{"text": "/*******************************************************************************\n * This domain is a simplified version of the paper: \n * \n * \"A Partial-Order Approach to Array Content Analysis\" by \n *  Gange, Navas, Schachte, Sondergaard, and Stuckey\n *  available here http://arxiv.org/pdf/1408.1754v1.pdf.\n *\n * It reasons about array contents and the idea is to compute all the\n * feasible partial orderings between array indexes. It keeps a single\n * graph where vertices are the array indexes (potentially all scalar\n * variables) and edges are labelled with weights (that includes\n * scalar and array variables).  An edge (i,j) with weight w denotes\n * that the property w holds for the all elements in the array between\n * [i,j).\n ******************************************************************************/\n\n/* Limitations:\n\n  - The implementation is just a proof-of-concept so it is horribly\n    inefficient. I have not tried to make it more efficient yet or\n    ran even with real programs.\n  - Assume all array accesses are aligned wrt to the size of the array\n    element (e.g., if the size of the array element is 4 bytes then\n    all array accesses must be multiple of 4).\n  - Assume that the size of the array element is always\n    1. Therefore, if the array indexes are incremented or decremented\n    by 2,4,... we will lose all the precision.\n\n  FIXMEs:\n\n  - Use AdaptGraph instead of boost::graph\n  - Have a flag is_normalized and normalize only if the flag is false\n  - Perform incremental Floyd-Warshall by keeping track of changed edges.\n  - array_graph::widening is normalizing both operands. The first\n    operand cannot be normalized.\n  - perform common renaming before binary operations (join/widening/narrowing/meet)\n  - Do no use shared_ptr because we are doing deep copies Use magic\n    move semantics and also shared references with copy-on-write to\n    avoid unnecessary copies.\n  - etc.\n\n */\n\n#ifndef ARRAY_GRAPH_HPP\n#define ARRAY_GRAPH_HPP\n\n#include <boost/optional.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/graph/graph_traits.hpp> \n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include <crab/common/types.hpp>\n#include <crab/common/debug.hpp>\n#include <crab/common/stats.hpp>\n#include <crab/domains/patricia_trees.hpp>\n#include <crab/domains/operators_api.hpp>\n#include <crab/domains/domain_traits.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace ikos;\n\nnamespace crab {\n\n  namespace domains {\n\n     /*\n       A weighted array graph is a graph (V,E,L) where V is the set of\n       vertices, E the edges and L is a label function: E -> W such that:\n       - If there is an edge e from vertex i to j whose weight is not\n       bottom (i.e., L(e) != bot) then it means that i < j.\n       - It is possible one non-bottom edge from i to j and another\n       non-bottom one from j to i. This means that both i < j and j < i\n       are possible.\n       - If the both edges from i to j and from j to i are bottom then it\n       must be that (i>=j) && (j>=i) = (i==j)\n     */\n     template< typename VertexName, typename Weight, \n               typename ScalarNumDomain, bool IsDistWeight >\n     class array_graph: public writeable{\n       \n       typedef VertexName VertexNameKey;\n       \n       template < typename Any1, typename Any2, bool Any5> \n       friend class array_graph_domain;\n       \n       typedef index_t key_t;\n       typedef boost::shared_ptr<VertexName> VertexNamePtr;\n       typedef boost::shared_ptr<Weight>     WeightPtr;\n       struct  graph_vertex_t { VertexNamePtr name; };\n       struct  graph_edge_t   { WeightPtr weight; }; \n       \n      public:\n       typedef array_graph<VertexName,Weight,ScalarNumDomain,IsDistWeight> array_graph_t;\n       typedef boost::tuple<VertexName, VertexName, Weight> edge_t;\n       \n      private:\n       typedef adjacency_list<listS,listS,bidirectionalS,graph_vertex_t,graph_edge_t> graph_t;\n       \n       typedef typename graph_traits<graph_t>::edge_iterator     edge_iterator;\n       typedef typename graph_traits<graph_t>::vertex_iterator   vertex_iterator;\n       typedef typename graph_traits<graph_t>::edge_descriptor   edge_descriptor_t;\n       typedef typename graph_traits<graph_t>::vertex_descriptor vertex_descriptor_t;\n       typedef typename graph_traits<graph_t>::out_edge_iterator out_edge_iterator;  \n       typedef typename graph_traits<graph_t>::in_edge_iterator  in_edge_iterator;  \n       \n       typedef typename ScalarNumDomain::linear_constraint_t     linear_constraint_t;\n       typedef typename ScalarNumDomain::variable_t              variable_t;\n       \n       typedef boost::unordered_map<key_t, vertex_descriptor_t >  vertex_map_t;\n       \n       typedef std::set<VertexName> vertex_names_set_t;\n       \n       typedef boost::shared_ptr <graph_t> graph_ptr;\n       typedef boost::shared_ptr< vertex_map_t > vertex_map_ptr;\n       typedef boost::shared_ptr< vertex_names_set_t > vertex_names_set_ptr;\n       \n       bool _is_bottom;\n       graph_ptr  _graph; \n       vertex_map_ptr _vertex_map;   //! map a VertexName to a graph vertex\n       vertex_names_set_ptr _vertices_set;\n       \n       bool find_vertex_map (VertexName v) {\n         return (_vertex_map->find(v.index()) != _vertex_map->end()); \n       }\n       \n       void insert_vertex_map (VertexName key, vertex_descriptor_t value)\n       {\n         if (find_vertex_map(key))\n           CRAB_ERROR (key,\" already in the vertex map\");\n         \n         _vertex_map->insert (make_pair(key.index(), value));\n         _vertices_set->insert (key);\n       }\n       \n       void remove_vertex_map (VertexName key)\n       {\n         _vertex_map->erase (key.index());\n         _vertices_set->erase (key);\n       }\n    \n       vertex_descriptor_t lookup_vertex_map (VertexName key) const\n       {\n         auto it = _vertex_map->find(key.index());\n         if (it != _vertex_map->end())\n           return it->second;\n      \n         CRAB_ERROR (\"No vertex with name \",key,\" found in the graph\");\n       }\n    \n       // All methods that add new vertices should call this one.\n       void add (vector<VertexName> vertices, vector<edge_t> edges) \n       {\n         for(auto v: vertices)\n         {\n           vertex_descriptor_t u = add_vertex(*_graph);\n           (*_graph)[u].name = VertexNamePtr (new VertexName(v));\n           insert_vertex_map(v, u);\n         }\n      \n         for(auto e: edges)\n         {\n           vertex_descriptor_t u =  lookup_vertex_map(e.template get<0>());\n           vertex_descriptor_t v =  lookup_vertex_map(e.template get<1>());\n           edge_descriptor_t k; bool b;\n           boost::tie(k,b) = add_edge(u, v, *_graph);\n           if (!b)\n             CRAB_ERROR (\"edge is already in the graph\");\n        \n           (*_graph)[k].weight = WeightPtr(new Weight(e.template get<2>()));\n         }\n      \n         canonical();\n       }\n    \n       // All methods that remove vertices should call this one.\n       void remove (VertexName v)\n       {\n         if (!find_vertex_map (v)) return ;\n      \n         canonical(); \n         vertex_descriptor_t u = lookup_vertex_map(v);\n      \n         // remove all in and out edges to/from u\n         clear_vertex(u, *_graph);\n      \n         // remove the vertex\n         remove_vertex(u, *_graph);\n         remove_vertex_map(v);\n       }\n    \n       ///////////////////////////////////////////////////////////////////////\n       // For our canonical form, we would like to compute the greatest\n       // fixed point to the set of inequalities:\n       //    \\forall i,j,k. G[i,j] \\subseteq G[i,k] \\cup G[k,j]\n       // If the weight domain is distributive we can solve this set of\n       // inequations by solving:\n       //    \\forall i,j,k. G[i,j] = G[i,j] \\cap G[i,k] \\cup G[k,j]\n       // The Floyd-Warshall algorithm does exactly that.\n       // Otherwise, we iterate the Floyd-Warshall algorithm until no change.\n       ///////////////////////////////////////////////////////////////////////\n       bool oneStep()\n       {\n         binary_join_op join;\n         binary_meet_op meet;\n         vertex_iterator ki, ke, ii, ie, ji, je;\n         bool change = false;\n         for (tie(ki, ke) = vertices(*_graph); ki != ke; ++ki)\n         {\n           for (tie(ii, ie) = vertices(*_graph); ii != ie; ++ii)\n           {\n             if (edge(*ii, *ki, *_graph).second)\n             {\n               for (tie(ji, je) = vertices(*_graph); ji != je; ++ji)\n               {\n                 if (edge(*ii, *ji, (*_graph)).second && \n                     edge(*ki, *ji, (*_graph)).second) \n                 {\n                   auto e_ij = edge(*ii, *ji, (*_graph)).first;\n                   auto e_ik = edge(*ii, *ki, (*_graph)).first;\n                   auto e_kj = edge(*ki, *ji, (*_graph)).first;\n                   auto Old = (*_graph)[e_ij].weight;\n                   auto New = meet((*_graph)[e_ij].weight,\n                                   (join((*_graph)[e_ik].weight,\n                                         (*_graph)[e_kj].weight)));\n                   change |= (!(*Old <= *New && *New <= *Old));\n                   (*_graph)[e_ij].weight = New;\n                 }\n               }\n             }\n           }\n         }\n         return change;\n       }\n    \n       void canonical()\n       {\n         if (IsDistWeight)\n           oneStep ();\n         else\n         {\n           bool change = true;\n           while (change)\n             change = oneStep ();\n         }\n       }\n    \n       void insert_vertex (VertexName u, Weight val = Weight::top())\n       {\n         if (!is_bottom () && !find_vertex_map(u))\n         {\n           vector<VertexName> new_vertices;\n           new_vertices.push_back(u);\n           vector<edge_t> new_edges;\n           vertex_iterator i, e;\n           for (tie(i, e) = vertices(*_graph); i != e; ++i)\n           {\n             VertexNamePtr v = (*_graph)[*i].name;\n             // add two edges in both directions\n             new_edges.push_back(edge_t(u, *v, val));\n             new_edges.push_back(edge_t(*v, u, val));\n           }\n           add(new_vertices, new_edges);\n         }\n       }\n    \n       template<typename Iterator>\n       void insert_vertices(array_graph_t &g, Iterator begin, Iterator end)\n       {\n         for(;begin!=end;++begin)\n           g.insert_vertex(begin->name());\n       }  \n    \n       // pre: caller must ensure the graph is in canonical form\n       void set_incoming (const VertexName &v, const Weight &weight)\n       {\n         if (!is_bottom ())\n         {      \n           vertex_descriptor_t u = lookup_vertex_map(v);\n           in_edge_iterator in_it, in_et;\n           for (tie(in_it, in_et) = in_edges(u, *_graph); in_it != in_et; ++in_it)\n             (*_graph)[*in_it].weight = WeightPtr( new Weight(weight));\n         }\n       }\n    \n       // pre: caller must ensure the graph is in canonical form\n       void set_outgoing (const VertexName &v, const Weight &weight)\n       {\n         if (!is_bottom ())\n         {\n           vertex_descriptor_t u = lookup_vertex_map(v);\n           out_edge_iterator out_it, out_et;\n           for (tie(out_it, out_et) = out_edges(u, *_graph); \n                out_it != out_et; ++out_it)\n             (*_graph)[*out_it].weight = WeightPtr( new Weight(weight));\n         }\n       }\n    \n       struct binary_join_op{\n         WeightPtr operator()(WeightPtr w1, WeightPtr w2) {\n           return WeightPtr(new Weight(*w1 | *w2));\n         }\n       };\n    \n       struct binary_meet_op{\n         WeightPtr operator()(WeightPtr w1, WeightPtr w2) {\n           return WeightPtr(new Weight(*w1 & *w2));\n         }\n       };\n    \n       struct binary_widening_op{\n         WeightPtr operator()(WeightPtr w1, WeightPtr w2) {\n           return WeightPtr(new Weight(*w1 || *w2));\n         }\n       };\n    \n       struct binary_narrowing_op{\n         WeightPtr operator()(WeightPtr w1, WeightPtr w2) {\n           return WeightPtr(new Weight(*w1 && *w2));\n         }\n       };\n    \n    \n       template<typename Op>\n       void pointwise_binop_helper (array_graph_t &g1, \n                                    const array_graph_t &g2)\n       {\n         // pre: g1 and g2 have the same adjacency structure\n         edge_iterator it_1, et_1;\n         for(tie(it_1,et_1) = edges(*g1._graph); it_1 != et_1; ++it_1)\n         {\n           edge_descriptor_t e_1   = *it_1;\n           vertex_descriptor_t u_1 = source(e_1, *g1._graph);\n           vertex_descriptor_t v_1 = target(e_1, *g1._graph);\n           VertexNamePtr u_name_1  = (*g1._graph)[u_1].name;\n           VertexNamePtr v_name_1  = (*g1._graph)[v_1].name;\n           WeightPtr     weight_1  = (*g1._graph)[e_1].weight;\n           vertex_descriptor_t u_2 = g2.lookup_vertex_map(*u_name_1);\n           vertex_descriptor_t v_2 = g2.lookup_vertex_map(*v_name_1);\n           if (edge(u_2, v_2, *g2._graph).second)\n           {\n             Op op;\n             edge_descriptor_t e_2 = edge(u_2, v_2, *g2._graph).first;\n             (*g1._graph)[e_1].weight = \n                 op((*g1._graph)[e_1].weight, (*g2._graph)[e_2].weight);\n           }\n           else\n             CRAB_ERROR(\"unreachable\");\n         } \n       }\n    \n       template<typename Op>\n       array_graph_t pointwise_binop (array_graph_t g1, \n                                      array_graph_t g2)\n       {\n         g1.canonical();\n         g2.canonical();\n      \n         // if (*(g1._vertices_set) != *(g2._vertices_set)){\n         //   set<VertexName> all_vs;\n         //   set_union(g1._vertices_set->begin(), g1._vertices_set->end(), \n         //             g2._vertices_set->begin(), g2._vertices_set->end(), inserter(all_vs, all_vs.end()));\n         //   vector<VertexName> new_g1, new_g2;\n         //   set_difference(all_vs.begin(), all_vs.end(),\n         //                  g1._vertices_set->begin(), g1._vertices_set->end(), inserter(new_g1, new_g1.end()));\n         //   set_difference(all_vs.begin(), all_vs.end(),\n         //                  g2._vertices_set->begin(), g2._vertices_set->end(), inserter(new_g2, new_g2.end()));\n         //   insert_vertices<typename vector<VertexName>::iterator>(g1, new_g1.begin(), new_g1.end());\n         //   insert_vertices<typename vector<VertexName>::iterator>(g2, new_g2.begin(), new_g2.end());\n         // }\n      \n         // pre: g1 and g2 have the same set of vertices and edges at this\n         // point\n         pointwise_binop_helper<Op>(g1,g2);\n         return g1;\n       }\n    \n       array_graph(bool is_bot): \n           _is_bottom(is_bot), \n           _graph(new graph_t(0)), \n           _vertex_map(new vertex_map_t()), \n           _vertices_set(new vertex_names_set_t()) \n       {  }\n    \n      public:\n    \n       static array_graph_t bottom()  { return array_graph(true); }\n    \n       static array_graph_t top() { return array_graph(false); }\n    \n       // Deep copy of the array graph\n       array_graph(const array_graph_t &other): \n           writeable(), \n           _is_bottom(other._is_bottom), \n           //_graph(new graph_t(*other._graph)),\n           //_vertex_map(new vertex_map_t(*other._vertex_map)),\n           //_vertices_set( new vertex_names_set_t(*other._vertices_set))\n           _graph (new graph_t(0)),\n           _vertex_map (new vertex_map_t()), \n           _vertices_set (new vertex_names_set_t())\n       {\n         crab::CrabStats::count (\"Domain.count.copy\");\n         crab::ScopedCrabStats __st__(\"Domain.copy\");\n\n         if (!is_bottom ())\n         {\n           // copy vertices, _vertex_map and _vertices_set\n           vertex_iterator i, e;\n           for (tie(i, e) = vertices(*other._graph); i != e; ++i)\n           {\n             vertex_descriptor_t u  = add_vertex(*_graph);\n             VertexName u_name = *((*other._graph)[*i].name);\n             (*_graph)[u].name = VertexNamePtr(new VertexName(u_name));\n             insert_vertex_map(u_name, u);\n           }\n        \n           // copy edges\n           edge_iterator ie, ee;\n           for(tie(ie,ee) = edges(*other._graph); ie != ee; ++ie)\n           {\n             VertexName u = *((*other._graph)[source(*ie, *other._graph)].name);\n             VertexName v = *((*other._graph)[target(*ie, *other._graph)].name);\n             Weight     w = *((*other._graph)[*ie].weight);\n             vertex_descriptor_t _u = lookup_vertex_map(u);\n             vertex_descriptor_t _v = lookup_vertex_map(v);\n             edge_descriptor_t _e; bool b;\n             boost::tie(_e,b) = add_edge(_u, _v, *_graph);\n             (*_graph)[_e].weight = WeightPtr(new Weight(w));      \n           }\n         }\n       }\n    \n       array_graph_t& operator=(const array_graph_t &other)\n       {\n         crab::CrabStats::count (\"Domain.count.copy\");\n         crab::ScopedCrabStats __st__(\"Domain.copy\");\n         if (this != &other)\n         {\n           _is_bottom      = other._is_bottom;\n           _graph          = other._graph;\n           _vertex_map     = other._vertex_map;\n           _vertices_set   = other._vertices_set;\n         }\n         return *this;\n       }\n    \n       bool is_bottom() { return this->_is_bottom; }\n    \n       bool is_top() \n       {\n         if (this->is_bottom())\n           return false;\n         else\n         {\n           // FIXME: speedup this operation\n           canonical();\n           edge_iterator it, et;\n           for(tie(it,et) = edges(*_graph); it != et; ++it)\n           {\n             edge_descriptor_t e = *it;\n             if (!(*(*_graph)[e].weight).is_top ()) \n               return false;\n           }\n           return true;\n         }\n       }\n    \n       void reduce(ScalarNumDomain scalar)\n       {\n         if (is_bottom ()) return;\n      \n         canonical();\n      \n         edge_iterator it, et;\n         for(tie(it,et) = edges(*_graph); it != et; ++it)\n         {\n           edge_descriptor_t e   = *it;\n           VertexNamePtr u = (*_graph)[source(e, *_graph)].name;\n           VertexNamePtr v = (*_graph)[target(e, *_graph)].name;\n           ScalarNumDomain tmp(scalar);\n           linear_constraint_t cst ( variable_t(*u) <= variable_t(*v) - 1);\n           tmp += cst;\n           if (tmp.is_bottom())\n             (*_graph)[e].weight = WeightPtr(new Weight(Weight::bottom()));         \n         }\n      \n         canonical();\n       }\n    \n       // Point-wise application of <= in the weight domain\n       bool operator <=(array_graph_t other)\n       {\n         if (is_bottom())  \n           return true;\n         else if (other.is_bottom()) \n           return false;\n         else\n         {\n           canonical();\n           other.canonical();\n           edge_iterator it_1, et_1;\n           edge_iterator it_2, et_2;\n           for(tie(it_1,et_1) = edges(*_graph); it_1 != et_1; ++it_1)\n           {\n             edge_descriptor_t e_1 = *it_1;\n             vertex_descriptor_t u_1 = source(e_1, *_graph);\n             vertex_descriptor_t v_1 = target(e_1, *_graph);\n             VertexNamePtr u_name_1 = (*_graph)[u_1].name;\n             VertexNamePtr v_name_1 = (*_graph)[v_1].name;\n             WeightPtr     weight_1 = (*_graph)[e_1].weight;\n             vertex_descriptor_t u_2 = other.lookup_vertex_map(*u_name_1);\n             vertex_descriptor_t v_2 = other.lookup_vertex_map(*v_name_1);\n             if (edge(u_2,v_2, *other._graph).second)\n             {\n               edge_descriptor_t e_2 = edge(u_2,v_2, *other._graph).first;\n               WeightPtr weight_2 = (*other._graph)[e_2].weight;\n               if (!(*weight_1 <= *weight_2))\n                 return false;\n             }\n             else\n               CRAB_ERROR (\"operator<= with graphs with different adjacency structure\");\n           }\n           return true;\n         }\n       }\n    \n       bool operator==(array_graph_t other)\n       {\n         if (is_bottom()) return other.is_bottom();\n         else\n           return (*(_vertices_set) == *(other._vertices_set) && \n                   ( *this <= other && other <= *this));\n       }\n    \n       void operator-=(VertexName v) \n       {\n         if (!is_bottom ()) \n           remove (v);\n       }\n\n       void operator|=(array_graph_t other) {\n         *this = *this | other;\n       }\n    \n       // Point-wise join in the weight domain\n       array_graph_t operator|(array_graph_t other)\n       {\n         if (is_bottom())\n           return other;\n         else if (other.is_bottom())\n           return *this;\n         else \n           return pointwise_binop<binary_join_op>(*this, other);\n       }\n    \n       // Point-wise widening in the weight domain\n       array_graph_t operator||(array_graph_t other)\n       {\n         if (is_bottom())\n           return other;\n         else if (other.is_bottom())\n           return *this;\n         else \n           return pointwise_binop<binary_widening_op>(*this, other);\n       }\n    \n       // Point-wise meet in the weight domain\n       array_graph_t operator&(array_graph_t other)\n       {\n         if (this->is_bottom())\n           return *this;\n         else if (other.is_bottom())\n           return other;\n         else {\n           return pointwise_binop<binary_meet_op>(*this, other);\n         }\n       }\n    \n       // Point-wise narrowing in the weight domain\n       array_graph_t operator&&(array_graph_t other)\n       {\n         if (this->is_bottom())\n           return *this;\n         else if (other.is_bottom())\n           return other;\n         else {\n           return pointwise_binop<binary_narrowing_op>(*this, other);\n         }\n       }\n    \n       void meet_weight (const VertexName &src, const VertexName &dest, \n                         Weight weight)\n       {\n         if (find_vertex_map(src) && find_vertex_map(dest))\n         {\n           vertex_descriptor_t u = lookup_vertex_map(src);\n           vertex_descriptor_t v = lookup_vertex_map(dest);\n           if (edge(u,v,*_graph).second) {\n             edge_descriptor_t e = edge(u,v,*_graph).first;\n             Weight meet = weight & (*(*_graph)[e].weight);\n             (*_graph)[e].weight = WeightPtr(new Weight(meet));\n           }\n           else {\n             vector<VertexName> vertices;\n             vector<edge_t>     edges;\n             edges.push_back(edge_t(src,dest,weight));\n             add(vertices,edges);\n           }\n         }\n       }\n    \n       void set_weight (const VertexName &src, const VertexName &dest, \n                        Weight weight)\n       {\n         if (find_vertex_map(src) && find_vertex_map(dest))\n         {\n           vertex_descriptor_t u = lookup_vertex_map(src);\n           vertex_descriptor_t v = lookup_vertex_map(dest);\n           if (edge(u,v,*_graph).second) {\n             edge_descriptor_t e = edge(u,v,*_graph).first;\n             (*_graph)[e].weight = WeightPtr(new Weight(weight));\n           }\n           else {\n             vector<VertexName> vertices;\n             vector<edge_t>     edges;\n             edges.push_back(edge_t(src,dest,weight));\n             add(vertices,edges);\n           }\n         }\n       }\n    \n       Weight& get_weight (const VertexName &src, const VertexName &dest) \n       {\n         if (find_vertex_map(src) && find_vertex_map(dest))\n         {\n           vertex_descriptor_t u = lookup_vertex_map(src);\n           vertex_descriptor_t v = lookup_vertex_map(dest);\n           if (edge(u,v,*_graph).second)\n           {\n             edge_descriptor_t e = edge(u,v,*_graph).first;\n             return *((*_graph)[e].weight);\n           }\n         }\n         CRAB_ERROR (\"No edge found with given vertices\");\n       }\n    \n       void write(crab_os& o) \n       {\n         if (is_bottom())\n           o << \"_|_\";\n         else\n         {\n           {\n             vertex_iterator it, et;\n             o << \"(V={\";\n             for (tie(it, et) = vertices(*_graph); it != et; ++it){\n               vertex_descriptor_t u = *it;\n               VertexNamePtr u_name  = (*_graph)[u].name;          \n               o << *u_name << \" \";\n             }\n             o << \"},\";\n           }\n           {\n             edge_iterator it, et;\n             o << \"E={\";\n             for(tie(it,et) = edges(*_graph); it!= et; ++it)\n             {\n               edge_descriptor_t e   = *it;\n               vertex_descriptor_t u = source(e, *_graph);\n               vertex_descriptor_t v = target(e, *_graph);\n               VertexNamePtr u_name = (*_graph)[u].name;\n               VertexNamePtr v_name = (*_graph)[v].name;\n               WeightPtr     weight = (*_graph)[e].weight;\n               if (!weight->is_bottom())\n                 o << \"(\" << *u_name << \",\" << *v_name << \",\" << *weight << \") \";\n             }\n             o << \"})\";\n           }\n         }\n       }\n     }; // end class array_graph\n\n \n    /*\n      Reduced product of a scalar numerical domain with a weighted array\n      graph.\n    */\n    template<typename ScalarNumDomain, typename WeightDomain, bool IsDistWeight = false>\n    class array_graph_domain: \n        public writeable, \n        public numerical_domain<typename ScalarNumDomain::number_t,\n                                typename ScalarNumDomain::varname_t>,\n        public bitwise_operators<typename ScalarNumDomain::number_t, \n                                 typename ScalarNumDomain::varname_t>, \n        public division_operators<typename ScalarNumDomain::number_t,\n                                  typename ScalarNumDomain::varname_t>,\n        public array_operators<typename ScalarNumDomain::number_t,\n                               typename ScalarNumDomain::varname_t >,\n        public pointer_operators<typename ScalarNumDomain::number_t,\n                                 typename ScalarNumDomain::varname_t > {\n\n      template<typename Key, typename Value>\n      class merge_op_check_equal: public patricia_tree< Key, Value >::binary_op_t {\n        boost::optional< Value > apply(Value x, Value y) {\n          if (x == y) return x;\n          else\n            CRAB_ERROR(\"merging a key with two different values\");\n        };\n        bool default_is_absorbing() { return false; }\n      }; \n   \n      template<typename Key, typename Value>\n      class merge_op_first: public patricia_tree< Key, Value >::binary_op_t {\n        boost::optional< Value > apply(Value x, Value y)  {\n          return x;\n        };\n        bool default_is_absorbing() { return false; } \n      }; \n   \n      template<typename Key, typename Value>\n      class merge_op_second: public patricia_tree< Key, Value >::binary_op_t {  \n        boost::optional< Value > apply(Value x, Value y)  {\n          return y;\n        };\n        bool default_is_absorbing() { return false; }\n      }; \n   \n     template < typename Key, typename Value, \n                typename MergeOp = merge_op_check_equal <Key, Value> >\n     class mergeable_map: public writeable {\n       \n      private:\n       typedef patricia_tree< Key, Value > patricia_tree_t;\n       typedef typename patricia_tree_t::binary_op_t binary_op_t;\n  \n      public:\n       typedef mergeable_map< Key, Value > mergeable_map_t;\n       typedef typename patricia_tree_t::iterator iterator;\n       \n      private:\n       patricia_tree_t _tree;\n       \n       static patricia_tree_t do_union(patricia_tree_t t1, patricia_tree_t t2) {\n         MergeOp o;\n         t1.merge_with(t2, o);\n         return t1;\n       }\n       \n       mergeable_map(patricia_tree_t t): _tree(t) { }\n       \n      public:\n       \n       mergeable_map(): _tree(patricia_tree_t()) { }\n  \n       mergeable_map(const mergeable_map_t& e): writeable(), _tree(e._tree) { }\n       \n       mergeable_map_t& operator=(mergeable_map_t e) {\n         _tree = e._tree;\n         return *this;\n       }\n       \n       iterator begin() { return _tree.begin(); }\n\n       iterator end() { return _tree.end(); }\n\n       std::size_t size(){ return _tree.size(); }\n\n       void set(Key k, Value v) { _tree.insert(k, v); }\n\n       mergeable_map_t& operator-=(Key k) {\n         _tree.remove(k);\n         return *this;\n       }       \n       mergeable_map_t operator|(mergeable_map_t e) {\n         mergeable_map_t u(do_union(_tree, e._tree));\n         return u;\n       }\n              \n       boost::optional<Value> operator[](Key k) { return _tree.lookup(k); }\n       void clear() { _tree = patricia_tree_t(); }\n       \n       void write(crab_os& o) {\n         o << \"{\";\n         for (auto it = _tree.begin(); it != _tree.end(); ) {\n           Key k = it->first;\n           k.write(o);\n           o << \" -> \";\n           Value v = it->second;\n           o << v;\n           ++it;\n           if (it != _tree.end()) {\n             o << \"; \";\n           }\n         }\n         o << \"}\";\n       }    \n     }; // class mergeable_map\n      \n     public:\n      typedef typename ScalarNumDomain::number_t Number;\n      typedef typename ScalarNumDomain::varname_t VariableName;\n      \n      // WARNING: assumes ScalarNumDomain::number_t = WeightDomain::number_t and\n      //                  ScalarNumDomain::varname_t = WeightDomain::varname_t\n      using typename numerical_domain< Number, VariableName>::linear_expression_t;\n      using typename numerical_domain< Number, VariableName>::linear_constraint_t;\n      using typename numerical_domain< Number, VariableName>::linear_constraint_system_t;\n      using typename numerical_domain< Number, VariableName>::variable_t;\n      using typename numerical_domain< Number, VariableName>::number_t;\n      using typename numerical_domain< Number, VariableName>::varname_t;\n      typedef WeightDomain content_domain_t;      \n      typedef ScalarNumDomain index_domain_t;      \n\n     private:\n      typedef array_graph< VariableName,WeightDomain,ScalarNumDomain,IsDistWeight> array_graph_t;\n      typedef array_graph_domain<ScalarNumDomain,WeightDomain,IsDistWeight> array_graph_domain_t;\n      \n      typedef mergeable_map<VariableName,VariableName> succ_index_map_t;\n      typedef boost::shared_ptr< succ_index_map_t > succ_index_map_ptr;\n      \n      bool  _is_bottom;\n      ScalarNumDomain _scalar;        \n      array_graph_t _g;        \n      // for each array index i we keep track of a special index that\n      // represent i+1\n      succ_index_map_ptr _succ_idx_map;\n      \n      void abstract (VariableName v) \n      {\n        if (_g.find_vertex_map(v))\n        {\n          _g.set_incoming(v , WeightDomain::top());\n          _g.set_outgoing(v , WeightDomain::top());\n          optional<VariableName> succ_v = get_succ_idx(v);\n          if (succ_v)\n          {\n            _g.set_incoming(*succ_v, WeightDomain::top());\n            _g.set_outgoing(*succ_v, WeightDomain::top());\n          }\n        }\n      }\n      \n    \n      optional<VariableName> get_succ_idx (VariableName v) const\n      {\n        return (*_succ_idx_map)[v];\n      }\n\n      template <typename VariableFactory>\n      VariableName add_variable (Number n, VariableFactory &vfac)\n      {\n        // FIXME: really big assumption that the variable factory\n        // understands strings. For instance, this is not true if the\n        // factory is created by Crab-llvm.\n        VariableName var_n = vfac[\"#C\" + n.get_str()];\n\n        if (n >= 0)\n        {\n          _g.insert_vertex(var_n);\n          _scalar.assign(var_n, n);\n        }\n        return var_n;\n      }\n\n      void add_variable (VariableName v)\n      {\n        if (is_array_index(v))\n        {\n          /*assign to v_succ a fresh var must be always the same*/ \n          VariableName v_succ = v.get_var_factory().get (v.index()); \n\n          _g.insert_vertex (v);\n          _g.insert_vertex (v_succ);\n          _succ_idx_map->set (v, v_succ);\n      \n          /// FIXME: assume that the array element size is 1.\n\n          // --- Enforce: i+ == i+1\n          _scalar += linear_constraint_t( variable_t (v_succ) == variable_t(v) + 1);\n          // needed if scalar domain is non-relational:\n          _g.set_weight (v_succ,v,WeightDomain::bottom ());\n        }\n      }\n\n      void meet_weight (VariableName i, VariableName j, WeightDomain w)\n      {\n        add_variable (i);\n        add_variable (j);\n        _g.meet_weight (i,j,w);\n        reduce();\n      }\n\n      template <typename VariableFactory>\n      void meet_weight (Number i, Number j, WeightDomain w, VariableFactory &vfac)\n      {\n        _g.meet_weight (add_variable (i, vfac),\n                        add_variable (j, vfac) ,\n                        w);\n        reduce();\n      }\n\n      void meet_weight (Number i, VariableName j, WeightDomain w)\n      {\n        add_variable (j);\n        _g.meet_weight (add_variable(i, j.get_var_factory ()),j,w);\n        reduce();\n      }\n\n      void meet_weight (VariableName i, Number j, WeightDomain w)\n      {\n        add_variable(i);\n        _g.meet_weight(i,add_variable(j, i.get_var_factory ()),w);\n        reduce();\n      }\n\n      bool IsDefiniteOne (Number x)  { \n        return x == Number (1); \n      }\n\n      bool IsDefiniteOne (VariableName x)  { \n        auto n = _scalar [x].singleton ();\n        if (n) return *n == Number (1); \n        else return false;\n      }\n  \n      // x := x op k \n      // Most of the magic happens here.\n      template<typename VarNum>\n      void apply_helper (operation_t op, VariableName x, VarNum k) \n      {\n        if (is_bottom()) return;\n\n        /// step 1: add x_old in the graph\n        VariableName x_old = x.get_var_factory ().get (); /*fresh var*/ \n        VariableName x_old_succ = x.get_var_factory ().get (); /*fresh var*/\n        _g.insert_vertex(x_old);\n        _g.insert_vertex(x_old_succ);\n        _succ_idx_map->set(x_old, x_old_succ);\n\n        /// --- Enforce the following relationships:\n        ///     { x_old = x, x_old+ = x+, x_old+ = x_old + 1} \n\n        /// x_old = x\n        _scalar.assign(x_old, linear_expression_t(x)); \n        // needed if scalar domain is non-relational:\n        // enforcing x_old = x\n        _g.set_weight (x_old,x,WeightDomain::bottom ());\n        _g.set_weight (x,x_old,WeightDomain::bottom ());\n\n        /// x_old+ = x_old +1\n        _scalar += linear_constraint_t(variable_t(x_old_succ) == variable_t(x_old) + 1);      \n        // needed if scalar domain is non-relational:\n        // enforcing x_old+ < x_old is false\n        _g.set_weight (x_old_succ,x_old,WeightDomain::bottom ());\n        // enforcing x_old+ < x is false\n        _g.set_weight (x_old_succ,x,WeightDomain::bottom ());\n\n        /// x_old+ = x+\n        optional<VariableName> x_succ = get_succ_idx(x);\n        if (x_succ) {\n          _scalar += linear_constraint_t( variable_t(x_old_succ) == variable_t(*x_succ));      \n          // needed if scalar domain is non-relational:\n          // enforcing x_old + = x+\n          _g.set_weight (x_old_succ,*x_succ,WeightDomain::bottom ());\n          _g.set_weight (*x_succ,x_old_succ,WeightDomain::bottom ());\n          // enforcing x+ < x_old is false\n          _g.set_weight (*x_succ,x_old,WeightDomain::bottom ());\n        }\n        // propagate the scalar constraints to the graph\n        reduce();\n\n        /// step 2: abstract all incoming/outgoing edges of x\n        abstract(x);\n\n        /// step 3: update the graph with the scalar domain after applying\n        ///         x = x op k.\n        _scalar.apply(op, x, x, k); \n\n#if 1\n        // This is not needed at all if the scalar domain is relational.\n        // Otherwise, we would like to keep the relationship between\n        // x_old+ and x. We do it in a completely adhoc way but at least\n        // we cover common cases when the array is traversed forward or\n        // backwards one element by one.\n        if (op == OP_ADDITION && IsDefiniteOne (k)) {\n          _g.set_weight (x,x_old_succ,WeightDomain::bottom ());\n          _g.set_weight (x_old_succ,x,WeightDomain::bottom ());  \n        }\n        else if (op == OP_SUBTRACTION && IsDefiniteOne (k)) {\n          _g.set_weight (x_old,*x_succ,WeightDomain::bottom ());\n          _g.set_weight (*x_succ,x_old,WeightDomain::bottom ());  \n        }\n#endif \n\n        if (x_succ){\n          _scalar -= *x_succ;\n          /// --- Enforce x+ == x + 1 \n          _scalar += linear_constraint_t(variable_t(*x_succ) == variable_t(x) + 1); \n          // needed if scalar domain is non-relational:\n          _g.set_weight (*x_succ,x,WeightDomain::bottom ());\n        }\n\n        /* { x = x op k, x+ = x+1} */\n        reduce();\n\n        /// step 4: delete x_old\n        _g -= x_old;\n        _g -= x_old_succ;\n        (*_succ_idx_map) -= x_old;\n        _scalar -= x_old;\n        _scalar -= x_old_succ;\n\n        //this->reduce();\n      }\n\n      //! In case we can statically determine which variables should be\n      //  considered array indexes. Note that any subset is sound but it\n      //  might be imprecise. By default we consider all.\n      bool is_array_index(VariableName v) const {  \n        return true; \n      }\n\n      // model array reads: return the weight from the edge i to i+\n      WeightDomain array_read (VariableName i) \n      {\n        if (is_bottom()) \n          return WeightDomain::bottom();\n  \n        if (!is_array_index(i)) \n          return WeightDomain::top();\n    \n        //this->reduce();\n        optional<VariableName> i_succ = get_succ_idx(i);\n        if (i_succ) \n          return _g.get_weight(i, *i_succ);\n\n        CRAB_ERROR (\"There is no successor index associated with \",i);\n      }\n \n      // model array writes\n      void array_write (VariableName arr, VariableName i, WeightDomain w)\n      {\n        if (is_bottom()) return;\n        //this->reduce();\n\n        //--- strong update\n        optional<VariableName> i_succ = get_succ_idx(i);\n        if (!i_succ) \n          CRAB_ERROR (\"There is no successor index associated with \",i);\n\n        WeightDomain& old_w = _g.get_weight(i, *i_succ);\n        old_w -= arr;\n        _g.meet_weight(i, *i_succ, w);\n        WeightDomain new_w = _g.get_weight(i, *i_succ);\n    \n        //--- weak update: \n        // An edge (p,q) must be weakened if p <= i <= q and p < q\n        typename array_graph_t::edge_iterator it, et;\n        for(tie(it,et) = edges(*_g._graph); it!= et; ++it)\n        {\n          typename array_graph_t::edge_descriptor_t e = *it;\n          typename array_graph_t::VertexNamePtr  p = (*_g._graph)[source(e, *_g._graph)].name;\n          typename array_graph_t::VertexNamePtr  q = (*_g._graph)[target(e, *_g._graph)].name;\n          typename array_graph_t::WeightPtr weight = (*_g._graph)[e].weight;\n          if ( ((*p == i) &&  (*q == *i_succ)) || weight->is_bottom())\n            continue;\n          // p < q \n          ScalarNumDomain tmp(_scalar);\n          tmp += linear_constraint_t( variable_t(*p) <= variable_t(i));      \n          tmp += linear_constraint_t( variable_t(*i_succ)  <= variable_t(*q));     \n          if (tmp.is_bottom())\n            continue;\n          // p <= i <= q and p < q\n          typename array_graph_t::binary_join_op join;\n          (*_g._graph)[e].weight = join (weight, \n                                         typename array_graph_t::WeightPtr (new WeightDomain(new_w)));\n        }\n        _g.canonical();\n\n      }\n  \n      void set_to_bottom()\n      {\n        _is_bottom = true;\n        _scalar = ScalarNumDomain::bottom();\n        _g = array_graph_t::bottom();\n        _succ_idx_map->clear();\n      }\n\n      array_graph_domain(ScalarNumDomain scalar, \n                         array_graph_t g, \n                         succ_index_map_ptr map): \n          writeable(), \n          _is_bottom(false), \n          _scalar(scalar), \n          _g(g), \n          _succ_idx_map(new succ_index_map_t(*map)) \n      { \n        if (_scalar.is_bottom() || _g.is_bottom())\n          set_to_bottom();\n        else\n          reduce();\n      }\n\n     public:\n\n      array_graph_domain(): \n          writeable(), \n          _is_bottom(false), \n          _scalar(ScalarNumDomain::top()), \n          _g(array_graph_t::top()), \n          _succ_idx_map(new succ_index_map_t()) \n      { }\n\n      static array_graph_domain_t top() \n      {\n        return array_graph_domain(ScalarNumDomain::top(), \n                                  array_graph_t::top(), \n                                  succ_index_map_ptr(new succ_index_map_t()));\n      }\n  \n      static array_graph_domain_t bottom() \n      {\n        return array_graph_domain(ScalarNumDomain::bottom(), \n                                  array_graph_t::bottom(),\n                                  succ_index_map_ptr(new succ_index_map_t()));\n      }\n      \n      array_graph_domain(const array_graph_domain_t& other): \n          writeable(), \n          _is_bottom(other._is_bottom),\n          _scalar(other._scalar) , \n          _g(other._g), \n          _succ_idx_map(new succ_index_map_t(*other._succ_idx_map))\n      {\n        crab::CrabStats::count (getDomainName() + \".count.copy\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n      }\n  \n      array_graph_domain_t& operator=(array_graph_domain_t other) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.copy\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".copy\");\n\n        if (this != &other)\n        {\n          this->_is_bottom = other._is_bottom;\n          this->_scalar = other._scalar;\n          this->_g = other._g;\n          this->_succ_idx_map = other._succ_idx_map;\n        }\n        return *this;\n      }\n  \n      bool is_bottom() { return _is_bottom; }\n\n      // --- top operation in the graph is expensive because we need to\n      //     traverse the whole graph and check each edge.\n      // bool is_top() { return (_scalar.is_top() && _g.is_top()); }\n    \n      bool is_top() { return (_scalar.is_top()); }\n  \n      void reduce ()\n      {\n        crab::CrabStats::count (getDomainName() + \".count.reduce\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".reduce\");\n\n        if (is_bottom ()) return; \n      \n        domain_traits<ScalarNumDomain>::normalize(_scalar);\n\n        if (_scalar.is_bottom() || _g.is_bottom())\n          set_to_bottom();\n        else\n          _g.reduce(_scalar);\n      }\n\n      bool operator<=(array_graph_domain_t other) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.leq\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".leq\");\n\n        if (is_bottom ()) {\n          return true;\n        } else if (other.is_bottom ()) {\n          return false;\n        } else {\n          return (_scalar <= other._scalar && _g <= other._g);\n        }\n      }\n\n      void operator|=(array_graph_domain_t other)  {\n        *this = *this | other;\n      }\n  \n      array_graph_domain_t operator|(array_graph_domain_t other) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.join\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".join\");\n\n        if (is_bottom ()) {\n          return other;\n        } else if (other.is_bottom ()) {\n          return *this;\n        } else {\n          succ_index_map_ptr map(new succ_index_map_t(*(_succ_idx_map) | \n                                                      *(other._succ_idx_map)));\n          return array_graph_domain_t(_scalar | other._scalar, \n                                      _g | other._g, map); \n        }\n      }\n  \n      array_graph_domain_t operator&(array_graph_domain_t other) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.meet\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".meet\");\n\n        if (is_bottom () || other.is_bottom ()) {\n          return bottom();\n        } else {\n          succ_index_map_ptr map(new succ_index_map_t(*(_succ_idx_map) | \n                                                      *(other._succ_idx_map)));\n          return array_graph_domain_t(_scalar & other._scalar, \n                                      _g & other._g, map);\n        }\n      }\n  \n      array_graph_domain_t operator||(array_graph_domain_t other) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.widening\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".widening\");\n\n        if (is_bottom ())  return other;\n        else if (other.is_bottom ())  return *this;\n        else \n        {\n          succ_index_map_ptr map (new succ_index_map_t(*(_succ_idx_map) | \n                                                       *(other._succ_idx_map)));\n          array_graph_domain_t widen (_scalar || other._scalar, \n                                      _g || other._g, map);\n          CRAB_LOG(\"array-graph\" , crab::outs() << \"Widening: \" << *this<<\"\\n\";);\n          return widen;\n        }\n      }\n\n      template<typename Thresholds>\n      array_graph_domain_t widening_thresholds (array_graph_domain_t other, \n                                                const Thresholds & /*ts*/) {\n        return (*this || other);\n      }\n        \n      array_graph_domain_t operator&& (array_graph_domain_t other) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.narrowing\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".narrowing\");\n\n        if (is_bottom ()|| other.is_bottom ()) \n          return bottom();\n        else \n        {\n          succ_index_map_ptr map (new succ_index_map_t(*(_succ_idx_map) | \n                                                       *(other._succ_idx_map)));\n          return array_graph_domain_t (_scalar && other._scalar, \n                                       _g && other._g, map);\n        }\n      }\n  \n      void operator-=(VariableName var)\n      {\n        crab::CrabStats::count (getDomainName() + \".count.forget\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".forget\");\n\n        if (is_bottom ()) return;\n\n        // scalar domain\n        _scalar -= var;\n        _g -= var;\n        optional<VariableName> var_succ = get_succ_idx(var);\n        if (var_succ) {\n          _scalar -= *var_succ;\n          _g -= *var_succ;        \n          (*_succ_idx_map) -= var;\n        }\n\n        // graph domain\n        typename array_graph_t::edge_iterator it, et;\n        for(tie(it,et) = edges(*(_g._graph)); it!= et; ++it) {\n          auto e  = *it;\n          auto weight = (*(_g._graph))[e].weight;\n          (*weight) -= var;\n        }      \n        // this->reduce();\n      }\n  \n      /////\n      // Transfer functions\n      /////\n\n      void operator += (linear_constraint_system_t csts) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.add_constraints\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".add_constraints\");\n\n        if (is_bottom()) return;\n    \n        // graph domain: make sure that all the relevant variables\n        // (included special \"0\") are inserted in the graph\n        for (auto cst : csts) {\n          // TODO\n          //Number n = cst.expression().constant();\n          //if (n == 0) add_variable(n, vfac);\n          for (auto v : cst.variables())\n            add_variable (v.name());\n        }\n\n        _scalar += csts;\n        reduce();\n\n        CRAB_LOG(\"array-graph\", \n                 crab::outs() << \"Assume(\"<< csts<< \") --- \"<< *this<<\"\\n\";);\n      }\n\n      void assign (VariableName x, linear_expression_t e) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.assign\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".assign\");\n\n        if (is_bottom()) return;\n\n        if (optional<variable_t> y = e.get_variable())\n        {\n          if ((*y).name() == x) return;\n        }\n\n        // scalar domain\n        _scalar.assign(x, e);\n   \n        // graph domain\n        if (e.is_constant() && (e.constant() == 0))\n          add_variable (e.constant(), x.get_var_factory ());\n\n        if (_g.find_vertex_map(x))\n        {\n          abstract(x);\n          // wrong results if we do not restore the relationship between x\n          // and x+ in the scalar domain\n          optional<VariableName> x_succ = get_succ_idx(x);      \n          if (x_succ){\n            _scalar -= *x_succ;\n            /// --- Enforce x+ == x+1\n            _scalar += linear_constraint_t( variable_t(*x_succ) == variable_t(x) + 1);        \n            // needed if scalar domain is non-relational:\n            _g.set_weight (*x_succ,x,WeightDomain::bottom ());\n          }\n        }\n        else\n          add_variable(x);\n    \n        reduce();\n\n        CRAB_LOG(\"array-graph\", \n                 crab::outs() << \"Assign \"<<x<<\" := \"<<e<<\" ==> \"<<*this<<\"\\n\";);\n      }\n\n      void apply (operation_t op, VariableName x, VariableName y, Number z) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        assign (x, linear_expression_t(y));\n        apply_helper<Number> (op, x, z);\n\n        CRAB_LOG(\"array-graph\",\n                 crab::outs() << \"Apply \"<<x<<\" := \"<<y<<\" \"<<op<<\" \"<<z<<\" ==> \"<<*this<<\"\\n\";); \n      }\n\n      void apply(operation_t op, VariableName x, VariableName y, VariableName z) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        assign (x, linear_expression_t(y));\n        apply_helper<VariableName> (op, x, z);\n\n        CRAB_LOG(\"array-graph\", \n                 crab::outs() << \"Apply \"<<x<<\" := \"<<y<<\" \"<<op<<\" \"<<z<<\" ==> \"<<*this<<\"\\n\";);\n      }\n\n      void apply(operation_t op, VariableName x, Number k) \n      {\n        crab::CrabStats::count (getDomainName() + \".count.apply\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".apply\");\n\n        apply_helper<Number> (op, x, k);\n\n        CRAB_LOG(\"array-graph\",\n                 crab::outs() << \"Apply \"<<x<<\" := \"<<x<<\" \"<<op<<\" \"<<k<<\" ==> \"<<*this<<\"\\n\";);\n      }\n\n\n      // bitwise_operators_api\n      void apply(conv_operation_t op, VariableName x, VariableName y, unsigned width) {\n        assign (x, variable_t (y));\n      }\n      \n      void apply(conv_operation_t op, VariableName x, Number k, unsigned width) {\n        assign (x, k);\n      }\n      \n      void apply(bitwise_operation_t op, VariableName x, VariableName y, VariableName z) {\n        CRAB_WARN (\"bitwise operations not implemented in array_graph\");\n      }\n      \n      void apply(bitwise_operation_t op, VariableName x, VariableName y, Number k) {\n        CRAB_WARN (\"bitwise operations not implemented in array_graph\");\n      }\n      \n      // division_operators_api\n      void apply(div_operation_t op, VariableName x, VariableName y, VariableName z) {\n        CRAB_WARN (\"division operations not implemented in array_graph\");\n      }\n      \n      void apply(div_operation_t op, VariableName x, VariableName y, Number k) {\n        CRAB_WARN (\"division operations not implemented in array_graph\");\n      }\n\n      // array_operators_api\n        \n      virtual void array_init (VariableName a, const vector<ikos::z_number> &values)  override {\n        CRAB_WARN (\"array_graph_domain init not implemented\");\n      }\n\n      virtual void array_assume (VariableName a, \n                                 boost::optional<Number> lb, boost::optional<Number> ub) override {\n        CRAB_WARN (\"array_graph_domain assume not implemented\");\n      }\n\n      virtual void array_load (VariableName lhs, VariableName arr, VariableName idx, \n                               z_number /*bytes*/) override {\n        crab::CrabStats::count (getDomainName() + \".count.load\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".load\");\n\n        WeightDomain w = array_read (idx);\n        // --- Simplification wrt Gange et.al.:\n        //     Only non-relational invariants are passed from the graph\n        //     domain to the scalar domain.\n        //     We use operator[] as the conversion function\n        _scalar.set (lhs, w [arr]);\n\n        CRAB_LOG(\"array-graph\",\n                 crab::outs() << \"Array read \"<<lhs<<\" := \"<< arr<<\"[\"<<idx<<\"] ==> \"\n                           << *this <<\"\\n\";);    \n      }\n\n      virtual void array_store (VariableName arr, VariableName idx, linear_expression_t val,\n                                 z_number /*n_bytes*/, bool /*is_singleton*/) override {\n\n        crab::CrabStats::count (getDomainName() + \".count.store\");\n        crab::ScopedCrabStats __st__(getDomainName() + \".store\");\n\n        // --- Simplification wrt Gange et.al.:\n        //     Only non-relational invariants are passed from the scalar\n        //     domain to the graph domain.\n        //     We use operator[] as the conversion function\n        WeightDomain w = WeightDomain::top ();\n        if (val.is_constant ())\n          w.assign (arr, val);      \n        else if (auto v = val.get_variable ()){\n          w.set (arr, _scalar[(*v).name()]);      \n        }\n        else {\n          // If you see this warning you can switch to intervals.\n          crab::outs() << \"Warning: scalar domain does not support assignments with arbitrary rhs.\\n\";\n        }\n        array_write (arr, idx, w);\n\n        CRAB_LOG(\"array-graph\",\n                 crab::outs() << \"Array write \"<<arr<<\"[\"<<idx<<\"] := \"<<val<< \" ==> \"<< *this <<\"\\n\";);\n      }\n    \n      void write(crab_os& o) \n      {\n        o << \"(\" ;\n#if 1\n        // less verbose: remove the special variables i+ from the scalar\n        // domain\n        ScalarNumDomain inv (_scalar);\n        for(auto p : *_succ_idx_map) {\n          inv -= p.second;\n        }\n        o << inv;\n#else\n        o << _scalar;\n#endif \n        o << \",\" << _g;\n        o << \")\";\n      }\n\n      linear_constraint_system_t to_linear_constraint_system (){\n        CRAB_ERROR (\"array_graph: to_linear_constraint_system not implemented\");\n      }\n\n      static string getDomainName () {\n        string name (\"ArrayGraph(\" + \n                     ScalarNumDomain::getDomainName () +  \",\" + \n                     WeightDomain::getDomainName () +\n                     \")\");\n        return name;\n      }\n\n    }; // end array_graph_domain\n\n\n    }// namespace domain_traits\n\n} // namespace crab\n\n#endif \n", "meta": {"hexsha": "99534ac8b58de09eabef097fcf605840a3ee4f06", "size": 53747, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/array_graph.hpp", "max_stars_repo_name": "satbekmyrza/crab", "max_stars_repo_head_hexsha": "0f71d09f4fa872d6b02f225963c1a960977578f4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crab/domains/array_graph.hpp", "max_issues_repo_name": "satbekmyrza/crab", "max_issues_repo_head_hexsha": "0f71d09f4fa872d6b02f225963c1a960977578f4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crab/domains/array_graph.hpp", "max_forks_repo_name": "satbekmyrza/crab", "max_forks_repo_head_hexsha": "0f71d09f4fa872d6b02f225963c1a960977578f4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3134034166, "max_line_length": 113, "alphanum_fraction": 0.5448490148, "num_tokens": 12650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.76908023177796, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.44998973128817293}}
{"text": "#include <itkImage.h>\n#include <itkImageFileReader.h>\n#include <itkImageFileWriter.h>\n#include <itkImageRegionIteratorWithIndex.h>\n#include <itkImageLinearIteratorWithIndex.h>\n#include <itkImageRegionIterator.h>\n#include <itkDiffusionTensor3D.h>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n#include <boost/math/special_functions/ellint_rf.hpp>\n#include <boost/math/special_functions/ellint_rd.hpp>\n\n#include \"tkdCmdParser.h\"\n\n#include <algorithm> // for sort\n#include <cmath> // for pow and sqrt\n#include <valarray> // for atan\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n#include <vnl/vnl_vector.h>\n#include <vnl/vnl_matrix.h>\n#include <vnl/algo/vnl_symmetric_eigensystem.h>\n\n#include \"vnl_vector_to_std_vector.h\"\n#include \"std_vector_to_vnl_vector.h\"\n\nnamespace dki\n{\n\t/**\n\t * Calculate diffusion kurtosis maps from given input tensors.\n\t *\n\t * Modification to Tabesh et al: If eigenvalues are negative set them to 0!\n\t *\n\t */\n\tclass DkiMaps\n\t{\n\tpublic:\n\n\t\tstruct parameters\n\t\t{\n\t\t\tstd::string inputFileName;\n\t\t\tstd::string maskFileName;\n\t\t\tstd::string outputFileName;\n\t\t};\n\n\t\ttypedef double PixelType;\n\n\t\ttypedef itk::Image< PixelType, 4 > ImageType;\n\t\ttypedef itk::Image< PixelType, 3 > OutputImageType;\n\t\ttypedef itk::ImageFileReader< OutputImageType > MaskReaderType;\n\t\ttypedef itk::ImageFileReader< ImageType > ReaderType;\n\t\ttypedef itk::ImageLinearConstIteratorWithIndex< ImageType > ConstIterator4DType;\n\t\ttypedef itk::ImageLinearIteratorWithIndex< ImageType > Iterator4DType;\n\t\ttypedef itk::ImageRegionIteratorWithIndex< OutputImageType > Iterator3DType;\n\n\t\ttypedef itk::ImageRegionConstIteratorWithIndex< OutputImageType > ConstIterator3DType;\n\t\ttypedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n\t\ttypedef vnl_vector< PixelType > VectorType;\n\t\ttypedef vnl_matrix< PixelType > MatrixType;\n\n\t\ttypedef std::pair< PixelType, VectorType > EigenType;\n\t\ttypedef std::vector< EigenType > EigenContainerType;\n\n\t\t/**\n\t\t * Constructor.\n\t\t */\n\t\tDkiMaps( const parameters& args )\n\t\t{\n\t\t\tSetInput( args.inputFileName );\n\t\t\tInitMask( args.maskFileName );\n\t\t\tAllocateOutput();\n\t\t\tInitGlobalIndices();\n\t\t\tCalculateMaps();\n\t\t\tWrite( args.outputFileName );\n\t\t}\n\n\tprotected:\n\n\t\tImageType::Pointer m_Input;\n\t\tOutputImageType::Pointer m_Mask;\n\n\n\t\t// dti maps\n\n\t\tOutputImageType::Pointer m_FA;\n\t\tOutputImageType::Pointer m_Trace;\n\t\tOutputImageType::Pointer m_Lradial;\n\t\tOutputImageType::Pointer m_Laxial;\n\n\t\t// dki maps\n\n\t\tOutputImageType::Pointer m_MK;\n\t\tOutputImageType::Pointer m_Kradial;\n\t\tOutputImageType::Pointer m_Kaxial;\n\n\t\t// indices\n\t\tVectorType m_kvec_to_table;\n\t\tMatrixType m_indices_w0000;\n\t\tMatrixType m_indices_w1111;\n\t\tMatrixType m_indices_w2222;\n\t\tMatrixType m_indices_w1122;\n\t\tMatrixType m_indices_w0022;\n\t\tMatrixType m_indices_w0011;\n\n\t\t/**\n\t\t * Init indices for Wtilda rotation.\n\t\t */\n\t\tvoid InitGlobalIndices()\n\t\t{\n\t\t\tMatrixType index_table = GetIndexTable();\n\t\t\tMatrixType kvec_indices = GetKvecIndices();\n\t\t\tm_kvec_to_table = GetKvec2Table( GetRowSort( index_table ), kvec_indices );\n\n\t\t\tm_indices_w0000 = GetIndicesW( 0, 0, 0, 0, index_table );\n\t\t\tm_indices_w1111 = GetIndicesW( 1, 1, 1, 1, index_table );\n\t\t\tm_indices_w2222 = GetIndicesW( 2, 2, 2, 2, index_table );\n\t\t\tm_indices_w1122 = GetIndicesW( 1, 1, 2, 2, index_table );\n\t\t\tm_indices_w0022 = GetIndicesW( 0, 0, 2, 2, index_table );\n\t\t\tm_indices_w0011 = GetIndicesW( 0, 0, 1, 1, index_table );\n\t\t}\n\n\t\t/**\n\t\t * DKI maps.\n\t\t */\n\t\tvoid CalculateMaps()\n\t\t{\n\t\t\tConstIterator4DType it( m_Input, m_Input->GetLargestPossibleRegion() );\n\t\t\tConstIterator3DType mit( m_Mask, m_Mask->GetLargestPossibleRegion() );\n\n\t\t\tIterator3DType itFA( m_FA, m_FA->GetLargestPossibleRegion() );\n\t\t\tIterator3DType itTrace( m_Trace, m_Trace->GetLargestPossibleRegion() );\n\t\t\tIterator3DType itLaxial( m_Laxial, m_Laxial->GetLargestPossibleRegion() );\n\t\t\tIterator3DType itLradial( m_Lradial, m_Lradial->GetLargestPossibleRegion() );\n\n\t\t\tIterator3DType itMK( m_MK, m_MK->GetLargestPossibleRegion() );\n\t\t\tIterator3DType itKaxial( m_Kaxial, m_Kaxial->GetLargestPossibleRegion() );\n\t\t\tIterator3DType itKradial( m_Kradial, m_Kradial->GetLargestPossibleRegion() );\n\n\t\t\tit.SetDirection( 3 );\n\t\t\tit.GoToBegin();\n\n\t\t\tmit.GoToBegin();\n\n\t\t\titFA.GoToBegin();\n\t\t\titTrace.GoToBegin();\n\t\t\titLaxial.GoToBegin();\n\t\t\titLradial.GoToBegin();\n\n\t\t\titMK.GoToBegin();\n\t\t\titKaxial.GoToBegin();\n\t\t\titKradial.GoToBegin();\n\n\t\t\tif ( m_Input->GetLargestPossibleRegion().GetSize()[3] < 21 )\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: input does not contain less than 21 tensor elements!\" << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\n\t\t\tunsigned int sliceIndex = 0;\n\n\t\t\t// for each voxel\n\n\t\t\twhile ( !it.IsAtEnd(), !mit.IsAtEnd() )\n\t\t\t{\n\t\t\t\tif ( mit.Get() != 0 )\n\t\t\t\t{\n\n\t\t\t\t\t// slice index\n\t\t\t\t\tif ( sliceIndex != it.GetIndex()[2] )\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"Processing slice: \" << sliceIndex << std::endl;\n\t\t\t\t\t\tsliceIndex = it.GetIndex()[2];\n\t\t\t\t\t}\n\n\t\t\t\t\tVectorType b( 6 );\n\t\t\t\t\tVectorType kvec( 15 );\n\n\t\t\t\t\twhile ( !it.IsAtEndOfLine() )\n\t\t\t\t\t{\n\t\t\t\t\t\tunsigned int i = ( it.GetIndex() )[3];\n\n\t\t\t\t\t\tif ( i < 6 )\n\t\t\t\t\t\t\tb( i ) = it.Get();\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tkvec( i - 6 ) = it.Get();\n\n\t\t\t\t\t\t++it;\n\t\t\t\t\t}\n\n\t\t\t\t\tMatrixType DT = GetDTITensor( b );\n\n\t\t\t\t\titFA.Set( GetFA( DT ) );\n\t\t\t\t\titTrace.Set( GetTrace( DT ) );\n\n\t\t\t\t\tEigenContainerType eig = GetEigenSystem( DT );\n\n\t\t\t\t\t// set negative eigenvalues to 0\n\n\t\t\t\t\tfor ( unsigned int i = 0; i < eig.size(); i++ )\n\t\t\t\t\t\tif ( eig.at( i ).first < 0 )\n\t\t\t\t\t\t\teig.at( i ).first = 0;\n\n\t\t\t\t\titLaxial.Set( eig.at( 0 ).first );\n\t\t\t\t\titLradial.Set( ( eig.at( 1 ).first + eig.at( 2 ).first ) / 2. );\n\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tVectorType kvec_scaled = kvec * ( 1. / std::pow( GetTrace( DT ), 2 ) );\n\t\t\t\t\t\tVectorType k = GetKurtosisValues( kvec_scaled, eig ); // TODO\n\t\t\t\t\t\titMK.Set( k( 0 ) );\n\t\t\t\t\t\titKaxial.Set( k( 1 ) );\n\t\t\t\t\t\titKradial.Set( k( 2 ) );\n\t\t\t\t\t} catch ( boost::math::evaluation_error e )\n\t\t\t\t\t{\n\t\t\t\t\t\t// convergence error, leave kurtosis output zero?\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// go to next voxel\n\n\t\t\t\tit.NextLine();\n\t\t\t\t++mit;\n\t\t\t\t++itFA;\n\t\t\t\t++itTrace;\n\t\t\t\t++itLaxial;\n\t\t\t\t++itLradial;\n\n\t\t\t\t++itMK;\n\t\t\t\t++itKaxial;\n\t\t\t\t++itKradial;\n\t\t\t}\n\t\t}\n\n\t\t// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\t\t/**\n\t\t * Return eigenvalues and eigenvector sorted from l1 > l2 > l3.\n\t\t */\n\t\tEigenContainerType GetEigenSystem( const MatrixType& DT )\n\t\t{\n\t\t\tvnl_symmetric_eigensystem< PixelType > eig( DT );\n\n\t\t\tEigenContainerType container( 3 );\n\t\t\tcontainer.at( 0 ) = EigenType( eig.get_eigenvalue( 2 ), eig.get_eigenvector( 2 ) );\n\t\t\tcontainer.at( 1 ) = EigenType( eig.get_eigenvalue( 1 ), eig.get_eigenvector( 1 ) );\n\t\t\tcontainer.at( 2 ) = EigenType( eig.get_eigenvalue( 0 ), eig.get_eigenvector( 0 ) );\n\t\t\treturn container;\n\t\t}\n\t\t/**\n\t\t * Return sum eigenvalues.\n\t\t */\n\t\tPixelType GetTrace( const MatrixType& DT )\n\t\t{\n\t\t\treturn DT( 0, 0 ) + DT( 1, 1 ) + DT( 2, 2 );\n\t\t}\n\n\t\t/**\n\t\t * Return fractional anisotropy (FA).\n\t\t */\n\t\tPixelType GetFA( const MatrixType& DT )\n\t\t{\n\t\t\tPixelType isp = inner_product( DT, DT );\n\t\t\tif ( isp > 0.0 )\n\t\t\t{\n\t\t\t\tPixelType trace = GetTrace( DT );\n\t\t\t\tPixelType anisotropy = 3.0 * isp - trace * trace;\n\t\t\t\tPixelType fractionalAnisotropy = std::sqrt( anisotropy / ( 2.0 * isp ) );\n\t\t\t\treturn fractionalAnisotropy;\n\t\t\t}\n\t\t\treturn 0.0;\n\t\t}\n\n\t\t/**\n\t\t * Index table W sort.\n\t\t */\n\t\tMatrixType GetIndexTable()\n\t\t{\n\t\t\tMatrixType table( 81, 4 );\n\n\t\t\tunsigned int lin_idx = 0;\n\n\t\t\tfor ( unsigned int i = 0; i < 3; i++ )\n\t\t\t\tfor ( unsigned int j = 0; j < 3; j++ )\n\t\t\t\t\tfor ( unsigned int k = 0; k < 3; k++ )\n\t\t\t\t\t\tfor ( unsigned int l = 0; l < 3; l++ )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tVectorType row( 4 );\n\t\t\t\t\t\t\trow( 0 ) = i;\n\t\t\t\t\t\t\trow( 1 ) = j;\n\t\t\t\t\t\t\trow( 2 ) = k;\n\t\t\t\t\t\t\trow( 3 ) = l;\n\t\t\t\t\t\t\ttable.set_row( lin_idx, row );\n\t\t\t\t\t\t\tlin_idx++;\n\t\t\t\t\t\t}\n\n\t\t\treturn table;\n\t\t}\n\n\t\t/**\n\t\t * Sort rows in matrix ('ascend' way).\n\t\t */\n\t\tMatrixType GetRowSort( const MatrixType& M )\n\t\t{\n\t\t\tMatrixType out( M );\n\n\t\t\tfor ( unsigned int r = 0; r < out.rows(); r++ )\n\t\t\t{\n\t\t\t\tstd::vector< PixelType > v = vnl_vector_to_std_vector( out.get_row( r ) );\n\t\t\t\tstd::sort( v.begin(), v.end() );\n\t\t\t\tout.set_row( r, std_vector_to_vnl_vector( v ) );\n\t\t\t}\n\n\t\t\treturn out;\n\t\t}\n\n\t\t/**\n\t\t * Return matching indices.\n\t\t */\n\t\tVectorType GetKvec2Table( const MatrixType& table, const MatrixType& kvec )\n\t\t{\n\t\t\tVectorType indices( table.rows(), 0 );\n\n\t\t\tfor ( unsigned int i = 0; i < table.rows(); i++ )\n\t\t\t{\n\t\t\t\tfor ( unsigned int j = 0; j < kvec.rows(); j++ )\n\t\t\t\t{\n\t\t\t\t\tif ( kvec.get_row( j ) == table.get_row( i ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tindices( i ) = j;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn indices;\n\t\t}\n\n\t\t/**\n\t\t * Kvec:\n\t\t *\n\t\t * k1111 k2222 k3333\n\t\t * k1112 k1113 k1222\n\t\t * k2223 k1333 k2333\n\t\t * k1122 k1133 k2233\n\t\t * k1123 k1223 k1233\n\t\t */\n\t\tMatrixType GetKvecIndices()\n\t\t{\n\t\t\tMatrixType t( 15, 4 );\n\n\t\t\tPixelType data[60] =\n\t\t\t{ 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 1, 0, 0, 0, 2, 0, 1, 1, 1, 1, 1, 1, 2, 0, 2, 2, 2, 1, 2, 2, 2, 0, 0, 1, 1, 0, 0,\n\t\t\t\t\t2, 2, 1, 1, 2, 2, 0, 0, 1, 2, 0, 1, 1, 2, 0, 1, 2, 2 };\n\n\t\t\tt.set( data );\n\n\t\t\treturn t;\n\t\t}\n\n\t\t/**\n\t\t * Matlab sub2ind.\n\t\t */\n\t\tunsigned int sub2ind( unsigned int nrow, unsigned int x, unsigned int y )\n\t\t{\n\n\t\t\treturn ( x + y * nrow );\n\t\t}\n\n\t\t/**\n\t\t * Return W_ijkl in terms of indices.\n\t\t */\n\t\tMatrixType GetIndicesW( unsigned int i, unsigned int j, unsigned int k, unsigned int l, const MatrixType indices )\n\t\t{\n\t\t\tMatrixType W( 81, 4 );\n\n\t\t\tfor ( unsigned int r = 0; r < W.rows(); r++ )\n\t\t\t{\n\t\t\t\tW( r, 0 ) = sub2ind( 3, indices( r, 0 ), i );\n\t\t\t\tW( r, 1 ) = sub2ind( 3, indices( r, 1 ), j );\n\t\t\t\tW( r, 2 ) = sub2ind( 3, indices( r, 2 ), k );\n\t\t\t\tW( r, 3 ) = sub2ind( 3, indices( r, 3 ), l );\n\t\t\t}\n\n\t\t\treturn W;\n\t\t}\n\n\t\t/**\n\t\t * Resort kvec.\n\t\t */\n\t\tVectorType GetKvecExtended( const VectorType& kvec, const VectorType& indices )\n\t\t{\n\t\t\tVectorType out( indices.size(), 0 );\n\n\t\t\tfor ( unsigned int i = 0; i < out.size(); i++ )\n\t\t\t{\n\t\t\t\tout( i ) = kvec( indices( i ) );\n\t\t\t}\n\t\t\treturn out;\n\t\t}\n\n\t\t/**\n\t\t * Get column-wise vector of sorted eigen vectors.\n\t\t */\n\t\tVectorType EigenVectorsToStretchedFormat( const VectorType& e1, const VectorType& e2, const VectorType& e3 )\n\t\t{\n\t\t\tVectorType s( 9 );\n\t\t\ts( 0 ) = e1( 0 );\n\t\t\ts( 1 ) = e2( 0 );\n\t\t\ts( 2 ) = e3( 0 );\n\n\t\t\ts( 3 ) = e1( 1 );\n\t\t\ts( 4 ) = e2( 1 );\n\t\t\ts( 5 ) = e3( 1 );\n\n\t\t\ts( 6 ) = e1( 2 );\n\t\t\ts( 7 ) = e2( 2 );\n\t\t\ts( 8 ) = e3( 2 );\n\n\t\t\treturn s;\n\t\t}\n\n\t\t/**\n\t\t * Return W~, rotated in DT coordinates.\n\t\t */\n\t\tPixelType GetRotatedW( const MatrixType& indices, const EigenContainerType& eig, const VectorType& kvec )\n\t\t{\n\t\t\tVectorType V = EigenVectorsToStretchedFormat( eig.at( 0 ).second, eig.at( 1 ).second, eig.at( 2 ).second );\n\n\t\t\tVectorType col1( indices.rows() );\n\t\t\tVectorType col2( indices.rows() );\n\t\t\tVectorType col3( indices.rows() );\n\t\t\tVectorType col4( indices.rows() );\n\n\t\t\tfor ( unsigned int i = 0; i < col1.size(); i++ )\n\t\t\t{\n\t\t\t\tcol1( i ) = V( indices( i, 0 ) );\n\t\t\t\tcol2( i ) = V( indices( i, 1 ) );\n\t\t\t\tcol3( i ) = V( indices( i, 2 ) );\n\t\t\t\tcol4( i ) = V( indices( i, 3 ) );\n\t\t\t}\n\n\t\t\tVectorType tmp = element_product( element_product( col1, col2 ), element_product( col3, col4 ) );\n\n\t\t\treturn dot_product( tmp, kvec );\n\t\t}\n\n\t\t/**\n\t\t * Return MK, Kaxial and Kradial.\n\t\t *\n\t\t * Given eig\n\t\t * Given kvec (15 kurtosis parameters)\n\t\t */\n\t\tVectorType GetKurtosisValues( const VectorType kvec, const EigenContainerType& eig )\n\t\t{\n\t\t\tVectorType kvec_extended = GetKvecExtended( kvec, m_kvec_to_table );\n\n\t\t\tPixelType Wtilda_0000 = GetRotatedW( m_indices_w0000, eig, kvec_extended );\n\t\t\tPixelType Wtilda_0011 = GetRotatedW( m_indices_w0011, eig, kvec_extended );\n\t\t\tPixelType Wtilda_0022 = GetRotatedW( m_indices_w0022, eig, kvec_extended );\n\t\t\tPixelType Wtilda_1111 = GetRotatedW( m_indices_w1111, eig, kvec_extended );\n\t\t\tPixelType Wtilda_1122 = GetRotatedW( m_indices_w1122, eig, kvec_extended );\n\t\t\tPixelType Wtilda_2222 = GetRotatedW( m_indices_w2222, eig, kvec_extended );\n\n\t\t\tPixelType l1 = eig.at( 0 ).first;\n\t\t\tPixelType l2 = eig.at( 1 ).first;\n\t\t\tPixelType l3 = eig.at( 2 ).first;\n\n\t\t\tPixelType MK = F1( l1, l2, l3 ) * Wtilda_0000 + F1( l2, l1, l3 ) * Wtilda_1111 + F1( l3, l2, l1 ) * Wtilda_2222 + F2( l1, l2,\n\t\t\t\t\tl3 ) * Wtilda_1122 + F2( l2, l1, l3 ) * Wtilda_0022 + F2( l3, l2, l1 ) * Wtilda_0011;\n\n\t\t\tPixelType Kaxial = ( std::pow( l1 + l2 + l3, 2 ) / 9 * std::pow( l1, 2 ) ) * Wtilda_0000;\n\n\t\t\tPixelType Kradial = G1( l1, l2, l3 ) * Wtilda_1111 + G1( l1, l3, l2 ) * Wtilda_2222 + G2( l1, l2, l3 ) * Wtilda_1122;\n\n\t\t\tVectorType k( 3 );\n\t\t\tk( 0 ) = MK;\n\t\t\tk( 1 ) = Kaxial;\n\t\t\tk( 2 ) = Kradial;\n\n\t\t\treturn k;\n\t\t}\n\n\t\t/**\n\t\t * Eq (33) Tabesh et al.\n\t\t */\n\t\tPixelType G1( PixelType l1, PixelType l2, PixelType l3 )\n\t\t{\n\t\t\tif ( l2 != l3 )\n\t\t\t{\n\t\t\t\tPixelType a = std::pow( l1 + l2 + l3, 2 ) / 18 * l1 * std::pow( l2 - l3, 2 );\n\t\t\t\tPixelType b = 2 * l2 + ( std::pow( l3, 2 ) - 3 * l2 * l3 ) / std::sqrt( l2 * l3 );\n\n\t\t\t\treturn a * ( 2 * l2 + b );\n\t\t\t}\n\n\t\t\treturn std::pow( l1 + 2 * l2, 2 ) / std::pow( 24. * l2, 2 );\n\t\t}\n\n\t\t/**\n\t\t * Eq (34) Tabesh et al.\n\t\t */\n\t\tPixelType G2( PixelType l1, PixelType l2, PixelType l3 )\n\t\t{\n\t\t\tif ( l2 != l3 )\n\t\t\t{\n\t\t\t\tPixelType a = std::pow( l1 + l2 + l3, 2 ) / 3 * std::pow( l2 - l3, 2 );\n\t\t\t\tPixelType b = l2 + l3 / std::sqrt( l2 + l3 );\n\n\t\t\t\treturn a * ( b - 2 );\n\t\t\t}\n\n\t\t\treturn 6 * std::pow( l1 + 2 * l2, 2 ) / std::pow( 72 * l2, 2 );\n\t\t}\n\n\t\t/**\n\t\t * Eq (27) Tabesh et al.\n\t\t */\n\t\tPixelType F1( PixelType l1, PixelType l2, PixelType l3 )\n\t\t{\n\t\t\tif ( ( l1 == l2 ) && ( l2 == l3 ) )\n\t\t\t{\n\t\t\t\treturn 0.2;\n\t\t\t} else if ( l1 == l2 )\n\t\t\t{\n\t\t\t\treturn 0.5 * F2( l3, l1, l1 );\n\t\t\t} else if ( l1 == l3 )\n\t\t\t{\n\t\t\t\treturn 0.5 * F2( l2, l1, l1 );\n\t\t\t}\n\n\t\t\tPixelType a = std::pow( l1 + l2 + l3, 2 ) / 18 * ( l1 - l2 ) * ( l1 - l3 );\n\t\t\tPixelType b = std::sqrt( l2 * l3 ) / l1;\n\t\t\tPixelType c = boost::math::ellint_rf( l1 / l2, l1 / l3, 1. );\n\t\t\tPixelType d = ( 3 * std::pow( l1, 2 ) - l1 * l2 - l1 * l3 - l2 * l3 ) / 3 * l1 * std::sqrt( l2 * l3 );\n\t\t\tPixelType e = boost::math::ellint_rd( l1 / l2, l1 / l3, 1. );\n\n\t\t\treturn a * ( b * c + d * e - 1 );\n\t\t}\n\n\t\t/**\n\t\t * Eq (28) Tabesh et al.\n\t\t */\n\t\tPixelType F2( PixelType l1, PixelType l2, PixelType l3 )\n\t\t{\n\t\t\tif ( l2 != l3 )\n\t\t\t{\n\t\t\t\tPixelType a = std::pow( l1 + l2 + l3, 2 ) / ( 3 * std::pow( l2 - l3, 2 ) );\n\t\t\t\tPixelType b = ( l2 + l3 ) / std::sqrt( l2 * l3 );\n\t\t\t\tPixelType c = boost::math::ellint_rf( l1 / l2, l1 / l3, 1. );\n\t\t\t\tPixelType d = ( 2 * l1 - l2 + l3 ) / ( 3 * std::sqrt( l2 * l3 ) );\n\t\t\t\tPixelType e = boost::math::ellint_rd( l1 / l2, l1 / l3, 1. );\n\n\t\t\t\treturn a * ( b * c + d * e - 2 );\n\t\t\t} else if ( l1 != l3 )\n\t\t\t{\n\t\t\t\tPixelType a = std::pow( l1 + 2 * l3, 2 ) / std::pow( 144 * l3, 2 ) * std::pow( l1 - l3, 2 );\n\t\t\t\tPixelType b = l3 * ( l1 + 2 * l3 );\n\t\t\t\tPixelType c = 1 - ( l1 / l3 );\n\t\t\t\tPixelType d = l1 * ( l1 - 4 * l3 );\n\n\t\t\t\tc = std::sqrt( std::abs< PixelType >( c ) );\n\t\t\t\td = d * ( 1. / c ) * std::atan( c );\n\n\t\t\t\treturn 6 * a * ( b + d );\n\t\t\t}\n\n\t\t\treturn 6. / 15.;\n\t\t}\n\n\t\t/**\n\t\t * Return 2-rank DTI tensor.\n\t\t *\n\t\t * layout =>\n\t\t * \t\t| 0  1  2  |\n\t\t *\t    | 1  3  4  |\n\t\t *      | 2  4  5  |\n\t\t */\n\t\tMatrixType GetDTITensor( const VectorType& x )\n\t\t{\n\t\t\tMatrixType DT( 3, 3 );\n\n\t\t\t/*\n\t\t\t m_A_D( i, 0 ) =     Gx * Gx;\n\t\t\t m_A_D( i, 1 ) =     Gy * Gy;\n\t\t\t m_A_D( i, 2 ) = 2 * Gx * Gy;\n\t\t\t m_A_D( i, 3 ) =     Gz * Gz;\n\t\t\t m_A_D( i, 4 ) = 2 * Gy * Gz;\n\t\t\t m_A_D( i, 5 ) = 2 * Gx * Gz;\n\t\t\t */\n\n\t\t\tDT( 0, 0 ) = x( 0 ); // x * x\n\t\t\tDT( 0, 1 ) = x( 2 );\n\t\t\tDT( 0, 2 ) = x( 5 );\n\n\t\t\tDT( 1, 0 ) = x( 2 );\n\t\t\tDT( 1, 1 ) = x( 1 ); // y * y\n\t\t\tDT( 1, 2 ) = x( 4 );\n\n\t\t\tDT( 2, 0 ) = x( 5 );\n\t\t\tDT( 2, 1 ) = x( 4 );\n\t\t\tDT( 2, 2 ) = x( 3 ); // z * z\n\n\t\t\treturn DT;\n\t\t}\n\n\t\t/**\n\t\t * Set input image.\n\t\t */\n\t\tvoid SetInput( const std::string& inputFileName )\n\t\t{\n\t\t\tif ( !inputFileName.empty() )\n\t\t\t{\n\t\t\t\tReaderType::Pointer reader = ReaderType::New();\n\t\t\t\treader->SetFileName( inputFileName );\n\t\t\t\treader->Update();\n\t\t\t\tm_Input = reader->GetOutput();\n\t\t\t} else\n\t\t\t{\n\t\t\t\tstd::cerr << \"Could not read input: \" << inputFileName << \"!\" << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t\t * Init mask if file given, else create empty mask from input file.\n\t\t\t */\n\t\t\tvoid InitMask( const std::string& maskFileName )\n\t\t\t{\n\t\t\t\tif ( !maskFileName.empty() )\n\t\t\t\t{\n\t\t\t\t\tMaskReaderType::Pointer reader = MaskReaderType::New();\n\t\t\t\t\treader->SetFileName( maskFileName );\n\t\t\t\t\treader->Update();\n\t\t\t\t\tm_Mask = reader->GetOutput();\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tOutputImageType::Pointer output = OutputImageType::New();\n\t\t\t\t\tOutputImageType::RegionType region3D;\n\t\t\t\t\tOutputImageType::IndexType index3D;\n\t\t\t\t\tOutputImageType::SizeType size3D;\n\t\t\t\t\tOutputImageType::SpacingType spacing3D;\n\t\t\t\t\tOutputImageType::PointType origin3D;\n\n\t\t\t\t\tImageType::RegionType region = m_Input->GetLargestPossibleRegion();\n\t\t\t\t\tImageType::SizeType size = region.GetSize();\n\t\t\t\t\tImageType::IndexType index = region.GetIndex();\n\t\t\t\t\tImageType::SpacingType spacing = m_Input->GetSpacing();\n\t\t\t\t\tImageType::PointType origin = m_Input->GetOrigin();\n\n\t\t\t\t\tsize3D[0] = size[0];\n\t\t\t\t\tsize3D[1] = size[1];\n\t\t\t\t\tsize3D[2] = size[2];\n\t\t\t\t\tindex3D[0] = index[0];\n\t\t\t\t\tindex3D[1] = index[1];\n\t\t\t\t\tindex3D[2] = index[2];\n\t\t\t\t\torigin3D[0] = origin[0];\n\t\t\t\t\torigin3D[1] = origin[1];\n\t\t\t\t\torigin3D[2] = origin[2];\n\t\t\t\t\tspacing3D[0] = spacing[0];\n\t\t\t\t\tspacing3D[1] = spacing[1];\n\t\t\t\t\tspacing3D[2] = spacing[2];\n\n\t\t\t\t\tregion3D.SetSize( size3D );\n\t\t\t\t\tregion3D.SetIndex( index3D );\n\n\t\t\t\t\t// set\n\t\t\t\t\toutput->SetRegions( region3D );\n\t\t\t\t\toutput->SetSpacing( spacing3D );\n\t\t\t\t\toutput->SetOrigin( origin3D );\n\t\t\t\t\toutput->Allocate();\n\t\t\t\t\toutput->FillBuffer( 1 );\n\n\t\t\t\t\tm_Mask = output;\n\t\t\t\t}\n\t\t\t}\n\n\t\t/**\n\t\t * Allocate all output images to 0.\n\t\t */\n\t\tvoid AllocateOutput()\n\t\t{\n\t\t\tOutputImageType::RegionType region3D;\n\t\t\tOutputImageType::IndexType index3D;\n\t\t\tOutputImageType::SizeType size3D;\n\t\t\tOutputImageType::SpacingType spacing3D;\n\t\t\tOutputImageType::PointType origin3D;\n\n\t\t\tImageType::RegionType region = m_Input->GetLargestPossibleRegion();\n\t\t\tImageType::SizeType size = region.GetSize();\n\t\t\tImageType::IndexType index = region.GetIndex();\n\t\t\tImageType::SpacingType spacing = m_Input->GetSpacing();\n\t\t\tImageType::PointType origin = m_Input->GetOrigin();\n\n\t\t\tsize3D[0] = size[0];\n\t\t\tsize3D[1] = size[1];\n\t\t\tsize3D[2] = size[2];\n\t\t\tindex3D[0] = index[0];\n\t\t\tindex3D[1] = index[1];\n\t\t\tindex3D[2] = index[2];\n\t\t\torigin3D[0] = origin[0];\n\t\t\torigin3D[1] = origin[1];\n\t\t\torigin3D[2] = origin[2];\n\t\t\tspacing3D[0] = spacing[0];\n\t\t\tspacing3D[1] = spacing[1];\n\t\t\tspacing3D[2] = spacing[2];\n\n\t\t\tregion3D.SetSize( size3D );\n\t\t\tregion3D.SetIndex( index3D );\n\n\t\t\t// create\n\t\t\tm_FA = OutputImageType::New();\n\t\t\tm_Trace = OutputImageType::New();\n\t\t\tm_Laxial = OutputImageType::New();\n\t\t\tm_Lradial = OutputImageType::New();\n\n\t\t\tm_MK = OutputImageType::New();\n\t\t\tm_Kaxial = OutputImageType::New();\n\t\t\tm_Kradial = OutputImageType::New();\n\n\t\t\t// set\n\t\t\tm_FA->SetRegions( region3D );\n\t\t\tm_FA->SetSpacing( spacing3D );\n\t\t\tm_FA->SetOrigin( origin3D );\n\t\t\tm_FA->Allocate();\n\t\t\tm_FA->FillBuffer( 0 );\n\n\t\t\tm_Trace->SetRegions( region3D );\n\t\t\tm_Trace->SetSpacing( spacing3D );\n\t\t\tm_Trace->SetOrigin( origin3D );\n\t\t\tm_Trace->Allocate();\n\t\t\tm_Trace->FillBuffer( 0 );\n\n\t\t\tm_Laxial->SetRegions( region3D );\n\t\t\tm_Laxial->SetSpacing( spacing3D );\n\t\t\tm_Laxial->SetOrigin( origin3D );\n\t\t\tm_Laxial->Allocate();\n\t\t\tm_Laxial->FillBuffer( 0 );\n\n\t\t\tm_Lradial->SetRegions( region3D );\n\t\t\tm_Lradial->SetSpacing( spacing3D );\n\t\t\tm_Lradial->SetOrigin( origin3D );\n\t\t\tm_Lradial->Allocate();\n\t\t\tm_Lradial->FillBuffer( 0 );\n\n\t\t\tm_MK->SetRegions( region3D );\n\t\t\tm_MK->SetSpacing( spacing3D );\n\t\t\tm_MK->SetOrigin( origin3D );\n\t\t\tm_MK->Allocate();\n\t\t\tm_MK->FillBuffer( 0 );\n\n\t\t\tm_Kaxial->SetRegions( region3D );\n\t\t\tm_Kaxial->SetSpacing( spacing3D );\n\t\t\tm_Kaxial->SetOrigin( origin3D );\n\t\t\tm_Kaxial->Allocate();\n\t\t\tm_Kaxial->FillBuffer( 0 );\n\n\t\t\tm_Kradial->SetRegions( region3D );\n\t\t\tm_Kradial->SetSpacing( spacing3D );\n\t\t\tm_Kradial->SetOrigin( origin3D );\n\t\t\tm_Kradial->Allocate();\n\t\t\tm_Kradial->FillBuffer( 0 );\n\t\t}\n\n\t\t/**\n\t\t * Write output images.\n\t\t */\n\t\tvoid Write( const std::string& outputFileName )\n\t\t{\n\t\t\t// Writer\n\t\t\tWriterType::Pointer writer = WriterType::New();\n\n\t\t\t// FA\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_FA.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( m_FA );\n\t\t\twriter->Update();\n\n\t\t\t// Trace\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_Trace.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( m_Trace );\n\t\t\twriter->Update();\n\n\t\t\t// L axial\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_Laxial.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( m_Laxial );\n\t\t\twriter->Update();\n\n\t\t\t// L radial\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_Lradial.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( m_Lradial );\n\t\t\twriter->Update();\n\n\t\t\t// MK\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_MK.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( m_MK );\n\t\t\twriter->Update();\n\n\t\t\t// K axial\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_Kaxial.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( m_Kaxial );\n\t\t\twriter->Update();\n\n\t\t\t// K radial\n\t\t\twriter->SetFileName( ( outputFileName + std::string( \"_Kradial.nii.gz\" ) ).c_str() );\n\t\t\twriter->SetInput( m_Kradial );\n\t\t\twriter->Update();\n\t\t}\n\n\t};\n\n} // end namespace dki\n\n\n/**\n * Create dki maps.\n */\nint main( int argc, char ** argv )\n{\n\ttkd::CmdParser p( argv[0], \"Create diffusion kurtosis maps.\" );\n\n\tdki::DkiMaps::parameters args;\n\n\tp.AddArgument( args.inputFileName, \"input\" ) ->AddAlias( \"i\" ) ->SetDescription( \"Input 4D image with 21 tensor elements\" ) ->SetRequired(\n\t\t\ttrue );\n\n\tp.AddArgument( args.outputFileName, \"output\" ) ->AddAlias( \"o\" ) ->SetDescription( \"Output filename base\" ) ->SetRequired( true );\n\n\tp.AddArgument( args.maskFileName, \"mask\" ) ->AddAlias( \"m\" ) ->SetDescription( \"Mask 3D image\" );\n\n\tif ( !p.Parse( argc, argv ) )\n\t{\n\t\tp.PrintUsage( std::cout );\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tdki::DkiMaps maps( args );\n\n\treturn EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "8537469d564d9caac2594c8383f7eb059ffd3573", "size": 21904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dkifit/dkimaps.cpp", "max_stars_repo_name": "wmotte/toolkid", "max_stars_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dkifit/dkimaps.cpp", "max_issues_repo_name": "wmotte/toolkid", "max_issues_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dkifit/dkimaps.cpp", "max_forks_repo_name": "wmotte/toolkid", "max_forks_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9526066351, "max_line_length": 139, "alphanum_fraction": 0.5967859752, "num_tokens": 7836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851918, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.44998972819136823}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n    @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_CEIL_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_CEIL_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-arithmetic\n    This function object computes the smallest integral representable value of\n    its parameter type which is greater or equal to it.\n\n    @par Header <boost/simd/function/ceil.hpp>\n\n    @par Notes\n\n     - @c ceil is also used as parameter to pass to @ref div or @ref rem\n\n    @par Decorators\n\n    - std_ for floating entries call std::ceil\n\n    @see  floor, round, nearbyint, trunc, iceil\n\n    @par Example:\n\n      @snippet ceil.cpp ceil\n\n    @par Possible output:\n\n      @snippet ceil.txt ceil\n\n  **/\n  Value ceil(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/ceil.hpp>\n#include <boost/simd/function/simd/ceil.hpp>\n\n#endif\n", "meta": {"hexsha": "fcdc43ad4ea14d6e37156ec1f8d3f2ba83726154", "size": 1231, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/ceil.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/ceil.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/ceil.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.6730769231, "max_line_length": 100, "alphanum_fraction": 0.5946385053, "num_tokens": 264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4499293052360427}}
{"text": "#include \"IntegratorRect.hh\"\n\n#include <Eigen/Dense>\n#include <iterator>\n\n#include \"TypesFunctions.hh\"\n\nusing namespace Eigen;\nusing namespace std;\n\nIntegratorRect::IntegratorRect(int order, const std::string& mode) : IntegratorBase(order)\n{\n  init(mode);\n}\n\nIntegratorRect::IntegratorRect(size_t bins, int orders, double* edges, const std::string& mode) : IntegratorBase(bins, orders, edges)\n{\n  init(mode);\n}\n\nIntegratorRect::IntegratorRect(size_t bins, int* orders, double* edges, const std::string& mode) : IntegratorBase(bins, orders, edges)\n{\n  init(mode);\n}\n\nvoid IntegratorRect::init(const std::string& mode) {\n  m_mode = mode;\n\n  if(m_mode==\"left\"){\n    m_rect_offset=-1;\n  }\n  else if(m_mode==\"center\"){\n    m_rect_offset=0;\n  }\n  else if(m_mode==\"right\"){\n    m_rect_offset=1;\n  }\n  else{\n    throw std::runtime_error(\"invalid rectangular integration mode\");\n  }\n\n  init_sampler();\n}\n\nvoid IntegratorRect::sample(FunctionArgs& fargs){\n  auto& rets=fargs.rets;\n  rets[1].x = m_edges.cast<double>();\n  rets[2].x = 0.0;\n  auto npoints=m_edges.size()-1;\n  rets[3].x = 0.5*(m_edges.tail(npoints)+m_edges.head(npoints));\n\n  auto& abscissa=rets[0].x;\n\n  auto nbins=m_edges.size()-1;\n  auto& binwidths=m_edges.tail(nbins) - m_edges.head(nbins);\n  ArrayXd samplewidths=binwidths/m_orders.cast<double>();\n\n  ArrayXd low, high;\n  switch(m_rect_offset){\n    case -1: {\n      low=m_edges.head(nbins);\n      high=m_edges.tail(nbins)-samplewidths;\n      break;\n      }\n    case 0: {\n      ArrayXd offsetwidth=samplewidths*0.5;\n      low=m_edges.head(nbins)+offsetwidth;\n      high=m_edges.tail(nbins)-offsetwidth;\n      break;\n      }\n    case 1: {\n      samplewidths=binwidths/m_orders.cast<double>();\n      low=m_edges.head(nbins)+samplewidths;\n      high=m_edges.tail(nbins);\n      break;\n      }\n  }\n\n  size_t offset=0;\n  for (size_t i = 0; i < static_cast<size_t>(m_orders.size()); ++i) {\n    auto n=m_orders[i];\n    if(n>1){\n      abscissa.segment(offset, n)=ArrayXd::LinSpaced(n, low[i], high[i]);\n      m_weights.segment(offset, n)=samplewidths[i];\n    }\n    else{\n      abscissa[i]=low[i];\n      m_weights[i]=binwidths[i];\n    }\n    offset+=n;\n  }\n  rets.untaint();\n  rets.freeze();\n}\n", "meta": {"hexsha": "087faacd081e6ad7e5bcb66e0956db2ec4f09ba8", "size": 2190, "ext": "cc", "lang": "C++", "max_stars_repo_path": "transformations/integrator/IntegratorRect.cc", "max_stars_repo_name": "gnafit/gna", "max_stars_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-10-14T01:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T16:33:06.000Z", "max_issues_repo_path": "transformations/integrator/IntegratorRect.cc", "max_issues_repo_name": "gnafit/gna", "max_issues_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "transformations/integrator/IntegratorRect.cc", "max_forks_repo_name": "gnafit/gna", "max_forks_repo_head_hexsha": "c1a58dac11783342c97a2da1b19c97b85bce0394", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0526315789, "max_line_length": 134, "alphanum_fraction": 0.6552511416, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4497767060312753}}
{"text": "//\n// Created by Hamza El-Kebir on 6/21/21.\n//\n\n#ifndef LODESTAR_SINGLETON_HPP\n#define LODESTAR_SINGLETON_HPP\n\n#include <type_traits>\n#include <Eigen/Dense>\n#include \"Lodestar/aux/CompileTimeQualifiers.hpp\"\n\n#include \"SetExpression.hpp\"\n#include \"SetUnion.hpp\"\n#include \"EmptySet.hpp\"\n#include \"SetComplement.hpp\"\n\nnamespace ls {\n    namespace primitives {\n        namespace sets {\n            /**\n             * @brief A singleton set.\n             *\n             * @brief A singleton contains a single element, represented by the vector \\c value_.\n             *\n             * @tparam TDimension The dimension of the singleton; if -1, it is dynamically sized.\n             * @tparam TScalarType The scalar type.\n             */\n            template<int TDimension = -1, typename TScalarType = double>\n            class Singleton : public SetExpression<Singleton<TDimension, TScalarType>> {\n            public:\n                template<typename, typename>\n                friend\n                class SetUnion;\n\n                using Base = SetExpression<Singleton<TDimension, TScalarType>>; //! Base class.\n                using type = Singleton<TDimension, TScalarType>; //! Expression type.\n\n                typedef Eigen::Matrix<TScalarType, LS_STATIC_UNLESS_DYNAMIC(TDimension), 1> TDValue; //! Value typedef.\n\n                /**\n                 * @brief Default constructor.\n                 */\n                Singleton() : value_{TDValue::Zero()}\n                {\n                    this->sEnum_ = SetEnum::Singleton;\n                }\n\n                /**\n                 * @brief Constructs a Singleton instance from a vector.\n                 *\n                 * @tparam TDerived Derived EigenBase class.\n                 *\n                 * @param value Singleton value.\n                 */\n                template<typename TDerived>\n                Singleton(const Eigen::EigenBase<TDerived> &value) : value_(value)\n                {\n                    this->sEnum_ = SetEnum::Singleton;\n                }\n\n                /**\n                 * @brief Returns the singleton dimension.\n                 *\n                 * @details This specialization deals with the static case.\n                 *\n                 * @tparam T_TDimension Copy of \\c TDimension.\n                 *\n                 * @return Dimension of the singleton instance.\n                 */\n                template<int T_TDimension = TDimension>\n                int\n                dimension(typename std::enable_if<(T_TDimension < 0)>::type * = nullptr) const\n                {\n                    return T_TDimension;\n                }\n\n                /**\n                 * @brief Returns the singleton dimension.\n                 *\n                 * @details This specialization deals with the dynamic case.\n                 *\n                 * @tparam T_TDimension Copy of \\c TDimension.\n                 *\n                 * @return Dimension of the singleton instance.\n                 */\n                template<int T_TDimension = TDimension>\n                int\n                dimension(typename std::enable_if<(T_TDimension >= 0)>::type * = nullptr) const\n                {\n                    return value_.rows();\n                }\n\n                /**\n                 * @brief Changes the dimension of the singleton.\n                 *\n                 * @details This specialization raises a static assert since statically type Singleton instances cannot\n                 * be resized.\n                 *\n                 * @tparam T_TDimension Copy of \\c TDimension.\n                 *\n                 * @param dim New dimension.\n                 */\n                template<int T_TDimension = TDimension>\n                void\n                setDimension(size_t dim, typename std::enable_if<(T_TDimension < 0)>::type * = nullptr)\n                {\n                    static_assert(TDimension > -1, \"Cannot set dimension of statically sized singleton.\");\n                }\n\n                /**\n                 * @brief Changes the dimension of the singleton.\n                 *\n                 * @details This specialization conservatively resizes \\c value_.\n                 *\n                 * @tparam T_TDimension Copy of \\c TDimension.\n                 *\n                 * @param dim New dimension.\n                 */\n                template<int T_TDimension = TDimension>\n                void\n                setDimension(size_t dim, typename std::enable_if<(T_TDimension >= 0)>::type * = nullptr)\n                {\n                    value_.conservativeResize(dim);\n                }\n\n                /**\n                 * @brief Returns true if this expression contains \\c expr.\n                 *\n                 * @details This specialization handles a singleton expression of the same type.\n                 *\n                 * @tparam TExpression Type of the other expression.\n                 *\n                 * @param expr Expression to check containment of.\n                 * @param tol Numerical tolerance.\n                 *\n                 * @return True if this expression contains \\c expr, false otherwise.\n                 */\n                template<typename TExpression>\n                typename std::enable_if<std::is_same<TExpression, type>::value, bool>::type\n                contains(const SetExpression<TExpression> &expr, double tol = 1e-6) const\n                {\n                    return (value_ - static_cast<const TExpression *>(&expr)->value_).isMuchSmallerThan(tol);\n                }\n\n                /**\n                 * @brief Returns true if this expression contains \\c expr.\n                 *\n                 * @details This specialization handles all other cases.\n                 *\n                 * @tparam TExpression Type of the other expression.\n                 *\n                 * @param expr Expression to check containment of.\n                 * @param tol Numerical tolerance.\n                 *\n                 * @return False.\n                 */\n                template<typename TExpression>\n                typename std::enable_if<!std::is_same<TExpression, type>::value, bool>::type\n                contains(const SetExpression<TExpression> &expr, double tol = 1e-6) const\n                {\n                    return false;\n                }\n\n                /**\n                 * @brief Checks if this expression is equal to \\expr.\n                 *\n                 * @details This specialization deals with singletons of the same type.\n                 *\n                 * @tparam TExpression Type of the other expression.\n                 *\n                 * @param expr Expression to check equality with.\n                 *\n                 * @return True if this expression is equal to \\c expr, false otherwise.\n                 */\n                template<typename TExpression>\n                typename std::enable_if<std::is_same<TExpression, type>::value, bool>::type\n                operator==(const SetExpression<TExpression> &expr) const\n                {\n                    return (value_ - static_cast<const TExpression *>(&expr)->value_).isMuchSmallerThan(1e-6);\n                }\n\n                // TODO: Add dynamic case.\n\n                /**\n                 * @brief Checks if this expression is equal to \\expr.\n                 *\n                 * @details This specialization deals with all other cases.\n                 *\n                 * @tparam TExpression Type of the other expression.\n                 *\n                 * @param expr Expression to check equality with.\n                 *\n                 * @return False.\n                 */\n                template<typename TExpression>\n                typename std::enable_if<!std::is_same<TExpression, type>::value, bool>::type\n                operator==(const SetExpression<TExpression> &expr) const\n                {\n                    return false;\n                }\n\n                /**\n                 * @brief Checks if this expression is not equal to \\expr.\n                 *\n                 * @details This specialization deals with singletons of the same type.\n                 *\n                 * @tparam TExpression Type of the other expression.\n                 *\n                 * @param expr Expression to check inequality with.\n                 *\n                 * @return True if this expression is not equal to \\c expr, false otherwise.\n                 */\n                template<typename TExpression>\n                typename std::enable_if<std::is_same<TExpression, type>::value, bool>::type\n                operator!=(const SetExpression<TExpression> &expr) const\n                {\n                    return !((value_ - static_cast<const TExpression *>(&expr)->value_).isMuchSmallerThan(1e-6));\n                }\n\n                /**\n                 * @brief Checks if this expression is not equal to \\expr.\n                 *\n                 * @details This specialization deals with all other cases.\n                 *\n                 * @tparam TExpression Type of the other expression.\n                 *\n                 * @param expr Expression to check inequality with.\n                 *\n                 * @return True.\n                 */\n                template<typename TExpression>\n                typename std::enable_if<!std::is_same<TExpression, type>::value, bool>::type\n                operator!=(const SetExpression<TExpression> &expr) const\n                {\n                    return true;\n                }\n\n                /**\n                 * @brief Creates a union between this expression and another SetExpression.\n                 *\n                 * @tparam TExpression Type of the other expression.\n                 *\n                 * @param expr Expression to create a union with.\n                 *\n                 * @return Union.\n                 */\n                template<typename TExpression>\n                SetUnion<type, TExpression> unionize(const SetExpression<TExpression> &expr)\n                {\n                    return SetUnion<type, TExpression>(*this, *static_cast<const TExpression *>(&expr));\n                }\n\n                /**\n                 * @brief Checks if this expression is a subset of \\c expr.\n                 *\n                 * @tparam TExpression Type of the other expression.\n                 *\n                 * @param expr Expression to check inclusion on.\n                 *\n                 * @return True if this expression is a subset of \\c expr, false otherwise.\n                 */\n                template<typename TExpression>\n                bool isSubset(const SetExpression<TExpression> &expr)\n                {\n                    return static_cast<const TExpression *>(&expr)->contains(*this);\n                }\n\n                /**\n                 * @brief Checks if this expression is a superset of \\c expr.\n                 *\n                 * @tparam TExpression Type of the other expression.\n                 *\n                 * @param expr Expression to check subsumption on.\n                 *\n                 * @return True if this expression is a superset of \\c expr, false otherwise.\n                 */\n                template<typename TExpression>\n                bool isSuperset(const SetExpression<TExpression> &expr)\n                {\n                    return contains(expr);\n                }\n\n                /**\n                 * @brief Returns true if the expression is the empty set.\n                 *\n                 * @note This always returns false, since a singleton always contains one element.\n                 *\n                 * @return False.\n                 */\n                bool isEmpty() const\n                {\n                    return false;\n                }\n\n                /**\n                 * @brief Computes the relative complement of this expression and \\c expr.\n                 *\n                 * @details The syntax is as follows:\n                 * \\code\n                 * // A \\ B\n                 * A.relComplement(B);\n                 * \\endcode\n                 *\n                 * @tparam TExpression Type of the other expression.\n                 *\n                 * @param expr Expression to take relative complement with.\n                 *\n                 * @return Relative complement.\n                 */\n                template<typename TExpression>\n                SetComplement<type, TExpression> relComplement(const SetExpression<TExpression> &expr)\n                {\n                    return SetComplement<type, TExpression>(*this, *static_cast<const TExpression *>(&expr),\n                                                            isSubset(expr));\n                }\n\n                /**\n                 * @brief Returns signed distance to \\c p.\n                 *\n                 * @tparam TDerived Derived MatrixBase class.\n                 *\n                 * @param p A point.\n                 *\n                 * @return Signed distance.\n                 */\n                template<typename TDerived>\n                double sdf(Eigen::MatrixBase<TDerived> &p) const\n                {\n                    p.resize(dimension());\n                    return (value_ - p).norm();\n                }\n\n            protected:\n                TDValue value_; //! Singleton value.\n            };\n        }\n    }\n}\n\n#endif //LODESTAR_SINGLETON_HPP\n", "meta": {"hexsha": "6764a70692af6d476de67d9f85a22fb279be470e", "size": 13459, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/primitives/sets/Singleton.hpp", "max_stars_repo_name": "helkebir/Lodestar", "max_stars_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T14:08:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T22:15:31.000Z", "max_issues_repo_path": "Lodestar/primitives/sets/Singleton.hpp", "max_issues_repo_name": "helkebir/Lodestar", "max_issues_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T15:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T17:43:20.000Z", "max_forks_repo_path": "Lodestar/primitives/sets/Singleton.hpp", "max_forks_repo_name": "helkebir/Lodestar", "max_forks_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T03:15:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T03:15:23.000Z", "avg_line_length": 39.4692082111, "max_line_length": 119, "alphanum_fraction": 0.4695742626, "num_tokens": 2336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4497094064867749}}
{"text": "//          Copyright Erik Lundin 2016.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <iomanip>\n#include <cstdlib>\n#include <cstring>\n#include <vector>\n#include <boost/program_options.hpp>\n\n#include \"gausskruger.h\"\n\nusing namespace gausskruger;\nnamespace po = boost::program_options;\n\n#define EXE_NAME \"gausskruger\"\n\nclass ParameterProjection : public Projection\n{\npublic:\n    ParameterProjection(double flattening, double equatorialRadius, double centralMeridian,\n            double scale, double falseNorthing, double falseEasting) :\n        mFlattening(flattening),\n        mEquatorialRadius(equatorialRadius),\n        mCentralMeridian(centralMeridian),\n        mScale(scale),\n        mFalseNorthing(falseNorthing),\n        mFalseEasting(falseEasting) {}\n    double flattening() { return mFlattening; }\n    double equatorialRadius() { return mEquatorialRadius; }\n    double centralMeridian() { return mCentralMeridian; }\n    double scale() { return mScale; }\n    double falseNorthing() { return mFalseNorthing; }\n    double falseEasting() { return mFalseEasting; }\nprivate:\n    double mFlattening;\n    double mEquatorialRadius;\n    double mCentralMeridian;\n    double mScale;\n    double mFalseNorthing;\n    double mFalseEasting;\n};\n\nint main(int argc, char *argv[])\n{\n    double inverseFlattening;\n    double equatorialRadius;\n    double centralMeridian;\n    double scale;\n    double falseNorthing;\n    double falseEasting;\n    std::vector<double> coords;\n    int nDecimals;\n\n    try {\n        // Projection parameters\n        po::options_description projection_parameters(\"Projection parameters (mandatory)\");\n        projection_parameters.add_options()\n                (\"invflattening,i\", po::value<double>(&inverseFlattening),\n                        \"inverse flattening of the ellipsoid\")\n                (\"radius,a\", po::value<double>(&equatorialRadius),\n                        \"equatorial radius, a.k.a. semi-major axis of the ellipsoid\")\n                (\"meridian,m\", po::value<double>(&centralMeridian),\n                        \"longitude of the central meridian\")\n                (\"scale,s\", po::value<double>(&scale),\n                        \"scale factor along the central meridian\")\n                (\"falsenorthing,n\", po::value<double>(&falseNorthing),\n                        \"false northing\")\n                (\"falseeasting,e\", po::value<double>(&falseEasting),\n                        \"false easting\")\n                ;\n\n        // Options\n        po::options_description options(\"Options\");\n        options.add_options()\n                (\"help,h\", \"print this help\")\n                (\"decimals,d\", po::value<int>(&nDecimals)->default_value(3), \"number of decimals\")\n                (\"reverse,r\",\n                        \"reverse transformation (grid to geodetic), default is geodetic to grid\")\n                ;\n\n        // Positional parameters (input coordinates)\n        po::options_description hidden_parameters;\n        hidden_parameters.add_options()\n                (\"coords\", po::value<std::vector<double> >(&coords))\n                ;\n        po::positional_options_description positional_parameters;\n        positional_parameters.add(\"coords\", 2);\n\n        // Store the parameters\n        po::options_description all_parameters;\n        all_parameters.add(options).add(projection_parameters).add(hidden_parameters);\n        po::variables_map vm;\n        po::store(po::command_line_parser(argc, argv).options(all_parameters).positional(positional_parameters).run(), vm);\n        po::notify(vm);\n\n        // Print help (if requested or no other options is given)\n        po::options_description visible_parameters;\n        visible_parameters.add(projection_parameters).add(options);\n        if (argc == 1 || vm.count(\"help\")) {\n            std::cout << \"Usage: \" << EXE_NAME << \" <projection> [options] latitude longitude\\n\"\n                      << \"       \" << EXE_NAME << \" <projection> [options] -r northing easting\\n\"\n                      << visible_parameters << std::endl;\n            return 1;\n        }\n\n        // Check for all mandatory parameters\n        if (!(vm.count(\"invflattening\") && vm.count(\"radius\") && vm.count(\"meridian\") && vm.count(\"scale\")\n                && vm.count(\"falsenorthing\") && vm.count(\"falseeasting\"))) {\n            std::cout << \"Missing mandatory projection parameter(s)\" << std::endl;\n            return 2;\n        }\n        if (coords.size() != 2) {\n            std::cerr << \"Exactly two coordinate values have to be entered\" << std::endl;\n            return 3;\n        }\n\n        // Set number of decimals in output\n        std::cout.setf(std::ios::fixed);\n        std::cout.precision(nDecimals);\n\n        // Do the actual transformation\n        ParameterProjection projection(1 / inverseFlattening, equatorialRadius,\n                centralMeridian, scale, falseNorthing, falseEasting);\n        if (vm.count(\"reverse\")) {\n            double lat, lon;\n            projection.gridToGeodetic(coords.at(0), coords.at(1), lat, lon);\n            std::cout << std::fixed << \"Latitude: \" << lat << \"\\nLongitude: \" << lon << std::endl;\n        } else {\n            double northing, easting;\n            projection.geodeticToGrid(coords.at(0), coords.at(1), northing, easting);\n            std::cout << std::fixed << \"Northing: \" << northing << \"\\nEasting: \" << easting << std::endl;\n        }\n    } catch (std::exception& e) {\n        std::cerr << \"Error: \" << e.what() << std::endl;\n        return 4;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "d3f367760a075458c95dfbee97cf31740ad1421a", "size": 5643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gausskruger_cli.cpp", "max_stars_repo_name": "f03el/gauss-kruger-cpp", "max_stars_repo_head_hexsha": "961236101d9d2e6feb5a48c2d8387def5bf78f01", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-02-19T08:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-08T04:59:34.000Z", "max_issues_repo_path": "gausskruger_cli.cpp", "max_issues_repo_name": "f03el/gauss-kruger-cpp", "max_issues_repo_head_hexsha": "961236101d9d2e6feb5a48c2d8387def5bf78f01", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gausskruger_cli.cpp", "max_forks_repo_name": "f03el/gauss-kruger-cpp", "max_forks_repo_head_hexsha": "961236101d9d2e6feb5a48c2d8387def5bf78f01", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-02-05T16:33:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-21T00:55:28.000Z", "avg_line_length": 39.4615384615, "max_line_length": 123, "alphanum_fraction": 0.6037568669, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4496652533861533}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2011 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/**\n * \\file\n * \\author Felix Lehmann\n */\n\n#ifndef ICC_0_PRECOND_HH\n#define ICC_0_PRECOND_HH\n\n#include <memory>\n#include <vector>\n\n#include <boost/fusion/include/at_c.hpp>\n\n#include \"dune/grid/common/grid.hh\"\n#include \"dune/istl/matrix.hh\"\n#include \"dune/istl/bcrsmatrix.hh\"\n#include \"dune/common/fmatrix.hh\"\n#include \"dune/common/fvector.hh\"\n#include \"dune/common/iteratorfacades.hh\"\n#include \"dune/istl/matrixindexset.hh\"\n\n#include \"dune/istl/preconditioners.hh\"\n\nnamespace Kaskade\n{\n\n/**\n * \\ingroup linalg\n * \n * Incomplete Cholesky factorization by algorithm from book \"Matrix Computations\" by Gene Golub & Charles van Loan\n *\n * algorith will create approximate cholesky factorization L by only using the sparsity pattern of A\n *\n * we will only touch the lower triangle of the matrix\n *\n * interface copied from iluprecond.hh\n *\n * iccprecond.hh (using TAUCS Incomplete Cholesky Decomposition) does the same (even faster),\n * if we set its droptolerance parameter sufficiently large\n *\n */\n\ntemplate <class Op>\nclass ICC_0Preconditioner: public Dune::Preconditioner<typename Op::Range, typename Op::Range>\n{\npublic:\n  typedef typename Op::Domain Domain;\n  typedef typename Op::Range Range;\n  typedef typename Op::Scalar Scalar;\n\nprivate:\n  typedef Dune::FieldMatrix<Scalar,1,1> BlockType;\n  typedef Dune::BlockVector<Dune::FieldVector<Scalar,1> > CoeffVector ;\n  typedef Dune::BCRSMatrix<BlockType> BCRS_Matrix;\n  typedef typename BCRS_Matrix::ConstColIterator ColIter;\n  \n    BCRS_Matrix mL;\n    std::vector<std::vector<int> > mEntries;\n    // int const mChoice;\n  public:\n    static int const category = Dune::SolverCategory::sequential;\n    ICC_0Preconditioner( Op& op );\n    void pre (Domain&, Range&) {}\n    void apply (Domain& x, Range const& y);\n    void post (Domain&) {}\n};\n\n\ntemplate <class Op>\nICC_0Preconditioner<Op>::ICC_0Preconditioner(Op& op)\n{\n  std::unique_ptr<BCRS_Matrix> mA = op.template getPointer<BCRS_Matrix>();\n  int N = (*mA).N();\n  // create kind of column iterator for BCRS\n  // and simultaneously read out the sparsity pattern of mA\n  mEntries.resize(N);\n  for(int i=0;i<N;i++)\n    for (ColIter cI=(*mA)[i].begin(); cI!=(*mA)[i].end() && cI.index()<i; ++cI)\n      mEntries[cI.index()].push_back(i);\n  \n  // backward substitution in ICC_0Preconditioner::apply() with BCRSMatrix mL^T is not\n  // efficiently applicable, therefore create two BCRSMatrices mL and mLT := mL^T\n  // set up sparsity pattern of lower triangle of mA (upper triangle of mA^T) for mL (mLT)\n  Dune::MatrixIndexSet sparsityPattern_mL(N,N);\n  for (int i=0; i<N; ++i)\n    for (ColIter cI=(*mA)[i].begin(); cI!=(*mA)[i].end() && cI.index()<=i; ++cI)\n      sparsityPattern_mL.add(i,cI.index() );\n  \n  sparsityPattern_mL.exportIdx( mL );\n  for(int i=0;i<N;++i)\n    for (ColIter cI=mL[i].begin(); cI!=mL[i].end(); ++cI)\n      mL[i][cI.index()] = (*mA)[i][cI.index()];\n  //find factorization mL of mA\n  double tmp;\n  for(int k=0;k<N;k++)\n  {\n    mL[k][k] = sqrt(mL[k][k]); \n    for(std::vector<int>::iterator it = mEntries[k].begin(); it!=mEntries[k].end(); it++)\n      mL[*it][k] /= mL[k][k];\n    for(std::vector<int>::iterator it = mEntries[k].begin(); it!=mEntries[k].end(); it++)\n    {\n      tmp = mL[*it][k];\n      mL[*it][*it] -= (mL[*it][k])*(mL[*it][k]); // \"mEntries\" contains not diagonal indices\n      for(std::vector<int>::iterator it2 = mEntries[*it].begin(); it2!=mEntries[*it].end(); it2++)\n        if( mL.exists(*it2,k) )\n\t  mL[*it2][*it] -= mL[*it2][k]*tmp;\n    }\n  }  \n}\n\ntemplate <class Op>\nvoid ICC_0Preconditioner<Op>::apply(Domain& x, Range const& b)\n{\n  int N = x.dim();\n  \n  CoeffVector &sol = boost::fusion::at_c<0>(x.data);\n  CoeffVector const &rhs = boost::fusion::at_c<0>(b.data);\n  // for forward substitution\n  CoeffVector forward(N); forward = 0;\n  \n  double tmp;\n  // forward substitution\n  for(int i=0;i<N;i++)\n  {\n    tmp = rhs[i];\n    for (ColIter cI = mL[i].begin(); cI != mL[i].end(); ++cI)\n      if( cI.index()<i )\n\ttmp -= mL[i][cI.index()]*forward[cI.index()];\n    forward[i] = tmp/mL[i][i];\n  }\n  // backward substitution\n  for(int i = N-1;i>=0;i--)\n  {\n    tmp = forward[i];\n    for(std::vector<int>::iterator it = mEntries[i].begin();it!=mEntries[i].end();it++)\n      tmp -= mL[*it][i]*sol[*it];\n    sol[i] = tmp/mL[i][i]; \n  }\n}\n}  // namespace Kaskade\n#endif\n     \n", "meta": {"hexsha": "822c9c5ae2891d292c5e2da30133cec6e005a5f0", "size": 5188, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/linalg/icc0precond.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/linalg/icc0precond.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/linalg/icc0precond.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 33.4709677419, "max_line_length": 114, "alphanum_fraction": 0.5784502699, "num_tokens": 1509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4496072898748402}}
{"text": "#ifndef __BOOST_GEOMETRY_DISSOLVE_H__\n#define __BOOST_GEOMETRY_DISSOLVE_H__\n\n/*\n * ----------------------------------------------------------------------------\n * \"THE BEER-WARE LICENSE\" (Revision 42):\n * Wouter van Kleunen wrote this file.  As long as you retain this notice you\n * can do whatever you want with this stuff. If we meet some day, and you think\n * this stuff is worth it, you can buy me a beer in return. \n * ----------------------------------------------------------------------------\n */\n\n#include <vector>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/multi_polygon.hpp>\n#include <boost/geometry/index/rtree.hpp>\n#include <boost/function_output_iterator.hpp>\n\nnamespace geometry {\n\nnamespace impl {\n\ntemplate<typename C, typename T>\nstatic inline void result_combine(C &result, T &&new_element)\n{\n    result.push_back(new_element);\n\n   \tfor(std::size_t i = 0; i < result.size() - 1; ) {\n        if(!boost::geometry::intersects(result[i], result.back())) {\n            ++i;\n            continue;\n        }\n\n        std::vector<T> union_result;\n        boost::geometry::union_(result[i], result.back(), union_result);\n\n        if(union_result.size() != 1) {\n\t\t\t++i;\n\t\t\tcontinue;\n\t\t}\n\n       \tresult.back() = std::move(union_result[0]);\n       \tresult.erase(result.begin() + i);\n    } \n}\n\nstruct pseudo_vertice_key\n{\n    std::size_t index_1;\n    double scale;\n    std::size_t index_2;\n    bool reroute;\n    \n    pseudo_vertice_key(std::size_t index_1 = 0, std::size_t index_2 = 0, double scale = 0.0, bool reroute = false)\n        : index_1(index_1), scale(scale), index_2(index_2), reroute(reroute)\n    { } \n};\n\nstruct compare_pseudo_vertice_key\n{\n    bool operator()(pseudo_vertice_key const &a, pseudo_vertice_key const &b) const {\n        if(a.index_1 < b.index_1) return true;\n        if(a.index_1 > b.index_1) return false;\n        if(a.scale < b.scale) return true;\n        if(a.scale > b.scale) return false;\n        if(a.index_2 > b.index_2) return true;\n        if(a.index_2 < b.index_2) return false;\n        if(a.reroute && !b.reroute) return true;\n        if(!a.reroute && b.reroute) return false;\n\t\treturn false;\n    }\n};\n\ntemplate<typename point_t = boost::geometry::model::d2::point_xy<double>>\nstruct pseudo_vertice\n{\n    point_t p;\n    pseudo_vertice_key link;\n    \n    pseudo_vertice(point_t p, pseudo_vertice_key link = pseudo_vertice_key())   \n        : p(p), link(link)\n    { }        \n};\n\ntemplate<\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename ring_t = boost::geometry::model::ring<point_t>\n\t>\nstatic inline void dissolve_find_intersections(\n\t\t\tring_t const &ring,\n\t\t\tstd::map<pseudo_vertice_key, pseudo_vertice<point_t>, compare_pseudo_vertice_key> &pseudo_vertices,\n    \t\tstd::set<pseudo_vertice_key, compare_pseudo_vertice_key> &start_keys)\n{\n\tif(ring.empty()) return;\n\n\tboost::geometry::index::rtree<std::pair< boost::geometry::model::segment<point_t>, std::size_t >, boost::geometry::index::quadratic<16>> index;\n\n\t// Generate all by-pass intersections in the graph\n\t// Generate a list of all by-pass intersections\n    pseudo_vertices.emplace(pseudo_vertice_key(ring.size() - 1, ring.size() - 1, 0.0), ring.back());       \n    for(std::size_t i = ring.size() - 1; i--; )\n    {\n        pseudo_vertices.emplace(pseudo_vertice_key(i, i, 0.0), ring[i]);       \n\t\tboost::geometry::model::segment<point_t> line_1(ring[i], ring[i + 1]);\n\n\t\tboost::geometry::index::query(\n\t\t\t\tindex, boost::geometry::index::intersects(line_1), \n\t\t\t\tboost::make_function_output_iterator([&](std::pair< boost::geometry::model::segment<point_t>, std::size_t > const &iter) {\n\n\t\t\tauto const &line_2 = iter.first;\n\t\t\tauto j = iter.second;\n\t\t\t\n\t\t\tstd::vector<point_t> output;\n\t\t\tboost::geometry::intersection(line_1, line_2, output);\n\n\t\t\tfor(auto const &p: output) {\n\t\t\t\tdouble scale_1 = boost::geometry::comparable_distance(p, ring[i]) / boost::geometry::comparable_distance(ring[i + 1], ring[i]);\n\t\t\t\tdouble scale_2 = boost::geometry::comparable_distance(p, ring[j]) / boost::geometry::comparable_distance(ring[j + 1], ring[j]);\n\t\t\t\tif(scale_1 < 1.0 && scale_2 < 1.0) {\n\t\t\t\t\tpseudo_vertice_key key_j(j, i, scale_2);\n\t\t\t\t\tpseudo_vertices.emplace(pseudo_vertice_key(i, j, scale_1, true), pseudo_vertice<point_t>(p, key_j));\n\t\t\t\t\tpseudo_vertices.emplace(key_j, p);\n\t\t\t\t\tstart_keys.insert(key_j);\n\n\t\t\t\t\tpseudo_vertice_key key_i(i, j, scale_1);\n\t\t\t\t\tpseudo_vertices.emplace(pseudo_vertice_key(j, i, scale_2, true), pseudo_vertice<point_t>(p, key_i));\n\t\t\t\t\tpseudo_vertices.emplace(key_i, p);\n\t\t\t\t\tstart_keys.insert(key_i);\n\t\t\t\t}\n\t\t\t}          \n\t\t}));\n\n\t\tindex.insert(std::make_pair(boost::geometry::model::segment<point_t>(ring[i], ring[i+1]), i));\n    }\n}\n\n// Remove invalid points (NaN) from ring\ntemplate<\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename ring_t = boost::geometry::model::ring<point_t>\n\t>\nstatic inline void correct_invalid(ring_t &ring)\n{\n\tfor(auto i = ring.begin(); i != ring.end(); ) {\n\t\tif(!boost::geometry::is_valid(*i))\n\t\t\ti = ring.erase(i);\n\t\telse\n\t\t\t++i;\n\t}\t\n}\n\n// Correct orientation of ring\ntemplate<\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename ring_t = boost::geometry::model::ring<point_t>\n\t>\nstatic inline double correct_orientation(ring_t &ring, boost::geometry::order_selector order)\n{\n\tauto area = boost::geometry::area(ring);\n\tbool should_reverse =\n\t\t(order == boost::geometry::clockwise && area < 0) ||\n\t\t(order == boost::geometry::counterclockwise && area > 0);\n\n\tif(should_reverse) {\n\t\tstd::reverse(ring.begin(), ring.end());\n\t} \n\n\treturn area;\n}\n\n// Close ring if not closed\ntemplate<\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename ring_t = boost::geometry::model::ring<point_t>\n\t>\nstatic inline void correct_close(ring_t &ring)\n{\n\t// Close ring if not closed\n\tif(!ring.empty() && !boost::geometry::equals(ring.back(), ring.front()))\n\t\tring.push_back(ring.front());\n\n}\n\ntemplate<\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename ring_t = boost::geometry::model::ring<point_t>\n\t>\nstatic inline std::vector<ring_t> dissolve_generate_rings(\n\t\t\tstd::map<pseudo_vertice_key, pseudo_vertice<point_t>, compare_pseudo_vertice_key> &pseudo_vertices,\n    \t\tstd::set<pseudo_vertice_key, compare_pseudo_vertice_key> &start_keys, \n\t\t\tboost::geometry::order_selector order, double remove_spike_min_area = 0.0)\n{\n\tstd::vector<ring_t> result;\n\n\t// Generate all polygons by tracing all the intersections\n\t// Perform union to combine all polygons into single polygon again\n    while(!start_keys.empty()) {    \n\t\tring_t new_ring;\n        \n\t\t// Store point in generated polygon\n\t\tauto push_point = [&new_ring](auto const &p) { \n            if(new_ring.empty() || boost::geometry::comparable_distance(new_ring.back(), p) > 0)\n                new_ring.push_back(p);\n\t\t};\n\n\t\tauto is_closed = [](ring_t &ring) {\n\t\t\tif(ring.size() < 2) return false;\n\t\t\tfor(std::size_t i = 0; i < ring.size() - 1; ++i) {\n\t\t\t\tif(boost::geometry::comparable_distance(ring[i], ring.back()) == 0) {\n\t\t\t\t\tring.erase(ring.begin(), ring.begin() + i);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false;\n\t\t};\n\n        auto start_iter = pseudo_vertices.find(*start_keys.begin());\n        auto i = start_iter;\n    \n        do {\n            auto const &key = i->first;\n            auto const &value = i->second;\n        \n\t\t\t// Store the point in output polygon\n\t\t\tpush_point(value.p);\n            \n            start_keys.erase(key);\n            if(key.reroute) {\n\t\t\t\t// Follow by-pass\n                i = pseudo_vertices.find(value.link);\n\t\t\t} else {\n\t\t\t\t// Continu following original polygon\n                ++i;\n                if(i == pseudo_vertices.end())\n                    i = pseudo_vertices.begin();\n            }\n\n\t\t\t// Repeat until back at starting point\n       \t} while(!is_closed(new_ring));\n\n\t\t// Combine with already generated polygons\n\t\tauto area = boost::geometry::area(new_ring);\n\t\tif(std::abs(area) > remove_spike_min_area) {\n\t    \tresult.push_back(std::move(new_ring));\n\t\t}\n   \t}\n\n    return result;\n}\n\ntemplate<\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename polygon_t = boost::geometry::model::polygon<point_t>,\n\ttypename ring_t = boost::geometry::model::ring<point_t>,\n\ttypename multi_polygon_t = boost::geometry::model::multi_polygon<polygon_t>\n\t>\nstatic inline std::vector<ring_t> correct(ring_t const &ring, boost::geometry::order_selector order, double remove_spike_min_area = 0.0)\n{\n\tconstexpr std::size_t min_nodes = 3;\n\tif(ring.size() < min_nodes)\n\t\treturn std::vector<ring_t>();\n\n    std::map<pseudo_vertice_key, pseudo_vertice<point_t>, compare_pseudo_vertice_key> pseudo_vertices;    \n    std::set<pseudo_vertice_key, compare_pseudo_vertice_key> start_keys;\n\n\tring_t new_ring = ring;\n\n\t// Remove invalid coordinates\n\tcorrect_invalid(new_ring);\n\n\t// Close ring\n\tcorrect_close(new_ring);\n\n\t// Correct orientation\n\tcorrect_orientation(new_ring, order);\n\n\t// Detect self-intersection points\n\tdissolve_find_intersections(new_ring, pseudo_vertices, start_keys);\n\n\tif(start_keys.empty()) {\n\t\tif(std::abs(boost::geometry::area(new_ring)) > remove_spike_min_area) \n\t\t\treturn { new_ring };\n\t\telse\n\t\t\treturn { };\n\t}\n\n\treturn dissolve_generate_rings(pseudo_vertices, start_keys, order, remove_spike_min_area);\n}\n\ntemplate<\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename polygon_t = boost::geometry::model::polygon<point_t>,\n\ttypename multi_polygon_t = boost::geometry::model::multi_polygon<polygon_t>\n\t>\nstruct combine_non_zero_winding\n{\n\tinline void operator()(multi_polygon_t &combined_outers, multi_polygon_t &combined_inners, polygon_t &poly) \n\t{\n\t\tif(boost::geometry::area(poly) > 0)\n\t\t\tresult_combine(combined_outers, std::move(poly));\n\t\telse {\n\t\t\tstd::reverse(poly.outer().begin(), poly.outer().end());\n\t\t\tresult_combine(combined_inners, std::move(poly));\n\t\t}\n\t}\n};\n\ntemplate<\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename polygon_t = boost::geometry::model::polygon<point_t>,\n\ttypename multi_polygon_t = boost::geometry::model::multi_polygon<polygon_t>\n\t>\nstruct combine_odd_even\n{\n\tinline void operator()(multi_polygon_t &combined_outers, multi_polygon_t &combined_inners, polygon_t &poly) \n\t{\n\t\tif(boost::geometry::area(poly) < 0)\n\t\t\tstd::reverse(poly.outer().begin(), poly.outer().end());\n\n\t\tmulti_polygon_t result;\n\t\tboost::geometry::sym_difference(combined_outers, poly, result);\n\t\tcombined_outers = std::move(result);\n\t}\n};\n \ntemplate<\n\ttypename combine_function_t,\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename polygon_t = boost::geometry::model::polygon<point_t>,\n\ttypename ring_t = boost::geometry::model::ring<point_t>,\n\ttypename multi_polygon_t = boost::geometry::model::multi_polygon<polygon_t>\n\t>\nstatic inline void correct(polygon_t const &input, multi_polygon_t &output, double remove_spike_min_area, combine_function_t combine)\n{\n\tauto order = boost::geometry::point_order<polygon_t>::value;\n\tauto outer_rings = correct(input.outer(), order, remove_spike_min_area);\n\n\t// Calculate all outers and combine them if possible\n\tmulti_polygon_t combined_outers;\n\tmulti_polygon_t combined_inners;\n\n\tfor(auto &ring: outer_rings) {\n\t\tpolygon_t poly;\n\t\tpoly.outer() = std::move(ring);\n\t\tcombine(combined_outers, combined_inners, poly);\n\t}\n\n\t// Calculate all inners and combine them if possible\n\tfor(auto const &ring: input.inners()) {\n\t\tpolygon_t poly;\n\t\tpoly.outer() = std::move(ring);\n\n\t\tmulti_polygon_t new_inners;\n\t\tcorrect(poly, new_inners, remove_spike_min_area, combine);\n\n\t\tfor(auto &poly: new_inners) {\n\t\t\tresult_combine(combined_inners, std::move(poly));\n\t\t} \n\t}\n\n\t// Cut out all inners from all the outers\n\tboost::geometry::difference(combined_outers, combined_inners, output);\n}\n\ntemplate<\n\ttypename combine_function_t,\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename polygon_t = boost::geometry::model::polygon<point_t>,\n\ttypename ring_t = boost::geometry::model::ring<point_t>,\n\ttypename multi_polygon_t = boost::geometry::model::multi_polygon<polygon_t>\n\t>\nstatic inline void correct(multi_polygon_t const &input, multi_polygon_t &output, double remove_spike_min_area, combine_function_t combine)\n{\n\tfor(auto const &polygon: input)\n\t{\n\t\tmulti_polygon_t new_polygons;\n\t\tcorrect(polygon, new_polygons, remove_spike_min_area, combine);\n\n\t\tfor(auto &new_polygon: new_polygons) \n\t\t\tresult_combine(output, std::move(new_polygon));\n\t}\n}\n\n}\n\ntemplate<\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename polygon_t = boost::geometry::model::polygon<point_t>,\n\ttypename multi_polygon_t = boost::geometry::model::multi_polygon<polygon_t>\n\t>\nstatic inline void correct(polygon_t const &input, multi_polygon_t &output, double remove_spike_min_area = 0.0)\n{\n\timpl::correct(input, output, remove_spike_min_area, impl::combine_non_zero_winding<point_t, polygon_t, multi_polygon_t>());\n}\n\ntemplate<\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename polygon_t = boost::geometry::model::polygon<point_t>,\n\ttypename multi_polygon_t = boost::geometry::model::multi_polygon<polygon_t>\n\t>\nstatic inline void correct_odd_even(polygon_t const &input, multi_polygon_t &output, double remove_spike_min_area = 0.0)\n{\n\timpl::correct(input, output, remove_spike_min_area, impl::combine_odd_even<point_t, polygon_t, multi_polygon_t>());\n}\n\n\ntemplate<\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename polygon_t = boost::geometry::model::polygon<point_t>,\n\ttypename ring_t = boost::geometry::model::ring<point_t>,\n\ttypename multi_polygon_t = boost::geometry::model::multi_polygon<polygon_t>\n\t>\nstatic inline void correct(multi_polygon_t const &input, multi_polygon_t &output, double remove_spike_min_area = 0.0)\n{\n\timpl::correct(input, output, remove_spike_min_area, impl::combine_non_zero_winding<point_t, polygon_t, multi_polygon_t>());\n}\n\ntemplate<\n\ttypename point_t = boost::geometry::model::d2::point_xy<double>, \n\ttypename polygon_t = boost::geometry::model::polygon<point_t>,\n\ttypename ring_t = boost::geometry::model::ring<point_t>,\n\ttypename multi_polygon_t = boost::geometry::model::multi_polygon<polygon_t>\n\t>\nstatic inline void correct_odd_even(multi_polygon_t const &input, multi_polygon_t &output, double remove_spike_min_area = 0.0)\n{\n\timpl::correct(input, output, remove_spike_min_area, impl::combine_odd_even<point_t, polygon_t, multi_polygon_t>());\n}\n\n}\n\n#endif\n", "meta": {"hexsha": "7adb5d34e6d1d0274fba8c8784ce8efc7b54fc0d", "size": 14588, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/geometry/correct.hpp", "max_stars_repo_name": "typebrook/tilemaker", "max_stars_repo_head_hexsha": "a8185978a0fd53a5c61404a3ae0b16ef119e1413", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 815.0, "max_stars_repo_stars_event_min_datetime": "2015-06-29T13:39:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:35:53.000Z", "max_issues_repo_path": "include/geometry/correct.hpp", "max_issues_repo_name": "typebrook/tilemaker", "max_issues_repo_head_hexsha": "a8185978a0fd53a5c61404a3ae0b16ef119e1413", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 341.0, "max_issues_repo_issues_event_min_datetime": "2015-06-29T01:20:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:44:52.000Z", "max_forks_repo_path": "include/geometry/correct.hpp", "max_forks_repo_name": "typebrook/tilemaker", "max_forks_repo_head_hexsha": "a8185978a0fd53a5c61404a3ae0b16ef119e1413", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 165.0, "max_forks_repo_forks_event_min_datetime": "2015-06-29T07:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T12:38:06.000Z", "avg_line_length": 33.5356321839, "max_line_length": 144, "alphanum_fraction": 0.6989306279, "num_tokens": 3844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4496072898748402}}
{"text": "﻿#include \"distribution_mixture_models.hxx\"\n\n#include <boost/range/combine.hpp>\n#include <iomanip>\n#include <math.h>\n\n\nnamespace vmf_fitting\n{\n\ntemplate<int N_>\nvoid ExpApproximation(Eigen::Array<float, N_, 1> &vals)\n{\n  // From http://spfrnd.de/posts/2018-03-10-fast-exponential.html\n  // It is also implemented in the supplemental code of the Vorba paper about gaussian mixtures for path guiding.\n  // Eigen also does it this way by default but with more precision.\n\n  static_assert(std::numeric_limits<float>::is_iec559);\n  static_assert(sizeof(float) == sizeof(std::uint32_t));\n  constexpr int N = N_;\n  constexpr float log2_e = 1.4426950408889634f;\n  // This polynomial gives less than 0.3% relative error.\n  constexpr float poly_coeffs[3] = { 0.34271437f, 0.6496069f , 1.f + 0.0036554f };\n  constexpr uint32_t exp_mask = 255u << 23u;\n\n  using FloatVals = Eigen::Array<float, N, 1>;\n  using IntVals = Eigen::Array<int, N, 1>;\n\n  vals *= log2_e;\n\n  // Notes:\n  //  floor() needs some fancy instructions sets to be vectorized. Compilation with -march=core2 is not enough. corei7-avx works.\n  //  Apparently my CPU has it\n  //  https://ark.intel.com/content/www/us/en/ark/products/52214/intel-core-i7-2600k-processor-8m-cache-up-to-3-80-ghz.html\n  //  See also the Eigen manual https://eigen.tuxfamily.org/dox/group__CoeffwiseMathFunctions.html\n  auto floored = vals.floor().eval();\n  const IntVals xi = floored.template cast<int>();\n  const FloatVals xf = vals - floored;\n  \n  vals = xf*(xf*poly_coeffs[0] + poly_coeffs[1]) + poly_coeffs[2];\n\n  // memcpy does actually copy stuff :-(\n  //std::uint32_t int_view[N];\n  //std::memcpy(int_view, vals.data(), N*sizeof(float));\n\n  // This is UB afaik. But every reasonable compiler should do the right thing ...\n  std::uint32_t* int_view = reinterpret_cast<uint32_t*>(vals.data());\n\n  // Should be auto-vectorized. Clang 9 in compiler explorer can do it!\n  for (int i=0; i<N; ++i)\n  {\n      int_view[i] = (int_view[i] & ~exp_mask) | ((((xi[i] + 127)) << 23) & exp_mask);\n  }\n\n  //std::memcpy(vals.data(), int_view, N*sizeof(float));\n}\n\n\nfloat ExpApproximation(float x)\n{\n  // Should compile to ca 10 instructions.\n  // And it can be inlined in contrast to std::exp().\n  static_assert(std::numeric_limits<float>::is_iec559);\n  static_assert(sizeof(float) == sizeof(std::uint32_t));\n\n  constexpr float log2_e = 1.4426950408889634f;\n  constexpr float poly_coeffs[3] = { 0.34271437f, 0.6496069f , 1.f + 0.0036554f };\n  constexpr uint32_t exp_mask = 255u << 23u;\n\n  x *= log2_e;\n\n  const float floored = std::floor(x);\n  const int xi = int(floored);\n  const float xf = x - floored;\n\n  const float mantisse = xf*(xf*poly_coeffs[0] + poly_coeffs[1]) + poly_coeffs[2];\n\n  std::uint32_t int_view;\n  std::memcpy(&int_view, &mantisse, sizeof(float));\n\n  int_view = (int_view & ~exp_mask) | ((((xi + 127)) << 23) & exp_mask);\n\n  float result;\n  std::memcpy(&result, &int_view, sizeof(float));\n\n  return result;\n}\n\n\n\n\ntemplate<int N = 8>\ninline Eigen::Array<float, N, 1> ComponentPdfs(const VonMisesFischerMixture<N> & mixture, const Eigen::Vector3f & pos) noexcept\n{\n  const auto& k = mixture.concentrations;\n  assert((k >= K_THRESHOLD).all() && (k <= K_THRESHOLD_MAX).all());\n  auto t1 = (-2.f*k).eval();\n  ExpApproximation<N>(t1);\n  //assert(t1.isFinite().all());\n  const auto prefactors = (float(Pi)*2.f*(1.f - t1)).eval();\n  //assert((prefactors > -0.1f).all());\n  //assert((prefactors > 0.f).all());\n  auto t2 = (k*((mixture.means.matrix() * pos).array() - 1.f)).eval();\n  ExpApproximation<N>(t2);\n  //assert(t2.isFinite().all());\n  const auto result = (k / prefactors * t2).eval();\n  assert(result.isFinite().all() && (result >= 0.f).all());\n  return result;\n}\n\n\ntemplate<int N = 8>\nfloat Pdf(const VonMisesFischerMixture<N> & mixture, const Eigen::Vector3f & pos) noexcept\n{\n  const auto component_pdfs = ComponentPdfs(mixture, pos);\n  return (component_pdfs * mixture.weights).sum();\n}\n\n\nEigen::Vector3f Sample(const Eigen::Vector3f& mu, float k, float r1, float r2) noexcept\n{\n  assert (k >= K_THRESHOLD);\n  assert (k <= K_THRESHOLD_MAX);\n  const float vx = std::cos((float)(Pi*2.)*r1);\n  const float vy = std::sin((float)(Pi*2.)*r1);\n  // if (!std::isfinite(vx) || !std::isfinite(vy))\n  //   std::cerr << \"Oh noz vx or vy are non-finite! \" << vx << \", \" << vy << std::endl;\n  const float w = 1.f + std::log(r2 + (1.f - r2)*ExpApproximation(-2.f*k)) / k;\n  // if (!std::isfinite(w))\n  //   std::cerr << \"Oh noz w is not finite! \" << w << std::endl;\n  const float tmp = 1.f - w * w;\n  // if (tmp < 0.f)\n  //   std::cerr << \"Oh noz tmp is negative! \" << std::setprecision(std::numeric_limits<float>::digits10 + 1) << tmp << std::endl;\n  const float rho = std::sqrt(std::max(0.f, tmp));\n  // if (!std::isfinite(rho))\n  //   std::cerr << \"Oh noz rho is not finite! \" << rho << \", \" << w << std::endl;\n  Eigen::Vector3f x{\n    rho*vx, rho*vy, w\n  };\n  Eigen::Matrix3f frame = OrthogonalSystemZAligned(mu);\n  // if (!frame.array().isFinite().all())\n  //   std::cerr << \"Oh noz the frame is not finite! \" << frame << \", mu = \" << mu << std::endl;\n  return frame * x;\n}\n\n\ntemplate<int N = 8>\nEigen::Vector3f Sample(const VonMisesFischerMixture<N> & mixture, std::array<double, 3> rs) noexcept\n{\n  const int idx = TowerSampling<N>(mixture.weights.data(), (float)rs[0]);\n  return Sample(mixture.means.row(idx).matrix(), mixture.concentrations[idx], (float)rs[1], (float)rs[2]);\n}\n\n\ntemplate<int N>\nvoid InitializeForUnitSphere(VonMisesFischerMixture<N> & mixture)  noexcept\n{\n  assert (\"!Not implemented!\");\n}\n\n\ntemplate<>\nvoid InitializeForUnitSphere<2>(VonMisesFischerMixture<2> & mixture)  noexcept\n{\n  using MoVMF = VonMisesFischerMixture<2>;\n  mixture.means <<\n    -1., 0., 0.,\n     1., 0., 0.;\n  mixture.concentrations = MoVMF::ConcArray::Constant(0.1f);\n  mixture.weights = typename MoVMF::WeightArray(1.f / MoVMF::NUM_COMPONENTS);\n}\n\n\ntemplate<>\nvoid InitializeForUnitSphere<8>(VonMisesFischerMixture<8> & mixture)  noexcept\n{\n  using MoVMF = VonMisesFischerMixture<8>;\n    mixture.means <<\n      0.66778004,0.73539025,0.11519922,\n      -0.9836298,-0.008926501,0.1799797,\n      -0.14629413,-0.7809748,0.60718733,\n      0.49043104,0.04368747,-0.87038434,\n      -0.10088497,0.42765132,0.8982965,\n      -0.35999632,-0.6945797,-0.62286574,\n      -0.43178025,0.7588791,-0.48751223,\n      0.860208,-0.47938251,0.17388113;\n  mixture.concentrations = MoVMF::ConcArray::Constant(2.f);\n  mixture.weights = typename MoVMF::WeightArray(1.f / MoVMF::NUM_COMPONENTS);\n}\n\ntemplate<>\nvoid InitializeForUnitSphere<16>(VonMisesFischerMixture<16> & mixture)  noexcept\n{\n  using MoVMF = VonMisesFischerMixture<16>;\n  mixture.means <<\n    0.49468744,-0.1440351,-0.8570521,\n    0.36735174,-0.8573688,-0.36051556,\n    -0.40503788,-0.48854542,-0.772831,\n    -0.32770208,-0.12784185,0.9360917,\n    -0.46322507,-0.8861626,-0.011769729,\n    -0.933043,0.16280192,-0.32082137,\n    -0.4759586,0.8746706,-0.09173246,\n    -0.2931369,0.36415973,-0.8840013,\n    -0.9006278,-0.24284472,0.360411,\n    -0.32578856,0.650924,0.685682,\n    0.5459307,0.11810207,0.8294646,\n    0.9575066,0.22513846,-0.18026012,\n    0.84576833,-0.47598344,0.24107178,\n    0.47158864,0.8217275,0.31995004,\n    0.12246728,-0.77039504,0.6256942,\n    0.34670526,0.77106386,-0.5340936;\n    mixture.concentrations = MoVMF::ConcArray::Constant(5.f);  \n    mixture.weights = typename MoVMF::WeightArray(1.f / MoVMF::NUM_COMPONENTS);\n}\n\n\ntemplate<int N, int M>\nVonMisesFischerMixture<N*M> Product(const VonMisesFischerMixture<N> &m1, const VonMisesFischerMixture<M> &m2) noexcept\n{\n  static constexpr int NM = N*M;\n  VonMisesFischerMixture<NM> result;\n  for (int i=0; i<N; ++i)\n  {\n    result.means.block(i*M, 0, M, 3) = (m1.concentrations[i]*m1.means.row(i)).replicate(M,1) + (m2.means*m2.concentrations.replicate(1,3));\n  }\n  result.concentrations = result.means.matrix().rowwise().norm();\n  result.means.colwise() /= result.concentrations;\n\n  // Weights ...\n  const typename VonMisesFischerMixture<N>::WeightArray  exponentials1 = 1.f+incremental::eps - (-2.f*m1.concentrations    ).exp();\n  const typename VonMisesFischerMixture<M>::WeightArray  exponentials2 = 1.f+incremental::eps - (-2.f*m2.concentrations    ).exp();\n  const typename VonMisesFischerMixture<NM>::WeightArray exponentialsk = 1.f+incremental::eps - (-2.f*result.concentrations).exp();\n\n  for (int i=0; i<N; ++i)\n  {\n    for (int j=0; j<M; ++j)\n    {\n      const int k = i*M + j;\n      result.weights[k] = m1.concentrations[i]*m2.concentrations[j]*exponentialsk[k] / \n                          (2.f*PiFloat*result.concentrations[k]*exponentials1[i]*exponentials2[j] + incremental::eps);\n      result.weights[k] *= ExpApproximation(m1.concentrations[i]*(m1.means.row(i).matrix().dot(result.means.row(k).matrix())-1.f) + \n                                    m2.concentrations[j]*(m2.means.row(j).matrix().dot(result.means.row(k).matrix())-1.f));\n      result.weights[k] *= m1.weights[i] * m2.weights[j];\n    }\n  }\n\n  // Hack to avoid numerical problems ...\n  result.concentrations = result.concentrations.max(K_THRESHOLD).min(K_THRESHOLD_MAX).eval();\n  return result;\n}\n\n\ntemplate<int N>\nvoid Normalize(VonMisesFischerMixture<N> &mixture) noexcept\n{\n  const float wsum = mixture.weights.sum();\n  if (unlikely(wsum <= 0.f))\n  {\n    // Case may happen due to underflow in calculations with exponentials\n    mixture.weights.setConstant(1.f/N);\n  }\n  else\n  {\n    mixture.weights /= wsum;\n  }\n}\n\n\nnamespace incremental\n{\n\ntemplate<int N>\nvoid UpdateStatistics(VonMisesFischerMixture<N> &mixture, Data<N> &dta, const Params<N> &params, const Eigen::Vector3f &x, float weight) noexcept;\n\ntemplate<int N>\nvoid MaximizationStep(VonMisesFischerMixture<N> &mixture, const Data<N> &dta, const Params<N> &params) noexcept;\n\ntemplate<int N>\nvoid Fit(VonMisesFischerMixture<N> &mixture, Data<N> &dta, const Params<N> &params, Span<const Eigen::Vector3f> data, Span<const float> data_weights) noexcept\n{\n  assert(data.size() == data_weights.size());\n  assert(params.prior_mode != nullptr);\n  \n  for (int i=0; i<data.size(); ++i)\n  {\n    UpdateStatistics(mixture, dta, params, data[i], data_weights[i]);\n    if (dta.avg_positions.Count() % params.maximization_step_every == 0)\n    {\n      MaximizationStep(mixture, dta, params);\n\n      // Clear the statistics. Only keep average weights since they don't depend on the mixture parameters.\n      auto backup = dta.avg_weights;\n      dta = Data<N>{};\n      dta.avg_weights = backup;\n    }\n  }\n}\n\n\ntemplate<int N>\nvoid UpdateStatistics(VonMisesFischerMixture<N> & mixture, Data<N> &fitdata, const Params<N> &params, const Eigen::Vector3f & x, float weight) noexcept\n{\n  Eigen::Array<float, N, 1> responsibilities = mixture.weights * ComponentPdfs(mixture, x) + eps;\n  responsibilities /= responsibilities.sum();\n\n#if 0\n  if (fitdata.data_count_weights == 0)\n    fitdata.avg_weights = weight;\n  else\n    fitdata.avg_weights = Lerp(fitdata.avg_weights, weight, (float)std::pow(double(fitdata.data_count_weights), -0.75));\n\n  if (fitdata.data_count == 0)\n  {\n    fitdata.avg_responsibilities_unweighted = responsibilities;\n    fitdata.avg_responsibilities = weight * responsibilities;\n    fitdata.avg_positions = weight*(responsibilities.matrix()*x.transpose()).array();\n  }\n  else\n  {\n    // How much to \"trust\" new data.\n    const float mix_factor = (float)std::pow(double(fitdata.data_count), -0.75f);\n    fitdata.avg_responsibilities_unweighted += mix_factor*(responsibilities        - fitdata.avg_responsibilities_unweighted);\n    fitdata.avg_responsibilities            += mix_factor*(weight*responsibilities - fitdata.avg_responsibilities);\n    fitdata.avg_positions                   += mix_factor*(weight*(responsibilities.matrix()*x.transpose()).array() - fitdata.avg_positions);\n  }\n  ++fitdata.data_count;\n  ++fitdata.data_count_weights;\n#else\n  fitdata.avg_weights += weight;\n  fitdata.avg_responsibilities_unweighted += responsibilities;\n  fitdata.avg_responsibilities  += weight * responsibilities;\n  fitdata.avg_positions += weight*(responsibilities.matrix()*x.transpose()).array();\n#endif\n} \n\n\ntemplate<int N>\nvoid MaximizationStep(VonMisesFischerMixture<N> & mixture, const Data<N> &dta, const Params<N> &params) noexcept\n{\n\n  const std::uint64_t unique_data_count = dta.avg_responsibilities.Count();\n  for (int k = 0; k < VonMisesFischerMixture<N>::NUM_COMPONENTS; ++k)\n  {\n    const float scaled_responsibilities = dta.avg_responsibilities()[k] / (dta.avg_weights() + eps);\n\n    // The eps is there in case both of the former terms evaluate to zero!\n    mixture.weights[k] = (params.prior_nu-1)/unique_data_count*params.prior_mode->weights[k] + scaled_responsibilities + eps;\n\n    { // Posterior of mean.\n      const float diminished_prior_factor = dta.avg_weights() * params.prior_tau / unique_data_count;\n      mixture.means.row(k) = (diminished_prior_factor*params.prior_mode->means.row(k) + dta.avg_positions().row(k)) /\n        (diminished_prior_factor + dta.avg_responsibilities()[k] + eps);\n      float norm = mixture.means.row(k).matrix().norm();\n      if (norm > eps)\n        mixture.means.row(k) /= norm;\n      else\n        mixture.means.row(k).matrix() = Eigen::Vector3f{1.f, 0.f, 0.f};\n    }\n\n    {\n      #if 1\n      // Note: Don't use avg_responsibilities_unweighted[k]*avg_weights here. It computes the average position wrong\n      // in a way that mean_cosine is way overestimated.\n      const float mean_cosine = (1.f/(dta.avg_responsibilities()[k] + eps)) * dta.avg_positions().row(k).matrix().norm();\n      const float conc_estimate = MeanCosineToConc(mean_cosine);\n      const float diminished_alpha = params.prior_alpha/unique_data_count;\n      const float post_conc = \n        (params.prior_mode->concentrations[k]*diminished_alpha + conc_estimate) / (diminished_alpha + 1.f);\n      mixture.concentrations[k] = post_conc;\n      #endif\n\n      #if 0\n      // This does not do percievably better than the simpler code above!!\n      // Here the prior is on the mean cosine, forcing me to go back and forth with the cosine-k-conversions.\n      const float prior_cos = ConcToMeanCos(params.prior_mode->concentrations[k]);\n      const float mean_cosine = (1.f/(dta.avg_responsibilities()[k] + eps)) * dta.avg_positions().row(k).matrix().norm();\n      const float diminished_alpha = params.prior_alpha/unique_data_count;\n      const float mean_cosine_post = (diminished_alpha*prior_cos + mean_cosine) / (diminished_alpha + 1.f);\n      mixture.concentrations[k] = MeanCosineToConc(mean_cosine_post);\n      #endif\n    }\n  }\n\n  mixture.concentrations = mixture.concentrations.max(K_THRESHOLD).min(K_THRESHOLD_MAX).eval();\n\n  assert(mixture.weights.sum() > 0.f);\n  mixture.weights /= mixture.weights.sum();\n}\n\n\n} // namespace incremental\n\n} // namespace vmf_fitting\n\n\n#define INSTANTIATE_VonMisesFischerMixture(n) \\\n  template void vmf_fitting::incremental::Fit<n>(VonMisesFischerMixture<n> &mixture, Data<n> &fitdata, const Params<n> &params, Span<const Eigen::Vector3f> data, Span<const float> data_weights) noexcept; \\\n  template float  vmf_fitting::Pdf<n>(const VonMisesFischerMixture<n> &mixture, const Eigen::Vector3f &pos) noexcept; \\\n  template Eigen::Vector3f  vmf_fitting::Sample<n>(const VonMisesFischerMixture<n> &mixture, std::array<double, 3> rs) noexcept; \\\n  template void  vmf_fitting::InitializeForUnitSphere(VonMisesFischerMixture<n> &mixture) noexcept; \\\n  template void vmf_fitting::Normalize(VonMisesFischerMixture<n> &mixture) noexcept; \\\n  template void vmf_fitting::ExpApproximation<n>(Eigen::Array<float, n, 1> &vals);\n\nINSTANTIATE_VonMisesFischerMixture(2)\nINSTANTIATE_VonMisesFischerMixture(8)\nINSTANTIATE_VonMisesFischerMixture(16)\n\ntemplate vmf_fitting::VonMisesFischerMixture<16> vmf_fitting::Product(const vmf_fitting::VonMisesFischerMixture<2> &m1, const vmf_fitting::VonMisesFischerMixture<8> &m2) noexcept;", "meta": {"hexsha": "f8f2e9c68cf2db705cb0f8c939e7d680784308ad", "size": 15840, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/distribution_mixture_models.cxx", "max_stars_repo_name": "DaWelter/NaiveTrace", "max_stars_repo_head_hexsha": "a904785a0e13c394b2c221bc918cddb41bc8b175", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T08:14:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T06:19:16.000Z", "max_issues_repo_path": "src/distribution_mixture_models.cxx", "max_issues_repo_name": "DaWelter/NaiveTrace", "max_issues_repo_head_hexsha": "a904785a0e13c394b2c221bc918cddb41bc8b175", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/distribution_mixture_models.cxx", "max_forks_repo_name": "DaWelter/NaiveTrace", "max_forks_repo_head_hexsha": "a904785a0e13c394b2c221bc918cddb41bc8b175", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8235294118, "max_line_length": 205, "alphanum_fraction": 0.6906565657, "num_tokens": 4868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4496072898748402}}
{"text": "/* +---------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)               |\n   |                          http://www.mrpt.org/                             |\n   |                                                                           |\n   | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file        |\n   | See: http://www.mrpt.org/Authors - All rights reserved.                   |\n   | Released under BSD License. See details in http://www.mrpt.org/License    |\n   +---------------------------------------------------------------------------+ */\n\n#include \"vision-precomp.h\"   // Precompiled headers\n\n#include <mrpt/config.h>\n#include <mrpt/vision/utils.h>\n#include <mrpt/vision/pnp_algos.h>\n\n\n// Opencv 2.3 had a broken <opencv/eigen.h> in Ubuntu 14.04 Trusty => Disable PNP classes\n#include <mrpt/config.h>\n\n#if MRPT_HAS_OPENCV && MRPT_OPENCV_VERSION_NUM<0x240\n#\tundef MRPT_HAS_OPENCV\n#\tdefine MRPT_HAS_OPENCV 0\n#endif\n\n#include <iostream>\n\n#include <mrpt/utils/types_math.h> // Eigen must be included first via MRPT to enable the plugin system\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <mrpt/otherlibs/do_opencv_includes.h>\n#if MRPT_HAS_OPENCV\n#\tinclude <opencv2/core/eigen.hpp>\n#endif\n\n#include \"dls.h\"\n#include \"epnp.h\"\n#include \"upnp.h\"\n#include \"p3p.h\"\n#include \"ppnp.h\"\n#include \"posit.h\"\n#include \"lhm.h\"\n#include \"rpnp.h\"\n#include \"so3.h\"\n\nbool mrpt::vision::pnp::CPnP::dls(const Eigen::Ref<Eigen::MatrixXd> obj_pts, const Eigen::Ref<Eigen::MatrixXd> img_pts, int n, const Eigen::Ref<Eigen::MatrixXd> cam_intrinsic, Eigen::Ref<Eigen::MatrixXd> pose_mat){\n    try{\n        #if MRPT_HAS_OPENCV==1\n\n        // Input 2d/3d correspondences and camera intrinsic matrix\n        Eigen::MatrixXd cam_in_eig,img_pts_eig, obj_pts_eig;\n\n        // Check for consistency of input matrix dimensions\n        if (img_pts.rows() != obj_pts.rows() || img_pts.cols() !=obj_pts.cols())\n            throw(2);\n        else if (cam_intrinsic.rows()!=3 || cam_intrinsic.cols()!=3)\n            throw(3);\n\n        if(obj_pts.rows() < obj_pts.cols())\n        {\n            cam_in_eig=cam_intrinsic.transpose();\n            img_pts_eig=img_pts.transpose().block(0,0,n,2);\n            obj_pts_eig=obj_pts.transpose();\n        }\n        else\n        {\n            cam_in_eig=cam_intrinsic;\n            img_pts_eig=img_pts.block(0,0,n,2);\n            obj_pts_eig=obj_pts;\n        }\n\n        // Output pose\n        Eigen::Matrix3d R_eig;\n        Eigen::MatrixXd t_eig;\n\n        // Compute pose\n        cv::Mat cam_in_cv(3,3,CV_32F), img_pts_cv(2,n,CV_32F), obj_pts_cv(3,n,CV_32F), R_cv(3,3,CV_32F), t_cv(3,1,CV_32F);\n\n        cv::eigen2cv(cam_in_eig, cam_in_cv);\n        cv::eigen2cv(img_pts_eig, img_pts_cv);\n        cv::eigen2cv(obj_pts_eig, obj_pts_cv);\n\n        mrpt::vision::pnp::dls d(obj_pts_cv, img_pts_cv);\n        bool ret = d.compute_pose(R_cv,t_cv);\n\n        cv::cv2eigen(R_cv, R_eig);\n        cv::cv2eigen(t_cv, t_eig);\n\n        Eigen::Quaterniond q(R_eig);\n\n        pose_mat << t_eig,q.vec();\n\n        return ret;\n\n        #else\n\t\tthrow(-1);\n        #endif\n    }\n    catch(int e)\n    {\n        switch(e)\n        {\n            case -1: std::cout << \"Please install OpenCV for DLS-PnP\" << std::endl;\n            case  2: std::cout << \"2d/3d correspondences mismatch\\n Check dimension of obj_pts and img_pts\" << std::endl;\n            case  3: std::cout << \"Camera intrinsic matrix does not have 3x3 dimensions \" << std::endl;\n        }\n        return false;\n    }\n}\n\nbool mrpt::vision::pnp::CPnP::epnp(const Eigen::Ref<Eigen::MatrixXd> obj_pts, const Eigen::Ref<Eigen::MatrixXd> img_pts, int n, const Eigen::Ref<Eigen::MatrixXd> cam_intrinsic, Eigen::Ref<Eigen::MatrixXd> pose_mat){\n    try{\n        #if MRPT_HAS_OPENCV==1\n\n        // Input 2d/3d correspondences and camera intrinsic matrix\n        Eigen::MatrixXd cam_in_eig,img_pts_eig, obj_pts_eig;\n\n        // Check for consistency of input matrix dimensions\n        if (img_pts.rows() != obj_pts.rows() || img_pts.cols() !=obj_pts.cols())\n            throw(2);\n        else if (cam_intrinsic.rows()!=3 || cam_intrinsic.cols()!=3)\n            throw(3);\n\n        if(obj_pts.rows() < obj_pts.cols())\n        {\n            cam_in_eig=cam_intrinsic.transpose();\n            img_pts_eig=img_pts.transpose().block(0,0,n,2);\n            obj_pts_eig=obj_pts.transpose();\n        }\n        else\n        {\n            cam_in_eig=cam_intrinsic;\n            img_pts_eig=img_pts.block(0,0,n,2);\n            obj_pts_eig=obj_pts;\n        }\n\n        // Output pose\n        Eigen::Matrix3d R_eig;\n        Eigen::MatrixXd t_eig;\n\n        // Compute pose\n        cv::Mat cam_in_cv(3,3,CV_32F), img_pts_cv(2,n,CV_32F), obj_pts_cv(3,n,CV_32F), R_cv, t_cv;\n\n        cv::eigen2cv(cam_in_eig, cam_in_cv);\n        cv::eigen2cv(img_pts_eig, img_pts_cv);\n        cv::eigen2cv(obj_pts_eig, obj_pts_cv);\n\n        mrpt::vision::pnp::epnp e(cam_in_cv, obj_pts_cv, img_pts_cv);\n        e.compute_pose(R_cv,t_cv);\n\n        cv::cv2eigen(R_cv, R_eig);\n        cv::cv2eigen(t_cv, t_eig);\n\n        Eigen::Quaterniond q(R_eig);\n\n        pose_mat << t_eig,q.vec();\n\n        return true;\n\n        #else\n        throw(-1);\n        #endif\n    }\n    catch(int e){\n        switch(e)\n        {\n            case -1: std::cout << \"Please install OpenCV for DLS-PnP\" << std::endl;\n            case  2: std::cout << \"2d/3d correspondences mismatch\\n Check dimension of obj_pts and img_pts\" << std::endl;\n            case  3: std::cout << \"Camera intrinsic matrix does not have 3x3 dimensions \" << std::endl;\n        }\n        return false;\n    }\n}\n\nbool mrpt::vision::pnp::CPnP::upnp(const Eigen::Ref<Eigen::MatrixXd> obj_pts, const Eigen::Ref<Eigen::MatrixXd> img_pts, int n, const Eigen::Ref<Eigen::MatrixXd> cam_intrinsic, Eigen::Ref<Eigen::MatrixXd> pose_mat){\n    try{\n        #if MRPT_HAS_OPENCV==1\n\n        // Input 2d/3d correspondences and camera intrinsic matrix\n        Eigen::MatrixXd cam_in_eig,img_pts_eig, obj_pts_eig;\n\n        // Check for consistency of input matrix dimensions\n        if (img_pts.rows() != obj_pts.rows() || img_pts.cols() !=obj_pts.cols())\n            throw(2);\n        else if (cam_intrinsic.rows()!=3 || cam_intrinsic.cols()!=3)\n            throw(3);\n\n        if(obj_pts.rows() < obj_pts.cols())\n        {\n            cam_in_eig=cam_intrinsic.transpose();\n            img_pts_eig=img_pts.transpose().block(0,0,n,2);\n            obj_pts_eig=obj_pts.transpose();\n        }\n        else\n        {\n            cam_in_eig=cam_intrinsic;\n            img_pts_eig=img_pts.block(0,0,n,2);\n            obj_pts_eig=obj_pts;\n        }\n\n        // Output pose\n        Eigen::Matrix3d R_eig;\n        Eigen::MatrixXd t_eig;\n\n        // Compute pose\n        cv::Mat cam_in_cv(3,3,CV_32F), img_pts_cv(2,n,CV_32F), obj_pts_cv(3,n,CV_32F), R_cv, t_cv;\n\n        cv::eigen2cv(cam_in_eig, cam_in_cv);\n        cv::eigen2cv(img_pts_eig, img_pts_cv);\n        cv::eigen2cv(obj_pts_eig, obj_pts_cv);\n\n        mrpt::vision::pnp::upnp u(cam_in_cv, obj_pts_cv, img_pts_cv);\n        u.compute_pose(R_cv,t_cv);\n\n        cv::cv2eigen(R_cv, R_eig);\n        cv::cv2eigen(t_cv, t_eig);\n\n        Eigen::Quaterniond q(R_eig);\n\n        pose_mat << t_eig,q.vec();\n\n        return true;\n        #else\n        throw(-1);\n        #endif\n    }\n    catch(int e)\n    {\n        switch(e)\n        {\n            case -1: std::cout << \"Please install OpenCV for DLS-PnP\" << std::endl;\n            case  2: std::cout << \"2d/3d correspondences mismatch\\n Check dimension of obj_pts and img_pts\" << std::endl;\n            case  3: std::cout << \"Camera intrinsic matrix does not have 3x3 dimensions \" << std::endl;\n        }\n        return false;\n    }\n}\n\n\nbool mrpt::vision::pnp::CPnP::p3p(const Eigen::Ref<Eigen::MatrixXd> obj_pts, const Eigen::Ref<Eigen::MatrixXd> img_pts, int n, const Eigen::Ref<Eigen::MatrixXd> cam_intrinsic, Eigen::Ref<Eigen::MatrixXd> pose_mat){\n\n    try{\n        // Input 2d/3d correspondences and camera intrinsic matrix\n        Eigen::MatrixXd cam_in_eig,img_pts_eig, obj_pts_eig;\n\n        // Check for consistency of input matrix dimensions\n        if (img_pts.rows() != obj_pts.rows() || img_pts.cols() !=obj_pts.cols())\n            throw(2);\n        else if (cam_intrinsic.rows()!=3 || cam_intrinsic.cols()!=3)\n            throw(3);\n\n        if(obj_pts.rows() < obj_pts.cols())\n        {\n            cam_in_eig=cam_intrinsic.transpose();\n            img_pts_eig=img_pts.transpose().block(0,0,n,2);\n            obj_pts_eig=obj_pts.transpose();\n        }\n        else\n        {\n            cam_in_eig=cam_intrinsic;\n            img_pts_eig=img_pts.block(0,0,n,2);\n            obj_pts_eig=obj_pts;\n        }\n\n        // Output pose\n        Eigen::Matrix3d R;\n        Eigen::Vector3d t;\n\n        // Compute pose\n        mrpt::vision::pnp::p3p p(cam_in_eig);\n        bool ret = p.solve(R,t, obj_pts_eig, img_pts_eig);\n\n        Eigen::Quaterniond q(R);\n\n        pose_mat << t,q.vec();\n\n        return ret;\n    }\n    catch(int e)\n    {\n        switch(e)\n        {\n            case  2: std::cout << \"2d/3d correspondences mismatch\\n Check dimension of obj_pts and img_pts\" << std::endl;\n            case  3: std::cout << \"Camera intrinsic matrix does not have 3x3 dimensions \" << std::endl;\n        }\n        return false;\n    }\n}\n\n\nbool mrpt::vision::pnp::CPnP::rpnp(const Eigen::Ref<Eigen::MatrixXd> obj_pts, const Eigen::Ref<Eigen::MatrixXd> img_pts, int n, const Eigen::Ref<Eigen::MatrixXd> cam_intrinsic, Eigen::Ref<Eigen::MatrixXd> pose_mat){\n    try{\n        // Input 2d/3d correspondences and camera intrinsic matrix\n        Eigen::MatrixXd cam_in_eig,img_pts_eig, obj_pts_eig;\n\n        // Check for consistency of input matrix dimensions\n        if (img_pts.rows() != obj_pts.rows() || img_pts.cols() !=obj_pts.cols())\n            throw(2);\n        else if (cam_intrinsic.rows()!=3 || cam_intrinsic.cols()!=3)\n            throw(3);\n\n        if(obj_pts.rows() < obj_pts.cols())\n        {\n            cam_in_eig=cam_intrinsic.transpose();\n            img_pts_eig=img_pts.transpose();\n            obj_pts_eig=obj_pts.transpose();\n        }\n        else\n        {\n            cam_in_eig=cam_intrinsic;\n            img_pts_eig=img_pts;\n            obj_pts_eig=obj_pts;\n        }\n\n        // Output pose\n        Eigen::Matrix3d R;\n        Eigen::Vector3d t;\n\n        // Compute pose\n        mrpt::vision::pnp::rpnp r(obj_pts_eig, img_pts_eig, cam_in_eig, n);\n        bool ret = r.compute_pose(R,t);\n\n        Eigen::Quaterniond q(R);\n\n        pose_mat << t,q.vec();\n\n        return ret;\n    }\n    catch(int e)\n    {\n        switch(e)\n        {\n            case  2: std::cout << \"2d/3d correspondences mismatch\\n Check dimension of obj_pts and img_pts\" << std::endl;\n            case  3: std::cout << \"Camera intrinsic matrix does not have 3x3 dimensions \" << std::endl;\n        }\n        return false;\n    }\n}\n\nbool mrpt::vision::pnp::CPnP::ppnp(const Eigen::Ref<Eigen::MatrixXd> obj_pts, const Eigen::Ref<Eigen::MatrixXd> img_pts, int n, const Eigen::Ref<Eigen::MatrixXd> cam_intrinsic, Eigen::Ref<Eigen::MatrixXd> pose_mat)\n{\n\ttry{\n        // Input 2d/3d correspondences and camera intrinsic matrix\n        Eigen::MatrixXd cam_in_eig,img_pts_eig, obj_pts_eig;\n\n        // Check for consistency of input matrix dimensions\n        if (img_pts.rows() != obj_pts.rows() || img_pts.cols() !=obj_pts.cols())\n            throw(2);\n        else if (cam_intrinsic.rows()!=3 || cam_intrinsic.cols()!=3)\n            throw(3);\n\n        if(obj_pts.rows() < obj_pts.cols())\n        {\n            cam_in_eig=cam_intrinsic.transpose();\n            img_pts_eig=img_pts.transpose();\n            obj_pts_eig=obj_pts.transpose();\n        }\n        else\n        {\n            cam_in_eig=cam_intrinsic;\n            img_pts_eig=img_pts;\n            obj_pts_eig=obj_pts;\n        }\n\n        // Output pose\n        Eigen::Matrix3d R;\n        Eigen::Vector3d t;\n\n        // Compute pose\n        mrpt::vision::pnp::ppnp p(obj_pts_eig,img_pts_eig, cam_in_eig);\n\n        bool ret = p.compute_pose(R,t,n);\n\n        Eigen::Quaterniond q(R);\n\n        pose_mat << t,q.vec();\n\n        return ret;\n    }\n    catch(int e)\n    {\n        switch(e)\n        {\n            case  2: std::cout << \"2d/3d correspondences mismatch\\n Check dimension of obj_pts and img_pts\" << std::endl;\n            case  3: std::cout << \"Camera intrinsic matrix does not have 3x3 dimensions \" << std::endl;\n        }\n        return false;\n    }\n}\n\nbool mrpt::vision::pnp::CPnP::posit(const Eigen::Ref<Eigen::MatrixXd> obj_pts, const Eigen::Ref<Eigen::MatrixXd> img_pts, int n, const Eigen::Ref<Eigen::MatrixXd> cam_intrinsic, Eigen::Ref<Eigen::MatrixXd> pose_mat)\n{\n\ttry{\n        // Input 2d/3d correspondences and camera intrinsic matrix\n        Eigen::MatrixXd cam_in_eig,img_pts_eig, obj_pts_eig;\n\n        // Check for consistency of input matrix dimensions\n        if (img_pts.rows() != obj_pts.rows() || img_pts.cols() !=obj_pts.cols())\n            throw(2);\n        else if (cam_intrinsic.rows()!=3 || cam_intrinsic.cols()!=3)\n            throw(3);\n\n        if(obj_pts.rows() < obj_pts.cols())\n        {\n            cam_in_eig=cam_intrinsic.transpose();\n            img_pts_eig=img_pts.transpose().block(0,0,n,2);\n            obj_pts_eig=obj_pts.transpose();\n        }\n        else\n        {\n            cam_in_eig=cam_intrinsic;\n            img_pts_eig=img_pts.block(0,0,n,2);\n            obj_pts_eig=obj_pts;\n        }\n\n        // Output pose\n        Eigen::Matrix3d R;\n        Eigen::Vector3d t;\n\n        // Compute pose\n        mrpt::vision::pnp::posit p(obj_pts_eig,img_pts_eig, cam_in_eig, n);\n\n        bool ret = p.compute_pose(R,t);\n\n        Eigen::Quaterniond q(R);\n\n        pose_mat << t,q.vec();\n\n        return ret;\n    }\n    catch(int e)\n    {\n        switch(e)\n        {\n            case  2: std::cout << \"2d/3d correspondences mismatch\\n Check dimension of obj_pts and img_pts\" << std::endl;\n            case  3: std::cout << \"Camera intrinsic matrix does not have 3x3 dimensions \" << std::endl;\n        }\n        return false;\n    }\n\n}\n\nbool mrpt::vision::pnp::CPnP::lhm(const Eigen::Ref<Eigen::MatrixXd> obj_pts, const Eigen::Ref<Eigen::MatrixXd> img_pts, int n, const Eigen::Ref<Eigen::MatrixXd> cam_intrinsic, Eigen::Ref<Eigen::MatrixXd> pose_mat)\n{\n    try{\n        // Input 2d/3d correspondences and camera intrinsic matrix\n        Eigen::MatrixXd cam_in_eig,img_pts_eig, obj_pts_eig;\n\n        // Check for consistency of input matrix dimensions\n        if (img_pts.rows() != obj_pts.rows() || img_pts.cols() !=obj_pts.cols())\n            throw(2);\n        else if (cam_intrinsic.rows()!=3 || cam_intrinsic.cols()!=3)\n            throw(3);\n\n        if(obj_pts.rows() < obj_pts.cols())\n        {\n            cam_in_eig=cam_intrinsic.transpose();\n            img_pts_eig=img_pts.transpose();\n            obj_pts_eig=obj_pts.transpose();\n        }\n        else\n        {\n            cam_in_eig=cam_intrinsic;\n            img_pts_eig=img_pts;\n            obj_pts_eig=obj_pts;\n        }\n\n        // Output pose\n        Eigen::Matrix3d R;\n        Eigen::Vector3d t;\n\n        // Compute pose\n        mrpt::vision::pnp::lhm l(obj_pts_eig, img_pts_eig, cam_intrinsic, n);\n\n        bool ret = l.compute_pose(R,t);\n\n        Eigen::Quaterniond q(R);\n\n        pose_mat<<t,q.vec();\n\n        return ret;\n    }\n    catch(int e)\n    {\n        switch(e)\n        {\n            case  2: std::cout << \"2d/3d correspondences mismatch\\n Check dimension of obj_pts and img_pts\" << std::endl;\n            case  3: std::cout << \"Camera intrinsic matrix does not have 3x3 dimensions \" << std::endl;\n        }\n        return false;\n    }\n}\n\nbool mrpt::vision::pnp::CPnP::so3(const Eigen::Ref<Eigen::MatrixXd> obj_pts, const Eigen::Ref<Eigen::MatrixXd> img_pts, int n, const Eigen::Ref<Eigen::MatrixXd> cam_intrinsic, Eigen::Ref<Eigen::MatrixXd> pose_mat)\n{\n    try{\n        // Input 2d/3d correspondences and camera intrinsic matrix\n        Eigen::MatrixXd cam_in_eig,img_pts_eig, obj_pts_eig;\n\n        // Check for consistency of input matrix dimensions\n        if (img_pts.rows() != obj_pts.rows() || img_pts.cols() !=obj_pts.cols())\n            throw(2);\n        else if (cam_intrinsic.rows()!=3 || cam_intrinsic.cols()!=3)\n            throw(3);\n\n        if(obj_pts.rows() < obj_pts.cols())\n        {\n            cam_in_eig=cam_intrinsic.transpose();\n            img_pts_eig=img_pts.transpose().block(0,0,n,2);\n            obj_pts_eig=obj_pts.transpose();\n        }\n        else\n        {\n            cam_in_eig=cam_intrinsic;\n            img_pts_eig=img_pts.block(0,0,n,2);\n            obj_pts_eig=obj_pts;\n        }\n\n        // Output pose\n        Eigen::Matrix3d R;\n        Eigen::Vector3d t;\n\n        // Compute pose\n        mrpt::vision::pnp::p3p p(cam_in_eig);\n        p.solve(R,t, obj_pts_eig, img_pts_eig);\n\n        mrpt::vision::pnp::so3 s(obj_pts_eig, img_pts_eig, cam_in_eig, n);\n        bool ret = s.compute_pose(R,t);\n\n        Eigen::Quaterniond q(R);\n\n        pose_mat<<t,q.vec();\n\n        return ret;\n    }\n    catch(int e)\n    {\n        switch(e)\n        {\n            case  2: std::cout << \"2d/3d correspondences mismatch\\n Check dimension of obj_pts and img_pts\" << std::endl;\n            case  3: std::cout << \"Camera intrinsic matrix does not have 3x3 dimensions \" << std::endl;\n        }\n        return false;\n    }\n}\n", "meta": {"hexsha": "caac883e9b1bbb20622e5bd7ae78783590608788", "size": 17404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/vision/src/pnp/pnp_algos.cpp", "max_stars_repo_name": "yhexie/mrpt", "max_stars_repo_head_hexsha": "0bece2883aa51ad3dc88cb8bb84df571034ed261", "max_stars_repo_licenses": ["OLDAP-2.3"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/vision/src/pnp/pnp_algos.cpp", "max_issues_repo_name": "yhexie/mrpt", "max_issues_repo_head_hexsha": "0bece2883aa51ad3dc88cb8bb84df571034ed261", "max_issues_repo_licenses": ["OLDAP-2.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/vision/src/pnp/pnp_algos.cpp", "max_forks_repo_name": "yhexie/mrpt", "max_forks_repo_head_hexsha": "0bece2883aa51ad3dc88cb8bb84df571034ed261", "max_forks_repo_licenses": ["OLDAP-2.3"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-16T11:50:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T11:50:47.000Z", "avg_line_length": 31.8754578755, "max_line_length": 215, "alphanum_fraction": 0.5741208917, "num_tokens": 4706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.44959342538212776}}
{"text": "#include <boost/math/tools/roots.hpp>\n#include <ibs>\n#include <ste>\n//#include <boost/math/tools/roots.hpp>\n#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <iostream>\n#include <map>\n#include <math.h>\n#include <string>\n\ntemplate <class T> struct synchronousPhaseFunctor {\n  synchronousPhaseFunctor(T const &target, std::vector<double> &voltages,\n                          std::vector<double> &harmonicNumbers, float charge)\n      : U0(target), volts(voltages), hs(harmonicNumbers), ch(charge) {}\n  std::tuple<double, double> operator()(T const &phi) {\n    T volt1, volt2, volt3;\n    T dvolt1, dvolt2, dvolt3;\n    volt1 = ch * volts[0] * sin(phi);\n    volt2 = ch * volts[1] * sin((hs[1] / hs[0]) * phi);\n    volt3 = ch * volts[2] * sin((hs[2] / hs[0]) * phi);\n\n    dvolt1 = ch * volts[0] * cos(phi);\n    dvolt2 = ch * volts[1] * (hs[1] / hs[0]) * cos((hs[1] / hs[0]) * phi);\n    dvolt3 = ch * volts[2] * (hs[2] / hs[0]) * cos((hs[2] / hs[0]) * phi);\n    std::tuple<double, double> out = {volt1 + volt2 + volt3 - U0,\n                                      dvolt1 + dvolt2 + dvolt3};\n    return out;\n  }\n\nprivate:\n  T U0;\n  std::vector<double> volts;\n  std::vector<double> hs;\n  double ch;\n};\n\ntemplate <class T>\nT synchronousPhaseFunctorDeriv(T x, std::vector<double> &voltages,\n                               std::vector<double> &harmnumbers, double charge,\n                               T guess, T min, T max) {\n  // return cube root of x using 1st derivative and Newton_Raphson.\n  using namespace boost::math::tools;\n\n  const int digits =\n      std::numeric_limits<T>::digits; // Maximum possible binary digits accuracy\n                                      // for type T.\n  int get_digits = static_cast<int>(\n      digits * 0.6); // Accuracy doubles with each step, so stop when we have\n                     // just over half the digits correct.\n  const boost::uintmax_t maxit = 20;\n  boost::uintmax_t it = maxit;\n  T result = newton_raphson_iterate(\n      synchronousPhaseFunctor<T>(x, voltages, harmnumbers, charge), guess, min,\n      max, get_digits, it);\n  return result;\n}\ndouble pcoeff(double voltage, double angularFreq, double p0,\n              double betaRelativistic, double charge) {\n  return (angularFreq * voltage * charge) / (2.0 * pi * p0 * betaRelativistic);\n}\n\ndouble HamiltonianTripleRf(double tcoeff, std::vector<double> &voltages,\n                           std::vector<double> &harmonicNumbers,\n                           double phiSynchronous, double t, double delta,\n                           double omega0, double p0, double betaRelativistic,\n                           double charge) {\n  double kinetic, potential1, potential2, potential3;\n  kinetic = 0.5 * tcoeff * pow(delta, 2);\n\n  std::printf(\"%-30s %16.8e\\n\", \"kinetic\", kinetic);\n  potential1 = pcoeff(voltages[0], omega0, p0, betaRelativistic, charge) *\n               (cos(harmonicNumbers[0] * omega0 * t) - cos(phiSynchronous) +\n                (harmonicNumbers[0] * omega0 * t - phiSynchronous) *\n                    sin(phiSynchronous));\n  std::printf(\"%-30s %16.8e\\n\", \"pcoeff0\",\n              pcoeff(voltages[0], omega0, p0, betaRelativistic, charge));\n  std::printf(\"%-30s %16.8e\\n\", \"phase0\", harmonicNumbers[0] * omega0 * t);\n  std::printf(\"%-30s %16.8e\\n\", \"potential1\", potential1);\n\n  potential2 =\n      pcoeff(voltages[1], omega0, p0, betaRelativistic, charge) *\n      (harmonicNumbers[0] / harmonicNumbers[1]) *\n      (cos(harmonicNumbers[1] * omega0 * t) -\n       cos(harmonicNumbers[1] * phiSynchronous / harmonicNumbers[0]) +\n       (harmonicNumbers[1] * omega0 * t -\n        harmonicNumbers[1] * phiSynchronous / harmonicNumbers[0]) *\n           sin(harmonicNumbers[1] * phiSynchronous / harmonicNumbers[0]));\n\n  potential3 =\n      pcoeff(voltages[2], omega0, p0, betaRelativistic, charge) *\n      (harmonicNumbers[0] / harmonicNumbers[2]) *\n      (cos(harmonicNumbers[2] * omega0 * t) -\n       cos(harmonicNumbers[2] * phiSynchronous / harmonicNumbers[0]) +\n       (harmonicNumbers[2] * omega0 * t -\n        harmonicNumbers[2] * phiSynchronous / harmonicNumbers[0]) *\n           sin(harmonicNumbers[2] * phiSynchronous / harmonicNumbers[0]));\n\n  return kinetic + potential1 + potential2 + potential3;\n};\n\ndouble synchrotronTune(std::map<string, double> &twissheadermap,\n                       std::vector<double> h, std::vector<double> v) {\n  double p0 = twissheadermap[\"PC\"] * 1.0e9;\n  double phis = twissheadermap[\"phis\"];\n  double charge = twissheadermap[\"CHARGE\"];\n  double Omega2 =\n      (h[0] * twissheadermap[\"eta\"] * charge) / (2.0 * pi * p0) *\n      (v[0] * cos(phis) + v[1] * (h[1] / h[0]) * cos((h[1] / h[0]) * phis) +\n       v[2] * (h[2] / h[0]) * cos((h[2] / h[0]) * phis));\n  return sqrt(abs(Omega2));\n};\n\nint main() {\n  string twissfilename = \"../src/b2_design_lattice_1996.twiss\";\n  map<string, double> twissheadermap;\n  twissheadermap = GetTwissHeader(twissfilename);\n\n  // rf settings\n  std::vector<double> h, v;\n  h.push_back(400.0);\n  v.push_back(-1.5e6);\n\n  // bunch length\n  double sigs = 0.005;\n  // aatom\n  double aatom = emass / pmass;\n  // set energy loss per turn manually\n  // TODO: implement radiation update of twiss\n  twissheadermap[\"U0\"] = 174e3;\n  // update twiss header with long parameters\n  ste_longitudinal::updateTwissHeaderLong(twissheadermap, h, v, aatom, sigs);\n\n  double energyLostPerTurn = 174000;    // radation losses per turn per particle\n  double acceleratorLength = 240.00839; // length in meter\n  double gammar = twissheadermap[\"GAMMA\"]; // relativistic gamma\n  // double eta = 0.0007038773471 -\n  //          1 / pow(gammar, 2); // slip factor approx alpha - 1/ gammar**2\n  double betar = twissheadermap[\"betar\"]; // relativistic beta\n  double trev = twissheadermap[\"trev\"];\n  double h0 = 400.0;\n  double h1 = 400; // 1200.0;\n  double h2 = 400; // 1400.0;\n  double v0 = -1.5e6;\n  double v1 = 0.0; // 20.0e6;\n  double v2 = 0.0; // 17.14e6;\n  double omega0 = (2 * pi) / trev;\n  double p0 = 1.7e9;\n  double charge = -1.0;\n  std::vector<double> hnumbers = {h0, h1, h2};\n  std::vector<double> voltages = {v0, v1, v2};\n\n  double search1 =\n      trev * h0 * omega0 /\n      (8 * max(max(h0, h1), h2)); // give positive offset to find upstream\n                                  // root and not downstream root\n  double search2 = trev * h0 * omega0 / (8 * max(max(h0, h1), h2)) -\n                   trev * h0 * omega0 / min(min(h0, h1), h2);\n  double searchWidth = trev * h0 * omega0 / (2 * max(max(h0, h1), h2));\n  ste_output::cyan();\n  std::printf(\"%-30s : %16.6f\\n\", \"Search1\", search1 / pi * 180);\n  std::printf(\"%-30s : %16.6f\\n\", \"Search2\", search2 / pi * 180);\n  std::printf(\"%-30s : %16.6f\\n\", \"Width\", searchWidth / pi * 180);\n  ste_output::reset();\n\n  double synchronousPhase0 = synchronousPhaseFunctorDeriv(\n      energyLostPerTurn, voltages, hnumbers, charge, search1,\n      search1 - searchWidth, search1 + searchWidth);\n  double synchronousPhase1 = synchronousPhaseFunctorDeriv(\n      energyLostPerTurn, voltages, hnumbers, charge, search2,\n      search2 - searchWidth, search2 + searchWidth);\n\n  ste_output::blue();\n  std::printf(\"%-30s : %16.6f %16.6f %16.6e \\n\", \"synchronous phase\", search1,\n              synchronousPhase0 / pi * 180, synchronousPhase0 / (h0 * omega0));\n  std::printf(\"%-30s : %16.6f %16.6f %16.6e \\n\", \"synchronous phase\", search2,\n              synchronousPhase1 / pi * 180, synchronousPhase1 / (h0 * omega0));\n  ste_output::yellow();\n  std::printf(\"%-30s : %16.6f %16.6f %16.6e\\n\", \"synchronous phase\", 173.0,\n              twissheadermap[\"phis\"],\n              twissheadermap[\"phis\"] / 180.0 * pi / (h0 * omega0));\n  ste_output::reset();\n\n  std::cout << \"Find next extremum of Hamiltonian\" << std::endl;\n\n  double synchronousPhase0Next = synchronousPhaseFunctorDeriv(\n      energyLostPerTurn, voltages, hnumbers, charge, search1 + searchWidth,\n      search1 + searchWidth / 2, search1 + 2 * searchWidth);\n  double synchronousPhase1Next = synchronousPhaseFunctorDeriv(\n      energyLostPerTurn, voltages, hnumbers, charge, search2 + searchWidth,\n      search2 + searchWidth / 2, search2 + 2 * searchWidth);\n\n  ste_output::blue();\n  std::printf(\"%-30s : %16.6f %16.6f %16.6e \\n\", \"synchronous phase next\",\n              search1 + searchWidth, synchronousPhase0Next / pi * 180,\n              synchronousPhase0Next / (h0 * omega0));\n  std::printf(\"%-30s : %16.6f %16.6f %16.6e \\n\", \"synchronous phase next \",\n              search2 + searchWidth, synchronousPhase1Next / pi * 180,\n              synchronousPhase1Next / (h0 * omega0));\n  ste_output::yellow();\n  std::printf(\"%-30s : %16.6f\\n\", \"synchronous phase\", twissheadermap[\"phis\"]);\n  ste_output::reset();\n\n  std::printf(\"%s\", \"\\nHamiltonians\\n\");\n  ste_output::blue();\n  double tc = ste_longitudinal::tcoeff(twissheadermap, h0);\n  double tcval = tc / (h0 * omega0);\n  double ohammax = HamiltonianTripleRf(\n      tcval, voltages, hnumbers, synchronousPhase1,\n      synchronousPhase1Next / (h0 * omega0), 0.0, omega0, p0, betar, charge);\n  double hammax =\n      ste_longitudinal::Hamiltonian(twissheadermap, hnumbers, voltages, tc,\n                                    synchronousPhase1Next / (h0 * omega0), 0.0);\n  std::printf(\"%-30s : %16.6f \\n\", \"tcoeff\", tcval);\n  std::printf(\"%-30s : %16.6f \\n\", \"ohammax\", ohammax);\n  ste_output::yellow();\n  std::printf(\"%-30s : %16.6f \\n\", \"hammax\", hammax);\n  ste_output::reset();\n\n  std::cout << \"Synchrotron tune : \"\n            << synchrotronTune(twissheadermap, hnumbers, voltages) << std::endl;\n  std::cout << \"Synchrotron tune (Hz): \"\n            << synchrotronTune(twissheadermap, hnumbers, voltages) * omega0 /\n                   (2.0 * pi)\n            << std::endl;\n  std::printf(\"%-30s : %16.6f \\n\", \"syncTune\",\n              synchrotronTune(twissheadermap, hnumbers, voltages));\n  std::printf(\"%-30s : %16.6f \\n\", \"syncTune Hz\",\n              synchrotronTune(twissheadermap, hnumbers, voltages) * omega0 /\n                  (2.0 * pi));\n  ste_output::yellow();\n  std::printf(\"%-30s : %16.6f \\n\", \"syncTune\", twissheadermap[\"qs\"]);\n  std::printf(\"%-30s : %16.6f \\n\", \"syncTune Hz\",\n              twissheadermap[\"qs\"] * omega0 / (2.0 * pi));\n  ste_output::reset();\n\n  std::printf(\"%16.6e  %16.6e %16.6e %16.6e %16.6e\\n\", synchronousPhase0Next,\n              synchronousPhase0,\n              abs((synchronousPhase0Next - synchronousPhase0) / pi * 180.0), h0,\n              omega0);\n  std::printf(\"%-30s : %16.6e \\n\", \"tauhat\",\n              abs((synchronousPhase0Next - synchronousPhase0) / (h0 * omega0)));\n  ste_output::yellow();\n  std::printf(\"%-30s : %16.6e \\n\", \"tauhat\", twissheadermap[\"tauhat\"]);\n  std::printf(\"%-30s : %16.6e \\n\", \"tauhat\",\n              (twissheadermap[\"phis\"] - (twissheadermap[\"phis\"] - 180.0)) /\n                  180.0 * pi / (h0 * omega0));\n  ste_output::reset();\n  return 0;\n}", "meta": {"hexsha": "30808bd0ddc8a5566bf0959da3e8586ed013a953", "size": 10808, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/tests/src/origcodetest.cpp", "max_stars_repo_name": "tomerten/steibs", "max_stars_repo_head_hexsha": "8d4e994020dd17475ba1371e9c6f365c916828a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/tests/src/origcodetest.cpp", "max_issues_repo_name": "tomerten/steibs", "max_issues_repo_head_hexsha": "8d4e994020dd17475ba1371e9c6f365c916828a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/tests/src/origcodetest.cpp", "max_forks_repo_name": "tomerten/steibs", "max_forks_repo_head_hexsha": "8d4e994020dd17475ba1371e9c6f365c916828a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.0597609562, "max_line_length": 80, "alphanum_fraction": 0.6098260548, "num_tokens": 3406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789040926008, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4493866147928419}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2012, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n               \n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n\n//\n// *** System\n//\n#include <iostream>\n\n//\n// *** Boost\n//\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n//\n// *** ViennaCL\n//\n//#define VIENNACL_DEBUG_ALL\n#define VIENNACL_HAVE_UBLAS 1\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/linalg/direct_solve.hpp\"\n#include \"viennacl/linalg/lu.hpp\"\n#include \"examples/tutorial/Random.hpp\"\n\n//\n// -------------------------------------------------------------\n//\nusing namespace boost::numeric;\n//\n// -------------------------------------------------------------\n//\ntemplate <typename ScalarType>\nScalarType diff(ScalarType & s1, viennacl::scalar<ScalarType> & s2) \n{\n   viennacl::backend::finish();\n   if (s1 != s2)\n      return (s1 - s2) / std::max(fabs(s1), fabs(s2));\n   return 0;\n}\n\ntemplate <typename ScalarType, typename VCLVectorType>\nScalarType diff(ublas::vector<ScalarType> const & v1, VCLVectorType const & v2)\n{\n   ublas::vector<ScalarType> v2_cpu(v2.size());\n   viennacl::backend::finish();  //workaround for a bug in APP SDK 2.7 on Trinity APUs (with Catalyst 12.8)\n   viennacl::copy(v2.begin(), v2.end(), v2_cpu.begin());\n\n   for (unsigned int i=0;i<v1.size(); ++i)\n   {\n      if ( std::max( fabs(v2_cpu[i]), fabs(v1[i]) ) > 0 )\n         v2_cpu[i] = fabs(v2_cpu[i] - v1[i]) / std::max( fabs(v2_cpu[i]), fabs(v1[i]) );\n      else\n         v2_cpu[i] = 0.0;\n   }\n\n   return norm_inf(v2_cpu);\n}\n\ntemplate <typename ScalarType, typename VCLMatrixType>\nScalarType diff(ublas::matrix<ScalarType> const & mat1, VCLMatrixType const & mat2)\n{\n   ublas::matrix<ScalarType> mat2_cpu(mat2.size1(), mat2.size2());\n   viennacl::backend::finish();  //workaround for a bug in APP SDK 2.7 on Trinity APUs (with Catalyst 12.8)\n   viennacl::copy(mat2, mat2_cpu);\n   ScalarType ret = 0;\n   ScalarType act = 0;\n\n    for (unsigned int i = 0; i < mat2_cpu.size1(); ++i)\n    {\n      for (unsigned int j = 0; j < mat2_cpu.size2(); ++j)\n      {\n         act = fabs(mat2_cpu(i,j) - mat1(i,j)) / std::max( fabs(mat2_cpu(i, j)), fabs(mat1(i,j)) );\n         if (act > ret)\n           ret = act;\n      }\n    }\n   //std::cout << ret << std::endl;\n   return ret;\n}\n//\n// -------------------------------------------------------------\n//\n\ntemplate <typename NumericT, typename Epsilon, \n          typename UblasMatrixType, typename UblasVectorType,\n          typename VCLMatrixType, typename VCLVectorType1, typename VCLVectorType2>\nint test_prod_rank1(Epsilon const & epsilon,\n                    UblasMatrixType & ublas_m1, UblasVectorType & ublas_v1, UblasVectorType & ublas_v2, \n                    VCLMatrixType & vcl_m1, VCLVectorType1 & vcl_v1, VCLVectorType2 & vcl_v2)\n{\n   int retval = EXIT_SUCCESS;\n  \n   // sync data:\n   viennacl::copy(ublas_v1.begin(), ublas_v1.end(), vcl_v1.begin());\n   viennacl::copy(ublas_v2.begin(), ublas_v2.end(), vcl_v2.begin());\n   viennacl::copy(ublas_m1, vcl_m1);\n   \n   // --------------------------------------------------------------------------            \n   std::cout << \"Rank 1 update\" << std::endl;\n   \n   ublas_m1 += ublas::outer_prod(ublas_v1, ublas_v2);\n   vcl_m1 += viennacl::linalg::outer_prod(vcl_v1, vcl_v2);\n   if( fabs(diff(ublas_m1, vcl_m1)) > epsilon )\n   {\n      std::cout << \"# Error at operation: rank 1 update\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_m1, vcl_m1)) << std::endl;\n      return EXIT_FAILURE;\n   }\n   \n   \n   \n   // --------------------------------------------------------------------------            \n   std::cout << \"Scaled rank 1 update\" << std::endl;\n   ublas_m1 += NumericT(4.2) * ublas::outer_prod(ublas_v1, ublas_v2);\n   vcl_m1 += NumericT(2.1) * viennacl::linalg::outer_prod(vcl_v1, vcl_v2);\n   vcl_m1 += viennacl::linalg::outer_prod(vcl_v1, vcl_v2) * NumericT(2.1);  //check proper compilation\n   if( fabs(diff(ublas_m1, vcl_m1)) > epsilon )\n   {\n      std::cout << \"# Error at operation: scaled rank 1 update\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_m1, vcl_m1)) << std::endl;\n      return EXIT_FAILURE;\n   }\n   \n   //reset vcl_matrix:\n   viennacl::copy(ublas_m1, vcl_m1);\n   \n   // --------------------------------------------------------------------------            \n   std::cout << \"Matrix-Vector product\" << std::endl;\n   ublas_v1 = viennacl::linalg::prod(ublas_m1, ublas_v2);\n   vcl_v1   = viennacl::linalg::prod(vcl_m1, vcl_v2);\n   \n   if( fabs(diff(ublas_v1, vcl_v1)) > epsilon )\n   {\n      std::cout << \"# Error at operation: matrix-vector product\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_v1, vcl_v1)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n   // --------------------------------------------------------------------------            \n   std::cout << \"Matrix-Vector product with scaled add\" << std::endl;\n   NumericT alpha = static_cast<NumericT>(2.786);\n   NumericT beta = static_cast<NumericT>(1.432);\n   viennacl::copy(ublas_v1.begin(), ublas_v1.end(), vcl_v1.begin());\n   viennacl::copy(ublas_v2.begin(), ublas_v2.end(), vcl_v2.begin());\n\n   ublas_v1 = alpha * viennacl::linalg::prod(ublas_m1, ublas_v2) + beta * ublas_v1;\n   vcl_v1   = alpha * viennacl::linalg::prod(vcl_m1, vcl_v2) + beta * vcl_v1;\n\n   if( fabs(diff(ublas_v1, vcl_v1)) > epsilon )\n   {\n      std::cout << \"# Error at operation: matrix-vector product with scaled additions\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_v1, vcl_v1)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n   // --------------------------------------------------------------------------            \n\n   viennacl::copy(ublas_v1.begin(), ublas_v1.end(), vcl_v1.begin());\n   viennacl::copy(ublas_v2.begin(), ublas_v2.end(), vcl_v2.begin());\n\n   std::cout << \"Transposed Matrix-Vector product\" << std::endl;\n   ublas_v2     = alpha * viennacl::linalg::prod(trans(ublas_m1), ublas_v1);  \n   vcl_v2 = alpha * viennacl::linalg::prod(trans(vcl_m1), vcl_v1);\n\n   if( fabs(diff(ublas_v2, vcl_v2)) > epsilon )\n   {\n      std::cout << \"# Error at operation: transposed matrix-vector product\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_v2, vcl_v2)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n\n   std::cout << \"Transposed Matrix-Vector product with scaled add\" << std::endl;\n   ublas_v2 = alpha * viennacl::linalg::prod(trans(ublas_m1), ublas_v1) + beta * ublas_v2;  \n   vcl_v2   = alpha * viennacl::linalg::prod(trans(vcl_m1), vcl_v1) + beta * vcl_v2;\n\n   if( fabs(diff(ublas_v2, vcl_v2)) > epsilon )\n   {\n      std::cout << \"# Error at operation: transposed matrix-vector product with scaled additions\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_v2, vcl_v2)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n   // --------------------------------------------------------------------------            \n\n   return retval;\n}\n\n\n\ntemplate <typename NumericT, typename Epsilon, \n          typename UblasMatrixType, typename UblasVectorType,\n          typename VCLMatrixType, typename VCLVectorType1>\nint test_solve(Epsilon const & epsilon,\n               UblasMatrixType & ublas_m1, UblasVectorType & ublas_v1,\n               VCLMatrixType & vcl_m1, VCLVectorType1 & vcl_v1)\n{\n   int retval = EXIT_SUCCESS;\n  \n   // sync data:\n   //viennacl::copy(ublas_v1.begin(), ublas_v1.end(), vcl_v1.begin());\n   viennacl::copy(ublas_v1, vcl_v1);\n   viennacl::copy(ublas_m1, vcl_m1);\n\n   /////////////////// test direct solvers ////////////////////////////\n   \n   //upper triangular:\n   std::cout << \"Upper triangular solver\" << std::endl;\n   ublas_v1 = ublas::solve(ublas_m1, ublas_v1, ublas::upper_tag());\n   vcl_v1 = viennacl::linalg::solve(vcl_m1, vcl_v1, viennacl::linalg::upper_tag());\n   if( fabs(diff(ublas_v1, vcl_v1)) > epsilon )\n   {\n      std::cout << \"# Error at operation: upper triangular solver\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_v1, vcl_v1)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n\n   //upper unit triangular:\n   std::cout << \"Upper unit triangular solver\" << std::endl;\n   viennacl::copy(ublas_v1, vcl_v1);\n   ublas_v1 = ublas::solve(ublas_m1, ublas_v1, ublas::unit_upper_tag());\n   vcl_v1 = viennacl::linalg::solve(vcl_m1, vcl_v1, viennacl::linalg::unit_upper_tag());\n   if( fabs(diff(ublas_v1, vcl_v1)) > epsilon )\n   {\n      std::cout << \"# Error at operation: unit upper triangular solver\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_v1, vcl_v1)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n\n   //lower triangular:\n   std::cout << \"Lower triangular solver\" << std::endl;\n   viennacl::copy(ublas_v1, vcl_v1);\n   ublas_v1 = ublas::solve(ublas_m1, ublas_v1, ublas::lower_tag());\n   vcl_v1 = viennacl::linalg::solve(vcl_m1, vcl_v1, viennacl::linalg::lower_tag());\n   if( fabs(diff(ublas_v1, vcl_v1)) > epsilon )\n   {\n      std::cout << \"# Error at operation: lower triangular solver\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_v1, vcl_v1)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n\n   //lower unit triangular:\n   std::cout << \"Lower unit triangular solver\" << std::endl;\n   viennacl::copy(ublas_v1, vcl_v1);\n   ublas_v1 = ublas::solve(ublas_m1, ublas_v1, ublas::unit_lower_tag());\n   vcl_v1 = viennacl::linalg::solve(vcl_m1, vcl_v1, viennacl::linalg::unit_lower_tag());\n   if( fabs(diff(ublas_v1, vcl_v1)) > epsilon )\n   {\n      std::cout << \"# Error at operation: unit lower triangular solver\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_v1, vcl_v1)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n\n\n\n\n\n   //transposed upper triangular:\n   std::cout << \"Transposed upper triangular solver\" << std::endl;\n   viennacl::copy(ublas_v1, vcl_v1);\n   ublas_v1 = ublas::solve(trans(ublas_m1), ublas_v1, ublas::upper_tag());\n   vcl_v1 = viennacl::linalg::solve(trans(vcl_m1), vcl_v1, viennacl::linalg::upper_tag());\n   if( fabs(diff(ublas_v1, vcl_v1)) > epsilon )\n   {\n      std::cout << \"# Error at operation: upper triangular solver\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_v1, vcl_v1)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n\n   //transposed upper unit triangular:\n   std::cout << \"Transposed unit upper triangular solver\" << std::endl;\n   viennacl::copy(ublas_v1, vcl_v1);\n   ublas_v1 = ublas::solve(trans(ublas_m1), ublas_v1, ublas::unit_upper_tag());\n   vcl_v1 = viennacl::linalg::solve(trans(vcl_m1), vcl_v1, viennacl::linalg::unit_upper_tag());\n   if( fabs(diff(ublas_v1, vcl_v1)) > epsilon )\n   {\n      std::cout << \"# Error at operation: unit upper triangular solver\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_v1, vcl_v1)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n\n   //transposed lower triangular:\n   std::cout << \"Transposed lower triangular solver\" << std::endl;\n   viennacl::copy(ublas_v1, vcl_v1);\n   ublas_v1 = ublas::solve(trans(ublas_m1), ublas_v1, ublas::lower_tag());\n   vcl_v1 = viennacl::linalg::solve(trans(vcl_m1), vcl_v1, viennacl::linalg::lower_tag());\n   if( fabs(diff(ublas_v1, vcl_v1)) > epsilon )\n   {\n      std::cout << \"# Error at operation: lower triangular solver\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_v1, vcl_v1)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n\n   //transposed lower unit triangular:\n   std::cout << \"Transposed unit lower triangular solver\" << std::endl;\n   viennacl::copy(ublas_v1, vcl_v1);\n   ublas_v1 = ublas::solve(trans(ublas_m1), ublas_v1, ublas::unit_lower_tag());\n   vcl_v1 = viennacl::linalg::solve(trans(vcl_m1), vcl_v1, viennacl::linalg::unit_lower_tag());\n   if( fabs(diff(ublas_v1, vcl_v1)) > epsilon )\n   {\n      std::cout << \"# Error at operation: unit lower triangular solver\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(ublas_v1, vcl_v1)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n   \n   return retval;\n}\n\n\n//\n// -------------------------------------------------------------\n//\ntemplate< typename NumericT, typename F, typename Epsilon >\nint test(Epsilon const& epsilon)\n{\n   int retval = EXIT_SUCCESS;\n   \n   std::size_t num_rows = 141;\n   std::size_t num_cols = 103;\n   \n   // --------------------------------------------------------------------------            \n   ublas::vector<NumericT> ublas_v1(num_rows);\n   for (std::size_t i = 0; i < ublas_v1.size(); ++i)\n     ublas_v1(i) = random<NumericT>();\n   ublas::vector<NumericT> ublas_v2 = ublas::scalar_vector<NumericT>(num_cols, NumericT(3.1415));\n\n  \n   ublas::matrix<NumericT> ublas_m1(ublas_v1.size(), ublas_v2.size());\n  \n   for (std::size_t i = 0; i < ublas_m1.size1(); ++i)\n      for (std::size_t j = 0; j < ublas_m1.size2(); ++j)\n         ublas_m1(i,j) = static_cast<NumericT>(0.1) * random<NumericT>();\n\n      \n   ublas::matrix<NumericT> ublas_m2(ublas_v1.size(), ublas_v1.size());\n  \n   for (std::size_t i = 0; i < ublas_m2.size1(); ++i)\n   {\n      for (std::size_t j = 0; j < ublas_m2.size2(); ++j)\n         ublas_m2(i,j) = static_cast<NumericT>(-0.1) * random<NumericT>();\n      ublas_m2(i, i) = static_cast<NumericT>(2) + random<NumericT>();\n   }\n\n      \n   viennacl::vector<NumericT> vcl_v1_native(ublas_v1.size());\n   viennacl::vector<NumericT> vcl_v1_large(4 * ublas_v1.size());\n   viennacl::vector_range< viennacl::vector<NumericT> > vcl_v1_range(vcl_v1_large, viennacl::range(3, ublas_v1.size() + 3));\n   viennacl::vector_slice< viennacl::vector<NumericT> > vcl_v1_slice(vcl_v1_large, viennacl::slice(2, 3, ublas_v1.size()));\n   \n   viennacl::vector<NumericT> vcl_v2_native(ublas_v2.size());\n   viennacl::vector<NumericT> vcl_v2_large(4 * ublas_v2.size());\n   viennacl::vector_range< viennacl::vector<NumericT> > vcl_v2_range(vcl_v2_large, viennacl::range(8, ublas_v2.size() + 8));\n   viennacl::vector_slice< viennacl::vector<NumericT> > vcl_v2_slice(vcl_v2_large, viennacl::slice(6, 2, ublas_v2.size()));\n   \n   viennacl::matrix<NumericT, F> vcl_m1_native(ublas_m1.size1(), ublas_m1.size2());\n   viennacl::matrix<NumericT, F> vcl_m1_large(4 * ublas_m1.size1(), 4 * ublas_m1.size2());\n   viennacl::matrix_range< viennacl::matrix<NumericT, F> > vcl_m1_range(vcl_m1_large,\n                                                                        viennacl::range(8, ublas_m1.size1() + 8),\n                                                                        viennacl::range(ublas_m1.size2(), 2 * ublas_m1.size2()) );\n   viennacl::matrix_slice< viennacl::matrix<NumericT, F> > vcl_m1_slice(vcl_m1_large,\n                                                                        viennacl::slice(6, 2, ublas_m1.size1()),\n                                                                        viennacl::slice(ublas_m1.size2(), 2, ublas_m1.size2()) );\n   \n   viennacl::matrix<NumericT, F> vcl_m2_native(ublas_m2.size1(), ublas_m2.size2());\n   viennacl::matrix<NumericT, F> vcl_m2_large(4 * ublas_m2.size1(), 4 * ublas_m2.size2());\n   viennacl::matrix_range< viennacl::matrix<NumericT, F> > vcl_m2_range(vcl_m2_large,\n                                                                        viennacl::range(8, ublas_m2.size1() + 8),\n                                                                        viennacl::range(ublas_m2.size2(), 2 * ublas_m2.size2()) );\n   viennacl::matrix_slice< viennacl::matrix<NumericT, F> > vcl_m2_slice(vcl_m2_large,\n                                                                        viennacl::slice(6, 2, ublas_m2.size1()),\n                                                                        viennacl::slice(ublas_m2.size2(), 2, ublas_m2.size2()) );\n\n   \n/*   std::cout << \"Matrix resizing (to larger)\" << std::endl;\n   matrix.resize(2*num_rows, 2*num_cols, true);\n   for (unsigned int i = 0; i < matrix.size1(); ++i)\n   {\n      for (unsigned int j = (i<result.size() ? rhs.size() : 0); j < matrix.size2(); ++j)\n         matrix(i,j) = 0;\n   }\n   vcl_matrix.resize(2*num_rows, 2*num_cols, true);\n   viennacl::copy(vcl_matrix, matrix);\n   if( fabs(diff(matrix, vcl_matrix)) > epsilon )\n   {\n      std::cout << \"# Error at operation: matrix resize (to larger)\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(matrix, vcl_matrix)) << std::endl;\n      return EXIT_FAILURE;\n   }\n   \n   matrix(12, 14) = NumericT(1.9);\n   matrix(19, 16) = NumericT(1.0);\n   matrix (13, 15) =  NumericT(-9);\n   vcl_matrix(12, 14) = NumericT(1.9);\n   vcl_matrix(19, 16) = NumericT(1.0);\n   vcl_matrix (13, 15) =  NumericT(-9);\n   \n   std::cout << \"Matrix resizing (to smaller)\" << std::endl;\n   matrix.resize(result.size(), rhs.size(), true);\n   vcl_matrix.resize(result.size(), rhs.size(), true);\n   if( fabs(diff(matrix, vcl_matrix)) > epsilon )\n   {\n      std::cout << \"# Error at operation: matrix resize (to smaller)\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(matrix, vcl_matrix)) << std::endl;\n      return EXIT_FAILURE;\n   }\n   */\n\n   //\n   // Run a bunch of tests for rank-1-updates, matrix-vector products\n   //\n   std::cout << \"------------ Testing rank-1-updates and matrix-vector products ------------------\" << std::endl;\n   \n   std::cout << \"* m = full, v1 = full, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_native, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = full, v1 = full, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_native, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = full, v1 = full, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_native, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   // v1 = range\n   \n   \n   std::cout << \"* m = full, v1 = range, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_range, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = full, v1 = range, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_range, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = full, v1 = range, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_range, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   \n   // v1 = slice\n   \n   std::cout << \"* m = full, v1 = slice, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_slice, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = full, v1 = slice, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_slice, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = full, v1 = slice, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_native, vcl_v1_slice, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   ///////////////////////////// matrix_range\n     \n   std::cout << \"* m = range, v1 = full, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_native, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = range, v1 = full, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_native, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = range, v1 = full, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_native, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   // v1 = range\n   \n   \n   std::cout << \"* m = range, v1 = range, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_range, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = range, v1 = range, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_range, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = range, v1 = range, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_range, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   \n   // v1 = slice\n   \n   std::cout << \"* m = range, v1 = slice, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_slice, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = range, v1 = slice, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_slice, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = range, v1 = slice, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_range, vcl_v1_slice, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   ///////////////////////////// matrix_slice\n\n   std::cout << \"* m = slice, v1 = full, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_native, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = slice, v1 = full, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_native, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = slice, v1 = full, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_native, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   // v1 = range\n   \n   \n   std::cout << \"* m = slice, v1 = range, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_range, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = slice, v1 = range, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_range, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = slice, v1 = range, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_range, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n\n   \n   // v1 = slice\n   \n   std::cout << \"* m = slice, v1 = slice, v2 = full\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_slice, vcl_v2_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = slice, v1 = slice, v2 = range\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_slice, vcl_v2_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   std::cout << \"* m = slice, v1 = slice, v2 = slice\" << std::endl;\n   retval = test_prod_rank1<NumericT>(epsilon,\n                                      ublas_m1, ublas_v1, ublas_v2,\n                                      vcl_m1_slice, vcl_v1_slice, vcl_v2_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   \n   \n   //\n   // Testing triangular solve() routines\n   //\n     \n   std::cout << \"------------ Testing triangular solves ------------------\" << std::endl;\n     \n   std::cout << \"* m = full, v1 = full\" << std::endl;\n   retval = test_solve<NumericT>(epsilon,\n                                 ublas_m2, ublas_v1,\n                                 vcl_m2_native, vcl_v1_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n     \n   std::cout << \"* m = full, v1 = range\" << std::endl;\n   retval = test_solve<NumericT>(epsilon,\n                                 ublas_m2, ublas_v1,\n                                 vcl_m2_native, vcl_v1_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   std::cout << \"* m = full, v1 = slice\" << std::endl;\n   retval = test_solve<NumericT>(epsilon,\n                                 ublas_m2, ublas_v1,\n                                 vcl_m2_native, vcl_v1_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   ///////// matrix_range\n   \n     \n   std::cout << \"* m = range, v1 = full\" << std::endl;\n   retval = test_solve<NumericT>(epsilon,\n                                 ublas_m2, ublas_v1,\n                                 vcl_m2_range, vcl_v1_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n     \n   std::cout << \"* m = range, v1 = range\" << std::endl;\n   retval = test_solve<NumericT>(epsilon,\n                                 ublas_m2, ublas_v1,\n                                 vcl_m2_range, vcl_v1_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   std::cout << \"* m = range, v1 = slice\" << std::endl;\n   retval = test_solve<NumericT>(epsilon,\n                                 ublas_m2, ublas_v1,\n                                 vcl_m2_range, vcl_v1_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   //////// matrix_slice\n     \n   std::cout << \"* m = slice, v1 = full\" << std::endl;\n   retval = test_solve<NumericT>(epsilon,\n                                 ublas_m2, ublas_v1,\n                                 vcl_m2_slice, vcl_v1_native);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n     \n   std::cout << \"* m = slice, v1 = range\" << std::endl;\n   retval = test_solve<NumericT>(epsilon,\n                                 ublas_m2, ublas_v1,\n                                 vcl_m2_slice, vcl_v1_range);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n\n   std::cout << \"* m = slice, v1 = slice\" << std::endl;\n   retval = test_solve<NumericT>(epsilon,\n                                 ublas_m2, ublas_v1,\n                                 vcl_m2_slice, vcl_v1_slice);\n   if (retval == EXIT_FAILURE)\n   {\n     std::cout << \" --- FAILED! ---\" << std::endl;\n     return retval;\n   }\n   else\n     std::cout << \" --- PASSED ---\" << std::endl;\n     \n     \n   \n   \n   \n   \n   \n   ////////////// Final test for full LU decomposition:\n   \n   //full solver:\n   std::cout << \"Full solver\" << std::endl;\n   unsigned int lu_dim = 100;\n   ublas::matrix<NumericT> square_matrix(lu_dim, lu_dim);\n   ublas::vector<NumericT> lu_rhs(lu_dim);\n   viennacl::matrix<NumericT, F> vcl_square_matrix(lu_dim, lu_dim);\n   viennacl::vector<NumericT> vcl_lu_rhs(lu_dim);\n\n   for (std::size_t i=0; i<lu_dim; ++i)\n     for (std::size_t j=0; j<lu_dim; ++j)\n       square_matrix(i,j) = -static_cast<NumericT>(0.5) * random<NumericT>();\n\n   //put some more weight on diagonal elements:\n   for (std::size_t j=0; j<lu_dim; ++j)\n   {\n     square_matrix(j,j) = static_cast<NumericT>(20.0) + random<NumericT>();\n     lu_rhs(j) = random<NumericT>();\n   }\n   \n   viennacl::copy(square_matrix, vcl_square_matrix);\n   viennacl::copy(lu_rhs, vcl_lu_rhs);\n   \n   //ublas::\n   ublas::lu_factorize(square_matrix);\n   ublas::inplace_solve (square_matrix, lu_rhs, ublas::unit_lower_tag ());\n   ublas::inplace_solve (square_matrix, lu_rhs, ublas::upper_tag ());\n\n   // ViennaCL:\n   viennacl::linalg::lu_factorize(vcl_square_matrix);\n   //viennacl::copy(square_matrix, vcl_square_matrix);\n   viennacl::linalg::lu_substitute(vcl_square_matrix, vcl_lu_rhs);\n\n   if( fabs(diff(lu_rhs, vcl_lu_rhs)) > epsilon )\n   {\n      std::cout << \"# Error at operation: dense solver\" << std::endl;\n      std::cout << \"  diff: \" << fabs(diff(lu_rhs, vcl_lu_rhs)) << std::endl;\n      retval = EXIT_FAILURE;\n   }\n   \n   \n\n   return retval;\n}\n//\n// -------------------------------------------------------------\n//\nint main()\n{\n   std::cout << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << \"## Test :: Matrix\" << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << std::endl;\n\n   int retval = EXIT_SUCCESS;\n\n   std::cout << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << std::endl;\n   {\n      typedef float NumericT;\n      NumericT epsilon = NumericT(1.0E-3);\n      std::cout << \"# Testing setup:\" << std::endl;\n      std::cout << \"  eps:     \" << epsilon << std::endl;\n      std::cout << \"  numeric: float\" << std::endl;\n      std::cout << \"  layout: row-major\" << std::endl;\n      retval = test<NumericT, viennacl::row_major>(epsilon);\n      if( retval == EXIT_SUCCESS )\n         std::cout << \"# Test passed\" << std::endl;\n      else\n         return retval;\n   }\n   std::cout << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << std::endl;\n   {\n      typedef float NumericT;\n      NumericT epsilon = NumericT(1.0E-3);\n      std::cout << \"# Testing setup:\" << std::endl;\n      std::cout << \"  eps:     \" << epsilon << std::endl;\n      std::cout << \"  numeric: float\" << std::endl;\n      std::cout << \"  layout: column-major\" << std::endl;\n      retval = test<NumericT, viennacl::column_major>(epsilon);\n      if( retval == EXIT_SUCCESS )\n         std::cout << \"# Test passed\" << std::endl;\n      else\n         return retval;\n   }\n   std::cout << std::endl;\n   std::cout << \"----------------------------------------------\" << std::endl;\n   std::cout << std::endl;\n   \n   \n#ifdef VIENNACL_HAVE_OPENCL   \n   if( viennacl::ocl::current_device().double_support() )\n#endif\n   {\n      {\n         typedef double NumericT;\n         NumericT epsilon = 1.0E-11;\n         std::cout << \"# Testing setup:\" << std::endl;\n         std::cout << \"  eps:     \" << epsilon << std::endl;\n         std::cout << \"  numeric: double\" << std::endl;\n         std::cout << \"  layout: row-major\" << std::endl;\n         retval = test<NumericT, viennacl::row_major>(epsilon);\n            if( retval == EXIT_SUCCESS )\n               std::cout << \"# Test passed\" << std::endl;\n            else\n              return retval;\n      }\n      std::cout << std::endl;\n      std::cout << \"----------------------------------------------\" << std::endl;\n      std::cout << std::endl;\n      {\n         typedef double NumericT;\n         NumericT epsilon = 1.0E-11;\n         std::cout << \"# Testing setup:\" << std::endl;\n         std::cout << \"  eps:     \" << epsilon << std::endl;\n         std::cout << \"  numeric: double\" << std::endl;\n         std::cout << \"  layout: column-major\" << std::endl;\n         retval = test<NumericT, viennacl::column_major>(epsilon);\n            if( retval == EXIT_SUCCESS )\n               std::cout << \"# Test passed\" << std::endl;\n            else\n              return retval;\n      }\n      std::cout << std::endl;\n      std::cout << \"----------------------------------------------\" << std::endl;\n      std::cout << std::endl;\n   }\n   \n   std::cout << std::endl;\n   std::cout << \"------- Test completed --------\" << std::endl;\n   std::cout << std::endl;\n   \n   \n   return retval;\n}\n", "meta": {"hexsha": "ce082781e261969bfaee8c758aa4e8ba09b6bbaf", "size": 38821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/matrix-vector.cpp", "max_stars_repo_name": "bollig/viennacl", "max_stars_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-21T08:33:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-21T08:33:10.000Z", "max_issues_repo_path": "tests/src/matrix-vector.cpp", "max_issues_repo_name": "bollig/viennacl", "max_issues_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/matrix-vector.cpp", "max_forks_repo_name": "bollig/viennacl", "max_forks_repo_head_hexsha": "6dac70e558ed42abe63d8c5bfd08465aafeda859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1461824953, "max_line_length": 130, "alphanum_fraction": 0.519924783, "num_tokens": 11206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.44925580094257067}}
{"text": "// Demonstrating the use of ranges built using istream_iterator with a custom stream operator\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <iterator>\n#include <cmath>\n\n#include <boost/geometry.hpp>\n\n#include <range/v3/all.hpp>\n\n#include \"nmea.h\"\n\nint main() {\n    using namespace std;\n\n    string test(\"$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,,*47\");\n    test +=   \"\\n$GPGGA,170834,4124.8963,N,08151.6838,W,1,05,1.5,280.2,M,-34.0,M,,,*59\";\n\n    using namespace ranges::v3;\n    istringstream ss(test);\n    ranges::for_each(istream_range<gga_t>(ss),\n                     [](gga_t const& g) {\n                         cout << g << \"\\n\";\n                     });\n\n    // produce a filtered range of Boost Geometry world coordinates using Range views\n    using namespace boost::geometry;\n    typedef model::point<double, 2, cs::geographic<degree> > coord_t;\n    ss = istringstream(test);   // reset stream\n    auto construct_coord = [](gga_t const& g) {\n        double lat_deg = floor(g.latitude / 100.0);\n        if (g.lat_hemi == 'W') {\n            lat_deg = -lat_deg;\n        }\n        double long_deg = floor(g.longitude / 100.0);\n        if (g.lat_hemi == 'S') {\n            long_deg = -long_deg;\n        }\n        return coord_t(lat_deg, long_deg);\n    };\n    auto coord_range =\n        istream_range<gga_t>(ss) |\n        ranges::view::remove_if([](gga_t const& g) {\n                return g.dilution > 1.0;\n            }) |\n        ranges::view::transform(construct_coord);\n\n    // print out resulting Geometry coordinates (only one passes dilution test)\n    ranges::for_each(coord_range,\n                     [](coord_t const& pt) {\n                         std::cout << wkt(pt) << \"\\n\";\n                     });\n}\n", "meta": {"hexsha": "6a11acbc5e06ec80b8e9e9396102e0f511eac5eb", "size": 1761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "custom_stream_operator.cpp", "max_stars_repo_name": "jefftrull/SequencesFromStreams", "max_stars_repo_head_hexsha": "44a903c5c4c322280053dd16fa47512bda87f6ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-14T12:04:07.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-14T12:04:07.000Z", "max_issues_repo_path": "custom_stream_operator.cpp", "max_issues_repo_name": "jefftrull/SequencesFromStreams", "max_issues_repo_head_hexsha": "44a903c5c4c322280053dd16fa47512bda87f6ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "custom_stream_operator.cpp", "max_forks_repo_name": "jefftrull/SequencesFromStreams", "max_forks_repo_head_hexsha": "44a903c5c4c322280053dd16fa47512bda87f6ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0181818182, "max_line_length": 93, "alphanum_fraction": 0.5684270301, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.44922469088316413}}
{"text": "/*!\n * Exact calculation of the overlap volume of spheres and mesh elements.\n * http://dx.doi.org/10.1016/j.jcp.2016.02.003\n *\n * Copyright (C) 2015-2017 Severin Strobl <severin.strobl@fau.de>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef OVERLAP_HPP\n#define OVERLAP_HPP\n\n// Eigen\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n// C++\n#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cassert>\n#include <cmath>\n#include <iterator>\n#include <limits>\n#include <numeric>\n#include <stdexcept>\n#include <type_traits>\n#include <utility>\n\n// typedefs\ntypedef double scalar_t;\ntypedef Eigen::Matrix<scalar_t, 3, 1, Eigen::DontAlign> vector_t;\ntypedef Eigen::Matrix<scalar_t, 2, 1, Eigen::DontAlign> vector2_t;\n\n// Pretty-printing of Eigen matrices.\nstatic const Eigen::IOFormat pretty(\n    Eigen::StreamPrecision, Eigen::DontAlignCols, \" \", \";\\n\", \"\", \"\", \"[\", \"]\");\n\n// constants\nconst scalar_t pi = scalar_t(4) * std::atan(scalar_t(1.0));\n\nnamespace detail {\n\nstatic const scalar_t tinyEpsilon(2 * std::numeric_limits<scalar_t>::epsilon());\n\nstatic const scalar_t mediumEpsilon(1e2 * tinyEpsilon);\nstatic const scalar_t largeEpsilon(1e-10);\n\n// Robust calculation of the normal vector of a polygon using Newell's method\n// and a pre-calculated center.\n// Ref: Christer Ericson - Real-Time Collision Detection (2005)\ntemplate <typename Iterator>\ninline vector_t normalNewell(\n    Iterator begin, Iterator end, const vector_t& center) {\n  const size_t count = end - begin;\n  vector_t n(vector_t::Zero());\n\n  for (size_t i = 0; i < count; ++i)\n    n += (*(begin + i) - center).cross(*(begin + ((i + 1) % count)) - center);\n\n  scalar_t length = n.stableNorm();\n\n  if (length)\n    return n / length;\n  else\n    return n;\n}\n\n// This implementation of double_prec is based on:\n// T.J. Dekker, A floating-point technique for extending the available\n// precision, http://dx.doi.org/10.1007/BF01397083\n\ntemplate <typename T>\nstruct double_prec_constant;\n\ntemplate <>\nstruct double_prec_constant<float> {\n  // Constant used to split double precision values:\n  // 2^(24 - 24/2) + 1 = 2^12 + 1 = 4097\n  static const uint32_t value = 4097;\n};\n\ntemplate <>\nstruct double_prec_constant<double> {\n  // Constant used to split double precision values:\n  // 2^(53 - int(53/2)) + 1 = 2^27 + 1 = 134217729\n  static const uint32_t value = 134217729;\n};\n\n// For GCC and Clang an attribute can be used to control the FP precision...\n#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && \\\n    !defined(__INTEL_COMPILER)\n#define ENFORCE_EXACT_FPMATH_ATTR __attribute__((__target__(\"ieee-fp\")))\n#else\n#define ENFORCE_EXACT_FPMATH_ATTR\n#endif\n\n// ... whereas ICC requires a pragma.\n#if defined(__ICC) || defined(__INTEL_COMPILER)\n#define ENFORCE_EXACT_FPMATH_ATTR\n#define USE_EXACT_FPMATH_PRAGMA 1\n#endif\n\ntemplate <typename T>\nclass double_prec;\n\ntemplate <typename T>\ninline double_prec<T> operator+(\n    const double_prec<T>& lhs,\n    const double_prec<T>& rhs) ENFORCE_EXACT_FPMATH_ATTR;\n\ntemplate <typename T>\ninline double_prec<T> operator-(\n    const double_prec<T>& lhs,\n    const double_prec<T>& rhs) ENFORCE_EXACT_FPMATH_ATTR;\n\ntemplate <typename T>\ninline double_prec<T> operator*(\n    const double_prec<T>& lhs,\n    const double_prec<T>& rhs) ENFORCE_EXACT_FPMATH_ATTR;\n\ntemplate <typename T>\nclass double_prec {\n private:\n  static const uint32_t c = detail::double_prec_constant<T>::value;\n\n  template <typename TF>\n  friend double_prec<TF> operator+(\n      const double_prec<TF>&, const double_prec<TF>&);\n\n  template <typename TF>\n  friend double_prec<TF> operator-(\n      const double_prec<TF>&, const double_prec<TF>&);\n\n  template <typename TF>\n  friend double_prec<TF> operator*(\n      const double_prec<TF>&, const double_prec<TF>&);\n\n public:\n  inline double_prec() : h_(0), l_(0) {}\n\n  // This constructor requires floating point operations in accordance\n  // with IEEE754 to perform the proper splitting. To allow full\n  // optimization of all other parts of the code, precise floating point\n  // ops are only requested here. Unfortunately the way to do this is\n  // extremely compiler dependent.\n  inline double_prec(const T& val) ENFORCE_EXACT_FPMATH_ATTR : h_(0), l_(0) {\n#ifdef USE_EXACT_FPMATH_PRAGMA\n#pragma float_control(precise, on)\n#endif\n\n    T p = val * T(c);\n    h_ = (val - p) + p;\n    l_ = val - h_;\n  }\n\n private:\n  inline explicit double_prec(const T& h, const T& l) : h_(h), l_(l) {}\n\n public:\n  inline const T& high() const {\n    return h_;\n  }\n\n  inline const T& low() const {\n    return l_;\n  }\n\n  inline T value() const {\n    return h_ + l_;\n  }\n\n  template <typename TOther>\n  inline TOther convert() const {\n    return TOther(h_) + TOther(l_);\n  }\n\n private:\n  T h_;\n  T l_;\n};\n\ntemplate <typename T>\ninline double_prec<T> operator+(\n    const double_prec<T>& lhs, const double_prec<T>& rhs) {\n#ifdef USE_EXACT_FPMATH_PRAGMA\n#pragma float_control(precise, on)\n#endif\n\n  T h = lhs.h_ + rhs.h_;\n  T l = std::abs(lhs.h_) >= std::abs(rhs.h_)\n            ? ((((lhs.h_ - h) + rhs.h_) + lhs.l_) + rhs.l_)\n            : ((((rhs.h_ - h) + lhs.h_) + rhs.l_) + lhs.l_);\n\n  T c = h + l;\n\n  return double_prec<T>(c, (h - c) + l);\n}\n\ntemplate <typename T>\ninline double_prec<T> operator-(\n    const double_prec<T>& lhs, const double_prec<T>& rhs) {\n#ifdef USE_EXACT_FPMATH_PRAGMA\n#pragma float_control(precise, on)\n#endif\n\n  T h = lhs.h_ - rhs.h_;\n  T l = std::abs(lhs.h_) >= std::abs(rhs.h_)\n            ? ((((lhs.h_ - h) - rhs.h_) - rhs.l_) + lhs.l_)\n            : ((((-rhs.h_ - h) + lhs.h_) + lhs.l_) - rhs.l_);\n\n  T c = h + l;\n\n  return double_prec<T>(c, (h - c) + l);\n}\n\ntemplate <typename T>\ninline double_prec<T> operator*(\n    const double_prec<T>& lhs, const double_prec<T>& rhs) {\n#ifdef USE_EXACT_FPMATH_PRAGMA\n#pragma float_control(precise, on)\n#endif\n\n  double_prec<T> l(lhs.h_);\n  double_prec<T> r(rhs.h_);\n\n  T p = l.h_ * r.h_;\n  T q = l.h_ * r.l_ + l.l_ * r.h_;\n  T v = p + q;\n\n  double_prec<T> c(v, ((p - v) + q) + l.l_ * r.l_);\n  c.l_ = ((lhs.h_ + lhs.l_) * rhs.l_ + lhs.l_ * rhs.h_) + c.l_;\n  T z = c.value();\n\n  return double_prec<T>(z, (c.h_ - z) + c.l_);\n}\n\n// Ref: J.R. Shewchuk - Lecture Notes on Geometric Robustness\n//      http://www.cs.berkeley.edu/~jrs/meshpapers/robnotes.pdf\ninline scalar_t orient2D(\n    const vector2_t& a, const vector2_t& b, const vector2_t& c) {\n  typedef double_prec<scalar_t> real_t;\n\n  real_t a0(a[0]);\n  real_t a1(a[1]);\n  real_t b0(b[0]);\n  real_t b1(b[1]);\n  real_t c0(c[0]);\n  real_t c1(c[1]);\n\n  real_t result = (a0 - c0) * (b1 - c1) - (a1 - c1) * (b0 - c0);\n\n  return result.convert<scalar_t>();\n}\n\n// Numerically robust calculation of the normal of the triangle defined by\n// the points a, b, and c.\n// Ref: J.R. Shewchuk - Lecture Notes on Geometric Robustness\n//      http://www.cs.berkeley.edu/~jrs/meshpapers/robnotes.pdf\ninline vector_t triangleNormal(\n    const vector_t& a, const vector_t& b, const vector_t& c) {\n  scalar_t xy = orient2D(\n      vector2_t(a[0], a[1]), vector2_t(b[0], b[1]), vector2_t(c[0], c[1]));\n\n  scalar_t yz = orient2D(\n      vector2_t(a[1], a[2]), vector2_t(b[1], b[2]), vector2_t(c[1], c[2]));\n\n  scalar_t zx = orient2D(\n      vector2_t(a[2], a[0]), vector2_t(b[2], b[0]), vector2_t(c[2], c[0]));\n\n  return vector_t(yz, zx, xy).normalized();\n}\n\n// Numerically robust routine to calculate the angle between normalized\n// vectors.\n// Ref: http://www.plunk.org/~hatch/rightway.php\ninline scalar_t angle(const vector_t& v0, const vector_t& v1) {\n  if (v0.dot(v1) < scalar_t(0))\n    return pi - scalar_t(2) * std::asin(scalar_t(0.5) * (v0 + v1).stableNorm());\n  else\n    return scalar_t(2) * std::asin(scalar_t(0.5) * (v0 - v1).stableNorm());\n}\n\ntemplate <typename Derived0, typename Derived1>\ninline std::array<vector_t, 2> gramSchmidt(\n    const Eigen::MatrixBase<Derived0>& arg0,\n    const Eigen::MatrixBase<Derived1>& arg1) {\n  vector_t v0(arg0.normalized());\n  vector_t v1(arg1);\n\n  std::array<vector_t, 2> result;\n  result[0] = v0;\n  result[1] = (v1 - v1.dot(v0) * v0).normalized();\n\n  return result;\n}\n\ninline scalar_t clamp(\n    scalar_t value, scalar_t min, scalar_t max, scalar_t limit) {\n  assert(min <= max && limit >= scalar_t(0));\n\n  value = (value < min && value > (min - limit)) ? min : value;\n  value = (value > max && value < (max + limit)) ? max : value;\n\n  return value;\n}\n\n} // namespace detail\n\nclass Transformation {\n public:\n  Transformation(const vector_t& t, const scalar_t& s)\n      : translation(t), scaling(s) {}\n\n  vector_t translation;\n  scalar_t scaling;\n};\n\ntemplate <size_t VertexCount>\nclass Polygon {\n private:\n  static_assert(\n      VertexCount >= 3 && VertexCount <= 4,\n      \"Only triangles and quadrilateral are supported.\");\n\n public:\n  static const size_t vertex_count = VertexCount;\n\n protected:\n  Polygon() : vertices(), center(), normal(), area() {}\n\n  template <typename... Types>\n  Polygon(const vector_t& v0, Types... verts)\n      : vertices{{v0, verts...}}, center(), normal(), area() {\n    center = scalar_t(1.0 / vertex_count) *\n             std::accumulate(\n                 vertices.begin(), vertices.end(), vector_t::Zero().eval());\n\n    // For a quadrilateral, Newell's method can be simplified\n    // significantly.\n    // Ref: Christer Ericson - Real-Time Collision Detection (2005)\n    if (VertexCount == 4) {\n      normal = ((vertices[2] - vertices[0]).cross(vertices[3] - vertices[1]))\n                   .normalized();\n    } else {\n      normal = detail::normalNewell(vertices.begin(), vertices.end(), center);\n    }\n  }\n\n  void apply(const Transformation& t) {\n    for (auto& v : vertices)\n      v = t.scaling * (v + t.translation);\n\n    center = t.scaling * (center + t.translation);\n  }\n\n public:\n  bool isPlanar(const scalar_t epsilon = detail::largeEpsilon) const {\n    if (VertexCount == 3) return true;\n\n    for (auto& v : vertices)\n      if (std::abs(normal.dot(v - center)) > epsilon) return false;\n\n    return true;\n  }\n\n public:\n  std::array<vector_t, vertex_count> vertices;\n  vector_t center;\n  vector_t normal;\n  scalar_t area;\n};\n\nclass Triangle : public Polygon<3> {\n public:\n  Triangle() : Polygon<3>() {}\n\n  template <typename... Types>\n  Triangle(const vector_t& v0, Types... verts) : Polygon<3>(v0, verts...) {\n    init();\n  }\n\n  void apply(const Transformation& t) {\n    Polygon<3>::apply(t);\n    init();\n  }\n\n private:\n  void init() {\n    area = scalar_t(0.5) *\n           ((vertices[1] - vertices[0]).cross(vertices[2] - vertices[0]))\n               .stableNorm();\n  }\n};\n\nclass Quadrilateral : public Polygon<4> {\n public:\n  Quadrilateral() : Polygon<4>() {}\n\n  template <typename... Types>\n  Quadrilateral(const vector_t& v0, Types... verts) : Polygon<4>(v0, verts...) {\n    init();\n  }\n\n  void apply(const Transformation& t) {\n    Polygon<4>::apply(t);\n    init();\n  }\n\n private:\n  void init() {\n    area = scalar_t(0.5) *\n           (((vertices[1] - vertices[0]).cross(vertices[2] - vertices[0]))\n                .stableNorm() +\n            ((vertices[2] - vertices[0]).cross(vertices[3] - vertices[0]))\n                .stableNorm());\n  }\n};\n\n// Forward declarations of the mesh elements.\nclass Tetrahedron;\nclass Wedge;\nclass Hexahedron;\n\nnamespace detail {\n\n// Some tricks are required to keep this code header-only.\ntemplate <typename T, typename Nil>\nstruct mappings;\n\ntemplate <typename Nil>\nstruct mappings<Tetrahedron, Nil> {\n  // Map edges of a tetrahedron to vertices and faces.\n  static const uint32_t edge_mapping[6][2][2];\n\n  // Map vertices of a tetrahedron to edges and faces.\n  // 0: local IDs of the edges intersecting at this vertex\n  // 1: 0 if the edge is pointing away from the vertex, 1 otherwise\n  // 2: faces joining at the vertex\n  static const uint32_t vertex_mapping[4][3][3];\n\n  // This mapping contains the three sets of the two edges for each of the\n  // faces joining at a vertex. The indices are mapped to the local edge IDs\n  // using the first value field of the 'vertex_mapping' table.\n  static const uint32_t face_mapping[3][2];\n};\n\ntemplate <typename Nil>\nconst uint32_t mappings<Tetrahedron, Nil>::edge_mapping[6][2][2] = {\n    {{0, 1}, {0, 1}}, {{1, 2}, {0, 2}}, {{2, 0}, {0, 3}},\n    {{0, 3}, {1, 3}}, {{1, 3}, {1, 2}}, {{2, 3}, {2, 3}}};\n\ntemplate <typename Nil>\nconst uint32_t mappings<Tetrahedron, Nil>::vertex_mapping[4][3][3] = {\n    {{0, 2, 3}, {0, 1, 0}, {0, 1, 3}},\n    {{0, 1, 4}, {1, 0, 0}, {0, 1, 2}},\n    {{1, 2, 5}, {1, 0, 0}, {0, 2, 3}},\n    {{3, 4, 5}, {1, 1, 1}, {1, 3, 2}}};\n\ntemplate <typename Nil>\nconst uint32_t mappings<Tetrahedron, Nil>::face_mapping[3][2] = {\n    {0, 1}, {0, 2}, {1, 2}};\n\ntypedef mappings<Tetrahedron, void> tet_mappings;\n\n} // namespace detail\n\nclass Tetrahedron : public detail::tet_mappings {\n public:\n  template <typename... Types>\n  Tetrahedron(const vector_t& v0, Types... verts)\n      : vertices{{v0, verts...}}, faces(), center(), volume() {\n#ifndef NDEBUG\n    // Make sure the ordering of the vertices is correct.\n    assert(\n        (vertices[1] - vertices[0])\n            .cross(vertices[2] - vertices[0])\n            .dot(vertices[3] - vertices[0]) >= scalar_t(0));\n#endif // NDEBUG\n\n    init();\n  }\n\n  Tetrahedron(const std::array<vector_t, 4>& verts)\n      : vertices(verts), faces(), center(), volume() {\n    init();\n  }\n\n  Tetrahedron()\n      : vertices{{vector_t::Zero(), vector_t::Zero(), vector_t::Zero(), vector_t::Zero()}}\n      , faces()\n      , center()\n      , volume() {}\n\n  void apply(const Transformation& t) {\n    for (auto& v : vertices)\n      v = t.scaling * (v + t.translation);\n\n    for (auto& f : faces)\n      f.apply(t);\n\n    center = scalar_t(0.25) *\n             std::accumulate(\n                 vertices.begin(), vertices.end(), vector_t::Zero().eval());\n\n    volume = calcVolume();\n  }\n\n  scalar_t surfaceArea() const {\n    scalar_t area(0);\n    for (const auto& f : faces)\n      area += f.area;\n\n    return area;\n  }\n\n private:\n  void init() {\n    // 0: v2, v1, v0\n    faces[0] = Triangle(vertices[2], vertices[1], vertices[0]);\n\n    // 1: v0, v1, v3\n    faces[1] = Triangle(vertices[0], vertices[1], vertices[3]);\n\n    // 2: v1, v2, v3\n    faces[2] = Triangle(vertices[1], vertices[2], vertices[3]);\n\n    // 3: v2, v0, v3\n    faces[3] = Triangle(vertices[2], vertices[0], vertices[3]);\n\n    center = scalar_t(0.25) *\n             std::accumulate(\n                 vertices.begin(), vertices.end(), vector_t::Zero().eval());\n\n    volume = calcVolume();\n  }\n\n  scalar_t calcVolume() const {\n    return scalar_t(1.0 / 6.0) *\n           std::abs((vertices[0] - vertices[3])\n                        .dot((vertices[1] - vertices[3])\n                                 .cross(vertices[2] - vertices[3])));\n  }\n\n public:\n  std::array<vector_t, 4> vertices;\n  std::array<Triangle, 4> faces;\n  vector_t center;\n  scalar_t volume;\n};\n\nnamespace detail {\n\ntemplate <typename Nil>\nstruct mappings<Wedge, Nil> {\n  // Map edges of a wedge to vertices and faces.\n  static const uint32_t edge_mapping[9][2][2];\n\n  // Map vertices of a wedge to edges and faces.\n  // 0: local IDs of the edges intersecting at this vertex\n  // 1: 0 if the edge is pointing away from the vertex, 1 otherwise\n  // 2: faces joining at the vertex\n  static const uint32_t vertex_mapping[6][3][3];\n\n  // This mapping contains the three sets of the two edges for each of the\n  // faces joining at a vertex. The indices are mapped to the local edge IDs\n  // using the first value field of the 'vertex_mapping' table.\n  static const uint32_t face_mapping[3][2];\n};\n\ntemplate <typename Nil>\nconst uint32_t mappings<Wedge, Nil>::edge_mapping[9][2][2] = {\n    {{0, 1}, {0, 1}}, {{1, 2}, {0, 2}}, {{2, 0}, {0, 3}},\n    {{0, 3}, {1, 3}}, {{1, 4}, {1, 2}}, {{2, 5}, {2, 3}},\n    {{3, 4}, {1, 4}}, {{4, 5}, {2, 4}}, {{5, 3}, {3, 4}}};\n\ntemplate <typename Nil>\nconst uint32_t mappings<Wedge, Nil>::vertex_mapping[6][3][3] = {\n    {{0, 2, 3}, {0, 1, 0}, {0, 1, 3}}, {{0, 1, 4}, {1, 0, 0}, {0, 1, 2}},\n    {{1, 2, 5}, {1, 0, 0}, {0, 2, 3}},\n\n    {{3, 6, 8}, {1, 0, 1}, {1, 3, 4}}, {{4, 6, 7}, {1, 1, 0}, {1, 2, 4}},\n    {{5, 7, 8}, {1, 1, 0}, {2, 3, 4}}};\n\ntemplate <typename Nil>\nconst uint32_t mappings<Wedge, Nil>::face_mapping[3][2] = {\n    {0, 1}, {0, 2}, {1, 2}};\n\ntypedef mappings<Wedge, void> wedge_mappings;\n\n} // namespace detail\n\nclass Wedge : public detail::wedge_mappings {\n public:\n  template <typename... Types>\n  Wedge(const vector_t& v0, Types... verts)\n      : vertices{{v0, verts...}}, faces(), center(), volume() {\n    init();\n  }\n\n  Wedge(const std::array<vector_t, 6>& verts)\n      : vertices(verts), faces(), center(), volume() {\n    init();\n  }\n\n  Wedge()\n      : vertices{{vector_t::Zero(), vector_t::Zero(), vector_t::Zero(), vector_t::Zero(), vector_t::Zero(), vector_t::Zero()}}\n      , faces()\n      , center()\n      , volume() {}\n\n  void apply(const Transformation& t) {\n    for (auto& v : vertices)\n      v = t.scaling * (v + t.translation);\n\n    for (auto& f : faces)\n      f.apply(t);\n\n    center = scalar_t(1.0 / 6.0) *\n             std::accumulate(\n                 vertices.begin(), vertices.end(), vector_t::Zero().eval());\n\n    volume = calcVolume();\n  }\n\n  scalar_t surfaceArea() const {\n    scalar_t area(0);\n    for (const auto& f : faces)\n      area += f.area;\n\n    return area;\n  }\n\n private:\n  void init() {\n    // All faces of the wedge are stored as quadrilaterals, so an\n    // additional point is inserted between v0 and v1.\n    // 0: v2, v1, v0, v02\n    faces[0] = Quadrilateral(\n        vertices[2], vertices[1], vertices[0],\n        scalar_t(0.5) * (vertices[0] + vertices[2]));\n\n    // 1: v0, v1, v4, v3\n    faces[1] =\n        Quadrilateral(vertices[0], vertices[1], vertices[4], vertices[3]);\n\n    // 2: v1, v2, v5, v4\n    faces[2] =\n        Quadrilateral(vertices[1], vertices[2], vertices[5], vertices[4]);\n\n    // 3: v2, v0, v3, v5\n    faces[3] =\n        Quadrilateral(vertices[2], vertices[0], vertices[3], vertices[5]);\n\n    // All faces of the wedge are stored as quadrilaterals, so an\n    // additional point is inserted between v3 and v5.\n    // 4: v3, v4, v5, v53\n    faces[4] = Quadrilateral(\n        vertices[3], vertices[4], vertices[5],\n        scalar_t(0.5) * (vertices[5] + vertices[3]));\n\n    center = scalar_t(1.0 / 6.0) *\n             std::accumulate(\n                 vertices.begin(), vertices.end(), vector_t::Zero().eval());\n\n    volume = calcVolume();\n  }\n\n  scalar_t calcVolume() const {\n    // The wedge is treated as a degenerate hexahedron here by adding\n    // two fake vertices v02 and v35.\n    vector_t diagonal(vertices[5] - vertices[0]);\n\n    return scalar_t(1.0 / 6.0) *\n           (diagonal.dot(\n               ((vertices[1] - vertices[0]).cross(vertices[2] - vertices[4])) +\n               ((vertices[3] - vertices[0])\n                    .cross(\n                        vertices[4] -\n                        scalar_t(0.5) * (vertices[3] + vertices[5]))) +\n               ((scalar_t(0.5) * (vertices[0] + vertices[2]) - vertices[0])\n                    .cross(\n                        scalar_t(0.5) * (vertices[3] + vertices[5]) -\n                        vertices[2]))));\n  }\n\n public:\n  std::array<vector_t, 6> vertices;\n  std::array<Quadrilateral, 5> faces;\n  vector_t center;\n  scalar_t volume;\n};\n\nnamespace detail {\n\ntemplate <typename Nil>\nstruct mappings<Hexahedron, Nil> {\n  // Map edges of a hexahedron to vertices and faces.\n  static const uint32_t edge_mapping[12][2][2];\n\n  // Map vertices of a hexahedron to edges and faces.\n  // 0: local IDs of the edges intersecting at this vertex\n  // 1: 0 if the edge is pointing away from the vertex, 1 otherwise\n  // 2: faces joining at the vertex\n  static const uint32_t vertex_mapping[8][3][3];\n\n  // This mapping contains the three sets of the two edges for each of the\n  // faces joining at a vertex. The indices are mapped to the local edge IDs\n  // using the first value field of the 'vertex_mapping' table.\n  static const uint32_t face_mapping[3][2];\n};\n\ntemplate <typename Nil>\nconst uint32_t mappings<Hexahedron, Nil>::edge_mapping[12][2][2] = {\n    {{0, 1}, {0, 1}}, {{1, 2}, {0, 2}}, {{2, 3}, {0, 3}}, {{3, 0}, {0, 4}},\n\n    {{0, 4}, {1, 4}}, {{1, 5}, {1, 2}}, {{2, 6}, {2, 3}}, {{3, 7}, {3, 4}},\n\n    {{4, 5}, {1, 5}}, {{5, 6}, {2, 5}}, {{6, 7}, {3, 5}}, {{7, 4}, {4, 5}}};\n\ntemplate <typename Nil>\nconst uint32_t mappings<Hexahedron, Nil>::vertex_mapping[8][3][3] = {\n    {{0, 3, 4}, {0, 1, 0}, {0, 1, 4}},  {{0, 1, 5}, {1, 0, 0}, {0, 1, 2}},\n    {{1, 2, 6}, {1, 0, 0}, {0, 2, 3}},  {{2, 3, 7}, {1, 0, 0}, {0, 3, 4}},\n\n    {{4, 8, 11}, {1, 0, 1}, {1, 4, 5}}, {{5, 8, 9}, {1, 1, 0}, {1, 2, 5}},\n    {{6, 9, 10}, {1, 1, 0}, {2, 3, 5}}, {{7, 10, 11}, {1, 1, 0}, {3, 4, 5}}};\n\ntemplate <typename Nil>\nconst uint32_t mappings<Hexahedron, Nil>::face_mapping[3][2] = {\n    {0, 1}, {0, 2}, {1, 2}};\n\ntypedef mappings<Hexahedron, void> hex_mappings;\n\n} // namespace detail\n\nclass Hexahedron : public detail::hex_mappings {\n public:\n  template <typename... Types>\n  Hexahedron(const vector_t& v0, Types... verts)\n      : vertices{{v0, verts...}}, faces(), center(), volume() {\n    init();\n  }\n\n  Hexahedron(const std::array<vector_t, 8>& verts)\n      : vertices(verts), faces(), center(), volume() {\n    init();\n  }\n\n  void apply(const Transformation& t) {\n    for (auto& v : vertices)\n      v = t.scaling * (v + t.translation);\n\n    for (auto& f : faces)\n      f.apply(t);\n\n    center = scalar_t(1.0 / 8.0) *\n             std::accumulate(\n                 vertices.begin(), vertices.end(), vector_t::Zero().eval());\n\n    volume = calcVolume();\n  }\n\n  scalar_t surfaceArea() const {\n    scalar_t area(0);\n    for (const auto& f : faces)\n      area += f.area;\n\n    return area;\n  }\n\n private:\n  void init() {\n    // 0: v3, v2, v1, v0\n    faces[0] =\n        Quadrilateral(vertices[3], vertices[2], vertices[1], vertices[0]);\n\n    // 1: v0, v1, v5, v4\n    faces[1] =\n        Quadrilateral(vertices[0], vertices[1], vertices[5], vertices[4]);\n\n    // 2: v1, v2, v6, v5\n    faces[2] =\n        Quadrilateral(vertices[1], vertices[2], vertices[6], vertices[5]);\n\n    // 3: v2, v3, v7, v6\n    faces[3] =\n        Quadrilateral(vertices[2], vertices[3], vertices[7], vertices[6]);\n\n    // 4: v3, v0, v4, v7\n    faces[4] =\n        Quadrilateral(vertices[3], vertices[0], vertices[4], vertices[7]);\n\n    // 5: v4, v5, v6, v7\n    faces[5] =\n        Quadrilateral(vertices[4], vertices[5], vertices[6], vertices[7]);\n\n    center = scalar_t(1.0 / 8.0) *\n             std::accumulate(\n                 vertices.begin(), vertices.end(), vector_t::Zero().eval());\n\n    volume = calcVolume();\n  }\n\n  scalar_t calcVolume() const {\n    vector_t diagonal(vertices[6] - vertices[0]);\n\n    return scalar_t(1.0 / 6.0) *\n           diagonal.dot(\n               ((vertices[1] - vertices[0]).cross(vertices[2] - vertices[5])) +\n               ((vertices[4] - vertices[0]).cross(vertices[5] - vertices[7])) +\n               ((vertices[3] - vertices[0]).cross(vertices[7] - vertices[2])));\n  }\n\n public:\n  std::array<vector_t, 8> vertices;\n  std::array<Quadrilateral, 6> faces;\n  vector_t center;\n  scalar_t volume;\n};\n\nclass Sphere {\n public:\n  Sphere(const vector_t& c, scalar_t r)\n      : center(c), radius(r), volume(scalar_t(4.0 / 3.0 * pi) * r * r * r) {}\n\n  scalar_t capVolume(scalar_t h) const {\n    if (h <= scalar_t(0))\n      return scalar_t(0);\n    else if (h >= scalar_t(2) * radius)\n      return volume;\n    else\n      return scalar_t(pi / 3.0) * h * h * (scalar_t(3) * radius - h);\n  }\n\n  scalar_t capSurfaceArea(scalar_t h) const {\n    if (h <= scalar_t(0))\n      return scalar_t(0);\n    else if (h >= scalar_t(2) * radius)\n      return surfaceArea();\n    else\n      return scalar_t(2 * pi) * radius * h;\n  }\n\n  scalar_t diskArea(scalar_t h) const {\n    if (h <= scalar_t(0) || h >= scalar_t(2) * radius)\n      return scalar_t(0);\n    else\n      return pi * h * (scalar_t(2) * radius - h);\n  }\n\n  scalar_t surfaceArea() const {\n    return (scalar_t(4) * pi) * (radius * radius);\n  }\n\n public:\n  vector_t center;\n  scalar_t radius;\n  scalar_t volume;\n};\n\nclass Plane {\n public:\n  Plane(const vector_t& c, const vector_t& n) : center(c), normal(n) {}\n\n public:\n  vector_t center;\n  vector_t normal;\n};\n\nclass AABB {\n public:\n  AABB(\n      const vector_t& minimum =\n          vector_t::Constant(std::numeric_limits<scalar_t>::infinity()),\n      const vector_t& maximum =\n          vector_t::Constant(-std::numeric_limits<scalar_t>::infinity()))\n      : min(minimum), max(maximum) {}\n\n  bool intersects(const AABB& aabb) const {\n    if ((min.array() > aabb.max.array()).any() ||\n        (max.array() < aabb.min.array()).any())\n      return false;\n\n    return true;\n  }\n\n  AABB overlap(const AABB& aabb) const {\n    return AABB(min.cwiseMax(aabb.min), max.cwiseMin(aabb.max));\n  }\n\n  bool contains(const vector_t& p) const {\n    if ((p.array() < min.array()).any() || (p.array() > max.array()).any())\n      return false;\n\n    return true;\n  }\n\n  void include(const vector_t& point) {\n    min = min.cwiseMin(point);\n    max = max.cwiseMax(point);\n  }\n\n  template <size_t N>\n  void include(const std::array<vector_t, N>& points) {\n    for (const auto& p : points)\n      include(p);\n  }\n\n  scalar_t volume() const {\n    vector_t size(max - min);\n\n    return size[0] * size[1] * size[2];\n  }\n\n public:\n  vector_t min, max;\n};\n\n// Decomposition of a tetrahedron into 4 tetrahedra.\ninline void decompose(\n    const Tetrahedron& tet, std::array<Tetrahedron, 4>& tets) {\n  tets[0] = Tetrahedron(\n      tet.vertices[0], tet.vertices[1], tet.vertices[2], tet.center);\n\n  tets[1] = Tetrahedron(\n      tet.vertices[0], tet.vertices[1], tet.center, tet.vertices[3]);\n\n  tets[2] = Tetrahedron(\n      tet.vertices[1], tet.vertices[2], tet.center, tet.vertices[3]);\n\n  tets[3] = Tetrahedron(\n      tet.vertices[2], tet.vertices[0], tet.center, tet.vertices[3]);\n}\n\n// Decomposition of a hexahedron into 2 wedges.\ninline void decompose(const Hexahedron& hex, std::array<Wedge, 2>& wedges) {\n  wedges[0] = Wedge(\n      hex.vertices[0], hex.vertices[1], hex.vertices[2], hex.vertices[4],\n      hex.vertices[5], hex.vertices[6]);\n\n  wedges[1] = Wedge(\n      hex.vertices[0], hex.vertices[2], hex.vertices[3], hex.vertices[4],\n      hex.vertices[6], hex.vertices[7]);\n}\n\n// Decomposition of a hexahedron into 5 tetrahedra.\ninline void decompose(const Hexahedron& hex, std::array<Tetrahedron, 5>& tets) {\n  tets[0] = Tetrahedron(\n      hex.vertices[0], hex.vertices[1], hex.vertices[2], hex.vertices[5]);\n\n  tets[1] = Tetrahedron(\n      hex.vertices[0], hex.vertices[2], hex.vertices[7], hex.vertices[5]);\n\n  tets[2] = Tetrahedron(\n      hex.vertices[0], hex.vertices[2], hex.vertices[3], hex.vertices[7]);\n\n  tets[3] = Tetrahedron(\n      hex.vertices[0], hex.vertices[5], hex.vertices[7], hex.vertices[4]);\n\n  tets[4] = Tetrahedron(\n      hex.vertices[2], hex.vertices[7], hex.vertices[5], hex.vertices[6]);\n}\n\n// Decomposition of a hexahedron into 6 tetrahedra.\ninline void decompose(const Hexahedron& hex, std::array<Tetrahedron, 6>& tets) {\n  tets[0] = Tetrahedron(\n      hex.vertices[0], hex.vertices[5], hex.vertices[7], hex.vertices[4]);\n\n  tets[1] = Tetrahedron(\n      hex.vertices[0], hex.vertices[1], hex.vertices[7], hex.vertices[5]);\n\n  tets[2] = Tetrahedron(\n      hex.vertices[1], hex.vertices[6], hex.vertices[7], hex.vertices[5]);\n\n  tets[3] = Tetrahedron(\n      hex.vertices[0], hex.vertices[7], hex.vertices[2], hex.vertices[3]);\n\n  tets[4] = Tetrahedron(\n      hex.vertices[0], hex.vertices[7], hex.vertices[1], hex.vertices[2]);\n\n  tets[5] = Tetrahedron(\n      hex.vertices[1], hex.vertices[7], hex.vertices[6], hex.vertices[2]);\n}\n\ninline bool contains(const Sphere& s, const vector_t& p) {\n  return (s.center - p).squaredNorm() <= s.radius * s.radius;\n}\n\n// The (convex!) polygon is assumed to be planar, making this a 2D problem.\n// Check the projection of the point onto the plane of the polygon for\n// containment within the polygon.\ntemplate <size_t VertexCount>\nbool contains(const Polygon<VertexCount>& poly, const vector_t& point) {\n  const vector_t proj(\n      point - poly.normal.dot(point - poly.center) * poly.normal);\n\n  for (size_t n = 0; n < poly.vertices.size(); ++n) {\n    const auto& v0 = poly.vertices[n];\n    const auto& v1 = poly.vertices[(n + 1) % poly.vertices.size()];\n    vector_t base(scalar_t(0.5) * (v0 + v1));\n    vector_t edge(v1 - v0);\n\n    // Note: Only the sign of the projection is of interest, so this vector\n    // does not have to be normalized.\n    vector_t dir(edge.cross(poly.normal));\n\n    // Check whether the projection of the point lies inside of the\n    // polygon.\n    if (dir.dot(proj - base) > scalar_t(0)) return false;\n  }\n\n  return true;\n}\n\ninline bool contains(const Tetrahedron& tet, const vector_t& p) {\n  for (const auto& f : tet.faces)\n    if (f.normal.dot(p - f.center) > scalar_t(0)) return false;\n\n  return true;\n}\n\ninline bool contains(const Wedge& wedge, const vector_t& p) {\n  for (const auto& f : wedge.faces)\n    if (f.normal.dot(p - f.center) > scalar_t(0)) return false;\n\n  return true;\n}\n\ninline bool contains(const Hexahedron& hex, const vector_t& p) {\n  for (const auto& f : hex.faces)\n    if (f.normal.dot(p - f.center) > scalar_t(0)) return false;\n\n  return true;\n}\n\ninline bool intersect(const Sphere& s, const Plane& p) {\n  scalar_t proj = p.normal.dot(s.center - p.center);\n\n  return proj * proj - s.radius * s.radius < scalar_t(0);\n}\n\ntemplate <size_t VertexCount>\ninline bool intersect(const Sphere& s, const Polygon<VertexCount>& poly) {\n  return intersect(s, Plane(poly.center, poly.normal)) &&\n         contains(poly, s.center);\n}\n\ninline std::pair<std::array<scalar_t, 2>, size_t> lineSphereIntersection(\n    const vector_t& origin, const vector_t& direction, const Sphere& s) {\n  std::array<scalar_t, 2> solutions = {\n      {std::numeric_limits<scalar_t>::infinity(),\n       std::numeric_limits<scalar_t>::infinity()}};\n\n  vector_t originRel(origin - s.center);\n  scalar_t a = direction.squaredNorm();\n\n  if (a == scalar_t(0)) return std::make_pair(solutions, 0);\n\n  scalar_t b = scalar_t(2) * direction.dot(originRel);\n  scalar_t c = originRel.squaredNorm() - s.radius * s.radius;\n\n  scalar_t discriminant = b * b - scalar_t(4) * a * c;\n  if (discriminant > scalar_t(0)) {\n    // Two real roots.\n    scalar_t q =\n        scalar_t(-0.5) * (b + std::copysign(std::sqrt(discriminant), b));\n\n    solutions[0] = q / a;\n    solutions[1] = c / q;\n\n    if (solutions[0] > solutions[1]) std::swap(solutions[0], solutions[1]);\n\n    return std::make_pair(solutions, 2);\n  } else if (std::abs(discriminant) == scalar_t(0)) {\n    // Double real root.\n    solutions[0] = (scalar_t(-0.5) * b) / a;\n    solutions[1] = solutions[0];\n\n    return std::make_pair(solutions, 1);\n  } else {\n    // No real roots.\n    return std::make_pair(solutions, 0);\n  }\n}\n\nnamespace detail {\n\n// Calculate the volume of a regularized spherical wedge defined by the radius,\n// the distance of the intersection point from the center of the sphere and the\n// angle.\ninline scalar_t regularizedWedge(scalar_t r, scalar_t d, scalar_t alpha) {\n#ifndef NDEBUG\n  // Clamp slight deviations of the angle to valid range.\n  if (alpha < scalar_t(0) && alpha > -detail::tinyEpsilon) alpha = scalar_t(0);\n\n  if (alpha > scalar_t(0.5 * pi) && alpha < scalar_t(0.5 * pi) + tinyEpsilon)\n    alpha = scalar_t(0.5 * pi);\n#endif\n\n  // Check the parameters for validity (debug version only).\n  assert(r > scalar_t(0));\n  assert(d >= scalar_t(0) && d <= r);\n  assert(alpha >= scalar_t(0) && alpha <= scalar_t(0.5 * pi));\n\n  const scalar_t sinAlpha = std::sin(alpha);\n  const scalar_t cosAlpha = std::cos(alpha);\n\n  const scalar_t a = d * sinAlpha;\n  const scalar_t b = std::sqrt(std::abs(r * r - d * d));\n  const scalar_t c = d * cosAlpha;\n\n  return scalar_t(1.0 / 3.0) * a * b * c +\n         a * (scalar_t(1.0 / 3.0) * a * a - r * r) * std::atan2(b, c) +\n         scalar_t(2.0 / 3.0) * r * r * r *\n             std::atan2(sinAlpha * b, cosAlpha * r);\n}\n\n// Wrapper around the above function handling correctly handling the case of\n// alpha > pi/2 and negative z.\ninline scalar_t regularizedWedge(\n    scalar_t r, scalar_t d, scalar_t alpha, scalar_t z) {\n  if (z >= scalar_t(0)) {\n    if (alpha > scalar_t(0.5 * pi)) {\n      scalar_t h = r - z;\n\n      return scalar_t(pi / 3.0) * h * h * (scalar_t(3) * r - h) -\n             regularizedWedge(r, d, pi - alpha);\n    } else {\n      return regularizedWedge(r, d, alpha);\n    }\n  } else {\n    scalar_t vHem = scalar_t(2.0 / 3.0 * pi) * r * r * r;\n\n    if (alpha > scalar_t(0.5 * pi)) {\n      return vHem - regularizedWedge(r, d, pi - alpha);\n    } else {\n      scalar_t h = r + z;\n      scalar_t vCap = scalar_t(pi / 3.0) * h * h * (scalar_t(3) * r - h);\n\n      return vHem - (vCap - regularizedWedge(r, d, alpha));\n    }\n  }\n}\n\n// Calculate the surface area of a regularized spherical wedge defined by the\n// radius, the distance of the intersection point from the center of the sphere\n// and the angle.\n// Ref: Gibson, K. D. & Scheraga, H. A.: Exact calculation of the volume and\n//      surface area of fused hard-sphere molecules with unequal atomic radii,\n//      Molecular Physics, 1987, 62, 1247-1265\ninline scalar_t regularizedWedgeArea(scalar_t r, scalar_t z, scalar_t alpha) {\n#ifndef NDEBUG\n  // Clamp slight deviations of the angle to valid range.\n  if (alpha < scalar_t(0) && alpha > -detail::tinyEpsilon) alpha = scalar_t(0);\n\n  if (alpha > pi && alpha < pi + tinyEpsilon) alpha = pi;\n#endif\n\n  // Check the parameters for validity (debug version only).\n  assert(r > scalar_t(0));\n  assert(z >= -r && z <= r);\n  assert(alpha >= scalar_t(0) && alpha <= pi);\n\n  if (alpha < tinyEpsilon || std::abs(r * r - z * z) <= tinyEpsilon)\n    return scalar_t(0);\n\n  const scalar_t sinAlpha = std::sin(alpha);\n  const scalar_t cosAlpha = std::cos(alpha);\n  const scalar_t factor = scalar_t(1) / std::sqrt(std::abs(r * r - z * z));\n\n  // Clamp slight deviations of the argument to acos() to valid range.\n  const scalar_t arg0 = clamp(\n      r * cosAlpha * factor, scalar_t(-1), scalar_t(1), detail::tinyEpsilon);\n\n  const scalar_t arg1 = clamp(\n      (z * cosAlpha * factor) / sinAlpha, scalar_t(-1), scalar_t(1),\n      detail::tinyEpsilon);\n\n  // Check the argument to acos() for validity (debug version only).\n  assert(scalar_t(-1) <= arg0 && arg0 <= scalar_t(1));\n  assert(scalar_t(-1) <= arg1 && arg1 <= scalar_t(1));\n\n  return scalar_t(2) * r * r * std::acos(arg0) -\n         scalar_t(2) * r * z * std::acos(arg1);\n}\n\n} // namespace detail\n\n// Depending on the dimensionality, either the volume or external surface area\n// of the general wedge is computed.\ntemplate <size_t Dim>\ninline scalar_t generalWedge(\n    const Sphere& s, const Plane& p0, const Plane& p1, const vector_t& d) {\n  static_assert(\n      Dim == 2 || Dim == 3, \"Invalid dimensionality, must be 2 or 3.\");\n\n  scalar_t dist(d.stableNorm());\n\n  if (dist < detail::tinyEpsilon) {\n    // The wedge (almost) touches the center, the volume depends only on\n    // the angle.\n    scalar_t angle = pi - detail::angle(p0.normal, p1.normal);\n\n    if (Dim == 2) {\n      return scalar_t(2) * s.radius * s.radius * angle;\n    } else {\n      return scalar_t(2.0 / 3.0) * s.radius * s.radius * s.radius * angle;\n    }\n  }\n\n  scalar_t s0 = d.dot(p0.normal);\n  scalar_t s1 = d.dot(p1.normal);\n\n  // Detect degenerated general spherical wedge that can be treated as\n  // a regularized spherical wedge.\n  if (std::abs(s0) < detail::tinyEpsilon ||\n      std::abs(s1) < detail::tinyEpsilon) {\n    scalar_t angle = pi - detail::angle(p0.normal, p1.normal);\n\n    if (Dim == 2) {\n      return detail::regularizedWedgeArea(\n          s.radius, std::abs(s0) > std::abs(s1) ? s0 : s1, angle);\n    } else {\n      return detail::regularizedWedge(\n          s.radius, dist, angle, std::abs(s0) > std::abs(s1) ? s0 : s1);\n    }\n  }\n\n  vector_t dUnit(d * (scalar_t(1) / dist));\n  if (dist < detail::largeEpsilon)\n    dUnit = detail::gramSchmidt(p0.normal.cross(p1.normal), dUnit)[1];\n\n  // Check the planes specify a valid setup (debug version only).\n  assert(p0.normal.dot(p1.center - p0.center) <= scalar_t(0));\n  assert(p1.normal.dot(p0.center - p1.center) <= scalar_t(0));\n\n  // Calculate the angles between the vector from the sphere center\n  // to the intersection line and the normal vectors of the two planes.\n  scalar_t alpha0 = detail::angle(p0.normal, dUnit);\n  scalar_t alpha1 = detail::angle(p1.normal, dUnit);\n\n  scalar_t dir0 = dUnit.dot((s.center + d) - p0.center);\n  scalar_t dir1 = dUnit.dot((s.center + d) - p1.center);\n\n  if (s0 >= scalar_t(0) && s1 >= scalar_t(0)) {\n    alpha0 = scalar_t(0.5 * pi) - std::copysign(alpha0, dir0);\n    alpha1 = scalar_t(0.5 * pi) - std::copysign(alpha1, dir1);\n\n    if (Dim == 2) {\n      return detail::regularizedWedgeArea(s.radius, s0, alpha0) +\n             detail::regularizedWedgeArea(s.radius, s1, alpha1);\n    } else {\n      return detail::regularizedWedge(s.radius, dist, alpha0, s0) +\n             detail::regularizedWedge(s.radius, dist, alpha1, s1);\n    }\n  } else if (s0 < scalar_t(0) && s1 < scalar_t(0)) {\n    alpha0 =\n        scalar_t(0.5 * pi) + std::copysign(scalar_t(1), dir0) * (alpha0 - pi);\n\n    alpha1 =\n        scalar_t(0.5 * pi) + std::copysign(scalar_t(1), dir1) * (alpha1 - pi);\n\n    if (Dim == 2) {\n      return s.surfaceArea() -\n             (detail::regularizedWedgeArea(s.radius, -s0, alpha0) +\n              detail::regularizedWedgeArea(s.radius, -s1, alpha1));\n    } else {\n      return s.volume - (detail::regularizedWedge(s.radius, dist, alpha0, -s0) +\n                         detail::regularizedWedge(s.radius, dist, alpha1, -s1));\n    }\n  } else {\n    alpha0 = scalar_t(0.5 * pi) -\n             std::copysign(scalar_t(1), dir0 * s0) *\n                 (alpha0 - (s0 < scalar_t(0) ? pi : scalar_t(0)));\n\n    alpha1 = scalar_t(0.5 * pi) -\n             std::copysign(scalar_t(1), dir1 * s1) *\n                 (alpha1 - (s1 < scalar_t(0) ? pi : scalar_t(0)));\n\n    if (Dim == 2) {\n      scalar_t area0 =\n          detail::regularizedWedgeArea(s.radius, std::abs(s0), alpha0);\n\n      scalar_t area1 =\n          detail::regularizedWedgeArea(s.radius, std::abs(s1), alpha1);\n\n      return std::max(area0, area1) - std::min(area0, area1);\n    } else {\n      scalar_t volume0 =\n          detail::regularizedWedge(s.radius, dist, alpha0, std::abs(s0));\n\n      scalar_t volume1 =\n          detail::regularizedWedge(s.radius, dist, alpha1, std::abs(s1));\n\n      return std::max(volume0, volume1) - std::min(volume0, volume1);\n    }\n  }\n}\n\ntemplate <typename T>\nstruct array_size;\n\ntemplate <typename T, size_t N>\nstruct array_size<std::array<T, N>> {\n  static constexpr size_t value() {\n    return N;\n  }\n};\n\ntemplate <typename Element>\nconstexpr size_t nrEdges() {\n  return std::is_same<Element, Hexahedron>::value\n             ? 12\n             : (std::is_same<Element, Wedge>::value\n                    ? 9\n                    : (std::is_same<Element, Tetrahedron>::value ? 6 : -1));\n}\n\n// Workaround for the Intel compiler, as it does not yet support constexpr for\n// template arguments.\ntemplate <typename Element>\nstruct element_trait {\n  static const size_t nrVertices =\n      array_size<decltype(Element::vertices)>::value();\n\n  static const size_t nrFaces = array_size<decltype(Element::faces)>::value();\n};\n\n// Depending on the dimensionality, either the volume or external surface area\n// of the general wedge is computed.\ntemplate <size_t Dim, typename Element>\nscalar_t generalWedge(\n    const Sphere& sphere, const Element& element, size_t edge,\n    const std::array<std::array<vector_t, 2>, nrEdges<Element>()>&\n        intersections) {\n  static_assert(\n      Dim == 2 || Dim == 3, \"Invalid dimensionality, must be 2 or 3.\");\n\n  const auto& f0 = element.faces[Element::edge_mapping[edge][1][0]];\n  const auto& f1 = element.faces[Element::edge_mapping[edge][1][1]];\n\n  vector_t edgeCenter(\n      scalar_t(0.5) * ((intersections[edge][0] +\n                        element.vertices[Element::edge_mapping[edge][0][0]]) +\n                       (intersections[edge][1] +\n                        element.vertices[Element::edge_mapping[edge][0][1]])));\n\n  Plane p0(f0.center, f0.normal);\n  Plane p1(f1.center, f1.normal);\n\n  return generalWedge<Dim>(sphere, p0, p1, edgeCenter - sphere.center);\n}\n\ntemplate <typename Element>\nscalar_t overlap(const Sphere& sOrig, const Element& elementOrig) {\n  static_assert(\n      std::is_same<Element, Tetrahedron>::value ||\n          std::is_same<Element, Wedge>::value ||\n          std::is_same<Element, Hexahedron>::value,\n      \"Invalid element type detected.\");\n\n  // Construct AABBs and perform a coarse overlap detection.\n  AABB sAABB(\n      sOrig.center - vector_t::Constant(sOrig.radius),\n      sOrig.center + vector_t::Constant(sOrig.radius));\n\n  AABB eAABB;\n  eAABB.include(elementOrig.vertices);\n\n  if (!sAABB.intersects(eAABB)) return scalar_t(0);\n\n  // Use scaled and shifted versions of the sphere and the element.\n  Transformation transformation(-sOrig.center, scalar_t(1) / sOrig.radius);\n\n  Sphere s(vector_t::Zero(), scalar_t(1));\n\n  Element element(elementOrig);\n  element.apply(transformation);\n\n  // Constants: Number of vertices and faces.\n  static const size_t nrVertices = element_trait<Element>::nrVertices;\n  static const size_t nrFaces = element_trait<Element>::nrFaces;\n\n  size_t vOverlap = 0;\n  // Check whether the vertices lie on or outside of the sphere.\n  for (const auto& vertex : element.vertices)\n    if ((s.center - vertex).squaredNorm() <= s.radius * s.radius) ++vOverlap;\n\n  // Check for trivial case: All vertices inside of the sphere, resulting in\n  // a full overlap.\n  if (vOverlap == nrVertices) return elementOrig.volume;\n\n  // Sanity check: All faces of the mesh element have to be planar.\n  for (const auto& face : element.faces)\n    if (!face.isPlanar())\n      throw std::runtime_error(\"Non-planer face detected in element!\");\n\n  // Sets of overlapping primitives.\n  std::bitset<nrVertices> vMarked;\n  std::bitset<nrEdges<Element>()> eMarked;\n  std::bitset<nrFaces> fMarked;\n\n  // Initial value: Volume of the full sphere.\n  scalar_t result = s.volume;\n\n  // The intersection points between the single edges and the sphere, this\n  // is needed later on.\n  std::array<std::array<vector_t, 2>, nrEdges<Element>()> eIntersections;\n\n  // Process all edges of the element.\n  for (size_t n = 0; n < nrEdges<Element>(); ++n) {\n    vector_t start(element.vertices[Element::edge_mapping[n][0][0]]);\n    vector_t direction(\n        element.vertices[Element::edge_mapping[n][0][1]] - start);\n\n    auto solutions = lineSphereIntersection(start, direction, s);\n\n    // No intersection between the edge and the sphere, where intersection\n    // points close to the surface of the sphere are ignored.\n    // Or:\n    // The sphere cuts the edge twice, no vertex is inside of the\n    // sphere, but the case of the edge only touching the sphere has to\n    // be avoided.\n    if (!solutions.second ||\n        (solutions.first[0] >= scalar_t(1) - detail::mediumEpsilon) ||\n        solutions.first[1] <= detail::mediumEpsilon ||\n        (solutions.first[0] > scalar_t(0) && solutions.first[1] < scalar_t(1) &&\n         (solutions.first[1] - solutions.first[0] < detail::largeEpsilon))) {\n      continue;\n    } else {\n      vMarked[Element::edge_mapping[n][0][0]] =\n          solutions.first[0] < scalar_t(0);\n\n      vMarked[Element::edge_mapping[n][0][1]] =\n          solutions.first[1] > scalar_t(1);\n    }\n\n    // Store the two intersection points of the edge with the sphere for\n    // later usage.\n    eIntersections[n][0] =\n        solutions.first[0] * direction +\n        (start - element.vertices[Element::edge_mapping[n][0][0]]);\n\n    eIntersections[n][1] =\n        solutions.first[1] * direction +\n        (start - element.vertices[Element::edge_mapping[n][0][1]]);\n\n    eMarked[n] = true;\n\n    // If the edge is marked as having an overlap, the two faces forming it\n    // have to be marked as well.\n    fMarked[Element::edge_mapping[n][1][0]] = true;\n    fMarked[Element::edge_mapping[n][1][1]] = true;\n  }\n\n  // Check whether the dependencies for a vertex intersection are fulfilled.\n  for (size_t n = 0; n < nrVertices; ++n) {\n    if (!vMarked[n]) continue;\n\n    bool edgesValid = true;\n    for (size_t eN = 0; eN < 3; ++eN) {\n      size_t edgeId = Element::vertex_mapping[n][0][eN];\n      edgesValid &= eMarked[edgeId];\n    }\n\n    // If not all three edges intersecting at this vertex where marked, the\n    // sphere is only touching.\n    if (!edgesValid) vMarked[n] = false;\n  }\n\n  // Process all faces of the element, ignoring the edges as those where\n  // already checked above.\n  for (size_t n = 0; n < nrFaces; ++n)\n    if (intersect(s, element.faces[n])) fMarked[n] = true;\n\n  // Trivial case: The center of the sphere overlaps the element, but the\n  // sphere does not intersect any of the faces of the element, meaning the\n  // sphere is completely contained within the element.\n  if (!fMarked.count() && contains(element, s.center)) return sOrig.volume;\n\n  // Spurious intersection: The initial intersection test was positive, but\n  // the detailed checks revealed no overlap.\n  if (!vMarked.count() && !eMarked.count() && !fMarked.count())\n    return scalar_t(0);\n\n  // Iterate over all the marked faces and subtract the volume of the cap cut\n  // off by the plane.\n  for (size_t n = 0; n < nrFaces; ++n) {\n    if (!fMarked[n]) continue;\n\n    const auto& f = element.faces[n];\n    scalar_t dist = f.normal.dot(s.center - f.center);\n    scalar_t vCap = s.capVolume(s.radius + dist);\n\n    result -= vCap;\n  }\n\n  // Handle the edges and add back the volume subtracted twice above in the\n  // processing of the faces.\n  for (size_t n = 0; n < nrEdges<Element>(); ++n) {\n    if (!eMarked[n]) continue;\n\n    scalar_t edgeCorrection =\n        generalWedge<3, Element>(s, element, n, eIntersections);\n\n    result += edgeCorrection;\n  }\n\n  // Handle the vertices and subtract the volume added twice above in the\n  // processing of the edges.\n  for (size_t n = 0; n < nrVertices; ++n) {\n    if (!vMarked[n]) continue;\n\n    // Collect the points where the three edges intersecting at this\n    // vertex intersect the sphere.\n    // Both the relative and the absolute positions are required.\n    std::array<vector_t, 3> intersectionPointsRelative;\n    std::array<vector_t, 3> intersectionPoints;\n    for (size_t e = 0; e < 3; ++e) {\n      auto edgeIdx = Element::vertex_mapping[n][0][e];\n      intersectionPointsRelative[e] =\n          eIntersections[edgeIdx][Element::vertex_mapping[n][1][e]];\n\n      intersectionPoints[e] =\n          intersectionPointsRelative[e] + element.vertices[n];\n    }\n\n    // This triangle is constructed by hand to have more freedom of how\n    // the normal vector is calculated.\n    Triangle coneTria;\n    coneTria.vertices = {\n        {intersectionPoints[0], intersectionPoints[1], intersectionPoints[2]}};\n\n    coneTria.center = scalar_t(1.0 / 3.0) * std::accumulate(\n                                                intersectionPoints.begin(),\n                                                intersectionPoints.end(),\n                                                vector_t::Zero().eval());\n\n    // Calculate the normal of the triangle defined by the intersection\n    // points in relative coordinates to improve accuracy.\n    // Also use double the normal precision to calculate this normal.\n    coneTria.normal = detail::triangleNormal(\n        intersectionPointsRelative[0], intersectionPointsRelative[1],\n        intersectionPointsRelative[2]);\n\n    // The area of this triangle is never needed, so it is set to an\n    // invalid value.\n    coneTria.area = std::numeric_limits<scalar_t>::infinity();\n\n    std::array<std::pair<size_t, scalar_t>, 3> distances;\n    for (size_t i = 0; i < 3; ++i)\n      distances[i] =\n          std::make_pair(i, intersectionPointsRelative[i].squaredNorm());\n\n    std::sort(\n        distances.begin(), distances.end(),\n        [](const std::pair<size_t, scalar_t>& a,\n           const std::pair<size_t, scalar_t>& b) -> bool {\n          return a.second < b.second;\n        });\n\n    if (distances[1].second < distances[2].second * detail::largeEpsilon) {\n      // Use the general spherical wedge defined by the edge with the\n      // non-degenerated intersection point and the normals of the\n      // two faces forming it.\n      scalar_t correction = generalWedge<3, Element>(\n          s, element, Element::vertex_mapping[n][0][distances[2].first],\n          eIntersections);\n\n      result -= correction;\n\n      continue;\n    }\n\n    scalar_t tipTetVolume =\n        scalar_t(1.0 / 6.0) *\n        std::abs(-intersectionPointsRelative[2].dot(\n            (intersectionPointsRelative[0] - intersectionPointsRelative[2])\n                .cross(\n                    intersectionPointsRelative[1] -\n                    intersectionPointsRelative[2])));\n\n    // Make sure the normal points in the right direction i.e. away from\n    // the center of the element.\n    if (coneTria.normal.dot(element.center - coneTria.center) > scalar_t(0)) {\n      coneTria.normal = -coneTria.normal;\n    }\n\n    Plane plane(coneTria.center, coneTria.normal);\n\n    scalar_t dist = coneTria.normal.dot(s.center - coneTria.center);\n    scalar_t capVolume = s.capVolume(s.radius + dist);\n\n    // The cap volume is tiny, so the corrections will be even smaller.\n    // There is no way to actually calculate them with reasonable\n    // precision, so just the volume of the tetrahedron at the tip is\n    // used.\n    if (capVolume < detail::tinyEpsilon) {\n      result -= tipTetVolume;\n      continue;\n    }\n\n    // Calculate the volume of the three spherical segments between\n    // the faces joining at the vertex and the plane through the\n    // intersection points.\n    scalar_t segmentVolume = 0;\n\n    for (size_t e = 0; e < 3; ++e) {\n      const auto& f = element.faces[Element::vertex_mapping[n][2][e]];\n      uint32_t e0 = Element::face_mapping[e][0];\n      uint32_t e1 = Element::face_mapping[e][1];\n\n      vector_t center(\n          scalar_t(0.5) * (intersectionPoints[e0] + intersectionPoints[e1]));\n\n      scalar_t wedgeVolume = generalWedge<3>(\n          s, plane, Plane(f.center, -f.normal), center - s.center);\n\n      segmentVolume += wedgeVolume;\n    }\n\n    // Calculate the volume of the cone and clamp it to zero.\n    scalar_t coneVolume =\n        std::max(tipTetVolume + capVolume - segmentVolume, scalar_t(0));\n\n    // Sanity check: detect negative cone volume.\n    assert(coneVolume > -std::sqrt(detail::tinyEpsilon));\n\n    result -= coneVolume;\n\n    // Sanity check: detect negative intermediate result.\n    assert(result > -std::sqrt(detail::tinyEpsilon));\n  }\n\n  // In case of different sized objects the error can become quite large,\n  // so a relative limit is used.\n  scalar_t maxOverlap = std::min(s.volume, element.volume);\n  const scalar_t limit(\n      std::sqrt(std::numeric_limits<scalar_t>::epsilon()) * maxOverlap);\n\n  // Clamp tiny negative volumes to zero.\n  if (result < scalar_t(0) && result > -limit) return scalar_t(0);\n\n  // Clamp results slightly too large.\n  if (result > maxOverlap && result - maxOverlap < limit)\n    return std::min(sOrig.volume, elementOrig.volume);\n\n  // Perform a sanity check on the final result (debug version only).\n  assert(result >= scalar_t(0) && result <= maxOverlap);\n\n  // Scale the overlap volume back for the original objects.\n  result = (result / s.volume) * sOrig.volume;\n\n  return result;\n}\n\ntemplate <typename Iterator>\nscalar_t overlap(const Sphere& s, Iterator eBegin, Iterator eEnd) {\n  scalar_t sum(0);\n\n  for (Iterator it = eBegin; it != eEnd; ++it)\n    sum += overlap(s, *it);\n\n  return sum;\n}\n\n// Calculate the surface area of the sphere and the element that are contained\n// within the common or intersecting part of the geometries, respectively.\n// The returned array of size (N + 2), with N being the number of vertices,\n// holds (in this order):\n//   - surface area of the region of the sphere intersecting the element\n//   - for each face of the element: area contained within the sphere\n//   - total surface area of the element intersecting the sphere\ntemplate <\n    typename Element, size_t NrFaces = element_trait<Element>::nrFaces + 2>\nauto overlapArea(const Sphere& sOrig, const Element& elementOrig)\n    -> std::array<scalar_t, NrFaces> {\n  static_assert(\n      NrFaces == element_trait<Element>::nrFaces + 2,\n      \"Invalid number of faces for the element provided.\");\n\n  static_assert(\n      std::is_same<Element, Tetrahedron>::value ||\n          std::is_same<Element, Wedge>::value ||\n          std::is_same<Element, Hexahedron>::value,\n      \"Invalid element type detected.\");\n\n  // Constants: Number of vertices and faces.\n  static const size_t nrVertices = element_trait<Element>::nrVertices;\n  static const size_t nrFaces = element_trait<Element>::nrFaces;\n\n  // Initial value: Zero overlap.\n  std::array<scalar_t, nrFaces + 2> result;\n  result.fill(scalar_t(0));\n\n  // Construct AABBs and perform a coarse overlap detection.\n  AABB sAABB(\n      sOrig.center - vector_t::Constant(sOrig.radius),\n      sOrig.center + vector_t::Constant(sOrig.radius));\n\n  AABB eAABB;\n  eAABB.include(elementOrig.vertices);\n\n  if (!sAABB.intersects(eAABB)) return result;\n\n  // Use scaled and shifted versions of the sphere and the element.\n  Transformation transformation(-sOrig.center, scalar_t(1) / sOrig.radius);\n\n  Sphere s(vector_t::Zero(), scalar_t(1));\n\n  Element element(elementOrig);\n  element.apply(transformation);\n\n  size_t vOverlap = 0;\n  // Check whether the vertices lie on or outside of the sphere.\n  for (const auto& vertex : element.vertices)\n    if ((s.center - vertex).squaredNorm() <= s.radius * s.radius) ++vOverlap;\n\n  // Check for trivial case: All vertices inside of the sphere, resulting in\n  // a full coverage of all faces.\n  if (vOverlap == nrVertices) {\n    for (size_t n = 0; n < nrFaces; ++n) {\n      result[n + 1] = elementOrig.faces[n].area;\n      result[nrFaces + 1] += elementOrig.faces[n].area;\n    }\n\n    return result;\n  }\n\n  // Sanity check: All faces of the mesh element have to be planar.\n  for (const auto& face : element.faces)\n    if (!face.isPlanar())\n      throw std::runtime_error(\"Non-planer face detected in element!\");\n\n  // Sets of overlapping primitives.\n  std::bitset<nrVertices> vMarked;\n  std::bitset<nrEdges<Element>()> eMarked;\n  std::bitset<nrFaces> fMarked;\n\n  // The intersection points between the single edges and the sphere, this\n  // is needed later on.\n  std::array<std::array<vector_t, 2>, nrEdges<Element>()> eIntersections;\n\n  // Cache the squared radius of the disk formed by the intersection between\n  // the planes defined by each face and the sphere.\n  std::array<scalar_t, nrFaces> intersectionRadiusSq;\n\n  // Process all edges of the element.\n  for (size_t n = 0; n < nrEdges<Element>(); ++n) {\n    vector_t start(element.vertices[Element::edge_mapping[n][0][0]]);\n    vector_t direction(\n        element.vertices[Element::edge_mapping[n][0][1]] - start);\n\n    auto solutions = lineSphereIntersection(start, direction, s);\n\n    // No intersection between the edge and the sphere, where intersection\n    // points close to the surface of the sphere are ignored.\n    // Or:\n    // The sphere cuts the edge twice, no vertex is inside of the\n    // sphere, but the case of the edge only touching the sphere has to\n    // be avoided.\n    if (!solutions.second ||\n        solutions.first[0] >= scalar_t(1) - detail::mediumEpsilon ||\n        solutions.first[1] <= detail::mediumEpsilon ||\n        (solutions.first[0] > scalar_t(0) && solutions.first[1] < scalar_t(1) &&\n         solutions.first[1] - solutions.first[0] < detail::largeEpsilon)) {\n      continue;\n    } else {\n      vMarked[Element::edge_mapping[n][0][0]] =\n          solutions.first[0] < scalar_t(0);\n\n      vMarked[Element::edge_mapping[n][0][1]] =\n          solutions.first[1] > scalar_t(1);\n    }\n\n    // Store the two intersection points of the edge with the sphere for\n    // later usage.\n    eIntersections[n][0] =\n        solutions.first[0] * direction +\n        (start - element.vertices[Element::edge_mapping[n][0][0]]);\n\n    eIntersections[n][1] =\n        solutions.first[1] * direction +\n        (start - element.vertices[Element::edge_mapping[n][0][1]]);\n\n    eMarked[n] = true;\n\n    // If the edge is marked as having an overlap, the two faces forming it\n    // have to be marked as well.\n    fMarked[Element::edge_mapping[n][1][0]] = true;\n    fMarked[Element::edge_mapping[n][1][1]] = true;\n  }\n\n  // Check whether the dependencies for a vertex intersection are fulfilled.\n  for (size_t n = 0; n < nrVertices; ++n) {\n    if (!vMarked[n]) continue;\n\n    bool edgesValid = true;\n    for (size_t eN = 0; eN < 3; ++eN) {\n      size_t edgeId = Element::vertex_mapping[n][0][eN];\n      edgesValid &= eMarked[edgeId];\n    }\n\n    // If not all three edges intersecting at this vertex where marked, the\n    // sphere is only touching.\n    if (!edgesValid) vMarked[n] = false;\n  }\n\n  // Process all faces of the element, ignoring the edges as those where\n  // already checked above.\n  for (size_t n = 0; n < nrFaces; ++n)\n    if (intersect(s, element.faces[n])) fMarked[n] = true;\n\n  // Trivial case: The center of the sphere overlaps the element, but the\n  // sphere does not intersect any of the faces of the element, meaning the\n  // sphere is completely contained within the element.\n  if (!fMarked.count() && contains(element, s.center)) {\n    result[0] = sOrig.surfaceArea();\n\n    return result;\n  }\n\n  // Spurious intersection: The initial intersection test was positive, but\n  // the detailed checks revealed no overlap.\n  if (!vMarked.count() && !eMarked.count() && !fMarked.count()) return result;\n\n  // Initial value for the surface of the sphere: Surface area of the full\n  // sphere.\n  result[0] = s.surfaceArea();\n\n  // Iterate over all the marked faces and calculate the area of the disk\n  // defined by the plane as well as the cap surfaces.\n  for (size_t n = 0; n < nrFaces; ++n) {\n    if (!fMarked[n]) continue;\n\n    const auto& f = element.faces[n];\n    scalar_t dist = f.normal.dot(s.center - f.center);\n    result[0] -= s.capSurfaceArea(s.radius + dist);\n    result[n + 1] = s.diskArea(s.radius + dist);\n  }\n\n  // Handle the edges and subtract the area of the respective disk cut off by\n  // the edge and add back the surface area of the spherical wedge defined\n  // by the edge.\n  for (size_t n = 0; n < nrEdges<Element>(); ++n) {\n    if (!eMarked[n]) continue;\n\n    result[0] += generalWedge<2, Element>(s, element, n, eIntersections);\n\n    // The intersection points are relative to the vertices forming the\n    // edge.\n    const vector_t chord =\n        ((element.vertices[Element::edge_mapping[n][0][0]] +\n          eIntersections[n][0]) -\n         (element.vertices[Element::edge_mapping[n][0][1]] +\n          eIntersections[n][1]));\n\n    const scalar_t chordLength = chord.stableNorm();\n\n    // Each edge belongs to two faces, indexed via\n    // Element::edge_mapping[n][1][{0,1}].\n    for (size_t e = 0; e < 2; ++e) {\n      const auto faceIdx = Element::edge_mapping[n][1][e];\n      const auto& f = element.faces[faceIdx];\n\n      // Height of the spherical cap cut off by the plane containing the\n      // face.\n      const scalar_t dist = f.normal.dot(s.center - f.center) + s.radius;\n      intersectionRadiusSq[faceIdx] = dist * (scalar_t(2) * s.radius - dist);\n\n      // Calculate the height of the triangular segment in the plane of\n      // the base.\n      const scalar_t factor = std::sqrt(std::max(\n          scalar_t(0), intersectionRadiusSq[faceIdx] -\n                           scalar_t(0.25) * chordLength * chordLength));\n\n      const scalar_t theta =\n          scalar_t(2) * std::atan2(chordLength, scalar_t(2) * factor);\n\n      scalar_t area = scalar_t(0.5) * intersectionRadiusSq[faceIdx] *\n                      (theta - std::sin(theta));\n\n      // FIXME: Might not be necessary to use the center of the chord.\n      const vector_t chordCenter =\n          scalar_t(0.5) * ((element.vertices[Element::edge_mapping[n][0][0]] +\n                            eIntersections[n][0]) +\n                           (element.vertices[Element::edge_mapping[n][0][1]] +\n                            eIntersections[n][1]));\n\n      const vector_t proj(\n          s.center - f.normal.dot(s.center - f.center) * f.normal);\n\n      // If the projected sphere center and the face center fall on\n      // opposite sides of the edge, the area has to be inverted.\n      if (chord.cross(proj - chordCenter)\n              .dot(chord.cross(f.center - chordCenter)) < scalar_t(0)) {\n        area = intersectionRadiusSq[faceIdx] * pi - area;\n      }\n\n      result[faceIdx + 1] -= area;\n    }\n  }\n\n  // Handle the vertices and add the area subtracted twice above in the\n  // processing of the edges.\n\n  // First, handle the spherical surface area of the intersection.\n  // This is to a large part code duplicated from the volume calculation.\n  // TODO: Unify the area and volume calculation to remove duplicate code.\n  for (size_t n = 0; n < nrVertices; ++n) {\n    if (!vMarked[n]) continue;\n\n    // Collect the points where the three edges intersecting at this\n    // vertex intersect the sphere.\n    // Both the relative and the absolute positions are required.\n    std::array<vector_t, 3> intersectionPointsRelative;\n    std::array<vector_t, 3> intersectionPoints;\n    for (size_t e = 0; e < 3; ++e) {\n      auto edgeIdx = Element::vertex_mapping[n][0][e];\n      intersectionPointsRelative[e] =\n          eIntersections[edgeIdx][Element::vertex_mapping[n][1][e]];\n\n      intersectionPoints[e] =\n          intersectionPointsRelative[e] + element.vertices[n];\n    }\n\n    // This triangle is constructed by hand to have more freedom of how\n    // the normal vector is calculated.\n    Triangle coneTria;\n    coneTria.vertices = {\n        {intersectionPoints[0], intersectionPoints[1], intersectionPoints[2]}};\n\n    coneTria.center = scalar_t(1.0 / 3.0) * std::accumulate(\n                                                intersectionPoints.begin(),\n                                                intersectionPoints.end(),\n                                                vector_t::Zero().eval());\n\n    // Calculate the normal of the triangle defined by the intersection\n    // points in relative coordinates to improve accuracy.\n    // Also use double the normal precision to calculate this normal.\n    coneTria.normal = detail::triangleNormal(\n        intersectionPointsRelative[0], intersectionPointsRelative[1],\n        intersectionPointsRelative[2]);\n\n    // The area of this triangle is never needed, so it is set to an\n    // invalid value.\n    coneTria.area = std::numeric_limits<scalar_t>::infinity();\n\n    std::array<std::pair<size_t, scalar_t>, 3> distances;\n    for (size_t i = 0; i < 3; ++i)\n      distances[i] =\n          std::make_pair(i, intersectionPointsRelative[i].squaredNorm());\n\n    std::sort(\n        distances.begin(), distances.end(),\n        [](const std::pair<size_t, scalar_t>& a,\n           const std::pair<size_t, scalar_t>& b) -> bool {\n          return a.second < b.second;\n        });\n\n    if (distances[1].second < distances[2].second * detail::largeEpsilon) {\n      // Use the general spherical wedge defined by the edge with the\n      // non-degenerated intersection point and the normals of the\n      // two faces forming it.\n      scalar_t correction = generalWedge<2, Element>(\n          s, element, Element::vertex_mapping[n][0][distances[2].first],\n          eIntersections);\n\n      result[0] -= correction;\n\n      continue;\n    }\n\n    // Make sure the normal points in the right direction, i.e., away from\n    // the center of the element.\n    if (coneTria.normal.dot(element.center - coneTria.center) > scalar_t(0)) {\n      coneTria.normal = -coneTria.normal;\n    }\n\n    Plane plane(coneTria.center, coneTria.normal);\n\n    scalar_t dist = coneTria.normal.dot(s.center - coneTria.center);\n    scalar_t capSurface = s.capSurfaceArea(s.radius + dist);\n\n    // If cap surface area is small, the corrections will be even smaller.\n    // There is no way to actually calculate them with reasonable\n    // precision, so they are just ignored.\n    if (capSurface < detail::largeEpsilon) continue;\n\n    // Calculate the surface area of the three spherical segments between\n    // the faces joining at the vertex and the plane through the\n    // intersection points.\n    scalar_t segmentSurface = 0;\n    for (size_t e = 0; e < 3; ++e) {\n      const auto& f = element.faces[Element::vertex_mapping[n][2][e]];\n      uint32_t e0 = Element::face_mapping[e][0];\n      uint32_t e1 = Element::face_mapping[e][1];\n\n      vector_t center(\n          scalar_t(0.5) * (intersectionPoints[e0] + intersectionPoints[e1]));\n\n      segmentSurface += generalWedge<2>(\n          s, plane, Plane(f.center, -f.normal), center - s.center);\n    }\n\n    // Calculate the surface area of the cone and clamp it to zero.\n    scalar_t coneSurface = std::max(capSurface - segmentSurface, scalar_t(0));\n\n    result[0] -= coneSurface;\n\n    // Sanity checks: detect negative/excessively large intermediate\n    // result.\n    assert(result[0] > -std::sqrt(detail::tinyEpsilon));\n    assert(result[0] < s.surfaceArea() + detail::tinyEpsilon);\n  }\n\n  // Second, correct the intersection area of the facets.\n  for (size_t n = 0; n < nrVertices; ++n) {\n    if (!vMarked[n]) continue;\n\n    // Iterate over all the faces joining at this vertex.\n    for (size_t f = 0; f < 3; ++f) {\n      // Determine the two edges of this face intersecting at the\n      // vertex.\n      uint32_t e0 = Element::face_mapping[f][0];\n      uint32_t e1 = Element::face_mapping[f][1];\n      std::array<uint32_t, 2> edgeIndices = {\n          {Element::vertex_mapping[n][0][e0],\n           Element::vertex_mapping[n][0][e1]}};\n\n      // Extract the (relative) intersection points of these edges with\n      // the sphere furthest from the vertex.\n      std::array<vector_t, 2> intersectionPoints = {\n          {eIntersections[edgeIndices[0]][Element::vertex_mapping[n][1][e0]],\n\n           eIntersections[edgeIndices[1]][Element::vertex_mapping[n][1][e1]]}};\n\n      // Together with the vertex, this determines the triangle\n      // representing one part of the correction.\n      const scalar_t triaArea =\n          scalar_t(0.5) *\n          (intersectionPoints[0].cross(intersectionPoints[1])).stableNorm();\n\n      // The second component is the segment defined by the face and the\n      // intersection points.\n      const scalar_t chordLength =\n          (intersectionPoints[0] - intersectionPoints[1]).stableNorm();\n\n      const auto faceIdx = Element::vertex_mapping[n][2][f];\n\n      // TODO: Cache theta for each edge.\n      const scalar_t theta =\n          scalar_t(2) *\n          std::atan2(\n              chordLength,\n              scalar_t(2) * std::sqrt(std::max(\n                                scalar_t(0), intersectionRadiusSq[faceIdx] -\n                                                 scalar_t(0.25) * chordLength *\n                                                     chordLength)));\n\n      scalar_t segmentArea = scalar_t(0.5) * intersectionRadiusSq[faceIdx] *\n                             (theta - std::sin(theta));\n\n      // Determine if the (projected) center of the sphere lies within\n      // the triangle or not. If not, the segment area has to be\n      // corrected.\n      const vector_t d(\n          scalar_t(0.5) * (intersectionPoints[0] + intersectionPoints[1]));\n\n      const auto& face = element.faces[faceIdx];\n      const vector_t proj(\n          s.center - face.normal.dot(s.center - face.center) * face.normal);\n\n      if (d.dot((proj - element.vertices[n]) - d) > scalar_t(0)) {\n        segmentArea = intersectionRadiusSq[faceIdx] * pi - segmentArea;\n      }\n\n      result[faceIdx + 1] += triaArea + segmentArea;\n\n      // Sanity checks: detect excessively large intermediate result.\n      assert(\n          result[faceIdx + 1] <\n          element.faces[faceIdx].area + std::sqrt(detail::largeEpsilon));\n    }\n  }\n\n  // Scale the surface areas back for the original objects and clamp\n  // values within reasonable limits.\n  const scalar_t scaling = sOrig.radius / s.radius;\n  const scalar_t sLimit(\n      std::sqrt(std::numeric_limits<scalar_t>::epsilon()) * s.surfaceArea());\n\n  // As the precision of the area calculation deteriorates quickly with a\n  // increasing size ratio between the element and the sphere, the precision\n  // limit applied to the sphere is used as the lower limit for the facets.\n  const scalar_t fLimit(std::max(\n      sLimit, std::sqrt(std::numeric_limits<scalar_t>::epsilon()) *\n                  element.surfaceArea()));\n\n  // Sanity checks: detect negative/excessively large results for the\n  // surface area of the facets.\n#ifndef NDEBUG\n  for (size_t n = 0; n < nrFaces; ++n) {\n    assert(result[n + 1] > -fLimit);\n    assert(result[n + 1] <= element.faces[n].area + fLimit);\n  }\n#endif // NDEBUG\n\n  // Surface of the sphere.\n  result[0] = detail::clamp(result[0], scalar_t(0), s.surfaceArea(), sLimit);\n  result[0] *= (scaling * scaling);\n\n  // Surface of the mesh element.\n  for (size_t f = 0; f < nrFaces; ++f) {\n    auto& value = result[f + 1];\n    value = detail::clamp(value, scalar_t(0), element.faces[f].area, fLimit);\n\n    value = value * (scaling * scaling);\n  }\n\n  result.back() =\n      std::accumulate(result.begin() + 1, result.end() - 1, scalar_t(0));\n\n  // Perform some more sanity checks on the final result (debug version\n  // only).\n  assert(scalar_t(0) <= result[0] && result[0] <= sOrig.surfaceArea());\n\n  assert(\n      scalar_t(0) <= result.back() &&\n      result.back() <= elementOrig.surfaceArea());\n\n  return result;\n}\n\n#endif // OVERLAP_HPP\n", "meta": {"hexsha": "5d499b29a9e8ca591334ea16fcab5be5b1297894", "size": 70257, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/overlap/overlap.hpp", "max_stars_repo_name": "ChristopherKotthoff/Aphros-with-GraphContraction", "max_stars_repo_head_hexsha": "18af982a50e350a8bf6979ae5bd25b2ef4d3792a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/overlap/overlap.hpp", "max_issues_repo_name": "ChristopherKotthoff/Aphros-with-GraphContraction", "max_issues_repo_head_hexsha": "18af982a50e350a8bf6979ae5bd25b2ef4d3792a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/overlap/overlap.hpp", "max_forks_repo_name": "ChristopherKotthoff/Aphros-with-GraphContraction", "max_forks_repo_head_hexsha": "18af982a50e350a8bf6979ae5bd25b2ef4d3792a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7081005587, "max_line_length": 126, "alphanum_fraction": 0.6298731799, "num_tokens": 19756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949442167993, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4492246833057026}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_OPERATOR_FUNCTIONS_COMPLEX_GENERIC_MULTIPLIES_HPP_INCLUDED\n#define NT2_OPERATOR_FUNCTIONS_COMPLEX_GENERIC_MULTIPLIES_HPP_INCLUDED\n\n#include <nt2/operator/functions/multiplies.hpp>\n#include <nt2/include/functions/real.hpp>\n#include <nt2/include/functions/imag.hpp>\n#include <nt2/include/functions/pure.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/functions/simd/unary_minus.hpp>\n#include <nt2/include/functions/simd/any.hpp>\n#include <nt2/include/functions/fma.hpp>\n#include <nt2/include/functions/simd/all.hpp>\n#include <nt2/include/functions/simd/is_nez.hpp>\n#include <nt2/include/functions/simd/is_invalid.hpp>\n#include <nt2/include/functions/logical_or.hpp>\n#include <nt2/include/functions/logical_and.hpp>\n#include <nt2/include/functions/logical_andnot.hpp>\n#include <nt2/include/functions/if_else.hpp>\n#include <nt2/include/functions/if_zero_else.hpp>\n#include <nt2/include/functions/if_else_zero.hpp>\n#include <nt2/include/functions/is_finite.hpp>\n#include <nt2/include/functions/is_eqz.hpp>\n#include <nt2/include/functions/is_real.hpp>\n#include <nt2/include/functions/is_imag.hpp>\n#include <nt2/include/functions/simd/mul_i.hpp>\n#include <nt2/include/functions/bitwise_cast.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/sdk/complex/hierarchy.hpp>\n#include <nt2/sdk/complex/meta/as_real.hpp>\n#include <nt2/sdk/complex/meta/as_dry.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n#include <boost/simd/sdk/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  // complex/complex\n  BOOST_DISPATCH_IMPLEMENT  ( multiplies_, tag::cpu_, (A0)\n                            , ((generic_< complex_< arithmetic_<A0> > >))\n                              ((generic_< complex_< arithmetic_<A0> > >))\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename nt2::meta::as_real<A0>::type r_type;\n      const r_type a = nt2::real(a0);\n      const r_type b = nt2::imag(a0);\n      const r_type c = nt2::real(a1);\n      const r_type d = nt2::imag(a1);\n      result_type r(fma(a,c,-b*d), fma(a,d,b*c));\n#ifndef BOOST_SIMD_NO_INVALIDS\n      typedef typename meta::as_logical<r_type>::type l_type;\n      l_type test = is_finite(r);\n      if (nt2::all(test)) return r;\n      l_type cur  = nt2::logical_andnot(is_real(a0), test);\n      if (nt2::any(cur))\n      {\n        r = if_else(cur, nt2::multiplies(a, a1), r);\n        test = logical_or(test, cur);\n        if (nt2::all(test)) return r;\n      }\n      cur = nt2::logical_andnot(is_imag(a0), test);\n      if (nt2::any(cur))\n      {\n        r = if_else(cur, nt2::mul_i(nt2::multiplies(b, a1)), r);\n        test = logical_or(test, cur);\n        if (nt2::all(test)) return r;\n      }\n      cur = nt2::logical_andnot(is_real(a1), test);\n      if (nt2::any(cur))\n      {\n        r = if_else(cur, nt2::multiplies(c, a0), r);\n        test = logical_or(test, cur);\n        if (nt2::all(test)) return r;\n      }\n      cur = nt2::logical_andnot(is_imag(a1), test);\n      if (nt2::any(cur))\n      {\n        r = if_else(cur, nt2::mul_i(nt2::multiplies(d, a0)), r);\n        test = logical_or(test, cur);\n        if (nt2::all(test)) return r;\n      }\n #endif\n      return r;\n    }\n  };\n\n  // complex/real\n  BOOST_DISPATCH_IMPLEMENT  ( multiplies_, tag::cpu_, (A0)(A1)\n                            , ((generic_< arithmetic_<A0> >))\n                              ((generic_< complex_< arithmetic_<A1> > >))\n                            )\n  {\n    typedef A1 result_type;\n    typedef A0 r_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n      r_type r = a0*nt2::real(a1);\n      r_type i = a0*nt2::imag(a1);\n#ifndef BOOST_SIMD_NO_INVALIDS\n      typename meta::as_logical<A1>::type is_real_a1 = is_real(a1);\n      r = if_zero_else(logical_andnot(is_imag(a1), is_real_a1), r);\n      i = if_zero_else(is_real_a1, i);\n#endif\n      return result_type(r, i);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( multiplies_, tag::cpu_, (A0)(A1)\n                            , ((generic_< complex_< arithmetic_<A0> > >))\n                              ((generic_< arithmetic_<A1> >))\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n      return nt2::multiplies(a1, a0);\n    }\n  };\n  BOOST_DISPATCH_IMPLEMENT  ( multiplies_, tag::cpu_, (A0)(A1)\n                            , ((generic_< dry_ < arithmetic_<A0> > >))\n                              ((generic_< complex_< arithmetic_<A1> > >))\n                            )\n  {\n    typedef A1 result_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n      return nt2::multiplies(nt2::real(a0), a1);\n    }\n  };\n  BOOST_DISPATCH_IMPLEMENT  ( multiplies_, tag::cpu_, (A0)(A1)\n                            , ((generic_< complex_< arithmetic_<A0> > >))\n                              ((generic_< dry_ < arithmetic_<A1> > >))\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n      return nt2::multiplies(a0, nt2::real(a1));\n    }\n  };\n\n  // dry/dry\n  BOOST_DISPATCH_IMPLEMENT  ( multiplies_, tag::cpu_, (A0)(A1)\n                            , ((generic_< dry_< arithmetic_<A0> > >))\n                              ((generic_< dry_< arithmetic_<A1> > >))\n                            )\n  {\n    typedef typename nt2::meta::as_dry<A0>::type result_type;\n    NT2_FUNCTOR_CALL(2)\n    {\n      return bitwise_cast<result_type>(nt2::real(a0)*nt2::real(a1));\n    }\n  };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "406831fae281d348c0333b701baa37e80acfe58d", "size": 5936, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/base/include/nt2/operator/functions/complex/generic/multiplies.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/type/complex/base/include/nt2/operator/functions/complex/generic/multiplies.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/type/complex/base/include/nt2/operator/functions/complex/generic/multiplies.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 35.3333333333, "max_line_length": 80, "alphanum_fraction": 0.5813679245, "num_tokens": 1551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4491194134876732}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_ACSCPI_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ACSCPI_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing acscpi capabilities\n\n     inverse secant in degree: \\f$(1/\\pi) \\arcsin(1/x)\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = acscpi(x);\n    @endcode\n\n\n    @see acsc, acscd, asinpi, sinpi\n\n  **/\n  Value acscpi(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/acscpi.hpp>\n#include <boost/simd/function/simd/acscpi.hpp>\n\n#endif\n", "meta": {"hexsha": "9bf67c4d7d493c43479197679e77f820d87b5f37", "size": 1008, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/acscpi.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/function/acscpi.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/acscpi.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 22.4, "max_line_length": 100, "alphanum_fraction": 0.5714285714, "num_tokens": 230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4490046809690305}}
{"text": "// #define R_BUILD\n#ifdef R_BUILD\n\n#include <Rcpp.h>\n#include <RcppEigen.h>\n// [[Rcpp::depends(RcppEigen)]]\nusing namespace Rcpp;\n\n#else\n\n#include <Eigen/Eigen>\n\n#include \"List.h\"\n\n#endif\n\n#include <iostream>\n#include <vector>\n\n#include \"Algorithm.h\"\n#include \"AlgorithmGLM.h\"\n#include \"AlgorithmPCA.h\"\n#include \"utilities.h\"\n#include \"workflow.h\"\n\ntypedef Eigen::Triplet<double> triplet;\n\nusing namespace Eigen;\nusing namespace std;\n\n// [[Rcpp::export]]\nList abessGLM_API(Eigen::MatrixXd x, Eigen::MatrixXd y, int n, int p, int normalize_type, Eigen::VectorXd weight,\n                  int algorithm_type, int model_type, int max_iter, int exchange_num, int path_type, bool is_warm_start,\n                  int ic_type, double ic_coef, int Kfold, Eigen::VectorXi sequence, Eigen::VectorXd lambda_seq,\n                  int s_min, int s_max, double lambda_min, double lambda_max, int nlambda, int screening_size,\n                  Eigen::VectorXi g_index, Eigen::VectorXi always_select, int primary_model_fit_max_iter,\n                  double primary_model_fit_epsilon, bool early_stop, bool approximate_Newton, int thread,\n                  bool covariance_update, bool sparse_matrix, int splicing_type, int sub_search,\n                  Eigen::VectorXi cv_fold_id, Eigen::VectorXi A_init) {\n#ifdef _OPENMP\n    // Eigen::initParallel();\n    int max_thread = omp_get_max_threads();\n    if (thread == 0 || thread > max_thread) {\n        thread = max_thread;\n    }\n\n    Eigen::setNbThreads(thread);\n    omp_set_num_threads(thread);\n\n#endif\n    int algorithm_list_size = max(thread, Kfold);\n    vector<Algorithm<Eigen::VectorXd, Eigen::VectorXd, double, Eigen::MatrixXd> *> algorithm_list_uni_dense(\n        algorithm_list_size);\n    vector<Algorithm<Eigen::MatrixXd, Eigen::MatrixXd, Eigen::VectorXd, Eigen::MatrixXd> *> algorithm_list_mul_dense(\n        algorithm_list_size);\n    vector<Algorithm<Eigen::VectorXd, Eigen::VectorXd, double, Eigen::SparseMatrix<double>> *>\n        algorithm_list_uni_sparse(algorithm_list_size);\n    vector<Algorithm<Eigen::MatrixXd, Eigen::MatrixXd, Eigen::VectorXd, Eigen::SparseMatrix<double>> *>\n        algorithm_list_mul_sparse(algorithm_list_size);\n\n    for (int i = 0; i < algorithm_list_size; i++) {\n        if (!sparse_matrix) {\n            if (model_type == 1) {\n                abessLm<Eigen::MatrixXd> *temp = new abessLm<Eigen::MatrixXd>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->covariance_update = covariance_update;\n                algorithm_list_uni_dense[i] = temp;\n            } else if (model_type == 2) {\n                abessLogistic<Eigen::MatrixXd> *temp = new abessLogistic<Eigen::MatrixXd>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->approximate_Newton = approximate_Newton;\n                algorithm_list_uni_dense[i] = temp;\n            } else if (model_type == 3) {\n                abessPoisson<Eigen::MatrixXd> *temp = new abessPoisson<Eigen::MatrixXd>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->approximate_Newton = approximate_Newton;\n                algorithm_list_uni_dense[i] = temp;\n            } else if (model_type == 4) {\n                abessCox<Eigen::MatrixXd> *temp = new abessCox<Eigen::MatrixXd>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->approximate_Newton = approximate_Newton;\n                algorithm_list_uni_dense[i] = temp;\n            } else if (model_type == 5) {\n                abessMLm<Eigen::MatrixXd> *temp = new abessMLm<Eigen::MatrixXd>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->covariance_update = covariance_update;\n                algorithm_list_mul_dense[i] = temp;\n            } else if (model_type == 6) {\n                abessMultinomial<Eigen::MatrixXd> *temp = new abessMultinomial<Eigen::MatrixXd>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->approximate_Newton = approximate_Newton;\n                algorithm_list_mul_dense[i] = temp;\n            } else if (model_type == 8) {\n                abessGamma<Eigen::MatrixXd> *temp = new abessGamma<Eigen::MatrixXd>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->approximate_Newton = approximate_Newton;\n                algorithm_list_uni_dense[i] = temp;\n            } else if (model_type == 9) {\n                abessOrdinal<Eigen::MatrixXd> *temp = new abessOrdinal<Eigen::MatrixXd>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                algorithm_list_mul_dense[i] = temp;\n            }\n        } else {\n            if (model_type == 1) {\n                abessLm<Eigen::SparseMatrix<double>> *temp = new abessLm<Eigen::SparseMatrix<double>>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->covariance_update = covariance_update;\n                algorithm_list_uni_sparse[i] = temp;\n            } else if (model_type == 2) {\n                abessLogistic<Eigen::SparseMatrix<double>> *temp = new abessLogistic<Eigen::SparseMatrix<double>>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->approximate_Newton = approximate_Newton;\n                algorithm_list_uni_sparse[i] = temp;\n            } else if (model_type == 3) {\n                abessPoisson<Eigen::SparseMatrix<double>> *temp = new abessPoisson<Eigen::SparseMatrix<double>>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->approximate_Newton = approximate_Newton;\n                algorithm_list_uni_sparse[i] = temp;\n            } else if (model_type == 4) {\n                abessCox<Eigen::SparseMatrix<double>> *temp = new abessCox<Eigen::SparseMatrix<double>>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->approximate_Newton = approximate_Newton;\n                algorithm_list_uni_sparse[i] = temp;\n            } else if (model_type == 5) {\n                abessMLm<Eigen::SparseMatrix<double>> *temp = new abessMLm<Eigen::SparseMatrix<double>>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->covariance_update = covariance_update;\n                algorithm_list_mul_sparse[i] = temp;\n            } else if (model_type == 6) {\n                abessMultinomial<Eigen::SparseMatrix<double>> *temp = new abessMultinomial<Eigen::SparseMatrix<double>>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->approximate_Newton = approximate_Newton;\n                algorithm_list_mul_sparse[i] = temp;\n            } else if (model_type == 8) {\n                abessGamma<Eigen::SparseMatrix<double>> *temp = new abessGamma<Eigen::SparseMatrix<double>>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                temp->approximate_Newton = approximate_Newton;\n                algorithm_list_uni_sparse[i] = temp;\n            } else if (model_type == 9) {\n                abessOrdinal<Eigen::SparseMatrix<double>> *temp = new abessOrdinal<Eigen::SparseMatrix<double>>(\n                    algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                    is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n                algorithm_list_mul_sparse[i] = temp;\n            }\n        }\n    }\n\n    // parameter list\n    Parameters parameters(sequence, lambda_seq, s_min, s_max);\n\n    List out_result;\n    if (!sparse_matrix) {\n        if (y.cols() == 1 && model_type != 5 && model_type != 6) {\n            Eigen::VectorXd y_vec = y.col(0).eval();\n\n            out_result = abessWorkflow<Eigen::VectorXd, Eigen::VectorXd, double, Eigen::MatrixXd>(\n                x, y_vec, n, p, normalize_type, weight, algorithm_type, path_type, is_warm_start, ic_type, ic_coef,\n                Kfold, parameters, screening_size, g_index, early_stop, thread, sparse_matrix, cv_fold_id, A_init,\n                algorithm_list_uni_dense);\n        } else {\n            out_result = abessWorkflow<Eigen::MatrixXd, Eigen::MatrixXd, Eigen::VectorXd, Eigen::MatrixXd>(\n                x, y, n, p, normalize_type, weight, algorithm_type, path_type, is_warm_start, ic_type, ic_coef, Kfold,\n                parameters, screening_size, g_index, early_stop, thread, sparse_matrix, cv_fold_id, A_init,\n                algorithm_list_mul_dense);\n        }\n    } else {\n        Eigen::SparseMatrix<double> sparse_x(n, p);\n\n        // std::vector<triplet> tripletList;\n        // tripletList.reserve(x.rows());\n        // for (int i = 0; i < x.rows(); i++)\n        // {\n        //   tripletList.push_back(triplet(int(x(i, 1)), int(x(i, 2)), x(i, 0)));\n        // }\n        // sparse_x.setFromTriplets(tripletList.begin(), tripletList.end());\n\n        sparse_x.reserve(x.rows());\n        for (int i = 0; i < x.rows(); i++) {\n            sparse_x.insert(int(x(i, 1)), int(x(i, 2))) = x(i, 0);\n        }\n        sparse_x.makeCompressed();\n\n        if (y.cols() == 1 && model_type != 5 && model_type != 6) {\n            Eigen::VectorXd y_vec = y.col(0).eval();\n\n            out_result = abessWorkflow<Eigen::VectorXd, Eigen::VectorXd, double, Eigen::SparseMatrix<double>>(\n                sparse_x, y_vec, n, p, normalize_type, weight, algorithm_type, path_type, is_warm_start, ic_type,\n                ic_coef, Kfold, parameters, screening_size, g_index, early_stop, thread, sparse_matrix, cv_fold_id,\n                A_init, algorithm_list_uni_sparse);\n        } else {\n            out_result = abessWorkflow<Eigen::MatrixXd, Eigen::MatrixXd, Eigen::VectorXd, Eigen::SparseMatrix<double>>(\n                sparse_x, y, n, p, normalize_type, weight, algorithm_type, path_type, is_warm_start, ic_type, ic_coef,\n                Kfold, parameters, screening_size, g_index, early_stop, thread, sparse_matrix, cv_fold_id, A_init,\n                algorithm_list_mul_sparse);\n        }\n    }\n\n    for (int i = 0; i < algorithm_list_size; i++) {\n        delete algorithm_list_uni_dense[i];\n        delete algorithm_list_mul_dense[i];\n        delete algorithm_list_uni_sparse[i];\n        delete algorithm_list_mul_sparse[i];\n    }\n\n    return out_result;\n};\n\n// [[Rcpp::export]]\nList abessPCA_API(Eigen::MatrixXd x, int n, int p, int normalize_type, Eigen::VectorXd weight, Eigen::MatrixXd sigma,\n                  int max_iter, int exchange_num, int path_type, bool is_warm_start, int ic_type, double ic_coef,\n                  int Kfold, Eigen::MatrixXi sequence, int s_min, int s_max, int screening_size,\n                  Eigen::VectorXi g_index, Eigen::VectorXi always_select, bool early_stop, int thread,\n                  bool sparse_matrix, int splicing_type, int sub_search, Eigen::VectorXi cv_fold_id, int pca_num,\n                  Eigen::VectorXi A_init) {\n    /* this function for abessPCA only (model_type == 7) */\n\n#ifdef _OPENMP\n    // Eigen::initParallel();\n    int max_thread = omp_get_max_threads();\n    if (thread == 0 || thread > max_thread) {\n        thread = max_thread;\n    }\n\n    Eigen::setNbThreads(thread);\n    omp_set_num_threads(thread);\n#endif\n    int model_type = 7, algorithm_type = 6;\n    Eigen::VectorXd lambda_seq = Eigen::VectorXd::Zero(1);\n    int lambda_min = 0, lambda_max = 0, nlambda = 100;\n    int primary_model_fit_max_iter = 1;\n    double primary_model_fit_epsilon = 1e-3;\n    int pca_n = -1;\n    sub_search = 0;\n    if (!sparse_matrix && n != x.rows()) {\n        pca_n = n;\n        n = x.rows();\n    }\n    Eigen::VectorXd y_vec = Eigen::VectorXd::Zero(n);\n\n    //////////////////// function generate_algorithm_pointer() ////////////////////////////\n    int algorithm_list_size = max(thread, Kfold);\n    vector<Algorithm<Eigen::VectorXd, Eigen::VectorXd, double, Eigen::MatrixXd> *> algorithm_list_uni_dense(\n        algorithm_list_size);\n    vector<Algorithm<Eigen::VectorXd, Eigen::VectorXd, double, Eigen::SparseMatrix<double>> *>\n        algorithm_list_uni_sparse(algorithm_list_size);\n    for (int i = 0; i < algorithm_list_size; i++) {\n        if (!sparse_matrix) {\n            abessPCA<Eigen::MatrixXd> *temp = new abessPCA<Eigen::MatrixXd>(\n                algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n            temp->is_cv = Kfold > 1;\n            temp->pca_n = pca_n;\n            temp->sigma = sigma;\n            algorithm_list_uni_dense[i] = temp;\n        } else {\n            abessPCA<Eigen::SparseMatrix<double>> *temp = new abessPCA<Eigen::SparseMatrix<double>>(\n                algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n            temp->is_cv = Kfold > 1;\n            temp->pca_n = pca_n;\n            temp->sigma = sigma;\n            algorithm_list_uni_sparse[i] = temp;\n        }\n    }\n\n    // call `abessWorkflow` for result\n#ifdef R_BUILD\n    List out_result(pca_num);\n#else\n    List out_result;\n#endif\n    List out_result_next;\n    int num = 0;\n\n    if (!sparse_matrix) {\n        while (num++ < pca_num) {\n            int pca_support_size_num = sequence.col(num - 1).sum();\n            Eigen::VectorXi pca_support_size(pca_support_size_num);\n            // map sequence matrix to support.size\n            int non_zero_num = 0;\n            for (int i = 0; i < sequence.rows(); i++) {\n                if (sequence(i, num - 1) == 1) {\n                    pca_support_size(non_zero_num++) = i + 1;\n                }\n            }\n\n            // parameter list\n            Parameters parameters(pca_support_size, lambda_seq, s_min, s_max);\n\n            out_result_next = abessWorkflow<Eigen::VectorXd, Eigen::VectorXd, double, Eigen::MatrixXd>(\n                x, y_vec, n, p, normalize_type, weight, algorithm_type, path_type, is_warm_start, ic_type, ic_coef,\n                Kfold, parameters, screening_size, g_index, early_stop, thread, sparse_matrix, cv_fold_id, A_init,\n                algorithm_list_uni_dense);\n            Eigen::VectorXd beta_next;\n#ifdef R_BUILD\n            beta_next = out_result_next[\"beta\"];\n#else\n            out_result_next.get_value_by_name(\"beta\", beta_next);\n#endif\n            if (num == 1) {\n#ifdef R_BUILD\n                if (pca_num > 1) {\n                    out_result(0) = out_result_next;\n                } else {\n                    out_result = out_result_next;\n                }\n#else\n                out_result = out_result_next;\n#endif\n            } else {\n#ifdef R_BUILD\n                // Eigen::MatrixXd beta_new(p, num);\n                // Eigen::VectorXd temp = out_result[\"beta\"];\n                // Eigen::Map<Eigen::MatrixXd> temp2(temp.data(), p, num - 1);\n                // beta_new << temp2, beta_next;\n                // out_result[\"beta\"] = beta_new;\n                out_result(num - 1) = out_result_next;\n#else\n                out_result.combine_beta(beta_next);\n#endif\n            }\n\n            if (num < pca_num) {\n                Eigen::MatrixXd temp = beta_next * beta_next.transpose();\n                if (Kfold > 1) {\n                    x -= x * temp;\n                } else {\n                    Eigen::MatrixXd temp1 = temp * sigma;\n                    sigma += temp1 * temp - temp1 - temp1.transpose();\n                    for (int i = 0; i < algorithm_list_size; i++) {\n                        abessPCA<Eigen::MatrixXd> *pca_model =\n                            dynamic_cast<abessPCA<Eigen::MatrixXd> *>(algorithm_list_uni_dense[i]);\n                        if (pca_model) {\n                            // cout << \"update Sigma\"<<endl;\n                            pca_model->sigma = sigma;\n                        }\n                    }\n                }\n            }\n        }\n    } else {\n        Eigen::SparseMatrix<double> sparse_x(n, p);\n\n        // std::vector<triplet> tripletList;\n        // tripletList.reserve(x.rows());\n        // for (int i = 0; i < x.rows(); i++)\n        // {\n        //   tripletList.push_back(triplet(int(x(i, 1)), int(x(i, 2)), x(i, 0)));\n        // }\n        // sparse_x.setFromTriplets(tripletList.begin(), tripletList.end());\n\n        sparse_x.reserve(x.rows());\n        for (int i = 0; i < x.rows(); i++) {\n            sparse_x.insert(int(x(i, 1)), int(x(i, 2))) = x(i, 0);\n        }\n        sparse_x.makeCompressed();\n\n        while (num++ < pca_num) {\n            int pca_support_size_num = sequence.col(num - 1).sum();\n            Eigen::VectorXi pca_support_size(pca_support_size_num);\n            // map sequence matrix to support.size\n            int non_zero_num = 0;\n            for (int i = 0; i < sequence.rows(); i++) {\n                if (sequence(i, num - 1) == 1) {\n                    pca_support_size(non_zero_num++) = i + 1;\n                }\n            }\n\n            // parameter list\n            Parameters parameters(pca_support_size, lambda_seq, s_min, s_max);\n\n            out_result_next = abessWorkflow<Eigen::VectorXd, Eigen::VectorXd, double, Eigen::SparseMatrix<double>>(\n                sparse_x, y_vec, n, p, normalize_type, weight, algorithm_type, path_type, is_warm_start, ic_type,\n                ic_coef, Kfold, parameters, screening_size, g_index, early_stop, thread, sparse_matrix, cv_fold_id,\n                A_init, algorithm_list_uni_sparse);\n            Eigen::VectorXd beta_next;\n#ifdef R_BUILD\n            beta_next = out_result_next[\"beta\"];\n#else\n            out_result_next.get_value_by_name(\"beta\", beta_next);\n#endif\n            if (num == 1) {\n#ifdef R_BUILD\n                if (pca_num > 1) {\n                    out_result(0) = out_result_next;\n                } else {\n                    out_result = out_result_next;\n                }\n#else\n                out_result = out_result_next;\n#endif\n            } else {\n#ifdef R_BUILD\n                // Eigen::MatrixXd beta_new(p, num);\n                // Eigen::VectorXd temp = out_result[\"beta\"];\n                // Eigen::Map<Eigen::MatrixXd> temp2(temp.data(), p, num - 1);\n                // beta_new << temp2, beta_next;\n                // out_result[\"beta\"] = beta_new;\n                out_result(num - 1) = out_result_next;\n#else\n                out_result.combine_beta(beta_next);\n#endif\n            }\n\n            // update for next PCA\n            if (num < pca_num) {\n                Eigen::MatrixXd temp = beta_next * beta_next.transpose();\n                if (Kfold > 1) {\n                    sparse_x = sparse_x - sparse_x * temp;\n                } else {\n                    Eigen::MatrixXd temp1 = temp * sigma;\n                    sigma += temp1 * temp - temp1 - temp1.transpose();\n                    for (int i = 0; i < algorithm_list_size; i++) {\n                        abessPCA<Eigen::SparseMatrix<double>> *pca_model =\n                            dynamic_cast<abessPCA<Eigen::SparseMatrix<double>> *>(algorithm_list_uni_sparse[i]);\n                        if (pca_model) {\n                            // cout << \"update Sigma\"<<endl;\n                            pca_model->sigma = sigma;\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    for (int i = 0; i < algorithm_list_size; i++) {\n        delete algorithm_list_uni_dense[i];\n        delete algorithm_list_uni_sparse[i];\n    }\n    return out_result;\n};\n\n// [[Rcpp::export]]\nList abessRPCA_API(Eigen::MatrixXd x, int n, int p, int max_iter, int exchange_num, int path_type, bool is_warm_start,\n                   int ic_type, double ic_coef, Eigen::VectorXi sequence,\n                   Eigen::VectorXd lambda_seq,  // rank of L\n                   int s_min, int s_max, double lambda_min, double lambda_max, int nlambda, int screening_size,\n                   int primary_model_fit_max_iter, double primary_model_fit_epsilon, Eigen::VectorXi g_index,\n                   Eigen::VectorXi always_select, bool early_stop, int thread, bool sparse_matrix, int splicing_type,\n                   int sub_search, Eigen::VectorXi A_init) {\n#ifdef _OPENMP\n    // Eigen::initParallel();\n    int max_thread = omp_get_max_threads();\n    if (thread == 0 || thread > max_thread) {\n        thread = max_thread;\n    }\n\n    Eigen::setNbThreads(thread);\n    omp_set_num_threads(thread);\n\n#endif\n    int model_type = 10, algorithm_type = 6;\n    int Kfold = 1;\n    int normalize_type = 0;\n    Eigen::VectorXi cv_fold_id = Eigen::VectorXi::Zero(0);\n    Eigen::VectorXd weight = Eigen::VectorXd::Ones(n);\n    Eigen::VectorXd y_vec = Eigen::VectorXd::Zero(n);\n\n    int algorithm_list_size = max(thread, Kfold);\n    vector<Algorithm<Eigen::VectorXd, Eigen::VectorXd, double, Eigen::MatrixXd> *> algorithm_list_uni_dense(\n        algorithm_list_size);\n    vector<Algorithm<Eigen::VectorXd, Eigen::VectorXd, double, Eigen::SparseMatrix<double>> *>\n        algorithm_list_uni_sparse(algorithm_list_size);\n\n    for (int i = 0; i < algorithm_list_size; i++) {\n        if (!sparse_matrix) {\n            abessRPCA<Eigen::MatrixXd> *temp = new abessRPCA<Eigen::MatrixXd>(\n                algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n            temp->r = lambda_seq(0);\n            algorithm_list_uni_dense[i] = temp;\n        } else {\n            abessRPCA<Eigen::SparseMatrix<double>> *temp = new abessRPCA<Eigen::SparseMatrix<double>>(\n                algorithm_type, model_type, max_iter, primary_model_fit_max_iter, primary_model_fit_epsilon,\n                is_warm_start, exchange_num, always_select, splicing_type, sub_search);\n            temp->r = lambda_seq(0);\n            algorithm_list_uni_sparse[i] = temp;\n        }\n    }\n\n    // parameter list\n    Parameters parameters(sequence, lambda_seq, s_min, s_max);\n\n    List out_result;\n    if (!sparse_matrix) {\n        out_result = abessWorkflow<Eigen::VectorXd, Eigen::VectorXd, double, Eigen::MatrixXd>(\n            x, y_vec, n, p, normalize_type, weight, algorithm_type, path_type, is_warm_start, ic_type, ic_coef, Kfold,\n            parameters, screening_size, g_index, early_stop, thread, sparse_matrix, cv_fold_id, A_init,\n            algorithm_list_uni_dense);\n\n    } else {\n        Eigen::SparseMatrix<double> sparse_x(n, p);\n\n        // std::vector<triplet> tripletList;\n        // tripletList.reserve(x.rows());\n        // for (int i = 0; i < x.rows(); i++)\n        // {\n        //   tripletList.push_back(triplet(int(x(i, 1)), int(x(i, 2)), x(i, 0)));\n        // }\n        // sparse_x.setFromTriplets(tripletList.begin(), tripletList.end());\n\n        sparse_x.reserve(x.rows());\n        for (int i = 0; i < x.rows(); i++) {\n            sparse_x.insert(int(x(i, 1)), int(x(i, 2))) = x(i, 0);\n        }\n        sparse_x.makeCompressed();\n\n        out_result = abessWorkflow<Eigen::VectorXd, Eigen::VectorXd, double, Eigen::SparseMatrix<double>>(\n            sparse_x, y_vec, n, p, normalize_type, weight, algorithm_type, path_type, is_warm_start, ic_type, ic_coef,\n            Kfold, parameters, screening_size, g_index, early_stop, thread, sparse_matrix, cv_fold_id, A_init,\n            algorithm_list_uni_sparse);\n    }\n\n    for (int i = 0; i < algorithm_list_size; i++) {\n        delete algorithm_list_uni_dense[i];\n        delete algorithm_list_uni_sparse[i];\n    }\n\n    return out_result;\n}\n", "meta": {"hexsha": "c11084d47ca2ccdb6295a089c0b5d4155dac1702", "size": 25567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/api.cpp", "max_stars_repo_name": "bbayukari/abess", "max_stars_repo_head_hexsha": "3b21b0a58cac6c1464ec9403ffbe4902fee7b890", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/api.cpp", "max_issues_repo_name": "bbayukari/abess", "max_issues_repo_head_hexsha": "3b21b0a58cac6c1464ec9403ffbe4902fee7b890", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/api.cpp", "max_forks_repo_name": "bbayukari/abess", "max_forks_repo_head_hexsha": "3b21b0a58cac6c1464ec9403ffbe4902fee7b890", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6996268657, "max_line_length": 120, "alphanum_fraction": 0.6041772597, "num_tokens": 5916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4489965644985545}}
{"text": "/**\n* \\file importance_sampling.cpp\n* \\brief main file for importance sampling method to infere the age of edges \nin a network.\n* \\author Guillaume St-Onge\n* \\version 1.0\n* \\date 08/11/2017\n*/\n\n#include \"DynamicNetwork.hpp\"\n#include \"auxiliaryFunctions.hpp\"\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/discrete_distribution.hpp>\n#include <chrono>\n\nusing namespace std;\nusing namespace DynNet;\n\ntypedef boost::random::uniform_01<> uniform_01;\ntypedef boost::random::uniform_int_distribution<> uniform_int;\n\nconst unsigned int CALIBSIZE = 100;\nint main(int argc, char const *argv[])\n{\n\t//Parameters\n\tstring path = argv[1];\n\tdouble gamma = stod(argv[2]);\n\tdouble b = stod(argv[3]);\n\tunsigned int sampleSize = atoi(argv[4]);\n\tdouble seedExponent = stod(argv[5]);\n\tunsigned int seed;\n\tif (argc == 6)\n\t{\n\t\tseed = (unsigned int) std::chrono::high_resolution_clock::now().time_since_epoch().count();\n\t}\n\telse\n\t{\n\t\tseed = atoi(argv[6]);\n\t}\n\n\tunsigned int calibSize;\n\tif (sampleSize > CALIBSIZE)\n\t{\n\t\tcalibSize = CALIBSIZE;\n\t}\n\telse\n\t{\n\t\tcalibSize = sampleSize;\n\t}\n\tpair<double,double> param(gamma,b);\n\n\t//Load edgeList\n\tvector<edge> edgeList = input_edgeList(path);\n\tsize_t M = edgeList.size();\n\n\t//Create unvarying maps associated to the observed network\n\tunordered_map<node,set<node> > neighborMap;\n\tunordered_map<node, unsigned int> degreeMap;\n\tedgeIntMap multiplicityMap;\n\tfor (int i = 0; i < edgeList.size(); ++i)\n\t{\n\t\t//edges are assume to be in ascending order\n\t\tneighborMap[edgeList[i].first].insert(edgeList[i].second);\n\t\tneighborMap[edgeList[i].second].insert(edgeList[i].first);\n\t\tif (multiplicityMap.find(edgeList[i]) == \n\t\t\tmultiplicityMap.end())\n\t\t{\n\t\t\tmultiplicityMap[edgeList[i]] = 1;\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmultiplicityMap[edgeList[i]] += 1;\n\t\t}\n\t\tif (degreeMap.find(edgeList[i].first) != degreeMap.end())\n\t\t{\n\t\t\tdegreeMap[edgeList[i].first] += 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdegreeMap[edgeList[i].first] = 1;\n\t\t}\n\t\tif (degreeMap.find(edgeList[i].second) != degreeMap.end())\n\t\t{\n\t\t\tdegreeMap[edgeList[i].second] += 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdegreeMap[edgeList[i].second] = 1;\n\t\t}\n\t}\n\tsize_t N = degreeMap.size();\n\n\t//Initialize mean marginal estimation\n\tunordered_map< edge, vector<double>, \n\t\tboost::hash<edge> > meanMarginalMap;\n\tfor (auto iter = multiplicityMap.begin(); iter != multiplicityMap.end(); \n\t\t++iter)\n\t{\n\t\tvector<double> emptyVector(iter->second, 0.);\n\t\tmeanMarginalMap[iter->first] = emptyVector;\n\t}\n\tdouble effectiveWeightSum = 0.;\n\n\t/*=======================================\n\t\tCalibration of the mean logweight\n\t=======================================*/\n\n\tvector<DynamicNetwork> calibSample;\n\n\t//Initialize random number generator and seed distribution\n\tRNGType gen(seed);\n\tvector<double> seedWeightVector;\n\tfor (auto iter = edgeList.begin(); iter != edgeList.end() ; ++iter)\n\t{\n\t\tif (iter->first == iter->second)\n\t\t{\n\t\t\tseedWeightVector.push_back(0.);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tseedWeightVector.push_back(pow(degreeMap[iter->first]\n\t\t\t\t*degreeMap[iter->second],seedExponent));\n\t\t}\n\t}\n\tboost::random::discrete_distribution<int> seedDist(seedWeightVector.begin(),\n\t\tseedWeightVector.end());\n\n\t//Get calibrating sample\n\tfor (int n = 0; n < calibSize; ++n)\n\t{\n\t\t//Initialize dynamic network\n\t\tDynamicNetwork net(neighborMap, multiplicityMap);\n\n\t\t//choose a first random edge\n\t\tint seedIndex = seedDist(gen);\n\t\tedge seedEdge = edgeList[seedIndex];\n\t\tdouble seedInvWeight = 1/(seedWeightVector[seedIndex]);\n\t\tnet.init(seedEdge, seedInvWeight);\n\t\t//init degree norm\n\t\tdouble degreeNormalization = 2.; //initial loop are impossible\n\n\t\t//Reconstruct the network\n\t\twhile (net.get_reachableEdgeSet().size() > 0)\n\t\t{\n\t\t\tadd_edge(net, param, degreeNormalization, gen);\n\t\t}\n\t\tcalibSample.push_back(net);\n\t}\n\n\t//Determine mean logweight from calibration\n\tdouble meanLogweight = 0.;\n\tfor (int n = 0; n < calibSize; ++n)\n\t{\n\t\tmeanLogweight += calibSample[n].get_logweight();\t\n\t}\n\tmeanLogweight /= calibSize;\n\n\t//Estimate the mean marginal from the sample\n\tfor (int n = 0; n < calibSize; ++n)\n\t{\n\t\tupdate_meanMarginal(calibSample[n], meanMarginalMap, meanLogweight,\n\t\t\teffectiveWeightSum);\n\t}\n\tcalibSample.clear();\n\n\t/*=======================================\n\t       Refining the mean marginal\n\t=======================================*/\n\n\tfor (int n = 0; n < sampleSize-calibSize; ++n)\n\t{\n\t\t//Initialize dynamic network\n\t\tDynamicNetwork net(neighborMap, multiplicityMap);\n\n\t\t//choose a first random edge\n\t\tint seedIndex = seedDist(gen);\n\t\tedge seedEdge = edgeList[seedIndex];\n\t\tdouble seedInvWeight = 1/(seedWeightVector[seedIndex]);\n\t\tnet.init(seedEdge, seedInvWeight);\n\t\t//init degree norm\n\t\tdouble degreeNormalization = 2.; //initial loop are impossible\n\n\t\t//Reconstruct the network\n\t\twhile (net.get_reachableEdgeSet().size() > 0)\n\t\t{\n\t\t\tadd_edge(net, param, degreeNormalization, gen);\n\t\t}\n\t\t\n\t\tupdate_meanMarginal(net, meanMarginalMap, meanLogweight,\n\t\t\teffectiveWeightSum);\n\t}\n\n\t/*=======================================\n\t       \t\tOutput the data\n\t=======================================*/\n\tfor (auto iter = meanMarginalMap.begin(); iter != meanMarginalMap.end(); \n\t\t++iter)\n\t{\n\t\tdouble average = 0;\n\t\tfor (int i = 0; i < (iter->second).size(); ++i)\n\t\t{\n\t\t\taverage += (iter->second)[i]/effectiveWeightSum;\n\t\t}\n\t\tfor (int i = 0; i < (iter->second).size(); ++i)\n\t\t{\n\t\t\tcout << (iter->first).first << \" \" << (iter->first).second << \" \" << i << \" \";\n\t\t\tcout << average / double((iter->second).size()) << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}", "meta": {"hexsha": "6b526978bb6cea400caed492b64c60b5552ca2c8", "size": 5562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/bins/importance_sampling_cpp/src/random_sampling_std.cpp", "max_stars_repo_name": "junipertcy/network-archaeology", "max_stars_repo_head_hexsha": "7cef0de7a388e8dde812e746d50470d167da8a9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/bins/importance_sampling_cpp/src/random_sampling_std.cpp", "max_issues_repo_name": "junipertcy/network-archaeology", "max_issues_repo_head_hexsha": "7cef0de7a388e8dde812e746d50470d167da8a9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/bins/importance_sampling_cpp/src/random_sampling_std.cpp", "max_forks_repo_name": "junipertcy/network-archaeology", "max_forks_repo_head_hexsha": "7cef0de7a388e8dde812e746d50470d167da8a9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6313364055, "max_line_length": 93, "alphanum_fraction": 0.6587558432, "num_tokens": 1585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4489825667348353}}
{"text": "/*\n *                This source code is part of\n *\n *                     E  R  K  A  L  E\n *                             -\n *                       DFT from Hel\n *\n * Written by Susi Lehtola, 2010-2011\n * Copyright (c) 2010-2011, Susi Lehtola\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n */\n\n\n\n#include <armadillo>\n#include <cfloat>\n#include <cstdio>\n#include <sstream>\n#include <stdexcept>\n\n#include \"obara-saika.h\"\n#include \"integrals.h\"\n#include \"mathf.h\"\n\n// For comparison against Huzinaga integrals\n//#define DEBUG\n\narma::mat overlap_int_os(double xa, double ya, double za, double zetaa, const std::vector<shellf_t> & carta, double xb, double yb, double zb, double zetab, const std::vector<shellf_t> & cartb) {\n  // Compute shell of overlap integrals\n\n  // Angular momenta of shells\n  int am_a=carta[0].l+carta[0].m+carta[0].n;\n  int am_b=cartb[0].l+cartb[0].m+cartb[0].n;\n\n  // Returned matrix\n  arma::mat S(carta.size(),cartb.size());\n  S.zeros();\n\n  // Get 1d overlaps\n  arma::mat ox=overlap_ints_1d(xa,xb,zetaa,zetab,am_a,am_b);\n  arma::mat oy=overlap_ints_1d(ya,yb,zetaa,zetab,am_a,am_b);\n  arma::mat oz=overlap_ints_1d(za,zb,zetaa,zetab,am_a,am_b);\n\n  int la, ma, na;\n  int lb, mb, nb;\n  double norma, normb;\n\n  for(size_t i=0;i<carta.size();i++) {\n      la=carta[i].l;\n      ma=carta[i].m;\n      na=carta[i].n;\n      norma=carta[i].relnorm;\n\n    for(size_t j=0;j<cartb.size();j++) {\n      lb=cartb[j].l;\n      mb=cartb[j].m;\n      nb=cartb[j].n;\n      normb=cartb[j].relnorm;\n\n      S(i,j)=norma*normb*ox(la,lb)*oy(ma,mb)*oz(na,nb);\n\n    }\n  }\n\n#ifdef DEBUG\n  arma::mat huz(carta.size(),cartb.size());\n  for(size_t i=0;i<carta.size();i++) {\n    la=carta[i].l;\n    ma=carta[i].m;\n    na=carta[i].n;\n    norma=carta[i].relnorm;\n\n    for(size_t j=0;j<cartb.size();j++) {\n      lb=cartb[j].l;\n      mb=cartb[j].m;\n      nb=cartb[j].n;\n      normb=cartb[j].relnorm;\n\n      huz(i,j)=norma*normb*overlap_int(xa,ya,za,zetaa,la,ma,na,xb,yb,zb,zetab,lb,mb,nb);\n    }\n  }\n\n  int diff=0;\n  for(size_t i=0;i<carta.size();i++)\n    for(size_t j=0;j<cartb.size();j++)\n      if(fabs(S(i,j)-huz(i,j))>10*DBL_EPSILON*fabs(huz(i,j)))\n\tdiff++;\n\n  if(diff==0)\n    //    printf(\"Computed shell of overlaps (%e,%e,%e)-(%e,%e,%e) with zeta=(%e,%e) and am=(%i,%i), the results match.\\n\",xa,ya,za,xb,yb,zb,zetaa,zetab,am_a,am_b);\n    ;\n  else\n      for(size_t i=0;i<carta.size();i++)\n\tfor(size_t j=0;j<cartb.size();j++)\n\t  if(fabs(S(i,j)-huz(i,j))>10*DBL_EPSILON*fabs(huz(i,j))) {\n\t    printf(\"Computed overlap (%e,%e,%e)-(%e,%e,%e) with zeta=(%e,%e) and am=(%i,%i,%i)-(%i,%i,%i)\\n\",xa,ya,za,xb,yb,zb,zetaa,zetab,la,ma,na,lb,mb,nb);\n\t    printf(\"Huzinaga gives %e, OS gives %e.\\n\",huz(i,j),S(i,j));\n\t  }\n\n#endif\n\n  return S;\n}\n\nstd::vector<arma::mat> overlap_int_pulay_os(double xa, double ya, double za, double zetaa, const std::vector<shellf_t> & carta, double xb, double yb, double zb, double zetab, const std::vector<shellf_t> & cartb) {\n  // Compute shell of overlap integrals\n\n  // Angular momenta of shells\n  int am_a=carta[0].l+carta[0].m+carta[0].n;\n  int am_b=cartb[0].l+cartb[0].m+cartb[0].n;\n\n  // Returned matrix\n  std::vector<arma::mat> S(6);\n  for(int ic=0;ic<6;ic++)\n    S[ic].zeros(carta.size(),cartb.size());\n\n  // Get 1d overlaps\n  arma::mat ox=overlap_ints_1d(xa,xb,zetaa,zetab,am_a+1,am_b+1);\n  arma::mat oy=overlap_ints_1d(ya,yb,zetaa,zetab,am_a+1,am_b+1);\n  arma::mat oz=overlap_ints_1d(za,zb,zetaa,zetab,am_a+1,am_b+1);\n\n  int la, ma, na;\n  int lb, mb, nb;\n  double norma, normb;\n\n  for(size_t i=0;i<carta.size();i++) {\n      la=carta[i].l;\n      ma=carta[i].m;\n      na=carta[i].n;\n      norma=carta[i].relnorm;\n\n    for(size_t j=0;j<cartb.size();j++) {\n      lb=cartb[j].l;\n      mb=cartb[j].m;\n      nb=cartb[j].n;\n      normb=cartb[j].relnorm;\n\n      // LHS derivatives\n      S[0](i,j)=2*zetaa*ox(la+1,lb)*oy(ma,mb)*oz(na,nb);\n      if(la>0)\n\tS[0](i,j)-=la*ox(la-1,lb)*oy(ma,mb)*oz(na,nb);\n      S[0](i,j)*=-norma*normb;\n\n      S[1](i,j)=2*zetaa*ox(la,lb)*oy(ma+1,mb)*oz(na,nb);\n      if(ma>0)\n\tS[1](i,j)-=ma*ox(la,lb)*oy(ma-1,mb)*oz(na,nb);\n      S[1](i,j)*=-norma*normb;\n\n      S[2](i,j)=2*zetaa*ox(la,lb)*oy(ma,mb)*oz(na+1,nb);\n      if(na>0)\n\tS[2](i,j)-=na*ox(la,lb)*oy(ma,mb)*oz(na-1,nb);\n      S[2](i,j)*=-norma*normb;\n\n      // RHS derivatives\n      S[3](i,j)=2*zetab*ox(la,lb+1)*oy(ma,mb)*oz(na,nb);\n      if(lb>0)\n\tS[3](i,j)-=lb*ox(la,lb-1)*oy(ma,mb)*oz(na,nb);\n      S[3](i,j)*=-norma*normb;\n\n      S[4](i,j)=2*zetab*ox(la,lb)*oy(ma,mb+1)*oz(na,nb);\n      if(mb>0)\n\tS[4](i,j)-=mb*ox(la,lb)*oy(ma,mb-1)*oz(na,nb);\n      S[4](i,j)*=-norma*normb;\n\n      S[5](i,j)=2*zetab*ox(la,lb)*oy(ma,mb)*oz(na,nb+1);\n      if(nb>0)\n\tS[5](i,j)-=nb*ox(la,lb)*oy(ma,mb)*oz(na,nb-1);\n      S[5](i,j)*=-norma*normb;\n  }\n  }\n\n  return S;\n}\n\ndouble overlap_int_os(double xa, double ya, double za, double zetaa, int la, int ma, int na, double xb, double yb, double zb, double zetab, int lb, int mb, int nb) {\n  return overlap_int_1d(xa,xb,zetaa,zetab,la,lb)*overlap_int_1d(ya,yb,zetaa,zetab,ma,mb)*overlap_int_1d(za,zb,zetaa,zetab,na,nb);\n}\n\ndouble overlap_int_1d(double xa, double xb, double zetaa, double zetab, int la, int lb) {\n  return overlap_ints_1d(xa,xb,zetaa,zetab,la,lb)(la,lb);\n}\n\narma::mat overlap_ints_1d(double xa, double xb, double zetaa, double zetab, int la, int lb) {\n  // In the following we assume la>lb.\n  if(lb<la) // Switch arguments if necessary.\n    return trans(overlap_ints_1d(xb,xa,zetab,zetaa,lb,la));\n\n  // Compute exponents\n  double p=zetaa+zetab;\n  double mu=zetaa*zetab/(zetaa+zetab);\n\n  // Compute center\n  double px=(zetaa*xa+zetab*xb)/p;\n\n  double xab=xa-xb;\n  double xpb=px-xb;\n\n  // We want to compute S_{la lb} with recurrence relations\n  // S_{i+1,j} = X_{PA} S_{i,j} + 1/2p * (iS_{i-1,j}+jS_{i,j-1})\n  // S_{i,j+1} = X_{PB} S_{i,j} + 1/2p * (iS_{i-1,j}+jS_{i,j-1})\n\n  // We need some extra work space to use the recursion relations\n  int lawrk=la+1;\n  int lbwrk=lb+la+2;\n\n  arma::mat S(lawrk,lbwrk);\n  S.zeros();\n\n  // Initialize S_{00}\n  S(0,0)=sqrt(M_PI/p)*exp(-mu*xab*xab);\n\n  if(la>0 || lb>0) {\n\n    // Generate integrals S_{0,j}\n    S(0,1)=xpb*S(0,0);\n    for(int j=1;j<lbwrk-1;j++) {\n      S(0,j+1)=xpb*S(0,j)+0.5/p*j*S(0,j-1);\n    }\n\n    // Use horizontal recurrence to generate S_{ij}\n    // S_{i+1,j} = S_{i,j+1} - X_{AB} S_{ij}\n    for(int i=0;i<la;i++) {\n      for(int j=0;j<lb+la-i;j++) {\n\tS(i+1,j)=S(i,j+1)-xab*S(i,j);\n      }\n    }\n  }\n\n  // Return result, dropping the temporary\n  return S.submat(0,0,la,lb);\n}\n\narma::mat kinetic_int_os(double xa, double ya, double za, double zetaa, const std::vector<shellf_t> & carta, double xb, double yb, double zb, double zetab, const std::vector<shellf_t> & cartb) {\n  // Compute shell of kinetic energy integrals\n\n  // Angular momenta of shells\n  int am_a=carta[0].l+carta[0].m+carta[0].n;\n  int am_b=cartb[0].l+cartb[0].m+cartb[0].n;\n\n  // Returned matrix\n  arma::mat T(carta.size(),cartb.size());\n\n  // Get 1d overlap integrals\n  arma::mat ox_arr=overlap_ints_1d(xa,xb,zetaa,zetab,am_a,am_b);\n  arma::mat oy_arr=overlap_ints_1d(ya,yb,zetaa,zetab,am_a,am_b);\n  arma::mat oz_arr=overlap_ints_1d(za,zb,zetaa,zetab,am_a,am_b);\n\n  // Get kinetic energy integrals\n  arma::mat kx_arr=derivative_ints_1d(xa,xb,zetaa,zetab,am_a,am_b,2);\n  arma::mat ky_arr=derivative_ints_1d(ya,yb,zetaa,zetab,am_a,am_b,2);\n  arma::mat kz_arr=derivative_ints_1d(za,zb,zetaa,zetab,am_a,am_b,2);\n\n  double ox, oy, oz;\n  double kx, ky, kz;\n\n  int la, ma, na;\n  int lb, mb, nb;\n\n  double anorm, bnorm;\n\n  for(size_t i=0;i<carta.size();i++) {\n    anorm=carta[i].relnorm;\n\n    la=carta[i].l;\n    ma=carta[i].m;\n    na=carta[i].n;\n\n    for(size_t j=0;j<cartb.size();j++) {\n      lb=cartb[j].l;\n      mb=cartb[j].m;\n      nb=cartb[j].n;\n\n      bnorm=cartb[j].relnorm;\n\n      ox=ox_arr(la,lb);\n      oy=oy_arr(ma,mb);\n      oz=oz_arr(na,nb);\n\n      kx=kx_arr(la,lb);\n      ky=ky_arr(ma,mb);\n      kz=kz_arr(na,nb);\n\n      T(i,j)=-0.5*anorm*bnorm*(kx*oy*oz + ox*ky*oz + ox*oy*kz);\n    }\n  }\n\n#ifdef DEBUG\n\n  arma::mat huz(carta.size(),cartb.size());\n  for(size_t i=0;i<carta.size();i++) {\n    la=carta[i].l;\n    ma=carta[i].m;\n    na=carta[i].n;\n    anorm=carta[i].relnorm;\n\n    for(size_t j=0;j<cartb.size();j++) {\n      lb=cartb[j].l;\n      mb=cartb[j].m;\n      nb=cartb[j].n;\n      bnorm=cartb[j].relnorm;\n\n      huz(i,j)=anorm*bnorm*kinetic_int(xa,ya,za,zetaa,la,ma,na,xb,yb,zb,zetab,lb,mb,nb);\n    }\n  }\n\n  int diff=0;\n  for(size_t i=0;i<carta.size();i++)\n    for(size_t j=0;j<cartb.size();j++)\n      if(fabs(T(i,j)-huz(i,j))>10*DBL_EPSILON*fabs(huz(i,j)))\n\tdiff++;\n\n  if(diff==0)\n    //    printf(\"Computed shell of KE (%e,%e,%e)-(%e,%e,%e) with zeta=(%e,%e) and am=(%i,%i), the results match.\\n\",xa,ya,za,xb,yb,zb,zetaa,zetab,am_a,am_b);\n    ;\n  else\n      for(size_t i=0;i<carta.size();i++)\n\tfor(size_t j=0;j<cartb.size();j++)\n\t  if(fabs(T(i,j)-huz(i,j))>1000*DBL_EPSILON*fabs(huz(i,j))) {\n\t    printf(\"Computed KE (%e,%e,%e)-(%e,%e,%e) with zeta=(%e,%e) and am=(%i,%i,%i)-(%i,%i,%i)\\n\",xa,ya,za,xb,yb,zb,zetaa,zetab,la,ma,na,lb,mb,nb);\n\t    printf(\"Huzinaga gives %e, OS gives %e.\\n\",huz(i,j),T(i,j));\n\t  }\n\n#endif\n\n  return T;\n}\n\nstd::vector<arma::mat> kinetic_int_pulay_os(double xa, double ya, double za, double zetaa, const std::vector<shellf_t> & carta, double xb, double yb, double zb, double zetab, const std::vector<shellf_t> & cartb) {\n  // Compute shell of kinetic energy integrals\n\n  // Angular momenta of shells\n  int am_a=carta[0].l+carta[0].m+carta[0].n;\n  int am_b=cartb[0].l+cartb[0].m+cartb[0].n;\n\n  // Returned matrix\n  std::vector<arma::mat> T(6);\n  for(int ic=0;ic<6;ic++)\n    T[ic].zeros(carta.size(),cartb.size());\n\n  // Get 1d overlap integrals\n  arma::mat ox_arr=overlap_ints_1d(xa,xb,zetaa,zetab,am_a+1,am_b+1);\n  arma::mat oy_arr=overlap_ints_1d(ya,yb,zetaa,zetab,am_a+1,am_b+1);\n  arma::mat oz_arr=overlap_ints_1d(za,zb,zetaa,zetab,am_a+1,am_b+1);\n\n  // Get kinetic energy integrals\n  arma::mat kx_arr=derivative_ints_1d(xa,xb,zetaa,zetab,am_a+1,am_b+1,2);\n  arma::mat ky_arr=derivative_ints_1d(ya,yb,zetaa,zetab,am_a+1,am_b+1,2);\n  arma::mat kz_arr=derivative_ints_1d(za,zb,zetaa,zetab,am_a+1,am_b+1,2);\n\n  int la, ma, na;\n  int lb, mb, nb;\n\n  double ox, oy, oz;\n  double oxp, oyp, ozp;\n  double oxm, oym, ozm;\n  double kx, ky, kz;\n  double kxp, kyp, kzp;\n  double kxm, kym, kzm;\n\n  double anorm, bnorm;\n\n  for(size_t i=0;i<carta.size();i++) {\n    anorm=carta[i].relnorm;\n\n    la=carta[i].l;\n    ma=carta[i].m;\n    na=carta[i].n;\n\n    for(size_t j=0;j<cartb.size();j++) {\n      lb=cartb[j].l;\n      mb=cartb[j].m;\n      nb=cartb[j].n;\n\n      bnorm=cartb[j].relnorm;\n\n      // LHS, derivative acting on x component. The lhs function with\n      // cartesian angular momentum (la,ma,na) becomes two functions:\n      // sqrt[(2 la+1) zetaa] (la+1,ma,na) - 2 la sqrt[zetaa / (2 la -1)] (la-1,ma,na)\n      // note that derivatives are with respect to normalized functions!\n\n      {\n\toxp=ox_arr(la+1,lb);\n\toy=oy_arr(ma,mb);\n\toz=oz_arr(na,nb);\n\n\tkxp=kx_arr(la+1,lb);\n\tky=ky_arr(ma,mb);\n\tkz=kz_arr(na,nb);\n\n\tT[0](i,j)= 2*zetaa*(kxp*oy*oz + oxp*ky*oz + oxp*oy*kz);\n\tif(la>0) {\n\t  oxm=ox_arr(la-1,lb);\n\t  kxm=kx_arr(la-1,lb);\n\t  T[0](i,j)-=la*(kxm*oy*oz + oxm*ky*oz + oxm*oy*kz);\n\t}\n\tT[0](i,j)*=0.5*anorm*bnorm;\n      }\n\n      // LHS, derivative acting on y component\n      {\n\tox=ox_arr(la,lb);\n\toyp=oy_arr(ma+1,mb);\n\toz=oz_arr(na,nb);\n\n\tkx=kx_arr(la,lb);\n\tkyp=ky_arr(ma+1,mb);\n\tkz=kz_arr(na,nb);\n\n\tT[1](i,j)= 2*zetaa*(kx*oyp*oz + ox*kyp*oz + ox*oyp*kz);\n\tif(ma>0) {\n\t  oym=oy_arr(ma-1,mb);\n\t  kym=ky_arr(ma-1,mb);\n\t  T[1](i,j)-=ma*(kx*oym*oz + ox*kym*oz + ox*oym*kz);\n\t}\n\tT[1](i,j)*=0.5*anorm*bnorm;\n      }\n\n      // LHS, derivative acting on z component\n      {\n\tox=ox_arr(la,lb);\n\toy=oy_arr(ma,mb);\n\tozp=oz_arr(na+1,nb);\n\n\tkx=kx_arr(la,lb);\n\tky=ky_arr(ma,mb);\n\tkzp=kz_arr(na+1,nb);\n\n\tT[2](i,j)= 2*zetaa*(kx*oy*ozp + ox*ky*ozp + ox*oy*kzp);\n\tif(na>0) {\n\t  ozm=oz_arr(na-1,nb);\n\t  kzm=kz_arr(na-1,nb);\n\t  T[2](i,j)-=na*(kx*oy*ozm + ox*ky*ozm + ox*oy*kzm);\n\t}\n\tT[2](i,j)*=0.5*anorm*bnorm;\n      }\n\n\n      // RHS, derivative acting on x component\n      {\n\toxp=ox_arr(la,lb+1);\n\toy=oy_arr(ma,mb);\n\toz=oz_arr(na,nb);\n\n\tkxp=kx_arr(la,lb+1);\n\tky=ky_arr(ma,mb);\n\tkz=kz_arr(na,nb);\n\n\tT[3](i,j)=2*zetab*(kxp*oy*oz + oxp*ky*oz + oxp*oy*kz);\n\tif(lb>0) {\n\t  oxm=ox_arr(la,lb-1);\n\t  kxm=kx_arr(la,lb-1);\n\t  T[3](i,j)-=lb*(kxm*oy*oz + oxm*ky*oz + oxm*oy*kz);\n\t}\n\tT[3](i,j)*=0.5*anorm*bnorm;\n      }\n\n      // RHS, derivative acting on y component\n      {\n\tox=ox_arr(la,lb);\n\toyp=oy_arr(ma,mb+1);\n\toz=oz_arr(na,nb);\n\n\tkx=kx_arr(la,lb);\n\tkyp=ky_arr(ma,mb+1);\n\tkz=kz_arr(na,nb);\n\n\tT[4](i,j)= 2*zetab*(kx*oyp*oz + ox*kyp*oz + ox*oyp*kz);\n\tif(mb>0) {\n\t  oym=oy_arr(ma,mb-1);\n\t  kym=ky_arr(ma,mb-1);\n\t  T[4](i,j)-=mb*(kx*oym*oz + ox*kym*oz + ox*oym*kz);\n\t}\n\tT[4](i,j)*=0.5*anorm*bnorm;\n      }\n\n      // RHS, derivative acting on z component\n      {\n\tox=ox_arr(la,lb);\n\toy=oy_arr(ma,mb);\n\tozp=oz_arr(na,nb+1);\n\n\tkx=kx_arr(la,lb);\n\tky=ky_arr(ma,mb);\n\tkzp=kz_arr(na,nb+1);\n\n\tT[5](i,j)= 2*zetab*(kx*oy*ozp + ox*ky*ozp + ox*oy*kzp);\n\tif(nb>0) {\n\t  ozm=oz_arr(na,nb-1);\n\t  kzm=kz_arr(na,nb-1);\n\t  T[5](i,j)-=nb*(kx*oy*ozm + ox*ky*ozm + ox*oy*kzm);\n\t}\n\tT[5](i,j)*=0.5*anorm*bnorm;\n      }\n\n    }\n  }\n\n  return T;\n}\n\n\n// Compute kinetic energy integral of unnormalized primitives at r_A and r_B\ndouble kinetic_int_os(double xa, double ya, double za, double zetaa, int la, int ma, int na, double xb, double yb, double zb, double zetab, int lb, int mb, int nb) {\n\n  // Kinetic energy contributions in x, y and z\n  double kx, ky, kz;\n\n  // Overlaps in x, y and z\n  double ox, oy, oz;\n\n  // Compute kinetic energy integrals\n  //  kx=kinetic_int_1d(xa,xb,zetaa,zetab,la,lb);\n  //  ky=kinetic_int_1d(ya,yb,zetaa,zetab,ma,mb);\n  //  kz=kinetic_int_1d(za,zb,zetaa,zetab,na,nb);\n  kx=derivative_int_1d(xa,xb,zetaa,zetab,la,lb,2);\n  ky=derivative_int_1d(ya,yb,zetaa,zetab,ma,mb,2);\n  kz=derivative_int_1d(za,zb,zetaa,zetab,na,nb,2);\n\n  // Compute overlap integrals\n  ox=overlap_int_1d(xa,xb,zetaa,zetab,la,lb);\n  oy=overlap_int_1d(ya,yb,zetaa,zetab,ma,mb);\n  oz=overlap_int_1d(za,zb,zetaa,zetab,na,nb);\n\n\n#ifdef DEBUG\n  // Check overlap\n  double ov=ox*oy*oz;\n  double hov=overlap_int(xa,ya,za,zetaa,la,ma,na,xb,yb,zb,zetab,lb,mb,nb);\n  if(fabs(ov-hov)>10*DBL_EPSILON*fabs(hov)) {\n    printf(\"Computed overlap integral (%e,%e,%e)-(%e,%e,%e) with zeta=(%e,%e) and am=(%i,%i,%i)-(%i,%i,%i)\\n\",xa,ya,za,xb,yb,zb,zetaa,zetab,la,ma,na,lb,mb,nb);\n    printf(\"Huzinaga gives %e, OS gives %e.\\n\",hov,ov);\n    printf(\"overlap\\t%e\\t%e\\t%e\\n\\n\",ox,oy,oz);\n  }\n#endif\n\n  // The result is\n  return -0.5*(kx*oy*oz + ox*ky*oz + ox*oy*kz);\n}\n\n\n// Worker function for kinetic energy\ndouble kinetic_int_1d(double xa, double xb,double zetaa, double zetab, int la, int lb) {\n\n  // In the following we assume la>lb.\n  if(lb<la) // Switch arguments if necessary.\n    return kinetic_int_1d(xb,xa,zetab,zetaa,lb,la);\n\n  // Compute exponents\n  double p=zetaa+zetab;\n\n  // Compute center\n  double px=(zetaa*xa+zetab*xb)/p;\n\n  double xpa=px-xa;\n  double xpb=px-xb;\n\n  // Get overlap integrals\n  arma::mat S=overlap_ints_1d(xa,xb,zetaa,zetab,la+1,lb);\n\n  // Compute the kinetic energy integrals\n  //      T_{ij} = - ½ <G_i | \\partial_x^2 | G_j >\n  // using recursion relations\n  // T_{i+1,j} = X_{PA} T_{i,j} + 1/2p * ( i*T_{i-1,j} + j*T_{i,j-1} ) + zetab/p * (2 * zetaa * S_{i+1,j} - i*S_{i-1,j})\n  // T_{i,j+1} = X_{PB} T_{i,j} + 1/2p * ( i*T_{i-1,j} + j*T_{i,j-1} ) + zetaa/p * (2 * zetab * S_{i,j+1} - j*S_{i,j-1})\n  // and the initial result\n  // T_{00} = zetaa * (1 - 2*zetaa*(X_{PA}^2 + 1/2p)) * S_{00}\n\n  arma::mat T(la+2,lb+1);\n  T.zeros();\n\n  // Initialize array\n  T(0,0)=zetaa*(1.0 - 2.0*zetaa*(xpa*xpa + 0.5/p))*S(0,0);\n\n  // Generate integrals T_{i,0}\n  T(1,0)=xpa*T(0,0) + zetab/p*2.0*zetaa*S(1,0);\n  for(int i=1;i<=la;i++) {\n    T(i+1,0)=xpa*T(i,0) + 0.5/p*i*T(i-1,0) + zetab/p*(2.0*zetaa*S(i+1,0)-i*S(i-1,0));\n  }\n\n  if(lb>0) {\n    T(0,1)=xpb*T(0,0) + zetaa/p*2.0*zetab*S(0,1);\n    for(int j=1;j<lb;j++)\n      T(0,j+1)=xpb*T(0,j) + 0.5/p*j*T(0,j-1) + zetaa/p*(2.0*zetab*S(0,j+1)-j*S(0,j-1));\n\n    // Form target integral T_{la,lb}\n    for(int i=1;i<=la;i++)\n      for(int j=1;j<lb;j++) {\n\tT(i,j+1)=xpb*T(i,j) + 0.5/p*(i*T(i-1,j) + j*T(i,j-1)) + zetaa/p*(2.0*zetab*S(i,j+1)-j*S(i,j-1));\n      }\n  }\n\n  return T(la,lb);\n}\n\n// Compute matrix element of derivative\ndouble derivative_int_1d(double xa, double xb, double zetaa, double zetab, int la, int lb, int eval) {\n\n  return derivative_ints_1d(xa,xb,zetaa,zetab,la,lb,eval)(la,lb);\n\n}\n\n// Compute shell of matrix elements of derivative\narma::mat derivative_ints_1d(double xa, double xb, double zetaa, double zetab, int la, int lb, int eval) {\n\n  // In the following we assume la>lb.\n  if(lb<la) // Switch arguments if necessary.\n    return trans(derivative_ints_1d(xb,xa,zetab,zetaa,lb,la,eval));\n\n  // Work matrices\n  std::vector<arma::mat> D;\n\n  // We compute the wanted matrix with\n  // D^{e+1}_{i,j} = 2*zetaa*D^e_{i+1,j} - iD^e_{i-1,j}\n\n  // The lowest order matrix is simply the ovelap matrix,\n  // which we need to get in a big enough form\n  D.push_back(overlap_ints_1d(xa,xb,zetaa,zetab,la+eval,lb));\n\n  // Now, perform the recursion.\n  for(int e=1;e<=eval;e++) {\n    // Number of rows in the matrix of the current iteration\n    int laval=la+eval-e;\n\n    // Create matrix\n    D.push_back(arma::mat(laval+1,lb+1));\n    D[e].zeros();\n\n    // Do recursion\n    for(int j=0;j<=lb;j++) // i=0\n      D[e](0,j)=2*zetaa*D[e-1](1,j);\n    for(int i=1;i<=laval;i++)\n      for(int j=0;j<=lb;j++)\n\tD[e](i,j)=2*zetaa*D[e-1](i+1,j)-i*D[e-1](i-1,j);\n  }\n\n  // Return result\n  return D[eval].submat(0,0,la,lb);\n}\n\narma::mat nuclear_int_os(double xa, double ya, double za, double zetaa, const std::vector<shellf_t> & carta, double xnuc, double ynuc, double znuc, double xb, double yb, double zb, double zetab, const std::vector<shellf_t> & cartb) {\n  // Compute shell of overlap integrals\n\n  // Angular momenta of shells\n  int am_a=carta[0].l+carta[0].m+carta[0].n;\n  int am_b=cartb[0].l+cartb[0].m+cartb[0].n;\n\n  // Compute the matrix\n  arma::mat V=nuclear_ints_os(xa,ya,za,zetaa,am_a,xnuc,ynuc,znuc,xb,yb,zb,zetab,am_b);\n\n  // Plug in the relative normalization factors\n  for(size_t i=0;i<carta.size();i++)\n    for(size_t j=0;j<cartb.size();j++)\n      V(i,j)*=carta[i].relnorm*cartb[j].relnorm;\n\n  return V;\n}\n\ndouble nuclear_int_os(double xa, double ya, double za, double zetaa, int la, int ma, int na, double xnuc, double ynuc, double znuc, double xb, double yb, double zb, double zetab, int lb, int mb, int nb) {\n\n  // Compute the shell\n  int am_a=la+ma+na;\n  int am_b=lb+mb+nb;\n\n  arma::mat ints=nuclear_ints_os(xa,ya,za,zetaa,am_a,xnuc,ynuc,znuc,xb,yb,zb,zetab,am_b);\n\n  // Find the integral in the table\n  double os=ints(getind(la,ma,na),getind(lb,mb,nb));\n\n  return os;\n}\n\n/*\n\n  The Obara-Saika recursion routine for nuclear attraction integrals\n  was heavily inspired by the routine in\n\n  PSI3: An open-source ab initio electronic structure package version 3.1.0.\n\n  by\n\n  T. D. Crawford, C. D. Sherrill, E. F. Valeev, J. T. Fermann, R. A. King,\n  M. L. Leininger, S. T. Brown, C. L. Janssen, E. T. Seidl, J. P. Kenny,\n  and W. D. Allen [J. Comp. Chem. 28, 1610 (2007)].\n\n  The original license was the GNU General Public License.\n  This version is relicensed under GPLv2+.\n\n*/\n\n\narma::mat nuclear_ints_os(double xa, double ya, double za, double zetaa, int am_a, double xnuc, double ynuc, double znuc, double xb, double yb, double zb, double zetab, int am_b) {\n\n  // Compute coordinates of center\n  const double zeta=zetaa+zetab;\n  const double o2g=1/(2.0*zeta);\n\n  const double xp=(zetaa*xa+zetab*xb)/zeta;\n  const double yp=(zetaa*ya+zetab*yb)/zeta;\n  const double zp=(zetaa*za+zetab*zb)/zeta;\n\n  const double PAx=xp-xa;\n  const double PAy=yp-ya;\n  const double PAz=zp-za;\n\n  const double PBx=xp-xb;\n  const double PBy=yp-yb;\n  const double PBz=zp-zb;\n\n  const double PCx=xp-xnuc;\n  const double PCy=yp-ynuc;\n  const double PCz=zp-znuc;\n\n  const double ABsq=(xa-xb)*(xa-xb) + (ya-yb)*(ya-yb) + (za-zb)*(za-zb);\n\n  // Sum of angular momenta\n  const int mmax=am_a+am_b;\n\n  const int size_a=(am_a+1)*(am_a+1)*am_a+1;\n  const int size_b=(am_b+1)*(am_b+1)*am_b+1;\n\n  // Work array for recursion formulas\n  arma::cube ints(size_a,size_b,mmax+1);\n  ints.zeros();\n\n  // Helpers for computing indices on work array\n  const int Nan = 1;\n  const int Nam = am_a+1;\n  const int Nal = Nam*Nam;\n\n  const int Nbn = 1;\n  const int Nbm = am_b+1;\n  const int Nbl = Nbm*Nbm;\n\n  // Argument of Boys' function\n  const double boysarg=zeta*(PCx*PCx + PCy*PCy + PCz*PCz);\n  // Evaluate Boys' function\n  arma::vec bf;\n  boysF_arr(mmax,boysarg,bf);\n\n  // Constant prefactor for auxiliary integrals\n  const double prefac=2.0*M_PI/zeta*exp(-zetaa*zetab*ABsq/zeta);\n\n  // Initialize integral array (0_A | A(0) | 0_B)^(m)\n  for(size_t m=0;m<bf.size();m++)\n    ints(0,0,m)=prefac*bf[m];\n\n  // Increase angular momentum on right hand side.\n\n  // Loop over total angular momentum\n  for(int lambdab=1;lambdab<=am_b;lambdab++)\n\n    // Loop over angular momentum functions belonging to this shell\n    for(int ii=0; ii<=lambdab; ii++) {\n      int lb=lambdab - ii;\n      for(int jj=0; jj<=ii; jj++) {\n\tint mb=ii - jj;\n\tint nb=jj;\n\n\t// Index in integrals table\n\tint bind = lb*Nbl+mb*Nbm+nb*Nbn;\n\n\tif (nb > 0) {\n\t  for(int m=0;m<=mmax-lambdab;m++)\n\t    ints(0,bind,m) = PBz*ints(0,bind-Nbn,m)-PCz*ints(0,bind-Nbn,m+1);\n\n\t  if (nb > 1) {\n\t    for(int m=0;m<=mmax-lambdab;m++)\n\t      ints(0,bind,m) += o2g*(nb-1)*(ints(0,bind-2*Nbn,m)-ints(0,bind-2*Nbn,m+1));\n\t  }\n\t}\n\n\telse if (mb > 0) {\n\n\t  for(int m=0;m<=mmax-lambdab;m++)\n\t    ints(0,bind,m) = PBy*ints(0,bind-Nbm,m)-PCy*ints(0,bind-Nbm,m+1);\n\n\t  if (mb > 1) {\n\t      for(int m=0;m<=mmax-lambdab;m++)\n\t\tints(0,bind,m) += o2g*(mb-1)*(ints(0,bind-2*Nbm,m)-ints(0,bind-2*Nbm,m+1));\n\t  }\n\t}\n\n\telse if (lb > 0) {\n\n\t  for(int m=0;m<=mmax-lambdab;m++)\n\t    ints(0,bind,m) = PBx*ints(0,bind-Nbl,m)-PCx*ints(0,bind-Nbl,m+1);\n\n\t  if (lb > 1) {\n\t    for(int m=0;m<=mmax-lambdab;m++)\n\t      ints(0,bind,m) += o2g*(lb-1)*(ints(0,bind-2*Nbl,m)-ints(0,bind-2*Nbl,m+1));\n\t  }\n\n\t}\n\telse {\n\t  ERROR_INFO();\n\t  throw std::runtime_error(\"Something went haywire in the Obara-Saika nuclear attraction integral algorithm.\\n\");\n\t}\n      }\n  }\n\n  // Now, increase the angular momentum of the left-hand side, too.\n\n  // Loop over total angular momentum of RHS\n  for(int lambdab=0;lambdab<=am_b;lambdab++)\n\n    // Loop over the functions belonging to the shell\n    for(int ii=0; ii<=lambdab; ii++) {\n      int lb=lambdab - ii;\n      for(int jj=0; jj<=ii; jj++) {\n\tint mb=ii - jj;\n\tint nb=jj;\n\n\t// RHS index is\n\tint bind = lb*Nbl + mb*Nbm + nb*Nbn;\n\n\t// Loop over total angular momentum of LHS\n\tfor(int lambdaa=1;lambdaa<=am_a;lambdaa++)\n\n\t  // Loop over angular momentum of second shell\n\t  for(int kk=0; kk<=lambdaa; kk++) {\n\t    int la=lambdaa-kk;\n\n\t    for(int ll=0; ll<=kk; ll++) {\n\t      int ma=kk-ll;\n\t      int na=ll;\n\n\t      // LHS index is\n\t      int aind = la*Nal + ma*Nam + na*Nan;\n\n\t      if (na > 0) {\n\n\t\tfor(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t  ints(aind,bind,m) = PAz*ints(aind-Nan,bind,m)-PCz*ints(aind-Nan,bind,m+1);\n\t\t}\n\n\t\tif (na > 1) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*(na-1)*(ints(aind-2*Nan,bind,m)-ints(aind-2*Nan,bind,m+1));\n\t\t}\n\n\t\tif (nb > 0) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*nb*(ints(aind-Nan,bind-Nbn,m)-ints(aind-Nan,bind-Nbn,m+1));\n\t\t}\n\n\t      } else if (ma > 0) {\n\n\t\tfor(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t  ints(aind,bind,m) = PAy*ints(aind-Nam,bind,m)-PCy*ints(aind-Nam,bind,m+1);\n\t\t}\n\n\t\tif (ma > 1) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*(ma-1)*(ints(aind-2*Nam,bind,m) - ints(aind-2*Nam,bind,m+1));\n\t\t}\n\n\t\tif (mb > 0) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*mb*(ints(aind-Nam,bind-Nbm,m) - ints(aind-Nam,bind-Nbm,m+1));\n\t\t}\n\n\t      }\telse if (la > 0) {\n\n\t\tfor(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t  ints(aind,bind,m) = PAx*ints(aind-Nal,bind,m)-PCx*ints(aind-Nal,bind,m+1);\n\t\t}\n\n\t\tif (la > 1) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*(la-1)*(ints(aind-2*Nal,bind,m) - ints(aind-2*Nal,bind,m+1));\n\t\t}\n\n\t\tif (lb > 0) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*lb*(ints(aind-Nal,bind-Nbl,m) - ints(aind-Nal,bind-Nbl,m+1));\n\t\t}\n\t      }\n\t      else {\n\t\tERROR_INFO();\n\t\tthrow std::runtime_error(\"Something went haywire in the Obara-Saika nuclear attraction integral algorithm.\\n\");\n\t      }\n\t    }\n\t  }\n    }\n  }\n\n  // Size of returned array\n  int Na=(am_a+1)*(am_a+2)/2;\n  int Nb=(am_b+1)*(am_b+2)/2;\n\n  // Returned array\n  arma::mat V(Na,Nb);\n  V.zeros();\n\n  // Fill in array\n  int ia, ib;\n\n  // Index of left basis function\n  ia=0;\n\n\n  // Loop over basis functions on this shell\n  for(int ii=0; ii<=am_a; ii++) {\n    int la=am_a - ii;\n    for(int jj=0; jj<=ii; jj++) {\n      int ma=ii - jj;\n      int na=jj;\n\n      // Index in worker array\n      int aind=la*Nal+ma*Nam+na;\n\n      // Index of right basis function\n      ib=0;\n\n      // Loop over angular momentum of second shell\n      for(int kk=0; kk<=am_b; kk++) {\n\tint lb=am_b - kk;\n\n\tfor(int ll=0; ll<=kk; ll++) {\n\t  int mb=kk-ll;\n\t  int nb=ll;\n\n\t  // Other index is\n\t  int bind=lb*Nbl+mb*Nbm+nb;\n\n\t  // Store result\n\t  V(ia,ib)=-ints(aind,bind,0);\n\n\t  // Increment index of basis function\n\t  ib++;\n\t}\n      }\n\n      // Increment index of basis function\n      ia++;\n    }\n  }\n\n#ifdef DEBUG\n  // Compute Huzinaga integrals\n  arma::mat huzint=V;\n  huzint.zeros();\n\n  int diff=0;\n\n  ia=0;\n  // Loop over basis functions on this shell\n  for(int ii=0; ii<=am_a; ii++) {\n    int ila=am_a - ii;\n    for(int jj=0; jj<=ii; jj++) {\n      int ima=ii - jj;\n      int ina=jj;\n\n      ib=0;\n      // Loop over basis functions on this shell\n      for(int kk=0; kk<=am_b; kk++) {\n\tint ilb=am_b - kk;\n\tfor(int ll=0; ll<=kk; ll++) {\n\t  int imb=kk - ll;\n\t  int inb=ll;\n\n\t  huzint(ia,ib)=nuclear_int(xa,ya,za,zetaa,ila,ima,ina,xnuc,ynuc,znuc,xb,yb,zb,zetab,ilb,imb,inb);\n\n\t  if(fabs(huzint(ia,ib)-V(ia,ib))>100*DBL_EPSILON*fabs(huzint(ia,ib)))\n\t    diff++;\n\n\t  ib++;\n\t}\n      }\n\n      ia++;\n    }\n  }\n\n  if(diff==0)\n    //    printf(\"Computed NAI shell (%e,%e,%e) - (%e,%e,%e) with nucleus at (%e,%e,%e) and exponents %e and %e with am=(%i,%i), the results match.\\n\",xa,ya,za,xb,yb,zb,xnuc,ynuc,znuc,zetaa,zetab,am_a,am_b);\n    ;\n  else {\n    ia=0;\n    // Loop over basis functions on this shell\n    for(int ii=0; ii<=am_a; ii++) {\n      int ila=am_a - ii;\n      for(int jj=0; jj<=ii; jj++) {\n\tint ima=ii - jj;\n\tint ina=jj;\n\n\tib=0;\n\t// Loop over basis functions on this shell\n\tfor(int kk=0; kk<=am_b; kk++) {\n\t  int ilb=am_b - kk;\n\t  for(int ll=0; ll<=kk; ll++) {\n\t    int imb=kk - ll;\n\t    int inb=ll;\n\n\t    if(fabs(huzint(ia,ib)-V(ia,ib))>100*DBL_EPSILON*fabs(huzint(ia,ib))) {\n\t      printf(\"Computed NAI shell (%e,%e,%e) - (%e,%e,%e) with nucleus at (%e,%e,%e) and exponents %e and %e.\\n\",xa,ya,za,xb,yb,zb,xnuc,ynuc,znuc,zetaa,zetab);\n\t      printf(\"The result for the integral (%i,%i,%i)-(%i,%i,%i) is %e with Huzinaga, whereas %e with Obara-Saika; difference is %e.\\n\\n\",ila,ima,ina,ilb,imb,inb,huzint(ia,ib),V(ia,ib),huzint(ia,ib)-V(ia,ib));\n\t    }\n\t    ib++;\n\t  }\n\t}\n\tia++;\n      }\n    }\n  }\n\n  /*    printf(\"Obara-Saika shell of integrals:\\n\");\n\tV.print();\n\tprintf(\"Huzinaga shell of integrals:\\n\");\n\thuzint.print();\n\tprintf(\"\\n\");*/\n#endif\n\n  return V;\n}\n\n\nstd::vector<arma::mat> nuclear_int_pulay_os(double xa, double ya, double za, double zetaa, int amorig_a, double xnuc, double ynuc, double znuc, double xb, double yb, double zb, double zetab, int amorig_b) {\n\n  // Compute coordinates of center\n  const double zeta=zetaa+zetab;\n  const double o2g=1/(2.0*zeta);\n\n  const double xp=(zetaa*xa+zetab*xb)/zeta;\n  const double yp=(zetaa*ya+zetab*yb)/zeta;\n  const double zp=(zetaa*za+zetab*zb)/zeta;\n\n  const double PAx=xp-xa;\n  const double PAy=yp-ya;\n  const double PAz=zp-za;\n\n  const double PBx=xp-xb;\n  const double PBy=yp-yb;\n  const double PBz=zp-zb;\n\n  const double PCx=xp-xnuc;\n  const double PCy=yp-ynuc;\n  const double PCz=zp-znuc;\n\n  const double ABsq=(xa-xb)*(xa-xb) + (ya-yb)*(ya-yb) + (za-zb)*(za-zb);\n\n  // Recursion formulas need am_a and am_b increased by one.\n  int am_a=amorig_a+1;\n  int am_b=amorig_b+1;\n\n  // Sum of angular momenta\n  const int mmax=am_a+am_b;\n\n  const int size_a=(am_a+1)*(am_a+1)*am_a+1;\n  const int size_b=(am_b+1)*(am_b+1)*am_b+1;\n\n  // Work array for recursion formulas\n  arma::cube ints(size_a,size_b,mmax+1);\n  ints.zeros();\n\n  // Helpers for computing indices on work array\n  const int Nan = 1;\n  const int Nam = am_a+1;\n  const int Nal = Nam*Nam;\n\n  const int Nbn = 1;\n  const int Nbm = am_b+1;\n  const int Nbl = Nbm*Nbm;\n\n  // Argument of Boys' function\n  const double boysarg=zeta*(PCx*PCx + PCy*PCy + PCz*PCz);\n  // Evaluate Boys' function\n  arma::vec bf;\n  boysF_arr(mmax,boysarg,bf);\n\n  // Constant prefactor for auxiliary integrals\n  const double prefac=2.0*M_PI/zeta*exp(-zetaa*zetab*ABsq/zeta);\n\n  // Initialize integral array (0_A | A(0) | 0_B)^(m)\n  for(size_t m=0;m<bf.size();m++)\n    ints(0,0,m)=prefac*bf[m];\n\n  // Increase angular momentum on right hand side.\n\n  // Loop over total angular momentum\n  for(int lambdab=1;lambdab<=am_b;lambdab++)\n\n    // Loop over angular momentum functions belonging to this shell\n    for(int ii=0; ii<=lambdab; ii++) {\n      int lb=lambdab - ii;\n      for(int jj=0; jj<=ii; jj++) {\n\tint mb=ii - jj;\n\tint nb=jj;\n\n\t// Index in integrals table\n\tint bind = lb*Nbl+mb*Nbm+nb*Nbn;\n\n\tif (nb > 0) {\n\t  for(int m=0;m<=mmax-lambdab;m++)\n\t    ints(0,bind,m) = PBz*ints(0,bind-Nbn,m)-PCz*ints(0,bind-Nbn,m+1);\n\n\t  if (nb > 1) {\n\t    for(int m=0;m<=mmax-lambdab;m++)\n\t      ints(0,bind,m) += o2g*(nb-1)*(ints(0,bind-2*Nbn,m)-ints(0,bind-2*Nbn,m+1));\n\t  }\n\t}\n\n\telse if (mb > 0) {\n\n\t  for(int m=0;m<=mmax-lambdab;m++)\n\t    ints(0,bind,m) = PBy*ints(0,bind-Nbm,m)-PCy*ints(0,bind-Nbm,m+1);\n\n\t  if (mb > 1) {\n\t      for(int m=0;m<=mmax-lambdab;m++)\n\t\tints(0,bind,m) += o2g*(mb-1)*(ints(0,bind-2*Nbm,m)-ints(0,bind-2*Nbm,m+1));\n\t  }\n\t}\n\n\telse if (lb > 0) {\n\n\t  for(int m=0;m<=mmax-lambdab;m++)\n\t    ints(0,bind,m) = PBx*ints(0,bind-Nbl,m)-PCx*ints(0,bind-Nbl,m+1);\n\n\t  if (lb > 1) {\n\t    for(int m=0;m<=mmax-lambdab;m++)\n\t      ints(0,bind,m) += o2g*(lb-1)*(ints(0,bind-2*Nbl,m)-ints(0,bind-2*Nbl,m+1));\n\t  }\n\n\t}\n\telse {\n\t  ERROR_INFO();\n\t  throw std::runtime_error(\"Something went haywire in the Obara-Saika nuclear attraction integral algorithm.\\n\");\n\t}\n      }\n  }\n\n  // Now, increase the angular momentum of the left-hand side, too.\n\n  // Loop over total angular momentum of RHS\n  for(int lambdab=0;lambdab<=am_b;lambdab++)\n\n    // Loop over the functions belonging to the shell\n    for(int ii=0; ii<=lambdab; ii++) {\n      int lb=lambdab - ii;\n      for(int jj=0; jj<=ii; jj++) {\n\tint mb=ii - jj;\n\tint nb=jj;\n\n\t// RHS index is\n\tint bind = lb*Nbl + mb*Nbm + nb*Nbn;\n\n\t// Loop over total angular momentum of LHS\n\tfor(int lambdaa=1;lambdaa<=am_a;lambdaa++)\n\n\t  // Loop over angular momentum of second shell\n\t  for(int kk=0; kk<=lambdaa; kk++) {\n\t    int la=lambdaa-kk;\n\n\t    for(int ll=0; ll<=kk; ll++) {\n\t      int ma=kk-ll;\n\t      int na=ll;\n\n\t      // LHS index is\n\t      int aind = la*Nal + ma*Nam + na*Nan;\n\n\t      if (na > 0) {\n\n\t\tfor(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t  ints(aind,bind,m) = PAz*ints(aind-Nan,bind,m)-PCz*ints(aind-Nan,bind,m+1);\n\t\t}\n\n\t\tif (na > 1) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*(na-1)*(ints(aind-2*Nan,bind,m)-ints(aind-2*Nan,bind,m+1));\n\t\t}\n\n\t\tif (nb > 0) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*nb*(ints(aind-Nan,bind-Nbn,m)-ints(aind-Nan,bind-Nbn,m+1));\n\t\t}\n\n\t      } else if (ma > 0) {\n\n\t\tfor(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t  ints(aind,bind,m) = PAy*ints(aind-Nam,bind,m)-PCy*ints(aind-Nam,bind,m+1);\n\t\t}\n\n\t\tif (ma > 1) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*(ma-1)*(ints(aind-2*Nam,bind,m) - ints(aind-2*Nam,bind,m+1));\n\t\t}\n\n\t\tif (mb > 0) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*mb*(ints(aind-Nam,bind-Nbm,m) - ints(aind-Nam,bind-Nbm,m+1));\n\t\t}\n\n\t      }\telse if (la > 0) {\n\n\t\tfor(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t  ints(aind,bind,m) = PAx*ints(aind-Nal,bind,m)-PCx*ints(aind-Nal,bind,m+1);\n\t\t}\n\n\t\tif (la > 1) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*(la-1)*(ints(aind-2*Nal,bind,m) - ints(aind-2*Nal,bind,m+1));\n\t\t}\n\n\t\tif (lb > 0) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*lb*(ints(aind-Nal,bind-Nbl,m) - ints(aind-Nal,bind-Nbl,m+1));\n\t\t}\n\t      }\n\t      else {\n\t\tERROR_INFO();\n\t\tthrow std::runtime_error(\"Something went haywire in the Obara-Saika nuclear attraction integral algorithm.\\n\");\n\t      }\n\t    }\n\t  }\n    }\n  }\n\n  // Size of returned array\n  int Na=(amorig_a+1)*(amorig_a+2)/2;\n  int Nb=(amorig_b+1)*(amorig_b+2)/2;\n\n  // Returned array\n  std::vector<arma::mat> V(6);\n  for(int ic=0;ic<6;ic++)\n    V[ic].zeros(Na,Nb);\n\n  // Fill in array\n  int ia, ib;\n\n  // Index of left basis function\n  ia=0;\n\n  // Loop over basis functions on this shell\n  for(int ii=0; ii<=amorig_a; ii++) {\n    int la=amorig_a - ii;\n    for(int jj=0; jj<=ii; jj++) {\n      int ma=ii - jj;\n      int na=jj;\n\n      // Index of right basis function\n      ib=0;\n\n      // Loop over angular momentum of second shell\n      for(int kk=0; kk<=amorig_b; kk++) {\n\tint lb=amorig_b - kk;\n\n\tfor(int ll=0; ll<=kk; ll++) {\n\t  int mb=kk-ll;\n\t  int nb=ll;\n\n\t  int aind=la*Nal+ma*Nam+na;\n\t  // x\n\t  int alpind=(la+1)*Nal+ma*Nam+na;\n\t  int almind=(la-1)*Nal+ma*Nam+na;\n\t  // y\n\t  int ampind=la*Nal+(ma+1)*Nam+na;\n\t  int ammind=la*Nal+(ma-1)*Nam+na;\n\t  // z\n\t  int anpind=la*Nal+ma*Nam+na+1;\n\t  int anmind=la*Nal+ma*Nam+na-1;\n\n\t  int bind=lb*Nbl+mb*Nbm+nb;\n\t  // x\n\t  int blpind=(lb+1)*Nbl+mb*Nbm+nb;\n\t  int blmind=(lb-1)*Nbl+mb*Nbm+nb;\n\t  // y\n\t  int bmpind=lb*Nbl+(mb+1)*Nbm+nb;\n\t  int bmmind=lb*Nbl+(mb-1)*Nbm+nb;\n\t  // z\n\t  int bnpind=lb*Nbl+mb*Nbm+nb+1;\n\t  int bnmind=lb*Nbl+mb*Nbm+nb-1;\n\n\t  // LHS, x\n\t  V[0](ia,ib)=2*zetaa*ints(alpind,bind,0);\n\t  if(la>0)\n\t    V[0](ia,ib)-=la*ints(almind,bind,0);\n\t  // LHS, y\n\t  V[1](ia,ib)=2*zetaa*ints(ampind,bind,0);\n\t  if(ma>0)\n\t    V[1](ia,ib)-=ma*ints(ammind,bind,0);\n\t  // LHS, z\n\t  V[2](ia,ib)=2*zetaa*ints(anpind,bind,0);\n\t  if(na>0)\n\t    V[2](ia,ib)-=na*ints(anmind,bind,0);\n\n\t  // RHS, x\n\t  V[3](ia,ib)=2*zetab*ints(aind,blpind,0);\n\t  if(lb>0)\n\t    V[3](ia,ib)-=lb*ints(aind,blmind,0);\n\t  // RHS, y\n\t  V[4](ia,ib)=2*zetab*ints(aind,bmpind,0);\n\t  if(mb>0)\n\t    V[4](ia,ib)-=mb*ints(aind,bmmind,0);\n\t  // RHS, z\n\t  V[5](ia,ib)=2*zetab*ints(aind,bnpind,0);\n\t  if(nb>0)\n\t    V[5](ia,ib)-=nb*ints(aind,bnmind,0);\n\n\t  // Increment index of basis function\n\t  ib++;\n\t}\n      }\n\n      // Increment index of basis function\n      ia++;\n    }\n  }\n\n  return V;\n}\n\n\nstd::vector<arma::mat> nuclear_int_pulay_os(double xa, double ya, double za, double zetaa, const std::vector<shellf_t> & carta, double xnuc, double ynuc, double znuc, double xb, double yb, double zb, double zetab, const std::vector<shellf_t> & cartb) {\n  // Compute shell of overlap integrals\n\n  // Angular momenta of shells\n  int am_a=carta[0].l+carta[0].m+carta[0].n;\n  int am_b=cartb[0].l+cartb[0].m+cartb[0].n;\n\n  // Compute the matrix\n  std::vector<arma::mat> V=nuclear_int_pulay_os(xa,ya,za,zetaa,am_a,xnuc,ynuc,znuc,xb,yb,zb,zetab,am_b);\n\n  // Plug in the relative normalization factors\n  for(size_t i=0;i<carta.size();i++)\n    for(size_t j=0;j<cartb.size();j++)\n      for(size_t ic=0;ic<V.size();ic++)\n\tV[ic](i,j)*=carta[i].relnorm*cartb[j].relnorm;\n\n  return V;\n}\n\nstd::vector<arma::mat> nuclear_int_ders_os(double xa, double ya, double za, double zetaa, int am_a, double xnuc, double ynuc, double znuc, double xb, double yb, double zb, double zetab, int am_b) {\n\n  // Compute coordinates of center\n  const double zeta=zetaa+zetab;\n  const double o2g=1/(2.0*zeta);\n\n  const double xp=(zetaa*xa+zetab*xb)/zeta;\n  const double yp=(zetaa*ya+zetab*yb)/zeta;\n  const double zp=(zetaa*za+zetab*zb)/zeta;\n\n  const double PAx=xp-xa;\n  const double PAy=yp-ya;\n  const double PAz=zp-za;\n\n  const double PBx=xp-xb;\n  const double PBy=yp-yb;\n  const double PBz=zp-zb;\n\n  const double PCx=xp-xnuc;\n  const double PCy=yp-ynuc;\n  const double PCz=zp-znuc;\n\n  const double ABsq=(xa-xb)*(xa-xb) + (ya-yb)*(ya-yb) + (za-zb)*(za-zb);\n\n  // Sum of angular momenta\n  const int mmax=am_a+am_b;\n\n  const int size_a=(am_a+1)*(am_a+1)*am_a+1;\n  const int size_b=(am_b+1)*(am_b+1)*am_b+1;\n\n  // Work array for recursion formulas\n  arma::cube ints(size_a,size_b,mmax+1);\n  ints.zeros();\n\n  arma::cube xint(size_a,size_b,mmax+1);\n  xint.zeros();\n  arma::cube yint(size_a,size_b,mmax+1);\n  yint.zeros();\n  arma::cube zint(size_a,size_b,mmax+1);\n  zint.zeros();\n\n  // Helpers for computing indices on work array\n  const int Nan = 1;\n  const int Nam = am_a+1;\n  const int Nal = Nam*Nam;\n\n  const int Nbn = 1;\n  const int Nbm = am_b+1;\n  const int Nbl = Nbm*Nbm;\n\n  // Argument of Boys' function\n  const double boysarg=zeta*(PCx*PCx + PCy*PCy + PCz*PCz);\n  // Evaluate Boys' function\n  arma::vec bf;\n  boysF_arr(mmax+1,boysarg,bf);\n\n  // Constant prefactor for auxiliary integrals\n  const double prefac=2.0*M_PI/zeta*exp(-zetaa*zetab*ABsq/zeta);\n\n  // Initialize integral array (0_A | A(0) | 0_B)^(m)\n  for(int m=0;m<=mmax;m++)\n    ints(0,0,m)=prefac*bf[m];\n  // and (0_A | A(1) | 0_B)^(m)\n  for(int m=0;m<=mmax;m++) {\n    xint(0,0,m)=2.0*zeta*PCx*prefac*bf[m+1];\n    yint(0,0,m)=2.0*zeta*PCy*prefac*bf[m+1];\n    zint(0,0,m)=2.0*zeta*PCz*prefac*bf[m+1];\n  }\n\n  // Increase angular momentum on right hand side.\n\n  // Loop over total angular momentum\n  for(int lambdab=1;lambdab<=am_b;lambdab++)\n\n    // Loop over angular momentum functions belonging to this shell\n    for(int ii=0; ii<=lambdab; ii++) {\n      int lb=lambdab - ii;\n      for(int jj=0; jj<=ii; jj++) {\n\tint mb=ii - jj;\n\tint nb=jj;\n\n\t// Index in integrals table\n\tint bind = lb*Nbl+mb*Nbm+nb*Nbn;\n\n\tif (nb > 0) {\n\t  for(int m=0;m<=mmax-lambdab;m++)\n\t    ints(0,bind,m) = PBz*ints(0,bind-Nbn,m)-PCz*ints(0,bind-Nbn,m+1);\n\t  for(int m=0;m<=mmax-lambdab;m++) {\n\t    xint(0,bind,m) = PBz*xint(0,bind-Nbn,m)-PCz*xint(0,bind-Nbn,m+1);\n\t    yint(0,bind,m) = PBz*yint(0,bind-Nbn,m)-PCz*yint(0,bind-Nbn,m+1);\n\t    zint(0,bind,m) = PBz*zint(0,bind-Nbn,m)-PCz*zint(0,bind-Nbn,m+1) + ints(0,bind-Nbn,m+1);\n\t  }\n\n\t  if (nb > 1) {\n\t    for(int m=0;m<=mmax-lambdab;m++)\n\t      ints(0,bind,m) += o2g*(nb-1)*(ints(0,bind-2*Nbn,m)-ints(0,bind-2*Nbn,m+1));\n\t    for(int m=0;m<=mmax-lambdab;m++) {\n\t      xint(0,bind,m) += o2g*(nb-1)*(xint(0,bind-2*Nbn,m)-xint(0,bind-2*Nbn,m+1));\n\t      yint(0,bind,m) += o2g*(nb-1)*(yint(0,bind-2*Nbn,m)-yint(0,bind-2*Nbn,m+1));\n\t      zint(0,bind,m) += o2g*(nb-1)*(zint(0,bind-2*Nbn,m)-zint(0,bind-2*Nbn,m+1));\n\t    }\n\t  }\n\t}\n\n\telse if (mb > 0) {\n\n\t  for(int m=0;m<=mmax-lambdab;m++)\n\t    ints(0,bind,m) = PBy*ints(0,bind-Nbm,m)-PCy*ints(0,bind-Nbm,m+1);\n\t  for(int m=0;m<=mmax-lambdab;m++) {\n\t    xint(0,bind,m) = PBy*xint(0,bind-Nbm,m)-PCy*xint(0,bind-Nbm,m+1);\n\t    yint(0,bind,m) = PBy*yint(0,bind-Nbm,m)-PCy*yint(0,bind-Nbm,m+1) + ints(0,bind-Nbm,m+1);\n\t    zint(0,bind,m) = PBy*zint(0,bind-Nbm,m)-PCy*zint(0,bind-Nbm,m+1);\n\t  }\n\n\t  if (mb > 1) {\n\t      for(int m=0;m<=mmax-lambdab;m++)\n\t\tints(0,bind,m) += o2g*(mb-1)*(ints(0,bind-2*Nbm,m)-ints(0,bind-2*Nbm,m+1));\n\t      for(int m=0;m<=mmax-lambdab;m++) {\n\t\txint(0,bind,m) += o2g*(mb-1)*(xint(0,bind-2*Nbm,m)-xint(0,bind-2*Nbm,m+1));\n\t\tyint(0,bind,m) += o2g*(mb-1)*(yint(0,bind-2*Nbm,m)-yint(0,bind-2*Nbm,m+1));\n\t\tzint(0,bind,m) += o2g*(mb-1)*(zint(0,bind-2*Nbm,m)-zint(0,bind-2*Nbm,m+1));\n\t      }\n\t  }\n\t}\n\n\telse if (lb > 0) {\n\n\t  for(int m=0;m<=mmax-lambdab;m++)\n\t    ints(0,bind,m) = PBx*ints(0,bind-Nbl,m)-PCx*ints(0,bind-Nbl,m+1);\n\t  for(int m=0;m<=mmax-lambdab;m++) {\n\t    xint(0,bind,m) = PBx*xint(0,bind-Nbl,m)-PCx*xint(0,bind-Nbl,m+1) + ints(0,bind-Nbl,m+1);\n\t    yint(0,bind,m) = PBx*yint(0,bind-Nbl,m)-PCx*yint(0,bind-Nbl,m+1);\n\t    zint(0,bind,m) = PBx*zint(0,bind-Nbl,m)-PCx*zint(0,bind-Nbl,m+1);\n\t  }\n\n\t  if (lb > 1) {\n\t    for(int m=0;m<=mmax-lambdab;m++)\n\t      ints(0,bind,m) += o2g*(lb-1)*(ints(0,bind-2*Nbl,m)-ints(0,bind-2*Nbl,m+1));\n\t    for(int m=0;m<=mmax-lambdab;m++) {\n\t      xint(0,bind,m) += o2g*(lb-1)*(xint(0,bind-2*Nbl,m)-xint(0,bind-2*Nbl,m+1));\n\t      yint(0,bind,m) += o2g*(lb-1)*(yint(0,bind-2*Nbl,m)-yint(0,bind-2*Nbl,m+1));\n\t      zint(0,bind,m) += o2g*(lb-1)*(zint(0,bind-2*Nbl,m)-zint(0,bind-2*Nbl,m+1));\n\t    }\n\t  }\n\n\t}\n\telse {\n\t  ERROR_INFO();\n\t  throw std::runtime_error(\"Something went haywire in the Obara-Saika nuclear attraction integral derivative algorithm.\\n\");\n\t}\n      }\n  }\n\n  // Now, increase the angular momentum of the left-hand side, too.\n\n  // Loop over total angular momentum of RHS\n  for(int lambdab=0;lambdab<=am_b;lambdab++)\n\n    // Loop over the functions belonging to the shell\n    for(int ii=0; ii<=lambdab; ii++) {\n      int lb=lambdab - ii;\n      for(int jj=0; jj<=ii; jj++) {\n\tint mb=ii - jj;\n\tint nb=jj;\n\n\t// RHS index is\n\tint bind = lb*Nbl + mb*Nbm + nb*Nbn;\n\n\t// Loop over total angular momentum of LHS\n\tfor(int lambdaa=1;lambdaa<=am_a;lambdaa++)\n\n\t  // Loop over angular momentum of second shell\n\t  for(int kk=0; kk<=lambdaa; kk++) {\n\t    int la=lambdaa-kk;\n\n\t    for(int ll=0; ll<=kk; ll++) {\n\t      int ma=kk-ll;\n\t      int na=ll;\n\n\t      // LHS index is\n\t      int aind = la*Nal + ma*Nam + na*Nan;\n\n\t      if (na > 0) {\n\t\tfor(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t  ints(aind,bind,m) = PAz*ints(aind-Nan,bind,m)-PCz*ints(aind-Nan,bind,m+1);\n\t\tfor(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t  xint(aind,bind,m) = PAz*xint(aind-Nan,bind,m)-PCz*xint(aind-Nan,bind,m+1);\n\t\t  yint(aind,bind,m) = PAz*yint(aind-Nan,bind,m)-PCz*yint(aind-Nan,bind,m+1);\n\t\t  zint(aind,bind,m) = PAz*zint(aind-Nan,bind,m)-PCz*zint(aind-Nan,bind,m+1) + ints(aind-Nan,bind,m+1);\n\t\t}\n\n\t\tif (na > 1) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*(na-1)*(ints(aind-2*Nan,bind,m)-ints(aind-2*Nan,bind,m+1));\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t    xint(aind,bind,m) += o2g*(na-1)*(xint(aind-2*Nan,bind,m)-xint(aind-2*Nan,bind,m+1));\n\t\t    yint(aind,bind,m) += o2g*(na-1)*(yint(aind-2*Nan,bind,m)-yint(aind-2*Nan,bind,m+1));\n\t\t    zint(aind,bind,m) += o2g*(na-1)*(zint(aind-2*Nan,bind,m)-zint(aind-2*Nan,bind,m+1));\n\t\t  }\n\t\t}\n\n\t\tif (nb > 0) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*nb*(ints(aind-Nan,bind-Nbn,m)-ints(aind-Nan,bind-Nbn,m+1));\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t    xint(aind,bind,m) += o2g*nb*(xint(aind-Nan,bind-Nbn,m)-xint(aind-Nan,bind-Nbn,m+1));\n\t\t    yint(aind,bind,m) += o2g*nb*(yint(aind-Nan,bind-Nbn,m)-yint(aind-Nan,bind-Nbn,m+1));\n\t\t    zint(aind,bind,m) += o2g*nb*(zint(aind-Nan,bind-Nbn,m)-zint(aind-Nan,bind-Nbn,m+1));\n\t\t  }\n\t\t}\n\n\t      } else if (ma > 0) {\n\n\t\tfor(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t  ints(aind,bind,m) = PAy*ints(aind-Nam,bind,m)-PCy*ints(aind-Nam,bind,m+1);\n\t\tfor(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t  xint(aind,bind,m) = PAy*xint(aind-Nam,bind,m)-PCy*xint(aind-Nam,bind,m+1);\n\t\t  yint(aind,bind,m) = PAy*yint(aind-Nam,bind,m)-PCy*yint(aind-Nam,bind,m+1) + ints(aind-Nam,bind,m+1);\n\t\t  zint(aind,bind,m) = PAy*zint(aind-Nam,bind,m)-PCy*zint(aind-Nam,bind,m+1);\n\t\t}\n\n\t\tif (ma > 1) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*(ma-1)*(ints(aind-2*Nam,bind,m) - ints(aind-2*Nam,bind,m+1));\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t    xint(aind,bind,m) += o2g*(ma-1)*(xint(aind-2*Nam,bind,m) - xint(aind-2*Nam,bind,m+1));\n\t\t    yint(aind,bind,m) += o2g*(ma-1)*(yint(aind-2*Nam,bind,m) - yint(aind-2*Nam,bind,m+1));\n\t\t    zint(aind,bind,m) += o2g*(ma-1)*(zint(aind-2*Nam,bind,m) - zint(aind-2*Nam,bind,m+1));\n\t\t  }\n\t\t}\n\n\t\tif (mb > 0) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*mb*(ints(aind-Nam,bind-Nbm,m) - ints(aind-Nam,bind-Nbm,m+1));\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t    xint(aind,bind,m) += o2g*mb*(xint(aind-Nam,bind-Nbm,m) - xint(aind-Nam,bind-Nbm,m+1));\n\t\t    yint(aind,bind,m) += o2g*mb*(yint(aind-Nam,bind-Nbm,m) - yint(aind-Nam,bind-Nbm,m+1));\n\t\t    zint(aind,bind,m) += o2g*mb*(zint(aind-Nam,bind-Nbm,m) - zint(aind-Nam,bind-Nbm,m+1));\n\t\t  }\n\t\t}\n\n\t      }\telse if (la > 0) {\n\n\t\tfor(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t  ints(aind,bind,m) = PAx*ints(aind-Nal,bind,m)-PCx*ints(aind-Nal,bind,m+1);\n\t\tfor(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t  xint(aind,bind,m) = PAx*xint(aind-Nal,bind,m)-PCx*xint(aind-Nal,bind,m+1) + ints(aind-Nal,bind,m+1);\n\t\t  yint(aind,bind,m) = PAx*yint(aind-Nal,bind,m)-PCx*yint(aind-Nal,bind,m+1);\n\t\t  zint(aind,bind,m) = PAx*zint(aind-Nal,bind,m)-PCx*zint(aind-Nal,bind,m+1);\n\t\t}\n\n\t\tif (la > 1) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*(la-1)*(ints(aind-2*Nal,bind,m) - ints(aind-2*Nal,bind,m+1));\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t    xint(aind,bind,m) += o2g*(la-1)*(xint(aind-2*Nal,bind,m) - xint(aind-2*Nal,bind,m+1));\n\t\t    yint(aind,bind,m) += o2g*(la-1)*(yint(aind-2*Nal,bind,m) - yint(aind-2*Nal,bind,m+1));\n\t\t    zint(aind,bind,m) += o2g*(la-1)*(zint(aind-2*Nal,bind,m) - zint(aind-2*Nal,bind,m+1));\n\t\t  }\n\t\t}\n\n\t\tif (lb > 0) {\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++)\n\t\t    ints(aind,bind,m) += o2g*lb*(ints(aind-Nal,bind-Nbl,m) - ints(aind-Nal,bind-Nbl,m+1));\n\t\t  for(int m=0;m<=mmax-lambdaa-lambdab;m++) {\n\t\t    xint(aind,bind,m) += o2g*lb*(xint(aind-Nal,bind-Nbl,m) - xint(aind-Nal,bind-Nbl,m+1));\n\t\t    yint(aind,bind,m) += o2g*lb*(yint(aind-Nal,bind-Nbl,m) - yint(aind-Nal,bind-Nbl,m+1));\n\t\t    zint(aind,bind,m) += o2g*lb*(zint(aind-Nal,bind-Nbl,m) - zint(aind-Nal,bind-Nbl,m+1));\n\t\t  }\n\t\t}\n\t      }\n\t      else {\n\t\tERROR_INFO();\n\t\tthrow std::runtime_error(\"Something went haywire in the Obara-Saika nuclear attraction integral derivative algorithm.\\n\");\n\t      }\n\t    }\n\t  }\n      }\n    }\n\n  // Size of returned array\n  int Na=(am_a+1)*(am_a+2)/2;\n  int Nb=(am_b+1)*(am_b+2)/2;\n\n  // Returned array\n  std::vector<arma::mat> V(3);\n  for(int ic=0;ic<3;ic++)\n    V[ic].zeros(Na,Nb);\n\n  // Fill in array\n  int ia, ib;\n\n  // Index of left basis function\n  ia=0;\n\n  // Loop over basis functions on this shell\n  for(int ii=0; ii<=am_a; ii++) {\n    int la=am_a - ii;\n    for(int jj=0; jj<=ii; jj++) {\n      int ma=ii - jj;\n      int na=jj;\n\n      // Index in worker array\n      int aind=la*Nal+ma*Nam+na;\n\n      // Index of right basis function\n      ib=0;\n\n      // Loop over angular momentum of second shell\n      for(int kk=0; kk<=am_b; kk++) {\n\tint lb=am_b - kk;\n\n\tfor(int ll=0; ll<=kk; ll++) {\n\t  int mb=kk-ll;\n\t  int nb=ll;\n\n\t  // Other index is\n\t  int bind=lb*Nbl+mb*Nbm+nb;\n\n\t  // Store result\n\t  V[0](ia,ib)=xint(aind,bind,0);\n\t  V[1](ia,ib)=yint(aind,bind,0);\n\t  V[2](ia,ib)=zint(aind,bind,0);\n\n\t  // Increment index of basis function\n\t  ib++;\n\t}\n      }\n\n      // Increment index of basis function\n      ia++;\n    }\n  }\n\n#ifdef DEBUG\n  // Compute Huzinaga integrals\n  std::vector<arma::mat> huzint(V);\n  for(size_t ic=0;ic<V.size();ic++)\n    huzint[ic].zeros();\n\n  int diff=0;\n\n  ia=0;\n  // Loop over basis functions on this shell\n  for(int ii=0; ii<=am_a; ii++) {\n    int ila=am_a - ii;\n    for(int jj=0; jj<=ii; jj++) {\n      int ima=ii - jj;\n      int ina=jj;\n\n      ib=0;\n      // Loop over basis functions on this shell\n      for(int kk=0; kk<=am_b; kk++) {\n\tint ilb=am_b - kk;\n\tfor(int ll=0; ll<=kk; ll++) {\n\t  int imb=kk - ll;\n\t  int inb=ll;\n\n\t  nuclear_int_der(xa,ya,za,zetaa,ila,ima,ina,xnuc,ynuc,znuc,xb,yb,zb,zetab,ilb,imb,inb,huzint[0](ia,ib),huzint[1](ia,ib),huzint[2](ia,ib));\n\n\t  for(int ic=0;ic<3;ic++)\n\t    // Differring sign convention - we actually do the force, not the derivative\n\t    if(fabs(huzint[ic](ia,ib)+V[ic](ia,ib))>100*DBL_EPSILON*std::max(fabs(huzint[ic](ia,ib)),fabs(V[ic](ia,ib))))\n\t      diff++;\n\n\t  ib++;\n\t}\n      }\n\n      ia++;\n    }\n  }\n\n  if(diff==0)\n    //    printf(\"Computed NAI shell (%e,%e,%e) - (%e,%e,%e) with nucleus at (%e,%e,%e) and exponents %e and %e with am=(%i,%i), the results match.\\n\",xa,ya,za,xb,yb,zb,xnuc,ynuc,znuc,zetaa,zetab,am_a,am_b);\n    ;\n  else {\n    ia=0;\n    // Loop over basis functions on this shell\n    for(int ii=0; ii<=am_a; ii++) {\n      int ila=am_a - ii;\n      for(int jj=0; jj<=ii; jj++) {\n\tint ima=ii - jj;\n\tint ina=jj;\n\n\tib=0;\n\t// Loop over basis functions on this shell\n\tfor(int kk=0; kk<=am_b; kk++) {\n\t  int ilb=am_b - kk;\n\t  for(int ll=0; ll<=kk; ll++) {\n\t    int imb=kk - ll;\n\t    int inb=ll;\n\n\t    for(int ic=0;ic<3;ic++)\n\t      if(fabs(huzint[ic](ia,ib)-V[ic](ia,ib))>100*DBL_EPSILON*std::max(fabs(huzint[ic](ia,ib)),fabs(V[ic](ia,ib)))) {\n\t\tprintf(\"Computed NAI shell (%e,%e,%e) - (%e,%e,%e) with nucleus at (%e,%e,%e) and exponents %e and %e.\\n\",xa,ya,za,xb,yb,zb,xnuc,ynuc,znuc,zetaa,zetab);\n\t\tprintf(\"The result for the %i derivative (%i,%i,%i)-(%i,%i,%i) is %e with Huzinaga, whereas %e with Obara-Saika; difference is %e.\\n\\n\",(int) ic, ila,ima,ina,ilb,imb,inb,huzint[ic](ia,ib),V[ic](ia,ib),huzint[ic](ia,ib)-V[ic](ia,ib));\n\t      }\n\t    ib++;\n\t  }\n\t}\n\tia++;\n      }\n    }\n  }\n#endif\n\n\n  return V;\n}\n\nstd::vector<arma::mat> nuclear_int_ders_os(double xa, double ya, double za, double zetaa, const std::vector<shellf_t> & carta, double xnuc, double ynuc, double znuc, double xb, double yb, double zb, double zetab, const std::vector<shellf_t> & cartb) {\n  // Compute shell of overlap integrals\n\n  // Angular momenta of shells\n  int am_a=carta[0].l+carta[0].m+carta[0].n;\n  int am_b=cartb[0].l+cartb[0].m+cartb[0].n;\n\n  // Compute the matrices\n  std::vector<arma::mat> V=nuclear_int_ders_os(xa,ya,za,zetaa,am_a,xnuc,ynuc,znuc,xb,yb,zb,zetab,am_b);\n\n  // Plug in the relative normalization factors\n  for(size_t i=0;i<carta.size();i++)\n    for(size_t j=0;j<cartb.size();j++)\n      for(size_t ic=0;ic<V.size();ic++)\n\tV[ic](i,j)*=carta[i].relnorm*cartb[j].relnorm;\n\n  return V;\n}\n\narma::cube three_overlap_int_os(double xa, double ya, double za, double xc, double yc, double zc, double xb, double yb, double zb, double zetaa, double zetac, double zetab, const std::vector<shellf_t> & carta, const std::vector<shellf_t> & cartc, const std::vector<shellf_t> & cartb) {\n\n  // Angular momenta of shells\n  const int am_a=carta[0].l+carta[0].m+carta[0].n;\n  const int am_b=cartb[0].l+cartb[0].m+cartb[0].n;\n  const int am_c=cartc[0].l+cartc[0].m+cartc[0].n;\n\n  //  printf(\"am_a = %i, am_b = %i, am_c = %i.\\n\",am_a,am_b,am_c);\n\n  // Necessary size for work array\n  const int size_a=(am_a+1)*(am_a+1)*am_a+1;\n  const int size_c=(am_c+1)*(am_c+1)*am_c+1;\n  const int size_b=(am_b+1)*(am_b+1)*am_b+1;\n\n  // Work array for recursion formulas\n  arma::cube ints(size_a,size_c,size_b);\n  ints.zeros();\n\n  // Helpers for computing indices on work array\n  const int Nan = 1;\n  const int Nam = am_a+1;\n  const int Nal = Nam*Nam;\n\n  const int Nbn = 1;\n  const int Nbm = am_b+1;\n  const int Nbl = Nbm*Nbm;\n\n  const int Ncn = 1;\n  const int Ncm = am_c+1;\n  const int Ncl = Ncm*Ncm;\n\n  // Reduced exponents\n  double xi=zetaa*zetab/(zetaa+zetab);\n  double zeta=zetaa+zetab;\n\n  // r_ab\n  double rabsq=(xa-xb)*(xa-xb)+(ya-yb)*(ya-yb)+(za-zb)*(za-zb);\n\n  // P\n  double px=(zetaa*xa+zetab*xb)/zeta;\n  double py=(zetaa*ya+zetab*yb)/zeta;\n  double pz=(zetaa*za+zetab*zb)/zeta;\n\n  // r_pc\n  double rpcsq=(px-xc)*(px-xc)+(py-yc)*(py-yc)+(pz-zc)*(pz-zc);\n\n  // G\n  double gx=(zeta*px+zetac*xc)/(zeta+zetac);\n  double gy=(zeta*py+zetac*yc)/(zeta+zetac);\n  double gz=(zeta*pz+zetac*zc)/(zeta+zetac);\n\n  // GA\n  double gax=gx-xa;\n  double gay=gy-ya;\n  double gaz=gz-za;\n  // GB\n  double gbx=gx-xb;\n  double gby=gy-yb;\n  double gbz=gz-zb;\n  // GC\n  double gcx=gx-xc;\n  double gcy=gy-yc;\n  double gcz=gz-zc;\n\n  // Compute initial data.\n  ints(0,0,0)=(M_PI/(zeta+zetac))*sqrt(M_PI/(zeta+zetac))*exp(-xi*rabsq - zeta*zetac/(zeta+zetac)*rpcsq);\n\n  // Now am=(0,0,0). Increase LHS angular momentum.\n  // Loop over total angular momentum\n  for(int lambdaa=1;lambdaa<=am_a;lambdaa++)\n    // Loop over angular momentum functions belonging to this shell\n    for(int ii=0; ii<=lambdaa; ii++) {\n      int la=lambdaa - ii;\n      for(int jj=0; jj<=ii; jj++) {\n\tint ma=ii - jj;\n\tint na=jj;\n\n\t// Index in integrals table\n\tint aind = la*Nal+ma*Nam+na*Nan;\n\n\t// Compute integral\n\tif(la>0) {\n\n\t  ints(aind,0,0)+=gax*ints(aind-Nal,0,0);\n\t  if(la>1)\n\t    ints(aind,0,0)+=0.5/(zeta+zetac)*(la-1)*ints(aind-2*Nal,0,0);\n\n\t} else if(ma>0) {\n\n\t  ints(aind,0,0)+=gay*ints(aind-Nam,0,0);\n\t  if(ma>1)\n\t    ints(aind,0,0)+=0.5/(zeta+zetac)*(ma-1)*ints(aind-2*Nam,0,0);\n\n\t} else if(na>0) {\n\n\t  ints(aind,0,0)+=gaz*ints(aind-Nan,0,0);\n\t  if(na>1)\n\t    ints(aind,0,0)+=0.5/(zeta+zetac)*(na-1)*ints(aind-2*Nan,0,0);\n\n\t}\n      }\n    }\n\n  // Increase total angular momentum on right-hand side\n  // Loop over total angular momentum of LHS\n  for(int lambdaa=0;lambdaa<=am_a;lambdaa++)\n\n    // Loop over angular momentum of second shell\n    for(int kk=0; kk<=lambdaa; kk++) {\n      int la=lambdaa-kk;\n\n      for(int ll=0; ll<=kk; ll++) {\n\tint ma=kk-ll;\n\tint na=ll;\n\n\t// LHS index is\n\tint aind = la*Nal + ma*Nam + na*Nan;\n\n\t// Loop over total angular momentum of RHS\n\tfor(int lambdab=1;lambdab<=am_b;lambdab++)\n\n\t  // Loop over the functions belonging to the shell\n\t  for(int ii=0; ii<=lambdab; ii++) {\n\t    int lb=lambdab - ii;\n\t    for(int jj=0; jj<=ii; jj++) {\n\t      int mb=ii - jj;\n\t      int nb=jj;\n\n\t      // RHS index is\n\t      int bind = lb*Nbl + mb*Nbm + nb*Nbn;\n\n\t      // Compute integral\n\t      if(lb>0) {\n\n\t\tints(aind,0,bind)+=gbx*ints(aind,0,bind-Nbl);\n\t\tif(lb>1)\n\t\t  ints(aind,0,bind)+=0.5/(zeta+zetac)*(lb-1)*ints(aind,0,bind-2*Nbl);\n\t\tif(la>0)\n\t\t  ints(aind,0,bind)+=0.5/(zeta+zetac)*la*ints(aind-Nal,0,bind-Nbl);\n\n\t      } else if(mb>0) {\n\n\t\tints(aind,0,bind)+=gby*ints(aind,0,bind-Nbm);\n\t\tif(mb>1)\n\t\t  ints(aind,0,bind)+=0.5/(zeta+zetac)*(mb-1)*ints(aind,0,bind-2*Nbm);\n\t\tif(ma>0)\n\t\t  ints(aind,0,bind)+=0.5/(zeta+zetac)*ma*ints(aind-Nam,0,bind-Nbm);\n\n\t      } else if(nb>0) {\n\n\t\tints(aind,0,bind)+=gbz*ints(aind,0,bind-Nbn);\n\t\tif(nb>1)\n\t\t  ints(aind,0,bind)+=0.5/(zeta+zetac)*(nb-1)*ints(aind,0,bind-2*Nbn);\n\t\tif(na>0)\n\t\t  ints(aind,0,bind)+=0.5/(zeta+zetac)*na*ints(aind-Nan,0,bind-Nbn);\n\n\t      } else {\n\t\tERROR_INFO();\n\t\tthrow std::runtime_error(\"Something went haywire in the Obara-Saika three-center overlap algorithm.\\n\");\n\t      }\n\t    }\n\t  }\n      }\n    }\n\n  // Finally, increase angular momentum in the middle\n  // Loop over total angular momentum of LHS\n  for(int lambdaa=0;lambdaa<=am_a;lambdaa++)\n\n    // Loop over angular momentum of second shell\n    for(int kk=0; kk<=lambdaa; kk++) {\n      int la=lambdaa-kk;\n\n      for(int ll=0; ll<=kk; ll++) {\n\tint ma=kk-ll;\n\tint na=ll;\n\n\t// LHS index is\n\tint aind = la*Nal + ma*Nam + na*Nan;\n\n\t// Loop over total angular momentum of RHS\n\tfor(int lambdab=0;lambdab<=am_b;lambdab++)\n\n\t  // Loop over the functions belonging to the shell\n\t  for(int ii=0; ii<=lambdab; ii++) {\n\t    int lb=lambdab - ii;\n\t    for(int jj=0; jj<=ii; jj++) {\n\t      int mb=ii - jj;\n\t      int nb=jj;\n\n\t      // RHS index is\n\t      int bind = lb*Nbl + mb*Nbm + nb*Nbn;\n\n\t      // Loop over total angular momentum of middle\n\t      for(int lambdac=1;lambdac<=am_c;lambdac++)\n\t\t// Loop over the functions belonging to the shell\n\t\tfor(int mm=0; mm<=lambdac; mm++) {\n\t\t  int lc=lambdac - mm;\n\t\t  for(int nn=0; nn<=mm; nn++) {\n\t\t    int mc=mm - nn;\n\t\t    int nc=nn;\n\n\t\t    // RHS index is\n\t\t    int cind = lc*Ncl + mc*Ncm + nc*Ncn;\n\n\t\t    // Calculate integral\n\t\t    if(lc>0) {\n\n\t\t      ints(aind,cind,bind)+=gcx*ints(aind,cind-Ncl,bind);\n\t\t      if(lc>1)\n\t\t\tints(aind,cind,bind)+=0.5/(zeta+zetac)*(lc-1)*ints(aind,cind-2*Ncl,bind);\n\t\t      if(la>0)\n\t\t\tints(aind,cind,bind)+=0.5/(zeta+zetac)*la*ints(aind-Nal,cind-Ncl,bind);\n\t\t      if(lb>0)\n\t\t\tints(aind,cind,bind)+=0.5/(zeta+zetac)*lb*ints(aind,cind-Ncl,bind-Nbl);\n\n\t\t    } else if(mc>0) {\n\n\t\t      ints(aind,cind,bind)+=gcy*ints(aind,cind-Ncm,bind);\n\t\t      if(mc>1)\n\t\t\tints(aind,cind,bind)+=0.5/(zeta+zetac)*(mc-1)*ints(aind,cind-2*Ncm,bind);\n\t\t      if(ma>0)\n\t\t\tints(aind,cind,bind)+=0.5/(zeta+zetac)*ma*ints(aind-Nam,cind-Ncm,bind);\n\t\t      if(mb>0)\n\t\t\tints(aind,cind,bind)+=0.5/(zeta+zetac)*mb*ints(aind,cind-Ncm,bind-Nbm);\n\n\t\t    } else if(nc>0) {\n\n\t\t      ints(aind,cind,bind)+=gcz*ints(aind,cind-Ncn,bind);\n\t\t      if(nc>1)\n\t\t\tints(aind,cind,bind)+=0.5/(zeta+zetac)*(nc-1)*ints(aind,cind-2*Ncn,bind);\n\t\t      if(na>0)\n\t\t\tints(aind,cind,bind)+=0.5/(zeta+zetac)*na*ints(aind-Nan,cind-Ncn,bind);\n\t\t      if(nb>0)\n\t\t\tints(aind,cind,bind)+=0.5/(zeta+zetac)*nb*ints(aind,cind-Ncn,bind-Nbn);\n\n\t\t    } else {\n\t\t      ERROR_INFO();\n\t\t      throw std::runtime_error(\"Something went haywire in the Obara-Saika three-center overlap algorithm.\\n\");\n\t\t    }\n\t\t  }\n\t\t}\n\t    }\n\t  }\n      }\n    }\n\n  // Size of returned array\n  const int Na=carta.size();\n  const int Nc=cartc.size();\n  const int Nb=cartb.size();\n\n  // Fill in returned array\n  arma::cube S(Na,Nc,Nb);\n  S.zeros();\n\n  for(size_t i=0;i<carta.size();i++) {\n    int la=carta[i].l;\n    int ma=carta[i].m;\n    int na=carta[i].n;\n\n    double ca=carta[i].relnorm;\n\n    // LHS index in worker array\n    int aind=la*Nal+ma*Nam+na;\n\n    for(size_t j=0;j<cartb.size();j++) {\n      int lb=cartb[j].l;\n      int mb=cartb[j].m;\n      int nb=cartb[j].n;\n\n      double cb=cartb[j].relnorm;\n\n      // RHS index in worker array\n      int bind=lb*Nbl+mb*Nbm+nb;\n\n      for(size_t k=0;k<cartc.size();k++) {\n\tint lc=cartc[k].l;\n\tint mc=cartc[k].m;\n\tint nc=cartc[k].n;\n\n\tdouble cc=cartc[k].relnorm;\n\n\t// Middle index in worker array\n\tint cind = lc*Ncl + mc*Ncm + nc*Ncn;\n\n\t/*\n\tprintf(\"(%i,%i,%i) (%i,%i,%i) (%i,%i,%i)\\n\",la,ma,na,lb,mb,nb,lc,mc,nc);\n\tprintf(\"S is (%i,%i,%i), accessing element (%i,%i,%i).\\n\",Na,Nc,Nb,i,k,j);\n\tprintf(\"ints is (%i,%i,%i), accessing element (%i,%i,%i).\\n\",size_a,size_c,size_b,aind,cind,bind);\n\tfflush(stdout);\n\t*/\n\n\tS(i,k,j)=ca*cb*cc*ints(aind,cind,bind);\n      }\n    }\n  }\n\n  return S;\n}\n", "meta": {"hexsha": "c24fbb70a5c180776aeed97151e6f6acdf881f9f", "size": 58223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tiger_ci/erkale/obara-saika.cpp", "max_stars_repo_name": "EACcodes/TigerCI", "max_stars_repo_head_hexsha": "ac1311ea5e2b829b5507171afdbdd6c64e12e6fd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-12-08T13:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-17T17:05:46.000Z", "max_issues_repo_path": "tiger_ci/erkale/obara-saika.cpp", "max_issues_repo_name": "EACcodes/TigerCI", "max_issues_repo_head_hexsha": "ac1311ea5e2b829b5507171afdbdd6c64e12e6fd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tiger_ci/erkale/obara-saika.cpp", "max_forks_repo_name": "EACcodes/TigerCI", "max_forks_repo_head_hexsha": "ac1311ea5e2b829b5507171afdbdd6c64e12e6fd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-20T06:03:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-09T09:00:49.000Z", "avg_line_length": 28.1815101646, "max_line_length": 285, "alphanum_fraction": 0.5998832077, "num_tokens": 23914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4489126742804637}}
{"text": "#include <iostream>\n#include <vector>\n#include <zmqpp/zmqpp.hpp>\n#include <string>\n#include <sstream>\n#include <stdlib.h>     /* for realloc() and free() */\n#include <string.h>     /* for memset() */\n#include <errno.h>      /* for errno */\n#include \"nlohmann/json.hpp\"\n#include <armadillo>\n#include <typeinfo>\n#include \"Threadpool.hh\"\n\nusing namespace zmqpp;\nusing namespace arma;\nusing json = nlohmann::json;\n\nclass EWorker{\n    private:\n        mat r_ic;\n        std::vector<mat> cov;\n        mat regcov;\n        mat mu;\n        vec pivector;\n        mat data;\n    public:\n        EWorker(std::vector<std::vector<double>> muvec,\n                std::vector<double> piv,\n                std::vector<std::vector<double>> regcovvec,\n                std::vector<std::vector<std::vector<double>>> covvec,\n                std::vector<std::vector<double>> xvec \n\n                ){\n            // int n_of_sources = data.size();\n            // int n_of_data = data.at(0).size();\n            int counter = 0;\n            for (std::vector<double> cmu: muvec){\n                mu.insert_cols(counter, vec(cmu));\n                counter++;\n            }\n            pivector = vec(piv);\n            counter = 0;\n            for (std::vector<double> cregcov: regcovvec){\n                regcov.insert_cols(counter, vec(cregcov));\n                counter++;\n            }\n            counter = 0;\n            int counter2 = 0;\n            for (std::vector<std::vector<double>> covmatrix : covvec){\n                mat temp;\n                for(std::vector<double>covmatrixrow: covmatrix){\n                    temp.insert_cols(counter,vec(covmatrixrow));\n                    counter++;\n                }\n                counter = 0;\n                cov.insert(cov.begin() + counter2, temp);\n                counter2++;\n            }\n\n            // cout<<\"MU:\\n-------------------\\n\"<<mu<<\"\\n-------------------\\n\";\n            // cout<<\"PI:\\n-------------------\\n\"<<pivector<<\"\\n-------------------\\n\";\n            // // cout<<\"COV:\\n-------------------\\n\";\n\n            // for (mat covtest : cov)\n            //     cout<<covtest<<endl;\n            // cout<<\"\\n-------------------\\n\";\n            for(int i=0;i<xvec.at(0).size();i++){\n                std::vector<double>temp(xvec.size());\n                counter = 0;\n                for(std::vector<double> datarow : xvec){\n                    temp.at(counter)= datarow.at(i);\n                    counter++;\n                }\n                data.insert_cols(i, vec(temp));\n            }\n            // cout<<\"\\n-------------------\\n\";\n\n            // cout<<\"DATA: \"<<endl<<data;\n            // cout<<\"\\n-------------------\\n\";\n\n            // r_ic = new mat(n_of_data, n_of_sources);\n            // cov = new mat(n_of_data, n_of_data);\n            // std::cout<<mu<<endl;\n        }   \n        \n        mat& getRIC(){\n            // r_ic.zeros();\n            mat datatranspose = data.t();\n            for(int i = 0; i < mu.n_cols; i++){\n                {\n                    ThreadPool pool(4);\n                    pool.enqueue([i, this, datatranspose]{\n                    mat co = cov.at(i);\n                    co += regcov;\n                    std::vector<double> r(data.n_rows);\n                    double detco = det(co);\n                    double pic = pivector.at(i);\n                    double fraction = 1/sqrt(pow((2*datum::pi), mu.n_rows)* det(co));\n                    vec m(mu.colptr(i),mu.n_rows);\n\n                    \n                        for(int j = 0; j < datatranspose.n_cols; j++){\n                        \n                            vec datasubset(datatranspose.colptr(j), datatranspose.n_rows);\n                            mat delta = datasubset - m;\n                            mat deltatranspose = delta.t();\n                            double exparg = ((-0.5)*deltatranspose*inv(co)*delta).eval()(0,0);\n                            double eulerexp = exp(exparg);\n                            // cout<<\"First: \"<<(-0.5)*deltatranspose;\n                            // cout<<\"Second:\\n \"<<inv(co)*delta<<endl;\n\n                            // cout<<\"Fraction: \"<<fraction<<\"\\tExparg: \"<<exparg<<\"\\tEulerexp:\"<<eulerexp<<endl;\n                            double pdf = eulerexp * fraction;\n                            pdf *= pic;\n                            r.at(j)=pdf;\n\n                        }\n                    r_ic.insert_cols(i,vec(r));\n                });\n                }\n               \n            \n            }\n            \n            r_ic = normalise(r_ic,1,1);\n            return r_ic;\n        }\n};\n\n// Lo que debe hacer el worker es:\n// 1. Recibir un arreglo de tuplas\n// 2. Iterar sobre calcular el arreglo ric para estos datos \n// 3. Enviar Ric al sink\n\n// class EWorker {\n//   public:\n//     EWorker(std::vector <std::vector <float>> data) {\n\n//     };\n\n//     std::vector <std::vector <float>> obtenerVectorRIC() {\n    // \"\"\"E Step\"\"\"\n    // r_ic = np.zeros((len(self.X),len(self.cov)))\n    // for m,co,p,r in zip(self.mu,self.cov,self.pi,range(len(r_ic[0]))):\n    //     co+=self.reg_cov\n    //     mn = multivariate_normal(mean=m,cov=co)\n    //     r_ic[:,r] = p*mn.pdf(self.X)/np.sum([pi_c*multivariate_normal(mean=mu_c,cov=cov_c).pdf(X) for pi_c,mu_c,cov_c in zip(self.pi,self.mu,self.cov+self.reg_cov)],axis=0)\n\n//     }\n// };\n\n// std::vector <std::vector<float>> convertToVector(std::string npArray) {\n//     std::vector <float> vec;\n//     vec.push_back(1);\n//     std::vector <std::vector <float>> vecs;\n//     vecs.push_back(vec);\n//     return vecs;\n\n// }\nint main() {\n    context ctx;\n    zmqpp::message message;\n    socket work(ctx, socket_type::pull);\n    socket sink(ctx, socket_type::push);\n    std::cout<<\"connecting\"<<std::endl;\n    work.connect(\"tcp://localhost:5557\");\n    sink.connect(\"tcp://localhost:5558\");\n    std::cout<<\"Receiving\"<<std::endl;\n\n    while(true){\n    work.receive(message);\n    json info = json::parse(message.get(0));\n\n    std::cout<<\"using json\"<<std::endl;\n    // std::cout << info[\"mu\"] << std::endl;\n    // std::vector<double> armadillotest{10,20,30};\n    // mat hi(armadillotest);\n    std::vector<std::vector<double>> mu = info[\"mu\"].get <std::vector<std::vector<double>>> ();\n    std::vector<double> pi = info[\"pi\"].get <std::vector <double>>();\n    std::vector<std::vector<double>> regcov = info[\"regcov\"].get <std::vector<std::vector<double>>> ();\n    std::vector<std::vector<std::vector<double>>> cov = info[\"cov\"]\n    .get <std::vector<std::vector<std::vector<double>>>> ();\n    std::vector<std::vector<double>> x = info[\"x\"].get <std::vector<std::vector<double>>> ();\n    // std::cout<<\"mu: \"<<info[\"mu\"]<<std::endl;\n    \n    EWorker worker(mu,pi,regcov, cov, x);\n    mat  r_ic = worker.getRIC(); \n    std::vector<std::vector <double>> vectosend(x.size());\n    for (int i=0; i<r_ic.n_rows;i++){\n        vectosend[i]=arma::conv_to<std::vector<double>>::from(r_ic.row(i));\n    }\n    cout<<\"R_IC:\\n-------------------\\n\";\n\n    cout<<r_ic<<endl;\n\n    json tosend;\n    tosend[\"ric\"] = vectosend;\n    tosend[\"X\"] = x;\n    auto t = tosend.dump();\n    sink.send(t);\n    }\n    // std::vector <std::vector <float>> dataAsVector = convertToVector(message.get(0));\n    // EWorker worker = EWorker(dataAsVector);\n    // std::vector <std::vector <float>> ric = worker.obtenerVectorRIC();\n}\n", "meta": {"hexsha": "4a14a9b690b675565195b85fa44fed59009cc79b", "size": 7316, "ext": "cc", "lang": "C++", "max_stars_repo_path": "practicas/maximizacion_esperanza/worker.cc", "max_stars_repo_name": "mrfreedeer/Arquitectura-Cliente-Servidor", "max_stars_repo_head_hexsha": "aac90b50d150de29a2cee276050013f7bb826d72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "practicas/maximizacion_esperanza/worker.cc", "max_issues_repo_name": "mrfreedeer/Arquitectura-Cliente-Servidor", "max_issues_repo_head_hexsha": "aac90b50d150de29a2cee276050013f7bb826d72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "practicas/maximizacion_esperanza/worker.cc", "max_forks_repo_name": "mrfreedeer/Arquitectura-Cliente-Servidor", "max_forks_repo_head_hexsha": "aac90b50d150de29a2cee276050013f7bb826d72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5145631068, "max_line_length": 175, "alphanum_fraction": 0.4767632586, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.4488972936277532}}
{"text": "/********************************************************************************\n*  This file is part of CinoLib                                                 *\n*  Copyright(C) 2016: Marco Livesu                                              *\n*                                                                               *\n*  The MIT License                                                              *\n*                                                                               *\n*  Permission is hereby granted, free of charge, to any person obtaining a      *\n*  copy of this software and associated documentation files (the \"Software\"),   *\n*  to deal in the Software without restriction, including without limitation    *\n*  the rights to use, copy, modify, merge, publish, distribute, sublicense,     *\n*  and/or sell copies of the Software, and to permit persons to whom the        *\n*  Software is furnished to do so, subject to the following conditions:         *\n*                                                                               *\n*  The above copyright notice and this permission notice shall be included in   *\n*  all copies or substantial portions of the Software.                          *\n*                                                                               *\n*  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR   *\n*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,     *\n*  FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE *\n*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER       *\n*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      *\n*  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS *\n*  IN THE SOFTWARE.                                                             *\n*                                                                               *\n*  Author(s):                                                                   *\n*                                                                               *\n*     Marco Livesu (marco.livesu@gmail.com)                                     *\n*     http://pers.ge.imati.cnr.it/livesu/                                       *\n*                                                                               *\n*     Daniela Cabiddu                                                           *\n*     http://www.imati.cnr.it/index.php/people/8-curricula/119-daniela-cabiddu  *\n*                                                                               *\n*     Italian National Research Council (CNR)                                   *\n*     Institute for Applied Mathematics and Information Technologies (IMATI)    *\n*     Via de Marini, 6                                                          *\n*     16149 Genoa,                                                              *\n*     Italy                                                                     *\n*********************************************************************************/\n#include <cinolib/polygon_maximum_inscribed_circle.h>\n#include <cinolib/geometry/segment.h>\n#include <cinolib/min_max_inf.h>\n\n// Most of this is coming from here:\n// http://www.boost.org/doc/libs/1_65_1/libs/polygon/doc/voronoi_diagram.htm\n// http://www.boost.org/doc/libs/1_65_0/libs/polygon/example/voronoi_basic_tutorial.cpp\n//\n#ifdef CINOLIB_USES_BOOST\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry.hpp>\n#include <boost/polygon/voronoi.hpp>\n//\nusing boost::polygon::voronoi_builder;\nusing boost::polygon::voronoi_diagram;\nusing boost::polygon::voronoi_edge;\nusing boost::polygon::x;\nusing boost::polygon::y;\nusing boost::polygon::low;\nusing boost::polygon::high;\n//\nstruct polygon_point\n{\n    int x;\n    int y;\n    polygon_point(int x, int y) : x(x), y(y) {}\n};\n//\nstruct polygon_segment\n{\n    polygon_point p0;\n    polygon_point p1;\n    polygon_segment(int x1, int y1, int x2, int y2) : p0(x1, y1), p1(x2, y2) {}\n};\n//\ntemplate<>\nstruct boost::polygon::geometry_concept<polygon_point>\n{\n    typedef boost::polygon::point_concept type;\n};\n//\ntemplate<>\nstruct boost::polygon::point_traits<polygon_point>\n{\n    typedef int coordinate_type;\n    static inline coordinate_type get(const polygon_point & point, orientation_2d orient)\n    {\n        return (orient == HORIZONTAL) ? point.x : point.y;\n    }\n};\n//\ntemplate<>\nstruct boost::polygon::geometry_concept<polygon_segment>\n{\n    typedef boost::polygon::segment_concept type;\n};\n//\ntemplate<>\nstruct boost::polygon::segment_traits<polygon_segment>\n{\n    typedef int coordinate_type;\n    typedef polygon_point point_type;\n\n    static inline point_type get(const polygon_segment& segment, direction_1d dir)\n    {\n        return dir.to_int() ? segment.p1 : segment.p0;\n    }\n};\n//\ntypedef boost::geometry::model::d2::point_xy<double> BoostPoint;\ntypedef boost::geometry::model::polygon<BoostPoint>  BoostPolygon;\n\n#endif // CINOLIB_USES_BOOST\n\nnamespace cinolib\n{\n\n#ifdef CINOLIB_USES_BOOST\n\nBoostPolygon make_boost_poly(const std::vector<vec2d> & poly)\n{\n    BoostPolygon boost_poly;\n    for(vec2d p : poly) boost::geometry::append(boost_poly, BoostPoint(p.x(), p.y()));\n    boost::geometry::correct(boost_poly);\n    return boost_poly;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nvoid polygon_maximum_inscribed_circle(const std::vector<vec2d> & poly,\n                                            vec2d              & center,\n                                            double             & radius)\n{\n    radius = 0.0;\n    center = vec2d(0,0);\n\n    vec2d min( inf_double,  inf_double);\n    vec2d max(-inf_double, -inf_double);\n    for(auto p : poly)\n    {\n        min = min.min(p);\n        max = max.max(p);\n    }\n\n    double scale_factor;\n    double diag = min.dist(max);\n\n    if(diag >= 1.0) scale_factor = std::numeric_limits<int>::max() / diag;\n    else            scale_factor = std::numeric_limits<int>::max() * diag;\n\n    scale_factor *= 0.5; // dumb attempt to stay on the safe side and avoid overflows...\n\n    // Boost implementation of Generazlied Voronoi uses integer coordinates.\n    // In order to achieve maximum precision I am scaling the polygon as much\n    // as I can in order to minimize loss of precision during integer roundoff...\n\n    std::vector<polygon_segment> segments;\n    for(uint i=0; i<poly.size(); ++i)\n    {\n        vec2d v0 = scale_factor * poly.at(i);\n        vec2d v1 = scale_factor * poly.at((i+1)%poly.size());\n        segments.push_back(polygon_segment(v0.x(), v0.y(), v1.x(), v1.y()));\n    }\n\n    voronoi_diagram<double> vd;\n    construct_voronoi(segments.begin(), segments.end(), &vd);\n\n    BoostPolygon boost_poly = make_boost_poly(poly);\n    for(auto it=vd.vertices().begin(); it!=vd.vertices().end(); ++it)\n    {\n        const voronoi_diagram<double>::vertex_type &v = *it;\n        const voronoi_diagram<double>::edge_type   *e = v.incident_edge();\n        const voronoi_diagram<double>::cell_type   *c = e->cell();\n        const polygon_segment                        &s = segments.at(c->source_index());\n\n        // do not consider Voronoi vertices outside the polygon\n        if (boost::geometry::within(BoostPoint(v.x()/scale_factor, v.y()/scale_factor), boost_poly))\n        {\n            // annoying wrap to vec3d (TODO: template cinolib::Segment to make it work in 2D too)\n            vec3d beg(s.p0.x, s.p0.y, 0);\n            vec3d end(s.p1.x, s.p1.y, 0);\n            vec3d c3d(v.x(),  v.y(),  0);\n            cinolib::Segment tmp(beg,end);\n            double d = tmp.dist_to_point(c3d);\n\n            if (d > radius)\n            {\n                radius = d;\n                center = vec2d(c3d); // will automatically drop z\n            }\n        }\n    }\n\n    radius /= scale_factor;\n    center /= scale_factor;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\nCINO_INLINE\nvoid polygon_maximum_inscribed_circle(const std::vector<vec3d> & poly,   // will drop z component\n                                            vec3d              & center, // will have z=0\n                                            double             & radius)\n{\n    std::vector<vec2d> poly_2d;\n    for(auto p : poly) poly_2d.push_back(vec2d(p.x(), p.y()));\n\n    vec2d center_2d;\n    polygon_maximum_inscribed_circle(poly_2d, center_2d, radius);\n    center = vec3d(center_2d.x(), center_2d.y(), 0);\n}\n\n#endif // CINOLIB_USES_BOOST\n\n}\n", "meta": {"hexsha": "f5069bb2fd7656d8e6b1ea74c04fbae57083e26c", "size": 8580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/cinolib/polygon_maximum_inscribed_circle.cpp", "max_stars_repo_name": "bbrrck/cinolib", "max_stars_repo_head_hexsha": "c7cceefd041646e1e1113339e681e212a9bba7e7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-22T00:23:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-22T00:23:45.000Z", "max_issues_repo_path": "include/cinolib/polygon_maximum_inscribed_circle.cpp", "max_issues_repo_name": "snowfox1939/cinolib", "max_issues_repo_head_hexsha": "6017d9dd7461e7008df8198563d63526db3ed86a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cinolib/polygon_maximum_inscribed_circle.cpp", "max_forks_repo_name": "snowfox1939/cinolib", "max_forks_repo_head_hexsha": "6017d9dd7461e7008df8198563d63526db3ed86a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7222222222, "max_line_length": 100, "alphanum_fraction": 0.5257575758, "num_tokens": 1851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4488870671879591}}
{"text": "//\n// Created by jianping on 17-9-11.\n//\n\n#include <iostream>\n#include <glog/logging.h>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <Eigen/Dense>\n#include <opencv2/core/eigen.hpp>\n#include <fstream>\n#include <Eigen/Geometry>\n\n//image intrinsics\n//reference image r,t\n//source image r,t\n//https://github.com/opencv/opencv/blob/master/samples/cpp/stereo_match.cpp\n\n\n\n\nvoid saveXYZ(const char* filename, const cv::Mat& mat,float tx)\n{\n    const double max_z = 10000;\n    FILE* fp = fopen(filename, \"wt\");\n    for(int y = 0; y < mat.rows; y++)\n    {\n        for(int x = 0; x < mat.cols; x++)\n        {\n            cv::Vec3f point = mat.at<cv::Vec3f>(y, x);\n            if(fabs(fabs(point[2]) - max_z) < FLT_EPSILON || fabs(point[2]) > max_z) continue;\n            fprintf(fp, \"%f %f %f\\n\", point[0], point[1], point[2]);\n        }\n    }\n    fclose(fp);\n}\n\nvoid readParams(const std::string& intrinsicFile,\n                Eigen::Matrix3d& K,\n                Eigen::Matrix3d& C,\n                Eigen::Vector3d& t)\n{\n    std::ifstream ifs(intrinsicFile.c_str(),std::ios_base::in);\n    char line[256];\n    ifs.getline(line,256);\n    sscanf(line,\"%lf %lf %lf\",&K(0,0),&K(0,1),&K(0,2));\n    ifs.getline(line,256);\n    sscanf(line,\"%lf %lf %lf\",&K(1,0),&K(1,1),&K(1,2));\n    ifs.getline(line,256);\n    sscanf(line,\"%lf %lf %lf\",&K(2,0),&K(2,1),&K(2,2));\n    ifs.getline(line,256);//useless\n    ifs.getline(line,256);\n    sscanf(line,\"%lf %lf %lf\",&C(0,0),&C(0,1),&C(0,2));\n    ifs.getline(line,256);\n    sscanf(line,\"%lf %lf %lf\",&C(1,0),&C(1,1),&C(1,2));\n    ifs.getline(line,256);\n    sscanf(line,\"%lf %lf %lf\",&C(2,0),&C(2,1),&C(2,2));\n    ifs.getline(line,256);\n    sscanf(line,\"%lf %lf %lf\",&t(0),&t(1),&t(2));\n    std::cout<<K<<\"\\n\"<<C<<\"\\n\"<<t.transpose()<<\"\\n\";\n\n}\n\n\nconst int scale = 1;\nint main()\n{\n    LOG(INFO)<<\"matching\"<<std::endl;\n    cv::Mat image_ref_origin = cv::imread(\"rdimage.001.ppm\");\n    cv::Mat image_source_origin = cv::imread(\"rdimage.000.ppm\");\n    cv::Mat image_ref,image_source;\n\n    cv::resize(image_ref_origin,image_ref,\n               cv::Size(image_ref_origin.cols/scale,image_ref_origin.rows/scale),\n               0,0,cv::INTER_CUBIC);\n    cv::resize(image_source_origin,image_source,\n               cv::Size(image_ref_origin.cols/scale,image_ref_origin.rows/scale),\n               0,0,cv::INTER_CUBIC);\n\n    Eigen::Matrix3d K0,C0,K1,C1,C;\n    Eigen::Vector3d r0,r1,r;\n    readParams(\"rdimage.001.ppm.camera\",K0,C0,r0);\n    readParams(\"rdimage.000.ppm.camera\",K1,C1,r1);\n    {\n        K0(0,0)/=scale;\n        K0(1,1)/=scale;\n        K0(0,2)/=scale;\n        K0(1,2)/=scale;\n        K1(0,0)/=scale;\n        K1(1,1)/=scale;\n        K1(0,2)/=scale;\n        K1(1,2)/=scale;\n    }\n    //C = C0.transpose()*C1;\n    //r = C0.transpose()*(r1-r0);\n    C = C1.transpose()*C0;// transform p from frame 0 to frame 1\n    r = C1.transpose()*(r0-r1);\n    Eigen::Quaterniond q(C);\n    C = q.toRotationMatrix();\n    cv::Mat Q;\n    cv::Rect roi1, roi2;\n    cv::Mat M0,M1,R01(3,3,CV_64FC1),t(3,1,CV_64FC1),R0__,R1__,P0__,P1__;\n    cv::Mat D0(5,1,CV_64FC1),D1(5,1,CV_64FC1);\n    D0.setTo(0);\n    D1.setTo(0);\n    cv::eigen2cv(K0,M0);\n    cv::eigen2cv(K1,M1);\n    cv::eigen2cv(C,R01);\n    cv::eigen2cv(r,t);\n\n    cv::Size size(image_ref.cols, image_ref.rows);\n    cv::stereoRectify(M0,D0,M1,D1,\n                      size,R01,t,\n                      R0__,R1__,\n                      P0__,P1__,\n                      Q,cv::CALIB_FIX_INTRINSIC,-1,\n                      size, &roi1, &roi2\n    );\n\n    cv::Mat map11, map12, map21, map22;\n    cv::initUndistortRectifyMap(M0, D0, R0__, P0__, size, CV_16SC2, map11, map12);\n    cv::initUndistortRectifyMap(M1, D1, R1__, P1__, size, CV_16SC2, map21, map22);\n    //std::cout<<P0__<<\"\\n\"<<R1__<<std::endl;\n    cv::Mat img1r, img2r;\n    cv::remap(image_ref, img1r, map11, map12, cv::INTER_LINEAR);\n    cv::remap(image_source, img2r, map21, map22, cv::INTER_LINEAR);\n\n    image_ref = img1r;\n    image_source = img2r;\n\n//    cv::resize(img1r,image_ref,cv::Size(size.width/3,size.height/3));\n//    cv::resize(img2r,image_source,cv::Size(size.width/3,size.height/3));\n\n\n    //cv::waitKey(0);\n\n    cv::StereoSGBM sgbm(-512,1024,\n                        8,8*3*3*3,32*3*3*3,2,\n                        16,5,100,\n                        2,false\n    );\n\n    cv::Mat disp,disp8,dispnorm(image_ref.rows,image_ref.cols,CV_64FC1);\n    sgbm(image_ref,image_source,disp);\n\n//    cv::normalize(disp,dispnorm,255,0,cv::NORM_MINMAX);\n//    dispnorm.convertTo(disp8, CV_8U);\n//    cv::namedWindow(\"re\",cv::WINDOW_NORMAL);\n//    cv::imshow(\"re\",disp8);\n\n\n    cv::namedWindow(\"ref\",cv::WINDOW_NORMAL);\n    cv::namedWindow(\"source\",cv::WINDOW_NORMAL);\n\n    for (int i = 0; i < image_ref.rows; i += image_ref.rows/20 ) {\n        cv::line(image_ref,cv::Point(0,i),cv::Point(image_ref.cols,i),cv::Scalar(0,255,0),1);\n        cv::line(image_source,cv::Point(0,i),cv::Point(image_ref.cols,i),cv::Scalar(0,255,0),1);\n\n    }\n\n    cv::imshow(\"ref\",image_ref);\n    cv::imshow(\"source\",image_source);\n\n    cv::Mat xyz,xyz8;\n    reprojectImageTo3D(disp, xyz, Q, false);\n\n    saveXYZ(\"./pts.xyz\", xyz, r(0));\n    cv::waitKey(0);\n    return 0;\n}", "meta": {"hexsha": "f696f523827f27b661031a1f3e4895c9144468cc", "size": 5238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/matchingtest.cpp", "max_stars_repo_name": "kafeiyin00/DepthProbability", "max_stars_repo_head_hexsha": "15a2f3a710cdf2aaf5dbef263dfdd32f5f53fe6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-01T02:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-01T02:10:32.000Z", "max_issues_repo_path": "src/matchingtest.cpp", "max_issues_repo_name": "kafeiyin00/DepthProbability", "max_issues_repo_head_hexsha": "15a2f3a710cdf2aaf5dbef263dfdd32f5f53fe6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matchingtest.cpp", "max_forks_repo_name": "kafeiyin00/DepthProbability", "max_forks_repo_head_hexsha": "15a2f3a710cdf2aaf5dbef263dfdd32f5f53fe6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-14T05:32:14.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-14T05:32:14.000Z", "avg_line_length": 30.6315789474, "max_line_length": 96, "alphanum_fraction": 0.5769377625, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4488730132608406}}
{"text": "//    Copyright 2021 Jij Inc.\n\n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n\n//        http://www.apache.org/licenses/LICENSE-2.0\n\n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n\n#ifndef OPENJIJ_GRAPH_DENSE_HPP__\n#define OPENJIJ_GRAPH_DENSE_HPP__\n\n#include <map>\n#include <vector>\n#include <cassert>\n#include <cstddef>\n#include <type_traits>\n#include <algorithm>\n#include <exception>\n\n#include <utility/disable_eigen_warning.hpp>\n#include <Eigen/Dense>\n\n#include <graph/json/parse.hpp>\n#include <graph/graph.hpp>\n\nnamespace openjij {\n    namespace graph {\n\n        /**\n         * @brief two-body all-to-all interactions \n         * The Hamiltonian is like\n         * \\f[\n         * H = \\sum_{i<j}J_{ij} \\sigma_i \\sigma_j + \\sum_{i}h_{i} \\sigma_i\n         * \\f]\n         *\n         * @tparam FloatType float type of Sparse class (double or float)\n         */\n        template<typename FloatType>\n            class Dense : public Graph{\n                static_assert(std::is_floating_point<FloatType>::value, \"FloatType must be floating-point type.\");\n                public:\n\n                    /**\n                     * @brief interaction type (Eigen)\n                     * The stored matrix has the following triangular form:\n                     *\n                     * \\f[\n                     * \\begin{pmatrix}\n                     * J_{0,0} & J_{0,1} & \\cdots & J_{0,N-1} & h_{0}\\\\\n                     * 0 & J_{1,1} & \\cdots & J_{1,N-1} & h_{1}\\\\\n                     * \\vdots & \\vdots & \\vdots & \\vdots & \\vdots \\\\\n                     * 0 & 0 & \\cdots & J_{N-1,N-1} & h_{N-1}\\\\\n                     * 0 & 0 & \\cdots & 0 & 1 \\\\\n                     * \\end{pmatrix}\n                     * \\f]\n                     */\n                    using Interactions = Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n                    /**\n                     * @brief float type\n                     */\n                    using value_type = FloatType;\n                    \n                private:\n\n                    /**\n                     * @brief interactions \n                     */\n                    Interactions _J;\n\n                public:\n\n                    /**\n                     * @brief Dense constructor\n                     *\n                     * @param num_spins the number of spins\n                     */\n                    explicit Dense(std::size_t num_spins)\n                        : Graph(num_spins), _J(Interactions::Zero(num_spins+1, num_spins+1)){\n                            _J(num_spins, num_spins) = 1;\n                        }\n\n                    /**\n                     * @brief Dense constructor (from nlohmann::json)\n                     *\n                     * @param j JSON object this object must be a serialized object of dense BQM.\n                     */\n                    Dense(const json& j) : Dense(static_cast<size_t>(j[\"num_variables\"])){\n                        //define bqm with ising variables\n                        auto bqm = json_parse<FloatType, cimod::Dense>(j);\n                        //interactions\n                        //for(auto&& elem : bqm.get_quadratic()){\n                        //    const auto& key = elem.first;\n                        //    const auto& val = elem.second;\n                        //    J(key.first, key.second) += val;\n                        //}\n                        //local field\n                        //for(auto&& elem : bqm.get_linear()){\n                        //    const auto& key = elem.first;\n                        //    const auto& val = elem.second;\n                        //    h(key) += val;\n                        //}\n                        // the above insertion is simplified as \n                        this->_J = bqm.interaction_matrix();\n                    }\n\n                    /**\n                     * @brief set interaction matrix from Eigen Matrix.\n                     *\n                     * @param interaction Eigen matrix\n                     */\n                    void set_interaction_matrix(const Interactions& interaction){\n                        if(interaction.rows() != interaction.cols()){\n                            std::runtime_error(\"interaction.rows() != interaction.cols()\");\n                        }\n\n                        if((size_t)interaction.rows() != get_num_spins() + 1){\n                            throw std::runtime_error(\"invalid matrix size.\");\n                        }\n\n                        //check if diagonal elements are zero\n                        for(size_t i=0; i<(size_t)(interaction.rows()-1); i++){\n                            if(interaction(i,i) != 0){\n                                throw std::runtime_error(\"The diagonal elements of interaction matrix must be zero.\");\n                            }\n                        }\n\n                        if(interaction(interaction.rows()-1,interaction.rows()-1) != 1){\n                            throw std::runtime_error(\"The right bottom element of interaction matrix must be unity.\");\n                        }\n\n                        _J = interaction.template selfadjointView<Eigen::Upper>();\n                    }\n\n\n                    /**\n                     * @brief Dense copy constructor\n                     */\n                    Dense(const Dense<FloatType>&) = default;\n\n                    /**\n                     * @brief Dense move constructor\n                     */\n                    Dense(Dense<FloatType>&&) = default;\n\n                    /**\n                     * @brief calculate total energy \n                     *\n                     * @param spins\n                     * @deprecated use energy(spins)\n                     *\n                     * @return corresponding energy\n                     */\n                    FloatType calc_energy(const Spins& spins) const{\n                        return this->energy(spins);\n                    }\n\n                    FloatType calc_energy(const Eigen::Matrix<FloatType, Eigen::Dynamic, 1, Eigen::ColMajor>& spins) const{\n                        return this->energy(spins);\n                    }\n\n                    /**\n                     * @brief calculate total energy \n                     *\n                     * @param spins\n                     *\n                     * @return corresponding energy\n                     */\n                    FloatType energy(const Spins& spins) const{\n                        if(spins.size() != this->get_num_spins()){\n                            throw std::out_of_range(\"Out of range in energy in Dense graph.\");\n                        }\n\n                        using Vec = Eigen::Matrix<FloatType, Eigen::Dynamic, 1, Eigen::ColMajor>;\n                        Vec s(get_num_spins()+1);\n                        for(size_t i=0; i<spins.size(); i++){\n                            s(i) = spins[i];\n                        }\n                        s(get_num_spins()) = 1;\n\n                        // the energy must be consistent with BinaryQuadraticModel.\n                        return (s.transpose()*(_J.template triangularView<Eigen::Upper>()*s))(0,0)-1;\n                    }\n\n                    FloatType energy(const Eigen::Matrix<FloatType, Eigen::Dynamic, 1, Eigen::ColMajor>& spins) const{\n                        graph::Spins temp_spins(get_num_spins());\n                        for(size_t i=0; i<temp_spins.size(); i++){\n                            temp_spins[i] = spins(i);\n                        }\n                        return energy(temp_spins);\n\n                    }\n\n                    /**\n                     * @brief access J_{ij}\n                     *\n                     * @param i Index i\n                     * @param j Index j\n                     *\n                     * @return J_{ij}\n                     */\n                    FloatType& J(Index i, Index j){\n                        assert(i < get_num_spins());\n                        assert(j < get_num_spins());\n\n                        if(i != j)\n                            return _J(std::min(i, j), std::max(i, j));\n                        else\n                            return _J(std::min(i, j), get_num_spins());\n                    }\n\n                    /**\n                     * @brief access J_{ij}\n                     *\n                     * @param i Index i\n                     * @param j Index j\n                     *\n                     * @return J_{ij}\n                     */\n                    const FloatType& J(Index i, Index j) const{\n                        assert(i < get_num_spins());\n                        assert(j < get_num_spins());\n\n                        if(i != j)\n                            return _J(std::min(i, j), std::max(i, j));\n                        else\n                            return _J(std::min(i, j), get_num_spins());\n                    }\n\n                    /**\n                     * @brief access h_{i} (local field)\n                     *\n                     * @param i Index i\n                     *\n                     * @return h_{i}\n                     */\n                    FloatType& h(Index i){\n                        assert(i < get_num_spins());\n                        return J(i, i);\n                    }\n\n                    /**\n                     * @brief access h_{i} (local field)\n                     *\n                     * @param i Index i\n                     *\n                     * @return h_{i}\n                     */\n                    const FloatType& h(Index i) const{\n                        assert(i < get_num_spins());\n                        return J(i, i);\n                    }\n\n                    /**\n                     * @brief get interactions (Eigen Matrix)\n                     *\n                     * The returned matrix has the following symmetric form:\n                     *\n                     * \\f[\n                     * \\begin{pmatrix}\n                     * J_{0,0} & J_{0,1} & \\cdots & J_{0,N-1} & h_{0}\\\\\n                     * J_{0,1} & J_{1,1} & \\cdots & J_{1,N-1} & h_{1}\\\\\n                     * \\vdots & \\vdots & \\vdots & \\vdots & \\vdots \\\\\n                     * J_{0,N-1} & J_{N-1,1} & \\cdots & J_{N-1,N-1} & h_{N-1}\\\\\n                     * h_{0} & h_{1} & \\cdots & h_{N-1} & 1 \\\\\n                     * \\end{pmatrix}\n                     * \\f]\n                     *\n                     * @return Eigen Matrix\n                     */\n                    const Interactions get_interactions() const{\n                        return this->_J.template selfadjointView<Eigen::Upper>();\n                    }\n\n            };\n    } // namespace graph \n} // namespace openjij\n\n#endif\n", "meta": {"hexsha": "d66065c2e6a093ab65c7a6e46f19498a4121db7d", "size": 11130, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/graph/dense.hpp", "max_stars_repo_name": "OpenJij/OpenJij", "max_stars_repo_head_hexsha": "9ed58500ef47583bc472410d470bb2dd4bfec74a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2019-01-05T13:37:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T02:11:08.000Z", "max_issues_repo_path": "src/graph/dense.hpp", "max_issues_repo_name": "OpenJij/OpenJij", "max_issues_repo_head_hexsha": "9ed58500ef47583bc472410d470bb2dd4bfec74a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2019-01-29T09:55:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T04:06:20.000Z", "max_forks_repo_path": "src/graph/dense.hpp", "max_forks_repo_name": "OpenJij/OpenJij", "max_forks_repo_head_hexsha": "9ed58500ef47583bc472410d470bb2dd4bfec74a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T07:55:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T14:27:23.000Z", "avg_line_length": 38.9160839161, "max_line_length": 123, "alphanum_fraction": 0.3907457323, "num_tokens": 2126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.44887300337396163}}
{"text": "// Copyright (C) 2016 Kasper Kristensen\n// License: GPL-2\n\n#ifndef TINY_AD_H\n#define TINY_AD_H\n\n/* Standalone ? */\n#ifndef R_RCONFIG_H\n#include <cmath>\n#include <iostream>\n#define CSKIP(x) x\n#endif\n\n/* Select the vector class to use (Default: tiny_vec) */\n#if defined(TINY_AD_USE_STD_VALARRAY)\n#include \"tiny_valarray.hpp\"\n#define TINY_VECTOR(type,size) tiny_vector<type, size>\n#elif defined(TINY_AD_USE_EIGEN_VEC)\n#include <Eigen/Dense>\n#define TINY_VECTOR(type,size) Eigen::Array<type, size, 1>\n#else\n#include \"tiny_vec.hpp\"\n#define TINY_VECTOR(type,size) tiny_vec<type, size>\n#endif\n\nnamespace tiny_ad {\n  template<class Type, class Vector>\n  struct ad {\n    Type value;\n    Vector deriv;\n    ad(){}\n    ad(Type v, Vector d){value = v; deriv = d;}\n    ad(double v)        {value = v; deriv.setZero();}\n    ad operator+ (const ad &other) const{\n      return ad(value + other.value,\n\t\tderiv + other.deriv);\n    }\n    ad operator+ () const{\n      return *this;\n    }\n    ad operator- (const ad &other) const{\n      return ad(value - other.value,\n\t\tderiv - other.deriv);\n    }\n    ad operator- () const{\n      return ad(-value, -deriv);\n    }\n    ad operator* (const ad &other) const{\n      return ad(value * other.value,\n\t\tvalue * other.deriv +\n\t\tderiv * other.value);\n    }\n    ad operator/ (const ad &other) const{\n      Type res = value / other.value;\n      return ad(res,\n\t\t(deriv - res * other.deriv) /\n\t\tother.value );\n    }\n    /* Comparison operators */\n#define COMPARISON_OPERATOR(OP)\t\t\t\\\n    template<class other>\t\t\t\\\n    bool operator OP (const other &x) const{\t\\\n      return (value OP x);\t\t\t\\\n    }\n    COMPARISON_OPERATOR(<)\n    COMPARISON_OPERATOR(>)\n    COMPARISON_OPERATOR(<=)\n    COMPARISON_OPERATOR(>=)\n    COMPARISON_OPERATOR(==)\n    COMPARISON_OPERATOR(!=)\n#undef COMPARISON_OPERATOR\n    /* Combine ad with other types (constants) */\n    ad operator+ (const double &x) const{\n      return ad(value + x, deriv);\n    }\n    ad operator- (const double &x) const{\n      return ad(value - x, deriv);\n    }\n    ad operator* (const double &x) const{\n      return ad(value * x, deriv * x);\n    }\n    ad operator/ (const double &x) const{\n      return ad(value / x, deriv / x);\n    }\n    /* Note: 'this' and 'other' may point to the same object */\n    ad& operator+=(const ad &other){\n      value += other.value;\n      deriv += other.deriv;\n      return *this;\n    }\n    ad& operator-=(const ad &other){\n      value -= other.value;\n      deriv -= other.deriv;\n      return *this;\n    }\n    ad& operator*=(const ad &other){\n      if (this != &other) {\n\tderiv *= other.value;\n\tderiv += other.deriv * value;\n\tvalue *= other.value;\n      } else {\n\tderiv *= value * 2.;\n\tvalue *= value;\n      }\n      return *this;\n    }\n    ad& operator/=(const ad &other){\n      value /= other.value;\n      deriv -= other.deriv * value;\n      deriv /= other.value;\n      return *this;\n    }\n  };\n  /* Binary operators where a constant is first argument */\n  template<class T, class V>\n  ad<T, V> operator+ (const double &x, const ad<T, V> &y) {\n    return y + x;\n  }\n  template<class T, class V>\n  ad<T, V> operator- (const double &x, const ad<T, V> &y) {\n    return -(y - x);\n  }\n  template<class T, class V>\n  ad<T, V> operator* (const double &x, const ad<T, V> &y) {\n    return y * x;\n  }\n  template<class T, class V>\n  ad<T, V> operator/ (const double &x, const ad<T, V> &y) {\n    T value = x / y.value;\n    return ad<T, V>(value, T(-value / y.value) * y.deriv);\n  }\n  /* Unary operators with trivial derivatives */\n#define UNARY_MATH_ZERO_DERIV(F)\t\t\\\n  template<class T, class V>\t\t\t\\\n  double F (const ad<T, V> &x){\t\t\t\\\n    return F(x.value);\t\t\t\t\\\n  }\n  using ::floor; using ::ceil;\n  using ::trunc; using ::round;\n  UNARY_MATH_ZERO_DERIV(floor)\n  UNARY_MATH_ZERO_DERIV(ceil)\n  UNARY_MATH_ZERO_DERIV(trunc)\n  UNARY_MATH_ZERO_DERIV(round)\n  template<class T>\n  double sign(const T &x){return (x > 0) - (x < 0);}\n  bool isfinite(const double &x)CSKIP( {return std::isfinite(x);} )\n  template<class T, class V>\n  bool isfinite(const ad<T, V> &x){return isfinite(x.value);}\n#undef UNARY_MATH_ZERO_DERIV\n  /* Unary operators with non-trivial derivatives */\n#define UNARY_MATH_DERIVATIVE(F,DF)\t\t\\\n  template<class T, class V>\t\t\t\\\n  ad<T, V> F (const ad<T, V> &x){\t\t\\\n    return ad<T, V>(F (x.value),\t\t\\\n\t\t    T(DF(x.value)) * x.deriv);\t\\\n  }\n  using ::exp;  using ::log;\n  using ::sin;  using ::cos;  using ::tan;\n  using ::sinh; using ::cosh; using ::tanh;\n  using ::sqrt; using ::fabs;\n  template<class T> T D_tan(const T &x) {\n    T y = cos(x); return 1. / (y * y);\n  }\n  template<class T> T D_tanh(const T &x) {\n    T y = cosh(x); return 1. / (y * y);\n  }\n  UNARY_MATH_DERIVATIVE(exp, exp)\n  UNARY_MATH_DERIVATIVE(log, 1.0/)\n  UNARY_MATH_DERIVATIVE(sin, cos)\n  UNARY_MATH_DERIVATIVE(cos, -sin)\n  UNARY_MATH_DERIVATIVE(tan, D_tan)\n  UNARY_MATH_DERIVATIVE(sinh, cosh)\n  UNARY_MATH_DERIVATIVE(cosh, sinh)\n  UNARY_MATH_DERIVATIVE(tanh, D_tanh)\n  UNARY_MATH_DERIVATIVE(sqrt, 0.5/sqrt)\n  UNARY_MATH_DERIVATIVE(fabs, sign)\n  using ::expm1; using ::log1p;\n  UNARY_MATH_DERIVATIVE(expm1, exp)\n  template<class T> T D_log1p(const T &x) {return 1. / (x + 1.);}\n  UNARY_MATH_DERIVATIVE(log1p, D_log1p)\n  /* asin, acos, atan */\n  using ::asin; using ::acos; using ::atan;\n  template<class T> T D_asin(const T &x) {\n    return 1. / sqrt(1. - x * x);\n  }\n  template<class T> T D_acos(const T &x) {\n    return -1. / sqrt(1. - x * x);\n  }\n  template<class T> T D_atan(const T &x) {\n    return 1. / (1. + x * x);\n  }\n  UNARY_MATH_DERIVATIVE(asin, D_asin)\n  UNARY_MATH_DERIVATIVE(acos, D_acos)\n  UNARY_MATH_DERIVATIVE(atan, D_atan)\n#undef UNARY_MATH_DERIVATIVE\n  /* A few more ... */\n  template<class T, class V>\n  ad<T, V> pow (const ad<T, V> &x, const ad<T, V> &y){\n    return exp(y * log(x));\n  }\n  using ::pow;\n  template<class T, class V>\n  ad<T, V> pow (const ad<T, V> &x, const double &y){\n    return ad<T, V> (pow(x.value, y), // Note: x.value could be 0\n\t\t     T( y * pow(x.value, y - 1.) ) * x.deriv);\n  }\n  /* Comparison operators where a constant is first argument */\n#define COMPARISON_OPERATOR_FLIP(OP1, OP2)\t\t\t\\\n  template<class T, class V>\t\t\t\t\t\\\n  bool operator OP1 (const double &x, const ad<T, V> &y) {\t\\\n    return y OP2 x;\t\t\t\t\t\t\\\n  }\n  COMPARISON_OPERATOR_FLIP(<,>)\n  COMPARISON_OPERATOR_FLIP(<=,>=)\n  COMPARISON_OPERATOR_FLIP(>,<)\n  COMPARISON_OPERATOR_FLIP(>=,<=)\n  COMPARISON_OPERATOR_FLIP(==,==)\n  COMPARISON_OPERATOR_FLIP(!=,!=)\n#undef COMPARISON_OPERATOR_FLIP\n  /* Utility: Return the value of a tiny_ad type */\n  double asDouble(double x) CSKIP( {return x;} )\n  template<class T, class V>\n  double asDouble (const ad<T, V> &x){\n    return asDouble(x.value);\n  }\n  /* Utility: Return the max absolute value of all members of a\n     tiny_ad type */\n  double max_fabs(double x) CSKIP( {return fabs(x);} )\n  template<class T, class V>\n  double max_fabs (const ad<T, V> &x){\n    double ans = max_fabs(x.value);\n    for(int i=0; i<x.deriv.size(); i++) {\n      double tmp = max_fabs(x.deriv[i]);\n      ans = (tmp > ans ? tmp : ans);\n    }\n    return ans;\n  }\n  /* R-specific derivatives (rely on Rmath)*/\n#ifdef R_RCONFIG_H\n  extern \"C\" {\n    /* See 'R-API: entry points to C-code' (Writing R-extensions) */\n    double\tRf_lgammafn(double);\n    double\tRf_psigamma(double, double);\n  }\n  template<int deriv>\n  double lgamma(const double &x) {\n    return Rf_psigamma(x, deriv-1);\n  }\n  template<>\n  double lgamma<0>(const double &x) CSKIP( {return Rf_lgammafn(x);} )\n  double lgamma(const double &x) CSKIP( {return lgamma<0>(x);} )\n  template<int deriv, class T, class V>\n  ad<T, V> lgamma (const ad<T, V> &x){\n    return ad<T, V> (lgamma< deriv >(x.value),\n\t\t     T(lgamma< deriv + 1 >(x.value)) * x.deriv);\n  }\n  template<class T, class V>\n  ad<T, V> lgamma (const ad<T, V> &x){\n    return lgamma<0>(x);\n  }\n#endif\n  /* Print method */\n  template<class T, class V>\n  std::ostream &operator<<(std::ostream &os, const ad<T, V> &x) {\n    os << \"{\";\n    os << \" value=\" << x.value;\n    os << \" deriv=\" << x.deriv;\n    os << \"}\";\n    return os;\n  }\n\n  /* Interface to higher order derivatives. Example:\n\n     typedef tiny_ad::variable<3, 2> Float; // Track 3rd order derivs wrt. 2 parameters\n     Float a (1.23, 0);                     // Let a = 1.23 have parameter index 0\n     Float b (2.34, 1);                     // Let b = 2.34 have parameter index 1\n     Float y = sin(a + b);                  // Run the algorithm\n     y.getDeriv();                          // Get all 3rd order derivatives\n  */\n#define VARIABLE(order, nvar, scalartype) variable<order, nvar, scalartype>\n  template<int order, int nvar, class Double=double>\n  struct variable : ad< VARIABLE(order-1, nvar, Double),\n\t\t\tTINY_VECTOR( VARIABLE(order-1, nvar, Double) , nvar) > {\n    typedef ad< VARIABLE(order-1, nvar, Double),\n\t\tTINY_VECTOR(VARIABLE(order-1, nvar, Double), nvar) > Base;\n    typedef variable<order-1, nvar, Double> Type;\n    static const int result_size = nvar * Type::result_size;\n#define ___COMMON_CTORS___                      \\\n    variable() {}                               \\\n    variable(Base x) : Base(x) {}               \\\n    variable(double x) : Base(x) {}             \\\n    variable(double x, int id) : Base(x) {      \\\n      setid(id);                                \\\n    }                                           \\\n    template<int T1, int T2, class T3>          \\\n    variable(variable<T1,T2,T3> x) {            \\\n      Base::value = x; Base::deriv.setZero();   \\\n    }                                           \\\n    template<class T1, class T2>                \\\n    variable(ad<T1,T2> x) {                     \\\n      Base::value = x; Base::deriv.setZero();   \\\n    }                                           \\\n    template<int T1, int T2, class T3>          \\\n    variable(variable<T1,T2,T3> x, int id) {    \\\n      Base::value = x; Base::deriv.setZero();   \\\n      setid(id);                                \\\n    }                                           \\\n    template<class T1, class T2>                \\\n    variable(ad<T1,T2> x, int id) {             \\\n      Base::value = x; Base::deriv.setZero();   \\\n      setid(id);                                \\\n    }\n    ___COMMON_CTORS___\n    void setid(int i0, int count = 0){\n      this->value.setid(i0, count);\n      this->deriv[i0].setid(i0, count + 1);\n    }\n    TINY_VECTOR(Double, result_size) getDeriv(){\n      TINY_VECTOR(Double, result_size) ans;\n      int stride = result_size / nvar;\n      for(int i=0; i<nvar; i++)\n\tans.segment(i * stride, stride) = this->deriv[i].getDeriv();\n      return ans;\n    }\n  };\n#undef VARIABLE\n  template<int nvar, class Double>\n  struct variable<1, nvar, Double> : ad<Double, TINY_VECTOR(Double,nvar) >{\n    typedef ad<Double, TINY_VECTOR(Double,nvar) > Base;\n    static const int result_size = nvar;\n    ___COMMON_CTORS___\n    void setid(int i0, int count = 0){\n      if(count == 0)\n\tthis->deriv[i0] = 1.0;\n      if(count == 1)\n\tthis->value = 1.0;\n    }\n    TINY_VECTOR(Double, nvar) getDeriv(){\n      return this->deriv;\n    }\n  };\n#undef ___COMMON_CTORS___\n#undef TINY_VECTOR\n} // End namespace tiny_ad\n\n#endif\n", "meta": {"hexsha": "83fa9542ef2abd5f5918213484762dd2a67ebef1", "size": 11107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "renv/library/R-4.1/x86_64-w64-mingw32/TMB/include/tiny_ad/tiny_ad/tiny_ad.hpp", "max_stars_repo_name": "rebeccagb/gtsummary", "max_stars_repo_head_hexsha": "04996e385acab0b76a9938378e8af87526117aef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "renv/library/R-4.1/x86_64-w64-mingw32/TMB/include/tiny_ad/tiny_ad/tiny_ad.hpp", "max_issues_repo_name": "rebeccagb/gtsummary", "max_issues_repo_head_hexsha": "04996e385acab0b76a9938378e8af87526117aef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "renv/library/R-4.1/x86_64-w64-mingw32/TMB/include/tiny_ad/tiny_ad/tiny_ad.hpp", "max_forks_repo_name": "rebeccagb/gtsummary", "max_forks_repo_head_hexsha": "04996e385acab0b76a9938378e8af87526117aef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0086455331, "max_line_length": 87, "alphanum_fraction": 0.5867470964, "num_tokens": 3358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.44882745210289016}}
{"text": "/**\n * @file BooleanOperation.hpp\n * @author bwu\n * @brief Boolean operation for geometries\n * @version 0.1\n * @date 2022-02-22\n */\n#ifndef GENERIC_GEOMETRY_BOOLEANOPERATION_HPP\n#define GENERIC_GEOMETRY_BOOLEANOPERATION_HPP\n#include \"BoostPolygonRegister.hpp\"\n#include \"GeometryTraits.hpp\"\n#include <boost/polygon/polygon_set_traits.hpp>\n#include <boost/polygon/polygon_set_data.hpp>\nnamespace generic  {\nnamespace geometry {\n///@brief boolean operations of geometry\nnamespace boolean  {\n\ntemplate <typename num_type>\nusing PolygonSet2D = boost::polygon::polygon_set_data<num_type>;\n\n/**\n * @brief Boolean OR (polygon set union) operation of two geometries\n * @param[in] g1 one of the input geometries, could be one of Triangle2D, Box2D, Polygon2D, PolygonWithHoles2D\n * @param[in] g2 one of the input geometries, could be one of Triangle2D, Box2D, Polygon2D, PolygonWithHoles2D\n * @param[out] results stl container with Polygon2D that hold the union result of two geometries\n */\ntemplate <typename geometry_t1, typename geometry_t2, \n          template <typename, typename> class container, \n          template <typename> class allocator = std::allocator,\n          typename std::enable_if<traits::is_2d_surf_geom_t<geometry_t1>::value &&\n                                  traits::is_2d_surf_geom_t<geometry_t2>::value, bool>::type = true>\ninline void Unite(const geometry_t1 & g1, const geometry_t2 & g2, container<polygon_type<geometry_t1>, allocator<polygon_type<geometry_t1> > > & results)\n{\n    using namespace boost::polygon::operators;\n    PolygonSet2D<typename geometry_t1::coor_t> polygonSet;    \n    polygonSet += g1;\n    polygonSet += g2;\n    results.clear();\n    polygonSet.get(results);\n}\n\n/**\n * @brief Boolean OR (polygon set union) operation of a collection of geometries\n * @param[in] begin iterator to the beginning of the geometry collection\n * @param[in] end iterator to the ending of the geometry collection\n * @param[out] results stl container with Polygon2D that hold the union result of the collection of geometries\n */\ntemplate <typename iterator, \n          template <typename, typename> class container,\n          template <typename> class allocator = std::allocator,\n          typename std::enable_if<traits::is_2d_surf_geom_t<\n          typename std::iterator_traits<iterator>::value_type>::value, bool>::type = true>\ninline void Unite(iterator begin, iterator end,\n                  container<polygon_type<typename std::iterator_traits<iterator>::value_type>,\n                  allocator<polygon_type<typename std::iterator_traits<iterator>::value_type> > > & results)\n{\n    using namespace boost::polygon::operators;\n    using coor_t = typename std::iterator_traits<iterator>::value_type::coor_t;\n    PolygonSet2D<coor_t> polygonSet;\n    for(auto iter = begin; iter != end; ++iter) \n        polygonSet += *iter;\n    results.clear();\n    polygonSet.get(results);\n}\n\n/**\n * @brief Boolean AND (polygon set intersection) operation of a two geometries\n * @param[in] g1 one of the input geometries, could be one of Triangle2D, Box2D, Polygon2D, PolygonWithHoles2D\n * @param[in] g2 one of the input geometries, could be one of Triangle2D, Box2D, Polygon2D, PolygonWithHoles2D\n * @param[out] results stl container with Polygon2D that hold the intersection result of two geometries\n */\ntemplate <typename geometry_t1, typename geometry_t2, \n          template <typename, typename> class container, \n          template <typename> class allocator = std::allocator,\n          typename std::enable_if<traits::is_2d_surf_geom_t<geometry_t1>::value &&\n                                  traits::is_2d_surf_geom_t<geometry_t2>::value, bool>::type = true>\ninline void Intersect(const geometry_t1 & g1, const geometry_t2 & g2, container<polygon_type<geometry_t1>, allocator<polygon_type<geometry_t1> > > & results)\n{\n    using namespace boost::polygon::operators;\n    PolygonSet2D<typename geometry_t1::coor_t> polygonSet;    \n    polygonSet += g1;\n    polygonSet &= g2;\n    results.clear();\n    polygonSet.get(results);\n}\n\n/**\n * @brief Boolean AND (polygon set intersection) operation of two geometry sets\n * @param[in] begin1 iterator to the beginning of the geometry collection one\n * @param[in] end1 iterator to the ending of the geometry collection one\n * @param[in] begin2 iterator to the beginning of the geometry collection two\n * @param[in] end2 iterator to the ending of the geometry collection two\n * @param[out] results stl container with Polygon2D that hold the intersection result of two geometry sets\n */\ntemplate <typename iterator1, typename iterator2,\n          template <typename, typename> class container,\n          template <typename> class allocator = std::allocator,\n          typename std::enable_if<traits::is_2d_surf_geom_t<typename std::iterator_traits<iterator1>::value_type>::value &&\n                                  traits::is_2d_surf_geom_t<typename std::iterator_traits<iterator2>::value_type>::value, bool>::type = true>\ninline void Intersect(iterator1 begin1, iterator1 end1, iterator2 begin2, iterator2 end2,\n                      container<polygon_type<typename std::iterator_traits<iterator1>::value_type>,\n                      allocator<polygon_type<typename std::iterator_traits<iterator1>::value_type> > > & results)\n{\n    using namespace boost::polygon::operators;\n    using coor_t = typename std::iterator_traits<iterator1>::value_type::coor_t;\n    PolygonSet2D<coor_t> polygonSet1, polygonSet2;\n    for(auto iter1 = begin1; iter1 != end1; ++iter1) \n        polygonSet1 += *iter1;\n    for(auto iter2 = begin2; iter2 != end2; ++iter2)\n        polygonSet2 += *iter2;\n    polygonSet1 *= polygonSet2;\n    results.clear();\n    polygonSet1.get(results);\n}\n\n/**\n * @brief Boolean SUBTRACT operation (polygon set difference) of two geometries\n * @param[in] g1 one of the input geometries, could be one of Triangle2D, Box2D, Polygon2D, PolygonWithHoles2D\n * @param[in] g2 one of the input geometries, could be one of Triangle2D, Box2D, Polygon2D, PolygonWithHoles2D\n * @param[out] results stl container with Polygon2D that hold the difference result of two geometries\n */\ntemplate <typename geometry_t1, typename geometry_t2, \n          template <typename, typename> class container, \n          template <typename> class allocator = std::allocator,\n          typename std::enable_if<traits::is_2d_surf_geom_t<geometry_t1>::value &&\n                                  traits::is_2d_surf_geom_t<geometry_t2>::value, bool>::type = true>\ninline void Subtract(const geometry_t1 & g1, const geometry_t2 & g2, container<polygon_type<geometry_t1>, allocator<polygon_type<geometry_t1> > > & results)\n{\n    using namespace boost::polygon::operators;\n    PolygonSet2D<typename geometry_t1::coor_t> polygonSet;    \n    polygonSet += g1;\n    polygonSet -= g2;\n    results.clear();\n    polygonSet.get(results);\n}\n\n/**\n * @brief Boolean SUBTRACT operation (polygon set difference) of two geometry sets\n * @param[in] begin1 iterator to the beginning of the geometry collection one\n * @param[in] end1 iterator to the ending of the geometry collection one\n * @param[in] begin2 iterator to the beginning of the geometry collection two\n * @param[in] end2 iterator to the ending of the geometry collection two\n * @param[out] results stl container with Polygon2D that hold the difference result of two geometry sets\n */\ntemplate <typename iterator1, typename iterator2,\n          template <typename, typename> class container,\n          template <typename> class allocator = std::allocator,\n          typename std::enable_if<traits::is_2d_surf_geom_t<typename std::iterator_traits<iterator1>::value_type>::value &&\n                                  traits::is_2d_surf_geom_t<typename std::iterator_traits<iterator2>::value_type>::value, bool>::type = true>\ninline void Subtract(iterator1 begin1, iterator1 end1, iterator2 begin2, iterator2 end2,\n                     container<polygon_type<typename std::iterator_traits<iterator1>::value_type>,\n                     allocator<polygon_type<typename std::iterator_traits<iterator1>::value_type> > > & results)\n{\n    using namespace boost::polygon::operators;\n    using coor_t = typename std::iterator_traits<iterator1>::value_type::coor_t;\n    PolygonSet2D<coor_t> polygonSet;\n    for(auto iter = begin1; iter != end1; ++iter) \n        polygonSet += *iter;\n    for(auto iter = begin2; iter != end2; ++iter)\n        polygonSet -= *iter;\n    results.clear();\n    polygonSet.get(results);\n}\n\n/**\n * @brief Boolean XOR operation (polygon set disjoint-union) of two geometries\n * @param[in] g1 one of the input geometries, could be one of Triangle2D, Box2D, Polygon2D, PolygonWithHoles2D\n * @param[in] g2 one of the input geometries, could be one of Triangle2D, Box2D, Polygon2D, PolygonWithHoles2D\n * @param[out] results stl container with Polygon2D that hold the disjoint-union result of two geometries\n */\ntemplate <typename geometry_t1, typename geometry_t2, \n          template <typename, typename> class container, \n          template <typename> class allocator = std::allocator,\n          typename std::enable_if<traits::is_2d_surf_geom_t<geometry_t1>::value &&\n                                  traits::is_2d_surf_geom_t<geometry_t2>::value, bool>::type = true>\ninline void Xor(const geometry_t1 & g1, const geometry_t2 & g2, container<polygon_type<geometry_t1>, allocator<polygon_type<geometry_t1> > > & results)\n{\n    using namespace boost::polygon::operators;\n    PolygonSet2D<typename geometry_t1::coor_t> polygonSet;    \n    polygonSet += g1;\n    polygonSet ^= g2;\n    results.clear();\n    polygonSet.get(results);\n}\n\n/**\n * @brief Boolean XOR operation (polygon set disjoint-union) of two geometry sets\n * @param[in] begin1 iterator to the beginning of the geometry collection one\n * @param[in] end1 iterator to the ending of the geometry collection one\n * @param[in] begin2 iterator to the beginning of the geometry collection two\n * @param[in] end2 iterator to the ending of the geometry collection two\n * @param[out] results stl container with Polygon2D that hold the disjoint-union result of two geometry sets\n */\ntemplate <typename iterator1, typename iterator2,\n          template <typename, typename> class container,\n          template <typename> class allocator = std::allocator,\n          typename std::enable_if<traits::is_2d_surf_geom_t<typename std::iterator_traits<iterator1>::value_type>::value &&\n                                  traits::is_2d_surf_geom_t<typename std::iterator_traits<iterator2>::value_type>::value, bool>::type = true>\ninline void Xor(iterator1 begin1, iterator1 end1, iterator2 begin2, iterator2 end2,\n                container<polygon_type<typename std::iterator_traits<iterator1>::value_type>,\n                allocator<polygon_type<typename std::iterator_traits<iterator1>::value_type> > > & results)\n{\n    using namespace boost::polygon::operators;\n    using coor_t = typename std::iterator_traits<iterator1>::value_type::coor_t;\n    PolygonSet2D<coor_t> polygonSet1, polygonSet2;\n    for(auto iter1 = begin1; iter1 != end1; ++iter1) \n        polygonSet1 += *iter1;\n    for(auto iter2 = begin2; iter2 != end2; ++iter2)\n        polygonSet2 += *iter2;\n    polygonSet1 ^= polygonSet2;\n    results.clear();\n    polygonSet1.get(results);\n}\n\n} //namespace boolean\n} //namespace geometry\n} //namespace generic\n#endif//GENERIC_GEOMETRY_BOOLEANOPERATION_HPP", "meta": {"hexsha": "bfdc33d5383570351f402698a597e0d20ac87938", "size": 11375, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry/BooleanOperation.hpp", "max_stars_repo_name": "Draaaaaaven/generic", "max_stars_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-05T02:34:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:51:50.000Z", "max_issues_repo_path": "geometry/BooleanOperation.hpp", "max_issues_repo_name": "Draaaaaaven/generic", "max_issues_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry/BooleanOperation.hpp", "max_forks_repo_name": "Draaaaaaven/generic", "max_forks_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.9406392694, "max_line_length": 157, "alphanum_fraction": 0.7163076923, "num_tokens": 2758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4488274449900026}}
{"text": "//  (C) Copyright John Maddock 2005.\r\n//  (C) Copyright Henry S. Warren 2005.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_TR1_RANDOM_HPP_INCLUDED\r\n#  define BOOST_TR1_RANDOM_HPP_INCLUDED\r\n#  include <boost/tr1/detail/config.hpp>\r\n\r\n#ifdef BOOST_HAS_TR1_RANDOM\r\n#  if defined(BOOST_HAS_INCLUDE_NEXT) && !defined(BOOST_TR1_DISABLE_INCLUDE_NEXT)\r\n#     include_next BOOST_TR1_HEADER(random)\r\n#  else\r\n#     include <boost/tr1/detail/config_all.hpp>\r\n#     include BOOST_TR1_STD_HEADER(BOOST_TR1_PATH(random))\r\n#  endif\r\n#else\r\n// Boost.Random:\r\n#include <boost/random.hpp>\r\n#ifndef __SUNPRO_CC\r\n    // Sunpros linker complains if we so much as include this...\r\n#   include <boost/nondet_random.hpp>\r\n#endif\r\n#include <boost/tr1/detail/functor2iterator.hpp>\r\n#include <boost/type_traits/is_fundamental.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n\r\nnamespace std { namespace tr1{\r\n\r\nusing ::boost::variate_generator;\r\n\r\ntemplate<class UIntType, UIntType a, UIntType c, UIntType m>\r\nclass linear_congruential\r\n{\r\nprivate:\r\n   typedef ::boost::random::linear_congruential<UIntType, a, c, m, 0> impl_type;\r\npublic:\r\n   // types\r\n   typedef UIntType result_type;\r\n   // parameter values\r\n   BOOST_STATIC_CONSTANT(UIntType, multiplier = a);\r\n   BOOST_STATIC_CONSTANT(UIntType, increment = c);\r\n   BOOST_STATIC_CONSTANT(UIntType, modulus = m);\r\n   // constructors and member function\r\n   explicit linear_congruential(unsigned long x0 = 1)\r\n      : m_gen(x0){}\r\n   linear_congruential(const linear_congruential& that)\r\n      : m_gen(that.m_gen){}\r\n   template<class Gen> linear_congruential(Gen& g)\r\n   {\r\n      init1(g, ::boost::is_same<Gen,linear_congruential>());\r\n   }\r\n   void seed(unsigned long x0 = 1)\r\n   { m_gen.seed(x0); }\r\n   template<class Gen> void seed(Gen& g)\r\n   { \r\n      init2(g, ::boost::is_fundamental<Gen>());\r\n   }\r\n   result_type min BOOST_PREVENT_MACRO_SUBSTITUTION() const\r\n   { return (m_gen.min)(); }\r\n   result_type max BOOST_PREVENT_MACRO_SUBSTITUTION() const\r\n   { return (m_gen.max)(); }\r\n   result_type operator()()\r\n   {\r\n      return m_gen(); \r\n   }\r\n   bool operator==(const linear_congruential& that)const\r\n   { return m_gen == that.m_gen; }\r\n   bool operator!=(const linear_congruential& that)const\r\n   { return m_gen != that.m_gen; }\r\n\r\n#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))\r\n  template<class CharT, class Traits>\r\n  friend std::basic_ostream<CharT,Traits>&\r\n  operator<<(std::basic_ostream<CharT,Traits>& os,\r\n             const linear_congruential& lcg)\r\n  {\r\n    return os << lcg.m_gen; \r\n  }\r\n\r\n  template<class CharT, class Traits>\r\n  friend std::basic_istream<CharT,Traits>&\r\n  operator>>(std::basic_istream<CharT,Traits>& is,\r\n             linear_congruential& lcg)\r\n  {\r\n    return is >> lcg.m_gen;\r\n  }\r\n#endif\r\n\r\nprivate:\r\n   template <class Gen>\r\n   void init1(Gen& g, const ::boost::true_type&)\r\n   {\r\n      m_gen = g.m_gen;\r\n   }\r\n   template <class Gen>\r\n   void init1(Gen& g, const ::boost::false_type&)\r\n   {\r\n      init2(g, ::boost::is_fundamental<Gen>());\r\n   }\r\n   template <class Gen>\r\n   void init2(Gen& g, const ::boost::true_type&)\r\n   {\r\n      m_gen.seed(static_cast<unsigned long>(g));\r\n   }\r\n   template <class Gen>\r\n   void init2(Gen& g, const ::boost::false_type&)\r\n   {\r\n      //typedef typename Gen::result_type gen_rt;\r\n      boost::tr1_details::functor2iterator<Gen, unsigned long> f1(g), f2;\r\n      m_gen.seed(f1, f2);\r\n   }\r\n   impl_type m_gen;\r\n};\r\n\r\ntemplate<class UIntType, int w, int n, int m, int r,\r\nUIntType a, int u, int s, UIntType b, int t, UIntType c, int l>\r\nclass mersenne_twister\r\n{\r\n   typedef ::boost::random::mersenne_twister\r\n      <UIntType, w, n, m, r, a, u, s, b, t, c, l, 0> imp_type;\r\npublic:\r\n   // types\r\n   typedef UIntType result_type;\r\n   // parameter values\r\n   BOOST_STATIC_CONSTANT(int, word_size = w);\r\n   BOOST_STATIC_CONSTANT(int, state_size = n);\r\n   BOOST_STATIC_CONSTANT(int, shift_size = m);\r\n   BOOST_STATIC_CONSTANT(int, mask_bits = r);\r\n   BOOST_STATIC_CONSTANT(UIntType, parameter_a = a);\r\n   BOOST_STATIC_CONSTANT(int, output_u = u);\r\n   BOOST_STATIC_CONSTANT(int, output_s = s);\r\n   BOOST_STATIC_CONSTANT(UIntType, output_b = b);\r\n   BOOST_STATIC_CONSTANT(int, output_t = t);\r\n   BOOST_STATIC_CONSTANT(UIntType, output_c = c);\r\n   BOOST_STATIC_CONSTANT(int, output_l = l);\r\n   // constructors and member function\r\n   mersenne_twister(){}\r\n   explicit mersenne_twister(unsigned long value)\r\n      : m_gen(value == 0 ? 5489UL : value){}\r\n   template<class Gen> mersenne_twister(Gen& g)\r\n   {\r\n      init1(g, ::boost::is_same<mersenne_twister,Gen>());\r\n   }\r\n   void seed()\r\n   { m_gen.seed(); }\r\n   void seed(unsigned long value)\r\n   { m_gen.seed(value == 0 ? 5489UL : value); }\r\n   template<class Gen> void seed(Gen& g)\r\n   { init2(g, ::boost::is_fundamental<Gen>()); }\r\n   result_type min BOOST_PREVENT_MACRO_SUBSTITUTION() const\r\n   { return (m_gen.min)(); }\r\n   result_type max BOOST_PREVENT_MACRO_SUBSTITUTION() const\r\n   { return (m_gen.max)(); }\r\n   result_type operator()()\r\n   { return m_gen(); }\r\n   bool operator==(const mersenne_twister& that)const\r\n   { return m_gen == that.m_gen; }\r\n   bool operator!=(const mersenne_twister& that)const\r\n   { return m_gen != that.m_gen; }\r\n\r\n#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))\r\n   template<class CharT, class Traits>\r\n   friend std::basic_ostream<CharT,Traits>&\r\n   operator<<(std::basic_ostream<CharT,Traits>& os,\r\n            const mersenne_twister& lcg)\r\n   {\r\n      return os << lcg.m_gen;\r\n   }\r\n\r\n   template<class CharT, class Traits>\r\n   friend std::basic_istream<CharT,Traits>&\r\n   operator>>(std::basic_istream<CharT,Traits>& is,\r\n            mersenne_twister& lcg)\r\n   {\r\n      return is >> lcg.m_gen;\r\n   }\r\n#endif\r\nprivate:\r\n   template <class Gen>\r\n   void init1(Gen& g, const ::boost::true_type&)\r\n   {\r\n      m_gen = g.m_gen;\r\n   }\r\n   template <class Gen>\r\n   void init1(Gen& g, const ::boost::false_type&)\r\n   {\r\n      init2(g, ::boost::is_fundamental<Gen>());\r\n   }\r\n   template <class Gen>\r\n   void init2(Gen& g, const ::boost::true_type&)\r\n   {\r\n      m_gen.seed(static_cast<unsigned long>(g == 0 ? 4357UL : g));\r\n   }\r\n   template <class Gen>\r\n   void init2(Gen& g, const ::boost::false_type&)\r\n   {\r\n      m_gen.seed(g);\r\n   }\r\n   imp_type m_gen;\r\n};\r\n\r\ntemplate<class IntType, IntType m, int s, int r>\r\nclass subtract_with_carry\r\n{\r\npublic:\r\n   // types\r\n   typedef IntType result_type;\r\n   // parameter values\r\n   BOOST_STATIC_CONSTANT(IntType, modulus = m);\r\n   BOOST_STATIC_CONSTANT(int, long_lag = r);\r\n   BOOST_STATIC_CONSTANT(int, short_lag = s);\r\n\r\n   // constructors and member function\r\n   subtract_with_carry(){}\r\n   explicit subtract_with_carry(unsigned long value)\r\n      : m_gen(value == 0 ? 19780503UL : value){}\r\n   template<class Gen> subtract_with_carry(Gen& g)\r\n   { init1(g, ::boost::is_same<Gen, subtract_with_carry<IntType, m, s, r> >()); }\r\n   void seed(unsigned long value = 19780503ul)\r\n   { m_gen.seed(value == 0 ? 19780503UL : value); }\r\n   template<class Gen> void seed(Gen& g)\r\n   { init2(g, ::boost::is_fundamental<Gen>()); }\r\n   result_type min BOOST_PREVENT_MACRO_SUBSTITUTION() const\r\n   { return (m_gen.min)(); }\r\n   result_type max BOOST_PREVENT_MACRO_SUBSTITUTION() const\r\n   { return (m_gen.max)(); }\r\n   result_type operator()()\r\n   { return m_gen(); }\r\n   bool operator==(const subtract_with_carry& that)const\r\n   { return m_gen == that.m_gen; }\r\n   bool operator!=(const subtract_with_carry& that)const\r\n   { return m_gen != that.m_gen; }\r\n\r\n#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))\r\n   template<class CharT, class Traits>\r\n   friend std::basic_ostream<CharT,Traits>&\r\n   operator<<(std::basic_ostream<CharT,Traits>& os,\r\n            const subtract_with_carry& lcg)\r\n   {\r\n      return os << lcg.m_gen;\r\n   }\r\n\r\n   template<class CharT, class Traits>\r\n   friend std::basic_istream<CharT,Traits>&\r\n   operator>>(std::basic_istream<CharT,Traits>& is,\r\n            subtract_with_carry& lcg)\r\n   {\r\n      return is >> lcg.m_gen;\r\n   }\r\n#endif\r\nprivate:\r\n   template <class Gen>\r\n   void init1(Gen& g, const ::boost::true_type&)\r\n   {\r\n      m_gen = g.m_gen;\r\n   }\r\n   template <class Gen>\r\n   void init1(Gen& g, const ::boost::false_type&)\r\n   {\r\n      init2(g, ::boost::is_fundamental<Gen>());\r\n   }\r\n   template <class Gen>\r\n   void init2(Gen& g, const ::boost::true_type&)\r\n   {\r\n      m_gen.seed(static_cast<unsigned long>(g == 0 ? 19780503UL : g));\r\n   }\r\n   template <class Gen>\r\n   void init2(Gen& g, const ::boost::false_type&)\r\n   {\r\n      m_gen.seed(g);\r\n   }\r\n   ::boost::random::subtract_with_carry<IntType, m, s, r, 0> m_gen;\r\n};\r\n\r\ntemplate<class RealType, int w, int s, int r>\r\nclass subtract_with_carry_01\r\n{\r\npublic:\r\n   // types\r\n   typedef RealType result_type;\r\n   // parameter values\r\n   BOOST_STATIC_CONSTANT(int, word_size = w);\r\n   BOOST_STATIC_CONSTANT(int, long_lag = r);\r\n   BOOST_STATIC_CONSTANT(int, short_lag = s);\r\n\r\n   // constructors and member function\r\n   subtract_with_carry_01(){}\r\n   explicit subtract_with_carry_01(unsigned long value)\r\n      : m_gen(value == 0 ? 19780503UL : value){}\r\n   template<class Gen> subtract_with_carry_01(Gen& g)\r\n   { init1(g, ::boost::is_same<Gen, subtract_with_carry_01<RealType, w, s, r> >()); }\r\n   void seed(unsigned long value = 19780503UL)\r\n   { m_gen.seed(value == 0 ? 19780503UL : value); }\r\n   template<class Gen> void seed(Gen& g)\r\n   { init2(g, ::boost::is_fundamental<Gen>()); }\r\n   result_type min BOOST_PREVENT_MACRO_SUBSTITUTION() const\r\n   { return (m_gen.min)(); }\r\n   result_type max BOOST_PREVENT_MACRO_SUBSTITUTION() const\r\n   { return (m_gen.max)(); }\r\n   result_type operator()()\r\n   { return m_gen(); }\r\n   bool operator==(const subtract_with_carry_01& that)const\r\n   { return m_gen == that.m_gen; }\r\n   bool operator!=(const subtract_with_carry_01& that)const\r\n   { return m_gen != that.m_gen; }\r\n\r\n#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))\r\n   template<class CharT, class Traits>\r\n   friend std::basic_ostream<CharT,Traits>&\r\n   operator<<(std::basic_ostream<CharT,Traits>& os,\r\n            const subtract_with_carry_01& lcg)\r\n   {\r\n      return os << lcg.m_gen;\r\n   }\r\n\r\n   template<class CharT, class Traits>\r\n   friend std::basic_istream<CharT,Traits>&\r\n   operator>>(std::basic_istream<CharT,Traits>& is,\r\n            subtract_with_carry_01& lcg)\r\n   {\r\n      return is >> lcg.m_gen;\r\n   }\r\n#endif\r\nprivate:\r\n   template <class Gen>\r\n   void init1(Gen& g, const ::boost::true_type&)\r\n   {\r\n      m_gen = g.m_gen;\r\n   }\r\n   template <class Gen>\r\n   void init1(Gen& g, const ::boost::false_type&)\r\n   {\r\n      init2(g, ::boost::is_fundamental<Gen>());\r\n   }\r\n   template <class Gen>\r\n   void init2(Gen& g, const ::boost::true_type&)\r\n   {\r\n      m_gen.seed(static_cast<unsigned long>(g == 0 ? 19780503UL : g));\r\n   }\r\n   template <class Gen>\r\n   void init2(Gen& g, const ::boost::false_type&)\r\n   {\r\n      //typedef typename Gen::result_type gen_rt;\r\n      boost::tr1_details::functor2iterator<Gen, unsigned long> f1(g), f2;\r\n      m_gen.seed(f1, f2);\r\n   }\r\n   ::boost::random::subtract_with_carry_01<RealType, w, s, r, 0> m_gen;\r\n};\r\n\r\nusing ::boost::random::discard_block;\r\n\r\ntemplate<class UniformRandomNumberGenerator1, int s1, class UniformRandomNumberGenerator2, int s2>\r\nclass xor_combine\r\n{\r\npublic:\r\n   // types\r\n   typedef UniformRandomNumberGenerator1 base1_type;\r\n   typedef UniformRandomNumberGenerator2 base2_type;\r\n   typedef unsigned long result_type;\r\n   // parameter values\r\n   BOOST_STATIC_CONSTANT(int, shift1 = s1);\r\n   BOOST_STATIC_CONSTANT(int, shift2 = s2);\r\n   // constructors and member function\r\n   xor_combine(){ init_minmax(); }\r\n   xor_combine(const base1_type & rng1, const base2_type & rng2)\r\n      : m_b1(rng1), m_b2(rng2) { init_minmax(); }\r\n   xor_combine(unsigned long s)\r\n      : m_b1(s), m_b2(s+1) { init_minmax(); }\r\n   template<class Gen> xor_combine(Gen& g)\r\n   { \r\n      init_minmax(); \r\n      init1(g, ::boost::is_same<Gen, xor_combine<UniformRandomNumberGenerator1, s1, UniformRandomNumberGenerator2, s2> >());\r\n   }\r\n   void seed()\r\n   {\r\n      m_b1.seed();\r\n      m_b2.seed();\r\n   }\r\n   void seed(unsigned long s)\r\n   {\r\n      m_b1.seed(s);\r\n      m_b2.seed(s+1);\r\n   }\r\n   template<class Gen> void seed(Gen& g)\r\n   {\r\n      init2(g, ::boost::is_fundamental<Gen>());\r\n   }\r\n\r\n   const base1_type& base1() const\r\n   { return m_b1; }\r\n   const base2_type& base2() const\r\n   { return m_b2; }\r\n   result_type min BOOST_PREVENT_MACRO_SUBSTITUTION() const\r\n   { return m_min; }\r\n   result_type max BOOST_PREVENT_MACRO_SUBSTITUTION() const\r\n   { return m_max; }\r\n   result_type operator()()\r\n   { return (m_b1() << s1) ^ (m_b2() << s2); }\r\n\r\n   bool operator == (const xor_combine& that)const\r\n   { return (m_b1 == that.m_b1) && (m_b2 == that.m_b2); }\r\n   bool operator != (const xor_combine& that)const\r\n   { return !(*this == that); }\r\n\r\n#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))\r\n   template<class CharT, class Traits>\r\n   friend std::basic_ostream<CharT,Traits>&\r\n   operator<<(std::basic_ostream<CharT,Traits>& os,\r\n            const xor_combine& lcg)\r\n   {\r\n      return os << lcg.m_b1 << \" \" << lcg.m_b2;\r\n   }\r\n\r\n   template<class CharT, class Traits>\r\n   friend std::basic_istream<CharT,Traits>&\r\n   operator>>(std::basic_istream<CharT,Traits>& is,\r\n            xor_combine& lcg)\r\n   {\r\n      return is >> lcg.m_b1 >> lcg.m_b2;\r\n   }\r\n#endif\r\n\r\nprivate:\r\n   void init_minmax();\r\n   base1_type m_b1;\r\n   base2_type m_b2;\r\n   result_type m_min;\r\n   result_type m_max;\r\n\r\n   template <class Gen>\r\n   void init1(Gen& g, const ::boost::true_type&)\r\n   {\r\n      m_b1 = g.m_b1;\r\n      m_b2 = g.m_b2;\r\n   }\r\n   template <class Gen>\r\n   void init1(Gen& g, const ::boost::false_type&)\r\n   {\r\n      init2(g, ::boost::is_fundamental<Gen>());\r\n   }\r\n   template <class Gen>\r\n   void init2(Gen& g, const ::boost::true_type&)\r\n   {\r\n      m_b1.seed(static_cast<unsigned long>(g));\r\n      m_b2.seed(static_cast<unsigned long>(g));\r\n   }\r\n   template <class Gen>\r\n   void init2(Gen& g, const ::boost::false_type&)\r\n   {\r\n      m_b1.seed(g);\r\n      m_b2.seed(g);\r\n   }\r\n};\r\n\r\ntemplate<class UniformRandomNumberGenerator1, int s1, class UniformRandomNumberGenerator2, int s2>\r\nvoid xor_combine<UniformRandomNumberGenerator1, s1, UniformRandomNumberGenerator2, s2>::init_minmax()\r\n{\r\n   //\r\n   // The following code is based on that given in \"Hacker's Delight\"\r\n   // by Henry S. Warren, (Addison-Wesley, 2003), and at \r\n   // http://www.hackersdelight.org/index.htm.\r\n   // Used here by permission.\r\n   //\r\n   // calculation of minimum value:\r\n   //\r\n   result_type a = (m_b1.min)() << s1;\r\n   result_type b = (m_b1.max)() << s1;\r\n   result_type c = (m_b2.min)() << s2;\r\n   result_type d = (m_b2.max)() << s2;\r\n   result_type m, temp;\r\n\r\n   m = 0x1uL << ((sizeof(result_type) * CHAR_BIT) - 1);\r\n   while (m != 0) {\r\n      if (~a & c & m) {\r\n         temp = (a | m) & (static_cast<result_type>(0u) - m);\r\n         if (temp <= b) a = temp;\r\n      }\r\n      else if (a & ~c & m) {\r\n         temp = (c | m) & (static_cast<result_type>(0u) - m);\r\n         if (temp <= d) c = temp;\r\n      }\r\n      m >>= 1;\r\n   }\r\n   m_min = a ^ c;\r\n\r\n   //\r\n   // calculation of maximum value:\r\n   //\r\n   if((((std::numeric_limits<result_type>::max)() >> s1) < (m_b1.max)())\r\n      || ((((std::numeric_limits<result_type>::max)()) >> s2) < (m_b2.max)()))\r\n   {\r\n      m_max = (std::numeric_limits<result_type>::max)();\r\n      return;\r\n   }\r\n   a = (m_b1.min)() << s1;\r\n   b = (m_b1.max)() << s1;\r\n   c = (m_b2.min)() << s2;\r\n   d = (m_b2.max)() << s2;\r\n\r\n   m = 0x1uL << ((sizeof(result_type) * CHAR_BIT) - 1);\r\n\r\n   while (m != 0) {\r\n      if (b & d & m) {\r\n         temp = (b - m) | (m - 1);\r\n         if (temp >= a) b = temp;\r\n         else {\r\n            temp = (d - m) | (m - 1);\r\n            if (temp >= c) d = temp;\r\n         }\r\n      }\r\n      m = m >> 1;\r\n   }\r\n   m_max = b ^ d;\r\n}\r\n\r\ntypedef linear_congruential< ::boost::int32_t, 16807, 0, 2147483647> minstd_rand0;\r\ntypedef linear_congruential< ::boost::int32_t, 48271, 0, 2147483647> minstd_rand;\r\ntypedef mersenne_twister< ::boost::uint32_t, 32,624,397,31,0x9908b0df,11,7,0x9d2c5680,15,0xefc60000,18> mt19937;\r\ntypedef subtract_with_carry_01<float, 24, 10, 24> ranlux_base_01;\r\ntypedef subtract_with_carry_01<double, 48, 10, 24> ranlux64_base_01;\r\ntypedef discard_block<subtract_with_carry< ::boost::int32_t, (1<<24), 10, 24>, 223, 24> ranlux3;\r\ntypedef discard_block<subtract_with_carry< ::boost::int32_t, (1<<24), 10, 24>, 389, 24> ranlux4;\r\ntypedef discard_block<subtract_with_carry_01<float, 24, 10, 24>, 223, 24> ranlux3_01;\r\ntypedef discard_block<subtract_with_carry_01<float, 24, 10, 24>, 389, 24> ranlux4_01;\r\n\r\n#ifndef __SUNPRO_CC\r\nusing ::boost::random_device;\r\n#endif\r\nusing ::boost::uniform_int;\r\n\r\nclass bernoulli_distribution\r\n{\r\npublic:\r\n   // types\r\n   typedef int input_type;\r\n   typedef bool result_type;\r\n   // constructors and member function\r\n   explicit bernoulli_distribution(double p = 0.5)\r\n      : m_dist(p){}\r\n   double p() const\r\n   { return m_dist.p(); }\r\n   void reset()\r\n   { m_dist.reset(); }\r\n   template<class UniformRandomNumberGenerator>\r\n   result_type operator()(UniformRandomNumberGenerator& urng)\r\n   {\r\n      return m_dist(urng);\r\n   }\r\n#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))\r\n   template<class CharT, class Traits>\r\n   friend std::basic_ostream<CharT,Traits>&\r\n   operator<<(std::basic_ostream<CharT,Traits>& os,\r\n            const bernoulli_distribution& lcg)\r\n   {\r\n      return os << lcg.m_dist;\r\n   }\r\n\r\n   template<class CharT, class Traits>\r\n   friend std::basic_istream<CharT,Traits>&\r\n   operator>>(std::basic_istream<CharT,Traits>& is,\r\n            bernoulli_distribution& lcg)\r\n   {\r\n      return is >> lcg.m_dist;\r\n   }\r\n#endif\r\n\r\nprivate:\r\n   ::boost::bernoulli_distribution<double> m_dist;\r\n};\r\n//using ::boost::bernoulli_distribution;\r\nusing ::boost::geometric_distribution;\r\nusing ::boost::poisson_distribution;\r\nusing ::boost::binomial_distribution;\r\nusing ::boost::uniform_real;\r\nusing ::boost::exponential_distribution;\r\nusing ::boost::normal_distribution;\r\nusing ::boost::gamma_distribution;\r\n\r\n} }\r\n\r\n#endif\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "a1771aaef5c4b9bd2fb115392c1b93f04d9ba85c", "size": 18630, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/tr1/random.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/tr1/random.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/tr1/random.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 31.737649063, "max_line_length": 125, "alphanum_fraction": 0.642243693, "num_tokens": 5386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4488274378771148}}
{"text": "#include <sm/random.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/normal_distribution.hpp>\n\n\nnamespace sm {\n  \nnamespace random {\n    \nclass Random\n{\n public:\n  // http://www.boost.org/doc/libs/1_49_0/doc/html/boost_random/reference.html#boost_random.reference.generators\n  typedef boost::mt19937 base_generator_type;\n\n  base_generator_type _generator;\n  // Define a uniform random number distribution which produces \"double\"\n  // values between 0 and 1 (0 inclusive, 1 exclusive).\n  boost::uniform_real<> _uni_dist;\n  boost::variate_generator<base_generator_type&, boost::uniform_real<> > _uniform;\n  boost::normal_distribution<> _normal_dist;\n  boost::variate_generator<base_generator_type&, boost::normal_distribution<> > _normal;\n\n  Random() : _uni_dist(0.0,1.0), _uniform(_generator, _uni_dist), _normal_dist(), _normal(_generator, _normal_dist)\n  {\n\t// 0\n  }\n\n  double normal()\n  {\n\treturn _normal();\n  }\n\n  double uniform()\n  {\n\treturn _uniform();\n  }\n\n  void seed(boost::uint64_t s)\n  {\n    _normal.engine().seed(s);\n    _normal.distribution().reset();\n    _uniform.engine().seed(s);\n    _uniform.distribution().reset();\n  }\n\n  static Random & instance()\n  {\n\tstatic Random random;\n\treturn random;\n  }\n};\n\ndouble normal()\n{\n  return Random::instance().normal();\n}\n\ndouble randn()\n{\n  return Random::instance().normal();\n}\n\ndouble uniform()\n{\n  return Random::instance().uniform();\n}\n\ndouble rand()\n{\n  return Random::instance().uniform();\n}\n\ndouble randLU(double lowerBoundInclusive, double upperBoundExclusive)\n{\n  return Random::instance().uniform() * (upperBoundExclusive - lowerBoundInclusive) + lowerBoundInclusive;\n}\n\nint randLUi(int lowerBoundInclusive, int upperBoundExclusive)\n{\n  return (int)floor(Random::instance().uniform() * (upperBoundExclusive - lowerBoundInclusive)) + lowerBoundInclusive;\n}\n\nvoid seed(boost::uint64_t s)\n{\n  Random::instance().seed(s);\n}\n\n  \n} // namespace random\n\n} // namespace sm\n", "meta": {"hexsha": "6b9a5d21a1bb0d54790e01e5a5a452e5e67dce7f", "size": 2128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_random/src/random.cpp", "max_stars_repo_name": "PushyamiKaveti/kalibr", "max_stars_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2690.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:27:01.000Z", "max_issues_repo_path": "Schweizer-Messer/sm_random/src/random.cpp", "max_issues_repo_name": "PushyamiKaveti/kalibr", "max_issues_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 481.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T10:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:02:41.000Z", "max_forks_repo_path": "Schweizer-Messer/sm_random/src/random.cpp", "max_forks_repo_name": "PushyamiKaveti/kalibr", "max_forks_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1091.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T21:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:55:33.000Z", "avg_line_length": 21.9381443299, "max_line_length": 118, "alphanum_fraction": 0.725093985, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.44882743787711465}}
{"text": "/* compile with g++ ... -l arprec */\n\n#include <iostream>\n#include <fstream>\n#include <arprec/mp_real.h>\n#include <arprec/mp_complex.h>\n#include <complex>\n#include <boost/numeric/mtl/mtl.hpp>\n#include <cassert>\n#include <boost/numeric/linear_algebra/identity.hpp>\n\nusing namespace std;\ntypedef mtl::dense2D<mp_complex> mat_c;\n\nostream& operator<< (ostream& os, const mp_complex& c) {\n\treturn os << \"(\" << c.real << \", \" << c.imag << \")\";\n}\n\nint main() {\n\n\tmp::mp_init(102);\n\tcout.precision(30);\n\n\tmp_real x1,x2,x3,x4,x5,x6;\n\tx1 = mp_real(\"2e18\");\n\tx2 = mp_real(\"-1.34\");\n\tx3 = mp_real(\"1.6\");\n\tx4 = mp_real(3);\n\tx5 = mp_real(\"1.83e7\");\n\tx6 = mp_real(\"-4.234\");\n\tcout << \"x1 = \" << x1 << \"\\n\";\n\tcout << \"x2 = \" << x2 << \"\\n\";\n\tcout << \"x3 = \" << x3 << \"\\n\";\n\tcout << \"x4 = \" << x4 << \"\\n\";\n\tcout << \"x5 = \" << x5 << \"\\n\";\n\tcout << \"x6 = \" << x6 << \"\\n\";\n\tcout << \"---------------\\n\";\n\n\tmp_complex z1,z2,z3,z4,z5,z6;\n\tz1 = mp_complex(\"4e30\",\"3e30\");\n\tz2 = mp_complex(\"3\",\"-3.5\");\n\tz3 = z1+z2;\n\tz4 = sqrt(mp_complex(\"-4\",\"0\"));\n\tz5 = z2+z4;\n\tz6 = z2-z3+z1+z4;\n\tcout << \"z1 = \" << z1 << \"\\n\";\n\tcout << \"z2 = \" << z2 << \"\\n\";\n\tcout << \"z3 = \" << z3 << \"\\n\";\n\tcout << \"z4 = \" << z4 << \"\\n\";\n\tcout << \"z5 = \" << z5 << \"\\n\";\n\tcout << \"z6 = \" << z6 << \"\\n\";\n\tcout << \"---------------\\n\";\n\t{\n\tmtl::dense2D<mp_real> A(2,2),B(2,2),C(2,2),D(2,2);\n\tmtl::dense_vector<mp_real> b(2),x(2),r(2);\n\tA = x1,x2,\n\t    x3,x4;\n\tb = x5,x6;\n\tcout << \"A = \\n\" << A;\n\tcout << \"b = \" << b << endl;\n\n\t// A = A*A;\t// Laufzeitfehler\n\tA*=A;\n\tcout << \"A = \\n\" << A;\n\tcout << \"A*A = \\n\" << A*A;\n\tB =A*A;\n\tcout << \"B = \\n\" << B;\n\tC = trans(A);\n\tcout << \"C = \\n\" << C;\n\tD = A;\n\n\tmtl::dense_vector<int> p(2);\n\tlu(A,p);\n\tx = lu_apply(A,p,b);\n\tr = D*x-b;\n\tcout << \"Ax-b = \" << r << endl;\n\tcout << \"---------------\\n\";\n\t}\n\n\t{\n\tmtl::dense2D<mp_complex> A(2,2),B(2,2),C(2,2),D(2,2);\n\tmtl::dense_vector<mp_complex> b(2),x(2),r(2);\n \tA = z1,z2,\t\n \t    z3,z4;\n\n\n\tb = z5,z6;\n\tcout << \"A = \\n\" << A;\n\tcout << \"b = \" << b << endl;\n\n\t// A = A*A;\t// Compilezeitfehler\n\t// A*=A;\t// Compilezeitfehler\n\tB =A*A;\t// Compilezeitfehler\n\tC = trans(A);\t// Compilezeitfehler\n\n\tD = A;\n\n\tmtl::dense_vector<int> p(2);\n\tlu(A,p);\t// Compilezeitfehler\n\tx = lu_apply(A,p,b);\n\tr = D*x-b;\n \tcout << \"Ax-b = \" << r << endl;\n\tcout << \"---------------\\n\";\n\n\tcout << \"abs(A[0][0]) is \" << abs(A[0][0]) << '\\n';\n\t}\n\n\tmp::mp_finalize();\n\n}\n", "meta": {"hexsha": "1d762b92708db987a80a84d087599aedb9ead23c", "size": 2363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/experimental/mp_mtl_kompatibilitaet.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/experimental/mp_mtl_kompatibilitaet.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/experimental/mp_mtl_kompatibilitaet.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 21.2882882883, "max_line_length": 56, "alphanum_fraction": 0.4790520525, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4488228250785546}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_TOOLS_REMEZ_HPP\n#define BOOST_MATH_TOOLS_REMEZ_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/math/tools/solve.hpp>\n#include <boost/math/tools/minima.hpp>\n#include <boost/math/tools/roots.hpp>\n#include <boost/math/tools/polynomial.hpp>\n#include <boost/function/function1.hpp>\n#include <boost/scoped_array.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/policies/policy.hpp>\n\nnamespace boost{ namespace math{ namespace tools{\n\nnamespace detail{\n\n//\n// The error function: the difference between F(x) and\n// the current approximation.  This is the function\n// for which we must find the extema.\n//\ntemplate <class T>\nstruct remez_error_function\n{\n   typedef boost::function1<T, T const &> function_type;\npublic:\n   remez_error_function(\n      function_type f_, \n      const polynomial<T>& n, \n      const polynomial<T>& d, \n      bool rel_err)\n         : f(f_), numerator(n), denominator(d), rel_error(rel_err) {}\n\n   T operator()(const T& z)const\n   {\n      T y = f(z);\n      T abs = y - (numerator.evaluate(z) / denominator.evaluate(z));\n      T err;\n      if(rel_error)\n      {\n         if(y != 0)\n            err = abs / fabs(y);\n         else if(0 == abs)\n         {\n            // we must be at a root, or it's not recoverable:\n            BOOST_ASSERT(0 == abs);\n            err = 0;\n         }\n         else\n         {\n            // We have a divide by zero!\n            // Lets assume that f(x) is zero as a result of\n            // internal cancellation error that occurs as a result\n            // of shifting a root at point z to the origin so that\n            // the approximation can be \"pinned\" to pass through\n            // the origin: in that case it really\n            // won't matter what our approximation calculates here\n            // as long as it's a small number, return the absolute error:\n            err = abs;\n         }\n      }\n      else\n         err = abs;\n      return err;\n   }\nprivate:\n   function_type f;\n   polynomial<T> numerator;\n   polynomial<T> denominator;\n   bool rel_error;\n};\n//\n// This function adapts the error function so that it's minima\n// are the extema of the error function.  We can find the minima\n// with standard techniques.\n//\ntemplate <class T>\nstruct remez_max_error_function\n{\n   remez_max_error_function(const remez_error_function<T>& f)\n      : func(f) {}\n\n   T operator()(const T& x)\n   {\n      BOOST_MATH_STD_USING\n      return -fabs(func(x));\n   }\nprivate:\n   remez_error_function<T> func;\n};\n\n} // detail\n\ntemplate <class T>\nclass remez_minimax\n{\npublic:\n   typedef boost::function1<T, T const &> function_type;\n   typedef boost::numeric::ublas::vector<T> vector_type;\n   typedef boost::numeric::ublas::matrix<T> matrix_type;\n\n   remez_minimax(function_type f, unsigned oN, unsigned oD, T a, T b, bool pin = true, bool rel_err = false, int sk = 0, int bits = 0);\n   remez_minimax(function_type f, unsigned oN, unsigned oD, T a, T b, bool pin, bool rel_err, int sk, int bits, const vector_type& points);\n\n   void reset(unsigned oN, unsigned oD, T a, T b, bool pin = true, bool rel_err = false, int sk = 0, int bits = 0);\n   void reset(unsigned oN, unsigned oD, T a, T b, bool pin, bool rel_err, int sk, int bits, const vector_type& points);\n\n   void set_brake(int b)\n   {\n      BOOST_ASSERT(b < 100);\n      BOOST_ASSERT(b >= 0);\n      m_brake = b;\n   }\n\n   T iterate();\n\n   polynomial<T> denominator()const;\n   polynomial<T> numerator()const;\n\n   vector_type const& chebyshev_points()const\n   {\n      return control_points;\n   }\n\n   vector_type const& zero_points()const\n   {\n      return zeros;\n   }\n\n   T error_term()const\n   {\n      return solution[solution.size() - 1];\n   }\n   T max_error()const\n   {\n      return m_max_error;\n   }\n   T max_change()const\n   {\n      return m_max_change;\n   }\n   void rotate()\n   {\n      --orderN;\n      ++orderD;\n   }\n   void rescale(T a, T b)\n   {\n      T scale = (b - a) / (max - min);\n      for(unsigned i = 0; i < control_points.size(); ++i)\n      {\n         control_points[i] = (control_points[i] - min) * scale + a;\n      }\n      min = a;\n      max = b;\n   }\nprivate:\n\n   void init_chebyshev();\n\n   function_type func;            // The function to approximate.\n   vector_type control_points;    // Current control points to be used for the next iteration.\n   vector_type solution;          // Solution from the last iteration contains all unknowns including the error term.\n   vector_type zeros;             // Location of points of zero error from last iteration, plus the two end points.\n   vector_type maxima;            // Location of maxima of the error function, actually contains the control points used for the last iteration.\n   T m_max_error;                 // Maximum error found in last approximation.\n   T m_max_change;                // Maximum change in location of control points after last iteration.\n   unsigned orderN;               // Order of the numerator polynomial.\n   unsigned orderD;               // Order of the denominator polynomial.\n   T min, max;                    // End points of the range to optimise over.\n   bool rel_error;                // If true optimise for relative not absolute error.\n   bool pinned;                   // If true the approximation is \"pinned\" to go through the origin.\n   unsigned unknowns;             // Total number of unknowns.\n   int m_precision;               // Number of bits precision to which the zeros and maxima are found.\n   T m_max_change_history[2];     // Past history of changes to control points.\n   int m_brake;                     // amount to break by in percentage points.\n   int m_skew;                      // amount to skew starting points by in percentage points: -100-100\n};\n\n#ifndef BRAKE\n#define BRAKE 0\n#endif\n#ifndef SKEW\n#define SKEW 0\n#endif\n\ntemplate <class T>\nvoid remez_minimax<T>::init_chebyshev()\n{\n   BOOST_MATH_STD_USING\n   //\n   // Fill in the zeros:\n   //\n   unsigned terms = pinned ? orderD + orderN : orderD + orderN + 1;\n\n   for(unsigned i = 0; i < terms; ++i)\n   {\n      T cheb = cos((2 * terms - 1 - 2 * i) * constants::pi<T>() / (2 * terms));\n      cheb += 1;\n      cheb /= 2;\n      if(m_skew != 0)\n      {\n         T p = static_cast<T>(200 + m_skew) / 200;\n         cheb = pow(cheb, p);\n      }\n      cheb *= (max - min);\n      cheb += min;\n      zeros[i+1] = cheb;\n   }\n   zeros[0] = min;\n   zeros[unknowns] = max;\n   // perform a regular interpolation fit:\n   matrix_type A(terms, terms);\n   vector_type b(terms);\n   // fill in the y values:\n   for(unsigned i = 0; i < b.size(); ++i)\n   {\n      b[i] = func(zeros[i+1]);\n   }\n   // fill in powers of x evaluated at each of the control points:\n   unsigned offsetN = pinned ? 0 : 1;\n   unsigned offsetD = offsetN + orderN;\n   unsigned maxorder = (std::max)(orderN, orderD);\n   for(unsigned i = 0; i < b.size(); ++i)\n   {\n      T x0 = zeros[i+1];\n      T x = x0;\n      if(!pinned)\n         A(i, 0) = 1;\n      for(unsigned j = 0; j < maxorder; ++j)\n      {\n         if(j < orderN)\n            A(i, j + offsetN) = x;\n         if(j < orderD)\n         {\n            A(i, j + offsetD) = -x * b[i];\n         }\n         x *= x0;\n      }\n   }\n   //\n   // Now go ahead and solve the expression to get our solution:\n   //\n   vector_type l_solution = boost::math::tools::solve(A, b);\n   // need to add a \"fake\" error term:\n   l_solution.resize(unknowns);\n   l_solution[unknowns-1] = 0;\n   solution = l_solution;\n   //\n   // Now find all the extrema of the error function:\n   //\n   detail::remez_error_function<T> Err(func, this->numerator(), this->denominator(), rel_error);\n   detail::remez_max_error_function<T> Ex(Err);\n   m_max_error = 0;\n   //int max_err_location = 0;\n   for(unsigned i = 0; i < unknowns; ++i)\n   {\n      std::pair<T, T> r = brent_find_minima(Ex, zeros[i], zeros[i+1], m_precision);\n      maxima[i] = r.first;\n      T rel_err = fabs(r.second);\n      if(rel_err > m_max_error)\n      {\n         m_max_error = fabs(r.second);\n         //max_err_location = i;\n      }\n   }\n   control_points = maxima;\n}\n\ntemplate <class T>\nvoid remez_minimax<T>::reset(\n         unsigned oN, \n         unsigned oD, \n         T a, \n         T b, \n         bool pin, \n         bool rel_err, \n         int sk,\n         int bits)\n{\n   control_points = vector_type(oN + oD + (pin ? 1 : 2));\n   solution = control_points;\n   zeros = vector_type(oN + oD + (pin ? 2 : 3));\n   maxima = control_points;\n   orderN = oN;\n   orderD = oD;\n   rel_error = rel_err;\n   pinned = pin;\n   m_skew = sk;\n   min = a;\n   max = b;\n   m_max_error = 0;\n   unknowns = orderN + orderD + (pinned ? 1 : 2);\n   // guess our initial control points:\n   control_points[0] = min;\n   control_points[unknowns - 1] = max;\n   T interval = (max - min) / (unknowns - 1);\n   T spot = min + interval;\n   for(unsigned i = 1; i < control_points.size(); ++i)\n   {\n      control_points[i] = spot;\n      spot += interval;\n   }\n   solution[unknowns - 1] = 0;\n   m_max_error = 0;\n   if(bits == 0)\n   {\n      // don't bother about more than float precision:\n      m_precision = (std::min)(24, (boost::math::policies::digits<T, boost::math::policies::policy<> >() / 2) - 2);\n   }\n   else\n   {\n      // can't be more accurate than half the bits of T:\n      m_precision = (std::min)(bits, (boost::math::policies::digits<T, boost::math::policies::policy<> >() / 2) - 2);\n   }\n   m_max_change_history[0] = m_max_change_history[1] = 1;\n   init_chebyshev();\n   // do one iteration whatever:\n   //iterate();\n}\n\ntemplate <class T>\ninline remez_minimax<T>::remez_minimax(\n         typename remez_minimax<T>::function_type f, \n         unsigned oN, \n         unsigned oD, \n         T a, \n         T b, \n         bool pin, \n         bool rel_err, \n         int sk,\n         int bits)\n   : func(f) \n{\n   m_brake = 0;\n   reset(oN, oD, a, b, pin, rel_err, sk, bits);\n}\n\ntemplate <class T>\nvoid remez_minimax<T>::reset(\n         unsigned oN, \n         unsigned oD, \n         T a, \n         T b, \n         bool pin, \n         bool rel_err, \n         int sk,\n         int bits,\n         const vector_type& points)\n{\n   control_points = vector_type(oN + oD + (pin ? 1 : 2));\n   solution = control_points;\n   zeros = vector_type(oN + oD + (pin ? 2 : 3));\n   maxima = control_points;\n   orderN = oN;\n   orderD = oD;\n   rel_error = rel_err;\n   pinned = pin;\n   m_skew = sk;\n   min = a;\n   max = b;\n   m_max_error = 0;\n   unknowns = orderN + orderD + (pinned ? 1 : 2);\n   control_points = points;\n   solution[unknowns - 1] = 0;\n   m_max_error = 0;\n   if(bits == 0)\n   {\n      // don't bother about more than float precision:\n      m_precision = (std::min)(24, (boost::math::policies::digits<T, boost::math::policies::policy<> >() / 2) - 2);\n   }\n   else\n   {\n      // can't be more accurate than half the bits of T:\n      m_precision = (std::min)(bits, (boost::math::policies::digits<T, boost::math::policies::policy<> >() / 2) - 2);\n   }\n   m_max_change_history[0] = m_max_change_history[1] = 1;\n   // do one iteration whatever:\n   //iterate();\n}\n\ntemplate <class T>\ninline remez_minimax<T>::remez_minimax(\n         typename remez_minimax<T>::function_type f, \n         unsigned oN, \n         unsigned oD, \n         T a, \n         T b, \n         bool pin, \n         bool rel_err, \n         int sk,\n         int bits,\n         const vector_type& points)\n   : func(f)\n{\n   m_brake = 0;\n   reset(oN, oD, a, b, pin, rel_err, sk, bits, points);\n}\n\ntemplate <class T>\nT remez_minimax<T>::iterate()\n{\n   BOOST_MATH_STD_USING\n   matrix_type A(unknowns, unknowns);\n   vector_type b(unknowns);\n\n   // fill in evaluation of f(x) at each of the control points:\n   for(unsigned i = 0; i < b.size(); ++i)\n   {\n      // take care that none of our control points are at the origin:\n      if(pinned && (control_points[i] == 0))\n      {\n         if(i)\n            control_points[i] = control_points[i-1] / 3;\n         else\n            control_points[i] = control_points[i+1] / 3;\n      }\n      b[i] = func(control_points[i]);\n   }\n\n   T err_err;\n   unsigned convergence_count = 0;\n   do{\n      // fill in powers of x evaluated at each of the control points:\n      int sign = 1;\n      unsigned offsetN = pinned ? 0 : 1;\n      unsigned offsetD = offsetN + orderN;\n      unsigned maxorder = (std::max)(orderN, orderD);\n      T Elast = solution[unknowns - 1];\n\n      for(unsigned i = 0; i < b.size(); ++i)\n      {\n         T x0 = control_points[i];\n         T x = x0;\n         if(!pinned)\n            A(i, 0) = 1;\n         for(unsigned j = 0; j < maxorder; ++j)\n         {\n            if(j < orderN)\n               A(i, j + offsetN) = x;\n            if(j < orderD)\n            {\n               T mult = rel_error ? T(b[i] - sign * fabs(b[i]) * Elast): T(b[i] - sign * Elast);\n               A(i, j + offsetD) = -x * mult;\n            }\n            x *= x0;\n         }\n         // The last variable to be solved for is the error term, \n         // sign changes with each control point:\n         T E = rel_error ? T(sign * fabs(b[i])) : T(sign);\n         A(i, unknowns - 1) = E;\n         sign = -sign;\n      }\n\n   #ifdef BOOST_MATH_INSTRUMENT\n      for(unsigned i = 0; i < b.size(); ++i)\n         std::cout << b[i] << \" \";\n      std::cout << \"\\n\\n\";\n      for(unsigned i = 0; i < b.size(); ++i)\n      {\n         for(unsigned j = 0; j < b.size(); ++ j)\n            std::cout << A(i, j) << \" \";\n         std::cout << \"\\n\";\n      }\n      std::cout << std::endl;\n   #endif\n      //\n      // Now go ahead and solve the expression to get our solution:\n      //\n      solution = boost::math::tools::solve(A, b);\n\n      err_err = (Elast != 0) ? T(fabs((fabs(solution[unknowns-1]) - fabs(Elast)) / fabs(Elast))) : T(1);\n   }while(orderD && (convergence_count++ < 80) && (err_err > 0.001));\n\n   //\n   // Perform a sanity check to verify that the solution to the equations\n   // is not so much in error as to be useless.  The matrix inversion can\n   // be very close to singular, so this can be a real problem.\n   //\n   vector_type sanity = prod(A, solution);\n   for(unsigned i = 0; i < b.size(); ++i)\n   {\n      T err = fabs((b[i] - sanity[i]) / fabs(b[i]));\n      if(err > sqrt(epsilon<T>()))\n      {\n         std::cerr << \"Sanity check failed: more than half the digits in the found solution are in error.\" << std::endl;\n      }\n   }\n\n   //\n   // Next comes another sanity check, we want to verify that all the control\n   // points do actually alternate in sign, in practice we may have \n   // additional roots in the error function that cause this to fail.\n   // Failure here is always fatal: even though this code attempts to correct\n   // the problem it usually only postpones the inevitable.\n   //\n   polynomial<T> num, denom;\n   num = this->numerator();\n   denom = this->denominator();\n   T e1 = b[0] - num.evaluate(control_points[0]) / denom.evaluate(control_points[0]);\n#ifdef BOOST_MATH_INSTRUMENT\n   std::cout << e1;\n#endif\n   for(unsigned i = 1; i < b.size(); ++i)\n   {\n      T e2 = b[i] - num.evaluate(control_points[i]) / denom.evaluate(control_points[i]);\n#ifdef BOOST_MATH_INSTRUMENT\n      std::cout << \" \" << e2;\n#endif\n      if(e2 * e1 > 0)\n      {\n         std::cerr << std::flush << \"Basic sanity check failed: Error term does not alternate in sign, non-recoverable error may follow...\" << std::endl;\n         T perturbation = 0.05;\n         do{\n            T point = control_points[i] * (1 - perturbation) + control_points[i-1] * perturbation;\n            e2 = func(point) - num.evaluate(point) / denom.evaluate(point);\n            if(e2 * e1 < 0)\n            {\n               control_points[i] = point;\n               break;\n            }\n            perturbation += 0.05;\n         }while(perturbation < 0.8);\n\n         if((e2 * e1 > 0) && (i + 1 < b.size()))\n         {\n            perturbation = 0.05;\n            do{\n               T point = control_points[i] * (1 - perturbation) + control_points[i+1] * perturbation;\n               e2 = func(point) - num.evaluate(point) / denom.evaluate(point);\n               if(e2 * e1 < 0)\n               {\n                  control_points[i] = point;\n                  break;\n               }\n               perturbation += 0.05;\n            }while(perturbation < 0.8);\n         }\n\n      }\n      e1 = e2;\n   }\n\n#ifdef BOOST_MATH_INSTRUMENT\n   for(unsigned i = 0; i < solution.size(); ++i)\n      std::cout << solution[i] << \" \";\n   std::cout << std::endl << this->numerator() << std::endl;\n   std::cout << this->denominator() << std::endl;\n   std::cout << std::endl;\n#endif\n\n   //\n   // The next step is to find all the intervals in which our maxima\n   // lie:\n   //\n   detail::remez_error_function<T> Err(func, this->numerator(), this->denominator(), rel_error);\n   zeros[0] = min;\n   zeros[unknowns] = max;\n   for(unsigned i = 1; i < control_points.size(); ++i)\n   {\n      eps_tolerance<T> tol(m_precision);\n      boost::uintmax_t max_iter = 1000;\n      std::pair<T, T> p = toms748_solve(\n         Err, \n         control_points[i-1], \n         control_points[i], \n         tol, \n         max_iter);\n      zeros[i] = (p.first + p.second) / 2;\n      //zeros[i] = bisect(Err, control_points[i-1], control_points[i], m_precision);\n   }\n   //\n   // Now find all the extrema of the error function:\n   //\n   detail::remez_max_error_function<T> Ex(Err);\n   m_max_error = 0;\n   //int max_err_location = 0;\n   for(unsigned i = 0; i < unknowns; ++i)\n   {\n      std::pair<T, T> r = brent_find_minima(Ex, zeros[i], zeros[i+1], m_precision);\n      maxima[i] = r.first;\n      T rel_err = fabs(r.second);\n      if(rel_err > m_max_error)\n      {\n         m_max_error = fabs(r.second);\n         //max_err_location = i;\n      }\n   }\n   //\n   // Almost done now! we just need to set our control points\n   // to the extrema, and calculate how much each point has changed\n   // (this will be our termination condition):\n   //\n   swap(control_points, maxima);\n   m_max_change = 0;\n   //int max_change_location = 0;\n   for(unsigned i = 0; i < unknowns; ++i)\n   {\n      control_points[i] = (control_points[i] * (100 - m_brake) + maxima[i] * m_brake) / 100;\n      T change = fabs((control_points[i] - maxima[i]) / control_points[i]);\n#if 0\n      if(change > m_max_change_history[1])\n      {\n         // divergence!!! try capping the change:\n         std::cerr << \"Possible divergent step, change will be capped!!\" << std::endl;\n         change = m_max_change_history[1];\n         if(control_points[i] < maxima[i])\n            control_points[i] = maxima[i] - change * maxima[i];\n         else\n            control_points[i] = maxima[i] + change * maxima[i];\n      }\n#endif\n      if(change > m_max_change)\n      {\n         m_max_change = change;\n         //max_change_location = i;\n      }\n   }\n   //\n   // store max change information:\n   //\n   m_max_change_history[0] = m_max_change_history[1];\n   m_max_change_history[1] = fabs(m_max_change);\n\n   return m_max_change;\n}\n\ntemplate <class T>\npolynomial<T> remez_minimax<T>::numerator()const\n{\n   boost::scoped_array<T> a(new T[orderN + 1]);\n   if(pinned)\n      a[0] = 0;\n   unsigned terms = pinned ? orderN : orderN + 1;\n   for(unsigned i = 0; i < terms; ++i)\n      a[pinned ? i+1 : i] = solution[i];\n   return boost::math::tools::polynomial<T>(&a[0], orderN);\n}\n\ntemplate <class T>\npolynomial<T> remez_minimax<T>::denominator()const\n{\n   unsigned terms = orderD + 1;\n   unsigned offsetD = pinned ? orderN : (orderN + 1);\n   boost::scoped_array<T> a(new T[terms]);\n   a[0] = 1;\n   for(unsigned i = 0; i < orderD; ++i)\n      a[i+1] = solution[i + offsetD];\n   return boost::math::tools::polynomial<T>(&a[0], orderD);\n}\n\n\n}}} // namespaces\n\n#endif // BOOST_MATH_TOOLS_REMEZ_HPP\n\n\n\n", "meta": {"hexsha": "44a3412fc3a9fb6c57dabec36cfeda0e6d1a14cf", "size": 19802, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/math/include_private/boost/math/tools/remez.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/math/include_private/boost/math/tools/remez.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/math/include_private/boost/math/tools/remez.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 29.6437125749, "max_line_length": 153, "alphanum_fraction": 0.5735279265, "num_tokens": 5556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.44882281820780456}}
{"text": "// Copyright (c) 2015-2018, CNRS\n// Authors: Justin Carpentier <jcarpent@laas.fr>\n\n#ifndef __multicontact_api_geometry_second_order_cone_hpp__\n#define __multicontact_api_geometry_second_order_cone_hpp__\n\n#include <Eigen/Dense>\n#include <iostream>\n\n#include \"multicontact-api/geometry/fwd.hpp\"\n#include \"multicontact-api/serialization/archive.hpp\"\n#include \"multicontact-api/serialization/eigen-matrix.hpp\"\n\nnamespace multicontact_api {\nnamespace geometry {\n\ntemplate <typename _Scalar, int _dim, int _Options>\nstruct SecondOrderCone : public serialization::Serializable<SecondOrderCone<_Scalar, _dim, _Options> > {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  enum { dim = _dim, Options = _Options };\n  typedef _Scalar Scalar;\n  typedef Eigen::Matrix<Scalar, dim, dim, Options> MatrixD;\n  typedef Eigen::Matrix<Scalar, dim, 1, Options> VectorD;\n  typedef Eigen::DenseIndex DenseIndex;\n\n  SecondOrderCone()\n      : m_Q(MatrixD::Identity()), m_QPo(_dim, _dim), m_direction(VectorD::Zero()), m_Pd(_dim, _dim), m_Po(_dim, _dim) {\n    m_direction[_dim - 1] = 1.;\n    computeProjectors();\n  }\n\n  SecondOrderCone(const MatrixD& Q, const VectorD& direction)\n      : m_Q(Q), m_QPo(_dim, _dim), m_direction(direction.normalized()), m_Pd(_dim, _dim), m_Po(_dim, _dim) {\n    assert(direction.norm() >= Eigen::NumTraits<Scalar>::dummy_precision());\n    assert((Q - Q.transpose()).isMuchSmallerThan(Q));\n    computeProjectors();\n  }\n\n  ///\n  /// \\brief Build a regular cone from a given friction coefficient and a direction.\n  ///\n  /// \\param mu Friction coefficient.\n  /// \\param direction Direction of the cone.\n  ///\n  /// \\returns A second order cone.\n  ///\n  static SecondOrderCone RegularCone(const Scalar mu, const VectorD& direction) {\n    assert(mu > 0 && \"The friction coefficient must be non-negative\");\n    MatrixD Q(MatrixD::Zero());\n    Q.diagonal().fill(1. / mu);\n\n    return SecondOrderCone(Q, direction);\n  }\n\n  template <typename S2, int O2>\n  bool operator==(const SecondOrderCone<S2, dim, O2>& other) const {\n    return m_Q == other.m_Q && m_direction == other.m_direction;\n  }\n\n  template <typename S2, int O2>\n  bool operator!=(const SecondOrderCone<S2, dim, O2>& other) const {\n    return !(*this == other);\n  }\n\n  /// \\returns the value of lhs of the conic inequality\n  Scalar lhsValue(const VectorD& point) const {\n    //        const VectorD x_Po(m_Po * point);\n    return (m_QPo * point).norm();\n  }\n\n  /// \\returns the value of rhs of the conic inequality\n  Scalar rhsValue(const VectorD& point) const { return m_direction.dot(point); }\n\n  /// \\returns true if the point is inside the cone\n  bool check(const VectorD& point) const { return check(point, 1.); }\n\n  bool check(const VectorD& point, const Scalar factor) const { return lhsValue(point) <= factor * rhsValue(point); }\n\n  /// \\returns the direction of the cone.\n  const VectorD& direction() const { return m_direction; }\n  void setDirection(const VectorD& direction) {\n    assert(direction.norm() >= Eigen::NumTraits<Scalar>::dummy_precision());\n    m_direction = direction.normalized();\n    computeProjectors();\n  }\n\n  template <typename S2, int O2>\n  bool isApprox(const SecondOrderCone<S2, dim, O2>& other,\n                const Scalar& prec = Eigen::NumTraits<Scalar>::dummy_precision()) const {\n    return m_direction.isApprox(other.m_direction, prec) && m_Q.isApprox(other.m_Q, prec);\n  }\n\n  /// \\returns the quadratic term of the lhs norm.\n  const MatrixD& Q() const { return m_Q; }\n  void setQ(const MatrixD& Q) {\n    assert((Q - Q.transpose()).isMuchSmallerThan(Q));\n    m_Q = Q;\n    computeProjectors();\n  }\n\n  void disp(std::ostream& os) const {\n    os << \"Q:\\n\" << m_Q << std::endl << \"direction: \" << m_direction.transpose() << std::endl;\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, const SecondOrderCone& C) {\n    C.disp(os);\n    return os;\n  }\n\n protected:\n  inline void computeProjectors() {\n    m_Pd = m_direction * m_direction.transpose();\n    m_Po = MatrixD::Identity() - m_Pd;\n    m_QPo.noalias() = m_Q * m_Po;\n  }\n\n  /// \\brief Cholesky decomposition matrix reprensenting the conic norm\n  MatrixD m_Q;\n  /// \\brief Cholesky decomposition projected on the orthogonal of m_direction\n  MatrixD m_QPo;\n\n  /// \\brief Direction of the cone\n  VectorD m_direction;\n\n  /// \\brief Projector along the direction of d\n  MatrixD m_Pd;\n  /// \\brief Projector orthogonal to d\n  MatrixD m_Po;\n\n private:\n  // Serialization of the class\n  friend class boost::serialization::access;\n\n  template <class Archive>\n  void save(Archive& ar, const unsigned int /*version*/) const {\n    ar& boost::serialization::make_nvp(\"quadratic_term\", m_Q);\n    ar& boost::serialization::make_nvp(\"direction\", m_direction);\n  }\n\n  template <class Archive>\n  void load(Archive& ar, const unsigned int /*version*/) {\n    ar >> boost::serialization::make_nvp(\"quadratic_term\", m_Q);\n    ar >> boost::serialization::make_nvp(\"direction\", m_direction);\n\n    computeProjectors();\n  }\n\n  BOOST_SERIALIZATION_SPLIT_MEMBER()\n};\n\n}  // namespace geometry\n}  // namespace multicontact_api\n\n#endif  // ifndef __multicontact_api_geometry_second_order_cone_hpp__\n", "meta": {"hexsha": "1d2edc4626406fed103a1aff0203f4e9a60ab97b", "size": 5112, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/multicontact-api/geometry/second-order-cone.hpp", "max_stars_repo_name": "nim65s/multicontact-api", "max_stars_repo_head_hexsha": "036b902deb2472bb22496a567e93a25a236a3e1e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-23T11:55:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-23T11:55:53.000Z", "max_issues_repo_path": "include/multicontact-api/geometry/second-order-cone.hpp", "max_issues_repo_name": "nim65s/multicontact-api", "max_issues_repo_head_hexsha": "036b902deb2472bb22496a567e93a25a236a3e1e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2020-03-13T13:28:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:23:27.000Z", "max_forks_repo_path": "include/multicontact-api/geometry/second-order-cone.hpp", "max_forks_repo_name": "nim65s/multicontact-api", "max_forks_repo_head_hexsha": "036b902deb2472bb22496a567e93a25a236a3e1e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T13:52:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T06:53:58.000Z", "avg_line_length": 32.9806451613, "max_line_length": 119, "alphanum_fraction": 0.6971830986, "num_tokens": 1359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4488228182078045}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_REC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-arithmetic\n    Function object implementing rec capabilities\n\n    Returns the inverse (reciprocal) of the entry.\n\n    @par semantic:\n    For any given value @c x of type @c T:\n\n    @code\n    T r = rec(x);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    T r = T(1)/x;\n    @endcode\n\n    @par Note\n\n    For integral typed entries the result is always in the set \\f$\\{0,  \\pm1, Valmax \\}\\f$\n\n    @par Decorators\n\n     For floating types @c rec has several decorated variations\n\n\n     - raw_ Many simd architectures provide an intrinsic that computes some bits of the inverse (at least 12)\n            and don't care of denormals or limiting values. If it exists this is obtained by the raw_ decorator.\n            As usual if it doesn't the plain rec is called.\n\n     - with no decorators ensure 1ulp but still doesn't care of limiting value or denormals\n\n  **/\n  Value rec(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/rec.hpp>\n#include <boost/simd/function/simd/rec.hpp>\n\n#endif\n", "meta": {"hexsha": "fbe57965d075f0db508447c6ea8f880c3dc970e3", "size": 1577, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/rec.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "include/boost/simd/function/rec.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/rec.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 26.2833333333, "max_line_length": 112, "alphanum_fraction": 0.6068484464, "num_tokens": 352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4488228113370543}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n#include \"DavidsonDiagonalizer.h\"\n#include \"../MathUtils.h\"\n#include \"DiagonalizerSettings.h\"\n#include \"PreconditionerEvaluator.h\"\n#include \"SubspaceOrthogonalizer.h\"\n#include <Core/Log.h>\n#include <Eigen/Eigenvalues>\n\nnamespace Scine {\nnamespace Utils {\n\nNonOrthogonalDavidson::NonOrthogonalDavidson(int eigenvaluesToCompute, int totalDimension)\n  : KrylovDiagonalizer(eigenvaluesToCompute, totalDimension) {\n}\n\nNonOrthogonalDavidson::~NonOrthogonalDavidson() = default;\n\nEigenContainer NonOrthogonalDavidson::eigenDecomposition(const Eigen::MatrixXd& projectedMatrix) const {\n  auto algorithm = settings_->getString(gepAlgorithmForBalancedMethodOption);\n  if (algorithm == \"standard\")\n    return MathUtils::stabilizedGeneralizedEigendecomposition<MathUtils::GepAlgorithm::Standard>(\n        projectedMatrix, basisOverlap_.selfadjointView<Eigen::Upper>());\n  else if (algorithm == \"cholesky\")\n    return MathUtils::stabilizedGeneralizedEigendecomposition<MathUtils::GepAlgorithm::Cholesky>(\n        projectedMatrix, basisOverlap_.selfadjointView<Eigen::Upper>());\n  else if (algorithm == \"simultaneous_diag\")\n    return MathUtils::stabilizedGeneralizedEigendecomposition<MathUtils::GepAlgorithm::SimultaneousDiagonalization>(\n        projectedMatrix, basisOverlap_.selfadjointView<Eigen::Upper>());\n  else\n    throw InvalidDiagonalizerInputException(\"Algorithm \" + algorithm + \" not available for stable GEP solution.\");\n}\n\ninline void NonOrthogonalDavidson::onSigmaMatrixEvaluation(const Eigen::MatrixXd& projector) {\n  decltype(basisOverlap_)::Index newCols = subspaceDimension_ - basisOverlap_.cols();\n  basisOverlap_.conservativeResize(subspaceDimension_, subspaceDimension_);\n  Eigen::MatrixXd rightCols = projector.rightCols(newCols);\n  basisOverlap_.rightCols(newCols) = projector.transpose() * rightCols;\n}\n\ninline void NonOrthogonalDavidson::filterCorrectionVectors(const Eigen::MatrixXd& projector,\n                                                           Eigen::MatrixXd& newGuessVectors) const {\n  double absNorm =\n      std::abs(newGuessVectors.col(newGuessVectors.cols() - 1).transpose() * projector.col(projector.cols() - 1));\n  if (absNorm > 1.0 - settings_->getDouble(correctionToleranceOption)) {\n    newGuessVectors.col(newGuessVectors.cols() - 1) = residualVectors_.col(newGuessVectors.cols() - 1);\n  }\n}\n\nvoid NonOrthogonalDavidson::callCollapserImpl() {\n  guessVectors_ = subspaceCollapser_->getCollapsedNonOrthogonalSubspace();\n  subspaceDimension_ = guessVectors_.cols();\n  basisOverlap_.resize(0, 0);\n}\n\nOrthogonalDavidson::OrthogonalDavidson(int eigenvaluesToCompute, int totalDimension)\n  : KrylovDiagonalizer(eigenvaluesToCompute, totalDimension) {\n}\n\nOrthogonalDavidson::~OrthogonalDavidson() = default;\n\ninline void OrthogonalDavidson::filterCorrectionVectors(const Eigen::MatrixXd& projector, Eigen::MatrixXd& newGuessVectors) const {\n  Eigen::MatrixXd orthogonalizedCorrectionVector = newGuessVectors;\n  Eigen::VectorXd correctionVectorsNorms = newGuessVectors.colwise().norm();\n\n  int dimension = 0;\n  double maxNorm = 0;\n  Eigen::VectorXd maxNormOrthogonalizedVector;\n  for (int i = 0; i < orthogonalizedCorrectionVector.cols(); ++i) {\n    Eigen::VectorXd orthogonalizedVector;\n    SubspaceOrthogonalizer::orthogonalizeToSubspace(orthogonalizedCorrectionVector.col(i), projector, orthogonalizedVector);\n\n    double norm = orthogonalizedVector.norm() / correctionVectorsNorms(i);\n    if (norm > maxNorm) {\n      std::swap(norm, maxNorm);\n      maxNormOrthogonalizedVector = orthogonalizedVector;\n    }\n\n    if (norm / correctionVectorsNorms(i) > settings_->getDouble(correctionToleranceOption)) {\n      newGuessVectors.col(dimension++) = orthogonalizedVector;\n    }\n  }\n  // Retain one at least if everything is thrown away, the one that corrects the most\n  if (dimension == 0) {\n    newGuessVectors.col(0) = maxNormOrthogonalizedVector;\n    dimension = 1;\n  }\n  newGuessVectors.conservativeResize(Eigen::NoChange, dimension);\n}\n\ninline void OrthogonalDavidson::onIterationStart() {\n  KrylovDiagonalizer::onIterationStart();\n  SubspaceOrthogonalizer::qrOrthogonalize(guessVectors_, subspaceDimension_);\n  guessVectors_.leftCols(subspaceDimension_).colwise().normalize();\n}\n\nEigenContainer OrthogonalDavidson::eigenDecomposition(const Eigen::MatrixXd& projectedMatrix) const {\n  EigenContainer result;\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> subspaceDiagonalizer(projectedMatrix);\n  result.eigenVectors = subspaceDiagonalizer.eigenvectors();\n  result.eigenValues = subspaceDiagonalizer.eigenvalues();\n  return result;\n}\n\nvoid OrthogonalDavidson::callCollapserImpl() {\n  guessVectors_ = subspaceCollapser_->getCollapsedOrthogonalSubspace();\n  subspaceDimension_ = guessVectors_.cols();\n}\n} // namespace Utils\n} // namespace Scine\n", "meta": {"hexsha": "a9a789a10532633138b052db9155eaf107f55ee3", "size": 4989, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Math/IterativeDiagonalizer/DavidsonDiagonalizer.cpp", "max_stars_repo_name": "qcscine/utilities", "max_stars_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Utils/Math/IterativeDiagonalizer/DavidsonDiagonalizer.cpp", "max_issues_repo_name": "qcscine/utilities", "max_issues_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-19T14:34:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:07:18.000Z", "max_forks_repo_path": "src/Utils/Utils/Math/IterativeDiagonalizer/DavidsonDiagonalizer.cpp", "max_forks_repo_name": "qcscine/utilities", "max_forks_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T16:44:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T20:48:19.000Z", "avg_line_length": 43.0086206897, "max_line_length": 131, "alphanum_fraction": 0.7700942073, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.448721855160648}}
{"text": "#include <mex.h> \n#include <math.h>\n#include <Eigen/Dense>\n#include <iostream>\n\n\nusing namespace Eigen;\nusing namespace std;\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n    \n    mxArray *output_mex;\n    \n    double *tri_num, *obj_tri, *q_target;\n    double *output;\n     \n    tri_num = mxGetPr(prhs[0]);\n    obj_tri = mxGetPr(prhs[1]);\n    q_target = mxGetPr(prhs[2]);\n    \n    int tri_n = tri_num[0];\n    \n    output_mex = plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);\n    \n    output = mxGetPr(output_mex);\n    \n    int tri[3];\n    \n    output[0] = 1;\n     \n    tri[0] = obj_tri[0] - 1; \n    tri[1] = obj_tri[0 + tri_n] - 1; \n    tri[2] = obj_tri[0 + 2 * tri_n] - 1; \n    \n    Vector3d va(q_target[2 * tri[0]], q_target[2 * tri[0] + 1], 0);\n    Vector3d vb(q_target[2 * tri[1]], q_target[2 * tri[1] + 1], 0);\n    Vector3d vc(q_target[2 * tri[2]], q_target[2 * tri[2] + 1], 0);\n    \n    Vector3d e1 = va - vb;\n    Vector3d e2 = vc - vb;\n    Vector3d flag = e1.cross(e2);\n     \n    for(int i = 0; i < tri_n; i++)\n    {   \n        tri[0] = obj_tri[i] - 1; \n        tri[1] = obj_tri[i + tri_n] - 1; \n        tri[2] = obj_tri[i + 2 * tri_n] - 1; \n        \n        Vector3d va(q_target[2 * tri[0]], q_target[2 * tri[0] + 1], 0);\n        Vector3d vb(q_target[2 * tri[1]], q_target[2 * tri[1] + 1], 0);\n        Vector3d vc(q_target[2 * tri[2]], q_target[2 * tri[2] + 1], 0);\n        \n        Vector3d e1 = va - vb;\n        Vector3d e2 = vc - vb;\n        Vector3d f1 = e1.cross(e2);\n        \n        if(f1.dot(flag) < 0)\n        {\n            output[0] = 0;\n        }\n    }\n    \n    return;\n    \n}", "meta": {"hexsha": "bf28c5a61b71300a507c774db2057b6945fdb26c", "size": 1627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/2D/lib/mex/local_injectivity_check_mex.cpp", "max_stars_repo_name": "ErisZhang/BCQN", "max_stars_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T16:35:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T11:47:42.000Z", "max_issues_repo_path": "code/2D/lib/mex/local_injectivity_check_mex.cpp", "max_issues_repo_name": "ErisZhang/BCQN", "max_issues_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-10T12:12:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-10T12:12:18.000Z", "max_forks_repo_path": "code/2D/lib/mex/local_injectivity_check_mex.cpp", "max_forks_repo_name": "ErisZhang/BCQN", "max_forks_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T06:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-27T09:58:32.000Z", "avg_line_length": 24.2835820896, "max_line_length": 76, "alphanum_fraction": 0.5064535956, "num_tokens": 594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.44872184976297047}}
{"text": "// Created by enenra on 19.11.2021.\n\n#ifndef KURSOVAYA_1_HEADER_HPP\n#define KURSOVAYA_1_HEADER_HPP\n\n#include \"nlohmann/json.hpp\"\n#include <boost/filesystem.hpp>\n#include <algorithm>\n#include <regex>\n#include <string>\n#include <iomanip>\n#include <cmath>\n#include <ctime>\n\nusing json = nlohmann::json;\n\nsize_t power(std::string &X);\n\nsize_t number_degree(const size_t &val);\n\nint number_degree(const int &val);\n\nclass boolean {\nprivate:\n    std::vector<int> vec;\n\npublic:\n    boolean()=default;\n\n    explicit boolean(std::string &init) {\n        for (size_t i = 0; i < init.size(); ++i) {\n            if ((init[i] == '0') || (init[i] == '1')) {\n                if (i == 0)\n                    if ((init[i + 1] == '0') || (init[i + 1] == '1')) {\n                        if (init[i] == '0')\n                            vec.push_back(0);\n                        else vec.push_back(1);\n                    }\n                if ((i > 0) && (i < init.size() - 1))\n                    if ((init[i + 1] == '0') || (init[i + 1] == '1') || (init[i - 1] == '0') || (init[i - 1] == '1')) {\n                        if (init[i] == '0')\n                            vec.push_back(0);\n                        else vec.push_back(1);\n                    }\n                if (i == init.size() - 1) {\n                    if ((init[i - 1] == '0') || (init[i - 1] == '1')) {\n                        if (init[i] == '0')\n                            vec.push_back(0);\n                        else vec.push_back(1);\n                    }\n                }\n            }\n        }\n    }\n\n    boolean(int val, int deg) {\n        for (int i = 0; i < deg; ++i)\n            vec.push_back(0);\n        while (deg > 0) {\n            vec[deg - 1] = val % 2;\n            val /= 2;\n            --deg;\n        }\n    }\n\n    ~boolean() = default;\n\n    void push_back(int val) {\n        vec.push_back(val);\n    }\n\n    bool empty() {\n        if (vec.empty())\n            return true;\n        return false;\n    }\n\n    int degree() {\n        int deg = 0;\n        while (pow(2.0, deg) != vec.size())\n            deg += 1;\n        return deg;\n    }\n\n    boolean operator+=(boolean &r) {\n        for (size_t i = 0; i < vec.size(); ++i)\n            vec[i] ^= r.vec[i];\n        return *this;\n    }\n\n    boolean operator*=(boolean &r) {\n        for (size_t i = 0; i < vec.size(); ++i)\n            vec[i] &= r.vec[i];\n        return *this;\n    }\n\n    int &operator[](size_t &index) {\n        return vec[index];\n    }\n\n    int &operator[](int index) {\n        return vec[index];\n    }\n\n    size_t to_number() {\n        size_t result = 0;\n        for (size_t i = 0; i < vec.size(); ++i)\n            result += vec[i] * pow(2.0, vec.size() - 1 - i);\n        return result;\n    }\n\n    bool operator==(const boolean& r) const {\n        if (vec.size() != r.vec.size())\n            return false;\n        else\n            for (size_t i = 0; i < vec.size(); ++i)\n                if (vec[i] != r.vec[i])\n                    return false;\n        return true;\n    }\n\n    bool operator!=(const boolean &r) const {\n        if (vec.size() != r.vec.size())\n            return true;\n        else\n            for (size_t i = 0; i < vec.size(); ++i)\n                if (vec[i] != r.vec[i])\n                    return true;\n        return false;\n    }\n};\n\nclass cryptalgorithm {\nprivate:\n    std::string text;\n    std::string cipher;\n    std::vector<int> keys;\n    std::vector<std::string> functions;\n\npublic:\n    cryptalgorithm() = default;\n\n    cryptalgorithm(std::string &t, std::string &c, std::vector<int> &k, std::vector<std::string> &f) {\n        text = t;\n        cipher = c;\n        keys = k;\n        functions = f;\n    }\n\n    ~cryptalgorithm() = default;\n\n\n    void absolute_stability(std::ofstream &out) {\n        out << '\\n' << \" - ANALYZING ABSOLUTE STABILITY:\" << '\\n';\n        if (power(text) <= keys.size())\n            out << '\\n' << \"Your algorithm is absolutely stable\" << '\\n';\n        else out << '\\n' << \"Your algorithm is not absolutely stable\" << '\\n';\n        out << '\\n';\n    }\n\n    void differential_attack(std::ofstream &out) {\n        out << '\\n' << \" - DIFFERENTIAL ATTACK:\" << '\\n';\n        if (functions.size() == 1) {\n            out\n                    << \"Your algorithm does not cannot ba attacked with differential attack, or entered functions are incorrect\"\n                    << '\\n';\n            out\n                    << \"Make sure. that, if Your encryption function is a permutation, You enter it as a system of coordinate boolean functions\"\n                    << '\\n';\n            out << \"Boolean functions are entered as a vector of 0 and 1\" << '\\n';\n        } else {\n            std::vector<boolean> system;\n            for (auto &function: functions) {\n                boolean f(function);\n                if (!f.empty())\n                    system.push_back(f);\n            }\n            if (system.empty()) {\n                out\n                        << \"Your algorithm does not cannot ba attacked with differential attack, or entered functions are incorrect\"\n                        << '\\n';\n                out\n                        << \"Make sure. that, if Your encryption function is a permutation, You enter it as a system of coordinate boolean functions\"\n                        << '\\n';\n                out << \"Boolean functions are entered as a vector of 0 and 1\" << '\\n';\n            } else {\n                unsigned int start = clock();\n                int deg = system[0].degree();\n                size_t n;\n                if (text == \"ASCII\")\n                    n = 256;\n                else n = text.size();\n                auto **table = new size_t *[n];\n                for (size_t k = 0; k < n; ++k) {\n                    table[k] = new size_t[n];\n                    boolean delta_x(k, deg);\n                    for (size_t i = 0; i < n; ++i) {\n                        boolean delta_y, y;\n                        for (auto &j: system)\n                            y.push_back(j[i]);\n                        boolean x(i, deg);\n                        x += delta_x;\n                        size_t index = x.to_number();\n                        for (auto &j: system)\n                            delta_y.push_back(j[index]);\n                        delta_y += y;\n                        size_t eq = delta_y.to_number();\n                        table[k][i] = eq;\n                    }\n                    std::vector<size_t> v;\n                    for (size_t i = 0; i < n; ++i)\n                        v.push_back(0);\n                    for (size_t r = 0; r < n; ++r)\n                        v[table[k][r]] += 1;\n                    for (size_t i = 0; i < n; ++i)\n                        table[k][i] = v[i];\n                }\n                unsigned int end = clock();\n                unsigned int time = end - start;\n                // Вывод данных\n                out << '\\n';\n                for (size_t i = 0; i <= n; ++i) {\n                    for (size_t j = 0; j <= n; ++j) {\n                        if (i * j == 0) {\n                            if ((i == 0) && (j == 0))\n                                out << \"|     \";\n                            if ((i == 0) && (j != 0)) {\n                                size_t val = j - 1;\n                                boolean output(val, deg);\n                                out << ' ';\n                                for (int k = 0; k < deg; ++k)\n                                    out << output[k];\n                            }\n                            if ((i != 0) && (j == 0)) {\n                                size_t val = i - 1;\n                                boolean output(val, deg);\n                                out << \"| \";\n                                for (int k = 0; k < deg; ++k)\n                                    out << output[k];\n                            }\n                            out << \" |\";\n                        } else {\n                            out << \"  \" << table[i - 1][j - 1];\n                            for (size_t h = 0; h < deg - number_degree(table[i - 1][j - 1]); ++h)\n                                out << ' ';\n                            out << '|';\n                        }\n                    }\n                    out << '\\n';\n                }\n                out\n                        << '\\n'\n                        << \"Estimated time of analyzing given S-block to find most probable outcomes from certain entered text is \"\n                        << time << \" ns\" << '\\n';\n                for (size_t i = 0; i < n; ++i)\n                    delete[] table[i];\n                delete[] table;\n            }\n        }\n    }\n\n    void brute_force(std::ofstream &out) {\n        out << '\\n' << \" - BRUTE FORCE ATTACK:\" << '\\n';\n        size_t n;\n        if (text == \"ASCII\")\n            n = 256;\n        else\n            n = text.size();\n        out << '\\n' << \"This attack is always very long and needs many resources, in your case it will take about \";\n        out << n << \" factorial, multiplied by the time of one tact.\" << '\\n';\n    }\n\n    void linear_attack(std::ofstream &out) {\n        out << '\\n' << \" - LINEAR ATTACK:\" << '\\n';\n        if (functions.size() == 1) {\n            out\n                    << \"Your algorithm does not cannot ba attacked with linear attack, or entered functions are incorrect\"\n                    << '\\n';\n            out\n                    << \"Make sure. that, if Your encryption function is a permutation, You enter it as a system of coordinate boolean functions\"\n                    << '\\n';\n            out << \"Boolean functions are entered as a vector of 0 and 1\" << '\\n';\n        } else {\n            std::vector<boolean> system;\n            for (auto &function: functions) {\n                boolean f(function);\n                if (!f.empty())\n                    system.push_back(f);\n            }\n            if (system.empty()) {\n                out\n                        << \"Your algorithm does not cannot ba attacked with linear attack, or entered functions are incorrect\"\n                        << '\\n';\n                out\n                        << \"Make sure. that, if Your encryption function is a permutation, You enter it as a system of coordinate boolean functions\"\n                        << '\\n';\n                out << \"Boolean functions are entered as a vector of 0 and 1\" << '\\n';\n            } else {\n                unsigned int start = clock();\n                size_t n, deg = system[0].degree();\n                if (text == \"ASCII\")\n                    n = 256;\n                else n = text.size();\n                auto **table = new int *[n];\n                for (size_t i = 0; i < n; ++i) {\n                    table[i] = new int[n];\n                    boolean x_linear(i, deg);\n                    for (size_t j = 0; j < n; ++j) {\n                        table[i][j] = 0;\n                        boolean y_linear(j, deg);\n                        for (size_t h = 0; h < n; ++h) {\n                            boolean alfa(h, deg);\n                            boolean beta;\n                            for (auto &k: system)\n                                beta.push_back(k[h]);\n                            alfa *= x_linear;\n                            beta *= y_linear;\n                            int x = 0, y = 0;\n                            for (size_t t = 0; t < deg; ++t) {\n                                x ^= alfa[t];\n                                y ^= beta[t];\n                            }\n                            if (x == y)\n                                table[i][j] += 1;\n                        }\n                        table[i][j] = table[i][j] - n / 2;\n                    }\n                }\n                unsigned int end = clock();\n                unsigned int time = end - start;\n                // Вывод данных\n                out << '\\n';\n                for (size_t i = 0; i <= n; ++i) {\n                    for (size_t j = 0; j <= n; ++j) {\n                        if (i * j == 0) {\n                            if ((i == 0) && (j == 0))\n                                out << \"|     \";\n                            if ((i == 0) && (j != 0)) {\n                                size_t val = j - 1;\n                                boolean output(val, deg);\n                                out << ' ';\n                                for (size_t k = 0; k < deg; ++k)\n                                    out << output[k];\n                            }\n                            if ((i != 0) && (j == 0)) {\n                                size_t val = i - 1;\n                                boolean output(val, deg);\n                                out << \"| \";\n                                for (size_t k = 0; k < deg; ++k)\n                                    out << output[k];\n                            }\n                            out << \" |\";\n                        } else {\n                            if (table[i - 1][j - 1] > 0) {\n                                out << \" +\" << table[i - 1][j - 1];\n                                for (size_t h = 0; h < deg - number_degree(table[i - 1][j - 1]); ++h)\n                                    out << ' ';\n                                out << '|';\n                            }\n                            if (table[i - 1][j - 1] == 0) {\n                                out << \"  \" << table[i - 1][j - 1];\n                                for (size_t h = 0; h < deg - 1; ++h)\n                                    out << ' ';\n                                out << '|';\n                            }\n                            if (table[i - 1][j - 1] < 0) {\n                                out << ' ' << table[i - 1][j - 1];\n                                for (size_t h = 0; h < deg - number_degree(table[i - 1][j - 1]); ++h)\n                                    out << ' ';\n                                out << '|';\n                            }\n                        }\n                    }\n                    out << '\\n';\n                }\n                out\n                        << '\\n'\n                        << \"Estimated time to build needed approximations and analyse the probability of destabilization of given S-block is \"\n                        << time << \" ns\" << '\\n';\n                for (size_t i = 0; i < n; ++i)\n                    delete[] table[i];\n                delete[] table;\n            }\n        }\n    }\n};\n\n#endif //KURSOVAYA_1_HEADER_HPP\n", "meta": {"hexsha": "807f5539bc2a98b81f7439a94aecb9105145cd94", "size": 14445, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/header.hpp", "max_stars_repo_name": "MikhailZarif/Kursovaya_1", "max_stars_repo_head_hexsha": "db4633dd16ee86a5c621a3a9e74c5d63ce7bf9a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/header.hpp", "max_issues_repo_name": "MikhailZarif/Kursovaya_1", "max_issues_repo_head_hexsha": "db4633dd16ee86a5c621a3a9e74c5d63ce7bf9a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/header.hpp", "max_forks_repo_name": "MikhailZarif/Kursovaya_1", "max_forks_repo_head_hexsha": "db4633dd16ee86a5c621a3a9e74c5d63ce7bf9a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-25T15:57:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T15:57:27.000Z", "avg_line_length": 37.1336760925, "max_line_length": 148, "alphanum_fraction": 0.3463482174, "num_tokens": 3202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.44869224235349775}}
{"text": "/*====================================================================\n   bouncingBallBenchmark.cc\n   Copyright (c) 2019 Matthew Millard <matthew.millard@iwr.uni-heidelberg.de>\n   Licensed under the zlib license. See LICENSE for more details.\n *///=================================================================\n\n\n#include <string>\n#include <iostream>\n#include <stdio.h> \n#include <rbdl/rbdl.h>\n#include <rbdl/addons/luamodel/luamodel.h>\n#include <rbdl/addons/geometry/geometry.h>\n#include \"csvtools.h\"\n\n#include \"ContactToolkit.h\"\n\n#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp>\n#include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n#include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>\n#include <boost/numeric/odeint/stepper/generation/make_controlled.hpp>\n//using namespace std;\nusing namespace boost::numeric::odeint;\n\nusing namespace RigidBodyDynamics;\nusing namespace RigidBodyDynamics::Math;\n\n//====================================================================\n// Boost stuff\n//====================================================================\n\n\n\n\ntypedef std::vector< double > state_type;\ntypedef runge_kutta_cash_karp54< state_type > error_stepper_type;\ntypedef controlled_runge_kutta< error_stepper_type > controlled_stepper_type;\n\n\nclass rbdlToBoost {\n\n  public:\n    rbdlToBoost(Model* model,\n                std::string &ballName,\n                double ballRadius,\n                Vector3d &pointOnPlane, \n                Vector3d &planeNormal,\n                double stiffness,\n                double exponent,\n                double damping,\n                double staticFrictionSpeed,\n                double staticFrictionCoefficient,\n                double dynamicFrictionSpeed,\n                double dynamicFrictionCoefficient,\n                double viscousFrictionSlope,\n                unsigned int numberOfWorkTermsInState\n                ):model(model),r(ballRadius),r0P0(pointOnPlane),\n                  eN0(planeNormal),k(stiffness),p(exponent),beta(damping),\n                  staticFrictionSpeed(staticFrictionSpeed),\n                  staticFrictionCoefficient(staticFrictionCoefficient),\n                  dynamicFrictionSpeed(dynamicFrictionSpeed),\n                  dynamicFrictionCoefficient(dynamicFrictionCoefficient),\n                  viscousFrictionSlope(viscousFrictionSlope),\n                  numberOfWorkTermsInState(numberOfWorkTermsInState)\n    {\n\n        q = VectorNd::Zero(model->dof_count);\n        qd = VectorNd::Zero(model->dof_count);\n        qdd = VectorNd::Zero(model->dof_count);\n        tau = VectorNd::Zero(model->dof_count);\n        fext.resize(model->mBodies.size());\n        for(unsigned int i=0; i<fext.size();++i){\n            fext[i]=SpatialVector::Zero();\n        }\n        ballId = model->GetBodyId(ballName.c_str());\n        fK0n = Vector3dZero;\n        tK0n = Vector3dZero;\n        fK0t = Vector3dZero;\n        tK0t = Vector3dZero;\n\n        //1a. The regularized friction model is created and printed to file\n        ContactToolkit::createRegularizedFrictionCoefficientCurve(\n                          staticFrictionSpeed, staticFrictionCoefficient,\n                          dynamicFrictionSpeed,dynamicFrictionCoefficient,\n                          viscousFrictionSlope,\"mu\",frictionCoefficientCurve);\n\n        frictionCoefficientCurve.printCurveToCSVFile(\"../output/\",\n                           \"frictionCoefficientCurve\",0,dynamicFrictionSpeed*2);\n        printf(\"Wrote: ../output/frictionCoefficentCurve.csv\\n\");\n\n        //Set the velocity at which the relaxed method is used to compute\n        //the direction vector of the tangential velocity of the contact\n        //point\n        veps = staticFrictionSpeed/100.0;\n\n        //If veps is too small, we really might have problems\n        assert(veps > std::sqrt(std::numeric_limits<double>::epsilon()));\n\n\n    }\n\n    //1b. The state derivative for this model is called by Boost whenever the \n    //    code for the 'operator()' function is called\n    void operator() (const state_type &x,\n                     state_type &dxdt, \n                     const double t){\n\n        //1c. The state x is split into generalized positions (q), generalized\n        //    velocities (qdd). Here tau is set to 0 because we are not \n        //    applying any generlized forces: the ball contact/friction forces\n        //    are applied as external forces\n        //q\n        int j = 0;\n        for(unsigned int i=0; i<model->q_size; i++){                \n            q[i] = double(x[j]);\n            j++;\n        }\n\n        //qd\n        for(unsigned int i=0; i<model->qdot_size; i++){\n            qd[i] = double(x[j]);\n            j++;\n        }\n\n        //tau = 0\n        for(unsigned int i=0; i<model->qdot_size; i++){                \n            tau[i] = 0;\n        }\n\n        //2a. To evaluate the contact forces we must see if the ball is interpenetrating\n        //    the ground. Outside of FEA modelling it is common to allow (non deforming)\n        //    geometry to intepenetrate and to use the interpenetration to compute\n        //    contact forces. Here we go with the simplest option and map the \n        //    depth of penetration to a contact force.\n        r0B0 = CalcBodyToBaseCoordinates(*model,q,ballId,Vector3dZero,true);\n        ContactToolkit::calcSpherePlaneContactPointPosition(r0B0,r,eN0,r0K0);\n\n        //if the contact point is in the sphere compute contact data\n        z = (r0K0-r0P0).dot(eN0);\n        dz=0.; //this is zero until contact is made\n        if( z < 0. ){\n\n          //2b. If the sphere is in contact with the plane, we must get the position and\n          //velocity of the contact point.\n\n          //Get the point of contact resolved in the coordinates of the ball          \n          EB0   = CalcBodyWorldOrientation(*model,q,ballId,true);\n          rBKB  = EB0*(r0K0-r0B0);\n\n          //Get the velocity of the point of contact\n          v0K0 = CalcPointVelocity(*model,q,qd,ballId,rBKB,true);\n\n          //Evaluate Hunt-Crossley Contact forces\n          dz = (v0K0).dot(eN0); //assuming the plane is fixed.\n\n          //2c. Now we can evaluate the contact forces using a Hunt-Crossley contact model\n          //    This is a popular contact model because it is numerically well behaved.\n          //    See the comments in ContactToolkit.h above the function definition\n          //    for calcHuntCrossleyContactForce for further details.          \n          ContactToolkit::calcHuntCrossleyContactForce(z,dz,k,p,beta,hcInfo);\n\n          //2d. To apply this contact force as an external force in RBDL, we must first\n          //    transform it into a spatial wrench that is resolved in the Root frame.\n          //    Here we turn the scalar contact force into a vector, and then evaluate\n          //    the torque that this force vector produces about the Root frame  \n          fK0n = hcInfo.force*eN0;\n          tK0n = VectorCrossMatrix(r0K0)*fK0n;\n\n          //2e. Now we can use the tangential velocity of the contact point of the ball\n          //    to evaluate the coefficient of friction, and then the friction forces\n          v0K0t = v0K0 - dz*eN0;\n          ContactToolkit::calcTangentialVelocityDirection(v0K0t,veps,eT0);\n\n          mu = frictionCoefficientCurve.calcValue(v0K0t.norm());\n\n          //2f. As with the contact model we evaluate the force the friction model applies\n          //    to the ball and also the torque it generates about the ROOT frame          \n          fK0t = -mu*hcInfo.force*eT0;\n          tK0t = VectorCrossMatrix(r0K0)*fK0t;\n\n          //2g. The total wrench generated by the contact and friction models is applied to\n          //    the entry in the vector fext that corresponds to the ball.            \n          fext[ballId][0] = tK0n[0] + tK0t[0];\n          fext[ballId][1] = tK0n[1] + tK0t[1];\n          fext[ballId][2] = tK0n[2] + tK0t[2];\n\n          fext[ballId][3] = fK0n[0] + fK0t[0];\n          fext[ballId][4] = fK0n[1] + fK0t[1];\n          fext[ballId][5] = fK0n[2] + fK0t[2];\n\n        }else{\n          //zero the entry of fext associated with the ball.          \n          fext[ballId]=SpatialVector::Zero();\n          hcInfo.force        = 0.;\n          hcInfo.springForce  = 0.;\n          hcInfo.dampingForce = 0.;          \n          fK0n = Vector3dZero;\n          tK0n = Vector3dZero;\n          fK0t = Vector3dZero;\n          tK0t = Vector3dZero;\n        }\n\n        //3a. Now the generalized accelerations of the ball can be computed\n        ForwardDynamics(*model,q,qd,tau,qdd,&fext);\n\n        //3b. The state derivative dxdt is now formed using qd, and qdd. The \n        //    derivatives of the  work done by the contact and friction models \n        //    is also stored so that we  can track the system energy of the \n        //    system through the simulation\n        j = 0;\n        for(unsigned int i = 0; i < model->q_size; i++){\n            dxdt[j] = double(qd[i]);\n            j++;\n        }\n        for(unsigned int i = 0; i < model->qdot_size; i++){\n            dxdt[j] = double(qdd[i]);\n            j++;\n        }\n\n        dworkN = hcInfo.force*dz;\n        dxdt[j] = dworkN;\n        j++;\n        dxdt[j] = fK0t.dot(v0K0t);\n        j++;\n        assert((numberOfWorkTermsInState\n                + model->q_size \n                + model->qdot_size) == j);\n\n    }\n\n    /*\n      Ascii Vector Notation:\n      rBKB\n        r: vector\n        B: from the origin of the Ball frame\n        K: to the contact point K\n        B: expressed in the coordinates of the ball frame.\n      EB0:\n        E: rotation matrix\n        B: to Frame B\n        0: from Frame 0\n      eN0:\n        e: unit vector\n        N: Normal direction\n        0: expressed in the coordinates of the root frame (0)\n      fK0\n        f: force\n        K: At point K\n        0: expressed in the coordinates of the root frame\n      tK0\n        t: torque\n        K: At point K\n        0: expressed in the coordinates of the root frame\n\n    */\n\n    //Multibody Variables\n    Model* model;\n    VectorNd q, qd, qdd, tau;    \n\n    //Normal-Contact Model Working Variables\n    unsigned int ballId;\n    double z, dz; //pentration depth and velocity\n    HuntCrossleyContactInfo hcInfo;\n    std::vector< SpatialVector > fext;\n    double dworkN, dworkT; //Work in the normal and tangential directions\n    double mu;      //Friction coefficient\n    Matrix3d EB0;   //Orientation of the ball expressed in the Root frame\n    Vector3d r0B0;  //Position of the ball\n    Vector3d rBKB;  //B : ball.\n    Vector3d r0K0;  //K : contact point\n    Vector3d v0K0;  //velocity of the contact point\n    Vector3d v0K0t; //tangential velocity of the contact point\n    Vector3d r0P0;  //Origin of the plane\n    Vector3d eN0;   //Normal of the plane\n    Vector3d eT0;   //Tangental direction of the plane: in 2d this isn't necessary\n                    //here we compute it to show how this is done in a\n                    //numerically stable way in 3d.\n    Vector3d fK0n, tK0n; //contact force and moment\n    Vector3d fK0t, tK0t; //tangential friction force and moment\n\n    //Normal Contact-Model Parameters\n    double r; //ball radius\n    double k; //stiffness\n    double p; //exponential power on the spring compression\n    double beta; //damping\n\n    //Friction Model Parameters: see ContactToolkit \n    // createRegularizedFrictionCoefficientCurve for details\n    double staticFrictionSpeed;\n    double staticFrictionCoefficient;\n    double dynamicFrictionSpeed;\n    double dynamicFrictionCoefficient;\n    double viscousFrictionSlope;\n    double veps; //Velocity at which the relaxed method is used to compute\n                 //the direction vector of the tangential velocity\n    RigidBodyDynamics::Addons::Geometry\n        ::SmoothSegmentedFunction frictionCoefficientCurve;\n\n    unsigned int numberOfWorkTermsInState;\n\n};\n\nstruct pushBackStateAndTime\n{\n    std::vector< state_type >& states;\n    std::vector< double >& times;\n\n    pushBackStateAndTime( std::vector< state_type > &states , \n                              std::vector< double > &times )\n    : states( states ) , times( times ) { }\n\n    void operator()( const state_type &x , double t )\n    {\n        states.push_back( x );\n        times.push_back( t );\n    }\n};\n\nvoid f(const state_type &x, state_type &dxdt, const double t);\n\n/* Problem Constants */\nint main (int argc, char* argv[]) {\n    rbdl_check_api_version (RBDL_API_VERSION);\n\n  RigidBodyDynamics::Model model;\n\n  std::string fileName(\"../model/ballPlaneContact.lua\");\n  std::string ballName(\"Ball\");\n\n  //0a. ballPlaneContact.lua model is read in\n  if (!Addons::LuaModelReadFromFile(fileName.c_str(),&model)){\n    std::cerr << \"Error loading LuaModel: \" << fileName << std::endl;\n    abort();\n  }\n\n  //0b. Contact and friction parameters are set (more on these later)\n  double radius = 0.5;\n  Vector3d pointOnPlane = Vector3d(0.,0.,0.);\n  Vector3d planeNormal  = Vector3d(0.,0.,1.);\n\n  //Hunt-Crossley contact terms. See\n  // ContactToolkit::calcHuntCrossleyContactForce for details\n  double exponent = 2.0; //The spring force will increase with the deflection squared.\n  double stiffness = 9.81/pow(0.01,2.); //The ball will settle to 1cm penetration\n  double damping = 0.1; //lightly damped  \n\n  //Friction model terms. See\n  // ContactToolkit::createRegularizedFrictionCoefficientCurve for details\n  double staticFrictionSpeed        = 0.001;\n  double staticFrictionCoefficient  = 0.8;\n  double dynamicFrictionSpeed       = 0.01;\n  double dynamicFrictionCoeffient   = 0.6;\n  double viscousFrictionSlope       = 0.1;\n\n  unsigned int numWorkTermsInState = 2; //1 normal work term\n                                        //1 friction term\n\n\n  VectorNd q, qd, x, tau;\n  q.resize(model.dof_count);\n  qd.resize(model.dof_count);\n  tau.resize(model.dof_count);\n  x.resize(model.dof_count*2);\n  q.setZero();\n  qd.setZero();\n  x.setZero();\n  tau.setZero();\n\n  q[1] = 1.; //ball starts 1m off the ground\n  qd[0]= 1.;\n\n  for(unsigned int i=0; i<q.rows();++i){\n    x[i] =q[i];\n    x[i+q.rows()] = qd[i];\n  }\n\n  //0c. An object that Boost can integrate is instantiated:\n  rbdlToBoost rbdlModel(&model,\n                        ballName,\n                        radius,\n                        pointOnPlane,\n                        planeNormal,\n                        stiffness,\n                        exponent,\n                        damping,\n                        staticFrictionSpeed,\n                        staticFrictionCoefficient,\n                        dynamicFrictionSpeed,\n                        dynamicFrictionCoeffient,\n                        viscousFrictionSlope,\n                        numWorkTermsInState);\n\n    //4a. The model state is initialized\n    state_type xState(x.size()+numWorkTermsInState);\n    state_type dxState(x.size()+numWorkTermsInState);\n    for(unsigned int i=0; i<x.size(); ++i){\n      xState[i]   = x[i];\n    }\n\n    //4b. This model is integrated forward in time from t0 to t1 and is evaluated\n    //    at npts between these time points\n    double t;\n    double t0 = 0;\n    double t1 = 1.0;\n    unsigned int npts      = 100;\n\n    double absTolVal = 1e-8;\n    double relTolVal = 1e-8;\n\n    double dt = (t1-t0)/(npts-1);\n    double ke,pe,w =0;\n    unsigned int k=0;\n\n    std::vector<std::vector< double > > matrixData, matrixForceData;\n    std::vector<std::vector< double > > matrixErrorData;\n    std::vector< double > rowData(model.dof_count+1);\n    std::vector< double > rowForceData(10);\n    std::vector< double > rowErrorData(2);\n\n    double a_x = 1.0 , a_dxdt = 1.0;\n    controlled_stepper_type\n    controlled_stepper(\n        default_error_checker< double ,\n                               range_algebra ,\n                               default_operations >\n        ( absTolVal , relTolVal , a_x , a_dxdt ) );\n\n    double tp = 0;\n    rowData[0] = 0;\n    for(unsigned int z=0; z < model.dof_count; z++){\n        rowData[z+1] = xState[z];\n    }\n    matrixData.push_back(rowData);\n\n    SpatialVector fA0 = SpatialVector::Zero();\n    for(unsigned int i=0; i<rowForceData.size();++i){\n      rowForceData[i]=0.;\n    }\n\n    matrixForceData.push_back(rowForceData);\n\n    double kepe0 = 0;\n    double th,dth;\n\n    //                 ,             ,             ,             ,             ,             ,             ,\n    printf(\"Columns below:\\n\");\n    printf(\"          t,        theta,   d/dt theta,           ke,           pe,            w, ke+pe-w-kepe0\\n\");\n\n    for(unsigned int i=0; i<= npts; ++i){\n      t = t0 + dt*i;\n\n      integrate_adaptive(\n          controlled_stepper ,\n          rbdlModel , xState , tp , t , (t-tp)/10 );\n      tp = t;\n\n      //4c. At each time point the q's, qd's, and the work done on the ball by the \n      //    contact & friction model is saved\n\n      for(unsigned int j=0; j<x.rows();++j){\n        x[j] = xState[j];\n      }\n      k=0;\n      for(unsigned int j=0; j<model.q_size;++j){\n        q[j] = xState[k];\n        ++k;\n      }\n      for(unsigned int j=0; j<model.qdot_size;++j){\n        qd[j] = xState[k];\n        ++k;\n      }\n      w = 0.;\n      for(unsigned int j=0; j<numWorkTermsInState;++j){\n        w += xState[k];\n        ++k;\n      }\n\n      //4d. The q's, qd's, and work terms are used to numerically evaluate the system\n      //    energy of the ball less the work done on it: ke+pe-w, where \n      //    ke is kinetic energy, pe is potential energy, and w is work.\n      pe = Utils::CalcPotentialEnergy(model,\n                                      q,true);\n\n      ke = Utils::CalcKineticEnergy(model,\n                                    q,\n                                    qd,true);\n\n      rowData[0] = t;\n      for(unsigned int z=0; z < model.dof_count; z++){\n          rowData[z+1] = xState[z];\n      }\n      matrixData.push_back(rowData);\n\n    //4e. This is evaluated relative to the system energy of the ball at the \n    //    beginning of the simulation. If the integrator were perfect the sum of \n    //    ke+pe-w-kepe0 would be numerically zero. Because numerical integration is\n    //    not perfect this quantity (printed to screen) will drift over time.\n    //    You can see this if you adjust the absolute and relative tolerances\n    //    (set between 4b and 4c) on the integrator and re-run the simulations.\n    //    drift will be larger with looser integration tolerances.      \n      if(i==0) kepe0 = (ke+pe-w);\n\n      rowErrorData[0] = t;\n      rowErrorData[1] = (ke + pe -w) - kepe0;\n      matrixErrorData.push_back(rowErrorData);\n\n      printf(\"%e, %e, %e, %e, %e, %e, %e\\n\",\n                  t, q[2],qd[2],ke,\n                  pe,w,(ke+pe-w-kepe0));\n\n      //Make sure the model state is up to date.\n      rbdlModel(xState,dxState,tp);\n\n      //4f. Here we grab quantities that we would like to save\n      rowForceData[0] = t;\n      //contact point location\n      rowForceData[1] = rbdlModel.r0K0[0];\n      rowForceData[2] = rbdlModel.r0K0[1];\n      rowForceData[3] = rbdlModel.r0K0[2];\n      //force at the contact point\n      rowForceData[4] = rbdlModel.fK0n[0] + rbdlModel.fK0t[0];\n      rowForceData[5] = rbdlModel.fK0n[1] + rbdlModel.fK0t[1];\n      rowForceData[6] = rbdlModel.fK0n[2] + rbdlModel.fK0t[2];\n      //moment at the contact point\n      rowForceData[7] = 0.;//This contact model generates no contact moments\n      rowForceData[8] = 0.;//This contact model generates no contact moments\n      rowForceData[9] = 0.;//This contact model generates no contact moments\n\n      matrixForceData.push_back(rowForceData);\n\n\n      bool here=true;\n\n    }\n    printf(\"Columns above:\\n\");\n    printf(\"          t,        theta,   d/dt theta,           ke,           pe,            w, ke+pe-w-kepe0\\n\");\n\n\n    //5a. Finally we write the simulation data to file\n    std::cout << std::endl;\n    std::string emptyHeader(\"\");\n    std::string fileNameOut(\"../output/animation.csv\");\n    printMatrixToFile(matrixData,emptyHeader,fileNameOut);\n    printf(\"Wrote: ../output/animation.csv (meshup animation file)\\n\");\n    fileNameOut.assign(\"../output/animationForces.ff\");\n    printMatrixToFile(matrixForceData,emptyHeader,fileNameOut);\n    printf(\"Wrote: ../output/animationForces.ff (meshup force file)\\n\");\n\n    fileNameOut = \"../output/kepe.csv\";\n    std::string header(\"time,systemEnergy,\");\n    printMatrixToFile(matrixErrorData,header,fileNameOut);\n    printf(\"Wrote: ../output/kepe.csv (simulation data)\\n\");\n\n\n\n   return 0;\n        \n}\n", "meta": {"hexsha": "938e06315aa64c257b95429338443a2ff93dcca5", "size": 20395, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/bouncingBall/src/bouncingBallBenchmark.cc", "max_stars_repo_name": "ju6ge/rbdl-orb", "max_stars_repo_head_hexsha": "321e20e80e2859a3a2ab43629c7c26c1020cb6f6", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-04-30T19:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T11:30:23.000Z", "max_issues_repo_path": "examples/bouncingBall/src/bouncingBallBenchmark.cc", "max_issues_repo_name": "ju6ge/rbdl-orb", "max_issues_repo_head_hexsha": "321e20e80e2859a3a2ab43629c7c26c1020cb6f6", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-04T23:16:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T23:37:28.000Z", "max_forks_repo_path": "examples/bouncingBall/src/bouncingBallBenchmark.cc", "max_forks_repo_name": "ju6ge/rbdl-orb", "max_forks_repo_head_hexsha": "321e20e80e2859a3a2ab43629c7c26c1020cb6f6", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-02-01T20:38:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T22:28:24.000Z", "avg_line_length": 36.4196428571, "max_line_length": 113, "alphanum_fraction": 0.5931846041, "num_tokens": 5313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.44867501078757144}}
{"text": "#include \"graph.h\"\n#include \"grDB.h\"\n#include <map>\n#include <vector>\n#include <set>\n#include <boost/unordered_map.hpp>\n#include <boost/functional/hash.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <chrono>\n#include <cmath>\n\n// Manhattan distance heuristic\ntemplate<typename Graph, typename CostType>\nclass distance_heuristic: public boost::astar_heuristic<Graph, CostType> {\npublic:\n\tdistance_heuristic(const unordered_set<Vertex> &goals, Graph graph) :\n\t\t\tm_graph(graph), m_goals(goals) {\n\t}\n\tCostType operator()(Vertex u) {\n\t\tCostType result = INFINITY;\n\t\tfor (Vertex m_goal : m_goals) {\n\t\t\tCostType dx = m_graph[m_goal].x - m_graph[u].x;\n\t\t\tCostType dy = m_graph[m_goal].y - m_graph[u].y;\n\t\t\tCostType dz = m_graph[m_goal].z - m_graph[u].z;\n\t\t\tCostType tmp = fabs(dx) + fabs(dy) + fabs(dz);\n\t\t\tif (tmp < result)\n\t\t\t\tresult = tmp;\n\t\t}\n\t\treturn result;\n\t}\nprivate:\n\tGraph m_graph;\n\tunordered_set<Vertex> m_goals;\n};\n\nstruct found_goal {\n\tVertex goal;\n};\n\nstruct astar_goal_visitor: public boost::default_astar_visitor {\n\tastar_goal_visitor(const unordered_set<Vertex> &goals) :\n\t\t\tm_goals(goals) {\n\t}\n\tvoid examine_vertex(Vertex u, const Graph &g) {\n\t\tif (m_goals.find(u) != m_goals.end()) {\n\t\t\tthrow found_goal( { u });\n\t\t}\n\t}\nprivate:\n\tunordered_set<Vertex> m_goals;\n\t// boost::unordered_map<Vertex, Vertex, vertex_hash> m_predecessor;\n};\n\nstd::pair<double, vector<Vertex>> RoutingDB::a_star(Graph &graph3D,\n\t\tconst Vertex &s, const unordered_set<Vertex> &goals) const {\n\tusing namespace boost;\n\ttypedef boost::unordered_map<Vertex, Vertex, vertex_hash> pred_map;\n\tpred_map predecessor;\n\tboost::associative_property_map<pred_map> pred_pmap(predecessor);\n\n\ttypedef boost::unordered_map<Vertex, double, vertex_hash> dist_map;\n\tdist_map distance;\n\tboost::associative_property_map<dist_map> dist_pmap(distance);\n\n\ttypedef boost::unordered_map<Vertex, double, vertex_hash> cost_map;\n\tcost_map cost;\n\tboost::associative_property_map<cost_map> cost_pmap(cost);\n\n\ttypedef boost::unordered_map<EdgeType, double, edge_hash> wt_map;\n\twt_map weight;\n\tEdgeIter e, eend;\n\tfor (tie(e, eend) = edges(graph3D); e != eend; ++e) {\n\t\tweight[*e] = graph3D[*e].weight;\n\t}\n\tGraph::out_edge_iterator oe, oeend;\n\ttie(oe, oeend) = out_edges(s, graph3D);\n\tboost::associative_property_map<wt_map> wt_pmap(weight);\n\n\tastar_goal_visitor visitor(goals);\n\n\tauto heur = distance_heuristic<Graph, double>(goals, graph3D);\n\tvector<Vertex> vecPath;\n\ttry {\n\t\tVertexIter ui, ui_end;\n\t\tfor (boost::tie(ui, ui_end) = vertices(graph3D); ui != ui_end; ++ui) {\n\t\t\tput(dist_pmap, *ui, INFINITY);\n\t\t\tput(cost_pmap, *ui, INFINITY);\n\t\t\tput(pred_pmap, *ui, *ui);\n\t\t\tvisitor.initialize_vertex(*ui, graph3D);\n\t\t}\n\t\tput(dist_pmap, s, 0);\n\t\tput(cost_pmap, s, heur(s));\n\t\tboost::astar_search_no_init_tree(graph3D, s, heur,\n\t\t\t\tweight_map(wt_pmap).predecessor_map(pred_pmap).distance_map(\n\t\t\t\t\t\tdist_pmap).visitor(visitor));\n\t\t// printf(\"No feasible path.\\n\");\n\t\treturn make_pair(INFINITY, vecPath);\n\t} catch (found_goal &fg) {\n\t\t// Walk backwards from the goal through the predecessor chain adding\n\t\t// vertices to the solution path.\n\t\t//printf(\"Path found: \");\n\t\t//isFeasible = true;\n\t\tdouble wl = 0;\n\t\tfor (Vertex u = fg.goal; u != s; u = predecessor[u]) {\n\t\t\t//\tprintf(\"(%d,%d,%d)-\", graph3D[u].x, graph3D[u].y, graph3D[u].z);\n\t\t\t// auto r = edge(u, predecessor[u], graph3D);\n\t\t\t// assert(r.second);\n\t\t\tvecPath.push_back(u);\n\t\t\t//\tgraph3D[r.first].isPath = true;\n\t\t\t++wl;\n\t\t}\n\t\tvecPath.push_back(s);\n\t\t// printf(\"(%d,%d,%d)\\n\", graph3D[s].x, graph3D[s].y, graph3D[s].z);\n\t\t// cout << \"WL = \" << wl << endl;\n\t\treturn make_pair(wl, vecPath);\n\t}\n}\n\nunordered_set<Vertex> RoutingDB::build_goals(const Vpin &vp, const int xlLim,\n\t\tconst int xuLim, const int ylLim, const int yuLim,\n\t\tconst int zlLim) const {\n\tusing namespace boost;\n\tstd::unordered_set<Vertex> goals;\n\tint X = xuLim - xlLim + 1, Y = yuLim - ylLim + 1;\n\tfor (auto gv : vp.gnetGrids) {\n\t\tgoals.insert(\n\t\t\t\t(gv._z - zlLim) * Y * X + (gv._y - ylLim) * X\n\t\t\t\t\t\t+ (gv._x - xlLim));\n\t}\n\treturn goals;\n}\n\nGraph RoutingDB::build_graph(const size_t gnetId,\n\t\tconst std::unordered_set<Gcell, HashGcell3d> &bannedPts,\n\t\tconst int xlLim, const int xuLim, const int ylLim, const int yuLim,\n\t\tconst int zlLim, const int zuLim) const {\n\tusing namespace boost;\n\tGraph graph3D;\n\t// vector<double> capacities;\n\t// vector<Location> locations;\n\t// boost::property_map<Graph, boost::edge_index_t>::type edge_index_map = get(boost::edge_index, graph2D);\n\t// boost::property_map<Graph, boost::vertex_index_t>::type vertex_index_map = get(boost::vertex_index, graph2D);\n\tint X = xuLim - xlLim + 1, Y = yuLim - ylLim + 1;\n\tfor (int z = zlLim; z <= zuLim; ++z) {\n\t\tfor (int y = ylLim; y <= yuLim; ++y) {\n\t\t\tfor (int x = xlLim; x <= xuLim; ++x) {\n\t\t\t\tVertex v = add_vertex(graph3D);\n\t\t\t\tgraph3D[v].x = x;\n\t\t\t\tgraph3D[v].y = y;\n\t\t\t\tgraph3D[v].z = z;\n\t\t\t}\n\t\t}\n\t}\n\tint cap, dem, blk;\n\tbool vacant, banned;\n\tfor (int x = xlLim; x <= xuLim; ++x) {\n\t\tfor (int y = ylLim; y <= yuLim; ++y) {\n\t\t\tif (x > xlLim) {\n\t\t\t\tfor (int z = zlLim; z <= zuLim; ++z) {\n\t\t\t\t\tif (getRoutingDir(z) == H) {\n\t\t\t\t\t\tsize_t edgeId = findEdge(x - 1, y, z);\n\t\t\t\t\t\tcap = getEdgeCap(edgeId);\n\t\t\t\t\t\tdem = getEdgeDemand(edgeId);\n\t\t\t\t\t\tblk = getEdgeBlk(edgeId);\n\t\t\t\t\t\tvacant = _gnets[gnetId]._occupiedEdges.find(edgeId)\n\t\t\t\t\t\t\t\t== _gnets[gnetId]._occupiedEdges.end();\n\t\t\t\t\t\tbanned = (bannedPts.find(Gcell(x - 1, y, z))\n\t\t\t\t\t\t\t\t!= bannedPts.end()\n\t\t\t\t\t\t\t\t|| bannedPts.find(Gcell(x, y, z))\n\t\t\t\t\t\t\t\t\t\t!= bannedPts.end());\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcap = 0;\n\t\t\t\t\t\tdem = 0;\n\t\t\t\t\t\tblk = 0;\n\t\t\t\t\t\tvacant = false;\n\t\t\t\t\t\tbanned = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (cap > dem + blk && vacant && !banned) {\n\t\t\t\t\t\tauto r = add_edge(\n\t\t\t\t\t\t\t\tvertex(\n\t\t\t\t\t\t\t\t\t\t(z - zlLim) * Y * X + (y - ylLim) * X\n\t\t\t\t\t\t\t\t\t\t\t\t+ (x - xlLim), graph3D),\n\t\t\t\t\t\t\t\tvertex(\n\t\t\t\t\t\t\t\t\t\t(z - zlLim) * Y * X + (y - ylLim) * X\n\t\t\t\t\t\t\t\t\t\t\t\t+ (x - 1 - xlLim), graph3D),\n\t\t\t\t\t\t\t\tgraph3D);\n\t\t\t\t\t\tassert(r.second);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (y > ylLim) {\n\t\t\t\tfor (int z = zlLim; z <= zuLim; ++z) {\n\t\t\t\t\tif (getRoutingDir(z) == V) {\n\t\t\t\t\t\tsize_t edgeId = findEdge(x, y - 1, z);\n\t\t\t\t\t\tcap = getEdgeCap(edgeId);\n\t\t\t\t\t\tdem = getEdgeDemand(edgeId);\n\t\t\t\t\t\tblk = getEdgeBlk(edgeId);\n\t\t\t\t\t\tvacant = _gnets[gnetId]._occupiedEdges.find(edgeId)\n\t\t\t\t\t\t\t\t== _gnets[gnetId]._occupiedEdges.end();\n\t\t\t\t\t\tbanned = (bannedPts.find(Gcell(x, y - 1, z))\n\t\t\t\t\t\t\t\t!= bannedPts.end()\n\t\t\t\t\t\t\t\t|| bannedPts.find(Gcell(x, y, z))\n\t\t\t\t\t\t\t\t\t\t!= bannedPts.end());\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcap = 0;\n\t\t\t\t\t\tdem = 0;\n\t\t\t\t\t\tblk = 0;\n\t\t\t\t\t\tvacant = false;\n\t\t\t\t\t\tbanned = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (cap > dem + blk && vacant && !banned) {\n\t\t\t\t\t\tauto r = add_edge(\n\t\t\t\t\t\t\t\tvertex(\n\t\t\t\t\t\t\t\t\t\t(z - zlLim) * Y * X + (y - ylLim) * X\n\t\t\t\t\t\t\t\t\t\t\t\t+ (x - xlLim), graph3D),\n\t\t\t\t\t\t\t\tvertex(\n\t\t\t\t\t\t\t\t\t\t(z - zlLim) * Y * X\n\t\t\t\t\t\t\t\t\t\t\t\t+ (y - 1 - ylLim) * X\n\t\t\t\t\t\t\t\t\t\t\t\t+ (x - xlLim), graph3D),\n\t\t\t\t\t\t\t\tgraph3D);\n\t\t\t\t\t\tassert(r.second);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int z = zlLim + 1; z <= zuLim; ++z) {\n\t\t\t\tsize_t viaId = findVia(x, y, z - 1);\n\t\t\t\tcap = getViaCap(viaId);\n\t\t\t\tdem = getViaDemand(viaId);\n\t\t\t\tvacant = _gnets[gnetId]._occupiedVias.find(viaId)\n\t\t\t\t\t\t== _gnets[gnetId]._occupiedVias.end();\n\t\t\t\tbanned = (bannedPts.find(Gcell(x, y, z - 1)) != bannedPts.end()\n\t\t\t\t\t\t|| bannedPts.find(Gcell(x, y, z)) != bannedPts.end());\n\t\t\t\tif (cap > dem && vacant && !banned) {\n\t\t\t\t\tauto r = add_edge(\n\t\t\t\t\t\t\tvertex(\n\t\t\t\t\t\t\t\t\t(z - zlLim) * Y * X + (y - ylLim) * X\n\t\t\t\t\t\t\t\t\t\t\t+ (x - xlLim), graph3D),\n\t\t\t\t\t\t\tvertex(\n\t\t\t\t\t\t\t\t\t(z - 1 - zlLim) * Y * X + (y - ylLim) * X\n\t\t\t\t\t\t\t\t\t\t\t+ (x - xlLim), graph3D), graph3D);\n\t\t\t\t\tassert(r.second);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn graph3D;\n}\n\nbool comp_x(Gcell i, Gcell j) {\n\treturn i._x < j._x;\n}\nbool comp_y(Gcell i, Gcell j) {\n\treturn i._y < j._y;\n}\n\nstd::tuple<double, vector<int>, vector<int>, int,\n\t\tstd::unordered_set<Gcell, HashGcell3d>> RoutingDB::rerouteNet(\n\t\tconst Layout &layout, Vpin &vp,\n\t\tconst std::unordered_set<Gcell, HashGcell3d> &bannedPts,\n\t\tconst int zlLim, const int zuLim, const int maxMargin,\n\t\tconst bool singleMargin, const bool writeToDB, const bool updateRoot) {\n\t// Connect one v-pin to its remaining net\n\tusing namespace boost;\n\tauto terminals = vp.gnetVertices;\n\tstd::unordered_set<Gcell, HashGcell3d> addlBannedPts;\n\tterminals.insert(Gcell(vp.xCoord, vp.yCoord, vp.zCoord));\n\tint margin = singleMargin ? maxMargin : 0;\n\tint next_margin = 0;\n\tdouble wl = INFINITY;\n\tbool isFeasible = false;\n\tdouble minmhd = INFINITY;\n\tstd::pair<double, vector<Vertex>> res;\n\tGraph g;\n\tstd::vector<int> addedEdges, addedVias;\n\tint viaID = findVia(vp.xCoord, vp.yCoord, vp.zCoord);\n\tif (getViaDemand(viaID) >= getViaCap(viaID)) {\n\t\treturn make_tuple(wl, addedEdges, addedVias, margin, addlBannedPts); // infeasible\n\t}\n\t// add new vpin\n\t// addViaDemand(viaID);\n\t// addedVias.push_back(viaID);\n\twhile (margin <= maxMargin) {\n// cout << \"margin = \" << margin << endl;\n\t\tint xlLim = max(\n\t\t\t\tmin_element(terminals.begin(), terminals.end(), comp_x)->_x\n\t\t\t\t\t\t- margin, 0);\n\t\tint xuLim = min(\n\t\t\t\tmax_element(terminals.begin(), terminals.end(), comp_x)->_x\n\t\t\t\t\t\t+ margin, (int) layout._numTilesX - 1);\n\t\tint ylLim = max(\n\t\t\t\tmin_element(terminals.begin(), terminals.end(), comp_y)->_y\n\t\t\t\t\t\t- margin, 0);\n\t\tint yuLim = min(\n\t\t\t\tmax_element(terminals.begin(), terminals.end(), comp_y)->_y\n\t\t\t\t\t\t+ margin, (int) layout._numTilesY - 1);\n\t\tg = build_graph(vp.gnetID, bannedPts, xlLim, xuLim, ylLim, yuLim, zlLim,\n\t\t\t\tzuLim);\n\t\t/*for (auto v : g.m_vertices) {\n\t\t cerr << \"Vertex: \" << v.m_property.x << \" \"\n\t\t << v.m_property.y << \" \" << v.m_property.z << endl;\n\t\t }\n\t\t for (auto e : g.m_edges) {\n\t\t cerr << \"Edge: \" << g[e.m_source].id << \" \" << g[e.m_target].id\n\t\t << endl;\n\t\t }*/\n\n\t\tint X = xuLim - xlLim + 1, Y = yuLim - ylLim + 1;\n\t\tVertex start = (vp.zCoord - zlLim) * Y * X + (vp.yCoord - ylLim) * X\n\t\t\t\t+ (vp.xCoord - xlLim);\n\t\tstd::unordered_set<Vertex> goals = build_goals(vp, xlLim, xuLim, ylLim,\n\t\t\t\tyuLim, zlLim);\n\t\tif (minmhd == INFINITY) {\n\t\t\tfor (auto goal : goals) {\n\t\t\t\tdouble mhd = fabs(g[start].x - g[goal].x)\n\t\t\t\t\t\t+ fabs(g[start].y - g[goal].y)\n\t\t\t\t\t\t+ fabs(g[start].z - g[goal].z);\n\t\t\t\tif (mhd < minmhd)\n\t\t\t\t\tminmhd = mhd;\n\t\t\t}\n\t\t}\n\t\tres = a_star(g, start, goals);\n\t\tif (res.first < INFINITY) { // found a-star path\n\t\t\twl = res.first;\n// cout << \"wl = \" << wl << endl;\n\t\t\tisFeasible = true;\n\t\t\tnext_margin = std::max(next_margin,\n\t\t\t\t\tstd::min(maxMargin, (int) ((res.first - minmhd) / 2.0)));\n\t\t} else { // not found\n\t\t\tnext_margin = std::max(next_margin,\n\t\t\t\t\tstd::min(maxMargin, margin * 2 + 1));\n// cout << \"next_margin = \" << next_margin << endl;\n\t\t}\n\t\tif (next_margin > margin)\n\t\t\tmargin = next_margin;\n\t\telse\n\t\t\tbreak;\n\t}\n\tif (!isFeasible)\n\t\treturn make_tuple(INFINITY, addedEdges, addedVias, margin,\n\t\t\t\taddlBannedPts);\n\t// fill addedEdges / addedVias\n\tauto vecPath = res.second;\n\tif (writeToDB) {\n\t\tvp.wlToL1 += vecPath.size();\n\t}\n\tif (vecPath.size() > 0)\n\t\taddlBannedPts.insert(\n\t\t\t\tGcell(g[vecPath[0]].x, g[vecPath[0]].y, g[vecPath[0]].z));\n\tfor (int i = 1; i < static_cast<int>(vecPath.size()); i++) {\n\t\taddlBannedPts.insert(\n\t\t\t\tGcell(g[vecPath[i]].x, g[vecPath[i]].y, g[vecPath[i]].z));\n\t\tif (g[vecPath[i]].z == g[vecPath[i - 1]].z) {\n\t\t\tif (_dirLayers[g[vecPath[i]].z] == H) {\n\t\t\t\tassert(g[vecPath[i]].y == g[vecPath[i - 1]].y);\n\t\t\t\tfor (int x = min(g[vecPath[i]].x, g[vecPath[i - 1]].x);\n\t\t\t\t\t\tx < max(g[vecPath[i]].x, g[vecPath[i - 1]].x); x++) {\n\t\t\t\t\tif (writeToDB) {\n\t\t\t\t\t\tint edgeId = findEdge(x, g[vecPath[i]].y,\n\t\t\t\t\t\t\t\tg[vecPath[i]].z);\n\t\t\t\t\t\tif (!(_gnets[vp.gnetID].findCleanEdge(edgeId))) {\n\t\t\t\t\t\t\t_gnets[vp.gnetID].setCleanEdge(edgeId,\n\t\t\t\t\t\t\t\t\t_edges[edgeId]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!(_gnets[vp.gnetID].findRUEdge(edgeId))) {\n\t\t\t\t\t\t\t_gnets[vp.gnetID].setRUEdge(edgeId, _edges[edgeId]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\trestoreEdge(edgeId);\n\t\t\t\t\t\t_gnets[vp.gnetID]._occupiedEdges.insert(edgeId);\n\t\t\t\t\t\t_dirty = true;\n\t\t\t\t\t}\n\t\t\t\t\taddedEdges.push_back(\n\t\t\t\t\t\t\tfindEdge(x, g[vecPath[i]].y, g[vecPath[i]].z));\n\t\t\t\t}\n\t\t\t} else if (_dirLayers[g[vecPath[i]].z] == V) {\n\t\t\t\tassert(g[vecPath[i]].x == g[vecPath[i - 1]].x);\n\t\t\t\tfor (int y = min(g[vecPath[i]].y, g[vecPath[i - 1]].y);\n\t\t\t\t\t\ty < max(g[vecPath[i]].y, g[vecPath[i - 1]].y); y++) {\n\t\t\t\t\tif (writeToDB) {\n\t\t\t\t\t\tint edgeId = findEdge(g[vecPath[i]].x, y,\n\t\t\t\t\t\t\t\tg[vecPath[i]].z);\n\t\t\t\t\t\tif (!(_gnets[vp.gnetID].findCleanEdge(edgeId))) {\n\t\t\t\t\t\t\t_gnets[vp.gnetID].setCleanEdge(edgeId,\n\t\t\t\t\t\t\t\t\t_edges[edgeId]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!(_gnets[vp.gnetID].findRUEdge(edgeId))) {\n\t\t\t\t\t\t\t_gnets[vp.gnetID].setRUEdge(edgeId, _edges[edgeId]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\trestoreEdge(edgeId);\n\t\t\t\t\t\t_gnets[vp.gnetID]._occupiedEdges.insert(edgeId);\n\t\t\t\t\t\t_dirty = true;\n\t\t\t\t\t}\n\t\t\t\t\taddedEdges.push_back(\n\t\t\t\t\t\t\tfindEdge(g[vecPath[i]].x, y, g[vecPath[i]].z));\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\tassert(0);\n\t\t} else {\n\t\t\tassert(g[vecPath[i]].y == g[vecPath[i - 1]].y);\n\t\t\tassert(g[vecPath[i]].x == g[vecPath[i - 1]].x);\n\t\t\tfor (int z = min(g[vecPath[i]].z, g[vecPath[i - 1]].z);\n\t\t\t\t\tz < max(g[vecPath[i]].z, g[vecPath[i - 1]].z); z++) {\n\t\t\t\tif (writeToDB) {\n\t\t\t\t\tint viaId = findVia(g[vecPath[i]].x, g[vecPath[i]].y, z);\n\t\t\t\t\tif (!(_gnets[vp.gnetID].findCleanVia(viaId))) {\n\t\t\t\t\t\t_gnets[vp.gnetID].setCleanVia(viaId, _vias[viaId]);\n\t\t\t\t\t}\n\t\t\t\t\tif (!(_gnets[vp.gnetID].findRUVia(viaId))) {\n\t\t\t\t\t\t_gnets[vp.gnetID].setRUVia(viaId, _vias[viaId]);\n\t\t\t\t\t}\n\t\t\t\t\trestoreVia(viaId);\n\t\t\t\t\t_gnets[vp.gnetID]._occupiedVias.insert(viaId);\n\t\t\t\t\t_dirty = true;\n\t\t\t\t}\n\t\t\t\taddedVias.push_back(\n\t\t\t\t\t\tfindVia(g[vecPath[i]].x, g[vecPath[i]].y, z));\n\t\t\t}\n\t\t}\n\t}\n\tif (writeToDB) {\n\t\tauto &vecPath = res.second;\n\t\t// Erase points in the middle in the same direction along the path\n\t\tvector<bool> validPt;\n\t\tvalidPt.assign(vecPath.size(), true);\n\t\tchar prevDir = 0; // 0 = default, 1 = +x, 2 = -x, 3 = +y, 4 = -y, 5 = +z, 6 = -z, 7 = other\n\t\tif (vecPath.size() > 2) {\n\t\t\tfor (size_t i = 1; i < vecPath.size(); ++i) {\n\t\t\t\tif (g[vecPath[i]].x > g[vecPath[i - 1]].x\n\t\t\t\t\t\t&& g[vecPath[i]].y == g[vecPath[i - 1]].y\n\t\t\t\t\t\t&& g[vecPath[i]].z == g[vecPath[i - 1]].z) {\n\t\t\t\t\tif (prevDir == 1) {\n\t\t\t\t\t\tvalidPt[i - 1] = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprevDir = 1;\n\t\t\t\t\t}\n\t\t\t\t} else if (g[vecPath[i]].x < g[vecPath[i - 1]].x\n\t\t\t\t\t\t&& g[vecPath[i]].y == g[vecPath[i - 1]].y\n\t\t\t\t\t\t&& g[vecPath[i]].z == g[vecPath[i - 1]].z) {\n\t\t\t\t\tif (prevDir == 2) {\n\t\t\t\t\t\tvalidPt[i - 1] = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprevDir = 2;\n\t\t\t\t\t}\n\t\t\t\t} else if (g[vecPath[i]].x == g[vecPath[i - 1]].x\n\t\t\t\t\t\t&& g[vecPath[i]].y > g[vecPath[i - 1]].y\n\t\t\t\t\t\t&& g[vecPath[i]].z == g[vecPath[i - 1]].z) {\n\t\t\t\t\tif (prevDir == 3) {\n\t\t\t\t\t\tvalidPt[i - 1] = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprevDir = 3;\n\t\t\t\t\t}\n\t\t\t\t} else if (g[vecPath[i]].x == g[vecPath[i - 1]].x\n\t\t\t\t\t\t&& g[vecPath[i]].y < g[vecPath[i - 1]].y\n\t\t\t\t\t\t&& g[vecPath[i]].z == g[vecPath[i - 1]].z) {\n\t\t\t\t\tif (prevDir == 4) {\n\t\t\t\t\t\tvalidPt[i - 1] = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprevDir = 4;\n\t\t\t\t\t}\n\t\t\t\t} else if (g[vecPath[i]].x == g[vecPath[i - 1]].x\n\t\t\t\t\t\t&& g[vecPath[i]].y == g[vecPath[i - 1]].y\n\t\t\t\t\t\t&& g[vecPath[i]].z > g[vecPath[i - 1]].z) {\n\t\t\t\t\tif (prevDir == 5) {\n\t\t\t\t\t\t// validPt[i - 1] = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprevDir = 5;\n\t\t\t\t\t}\n\t\t\t\t} else if (g[vecPath[i]].x == g[vecPath[i - 1]].x\n\t\t\t\t\t\t&& g[vecPath[i]].y == g[vecPath[i - 1]].y\n\t\t\t\t\t\t&& g[vecPath[i]].z < g[vecPath[i - 1]].z) {\n\t\t\t\t\tif (prevDir == 6) {\n\t\t\t\t\t\t// validPt[i - 1] = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprevDir = 6;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tprevDir = 7;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvector<Vertex> vecPath_tmp;\n\t\t\tfor (size_t i = 0; i < vecPath.size(); ++i) {\n\t\t\t\tif (validPt[i]) {\n\t\t\t\t\tvecPath_tmp.push_back(vecPath[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tvecPath.swap(vecPath_tmp);\n\t\t}\n\t\tGnet &gnet = _gnets[vp.gnetID];\n\t\tgnet._gWires.reserve(gnet._gWires.size() + vecPath.size() + 1);\n\t\tint addedVertex = -1; // gWireID of the added vertex, -1 if n/a.\n\n\t\tvector<GlobalWire>::iterator gWireItr;\n// check if there is a removed vertex due to broken wires and if so, add it back\n\t\tif (updateRoot) { // this can happen only when updateRoot == true\n\t\t\tvector<vector<GlobalWire>::iterator> rootItrs;\n\t\t\tfor (gWireItr = gnet._gWires.begin(); gWireItr < gnet._gWires.end();\n\t\t\t\t\t++gWireItr) {\n\t\t\t\tif (gWireItr->_pWireId == -1\n\t\t\t\t\t\t&& gWireItr != gnet._gWires.begin() + gnet._root) {\n\t\t\t\t\trootItrs.push_back(gWireItr);\n\t\t\t\t}\n\t\t\t}\n\t\t\tauto s = vp.gnetVertices;\n\t\t\tfor (auto gw : gnet._gWires) {\n//\tcout << gw._x << \" \" << gw._y << \" \" << gw._z << endl;\n\t\t\t\ts.erase(Gcell(gw._x, gw._y, gw._z));\n\t\t\t}\n//\t\tcout << \"s.size() = \" << s.size() << endl;\n\t\t\tif (s.size() > 1) {\n\t\t\t\tcout << s.size() << endl;\n\t\t\t\texit(-2);\n\t\t\t}\n\t\t\tif (s.size() == 1) { // have to make a new gWire that ALL roots (except gWire[0]) point to.\n\t\t\t\tgnet._gWires.push_back(\n\t\t\t\t\t\tGlobalWire(s.begin()->_x, s.begin()->_y, s.begin()->_z,\n\t\t\t\t\t\t\t\t-1, -1));\n\t\t\t\taddedVertex = gnet._gWires.size() - 1;\n\t\t\t\tfor (auto &rootItr : rootItrs) {\n\t\t\t\t\trootItr->_pWireId = addedVertex;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n// Identify goal type\n\t\tfor (gWireItr = gnet._gWires.begin(); gWireItr < gnet._gWires.end();\n\t\t\t\t++gWireItr) {\n\t\t\tif (gWireItr->_x == g[vecPath[0]].x\n\t\t\t\t\t&& gWireItr->_y == g[vecPath[0]].y\n\t\t\t\t\t&& gWireItr->_z == g[vecPath[0]].z) {\n\t\t\t\tbreak; // Case 0: goal is one of endpoints of a gWire\n\t\t\t}\n\t\t}\n\n\t\tif (gWireItr == gnet._gWires.end()) { // Case 1: goal in the middle of a gWire\n\t\t\tfor (gWireItr = gnet._gWires.begin(); gWireItr < gnet._gWires.end();\n\t\t\t\t\t++gWireItr) {\n\t\t\t\tif (gWireItr->_pWireId != -1) {\n\t\t\t\t\tint &x1 = gWireItr->_x, &y1 = gWireItr->_y, &z1 =\n\t\t\t\t\t\t\tgWireItr->_z;\n\t\t\t\t\tint &x2 = gnet._gWires[gWireItr->_pWireId]._x, &y2 =\n\t\t\t\t\t\t\tgnet._gWires[gWireItr->_pWireId]._y, &z2 =\n\t\t\t\t\t\t\tgnet._gWires[gWireItr->_pWireId]._z;\n\t\t\t\t\tint &x0 = g[vecPath[0]].x, &y0 = g[vecPath[0]].y, &z0 =\n\t\t\t\t\t\t\tg[vecPath[0]].z;\n\t\t\t\t\tif ((x1 != x2 && y0 == y1 && z0 == z1 && min(x1, x2) < x0\n\t\t\t\t\t\t\t&& x0 < max(x1, x2))\n\t\t\t\t\t\t\t|| (y1 != y2 && x0 == x1 && z0 == z1\n\t\t\t\t\t\t\t\t\t&& min(y1, y2) < y0 && y0 < max(y1, y2))\n\t\t\t\t\t\t\t|| (z1 != z2 && x0 == x1 && y0 == y1\n\t\t\t\t\t\t\t\t\t&& min(z1, z2) < z0 && z0 < max(z1, z2))) {\n\t\t\t\t\t\t// make a new gWire in the middle\n\t\t\t\t\t\tgnet._gWires.push_back(\n\t\t\t\t\t\t\t\tGlobalWire(x0, y0, z0, gWireItr->_pWireId, -1));\n\t\t\t\t\t\tgWireItr->_pWireId = gnet._gWires.size() - 1;\n\t\t\t\t\t\tgWireItr = gnet._gWires.end() - 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tassert(gWireItr < gnet._gWires.end());\n\t\tif (updateRoot) {\n// Mode 2: move the root, make the root point to the new vertex, update the root\n// search for all roots due to broken wires\n\t\t\tauto rootItr = gWireItr;\n\t\t\tvector<int> gWireIDsToReverse;\n\t\t\tif (rootItr < gnet._gWires.end()) { // Case 0 or Case 1\n\t\t\t\twhile (rootItr->_pWireId != -1) {\n\t\t\t\t\tgWireIDsToReverse.push_back(rootItr - gnet._gWires.begin());\n\t\t\t\t\trootItr = gnet._gWires.begin() + rootItr->_pWireId;\n\t\t\t\t}\n\t\t\t\tgWireIDsToReverse.push_back(rootItr - gnet._gWires.begin());\n\t\t\t}\n\n\t\t\tgnet._gWires[gWireIDsToReverse[0]]._pWireId = -1;\n\t\t\tfor (auto itr = gWireIDsToReverse.begin() + 1;\n\t\t\t\t\titr < gWireIDsToReverse.end(); ++itr) {\n// Reverse the directions of each gWire\n\t\t\t\tgnet._gWires[(*itr)]._pWireId = *(itr - 1);\n\t\t\t}\n\t\t\tif (gnet._gWires[gnet._root]._pWireId != -1) {\n\t\t\t\tgnet._root = gWireIDsToReverse[0];\n\t\t\t\tcout << \"<I> Root changed to: \" << gnet._root << endl;\n\t\t\t}\n// let the new gWire point to the last gwire in the list to reverse,\n// finishing the reversing process.\n//if (addedVertex != -1) {\n//\tgnet._gWires[addedVertex]._pWireId =\n//\t\t\t*(gWireIDsToReverse.end() - 1);\n//}\n\n// expose the new root and prepare for adding the new path.\n\t\t\tgWireItr = gnet._gWires.begin() + gWireIDsToReverse[0];\n\n\t\t\tfor (auto itr = vecPath.begin() + 1; itr < vecPath.end(); ++itr) {\n// Add edge (*itr, *(itr-1)) to DB (gnet/addEdgeDemand)\n\t\t\t\tgnet._gWires.push_back(\n\t\t\t\t\t\tGlobalWire(g[*itr].x, g[*itr].y, g[*itr].z, -1, -1));\n\t\t\t\tgWireItr->_pWireId = gnet._gWires.size() - 1;\n\t\t\t\tgWireItr = gnet._gWires.end() - 1;\n\t\t\t}\n\t\t} else {\n// Mode 1: make the new vertex point to the root, keep the root\n\t\t\tint pWireId = gWireItr - gnet._gWires.begin();\n\t\t\tfor (auto itr = vecPath.begin() + 1; itr < vecPath.end(); ++itr) {\n// Add edge (*itr, *(itr+1)) to DB (gnet/addEdgeDemand)\n\t\t\t\tgnet._gWires.push_back(\n\t\t\t\t\t\tGlobalWire(g[*itr].x, g[*itr].y, g[*itr].z, pWireId,\n\t\t\t\t\t\t\t\t-1));\n\t\t\t\tpWireId = gnet._gWires.size() - 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn make_tuple(wl, addedEdges, addedVias, margin, addlBannedPts);\n}\n\nstd::tuple<double, vector<int>, vector<int>, int> RoutingDB::rerouteNet(\n\t\tconst Layout &layout, const Vpin &vp1, const Vpin &vp2, const int zlLim,\n\t\tconst int zuLim, const int maxMargin, const bool singleMargin,\n\t\tconst bool writeToDB) {\n// Connect two v-pins\n\tusing namespace boost;\n\tint margin = singleMargin ? maxMargin : 0;\n\tint next_margin = 0;\n\tdouble wl = INFINITY;\n\tbool isFeasible = false;\n\tdouble minmhd = INFINITY;\n\tstd::pair<double, vector<Vertex>> res;\n\tstd::vector<int> addedEdges, addedVias;\n\tGraph g;\n\tstd::unordered_set<Gcell, HashGcell3d> bannedPts; // empty set\n\twhile (margin <= maxMargin) {\n// cout << \"[2vp] margin = \" << margin << endl;\n\t\tint xlLim = max(min(vp1.xCoord, vp2.xCoord) - margin, 0);\n\t\tint xuLim = min(max(vp1.xCoord, vp2.xCoord) + margin,\n\t\t\t\t(int) layout._numTilesX - 1);\n\t\tint ylLim = max(min(vp1.yCoord, vp2.yCoord) - margin, 0);\n\t\tint yuLim = min(max(vp1.yCoord, vp2.yCoord) + margin,\n\t\t\t\t(int) layout._numTilesY - 1);\n\t\tg = build_graph(vp1.gnetID, bannedPts, xlLim, xuLim, ylLim, yuLim,\n\t\t\t\tzlLim, zuLim);\n\t\tint X = xuLim - xlLim + 1, Y = yuLim - ylLim + 1;\n\t\tVertex start = (vp1.zCoord + 1 - zlLim) * Y * X\n\t\t\t\t+ (vp1.yCoord - ylLim) * X + (vp1.xCoord - xlLim);\n\t\tVertex goal = (vp2.zCoord + 1 - zlLim) * Y * X\n\t\t\t\t+ (vp2.yCoord - ylLim) * X + (vp2.xCoord - xlLim);\n\t\tif (minmhd == INFINITY) {\n\t\t\tminmhd = fabs(g[start].x - g[goal].x) + fabs(g[start].y - g[goal].y)\n\t\t\t\t\t+ fabs(g[start].z - g[goal].z);\n\t\t}\n\t\tstd::unordered_set<Vertex> goals = { goal };\n\t\tres = a_star(g, start, goals);\n\t\tif (res.first < INFINITY) { // found a-star path\n\t\t\twl = res.first;\n// cout << \"wl = \" << wl << endl;\n\t\t\tisFeasible = true;\n\t\t\tnext_margin = std::max(next_margin,\n\t\t\t\t\tstd::min(maxMargin, (int) ((res.first - minmhd) / 2.0)));\n\t\t} else { // not found\n\t\t\tnext_margin = std::max(next_margin,\n\t\t\t\t\tstd::min(maxMargin, margin * 2 + 1));\n// cout << \"next_margin = \" << next_margin << endl;\n\t\t}\n\t\tif (next_margin > margin)\n\t\t\tmargin = next_margin;\n\t\telse\n\t\t\tbreak;\n\t}\n\tif (!isFeasible)\n\t\treturn make_tuple(INFINITY, addedEdges, addedVias, margin);\n// add the new vpin\n\tif (writeToDB) {\n\t\tint viaId = findVia(vp1.xCoord, vp1.yCoord, vp1.zCoord);\n\t\tif (!(_gnets[vp1.gnetID].findCleanVia(viaId))) {\n\t\t\t_gnets[vp1.gnetID].setCleanVia(viaId, _vias[viaId]);\n\t\t}\n\t\tif (!(_gnets[vp1.gnetID].findRUVia(viaId))) {\n\t\t\t_gnets[vp1.gnetID].setRUVia(viaId, _vias[viaId]);\n\t\t}\n\t\trestoreVia(viaId);\n\t\t_dirty = true;\n\t}\n\taddedVias.push_back(findVia(vp1.xCoord, vp1.yCoord, vp1.zCoord));\n\n\tauto &vecPath = res.second;\n\t// Erase points in the middle in the same direction along the path\n\tvector<bool> validPt;\n\tvalidPt.assign(vecPath.size(), true);\n\tchar prevDir = 0; // 0 = default, 1 = +x, 2 = -x, 3 = +y, 4 = -y, 5 = +z, 6 = -z, 7 = other\n\tif (vecPath.size() > 2) {\n\t\tfor (size_t i = 1; i < vecPath.size(); ++i) {\n\t\t\tif (g[vecPath[i]].x > g[vecPath[i - 1]].x\n\t\t\t\t\t&& g[vecPath[i]].y == g[vecPath[i - 1]].y\n\t\t\t\t\t&& g[vecPath[i]].z == g[vecPath[i - 1]].z) {\n\t\t\t\tif (prevDir == 1) {\n\t\t\t\t\tvalidPt[i - 1] = false;\n\t\t\t\t} else {\n\t\t\t\t\tprevDir = 1;\n\t\t\t\t}\n\t\t\t} else if (g[vecPath[i]].x < g[vecPath[i - 1]].x\n\t\t\t\t\t&& g[vecPath[i]].y == g[vecPath[i - 1]].y\n\t\t\t\t\t&& g[vecPath[i]].z == g[vecPath[i - 1]].z) {\n\t\t\t\tif (prevDir == 2) {\n\t\t\t\t\tvalidPt[i - 1] = false;\n\t\t\t\t} else {\n\t\t\t\t\tprevDir = 2;\n\t\t\t\t}\n\t\t\t} else if (g[vecPath[i]].x == g[vecPath[i - 1]].x\n\t\t\t\t\t&& g[vecPath[i]].y > g[vecPath[i - 1]].y\n\t\t\t\t\t&& g[vecPath[i]].z == g[vecPath[i - 1]].z) {\n\t\t\t\tif (prevDir == 3) {\n\t\t\t\t\tvalidPt[i - 1] = false;\n\t\t\t\t} else {\n\t\t\t\t\tprevDir = 3;\n\t\t\t\t}\n\t\t\t} else if (g[vecPath[i]].x == g[vecPath[i - 1]].x\n\t\t\t\t\t&& g[vecPath[i]].y < g[vecPath[i - 1]].y\n\t\t\t\t\t&& g[vecPath[i]].z == g[vecPath[i - 1]].z) {\n\t\t\t\tif (prevDir == 4) {\n\t\t\t\t\tvalidPt[i - 1] = false;\n\t\t\t\t} else {\n\t\t\t\t\tprevDir = 4;\n\t\t\t\t}\n\t\t\t} else if (g[vecPath[i]].x == g[vecPath[i - 1]].x\n\t\t\t\t\t&& g[vecPath[i]].y == g[vecPath[i - 1]].y\n\t\t\t\t\t&& g[vecPath[i]].z > g[vecPath[i - 1]].z) {\n\t\t\t\tif (prevDir == 5) {\n\t\t\t\t\t// validPt[i - 1] = false;\n\t\t\t\t} else {\n\t\t\t\t\tprevDir = 5;\n\t\t\t\t}\n\t\t\t} else if (g[vecPath[i]].x == g[vecPath[i - 1]].x\n\t\t\t\t\t&& g[vecPath[i]].y == g[vecPath[i - 1]].y\n\t\t\t\t\t&& g[vecPath[i]].z < g[vecPath[i - 1]].z) {\n\t\t\t\tif (prevDir == 6) {\n\t\t\t\t\t// validPt[i - 1] = false;\n\t\t\t\t} else {\n\t\t\t\t\tprevDir = 6;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tprevDir = 7;\n\t\t\t}\n\t\t}\n\t\tvector<Vertex> vecPath_tmp;\n\t\tfor (size_t i = 0; i < vecPath.size(); ++i) {\n\t\t\tif (validPt[i]) {\n\t\t\t\tvecPath_tmp.push_back(vecPath[i]);\n\t\t\t}\n\t\t}\n\t\tvecPath.swap(vecPath_tmp);\n\t}\n\tfor (int i = 1; i < static_cast<int>(vecPath.size()); i++) {\n\t\tif (g[vecPath[i]].z == g[vecPath[i - 1]].z) {\n\t\t\tif (_dirLayers[g[vecPath[i]].z] == H) {\n\t\t\t\tassert(g[vecPath[i]].y == g[vecPath[i - 1]].y);\n\t\t\t\tfor (int x = min(g[vecPath[i]].x, g[vecPath[i - 1]].x);\n\t\t\t\t\t\tx < max(g[vecPath[i]].x, g[vecPath[i - 1]].x); x++) {\n\t\t\t\t\tif (writeToDB) {\n\t\t\t\t\t\tint edgeId = findEdge(x, g[vecPath[i]].y,\n\t\t\t\t\t\t\t\tg[vecPath[i]].z);\n\t\t\t\t\t\tif (!(_gnets[vp1.gnetID].findCleanEdge(edgeId))) {\n\t\t\t\t\t\t\t_gnets[vp1.gnetID].setCleanEdge(edgeId,\n\t\t\t\t\t\t\t\t\t_edges[edgeId]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!(_gnets[vp1.gnetID].findRUEdge(edgeId))) {\n\t\t\t\t\t\t\t_gnets[vp1.gnetID].setRUEdge(edgeId,\n\t\t\t\t\t\t\t\t\t_edges[edgeId]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\trestoreEdge(edgeId);\n\t\t\t\t\t\t_dirty = true;\n\t\t\t\t\t}\n\t\t\t\t\taddedEdges.push_back(\n\t\t\t\t\t\t\tfindEdge(x, g[vecPath[i]].y, g[vecPath[i]].z));\n\n\t\t\t\t}\n\t\t\t} else if (_dirLayers[g[vecPath[i]].z] == V) {\n\t\t\t\tassert(g[vecPath[i]].x == g[vecPath[i - 1]].x);\n\t\t\t\tfor (int y = min(g[vecPath[i]].y, g[vecPath[i - 1]].y);\n\t\t\t\t\t\ty < max(g[vecPath[i]].y, g[vecPath[i - 1]].y); y++) {\n\t\t\t\t\tif (writeToDB) {\n\t\t\t\t\t\tint edgeId = findEdge(g[vecPath[i]].x, y,\n\t\t\t\t\t\t\t\tg[vecPath[i]].z);\n\t\t\t\t\t\tif (!(_gnets[vp1.gnetID].findCleanEdge(edgeId))) {\n\t\t\t\t\t\t\t_gnets[vp1.gnetID].setCleanEdge(edgeId,\n\t\t\t\t\t\t\t\t\t_edges[edgeId]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!(_gnets[vp1.gnetID].findRUEdge(edgeId))) {\n\t\t\t\t\t\t\t_gnets[vp1.gnetID].setRUEdge(edgeId,\n\t\t\t\t\t\t\t\t\t_edges[edgeId]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\trestoreEdge(edgeId);\n\t\t\t\t\t\t_dirty = true;\n\t\t\t\t\t}\n\t\t\t\t\taddedEdges.push_back(\n\t\t\t\t\t\t\tfindEdge(g[vecPath[i]].x, y, g[vecPath[i]].z));\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\tassert(0);\n\t\t} else {\n\t\t\tassert(g[vecPath[i]].y == g[vecPath[i - 1]].y);\n\t\t\tassert(g[vecPath[i]].x == g[vecPath[i - 1]].x);\n\t\t\tfor (int z = min(g[vecPath[i]].z, g[vecPath[i - 1]].z);\n\t\t\t\t\tz < max(g[vecPath[i]].z, g[vecPath[i - 1]].z); z++) {\n\t\t\t\tif (writeToDB) {\n\t\t\t\t\tint viaId = findVia(g[vecPath[i]].x, g[vecPath[i]].y, z);\n\t\t\t\t\tif (!(_gnets[vp1.gnetID].findCleanVia(viaId))) {\n\t\t\t\t\t\t_gnets[vp1.gnetID].setCleanVia(viaId, _vias[viaId]);\n\t\t\t\t\t}\n\t\t\t\t\tif (!(_gnets[vp1.gnetID].findRUVia(viaId))) {\n\t\t\t\t\t\t_gnets[vp1.gnetID].setRUVia(viaId, _vias[viaId]);\n\t\t\t\t\t}\n\t\t\t\t\trestoreVia(findVia(g[vecPath[i]].x, g[vecPath[i]].y, z));\n\t\t\t\t\t_dirty = true;\n\t\t\t\t}\n\t\t\t\taddedVias.push_back(\n\t\t\t\t\t\tfindVia(g[vecPath[i]].x, g[vecPath[i]].y, z));\n\t\t\t}\n\t\t}\n\t}\n\tif (writeToDB) {\n\t\tauto vecPath = res.second;\n\t\tGnet &gnet = _gnets[vp1.gnetID];\n\t\tgnet._gWires.reserve(gnet._gWires.size() + vecPath.size());\n\t\tvector<GlobalWire>::iterator gWireItr1, gWireItr2;\n\t\t// start\n\t\tfor (gWireItr1 = gnet._gWires.begin(); gWireItr1 < gnet._gWires.end();\n\t\t\t\t++gWireItr1) {\n\t\t\tif (gWireItr1->_x == g[vecPath.back()].x\n\t\t\t\t\t&& gWireItr1->_y == g[vecPath.back()].y\n\t\t\t\t\t&& gWireItr1->_z == g[vecPath.back()].z - 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t// goal\n\t\tfor (gWireItr2 = gnet._gWires.begin(); gWireItr2 < gnet._gWires.end();\n\t\t\t\t++gWireItr2) {\n\t\t\tif (gWireItr2->_x == g[vecPath[0]].x\n\t\t\t\t\t&& gWireItr2->_y == g[vecPath[0]].y\n\t\t\t\t\t&& gWireItr2->_z == g[vecPath[0]].z) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tassert((gWireItr1->_pWireId == -1) != (gWireItr2->_pWireId == -1));\n\t\tif (gWireItr2->_pWireId == -1) {\n// cout << \"Mode 2\" << endl;\n// Mode 2\n\t\t\tif (vecPath.size() == 1) {\n\t\t\t\tgWireItr2->_pWireId = gWireItr1 - gnet._gWires.begin();\n\t\t\t} else {\n\t\t\t\tfor (auto itr = vecPath.begin() + 1; itr < vecPath.end() - 1;\n\t\t\t\t\t\t++itr) {\n// Add edge (*itr, *(itr+1)) to DB (gnet/addEdgeDemand)\n\t\t\t\t\tgnet._gWires.push_back(\n\t\t\t\t\t\t\tGlobalWire(g[*itr].x, g[*itr].y, g[*itr].z, -1,\n\t\t\t\t\t\t\t\t\t-1));\n\t\t\t\t\tgWireItr2->_pWireId = gnet._gWires.size() - 1;\n\t\t\t\t\tgWireItr2 = gnet._gWires.end() - 1;\n\t\t\t\t}\n\t\t\t\tgnet._gWires.push_back(\n\t\t\t\t\t\tGlobalWire(g[vecPath.back()].x, g[vecPath.back()].y,\n\t\t\t\t\t\t\t\tg[vecPath.back()].z,\n\t\t\t\t\t\t\t\tgWireItr1 - gnet._gWires.begin(), -1));\n\t\t\t\tgWireItr2->_pWireId = gnet._gWires.size() - 1;\n\t\t\t}\n\t\t} else {\n// cout << \"Mode 1\" << endl;\n// Mode 1\n\t\t\tif (vecPath.size() == 1) {\n\t\t\t\tgWireItr1->_pWireId = gWireItr2 - gnet._gWires.begin();\n\t\t\t} else {\n\t\t\t\tstd::reverse(vecPath.begin(), vecPath.end());\n\t\t\t\tfor (auto itr = vecPath.begin(); itr < vecPath.end() - 2;\n\t\t\t\t\t\t++itr) {\n// Add edge (*itr, *(itr+1)) to DB (gnet/addEdgeDemand)\n\t\t\t\t\tgnet._gWires.push_back(\n\t\t\t\t\t\t\tGlobalWire(g[*itr].x, g[*itr].y, g[*itr].z, -1,\n\t\t\t\t\t\t\t\t\t-1));\n\t\t\t\t\tgWireItr1->_pWireId = gnet._gWires.size() - 1;\n\t\t\t\t\tgWireItr1 = gnet._gWires.end() - 1;\n\t\t\t\t}\n\t\t\t\tgnet._gWires.push_back(\n\t\t\t\t\t\tGlobalWire(g[vecPath[vecPath.size() - 2]].x,\n\t\t\t\t\t\t\t\tg[vecPath[vecPath.size() - 2]].y,\n\t\t\t\t\t\t\t\tg[vecPath[vecPath.size() - 2]].z,\n\t\t\t\t\t\t\t\tgWireItr2 - gnet._gWires.begin(), -1));\n\t\t\t\tgWireItr1->_pWireId = gnet._gWires.size() - 1;\n\t\t\t}\n\t\t}\n\t\trestoreNet(vp1.gnetID, gnet, _gnets[vp1.gnetID]._cleanEdges,\n\t\t\t\t_gnets[vp1.gnetID]._cleanVias, false);\n\t}\n\treturn make_tuple(wl + 1, addedEdges, addedVias, margin); // including WL of the new v-pin\n}\n\n", "meta": {"hexsha": "b98f7aaa0bab769052b5d60bd8f08f96b0ad63ae", "size": 29484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "a_star.cpp", "max_stars_repo_name": "wei-zeng/ISPD11-bench-split", "max_stars_repo_head_hexsha": "ddee82dcdd704175ed78d43731016b49a5efaa87", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "a_star.cpp", "max_issues_repo_name": "wei-zeng/ISPD11-bench-split", "max_issues_repo_head_hexsha": "ddee82dcdd704175ed78d43731016b49a5efaa87", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "a_star.cpp", "max_forks_repo_name": "wei-zeng/ISPD11-bench-split", "max_forks_repo_head_hexsha": "ddee82dcdd704175ed78d43731016b49a5efaa87", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0167973124, "max_line_length": 113, "alphanum_fraction": 0.5792294126, "num_tokens": 10810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.44867501078757144}}
{"text": "/*\n * car_model_propagator.hpp\n *\n * Created on: Oct 30, 2018 22:52\n * Description:\n *\n * Copyright (c) 2018 Ruixiang Du (rdu)\n */\n\n#ifndef CAR_MODEL_PROPAGATOR_HPP\n#define CAR_MODEL_PROPAGATOR_HPP\n\n#include <cstdint>\n#include <vector>\n\n#include <boost/numeric/odeint.hpp>\n\n#include \"reachability/details/car_longitudinal_model.hpp\"\n\nnamespace robotnav {\nclass CarModelPropagator {\n public:\n  CarLongitudinalModel::state_type Propagate(CarLongitudinalModel::state_type init_state,\n                       CarLongitudinalModel::control_type u, double t0,\n                       double tf, double dt) {\n    double t = t0;\n    CarLongitudinalModel::state_type x = init_state;\n\n    while (t <= tf) {\n      //   integrator_(CarLongitudinalModel(u), x, t, dt);\n\n      boost::numeric::odeint::integrate_const(\n          boost::numeric::odeint::runge_kutta4<\n              CarLongitudinalModel::state_type>(),\n          CarLongitudinalModel(u), x, t, t+dt, dt/10.0);\n\n      // add additional constraint to s, v: s >= s0, v >=0, v < v_max\n      if (x[0] < init_state[0]) x[0] = init_state[0];\n      if (x[1] < 0) x[1] = 0;\n      if (x[1] > CarLongitudinalModel::v_max)\n        x[1] = CarLongitudinalModel::v_max;\n    }\n\n    return x;\n  }\n};\n}  // namespace robotnav\n\n#endif /* CAR_MODEL_PROPAGATOR_HPP */\n", "meta": {"hexsha": "2191c6ea5421eac56471bc162db90ec9cccb8bae", "size": 1295, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/modules/planning/decision/reachability/include/reachability/details/car_model_propagator.hpp", "max_stars_repo_name": "rxdu/robotnav", "max_stars_repo_head_hexsha": "fb36ac4ae9372f027c41e7be526ac1e72f094051", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-02T09:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T06:36:42.000Z", "max_issues_repo_path": "src/modules/planning/decision/reachability/include/reachability/details/car_model_propagator.hpp", "max_issues_repo_name": "rxdu/robotnav", "max_issues_repo_head_hexsha": "fb36ac4ae9372f027c41e7be526ac1e72f094051", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-30T02:01:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T08:06:40.000Z", "max_forks_repo_path": "src/modules/planning/decision/reachability/include/reachability/details/car_model_propagator.hpp", "max_forks_repo_name": "rxdu/robotnav", "max_forks_repo_head_hexsha": "fb36ac4ae9372f027c41e7be526ac1e72f094051", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-02T09:16:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T03:06:48.000Z", "avg_line_length": 25.9, "max_line_length": 89, "alphanum_fraction": 0.6424710425, "num_tokens": 381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4486750107875714}}
{"text": "#include \"cpu/graph_proc.h\"\r\n\r\n#include <set>\r\n#include <vector>\r\n#include <numeric> //std::iota\r\n#include <algorithm>\r\n#include <random> \r\n#include <iostream>\r\n\r\n#include <Eigen/Dense>\r\n\r\nusing std::vector;\r\n\r\nnamespace graph_proc {\r\n\r\n    py::array_t<bool> erode_mesh(const py::array_t<float>& vertexPositions, const py::array_t<int>& faceIndices, int nIterations, int minNeighbors) {\r\n        int nVertices = vertexPositions.shape(0);\r\n        int nFaces = faceIndices.shape(0);\r\n\r\n        // Init output \r\n        py::array_t<bool> nonErodedVertices = py::array_t<bool>({ nVertices, 1 });\r\n        std::vector<bool> nonErodedVerticesVec(nVertices, false);\r\n        \r\n        // Init list of eroded face indices with original list\r\n        std::vector<Eigen::Vector3i> erodedFaceIndicesVec;\r\n        erodedFaceIndicesVec.reserve(nFaces);\r\n        for (int FaceIdx = 0; FaceIdx < nFaces; ++FaceIdx) {\r\n            Eigen::Vector3i face(*faceIndices.data(FaceIdx, 0), *faceIndices.data(FaceIdx, 1), *faceIndices.data(FaceIdx, 2));\r\n            erodedFaceIndicesVec.push_back(face);\r\n        }\r\n\r\n        // Erode mesh for a total of nIterations\r\n        for (int i = 0; i < nIterations; i++) {\r\n            nFaces = erodedFaceIndicesVec.size();\r\n\r\n            // We compute the number of neighboring vertices for each vertex.\r\n            vector<int> numNeighbors(nVertices, 0);\r\n            for (int i = 0; i < nFaces; i++) {\r\n                const auto& face = erodedFaceIndicesVec[i];\r\n                numNeighbors[face[0]] += 1;\r\n                numNeighbors[face[1]] += 1;\r\n                numNeighbors[face[2]] += 1;\r\n            }\r\n\r\n            std::vector<Eigen::Vector3i> tmp;\r\n            tmp.reserve(nFaces);\r\n\r\n            for (int i = 0; i < nFaces; i++) {\r\n                const auto& face = erodedFaceIndicesVec[i];\r\n                if (numNeighbors[face[0]] >= minNeighbors && numNeighbors[face[1]] >= minNeighbors && numNeighbors[face[2]] >= minNeighbors) {\r\n                    tmp.push_back(face);\r\n                }\r\n            }\r\n\r\n            // We kill the faces with border vertices.\r\n            erodedFaceIndicesVec.clear();\r\n            erodedFaceIndicesVec = std::move(tmp);\r\n        }\r\n\r\n        // Mark non isolated vertices as not eroded.\r\n        nFaces = erodedFaceIndicesVec.size();\r\n\r\n        for (int i = 0; i < nFaces; i++) {\r\n            const auto& face = erodedFaceIndicesVec[i];\r\n            nonErodedVerticesVec[face[0]] = true;\r\n            nonErodedVerticesVec[face[1]] = true;\r\n            nonErodedVerticesVec[face[2]] = true;\r\n        }\r\n\r\n        // Store into python array\r\n        for (int i = 0; i < nVertices; i++) {\r\n            *nonErodedVertices.mutable_data(i, 0) = nonErodedVerticesVec[i];\r\n        }\r\n\r\n        return nonErodedVertices;\r\n    }\r\n\r\n    int sample_nodes(\r\n        const py::array_t<float>& vertexPositions, const py::array_t<bool>& nonErodedVertices,\r\n        py::array_t<float>& nodePositions, py::array_t<int>& nodeIndices, \r\n        float nodeCoverage, \r\n        const bool useOnlyNonErodedIndices=true, \r\n        const bool randomShuffle=true\r\n    ) {\r\n        // assert(vertexPositions.ndim() == 2);\r\n\r\n        float nodeCoverage2 = nodeCoverage * nodeCoverage;\r\n        int nVertices = vertexPositions.shape(0);\r\n        // assert(vertexPositions.shape(1) == 3);\r\n        // assert(nodePositions.shape(0) == nVertices);\r\n        // assert(nodePositions.shape(1) == 3);\r\n        // assert(nodeIndices.shape(0) == nVertices);\r\n        // assert(nodeIndices.shape(1) == 1);\r\n\r\n        nodePositions.resize({ nVertices, 3 }, false);\r\n        nodeIndices.resize({ nVertices, 1 }, false);\r\n\r\n        // create list of shuffled indices\r\n        std::vector<int> shuffledVertices(nVertices);\r\n        std::iota(std::begin(shuffledVertices), std::end(shuffledVertices), 0);\r\n\r\n        if (randomShuffle) {\r\n            std::default_random_engine re{std::random_device{}()};\r\n            std::shuffle(std::begin(shuffledVertices), std::end(shuffledVertices), re);\r\n        }\r\n\r\n        std::vector<Eigen::Vector3f> nodePositionsVec;\r\n        for (int vertexIdx : shuffledVertices) {\r\n        // for (int vertexIdx = 0; vertexIdx < nVertices; ++vertexIdx) {\r\n            Eigen::Vector3f point(*vertexPositions.data(vertexIdx, 0), *vertexPositions.data(vertexIdx, 1), *vertexPositions.data(vertexIdx, 2));\r\n\r\n            if (useOnlyNonErodedIndices && !(*nonErodedVertices.data(vertexIdx))) {\r\n                continue;\r\n            }\r\n\r\n            bool bIsNode = true;\r\n            for (int nodeIdx = 0; nodeIdx < nodePositionsVec.size(); ++nodeIdx) {\r\n                if ((point - nodePositionsVec[nodeIdx]).squaredNorm() <= nodeCoverage2) {\r\n                    bIsNode = false;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            if (bIsNode) {\r\n                nodePositionsVec.push_back(point);\r\n                int newNodeIdx = nodePositionsVec.size() - 1;\r\n                *nodePositions.mutable_data(newNodeIdx, 0) = point.x();\r\n                *nodePositions.mutable_data(newNodeIdx, 1) = point.y();\r\n                *nodePositions.mutable_data(newNodeIdx, 2) = point.z();\r\n                *nodeIndices.mutable_data(newNodeIdx, 0) = vertexIdx;\r\n            }\r\n        }\r\n\r\n        return nodePositionsVec.size();\r\n    }\r\n\r\n    /**\r\n     * Custom comparison operator for geodesic priority queue.\r\n     */\r\n    struct CustomCompare {\r\n        bool operator()(const std::pair<int, float>& left, const std::pair<int, float>& right) {\r\n            return left.second > right.second;\r\n        }\r\n    };\r\n\r\n    inline float compute_anchor_weight(const Eigen::Vector3f& pointPosition, const Eigen::Vector3f& nodePosition, float nodeCoverage) {\r\n        return std::exp(-(nodePosition - pointPosition).squaredNorm() / (2.f * nodeCoverage * nodeCoverage));\r\n    }\r\n\r\n    inline float compute_anchor_weight(float dist, float nodeCoverage) {\r\n        return std::exp(- (dist * dist) / (2.f * nodeCoverage * nodeCoverage));\r\n    }\r\n\r\n    void compute_edges_geodesic(\r\n\t\tconst py::array_t<float>& vertexPositions,\r\n\t\tconst py::array_t<bool>& validVertices, \r\n\t\tconst py::array_t<int>& faceIndices, \r\n\t\tconst py::array_t<int>& nodeIndices, \r\n\t\tconst int nMaxNeighbors, const float nodeCoverage,\r\n        py::array_t<int>& graphEdges,\r\n        py::array_t<float>& graphEdgesWeights,\r\n        py::array_t<float>& graphEdgesDistances,\r\n        py::array_t<float>& nodeToVertexDistances,\r\n        const bool allow_only_valid_vertices,\r\n        const bool enforce_total_num_neighbors\r\n\t) {\r\n\t\tint nVertices = vertexPositions.shape(0);\r\n\t\tint nFaces = faceIndices.shape(0);\r\n        int nNodes = nodeIndices.shape(0);\r\n\r\n        float maxInfluence = 2.f * nodeCoverage;\r\n\r\n        // Preprocess vertex neighbors.\r\n\t\tvector<std::set<int>> vertexNeighbors(nVertices);\r\n        for (int faceIdx = 0; faceIdx < nFaces; faceIdx++) {\r\n            for (int j = 0; j < 3; j++) {\r\n                int v_idx = *faceIndices.data(faceIdx, j);\r\n                \r\n                for (int k = 0; k < 3; k++) {\r\n                    int n_idx = *faceIndices.data(faceIdx, k);\r\n                    \r\n                    if (v_idx == n_idx) continue;\r\n                    vertexNeighbors[v_idx].insert(n_idx);\r\n                }\r\n            }\r\n        }\r\n\r\n\t\t// Compute inverse vertex -> node relationship.\r\n\t\tvector<int> mapVertexToNode(nVertices, -1);\r\n\r\n\t\tfor (int nodeId = 0; nodeId < nNodes; nodeId++) {\r\n\t\t\tint vertexIdx = *nodeIndices.data(nodeId);\r\n\t\t\tif (vertexIdx >= 0) {\r\n\t\t\t\tmapVertexToNode[vertexIdx] = nodeId;\r\n\t\t\t}\r\n\t\t}\r\n\r\n        // #pragma omp parallel for\r\n\t\tfor (int nodeId = 0; nodeId < nNodes; nodeId++) {\r\n\t\t\t// vertex queue\r\n            std::priority_queue<\r\n\t\t\t\tstd::pair<int, float>,\r\n\t\t\t\tvector<std::pair<int, float>>,\r\n\t\t\t\tCustomCompare\r\n\t\t\t> nextVerticesWithIds;\r\n\r\n\t\t\tstd::set<int> visitedVertices;\r\n\r\n\t\t\t// Add node vertex as the first vertex to be visited.\r\n\t\t\tint nodeVertexIdx = *nodeIndices.data(nodeId);\r\n\t\t\tif (nodeVertexIdx < 0) continue;\r\n\t\t\tnextVerticesWithIds.push(std::make_pair(nodeVertexIdx, 0.f));\r\n\t\t\t\r\n\t\t\t// Traverse all neighbors in the monotonically increasing order.\r\n            vector<int>   neighborNodeIds;\r\n            vector<float> neighborNodeWeights;\r\n            vector<float> neighborNodeDistances;\r\n\t\t\twhile (!nextVerticesWithIds.empty()) {\r\n\t\t\t\tauto nextVertex = nextVerticesWithIds.top();\r\n\t\t\t\tnextVerticesWithIds.pop();\r\n\r\n\t\t\t\tint nextVertexIdx = nextVertex.first;\r\n\t\t\t\tfloat nextVertexDist = nextVertex.second;\r\n\r\n\t\t\t\t// We skip the vertex, if it was already visited before.\r\n\t\t\t\tif (visitedVertices.find(nextVertexIdx) != visitedVertices.end()) continue;\r\n\r\n                if (allow_only_valid_vertices && !*validVertices.data(nextVertexIdx)) {\r\n                    std::cout << \"compute_edges_geodesic:: ufff... we shouldn't be checking out this vertex\" << std::endl;\r\n                    exit(0);\r\n                }\r\n\r\n\t\t\t\t// We check if the vertex is a node.\r\n\t\t\t\tint nextNodeId = mapVertexToNode[nextVertexIdx];\r\n\t\t\t\tif (nextNodeId >= 0 && nextNodeId != nodeId) {\r\n                    neighborNodeIds.push_back(nextNodeId);\r\n                    neighborNodeWeights.push_back(compute_anchor_weight(nextVertexDist, nodeCoverage));\r\n                    neighborNodeDistances.push_back(nextVertexDist);\r\n                    if (neighborNodeIds.size() >= nMaxNeighbors) break;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// Note down the node-vertex distance.\r\n\t\t\t\t*nodeToVertexDistances.mutable_data(nodeId, nextVertexIdx) = nextVertexDist;\r\n\r\n\t\t\t\t// We visit the vertex, and check all his neighbors.\r\n\t\t\t\t// We add only valid vertices under a certain distance\r\n\t\t\t\tvisitedVertices.insert(nextVertexIdx);\r\n\t\t\t\tEigen::Vector3f nextVertexPos(*vertexPositions.data(nextVertexIdx, 0), *vertexPositions.data(nextVertexIdx, 1), *vertexPositions.data(nextVertexIdx, 2));\r\n\r\n\t\t\t\tconst auto& nextNeighbors = vertexNeighbors[nextVertexIdx];\r\n\t\t\t\tfor (int neighborIdx : nextNeighbors) {\r\n\r\n                    bool is_valid_vertex = *validVertices.data(neighborIdx); \r\n                    if (allow_only_valid_vertices && !is_valid_vertex) {\r\n                        continue;\r\n                    }\r\n\r\n\t\t\t\t\tEigen::Vector3f neighborVertexPos(*vertexPositions.data(neighborIdx, 0), *vertexPositions.data(neighborIdx, 1), *vertexPositions.data(neighborIdx, 2));\r\n\t\t\t\t\tfloat dist = nextVertexDist + (nextVertexPos - neighborVertexPos).norm();\r\n                    \r\n                    if (enforce_total_num_neighbors) {\r\n\t\t\t\t\t\tnextVerticesWithIds.push(std::make_pair(neighborIdx, dist));\r\n                    }\r\n\t\t\t\t\telse {\r\n                        // std::cout << dist << \" \" << maxInfluence << std::endl;\r\n                        if (dist <= maxInfluence) {\r\n\t\t\t\t\t\t    nextVerticesWithIds.push(std::make_pair(neighborIdx, dist));\r\n\t\t\t\t\t    }\r\n                    } \r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n            // Store the nearest neighbors.\r\n            int nNeighbors = neighborNodeIds.size();\r\n\r\n            float weightSum = 0.f;\r\n            for (int i = 0; i < nNeighbors; i++) {\r\n                *graphEdges.mutable_data(nodeId, i) = neighborNodeIds[i];\r\n                weightSum += neighborNodeWeights[i];\r\n            }\r\n\r\n            // Normalize weights\r\n            if (weightSum > 0) {\r\n                for (int i = 0; i < nNeighbors; i++) {\r\n                    *graphEdgesWeights.mutable_data(nodeId, i) = neighborNodeWeights[i] / weightSum;\r\n                }\r\n            }\r\n            else if (nNeighbors > 0) {\r\n                for (int i = 0; i < nNeighbors; i++) {\r\n                    *graphEdgesWeights.mutable_data(nodeId, i) = neighborNodeWeights[i] / nNeighbors;\r\n                }\r\n            }\r\n\r\n            // Store edge distance.\r\n            for (int i = 0; i < nNeighbors; i++) {\r\n                *graphEdgesDistances.mutable_data(nodeId, i) = neighborNodeDistances[i];\r\n            }\r\n\t\t}\r\n    }\r\n\r\n    py::array_t<int> compute_edges_euclidean(const py::array_t<float>& nodePositions, int nMaxNeighbors) {\r\n        int nNodes = nodePositions.shape(0);\r\n\r\n        py::array_t<int> graphEdges = py::array_t<int>({ nNodes, nMaxNeighbors });\r\n\r\n        // Find nearest Euclidean neighbors for each node.\r\n        for (int nodeId = 0; nodeId < nNodes; nodeId++) {\r\n            Eigen::Vector3f nodePos(*nodePositions.data(nodeId, 0), *nodePositions.data(nodeId, 1), *nodePositions.data(nodeId, 2));\r\n\r\n            // Keep only the k nearest Euclidean neighbors.\r\n            std::list<std::pair<int, float>> nearestNodesWithSquaredDistances;\r\n\r\n            for (int neighborId = 0; neighborId < nNodes; neighborId++) {\r\n                if (neighborId == nodeId) continue;\r\n\r\n                Eigen::Vector3f neighborPos(*nodePositions.data(neighborId, 0), *nodePositions.data(neighborId, 1), *nodePositions.data(neighborId, 2));\r\n\r\n                float distance2 = (nodePos - neighborPos).squaredNorm();\r\n                bool bInserted = false;\r\n                for (auto it = nearestNodesWithSquaredDistances.begin(); it != nearestNodesWithSquaredDistances.end(); ++it) {\r\n                    // We insert the element at the first position where its distance is smaller than the other\r\n                    // element's distance, which enables us to always keep a sorted list of at most k nearest\r\n                    // neighbors.\r\n                    if (distance2 <= it->second) {\r\n                        it = nearestNodesWithSquaredDistances.insert(it, std::make_pair(neighborId, distance2));\r\n                        bInserted = true;\r\n                        break;\r\n                    }\r\n                }\r\n\r\n                if (!bInserted && nearestNodesWithSquaredDistances.size() < nMaxNeighbors) {\r\n                    nearestNodesWithSquaredDistances.emplace_back(std::make_pair(neighborId, distance2));\r\n                }\r\n\r\n                // We keep only the list of k nearest elements.\r\n                if (bInserted && nearestNodesWithSquaredDistances.size() > nMaxNeighbors) {\r\n                    nearestNodesWithSquaredDistances.pop_back();\r\n                }\r\n            }\r\n            \r\n            // Store nearest neighbor ids.\r\n            int idx = 0;\r\n            for (auto it = nearestNodesWithSquaredDistances.begin(); it != nearestNodesWithSquaredDistances.end(); ++it) {\r\n                int neighborId = it->first;\r\n                *graphEdges.mutable_data(nodeId, idx) = neighborId;\r\n                idx++;\r\n            }\r\n\r\n            for (idx = nearestNodesWithSquaredDistances.size(); idx < nMaxNeighbors; idx++) {\r\n                *graphEdges.mutable_data(nodeId, idx) = -1;\r\n            }\r\n        }\r\n\r\n        return graphEdges;\r\n    }\r\n\r\n    inline int traverse_neighbors(const std::vector<std::set<int>>& node_neighbors, std::vector<int>& cluster_ids, int cluster_id, int node_id) {\r\n        if (cluster_ids[node_id] != -1) return 0;\r\n        \r\n        std::set<int> active_node_indices;\r\n\r\n        // Initialize with current node.\r\n        int cluster_size = 0;\r\n        active_node_indices.insert(node_id);\r\n\r\n        // Process until we have no active nodes anymore.\r\n        while (!active_node_indices.empty()) {\t\r\n            int active_node_id = *active_node_indices.begin();\r\n            active_node_indices.erase(active_node_indices.begin());\r\n\r\n            if (cluster_ids[active_node_id] == -1) {\r\n                cluster_ids[active_node_id] = cluster_id;\r\n                ++cluster_size;\r\n            }\r\n\r\n            // Look if we need to process any of the neighbors\r\n            for (const auto& n_idx : node_neighbors[active_node_id]) {\r\n                if (cluster_ids[n_idx] == -1) {\t// If it doesn't have a cluster yet\r\n                    active_node_indices.insert(n_idx);\r\n                }\r\n            }\r\n        }\r\n\r\n        return cluster_size;\r\n    }\r\n\r\n    void node_and_edge_clean_up(const py::array_t<int>& graph_edges, py::array_t<bool>& valid_nodes_mask) {\r\n        int num_nodes = graph_edges.shape(0);\r\n        int max_num_neighbors = graph_edges.shape(1);\r\n\r\n        std::list<int> removed_nodes;\r\n\r\n        while (true) {\r\n            int num_newly_removed_nodes = 0;\r\n\r\n            for (int node_id = 0; node_id < num_nodes; ++node_id) {\r\n\r\n                if (*valid_nodes_mask.data(node_id, 0) == false) {\r\n                    // if node has been already removed, continue\r\n                    continue;\r\n                }\r\n\r\n                int num_neighbors = 0;\r\n                for (int i = 0; i < max_num_neighbors; ++i) {\r\n\r\n                    int neighbor_id = *graph_edges.data(node_id, i);\r\n                    \r\n                    // if neighboring node is -1, break, since by design 'graph_edges' has\r\n                    // the shape [2, 3, 6, -1, -1, -1, -1, -1]\r\n                    if (neighbor_id == -1) {\r\n                        break;\r\n                    }\r\n\r\n                    // if neighboring node has been marked as invalid, continue\r\n                    if (std::find(removed_nodes.begin(), removed_nodes.end(), neighbor_id) != removed_nodes.end()) {\r\n                        continue;\r\n                    }\r\n\r\n                    ++num_neighbors;\r\n                }\r\n\r\n                if (num_neighbors <= 1) {\r\n                    // remove node\r\n                    *valid_nodes_mask.mutable_data(node_id, 0) = false;\r\n                    removed_nodes.emplace_back(node_id);\r\n                    // std::cout << \"\\tremoving node_id \" << node_id << std::endl;\r\n                    ++num_newly_removed_nodes;\r\n                }\r\n            }\r\n\r\n            // std::cout << \"num_newly_removed_nodes: \" << num_newly_removed_nodes << std::endl;\r\n\r\n            if (num_newly_removed_nodes == 0) {\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    std::vector<int> compute_clusters(\r\n        const py::array_t<int> graph_edges,\r\n        py::array_t<int> graph_clusters\r\n    ) {\r\n        int num_nodes = graph_edges.shape(0);\r\n        int max_num_neighbors = graph_edges.shape(1);\r\n\r\n        // convert graph_edges to a vector of sets\r\n        std::vector<std::set<int>> node_neighbors(num_nodes);\r\n\r\n        for (int node_id = 0; node_id < num_nodes; ++node_id) {\r\n            for (int neighbor_idx = 0; neighbor_idx < max_num_neighbors; ++neighbor_idx) {\r\n                \r\n                int neighbor_id = *graph_edges.data(node_id, neighbor_idx);\r\n                \r\n                if (neighbor_id == -1) {\r\n                    break;\r\n                }\r\n\r\n                node_neighbors[node_id].insert(neighbor_id);\r\n                node_neighbors[neighbor_id].insert(node_id);\r\n            }\r\n        }\r\n\r\n        std::vector<int> cluster_ids(num_nodes, -1);\r\n        std::vector<int> clusters_size;\r\n\r\n        int cluster_id = 0;\r\n        for (int node_id = 0; node_id < num_nodes; ++node_id) {\r\n            int cluster_size = traverse_neighbors(node_neighbors, cluster_ids, cluster_id, node_id);\r\n            if (cluster_size > 0) {\r\n                cluster_id++;\r\n                clusters_size.push_back(cluster_size);\r\n            }\r\n        }\r\n\r\n        for (int node_id = 0; node_id < num_nodes; ++node_id) {\r\n            *graph_clusters.mutable_data(node_id, 0) = cluster_ids[node_id];\r\n        }\r\n\r\n        return clusters_size;\r\n    }   \r\n\r\n    inline void compute_nearest_geodesic_nodes(\r\n        const py::array_t<float>&  node_to_vertex_distance, \r\n        const py::array_t<int>& valid_nodes_mask,\r\n        const int vertex_id, \r\n        std::vector<int>& nearest_geodesic_node_ids, \r\n        std::vector<float>& dist_to_nearest_geodesic_nodes\r\n    ) {\r\n        int num_nodes = node_to_vertex_distance.shape(0);\r\n\r\n        std::map<int, float> node_map;\r\n\r\n        for (int n = 0; n < num_nodes; ++n) {\r\n\r\n            // discard node if it was marked as invalid (due to not having enough neighbors)\r\n            if (*valid_nodes_mask.data(n, 0) == false) {\r\n                continue;\r\n            }\r\n\r\n            float dist = *node_to_vertex_distance.data(n, vertex_id);\r\n\r\n            if (dist >= 0) {\r\n                node_map.emplace(n, dist);\r\n            }\r\n        }\r\n\r\n        // Sort the map by distance\r\n        // Declaring the type of Predicate that accepts 2 pairs and return a bool\r\n        typedef std::function<bool(std::pair<int, float>, std::pair<int, float>)> Comparator;\r\n \r\n        // Defining a lambda function to compare two pairs. It will compare two pairs using second field\r\n        Comparator comp_functor =\r\n            [](std::pair<int, float> node1 ,std::pair<int, float> node2) {\r\n                return node1.second < node2.second;\r\n            };\r\n\r\n        // Declaring a set that will store the pairs using above comparision logic\r\n        std::set<std::pair<int, float>, Comparator> node_set(\r\n            node_map.begin(), node_map.end(), comp_functor\r\n        );\r\n\r\n        for (auto n : node_set) {\r\n            nearest_geodesic_node_ids.push_back(n.first);\r\n            dist_to_nearest_geodesic_nodes.push_back(n.second);\r\n\r\n            if (nearest_geodesic_node_ids.size() == GRAPH_K) {\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    void compute_pixel_anchors_geodesic(\r\n        const py::array_t<float> &node_to_vertex_distance, \r\n        const py::array_t<int> &valid_nodes_mask, \r\n        const py::array_t<float> &vertices,\r\n        const py::array_t<int> &vertex_pixels, \r\n        py::array_t<int>& pixel_anchors, \r\n        py::array_t<float>& pixel_weights,\r\n        const int width, const int height,\r\n        const float node_coverage\r\n    ) {\r\n        // Allocate graph node ids and corresponding skinning weights.\r\n        // Initialize with invalid anchors.\r\n        pixel_anchors.resize({ height, width, GRAPH_K }, false);\r\n        pixel_weights.resize({ height, width, GRAPH_K }, false);\r\n\r\n        for (int y = 0; y < height; y++) {\r\n            for (int x = 0; x < width; x++) {\r\n                for (int k = 0; k < GRAPH_K; k++) {\r\n                    *pixel_anchors.mutable_data(y, x, k) = -1;\r\n                    *pixel_weights.mutable_data(y, x, k) = 0.f;\r\n                }\r\n            }\r\n        }\r\n\r\n        int num_vertices = vertices.shape(0);\r\n\r\n        for (int vertex_id = 0; vertex_id < num_vertices; vertex_id++) {\r\n            // Get corresponding pixel location\r\n            int u = *vertex_pixels.data(vertex_id, 0);\r\n            int v = *vertex_pixels.data(vertex_id, 1);\r\n\r\n            // Initialize some variables\r\n            std::vector<int> nearest_geodesic_node_ids;\r\n            std::vector<float> dist_to_nearest_geodesic_nodes;\r\n            std::vector<float> skinning_weights;\r\n\r\n            nearest_geodesic_node_ids.reserve(GRAPH_K);\r\n            dist_to_nearest_geodesic_nodes.reserve(GRAPH_K);\r\n            skinning_weights.reserve(GRAPH_K);\r\n\r\n            // Find closest geodesic nodes\r\n            compute_nearest_geodesic_nodes(\r\n                node_to_vertex_distance, valid_nodes_mask, vertex_id,\r\n                nearest_geodesic_node_ids, dist_to_nearest_geodesic_nodes\r\n            );\r\n\r\n            int num_anchors = nearest_geodesic_node_ids.size();\r\n\r\n            // Compute skinning weights.\r\n            float weight_sum{ 0.f };\r\n            for (int i = 0; i < num_anchors; ++i) {\r\n                float geodesic_dist_to_node = dist_to_nearest_geodesic_nodes[i];\r\n\r\n                float weight = compute_anchor_weight(geodesic_dist_to_node, node_coverage);\r\n                weight_sum += weight;\r\n\r\n                skinning_weights.push_back(weight);\r\n            }\r\n\r\n            // Normalize the skinning weights.\r\n            if (weight_sum > 0) {\r\n                for (int i = 0; i < num_anchors; i++)\r\n                    skinning_weights[i] /= weight_sum;\r\n            }\r\n            else if (num_anchors > 0) {\r\n                for (int i = 0; i < num_anchors; i++)\r\n                    skinning_weights[i] = 1.f / num_anchors;\r\n            }\r\n            \r\n            // Store the results.\r\n            for (int i = 0; i < num_anchors; i++) {\r\n                *pixel_anchors.mutable_data(v, u, i) = nearest_geodesic_node_ids[i];\r\n                *pixel_weights.mutable_data(v, u, i) = skinning_weights[i];\r\n            }\r\n        }\r\n    }\r\n\r\n    void compute_pixel_anchors_euclidean(\r\n        const py::array_t<float>& graphNodes, \r\n        const py::array_t<float>& pointImage,\r\n        float nodeCoverage,\r\n        py::array_t<int>& pixelAnchors, \r\n        py::array_t<float>& pixelWeights\r\n    ) {\r\n        int nNodes = graphNodes.shape(0);\r\n        int width = pointImage.shape(2);\r\n        int height = pointImage.shape(1);\r\n        // int nChannels = pointImage.shape(0);\r\n\r\n        // Allocate graph node ids and corresponding skinning weights.\r\n        // Initialize with invalid anchors.\r\n        pixelAnchors.resize({ height, width, GRAPH_K }, false);\r\n        pixelWeights.resize({ height, width, GRAPH_K }, false);\r\n\r\n        for (int y = 0; y < height; y++) {\r\n            for (int x = 0; x < width; x++) {\r\n                for (int k = 0; k < GRAPH_K; k++) {\r\n                    *pixelAnchors.mutable_data(y, x, k) = -1;\r\n                    *pixelWeights.mutable_data(y, x, k) = 0.f;\r\n                }\r\n            }\r\n        }\r\n\r\n        // Compute anchors for every pixel.\r\n        #pragma omp parallel for\r\n        for (int y = 0; y < height; y++) {\r\n            for (int x = 0; x < width; x++) {\r\n                // Query 3d pixel position.\r\n                Eigen::Vector3f pixelPos(*pointImage.data(0, y, x), *pointImage.data(1, y, x), *pointImage.data(2, y, x));\r\n                if (pixelPos.z() <= 0) continue;\r\n                \r\n                // Keep only the k nearest Euclidean neighbors.\r\n                std::list<std::pair<int, float>> nearestNodesWithSquaredDistances;\r\n\r\n                for (int nodeId = 0; nodeId < nNodes; nodeId++) {\r\n                    Eigen::Vector3f nodePos(*graphNodes.data(nodeId, 0), *graphNodes.data(nodeId, 1), *graphNodes.data(nodeId, 2));\r\n\r\n                    float distance2 = (pixelPos - nodePos).squaredNorm();\r\n                    bool bInserted = false;\r\n                    for (auto it = nearestNodesWithSquaredDistances.begin(); it != nearestNodesWithSquaredDistances.end(); ++it) {\r\n                        // We insert the element at the first position where its distance is smaller than the other\r\n                        // element's distance, which enables us to always keep a sorted list of at most k nearest\r\n                        // neighbors.\r\n                        if (distance2 <= it->second) {\r\n                            it = nearestNodesWithSquaredDistances.insert(it, std::make_pair(nodeId, distance2));\r\n                            bInserted = true;\r\n                            break;\r\n                        }\r\n                    }\r\n\r\n                    if (!bInserted && nearestNodesWithSquaredDistances.size() < GRAPH_K) {\r\n                        nearestNodesWithSquaredDistances.emplace_back(std::make_pair(nodeId, distance2));\r\n                    }\r\n\r\n                    // We keep only the list of k nearest elements.\r\n                    if (bInserted && nearestNodesWithSquaredDistances.size() > GRAPH_K) {\r\n                        nearestNodesWithSquaredDistances.pop_back();\r\n                    }\r\n                }\r\n\r\n                // Compute skinning weights.\r\n                std::vector<int> nearestEuclideanNodeIds;\r\n                nearestEuclideanNodeIds.reserve(nearestNodesWithSquaredDistances.size());\r\n\r\n                std::vector<float> skinningWeights;\r\n                skinningWeights.reserve(nearestNodesWithSquaredDistances.size());\r\n\r\n                float weightSum{ 0.f };\r\n                for (auto it = nearestNodesWithSquaredDistances.begin(); it != nearestNodesWithSquaredDistances.end(); ++it) {\r\n                    int nodeId = it->first;\r\n\r\n                    Eigen::Vector3f nodePos(*graphNodes.data(nodeId, 0), *graphNodes.data(nodeId, 1), *graphNodes.data(nodeId, 2));\r\n                    float weight = compute_anchor_weight(pixelPos, nodePos, nodeCoverage);\r\n                    weightSum += weight;\r\n\r\n                    nearestEuclideanNodeIds.push_back(nodeId);\r\n                    skinningWeights.push_back(weight);\r\n                }\r\n\r\n                // Normalize the skinning weights.\r\n                int nAnchors = nearestEuclideanNodeIds.size();\r\n\r\n                if (weightSum > 0) {\r\n                    for (int i = 0; i < nAnchors; i++)\tskinningWeights[i] /= weightSum;\r\n                }\r\n                else if (nAnchors > 0) {\r\n                    for (int i = 0; i < nAnchors; i++)\tskinningWeights[i] = 1.f / nAnchors;\r\n                }\r\n                \r\n                // Store the results.\r\n                for (int i = 0; i < nAnchors; i++) {\r\n                    *pixelAnchors.mutable_data(y, x, i) = nearestEuclideanNodeIds[i];\r\n                    *pixelWeights.mutable_data(y, x, i) = skinningWeights[i];\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    void construct_regular_graph(\r\n        const py::array_t<float>& pointImage,\r\n        int xNodes, int yNodes,\r\n        float edgeThreshold,\r\n        float maxPointToNodeDistance,\r\n        float maxDepth,\r\n        py::array_t<float>& graphNodes, \r\n        py::array_t<int>& graphEdges, \r\n        py::array_t<int>& pixelAnchors, \r\n        py::array_t<float>& pixelWeights\r\n    ) {\r\n        int width = pointImage.shape(2);\r\n        int height = pointImage.shape(1);\r\n        int nChannels = pointImage.shape(0);\r\n\r\n        float xStep = float(width - 1) / (xNodes - 1);\r\n        float yStep = float(height - 1) / (yNodes - 1);\r\n\r\n        // Sample graph nodes.\r\n        // We need to maintain the mapping from all -> valid nodes ids.\r\n        int nNodes = xNodes * yNodes;\r\n        std::vector<int> sampledNodeMapping(nNodes, -1);\r\n\r\n        std::vector<Eigen::Vector3f> nodePositions;\r\n        nodePositions.reserve(nNodes);\r\n\r\n        int nodeId = 0;\r\n        for (int y = 0; y < yNodes; y++) {\r\n            for (int x = 0; x < xNodes; x++) {\r\n                int nodeIdx = y * xNodes + x;\r\n\r\n                // We use nearest neighbor interpolation for node position\r\n                // computation.\r\n                int xPixel = std::round(x * xStep); \r\n                int yPixel = std::round(y * yStep);\r\n\r\n                Eigen::Vector3f pixelPos(*pointImage.data(0, yPixel, xPixel), *pointImage.data(1, yPixel, xPixel), *pointImage.data(2, yPixel, xPixel));\r\n                if (pixelPos.z() <= 0 || pixelPos.z() > maxDepth) continue;\r\n\r\n                nodePositions.push_back(pixelPos);\r\n                sampledNodeMapping[nodeIdx] = nodeId;\r\n                nodeId++;\r\n            }\r\n        }\r\n        int nSampledNodes = nodeId;\r\n\r\n        // Compute graph edges using pixel-wise connectivity. Each node\r\n        // is connected with at most 8 neighboring pixels.\r\n        int numNeighbors = 8;\r\n        float edgeThreshold2 = edgeThreshold * edgeThreshold;\r\n\r\n        std::vector<int> sampledNodeEdges(nSampledNodes * numNeighbors, -1);\r\n        std::vector<bool> connectedNodes(nSampledNodes, false);\r\n\r\n        int nConnectedNodes = 0;\r\n        for (int y = 0; y < yNodes; y++) {\r\n            for (int x = 0; x < xNodes; x++) {\r\n                int nodeIdx = y * xNodes + x;\r\n                int nodeId = sampledNodeMapping[nodeIdx];\r\n\r\n                if (nodeId >= 0) {\r\n                    Eigen::Vector3f nodePosition = nodePositions[nodeId];\r\n\r\n                    int neighborCount = 0;\r\n                    for (int yDelta = -1; yDelta <= 1; yDelta++) {\r\n                        for (int xDelta = -1; xDelta <= 1; xDelta++) {\r\n                            int xNeighbor = x + xDelta;\r\n                            int yNeighbor = y + yDelta;\r\n                            if (xNeighbor < 0 || xNeighbor >= xNodes || yNeighbor < 0 || yNeighbor >= yNodes)\r\n                                continue;\r\n                            \r\n                            int neighborIdx = yNeighbor * xNodes + xNeighbor;\r\n                            \r\n                            if (neighborIdx == nodeIdx || neighborIdx < 0)\r\n                                continue;\r\n\r\n                            int neighborId = sampledNodeMapping[neighborIdx];\r\n                            if (neighborId >= 0) {\r\n                                Eigen::Vector3f neighborPosition = nodePositions[neighborId];\r\n\r\n                                if ((neighborPosition - nodePosition).squaredNorm() <= edgeThreshold2) {\r\n                                    sampledNodeEdges[nodeId * numNeighbors + neighborCount] = neighborId;\r\n                                    neighborCount++;\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    for (int i = neighborCount; i < numNeighbors; i++) {\r\n                        sampledNodeEdges[nodeId * numNeighbors + i] = -1;\r\n                    }\r\n\r\n                    if (neighborCount > 0) {\r\n                        connectedNodes[nodeId] = true;\r\n                        nConnectedNodes += 1;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        // Filter out nodes with no edges.\r\n        // After changing node ids the edge ids need to be changed as well.\r\n        std::vector<int> validNodeMapping(nSampledNodes, -1);\r\n\r\n        graphNodes.resize({ nConnectedNodes, 3 }, false);\r\n        graphEdges.resize({ nConnectedNodes, numNeighbors }, false);\r\n\r\n        int validNodeId = 0;\r\n        for (int y = 0; y < yNodes; y++) {\r\n            for (int x = 0; x < xNodes; x++) {\r\n                int nodeIdx = y * xNodes + x;\r\n                int nodeId = sampledNodeMapping[nodeIdx];\r\n\r\n                if (nodeId >= 0 && connectedNodes[nodeId]) {\r\n                    validNodeMapping[nodeId] = validNodeId;\r\n\r\n                    Eigen::Vector3f nodePosition = nodePositions[nodeId];\r\n                    *graphNodes.mutable_data(validNodeId, 0) = nodePosition.x();\r\n                    *graphNodes.mutable_data(validNodeId, 1) = nodePosition.y();\r\n                    *graphNodes.mutable_data(validNodeId, 2) = nodePosition.z();\r\n\r\n                    validNodeId++;\r\n                }\r\n            }\r\n        }\r\n\r\n        for (int y = 0; y < yNodes; y++) {\r\n            for (int x = 0; x < xNodes; x++) {\r\n                int nodeIdx = y * xNodes + x;\r\n                int nodeId = sampledNodeMapping[nodeIdx];\r\n\r\n                if (nodeId >= 0 && connectedNodes[nodeId]) {\r\n                    int validNodeId = validNodeMapping[nodeId];\r\n                    \r\n                    if (validNodeId >= 0) {\r\n                        for (int i = 0; i < numNeighbors; i++) {\r\n                            int sampledNeighborId = sampledNodeEdges[nodeId * numNeighbors + i];\r\n                            if (sampledNeighborId >= 0) {\r\n                                *graphEdges.mutable_data(validNodeId, i) = validNodeMapping[sampledNeighborId];\r\n                            }\r\n                            else {\r\n                                *graphEdges.mutable_data(validNodeId, i) = -1;\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        // Compute pixel anchors and weights.\r\n        pixelAnchors.resize({ height, width, 4 }, false);\r\n        pixelWeights.resize({ height, width, 4 }, false);\r\n\r\n        float maxPointToNodeDistance2 = maxPointToNodeDistance * maxPointToNodeDistance;\r\n\r\n        for (int y = 0; y < height; y++) {\r\n            for (int x = 0; x < width; x++) {\r\n                // Initialize with invalid values. \r\n                for (int k = 0; k < 4; k++) {\r\n                    *pixelAnchors.mutable_data(y, x, k) = -1;\r\n                    *pixelWeights.mutable_data(y, x, k) = 0.f;\r\n                }\r\n                \r\n                // Compute 4 nearest nodes.\r\n                float xNode = float(x) / xStep;\r\n                float yNode = float(y) / yStep;\r\n\r\n                int x0 = std::floor(xNode), x1 = x0 + 1;\r\n                int y0 = std::floor(yNode), y1 = y0 + 1;\r\n\r\n                // Check that all neighboring nodes are valid.\r\n                if (x0 < 0 || x1 >= xNodes || y0 < 0 || y1 >= yNodes)\r\n                    continue;\r\n\r\n                int sampledNode00 = sampledNodeMapping[y0 * xNodes + x0];\r\n                int sampledNode01 = sampledNodeMapping[y1 * xNodes + x0];\r\n                int sampledNode10 = sampledNodeMapping[y0 * xNodes + x1];\r\n                int sampledNode11 = sampledNodeMapping[y1 * xNodes + x1];\r\n\r\n                if (sampledNode00 < 0 || sampledNode01 < 0 || sampledNode10 < 0 || sampledNode11 < 0)\r\n                    continue;\r\n\r\n                int validNode00 = validNodeMapping[sampledNode00];\r\n                int validNode01 = validNodeMapping[sampledNode01];\r\n                int validNode10 = validNodeMapping[sampledNode10];\r\n                int validNode11 = validNodeMapping[sampledNode11];\r\n\r\n                if (validNode00 < 0 || validNode01 < 0 || validNode10 < 0 || validNode11 < 0)\r\n                    continue;\r\n\r\n                // Check that all nodes are close enough to the point.\r\n                Eigen::Vector3f pixelPos(*pointImage.data(0, y, x), *pointImage.data(1, y, x), *pointImage.data(2, y, x));\r\n                if (pixelPos.z() <= 0 || pixelPos.z() > maxDepth) continue;\r\n\r\n                if ((pixelPos - nodePositions[sampledNode00]).squaredNorm() > maxPointToNodeDistance2 ||\r\n                    (pixelPos - nodePositions[sampledNode01]).squaredNorm() > maxPointToNodeDistance2 ||\r\n                    (pixelPos - nodePositions[sampledNode10]).squaredNorm() > maxPointToNodeDistance2 ||\r\n                    (pixelPos - nodePositions[sampledNode11]).squaredNorm() > maxPointToNodeDistance2\r\n                ) {\r\n                    continue;\r\n                }\r\n\r\n                // Compute bilinear weights.\r\n                float dx = xNode - x0;\r\n                float dy = yNode - y0;\r\n\r\n                float w00 = (1 - dx) * (1 - dy);\r\n                float w01 = (1 - dx) * dy;\r\n                float w10 = dx * (1 - dy);\r\n                float w11 = dx * dy;\r\n                \r\n                *pixelAnchors.mutable_data(y, x, 0) = validNode00;\r\n                *pixelWeights.mutable_data(y, x, 0) = w00;\r\n                *pixelAnchors.mutable_data(y, x, 1) = validNode01;\r\n                *pixelWeights.mutable_data(y, x, 1) = w01;\r\n                *pixelAnchors.mutable_data(y, x, 2) = validNode10;\r\n                *pixelWeights.mutable_data(y, x, 2) = w10;\r\n                *pixelAnchors.mutable_data(y, x, 3) = validNode11;\r\n                *pixelWeights.mutable_data(y, x, 3) = w11;\r\n            }\r\n        }\r\n    }\r\n\r\n    void update_pixel_anchors(\r\n        const std::map<int, int>& node_id_mapping,\r\n        py::array_t<int>& pixel_anchors\r\n    ) {\r\n        int height      = pixel_anchors.shape(0);\r\n        int width       = pixel_anchors.shape(1);\r\n        int num_anchors = pixel_anchors.shape(2);\r\n\r\n        for (int y = 0; y < height; y++) {\r\n            for (int x = 0; x < width; x++) {\r\n\r\n                for (int a = 0; a < num_anchors; a++) {\r\n\r\n                    int current_anchor_id = *pixel_anchors.data(y, x, a);\r\n                    \r\n                    if (current_anchor_id != -1) {\r\n                        int mapped_anchor_id = node_id_mapping.at(current_anchor_id);\r\n\r\n                        // update anchor only if it would actually change something\r\n                        if (mapped_anchor_id != current_anchor_id) {\r\n                            *pixel_anchors.mutable_data(y, x, a) = mapped_anchor_id;\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n} // namespace graph_proc", "meta": {"hexsha": "c97530799e53c3cddd6713fc794608a1c84de7e8", "size": 39872, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "csrc/cpu/graph_proc.cpp", "max_stars_repo_name": "erezposner/NeuralTracking", "max_stars_repo_head_hexsha": "df03e13ef627fad7a392fb969bd7c79da1887b39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 139.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T22:28:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T18:22:41.000Z", "max_issues_repo_path": "csrc/cpu/graph_proc.cpp", "max_issues_repo_name": "erezposner/NeuralTracking", "max_issues_repo_head_hexsha": "df03e13ef627fad7a392fb969bd7c79da1887b39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-10-26T09:18:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-14T07:59:42.000Z", "max_forks_repo_path": "csrc/cpu/graph_proc.cpp", "max_forks_repo_name": "erezposner/NeuralTracking", "max_forks_repo_head_hexsha": "df03e13ef627fad7a392fb969bd7c79da1887b39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-10-22T01:18:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T00:50:13.000Z", "avg_line_length": 41.4901144641, "max_line_length": 158, "alphanum_fraction": 0.5271869984, "num_tokens": 8888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.44854574641440736}}
{"text": "/*\r\nThis file is a part of Raman-Scattering-Code-Conversion.\r\n<https://github.com/Kirbologist/Raman-Scattering-Code-Conversion>\r\n\r\nWritten by Siwan Li for the UQ School of Maths and Physics.\r\nCopyright (C) 2021-2022 Siwan Li\r\n\r\nThis source code form is subject to the terms of the MIT License.\r\nIf a copy of the MIT License was not distributed with this file,\r\nyou can obtain one at <https://opensource.org/licenses/MIT>.\r\n\r\n\r\nThis code is used to calculate Raman scattering off of spheroids.\r\nNone of the code was included in the original SMARTIES package.\r\nMany functions are used to provide I/O support to the main function.\r\n*/\r\n\r\n#ifndef RAMAN_ELASTIC_SCATTERING_HPP\r\n#define RAMAN_ELASTIC_SCATTERING_HPP\r\n\r\n#include \"core.hpp\"\r\n#include \"smarties.hpp\"\r\n#include <boost/lexical_cast.hpp>\r\n#include <chrono>\r\n#include <filesystem>\r\n#include <fstream>\r\n#include <exception>\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\nusing namespace Smarties;\r\nusing boost::lexical_cast;\r\nusing boost::bad_lexical_cast;\r\n\r\n/* Possible floating-point types used in calculations */\r\nenum CalcType {SINGLE, DOUBLE, QUAD, CUSTOM, NONE};\r\n\r\n/*\r\nControllable parameters that are used for calculations.\r\n_rm suffix denotes parameters used for excitation T-matrix,\r\nabsense of _rm suffix denotes parameters used for Raman T-matrix.\r\n*/\r\ntemplate <class Real>\r\nstruct RamanParams {\r\n  // Describes the minimum and maximum of the particle diameter\r\n  Real dia_min = 1000;\r\n  Real dia_max = 2000;\r\n\r\n  int N_rad = 100; // Number of particle sizes to calculate for\r\n  int N_theta_p = 19; // Number of particle orientations to calculate for\r\n  Real phi_p = 0; // Angle of rotation of particle about the z semiaxis\r\n\r\n  // Number of spherical coordinates used throughout the volume of the particle\r\n  int N_r = 100;\r\n  int N_theta = 320;\r\n  int N_phi = 320;\r\n\r\n  // Values of h used, where h = a/c. N_h is the number of h values\r\n  int N_h = 1;\r\n  Real h_min = static_cast<Real>(1.0)/3;\r\n  Real h_max = static_cast<Real>(1.0)/3;\r\n\r\n  // Incident light parameters. Used for stParams struct\r\n  Real epsilon1 = 1;\r\n  Real epsilon2 = pow(static_cast<Real>(1.35), 2);\r\n  Real epsilon2_rm = pow(static_cast<Real>(1.344), 2);\r\n  Real lambda = 355;\r\n  Real lambda_rm = 403.7;\r\n\r\n  // Used for stParams struct\r\n  int Nb_theta = 1000;\r\n  int Nb_theta_pst = 1;\r\n\r\n  // Used for stOptions struct\r\n  int delta = 0;\r\n\r\n  // Vectors of all possible radii/theta/h values\r\n  ArrayXr<Real> rad_var;\r\n  ArrayXr<Real> theta_p_var;\r\n  ArrayXr<Real> h_var;\r\n};\r\n\r\n// All non-template functions defined in raman_elastic_scattering.cpp\r\n\r\n/*\r\nGet the 2 types to be used for floating-point calculations from a text file.\r\nInputs:\r\n  in_file_name: path of the text file which contains the calculation type\r\nOutput:\r\n  String array of size 2 that specifies 2 calculation types.\r\n*/\r\nstd::array<CalcType, 2> GetCalcType(string in_file_name);\r\n\r\n/*\r\nGet the value given for some parameter from a text file.\r\nInputs:\r\n  in_file_name: path of the text file which contains the option\r\n  option: The exact string of the specific option/parameter to look for\r\nOutput:\r\n  The user-defined value given to the option, as a string\r\n*/\r\nstring GetOption(string in_file_name, string option);\r\n\r\n/*\r\nDetermine if it's okay to write calculation info to a file from an option in a text file.\r\nI.e. it checks the \"Print output to file:\" parameter.\r\nInputs:\r\n  in_file_name: path of the text file which specifies if it's okay to write to output or not\r\nOutput:\r\n  True if the file says \"yes\", i.e. it is okay, false otherwise\r\n*/\r\nbool CanWriteOutput(string in_file_name);\r\n\r\n/*\r\nDetermine number of CPUs to use from a text file. I.e. it checks the \"No. of CPUs\" parameter.\r\nInputs:\r\n  in_file_name: path of the text file which specifies the number of CPUs.\r\nOutput:\r\n  The number of CPUs that are allowed\r\n*/\r\nint GetNumCPUs(string in_file_name);\r\n\r\n/*\r\nDetermine number of threads to split the particle radii for from a text file.\r\nI.e. it checks the \"No. of CPUs to partition particle radii for:\" parameter.\r\nNote that any one of these threads can still fork into more threads if there are any available.\r\nInputs:\r\n  in_file_name: path of the text file which specifies the number of CPUs.\r\nOutput:\r\n  The number of CPUs to partition particle radii for\r\n*/\r\nint GetNumParticleCPUs(string in_file_name);\r\n\r\n/*\r\nPrints a string to both standard output (the terminal) and appends it to a text ilfe (if allowed).\r\nInputs:\r\n  out_string: the string to print/write\r\n  out_file_name: path of the text file to write to\r\n  write_output: true enables writing to output, false disables it.\r\n*/\r\nvoid MultiPrint(string out_string, string out_file_name, bool write_output = false);\r\n\r\n/*\r\nConverts a string that's a fraction of two floats into a single float value\r\nThrows a bad_lexical_cast error if string can't be read or converted.\r\nInput:\r\n  `frac` - must either be a floating-point literal, or two floating-point literals deliminated by a '/' character.\r\nOutput:\r\n  the calculated value as a floating-point variable.\r\n*/\r\ntemplate <class Real>\r\nReal Frac2Float(string frac) {\r\n  Real output;\r\n  size_t offset = frac.find(\"/\");\r\n  if (offset == string::npos) {\r\n    output = static_cast<Real>(lexical_cast<Real>(frac));\r\n    return output;\r\n  }\r\n  output = static_cast<Real>(lexical_cast<Real>(frac.substr(0, offset)));\r\n  output /= static_cast<Real>(lexical_cast<Real>(frac.substr(offset + 1)));\r\n  return output;\r\n}\r\n\r\n/*\r\nCreates RamanParams struct by reading values from text file.\r\nThe file can be opened or unopened, but must not be modified during this function call.\r\nInputs:\r\n  `in_file_name` - path to the file\r\nOutput:\r\n  A unique pointer to a new RamanParams struct with member values based on the parameters given in `in_file_name`.\r\nDependencies:\r\n  GetOption, Frac2Float\r\n*/\r\ntemplate <class Real>\r\nunique_ptr<RamanParams<Real>> LoadParams(string in_file_name) {\r\n  ifstream in_file;\r\n  in_file.open(in_file_name, ios::in);\r\n  if (!in_file.is_open())\r\n    throw runtime_error(\"Error: cannot open \" + in_file_name);\r\n\r\n  auto output = make_unique<RamanParams<Real>>();\r\n\r\n  string line;\r\n  // Lists all lines/options to check for. Options with floating-point values are listed first,\r\n  // then options with integral values are checked.\r\n  vector<string> options {\r\n    \"Minimum diameter:\", \"Maximum diameter:\", \"Particle phi:\", \"Minimum h:\", \"Maximum h:\",\r\n    \"epsilon1:\", \"epsilon2:\", \"Raman epsilon2:\", \"lambda:\", \"Raman lambda:\",\r\n    \"No. of particle radii:\", \"No. of particle thetas:\", \"No. of h ratios:\",\r\n    \"No. of r-coordinates:\", \"No. of theta-coordinates:\", \"No. of phi-coordinates:\",\r\n    \"Nb_theta:\", \"Nb_theta_pst:\", \"Delta:\"\r\n  };\r\n  std::array<Real, 10> float_params = {\r\n    output->dia_min, output->dia_max, output->phi_p, output->h_min, output->h_max,\r\n    output->epsilon1, output->epsilon2, output->epsilon2_rm, output->lambda, output->lambda_rm\r\n  };\r\n  std::array<int, 9> int_params = {\r\n    output->N_rad, output->N_theta_p, output->N_h, output->N_r, output->N_theta, output->N_phi,\r\n    output->Nb_theta, output->Nb_theta_pst, output->delta\r\n  };\r\n  for (size_t i = 0; i < options.size(); i++) {\r\n    string option = options[i];\r\n    string value = GetOption(in_file_name, option);\r\n\r\n    try {\r\n      if (i < float_params.size())\r\n        float_params[i] = Frac2Float<Real>(value);\r\n      else if (i < float_params.size() + int_params.size())\r\n        int_params[i - float_params.size()] = lexical_cast<int>(value);\r\n    } catch(bad_lexical_cast&) {\r\n      cerr << \"Cannot read value of option \\\"\" << option << \"\\\". Using default value.\";\r\n    }\r\n\r\n    output->dia_min = float_params[0];\r\n    output->dia_max = float_params[1];\r\n    output->phi_p = float_params[2];\r\n    output->h_min = float_params[3];\r\n    output->h_max = float_params[4];\r\n    output->epsilon1 = float_params[5];\r\n    output->epsilon2 = float_params[6];\r\n    output->epsilon2_rm = float_params[7];\r\n    output->lambda = float_params[8];\r\n    output->lambda_rm = float_params[9];\r\n    output->N_rad = int_params[0];\r\n    output->N_theta_p = int_params[1];\r\n    output->N_h = int_params[2];\r\n    output->N_r = int_params[3];\r\n    output->N_theta = int_params[4];\r\n    output->N_phi = int_params[5];\r\n    output->Nb_theta = int_params[6];\r\n    output->Nb_theta_pst = int_params[7];\r\n    output->delta = int_params[8];\r\n  }\r\n  ArrayXr<Real> dia_var = ArrayXr<Real>::LinSpaced(output->N_rad, output->dia_min, output->dia_max);\r\n  output->rad_var = dia_var/2;\r\n  output->theta_p_var = ArrayXr<Real>::LinSpaced(output->N_theta_p, 0, mp_pi<Real>()/2);\r\n  output->h_var = ArrayXr<Real>::LinSpaced(output->N_h, output->h_min, output->h_max);\r\n  return output;\r\n}\r\n\r\n/*\r\nTakes a RamanParams struct and uses it to generate an stParams struct for use with SMARTIES functions.\r\nstParams member values are based on RamanParams member values, and on the radius and h value\r\nat rad_ind and h_ind of rad_var and h_var respectively.\r\nInputs:\r\n  `raman_params` - unique pointer to a RamanParams struct\r\n  `rad_ind` - the index of the entry to use in `raman_params`->rad_var\r\n  `h_ind` - the index of the entry to use in `raman_params`->h_var\r\n  `type` - the type of values the output struct should have. If it's \"rm\",\r\n           then the values denote the parameters of the Raman T-matrix. Otherwise they denote the parameters\r\n           of the excitation T-matrix.\r\nOutput:\r\n  returns a unique pointer to a new stParams struct\r\nDependencies:\r\n  mp_pi\r\n*/\r\ntemplate <class Real>\r\nunique_ptr<stParams<Real>> Raman2SmartiesParams(\r\n    const unique_ptr<RamanParams<Real>>& raman_params, int rad_ind, int h_ind, string type = string()) {\r\n  auto params = make_unique<stParams<Real>>();\r\n  params->epsilon1 = raman_params->epsilon1;\r\n  params->lambda = ArrayXr<Real>(1);\r\n  params->epsilon2 = ArrayXr<Real>(1);\r\n  params->k1 = ArrayXr<Real>(1);\r\n  params->s = ArrayXr<Real>(1);\r\n  if (type == \"rm\") {\r\n    params->lambda(0) = raman_params->lambda_rm;\r\n    params->epsilon2(0) = raman_params->epsilon2_rm;\r\n    params->k1(0) = 2*mp_pi<Real>() / raman_params->lambda_rm * sqrt(raman_params->epsilon1);\r\n    params->s(0) = sqrt(raman_params->epsilon2_rm) / sqrt(raman_params->epsilon1);\r\n  } else {\r\n    params->lambda(0) = raman_params->lambda;\r\n    params->epsilon2(0) = raman_params->epsilon2;\r\n    params->k1(0) = 2*mp_pi<Real>() / raman_params->lambda * sqrt(raman_params->epsilon1);\r\n    params->s(0) = sqrt(raman_params->epsilon2) / sqrt(raman_params->epsilon1);\r\n  }\r\n  params->Nb_theta = raman_params->Nb_theta;\r\n  params->Nb_theta_pst = raman_params->Nb_theta_pst;\r\n\r\n  Real h = raman_params->h_var(h_ind);\r\n  Real radius = raman_params->rad_var(rad_ind);\r\n  if (h > 1) {\r\n    params->a = radius;\r\n    params->c = radius / h;\r\n  } else {\r\n    params->a = radius * h;\r\n    params->c = radius;\r\n  }\r\n  // The greater N is, the better the T-matrix converges.\r\n  params->N = 6 + 2*static_cast<int>(ceil(max(params->a, params->c)/40));\r\n  return params;\r\n}\r\n\r\n/*\r\nAppends a stamp with time and parameter details of Raman scattering calculations at the end of a text file.\r\nFunction opens the file itself. It does not check for any errors.\r\n`Real1` and `Real2` are the two selectable calculation types used for Raman scattering calculations.\r\nDEV NOTE: Can make this into a non-template function using c++20 'concepts' keyword\r\nInputs:\r\n  - out_file_name: text file to write stamp to\r\n  - raman_params: unique pointer to a RamanParams struct containing the parameters to be written\r\nDependencies:\r\n  - GetTypeName\r\n*/\r\ntemplate <class Real1, class Real2>\r\nvoid CreateTimeStamp(string out_file_name, const unique_ptr<RamanParams<Real1>>& raman_params) {\r\n  string main_calc_type = GetTypeName<Real1>();\r\n  string second_calc_type = GetTypeName<Real2>();\r\n\r\n  ofstream out_file(out_file_name, ios::out | ios::app);\r\n  auto sys_time = chrono::system_clock::now();\r\n  time_t sys_time_date = chrono::system_clock::to_time_t(sys_time);\r\n  out_file << \"Session began at system time: \" << ctime(&sys_time_date);\r\n  out_file << \"Running RamanElasticScattering with type \" << main_calc_type;\r\n  out_file << \" and \" << second_calc_type << endl;\r\n  out_file.flush();\r\n  out_file.close();\r\n}\r\n\r\n/*\r\nConverts an existing stTR struct containing entries of one type into a new stTR struct\r\nwith the same entries converted into another type. This could theoretically be\r\nimplemented as a template cast operator or template copy constructor.\r\n`From` is the entry type of the source struct and `To` is the entry type of the new struct.\r\nInputs:\r\n  - st_TR_list: the source stTR struct, with entries of type `From`\r\nOutputs:\r\n  - Returns a new stTR struct, with entries of type `To`.\r\nDependencies:\r\n  mp_im_unit\r\n*/\r\ntemplate <class From, class To>\r\nvector<unique_ptr<stTR<To>>> ConvertStTRList(const vector<unique_ptr<stTR<From>>>& st_TR_list) {\r\n  vector<unique_ptr<stTR<To>>> output(st_TR_list.size());\r\n  complex<To> I = mp_im_unit<To>();\r\n  for (size_t i = 0; i < st_TR_list.size(); i++) {\r\n    assert(st_TR_list[i]);\r\n    assert(st_TR_list[i]->mat_list.size() == 2);\r\n    assert(st_TR_list[i]->mat_list[0] == \"st_4M_T\");\r\n    assert(st_TR_list[i]->mat_list[1] == \"st_4M_R\");\r\n    output[i] = make_unique<stTR<To>>();\r\n    output[i]->mat_list = st_TR_list[i]->mat_list;\r\n\r\n    // Direct casting from a complex type to a complex type containing a Boost MPFR type isn't supported.\r\n    output[i]->st_4M_T_eo().M11 = st_TR_list[i]->st_4M_T_eo().M11.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_T_eo().M11.imag().template cast<To>();\r\n    output[i]->st_4M_T_eo().M12 = st_TR_list[i]->st_4M_T_eo().M12.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_T_eo().M12.imag().template cast<To>();\r\n    output[i]->st_4M_T_eo().M21 = st_TR_list[i]->st_4M_T_eo().M21.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_T_eo().M21.imag().template cast<To>();\r\n    output[i]->st_4M_T_eo().M22 = st_TR_list[i]->st_4M_T_eo().M22.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_T_eo().M22.imag().template cast<To>();\r\n    output[i]->st_4M_T_eo().m = st_TR_list[i]->st_4M_T_eo().m;\r\n    output[i]->st_4M_T_eo().ind1 = st_TR_list[i]->st_4M_T_eo().ind1;\r\n    output[i]->st_4M_T_eo().ind2 = st_TR_list[i]->st_4M_T_eo().ind2;\r\n\r\n    output[i]->st_4M_T_oe().M11 = st_TR_list[i]->st_4M_T_oe().M11.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_T_oe().M11.imag().template cast<To>();\r\n    output[i]->st_4M_T_oe().M12 = st_TR_list[i]->st_4M_T_oe().M12.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_T_oe().M12.imag().template cast<To>();\r\n    output[i]->st_4M_T_oe().M21 = st_TR_list[i]->st_4M_T_oe().M21.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_T_oe().M21.imag().template cast<To>();\r\n    output[i]->st_4M_T_oe().M22 = st_TR_list[i]->st_4M_T_oe().M22.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_T_oe().M22.imag().template cast<To>();\r\n    output[i]->st_4M_T_oe().m = st_TR_list[i]->st_4M_T_oe().m;\r\n    output[i]->st_4M_T_oe().ind1 = st_TR_list[i]->st_4M_T_oe().ind1;\r\n    output[i]->st_4M_T_oe().ind2 = st_TR_list[i]->st_4M_T_oe().ind2;\r\n\r\n    output[i]->st_4M_R_eo().M11 = st_TR_list[i]->st_4M_R_eo().M11.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_R_eo().M11.imag().template cast<To>();\r\n    output[i]->st_4M_R_eo().M12 = st_TR_list[i]->st_4M_R_eo().M12.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_R_eo().M12.imag().template cast<To>();\r\n    output[i]->st_4M_R_eo().M21 = st_TR_list[i]->st_4M_R_eo().M21.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_R_eo().M21.imag().template cast<To>();\r\n    output[i]->st_4M_R_eo().M22 = st_TR_list[i]->st_4M_R_eo().M22.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_R_eo().M22.imag().template cast<To>();\r\n    output[i]->st_4M_R_eo().m = st_TR_list[i]->st_4M_R_eo().m;\r\n    output[i]->st_4M_R_eo().ind1 = st_TR_list[i]->st_4M_R_eo().ind1;\r\n    output[i]->st_4M_R_eo().ind2 = st_TR_list[i]->st_4M_R_eo().ind2;\r\n\r\n    output[i]->st_4M_R_oe().M11 = st_TR_list[i]->st_4M_R_oe().M11.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_R_oe().M11.imag().template cast<To>();\r\n    output[i]->st_4M_R_oe().M12 = st_TR_list[i]->st_4M_R_oe().M12.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_R_oe().M12.imag().template cast<To>();\r\n    output[i]->st_4M_R_oe().M21 = st_TR_list[i]->st_4M_R_oe().M21.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_R_oe().M21.imag().template cast<To>();\r\n    output[i]->st_4M_R_oe().M22 = st_TR_list[i]->st_4M_R_oe().M22.real().template cast<To>() +\r\n        I * st_TR_list[i]->st_4M_R_oe().M22.imag().template cast<To>();\r\n    output[i]->st_4M_R_oe().m = st_TR_list[i]->st_4M_R_oe().m;\r\n    output[i]->st_4M_R_oe().ind1 = st_TR_list[i]->st_4M_R_oe().ind1;\r\n    output[i]->st_4M_R_oe().ind2 = st_TR_list[i]->st_4M_R_oe().ind2;\r\n  }\r\n  return output;\r\n}\r\n\r\n/*\r\nPerforms calculations of the Raman scattering of light off of spheroids with multiprocessing.\r\nIf calculations are done for multiple spheroid radii, the calculations for each radii may be\r\nallocated to the threads using dynamic scheduling.\r\nThe parameters are based on some input file, the T-matrices are calculated using floating-point type `Real1`,\r\nand the field calculations are calculated using floating-point type `Real2`.\r\nIt then prints a summary of results to the standard output (terminal) and in a set of files in a given directory.\r\nEach thread prints its own calculations to its own output file, so each output file is named\r\nbased on the parameters on the number of the thread.\r\nInputs:\r\n  - in_file_name: path to the file containing parameters for use in the Raman scattering calculations.\r\n                  Parameter details are given in the README file.\r\n  - out_dir: directory to write output files to. If empty, output files are written to.\r\nDependencies:\r\n  mp_pi, ArrayMap, TensorCast, TensorConj, LoadParams, CreateTimeStamp, MultiPrint,\r\n  Raman2SmartiesParams, ConvertStTRList, slvForT, pstScatteringMatrixOA, vshMakeIncidentParams,\r\n  rvhGetFieldCoefficients, pstMakeStructForField, vshEgenThetaAllPhi, vshEthetaForPhi\r\n*/\r\ntemplate <class Real1, class Real2>\r\nvoid RamanElasticScattering(string in_file_name, string out_dir = \"\", int cpus = 1) {\r\n  // Initialise all parameters and variables\r\n  Real2 PI = mp_pi<Real2>();\r\n\r\n  unique_ptr<RamanParams<Real1>> raman_params1 = LoadParams<Real1>(in_file_name);\r\n  unique_ptr<RamanParams<Real2>> raman_params2 = LoadParams<Real2>(in_file_name);\r\n  bool write_output = (out_dir != \"\");\r\n\r\n  Tensor3r<Real2> sigma_yz(raman_params2->N_rad, raman_params2->N_h, raman_params2->N_theta_p);\r\n  Tensor3r<Real2> sigma_zy(raman_params2->N_rad, raman_params2->N_h, raman_params2->N_theta_p);\r\n  Tensor3r<Real2> sigma_zz(raman_params2->N_rad, raman_params2->N_h, raman_params2->N_theta_p);\r\n  Tensor3r<Real2> sigma_yy(raman_params2->N_rad, raman_params2->N_h, raman_params2->N_theta_p);\r\n  ArrayXr<Real1> C_sca = ArrayXr<Real1>::Zero(raman_params1->N_rad);\r\n  ArrayXr<Real1> C_ext = ArrayXr<Real1>::Zero(raman_params1->N_rad);\r\n  ArrayXr<Real1> C_abs = ArrayXr<Real1>::Zero(raman_params1->N_rad);\r\n  vector<unique_ptr<stSM<Real2>>> stSM_list(raman_params2->N_rad);\r\n\r\n  auto options = make_unique<stOptions>();\r\n  options->get_R = true; // Needed for near fields and will be overridden in any case\r\n  options->delta = raman_params1->delta; // Use delta=-1 to estimate it automatically.\r\n  options->NB = 0; // NB will be estimated automatically\r\n  options->get_symmetric_T = false;\r\n  Real2 phi_p = raman_params2->phi_p;\r\n\r\n  int N_r = raman_params2->N_r;\r\n  int N_theta = raman_params2->N_theta;\r\n  int N_phi = raman_params2->N_phi;\r\n\r\n  // Initialises a set regularly spaced theta coordinates that are used for internal field calculations\r\n  RowArrayXr<Real2> theta_surf = RowArrayXr<Real2>::LinSpaced(N_theta, 0, PI);\r\n  // Initialises a non-uniform set of N_r radii inside a unit ball\r\n  // such that spherical shells between adjacent radii are equal volume\r\n  ArrayXr<Real2> r_surf_u = ArrayXr<Real2>::LinSpaced(\r\n      N_r, 1/static_cast<Real2>(N_r), 1).pow(static_cast<Real2>(1.0)/3);\r\n  ArrayXXr<Real2> r_mat_u = r_surf_u.replicate(1, N_theta);\r\n  ArrayXXr<Real2> theta_mat = theta_surf.replicate(N_r, 1);\r\n\r\n  // Initialise output files\r\n  if (write_output)\r\n    std::filesystem::create_directory(out_dir);\r\n\r\n  for (int h_ind = 0; h_ind < raman_params1->N_h; h_ind++) {\r\n    // Split the iterations of the next for-loop among threads for parallel processing.\r\n    #pragma omp parallel for num_threads(cpus) schedule(dynamic)\r\n    for (int k = 0; k < raman_params1->N_rad; k++) {\r\n      string out_file_name = out_dir + \"/a2c_\" + to_string(raman_params1->h_var(0)) +\r\n          \"_to_\" + to_string(raman_params1->h_var(last)) + \"_dia_\" + to_string(raman_params1->dia_min) +\r\n          \"_to_\" + to_string(raman_params1->dia_max) + \"_range_\" + to_string(omp_get_thread_num()) + \".txt\";\r\n      if (write_output) {\r\n        ofstream out_file(out_file_name, ios::out | ios::app);\r\n        out_file << endl;\r\n        if (!out_file.good()) {\r\n          cerr << \"Warning: cannot create or open output file. Some output won't be written.\" << endl;\r\n          out_file.close();\r\n          write_output = false;\r\n        }\r\n      }\r\n      if (write_output)\r\n        CreateTimeStamp<Real1, Real2>(out_file_name, raman_params1);\r\n      stringstream out_stream;\r\n\r\n      out_stream.precision(4);\r\n      out_stream << \"aspect ratio \" << raman_params1->h_var(h_ind) << endl;\r\n      MultiPrint(out_stream.str(), out_file_name, write_output);\r\n      out_stream.str(string());\r\n\r\n      unique_ptr<stParams<Real1>> params1 = Raman2SmartiesParams(raman_params1, k, h_ind);\r\n      unique_ptr<stParams<Real1>> params_rm1 = Raman2SmartiesParams(raman_params1, k, h_ind, \"rm\");\r\n      unique_ptr<stParams<Real2>> params2 = Raman2SmartiesParams(raman_params2, k, h_ind);\r\n      unique_ptr<stParams<Real2>> params_rm2 = Raman2SmartiesParams(raman_params2, k, h_ind, \"rm\");\r\n      Real2 a = params2->a;\r\n      Real2 c = params2->c;\r\n\r\n      int N = params2->N;\r\n      // Initialises array of radii coordinates that are used for internal field calculations\r\n      // by conforming r_mat_u to the spheroid shape. The ratios of radii along the same angle theta is kept invariant.\r\n      ArrayXXr<Real2> r_mat = a*c*r_mat_u/sqrt(pow(c, 2)*sin(theta_mat).pow(2) + pow(a, 2)*cos(theta_mat).pow(2));\r\n      ArrayXXr<Real2> d_theta = theta_mat(all, seq(1, last)) - theta_mat(all, seq(0, last - 1));\r\n      ArrayXXr<Real2> dr = r_mat(seq(1, last), all) - r_mat(seq(0, last - 1), all);\r\n      ArrayXXr<Real2> dt_dr = d_theta(seq(1, last), all) * dr(all, seq(1, last)); // Jacobian of the integral\r\n      RowArrayXr<Real2> r_row = r_mat.reshaped().transpose();\r\n      RowArrayXr<Real2> theta_row = theta_mat.reshaped().transpose();\r\n\r\n      chrono::steady_clock::time_point begin, end;\r\n      chrono::duration<double> elapsed_seconds;\r\n\r\n      // Calculating T-matrix for excitation\r\n      begin = chrono::steady_clock::now();\r\n      unique_ptr<stTmatrix<Real1>> T_mat = slvForT(params1, options);\r\n      end = chrono::steady_clock::now();\r\n      elapsed_seconds = end - begin;\r\n      out_stream << elapsed_seconds.count() << endl;\r\n      out_stream << \"T-matrix calculatred for excitation\" << endl;\r\n      MultiPrint(out_stream.str(), out_file_name, write_output);\r\n      out_stream.str(string());\r\n\r\n      // Calculating T-matrix for Raman\r\n      begin = chrono::steady_clock::now();\r\n      unique_ptr<stTmatrix<Real1>> T_mat_rm = slvForT(params_rm1, options);\r\n      end = chrono::steady_clock::now();\r\n      elapsed_seconds = end - begin;\r\n      out_stream << elapsed_seconds.count() << endl;\r\n      out_stream << \"T-matrix calculatred for Raman\" << endl;\r\n      MultiPrint(out_stream.str(), out_file_name, write_output);\r\n      out_stream.str(string());\r\n\r\n      // Converting variables to secondary calculation type\r\n      vector<unique_ptr<stTR<Real2>>> st_TR_list = ConvertStTRList<Real1, Real2>(T_mat->st_TR_list);\r\n      vector<unique_ptr<stTR<Real2>>> st_TR_list_rm = ConvertStTRList<Real1, Real2>(T_mat_rm->st_TR_list);\r\n\r\n      C_sca(k) = T_mat->st_C_oa->C_sca(0); // st_C_oa->sca should only contain 1 element\r\n      C_ext(k) = T_mat->st_C_oa->C_ext(0); // st_C_oa->ext should only contain 1 element\r\n      C_abs(k) = T_mat->st_C_oa->C_abs(0); // st_C_oa->abs should only contain 1 element\r\n      out_stream.precision(10);\r\n      out_stream << \"C_sca \" << C_sca(k) << endl;\r\n      out_stream << \"C_ext \" << C_ext(k) << endl;\r\n      out_stream << \"C_abs \" << C_abs(k) << endl;\r\n      MultiPrint(out_stream.str(), out_file_name, write_output);\r\n      out_stream.str(string());\r\n\r\n      // Calculating scattering matrix for 2 scattering angles 0 and pi\r\n      stSM_list[k] = pstScatteringMatrixOA(st_TR_list, params2->lambda(0), static_cast<Real2>(C_sca(k)));\r\n\r\n      for (int t = 0; t < raman_params2->N_theta_p; t++) {\r\n        begin = chrono::steady_clock::now();\r\n        Real2 theta_p = raman_params2->theta_p_var(t);\r\n        std::array<long int, 3> new_dims = {N_r, N_theta, 3};\r\n        ArrayXr<Real2> phi_var = ArrayXr<Real2>::LinSpaced(N_phi + 1, 0, 2*PI);\r\n\r\n        // Calculate field at excitation wavelength\r\n        Real2 alpha_p = 0; // Defines the orientation of the electric field, in the plane orthogonal to wavevector k.\r\n        params2->inc_par = vshMakeIncidentParams(sIncType::GENERAL, N, theta_p, phi_p, alpha_p);\r\n        // Internal field calculations for the incident field defined by stIncPar\r\n        unique_ptr<stAbcdnm<Real2>> st_abcdnm = rvhGetFieldCoefficients(N, st_TR_list, params2->inc_par);\r\n        unique_ptr<stRes<Real2>> st_res_E = pstMakeStructForField(st_abcdnm, params2);\r\n        ArrayXXc<Real2> c_nm = Map<RowArrayXc<Real2>>(st_res_E->c_nm.transpose().data(), st_res_E->c_nm.size());\r\n        ArrayXXc<Real2> d_nm = Map<RowArrayXc<Real2>>(st_res_E->d_nm.transpose().data(), st_res_E->d_nm.size());\r\n        unique_ptr<stEAllPhi<Real2>> st_E_surf = vshEgenThetaAllPhi(st_res_E->lambda, st_res_E->epsilon2,\r\n            c_nm, d_nm, r_row, theta_row, sBessel::J);\r\n        // The field is calculated for a set of phi, from 0 and 2*pi\r\n        Tensor4c<Real2> E_field_z(N_r, N_theta, N_phi + 1, 3);\r\n        E_field_z.setZero();\r\n        for (int m = 0; m <= N_phi; m++) {\r\n          Real2 phi = phi_var(m);\r\n          unique_ptr<stEforPhi<Real2>> st_E_for_phi = vshEthetaForPhi(st_E_surf, phi);\r\n          long int dims[2] = {st_E_for_phi->E_r.cols(), 3*st_E_for_phi->E_r.rows()};\r\n          ArrayXXc<Real2> E_field_phi(dims[0], dims[1]);\r\n          E_field_phi << st_E_for_phi->E_r.matrix().adjoint(),\r\n              st_E_for_phi->E_t.matrix().adjoint(), st_E_for_phi->E_f.matrix().adjoint();\r\n          E_field_z.chip(m, 2) = TensorCast(E_field_phi).reshape(new_dims);\r\n        }\r\n\r\n        alpha_p = PI/2; // Internal field calculations for different polarisation alpha_p\r\n        params2->inc_par = vshMakeIncidentParams(sIncType::GENERAL, N, theta_p, phi_p, alpha_p);\r\n        st_abcdnm = rvhGetFieldCoefficients(N, st_TR_list, params2->inc_par);\r\n        st_res_E = pstMakeStructForField(st_abcdnm, params2);\r\n        c_nm = Map<RowArrayXc<Real2>>(st_res_E->c_nm.transpose().data(), st_res_E->c_nm.size());\r\n        d_nm = Map<RowArrayXc<Real2>>(st_res_E->d_nm.transpose().data(), st_res_E->d_nm.size());\r\n        st_E_surf = vshEgenThetaAllPhi(st_res_E->lambda, st_res_E->epsilon2,\r\n            c_nm, d_nm, r_row, theta_row, sBessel::J);\r\n        // The field is calculated for a set of phi, from 0 and 2*pi\r\n        Tensor4c<Real2> E_field_y(N_r, N_theta, N_phi + 1, 3);\r\n        E_field_y.setZero();\r\n        for (int m = 0; m <= N_phi; m++) {\r\n          Real2 phi = phi_var(m);\r\n          unique_ptr<stEforPhi<Real2>> st_E_for_phi = vshEthetaForPhi(st_E_surf, phi);\r\n          long int dims[2] = {st_E_for_phi->E_r.cols(), 3*st_E_for_phi->E_r.rows()};\r\n          ArrayXXc<Real2> E_field_phi(dims[0], dims[1]);\r\n          E_field_phi << st_E_for_phi->E_r.matrix().adjoint(),\r\n              st_E_for_phi->E_t.matrix().adjoint(), st_E_for_phi->E_f.matrix().adjoint();\r\n          E_field_y.chip(m, 2) = TensorCast(E_field_phi).reshape(new_dims);\r\n        }\r\n\r\n        // Calculate field at Raman wavelength\r\n        alpha_p = 0;\r\n        params_rm2->inc_par = vshMakeIncidentParams(sIncType::GENERAL, N, theta_p, phi_p, alpha_p);\r\n        st_abcdnm = rvhGetFieldCoefficients(N, st_TR_list_rm, params_rm2->inc_par);\r\n        st_res_E = pstMakeStructForField(st_abcdnm, params_rm2);\r\n        c_nm = Map<RowArrayXc<Real2>>(st_res_E->c_nm.transpose().data(), st_res_E->c_nm.size());\r\n        d_nm = Map<RowArrayXc<Real2>>(st_res_E->d_nm.transpose().data(), st_res_E->d_nm.size());\r\n        st_E_surf = vshEgenThetaAllPhi(st_res_E->lambda, st_res_E->epsilon2,\r\n            c_nm, d_nm, r_row, theta_row, sBessel::J);\r\n        // The field is calculated for a set of phi, from 0 and 2*pi\r\n        Tensor4c<Real2> E_field_rm_z(N_r, N_theta, N_phi + 1, 3);\r\n        E_field_rm_z.setZero();\r\n        for (int m = 0; m <= N_phi; m++) {\r\n          Real2 phi = phi_var(m);\r\n          unique_ptr<stEforPhi<Real2>> st_E_for_phi = vshEthetaForPhi(st_E_surf, phi);\r\n          long int dims[2] = {st_E_for_phi->E_r.cols(), 3*st_E_for_phi->E_r.rows()};\r\n          ArrayXXc<Real2> E_field_phi(dims[0], dims[1]);\r\n          E_field_phi << st_E_for_phi->E_r.matrix().adjoint(),\r\n              st_E_for_phi->E_t.matrix().adjoint(), st_E_for_phi->E_f.matrix().adjoint();\r\n          E_field_rm_z.chip(m, 2) = TensorCast(E_field_phi).reshape(new_dims);\r\n        }\r\n\r\n        alpha_p = PI/2;\r\n        params_rm2->inc_par = vshMakeIncidentParams(sIncType::GENERAL, N, theta_p, phi_p, alpha_p);\r\n        st_abcdnm = rvhGetFieldCoefficients(N, st_TR_list_rm, params_rm2->inc_par);\r\n        st_res_E = pstMakeStructForField(st_abcdnm, params_rm2);\r\n        c_nm = Map<RowArrayXc<Real2>>(st_res_E->c_nm.transpose().data(), st_res_E->c_nm.size());\r\n        d_nm = Map<RowArrayXc<Real2>>(st_res_E->d_nm.transpose().data(), st_res_E->d_nm.size());\r\n        st_E_surf = vshEgenThetaAllPhi(st_res_E->lambda, st_res_E->epsilon2,\r\n            c_nm, d_nm, r_row, theta_row, sBessel::J);\r\n        // The field is calculated for a set of phi, from 0 and 2*pi\r\n        Tensor4c<Real2> E_field_rm_y(N_r, N_theta, N_phi + 1, 3);\r\n        E_field_rm_y.setZero();\r\n        for (int m = 0; m <= N_phi; m++) {\r\n          Real2 phi = phi_var(m);\r\n          unique_ptr<stEforPhi<Real2>> st_E_for_phi = vshEthetaForPhi(st_E_surf, phi);\r\n          long int dims[2] = {st_E_for_phi->E_r.cols(), 3*st_E_for_phi->E_r.rows()};\r\n          ArrayXXc<Real2> E_field_phi(dims[0], dims[1]);\r\n          E_field_phi << st_E_for_phi->E_r.matrix().adjoint(),\r\n              st_E_for_phi->E_t.matrix().adjoint(), st_E_for_phi->E_f.matrix().adjoint();\r\n          E_field_rm_y.chip(m, 2) = TensorCast(E_field_phi).reshape(new_dims);\r\n        }\r\n\r\n        // Calculate scattering cross-sections\r\n        std::array<int, 1> dim3 = {3}, dim2 = {2};\r\n        Tensor<Real2, 2> M_tens = 2*PI/N_phi*(E_field_rm_z * TensorConj(E_field_z))\r\n            .sum(dim3).abs().pow(static_cast<Real2>(2.0)).sum(dim2);\r\n        Map<ArrayXXr<Real2>> M_mat = ArrayMap(M_tens);\r\n        ArrayXXr<Real2> F = M_mat * r_mat.pow(2) * sin(theta_mat);\r\n        ArrayXXr<Real2> intergrand = (F(seq(1, last), seq(1, last)) + F(seq(0, last - 1), seq(1, last)) +\r\n            F(seq(1, last), seq(0, last - 1)) + F(seq(0, last - 1), seq(0, last - 1))) / 4 * dt_dr;\r\n        sigma_zz(k, h_ind, t) = (intergrand).sum()/(PI*a*a*c*4/3);\r\n\r\n        M_tens = 2*PI/N_phi*(E_field_rm_y * TensorConj(E_field_z))\r\n            .sum(dim3).abs().pow(static_cast<Real2>(2.0)).sum(dim2);\r\n        M_mat = ArrayMap(M_tens);\r\n        F = M_mat * r_mat.pow(2) * sin(theta_mat);\r\n        intergrand = (F(seq(1, last), seq(1, last)) + F(seq(0, last - 1), seq(1, last)) +\r\n            F(seq(1, last), seq(0, last - 1)) + F(seq(0, last - 1), seq(0, last - 1))) / 4 * dt_dr;\r\n        sigma_yz(k, h_ind, t) = (intergrand).sum()/(PI*a*a*c*4/3);\r\n\r\n        M_tens = 2*PI/N_phi*(E_field_rm_y * TensorConj(E_field_y))\r\n            .sum(dim3).abs().pow(static_cast<Real2>(2.0)).sum(dim2);\r\n        M_mat = ArrayMap(M_tens);\r\n        F = M_mat * r_mat.pow(2) * sin(theta_mat);\r\n        intergrand = (F(seq(1, last), seq(1, last)) + F(seq(0, last - 1), seq(1, last)) +\r\n            F(seq(1, last), seq(0, last - 1)) + F(seq(0, last - 1), seq(0, last - 1))) / 4 * dt_dr;\r\n        sigma_yy(k, h_ind, t) = (intergrand).sum()/(PI*a*a*c*4/3);\r\n\r\n        M_tens = 2*PI/N_phi*(E_field_rm_z * TensorConj(E_field_y))\r\n            .sum(dim3).abs().pow(static_cast<Real2>(2.0)).sum(dim2);\r\n        M_mat = ArrayMap(M_tens);\r\n        F = M_mat * r_mat.pow(2) * sin(theta_mat);\r\n        intergrand = (F(seq(1, last), seq(1, last)) + F(seq(0, last - 1), seq(1, last)) +\r\n            F(seq(1, last), seq(0, last - 1)) + F(seq(0, last - 1), seq(0, last - 1))) / 4 * dt_dr;\r\n        sigma_zy(k, h_ind, t) = (intergrand).sum()/(PI*a*a*c*4/3);\r\n\r\n        out_stream.precision(5);\r\n        out_stream << \"max diameter = \" << max(a, c)*2e-3;\r\n        out_stream.precision(10);\r\n        out_stream << \" µm, theta = \" << theta_p * 180/PI << \" degrees\" << endl;\r\n        out_stream.precision(11);\r\n        out_stream << \"--- relative raman zz = \" << sigma_zz(k, h_ind, t) << endl;\r\n        out_stream << \"--- relative raman yz = \" << sigma_yz(k, h_ind, t) << endl;\r\n        out_stream << \"--- relative raman zy = \" << sigma_zy(k, h_ind, t) << endl;\r\n        out_stream << \"--- relative raman yy = \" << sigma_yy(k, h_ind, t) << endl;\r\n\r\n        end = chrono::steady_clock::now();\r\n        elapsed_seconds = end - begin;\r\n        out_stream << elapsed_seconds.count() << endl;\r\n\r\n        MultiPrint(out_stream.str(), out_file_name, write_output);\r\n        out_stream.str(string());\r\n      }\r\n    }\r\n  }\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "ebcb02b9f48ea740367b50ee9289d7d1d8cc655d", "size": 33991, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/raman_elastic_scattering.hpp", "max_stars_repo_name": "Kirbologist/Raman-Scattering-Code-Conversion", "max_stars_repo_head_hexsha": "118a08238a2525f595c4b7d2b735dd37852fac6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-09T12:41:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T12:41:22.000Z", "max_issues_repo_path": "src/raman_elastic_scattering.hpp", "max_issues_repo_name": "Kirbologist/Raman-Scattering-Code-Conversion", "max_issues_repo_head_hexsha": "118a08238a2525f595c4b7d2b735dd37852fac6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/raman_elastic_scattering.hpp", "max_forks_repo_name": "Kirbologist/Raman-Scattering-Code-Conversion", "max_forks_repo_head_hexsha": "118a08238a2525f595c4b7d2b735dd37852fac6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4774381368, "max_line_length": 120, "alphanum_fraction": 0.6658527257, "num_tokens": 9951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4485252253981146}}
{"text": "#include <vector>\n#include <boost/math/tools/polynomial.hpp>\n#include <fstream>\n#include <immintrin.h>\n#include <map>\n#include \"cpp-btree/btree_map.h\"\n//---------------------------------------------------------------------------\ntypedef std::pair<double,double> Coord;\ntypedef std::pair<double, unsigned> segCoord;\ntypedef btree::btree_map<double, double> btree_map;\ntypedef btree::btree_map<double, unsigned> btree_map_segments;\n//---------------------------------------------------------------------------\nclass SplineEvaluation;\n//---------------------------------------------------------------------------\n/// A linear spline for evaluation\nclass SplineEvaluation \n{\n    private:\n    static const unsigned countOfBuckets = 2 + 1;\n    static const unsigned limitSplineSize = 100000;\n    int32_t offset;\n    int32_t length;\n    \n    void transformSpline();\n    double selfInterpolate(unsigned segment, double& x) const;\n    unsigned searchLeft(int segment, double& x) const;\n    unsigned searchRight(int segment, double& x) const;\n    unsigned binarySearch(unsigned lower, unsigned upper, double& x) const;\n    void changeIntoArray(long double** moveHere, boost::math::tools::polynomial<long double> poly);\n    void convertValues();\n    void splitSegmentSpline();\n    public:\n    static const unsigned polyGrade = 2;\n    /// Constructor\n    SplineEvaluation();\n    /// Deconstructor\n    ~SplineEvaluation();\n    /// Constructor with the function\n    SplineEvaluation(const std::vector<Coord>& function, unsigned desiredSize, const unsigned useSplineMode, const unsigned searchMode, const unsigned testMode);\n    /// Constructor with given data\n    SplineEvaluation(unsigned size, const double* x, const double* y);\n\n    void save(std::ofstream& file_out);\n    void load(std::ifstream& file_in);\n    \n    unsigned size() const;\n    unsigned findExactSegment(double segment, double& x) const;\n    /// Return the approximate value of function(x)\n    double evaluate(double& x) const;\n    double hornerEvaluate(double& x) const;\n    \n    double splittedHornerEvaluate(double& x) const;\n    double hornerEvaluateByBuckets(unsigned bucketIndex, double& x) const; \n\n    double chebyshevEvaluate(double& x) const;\n    double splittedChebyshevEvaluate(double& x) const;\n    \n    double mapEvaluate(double& x) const;\n    std::map<double, double> coordinates;\n    \n    double btreeEvaluate(double& x) const;\n    btree_map* btreeMap;\n    \n    double btreeSegmentsEvaluate(double& x) const;\n    btree_map_segments* btreeSegments;\n    \n    std::vector<Coord> spline;\n    /// Spline which has to be fitted\n    std::vector<segCoord> segmentSpline;\n    /// Fitted polynomial to the spline\n    long double* poly;\n    double* values;\n    unsigned splineSize;\n    \n    std::vector<segCoord>* splineBuckets;\n    long double **polyBuckets;\n    double splittedPositions[countOfBuckets];\n    __m128d saveLimits;\n    \n    /// Fit a polynomial to spline\n    boost::math::tools::polynomial<long double> fitSpline(const std::vector<segCoord>& spline);\n};\n//---------------------------------------------------------------------------\n\n", "meta": {"hexsha": "a6c1d7aba9f9becb73e9b4a50d96f3fee7a3ec5f", "size": 3108, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SplineEvaluation.hpp", "max_stars_repo_name": "stoianmihail/Planet", "max_stars_repo_head_hexsha": "c1869fbab7a57ca635830ea478d85070763aba9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-13T11:39:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-11T19:45:00.000Z", "max_issues_repo_path": "SplineEvaluation.hpp", "max_issues_repo_name": "Alexie81/Planet", "max_issues_repo_head_hexsha": "c1869fbab7a57ca635830ea478d85070763aba9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SplineEvaluation.hpp", "max_forks_repo_name": "Alexie81/Planet", "max_forks_repo_head_hexsha": "c1869fbab7a57ca635830ea478d85070763aba9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-13T11:39:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-13T11:39:46.000Z", "avg_line_length": 36.5647058824, "max_line_length": 161, "alphanum_fraction": 0.6454311454, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4485252253981146}}
{"text": "/*\n * convnn.cpp\n *\n */\n#include <string>\n\n#include <boost/assert.hpp>\n\n#include \"core/utils.h\"\n#include \"core/functions.h\"\n#include \"layers/contlayer.h\"\n#include \"layers/convlayer.h\"\n#include \"layers/fclayer.h\"\n#include \"layers/polllayer.h\"\n#include \"layers/smaxlayer.h\"\n\n#include \"cnn.h\"\n\nusing namespace std;\nusing namespace yann;\n\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// ConvolutionalNetwork implementation\n//\nyann::ConvolutionalNetwork::ConvPollParams::ConvPollParams() :\n    _output_frames_num(0),\n    _conv_filter_size(0),\n    _polling_mode(PollingLayer::PollMode_Avg),\n    _polling_filter_size(0)\n{\n}\n\nvoid yann::ConvolutionalNetwork::append(unique_ptr<SequentialLayer> & container,\n                   const MatrixSize & input_rows,\n                   const MatrixSize & input_cols,\n                   const MatrixSize & input_frames_num,\n                   const ConvPollParams & params)\n{\n  YANN_CHECK(container);\n  YANN_CHECK_GT(input_rows, 0);\n  YANN_CHECK_GT(input_cols, 0);\n  YANN_CHECK_GT(input_frames_num, 0);\n  YANN_CHECK(input_frames_num == 1 || !params._mappings.empty());\n  YANN_CHECK_GT(params._output_frames_num, 0 || !params._mappings.empty());\n  YANN_CHECK_GT(params._conv_filter_size, 0);\n  YANN_CHECK_GT(params._polling_filter_size, 0);\n\n  // ConvolutionalLayer\n  if(input_frames_num == 1) {\n    auto conv_bcast_layer = ConvolutionalLayer::create_conv_bcast_layer(\n        params._output_frames_num,   // N output frames\n        input_rows,\n        input_cols,\n        params._conv_filter_size,\n        params._conv_activation_funtion\n    );\n    YANN_CHECK(conv_bcast_layer);\n    container->append_layer(std::move(conv_bcast_layer));\n  } else {\n    YANN_CHECK(!params._mappings.empty());\n    YANN_CHECK(params._output_frames_num == 0 || params._output_frames_num == params._mappings.size());\n\n    auto conv_mapping_layer = make_unique<MappingLayer>(input_frames_num);\n    YANN_CHECK(conv_mapping_layer);\n    for(auto & layer_mappings : params._mappings) {\n      auto conv_layer = make_unique<ConvolutionalLayer>(\n          input_rows,\n          input_cols,\n          params._conv_filter_size);\n      YANN_CHECK(conv_layer);\n\n      if(params._conv_activation_funtion) {\n        conv_layer->set_activation_function(params._conv_activation_funtion);\n      }\n      conv_mapping_layer->append_layer(std::move(conv_layer), layer_mappings);\n    }\n    container->append_layer(std::move(conv_mapping_layer));\n  }\n\n  // PollingLayer\n  MatrixSize poll_input_rows = ConvolutionalLayer::get_conv_output_rows(input_rows, params._conv_filter_size);\n  MatrixSize poll_input_cols = ConvolutionalLayer::get_conv_output_cols(input_cols, params._conv_filter_size);\n  auto poll_layer = PollingLayer::create_poll_parallel_layer(\n     params._output_frames_num,\n     poll_input_rows,\n     poll_input_cols,\n     params._polling_filter_size,\n     params._polling_mode,\n     params._polling_activation_funtion);\n  YANN_CHECK(poll_layer);\n  container->append_layer(std::move(poll_layer));\n}\n\nunique_ptr<SequentialLayer> yann::ConvolutionalNetwork::create(\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    const ConvPollParams & params,\n    const std::unique_ptr<ActivationFunction> & fc_activation_funtion,\n    const MatrixSize & output_size)\n{\n  YANN_CHECK_GT(output_size, 0);\n\n  auto container = make_unique<SequentialLayer>();\n  YANN_CHECK(container);\n\n  // append one layer: we have 1 input frame\n  append(container, input_rows, input_cols, 1, params);\n\n  // FullyConnectedLayer\n  auto fc_layer = make_unique<FullyConnectedLayer>(\n      container->get_output_size(),\n      output_size);\n  YANN_CHECK(fc_layer);\n  if(fc_activation_funtion) {\n    fc_layer->set_activation_function(fc_activation_funtion);\n  }\n  container->append_layer(std::move(fc_layer));\n\n  // done\n  return container;\n}\n\nstd::unique_ptr<SequentialLayer> yann::ConvolutionalNetwork::create(\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    const ConvPollParams & params1,\n    const ConvPollParams & params2,\n    const std::unique_ptr<ActivationFunction> & fc_activation_funtion,\n    const MatrixSize & output_size)\n{\n  YANN_CHECK_GT(output_size, 0);\n\n  auto container = make_unique<SequentialLayer>();\n  YANN_CHECK(container);\n\n  // append one layer: we have 1 input frame\n  append(container, input_rows, input_cols, 1, params1);\n\n  // append second layer: the output frames from first layer are our inputs\n  MatrixSize poll1_input_rows = ConvolutionalLayer::get_conv_output_rows(input_rows, params1._conv_filter_size);\n  MatrixSize poll1_input_cols = ConvolutionalLayer::get_conv_output_cols(input_cols, params1._conv_filter_size);\n  MatrixSize conv2_input_rows = PollingLayer::get_output_rows(poll1_input_rows, params1._polling_filter_size);\n  MatrixSize conv2_input_cols = PollingLayer::get_output_cols(poll1_input_cols, params1._polling_filter_size);\n  append(container, conv2_input_rows, conv2_input_cols, params1._output_frames_num, params2);\n\n  // FullyConnectedLayer\n  auto fc_layer = make_unique<FullyConnectedLayer>(\n      container->get_output_size(),\n      output_size);\n  YANN_CHECK(fc_layer);\n  if(fc_activation_funtion) {\n    fc_layer->set_activation_function(fc_activation_funtion);\n  }\n  container->append_layer(std::move(fc_layer));\n\n  // done\n  return container;\n}\n\nstd::unique_ptr<SequentialLayer> yann::ConvolutionalNetwork::create_lenet1(\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    PollingLayer::Mode polling_mode,\n    const MatrixSize & fc_size,\n    const MatrixSize & output_size,\n    const std::unique_ptr<ActivationFunction> & conv_activation_funtion,\n    const std::unique_ptr<ActivationFunction> & poll_activation_funtion,\n    const std::unique_ptr<ActivationFunction> & fc_activation_funtion)\n{\n  // see http://yann.lecun.com/exdb/publis/pdf/lecun-90c.pdf\n  ConvPollParams params1;\n  params1._output_frames_num = 4;\n  params1._conv_filter_size  = 5;\n  if(conv_activation_funtion) {\n    params1._conv_activation_funtion = conv_activation_funtion->copy();\n  }\n  params1._polling_mode = polling_mode;\n  params1._polling_filter_size = 2;\n  if(poll_activation_funtion) {\n    params1._polling_activation_funtion = poll_activation_funtion->copy();\n  }\n\n  ConvPollParams params2;\n  params2._output_frames_num = 12;\n  params2._conv_filter_size  = 5;\n  if(conv_activation_funtion) {\n    params2._conv_activation_funtion = conv_activation_funtion->copy();\n  }\n  params2._polling_mode = polling_mode;\n  params2._polling_filter_size = 2;\n  if(poll_activation_funtion) {\n    params2._polling_activation_funtion = poll_activation_funtion->copy();\n  }\n  params2._mappings.push_back({ 0 });\n  params2._mappings.push_back({ 0, 1 });\n  params2._mappings.push_back({ 0, 1 });\n  params2._mappings.push_back({ 1 });\n  params2._mappings.push_back({ 0, 1 });\n  params2._mappings.push_back({ 0, 1 });\n  params2._mappings.push_back({ 2 });\n  params2._mappings.push_back({ 2, 3 });\n  params2._mappings.push_back({ 2, 3 });\n  params2._mappings.push_back({ 3 });\n  params2._mappings.push_back({ 2, 3 });\n  params2._mappings.push_back({ 2, 3 });\n\n  auto container = create(\n      input_rows, input_cols, params1, params2,\n      fc_activation_funtion, fc_size > 0 ? fc_size : output_size);\n  YANN_CHECK(container);\n\n  // add one more FC layer if needed\n  if(fc_size > 0) {\n    auto fc_layer = make_unique<FullyConnectedLayer>(fc_size, output_size);\n    YANN_CHECK(fc_layer);\n    if(fc_activation_funtion) {\n      fc_layer->set_activation_function(fc_activation_funtion);\n    }\n    container->append_layer(std::move(fc_layer));\n  }\n\n  // done\n  return container;\n}\n\nstd::unique_ptr<SequentialLayer> yann::ConvolutionalNetwork::create_boosted_lenet1(\n    const MatrixSize & paths_num,\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    PollingLayer::Mode polling_mode,\n    const MatrixSize & fc_size,\n    const MatrixSize & output_size,\n    const std::unique_ptr<ActivationFunction> & conv_activation_funtion,\n    const std::unique_ptr<ActivationFunction> & poll_activation_funtion,\n    const std::unique_ptr<ActivationFunction> & fc_activation_funtion)\n{\n  // create N paths\n  auto bcast_layer = make_unique<BroadcastLayer>();\n  YANN_CHECK(bcast_layer);\n  for(auto ii = paths_num; ii > 0; --ii) {\n    auto path = create_lenet1(\n        input_rows, input_cols, polling_mode,\n        0, fc_size, // don't create fc layer, we will add one for the merge\n        conv_activation_funtion, poll_activation_funtion,\n        fc_activation_funtion);\n    YANN_CHECK(path);\n    bcast_layer->append_layer(std::move(path));\n  }\n\n  // merge them together\n  auto fc_layer = make_unique<FullyConnectedLayer>(paths_num * fc_size, output_size);\n  YANN_CHECK(fc_layer);\n  fc_layer->set_activation_function(fc_activation_funtion);\n\n  // and finally create container\n  auto container = make_unique<SequentialLayer>();\n  YANN_CHECK(container);\n  container->append_layer(std::move(bcast_layer));\n  container->append_layer(std::move(fc_layer));\n\n  // done\n  return container;\n}\n\nstd::unique_ptr<SequentialLayer> yann::ConvolutionalNetwork::create_lenet5(\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    PollingLayer::Mode polling_mode,\n    const MatrixSize & fc1_size,\n    const MatrixSize & fc2_size,\n    const MatrixSize & output_size,\n    const std::unique_ptr<ActivationFunction> & conv_activation_funtion,\n    const std::unique_ptr<ActivationFunction> & poll_activation_funtion,\n    const std::unique_ptr<ActivationFunction> & fc_activation_funtion)\n{\n  // see http://vision.stanford.edu/cs598_spring07/papers/Lecun98.pdf\n  ConvPollParams params1;\n  params1._output_frames_num = 6;\n  params1._conv_filter_size  = 5;\n  if(conv_activation_funtion) {\n    params1._conv_activation_funtion = conv_activation_funtion->copy();\n  }\n  params1._polling_mode = polling_mode;\n  params1._polling_filter_size = 2;\n  if(poll_activation_funtion) {\n    params1._polling_activation_funtion = poll_activation_funtion->copy();\n  }\n\n  ConvPollParams params2;\n  params2._output_frames_num = 16;\n  params2._conv_filter_size  = 5;\n  if(conv_activation_funtion) {\n    params2._conv_activation_funtion = conv_activation_funtion->copy();\n  }\n  params2._polling_mode = polling_mode;\n  params2._polling_filter_size = 2;\n  if(poll_activation_funtion) {\n    params2._polling_activation_funtion = poll_activation_funtion->copy();\n  }\n  params2._mappings.push_back({ 0, 1, 2 }); // 0\n  params2._mappings.push_back({ 1, 2, 3 });\n  params2._mappings.push_back({ 2, 3, 4 });\n  params2._mappings.push_back({ 3, 4, 5 });\n  params2._mappings.push_back({ 0, 4, 5 }); // 4\n  params2._mappings.push_back({ 0, 1, 5 });\n  params2._mappings.push_back({ 0, 1, 2, 3 });\n  params2._mappings.push_back({ 1, 2, 3, 4 });\n  params2._mappings.push_back({ 2, 3, 4, 5 }); // 8\n  params2._mappings.push_back({ 0, 3, 4, 5 });\n  params2._mappings.push_back({ 0, 1, 4, 5 });\n  params2._mappings.push_back({ 0, 1, 2, 5 });\n  params2._mappings.push_back({ 0, 1, 3, 4 }); // 12\n  params2._mappings.push_back({ 1, 2, 4, 5 });\n  params2._mappings.push_back({ 0, 2, 3, 5 });\n  params2._mappings.push_back({ 0, 1, 2, 3, 4, 5 });\n\n  auto container = create(input_rows, input_cols, params1, params2, fc_activation_funtion, fc1_size);\n  YANN_CHECK(container);\n\n  // add one more FC layer\n  auto fc_layer1 = make_unique<FullyConnectedLayer>(fc1_size, fc2_size);\n  YANN_CHECK(fc_layer1);\n  if(fc_activation_funtion) {\n    fc_layer1->set_activation_function(fc_activation_funtion);\n  }\n  container->append_layer(std::move(fc_layer1));\n\n  // and one more FC layer\n  auto fc_layer2 = make_unique<FullyConnectedLayer>(fc2_size, output_size);\n  YANN_CHECK(fc_layer2);\n  if(fc_activation_funtion) {\n    fc_layer2->set_activation_function(fc_activation_funtion);\n  }\n  container->append_layer(std::move(fc_layer2));\n\n  // done\n  return container;\n}\n\n\n", "meta": {"hexsha": "c31be6bc1675f86feffcc59de0a2d07c1dbcf281", "size": 11914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/networks/cnn.cpp", "max_stars_repo_name": "lsh123/yann", "max_stars_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:14:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T10:25:07.000Z", "max_issues_repo_path": "src/networks/cnn.cpp", "max_issues_repo_name": "lsh123/yann", "max_issues_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/networks/cnn.cpp", "max_forks_repo_name": "lsh123/yann", "max_forks_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7346938776, "max_line_length": 112, "alphanum_fraction": 0.7313244922, "num_tokens": 3201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4483593012738318}}
{"text": "﻿#include \"stdafx.h\"\n#include \"NRSolver.h\"\n#include \"PrimitiveNetwork.h\"\n#include \"Exceptions.h\"\n#include <Eigen/Sparse>\n#include <Eigen/SparseLU>\n\nusing Eigen::Triplet;\nusing Eigen::SparseLU;\nusing Eigen::SparseQR;\nusing Eigen::SparseMatrix;\n\nusing namespace std;\nusing namespace PowerSolutions::ObjectModel;\n\nnamespace PowerSolutions\n{\n\tnamespace PowerFlow\n\t{\n\n\t\tNRSolver::NRSolver()\n\t\t{ }\n\n\t\tNRSolver::~NRSolver()\n\t\t{ }\n\n\t\tvoid NRSolver::BeforeIterations()\n\t\t{\n\t\t\tassert(Block1EquationCount() == PQNodeCount + PVNodeCount);\n\t\t\tassert(EquationCount() == PQNodeCount * 2 + PVNodeCount);\n\t\t\t//PQ节点：[dP dQ] = J * [V theta]\n\t\t\t//PV节点：[dP] = J * [theta]\n\t\t\t//       PQ/PV    |   PQ\n\t\t\t//Δy = [dP ... dP | dQ ... dQ] = ConstraintPower - CurrentPower\n\t\t\t//Δx = [theta ... theta | V ... V]\n\t\t\t// 分界线/起始索引：\n\t\t\t// H[0,0], N[NodeCount - 1, 0]\n\t\t\t//初始化矩阵维数\n\t\t\t//注意向量需要手动清零\n\t\t\tConstraintPowerInjection.resize(EquationCount());\n\t\t\tCurrentAnswer.resize(EquationCount());\n\t\t\tCorrectionAnswer.resize(EquationCount());\n\t\t\tPowerInjectionDeviation.resize(EquationCount());\n\t\t\t//估计雅可比矩阵非零元的数量\n\t\t\t//按照最不理想的情况来考虑雅可比矩阵的空间\n\t\t\tJocobianReservedValuesCount = 0;\n\t\t\tfor (int n = 0; n < Block1EquationCount(); n++)\n\t\t\t{\n\t\t\t\tauto& node = PNetwork->Nodes(n);\n\t\t\t\tJocobianReservedValuesCount += min(node.Degree() * 2, EquationCount());\n\t\t\t\tif (node.Type() == NodeType::PQNode)\n\t\t\t\t{\n\t\t\t\t\tJocobianReservedValuesCount += min(node.Degree() * 2, EquationCount());\n\t\t\t\t}\n\t\t\t}\n\t\t\tJocobian.resize(EquationCount(), EquationCount());\n\n\t\t\t//生成目标注入功率向量 y，以及迭代初值向量。\n\t\t\tfor (auto& node : PNetwork->Nodes())\n\t\t\t{\n\t\t\t\tif (node->Type() != NodeType::SlackNode)\n\t\t\t\t{\n\t\t\t\t\tint subIndex = Block1EquationCount() + node->SubIndex();\n\t\t\t\t\tConstraintPowerInjection(node->Index()) = node->ActivePowerInjection();\n\t\t\t\t\tCurrentAnswer(node->Index()) = arg(node->Bus()->InitialVoltage());\n\t\t\t\t\tif (node->Type() == NodeType::PQNode)\n\t\t\t\t\t{\n\t\t\t\t\t\tConstraintPowerInjection(subIndex) = node->ReactivePowerInjection();\n\t\t\t\t\t\tCurrentAnswer(subIndex) = abs(node->Bus()->InitialVoltage());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t_PS_TRACE(\"目标函数值 Y ==========\");\n\t\t\t_PS_TRACE(ConstraintPowerInjection);\n\t\t}\n\n\t\tpair<const PrimitiveNetwork::NodeInfo*, double> NRSolver::EvalDeviation()\n\t\t{\n\t\t\tEvalPowerInjection();\n\t\t\t//注意，最小系数不一定是绝对值最小的系数\n\t\t\tint row;\n\t\t\tdouble dev;\n\t\t\tdev = PowerInjectionDeviation.cwiseAbs().maxCoeff(&row);\n\t\t\tif (row < Block1EquationCount())\n\t\t\t\treturn make_pair(&PNetwork->Nodes(row), dev);\n\t\t\telse\n\t\t\t\treturn make_pair(&PNetwork->PQNodes(row - Block1EquationCount()), dev);\n\t\t}\n\n\t\tbool NRSolver::OnIteration()\n\t\t{\n\t\t\tGenerateJacobian();\n\t\t\tif (!GenerateNextAnswer()) return false;\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid NRSolver::AfterIterations()\n\t\t{\n\t\t\tfor (int i = 0; i < NodeCount; i++)\n\t\t\t\tUpdateNodeStatus(i);\n\t\t}\n\n\t\tinline double NRSolver::NodeVoltage(int NodeIndex)\n\t\t{\n\t\t\tauto& node = PNetwork->Nodes(NodeIndex);\n\t\t\tif (node.Type() == NodeType::PQNode)\n\t\t\t\treturn CurrentAnswer(Block1EquationCount() + node.SubIndex());\n\t\t\telse\n\t\t\t\treturn node.Voltage();\n\t\t}\n\n\t\tinline double NRSolver::NodeAngle(int NodeIndex)\n\t\t{\n\t\t\tassert(NodeIndex < NodeCount);\n\t\t\t//注意此处区分平衡节点。\n\t\t\treturn NodeIndex < NodeCount - 1 ? CurrentAnswer(NodeIndex) : 0;\n\t\t}\n\n\t\tvoid NRSolver::EvalPowerInjection()\n\t\t{\n\t\t\t//TODO 计入导纳矩阵可能的不对称性\n\t\t\t//计算各节点的实际注入功率，以及功率偏差 PowerInjectionDeviation\n\t\t\tPowerInjectionDeviation = ConstraintPowerInjection;\n\t\t\tfor (auto& node : PSolution->NodeStatus()) node.ClearPowerInjection();\n\t\t\t//遍历所有节点，包括平衡节点\n\t\t\t//此处使用 for 而非 for-each 是为了与数学表达保持一致\n\t\t\tauto &Admittance = PNetwork->Admittance;\n\t\t\tfor (int m = 0; m < NodeCount; m++)\n\t\t\t{\n\t\t\t\tauto &statusM = PSolution->NodeStatus(m);\n\t\t\t\tauto Um = NodeVoltage(m);\n\t\t\t\tauto thetaM = NodeAngle(m);\n\t\t\t\tint subM = Block1EquationCount() + statusM.SubIndex();\n\t\t\t\t//计算导纳矩阵中非对角元素对应的功率。\n\t\t\t\tfor (int n = m + 1; n < NodeCount; n++)\n\t\t\t\t{\n\t\t\t\t\t// 导纳矩阵是上三角矩阵，row < col\n\t\t\t\t\t// TODO 取消对导纳矩阵对称的假定（移相变压器）。\n\t\t\t\t\tcomplexd Y = Admittance.coeff(m, n);\n\t\t\t\t\tcomplexd Y1 = Admittance.coeff(n, m);\n\t\t\t\t\t//if (abs(Y) < 1e-10) continue;\n\t\t\t\t\tauto UmUn = Um * NodeVoltage(n);\n\t\t\t\t\tauto thetaMn = thetaM - NodeAngle(n);\n\t\t\t\t\tauto sinMn = sin(thetaMn);\n\t\t\t\t\tauto cosMn = cos(thetaMn);\n\t\t\t\t\tauto &statusN = PSolution->NodeStatus(n);\n\t\t\t\t\t//累计上一次迭代结果对应的注入功率\n\t\t\t\t\tstatusM.AddPowerInjections(UmUn * (Y.real() * cosMn + Y.imag() * sinMn),\n\t\t\t\t\t\tUmUn * (Y.real() * sinMn - Y.imag() * cosMn));\n\t\t\t\t\tstatusN.AddPowerInjections(UmUn * (Y1.real() * cosMn - Y1.imag() * sinMn),\n\t\t\t\t\t\tUmUn * (-Y1.real() * sinMn - Y1.imag() * cosMn));\n\t\t\t\t}\n\t\t\t\t//计算导纳矩阵中对角元素对应的功率。\n\t\t\t\tauto UmSqr = Um * Um;\n\t\t\t\tauto Y = Admittance.coeff(m, m);\n\t\t\t\tstatusM.AddPowerInjections(UmSqr * Y.real(), -UmSqr * Y.imag());\n\t\t\t\t//生成功率偏差向量 Δy'\n\t\t\t\tif (statusM.Type() != NodeType::SlackNode)\n\t\t\t\t{\n\t\t\t\t\tPowerInjectionDeviation(m) -= statusM.ActivePowerInjection();\n\t\t\t\t\tif (statusM.Type() == NodeType::PQNode)\n\t\t\t\t\t\tPowerInjectionDeviation(subM) -= statusM.ReactivePowerInjection();\n\t\t\t\t}\n\t\t\t}\n\t\t\t_PS_TRACE(\"平衡节点 ======\");\n\t\t\t_PS_TRACE(\"有功注入：\" << PSolution->NodeStatus(NodeCount - 1).ActivePowerInjection());\n\t\t\t_PS_TRACE(\"无功注入：\" << PSolution->NodeStatus(NodeCount - 1).ReactivePowerInjection());\n\t\t\t_PS_TRACE(\"偏差 deltaY ==========\");\n\t\t\t_PS_TRACE(PowerInjectionDeviation);\n\t\t}\n\t\t\n\t\tvoid NRSolver::GenerateJacobian()\n\t\t{\n\t\t\t//PQ节点：[dP dQ] = J * [V theta]\n\t\t\t//PV节点：[dP] = J * [theta]\n\t\t\t//       PQ/PV        PQ\n\t\t\t//Δy = [dP ... dP dQ ... dQ]\n\t\t\t//Δx = [theta ... theta V ... V]\n\t\t\t//    / H | N \\\n\t\t\t//J = | --+-- |\n\t\t\t//    \\ M | L /\n\t\t\t// 起始索引：（注意排除平衡节点）\n\t\t\t// H[0,0], N[NodeCount - 1, 0]\n\t\t\t// M[NodeCount - 1, 0], L[..., ...]\n\t\t\t// 对非对角元有\n\t\t\t// H =  L\n\t\t\t// N = -M\n\t\t\tauto& Admittance = PNetwork->Admittance;\n\t\t\t// 雅可比矩阵非零元。\n\t\t\tvector<Triplet<double>> values;\n\t\t\tvalues.reserve(JocobianReservedValuesCount);\n\t\t\t// 建议使用 Triplet 构造矩阵，可以取得不错的性能，而且生成的矩阵是压缩过的。\n\t\t\tfor (int outer = 0; outer < Admittance.outerSize(); outer++)\n\t\t\t\tfor (SparseMatrix<complexd>::InnerIterator it(Admittance, outer); it; ++it)\n\t\t\t\t{\n\t\t\t\t\tauto m = it.row();\n\t\t\t\t\tauto n = it.col();\n\t\t\t\t\t// 注意排除平衡节点\n\t\t\t\t\tif (m == NodeCount - 1 || n == NodeCount - 1) \n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tauto& nodeM = PSolution->NodeStatus(m);\n\t\t\t\t\tauto Um = NodeVoltage(m);\n\t\t\t\t\tauto thetaM = NodeAngle(m);\n\t\t\t\t\tauto subM = Block1EquationCount() + nodeM.SubIndex();\n\t\t\t\t\t//计算非对角元素\n\t\t\t\t\tif (n > m)\n\t\t\t\t\t{\n\t\t\t\t\t\tcomplexd Ymn = it.value();\n\t\t\t\t\t\tcomplexd Ynm = it.value();\n\t\t\t\t\t\tdouble UmUn = Um * NodeVoltage(n);\n\t\t\t\t\t\tdouble thetaMn = thetaM - NodeAngle(n);\n\t\t\t\t\t\tdouble sinMn = sin(thetaMn);\n\t\t\t\t\t\tdouble cosMn = cos(thetaMn);\n\t\t\t\t\t\t//H(m,n)\n\t\t\t\t\t\tdouble H = -UmUn * (Ymn.real() * sinMn - Ymn.imag() * cosMn);\n\t\t\t\t\t\tvalues.emplace_back(m, n, H);\n\t\t\t\t\t\t//H(n,m)\n\t\t\t\t\t\tdouble Hp = UmUn * (Ynm.real() * sinMn + Ynm.imag() * cosMn);\n\t\t\t\t\t\tvalues.emplace_back(n, m, Hp);\n\t\t\t\t\t\t//i.e. H(n,m) = -UmUn * (-Y.real() * sinMn - Y.imag() * cosMn)\n\t\t\t\t\t\t//N\n\t\t\t\t\t\tdouble N = -UmUn * (Ymn.real() * cosMn + Ymn.imag() * sinMn);\n\t\t\t\t\t\tdouble Np = -UmUn * (Ynm.real() * cosMn - Ynm.imag() * sinMn);\n\t\t\t\t\t\t//cout << \"::\" << m << \",\" << n << \" = \" << Jocobian.insert(1, 0) << endl;\n\t\t\t\t\t\tauto& nodeN = PSolution->NodeStatus(n);\n\t\t\t\t\t\tint subN = Block1EquationCount() + nodeN.SubIndex();\n\t\t\t\t\t\tif (nodeM.Type() == NodeType::PQNode)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (nodeN.Type() == NodeType::PQNode)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//PQ-PQ，子阵具有对称性\n\t\t\t\t\t\t\t\t// N\n\t\t\t\t\t\t\t\tvalues.emplace_back(m, subN, N);\n\t\t\t\t\t\t\t\tvalues.emplace_back(n, subM, Np);\n\t\t\t\t\t\t\t\t// M = -N\n\t\t\t\t\t\t\t\tvalues.emplace_back(subM, n, -N);\n\t\t\t\t\t\t\t\tvalues.emplace_back(subN, m, -Np);\n\t\t\t\t\t\t\t\t// L = H\n\t\t\t\t\t\t\t\tvalues.emplace_back(subM, subN, H);\n\t\t\t\t\t\t\t\tvalues.emplace_back(subN, subM, Hp);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t//PQ-PV（m,n）\n\t\t\t\t\t\t\t\t// M = -N\n\t\t\t\t\t\t\t\tvalues.emplace_back(subM, n, -N);\n\t\t\t\t\t\t\t\t//PV-PQ（n,m）\n\t\t\t\t\t\t\t\t// N\n\t\t\t\t\t\t\t\tvalues.emplace_back(n, subM, Np);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (nodeN.Type() == NodeType::PQNode)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//PV-PQ（m,n）\n\t\t\t\t\t\t\t\t// N\n\t\t\t\t\t\t\t\tvalues.emplace_back(m, subN, N);\n\t\t\t\t\t\t\t\t//PQ-PV（n,m）\n\t\t\t\t\t\t\t\t// M\n\t\t\t\t\t\t\t\tvalues.emplace_back(subN, m, -Np);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (n == m)\n\t\t\t\t\t{\n\t\t\t\t\t\tcomplexd Y = it.value();\n\t\t\t\t\t\tdouble UmSqr = Um * Um;\n\t\t\t\t\t\t//计算对角元素\n\t\t\t\t\t\t//H\n\t\t\t\t\t\tvalues.emplace_back(m, m, UmSqr * Y.imag() + nodeM.ReactivePowerInjection());\n\t\t\t\t\t\tif (nodeM.Type() == NodeType::PQNode)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//N\n\t\t\t\t\t\t\tvalues.emplace_back(m, subM, -UmSqr * Y.real() - nodeM.ActivePowerInjection());\n\t\t\t\t\t\t\t//M\n\t\t\t\t\t\t\tvalues.emplace_back(subM, m, UmSqr * Y.real() - nodeM.ActivePowerInjection());\n\t\t\t\t\t\t\t//L\n\t\t\t\t\t\t\tvalues.emplace_back(subM, subM, UmSqr * Y.imag() - nodeM.ReactivePowerInjection());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tJocobian.setFromTriplets(values.begin(), values.end());\n\t\t\t_PS_TRACE(\"雅可比矩阵 ==========\");\n\t\t\t_PS_TRACE(Jocobian);\n\t\t}\n\n\t\tbool NRSolver::GenerateNextAnswer()\n\t\t{\n\t\t\tSparseLU<SparseMatrix<double>> solver;\n\t\t\t//求解矩阵方程\n\t\t\tJocobian.makeCompressed();\n\t\t\tsolver.compute(Jocobian);\n\t\t\tif (solver.info() != Eigen::Success) return false;\n\t\t\tCorrectionAnswer = solver.solve(PowerInjectionDeviation);\n\t\t\tif (solver.info() != Eigen::Success) return false;\n\t\t\t//计算新的结果\n\t\t\t//注意到 Δy = -J Δx\n\t\t\t//而此处实际解的方程组为 Δy' = J Δx\n\t\t\t//也就是说，Δy = -Δy'\n\t\t\t//Δx = [theta ... theta V ... V]\n\t\t\tCurrentAnswer.head(Block1EquationCount()) -= CorrectionAnswer.head(Block1EquationCount());\n\t\t\tCurrentAnswer.tail(Block2EquationCount()) -= CurrentAnswer.tail(Block2EquationCount()).cwiseProduct(CorrectionAnswer.tail(Block2EquationCount()));\n\t\t\t_PS_TRACE(\"当前解向量 ==========\");\n\t\t\t_PS_TRACE(CurrentAnswer);\n\t\t\treturn true;\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "94340036d75ae60eb5be64fa1934febb6d0d0a0b", "size": 9461, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PowerSolutions.PowerFlow/NRSolver.cpp", "max_stars_repo_name": "CXuesong/PowerFlowSolver", "max_stars_repo_head_hexsha": "20dc3a02fed7f78011949eaa99df546681f28683", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-02T07:43:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T22:54:57.000Z", "max_issues_repo_path": "PowerSolutions.PowerFlow/NRSolver.cpp", "max_issues_repo_name": "CXuesong/PowerFlowSolver", "max_issues_repo_head_hexsha": "20dc3a02fed7f78011949eaa99df546681f28683", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-02T07:44:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-05T15:54:44.000Z", "max_forks_repo_path": "PowerSolutions.PowerFlow/NRSolver.cpp", "max_forks_repo_name": "CXuesong/PowerFlowSolver", "max_forks_repo_head_hexsha": "20dc3a02fed7f78011949eaa99df546681f28683", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-01T03:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-04T16:05:55.000Z", "avg_line_length": 30.7175324675, "max_line_length": 149, "alphanum_fraction": 0.5978226403, "num_tokens": 3394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936484231889, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4483592981510129}}
{"text": "/***************************************************************************\n *   Copyright (C) 2007 by Reed A. Cartwright                              *\n *   reed@scit.us                                                          *\n *                                                                         *\n *   Permission is hereby granted, free of charge, to any person obtaining *\n *   a copy of this software and associated documentation files (the       *\n *   \"Software\"), to deal in the Software without restriction, including   *\n *   without limitation the rights to use, copy, modify, merge, publish,   *\n *   distribute, sublicense, and/or sell copies of the Software, and to    *\n *   permit persons to whom the Software is furnished to do so, subject to *\n *   the following conditions:                                             *\n *                                                                         *\n *   The above copyright notice and this permission notice shall be        *\n *   included in all copies or substantial portions of the Software.       *\n *                                                                         *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR     *\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *\n *   OTHER DEALINGS IN THE SOFTWARE.                                       *\n ***************************************************************************/\n\n#ifdef HAVE_CONFIG_H\n#\tinclude \"config.h\"\n#endif\n\n#define _USE_MATH_DEFINES\n\n#include <iostream>\n\n#include <boost/math/special_functions/zeta.hpp>\n\n#include \"sample.h\"\n#include \"sample_k2p.h\"\n#include \"ccvector.h\"\n#include \"series.h\"\n#include \"invert_matrix.h\"\n#include \"table.h\"\n#include \"emdel.h\"\n\nusing namespace std;\n\nvoid sample_k2p_zeta::preallocate(size_t maxa, size_t maxd)\n{\n\tp.resize(maxa+1,maxd+1,0.0);\n}\n\nvoid sample_k2p_zeta::presample_step(const params_type &params, const sequence &seq_a, const sequence &seq_d)\n{\n\tsize_t sz_max = std::max(sz_height, sz_width);\n\tsize_t sz_anc = seq_a.size();\n\tsize_t sz_dec = seq_d.size();\n\tsa = seq_a;\n\tsd = seq_d;\n\t\n\tconst model_type &model = get_model();\n\t\n\tp(0,0) = prob_scale;\n\t\n\tfor(size_t d = 1; d <= sz_dec; ++d) {\n\t\tp(0,d) = 0.0;\n\t\tfor(size_t k = d; k > 0; --k)\n\t\t\tp(0,d) += p(0,d-k)*model.p_indel_size[k];\n\t}\n\t\t\n\tfor(size_t a = 1; a <= sz_anc; ++a) {\n\t\tp(a,0) = 0.0;\n\t\tfor(size_t k = a; k > 0; --k)\n\t\t\tp(a,0) += p(a-k,0)*model.p_indel_size[k];\n\t}\n\n\tfor(size_t a=1;a<=sz_anc;++a) {\n\t\tfor(size_t d=1;d<= sz_dec;++d) {\n\t\t\tdouble pt = p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]];\n\n\t\t\tfor(size_t k = d; k > 0; --k)\n\t\t\t\tpt += p(a,d-k)*model.p_indel_size[k];\n\t\t\tfor(size_t k = a; k > 0; --k)\n\t\t\t\tpt += p(a-k,d)*model.p_indel_size[k];\n\t\t\tp(a,d) = pt;\n\t\t}\n\t}\n}\n\nvoid sample_k2p_zeta::sample_once(std::string &seq_a, std::string &seq_d)\n{\n\tsize_t a = sa.size();\n\tsize_t d = sd.size();\n\tseq_a.clear();\n\tseq_d.clear();\n\t\n\tconst model_type &model = get_model();\n\t\n\twhile(a != 0 || d != 0) {\n\t\tdouble u = p(a,d)*myrand.uniform01();\n\t\tdouble t = (a > 0 && d > 0) ? p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]] : 0.0;\n\t\tif(u < t) {\n\t\t\t// match\n\t\t\ta = a-1;\n\t\t\td = d-1;\n\t\t\tseq_a.append(1, ccNuc[sa[a]]);\n\t\t\tseq_d.append(1, ccNuc[sd[d]]);\n\t\t} else {\n\t\t\tfor(size_t k = 1; k <= a || k <= d; ++k) {\n\t\t\t\tif(k <= a) {\n\t\t\t\t\tt += p(a-k,d)*model.p_indel_size[k];\n\t\t\t\t\tif(u < t) {\n\t\t\t\t\t\t// gap in d\n\t\t\t\t\t\tseq_d.append(k, '-');\n\t\t\t\t\t\twhile(k--) seq_a.append(1, ccNuc[sa[--a]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(k <= d)\n\t\t\t\t{\n\t\t\t\t\tt += p(a,d-k)*model.p_indel_size[k];\n\t\t\t\t\tif(u < t) {\n\t\t\t\t\t\t// gap in a\n\t\t\t\t\t\tseq_a.append(k, '-');\n\t\t\t\t\t\twhile(k--) seq_d.append(1, ccNuc[sd[--d]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//seq_a.append(1,',');\n\t\t//seq_d.append(1,',');\n\t}\n\treverse(seq_a.begin(), seq_a.end());\n\treverse(seq_d.begin(), seq_d.end());\n}\n\nvoid sample_k2p_geo::preallocate(size_t maxa, size_t maxd)\n{\n\tp.resize(maxa+1,maxd+1,0.0);\n}\n\nvoid sample_k2p_geo::presample_step(const params_type &params, const sequence &seq_a, const sequence &seq_d)\n{\n\tsize_t sz_max = std::max(sz_height, sz_width);\n\tsize_t sz_anc = seq_a.size();\n\tsize_t sz_dec = seq_d.size();\n\tsa = seq_a;\n\tsd = seq_d;\n\t\n\tconst model_type &model = get_model();\n\t\n\tdouble row_cache = 0.0;\n\tvector<double> col_cache(sz_dec+1, 0.0);\n\t\n\tp(0,0) = prob_scale;\n\tfor(size_t d = 1; d <= sz_dec; ++d) {\n\t\trow_cache *= model.p_extend;\n\t\trow_cache += p(0,d-1)*model.p_open;\n\t\tp(0,d) = row_cache;\n\t}\n\t\n\trow_cache = 0.0;\n\tfor(size_t a = 1; a <= sz_anc; ++a) {\n\t\trow_cache *= model.p_extend;\n\t\trow_cache += p(a-1,0)*model.p_open;\n\t\tp(a,0) = row_cache;\n\t}\n\n\tfor(size_t a=1;a<=sz_anc;++a) {\n\t\trow_cache = 0.0;\n\t\tfor(size_t d=1;d<= sz_dec;++d) {\n\t\t\tdouble pt = p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]];\n\t\t\trow_cache *= model.p_extend;\n\t\t\trow_cache += p(a,d-1)*model.p_open;\n\t\t\tpt += row_cache;\n\t\t\tcol_cache[d] *= model.p_extend;\n\t\t\tcol_cache[d] += p(a-1,d)*model.p_open;\n\t\t\tpt += col_cache[d];\n\t\t\tp(a,d) = pt;\n\t\t}\n\t}\n}\n\nvoid sample_k2p_geo::sample_once(std::string &seq_a, std::string &seq_d)\n{\n\tsize_t a = sa.size();\n\tsize_t d = sd.size();\n\tseq_a.clear();\n\tseq_d.clear();\n\t\n\tconst model_type &model = get_model();\n\t\n\twhile(a != 0 || d != 0) {\n\t\tdouble u = p(a,d)*myrand.uniform01();\n\t\tdouble t = (a > 0 && d > 0) ? p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]] : 0.0;\n\t\tif(u < t) {\n\t\t\t// match\n\t\t\ta = a-1;\n\t\t\td = d-1;\n\t\t\tseq_a.append(1, ccNuc[sa[a]]);\n\t\t\tseq_d.append(1, ccNuc[sd[d]]);\n\t\t} else {\n\t\t\tfor(size_t k = 1; k <= a || k <= d; ++k) {\n\t\t\t\tif(k <= a) {\n\t\t\t\t\tt += p(a-k,d)*model.p_indel_size[k];\n\t\t\t\t\tif(u < t) {\n\t\t\t\t\t\t// gap in d\n\t\t\t\t\t\tseq_d.append(k, '-');\n\t\t\t\t\t\twhile(k--) seq_a.append(1, ccNuc[sa[--a]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(k <= d)\n\t\t\t\t{\n\t\t\t\t\tt += p(a,d-k)*model.p_indel_size[k];\n\t\t\t\t\tif(u < t) {\n\t\t\t\t\t\t// gap in a\n\t\t\t\t\t\tseq_a.append(k, '-');\n\t\t\t\t\t\twhile(k--) seq_d.append(1, ccNuc[sd[--d]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//seq_a.append(1,',');\n\t\t//seq_d.append(1,',');\n\t}\n\treverse(seq_a.begin(), seq_a.end());\n\treverse(seq_d.begin(), seq_d.end());\n}\n\n// Draw from Zipf distribution, with parameter a > 1.0\n// Devroye Luc (1986) Non-uniform random variate generation.\n//     Springer-Verlag: Berlin. p551\ninline unsigned int rand_zipf(double a)\n{\n\tdouble b = pow(2.0, a-1.0);\n\tdouble x,t;\n\tdo {\n\t x = floor(pow(myrand.uniform01(), -1.0/(a-1.0)));\n\t t = pow(1.0+1.0/x, a-1.0);\n\t} while( myrand.uniform01()*x*(t-1.0)*b >= t*(b-1.0));\n\treturn (unsigned int)x;\n}\n\nconst char g_nuc[] = \"ACGT\";\nconst char g_nuc2[] = \"ACGT\" \"GTAC\" \"TGCA\" \"CATG\";\n\nvoid gen_sample_k2p_zeta::sample_once(std::string &seq_a, std::string &seq_d)\n{\n\tseq_a.clear();\n\tseq_d.clear();\n\t\n\tconst model_type &model = get_model();\n\tconst double z = get_params()[model_k2p_zeta::pZ];\n\twhile(1) {\n\t\tdouble p = myrand.uniform01();\n\t\tif(p < model.p_2h) {\n\t\t\t// M\n\t\t\tunsigned int x = myrand.uniform(4);\n\t\t\tseq_a.append(1, g_nuc[x]);\n\t\t\tp = myrand.uniform01();\n\t\t\tif(p < model.p_match) {\n\t\t\t\tseq_d.append(1, g_nuc2[x]);\n\t\t\t} else if(p < model.p_match+model.p_ts) {\n\t\t\t\tseq_d.append(1, g_nuc2[x+4]);\n\t\t\t} else if(p < 1.0 - 0.5*model.p_ts) {\n\t\t\t\tseq_d.append(1, g_nuc2[x+8]);\n\t\t\t} else {\n\t\t\t\tseq_d.append(1, g_nuc2[x+12]);\n\t\t\t}\n\t\t} else if(p <  model.p_2h+model.p_2g) {\n\t\t\t// U\n\t\t\tunsigned int x;\n\t\t\tdo {\n\t\t\t\tx = rand_zipf(z);\n\t\t\t} while(x > nmax);\n\t\t\tseq_d.append(x, '-');\n\t\t\twhile(x--) {\n\t\t\t\tseq_a.append(1, g_nuc[myrand.uniform(4)]);\n\t\t\t}\n\t\t} else if(p <  1.0-model.p_end) {\n\t\t\t// V\n\t\t\tunsigned int x;\n\t\t\tdo {\n\t\t\t\tx = rand_zipf(z);\n\t\t\t} while(x > nmax);\n\t\t\tseq_a.append(x, '-');\n\t\t\twhile(x--) {\n\t\t\t\tseq_d.append(1, g_nuc[myrand.uniform(4)]);\n\t\t\t}\t\t\t\n\t\t} else {\n\t\t\t// E\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid gen_sample_k2p_geo::sample_once(std::string &seq_a, std::string &seq_d)\n{\n\tseq_a.clear();\n\tseq_d.clear();\n\t\n\tconst model_type &model = get_model();\n\tconst double q = 1.0/get_params()[model_k2p_geo::pQ];\n\twhile(1) {\n\t\tdouble p = myrand.uniform01();\n\t\tif(p < model.p_2h) {\n\t\t\t// M\n\t\t\tunsigned int x = myrand.uniform(4);\n\t\t\tseq_a.append(1, g_nuc[x]);\n\t\t\tp = myrand.uniform01();\n\t\t\tif(p < model.p_match) {\n\t\t\t\tseq_d.append(1, g_nuc2[x]);\n\t\t\t} else if(p < model.p_match+model.p_ts) {\n\t\t\t\tseq_d.append(1, g_nuc2[x+4]);\n\t\t\t} else if(p < 1.0 - 0.5*model.p_ts) {\n\t\t\t\tseq_d.append(1, g_nuc2[x+8]);\n\t\t\t} else {\n\t\t\t\tseq_d.append(1, g_nuc2[x+12]);\n\t\t\t}\n\t\t} else if(p <  model.p_2h+model.p_2g) {\n\t\t\t// U\n\t\t\tunsigned int x = myrand.geometric(q);\n\t\t\tseq_d.append(x, '-');\n\t\t\twhile(x--) {\n\t\t\t\tseq_a.append(1, g_nuc[myrand.uniform(4)]);\n\t\t\t}\n\t\t} else if(p <  1.0-model.p_end) {\n\t\t\t// V\n\t\t\tunsigned int x = myrand.geometric(q);\n\t\t\tseq_a.append(x, '-');\n\t\t\twhile(x--) {\n\t\t\t\tseq_d.append(1, g_nuc[myrand.uniform(4)]);\n\t\t\t}\n\t\t} else {\n\t\t\t// E\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n", "meta": {"hexsha": "c9c1aa4f19e6498de34a61175dd7cf8af1f60929", "size": 9006, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sample.cpp", "max_stars_repo_name": "reedacartwright/emdel", "max_stars_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sample.cpp", "max_issues_repo_name": "reedacartwright/emdel", "max_issues_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-03T16:50:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T22:51:19.000Z", "max_forks_repo_path": "src/sample.cpp", "max_forks_repo_name": "reedacartwright/emdel", "max_forks_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3333333333, "max_line_length": 109, "alphanum_fraction": 0.5504108372, "num_tokens": 2977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4483592887825558}}
{"text": "/*\r\n * cg.cpp\r\n *\r\n * Author: H. Hofbauer (hhofbaue@cosy.sbg.ac.at), E. Pschernig (epschern@cosy.sbg.ac.at), P. Wild (pwild@cosy.sbg.ac.at)\r\n *\r\n * Generates an iris code from iris texture using complex gabor filters with different filter size and wavelength.\r\n *\r\n */\r\n#include \"version.h\"\r\n#include <cstdio>\r\n#include <map>\r\n#include <vector>\r\n#include <string>\r\n#include <cstring>\r\n#include <ctime>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <opencv2/core/core.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <boost/regex.hpp>\r\n#include <boost/lexical_cast.hpp>\r\n#include <boost/filesystem.hpp>\r\n#include <boost/date_time/posix_time/posix_time_types.hpp>\r\n#ifndef M_PI\r\n#define M_PI 3.14159265358979323846\r\n#endif\r\n\r\nusing namespace std;\r\nusing namespace cv;\r\n\r\n/** no globbing in win32 mode **/\r\nint _CRT_glob = 0;\r\n\r\n/** Program modes **/\r\nstatic const int MODE_MAIN = 1, MODE_HELP = 2;\r\n\r\nint FILTER_HEIGHT=31;\r\n\r\n/*\r\n * Print command line usage for this program\r\n */\r\nvoid printUsage() {\r\n    printVersion();\r\n\tprintf(\"+-----------------------------------------------------------------------------+\\n\");\r\n\tprintf(\"| cg - Iris-code generation (feature extraction) using complex gabor filters  |\\n\");\r\n\tprintf(\"|      with varying wavelengths.                                              |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| John Daugman. The importance of being random: statistical principles of     |\\n\");\r\n\tprintf(\"| iris recognition. Pattern Recognition 36(2003) 279--291.                    |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| MODES                                                                       |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n    printf(\"| (# 1) cg iris code extraction from iris textures                            |\\n\");\r\n    printf(\"| (# 2) usage                                                                 |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| ARGUMENTS                                                                   |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n    printf(\"| Name | Parameters | # | ? | Description                                     |\\n\");\r\n    printf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n    printf(\"| -i   | infile     | 1 | N | input iris texture (use * as wildcard, all other|\\n\");\r\n    printf(\"|      |            |   |   | file parameters may refer to n-th * with ?n)    |\\n\");\r\n    printf(\"| -o   | outfile    | 1 | N | output iris code image                          |\\n\");\r\n//    printf(\"| -m   | inmaskfile | 1 | Y | noise pixelmask (0: noise, 255: noise-free)     |\\n\");\r\n//    printf(\"|      | outmaskfile|   |   | code bitmask (0: noise, 1: noise-free, off)     |\\n\");\r\n    printf(\"| -q   |            | 1 | Y | quiet mode on (off)                             |\\n\");\r\n    printf(\"| -t   |            | 1 | Y | time progress on (off)                          |\\n\");\r\n    printf(\"| -h   |            | 2 | N | prints usage                                    |\\n\");\r\n    printf(\"|      |            |   |   |                                                 |\\n\");\r\n    printf(\"| -pwl | wavelength | 1 | N | Base wavelength of the gabor filter in pixel.   |\\n\");\r\n    printf(\"|      |            |   |   | Size of base filter will then be 2*wl+1.        |\\n\");\r\n    printf(\"|      |            |   |   | (default 6)                                     |\\n\");\r\n    printf(\"| -pbp | borderpower| 1 | N | Remaining power of the gauss-part of the filter |\\n\");\r\n    printf(\"|      |            |   |   | relative to the center (default 0.01).          |\\n\");\r\n    printf(\"| -psx | x-samples  | 1 | N | Number of horizontal samples (default 256)      |\\n\");\r\n    printf(\"| -x   | width      | 1 | N | Width of input texture (default 512).           |\\n\");\r\n    printf(\"| -y   | height     | 1 | N | Height of input texture (default 64).           |\\n\");\r\n    printf(\"|      |            |   |   |                                                 |\\n\");\r\n    printf(\"| -wf  |            | 1 | N | Write filterbank images                         |\\n\");\r\n    printf(\"| -ws  |            | 1 | N | Write image sample with filtered versions       |\\n\");\r\n    printf(\"| -wp  |            | 1 | N | Write iris image with extraction points         |\\n\");\r\n    printf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| EXAMPLE USAGE                                                               |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| -i s1.tiff -o s1.png                                                        |\\n\");\r\n    printf(\"| -i *.tiff -o ?1.png -q -t                                                   |\\n\");\r\n    printf(\"| -i *.tiff -im ?1_mask.png -o ?1_code.png -om ?1_codemask.png -q -t          |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| AUTHORS                                                                     |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| Heinz Hofbauer (hhofbaue@cosy.sbg.ac.at)                                    |\\n\");\r\n    printf(\"| Elias Pschernig (epschern@cosy.sbg.ac.at)                                   |\\n\");\r\n    printf(\"| Peter Wild (pwild@cosy.sbg.ac.at)                                           |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| COPYRIGHT                                                                   |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| (C) 2012 All rights reserved. Do not distribute without written permission. |\\n\");\r\n    printf(\"+-----------------------------------------------------------------------------+\\n\");\r\n}\r\n\r\n\r\n/** --------------- writerstuff for debugging/control --------------- **/\r\n\r\nvoid writeNormMatToFile(const Mat &what, const string &where, const string &txtmessage = \"\", bool write_sign=false){\r\n    if( write_sign){\r\n        Mat img = ( what >= 0);\r\n        imwrite( where, img);\r\n    } else {\r\n        Mat img(what.rows, what.cols, CV_8U);\r\n        normalize( what, img, 0, 255, NORM_MINMAX);\r\n        imwrite( where, img);\r\n    }\r\n    if( !txtmessage.empty()) cout << txtmessage << \" file(\"<<where<<\")\"<<endl;\r\n}\r\n\r\nvoid writeExtractionsequence( const Mat &img, const vector<Point> &extractionsequence, bool &writeagain){\r\n    Mat pointoverlay = img.clone();\r\n    for( vector<Point>::const_iterator eit = extractionsequence.begin(); eit != extractionsequence.end(); advance(eit, 1) )\r\n        circle( pointoverlay, *eit, 1, Scalar(255,128,128));\r\n    writeagain = false;\r\n    imwrite( \"extractionpointlocation.png\", pointoverlay);\r\n    cout << \"Extraction point locations written to: extractionpointlocation.png\"<<endl;\r\n}\r\nvoid writeFilterbank( const vector<Mat> &filterbank){\r\n    for( vector<Mat>::const_iterator it = filterbank.begin(); it != filterbank.end(); advance(it,1)){\r\n        string filename = \"filter_\";\r\n        int idx = distance( filterbank.begin(), it);\r\n        if ( idx % 2 == 0 ) filename+=\"re\";\r\n        else filename+=\"im\";\r\n        filename += boost::lexical_cast<string>(idx/2+1) + \"_wl\" + boost::lexical_cast<string>((it->cols-1)/2);\r\n        filename += \".png\";\r\n        writeNormMatToFile( *it, filename);\r\n        cout << \"filterbank written: \"<<filename<<endl;\r\n    }\r\n}\r\n/** ------------------------------- image processing functions ------------------------------- **/\r\n\r\n\r\nMat extendByWrap (const Mat &src,  int ext_width,  int  ext_height=0){\r\n    CV_Assert(ext_width >=0 && ext_height >= 0);\r\n    int w = src.cols + ext_width;\r\n    int woff = ext_width/2;\r\n    int wrest = ext_width-woff;\r\n    int h = src.rows + ext_height;\r\n    int hoff = ext_height/2;\r\n    int hrest = ext_height-hoff;\r\n\r\n    Mat dst(h,w,src.type());\r\n    copyMakeBorder( src, dst, hoff, hrest, woff, wrest, BORDER_WRAP);\r\n    return dst;\r\n}\r\n\r\n\r\nvoid featureExtract(Mat &code, Mat &codeMask, const Mat &img, const Mat &mask, const vector<Mat> &filterbank, const vector<Point> &extractionsequence, bool &write_samples){\r\n    CV_Assert(code.size() == Size( filterbank.size()  * extractionsequence.size()/8,1));\r\n    CV_Assert(mask.empty() || codeMask.empty() || codeMask.size() == code.size());\r\n    bool useMask = !mask.empty() && !codeMask.empty();\r\n\r\n    int filter_w=0, filter_h=0;\r\n    for( vector<Mat>::const_iterator it=filterbank.begin(); it != filterbank.end(); advance(it,1)){\r\n        if( it->cols > filter_w) filter_w = it->cols;\r\n        if( it->rows > filter_h) filter_h = it->rows;\r\n    }\r\n    Mat extimg = extendByWrap( img, filter_w/* , filter_h */);\r\n    Point extoff(filter_w/2, 0);\r\n\r\n    vector<Mat> filteredExtImg;\r\n    for( unsigned int i=0; i < filterbank.size(); ++i){\r\n        filteredExtImg.push_back(extimg.clone());\r\n        filter2D(extimg, filteredExtImg[i], CV_32F, filterbank[i]);\r\n        if( write_samples){\r\n            writeNormMatToFile(filteredExtImg[i], \"filtered_ext_fb\"+boost::lexical_cast<string>(i)+\".png\", \"sample written:\");\r\n            writeNormMatToFile(filteredExtImg[i], \"filtered_ext_fb\"+boost::lexical_cast<string>(i)+\"_bitmap.png\", \"sample written:\", true);\r\n        }\r\n    }\r\n    if( write_samples) writeNormMatToFile(extimg, \"filtered_ext_orig.png\", \"sample written\");\r\n    \r\n\r\n    uchar *codeMaskData = NULL;\r\n\tif (useMask){\r\n        codeMask.setTo(255);\r\n        codeMaskData = codeMask.data;\r\n    }\r\n\tcode.setTo(0);\r\n    uchar * codeData = code.data;\r\n    int bitpos = 0;\r\n    float fval;\r\n    for( vector<Mat>::const_iterator fit = filteredExtImg.begin(); fit != filteredExtImg.end(); advance( fit, 1) ){\r\n        for( vector<Point>::const_iterator eit = extractionsequence.begin(); eit != extractionsequence.end(); advance( eit,1) ){\r\n            // true = 1 for sign, 0 is default\r\n            fval = fit->at<float>(*eit + extoff);\r\n            if( fval >= 0) codeData[0] |= 1<<(7-bitpos);\r\n            if( useMask ){\r\n                if( ( fval*fval < 0.000000001 ) ||    // values are very small, discard as possible error\r\n                    ( codeMask.at<uchar>(*eit) > 0 ) )     // texture is masked\r\n                            codeMaskData[0] &= 0xff ^ 1 << (7-bitpos);\r\n            }\r\n            bitpos++;\r\n            if( bitpos == 8){\r\n                codeData++;\r\n                bitpos = 0;\r\n                if (useMask) codeMaskData++;\r\n            }\r\n        }\r\n    }\r\n    write_samples = false; // only write one set \r\n}\r\n\r\n/** ------------------------------- commandline functions ------------------------------- **/\r\n\r\n/**\r\n * Parses a command line\r\n * This routine should be called for parsing command lines for executables.\r\n * Note, that all options require '-' as prefix and may contain an arbitrary\r\n * number of optional arguments.\r\n *\r\n * cmd: commandline representation\r\n * argc: number of parameters\r\n * argv: string array of argument values\r\n */\r\nvoid cmdRead(map<string ,vector<string> >& cmd, int argc, char *argv[]){\r\n\tfor (int i=1; i< argc; i++){\r\n\t\tchar * argument = argv[i];\r\n\t\tif (strlen(argument) > 1 && argument[0] == '-' && (argument[1] < '0' || argument[1] > '9')){\r\n\t\t\tcmd[argument]; // insert\r\n\t\t\tchar * argument2;\r\n\t\t\twhile (i + 1 < argc && (strlen(argument2 = argv[i+1]) <= 1 || argument2[0] != '-'  || (argument2[1] >= '0' && argument2[1] <= '9'))){\r\n\t\t\t\tcmd[argument].push_back(argument2);\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tCV_Error(CV_StsBadArg,\"Invalid command line format\");\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Checks, if each command line option is valid, i.e. exists in the options array\r\n *\r\n * cmd: commandline representation\r\n * validOptions: list of valid options separated by pipe (i.e. |) character\r\n */\r\nvoid cmdCheckOpts(map<string ,vector<string> >& cmd, const string &validOptions){\r\n\tvector<string> tokens;\r\n\tconst string delimiters = \"|\";\r\n\tstring::size_type lastPos = validOptions.find_first_not_of(delimiters,0); // skip delimiters at beginning\r\n\tstring::size_type pos = validOptions.find_first_of(delimiters, lastPos); // find first non-delimiter\r\n\twhile (string::npos != pos || string::npos != lastPos){\r\n\t\ttokens.push_back(validOptions.substr(lastPos,pos - lastPos)); // add found token to vector\r\n\t\tlastPos = validOptions.find_first_not_of(delimiters,pos); // skip delimiters\r\n\t\tpos = validOptions.find_first_of(delimiters,lastPos); // find next non-delimiter\r\n\t}\r\n\tsort(tokens.begin(), tokens.end());\r\n\tfor (map<string, vector<string> >::iterator it = cmd.begin(); it != cmd.end(); std::advance(it,1)){\r\n\t\tif (!binary_search(tokens.begin(),tokens.end(),it->first)){\r\n\t\t\tCV_Error(CV_StsBadArg,\"Command line parameter '\" + it->first + \"' not allowed.\");\r\n\t\t\ttokens.clear();\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\ttokens.clear();\r\n}\r\n\r\n/*\r\n * Checks, if a specific required option exists in the command line\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n */\r\nvoid cmdCheckOptExists(map<string ,vector<string> >& cmd, const string &option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it == cmd.end()) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' is required, but does not exist.\");\r\n}\r\n\r\n/*\r\n * Checks, if a specific option has the appropriate number of parameters\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n * size: appropriate number of parameters for the option\r\n */\r\nvoid cmdCheckOptSize(map<string ,vector<string> >& cmd, const string &option, const unsigned int size = 1){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it->second.size() != size) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' has unexpected size.\");\r\n}\r\n\r\n/*\r\n * Checks, if a specific option has the appropriate number of parameters\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n * min: minimum appropriate number of parameters for the option\r\n * max: maximum appropriate number of parameters for the option\r\n */\r\nvoid cmdCheckOptRange(map<string ,vector<string> >& cmd, string option, unsigned int min = 0, unsigned int max = 1){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tunsigned int size = it->second.size();\r\n\tif (size < min || size > max) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' is out of range.\");\r\n}\r\n\r\n/*\r\n * Returns the list of parameters for a given option\r\n *\r\n * cmd: commandline representation\r\n * option: name of the option\r\n */\r\nvector<string> * cmdGetOpt(map<string ,vector<string> >& cmd, const string &option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\treturn (it != cmd.end()) ? &(it->second) : 0;\r\n}\r\n\r\n/*\r\n * Returns number of parameters in an option\r\n *\r\n * cmd: commandline representation\r\n * option: name of the option\r\n */\r\nunsigned int cmdSizePars(map<string ,vector<string> >& cmd, const string &option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\treturn (it != cmd.end()) ? it->second.size() : 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (int) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nint cmdGetParInt(map<string ,vector<string> >& cmd, string option, unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn atoi(it->second[param].c_str());\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (float) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nfloat cmdGetParFloat(map<string ,vector<string> >& cmd, const string &option, const unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn atof(it->second[param].c_str());\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (string) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nstring cmdGetPar(map<string ,vector<string> >& cmd, const string &option, const unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn it->second[param];\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/** ------------------------------- timing functions ------------------------------- **/\r\n\r\n/**\r\n * Class for handling timing progress information\r\n */\r\nclass Timing{\r\npublic:\r\n\t/** integer indicating progress with respect tot total **/\r\n\tint progress;\r\n\t/** total count for progress **/\r\n\tint total;\r\n\r\n\t/*\r\n\t * Default constructor for timing initializing time.\r\n\t * Automatically calls init()\r\n\t *\r\n\t * seconds: update interval in seconds\r\n\t * eraseMode: if true, outputs sends erase characters at each print command\r\n\t */\r\n\tTiming(long seconds, bool eraseMode){\r\n\t\tupdateInterval = seconds;\r\n\t\tprogress = 1;\r\n\t\ttotal = 100;\r\n\t\teraseCount=0;\r\n\t\terase = eraseMode;\r\n\t\tinit();\r\n\t}\r\n\r\n\t/*\r\n\t * Destructor\r\n\t */\r\n\t~Timing(){}\r\n\r\n\t/*\r\n\t * Initializes timing variables\r\n\t */\r\n\tvoid init(void){\r\n\t\tstart = boost::posix_time::microsec_clock::universal_time();\r\n\t\tlastPrint = start - boost::posix_time::seconds(updateInterval);\r\n\t}\r\n\r\n\t/*\r\n\t * Clears printing (for erase option only)\r\n\t */\r\n\tvoid clear(void){\r\n\t\tstring erase(eraseCount,'\\r');\r\n\t\terase.append(eraseCount,' ');\r\n\t\terase.append(eraseCount,'\\r');\r\n\t\tprintf(\"%s\",erase.c_str());\r\n\t\teraseCount = 0;\r\n\t}\r\n\r\n\t/*\r\n\t * Updates current time and returns true, if output should be printed\r\n\t */\r\n\tbool update(void){\r\n\t\tcurrent = boost::posix_time::microsec_clock::universal_time();\r\n\t\treturn ((current - lastPrint > boost::posix_time::seconds(updateInterval)) || (progress == total));\r\n\t}\r\n\r\n\t/*\r\n\t * Prints timing object to STDOUT\r\n\t */\r\n\tvoid print(void){\r\n\t\tlastPrint = current;\r\n\t\tfloat percent = 100.f * progress / total;\r\n\t\tboost::posix_time::time_duration passed = (current - start);\r\n\t\tboost::posix_time::time_duration togo = passed * (total - progress) / max(1,progress);\r\n\t\tif (erase) {\r\n\t\t\tstring erase(eraseCount,'\\r');\r\n\t\t\tprintf(\"%s\",erase.c_str());\r\n\t\t\tint newEraseCount = (progress != total) ? printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03i Remaining ca. %i:%02i:%02i.%03i)\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000),togo.hours(),togo.minutes(),togo.seconds(),(int)(togo.total_milliseconds() % 1000)) : printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03d)\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000));\r\n\t\t\tif (newEraseCount < eraseCount) {\r\n\t\t\t\tstring erase(newEraseCount-eraseCount,' ');\r\n\t\t\t\terase.append(newEraseCount-eraseCount,'\\r');\r\n\t\t\t\tprintf(\"%s\",erase.c_str());\r\n\t\t\t}\r\n\t\t\teraseCount = newEraseCount;\r\n\t\t}\r\n\t\telse {\r\n\t\t\teraseCount = (progress != total) ? printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03i Remaining ca. %i:%02i:%02i.%03i)\\n\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000),togo.hours(),togo.minutes(),togo.seconds(),(int)(togo.total_milliseconds() % 1000)) : printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03d)\\n\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000));\r\n\t\t}\r\n\t}\r\nprivate:\r\n\tlong updateInterval;\r\n\tboost::posix_time::ptime start;\r\n\tboost::posix_time::ptime current;\r\n\tboost::posix_time::ptime lastPrint;\r\n\tint eraseCount;\r\n\tbool erase;\r\n};\r\n\r\n/** ------------------------------- file pattern matching functions ------------------------------- **/\r\n\r\n\r\n/*\r\n * Formats a given string, such that it can be used as a regular expression\r\n * I.e. escapes special characters and uses * and ? as wildcards\r\n *\r\n * pattern: regular expression path pattern\r\n * pos: substring starting index\r\n * n: substring size\r\n *\r\n * returning: escaped substring\r\n */\r\nstring patternSubstrRegex(string& pattern, size_t pos, size_t n){\r\n\tstring result;\r\n\tfor (size_t i=pos, e=pos+n; i < e; i++ ) {\r\n\t\tchar c = pattern[i];\r\n\t\tif ( c == '\\\\' || c == '.' || c == '+' || c == '[' || c == '{' || c == '|' || c == '(' || c == ')' || c == '^' || c == '$' || c == '}' || c == ']') {\r\n\t\t\tresult.append(1,'\\\\');\r\n\t\t\tresult.append(1,c);\r\n\t\t}\r\n\t\telse if (c == '*'){\r\n\t\t\tresult.append(\"([^/\\\\\\\\]*)\");\r\n\t\t}\r\n\t\telse if (c == '?'){\r\n\t\t\tresult.append(\"([^/\\\\\\\\])\");\r\n\t\t}\r\n\t\telse {\r\n\t\t\tresult.append(1,c);\r\n\t\t}\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n/*\r\n * Converts a regular expression path pattern into a list of files matching with this pattern by replacing wildcards\r\n * starting in position pos assuming that all prior wildcards have been resolved yielding intermediate directory path.\r\n * I.e. this function appends the files in the specified path according to yet unresolved pattern by recursive calling.\r\n *\r\n * pattern: regular expression path pattern\r\n * files: the list to which new files can be applied\r\n * pos: an index such that positions 0...pos-1 of pattern are already considered/matched yielding path\r\n * path: the current directory (or empty)\r\n */\r\nvoid patternToFiles(string& pattern, vector<string>& files, const size_t& pos, const string& path){\r\n\tsize_t first_unknown = pattern.find_first_of(\"*?\",pos); // find unknown * in pattern\r\n\tif (first_unknown != string::npos){\r\n\t\tsize_t last_dirpath = pattern.find_last_of(\"/\\\\\",first_unknown);\r\n\t\tsize_t next_dirpath = pattern.find_first_of(\"/\\\\\",first_unknown);\r\n\t\tif (next_dirpath != string::npos){\r\n\t\t\tboost::regex expr((last_dirpath != string::npos && last_dirpath > pos) ? patternSubstrRegex(pattern,last_dirpath+1,next_dirpath-last_dirpath-1) : patternSubstrRegex(pattern,pos,next_dirpath-pos));\r\n\t\t\tboost::filesystem::directory_iterator end_itr; // default construction yields past-the-end\r\n\t\t\ttry {\r\n\t\t\t\tfor ( boost::filesystem::directory_iterator itr( ((path.length() > 0) ? path + pattern[pos-1] : (last_dirpath != string::npos && last_dirpath > pos) ? \"\" : \"./\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) : \"\")); itr != end_itr; ++itr )\r\n\t\t\t\t{\r\n\t\t\t\t\tif (boost::filesystem::is_directory(itr->path())){\r\n\t\t\t\t\t\tboost::filesystem::path p = itr->path().filename();\r\n\t\t\t\t\t\tstring s =  p.string();\r\n\t\t\t\t\t\tif (boost::regex_match(s.c_str(), expr)){\r\n\t\t\t\t\t\t\tpatternToFiles(pattern,files,(int)(next_dirpath+1),((path.length() > 0) ? path + pattern[pos-1] : \"\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) + pattern[last_dirpath] : \"\") + s);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch (boost::filesystem::filesystem_error &e){}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tboost::regex expr((last_dirpath != string::npos && last_dirpath > pos) ? patternSubstrRegex(pattern,last_dirpath+1,pattern.length()-last_dirpath-1) : patternSubstrRegex(pattern,pos,pattern.length()-pos));\r\n\t\t\tboost::filesystem::directory_iterator end_itr; // default construction yields past-the-end\r\n\t\t\ttry {\r\n\t\t\t\tfor ( boost::filesystem::directory_iterator itr(((path.length() > 0) ? path +  pattern[pos-1] : (last_dirpath != string::npos && last_dirpath > pos) ? \"\" : \"./\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) : \"\")); itr != end_itr; ++itr )\r\n\t\t\t\t{\r\n\t\t\t\t\tboost::filesystem::path p = itr->path().filename();\r\n\t\t\t\t\tstring s =  p.string();\r\n\t\t\t\t\tif (boost::regex_match(s.c_str(), expr)){\r\n\t\t\t\t\t\tfiles.push_back(((path.length() > 0) ? path + pattern[pos-1] : \"\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) + pattern[last_dirpath] : \"\") + s);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch (boost::filesystem::filesystem_error &e){}\r\n\t\t}\r\n\t}\r\n\telse { // no unknown symbols\r\n\t\tboost::filesystem::path file(((path.length() > 0) ? path + \"/\" : \"\") + pattern.substr(pos,pattern.length()-pos));\r\n\t\tif (boost::filesystem::exists(file)){\r\n\t\t\tfiles.push_back(file.string());\r\n\t\t}\r\n\t}\r\n}\r\n/**\r\n * Converts a regular expression path pattern into a list of files matching with this pattern\r\n *\r\n * pattern: regular expression path pattern\r\n * files: the list to which new files can be applied\r\n */\r\nvoid patternToFiles(string& pattern, vector<string>& files){\r\n\tpatternToFiles(pattern,files,0,\"\");\r\n}\r\n\r\n/*\r\n * Renames a given filename corresponding to the actual file pattern using a renaming pattern.\r\n * Wildcards can be referred to as ?1, ?2, ... in the order they appeared in the file pattern.\r\n *\r\n * pattern: regular expression path pattern\r\n * renamePattern: renaming pattern using ?1, ?2, ... as placeholders for wildcards\r\n * infile: path of the file (matching with pattern) to be renamed\r\n * outfile: path of the renamed file\r\n * par: used parameter (default: '?')\r\n */\r\nvoid patternFileRename(string& pattern, const string& renamePattern, const string& infile, string& outfile, const char par = '?'){\r\n\tsize_t first_unknown = renamePattern.find_first_of(par,0); // find unknown ? in renamePattern\r\n\tif (first_unknown != string::npos){\r\n\t\tstring formatOut = \"\";\r\n\t\tfor (size_t i=0, e=renamePattern.length(); i < e; i++ ) {\r\n\t\t\tchar c = renamePattern[i];\r\n\t\t\tif ( c == par && i+1 < e) {\r\n\t\t\t\tc = renamePattern[i+1];\r\n\t\t\t\tif (c > '0' && c <= '9'){\r\n\t\t\t\t\tformatOut.append(1,'$');\r\n\t\t\t\t\tformatOut.append(1,c);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tformatOut.append(1,par);\r\n\t\t\t\t\tformatOut.append(1,c);\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tformatOut.append(1,c);\r\n\t\t\t}\r\n\t\t}\r\n\t\tboost::regex patternOut(patternSubstrRegex(pattern,0,pattern.length()));\r\n\t\toutfile = boost::regex_replace(infile,patternOut,formatOut,boost::match_default | boost::format_perl);\r\n\t} else {\r\n\t\toutfile = renamePattern;\r\n\t}\r\n}\r\n\r\n\r\n/**\r\n * First filter ist square with width wl*2+1, for the other filter horizontal\r\n * wavelength increase by one octave for each filter. \r\n * A total of 8 filters are generated, 3 octaves from base with real and\r\n * imaginary parts of the complex gabor wavelet as separate filter.\r\n *\r\n * base_wavelength:       Is the base wavelength of the underlying cosine/sine.\r\n * border_gauss_residual: Adjust gauss sigma such that this percentage of\r\n *                        central energy is left at the border.\r\n */\r\nvoid generateFilterbank( vector<Mat> &filterbank, const int &base_wavelength, const float &border_gauss_residual, int max_octave=3){\r\n    float amp = -1*M_PI;\r\n    float borderfactor = sqrtf(amp/logf(border_gauss_residual));\r\n    int hr = FILTER_HEIGHT; // height radius and filter height\r\n    int h = 2*hr+1;\r\n    float alpha = hr*borderfactor;\r\n\r\n    for( int octave =0, wavelength = base_wavelength; octave <= max_octave; wavelength*=2, octave++){\r\n        int wr = wavelength;\r\n        int w = wr*2+1;\r\n        float beta = wr*borderfactor;\r\n        cout << \"generating filter for wavelength: \"<<wavelength<<\" and size \"<<w<<\"x\"<<h ; \r\n        cout <<\" alpha: \"<<alpha<<\" beta: \"<<beta<<endl;\r\n        Mat filter_re( h,w,CV_32F), filter_im( h,w,CV_32F);\r\n        float G,F_RE,F_IM;\r\n        int xp,yp;\r\n        for( int y = 0; y < h; ++y)\r\n        for( int x = 0; x < w; ++x){\r\n            xp = x-wr; \r\n            yp = y-hr;\r\n            G = exp( amp*( powf( float(xp)/beta,2) + pow(float(yp)/alpha,2)) );\r\n            F_RE = cos( xp * 2*M_PI/wavelength );\r\n            F_IM = sin( xp * 2*M_PI/wavelength );\r\n            filter_re.at<float>(y,x) = G*F_RE;\r\n            filter_im.at<float>(y,x) = G*F_IM;\r\n        }\r\n        filter_re -= sum(filter_re)[0]/(w*h); // correct for non/zero response  of real filter\r\n        filterbank.push_back(filter_re);\r\n        filterbank.push_back(filter_im);\r\n    }\r\n}\r\n\r\n\r\n/**\r\n * Specifies which points to use for the iris code, points are taken as given each point is taken from each filter, then the next point is taken.\r\n *\r\n * This function specifies and equally spaced grid for extraction\r\n *\r\n * grid_x: number of points in x-direction to extract\r\n *\r\n * returns the number of grouped points for a single angle\r\n */\r\nvoid generateExtractsequenceGrid( vector<Point> &extractsequence, const int &base_wavelength, const int &grid_x,  const int size_x, const int size_y){\r\n    int sample_x = (grid_x >= 1) ? grid_x : size_x/base_wavelength ;\r\n    int sample_y = size_y/(FILTER_HEIGHT*2+1) ;\r\n    int dx = size_x/sample_x; // horizontal equally spaced, image is rotationally extended for filtering\r\n    float offy = FILTER_HEIGHT+0.5;\r\n    float resty= size_y - 2.*offy;\r\n    float dy = resty/(sample_y-1); // keep filter in image for vertical\r\n    if (dy!=dy || sample_y == 1) dy=0; //NaN comparissons are always false or smaple_y ==1 ,i.e., dy = inf\r\n    for( int y=0; y<sample_y; ++y)\r\n    for( int x=0; x<sample_x; ++x)\r\n        extractsequence.push_back( Point( int(dx/2. + x*dx),int(offy + y*dy)));\r\n    \r\n    cout << \"Extractsequence samples: \"<<sample_x<<\"x\"<<sample_y<<endl;\r\n}\r\n\r\n/** ------------------------------- Program ------------------------------- **/\r\n\r\n/*\r\n * Main program\r\n */\r\nint main(int argc, char *argv[])\r\n{\r\n\tint mode = MODE_HELP;\r\n\tmap<string,vector<string> > cmd;\r\n\ttry {\r\n\t\tcmdRead(cmd,argc,argv);\r\n    \tif (cmd.empty() || cmdGetOpt(cmd,\"-h\") != 0) mode = MODE_HELP;\r\n    \telse mode = MODE_MAIN;\r\n    \tif (mode == MODE_MAIN){\r\n\t\t\t// validate command line\r\n\t\t\tcmdCheckOpts(cmd,\"-i|-o|-q|-t|-wf|-ws|-wp|-pwl|-pbp|-psx|-x|-y\");\r\n\t\t\tcmdCheckOptExists(cmd,\"-i\");\r\n\t\t\tcmdCheckOptSize(cmd,\"-i\",1);\r\n\t\t\tstring inFiles = cmdGetPar(cmd,\"-i\");\r\n\t\t\tcmdCheckOptExists(cmd,\"-o\");\r\n\t\t\tcmdCheckOptSize(cmd,\"-o\",1);\r\n\t\t\tstring outFiles = cmdGetPar(cmd,\"-o\");\r\n\t\t\tstring imaskFiles, omaskFiles;\r\n\t\t\tif (cmdGetOpt(cmd,\"-m\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-m\",2);\r\n\t\t\t\timaskFiles = cmdGetPar(cmd,\"-m\", 0);\r\n\t\t\t\tomaskFiles = cmdGetPar(cmd,\"-m\", 1);\r\n\t\t\t}\r\n            /** parmeters **/\r\n            int base_wavelength = 6;\r\n\t\t\tif (cmdGetOpt(cmd,\"-pwl\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-pwl\",1);\r\n\t\t\t\tbase_wavelength = cmdGetParInt(cmd,\"-pwl\", 0);\r\n\t\t\t}\r\n            float border_gauss_residual = 0.01;\r\n\t\t\tif (cmdGetOpt(cmd,\"-pbp\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-pbp\",1);\r\n\t\t\t\tborder_gauss_residual = cmdGetParFloat(cmd,\"-pbp\", 0);\r\n                if( border_gauss_residual <= 0 || border_gauss_residual >= 1){\r\n                    cout << \"WARNING: Border power does not make much sense, reverting to 0.01\"<<endl;\r\n                    border_gauss_residual = 0.01;\r\n                }\r\n\t\t\t}\r\n            int grid_x=256;\r\n\t\t\tif (cmdGetOpt(cmd,\"-psx\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-psx\",1);\r\n\t\t\t\tgrid_x = cmdGetParInt(cmd,\"-psx\", 0);\r\n                if( grid_x <= 0){\r\n                    cout << \"WARNING: grid_x does not make much sense, setting to sampling with 50% base filter overlap\" << endl;\r\n                    grid_x = -1;\r\n                }\r\n\t\t\t}\r\n            cout <<\" grid_x from parameters\" << grid_x << endl;\r\n            int size_x=512;\r\n\t\t\tif (cmdGetOpt(cmd,\"-x\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-x\",1);\r\n\t\t\t\tsize_x = cmdGetParInt(cmd,\"-x\", 0);\r\n\t\t\t}\r\n            int size_y=64;\r\n\t\t\tif (cmdGetOpt(cmd,\"-y\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-y\",1);\r\n\t\t\t\tsize_y = cmdGetParInt(cmd,\"-y\", 0);\r\n\t\t\t}\r\n            FILTER_HEIGHT=(size_y-1)/2 ;\r\n            /** options **/\r\n\t\t\tbool quiet = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-q\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-q\",0);\r\n\t\t\t\tquiet = true;\r\n\t\t\t}\r\n\t\t\tbool time = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-t\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-t\",0);\r\n\t\t\t\ttime = true;\r\n\t\t\t}\r\n\t\t\tbool write_filterbank = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-wf\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-wf\",0);\r\n\t\t\t\twrite_filterbank = true;\r\n\t\t\t}\r\n\t\t\tbool write_samples = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-ws\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-ws\",0);\r\n\t\t\t\twrite_samples = true;\r\n\t\t\t}\r\n\t\t\tbool write_points = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-wp\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-wp\",0);\r\n\t\t\t\twrite_points = true;\r\n\t\t\t}\r\n\t\t\t// starting routine\r\n\t\t\tTiming timing(1,quiet);\r\n\t\t\tvector<string> files;\r\n\t\t\tpatternToFiles(inFiles,files);\r\n\t\t\tCV_Assert(files.size() > 0);\r\n\t\t\ttiming.total = files.size();\r\n            vector<Mat> filterbank;\r\n            generateFilterbank( filterbank, base_wavelength, border_gauss_residual);\r\n            if( write_filterbank) writeFilterbank(filterbank);\r\n            vector<Point> extractsequence;\r\n            generateExtractsequenceGrid( extractsequence, base_wavelength, grid_x,  size_x, size_y);\r\n\t\t\tMat code (1,extractsequence.size()*filterbank.size()/8,CV_8UC1);\r\n            cout << \"Code size (bytes): \"<< code.size()<<endl;\r\n\t\t\tMat codeMask(1,extractsequence.size()*filterbank.size()/8,CV_8UC1);\r\n\t\t\tfor (vector<string>::iterator inFile = files.begin(); inFile != files.end(); std::advance( inFile, 1), timing.progress++){\r\n\t\t\t\tif (!quiet) printf(\"Loading texture '%s' ...\\n\", (*inFile).c_str());;\r\n\t\t\t\tMat img = imread(*inFile, CV_LOAD_IMAGE_GRAYSCALE);\r\n                if( write_points) writeExtractionsequence(img, extractsequence, write_points); // write_points is reset after one use\r\n\t\t\t\tCV_Assert(img.data != 0);\r\n\t\t\t\tCV_Assert(img.size() == Size(size_x,size_y));\r\n\t\t\t\tMat mask = Mat();\r\n\t\t\t\tif (!imaskFiles.empty()) {\r\n\t\t\t\t\tstring imaskfile;\r\n\t\t\t\t\tpatternFileRename(inFiles,imaskFiles,*inFile,imaskfile);\r\n\t\t\t\t\tif (!quiet) printf(\"Loading mask image '%s' ...\\n\", imaskfile.c_str());;\r\n\t\t\t\t\tmask = imread(imaskfile, CV_LOAD_IMAGE_GRAYSCALE);\r\n\t\t\t\t\tCV_Assert(mask.data != 0);\r\n\t\t\t\t\tCV_Assert(mask.size() == Size(size_x,size_y));\r\n\t\t\t\t}\r\n\t\t\t\tif (!quiet) printf(\"Creating iris-code ...\\n\");\r\n\r\n\t\t\t\t//featureExtract(code, codeMask, img, mask, m, n);\r\n\t\t\t\tfeatureExtract(code, codeMask, img, mask, filterbank, extractsequence, write_samples);\r\n\t\t\t\tstring outfile;\r\n\t\t\t\tpatternFileRename(inFiles,outFiles,*inFile,outfile);\r\n\t\t\t\tif (!quiet) printf(\"Storing code '%s' ...\\n\", outfile.c_str());\r\n\t\t\t\tif (!imwrite(outfile,code)) CV_Error(CV_StsError,\"Could not save image '\" + outfile + \"'\");\r\n\t\t\t\tif (!imaskFiles.empty()) {\r\n\t\t\t\t\tstring omaskfile;\r\n\t\t\t\t\tpatternFileRename(inFiles,omaskFiles,*inFile,omaskfile);\r\n\t\t\t\t\tif (!quiet) printf(\"Storing code-mask '%s' ...\\n\", omaskfile.c_str());\r\n\t\t\t\t\tif (!imwrite(omaskfile,codeMask)) CV_Error(CV_StsError,\"Could not save image '\" + omaskfile + \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tif (time && timing.update()) timing.print();\r\n\t\t\t}\r\n\t\t\tif (time && quiet) timing.clear();\r\n    \t}\r\n    \telse if (mode == MODE_HELP){\r\n\t\t\t// validate command line\r\n\t\t\tcmdCheckOpts(cmd,\"-h\");\r\n\t\t\tif (cmdGetOpt(cmd,\"-h\") != 0) cmdCheckOptSize(cmd,\"-h\",0);\r\n\t\t\t// starting routine\r\n\t\t\tprintUsage();\r\n    \t}\r\n    }\r\n\tcatch (...){\r\n\t   \tprintf(\"Exit with errors.\\n\");\r\n\t   \texit(EXIT_FAILURE);\r\n\t}\r\n    return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "76e582701447cff1905e3c4679bf0b0dab83f52d", "size": 35339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cg.cpp", "max_stars_repo_name": "ngoclamvt123/usit-v2.2.0", "max_stars_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-20T12:40:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T20:04:22.000Z", "max_issues_repo_path": "cg.cpp", "max_issues_repo_name": "ngoclamvt123/usit-v2.2.0", "max_issues_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cg.cpp", "max_forks_repo_name": "ngoclamvt123/usit-v2.2.0", "max_forks_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:51:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T02:49:06.000Z", "avg_line_length": 42.7832929782, "max_line_length": 513, "alphanum_fraction": 0.5689464897, "num_tokens": 8819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.44835382605475144}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n\n Copyright (C) 2016 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file stochasticcollocationinvcdf.hpp\n    Stochastic collocation inverse cumulative distribution function\n*/\n\n#ifndef quantlib_stochastic_collation_inv_cdf_hpp\n#define quantlib_stochastic_collation_inv_cdf_hpp\n\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/interpolations/lagrangeinterpolation.hpp>\n\n#include <boost/function.hpp>\n#include <functional>\n\nnamespace QuantLib {\n    //! Stochastic collocation inverse cumulative distribution function\n\n    /*! References:\n        L.A. Grzelak, J.A.S. Witteveen, M.Suárez-Taboada, C.W. Oosterlee,\n        The Stochastic Collocation Monte Carlo Sampler: Highly efficient\n        sampling from “expensive” distributions\n        http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2529691\n     */\n\n    class StochasticCollocationInvCDF : public std::unary_function<Real,Real> {\n      public:\n        StochasticCollocationInvCDF(\n            const boost::function<Real(Real)>& invCDF,\n            Size lagrangeOrder,\n            Real pMax = Null<Real>(),\n            Real pMin = Null<Real>());\n\n        Real value(Real x) const;\n        Real operator()(Real u) const;\n\n      private:\n        const Array x_;\n        const Volatility sigma_;\n        const Array y_;\n        const LagrangeInterpolation interpl_;\n    };\n}\n\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n\n Copyright (C) 2016 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file stochasticcollationcdf.cpp\n*/\n\n#include <ql/mathconstants.hpp>\n#include <ql/math/integrals/gaussianquadratures.hpp>\n\nnamespace QuantLib {\n\n    namespace {\n        Disposable<Array> g(Real sigma, const Array& x,\n                            const boost::function<Real(Real)>& invCDF) {\n\n            Array y(x.size());\n            const CumulativeNormalDistribution normalCDF;\n\n            for (Size i=0, n=x.size(); i < n; ++i) {\n                y[i] = invCDF(normalCDF(x[i]/sigma));\n            }\n\n            return y;\n        }\n    }\n\n    inline StochasticCollocationInvCDF::StochasticCollocationInvCDF(\n        const boost::function<Real(Real)>& invCDF,\n        Size lagrangeOrder, Real pMax, Real pMin)\n    : x_(M_SQRT2*GaussHermiteIntegration(lagrangeOrder).x()),\n      sigma_( (pMax != Null<Real>())\n              ? x_.back() / InverseCumulativeNormal()(pMax)\n              : (pMin != Null<Real>())\n                  ? x_.front() / InverseCumulativeNormal()(pMin)\n                  : 1.0),\n      y_(g(sigma_, x_, invCDF)),\n      interpl_(x_.begin(), x_.end(), y_.begin()) {\n    }\n\n    inline Real StochasticCollocationInvCDF::value(Real x) const {\n        return interpl_(x*sigma_, true);\n    }\n    inline Real StochasticCollocationInvCDF::operator()(Real u) const {\n        return value(InverseCumulativeNormal()(u));\n    }\n}\n\n\n#endif", "meta": {"hexsha": "c124324a7d9ccf6bf9017a93852381e5a35de594", "size": 4250, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/math/randomnumbers/stochasticcollocationinvcdf.hpp", "max_stars_repo_name": "markxio/Quantuccia", "max_stars_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2017-03-20T14:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T08:00:52.000Z", "max_issues_repo_path": "ql/math/randomnumbers/stochasticcollocationinvcdf.hpp", "max_issues_repo_name": "markxio/Quantuccia", "max_issues_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-04-02T14:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T05:31:12.000Z", "max_forks_repo_path": "ql/math/randomnumbers/stochasticcollocationinvcdf.hpp", "max_forks_repo_name": "markxio/Quantuccia", "max_forks_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T05:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:30:20.000Z", "avg_line_length": 32.9457364341, "max_line_length": 79, "alphanum_fraction": 0.6788235294, "num_tokens": 1004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893335913536, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4482669673018669}}
{"text": "/*\n * Author: Benoit Sklenard benoit.sklenard@cea.fr \n * \n * 3D Poisson solver.\n * Neumann and Dirichlet boundary conditions are supported and read from Kernel::Mesh class.\n *\n * Matrix operations rely on boost::numeric::ublas library. Atlas library should be more appropriate.\n *\n * Conjugate gradient is used to solve linear system Ax = b\n * Newton-Raphson method is used to get self-consistent Thomas-Fermi/Poisson solution\n *\n * Copyright 2014 IMDEA Materials Institute, Getafe, Madrid, Spain\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *    http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include <iomanip>\n\n#include \"kernel/Domain.h\" \n#include \"kernel/Mesh.h\"\n#include \"kernel/Constants.h\"\n\n#include \"io/Diagnostic.h\"\n#include \"io/ParameterManager.h\"\n#include \"io/FileParameters.h\"\n#include \"io/Parameters.h\"\n\n#include \"okmc/MobileParticleParam.h\"\n\n#include \"lkmc/LatticeDiamondParam.h\"\n\n#include \"FermiDirac.h\"\n#include <boost/lexical_cast.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/banded.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <boost/timer.hpp>\n\n#include \"Poisson.h\"\n\nusing namespace Kernel;\nusing namespace boost::numeric;\nusing namespace Electrostatics;\n\n\nPoisson::Poisson(Tcl_Interp *pTcl, Domain *pDomain) {\n\tLOWMSG(\"Loading Poisson...\");\n\n\t_pDomain            = pDomain;\n\t_pMesh              = pDomain->_pMesh;\n\t_pTcl               = pTcl;\n\n\t_T                  = 0;\n\n\t_nx                 = (_pMesh->getPeriodicX() ? _pMesh->getnx() - 1 : _pMesh->getnx());\n\t_ny                 = (_pMesh->getPeriodicY() ? _pMesh->getny() - 1 : _pMesh->getny());\n\t_nz                 = (_pMesh->getPeriodicZ() ? _pMesh->getnz() - 1 : _pMesh->getnz());\n\n\t_CG_tol             = Domains::global()->getFileParameters()->getFloat(\"MC/Electrostatic/cg.tolerance\");       // 1e-6;\n\t_CG_maxIter         = Domains::global()->getFileParameters()->getInt(\"MC/Electrostatic/cg.max.iteration\");     // 2000;\n\t_CG_verbose         = Domains::global()->getFileParameters()->getInt(\"MC/Electrostatic/cg.verbose\");\n\n\t_NR_tol             = Domains::global()->getFileParameters()->getFloat(\"MC/Electrostatic/newton.tolerance\");   // 1e-4;\n\t_NR_maxIter         = Domains::global()->getFileParameters()->getInt(\"MC/Electrostatic/newton.max.iteration\"); // 50;\n\t_NR_verbose         = Domains::global()->getFileParameters()->getInt(\"MC/Electrostatic/newton.verbose\");\n\n\t_FermiDirac         = Domains::global()->getFileParameters()->getBool(\"MC/Electrostatic/FermiDirac\");\n\t_partialIonization  = Domains::global()->getFileParameters()->getBool(\"MC/Electrostatic/partial.ionization\");\n\t_selfConsistentLKMC = Domains::global()->getFileParameters()->getBool(\"MC/Electrostatic/self.consistent.lkmc\");\n\n\t_Qe                 = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t_Qh                 = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t_Qokmc              = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t_psi                = ublas::zero_vector<double>(_nx * _ny * _nz);\n\n\t_Qlkmc_M            = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t_Qlkmc_P            = ublas::zero_vector<double>(_nx * _ny * _nz);\n\n\t_Eg                 = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t_Eg0                = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t_Nc                 = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t_Nv                 = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t_DEc                = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t_DEv                = ublas::zero_vector<double>(_nx * _ny * _nz);\n\n\tconst IO::ParameterManager      *pPM  = Domains::global()->PM();\n\tconst OKMC::MobileParticleParam *pMPP = _pDomain->_pMPPar;\n\tconst LKMC::LatticeParam             **pLP  = _pDomain->_pLaPar;\n\n\tfor(M_TYPE mt = 0; mt < pPM->getNMaterials(); ++mt)\n\t{\n\t\t// OKMC\n\t\tfor(P_TYPE pt = 0; pt < pPM->getNParticles(); ++pt)\n\t\t{\n\t\t\tif(!pPM->isParticleDefined(pt, mt))\n\t\t\t\tcontinue;\n\t\t\tif (pMPP->_mapToGrid[mt][pt])\n\t\t\t\t_Nokmc[mt][pt] = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t\t}\n\t\t// LKMC\n\t\tif (pLP[mt] != NULL && pLP[mt]->_mapToGrid)\n\t\t\t_Nlkmc[mt] = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t}\n}\n\nPoisson::~Poisson() {\n}\n\nvoid Poisson::computeElectronicParameters(double TKelvin) {\n\n\tMeshNode           ***pNode = _pMesh->getNodes();\n\tIO::FileParameters   *pPar  = Domains::global()->getFileParameters();\n\tIO::ParameterManager *pPM   = Domains::global()->PM();\n\n\tfor (Kernel::M_TYPE mt = 0; mt < Domains::global()->PM()->getNMaterials(); ++mt) {\n\t\tstd::string path = pPM->getMaterialName(mt) + \"/ElectronicStructure\";\n\n\t\tif (!pPar->specified(path)) {\n\t\t\tWARNINGMSG(path << \" does not exist!\");\n\t\t\t_matParam[mt]._Nc  = 0;\n\t\t\t_matParam[mt]._Nv  = 0;\n\t\t\t_matParam[mt]._Eg  = 0;\n\t\t\t_matParam[mt]._Eg0 = 0;\n\n\t\t\tcontinue ;\n\t\t}\n\t\tstd::string eDOSPath           = path + \"/eDOSMass\";\n\t\tstd::string hDOSPath           = path + \"/hDOSMass\";\n\t\tstd::string EgPath             = path + \"/Bandgap\";\n\t\tstd::string EcDilatationalPath = path + \"/Ec.dilatational\";\n\t\tstd::string EvDilatationalPath = path + \"/Ev.dilatational\";\n\t\tstd::string EcDeviatoricPath   = path + \"/Ec.deviatoric\";\n\t\tstd::string EvDeviatoricPath   = path + \"/Ev.deviatoric\";\n\n\t\tstd::string T  = boost::lexical_cast<std::string>(_T);\n\t\tstd::string T0 = boost::lexical_cast<std::string>(300);\n\n\t\tpPar->loadProcedure(_pTcl, eDOSPath, 1);\n\t\tpPar->loadProcedure(_pTcl, hDOSPath, 1);\n\t\tpPar->loadProcedure(_pTcl, EgPath, 1);\n\n\t\tdouble mdc = pPar->getFloatProc(_pTcl, eDOSPath, T);\n\t\tdouble mdv = pPar->getFloatProc(_pTcl, hDOSPath, T);\n\n\t\t_matParam[mt]._Nc  = 2. * pow(M0 * mdc * KB * _T / (2 * M_PI * pow(PLANCK_BAR, 2)), 3./2.);  // m3\n\t\t_matParam[mt]._Nv  = 2. * pow(M0 * mdv * KB * _T / (2 * M_PI * pow(PLANCK_BAR, 2)), 3./2.);  // m3\n\t\t_matParam[mt]._Eg  = ELECTRONVOLT_TO_HARTREE(pPar->getFloatProc(_pTcl, EgPath, T));     // Ha\n\t\t_matParam[mt]._Eg0 = ELECTRONVOLT_TO_HARTREE(pPar->getFloatProc(_pTcl, EgPath, T0));    // Ha\n\n\t\tif (pPar->specified(EcDilatationalPath) && pPar->specified(EvDilatationalPath)) {\n\t\t\t_matParam[mt]._Dc  = ublas::zero_vector<double>(3);\n\t\t\t_matParam[mt]._Dcx = ublas::zero_vector<double>(3);\n\t\t\t_matParam[mt]._Dcy = ublas::zero_vector<double>(3);\n\t\t\t_matParam[mt]._Dcz = ublas::zero_vector<double>(3);\n\t\t\t_matParam[mt]._Dv  = ublas::zero_vector<double>(2);\n\t\t\t_matParam[mt]._Dvb = ublas::zero_vector<double>(2);\n\t\t\t_matParam[mt]._Dvd = ublas::zero_vector<double>(2);\n\n\t\t\tstd::map<std::string, float> Dc  = pPar->getFloatMap(EcDilatationalPath);\n\t\t\tstd::map<std::string, float> Dcx = pPar->getFloatMap(EcDeviatoricPath + \"(1)\");\n\t\t\tstd::map<std::string, float> Dcy = pPar->getFloatMap(EcDeviatoricPath + \"(2)\");\n\t\t\tstd::map<std::string, float> Dcz = pPar->getFloatMap(EcDeviatoricPath + \"(3)\");\n\n\t\t\tstd::map<std::string, float> Dv  = pPar->getFloatMap(EvDilatationalPath);\n\t\t\tstd::map<std::string, float> Dvb = pPar->getFloatMap(EvDeviatoricPath + \"(1)\");\n\t\t\tstd::map<std::string, float> Dvd = pPar->getFloatMap(EvDeviatoricPath + \"(2)\");\n\n\t\t\tfor (unsigned i = 0; i < 3; ++i) {\n\t\t\t\t_matParam[mt]._Dc(i)  = Dc[boost::lexical_cast<std::string>(i + 1)];\n\t\t\t\t_matParam[mt]._Dcx(i) = Dcx[boost::lexical_cast<std::string>(i + 1)];\n\t\t\t\t_matParam[mt]._Dcy(i) = Dcy[boost::lexical_cast<std::string>(i + 1)];\n\t\t\t\t_matParam[mt]._Dcz(i) = Dcz[boost::lexical_cast<std::string>(i + 1)];\n\t\t\t}\n\n\t\t\tfor (unsigned i = 0; i < 2; ++i) {\n\t\t\t\t_matParam[mt]._Dv(i)  = Dv[boost::lexical_cast<std::string>(i + 1)];\n\t\t\t\t_matParam[mt]._Dvb(i) = Dvb[boost::lexical_cast<std::string>(i + 1)];\n\t\t\t\t_matParam[mt]._Dvd(i) = Dvd[boost::lexical_cast<std::string>(i + 1)];\n\t\t\t}\n\t\t\tLOWMSG(\"got stress data for \" << pPM->getMaterialName(mt));\n\t\t}\n\t}\n\n\t// initialize electronic parameters for the structure\n\tfor (unsigned ix = 0; ix < _nx; ++ix) {\n\t\tfor (unsigned iy = 0; iy < _ny; ++iy) {\n\t\t\tfor (unsigned iz = 0; iz < _nz; ++iz) {\n\t\t\t\tif (pNode[ix][iy][iz]._active) {\n\t\t\t\t\tconst unsigned idx = pNode[ix][iy][iz]._index;\n\n\t\t\t\t\t_Nc(idx)  = pNode[ix][iy][iz]._volume * 1e-27 * getNc(&pNode[ix][iy][iz]);\n\t\t\t\t\t_Nv(idx)  = pNode[ix][iy][iz]._volume * 1e-27 * getNv(&pNode[ix][iy][iz]);\n\n\t\t\t\t\t_Eg(idx)  = getEg(&pNode[ix][iy][iz]);\n\t\t\t\t\t_Eg0(idx) = getEg0(&pNode[ix][iy][iz]);\n\n\t\t\t\t\tif (_Eg(pNode[ix][iy][iz]._index) <= 0. || _Eg0(pNode[ix][iy][iz]._index) <= 0.)\n\t\t\t\t\t\tERRORMSG(\"Poisson::computeElectronicParameters: band gap cannot be zero!\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Poisson::setFirstGuess() {\n\tMeshNode ***pNode                     = _pMesh->getNodes();\n\tconst IO::ParameterManager *pPM       = Domains::global()->PM();\n\tconst OKMC::MobileParticleParam *pMPP = _pDomain->_pMPPar;\n\n\tfor (size_t ix = 0; ix < _nx; ++ix) {\n\t\tfor (size_t iy = 0; iy < _ny; ++iy) {\n\t\t\tfor (size_t iz = 0; iz < _nz; ++iz) {\n\t\t\t\tif (pNode[ix][iy][iz]._active) {\n\t\t\t\t\tconst unsigned i = pNode[ix][iy][iz]._index;\n\t\t\t\t\tdouble n = 0;\n\n\t\t\t\t\tfor(M_TYPE mt = 0; mt < pPM->getNMaterials(); ++mt)\n\t\t\t\t\t\tfor(P_TYPE pt = pPM->getNFamilies(); pt < pPM->getNParticles(); ++pt)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tP_TYPE fam = pPM->getFamily(pt);\n\t\t\t\t\t\t\tP_POS  pos = pPM->getPPos(pt);\n\t\t\t\t\t\t\tif(fam == V_TYPE || fam == pPM->getMaterial(mt)._pt[0] || fam == pPM->getMaterial(mt)._pt[1] ||\n\t\t\t\t\t\t\t\tpos == POS_I || pos == POS_V)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tif(!_Nokmc[mt][pt].empty() && _Nokmc[mt][pt](i) > 0)\n\t\t\t\t\t\t\t\tn += pMPP->_state2charge[mt][pt][0]; //impurities and dopants only have state 0!\n\t\t\t\t\t\t}\n\n\t\t\t\t\tif (n > 0.)\n\t\t\t\t\t\t_psi(i) = 0.5 * getEg(&pNode[ix][iy][iz]);\n\t\t\t\t\telse if (n < 0.)\n\t\t\t\t\t\t_psi(i) = - 0.5 * getEg(&pNode[ix][iy][iz]);\n\t\t\t\t\telse\n\t\t\t\t\t\t_psi(pNode[ix][iy][iz]._index) = 0;\n\n\t\t\t\t\tfor(M_TYPE mt = 0; mt < pPM->getNMaterials(); ++mt) {\n\t\t\t\t\t\tif (!_Nlkmc[mt].empty() && _Nlkmc[mt](i) > 0) {\n\t\t\t\t\t\t\t_psi(i) = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Poisson::setT(double T)\n{\n\tif (_T != T)\n\t{\n\t\t_T = T;\n\t\tMEDMSG(\"Building vector for OKMC particles...\");\n\t\tbuildOKMCVector();\n\n\t\tif (_selfConsistentLKMC)\n\t\t\tbuildLKMCVector();\n\n\t\tMEDMSG(\"Building Laplacian matrix...\");\n\t\tbuildLaplacianMatrix();\n\t\tcomputeElectronicParameters(T);\n\t\tsetFirstGuess();\n\t}\n}\n\nbool Poisson::compute() {\n\tMEDMSG(\"Building vector for OKMC particles...\");\n\tbuildOKMCVector();\n\n\tif (_selfConsistentLKMC)\n\t\tbuildLKMCVector();\n\n\tMEDMSG(\"Solving non-linear Poisson equation...\");\n\n\tif (! NewtonRaphson())\n\t\tERRORMSG(\"Poisson::NewtonRaphson did not converged!\");\n\n\tmap2Nodes();\n\tmap2Elements();\n\n\treturn true;\n}\n\ndouble Poisson::getDEc(MeshNode *pNode) {\n\tconst double kT = KB / Q * _T;\n\n\tstd::set<MeshElement *> s;\n\n\tdouble DEc = 0;\n\t_pMesh->getElementsFromNode(pNode, s);\n\n\tfor (std::set<MeshElement *>::const_iterator it = s.begin(); it != s.end(); ++it) {\n\t\tconst M_TYPE mt = (*it)->getMaterial();\n\n\t\t// ublas::vector<double> DEci = ublas::zero_vector<double>(3);\n\n\t\tdouble tmp = 0;\n\t\tfor (unsigned i = 0; i < 3; ++i) {\n\t\t\t// const ublas::vector<double> E = (*it)->strain();\n\t\t\tublas::vector<double> E = ublas::zero_vector<double>(3);\n\n\t\t\tconst double Dc         = (_matParam[mt]._Dc.size()  > 0 ? _matParam[mt]._Dc(i)  : 0);\n\t\t\tconst double Dcx        = (_matParam[mt]._Dcx.size() > 0 ? _matParam[mt]._Dcx(i) : 0);\n\t\t\tconst double Dcy        = (_matParam[mt]._Dcy.size() > 0 ? _matParam[mt]._Dcy(i) : 0);\n\t\t\tconst double Dcz        = (_matParam[mt]._Dcz.size() > 0 ? _matParam[mt]._Dcz(i) : 0);\n\n\t\t\ttmp += exp(- (Dc * (E(0) + E(1) + E(2)) + Dcx * E(0) + Dcy * E(1) + Dcz * E(2))/ kT);\n\t\t}\n\n\t\tDEc += ELECTRONVOLT_TO_HARTREE(-kT * log(1./3. * tmp));\n\n\t\tif (Domains::global()->PM()->getMaterialName(mt) == \"Silicon\")\n\t\t\tLOWMSG(\"DEc:\" << DEc / static_cast<double>(s.size()));\n\t}\n\n\treturn (DEc / static_cast<double>(s.size()));\n}\n\ndouble Poisson::getNc(MeshNode *pNode) {\n\tstd::set<MeshElement *> s;\n\tdouble Nc = 0;\n\t_pMesh->getElementsFromNode(pNode, s);\n\n\tfor (std::set<MeshElement *>::const_iterator it = s.begin(); it != s.end(); ++it)\n\t\tNc += _matParam[(*it)->getMaterial()]._Nc;\n\n\treturn (Nc / static_cast<double>(s.size()));\n}\n\ndouble Poisson::getNv(MeshNode *pNode) {\n\tstd::set<MeshElement *> s;\n\tdouble Nv = 0;\n\t_pMesh->getElementsFromNode(pNode, s);\n\n\tfor (std::set<MeshElement *>::const_iterator it = s.begin(); it != s.end(); ++it)\n\t\tNv += _matParam[(*it)->getMaterial()]._Nv;\n\n\treturn (Nv / static_cast<double>(s.size()));\n}\n\ndouble Poisson::getEg(MeshNode *pNode) {\n\tstd::set<MeshElement *> s;\n\tdouble Eg = 0;\n\t_pMesh->getElementsFromNode(pNode, s);\n\n\tfor (std::set<MeshElement *>::const_iterator it = s.begin(); it != s.end(); ++it)\n\t\tEg += _matParam[(*it)->getMaterial()]._Eg;\n\n\treturn (Eg / static_cast<double>(s.size()));\n}\n\ndouble Poisson::getEg0(MeshNode *pNode) {\n\tstd::set<MeshElement *> s;\n\tdouble Eg0 = 0;\n\t_pMesh->getElementsFromNode(pNode, s);\n\n\tfor (std::set<MeshElement *>::const_iterator it = s.begin(); it != s.end(); ++it)\n\t\tEg0 += _matParam[(*it)->getMaterial()]._Eg0;\n\n\treturn (Eg0 / static_cast<double>(s.size()));\n}\n\n// OBSOLETE METHOD\n// Do NOT call!\n/* double Poisson::getLA(MeshNode *pNode) {\n\tdouble w = 0.;\n\n\tfor (std::map<LKMC::LatticeAtom *, double>::iterator it = pNode->_mLA.begin(); it !=pNode->_mLA.end(); ++it)\n\t\tw += it->second;\n\n\treturn w;\n} */\n\nvoid Poisson::map2Nodes() {\n\tMeshNode ***pNode = _pMesh->getNodes();\n\n\tfor (unsigned ix = 0; ix < _nx; ++ix) {\n\t\tfor (unsigned iy = 0; iy < _ny; ++iy) {\n\t\t\tfor (unsigned iz = 0; iz < _nz; ++iz) {\n\t\t\t\tif (pNode[ix][iy][iz]._active) {\n\t\t\t\t\tpNode[ix][iy][iz]._V        = HARTREE_TO_ELECTRONVOLT(_psi(pNode[ix][iy][iz]._index));\n\t\t\t\t\tpNode[ix][iy][iz]._Eg       = HARTREE_TO_ELECTRONVOLT(_Eg(pNode[ix][iy][iz]._index));\n\t\t\t\t\tpNode[ix][iy][iz]._Eg0      = HARTREE_TO_ELECTRONVOLT(_Eg0(pNode[ix][iy][iz]._index));\n\t\t\t\t\tpNode[ix][iy][iz]._Ec       = HARTREE_TO_ELECTRONVOLT(0.5 * getEg(&pNode[ix][iy][iz]) - _psi(pNode[ix][iy][iz]._index));\n\t\t\t\t\tpNode[ix][iy][iz]._Ev       = HARTREE_TO_ELECTRONVOLT(- 0.5 * getEg(&pNode[ix][iy][iz]) - _psi(pNode[ix][iy][iz]._index));\n\t\t\t\t\tpNode[ix][iy][iz]._eDensity = _Qe(pNode[ix][iy][iz]._index) / (pNode[ix][iy][iz]._volume * 1e-21);\n\t\t\t\t\tpNode[ix][iy][iz]._hDensity = _Qh(pNode[ix][iy][iz]._index) / (pNode[ix][iy][iz]._volume * 1e-21);\n\n\t\t\t\t\t// pNode[ix][iy][iz]._N_okmc   = _Qokmc(pNode[ix][iy][iz]._index) / (pNode[ix][iy][iz]._volume * 1e-27); // FIXME\n\n\t\t\t\t\tif (ix > 0 && ix < (_nx - 1) && iy > 0 && iy < (_ny - 1) && iz > 0 && iz < (_nz - 1)) {\n\t\t\t\t\t\tif (pNode[ix-1][iy][iz]._index < 0)\n\t\t\t\t\t\t\tcontinue ;\n\t\t\t\t\t\tif (pNode[ix+1][iy][iz]._index < 0)\n\t\t\t\t\t\t\tcontinue ;\n\t\t\t\t\t\tif (pNode[ix][iy-1][iz]._index < 0)\n\t\t\t\t\t\t\tcontinue ;\n\t\t\t\t\t\tif (pNode[ix][iy+1][iz]._index < 0)\n\t\t\t\t\t\t\tcontinue ;\n\t\t\t\t\t\tif (pNode[ix][iy][iz-1]._index < 0)\n\t\t\t\t\t\t\tcontinue ;\n\t\t\t\t\t\tif (pNode[ix][iy][iz+1]._index < 0)\n\t\t\t\t\t\t\tcontinue ;\n\n\t\t\t\t\t\tconst double dxp = pNode[ix+1][iy][iz]._coord._x - pNode[ix][iy][iz]._coord._x;\n\t\t\t\t\t\tconst double dxm = pNode[ix][iy][iz]._coord._x - pNode[ix-1][iy][iz]._coord._x;\n\t\t\t\t\t\tconst double dyp = pNode[ix][iy+1][iz]._coord._y - pNode[ix][iy][iz]._coord._y;\n\t\t\t\t\t\tconst double dym = pNode[ix][iy][iz]._coord._y - pNode[ix][iy-1][iz]._coord._y;\n\t\t\t\t\t\tconst double dzp = pNode[ix][iy][iz+1]._coord._z - pNode[ix][iy][iz]._coord._z;\n\t\t\t\t\t\tconst double dzm = pNode[ix][iy][iz]._coord._z - pNode[ix][iy][iz-1]._coord._z;\n\n\t\t\t\t\t\tconst double Vxp = HARTREE_TO_ELECTRONVOLT(_psi(pNode[ix+1][iy][iz]._index));\n\t\t\t\t\t\tconst double Vxm = HARTREE_TO_ELECTRONVOLT(_psi(pNode[ix-1][iy][iz]._index));\n\t\t\t\t\t\tconst double Vyp = HARTREE_TO_ELECTRONVOLT(_psi(pNode[ix][iy+1][iz]._index));\n\t\t\t\t\t\tconst double Vym = HARTREE_TO_ELECTRONVOLT(_psi(pNode[ix][iy-1][iz]._index));\n\t\t\t\t\t\tconst double Vzp = HARTREE_TO_ELECTRONVOLT(_psi(pNode[ix][iy][iz+1]._index));\n\t\t\t\t\t\tconst double Vzm = HARTREE_TO_ELECTRONVOLT(_psi(pNode[ix][iy][iz-1]._index));\n\n\t\t\t\t\t\tconst double V   = HARTREE_TO_ELECTRONVOLT(_psi(pNode[ix][iy][iz]._index));\n\n\t\t\t\t\t\tpNode[ix][iy][iz]._E    = ublas::zero_vector<double>(3); // electric field in eV/nm\n\t\t\t\t\t\tpNode[ix][iy][iz]._E(0) = - 0.5 * ((Vxp - V) / dxp + (V  - Vxm) / dxm);\n\t\t\t\t\t\tpNode[ix][iy][iz]._E(1) = - 0.5 * ((Vyp - V) / dyp + (V  - Vym) / dym);\n\t\t\t\t\t\tpNode[ix][iy][iz]._E(2) = - 0.5 * ((Vzp - V) / dzp + (V  - Vzm) / dzm);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Poisson::map2Elements() {\n\tfor(Kernel::Mesh::iterator it = _pMesh->begin(); it != _pMesh->end(); ++it)\n\t{\n\t\tstd::set<MeshNode *> s;\n\t\tconst M_TYPE mt = it->getMaterial();\n\n\t\t_pMesh->getNodesFromElement(&(*it), s);\n\n\t\tif (s.empty())\n\t\t\tERRORMSG(\"Poisson::map2Elements: cannot find nodes of element \" << it->getIndex());\n\n\t\tdouble V  = 0;\n\t\tfor (std::set<MeshNode *>::const_iterator i = s.begin(); i != s.end(); ++i)\n\t\t\tV  += (*i)->_V;\n\n\t\tit->electrostaticPotential() = V / static_cast<double>(s.size());\n\t\tit->bandGap() = HARTREE_TO_ELECTRONVOLT(_matParam[mt]._Eg);\n\t}\n}\n\nbool Poisson::NewtonRaphson() {\n\tMeshNode ***pNode                     = _pMesh->getNodes();\n\tconst double kT                       = ELECTRONVOLT_TO_HARTREE(KB / Q * _T);\n\tconst IO::ParameterManager *pPM       = Domains::global()->PM();\n\tconst OKMC::MobileParticleParam *pMPP = _pDomain->_pMPPar;\n\tbool         ret                      = false;\n\n\tublas::vector<double> deltaPsi  = ublas::zero_vector<double>(_nx * _ny * _nz);\n\tublas::vector<double> err       = ublas::zero_vector<double>(_nx * _ny * _nz);\n\tublas::vector<double> totCharge = ublas::zero_vector<double>(_nx * _ny * _nz);\n\n\t// ublas::vector<double> Qtmp      = ublas::zero_vector<double>(_nx * _ny * _nz);\n\n\tboost::timer t;\n\tt.restart();\n\n\tfor (size_t it = 0; it < _NR_maxIter; ++it) {\n\t\tublas::compressed_matrix<double> J = _laplacian;\n\n\t\tfor (size_t ix = 0; ix < _nx; ++ix) {\n\t\t\tfor (size_t iy = 0; iy < _ny; ++iy) {\n\t\t\t\tfor (size_t iz = 0; iz < _nz; ++iz) {\n\t\t\t\t\tif (pNode[ix][iy][iz]._active) {\n\t\t\t\t\t\tconst size_t i   = pNode[ix][iy][iz]._index;\n\n\t\t\t\t\t\tdouble dQe        = 0.;\n\t\t\t\t\t\tdouble dQh        = 0.;\n\t\t\t\t\t\tdouble dQokmc     = 0;\n\t\t\t\t\t\tdouble dQlkmc_M   = 0.;\n\t\t\t\t\t\tdouble dQlkmc_P   = 0.;\n\n\t\t\t\t\t\tconst double Ef = 0;\n\t\t\t\t\t\tconst double CBM = 0.5 * _Eg(i) - _psi(i);\n\t\t\t\t\t\tconst double VBM = - 0.5 * _Eg(i) - _psi(i);\n\n\t\t\t\t\t\tconst double EfEc = Ef - CBM;\n\t\t\t\t\t\tconst double EvEf = VBM - Ef;\n\t\t\t\t\t\t// const double EfEc = _psi(i) - 0.5 * _Eg(i);\n\t\t\t\t\t\t// const double EvEf = - _psi(i) - 0.5 * _Eg(i);\n\n\t\t\t\t\t\t_Qokmc(i)   = 0;\n\t\t\t\t\t\t_Qlkmc_M(i) = 0.;\n\t\t\t\t\t\t_Qlkmc_P(i) = 0.;\n\n\t\t\t\t\t\tif (_FermiDirac) {\n\t\t\t\t\t\t\tdQe    = _Nc(i) / kT * FermiDirac::mhalf(EfEc / kT);\n\t\t\t\t\t\t\tdQh    = - _Nv(i) / kT * FermiDirac::mhalf(EvEf / kT);\n\t\t\t\t\t\t\t_Qe(i) = _Nc(i) * FermiDirac::phalf(EfEc / kT);\n\t\t\t\t\t\t\t_Qh(i) = _Nv(i) * FermiDirac::phalf(EvEf / kT);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tdQe    = _Nc(i) / kT * exp(EfEc / kT);\n\t\t\t\t\t\t\tdQh    = - _Nv(i) / kT * exp(EvEf / kT);\n\t\t\t\t\t\t\t_Qe(i) = _Nc(i) * exp(EfEc / kT);\n\t\t\t\t\t\t\t_Qh(i) = _Nv(i) * exp(EvEf / kT);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor(M_TYPE mt = 0; mt < pPM->getNMaterials(); ++mt)\n\t\t\t\t\t\t{// OKMC\n\t\t\t\t\t\t\tfor(P_TYPE pt = pPM->getNFamilies(); pt < pPM->getNParticles(); ++pt)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tP_TYPE fam = pPM->getFamily(pt);\n\t\t\t\t\t\t\t\tP_POS  pos = pPM->getPPos(pt);\n\t\t\t\t\t\t\t\tif(fam == V_TYPE || fam == pPM->getMaterial(mt)._pt[0] || fam == pPM->getMaterial(mt)._pt[1] ||\n\t\t\t\t\t\t\t\t\t\tpos == POS_I || pos == POS_V)\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\tif (! _Nokmc[mt][pt].empty() && _Nokmc[mt][pt](i) > 0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (pMPP->_state2charge[mt][pt][0] == 1) { //DONOR\n\t\t\t\t\t\t\t\t\t\tif (_partialIonization) {\n\t\t\t\t\t\t\t\t\t\t\t// const double E = _psi(i) - 0.5 * _Eg(i) + _Eg(i) / _Eg0(i) * ELECTRONVOLT_TO_HARTREE(pMPP->_stateEnergy[mt][pt]);\n\t\t\t\t\t\t\t\t\t\t\tconst double E = Ef - (CBM - _Eg(i) / _Eg0(i) * ELECTRONVOLT_TO_HARTREE(pMPP->_stateEnergy[mt][pt]));\n\t\t\t\t\t\t\t\t\t\t\t_Qokmc(i) += _Nokmc[mt][pt](i) / (1. + pMPP->_stateDegeneracy[mt][pt] * exp(E / kT));\n\t\t\t\t\t\t\t\t\t\t\tdQokmc    += - _Nokmc[mt][pt](i) * pMPP->_stateDegeneracy[mt][pt] / kT * exp(E / kT) / pow(1. + pMPP->_stateDegeneracy[mt][pt] * exp(E / kT), 2);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\t_Qokmc(i) += _Nokmc[mt][pt](i);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if (pMPP->_state2charge[mt][pt][0] == -1) { //ACCEPTOR\n\t\t\t\t\t\t\t\t\t\tif (_partialIonization) {\n\t\t\t\t\t\t\t\t\t\t\t// const double E = - _psi(i) - 0.5 * _Eg(i) + _Eg(i) / _Eg0(i) * ELECTRONVOLT_TO_HARTREE(pMPP->_stateEnergy[mt][pt]);\n\t\t\t\t\t\t\t\t\t\t\tconst double E = (VBM + _Eg(i) / _Eg0(i) * ELECTRONVOLT_TO_HARTREE(pMPP->_stateEnergy[mt][pt])) - Ef;\n\t\t\t\t\t\t\t\t\t\t\t_Qokmc(i) -= _Nokmc[mt][pt](i) / (1. + pMPP->_stateDegeneracy[mt][pt] * exp(E / kT));\n\t\t\t\t\t\t\t\t\t\t\tdQokmc    -= _Nokmc[mt][pt](i) * pMPP->_stateDegeneracy[mt][pt] / kT * exp(E / kT) / pow(1. + pMPP->_stateDegeneracy[mt][pt] * exp(E / kT), 2);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\t_Qokmc(i) -= _Nokmc[mt][pt](i);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// LKMC\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\tif (_selfConsistentGFLS && _Nlkmc[mt].empty() == false && _Nlkmc[mt](i) > 0.) {\n\t\t\t\t\t\t\t\tif (_pDomain->_pLat[mt]->getType() != LKMC::LatticeParam::DIAMOND_1) {\n\t\t\t\t\t\t\t\t\tERRORMSG(\"Poisson::NewtonRaphson does not support \" << pPM->getMaterialName(mt) << \" lattice.\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tLKMC::LatticeDiamondParam *pLDP = static_cast<LKMC::LatticeDiamondParam *>(_pDomain->_pLaPar[mt]);\n\n\t\t\t\t\t\t\t\tconst double E_lkmc_M = _psi(i) - 0.5 * _Eg(i) + _Eg(i) / _Eg0(i) * ELECTRONVOLT_TO_HARTREE(pLDP->_E_M0);   // Ef - E(0,-)\n\t\t\t\t\t\t\t\tconst double E_lkmc_P = - _psi(i) - 0.5 * _Eg(i) + _Eg(i) / _Eg0(i) * ELECTRONVOLT_TO_HARTREE(pLDP->_E_P0); // E(+,0) - Ef\n\n\t\t\t\t\t\t\t\tconst double g_M = pLDP->_g_M;\n\t\t\t\t\t\t\t\tconst double g_0 = pLDP->_g_0;\n\t\t\t\t\t\t\t\tconst double g_P = pLDP->_g_P;\n\n\t\t\t\t\t\t\t\tdQlkmc_M    +=   _Nc(i) / _Nlkmc[mt](i) * 1. / kT * g_M / g_0 * exp(E_lkmc_M / kT);\n\t\t\t\t\t\t\t\tdQlkmc_P    += - _Nv(i) / _Nlkmc[mt](i) * 1. / kT * g_P / g_0 * exp(E_lkmc_P / kT);\n\t\t\t\t\t\t\t\t_Qlkmc_M(i) += _Nc(i) / _Nlkmc[mt](i) * g_M / g_0 * exp(E_lkmc_M / kT);\n\t\t\t\t\t\t\t\t_Qlkmc_P(i) += _Nv(i) / _Nlkmc[mt](i) * g_P / g_0 * exp(E_lkmc_P / kT);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (_selfConsistentGFLS2 && _Nlkmc[mt].empty() == false && _Nlkmc[mt](i) > 0.) {\n\t\t\t\t\t\t\t\tif (_pDomain->_pLat[mt]->getType() != LKMC::LatticeParam::DIAMOND_1) {\n\t\t\t\t\t\t\t\t\tERRORMSG(\"Poisson::NewtonRaphson does not support \" << pPM->getMaterialName(mt) << \" lattice.\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tLKMC::LatticeDiamondParam *pLDP = static_cast<LKMC::LatticeDiamondParam *>(_pDomain->_pLaPar[mt]);\n\n\t\t\t\t\t\t\t\t// const double Ef  = 0;\n\t\t\t\t\t\t\t\t// const double VBM = - V - 0.5 * Eg;\n\n\t\t\t\t\t\t\t    // Note: defect level scales with bandgap\n\t\t\t\t\t\t\t\tconst double E_lkmc_M    = Ef - (VBM + _Eg(i) / _Eg0(i) * ELECTRONVOLT_TO_HARTREE(pLDP->_E_M0));      // Ef  - E(0,-)\n\t\t\t\t\t\t\t\tconst double E_lkmc_P    = (VBM + _Eg(i) / _Eg0(i) * ELECTRONVOLT_TO_HARTREE(pLDP->_E_P0)) - Ef; // Ef  - E(0,-)\n\n\t\t\t\t\t\t\t\tconst double g_M = pLDP->_g_M;\n\t\t\t\t\t\t\t\tconst double g_0 = pLDP->_g_0;\n\t\t\t\t\t\t\t\tconst double g_P = pLDP->_g_P;\n\n\t\t\t\t\t\t\t\tconst double den_M = 1. + (g_0 / g_M) * exp( - E_lkmc_M / kT) + (g_P / g_M) * exp((E_lkmc_P - E_lkmc_M) / kT);\n\t\t\t\t\t\t\t\tconst double den_P = 1. + (g_0 / g_P) * exp( - E_lkmc_P / kT) + (g_M / g_P) * exp((E_lkmc_M - E_lkmc_P) / kT);\n\n\t\t\t\t\t\t\t\tdQlkmc_M    +=   _Nlkmc[mt](i) * (1. / kT * (g_0 / g_M) * exp( - E_lkmc_M / kT) + 2. / kT * (g_P / g_M) * exp((E_lkmc_P - E_lkmc_M)/ kT)) / (den_M * den_M);\n\t\t\t\t\t\t\t\tdQlkmc_P    += - _Nlkmc[mt](i) * (1. / kT * (g_0 / g_P) * exp( - E_lkmc_P / kT) + 2. / kT * (g_M / g_P) * exp((E_lkmc_M - E_lkmc_P)/ kT)) / (den_P * den_P);\n\t\t\t\t\t\t\t\t_Qlkmc_M(i) += _Nlkmc[mt](i) / den_M;\n\t\t\t\t\t\t\t\t_Qlkmc_P(i) += _Nlkmc[mt](i) / den_P;\n\t\t\t\t\t\t\t}*/\n\n\t\t\t\t\t\t\tif (_selfConsistentLKMC && _Nlkmc[mt].empty() == false && _Nlkmc[mt](i) > 0.) {\n\t\t\t\t\t\t\t\tif (_pDomain->_pLat[mt]->getType() != LKMC::LatticeParam::DIAMOND) {\n\t\t\t\t\t\t\t\t\tERRORMSG(\"Poisson::NewtonRaphson does not support \" << pPM->getMaterialName(mt) << \" lattice.\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst LKMC::LatticeDiamondParam *pLDP = static_cast<const LKMC::LatticeDiamondParam *>(_pDomain->_pLaPar[mt]);\n\n\t\t\t\t\t\t\t\tconst double E_lkmc_M = _psi(i) - 0.5 * _Eg(i) + _Eg(i) / _Eg0(i) * ELECTRONVOLT_TO_HARTREE(pLDP->_E_M0);   // Ef - E(0,-)\n\t\t\t\t\t\t\t\tconst double E_lkmc_P = - _psi(i) - 0.5 * _Eg(i) + _Eg(i) / _Eg0(i) * ELECTRONVOLT_TO_HARTREE(pLDP->_E_P0); // E(+,0) - Ef\n\n\t\t\t\t\t\t\t\tconst double g_M = pLDP->_g_M;\n\t\t\t\t\t\t\t\tconst double g_0 = pLDP->_g_0;\n\t\t\t\t\t\t\t\tconst double g_P = pLDP->_g_P;\n\n\t\t\t\t\t\t\t\tconst double den_M = 1. + (g_0 / g_M) * exp( - E_lkmc_M / kT) + (g_P / g_M) * exp((E_lkmc_P - E_lkmc_M) / kT);\n\t\t\t\t\t\t\t\tconst double den_P = 1. + (g_0 / g_P) * exp( - E_lkmc_P / kT) + (g_M / g_P) * exp((E_lkmc_M - E_lkmc_P) / kT);\n\n\t\t\t\t\t\t\t\tdQlkmc_M    +=   _Nlkmc[mt](i) * (1. / kT * (g_0 / g_M) * exp( - E_lkmc_M / kT) + 2. / kT * (g_P / g_M) * exp((E_lkmc_P - E_lkmc_M)/ kT)) / (den_M * den_M);\n\t\t\t\t\t\t\t\tdQlkmc_P    += - _Nlkmc[mt](i) * (1. / kT * (g_0 / g_P) * exp( - E_lkmc_P / kT) + 2. / kT * (g_M / g_P) * exp((E_lkmc_M - E_lkmc_P)/ kT)) / (den_P * den_P);\n\t\t\t\t\t\t\t\t_Qlkmc_M(i) += _Nlkmc[mt](i) / den_M;\n\t\t\t\t\t\t\t\t_Qlkmc_P(i) += _Nlkmc[mt](i) / den_P;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tJ(i,i) -= 4. * M_PI * (dQh - dQe + dQokmc + dQlkmc_P - dQlkmc_M);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tublas::noalias(totCharge) = _Qh - _Qe + _Qokmc + _Qeff + _Qlkmc_P - _Qlkmc_M;\n\t\tublas::noalias(err)       = - ublas::prod(_laplacian, _psi) + 4 * M_PI * totCharge;\n\n\t\tif (ublas::norm_2(err) < _NR_tol) {\n\t\t\tret = true;\n\t\t\tif (_NR_verbose > 0)\n\t\t\t\tLOWMSG(\"Poisson::NewtonRaphson converged in \" << it << \" iterations (\" << t.elapsed() << \" s)\");\n\n\t\t\tbreak ;\n\t\t}\n\t\tif (_NR_verbose > 1)\n\t\t\tLOWMSG(\"Poisson::NewtonRaphson iteration \" << it << \" error= \" << ublas::norm_2(err) << \" (\" << t.elapsed() << \" s)\");\n\n\t\tdeltaPsi = ublas::zero_vector<double>(_nx * _ny * _nz);\n\n\t\tif (! ConjugateGradient(J, deltaPsi, err))\n\t\t\tERRORMSG(\"Poisson::CG did not converged\");\n\n\t\t_psi += deltaPsi;\n\t}\n\n\treturn ret;\n}\n\nbool Poisson::ConjugateGradient(const ublas::compressed_matrix<double> &A, ublas::vector<double> &x, const ublas::vector<double> &b) {\n\tboost::timer t;\n\tt.restart();\n\n\tublas::vector<double> a;\n\n\tbool                  ret = false;\n\tublas::vector<double> p   = ublas::zero_vector<double>(x.size());\n\tublas::vector<double> r   = ublas::zero_vector<double>(x.size());\n\n\n\tublas::noalias(r) = b - ublas::prod(A, x);\n\tublas::noalias(p) = r;\n\n\tfor (size_t it = 0; it < _CG_maxIter; ++it) {\n\t\tif (ublas::norm_2(r) < _CG_tol) {\n\n\t\t\tif (_CG_verbose > 0)\n\t\t\t\tLOWMSG(\"Poisson::CG solved in \" << it << \" iterations (\" << t.elapsed() << \" s)\");\n\n\t\t\tret = true;\n\t\t\tbreak ;\n\t\t}\n\t\tif (_CG_verbose > 1) {\n\t\t\tLOWMSG(\"Poisson::CG iteration \" << it << \" error= \" << ublas::norm_2(r) << \" (\" << t.elapsed() << \" s)\");\n\t\t}\n\n\t\ta                 = ublas::zero_vector<double>(x.size());\n\t\tublas::noalias(a) = ublas::prod(A, p);\n\n\t\tdouble  lambda = ublas::inner_prod(r, p) / ublas::inner_prod(a, p);\n\n\t\tx += lambda * p;\n\t\tr -= lambda * a;\n\n\t\tp = r - (ublas::inner_prod(r, a) / ublas::inner_prod(a, p)) * p;\n\t}\n\n\treturn (ret);\n}\n\n// This method is for test purpose only\nvoid Poisson::testPN() {\n\tMeshNode ***pNode = _pMesh->getNodes();\n\n\tfor (size_t ix = 0; ix < _nx; ++ix)\n\t\tfor (size_t iy = 0; iy < _ny; ++iy)\n\t\t\tfor (size_t iz = 0; iz < _nz; ++iz)\n\t\t\t\tif (pNode[ix][iy][iz]._active) {\n\t\t\t\t\tif (ix < _nx / 2)\n\t\t\t\t\t\t_Qokmc(pNode[ix][iy][iz]._index) = .01;\n\t\t\t\t\telse\n\t\t\t\t\t\t_Qokmc(pNode[ix][iy][iz]._index) = -.005;\n\n\t\t\t\t\tif (ix == 0 || ix == _nx - 1 || iy == 0 || iy == _ny - 1 || iz == 0 || iz == _nz - 1)\n\t\t\t\t\t\t_Qokmc(pNode[ix][iy][iz]._index) *= .5;\n\t\t\t\t}\n}\n\nvoid Poisson::buildOKMCVector() {\n\tMeshNode ***pNode = _pMesh->getNodes();\n\tconst IO::ParameterManager *pPM       = Domains::global()->PM();\n\n\tfor(M_TYPE mt = 0; mt < pPM->getNMaterials(); ++mt) {\n\t\tfor(P_TYPE pt = 0; pt < pPM->getNParticles(); ++pt) {\n\t\t\tif (!_Nokmc[mt][pt].empty()) {\n\t\t\t\t_Nokmc[mt][pt] = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (size_t ix = 0; ix < _nx; ++ix) {\n\t\tfor (size_t iy = 0; iy < _ny; ++iy) {\n\t\t\tfor (size_t iz = 0; iz < _nz; ++iz) {\n\t\t\t\tif (pNode[ix][iy][iz]._active && !pNode[ix][iy][iz]._mPart.empty()) {\n\t\t\t\t\tfor (std::map<OKMC::Particle *, double>::const_iterator it = pNode[ix][iy][iz]._mPart.begin(); it != pNode[ix][iy][iz]._mPart.end(); ++it) {\n\t\t\t\t\t\tconst OKMC::Particle * pPart = it->first;\n\t\t\t\t\t\tconst M_TYPE mt        = pPart->getElement()->getMaterial();\n\t\t\t\t\t\tconst P_TYPE pt        = pPart->getPType();\n\t\t\t\t\t\tif(_Nokmc[mt][pt].empty()) //particle not mapped.\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t_Nokmc[mt][pt](pNode[ix][iy][iz]._index) += it->second;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Poisson::buildLKMCVector() {\n\tMeshNode ***pNode = _pMesh->getNodes();\n\tconst IO::ParameterManager *pPM       = Domains::global()->PM();\n\n\tfor(M_TYPE mt = 0; mt < pPM->getNMaterials(); ++mt)\n\t\tif (!_Nlkmc[mt].empty())\n\t\t{\n\t\t\t_Nlkmc[mt] = ublas::zero_vector<double>(_nx * _ny * _nz);\n\t\t\tfor (size_t ix = 0; ix < _nx; ++ix)\n\t\t\t\tfor (size_t iy = 0; iy < _ny; ++iy)\n\t\t\t\t\tfor (size_t iz = 0; iz < _nz; ++iz)\n\t\t\t\t\t\tif (pNode[ix][iy][iz]._active && !pNode[ix][iy][iz]._mLA.empty())\n\t\t\t\t\t\t\tfor (std::map<LKMC::LatticeAtom *, double>::const_iterator it = pNode[ix][iy][iz]._mLA.begin(); it != pNode[ix][iy][iz]._mLA.end(); ++it)\n\t\t\t\t\t\t\t\tif (/*!it->first->getDefective() && */!it->first->getPerformed())\n\t\t\t\t\t\t\t\t\t_Nlkmc[mt](pNode[ix][iy][iz]._index) += it->second;\n\t\t}\n}\n\ndouble Poisson::getPermittivity(MeshNode *n1, MeshNode *n2, MeshNode *n3) {\n\tdouble eps = 0.;\n\n\tstd::set<MeshElement *> s1;\n\tstd::set<MeshElement *> s2;\n\tstd::set<MeshElement *> s3;\n\n\t_pMesh->getElementsFromNode(n1, s1);\n\t_pMesh->getElementsFromNode(n2, s2);\n\t_pMesh->getElementsFromNode(n3, s3);\n\n\tfor(std::set<MeshElement *>::const_iterator it = s1.begin(); it != s1.end(); ++it)\n\t\tif (s2.find(*it) != s2.end() && s3.find(*it) != s3.end()) {\n\t\t\t// eps = Domains::global()->PM()->getPermittivity((*it)->getMaterial());\n\t\t\teps = Domains::global()->PM()->getMaterial((*it)->getMaterial())._permittivity;\n\t\t\tbreak ;\n\t\t}\n\n\treturn eps;\n}\n\nvoid Poisson::buildLaplacianMatrix() {\n\tdouble dxm;\n\tdouble dxp;\n\tdouble dym;\n\tdouble dyp;\n\tdouble dzm;\n\tdouble dzp;\n\n\tMeshNode ***pNode = _pMesh->getNodes();\n\n\t_laplacian = ublas::compressed_matrix<double> (_nx * _ny * _nz, _nx * _ny * _nz);\n\t_Qeff      = ublas::zero_vector<double> (_nx * _ny * _nz);\n\n\tfor (unsigned ix = 0; ix < _pMesh->getnx(); ++ix) {\n\t\tfor (unsigned iy = 0; iy < _pMesh->getny(); ++iy) {\n\t\t\tfor (unsigned iz = 0; iz < _pMesh->getnz(); ++iz) {\n\n\t\t\t\tif (pNode[ix][iy][iz]._active) {\n\t\t\t\t\tdouble a[6] = {};\n\n\t\t\t\t\tunsigned ixm = ix - 1;\n\t\t\t\t\tunsigned ixp = ix + 1;\n\t\t\t\t\tunsigned iym = iy - 1;\n\t\t\t\t\tunsigned iyp = iy + 1;\n\t\t\t\t\tunsigned izm = iz - 1;\n\t\t\t\t\tunsigned izp = iz + 1;\n\n\t\t\t\t\t// xm\n\t\t\t\t\tif (ix == 0) {\n\t\t\t\t\t\tixm = (_pMesh->getPeriodicX() ? _nx-1 : ix);\n\t\t\t\t\t\tdxm = (_pMesh->getPeriodicX() ? pNode[_nx][iy][iz]._coord._x - pNode[_nx-1][iy][iz]._coord._x : 0);\n\t\t\t\t\t} else\n\t\t\t\t\t\tdxm = pNode[ix][iy][iz]._coord._x   - pNode[ixm][iy][iz]._coord._x;\n\t\t\t\t\t// xp\n\t\t\t\t\tif (ix == _nx - 1) {\n\t\t\t\t\t\tixp = (_pMesh->getPeriodicX() ? 0 : _nx-1);\n\t\t\t\t\t\tdxp = (_pMesh->getPeriodicX() ? pNode[_nx][iy][iz]._coord._x - pNode[_nx-1][iy][iz]._coord._x : 0);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tdxp = pNode[ixp][iy][iz]._coord._x - pNode[ix][iy][iz]._coord._x;\n\t\t\t\t\t// ym\n\t\t\t\t\tif (iy == 0) {\n\t\t\t\t\t\tiym = (_pMesh->getPeriodicY() ? _ny-1 : iy);\n\t\t\t\t\t\tdym = (_pMesh->getPeriodicY() ? pNode[ix][_ny][iz]._coord._y - pNode[ix][_ny-1][iz]._coord._y : 0);\n\t\t\t\t\t} else\n\t\t\t\t\t\tdym = pNode[ix][iy][iz]._coord._y   - pNode[ix][iym][iz]._coord._y;\n\t\t\t\t\t// yp\n\t\t\t\t\tif (iy == _ny - 1) {\n\t\t\t\t\t\tiyp = (_pMesh->getPeriodicY() ? 0 : _ny-1);\n\t\t\t\t\t\tdyp = (_pMesh->getPeriodicY() ? pNode[ix][_ny][iz]._coord._y - pNode[ix][_ny-1][iz]._coord._y : 0);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tdyp = pNode[ix][iyp][iz]._coord._y - pNode[ix][iy][iz]._coord._y;\n\t\t\t\t\t// zm\n\t\t\t\t\tif (iz == 0) {\n\t\t\t\t\t\tizm = (_pMesh->getPeriodicZ() ? _nz-1 : iz);\n\t\t\t\t\t\tdzm = (_pMesh->getPeriodicZ() ? pNode[ix][iy][_nz]._coord._z - pNode[ix][iy][_nz-1]._coord._z : 0);\n\t\t\t\t\t} else\n\t\t\t\t\t\tdzm = pNode[ix][iy][iz]._coord._z   - pNode[ix][iy][izm]._coord._z;\n\t\t\t\t\t// zp\n\t\t\t\t\tif (iz == _nz - 1) {\n\t\t\t\t\t\tizp = (_pMesh->getPeriodicZ() ? 0 : _nz-1);\n\t\t\t\t\t\tdzp = (_pMesh->getPeriodicZ() ? pNode[ix][iy][_nz]._coord._z - pNode[ix][iy][_nz-1]._coord._z : 0);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tdzp = pNode[ix][iy][izp]._coord._z - pNode[ix][iy][iz]._coord._z;\n\n\n\t\t\t\t\tdxm /= BOHR_RADIUS * 1e9;\n\t\t\t\t\tdxp /= BOHR_RADIUS * 1e9;\n\t\t\t\t\tdym /= BOHR_RADIUS * 1e9;\n\t\t\t\t\tdyp /= BOHR_RADIUS * 1e9;\n\t\t\t\t\tdzm /= BOHR_RADIUS * 1e9;\n\t\t\t\t\tdzp /= BOHR_RADIUS * 1e9;\n\n\t\t\t\t\tif (ix != ixp) {\n\t\t\t\t\t\tconst double eps1 = getPermittivity(&pNode[ixp][iy][iz], &pNode[ix][iyp][iz], &pNode[ix][iy][izp]);\n\t\t\t\t\t\tconst double eps2 = getPermittivity(&pNode[ixp][iy][iz], &pNode[ix][iym][iz], &pNode[ix][iy][izp]);\n\t\t\t\t\t\tconst double eps3 = getPermittivity(&pNode[ixp][iy][iz], &pNode[ix][iyp][iz], &pNode[ix][iy][izm]);\n\t\t\t\t\t\tconst double eps4 = getPermittivity(&pNode[ixp][iy][iz], &pNode[ix][iym][iz], &pNode[ix][iy][izm]);\n\n\t\t\t\t\t\ta[0] = 1. / (4. * dxp) * (eps1 * dyp * dzp + eps2 * dym * dzp + eps3 * dyp * dzm + eps4 * dym * dzm);\n\t\t\t\t\t}\n\t\t\t\t\tif (ix != ixm) {\n\t\t\t\t\t\tconst double eps1 = getPermittivity(&pNode[ixm][iy][iz], &pNode[ix][iyp][iz], &pNode[ix][iy][izp]);\n\t\t\t\t\t\tconst double eps2 = getPermittivity(&pNode[ixm][iy][iz], &pNode[ix][iym][iz], &pNode[ix][iy][izp]);\n\t\t\t\t\t\tconst double eps3 = getPermittivity(&pNode[ixm][iy][iz], &pNode[ix][iyp][iz], &pNode[ix][iy][izm]);\n\t\t\t\t\t\tconst double eps4 = getPermittivity(&pNode[ixm][iy][iz], &pNode[ix][iym][iz], &pNode[ix][iy][izm]);\n\n\t\t\t\t\t\ta[1] = 1. / (4. * dxm) * (eps1 * dyp * dzp + eps2 * dym * dzp + eps3 * dyp * dzm + eps4 * dym * dzm);\n\t\t\t\t\t}\n\t\t\t\t\tif (iy != iyp) {\n\t\t\t\t\t\tconst double eps1 = getPermittivity(&pNode[ix][iyp][iz], &pNode[ixp][iy][iz], &pNode[ix][iy][izp]);\n\t\t\t\t\t\tconst double eps2 = getPermittivity(&pNode[ix][iyp][iz], &pNode[ixm][iy][iz], &pNode[ix][iy][izp]);\n\t\t\t\t\t\tconst double eps3 = getPermittivity(&pNode[ix][iyp][iz], &pNode[ixp][iy][iz], &pNode[ix][iy][izm]);\n\t\t\t\t\t\tconst double eps4 = getPermittivity(&pNode[ix][iyp][iz], &pNode[ixm][iy][iz], &pNode[ix][iy][izm]);\n\n\t\t\t\t\t\ta[2] = 1. / (4. * dyp) * (eps1 * dxp * dzp + eps2 * dxm * dzp + eps3 * dxp * dzm + eps4 * dxm * dzm);\n\t\t\t\t\t}\n\t\t\t\t\tif (iy != iym) {\n\t\t\t\t\t\tconst double eps1 = getPermittivity(&pNode[ix][iym][iz], &pNode[ixp][iy][iz], &pNode[ix][iy][izp]);\n\t\t\t\t\t\tconst double eps2 = getPermittivity(&pNode[ix][iym][iz], &pNode[ixm][iy][iz], &pNode[ix][iy][izp]);\n\t\t\t\t\t\tconst double eps3 = getPermittivity(&pNode[ix][iym][iz], &pNode[ixp][iy][iz], &pNode[ix][iy][izm]);\n\t\t\t\t\t\tconst double eps4 = getPermittivity(&pNode[ix][iym][iz], &pNode[ixm][iy][iz], &pNode[ix][iy][izm]);\n\n\t\t\t\t\t\ta[3] = 1. / (4. * dym) * (eps1 * dxp * dzp + eps2 * dxm * dzp + eps3 * dxp * dzm + eps4 * dxm * dzm);\n\t\t\t\t\t}\n\t\t\t\t\tif (iz != izp) {\n\t\t\t\t\t\tconst double eps1 = getPermittivity(&pNode[ix][iy][izp], &pNode[ixp][iy][iz], &pNode[ix][iyp][iz]);\n\t\t\t\t\t\tconst double eps2 = getPermittivity(&pNode[ix][iy][izp], &pNode[ixp][iy][iz], &pNode[ix][iym][iz]);\n\t\t\t\t\t\tconst double eps3 = getPermittivity(&pNode[ix][iy][izp], &pNode[ixm][iy][iz], &pNode[ix][iyp][iz]);\n\t\t\t\t\t\tconst double eps4 = getPermittivity(&pNode[ix][iy][izp], &pNode[ixm][iy][iz], &pNode[ix][iym][iz]);\n\n\t\t\t\t\t\ta[4] = 1. / (4. * dzp) * (eps1 * dyp * dxp + eps2 * dym * dxp + eps3 * dyp * dxm + eps4 * dym * dxm);\n\t\t\t\t\t}\n\t\t\t\t\tif (iz != izm) {\n\t\t\t\t\t\tconst double eps1 = getPermittivity(&pNode[ix][iy][izm], &pNode[ixp][iy][iz], &pNode[ix][iyp][iz]);\n\t\t\t\t\t\tconst double eps2 = getPermittivity(&pNode[ix][iy][izm], &pNode[ixp][iy][iz], &pNode[ix][iym][iz]);\n\t\t\t\t\t\tconst double eps3 = getPermittivity(&pNode[ix][iy][izm], &pNode[ixm][iy][iz], &pNode[ix][iyp][iz]);\n\t\t\t\t\t\tconst double eps4 = getPermittivity(&pNode[ix][iy][izm], &pNode[ixm][iy][iz], &pNode[ix][iym][iz]);\n\n\t\t\t\t\t\ta[5] = 1. / (4. * dzm) * (eps1 * dyp * dxp + eps2 * dym * dxp + eps3 * dyp * dxm + eps4 * dym * dxm);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!pNode[ixp][iy][iz]._active && _pMesh->isDirichletX())\n\t\t\t\t\t\t_Qeff(pNode[ix][iy][iz]._index) += a[0] * ELECTRONVOLT_TO_HARTREE(pNode[ixp][iy][iz]._V) / (4. * M_PI);\n\t\t\t\t\tif (!pNode[ixm][iy][iz]._active && _pMesh->isDirichletX())\n\t\t\t\t\t\t_Qeff(pNode[ix][iy][iz]._index) += a[1] * ELECTRONVOLT_TO_HARTREE(pNode[ixm][iy][iz]._V) / (4. * M_PI);\n\n\t\t\t\t\tif (!pNode[ix][iyp][iz]._active && _pMesh->isDirichletY())\n\t\t\t\t\t\t_Qeff(pNode[ix][iy][iz]._index) += a[2] * ELECTRONVOLT_TO_HARTREE(pNode[ix][iyp][iz]._V) / (4. * M_PI);\n\t\t\t\t\tif (!pNode[ix][iym][iz]._active && _pMesh->isDirichletY())\n\t\t\t\t\t\t_Qeff(pNode[ix][iy][iz]._index) += a[3] * ELECTRONVOLT_TO_HARTREE(pNode[ix][iym][iz]._V) / (4. * M_PI);\n\n\t\t\t\t\tif (!pNode[ix][iy][izm]._active && _pMesh->isDirichletZ())\n\t\t\t\t\t\t_Qeff(pNode[ix][iy][iz]._index) += a[4] * ELECTRONVOLT_TO_HARTREE(pNode[ix][iy][izp]._V) / (4. * M_PI);\n\t\t\t\t\tif (!pNode[ix][iy][izp]._active && _pMesh->isDirichletZ())\n\t\t\t\t\t\t_Qeff(pNode[ix][iy][iz]._index) += a[5] * ELECTRONVOLT_TO_HARTREE(pNode[ix][iy][izm]._V) / (4. * M_PI);\n\n\t\t\t\t\t_laplacian(pNode[ix][iy][iz]._index, pNode[ix][iy][iz]._index)      = a[0] + a[1] + a[2] + a[3] + a[4] + a[5];\n\t\t\t\t\tif (ix != ixp)\n\t\t\t\t\t\t_laplacian(pNode[ix][iy][iz]._index, pNode[ixp][iy][iz]._index) = - a[0];\n\t\t\t\t\tif (ix != ixm)\n\t\t\t\t\t\t_laplacian(pNode[ix][iy][iz]._index, pNode[ixm][iy][iz]._index) = - a[1];\n\t\t\t\t\tif (iy != iyp)\n\t\t\t\t\t\t_laplacian(pNode[ix][iy][iz]._index, pNode[ix][iyp][iz]._index) = - a[2];\n\t\t\t\t\tif (iy != iym)\n\t\t\t\t\t\t_laplacian(pNode[ix][iy][iz]._index, pNode[ix][iym][iz]._index) = - a[3];\n\t\t\t\t\tif (iz != izp)\n\t\t\t\t\t\t_laplacian(pNode[ix][iy][iz]._index, pNode[ix][iy][izp]._index) = - a[4];\n\t\t\t\t\tif (iz != izm)\n\t\t\t\t\t\t_laplacian(pNode[ix][iy][iz]._index, pNode[ix][iy][izm]._index) = - a[5];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "8ee94f4d55fc799f803b84c0a542228961bcd62b", "size": 37738, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/electrostatics/Poisson.cpp", "max_stars_repo_name": "imartinbragado/MMonCa", "max_stars_repo_head_hexsha": "126744a90253d7d7884c6dc7ec100db00a106a66", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-11-23T16:20:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-15T09:13:49.000Z", "max_issues_repo_path": "src/electrostatics/Poisson.cpp", "max_issues_repo_name": "Warmshawn/MMonCa", "max_issues_repo_head_hexsha": "df279c2103484e89898ff4e81b45fb9ad43bcb9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/electrostatics/Poisson.cpp", "max_forks_repo_name": "Warmshawn/MMonCa", "max_forks_repo_head_hexsha": "df279c2103484e89898ff4e81b45fb9ad43bcb9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T03:28:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T10:38:14.000Z", "avg_line_length": 40.1041445271, "max_line_length": 164, "alphanum_fraction": 0.5793099793, "num_tokens": 13964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.448203841312571}}
{"text": "#include <Python.h>\n#include <iostream>\n#include <Eigen/Dense>\n#include <math.h>\n#include <numpy/arrayobject.h>\n#include \"ID_Daw.h\"\n\n/*\nThis module uses IDDAW.cpp to find the energy of a set of interlayer dislocations\nIt can be built using setup_ID_DAW.py\nand tested using test_IDDAW.py\n\nhttps://dfm.io/posts/python-c-extensions/\n*/\n\n\nstatic char module_docstring[] =\n    \"This module provides an interface for calculating the Continuum interlayer energy.\";\nstatic char Energyf_sp_docstring[] =\n    \"Calculate the Energy of a set of interlayer Dislocations using Daw's formalism.\";\nstatic char visDuftot_docstring[] =\n    \"Calculate the Distortion field of a set of interlayer Dislocations using Daw's formalism.\";\nstatic char visuftot_docstring[] =\n    \"Calculate the in-plane displacement field of a set of interlayer Dislocations using Daw's formalism with stacking.\";\n\n\nstatic PyObject *IDDAW_Energyf_sp(PyObject *self, PyObject *args);\nstatic PyObject *IDDAW_visDuftot(PyObject *self, PyObject *args);\nstatic PyObject *IDDAW_visuftot(PyObject *self, PyObject *args);\n\nMatrixXd unpacklocbur(double* , int);\n\nstatic PyMethodDef module_methods[] = {\n    {\"_Energyf_sp\", IDDAW_Energyf_sp, METH_VARARGS, Energyf_sp_docstring},\n    {\"_visDuftot\", IDDAW_visDuftot, METH_VARARGS, visDuftot_docstring},\n    {\"_visuftot\", IDDAW_visuftot, METH_VARARGS, visuftot_docstring},\n    {NULL, NULL, 0, NULL}\n};\n\nPyMODINIT_FUNC init_IDDAW(void)\n{\n    PyObject *m = Py_InitModule3(\"_IDDAW\", module_methods, module_docstring);\n    if (m == NULL)\n        return;\n\n    /* Load `numpy` functionality. */\n    import_array();\n}\n\n\nstatic PyObject *IDDAW_Energyf_sp(PyObject *self, PyObject *args)\n{\n    double rc, kap, c33, z0, alpha;\n    int ndisl, ndislout, pmax, qmax, ncoor;\n    PyObject *Cijkl_obj, *Lxy_obj, *a1_obj, *a2_obj, *loc_obj, *burgers_obj, *fG1_obj, *fG2_obj, *locout_obj, *dirout_obj, *burgersout_obj, *rcout_obj, *M_obj, *X_obj;\n\n    /* Parse the input tuple */\n    if (!PyArg_ParseTuple(args, \"OOOOOOdiOOiiOOOOidddOiOd\", &Cijkl_obj, &Lxy_obj, &a1_obj, &a2_obj,\n        &loc_obj, &burgers_obj, &rc, &ndisl, &fG1_obj, &fG2_obj, &pmax, &qmax,\n        &locout_obj, &dirout_obj, &burgersout_obj, &rcout_obj, &ndislout, &kap, &c33, &z0, &M_obj, &ncoor, &X_obj, &alpha))\n        return NULL;\n\n    /* Interpret the input objects as numpy arrays. */\n    PyObject *Cijkl_array = PyArray_FROM_OTF(Cijkl_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *Lxy_array = PyArray_FROM_OTF(Lxy_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *a1_array = PyArray_FROM_OTF(a1_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *a2_array = PyArray_FROM_OTF(a2_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *loc_array = PyArray_FROM_OTF(loc_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *burgers_array = PyArray_FROM_OTF(burgers_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *fG1_array = PyArray_FROM_OTF(fG1_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *fG2_array = PyArray_FROM_OTF(fG2_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *locout_array = PyArray_FROM_OTF(locout_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *dirout_array = PyArray_FROM_OTF(dirout_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *burgersout_array = PyArray_FROM_OTF(burgersout_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *rcout_array = PyArray_FROM_OTF(rcout_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *M_array = PyArray_FROM_OTF(M_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *X_array = PyArray_FROM_OTF(X_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n\n    /* If that didn't work, throw an exception. */\n    if (Cijkl_array == NULL || Lxy_array == NULL || a1_array == NULL ||\n        a2_array == NULL || loc_array == NULL || burgers_array == NULL ||\n        fG1_array == NULL || fG2_array == NULL || locout_array == NULL ||\n        burgersout_array == NULL || dirout_array == NULL || M_array == NULL || X_array == NULL) {\n        Py_XDECREF(Cijkl_array);\n        Py_XDECREF(Lxy_array);\n        Py_XDECREF(a1_array);\n        Py_XDECREF(a2_array);\n        Py_XDECREF(loc_array);\n        Py_XDECREF(burgers_array);\n        Py_XDECREF(fG1_array);\n        Py_XDECREF(fG2_array);\n        Py_XDECREF(locout_array);\n        Py_XDECREF(dirout_array);\n        Py_XDECREF(burgersout_array);\n        Py_XDECREF(rcout_array);\n        Py_XDECREF(M_array);\n        Py_XDECREF(X_array);\n        return NULL;\n    }\n\n    /* Get pointers to the data as C-types. */\n    double *Cijklp    = (double*)PyArray_DATA(Cijkl_array);\n    double *Lxyp    = (double*)PyArray_DATA(Lxy_array);\n    double *a1p = (double*)PyArray_DATA(a1_array);\n    double *a2p = (double*)PyArray_DATA(a2_array);\n    double *locp = (double*)PyArray_DATA(loc_array);\n    double *burgersp = (double*)PyArray_DATA(burgers_array);\n    double *fG1p = (double*)PyArray_DATA(fG1_array);\n    double *fG2p = (double*)PyArray_DATA(fG2_array);\n    double *locoutp = (double*)PyArray_DATA(locout_array);\n    double *diroutp = (double*)PyArray_DATA(dirout_array);\n    double *burgersoutp = (double*)PyArray_DATA(burgersout_array);\n    double *rcoutp = (double*)PyArray_DATA(rcout_array);\n    double *Mp = (double*)PyArray_DATA(M_array);\n    double *Xp = (double*)PyArray_DATA(X_array);\n\n    cout << \"pmax\" << endl << pmax << endl;\n    cout << \"qmax\" << endl << qmax << endl;\n\n    //Convert Pointers into C Data Types\n    MatrixXd C(2,8);\n    C(0,0) = Cijklp[0]; C(0,1) = Cijklp[1]; C(0,2) = Cijklp[2]; C(0,3) = Cijklp[3];\n    C(0,4) = Cijklp[4]; C(0,5) = Cijklp[5]; C(0,6) = Cijklp[6]; C(0,7) = Cijklp[7];\n    C(1,0) = Cijklp[8]; C(1,1) = Cijklp[9]; C(1,2) = Cijklp[10]; C(1,3) = Cijklp[11];\n    C(1,4) = Cijklp[12]; C(1,5) = Cijklp[13]; C(1,6) = Cijklp[14]; C(1,7) = Cijklp[15];\n    \n    MatrixXd burgers(ndisl,2);\n    MatrixXd loc(ndisl,2);\n\n    burgers = unpacklocbur(burgersp,ndisl);\n    loc = unpacklocbur(locp,ndisl);\n\n    MatrixXd burgersout(ndislout,2);\n    MatrixXd locout(ndislout,2);\n    MatrixXd dirout(ndislout,2);\n\n    burgersout = unpacklocbur(burgersoutp,ndislout);\n    locout = unpacklocbur(locoutp,ndislout);\n    dirout = unpacklocbur(diroutp,ndislout);\n    VectorXd rcout(2*ndislout);\n    for (int k = 0; k<2*ndislout; k++){ \n        rcout(k) = rcoutp[k];\n    }\n\n    Vector2d Lxy(Lxyp[0],Lxyp[1]);\n    Vector2d a1(a1p[0],a1p[1]);\n    Vector2d a2(a2p[0],a2p[1]);\n\n    Vector2d M(Mp[0],Mp[1]);\n\n    MatrixXd fG1 = Map<Matrix<double,Dynamic,Dynamic,RowMajor> >(fG1p,2*pmax+1,2*qmax+1);\n    MatrixXd fG2 = Map<Matrix<double,Dynamic,Dynamic,RowMajor> >(fG2p,2*pmax+1,2*qmax+1);\n\n\n    MatrixXd X = Map<Matrix<double,Dynamic,Dynamic,RowMajor> >(Xp,ncoor,2);\n\n    /*\n    cout << \"Cijkl\" << endl << C << endl;\n    cout << \"kap\" << endl << kap << endl;\n    cout << \"c33\" << endl << c33 << endl;\n    cout << \"Lxy\" << endl << Lxy << endl;\n    cout << \"a1\" << endl << a1 << endl;\n    cout << \"a2\" << endl << a2 << endl;\n    cout << \"fG1\" << endl << fG1 << endl;\n    cout << \"fG2\" << endl << fG2 << endl;\n    cout << \"loc\" << endl << loc << endl;\n    cout << \"burgers\" << endl << burgers << endl;\n    cout << \"rc\" << endl << rc << endl;\n    cout << \"loc_out\" << endl << locout << endl;\n    cout << \"dir_out\" << endl << dirout << endl;\n    cout << \"burgers_out\" << endl << burgersout << endl;\n    cout << \"rc_out\" << endl << rcout << endl;\n    cout << \"pmax\" << endl << pmax << endl;\n    cout << \"qmax\" << endl << qmax << endl;\n    cout << \"z0\" << endl << z0 << endl;\n    cout << \"M\" << endl << M << endl;\n    */\n    Vector3d res = energyf_sp(C, kap, c33, Lxy, a1, a2, fG1, fG2, loc, burgers, rc, locout, dirout, burgersout, rcout, pmax, qmax, z0, M, ncoor, X, alpha);\n\n    //double value = res[0];\n    double ret_array[3];\n    ret_array[0] = res[0];\n    ret_array[1] = res[1];\n    ret_array[2] = res[2];\n\n\n\n    /* Clean up. */\n    Py_XDECREF(Cijkl_array);\n    Py_XDECREF(Lxy_array);\n    Py_XDECREF(a1_array);\n    Py_XDECREF(a2_array);\n    Py_XDECREF(loc_array);\n    Py_XDECREF(burgers_array);\n    Py_XDECREF(fG1_array);\n    Py_XDECREF(fG2_array);\n    Py_XDECREF(locout_array);\n    Py_XDECREF(dirout_array);\n    Py_XDECREF(burgersout_array);\n    Py_XDECREF(rcout_array);\n    Py_XDECREF(M_array);\n    Py_XDECREF(X_array);\n\n    npy_intp dims[1] = {3};\n    PyObject *ret = PyArray_SimpleNew(1, dims, NPY_DOUBLE);\n    memcpy(PyArray_DATA(ret), ret_array, sizeof(ret_array));\n\n    /* Build the output tuple */\n    //PyObject *ret = Py_BuildValue(\"d\", value);\n    return ret;\n}\n\nstatic PyObject *IDDAW_visDuftot(PyObject *self, PyObject *args)\n{\n    double rc, kap, c33, z0, alpha;\n    int ndisl, ndislout, pmax, qmax, ncoor;\n    PyObject *Cijkl_obj, *Lxy_obj, *a1_obj, *a2_obj, *loc_obj, *burgers_obj, *fG1_obj, *fG2_obj, *locout_obj, *dirout_obj, *burgersout_obj, *rcout_obj, *M_obj, *X_obj;\n\n    /* Parse the input tuple */\n    if (!PyArg_ParseTuple(args, \"OOOOOOdiOOiiOOOOidddOiOd\", &Cijkl_obj, &Lxy_obj, &a1_obj, &a2_obj,\n        &loc_obj, &burgers_obj, &rc, &ndisl, &fG1_obj, &fG2_obj, &pmax, &qmax,\n        &locout_obj, &dirout_obj, &burgersout_obj, &rcout_obj, &ndislout, &kap, &c33, &z0, &M_obj, &ncoor, &X_obj, &alpha))\n        return NULL;\n\n    /* Interpret the input objects as numpy arrays. */\n    PyObject *Cijkl_array = PyArray_FROM_OTF(Cijkl_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *Lxy_array = PyArray_FROM_OTF(Lxy_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *a1_array = PyArray_FROM_OTF(a1_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *a2_array = PyArray_FROM_OTF(a2_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *loc_array = PyArray_FROM_OTF(loc_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *burgers_array = PyArray_FROM_OTF(burgers_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *fG1_array = PyArray_FROM_OTF(fG1_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *fG2_array = PyArray_FROM_OTF(fG2_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *locout_array = PyArray_FROM_OTF(locout_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *dirout_array = PyArray_FROM_OTF(dirout_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *burgersout_array = PyArray_FROM_OTF(burgersout_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *rcout_array = PyArray_FROM_OTF(rcout_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *M_array = PyArray_FROM_OTF(M_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *X_array = PyArray_FROM_OTF(X_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n\n    /* If that didn't work, throw an exception. */\n    if (Cijkl_array == NULL || Lxy_array == NULL || a1_array == NULL ||\n        a2_array == NULL || loc_array == NULL || burgers_array == NULL ||\n        fG1_array == NULL || fG2_array == NULL || locout_array == NULL ||\n        burgersout_array == NULL || dirout_array == NULL || M_array == NULL || X_array == NULL) {\n        Py_XDECREF(Cijkl_array);\n        Py_XDECREF(Lxy_array);\n        Py_XDECREF(a1_array);\n        Py_XDECREF(a2_array);\n        Py_XDECREF(loc_array);\n        Py_XDECREF(burgers_array);\n        Py_XDECREF(fG1_array);\n        Py_XDECREF(fG2_array);\n        Py_XDECREF(locout_array);\n        Py_XDECREF(dirout_array);\n        Py_XDECREF(burgersout_array);\n        Py_XDECREF(rcout_array);\n        Py_XDECREF(M_array);\n        Py_XDECREF(X_array);\n        return NULL;\n    }\n\n    /* Get pointers to the data as C-types. */\n    double *Cijklp    = (double*)PyArray_DATA(Cijkl_array);\n    double *Lxyp    = (double*)PyArray_DATA(Lxy_array);\n    double *a1p = (double*)PyArray_DATA(a1_array);\n    double *a2p = (double*)PyArray_DATA(a2_array);\n    double *locp = (double*)PyArray_DATA(loc_array);\n    double *burgersp = (double*)PyArray_DATA(burgers_array);\n    double *fG1p = (double*)PyArray_DATA(fG1_array);\n    double *fG2p = (double*)PyArray_DATA(fG2_array);\n    double *locoutp = (double*)PyArray_DATA(locout_array);\n    double *diroutp = (double*)PyArray_DATA(dirout_array);\n    double *burgersoutp = (double*)PyArray_DATA(burgersout_array);\n    double *rcoutp = (double*)PyArray_DATA(rcout_array);\n    double *Mp = (double*)PyArray_DATA(M_array);\n    double *Xp = (double*)PyArray_DATA(X_array);\n\n    cout << \"pmax\" << endl << pmax << endl;\n    cout << \"qmax\" << endl << qmax << endl;\n\n    //Convert Pointers into C Data Types\n    MatrixXd C(2,8);\n    C(0,0) = Cijklp[0]; C(0,1) = Cijklp[1]; C(0,2) = Cijklp[2]; C(0,3) = Cijklp[3];\n    C(0,4) = Cijklp[4]; C(0,5) = Cijklp[5]; C(0,6) = Cijklp[6]; C(0,7) = Cijklp[7];\n    C(1,0) = Cijklp[8]; C(1,1) = Cijklp[9]; C(1,2) = Cijklp[10]; C(1,3) = Cijklp[11];\n    C(1,4) = Cijklp[12]; C(1,5) = Cijklp[13]; C(1,6) = Cijklp[14]; C(1,7) = Cijklp[15];\n    \n    MatrixXd burgers(ndisl,2);\n    MatrixXd loc(ndisl,2);\n\n    burgers = unpacklocbur(burgersp,ndisl);\n    loc = unpacklocbur(locp,ndisl);\n\n    MatrixXd burgersout(ndislout,2);\n    MatrixXd locout(ndislout,2);\n    MatrixXd dirout(ndislout,2);\n\n    burgersout = unpacklocbur(burgersoutp,ndislout);\n    locout = unpacklocbur(locoutp,ndislout);\n    dirout = unpacklocbur(diroutp,ndislout);\n    VectorXd rcout(2*ndislout);\n    for (int k = 0; k<2*ndislout; k++){ \n        rcout(k) = rcoutp[k];\n    }\n\n    Vector2d Lxy(Lxyp[0],Lxyp[1]);\n    Vector2d a1(a1p[0],a1p[1]);\n    Vector2d a2(a2p[0],a2p[1]);\n\n    Vector2d M(Mp[0],Mp[1]);\n\n    MatrixXd fG1 = Map<Matrix<double,Dynamic,Dynamic,RowMajor> >(fG1p,2*pmax+1,2*qmax+1);\n    MatrixXd fG2 = Map<Matrix<double,Dynamic,Dynamic,RowMajor> >(fG2p,2*pmax+1,2*qmax+1);\n\n\n    MatrixXd X = Map<Matrix<double,Dynamic,Dynamic,RowMajor> >(Xp,ncoor,2);\n\n    /*\n    cout << \"Cijkl\" << endl << C << endl;\n    cout << \"kap\" << endl << kap << endl;\n    cout << \"c33\" << endl << c33 << endl;\n    cout << \"Lxy\" << endl << Lxy << endl;\n    cout << \"a1\" << endl << a1 << endl;\n    cout << \"a2\" << endl << a2 << endl;\n    cout << \"fG1\" << endl << fG1 << endl;\n    cout << \"fG2\" << endl << fG2 << endl;\n    cout << \"loc\" << endl << loc << endl;\n    cout << \"burgers\" << endl << burgers << endl;\n    cout << \"rc\" << endl << rc << endl;\n    cout << \"loc_out\" << endl << locout << endl;\n    cout << \"dir_out\" << endl << dirout << endl;\n    cout << \"burgers_out\" << endl << burgersout << endl;\n    cout << \"rc_out\" << endl << rcout << endl;\n    cout << \"pmax\" << endl << pmax << endl;\n    cout << \"qmax\" << endl << qmax << endl;\n    cout << \"z0\" << endl << z0 << endl;\n    cout << \"M\" << endl << M << endl;\n    */\n    MatrixXd res = visD_uftot(C, kap, c33, Lxy, a1, a2, fG1, fG2, loc, burgers, rc, locout, dirout, burgersout, rcout, pmax, qmax, z0, M, ncoor, X, alpha);\n\n    //cout << \"Return: \" << res << endl;\n    //double value = res[0];\n    \n    double ret_array[8*ncoor];\n\n    for (int i = 0; i < ncoor; i++){\n        for (int j = 0; j < 8; j++){\n            ret_array[8*i+j] = res(i,j);\n        }\n    }\n\n\n\n    /* Clean up. */\n    Py_XDECREF(Cijkl_array);\n    Py_XDECREF(Lxy_array);\n    Py_XDECREF(a1_array);\n    Py_XDECREF(a2_array);\n    Py_XDECREF(loc_array);\n    Py_XDECREF(burgers_array);\n    Py_XDECREF(fG1_array);\n    Py_XDECREF(fG2_array);\n    Py_XDECREF(locout_array);\n    Py_XDECREF(dirout_array);\n    Py_XDECREF(burgersout_array);\n    Py_XDECREF(rcout_array);\n    Py_XDECREF(M_array);\n    Py_XDECREF(X_array);\n\n    //cout << \"Return: \" << ret_array << endl;\n\n    npy_intp dims[1] = {8*ncoor};\n    PyObject *ret = PyArray_SimpleNew(1, dims, NPY_DOUBLE);\n    memcpy(PyArray_DATA(ret), ret_array, sizeof(ret_array));\n\n    /* Build the output tuple */\n    //PyObject *ret = Py_BuildValue(\"d\", value);\n    return ret;\n}\n\nstatic PyObject *IDDAW_visuftot(PyObject *self, PyObject *args)\n{\n    double rc, kap, c33, z0, alpha;\n    int ndisl, ndislout, pmax, qmax, ncoor;\n    PyObject *Cijkl_obj, *Lxy_obj, *a1_obj, *a2_obj, *loc_obj, *burgers_obj, *fG1_obj, *fG2_obj, *locout_obj, *dirout_obj, *burgersout_obj, *rcout_obj, *M_obj, *X_obj;\n\n    /* Parse the input tuple */\n    if (!PyArg_ParseTuple(args, \"OOOOOOdiOOiiOOOOidddOiOd\", &Cijkl_obj, &Lxy_obj, &a1_obj, &a2_obj,\n        &loc_obj, &burgers_obj, &rc, &ndisl, &fG1_obj, &fG2_obj, &pmax, &qmax,\n        &locout_obj, &dirout_obj, &burgersout_obj, &rcout_obj, &ndislout, &kap, &c33, &z0, &M_obj, &ncoor, &X_obj, &alpha))\n        return NULL;\n\n    /* Interpret the input objects as numpy arrays. */\n    PyObject *Cijkl_array = PyArray_FROM_OTF(Cijkl_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *Lxy_array = PyArray_FROM_OTF(Lxy_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *a1_array = PyArray_FROM_OTF(a1_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *a2_array = PyArray_FROM_OTF(a2_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *loc_array = PyArray_FROM_OTF(loc_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *burgers_array = PyArray_FROM_OTF(burgers_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *fG1_array = PyArray_FROM_OTF(fG1_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *fG2_array = PyArray_FROM_OTF(fG2_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *locout_array = PyArray_FROM_OTF(locout_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *dirout_array = PyArray_FROM_OTF(dirout_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *burgersout_array = PyArray_FROM_OTF(burgersout_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *rcout_array = PyArray_FROM_OTF(rcout_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *M_array = PyArray_FROM_OTF(M_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n    PyObject *X_array = PyArray_FROM_OTF(X_obj, NPY_DOUBLE, NPY_IN_ARRAY);\n\n    /* If that didn't work, throw an exception. */\n    if (Cijkl_array == NULL || Lxy_array == NULL || a1_array == NULL ||\n        a2_array == NULL || loc_array == NULL || burgers_array == NULL ||\n        fG1_array == NULL || fG2_array == NULL || locout_array == NULL ||\n        burgersout_array == NULL || dirout_array == NULL || M_array == NULL || X_array == NULL) {\n        Py_XDECREF(Cijkl_array);\n        Py_XDECREF(Lxy_array);\n        Py_XDECREF(a1_array);\n        Py_XDECREF(a2_array);\n        Py_XDECREF(loc_array);\n        Py_XDECREF(burgers_array);\n        Py_XDECREF(fG1_array);\n        Py_XDECREF(fG2_array);\n        Py_XDECREF(locout_array);\n        Py_XDECREF(dirout_array);\n        Py_XDECREF(burgersout_array);\n        Py_XDECREF(rcout_array);\n        Py_XDECREF(M_array);\n        Py_XDECREF(X_array);\n        return NULL;\n    }\n\n    /* Get pointers to the data as C-types. */\n    double *Cijklp    = (double*)PyArray_DATA(Cijkl_array);\n    double *Lxyp    = (double*)PyArray_DATA(Lxy_array);\n    double *a1p = (double*)PyArray_DATA(a1_array);\n    double *a2p = (double*)PyArray_DATA(a2_array);\n    double *locp = (double*)PyArray_DATA(loc_array);\n    double *burgersp = (double*)PyArray_DATA(burgers_array);\n    double *fG1p = (double*)PyArray_DATA(fG1_array);\n    double *fG2p = (double*)PyArray_DATA(fG2_array);\n    double *locoutp = (double*)PyArray_DATA(locout_array);\n    double *diroutp = (double*)PyArray_DATA(dirout_array);\n    double *burgersoutp = (double*)PyArray_DATA(burgersout_array);\n    double *rcoutp = (double*)PyArray_DATA(rcout_array);\n    double *Mp = (double*)PyArray_DATA(M_array);\n    double *Xp = (double*)PyArray_DATA(X_array);\n\n    cout << \"pmax\" << endl << pmax << endl;\n    cout << \"qmax\" << endl << qmax << endl;\n\n    //Convert Pointers into C Data Types\n    MatrixXd C(2,8);\n    C(0,0) = Cijklp[0]; C(0,1) = Cijklp[1]; C(0,2) = Cijklp[2]; C(0,3) = Cijklp[3];\n    C(0,4) = Cijklp[4]; C(0,5) = Cijklp[5]; C(0,6) = Cijklp[6]; C(0,7) = Cijklp[7];\n    C(1,0) = Cijklp[8]; C(1,1) = Cijklp[9]; C(1,2) = Cijklp[10]; C(1,3) = Cijklp[11];\n    C(1,4) = Cijklp[12]; C(1,5) = Cijklp[13]; C(1,6) = Cijklp[14]; C(1,7) = Cijklp[15];\n    \n    MatrixXd burgers(ndisl,2);\n    MatrixXd loc(ndisl,2);\n\n    burgers = unpacklocbur(burgersp,ndisl);\n    loc = unpacklocbur(locp,ndisl);\n\n    MatrixXd burgersout(ndislout,2);\n    MatrixXd locout(ndislout,2);\n    MatrixXd dirout(ndislout,2);\n\n    burgersout = unpacklocbur(burgersoutp,ndislout);\n    locout = unpacklocbur(locoutp,ndislout);\n    dirout = unpacklocbur(diroutp,ndislout);\n    VectorXd rcout(2*ndislout);\n    for (int k = 0; k<2*ndislout; k++){ \n        rcout(k) = rcoutp[k];\n    }\n\n    Vector2d Lxy(Lxyp[0],Lxyp[1]);\n    Vector2d a1(a1p[0],a1p[1]);\n    Vector2d a2(a2p[0],a2p[1]);\n\n    Vector2d M(Mp[0],Mp[1]);\n\n    MatrixXd fG1 = Map<Matrix<double,Dynamic,Dynamic,RowMajor> >(fG1p,2*pmax+1,2*qmax+1);\n    MatrixXd fG2 = Map<Matrix<double,Dynamic,Dynamic,RowMajor> >(fG2p,2*pmax+1,2*qmax+1);\n\n\n    MatrixXd X = Map<Matrix<double,Dynamic,Dynamic,RowMajor> >(Xp,ncoor,2);\n\n    /*\n    cout << \"Cijkl\" << endl << C << endl;\n    cout << \"kap\" << endl << kap << endl;\n    cout << \"c33\" << endl << c33 << endl;\n    cout << \"Lxy\" << endl << Lxy << endl;\n    cout << \"a1\" << endl << a1 << endl;\n    cout << \"a2\" << endl << a2 << endl;\n    cout << \"fG1\" << endl << fG1 << endl;\n    cout << \"fG2\" << endl << fG2 << endl;\n    cout << \"loc\" << endl << loc << endl;\n    cout << \"burgers\" << endl << burgers << endl;\n    cout << \"rc\" << endl << rc << endl;\n    cout << \"loc_out\" << endl << locout << endl;\n    cout << \"dir_out\" << endl << dirout << endl;\n    cout << \"burgers_out\" << endl << burgersout << endl;\n    \n    cout << \"pmax\" << endl << pmax << endl;\n    cout << \"qmax\" << endl << qmax << endl;\n    cout << \"z0\" << endl << z0 << endl;\n    cout << \"M\" << endl << M << endl;\n    */\n    cout << \"rc_out\" << endl << rcout << endl;\n    MatrixXd res = visuftot(C, kap, c33, Lxy, a1, a2, fG1, fG2, loc, burgers, rc, locout, dirout, burgersout, rcout, pmax, qmax, z0, M, ncoor, X, alpha);\n\n    //cout << \"Return: \" << res << endl;\n    //double value = res[0];\n    \n    double ret_array[4*ncoor];\n\n    for (int i = 0; i < ncoor; i++){\n        for (int j = 0; j < 4; j++){\n            ret_array[4*i+j] = res(i,j);\n        }\n    }\n\n\n\n    /* Clean up. */\n    Py_XDECREF(Cijkl_array);\n    Py_XDECREF(Lxy_array);\n    Py_XDECREF(a1_array);\n    Py_XDECREF(a2_array);\n    Py_XDECREF(loc_array);\n    Py_XDECREF(burgers_array);\n    Py_XDECREF(fG1_array);\n    Py_XDECREF(fG2_array);\n    Py_XDECREF(locout_array);\n    Py_XDECREF(dirout_array);\n    Py_XDECREF(burgersout_array);\n    Py_XDECREF(rcout_array);\n    Py_XDECREF(M_array);\n    Py_XDECREF(X_array);\n\n    //cout << \"Return: \" << ret_array << endl;\n\n    npy_intp dims[1] = {4*ncoor};\n    PyObject *ret = PyArray_SimpleNew(1, dims, NPY_DOUBLE);\n    memcpy(PyArray_DATA(ret), ret_array, sizeof(ret_array));\n\n    /* Build the output tuple */\n    //PyObject *ret = Py_BuildValue(\"d\", value);\n    return ret;\n}\n\n\nMatrixXd unpacklocbur(double* point, int ndisl){\n\tMatrixXd out(ndisl,2);\n\tfor (int i=0;i<ndisl;i++){\n\t\tout(i,0) = point[i*2];\n\t\tout(i,1) = point[i*2+1];\n\t}\n\n\treturn out;\n}", "meta": {"hexsha": "19c022c5022d67cb4bd3d3281897894cbfd3886f", "size": 22278, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_cIDDAW.cpp", "max_stars_repo_name": "emilannevelink/InterlayerDislocations_Daw", "max_stars_repo_head_hexsha": "be2982c857c4842184b3ca41527e39f029003e09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_cIDDAW.cpp", "max_issues_repo_name": "emilannevelink/InterlayerDislocations_Daw", "max_issues_repo_head_hexsha": "be2982c857c4842184b3ca41527e39f029003e09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_cIDDAW.cpp", "max_forks_repo_name": "emilannevelink/InterlayerDislocations_Daw", "max_forks_repo_head_hexsha": "be2982c857c4842184b3ca41527e39f029003e09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7112299465, "max_line_length": 167, "alphanum_fraction": 0.641888859, "num_tokens": 7386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.5544704649604274, "lm_q1q2_score": 0.44804939849215397}}
{"text": "#include <NTL/ZZ.h>\n#include <NTL/ZZ_pXFactoring.h>\n#include \"nsgen.h\"\n#include \"ring.h\"\n\nvoid print_poly (ZZX& f) {\n  long d = deg(f);\n  if (d == -1) {\n    cout << \"0\" << endl;\n  }\n  else {\n    for (long i = d; i >= 0; --i) {\n      if (f[i] != 0)\n\tcout << f[i] << \"*\" << \"X^\" << i << \" + \";\n    }\n    cout << endl;\n  }\n}\n\n/***********************************************************************/\nZZX ring::apply_conj (ZZX& a, long i) {\n  long d = deg(a);\n  if (d == -1) return ZZX(0);\n\n  ZZX phi = (ZZX(INIT_MONO, mR)-1)/(ZZX(INIT_MONO, 1)-1);\n  ZZX w = ZZX(0);\n  \n  for (long j = 0; j <= d; j++) {\n    if (a[j] != 0) {\n      long t = (j*i) % mR;\n      ZZX z = ZZX(INIT_MONO, t);\n      rem(z, z, phi);\n      z *= ZZX(a[j]);\n      w += z;\n    }\n  }\n  \n  return w;\n}\n\nZZX ring::trace (ZZX& w) {\n  ZZX r = ZZX(0);\n\n  for (long a = 0; a < dR; ++a) {\n    ZZX v = apply_conj(w, GZ(a));\n    r += v;\n  }\n  return r;\n}\n\nZZX ring::eta (long j) {\n  ZZX z = ZZX(INIT_MONO, 1);\n  ZZX phi = (ZZX(INIT_MONO, mR)-1)/(ZZX(INIT_MONO, 1)-1);\n\n  long t = GofZ(j);\n  ZZX w = ZZX(INIT_MONO, t);  // w = X^t\n  rem(w, w, phi);\n\n  return trace(w);\n}\n\nZZ_pX ring::delta (long j) {\n  return conv<ZZ_pX>(eta(j) - dR);\n}\n\nZZ ring::scalar_quo (ZZX& a, ZZX& b, ZZ& p) {\n  long d = max(deg(a), deg(b));\n  a.SetLength(d+1);\n  b.SetLength(d+1);\n\n  // ZZ_pContext context;\n  // context.save();\n  ZZ_p::init(p);\n\n  ZZ_pX a1, b1;\n  a1.SetLength(d+1);\n  a1 = conv<ZZ_pX>(a);\n  b1.SetLength(d+1);\n  b1 = conv<ZZ_pX>(b);\n  \n  long i;\n  ZZ w;\n  for (i = 0; i <= d; ++i) {\n    if (GCD(b[i]%p, p) == 1) {\n      w = (a[i] * InvMod(b[i]%p, p)) % p;\n      break;\n    }\n  }\n\n  // ZZ_pX c1 = conv<ZZ_pX>(w) * b1;\n  // if (c1 != a1) {\n  //   cout << \"Error: unexpected behaviour in scalar_quo\" << endl;\n  //   cout << \"i = \" << i << \", p = \" << p << endl;\n  //   // cout << \"a1 = \" << a1 << endl;\n  //   // cout << \"b1 = \" << b1 << endl;\n  //   // cout << \"c1 = \" << c1 << endl;\n  //   exit(-1);\n  // }\n\n  //context.restore();\n  return w;\n}\n\n/***********************************************************************/\nZZ compose_integer (const ZZ& r1, const ZZ& q1, const ZZ& r2, const ZZ& q2) {\n  ZZ a, b, c;\n  XGCD(a, b, c, q1, q2);  // 1 = a = b*q1 + c*q2\n  ZZ w1 = c * q2;\n  ZZ w2 = b * q1;\n  return (r1*w1 + r2*w2) % (q1*q2);\n}\n\nvoid compose_vector (vec_ZZ& omega, vec_ZZ& omega1, ZZ& q1, vec_ZZ& omega2, ZZ& q2) {\n  for (long i = 0; i < omega1.length(); i++)\n    omega[i] = compose_integer(omega1[i], q1, omega2[i], q2);\n}\n\nvoid compose (ZZX& res, ring& rg, ZZX& res0, ZZ& q0, ZZX& res1, ZZ& q1) {\n  vec_ZZ v0 = VectorCopy(res0, rg.mR-1);\n  vec_ZZ v1 = VectorCopy(res1, rg.mR-1);\n  vec_ZZ v; v.SetLength(rg.mR-1);\n  compose_vector(v, v0, q0, v1, q1);\n  res.SetLength(rg.mR-1);\n  for (long i = 0; i < rg.mR-1; i++) SetCoeff(res, i, v[i]);\n}\n\n// assumes that 'm' is prime\n// modulus of the resolution is p^r\nvoid ring::resolution_of_one (ZZX& res, const long m, const ZZ& p) {\n  ZZ_pContext context;\n  context.save();\n  ZZ_p::init(p);\n  \n  ZZ_pX phi = (ZZ_pX(INIT_MONO, m)-1)/(ZZ_pX(INIT_MONO, 1)-1);\n\n  cout << \".\" << flush;\n\n  vec_ZZ_pX factors;\n  //SFBerlekamp(factors, phi);\n  if (p==ZZ(2))\n    SFCanZass(factors, phi);\n  else\n    RootEDF(factors, phi);\n\n  ZZ_pX G = ZZ_pX(1);\n  for (long i = 1; i < factors.length(); ++i) G *= factors[i];\n  ZZ_pX a, b, c;\n  XGCD(a, b, c, factors[0], G); // 1 = a = b * factors[0] + c * G\n  ZZ_pX res1 = c*G;\n  \n  // ZZ_pX res2 = (res1*res1) % phi;\n  // if (res1 != res2) {\n  //   cout << \"Error in resolution_of_one\" << endl;\n  //   cout << \"res   = \" << res1 << endl;\n  //   cout << \"res2  = \" << res2 << endl;\n  //   exit(-1);\n  // }\n  \n  res = conv<ZZX>(res1);\n  context.restore();\n}\n\nvoid ring::lift_resolution (ZZX& res, const long m, const ZZ& r, const long l) {\n  ZZ_p::init(power(r, l));\n  ZZ_pX phi = (ZZ_pX(INIT_MONO, m)-1)/(ZZ_pX(INIT_MONO, 1)-1);\n\n  ZZ_pX x = conv<ZZ_pX>(-res);\n  for (long j = 0; j < l-1; ++j) {\n    if ((j % 100) == 0) cout << \".\" << flush;\n    x = (power(x+1, conv<long>(r)) - 1) % phi;\n  }\n  res = conv<ZZX>(-x);\n}\n\nvoid ring::canonical_resolution_of_one (ZZX& res, long prec) {\n  resolution_of_one(res, mR, ZZ(pR));\n  lift_resolution(res, mR, ZZ(pR), prec);    \n}\n\nvoid ring::init_resolution (long prec) {\n  if (type == prime) {\n    canonical_resolution_of_one(res, prec);\n  }\n  else { // ring is composite\n    if (left->initialized == false)\n      left->init_resolution(prec);\n    if (right->initialized == false)\n      right->init_resolution(prec);\n  }\n}\n\nvoid ring::init (long prec, noise& ns) {\n  if (initialized == true) return;\n\n  cout << \"Initializing ring \" << label << flush;\n  \n  init_resolution(prec);\n  \n  cout << \"computing omega...\" << flush;\n  init_omega(power(ZZ(2), prec));\n\n  depth = get_subrings(subrings);\n\n  initialized = true;\n  cout << \"done\" << endl;\n}\n\n/***********************************************************************/\n// Transpose a (m*n)-dim. vector 'a'\n// into a m x n matrix (m-dim vector of n-dim vector)'w'\nvoid mat (Vec<double*>& aa, const double* a, const long n, const long m) {\n  for (long j = 0; j < m; ++j)\n    for (long i = 0; i < n; ++i)\n      aa[j][i] = a[i + n*j];\n}\n\nvoid transpose (Vec<double*>& b, Vec<double*>& a) {\n  long m = a.length();\n  long n = b.length();\n\n  for (long i = 0; i < m; ++i)\n    for (long j = 0; j < n; ++j)\n      b[j][i] = a[i][j];  \n}\n\nvoid vec (double* b, const Vec<double*>& a, long n) {\n  long m = a.length();\n\n  for (long i = 0; i < m; ++i)\n    for (long j = 0; j < n; ++j)\n      b[i*n+j] = a[i][j];\n}\n\n/***************************************************************************/\n// (Omega)_{i,j} = (rho_{t_i}(eta_j))\nvoid ring::comp_omega (vec_ZZ& o, ZZ& q) {\n  ZZX phi = (ZZX(INIT_MONO, mR)-1)/(ZZX(INIT_MONO, 1)-1);\n\n  ZZ_p::init(q);\n  \n  o.SetLength(gR);\n  for (long i = 0; i < gR; ++i) {\n    if ((i % 100) == 0) cout << \".\" << flush;\n    ZZ_pX e = conv<ZZ_pX>(eta(i));\n    ZZ_pX a = (e * conv<ZZ_pX>(res)) % conv<ZZ_pX>(phi);\n    ZZX aa = conv<ZZX>(a);\n    o[i] = scalar_quo(aa, res, q);\n  }\n}\n\nvoid ring::comp_omega_inv (vec_ZZ& o, const vec_ZZ& _omega, const ZZ& q) {\n  o.SetLength(gR);\n  \n  for (long i = 0; i < gR; ++i) {\n    ZZ w, conj_eta;\n    if ((dR % 2) == 1) conj_eta = _omega[(i+gR/2) % gR];\n    else conj_eta = _omega[i];\n    w = conj_eta - dR;\n    w = (w * InvMod(ZZ(mR)%q, q)) % q;\n    o[i] = w;\n  }  \n}\n\n// (Gamma)_{i,j} = (rho_{t_i}(eta_j - d))\nvoid ring::comp_gamma (vec_ZZ& o, const vec_ZZ& _omega, const ZZ& q) {\n  o.SetLength(gR);\n\n  for (long i = 0; i < gR; ++i) {\n    o[i] = (omega[i] - dR) % q;\n  }  \n}\n\nvoid ring::comp_gamma_inv (vec_ZZ& o, const vec_ZZ& _omega, const ZZ& q) {\n  o.SetLength(gR);\n  \n  for (long i = 0; i < gR; ++i) {\n    ZZ conj_eta;\n    if ((dR % 2) == 1) conj_eta = _omega[(i+gR/2) % gR];\n    else conj_eta = _omega[i];\n    o[i] = (conj_eta * InvMod(ZZ(mR)%q, q)) % q;\n  }  \n}\n\nvoid ring::init_omega (ZZ q) {\n  if (type == prime) {\n    comp_omega(omega, q);\n    comp_omega_inv(omega_inv, omega, q);\n  }\n  else { // ring type is composite\n    if (left->initialized == false)\n      left->init_omega(q);\n    if (right->initialized == false)\n      right->init_omega(q);\n  }\n}\n\nvoid param::init (long prec) {\n  rg.init(prec, ns);  \n}\n\n", "meta": {"hexsha": "25f2d133c17358798da5ed5f0fad5dd2075d778a", "size": 7184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ring_init.cpp", "max_stars_repo_name": "aritalab/SRHE", "max_stars_repo_head_hexsha": "38161f1e62edc72a6d0afa638d057579f7005095", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ring_init.cpp", "max_issues_repo_name": "aritalab/SRHE", "max_issues_repo_head_hexsha": "38161f1e62edc72a6d0afa638d057579f7005095", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ring_init.cpp", "max_forks_repo_name": "aritalab/SRHE", "max_forks_repo_head_hexsha": "38161f1e62edc72a6d0afa638d057579f7005095", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8671096346, "max_line_length": 85, "alphanum_fraction": 0.5025055679, "num_tokens": 2751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4479721567868536}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2014 Alec Jacobson <alecjacobson@gmail.com>\n// \n// This Source Code Form is subject to the terms of the Mozilla Public License \n// v. 2.0. If a copy of the MPL was not distributed with this file, You can \n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"harmonic.h\"\n#include \"cotmatrix.h\"\n#include \"massmatrix.h\"\n#include \"invert_diag.h\"\n#include \"min_quad_with_fixed.h\"\n#include <Eigen/Sparse>\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename Derivedb,\n  typename Derivedbc,\n  typename DerivedW>\nIGL_INLINE bool igl::harmonic(\n  const Eigen::PlainObjectBase<DerivedV> & V,\n  const Eigen::PlainObjectBase<DerivedF> & F,\n  const Eigen::PlainObjectBase<Derivedb> & b,\n  const Eigen::PlainObjectBase<Derivedbc> & bc,\n  const int k,\n  Eigen::PlainObjectBase<DerivedW> & W)\n{\n  using namespace Eigen;\n  typedef typename DerivedV::Scalar Scalar;\n  typedef Matrix<Scalar,Dynamic,1> VectorXS;\n  SparseMatrix<Scalar> L,M,Mi;\n  cotmatrix(V,F,L);\n  switch(F.cols())\n  {\n    case 3:\n      massmatrix(V,F,MASSMATRIX_TYPE_VORONOI,M);\n      break;\n    case 4:\n    default:\n      massmatrix(V,F,MASSMATRIX_TYPE_BARYCENTRIC,M);\n      break;\n  }\n  invert_diag(M,Mi);\n  SparseMatrix<Scalar> Q = -L;\n  for(int p = 1;p<k;p++)\n  {\n    Q = (Q*Mi*-L).eval();\n  }\n  const VectorXS B = VectorXS::Zero(V.rows(),1);\n  min_quad_with_fixed_data<Scalar> data;\n  min_quad_with_fixed_precompute(Q,b,SparseMatrix<Scalar>(),true,data);\n  W.resize(V.rows(),bc.cols());\n  for(int w = 0;w<bc.cols();w++)\n  {\n    const VectorXS bcw = bc.col(w);\n    VectorXS Ww;\n    if(!min_quad_with_fixed_solve(data,B,bcw,VectorXS(),Ww))\n    {\n      return false;\n    }\n    W.col(w) = Ww;\n  }\n  return true;\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\ntemplate bool igl::harmonic<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&); \ntemplate bool igl::harmonic<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\n#endif\n", "meta": {"hexsha": "6aecdd7b538c834560cffa6191435527fe16e2f3", "size": 3023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/include/igl/harmonic.cpp", "max_stars_repo_name": "FabianRepository/SinusProject", "max_stars_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/include/igl/harmonic.cpp", "max_issues_repo_name": "FabianRepository/SinusProject", "max_issues_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/include/igl/harmonic.cpp", "max_forks_repo_name": "FabianRepository/SinusProject", "max_forks_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9861111111, "max_line_length": 592, "alphanum_fraction": 0.6520013232, "num_tokens": 1044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.44797215227816667}}
{"text": "/* boost random/fisher_f_distribution.hpp header file\n *\n * Copyright Steven Watanabe 2011\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id$\n */\n\n#ifndef BOOST_RANDOM_FISHER_F_DISTRIBUTION_HPP\n#define BOOST_RANDOM_FISHER_F_DISTRIBUTION_HPP\n\n#include <iosfwd>\n#include <istream>\n#include <boost/config.hpp>\n#include <boost/limits.hpp>\n#include <boost/random/detail/operators.hpp>\n#include <boost/random/chi_squared_distribution.hpp>\n\nnamespace boost {\nnamespace random {\n\n/**\n * The Fisher F distribution is a real valued distribution with two\n * parameters m and n.\n *\n * It has \\f$\\displaystyle p(x) =\n *   \\frac{\\Gamma((m+n)/2)}{\\Gamma(m/2)\\Gamma(n/2)}\n *   \\left(\\frac{m}{n}\\right)^{m/2}\n *   x^{(m/2)-1} \\left(1+\\frac{mx}{n}\\right)^{-(m+n)/2}\n * \\f$.\n */\ntemplate<class RealType = double>\nclass fisher_f_distribution {\npublic:\n    typedef RealType result_type;\n    typedef RealType input_type;\n\n    class param_type {\n    public:\n        typedef fisher_f_distribution distribution_type;\n\n        /**\n         * Constructs a @c param_type from the \"m\" and \"n\" parameters\n         * of the distribution.\n         *\n         * Requires: m > 0 and n > 0\n         */\n        explicit param_type(RealType m_arg = RealType(1.0),\n                            RealType n_arg = RealType(1.0))\n          : _m(m_arg), _n(n_arg)\n        {}\n\n        /** Returns the \"m\" parameter of the distribtuion. */\n        RealType m() const { return _m; }\n        /** Returns the \"n\" parameter of the distribution. */\n        RealType n() const { return _n; }\n\n        /** Writes a @c param_type to a @c std::ostream. */\n        BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm)\n        { os << parm._m << ' ' << parm._n; return os; }\n\n        /** Reads a @c param_type from a @c std::istream. */\n        BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm)\n        { is >> parm._m >> std::ws >> parm._n; return is; }\n\n        /** Returns true if the two sets of parameters are the same. */\n        BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs)\n        { return lhs._m == rhs._m && lhs._n == rhs._n; }\n\n        /** Returns true if the two sets of parameters are the different. */\n        BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type)\n\n    private:\n        RealType _m;\n        RealType _n;\n    };\n\n    /**\n     * Constructs a @c fisher_f_distribution from its \"m\" and \"n\" parameters.\n     *\n     * Requires: m > 0 and n > 0\n     */\n    explicit fisher_f_distribution(RealType m_arg = RealType(1.0),\n                                   RealType n_arg = RealType(1.0))\n      : _impl_m(m_arg), _impl_n(n_arg)\n    {}\n    /** Constructs an @c fisher_f_distribution from its parameters. */\n    explicit fisher_f_distribution(const param_type& parm)\n      : _impl_m(parm.m()), _impl_n(parm.n())\n    {}\n\n    /**\n     * Returns a random variate distributed according to the\n     * F distribution.\n     */\n    template<class URNG>\n    RealType operator()(URNG& urng)\n    {\n        return (_impl_m(urng) * n()) / (_impl_n(urng) * m());\n    }\n\n    /**\n     * Returns a random variate distributed according to the\n     * F distribution with parameters specified by @c param.\n     */\n    template<class URNG>\n    RealType operator()(URNG& urng, const param_type& parm) const\n    {\n        return fisher_f_distribution(parm)(urng);\n    }\n\n    /** Returns the \"m\" parameter of the distribution. */\n    RealType m() const { return _impl_m.n(); }\n    /** Returns the \"n\" parameter of the distribution. */\n    RealType n() const { return _impl_n.n(); }\n\n    /** Returns the smallest value that the distribution can produce. */\n    RealType min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return 0; }\n    /** Returns the largest value that the distribution can produce. */\n    RealType max BOOST_PREVENT_MACRO_SUBSTITUTION () const\n    { return std::numeric_limits<RealType>::infinity(); }\n\n    /** Returns the parameters of the distribution. */\n    param_type param() const { return param_type(m(), n()); }\n    /** Sets the parameters of the distribution. */\n    void param(const param_type& parm)\n    {\n        typedef chi_squared_distribution<RealType> impl_type;\n        typename impl_type::param_type m_param(parm.m());\n        _impl_m.param(m_param);\n        typename impl_type::param_type n_param(parm.n());\n        _impl_n.param(n_param);\n    }\n\n    /**\n     * Effects: Subsequent uses of the distribution do not depend\n     * on values produced by any engine prior to invoking reset.\n     */\n    void reset() { }\n\n    /** Writes an @c fisher_f_distribution to a @c std::ostream. */\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, fisher_f_distribution, fd)\n    {\n        os << fd.param();\n        return os;\n    }\n\n    /** Reads an @c fisher_f_distribution from a @c std::istream. */\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, fisher_f_distribution, fd)\n    {\n        param_type parm;\n        if(is >> parm) {\n            fd.param(parm);\n        }\n        return is;\n    }\n\n    /**\n     * Returns true if the two instances of @c fisher_f_distribution will\n     * return identical sequences of values given equal generators.\n     */\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(fisher_f_distribution, lhs, rhs)\n    { return lhs._impl_m == rhs._impl_m && lhs._impl_n == rhs._impl_n; }\n\n    /**\n     * Returns true if the two instances of @c fisher_f_distribution will\n     * return different sequences of values given equal generators.\n     */\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(fisher_f_distribution)\n\nprivate:\n    chi_squared_distribution<RealType> _impl_m;\n    chi_squared_distribution<RealType> _impl_n;\n};\n\n} // namespace random\n} // namespace boost\n\n#endif // BOOST_RANDOM_EXTREME_VALUE_DISTRIBUTION_HPP\n", "meta": {"hexsha": "dc2f1a6d2c2e6f98105eaffbcaf3622a77a98b46", "size": 5912, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/random/fisher_f_distribution.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/random/fisher_f_distribution.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/random/fisher_f_distribution.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 32.1304347826, "max_line_length": 77, "alphanum_fraction": 0.6430987821, "num_tokens": 1459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.44794426072931237}}
{"text": "/* boost random/mixmax.hpp header file\n *\n * Copyright Kostas Savvidis 2008-2019\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id$\n *\n * Revision history\n *  2019-04-23 created\n */\n\n#ifndef BOOST_RANDOM_MIXMAX_HPP\n#define BOOST_RANDOM_MIXMAX_HPP\n\n#include <sstream>\n#include <boost/cstdint.hpp>\n#include <boost/array.hpp>\n\n#include <boost/random/detail/seed.hpp>\n#include <boost/random/detail/seed_impl.hpp>\n\nnamespace boost {\nnamespace random {\n\n/**\n * Instantiations of class template mixmax_engine model,\n * \\pseudo_random_number_generator .\n *  It uses the  MIXMAX generator algorithms from:\n *\n *  @blockquote\n *  G.K.Savvidy and N.G.Ter-Arutyunian,\n *  On the Monte Carlo simulation of physical systems,\n *  J.Comput.Phys. 97, 566 (1991);\n *  Preprint EPI-865-16-86, Yerevan, Jan. 1986\n *  http://dx.doi.org/10.1016/0021-9991(91)90015-D\n *\n *  K.Savvidy\n *  The MIXMAX random number generator\n *  Comp. Phys. Commun. 196 (2015), pp 161–165\n *  http://dx.doi.org/10.1016/j.cpc.2015.06.003\n *\n *  K.Savvidy and G.Savvidy\n *  Spectrum and Entropy of C-systems. MIXMAX random number generator\n *  Chaos, Solitons & Fractals, Volume 91, (2016) pp. 33–38\n *  http://dx.doi.org/10.1016/j.chaos.2016.05.003\n *  @endblockquote\n *\n * The generator crucially depends on the choice of the\n * parameters. The valid sets of parameters are from the published papers above.\n *\n */\n\ntemplate <int Ndim, unsigned int SPECIALMUL, boost::int64_t SPECIAL> // MIXMAX TEMPLATE PARAMETERS\nclass mixmax_engine{\npublic:\n    // Interfaces required by C++11 std::random and boost::random\n    typedef boost::uint64_t result_type ;\n    BOOST_STATIC_CONSTANT(boost::uint64_t,mixmax_min=0);\n    BOOST_STATIC_CONSTANT(boost::uint64_t,mixmax_max=((1ULL<<61)-1));\n    BOOST_STATIC_CONSTEXPR result_type min BOOST_PREVENT_MACRO_SUBSTITUTION() {return mixmax_min;}\n    BOOST_STATIC_CONSTEXPR result_type max BOOST_PREVENT_MACRO_SUBSTITUTION() {return mixmax_max;}\n    static const bool has_fixed_range = false;\n    BOOST_STATIC_CONSTANT(int,N=Ndim);     ///< The main internal parameter, size of the defining MIXMAX matrix\n    // CONSTRUCTORS:\n    explicit mixmax_engine();                       ///< Constructor, unit vector as initial state, acted on by A^2^512\n    explicit mixmax_engine(boost::uint64_t);          ///< Constructor, one 64-bit seed\n    explicit mixmax_engine(uint32_t clusterID, uint32_t machineID, uint32_t runID, uint32_t  streamID );  ///< Constructor, four 32-bit seeds for 128-bit seeding flexibility\n    void seed(boost::uint64_t seedval=default_seed){seed_uniquestream( &S, 0, 0, (uint32_t)(seedval>>32), (uint32_t)seedval );} ///< seed with one 64-bit seed\n    \nprivate: // DATATYPES\n    struct rng_state_st{\n        boost::array<boost::uint64_t, Ndim> V;\n        boost::uint64_t sumtot;\n        int counter;\n    };\n    \n    typedef struct rng_state_st rng_state_t;     // struct alias\n    rng_state_t S;\n    \npublic: // SEEDING FUNCTIONS\n    template<class It> mixmax_engine(It& first, It last) { seed(first,last); }\n    BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(mixmax_engine,  SeedSeq, seq){ seed(seq); }\n    \n    /** Sets the state of the generator using values from an iterator range. */\n    template<class It>\n    void seed(It& first, It last){\n        uint32_t v[4];\n        detail::fill_array_int<32>(first, last, v);\n        seed_uniquestream( &S, v[0], v[1], v[2], v[3]);\n    }\n    /** Sets the state of the generator using values from a seed_seq. */\n    BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(mixmax_engine, SeeqSeq, seq){\n        uint32_t v[4];\n        detail::seed_array_int<32>(seq, v);\n        seed_uniquestream( &S, v[0], v[1], v[2], v[3]);\n    }\n    \n    /** return one uint64 between min=0 and max=2^61-1 */\n    boost::uint64_t operator()(){\n        if (S.counter<=(Ndim-1) ){\n            return S.V[S.counter++];\n        }else{\n            S.sumtot = iterate_raw_vec(S.V.data(), S.sumtot);\n            S.counter=2;\n            return S.V[1];\n        }\n    }\n    \n    /** Fills a range with random values */\n    template<class Iter>\n    void generate(Iter first, Iter last) { detail::generate_from_int(*this, first, last); }\n    \n    void discard(boost::uint64_t nsteps) { for(boost::uint64_t j = 0; j < nsteps; ++j)  (*this)(); } ///< discard n steps, required in boost::random\n    \n    /** save the state of the RNG to a stream */\n    template<class CharT, class Traits>\n    friend std::basic_ostream<CharT,Traits>&\n    operator<< (std::basic_ostream<CharT,Traits>& ost, const mixmax_engine& me){\n        ost << Ndim << \" \" << me.S.counter << \" \" << me.S.sumtot << \" \";\n        for (int j=0; (j< (Ndim) ); j++) {\n        ost <<  (boost::uint64_t)me.S.V[j] << \" \";\n        }\n        ost << \"\\n\";\n        ost.flush();\n        return ost;\n        }\n        \n    /** read the state of the RNG from a stream */\n    template<class CharT, class Traits>\n    friend std::basic_istream<CharT,Traits>&\n    operator>> (std::basic_istream<CharT,Traits> &in, mixmax_engine& me){\n        // will set std::ios::failbit if the input format is not right\n        boost::array<boost::uint64_t, Ndim> vec;\n        boost::uint64_t sum=0, savedsum=0, counter=0;\n        in >> counter >> std::ws;\n        BOOST_ASSERT(counter==Ndim);\n        in >> counter >> std::ws;\n        in >> savedsum >> std::ws;\n        for(int j=0;j<Ndim;j++) {\n        in >> std::ws >> vec[j] ;\n        sum=me.MOD_MERSENNE(sum+vec[j]);\n    }\n    if (sum == savedsum && counter>0 && counter<Ndim){\n        me.S.V=vec; me.S.counter = counter; me.S.sumtot=savedsum;\n    }else{\n        in.setstate(std::ios::failbit);\n    }\n    return in;\n    }\n\nfriend bool operator==(const mixmax_engine & x,\n                       const mixmax_engine & y){return x.S.counter==y.S.counter && x.S.sumtot==y.S.sumtot && x.S.V==y.S.V ;}\nfriend bool operator!=(const mixmax_engine & x,\n                       const mixmax_engine & y){return !operator==(x,y);}\n\n\nprivate:\nBOOST_STATIC_CONSTANT(int, BITS=61);\nBOOST_STATIC_CONSTANT(boost::uint64_t, M61=2305843009213693951ULL);\nBOOST_STATIC_CONSTANT(boost::uint64_t, default_seed=1);\ninline boost::uint64_t MOD_MERSENNE(boost::uint64_t k) {return ((((k)) & M61) + (((k)) >> BITS) );}\ninline boost::uint64_t MULWU(boost::uint64_t k);\ninline void seed_vielbein(rng_state_t* X, unsigned int i); // seeds with the i-th unit vector, i = 0..Ndim-1,  for testing only\ninline void seed_uniquestream( rng_state_t* Xin, uint32_t clusterID, uint32_t machineID, uint32_t runID, uint32_t  streamID );\ninline boost::uint64_t iterate_raw_vec(boost::uint64_t* Y, boost::uint64_t sumtotOld);\ninline boost::uint64_t apply_bigskip(boost::uint64_t* Vout, boost::uint64_t* Vin, uint32_t clusterID, uint32_t machineID, uint32_t runID, uint32_t  streamID );\ninline boost::uint64_t modadd(boost::uint64_t foo, boost::uint64_t bar);\ninline boost::uint64_t fmodmulM61(boost::uint64_t cum, boost::uint64_t s, boost::uint64_t a);\n};\n\ntemplate <int Ndim, unsigned int SPECIALMUL, boost::int64_t SPECIAL> mixmax_engine  <Ndim, SPECIALMUL, SPECIAL> ::mixmax_engine()\n///< constructor, with no params, seeds with seed=0,  random numbers are as good as from any other seed\n{\n    seed_uniquestream( &S, 0,  0, 0, default_seed);\n}\n\ntemplate <int Ndim, unsigned int SPECIALMUL, boost::int64_t SPECIAL> mixmax_engine  <Ndim, SPECIALMUL, SPECIAL> ::mixmax_engine(boost::uint64_t seedval){\n    ///< constructor, one uint64_t seed, random numbers are statistically independent from any two distinct seeds, e.g. consecutive seeds are ok\n    seed_uniquestream( &S, 0,  0,  (uint32_t)(seedval>>32), (uint32_t)seedval );\n}\n\ntemplate <int Ndim, unsigned int SPECIALMUL, boost::int64_t SPECIAL> mixmax_engine  <Ndim, SPECIALMUL, SPECIAL> ::mixmax_engine(uint32_t clusterID, uint32_t machineID, uint32_t runID, uint32_t  streamID){\n    // constructor, four 32-bit seeds for 128-bit seeding flexibility\n    seed_uniquestream( &S, clusterID,  machineID,  runID,  streamID );\n}\n\ntemplate <int Ndim, unsigned int SPECIALMUL, boost::int64_t SPECIAL> uint64_t mixmax_engine  <Ndim, SPECIALMUL, SPECIAL> ::MULWU (uint64_t k){ return (( (k)<<(SPECIALMUL) & M61) ^ ( (k) >> (BITS-SPECIALMUL))  )  ;}\n\ntemplate <int Ndim, unsigned int SPECIALMUL, boost::int64_t SPECIAL> boost::uint64_t mixmax_engine  <Ndim, SPECIALMUL, SPECIAL> ::iterate_raw_vec(boost::uint64_t* Y, boost::uint64_t sumtotOld){\n    // operates with a raw vector, uses known sum of elements of Y\n    boost::uint64_t  tempP=0, tempV=sumtotOld;\n    Y[0] = tempV;\n    boost::uint64_t sumtot = Y[0], ovflow = 0; // will keep a running sum of all new elements\n    for (int i=1; i<Ndim; i++){\n        boost::uint64_t tempPO = MULWU(tempP);\n        tempV = (tempV+tempPO);\n        tempP = modadd(tempP, Y[i]);\n        tempV = modadd(tempV, tempP); // new Y[i] = old Y[i] + old partial * m\n        Y[i] = tempV;\n        sumtot += tempV; if (sumtot < tempV) {ovflow++;}\n    }\n    return MOD_MERSENNE(MOD_MERSENNE(sumtot) + (ovflow <<3 ));\n}\n\ntemplate <int Ndim, unsigned int SPECIALMUL, boost::int64_t SPECIAL> void mixmax_engine  <Ndim, SPECIALMUL, SPECIAL> ::seed_vielbein(rng_state_t* X, unsigned int index){\n    for (int i=0; i < Ndim; i++){\n        X->V[i] = 0;\n    }\n    if (index<Ndim) { X->V[index] = 1; }else{ X->V[0]=1; }\n    X->counter = Ndim;  // set the counter to Ndim if iteration should happen right away\n    X->sumtot = 1;\n}\n\n\ntemplate <int Ndim, unsigned int SPECIALMUL, boost::int64_t SPECIAL> void mixmax_engine  <Ndim, SPECIALMUL, SPECIAL> ::seed_uniquestream( rng_state_t* Xin, uint32_t clusterID, uint32_t machineID, uint32_t runID, uint32_t  streamID ){\n    seed_vielbein(Xin,0);\n    Xin->sumtot = apply_bigskip(Xin->V.data(), Xin->V.data(),  clusterID,  machineID,  runID,   streamID );\n    Xin->counter = 1;\n}\n\n\ntemplate <int Ndim, unsigned int SPECIALMUL, boost::int64_t SPECIAL> boost::uint64_t mixmax_engine  <Ndim, SPECIALMUL, SPECIAL> ::apply_bigskip( boost::uint64_t* Vout, boost::uint64_t* Vin, uint32_t clusterID, uint32_t machineID, uint32_t runID, uint32_t  streamID ){\n    /*\n     makes a derived state vector, Vout, from the mother state vector Vin\n     by skipping a large number of steps, determined by the given seeding ID's\n     \n     it is mathematically guaranteed that the substreams derived in this way from the SAME (!!!) Vin will not collide provided\n     1) at least one bit of ID is different\n     2) less than 10^100 numbers are drawn from the stream\n     (this is good enough : a single CPU will not exceed this in the lifetime of the universe, 10^19 sec,\n     even if it had a clock cycle of Planck time, 10^44 Hz )\n     \n     Caution: never apply this to a derived vector, just choose some mother vector Vin, for example the unit vector by seed_vielbein(X,0),\n     and use it in all your runs, just change runID to get completely nonoverlapping streams of random numbers on a different day.\n     \n     clusterID and machineID are provided for the benefit of large organizations who wish to ensure that a simulation\n     which is running in parallel on a large number of  clusters and machines will have non-colliding source of random numbers.\n     \n     did i repeat it enough times? the non-collision guarantee is absolute, not probabilistic\n     \n     */\n    \n    \n    const    boost::uint64_t skipMat17[128][17] =\n#include \"boost/random/detail/mixmax_skip_N17.ipp\"\n    ;\n    \n    const boost::uint64_t* skipMat[128];\n    BOOST_ASSERT(Ndim==17);\n    for (int i=0; i<128; i++) { skipMat[i] = skipMat17[i];}\n    \n    uint32_t IDvec[4] = {streamID, runID, machineID, clusterID};\n    boost::uint64_t Y[Ndim], cum[Ndim];\n    boost::uint64_t sumtot=0;\n    \n    for (int i=0; i<Ndim; i++) { Y[i] = Vin[i]; sumtot = modadd( sumtot, Vin[i]); } ;\n    for (int IDindex=0; IDindex<4; IDindex++) { // go from lower order to higher order ID\n        uint32_t id=IDvec[IDindex];\n        int r = 0;\n        while (id){\n            if (id & 1) {\n                boost::uint64_t* rowPtr = (boost::uint64_t*)skipMat[r + IDindex*8*sizeof(uint32_t)];\n                for (int i=0; i<Ndim; i++){ cum[i] = 0; }\n                for (int j=0; j<Ndim; j++){              // j is lag, enumerates terms of the poly\n                    // for zero lag Y is already given\n                    boost::uint64_t coeff = rowPtr[j]; // same coeff for all i\n                    for (int i =0; i<Ndim; i++){\n                        cum[i] =  fmodmulM61( cum[i], coeff ,  Y[i] ) ;\n                    }\n                    sumtot = iterate_raw_vec(Y, sumtot);\n                }\n                sumtot=0;\n                for (int i=0; i<Ndim; i++){ Y[i] = cum[i]; sumtot = modadd( sumtot, cum[i]); } ;\n            }\n            id = (id >> 1); r++; // bring up the r-th bit in the ID\n        }\n    }\n    sumtot=0;\n    for (int i=0; i<Ndim; i++){ Vout[i] = Y[i]; sumtot = modadd( sumtot, Y[i]); } ;  // returns sumtot, and copy the vector over to Vout\n    return (sumtot) ;\n}\n\ntemplate <int Ndim, unsigned int SPECIALMUL, boost::int64_t SPECIAL> inline boost::uint64_t mixmax_engine  <Ndim, SPECIALMUL, SPECIAL> ::fmodmulM61(boost::uint64_t cum, boost::uint64_t s, boost::uint64_t a){\n    // works on all platforms, including 32-bit linux, PPC and PPC64, ARM and Windows\n    const boost::uint64_t MASK32=0xFFFFFFFFULL;\n    boost::uint64_t o,ph,pl,ah,al;\n    o=(s)*a;\n    ph = ((s)>>32);\n    pl = (s) & MASK32;\n    ah = a>>32;\n    al = a & MASK32;\n    o = (o & M61) + ((ph*ah)<<3) + ((ah*pl+al*ph + ((al*pl)>>32))>>29) ;\n    o += cum;\n    o = (o & M61) + ((o>>61));\n    return o;\n}\n\ntemplate <int Ndim, unsigned int SPECIALMUL, boost::int64_t SPECIAL> boost::uint64_t mixmax_engine  <Ndim, SPECIALMUL, SPECIAL> ::modadd(boost::uint64_t foo, boost::uint64_t bar){\n    return MOD_MERSENNE(foo+bar);\n}\n\n/* @copydoc boost::random::detail::mixmax_engine_doc */\n/** Instantiation with a valid parameter set. */\ntypedef mixmax_engine<17,36,0>          mixmax;\n}// namespace random\n}// namespace boost\n\n#endif // BOOST_RANDOM_MIXMAX_HPP\n", "meta": {"hexsha": "3f09fc323612d159ef821419335ab237a64795b2", "size": 14131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/random/mixmax.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2728.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T10:06:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T18:12:58.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/random/mixmax.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1192.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T06:03:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T09:14:36.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/random/mixmax.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 334.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T20:47:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T07:07:01.000Z", "avg_line_length": 45.0031847134, "max_line_length": 267, "alphanum_fraction": 0.653173873, "num_tokens": 4178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4479438727888907}}
{"text": "// Copyright (c) Dietmar Wolz.\r\n//\r\n// This source code is licensed under the MIT license found in the\r\n// LICENSE file in the root directory.\r\n\r\n// Eigen based implementation of multi objective\r\n// Differential Evolution using the DE/all/1 strategy.\r\n//\r\n// Can switch to NSGA-II like population update via parameter 'nsga_update'.\r\n// Then it works essentially like NSGA-II but instead of the tournament selection\r\n// the whole population is sorted and the best individuals survive. To do this\r\n// efficiently the crowd distance ordering is slightly inaccurate.\r\n//\r\n// Supports parallel fitness function evaluation.\r\n//\r\n// Features enhanced multiple constraint ranking (https://www.jstage.jst.go.jp/article/tjpnsec/11/2/11_18/_article/-char/en/)\r\n// improving its performance in handling constraints for engineering design optimization.\r\n//\r\n// Enables the comparison of DE and NSGA-II population update mechanism with everything else\r\n// kept completely identical.\r\n//\r\n// Uses the following deviation from the standard DE algorithm:\r\n// a) oscillating CR/F parameters.\r\n//\r\n// You may keep parameters F and CR at their defaults since this implementation works well with the given settings for most problems,\r\n// since the algorithm oscillates between different F and CR settings.\r\n//\r\n// For expensive objective functions (e.g. machine learning parameter optimization) use the workers\r\n// parameter to parallelize objective function evaluation. The workers parameter is limited by the\r\n// population size.\r\n\r\n#include <Eigen/Core>\r\n#include <iostream>\r\n#include <float.h>\r\n#include <stdint.h>\r\n#include <ctime>\r\n#include <random>\r\n#include <queue>\r\n#include <tuple>\r\n#include \"pcg_random.hpp\"\r\n#include \"evaluator.h\"\r\n\r\nnamespace mode_optimizer {\r\n\r\nclass MoDeOptimizer {\r\n\r\npublic:\r\n\r\n    MoDeOptimizer(long runid_, Fitness *fitfun_, callback_type log_, int dim_,\r\n    \t\tint nobj_, int ncon_, int seed_,\r\n            int popsize_, int maxEvaluations_, double F_, double CR_,\r\n            double pro_c_, double dis_c_, double pro_m_, double dis_m_,\r\n            bool nsga_update_, double pareto_update_, int log_period_) {\r\n        // runid used to identify a specific run\r\n        runid = runid_;\r\n        // fitness function to minimize\r\n        fitfun = fitfun_;\r\n        // callback to log progress\r\n        log = log_;\r\n        // Number of objective variables/problem dimension\r\n        dim = dim_;\r\n        // Number of objectives\r\n        nobj = nobj_;\r\n        // Number of constraints\r\n        ncon = ncon_;\r\n        // Population size\r\n        popsize = popsize_ > 0 ? popsize_ : 128;\r\n        // maximal number of evaluations allowed.\r\n        maxEvaluations = maxEvaluations_ > 0 ? maxEvaluations_ : 500000;\r\n        // DE population update parameters, ignored if nsga_update == true\r\n        F = F0 = F_ > 0 ? F_ : 0.5;\r\n        CR = CR0 = CR_ > 0 ? CR_ : 0.9;\r\n        // Number of iterations already performed.\r\n        iterations = 0;\r\n        // Number of evaluations already performed.\r\n        n_evals = 0;\r\n        // position of current x/y\r\n        pos = 0;\r\n        //std::random_device rd;\r\n        rs = new pcg64(seed_);\r\n        // NSGA population update parameters, ignored if nsga_update == false\r\n   \t    // usually use pro_c = 1.0, dis_c = 20.0, pro_m = 1.0, dis_m = 20.0.\r\n    \tpro_c = pro_c_;\r\n    \tdis_c = dis_c_;\r\n    \tpro_m = pro_m_;\r\n    \tdis_m = dis_m_;\r\n        // if true, use NSGA population update, if false, use DE population update\r\n        // Use DE update to diversify your results.\r\n    \tnsga_update = nsga_update_;\r\n        // DE population update parameter. Only applied if nsga_update = false.\r\n    \t// Use the pareto front for population update\r\n    \t// with probability pareto_update, else use the whole population.\r\n    \t// If pareto_update == 0: use always the whole population.\r\n        // usually should be 0, optimization can get stuck in local minima otherwise.\r\n    \tpareto_update = pareto_update_;\r\n        // The log callback is called each log_period iterations \r\n        log_period = log_period_;\r\n        if (log_period <= 0)\r\n            log_period = 1000;\r\n        init();\r\n    }\r\n\r\n    ~MoDeOptimizer() {\r\n        delete rs;\r\n    }\r\n\r\n    double rnd01() {\r\n        return distr_01(*rs);\r\n    }\r\n\r\n    int rndInt(int max) {\r\n        return (int) (max * distr_01(*rs));\r\n    }\r\n\r\n    vec nextX(int p) {\r\n        if (p == 0) {\r\n            iterations++;\r\n        \tif (iterations % log_period == 0) {\r\n        \t\tif (log(popX.cols(), popX.data(), popY.data()))\r\n        \t\t\tfitfun->setTerminate();\r\n        \t}\r\n        }\r\n    \tif (nsga_update) {\r\n    \t\tvec x = vX.col(vp);\r\n    \t\tvp = (vp + 1) % popsize;\r\n    \t\treturn x;\r\n    \t}\r\n    \t// use DE update strategy.\r\n        if (p == 0) {\r\n            CR = iterations % 2 == 0 ? 0.5 * CR0 : CR0;\r\n            F = iterations % 2 == 0 ? 0.5 * F0 : F0;\r\n        }\r\n        int r3;\r\n        if (rnd01() < pareto_update) {\r\n\t\t\t// sample from pareto front\r\n            do {\r\n            \tr3 = rndInt(bestP.size());\r\n            \tr3 = bestP[r3];\r\n            } while (r3 == p);\r\n        } else {\r\n\t\t\t// sample from whole population\r\n            do {\r\n                r3 = rndInt(popsize);\r\n            } while (r3 == p);\r\n        }\r\n        vec xp = popX.col(p);\r\n        vec x3 = popX.col(r3);\r\n        int r1, r2;\r\n        do {\r\n            r1 = rndInt(popsize);\r\n        } while (r1 == p || r1 == r3);\r\n        do {\r\n            r2 = rndInt(popsize);\r\n        } while (r2 == p || r2 == r3 || r2 == r1);\r\n        vec x1 = popX.col(r1);\r\n        vec x2 = popX.col(r2);\r\n        vec x = x3 + (x1 - x2) * F;\r\n        int r = rndInt(dim);\r\n        for (int j = 0; j < dim; j++)\r\n            if (j != r && rnd01() > CR)\r\n                x[j] = xp[j];\r\n        return fitfun->getClosestFeasible(x);\r\n    }\r\n\r\n    vec crowd_dist(mat& y) { // crowd distance for 1st objective\r\n    \tint n = y.cols();\r\n    \tvec y0 = y.row(0);\r\n    \tivec si = sort_index(y0); // sort 1st objective\r\n    \tvec y0s = y0(si); // sorted y0\r\n    \tvec d(n-1);\r\n        for (int i = 0; i < n-1; i++)\r\n        \td(i) = y0s[i+1] - y0s[i]; // neighbor distance\r\n        if (d.maxCoeff() == 0)\r\n        \treturn zeros(n);\r\n        vec dsum = zeros(n);\r\n        for (int i = 0; i < n; i++) {\r\n        \tif (i > 0)\r\n        \t\tdsum(i) += d(i-1); // distance to left\r\n        \tif (i < n-1)\r\n        \t\tdsum(i) += d(i); //  distance to right\r\n        }\r\n        dsum(0) = DBL_MAX; // keep borders\r\n        dsum(n-1) = DBL_MAX;\r\n        vec ds(n);\r\n        ds(si) = dsum;  // inverse order\r\n        return ds;\r\n    }\r\n\r\n    bool is_dominated(const mat& y, int i, int index) {\r\n    \tfor (int j = 0; j < y.rows(); j++)\r\n    \t\tif (y(j,i) < y(j,index))\r\n    \t\t\treturn false;\r\n    \treturn true;\r\n    }\r\n\r\n    vec pareto_levels(const mat& y) {\r\n         int n = y.cols();\r\n         ivec pareto(n);\r\n         for (int i = 0; i < n; i++)\r\n         \tpareto(i) = i;\r\n         vec domination = zeros(n);\r\n         bool mask[n];\r\n         for (int i = 0; i < n; i++)\r\n        \t mask[i] = true;\r\n         for (int index = 0; index < n;) {\r\n    \t\tfor (int i = 0; i < n; i++) {\r\n    \t\t\tif (i != index && mask[i] && is_dominated(y, i, index))\r\n    \t\t\t\tmask[i] = false;\r\n    \t\t}\r\n    \t\tfor (int i = 0; i < n; i++) {\r\n    \t\t\tif (mask[i])\r\n    \t\t\t\tdomination[i] += 1;\r\n    \t\t}\r\n    \t\tindex++;\r\n    \t\twhile(!mask[index] && index < n)\r\n    \t\t\tindex++;\r\n         }\r\n         return domination;\r\n    }\r\n\r\n    vec objranks(mat objs) {\r\n    \timat ci(objs.cols(), objs.rows());\r\n    \tfor (int i = 0; i < objs.rows(); i++)\r\n    \t\tci.col(i) = sort_index(objs.row(i).transpose());\r\n    \tmat rank(objs.rows(), objs.cols());\r\n    \tfor (int j = 0; j < objs.rows(); j++)\r\n    \t\tfor (int i = 0; i < objs.cols(); i++) {\r\n    \t\t\trank(j, ci(i,j)) = i;\r\n    \t}\r\n    \treturn rank.colwise().sum();\r\n    }\r\n\r\n    vec ranks(mat cons) {\r\n    \timat ci(cons.cols(), cons.rows());\r\n    \tfor (int i = 0; i < cons.rows(); i++)\r\n    \t\tci.col(i) = sort_index(cons.row(i).transpose());\r\n    \tmat rank(cons.rows(), cons.cols());\r\n    \tvec alpha = zeros(cons.rows());\r\n    \tfor (int j = 0; j < cons.rows(); j++) {\r\n    \t\tfor (int i = 0; i < cons.cols(); i++) {\r\n    \t\t\tif (cons(j,i) <= 0) {\r\n    \t\t\t\trank(j, ci(i,j)) = 0;\r\n    \t\t\t} else {\r\n    \t\t\t\trank(j, ci(i,j)) = i;\r\n    \t\t\t\talpha[j]++;\r\n    \t\t\t}\r\n    \t\t}\r\n    \t}\r\n    \tfor (int j = 0; j < cons.rows(); j++) {\r\n    \t\tfor (int i = 0; i < cons.cols(); i++)\r\n    \t\t\trank(j, ci(i,j)) *= alpha[j] / cons.rows();\r\n    \t}\r\n    \treturn rank.colwise().sum();\r\n    }\r\n\r\n    vec pareto(const mat& ys) {\r\n    \tif (ncon == 0)\r\n    \t\treturn pareto_levels(ys);\r\n        int popn = ys.cols();\r\n        mat yobj = ys(Eigen::seqN(0, nobj), Eigen::all);\r\n        mat ycon = ys(Eigen::lastN(ncon), Eigen::all);\r\n        vec csum = ranks(ycon);\r\n        bool feasible[ys.cols()];\r\n        bool hasFeasible = false;\r\n        for (int i = 0; i < ys.cols(); i++) {\r\n        \tfeasible[i] = ycon.col(i).maxCoeff() <= 0;\r\n        \tif (feasible[i])\r\n        \t\thasFeasible = true;\r\n        }\r\n        if (hasFeasible)\r\n        \tcsum += objranks(yobj);\r\n\t\t// first pareto front of feasible solutions\r\n        vec domination = zeros(popn);\r\n        std::vector<int> cyv;\r\n        for (int i = 0; i < ys.cols(); i++) // collect feasibles\r\n        \tif (feasible[i]) cyv.push_back(i);\r\n        ivec cy =  Eigen::Map<ivec, Eigen::Unaligned>(cyv.data(), cyv.size());\r\n        if (hasFeasible) { // compute pareto levels only for feasible\r\n        \tvec ypar = pareto_levels(yobj(Eigen::all, cy));\r\n        \tdomination(cy) += ypar;\r\n        }\r\n        // then constraint violations\r\n        ivec ci = sort_index(csum);\r\n        std::vector<int> civ;\r\n        for (int i = 0; i < ci.size(); i++)\r\n        \tif (!feasible[ci(i)]) civ.push_back(ci(i));\r\n        if (civ.size() > 0) {\r\n        \tivec ci =  Eigen::Map<ivec, Eigen::Unaligned>(civ.data(), civ.size());\r\n        \tint maxcdom = ci.size();\r\n        \t// higher constraint violation level gets lower domination level assigned\r\n        \tfor (int i = 0; i < ci.size(); i++)\r\n        \t\tdomination(ci(i)) += maxcdom - i;\r\n        \tif (cy.size() > 0) { // priorize feasible solutions\r\n            \tfor (int i = 0; i < cy.size(); i++)\r\n            \t\tdomination(cy(i)) += maxcdom + 1;\r\n        \t}\r\n        } // higher dominates lower\r\n        return domination;\r\n    }\r\n\r\n    mat variation(const mat& x) {\r\n    \tint n2 = x.cols() / 2;\r\n    \tint n = 2 * n2;\r\n        mat parent1 = x(Eigen::all, Eigen::seq(0, n2-1));\r\n        mat parent2 = x(Eigen::all, Eigen::seq(n2, n-1));\r\n        mat beta = mat(dim, n2);\r\n        vec to1;\r\n        if (pro_c < 1.0) {\r\n        \tto1 = uniformVec(dim, *rs);\r\n        }\r\n        for (int p = 0; p < n2; p++) {\r\n\t\t\tfor (int i = 0; i < dim; i++) {\r\n\t\t\t\tif (rnd01() > 0.5 || (pro_c < 1.0 && to1(i) < pro_c))\r\n\t\t\t\t\tbeta(i, p) = 1.0;\r\n\t\t\t\telse {\r\n\t\t\t\t\tdouble r = rnd01();\r\n\t\t\t\t\tif (r <= 0.5)\r\n\t\t\t\t\t\tbeta(i, p) = pow(2 * r, 1.0 / (dis_c + 1.0));\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tbeta(i, p) = pow(2 * r, -1.0 / (dis_c + 1.0));\r\n\t\t\t\t\tif (rnd01() > 0.5)\r\n\t\t\t\t\t\tbeta(i, p) = -beta(i, p);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n        mat offspring1 = ((parent1 + parent2) * 0.5);\r\n        mat offspring2 = mat(offspring1);\r\n        mat delta = (beta.array() * (parent1 - parent2).array()).matrix() * 0.5;\r\n        offspring1 += delta;\r\n        offspring2 -= delta;\r\n    \tmat offspring = mat(dim, n);\r\n    \toffspring << offspring1, offspring2;\r\n\r\n        double limit = pro_m / dim;\r\n        vec scale = fitfun->scale();\r\n        for (int p = 0; p < n; p++) {\r\n            for (int i = 0; i < dim; i++) {\r\n            \tif (rnd01() < limit) { // site\r\n            \t\tdouble mu = rnd01();\r\n        \t\t\tdouble norm = fitfun->norm_i(i, offspring(i, p));\r\n            \t\tif (mu <= 0.5) // temp\r\n            \t\t\toffspring(i, p) += scale(i) * \r\n                                (pow(2. * mu + (1. - 2. * mu) * pow(1. - norm, dis_m + 1.),\r\n\t                               1. / (dis_m + 1.)) - 1.);\r\n            \t\telse\r\n            \t\t\toffspring(i, p) += scale(i) * \r\n                                (1. - pow(2. * (1. - mu) + 2. * (mu - 0.5) * pow(1. - norm, dis_m + 1.),\r\n\t                               1. / (dis_m + 1.)));\r\n        \t\t}\r\n        \t}\r\n        }\r\n        fitfun->setClosestFeasible(offspring);\r\n    \treturn offspring;\r\n    }\r\n\r\n    void pop_update() {\r\n    \tvec domination = pareto(popY);\r\n    \tstd::vector<vec> x;\r\n    \tstd::vector<vec> y;\r\n    \tint maxdom = (int) domination.maxCoeff();\r\n    \tfor (int dom = maxdom; dom >= 0; dom--) {\r\n    \t\tstd::vector<int> level;\r\n    \t\tfor (int i = 0; i < domination.size(); i++)\r\n    \t\t\tif (domination(i) == dom)\r\n    \t\t\t\tlevel.push_back(i);\r\n            ivec domlevel =  Eigen::Map<ivec, Eigen::Unaligned>(level.data(), level.size());\r\n\t\t\tmat domx = popX(Eigen::all, domlevel);\r\n\t\t\tmat domy = popY(Eigen::all, domlevel);\r\n\t\t\tif (dom == maxdom) // store pareto front in bestP\r\n\t\t\t\tbestP = domlevel;\r\n\r\n    \t\tif ((int)(x.size() + domlevel.size()) <= popsize) {\r\n\t\t\t\t// whole level fits\r\n    \t\t\tfor (int i = 0; i < domy.cols(); i++) {\r\n    \t\t\t\tx.push_back(domx.col(i));\r\n    \t\t\t\ty.push_back(domy.col(i));\r\n    \t\t\t}\r\n    \t\t} else {\r\n    \t\t\tstd::vector<int> si;\r\n    \t\t\tsi.push_back(0);\r\n    \t\t\tif (domy.cols() > 1) {\r\n    \t\t\t\tvec cd = crowd_dist(domy);\r\n    \t\t\t\tivec si = sort_index(cd).reverse();\r\n    \t\t\t\tfor (int i = 0; i < si.size(); i++) {\r\n    \t\t\t\t\tif (((int)x.size()) >= popsize)\r\n    \t\t\t\t\t\tbreak;\r\n    \t\t\t\t\tx.push_back(domx.col(si(i)));\r\n    \t\t\t\t\ty.push_back(domy.col(si(i)));\r\n    \t\t\t\t}\r\n    \t\t\t}\r\n    \t\t\tbreak;\r\n    \t\t}\r\n    \t}\r\n    \tfor (int i = 0; i < popsize; i++) {\r\n    \t\tpopX.col(i) = x[i];\r\n       \t\tpopY.col(i) = y[i];\r\n    \t}\r\n    \tif (nsga_update)\r\n    \t\tvX = variation(popX(Eigen::all, Eigen::seqN(0, popsize)));\r\n    }\r\n\r\n    vec ask(int &p) {\r\n\t\tp = pos;\r\n\t\tvec x = nextX(p);\r\n\t\tpos = (pos + 1) % popsize;\r\n\t\treturn x;\r\n    }\r\n\r\n    int tell(const vec &y, const vec &x, int p) {\r\n    \tlong unsigned int dp = 0;\r\n    \tfor (; dp < vdone.size(); dp++)\r\n    \t\tif (!vdone[dp]) break;\r\n    \tnX.col(dp) = x;\r\n       \tnY.col(dp) = y;\r\n       \tvdone[dp] = true;\r\n    \tint ndone = 0;\r\n    \tfor (long unsigned int i = 0; i < vdone.size(); i++)\r\n    \t\tif (vdone[i]) ndone++;\r\n    \tif (ndone >= popsize) {\r\n\t\t\tint p = popsize;\r\n        \tfor (dp = 0; dp < vdone.size(); dp++) {\r\n        \t\tif (vdone[dp]) {\r\n\t\t\t\t\tpopX.col(p) = nX.col(dp);\r\n\t\t\t\t\tpopY.col(p) = nY.col(dp);\r\n\t\t\t\t\tvdone[dp] = false;\r\n\t\t\t\t\tif (p >= popY.cols())\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tp++;\r\n        \t\t}\r\n        \t}\r\n        \tpop_update();\r\n    \t}\r\n    \tn_evals += 1;\r\n//        if (n_evals % 1000 == 999)\r\n//        \tstd::cout << popY << std::endl;\r\n    \treturn stop;\r\n    }\r\n\r\n    void doOptimize() {\r\n    \titerations = 0;\r\n    \tfitfun->resetEvaluations();\r\n    \twhile (fitfun->evaluations() < maxEvaluations && !fitfun->terminate()) {\r\n            for (int p = 0; p < popsize; p++) {\r\n            \tvec x = nextX(p);\r\n            \tpopX.col(popsize + p) = x;\r\n            \tpopY.col(popsize + p) = fitfun->eval(x);\r\n            }\r\n            pop_update();\r\n     \t}\r\n    }\r\n\r\n    void do_optimize_delayed_update(int workers) {\r\n    \t iterations = 0;\r\n    \t fitfun->resetEvaluations();\r\n         workers = std::min(workers, popsize); // workers <= popsize\r\n    \t evaluator eval(fitfun, nobj, workers);\r\n    \t vec evals_x[popsize];\r\n\t     // fill eval queue with initial population\r\n    \t for (int i = 0; i < workers; i++) {\r\n    \t\t int p;\r\n    \t\t vec x = ask(p);\r\n    \t\t eval.evaluate(x, p);\r\n    \t\t evals_x[p] = x;\r\n    \t }\r\n    \t while (fitfun->evaluations() < maxEvaluations && !fitfun->terminate()) {\r\n    \t\t vec_id* vid = eval.result();\r\n    \t\t vec y = vec(vid->_v);\r\n    \t\t int p = vid->_id;\r\n    \t\t delete vid;\r\n    \t\t vec x = evals_x[p];\r\n    \t\t tell(y, x, p); // tell evaluated x\r\n    \t\t if (fitfun->evaluations() >= maxEvaluations)\r\n    \t\t\t break;\r\n    \t\t x = ask(p);\r\n    \t\t eval.evaluate(x, p);\r\n    \t\t evals_x[p] = x;\r\n    \t }\r\n\t}\r\n\r\n    void init() {\r\n        popX = mat(dim, 2*popsize);\r\n        popY = mat(nobj + ncon, 2*popsize);\r\n        for (int p = 0; p < popsize; p++) {\r\n            popX.col(p) = fitfun->sample(*rs);\r\n            popY.col(p) = constant(nobj + ncon, DBL_MAX);\r\n        }\r\n        next_size = 2*popsize;\r\n        vdone = std::vector<bool>(next_size, false);\r\n\t\tnX = mat(dim, next_size);\r\n\t\tnY = mat(nobj + ncon, next_size);\r\n\t\tvX = mat(popX);\r\n\t\tvp = 0;\r\n\t\tbestP = ivec(popsize);\r\n\t\tfor (int i = 0; i < popsize; i++)\r\n\t\t\tbestP(i) = i;\r\n    }\r\n\r\n    mat getX() {\r\n        return popX;\r\n    }\r\n\r\n    mat getY() {\r\n        return popY;\r\n    }\r\n\r\n    double getIterations() {\r\n        return iterations;\r\n    }\r\n\r\n    double getStop() {\r\n        return stop;\r\n    }\r\n\r\n    Fitness* getFitfun() {\r\n        return fitfun;\r\n    }\r\n\r\n    int getDim() {\r\n        return dim;\r\n    }\r\n\r\nprivate:\r\n    long runid;\r\n    Fitness *fitfun;\r\n    callback_type log;\r\n    int popsize; // population size\r\n    int dim;\r\n    int nobj;\r\n    int ncon;\r\n    int maxEvaluations;\r\n    double keep;\r\n    double stopfitness;\r\n    int iterations;\r\n    int n_evals;\r\n    ivec bestP;\r\n    int stop;\r\n    double F0;\r\n    double CR0;\r\n    double F;\r\n    double CR;\r\n\tdouble pro_c;\r\n\tdouble dis_c;\r\n\tdouble pro_m;\r\n\tdouble dis_m;\r\n    pcg64 *rs;\r\n    mat popX;\r\n    mat popY;\r\n    mat nX;\r\n    mat nY;\r\n    mat vX;\r\n    int vp;\r\n    int next_size;\r\n    std::vector<bool> vdone;\r\n    int pos;\r\n    bool nsga_update;\r\n    double pareto_update;\r\n    int log_period;\r\n};\r\n}\r\n\r\nusing namespace mode_optimizer;\r\n\r\nextern \"C\" {\r\nvoid optimizeMODE_C(long runid, callback_type func, callback_type log,\r\n\t\tint dim, int nobj, int ncon, int seed,\r\n        double *lower, double *upper, int maxEvals,\r\n\t\tint popsize, int workers, double F, double CR, \r\n\t    double pro_c, double dis_c, double pro_m, double dis_m,\r\n        bool nsga_update, double pareto_update, int log_period, double* res) {\r\n    vec lower_limit(dim), upper_limit(dim);\r\n    for (int i = 0; i < dim; i++) {\r\n        lower_limit[i] = lower[i];\r\n        upper_limit[i] = upper[i];\r\n    }\r\n    Fitness fitfun(func, dim, nobj + ncon, lower_limit, upper_limit);\r\n    MoDeOptimizer opt(runid, &fitfun, log, dim, nobj, ncon,\r\n    \t\tseed, popsize, maxEvals, F, CR, \r\n            pro_c, dis_c, pro_m, dis_m,\r\n            nsga_update, pareto_update, log_period);\r\n    try {\r\n        if (workers <= 1)\r\n            opt.doOptimize();\r\n        else\r\n            opt.do_optimize_delayed_update(workers);\r\n        double* xdata = opt.getX().data();\r\n        for (int i = 0; i < opt.getX().size(); i++)\r\n            res[i] = xdata[i];\r\n    } catch (std::exception &e) {\r\n    \tstd::cout << e.what() << std::endl;\r\n    }\r\n   }\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "283cef2a14f5b68d4b041875d15a4ccd27af84a9", "size": 18640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_fcmaescpp/modeoptimizer.cpp", "max_stars_repo_name": "vishalbelsare/fast-cma-es", "max_stars_repo_head_hexsha": "c6bed439bc4bf78dca7d9f2203b56d74ce272f01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-05-28T10:23:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T08:09:58.000Z", "max_issues_repo_path": "_fcmaescpp/modeoptimizer.cpp", "max_issues_repo_name": "vishalbelsare/fast-cma-es", "max_issues_repo_head_hexsha": "c6bed439bc4bf78dca7d9f2203b56d74ce272f01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-03-04T15:16:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T07:14:19.000Z", "max_forks_repo_path": "_fcmaescpp/modeoptimizer.cpp", "max_forks_repo_name": "vishalbelsare/fast-cma-es", "max_forks_repo_head_hexsha": "c6bed439bc4bf78dca7d9f2203b56d74ce272f01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2020-02-19T12:26:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:22:13.000Z", "avg_line_length": 31.3277310924, "max_line_length": 134, "alphanum_fraction": 0.5032188841, "num_tokens": 5326, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4479438727888907}}
{"text": "#ifndef NUMERICAL_OPTIMIZATION_HPP\n#define NUMERICAL_OPTIMIZATION_HPP\n\n#include <mathtoolbox/bfgs.hpp>\n#include <mathtoolbox/l-bfgs.hpp>\n#include <functional>\n#include <stdexcept>\n#include <Eigen/Core>\n\nnamespace mathtoolbox\n{\n    namespace optimization\n    {\n        enum class Algorithm\n        {\n            Bfgs, LBfgs\n        };\n\n        enum class Type\n        {\n            Min, Max\n        };\n\n        struct Setting\n        {\n            Algorithm algorithm                                      = Algorithm::Bfgs;\n            Eigen::VectorXd x_init                                   = Eigen::VectorXd(0);\n            std::function<double(const Eigen::VectorXd&)> f          = nullptr;\n            std::function<Eigen::VectorXd(const Eigen::VectorXd&)> g = nullptr;\n            double epsilon                                           = 1e-05;\n            unsigned int max_num_iterations                          = 1000;\n            Type type                                                = Type::Min;\n        };\n\n        struct Result\n        {\n            Eigen::VectorXd x_star;\n            unsigned        num_iterations;\n        };\n\n        inline Result RunOptimization(const Setting& input)\n        {\n            const auto f = (input.type == Type::Min) ? input.f : [&input](const Eigen::VectorXd& x) { return - input.f(x); };\n            const auto g = (input.type == Type::Min) ? input.g : [&input](const Eigen::VectorXd& x) { return - input.g(x); };\n\n            switch (input.algorithm) {\n                case Algorithm::Bfgs:\n                {\n                    if (!input.f || !input.g || input.x_init.rows() == 0)\n                    {\n                        throw std::invalid_argument(\"Invalid setting.\");\n                    }\n\n                    Result result;\n                    RunBfgs(input.x_init, f, g, input.epsilon, input.max_num_iterations, result.x_star, result.num_iterations);\n                    return result;\n                }\n                case Algorithm::LBfgs:\n                {\n                    if (!input.f || !input.g || input.x_init.rows() == 0)\n                    {\n                        throw std::invalid_argument(\"Invalid setting.\");\n                    }\n\n                    Result result;\n                    RunLBfgs(input.x_init, f, g, input.epsilon, input.max_num_iterations, result.x_star, result.num_iterations);\n                    return result;\n                }\n            }\n        }\n    }\n}\n\n#endif // NUMERICAL_OPTIMIZATION_HPP\n", "meta": {"hexsha": "085b4115a16437865dfb1599e4df38e2f68785f4", "size": 2509, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/numerical-optimization.hpp", "max_stars_repo_name": "josefgraus/self_similiarity", "max_stars_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T09:35:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-25T09:35:14.000Z", "max_issues_repo_path": "include/mathtoolbox/numerical-optimization.hpp", "max_issues_repo_name": "josefgraus/self_similarity", "max_issues_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mathtoolbox/numerical-optimization.hpp", "max_forks_repo_name": "josefgraus/self_similarity", "max_forks_repo_head_hexsha": "c032daa3009f60fdc8a52c437a07c6e3ba2efe4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-25T09:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T13:26:38.000Z", "avg_line_length": 33.4533333333, "max_line_length": 128, "alphanum_fraction": 0.4647269829, "num_tokens": 490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.44794386577113593}}
{"text": "// Copyright (C) 2013 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/vision/sfm/pose/five_point_relative_pose.h\"\n\n#include <Eigen/Dense>\n#include <glog/logging.h>\n\n#include <cmath>\n#include <ctime>\n#include <vector>\n\n#include \"theia/math/matrix/gauss_jordan.h\"\n#include \"theia/math/polynomial.h\"\n#include \"theia/vision/sfm/pose/util.h\"\n\nnamespace theia {\n\nusing Eigen::Map;\nusing Eigen::Matrix3d;\nusing Eigen::Matrix4d;\nusing Eigen::Matrix;\nusing Eigen::RowVector3d;\nusing Eigen::RowVector4d;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\nusing Eigen::Vector4d;\n\ntypedef Matrix<double, 3, 3, Eigen::RowMajor> RowMatrix3d;\n\nnamespace {\n// Multiplies two polynomials over the same variable.\ntemplate <int n1, int n2>\nMatrix<double, 1, n1 + n2 - 1> MultiplyPoly(const Matrix<double, 1, n1>& a,\n                                            const Matrix<double, 1, n2>& b) {\n  Matrix<double, 1, n1 + n2 - 1> poly = Matrix<double, 1, n1 + n2 - 1>::Zero();\n  for (int i = 0; i < a.cols(); i++)\n    for (int j = 0; j < b.cols(); j++)\n      poly[i + j] += a[i] * b[j];\n\n  return poly;\n}\n\n// Evaluates a given polynomial at the value x.\ntemplate <int n>\ndouble EvaluatePoly(const Matrix<double, 1, n>& poly, double x) {\n  double val = 0;\n  for (int i = poly.cols() - 1; i > 0; i--) {\n    val += poly[i];\n    val *= x;\n  }\n  val += poly[0];\n  return val;\n}\n\n// Multiply two degree one polynomials of variables x, y, z.\n// E.g. p1 = a[0]x + a[1]y + a[2]z + a[3]\n// x^2 y^2 z^2 xy xz yz x y z 1\nMatrix<double, 1, 10> MultiplyDegOnePoly(const RowVector4d& a,\n                                         const RowVector4d& b) {\n  Matrix<double, 1, 10> output;\n  output(0) = a(0) * b(0);\n  output(1) = a(1) * b(1);\n  output(2) = a(2) * b(2);\n  output(3) = a(0) * b(1) + a(1) * b(0);\n  output(4) = a(0) * b(2) + a(2) * b(0);\n  output(5) = a(1) * b(2) + a(2) * b(1);\n  output(6) = a(0) * b(3) + a(3) * b(0);\n  output(7) = a(1) * b(3) + a(3) * b(1);\n  output(8) = a(2) * b(3) + a(3) * b(2);\n  output(9) = a(3) * b(3);\n  return output;\n}\n\n// Multiply a 2 deg poly (in x, y, z) and a one deg poly.\n// x^3 y^3 x^2y xy^2 x^2z x^2 y^2z y^2 xyz xy | z^2x zx x z^2y zy y z^3 z^2 z 1\n// NOTE: after the | all are variables along z.\nMatrix<double, 1, 20> MultiplyDegTwoDegOnePoly(const Matrix<double, 1, 10>& a,\n                                               const RowVector4d& b) {\n  Matrix<double, 1, 20> output;\n  output(0) = a(0) * b(0);\n  output(1) = a(1) * b(1);\n  output(2) = a(0) * b(1) + a(3) * b(0);\n  output(3) = a(1) * b(0) + a(3) * b(1);\n  output(4) = a(0) * b(2) + a(4) * b(0);\n  output(5) = a(0) * b(3) + a(6) * b(0);\n  output(6) = a(1) * b(2) + a(5) * b(1);\n  output(7) = a(1) * b(3) + a(7) * b(1);\n  output(8) = a(3) * b(2) + a(4) * b(1) + a(5) * b(0);\n  output(9) = a(3) * b(3) + a(6) * b(1) + a(7) * b(0);\n  output(10) = a(2) * b(0) + a(4) * b(2);\n  output(11) = a(4) * b(3) + a(8) * b(0) + a(6) * b(2);\n  output(12) = a(6) * b(3) + a(9) * b(0);\n  output(13) = a(2) * b(1) + a(5) * b(2);\n  output(14) = a(5) * b(3) + a(8) * b(1) + a(7) * b(2);\n  output(15) = a(7) * b(3) + a(9) * b(1);\n  output(16) = a(2) * b(2);\n  output(17) = a(2) * b(3) + a(8) * b(2);\n  output(18) = a(8) * b(3) + a(9) * b(2);\n  output(19) = a(9) * b(3);\n  return output;\n}\n\n// Shorthand for multiplying the Essential matrix with its transpose according\n// to Eq. 20 in Nister paper.\nMatrix<double, 1, 10> EETranspose(\n    const Matrix<double, 9, 4>& null_matrix, int i, int j) {\n  return MultiplyDegOnePoly(null_matrix.row(3 * i), null_matrix.row(3 * j)) +\n      MultiplyDegOnePoly(null_matrix.row(3 * i + 1),\n                         null_matrix.row(3 * j + 1)) +\n      MultiplyDegOnePoly(null_matrix.row(3 * i + 2),\n                         null_matrix.row(3 * j + 2));\n}\n\n// Builds the 10x20 constraint matrix according to Section 3.2.2 of Nister\n// paper. Constraints are built based on the singularity of the Essential\n// matrix, and the trace equation (Eq. 6). This builds the 10x20 matrix such\n// that the columns correspond to: x^3, yx^2, y^2x, y^3, zx^2, zyx, zy^2, z^2x,\n// z^2y, z^3, x^2, yx, y^2, zx, zy, z^2, x, y, z, 1.\nMatrix<double, 10, 20> BuildConstraintMatrix(\n    const Matrix<double, 9, 4>& null_space) {\n  Matrix<double, 10, 20> constraint_matrix;\n  // Singularity constraint.\n  constraint_matrix.row(0) =\n      MultiplyDegTwoDegOnePoly(\n          MultiplyDegOnePoly(null_space.row(1), null_space.row(5)) -\n          MultiplyDegOnePoly(null_space.row(2), null_space.row(4)),\n          null_space.row(6)) +\n      MultiplyDegTwoDegOnePoly(\n          MultiplyDegOnePoly(null_space.row(2), null_space.row(3)) -\n          MultiplyDegOnePoly(null_space.row(0), null_space.row(5)),\n          null_space.row(7)) +\n      MultiplyDegTwoDegOnePoly(\n          MultiplyDegOnePoly(null_space.row(0), null_space.row(4)) -\n          MultiplyDegOnePoly(null_space.row(1), null_space.row(3)),\n          null_space.row(8));\n\n  // Trace Constraint. Only need to compute the upper triangular part of the\n  // symmetric polynomial matrix\n  Matrix<double, 1, 10> symmetric_poly[3][3];\n  symmetric_poly[0][0] = EETranspose(null_space, 0, 0);\n  symmetric_poly[1][1] = EETranspose(null_space, 1, 1);\n  symmetric_poly[2][2] = EETranspose(null_space, 2, 2);\n\n  Matrix<double, 1, 10> half_trace = 0.5*(symmetric_poly[0][0] +\n                                          symmetric_poly[1][1] +\n                                          symmetric_poly[2][2]);\n\n  symmetric_poly[0][0] -= half_trace;\n  symmetric_poly[1][1] -= half_trace;\n  symmetric_poly[2][2] -= half_trace;\n  symmetric_poly[0][1] = EETranspose(null_space, 0, 1);\n  symmetric_poly[0][2] = EETranspose(null_space, 0, 2);\n  symmetric_poly[1][0] = symmetric_poly[0][1];\n  symmetric_poly[1][2] = EETranspose(null_space, 1, 2);\n  symmetric_poly[2][0] = symmetric_poly[0][2];\n  symmetric_poly[2][1] = symmetric_poly[1][2];\n\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 3; j++) {\n      constraint_matrix.row(3*i + j + 1) =\n          MultiplyDegTwoDegOnePoly(symmetric_poly[i][0],\n                                   null_space.row(j)) +\n          MultiplyDegTwoDegOnePoly(symmetric_poly[i][1],\n                                   null_space.row(3 + j)) +\n          MultiplyDegTwoDegOnePoly(symmetric_poly[i][2],\n                                   null_space.row(6 + j));\n    }\n  }\n  return constraint_matrix;\n}\n\n// Efficient nullspace extraction based on the idea of QR decomposition on the 5\n// correspondences of the epipolar constraint. Instead of QR, we use\n// Gauss-Jordan for the same effect.\nMatrix<double, 9, 4> EfficientNullspaceExtraction(\n    const Matrix<double, 5, 9>& constraint) {\n  Matrix<double, 5, 9> constraint_copy(constraint);\n  GaussJordan(&constraint_copy);\n  Matrix<double, 4, 9> null_space;\n  null_space << constraint_copy.rightCols(4).transpose(),\n      -Matrix4d::Identity();\n  return null_space.transpose();\n}\n\nvoid EfficientSVDDecomp(const Matrix3d& essential_mat,\n                        Vector3d* null_space,\n                        Matrix3d rotation[4],\n                        Vector3d translation[4]) {\n  Matrix3d d;\n  d << 0, 1, 0,\n      -1, 0, 0,\n      0, 0, 1;\n\n  const Vector3d& ea = essential_mat.row(0);\n  const Vector3d& eb = essential_mat.row(1);\n  const Vector3d& ec = essential_mat.row(2);\n\n  // Generate cross products.\n  Matrix3d cross_products;\n  cross_products << ea.cross(eb), ea.cross(ec), eb.cross(ec);\n\n  // Choose the cross product with the largest norm (for numerical accuracy).\n  const Vector3d cf_scales(cross_products.col(0).squaredNorm(),\n                           cross_products.col(1).squaredNorm(),\n                           cross_products.col(2).squaredNorm());\n  int max_index;\n  cf_scales.maxCoeff(&max_index);\n\n  // For index 0, 1, we want ea and for index 2 we want eb.\n  const int max_e_index = max_index / 2;\n\n  // Construct v of the SVD.\n  Matrix3d v = Matrix3d::Zero();\n  v.col(2) = cross_products.col(max_index).normalized();\n  v.col(0) = essential_mat.row(max_e_index).normalized();\n  v.col(1) = v.col(2).cross(v.col(0));\n\n  // Construct U of the SVD.\n  Matrix3d u = Matrix3d::Zero();\n  u.col(0) = (essential_mat * v.col(0)).normalized();\n  u.col(1) = (essential_mat * v.col(1)).normalized();\n  u.col(2) = u.col(0).cross(u.col(1));\n\n  // Possible rotation configurations.\n  const RowMatrix3d ra =\n      Eigen::Quaterniond(u * d * v.transpose()).normalized().toRotationMatrix();\n  const RowMatrix3d rb = Eigen::Quaterniond(u * d.transpose() * v.transpose())\n      .normalized().toRotationMatrix();\n\n  // Scale t to be proper magnitude. Scale factor is derived from the fact that\n  // U*diag*V^t = E. We simply choose to scale it such that the last terms will\n  // be equal.\n  const Vector3d t = u.col(2).normalized();\n  const Vector3d t_neg = -t;\n\n  // Copy the 4 possible decompositions into the output arrays.\n  rotation[0] = ra;\n  translation[0] = t;\n  rotation[1] = ra;\n  translation[1] = t_neg;\n  rotation[2] = rb;\n  translation[2] = t;\n  rotation[3] = rb;\n  translation[3] = t_neg;\n\n  *null_space = v.col(2);\n}\n\nvoid DecomposeWithIdealCorrespondence(const Vector2d& image_point1,\n                                      const Vector2d& image_point2,\n                                      const Matrix3d& essential_mat,\n                                      Matrix3d* rotation,\n                                      Vector3d* translation) {\n  const Vector3d image_point1_homog = image_point1.homogeneous();\n  const Vector3d image_point2_homog = image_point2.homogeneous();\n\n  // Map the image points to vectors.\n  Matrix3d candidate_rotation[4];\n  Vector3d candidate_translation[4];\n  Vector3d null_space;\n  EfficientSVDDecomp(essential_mat, &null_space, candidate_rotation,\n                     candidate_translation);\n\n  Matrix<double, 3, 4> projection_mat;\n  projection_mat.block<3, 3>(0, 0) = candidate_rotation[0];\n  projection_mat.block<3, 1>(0, 3) = candidate_translation[0];\n\n  // Compute c.\n  Matrix3d temp_diag = Matrix3d::Identity();\n  temp_diag(2, 2) = 0.0;\n  const Vector3d c =\n      image_point2_homog.cross(temp_diag * essential_mat * image_point1_homog);\n\n  // Compute C.\n  const Vector4d C = projection_mat.transpose() * c;\n  const Vector4d Q(image_point1_homog(0) * C(3),\n                   image_point1_homog(1) * C(3),\n                   image_point1_homog(2) * C(3),\n                   -(image_point1_homog.dot(C.head<3>())));\n  // We only care about the sign of the depth because it informs us of the\n  // direction of the point (i.e. if it is in front of the camera). Use a\n  // multiply instead of divide for speed.\n  const double scaled_depth_1  = Q(2) * Q(3);\n  const double scaled_depth_2 = projection_mat.row(2).dot(Q) * Q(3);\n\n  // Create the twisted pair transformation.\n  const Vector4d twisted_transformation(-2.0 * null_space(0),\n                                        -2.0 * null_space(1),\n                                        -2.0 * null_space(2),\n                                        -1.0);\n\n  // Determine the proper configuration for the R,t decomposition.\n  int best_index;\n  if (scaled_depth_1 > 0 && scaled_depth_2 > 0) {\n    best_index = 0;\n  } else if (scaled_depth_1 < 0 && scaled_depth_2 < 0) {\n    best_index = 1;\n  } else if (Q(2) * twisted_transformation.dot(Q) > 0) {\n    best_index = 2;\n  } else {\n    best_index = 3;\n  }\n\n  *rotation = candidate_rotation[best_index];\n  *translation = candidate_translation[best_index];\n}\n\n}  // namespace\n\n// Implementation of Nister from \"An Efficient Solution to the Five-Point\n// Relative Pose Problem\"\nbool FivePointRelativePose(const Vector2d image1_points[5],\n                           const Vector2d image2_points[5],\n                           std::vector<Matrix3d>* rotation,\n                           std::vector<Vector3d>* translation) {\n  // Step 1. Create the 5x9 matrix containing epipolar constraints.\n  //   Essential matrix is a linear combination of the 4 vectors spanning the\n  //   null space of this matrix (found by SVD).\n  Matrix<double, 5, 9> epipolar_constraint;\n  for (int i = 0; i < 5; i++) {\n    // Fill matrix with the epipolar constraint from q'_t*E*q = 0. Where q is\n    // from the first image, and q' is from the second. Eq. 8 in the Nister\n    // paper.\n    epipolar_constraint.row(i) <<\n        image1_points[i].x() * image2_points[i].x(),\n        image1_points[i].y() * image2_points[i].x(),\n        image2_points[i].x(),\n        image1_points[i].x() * image2_points[i].y(),\n        image1_points[i].y() * image2_points[i].y(),\n        image2_points[i].y(),\n        image1_points[i].x(),\n        image1_points[i].y(),\n        1.0;\n  }\n\n  // Solve for right null space of the 5x9 matrix. NOTE: We use a\n  // super-efficient method that is a variation of the QR decomposition\n  // described in the Nister paper.  by roughly 5x.\n  Matrix<double, 9, 4> null_space =\n      EfficientNullspaceExtraction(epipolar_constraint);\n\n  // Step 2. Expansion of the epipolar constraints Eq. 5 and 6 from Nister\n  // paper.\n  Matrix<double, 10, 20> constraint_matrix = BuildConstraintMatrix(null_space);\n\n  // Step 3. Gauss-Jordan Elimination with partial pivoting on constraint\n  // matrix.\n  GaussJordan(&constraint_matrix);\n\n  // Step 4. Expand determinant polynomial of 3x3 polynomial B.\n  // Create matrix B. Horribly ugly, but not sure if there's a better way to do\n  // it!\n  RowVector4d b11(constraint_matrix(4, 12),\n                  constraint_matrix(4, 11) - constraint_matrix(5, 12),\n                  constraint_matrix(4, 10) - constraint_matrix(5, 11),\n                  -constraint_matrix(5, 10));\n  RowVector4d b12(constraint_matrix(4, 15),\n                  constraint_matrix(4, 14) - constraint_matrix(5, 15),\n                  constraint_matrix(4, 13) - constraint_matrix(5, 14),\n                  -constraint_matrix(5, 13));\n  Matrix<double, 1, 5> b13;\n  b13 << constraint_matrix(4, 19),\n      constraint_matrix(4, 18) - constraint_matrix(5, 19),\n      constraint_matrix(4, 17) - constraint_matrix(5, 18),\n      constraint_matrix(4, 16) - constraint_matrix(5, 17),\n      -constraint_matrix(5, 16);\n  RowVector4d b21(constraint_matrix(6, 12),\n                  constraint_matrix(6, 11) - constraint_matrix(7, 12),\n                  constraint_matrix(6, 10) - constraint_matrix(7, 11),\n                  -constraint_matrix(7, 10));\n  RowVector4d b22(constraint_matrix(6, 15),\n                  constraint_matrix(6, 14) - constraint_matrix(7, 15),\n                  constraint_matrix(6, 13) - constraint_matrix(7, 14),\n                  -constraint_matrix(7, 13));\n  Matrix<double, 1, 5> b23;\n  b23 << constraint_matrix(6, 19),\n      constraint_matrix(6, 18) - constraint_matrix(7, 19),\n      constraint_matrix(6, 17) - constraint_matrix(7, 18),\n      constraint_matrix(6, 16) - constraint_matrix(7, 17),\n      -constraint_matrix(7, 16);\n  RowVector4d b31(constraint_matrix(8, 12),\n                  constraint_matrix(8, 11) - constraint_matrix(9, 12),\n                  constraint_matrix(8, 10) - constraint_matrix(9, 11),\n                  -constraint_matrix(9, 10));\n  RowVector4d b32(constraint_matrix(8, 15),\n                  constraint_matrix(8, 14) - constraint_matrix(9, 15),\n                  constraint_matrix(8, 13) - constraint_matrix(9, 14),\n                  -constraint_matrix(9, 13));\n  Matrix<double, 1, 5> b33;\n  b33 << constraint_matrix(8, 19),\n      constraint_matrix(8, 18) - constraint_matrix(9, 19),\n      constraint_matrix(8, 17) - constraint_matrix(9, 18),\n      constraint_matrix(8, 16) - constraint_matrix(9, 17),\n      -constraint_matrix(9, 16);\n\n  // Eq. 24.\n  Matrix<double, 1, 8> p1 = MultiplyPoly(b12, b23) - MultiplyPoly(b13, b22);\n  // Eq. 25.\n  Matrix<double, 1, 8> p2 = MultiplyPoly(b13, b21) - MultiplyPoly(b11, b23);\n  // Eq. 26.\n  Matrix<double, 1, 7> p3 = MultiplyPoly(b11, b22) - MultiplyPoly(b12, b21);\n\n  // Eq. 27. Form determinant of B as a 10th degree polynomial.\n  Matrix<double, 1, 11> n = MultiplyPoly(p1, b31) + MultiplyPoly(p2, b32) +\n                            MultiplyPoly(p3, b33);\n\n  // Step 5. Extract real roots of the 10th degree polynomial.\n  Eigen::VectorXd roots;\n  FindRealPolynomialRoots(n.transpose().reverse(), &roots);\n\n  rotation->reserve(roots.size());\n  translation->reserve(roots.size());\n  static const double kTolerance = 1e-12;\n  for (int i = 0; i < roots.size(); i++) {\n    // We only want non-zero roots\n    if (fabs(roots(i)) < kTolerance)\n      continue;\n\n    double x = EvaluatePoly(p1, roots(i)) / EvaluatePoly(p3, roots(i));\n    double y = EvaluatePoly(p2, roots(i)) / EvaluatePoly(p3, roots(i));\n    Matrix<double, 9, 1> temp_sum =\n        x * null_space.col(0) + y * null_space.col(1) +\n        roots(i) * null_space.col(2) + null_space.col(3);\n    // Need to do it like this because temp_sum is a row vector and recasting\n    // it as a 3x3 will load it column-major.\n    Matrix3d candidate_essential_mat;\n    candidate_essential_mat << temp_sum.head<3>().transpose(),\n        temp_sum.segment(3, 3).transpose(), temp_sum.tail(3).transpose();\n\n    Matrix3d rotation_soln;\n    Vector3d translation_soln;\n    // Decompose into R, t using the first point correspondence.\n    DecomposeWithIdealCorrespondence(image1_points[0], image2_points[0],\n                                     candidate_essential_mat, &rotation_soln,\n                                     &translation_soln);\n    rotation->push_back(rotation_soln);\n    translation->push_back(translation_soln);\n  }\n  return (roots.size() > 0);\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "20977aa57ff4e01260a7ca371e367cbdfe68471a", "size": 19173, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/vision/sfm/pose/five_point_relative_pose.cc", "max_stars_repo_name": "nuernber/Theia", "max_stars_repo_head_hexsha": "4bac771b09458a46c44619afa89498a13cd39999", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-02T13:30:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-02T13:30:52.000Z", "max_issues_repo_path": "src/theia/vision/sfm/pose/five_point_relative_pose.cc", "max_issues_repo_name": "nuernber/Theia", "max_issues_repo_head_hexsha": "4bac771b09458a46c44619afa89498a13cd39999", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/vision/sfm/pose/five_point_relative_pose.cc", "max_forks_repo_name": "nuernber/Theia", "max_forks_repo_head_hexsha": "4bac771b09458a46c44619afa89498a13cd39999", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T08:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T08:43:13.000Z", "avg_line_length": 40.3642105263, "max_line_length": 80, "alphanum_fraction": 0.6238460335, "num_tokens": 5706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.44794386577113593}}
{"text": "#include \"profile.hpp\"\n#include \"profile_python.hpp\"\n#include <boost/python.hpp>\n#include <pyublas/numpy.hpp>\n#include \"optimization.hpp\"\n#include \"rootfinder.hpp\"\n\nnamespace gd {\nusing namespace boost::python;\n\n// in km/s^2 Msun/kpc\nconst double GravConst = 4.30200406461e-06;\n\nboost::python::tuple ProfileModel::Lmax_and_rcirc_at_E_(double E) {\n\tdouble Lmax, rcirc;\n\tLmax_and_rcirc_at_E(E, Lmax, rcirc);\n\treturn boost::python::make_tuple(Lmax, rcirc);\n}\nvoid ProfileModel::Lmax_and_rcirc_at_E(double E, double& Lmax, double& rcirc) {\n\t/*\tdef f(r, E=E):\n\t\t\tr = abs(r)\n\t\t\treturn -r**2*(2*(E-self.potentialr(r)))\n\t\trLmax, Lmaxsq = scipy.optimize.fmin(f, rtry, full_output=True, disp=False)[:2]\n\t\treturn sqrt(abs(Lmaxsq)), abs(rLmax[0])\n\t*/\n\tauto f = [&](double logr) -> double {\n\t\t//r = fabs(r);\n\t\tdouble r = pow(10, logr);\n\t\t//printf(\"r = %f logr\\n \", r);\n\t\treturn -r*r*(2*(E-this->potentialr(r)));\n\t};\n\tMinimizerNLopt2<> opt(f);\n\t//double lower_bounds[1] = { 0};\n\t//nlopt_set_lower_bounds(opt.opt, lower_bounds);\n\t//opt.x = 1.;\n\trcirc = pow(10, opt.optimize());\n\t//printf(\"r = %f Ekin = %f\\n\", r, 2*(E-this->potentialr(r)));\n\tLmax = sqrt(2*(E-this->potentialr(rcirc)))*rcirc;\n}\ndouble ProfileModel::Lmax_at_E(double E) {\n\tdouble Lmax, rcirc;\n\tLmax_and_rcirc_at_E(E, Lmax, rcirc);\n\treturn Lmax;\n}\ndouble ProfileModel::rcirc_at_E(double E) {\n\tdouble Lmax, rcirc;\n\tLmax_and_rcirc_at_E(E, Lmax, rcirc);\n\treturn rcirc;\n}\ndouble ProfileModel::rmax_at_E(double E, double rcirc) {\n\tauto f = [&](double r) -> double {\n\t\treturn E - this->potentialr(r);\n\t};\n\tdouble scale = 1.5;\n\tdouble r_far_way = rcirc * scale;\n\tassert(f(rcirc) >= 0);\n\twhile(f(r_far_way) > 0) {\n\t\tr_far_way *= scale;\n\t}\n\tRootFinderGSL<> rootfinder(f);\n\tdouble rmax = rootfinder.findRoot(rcirc, r_far_way);\n\treturn rmax;\n\t\n\t/*auto f = [&](double r) -> double {\n\t\treturn E - this->potentialr(r);\n\t};\n\tauto root = [&](double x, double * y, double *dy) -> void {\n\t\tdouble r = pow(10, x) + rcirc;\n\t\t// x = log10(r-rcirc)\n\t\t// dx = 1/(r-rcirc) / log(10) dr\n\t\t*y = f(r);\n\t\tdouble gradient = -this->dphidr(r) * (r-rcirc) * log(10);\n\t\t*dy = gradient;\n\t\t//*\n\t\tdouble r1 = r;\n\t\tdouble dx = 1e-4;\n\t\tdouble r2 = pow(10, x+dx)+rcirc;\n\t\tdouble y1 = f(r1);\n\t\tdouble y2 = f(r2);\n\t\tprintf(\"rmax grad: logr=%f r=%10.5f: erad=%10.5f [%10.5f %10.5f] (%f) \\n\", x, r, *y, (y2-y1)/dx, gradient, this->potentialr(r));\n\t\t//return g\n\t\t/**/\n\t/*};\n\t\n\t// find apo or peri center\n\tRootFinderGSLDerivative<> rootfinderFirst(root);\n\tdouble rstart = pow(10, rootfinderFirst.findRoot(1, 0, 1e-5))+rcirc; //pow(10, rootfinderFirst.findRoot(0));\n\tdouble scale = 1.+1e-4;\n\tassert(f(rstart*scale) < 0);\n\tassert(f(rstart/scale) > 0);\n\treturn rstart;*/\n}\n\n\nboost::python::tuple ProfileModel::get_apo_peri(double E, double L, double rmin, double rcirc, double rmax) {\n\n\tauto ekinrad = [&](double r) -> double { // kinetic energy in radial direction\n\t\treturn (-L*L/(2*r*r) - (this->potentialr(r) - E));\n\t};\n\tauto root = [&](double x, double * y, double *dy) -> void {\n\t\tif(x < 0) {\n\t\t\t//*y =FP_INFINITE;// inf;\n\t\t\t//*dy = FP_INFINITE;//inf;\n\t\t\t//return;\n\t\t\t//printf(\"grad: x=%f\\n\", x);\n\t\t\t//x = -x;\n\t\t}\n\t\tdouble r = pow(10, x);\n\t\t*y = ekinrad(r);\n\t\tdouble gradient = (-this->dphidr(r) + L*L/pow(r, 3)) * r * log(10);\n\t\t*dy = gradient;\n\t\t//*\n\t\tdouble r1 = r;\n\t\tdouble dx = 1e-4;\n\t\tdouble r2 = pow(10, x+dx);\n\t\tdouble y1 = ekinrad(r1);\n\t\tdouble y2 = ekinrad(r2);\n\t\t//printf(\"grad: logr=%f r=%10.5f: erad=%10.5f [%10.5f %10.5f] (%f) \\n\", x, r, *y, (y2-y1)/dx, gradient, this->potentialr(r));\n\t\t//return g\n\t\t/**/\n\t};\n\n\t// find apo or peri center\n\t//RootFinderGSLDerivative<> rootfinderFirst(root);\n\t//double rstart = pow(10, rootfinderFirst.findRoot(1)); //pow(10, rootfinderFirst.findRoot(0));\n\n\tdouble scale = (1+1e-4);\n\tdouble apo, peri;\n\tRootFinderGSL<> rootfinder(ekinrad);\n\t//printf(\"found a valid r %f (E=%f L=%f Eleft=%f (%f %f))\\n\", rstart, E, L, ekinrad(rstart), ekinrad(rstart*scale), ekinrad(rstart/scale));\n\t//printf(\"rmin : %f ekinrad: %f %f %f\\n\", rmin, ekinrad(rmin), ekinrad(rmin*scale), ekinrad(rmin/scale));\n\t//printf(\"rcirc: %f ekinrad: %f %f %f\\n\", rcirc, ekinrad(rcirc), ekinrad(rcirc*scale), ekinrad(rcirc/scale));\n\t//printf(\"rmax : %f ekinrad: %f %f %f\\n\", rmax, ekinrad(rmax), ekinrad(rmax*scale), ekinrad(rmax/scale));\n\tint n;\n\tn = 0;\n\tassert(ekinrad(rcirc) >= 0);\n\twhile((n < 10) & (ekinrad(rmin) > 0)) {\n\t\trmin /= scale;\n\t\tn++;\n\t}\n\tif(ekinrad(rmin) > 0) {\n\t\tthrow std::range_error(\"rmin cannot be properly found\");\n\t}\n\n\tn = 0;\n\twhile((n < 10) & (ekinrad(rmax) > 0)) {\n\t\trmax *= scale;\n\t\tn++;\n\t}\n\tif(ekinrad(rmax) > 0) {\n\t\tthrow std::range_error(\"rmax cannot be properly found\");\n\t}\n\n\n\tperi = rootfinder.findRoot(rmin, rcirc);\n\tapo = rootfinder.findRoot(rcirc, rmax);\n\t\n\t\t//printf(\"finding apocenter [%f]\\n\", rstart);\n\t\t//printf(\"found apocenter [%f]\\n\", apo);\n\t\t//printf(\"finding pericenter [%f] (%f %f %f)\\n\", rstart, ekinrad(1e-6), ekinrad(rstart/scale/scale), ekinrad(rstart*scale*scale));\n\t\t//printf(\"found pericenter [%f]\\n\", peri);\n\tscale = (1+1e-5);\n\twhile(ekinrad(peri) < 0) {\n\t\tperi *= scale;\n\t}\n\twhile(ekinrad(apo) < 0) {\n\t\tapo /= scale;\n\t}\n\treturn boost::python::make_tuple(apo/scale, peri*scale);\n\t\n\t/*\n\t# just find apo or pericenter\n\trstart = self.findR_at_EL(E, L, rtry)\n\ttry:\n\t\trstart = rstart[0]\n\texcept:\n\t\tpass\n\ts = (1+1e-5) # scale factor for testing apo/peri\n\tr = rstart\n\t#print rstart, ekinrad(rstart/s), ekinrad(rstart*s), -L**2/(2*r**2) - (self.potentialr(r) - E), -L**2/(2*r**2) , (self.potentialr(r) - E)\n\tif (ekinrad(rstart/s) < 0) and (ekinrad(rstart*s) > 0): # we found pericenter\n\t\trp = rstart\n\t\tra = brentq(ekinrad, rstart*s, 1e9)\n\telse: # we found apocenter\n\t\tra = rstart\n\t\trp = brentq(ekinrad, 1e-9, rstart/s)\n\t\n\t# sanity checks\n\tassert ekinrad(ra*s) < 0, \"available energy ar r > r_apo should be negative\"\n\tassert ekinrad(rp/s) < 0, \"available energy ar r < r_peri should be negative\"\n\tassert ekinrad(ra/s) > 0, \"available energy ar r < r_apo should be positive\"\n\tassert ekinrad(rp*s) > 0, \"available energy ar r > r_peri should be positive\"\n\tassert ra > rp, \"apocenter should be larger than pericenter\" \n\treturn ra/s, rp*s*/\n}\n\n\n\nvoid py_export_profile() {\n\tclass_< ProfileModel, boost::noncopyable >(\"ProfileModel\", no_init)\n\t\t.def(\"get_apo_peri\", (&ProfileModel::get_apo_peri))\n\t\t.def(\"Lmax_at_E\", (&ProfileModel::Lmax_at_E))\n\t\t.def(\"Lmax_and_rcirc_at_E\", (&ProfileModel::Lmax_and_rcirc_at_E_))\n\t\t.def(\"rcirc_at_E\", (&ProfileModel::rcirc_at_E))\n\t\t.def(\"rmax_at_E\", (&ProfileModel::rmax_at_E))\n\t\t\n\t\t;\n\tclass_<ProfileModel1C, bases<ProfileModel>, boost::noncopyable  >(\"ProfileModel1C\", init<Profile*>())\n\t\t.def(\"densityr\", (&ProfileModel1C::densityr))\n\t\t.def(\"dphidr\", (&ProfileModel1C::dphidr))\n\t\t.def(\"potentialr\", (&ProfileModel1C::potentialr))\n\t\t;\n\tclass_<ProfileModel2C, bases<ProfileModel>, boost::noncopyable  >(\"ProfileModel2C\", init<Profile*,Profile*>())\n\t\t.def(\"densityr\", (&ProfileModel2C::densityr))\n\t\t.def(\"dphidr\", (&ProfileModel2C::dphidr))\n\t\t.def(\"potentialr\", (&ProfileModel2C::potentialr))\n\t\t;\n\t\n\tclass_< Profile, boost::noncopyable >(\"Profile\", no_init)\n\t\t.def(\"densityr\", pure_virtual(&Profile::densityr))\n\t\t;\n\tclass_< Density, boost::noncopyable >(\"Density\", no_init)\n\t\t.def(\"densityr\", pure_virtual(&Density::densityr))\n\t\t;\n\t//py_export_profile_profile<Plummer, init<double, double, double>>(\"Plummer\");\n\t//init<double, double, double>((boost::python::arg(\"b\"), boost::python::arg(\"M\"), boost::python::arg(\"G\")))\n\tpy_export_profile_profile_kw<Plummer>(\"Plummer\", init<double, double, double>((boost::python::arg(\"M\"), boost::python::arg(\"b\"), boost::python::arg(\"G\")=GravConst)));\n\t/*class_<Plummer, bases<Profile, Density> >(\"Plummer\", init<double, double, double>())\n\t\t.def(\"potentialr\", (&Plummer::potentialr))\n\t\t.def(\"densityr\", (&Plummer::densityr))\n\t\t.def(\"densityR\", (&Plummer::densityR))\n\t\t.def(\"dphidr\", (&Plummer::dphidr))\n\t\t//.def(\"dphidr2\", (&Plummer::dphidr2))\n\t\t;\n\t*/\n\t//py_export_profile_profile_kw<ProjectedExponential>(\"ProjectedExponential\", init<double, double, double>((boost::python::arg(\"M\"), boost::python::arg(\"scale\"), boost::python::arg(\"G\")=GravConst)));\n\tpy_export_profile_profile_kw<ProjectedExponential>(\"ProjectedExponential\", init<double, double, double>());\n\t\n\t\n\tclass_<TestCase, bases<Profile, Density> >(\"TestCase\", init<double, double, double>())\n\t\t.def(\"potentialr\", (&TestCase::potentialr))\n\t\t.def(\"densityr\", (&TestCase::densityr))\n\t\t.def(\"densityR\", (&TestCase::densityR))\n\t\t.def(\"dphidr\", (&TestCase::dphidr))\n\t\t//.def(\"dphidr2\", (&TestCase::dphidr2))\n\t\t;\n\tclass_<LogarithmicProfile, bases<Profile, Density> >(\"LogarithmicProfile\", init<double, double>())\n\t\t.def(\"densityr\", (&LogarithmicProfile::densityr))\n\t\t.def(\"densityR\", (&LogarithmicProfile::densityR))\n\t\t.def(\"dphidr\", (&LogarithmicProfile::dphidr))\n\t\t//.def(\"dphidr2\", (&LogarithmicProfile::dphidr2))\n\t;\n\tclass_<Isochrone, bases<Profile, Density> >(\"Isochrone\", init<double, double, double>())\n\t\t.def(\"densityr\", (&Isochrone::densityr))\n\t\t.def(\"densityR\", (&Isochrone::densityR))\n\t\t.def(\"dphidr\", (&Isochrone::dphidr))\n\t\t//.def(\"dphidr2\", (&Isochrone::dphidr2))\n\t\t.def(\"potentialr\", (&Isochrone::potentialr))\n\t\t;\n\tclass_<NullProfile, bases<Profile, Density> >(\"NullProfile\", init<>())\n\t\t.def(\"densityr\", (&NullProfile::densityr))\n\t\t.def(\"densityR\", (&NullProfile::densityR))\n\t\t.def(\"dphidr\", (&NullProfile::dphidr))\n\t\t//.def(\"dphidr2\", (&NullProfile::dphidr2))\n\t;\n\tclass_<Hernquist, bases<Profile, Density> >(\"Hernquist\", init<double, double, double>())\n\t\t.def(\"densityr\", (&Hernquist::densityr))\n\t\t.def(\"densityR\", (&Hernquist::densityR))\n\t\t.def(\"dphidr\", (&Hernquist::dphidr))\n\t\t.def(\"potentialr\", (&Hernquist::potentialr))\n\t\t;\n\tclass_<Jaffe, bases<Profile, Density> >(\"Jaffe\", init<double, double, double>())\n\t\t.def(\"densityr\", (&Jaffe::densityr))\n\t\t.def(\"densityR\", (&Jaffe::densityR))\n\t\t.def(\"dphidr\", (&Jaffe::dphidr))\n\t\t.def(\"potentialr\", (&Jaffe::potentialr))\n\t\t;\n\tclass_<Einasto, bases<Profile, Density> >(\"Einasto\", init<double, double, double, double>())\n\t\t.def(\"densityr\", (&Einasto::densityr))\n\t\t.def(\"densityR\", (&Einasto::densityR))\n\t\t.def(\"dphidr\", (&Einasto::dphidr))\n\t\t.def(\"potentialr\", (&Einasto::potentialr))\n\t\t;\n\tclass_<Burkert, bases<Profile, Density> >(\"Burkert\", init<double, double, double>())\n\t\t.def(\"densityr\", (&Burkert::densityr))\n\t\t.def(\"densityR\", (&Burkert::densityR))\n\t\t.def(\"dphidr\", (&Burkert::dphidr))\n\t\t.def(\"potentialr\", (&Burkert::potentialr))\n\t\t;\n\tclass_<NFW, bases<Profile, Density> >(\"NFW\", init<double, double, double, double>())\n\t\t.def(\"densityr\", (&NFW::densityr))\n\t\t.def(\"potentialr\", (&NFW::potentialr))\n\t\t.def(\"dphidr\", (&NFW::dphidr))\n\t\t.def_readonly(\"c\", &NFW::c)\n\t\t.def_readonly(\"mass200\", &NFW::mass200)\n\t\t.def_readonly(\"r200\", &NFW::r200)\n\t\t.def_readonly(\"rs\", &NFW::rs)\n\t\t.def_readonly(\"rho0\", &NFW::rho0);\n\t;\n\tclass_<NFWCut, bases<Density> >(\"NFWCut\", init<double, double, double>())\n\t\t.def(\"densityr\", (&NFWCut::densityr))\n\t\t.def_readwrite(\"rs\", &NFWCut::rs)\n\t\t.def_readwrite(\"rte\", &NFWCut::rte)\n\t\t.def_readwrite(\"rho0\", &NFWCut::rho0)\n\t\t;\n\tclass_<TwoSlopeDensity, bases<Density> >(\"TwoSlopeDensity\", init<double, double, double, double, double>())\n\t\t.def(\"densityr\", (&TwoSlopeDensity::densityr))\n\t\t.def_readwrite(\"alpha\", &TwoSlopeDensity::alpha)\n\t\t.def_readwrite(\"beta\", &TwoSlopeDensity::beta)\n\t\t.def_readwrite(\"rho0\", &TwoSlopeDensity::rho0)\n\t\t.def_readwrite(\"rs\", &TwoSlopeDensity::rs)\n\t\t.def_readwrite(\"gamma\", &TwoSlopeDensity::gamma)\n\t\t;\n\tclass_<TwoSlopeDensityCut, bases<Density> >(\"TwoSlopeDensityCut\", init<double, double, double, double, double, double>())\n\t\t.def(\"densityr\", (&TwoSlopeDensityCut::densityr))\n\t\t.def_readwrite(\"alpha\", &TwoSlopeDensityCut::alpha)\n\t\t.def_readwrite(\"beta\", &TwoSlopeDensityCut::beta)\n\t\t.def_readwrite(\"rho0\", &TwoSlopeDensityCut::rho0)\n\t\t.def_readwrite(\"rs\", &TwoSlopeDensityCut::rs)\n\t\t.def_readwrite(\"gamma\", &TwoSlopeDensityCut::gamma)\n\t\t.def_readwrite(\"rte\", &TwoSlopeDensityCut::rte)\n\t\t;\n\tclass_<BrokenPowerLawDensitySoft3, bases<Density> >(\"BrokenPowerLawDensitySoft3\", init<double, double, double, double, double, double, double, double>())\n\t\t.def(\"densityr\", (&BrokenPowerLawDensitySoft3::densityr))\n\t\t.def_readwrite(\"rho0\", &BrokenPowerLawDensitySoft3::rho0)\n\t\t.def_readwrite(\"s1\", &BrokenPowerLawDensitySoft3::s1)\n\t\t.def_readwrite(\"s2\", &BrokenPowerLawDensitySoft3::s2)\n\t\t.def_readwrite(\"s3\", &BrokenPowerLawDensitySoft3::s3)\n\t\t.def_readwrite(\"gamma1\", &BrokenPowerLawDensitySoft3::gamma1)\n\t\t.def_readwrite(\"gamma2\", &BrokenPowerLawDensitySoft3::gamma2)\n\t\t.def_readwrite(\"rs1\", &BrokenPowerLawDensitySoft3::rs1)\n\t\t.def_readwrite(\"rs2\", &BrokenPowerLawDensitySoft3::rs2)\n\t\t;\n\t\n}\n\n\n}\n", "meta": {"hexsha": "8945770a1ac2af654c8835b315f047809695fe7e", "size": 12590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/profile.cpp", "max_stars_repo_name": "maartenbreddels/mab", "max_stars_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T04:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T04:10:34.000Z", "max_issues_repo_path": "gdfast/src/profile.cpp", "max_issues_repo_name": "maartenbreddels/mab", "max_issues_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdfast/src/profile.cpp", "max_forks_repo_name": "maartenbreddels/mab", "max_forks_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1386430678, "max_line_length": 199, "alphanum_fraction": 0.6633836378, "num_tokens": 4434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4479438587533811}}
{"text": "// Copyright (c) 2021 Stig Rune Sellevag\n//\n// This file is distributed under the MIT License. See the accompanying file\n// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms\n// and conditions.\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 5054)\n#endif\n\n#include <scilib/mdarray.h>\n#include <scilib/linalg.h>\n#include <chrono>\n#include <iostream>\n#include <valarray>\n#include <numeric>\n#include <Eigen/Dense>\n\nusing Timer = std::chrono::duration<double, std::micro>;\n\nvoid print(int n, const Timer& t_eigen, const Timer& t_sci, const Timer& t_val)\n{\n    std::cout << \"Dot product:\\n\"\n              << \"------------\\n\"\n              << \"size =            \" << n << '\\n'\n              << \"scilib/eigen =    \" << t_sci.count() / t_eigen.count() << \"\\n\"\n              << \"scilib/valarray = \" << t_sci.count() / t_val.count()\n              << \"\\n\\n\";\n}\n\nvoid benchmark(int n)\n{\n    Eigen::VectorXd aa(n);\n    Eigen::VectorXd ab(n);\n\n    aa.fill(1.0);\n    ab.fill(2.0);\n\n    auto t1 = std::chrono::high_resolution_clock::now();\n    double dot_eigen;\n    for (int it = 0; it < 10000; ++it) {\n        dot_eigen = aa.dot(ab);\n    }\n    auto t2 = std::chrono::high_resolution_clock::now();\n    Timer t_eigen = t2 - t1;\n    (void) dot_eigen; // ignore unused result\n\n    Sci::Vector<double> na(n);\n    Sci::Vector<double> nb(n);\n    na = 1.0;\n    nb = 2.0;\n    t1 = std::chrono::high_resolution_clock::now();\n    double sci;\n    for (int it = 0; it < 10000; ++it) {\n        sci = Sci::Linalg::dot(na.view(), nb.view());\n    }\n    t2 = std::chrono::high_resolution_clock::now();\n    Timer t_sci = t2 - t1;\n    (void) sci;\n\n    std::valarray<double> va(1.0, n);\n    std::valarray<double> vb(2.0, n);\n    t1 = std::chrono::high_resolution_clock::now();\n    double val;\n    for (int it = 0; it < 10000; ++it) {\n        val = std::inner_product(std::begin(va), std::end(va), std::begin(vb),\n                                 0.0);\n    }\n    t2 = std::chrono::high_resolution_clock::now();\n    Timer t_val = t2 - t1;\n    (void) val;\n\n    print(n, t_eigen, t_sci, t_val);\n}\n\nint main()\n{\n    int n = 10;\n    benchmark(n);\n\n    n = 100;\n    benchmark(n);\n\n    n = 1000;\n    benchmark(n);\n\n    n = 10000;\n    benchmark(n);\n\n    n = 100000;\n    benchmark(n);\n}\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n", "meta": {"hexsha": "2b64ca64e6f4fb9992d7cd93eda9546383c0510d", "size": 2328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bench/bench_dot.cpp", "max_stars_repo_name": "stigrs/scilib", "max_stars_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bench/bench_dot.cpp", "max_issues_repo_name": "stigrs/scilib", "max_issues_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bench/bench_dot.cpp", "max_forks_repo_name": "stigrs/scilib", "max_forks_repo_head_hexsha": "c49f1f882bf2031a4de537e0f5701b2648af181f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7551020408, "max_line_length": 80, "alphanum_fraction": 0.5652920962, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.44794385875338105}}
{"text": "/**\n * DD cut generation for CPLEX\n */\n\n#include <cassert>\n#include <queue>\n#include <stack>\n#include <boost/unordered_set.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/any.hpp>\n#include \"cut_cplex.hpp\"\n#include \"flow_decomp.hpp\"\n#include \"../bdd/bdd.hpp\"\n#include \"../util/graph.hpp\"\n#include \"../util/stats.hpp\"\n\nusing boost::any_cast;\nusing boost::unordered_set;\n\n\n/**\n * Generates a cut for the set of points represented by the given BDD towards the direction of the given point.\n * All input must be in layer space. Store additional information in cut_info unless it is NULL (default).\n */\nInequality* generate_bdd_inequality(BDD* bdd, const vector<double>& x, const vector<double>& interior_point, Options* options,\n                                    CutInfo* cut_info /* = NULL */)\n{\n\tInequality* facet;\n\tint nvars = bdd->layers.size() - 1;\n\n\tStats stats;\n\tstats.register_name(\"cut-time\");\n\tstats.start_timer(0);\n\ttry {\n\n\t\tIloEnv env;\n\t\tIloModel model(env);\n\n\t\tIloNumVarArray u(env, nvars);\n\t\tIloArray<IloNumVarArray> v(env, nvars+1);\n\n\t\t// Create variables\n\t\tfor (int i = 0; i < nvars; ++i) {\n\t\t\tu[i] = IloNumVar(env, -IloInfinity, IloInfinity, IloNumVar::Float, (\"u\" + to_string(i)).c_str());\n\t\t}\n\n\t\tfor (int i = 0; i < nvars + 1; ++i) {\n\t\t\tint size = bdd->layers[i].size();\n\t\t\tv[i] = IloNumVarArray(env, size);\n\t\t\tfor (int j = 0; j < size; ++j) {\n\t\t\t\tv[i][j] = IloNumVar(env, -IloInfinity, IloInfinity, IloNumVar::Float,\n\t\t\t\t                    (\"v\" + to_string(i) + \",\" + to_string(j)).c_str());\n\t\t\t}\n\t\t}\n\n\t\t// Define objective\n\t\tIloObjective obj = IloAdd(model, IloMaximize(env));\n\t\tfor (int i = 0; i < nvars; ++i) {\n\t\t\tobj.setLinearCoef(u[i], x[i] - interior_point[i]);\n\t\t}\n\n\t\t// Initialize constraint arrays\n\t\tIloArray<IloRangeArray> zero_arc_constrs(env, nvars + 1);\n\t\tIloArray<IloRangeArray> one_arc_constrs(env, nvars + 1);\n\t\tfor (int i = 0; i < nvars + 1; ++i) {\n\t\t\tint size = bdd->layers[i].size();\n\t\t\tzero_arc_constrs[i] = IloRangeArray(env, size);\n\t\t\tone_arc_constrs[i] = IloRangeArray(env, size);\n\t\t}\n\n\t\t// Add constraints\n\t\tfor (int i = 0; i < nvars; ++i) {\n\t\t\tint size = bdd->layers[i].size();\n\t\t\tfor (int j = 0; j < size; ++j) {\n\t\t\t\tNode* zero_node = bdd->layers[i][j]->zero_arc;\n\t\t\t\tNode* one_node = bdd->layers[i][j]->one_arc;\n\n\t\t\t\tif (zero_node != NULL) {\n\t\t\t\t\t// cout << i << \",\" << j << \" / \" << zero_node->layer << \",\" << zero_node->id << endl;\n\t\t\t\t\t// model.add( v[zero_node->layer][zero_node->id] <= v[i][j] );\n\t\t\t\t\tzero_arc_constrs[i][j] = IloRange(env, v[zero_node->layer][zero_node->id] - v[i][j], 0,\n\t\t\t\t\t                                  (\"a0_\" + to_string(i) + \",\" + to_string(j)).c_str());\n\t\t\t\t\tmodel.add(zero_arc_constrs[i][j]);\n\t\t\t\t}\n\t\t\t\tif (one_node != NULL) {\n\t\t\t\t\t// cout << i << \",\" << j << \" / \" << one_node->layer << \",\" << one_node->id << endl;\n\t\t\t\t\t// model.add( v[one_node->layer][one_node->id] <= v[i][j] - u[i] );\n\t\t\t\t\tone_arc_constrs[i][j] = IloRange(env, v[one_node->layer][one_node->id] - v[i][j] + u[i], 0,\n\t\t\t\t\t                                 (\"a1_\" + to_string(i) + \",\" + to_string(j)).c_str());\n\t\t\t\t\tmodel.add(one_arc_constrs[i][j]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// v_s = 1 + u^T interior_point\n\t\tIloExpr vs(env);\n\t\tvs += 1;\n\t\tfor (int i = 0; i < nvars; ++i) {\n\t\t\tvs += u[i] * interior_point[i];\n\t\t}\n\t\tassert(bdd->layers[0].size() == 1);\n\t\tmodel.add(v[0][0] == vs);\n\n\t\t// v_t = 0\n\t\tassert(bdd->layers[nvars].size() == 1);\n\t\tmodel.add(v[nvars][0] == 0);\n\n\t\t// Create CPLEX object\n\t\tIloCplex cplex(model);\n\t\tcplex.setParam(IloCplex::Threads, 1);\n\t\tcplex.setParam(IloCplex::AggInd, 100); // Important parameter for efficiency; there is often a lot to aggregate\n\t\t// cplex.setOut(env.getNullStream()); // Suppress output\n\n\t\tstats.end_timer(0);\n\t\tcout << \"Time to construct LP model: \" << stats.get_time(0) << endl;\n\t\tcout << cplex.getNrows() << \" rows and \" << cplex.getNcols() << \" columns\" << endl;\n\t\t// cplex.exportModel(\"cutlp.lp\");\n\n\t\t// Solve cut LP\n\t\tstats.start_timer(0);\n\t\tcplex.solve();\n\t\tstats.end_timer(0);\n\n\t\tcout << \"Time to solve LP: \" << stats.get_time(0) << endl;\n\n\t\tdouble bound = cplex.getObjValue();\n\t\tcout << \"Polar opt obj: \" << bound << endl;\n\n\t\t// // Debugging info, if unbounded\n\t\t// cout << \"Status: \" << cplex.getStatus() << endl;\n\t\t// IloNumArray ray_vals(env);\n\t\t// IloNumVarArray ray_vars(env);\n\t\t// cplex.getRay(ray_vals, ray_vars);\n\t\t// cout << \"Ray: \";\n\t\t// for (int i = 0; i < ray_vars.getSize(); ++i) {\n\t\t//   cout << ray_vars[i] << \" \" << ray_vals[i] << endl;\n\t\t// }\n\t\t// cout << endl;\n\n\t\t// Restrict to optimal face and perturb to obtain extreme point of the polar\n\t\tif (options->cut_perturbation_iterative) {\n\t\t\tperturb_bdd_cut_iterative(env, cplex, model, u, obj, nvars, x, interior_point);\n\t\t} else if (options->cut_perturbation_random) {\n\t\t\tperturb_bdd_cut_random(env, cplex, model, u, obj, nvars, x, interior_point);\n\t\t}\n\n\t\tvector<double> coeffs(nvars);\n\t\tdouble rhs;\n\n\t\t// Retrieve left-hand side coefficients: u\n\t\tfor (int i = 0; i < nvars; ++i) {\n\t\t\tif (cplex.isExtracted(u[i])) {\n\t\t\t\tcoeffs[i] = cplex.getValue(u[i]);\n\t\t\t} else {\n\t\t\t\t// If u[i] not extracted, this means it was not added to model: objective is zero and not added to constraints\n\t\t\t\t// Could be a bug, but it also may be the valid scenario of the variable being fixed to zero in the DD\n\t\t\t\tcoeffs[i] = 0;\n\t\t\t}\n\t\t}\n\n\t\t// Retrieve right-hand side: 1 + u^T interior\n\t\trhs = 1;\n\t\tfor (int i = 0; i < nvars; ++i) {\n\t\t\trhs += coeffs[i] * interior_point[i];\n\t\t}\n\n\t\t// Inequality u^T x <= 1 + u^T interior\n\t\tfacet = new Inequality();\n\t\tfacet->coeffs = coeffs;\n\t\tfacet->rhs = rhs;\n\n\t\t// cout << \"Relaxation facet generated (normalized), BDD order: \";\n\t\t// for( int i = 0; i < nvars; ++i ) {\n\t\t//   cout << facet->coeffs[i] / facet->rhs << \" \";\n\t\t// }\n\t\t// cout << \"<= 1\" << endl;\n\t\t// cout << \"Relaxation facet generated, BDD order: \";\n\t\t// for( int i = 0; i < nvars; ++i ) {\n\t\t//   cout << facet->coeffs[i] << \" \";\n\t\t// }\n\t\t// cout << \"<= \" << facet->rhs << endl;\n\n\t\tdouble lhs = 0;\n\t\tfor (int i = 0; i < nvars; ++i) {\n\t\t\tlhs += facet->coeffs[i] * x[i];\n\t\t\t// cout << \"coeff = \" << facet->coeffs[i] << \", x = \" << x[i] << endl;\n\t\t}\n\t\tcout << \"LHS = \" << lhs << \" / Violation: \" << lhs - facet->rhs << endl;\n\n\t\tcout << \"Distance = \" << get_distance_hyperplane_point(facet, x) << endl;\n\n\t\t// // Debugging info: Assert complementary slackness\n\t\t// int n_tight = 0;\n\t\t// int n_nzdual = 0;\n\t\t// for (int i = 0; i < nvars; ++i) {\n\t\t//  \tint size = bdd->layers[i].size();\n\t\t//  \t// cout << \"u[\" << i << \"] = \" << cplex.getValue(u[i]) << endl;\n\t\t//  \tfor (int j = 0; j < size; ++j) {\n\t\t//  \t\tNode* zero_node = bdd->layers[i][j]->zero_arc;\n\t\t//  \t\tNode* one_node = bdd->layers[i][j]->one_arc;\n\t\t//  \t\tif (zero_node != NULL) {\n\t\t//  \t\t\tcout << \"Dual (\" << i << \",\" << j << \") -0-> (\" << zero_node->layer << \",\" << zero_node->id << \"): \" << cplex.getDual(zero_arc_constrs[i][j]);\n\t\t//  \t\t\tcout << \" / slack: \" << cplex.getValue(v[zero_node->layer][zero_node->id]) - cplex.getValue(v[i][j]) << endl;\n\t\t//  \t\t\tassert(DBL_EQ(cplex.getDual(zero_arc_constrs[i][j]), 0) || DBL_EQ(cplex.getValue(v[zero_node->layer][zero_node->id]), cplex.getValue(v[i][j])));\n\t\t//  \t\t\tif (DBL_EQ(cplex.getValue(v[zero_node->layer][zero_node->id]), cplex.getValue(v[i][j])))\n\t\t//  \t\t\t\tn_tight++;\n\t\t//  \t\t\tif (!DBL_EQ(cplex.getDual(zero_arc_constrs[i][j]), 0))\n\t\t//  \t\t\t\tn_nzdual++;\n\t\t//  \t\t}\n\t\t//  \t\tif (one_node != NULL) {\n\t\t//  \t\t\tcout << \"Dual (\" << i << \",\" << j << \") -1-> (\" << one_node->layer << \",\" << one_node->id << \"): \" << cplex.getDual(one_arc_constrs[i][j]);\n\t\t//  \t\t\tcout << \" / slack: \" << cplex.getValue(v[one_node->layer][one_node->id]) - (cplex.getValue(v[i][j]) - cplex.getValue(u[i])) << endl;\n\t\t//  \t\t\tassert(DBL_EQ(cplex.getDual(one_arc_constrs[i][j]), 0) || DBL_EQ(cplex.getValue(v[one_node->layer][one_node->id]), cplex.getValue(v[i][j]) - cplex.getValue(u[i])));\n\t\t//  \t\t\tif (DBL_EQ(cplex.getValue(v[one_node->layer][one_node->id]), cplex.getValue(v[i][j]) - cplex.getValue(u[i])))\n\t\t//  \t\t\t\tn_tight++;\n\t\t//  \t\t\tif (!DBL_EQ(cplex.getDual(one_arc_constrs[i][j]), 0))\n\t\t//  \t\t\t\tn_nzdual++;\n\t\t//  \t\t}\n\t\t//  \t\t// cout << \"v[\" << i << \"][\" << j << \"] = \" << cplex.getValue(v[i][j]) << endl;\n\t\t//  \t}\n\t\t// }\n\t\t// // cout << \"Tight arcs = \" << n_tight << \" / Nonzero duals = \" << n_nzdual << endl;\n\n\t\t// Store additional information in cut_info\n\t\tif (cut_info != NULL) {\n\t\t\tint bdd_size = bdd->layers.size();\n\t\t\tcut_info->zero_arc_flow.clear();\n\t\t\tcut_info->zero_arc_flow.resize(bdd_size);\n\t\t\tcut_info->one_arc_flow.clear();\n\t\t\tcut_info->one_arc_flow.resize(bdd_size);\n\t\t\tfor (int layer = 0; layer < bdd_size; ++layer) {\n\t\t\t\tint size = bdd->layers[layer].size();\n\t\t\t\tfor (int k = 0; k < size; ++k) {\n\t\t\t\t\tNode* node = bdd->layers[layer][k];\n\t\t\t\t\tdouble zero_flow = 0;\n\t\t\t\t\tif (node->zero_arc != NULL) {\n\t\t\t\t\t\tzero_flow = cplex.getDual(zero_arc_constrs[layer][k]);\n\t\t\t\t\t}\n\t\t\t\t\tdouble one_flow = 0;\n\t\t\t\t\tif (node->one_arc != NULL) {\n\t\t\t\t\t\tone_flow = cplex.getDual(one_arc_constrs[layer][k]);\n\t\t\t\t\t}\n\t\t\t\t\tcut_info->zero_arc_flow[layer].push_back(zero_flow);\n\t\t\t\t\tcut_info->one_arc_flow[layer].push_back(one_flow);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// // Uncomment for debugging purposes\n\t\t\t// print_all_paths_in_flow(bdd, cut_info->zero_arc_flow, cut_info->one_arc_flow);\n\t\t}\n\n\t\tobj.end();\n\t\tzero_arc_constrs.end();\n\t\tone_arc_constrs.end();\n\t\tenv.end();\n\n\t} catch (IloException& ex) {\n\t\tcout << \"error: \" << ex << endl;\n\t\texit(1);\n\t}\n\n\treturn facet;\n}\n\n\nvoid perturb_bdd_cut_iterative(IloEnv env, IloCplex cplex, IloModel model, const IloNumVarArray u, IloObjective obj, int nvars,\n\tconst vector<double>& x, const vector<double>& interior_point)\n{\n\t// cplex.setOut(env.getNullStream()); // Suppress output\n\tcout << \"Before perturbation: \";\n\tfor (int i = 0; i < nvars; ++i) {\n\t\tcout << cplex.getValue(u[i]) << \" \";\n\t}\n\tcout << endl;\n\n\tIloExpr obj_expr(env);\n\tfor (int i = 0; i < nvars; ++i) {\n\t\tobj_expr += u[i] * (x[i] - interior_point[i]);\n\t}\n\tdouble bound = cplex.getObjValue();\n\t// model.add( obj_expr == bound );\n\tmodel.add(obj_expr <= bound + 1e-5);\n\tmodel.add(obj_expr >= bound - 1e-5);\n\tobj_expr.end();\n\n\tfor (int k = 0; k < nvars; ++k) {\n\t\tfor (int i = 0; i < nvars; ++i) {\n\t\t\tobj.setLinearCoef(u[i], 0);\n\t\t}\n\t\tobj.setLinearCoef(u[k], 1);\n\t\tcplex.solve();\n\t\tif (k != nvars - 1) {\n\t\t\tcout << \"u[\" << k << \"] = \" << cplex.getObjValue() << endl;\n\t\t\tif (DBL_EQ(cplex.getObjValue(), 0)) {\n\t\t\t\tu[k].setBounds(0, 0);\n\t\t\t} else {\n\t\t\t\t// u[k].setBounds(cplex.getObjValue(), cplex.getObjValue());\n\t\t\t\tu[k].setBounds(cplex.getObjValue() - 1e-5, cplex.getObjValue() + 1e-5);\n\t\t\t}\n\t\t}\n\t}\n\n\tcout << \"After perturbation: \";\n\tfor (int i = 0; i < nvars; ++i) {\n\t\tcout << cplex.getValue(u[i]) << \" \";\n\t}\n\tcout << endl;\n}\n\n\nvoid perturb_bdd_cut_random(IloEnv env, IloCplex cplex, IloModel model, const IloNumVarArray u, IloObjective obj, int nvars,\n\tconst vector<double>& x, const vector<double>& interior_point)\n{\n\t// Perturb the objective slightly\n\tcout << \"Before perturbation: \";\n\tfor (int i = 0; i < nvars; ++i) {\n\t\tcout << cplex.getValue(u[i]) << \" \";\n\t}\n\tcout << endl;\n\n\tIloExpr obj_expr(env);\n\tfor (int i = 0; i < nvars; ++i) {\n\t\tobj_expr += u[i] * (x[i] - interior_point[i]);\n\t}\n\tdouble bound = cplex.getObjValue();\n\tmodel.add(obj_expr == bound);\n\t// model.add( obj_expr <= bound + 1e-5 );\n\t// model.add( obj_expr >= bound - 1e-5 );\n\tobj_expr.end();\n\n\tfor (int i = 0; i < nvars; ++i) {\n\t\tdouble pert = ((double) rand() / (double) RAND_MAX - 0.5) * 2 * 1e-4;\n\t\tdouble new_coeff = x[i] - interior_point[i] + pert;\n\t\tif (new_coeff < 0) {\n\t\t\tnew_coeff = x[i] - interior_point[i] - pert;\n\t\t}\n\t\tobj.setLinearCoef(u[i], new_coeff);\n\t}\n\n\tcplex.solve();\n\n\tcout << \"After perturbation: \";\n\tfor (int i = 0; i < nvars; ++i) {\n\t\tcout << cplex.getValue(u[i]) << \" \";\n\t}\n\tcout << endl;\n}\n", "meta": {"hexsha": "05af53a0db2691b4250fdeb59fb21d427cdfb26b", "size": 11695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ddopt/src/cut/cut_cplex.cpp", "max_stars_repo_name": "ctjandra/ddopt-cut", "max_stars_repo_head_hexsha": "0ca4358e7c27a8a56fb2640d450356dcda91b7f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-15T03:54:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T03:06:05.000Z", "max_issues_repo_path": "ddopt/src/cut/cut_cplex.cpp", "max_issues_repo_name": "ctjandra/ddopt-cut", "max_issues_repo_head_hexsha": "0ca4358e7c27a8a56fb2640d450356dcda91b7f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ddopt/src/cut/cut_cplex.cpp", "max_forks_repo_name": "ctjandra/ddopt-cut", "max_forks_repo_head_hexsha": "0ca4358e7c27a8a56fb2640d450356dcda91b7f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-07T02:29:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-05T13:21:13.000Z", "avg_line_length": 33.6063218391, "max_line_length": 173, "alphanum_fraction": 0.5819581018, "num_tokens": 3965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.44793890167311246}}
{"text": "#ifndef EXPSUM_REDUCTION_CONEIG_SYM_RRD_HPP\n#define EXPSUM_REDUCTION_CONEIG_SYM_RRD_HPP\n\n#include <cassert>\n\n#include <armadillo>\n\n#include \"arma/lapack_extra.hpp\"\n\nnamespace expsum\n{\n\n//\n// Compute accurate con-eigenvalue decomposition of the matrix $A=XD^{2}X^{H}$\n//\n// This class computes the con-eigenvalue decomposition\n//\n// ``` math\n//   A U = \\Lambda \\overline{U},\n// ```\n//\n// of a real symmetric (or complex Hermitian) and positive-definite matrix $A$\n// having a rank-revealing decomposition of the form, $A = X D^{2} X^{H}$.\n//\n// @X  A matrix of type `T` of dimension $m \\times n$.\n//     On entry, the rank-revealing factor $X$.\n//     On exit, orthonormal con-eigenvectors of the matrix $A$.\n// @d  A vector of real values with size $n$.\n//     On entry, the diagonal elements of rank-revealing factor $D$. The\n//     diagonal of $D$ must be all positive and decreasing.\n//     On exit, con-eigenvalues of the matrix $A$.\n// @threshold threshold value for con-eigenvalues.\n//\n\ntemplate <typename T>\nclass coneig_sym_rrd\n{\npublic:\n    // Scalar types\n    using size_type    = arma::uword;\n    using value_type   = T;\n    using real_type    = typename arma::get_pod_type<T>::result;\n    using complex_type = std::complex<real_type>;\n\n    // Matrix/Vector types\n    using vector_type         = arma::Col<value_type>;\n    using matrix_type         = arma::Mat<value_type>;\n    using index_vector_type   = arma::uvec;\n    using real_vector_type    = arma::Col<real_type>;\n    using real_matrix_type    = arma::Mat<real_type>;\n    using complex_vector_type = arma::Col<complex_type>;\n    using complex_matrix_type = arma::Mat<complex_type>;\n\n    static size_type run(matrix_type& X, real_vector_type& d,\n                         real_type threshold, value_type* work,\n                         real_type* rwork);\n\nprivate:\n    //\n    // Compute QR factorization of matrix G = Q * R.\n    //\n    static void qr_factorization(matrix_type& G, value_type* work)\n    {\n        auto n          = static_cast<arma::blas_int>(G.n_rows);\n        auto lwork      = n * n;\n        value_type* tau = work + n * n;\n        arma::blas_int info;\n        arma::lapack::geqrf(&n, &n, G.memptr(), &n, tau, work, &lwork, &info);\n        if (info)\n        {\n            std::ostringstream msg;\n            msg << \"(coneig_sym_rrd) xGEQRF failed with info \" << info;\n            throw std::runtime_error(msg.str());\n        }\n    }\n    //\n    // Solve R * Y = X, where R is upper triangular matrix.\n    //\n    static void tri_solve(matrix_type& R, matrix_type& X)\n    {\n        char uplo  = 'U';\n        char trans = 'N';\n        char diag  = 'N';\n        auto m     = static_cast<arma::blas_int>(R.n_rows);\n        auto nrhs  = static_cast<arma::blas_int>(X.n_cols);\n        arma::blas_int info;\n        arma::lapack::trtrs(&uplo, &trans, &diag, &m, &nrhs, R.memptr(), &m,\n                            X.memptr(), &m, &info);\n        if (info)\n        {\n            std::ostringstream msg;\n            msg << \"(coneig_sym_rrd) xTRTRS failed with info \" << info;\n            throw std::runtime_error(msg.str());\n        }\n    }\n    //\n    // Compute singular values and corresponding left singular vectors of upper\n    // triangular matrix R using one-sided Jacobi method.\n    //\n    // --- for real matrix\n    static void jacobi_svd(matrix_type& R, real_vector_type& sigma,\n                           real_type* work, real_type* /*dummy*/)\n    {\n        assert(R.n_rows == R.n_cols);\n        assert(sigma.n_elem == R.n_cols);\n\n        char joba = 'U'; // Input matrix R is upper triangular matrix\n        char jobu = 'U'; // Compute left singular vectors\n        char jobv = 'N'; // Do not compute right singular vectors\n        auto n    = static_cast<arma::blas_int>(R.n_cols);\n        auto mv   = arma::blas_int();\n        auto ldv  = arma::blas_int(2);\n\n        real_type dummy_v[2];\n        auto lwork = 2 * n;\n\n        arma::blas_int info;\n\n        arma::lapack::gesvj(&joba, &jobu, &jobv, &n, &n, R.memptr(), &n,\n                            sigma.memptr(), &mv, &dummy_v[0], &ldv, work,\n                            &lwork, &info);\n\n        if (info < arma::blas_int())\n        {\n            std::ostringstream msg;\n            msg << \"[s/d]GESVJ error: \" << -info\n                << \" th argument had an illegal value\";\n            throw std::logic_error(msg.str());\n        }\n\n        if (info > arma::blas_int())\n        {\n            std::ostringstream msg;\n            msg << \"[s/d]GESVJ did not converge in the maximal allowed number \"\n                << info << \" of sweeps\";\n            throw std::runtime_error(msg.str());\n        }\n    }\n    // --- for complex matrix\n    static void jacobi_svd(matrix_type& R, real_vector_type& sigma,\n                           complex_type* work, real_type* rwork)\n    {\n        assert(R.n_rows == R.n_cols);\n        assert(sigma.n_elem == R.n_cols);\n\n        char joba = 'U'; // Input matrix R is upper triangular matrix\n        char jobu = 'U'; // Compute left singular vectors\n        char jobv = 'N'; // Do not compute right singular vectors\n        auto n    = static_cast<arma::blas_int>(R.n_cols);\n        auto mv   = arma::blas_int();\n        auto ldv  = arma::blas_int(2);\n\n        complex_type dummy_v[2];\n        auto lwork  = 2 * n;\n        auto lrwork = std::max(arma::blas_int(6), 2 * n);\n\n        arma::blas_int info;\n\n        arma::lapack::gesvj(&joba, &jobu, &jobv, &n, &n, R.memptr(), &n,\n                            sigma.memptr(), &mv, &dummy_v[0], &ldv, work,\n                            &lwork, rwork, &lrwork, &info);\n\n        if (info < arma::blas_int())\n        {\n            std::ostringstream msg;\n            msg << \"[c/z]GESVJ error: \" << -info\n                << \" th argument had an illegal value\";\n            throw std::logic_error(msg.str());\n        }\n\n        if (info > arma::blas_int())\n        {\n            std::ostringstream msg;\n            msg << \"[c/z]GESVJ did not converge in the maximal allowed number \"\n                << info << \" of sweeps\";\n            throw std::runtime_error(msg.str());\n        }\n    }\n};\n\n//\n// Required memory for workspace\n//\n// work size:\n//    for matrix G : n * n\n//    for matrix Y : n * n\n//    for workspace: 2 * n\n//    ------------------------------\n//    Total        : 2 * n * (n + 1)\n//\n// rwork size:\n//    if `T` is real type   : n\n//    if `T` is complex type: 3 * n\n//\ntemplate <typename T>\ntypename coneig_sym_rrd<T>::size_type\nconeig_sym_rrd<T>::run(matrix_type& X, real_vector_type& d, real_type threshold,\n                       value_type* work, real_type* rwork)\n{\n    // const size_type m = X.n_rows;\n    const size_type n = X.n_cols;\n\n    value_type* ptr1 = work;\n    value_type* ptr2 = work + n * n;\n    value_type* ptr3 = work + 2 * n * n;\n\n    real_vector_type dinv(rwork, n, false, true);\n    dinv = real_type(1) / d;\n\n    //\n    // Form G = D * (X.st() * X) * D\n    //\n    matrix_type G(ptr1, n, n, false, true);\n    G = X.st() * X;\n    for (size_type j = 0; j < n; ++j)\n    {\n        for (size_type i = 0; i < n; ++i)\n        {\n            G(i, j) *= d(i) * d(j);\n        }\n    }\n    //\n    // Compute G = Q * R by Householder QR factorization\n    //\n    qr_factorization(G, ptr2);\n    matrix_type& R = G; // R = trimatu(G), on exit\n    //\n    // Compute SVD of R = U * S * V.t() using one-sided Jacobi method.\n    // We need singular values and left singular vectors here.\n    //\n    real_vector_type& sigma = d;\n    matrix_type U(ptr2, n, n, false, true);\n    U = arma::trimatu(R); // make a copy of matrix R\n    jacobi_svd(U, sigma, ptr3, rwork + n);\n\n    //-------------------------------------------------------------------------\n    // Truncation: discard con-eigenvalues if negligibly small\n    //-------------------------------------------------------------------------\n    auto sum_d     = real_type();\n    size_type nvec = n;\n    while (nvec)\n    {\n        sum_d += d(nvec - 1);\n        if (2 * sum_d > threshold)\n        {\n            break;\n        }\n        --nvec;\n    }\n\n    if (nvec == size_type(0))\n    {\n        return size_type();\n    }\n\n    //-------------------------------------------------------------------------\n    //\n    // The eigenvectors of A * conj(A) are given as\n    //\n    //   conj(X') = X * D * V * S^{-1/2}.\n    //\n    // However, direct evaluation of eigenvectors with this formula might be\n    // inaccurate since D is ill-conditioned. The following formula are used\n    // instead.\n    //\n    //   conj(X') = X * D * R^(-1) * U * S^{1/2}\n    //            = X * (D.inv() * R * D.inv())^(-1) * (D.inv() * U * S^{1/2})\n    //            = X * R1.inv() * X1\n    //\n    //-------------------------------------------------------------------------\n    //\n    // Compute X1 = D^(-1) * U * S^{1/2} [in-place]\n    //\n    matrix_type U_trunc(ptr2, n, nvec, false, true);\n    for (size_type j = 0; j < nvec; ++j)\n    {\n        const auto sj = std::sqrt(sigma(j));\n        for (size_type i = 0; i < n; ++i)\n        {\n            U_trunc(i, j) *= sj * dinv(i);\n        }\n    }\n    //\n    // Compute R1 = D^(-1) * R * D^(-1) [in-place]\n    //\n    for (size_type j = 0; j < n; ++j)\n    {\n        for (size_type i = 0; i <= j; ++i)\n        {\n            R(i, j) *= dinv(i) * dinv(j);\n        }\n    }\n    //\n    // Solve R1 * Y1 = X1 in-place\n    //\n    tri_solve(R, U_trunc);\n    //\n    // Compute con-eigenvectors U = conj(X) * conj(Y).\n    //\n    X.head_cols(nvec) = arma::conj(X) * arma::conj(U_trunc);\n    //\n    // Adjust phase factor of each con-eigenvectors, so that U^{T} * U = I\n    //\n    if (arma::is_complex<T>::value)\n    {\n        for (size_type j = 0; j < nvec; ++j)\n        {\n            auto xj          = X.col(j);\n            const auto t     = arma::dot(xj, xj);\n            const auto phase = t / std::abs(t);\n            const auto scale = std::sqrt(arma::access::alt_conj(phase));\n            xj *= scale;\n        }\n    }\n\n    return nvec;\n}\n\n} // namespace: expsum\n\n#endif /* EXPSUM_REDUCTION_CONEIG_SYM_RRD_HPP */\n", "meta": {"hexsha": "7332b875204403778d19a6e63a63398efb990651", "size": 10005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/reduction/coneig_sym_rrd.hpp", "max_stars_repo_name": "hide-ikeno/expsum", "max_stars_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/expsum/reduction/coneig_sym_rrd.hpp", "max_issues_repo_name": "hide-ikeno/expsum", "max_issues_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/expsum/reduction/coneig_sym_rrd.hpp", "max_forks_repo_name": "hide-ikeno/expsum", "max_forks_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0714285714, "max_line_length": 80, "alphanum_fraction": 0.5106446777, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.44793890167311234}}
{"text": "/*\nCopyright 2013-2015 Rogier van Dalen.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n#ifndef MATH_MAX_SEMIRING_HPP_INCLUDED\n#define MATH_MAX_SEMIRING_HPP_INCLUDED\n\n#include <limits>\n#include <iosfwd>\n#include <type_traits>\n\n#include <boost/mpl/bool.hpp>\n\n#include <boost/functional/hash_fwd.hpp>\n\n#include \"magma.hpp\"\n\n#include \"detail/is_close.hpp\"\n\nnamespace math {\n\n/**\nSemiring whose \\ref plus (and \\ref choose) operation picks the maximum of the\ntwo values.\n\\ref times performs multiplication on the underlying value.\n\nThe underlying value must always be non-negative, so that the additive identity\nhas value 0.\nThe multiplicative identity has value 1.\n\nDivision is only implemented for non-integer types.\n\nThis type supports Boost.Hash, if \\c boost/functional/hash.hpp is included.\n\n\\tparam Type\n    Underlying type that represents the value.\n*/\ntemplate <class Type> class max_semiring;\n\ntemplate <class Type> struct max_semiring_tag;\n\ntemplate <class Type> struct decayed_magma_tag <max_semiring <Type>>\n{ typedef max_semiring_tag <Type> type; };\n\ntemplate <class Type> class max_semiring {\nprivate:\n    Type value_;\npublic:\n    /**\n    Initialise with 0.\n    */\n    max_semiring() : value_()\n    { assert (value_ >= Type (0)); }\n\n    /**\n    Initialise with \\a value as the value.\n    */\n    explicit max_semiring (Type const & value) : value_ (value) {}\n\n    /**\n    Return the underlying value.\n    */\n    Type const & value() const { return value_; }\n};\n\nnamespace detail {\n\n    template <class Type> struct is_max_semiring_tag : boost::mpl::false_ {};\n    template <class Type> struct is_max_semiring_tag <max_semiring_tag <Type>>\n    : boost::mpl::true_ {};\n\n} // namespace detail\n\nMATH_MAGMA_GENERATE_OPERATORS (detail::is_max_semiring_tag)\n\nnamespace operation {\n\n    /* Queries. */\n\n    template <class Type>\n        struct is_member <max_semiring_tag <Type>, typename std::enable_if <\n            std::numeric_limits <Type>::has_quiet_NaN>::type>\n    {\n        // Detect NaN.\n        bool operator() (max_semiring <Type> const & v) const { return v == v; }\n    };\n\n    template <class Type> struct equal <max_semiring_tag <Type>> {\n        bool operator() (\n            max_semiring <Type> const & left, max_semiring <Type> const & right)\n            const\n        { return left.value() == right.value(); }\n    };\n\n    template <class Type> struct approximately_equal <max_semiring_tag <Type>,\n        typename std::enable_if <!std::numeric_limits <Type>::is_exact>::type>\n    {\n        bool operator() (\n            max_semiring <Type> const & left, max_semiring <Type> const & right)\n            const\n        {\n            static Type const tolerance = 1e-5;\n            return math::detail::is_close (left.value(), right.value(),\n                tolerance);\n        }\n    };\n\n    // compare always orders smaller values first.\n    template <class Type> struct compare <max_semiring_tag <Type>> {\n        bool operator() (\n            max_semiring <Type> const & left, max_semiring <Type> const & right)\n            const\n        { return left.value() < right.value(); }\n    };\n\n    // \"choose\" and \"plus\" both select the maximal element.\n    template <class Type>\n    struct order <max_semiring_tag <Type>, callable::choose>\n    : reverse_order <compare <max_semiring_tag <Type>>> {};\n\n    template <class Type>\n    struct order <max_semiring_tag <Type>, callable::plus>\n    : reverse_order <compare <max_semiring_tag <Type>>> {};\n\n    /* Produce. */\n\n    // Return the not-a-number value, not-a-number, if it is available.\n    template <class Type> struct non_member <max_semiring_tag <Type>, typename\n        std::enable_if <std::numeric_limits <Type>::has_quiet_NaN>::type>\n    {\n        max_semiring <Type> operator() () const {\n            return max_semiring <Type> (\n                std::numeric_limits <Type>::quiet_NaN());\n        }\n    };\n\n    template <class Type>\n        struct identity <max_semiring_tag <Type>, callable::times>\n    {\n        max_semiring <Type> operator() () const\n        { return max_semiring <Type> (1); }\n    };\n\n    template <class Type>\n        struct identity <max_semiring_tag <Type>, callable::choose>\n    {\n        max_semiring <Type> operator() () const\n        { return max_semiring <Type> (0); }\n    };\n\n    // Additive identity: same as \"choose\".\n    template <class Type>\n        struct identity <max_semiring_tag <Type>, callable::plus>\n    : identity <max_semiring_tag <Type>, callable::choose> {};\n\n    // Multiplicative annihilator: forward to additive identity.\n    template <class Type>\n        struct annihilator <max_semiring_tag <Type>, callable::times>\n    : identity <max_semiring_tag <Type>, callable::plus> {};\n\n    /* Operations. */\n\n    // \"choose\" and \"plus\" are implemented automatically, since \"order\" is\n    // implemented for them.\n\n    template <class Type> struct times <max_semiring_tag <Type>>\n    : associative, commutative, approximate_if <\n        boost::mpl::bool_ <!std::numeric_limits <Type>::is_exact>>\n    {\n        max_semiring <Type> operator() (max_semiring <Type> const & left,\n            max_semiring <Type> const & right) const\n        { return max_semiring <Type> (left.value() * right.value()); }\n    };\n\n    // Semiring in both directions.\n    template <class Type> struct is_semiring <\n        max_semiring_tag <Type>, either, callable::times, callable::choose>\n    : rime::true_type {};\n\n    template <class Type> struct is_semiring <\n        max_semiring_tag <Type>, either, callable::times, callable::plus>\n    : rime::true_type {};\n\n    // Division is only implemented for non-integer types.\n    template <class Type> struct divide <max_semiring_tag <Type>, either,\n        typename std::enable_if <!std::numeric_limits <Type>::is_integer>::type>\n    : approximate_if <boost::mpl::bool_ <!std::numeric_limits <Type>::is_exact>>\n    {\n        max_semiring <Type> operator() (max_semiring <Type> const & left,\n            max_semiring <Type> const & right) const\n        { return max_semiring <Type> (left.value() / right.value()); }\n    };\n\n    // Inversion is only implemented for non-integer types.\n    template <class Type>\n        struct invert <max_semiring_tag <Type>, either, callable::times,\n        typename std::enable_if <!std::numeric_limits <Type>::is_integer>::type>\n    {\n        max_semiring <Type> operator() (max_semiring <Type> const & c) const\n        { return max_semiring <Type> (1 / c.value()); }\n    };\n\n    template <class Type> struct print <max_semiring_tag <Type>> {\n        template <class Stream>\n            void operator() (Stream & stream, max_semiring <Type> const & c)\n            const\n        { stream << c.value(); }\n    };\n\n} // namespace operation\n\ntemplate <class Type>\n    inline std::size_t hash_value (max_semiring <Type> const & m)\n{ return boost::hash <Type>() (m.value()); }\n\n} // namespace math\n\n#endif // MATH_MAX_SEMIRING_HPP_INCLUDED\n", "meta": {"hexsha": "127b3c6c3bfd0a5ba5d6b2d90ab957581b06a2cf", "size": 7385, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/math/max_semiring.hpp", "max_stars_repo_name": "rogiervd/math", "max_stars_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/max_semiring.hpp", "max_issues_repo_name": "rogiervd/math", "max_issues_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/max_semiring.hpp", "max_forks_repo_name": "rogiervd/math", "max_forks_repo_head_hexsha": "96174afac1a2933d71cb7ae3962437f860fc10ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9696969697, "max_line_length": 80, "alphanum_fraction": 0.6578199052, "num_tokens": 1771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.44793890167311234}}
{"text": "#include <Eigen/Core>\n#include <Eigen/StdVector>\n#include <Eigen/Geometry>\n#include <iostream>\n\n#include \"data.hpp\"\n#include \"../helper.hpp\"\n\n#include \"g2o/core/sparse_optimizer.h\"\n#include \"g2o/core/block_solver.h\"\n#include \"g2o/core/solver.h\"\n#include \"g2o/core/optimization_algorithm_levenberg.h\"\n#include \"g2o/core/base_vertex.h\"\n#include \"g2o/core/base_unary_edge.h\"\n#include \"g2o/solvers/csparse/linear_solver_csparse.h\"\n\nusing namespace std;\n\ntypedef g2o::BlockSolver< g2o::BlockSolverTraits<1, 1> >  ScaleBlockSolver;\ntypedef g2o::LinearSolverCSparse<ScaleBlockSolver::PoseMatrixType> ScaleLinearSolver;\n\nclass VertexScale : public g2o::BaseVertex<1, double>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n    VertexScale()\n    {\n    }\n\n    virtual bool read(std::istream& /*is*/)\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n      return false;\n    }\n\n    virtual bool write(std::ostream& /*os*/) const\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n      return false;\n    }\n\n    virtual void setToOriginImpl()\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n    }\n\n    virtual void oplusImpl(const double* update)\n    {\n      // cout<<_estimate<<\" + \"<<*update<<endl;\n      _estimate += *update;\n    }\n};\n\nclass EdgeScaleDirect : public g2o::BaseUnaryEdge<1, Eigen::VectorXd, VertexScale>\n{\n  public:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    EdgeScaleDirect(const Eigen::Vector3d& point3d, const Eigen::Matrix3d& K, double tx, const cv::Mat& _img1)\n    : img1(_img1)\n    {\n      Eigen::Vector3d KX = K * point3d;\n\n      u_base = KX(0)/KX(2);\n      v = KX(1)/KX(2);\n      u_inc = tx*K(0,0)/point3d(2);\n      au_as << u_inc, 0;\n    }\n\n    virtual bool read(std::istream& /*is*/)\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n      return false;\n    }\n    virtual bool write(std::ostream& /*os*/) const\n    {\n      cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n      return false;\n    }\n\n    void computeError();\n    void linearizeOplus();\n\n  private:\n\n    double u_base;\n    double v;\n    double u_inc;\n    Eigen::Matrix<double,2,1> au_as;\n    const cv::Mat& img1;\n};\n", "meta": {"hexsha": "4cec10e1996aaeb031ea3aaec6ca5c543ef8968d", "size": 2209, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/stereo_processor/g2o_edges/scale_edge.hpp", "max_stars_repo_name": "jiawei-mo/dsvo", "max_stars_repo_head_hexsha": "a6d6f3a5377b472550fd3f48308adc701ed5c679", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-09-22T16:00:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T15:14:04.000Z", "max_issues_repo_path": "include/stereo_processor/g2o_edges/scale_edge.hpp", "max_issues_repo_name": "TianQi-777/dsvo", "max_issues_repo_head_hexsha": "60f4153bc970718b7ebb4be66fa1ebb0f1372a38", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-22T02:12:15.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-28T18:57:12.000Z", "max_forks_repo_path": "include/stereo_processor/g2o_edges/scale_edge.hpp", "max_forks_repo_name": "jiawei-mo/dsvo", "max_forks_repo_head_hexsha": "a6d6f3a5377b472550fd3f48308adc701ed5c679", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-02T02:05:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-16T08:00:28.000Z", "avg_line_length": 24.2747252747, "max_line_length": 110, "alphanum_fraction": 0.6482571299, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.44793890167311234}}
{"text": "/*\nCopyright 2009-2021 Nicolas Colombe\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n#pragma once\n\n#include \"math.hpp\"\n#include \"vector2.hpp\"\n\n#include <boost/optional.hpp>\n\nnamespace eXl\n{\n  template <class Real>\n  class AABB2D\n  {\n  public:\n    inline AABB2D(){}\n    inline AABB2D(Real iMinX, Real iMinY, Real iMaxX, Real iMaxY)\n    {\n      m_Data[0] = Vector2<Real>(iMinX,iMinY);\n      m_Data[1] = Vector2<Real>(iMaxX,iMaxY);\n    }\n\n    static inline AABB2D FromCenterAndSize(Vector2<Real> iCenter,Vector2<Real> iSize)\n    {\n      AABB2D ret;\n      ret.m_Data[0] = iCenter - iSize / 2.0;\n      ret.m_Data[1] = iCenter + iSize / 2.0;\n      return ret;\n    }\n\n    inline AABB2D(Vector2<Real> iMin,Vector2<Real> iSize)\n    {\n      m_Data[0] = iMin;\n      m_Data[1] = iMin + iSize;\n    }\n\n    template <class OtherReal>\n    explicit inline AABB2D(AABB2D<OtherReal> const& iOther)\n    {\n      m_Data[0] = Vector2<Real>(iOther.m_Data[0]);\n      m_Data[1] = Vector2<Real>(iOther.m_Data[1]);\n    }\n\n    inline bool Empty() const\n    {\n      return m_Data[0].X() == m_Data[1].X() || m_Data[0].Y() == m_Data[1].Y();\n    }\n\n    bool CircleTest(Vector2f const& iPos, Real iRadius)\n    {\n      if(Contains(iPos))\n      {\n        return true;\n      }\n      else\n      {\n        //Test segment X == X0\n        Real dist = m_Data[0].X() - iPos.X();   //(x0-xc)\n        dist = (iRadius + dist)*(iRadius - dist); //R^2 - (x0-xc)^2\n        if(dist > 0)\n        {\n          Real y = Math<Real>::Sqrt(dist) + iPos.Y();\n          if(Math<Real>::ZERO_TOLERANCE < m_Data[1].Y() - y && y - m_Data[0].Y() > Math<Real>::ZERO_TOLERANCE)\n            return true;\n        }\n        //Test segment X == X1\n        dist = m_Data[1].X() - iPos.X();   //(x0-xc)\n        dist = (iRadius + dist)*(iRadius - dist); //R^2 - (x0-xc)^2\n        if(dist > 0)\n        {\n          Real y = Math<Real>::Sqrt(dist) + iPos.Y();\n          if(Math<Real>::ZERO_TOLERANCE < m_Data[1].Y() - y && y - m_Data[0].Y() > Math<Real>::ZERO_TOLERANCE)\n            return true;\n        }\n\n        //TestSegment Y == Y0\n        dist = m_Data[0].Y() - iPos.Y();   //(x0-xc)\n        dist = (iRadius + dist)*(iRadius - dist); //R^2 - (x0-xc)^2\n        if(dist > 0)\n        {\n          Real x = Math<Real>::Sqrt(dist) + iPos.X();\n          if(Math<Real>::ZERO_TOLERANCE < m_Data[1].X() - x && x - m_Data[0].X() > Math<Real>::ZERO_TOLERANCE)\n            return true;\n        }\n        //Test segment Y == Y1\n        dist = m_Data[1].Y() - iPos.Y();   //(x0-xc)\n        dist = (iRadius + dist)*(iRadius - dist); //R^2 - (x0-xc)^2\n        if(dist > 0)\n        {\n          Real x = Math<Real>::Sqrt(dist) + iPos.X();\n          if(Math<Real>::ZERO_TOLERANCE < m_Data[1].X() - x && x - m_Data[0].X() > Math<Real>::ZERO_TOLERANCE)\n            return true;\n        }\n      }\n      return false;\n    }\n\n    inline void Rotate(Real iAngle)\n    {\n      Vector2<Real> center = GetCenter();\n      Vector2<Real> size = GetSize();\n      Vector2<Real> points[4];\n      points[0] = size * -0.5;\n      points[1] = Vector2<Real>(size.X() * -0.5, size.Y() *  0.5) ;\n      points[2] = Vector2<Real>(size.X() *  0.5, size.Y() * -0.5) ;\n      points[3] = size * 0.5;\n      points[0] = Vector2<Real>(points[0].X() * Math<Real>::Cos(iAngle) + points[0].Y() * Math<Real>::Sin(iAngle)\n                         , points[0].Y() * Math<Real>::Cos(iAngle) - points[0].X() * Math<Real>::Sin(iAngle));\n      points[1] = Vector2<Real>(points[1].X() * Math<Real>::Cos(iAngle) + points[1].Y() * Math<Real>::Sin(iAngle)\n                         , points[1].Y() * Math<Real>::Cos(iAngle) - points[1].X() * Math<Real>::Sin(iAngle));\n      points[2] = Vector2<Real>(points[2].X() * Math<Real>::Cos(iAngle) + points[2].Y() * Math<Real>::Sin(iAngle)\n                         , points[2].Y() * Math<Real>::Cos(iAngle) - points[2].X() * Math<Real>::Sin(iAngle));\n      points[3] = Vector2<Real>(points[3].X() * Math<Real>::Cos(iAngle) + points[3].Y() * Math<Real>::Sin(iAngle)\n                         , points[3].Y() * Math<Real>::Cos(iAngle) - points[3].X() * Math<Real>::Sin(iAngle));\n\n      m_Data[0] = m_Data[1] = points[0];\n      for (unsigned int i = 1; i < 4; ++i)\n      {\n        m_Data[0].X() = Math<Real>::Min(m_Data[0].X(), points[i].X());\n        m_Data[0].Y() = Math<Real>::Min(m_Data[0].Y(), points[i].Y());\n        m_Data[1].X() = Math<Real>::Max(m_Data[1].X(), points[i].X());\n        m_Data[1].Y() = Math<Real>::Max(m_Data[1].Y(), points[i].Y());\n      }\n      m_Data[0] += center;\n      m_Data[1] += center;\n    }\n\n    inline Vector2<Real> GetCenter()const\n    {\n      return (m_Data[0] + m_Data[1])/2;\n    }\n\n    inline Vector2<Real> GetSize()const\n    {\n      return m_Data[1] - m_Data[0];\n    }\n\n    inline void Inflate(Real iCoeff)\n    {\n      Vector2<Real> center = (m_Data[1] + m_Data[0]) / 2;\n      Vector2<Real> size = m_Data[1] - m_Data[0];\n      size = size * iCoeff;\n      m_Data[0] = center - size / 2.0;\n      m_Data[1] = center + size / 2.0;\n    }\n\n    inline Real MinX()const{return m_Data[0].X();}\n    inline Real MinY()const{return m_Data[0].Y();}\n    inline Real MaxX()const{return m_Data[1].X();}\n    inline Real MaxY()const{return m_Data[1].Y();}\n    \n    inline Real& MinX(){return m_Data[0].X();}\n    inline Real& MinY(){return m_Data[0].Y();}\n    inline Real& MaxX(){return m_Data[1].X();}\n    inline Real& MaxY(){return m_Data[1].Y();}\n\n    inline bool operator ==(AABB2D const& iOther) const\n    {\n      return m_Data[0]==iOther.m_Data[0] && m_Data[1] == iOther.m_Data[1];\n    }\n\n    inline bool operator !=(AABB2D const& iOther) const\n    {\n      return !((*this) == iOther);\n    }\n\n\t  inline bool Empty()\n\t  {\n\t\t  return m_Data[0].X() == m_Data[1].X() || m_Data[0].Y() == m_Data[1].Y();\n\t  }\n\n    inline void SetCommonBox(AABB2D<Real> const& iBox1,AABB2D<Real> const& iBox2)\n    {\n      m_Data[0].X() = Math<Real>::Max(iBox1.m_Data[0].X(),iBox2.m_Data[0].X());\n      m_Data[0].Y() = Math<Real>::Max(iBox1.m_Data[0].Y(),iBox2.m_Data[0].Y());\n      m_Data[1].X() = Math<Real>::Max(Math<Real>::Min(iBox1.m_Data[1].X(),iBox2.m_Data[1].X()),m_Data[0].X());\n      m_Data[1].Y() = Math<Real>::Max(Math<Real>::Min(iBox1.m_Data[1].Y(),iBox2.m_Data[1].Y()),m_Data[0].Y());\n    }\n\n    inline void Absorb(Vector2<Real> const& iPoint)\n    {\n      m_Data[0].X() = Math<Real>::Min(m_Data[0].X(), iPoint.X());\n      m_Data[0].Y() = Math<Real>::Min(m_Data[0].Y(), iPoint.Y());\n      m_Data[1].X() = Math<Real>::Max(m_Data[1].X(), iPoint.X());\n      m_Data[1].Y() = Math<Real>::Max(m_Data[1].Y(), iPoint.Y());\n    }\n\n    inline void Absorb(AABB2D<Real> const& iBox)\n    {\n      m_Data[0].X() = Math<Real>::Min(m_Data[0].X(),iBox.m_Data[0].X());\n      m_Data[0].Y() = Math<Real>::Min(m_Data[0].Y(),iBox.m_Data[0].Y());\n      m_Data[1].X() = Math<Real>::Max(m_Data[1].X(),iBox.m_Data[1].X());\n      m_Data[1].Y() = Math<Real>::Max(m_Data[1].Y(),iBox.m_Data[1].Y());\n    }\n\n    inline bool IsInside(AABB2D const& iOther, Real iEpsilon = Math<Real>::ZERO_TOLERANCE) const\n    {\n      return (m_Data[0].X() - iOther.m_Data[0].X() >= iEpsilon && m_Data[0].Y() - iOther.m_Data[0].Y() >= iEpsilon\n           && iOther.m_Data[1].X() - m_Data[1].X() >= iEpsilon && iOther.m_Data[1].Y() - m_Data[1].Y() >= iEpsilon );\n    }\n\n    inline bool Intersect(AABB2D const& iOther, Real iEpsilon = Math<Real>::ZERO_TOLERANCE) const\n    {\n      return iOther.m_Data[1].X() - m_Data[0].X() >= iEpsilon && m_Data[1].X() - iOther.m_Data[0].X() >= iEpsilon\n          && iOther.m_Data[1].Y() - m_Data[0].Y() >= iEpsilon && m_Data[1].Y() - iOther.m_Data[0].Y() >= iEpsilon;\n    }\n\n    //0 No, 1 Left, 2 Right, 3 Down, 4 Up\n    inline int Touch(AABB2D const& iOther, Real iEpsilon = Math<Real>::ZERO_TOLERANCE) const\n    {\n      if(iOther.m_Data[1].Y() - m_Data[0].Y() >= iEpsilon && m_Data[1].Y() - iOther.m_Data[0].Y() >= iEpsilon)\n      {\n        Real val = m_Data[0].X() - iOther.m_Data[1].X();\n        if(val <= iEpsilon && val >= -iEpsilon)\n          return 1;\n        \n        val = m_Data[1].X() - iOther.m_Data[0].X();\n        if(val <= iEpsilon && val >= -iEpsilon)\n          return 2;\n      }\n      if(iOther.m_Data[1].X() - m_Data[0].X() >= iEpsilon && m_Data[1].X() - iOther.m_Data[0].X() >= iEpsilon)\n      {\n        Real val = m_Data[0].Y() - iOther.m_Data[1].Y();\n      \n        if(val <= iEpsilon && val >= -iEpsilon)\n          return 3;\n\n        val = m_Data[1].Y() - iOther.m_Data[0].Y();\n        if(val <= iEpsilon && val >= -iEpsilon)\n          return 4;\n      }\n      return 0;\n    }\n\n    boost::optional<Vector2<Real>> SegmentTest(Vector2<Real> const& iOrigin, Vector2<Real> const& iDir, Real iEpsilon = Math<Real>::ZERO_TOLERANCE)\n    {\n      Real const scaleX = 1.0 / iDir.X();\n      Real const scaleY = 1.0 / iDir.Y();\n      Real const signX = Math<Real>::Sign(scaleX);\n      Real const signY = Math<Real>::Sign(scaleY);\n\n      Real const nearTimeX = ((signX > 0 ? m_Data[0].X() : m_Data[1].X()) - iOrigin.X()) * scaleX;\n      Real const nearTimeY = ((signY > 0 ? m_Data[0].Y() : m_Data[1].Y()) - iOrigin.Y()) * scaleY;\n      Real const farTimeX = ((signX > 0 ? m_Data[1].X() : m_Data[0].X()) - iOrigin.X()) * scaleX;\n      Real const farTimeY = ((signY > 0 ? m_Data[1].Y() : m_Data[0].Y()) - iOrigin.Y()) * scaleY;\n\n      if (nearTimeX > farTimeY || nearTimeY > farTimeX) \n      {\n        return boost::none;\n      }\n\n      Real const nearTime = nearTimeX > nearTimeY ? nearTimeX : nearTimeY;\n      Real const farTime = farTimeX < farTimeY ? farTimeX : farTimeY;\n\n      if (nearTime > 1 - iEpsilon || farTime < -iEpsilon) \n      {\n        return boost::none;\n      }\n\n      return iOrigin + iDir * nearTime;\n    }\n\n    inline bool Contains(Vector2<Real>const& iPoint, Real iEpsilon = Math<Real>::ZERO_TOLERANCE) const\n    {\n      return iPoint.X() - m_Data[0].X() >= iEpsilon && m_Data[1].X() - iPoint.X() >= iEpsilon\n          && iPoint.Y() - m_Data[0].Y() >= iEpsilon && m_Data[1].Y() - iPoint.Y() >= iEpsilon;\n    }\n\n    // Neg value -> distance to min, Pos value -> distance to max, 0, inside\n    Vector2f Classify(Vector2<Real>const& iPoint, Real iEpsilon = Math<Real>::ZERO_TOLERANCE) const\n    {\n      Vector2f res(iPoint.X() - m_Data[0].X(), iPoint.Y() - m_Data[0].Y());\n      for(uint32_t axis = 0; axis < 2; ++axis)\n      {\n        if(!(res.m_Data[axis] < -iEpsilon))\n        {\n          res.m_Data[axis] = m_Data[1].m_Data[axis] - iPoint.m_Data[axis];\n          if(res.m_Data[axis] < -iEpsilon)\n          {\n            res.m_Data[axis] *= -1;\n          }\n          else\n          {\n            res.m_Data[axis] = 0;\n          }\n        }\n      }\n\n      return res;\n    }\n\n    inline Vector2<Real> GetDistX(AABB2D const& iOther) const\n    {\n      return Vector2<Real>(iOther.m_Data[0].X() - m_Data[0].X(),m_Data[1].X() - iOther.m_Data[1].X());\n    }\n\n    inline Vector2<Real> GetDistY(AABB2D const& iOther) const\n    {\n      return Vector2<Real>(iOther.m_Data[0].Y() - m_Data[0].Y(),m_Data[1].Y() - iOther.m_Data[1].Y());\n    }\n\n    Vector2<Real> m_Data[2];\n  };\n\n  typedef AABB2D<int> AABB2Di; \n  typedef AABB2D<float> AABB2Df;\n  typedef AABB2D<double> AABB2Dd;\n}", "meta": {"hexsha": "89ca1f8220f4ea8ff90d526c673ac8b7de0bd901", "size": 12076, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/math/aabb2d.hpp", "max_stars_repo_name": "eXl-Nic/eXl", "max_stars_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/math/aabb2d.hpp", "max_issues_repo_name": "eXl-Nic/eXl", "max_issues_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/math/aabb2d.hpp", "max_forks_repo_name": "eXl-Nic/eXl", "max_forks_repo_head_hexsha": "a5a0f77f47db3179365c107a184bb38b80280279", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2151898734, "max_line_length": 460, "alphanum_fraction": 0.5607817158, "num_tokens": 3918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.44782394478334403}}
{"text": "#ifndef SKYLARK_GEMV_HPP\n#define SKYLARK_GEMV_HPP\n\n#include <boost/mpi.hpp>\n#include \"exception.hpp\"\n\n// Defines a generic Gemv function that recieves a wider set of matrices\n\nnamespace skylark { namespace base {\n\ntemplate<typename T>\ninline void Gemv(elem::Orientation oA,\n    T alpha, const elem::Matrix<T>& A, const elem::Matrix<T>& x,\n    T beta, elem::Matrix<T>& y) {\n    elem::Gemv(oA, alpha, A, x, beta, y);\n}\n\ntemplate<typename T>\ninline void Gemv(elem::Orientation oA,\n    T alpha, const elem::Matrix<T>& A, const elem::Matrix<T>& x,\n    elem::Matrix<T>& y) {\n    elem::Gemv(oA, alpha, A, x, y);\n}\n\ntemplate<typename T>\ninline void Gemv(elem::Orientation oA,\n    T alpha, const elem::DistMatrix<T>& A, const elem::DistMatrix<T>& x,\n    T beta, elem::DistMatrix<T>& y) {\n    elem::Gemv(oA, alpha, A, x, beta, y);\n}\n\ntemplate<typename T>\ninline void Gemv(elem::Orientation oA,\n    T alpha, const elem::DistMatrix<T>& A, const elem::DistMatrix<T>& x,\n    elem::DistMatrix<T>& y) {\n    elem::Gemv(oA, alpha, A, x, y);\n}\n\n/**\n * The following combinations is not offered by Elemental, but is useful for us.\n * We implement it partially.\n */\n\ntemplate<typename T>\ninline void Gemv(elem::Orientation oA,\n    T alpha, const elem::DistMatrix<T, elem::VC, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::VC, elem::STAR>& x,\n    T beta, elem::DistMatrix<T, elem::STAR, elem::STAR>& y) {\n    // TODO verify sizes etc.\n    // TODO verify matching grids.\n\n    if (oA == elem::TRANSPOSE) {\n        boost::mpi::communicator comm(y.Grid().Comm(), boost::mpi::comm_attach);\n        elem::Matrix<T> ylocal(y.Matrix());\n        elem::Gemv(elem::TRANSPOSE,\n            alpha, A.LockedMatrix(), x.LockedMatrix(),\n            beta / T(comm.size()), ylocal);\n        boost::mpi::all_reduce(comm,\n            ylocal.Buffer(), ylocal.MemorySize(), y.Buffer(),\n            std::plus<T>());\n    } else {\n        SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation());\n    }\n}\n\ntemplate<typename T>\ninline void Gemv(elem::Orientation oA,\n    T alpha, const elem::DistMatrix<T, elem::VC, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::VC, elem::STAR>& x,\n    elem::DistMatrix<T, elem::STAR, elem::STAR>& y) {\n\n    int y_height = (oA == elem::NORMAL ? A.Height() : A.Width());\n    elem::Zeros(y, y_height, 1);\n    base::Gemv(oA, alpha, A, x, T(0), y);\n}\n\ntemplate<typename T>\ninline void Gemv(elem::Orientation oA,\n    T alpha, const elem::DistMatrix<T, elem::VC, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::STAR, elem::STAR>& x,\n    T beta, elem::DistMatrix<T, elem::VC, elem::STAR>& y) {\n    // TODO verify sizes etc.\n\n    if (oA == elem::NORMAL) {\n        elem::Gemv(elem::NORMAL,\n            alpha, A.LockedMatrix(), x.LockedMatrix(),\n            beta, y.Matrix());\n    } else {\n        SKYLARK_THROW_EXCEPTION(base::unsupported_base_operation());\n    }\n}\n\ntemplate<typename T>\ninline void Gemv(elem::Orientation oA,\n    T alpha, const elem::DistMatrix<T, elem::VC, elem::STAR>& A,\n    const elem::DistMatrix<T, elem::STAR, elem::STAR>& x,\n    elem::DistMatrix<T, elem::VC, elem::STAR>& y) {\n\n    int y_height = (oA == elem::NORMAL ? A.Height() : A.Width());\n    elem::Zeros(y, y_height, 1);\n    base::Gemv(oA, alpha, A, x, T(0), y);\n}\n\ntemplate<typename T>\ninline void Gemv(elem::Orientation oA,\n    T alpha, const sparse_matrix_t<T>& A, const elem::Matrix<T>& x,\n    T beta, elem::Matrix<T>& y) {\n    // TODO verify sizes etc.\n\n    const int* indptr = A.indptr();\n    const int* indices = A.indices();\n    const double *values = A.locked_values();\n    double *yd = y.Buffer();\n    const double *xd = x.LockedBuffer();\n\n    int n = A.width();\n\n    if (oA == elem::NORMAL) {\n        elem::Scal(beta, y);\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for\n#       endif\n        for(int col = 0; col < n; col++) {\n            T xv = alpha * xd[col];\n            for (int j = indptr[col]; j < indptr[col + 1]; j++) {\n                     int row = indices[j];\n                     T val = values[j];\n                     yd[row] += val * xv;\n                 }\n        }\n\n    } else {\n\n#       if SKYLARK_HAVE_OPENMP\n#       pragma omp parallel for\n#       endif\n        for(int col = 0; col < n; col++) {\n            double yv = beta * yd[col];\n            for (int j = indptr[col]; j < indptr[col + 1]; j++) {\n                     int row = indices[j];\n                     T val = values[j];\n                     yv += alpha * val * xd[row];\n                 }\n            yd[col] = yv;\n        }\n\n    }\n}\n\n} } // namespace skylark::base\n\n\n#endif // SKYLARK_GEMV_HPP\n", "meta": {"hexsha": "e8c3a0f3867fcac594ed9024121edb0235f1e1e1", "size": 4584, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "base/Gemv.hpp", "max_stars_repo_name": "wangg12/libskylark", "max_stars_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-12T07:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T07:26:47.000Z", "max_issues_repo_path": "base/Gemv.hpp", "max_issues_repo_name": "cjiyer/libskylark", "max_issues_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "base/Gemv.hpp", "max_forks_repo_name": "cjiyer/libskylark", "max_forks_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5741935484, "max_line_length": 80, "alphanum_fraction": 0.577443281, "num_tokens": 1293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.44782393800718806}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2021 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n\n#include \"determinant.hpp\"\n#include \"SiconosVector.hpp\"\n#include \"SimpleMatrix.hpp\"\n#include \"BlockMatrixIterators.hpp\"\n#include \"BlockMatrix.hpp\"\n\n#include \"SiconosAlgebra.hpp\"\n#include \"SiconosException.hpp\"\n\nusing namespace Siconos;\n\n//=======================\n//       get norm\n//=======================\n\ndouble SimpleMatrix::normInf() const\n{\n  if(_num == DENSE)\n    return norm_inf(*mat.Dense);\n  else if(_num == TRIANGULAR)\n    return norm_inf(*mat.Triang);\n  else if(_num == SYMMETRIC)\n    return norm_inf(*mat.Sym);\n  else if(_num == SPARSE)\n    return norm_inf(*mat.Sparse);\n  else if(_num == SPARSE_COORDINATE)\n    return norm_inf(*mat.SparseCoordinate);\n  else if(_num == BANDED)\n    return norm_inf(*mat.Banded);\n  else if(_num == ZERO)\n    return 0;\n  else if(_num == IDENTITY)\n    return 1;\n\n  THROW_EXCEPTION(\"Matrix type not supported\");\n  return std::numeric_limits<double>::infinity();\n}\n\nvoid SimpleMatrix::normInfByColumn(SP::SiconosVector vIn) const\n{\n  if(_num == DENSE)\n  {\n    if(vIn->size() != size(1))\n      THROW_EXCEPTION(\"the given vector does not have the right length\");\n    DenseVect tmpV = DenseVect(size(0));\n    for(unsigned int i = 0; i < size(1); i++)\n    {\n      ublas::noalias(tmpV) = ublas::column(*mat.Dense, i);\n      (*vIn)(i) = norm_inf(tmpV);\n    }\n  }\n  else\n    THROW_EXCEPTION(\"not implemented for data other than DenseMat\");\n}\n//=======================\n//       determinant\n//=======================\n\ndouble SimpleMatrix::det() const\n{\n  if(_num == DENSE)\n    return determinant(*mat.Dense);\n  else if(_num == TRIANGULAR)\n    return determinant(*mat.Triang);\n  else if(_num == SYMMETRIC)\n    return determinant(*mat.Sym);\n  else if(_num == SPARSE)\n    return determinant(*mat.Sparse);\n  else if(_num == SPARSE_COORDINATE)\n    return determinant(*mat.Sparse);\n  else if(_num == BANDED)\n    return determinant(*mat.Banded);\n  else if(_num == ZERO)\n    return 0;\n  else  if(_num == IDENTITY)\n    return 1;\n  THROW_EXCEPTION(\"Matrix type not supported\");\n  return std::numeric_limits<double>::infinity();\n}\n\n\nvoid SimpleMatrix::trans()\n{\n  switch(_num)\n  {\n  case DENSE:\n    *mat.Dense = ublas::trans(*mat.Dense);\n    break;\n  case TRIANGULAR:\n    THROW_EXCEPTION(\"failed, the matrix is triangular matrix and can not be transposed in place.\");\n    break;\n  case SYMMETRIC:\n    break;\n  case SPARSE:\n    *mat.Sparse = ublas::trans(*mat.Sparse);\n    break;\n  case SPARSE_COORDINATE:\n    *mat.Sparse = ublas::trans(*mat.Sparse);\n    break;\n  case BANDED:\n    *mat.Banded = ublas::trans(*mat.Banded);\n    break;\n  case Siconos::ZERO:\n    break;\n  case Siconos::IDENTITY:\n    break;\n  default:\n    THROW_EXCEPTION(\"Matrix type not supported\");\n  }\n  resetFactorizationFlags();\n}\n\nvoid SimpleMatrix::trans(const SiconosMatrix &m)\n{\n  if(m.isBlock())\n    THROW_EXCEPTION(\"not yet implemented for m being a BlockMatrix.\");\n\n\n  if(&m == this)\n    trans();\n  else\n  {\n    Siconos::UBLAS_TYPE numM = m.num();\n    switch(numM)\n    {\n    case DENSE:\n      if(_num != DENSE)\n        THROW_EXCEPTION(\"try to transpose a dense matrix into another type.\");\n      noalias(*mat.Dense) = ublas::trans(*m.dense());\n      break;\n    case TRIANGULAR:\n      if(_num != DENSE)\n        THROW_EXCEPTION(\"try to transpose a triangular matrix into a non-dense one.\");\n      noalias(*mat.Dense) = ublas::trans(*m.triang());\n      break;\n    case SYMMETRIC:\n      *this = m;\n      break;\n    case SPARSE:\n      if(_num == DENSE)\n        noalias(*mat.Dense) = ublas::trans(*m.sparse());\n      else if(_num == SPARSE)\n        noalias(*mat.Sparse) = ublas::trans(*m.sparse());\n      else if(_num == SPARSE_COORDINATE)\n        noalias(*mat.SparseCoordinate) = ublas::trans(*m.sparse());\n      else\n        THROW_EXCEPTION(\"try to transpose a sparse matrix into a forbidden type (not dense nor sparse).\");\n      break;\n    case SPARSE_COORDINATE:\n      if(_num == DENSE)\n        noalias(*mat.Dense) = ublas::trans(*m.sparseCoordinate());\n      else if(_num == SPARSE)\n        noalias(*mat.Sparse) = ublas::trans(*m.sparseCoordinate());\n      else if(_num == SPARSE_COORDINATE)\n        noalias(*mat.SparseCoordinate) = ublas::trans(*m.sparseCoordinate());\n      else\n        THROW_EXCEPTION(\"try to transpose a sparse coordinate matrix into a forbidden type (not dense nor sparse coordinate).\");\n      break;\n    case BANDED:\n      if(_num == DENSE)\n        noalias(*mat.Dense) = ublas::trans(*m.banded());\n      else if(_num == BANDED)\n        noalias(*mat.Banded) = ublas::trans(*m.banded());\n      else\n        THROW_EXCEPTION(\"try to transpose a banded matrix into a forbidden type (not dense nor banded).\");\n      break;\n    case ZERO:\n      *this = m;\n      break;\n    case IDENTITY:\n      *this = m;\n      break;\n    default:\n      THROW_EXCEPTION(\"\");\n    }\n    resetFactorizationFlags();\n  }\n}\n\n\n\n\n\n\n\n\n\n/*\nThe following code inverts the matrix input using LU-decomposition with backsubstitution of unit vectors. Reference: Numerical Recipies in C, 2nd ed., by Press, Teukolsky, Vetterling & Flannery.\n\nyou can solve Ax=b using three lines of ublas code:\n\npermutation_matrix<> piv;\nlu_factorize(A, piv);\nlu_substitute(A, piv, x);\n\n*/\n#ifndef INVERT_MATRIX_HPP\n#define INVERT_MATRIX_HPP\n\n// REMEMBER to update \"lu.hpp\" header includes from boost-CVS\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n/* Matrix inversion routine.\nUses lu_factorize and lu_substitute in uBLAS to invert a matrix */\ntemplate<class T, class U, class V>\nbool InvertMatrix(const ublas::matrix<T, U, V>& input, ublas::matrix<T, U, V>& inverse)\n{\n  using namespace boost::numeric::ublas;\n  typedef permutation_matrix<std::size_t> pmatrix;\n// create a working copy of the input\n  matrix<T, U, V> A(input);\n// create a permutation matrix for the LU-factorization\n  pmatrix pm(A.size1());\n\n// perform LU-factorization\n  int res = lu_factorize(A,pm);\n  if(res != 0) return false;\n\n// create identity matrix of \"inverse\"\n  inverse.assign(ublas::identity_matrix<T>(A.size1()));\n\n// backsubstitute to get the inverse\n  lu_substitute(A, pm, inverse);\n\n  return true;\n}\n\n#endif //INVERT_MATRIX_HPP\n\n// Note FP: never used. Comment before removal ?\n// void invertMatrix(const SimpleMatrix& input, SimpleMatrix& output)\n// {\n//   InvertMatrix(*input.dense(), *output.dense());\n// }\n\n", "meta": {"hexsha": "cbd5d2761c3d7a5026dcbab01c4c0b56a27820ae", "size": 7210, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixMisc.cpp", "max_stars_repo_name": "BuildJet/siconos", "max_stars_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixMisc.cpp", "max_issues_repo_name": "BuildJet/siconos", "max_issues_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "kernel/src/utils/SiconosAlgebra/SimpleMatrixMisc.cpp", "max_forks_repo_name": "BuildJet/siconos", "max_forks_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 27.3106060606, "max_line_length": 194, "alphanum_fraction": 0.6633841886, "num_tokens": 1899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4477688649960148}}
{"text": "/*\n *  Copyright Nick Thompson, 2017\n *  Use, modification and distribution are subject to the\n *  Boost Software License, Version 1.0. (See accompanying file\n *  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_MATH_INTERPOLATORS_BARYCENTRIC_RATIONAL_DETAIL_HPP\n#define BOOST_MATH_INTERPOLATORS_BARYCENTRIC_RATIONAL_DETAIL_HPP\n\n#include <vector>\n#include <utility> // for std::move\n#include <algorithm> // for std::is_sorted\n#include <boost/lexical_cast.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/core/demangle.hpp>\n#include <boost/assert.hpp>\n\nnamespace boost{ namespace math{ namespace detail{\n\ntemplate<class Real>\nclass barycentric_rational_imp\n{\npublic:\n    template <class InputIterator1, class InputIterator2>\n    barycentric_rational_imp(InputIterator1 start_x, InputIterator1 end_x, InputIterator2 start_y, size_t approximation_order = 3);\n\n    barycentric_rational_imp(std::vector<Real>&& x, std::vector<Real>&& y, size_t approximation_order = 3);\n\n    Real operator()(Real x) const;\n\n    Real prime(Real x) const;\n\n    // The barycentric weights are not really that interesting; except to the unit tests!\n    Real weight(size_t i) const { return m_w[i]; }\n\n    std::vector<Real>&& return_x()\n    {\n        return std::move(m_x);\n    }\n\n    std::vector<Real>&& return_y()\n    {\n        return std::move(m_y);\n    }\n\nprivate:\n\n    void calculate_weights(size_t approximation_order);\n\n    std::vector<Real> m_x;\n    std::vector<Real> m_y;\n    std::vector<Real> m_w;\n};\n\ntemplate <class Real>\ntemplate <class InputIterator1, class InputIterator2>\nbarycentric_rational_imp<Real>::barycentric_rational_imp(InputIterator1 start_x, InputIterator1 end_x, InputIterator2 start_y, size_t approximation_order)\n{\n    std::ptrdiff_t n = std::distance(start_x, end_x);\n\n    if (approximation_order >= (std::size_t)n)\n    {\n        throw std::domain_error(\"Approximation order must be < data length.\");\n    }\n\n    // Big sad memcpy.\n    m_x.resize(n);\n    m_y.resize(n);\n    for(unsigned i = 0; start_x != end_x; ++start_x, ++start_y, ++i)\n    {\n        // But if we're going to do a memcpy, we can do some error checking which is inexpensive relative to the copy:\n        if(boost::math::isnan(*start_x))\n        {\n            std::string msg = std::string(\"x[\") + boost::lexical_cast<std::string>(i) + \"] is a NAN\";\n            throw std::domain_error(msg);\n        }\n\n        if(boost::math::isnan(*start_y))\n        {\n           std::string msg = std::string(\"y[\") + boost::lexical_cast<std::string>(i) + \"] is a NAN\";\n           throw std::domain_error(msg);\n        }\n\n        m_x[i] = *start_x;\n        m_y[i] = *start_y;\n    }\n    calculate_weights(approximation_order);\n}\n\ntemplate <class Real>\nbarycentric_rational_imp<Real>::barycentric_rational_imp(std::vector<Real>&& x, std::vector<Real>&& y,size_t approximation_order) : m_x(std::move(x)), m_y(std::move(y))\n{\n    BOOST_ASSERT_MSG(m_x.size() == m_y.size(), \"There must be the same number of abscissas and ordinates.\");\n    BOOST_ASSERT_MSG(approximation_order < m_x.size(), \"Approximation order must be < data length.\");\n    BOOST_ASSERT_MSG(std::is_sorted(m_x.begin(), m_x.end()), \"The abscissas must be listed in increasing order x[0] < x[1] < ... < x[n-1].\");\n    calculate_weights(approximation_order);\n}\n\ntemplate<class Real>\nvoid barycentric_rational_imp<Real>::calculate_weights(size_t approximation_order)\n{\n    using std::abs;\n    int64_t n = m_x.size();\n    m_w.resize(n, 0);\n    for(int64_t k = 0; k < n; ++k)\n    {\n        int64_t i_min = (std::max)(k - (int64_t) approximation_order, (int64_t) 0);\n        int64_t i_max = k;\n        if (k >= n - (std::ptrdiff_t)approximation_order)\n        {\n            i_max = n - approximation_order - 1;\n        }\n\n        for(int64_t i = i_min; i <= i_max; ++i)\n        {\n            Real inv_product = 1;\n            int64_t j_max = (std::min)(static_cast<int64_t>(i + approximation_order), static_cast<int64_t>(n - 1));\n            for(int64_t j = i; j <= j_max; ++j)\n            {\n                if (j == k)\n                {\n                    continue;\n                }\n\n                Real diff = m_x[k] - m_x[j];\n                using std::numeric_limits;\n                if (abs(diff) < (numeric_limits<Real>::min)())\n                {\n                   std::string msg = std::string(\"Spacing between  x[\")\n                      + boost::lexical_cast<std::string>(k) + std::string(\"] and x[\")\n                      + boost::lexical_cast<std::string>(i) + std::string(\"] is \")\n                      + boost::lexical_cast<std::string>(diff) + std::string(\", which is smaller than the epsilon of \")\n                      + boost::core::demangle(typeid(Real).name());\n                    throw std::logic_error(msg);\n                }\n                inv_product *= diff;\n            }\n            if (i % 2 == 0)\n            {\n                m_w[k] += 1/inv_product;\n            }\n            else\n            {\n                m_w[k] -= 1/inv_product;\n            }\n        }\n    }\n}\n\n\ntemplate<class Real>\nReal barycentric_rational_imp<Real>::operator()(Real x) const\n{\n    Real numerator = 0;\n    Real denominator = 0;\n    for(size_t i = 0; i < m_x.size(); ++i)\n    {\n        // Presumably we should see if the accuracy is improved by using ULP distance of say, 5 here, instead of testing for floating point equality.\n        // However, it has been shown that if x approx x_i, but x != x_i, then inaccuracy in the numerator cancels the inaccuracy in the denominator,\n        // and the result is fairly accurate. See: http://epubs.siam.org/doi/pdf/10.1137/S0036144502417715\n        if (x == m_x[i])\n        {\n            return m_y[i];\n        }\n        Real t = m_w[i]/(x - m_x[i]);\n        numerator += t*m_y[i];\n        denominator += t;\n    }\n    return numerator/denominator;\n}\n\n/*\n * A formula for computing the derivative of the barycentric representation is given in\n * \"Some New Aspects of Rational Interpolation\", by Claus Schneider and Wilhelm Werner,\n * Mathematics of Computation, v47, number 175, 1986.\n * http://www.ams.org/journals/mcom/1986-47-175/S0025-5718-1986-0842136-8/S0025-5718-1986-0842136-8.pdf\n * and reviewed in\n * Recent developments in barycentric rational interpolation\n * Jean-Paul Berrut, Richard Baltensperger and Hans D. Mittelmann\n *\n * Is it possible to complete this in one pass through the data?\n */\n\ntemplate<class Real>\nReal barycentric_rational_imp<Real>::prime(Real x) const\n{\n    Real rx = this->operator()(x);\n    Real numerator = 0;\n    Real denominator = 0;\n    for(size_t i = 0; i < m_x.size(); ++i)\n    {\n        if (x == m_x[i])\n        {\n            Real sum = 0;\n            for (size_t j = 0; j < m_x.size(); ++j)\n            {\n                if (j == i)\n                {\n                    continue;\n                }\n                sum += m_w[j]*(m_y[i] - m_y[j])/(m_x[i] - m_x[j]);\n            }\n            return -sum/m_w[i];\n        }\n        Real t = m_w[i]/(x - m_x[i]);\n        Real diff = (rx - m_y[i])/(x-m_x[i]);\n        numerator += t*diff;\n        denominator += t;\n    }\n\n    return numerator/denominator;\n}\n}}}\n#endif\n", "meta": {"hexsha": "b4199ea266bd819d6fa717db123421ef3e0987a9", "size": 7187, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/detail/barycentric_rational_detail.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 597.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T10:59:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:59:36.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/detail/barycentric_rational_detail.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/interpolators/detail/barycentric_rational_detail.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 112.0, "max_forks_repo_forks_event_min_datetime": "2018-07-26T04:36:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:29:34.000Z", "avg_line_length": 33.2731481481, "max_line_length": 168, "alphanum_fraction": 0.5971893697, "num_tokens": 1897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.4477688504758321}}
{"text": "#pragma once\n\n#include \"../../util/assert.hh\"\n#include \"../../util/meta.hh\"\n\n#include <Eigen/Core>\n#include <stdexcept>\n#include <sstream>\n\nnamespace bold\n{\n  template<typename T,int dim>\n  struct LineSegment : Eigen::Matrix<T,dim,2>\n  {\n  public:\n    typedef Eigen::Matrix<T,dim,2> Base;\n    typedef Eigen::Matrix<T,dim,1> PointType;\n\n    template<typename OtherDerived>\n    LineSegment(Eigen::MatrixBase<OtherDerived> const& other)\n      :  Base(other)\n    {}\n\n    LineSegment(PointType const& p1,\n                PointType const& p2)\n    {\n      static_assert(std::is_arithmetic<T>::value, \"Must be an arithmetic type\");\n\n      this->col(0) = p1;\n      this->col(1) = p2;\n\n      ASSERT((p2 - p1).cwiseAbs().maxCoeff() != 0);\n    }\n\n    template<typename OtherDerived>\n    LineSegment& operator=(Eigen::MatrixBase<OtherDerived> const& other)\n    {\n      this->Base::operator=(other);\n      return *this;\n    }\n\n    PointType p1() const { return this->col(0); }\n    PointType p2() const { return this->col(1); }\n\n    /** Returns the vector formed by <code>p2() - p1()</code> */\n    PointType delta() const { return p2() - p1(); }\n\n    /** Returns the vector formed by <code>(p2() + p1()) / 2.0</code> */\n    PointType mid() const { return (p2() + p1()) / 2.0; }\n\n    T length() const { return delta().norm(); }\n\n    double normalisedDot(LineSegment<T,dim> other) const\n    {\n      return delta().normalized().dot( other.delta().normalized() );\n    }\n\n    /** Calculate the smallest angle between the two line segments.\n     *\n     * The output will be between 0 and PI/2, inclusive.\n     */\n    double smallestAngleBetween(LineSegment<T,dim> other)\n    {\n      auto a = fabs(acos(normalisedDot(other)));\n      if (a >= M_PI/2)\n        a = M_PI - a;\n      return a;\n    }\n\n    template<int newDim>\n    LineSegment<T,newDim> to() const\n    {\n      auto newLineSegment = LineSegment<T,newDim>{LineSegment<T,newDim>::Zero()};\n      newLineSegment.col(0).template head< meta::min<dim,newDim>::value >() =\n        this->col(0).template head< meta::min<dim,newDim>::value >();\n      newLineSegment.col(1).template head< meta::min<dim,newDim>::value >() =\n        this->col(1).template head< meta::min<dim,newDim>::value >();\n      return newLineSegment;\n    }\n\n    bool operator==(LineSegment<T,dim> const& other) const\n    {\n      const double epsilon = 0.0000004;\n      return (this->array() - other.array()).abs().sum() < epsilon;\n    }\n\n    LineSegment<T,dim> operator+(PointType const& delta) const\n    {\n      return LineSegment<T,dim>{this->colwise() + delta};\n    }\n\n    LineSegment<T,dim> operator-(PointType const& delta) const\n    {\n      return LineSegment<T,dim>{this->colwise() - delta};\n    }\n\n    friend std::ostream& operator<<(std::ostream& stream, LineSegment<T,dim> const& lineSegment)\n    {\n      return stream << \"LineSegment (P1=\" << lineSegment.p1().transpose() << \" P2=\" << lineSegment.p2().transpose() << \")\";\n    }\n\n  };\n\n  typedef LineSegment<double,3> LineSegment3d;\n  typedef LineSegment<int,3> LineSegment3i;\n}\n", "meta": {"hexsha": "7d71fdc44f87a4970dfd8eff1d0cd7cde4c9e1e0", "size": 3036, "ext": "hh", "lang": "C++", "max_stars_repo_path": "geometry/LineSegment/linesegment.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geometry/LineSegment/linesegment.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry/LineSegment/linesegment.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3738317757, "max_line_length": 123, "alphanum_fraction": 0.6123188406, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.4477688504758321}}
{"text": "/*\n * ---------------------------------------------------------------------\n * Copyright (C) 2012, 2014 Tino Kluge (ttk448 at gmail.com)\n *\n *  This program is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU General Public License\n *  as published by the Free Software Foundation; either version 2\n *  of the License, or (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see <http://www.gnu.org/licenses/>.\n * ---------------------------------------------------------------------\n */\n\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n#include <boost/multi_array.hpp>\n#include <fftw3.h>\n#include \"dvs_reconstruction/poisson_solver/laplace.h\"\n\n#ifdef TIME_REPORT\n#include <time.h>\n#include <sys/time.h>\nnamespace pde\n{\n\ndouble stoptime(void)\n{\n   struct timeval t;\n   gettimeofday(&t,NULL);\n   return (double) t.tv_sec + t.tv_usec/1000000.0;\n}\n}\n#endif // TIME_REPORT\n\n\nnamespace\n{\n\n// convenience function: square\ninline double sqr(double x)\n{\n   return x*x;\n}\n\n} // namespace\n\n\n// 2d-array utility functions\n// --------------------------\nnamespace arr\n{\n\n// helper function: [0,1] uniform random generator\ndouble runif()\n{\n   return (double) rand()/(RAND_MAX+1.0);\n}\n// fill vector with random values\nvoid runif(std::vector<double>& X)\n{\n   size_t n=X.size();\n   for(size_t i=0; i<n; i++) {\n      X[i]=runif();\n   }\n}\n// fill 2d-array with random values\nvoid runif(boost::multi_array<double,2>& X)\n{\n   size_t n1=X.shape()[0];\n   size_t n2=X.shape()[1];\n   for(size_t i=0; i<n1; i++) {\n      for(size_t j=0; j<n2; j++) {\n         X[i][j]=runif();\n      }\n   }\n}\n\n// print the matrix\nvoid print(const boost::multi_array<double,2>& X)\n{\n   size_t n1=X.shape()[0];\n   size_t n2=X.shape()[1];\n   for(size_t i=0; i<n1; i++) {\n      for(size_t j=0; j<n2; j++) {\n         printf(\"%9.5f \", X[i][j]);\n      }\n      printf(\"\\n\");\n   }\n}\n\n// L^2 difference between two vectors\ndouble diff(const std::vector<double>& X,\n            const std::vector<double>& Y,\n            bool allow_shift)\n{\n\n   assert(X.size()==Y.size());\n   size_t n=X.size();\n\n   double c=0.0;\n   if(allow_shift) {\n      c=X[1]-Y[1];\n   }\n   double sum=0.0;\n   for(size_t i=0; i<n; i++) {\n      sum+=sqr(X[i]-Y[i]-c);\n   }\n   return sqrt(sum);\n}\n\n// L^2 difference between vector and a constant\ndouble diff(const std::vector<double>& X, double c)\n{\n   size_t n=X.size();\n   double sum=0.0;\n   for(size_t i=0; i<n; i++) {\n      sum+=sqr(X[i]-c);\n   }\n   return sqrt(sum);\n}\n\n// L^2 difference between two 2d-arrays\n// allow_shift: removes a constant shift between 2 matrices,\n//    i.e.  comparing X[][] and Y[][] + (X[1][1]-Y[1][1])\n// ignore_corner: ignores all 4 corners, X[0][0], ...\ndouble diff(const boost::multi_array<double,2>& X,\n            const boost::multi_array<double,2>& Y,\n            bool allow_shift, bool ignore_corner)\n{\n\n   size_t n1=X.shape()[0];\n   size_t n2=X.shape()[1];\n\n   assert(Y.shape()[0]==n1 && n1>1);\n   assert(Y.shape()[1]==n2 && n2>1);\n\n   double c=0.0;\n   if(allow_shift) {\n      c=X[1][1]-Y[1][1];\n   }\n   double sum=0.0;\n   for(size_t i=0; i<n1; i++) {\n      for(size_t j=0; j<n2; j++) {\n         if( !(ignore_corner==true && (i==0 || i==n1-1) && (j==0 || j==n2-1)) )\n            sum+=sqr(X[i][j]-Y[i][j]-c);\n      }\n   }\n   return sqrt(sum);\n}\n\n} // namespace arr\n\n\n\n\nnamespace pde\n{\n\n\n// sets the number of threads for the fftw solver\nint fftw_threads(int n)\n{\n   int ret=fftw_init_threads();\n   fftw_plan_with_nthreads(n);\n   return ret;\n}\n// cleans up memory used by fftw for threads\nvoid fftw_clean()\n{\n   fftw_cleanup();\n   fftw_cleanup_threads();\n}\n\n// sets boundary vectors to a uniform value\nvoid set_boundary_to_uniform(\n   std::vector<double>& bd1a, std::vector<double>& bd1b,\n   std::vector<double>& bd2a, std::vector<double>& bd2b,\n   double value, size_t n1, size_t n2)\n{\n\n   bd1a.resize(n2);\n   bd1b.resize(n2);\n   bd2a.resize(n1);\n   bd2b.resize(n1);\n   for(size_t i=0; i<n2; i++) {\n      bd1a[i]=value;\n      bd1b[i]=value;\n   }\n   for(size_t i=0; i<n1; i++) {\n      bd2a[i]=value;\n      bd2b[i]=value;\n   }\n}\n\n// saves the 4 boundaries/edges of a 2-d array as individual vectors\n// note, the 4 corners/vertices are not saved and the resulting\n// vectors are of size n-2\nvoid get_boundary(std::vector<double>& bd1a, std::vector<double>& bd1b,\n                  std::vector<double>& bd2a, std::vector<double>& bd2b,\n                  const boost::multi_array<double,2>& X,\n                  double h1, double h2, types::boundary boundary)\n{\n   size_t n1=X.shape()[0];\n   size_t n2=X.shape()[1];\n   assert(n1>2 && n2>2);\n\n   // allocating memory for boundary vectors\n   bd1a.resize(n2-2);\n   bd1b.resize(n2-2);\n   bd2a.resize(n1-2);\n   bd2b.resize(n1-2);\n\n   // reading boundary values\n   if(boundary==types::Dirichlet) {\n      for(size_t i=1; i<n2-1; i++) {\n         bd1a[i-1] = X[0][i];\n         bd1b[i-1] = X[n1-1][i];\n      }\n      for(size_t i=1; i<n1-1; i++) {\n         bd2a[i-1] = X[i][0];\n         bd2b[i-1] = X[i][n2-1];\n      }\n   } else if(boundary==types::Neumann) {\n      for(size_t i=1; i<n2-1; i++) {\n         bd1a[i-1] = (X[0][i]-X[2][i]) / (2.0*h1);\n         bd1b[i-1] = (X[n1-1][i]-X[n1-3][i]) / (2.0*h1);\n      }\n      for(size_t i=1; i<n1-1; i++) {\n         bd2a[i-1] = (X[i][0]-X[i][2]) / (2.0*h2);\n         bd2b[i-1] = (X[i][n2-1]-X[i][n2-3]) / (2.0*h2);\n      }\n   } else {\n      assert(false);\n   }\n}\n\n\n// set boundary of matrix X according to conditions\n// can either add boundaries to the array (resize), or overwrite the\n// current boundary values\n// boundary vectors shall not contain the 4 corners (vertices), ie need to\n// be of size n-2 of the resulting array\nvoid set_boundary(boost::multi_array<double,2>& X, double h1, double h2,\n                  const std::vector<double>& bd1a, const std::vector<double>& bd1b,\n                  const std::vector<double>& bd2a, const std::vector<double>& bd2b,\n                  types::boundary boundary, bool add)\n{\n\n   size_t n1=X.shape()[0];\n   size_t n2=X.shape()[1];\n   assert(n1>0 && n2>0);\n\n   if(add==true) {\n      // add boundary --> grow array\n      X.resize(boost::extents[n1+2][n2+2]);  // element preserving resize\n      n1=X.shape()[0];\n      n2=X.shape()[1];\n      // shifting numbers inside the array to make space for boundary\n      for(int i=n1-3; i>=0; i--) {\n         for(int j=n2-3; j>=0; j--) {\n            X[i+1][j+1]=X[i][j];\n         }\n      }\n   }\n\n   // check the boundary vectors are of the correct size\n   assert( bd1a.size()==bd1b.size() && bd1a.size()==n2-2 );\n   assert( bd2a.size()==bd2b.size() && bd2a.size()==n1-2 );\n\n   // setting boundary values\n   if(boundary==types::Dirichlet) {\n      for(int i=0; i<(int)n2; i++) {\n         // include corner cases, which are otherwise undetermined\n         int idx = std::min(std::max(i-1,0),(int)n2-3);\n         X[0][i]    = bd1a[idx];\n         X[n1-1][i] = bd1b[idx];\n      }\n      for(size_t i=1; i<n1-1; i++) {\n         X[i][0]    = bd2a[i-1];\n         X[i][n2-1] = bd2b[i-1];\n      }\n   } else if(boundary==types::Neumann) {\n      for(int i=0; i<(int)n2; i++) {\n         // include corner cases, which are otherwise undetermined\n         int idx = std::min(std::max(i-1,0),(int)n2-3);\n         X[0][i]    = X[2][i]    + 2.0*h1*bd1a[idx];\n         X[n1-1][i] = X[n1-3][i] + 2.0*h1*bd1b[idx];\n      }\n      for(size_t i=1; i<n1-1; i++) {\n         X[i][0]    = X[i][2]    + 2.0*h2*bd2a[i-1];\n         X[i][n2-1] = X[i][n2-3] + 2.0*h2*bd2b[i-1];\n      }\n   } else {\n      assert(false);\n   }\n}\n// specialised version where all boundaries have the same value\nvoid set_boundary(boost::multi_array<double,2>& X, double h1, double h2,\n                  double bdvalue, types::boundary bdcond, bool add)\n{\n   size_t n1=X.shape()[0];\n   size_t n2=X.shape()[1];\n   // set the correct size of the boundary vectors\n   size_t m1,m2;\n   if(add==true) {\n      m1=n1;\n      m2=n2;\n   } else {\n      assert(n1>=2 && n2>=2);\n      m1=n1-2;\n      m2=n2-2;\n   }\n   // fill boundary vectors\n   std::vector<double> bd1a,bd1b,bd2a,bd2b;\n   set_boundary_to_uniform(bd1a,bd1b,bd2a,bd2b,bdvalue,m1,m2);\n\n   // call the general routine\n   set_boundary(X,h1,h2,bd1a,bd1b,bd2a,bd2b,bdcond,add);\n}\n\n\n\n\n\n// PDE functions to solve the discrete Poisson's Equation\n// ------------------------------------------------------\n\n// discrete Gradient operator on a uniform grid\n// given u(x,y), it returns DX = a_1 du/dx, DY = a_2 du/dy,\n// using one-sided finite differences\n// U[i][j]  = u(x_i, y_j), i=0...n-1\n// DX[i][j] = a1*(U[i+1][j]-U[i][j])/h, i=0...n-2\nvoid grad(boost::multi_array<double,2>& DX, boost::multi_array<double,2>& DY,\n          const boost::multi_array<double,2>& U,\n          double a1, double a2, double h1, double h2)\n{\n   assert(U.shape()[0]>1 && U.shape()[1]>1);\n   size_t n1=U.shape()[0]-1;\n   size_t n2=U.shape()[1]-1;\n   DX.resize(boost::extents[n1][n2]);\n   DY.resize(boost::extents[n1][n2]);\n   for(size_t i=0; i<n1; i++) {\n      for(size_t j=0; j<n2; j++) {\n         DX[i][j] = (a1/h1) * (U[i+1][j]-U[i][j]);\n         DY[i][j] = (a2/h2) * (U[i][j+1]-U[i][j]);\n      }\n   }\n}\n// discrete Gradient operator on a uniform grid\n// same as above, but the input U is assumed to contain only inner grid points\n// and the boundary grid points are inferred from the boundary condition\n// U[i][j] = u(x_i, y_j), i=0...n-1\n// DX[i][j] = a1*(U[i][j]-U[i-1][j])/h, i=0...n+1\nvoid grad(boost::multi_array<double,2>& DX, boost::multi_array<double,2>& DY,\n          const boost::multi_array<double,2>& U,\n          double a1, double a2, double h1, double h2,\n          const std::vector<double>& bd1a, const std::vector<double>& bd1b,\n          const std::vector<double>& bd2a, const std::vector<double>& bd2b,\n          types::boundary boundary)\n{\n   // this is lazy and very memory inefficient\n   // TODO: replace with a direct calculation\n   boost::multi_array<double,2> V=U;\n   pde::set_boundary(V,h1,h2,bd1a,bd1b,bd2a,bd2b,boundary,true);\n   grad(DX,DY,V,a1,a2,h1,h2);\n}\n// simplified version where only one boundary value can be specified\nvoid grad(boost::multi_array<double,2>& DX, boost::multi_array<double,2>& DY,\n          const boost::multi_array<double,2>& U,\n          double a1, double a2, double h1, double h2,\n          double bdvalue, types::boundary bdcond)\n{\n   size_t n1=U.shape()[0];\n   size_t n2=U.shape()[1];\n\n   // fill boundary vectors\n   std::vector<double> bd1a,bd1b,bd2a,bd2b;\n   set_boundary_to_uniform(bd1a,bd1b,bd2a,bd2b,bdvalue,n1,n2);\n\n   // call the general routine\n   grad(DX,DY,U,a1,a2,h1,h2,bd1a,bd1b,bd2a,bd2b,bdcond);\n}\n\n// discrete Divergence operator on a uniform grid\n// given u(x,y), v(x,y), it returns f = a_1 du/dx + a_2 dv/dx,\n// using one-sided finite differences\nvoid div(boost::multi_array<double,2>& F,\n         const boost::multi_array<double,2>& U,\n         const boost::multi_array<double,2>& V,\n         double a1, double a2, double h1, double h2)\n{\n   assert(U.shape()[0]==V.shape()[0]);\n   assert(U.shape()[1]==V.shape()[1]);\n   assert(U.shape()[0]>1 && U.shape()[1]>1);\n   size_t n1=U.shape()[0]-1;\n   size_t n2=V.shape()[1]-1;\n   F.resize(boost::extents[n1][n2]);\n   for(size_t i=0; i<n1; i++) {\n      for(size_t j=0; j<n2; j++) {\n         F[i][j] = (a1/h1) * (U[i+1][j+1]-U[i][j+1])\n                   + (a2/h2) * (V[i+1][j+1]-V[i+1][j]);\n      }\n   }\n}\n\n// discrete Laplace operator on a uniform grid\n// given u, it returns f = a_1 u_xx + a_2 u_yy\n// note, the Laplace operator can only be applied to inner grid points\n// and so the result F has two grid points less in each dimension, i.e.\n// U[i][j] = u(x_i, y_j)\n// F[i][j] = f(x_{i+1}, y_{i+1})\nvoid laplace(boost::multi_array<double,2>& F,\n             const boost::multi_array<double,2>& U,\n             double a1, double a2, double h1, double h2)\n{\n   assert(U.shape()[0]>2 && U.shape()[1]>2);\n   size_t n1=U.shape()[0]-2;\n   size_t n2=U.shape()[1]-2;\n   F.resize(boost::extents[n1][n2]);\n   for(size_t i=0; i<n1; i++) {\n      for(size_t j=0; j<n2; j++) {\n         // index [i][j] in F corresponds to [i+1][j+1] in U\n         F[i][j] = a1 * (U[i][j+1] - 2.0*U[i+1][j+1] + U[i+2][j+1]) / (h1*h1)\n                   + a2 * (U[i+1][j] - 2.0*U[i+1][j+1] + U[i+1][j+2]) / (h2*h2);\n      }\n   }\n}\n// discrete Laplace operator on a uniform grid\n// the input U is assumed to contain only inner grid points and the\n// boundary grid points are inferred from the boundary condition\n// U[i][j] = u(x_i, y_j)\n// F[i][j] = f(x_i, y_i)\nvoid laplace(boost::multi_array<double,2>& F,\n             const boost::multi_array<double,2>& U,\n             double a1, double a2, double h1, double h2,\n             const std::vector<double>& bd1a, const std::vector<double>& bd1b,\n             const std::vector<double>& bd2a, const std::vector<double>& bd2b,\n             types::boundary boundary)\n{\n   size_t n1=U.shape()[0];\n   size_t n2=U.shape()[1];\n   assert(n1>0 && n2>0);\n   assert(bd1a.size()==bd1b.size() && bd1a.size()==n2);\n   assert(bd2a.size()==bd2b.size() && bd2a.size()==n1);\n\n   F.resize(boost::extents[n1][n2]);\n   for(int i=0; i<(int)n1; i++) {\n      for(int j=0; j<(int)n2; j++) {\n         double Um1, U0, Up1;       // U[i-1], U[i], U[i+1]\n\n         // first dimension\n         Um1 = U[std::max(i-1,0)][j];\n         U0  = U[i][j];\n         Up1 = U[std::min(i+1,(int)n1-1)][j];\n         if(i==0) {\n            if(boundary==types::Dirichlet) {\n               Um1 = bd1a[j];\n            } else if(boundary==types::Neumann) {\n               Um1 = U[1][j] + 2.0*h1*bd1a[j];\n            }\n         } else if(i==(int)n1-1) {\n            if(boundary==types::Dirichlet) {\n               Up1 = bd1b[j];\n            } else if(boundary==types::Neumann) {\n               Up1 = U[n1-2][j] + 2.0*h1*bd1b[j];\n            }\n         }\n         F[i][j] = a1 * (Um1 - 2.0*U0 + Up1) / (h1*h1);\n\n         // second dimension\n         Um1 = U[i][std::max(j-1,0)];\n         Up1 = U[i][std::min(j+1,(int)n2-1)];\n         if(j==0) {\n            if(boundary==types::Dirichlet) {\n               Um1 = bd2a[i];\n            } else if(boundary==types::Neumann) {\n               Um1 = U[i][1] + 2.0*h2*bd2a[i];\n            }\n         } else if(j==(int)n2-1) {\n            if(boundary==types::Dirichlet) {\n               Up1 = bd2b[i];\n            } else if(boundary==types::Neumann) {\n               Up1 = U[i][n2-2] + 2.0*h2*bd2b[i];\n            }\n         }\n         F[i][j] += a2 * (Um1 - 2.0*U0 + Up1) / (h2*h2);\n      }\n   }\n}\n// simplified version where only one boundary value can be specified\nvoid laplace(boost::multi_array<double,2>& F,\n             const boost::multi_array<double,2>& U,\n             double a1, double a2, double h1, double h2,\n             double bdvalue, types::boundary bdcond)\n{\n\n   size_t n1=U.shape()[0];\n   size_t n2=U.shape()[1];\n   assert(n1>0 && n2>0);\n\n   // fill boundary vectors\n   std::vector<double> bd1a,bd1b,bd2a,bd2b;\n   set_boundary_to_uniform(bd1a,bd1b,bd2a,bd2b,bdvalue,n1,n2);\n\n   // call the general routine\n   laplace(F,U,a1,a2,h1,h2,bd1a,bd1b,bd2a,bd2b,bdcond);\n}\n\n// Neumann boundary condition with a general right hand side F will not\n// have a solution, however by looking at F we can say what the minimum\n// L2-norm error will be for 0-Neumann boundary conditions:\n// return = min ||Laplace U - F||\n// min is taken over all U consistent with 0-Neumann condition\ndouble neumann_error(const boost::multi_array<double,2>& F)\n{\n   size_t n1=F.shape()[0];\n   size_t n2=F.shape()[1];\n   assert(n1>1 && n2>1);\n\n   // assuming 0 boundary conditions, otherwise would have to adjust\n   // right hand side F as in poisolve()\n\n   // calculate min L2 error ||Laplace U - F|| = |\\hat F[0]| * ||EV[0]||\n   // where \\hat F, are the coordinates of F in EV-space,\n   // and can simply be calculated as follows\n   double sum=0.0;\n   double fac=1.0;\n   for(size_t i=0; i<n1; i++) {\n      for(size_t j=0; j<n2; j++) {\n         fac=1.0;\n         if(j==0 || j==n2-1)\n            fac*=0.5;\n         if(i==0 || i==n1-1)\n            fac*=0.5;\n         sum+=fac*F[i][j];\n      }\n   }\n   double F00 = sum/((n1-1)*(n2-1));      // \\hat F [0][0] (EV space)\n   double norm_ev=sqrt((double)(n1*n2));  // EV[0]=(1,...,1) --> norm=sqrt(n)\n   double l2_error=F00*norm_ev;\n   return l2_error;\n}\n\n// given a right hand side F, we can find a constant Neumann-boundary\n// value which will have a solution U, so that Laplace U = F,\n// returns the boundary value\ndouble neumann_compat(const boost::multi_array<double,2>& F,\n                      double a1, double a2, double h1, double h2)\n{\n   size_t n1=F.shape()[0];\n   size_t n2=F.shape()[1];\n\n   double l2_error=neumann_error(F);\n   double norm_ev=sqrt((double)(n1*n2));  // EV[0]=(1,...,1) --> norm=sqrt(n)\n   double F00 = l2_error/norm_ev;         // \\hat F [0][0] (EV space)\n\n   // with non-zero Neumann boundary condition, rhs F is modified,\n   // as in poisolve(), so we can calculate the exact boundary\n   // value to make the l2_error zero\n   double bd = F00 / (2.0*a1/(h1*(n1-1)) + 2.0*a2/(h2*(n2-1)));\n\n   return bd;\n}\n\n\n\n\n// solves the 2D Poisson equation: a1 u_xx + a2 u_yy = f\n//\n// discretised with uniform grid, x_{i+1} = x_i + h1, y_{i+1} = y_i + h2\n// input: rhs       F[i][j] = f(x_i, y_j)\n// output: solution  U[i][j] = u(x_i, y_j), ie only inner points by default\n//\n//\n//\n// boundary condition:\n// - lower and upper boundary in dimension 1: bd1a, bd1b\n// - lower and upper boundary in dimension 2: bd2a, bd2b\n// - e.g. bd1a[i] refers to U[-1][i]\ndouble poisolve( boost::multi_array<double,2>& U,\n                 const boost::multi_array<double,2>& F,\n                 double a1, double a2, double h1, double h2,\n                 const std::vector<double>& bd1a, const std::vector<double>& bd1b,\n                 const std::vector<double>& bd2a, const std::vector<double>& bd2b,\n                 types::boundary boundary, bool add_boundary_to_solution)\n{\n\n#ifdef TIME_REPORT\n   double t0=stoptime();\n   double t1=t0;\n   double t2;\n#endif\n\n   size_t n1=F.shape()[0];\n   size_t n2=F.shape()[1];\n   assert(n1>0 && n2>0);\n\n\n   // adjust right hand side F with boundary condition (nothing to do for =0)\n   boost::multi_array<double,2> rhs = F;\n   assert( bd1a.size()==bd1b.size() && bd1a.size()==n2 );\n   assert( bd2a.size()==bd2b.size() && bd2a.size()==n1 );\n   {\n      // factors for boundary adjustment to rhs\n      double c1 = 0.0, c2 = 0.0;\n      if(boundary==types::Dirichlet) {\n         c1=a1/sqr(h1);\n         c2=a2/sqr(h2);\n      } else if(boundary==types::Neumann) {\n         c1=2.0*a1/h1;\n         c2=2.0*a2/h2;\n      } else {\n         assert(false);\n      }\n      // adjust rhs with boundary conditions\n      for(size_t i=0; i<n2; i++) {\n         rhs[0][i]    -= c1 * bd1a[i];\n         rhs[n1-1][i] -= c1 * bd1b[i];\n      }\n      for(size_t i=0; i<n1; i++) {\n         rhs[i][0]    -= c2 * bd2a[i];\n         rhs[i][n2-1] -= c2 * bd2b[i];\n      }\n   }\n\n\n#ifdef TIME_REPORT\n   t2=stoptime();\n   printf(\"poisolve(): %5.0f ms: rhs boundary conditions\\n\",(t2-t1)*1000.0);\n   t1=t2;\n#endif\n\n\n   // transform rhs into EV space (inverse fft, in-place)\n   {\n      fftw_plan p;\n      double fft_norm=0.0;  // i.e. FFT(FFT(x)) = fft_norm * x\n\n      if(boundary==types::Dirichlet) {\n         // DST-I = FFTW_RODFT00 (note, additional factor of 2 in fftw)\n         p=fftw_plan_r2r_2d(n1, n2, &(rhs[0][0]), &(rhs[0][0]),\n                            FFTW_RODFT00, FFTW_RODFT00, FFTW_ESTIMATE);\n         fftw_execute(p);\n         fftw_destroy_plan(p);\n         fft_norm = 4.0*((n1+1)*(n2+1));\n\n      } else if(boundary==types::Neumann) {\n         // EV space is similar to DCT-I but without the factor of 1/2\n         // for the 1st and last element\n\n         // DCT-I = REDFT00 (note, additional factor of 2 in fftw)\n         // so that DCT-I*DCT-I = 2(n-1) I (and not the usual (n-1)/2)\n         p=fftw_plan_r2r_2d(n1, n2, &(rhs[0][0]), &(rhs[0][0]),\n                            FFTW_REDFT00, FFTW_REDFT00, FFTW_ESTIMATE);\n         fftw_execute(p);\n         fftw_destroy_plan(p);\n\n         for(size_t i=0; i<n1; i++) {\n            rhs[i][0]    *= 0.5;\n            rhs[i][n2-1] *= 0.5;\n         }\n         for(size_t j=0; j<n2; j++) {\n            rhs[0][j]    *= 0.5;\n            rhs[n1-1][j] *= 0.5;\n         }\n         fft_norm = 4.0*((n1-1)*(n2-1));\n\n      } else {\n         assert(false);\n      }\n      // scale so we get the inverse fft\n      for(size_t i=0; i<n1; i++) {\n         for(size_t j=0; j<n2; j++) {\n            rhs[i][j] *= (1.0/fft_norm);      // div is more expensive than mul\n         }\n      }\n   }\n\n\n#ifdef TIME_REPORT\n   t2=stoptime();\n   printf(\"poisolve(): %5.0f ms: rhs to EV space (inv fft)\\n\",(t2-t1)*1000.0);\n   t1=t2;\n#endif\n\n\n   // calculate eigenvalues of the linear operators L\n   std::vector<double> lambda1(n1);\n   std::vector<double> lambda2(n2);\n   if(boundary==types::Dirichlet) {\n      for(size_t i=0; i<n1; i++)\n         lambda1[i] = -4.0*sqr( sin((M_PI*(i+1))/(2.0*(n1+1))) );\n      for(size_t i=0; i<n2; i++)\n         lambda2[i] = -4.0*sqr( sin((M_PI*(i+1))/(2.0*(n2+1))) );\n   } else if(boundary==types::Neumann) {\n      for(size_t i=0; i<n1; i++)\n         lambda1[i] = -4.0*sqr( sin((M_PI*i)/(2.0*(n1-1))) );\n      for(size_t i=0; i<n2; i++)\n         lambda2[i] = -4.0*sqr( sin((M_PI*i)/(2.0*(n2-1))) );\n   } else {\n      assert(false);\n   }\n\n\n   // solve the equation for U in EV space\n   double error=0.0;\n   U.resize(boost::extents[n1][n2]);\n   for(size_t i=0; i<n1; i++) {\n      for(size_t j=0; j<n2; j++) {\n         double div = (a1*lambda1[i]/(h1*h1) + a2*lambda2[j]/(h2*h2));\n         if(div==0.0) {\n            // here we need rhs[i][j] == 0 or else there is no solution\n            // calculate the L2-norm of the error, need to know norm of EV\n            // we know div==0.0, only for Neumann and EV 0, ||EV[0]||^2=n\n            // however, since fftw has an extra factor 2, ||EV[0]||^2=4n\n            double norm_ev = 16.0*n1*n2;     // TODO: make this more general\n            error+=sqr(rhs[i][j])*norm_ev;\n            // U[i][j] is arbitrary here\n            U[i][j] = 0.0;\n         } else {\n            U[i][j] = rhs[i][j] / div;\n         }\n      }\n   }\n\n   // free rhs memory as it's no longer needed\n   rhs.resize(boost::extents[0][0]);\n\n#ifdef TIME_REPORT\n   t2=stoptime();\n   printf(\"poisolve(): %5.0f ms: solve equation in EV space\\n\",(t2-t1)*1000.0);\n   t1=t2;\n#endif\n\n\n   // transform U from EV space into canonical space (fft, in-place)\n   {\n      fftw_plan p = nullptr;\n\n      if(boundary==types::Dirichlet) {\n         // DST-I = FFTW_RODFT00 (note, additional factor of 2 in fftw)\n         // so that DST-I*DST-I = 2(n+1) I (and not the usual (n+1)/2)\n         p=fftw_plan_r2r_2d(n1, n2, &(U[0][0]), &(U[0][0]),\n                            FFTW_RODFT00, FFTW_RODFT00, FFTW_ESTIMATE);\n         fftw_execute(p);\n\n      } else if(boundary==types::Neumann) {\n         // EV space is similar to DCT-I but without the factor of 1/2\n         // for the 1st and last element\n\n         // apply factor 2\n         for(size_t i=0; i<n1; i++) {\n            U[i][0]    *= 2.0;\n            U[i][n2-1] *= 2.0;\n         }\n         for(size_t j=0; j<n2; j++) {\n            U[0][j]    *= 2.0;\n            U[n1-1][j] *= 2.0;\n         }\n         // DCT-I = REDFT00 (note, additional factor of 2 in fftw)\n         p=fftw_plan_r2r_2d(n1, n2, &(U[0][0]), &(U[0][0]),\n                            FFTW_REDFT00, FFTW_REDFT00, FFTW_ESTIMATE);\n         fftw_execute(p);\n\n      } else {\n         assert(false);\n      }\n      fftw_destroy_plan(p);\n   }\n\n#ifdef TIME_REPORT\n   t2=stoptime();\n   printf(\"poisolve(): %5.0f ms: solution to normal space (fft)\\n\",(t2-t1)*1000.0);\n   t1=t2;\n#endif\n\n   // by default, U only contains the inner grid points of the solution\n   // however, we can also add the boundary if needed (inefficient)\n   if(add_boundary_to_solution) {\n      set_boundary(U,h1,h2,bd1a,bd1b,bd2a,bd2b,boundary,true);\n   }\n\n#ifdef TIME_REPORT\n   t2=stoptime();\n   printf(\"poisolve(): %5.0f ms: total time\\n\", (t2-t0)*1000.0);\n#endif\n\n   return sqrt(error);\n}\n\n\n// Poisson solver, assuming uniform boundary\ndouble poisolve(boost::multi_array<double,2>& U,\n                const boost::multi_array<double,2>& F,\n                double a1, double a2, double h1, double h2,\n                double bound_value,\n                types::boundary boundarycondition,\n                bool add_boundary_to_solution)\n{\n\n   size_t n1=F.shape()[0];\n   size_t n2=F.shape()[1];\n\n   // fill boundary vectors\n   std::vector<double> bd1a,bd1b,bd2a,bd2b;\n   set_boundary_to_uniform(bd1a,bd1b,bd2a,bd2b,bound_value,n1,n2);\n\n   // call the general solver\n   return poisolve(U,F,a1,a2,h1,h2,bd1a,bd1b,bd2a,bd2b,\n                   boundarycondition,add_boundary_to_solution);\n}\n\n} // namespace pde\n\n\n", "meta": {"hexsha": "a81c2868e111cbdd499103af74bbbce35cb948d8", "size": 25023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dvs_reconstruction/src/poisson_solver/laplace.cpp", "max_stars_repo_name": "jsz0913/rpg_dvs_evo_open", "max_stars_repo_head_hexsha": "93edc7a2d215ed097e3f6a9abbefd0b572958b74", "max_stars_repo_licenses": ["BSD-2-Clause-Patent"], "max_stars_count": 97.0, "max_stars_repo_stars_event_min_datetime": "2021-06-24T09:34:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T01:58:09.000Z", "max_issues_repo_path": "dvs_reconstruction/src/poisson_solver/laplace.cpp", "max_issues_repo_name": "jsz0913/rpg_dvs_evo_open", "max_issues_repo_head_hexsha": "93edc7a2d215ed097e3f6a9abbefd0b572958b74", "max_issues_repo_licenses": ["BSD-2-Clause-Patent"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-06-14T13:01:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T01:49:57.000Z", "max_forks_repo_path": "dvs_reconstruction/src/poisson_solver/laplace.cpp", "max_forks_repo_name": "jsz0913/rpg_dvs_evo_open", "max_forks_repo_head_hexsha": "93edc7a2d215ed097e3f6a9abbefd0b572958b74", "max_forks_repo_licenses": ["BSD-2-Clause-Patent"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T09:34:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T15:23:29.000Z", "avg_line_length": 30.4046172539, "max_line_length": 83, "alphanum_fraction": 0.5540502737, "num_tokens": 8359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6150878414043816, "lm_q1q2_score": 0.4477688474629633}}
{"text": "#ifndef EIGEN_SOLVER_H\n#define EIGEN_SOLVER_H\n\n#include <cassert>\n#include <armadillo>\n\n\n\nnamespace willow { namespace qcmol {\n\n\nclass EigenSolver\n{\npublic:\n\n  EigenSolver (): m_is_init(false), m_eig_vals(), m_eig_vecs() {}\n\n  // Sinvh.n_rows = nbf\n  // Sinvh.n_cols = nmo\n  // F.n_rows = nbf\n  // F.n_cols = nbf\n  // solve WF(nmo, nmo) = Sinv^T(nmo,nbf) F(nbf,nbf) Sinv(nbf,nmo)\n  // dsyevd(WF) or eig_sym ()\n  // save m_eig_vecs (nbf,nmo) = Sinvh(nbf,nmo)*Cvec(nmo,nmo)\n  //\n  EigenSolver  (const arma::mat Sinvh, const arma::mat F):\n    m_is_init(true),\n    m_eig_vals(Sinvh.n_cols),\n    m_eig_vecs(Sinvh.n_rows, Sinvh.n_cols) {\n\n    compute (Sinvh, F);\n\n  }\n    \n  void compute (const arma::mat Sinvh, const arma::mat F) {\n    \n    const int nbf = Sinvh.n_rows;\n    const int nmo = Sinvh.n_cols;\n    \n    if (!m_is_init) {\n      m_is_init = true;\n      m_eig_vals.set_size (nmo);\n      m_eig_vecs.set_size (nbf, nmo);\n    }\n\n    // F' \n    arma::mat wf = Sinvh.t()*F*Sinvh; // (nmo, nmo)\n\n    // Update Orbitals and Energies\n    arma::mat eg_vecs;\n    bool ok = arma::eig_sym (m_eig_vals, eg_vecs, wf);\n\n    // Transform back to non-orthogonal basis\n    m_eig_vecs = Sinvh*eg_vecs; // (nbf, nmol)\n    \n  }\n\n  arma::vec eigenvalues() const {\n    assert (m_is_init);\n    return m_eig_vals;\n  }\n  \n  arma::mat eigenvectors() const {\n    assert (m_is_init);\n    return m_eig_vecs;\n  }\n\nprotected:\n  bool      m_is_init;\n  arma::vec m_eig_vals;\n  arma::mat m_eig_vecs;\n};\n\n\n\n} } // namespace willow::qcmol\n\n#endif\n", "meta": {"hexsha": "7113ce146f3d97191e9247698d1ae019f6b62e77", "size": 1513, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "EigenSolver.hpp", "max_stars_repo_name": "swillow/w-qcmol", "max_stars_repo_head_hexsha": "b278417ca8b9eaf08c4a0712e295bdf5ac18595a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-02-19T22:13:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-19T22:13:42.000Z", "max_issues_repo_path": "EigenSolver.hpp", "max_issues_repo_name": "swillow/w-qcmol", "max_issues_repo_head_hexsha": "b278417ca8b9eaf08c4a0712e295bdf5ac18595a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EigenSolver.hpp", "max_forks_repo_name": "swillow/w-qcmol", "max_forks_repo_head_hexsha": "b278417ca8b9eaf08c4a0712e295bdf5ac18595a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1518987342, "max_line_length": 66, "alphanum_fraction": 0.6226040978, "num_tokens": 535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.44757073739643677}}
{"text": "/* \n// Copyright 2018 University of Liege\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n//     http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Authors:\n// - Adrien Crovato\n*/\n\n//// Wake panels creation\n// Compute wake panel collocation point, surface, vertices, normal, longitudinal, transverse and perpendicular\n// vectors from data contained into sGrid\n// Wake panels extend to a constant x coordinate, based on the geometry\n//\n// I/O:\n// - sGrid: temporary dynamic array containing body panel vertices\n// - bPan: body panels (structure)\n// - wPan: wake panels (structure)\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"create_wake.h\"\n\n#define  NDIM 3\n\nusing namespace std;\nusing  namespace Eigen;\n\nvoid create_wake(MatrixX3d &sGrid, Network &bPan, Network &wPan) {\n\n    // Temporary variables\n    double norm = 0;\n    Vector3d v1(NDIM), v2(NDIM);\n    double dwnstrm;\n    int c2, c3;\n\n    //// Begin\n    cout << \"Creating wake panels... \" << flush;\n\n    // Set number of panels (currently only handles predefined wakes)\n    wPan.nC = 2;\n    wPan.nC_ = 1;\n    wPan.nS = bPan.nS;\n    wPan.nS_ = bPan.nS_;\n    wPan.nP = wPan.nS_;\n\n    // Resize network matrices\n    wPan.CG.resize(wPan.nP, NDIM);\n    wPan.v0.resize(wPan.nP, NDIM);\n    wPan.v1.resize(wPan.nP, NDIM);\n    wPan.v2.resize(wPan.nP, NDIM);\n    wPan.v3.resize(wPan.nP, NDIM);\n    wPan.S.resize(wPan.nP, 1);\n    wPan.n.resize(wPan.nP, NDIM);\n    wPan.l.resize(wPan.nP, NDIM);\n    wPan.t.resize(wPan.nP, NDIM);\n    wPan.p.resize(wPan.nP, NDIM);\n\n    // Downstream coordinate of wake panels = tip x-coord+ 5*chord\n    dwnstrm = sGrid(sGrid.rows()-1,0) + 5*sGrid(0,0);\n\n    // Collocations points, corners and vectors\n    for (int j = 0; j < wPan.nP; ++j) {\n\n        c2 = j * bPan.nC;\n        c3 = (j+1) * bPan.nC;\n\n        wPan.v0(j,0) = dwnstrm; // pts[i][k]\n        wPan.v1(j,0) = sGrid(c2,0); // pts[i+1][k]\n        wPan.v2(j,0) = sGrid(c3,0); // pts[i+1][k+1]\n        wPan.v3(j,0) = dwnstrm; // pts[i][k+1]\n        wPan.v0(j,1) = sGrid(c2,1);\n        wPan.v1(j,1) = sGrid(c2,1);\n        wPan.v2(j,1) = sGrid(c3,1);\n        wPan.v3(j,1) = sGrid(c3,1);\n        wPan.v0(j,2) = sGrid(c2,2);\n        wPan.v1(j,2) = sGrid(c2,2);\n        wPan.v2(j,2) = sGrid(c3,2);\n        wPan.v3(j,2) = sGrid(c3,2);\n\n        wPan.CG(j,0) = (wPan.v0(j,0) + wPan.v1(j,0) + wPan.v2(j,0) + wPan.v3(j,0)) / 4;\n        wPan.CG(j,1) = (wPan.v1(j,1) + wPan.v2(j,1)) / 2;\n        wPan.CG(j,2) = (wPan.v1(j,2) + wPan.v2(j,2)) / 2;\n\n        wPan.l(j,0) = (wPan.v0(j,0) + wPan.v3(j,0) - wPan.v1(j,0) - wPan.v2(j,0)) / 4;\n        wPan.l(j,1) = 0;\n        wPan.l(j,2) = 0;\n        wPan.l.row(j) /= wPan.l.row(j).norm();\n\n        wPan.t(j,0) = (wPan.v2(j,0) - wPan.v1(j,0)) / 2;\n        wPan.t(j,1) = (wPan.v2(j,1) - wPan.v1(j,1)) / 2;\n        wPan.t(j,2) = (wPan.v2(j,2) - wPan.v1(j,2)) / 2;\n        wPan.t.row(j) /= wPan.t.row(j).norm();\n    }\n    // Surfaces and normals\n    for (int j = 0; j < wPan.nP; ++j) {\n        v1(0) = wPan.v2(j,0) - wPan.v0(j,0);\n        v2(0) = wPan.v1(j,0) - wPan.v3(j,0);\n        v1(1) = wPan.v2(j,1) - wPan.v0(j,1);\n        v2(1) = wPan.v1(j,1) - wPan.v3(j,1);\n        v1(2) = wPan.v2(j,2) - wPan.v0(j,2);\n        v2(2) = wPan.v1(j,2) - wPan.v3(j,2);\n\n        wPan.n.row(j) = v1.cross(v2);\n        norm = wPan.n.row(j).norm();\n\n        wPan.S(j) = norm/2;\n        wPan.n.row(j) /= norm;\n    }\n    // Perpendicular vector\n    for (int j = 0; j < wPan.nP; ++j)\n        wPan.p.row(j) = wPan.n.row(j).cross(wPan.l.row(j));\n\n    //// Control display\n    cout << \"Done!\" << endl;\n    cout << \"Wake panels extend to \" << dwnstrm << \" in the x direction\" << endl;\n    #ifdef VERBOSE\n        cout << \"Collocation points: \" << wPan.CG.rows() << 'X' << wPan.CG.cols() << endl;\n        for (int i = 0; i < wPan.nP; ++i)\n            cout << i << ' ' << wPan.CG(i,0) << ' ' << wPan.CG(i,1) << ' ' << wPan.CG(i,2) << endl;\n        cout << \"Panel surfaces: \" << wPan.S.rows() << 'X' << wPan.S.cols() << endl;\n        for (int i = 0; i < wPan.nP; ++i)\n            cout << i << ' ' << wPan.S(i) << endl;\n        cout << \"Unit normals: \" << wPan.n.rows() << 'X' << wPan.n.cols() << endl;\n        for (int i = 0; i < wPan.nP; ++i)\n            cout << i << ' ' << wPan.n(i,0) << ' ' << wPan.n(i,1) << ' ' << wPan.n(i,2) << endl;\n        cout << \"Unit longitudinal vectors: \" << wPan.l.rows() << 'X' << wPan.l.cols() << endl;\n        for (int i = 0; i < wPan.nP; ++i)\n            cout << i << ' ' << wPan.l(i,0) << ' ' << wPan.l(i,1) << ' ' << wPan.l(i,2) << endl;\n        cout << \"Unit transverse vectors: \" << wPan.t.rows() << 'X' << wPan.t.cols() << endl;\n        for (int i = 0; i < wPan.nP; ++i)\n            cout << i << ' ' << wPan.t(i,0) << ' ' << wPan.t(i,1) << ' ' << wPan.t(i,2) << endl;\n        cout << \"Unit perpendicular vectors: \" << wPan.p.rows() << 'X' << wPan.p.cols() << endl;\n        for (int i = 0; i < wPan.nP; ++i)\n            cout << i << ' ' << wPan.p(i,0) << ' ' << wPan.p(i,1) << ' ' << wPan.p(i,2) << endl;\n    #endif\n    cout << endl;\n}", "meta": {"hexsha": "6dd09e4b58ef780422cef92ffbd4739995e5d0b9", "size": 5473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/create_wake.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/create_wake.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/create_wake.cpp", "max_forks_repo_name": "acrovato/aero", "max_forks_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9797297297, "max_line_length": 110, "alphanum_fraction": 0.5278640599, "num_tokens": 2017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.44757073240424317}}
{"text": "#ifndef LIMEX_HH\n#define LIMEX_HH\n\n#include <fstream>\n#include <iostream>\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/istl/solvers.hh\"\n\n#include \"fem/embedded_errorest.hh\"\n#include \"fem/iterate_grid.hh\"\n#include \"fem/hierarchicErrorEstimator.hh\"\n#include \"fem/hierarchicspace.hh\"\n#include \"fem/istlinterface.hh\"\n\n#include \"dune/istl/solvers.hh\"\n#include \"dune/istl/preconditioners.hh\"\n\n#include \"timestepping/extrapolation.hh\"\n#include \"timestepping/semieuler.hh\"\n\n#include \"linalg/factorization.hh\"\n#include \"linalg/umfpack_solve.hh\"\n// #include \"linalg/mumps_solve.hh\"\n// #include \"linalg/superlu_solve.hh\"\n\n#include \"linalg/trivialpreconditioner.hh\"\n#include \"linalg/direct.hh\"\n#include \"linalg/triplet.hh\"\n#include \"linalg/iluprecond.hh\"\n#include \"linalg/additiveschwarz.hh\"\n// #include \"linalg/hyprecond.hh\"\n#include \"linalg/jacobiPreconditioner.hh\"\n\n#include \"utilities/enums.hh\"\n\n#include \"io/vtk.hh\"\n\nbool fabscompare( double a, double b ) { return fabs( a ) < fabs( b ) ; }\n\nDirectType xyz = DirectType::UMFPACK;\n\nnamespace Kaskade\n{\n  \n  \n  template <class Functional>\n  struct CardioD2\n  {\n    template <int row, int col>\n    class D2: public Functional::template D2<row,col>\n    {\n      typedef typename Functional::template D2<row,col> d2;\n      \n      public:\n\tstatic bool const present = d2::present && (row==0) && (col==0);\n\tstatic bool const lumped = true;\n    };\n  };\n  \n/**\n * \\ingroup timestepping\n * \\brief Extrapolated linearly implicit Euler method.\n * \n * This class implements the extrapolated linearly implicit Euler\n * method for integrating time-dependent evolution problems. The\n * implementation follows Deuflhard/Bornemann Chapter 6.4.3.\n */\ntemplate <class Eq>\nclass Limex \n{\npublic:\n  typedef Eq EvolutionEquation;\n  typedef typename EvolutionEquation::AnsatzVars::VariableSet State;\n\nprivate:\n  typedef SemiLinearizationAt<SemiImplicitEulerStep<EvolutionEquation> > Linearization;\n  typedef VariationalFunctionalAssembler<Linearization> Assembler;\n  \n  // for hierarchic error estimator\n  typedef FEFunctionSpace<ContinuousHierarchicExtensionMapper<double,typename Eq::AnsatzVars::Grid::LeafGridView> > SpaceEx;\n  typedef boost::fusion::vector< typename SpaceType<typename Eq::AnsatzVars::Spaces,0>::type const*, SpaceEx const*> ExSpaces;\n  \n//   two components, 1 space -- how to generalize?\n//   typedef boost::fusion::vector<VariableDescription<1,1,0>, VariableDescription<1,1,1> > ExVariableDescriptions;\n  \n  // 1 component, 1 space -- how to generalize?\n  typedef boost::fusion::vector<VariableDescription<1,1,0> > ExVariableDescriptions;\n  \n  typedef VariableSetDescription<ExSpaces,ExVariableDescriptions> ExVariableSet;\n  typedef HierarchicErrorEstimator<Linearization,ExVariableSet,ExVariableSet,CardioD2<Linearization> > ErrorEstimator;\n  typedef VariationalFunctionalAssembler<ErrorEstimator> EstimatorAssembler;\n  \n//   typedef typename EstimatorAssembler::template AnsatzVariableRepresentation<> Ansatz;\n//   typedef typename EstimatorAssembler::template TestVariableRepresentation<> Test;\n/*  typedef typename ExVariableSet::template CoefficientVectorRepresentation<0,1>::type ExCoefficientVectors;*/\n  \n  typedef typename Eq::AnsatzVars::Grid::Traits::LeafIndexSet IS ;\n  \n\npublic:\n  /**\n   * Constructs an ODE integrator. The arguments eq and ansatzVars\n   * have to exist during the lifetime of the integrator.\n   */\n  Limex(GridManager<typename EvolutionEquation::AnsatzVars::Grid>& gridManager_,\n        EvolutionEquation& eq_, typename EvolutionEquation::AnsatzVars const& ansatzVars_, DirectType st=DirectType::UMFPACK):\n    gridManager(gridManager_), ansatzVars(ansatzVars_), eq(&eq_,0),\n    assembler(gridManager,ansatzVars.spaces), \n    iteSteps(10000), iteEps(1e-6), extrap(0),\n    rhsAssemblyTime(0.0), matrixAssemblyTime(0.0), factorizationTime(0.0), solutionTime(0.0), adaptivityTime(0.0),\n    solverType(st)\n    {}\n\n\n  /**\n   * In order to maintain compatibility with existing code,\n   * this overload is needed, as non const reference parameters (refinements) can not\n   * have default values. All ist does is call the original method with a temporary\n   * parameter.\n   */\n  State const& step(State const& x, double dt, int order,\n                    std::vector<std::pair<double,double> > const& tolX)\n  {\n    std::vector<std::vector<bool> > tmp ;\n    return step(x,dt,order,tolX,tmp);\n  }\n\n  /**\n   * Computes a state increment that advances the given state in\n   * time. The time in the given evolution equation is increased by\n   * dt.\n   *\n   * \\param x the initial state to be evolved\n   * \\param dt the time step\n   * \\param order the extrapolation order >= 0 (0 corresponds to the linearly implicit Euler)\n   * \\param tolX \n   * \\param refinements keep track of the cells marked for refinement\n   * \\return the state increment (references an internal variable that will be\n   *         invalidated by a subsequent call of step)\n   *\n   * \\todo (i) check for B constant, do not reassemble matrix in this case\n   *       (ii) implement fixed point iteration instead of new factorization\n   *            in case B is not constant\n   */\n  State const& step(State const& x, double dt, int order,\n                    std::vector<std::pair<double,double> > const& tolX,\n\t\t    \n\t\t    std::vector< std::vector<bool> > &refinements )\n  {\n    boost::timer::cpu_timer timer;\n    \n    std::vector<double> stepFractions(order+1);\n    for (int i=0; i<=order; ++i) stepFractions[i] = 1.0/(i+1); // harmonic sequence\n    extrap.clear();\n\n    typedef typename EvolutionEquation::AnsatzVars::Grid Grid;\n    \n    int const dim = EvolutionEquation::AnsatzVars::Grid::dimension;\n    int const nvars = EvolutionEquation::AnsatzVars::noOfVariables;\n    int const neq = EvolutionEquation::TestVars::noOfVariables;\n    size_t  nnz = assembler.nnz(0,neq,0,nvars,false);\n    size_t  size = ansatzVars.degreesOfFreedom(0,nvars);\n    \n    std::vector<double> rhs(size), sol(size);\n\n    State dx(x), dxsum(x), tmp(x);\n    double const t = eq.time();\n    \n    double estTime = 0 ;\n\n    eq.temporalEvaluationRange(t,t+dt);\n    \n    typedef AssembledGalerkinOperator<Assembler,0,neq,0,neq> Op;\n        \n    bool iterative = true ;\n    int fill_lev = /*0*/ /*1*/2;\n        \n    typedef typename EvolutionEquation::AnsatzVars::template CoefficientVectorRepresentation<0,neq>::type\n      CoefficientVectors;\n    typedef typename EvolutionEquation::TestVars::template CoefficientVectorRepresentation<0,neq>::type \n      LinearSpaceX;\n\n    for (int i=0; i<=order; ++i) {\n      double const tau = stepFractions[i]*dt;\n      eq.setTau(tau);\n      eq.time(t);\n\n      // mesh adaptation loop. Just once if i>0.\n      bool accurate = true;\n      int refinement_count = 0 ;             \n\t\n      \n      do {\t\n        // Evaluate and factorize matrix B(t)-tau*J\n        dx/* * */= 0;\n        timer.start();\n\t\n// \tassembler.assemble(Linearization(eq,x,x,dx)/*,(Assembler::VALUE|Assembler::RHS|Assembler::MATRIX),4*/);\n\t\n// #ifndef KASKADE_SEQUENTIAL\n// \tgridManager.enforceConcurrentReads(std::is_same<Grid,Dune::UGGrid<dim> >::value);\n// \tassembler.setNSimultaneousBlocks(40);\n// \tassembler.setRowBlockFactor(2.0);\n// #endif\n// \tstd::cout << \"assemble linear system ...\" ; std::cout.flush();\n\tassembler.assemble(Linearization(eq,x,x,dx)/*,(Assembler::VALUE|Assembler::RHS|Assembler::MATRIX),4*/);\n// \tstd::cout << \" done\\n\"; std::cout.flush();\n\n\tmatrixAssemblyTime += (double)(timer.elapsed().user)/1e9;\n\t\n\tOp A(assembler);\n// \tstd::cout << \"solve linear system\\n\"; std::cout.flush();\n\t  \n\tif (iterative) \n\t{  \t  \n\t  timer.start();\n\n\t  CoefficientVectors  solution(EvolutionEquation::AnsatzVars::template CoefficientVectorRepresentation<0,neq>::init(ansatzVars.spaces)\n\t    );\n\t  solution = 0;\n\t  CoefficientVectors rhs(assembler.rhs());\n\t  \n\t  ILUKPreconditioner<Op> p(A,fill_lev,0);\n// \t  ILUTPreconditioner<Op> p(A,240,1e-2,0);\n// \t  JacobiPreconditioner<Op> p(A,1.0);\n\n\t  Dune::BiCGSTABSolver<LinearSpaceX> cg(A,p,1e-7,2000,0); //verbosity: 0-1-2 (nothing-start/final-every it.)\n\t  Dune::InverseOperatorResult res;\n\t  cg.apply(solution,rhs,res);\n\t  if ( !(res.converged) || (res.iterations == 2001) ) {\n\t    std::cout << \"   no of iterations in cg = \" << res.iterations << std::endl;\n\t    std::cout << \" convergence status of cg = \" << res.converged  << std::endl;\n\t    assert(0);\n\t  }\n\t  dx.data = solution.data;\n\t  solutionTime += (double)(timer.elapsed().user)/1e9;\n\t}\n\telse\n\t{\n\t  // direct solution\n\t  timer.start();\n// \t  assembler.toTriplet(0,neq,0,nvars,ridx.begin(),cidx.begin(),data.begin(),false);\n\t  MatrixAsTriplet<double> triplet = A.template get<MatrixAsTriplet<double> >();\n\t  \n\t  Factorization<double> *matrix = 0;\n\t  switch (solverType) {\n\t    case DirectType::UMFPACK:\n\t      matrix = new UMFFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);\n\t      break;\n\t    case DirectType::UMFPACK3264:\n\t      matrix = new UMFFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);\n\t      break;\n// \t    case MUMPS:\n// \t      matrix = new MUMPSFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);\n// \t      break;\n// \t    case SUPERLU:\n// \t      matrix = new SUPERLUFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);\n// \t      break;\n\t    default:\n\t      throw -321;\n\t      break;\n\t  }\n\t  factorizationTime += (double)(timer.elapsed().user)/1e9;\n\t  \n\t  // First right hand side (j=0) has been assembled together with matrix.\n\t  timer.start();\n\t  A.getAssembler().toSequence(0,neq,rhs.begin());\n\t  for (int k=0; k<rhs.size(); ++k) assert(std::isfinite(rhs[k]));\n\t  matrix->solve(rhs,sol);\n\t  delete matrix;\n\t  for (int k=0; k<sol.size(); ++k) assert(std::isfinite(sol[k]));\n\t  dx.read(sol.begin());\n\t  solutionTime += (double)(timer.elapsed().user)/1e9;\n\t  \n\n// \t  Factorization<double> *matrix = 0;\n// \t  switch (solverType)\n// \t    {\n// \t      case UMFPACK:\n// \t\tmatrix = new UMFFactorization<double>(size,0,ridx,cidx,data);\n// \t\tbreak;\n// \t      case UMFPACK3264:\n// \t\tmatrix = new UMFFactorization<double>(size,0,ridx,cidx,data);\n// \t\tbreak;\n// \t      case MUMPS:\n// \t\tmatrix = new MUMPSFactorization<double>(size,0,ridx,cidx,data);\n// \t\tbreak;\n// \t      case SUPERLU:\n// \t\tmatrix = new SUPERLUFactorization<double>(size,0,ridx,cidx,data);\n// \t\tbreak;\n// \t      default:\n// \t\tthrow -321;\n// \t\tbreak;\n// \t    }\n// \t  factorizationTime += (double)(timer.elapsed().user)/1e9;\n// \n// \t  // First right hand side (j=0) has been assembled together with matrix.\n// \t  timer.start();\n// \t  assembler.toSequence(0,neq,rhs.begin());\n// \t  for (size_t k=0; k<rhs.size(); ++k) assert(finite(rhs[k]));\n// \t  matrix->solve(rhs,sol);\n// \t  delete matrix;\n// \t  for (size_t k=0; k<sol.size(); ++k) assert(finite(sol[k]));\n// \t  dx.read(sol.begin());\n// \t  solutionTime += (double)(timer.elapsed().user)/1e9;\n\t  //end: direct solution\n\t}\n\n        // Mesh adaptation only if requested and only for the full\n        // implicit Euler step (first stage).\n        \n\ttypedef typename EvolutionEquation::AnsatzVars::GridView::template Codim<0>::Iterator CellIterator ;\n        \n\taccurate = true ;\n\ttimer.start();\n\tIS const& is = gridManager.grid().leafIndexSet();\n\tstd::vector<double> errorDistribution(is.size(0),0.0);\n\tdouble maxErr = 0.0, errNorm = 0.0 ;\n\n        if (!tolX.empty() && i==0) {\n\n\t  // embeddedErrorEstimator can not be used for linear finite elements\n\t  // use HierarchicErrorEstimator instead\n\t  // preparation for HierarchicErrorEstimator\n\t  if(true) // to avoid mesh adaptation for exVariables\n\t  {\n\t  //TODO: this should be using the gridviews/index sets of the original space, not the leaf!\n\t  SpaceEx  spaceEx(gridManager,gridManager.grid().leafGridView(), boost::fusion::at_c<0>(ansatzVars.spaces)->mapper().getOrder()+1);\n\t  typename SpaceType<typename Eq::AnsatzVars::Spaces,0>::type spaceH1 = *(boost::fusion::at_c<0>(ansatzVars.spaces)) ;\n\t  ExSpaces exSpaces(&spaceH1,&spaceEx);\n\t  std::string exVarNames[2] = { \"ev\", \"ew\" };\n\t  ExVariableSet exVariableSet(exSpaces, exVarNames);\n\t  EstimatorAssembler estAssembler(gridManager,exSpaces);   \n\t   \n\t  tmp/* * */= 0 ;\n// \t  estAssembler.assemble(ErrorEstimator(Linearization(eq,x,x,tmp/*dx*/),dx));\n\t  estAssembler.assemble(ErrorEstimator(semiLinearization(eq,x,x,/*dx*/tmp),dx));\n\n\t  \n\t  int const estNvars = ErrorEstimator::AnsatzVars::noOfVariables;\n// \t  std::cout << \"estimator: nvars = \" << estNvars << \"\\n\";\n\t  int const estNeq = ErrorEstimator::TestVars::noOfVariables;\n// \t  std::cout << \"estimator:   neq = \" << estNeq << \"\\n\";\n\t  size_t  estNnz = estAssembler.nnz(0,estNeq,0,estNvars,false);\n\t  size_t  estSize = exVariableSet.degreesOfFreedom(0,estNvars);\n\t  \n\t  std::vector<int> estRidx(estNnz), estCidx(estNnz);\n\t  std::vector<double> estData(estNnz), estRhs(estSize), estSolVec(estSize);\n\t  \n\t  estAssembler.toSequence(0,estNeq,estRhs.begin());\n\t  \n\t  typedef typename ExVariableSet::template CoefficientVectorRepresentation<0,estNeq>::type ExCoefficientVectors;\n\t  \n\t  // iterative solution of error estimator\n// \t  timer.start();\n// \t  AssembledGalerkinOperator<EstimatorAssembler> E(estAssembler);\n// \t  typename Dune::InverseOperatorResult estRes;\n// \t  typename Test::type estRhside( Test::rhs(estAssembler) ) ;\n// \t  typename Ansatz::type estSol( Ansatz::init(estAssembler) ) ;\n// \t  estSol = 1.0 ;\n// \t  JacobiPreconditioner<EstimatorAssembler> jprec(estAssembler, 1.0);\n// \t  jprec.apply(estSol,estRhside); //single Jacobi iteration\n// \t  estTime += (double)(timer.elapsed().user)/1e9;\n// \t  estSol.write(estSolVec.begin());\n\t  \n\t  typedef AssembledGalerkinOperator<EstimatorAssembler> AssEstOperator;\n\t  AssEstOperator agro(estAssembler);\n\t  Dune::InverseOperatorResult estRes;\n\t  ExCoefficientVectors estRhside(estAssembler.rhs());\n\t  ExCoefficientVectors estSol(ExVariableSet::template CoefficientVectorRepresentation<0,estNeq>::init(exVariableSet.spaces));\n\t  estSol = 1.0 ;\n\t  JacobiPreconditioner<AssEstOperator> jprec(agro, 1.0);\n\t  jprec.apply(estSol,estRhside); //single Jacobi iteration\n// \t  estTime += (double)(timer.elapsed().user)/1e9;\n\t  estSol.write(estSolVec.begin());\n\t  \n\t  //--\n\t  \n\t  // Transfer error indicators to cells.\n\t  CellIterator ciEnd = ansatzVars.gridView.template end<0>() ;\n\t  for (CellIterator ci=ansatzVars.gridView.template begin<0>(); ci!=ciEnd; ++ci) {\n\t    typedef typename SpaceEx::Mapper::GlobalIndexRange GIR;\n\t    double err = 0.0;\n\t    GIR gix = spaceEx.mapper().globalIndices(*ci);\n\t    for (typename GIR::iterator j=gix.begin(); j!=gix.end(); ++j)\n\t      err += fabs(boost::fusion::at_c<0>(estSol.data)[*j]);\n\t    // only for 1st component -- second in monodomain is ODE\n\t    errorDistribution[is.index(*ci)] = err;\n\t    if (fabs(err)>maxErr) maxErr = fabs(err);\n\t  }\n// \t  std::cout << \"maxErr: \" << maxErr << \"\\n\";\n\t  \n// \t  for( size_t cno = 0 ; cno < is.size(0); cno++ )\n// \t    std::cout << cno << \"\\t\\t\" << errorDistribution[cno] << \"\\n\";\n// \t  std::cout.flush();\n\t  \n\t  //TODO: estimate only error in PDE, not ODE!\n\t  // what about relative accuracy?\n\t  for (size_t k = 0; k < estRhs.size() ; k++ ) errNorm +=  fabs( estRhs[k] * estSolVec[k] ); \n\t  // this is for all variables?!\n// \t  errNorm = tau/*dt*/*sqrt(errNorm);\n\t  std::cout << \"errNorm = \" << errNorm << std::endl ;\n\t  std::cout.flush();\n\n\t  }\n\t\n\t  double overallTol = tolX[0].first ;\n\n\t  \n// \t  for( int i = 0 ; i < 1 /*nvars*/ ; i++ )\n// \t    overallTol += tolX[i].first*tolX[i].first ; \n// \t  overallTol = sqrt(overallTol);\n\t  \n// \t  std::cout << \"overallTol = \" << overallTol << std::endl ;\n\t  \n\t  \n// \t  alpha = 0 ; // for uniform refinement\n\n\t  int nRefMax = /*10*/7 ;/*7*//*5*//*3*//*15*/ /*4*/ /*5*/ /*10*/\n\t  double fractionOfCells = 0.05; /*0.1,0.2*/\n\t  unsigned long noToRefine = 0, noToCoarsen = 0;\n\t  double alpha = 1.0; /*0.5; //test april 13*/\n\t  \n\t  double errLevel = 0.5*maxErr ; //0.75\n// \t  double minRefine = 0.05;\n\t  \n// \t  if (minRefine>0.0)\n// \t  {\n// \t    std::vector<double> eSort(errorDistribution);\n// \t    std::sort(eSort.begin(),eSort.end(),fabscompare);\n// \t    int minRefineIndex = minRefine*(eSort.size()-1);\n// \t    double minErrLevel = fabs(eSort[minRefineIndex])+1.0e-15;\n// \t    if (minErrLevel<errLevel)\n// \t      errLevel = minErrLevel;\n// \t  }\n\t  \n// \t  double minRefine = fractionOfCells; //* gridManager.grid().size(0);\n// \t  if (minRefine >0.0)\n// \t  {\n// \t    std::vector<double> eSort(errorDistribution);\n// \t    std::sort(eSort.begin(),eSort.end(),fabscompare);\n// \t    int minRefineIndex = minRefine*(eSort.size()-1);\n// \t    double minErrLevel = fabs(eSort[minRefineIndex])+1.0e-15;\n// \t    if (minErrLevel<errLevel)\n// \t      errLevel = minErrLevel;\n// \t  }\n\n\t  size_t maxNoOfVertices =/* 500000*/ /*2000000*//*12000*/30000;\n\t  size_t maxNoOfElements = 2000000;\n\t  int maxLevel = /*20*/6 /*25*/ /*18*/; // additional refinement levels\n\t    \n\t  if( errNorm > overallTol && refinement_count < nRefMax \n\t    && gridManager.grid().size(/*dim*/0) < /*maxNoOfVertices*/maxNoOfElements )\n\t    //current setup: for 2D BFGS; for 3D fibrillation: use maxNoOfElements\n\t  {    \n// \t    accurate = false;\n// \t    std::vector<bool> toRefine( is.size(0), false ) ; \n// \t    size_t noCells = gridManager.grid().size(0);\n// // \t    std::cout << is.size(0) << \"   \" << noCells << \"\\n\"; std::cout.flush();\n// \t    for( size_t cno = 0 ; cno < noCells ; cno++ )\n// \t    {\n// \t      if (fabs(errorDistribution[cno]) >= alpha*errLevel)\n// \t      {\n// \t\tnoToRefine++;\n// \t\ttoRefine[cno] = true ;\n// \t      }\n// \t    }\n\t    std::vector<bool> toRefine( is.size(0), false ) ; //for adaptivity in compression\n\t    \n\t    accurate = false ;\n\t    size_t noCells = gridManager.grid().size(0);\n\t    \n// \t    // Nagaiah paper:\n// \t    unsigned minLevel = 10 ; // do not coarsen below that level     \n// \t    CellIterator ciEnd = ansatzVars.gridView.template end<0>() ;\n// \t    for (CellIterator ci=ansatzVars.gridView.template begin<0>(); ci!=ciEnd; ++ci) \n// \t    {\n// \t      double vol = sqrt( ci->geometry().volume() );\n// \t      if (fabs(errorDistribution[is.index(*ci)])/vol >= 0.2 /*0.1*/ )\n// \t      {\n// \t\tif( ci->level() < maxLevel && gridManager.grid().size(dim) < maxNoOfVertices )\n// \t\t{\n// \t\t  gridManager.mark(1,*ci);\n// \t\t  noToRefine++;\n// \t\t}\n// \t      }\n// \t      else if (fabs(errorDistribution[is.index(*ci)])/vol < 0.1 /* /2 */ && ci->level() > minLevel ) \n// \t      {\n// \t\tgridManager.mark(-1,*ci);\n// \t\tnoToCoarsen++;\n// \t      }\n// \t    }\n// \t    std::cout << \"refine: \" << noToRefine << \"    coarsen: \" << noToCoarsen << \"\\n\";\n// \t    gridManager.countMarked();\n\t    \n// \t    last implementation was the following:\n\t    unsigned long noToRefineOld = 0;\n\t    do{\n\t      noToRefineOld = noToRefine;\n\t      for( size_t cno = 0 ; cno < noCells ; cno++ )\n\t      {\n\t\t      if (fabs(errorDistribution[cno]) >= alpha*errLevel) \n\t\t      { // TODO: check and bugfix this!\n\t\t\t      if( !toRefine[cno] ) noToRefine++;\n\t\t\t      toRefine[cno] = true ;\n\t\t      }\n\t      }\n// \t\tstd::cout << \"alpha: \" << alpha << \"\\trefine: \" << noToRefine << \"\\n\";\n// \t\tstd::cout.flush();\n\t\talpha *= 0.75; // refine more aggressively: reduce alpha by larger amount\n\t    } while ( noToRefine < fractionOfCells * noCells && (!noToRefineOld == noToRefine) ) ;\n//   \t    std::cout << \"to refine: \" << noToRefine << \"\\n\";\n\t    std::cout.flush();\n\n\t    \n// \t    alpha = 0.5; //50\n// \t    do {\n// \t      for( size_t cno = 0 ; cno < noCells ; cno++ )\n// \t\tif (fabs(errorDistribution[cno]) > alpha*maxErr/*overallTol/noCells*/) {\n// \t\t    /*if( !toRefine[cno] )*/ noToRefine++;\n// \t\t    toRefine[cno] = true;\n// \t\t  }\n// \t      \n// \t\t  alpha *=0.9;\n// \t    } while (noToRefine < fractionOfCells * noCells);\n\t    \n// \t    long int nRefined = (long int) std::count( toRefine.begin(), toRefine.end(), true );\n// \t    std::cout << \"   noToRefine = \" << nRefined << std::endl;\n// \t    refinements.push_back(toRefine);\n\n\t    for (CellIterator ci=ansatzVars.gridView.template begin<0>(); ci!=ansatzVars.gridView.template end<0>(); ++ci)\n\t      if( toRefine[is.index(*ci)] && ci->level() < maxLevel )  gridManager.mark(1,*ci);\n\t    \n\t    bool refok = gridManager.adaptAtOnce();  // something has been refined?\n\t    if( !refok ) \n\t    {\n\t      // nothing has been refined\n\t      std::cout << \"nothing has been refined (probably due to maxLevel constraint), stopping\\n\";\n\t      accurate = true ;\n\t    }\n\t    \n\t    if (!accurate) {\n\t      refinement_count++ ;\n\t      nnz = assembler.nnz(0,neq,0,nvars,false);\n\t      size = ansatzVars.degreesOfFreedom(0,nvars);\n\t      rhs.resize(size);\n\t      sol.resize(size);\n\t    }\n\t  }\n\t  else\n\t  {\n\t   if( errNorm > overallTol && refinement_count > nRefMax ) \n\t     std::cout << \"max no of refinements exceeded\\n\";\n// \t   if( errNorm > overallTol && gridManager.grid().size(2) > maxNoOfVertices ) \n// \t     std::cout << \"max no of nodes exceeded\\n\";\n\t    \n\t   accurate = true ;\n\t  }\n        }\n      } while (!accurate); \n      adaptivityTime += (double)(timer.elapsed().user)/1e9;\n\n//       std::cout << gridManager.grid().size(dim) << \" nodes on \" << gridManager.grid().maxLevel() << \"levels\\n\";\n\n      dxsum = dx;\n\n      // propagate by linearly implicit Euler \n      for (int j=1; j<=i; ++j) {\n\t// Assemble new right hand side tau*f(x_j)\n        eq.time(eq.time()+tau);\n\ttmp = x; tmp += dxsum;\n        State zero(x); zero /* * */= 0;\n        timer.start();\n// \tgridManager.enforceConcurrentReads(true);\n// \tassembler.setNSimultaneousBlocks(40);\n// \tassembler.setRowBlockFactor(2.0);\n        assembler.assemble(Linearization(eq,tmp,x,zero),Assembler::RHS|Assembler::MATRIX,4);\n        rhsAssemblyTime += (double)(timer.elapsed().user)/1e9;\n\t\n\tOp A(assembler);\n\t\n\tif( !iterative )\n\t{\n\t  timer.start();\n\t  //direct solution\n\t  A.getAssembler().toSequence(0,neq,rhs.begin());\n\t  MatrixAsTriplet<double> triplet = A.template get<MatrixAsTriplet<double> >();\n\t  Factorization<double> *matrix = 0;\n\t  switch (solverType) {\n\t    case DirectType::UMFPACK:\n\t      matrix = new UMFFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);\n\t      break;\n\t    case DirectType::UMFPACK3264:\n\t      matrix = new UMFFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);\n\t      break;\n// \t    case MUMPS:\n// \t      matrix = new MUMPSFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);\n// \t      break;\n// \t    case SUPERLU:\n// \t      matrix = new SUPERLUFactorization<double>(size,0,triplet.ridx,triplet.cidx,triplet.data);\n// \t      break;\n\t    default:\n\t      throw -321;\n\t      break;\n\t  }\n\t  factorizationTime += (double)(timer.elapsed().user)/1e9;\n\t  timer.start();\n\t  matrix->solve(rhs,sol);\n\t  delete matrix;\n\t  for (int k=0; k<rhs.size(); ++k) assert(std::isfinite(rhs[k]));\n\t  for (int k=0; k<sol.size(); ++k) assert(std::isfinite(sol[k]));\n\t  dx.read(sol.begin());\n\t  solutionTime += (double)(timer.elapsed().user)/1e9;\n\t}\n\telse\n\t{\n\t  timer.start();\n\t  CoefficientVectors  solution(EvolutionEquation::AnsatzVars::template\n\t\t    CoefficientVectorRepresentation<0,neq>::init(ansatzVars.spaces) );\n\t  solution = 0;\n\t  // \t  assembler.assemble(linearization(F,x));\n\t  CoefficientVectors rhs(assembler.rhs());\n\t  \n\t  ILUKPreconditioner<Op> p(A,fill_lev,0);\n// \t  ILUTPreconditioner<Op> p(A,240,1e-2,0);\n// \t  JacobiPreconditioner<Op> p(A,1.0);\n\n\t  \n\t  Dune::BiCGSTABSolver<LinearSpaceX> cg(A,p,1e-7,2000,0); //verbosity: 0-1-2 (nothing-start/final-every it.)\n\t  Dune::InverseOperatorResult res;\n\t  cg.apply(solution,rhs,res);\n\t  if ( !(res.converged) || (res.iterations == 2001) ) {\n\t    std::cout << \"   no of iterations in cg = \" << res.iterations << std::endl;\n\t    std::cout << \" convergence status of cg = \" << res.converged  << std::endl;\n\t    assert(0);\n\t  }\n\t  dx.data = solution.data;\n// \t// iterative solution\n//         timer.start();\n// \ttypedef typename Assembler::template TestVariableRepresentation<>::type Rhs;\n// \ttypedef typename Assembler::template AnsatzVariableRepresentation<>::type Sol;\n// \tSol solution(Assembler::template AnsatzVariableRepresentation<>::init(assembler));\n// \tRhs rhside(Assembler::template TestVariableRepresentation<>::rhs(assembler));\n// \tAssembledGalerkinOperator<Assembler,0,1,0,1> A(assembler, false);\n// \ttypename AssembledGalerkinOperator<Assembler,0,1,0,1>::matrix_type tri(A.getmat());\n// \n// \t\n//         typedef typename Assembler::template TestVariableRepresentation<>::type LinearSpace;\n// \tDune::InverseOperatorResult res;\n// \tsolution = 1.0;\n//      \tJacobiPreconditioner<Assembler,0,1,0> p(assembler,1.0);\n// // \tTrivialPreconditioner<LinearSpace> trivial;\n// \tDune::CGSolver<LinearSpace> cg(A,/*trivial*/p,iteEps,iteSteps,0);\n// \tcg.apply(solution,rhside,res);\n// \tA.applyscaleadd(-1.0,rhside,solution);\n// \tdouble slntime = (double)(timer.elapsed().user)/1e9;\n// \tsolutionTime += slntime ;\n// \tdx.data = solution.data ;  \n// \t// end: iterative solution\n\t}\n\t\n        dxsum += dx;\n        solutionTime += (double)(timer.elapsed().user)/1e9;\n      }\n\n      // insert into extrapolation tableau\n      extrap.push_back(dxsum,stepFractions[i]);\n\n      // restore initial time\n      eq.time(t);\n    }\n\n    return extrap.back();\n  }\n\n  /**\n   * Estimates the time discretization error of the previously\n   * computed step by taking the difference between the diagonal and\n   * subdiagonal extrapolation values of maximal order. This requires\n   * that order>1 has been given for the last step.\n   */\n  std::vector<std::pair<double,double> > estimateError(State const& x,int i, int j) const \n  {\n    assert(extrap.size()>1);\n\n    std::vector<std::pair<double,double> > e(ansatzVars.noOfVariables);\n    \n    relativeError(typename EvolutionEquation::AnsatzVars::Variables(),extrap[i].data,\n                  extrap[j].data,x.data,\n                  ansatzVars.spaces,eq.scaling(),e.begin());\n    \n    return e;\n  }\n  \n  template <class OutStream>\n  void reportTime(OutStream& out) const {\n    out << \"Limex time: \" << matrixAssemblyTime << \"s matrix assembly\\n\"\n        << \"            \" << rhsAssemblyTime << \"s rhs assembly\\n\"\n        << \"            \" << factorizationTime << \"s factorization\\n\"\n        << \"            \" << solutionTime << \"s solution\\n\"\n\t<< \"            \" << adaptivityTime << \"s adaptivity\\n\";\n  }\n  \n  void advanceTime(double dt) { eq.time(eq.time()+dt); }\n  \n  \nprivate:\n  GridManager<typename EvolutionEquation::AnsatzVars::Grid>& gridManager;\n  typename EvolutionEquation::AnsatzVars const& ansatzVars;\n  SemiImplicitEulerStep<EvolutionEquation>      eq;\n  Assembler                                     assembler;\n  int iteSteps ;\n  double iteEps ;\n    \npublic:\n  ExtrapolationTableau<State>  extrap;\n  double rhsAssemblyTime, matrixAssemblyTime, factorizationTime, solutionTime, adaptivityTime;\n  DirectType solverType;\n};\n\n} //namespace Kaskade\n#endif\n", "meta": {"hexsha": "1361a37f4b1da97bb92190c9e2e46117ec901d0b", "size": 26700, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/timestepping/limexWithoutJensHierarchicEst.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/timestepping/limexWithoutJensHierarchicEst.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:33.000Z", "max_forks_repo_path": "Kaskade/timestepping/limexWithoutJensHierarchicEst.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 36.8275862069, "max_line_length": 135, "alphanum_fraction": 0.6483146067, "num_tokens": 7687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4475332806088169}}
{"text": "#ifndef SCALARREWRITE_HPP\n#define SCALARREWRITE_HPP\n\n#include \"scalarbase.hpp\"\n#include \"exprrewrite.hpp\"\n#include \"exprmatch.hpp\"\n#include <algorithm>\n//#include <boost/logiclogic/tribool>\n#include \"scalarrange.hpp\"\n\nbool isgenexp(const expr &e) {\n\tif (e.isleaf()) {\n\t\tif (e.asleaf().type()==typeid(matchleaf)) {\n\t\t\tmatchleaf ml = MYany_cast<matchleaf>(e.asleaf());\n\t\t\tif (std::dynamic_pointer_cast<matchany>(ml)\n\t\t\t    || std::dynamic_pointer_cast<matchvar>(ml)\n\t\t\t    || std::dynamic_pointer_cast<matchconstwrt>(ml)\n\t\t\t    || std::dynamic_pointer_cast<matchnonconstwrt>(ml))\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\tauto n = std::dynamic_pointer_cast<matchlabelop>(e.asnode());\n\tif (!n) return false;\n\tif (e.children().size()!=1) return false;\n\treturn isgenexp(e.children()[0]);\n}\n\n\nexpr chainpatternmod(const expr &ex) {\n\treturn ex.map([](const expr &e) {\n\t\t\tif (e.isleaf()) return optional<expr>{};\n\t\t\tauto n = e.asnode();\n\t\t\tif (n==pluschain || n==multiplieschain) {\n\t\t\t\tauto bop = std::dynamic_pointer_cast<opchain>(n)->baseop;\n\t\t\t\tauto ch = e.children();\n\t\t\t\tauto last = ch.back();\n\t\t\t\tif (isgenexp(last))\n\t\t\t\t\treturn optional<expr>{in_place,std::make_shared<matchassocop>(std::make_shared<matchremainderop>(bop)),\n\t\t\t\t\t\t\tch};\n\t\t\t\telse return optional<expr>{in_place,std::make_shared<matchassocop>(bop),\n\t\t\t\t\t\t\tch};\n\t\t\t}\n\t\t\treturn optional<expr>{};\n\t\t});\n}\n\nstruct sortchildren : public rewriterule {\n\tvirtual ruleptr clone() const { return std::make_shared<sortchildren>(*this); }\n\toptional<vset> vars;\n\tstd::vector<op> cops;\n\n\tsortchildren(std::vector<op> comops)\n\t\t: cops(comops), vars{} { }\n\tsortchildren(std::vector<op> comops, vset v)\n\t\t: cops(comops), vars(in_place,std::move(v)) {}\n\n\tint typeorder(const expr &e) const {\n\t\t// TODO: use map/unordered_map\n\t\tif (isconst(e)) return 0;\n\t\tint add = (isconstexpr(e,vars) ? 0 : 13);\n\t\tif (e.isleaf()) return 1+add;\n\t\tauto &op = e.asnode();\n\t\tif (op==plusop || op==pluschain) return 2+add;\n\t\tif (op==multipliesop || op==multiplieschain) return 3+add;\n\t\tif (op==powerop) return 4+add;\n\t\tif (op==logop) return 5+add;\n\t\t//if (op==switchop) return 6+add;\n\t\tif (op==condop) return 7+add;\n\t\tif (op==condeqop) return 8+add;\n\t\tif (op==absop) return 9+add;\n\t\tif (op==derivop) return 10+add;\n\t\tif (op==integrateop) return 11+add;\n\t\tif (op==evalatop) return 12+add;\n\t\treturn 13+add;\n\t}\n\n\tvirtual void setvars(const vset &v) {\n\t\tvars = v;\n\t}\n\n\tint secondordering(const expr &e1, const expr &e2) const {\n\t\tif (isconst(e1)) {\n\t\t\tscalarreal v1 = getconst<scalarreal>(e1);\n\t\t\tscalarreal v2 = getconst<scalarreal>(e2);\n\t\t\tif (v1<v2) return -1;\n\t\t\tif (v1>v2) return +1;\n\t\t\treturn 0;\n\t\t}\n\t\tif (isvar(e1))\n\t\t\treturn MYany_cast<var>(e1.asleaf())->name\n\t\t\t\t\t.compare(MYany_cast<var>(e2.asleaf())->name);\n\t\tif (e1.isleaf()) return 0;\n\t\tauto &ch1 = e1.children();\n\t\tauto &ch2 = e2.children();\n\t\tfor(int i=std::min(ch1.size(),ch2.size())-1;i>=0;i--) {\n\t\t\tint res = exprcmp(ch1[i],ch2[i]);\n\t\t\tif (res!=0) return res;\n\t\t}\n\t\treturn ch1.size()-ch2.size();\n\t}\n\n\tint exprcmp(const expr &e1, const expr &e2) const {\n\t\tint o1 = typeorder(e1), o2 = typeorder(e2);\n\t\tif (o1!=o2) return o1-o2;\n\t\treturn secondordering(e1,e2);\n\t}\n\n\tvirtual optional<expr> apply(const expr &e) const {\n\t\tif (e.isleaf()) return {};\n\t\tif (std::find(cops.begin(),cops.end(),e.asnode())==cops.end())\n\t\t\treturn {};\n\t\tauto &ch = e.children();\n\t\tif (ch.size()<2) return {};\n\t\tfor(int i=1;i<ch.size();i++) {\n\t\t\tif (exprcmp(ch[i-1],ch[i])>0) {\n\t\t\t\tstd::vector<expr> che = ch;\n\t\t\t\tstd::sort(che.begin(),che.end(),\n\t\t\t\t\t\t[this](const expr &e1, const expr &e2) {\n\t\t\t\t\t\t\treturn exprcmp(e1,e2)<0;\n\t\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\treturn optional<expr>{in_place,e.asnode(),che};\n\t\t\t}\n\t\t}\n\t\treturn {};\n\t}\n};\n\nscalarset<scalarreal> rangeprop(const expr &e) {\n\tif (isconst(e)) {\n\t\treturn {getconst<scalarreal>(e)};\n\t}\n\tif (isop(e,pluschain)) {\n\t\tauto &ch = e.children();\n\t\tif (ch.empty()) return {-std::numeric_limits<scalarreal>::infinity(),\n\t\t\t\t\tstd::numeric_limits<scalarreal>::infinity()};\n\t\tauto ret = rangeprop(ch[0]);\n\t\tfor(int i=1;i<ch.size();i++)\n\t\t\tret = ret.combine(rangeprop(ch[i]),\n\t\t\t\t\t[](const range<scalarreal> &a, const range<scalarreal> &b) {\n\t\t\t\t\t\treturn range<scalarreal>{a.first+b.first,\n\t\t\t\t\t\t\t\t\ta.second+b.second}; });\n\t\treturn ret;\n\t}\n\tif (isop(e,multiplieschain)) {\n\t\tauto &ch = e.children();\n\t\tif (ch.empty()) return {-std::numeric_limits<scalarreal>::infinity(),\n\t\t\t\t\tstd::numeric_limits<scalarreal>::infinity()};\n\t\tauto ret = rangeprop(ch[0]);\n\t\tfor(int i=1;i<ch.size();i++)\n\t\t\tret = ret.combine(rangeprop(ch[i]),\n\t\t\t\t\t[](const range<scalarreal> &a, const range<scalarreal> &b) {\n\t\t\t\t\t\tauto v1=a.first*b.first, v2=a.second*b.second,\n\t\t\t\t\t\t\tv3 = a.first*b.second, v4=a.second*b.first;\n\t\t\t\t\t\treturn range<scalarreal>{\n\t\t\t\t\t\t\tstd::min(std::min(v1,v2),std::min(v3,v4)),\n\t\t\t\t\t\t\tstd::max(std::max(v1,v2),std::max(v3,v4))};\n\t\t\t\t\t\t\t});\n\t\treturn ret;\n\t}\n\tif (isop(e,absop)) {\n\t\treturn rangeprop(e.children()[0]).modify(\n\t\t\t\t[](const range<scalarreal> &a) {\n\t\t\t\t\tif (a.first>=0) return a;\n\t\t\t\t\tif (a.second<=0) return range<scalarreal>{-a.second,-a.first};\n\t\t\t\t\treturn range<scalarreal>{scalarreal{0},std::max(-a.first,a.second)};\n\t\t\t\t\t});\n\t}\n\tif (isop(e,powerop)) {\n\t\treturn rangeprop(e.children()[0]).combinemult(\n\t\t\t\trangeprop(e.children()[1]),\n\t\t\t\t[](const range<scalarreal> &b, const range<scalarreal> &p) {\n\t\t\t\t\tscalarset<scalarreal> ret;\n\t\t\t\t\tlimpt<scalarreal> zero(scalarreal{0});\n\t\t\t\t\tif (b.first>zero) {\n\t\t\t\t\t\tauto v1=pow(b.first,p.first),\n\t\t\t\t\t\t\tv2=pow(b.second,p.second),\n\t\t\t\t\t\t\tv3=pow(b.first,p.second),\n\t\t\t\t\t\t\tv4=pow(b.second,p.first);\n\t\t\t\t\t\tret.x.emplace(\n\t\t\t\t\t\t\tstd::min(std::min(v1,v2),std::min(v3,v4)),\n\t\t\t\t\t\t\tstd::max(std::max(v1,v2),std::max(v3,v4)));\n\t\t\t\t\t\treturn ret;\n\t\t\t\t\t}\n\t\t\t\t\tif (b.second>zero) {\n\t\t\t\t\t\tauto v1=pow(zero,p.first),\n\t\t\t\t\t\t\tv2=pow(b.second,p.second),\n\t\t\t\t\t\t\tv3=pow(zero,p.second),\n\t\t\t\t\t\t\tv4=pow(b.second,p.first);\n\t\t\t\t\t\tv1.closed = v3.closed = false;\n\t\t\t\t\t\tret.x.emplace(\n\t\t\t\t\t\t\tstd::min(std::min(v1,v2),std::min(v3,v4)),\n\t\t\t\t\t\t\tstd::max(std::max(v1,v2),std::max(v3,v4)));\n\t\t\t\t\t}\n\t\t\t\t\t// what to do with negative base???\n\t\t\t\t\tif (p.first.pt==p.second.pt) { // single exponent\n\t\t\t\t\t\tif (p.first.pt.isint()) {\n\t\t\t\t\t\t\tauto v1 = pow(zero,p.first);\n\t\t\t\t\t\t\tauto v2 = pow(b.first,p.first);\n\t\t\t\t\t\t\tret.x.emplace(v1,v2);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlimpt<scalarreal> b2 = b.second.pt>=zero ? zero :\n\t\t\t\t\t\t\t\t(b.second.pt.isint() ? b.second :\n\t\t\t\t\t\t\t\t\t(limpt<scalarreal>{\n\t\t\t\t\t\t\t\t\t\tb.first.pt.floor()}));\n\t\t\t\t\t\tlimpt<scalarreal> b1 = b2-limpt<scalarreal>{scalarreal{1}};\n\t\t\t\t\t\tif (b1>b.first) {\n\t\t\t\t\t\t\tauto v1 = pow(b2,p.first);\n\t\t\t\t\t\t\tauto v2 = pow(b1,p.first);\n\t\t\t\t\t\t\tauto v3 = pow(b2,p.second);\n\t\t\t\t\t\t\tauto v4 = pow(b1,p.second);\n\t\t\t\t\t\t\tret.x.emplace(\n\t\t\t\t\t\t\t\tstd::min(std::min(v1,v2),\n\t\t\t\t\t\t\t\t\tstd::min(v3,v4)),\n\t\t\t\t\t\t\t\tstd::max(std::max(v1,v2),\n\t\t\t\t\t\t\t\t\tstd::max(v3,v4)));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tauto v1 = pow(b2,p.first);\n\t\t\t\t\t\t\tauto v3 = pow(b2,p.second);\n\t\t\t\t\t\t\tret.x.emplace(v1,v3);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t/* not sure why this was the code... seems very wrong\n\t\t\t\t\t * p not even mentioned!\n\t\t\t\t\t */\n\t\t\t\t\t/*\n\t\t\t\t\tfor(auto ip = b.first.closed\n\t\t\t\t\t\t\t\t|| !b.first.pt.iseven() ?\n\t\t\t\t\t\t\tceil(b.first.pt/2)*2\n\t\t\t\t\t\t\t: ceil(b.first.pt/2+1)*2;\n\t\t\t\t\t\t\tip<0 && b.second>ip;ip+=2) {\n\t\t\t\t\t\tstd::cout << \"looking at \" << tostring(b.first.pt) << ' ' << tostring(b.second.pt) << ' ' << tostring(ip) << std::endl;\n\t\t\t\t\t\tret.x.emplace(\n\t\t\t\t\t\t\tb.first<=0 && b.second>=0 ?\n\t\t\t\t\t\t\t\tscalarreal{0} : pow(\n\t\t\t\t\t\t\t\t\tstd::min(abs(b.first),\n\t\t\t\t\t\t\t\t\t\tabs(b.second)),ip),\n\t\t\t\t\t\t\tpow(std::max(abs(b.first),\n\t\t\t\t\t\t\t\t\tabs(b.second)),ip));\n\t\t\t\t\t}\n\t\t\t\t\t*/\n\n\t\t\t\t});\n\t}\n\tif (isop(e,logop)) {\n\t\treturn rangeprop(e.children()[0]).modify(\n\t\t\t\t[](range<scalarreal> a) {\n\t\t\t\t\ta.first.pt = log(a.first.pt);\n\t\t\t\t\ta.second.pt = log(a.second.pt);\n\t\t\t\t\treturn a;\n\t\t\t\t\t});\n\t}\n\tif (isop(e,heavisideop)) {\n\t\treturn rangeprop(e.children()[0]).modify(\n\t\t\t\t[](const range<scalarreal> &a) {\n\t\t\t\t\treturn range<scalarreal>{a.first < 0 ? 0 : 1,\n\t\t\t\t\t\t\t\ta.second < 0 ? 0 : 1};\n\t\t\t\t\treturn a;\n\t\t\t\t});\n\t}\n\tif (isop(e,diracop)) {\n\t\treturn rangeprop(e.children()[0]).modify(\n\t\t\t\t[](const range<scalarreal> &a) {\n\t\t\t\t\treturn range<scalarreal>{scalarreal{0},\n\t\t\t\t\t\ta.overlap(range<scalarreal>(0,0)) ?\n\t\t\t\t\t\t\tstd::numeric_limits<scalarreal>::infinity()\n\t\t\t\t\t\t\t: scalarreal{0}};\n\t\t\t\t});\n\t}\n\treturn {-std::numeric_limits<scalarreal>::infinity(),\n\t\t\t\t\tstd::numeric_limits<scalarreal>::infinity()};\n}\n\n\n// perhaps these should do their own simplification first...\n\nbool ispos(const expr &e) {\n\tauto rs = rangeprop(e);\n\tif (rs.x.empty()) return false; //???\n\tfor(auto &r : rs.x)\n\t\tif (r.first<=0) return false;\n\treturn true;\n}\nbool isneg(const expr &e) {\n\tauto rs = rangeprop(e);\n\tif (rs.x.empty()) return false; //???\n\tfor(auto &r : rs.x)\n\t\tif (r.second>=0) return false;\n\treturn true;\n}\nbool isnonneg(const expr &e) {\n\tauto rs = rangeprop(e);\n\tif (rs.x.empty()) return false; //???\n\tfor(auto &r : rs.x)\n\t\tif (r.first<0) return false;\n\treturn true;\n}\nbool isnonpos(const expr &e) {\n\tauto rs = rangeprop(e);\n\tif (rs.x.empty()) return false; //???\n\tfor(auto &r : rs.x)\n\t\tif (r.second>0) return false;\n\treturn true;\n}\nbool isconst(const expr &e, scalarreal k) {\n\tauto rs = rangeprop(e);\n\tif (rs.x.empty()) return false; //???\n\tfor(auto &r : rs.x)\n\t\tif (r.first!=k || r.second!=k) return false;\n\treturn true;\n}\nbool iseven(const expr &e) {\n\tauto rs = rangeprop(e);\n\tif (rs.x.empty()) return false; //???\n\tfor(auto &r : rs.x)\n\t\tif (r.first!=r.second || !r.first.pt.iseven()) return false;\n\treturn true;\n}\nbool isodd(const expr &e) {\n\tauto rs = rangeprop(e);\n\tif (rs.x.empty()) return false; //???\n\tfor(auto &r : rs.x)\n\t\tif (r.first!=r.second || !r.first.pt.isodd()) return false;\n\treturn true;\n}\n\nstruct simpcond : public rewriterule {\n\tvirtual ruleptr clone() const { return std::make_shared<simpcond>(*this); }\n\tvirtual optional<expr> apply(const expr &e) const {\n\t\tif (!isop(e,condop) && !isop(e,condeqop)) return {};\n\t\tauto rngset = rangeprop(e.children()[0]);\n\t\tif (isop(e,condop)) {\n\t\t\tbool hasless=false, hasgreq=false;\n\t\t\tfor(auto &rng : rngset.x) {\n\t\t\t\tif (rng.first<0) {\n\t\t\t\t\thasless=true;\n\t\t\t\t\tif (hasgreq) break;\n\t\t\t\t}\n\t\t\t\tif (rng.second>=0) {\n\t\t\t\t\thasgreq=true;\n\t\t\t\t\tif (hasless) break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!hasgreq) return optional<expr>{in_place,e.children()[1]};\n\t\t\tif (!hasless) return optional<expr>{in_place,e.children()[2]};\n\t\t\treturn {};\n\t\t} else {\n\t\t\tbool hasnotzero=false, haszero=false;\n\t\t\tfor(auto &rng : rngset.x) {\n\t\t\t\tif (rng.first!=0 || rng.second!=0) {\n\t\t\t\t\thasnotzero=true;\n\t\t\t\t\tif (haszero) break;\n\t\t\t\t}\n\t\t\t\tif (rng.first<=0 && rng.second>=0) {\n\t\t\t\t\thaszero=true;\n\t\t\t\t\tif (hasnotzero) break;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!hasnotzero) return optional<expr>{in_place,e.children()[1]};\n\t\t\tif (!haszero) return optional<expr>{in_place,e.children()[2]};\n\t\t\treturn {};\n\t\t}\n\t}\n};\n\n\n/*\nstruct normswitch : public rewriterule {\n\tvirtual ruleptr clone() const { return std::make_shared<normswitch>(*this); }\n\tvirtual optional<expr> apply(const expr &e) const {\n\t\tif (!isop(e,switchop)) return {};\n\t\tauto &c0 = e.children()[0];\n\t\texpr tosub = scalar(0);\n\t\tif (c0.isleaf()) {\n\t\t\tif (!isconst(c0) || getconst<scalarreal>(c0)==0)\n\t\t\t\treturn {};\n\t\t\ttosub = c0;\n\t\t} else {\n\t\t\tif (!isop(c0,pluschain) || c0.children().empty()\n\t\t\t\t\t|| !isconst(c0.children()[0])\n\t\t\t\t\t|| getconst<scalarreal>(c0.children()[0])==0)\n\t\t\t\treturn {};\n\t\t\ttosub = c0.children()[0];\n\t\t}\n\t\tstd::vector<expr> newch(e.children());\n\t\tfor (int i=0;i<newch.size();i+=2)\n\t\t\tnewch[i] = newch[i] - tosub;\n\t\treturn optional<expr>{in_place,e.asnode(),newch};\n\t}\n};\n\nstruct liftswitch : public rewriterule {\n\tvirtual ruleptr clone() const { return std::make_shared<liftswitch>(*this); }\n\tstatic expr replacech(const expr &e, int chi, const expr &ch) {\n\t\tauto &ech = e.children();\n\t\tstd::vector<expr> newch;\n\t\tnewch.reserve(ech.size());\n\t\tfor(int i=0;i<ech.size();i++)\n\t\t\tif (i==chi) newch.emplace_back(ch);\n\t\t\telse newch.emplace_back(ech[i]);\n\t\treturn {e.asnode(),newch};\n\t}\n\n\tvirtual optional<expr> apply(const expr &e) const {\n\t\tif (e.isleaf() || e.asnode()==switchop) return {};\n\t\tauto &ch = e.children();\n\t\tfor(int i=0;i<ch.size();i++)\n\t\t\tif (isop(ch[i],switchop)) {\n\t\t\t\tauto &sch = ch[i].children();\n\t\t\t\tstd::vector<expr> newch;\n\t\t\t\tfor(int j=0;j<sch.size();j+=2) {\n\t\t\t\t\tnewch.emplace_back(sch[j]);\n\t\t\t\t\tnewch.emplace_back(replacech(e,i,sch[j+1]));\n\t\t\t\t}\n\t\t\t\treturn optional<expr>{in_place,switchop,newch};\n\t\t\t}\n\t\treturn {};\n\t}\n};\n\nstruct squeezeswitch : public rewriterule {\n\tvirtual ruleptr clone() const { return std::make_shared<squeezeswitch>(*this); }\n\tvirtual optional<expr> apply(expr &e) const {\n\t\tif (!isop(e,switchop)) return {};\n\t\tauto &ch = e.children();\n\t\tif (ch.size()<5) {\n\t\t\tif (ch[1]==ch[3]) // technically, this might expand\n\t\t\t\t// the domain (if ch[0] is undefined in places)\n\t\t\t\treturn optional<expr>{in_place,ch[1]};\n\t\t\treturn {};\n\t\t}\n\t\tfor(int i=2;i<ch.size()-1;i+=2)\n\t\t\tif (ch[i-1]==ch[i+1]) {\n\t\t\t\tstd::vector<expr> newch;\n\t\t\t\tnewch.reserve(ch.size()-2);\n\t\t\t\tfor(int j=0;j<i;j++) newch.emplace_back(ch[j]);\n\t\t\t\tfor(int j=i+2;j<ch.size();j++) newch.emplace_back(ch[j]);\n\t\t\t\treturn optional<expr>{in_place,e.asnode(),newch};\n\t\t\t}\n\t\treturn {};\n\t}\n};\n\n\nstruct mergeswitch : public rewriterule {\n\tvirtual ruleptr clone() const { return std::make_shared<mergeswitch>(*this); }\n\tstatic bool ismergeable(const expr &e, const expr &te, bool checkte=true) {\n\t\tif (!isop(e,switchop)) return false;\n\t\tauto &ch = e.children();\n\t\tif (checkte && !(ch[0]==te)) return false;\n\t\tscalarreal lastk = 0;\n\t\tfor(int i=2;i<ch.size();i+=2) {\n\t\t\tif (!isconst(ch[i])) return false;\n\t\t\tif (i>2) {\n\t\t\t\tscalarreal newk = getconst<scalarreal>(ch[i]);\n\t\t\t\tif (newk<lastk) return false;\n\t\t\t\tlastk = newk;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tvirtual optional<expr> apply(expr &e) const {\n\t\tif (!ismergeable(e,e,false)) return {};\n\t\tauto &ch = e.children();\n\t\tint mchi = -1;\n\t\tscalarreal preth = -std::numeric_limits<scalarreal>::infinity();\n\t\tscalarreal postth = std::numeric_limits<scalarreal>::infinity();\n\t\tfor(int i=1;i<ch.size();i+=2)\n\t\t\tif (ismergeable(ch[i],ch[0])) {\n\t\t\t\tmchi = i;\n\t\t\t\tif (i>1) preth = getconst<scalarreal>(ch[i-1]);\n\t\t\t\tif (i+1 < ch.size()) postth = getconst<scalarreal>(ch[i+1]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\tif (mchi==-1) return {};\n\n\t\tauto &mch = ch[mchi].children();\n\t\tstd::vector<expr> newch;\n\t\tfor(int i=0;i<mchi;i++)\n\t\t\tnewch.emplace_back(ch[i]);\n\t\tnewch.reserve(ch.size()+mch.size()-2);\n\t\tfor(int i=1;i<mch.size();i+=2) {\n\t\t\tscalarreal th = (i+1<mch.size() ? getconst<scalarreal>(mch[i+1])\n\t\t\t\t\t\t\t: std::numeric_limits<scalarreal>::infinity());\n\t\t\tif (th > preth) {\n\t\t\t\tnewch.emplace_back(mch[i]);\n\t\t\t\tif (th < postth && i+1<mch.size()) newch.emplace_back(mch[i+1]);\n\t\t\t\telse break;\n\t\t\t}\n\t\t}\n\t\tfor(int i=mchi+1;i<ch.size();i++)\n\t\t\tnewch.emplace_back(ch[i]);\n\t\treturn optional<expr>{in_place,e.asnode(),newch};\n\t}\n};\n*/\n\nruleptr SRR(const expr &s, const expr &p) {\n\treturn SR(chainpatternmod(s),p);\n}\n\ntemplate<typename F>\nruleptr SRR(const expr &s, const expr &p, F &&f) {\n\treturn SR(chainpatternmod(s),p,std::forward<F>(f));\n}\n\ntemplate<typename T>\nstruct bigopexpand : public rewriterule {\n\tvirtual ruleptr clone() const { return std::make_shared<bigopexpand>(*this); }\n\tint nterms;\n\top bigop, chainop;\n\tT id;\n\n\tbigopexpand(int n, op bop, op cop, T i) : nterms(n), bigop(bop), chainop(cop), id(i) {}\n\n\tvirtual optional<expr> apply(const expr &e) const {\n\t\tif (!isop(e,bigop)) return {};\n\t\tauto &ch = e.children();\n\t\tif (!isconst(ch[2]) || !isconst(ch[3])) return {};\n\t\tscalarreal x0 = getconst<scalarreal>(ch[2]);\n\t\tscalarreal x1 = getconst<scalarreal>(ch[3]);\n\t\tif (x1 < x0) return optional<expr>{in_place,scalar(id)};\n\t\tif (x1 >= x0+nterms) return {};\n\t\tstd::vector<expr> terms;\n\t\tfor(scalarreal x=x0;x<=x1;x+=1)\n\t\t\tterms.emplace_back(substitute(ch[1],ch[0],scalar(x)));\n\t\treturn optional<expr>{in_place,chainop,terms};\n\t}\n};\n\nexpr x_ = newvar<scalarreal>(\"x_\");\nexpr notx_{makematchleaf<matchconstwrt>(vset{{getvar(x_)}})};\nexpr k1_ = L(1,notx_);\nexpr k2_ = L(2,notx_);\nexpr k3_ = L(3,notx_);\nexpr k4_ = L(4,notx_);\nexpr k5_ = L(5,notx_);\nexpr k6_ = L(6,notx_);\nexpr k7_ = L(7,notx_);\nexpr k8_ = L(8,notx_);\nexpr k9_ = L(9,notx_);\n\nstruct tableintegrate : public rewriterule {\n\tvirtual ruleptr clone() const { return std::make_shared<tableintegrate>(*this); }\n\tstd::vector<std::pair<expr,expr>> antiderivs;\n\n\ttableintegrate(std::vector<std::pair<expr,expr>> ader)\n\t\t\t: antiderivs(std::move(ader)) {}\n\n\tvirtual optional<expr> apply(const expr &e) const {\n\t\tif (!isop(e,integrateop)) return {};\n\t\tauto &ch = e.children();\n\t\texpr newint = substitute(ch[1],ch[0],x_);\n\t\tfor(auto &ad : antiderivs) {\n\t\t\tauto res = match(newint,ad.first);\n\t\t\tif (res) {\n\t\t\t\texpr ader = substitute(ad.second,*res);\n\t\t\t\texpr ret = substitute(ader,x_,ch[3])\n\t\t\t\t\t- substitute(ader,x_,ch[2]);\n\t\t\t\treturn optional<expr>{in_place,std::move(ret)};\n\t\t\t}\n\t\t}\n\t\treturn {};\n\t}\n};\n\ntemplate<typename E1, typename E2>\nstd::pair<expr,expr> ADR(E1 &&e, E2 &&ad) {\n\treturn std::make_pair(chainpatternmod(std::forward<E1>(e)),\n\t\t\tstd::forward<E2>(ad));\n}\n\nstd::vector<std::pair<expr,expr>> stdantiderivs\n\t{{\n\t\t ADR(  k1_,              \n\t            P1_*x_   ),\n\n\t\t ADR(  x_,\n\t\t       x_*x_/2   ),\n\n\t\t // TODO:\n\t\t // when k1_<0 this doesn't work if the integral goes over the pole (@ x_=0)\n\t\t // similar problem with the other rational function antiderivatives below!\n\t\t ADR(  pow(x_,k1_),\n\t\t\t  ifeqthenelse(P1_+1,log(abs(x_)),pow(x_,P1_+1)/(P1_+1))   ),\n\n\t\t ADR(  pow(x_ + k2_,k3_),\n\t\t\t  ifeqthenelse(P3_+1, log(abs(x_+P2_)),\n\t\t\t\t\t\t\tpow(x_+P2_,P3_+1)/(P3_+1))),\n\n\t\t ADR(  pow(k1_*x_ + k2_,k3_),\n\t\t\t  ifeqthenelse(P1_,pow(P2_,P3_)*x_,\n\t\t\t\t  ifeqthenelse(P3_+1, log(abs(P1_*x_+P2_))/P1_,\n\t\t\t\t\t  \t\t\tpow(P1_*x_+P2_,P3_+1)/(P3_+1)/P1_))),\n\n\t\t // added to make example in proposal work... needs to be\n\t\t // more general\n\t\t ADR(  pow(k1_,k2_*x_),\n\t\t\t\t ifeqthenelse(P2_,x_,\n\t\t\t\t\t pow(P1_,P2_*x_)/(P2_*log(P1_)))),\n\n\t }};\n\n// all of the next few \"helpers\" should perhaps be moved elsewhere\n// they may also need to be made more efficient and perhaps given\n// their own algebraic symbols to be reasonable about directly\n// (for instance, we probably don't want to be evaluating \"factorial\"\n//  or \"choose\" directly)\nexpr factorial(const expr &n) {\n\texpr i = newvar<scalarreal>(); \n\treturn prod(i,i,scalar(1),n);\n}\n\nexpr nchoosek(const expr &n, const expr k) {\n\treturn factorial(n)/(factorial(k)*factorial(n-k));\n}\n\nexpr B0(const expr &m) {\n\texpr k=newvar<scalarreal>(), v=newvar<scalarreal>();\n\n\t// pos series\n\t//return sum(sum(pow(scalar(-1),v)*nchoosek(k,v)*pow(v+1,m)/(k+1),v,scalar(0),k),k,scalar(0),m);\n\t// neg series\n\treturn sum(sum(pow(scalar(-1),v)*nchoosek(k,v)*pow(v,m)/(k+1),v,scalar(0),k),k,scalar(0),m);\n}\n\n// Bernoulli polynomial\nexpr B(const expr &n, const expr &m) {\n\texpr k = newvar<scalarreal>();\n\treturn sum(nchoosek(n,k)*B0(n-k)*pow(m,k),k,scalar(0),n);\n}\n\nexpr psum(const expr &p, const expr &n) {\n\texpr k = newvar<scalarreal>();\n\treturn sum(nchoosek(p,k)*B0(p-k)*pow(-1,p-k)/(k+1)*pow(n,k+1),k,scalar(0),p);\n}\n\n// TODO:  will need to be separated out into general and specific to scalars\n//std::vector<ruleptr>\n\nruleset basicscalarrules\n\t{{toptr<trivialconsteval>(),\n\t  toptr<scopeeval>(),\n\t  toptr<sortchildren>(std::vector<op>{pluschain,multiplieschain}),\n\n  SRR(E1_ - E2_                          ,  P1_ + -1*P2_                   ),\n  SRR(-E1_                               ,  -1*P1_                         ),\n\n  SRR(E1_ / E2_                          ,  P1_ * pow(P2_,-1)              ),\n\n  /*\n  SRR(E1_ + (E2_ + E3_)                  ,  P1_ + P2_ + P3_                  ),\n  SRR( E1_ + (E2_ + E3_) + E4_           ,  P1_ + P2_ + P3_ + P4_            ),\n\n  SRR(E1_ * (E2_ * E3_)                  ,  P1_ * P2_ * P3_                  ),\n  SRR( E1_ * (E2_ * E3_) * E4_           ,  P1_ * P2_ * P3_ * P4_            ),\n  */\n  toptr<collapsechain>(pluschain,true),\n  toptr<collapsechain>(multiplieschain,true),\n  toptr<constchaineval>(pluschain),\n  toptr<constchaineval>(multiplieschain),\n  toptr<simpcond>(),\n  /*\n  toptr<normswitch>(),\n  toptr<mergeswitch>(),\n  toptr<squeezeswitch>(),\n  toptr<liftswitch>(),\n  */\n\n  // some of these are only true \"almost everywhere\"\n  // and might need to be removed for some applications\n  // (or, we need a \"domain\" to be propagated with the expr)\n  //\n  SRR( 0 + E1_                          ,  P1_                             ),\n  SRR( -0 + E1_                          ,  P1_                             ),\n  SRR( 1 * E1_                          ,  P1_                             ),\n  SRR( 0 * E1_                          ,  scalar(0)                   ),\n  SRR( -0 * E1_                          ,  scalar(0)                   ),\n  SRR( pow(E1_,1)                       ,  P1_                             ),\n  SRR( pow(1,E1_)                       ,  scalar(1)                   ),\n  SRR( pow(0,E1_)                       ,  ifthenelse(P1_,\n\t\t\t\tscalar(std::numeric_limits<scalarreal>::infinity()),\n\t\t\t\tscalar(0))                                           ),\n  SRR( pow(E1_,0)                       ,  scalar(1)                   ),\n\n  SRR( E1_ + E1_                          ,  2*P1_                           ),\n  SRR( E1_ + E1_ + E2_                    ,  2*P1_ + P2_                     ),\n\n  SRR( E1_ * E1_                          ,  pow(P1_,2)                    ),\n  SRR( E1_ * E1_ * E2_                    ,  pow(P1_,2)*P2_                ),\n\n  SRR( log(pow(E1_,E2_))                  ,  P2_*log(P1_)                    ),\n  SRR( log(E1_*E2_)                       ,  log(P1_) + log(P2_)             ),\n\n  SRR( (W2_ + W3_)*E1_                    ,  P1_*P2_ + P1_*P3_               ),\n  SRR( (K2_ + W3_)*E1_                    ,  P1_*P2_ + P1_*P3_               ),\n  SRR( (W2_ + K3_)*E1_                    ,  P1_*P2_ + P1_*P3_               ),\n\n  SRR( K1_*E2_ + K3_*E2_                  ,  (P1_+P3_) * P2_                 ),\n  SRR( K1_*E2_ + K3_*E2_ + E4_            ,  (P1_+P3_) * P2_ + P4_           ),\n  SRR( E2_ + K3_*E2_                      ,  (scalar(1)+P3_) * P2_       ),\n  SRR( E2_ + K3_*E2_ + E4_                ,  (scalar(1)+P3_) * P2_ + P4_ ),\n\n  SRR( pow(E1_,E2_) * pow(E1_,E3_)        ,  pow(P1_,P2_+P3_)                ),\n  SRR( pow(E1_,E2_) * pow(E1_,E3_) * E4_  ,  pow(P1_,P2_+P3_)*P4_            ),\n  SRR( E1_ * pow(E1_,E3_)                 ,  pow(P1_,scalar(1)+P3_)      ),\n  SRR( E1_ * pow(E1_,E3_) * E4_           ,  pow(P1_,scalar(1)+P3_)*P4_  ),\n\n  SRR( pow(pow(W1_,E2_),E3_)              ,  pow(P1_,P2_*P3_)                ),\n  SRR( pow(pow(K1_,W2_),W3_)              ,  pow(P1_,P2_*P3_)                ),\n  SRR( pow(pow(K1_,W2_),K3_)              ,  pow(pow(P1_,P3_),P2_)           ),\n  SRR( pow(K1_,K2_*E3_)                   ,  pow(pow(P1_,P2_),P3_)           ),\n\n  SRR( pow(E1_*W2_,E3_)                   ,  pow(P1_,P3_)*pow(P2_,P3_)       ),\n  SRR( pow(W1_*E2_,E3_)                   ,  pow(P1_,P3_)*pow(P2_,P3_)       ),\n  SRR( pow(K1_,E3_)*pow(K2_,E3_)          ,  pow(P1_*P2_,P3_)                ),\n\n\n  SRR( log(ifthenelse(E1_,E2_,E3_))    ,  ifthenelse(P1_,log(P2_),log(P3_))  ),\n\n  SRR( abs(E1_)                           ,  P1_ ,\n   [](const exprmap &m) { return isnonneg(m.at(1)); } ),\n\n  SRR( abs(E1_)                           ,  -P1_ ,\n   [](const exprmap &m) { return isnonpos(m.at(1)); } ),\n\t }};\n\nruleset derivscalarrules{{\n  SRR( deriv(E1_,V2_,V3_)                 ,  scalar(0),\n      [](const exprmap &m) { return isconstexpr(m.at(1),getvar(m.at(2))); }),\n  SRR( deriv(V1_,V1_,V3_)                 ,  scalar(1)                   ),\n\n  SRR( deriv(E1_+E2_,V3_,V4_)             ,\n\t\t                           deriv(P1_,P3_,P4_) + deriv(P2_,P3_,P4_) ),\n\n  SRR( deriv(E1_*E2_,V3_,V4_)             ,\n\t\t     deriv(P1_,P3_,P4_)*evalat(P2_,P3_,P4_)\n\t\t  + evalat(P1_,P3_,P4_)* deriv(P2_,P3_,P4_)                        ),\n\n  SRR( deriv(pow(E1_,E2_),V3_,V4_)        ,\n\t  evalat(pow(P1_,P2_),P3_,P4_)*evalat(log(P1_),P3_,P4_)*deriv(P2_,P3_,P4_)\n   + evalat(P2_,P3_,P4_)*evalat(pow(P1_,P2_-1),P3_,P4_)*deriv(P1_,P3_,P4_) ),\n\n  SRR( deriv(log(E1_),V2_,V3_)            ,\n\t\t                          deriv(P1_,P2_,P3_) / evalat(P1_,P2_,P3_) ),\n\n  SRR( deriv(abs(E1_),V2_,V3_)            ,\n\t\t  deriv(P1_,P2_,P3_)*ifthenelse(P1_,scalar(-1),scalar(1)) ),\n\n  SRR( deriv(expr{heavisideop,E1_},V2_,V3_),\n\t\t\t\t evalat(expr{diracop,P1_},P2_,P3_)*deriv(P1_,P2_,P3_) ),\n\n  // not sure this is right with diracop\n  SRR( deriv(ifthenelse(E1_,E2_,E3_),V4_,V5_)   ,\n\t\t  evalat(expr{diracop,P1_},P4_,P5_)*deriv(P1_,P4_,P5_)*(E2_-E3_)\n\t\t  + ifthenelse(P1_,deriv(P2_,P4_,P5_),deriv(P3_,P4_,P5_))           ),\n\n  SRR( deriv(ifeqthenelse(E1_,E2_,E3_),V4_,V5_)  ,\n\t\t  ifeqthenelse(evalat(P1_,P4_,P5_),\n\t\t\t  deriv(P2_,P4_,P5_),deriv(P3_,P4_,P5_))                       ),\n\n  SRR( deriv(integrate(E1_,E2_,E3_,E4_),E5_,E6_)  ,\n\t\t  integrate(deriv(P1_,P5_,P6_),P2_,\n\t\t\t\t\tevalat(P3_,P5_,P6_),evalat(P4_,P5_,P6_))\n\t\t  + deriv(P4_,P5_,P6_)*evalat(evalat(P1_,P2_,P4_),P5_,P6_)\n\t\t  - deriv(P3_,P5_,P6_)*evalat(evalat(P1_,P2_,P3_),P5_,P6_)          ),\n}};\n\nruleset integralscalarrules {{\n  SRR( integrate(E1_+E2_,E3_,E4_,E5_), integrate(P1_,P3_,P4_,P5_) + integrate(P2_,P3_,P4_,P5_) ),\n\n  SRR( integrate(E1_*E2_,E3_,E4_,E5_), P1_ * integrate(P2_,P3_,P4_,P5_) ,\n  \t\t[](const exprmap &m) { return isconstexpr(m.at(1),getvar(m.at(3))); } ),\n\n  SRR( integrate(E1_*E2_,E3_,E4_,E5_), integrate(P1_,P3_,P4_,P5_) * P2_ ,\n  \t\t[](const exprmap &m) { return isconstexpr(m.at(2),getvar(m.at(3))); } ),\n\n  SRR( integrate(ifthenelse(E1_+E2_*E3_,E4_,E5_),E3_,E6_,E7_) ,\n\t\t  ifthenelse(-P1_/P2_ - P6_,\n\t\t\t  \t\tintegrate(P5_,P3_,P6_,P7_),\n\t\t\t\t\tifthenelse(-P1_/P2_ - P7_,\n\t\t\t\t\t\tintegrate(P5_,P3_,P6_,-P1_/P2_)\n\t\t\t\t\t\t+ integrate(P4_,P3_,-P1_/P2_,P7_),\n\t\t\t\t\t\tintegrate(P4_,P3_,P6_,P7_))),\n\t\t  [](const exprmap &m) { \n\t\t  \treturn isconstexpr(m.at(1),getvar(m.at(3)))\n\t\t\t\t\t&& isconstexpr(m.at(2),getvar(m.at(3))); } ),\n\n  toptr<tableintegrate>(stdantiderivs),\n\n  SRR( sum(E1_,V2_,E3_,E4_)               , scalar(0),\n\t\t  [](const exprmap &m) { return isneg(E4_-E3_); } ),\n  SRR( prod(E1_,V2_,E3_,E4_)               , scalar(1),\n\t\t  [](const exprmap &m) { return isneg(E4_-E3_); } ),\n\n  // perhaps need \"max(0,P4_-P3_+1)\"??\n  SRR( sum(E1_,V2_,E3_,E4_)               , P1_*(P4_-P3_+1),\n      [](const exprmap &m) { return isconstexpr(m.at(1),getvar(m.at(2))); }   ),\n\n  SRR( sum(E1_*E2_,V3_,E4_,E5_)           , P1_*sum(P2_,P3_,P4_,P5_),\n\t [](const exprmap &m) { return isconstexpr(m.at(1),getvar(m.at(3))); }   ),\n  SRR( sum(E1_*E2_,V3_,E4_,E5_)           , sum(P1_,P3_,P4_,P5_)*P2_,\n\t [](const exprmap &m) { return isconstexpr(m.at(2),getvar(m.at(3))); }   ),\n}};\n\nruleset sumprodscalarrules {{\n  toptr<bigopexpand<scalarreal>>(3,sumop,pluschain,0),\n  toptr<bigopexpand<scalarreal>>(3,prodop,multiplieschain,1),\n\n  SRR( sum(V2_,V2_,E3_,E4_)      , ifthenelse(P4_-P3_,scalar(0),(P4_+1-P3_)*(P4_+P3_)/2)                  ),\n  SRR( sum((V2_+E1_),V2_,E3_,E4_) , ifthenelse(P4_-P3_,scalar(0),(P4_+1-P3_)*(P4_+P3_+2*P1_)/2)              ,\n\t  [](const exprmap &m) { return isconstexpr(m.at(1),getvar(m.at(2))); } ),\n\n  SRR( sum(pow(V2_,2),V2_,E3_,E4_)  \n\t  , ifthenelse(P4_-P3_,scalar(0),scalarreal{1,6}*(P4_-P3_+1) + scalarreal{1,2}*(pow(P4_,2)-pow(P3_-1,2))\n\t  \t\t+ scalarreal{1,3}*(pow(P4_,3)-pow(P3_-1,3)))                   ),\n  SRR( sum(pow(V2_+E1_,2),V2_,E3_,E4_)  \n\t  , ifthenelse(P4_-P3_,scalar(0),scalarreal{1,6}*(P4_-P3_+1) + scalarreal{1,2}*(pow(P4_,2)-pow(P3_-1,2))\n\t  \t\t+ scalarreal{1,3}*(pow(P4_,3)-pow(P3_-1,3))\n\t\t\t+ pow(P1_,2)*(P4_-P3_) + P1_*(pow(P4_,2)-pow(P3_,2))          ),\n\t  [](const exprmap &m) { return isconstexpr(m.at(1),getvar(m.at(2))); } ),\n\n  // Faulhaber's formula\n  SRR( sum(pow(V1_,E2_),V1_,E3_,E4_)      ,\n\t//\t \t\t\t(B(P2_+1,P4_+1) - B(P2_+1,P3_+1))/(P2_+1) ,\n\t\tifthenelse(P4_-P3_,scalar(0),psum(P2_,P4_) - psum(P2_,P3_-1)),\n  \t[](const exprmap &m) { return isconstexpr(m.at(2),getvar(m.at(1))); }   ),\n  SRR( sum(pow((V1_+E5_),E2_),V1_,E3_,E4_)      ,\n\t//\t \t\t\t(B(P2_+1,P4_+1) - B(P2_+1,P3_+1))/(P2_+1) ,\n\t\tifthenelse(P4_-P3_,scalar(0),psum(P2_,P4_+P5_) - psum(P2_,P3_+P5_-1)),\n  \t[](const exprmap &m) { return isconstexpr(m.at(2),getvar(m.at(1)))\n\t\t\t\t&& isconstexpr(m.at(5),getvar(m.at(1))); }   ),\n}};\n\nruleset numericevalrules {{\n\t\t  toptr<consteval>(),\n\t }};\n\nruleset scalarruleset = basicscalarrules\n\t\t\t+ derivscalarrules\n\t\t\t+ integralscalarrules\n\t\t\t+ sumprodscalarrules\n\t\t\t+ numericevalrules;\n#endif\n", "meta": {"hexsha": "a9a12d3ec4e48c18a3505dce11d6a9aa80a54d49", "size": 28262, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "scalarrewrite.hpp", "max_stars_repo_name": "cshelton/tqscas", "max_stars_repo_head_hexsha": "404fc79993571fe0c844bfca964eec5484e3b307", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scalarrewrite.hpp", "max_issues_repo_name": "cshelton/tqscas", "max_issues_repo_head_hexsha": "404fc79993571fe0c844bfca964eec5484e3b307", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scalarrewrite.hpp", "max_forks_repo_name": "cshelton/tqscas", "max_forks_repo_head_hexsha": "404fc79993571fe0c844bfca964eec5484e3b307", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3278301887, "max_line_length": 125, "alphanum_fraction": 0.5703418017, "num_tokens": 9926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.4475332806088169}}
{"text": "#include <iomanip>\n#include <Eigen/Dense>\n#include <Exception.hh>\n#include \"HartreeFock.hh\"\n#include \"HFConverger.hh\"\n#include \"exceptions.hh\"\n\nconst int HartreeFock::default_max_iter = 100;\nconst double HartreeFock::default_tolerance = 1.e-10;\n\nHartreeFock::HartreeFock(): _max_iter(default_max_iter),\n\t_tolerance(default_tolerance), _conv_method(\"diis\"),  _status(),\n\t_orbitals(), _orb_ener(), _density() {}\n\nHartreeFock::HartreeFock(const Basis& basis, const Geometry& geometry,\n\tint multiplicity, bool restricted): _max_iter(default_max_iter),\n\t_tolerance(default_tolerance), _conv_method(\"diis\"), _status(),\n\t_orbitals(), _orb_ener(), _density()\n{\n\titerate(basis, geometry, multiplicity, restricted);\n}\n\nvoid HartreeFock::iterate(const Basis& basis, const Geometry& geometry,\n\tint multiplicity, bool restricted)\n{\n\t_status.reset();\n\t_restricted = restricted;\n\tsetMultiplicity(geometry, multiplicity);\n\n\tdouble nuc_rep = geometry.nuclearRepulsion();\n\tstd::cout << \"nuclear repulsion = \" << nuc_rep << \"\\n\";\n\n\tEigen::MatrixXd H = basis.kineticEnergy()\n\t\t+ basis.nuclearAttraction(geometry.positions(), geometry.charges());\n\tconst Eigen::MatrixXd& S = basis.overlap();\n\n\tif (restricted)\n\t\titerateRestricted(basis, H, S, nuc_rep);\n\telse\n\t\titerateUnrestricted(basis, H, S, nuc_rep);\n}\n\nvoid HartreeFock::iterateRestricted(const Basis& basis,\n\tconst Eigen::MatrixXd& H, const Eigen::MatrixXd& S,\n\tdouble nuc_rep)\n{\n\tcalcOrbitals(H, S);\n\n\t_energy = nuc_rep;\n\tif (_nr_double > 0) _energy += 2 * _orb_ener.head(_nr_double).sum();\n\tif (_nr_single > 0) _energy += _orb_ener.segment(_nr_double, _nr_single).sum();\n\tstd::cout << \"Energy: \" << _energy << \"\\n\";\n\n\tEigen::MatrixXd J, K;\n\tHFConverger::Ptr converger = HFConverger::create(_conv_method, *this,\n\t\tbasis);\n\tfor (int iter = 0; iter < _max_iter; ++iter)\n\t{\n\t\tdouble last_energy = _energy;\n\t\t\n\t\tconst Eigen::MatrixXd& D = density();\n\t\tbasis.twoElectron(D, J, K);\n\t\t_energy = (H + 0.5*(J - 0.5*K)).cwiseProduct(D).sum() + nuc_rep;\n\t\tstd::cout << std::setw(3) << iter << \" \"\n\t\t\t<< std::setw(20) << std::setprecision(15) << std::fixed << _energy << \" \"\n\t\t\t<< std::setw(13) << std::setprecision(6) << std::scientific << converger->error()\n\t\t\t<< \"\\n\";\n\t\t//std::cout << \"orbital energies: \" << _orb_ener.transpose() << \"\\n\";\n\n\t\tif (std::abs(_energy - last_energy) < _tolerance)\n\t\t{\n\t\t\t_status.set(ENERGY_CONVERGED);\n\t\t\treturn;\n\t\t}\n\n\t\tEigen::MatrixXd F = H + J - 0.5*K;\n\t\tconverger->step(F, _energy);\n\t\tcalcOrbitals(F, S);\n\t}\n\t\n\tthrow NoConvergence();\n}\n\nvoid HartreeFock::iterateUnrestricted(const Basis& basis,\n\tconst Eigen::MatrixXd& H, const Eigen::MatrixXd& S,\n\tdouble nuc_rep)\n{\n\tint nr_func = basis.size();\n\n\tcalcOrbitals(H, H, S);\t\n\t_energy = nuc_rep + _orb_ener.head(_nr_alpha).sum()\n\t\t+ _orb_ener.segment(nr_func, _nr_beta).sum();\n\tstd::cout << \"Energy: \" << _energy << \"\\n\";\n\n\tEigen::MatrixXd Ja, Ka, Jb, Kb;\n\tHFConverger::Ptr converger = HFConverger::create(_conv_method, *this,\n\t\tbasis);\n\tfor (int iter = 0; iter < _max_iter; ++iter)\n\t{\n\t\tdouble last_energy = _energy;\n\n\t\tEigen::MatrixXd::ConstColsBlockXpr Da = density().leftCols(nr_func);\n\t\tEigen::MatrixXd::ConstColsBlockXpr Db = density().rightCols(nr_func);\n\t\tbasis.twoElectron(Da, Ja, Ka);\n\t\tbasis.twoElectron(Db, Jb, Kb);\n\n\t\tdouble energyA = (H + 0.5*(Ja+Jb-Ka)).cwiseProduct(Da).sum();\n\t\tdouble energyB = (H + 0.5*(Ja+Jb-Kb)).cwiseProduct(Db).sum();\n\t\t_energy = energyA + energyB + nuc_rep;\n\n\t\tstd::cout << std::setw(3) << iter << \" \"\n\t\t\t<< std::setw(20) << std::setprecision(15) << std::fixed << _energy << \" \"\n\t\t\t<< std::setw(13) << std::setprecision(6) << std::scientific << converger->error() << \"\\n\";\n\t\t//std::cout << \"orbital energies: \" << _orb_ener.transpose() << \"\\n\";\n\n\t\tif (std::abs(_energy - last_energy) < _tolerance)\n\t\t{\n\t\t\t_status.set(ENERGY_CONVERGED);\n\t\t\treturn;\n\t\t}\n\n\t\tEigen::MatrixXd Fa = H + Ja + Jb - Ka;\n\t\tEigen::MatrixXd Fb = H + Ja + Jb - Kb;\n\t\tconverger->step(Fa, Fb, _energy);\n\t\tcalcOrbitals(Fa, Fb, S);\n\t}\n\n\tthrow NoConvergence();\n}\n\ndouble HartreeFock::energy()\n{\n\treturn _energy;\n}\n\nvoid HartreeFock::setMultiplicity(const Geometry& geometry, int multiplicity)\n{\n\tint nr_elec = geometry.totalCharge();\n\n\tif (multiplicity < 1)\n\t\t// Use lowest possible spin multiplicity\n\t\tmultiplicity = 1 + nr_elec % 2;\n\telse if (nr_elec % 2 == multiplicity % 2 || multiplicity > nr_elec+1)\n\t\tthrow Li::Exception(\"Multiplicity does not match number of electrons\");\n\n\t_nr_single = multiplicity - 1;\n\t_nr_double = (nr_elec - _nr_single) / 2;\n\tif (!_restricted)\n\t{\n\t\t_nr_alpha = _nr_double + _nr_single;\n\t\t_nr_beta = _nr_double;\n\t}\n}\n\nvoid HartreeFock::calcDensity()\n{\n\tif (!_status.test(ORBITALS_CURRENT))\n\t\tthrow Li::Exception(\"No orbitals to compute density matrix with\");\n\n\tint nr_func = _orbitals.rows();\n\tif (_restricted)\n\t{\n\t\t_density.resize(nr_func, nr_func);\n\t\tfor (int j = 0; j < nr_func; j++)\n\t\t{\n\t\t\tfor (int i = 0; i <= j; i++)\n\t\t\t{\n\t\t\t\tdouble sum = 0.0;\n\t\t\t\tif (_nr_double)\n\t\t\t\t\tsum += 2 * _orbitals.row(i).head(_nr_double).dot(\n\t\t\t\t\t\t_orbitals.row(j).head(_nr_double));\n\t\t\t\tif (_nr_single)\n\t\t\t\t\tsum += _orbitals.row(i).segment(_nr_double, _nr_single).dot(\n\t\t\t\t\t\t_orbitals.row(j).segment(_nr_double, _nr_single));\n\t\t\t\t_density(j,i) = _density(i,j) = sum;\n\t\t\t}\n\t\t}\n        }\n        else\n\t{\n\t\t_density.resize(nr_func, 2*nr_func);\n\t\tif (_nr_alpha == 0)\n\t\t{\n\t\t\t_density.leftCols(nr_func).setZero();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tEigen::MatrixXd::ColsBlockXpr occ\n\t\t\t\t= _orbitals.leftCols(_nr_alpha);\n\t\t\t_density.leftCols(nr_func) = occ * occ.transpose();\n\t\t}\n\t\tif (_nr_beta == 0)\n\t\t{\n\t\t\t_density.rightCols(nr_func).setZero();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tEigen::Block<Eigen::MatrixXd> occ\n\t\t\t\t= _orbitals.block(0, nr_func, nr_func, _nr_beta);\n\t\t\t_density.rightCols(nr_func) = occ * occ.transpose();\n\t\t}\n\t}\n\n\t_status.set(DENSITY_CURRENT);\n}\n\nvoid HartreeFock::calcOrbitals(const Eigen::MatrixXd& F,\n\tconst Eigen::MatrixXd& S)\n{\n\tEigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> solver(F, S);\n\t_orbitals = solver.eigenvectors();\n\t_orb_ener = solver.eigenvalues();\n\t_status.set(ORBITALS_CURRENT);\n\t_status.reset(DENSITY_CURRENT);\n}\n\nvoid HartreeFock::calcOrbitals(const Eigen::MatrixXd& Fa,\n\tconst Eigen::MatrixXd& Fb, const Eigen::MatrixXd& S)\n{\n\tint nr_func = S.rows();\n\t_orbitals.resize(nr_func, 2*nr_func);\n\t_orb_ener.resize(2*nr_func);\n\n\tEigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> solver(Fa, S);\n\t_orbitals.leftCols(nr_func) = solver.eigenvectors();\n\t_orb_ener.head(nr_func) = solver.eigenvalues();\n\tsolver.compute(Fb, S);\n\t_orbitals.rightCols(nr_func) = solver.eigenvectors();\n\t_orb_ener.tail(nr_func) = solver.eigenvalues();\n\n\t_status.set(ORBITALS_CURRENT);\n\t_status.reset(DENSITY_CURRENT);\n}", "meta": {"hexsha": "3288dfb4e667c131d115c55bfc0515015fb28798", "size": 6628, "ext": "cc", "lang": "C++", "max_stars_repo_path": "HartreeFock.cc", "max_stars_repo_name": "gvissers/quill2", "max_stars_repo_head_hexsha": "589d7bc3ce20da888547f8f4f6b8da908b3d63a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HartreeFock.cc", "max_issues_repo_name": "gvissers/quill2", "max_issues_repo_head_hexsha": "589d7bc3ce20da888547f8f4f6b8da908b3d63a5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HartreeFock.cc", "max_forks_repo_name": "gvissers/quill2", "max_forks_repo_head_hexsha": "589d7bc3ce20da888547f8f4f6b8da908b3d63a5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4463519313, "max_line_length": 93, "alphanum_fraction": 0.6789378395, "num_tokens": 2090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370421, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4475101827237891}}
{"text": "/*\n * BSD 2-Clause License\n *\n * Copyright (c) 2020, Christoph Neuhauser\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n *   list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n *   this list of conditions and the following disclaimer in the documentation\n *   and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <cstdio>\n#include <iostream>\n\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/algorithm/string/case_conv.hpp>\n\n#include <Utils/File/Logfile.hpp>\n#include <Utils/File/LineReader.hpp>\n\n#include \"Utils/TriangleNormals.hpp\"\n#include \"StressTrajectoriesDatLoader.hpp\"\n\n#ifdef USE_EIGEN\n#include <Eigen/Eigenvalues>\n\nvoid computePrincipalStresses(\n        float xx, float yy, float zz, float xy, float yz, float zx,\n        float& majorStress, float& mediumStress, float& minorStress/*,\n        glm::vec3& v0, glm::vec3& v1, glm::vec3& v2*/) {\n    Eigen::Matrix3f stressTensor;\n    stressTensor.row(0) << xx, xy, zx;\n    stressTensor.row(1) << xy, yy, yz;\n    stressTensor.row(2) << zx, yz, zz;\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> selfAdjointEigenSolver;\n    selfAdjointEigenSolver.compute(stressTensor);\n    Eigen::Vector3f eigenvalues = selfAdjointEigenSolver.eigenvalues();\n    /*Eigen::Matrix3f eigenvectors = selfAdjointEigenSolver.eigenvectors();\n    v0 = glm::vec3(eigenvectors(0, 0), eigenvectors(1, 0), eigenvectors(2, 0));\n    v1 = glm::vec3(eigenvectors(0, 1), eigenvectors(1, 1), eigenvectors(2, 1));\n    v2 = glm::vec3(eigenvectors(0, 2), eigenvectors(1, 2), eigenvectors(2, 2));*/\n\n    minorStress = eigenvalues(0);\n    mediumStress = eigenvalues(1);\n    majorStress = eigenvalues(2);\n}\n\nfloat computeDegeneracyMeasure(float sigma1, float sigma2, float sigma3) {\n    float degeneracyMeasure = 0.5f * std::abs((sigma1 - sigma2) / (sigma1 + sigma2));\n    degeneracyMeasure = std::min(degeneracyMeasure, 0.5f * std::abs((sigma3 - sigma2) / (sigma3 + sigma2)));\n    return degeneracyMeasure;\n}\n#endif\n\nvoid loadStressLineHierarchyFromDat(\n        const std::vector<std::string>& filenamesHierarchy,\n        std::vector<StressTrajectoriesData>& stressTrajectoriesDataPs) {\n    size_t psIdx = 0;\n    for (size_t fileIdx = 0; fileIdx < filenamesHierarchy.size(); fileIdx++) {\n        const std::string& filename = filenamesHierarchy.at(fileIdx);\n\n        sgl::LineReader lineReader(filename);\n        while (lineReader.isLineLeft()) {\n            assert(psIdx < stressTrajectoriesDataPs.size());\n            StressTrajectoriesData& stressTrajectoriesData = stressTrajectoriesDataPs.at(psIdx);\n            std::vector<std::string> linesInfo = lineReader.readVectorLine<std::string>();\n            // Line metadata saved?\n            uint32_t numLines = 0;\n            if (linesInfo.size() == 1) {\n                numLines = sgl::fromString<uint32_t>(linesInfo.at(0));\n            } else if (linesInfo.size() == 2) {\n                numLines = sgl::fromString<uint32_t>(linesInfo.at(1));\n            } else {\n                sgl::Logfile::get()->writeError(\n                        std::string() + \"ERROR in loadStressLineHierarchyFromDat: Invalid line metadata in file \\\"\"\n                        + filename + \"\\\".\");\n            }\n            assert(stressTrajectoriesData.size() == numLines);\n            for (uint32_t lineIdx = 0; lineIdx < numLines; lineIdx++) {\n                StressTrajectoryData& stressTrajectoryData = stressTrajectoriesData.at(lineIdx);\n                float lineHierarchyLevel = lineReader.readScalarLine<float>();\n                stressTrajectoryData.hierarchyLevels.push_back(lineHierarchyLevel);\n            }\n\n            psIdx++;\n        }\n    }\n}\n\nvoid loadStressTrajectoriesFromDat_v1(\n        const std::vector<std::string>& filenamesTrajectories,\n        const std::vector<std::string>& filenamesHierarchy,\n        std::vector<int>& loadedPsIndices,\n        std::vector<Trajectories>& trajectoriesPs,\n        std::vector<StressTrajectoriesData>& stressTrajectoriesDataPs) {\n    trajectoriesPs.reserve(filenamesTrajectories.size());\n    stressTrajectoriesDataPs.reserve(filenamesTrajectories.size());\n    size_t geometryByteSize = 0;\n\n    size_t psIdx = 0;\n    for (size_t fileIdx = 0; fileIdx < filenamesTrajectories.size(); fileIdx++) {\n        const std::string& filename = filenamesTrajectories.at(fileIdx);\n\n        sgl::LineReader lineReader(filename);\n        while (lineReader.isLineLeft()) {\n            Trajectories trajectories;\n            StressTrajectoriesData stressTrajectoriesData;\n            std::vector<std::string> linesInfo = lineReader.readVectorLine<std::string>();\n            // Line metadata saved?\n            uint32_t numLines = 0;\n            if (linesInfo.size() == 1) {\n                numLines = sgl::fromString<uint32_t>(linesInfo.at(0));\n            } else if (linesInfo.size() == 2) {\n                numLines = sgl::fromString<uint32_t>(linesInfo.at(1));\n                boost::algorithm::to_lower(linesInfo.at(0));\n                if (boost::ends_with(linesInfo.at(0), \"major\")) {\n                    loadedPsIndices.push_back(0);\n                } else if (boost::ends_with(linesInfo.at(0), \"medium\")) {\n                    loadedPsIndices.push_back(1);\n                } else if (boost::ends_with(linesInfo.at(0), \"minor\")) {\n                    loadedPsIndices.push_back(2);\n                } else {\n                    sgl::Logfile::get()->writeError(\n                            std::string() + \"ERROR in loadStressTrajectoriesFromDat_: \"\n                            + \"Invalid principal stress identifier \\\"\" + linesInfo.at(0) + \"\\\".\");\n                }\n            } else {\n                sgl::Logfile::get()->writeError(\n                        std::string() + \"ERROR in loadStressTrajectoriesFromDat_v1: Invalid line metadata in file \\\"\"\n                        + filename + \"\\\".\");\n            }\n            trajectories.resize(numLines);\n            stressTrajectoriesData.resize(numLines);\n            for (uint32_t lineIdx = 0; lineIdx < numLines; lineIdx++) {\n                Trajectory& trajectory = trajectories.at(lineIdx);\n                StressTrajectoryData& stressTrajectoryData = stressTrajectoriesData.at(lineIdx);\n\n                uint32_t lineLength = lineReader.readScalarLine<uint32_t>();\n                trajectory.positions.reserve(lineLength);\n                stressTrajectoryData.majorPs.reserve(lineLength);\n                stressTrajectoryData.mediumPs.reserve(lineLength);\n                stressTrajectoryData.minorPs.reserve(lineLength);\n                stressTrajectoryData.majorPsDir.reserve(lineLength);\n                stressTrajectoryData.mediumPsDir.reserve(lineLength);\n                stressTrajectoryData.minorPsDir.reserve(lineLength);\n                trajectory.attributes.resize(2);\n                trajectory.attributes.front().reserve(lineLength);\n                std::vector<float> positionData = lineReader.readVectorLine<float>(lineLength * 3);\n                std::vector<float> psData = lineReader.readVectorLine<float>(lineLength * 12);\n                std::vector<float> vonMisesData = lineReader.readVectorLine<float>(lineLength);\n\n                for (uint32_t pointIdx = 0; pointIdx < lineLength; pointIdx++) {\n                    trajectory.positions.push_back(glm::vec3(\n                            positionData.at(pointIdx * 3),\n                            positionData.at(pointIdx * 3 + 1),\n                            positionData.at(pointIdx * 3 + 2)));\n                    stressTrajectoryData.majorPs.push_back(psData.at(pointIdx * 12));\n                    stressTrajectoryData.majorPsDir.push_back(glm::vec3(\n                            psData.at(pointIdx * 12 + 1),\n                            psData.at(pointIdx * 12 + 2),\n                            psData.at(pointIdx * 12 + 3)));\n                    stressTrajectoryData.mediumPs.push_back(psData.at(pointIdx * 12 + 4));\n                    stressTrajectoryData.mediumPsDir.push_back(glm::vec3(\n                            psData.at(pointIdx * 12 + 5),\n                            psData.at(pointIdx * 12 + 6),\n                            psData.at(pointIdx * 12 + 7)));\n                    stressTrajectoryData.minorPs.push_back(psData.at(pointIdx * 12 + 8));\n                    stressTrajectoryData.minorPsDir.push_back(glm::vec3(\n                            psData.at(pointIdx * 12 + 9),\n                            psData.at(pointIdx * 12 + 10),\n                            psData.at(pointIdx * 12 + 11)));\n                    trajectory.attributes.at(0).push_back(vonMisesData.at(pointIdx));\n                    if (psIdx == 0) {\n                        trajectory.attributes.at(1).push_back(std::abs(stressTrajectoryData.majorPs.back()));\n                    } else if (psIdx == 1) {\n                        trajectory.attributes.at(1).push_back(std::abs(stressTrajectoryData.mediumPs.back()));\n                    } else {\n                        trajectory.attributes.at(1).push_back(std::abs(stressTrajectoryData.minorPs.back()));\n                    }\n                }\n            }\n\n            for (size_t trajectoryIdx = 0; trajectoryIdx < trajectories.size(); trajectoryIdx++) {\n                Trajectory& trajectory = trajectories.at(trajectoryIdx);\n                StressTrajectoryData& stressTrajectoryData = stressTrajectoriesData.at(trajectoryIdx);\n                geometryByteSize += trajectory.positions.size() * sizeof(float) * 3;\n                geometryByteSize += sizeof(float); // hierarchy level\n                geometryByteSize += stressTrajectoryData.majorPs.size() * sizeof(float);\n                geometryByteSize += stressTrajectoryData.mediumPs.size() * sizeof(float);\n                geometryByteSize += stressTrajectoryData.minorPs.size() * sizeof(float);\n                geometryByteSize += stressTrajectoryData.majorPsDir.size() * sizeof(float) * 3;\n                geometryByteSize += stressTrajectoryData.mediumPsDir.size() * sizeof(float) * 3;\n                geometryByteSize += stressTrajectoryData.minorPsDir.size() * sizeof(float) * 3;\n                for (const std::vector<float>& attributes : trajectory.attributes) {\n                    geometryByteSize += attributes.size() * sizeof(float);\n                }\n            }\n\n            trajectoriesPs.emplace_back(trajectories);\n            stressTrajectoriesDataPs.emplace_back(stressTrajectoriesData);\n            psIdx++;\n        }\n    }\n\n    // Check if there's additional line hierarchy data.\n    if (filenamesHierarchy.size() > 0) {\n        loadStressLineHierarchyFromDat(filenamesHierarchy, stressTrajectoriesDataPs);\n    }\n\n    // Assume that all three PS directions are provided for the v1 .dat format.\n    if (loadedPsIndices.size() == 0 && trajectoriesPs.size() == 3) {\n        loadedPsIndices = {0, 1, 2};\n    }\n\n    std::cout << \"Size of line geometry data (MiB): \" << (geometryByteSize / (1024.0 * 1024.0)) << std::endl;\n}\n\nvoid loadStressTrajectoriesFromDat_v2(\n        const std::vector<std::string>& filenamesTrajectories,\n        std::vector<int>& loadedPsIndices,\n        std::vector<Trajectories>& trajectoriesPs,\n        std::vector<StressTrajectoriesData>& stressTrajectoriesDataPs,\n        std::vector<std::vector<std::vector<glm::vec3>>>& bandPointsListLeftPs,\n        std::vector<std::vector<std::vector<glm::vec3>>>& bandPointsListRightPs) {\n    trajectoriesPs.reserve(filenamesTrajectories.size());\n    stressTrajectoriesDataPs.reserve(filenamesTrajectories.size());\n    bandPointsListLeftPs.reserve(filenamesTrajectories.size());\n    bandPointsListRightPs.reserve(filenamesTrajectories.size());\n    size_t geometryByteSize = 0;\n\n    size_t psIdx = 0;\n    for (size_t fileIdx = 0; fileIdx < filenamesTrajectories.size(); fileIdx++) {\n        const std::string& filename = filenamesTrajectories.at(fileIdx);\n\n        sgl::LineReader lineReader(filename);\n        while (lineReader.isLineLeft()) {\n            Trajectories trajectories;\n            StressTrajectoriesData stressTrajectoriesData;\n            std::vector<std::vector<glm::vec3>> bandPointsListLeft;\n            std::vector<std::vector<glm::vec3>> bandPointsListRight;\n            std::vector<std::string> linesInfo = lineReader.readVectorLine<std::string>();\n            // Line metadata saved?\n            uint32_t numLines = 0;\n            if (linesInfo.size() == 1) {\n                numLines = sgl::fromString<uint32_t>(linesInfo.at(0));\n            } else if (linesInfo.size() == 2) {\n                boost::algorithm::to_lower(linesInfo.at(0));\n                if (boost::ends_with(linesInfo.at(0), \"major\")) {\n                    loadedPsIndices.push_back(0);\n                } else if (boost::ends_with(linesInfo.at(0), \"medium\")) {\n                    loadedPsIndices.push_back(1);\n                } else if (boost::ends_with(linesInfo.at(0), \"minor\")) {\n                    loadedPsIndices.push_back(2);\n                } else {\n                    sgl::Logfile::get()->writeError(\n                            std::string() + \"ERROR in loadStressTrajectoriesFromDat_v2: \"\n                            + \"Invalid principal stress identifier \\\"\" + linesInfo.at(0) + \"\\\".\");\n                }\n                numLines = sgl::fromString<uint32_t>(linesInfo.at(1));\n            } else {\n                sgl::Logfile::get()->writeError(\n                        std::string() + \"ERROR in loadStressTrajectoriesFromDat_v2: \"\n                        + \"Invalid line metadata in file \\\"\" + filename + \"\\\".\");\n            }\n            trajectories.resize(numLines);\n            stressTrajectoriesData.resize(numLines);\n            bandPointsListLeft.resize(numLines);\n            bandPointsListRight.resize(numLines);\n            for (uint32_t lineIdx = 0; lineIdx < numLines; lineIdx++) {\n                Trajectory& trajectory = trajectories.at(lineIdx);\n                StressTrajectoryData& stressTrajectoryData = stressTrajectoriesData.at(lineIdx);\n                std::vector<glm::vec3>& bandPointsLeft = bandPointsListLeft.at(lineIdx);\n                std::vector<glm::vec3>& bandPointsRight = bandPointsListRight.at(lineIdx);\n\n                std::vector<std::string> firstLineVector = lineReader.readVectorLine<std::string>();\n                if (firstLineVector.size() != 2) {\n                    sgl::Logfile::get()->writeError(\n                            std::string() + \"ERROR in loadStressTrajectoriesFromDat_v2: \"\n                            + \"Invalid per line metadata in file \\\"\" + filename + \"\\\".\");\n                }\n                uint32_t lineLength = sgl::fromString<uint32_t>(firstLineVector.at(0));\n                float hierarchyLevel = sgl::fromString<float>(firstLineVector.at(1));\n                stressTrajectoryData.hierarchyLevels.push_back(hierarchyLevel);\n                trajectory.positions.reserve(lineLength);\n                trajectory.attributes.resize(1);\n                trajectory.attributes.front().reserve(lineLength);\n                bandPointsLeft.reserve(lineLength);\n                bandPointsRight.reserve(lineLength);\n                std::vector<float> positionData = lineReader.readVectorLine<float>(lineLength * 3);\n                std::vector<float> bandVertexData = lineReader.readVectorLine<float>(lineLength * 6);\n                std::vector<float> scalarFieldData = lineReader.readVectorLine<float>(lineLength);\n\n                for (uint32_t pointIdx = 0; pointIdx < lineLength; pointIdx++) {\n                    trajectory.positions.push_back(glm::vec3(\n                            positionData.at(pointIdx * 3),\n                            positionData.at(pointIdx * 3 + 1),\n                            positionData.at(pointIdx * 3 + 2)));\n                    bandPointsLeft.push_back(glm::vec3(\n                            bandVertexData.at(pointIdx * 6 + 0),\n                            bandVertexData.at(pointIdx * 6 + 1),\n                            bandVertexData.at(pointIdx * 6 + 2)));\n                    bandPointsRight.push_back(glm::vec3(\n                            bandVertexData.at(pointIdx * 6 + 3),\n                            bandVertexData.at(pointIdx * 6 + 4),\n                            bandVertexData.at(pointIdx * 6 + 5)));\n                    trajectory.attributes.at(0).push_back(scalarFieldData.at(pointIdx));\n                }\n            }\n\n            for (size_t trajectoryIdx = 0; trajectoryIdx < trajectories.size(); trajectoryIdx++) {\n                Trajectory& trajectory = trajectories.at(trajectoryIdx);\n                StressTrajectoryData& stressTrajectoryData = stressTrajectoriesData.at(trajectoryIdx);\n                geometryByteSize += trajectory.positions.size() * sizeof(float) * 3;\n                geometryByteSize += sizeof(float); // hierarchy level\n                geometryByteSize += stressTrajectoryData.majorPs.size() * sizeof(float);\n                geometryByteSize += stressTrajectoryData.mediumPs.size() * sizeof(float);\n                geometryByteSize += stressTrajectoryData.minorPs.size() * sizeof(float);\n                geometryByteSize += stressTrajectoryData.majorPsDir.size() * sizeof(float) * 3;\n                geometryByteSize += stressTrajectoryData.mediumPsDir.size() * sizeof(float) * 3;\n                geometryByteSize += stressTrajectoryData.minorPsDir.size() * sizeof(float) * 3;\n                for (const std::vector<float>& attributes : trajectory.attributes) {\n                    geometryByteSize += attributes.size() * sizeof(float);\n                }\n                geometryByteSize += bandPointsListLeft.at(trajectoryIdx).size() * sizeof(float) * 3;\n                geometryByteSize += bandPointsListRight.at(trajectoryIdx).size() * sizeof(float) * 3;\n            }\n\n            trajectoriesPs.emplace_back(trajectories);\n            stressTrajectoriesDataPs.emplace_back(stressTrajectoriesData);\n            bandPointsListLeftPs.emplace_back(bandPointsListLeft);\n            bandPointsListRightPs.emplace_back(bandPointsListRight);\n            psIdx++;\n        }\n    }\n\n    std::cout << \"Size of line geometry data (MiB): \" << (geometryByteSize / (1024.0 * 1024.0)) << std::endl;\n}\n\n\n\nvoid parseOutlineMeshHull(\n        sgl::LineReader& lineReader,\n        std::vector<uint32_t>& simulationMeshOutlineTriangleIndices,\n        std::vector<glm::vec3>& simulationMeshOutlineVertexPositions) {\n    std::vector<std::string> numVerticesLine = lineReader.readVectorLine<std::string>();\n    if (numVerticesLine.size() != 2 || numVerticesLine.front() != \"#Vertices\") {\n        sgl::Logfile::get()->writeError(\"Error in parseOutlineMeshHull: Invalid vertex information.\");\n    }\n    uint32_t numVertices = sgl::fromString<uint32_t>(numVerticesLine.at(1));\n    for (uint32_t vertexIdx = 0; vertexIdx < numVertices; vertexIdx++) {\n        std::vector<float> vertexPosition = lineReader.readVectorLine<float>(3);\n        assert(vertexPosition.size() == 3);\n        simulationMeshOutlineVertexPositions.push_back(\n                glm::vec3(vertexPosition.at(0), vertexPosition.at(1), vertexPosition.at(2)));\n    }\n\n    std::vector<std::string> numFacesLine = lineReader.readVectorLine<std::string>();\n    if (numFacesLine.size() != 2 || numFacesLine.front() != \"#Faces\") {\n        sgl::Logfile::get()->writeError(\"Error in parseOutlineMeshHull: Invalid face information.\");\n    }\n    uint32_t numFaces = sgl::fromString<uint32_t>(numFacesLine.at(1));\n    for (uint32_t faceIdx = 0; faceIdx < numFaces; faceIdx++) {\n        std::vector<uint32_t> faceIndices = lineReader.readVectorLine<uint32_t>(4);\n        assert(faceIndices.size() == 4);\n\n        simulationMeshOutlineTriangleIndices.push_back(faceIndices.at(0));\n        simulationMeshOutlineTriangleIndices.push_back(faceIndices.at(1));\n        simulationMeshOutlineTriangleIndices.push_back(faceIndices.at(2));\n\n        simulationMeshOutlineTriangleIndices.push_back(faceIndices.at(0));\n        simulationMeshOutlineTriangleIndices.push_back(faceIndices.at(2));\n        simulationMeshOutlineTriangleIndices.push_back(faceIndices.at(3));\n    }\n}\n\nvoid loadStressTrajectoriesFromDat_v3(\n        const std::vector<std::string>& filenamesTrajectories,\n        std::vector<int>& loadedPsIndices, MeshType& meshType,\n        std::vector<Trajectories>& trajectoriesPs,\n        std::vector<StressTrajectoriesData>& stressTrajectoriesDataPs,\n        std::vector<std::vector<std::vector<glm::vec3>>>& bandPointsUnsmoothedListLeftPs,\n        std::vector<std::vector<std::vector<glm::vec3>>>& bandPointsUnsmoothedListRightPs,\n        std::vector<std::vector<std::vector<glm::vec3>>>& bandPointsSmoothedListLeftPs,\n        std::vector<std::vector<std::vector<glm::vec3>>>& bandPointsSmoothedListRightPs,\n        std::vector<uint32_t>& simulationMeshOutlineTriangleIndices,\n        std::vector<glm::vec3>& simulationMeshOutlineVertexPositions) {\n    trajectoriesPs.reserve(filenamesTrajectories.size());\n    stressTrajectoriesDataPs.reserve(filenamesTrajectories.size());\n    bandPointsUnsmoothedListLeftPs.reserve(filenamesTrajectories.size());\n    bandPointsUnsmoothedListRightPs.reserve(filenamesTrajectories.size());\n    bandPointsSmoothedListLeftPs.reserve(filenamesTrajectories.size());\n    bandPointsSmoothedListRightPs.reserve(filenamesTrajectories.size());\n    size_t geometryByteSize = 0;\n\n    size_t psIdx = 0;\n    for (size_t fileIdx = 0; fileIdx < filenamesTrajectories.size(); fileIdx++) {\n        const std::string& filename = filenamesTrajectories.at(fileIdx);\n\n        sgl::LineReader lineReader(filename);\n        while (lineReader.isLineLeft()) {\n            Trajectories trajectories;\n            StressTrajectoriesData stressTrajectoriesData;\n            std::vector<std::vector<glm::vec3>> bandPointsUnsmoothedListLeft;\n            std::vector<std::vector<glm::vec3>> bandPointsUnsmoothedListRight;\n            std::vector<std::vector<glm::vec3>> bandPointsSmoothedListLeft;\n            std::vector<std::vector<glm::vec3>> bandPointsSmoothedListRight;\n            std::vector<std::string> linesInfo = lineReader.readVectorLine<std::string>();\n\n            if (linesInfo.front() == \"#Outline\") {\n                if (linesInfo.size() == 1) {\n                    meshType = MeshType::CARTESIAN;\n                } else {\n                    if (linesInfo.at(1) == \"Cartesian\") {\n                        meshType = MeshType::CARTESIAN;\n                    } else {\n                        meshType = MeshType::UNSTRUCTURED;\n                    }\n                }\n                parseOutlineMeshHull(\n                        lineReader, simulationMeshOutlineTriangleIndices, simulationMeshOutlineVertexPositions);\n                continue;\n            }\n\n            // Line metadata saved?\n            uint32_t numLines = 0;\n            if (linesInfo.size() == 1) {\n                numLines = sgl::fromString<uint32_t>(linesInfo.at(0));\n                if (numLines == 0) {\n                    continue;\n                }\n            } else if (linesInfo.size() == 2) {\n                numLines = sgl::fromString<uint32_t>(linesInfo.at(1));\n                if (numLines == 0) {\n                    continue;\n                }\n                boost::algorithm::to_lower(linesInfo.at(0));\n                if (boost::ends_with(linesInfo.at(0), \"major\")) {\n                    loadedPsIndices.push_back(0);\n                } else if (boost::ends_with(linesInfo.at(0), \"medium\")) {\n                    loadedPsIndices.push_back(1);\n                } else if (boost::ends_with(linesInfo.at(0), \"minor\")) {\n                    loadedPsIndices.push_back(2);\n                } else {\n                    sgl::Logfile::get()->writeError(\n                            std::string() + \"ERROR in loadStressTrajectoriesFromDat_v2: \"\n                            + \"Invalid principal stress identifier \\\"\" + linesInfo.at(0) + \"\\\".\");\n                }\n            } else {\n                sgl::Logfile::get()->writeError(\n                        std::string() + \"ERROR in loadStressTrajectoriesFromDat_v2: \"\n                        + \"Invalid line metadata in file \\\"\" + filename + \"\\\".\");\n            }\n            trajectories.resize(numLines);\n            stressTrajectoriesData.resize(numLines);\n            bandPointsUnsmoothedListLeft.resize(numLines);\n            bandPointsUnsmoothedListRight.resize(numLines);\n            bandPointsSmoothedListLeft.resize(numLines);\n            bandPointsSmoothedListRight.resize(numLines);\n            for (uint32_t lineIdx = 0; lineIdx < numLines; lineIdx++) {\n                Trajectory& trajectory = trajectories.at(lineIdx);\n                StressTrajectoryData& stressTrajectoryData = stressTrajectoriesData.at(lineIdx);\n                std::vector<glm::vec3>& bandPointsUnsmoothedLeft = bandPointsUnsmoothedListLeft.at(lineIdx);\n                std::vector<glm::vec3>& bandPointsUnsmoothedRight = bandPointsUnsmoothedListRight.at(lineIdx);\n                std::vector<glm::vec3>& bandPointsSmoothedLeft = bandPointsSmoothedListLeft.at(lineIdx);\n                std::vector<glm::vec3>& bandPointsSmoothedRight = bandPointsSmoothedListRight.at(lineIdx);\n\n                std::vector<std::string> firstLineVector = lineReader.readVectorLine<std::string>();\n                if (firstLineVector.size() == 0) {\n                    sgl::Logfile::get()->writeError(\n                            std::string() + \"ERROR in loadStressTrajectoriesFromDat_v2: \"\n                            + \"Invalid per line metadata in file \\\"\" + filename + \"\\\".\");\n                }\n                uint32_t lineLength = sgl::fromString<uint32_t>(firstLineVector.at(0));\n\n                // Add the hierarchy levels.\n                for (int hierarchyIdx = 1; hierarchyIdx < std::max(int(firstLineVector.size()), 5); hierarchyIdx++) {\n                    float hierarchyLevel = sgl::fromString<float>(firstLineVector.at(hierarchyIdx));\n                    stressTrajectoryData.hierarchyLevels.push_back(hierarchyLevel);\n                }\n                if (firstLineVector.size() == 9) {\n                    stressTrajectoryData.appearanceOrder = sgl::fromString<int>(firstLineVector.at(5)) - 1;\n                    stressTrajectoryData.seedPosition = glm::vec3(\n                            sgl::fromString<float>(firstLineVector.at(6)),\n                            sgl::fromString<float>(firstLineVector.at(7)),\n                            sgl::fromString<float>(firstLineVector.at(8)));\n                }\n\n                trajectory.positions.reserve(lineLength);\n                bandPointsUnsmoothedLeft.reserve(lineLength);\n                bandPointsUnsmoothedRight.reserve(lineLength);\n                bandPointsSmoothedLeft.reserve(lineLength);\n                bandPointsSmoothedRight.reserve(lineLength);\n                std::vector<float> positionData = lineReader.readVectorLine<float>(\n                        lineLength * 3);\n                std::vector<float> bandVertexDataUnsmoothed = lineReader.readVectorLine<float>(\n                        lineLength * 6);\n                std::vector<float> bandVertexDataSmoothed = lineReader.readVectorLine<float>(\n                        lineLength * 6);\n\n                for (uint32_t pointIdx = 0; pointIdx < lineLength; pointIdx++) {\n                    trajectory.positions.emplace_back(\n                            positionData.at(pointIdx * 3),\n                            positionData.at(pointIdx * 3 + 1),\n                            positionData.at(pointIdx * 3 + 2));\n                    bandPointsUnsmoothedLeft.emplace_back(\n                            bandVertexDataUnsmoothed.at(pointIdx * 6 + 0),\n                            bandVertexDataUnsmoothed.at(pointIdx * 6 + 1),\n                            bandVertexDataUnsmoothed.at(pointIdx * 6 + 2));\n                    bandPointsUnsmoothedRight.emplace_back(\n                            bandVertexDataUnsmoothed.at(pointIdx * 6 + 3),\n                            bandVertexDataUnsmoothed.at(pointIdx * 6 + 4),\n                            bandVertexDataUnsmoothed.at(pointIdx * 6 + 5));\n                    bandPointsSmoothedLeft.emplace_back(\n                            bandVertexDataSmoothed.at(pointIdx * 6 + 0),\n                            bandVertexDataSmoothed.at(pointIdx * 6 + 1),\n                            bandVertexDataSmoothed.at(pointIdx * 6 + 2));\n                    bandPointsSmoothedRight.emplace_back(\n                            bandVertexDataSmoothed.at(pointIdx * 6 + 3),\n                            bandVertexDataSmoothed.at(pointIdx * 6 + 4),\n                            bandVertexDataSmoothed.at(pointIdx * 6 + 5));\n                }\n\n#ifdef USE_EIGEN\n                trajectory.attributes.resize(13);\n#else\n                trajectory.attributes.resize(9);\n#endif\n\n                // Principal stress.\n                trajectory.attributes.at(0).reserve(lineLength);\n                std::vector<float> scalarFieldData = lineReader.readVectorLine<float>(lineLength);\n                for (uint32_t pointIdx = 0; pointIdx < lineLength; pointIdx++) {\n                    trajectory.attributes.at(0).push_back(scalarFieldData.at(pointIdx));\n                }\n\n                // Principal stress magnitude.\n                for (uint32_t pointIdx = 0; pointIdx < lineLength; pointIdx++) {\n                    trajectory.attributes.at(1).push_back(std::abs(scalarFieldData.at(pointIdx)));\n                }\n\n                // Von Mises stress, normal stress (xx), normal stress (yy), normal stress (zz), shear stress (yz),\n                // shear stress (zx), shear stress (xy).\n                for (int varIdx = 2; varIdx < 9; varIdx++) {\n                    trajectory.attributes.at(varIdx).reserve(lineLength);\n                    std::vector<float> scalarFieldData = lineReader.readVectorLine<float>(lineLength);\n                    for (uint32_t pointIdx = 0; pointIdx < lineLength; pointIdx++) {\n                        trajectory.attributes.at(varIdx).push_back(scalarFieldData.at(pointIdx));\n                    }\n                }\n\n#ifdef USE_EIGEN\n                int xxIdx = 3;\n                int yyIdx = 4;\n                int zzIdx = 5;\n                int xyIdx = 8;\n                int yzIdx = 6;\n                int zxIdx = 7;\n\n                float majorStress, mediumStress, minorStress;\n                //glm::vec3 v0, v1, v2;\n                for (uint32_t pointIdx = 0; pointIdx < lineLength; pointIdx++) {\n                    computePrincipalStresses(\n                            trajectory.attributes.at(xxIdx).at(pointIdx),\n                            trajectory.attributes.at(yyIdx).at(pointIdx),\n                            trajectory.attributes.at(zzIdx).at(pointIdx),\n                            trajectory.attributes.at(xyIdx).at(pointIdx),\n                            trajectory.attributes.at(yzIdx).at(pointIdx),\n                            trajectory.attributes.at(zxIdx).at(pointIdx),\n                            majorStress, mediumStress, minorStress/*, v0, v1, v2*/);\n                    float degeneracyMeasure = computeDegeneracyMeasure(\n                            minorStress, mediumStress, majorStress);\n                    trajectory.attributes.at(9).push_back(majorStress);\n                    trajectory.attributes.at(10).push_back(mediumStress);\n                    trajectory.attributes.at(11).push_back(minorStress);\n                    trajectory.attributes.at(12).push_back(degeneracyMeasure);\n                }\n#endif\n            }\n\n            for (size_t trajectoryIdx = 0; trajectoryIdx < trajectories.size(); trajectoryIdx++) {\n                Trajectory& trajectory = trajectories.at(trajectoryIdx);\n                StressTrajectoryData& stressTrajectoryData = stressTrajectoriesData.at(trajectoryIdx);\n                geometryByteSize += trajectory.positions.size() * sizeof(float) * 3;\n                geometryByteSize += sizeof(float); // hierarchy level\n                geometryByteSize += stressTrajectoryData.majorPs.size() * sizeof(float);\n                geometryByteSize += stressTrajectoryData.mediumPs.size() * sizeof(float);\n                geometryByteSize += stressTrajectoryData.minorPs.size() * sizeof(float);\n                geometryByteSize += stressTrajectoryData.majorPsDir.size() * sizeof(float) * 3;\n                geometryByteSize += stressTrajectoryData.mediumPsDir.size() * sizeof(float) * 3;\n                geometryByteSize += stressTrajectoryData.minorPsDir.size() * sizeof(float) * 3;\n                for (const std::vector<float>& attributes : trajectory.attributes) {\n                    geometryByteSize += attributes.size() * sizeof(float);\n                }\n                geometryByteSize += bandPointsUnsmoothedListLeft.at(trajectoryIdx).size() * sizeof(float) * 3;\n                geometryByteSize += bandPointsUnsmoothedListRight.at(trajectoryIdx).size() * sizeof(float) * 3;\n                geometryByteSize += bandPointsSmoothedListLeft.at(trajectoryIdx).size() * sizeof(float) * 3;\n                geometryByteSize += bandPointsSmoothedListRight.at(trajectoryIdx).size() * sizeof(float) * 3;\n            }\n\n            trajectoriesPs.emplace_back(trajectories);\n            stressTrajectoriesDataPs.emplace_back(stressTrajectoriesData);\n            bandPointsUnsmoothedListLeftPs.emplace_back(bandPointsUnsmoothedListLeft);\n            bandPointsUnsmoothedListRightPs.emplace_back(bandPointsUnsmoothedListRight);\n            bandPointsSmoothedListLeftPs.emplace_back(bandPointsSmoothedListLeft);\n            bandPointsSmoothedListRightPs.emplace_back(bandPointsSmoothedListRight);\n            psIdx++;\n        }\n    }\n\n    std::cout << \"Size of line geometry data (MiB): \" << (geometryByteSize / (1024.0 * 1024.0)) << std::endl;\n}\n", "meta": {"hexsha": "17f87b65fbabf3694e3974e774d96c49070296d7", "size": 34701, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Loaders/StressTrajectoriesDatLoader.cpp", "max_stars_repo_name": "chrismile/ActionsTestRepo", "max_stars_repo_head_hexsha": "bcea39e6bf280c7c8e84ee5e0d8d9db6114d6add", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Loaders/StressTrajectoriesDatLoader.cpp", "max_issues_repo_name": "chrismile/ActionsTestRepo", "max_issues_repo_head_hexsha": "bcea39e6bf280c7c8e84ee5e0d8d9db6114d6add", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Loaders/StressTrajectoriesDatLoader.cpp", "max_forks_repo_name": "chrismile/ActionsTestRepo", "max_forks_repo_head_hexsha": "bcea39e6bf280c7c8e84ee5e0d8d9db6114d6add", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.080952381, "max_line_length": 117, "alphanum_fraction": 0.5997233509, "num_tokens": 7564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.4474650848420403}}
{"text": "// Copyright (c) 2018 by University Paris-Est Marne-la-Vallee\n// MetaData.cpp\n// This file is part of the Garamon Generator.\n// Authors: Stephane Breuils and Vincent Nozick\n// Contact: vincent.nozick@u-pem.fr\n//\n// Licence MIT\n// A a copy of the MIT License is given along with this program\n\n\n#include <math.h>\n#include <set>\n\n#include <Eigen/Eigenvalues>\n\n#include \"MetaData.hpp\"\n#include \"ConfigParser.hpp\"\n\n\nMetaData::MetaData() : dimension(0), inputMetricDiagonal(false), identityMetric(false), inputMetricPermutationOfDiagonal(false), maxDimPrecomputedProducts(256) {}\n\nMetaData::~MetaData() {}\n\nvoid MetaData::display() const {\n    std::cout << \"MetaData\" << std::endl;\n    std::cout << \"dimension         : \" << dimension << std::endl;\n    std::cout << \"namespace         : \" << namespaceName << std::endl;\n\n    std::cout << \"refinement        : \" << (useEigenRefinement==true?\"true\":\"false\") << std::endl;\n    std::cout << \"cleanup           : \" << (useNumericalCleanUp==true?\"true\":\"false\") << std::endl;\n    std::cout << \"maxDim prec func  : \" << maxDimPrecomputedProducts << std::endl;\n    std::cout << \"maxDim accessors  : \" << maxDimBasisAccessor << std::endl;\n    std::cout << \"epsilon           : \" << epsilon << std::endl;\n    std::cout << \"basis vector name : \";\n    for(unsigned int i=0; i<basisVectorName.size(); ++i)\n        std::cout << basisVectorName[i] << \" \";\n    std::cout << std::endl;\n    std::cout << \"metric            : \\n\" << metric << std::endl;\n    std::cout << \"is initialy diag  : \" << (inputMetricDiagonal==true?\"true\":\"false\") << std::endl;\n    std::cout << \"is identity       : \" << (identityMetric==true?\"true\":\"false\") << std::endl;\n    std::cout << \"is full rank      : \" << (fullRankMetric==true?\"true\":\"false\") << std::endl;\n    std::cout << \"is permutation of diagonal matrix : \" << (inputMetricPermutationOfDiagonal==true?\"true\":\"false\") << std::endl;\n    std::cout << \"diag metric       : \" << diagonalMetric.transpose() << std::endl;\n    if(!inputMetricDiagonal){\n        std::cout << \"Vector transformation matrix : \\n\" << transformationMatrix << std::endl;\n        std::cout << \"Vector inverse Transformation  : \\n\" << inverseTransformationMatrix<< std::endl;\n    }\n}\n\nbool MetaData::checkConsistency() const {\n\n    bool consistencyCheck = true;\n\n    // maxDimBasisAccessor consistency: at least for vectors\n    if(maxDimBasisAccessor == 0){\n        std::cout << \"error: at least vector accessors are required, see 'max dimension basis accessor' in the conf file.\" << std::endl;\n        consistencyCheck = false;\n    }\n\n    // dimension consistency\n    if(dimension == 0){\n        std::cout << \"error: dimension should not be 0.\" << std::endl;\n        consistencyCheck = false;\n    }\n\n    // basis vector name dimension consistency\n    if(basisVectorName.size() != dimension){\n        std::cout << \"error: 'basis vector name' size is not consistent with 'dimension'.\" << std::endl;\n        consistencyCheck = false;\n    }\n\n    // metric empty\n    bool metricDefined = true;\n    if( (metric.rows()==0) || (metric.cols()==0) ) {\n        metricDefined = false;\n        std::cout << \"error: the metric matrix is not defined.\" << std::endl;\n        consistencyCheck = false;\n    }\n\n    // metric matrix ?\n    if(metricDefined) {\n        // metric : square matrix ?\n        bool squareMatrix = true;\n        if( metric.rows() != metric.cols() ){\n            std::cout << \"error: the metric is not a square matrix.\" << std::endl;\n            consistencyCheck = false;\n            squareMatrix = false;\n        }\n\n        // metric : dimension consistency\n        if( ((unsigned int)metric.cols() != dimension) || ((unsigned int)metric.rows() != dimension) ) {\n            std::cout << \"error: the metric dimension is not consistent with 'dimension'.\" << std::endl;\n            consistencyCheck = false;\n        }\n\n        if(squareMatrix) {\n            // check if metric is symetric\n            bool symetric = true;\n            for(unsigned int i=0; i<(unsigned int)metric.rows(); ++i)\n                for(unsigned int j=i; j<(unsigned int)metric.cols(); ++j)\n                    if(fabs(metric(i,j) - metric(j,i)) > epsilon)\n                        symetric = false;\n            if (!symetric) {\n                std::cout << \"error: the metric is not a symmetric matrix.\" << std::endl;\n                consistencyCheck = false;\n            }\n        }\n    }\n\n    // check if the name of the vector basis are not ambiguous for high dimensions\n    // i.e. in dimension 15: e12 is for twelve or one-two ?\n    std::set<std::string> basis;\n\n    // represent a k-vector with a binary number (k-st bit to 1 means the k-st basis is used)\n    for(unsigned int i=1; i<=pow(2,dimension); ++i){\n\n        std::string kvector;\n        for(unsigned int k=0; k<dimension; ++k)\n            if(i & (1 << k))\n                kvector = kvector + basisVectorName[k];\n\n        if(basis.count(kvector) != 0){\n            std::cout << \"error in the basis vector name: \" << kvector << \" is ambiguous.\" << std::endl;\n            consistencyCheck = false;\n        }else{\n            basis.insert(kvector);\n        }\n    }\n\n    // namespace name compatible with C++\n    if(isalpha(namespaceName[0]) == 0){\n        std::cout << \"error in the namespace name: the first character of '\" << namespaceName << \"' should be an alphabetic letter for C++ compliance.\" << std::endl;\n        consistencyCheck = false;\n    }\n\n    return consistencyCheck;\n}\n\nMetaData::MetaData(const std::string &filename):inputMetricDiagonal(false), identityMetric(false) {\n\n    // open the parser\n    ConfigParser parser(filename);\n\n    // load all components of the meta data\n    if(!parser.readString(\"namespace\", namespaceName)) {\n        std::cerr << \"error: failed to find \" << \"namespace\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if(!parser.readUInt(\"dimension\", dimension)){\n        std::cerr << \"error: failed to find \" << \"dimension\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if(!parser.readUInt(\"max dimension precomputed products\", maxDimPrecomputedProducts)){\n        std::cerr << \"error: failed to find \" << \"max dimension precomputed products\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if(!parser.readUInt(\"max dimension basis accessor\", maxDimBasisAccessor)){\n        std::cerr << \"error: failed to find \" << \"max dimension basis accessor\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if(!parser.readStringList(\"basis vector name\", basisVectorName)){\n        std::cerr << \"error: failed to find \" << \"basis vector name\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if(!parser.readMatrix(\"metric\", metric)){\n        std::cerr << \"error: failed to find \" << \"metric\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if(!parser.readBool(\"metric decomposition refinement\", useEigenRefinement)){\n        std::cerr << \"error: failed to find \" << \"metric decomposition refinement\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if(!parser.readBool(\"metric decomposition numerical cleanup\", useNumericalCleanUp)){\n        std::cerr << \"error: failed to find \" << \"metric decomposition numerical cleanup\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if(!parser.readDouble(\"metric decomposition numerical cleanup espilon\", epsilon)){\n        std::cerr << \"error: failed to find \" << \"metric decomposition numerical cleanup espilon\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    // check the data consistency\n    if(!checkConsistency()){\n        std::cerr << \"configuration inconsistent ... abord\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n\n    // metric diagonalization\n    if(!metricDiagonalization()){\n        std::cerr << \"metric diagonalization ... failed\" << std::endl;\n        std::cerr << \"Please try again without the metric decomposition refinement or without the numerical cleanup.\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n}\n\n\nbool MetaData::metricDiagonalization() {\n\n\t// compute the metric rank\n\tif (getRank(metric) == dimension)\n\t\tfullRankMetric = true;\n\telse fullRankMetric = false;\n\n    // check if the metric is already diagonal\n    if(isMatrixDiagonal(metric, epsilon)){\n        diagonalMetric = metric.diagonal();\n        inputMetricDiagonal = true;\n        if(isMatrixIdentity(metric,epsilon))\n            identityMetric = true;\n        return true;\n    }\n\n\n    // ckeck if the metric is a permutation of a diagonal matrix (for fast dual)\n    inputMetricPermutationOfDiagonal = isMatrixPermutationOfDiagonal(metric, epsilon);\n\n    // compute the diagonalization\n    Eigen::MatrixXd diagonalMatrix;\n    eigenDecomposition(metric, transformationMatrix, diagonalMatrix);\n//    std::cout << \"metric\\n\" << metric << std::endl;\n//    std::cout << \"P\\n\" << transformationMatrix << std::endl;\n//    std::cout << \"D\\n\" << diagonalMatrix << std::endl;\n//    std::cout << \"metric ??\\n\" << transformationMatrix * diagonalMatrix * transformationMatrix.transpose() << std::endl;\n\n    // invert the transformation matrix\n    inverseTransformationMatrix = Eigen::MatrixXd(transformationMatrix.transpose());\n\n    // convert floating points to nearest integers (when possible)\n    Eigen::MatrixXd scaleMatrix = Eigen::MatrixXd::Identity(metric.rows(),metric.cols()); // refer to issue #9\n    if(useEigenRefinement)\n        scaleMatrix = eigenRefinement(transformationMatrix, diagonalMatrix, inverseTransformationMatrix);\n//    std::cout << \"metric\\n\" << metric << std::endl;\n//    std::cout << \"P\\n\" << transformationMatrix << std::endl;\n//    std::cout << \"D\\n\" << diagonalMatrix << std::endl;\n//    std::cout << \"Pinv\\n\" << inverseTransformationMatrix << std::endl;\n//    std::cout << \"metric ??\\n\" << transformationMatrix * diagonalMatrix * inverseTransformationMatrix << std::endl;\n\n\n    //numerical clean up\n    if(useNumericalCleanUp) {\n        transformationMatrix = numericalCleanUp(transformationMatrix,epsilon);\n        diagonalMatrix = numericalCleanUp(diagonalMatrix, epsilon);\n        inverseTransformationMatrix = numericalCleanUp(inverseTransformationMatrix,epsilon);\n    }\n\n    // check if the new metric is identity\n    if(isMatrixIdentity(diagonalMatrix,epsilon))\n        identityMetric = true;\n\n    // check decomposition\n    if(!checkNumericalCleanUp(metric,transformationMatrix,diagonalMatrix,inverseTransformationMatrix, epsilon))\n        return false;\n\n    // diagonal metric must be changed if we consider only inverse\n    diagonalMatrix = (scaleMatrix*scaleMatrix)*diagonalMatrix;\n    if(useNumericalCleanUp)\n        diagonalMatrix = numericalCleanUp(diagonalMatrix, epsilon);\n\n    // compact form of the diagonal matrix\n    diagonalMetric = diagonalMatrix.diagonal();\n\n    return true;\n}\n\n", "meta": {"hexsha": "ae0de3139a3a99a0550f434ea419df44825dff03", "size": 10700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MetaData.cpp", "max_stars_repo_name": "vincentnozick/garamon", "max_stars_repo_head_hexsha": "242bd064eda0e2d3847c159d46715df18747152c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T10:56:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T22:18:04.000Z", "max_issues_repo_path": "src/MetaData.cpp", "max_issues_repo_name": "vincentnozick/garamon", "max_issues_repo_head_hexsha": "242bd064eda0e2d3847c159d46715df18747152c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-04-03T08:06:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T07:01:55.000Z", "max_forks_repo_path": "src/MetaData.cpp", "max_forks_repo_name": "vincentnozick/garamon", "max_forks_repo_head_hexsha": "242bd064eda0e2d3847c159d46715df18747152c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-10-22T12:41:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-14T12:17:15.000Z", "avg_line_length": 39.1941391941, "max_line_length": 165, "alphanum_fraction": 0.6285046729, "num_tokens": 2532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.44746508484204023}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef ITL_PC_IC_0_INCLUDE\n#define ITL_PC_IC_0_INCLUDE\n\n#include <boost/mpl/bool.hpp>\n\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/linear_algebra/inverse.hpp>\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/ashape.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/operation/lower_trisolve.hpp>\n#include <boost/numeric/mtl/operation/upper_trisolve.hpp>\n#include <boost/numeric/mtl/matrix/upper.hpp>\n#include <boost/numeric/mtl/matrix/strict_lower.hpp>\n#include <boost/numeric/mtl/matrix/compressed2D.hpp>\n#include <boost/numeric/mtl/matrix/parameter.hpp>\n#include <boost/numeric/mtl/matrix/transposed_view.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n#include <boost/numeric/itl/pc/solver.hpp>\n\n\nnamespace itl { namespace pc {\n\ntemplate <typename Matrix, typename Value= typename mtl::Collection<Matrix>::value_type>\nclass ic_0\n{\n  public:\n    typedef Value                                                    value_type;\n    typedef typename mtl::Collection<Matrix>::size_type              size_type;\n    typedef ic_0                                                     self;\n\n    typedef mtl::matrix::parameters<mtl::row_major, mtl::index::c_index, mtl::non_fixed::dimensions, false, size_type> para;\n    typedef mtl::matrix::compressed2D<value_type, para>                      U_type;\n#ifndef ITL_IC_0_ONE_MATRIX\n    typedef U_type                                                   L_type;\n#else\n    typedef typename mtl::matrix::transposed_view<U_type>            L_type;\n#endif\n    typedef mtl::matrix::detail::lower_trisolve_t<L_type, mtl::tag::inverse_diagonal, true> lower_solver_t;\n    typedef mtl::matrix::detail::upper_trisolve_t<U_type, mtl::tag::inverse_diagonal, true> upper_solver_t;\n\n    ic_0(const Matrix& A) : f(A, U), L(trans(U)), lower_solver(L), upper_solver(U) {}\n\n\n    // solve x = U^* U y --> y= U^{-1} U^{-*} x\n    template <typename Vector>\n    Vector solve(const Vector& x) const\n    {\n\tmtl::vampir_trace<5036> tracer;\n\treturn inverse_upper_trisolve(U, inverse_lower_trisolve(adjoint(U), x));\n    }\n\n    // solve x = U^* y --> y0= U^{-*} x\n    template <typename VectorIn, typename VectorOut>\n    const VectorOut& solve_lower(const VectorIn& x, VectorOut&) const\n    {\n\tstatic VectorOut y0;\n\ty0.change_resource(resource(x));\n\tlower_solver(x, y0);\n\treturn y0;\n    }\n\n    // solve x = U^* U y --> y= U^{-1} U^{-*} x\n    template <typename VectorIn, typename VectorOut>\n    void solve(const VectorIn& x, VectorOut& y) const\n    {\n\tmtl::vampir_trace<5037> tracer;\n\tconst VectorOut& y0= solve_lower(x, y);\n\n\ty.checked_change_resource(x);\n\tupper_solver(y0, y);\n    }\n\n    // solve x = (LU)^* y --> y= L^{-*} U^{-*} x\n    template <typename Vector>\n    Vector adjoint_solve(const Vector& x) const\n    {\n\tmtl::vampir_trace<5044> tracer;\n\treturn solve(x);\n    }\n\n    // solve x = (LU)^* y --> y= L^{-*} U^{-*} x\n    template <typename VectorIn, typename VectorOut>\n    void adjoint_solve(const VectorIn& x, VectorOut& y) const\n    {\n\tmtl::vampir_trace<5044> tracer;\n\tsolve(x, y); \n    }\n\n\n    L_type get_L() { return L_type(L); }\n    U_type get_U() { return U; }\n\n  protected:\n    template <typename VectorOut, typename Solver> friend struct ic_0_evaluator;\n\n    // Dummy type to perform factorization in initializer list not in \n    struct factorizer\n    {\n\tfactorizer(const Matrix &A, U_type& U)\n\t{   factorize(A, U, mtl::traits::is_sparse<Matrix>(), boost::is_same<Value, typename mtl::Collection<Matrix>::value_type>());  }\n\n\ttemplate <typename T>\n\tvoid factorize(const Matrix&, U_type&, boost::mpl::false_, T)\n\t{   MTL_THROW_IF(true, mtl::logic_error(\"IC(0) is not suited for dense matrices\"));\t}\n\n\t// When we change the value_type then the factorization is still performed with that of A\n\ttemplate <typename UF>\n\tvoid factorize(const Matrix& A, UF& U, boost::mpl::true_, boost::mpl::false_)\n\t{\n\t    typedef mtl::matrix::compressed2D<typename mtl::Collection<Matrix>::value_type, para> tmp_type;\n\t    tmp_type U_tmp;\n\t    factorize(A, U_tmp, boost::mpl::true_(), boost::mpl::true_());\n\t    U= U_tmp;\n\t}\n\n\t// Factorization adapted from Saad\n\t// Undefined (runtime) behavior if matrix is not symmetric \n\t// UF is type for the factorization\n\ttemplate <typename UF> \n\tvoid factorize(const Matrix& A, UF& U, boost::mpl::true_, boost::mpl::true_)\n\t{\n\t    using namespace mtl; using namespace mtl::tag;  using mtl::traits::range_generator;  \n\t    using math::reciprocal; using mtl::matrix::upper;\n\t    mtl::vampir_trace<5035> tracer;\n\n\t    // For the factorization we take still the value_type of A and later we copy it maybe to another value_type\n\t    typedef typename mtl::Collection<Matrix>::value_type      value_type;\n\t    typedef typename range_generator<row, UF>::type       cur_type;    \n\t    typedef typename range_generator<nz, cur_type>::type      icur_type;            \n\n\t    MTL_THROW_IF(num_rows(A) != num_cols(A), mtl::matrix_not_square());\n\t    U= upper(A);\n\n\t    typename mtl::traits::col<UF>::type                   col(U);\n\t    typename mtl::traits::value<UF>::type                 value(U); \t\n\n\t    cur_type kc= begin<row>(U), kend= end<row>(U);\n\t    for (size_type k= 0; kc != kend; ++kc, ++k) {\n\n\t\ticur_type ic= begin<nz>(kc), iend= end<nz>(kc);\n\t\tMTL_DEBUG_THROW_IF(col(*ic) != k, mtl::missing_diagonal());\n\n\t\t// U[k][k]= 1.0 / sqrt(U[k][k]);\n\t\tvalue_type inv_dia= reciprocal(sqrt(value(*ic)));\n\t\tvalue(*ic, inv_dia);\n\t\t// icur_type jbegin= \n\t\t++ic;\n\t\tfor (; ic != iend; ++ic) {\n\t\t    // U[k][i] *= U[k][k]\n\t\t    value_type d= value(*ic) * inv_dia;\n\t\t    value(*ic, d);\n\t\t    size_type i= col(*ic);\n\n\t\t    // find non-zeros U[j][i] below U[k][i] for j in (k, i]\n\t\t    // 1. Go to ith row in U (== ith column in U)\n\t\t    cur_type irow(i, U); // = begin<row>(U); irow+= i;\n\t\t    // 2. Find nonzeros with col() in (k, i]\n\t\t    icur_type jc= begin<nz>(irow), jend= end<nz>(irow);\n\t\t    while (col(*jc) <= k)  ++jc;\n\t\t    while (col(*--jend) > i) ;\n\t\t    ++jend; \n\t\t\n\t\t    for (; jc != jend; ++jc) {\n\t\t\tsize_type j= col(*jc);\n\t\t\tU.lvalue(j, i)-= d * U[k][j];\n\t\t    }\n\t\t    // std::cout << \"U after eliminating U[\" << i << \"][\" << k << \"] =\\n\" << U;\n\t\t}\n\t    }\n\t}\n    };\n\n    U_type                       U;\n    factorizer                   f;\n    L_type                       L;\n    lower_solver_t               lower_solver;\n    upper_solver_t               upper_solver;\n}; \n\n#if 0\ntemplate <typename Matrix, typename Value, typename Vector>\nstruct ic_0_solver\n  : mtl::vector::assigner<ic_0_solver<Matrix, Value, Vector> >\n{\n    typedef ic_0<Matrix, Value> pc_type;\n\n    ic_0_solver(const ic_0<Matrix, Value>& P, const Vector& x) : P(P), x(x) {}\n\n    template <typename VectorOut>\n    void assign_to(VectorOut& y) const\n    {\tP.solve(x, y);    }    \n\n    const ic_0<Matrix, Value>& P; \n    const Vector&              x;\n};\n#endif\n\ntemplate <typename VectorOut, typename Solver>\nstruct ic_0_evaluator\n{\n    typedef typename Solver::pc_type                        pc_type;\n    typedef typename pc_type::size_type                     size_type;\n    typedef typename mtl::Collection<VectorOut>::value_type out_value_type;\n\n\n    ic_0_evaluator(VectorOut& y, const Solver& s) \n      : y(y), s(s), U(s.P.U), y0(s.P.solve_lower(s.x, y)) { MTL_DEBUG_ARG(lr= 99999999); }\n\n\n    void operator()(size_type i) { at<0>(i); }\n    void operator[](size_type i) { at<0>(i); }\n\n    template <unsigned Offset>\n    void at(size_type r)\n    {\n#ifndef NDEBUG\n\tMTL_THROW_IF(r+Offset >= lr, mtl::logic_error(\"Traversal must be backward\")); lr= r+Offset;\n#endif\n\tsize_type j0= U.ref_major()[r+Offset];\n\tconst size_type cj1= U.ref_major()[r+Offset+1];\n\tMTL_DEBUG_THROW_IF(j0 == cj1 || U.ref_minor()[j0] != r+Offset, mtl::missing_diagonal());\n\tout_value_type rr= y0[r+Offset], dia= U.data[j0++];\n\tfor (; j0 != cj1; ++j0) {\n\t    MTL_DEBUG_THROW_IF(U.ref_minor()[j0] <= r+Offset, mtl::logic_error(\"Matrix entries must be sorted for this.\"));\n\t    rr-= U.data[j0] * y[U.ref_minor()[j0]];\n\t}\n\ty[r+Offset]= rr * dia;\n    }\n\n    VectorOut&                               y;\n    const Solver&                            s;\n    const typename pc_type::U_type&          U;\n    const VectorOut&                         y0;\n    MTL_DEBUG_ARG(size_type                  lr;)\n};\n\ntemplate <typename VectorOut, typename Solver>\ninline std::size_t size(const ic_0_evaluator<VectorOut, Solver>& eval)\n{   return size(eval.y); }\n\ntemplate <typename Matrix, typename Value, typename Vector>\nsolver<ic_0<Matrix, Value>, Vector, false>\ninline solve(const ic_0<Matrix, Value>& P, const Vector& x)\n{\n    return solver<ic_0<Matrix, Value>, Vector, false>(P, x);\n}\n\ntemplate <typename Matrix, typename Value, typename Vector>\nsolver<ic_0<Matrix, Value>, Vector, true>\ninline adjoint_solve(const ic_0<Matrix, Value>& P, const Vector& x)\n{\n    return solver<ic_0<Matrix, Value>, Vector, true>(P, x);\n}\n\n\n}} // namespace itl::pc\n\nnamespace mtl { namespace vector {\n    using itl::pc::size;\n}} // namespace mtl::vector\n\n#endif // ITL_PC_IC_0_INCLUDE\n", "meta": {"hexsha": "d38b8b4a5ac0c2564cbeaa64ef6a7726090ca464", "size": 9583, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/itl/pc/ic_0.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/itl/pc/ic_0.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mtl4/boost/numeric/itl/pc/ic_0.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3476702509, "max_line_length": 129, "alphanum_fraction": 0.6343524992, "num_tokens": 2717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.44746508484204023}}
{"text": "/* =========================================================================\n   Copyright (c) 2012-2014, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n                             -----------------\n               ViennaFEM - The Vienna Finite Element Method Library\n                             -----------------\n\n   Author:     Karl Rupp                          rupp@iue.tuwien.ac.at\n\n   License:    MIT (X11), see file LICENSE in the ViennaFEM base directory\n============================================================================ */\n\n// remove assert() statements and the like in order to get reasonable performance\n#ifndef NDEBUG\n  #define NDEBUG\n#endif\n\n// include necessary system headers\n#include <iostream>\n\n// ViennaFEM includes:\n#include \"viennafem/fem.hpp\"\n#include \"viennafem/io/vtk_writer.hpp\"\n\n// ViennaGrid includes:\n#include \"viennagrid/forwards.hpp\"\n#include \"viennagrid/config/default_configs.hpp\"\n#include \"viennagrid/io/netgen_reader.hpp\"\n\n// ViennaData includes:\n#include \"viennadata/api.hpp\"\n\n// ViennaMath includes:\n#include \"viennamath/expression.hpp\"\n\n// Boost.uBLAS includes:\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n\n\n//ViennaCL includes:\n#ifndef VIENNACL_HAVE_UBLAS\n #define VIENNACL_HAVE_UBLAS\n#endif\n\n#include \"viennacl/linalg/cg.hpp\"\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n\n\nint main()\n{\n  typedef viennagrid::hexahedral_3d_mesh                                                  DomainType;\n  typedef viennagrid::result_of::segmentation<DomainType>::type                           SegmentationType;\n\n  typedef viennagrid::result_of::element<DomainType, viennagrid::vertex_tag>::type        VertexType;\n  typedef viennagrid::result_of::element_range<DomainType, viennagrid::vertex_tag>::type  VertexContainer;\n  typedef viennagrid::result_of::iterator<VertexContainer>::type                          VertexIterator;\n\n  typedef boost::numeric::ublas::compressed_matrix<viennafem::numeric_type>  MatrixType;\n  typedef boost::numeric::ublas::vector<viennafem::numeric_type>             VectorType;\n\n  typedef viennamath::function_symbol   FunctionSymbol;\n  typedef viennamath::equation          Equation;\n\n  //\n  // Create a domain from file\n  //\n  DomainType my_domain;\n  SegmentationType segments(my_domain);\n\n  //\n  // Create a storage object\n  //\n  typedef viennadata::storage<> StorageType;\n  StorageType   storage;\n\n  try\n  {\n    viennagrid::io::netgen_reader my_reader;\n    my_reader(my_domain, segments, \"../examples/data/cube343_hex.mesh\");\n  }\n  catch (...)\n  {\n    std::cerr << \"File-Reader failed. Aborting program...\" << std::endl;\n    exit(EXIT_FAILURE);\n  }\n\n\n  //\n  // Specify two PDEs:\n  //\n  FunctionSymbol u(0, viennamath::unknown_tag<>());   //an unknown function used for PDE specification\n  Equation poisson_equ_1 = viennamath::make_equation( viennamath::laplace(u), -1);\n  Equation poisson_equ_2 = viennamath::make_equation( viennamath::laplace(u), -1);\n\n  MatrixType system_matrix_1, system_matrix_2;\n  VectorType load_vector_1, load_vector_2;\n\n  //\n  // Setting boundary information on domain (this should come from device specification)\n  //\n  //setting some boundary flags:\n  VertexContainer vertices = viennagrid::elements<VertexType>(my_domain);\n  for (VertexIterator vit = vertices.begin();\n      vit != vertices.end();\n      ++vit)\n  {\n    // First equation: Homogeneous boundary conditions at x=0, x=1, y=0, or y=1\n    if ( viennagrid::point(my_domain, *vit)[0] == 0.0 || viennagrid::point(my_domain, *vit)[0] == 1.0\n         || viennagrid::point(my_domain, *vit)[1] == 0.0 || viennagrid::point(my_domain, *vit)[1] == 1.0 )\n      viennafem::set_dirichlet_boundary(storage, *vit, 0.0, 0);  //simulation with ID 0 uses homogeneous boundary data\n\n    // Boundary for second equation (ID 1): 0 at left boundary, 1 at right boundary\n    if ( viennagrid::point(my_domain, *vit)[0] == 0.0)\n      viennafem::set_dirichlet_boundary(storage, *vit, 0.0, 1);\n    else if ( viennagrid::point(my_domain, *vit)[0] == 1.0)\n      viennafem::set_dirichlet_boundary(storage, *vit, 1.0, 1);\n  }\n\n\n  //\n  // Create PDE solver functors: (discussion about proper interface required)\n  //\n  viennafem::pde_assembler<StorageType> fem_assembler(storage);\n\n\n  //\n  // Solve system and write solution vector to pde_result:\n  // (discussion about proper interface required. Introduce a pde_result class?)\n  //\n  fem_assembler(viennafem::make_linear_pde_system(poisson_equ_1,\n                                                  u,\n                                                  viennafem::make_linear_pde_options(0,\n                                                                                     viennafem::lagrange_tag<1>(),\n                                                                                     viennafem::lagrange_tag<1>())\n                                                 ),\n                my_domain,\n                system_matrix_1,\n                load_vector_1\n               );\n\n  fem_assembler(viennafem::make_linear_pde_system(poisson_equ_2,\n                                                  u,\n                                                  viennafem::make_linear_pde_options(1,\n                                                                                     viennafem::lagrange_tag<1>(),\n                                                                                     viennafem::lagrange_tag<1>())\n                                                 ),\n                my_domain,\n                system_matrix_2,\n                load_vector_2\n               );\n\n  VectorType pde_result_1 = viennacl::linalg::solve(system_matrix_1, load_vector_1, viennacl::linalg::cg_tag());\n  std::cout << \"* solve(): Residual: \" << norm_2(prod(system_matrix_1, pde_result_1) - load_vector_1) << std::endl;\n\n  VectorType pde_result_2 = viennacl::linalg::solve(system_matrix_2, load_vector_2, viennacl::linalg::cg_tag());\n  std::cout << \"* solve(): Residual: \" << norm_2(prod(system_matrix_2, pde_result_2) - load_vector_2) << std::endl;\n\n\n  //\n  // Writing solution back to domain (discussion about proper way of returning a solution required...)\n  //\n  viennafem::io::write_solution_to_VTK_file(pde_result_1, \"poisson_3d_hex_1\", my_domain, segments, storage, 0);\n  viennafem::io::write_solution_to_VTK_file(pde_result_2, \"poisson_3d_hex_2\", my_domain, segments, storage, 1);\n\n  std::cout << \"*****************************************\" << std::endl;\n  std::cout << \"* Poisson solver finished successfully! *\" << std::endl;\n  std::cout << \"*****************************************\" << std::endl;\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "44e5d53a8502286cbd0615530a05f2354eae802b", "size": 6902, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorials/poisson_3d_hex.cpp", "max_stars_repo_name": "viennafem/viennafem-dev", "max_stars_repo_head_hexsha": "1f2d772cef5fb1c148e22e5bbbb6302b301e896b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-23T17:35:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-19T14:39:03.000Z", "max_issues_repo_path": "examples/tutorials/poisson_3d_hex.cpp", "max_issues_repo_name": "viennafem/viennafem-dev", "max_issues_repo_head_hexsha": "1f2d772cef5fb1c148e22e5bbbb6302b301e896b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-11-17T03:28:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-04T03:40:11.000Z", "max_forks_repo_path": "examples/tutorials/poisson_3d_hex.cpp", "max_forks_repo_name": "viennafem/viennafem-dev", "max_forks_repo_head_hexsha": "1f2d772cef5fb1c148e22e5bbbb6302b301e896b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-23T20:24:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T20:24:15.000Z", "avg_line_length": 39.2159090909, "max_line_length": 118, "alphanum_fraction": 0.5924369748, "num_tokens": 1654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.44746508484204023}}
{"text": "/**\n* @file  AdBidStrategy.cpp\n* @brief Implementation to class AdBidStrategy.\n*/\n\n#include <functional>\n#include <limits>\n#include <algorithm>\n#include <utility>\n#include <set>\n#include <queue>\n#include <cmath>\n#include <time.h>\n#include <cstdlib>\n#include <cstdio>\n#include <boost/unordered_map.hpp>\n#include <boost/multi_array.hpp>\n#include \"AdBidStrategy.h\"\n\nnamespace sf1r\n{\n\nnamespace sponsored\n{\n\nstatic const double E = 2.71828;\n\nAdBidStrategy::AdBidStrategy()\n{\n\n}\n\nAdBidStrategy::~AdBidStrategy()\n{\n\n}\n\nstatic bool isZero(double f)\n{\n    return std::abs(f) < std::numeric_limits<double>::epsilon();\n}\n\nstruct Point\n{\n    double x;\n    double y;\n\n    Point(double X = 0.0, double Y = 0.0):x(X), y(Y) {}\n};\n\nstatic bool operator<(const Point& p1, const Point& p2)\n{\n    return (p1.x < p2.x) || (isZero(p1.x - p2.x) && p1.y < p2.y);\n}\n\nstatic bool xsmall(const Point& p1, const Point& p2)\n{\n    return (p1.x < p2.x) ;\n}\n\n//judge the turning direction for line p0->p1->p2 at point p1.\n//turn left return 1, turn right return -1, in the same line return 0.\nstatic int turnDirection(const Point& p0, const Point& p1, const Point& p2)\n{\n    double tmp = (p2.x - p0.x)*(p1.y - p0.y) - (p2.y - p0.y)*(p1.x - p0.x);\n    if (tmp < 0) return 1;\n    else if (tmp > 0) return -1;\n    else return 0;\n}\n\nclass AnglePredicate\n{\npublic:\n    AnglePredicate(const Point& p): base_(p) {}\n\n    bool operator()(const Point& p1, const Point& p2)\n    {\n        int tmp = turnDirection(base_, p1, p2);\n        return (tmp > 0) || (tmp == 0 &&\n                             (p1.x - base_.x)*(p1.x - base_.x) + (p1.y - base_.y)*(p1.y - base_.y) < (p2.x - base_.x)*(p2.x - base_.x) + (p2.y - base_.y)*(p2.y - base_.y)\n                            );\n    }\n\nprivate:\n    Point base_;\n};\n\nstd::vector<std::pair<int, double> > AdBidStrategy::convexUniformBid( const std::vector<AdQueryStatisticInfo>& qsInfos, int budget)\n{\n    static const std::vector<std::pair<int, double> > NULLBID_(2, std::make_pair(0, 0.0));\n\n    if (qsInfos.empty())\n    {\n        return NULLBID_;\n    }\n\n\n    //aggregate landscape\n    boost::unordered_map<int, Point> landscape; //(cpc, <cost, clicks>)\n    for (std::vector<AdQueryStatisticInfo>::const_iterator cit = qsInfos.begin(); cit != qsInfos.end(); ++cit)\n    {\n        std::vector<int>::const_iterator cpcit = cit->cpc_.begin();\n        std::vector<double>::const_iterator ctrit = cit->ctr_.begin();\n        for (; cpcit != cit->cpc_.end() && ctrit != cit->ctr_.end(); ++cpcit, ++ctrit)\n        {\n            Point& curP = landscape[*cpcit];\n            curP.x += (*cpcit) * (*ctrit);\n            curP.y += (*ctrit);\n        }\n    }\n\n    std::vector<struct Point> allPoints;\n    allPoints.reserve(landscape.size());\n    Point minP(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());\n    size_t minI = -1;\n    for (boost::unordered_map<int, Point>::const_iterator cit = landscape.begin(); cit != landscape.end(); ++cit)\n    {\n        if (cit->second.y > 0 && cit->second.x > 0)\n        {\n            allPoints.push_back(cit->second);\n\n            if (cit->second < minP)\n            {\n                minP = cit->second;\n                minI = allPoints.size() - 1;\n            }\n        }\n    }\n    //   landscape.clear();\n\n    if (allPoints.empty())\n    {\n        std::vector<std::pair<int, double> > minBID_(2, std::make_pair(qsInfos.front().minBid_, 0.5));\n        return minBID_;\n    }\n\n    std::swap(allPoints[0], allPoints[minI]);\n\n    AnglePredicate ap(minP);\n    std::sort(++allPoints.begin(), allPoints.end(), ap);\n\n    //convex hull, Graham's Scan Algorithm.\n    std::vector<struct Point> ch;\n    int i = 0;\n    while (i < 2 && i < (int)allPoints.size())\n    {\n        //init\n        ch.push_back(allPoints[i++]);\n    }\n\n    for (; i < (int)allPoints.size(); ++i)\n    {\n        while(ch.size() >= 2)\n        {\n            int tmp = turnDirection(ch[ch.size() -2], ch[ch.size() - 1], allPoints[i]);\n            if (tmp < 0)\n            {\n                ch.pop_back();\n            }\n            else\n            {\n                break;\n            }\n        }\n        ch.push_back(allPoints[i]);\n    }\n    allPoints.clear();\n\n    //candidate convex hull points for bid\n    std::vector<struct Point> canch;\n    int j = 0;\n    for (; j < (int)ch.size(); ++j)\n    {\n        if (j < ((int)ch.size()) - 1 && ch[j] < ch[j+1])\n        {\n            continue;\n        }\n        else\n        {\n            break;\n        }\n    }\n\n    //upper bipart of convex hull.\n    canch.reserve(ch.size() - j + 2);\n    canch.push_back(Point()); //zero point.\n    if (ch.size()>= 2 && !isZero(ch.front().x - ch.back().x))\n    {\n        canch.push_back(ch[0]);\n    }\n\n    for (int i = ch.size() -1; i >= j; --i)\n    {\n        canch.push_back(ch[i]);\n    }\n\n    ch.clear();\n\n    //convex combination\n    std::vector<std::pair<int, double> > bid;\n    int minBid = qsInfos.front().minBid_;\n\n    int singleBudget = 1000000000;\n    int totalImpression = 0;\n    for (std::vector<AdQueryStatisticInfo>::const_iterator cit = qsInfos.begin(); cit != qsInfos.end(); ++cit)\n    {\n        totalImpression += cit->impression_;\n        singleBudget = std::min(cit->minBid_, singleBudget);\n    }\n    if (totalImpression > 0)\n    {\n        singleBudget = std::max(singleBudget, (int)(budget / (totalImpression / (double)qsInfos.size())));\n    }\n\n\n\n    Point budgetPoint(singleBudget, 0.0);\n    std::vector<struct Point>::const_iterator uit = std::upper_bound(canch.begin(), canch.end(), budgetPoint, xsmall);\n    if (uit == canch.end())\n    {\n        int mybid = std::max(minBid, singleBudget);\n        bid.push_back(std::make_pair(mybid, 0.5));\n        bid.push_back(std::make_pair(mybid, 0.5));\n    }\n    else\n    {\n        std::vector<struct Point>::const_iterator preit = uit - 1;\n        if (isZero(preit->x - singleBudget))\n        {\n            int mybid = isZero(preit->y) ? 0 : int(preit->x / preit->y);\n            mybid = std::max(minBid, mybid);\n            bid.push_back(std::make_pair(mybid, 0.5));\n            bid.push_back(std::make_pair(mybid, 0.5));\n        }\n        else\n        {\n            double p = double((singleBudget - preit->x) / (uit->x - preit->x));\n            int prebid = int(isZero(preit->y)? 0 : preit->x / preit->y);\n            if(prebid > 0)\n                prebid = std::max(prebid, minBid);\n            int lastbid = std::max(int(uit->x / uit->y), minBid);\n\n            bid.push_back(std::make_pair(prebid, p));\n            bid.push_back(std::make_pair(lastbid, 1.0 - p));\n        }\n    }\n\n    return bid;\n}\n\nint AdBidStrategy::realtimeBidWithRevenueMax(const AdQueryStatisticInfo& qsInfo,  int budgetUsed, int budgetLeft, int vpc /*= 1000*/)\n{\n    int budget = budgetLeft + budgetUsed;\n    if (budget <= 0 || qsInfo.cpc_.empty())\n    {\n        return 0;\n    }\n\n    double U = std::numeric_limits<double>::max();\n    int minBid = qsInfo.minBid_;\n    if (minBid < 0)\n    {\n        minBid = 0;\n    }\n    if (minBid > 0)\n    {\n        U = ((double)vpc) / minBid;\n    }\n\n    double z = ((double)budgetUsed) / budget;\n\n    //efficiency\n    double eff = pow(U * E, z) / E;\n\n    for (int i = 0; i < (int)qsInfo.cpc_.size(); ++i)\n    {\n        double avaiableB = budgetLeft / (qsInfo.ctr_[i] * qsInfo.impression_);\n        double myeff = ((double)vpc) / qsInfo.cpc_[i];\n        if (eff > myeff && qsInfo.cpc_[i] <= avaiableB)\n        {\n            eff = myeff;\n        }\n    }\n\n    for (int i = 0; i < (int)qsInfo.cpc_.size(); ++i)\n    {\n        double myeff = ((double)vpc) / qsInfo.cpc_[i];\n        if (myeff >= eff)\n        {\n            return qsInfo.cpc_[i];\n        }\n    }\n\n    return int(vpc / (1 + eff));\n}\n\nint AdBidStrategy::realtimeBidWithProfitMax( const AdQueryStatisticInfo& qsInfo, int budgetUsed, int budgetLeft, int vpc /*= 1000*/)\n{\n    static const double MINEFF = 0.1;\n\n    int budget = budgetLeft + budgetUsed;\n    if (budget <= 0 || qsInfo.cpc_.empty())\n    {\n        return 0;\n    }\n\n    double U = std::numeric_limits<double>::max();\n    int minBid = qsInfo.minBid_;\n    if (minBid < 0)\n    {\n        minBid = 0;\n    }\n    if (minBid > 0)\n    {\n        U = ((double)vpc) / minBid - 1;\n    }\n\n    double z = ((double)budgetUsed) / budget;\n\n    //efficiency\n    double eff = pow(U * E / MINEFF, z) * MINEFF / E;\n\n    for (int i = 0; i < (int)qsInfo.cpc_.size(); ++i)\n    {\n        double avaiableB = budgetLeft / (qsInfo.ctr_[i] * qsInfo.impression_);\n        double myeff = ((double)vpc) / qsInfo.cpc_[i] - 1;\n        if (eff > myeff && qsInfo.cpc_[i] <= avaiableB)\n        {\n            eff = myeff;\n        }\n    }\n\n    int maxI = -1;\n    double maxV = -1.0;\n    for (int i = 0; i < (int)qsInfo.cpc_.size(); ++i)\n    {\n        double myeff = ((double)vpc) / qsInfo.cpc_[i] - 1;\n        if (myeff >= eff)\n        {\n            double myV = (vpc - qsInfo.cpc_[i]) * qsInfo.ctr_[i];\n            if (myV > maxV)\n            {\n                maxV = myV;\n                maxI = i;\n            }\n        }\n    }\n    if (maxI >= 0)\n    {\n        return qsInfo.cpc_[maxI];\n    }\n    else\n        return int(vpc / (1 + eff));\n}\n\n\nclass LargerFit\n{\npublic:\n    LargerFit(const std::vector<double>& Fit): _fit(Fit) {}\n    bool operator()(int l, int r)\n    {\n        return _fit[l] < _fit[r];\n    }\n\nprivate:\n    const std::vector<double>& _fit;\n};\n\nstatic void enumKPRecursive(const std::vector<std::vector<double> >& W, const std::vector<std::vector<double> >& V, int i, std::vector<int>&curSol, double leftB, double curValue, double& maxValue, std::vector<int>& maxSol)\n{\n    if(i >= (int) W.size())\n    {\n        if(curValue > maxValue)\n        {\n            maxValue = curValue;\n            maxSol = curSol;\n        }\n        return;\n    }\n\n    //do not choose cur item.\n    curSol[i] = -1;\n    enumKPRecursive(W, V, i+1, curSol, leftB, curValue, maxValue, maxSol);\n\n    for(int j = 0; j < (int)W[i].size(); ++j)\n    {\n        if(leftB >= W[i][j])\n        {\n            curSol[i] = j;\n            enumKPRecursive(W, V, i+1, curSol, leftB - W[i][j], curValue + V[i][j], maxValue, maxSol);\n        }\n    }\n}\n\nstatic std::vector<int> enumKP(const std::vector<std::vector<double> >& W, const std::vector<std::vector<double> >& V, int B)\n{\n    std::vector<int> curSol(W.size(), -1);\n    std::vector<int> maxSol(W.size(), -1);\n    double maxValue = 0.0;\n\n    enumKPRecursive(W, V, 0, curSol, B, 0.0, maxValue, maxSol);\n\n    return maxSol;\n}\n\n//dynamic programming for knapsack problem\nstatic std::vector<int> dpKP(const std::vector<std::vector<double> >& W, const std::vector<std::vector<double> >& V, int B)\n{\n    typedef boost::multi_array<int, 2> array_type;\n    typedef array_type::index index;\n    array_type\tS(boost::extents[W.size()][B+1]);\n    std::vector<double> F(B + 1, 0.0);\n\n    for(int i = 0; i < (int)W.size(); ++i)\n    {\n        for(int v = B; v >= 0; --v)\n        {\n            double maxF = F[v];\n            int maxI = -1;\n            for(int j = 0; j < (int)W[i].size(); ++j)\n            {\n                if(v >= W[i][j])\n                {\n                    double myF = F[v - W[i][j]] + V[i][j];\n                    if(myF > maxF)\n                    {\n                        maxF = myF;\n                        maxI = j;\n                    }\n                }\n            }\n            F[v] = maxF;\n            S[i][v] = maxI;\n        }\n    }\n\n    //construct solution.\n    std::vector<int> Sol(W.size(), -1);\n    for(int i = W.size() - 1, v = B; i >= 0; --i)\n    {\n        Sol[i] = S[i][v];\n        if(S[i][v] != -1)\n        {\n            v = (int)(v - W[i][Sol[i]]);\n        }\n    }\n\n    return Sol;\n}\n\nstatic void convertIndexToBid(const std::vector<AdQueryStatisticInfo>& qsInfos, const std::vector<int>& bidindex, std::vector<int>& bid)\n{\n    std::vector<AdQueryStatisticInfo>::const_iterator cit = qsInfos.begin();\n    int i = 0;\n    int bi = 0;\n    for (; cit != qsInfos.end(); ++cit, ++i)\n    {\n        if (cit->bid_ != -1)\n        {\n            bid[i] = cit->bid_;\n        }\n        else\n        {\n            if (bidindex[bi] != -1)\n            {\n                bid[i] = cit->cpc_[bidindex[bi]];\n            }\n            else\n            {\n                bid[i] = 0;\n            }\n\n            ++bi;\n        }\n    }\n\n}\n\n//for debug.\nstatic double computeValue(const std::vector<AdQueryStatisticInfo>& qsInfos, const std::vector<int>& sol)\n{\n    double myV = 0.0;\n    std::vector<AdQueryStatisticInfo>::const_iterator cit = qsInfos.begin();\n    std::vector<int>::const_iterator sit = sol.begin();\n    for (; cit != qsInfos.end(); ++cit)\n    {\n        if (cit->bid_ == -1)\n        {\n            if (*sit != -1)\n            {\n                myV += cit->ctr_[*sit] * cit->impression_;\n            }\n            ++sit;\n        }\n    }\n\n    return myV;\n}\n\nstatic void checkGABid(const std::vector<AdQueryStatisticInfo>& qsInfos, int budget, std::vector<int>& bid)\n{\n    bool allZeroFlag = true;\n    std::vector<AdQueryStatisticInfo>::const_iterator qsIt = qsInfos.begin();\n    for (std::vector<int>::iterator it = bid.begin(); it != bid.end(); ++it, ++qsIt)\n    {\n        if (*it > 0)\n        {\n            if (*it < qsIt->minBid_)\n            {\n                *it = qsIt->minBid_;\n            }\n\n            allZeroFlag = false;\n        }\n    }\n    if (!allZeroFlag)\n    {\n        return;\n    }\n\n    int minBid = qsInfos.front().minBid_;\n    std::vector<std::pair<int, double> > ubid = AdBidStrategy::convexUniformBid(qsInfos, budget);\n    int lastBid = int(ubid.front().first * ubid.front().second + ubid.back().first * ubid.back().second);\n    lastBid = std::max(lastBid, minBid);\n    for (std::vector<int>::iterator it = bid.begin(); it != bid.end(); ++it)\n    {\n        *it = lastBid;\n    }\n}\n\nstd::vector<int> AdBidStrategy::geneticBid( const std::vector<AdQueryStatisticInfo>& qsInfos, int budget )\n{\n    std::vector<int> bid(qsInfos.size(), 0);\n\n\n    //support for predefined bidding.\n    int tmpKeywordNum = 0, tmpBidIndex = 0, tmpBudget = budget;\n    for (std::vector<AdQueryStatisticInfo>::const_iterator cit = qsInfos.begin(); cit != qsInfos.end(); ++cit, ++tmpBidIndex)\n    {\n        if (cit->bid_ == -1)\n        {\n            ++tmpKeywordNum;\n            bid[tmpBidIndex] = 0;\n        }\n        else\n        {\n            bid[tmpBidIndex] = cit->bid_;\n            int i = 0;\n            for (; i <(int)cit->cpc_.size(); ++i)\n            {\n                if (cit->bid_ >= cit->cpc_[i])\n                {\n                    break;\n                }\n            }\n            if (i < (int)cit->cpc_.size())\n            {\n                tmpBudget -= cit->cpc_[i] * cit->ctr_[i] * cit->impression_;\n            }\n        }\n    }\n\n    const int KeywordNum = tmpKeywordNum;\n    const int AvaiableBudget = tmpBudget;\n\n\n    const int MaxAllowedEvolutions = 300 * KeywordNum;\n    const int MinAllowedEvolutions = 50 * KeywordNum;\n    static const double EndPopulationRate = 0.90;  //when 90% of the population has same fitness value, stop evolute.\n    static const int PopulationSize = 40; //must be even\n    static const int ElitismSize = 2;\n    static const double MinFitVariance = 0.001;  //minimum max fitness variance ratio. variance / fit^2\n    static const long long MaxLoopNum = 10000000000;\n    static const long long MaxDPSpace = 100000000;\n\n\n    if (KeywordNum <= 0 || AvaiableBudget <= 0)\n    {\n        return bid;\n    }\n\n    typedef std::vector<std::vector<double> > TQSDataType;\n    TQSDataType W(KeywordNum), V(KeywordNum);\n    std::vector<int> adP(KeywordNum);  //ad position num for each keyword.\n    int kNum = 0;\n    for (std::vector<AdQueryStatisticInfo>::const_iterator cit = qsInfos.begin(); cit != qsInfos.end(); ++cit)\n    {\n        if (cit->bid_ != -1)\n        {\n            continue;\n        }\n\n        const std::vector<int>& cpc = cit->cpc_;\n        const std::vector<double>& ctr = cit->ctr_;\n\n        W[kNum].reserve(cpc.size());\n        V[kNum].reserve(cpc.size());\n        adP[kNum] = cpc.size();\n\n        for (int j = 0; j < (int)cpc.size(); ++j)\n        {\n            W[kNum].push_back(cpc[j] * cit->impression_ * ctr[j]);\n            V[kNum].push_back(cit->impression_ * ctr[j]);  //max traffics. value is defined as click traffics.\n        }\n\n        ++kNum;\n    }\n\n    // judge whether problem can be solved by enumerating to directly get optimal solution.\n    {\n        long long timeCP = 1;\n        for(int i = 0; i < KeywordNum; ++i)\n        {\n            timeCP *= (W[i].size() + 1);\n            if(timeCP > MaxLoopNum) break;\n        }\n        if(timeCP < MaxLoopNum)\n        {\n            const std::vector<int>& mySol = enumKP(W, V, AvaiableBudget);\n            convertIndexToBid(qsInfos, mySol, bid);\n            checkGABid(qsInfos, budget, bid);\n            return bid;\n        }\n    }\n\n    // judge whether problem can be solved by dynamic programming to directly get optimal solution.\n    {\n        long long spaceComplexity = KeywordNum;\n        spaceComplexity *= (AvaiableBudget + 1);\n        if (spaceComplexity <= MaxDPSpace)\n        {\n            const std::vector<int>& mySol = dpKP(W, V, AvaiableBudget);\n            convertIndexToBid(qsInfos, mySol, bid);\n            checkGABid(qsInfos, budget, bid);\n            return bid;\n        }\n    }\n\n    typedef std::vector<std::vector<int> > TPopType; //every individual is a vector of index of ad position for each keyword, 0-based.\n    TPopType P(PopulationSize);\n    TPopType newP(PopulationSize);\n\n    srand(time(NULL));\n    for (int i = 0; i < PopulationSize; ++i)\n    {\n        P[i].reserve(KeywordNum);\n        newP[i].reserve(KeywordNum);\n        for (size_t j = 0; j < KeywordNum; ++j)\n        {\n            int N = adP[j] + 1;\n            P[i].push_back(rand() % N - 1); //ad position is 0-based, -1 means do not bid for that keyword.\n            newP[i].push_back(0);\n        }\n\n        //clear population for budget requirement.\n        for (int i = 0; i < PopulationSize; ++i)\n        {\n            std::vector<std::pair<int, int> > kw; //(keyword index, selected ad position index)\n            for (int j = 0; j < (int)(P[i].size()); ++j)\n            {\n                //for each keyword\n                if (P[i][j] != -1)\n                {\n                    kw.push_back(std::make_pair(j, P[i][j]));\n                }\n            }\n\n            double totalW = 0.0;\n            for (std::vector<std::pair<int, int> >::const_iterator cit = kw.begin(); cit != kw.end(); ++cit)\n            {\n                totalW += W[cit->first][cit->second];\n            }\n\n            int aN = kw.size();\n            while(totalW > AvaiableBudget)\n            {\n                int r = rand() % aN;\n                totalW -= W[kw[r].first][kw[r].second];\n                P[i][kw[r].first] = -1;\n                std::swap(kw[r], kw[aN - 1]);\n                --aN;\n            }\n        }\n    }\n\n    int iterNum = MaxAllowedEvolutions;\n    double averageFit = 0.0, averageSquareFit = 0.0;\n\n    while(iterNum--)\n    {\n        //selection,\n        std::vector<int> SP(PopulationSize); //selected individual's index in P\n        int GASize = PopulationSize - ElitismSize;\n\n        {\n            std::vector<double> fitness(PopulationSize); //total fitness.\n            std::vector<double> fit(PopulationSize);    //each individual fitness.\n            double fn = 0.0;\n            for (int i = 0; i < PopulationSize; ++i)\n            {\n                double curfn = 0.0;\n                for (int j = 0; j < (int)(P[i].size()); ++j)\n                {\n                    //for each keyword\n                    if (P[i][j] != -1)\n                    {\n                        curfn += V[j][P[i][j]];\n                    }\n                }\n                fn += curfn;\n                fit[i] = curfn;\n                fitness[i] = fn;\n            }\n\n            //check condition of stop evolution.\n            if (MaxAllowedEvolutions - iterNum > MinAllowedEvolutions)\n            {\n                boost::unordered_map<double, int> fitNum;\n                for (int i = 0; i < PopulationSize; ++i)\n                {\n                    fitNum[fit[i]]++;\n                }\n                int maxNum = -1;\n                for (boost::unordered_map<double, int>::const_iterator cit = fitNum.begin(); cit != fitNum.end(); ++cit)\n                {\n                    if (cit->second > maxNum)\n                    {\n                        maxNum = cit->second;\n                    }\n                }\n\n                if ((double)maxNum / PopulationSize >= EndPopulationRate)\n                {\n                    break;\n                }\n            }\n\n            //stochastic universal sampling.\n            double fstep = fn / GASize;\n            double fstart = ((double)rand()) / RAND_MAX * fstep;\n\n            if (!isZero(fstep))\n            {\n                for (int i = 0, j = 0; i < GASize; ++i)\n                {\n                    double fcur = fstart + i * fstep;\n                    for (int k = j; k < PopulationSize; ++k)\n                    {\n                        if (fitness[k] > fcur)\n                        {\n                            SP[i] = k;\n                            j = k;\n                            break;\n                        }\n                    }\n                }\n            }\n            else\n            {\n                for (int i = 0; i < PopulationSize; ++i)\n                {\n                    SP[i] = i;\n                }\n            }\n\n            //random to select crossover pair\n            for (int i = GASize; i >= 1; --i)\n            {\n                int j = rand() % i;\n                std::swap(SP[j], SP[i - 1]);\n            }\n\n            //elitism\n            LargerFit mylf(fit);\n            std::priority_queue<int, std::vector<int>, LargerFit> pq(mylf);\n            for (int i = 0; i < PopulationSize; ++i)\n            {\n                pq.push(i);\n            }\n\n            {\n                //average fit\n                int eNum = MaxAllowedEvolutions - iterNum;\n                double curMaxFit = fit[pq.top()];\n                if (!isZero(curMaxFit))\n                {\n                    averageFit = ((eNum - 1) * averageFit + curMaxFit) / eNum;\n                    averageSquareFit = ((eNum - 1) * averageSquareFit + curMaxFit * curMaxFit) / eNum;\n                    //variance\n                    double variance = averageSquareFit - averageFit * averageFit;\n                    if (eNum > MinAllowedEvolutions && variance / (curMaxFit*curMaxFit) < MinFitVariance)\n                    {\n                        break;\n                    }\n                }\n            }\n\n            for (int i = GASize; i < PopulationSize; ++i)\n            {\n                SP[i] = pq.top();\n                pq.pop();\n            }\n\n\n        }\n\n        //crossover\n        int crossoverRate = 85;\n        for (int i = 0; i < GASize; i += 2)\n        {\n            int myRate = rand() % 100;\n            if (myRate < crossoverRate)\n            {\n                const std::vector<int>& lp = P[SP[i]];\n                const std::vector<int>& rp = P[SP[i+1]];\n\n                for (int j = 0; j < KeywordNum; ++j)\n                {\n                    double p = (double)rand() / RAND_MAX * 1.50 - 0.25;\n\n                    if (lp[j] != -1 && rp[j] != -1)\n                    {\n                        //newP[i][j]\n                        int v = (int)(lp[j] * p + rp[j] * (1.0 - p) + 0.5);\n                        v = std::max(v, 0);\n                        v = std::min(v, adP[j] - 1);\n                        newP[i][j] = v;\n\n                        //newP[i+1]\n                        //newP[i]\n                        v = (int)(lp[j] * ( 1.0 - p ) + rp[j] * p + 0.5);\n                        v = std::max(v, 0);\n                        v = std::min(v, adP[j] - 1);\n                        newP[i+1][j] = v;\n                    }\n                    else if (lp[j] == -1 && rp[j] == -1)\n                    {\n                        newP[i][j] = -1;\n                        newP[i+1][j] = -1;\n                    }\n                    else\n                    {\n                        //discrete\n                        int ip = rand() % 2;\n                        if (ip)\n                        {\n                            newP[i][j] = -1;\n                            newP[i+1][j] = -1;\n                        }\n                        else\n                        {\n                            int tmp = std::max(lp[j], rp[j]);\n                            newP[i][j] = tmp;\n                            newP[i+1][j] = tmp;\n                        }\n                    }\n\n                }\n            }\n            else\n            {\n                newP[i] = P[SP[i]];\n                newP[i+1] = P[SP[i+1]];\n            }\n        }\n        for (int i = GASize; i < PopulationSize; ++i)\n        {\n            newP[i] = P[SP[i]];\n        }\n\n        //mutation, mutation rate, 1/countof(var)\n        int mRate = KeywordNum;\n        for (int i = 0; i < GASize; ++i)\n        {\n            for (int j = 0; j < KeywordNum; ++j)\n            {\n                if (rand() % mRate == 0)\n                {\n                    //do mutation\n                    newP[i][j] = rand() % (adP[j] + 1) - 1;\n                }\n            }\n        }\n\n        newP.swap(P);\n\n\n        //clear population for budget requirement.\n        for (int i = 0; i < PopulationSize; ++i)\n        {\n            std::vector<std::pair<int, int> > kw; //(keyword index, selected ad position index)\n            for (int j = 0; j < (int)(P[i].size()); ++j)\n            {\n                //for each keyword\n                if (P[i][j] != -1)\n                {\n                    kw.push_back(std::make_pair(j, P[i][j]));\n                }\n            }\n\n            double totalW = 0.0;\n            for (std::vector<std::pair<int, int> >::const_iterator cit = kw.begin(); cit != kw.end(); ++cit)\n            {\n                totalW += W[cit->first][cit->second];\n            }\n\n            int aN = kw.size();\n            while(totalW > AvaiableBudget)\n            {\n                int r = rand() % aN;\n                totalW -= W[kw[r].first][kw[r].second];\n                P[i][kw[r].first] = -1;\n                std::swap(kw[r], kw[aN - 1]);\n                --aN;\n            }\n        }\n\n    }\n\n    //max fitness in population\n    int maxI = -1;\n    double maxfit = -1.0;\n    for (int i = 0; i < PopulationSize; ++i)\n    {\n        double ft = 0.0;\n        for (int j = 0; j < KeywordNum; ++j)\n        {\n            if (P[i][j] != -1)\n            {\n                ft += V[j][P[i][j]];\n            }\n        }\n        if (ft > maxfit)\n        {\n            maxfit = ft;\n            maxI = i;\n        }\n    }\n\n\n    if (maxI != -1)\n    {\n        convertIndexToBid(qsInfos, P[maxI], bid);\n\n    }\n\n    checkGABid(qsInfos, budget, bid);\n    return bid;\n}\n\n}\n}\n\n", "meta": {"hexsha": "dfed8a1234ab33e47ebc20d903697e41ca07d4cf", "size": 26788, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/core/ad-manager/sponsored-ad-search/AdBidStrategy.cpp", "max_stars_repo_name": "izenecloud/sf1r-ad-delivery", "max_stars_repo_head_hexsha": "998eadb243098446854615de9a96e58a24bd2f4f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-04-20T03:40:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-09T08:43:07.000Z", "max_issues_repo_path": "source/core/ad-manager/sponsored-ad-search/AdBidStrategy.cpp", "max_issues_repo_name": "izenecloud/sf1r-ad-delivery", "max_issues_repo_head_hexsha": "998eadb243098446854615de9a96e58a24bd2f4f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/core/ad-manager/sponsored-ad-search/AdBidStrategy.cpp", "max_forks_repo_name": "izenecloud/sf1r-ad-delivery", "max_forks_repo_head_hexsha": "998eadb243098446854615de9a96e58a24bd2f4f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-02-01T13:53:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-07T15:45:36.000Z", "avg_line_length": 28.0502617801, "max_line_length": 222, "alphanum_fraction": 0.4627445125, "num_tokens": 7331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.44741289852120847}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <stdexcept>\n#include <boost/foreach.hpp>\n\nnamespace argus\n{\n\nVectorType flatten_matrices( const std::vector<MatrixType>& mats )\n{\n\tunsigned int n = 0;\n\tBOOST_FOREACH( const MatrixType& mat, mats )\n\t{\n\t\tn += mat.size();\n\t}\n\tVectorType out(n);\n\tunsigned int ind = 0;\n\tBOOST_FOREACH( const MatrixType& mat, mats )\n\t{\n\t\tEigen::Map<const VectorType> v( mat.data(), mat.size(), 1 );\n\t\tout.segment(ind, mat.size()) = v;\n\t\tind += v.size();\n\t}\n\treturn out;\n}\n\nMatrixType vstack_matrices( const std::vector<MatrixType>& mats )\n{\n\tunsigned int rows = 0;\n\tunsigned int cols = mats[0].cols();\n\n\tBOOST_FOREACH( const MatrixType& mat, mats )\n\t{\n\t\trows += mat.rows();\n\t\tif( mat.cols() != cols )\n\t\t{\n\t\t\tthrow std::invalid_argument( \"Not all mats same width!\" );\n\t\t}\n\t}\n\n\tMatrixType out( rows, cols );\n\tunsigned int ind = 0;\n\tBOOST_FOREACH( const MatrixType& mat, mats )\n\t{\n\t\tout.block(ind, 0, mat.rows(), mat.cols() ) = mat;\n\t\tind += mat.rows();\n\t}\n\treturn out;\n}\n\nMatrixType hstack_matrices( const std::vector<MatrixType>& mats )\n{\n\tunsigned int rows = mats[0].rows();\n\tunsigned int cols = 0;\n\n\tBOOST_FOREACH( const MatrixType& mat, mats )\n\t{\n\t\tcols += mat.cols();\n\t\tif( mat.rows() != rows )\n\t\t{\n\t\t\tthrow std::invalid_argument( \"Not all mats same height!\" );\n\t\t}\n\t}\n\n\tMatrixType out( rows, cols );\n\tunsigned int ind = 0;\n\tBOOST_FOREACH( const MatrixType& mat, mats )\n\t{\n\t\tout.block(0, ind, mat.rows(), mat.cols() ) = mat;\n\t\tind += mat.cols();\n\t}\n\treturn out;\n}\n\n// template <class Derived>\n// Derived ConcatenateHor( const Eigen::DenseBase<Derived>& l,\n//                         const Eigen::DenseBase<Derived>& r )\n// {\n// \tif( l.size() == 0 )\n// \t{\n// \t\treturn r;\n// \t}\n// \tif( r.size() == 0 )\n// \t{\n// \t\treturn l;\n// \t}\n\n// \tif( l.rows() != r.rows() )\n// \t{\n// \t\tthrow std::runtime_error( \"ConcatenateHor: Dimension mismatch.\" );\n// \t}\n// \tDerived out( l.rows(), l.cols() + r.cols() );\n// \tout.leftCols( l.cols() ) = l;\n// \tout.rightCols( r.cols() ) = r;\n// \treturn out;\n// }\n\n// template <class Derived>\n// Derived ConcatenateVer( const Eigen::DenseBase<Derived>& l,\n//                         const Eigen::DenseBase<Derived>& r )\n// {\n// \tif( l.size() == 0 )\n// \t{\n// \t\treturn r;\n// \t}\n// \tif( r.size() == 0 )\n// \t{\n// \t\treturn l;\n// \t}\n\n// \tif( l.cols() != r.cols() )\n// \t{\n// \t\tthrow std::runtime_error( \"ConcatenateVer: Dimension mismatch.\" );\n// \t}\n// \tDerived out( l.rows() + r.rows(), l.cols() );\n// \tout.topRows( l.rows() ) = l;\n// \tout.bottomRows( r.rows() ) = r;\n// \treturn out;\n// }\n\n}", "meta": {"hexsha": "1808100c3021f41a5c8a6935b5216e94eaac0b04", "size": 2531, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/modprop/utils/MatrixUtils.hpp", "max_stars_repo_name": "Humhu/modprop", "max_stars_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-10T00:54:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-10T00:54:53.000Z", "max_issues_repo_path": "include/modprop/utils/MatrixUtils.hpp", "max_issues_repo_name": "Humhu/modprop", "max_issues_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/modprop/utils/MatrixUtils.hpp", "max_forks_repo_name": "Humhu/modprop", "max_forks_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7459016393, "max_line_length": 71, "alphanum_fraction": 0.5827736073, "num_tokens": 776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.4474128952532588}}
{"text": "//\n// Copyright (c) 2015-2019 CNRS INRIA\n// Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n//\n\n#include \"pinocchio/bindings/python/spatial/explog.hpp\"\n#include <boost/python.hpp>\n\nnamespace pinocchio\n{\n  namespace python\n  {\n    namespace bp = boost::python;\n    \n    void exposeExplog()\n    {\n      \n      bp::def(\"exp3\",&exp3_proxy<Eigen::Vector3d>,\n              bp::arg(\"Angular velocity (vector of size 3)\"),\n              \"Exp: so3 -> SO3. Return the integral of the input\"\n              \" angular velocity during time 1.\");\n      \n      bp::def(\"Jexp3\",&Jexp3_proxy<Eigen::Vector3d>,\n              bp::arg(\"v: Angular velocity (vector of size 3)\"),\n              \"Jacobian of exp(R) which maps from the tangent of SO(3) at exp(v) to\"\n              \" the tangent of SO(3) at Identity.\");\n      \n      bp::def(\"log3\",&log3_proxy<Eigen::Matrix3d>,\n              bp::arg(\"Rotation matrix (matrix of size 3x3))\"),\n              \"Log: SO3 -> so3. Pseudo-inverse of log from SO3\"\n              \" -> { v in so3, ||v|| < 2pi }.Exp: so3 -> SO3.\");\n      \n      bp::def(\"Jlog3\",&Jlog3_proxy<Eigen::Matrix3d>,\n              bp::arg(\"Rotation matrix R (matrix of size 3x3)\"),\n              \"Jacobian of log(R) which maps from the tangent of SO(3) at R to\"\n              \" the tangent of SO(3) at Identity.\");\n      \n      bp::def(\"exp6\",&exp6_proxy<double,0>,\n              bp::arg(\"Spatial velocity (Motion)\"),\n              \"Exp: se3 -> SE3. Return the integral of the input\"\n              \" spatial velocity during time 1.\");\n              \n      bp::def(\"exp6\",&exp6_proxy<Motion::Vector6>,\n              bp::arg(\"Spatial velocity (vector 6x1)\"),\n              \"Exp: se3 -> SE3. Return the integral of the input\"\n              \" spatial velocity during time 1.\");\n      \n      bp::def(\"Jexp6\",&Jexp6_proxy<double,0>,\n              bp::arg(\"v: Spatial velocity (Motion)\"),\n              \"Jacobian of exp(v) which maps from the tangent of SE(3) at exp(v) to\"\n              \" the tangent of SE(3) at Identity.\");\n              \n      bp::def(\"Jexp6\",&Jexp6_proxy<Motion::Vector6>,\n              bp::arg(\"v: Spatial velocity (vector 6x1)\"),\n              \"Jacobian of exp(v) which maps from the tangent of SE(3) at exp(v) to\"\n              \" the tangent of SE(3) at Identity.\");\n      \n      bp::def(\"log6\",(Motion (*)(const SE3 &))&log6<double,0>,\n              bp::arg(\"Spatial transform (SE3)\"),\n              \"Log: SE3 -> se3. Pseudo-inverse of exp from SE3\"\n              \" -> { v,w in se3, ||w|| < 2pi }.\");\n      \n      bp::def(\"log6\",&log6_proxy<Eigen::Matrix4d>,\n              bp::arg(\"Homegenious matrix (matrix 4x4)\"),\n              \"Log: SE3 -> se3. Pseudo-inverse of exp from SE3\"\n              \" -> { v,w in se3, ||w|| < 2pi }.\");\n      \n      bp::def(\"Jlog6\",&Jlog6_proxy<double,0>,\n              bp::arg(\"Spatial transform M (SE3)\"),\n              \"Jacobian of log(M) which maps from the tangent of SE(3) at M to\"\n              \" the tangent of SE(3) at Identity.\");\n      \n    }\n    \n  } // namespace python\n} // namespace pinocchio\n", "meta": {"hexsha": "4fb2fb3ad8a0ecd1e377a80a45687912ee915697", "size": 3066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bindings/python/spatial/expose-explog.cpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-05-10T08:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T14:26:57.000Z", "max_issues_repo_path": "bindings/python/spatial/expose-explog.cpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bindings/python/spatial/expose-explog.cpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-21T16:00:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T06:24:52.000Z", "avg_line_length": 39.8181818182, "max_line_length": 84, "alphanum_fraction": 0.5293542074, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.4473040567487211}}
{"text": "// Copyright (c) 2017 Graphcore Ltd. All rights reserved.\n#include \"poplibs_support/logging.hpp\"\n#include <boost/multi_array.hpp>\n#include <cassert>\n#include <poplibs_test/GeneralMatrixAdd.hpp>\n#include <poplibs_test/GeneralMatrixMultiply.hpp>\n#include <poplibs_test/Lstm.hpp>\n#include <poplibs_test/NonLinearity.hpp>\n#include <unordered_map>\n\n// Fwd state array indices\n#define LSTM_FWD_STATE_FORGET_GATE 2\n#define LSTM_FWD_STATE_CAND_TANH 3\n#define LSTM_FWD_STATE_INPUT_GATE 4\n#define LSTM_FWD_STATE_OUTPUT_GATE 5\n#define LSTM_FWD_STATE_OUTPUT_TANH 6\n\nusing IndexRange = boost::multi_array_types::index_range;\nusing Array1dRef = boost::multi_array_ref<double, 1>;\nusing Array1dRefUNSIGNED = boost::multi_array_ref<unsigned, 1>;\nusing Array2dRef = boost::multi_array_ref<double, 2>;\nusing Array2d = boost::multi_array<double, 2>;\nusing Array3dRef = boost::multi_array_ref<double, 3>;\nusing Array4dRef = boost::multi_array_ref<double, 4>;\nusing Array3d = boost::multi_array<double, 3>;\n\nusing namespace poplibs_support;\nusing namespace poplibs_test;\n\nstatic void matrixZero(boost::multi_array_ref<double, 2> matA) {\n  std::fill(matA.data(), matA.data() + matA.num_elements(), 0.0);\n}\n\n/**\n * Process a given unit type within an LSTM given its weights and biases.\n * The non-linearity is also specified although it may be derived from the unit\n */\nstatic void processBasicLstmUnit(const Array2dRef prevOutput,\n                                 const Array2dRef input,\n                                 const Array3dRef weightsInput,\n                                 const Array3dRef weightsOutput,\n                                 const Array2dRef biases, Array2dRef output,\n                                 unsigned lstmUnitOffset,\n                                 popnn::NonLinearityType nonLinearityType) {\n  const auto batchSize = prevOutput.shape()[0];\n  const auto outputSize = prevOutput.shape()[1];\n\n  /* split weight into two parts:\n   * 1) part which weighs only the previous output\n   * 2) part which weighs only the input\n   */\n  Array2d weightsOutputUnit = weightsOutput[lstmUnitOffset];\n  Array2d weightsInputUnit = weightsInput[lstmUnitOffset];\n\n  gemm::generalMatrixMultiply(prevOutput, weightsOutputUnit, output, output,\n                              1.0, 0, false, false);\n  gemm::generalMatrixMultiply(input, weightsInputUnit, output, output, 1.0, 1.0,\n                              false, false);\n  /* add bias */\n  for (auto b = 0U; b != batchSize; ++b) {\n    for (auto i = 0U; i != outputSize; ++i) {\n      output[b][i] += biases[lstmUnitOffset][i];\n    }\n  }\n\n  /* apply non-linearity */\n  nonLinearity(nonLinearityType, output);\n}\n\n/**\n * Apply mask to gates.\n */\nstatic void applySeqMask(const boost::optional<Array1dRefUNSIGNED> &timeSteps,\n                         const unsigned step, Array2dRef ionput) {\n  if (timeSteps) {\n    const auto batchSize = ionput.shape()[0];\n    const auto outputSize = ionput.shape()[1];\n    for (auto b = 0U; b != batchSize; ++b) {\n      for (auto i = 0U; i != outputSize; ++i) {\n        auto limit = (*timeSteps)[timeSteps->size() > 1 ? b : 0];\n        if (step >= limit) {\n          ionput[b][i] = 0;\n        }\n      }\n    }\n  }\n}\n\n/**\n * Update output for batches that have not reached iteration limit\n */\nstatic void\ncopyIfStepWithinRange(const boost::optional<Array1dRefUNSIGNED> &timeSteps,\n                      const unsigned step,\n                      const boost::optional<Array2dRef> &current,\n                      const Array2dRef update, Array2dRef dst) {\n  const auto batchSize = dst.shape()[0];\n  const auto outputSize = dst.shape()[1];\n  for (auto b = 0U; b != batchSize; ++b) {\n    for (auto i = 0U; i != outputSize; ++i) {\n      auto limit = (*timeSteps)[(timeSteps->size() > 1) ? b : 0];\n      if (step < limit) {\n        dst[b][i] = update[b][i];\n      } else if (current) {\n        dst[b][i] = (*current)[b][i];\n      }\n    }\n  }\n}\n\nstatic void\ncopyIfStepWithinRange(const boost::optional<Array1dRefUNSIGNED> &timeSteps,\n                      const unsigned step, const Array2dRef update,\n                      Array2dRef dst) {\n  copyIfStepWithinRange(timeSteps, step, {}, update, dst);\n}\n\nstatic std::unordered_map<BasicLstmCellUnit, unsigned>\ngetCellMapping(const std::vector<BasicLstmCellUnit> &cellOrder) {\n  // build a mapping of the order that the gates are stored in.\n  std::unordered_map<BasicLstmCellUnit, unsigned> cellMapping;\n  for (unsigned i = 0; i < cellOrder.size(); ++i) {\n    auto gate = cellOrder.at(i);\n    cellMapping.insert(std::make_pair(gate, i));\n  }\n\n  return cellMapping;\n}\n\nvoid poplibs_test::lstm::basicLstmCellForwardPass(\n    const Array3dRef input, const Array2dRef biases,\n    const Array2dRef prevOutput, const Array3dRef weightsInput,\n    const Array3dRef weightsOutput,\n    const boost::optional<Array1dRefUNSIGNED> &timeSteps,\n    Array2dRef prevCellState, Array4dRef state, Array2dRef lastOutput,\n    Array2dRef lastCellState, const std::vector<BasicLstmCellUnit> &cellOrder,\n    const popnn::NonLinearityType activation,\n    const popnn::NonLinearityType recurrentActivation) {\n  const auto sequenceSize = state.shape()[1];\n  const auto batchSize = state.shape()[2];\n  const auto outputSize = state.shape()[3];\n#ifndef NDEBUG\n  const auto inputSize = input.shape()[2];\n#endif\n  assert(state.shape()[0] == LSTM_NUM_FWD_STATES);\n  assert(weightsInput.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(weightsInput.shape()[1] == inputSize);\n  assert(weightsInput.shape()[2] == outputSize);\n  assert(weightsOutput.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(weightsOutput.shape()[1] == outputSize);\n  assert(weightsOutput.shape()[2] == outputSize);\n  assert(prevCellState.shape()[0] == batchSize);\n  assert(prevCellState.shape()[1] == outputSize);\n  assert(biases.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(biases.shape()[1] == outputSize);\n  assert(prevOutput.shape()[0] == batchSize);\n  assert(prevOutput.shape()[1] == outputSize);\n\n  auto cellMapping = getCellMapping(cellOrder);\n\n  Array2d nextOutput = prevOutput;\n  Array2d nextCellState = prevCellState;\n  for (auto s = 0U; s != sequenceSize; ++s) {\n    Array2d inputThisStep = input[s];\n\n    auto cellState = nextCellState;\n\n    /* forget gate */\n    Array2d forgetGate(boost::extents[batchSize][outputSize]);\n    processBasicLstmUnit(nextOutput, inputThisStep, weightsInput, weightsOutput,\n                         biases, forgetGate,\n                         cellMapping.at(BASIC_LSTM_CELL_FORGET_GATE),\n                         recurrentActivation);\n    applySeqMask(timeSteps, s, forgetGate);\n    state[LSTM_FWD_STATE_FORGET_GATE][s] = forgetGate;\n\n    /* input gate */\n    Array2d inputGate(boost::extents[batchSize][outputSize]);\n    processBasicLstmUnit(nextOutput, inputThisStep, weightsInput, weightsOutput,\n                         biases, inputGate,\n                         cellMapping.at(BASIC_LSTM_CELL_INPUT_GATE),\n                         recurrentActivation);\n    applySeqMask(timeSteps, s, inputGate);\n    state[LSTM_FWD_STATE_INPUT_GATE][s] = inputGate;\n\n    /* new candidate contribution to this cell */\n    Array2d candidate(boost::extents[batchSize][outputSize]);\n    processBasicLstmUnit(nextOutput, inputThisStep, weightsInput, weightsOutput,\n                         biases, candidate,\n                         cellMapping.at(BASIC_LSTM_CELL_CANDIDATE), activation);\n    applySeqMask(timeSteps, s, candidate);\n    state[LSTM_FWD_STATE_CAND_TANH][s] = candidate;\n\n    /* output gate */\n    Array2d outputGate(boost::extents[batchSize][outputSize]);\n    processBasicLstmUnit(nextOutput, inputThisStep, weightsInput, weightsOutput,\n                         biases, outputGate,\n                         cellMapping.at(BASIC_LSTM_CELL_OUTPUT_GATE),\n                         recurrentActivation);\n    applySeqMask(timeSteps, s, outputGate);\n    state[LSTM_FWD_STATE_OUTPUT_GATE][s] = outputGate;\n\n    poplibs_test::gemm::hadamardProduct(forgetGate, cellState, cellState);\n    poplibs_test::gemm::hadamardProduct(inputGate, candidate, candidate);\n    poplibs_test::axpby::add(cellState, candidate, cellState);\n\n    /* need to maintain the cell state for next step */\n    Array2d outputThisStep = cellState;\n    nonLinearity(activation, outputThisStep);\n    state[LSTM_FWD_STATE_OUTPUT_TANH][s] = outputThisStep;\n    gemm::hadamardProduct(outputThisStep, outputGate, outputThisStep);\n\n    if (timeSteps) {\n      copyIfStepWithinRange(timeSteps, s, outputThisStep, nextOutput);\n      copyIfStepWithinRange(timeSteps, s, cellState, nextCellState);\n    } else {\n      nextOutput = outputThisStep;\n      nextCellState = cellState;\n    }\n    state[LSTM_FWD_STATE_ACTS_IDX][s] = outputThisStep;\n    state[LSTM_FWD_STATE_CELL_STATE_IDX][s] = cellState;\n  }\n\n  // Save final state\n  lastOutput = nextOutput;\n  lastCellState = nextCellState;\n}\n\nstatic void computeGradients(const Array2dRef weightIn,\n                             const Array2dRef weightPrev, const Array2dRef grad,\n                             Array2dRef gradIn, Array2dRef gradPrev, bool acc) {\n  double k = acc ? 1.0 : 0.0;\n  gemm::generalMatrixMultiply(grad, weightIn, gradIn, gradIn, 1.0, k, false,\n                              true);\n  gemm::generalMatrixMultiply(grad, weightPrev, gradPrev, gradPrev, 1.0, k,\n                              false, true);\n}\n\nvoid poplibs_test::lstm::basicLstmCellBackwardPass(\n    bool outputFullSequence, const Array3dRef weightsInput,\n    const Array3dRef weightsOutput, const Array3dRef gradsNextLayer,\n    const Array2dRef prevCellState, const Array4dRef fwdState,\n    const boost::optional<Array2dRef> initOutputGrad,\n    const boost::optional<Array2dRef> initCellStateGrad,\n    const boost::optional<Array1dRefUNSIGNED> &timeSteps, Array4dRef bwdState,\n    Array3dRef gradsPrevLayer, Array2dRef lastGradLayerOut,\n    Array2dRef lastGradCellState,\n    const std::vector<BasicLstmCellUnit> &cellOrder,\n    const popnn::NonLinearityType activation,\n    const popnn::NonLinearityType recurrentActivation) {\n  const auto sequenceSize = fwdState.shape()[1];\n  const auto batchSize = fwdState.shape()[2];\n  const auto outputSize = fwdState.shape()[3];\n  const auto inputSize = gradsPrevLayer.shape()[2];\n\n  assert(fwdState.shape()[0] == LSTM_NUM_FWD_STATES);\n  assert(bwdState.shape()[0] == LSTM_NUM_BWD_STATES);\n  assert(weightsInput.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(weightsInput.shape()[1] == inputSize);\n  assert(weightsInput.shape()[2] == outputSize);\n  assert(weightsOutput.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(weightsOutput.shape()[1] == outputSize);\n  assert(weightsOutput.shape()[2] == outputSize);\n  assert(prevCellState.shape()[0] == batchSize);\n  assert(prevCellState.shape()[1] == outputSize);\n  assert(fwdState.shape()[1] == sequenceSize);\n  assert(fwdState.shape()[2] == batchSize);\n  assert(fwdState.shape()[3] == outputSize);\n  assert(bwdState.shape()[1] == sequenceSize);\n  assert(bwdState.shape()[2] == batchSize);\n  assert(bwdState.shape()[3] == outputSize);\n  assert(gradsNextLayer.shape()[0] == sequenceSize);\n  assert(gradsNextLayer.shape()[1] == batchSize);\n  assert(gradsNextLayer.shape()[2] == outputSize);\n  assert(gradsPrevLayer.shape()[0] == sequenceSize);\n  assert(gradsPrevLayer.shape()[1] == batchSize);\n\n  auto cellMapping = getCellMapping(cellOrder);\n\n  // gradient of cell state for this step\n  Array2d prevGradCellState(boost::extents[batchSize][outputSize]);\n  if (initCellStateGrad) {\n    prevGradCellState = *initCellStateGrad;\n  } else {\n    matrixZero(prevGradCellState);\n  }\n\n  // gradient of output of this step\n  Array2d gradOutput(boost::extents[batchSize][outputSize]);\n  if (initOutputGrad) {\n    gradOutput = *initOutputGrad;\n  } else {\n    matrixZero(gradOutput);\n  }\n\n  for (auto i = sequenceSize; i != 0; --i) {\n    const auto s = i - 1;\n    Array2d gradOut(boost::extents[batchSize][outputSize]);\n    Array2d sumGradOut(boost::extents[batchSize][outputSize]);\n\n    if (outputFullSequence) {\n      gradOut = gradsNextLayer[s];\n    } else {\n      // Only the last layer receive the gradient\n      if (s == sequenceSize - 1)\n        gradOut = gradsNextLayer[0];\n      else {\n        matrixZero(gradOut);\n      }\n    }\n    auto gradCellState = prevGradCellState;\n    axpby::add(gradOut, gradOutput, sumGradOut);\n\n    Array2d actOutGate = fwdState[LSTM_FWD_STATE_OUTPUT_GATE][s];\n    Array2d gradAtOTanhInp(boost::extents[batchSize][outputSize]);\n    gemm::hadamardProduct(actOutGate, sumGradOut, gradAtOTanhInp);\n\n    Array2d actTanhOutGate = fwdState[LSTM_FWD_STATE_OUTPUT_TANH][s];\n    Array2d gradAtOutGate(boost::extents[batchSize][outputSize]);\n    ;\n\n    gemm::hadamardProduct(actTanhOutGate, sumGradOut, gradAtOutGate);\n\n    bwdNonLinearity(activation, actTanhOutGate, gradAtOTanhInp);\n\n    bwdNonLinearity(recurrentActivation, actOutGate, gradAtOutGate);\n\n    Array2dRef gradAtCellStateSum = gradAtOTanhInp;\n    axpby::add(gradAtOTanhInp, gradCellState, gradAtCellStateSum);\n\n    Array2d actInpGate = fwdState[LSTM_FWD_STATE_INPUT_GATE][s];\n    Array2d gradAtCand(boost::extents[batchSize][outputSize]);\n    ;\n    gemm::hadamardProduct(actInpGate, gradAtCellStateSum, gradAtCand);\n    Array2d actCand = fwdState[LSTM_FWD_STATE_CAND_TANH][s];\n    Array2d gradAtInpGate(boost::extents[batchSize][outputSize]);\n    ;\n    gemm::hadamardProduct(actCand, gradAtCellStateSum, gradAtInpGate);\n    bwdNonLinearity(activation, actCand, gradAtCand);\n    bwdNonLinearity(recurrentActivation, actInpGate, gradAtInpGate);\n\n    Array2d actForgetGate = fwdState[LSTM_FWD_STATE_FORGET_GATE][s];\n    gemm::hadamardProduct(actForgetGate, gradAtCellStateSum, gradCellState);\n\n    Array2d pCellAct(boost::extents[batchSize][outputSize]);\n\n    if (s == 0) {\n      pCellAct = prevCellState;\n    } else {\n      pCellAct = fwdState[LSTM_FWD_STATE_CELL_STATE_IDX][s - 1];\n    }\n    Array2d gradAtForgetGate(boost::extents[batchSize][outputSize]);\n    ;\n\n    gemm::hadamardProduct(pCellAct, gradAtCellStateSum, gradAtForgetGate);\n    bwdNonLinearity(recurrentActivation, actForgetGate, gradAtForgetGate);\n\n    Array2d gradIn(boost::extents[batchSize][inputSize]);\n    ;\n    Array2d weightsInUnit =\n        weightsInput[cellMapping.at(BASIC_LSTM_CELL_FORGET_GATE)];\n    Array2d weightsOutUnit =\n        weightsOutput[cellMapping.at(BASIC_LSTM_CELL_FORGET_GATE)];\n    Array2d nextGradOut(boost::extents[batchSize][outputSize]);\n    computeGradients(weightsInUnit, weightsOutUnit, gradAtForgetGate, gradIn,\n                     nextGradOut, false);\n    weightsInUnit = weightsInput[cellMapping.at(BASIC_LSTM_CELL_INPUT_GATE)];\n    weightsOutUnit = weightsOutput[cellMapping.at(BASIC_LSTM_CELL_INPUT_GATE)];\n    computeGradients(weightsInUnit, weightsOutUnit, gradAtInpGate, gradIn,\n                     nextGradOut, true);\n    weightsInUnit = weightsInput[cellMapping.at(BASIC_LSTM_CELL_OUTPUT_GATE)];\n    weightsOutUnit = weightsOutput[cellMapping.at(BASIC_LSTM_CELL_OUTPUT_GATE)];\n    computeGradients(weightsInUnit, weightsOutUnit, gradAtOutGate, gradIn,\n                     nextGradOut, true);\n    weightsInUnit = weightsInput[cellMapping.at(BASIC_LSTM_CELL_CANDIDATE)];\n    weightsOutUnit = weightsOutput[cellMapping.at(BASIC_LSTM_CELL_CANDIDATE)];\n    computeGradients(weightsInUnit, weightsOutUnit, gradAtCand, gradIn,\n                     nextGradOut, true);\n\n    if (timeSteps) {\n      if (outputFullSequence) {\n        copyIfStepWithinRange(timeSteps, s, nextGradOut, gradOutput);\n      } else {\n        copyIfStepWithinRange(timeSteps, s, sumGradOut, nextGradOut,\n                              gradOutput);\n      }\n      copyIfStepWithinRange(timeSteps, s, gradCellState, prevGradCellState);\n    } else {\n      gradOutput = nextGradOut;\n      prevGradCellState = gradCellState;\n    }\n    gradsPrevLayer[s] = gradIn;\n\n    // save bwd state for weight update\n    bwdState[BASIC_LSTM_CELL_FORGET_GATE][s] = gradAtForgetGate;\n    bwdState[BASIC_LSTM_CELL_INPUT_GATE][s] = gradAtInpGate;\n    bwdState[BASIC_LSTM_CELL_OUTPUT_GATE][s] = gradAtOutGate;\n    bwdState[BASIC_LSTM_CELL_CANDIDATE][s] = gradAtCand;\n  }\n  lastGradLayerOut = gradOutput;\n  lastGradCellState = prevGradCellState;\n}\n\nvoid poplibs_test::lstm::basicLstmCellParamUpdate(\n    const Array3dRef prevLayerActs, const Array4dRef fwdState,\n    const Array2dRef outputActsInit, const Array4dRef bwdState,\n    Array3dRef weightsInputDeltas, Array3dRef weightsOutputDeltas,\n    Array2dRef biasDeltas, const std::vector<BasicLstmCellUnit> &cellOrder) {\n  const auto sequenceSize = prevLayerActs.shape()[0];\n  const auto batchSize = prevLayerActs.shape()[1];\n  const auto inputSize = prevLayerActs.shape()[2];\n  const auto outputSize = fwdState.shape()[3];\n\n  assert(fwdState.shape()[0] == LSTM_NUM_FWD_STATES);\n  assert(fwdState.shape()[1] == sequenceSize);\n  assert(fwdState.shape()[2] == batchSize);\n  assert(outputActsInit.shape()[0] == batchSize);\n  assert(outputActsInit.shape()[1] == outputSize);\n  assert(bwdState.shape()[0] == LSTM_NUM_BWD_STATES);\n  assert(bwdState.shape()[1] == sequenceSize);\n  assert(bwdState.shape()[2] == batchSize);\n  assert(bwdState.shape()[3] == outputSize);\n  assert(weightsInputDeltas.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(weightsInputDeltas.shape()[1] == inputSize);\n  assert(weightsInputDeltas.shape()[2] == outputSize);\n  assert(weightsOutputDeltas.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(weightsOutputDeltas.shape()[1] == outputSize);\n  assert(weightsOutputDeltas.shape()[2] == outputSize);\n  assert(biasDeltas.shape()[0] == BASIC_LSTM_CELL_NUM_UNITS);\n  assert(biasDeltas.shape()[1] == outputSize);\n\n  auto cellMapping = getCellMapping(cellOrder);\n\n  for (auto it = weightsInputDeltas.data(),\n            end = weightsInputDeltas.data() + weightsInputDeltas.num_elements();\n       it != end; ++it) {\n    *it = 0;\n  }\n  for (auto it = weightsOutputDeltas.data(),\n            end =\n                weightsOutputDeltas.data() + weightsOutputDeltas.num_elements();\n       it != end; ++it) {\n    *it = 0;\n  }\n  for (auto it = biasDeltas.data(),\n            end = biasDeltas.data() + biasDeltas.num_elements();\n       it != end; ++it) {\n    *it = 0;\n  }\n\n  for (auto i = sequenceSize; i != 0; --i) {\n    const auto s = i - 1;\n    Array2d outActs(boost::extents[batchSize][outputSize]);\n    if (s == 0) {\n      outActs = outputActsInit;\n    } else {\n      outActs = fwdState[LSTM_FWD_STATE_ACTS_IDX][s - 1];\n    }\n    Array2d inActs = prevLayerActs[s];\n    for (auto i = 0; i != BASIC_LSTM_CELL_NUM_UNITS; ++i) {\n      const auto unit = static_cast<BasicLstmCellUnit>(i);\n\n      Array2d grad = bwdState[i][s];\n      Array2d wInputDeltasUnit(boost::extents[inputSize][outputSize]);\n\n      gemm::generalMatrixMultiply(inActs, grad, wInputDeltasUnit,\n                                  wInputDeltasUnit, 1.0, 0, true, false);\n      for (auto ic = 0u; ic != inputSize; ++ic) {\n        for (auto oc = 0u; oc != outputSize; ++oc) {\n          weightsInputDeltas[cellMapping.at(unit)][ic][oc] +=\n              wInputDeltasUnit[ic][oc];\n        }\n      }\n      Array2d wOutputDeltasUnit(boost::extents[outputSize][outputSize]);\n\n      gemm::generalMatrixMultiply(outActs, grad, wOutputDeltasUnit,\n                                  wOutputDeltasUnit, 1.0, 0, true, false);\n      for (auto oc1 = 0u; oc1 != outputSize; ++oc1) {\n        for (auto oc2 = 0u; oc2 != outputSize; ++oc2) {\n          weightsOutputDeltas[cellMapping.at(unit)][oc1][oc2] +=\n              wOutputDeltasUnit[oc1][oc2];\n        }\n      }\n\n      for (auto oc = 0u; oc != outputSize; ++oc) {\n        for (auto b = 0u; b != batchSize; ++b) {\n          biasDeltas[cellMapping.at(unit)][oc] += grad[b][oc];\n        }\n      }\n    }\n  }\n}\n", "meta": {"hexsha": "06c01b7f99f2742b96426b542e12645fca4c2e1f", "size": 19672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/poplibs_test/Lstm.cpp", "max_stars_repo_name": "graphcore/poplibs", "max_stars_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 95.0, "max_stars_repo_stars_event_min_datetime": "2020-07-06T17:11:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T14:42:28.000Z", "max_issues_repo_path": "lib/poplibs_test/Lstm.cpp", "max_issues_repo_name": "graphcore/poplibs", "max_issues_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/poplibs_test/Lstm.cpp", "max_forks_repo_name": "graphcore/poplibs", "max_forks_repo_head_hexsha": "3fe5a3ecafe995eddb72675d1b4a7af8a622009e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T12:32:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T14:58:45.000Z", "avg_line_length": 39.9026369168, "max_line_length": 80, "alphanum_fraction": 0.6828995527, "num_tokens": 5265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581049086031, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4473002893189437}}
{"text": "#include <queue>\n#include <unordered_set>\n#include <boost/math/constants/constants.hpp>\n#include <CGAL/boost/graph/Euler_operations.h>\n#include <Euclid/Geometry/TriMeshGeometry.h>\n#include <Euclid/Math/Numeric.h>\n\nnamespace Euclid\n{\n\nnamespace _impl\n{\n\ntemplate<typename Mesh>\nvoid init_queue(const Mesh& mesh,\n                std::queue<edge_t<Mesh>>& queue,\n                std::vector<bool>& inqueue)\n{\n    auto eimap = get(boost::edge_index, mesh);\n    inqueue.resize(num_edges(mesh), false);\n    for (auto e : edges(mesh)) {\n        if (!is_delaunay(mesh, e)) {\n            queue.push(e);\n            inqueue[get(eimap, e)] = true;\n        }\n    }\n}\n\ntemplate<typename Mesh>\nvoid init_physical_edges(const Mesh& mesh, std::vector<bool>& physical)\n{\n    auto eimap = get(boost::edge_index, mesh);\n    physical.resize(num_edges(mesh), true);\n    for (auto e : edges(mesh)) {\n        if (eq_almost(dihedral_angle(e, mesh),\n                      boost::math::constants::pi<FT_t<Mesh>>())) {\n            physical[get(eimap, e)] = false;\n        }\n    }\n}\n\ntemplate<typename Mesh, typename Visitor>\nvoid flip(Mesh& mesh,\n          Visitor& visitor,\n          edge_t<Mesh> e,\n          std::queue<edge_t<Mesh>>& queue,\n          std::vector<bool>& inqueue)\n{\n    auto eimap = get(boost::edge_index, mesh);\n    auto h = halfedge(e, mesh);\n    auto ho = opposite(h, mesh);\n    auto ha = next(h, mesh);\n    auto hb = next(ha, mesh);\n    auto hc = next(ho, mesh);\n    auto hd = next(hc, mesh);\n    auto ea = edge(ha, mesh);\n    auto eb = edge(hb, mesh);\n    auto ec = edge(hc, mesh);\n    auto ed = edge(hd, mesh);\n    visitor.on_flipping(mesh, e);\n    CGAL::Euler::flip_edge(h, mesh);\n    visitor.on_flipped(mesh, e);\n    if (!inqueue[get(eimap, ea)]) {\n        queue.push(ea);\n        inqueue[get(eimap, ea)] = true;\n    }\n    if (!inqueue[get(eimap, eb)]) {\n        queue.push(eb);\n        inqueue[get(eimap, eb)] = true;\n    }\n    if (!inqueue[get(eimap, ec)]) {\n        queue.push(ec);\n        inqueue[get(eimap, ec)] = true;\n    }\n    if (!inqueue[get(eimap, ed)]) {\n        queue.push(ed);\n        inqueue[get(eimap, ed)] = true;\n    }\n}\n\ntemplate<typename Mesh>\nbool is_flip_topologically_ok(const Mesh& mesh, edge_t<Mesh>& e)\n{\n    auto h = halfedge(e, mesh);\n    return !halfedge(target(next(h, mesh), mesh),\n                     target(next(opposite(h, mesh), mesh), mesh),\n                     mesh)\n                .second;\n}\n\ntemplate<typename Mesh, typename Visitor>\nvoid split(Mesh& mesh,\n           Visitor& visitor,\n           edge_t<Mesh> e,\n           std::queue<edge_t<Mesh>>& queue,\n           std::vector<bool>& inqueue,\n           std::vector<bool>& physical_edges,\n           std::unordered_set<vertex_t<Mesh>>& split_vertices)\n{\n    auto hpq = halfedge(e, mesh);\n    auto hqp = opposite(hpq, mesh);\n    auto hqv = next(hpq, mesh);\n    auto hvp = prev(hpq, mesh);\n    auto hpu = next(hqp, mesh);\n    auto huq = prev(hqp, mesh);\n\n    // do edge split\n    visitor.on_splitting(mesh, e);\n    auto hps = CGAL::Euler::split_edge(hpq, mesh);\n    auto hsq = next(hps, mesh);\n    auto hqs = opposite(hsq, mesh);\n    auto hsv = CGAL::Euler::split_face(hps, hqv, mesh);\n    auto hsu = CGAL::Euler::split_face(hqs, hpu, mesh);\n    auto vs = target(hps, mesh);\n\n    SplitSite<Mesh> site;\n    site.epq = e;\n    site.vs = vs;\n    site.hps = hps;\n    site.hqs = opposite(hsq, mesh);\n    site.hvs = opposite(hsv, mesh);\n    site.hus = opposite(hsu, mesh);\n    visitor.on_split(mesh, site);\n\n    // update realted buffers\n    auto eimap = get(boost::edge_index, mesh);\n    auto eqv = edge(hqv, mesh);\n    if (!inqueue[get(eimap, eqv)]) {\n        queue.push(eqv);\n        inqueue[get(eimap, eqv)] = true;\n    }\n    auto evp = edge(hvp, mesh);\n    if (!inqueue[get(eimap, evp)]) {\n        queue.push(evp);\n        inqueue[get(eimap, evp)] = true;\n    }\n    auto epu = edge(hpu, mesh);\n    if (!inqueue[get(eimap, epu)]) {\n        queue.push(epu);\n        inqueue[get(eimap, epu)] = true;\n    }\n    auto euq = edge(huq, mesh);\n    if (!inqueue[get(eimap, euq)]) {\n        queue.push(euq);\n        inqueue[get(eimap, euq)] = true;\n    }\n    auto esp = edge(hps, mesh);\n    auto esq = edge(hsq, mesh);\n    auto esu = edge(hsu, mesh);\n    auto esv = edge(hsv, mesh);\n    // auto isp = get(eimap, esp);\n    // auto isq = get(eimap, esq);\n    // auto isu = get(eimap, esu);\n    // auto isv = get(eimap, esv);\n    queue.push(esp);\n    queue.push(esq);\n    queue.push(esu);\n    queue.push(esv);\n    inqueue[get(eimap, esq)] = true;\n    inqueue.push_back(true);         // esp\n    inqueue.push_back(true);         // esv\n    inqueue.push_back(true);         // esu\n    physical_edges.push_back(true);  // esp\n    physical_edges.push_back(false); // esv\n    physical_edges.push_back(false); // esu\n    split_vertices.insert(vs);\n\n    // determine new vertex position\n    auto vpmap = get(boost::vertex_point, mesh);\n    auto vp = target(hvp, mesh);\n    auto vq = target(huq, mesh);\n    auto pp = get(vpmap, vp);\n    auto pq = get(vpmap, vq);\n    auto pm = CGAL::midpoint(pp, pq);\n    auto lm = length(pp - pm);\n    auto l = 0.0;\n    if (lm > 1.5) {\n        l = 2.0;\n        while (l < lm) {\n            l *= 2.0;\n        }\n        if (std::abs(l - lm) > std::abs(l * 0.5 - lm)) {\n            l *= 0.5;\n        }\n    }\n    else if (lm < 0.75) {\n        l = 0.5;\n        while (l > lm) {\n            l *= 0.5;\n        }\n        if (std::abs(l - lm) > std::abs(l * 2.0 - lm)) {\n            l *= 2.0;\n        }\n    }\n    else {\n        l = 1.0;\n    }\n    if (split_vertices.find(vp) == split_vertices.end()) {\n        auto ps = pp + normalized(pm - pp) * l;\n        put(vpmap, vs, ps);\n    }\n    else {\n        auto ps = pq + normalized(pm - pq) * l;\n        put(vpmap, vs, ps);\n    }\n}\n\ntemplate<typename Mesh, typename Visitor>\nvoid remesh_delaunay_simple_flip(Mesh& mesh, Visitor& visitor)\n{\n    visitor.on_started(mesh);\n    auto eimap = get(boost::edge_index, mesh);\n    std::queue<edge_t<Mesh>> queue;\n    std::vector<bool> inqueue;\n    init_queue(mesh, queue, inqueue);\n    while (!queue.empty()) {\n        auto e = queue.front();\n        queue.pop();\n        inqueue[get(eimap, e)] = false;\n        if (!is_delaunay(mesh, e) && is_flip_topologically_ok(mesh, e)) {\n            flip(mesh, visitor, e, queue, inqueue);\n        }\n        else {\n            visitor.on_nonflippable(mesh, e);\n        }\n    }\n    visitor.on_finished(mesh);\n}\n\ntemplate<typename Mesh, typename Visitor>\nvoid remesh_delaunay_geometry_preserving(Mesh& mesh, Visitor& visitor)\n{\n    visitor.on_started(mesh);\n    auto eimap = get(boost::edge_index, mesh);\n    std::queue<edge_t<Mesh>> queue;\n    std::vector<bool> inqueue;\n    init_queue(mesh, queue, inqueue);\n    std::vector<bool> physical_edges;\n    init_physical_edges(mesh, physical_edges);\n    std::unordered_set<vertex_t<Mesh>> split_vertices;\n    while (!queue.empty()) {\n        auto e = queue.front();\n        queue.pop();\n        inqueue[get(eimap, e)] = false;\n        if (!is_delaunay(mesh, e)) {\n            if (!physical_edges[get(eimap, e)]) {\n                flip(mesh, visitor, e, queue, inqueue);\n            }\n            else {\n                visitor.on_nonflippable(mesh, e);\n                split(mesh,\n                      visitor,\n                      e,\n                      queue,\n                      inqueue,\n                      physical_edges,\n                      split_vertices);\n            }\n        }\n    }\n    visitor.on_finished(mesh);\n}\n\ntemplate<typename Mesh, typename Visitor>\nvoid remesh_delaunay_feature_preserving(Mesh& mesh,\n                                        Visitor& visitor,\n                                        double threshold)\n{\n    visitor.on_started(mesh);\n    auto eimap = get(boost::edge_index, mesh);\n    std::queue<edge_t<Mesh>> queue;\n    std::vector<bool> inqueue;\n    init_queue(mesh, queue, inqueue);\n    std::vector<bool> physical_edges;\n    init_physical_edges(mesh, physical_edges);\n    std::unordered_set<vertex_t<Mesh>> split_vertices;\n    while (!queue.empty()) {\n        auto e = queue.front();\n        queue.pop();\n        inqueue[get(eimap, e)] = false;\n        if (!is_delaunay(mesh, e)) {\n            if (!physical_edges[get(eimap, e)] ||\n                dihedral_angle(e, mesh) > threshold) {\n                flip(mesh, visitor, e, queue, inqueue);\n            }\n            else {\n                visitor.on_nonflippable(mesh, e);\n                split(mesh,\n                      visitor,\n                      e,\n                      queue,\n                      inqueue,\n                      physical_edges,\n                      split_vertices);\n            }\n        }\n    }\n    visitor.on_finished(mesh);\n}\n\n} // namespace _impl\n\ntemplate<typename Mesh>\nbool is_delaunay(const Mesh& mesh, double eps)\n{\n    for (auto e : edges(mesh)) {\n        if (!is_delaunay(mesh, e, eps)) {\n            return false;\n        }\n    }\n    return true;\n}\n\ntemplate<typename Mesh>\nbool is_delaunay(const Mesh& mesh, edge_t<Mesh> e, double eps)\n{\n    auto cot = static_cast<double>(cotangent_weight(e, mesh));\n    return cot > eps;\n}\n\ntemplate<typename Mesh>\nvoid remesh_delaunay(Mesh& mesh,\n                     RemeshDelaunayScheme scheme,\n                     double dihedral_angle)\n{\n    RemeshDelaunayVisitor<Mesh> visitor;\n    remesh_delaunay(mesh, visitor, scheme, dihedral_angle);\n}\n\ntemplate<typename Mesh, typename Visitor>\nvoid remesh_delaunay(Mesh& mesh,\n                     Visitor& visitor,\n                     RemeshDelaunayScheme scheme,\n                     double dihedral_angle)\n{\n    switch (scheme) {\n    case RemeshDelaunayScheme::FeaturePreserving:\n        _impl::remesh_delaunay_feature_preserving(\n            mesh,\n            visitor,\n            boost::math::constants::pi<double>() -\n                dihedral_angle * boost::math::constants::degree<double>());\n        break;\n    case RemeshDelaunayScheme::GeometryPreserving:\n        _impl::remesh_delaunay_geometry_preserving(mesh, visitor);\n        break;\n    case RemeshDelaunayScheme::SimpleFlip:\n    default:\n        _impl::remesh_delaunay_simple_flip(mesh, visitor);\n        break;\n    }\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "8d2ff8e9c7de58f7974068a6d861ae0974c0b4ff", "size": 10197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/SurfaceDelaunay/src/DelaunayMesh.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "include/Euclid/SurfaceDelaunay/src/DelaunayMesh.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Euclid/SurfaceDelaunay/src/DelaunayMesh.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 28.723943662, "max_line_length": 75, "alphanum_fraction": 0.5542806708, "num_tokens": 2710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4473002865949462}}
{"text": "﻿#define _USE_MATH_DEFINES\n\n#include <cstdlib>\n#include <iostream>\n#include <regex>\n#include <fstream>\n#include <iterator>\n#include <random>\n#include <experimental/filesystem>\n#include <cmath>\n#include <string>\n\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/lock_guard.hpp>\n\n#include \"Macros.h\"\n#include \"StandardLibrary.h\"\n#include \"DataTypes/Ops/Ops.h\"\n#include \"DataTypes/Ops/StringOps.h\"\n#include \"DataTypes/Ops/ArrayOps.h\"\n#include \"DataTypes/Ops/IntegerOps.h\"\n#include \"Utils/FileStreamHelper.h\"\n\nnamespace FPTL\n{\n\tnamespace Runtime\n\t{\n\t\tnamespace {\n\t\t\tvoid id(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\t// Копируем данные аргументы от начала фрейма.\n\t\t\t\tfor (size_t i = 0; i < aCtx.argNum; ++i)\n\t\t\t\t{\n\t\t\t\t\taCtx.push(aCtx.getArg(i));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvoid tupleLength(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\taCtx.push(DataBuilders::createInt(static_cast<long long>(aCtx.argNum)));\n\t\t\t}\n\n\t\t\tvoid Not(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\n\t\t\t\taCtx.push(DataBuilders::createBoolean(!arg.getOps()->toInt(arg)));\n\t\t\t}\n\n\t\t\tvoid And(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(DataBuilders::createBoolean((lhs.getOps()->toInt(lhs) * rhs.getOps()->toInt(rhs))));\n\t\t\t}\n\n\t\t\tvoid Or(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(DataBuilders::createBoolean((lhs.getOps()->toInt(lhs) + rhs.getOps()->toInt(rhs))));\n\t\t\t}\n\n\t\t\tvoid Xor(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(DataBuilders::createBoolean((lhs.getOps()->toInt(lhs) ^ rhs.getOps()->toInt(rhs))));\n\t\t\t}\n\n\t\t\tvoid equal(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(lhs.getOps()->combine(rhs.getOps())->equal(lhs, rhs));\n\t\t\t}\n\n\t\t\tvoid notEqual(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(\n\t\t\t\t\tDataBuilders::createBoolean(\n\t\t\t\t\t\t!lhs.getOps()->combine(rhs.getOps())->equal(lhs, rhs).mIntVal\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tvoid greater(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(lhs.getOps()->combine(rhs.getOps())->greater(lhs, rhs));\n\t\t\t}\n\n\t\t\tvoid greaterOrEqual(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(\n\t\t\t\t\tDataBuilders::createBoolean(\n\t\t\t\t\t\t!lhs.getOps()->combine(rhs.getOps())->less(lhs, rhs).mIntVal\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tvoid less(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(lhs.getOps()->combine(rhs.getOps())->less(lhs, rhs));\n\t\t\t}\n\n\t\t\tvoid lessOrEqual(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(\n\t\t\t\t\tDataBuilders::createBoolean(\n\t\t\t\t\t\t!lhs.getOps()->combine(rhs.getOps())->greater(lhs, rhs).mIntVal\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tvoid add(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(lhs.getOps()->combine(rhs.getOps())->add(lhs, rhs));\n\t\t\t}\n\n\t\t\tvoid sub(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(lhs.getOps()->combine(rhs.getOps())->sub(lhs, rhs));\n\t\t\t}\n\n\t\t\tvoid mul(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(lhs.getOps()->combine(rhs.getOps())->mul(lhs, rhs));\n\t\t\t}\n\n\t\t\tvoid div(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(lhs.getOps()->combine(rhs.getOps())->div(lhs, rhs));\n\t\t\t}\n\n\t\t\tvoid mod(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & lhs = aCtx.getArg(0);\n\t\t\t\tconst auto & rhs = aCtx.getArg(1);\n\n\t\t\t\taCtx.push(lhs.getOps()->combine(rhs.getOps())->mod(lhs, rhs));\n\t\t\t}\n\n\t\t\t// Генерирует случайное вещественное число в диапазоне от 0 до 1.\n\t\t\tvoid rand(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tstatic thread_local std::random_device rd;\n\t\t\t\tstatic thread_local std::mt19937_64 gen(rd());\n\t\t\t\tstatic std::uniform_real_distribution realDistrib;\n\t\t\t\taCtx.push(DataBuilders::createDouble(realDistrib(gen)));\n\t\t\t}\n\n\t\t\tvoid sqrt(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\t\t\t\taCtx.push(DataBuilders::createDouble(std::sqrt(arg.getOps()->toDouble(arg))));\n\t\t\t}\n\n\t\t\tvoid sin(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\t\t\t\taCtx.push(DataBuilders::createDouble(std::sin(arg.getOps()->toDouble(arg))));\n\t\t\t}\n\n\t\t\tvoid cos(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\t\t\t\taCtx.push(DataBuilders::createDouble(std::cos(arg.getOps()->toDouble(arg))));\n\t\t\t}\n\n\t\t\tvoid tan(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\t\t\t\taCtx.push(DataBuilders::createDouble(std::tan(arg.getOps()->toDouble(arg))));\n\t\t\t}\n\n\t\t\tvoid asin(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\t\t\t\taCtx.push(DataBuilders::createDouble(std::asin(arg.getOps()->toDouble(arg))));\n\t\t\t}\n\n\t\t\tvoid atan(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\t\t\t\taCtx.push(DataBuilders::createDouble(std::atan(arg.getOps()->toDouble(arg))));\n\t\t\t}\n\n\t\t\tvoid round(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\t\t\t\taCtx.push(DataBuilders::createDouble(std::floor(arg.getOps()->toDouble(arg) + 0.5)));\n\t\t\t}\n\n\t\t\tvoid log(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\t\t\t\taCtx.push(DataBuilders::createDouble(std::log(arg.getOps()->toDouble(arg))));\n\t\t\t}\n\n\t\t\tvoid exp(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\t\t\t\taCtx.push(DataBuilders::createDouble(std::exp(arg.getOps()->toDouble(arg))));\n\t\t\t}\n\n\t\t\tvoid loadPi(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\taCtx.push(DataBuilders::createDouble(M_PI));\n\t\t\t}\n\n\t\t\tvoid loadE(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\taCtx.push(DataBuilders::createDouble(M_E));\n\t\t\t}\n\n\t\t\tvoid abs(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\t\t\t\taCtx.push(arg.getOps()->abs(arg));\n\t\t\t}\n\n\t\t\tvoid print(const SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tstatic boost::mutex outputMutex;\n\t\t\t\tboost::lock_guard<boost::mutex> guard(outputMutex);\n\n\t\t\t\taCtx.print(std::cout);\n\t\t\t}\n\n\t\t\tvoid printType(const SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tstatic boost::mutex outputMutex;\n\t\t\t\tboost::lock_guard<boost::mutex> guard(outputMutex);\n\n\t\t\t\taCtx.printTypes(std::cout);\n\t\t\t}\n\n\t\t\t// Преобразование в строку.\n\t\t\tvoid toString(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tstd::stringstream strStream;\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\n\t\t\t\targ.getOps()->print(arg, strStream);\n\n\t\t\t\taCtx.push(StringBuilder::create(aCtx, strStream.str()));\n\t\t\t}\n\n\t\t\t// Преобразование в вещественное число.\n\t\t\tvoid toInteger(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\n\t\t\t\taCtx.push(DataBuilders::createInt(arg.getOps()->toInt(arg)));\n\t\t\t}\n\n\t\t\t// Преобразование в целое число.\n\t\t\tvoid toDouble(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\n\t\t\t\taCtx.push(DataBuilders::createDouble(arg.getOps()->toDouble(arg)));\n\t\t\t}\n\n\t\t\t// Конкатенация строк.\n\t\t\tvoid concat(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tsize_t len = 0;\n\t\t\t\tfor (size_t i = 0; i < aCtx.argNum; ++i)\n\t\t\t\t{\n\t\t\t\t\tconst auto & arg = aCtx.getArg(i);\n\t\t\t\t\tconst auto inStr = arg.getOps()->toString(arg);\n\t\t\t\t\tlen += inStr->length();\n\t\t\t\t}\n\n\t\t\t\tconst auto val = StringBuilder::create(aCtx, len);\n\t\t\t\tconst auto str = val.mString->getChars();\n\t\t\t\tsize_t curPos = 0;\n\n\t\t\t\tfor (size_t i = 0; i < aCtx.argNum; ++i)\n\t\t\t\t{\n\t\t\t\t\tconst auto & arg = aCtx.getArg(i);\n\t\t\t\t\tconst auto inStr = arg.getOps()->toString(arg);\n\t\t\t\t\tstd::memcpy(str + curPos, inStr->getChars(), inStr->length());\n\t\t\t\t\tcurPos += inStr->length();\n\t\t\t\t}\n\n\t\t\t\taCtx.push(val);\n\t\t\t}\n\n\t\t\t// Длина строки.\n\t\t\tvoid length(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\t\t\t\tconst auto str = arg.getOps()->toString(arg);\n\n\t\t\t\taCtx.push(DataBuilders::createInt(static_cast<long long>(str->length())));\n\t\t\t}\n\n\t\t\t// Поиск по регулярному выражению.\n\t\t\tvoid search(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg0 = aCtx.getArg(0);\n\t\t\t\tconst auto & arg1 = aCtx.getArg(1);\n\n\t\t\t\tconst auto src = arg0.getOps()->toString(arg0);\n\t\t\t\tconst auto regEx = arg1.getOps()->toString(arg1);\n\n\t\t\t\tstd::regex rx(regEx->str());\n\t\t\t\tstd::cmatch matchResults;\n\n\t\t\t\tif (std::regex_search(static_cast<const char *>(src->getChars()), static_cast<const char *>(src->getChars() + src->length()), matchResults, rx))\n\t\t\t\t{\n\t\t\t\t\tfor (size_t i = 0; i < rx.mark_count(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto & m = matchResults[i + 1];\n\t\t\t\t\t\tauto val = StringBuilder::create(aCtx, src, m.first - src->contents(), m.second - src->contents());\n\t\t\t\t\t\taCtx.push(val);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\taCtx.push(DataBuilders::createUndefinedValue());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Проверка соответствия по регулярному выражению.\n\t\t\tvoid match(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg0 = aCtx.getArg(0);\n\t\t\t\tconst auto & arg1 = aCtx.getArg(1);\n\n\t\t\t\tconst auto src = arg0.getOps()->toString(arg0);\n\t\t\t\tconst auto regEx = arg1.getOps()->toString(arg1);\n\n\t\t\t\tstd::regex rx(regEx->str());\n\t\t\t\tstd::cmatch match;\n\n\t\t\t\tif (std::regex_match(static_cast<const char *>(src->getChars()), static_cast<const char *>(src->getChars() + src->length()), match, rx))\n\t\t\t\t{\n\t\t\t\t\tfor (size_t i = 0; i < rx.mark_count(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst auto & m = match[i + 1];\n\t\t\t\t\t\tconst auto val = StringBuilder::create(aCtx, src, m.first - src->contents(), m.second - src->contents());\n\t\t\t\t\t\taCtx.push(val);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\taCtx.push(DataBuilders::createUndefinedValue());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Замена по регулярному выражению.\n\t\t\tvoid replace(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg0 = aCtx.getArg(0);\n\t\t\t\tconst auto & arg1 = aCtx.getArg(1);\n\t\t\t\tconst auto & arg2 = aCtx.getArg(2);\n\n\n\t\t\t\tconst auto src = arg0.getOps()->toString(arg0);\n\t\t\t\tconst auto pattern = arg1.getOps()->toString(arg1);\n\t\t\t\tconst auto format = arg2.getOps()->toString(arg2);\n\n\t\t\t\tconst std::regex rx(pattern->str());\n\t\t\t\tconst auto result = std::regex_replace(src->str(), rx, format->str());\n\t\t\t\taCtx.push(StringBuilder::create(aCtx, result));\n\t\t\t}\n\n\t\t\t// Выделение лексемы с начала строки.\n\t\t\tvoid getToken(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arg0 = aCtx.getArg(0);\n\t\t\t\tconst auto & arg1 = aCtx.getArg(1);\n\n\t\t\t\tconst auto src = arg0.getOps()->toString(arg0);\n\t\t\t\tconst auto pattern = arg1.getOps()->toString(arg1);\n\n\t\t\t\tconst std::regex rx(\"^(?:\\\\s*)(\" + pattern->str() + \")\");\n\n\t\t\t\tstd::cmatch matchResults;\n\n\t\t\t\tconst auto first = static_cast<const char *>(src->getChars());\n\t\t\t\tconst auto last = static_cast<const char *>(src->getChars() + src->length());\n\n\t\t\t\tif (std::regex_search(first, last, matchResults, rx))\n\t\t\t\t{\n\t\t\t\t\tconst auto prefix = StringBuilder::create(aCtx, src, matchResults[1].first - src->contents(), matchResults[1].second - src->contents());\n\t\t\t\t\taCtx.push(prefix);\n\n\t\t\t\t\tconst auto suffix = StringBuilder::create(aCtx, src, matchResults.suffix().first - src->contents(), matchResults.suffix().second - src->contents());\n\t\t\t\t\taCtx.push(suffix);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\taCtx.push(DataBuilders::createUndefinedValue());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Чтение содержимого файла.\n\t\t\tvoid readFile(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\t// Проверяем имя файла.\n\t\t\t\tconst auto & arg = aCtx.getArg(0);\n\n\t\t\t\tconst auto fileName = arg.getOps()->toString(arg);\n\t\t\t\t\n\t\t\t\tDataValue val;\n\t\t\t\tstd::string errMsg = \"\";\n\t\t\t\tstd::fstream input;\n\t\t\t\tinput.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\t// Вычисляем размер файла.\n\t\t\t\t\tconst auto begin = input.tellg();\n\t\t\t\t\tinput.seekg(0, std::ios::end);\n\t\t\t\t\tconst auto size = input.tellg() - begin;\n\t\t\t\t\tinput.seekg(0, std::ios::beg);\n\n\t\t\t\t\t// Резервируем память под файл.\t\t\t\t\t\n\t\t\t\t\tval = StringBuilder::create(aCtx, size);\n\t\t\t\t\t// Читаем данные.\n\t\t\t\t\tstd::copy(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>(), val.mString->getChars());\n\t\t\t\t\tinput.close();\n\t\t\t\t}\n\t\t\t\tcatch (const std::ios_base::failure& exc)\n\t\t\t\t{\n\t\t\t\t\tval = DataBuilders::createUndefinedValue();\n\t\t\t\t\terrMsg = Utils::getfStreamError(input);\n\t\t\t\t\tif (errMsg == \"\") errMsg = exc.what();\n\t\t\t\t}\n\t\t\t\taCtx.push(val);\n\t\t\t\taCtx.push(StringBuilder::create(aCtx, errMsg));\n\t\t\t}\n\n\t\t\tvoid writeToFile(SExecutionContext & aCtx, std::ios::openmode mode)\n\t\t\t{\n\t\t\t\t// Проверяем имя файла.\n\t\t\t\tconst auto & val = aCtx.getArg(0);\n\t\t\t\tconst auto & file = aCtx.getArg(1);\n\n\t\t\t\tconst auto fileName = file.getOps()->toString(file);\n\t\t\t\t\n\t\t\t\tUtils::setPermissions(fileName->str());\n\n\t\t\t\tDataValue res;\n\t\t\t\tstd::string errMsg = \"\";\n\t\t\t\tstd::fstream output;\n\t\t\t\toutput.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\toutput.open(fileName->str(), mode);\n\t\t\t\t\toutput.precision(std::numeric_limits<double>::max_digits10);\n\t\t\t\t\tval.getOps()->write(val, output);\n\t\t\t\t\tres = DataBuilders::createBoolean(true);\n\t\t\t\t\toutput.close();\n\t\t\t\t}\n\t\t\t\tcatch (const std::ios_base::failure& exc)\n\t\t\t\t{\n\t\t\t\t\tres = DataBuilders::createBoolean(false);\n\t\t\t\t\terrMsg = Utils::getfStreamError(output);\n\t\t\t\t\tif (errMsg == \"\") errMsg = exc.what();\n\t\t\t\t}\n\t\t\t\taCtx.push(res);\n\t\t\t\taCtx.push(StringBuilder::create(aCtx, errMsg));\n\t\t\t}\n\n\t\t\t// Создание или перезапись файла.\n\t\t\tvoid createFile(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\twriteToFile(aCtx, std::ios::out);\n\t\t\t}\n\n\t\t\t// Запись в конец файла.\n\t\t\tvoid appendFile(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\twriteToFile(aCtx, std::ios::app);\n\t\t\t}\n\n\t\t\t// Создание массива.\n\t\t\tvoid createArray(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto sizeVal = aCtx.getArg(0);\n\t\t\t\tconst auto& initialVal = aCtx.getArg(1);\n\n\t\t\t\tconst auto intSize = sizeVal.getOps()->toInt(sizeVal);\n\n#if fptlDebugBuild\n\t\t\t\tif (sizeVal.getOps() != IntegerOps::get())\n\t\t\t\t\tthrow BaseOps::invalidOperation(sizeVal.getOps()->getType(sizeVal), \"toInt\");\n\t\t\t\tif (intSize <= 0) throw std::invalid_argument(ArrayValue::negativeSizeMsg(intSize));\n#endif\n\n\t\t\t\tconst auto size = static_cast<size_t>(intSize);\n\t\t\t\taCtx.push(ArrayValue::create(aCtx, size, initialVal));\n\t\t\t}\n\n\t\t\t// Чтение элемента из массива.\n\t\t\tvoid getArrayElement(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arrVal = aCtx.getArg(0);\n\t\t\t\tconst auto & posVal = aCtx.getArg(1);\n\n#if fptlDebugBuild\n\t\t\t\tArrayValue::arrayValueCheck(arrVal);\n\t\t\t\tif (posVal.getOps() != IntegerOps::get())\n\t\t\t\t\tthrow BaseOps::invalidOperation(posVal.getOps()->getType(posVal), \"toInt\");\n#endif\n\n\t\t\t\tconst size_t pos = posVal.getOps()->toInt(posVal);\n\t\t\t\taCtx.push(ArrayValue::get(arrVal, pos));\n\t\t\t}\n\n\t\t\t// Запись элемента в массив.\n\t\t\tvoid setArrayElement(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arrVal = aCtx.getArg(0);\n\t\t\t\tconst auto & posVal = aCtx.getArg(1);\n\t\t\t\tconst auto & val = aCtx.getArg(2);\n\n#if fptlDebugBuild\n\t\t\t\tArrayValue::arrayValueCheck(arrVal);\n\t\t\t\tif (posVal.getOps() != IntegerOps::get())\n\t\t\t\t\tthrow BaseOps::invalidOperation(posVal.getOps()->getType(posVal), \"toInt\");\n#endif\n\n\t\t\t\tconst size_t pos = posVal.getOps()->toInt(posVal);\n\n\t\t\t\tArrayValue::set(const_cast<DataValue &>(arrVal), pos, val);\n\n\t\t\t\taCtx.push(arrVal);\n\t\t\t}\n\n\t\t\tvoid getArrayLength(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arrVal = aCtx.getArg(0);\n\t\t\t\tArrayValue::arrayValueCheck(arrVal);\n\t\t\t\taCtx.push(DataBuilders::createInt(ArrayValue::getLen(arrVal)));\n\t\t\t}\n\n\t\t\tvoid ArrayConcat(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\taCtx.push(ArrayValue::concat(aCtx));\n\t\t\t}\n\n\t\t\tvoid ArrayCopy(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arrVal = aCtx.getArg(0);\n\t\t\t\tArrayValue::arrayValueCheck(arrVal);\n\t\t\t\taCtx.push(ArrayValue::copy(aCtx, arrVal));\n\t\t\t}\n\n\t\t\tvoid ArrayDot(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tconst auto & arrVal1 = aCtx.getArg(0);\n\t\t\t\tconst auto & arrVal2 = aCtx.getArg(1);\n\t\t\t\tArrayValue::arrayValueCheck(arrVal1);\n\t\t\t\tArrayValue::arrayValueCheck(arrVal2);\n\t\t\t\taCtx.push(ArrayValue::dot(aCtx, arrVal1, arrVal2));\n\t\t\t}\n\n\t\t\t// Запись элемента в массив.\n\t\t\tvoid arrayFromFile(SExecutionContext & aCtx)\n\t\t\t{\n\t\t\t\tauto arrVal = aCtx.getArg(0);\n\t\t\t\tconst auto fileVal = aCtx.getArg(1);\n\n\t\t\t\tArrayValue::arrayValueCheck(arrVal);\n\t\t\t\tconst auto fileName = fileVal.getOps()->toString(fileVal);\n\n\t\t\t\tstd::string errMsg = \"\";\n\t\t\t\tstd::fstream input;\n\t\t\t\tinput.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tinput.open(fileName->str());\n\t\t\t\t\tArrayValue::fromString(arrVal, static_cast<std::istream&>(input));\n\t\t\t\t\tinput.close();\n\t\t\t\t}\n\t\t\t\tcatch (const std::ios_base::failure& exc)\n\t\t\t\t{\n\t\t\t\t\tarrVal = DataBuilders::createUndefinedValue();\n\t\t\t\t\terrMsg = Utils::getfStreamError(input);\n\t\t\t\t\tif (errMsg == \"\") errMsg = exc.what();\n\t\t\t\t}\n\t\t\t\taCtx.push(arrVal);\n\t\t\t\taCtx.push(StringBuilder::create(aCtx, errMsg));\n\t\t\t}\n\t\t} // anonymous namespace\n\n\t\tconst std::map<std::string, TFunction> StandardLibrary::mFunctions =\n\t\t{\n\t\t\t// Работа с кортежем.\n\t\t\t{\"id\", &id},\n\t\t\t{\"tupleLen\", &tupleLength},\n\n\t\t\t// Арифметические.\n\t\t\t{\"add\",&add},\n\t\t\t{\"sub\", &sub},\n\t\t\t{\"mul\", &mul},\n\t\t\t{\"div\", &div},\n\t\t\t{\"mod\", &mod},\n\t\t\t{\"abs\", &abs},\n\t\t\t{\"sqrt\", &sqrt},\n\t\t\t{\"exp\", &exp},\n\t\t\t{\"ln\", &log},\n\t\t\t{\"round\", &round},\n\t\t\t{\"sin\", &sin},\n\t\t\t{\"cos\", &cos},\n\t\t\t{\"tan\", &tan},\n\t\t\t{\"asin\", &asin},\n\t\t\t{\"atan\", &atan},\n\t\t\t{\"Pi\", &loadPi},\n\t\t\t{\"E\", &loadE},\n\t\t\t{\"rand\", &rand},\n\n\t\t\t//Логические.\n\t\t\t{\"not\", &Not},\n\t\t\t{\"and\", &And},\n\t\t\t{\"or\", &Or },\n\t\t\t{\"xor\", &Xor },\n\t\t\t{\"equal\", &equal},\n\t\t\t{\"nequal\", &notEqual},\n\t\t\t{\"greater\", &greater},\n\t\t\t{\"gequal\", &greaterOrEqual},\n\t\t\t{\"less\", &less},\n\t\t\t{\"lequal\", &lessOrEqual},\n\n\t\t\t// Работа со строками.\n\t\t\t{\"length\", &length},\n\t\t\t{\"cat\", &concat},\n\t\t\t{\"search\", &search},\n\t\t\t{\"replace\", &replace},\n\t\t\t{\"match\", &match},\n\t\t\t{\"getToken\", &getToken},\n\n\t\t\t// Преобразования типов.\n\t\t\t{\"toInt\", &toInteger},\n\t\t\t{\"toReal\", &toDouble},\n\t\t\t{\"toString\", &toString},\n\n\t\t\t// Ввод / вывод.\n\t\t\t{\"print\", &print},\n\t\t\t{\"printType\", &printType},\n\t\t\t{\"readFile\", &readFile},\n\t\t\t{\"createFile\", &createFile},\n\t\t\t{\"appendFile\", &appendFile},\n\n\t\t\t// Работа с массивами.\n\t\t\t{\"arrayCreate\", &createArray},\n\t\t\t{\"arrayGet\", &getArrayElement},\n\t\t\t{\"arraySet\", &setArrayElement},\n\t\t\t{\"arrayLen\", &getArrayLength},\n\t\t\t{\"arrayCat\", &ArrayConcat},\n\t\t\t{\"arrayCopy\", &ArrayCopy},\n\t\t\t{\"ArrayDot\", &ArrayDot},\n\t\t\t{\"arrayFromFile\", &arrayFromFile}\n\t\t};\n\n\t\tStandardLibrary::StandardLibrary() : FunctionLibrary(\"StdLib\")\n\t\t{\n\t\t\taddFunctions(mFunctions);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "d8f6730a7f0c46ab7750f4e23b521a479eebbe26", "size": 18550, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/Libraries/StandardLibrary.cpp", "max_stars_repo_name": "Psy-Rat/FPTL", "max_stars_repo_head_hexsha": "f3e1f560efa0c67ce62e673a8e142bc4df837a6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Libraries/StandardLibrary.cpp", "max_issues_repo_name": "Psy-Rat/FPTL", "max_issues_repo_head_hexsha": "f3e1f560efa0c67ce62e673a8e142bc4df837a6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Libraries/StandardLibrary.cpp", "max_forks_repo_name": "Psy-Rat/FPTL", "max_forks_repo_head_hexsha": "f3e1f560efa0c67ce62e673a8e142bc4df837a6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5759312321, "max_line_length": 153, "alphanum_fraction": 0.6262533693, "num_tokens": 5442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.44730028659494614}}
{"text": "/***********************************************************************************************************************\n *  OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n *  following conditions are met:\n *\n *  (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n *  disclaimer.\n *\n *  (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n *  following disclaimer in the documentation and/or other materials provided with the distribution.\n *\n *  (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote\n *  products derived from this software without specific prior written permission from the respective party.\n *\n *  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative\n *  works may not use the \"OpenStudio\" trademark, \"OS\", \"os\", or any other confusingly similar designation without\n *  specific prior written permission from Alliance for Sustainable Energy, LLC.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR\n *  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *  AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **********************************************************************************************************************/\n\n#ifndef UTILITIES_GEOMETRY_GEOMETRY_HPP\n#define UTILITIES_GEOMETRY_GEOMETRY_HPP\n\n#include \"../UtilitiesAPI.hpp\"\n\n#include <vector>\n#include <boost/optional.hpp>\n\nnamespace openstudio{\n\n  class Point3d;\n  class PointLatLon;\n  class Vector3d;\n\n  /// convert degrees to radians\n  UTILITIES_API double degToRad(double degrees);\n\n  /// convert radians to degrees\n  UTILITIES_API double radToDeg(double radians);\n\n  /// compute area from surface as Point3dVector\n  UTILITIES_API boost::optional<double> getArea(const std::vector<Point3d>& points);\n\n  /// compute Newall vector from surface as Point3dVector, direction is same as outward normal\n  /// magnitude is twice the area\n  UTILITIES_API boost::optional<Vector3d> getNewallVector(const std::vector<Point3d>& points);\n\n  /// compute outward normal from surface as Point3dVector\n  UTILITIES_API boost::optional<Vector3d> getOutwardNormal(const std::vector<Point3d>& points);\n\n  /// compute centroid from surface as Point3dVector\n  UTILITIES_API boost::optional<Point3d> getCentroid(const std::vector<Point3d>& points);\n\n  /// reorder points to upper-left-corner convention\n  UTILITIES_API std::vector<Point3d> reorderULC(const std::vector<Point3d>& points);\n\n  /// removes collinear points, tolerance is for length of cross product after normalizing each line segment\n  UTILITIES_API std::vector<Point3d> removeCollinear(const std::vector<Point3d>& points, double tol = 0.001);\n\n  /// return distance between two points\n  UTILITIES_API double getDistance(const Point3d& point1, const Point3d& point2);\n\n  /// return distance between a point and a line segment\n  /// returns 0 if lineSegment does not have length 2\n  UTILITIES_API double getDistancePointToLineSegment(const Point3d& point, const std::vector<Point3d>& lineSegment);\n\n  /// return distance between a point and a triangle\n  /// returns 0 if triangle does not have length 3\n  UTILITIES_API double getDistancePointToTriangle(const Point3d& point, const std::vector<Point3d>& triangle);\n\n  /// return angle (in radians) between two vectors\n  UTILITIES_API double getAngle(const Vector3d& vector1, const Vector3d& vector2);\n\n  /// check if two vectors of points are equal (within tolerance) irregardless of initial ordering.\n  UTILITIES_API bool circularEqual(const std::vector<Point3d>& points1, const std::vector<Point3d>& points2, double tol = 0.001);\n\n  /// if point3d is within tol of any existing points then returns existing point\n  /// otherwise adds point3d to allPoints and returns point3d\n  UTILITIES_API Point3d getCombinedPoint(const Point3d& point3d, std::vector<Point3d>& allPoints, double tol = 0.001);\n\n  /// compute triangulation of vertices, holes are removed in the triangulation\n  /// requires that vertices and holes are in clockwise order on the z = 0 plane (i.e. in face coordinates but reversed)\n  UTILITIES_API std::vector<std::vector<Point3d> > computeTriangulation(const std::vector<Point3d>& vertices, const std::vector<std::vector<Point3d> >& holes, double tol = 0.001);\n\n  /// move all vertices towards point by distance, pass negative distance to move away from point\n  /// no guarantee that resulting polygon will be valid\n  UTILITIES_API std::vector<Point3d> moveVerticesTowardsPoint(const std::vector<Point3d>& vertices, const Point3d& point, double distance);\n\n  /// reverse order of vertices\n  UTILITIES_API std::vector<Point3d> reverse(const std::vector<Point3d>& vertices);\n\n  /// Sets view and daylighting window, overhang and light shelf vertices by reference.  Returns true if successful, false otherwise.\n  UTILITIES_API bool applyViewAndDaylightingGlassRatios(double viewGlassToWallRatio, double daylightingGlassToWallRatio,\n                                                        double desiredViewGlassSillHeight, double desiredDaylightingGlassHeaderHeight,\n                                                        double exteriorShadingProjectionFactor, double interiorShelfProjectionFactor,\n                                                        const std::vector<Point3d>& surfaceVertices, std::vector<Point3d>& viewVertices,\n                                                        std::vector<Point3d>& daylightingVertices, std::vector<Point3d>& exteriorShadingVertices,\n                                                        std::vector<Point3d>& interiorShelfVertices);\n\n} // openstudio\n\n#endif //UTILITIES_GEOMETRY_GEOMETRY_HPP\n", "meta": {"hexsha": "edb4f2a0ddda8387cfdc53ab20a9c73ac3327fb0", "size": 6615, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3DViewer/src/utilities/geometry/Geometry.hpp", "max_stars_repo_name": "nschrader/floorspace.js", "max_stars_repo_head_hexsha": "236da0deecdb98fde2f4c79e6f55873b3113df58", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2017-12-21T20:40:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T14:08:11.000Z", "max_issues_repo_path": "3DViewer/src/utilities/geometry/Geometry.hpp", "max_issues_repo_name": "nschrader/floorspace.js", "max_issues_repo_head_hexsha": "236da0deecdb98fde2f4c79e6f55873b3113df58", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 139.0, "max_issues_repo_issues_event_min_datetime": "2017-12-06T22:24:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T01:51:14.000Z", "max_forks_repo_path": "3DViewer/src/utilities/geometry/Geometry.hpp", "max_forks_repo_name": "nschrader/floorspace.js", "max_forks_repo_head_hexsha": "236da0deecdb98fde2f4c79e6f55873b3113df58", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2018-05-02T21:33:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T09:58:04.000Z", "avg_line_length": 59.5945945946, "max_line_length": 179, "alphanum_fraction": 0.7185185185, "num_tokens": 1414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.44729579250758655}}
{"text": "// MIT License\n// \n// Copyright (c) 2019 worldwide-asset-exchange\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#pragma once\n\n#include <cstddef>\n#include <iterator>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <fc/crypto/sha256.hpp>\n\nnamespace wax {\n    //// Simple RSA signer class\n    class rsa_signer {\n    public:\n        /// @param private_exp Non empty hex string\n        /// @param modulus Non empty hex string, the 1st char cannot be 0 (zero)\n        /// @exception std::invalid_argument if strings are empty, non hex or\n        ///            1st char in modulus is 0\n        rsa_signer(const std::string& private_exp, const std::string& modulus) \n            : private_exp_{ \"0x\" + check_emptiness(private_exp) }\n            , modulus_{ \"0x\" + check_modulus(check_emptiness(modulus)) }\n            , modulus_size_{ modulus.size() } {\n        }\n\n        /// @param message Message/Data to sign\n        /// @return Signed message as hex string\n        /// @exception std::invalid_argument if message is empty\n        std::string sign(const std::string& message) const {\n            using namespace boost::multiprecision;\n\n            check_emptiness(message);\n            fc::sha256 message_hash(fc::sha256::hash(message.data(), message.size()));\n\n            std::string pkcs1_encoding = \n                pkcs1_encode(modulus_size_, bytes_to_string(message_hash.data(), message_hash.data_size()));\n            \n            cpp_int pkcs1_encoding_big{ \"0x\" + pkcs1_encoding };\n            cpp_int modexp = powm(pkcs1_encoding_big, private_exp_, modulus_);\n\n            std::vector<char> result;\n            export_bits(modexp, std::back_inserter(result), 8);\n\n            return bytes_to_string(result.data(), result.size());\n        }\n\n        /// @todo Add getters/setter for private_exp and modulus\n\n    // Implementation\n    private:\n        boost::multiprecision::cpp_int private_exp_;\n        boost::multiprecision::cpp_int modulus_;\n        std::size_t                    modulus_size_;\n\n        static std::string bytes_to_string(const char* in, std::size_t size) {\n            std::string out;\n            const char* hex = \"0123456789abcdef\";\n            for (std::size_t i = 0; i < size; i++) {\n                out += hex[(in[i]>>4) & 0xF];\n                out += hex[in[i] & 0xF];\n            }\n            return out;\n        }\n\n        static const std::string& check_emptiness(const std::string& str) {\n            if (str.empty()) throw std::invalid_argument(\"String cannot be empty\");\n            return str;\n        }\n\n        static const std::string& check_modulus(const std::string& modulus) {\n            if (modulus[0] == '0') throw std::invalid_argument(\"No leading zeroes allowed in modulus\");\n            return modulus;\n        }\n\n        /**\n         * @dev Generates the pkcs1 encoding for an already hashed (via sha256) message.\n         * @param modulus_length [size_t] the length in hex digits of the modulus, not including any leading zeroes\n         * @param message_hash [string] the sha256 hash of the message intended for signing over\n         * @returns [string] the pkcs1 encoding for the message hash given the modulus length\n         *\n         * For more on RSA signatures, see:\n         * https://www.emc.com/collateral/white-papers/h11300-pkcs-1v2-2-rsa-cryptography-standard-wp.pdf\n         * Page 39 is extra useful for understanding the padding scheme\n         */\n        static std::string pkcs1_encode(std::size_t modulus_length, const std::string& message_hash) {\n            // pkcs1 padding constant indicating sha256 was used as the message digest for signing\n            const char* PKCS1_SHA256 = \"003031300d060960864801650304020105000420\";\n\n            // Prepend the hash type identifier for sha256\n            std::string pkcs1_encoding = PKCS1_SHA256 + message_hash;\n\n            // Prepend all f's and a starting 1 so that the final result is as long as the modulus, minus 3\n            pkcs1_encoding = std::string(modulus_length - pkcs1_encoding.size() - 3, 'f').append(pkcs1_encoding);\n\n            // First byte must be 1\n            pkcs1_encoding[0] = '1';\n            return pkcs1_encoding;\n        }\n\n    }; // class rsa_signer\n\n\n} // namespace wax\n\n", "meta": {"hexsha": "f2744b1c1b4aa7dcfbb3287339881daa4c031a53", "size": 5325, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tests/src/rsa_signer.hpp", "max_stars_repo_name": "extrasaucestudio/wax-orng", "max_stars_repo_head_hexsha": "31b68eebfc7a359361bf87925f314e6888fb027e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-06-20T22:44:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T20:47:11.000Z", "max_issues_repo_path": "tests/src/rsa_signer.hpp", "max_issues_repo_name": "extrasaucestudio/wax-orng", "max_issues_repo_head_hexsha": "31b68eebfc7a359361bf87925f314e6888fb027e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/rsa_signer.hpp", "max_forks_repo_name": "extrasaucestudio/wax-orng", "max_forks_repo_head_hexsha": "31b68eebfc7a359361bf87925f314e6888fb027e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T02:37:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T12:45:23.000Z", "avg_line_length": 41.9291338583, "max_line_length": 115, "alphanum_fraction": 0.6469483568, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4472957850050581}}
{"text": "/* Copyright (C) 2020 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n\n// This is a sample program for education purposes only.\n// It implements a very simple homomorphic encryption based\n// db search algorithm for demonstration purposes.\n\n// This country lookup example is derived from the BGV database demo\n// code originally written by Jack Crawford for a lunch and learn\n// session at IBM Research (Hursley) in 2019.\n// The original example code ships with HElib and can be found at\n// https://github.com/IBM-HElib/HElib/tree/master/examples/BGV_database_lookup\n\n#include <iostream>\n\n#include <helib/helib.h>\n#include <helib/EncryptedArray.h>\n#include <helib/ArgMap.h>\n#include <NTL/BasicThreadPool.h>\n\n// Utility function to print polynomials\nvoid printPoly(NTL::ZZX& poly)\n{\n  for (int i = NTL::deg(poly); i >= 0; i--) {\n    std::cout << poly[i] << \"x^\" << i;\n    if (i > 0)\n      std::cout << \" + \";\n    else\n      std::cout << \"\\n\";\n  }\n}\n\n// Utility function to read <K,V> CSV data from file\nstd::vector<std::pair<std::string, std::string>> read_csv(std::string filename)\n{\n  std::vector<std::pair<std::string, std::string>> dataset;\n  std::ifstream data_file(filename);\n\n  if (!data_file.is_open())\n    throw std::runtime_error(\n        \"Error: This example failed trying to open the data file: \" + filename +\n        \"\\n           Please check this file exists and try again.\");\n\n  std::vector<std::string> row;\n  std::string line, entry, temp;\n\n  if (data_file.good()) {\n    // Read each line of file\n    while (std::getline(data_file, line)) {\n      row.clear();\n      std::stringstream ss(line);\n      while (getline(ss, entry, ',')) {\n        row.push_back(entry);\n      }\n      // Add key value pairs to dataset\n      dataset.push_back(std::make_pair(row[0], row[1]));\n    }\n  }\n\n  data_file.close();\n  return dataset;\n}\n\nint main(int argc, char* argv[])\n{\n  /************ HElib boiler plate ************/\n\n  // Note: The parameters have been chosen to provide a somewhat\n  // faster running time with a non-realistic security level.\n  // Do Not use these parameters in real applications.\n\n  // Plaintext prime modulus\n  unsigned long p = 131;\n  // Cyclotomic polynomial - defines phi(m)\n  unsigned long m = 130; // this will give 48 slots\n  // Hensel lifting (default = 1)\n  unsigned long r = 1;\n  // Number of bits of the modulus chain\n  unsigned long bits = 1000;\n  // Number of columns of Key-Switching matrix (default = 2 or 3)\n  unsigned long c = 2;\n  // Size of NTL thread pool (default =1)\n  unsigned long nthreads = 1;\n  // input database file name\n  std::string db_filename = \"./countries_dataset.csv\";\n  // debug output (default no debug output)\n  bool debug = false;\n\n  helib::ArgMap amap;\n  amap.arg(\"m\", m, \"Cyclotomic polynomial ring\");\n  amap.arg(\"p\", p, \"Plaintext prime modulus\");\n  amap.arg(\"r\", r, \"Hensel lifting\");\n  amap.arg(\"bits\", bits, \"# of bits in the modulus chain\");\n  amap.arg(\"c\", c, \"# fo columns of Key-Switching matrix\");\n  amap.arg(\"nthreads\", nthreads, \"Size of NTL thread pool\");\n  amap.arg(\"db_filename\",\n           db_filename,\n           \"Qualified name for the database filename\");\n  amap.toggle().arg(\"-debug\", debug, \"Toggle debug output\", \"\");\n  amap.parse(argc, argv);\n\n  // set NTL Thread pool size\n  if (nthreads > 1)\n    NTL::SetNumThreads(nthreads);\n\n  std::cout << \"\\n*********************************************************\";\n  std::cout << \"\\n*           Privacy Preserving Search Example           *\";\n  std::cout << \"\\n*           =================================           *\";\n  std::cout << \"\\n*                                                       *\";\n  std::cout << \"\\n* This is a sample program for education purposes only. *\";\n  std::cout << \"\\n* It implements a very simple homomorphic encryption    *\";\n  std::cout << \"\\n* based db search algorithm for demonstration purposes. *\";\n  std::cout << \"\\n*                                                       *\";\n  std::cout << \"\\n*********************************************************\";\n  std::cout << \"\\n\" << std::endl;\n\n  std::cout << \"---Initialising HE Environment ... \";\n  // Initialize context\n  // This object will hold information about the algebra used for this scheme.\n  std::cout << \"\\nInitializing the Context ... \";\n  HELIB_NTIMER_START(timer_Context);\n  helib::Context context = helib::ContextBuilder<helib::BGV>()\n                               .m(m)\n                               .p(p)\n                               .r(r)\n                               .bits(bits)\n                               .c(c)\n                               .build();\n  HELIB_NTIMER_STOP(timer_Context);\n\n  // Secret key management\n  std::cout << \"\\nCreating Secret Key ...\";\n  HELIB_NTIMER_START(timer_SecKey);\n  // Create a secret key associated with the context\n  helib::SecKey secret_key = helib::SecKey(context);\n  // Generate the secret key\n  secret_key.GenSecKey();\n  HELIB_NTIMER_STOP(timer_SecKey);\n\n  // Compute key-switching matrices that we need\n  HELIB_NTIMER_START(timer_SKM);\n  helib::addSome1DMatrices(secret_key);\n  HELIB_NTIMER_STOP(timer_SKM);\n\n  // Public key management\n  // Set the secret key (upcast: FHESecKey is a subclass of FHEPubKey)\n  std::cout << \"\\nCreating Public Key ...\";\n  HELIB_NTIMER_START(timer_PubKey);\n  const helib::PubKey& public_key = secret_key;\n  HELIB_NTIMER_STOP(timer_PubKey);\n\n  // Get the EncryptedArray of the context\n  const helib::EncryptedArray& ea = context.getEA();\n\n  // Print the context\n  std::cout << std::endl;\n  if (debug)\n    context.printout();\n\n  // Print the security level\n  // Note: This will be negligible to improve performance time.\n  std::cout << \"\\n***Security Level: \" << context.securityLevel()\n            << \" *** Negligible for this example ***\" << std::endl;\n\n  // Get the number of slot (phi(m))\n  long nslots = ea.size();\n  std::cout << \"\\nNumber of slots: \" << nslots << std::endl;\n\n  /************ Read in the database ************/\n  std::vector<std::pair<std::string, std::string>> country_db;\n  try {\n    country_db = read_csv(db_filename);\n  } catch (std::runtime_error& e) {\n    std::cerr << \"\\n\" << e.what() << std::endl;\n    exit(1);\n  }\n\n  // Convert strings into numerical vectors\n  std::cout << \"\\n---Initializing the encrypted key,value pair database (\"\n            << country_db.size() << \" entries)...\";\n  std::cout\n      << \"\\nConverting strings to numeric representation into Ptxt objects ...\"\n      << std::endl;\n\n  // Generating the Plain text representation of Country DB\n  HELIB_NTIMER_START(timer_PtxtCountryDB);\n  std::vector<std::pair<helib::Ptxt<helib::BGV>, helib::Ptxt<helib::BGV>>>\n      country_db_ptxt;\n  for (const auto& country_capital_pair : country_db) {\n    if (debug) {\n      std::cout << \"\\t\\tname_addr_pair.first size = \"\n                << country_capital_pair.first.size() << \" (\"\n                << country_capital_pair.first << \")\"\n                << \"\\tname_addr_pair.second size = \"\n                << country_capital_pair.second.size() << \" (\"\n                << country_capital_pair.second << \")\" << std::endl;\n    }\n\n    helib::Ptxt<helib::BGV> country(context);\n    // std::cout << \"\\tname size = \" << country.size() << std::endl;\n    for (long i = 0; i < country_capital_pair.first.size(); ++i)\n      country.at(i) = country_capital_pair.first[i];\n\n    helib::Ptxt<helib::BGV> capital(context);\n    for (long i = 0; i < country_capital_pair.second.size(); ++i)\n      capital.at(i) = country_capital_pair.second[i];\n    country_db_ptxt.emplace_back(std::move(country), std::move(capital));\n  }\n  HELIB_NTIMER_STOP(timer_PtxtCountryDB);\n\n  // Encrypt the Country DB\n  std::cout << \"Encrypting the database...\" << std::endl;\n  HELIB_NTIMER_START(timer_CtxtCountryDB);\n  std::vector<std::pair<helib::Ctxt, helib::Ctxt>> encrypted_country_db;\n  for (const auto& country_capital_pair : country_db_ptxt) {\n    helib::Ctxt encrypted_country(public_key);\n    helib::Ctxt encrypted_capital(public_key);\n    public_key.Encrypt(encrypted_country, country_capital_pair.first);\n    public_key.Encrypt(encrypted_capital, country_capital_pair.second);\n    encrypted_country_db.emplace_back(std::move(encrypted_country),\n                                      std::move(encrypted_capital));\n  }\n\n  HELIB_NTIMER_STOP(timer_CtxtCountryDB);\n\n  // Print DB Creation Timers\n  if (debug) {\n    helib::printNamedTimer(std::cout << std::endl, \"timer_Context\");\n    helib::printNamedTimer(std::cout, \"timer_Chain\");\n    helib::printNamedTimer(std::cout, \"timer_SecKey\");\n    helib::printNamedTimer(std::cout, \"timer_SKM\");\n    helib::printNamedTimer(std::cout, \"timer_PubKey\");\n    helib::printNamedTimer(std::cout, \"timer_PtxtCountryDB\");\n    helib::printNamedTimer(std::cout, \"timer_CtxtCountryDB\");\n  }\n\n  std::cout << \"\\nInitialization Completed - Ready for Queries\" << std::endl;\n  std::cout << \"--------------------------------------------\" << std::endl;\n\n  /** Create the query **/\n\n  // Read in query from the command line\n  std::string query_string;\n  std::cout << \"\\nPlease enter the name of an European Country: \";\n  // std::cin >> query_string;\n  std::getline(std::cin, query_string);\n  std::cout << \"Looking for the Capital of \" << query_string << std::endl;\n  std::cout << \"This may take few minutes ... \" << std::endl;\n\n  HELIB_NTIMER_START(timer_TotalQuery);\n\n  HELIB_NTIMER_START(timer_EncryptQuery);\n  // Convert query to a numerical vector\n  helib::Ptxt<helib::BGV> query_ptxt(context);\n  for (long i = 0; i < query_string.size(); ++i)\n    query_ptxt[i] = query_string[i];\n\n  // Encrypt the query\n  helib::Ctxt query(public_key);\n  public_key.Encrypt(query, query_ptxt);\n  HELIB_NTIMER_STOP(timer_EncryptQuery);\n\n  /************ Perform the database search ************/\n\n  HELIB_NTIMER_START(timer_QuerySearch);\n  std::vector<helib::Ctxt> mask;\n  mask.reserve(country_db.size());\n  for (const auto& encrypted_pair : encrypted_country_db) {\n    helib::Ctxt mask_entry = encrypted_pair.first; // Copy of database key\n    mask_entry -= query;                           // Calculate the difference\n    mask_entry.power(p - 1);                       // Fermat's little theorem\n    mask_entry.negate();                           // Negate the ciphertext\n    mask_entry.addConstant(NTL::ZZX(1));           // 1 - mask = 0 or 1\n    // Create a vector of copies of the mask\n    std::vector<helib::Ctxt> rotated_masks(ea.size(), mask_entry);\n    for (int i = 1; i < rotated_masks.size(); i++)\n      ea.rotate(rotated_masks[i], i);             // Rotate each of the masks\n    totalProduct(mask_entry, rotated_masks);      // Multiply each of the masks\n    mask_entry.multiplyBy(encrypted_pair.second); // multiply mask with values\n    mask.push_back(mask_entry);\n  }\n\n  // Aggregate the results into a single ciphertext\n  // Note: This code is for educational purposes and thus we try to refrain\n  // from using the STL and do not use std::accumulate\n  helib::Ctxt value = mask[0];\n  for (int i = 1; i < mask.size(); i++)\n    value += mask[i];\n\n  HELIB_NTIMER_STOP(timer_QuerySearch);\n\n  /************ Decrypt and print result ************/\n\n  HELIB_NTIMER_START(timer_DecryptQueryResult);\n  helib::Ptxt<helib::BGV> plaintext_result(context);\n  secret_key.Decrypt(plaintext_result, value);\n  HELIB_NTIMER_STOP(timer_DecryptQueryResult);\n\n  // Convert from ASCII to a string\n  std::string string_result;\n  for (long i = 0; i < plaintext_result.size(); ++i)\n    string_result.push_back(static_cast<long>(plaintext_result[i]));\n\n  HELIB_NTIMER_STOP(timer_TotalQuery);\n\n  // Print DB Query Timers\n  if (debug) {\n    helib::printNamedTimer(std::cout << std::endl, \"timer_EncryptQuery\");\n    helib::printNamedTimer(std::cout, \"timer_QuerySearch\");\n    helib::printNamedTimer(std::cout, \"timer_DecryptQueryResult\");\n    std::cout << std::endl;\n  }\n\n  if (string_result.at(0) == 0x00) {\n    string_result =\n        \"Country name not in the database.\"\n        \"\\n*** Please make sure to enter the name of a European Country\"\n        \"\\n*** with the first letter in upper case.\";\n  }\n  std::cout << \"\\nQuery result: \" << string_result << std::endl;\n  helib::printNamedTimer(std::cout, \"timer_TotalQuery\");\n\n  return 0;\n}\n", "meta": {"hexsha": "783e4b7c77ab60cea41f4ff72b83ddd6a1c4499c", "size": 12708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/BGV_country_db_lookup/BGV_country_db_lookup.cpp", "max_stars_repo_name": "Manny27nyc/HElib", "max_stars_repo_head_hexsha": "a5f914e498bc9358aa55d1731c0fb0ff02955bcd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2021-03-10T18:33:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T09:53:49.000Z", "max_issues_repo_path": "examples/BGV_country_db_lookup/BGV_country_db_lookup.cpp", "max_issues_repo_name": "Manny27nyc/HElib", "max_issues_repo_head_hexsha": "a5f914e498bc9358aa55d1731c0fb0ff02955bcd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-02-11T18:45:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-27T14:46:59.000Z", "max_forks_repo_path": "examples/BGV_country_db_lookup/BGV_country_db_lookup.cpp", "max_forks_repo_name": "Manny27nyc/HElib", "max_forks_repo_head_hexsha": "a5f914e498bc9358aa55d1731c0fb0ff02955bcd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-03-03T10:34:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T07:27:52.000Z", "avg_line_length": 38.0479041916, "max_line_length": 80, "alphanum_fraction": 0.6339313818, "num_tokens": 3232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.4471831455447271}}
{"text": "/*******************************************************************************\n * Copyright (c) 2012, Dougal J. Sutherland (dsutherl@cs.cmu.edu).             *\n * All rights reserved.                                                        *\n *                                                                             *\n * Redistribution and use in source and binary forms, with or without          *\n * modification, are permitted provided that the following conditions are met: *\n *                                                                             *\n *     * Redistributions of source code must retain the above copyright        *\n *       notice, this list of conditions and the following disclaimer.         *\n *                                                                             *\n *     * Redistributions in binary form must reproduce the above copyright     *\n *       notice, this list of conditions and the following disclaimer in the   *\n *       documentation and/or other materials provided with the distribution.  *\n *                                                                             *\n *     * Neither the name of Carnegie Mellon University nor the                *\n *       names of the contributors may be used to endorse or promote products  *\n *       derived from this software without specific prior written permission. *\n *                                                                             *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" *\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE   *\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE  *\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE   *\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR         *\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF        *\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS    *\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN     *\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)     *\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE  *\n * POSSIBILITY OF SUCH DAMAGE.                                                 *\n ******************************************************************************/\n#include \"sdm/basics.hpp\"\n#include \"sdm/kernels/polynomial.hpp\"\n\n#include <cmath>\n#include <string>\n\n#include <boost/format.hpp>\n#include <boost/ptr_container/ptr_vector.hpp>\n\nnamespace sdm {\n\ndouble PolynomialKernel::transformDivergence(double div) const {\n    return std::pow(div + coef0, (int) degree);\n}\n\nstd::string PolynomialKernel::name() const {\n    return (boost::format(\"Polynomial(%d, %g)\") % degree % coef0).str();\n}\nsize_t PolynomialKernel::getDegree() const { return degree; }\ndouble PolynomialKernel::getCoef0() const { return coef0; }\n\nPolynomialKernel* PolynomialKernel::do_clone() const {\n    return new PolynomialKernel(degree, coef0);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n\nconst boost::ptr_vector<Kernel>* PolynomialKernelGroup::getTuningVector(\n        const double* divs, size_t n)\nconst {\n    boost::ptr_vector<Kernel>* kerns = new boost::ptr_vector<Kernel>;\n    for (size_t d = 0; d < degrees.size(); d++) {\n        for (size_t c = 0; c < coef0s.size(); c++) {\n            kerns->push_back(new PolynomialKernel(degrees[d], coef0s[c]));\n        }\n    }\n    return kerns;\n}\n\nPolynomialKernelGroup* PolynomialKernelGroup::do_clone() const {\n    return new PolynomialKernelGroup(degrees, coef0s);\n}\n\n} // end namespace\n", "meta": {"hexsha": "e6e886fc9c7c73c4044cd04d35c13f4962f16f68", "size": 3716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdm/kernels/polynomial.cpp", "max_stars_repo_name": "dougalsutherland/sdm", "max_stars_repo_head_hexsha": "2f6a57c5b337649a64f899dd5acba6e4eb35dff9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-04-03T11:49:19.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-22T12:08:02.000Z", "max_issues_repo_path": "sdm/kernels/polynomial.cpp", "max_issues_repo_name": "dougalsutherland/sdm", "max_issues_repo_head_hexsha": "2f6a57c5b337649a64f899dd5acba6e4eb35dff9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T00:02:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-05T00:02:54.000Z", "max_forks_repo_path": "sdm/kernels/polynomial.cpp", "max_forks_repo_name": "dougalsutherland/sdm", "max_forks_repo_head_hexsha": "2f6a57c5b337649a64f899dd5acba6e4eb35dff9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-05-20T10:40:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-21T15:50:32.000Z", "avg_line_length": 49.5466666667, "max_line_length": 80, "alphanum_fraction": 0.5578579117, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.658417500561683, "lm_q1q2_score": 0.44718314154579747}}
{"text": "#include <ros/ros.h>\n#include <image_transport/image_transport.h>\n#include <opencv2/highgui/highgui.hpp>\n#include <cv_bridge/cv_bridge.h>\n#include <arpa/inet.h>\n//#include <boost/endian/conversion.hpp>\n#include <tf/transform_broadcaster.h>\n\n\n#include <nav_msgs/Odometry.h>\n\n\n#include <unsupported/Eigen/MatrixFunctions>\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Geometry>\n\n\n#include <cmath>\n\n\n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\n\n\ndouble dt = 1;\n\nEigen::VectorXd\t\tp_k(3);\nEigen::VectorXd \t\tq_k(4);\nEigen::VectorXd\t\tq_k_1(4);\nEigen::VectorXd\t\tq_k_dot(4);\nEigen::MatrixXd \t\tR_k(3,3);\t\t//passo attuale\nEigen::MatrixXd \t\tR_k_1(3,3);\t\t//passo precedente\nEigen::MatrixXd \t\tR_k_dot(3,3);\nEigen::MatrixXd \t\tR_k_dot2(3,3);\nEigen::MatrixXd\t\tS_w(3,3);\nEigen::MatrixXd\t\tS_w2(3,3);\nEigen::MatrixXd\t\tE_q(4,3);\nEigen::VectorXd\t\tw(3);\n\n\n\n\nvoid skew(const geometry_msgs::TransformStamped::ConstPtr& Transform_estimate)\n{\n\n\nstd::cout<<\"---------------FRAME_-----------------------\"<< endl;\n\tcout <<\tTransform_estimate->header.frame_id << endl;\nstd::cout<<\"--------------------------------------\"<< endl;\n\n\n\nstd::cout<<\"---------------FRAME_CHILD-----------------------\"<< endl;\n\tcout <<\tTransform_estimate->child_frame_id <<endl;\nstd::cout<<\"--------------------------------------\"<< endl;\n\n//____prendo la misura corrispondente al centro dell'oggetto\n\n\t\tp_k[0] = Transform_estimate->transform.translation.x;\n\t\tp_k[1] = Transform_estimate->transform.translation.y;\n\t\tp_k[2] = Transform_estimate->transform.translation.z;\n\t\tq_k[0] = Transform_estimate->transform.rotation.w; \t\t\t\n\t\tq_k[1] = Transform_estimate->transform.rotation.x;\t\t\t\n\t\tq_k[2] = Transform_estimate->transform.rotation.y;\t\t\n\t\tq_k[3] = Transform_estimate->transform.rotation.z;\t\t\t\n\n\n\n//\t\tq[0] w q[1] x  q[2] y  q[3] z\n\n\n\t\tstd::cout<<\"---------------QUATERNION-----------------------\"<< endl;\n\t\tstd::cout<<  q_k[0] << endl;\n\t\tstd::cout<<  q_k[1] << endl;\n\t\tstd::cout<<  q_k[2] << endl;\n\t\tstd::cout<<  q_k[3] << endl;\n\t\tstd::cout<<\"------------------------------------------------\"<< endl;\n\n\n\n\t\tstd::cout<<\"---------------QUATERNION_PREVIOUS--------------\"<< endl;\n\t\tstd::cout<<  q_k_1[0] << endl;\n\t\tstd::cout<<  q_k_1[1] << endl;\n\t\tstd::cout<<  q_k_1[2] << endl;\n\t\tstd::cout<<  q_k_1[3] << endl;\n\t\tstd::cout<<\"------------------------------------------------\"<< endl;\n\n\n\n\t\tstd::cout<<\"---------------SAMPLING_TIME--------------------\"<< endl;\n\t\tstd::cout<<  dt << endl;\n\t\tstd::cout<<\"------------------------------------------------\"<< endl;\n\n\n\t\t\n\n\t\tq_k_dot(0) = ( q_k(0) - q_k_1(0) ) / dt ;   \n\t\tq_k_dot(1) = ( q_k(1) - q_k_1(1) ) / dt ;   \n\t\tq_k_dot(2) = ( q_k(2) - q_k_1(2) ) / dt ;  \n\t\tq_k_dot(3) = ( q_k(3) - q_k_1(3) ) / dt ;  \n\n\t\n\t\tstd::cout<<\"---------------QUATERNION_DOT-------------------\"<< endl;\n\t\tstd::cout<<  q_k_dot[0] << endl;\n\t\tstd::cout<<  q_k_dot[1] << endl;\n\t\tstd::cout<<  q_k_dot[2] << endl;\n\t\tstd::cout<<  q_k_dot[3] << endl;\n\t\tstd::cout<<\"------------------------------------------------\"<< endl;\n\n\t\t\n\n\n\t\n\n\t\tE_q(0,0) = - q_k(1) ;\n\t\tE_q(0,1) = - q_k(2) ;\n\t\tE_q(0,2) = - q_k(3) ;\n\t\tE_q(1,0) =   q_k(0) ;\n\t\tE_q(1,1) =   q_k(3) ;\n\t\tE_q(1,2) = - q_k(2) ;\n\t\tE_q(2,0) = - q_k(3) ;\n\t\tE_q(2,1) =   q_k(0) ;\n\t\tE_q(2,2) =   q_k(1) ;\n\t\tE_q(3,0) =   q_k(2) ;\n\t\tE_q(3,1) = - q_k(1) ;\n\t\tE_q(3,2) =   q_k(0) ;\n\n\n\t\t\n\t\tstd::cout<<\"---------------E_q-----------------------------\"<< endl;\n\t\tstd::cout<<  E_q << endl;\n\t\tstd::cout<<\"------------------------------------------------\"<< endl;\n\n\n\n\t\n\t\tw = 2*E_q.transpose()*q_k_dot ;\n\n\n\n\t\tstd::cout<<\"---------------ANGULAR_VELOCITY--------------------\"<< endl;\n\t\tstd::cout<<  w << endl;\n\t\tstd::cout<<\"------------------------------------------------\"<< endl;\n\n\n\n\n\n\n\t\tR_k(0,0)\t= q_k[0]*q_k[0] + q_k[1]*q_k[1] - q_k[2]*q_k[2] - q_k[3]*q_k[3];\n\t\tR_k(0,1)\t= 2*q_k[1]*q_k[2] - 2*q_k[0]*q_k[3];\n\t\tR_k(0,2)\t= 2*q_k[1]*q_k[3] + 2*q_k[0]*q_k[2];\n\t\tR_k(1,0)\t= 2*q_k[1]*q_k[2] + 2*q_k[0]*q_k[3];\n\t\tR_k(1,1)\t= q_k[0]*q_k[0] + q_k[2]*q_k[2] - q_k[1]*q_k[1] - q_k[3]*q_k[3];\n\t\tR_k(1,2)\t= 2*q_k[2]*q_k[3] - 2*q_k[0]*q_k[1];\n\t\tR_k(2,0)\t= 2*q_k[1]*q_k[3] - 2*q_k[0]*q_k[2];\n\t\tR_k(2,1)\t= 2*q_k[2]*q_k[3] + 2*q_k[0]*q_k[1];\n\t\tR_k(2,2)\t= q_k[0]*q_k[0] + q_k[3]*q_k[3] - q_k[2]*q_k[2] - q_k[1]*q_k[1];\n\n\t\t\n\n\t\t//\t\t\tR_k_dot = ( R_k - R_k_1 ) / dt ;\t\n\n\n\t\tR_k_dot(0,0)\t= ( R_k(0,0) - R_k_1(0,0) ) / dt ;\n\t\tR_k_dot(0,1)\t= ( R_k(0,1) - R_k_1(0,1) ) / dt ;\n\t\tR_k_dot(0,2)\t= ( R_k(0,2) - R_k_1(0,2) ) / dt ;\n\t\tR_k_dot(1,0)\t= ( R_k(1,0) - R_k_1(1,0) ) / dt ;\n\t\tR_k_dot(1,1)\t= ( R_k(1,1) - R_k_1(1,1) ) / dt ;\n\t\tR_k_dot(1,2)\t= ( R_k(1,2) - R_k_1(1,2) ) / dt ;\n\t\tR_k_dot(2,0)\t= ( R_k(2,0) - R_k_1(2,0) ) / dt ;\n\t\tR_k_dot(2,1)\t= ( R_k(2,1) - R_k_1(2,1) ) / dt ;\n\t\tR_k_dot(2,2)\t= ( R_k(2,2) - R_k_1(2,2) ) / dt ;\n\n\n\t\t\n\t\tR_k_dot2(0,0)\t= 2*(q_k(0)*q_k_dot(0) + q_k(1)*q_k_dot(1) - q_k(2)*q_k_dot(2) - q_k(3)*q_k_dot(3));\n\t\tR_k_dot2(0,1)\t= 2*(q_k_dot(1)*q_k(2) + q_k(1)*q_k_dot(2) - q_k_dot(0)*q_k(3) - q_k(0)*q_k_dot(3));\n\t\tR_k_dot2(0,2)\t= 2*(q_k_dot(1)*q_k(3) + q_k(1)*q_k_dot(3) + q_k_dot(0)*q_k(2) + q_k(0)*q_k_dot(2));\n\t\tR_k_dot2(1,0)\t= 2*(q_k_dot(1)*q_k(2) + q_k(1)*q_k_dot(2) + q_k_dot(0)*q_k(3) + q_k(0)*q_k_dot(3));\n\t\tR_k_dot2(1,1)\t= 2*(q_k(0)*q_k_dot(0) - q_k(1)*q_k_dot(1) + q_k(2)*q_k_dot(2) - q_k(3)*q_k_dot(3));\n\t\tR_k_dot2(1,2)\t= 2*(q_k_dot(2)*q_k(3) + q_k(2)*q_k_dot(3) - q_k_dot(0)*q_k(1) - q_k(0)*q_k_dot(1));\n\t\tR_k_dot2(2,0)\t= 2*(q_k_dot(1)*q_k(3) + q_k(1)*q_k_dot(3) - q_k_dot(0)*q_k(2) - q_k(0)*q_k_dot(2));\n\t\tR_k_dot2(2,1)\t= 2*(q_k_dot(2)*q_k(3) + q_k(2)*q_k_dot(3) + q_k_dot(0)*q_k(1) + q_k(0)*q_k_dot(1));\n\t\tR_k_dot2(2,2)\t= 2*(q_k(0)*q_k_dot(0) + q_k(1)*q_k_dot(1) - q_k(2)*q_k_dot(2) - q_k(3)*q_k_dot(3));\n\n\t\n\n\t\tS_w2 = R_k_dot2 * R_k.transpose() ;\n\n\t\tS_w = R_k_dot * R_k.transpose() ;\t\t\t//body_frame\n\t\t\n\n/*\n\t\n\t\tstd::cout<<\"---------------SAMPLING_TIME--------------------\"<< endl;\n\t\tstd::cout<<  dt << endl;\n\t\tstd::cout<<\"------------------------------------------------\"<< endl;\n\n*/\n\t\t\n\n\t\tstd::cout<<\"----------------ROTATION_MATRIX-----------------\"<< endl;\n\t\tstd::cout<<  R_k << endl;\n\t\tstd::cout<<\"------------------------------------------------\"<< endl;\n\n\n\n\n\n   \tstd::cout<<\"-------------DOT_ROTATION_MATRIX----------------\"<< endl;\n\t\tstd::cout<<  R_k_dot << endl;\n\t\tstd::cout<<\"------------------------------------------------\"<< endl;\n\n\n\n\t\tstd::cout<<\"-----------------SKEW_MATRIX--------------------\"<< endl;\n\t\tstd::cout<<  S_w << endl;\n\t\tstd::cout<<\"------------------------------------------------\"<< endl;\n\n\n/*\n\n\t   std::cout<<\"----------2_____________DOT_ROTATION_MATRIX----------------\"<< endl;\n\t\tstd::cout<<  R_k_dot2 << endl;\n\t\tstd::cout<<\"------------------------------------------------\"<< endl;\n\n\n\n\n\t\tstd::cout<<\"----------2_______SKEW_MATRIX--------------------\"<< endl;\n\t\tstd::cout<<  S_w2 << endl;\n\t\tstd::cout<<\"------------------------------------------------\"<< endl;\n\n\n*/\n\n\t\tR_k_1 = R_k ;\n\n\t\tq_k_1 = q_k ;\n\n}\n\n\n\n\nint main(int argc, char** argv)\n{\n \n\t//inizializzazione nodo \n\tros::init(argc, argv, \"skew\");// ROS node\n   ros::NodeHandle nn;\n\n\n\tcout<<\"1\"<<endl;\n\n\t\n\t\n\tros::Subscriber pose_sub;\n\tpose_sub = nn.subscribe(\"/transform_obj\", 1, &skew);\n\n\n\n\tros::Rate loop_rate(100);//RATE, non metterlo al massimo sennò occupo tutta la CPU ( no good )\n\n\tcout<<\"2\"<<endl;\n\n\n\n//inizializzazione \n\n\n\tp_k     <<  0,0,0;\n\tq_k\t  <<  1,0,0,0;\n\tq_k_1\t  <<  1,0,0,0;\n\tq_k_dot <<  1,0,0,0;\n\n\n\tw\t\t\t<< 0,0,0 ;\n\n\n\tR_k     <<  MatrixXd::Zero(3,3);\t\n\tR_k_1   <<  MatrixXd::Zero(3,3);\t\n\tR_k_dot <<  MatrixXd::Zero(3,3);\t\n\tR_k_dot2<<  MatrixXd::Zero(3,3); \n\tE_q     <<  MatrixXd::Zero(4,3);\t\n\n\n\n\n\n\n\n\t\n    ros::Time current_time, last_time;\n    current_time = ros::Time::now();\n    last_time = ros::Time::now();\n\n\n\twhile(nn.ok())\n\t{\n\n\t\tcurrent_time = ros::Time::now();\n\t\tdt = (current_time - last_time).toSec();\n\t\n\t\t\n\t\tros::spinOnce();\n\n  \t\t\n\t\tlast_time = current_time;\n\n\t\tloop_rate.sleep();\n\t\t\n\t}\n\n}\n  \n\n", "meta": {"hexsha": "82668798a2572239db5ffb17aaae17b767a788cc", "size": 7858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ar_track/Skew.cpp", "max_stars_repo_name": "lia2790/object-detection", "max_stars_repo_head_hexsha": "ad0bdd42bab5d218cbf1ddb53af29c66ba06860d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-06-13T03:51:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T12:17:25.000Z", "max_issues_repo_path": "src/ar_track/Skew.cpp", "max_issues_repo_name": "lia2790/object-detection", "max_issues_repo_head_hexsha": "ad0bdd42bab5d218cbf1ddb53af29c66ba06860d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ar_track/Skew.cpp", "max_forks_repo_name": "lia2790/object-detection", "max_forks_repo_head_hexsha": "ad0bdd42bab5d218cbf1ddb53af29c66ba06860d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-06-13T03:51:16.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-13T03:51:16.000Z", "avg_line_length": 24.3281733746, "max_line_length": 100, "alphanum_fraction": 0.4874013744, "num_tokens": 3046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461008, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.44714741838970523}}
{"text": "#include <iostream>\n#include <boost/iterator/iterator_adaptor.hpp>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/AABB_tree.h>\n#include <CGAL/AABB_traits.h>\n\n\n\ntypedef CGAL::Simple_cartesian<double> K;\n\n\n// The points are stored in a flat array of doubles\n// The triangles are stored in a flat array of indices\n// referring to an array of coordinates: three consecutive\n// coordinates represent a point, and three consecutive\n// indices represent a triangle.\n\ntypedef size_t* Point_index_iterator;\n\n// Let us now define the iterator on triangles that the tree needs:\nclass Triangle_iterator\n    : public boost::iterator_adaptor<\n    Triangle_iterator               // Derived\n    , Point_index_iterator            // Base\n    , boost::use_default              // Value\n    , boost::forward_traversal_tag    // CategoryOrTraversal\n    >\n{\npublic:\n    Triangle_iterator()\n        : Triangle_iterator::iterator_adaptor_() {}\n\n    explicit Triangle_iterator(Point_index_iterator p)\n        : Triangle_iterator::iterator_adaptor_(p) {}\n\nprivate:\n    friend class boost::iterator_core_access;\n    void increment() { this->base_reference() += 3; }\n};\n\n\n// The following primitive provides the conversion facilities between\n// my own triangle and point types and the CGAL ones\nstruct My_triangle_primitive {\npublic:\n    typedef Triangle_iterator    Id;\n\n    // the CGAL types returned\n    typedef K::Point_3    Point;\n    typedef K::Triangle_3 Datum;\n\n    // a static pointer to the vector containing the points\n    // is needed to build the triangles on the fly:\n    static const double* point_container;\n\nprivate:\n    Id m_it; // this is what the AABB tree stores internally\n\npublic:\n    My_triangle_primitive() {} // default constructor needed\n\n    // the following constructor is the one that receives the iterators from the\n    // iterator range given as input to the AABB_tree\n    My_triangle_primitive(Triangle_iterator a)\n        : m_it(a) {}\n\n    Id id() const { return m_it; }\n\n    // on the fly conversion from the internal data to the CGAL types\n    Datum datum() const\n    {\n        Point_index_iterator p_it = m_it.base();\n        Point p(*(point_container + 3 * (*p_it)),\n                *(point_container + 3 * (*p_it) + 1),\n                *(point_container + 3 * (*p_it) + 2) );\n        ++p_it;\n        Point q(*(point_container + 3 * (*p_it)),\n                *(point_container + 3 * (*p_it) + 1),\n                *(point_container + 3 * (*p_it) + 2));\n        ++p_it;\n        Point r(*(point_container + 3 * (*p_it)),\n                *(point_container + 3 * (*p_it) + 1),\n                *(point_container + 3 * (*p_it) + 2));\n\n        return Datum(p, q, r); // assembles triangle from three points\n    }\n\n    // one point which must be on the primitive\n    Point reference_point() const\n    {\n      return Point(*(point_container + 3 * (*m_it)),\n                   *(point_container + 3 * (*m_it) + 1),\n                   *(point_container + 3 * (*m_it) + 2));\n    }\n};\n\n\n// types\ntypedef CGAL::AABB_traits<K, My_triangle_primitive> My_AABB_traits;\ntypedef CGAL::AABB_tree<My_AABB_traits> Tree;\nconst double* My_triangle_primitive::point_container = 0;\n\nint main()\n{\n    // generates point set\n    double points[12];\n    My_triangle_primitive::point_container = points;\n    points[0] = 1.0; points[1] = 0.0; points[2] = 0.0;\n    points[3] = 0.0; points[4] = 1.0; points[5] = 0.0;\n    points[6] = 0.0; points[7] = 0.0; points[8] = 1.0;\n    points[9] = 0.0; points[10] = 0.0; points[11] = 0.0;\n\n\n    // generates indexed triangle set\n    size_t triangles[9];\n    triangles[0] = 0; triangles[1] = 1; triangles[2] = 2;\n    triangles[3] = 0; triangles[4] = 1; triangles[5] = 3;\n    triangles[6] = 0; triangles[7] = 3; triangles[8] = 2;\n\n    // constructs AABB tree\n    Tree tree(Triangle_iterator(triangles),\n        Triangle_iterator(triangles+9));\n\n    // counts #intersections\n    K::Ray_3 ray_query(K::Point_3(0.2, 0.2, 0.2), K::Point_3(0.0, 1.0, 0.0));\n    std::cout << tree.number_of_intersected_primitives(ray_query)\n        << \" intersections(s) with ray query\" << std::endl;\n\n    // computes closest point\n    K::Point_3 point_query(2.0, 2.0, 2.0);\n    K::Point_3 closest_point = tree.closest_point(point_query);\n    std::cout << \"closest point to \" << point_query << \" is: \" << closest_point.x() << \" \" << closest_point.y() << \" \" << closest_point.z() << std::endl;\n\n    return EXIT_SUCCESS;\n}\n\n\n", "meta": {"hexsha": "d15c7155cd9140c09acfdf493632bc8a69be322a", "size": 4418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AABB_tree/examples/AABB_tree/AABB_custom_indexed_triangle_set_array_example.cpp", "max_stars_repo_name": "gaschler/cgal", "max_stars_repo_head_hexsha": "d1fe2afa18da5524db6d4946f42ca4b8d00e0bda", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T09:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T05:00:23.000Z", "max_issues_repo_path": "AABB_tree/examples/AABB_tree/AABB_custom_indexed_triangle_set_array_example.cpp", "max_issues_repo_name": "guorongtao/cgal", "max_issues_repo_head_hexsha": "a848e52552a9205124b7ae13c7bcd2b860eb4530", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AABB_tree/examples/AABB_tree/AABB_custom_indexed_triangle_set_array_example.cpp", "max_forks_repo_name": "guorongtao/cgal", "max_forks_repo_head_hexsha": "a848e52552a9205124b7ae13c7bcd2b860eb4530", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-05T04:18:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-05T04:18:59.000Z", "avg_line_length": 31.7841726619, "max_line_length": 153, "alphanum_fraction": 0.6349026709, "num_tokens": 1191, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.44706871876267545}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_HYPOT_HPP_INCLUDED\n#include <boost/simd/function/fast.hpp>\n#include <boost/simd/function/fast.hpp>\n\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/function/scalar/is_inf.hpp>\n#include <boost/simd/function/scalar/is_nan.hpp>\n#endif\n#include <boost/simd/constant/maxexponentm1.hpp>\n#include <boost/simd/constant/minexponent.hpp>\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/scalar/exponent.hpp>\n#include <boost/simd/function/scalar/ldexp.hpp>\n#include <boost/simd/function/scalar/max.hpp>\n#include <boost/simd/function/scalar/min.hpp>\n#include <boost/simd/function/scalar/sqr.hpp>\n#include <boost/simd/function/scalar/sqrt.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( hypot_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_<bd::floating_<A0> >\n                          , bd::scalar_<bd::floating_<A0> >\n                          )\n  {\n\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      using i_t = bd::as_integer_t<A0>;\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if (is_nan(a0) && is_inf(a1)) return Inf<A0>();\n      if (is_inf(a0) && is_nan(a1)) return Inf<A0>();\n      #endif\n      A0 r =  bs::abs(a0);\n      A0 i =  bs::abs(a1);\n      i_t e =  exponent(bs::max(i, r));\n      e = bs::min(bs::max(e,Minexponent<A0>()),Maxexponentm1<A0>());\n      return bs::ldexp(sqrt(sqr(bs::ldexp(r, -e))+sqr(bs::ldexp(i, -e))), e);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( hypot_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_<bd::floating_<A0> >\n                          , bd::scalar_<bd::floating_<A0> >\n                          , boost::simd::std_tag\n                          )\n  {\n\n    BOOST_FORCEINLINE A0 operator() ( A0 a0, A0 a1\n                                    , std_tag const&) const BOOST_NOEXCEPT\n    {\n      return std::hypot(a0, a1);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "6096eaa8b09cee3f56dc7a1cabe432074ad89027", "size": 2837, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/hypot.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/scalar/function/hypot.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/hypot.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7738095238, "max_line_length": 100, "alphanum_fraction": 0.5720831865, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4470687126092705}}
{"text": "#include <iostream>\n#include <string>\n#include <windows.h>\n#include <time.h>\n#include <Eigen/Dense>\n#include \"utlt.h\"\n#include \"OneD_system_solve.h\"\n#include \"OneD_exciton_TDDFT_Linear_resp.h\"\n\nusing namespace std;\nusing Eigen::VectorXd;\n\nint main()\n{\n\tclock_t t_begin,t_end;\n\tt_begin=clock();\n\tint band_considered(3), gridnum(150), kpointnum(151);\n\tdouble amplitude1(3.5645),amplitude2(1.0);\n\tVectorXd w1(2), h1(w1.rows());\n\t// w1<<2.4, 0.6; h1<<0.0, 8.0;\n\tw1<<0.5, 0.5; h1<<0.0, 20.0;\n\tVectorXd w2(4), h2(w2.rows());\n\tw2<<2.4, 0.6, 2.8, 0.2;\n\th2<<0.0, 8.0, 0.0, 10.0;\n\t// --------------------------------------------------------------------------------\n\tOneD_system KP_model(w1, h1, \"My_kp_model\", gridnum, kpointnum, band_considered);\n\tcout<<KP_model.name<<\" is running...\"<<endl;\n\tKP_model.Solve_wf_dens();\n\tKP_model.Write_Energy();\n\tKP_model.Write_system_spec ();\n\texciton_TDDFT_Tamm_Dancoff_Soft_Coulumb KP_exciton( KP_model,1,2 );\n\tKP_exciton.Solve_f_kq (0.01);\n\tKP_exciton.Write_excitation_shift ();\n\tKP_exciton.Write_excitation_mix ();\n\tKP_exciton.Write_matrix_fkq ();\n\tKP_exciton.Write_eff_fkq ();\n\tKP_exciton.Write_sum_fkq();\n\t//--------------------------------------------------------------------------------\n\t// OneD_system Double_model(w2, h2, \"dmodel\", gridnum, kpointnum, band_considered);\n\t// cout<<Double_model.name<<\" is running...\"<<endl;\n\t// Double_model.Write_system_spec ();\n\t// Double_model.Solve_wf_dens ();\n\t// exciton_TDDFT_Tamm_Dancoff_delta Dw_exciton( Double_model,1,2 );\n\t// Dw_exciton.Solve_f_kq (amplitude1);\n\t// Dw_exciton.Write_excitation_shift ();\n\t// Dw_exciton.Write_excitation_mix ();\n\t// Dw_exciton.Write_matrix_fkq ();\n\t// Dw_exciton.Write_eff_fkq ();\n\t// Dw_exciton.Write_sum_fkq();\n\t//--------------------------------------------------------------------------------\n\t// OneD_system scmodel(w1, h1, \"scmodel\", gridnum, kpointnum, band_considered);\n\t// cout<<scmodel.name<<\" is running...\"<<endl;\n\t// scmodel.Write_system_spec ();\n\t// scmodel.Solve_wf_dens ();\n\t// exciton_TDDFT_Tamm_Dancoff_Soft_Coulumb sc_exciton( scmodel,1,2 );\n\t// sc_exciton.Solve_f_kq (amplitude2);\n\t// sc_exciton.Write_excitation_shift ();\n\t// sc_exciton.Write_excitation_mix ();\n\t// sc_exciton.Write_matrix_fkq ();\n\t// sc_exciton.Write_eff_fkq ();\n\t// sc_exciton.Write_sum_fkq();\n\t//---------------------------------------------------------------------------------\n\t// OneD_system anymodel(w1, h1, \"anymodel\", gridnum, kpointnum, band_considered);\n\t// cout<<anymodel.name<<\" is running...\"<<endl;\n\t// anymodel.Write_system_spec ();\n\t// anymodel.Solve_wf_dens ();\n\t// exciton_TDDFT_Tamm_Dancoff_any_kernel any_exciton( anymodel,1,2 );\n\t// any_exciton.Solve_f_kq (amplitude1);\n\t// any_exciton.Write_excitation_shift ();\n\t// any_exciton.Write_excitation_mix ();\n\t// any_exciton.Write_matrix_fkq ();\n\t// any_exciton.Write_eff_fkq ();\n\t// any_exciton.Write_sum_fkq();\n\t//---------------------------------------------------------------------------------\n\tEigen::Matrix2cd a;\n\ta<<dcmplx(1,2),dcmplx(2,3),dcmplx(1,4),dcmplx(2,4);\n\tcout<<a<<endl;\n\tcout<<a.cwiseAbs()<<endl;\n\tt_end=clock();\n\tcout<<\"program running time \"<<(double(t_end)-double(t_begin))/CLOCKS_PER_SEC<<endl;\n\tMessageBox(NULL, L\"Work finished!\", L\"Notice\", MB_OK);\n\treturn 0;\n}", "meta": {"hexsha": "f4c5f78095f4bcf661c8a30bd3a0680303cb2d3b", "size": 3251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Exciton_import/main.cpp", "max_stars_repo_name": "ylqk9/ExcitonEnergyCalculation", "max_stars_repo_head_hexsha": "1bf9995d8dd27c2ac4418a2532f9c1a4ffbbea65", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Exciton_import/main.cpp", "max_issues_repo_name": "ylqk9/ExcitonEnergyCalculation", "max_issues_repo_head_hexsha": "1bf9995d8dd27c2ac4418a2532f9c1a4ffbbea65", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exciton_import/main.cpp", "max_forks_repo_name": "ylqk9/ExcitonEnergyCalculation", "max_forks_repo_head_hexsha": "1bf9995d8dd27c2ac4418a2532f9c1a4ffbbea65", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1686746988, "max_line_length": 85, "alphanum_fraction": 0.6268840357, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.44706593661526006}}
{"text": "\n//  Copyright (c) 2011-2013 Thomas Heller\n//\n//  Distributed under the Boost Software License, Version 1.0. (See accompanying\n//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include \"jacobi.hpp\"\n#include <boost/program_options.hpp>\n#include <iostream>\n#include <chrono>\n\nusing boost::program_options::variables_map;\nusing boost::program_options::options_description;\nusing boost::program_options::value;\nusing boost::program_options::store;\nusing boost::program_options::parse_command_line;\n\nusing boost::shared_ptr;\nusing std::min;\nusing std::vector;\n\n\nvoid jacobi_kernel_wrap(size_t y_begin, size_t y_end, size_t n, vector<double> & dst, vector<double> const & src) {\n    for(size_t y = y_begin; y < y_end; ++y) {\n        size_t offset = y * n;\n        for(size_t x = offset + 1; x < offset + n-1; ++x) {\n            dst[x] = (src[x-n] + src[x+n] + src[x] + src[x-1] + src[x+1]) * 0.2;\n        }\n    }\n}\n\nvoid jacobi( size_t n , size_t iterations, size_t block_size, std::string output_filename) {\n    shared_ptr< vector<double> > grid_new(new vector<double>(n * n, 1));\n    shared_ptr< vector<double> > grid_old(new vector<double>(n * n, 1));\n\n    size_t n_block = static_cast<size_t>(std::ceil(double(n)/block_size));\n\n#pragma omp parallel \n{\n#pragma omp single\n{\n    auto start = std::chrono::high_resolution_clock::now();\n\n    for(size_t i = 0; i < iterations; ++i) {\n        for(size_t y = 1, j = 0; y < n - 1; y += block_size, ++j) {\n            size_t y_end = min(y + block_size, n - 1);\n\n            double *dest = (*grid_new).data();\n            double *src = (*grid_old).data();\n\n#pragma omp task firstprivate(y, y_end, grid_new, grid_old) depend(inout: dest[y*n], src[y*n])\n        {\n            jacobi_kernel_wrap(y, y_end, n, boost::ref(*grid_new), boost::cref(*grid_old));\n        }\n            std::swap(grid_new, grid_old);\n        }\n    }\n#pragma omp taskwait\n    auto end = std::chrono::high_resolution_clock::now();\n    double elapsed = std::chrono::duration_cast< std::chrono::duration<double> >(end-start).count();\n    jacobi_smp::report_timing(n, iterations, elapsed);\n    jacobi_smp::output_grid(output_filename, *grid_old, n);\n}}\n\n}\n\n\nint main(int argc, char **argv)\n{\n    options_description\n        desc_cmd(\"usage: jacobi_omp [options]\");\n\n    desc_cmd.add_options()\n        (\n         \"n\", value<std::size_t>()->default_value(16)\n         , \"Will run on grid with dimensions (n x n)\"\n        )\n        (\n         \"iterations\", value<std::size_t>()->default_value(1000)\n         , \"Number of iterations\"\n        )\n        (\n         \"block-size\", value<std::size_t>()->default_value(256)\n         , \"Block size of the different chunks to calculate in parallel\"\n        )\n        (\n         \"output-filename\", value<std::string>()\n         , \"Filename of the result (if empty no result is written)\"\n        );\n\n    variables_map vm;\n    store(parse_command_line( argc, argv, desc_cmd), vm);\n    boost::program_options::notify(vm);\n\n    std::size_t n           = vm[\"n\"].as<std::size_t>();\n    std::size_t iterations  = vm[\"iterations\"].as<std::size_t>();\n    std::size_t block_size  = vm[\"block-size\"].as<std::size_t>();\n\n    std::string output_filename;\n    if(vm.count(\"output-filename\"))\n    {\n        output_filename = vm[\"output-filename\"].as<std::string>();\n    }\n\n    jacobi(n, iterations, block_size, output_filename);\n\n    return 0;\n}\n", "meta": {"hexsha": "020a92f9edc00f95957d759621e9dd7ea4329498", "size": 3401, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/hpx/jacobi_smp/jacobi_omp.cpp", "max_stars_repo_name": "tianyi93/hpxMP_mirror", "max_stars_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-07-16T14:39:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T11:25:09.000Z", "max_issues_repo_path": "examples/hpx/jacobi_smp/jacobi_omp.cpp", "max_issues_repo_name": "tianyi93/hpxMP_mirror", "max_issues_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-06-18T14:59:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-16T20:43:57.000Z", "max_forks_repo_path": "examples/hpx/jacobi_smp/jacobi_omp.cpp", "max_forks_repo_name": "tianyi93/hpxMP_mirror", "max_forks_repo_head_hexsha": "668e8881a6f2f437a614ae92e205ae49f083691e", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T18:44:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-21T11:17:28.000Z", "avg_line_length": 31.2018348624, "max_line_length": 115, "alphanum_fraction": 0.6218759188, "num_tokens": 909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370114, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.4470514756979748}}
{"text": "#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Monge_via_jet_fitting.h>\n\n#include <fstream>\n#include <cassert>\n\n#include <CGAL/property_map.h>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\nusing namespace std;\n\n#include \"PolyhedralSurf.h\"\n#include \"PolyhedralSurf_operations.h\"\n#include \"PolyhedralSurf_rings.h\"\n\n//Kernel of the PolyhedralSurf\ntypedef double                DFT;\ntypedef CGAL::Simple_cartesian<DFT>  Data_Kernel;\ntypedef Data_Kernel::Point_3  DPoint;\ntypedef Data_Kernel::Vector_3 DVector;\n\n//HDS\ntypedef PolyhedralSurf::Vertex_handle Vertex_handle;\ntypedef PolyhedralSurf::Vertex Vertex;\ntypedef PolyhedralSurf::Halfedge_handle Halfedge_handle;\ntypedef PolyhedralSurf::Halfedge Halfedge;\ntypedef PolyhedralSurf::Vertex_iterator Vertex_iterator;\ntypedef PolyhedralSurf::Facet_handle Facet_handle;\ntypedef PolyhedralSurf::Facet Facet;\n\nstruct Hedge_cmp{\n  bool operator()(Halfedge_handle a,  Halfedge_handle b) const{\n    return &*a < &*b;\n  }\n};\n\nstruct Facet_cmp{\n  bool operator()(Facet_handle a, Facet_handle b) const{\n    return &*a < &*b;\n  }\n};\n\n//Vertex property map, with std::map\ntypedef std::map<Vertex*, int> Vertex2int_map_type;\ntypedef boost::associative_property_map< Vertex2int_map_type > Vertex_PM_type;\ntypedef T_PolyhedralSurf_rings<PolyhedralSurf, Vertex_PM_type > Poly_rings;\n\n//Hedge property map, with enriched Halfedge with its length\n// typedef HEdge_PM<PolyhedralSurf> Hedge_PM_type;\n// typedef T_PolyhedralSurf_hedge_ops<PolyhedralSurf, Hedge_PM_type> Poly_hedge_ops;\n//Hedge property map, with std::map\ntypedef std::map<Halfedge_handle, double, Hedge_cmp> Hedge2double_map_type;\ntypedef boost::associative_property_map<Hedge2double_map_type> Hedge_PM_type;\ntypedef T_PolyhedralSurf_hedge_ops<PolyhedralSurf, Hedge_PM_type> Poly_hedge_ops;\n\n// //Facet property map with enriched Facet with its normal\n// typedef Facet_PM<PolyhedralSurf> Facet_PM_type;\n// typedef T_PolyhedralSurf_facet_ops<PolyhedralSurf, Facet_PM_type> Poly_facet_ops;\n//Facet property map, with std::map\ntypedef std::map<Facet_handle, Vector_3, Facet_cmp> Facet2normal_map_type;\ntypedef boost::associative_property_map<Facet2normal_map_type> Facet_PM_type;\ntypedef T_PolyhedralSurf_facet_ops<PolyhedralSurf, Facet_PM_type> Poly_facet_ops;\n\ntypedef double                   LFT;\ntypedef CGAL::Simple_cartesian<LFT>     Local_Kernel;\ntypedef CGAL::Monge_via_jet_fitting<Data_Kernel> My_Monge_via_jet_fitting;\ntypedef My_Monge_via_jet_fitting::Monge_form My_Monge_form;\n\n\n// default parameter values and global variables\nunsigned int d_fitting = 2;\nunsigned int d_monge = 2;\nunsigned int nb_rings = 0;//seek min # of rings to get the required #pts\nunsigned int nb_points_to_use = 0;//\nbool verbose = false;\nunsigned int min_nb_points = (d_fitting + 1) * (d_fitting + 2) / 2;\n\n\n//gather points around the vertex v using rings on the\n//polyhedralsurf. the collection of points resorts to 3 alternatives:\n// 1. the exact number of points to be used\n// 2. the exact number of rings to be used\n// 3. nothing is specified\nvoid gather_fitting_points(Vertex* v,\n                           std::vector<DPoint> &in_points,\n                           Vertex_PM_type& vpm)\n{\n  //container to collect vertices of v on the PolyhedralSurf\n  std::vector<Vertex*> gathered;\n  //initialize\n  in_points.clear();\n\n  //OPTION -p nb_points_to_use, with nb_points_to_use != 0. Collect\n  //enough rings and discard some points of the last collected ring to\n  //get the exact \"nb_points_to_use\"\n  if ( nb_points_to_use != 0 ) {\n    Poly_rings::collect_enough_rings(v, nb_points_to_use, gathered, vpm);\n    if ( gathered.size() > nb_points_to_use ) gathered.resize(nb_points_to_use);\n  }\n  else { // nb_points_to_use=0, this is the default and the option -p is not considered;\n    // then option -a nb_rings is checked. If nb_rings=0, collect\n    // enough rings to get the min_nb_points required for the fitting\n    // else collect the nb_rings required\n    if ( nb_rings == 0 )\n      Poly_rings::collect_enough_rings(v, min_nb_points, gathered, vpm);\n    else Poly_rings::collect_i_rings(v, nb_rings, gathered, vpm);\n  }\n\n  //store the gathered points\n  std::vector<Vertex*>::iterator\n    itb = gathered.begin(), ite = gathered.end();\n  CGAL_For_all(itb,ite) in_points.push_back((*itb)->point());\n}\n\n///////////////MAIN///////////////////////////////////////////////////////\n#if defined(CGAL_USE_BOOST_PROGRAM_OPTIONS) && ! defined(DONT_USE_BOOST_PROGRAM_OPTIONS)\nint main(int argc, char *argv[])\n#else\nint main()\n#endif\n{\n  string if_name_string;\n  string if_name; //input file name\n  string w_if_name;  //as above, but / replaced by _\n  string res4openGL_fname;\n  string verbose_fname;\n  std::ofstream out_4ogl, out_verbose;\n\n  try {\n#if defined(CGAL_USE_BOOST_PROGRAM_OPTIONS) && ! defined(DONT_USE_BOOST_PROGRAM_OPTIONS)\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n      (\"help,h\", \"produce help message.\")\n      (\"input-file,f\", po::value<string>(&if_name_string)->default_value(CGAL::data_file_path(\"meshes/ellipe0.003.off\")),\n       \"name of the input off file\")\n      (\"degree-jet,d\", po::value<unsigned int>(&d_fitting)->default_value(2),\n       \"degree of the jet, 1 <= degre-jet <= 4\")\n      (\"degree-monge,m\", po::value<unsigned int>(&d_monge)->default_value(2),\n       \"degree of the Monge rep, 1 <= degree-monge <= degree-jet\")\n      (\"nb-rings,a\", po::value<unsigned int>(&nb_rings)->default_value(0),\n       \"number of rings to collect neighbors. 0 means collect enough rings to make appro possible a>=1 fixes the nb of rings to be collected\")\n      (\"nb-points,p\", po::value<unsigned int>(&nb_points_to_use)->default_value(0),\n       \"number of neighbors to use.  0 means this option is not considered, this is the default p>=1 fixes the nb of points to be used\")\n      (\"verbose,v\", po::value<bool>(&verbose)->default_value(false),\n       \"verbose output on text file\")\n      ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\")) {\n      cout << desc << \"\\n\";\n      return 1;\n    }\n#else\n    std::cerr << \"Command-line options require Boost.ProgramOptions\" << std::endl;\n    if_name_string = CGAL::data_file_path(\"meshes/ellipe0.003.off\");\n    d_fitting = 2;\n    d_monge = 2;\n    nb_rings = 0;\n    nb_points_to_use = 0;\n    verbose = false;\n#endif\n  }\n  catch(exception& e) {\n    cerr << \"error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n  catch(...) {\n    cerr << \"Exception of unknown type!\\n\";\n  }\n\n  //modify global variables which are fct of options:\n  min_nb_points = (d_fitting + 1) * (d_fitting + 2) / 2;\n  if (nb_points_to_use < min_nb_points && nb_points_to_use != 0)\n    {std::cerr << \"the nb of points asked is not enough to perform the fitting\" << std::endl; exit(0);}\n\n  //prepare output file names\n  //--------------------------\n  std::cerr << \"if_name_string\" << if_name_string  << std::endl;\n  if_name = if_name_string;\n\n  w_if_name = if_name;\n  for(unsigned int i=0; i<w_if_name.size(); i++)\n    if (w_if_name[i] == '/') w_if_name[i]='_';\n  cerr << if_name << '\\n';\n  cerr << w_if_name << '\\n';\n\n  res4openGL_fname = w_if_name + \".4ogl.txt\";\nstd::cerr << \"res4openGL_fname\" << res4openGL_fname  << std::endl;\n  out_4ogl.open(res4openGL_fname.c_str(), std::ios::out);\n  assert(out_4ogl.good());\n  //if verbose only...\n  if(verbose){\n    verbose_fname  = w_if_name + \".verb.txt\";\n    out_verbose.open(verbose_fname.c_str(), std::ios::out);\n    assert(out_verbose.good());\n    CGAL::IO::set_pretty_mode(out_verbose);\n  }\n  unsigned int nb_vertices_considered = 0;//count vertices for verbose\n\n  //load the model from <mesh.off>\n  //------------------------------\n  PolyhedralSurf P;\n  std::ifstream stream(if_name.c_str());\n  stream >> P;\n  std::cout << \"loadMesh...  \"<< \"Polysurf with \" << P.size_of_vertices()\n            << \" vertices and \" << P.size_of_facets()\n            << \" facets. \" << std::endl;\n\n  if(verbose)\n    out_verbose << \"Polysurf with \" << P.size_of_vertices()\n                << \" vertices and \" << P.size_of_facets()\n                << \" facets. \" << std::endl;\n  //exit if not enough points in the model\n  if (min_nb_points > P.size_of_vertices())    exit(0);\n\n  //create property maps\n  //-----------------------------\n  //Vertex, using a std::map\n  Vertex2int_map_type vertex2props;\n  Vertex_PM_type vpm(vertex2props);\n\n  //Hedge, with enriched hedge\n  //HEdgePM_type hepm = get_hepm(boost::edge_weight_t(), P);\n  //Hedge, using a std::map\n  Hedge2double_map_type hedge2props;\n  Hedge_PM_type hepm(hedge2props);\n\n  //Facet PM, with enriched Facet\n  //FacetPM_type fpm = get_fpm(boost::vertex_attribute_t(), P);\n  //Facet PM, with std::map\n  Facet2normal_map_type facet2props;\n  Facet_PM_type fpm(facet2props);\n\n  //initialize Polyhedral data : length of edges, normal of facets\n  Poly_hedge_ops::compute_edges_length(P, hepm);\n  Poly_facet_ops::compute_facets_normals(P, fpm);\n\n  //MAIN LOOP: perform calculation for each vertex\n  //----------------------------------------------\n  std::vector<DPoint> in_points;  //container for data points\n  Vertex_iterator vitb, vite;\n\n  //initialize the tag of all vertices to -1\n  vitb = P.vertices_begin(); vite = P.vertices_end();\n  CGAL_For_all(vitb,vite) put(vpm, &(*vitb), -1);\n\n  vitb = P.vertices_begin(); vite = P.vertices_end();\n  for (; vitb != vite; vitb++) {\n    //initialize\n    Vertex* v = &(*vitb);\n    in_points.clear();\n    My_Monge_form monge_form;\n\n    //gather points around the vertex using rings\n    gather_fitting_points(v, in_points, vpm);\n\n    //skip if the nb of points is to small\n    if ( in_points.size() < min_nb_points )\n      {std::cerr << \"not enough pts for fitting this vertex\" << in_points.size() << std::endl;\n        continue;}\n\n    // perform the fitting\n    My_Monge_via_jet_fitting monge_fit;\n    monge_form = monge_fit(in_points.begin(), in_points.end(),\n                           d_fitting, d_monge);\n    //switch min-max ppal curv/dir wrt the mesh orientation\n    const DVector normal_mesh = Poly_facet_ops::compute_vertex_average_unit_normal(v, fpm);\n    monge_form.comply_wrt_given_normal(normal_mesh);\n\n    //OpenGL output. Scaling for ppal dir, may be optimized with a\n    //global mean edges length computed only once on all edges of P\n    DFT scale_ppal_dir = Poly_hedge_ops::compute_mean_edges_length_around_vertex(v, hepm)/2;\n\n    out_4ogl << v->point()  << \" \";\n    monge_form.dump_4ogl(out_4ogl, scale_ppal_dir);\n\n    //verbose txt output\n    if (verbose) {\n      std::vector<DPoint>::iterator itbp = in_points.begin(), itep = in_points.end();\n      out_verbose << \"in_points list : \" << std::endl ;\n      for (;itbp!=itep;itbp++) out_verbose << *itbp << std::endl ;\n\n      out_verbose << \"--- vertex \" <<  ++nb_vertices_considered\n                  <<        \" : \" << v->point() << std::endl\n                  << \"number of points used : \" << in_points.size() << std::endl\n        ;// << monge_form;\n    }\n  } //all vertices processed\n\n  //cleanup filenames\n  //------------------\n  out_4ogl.close();\n  if(verbose) {\n    out_verbose.close();\n  }\n  return 0;\n}\n", "meta": {"hexsha": "eb100d51f6ae10028f01d8dfa1334c5b0b10899b", "size": 11148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Jet_fitting_3/examples/Jet_fitting_3/Mesh_estimation.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Jet_fitting_3/examples/Jet_fitting_3/Mesh_estimation.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Jet_fitting_3/examples/Jet_fitting_3/Mesh_estimation.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 36.7920792079, "max_line_length": 142, "alphanum_fraction": 0.6817366344, "num_tokens": 3074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.44705147081383645}}
{"text": "\n\n#include<iostream>\n#include <Eigen/Eigenvalues> \n#include\"numerics.hpp\"\n#include\"reddm.hpp\"\n#include\"tpoperators.hpp\"\n#include \"files.hpp\"\n#include <boost/program_options.hpp>\n\nusing namespace boost::program_options;\nusing namespace Many_Body;\nint main(int argc, char *argv[])\n{\n  using Mat= Operators::Mat;\n  size_t M{};\n  size_t L{};\n  double t0{};\n  double omega{};\n  double gamma{};\n  bool PB{};\n  try\n  {\n    options_description desc{\"Options\"};\n    desc.add_options()\n      (\"help,h\", \"Help screen\")\n      (\"L\", value(&L)->default_value(4), \"L\")\n      (\"M\", value(&M)->default_value(2), \"M\")\n      (\"t\", value(&t0)->default_value(1.), \"t0\")\n      (\"gam\", value(&gamma)->default_value(1.), \"gamma\")\n      (\"omg\", value(&omega)->default_value(1.), \"omega\")\n    (\"pb\", value(&PB)->default_value(true), \"PB\");\n  \n\n\n    variables_map vm;\n    store(parse_command_line(argc, argv, desc), vm);\n    notify(vm);\n\n    if (vm.count(\"help\"))\n      {std::cout << desc << '\\n'; return 0;}\n    else{\n      if (vm.count(\"L\"))\n      {      std::cout << \"L: \" << vm[\"L\"].as<size_t>() << '\\n';\n\t\n      }\n     if (vm.count(\"M,m\"))\n      {\n\tstd::cout << \"M: \" << vm[\"M\"].as<size_t>() << '\\n';\n\t\n      }\n      if (vm.count(\"t\"))\n      {\n\tstd::cout << \"t0: \" << vm[\"t\"].as<double>() << '\\n';\t\n      }\n       if (vm.count(\"omg\"))\n      {\n\tstd::cout << \"omega: \" << vm[\"omg\"].as<double>() << '\\n';\n      }\n       if (vm.count(\"gam\"))\n      {\n\tstd::cout << \"gamma: \" << vm[\"gam\"].as<double>() << '\\n';\n      }\n              if (vm.count(\"pb\"))\n      {\n\tstd::cout << \"PB: \" << vm[\"pb\"].as<bool>() << '\\n';\n      }\n    }\n  }\n  catch (const error &ex)\n  {\n    std::cerr << ex.what() << '\\n';\n    return 0;\n  }\n\n    \nusing HolsteinBasis= TensorProduct<ElectronBasis, PhononBasis>;\n   // std::vector<size_t> ee(L, 0);\n   //    ee[L-1]=1;\n   //    ElectronState aa(ee);\n   // ElectronBasis e(aa);\n   ElectronBasis e( L, 1);\n   //   std::cout<< e<<std::endl;\n  \n  PhononBasis ph(L, M);\n  //  std::cout<< ph<<std::endl;\n  HolsteinBasis TP(e, ph);\n  //  std::cout<< TP<<std::endl;\n\n  std::cout<<\"total dim \"<< TP.dim << std::endl;\n  std::cout<<std::endl;\n        Mat E1=Operators::EKinOperatorL(TP, e, t0, PB);\n      Mat Ebdag=Operators::NBosonCOperator(TP, ph, gamma, PB);\n      Mat Eb=Operators::NBosonDOperator(TP, ph, gamma, PB);\n      Mat Eph=Operators::NumberOperator(TP, ph, omega,  PB);\n\n\n //      Eigen::VectorXd eigenVals(TP.dim);\n      Mat H=E1  +Ebdag + Eb+ Eph;\n      //+phMOM;\n      //\n      //\n\n\t//\n      //+\n      //+ phKNN phK+;\n      \n          Eigen::MatrixXcd HH=Eigen::MatrixXcd(H);\n\t  //\t   std::cout<< HH << std::endl;\n\t  // for(int i=0; i<HH.rows(); i++)\n\t  //   {\n\t  //    for(int j=0; j<HH.rows(); j++)\n\t  //   {\n\t  //     if(std::abs(HH(i, j))>0.00001){\n\t  //     \tif(std::abs(HH(j, i)-HH(i, j))>0.000001){ std::cout<< \"err \"<<std::endl;}\n\t  //     \t\tstd::cout<< \"went from  \"<< i << \" to \"<< j << \"  \" <<HH(i, j)<< std::endl;\n\t  //     }\n\t  //   }\n\t  //   }\n\t  // std::cout<< HH << std::endl;\n\t     Eigen::VectorXd ev=Eigen::VectorXd(TP.dim);\n\t     diagMat(HH, ev);\n\t     std::cout<<\"GS \"<< std::setprecision(8)<< ev[0]<< std::endl;\n\t     std::cout<< \" nect \"<< std::endl;\n\t     std::cout<< ev<<std::endl;\n\t\t\t      bin_write(\"holstdata.bin\", ev);\n\t     //\t     std::cout<< HH.col(0).adjoint()*Eph*HH.col(0);\n   // \t     Eigen::MatrixXd MDF2=HH.adjoint()*(O)*HH;\n   // Eigen::VectorXd v=MDF2.diagonal();\n   // std::cout<< v << std::endl;\n   // std::cout <<\"mean \"<< v.mean()<< std::endl;\n // \t  bool isDiag=false;\n // \t //  std::vector<double> Tr={0.0100, 0.1000, 1.000, 2.0000, 5.0000, 10.0000};\n // \t //  for(auto t: Tr){\n // \t //      std::string sT=std::string(std::to_string(t)).substr(0,6);\n // auto t=0.5;\n // \t       auto optModes=makeThermalRDMTP(HH,ev,  TP, t, isDiag, 0);\n // \t //  //\t  std::cout << \"sum of all eigenvalues \"<< optModes.sum()<< std::endl;\n // \t //      isDiag=true;\n // \t  int n=0;\n\t \n // \t  for(auto& l : optModes)\n // \t    {\n // \t      \t      std::string sn=std::string(std::to_string(n)).substr(0,1);\n // \t\t      //std::string filename=\"OML\"+std::to_string(L)+\"M\"+std::to_string(M)+\"t0_\"+\"1.0\"+\"gam\"+sgam+\"omg\"+ somg+\"T\"+ sT+ \"esec\" +sn  + \".bin\";\n // \t\t std::cout << n << std::endl;\n // \t\t std::cout<< \"value \"<< \" fot T = \"<< t <<std::endl;\n // \t\t \t      std::cout<< l<<std::endl;\n // \t\t\t      std::cout << \" and sum \"<< l.sum()<< std::endl;\n  // \t\t\t      //bin_write(filename, l);\n // \t\t n++;\n // \t    }\n\t  \n\t  \n\t  // }\n  //   std::cout<< TP<< std::endl;\n  // Eigen::VectorXd v1=Eigen::VectorXd::Zero(TP.dim);\n  // v1[1]=1/std::sqrt(2);\n  // Eigen::VectorXd v2=Eigen::VectorXd::Zero(TP.dim);\n  //   v2[5]=1/std::sqrt(2);\n  // \tEigen::VectorXd V1=v1 +v2;\n  // \tEigen::MatrixXd V2=V1.transpose();\n  // \t// std::cout<< V1<<std::endl;\n  // \t// std::cout<< V2<<std::endl;\t\n  // \tMatrixXd M=V1*(V2);\n  // \t// std::cout<< M<<std::endl;\n  // \t// \tstd::cout<< g2<<std::endl;\n  // \t//\tmakeRedDM(g2, 0, M);\n  // \tmakeRedDMTP(TP, ph,  0, M);\n  return 0;\n}\n", "meta": {"hexsha": "cd517a9bd9eeab7a528659ca9c03df9331071e4c", "size": 4977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/holstexDi.cpp", "max_stars_repo_name": "jansendavid/many-body-lib", "max_stars_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/holstexDi.cpp", "max_issues_repo_name": "jansendavid/many-body-lib", "max_issues_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/holstexDi.cpp", "max_forks_repo_name": "jansendavid/many-body-lib", "max_forks_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9360465116, "max_line_length": 146, "alphanum_fraction": 0.4962829013, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4470148597431645}}
{"text": "#ifndef qlex_multibootstrap_hpp\n#define qlex_multibootstrap_hpp\n\n#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>\n#include <ql/termstructures/bootstraphelper.hpp>\n#include <ql/math/optimization/costfunction.hpp>\n#include <ql/math/optimization/constraint.hpp>\n#include <ql/math/optimization/armijo.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/math/optimization/leastsquare.hpp>\n#include <ql/math/optimization/problem.hpp>\n#include <ql/utilities/dataformatters.hpp>\n#include <ql/termstructures/iterativebootstrap.hpp>\n#include <ql/patterns/lazyobject.hpp>\n#include <boost/shared_ptr.hpp>\n\nusing namespace QuantLib;\n\nnamespace QLExtension {\n\t// penalty function class for multiple curve\n\ttemplate <class Curve>\n\tclass MultiCurvePenaltyFunction : public CostFunction {\n\tpublic:\n\t\ttypedef typename Curve::traits_type Traits;\n\t\ttypedef typename Traits::helper helper;\n\t\ttypedef\n\t\t\ttypename std::vector< boost::shared_ptr<helper> >::const_iterator helper_iterator;\n\n\t\tMultiCurvePenaltyFunction(std::vector<Curve*> curves,\n\t\t\tstd::vector<Size> initialIndexes,\n\t\t\tstd::vector<helper_iterator> rateHelpersStarts,\n\t\t\tstd::vector<helper_iterator> rateHelpersEnds)\n\t\t\t: curves_(curves), initialIndexes_(initialIndexes),\n\t\t\trateHelpersStarts_(rateHelpersStarts), rateHelpersEnds_(rateHelpersEnds) {\n\t\t}\n\n\t\tReal value(const Array& x) const;\n\t\tDisposable<Array> values(const Array& x) const;\n\n\tprivate:\n\t\tstd::vector<Curve*> curves_;\n\t\tstd::vector<Size> initialIndexes_;\n\t\tstd::vector<helper_iterator> rateHelpersStarts_;\n\t\tstd::vector<helper_iterator> rateHelpersEnds_;\n\t};\n\n\n\ttemplate <class Curve>\n\tclass MultiCurveOptimizer : public LazyObject {\n\tpublic:\n\t\tMultiCurveOptimizer(bool forcePositive = true)\n\t\t\t: accuracy_(1.0e-12), forcePositive_(forcePositive){};\n\t\tvoid addTermStructure(Curve* c) {\n\t\t\tfor (Size i = 0; i<c->instruments_.size(); ++i){\n\t\t\t\tthis->registerWith(c->instruments_[i]);\n\t\t\t}\n\t\t\tts_.push_back(c);\n\t\t\taccuracy_ = accuracy_ > c->accuracy_ ? c->accuracy_ : accuracy_;\n\t\t};\n\t\tvoid optimize() const { calculate(); };\n\t\t//! \\name Observer interface\n\t\t//@{\n\t\tvoid update();\n\t\t//@}\n\tprivate:\n\t\t//! \\name LazyObject interface\n\t\t//@{\n\t\tvoid performCalculations() const;\n\t\t//@}\n\t\tReal accuracy_;\n\t\tbool forcePositive_;\n\t\tstd::vector<Curve*> ts_;\n\t};\n\n\ttemplate <class Curve>\n\tvoid MultiCurveOptimizer<Curve>::update() {\n\t\tLazyObject::update();\n\t}\n\n\ttemplate <class Curve>\n\tvoid MultiCurveOptimizer<Curve>::performCalculations() const {\n\n\t\tstd::vector<Size> initialIndexes;\n\t\tstd::vector< typename MultiCurvePenaltyFunction<Curve>::helper_iterator > rateHelpersStarts;\n\t\tstd::vector< typename MultiCurvePenaltyFunction<Curve>::helper_iterator > rateHelpersEnds;\n\n\t\tSize nInsts = 0;\n\t\tfor (Size i = 0; i < ts_.size(); i++) {\n\t\t\tts_[i]->bootstrap_.initialize();\n\t\t\tnInsts += ts_[i]->instruments_.size();\n\t\t\tinitialIndexes.push_back(1);\n\t\t\trateHelpersStarts.push_back(ts_[i]->instruments_.begin());\n\t\t\trateHelpersEnds.push_back(ts_[i]->instruments_.end());\n\t\t}\n\n\t\tLevenbergMarquardt solver(accuracy_,\n\t\t\taccuracy_,\n\t\t\taccuracy_);\n\n\t\tEndCriteria endCriteria(20 * nInsts, 10, 0.00, accuracy_, 0.00);\n\t\tPositiveConstraint posConstraint;\n\t\tNoConstraint noConstraint;\n\t\tConstraint& solverConstraint = forcePositive_ ?\n\t\t\tstatic_cast<Constraint&>(posConstraint) :\n\t\t\tstatic_cast<Constraint&>(noConstraint);\n\n\t\tArray startArray(nInsts);\n\n\t\tSize pos = 0;\n\t\tfor (Size i = 0; i < ts_.size(); i++) {\n\t\t\tfor (Size j = 0; j < ts_[i]->instruments_.size(); j++) {\n\t\t\t\tstartArray[pos] = ts_[i]->data_[j + initialIndexes[i]];\n\t\t\t\tpos++;\n\t\t\t}\n\t\t}\n\n\t\tMultiCurvePenaltyFunction<Curve> currentCost(\n\t\t\tts_,\n\t\t\tinitialIndexes,\n\t\t\trateHelpersStarts,\n\t\t\trateHelpersEnds);\n\n\t\tProblem toSolve(currentCost, solverConstraint, startArray);\n\n\t\tEndCriteria::Type endType = solver.minimize(toSolve, endCriteria);\n\n\t\t// check the end criteria\n\t\tQL_REQUIRE(endType == EndCriteria::StationaryFunctionAccuracy ||\n\t\t\tendType == EndCriteria::StationaryFunctionValue,\n\t\t\t\"Unable to strip yieldcurve to required accuracy \");\n\n\n\t}\n\n\t//! multiple bootstrapper for simultanaous bootstrap of multiple curves.\n\t/*!\n\t\\TODO: template <class Curve> should be unique for all curves.\n\t*/\n\ttemplate <class Curve>\n\tclass MultiBootstrap {\n\t\ttypedef typename Curve::traits_type Traits;\n\t\ttypedef typename Curve::interpolator_type Interpolator;\n\tpublic:\n\n\t\tMultiBootstrap(boost::shared_ptr<MultiCurveOptimizer<Curve> > optimizer =\n\t\t\tboost::shared_ptr<MultiCurveOptimizer<Curve> >(new MultiCurveOptimizer<Curve>()));\n\t\tvoid setup(Curve* ts);\n\t\tvoid calculate() const;\n\n\tprivate:\n\t\tfriend MultiCurveOptimizer<Curve>;\n\t\tvoid initialize() const;\n\t\tmutable bool validCurve_;\n\t\tCurve* ts_;\n\t\tboost::shared_ptr<MultiCurveOptimizer<Curve> > multiCurveOptimizer_;\n\t};\n\n\n\t// template definitions\n\n\ttemplate <class Curve>\n\tMultiBootstrap<Curve>::MultiBootstrap(boost::shared_ptr<MultiCurveOptimizer<Curve> > optimizer)\n\t\t: ts_(0), validCurve_(false), multiCurveOptimizer_(optimizer)\n\t{}\n\n\ttemplate <class Curve>\n\tvoid MultiBootstrap<Curve>::setup(Curve* ts) {\n\n\t\tts_ = ts;\n\n\t\tSize n = ts_->instruments_.size();\n\t\tQL_REQUIRE(n >= Interpolator::requiredPoints,\n\t\t\t\"not enough instruments: \" << n << \" provided, \" <<\n\t\t\tInterpolator::requiredPoints << \" required\");\n\n\t\tfor (Size i = 0; i<n; ++i){\n\t\t\tts_->registerWith(ts_->instruments_[i]);\n\t\t}\n\n\t\tmultiCurveOptimizer_->addTermStructure(ts_);\n\n\t}\n\n\ttemplate <class Curve>\n\tvoid MultiBootstrap<Curve>::initialize() const {\n\n\t\tSize nInsts = ts_->instruments_.size();\n\n\t\t// ensure rate helpers are sorted\n\t\tstd::sort(ts_->instruments_.begin(), ts_->instruments_.end(),\n\t\t\tdetail::BootstrapHelperSorter());\n\n\t\t// check that there is no instruments with the same maturity\n\t\tfor (Size i = 1; i<nInsts; ++i) {\n\t\t\tDate m1 = ts_->instruments_[i - 1]->latestDate(),\n\t\t\t\tm2 = ts_->instruments_[i]->latestDate();\n\t\t\tQL_REQUIRE(m1 != m2,\n\t\t\t\t\"two instruments have the same maturity (\" << m1 << \")\");\n\t\t}\n\n\t\t// check that there is no instruments with invalid quote\n\t\tfor (Size i = 0; i<nInsts; ++i)\n\t\t\tQL_REQUIRE(ts_->instruments_[i]->quote()->isValid(),\n\t\t\tio::ordinal(i + 1) << \" instrument (maturity: \" <<\n\t\t\tts_->instruments_[i]->latestDate() <<\n\t\t\t\") has an invalid quote\");\n\n\t\t// setup instruments\n\t\tfor (Size i = 0; i<nInsts; ++i) {\n\t\t\t// don't try this at home!\n\t\t\t// This call creates instruments, and removes \"const\".\n\t\t\t// There is a significant interaction with observability.\n\t\t\tts_->instruments_[i]->setTermStructure(const_cast<Curve*>(ts_));\n\t\t}\n\t\t// set initial guess only if the current curve cannot be used as guess\n\t\tif (validCurve_)\n\t\t\tQL_ENSURE(ts_->data_.size() == nInsts + 1,\n\t\t\t\"dimension mismatch: expected \" << nInsts + 1 <<\n\t\t\t\", actual \" << ts_->data_.size());\n\t\telse {\n\t\t\tts_->data_ = std::vector<Rate>(nInsts + 1);\n\t\t\tts_->data_[0] = Traits::initialValue(ts_);\n\t\t}\n\n\t\t// calculate dates and times\n\t\tts_->dates_ = std::vector<Date>(nInsts + 1);\n\t\tts_->times_ = std::vector<Time>(nInsts + 1);\n\t\tts_->dates_[0] = Traits::initialDate(ts_);\n\t\tts_->times_[0] = ts_->timeFromReference(ts_->dates_[0]);\n\t\tfor (Size i = 0; i<nInsts; ++i) {\n\t\t\tts_->dates_[i + 1] = ts_->instruments_[i]->latestDate();\n\t\t\tts_->times_[i + 1] = ts_->timeFromReference(ts_->dates_[i + 1]);\n\t\t\tif (!validCurve_)\n\t\t\t\tts_->data_[i + 1] = ts_->data_[i];\n\t\t}\n\n\t\tts_->interpolation_ =\n\t\t\tts_->interpolator_.interpolate(ts_->times_.begin(),\n\t\t\tts_->times_.end(),\n\t\t\tts_->data_.begin());\n\n\n\t}\n\n\ttemplate <class Curve>\n\tvoid MultiBootstrap<Curve>::calculate() const {\n\t\tvalidCurve_ = false;\n\t\tmultiCurveOptimizer_->optimize();\n\t\tvalidCurve_ = true;\n\n\t}\n\n\ttemplate <class Curve>\n\tReal MultiCurvePenaltyFunction<Curve>::value(const Array& x) const {\n\t\tArray::const_iterator guessIt = x.begin();\n\t\tfor (Size n = 0; n < curves_.size(); n++) {\n\t\t\tSize nInsts = curves_[n]->instruments_.size();\n\t\t\tSize i = initialIndexes_[n];\n\t\t\tfor (Size j = 0; j < nInsts; j++) {\n\t\t\t\tTraits::updateGuess(curves_[n]->data_, *guessIt, j + i);\n\t\t\t\t++guessIt;\n\t\t\t}\n\t\t\tcurves_[n]->interpolation_.update();\n\t\t}\n\n\t\tReal penalty = 0.0;\n\t\tfor (Size n = 0; n < curves_.size(); n++) {\n\t\t\thelper_iterator instIt = rateHelpersStarts_[n];\n\t\t\twhile (instIt != rateHelpersEnds_[n]) {\n\t\t\t\tReal quoteError = (*instIt)->quoteError();\n\t\t\t\tpenalty += std::fabs(quoteError);\n\t\t\t\t++instIt;\n\t\t\t}\n\t\t}\n\t\treturn penalty;\n\t}\n\n\ttemplate <class Curve>\n\tDisposable<Array> MultiCurvePenaltyFunction<Curve>::values(const Array& x) const {\n\t\tArray::const_iterator guessIt = x.begin();\n\t\tfor (Size n = 0; n < curves_.size(); n++) {\n\t\t\tSize nInsts = curves_[n]->instruments_.size();\n\t\t\tSize i = initialIndexes_[n];\n\t\t\tfor (Size j = 0; j < nInsts; j++) {\n\t\t\t\tTraits::updateGuess(curves_[n]->data_, *guessIt, j + i);\n\t\t\t\t++guessIt;\n\t\t\t}\n\t\t\tcurves_[n]->interpolation_.update();\n\t\t}\n\n\t\tArray penalties(x.size());\n\t\tArray::iterator penIt = penalties.begin();\n\t\tfor (Size n = 0; n < curves_.size(); n++) {\n\t\t\thelper_iterator instIt = rateHelpersStarts_[n];\n\t\t\twhile (instIt != rateHelpersEnds_[n]) {\n\t\t\t\tReal quoteError = (*instIt)->quoteError();\n\t\t\t\t*penIt = std::fabs(quoteError);\n\t\t\t\t++instIt;\n\t\t\t\t++penIt;\n\t\t\t}\n\t\t}\n\t\treturn penalties;\n\t}    \n}\n\n#endif\n", "meta": {"hexsha": "a71af364ba304849374bb8418ce3f52c17000a9c", "size": 9086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CppCoreLibrary/QLExtension/termstructures/multibootstrap.hpp", "max_stars_repo_name": "qg0/EliteQuant_Excel", "max_stars_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-21T23:06:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T17:29:10.000Z", "max_issues_repo_path": "CppCoreLibrary/QLExtension/termstructures/multibootstrap.hpp", "max_issues_repo_name": "qg0/EliteQuant_Excel", "max_issues_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CppCoreLibrary/QLExtension/termstructures/multibootstrap.hpp", "max_forks_repo_name": "qg0/EliteQuant_Excel", "max_forks_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T13:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T11:13:12.000Z", "avg_line_length": 29.5960912052, "max_line_length": 96, "alphanum_fraction": 0.6931543033, "num_tokens": 2583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.44701485974316446}}
{"text": "//\r\n//=======================================================================\r\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\r\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//=======================================================================\r\n//\r\n#ifndef BOOST_DISJOINT_SETS_HPP\r\n#define BOOST_DISJOINT_SETS_HPP\r\n\r\n#include <vector>\r\n#include <boost/graph/properties.hpp>\r\n#include <boost/pending/detail/disjoint_sets.hpp>\r\n\r\nnamespace boost {\r\n\r\n  struct find_with_path_halving {\r\n    template <class ParentPA, class Vertex>\r\n    Vertex operator()(ParentPA p, Vertex v) { \r\n      return detail::find_representative_with_path_halving(p, v);\r\n    }\r\n  };\r\n\r\n  struct find_with_full_path_compression {\r\n    template <class ParentPA, class Vertex>\r\n    Vertex operator()(ParentPA p, Vertex v){\r\n      return detail::find_representative_with_full_compression(p, v);\r\n    }\r\n  };\r\n\r\n  // This is a generalized functor to provide disjoint sets operations\r\n  // with \"union by rank\" and \"path compression\".  A disjoint-set data\r\n  // structure maintains a collection S={S1, S2, ..., Sk} of disjoint\r\n  // sets. Each set is identified by a representative, which is some\r\n  // member of of the set. Sets are represented by rooted trees. Two\r\n  // heuristics: \"union by rank\" and \"path compression\" are used to\r\n  // speed up the operations.\r\n\r\n  // Disjoint Set requires two vertex properties for internal use.  A\r\n  // RankPA and a ParentPA. The RankPA must map Vertex to some Integral type\r\n  // (preferably the size_type associated with Vertex). The ParentPA\r\n  // must map Vertex to Vertex.\r\n  template <class RankPA, class ParentPA,\r\n    class FindCompress = find_with_full_path_compression\r\n    >\r\n  class disjoint_sets {\r\n    typedef disjoint_sets self;\r\n    \r\n    inline disjoint_sets() {}\r\n  public:\r\n    inline disjoint_sets(RankPA r, ParentPA p) \r\n      : rank(r), parent(p) {}\r\n\r\n    inline disjoint_sets(const self& c) \r\n      : rank(c.rank), parent(c.parent) {}\r\n    \r\n    // Make Set -- Create a singleton set containing vertex x\r\n    template <class Element>\r\n    inline void make_set(Element x)\r\n    {\r\n      put(parent, x, x);\r\n      typedef typename property_traits<RankPA>::value_type R;\r\n      put(rank, x, R());\r\n    }\r\n    \r\n    // Link - union the two sets represented by vertex x and y\r\n    template <class Element>\r\n    inline void link(Element x, Element y)\r\n    {\r\n      detail::link_sets(parent, rank, x, y, rep);\r\n    }\r\n    \r\n    // Union-Set - union the two sets containing vertex x and y \r\n    template <class Element>\r\n    inline void union_set(Element x, Element y)\r\n    {\r\n      link(find_set(x), find_set(y));\r\n    }\r\n    \r\n    // Find-Set - returns the Element representative of the set\r\n    // containing Element x and applies path compression.\r\n    template <class Element>\r\n    inline Element find_set(Element x)\r\n    {\r\n      return rep(parent, x);\r\n    }\r\n\r\n    template <class ElementIterator>\r\n    inline std::size_t count_sets(ElementIterator first, ElementIterator last)\r\n    {\r\n      std::size_t count = 0;  \r\n      for ( ; first != last; ++first)\r\n      if (get(parent, *first) == *first)\r\n        ++count;\r\n      return count;\r\n    }\r\n\r\n    template <class ElementIterator>\r\n    inline void normalize_sets(ElementIterator first, ElementIterator last)\r\n    {\r\n      for (; first != last; ++first) \r\n        detail::normalize_node(parent, *first);\r\n    }    \r\n    \r\n    template <class ElementIterator>\r\n    inline void compress_sets(ElementIterator first, ElementIterator last)\r\n    {\r\n      for (; first != last; ++first) \r\n        detail::find_representative_with_full_compression(parent, *first);\r\n    }    \r\n  protected:\r\n    RankPA rank;\r\n    ParentPA parent;\r\n    FindCompress rep;\r\n  };\r\n\r\n\r\n  \r\n\r\n  template <class ID = identity_property_map,\r\n            class InverseID = identity_property_map,\r\n            class FindCompress = find_with_full_path_compression\r\n            >\r\n  class disjoint_sets_with_storage\r\n  {\r\n    typedef typename property_traits<ID>::value_type Index;\r\n    typedef std::vector<Index> ParentContainer;\r\n    typedef std::vector<unsigned char> RankContainer;\r\n  public:\r\n    typedef typename ParentContainer::size_type size_type;\r\n\r\n    disjoint_sets_with_storage(size_type n = 0,\r\n                               ID id_ = ID(),\r\n                               InverseID inv = InverseID())\r\n      : id(id_), id_to_vertex(inv), rank(n, 0), parent(n)\r\n    {\r\n      for (Index i = 0; i < n; ++i)\r\n        parent[i] = i;\r\n    }\r\n    // note this is not normally needed\r\n    template <class Element>\r\n    inline void \r\n    make_set(Element x) {\r\n      parent[x] = x;\r\n      rank[x]   = 0;\r\n    }\r\n    template <class Element>\r\n    inline void \r\n    link(Element x, Element y)\r\n    {\r\n      extend_sets(x,y);\r\n      detail::link_sets(&parent[0], &rank[0], \r\n                        get(id,x), get(id,y), rep);\r\n    }\r\n    template <class Element>\r\n    inline void \r\n    union_set(Element x, Element y) {\r\n      Element rx = find_set(x);\r\n      Element ry = find_set(y);\r\n      link(rx, ry);\r\n    }\r\n    template <class Element>\r\n    inline Element find_set(Element x) {\r\n      return id_to_vertex[rep(&parent[0], get(id,x))];\r\n    }\r\n\r\n    template <class ElementIterator>\r\n    inline std::size_t count_sets(ElementIterator first, ElementIterator last)\r\n    {\r\n      std::size_t count = 0;  \r\n      for ( ; first != last; ++first)\r\n      if (parent[*first] == *first)\r\n        ++count;\r\n      return count;\r\n    }\r\n\r\n    template <class ElementIterator>\r\n    inline void normalize_sets(ElementIterator first, ElementIterator last)\r\n    {\r\n      for (; first != last; ++first) \r\n        detail::normalize_node(&parent[0], *first);\r\n    }    \r\n    \r\n    template <class ElementIterator>\r\n    inline void compress_sets(ElementIterator first, ElementIterator last)\r\n    {\r\n      for (; first != last; ++first) \r\n        detail::find_representative_with_full_compression(&parent[0],\r\n                                                          *first);\r\n    }    \r\n\r\n    const ParentContainer& parents() { return parent; }\r\n\r\n  protected:\r\n\r\n    template <class Element>\r\n    inline void \r\n    extend_sets(Element x, Element y)\r\n    {\r\n      Index needed = get(id,x) > get(id,y) ? get(id,x) + 1 : get(id,y) + 1;\r\n      if (needed > parent.size()) {\r\n        rank.insert(rank.end(), needed - rank.size(), 0);\r\n        for (Index k = parent.size(); k < needed; ++k)\r\n        parent.push_back(k);\r\n      } \r\n    }\r\n\r\n    ID id;\r\n    InverseID id_to_vertex;\r\n    RankContainer rank;\r\n    ParentContainer parent;\r\n    FindCompress rep;\r\n  };\r\n\r\n} // namespace boost\r\n\r\n#endif // BOOST_DISJOINT_SETS_HPP\r\n", "meta": {"hexsha": "150dbd48d126078df55600a6ea49d12bf407251b", "size": 6855, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/pending/disjoint_sets.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/pending/disjoint_sets.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/pending/disjoint_sets.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 31.0180995475, "max_line_length": 79, "alphanum_fraction": 0.6002917578, "num_tokens": 1581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.44701485974316435}}
{"text": "/*\n * Copyright (c) 2017, The Regents of the University of California (Regents).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *    1. Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *\n *    2. Redistributions in binary form must reproduce the above\n *       copyright notice, this list of conditions and the following\n *       disclaimer in the documentation and/or other materials provided\n *       with the distribution.\n *\n *    3. Neither the name of the copyright holder nor the names of its\n *       contributors may be used to endorse or promote products derived\n *       from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Please contact the author(s) of this library if you have any questions.\n * Authors: David Fridovich-Keil   ( dfk@eecs.berkeley.edu )\n */\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Defines the GaussianProcess class.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef GP_PROCESS_GAUSSIAN_PROCESS_H\n#define GP_PROCESS_GAUSSIAN_PROCESS_H\n\n#include \"../kernels/kernel.hpp\"\n#include \"../utils/types.hpp\"\n\n#include <Eigen/Cholesky>\n#include <glog/logging.h>\n#include <vector>\n\nnamespace gp {\n\n  class GaussianProcess {\n  public:\n    ~GaussianProcess() {}\n\n    // Constructors. By default picks 10% of the maximum number of points\n    // randomly within the unit box [-1, 1]^d.\n    explicit GaussianProcess(const Kernel::Ptr& kernel, double noise,\n                             size_t dimension, size_t max_points = 100);\n    explicit GaussianProcess(const Kernel::Ptr& kernel, double noise,\n                             const PointSet& points,\n                             size_t max_points = 100);\n    explicit GaussianProcess(const Kernel::Ptr& kernel, double noise,\n                             const PointSet& points,\n                             const VectorXd& targets,\n                             size_t max_points = 100);\n\n    // Evaluate mean and variance at a point.\n    void Evaluate(const VectorXd& x, double& mean, double& variance) const;\n    void EvaluateTrainingPoint(size_t ii, double& mean, double& variance) const;\n\n    // Add new point(s). Returns whether or not points were added (points will\n    // only be added until 'max_points' is reached).\n    bool Add(const VectorXd& x, double target);\n    bool Add(const std::vector<VectorXd>& points, const VectorXd& targets);\n\n    // Update the training targets in the direction of the gradient of the\n    // mean squared error at the given points. Returns the mean squared error.\n    // If 'finalize' is set, computes regressed targets - only set to false if\n    // you are doing repeated updates, and be sure to set true on final update.\n    double UpdateTargets(const std::vector<VectorXd>& points,\n                         const std::vector<double>& targets,\n                         double step_size, bool finalize = true);\n\n    // Learn kernel hyperparameters by maximizing log-likelihood of the\n    // training data.\n    bool LearnHyperparams();\n\n    // Immutable accessors.\n    const MatrixXd& ImmutableCovariance() const { return covariance_; }\n    const VectorXd& ImmutableRegressedTargets() const { return regressed_; }\n    const VectorXd& ImmutableTargets() const { return targets_; }\n    const ConstPointSet ImmutablePoints() const { return points_; }\n    const Eigen::LLT<MatrixXd>& ImmutableCholesky() const { return llt_; }\n    size_t Dimension() const { return dimension_; }\n\n  private:\n    // Compute the covariance and cross covariance against the training points.\n    void Covariance();\n    void CrossCovariance(const VectorXd& x, VectorXd& cross) const;\n\n    // Kernel.\n    const Kernel::Ptr kernel_;\n\n    // Noise variance.\n    const double noise_;\n\n    // Training points, targets, and regressed targets (inv(cov) * targets).\n    const PointSet points_;\n    size_t dimension_;\n    VectorXd targets_;\n    VectorXd regressed_;\n\n    // Maximum number of points.\n    const size_t max_points_;\n\n    // Covariance matrix, with Cholesky decomposition.\n    MatrixXd covariance_;\n    Eigen::LLT<MatrixXd> llt_;\n  }; //\\class GaussianProcess\n\n}  //\\namespace gp\n\n#endif\n", "meta": {"hexsha": "3bf54214f014afcf0fdebafaeb7bbfb74f4ad0c9", "size": 5188, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/process/gaussian_process.hpp", "max_stars_repo_name": "dfridovi/gp", "max_stars_repo_head_hexsha": "d96f750645ec5b46c6712a3792f9ef79289f5768", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-10T20:29:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T13:06:31.000Z", "max_issues_repo_path": "include/process/gaussian_process.hpp", "max_issues_repo_name": "dfridovi/gp", "max_issues_repo_head_hexsha": "d96f750645ec5b46c6712a3792f9ef79289f5768", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-11T20:59:59.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-12T19:00:04.000Z", "max_forks_repo_path": "include/process/gaussian_process.hpp", "max_forks_repo_name": "dfridovi/gp", "max_forks_repo_head_hexsha": "d96f750645ec5b46c6712a3792f9ef79289f5768", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-10-31T16:24:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-21T14:48:32.000Z", "avg_line_length": 40.53125, "max_line_length": 80, "alphanum_fraction": 0.6752120278, "num_tokens": 1078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.6548947155710233, "lm_q1q2_score": 0.4470139231966709}}
{"text": "\r\n#include <bg/bondgeek.hpp>\r\n\r\n#include <iostream>\r\n#include <algorithm>\r\n\r\n#include <boost/timer.hpp>\r\n\r\nusing namespace std;\r\nusing namespace QuantLib;\r\nusing namespace bondgeek;\r\n\r\n#if defined(QL_ENABLE_SESSIONS)\r\nnamespace QuantLib {\r\n    Integer sessionId() { return 0; }\r\n}\r\n#endif\r\n\r\n\r\n/* TODO: Instrument interface\r\n - swaps: euro swaps, usd\r\n - bonds:  UST, corp, tax-exempt munis\r\n */\r\nint main () \r\n{\r\n    cout << \"QuantLib Version #: \" << QL_VERSION << endl ;    \r\n        \r\n    Calendar calendar = TARGET();\r\n//    Date todaysDate = TARGET().adjust( Date(20, September, 2004) );\r\n    Date todaysDate = TARGET().adjust( Date(28, May, 2012) );\r\n    \r\n    Settings::instance().evaluationDate() = todaysDate;\r\n    cout << \"settings: \" << &Settings::instance() << endl;\r\n    cout << \"\\n\\nToday: \" << todaysDate << endl;\r\n    \r\n    string futtenors[] = {\"ED1\", \"ED2\", \"ED3\", \"ED4\", \"ED5\", \"ED6\", \"ED7\", \"ED8\"};\r\n    double futspots[] = {96.2875, 96.7875, 96.9875, 96.6875, 96.4875, 96.3875, 96.2875, 96.0875};\r\n    \r\n    string depotenors[] = {\"1W\", \"1M\", \"3M\", \"6M\", \"9M\", \"1y\"};\r\n    double depospots[] = {.0382, 0.0372, 0.0363, 0.0353, 0.0348, 0.0345};\r\n    string swaptenors[] = {\"2y\", \"3y\", \"5y\", \"10Y\", \"15Y\"};\r\n    double swapspots[] = {0.037125, 0.0398, 0.0443, 0.05165, 0.055175};\r\n    \r\n    cout << \"test sc1\" << endl;\r\n    RateHelperCurve acurve = RateHelperCurve(EURiborCurve(\"6M\"));\r\n    acurve.update(depotenors, depospots, 6, \r\n                  swaptenors, swapspots, 5,\r\n                  todaysDate);\r\n    \r\n    cout << \"quote:  \" << acurve.tenorquote(\"10Y\") << endl;\r\n    \r\n    cout << \"test tenors\\n\" << Period(6, Months) << \" | \" << Tenor(\"6M\") << endl;\r\n    cout << \"fixing calendar: \" << acurve.calendar() << endl;\r\n    \r\n    /*********************\r\n     * SWAPS TO BE PRICED *\r\n     **********************/\r\n\r\n    RelinkableHandle<YieldTermStructure>forecastingTermStructure = acurve.forecastingTermStructure();\r\n    \r\n    // constant nominal 1,000,000 Euro\r\n    Real nominal = 1000000.0;\r\n    // fixed leg\r\n    Frequency fixedLegFrequency = Annual;\r\n    BusinessDayConvention fixedLegConvention = Unadjusted;\r\n    BusinessDayConvention floatingLegConvention = ModifiedFollowing;\r\n    DayCounter fixedLegDayCounter = Thirty360(Thirty360::European);\r\n    Rate fixedRate = 0.04;\r\n    DayCounter floatingLegDayCounter = Actual360();\r\n    \r\n    // floating leg\r\n    Frequency floatingLegFrequency = Semiannual;\r\n    \r\n    boost::shared_ptr<IborIndex> euriborIndex(new Euribor6M(forecastingTermStructure));\r\n    \r\n    Spread spread = 0.0;\r\n    \r\n    Integer lenghtInYears = 5;\r\n    VanillaSwap::Type swapType = VanillaSwap::Payer;\r\n    \r\n    \r\n    Date settlementDate = acurve.referenceDate(); \r\n    Date maturity = acurve.referenceDate() + lenghtInYears*Years;\r\n    Schedule fixedSchedule(settlementDate, maturity,\r\n                           Period(fixedLegFrequency),\r\n                           calendar, fixedLegConvention,\r\n                           fixedLegConvention,\r\n                           DateGeneration::Forward, false);\r\n    Schedule floatSchedule(settlementDate, maturity,\r\n                           Period(floatingLegFrequency),\r\n                           calendar, floatingLegConvention,\r\n                           floatingLegConvention,\r\n                           DateGeneration::Forward, false);\r\n    VanillaSwap spot5YearSwap(swapType, nominal,\r\n                              fixedSchedule, fixedRate, fixedLegDayCounter,\r\n                              floatSchedule, euriborIndex, spread,\r\n                              floatingLegDayCounter);\r\n    \r\n    Date fwdStart = calendar.advance(settlementDate, 1, Years);\r\n    Date fwdMaturity = fwdStart + lenghtInYears*Years;\r\n    Schedule fwdFixedSchedule(fwdStart, fwdMaturity,\r\n                              Period(fixedLegFrequency),\r\n                              calendar, fixedLegConvention,\r\n                              fixedLegConvention,\r\n                              DateGeneration::Forward, false);\r\n    Schedule fwdFloatSchedule(fwdStart, fwdMaturity,\r\n                              Period(floatingLegFrequency),\r\n                              calendar, floatingLegConvention,\r\n                              floatingLegConvention,\r\n                              DateGeneration::Forward, false);\r\n    VanillaSwap oneYearForward5YearSwap(swapType, nominal,\r\n                                        fwdFixedSchedule, fixedRate, fixedLegDayCounter,\r\n                                        fwdFloatSchedule, euriborIndex, spread,\r\n                                        floatingLegDayCounter);\r\n    \r\n    cout << \"swap.\" << endl;\r\n    \r\n    boost::shared_ptr<PricingEngine> swapEngine = createPriceEngine<DiscountingSwapEngine>(\r\n                                                                                           acurve.discountingTermStructure()\r\n                                                                                           );\r\n    \r\n    spot5YearSwap.setPricingEngine(swapEngine);\r\n    oneYearForward5YearSwap.setPricingEngine(swapEngine);\r\n    \r\n    Real NPV;\r\n    Rate fairRate;\r\n    Spread fairSpread;\r\n    \r\n    cout << \"spot \" << endl;\r\n    NPV = spot5YearSwap.NPV();\r\n    fairSpread = spot5YearSwap.fairSpread();\r\n    fairRate = spot5YearSwap.fairRate();\r\n    \r\n    cout << std::setprecision(2) << std::setw(12) << std::fixed <<\r\n    \"NPV : \" << NPV << \r\n    \"   | Fair Spread: \" << io::rate(fairSpread) << \r\n    \"   | Fair Rate: \" << io::rate(fairRate) << endl;\r\n    \r\n    cout << std::setprecision(2) << std::setw(12) << std::fixed <<\r\n    \"fx NPV : \" << spot5YearSwap.fixedLegNPV() << \r\n    \"   | fx NPV : \" << spot5YearSwap.floatingLegNPV() << endl; \r\n    \r\n    cout << \"forward \" << endl;\r\n    NPV = oneYearForward5YearSwap.NPV();\r\n    fairSpread = oneYearForward5YearSwap.fairSpread();\r\n    fairRate = oneYearForward5YearSwap.fairRate();\r\n    \r\n    cout << std::setprecision(2) << std::setw(12) << std::fixed <<\r\n    \"NPV : \" << NPV << \r\n    \"   | Fair Spread: \" << io::rate(fairSpread) << \r\n    \"   | Fair Rate: \" << io::rate(fairRate) << endl;\r\n    \r\n    cout << std::setprecision(2) << std::setw(12) << std::fixed <<\r\n    \"fx NPV : \" << oneYearForward5YearSwap.fixedLegNPV() << \r\n    \"   | fx NPV : \" << oneYearForward5YearSwap.floatingLegNPV() << endl; \r\n    \r\n    cout << \"test libor clone\" << endl;\r\n    RelinkableHandle<YieldTermStructure> indexTermStructure;\r\n    boost::shared_ptr<IborIndex> libor3m(new USDLibor(Period(3, Months), \r\n                                                      indexTermStructure));\r\n    \r\n    Handle<YieldTermStructure>testTS = acurve.forecastingTermStructure();\r\n    boost::shared_ptr<IborIndex> newlib = libor3m->clone(testTS);\r\n    \r\n    // If one wanted a USD Libor index....\r\n    USDLiborBase testIndex;\r\n    \r\n    cout << \"\\n\\nSwap to compare to first swap \" << endl;\r\n    cout << \"Qswap\" << endl;\r\n    cout << \"mty: \" << maturity << \" | cpn: \" << io::rate(fixedRate) << endl;\r\n    EuriborBase euribor(6, Months);\r\n    \r\n    FixedFloatSwap qswp(settlementDate,\r\n                        maturity,\r\n                        fixedRate,\r\n                        euribor(acurve.yieldTermStructurePtr()),\r\n                        FixedPayer,\r\n                        0.0,\r\n                        1000000.0,\r\n                        Annual,\r\n                        Thirty360(Thirty360::European),\r\n                        Unadjusted,\r\n                        Semiannual,\r\n                        Actual360(),\r\n                        ModifiedFollowing,\r\n                        TARGET()\r\n                        );\r\n    \r\n    qswp.setPricingEngine(swapEngine);\r\n    \r\n    cout << std::setprecision(2) << std::setw(12) << std::fixed <<\r\n    \"NPV : \" << qswp.NPV() << \r\n    \"   | Fair Spread: \" << io::rate(qswp.fairSpread()) << \r\n    \"   | Fair Rate: \" << io::rate(qswp.fairRate()) << endl; \r\n    \r\n    cout << std::setprecision(2) << std::setw(12) << std::fixed <<\r\n    \"fx NPV : \" << qswp.fixedLegNPV() << \r\n    \"   | fl NPV : \" << qswp.floatingLegNPV() << endl; \r\n    \r\n    cout << \"Inspect Legs\" << endl << endl;\r\n    Leg fixedLeg = qswp.fixedLeg();\r\n    Leg floatingLeg = qswp.floatingLeg();\r\n    \r\n    cout << \"Fixed: \" << endl;\r\n    Leg::iterator fxIt;\r\n    int cfCount =0;\r\n    Date cfDate;\r\n    double cfAmt;\r\n    double cfDF;\r\n    double cfNPV = 0.0;\r\n    for (fxIt=fixedLeg.begin(); fxIt < fixedLeg.end(); fxIt++) {\r\n        cfDate = (*fxIt)->date();\r\n        cfAmt = (*fxIt)->amount();\r\n        cfDF = acurve.discount((*fxIt)->date());\r\n        cfNPV += cfAmt*cfDF;\r\n        \r\n        cout << cfCount++ << \") \" \r\n        << std::setw(24) << cfDate << \" | \"  << std::setw(12) \r\n        << cfAmt << \" | \" \r\n        << std::setprecision(6) << cfDF << \" | \" \r\n        << std::setprecision(2) << cfNPV\r\n        << endl;\r\n    }\r\n\r\n    cout << \"Floating: \" << endl;\r\n    Leg::iterator flIt;\r\n    cfCount =0;\r\n    cfNPV = 0.0;\r\n    for (flIt=floatingLeg.begin(); flIt < floatingLeg.end(); flIt++) {\r\n        cfDate = (*flIt)->date();\r\n        cfAmt = (*flIt)->amount();\r\n        cfDF = acurve.discount((*flIt)->date());\r\n        cfNPV += cfAmt*cfDF;\r\n        \r\n        cout << cfCount++ << \") \" \r\n        << std::setw(24) << cfDate << \" | \"  << std::setw(12) \r\n        << cfAmt << \" | \" \r\n        << std::setprecision(6) << cfDF << \" | \" \r\n        << std::setprecision(2) << cfNPV\r\n        << endl;\r\n    }\r\n    \r\n    cout << \"swp2 \" << endl;\r\n    \r\n    SwapType<Euribor> euriborswaps(Annual,\r\n                                   Thirty360(Thirty360::European),\r\n                                   Unadjusted,\r\n                                   Semiannual,\r\n                                   Actual360(),\r\n                                   ModifiedFollowing,\r\n                                   TARGET()\r\n                                   );\r\n    \r\n    cout << \"create\" << endl;\r\n    boost::shared_ptr<FixedFloatSwap> qswp2 = euriborswaps.create(settlementDate,\r\n                                                                  maturity,\r\n                                                                  fixedRate);\r\n    \r\n    cout << \"pricing\" << endl;\r\n    qswp2->setEngine(acurve);\r\n    \r\n    cout << \"link\" << endl;\r\n    euriborswaps.linkIndex(acurve);\r\n    \r\n    cout << std::setprecision(2) << std::setw(12) << std::fixed <<\r\n    \"NPV : \" << qswp2->NPV() << \r\n    \"   | Fair Spread: \" << io::rate(qswp2->fairSpread()) << \r\n    \"   | Fair Rate: \" << io::rate(qswp2->fairRate()) << endl; \r\n    \r\n    cout << std::setprecision(2) << std::setw(12) << std::fixed <<\r\n    \"fx NPV : \" << qswp2->fixedLegNPV() << \r\n    \"   | fx NPV : \" << qswp2->floatingLegNPV() << endl; \r\n    \r\n    cout << \"\\nSwap 3: forward\" << endl;\r\n    boost::shared_ptr<FixedFloatSwap> qswp3 = euriborswaps.create(fwdStart,\r\n                                                                  fwdMaturity,\r\n                                                                  fixedRate);\r\n    cout << \"fixed rate: \" << qswp3->fixedRate() << endl;\r\n    qswp3->setPricingEngine(swapEngine);\r\n    euriborswaps.linkIndexTo(acurve.yieldTermStructurePtr());\r\n    \r\n    cout << std::setprecision(2) << std::setw(12) << std::fixed <<\r\n    \"NPV : \" << qswp3->NPV() << \r\n    \"   | Fair Spread: \" << io::rate(qswp3->fairSpread()) << \r\n    \"   | Fair Rate: \" << io::rate(qswp3->fairRate()) << endl; \r\n    \r\n    cout << std::setprecision(2) << std::setw(12) << std::fixed <<\r\n    \"fx NPV : \" << qswp3->fixedLegNPV() << \r\n    \"   | fx NPV : \" << qswp3->floatingLegNPV() << endl; \r\n    \r\n    cout << \"\\n\\nBonds\" << endl;\r\n    \r\n    boost::shared_ptr<BulletBond> bond1(new BulletBond(.045, \r\n                                                       Date(15, May, 2017), \r\n                                                       Date(15, May, 2003))\r\n                                        );\r\n    \r\n    cout << \"mty: \" << bond1->maturityDate() << endl;\r\n    cout << \"stl: \" << bond1->settlementDate() << endl;\r\n    \r\n    cout << \"test\" << endl;\r\n    bond1->setEngine(acurve);\r\n    \r\n    cout << \"bondprice: \" ;\r\n    double prc = bond1->cleanPrice();\r\n    cout << std::setprecision(3) << prc << endl;\r\n    \r\n    cout << \"Yield: \" ;\r\n    double yld = bond1->yield(prc, bond1->dayCounter(), Compounded, bond1->frequency());\r\n    cout << io::rate(yld) << endl;\r\n    \r\n    cout << \"\\n\\nIMM Stuff\\n\";\r\n    cout << \"settle: \" << settlementDate << endl;\r\n    Date  imm = IMM::nextDate(settlementDate);\r\n    string immcode = IMM::code(imm);\r\n    \r\n    Date imm2 = imm_nextDate(imm);\r\n    string immcode2 = imm_nextCode(immcode);\r\n    \r\n    cout << \"date: \" << imm << \" | code: \" << immcode << endl; \r\n    cout << \"date: \" << imm2 << \" | code: \" << immcode2 << endl; \r\n    \r\n    cout << \"ED3: \" << FuturesTenor(\"ED3\") << endl;\r\n    \r\n    CurveMap depocurve;\r\n    CurveMap futscurve;\r\n    CurveMap swapcurve;\r\n    RateHelperCurve rhcurve( EURiborCurve(\"6M\", Annual) );\r\n    \r\n    if (futscurve.empty()) {\r\n        cout << \"futscurve empty \" << endl;\r\n    } else {\r\n        cout << \"futscurve not empty: \" << endl;\r\n    }\r\n\r\n    \r\n    for (int i=0; i<2; i++) \r\n        depocurve[depotenors[i]] = depospots[i];\r\n    \r\n    for (int i=0; i<6; i++) \r\n        futscurve[futtenors[i]] = futspots[i];\r\n    \r\n    for (int i=0; i<5; i++) \r\n        swapcurve[swaptenors[i]] = swapspots[i];\r\n    \r\n    rhcurve.update(depocurve, futscurve, swapcurve);\r\n    \r\n    cout << \"\\n10Y: \" << io::rate(rhcurve.tenorquote(\"10Y\")) << endl;\r\n    cout << \"discount: \" << rhcurve.discount(10.0) << endl;\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "3501464d618f152cfdf2687a4dcab25d601fa384", "size": 13528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/bg_example.cpp", "max_stars_repo_name": "bondgeek/pybg", "max_stars_repo_head_hexsha": "046a25074b78409c6d29302177aeac581ade90d1", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-03-14T05:39:15.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-14T05:39:15.000Z", "max_issues_repo_path": "examples/bg_example.cpp", "max_issues_repo_name": "bondgeek/pybg", "max_issues_repo_head_hexsha": "046a25074b78409c6d29302177aeac581ade90d1", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/bg_example.cpp", "max_forks_repo_name": "bondgeek/pybg", "max_forks_repo_head_hexsha": "046a25074b78409c6d29302177aeac581ade90d1", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4318181818, "max_line_length": 125, "alphanum_fraction": 0.4995564755, "num_tokens": 3551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.44699916308430593}}
{"text": "#include <iostream>\n#include <NTL/ZZ.h>\n#include <gmp.h>\n#include <gmpxx.h>\n#include \"../bernmm-1.1/bern_modp_util.h\"\n#include \"../bernmm-1.1/bern_modp.h\"\n#include \"../bernmm-1.1/bern_rat.h\"\n#include \"berrb.h\"\n\nBerrb::Berrb()\n{\n\n}\n\n\nBerrb::~Berrb()\n{\n\n}\n\nstd::string Berrb::ber(long k, long thread)\n{\n\tmpq_t r;\n\tmpq_init(r);\n\tbernmm::bern_rat(r, k, thread);\n\n    mpq_class q(r);\n\n\tmpq_clear(r);\n\n    return q.get_str();\n}\n\nlong Berrb::ber_modp(long p, long k)\n{\n    long r = bernmm::bern_modp(p, k);\n\n    return r;\n}\n\n\n\n\n", "meta": {"hexsha": "a9c9b332ed13fdff6f6e968188980c7cd6f80977", "size": 521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ruby_wrapper/berrb.cpp", "max_stars_repo_name": "junpeitsuji/libbernmm", "max_stars_repo_head_hexsha": "f2d80b7f1d0168d26e270d4779ad748b5893c2ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ruby_wrapper/berrb.cpp", "max_issues_repo_name": "junpeitsuji/libbernmm", "max_issues_repo_head_hexsha": "f2d80b7f1d0168d26e270d4779ad748b5893c2ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ruby_wrapper/berrb.cpp", "max_forks_repo_name": "junpeitsuji/libbernmm", "max_forks_repo_head_hexsha": "f2d80b7f1d0168d26e270d4779ad748b5893c2ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.8409090909, "max_line_length": 43, "alphanum_fraction": 0.6218809981, "num_tokens": 184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834649, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4469991630843058}}
{"text": "\n#include \"sparse.h\"\n\n#define USE_EIGEN\n//#define USE_SUITESPARSE\n\n#ifdef USE_EIGEN\n#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET\n//#define EIGEN_CHOLMOD_SUPPORT\n//#define EIGEN_UMFPACK_SUPPORT\n#include <Eigen/Cholesky>\n#include <Eigen/LU>\n#include <Eigen/Sparse>\n#include <Eigen/SparseExtra>\nusing namespace Eigen;\n#endif  // USE_EIGEN\n\n#ifdef USE_SUITESPARSE\n#include <suitesparse/SuiteSparseQR.hpp>\n#endif // USE_SUITESPARSE\n\nnamespace LinAlg\n{\n\n//----( sparse solvers )------------------------------------------------------\n\n#ifdef USE_EIGEN\n\n// conversions between k nearest neighbor & Eigen sparse matrix formats\n\nvoid knn_to_eigen (\n    const size_t dim,\n    const size_t degree,\n    const Vector<uint16_t> & nbhd,\n    const Vector<float> & knn_A,\n    SparseMatrix<double> & eigen_A)\n{\n  DynamicSparseMatrix<double> A(dim,dim);\n\n  for (size_t i = 0; i < dim; ++i) {\n    for (size_t n = 0; n < degree; ++n) {\n      size_t knn_pos = degree * i + n;\n      size_t j = nbhd[knn_pos];\n\n      A.coeffRef(i,j) = knn_A[knn_pos];\n    }\n  }\n\n  eigen_A = A;\n}\n\nvoid symmetric_knn_to_eigen (\n    const size_t dim,\n    const size_t degree,\n    const Vector<uint16_t> & nbhd,\n    const Vector<float> & knn_A,\n    SparseMatrix<double> & eigen_A)\n{\n  DynamicSparseMatrix<double> A(dim,dim);\n\n  for (size_t i = 0; i < dim; ++i) {\n    for (size_t n = 0; n < degree; ++n) {\n      size_t knn_pos = degree * i + n;\n      size_t j = nbhd[knn_pos];\n\n      A.coeffRef(i,j) = A.coeffRef(j,i) = knn_A[knn_pos];\n    }\n  }\n\n  eigen_A = A;\n}\n\nvoid eigen_to_knn (\n    const size_t dim,\n    const size_t degree,\n    const Vector<uint16_t> & nbhd,\n    const SparseMatrix<double> & eigen_A,\n    Vector<float> & knn_A)\n{\n  for (size_t i = 0; i < dim; ++i) {\n    for (size_t n = 0; n < degree; ++n) {\n      size_t knn_pos = degree * i + n;\n      size_t j = nbhd[knn_pos];\n\n      knn_A[knn_pos] = eigen_A.coeff(i,j);\n    }\n  }\n}\n\nvoid sparse_symmetric_solve (\n    const size_t dim,\n    const size_t degree,\n    const Vector<uint16_t> & nbhd,\n    const Vector<float> & knn_Pxx,\n    const Vector<float> & knn_Pxy,\n    Vector<float> & knn_Fxy,\n    double tol,\n    bool debug)\n{\n  ASSERT_SIZE(nbhd, dim * degree);\n  ASSERT_SIZE(knn_Pxx, dim * degree);\n  ASSERT_SIZE(knn_Pxy, dim * degree);\n  ASSERT_SIZE(knn_Fxy, dim * degree);\n\n  LOG(\"solving sparse \" << dim << \" x \" << dim << \" matrix problem\");\n  SparseMatrix<double> Pxx;\n  symmetric_knn_to_eigen(dim, degree, nbhd, knn_Pxx, Pxx);\n\n  //typedef SparseLLT<SparseMatrix<double>, Cholmod> Solver;\n  typedef SparseLLT<SparseMatrix<double> > Solver;\n  Solver solver(Pxx);\n\n  VectorXd Fxy_i(dim);\n  VectorXd Pxy_i(dim);\n  float residual = 0;\n\n  for (size_t i = 0; i < dim; ++i) {\n\n    Pxy_i.setZero();\n    for (size_t n = 0; n < degree; ++n) {\n      size_t knn_pos = degree * i + n;\n      Pxy_i(nbhd[knn_pos]) = knn_Pxy[knn_pos];\n    }\n\n    Fxy_i = Pxy_i;\n    solver.solveInPlace(Fxy_i);\n    // eigen does not set the succeeded flag, otherwise we could check this\n    //ASSERT(solver.succeeded(), \"sparse linear solver failed\");\n\n    for (size_t n = 0; n < degree; ++n) {\n      size_t knn_pos = degree * i + n;\n      knn_Fxy[knn_pos] = Fxy_i(nbhd[knn_pos]);\n    }\n\n    if (debug) {\n      Pxy_i -= Pxx * Fxy_i;\n      residual += Pxy_i.norm();\n    }\n  }\n\n  if (debug) {\n\n    LOG(\" 2-norm of dense residual = \" << residual);\n\n    SparseMatrix<double> Pxy, Fxy;\n    knn_to_eigen(dim, degree, nbhd, knn_Pxy, Pxy);\n    knn_to_eigen(dim, degree, nbhd, knn_Fxy, Fxy);\n\n    Pxy -= Pxx * Fxy;\n    LOG(\" 2-norm of sparse residual = \" << Pxy.norm());\n  }\n}\n\n#endif // USE_EIGEN\n\n//----------------------------------------------------------------------------\n\n#ifdef USE_SUITESPARSE\n\n// This uses the GLP's SuiteSparseQR function\n// http://www.cise.ufl.edu/research/sparse/SPQR/SPQR/Doc/spqr_user_guide.pdf\n\n// conversions between k nearest neighbor & cholmod formats for sparse matrices\n\nstatic cholmod_sparse * knn_to_cholmod (\n    const size_t dim,\n    const size_t degree,\n    const Vector<uint16_t> & nbhd,\n    const Vector<float> & A,\n    cholmod_common * cc)\n{\n  TODO(\"implement conversion\");\n}\n\nstatic cholmod_sparse * symmetric_knn_to_cholmod (\n    const size_t dim,\n    const size_t degree,\n    const Vector<uint16_t> & nbhd,\n    const Vector<float> & A,\n    cholmod_common * cc)\n{\n  TODO(\"implement conversion\");\n}\n\nstatic void cholmod_to_knn (\n    const size_t dim,\n    const size_t degree,\n    const Vector<uint16_t> & nbhd,\n    const cholmod_sparse * a,\n    Vector<float> & A,\n    cholmod_common * cc)\n{\n  TODO(\"implement conversion\");\n}\n\nvoid sparse_symmetric_solve (\n    const size_t dim,\n    const size_t degree,\n    const Vector<uint16_t> & nbhd,\n    const Vector<float> & Pxx,\n    const Vector<float> & Pxy,\n    Vector<float> & Fxy,\n    double tol,\n    bool debug)\n{\n  ASSERT_SIZE(Pxx, dim * degree);\n  ASSERT_SIZE(Pxy, dim * degree);\n  ASSERT_SIZE(Fxy, dim * degree);\n\n  TODO(\"implement sparse symmetric linear solver\");\n\n  LOG(\"solving sparse \" << dim << \" x \" << dim << \" matrix problem\");\n\n  // start CHOLMOD\n  cholmod_common Common, *cc = &Common;\n  cholmod_l_start(cc);\n\n  cholmod_sparse * A = symmetric_knn_to_cholmod(dim, degree, nbhd, Pxx, cc);\n  cholmod_sparse * B = knn_to_cholmod(dim, degree, nbhd, Pxy, cc);\n\n  // matlab equivalent: X = A\\B\n  int ordering = CHOLMOD_NATURAL;\n  cholmod_sparse * X = SuiteSparseQR<double>(ordering, tol, A, B, cc);\n\n  cholmod_to_knn(dim, degree, nbhd, X, Fxy, cc);\n\n  if (debug) {\n    cholmod_sparse * B2 = cholmod_l_ssmult(A, B, 0, true, true, cc);\n\n    Vector<float> Pxy2(Pxy.size);\n    cholmod_to_knn(dim, degree, nbhd, B2, Pxy2, cc);\n\n    cholmod_l_free_sparse(&B2, cc);\n\n    LOG(\" 2-norm of residual = \" << dist_squared(Pxy, Pxy2));\n  }\n\n  // free everything and finish CHOLMOD\n  cholmod_l_free_sparse(&A, cc);\n  cholmod_l_free_sparse(&B, cc);\n  cholmod_l_free_sparse(&X, cc);\n  cholmod_l_finish(cc);\n}\n\n#endif // USE_SUITESPARSE\n\n} // namespace LinAlg\n\n", "meta": {"hexsha": "0aac242f4458fe34476865b3892ebe7e7fb104c1", "size": 5934, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sparse.cpp", "max_stars_repo_name": "fritzo/kazoo", "max_stars_repo_head_hexsha": "7281fe382b98ec81a0e223bfc76c49749543afdb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-04-29T11:38:29.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-31T01:32:13.000Z", "max_issues_repo_path": "src/sparse.cpp", "max_issues_repo_name": "fritzo/kazoo", "max_issues_repo_head_hexsha": "7281fe382b98ec81a0e223bfc76c49749543afdb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sparse.cpp", "max_forks_repo_name": "fritzo/kazoo", "max_forks_repo_head_hexsha": "7281fe382b98ec81a0e223bfc76c49749543afdb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8313253012, "max_line_length": 79, "alphanum_fraction": 0.6363329963, "num_tokens": 1804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.44699916308430576}}
{"text": "\n\n#include <deal.II/base/utilities.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/base/conditional_ostream.h>\n#include <deal.II/base/index_set.h>\n#include <deal.II/base/parameter_handler.h>\n\n#include <deal.II/lac/generic_linear_algebra.h>\nnamespace LA\n{\n    using namespace dealii::LinearAlgebraPETSc;\n#  define USE_PETSC_LA\n}\n\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n//#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/lac/sparsity_tools.h>\n\n//#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/error_estimator.h>\n//#include <deal.II/numerics/solution_transfer.h>\n//#include <deal.II/numerics/matrix_tools.h>\n\n\n#include <deal.II/lac/petsc_parallel_sparse_matrix.h>\n#include <deal.II/lac/petsc_parallel_vector.h>\n#include <deal.II/lac/petsc_solver.h>\n#include <deal.II/lac/petsc_precondition.h>\n\n#include <deal.II/distributed/tria.h>\n#include <deal.II/distributed/grid_refinement.h>\n#include <deal.II/grid/filtered_iterator.h>\n\n#include <fstream>\n#include <iostream>\n\n#include \"my_utility_functions.h\"\n#include \"parameters.h\"\n\n\nnamespace CPPLS\n{\n\tusing namespace dealii;\n\n\ttemplate <int dim>\n\tclass LayerMovementProblem\n\t{\n\tpublic:\n\t\tLayerMovementProblem (const CPPLS::Parameters &parameters);\n\t\t~LayerMovementProblem ();\n\t\tvoid run();\n\n\tprivate:\n\t//Member Data\t\n\t\t//runtime parameters\n\t\tconst CPPLS::Parameters parameters;\n\t\t//mpi communication\n  \t\tMPI_Comm mpi_communicator;\n\t\tconst unsigned int n_mpi_processes;\n\t\tconst unsigned int this_mpi_process;\n\t\t//mesh\n\t\tparallel::distributed::Triangulation<dim> triangulation;\n\t\t//FE basis spaces\n\t\t//pressure\n\t\tint                  degree_P;\n\t  \tDoFHandler<dim>      dof_handler_P;\n\t  \tFE_Q<dim>            fe_P;\n\t  \tIndexSet             locally_owned_dofs_P;\n\t  \tIndexSet             locally_relevant_dofs_P;\n\t  \t//temperature\n\t  \tint                  degree_T;\n\t  \tDoFHandler<dim>      dof_handler_T;\n\t  \tFE_Q<dim>            fe_T;\n\t  \tIndexSet             locally_owned_dofs_T;\n\t  \tIndexSet             locally_relevant_dofs_T;\n\t  \t// level set (can multiple level sets use the same of below? probably not IndexSets)std::vector<IndexSets>\n\t  \tint                  degree_LS;\n\t  \tDoFHandler<dim>      dof_handler_LS;\n\t  \tFE_Q<dim>            fe_LS;\n\t  \tIndexSet             locally_owned_dofs_LS;\n\t  \tIndexSet             locally_relevant_dofs_LS;\n\n\t  \t//output stream where only mpi rank 0 output gets to stdout\n\t  \tConditionalOStream                pcout;\n\n\n\t\tconst double time_step;\n  \t\tdouble current_time;\n\n  \t\t//FE Field Solution Vectors\n\n\t\t  LA::MPI::Vector locally_relevant_solution_u; //ls\n\t\t  LA::MPI::Vector locally_relevant_solution_p;\n\t\t  LA::MPI::Vector locally_relevant_solution_t;\n\t\t  LA::MPI::Vector locally_relevant_solution_f; //speed function\n\t\t  LA::MPI::Vector completely_distributed_solution_u;\n\t\t  LA::MPI::Vector completely_distributed_solution_p;\n\t\t  LA::MPI::Vector completely_distributed_solution_t;\n\t\t  LA::MPI::Vector completely_distributed_solution_f;\n\n\t\t  LA::MPI::Vector overburden;\n\t\t  LA::MPI::Vector bulkdensity;\n\t\t  LA::MPI::Vector porosity;\n\n\n  \t\t// for boundary conditions\n\t  \tstd::vector<unsigned int> boundary_values_id_u;\n\t  \tstd::vector<unsigned int> boundary_values_id_p;\n\t  \tstd::vector<unsigned int> boundary_values_id_t;\n\t  \tstd::vector<double> boundary_values_u;\n\t  \tstd::vector<double> boundary_values_p;\n\t  \tstd::vector<double> boundary_values_t;\n\n\n  \t\t//Physical Vectors\n\n\n\n\n  \t//Member Functions\n\n\t  //create mesh\n\t  void setup_geometry();\n\n\t  void setup_material_configuration(LA::MPI::Vector/*std::vector<LA::MPI::Vector>*/);\n\t  // initialize vectors\n\t  void setup_dofs_P();\n\t  void setup_dofs_T();\n\n\t  void assemble_system_P();\n\t  void assemble_system_T();\n\t\t\n\t  void compute_bulkdensity();\n\t  void compute_overburden();\n\t  void compute_porosity();\n\t  void compute_speed_function();\n\n\t  void output_vectors();\n\n\t};\n\n\n\n\n\n//Constructor\n\n\ttemplate<int dim>\n \tLayerMovementProblem<dim>::LayerMovementProblem (const CPPLS::Parameters &parameters)\n \t:\n\tparameters(parameters),\n\tmpi_communicator (MPI_COMM_WORLD),\n \tn_mpi_processes {Utilities::MPI::n_mpi_processes(mpi_communicator)},\n \tthis_mpi_process {Utilities::MPI::this_mpi_process(mpi_communicator)},\n \t{};\n\n\n//\t\ntemplate<int dim>\nvoid\n\tLayerMovementProblem<dim>::setup_geometry()\n\t{\n\t\t  //GridGenerator::hyper_cube(triangulation, 0, parameters.box_size);\n\t\t  //GridGenerator::subdivided_hyper_rectangle(triangulation, 0, parameters.box_size);\n   \t\t  triangulation.refine_global(parameters.initial_refinement_level);\n\n\t}\n\n\ntemplate <int dim>\n\tvoid\n\tLayerMovementProblem<dim>::compute_bulkdensity()\n\t{\n\t\tfor (auto cell : filter_iterators(triangulation.active_cell_iterators(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tIteratorFilters::LocallyOwnedCell()))\n\t\t  {\n\t\t    fe_values.reinit (cell);\n\t\t    //query the local porosity\n\t\t    \n\t\t  } \n\t}\n\n\ntemplate <int dim>\n\tvoid\n\tLayerMovementProblem<dim>::compute_overburden()\n\t{\n\n\t    const QGauss<dim>  quadrature_formula(3);\n\n\t    FEValues<dim> fe_values (fe, quadrature_formula,\n\t                             update_values    |  update_gradients |\n\t                             update_quadrature_points |\n\t                             update_JxW_values);\n\n\t    const unsigned int   dofs_per_cell = fe.dofs_per_cell;\n\t    const unsigned int   n_q_points    = quadrature_formula.size();\n\n\t    FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n\t    Vector<double>       cell_rhs (dofs_per_cell);\n\n\t    std::vector<types::global_dof_index> local_dof_indices (dofs_per_cell);\n\t\tfor (auto cell : filter_iterators(triangulation.active_cell_iterators(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tIteratorFilters::LocallyOwnedCell())\n\t\t  {\n\t\t    fe_values.reinit (cell);\n\n\t\t \n\t\t  } \n\t}\n\n\ntemplate <int dim>\n\tvoid LayerMovementProblem<dim>::assemble_system_P()\n\t{\n\n    TimerOutput::Scope t(computing_timer, \"assembly_P\");\n     const QGauss<dim>  quadrature_formula(3);\n\n     // RightHandSide<dim> right_hand_side;\n     // //set time too\n     // right_hand_side.set_time(time);\n     // DiffusionCoefficient<dim> diffusion_coeff;\n\n\n    FEValues<dim> fe_values (fe_P, quadrature_formula,\n                             update_values    |  update_gradients |\n                             update_quadrature_points |\n                             update_JxW_values);\n\n    const unsigned int   dofs_per_cell = fe.dofs_per_cell;\n    const unsigned int   n_q_points    = quadrature_formula.size();\n\n    FullMatrix<double>   cell_laplace_matrix (dofs_per_cell, dofs_per_cell);\n    FullMatrix<double>   cell_mass_matrix (dofs_per_cell, dofs_per_cell);\n    Vector<double>       cell_rhs (dofs_per_cell);\n\n    std::vector<types::global_dof_index> local_dof_indices (dofs_per_cell);\n\n    std::vector<double> u_at_quad(n_q_points);\n\n\n    // typename DoFHandler<dim>::active_cell_iterator\n    // cell = dof_handler.begin_active(),\n    // endc = dof_handler.end();\n    // for (; cell!=endc; ++cell)\n    //   if (cell->is_locally_owned())\n    //     {\n\n      for (auto cell : filter_iterators(dof_handler.active_cell_iterators(),\n\t\t\t\t\t\t\t\t\t\tIteratorFilters::LocallyOwnedCell())\n  \t\t{ \n          cell_laplace_matrix = 0;\n          cell_mass_matrix = 0;\n          cell_rhs = 0;\n\n          fe_values.reinit (cell);\n          fe_values.get_function_values(interface_phi,phi_at_quad);\n          fe_values.get_function_values(locally_relevant_solution_p,pressure_at_quad);\n\n          for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n            {\n              poro = get_poro(phi_at_quad[q_point]);\n\t          press = get_pressure(pressure_at_quad[q_point]);\n              poro = exp(-k*press);\n               \n            }\n\n          cell->get_dof_indices (local_dof_indices);\n          constraints.distribute_local_to_global (cell_laplace_matrix,\n                                                  cell_rhs,\n                                                  local_dof_indices,\n                                                  laplace_matrix,\n                                                  forcing);\n          constraints.distribute_local_to_global (cell_mass_matrix,\n                                                  local_dof_indices,\n                                                  mass_matrix);\n\n        }\n\n    // Notice that the assembling above is just a local operation. So, to\n    // form the \"global\" linear system, a synchronization between all\n    // processors is needed. This could be done by invoking the function\n    // compress(). See @ref GlossCompress  \"Compressing distributed objects\"\n    // for more information on what is compress() designed to do.\n    laplace_matrix.compress (VectorOperation::add);\n    mass_matrix.compress (VectorOperation::add);\n    forcing.compress (VectorOperation::add);\n\n\n  }\n\n\t\t\n\n\t}\n\n\n\ntemplate <int dim>\nvoid \nLayerMovementProblem<dim>::output_vectors()\n{\n  DataOut<dim> data_out;\n  data_out.attach_dof_handler (dof_handler_LS);  \n  data_out.add_data_vector (locally_relevant_solution_u, \"u\");\n  data_out.build_patches ();\n  \n  const std::string filename = (\"sol_vectors-\" +\n\t\t\t\tUtilities::int_to_string (output_number, 3) +\n\t\t\t\t\".\" +\n\t\t\t\tUtilities::int_to_string\n\t\t\t\t(triangulation.locally_owned_subdomain(), 4));\n  std::ofstream output ((filename + \".vtu\").c_str());\n  data_out.write_vtu (output);\n  \n  if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)\n    {\n      std::vector<std::string> filenames;\n      for (unsigned int i=0;\n\t   i<Utilities::MPI::n_mpi_processes(mpi_communicator);\n\t   ++i)\n\tfilenames.push_back (\"sol_vectors-\" +\n\t\t\t     Utilities::int_to_string (output_number, 3) +\n\t\t\t     \".\" +\n\t\t\t     Utilities::int_to_string (i, 4) +\n\t\t\t     \".vtu\");\n      \n      std::ofstream master_output ((filename + \".pvtu\").c_str());\n      data_out.write_pvtu_record (master_output, filenames);\n    }\n}\n\n\n\n\n\n\n\n\ntemplate<int dim>\n\tLayerMovementProblem<dim>::run()\n\t{\n\t\t//common mesh\n\t\tsetup_geometry();\n\t\t// \n\t\t//initialize level set solver\n\t\tLevelSetSolver<dim> level_set_solver;\n\n\t\t//initialize pressure solver\n\t\tPressureEquation<dim> pressure_solver;\n\t\t//initialize temperature solver\n\t\t//TemperatureEquation<dim> temperature_solver;\n\n\n\n\n\n  // TIME STEPPING\n  for (timestep_number=1, time=time_step; time<=final_time;\n       time+=time_step,++timestep_number)\n    {\n      pcout << \"Time step \" << timestep_number \n\t    << \" at t=\" << time \n\t    << std::endl;\n      // GET NAVIER STOKES VELOCITY\n      navier_stokes.set_phi(locally_relevant_solution_phi);\n      navier_stokes.nth_time_step(); \n      navier_stokes.get_velocity(locally_relevant_solution_u,locally_relevant_solution_v);\n      transport_solver.set_velocity(locally_relevant_solution_u,locally_relevant_solution_v);\n      // GET LEVEL SET SOLUTION\n      transport_solver.nth_time_step();\n      transport_solver.get_unp1(locally_relevant_solution_phi);      \n      if (get_output && time-(output_number)*output_time>0)\n\toutput_results();\n    }\n\n\n\n\n\t}\n\n\n\n} //end namespace CPPLS\n\nconstexpr int dim {3};\n\n\nint main(int argc, char *argv[])\n{\n  // One of the new features in C++11 is the <code>chrono</code> component of\n  // the standard library. This gives us an easy way to time the output.\n  try\n    {\n\t    using namespace dealii;\n\t    using namespace CPPLS;\n\t      \n\t    auto t0 = std::chrono::high_resolution_clock::now();\n\n\t  \tUtilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n\t  \t\n\t  \tCPPLS::Parameters parameters;\n\t  \tparameters.read_parameter_file(\"parameters.prm\");\n\t  \t\n\t  \tLayerMovementProblem<dim> run_layers(parameters);\n\t  \trun_layers.run();\n\n\t  \tauto t1 = std::chrono::high_resolution_clock::now();\n\t  \tif (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)\n\t    {\n\t      std::cout << \"time elapsed: \"\n\t                << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count()\n\t                << \" milliseconds.\"\n\t                << std::endl;\n\t    }\n\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl << exc.what()\n                << std::endl << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl << \"Aborting!\"\n                << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n  \n}\n", "meta": {"hexsha": "ec62ec1d196e3adbe14bd9d3e185391b834b920a", "size": 13406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/cppls_qh.cpp", "max_stars_repo_name": "stmcgovern/CPPLS", "max_stars_repo_head_hexsha": "b73b73d158323fb4fd482cc144e3c0df6105c6ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-04T17:57:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-04T17:57:16.000Z", "max_issues_repo_path": "source/cppls_qh.cpp", "max_issues_repo_name": "stmcgovern/CPPLS", "max_issues_repo_head_hexsha": "b73b73d158323fb4fd482cc144e3c0df6105c6ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/cppls_qh.cpp", "max_forks_repo_name": "stmcgovern/CPPLS", "max_forks_repo_head_hexsha": "b73b73d158323fb4fd482cc144e3c0df6105c6ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5842217484, "max_line_length": 110, "alphanum_fraction": 0.6450096972, "num_tokens": 3231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744806385542, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.44699916065410356}}
{"text": "#include <boost/mpl/vector_c.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/transform.hpp>\n#include <boost/mpl/equal.hpp>\n#include <boost/mpl/placeholders.hpp>\n\n#include <cassert>\n\nnamespace mpl = boost::mpl;\nusing namespace mpl::placeholders;\n\ntypedef mpl::vector_c<int, 1, 0, 0, 0, 0, 0, 0> mass;\ntypedef mpl::vector_c<int, 0, 1, 0, 0, 0, 0, 0> length;\ntypedef mpl::vector_c<int, 0, 0, 1, 0, 0, 0, 0> time;\ntypedef mpl::vector_c<int, 0, 0, 0, 1, 0, 0, 0> charge;\ntypedef mpl::vector_c<int, 0, 0, 0, 0, 1, 0, 0> temperature;\ntypedef mpl::vector_c<int, 0, 0, 0, 0, 0, 1, 0> intensity;\ntypedef mpl::vector_c<int, 0, 0, 0, 0, 0, 0, 1> substance;\n\n/**\n * Wrapper for int\n */\ntemplate <int n>\nstruct Int {\n    const static int value = n;\n};\n\ntemplate <class T, class Dimensions>\nstruct quantity {\n    explicit quantity(T x): value_(x) {}\n\n    template <class Other>\n        quantity(const quantity<T, Other>& rhs): value_(rhs.value()) {\n            static_assert(mpl::equal<Other, Dimensions>::value, \"They must has same dimensions\");\n        }\n    \n    T value() const { return value_; }\n    private:\n        T value_;\n};\n\ntemplate <class T, class D>\nquantity<T, D> operator + (const quantity<T,D>& lhs, const quantity<T, D>& rhs) {\n    return quantity<T, D>(lhs.value() + rhs.value());\n}\n\ntemplate <class T, class D>\nquantity<T, D> operator - (const quantity<T, D>& lhs, const quantity<T, D>& rhs) {\n    return quantity<T, D>(lhs.value() - rhs.value());\n}\n\n/**\n * wrapper for plus\n */\nstruct plus_f {\n    template <class T1, class T2> \n        struct apply: mpl::plus<T1, T2> {};\n};\n\n\n/**\n * wrapper for minus\n */\nstruct minus_f {\n    template <class T1, class T2>\n        struct apply: mpl::minus<T1, T2> {};\n};\n\n/**\n * operator * overloading, using placeholder to compute type\n */\ntemplate <class T, class D1, class D2>\nquantity<T, typename mpl::transform<D1, D2, mpl::plus<_1, _2>>::type>\n    operator * (const quantity<T, D1>& lhs, const quantity<T, D2>& rhs) {\n        typedef typename mpl::transform<D1, D2, mpl::plus<_1, _2>>::type dim;\n        return quantity<T, dim>(lhs.value() * rhs.value());\n    }\n\ntemplate <class T, class D1, class D2>\nquantity<T, typename mpl::transform<D1, D2, mpl::minus<_1, _2>>::type>\n    operator / (const quantity<T, D1>& lhs, const quantity<T, D2>& rhs) {\n        typedef typename mpl::transform<D1, D2, mpl::minus<_1, _2>>::type dim;\n        return quantity<T, dim>(lhs.value() / rhs.value());\n    }\n\n\nint main()\n{\n    quantity<float, length> la(1.0);\n    quantity<float, length> lb(2.0);\n    quantity<float, mass> m(1.0);\n    \n    quantity<float, length> ls = la + lb;\n    assert(ls.value() == 3.0 && \"la + lb\");\n\n    auto res = la * m;\n\n    return 0;\n}\n", "meta": {"hexsha": "c1b6806396d96d6413787cb512a2189fc20d064b", "size": 2732, "ext": "cc", "lang": "C++", "max_stars_repo_path": "chapter3/dimensions.cc", "max_stars_repo_name": "HelloCodeMing/TMP", "max_stars_repo_head_hexsha": "49573215d1c88eadda8273499b31c3b184a64d0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-02T03:03:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-02T03:03:43.000Z", "max_issues_repo_path": "chapter3/dimensions.cc", "max_issues_repo_name": "HelloCodeMing/TMP", "max_issues_repo_head_hexsha": "49573215d1c88eadda8273499b31c3b184a64d0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "chapter3/dimensions.cc", "max_forks_repo_name": "HelloCodeMing/TMP", "max_forks_repo_head_hexsha": "49573215d1c88eadda8273499b31c3b184a64d0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0495049505, "max_line_length": 97, "alphanum_fraction": 0.6204245974, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744673038222, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4469991533634968}}
{"text": "#include \"../../include/waveO1/observer.hpp\"\n#include \"../../include/waveO1/utilities.hpp\"\n#include \"../../include/mymfem/utilities.hpp\"\n\n#include <iostream>\n#include <Eigen/Core>\n\n\n// Computes DG error on time-like face at a specified time\ndouble WaveO1Observer\n:: eval_dgFtimeError (std::shared_ptr<GridFunction>& p,\n                      std::shared_ptr<GridFunction>& v,\n                      double t) const\n{\n    double errp=0;\n    double errv=0;\n\n    // assumes that all elements have the same geometry\n    auto faceElGeomType = p->FESpace()->GetMesh()\n                ->GetFaceGeometryType(0);\n\n    // L2 error in pressure\n    // set integration rules\n    IntegrationRules rule1{};\n    const IntegrationRule *ir1;\n    int order1 = 2*p->FESpace()->GetFE(0)->GetOrder()+2;\n    ir1 = &rule1.Get(faceElGeomType, order1);\n    m_pE_coeff->SetTime(t);\n    m_assembleDgError->SetIntegrationRule(ir1);\n    errp = m_assembleDgError->Ftime(p.get(),\n                                    m_pE_coeff.get());\n\n    // L2 error in velocity\n    // set integration rules\n    IntegrationRules rule2{};\n    const IntegrationRule *ir2;\n    int order2 = 2*v->FESpace()->GetFE(0)->GetOrder()+2;\n    ir2 = &rule2.Get(faceElGeomType, order2);\n    m_vE_coeff->SetTime(t);\n    m_assembleDgError->SetIntegrationRule(ir2);\n    errv = m_assembleDgError->Ftime(v.get(),\n                                    m_vE_coeff.get());\n\n    return (errp + errv);\n}\n\n//! Computes DG error for a space-like face\n//! at a specified time\ndouble WaveO1Observer\n:: eval_dgFspaceError\n(std::shared_ptr<GridFunction>& p,\n std::shared_ptr<GridFunction>& v,\n double t,\n std::shared_ptr<WaveO1InvSqMediumCoeff>&\n invSqMed) const\n{\n    double errp=0;\n    double errv=0;\n\n    // assumes that all elements have the same geometry\n    auto elGeomType = p->FESpace()\n                ->GetFE(0)->GetGeomType();\n\n    IntegrationRules rule1{}, rule2{};\n    const IntegrationRule *ir1, *ir2;\n\n    m_pE_coeff->SetTime(t);\n    m_vE_coeff->SetTime(t);\n\n    // pressure\n    int order1 = 2*p->FESpace()->GetFE(0)->GetOrder()+2;\n    ir1 = &rule1.Get(elGeomType, order1);\n    m_assembleDgError->SetIntegrationRule(ir1);\n    errp = m_assembleDgError->Fspace(p.get(),\n                                     m_pE_coeff.get(),\n                                     invSqMed.get());\n\n    // velocity\n    int order2 = 2*v->FESpace()->GetFE(0)->GetOrder()+2;\n    ir2 = &rule2.Get(elGeomType, order2);\n    m_assembleDgError->SetIntegrationRule(ir2);\n    m_vE->ProjectCoefficient(*m_vE_coeff);\n    errv = m_assembleDgError->Fspace(v.get(),\n                                     m_vE_coeff.get());\n\n    return (errp + errv);\n}\n\ndouble WaveO1Observer\n:: eval_dgFspaceError\n(std::shared_ptr<GridFunction>& p1,\n std::shared_ptr<GridFunction>& p2,\n std::shared_ptr<GridFunction>& v1,\n std::shared_ptr<GridFunction>& v2,\n double t,\n std::shared_ptr<WaveO1InvSqMediumCoeff>&\n invSqMed) const\n{\n    double errp=0;\n    double errv=0;\n\n    // assumes that all elements have the same geometry\n    auto elGeomType = p1->FESpace()\n                ->GetFE(0)->GetGeomType();\n\n    IntegrationRules rule1{}, rule2{};\n    const IntegrationRule *ir1, *ir2;\n\n    m_pE_coeff->SetTime(t);\n    m_vE_coeff->SetTime(t);\n\n    // pressure\n    int order1 = 2*p1->FESpace()->GetFE(0)->GetOrder()+2;\n    ir1 = &rule1.Get(elGeomType, order1);\n    m_assembleDgError->SetIntegrationRule(ir1);\n    errp = m_assembleDgError->Fspace(p1.get(), p2.get(),\n                                     m_pE_coeff.get(),\n                                     invSqMed.get());\n\n    // velocity\n    int order2 = 2*v1->FESpace()->GetFE(0)->GetOrder()+2;\n    ir2 = &rule2.Get(elGeomType, order2);\n    m_assembleDgError->SetIntegrationRule(ir2);\n    errv = m_assembleDgError->Fspace(v1.get(), v2.get(),\n                                     m_vE_coeff.get());\n\n    return (errp + errv);\n}\n\n// Computes DG error\nstd::tuple <double, double> WaveO1Observer\n:: eval_xtDgError (BlockVector& W) const\n{\n    double errDgFtime=0;\n    double errDgFspace=0;\n\n    int Nt = m_tWspace->GetNE();\n    int xdimW1 = m_xW1space->GetTrueVSize();\n    int xdimW2 = m_xW2space->GetTrueVSize();\n\n    Vector& p = W.GetBlock(0);\n    Vector& v = W.GetBlock(1);\n\n    Vector pSol1(xdimW1), pSol2(xdimW1);\n    std::shared_ptr<GridFunction> pGSol1\n            = std::make_shared<GridFunction>\n            (m_xW1space, pSol1);\n    std::shared_ptr<GridFunction> pGSol2\n            = std::make_shared<GridFunction>\n            (m_xW1space, pSol2);\n\n    Vector vSol1(xdimW2), vSol2(xdimW2);\n    std::shared_ptr<GridFunction> vGSol1\n            = std::make_shared<GridFunction>\n            (m_xW2space, vSol1);\n    std::shared_ptr<GridFunction> vGSol2\n            = std::make_shared<GridFunction>\n            (m_xW2space, vSol2);\n\n    // medium\n    auto invSqMed = std::make_shared<WaveO1InvSqMediumCoeff>\n            (m_testCase);\n\n    ElementTransformation *tTrans = nullptr;\n    const FiniteElement *tFe = nullptr;\n    Vector tShape;\n    Array<int> tVdofs;\n\n    // DG error for time-like faces\n    Eigen::VectorXd bufErrFtime(Nt);\n    bufErrFtime.setZero();\n\n    double errFtime;\n    for (int n=0; n<Nt; n++)\n    {\n        m_tWspace->GetElementVDofs(n, tVdofs);\n        tTrans = m_tWspace->GetElementTransformation(n);\n\n        tFe = m_tWspace->GetFE(n);\n        int tNdofs = tFe->GetDof();\n        tShape.SetSize(tNdofs);\n\n        int order = 2*tFe->GetOrder()+2;\n        const IntegrationRule *ir\n                = &IntRules.Get(tFe->GetGeomType(), order);\n\n        for (int i = 0; i < ir->GetNPoints(); i++)\n        {\n            const IntegrationPoint &ip = ir->IntPoint(i);\n            tTrans->SetIntPoint(&ip);\n            tFe->CalcShape(ip, tShape);\n\n            // build solution at time t\n            Vector t;\n            tTrans->Transform(ip, t);\n            build_xSol_FG(p, tShape, tVdofs, pSol1);\n            build_xSol_FG(v, tShape, tVdofs, vSol1);\n\n            errFtime = eval_dgFtimeError\n                    (pGSol1, vGSol1, t(0));\n\n            double w = ip.weight*tTrans->Weight();\n            bufErrFtime(n) += w*errFtime;\n        }\n    }\n    errDgFtime = std::sqrt(bufErrFtime.sum());\n\n    // DG error for space-like faces\n    Eigen::VectorXd bufErrFspace(Nt+1);\n    bufErrFspace.setZero();\n\n    Vector t;\n    IntegrationPoint ip0, ip1;\n    ip0.Set1w(0, 1);\n    ip1.Set1w(1, 1);\n\n    // for t=0\n    {\n        int n=0;\n        int np = n;\n\n        // build solution at tn^{+}\n        m_tWspace->GetElementVDofs(np, tVdofs);\n        tTrans = m_tWspace->GetElementTransformation(np);\n        tFe = m_tWspace->GetFE(np);\n        int tNdofs = tFe->GetDof();\n        tShape.SetSize(tNdofs);\n\n        tTrans->SetIntPoint(&ip0);\n        tFe->CalcShape(ip0, tShape);\n        tTrans->Transform(ip0, t);\n        build_xSol_FG(p, tShape, tVdofs, pSol2);\n        build_xSol_FG(v, tShape, tVdofs, vSol2);\n\n        // compute error\n        bufErrFspace(0) = eval_dgFspaceError\n                (pGSol2, vGSol2, t(0), invSqMed);\n    }\n\n    // for 0 < t < T\n    for (int n=1; n<Nt; n++)\n    {\n        int nm = n-1;\n        int np = n;\n\n        // build solution at tn^{-}\n        m_tWspace->GetElementVDofs(nm, tVdofs);\n        tTrans = m_tWspace->GetElementTransformation(nm);\n        tFe = m_tWspace->GetFE(nm);\n        int tNdofs = tFe->GetDof();\n        tShape.SetSize(tNdofs);\n\n        tTrans->SetIntPoint(&ip1);\n        tFe->CalcShape(ip1, tShape);\n        tTrans->Transform(ip1, t);\n        build_xSol_FG(p, tShape, tVdofs, pSol1);\n        build_xSol_FG(v, tShape, tVdofs, vSol1);\n\n        // build solution at tn^{+}\n        m_tWspace->GetElementVDofs(np, tVdofs);\n        tTrans = m_tWspace->GetElementTransformation(np);\n        tFe = m_tWspace->GetFE(np);\n        tNdofs = tFe->GetDof();\n        tShape.SetSize(tNdofs);\n\n        tTrans->SetIntPoint(&ip0);\n        tFe->CalcShape(ip0, tShape);\n        tTrans->Transform(ip0, t);\n        build_xSol_FG(p, tShape, tVdofs, pSol2);\n        build_xSol_FG(v, tShape, tVdofs, vSol2);\n\n        // compute error\n        bufErrFspace(n) = eval_dgFspaceError\n                (pGSol1, pGSol2, vGSol1, vGSol2,\n                 t(0), invSqMed);\n    }\n\n    // for t=T\n    {\n        int n = Nt;\n        int nm = n-1;\n\n        // build solution at tn^{-}\n        m_tWspace->GetElementVDofs(nm, tVdofs);\n        tTrans = m_tWspace->GetElementTransformation(nm);\n        tFe = m_tWspace->GetFE(nm);\n        int tNdofs = tFe->GetDof();\n        tShape.SetSize(tNdofs);\n\n        tTrans->SetIntPoint(&ip1);\n        tFe->CalcShape(ip1, tShape);\n        tTrans->Transform(ip1, t);\n        build_xSol_FG(p, tShape, tVdofs, pSol1);\n        build_xSol_FG(v, tShape, tVdofs, vSol1);\n\n        // compute error\n        bufErrFspace(n) = eval_dgFspaceError\n                (pGSol1, vGSol1, t(0), invSqMed);\n    }\n    errDgFspace = std::sqrt(0.5*bufErrFspace.sum());\n\n    return {errDgFtime, errDgFspace};\n}\n\n// End of file\n", "meta": {"hexsha": "5973a3137ba5860767c34ddb2c885def1147f55f", "size": 8891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/waveO1/dg_error.cpp", "max_stars_repo_name": "pratyuksh/FEMWave", "max_stars_repo_head_hexsha": "9ed0fbe0981d712ce3e531500381589b034fb9f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T13:06:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T13:06:38.000Z", "max_issues_repo_path": "src/waveO1/dg_error.cpp", "max_issues_repo_name": "pratyuksh/FEMWave", "max_issues_repo_head_hexsha": "9ed0fbe0981d712ce3e531500381589b034fb9f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/waveO1/dg_error.cpp", "max_forks_repo_name": "pratyuksh/FEMWave", "max_forks_repo_head_hexsha": "9ed0fbe0981d712ce3e531500381589b034fb9f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-05T13:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T13:06:39.000Z", "avg_line_length": 29.0555555556, "max_line_length": 60, "alphanum_fraction": 0.5881228208, "num_tokens": 2726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.44695603639642967}}
{"text": "#include \"davidson_util.h\"\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <cmath>\n\nstd::pair<double, std::vector<double>> DavidsonUtil::diagonalize(\n    const std::vector<double>& initial_vector,\n    const std::vector<double>& diagonal,\n    const std::function<std::vector<double>(\n        const std::vector<double>&, const bool)>& apply_hamiltonian,\n    const int max_iterations_in,\n    const bool verbose) {\n  const double TOLERANCE = 1.0e-10;\n  const double EPSILON = 1.0e-10;\n  const int n_dets = initial_vector.size();\n  double lowest_eigenvalue = 0.0;\n  std::vector<double> lowest_eigenvector;\n\n  if (n_dets == 1) {\n    lowest_eigenvalue = diagonal[0];\n    lowest_eigenvector.resize(1);\n    lowest_eigenvector[0] = 1.0;\n    return std::make_pair(lowest_eigenvalue, std::move(lowest_eigenvector));\n  }\n\n  const int max_iterations = std::min(n_dets, max_iterations_in);\n  double lowest_eigenvalue_prev = 0.0;\n  double residual_norm = 0.0;\n\n  Eigen::MatrixXd v = Eigen::MatrixXd::Zero(n_dets, max_iterations);\n  for (int i = 0; i < n_dets; i++) v(i, 0) = initial_vector[i];\n  v.col(0).normalize();\n\n  Eigen::MatrixXd Hv = Eigen::MatrixXd::Zero(n_dets, max_iterations);\n  Eigen::VectorXd w = Eigen::VectorXd::Zero(n_dets);\n  Eigen::VectorXd Hw = Eigen::VectorXd::Zero(n_dets);\n  Eigen::MatrixXd h_krylov =\n      Eigen::MatrixXd::Zero(max_iterations, max_iterations);\n  Eigen::MatrixXd h_overwrite;\n  Eigen::VectorXd eigenvalues = Eigen::VectorXd::Zero(max_iterations);\n  int len_work = 3 * max_iterations - 1;\n  Eigen::VectorXd work(len_work);\n  bool converged = false;\n  std::vector<double> tmp_v(n_dets);\n\n  // Get diagonal elements.\n  Eigen::VectorXd diag_elems(n_dets);\n  for (int i = 0; i < n_dets; i++) diag_elems[i] = diagonal[i];\n\n  // First iteration.\n  for (int i = 0; i < n_dets; i++) tmp_v[i] = v(i, 0);\n  const auto& tmp_Hv = apply_hamiltonian(tmp_v, true);\n  for (int i = 0; i < n_dets; i++) Hv(i, 0) = tmp_Hv[i];\n  lowest_eigenvalue = v.col(0).dot(Hv.col(0));\n  h_krylov(0, 0) = lowest_eigenvalue;\n  w = v.col(0);\n  Hw = Hv.col(0);\n  if (verbose) print_intermediate_result(0, lowest_eigenvalue);\n\n  for (int it = 1; it < max_iterations; it++) {\n    // Compute residual.\n    for (int j = 0; j < n_dets; j++) {\n      const double diff_to_diag = lowest_eigenvalue - diag_elems[j];\n      if (std::abs(diff_to_diag) < EPSILON) {\n        v(j, it) = -1.0;\n      } else {\n        v(j, it) = (Hw(j, 0) - lowest_eigenvalue * w(j, 0)) / diff_to_diag;\n      }\n    }\n\n    // If residual is small, converge.\n    residual_norm = v.col(it).norm();\n    if (residual_norm < TOLERANCE) converged = true;\n\n    // Orthogonalize and normalize.\n    for (int i = 0; i < it; i++) {\n      double norm = v.col(it).dot(v.col(i));\n      v.col(it) -= norm * v.col(i);\n    }\n    v.col(it).normalize();\n\n    // Apply H once.\n    for (int i = 0; i < n_dets; i++) tmp_v[i] = v(i, it);\n    const auto& tmp_Hv2 = apply_hamiltonian(tmp_v, false);\n    for (int i = 0; i < n_dets; i++) Hv(i, it) = tmp_Hv2[i];\n\n    // Construct subspace matrix.\n    for (int i = 0; i <= it; i++) {\n      h_krylov(i, it) = v.col(i).dot(Hv.col(it));\n      h_krylov(it, i) = h_krylov(i, it);\n    }\n\n    // Diagonalize subspace matrix.\n    len_work = 3 * it + 2;\n    h_overwrite = h_krylov.leftCols(it + 1).topRows(it + 1);\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigenSolver(\n        h_krylov.leftCols(it + 1).topRows(it + 1));\n    const auto& eigenvalues = eigenSolver.eigenvalues();\n    const auto& eigenvectors = eigenSolver.eigenvectors();\n    lowest_eigenvalue = eigenvalues[0];\n    int lowest_id = 0;\n    for (int i = 1; i <= it; i++) {\n      if (eigenvalues[i] < lowest_eigenvalue) {\n        lowest_eigenvalue = eigenvalues[i];\n        lowest_id = i;\n      }\n    }\n    w = v.leftCols(it) * eigenvectors.col(lowest_id).topRows(it);\n    Hw = Hv.leftCols(it) * eigenvectors.col(lowest_id).topRows(it);\n\n    if (verbose) print_intermediate_result(it, lowest_eigenvalue);\n    if (std::abs(lowest_eigenvalue - lowest_eigenvalue_prev) < TOLERANCE) {\n      converged = true;\n      break;\n    } else {\n      lowest_eigenvalue_prev = lowest_eigenvalue;\n    }\n\n    if (converged) break;\n  }\n\n  lowest_eigenvector.resize(n_dets);\n  for (int i = 0; i < n_dets; i++) lowest_eigenvector[i] = w(i);\n\n  return std::make_pair(lowest_eigenvalue, std::move(lowest_eigenvector));\n}\n\nvoid DavidsonUtil::print_intermediate_result(\n    const int iteration, const double lowest_eigenvalue) {\n  printf(\n      \"Davidson Iteration #%d. Eigenvalue: %#.12f\\n\",\n      iteration,\n      lowest_eigenvalue);\n}\n", "meta": {"hexsha": "702ea5a97dd3efbfd0dbae49337fadc36afbacf5", "size": 4559, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/solver/davidson_util.cc", "max_stars_repo_name": "jl2922/hci", "max_stars_repo_head_hexsha": "2806ad1f2cc0e100632eaaaf491670f928c9feec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-09-23T17:52:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-01T20:15:01.000Z", "max_issues_repo_path": "src/solver/davidson_util.cc", "max_issues_repo_name": "jl2922/hci", "max_issues_repo_head_hexsha": "2806ad1f2cc0e100632eaaaf491670f928c9feec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-09-24T14:29:03.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-24T14:44:12.000Z", "max_forks_repo_path": "src/solver/davidson_util.cc", "max_forks_repo_name": "jl2922/hci", "max_forks_repo_head_hexsha": "2806ad1f2cc0e100632eaaaf491670f928c9feec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5220588235, "max_line_length": 76, "alphanum_fraction": 0.643781531, "num_tokens": 1421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.44679652279814125}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Domain/CoordinateMaps/SpecialMobius.hpp\"\n\n#include <boost/none.hpp>\n#include <boost/optional.hpp>\n#include <cmath>\n#include <pup.h>\n\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"ErrorHandling/Assert.hpp\"\n#include \"Utilities/ConstantExpressions.hpp\"\n#include \"Utilities/DereferenceWrapper.hpp\"\n#include \"Utilities/EqualWithinRoundoff.hpp\"\n#include \"Utilities/GenerateInstantiations.hpp\"\n#include \"Utilities/MakeWithValue.hpp\"\n#include \"Utilities/StdArrayHelpers.hpp\"\n\nnamespace domain {\nnamespace CoordinateMaps {\n\nSpecialMobius::SpecialMobius(const double mu) noexcept\n    : mu_(mu), is_identity_(mu_ == 0.0) {\n  // Note: Empirically we have found that the map is accurate\n  // to 12 decimal places for mu = 0.96.\n  ASSERT(abs(mu) < 0.96, \"The magnitude of mu must be less than 0.96.\");\n}\n\ntemplate <typename T>\nstd::array<tt::remove_cvref_wrap_t<T>, 3> SpecialMobius::mobius_distortion(\n    const std::array<T, 3>& coords, const double mu) const noexcept {\n  using ReturnType = tt::remove_cvref_wrap_t<T>;\n  const ReturnType& x = coords[0];\n  const ReturnType& y = coords[1];\n  const ReturnType& z = coords[2];\n  const double mu_squared = square(mu);\n  const ReturnType r_squared = square(x) + square(y) + square(z);\n  const ReturnType lambda = 1.0 / (1.0 - 2.0 * mu * x + mu_squared * r_squared);\n  return std::array<ReturnType, 3>{\n      {lambda * ((1.0 + mu_squared) * x - mu * (1.0 + r_squared)),\n       (1.0 - mu_squared) * lambda * y, (1.0 - mu_squared) * lambda * z}};\n}\n\ntemplate <typename T>\ntnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame>\nSpecialMobius::mobius_distortion_jacobian(const std::array<T, 3>& coords,\n                                          const double mu) const noexcept {\n  using ReturnType = tt::remove_cvref_wrap_t<T>;\n  const ReturnType& x = coords[0];\n  const ReturnType& y = coords[1];\n  const ReturnType& z = coords[2];\n  const double mu_squared = square(mu);\n  const ReturnType r_squared = square(x) + square(y) + square(z);\n  const ReturnType common_factor =\n      (mu_squared - 1.0) / square(1.0 - 2.0 * mu * x + mu_squared * r_squared);\n  auto jacobian_matrix =\n      make_with_value<tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame>>(\n          dereference_wrapper(coords[0]), 0.0);\n\n  get<0, 0>(jacobian_matrix) =\n      -(mu_squared * (2.0 * square(x) - r_squared) - 2.0 * mu * x + 1.0) *\n      common_factor;\n  get<1, 0>(jacobian_matrix) = (2.0 * mu * y * (mu * x - 1.0)) * common_factor;\n  get<2, 0>(jacobian_matrix) = (2.0 * mu * z * (mu * x - 1.0)) * common_factor;\n\n  get<0, 1>(jacobian_matrix) = -1.0 * get<1, 0>(jacobian_matrix);\n  get<1, 1>(jacobian_matrix) =\n      -(mu_squared * (r_squared - 2.0 * square(y)) - 2.0 * mu * x + 1.0) *\n      common_factor;\n  get<2, 1>(jacobian_matrix) = 2.0 * mu_squared * y * z * common_factor;\n\n  get<0, 2>(jacobian_matrix) = -1.0 * get<2, 0>(jacobian_matrix);\n  get<1, 2>(jacobian_matrix) = get<2, 1>(jacobian_matrix);\n  get<2, 2>(jacobian_matrix) =\n      -(mu_squared * (r_squared - 2.0 * square(z)) - 2.0 * mu * x + 1.0) *\n      common_factor;\n  return jacobian_matrix;\n}\n\ntemplate <typename T>\nstd::array<tt::remove_cvref_wrap_t<T>, 3> SpecialMobius::operator()(\n    const std::array<T, 3>& source_coords) const noexcept {\n  return mobius_distortion(source_coords, mu_);\n}\n\nboost::optional<std::array<double, 3>> SpecialMobius::inverse(\n    const std::array<double, 3>& target_coords) const noexcept {\n  // Invert only points inside or on the unit sphere.\n  const auto r_squared = magnitude(target_coords);\n  if (r_squared <= 1.0 or equal_within_roundoff(r_squared,1.0)) {\n    return mobius_distortion(target_coords, -mu_);\n  }\n  return boost::none;\n}\n\ntemplate <typename T>\ntnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> SpecialMobius::jacobian(\n    const std::array<T, 3>& source_coords) const noexcept {\n  return mobius_distortion_jacobian(source_coords, mu_);\n}\n\ntemplate <typename T>\ntnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame>\nSpecialMobius::inv_jacobian(const std::array<T, 3>& source_coords) const\n    noexcept {\n  return mobius_distortion_jacobian((*this)(source_coords), -mu_);\n}\n\nvoid SpecialMobius::pup(PUP::er& p) noexcept {\n  p | mu_;\n  p | is_identity_;\n}\n\nbool operator==(const SpecialMobius& lhs, const SpecialMobius& rhs) noexcept {\n  return lhs.mu_ == rhs.mu_ and lhs.is_identity_ == rhs.is_identity_;\n}\n\nbool operator!=(const SpecialMobius& lhs, const SpecialMobius& rhs) noexcept {\n  return not(lhs == rhs);\n}\n\n// Explicit instantiations\n/// \\cond\n#define DTYPE(data) BOOST_PP_TUPLE_ELEM(0, data)\n\n#define INSTANTIATE(_, data)                                                   \\\n  template std::array<tt::remove_cvref_wrap_t<DTYPE(data)>, 3> SpecialMobius:: \\\n  operator()(const std::array<DTYPE(data), 3>& source_coords) const noexcept;  \\\n  template tnsr::Ij<tt::remove_cvref_wrap_t<DTYPE(data)>, 3, Frame::NoFrame>   \\\n  SpecialMobius::jacobian(const std::array<DTYPE(data), 3>& source_coords)     \\\n      const noexcept;                                                          \\\n  template tnsr::Ij<tt::remove_cvref_wrap_t<DTYPE(data)>, 3, Frame::NoFrame>   \\\n  SpecialMobius::inv_jacobian(const std::array<DTYPE(data), 3>& source_coords) \\\n      const noexcept;\n\nGENERATE_INSTANTIATIONS(INSTANTIATE, (double, DataVector,\n                                      std::reference_wrapper<const double>,\n                                      std::reference_wrapper<const DataVector>))\n\n#undef DTYPE\n#undef INSTANTIATE\n/// \\endcond\n}  // namespace CoordinateMaps\n}  // namespace domain\n", "meta": {"hexsha": "2968e40349ca7195f5b3f20b0bfb68ddb3103b9a", "size": 5617, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Domain/CoordinateMaps/SpecialMobius.cpp", "max_stars_repo_name": "tomwlodarczyk/spectre", "max_stars_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Domain/CoordinateMaps/SpecialMobius.cpp", "max_issues_repo_name": "tomwlodarczyk/spectre", "max_issues_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Domain/CoordinateMaps/SpecialMobius.cpp", "max_forks_repo_name": "tomwlodarczyk/spectre", "max_forks_repo_head_hexsha": "086aaee002f2f07eb812cf17b8e1ba54052feb71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4726027397, "max_line_length": 80, "alphanum_fraction": 0.6688623821, "num_tokens": 1624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388083214156, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.44678410866208745}}
{"text": "\n///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2018 John Maddock\n//  Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_BESSEL_ITERATORS_HPP\n#define BOOST_MATH_BESSEL_ITERATORS_HPP\n\n#include <boost/math/tools/recurrence.hpp>\n\nnamespace boost {\n   namespace math {\n      namespace detail {\n\n         template <class T>\n         struct bessel_jy_recurrence\n         {\n            bessel_jy_recurrence(T v, T z) : v(v), z(z) {}\n            boost::math::tuple<T, T, T> operator()(int k)\n            {\n               return boost::math::tuple<T, T, T>(1, -2 * (v + k) / z, 1);\n            }\n\n            T v, z;\n         };\n         template <class T>\n         struct bessel_ik_recurrence\n         {\n            bessel_ik_recurrence(T v, T z) : v(v), z(z) {}\n            boost::math::tuple<T, T, T> operator()(int k)\n            {\n               return boost::math::tuple<T, T, T>(1, -2 * (v + k) / z, -1);\n            }\n\n            T v, z;\n         };\n      } // namespace detail\n\n      template <class T>\n      struct bessel_j_backwards_iterator\n      {\n         typedef std::ptrdiff_t difference_type;\n         typedef T value_type;\n         typedef T* pointer;\n         typedef T& reference;\n         typedef std::input_iterator_tag iterator_category;\n\n         bessel_j_backwards_iterator(const T& v, const T& x)\n            : it(detail::bessel_jy_recurrence<T>(v, x), boost::math::cyl_bessel_j(v, x)) \n         {\n            if(v < 0)\n               boost::math::policies::raise_domain_error(\"bessel_j_backwards_iterator<%1%>\", \"Order must be > 0 stable backwards recurrence but got %1%\", v, boost::math::policies::policy<>());\n         }\n\n         bessel_j_backwards_iterator(const T& v, const T& x, const T& J_v)\n            : it(detail::bessel_jy_recurrence<T>(v, x), J_v) \n         {\n            if(v < 0)\n               boost::math::policies::raise_domain_error(\"bessel_j_backwards_iterator<%1%>\", \"Order must be > 0 stable backwards recurrence but got %1%\", v, boost::math::policies::policy<>());\n         }\n         bessel_j_backwards_iterator(const T& v, const T& x, const T& J_v_plus_1, const T& J_v)\n            : it(detail::bessel_jy_recurrence<T>(v, x), J_v_plus_1, J_v)\n         {\n            if (v < -1)\n               boost::math::policies::raise_domain_error(\"bessel_j_backwards_iterator<%1%>\", \"Order must be > 0 stable backwards recurrence but got %1%\", v, boost::math::policies::policy<>());\n         }\n\n         bessel_j_backwards_iterator& operator++()\n         {\n            ++it;\n            return *this;\n         }\n\n         bessel_j_backwards_iterator operator++(int)\n         {\n            bessel_j_backwards_iterator t(*this);\n            ++(*this);\n            return t;\n         }\n\n         T operator*() { return *it; }\n\n      private:\n         boost::math::tools::backward_recurrence_iterator< detail::bessel_jy_recurrence<T> > it;\n      };\n\n      template <class T>\n      struct bessel_i_backwards_iterator\n      {\n         typedef std::ptrdiff_t difference_type;\n         typedef T value_type;\n         typedef T* pointer;\n         typedef T& reference;\n         typedef std::input_iterator_tag iterator_category;\n\n         bessel_i_backwards_iterator(const T& v, const T& x)\n            : it(detail::bessel_ik_recurrence<T>(v, x), boost::math::cyl_bessel_i(v, x)) \n         {\n            if(v < -1)\n               boost::math::policies::raise_domain_error(\"bessel_i_backwards_iterator<%1%>\", \"Order must be > 0 stable backwards recurrence but got %1%\", v, boost::math::policies::policy<>());\n         }\n         bessel_i_backwards_iterator(const T& v, const T& x, const T& I_v)\n            : it(detail::bessel_ik_recurrence<T>(v, x), I_v) \n         {\n            if(v < -1)\n               boost::math::policies::raise_domain_error(\"bessel_i_backwards_iterator<%1%>\", \"Order must be > 0 stable backwards recurrence but got %1%\", v, boost::math::policies::policy<>());\n         }\n         bessel_i_backwards_iterator(const T& v, const T& x, const T& I_v_plus_1, const T& I_v)\n            : it(detail::bessel_ik_recurrence<T>(v, x), I_v_plus_1, I_v)\n         {\n            if(v < -1)\n               boost::math::policies::raise_domain_error(\"bessel_i_backwards_iterator<%1%>\", \"Order must be > 0 stable backwards recurrence but got %1%\", v, boost::math::policies::policy<>());\n         }\n\n         bessel_i_backwards_iterator& operator++()\n         {\n            ++it;\n            return *this;\n         }\n\n         bessel_i_backwards_iterator operator++(int)\n         {\n            bessel_i_backwards_iterator t(*this);\n            ++(*this);\n            return t;\n         }\n\n         T operator*() { return *it; }\n\n      private:\n         boost::math::tools::backward_recurrence_iterator< detail::bessel_ik_recurrence<T> > it;\n      };\n\n      template <class T>\n      struct bessel_i_forwards_iterator\n      {\n         typedef std::ptrdiff_t difference_type;\n         typedef T value_type;\n         typedef T* pointer;\n         typedef T& reference;\n         typedef std::input_iterator_tag iterator_category;\n\n         bessel_i_forwards_iterator(const T& v, const T& x)\n            : it(detail::bessel_ik_recurrence<T>(v, x), boost::math::cyl_bessel_i(v, x)) \n         {\n            if(v > 1)\n               boost::math::policies::raise_domain_error(\"bessel_i_forwards_iterator<%1%>\", \"Order must be < 0 stable forwards recurrence but got %1%\", v, boost::math::policies::policy<>());\n         }\n         bessel_i_forwards_iterator(const T& v, const T& x, const T& I_v)\n            : it(detail::bessel_ik_recurrence<T>(v, x), I_v) \n         {\n            if (v > 1)\n               boost::math::policies::raise_domain_error(\"bessel_i_forwards_iterator<%1%>\", \"Order must be < 0 stable forwards recurrence but got %1%\", v, boost::math::policies::policy<>());\n         }\n         bessel_i_forwards_iterator(const T& v, const T& x, const T& I_v_plus_1, const T& I_v)\n            : it(detail::bessel_ik_recurrence<T>(v, x), I_v_plus_1, I_v)\n         {\n            if (v > 1)\n               boost::math::policies::raise_domain_error(\"bessel_i_forwards_iterator<%1%>\", \"Order must be < 0 stable forwards recurrence but got %1%\", v, boost::math::policies::policy<>());\n         }\n\n         bessel_i_forwards_iterator& operator++()\n         {\n            ++it;\n            return *this;\n         }\n\n         bessel_i_forwards_iterator operator++(int)\n         {\n            bessel_i_forwards_iterator t(*this);\n            ++(*this);\n            return t;\n         }\n\n         T operator*() { return *it; }\n\n      private:\n         boost::math::tools::forward_recurrence_iterator< detail::bessel_ik_recurrence<T> > it;\n      };\n\n   }\n} // namespaces\n\n#endif // BOOST_MATH_BESSEL_ITERATORS_HPP\n", "meta": {"hexsha": "b7205cff5d902e9726b9e1743e7a915bdaa2f1b3", "size": 6893, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/special_functions/bessel_iterators.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 597.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T10:59:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:59:36.000Z", "max_issues_repo_path": "boost/math/special_functions/bessel_iterators.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "boost/math/special_functions/bessel_iterators.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 112.0, "max_forks_repo_forks_event_min_datetime": "2018-07-26T04:36:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:29:34.000Z", "avg_line_length": 36.8609625668, "max_line_length": 192, "alphanum_fraction": 0.5623095894, "num_tokens": 1780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289387998695208, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4467841041066579}}
{"text": "// Copyright  (C)  2007  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n\n// Version: 1.0\n// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// URL: http://www.orocos.org/kdl\n\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// Lesser General Public License for more details.\n\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n#ifndef KDL_CHAIN_IKSOLVERVEL_PINV_NSO_HPP\n#define KDL_CHAIN_IKSOLVERVEL_PINV_NSO_HPP\n\n#include \"chainiksolver.hpp\"\n#include \"chainjnttojacsolver.hpp\"\n#include <Eigen/Core>\n\nnamespace KDL\n{\n    /**\n     * Implementation of a inverse velocity kinematics algorithm based\n     * on the generalize pseudo inverse to calculate the velocity\n     * transformation from Cartesian to joint space of a general\n     * KDL::Chain. It uses a svd-calculation based on householders\n     * rotations.\n     *\n     * In case of a redundant robot this solver optimizes the following criterium:\n     * g=0.5*sum(weight*(Desired_joint_positions - actual_joint_positions))^2 as described in \n     *  A. Liegeois. Automatic supervisory control of the configuration and \n     * behavior of multibody mechanisms. IEEE Transactions on Systems, Man, and \n     * Cybernetics, 7(12):868–871, 1977\n     *\n     * @ingroup KinematicFamily\n     */\n    class ChainIkSolverVel_pinv_nso : public ChainIkSolverVel\n    {\n    public:\n        /**\n         * Constructor of the solver\n         *\n         * @param chain the chain to calculate the inverse velocity\n         * kinematics for\n         * @param opt_pos the desired positions of the chain used by to resolve the redundancy\n         * @param weights the weights applied in the joint space\n         * @param eps if a singular value is below this value, its\n         * inverse is set to zero, default: 0.00001\n         * @param maxiter maximum iterations for the svd calculation,\n         * default: 150\n         * @param alpha the null-space velocity gain\n         *\n         */\n        ChainIkSolverVel_pinv_nso(const Chain& chain, const JntArray& opt_pos, const JntArray& weights, double eps=0.00001,int maxiter=150, double alpha = 0.25);\n        explicit ChainIkSolverVel_pinv_nso(const Chain& chain, double eps=0.00001,int maxiter=150, double alpha = 0.25);\n        ~ChainIkSolverVel_pinv_nso();\n\n        virtual int CartToJnt(const JntArray& q_in, const Twist& v_in, JntArray& qdot_out);\n        /**\n         * not (yet) implemented.\n         *\n         */\n        virtual int CartToJnt(const JntArray& q_init, const FrameVel& v_in, JntArrayVel& q_out){return -1;};\n\n        /**\n         * Request the joint weights for optimization criterion\n         *\n         *\n         * @return const reference to the joint weights\n         */\n        const JntArray& getWeights()const\n        {\n            return weights;\n        }\n\n        /**\n         * Request the optimal joint positions\n         *\n         *\n         * @return const reference to the optimal joint positions\n         */\n        const JntArray& getOptPos()const\n        {\n            return opt_pos;\n        }\n\n        /**\n         * Request null space velocity gain\n         *\n         *\n         * @return const reference to the null space velocity gain\n         */\n        const double& getAlpha()const\n        {\n            return alpha;\n        }\n\n        /**\n         *Set joint weights for optimization criterion\n         *\n         *@param weights the joint weights\n         *\n         */\n        virtual int setWeights(const JntArray &weights);\n\n        /**\n         *Set optimal joint positions\n         *\n         *@param opt_pos optimal joint positions\n         *\n         */\n        virtual int setOptPos(const JntArray &opt_pos);\n\n        /**\n         *Set null psace velocity gain\n         *\n         *@param alpha NUllspace velocity cgain\n         *\n         */\n        virtual int setAlpha(const double alpha);\n\n        /**\n         * Retrieve the latest return code from the SVD algorithm\n         * @return 0 if CartToJnt() not yet called, otherwise latest SVD result code.\n         */\n        int getSVDResult()const {return svdResult;};\n\n        /// @copydoc KDL::SolverI::updateInternalDataStructures\n        virtual void updateInternalDataStructures();\n\n    private:\n        const Chain& chain;\n        ChainJntToJacSolver jnt2jac;\n        unsigned int nj;\n        Jacobian jac;\n        Eigen::MatrixXd U;\n        Eigen::VectorXd S;\n        Eigen::VectorXd Sinv;\n        Eigen::MatrixXd V;\n        Eigen::VectorXd tmp;\n        Eigen::VectorXd tmp2;\n        double eps;\n        int maxiter;\n        int svdResult;\n        double alpha;\n        JntArray weights;\n        JntArray opt_pos;\n    };\n}\n#endif\n\n", "meta": {"hexsha": "0690bd4a2acfd149e765536e804f0518a7b8270a", "size": 5324, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libraries/kdl/kdl/chainiksolvervel_pinv_nso.hpp", "max_stars_repo_name": "Laragervaise/AR-mobile-app-for-robots", "max_stars_repo_head_hexsha": "f8b6581bb21a3956893d6552913cc606cc063992", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T12:33:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T07:14:13.000Z", "max_issues_repo_path": "melodic/src/orocos_kinematics_dynamics/orocos_kdl/src/chainiksolvervel_pinv_nso.hpp", "max_issues_repo_name": "disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA", "max_issues_repo_head_hexsha": "3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-08T10:26:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T10:31:11.000Z", "max_forks_repo_path": "melodic/src/orocos_kinematics_dynamics/orocos_kdl/src/chainiksolvervel_pinv_nso.hpp", "max_forks_repo_name": "disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA", "max_forks_repo_head_hexsha": "3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0683229814, "max_line_length": 161, "alphanum_fraction": 0.6286626597, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.446780450026472}}
{"text": "/*!\n  \\file gpp_math.hpp\n  \\rst\n  1. OVERVIEW OF GAUSSIAN PROCESSES AND EXPECTED IMPROVEMENT; WHAT ARE WE TRYING TO DO?\n  2. FILE OVERVIEW\n  3. IMPLEMENTATION NOTES\n  4. NOTATION\n  5. CITATIONS\n\n  **1. OVERVIEW OF GAUSSIAN PROCESSES AND EXPECTED IMPROVEMENT; WHAT ARE WE TRYING TO DO?**\n\n  .. Note:: these comments are copied in Python: interfaces/__init__.py\n\n  At a high level, this file optimizes an objective function \\ms f(x)\\me.  This operation\n  requires data/uncertainties about prior and concurrent experiments as well as\n  a covariance function describing how these data [are expected to] relate to each\n  other.  The points x represent experiments. If \\ms f(x)\\me is say, survival rate for\n  a drug test, the dimensions of x might include dosage amount, dosage frequency,\n  and overall drug-use time-span.\n\n  The objective function is not required in closed form; instead, only the ability\n  to sample it at points of interest is needed.  Thus, the optimization process\n  cannot work with \\ms f(x)\\me directly; instead a surrogate is built via interpolation\n  with Gaussian Proccesses (GPs).\n\n  Following Rasmussen & Williams (2.2), a Gaussian Process is a collection of random\n  variables, any finite number of which have a joint Gaussian distribution (Defn 2.1).\n  Hence a GP is fully specified by its mean function, \\ms m(x)\\me, and covariance function,\n  \\ms k(x,x')\\me.  Then we assume that a real process \\ms f(x)\\me (e.g., drug survival rate) is\n  distributed like:\n\n  .. math:: f(x) ~ GP(m(x), k(x,x'))\n\n  with\n\n  .. math:: m(x) = E[f(x)], k(x,x') = E[(f(x) - m(x))*(f(x') - m(x'))].\n\n  Then sampling from \\ms f(x)\\me is simply drawing from a Gaussian with the appropriate mean\n  and variance.\n\n  However, since we do not know \\ms f(x)\\me, we cannot precisely build its corresponding GP.\n  Instead, using samples from \\ms f(x)\\me (e.g., by measuring experimental outcomes), we can\n  iteratively improve our estimate of \\ms f(x)\\me.  See GaussianProcess class docs\n  and implementation docs for details on how this is done.\n\n  The optimization process models the objective using a Gaussian process (GP) prior\n  (also called a GP predictor) based on the specified covariance and the input\n  data (e.g., through member functions ComputeMeanOfPoints, ComputeVarianceOfPoints).  Using the GP,\n  we can compute the expected improvement (EI) from sampling any particular point.  EI\n  is defined relative to the best currently known value, and it represents what the\n  algorithm believes is the most likely outcome from sampling a particular point in parameter\n  space (aka conducting a particular experiment).\n\n  See ExpectedImprovementEvaluator and OnePotentialSampleExpectedImprovementEvaluator class\n  docs for further details on computing EI.  Both support ComputeExpectedImprovement() and\n  ComputeGradExpectedImprovement().\n\n  The dimension of the GP is equal to the number of simultaneous experiments being run;\n  i.e., the GP may be multivariate.  The behavior of the GP is controlled by its underlying\n  covariance function and the data/uncertainty of prior points (experiments).\n\n  With the ability the compute EI, the final step is to optimize\n  to find the best EI.  This is done using multistart gradient descent (MGD), in\n  ComputeOptimalPointsToSample(). This method wraps a MGD call and falls back on random search\n  if that fails. See gpp_optimization.hpp for multistart/optimization templates. This method\n  can evaluate and optimize EI at serval points simultaneously; e.g., if we wanted to run 4 simultaneous\n  experiments, we can use EI to select all 4 points at once.\n\n  The literature (e.g., Ginsbourger 2008) refers to these problems collectively as q-EI, where q\n  is a positive integer. So 1-EI is the originally dicussed usage, and the previous scenario with\n  multiple simultaneous points/experiments would be called 4-EI.\n\n  Additionally, there are use cases where we have existing experiments that are not yet complete but\n  we have an opportunity to start some new trials. For example, maybe we are a drug company currently\n  testing 2 combinations of dosage levels. We got some new funding, and can now afford to test\n  3 more sets of dosage parameters. Ideally, the decision on the new experiments should depend on\n  the existence of the 2 ongoing tests. We may not have any data from the ongoing experiments yet;\n  e.g., they are [double]-blind trials. If nothing else, we would not want to duplicate any\n  existing experiments! So we want to solve 3-EI using the knowledge of the 2 ongoing experiments.\n\n  We call this q,p-EI, so the previous example would be 3,2-EI. The q-EI notation is equivalent to\n  q,0-EI; if we do not explicitly write the value of p, it is 0. So q is the number of new\n  (simultaneous) experiments to select. In code, this would be the size of the output from EI\n  optimization (i.e., ``best_points_to_sample``, of which there are ``q = num_to_sample points``).\n  p is the number of ongoing/incomplete experiments to take into account (i.e., ``points_being_sampled``\n  of which there are ``p = num_being_sampled`` points).\n\n  Back to optimization: the idea behind gradient descent is simple.  The gradient gives us the\n  direction of steepest ascent (negative gradient is steepest descent).  So each iteration, we\n  compute the gradient and take a step in that direction.  The size of the step is not specified\n  by GD and is left to the specific implementation.  Basically if we take steps that are\n  too large, we run the risk of over-shooting the solution and even diverging.  If we\n  take steps that are too small, it may take an intractably long time to reach the solution.\n  Thus the magic is in choosing the step size; we do not claim that our implementation is\n  perfect, but it seems to work reasonably.  See ``gpp_optimization.hpp`` for more details about\n  GD as well as the template definition.\n\n  For particularly difficult problems or problems where gradient descent's parameters are not\n  well-chosen, GD can fail to converge.  If this happens, we can fall back on heuristics;\n  e.g., 'dumb' search (i.e., evaluate EI at a large number of random points and take the best\n  one). Naive search lives in: ComputeOptimalPointsToSampleViaLatinHypercubeSearch<>().\n\n  **2. FILE OVERVIEW**\n\n  This file contains mathematical functions supporting optimal learning.\n  These include functions to compute characteristics of Gaussian Processes\n  (e.g., variance, mean) and the gradients of these quantities as well as functions to\n  compute and optimize the expected improvement.\n\n  Functions here generally require some combination of a CovarianceInterface object as well as\n  data about prior and current (i.e., concurrent) experiments.  These data are encapsulated in\n  the GaussianProcess class.  Then we build an ExpectedImprovementEvaluator object (with\n  associated state, see ``gpp_common.hpp`` item 5 for (Evaluator, State) relations) on top of a\n  GaussianProcess for computing and optimizing EI.\n\n  For further theoretical details about Gaussian Processes, see\n  Rasmussen and Williams, Gaussian Processes for Machine Learning (2006).\n  A bare-bones summary is provided in ``gpp_math.cpp``.\n\n  For further details about expected improvement and the optimization thereof,\n  see Scott Clark's PhD thesis.  Again, a summary is provided in ``gpp_math.cpp``'s file comments.\n\n  **3. IMPLEMENTATION NOTES**\n\n  a. This file has a few primary endpoints for EI optimization:\n\n     i. ComputeOptimalPointsToSampleWithRandomStarts<>():\n\n        Solves the q,p-EI problem.\n\n        Takes in a gaussian_process describing the prior, domain, config, etc.; outputs the next best point(s) (experiment)\n        to sample (run). Uses gradient descent.\n\n     ii. ComputeOptimalPointsToSampleViaLatinHypercubeSearch<>():\n\n         Estimates the q,p-EI problem.\n\n         Takes in a gaussian_process describing the prior, domain, etc.; outputs the next best point(s) (experiment)\n         to sample (run). Uses 'dumb' search.\n\n     iii. ComputeOptimalPointsToSample<>() (Recommended):\n\n          Solves the q,p-EI problem.\n\n          Wraps the previous two items; relies on gradient descent and falls back to \"dumb\" search if it fails.\n\n     .. NOTE::\n         See ``gpp_math.cpp``'s header comments for more detailed implementation notes.\n\n         There are also several other functions with external linkage in this header; these\n         are provided primarily to ease testing and to permit lower level access from python.\n\n  b. See ``gpp_common.hpp`` header comments for additional implementation notes.\n\n  **4. NOTATION**\n\n  And domain-specific notation, following Rasmussen, Williams:\n\n    * ``X = points_sampled``; this is the training data (size ``dim`` X ``num_sampled``), also called the design matrix\n    * ``Xs = points_to_sample``; this is the test data (size ``dim`` X num_to_sample``)\n    * ``y, f, f(x) = points_sampled_value``, the experimental results from sampling training points\n    * ``K, K_{ij}, K(X,X) = covariance(X_i, X_j)``, covariance matrix between training inputs (``num_sampled x num_sampled``)\n    * ``Ks, Ks_{ij}, K(X,Xs) = covariance(X_i, Xs_j)``, covariance matrix between training and test inputs (``num_sampled x num_to_sample``)\n    * ``Kss, Kss_{ij}, K(Xs,Xs) = covariance(Xs_i, Xs_j)``, covariance matrix between test inputs (``num_to_sample x num_to_sample``)\n    * ``\\theta``: (vector) of hyperparameters for a covariance function\n\n  .. NOTE::\n       Due to confusion with multiplication (K_* looks awkward in code comments), Rasmussen & Williams' \\ms K_*\\me\n       notation has been repalced with ``Ks`` and \\ms K_{**}\\me is ``Kss``.\n\n  Connecting to the q,p-EI notation, both the points represented by \"q\" and \"p\" are represented by ``Xs``. Within\n  the GP, there is no distinction between points being sampled by ongoing experiments and new points to sample.\n\n  **5. CITATIONS**\n\n  a. Gaussian Processes for Machine Learning.\n     Carl Edward Rasmussen and Christopher K. I. Williams. 2006.\n     Massachusetts Institute of Technology.  55 Hayward St., Cambridge, MA 02142.\n     http://www.gaussianprocess.org/gpml/ (free electronic copy)\n\n  b. Parallel Machine Learning Algorithms In Bioinformatics and Global Optimization (PhD Dissertation).\n     Part II, EPI: Expected Parallel Improvement\n     Scott Clark. 2012.\n     Cornell University, Center for Applied Mathematics.  Ithaca, NY.\n     https://github.com/sc932/Thesis\n     sclark@yelp.com\n\n  c. Differentiation of the Cholesky Algorithm.\n     S. P. Smith. 1995.\n     Journal of Computational and Graphical Statistics. Volume 4. Number 2. p134-147\n\n  d. A Multi-points Criterion for Deterministic Parallel Global Optimization based on Gaussian Processes.\n     David Ginsbourger, Rodolphe Le Riche, and Laurent Carraro.  2008.\n     D´epartement 3MI. Ecole Nationale Sup´erieure des Mines. 158 cours Fauriel, Saint-Etienne, France.\n     ginsbourger@emse.fr, leriche@emse.fr, carraro@emse.fr\n\n  e. Efficient Global Optimization of Expensive Black-Box Functions.\n     Jones, D.R., Schonlau, M., Welch, W.J. 1998.\n     Journal of Global Optimization, 13, 455-492.\n\\endrst*/\n\n#ifndef MOE_OPTIMAL_LEARNING_CPP_GPP_MATH_HPP_\n#define MOE_OPTIMAL_LEARNING_CPP_GPP_MATH_HPP_\n\n#include <algorithm>\n#include <limits>\n#include <memory>\n#include <vector>\n\n#include <stdlib.h>\n#include <queue>\n\n#include <boost/math/distributions/normal.hpp>  // NOLINT(build/include_order)\n\n#include \"gpp_common.hpp\"\n#include \"gpp_domain.hpp\"\n#include \"gpp_exception.hpp\"\n#include \"gpp_covariance.hpp\"\n#include \"gpp_logging.hpp\"\n#include \"gpp_optimization.hpp\"\n#include \"gpp_optimizer_parameters.hpp\"\n#include \"gpp_random.hpp\"\n\nnamespace optimal_learning {\n\nvoid BuildMixCovarianceMatrix(const CovarianceInterface& covariance,\n                              double const * restrict points_sampled,\n                              double const * restrict points_to_sample,\n                              int dim, int num_sampled, int num_to_sample,\n                              int const * restrict derivatives_sampled,\n                              int num_derivatives_sampled,\n                              int const * restrict derivatives_to_sample,\n                              int num_derivatives_to_sample,\n                              double * restrict cov_matrix) noexcept;\n\nstruct ThreadSchedule;\nstruct PointsToSampleState;\n\n/*!\\rst\n  Object that encapsulates Gaussian Process Priors (GPPs).  A GPP is defined by a set of\n  (sample point, function value, noise variance) triples along with a covariance function that relates the points.\n  Each point has dimension dim.  These are the training data; for example, each sample point might specify an experimental\n  cohort and the corresponding function value is the objective measured for that experiment.  There is one noise variance\n  value per function value; this is the measurement error and is treated as N(0, noise_variance) Gaussian noise.\n\n  GPPs estimate a real process \\ms f(x) = GP(m(x), k(x,x'))\\me (see file docs).  This class deals with building an estimator\n  to the actual process using measurements taken from the actual process--the (sample point, function val, noise) triple.\n  Then predictions about unknown points can be made by sampling from the GPP--in particular, finding the (predicted)\n  mean and variance.  These functions (and their gradients) are provided in ComputeMeanOfPoints, ComputeVarianceOfPoints,\n  etc.\n\n  Further mathematical details are given in the implementation comments, but we are essentially computing:\n\n  | ComputeMeanOfPoints    : ``K(Xs, X) * [K(X,X) + \\sigma_n^2 I]^{-1} * y``\n  | ComputeVarianceOfPoints: ``K(Xs, Xs) - K(Xs,X) * [K(X,X) + \\sigma_n^2 I]^{-1} * K(X,Xs)``\n\n  This (estimated) mean and variance characterize the predicted distributions of the actual \\ms m(x), k(x,x')\\me\n  functions that underly our GP.\n\n  .. Note:: the preceding comments are copied in Python: interfaces/gaussian_process_interface.py\n\n  For testing and experimental purposes, this class provides a framework for sampling points from the GP (i.e., given a\n  point to sample and predicted measurement noise) as well as adding additional points to an already-formed GP.  Sampling\n  points requires drawing from \\ms N(0,1)\\me so this class also holds PRNG state to do so via the NormalRNG object from gpp_random.\n\n  .. NOTE::\n       Functions that manipulate the PRNG directly or indirectly (changing state, generating points)\n       are NOT THREAD-SAFE. All thread-safe functions are marked const.\n\n  These mean/variance methods require some external state: namely, the set of potential points to sample.  Additionally,\n  temporaries and derived quantities depending on these \"points to sample\" eliminate redundant computation.  This external\n  state is handled through PointsToSampleState objects, which are constructed separately and filled through\n  PointsToSampleState::SetupState() which interacts with functions in this class.\n\\endrst*/\nclass GaussianProcess final {\n public:\n  using StateType = PointsToSampleState;\n  using NormalGeneratorType = NormalRNG;\n  using EngineType = NormalGeneratorType::EngineType;\n\n  //! Default seed value to make reproducing test results simple.\n  static constexpr EngineType::result_type kDefaultSeed = 87214;\n\n  //! Minimum allowed standard deviation value in ComputeGradCholeskyVarianceOfPointsPerPoint (= machine precision).\n  //! Values that are too small result in problems b/c we may compute ``std_dev/var`` (which is enormous\n  //! if ``std_dev = 1.0e-150`` and ``var = 1.0e-300``) since this only arises when we fail to compute ``std_dev = var = 0.0``.\n  //! Note: this is only relevant if noise = 0.0; this minimum will not affect GPs with noise since this value\n  //! is below the smallest amount of noise users can meaningfully add.\n  //! This value was chosen to be consistent with the singularity condition in CholeskyFactorL\n  //! and tested for robustness with the setup in EIOnePotentialSampleEdgeCasesTest().\n  static constexpr double kMinimumStdDev = std::numeric_limits<double>::epsilon();\n\n  /*!\\rst\n    Constructs a GaussianProcess object.  All inputs are required; no default constructor nor copy/assignment are allowed.\n\n    .. Warning::\n        ``points_sampled`` is not allowed to contain duplicate points; doing so results in singular covariance matrices.\n\n    \\param\n      :covariance: the CovarianceFunction object encoding assumptions about the GP's behavior on our data\n      :points_sampled[dim][num_sampled]: points that have already been sampled\n      :points_sampled_value[num_sampled]: values of the already-sampled points\n      :noise_variance[num_sampled]: the ``\\sigma_n^2`` (noise variance) associated w/observation, points_sampled_value\n      :dim: the spatial dimension of a point (i.e., number of independent params in experiment)\n      :num_sampled: number of already-sampled points\n  \\endrst*/\n  GaussianProcess(const CovarianceInterface& covariance_in,\n                  double const * restrict points_sampled_in,\n                  double const * restrict points_sampled_value_in,\n                  double const * restrict noise_variance_in,\n                  int const * restrict derivatives_in,\n                  int num_derivatives_in,\n                  int dim_in, int num_sampled_in) OL_NONNULL_POINTERS;\n\n  GaussianProcess(const GaussianProcess& source);\n\n  int dim() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return dim_;\n  }\n\n  int num_sampled() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return num_sampled_;\n  }\n\n  int num_derivatives() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return num_derivatives_;\n  }\n\n  const std::vector<double>& points_sampled() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return points_sampled_;\n  }\n\n  const std::vector<double>& points_sampled_value() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return points_sampled_value_;\n  }\n\n  const std::vector<double>& noise_variance() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return noise_variance_;\n  }\n\n  const std::vector<int>& derivatives() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return derivatives_;\n  }\n\n  double get_mean() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return mean_;\n  }\n\n  const std::vector<double>& get_K_inv_y() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return K_inv_y_;\n  }\n\n  /*!\\rst\n    Change the hyperparameters of this GP's covariance function.\n    Also forces recomputation of all derived quantities for GP to remain consistent.\n\n    .. WARNING::\n         Using this function invalidates any PointsToSampleState objects created with \"this\" object.\n         For any such objects \"state\", call state.SetupState(...) to restore them.\n\n    \\param\n      :hyperparameters_new[covariance_ptr->GetNumberOfHyperparameters]: new hyperparameter array\n  \\endrst*/\n  void SetCovarianceHyperparameters(double const * restrict hyperparameters_new) OL_NONNULL_POINTERS {\n    covariance_ptr_->SetHyperparameters(hyperparameters_new);\n    RecomputeDerivedVariables();\n  }\n\n  /*!\\rst\n    Sets up the PointsToSampleState object so that it can be used to compute GP mean, variance, and gradients thereof.\n    ASSUMES all needed space is ALREADY ALLOCATED.\n\n    This function should not be called directly; instead use PointsToSampleState::SetupState().\n\n    \\param\n      :points_to_sample_state[1]: pointer to a PointsToSampleState object where all space has been properly allocated\n    \\output\n      :points_to_sample_state[1]: pointer to a fully configured PointsToSampleState object. overwrites input\n  \\endrst*/\n  void FillPointsToSampleState(StateType * points_to_sample_state) const OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Add the specified (point, fcn value, noise variance) historical data to this GP.\n\n    Forces recomputation of all derived quantities for GP to remain consistent.\n\n    \\param\n      :new_points[dim][num_new_points]: coordinates of each new point to add\n      :new_points_value[num_new_points]: function value at each new point\n      :new_points_noise_variance[num_new_points]: \\sigma_n^2 corresponding to the signal noise in measuring new_points_value\n      :num_new_points: number of new points to add to the GP\n  \\endrst*/\n  void AddPointsToGP(double const * restrict new_points,\n                     double const * restrict new_points_value,\n                     //double const * restrict new_points_noise_variance,\n                     int num_new_points);\n\n  /*!\\rst\n    Sample a function value from a Gaussian Process prior, provided a point at which to sample.\n\n    Uses the formula ``function_value = gpp_mean + sqrt(gpp_variance) * w1 + sqrt(noise_variance) * w2``, where ``w1, w2``\n    are draws from \\ms N(0,1)\\me.\n\n    .. NOTE::\n         Set noise_variance to 0 if you want \"accurate\" draws from the GP.\n         BUT if the drawn (point, value) pair is meant to be added back into the GP (e.g., for testing), then this point\n         MUST be drawn with noise_variance equal to the noise associated with \"point\" as a member of \"points_sampled\"\n\n    \\param\n      :point_to_sample[dim]: coordinates of the point at which to generate a function value (from GP)\n      :noise_variance_this_point: if this point is to be added into the GP, it needs to be generated with its associated noise var\n    \\return\n      function value drawn from this GP\n  \\endrst*/\n  void SamplePointFromGP(double const * restrict point_to_sample,\n//                       double noise_variance_this_point,\n                         double * results) noexcept OL_NONNULL_POINTERS;\n\n\n  /*!\\rst\n    Sample only function values for a list of points\n  \\endrst*/\n  int SamplePointsFromGP(double const * restrict points_to_sample,\n                         const int num_sample,\n                         double * results) noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Approximate the global optima of the GP.\n  \\endrst*/\n  void SampleGlobalOptimaFromGP(int const num_optima,\n                                int const inner_number,\n                                const TensorProductDomain& domain,\n                                double * points_optima) noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Computes the mean of this GP at each of ``Xs`` (``points_to_sample``).\n\n    .. Note:: ``points_to_sample`` should not contain duplicate points.\n\n    .. Note:: comments are copied in Python: interfaces/gaussian_process_interface.py\n\n    \\param\n      :points_to_sample_state: a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n    \\output\n      :mean_of_points[num_to_sample]: mean of GP, one per GP dimension\n  \\endrst*/\n  void ComputeMeanOfPoints(const StateType& points_to_sample_state,\n                           double * restrict mean_of_points) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    \\param\n      :discrete_pts[dim][num_pts]: the set of points to approximate the KG factor\n      :num_pts: number of points in discrete_pts\n    \\output\n      :mean_of_points[num_pts]: mean of GP, one per GP dimension\n  \\endrst*/\n  void ComputeMeanOfAdditionalPoints(double const * discrete_pts,\n                                     int num_pts, int const * gradients_discrete_pts,\n                                     int num_gradients_discrete_pts,\n                                     double * restrict mean_of_points) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Computes the gradient of the mean of this GP at each of ``Xs`` (``points_to_sample``) wrt ``Xs``.\n\n    .. Note:: ``points_to_sample`` should not contain duplicate points.\n\n    Note that ``grad_mu`` is nominally sized: ``grad_mu[dim][num_to_sample][num_to_sample]``.\n    However, for ``0 <= i,j < num_to_sample``, ``i != j``, ``grad_mu[d][i][j] = 0``.\n    (See references or implementation for further details.)\n    Thus, ``grad_mu`` is stored in a reduced form which only tracks the nonzero entries.\n\n    .. Note:: comments are copied in Python: interfaces/gaussian_process_interface.py\n\n    \\param\n      :points_to_sample_state: a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n    \\output\n      :grad_mu[dim][state.num_derivatives]: gradient of the mean of the GP.  ``grad_mu[d][i]`` is\n        actually the gradient of ``\\mu_i`` with respect to ``x_{d,i}``, the d-th dimension of\n        the i-th entry of ``points_to_sample``.\n  \\endrst*/\n  void ComputeGradMeanOfPoints(const StateType& points_to_sample_state,\n                               double * restrict grad_mu) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Computes the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``).\n\n    The variance matrix is symmetric (in fact, SPD) and is stored in the LOWER TRIANGLE.\n\n    .. Note:: ``points_to_sample`` should not contain duplicate points.\n\n    .. Note:: comments are copied in Python: interfaces/gaussian_process_interface.py\n\n    \\param\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n    \\output\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n      :var_star[num_to_sample][num_to_sample]: variance of GP evaluated at ``points_to_sample``, LOWER TRIANGLE\n  \\endrst*/\n  void ComputeVarianceOfPoints(StateType * points_to_sample_state,\n                               int const * restrict gradients_to_sample_part2,\n                               int num_gradients_to_sample_part2,\n                               double * restrict var_star) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Computes the covariance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``) and each point of discrete points.\n\n    .. Note:: ``points_to_sample`` should not contain duplicate points.\n\n    .. Note:: comments are copied in Python: interfaces/gaussian_process_interface.py\n\n    \\param\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n      :discrete_pts[dim][num_pts]: the set of points to approximate the KG factor\n      :num_pts: number of points in discrete_pts\n    \\output\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n      :var_star[num_to_sample][num_pts]: covariance of GP evaluated at ``points_to_sample`` and ``discrete_pts``\n  \\endrst*/\n\n  void ComputeCovarianceOfPoints(StateType * points_to_sample_state,\n                                 double const * restrict discrete_pts,\n                                 int num_pts, int const * restrict gradients_discrete_pts,\n                                 int num_gradients_discrete_pts, bool precomputed, double const * ktd,\n                                 double * restrict var_star) const noexcept;\n\n  /*!\\rst\n    Computes the covariance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``) and each point of discrete points.\n\n    .. Note:: ``points_to_sample`` should not contain duplicate points.\n\n    .. Note:: comments are copied in Python: interfaces/gaussian_process_interface.py\n\n    \\param\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n      :discrete_pts[dim][num_pts]: the set of points to approximate the KG factor\n      :num_pts: number of points in discrete_pts\n    \\output\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n      :var_star[num_to_sample][num_pts]: covariance of GP evaluated at ``points_to_sample`` and ``discrete_pts``\n  \\endrst*/\n  void ComputeTrain(double const * restrict discrete_pts,\n                    int num_pts, int const * restrict gradients_discrete_pts,\n                    int num_gradients_discrete_pts, double * restrict var_star) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Similar to ComputeGradCholeskyVarianceOfPoints() except this does not include the gradient terms from\n    the cholesky factorization.  Description will not be duplicated here.\n  \\endrst*/\n  void ComputeGradVarianceOfPoints(StateType * points_to_sample_state,\n                                   double * restrict grad_var) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    \\param\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n      :discrete_pts[dim][num_pts]: the set of points to approximate the KG factor\n      :num_pts: number of points in discrete_pts\n    \\output\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n      :grad_var[dim][num_to_sample][num_pts][state->num_derivatives]: gradient of the\n        variance of the GP.  ``grad_var[d][i][j][k]`` is actually the gradients of ``var_{i,j}`` with\n        respect to ``x_{d,k}``, the d-th dimension of the k-th entry of ``points_to_sample``\n  \\endrst*/\n\n  void ComputeGradCovarianceOfPoints(StateType * points_to_sample_state,\n                                     double const * restrict discrete_pts,\n                                     int num_pts, int const * restrict gradients_discrete_pts,\n                                     int num_gradients_discrete_pts, bool precomputed, double const * ktd,\n                                     double * restrict grad_var) const noexcept;\n\n  /*!\\rst\n    Computes the gradient of the cholesky factorization of the variance of this GP with respect to ``points_to_sample``.\n    This function accounts for the effect on the gradient resulting from\n    cholesky-factoring the variance matrix.  See Smith 1995 for algorithm details.\n\n    ``points_to_sample`` is not allowed to contain duplicate points. Violating this results in a singular variance matrix.\n\n    Note that ``grad_chol`` is nominally sized:\n\n    ``grad_chol[dim][num_to_sample][num_to_sample][num_to_sample]``.\n\n    Let this be indexed ``grad_chol[d][i][j][k]``, which is read the derivative of ``var[i][j]``\n    with respect to ``x_{d,k}`` (x = ``points_to_sample``)\n\n    .. Note:: comments are copied in Python: interfaces/gaussian_process_interface.py\n\n    \\param\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n      :chol_var[num_to_sample][num_to_sample]: the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``)\n        e.g., from the cholesky factorization of ``ComputeVarianceOfPoints``\n    \\output\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n      :grad_chol[dim][num_to_sample][num_to_sample][state->num_derivatives]: gradient of the cholesky-factored\n        variance of the GP.  ``grad_chol[d][i][j][k]`` is actually the gradients of ``var_{i,j}`` with\n        respect to ``x_{d,k}``, the d-th dimension of the k-th entry of ``points_to_sample``\n\n    ** store in UPPER triangle\n  \\endrst*/\n  void ComputeGradCholeskyVarianceOfPoints(StateType * points_to_sample_state,\n                                           double const * restrict chol_var,\n                                           double * restrict grad_chol) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Computes the gradient of the invers of the cholesky factorization of the variance of this GP with respect to ``points_to_sample``.\n\n    Note that ``grad_chol`` is nominally sized:\n\n    ``grad_chol[dim][num_to_sample][num_to_sample][num_to_sample]``.\n\n    Let this be indexed ``grad_chol[d][i][j][k]``, which is read the derivative of ``var[i][j]``\n    with respect to ``x_{d,k}`` (x = ``points_to_sample``)\n\n    .. Note:: comments are copied in Python: interfaces/gaussian_process_interface.py\n\n    \\param\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n      :chol_var[num_to_sample][num_to_sample]: the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``)\n        e.g., from the cholesky factorization of ``ComputeVarianceOfPoints``\n    \\output\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n      :grad_var[dim][num_to_sample][num_pts + num_to_sample][state->num_derivatives]: gradient of the invers of the cholesky-factored\n        variance of the GP.  ``grad_chol[d][i][j][k]`` is actually the gradients of ``var_{i,j}`` with\n        respect to ``x_{d,k}``, the d-th dimension of the k-th entry of ``points_to_sample``\n  \\endrst*/\n  void ComputeGradInverseCholeskyVarianceOfPoints(StateType * points_to_sample_state,\n                                                  double const * restrict chol_var,\n                                                  double const * restrict var,\n                                                  double const * restrict cov,\n                                                  double const * restrict discrete_pts,\n                                                  int num_pts, bool precomputed, double const * ktd,\n                                                  double * restrict grad_chol) const noexcept;\n\n  /*!\\rst\n    Computes the gradient of the invers of the cholesky factorization of the variance of this GP with respect to ``points_to_sample``.\n\n    Note that ``grad_chol`` is nominally sized:\n\n    ``grad_chol[dim][num_to_sample][num_to_sample][num_to_sample]``.\n\n    Let this be indexed ``grad_chol[d][i][j][k]``, which is read the derivative of ``var[i][j]``\n    with respect to ``x_{d,k}`` (x = ``points_to_sample``)\n\n    .. Note:: comments are copied in Python: interfaces/gaussian_process_interface.py\n\n    \\param\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n      :chol_var[num_to_sample][num_to_sample]: the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``)\n        e.g., from the cholesky factorization of ``ComputeVarianceOfPoints``\n    \\output\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n      :grad_var[dim][num_to_sample][num_pts][state->num_derivatives]: gradient of the invers of the cholesky-factored\n        variance of the GP.  ``grad_chol[d][i][j][k]`` is actually the gradients of ``var_{i,j}`` with\n        respect to ``x_{d,k}``, the d-th dimension of the k-th entry of ``points_to_sample``\n  \\endrst*/\n  void ComputeGradInverseCholeskyCovarianceOfPoints(StateType * points_to_sample_state,\n                                                  double const * restrict chol_var,\n                                                  double const * restrict grad_chol,\n                                                  double const * restrict chol_inv_times_cov,\n                                                  double const * restrict discrete_pts,\n                                                  int num_pts, bool precomputed, double const * ktd,\n                                                  double * restrict grad_inverse_chol) const noexcept;\n\n  /*!\\rst\n    Seed the random number generator with the specified seed.\n    See gpp_random, struct NormalRNG for details.\n\n    \\param\n      :seed: new seed to set\n  \\endrst*/\n  void SetExplicitSeed(EngineType::result_type seed) noexcept;\n\n  /*!\\rst\n    Seed the random number generator using a combination of the specified seed,\n    current time, and potentially other factors.\n    See gpp_random, struct NormalRNG for details.\n\n    \\param\n      :seed: base value for new seed\n  \\endrst*/\n  void SetRandomizedSeed(EngineType::result_type seed) noexcept;\n\n  /*!\\rst\n    Seeds the generator with its last used seed value.\n    Useful for testing--e.g., can conduct multiple runs with the same initial conditions\n  \\endrst*/\n  void ResetToMostRecentSeed() noexcept;\n\n  /*!\\rst\n    Clones \"this\" GaussianProcess.\n\n    \\return\n      Pointer to a constructed object that is a copy of \"this\"\n  \\endrst*/\n  GaussianProcess * Clone() const OL_WARN_UNUSED_RESULT;\n\n  OL_DISALLOW_DEFAULT_AND_ASSIGN(GaussianProcess);\n\n// protected:\n//  explicit GaussianProcess(const GaussianProcess& source);\n  //! covariance class (for computing covariance and its gradients)\n  std::unique_ptr<CovarianceInterface> covariance_ptr_;\n\n private:\n  void BuildCovarianceMatrixWithNoiseVariance() noexcept;\n\n  /*!\\rst\n    :cov_matrix[num_sampled][num_to_sample]: computed \"mix\" covariance matrix\n  \\endrst*/\n  void BuildMixCovarianceMatrix(double const * restrict points_to_sample, int num_to_sample, int const * restrict derivatives_to_sample,\n                                int num_derivatives_to_sample, double * restrict cov_mat) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Similar to ComputeGradCholeskyVarianceOfPointsPerPoint() except this does not include the gradient terms from\n    the cholesky factorization.  Description will not be duplicated here.\n  \\endrst*/\n  void ComputeGradVarianceOfPointsPerPoint(StateType * points_to_sample_state, int diff_index,\n                                           double * restrict grad_var) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    \\param\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n      :discrete_pts[dim][num_pts]: the set of points to approximate the KG factor\n      :num_pts: number of points in discrete_pts\n      :diff_index: index of ``points_to_sample`` in {0, .. ``num_to_sample``-1} to be differentiated against\n    \\output\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n      :grad_chol[dim][num_to_sample][num_pts]: gradient of the cholesky-factored\n        variance of the GP.  ``grad_chol[d][i][j]`` is actually the gradients of ``var_{i,j}`` with\n        respect to ``x_{d,k}``, the d-th dimension of the k-th entry of ``points_to_sample``, where\n        k = ``diff_index``\n  \\endrst*/\n\n  void ComputeGradCovarianceOfPointsPerPoint(StateType * points_to_sample_state, int diff_index,\n                                             double const * restrict discrete_pts, int num_pts,\n                                             int const * restrict gradients_discrete_pts,\n                                             int num_gradients_discrete_pts, bool precomputed, double const * kt,\n                                             double * restrict grad_var) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Computes the gradient of the cholesky factorization of the variance of this GP with respect to the\n    ``diff_index``-th point in ``points_to_sample``.\n\n    This internal method is meant to be used by ComputeGradCholeskyVarianceOfPoints() to construct the gradient wrt all\n    points of ``points_to_sample``. See that function for more details.\n\n    \\param\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n      :diff_index: index of ``points_to_sample`` in {0, .. ``num_to_sample``-1} to be differentiated against\n      :chol_var[num_to_sample][num_to_sample]: the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``)\n        e.g., from the cholesky factorization of ``ComputeVarianceOfPoints``\n    \\output\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n      :grad_chol[dim][num_to_sample][num_to_sample]: gradient of the inverse of the cholesky-factored\n        variance of the GP.  ``grad_chol[d][i][j]`` is actually the gradients of ``var_{i,j}`` with\n        respect to ``x_{d,k}``, the d-th dimension of the k-th entry of ``points_to_sample``, where\n        k = ``diff_index``\n  \\endrst*/\n  void ComputeGradCholeskyVarianceOfPointsPerPoint(StateType * points_to_sample_state, int diff_index,\n                                                   double const * restrict chol_var,\n                                                   double * restrict grad_chol) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Computes the gradient of the invers of the cholesky factorization of the variance of this GP with respect to the\n    ``diff_index``-th point in ``points_to_sample``.\n\n    This internal method is meant to be used by ComputeGradInverseCholeskyVarianceOfPoints() to construct the gradient wrt all\n    points of ``points_to_sample``. See that function for more details.\n\n    \\param\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n      :diff_index: index of ``points_to_sample`` in {0, .. ``num_to_sample``-1} to be differentiated against\n      :chol_var[num_to_sample][num_to_sample]: the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``)\n        e.g., from the cholesky factorization of ``ComputeVarianceOfPoints``\n    \\output\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n      :grad_chol[dim][num_to_sample][num_to_sample]: gradient of the cholesky-factored\n        variance of the GP.  ``grad_chol[d][i][j]`` is actually the gradients of ``var_{i,j}`` with\n        respect to ``x_{d,k}``, the d-th dimension of the k-th entry of ``points_to_sample``, where\n        k = ``diff_index``\n  \\endrst*/\n\n  void ComputeGradInverseCholeskyVarianceOfPointsPerPoint(StateType * points_to_sample_state, int diff_index,\n                                                          double const * restrict chol_var,\n                                                          double const * restrict var,\n                                                          double const * restrict cov,\n                                                          double const * restrict discrete_pts,\n                                                          int num_pts, bool precomputed, double const * kt,\n                                                          double * restrict grad_chol) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Computes the gradient of the invers of the cholesky factorization of the variance of this GP with respect to the\n    ``diff_index``-th point in ``points_to_sample``.\n\n    This internal method is meant to be used by ComputeGradInverseCholeskyVarianceOfPoints() to construct the gradient wrt all\n    points of ``points_to_sample``. See that function for more details.\n\n    \\param\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState (configure via PointsToSampleState::SetupState)\n      :diff_index: index of ``points_to_sample`` in {0, .. ``num_to_sample``-1} to be differentiated against\n      :chol_var[num_to_sample][num_to_sample]: the variance (matrix) of this GP at each point of ``Xs`` (``points_to_sample``)\n        e.g., from the cholesky factorization of ``ComputeVarianceOfPoints``\n    \\output\n      :points_to_sample_state[1]: ptr to a FULLY CONFIGURED PointsToSampleState; only temporary state may be mutated\n      :grad_chol[dim][num_to_sample][num_to_sample]: gradient of the cholesky-factored\n        variance of the GP.  ``grad_chol[d][i][j]`` is actually the gradients of ``var_{i,j}`` with\n        respect to ``x_{d,k}``, the d-th dimension of the k-th entry of ``points_to_sample``, where\n        k = ``diff_index``\n  \\endrst*/\n\n  void ComputeGradInverseCholeskyCovarianceOfPointsPerPoint(StateType * points_to_sample_state, int diff_index,\n                                                          double const * restrict chol_var,\n                                                          double const * restrict grad_chol_pt,\n                                                          double const * restrict chol_inv_times_cov,\n                                                          double const * restrict discrete_pts,\n                                                          int num_pts, bool precomputed, double const * kt,\n                                                          double * restrict grad_inverse_chol) const noexcept OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Recomputes (including resizing as needed) the derived quantities in this class.\n    This function should be called any time state variables are changed.\n  \\endrst*/\n  void RecomputeDerivedVariables();\n\n  // size information\n  //! spatial dimension (e.g., entries per point of ``points_sampled``)\n  int dim_;\n  //! number of points in ``points_sampled``\n  int num_sampled_;\n  //! the mean of the ``points_sampled_value_``\n  double mean_;\n\n  // state variables for prior\n  //! coordinates of already-sampled points, ``X``\n  std::vector<double> points_sampled_;\n  //! function values at points_sampled, ``y``\n  std::vector<double> points_sampled_value_;\n\n  //! derivatives index\n  std::vector<int> derivatives_;\n  //! number of derivatives observations\n  int num_derivatives_;\n\n  //! ``\\sigma_n^2``, the noise variance\n  std::vector<double> noise_variance_;\n\n  // derived variables for prior\n  //! cholesky factorization of ``K`` (i.e., ``K(X,X)`` covariance matrix (prior), includes noise variance)\n  std::vector<double> K_chol_;\n  //! ``K^-1 * y``; computed WITHOUT forming ``K^-1``\n  std::vector<double> K_inv_y_;\n\n  //! Normal PRNG for use with sampling points from GP\n  NormalGeneratorType normal_rng_;\n};\n\n/*!\\rst\n  This object holds the state needed for a GaussianProcess object characterize the distribution of function values arising from\n  sampling the GP at a list of ``points_to_sample``.  This object is required by the GaussianProcess to access functionality for\n  computing the mean, variance, and spatial gradients thereof.\n\n  The \"independent variables\" for this object are ``points_to_sample``. These points are both the \"p\" and the \"q\" in q,p-EI;\n  i.e., they are the parameters of both ongoing experiments and new predictions. Recall that in q,p-EI, the q points are\n  called ``points_to_sample`` and the p points are called ``points_being_sampled.`` Here, we need to make predictions about\n  both point sets with the GP, so we simply call the union of point sets ``points_to_sample.``\n\n  In GP computations, there is really no distinction between the \"q\" and \"p\" points from EI, ``points_to_sample`` and\n  ``points_being_sampled``, respectively. However, in EI optimization, we only need gradients of GP quantities wrt\n  ``points_to_sample``, so users should build PointsToSampleState() with ``num_derivatives = num_to_sample``.\n\n  Once constructed, this object provides the SetupState() function to update it for computations at different sets of\n  potential points to sample.\n\n  See general comments on State structs in ``gpp_common.hpp``'s header docs.\n\\endrst*/\nstruct PointsToSampleState final {\n  /*!\\rst\n    Constructs a PointsToSampleState object with new ``points_to_sample``.\n    Ensures all state variables & temporaries are properly sized.\n    Properly sets all state variables so that GaussianProcess's mean, variance (and gradients thereof) functions can be called.\n\n    .. WARNING::\n         This object's state is INVALIDATED if the gaussian_process used in construction is mutated!\n         SetupState() should be called again in such a situation.\n\n    .. WARNING::\n         Using this object to compute gradients when ``num_derivatives`` := 0 results in UNDEFINED BEHAVIOR.\n\n    \\param\n      :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n        that describes the underlying GP\n      :points_to_sample[dim][num_to_sample]: points at which to compute GP-derived quantities (mean, variance, etc.)\n      :num_to_sample: number of points being sampled concurrently\n      :num_derivatives: configure this object to compute ``num_derivatives`` derivative terms wrt\n        points_to_sample[:][0:num_derivatives]; 0 means no gradient computation will be performed.\n  \\endrst*/\n  PointsToSampleState(const GaussianProcess& gaussian_process,\n                      double const * restrict points_to_sample_in,\n                      int num_to_sample_in, int const * restrict gradients_in,\n                      int num_gradients_in, int num_derivatives_in,\n                      bool precomputed_in = true, bool precomputed_grad_K_inv_times_K_star_in = false) OL_NONNULL_POINTERS;\n\n  PointsToSampleState(PointsToSampleState&& other);\n\n  /*!\\rst\n    Configures this object with new ``points_to_sample``.\n    Ensures all state variables & temporaries are properly sized.\n    Properly sets all state variables so that GaussianProcess's mean, variance (and gradients thereof) functions can be called.\n\n    .. WARNING::\n         This object's state is INVALIDATED if the gaussian_process used in SetupState is mutated!\n         SetupState() should be called again in such a situation.\n\n    .. WARNING::\n         Using this object to compute gradients when ``num_derivatives`` := 0 results in UNDEFINED BEHAVIOR.\n\n    \\param\n      :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n        that describes the underlying GP\n      :points_to_sample[dim][num_to_sample]: points at which to compute GP-derived quantities (mean, variance, etc.)\n      :num_to_sample: number of points being sampled concurrently\n      :num_derivatives: configure this object to compute ``num_derivatives`` derivative terms wrt\n        points_to_sample[:][0:num_derivatives]; 0 means no gradient computation will be performed.\n  \\endrst*/\n  void SetupState(const GaussianProcess& gaussian_process, double const * restrict points_to_sample_in,\n                  int num_to_sample_in, int num_gradients_in, int num_derivatives_in,\n                  bool precomputed_in = true, bool precomputed_grad_K_inv_times_K_star_in = false) OL_NONNULL_POINTERS;\n\n  //! pointer to gaussian process used in EI computations\n  const GaussianProcess * gaussian_process;\n\n  //! spatial dimension (e.g., entries per point of ``points_sampled``)\n  const int dim;\n  //! number of points alerady sampled\n  int num_sampled;\n  //! number of points currently being sampled\n  int num_to_sample;\n\n  //! this object can compute ``num_derivatives`` derivative terms wrt\n  //! points_to_sample[:][0:num_derivatives]; 0 means no gradient computation will be performed\n  int num_derivatives;\n\n  //! precompute K_inv_K_star\n  bool precomputed;\n  //!precompute grad_K_inv_K_star\n  bool precomputed_grad_K_inv_times_K_star;\n\n  // gradients index\n  std::vector<int> gradients;\n  // the number of gradients observations\n  int num_gradients_to_sample;\n\n  int num_gradients_sampled;\n\n  // state variables for predictive component\n  //! points to make predictions about, ``Xs``\n  std::vector<double> points_to_sample;\n\n  // derived variables for predictive component; these are all *temporary* quantities\n  //! the \"mixed\" covariance matrix: ``Ks, Ks_{ij}, K(X,Xs) = covariance(X_i, Xs_j)``, covariance matrix between training and test inputs (``num_sampled x num_to_sample``)\n  std::vector<double> K_star;\n  //! the gradient of mixed covariance matrix, ``Ks``, wrt ``Xs``, dimension: dim*num_sampled*num_derivatives\n  std::vector<double> grad_K_star;\n  //! the gradient of K_inv_times_K_star wrt ``Xs``, dimension: dim*num_sampled*derivatives\n  std::vector<double> grad_K_inv_times_K_star;\n  //! the variance matrix (output from the GP)\n  std::vector<double> V;\n  //! ``K^{-1} Ks`` (computed without taking an inverse)\n  std::vector<double> K_inv_times_K_star;\n  //! the gradient of covariance(x_1, x_2) wrt x_1\n  // std::vector<double> grad_cov;\n\n  OL_DISALLOW_DEFAULT_AND_COPY_AND_ASSIGN(PointsToSampleState);\n};\n\nstruct ExpectedImprovementState;\nstruct OnePotentialSampleExpectedImprovementState;\n\n/*!\\rst\n  A class to encapsulate the computation of expected improvement and its spatial gradient. This class handles the\n  general EI computation case using monte carlo integration; it can support q,p-EI optimization. It is designed to work\n  with any GaussianProcess.  Additionally, this class has no state and within the context of EI optimization, it is\n  meant to be accessed by const reference only.\n\n  The random numbers needed for EI computation will be passed as parameters instead of contained as members to make\n  multithreading more straightforward.\n\\endrst*/\nclass ExpectedImprovementEvaluator final {\n public:\n  using StateType = ExpectedImprovementState;\n  /*!\\rst\n    Constructs a ExpectedImprovementEvaluator object.  All inputs are required; no default constructor nor copy/assignment are allowed.\n\n    \\param\n      :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n        that describes the underlying GP\n      :num_mc_iterations: number of monte carlo iterations\n      :best_so_far: best (minimum) objective function value (in ``points_sampled_value``)\n  \\endrst*/\n  ExpectedImprovementEvaluator(const GaussianProcess& gaussian_process_in, int num_mc_iterations, double best_so_far);\n  ExpectedImprovementEvaluator(ExpectedImprovementEvaluator&& other);\n\n  int dim() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return dim_;\n  }\n\n  int num_mc_iterations() noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return num_mc_iterations_;\n  }\n\n  double best_so_far() noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return best_so_far_;\n  }\n\n  const GaussianProcess * gaussian_process() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return gaussian_process_;\n  }\n\n  /*!\\rst\n    Wrapper for ComputeExpectedImprovement(); see that function for details.\n  \\endrst*/\n  double ComputeObjectiveFunction(StateType * ei_state) const OL_NONNULL_POINTERS OL_WARN_UNUSED_RESULT {\n    return ComputeExpectedImprovement(ei_state);\n  }\n\n  /*!\\rst\n    Wrapper for ComputeGradExpectedImprovement(); see that function for details.\n  \\endrst*/\n  void ComputeGradObjectiveFunction(StateType * ei_state, double * restrict grad_EI) const OL_NONNULL_POINTERS {\n    ComputeGradExpectedImprovement(ei_state, grad_EI);\n  }\n\n  /*!\\rst\n    Computes the expected improvement ``EI(Xs) = E_n[[f^*_n(X) - min(f(Xs_1),...,f(Xs_m))]^+]``, where ``Xs``\n    are potential points to sample (union of ``points_to_sample`` and ``points_being_sampled``) and ``X`` are\n    already sampled points.  The ``^+`` indicates that the expression in the expectation evaluates to 0 if it\n    is negative.  ``f^*(X)`` is the MINIMUM over all known function evaluations (``points_sampled_value``),\n    whereas ``f(Xs)`` are *GP-predicted* function evaluations.\n\n    ``points_to_sample`` is the \"q\" and ``points_being_sampled`` is the \"p\" in q,p-EI.\n\n    In words, we are computing the expected improvement (over the current ``best_so_far``, best known\n    objective function value) that would result from sampling (aka running new experiments) at\n    ``points_to_sample`` with ``points_being_sampled`` concurrent/ongoing experiments.\n\n    In general, the EI expression is complex and difficult to evaluate; hence we use Monte-Carlo simulation to approximate it.\n    When faster (e.g., analytic) techniques are available, we will prefer them.\n\n    The idea of the MC approach is to repeatedly sample at the union of ``points_to_sample`` and\n    ``points_being_sampled``. This is analogous to gaussian_process_interface.sample_point_from_gp,\n    but we sample ``num_union`` points at once:\n\n    ``y = \\mu + Lw``\n\n    where ``\\mu`` is the GP-mean, ``L`` is the ``chol_factor(GP-variance)`` and ``w`` is a vector\n    of ``num_union`` draws from N(0, 1). Then:\n\n    ``improvement_per_step = max(max(best_so_far - y), 0.0)``\n\n    Observe that the inner ``max`` means only the smallest component of ``y`` contributes in each iteration.\n    We compute the improvement over many random draws and average.\n\n    .. Note:: These comments were copied into ExpectedImprovementInterface.compute_expected_improvement() in interfaces/expected_improvement_interface.py.\n\n    \\param\n      :ei_state[1]: properly configured state object\n    \\output\n      :ei_state[1]: state with temporary storage modified; ``normal_rng`` modified\n    \\return\n      the expected improvement from sampling ``points_to_sample`` with ``points_being_sampled`` concurrent experiments\n  \\endrst*/\n  double ComputeExpectedImprovement(StateType * ei_state) const OL_NONNULL_POINTERS OL_WARN_UNUSED_RESULT;\n\n  /*!\\rst\n    Computes the (partial) derivatives of the expected improvement with respect to each point of ``points_to_sample``.\n    As with ComputeExpectedImprovement(), this computation accounts for the effect of ``points_being_sampled``\n    concurrent experiments.\n\n    ``points_to_sample`` is the \"q\" and ``points_being_sampled`` is the \"p\" in q,p-EI..\n\n    In general, the expressions for gradients of EI are complex and difficult to evaluate; hence we use\n    Monte-Carlo simulation to approximate it. When faster (e.g., analytic) techniques are available, we will prefer them.\n\n    The MC computation of grad EI is similar to the computation of EI (decsribed in\n    compute_expected_improvement). We differentiate ``y = \\mu + Lw`` wrt ``points_to_sample``;\n    only terms from the gradient of ``\\mu`` and ``L`` contribute. In EI, we computed:\n\n    ``improvement_per_step = max(max(best_so_far - y), 0.0)``\n\n    and noted that only the smallest component of ``y`` may contribute (if it is > 0.0).\n    Call this index ``winner``. Thus in computing grad EI, we only add gradient terms\n    that are attributable to the ``winner``-th component of ``y``.\n\n    .. Note:: These comments were copied into ExpectedImprovementInterface.compute_expected_improvement() in interfaces/expected_improvement_interface.py.\n\n    \\param\n      :ei_state[1]: properly configured state object\n    \\output\n      :ei_state[1]: state with temporary storage modified; ``normal_rng`` modified\n      :grad_EI[dim][num_to_sample]: gradient of EI, ``\\pderiv{EI(Xq \\cup Xp)}{Xq_{d,i}}`` where ``Xq`` is ``points_to_sample``\n          and ``Xp`` is ``points_being_sampled`` (grad EI from sampling ``points_to_sample`` with\n          ``points_being_sampled`` concurrent experiments wrt each dimension of the points in ``points_to_sample``)\n  \\endrst*/\n  void ComputeGradExpectedImprovement(StateType * ei_state, double * restrict grad_EI) const OL_NONNULL_POINTERS;\n\n  OL_DISALLOW_DEFAULT_AND_COPY_AND_ASSIGN(ExpectedImprovementEvaluator);\n\n private:\n  //! spatial dimension (e.g., entries per point of points_sampled)\n  const int dim_;\n  //! number of monte carlo iterations\n  int num_mc_iterations_;\n  //! best (minimum) objective function value (in points_sampled_value)\n  double best_so_far_;\n  //! pointer to gaussian process used in EI computations\n  const GaussianProcess * gaussian_process_;\n};\n\n/*!\\rst\n  State object for ExpectedImprovementEvaluator.  This tracks the points being sampled in concurrent experiments\n  (``points_being_sampled``) ALONG with the points currently being evaluated via expected improvement for future experiments\n  (called ``points_to_sample``); these are the p and q of q,p-EI, respectively.  ``points_to_sample`` joined with\n  ``points_being_sampled`` is stored in ``union_of_points`` in that order.\n\n  This struct also tracks the state of the GaussianProcess that underlies the expected improvement computation: the GP state\n  is built to handle the initial ``union_of_points``, and subsequent updates to ``points_to_sample`` in this object also update\n  the GP state.\n\n  This struct also holds a pointer to a random number generator needed for Monte Carlo integrated EI computations.\n\n  .. WARNING::\n       Users MUST guarantee that multiple state objects DO NOT point to the same RNG (in a multithreaded env).\n\n  See general comments on State structs in ``gpp_common.hpp``'s header docs.\n\\endrst*/\nstruct ExpectedImprovementState final {\n  using EvaluatorType = ExpectedImprovementEvaluator;\n\n  /*!\\rst\n    Constructs an ExpectedImprovementState object with a specified source of randomness for the purpose of computing EI\n    (and its gradient) over the specified set of points to sample.\n    This establishes properly sized/initialized temporaries for EI computation, including dependent state from the\n    associated Gaussian Process (which arrives as part of the ei_evaluator).\n\n    .. WARNING:: This object is invalidated if the associated ei_evaluator is mutated.  SetupState() should be called to reset.\n\n    .. WARNING::\n         Using this object to compute gradients when ``configure_for_gradients`` := false results in UNDEFINED BEHAVIOR.\n\n    \\param\n      :ei_evaluator: expected improvement evaluator object that specifies the parameters & GP for EI evaluation\n      :points_to_sample[dim][num_to_sample]: points at which to evaluate EI and/or its gradient to check their value in future experiments (i.e., test points for GP predictions)\n      :points_being_sampled[dim][num_being_sampled]: points being sampled in concurrent experiments\n      :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n      :num_being_sampled: number of points being sampled in concurrent experiments (i.e., the \"p\" in q,p-EI)\n      :configure_for_gradients: true if this object will be used to compute gradients, false otherwise\n      :normal_rng[1]: pointer to a properly initialized\\* NormalRNG object\n\n    .. NOTE::\n         \\* The NormalRNG object must already be seeded.  If multithreaded computation is used for EI, then every state object\n         must have a different NormalRNG (different seeds, not just different objects).\n  \\endrst*/\n  ExpectedImprovementState(const EvaluatorType& ei_evaluator, double const * restrict points_to_sample,\n                           double const * restrict points_being_sampled, int num_to_sample_in,\n                           int num_being_sampled_in, bool configure_for_gradients, NormalRNGInterface * normal_rng_in);\n\n  ExpectedImprovementState(ExpectedImprovementState&& other);\n\n  /*!\\rst\n    Create a vector with the union of points_to_sample and points_being_sampled (the latter is appended to the former).\n\n    Note the l-value return. Assigning the return to a std::vector<double> or passing it as an argument to the ctor\n    will result in copy-elision or move semantics; no copying/performance loss.\n\n    \\param:\n      :points_to_sample[dim][num_to_sample]: points at which to evaluate EI and/or its gradient to check their value in future experiments (i.e., test points for GP predictions)\n      :points_being_sampled[dim][num_being_sampled]: points being sampled in concurrent experiments\n      :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n      :num_being_sampled: number of points being sampled in concurrent experiments (i.e., the \"p\" in q,p-EI)\n      :dim: the number of spatial dimensions of each point array\n    \\return\n      std::vector<double> with the union of the input arrays: points_being_sampled is *appended* to points_to_sample\n  \\endrst*/\n  static std::vector<double> BuildUnionOfPoints(double const * restrict points_to_sample,\n                                                double const * restrict points_being_sampled,\n                                                int num_to_sample, int num_being_sampled,\n                                                int dim) noexcept OL_WARN_UNUSED_RESULT {\n    std::vector<double> union_of_points(dim*(num_to_sample + num_being_sampled));\n    std::copy(points_to_sample, points_to_sample + dim*num_to_sample, union_of_points.data());\n    std::copy(points_being_sampled, points_being_sampled + dim*num_being_sampled,\n              union_of_points.data() + dim*num_to_sample);\n    return union_of_points;\n  }\n\n  int GetProblemSize() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return dim*num_to_sample;\n  }\n\n  /*!\\rst\n    Get the ``points_to_sample``: potential future samples whose EI (and/or gradients) are being evaluated\n\n    \\output\n      :points_to_sample[dim][num_to_sample]: potential future samples whose EI (and/or gradients) are being evaluated\n  \\endrst*/\n  void GetCurrentPoint(double * restrict points_to_sample) const noexcept OL_NONNULL_POINTERS {\n    std::copy(union_of_points.data(), union_of_points.data() + num_to_sample*dim, points_to_sample);\n  }\n\n  /*!\\rst\n    Change the potential samples whose EI (and/or gradient) are being evaluated.\n    Update the state's derived quantities to be consistent with the new points.\n\n    \\param\n      :ei_evaluator: expected improvement evaluator object that specifies the parameters & GP for EI evaluation\n      :points_to_sample[dim][num_to_sample]: potential future samples whose EI (and/or gradients) are being evaluated\n  \\endrst*/\n  void SetCurrentPoint(const EvaluatorType& ei_evaluator,\n                       double const * restrict points_to_sample) OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Configures this state object with new ``points_to_sample``, the location of the potential samples whose EI is to be evaluated.\n    Ensures all state variables & temporaries are properly sized.\n    Properly sets all dependent state variables (e.g., GaussianProcess's state) for EI evaluation.\n\n    .. WARNING::\n         This object's state is INVALIDATED if the ``ei_evaluator`` (including the GaussianProcess it depends on) used in\n         SetupState is mutated! SetupState() should be called again in such a situation.\n\n    \\param\n      :ei_evaluator: expected improvement evaluator object that specifies the parameters & GP for EI evaluation\n      :points_to_sample[dim][num_to_sample]: potential future samples whose EI (and/or gradients) are being evaluated\n  \\endrst*/\n  void SetupState(const EvaluatorType& ei_evaluator, double const * restrict points_to_sample);\n\n  // size information\n  //! spatial dimension (e.g., entries per point of ``points_sampled``)\n  const int dim;\n  //! number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n  const int num_to_sample;\n  //! number of points being sampled concurrently (i.e., the \"p\" in q,p-EI)\n  const int num_being_sampled;\n  //! number of derivative terms desired (usually 0 for no derivatives or num_to_sample)\n  const int num_derivatives;\n  //! number of points in union_of_points: num_to_sample + num_being_sampled\n  const int num_union;\n\n  //! points currently being sampled; this is the union of the points represented by \"q\" and \"p\" in q,p-EI\n  //! ``points_to_sample`` is stored first in memory, immediately followed by ``points_being_sampled``\n  std::vector<double> union_of_points;\n\n  //! gaussian process state\n  GaussianProcess::StateType points_to_sample_state;\n\n  //! random number generator\n  NormalRNGInterface * normal_rng;\n\n  // temporary storage: preallocated space used by ExpectedImprovementEvaluator's member functions\n  //! the mean of the GP evaluated at union_of_points\n  std::vector<double> to_sample_mean;\n  //! the gradient of the GP mean evaluated at union_of_points, wrt union_of_points[0:num_to_sample]\n  std::vector<double> grad_mu;\n  //! the cholesky (``LL^T``) factorization of the GP variance evaluated at union_of_points\n  std::vector<double> cholesky_to_sample_var;\n  //! the gradient of the cholesky (``LL^T``) factorization of the GP variance evaluated at union_of_points wrt union_of_points[0:num_to_sample]\n  std::vector<double> grad_chol_decomp;\n\n  //! improvement (per mc iteration) evaluated at each of union_of_points\n  std::vector<double> EI_this_step_from_var;\n  //! tracks the aggregate grad EI from all mc iterations\n  std::vector<double> aggregate;\n  //! normal rng draws\n  std::vector<double> normals;\n\n  OL_DISALLOW_DEFAULT_AND_COPY_AND_ASSIGN(ExpectedImprovementState);\n};\n\n/*!\\rst\n  This is a specialization of the ExpectedImprovementEvaluator class for when the number of potential samples is 1; i.e.,\n  ``num_to_sample == 1`` and the number of concurrent samples is 0; i.e. ``num_being_sampled == 0``.\n  In other words, this class only supports the computation of 1,0-EI.  In this case, we have analytic formulas\n  for computing EI and its gradient.\n\n  Thus this class does not perform any explicit numerical integration, nor do its EI functions require access to a\n  random number generator.\n\n  This class's methods have some parameters that are unused or redundant.  This is so that the interface matches that of\n  the more general ExpectedImprovementEvaluator.\n\n  For other details, see ExpectedImprovementEvaluator for more complete description of what EI is and the outputs of\n  EI and grad EI computations.\n\\endrst*/\nclass OnePotentialSampleExpectedImprovementEvaluator final {\n public:\n  using StateType = OnePotentialSampleExpectedImprovementState;\n\n  //! Minimum allowed variance value in the \"1D\" analytic EI computation.\n  //! Values that are too small result in problems b/c we may compute ``std_dev/var`` (which is enormous\n  //! if ``std_dev = 1.0e-150`` and ``var = 1.0e-300``) since this only arises when we fail to compute ``std_dev = var = 0.0``.\n  //! Note: this is only relevant if noise = 0.0; this minimum will not affect EI computation with noise since this value\n  //! is below the smallest amount of noise users can meaningfully add.\n  //! This is the smallest possible value that prevents the denominator (best_so_far - mean) / sqrt(variance)\n  //! from being 0. 1D analytic EI is simple and no other robustness considerations are needed.\n  static constexpr double kMinimumVarianceEI = std::numeric_limits<double>::min();\n\n  //! Minimum allowed variance value in the \"1D\" analytic grad EI computation.\n  //! See kMinimumVarianceEI for more details.\n  //! This value was chosen so its sqrt would be a little larger than GaussianProcess::kMinimumStdDev (by ~12x).\n  //! The 150.0 was determined by numerical experiment with the setup in EIOnePotentialSampleEdgeCasesTest\n  //! in order to find a setting that would be robust (no 0/0) while introducing minimal error.\n  static constexpr double kMinimumVarianceGradEI = 150.0*Square(GaussianProcess::kMinimumStdDev);\n\n  /*!\\rst\n    Constructs a OnePotentialSampleExpectedImprovementEvaluator object.  All inputs are required; no default constructor nor copy/assignment are allowed.\n\n    \\param\n      :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n        that describes the underlying GP\n      :best_so_far: best (minimum) objective function value (in ``points_sampled_value``)\n  \\endrst*/\n  OnePotentialSampleExpectedImprovementEvaluator(const GaussianProcess& gaussian_process_in, double best_so_far);\n  OnePotentialSampleExpectedImprovementEvaluator(OnePotentialSampleExpectedImprovementEvaluator&& other);\n\n  int dim() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return dim_;\n  }\n\n  double best_so_far() noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return best_so_far_;\n  }\n\n  const GaussianProcess * gaussian_process() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return gaussian_process_;\n  }\n\n  /*!\\rst\n    Wrapper for ComputeExpectedImprovement(); see that function for details.\n  \\endrst*/\n  double ComputeObjectiveFunction(StateType * ei_state) const OL_NONNULL_POINTERS OL_WARN_UNUSED_RESULT {\n    return ComputeExpectedImprovement(ei_state);\n  }\n\n  /*!\\rst\n    Wrapper for ComputeGradExpectedImprovement(); see that function for details.\n  \\endrst*/\n  void ComputeGradObjectiveFunction(StateType * ei_state, double * restrict grad_EI) const OL_NONNULL_POINTERS {\n    ComputeGradExpectedImprovement(ei_state, grad_EI);\n  }\n\n  /*!\\rst\n    Computes the expected improvement ``EI(Xs) = E_n[[f^*_n(X) - min(f(Xs_1),...,f(Xs_m))]^+]``\n\n    Uses analytic formulas to evaluate the expected improvement.\n\n    \\param\n      :ei_state[1]: properly configured state object\n    \\output\n      :ei_state[1]: state with temporary storage modified\n    \\return\n      the expected improvement from sampling ``point_to_sample``\n  \\endrst*/\n  double ComputeExpectedImprovement(StateType * ei_state) const;\n\n  /*!\\rst\n    Computes the (partial) derivatives of the expected improvement with respect to the point to sample.\n\n    Uses analytic formulas to evaluate the spatial gradient of the expected improvement.\n\n    \\param\n      :ei_state[1]: properly configured state object\n    \\output\n      :ei_state[1]: state with temporary storage modified\n      :grad_EI[dim]: gradient of EI, ``\\pderiv{EI(x)}{x_d}``, where ``x`` is ``points_to_sample``\n  \\endrst*/\n  void ComputeGradExpectedImprovement(StateType * ei_state, double * restrict grad_EI) const;\n\n  OL_DISALLOW_DEFAULT_AND_COPY_AND_ASSIGN(OnePotentialSampleExpectedImprovementEvaluator);\n\n private:\n  //! spatial dimension (e.g., entries per point of ``points_sampled``)\n  const int dim_;\n  //! best (minimum) objective function value (in ``points_sampled_value``)\n  double best_so_far_;\n\n  //! normal distribution object\n  const boost::math::normal_distribution<double> normal_;\n  //! pointer to gaussian process used in EI computations\n  const GaussianProcess * gaussian_process_;\n};\n\n/*!\\rst\n  State object for OnePotentialSampleExpectedImprovementEvaluator.  This tracks the *ONE* ``point_to_sample``\n  being evaluated via expected improvement.\n\n  This is just a special case of ExpectedImprovementState; see those class docs for more details.\n  See general comments on State structs in ``gpp_common.hpp``'s header docs.\n\\endrst*/\nstruct OnePotentialSampleExpectedImprovementState final {\n  using EvaluatorType = OnePotentialSampleExpectedImprovementEvaluator;\n\n  /*!\\rst\n    Constructs an OnePotentialSampleExpectedImprovementState object for the purpose of computing EI\n    (and its gradient) over the specified point to sample.\n    This establishes properly sized/initialized temporaries for EI computation, including dependent state from the\n    associated Gaussian Process (which arrives as part of the ``ei_evaluator``).\n\n    .. WARNING::\n         This object is invalidated if the associated ei_evaluator is mutated.  SetupState() should be called to reset.\n\n    .. WARNING::\n         Using this object to compute gradients when ``configure_for_gradients`` := false results in UNDEFINED BEHAVIOR.\n\n    \\param\n      :ei_evaluator: expected improvement evaluator object that specifies the parameters & GP for EI evaluation\n      :point_to_sample[dim]: point at which to evaluate EI and/or its gradient to check their value in future experiments (i.e., test point for GP predictions)\n      :configure_for_gradients: true if this object will be used to compute gradients, false otherwise\n  \\endrst*/\n  OnePotentialSampleExpectedImprovementState(const EvaluatorType& ei_evaluator,\n                                             double const * restrict point_to_sample_in, bool configure_for_gradients);\n\n  /*!\\rst\n    Constructor wrapper to match the signature of the ctor for ExpectedImprovementState().\n  \\endrst*/\n  OnePotentialSampleExpectedImprovementState(const EvaluatorType& ei_evaluator,\n                                             double const * restrict points_to_sample,\n                                             double const * restrict OL_UNUSED(points_being_sampled),\n                                             int OL_UNUSED(num_to_sample_in), int OL_UNUSED(num_being_sampled_in),\n                                             bool configure_for_gradients, NormalRNGInterface * OL_UNUSED(normal_rng_in));\n\n  OnePotentialSampleExpectedImprovementState(OnePotentialSampleExpectedImprovementState&& other);\n\n  int GetProblemSize() const noexcept OL_PURE_FUNCTION OL_WARN_UNUSED_RESULT {\n    return dim;\n  }\n\n  /*!\\rst\n    Get ``point_to_sample``: the potential future sample whose EI (and/or gradients) is being evaluated\n\n    \\output\n      :point_to_sample[dim]: potential sample whose EI is being evaluted\n  \\endrst*/\n  void GetCurrentPoint(double * restrict point_to_sample_out) const noexcept OL_NONNULL_POINTERS {\n    std::copy(point_to_sample.begin(), point_to_sample.end(), point_to_sample_out);\n  }\n\n  /*!\\rst\n    Change the potential sample whose EI (and/or gradient) is being evaluated.\n    Update the state's derived quantities to be consistent with the new point.\n\n    \\param\n      :ei_evaluator: expected improvement evaluator object that specifies the parameters & GP for EI evaluation\n      :point_to_sample[dim]: potential future sample whose EI (and/or gradients) is being evaluated\n  \\endrst*/\n  void SetCurrentPoint(const EvaluatorType& ei_evaluator,\n                       double const * restrict point_to_sample_in) OL_NONNULL_POINTERS;\n\n  /*!\\rst\n    Configures this state object with a new ``point_to_sample``, the location of the potential sample whose EI is to be evaluated.\n    Ensures all state variables & temporaries are properly sized.\n    Properly sets all dependent state variables (e.g., GaussianProcess's state) for EI evaluation.\n\n    .. WARNING::\n         This object's state is INVALIDATED if the ei_evaluator (including the GaussianProcess it depends on) used in\n         SetupState is mutated! SetupState() should be called again in such a situation.\n\n    \\param\n      :ei_evaluator: expected improvement evaluator object that specifies the parameters & GP for EI evaluation\n      :point_to_sample[dim]: potential future sample whose EI (and/or gradients) is being evaluated\n  \\endrst*/\n  void SetupState(const EvaluatorType& ei_evaluator,\n                  double const * restrict point_to_sample_in) OL_NONNULL_POINTERS;\n\n  // size information\n  //! spatial dimension (e.g., entries per point of ``points_sampled``)\n  const int dim;\n  //! number of points to sample (i.e., the \"q\" in q,p-EI); MUST be 1\n  const int num_to_sample = 1;\n  //! number of derivative terms desired (usually 0 for no derivatives or num_to_sample)\n  const int num_derivatives;\n\n  //! point at which to evaluate EI and/or its gradient (e.g., to check its value in future experiments)\n  std::vector<double> point_to_sample;\n\n  //! gaussian process state\n  GaussianProcess::StateType points_to_sample_state;\n\n  // temporary storage: preallocated space used by OnePotentialSampleExpectedImprovementEvaluator's member functions\n  //! the gradient of the GP mean evaluated at point_to_sample, wrt point_to_sample\n  std::vector<double> grad_mu;\n  //! the gradient of the sqrt of the GP variance evaluated at point_to_sample wrt point_to_sample\n  std::vector<double> grad_chol_decomp;\n\n  OL_DISALLOW_DEFAULT_AND_COPY_AND_ASSIGN(OnePotentialSampleExpectedImprovementState);\n};\n\n/*!\\rst\n  Set up vector of OnePotentialSampleExpectedImprovementEvaluator::StateType.\n\n  This is a utility function just for reducing code duplication.\n\n  dim is the spatial dimension, ``ei_evaluator.dim()``\n\n  \\param\n    :ei_evaluator: evaluator object associated w/the state objects being constructed\n    :starting_point[dim]: initial point to load into state (must be a valid point for the problem)\n    :max_num_threads: maximum number of threads for use by OpenMP (generally should be <= # cores)\n    :configure_for_gradients: true if these state objects will be used to compute gradients, false otherwise\n    :state_vector[arbitrary]: vector of state objects, arbitrary size (usually 0)\n  \\output\n    :state_vector[max_num_threads]: vector of states containing ``max_num_threads`` properly initialized state objects\n\\endrst*/\ninline OL_NONNULL_POINTERS void SetupExpectedImprovementState(\n    const OnePotentialSampleExpectedImprovementEvaluator& ei_evaluator,\n    double const * restrict starting_point,\n    int max_num_threads,\n    bool configure_for_gradients,\n    std::vector<typename OnePotentialSampleExpectedImprovementEvaluator::StateType> * state_vector) {\n  state_vector->reserve(max_num_threads);\n  for (int i = 0; i < max_num_threads; ++i) {\n    state_vector->emplace_back(ei_evaluator, starting_point, configure_for_gradients);\n  }\n}\n\n/*!\\rst\n  Set up vector of ExpectedImprovementEvaluator::StateType.\n\n  This is a utility function just for reducing code duplication.\n\n  \\param\n    :ei_evaluator: evaluator object associated w/the state objects being constructed\n    :points_to_sample[dim][num_to_sample]: initial points to load into state (must be a valid point for the problem);\n      i.e., points at which to evaluate EI and/or its gradient\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrently experiments\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :max_num_threads: maximum number of threads for use by OpenMP (generally should be <= # cores)\n    :configure_for_gradients: true if these state objects will be used to compute gradients, false otherwise\n    :state_vector[arbitrary]: vector of state objects, arbitrary size (usually 0)\n    :normal_rng[max_num_threads]: a vector of NormalRNG objects that provide the (pesudo)random source for MC integration\n  \\output\n    :state_vector[max_num_threads]: vector of states containing ``max_num_threads`` properly initialized state objects\n\\endrst*/\ninline OL_NONNULL_POINTERS void SetupExpectedImprovementState(\n    const ExpectedImprovementEvaluator& ei_evaluator,\n    double const * restrict points_to_sample,\n    double const * restrict points_being_sampled,\n    int num_to_sample,\n    int num_being_sampled,\n    int max_num_threads,\n    bool configure_for_gradients,\n    NormalRNG * normal_rng,\n    std::vector<typename ExpectedImprovementEvaluator::StateType> * state_vector) {\n  state_vector->reserve(max_num_threads);\n  for (int i = 0; i < max_num_threads; ++i) {\n    state_vector->emplace_back(ei_evaluator, points_to_sample, points_being_sampled, num_to_sample,\n                               num_being_sampled, configure_for_gradients, normal_rng + i);\n  }\n}\n\n/*!\\rst\n  Solve the q,p-EI problem (see ComputeOptimalPointsToSample and/or header docs) by optimizing the Expected Improvement.\n  Optimization is done using restarted Gradient Descent, via GradientDescentOptimizer<...>::Optimize() from\n  ``gpp_optimization.hpp``.  Please see that file for details on gradient descent and see gpp_optimizer_parameters.hpp\n  for the meanings of the GradientDescentParameters.\n\n  This function is just a simple wrapper that sets up the Evaluator's State and calls a general template for restarted GD.\n\n  This function does not perform multistarting or employ any other robustness-boosting heuristcs; it only\n  converges if the ``initial_guess`` is close to the solution. In general,\n  ComputeOptimalPointsToSample() (see below) is preferred. This function is meant for:\n\n  1. easier testing;\n  2. if you really know what you're doing.\n\n  Solution is guaranteed to lie within the region specified by ``domain``; note that this may not be a\n  true optima (i.e., the gradient may be substantially nonzero).\n\n  \\param\n    :ei_evaluator: reference to object that can compute ExpectedImprovement and its spatial gradient\n    :optimizer_parameters: GradientDescentParameters object that describes the parameters controlling EI optimization\n      (e.g., number of iterations, tolerances, learning rate)\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :initial_guess[dim][num_to_sample]: initial guess for gradient descent\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-EI)\n    :normal_rng[1]: a NormalRNG object that provides the (pesudo)random source for MC integration\n  \\output\n    :normal_rng[1]: NormalRNG object will have its state changed due to random draws\n    :next_point[dim][num_to_sample]: points yielding the best EI according to gradient descent\n\\endrst*/\ntemplate <typename ExpectedImprovementEvaluator, typename DomainType>\nvoid RestartedGradientDescentEIOptimization(const ExpectedImprovementEvaluator& ei_evaluator,\n                                            const GradientDescentParameters& optimizer_parameters,\n                                            const DomainType& domain, double const * restrict initial_guess,\n                                            double const * restrict points_being_sampled, int num_to_sample,\n                                            int num_being_sampled, NormalRNG * normal_rng,\n                                            double * restrict next_point) {\n  if (unlikely(optimizer_parameters.max_num_restarts <= 0)) {\n    return;\n  }\n  int dim = ei_evaluator.dim();\n\n  OL_VERBOSE_PRINTF(\"Expected Improvement Optimization via %s:\\n\", OL_CURRENT_FUNCTION_NAME);\n\n  bool configure_for_gradients = true;\n  typename ExpectedImprovementEvaluator::StateType ei_state(ei_evaluator, initial_guess,\n                                                            points_being_sampled, num_to_sample,\n                                                            num_being_sampled, configure_for_gradients,\n                                                            normal_rng);\n\n  using RepeatedDomain = RepeatedDomain<DomainType>;\n  RepeatedDomain repeated_domain(domain, num_to_sample);\n  GradientDescentOptimizer<ExpectedImprovementEvaluator, RepeatedDomain> gd_opt;\n  gd_opt.Optimize(ei_evaluator, optimizer_parameters, repeated_domain, &ei_state);\n  ei_state.GetCurrentPoint(next_point);\n}\n\n/*!\\rst\n  Perform multistart gradient descent (MGD) to solve the q,p-EI problem (see ComputeOptimalPointsToSample and/or\n  header docs).  Starts a GD run from each point in ``start_point_set``.  The point corresponding to the\n  optimal EI\\* is stored in ``best_next_point``.\n\n  \\* Multistarting is heuristic for global optimization. EI is not convex so this method may not find the true optimum.\n\n  This function wraps MultistartOptimizer<>::MultistartOptimize() (see ``gpp_optimization.hpp``), which provides the multistarting\n  component. Optimization is done using restarted Gradient Descent, via GradientDescentOptimizer<...>::Optimize() from\n  ``gpp_optimization.hpp``. Please see that file for details on gradient descent and see ``gpp_optimizer_parameters.hpp``\n  for the meanings of the GradientDescentParameters.\n\n  This function (or its wrappers, e.g., ComputeOptimalPointsToSampleWithRandomStarts) are the primary entry-points for\n  gradient descent based EI optimization in the ``optimal_learning`` library.\n\n  Users may prefer to call ComputeOptimalPointsToSample(), which applies other heuristics to improve robustness.\n\n  Currently, during optimization, we recommend that the coordinates of the initial guesses not differ from the\n  coordinates of the optima by more than about 1 order of magnitude. This is a very (VERY!) rough guideline for\n  sizing the domain and num_multistarts; i.e., be wary of sets of initial guesses that cover the space too sparsely.\n\n  Solution is guaranteed to lie within the region specified by ``domain``; note that this may not be a\n  true optima (i.e., the gradient may be substantially nonzero).\n\n  .. WARNING::\n       This function fails ungracefully if NO improvement can be found!  In that case,\n       ``best_next_point`` will always be the first point in ``start_point_set``.\n       ``found_flag`` will indicate whether this occured.\n\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :optimizer_parameters: GradientDescentParameters object that describes the parameters controlling EI optimization\n      (e.g., number of iterations, tolerances, learning rate)\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_dynamic), chunk_size (0).\n    :start_point_set[dim][num_to_sample][num_multistarts]: set of initial guesses for MGD (one block of num_to_sample points per multistart)\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :num_multistarts: number of points in set of initial guesses\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-EI)\n    :best_so_far: value of the best sample so far (must be ``min(points_sampled_value)``)\n    :max_int_steps: maximum number of MC iterations\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n  \\output\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :found_flag[1]: true if ``best_next_point`` corresponds to a nonzero EI\n    :best_next_point[dim][num_to_sample]: points yielding the best EI according to MGD\n\\endrst*/\ntemplate <typename DomainType>\nOL_NONNULL_POINTERS void ComputeOptimalPointsToSampleViaMultistartGradientDescent(\n    const GaussianProcess& gaussian_process,\n    const GradientDescentParameters& optimizer_parameters,\n    const DomainType& domain,\n    const ThreadSchedule& thread_schedule,\n    double const * restrict start_point_set,\n    double const * restrict points_being_sampled,\n    int num_multistarts,\n    int num_to_sample,\n    int num_being_sampled,\n    double best_so_far,\n    int max_int_steps,\n    NormalRNG * normal_rng,\n    bool * restrict found_flag,\n    double * restrict best_next_point) {\n  if (unlikely(num_multistarts <= 0)) {\n    OL_THROW_EXCEPTION(LowerBoundException<int>, \"num_multistarts must be > 1\", num_multistarts, 1);\n  }\n\n  bool configure_for_gradients = true;\n  if (num_to_sample == 1 && num_being_sampled == 0) {\n    // special analytic case when we are not using (or not accounting for) multiple, simultaneous experiments\n    OnePotentialSampleExpectedImprovementEvaluator ei_evaluator(gaussian_process, best_so_far);\n\n    std::vector<typename OnePotentialSampleExpectedImprovementEvaluator::StateType> ei_state_vector;\n    SetupExpectedImprovementState(ei_evaluator, start_point_set, thread_schedule.max_num_threads,\n                                  configure_for_gradients, &ei_state_vector);\n\n    std::vector<double> EI_starting(num_multistarts);\n    for (int i=0; i<num_multistarts; ++i){\n      ei_state_vector[0].SetCurrentPoint(ei_evaluator, start_point_set + i*num_to_sample*gaussian_process.dim());\n      EI_starting[i] = ei_evaluator.ComputeExpectedImprovement(&ei_state_vector[0]);\n    }\n\n    std::priority_queue<std::pair<double, int>> q;\n    int k = 20; // number of indices we need\n    for (int i = 0; i < EI_starting.size(); ++i) {\n      if (i < k){\n        q.push(std::pair<double, int>(-EI_starting[i], i));\n      }\n      else{\n        if (q.top().first > -EI_starting[i]){\n          q.pop();\n          q.push(std::pair<double, int>(-EI_starting[i], i));\n        }\n      }\n    }\n\n    std::vector<double> top_k_starting(k*num_to_sample*gaussian_process.dim());\n    for (int i = 0; i < k; ++i) {\n      int ki = q.top().second;\n      for (int d = 0; d<num_to_sample*gaussian_process.dim(); ++d){\n        top_k_starting[i*num_to_sample*gaussian_process.dim() + d] = start_point_set[ki*num_to_sample*gaussian_process.dim() + d];\n      }\n      q.pop();\n    }\n\n    // init winner to be first point in set and 'force' its value to be 0.0; we cannot do worse than this\n    OptimizationIOContainer io_container(ei_state_vector[0].GetProblemSize(), -1.0, top_k_starting.data());\n\n    GradientDescentOptimizer<OnePotentialSampleExpectedImprovementEvaluator, DomainType> gd_opt;\n    MultistartOptimizer<GradientDescentOptimizer<OnePotentialSampleExpectedImprovementEvaluator, DomainType> > multistart_optimizer;\n    multistart_optimizer.MultistartOptimize(gd_opt, ei_evaluator, optimizer_parameters,\n                                            domain, thread_schedule, top_k_starting.data(),\n                                            k, ei_state_vector.data(), nullptr, &io_container);\n    *found_flag = io_container.found_flag;\n    std::copy(io_container.best_point.begin(), io_container.best_point.end(), best_next_point);\n  } else {\n    ExpectedImprovementEvaluator ei_evaluator(gaussian_process, max_int_steps, best_so_far);\n\n    std::vector<typename ExpectedImprovementEvaluator::StateType> ei_state_vector;\n    SetupExpectedImprovementState(ei_evaluator, start_point_set, points_being_sampled,\n                                  num_to_sample, num_being_sampled, thread_schedule.max_num_threads,\n                                  configure_for_gradients, normal_rng, &ei_state_vector);\n\n    std::vector<double> EI_starting(num_multistarts);\n    for (int i=0; i<num_multistarts; ++i){\n      ei_state_vector[0].SetCurrentPoint(ei_evaluator, start_point_set + i*num_to_sample*gaussian_process.dim());\n      EI_starting[i] = ei_evaluator.ComputeExpectedImprovement(&ei_state_vector[0]);\n    }\n\n    std::priority_queue<std::pair<double, int>> q;\n    int k = 20; // number of indices we need\n    for (int i = 0; i < EI_starting.size(); ++i) {\n      if (i < k){\n        q.push(std::pair<double, int>(-EI_starting[i], i));\n      }\n      else{\n        if (q.top().first > -EI_starting[i]){\n          q.pop();\n          q.push(std::pair<double, int>(-EI_starting[i], i));\n        }\n      }\n    }\n\n    std::vector<double> top_k_starting(k*num_to_sample*gaussian_process.dim());\n    for (int i = 0; i < k; ++i) {\n      int ki = q.top().second;\n      for (int d = 0; d<num_to_sample*gaussian_process.dim(); ++d){\n        top_k_starting[i*num_to_sample*gaussian_process.dim() + d] = start_point_set[ki*num_to_sample*gaussian_process.dim() + d];\n      }\n      q.pop();\n    }\n\n    // init winner to be first point in set and 'force' its value to be 0.0; we cannot do worse than this\n    OptimizationIOContainer io_container(ei_state_vector[0].GetProblemSize(), -1.0, top_k_starting.data());\n\n    using RepeatedDomain = RepeatedDomain<DomainType>;\n    RepeatedDomain repeated_domain(domain, num_to_sample);\n    GradientDescentOptimizer<ExpectedImprovementEvaluator, RepeatedDomain> gd_opt;\n    MultistartOptimizer<GradientDescentOptimizer<ExpectedImprovementEvaluator, RepeatedDomain> > multistart_optimizer;\n\n    multistart_optimizer.MultistartOptimize(gd_opt, ei_evaluator, optimizer_parameters,\n                                            repeated_domain, thread_schedule, top_k_starting.data(), k,\n                                            ei_state_vector.data(), nullptr, &io_container);\n\n    *found_flag = io_container.found_flag;\n    std::copy(io_container.best_point.begin(), io_container.best_point.end(), best_next_point);\n  }\n}\n\n/*!\\rst\n  Perform multistart gradient descent (MGD) to solve the q,p-EI problem (see ComputeOptimalPointsToSample and/or\n  header docs), starting from ``num_multistarts`` points selected randomly from the within th domain.\n\n  This function is a simple wrapper around ComputeOptimalPointsToSampleViaMultistartGradientDescent(). It additionally\n  generates a set of random starting points and is just here for convenience when better initial guesses are not\n  available.\n\n  See ComputeOptimalPointsToSampleViaMultistartGradientDescent() for more details.\n\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :optimizer_parameters: GradientDescentParameters object that describes the parameters controlling EI optimization\n      (e.g., number of iterations, tolerances, learning rate)\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_dynamic), chunk_size (0).\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-EI)\n    :best_so_far: value of the best sample so far (must be ``min(points_sampled_value)``)\n    :max_int_steps: maximum number of MC iterations\n    :uniform_generator[1]: a UniformRandomGenerator object providing the random engine for uniform random numbers\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n  \\output\n    :found_flag[1]: true if best_next_point corresponds to a nonzero EI\n    :uniform_generator[1]: UniformRandomGenerator object will have its state changed due to random draws\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :best_next_point[dim][num_to_sample]: points yielding the best EI according to MGD\n\\endrst*/\ntemplate <typename DomainType>\nvoid ComputeOptimalPointsToSampleWithRandomStarts(const GaussianProcess& gaussian_process,\n                                                  const GradientDescentParameters& optimizer_parameters,\n                                                  const DomainType& domain, const ThreadSchedule& thread_schedule,\n                                                  double const * restrict points_being_sampled,\n                                                  int num_to_sample, int num_being_sampled, double best_so_far,\n                                                  int max_int_steps, bool * restrict found_flag,\n                                                  UniformRandomGenerator * uniform_generator, NormalRNG * normal_rng,\n                                                  double * restrict best_next_point) {\n  std::vector<double> starting_points(gaussian_process.dim()*optimizer_parameters.num_multistarts*num_to_sample);\n\n  // GenerateUniformPointsInDomain() is allowed to return fewer than the requested number of multistarts\n  RepeatedDomain<DomainType> repeated_domain(domain, num_to_sample);\n  int num_multistarts = repeated_domain.GenerateUniformPointsInDomain(optimizer_parameters.num_multistarts,\n                                                                      uniform_generator, starting_points.data());\n\n  ComputeOptimalPointsToSampleViaMultistartGradientDescent(gaussian_process, optimizer_parameters, domain,\n                                                           thread_schedule, starting_points.data(),\n                                                           points_being_sampled, num_multistarts, num_to_sample,\n                                                           num_being_sampled, best_so_far, max_int_steps,\n                                                           normal_rng, found_flag, best_next_point);\n#ifdef OL_WARNING_PRINT\n  if (false == *found_flag) {\n    OL_WARNING_PRINTF(\"WARNING: %s DID NOT CONVERGE\\n\", OL_CURRENT_FUNCTION_NAME);\n    OL_WARNING_PRINTF(\"First multistart point was returned:\\n\");\n    PrintMatrixTrans(starting_points.data(), num_to_sample, gaussian_process.dim());\n  }\n#endif\n}\n\n/*!\\rst\n  Function to evaluate Expected Improvement (q,p-EI) over a specified list of ``num_multistarts`` points.\n  Optionally outputs the EI at each of these points.\n  Outputs the point of the set obtaining the maximum EI value.\n\n  Generally gradient descent is preferred but when they fail to converge this may be the only \"robust\" option.\n  This function is also useful for plotting or debugging purposes (just to get a bunch of EI values).\n\n  This function is just a wrapper that builds the required state objects and a NullOptimizer object and calls\n  MultistartOptimizer<...>::MultistartOptimize(...); see gpp_optimization.hpp.\n\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_static), chunk_size (0).\n    :initial_guesses[dim][num_to_sample][num_multistarts]: list of points at which to compute EI\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :num_multistarts: number of points to check\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-EI)\n    :best_so_far: value of the best sample so far (must be ``min(points_sampled_value)``)\n    :max_int_steps: maximum number of MC iterations\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n  \\output\n    :found_flag[1]: true if best_next_point corresponds to a nonzero EI\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :function_values[num_multistarts]: EI evaluated at each point of ``initial_guesses``, in the same order as\n      ``initial_guesses``; never dereferenced if nullptr\n    :best_next_point[dim][num_to_sample]: points yielding the best EI according to dumb search\n\\endrst*/\nvoid EvaluateEIAtPointList(const GaussianProcess& gaussian_process,\n                           const ThreadSchedule& thread_schedule,\n                           double const * restrict initial_guesses,\n                           double const * restrict points_being_sampled,\n                           int num_multistarts, int num_to_sample,\n                           int num_being_sampled, double best_so_far,\n                           int max_int_steps,\n                           bool * restrict found_flag, NormalRNG * normal_rng,\n                           double * restrict function_values,\n                           double * restrict best_next_point);\n\n/*!\\rst\n  Perform a random, naive search to \"solve\" the q,p-EI problem (see ComputeOptimalPointsToSample and/or\n  header docs).  Evaluates EI at ``num_multistarts`` points (e.g., on a latin hypercube) to find the\n  point with the best EI value.\n\n  Generally gradient descent is preferred but when they fail to converge this may be the only \"robust\" option.\n\n  Solution is guaranteed to lie within the region specified by ``domain``; note that this may not be a\n  true optima (i.e., the gradient may be substantially nonzero).\n\n  Wraps EvaluateEIAtPointList(); constructs the input point list with a uniform random sampling from the given Domain object.\n\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_static), chunk_size (0).\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :num_multistarts: number of random points to check\n    :num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the \"p\" in q,p-EI)\n    :best_so_far: value of the best sample so far (must be ``min(points_sampled_value)``)\n    :max_int_steps: maximum number of MC iterations\n    :uniform_generator[1]: a UniformRandomGenerator object providing the random engine for uniform random numbers\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n  \\output\n    found_flag[1]: true if best_next_point corresponds to a nonzero EI\n    :uniform_generator[1]: UniformRandomGenerator object will have its state changed due to random draws\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :best_next_point[dim][num_to_sample]: points yielding the best EI according to dumb search\n\\endrst*/\ntemplate <typename DomainType>\nvoid ComputeOptimalPointsToSampleViaLatinHypercubeSearch(const GaussianProcess& gaussian_process,\n                                                         const DomainType& domain,\n                                                         const ThreadSchedule& thread_schedule,\n                                                         double const * restrict points_being_sampled,\n                                                         int num_multistarts, int num_to_sample,\n                                                         int num_being_sampled, double best_so_far,\n                                                         int max_int_steps,\n                                                         bool * restrict found_flag,\n                                                         UniformRandomGenerator * uniform_generator,\n                                                         NormalRNG * normal_rng,\n                                                         double * restrict best_next_point) {\n  std::vector<double> initial_guesses(gaussian_process.dim()*num_multistarts*num_to_sample);\n  RepeatedDomain<DomainType> repeated_domain(domain, num_to_sample);\n  num_multistarts = repeated_domain.GenerateUniformPointsInDomain(num_multistarts, uniform_generator,\n                                                                  initial_guesses.data());\n\n  EvaluateEIAtPointList(gaussian_process, thread_schedule, initial_guesses.data(),\n                        points_being_sampled, num_multistarts, num_to_sample,\n                        num_being_sampled, best_so_far, max_int_steps,\n                        found_flag, normal_rng, nullptr, best_next_point);\n}\n\n/*!\\rst\n  Solve the q,p-EI problem (see header docs) by optimizing the Expected Improvement.\n  Uses multistart gradient descent, \"dumb\" search, and/or other heuristics to perform the optimization.\n\n  This is the primary entry-point for EI optimization in the optimal_learning library. It offers our best shot at\n  improving robustness by combining higher accuracy methods like gradient descent with fail-safes like random/grid search.\n\n  Returns the optimal set of q points to sample CONCURRENTLY by solving the q,p-EI problem.  That is, we may want to run 4\n  experiments at the same time and maximize the EI across all 4 experiments at once while knowing of 2 ongoing experiments\n  (4,2-EI). This function handles this use case. Evaluation of q,p-EI (and its gradient) for q > 1 or p > 1 is expensive\n  (requires monte-carlo iteration), so this method is usually very expensive.\n\n  Wraps ComputeOptimalPointsToSampleWithRandomStarts() and ComputeOptimalPointsToSampleViaLatinHypercubeSearch().\n\n  Compared to ComputeHeuristicPointsToSample() (``gpp_heuristic_expected_improvement_optimization.hpp``), this function\n  makes no external assumptions about the underlying objective function. Instead, it utilizes a feature of the\n  GaussianProcess that allows the GP to account for ongoing/incomplete experiments.\n\n  .. NOTE:: These comments were copied into multistart_expected_improvement_optimization() in cpp_wrappers/expected_improvement.py.\n\n  \\param\n    :gaussian_process: GaussianProcess object (holds ``points_sampled``, ``values``, ``noise_variance``, derived quantities)\n      that describes the underlying GP\n    :optimizer_parameters: GradientDescentParameters object that describes the parameters controlling EI optimization\n      (e.g., number of iterations, tolerances, learning rate)\n    :domain: object specifying the domain to optimize over (see ``gpp_domain.hpp``)\n    :thread_schedule: struct instructing OpenMP on how to schedule threads; i.e., (suggestions in parens)\n      max_num_threads (num cpu cores), schedule type (omp_sched_dynamic), chunk_size (0).\n    :points_being_sampled[dim][num_being_sampled]: points that are being sampled in concurrent experiments\n    :num_to_sample: how many simultaneous experiments you would like to run (i.e., the q in q,p-EI)\n    :num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :best_so_far: value of the best sample so far (must be ``min(points_sampled_value)``)\n    :max_int_steps: maximum number of MC iterations\n    :lhc_search_only: whether to ONLY use latin hypercube search (and skip gradient descent EI opt)\n    :num_lhc_samples: number of samples to draw if/when doing latin hypercube search\n    :uniform_generator[1]: a UniformRandomGenerator object providing the random engine for uniform random numbers\n    :normal_rng[thread_schedule.max_num_threads]: a vector of NormalRNG objects that provide\n      the (pesudo)random source for MC integration\n  \\output\n    :found_flag[1]: true if best_points_to_sample corresponds to a nonzero EI if sampled simultaneously\n    :uniform_generator[1]: UniformRandomGenerator object will have its state changed due to random draws\n    :normal_rng[thread_schedule.max_num_threads]: NormalRNG objects will have their state changed due to random draws\n    :best_points_to_sample[num_to_sample*dim]: point yielding the best EI according to MGD\n\\endrst*/\ntemplate <typename DomainType>\nvoid ComputeOptimalPointsToSample(const GaussianProcess& gaussian_process,\n                                  const GradientDescentParameters& optimizer_parameters,\n                                  const DomainType& domain, const ThreadSchedule& thread_schedule,\n                                  double const * restrict points_being_sampled,\n                                  int num_to_sample, int num_being_sampled, double best_so_far,\n                                  int max_int_steps, bool lhc_search_only,\n                                  int num_lhc_samples, bool * restrict found_flag,\n                                  UniformRandomGenerator * uniform_generator,\n                                  NormalRNG * normal_rng, double * restrict best_points_to_sample);\n\n// template explicit instantiation declarations, see gpp_common.hpp header comments, item 6\nextern template void ComputeOptimalPointsToSample(\n    const GaussianProcess& gaussian_process, const GradientDescentParameters& optimizer_parameters,\n    const TensorProductDomain& domain, const ThreadSchedule& thread_schedule,\n    double const * restrict points_being_sampled, int num_to_sample,\n    int num_being_sampled, double best_so_far, int max_int_steps, bool lhc_search_only,\n    int num_lhc_samples, bool * restrict found_flag, UniformRandomGenerator * uniform_generator,\n    NormalRNG * normal_rng, double * restrict best_points_to_sample);\nextern template void ComputeOptimalPointsToSample(\n    const GaussianProcess& gaussian_process, const GradientDescentParameters& optimizer_parameters,\n    const SimplexIntersectTensorProductDomain& domain, const ThreadSchedule& thread_schedule,\n    double const * restrict points_being_sampled,\n    int num_to_sample, int num_being_sampled, double best_so_far, int max_int_steps,\n    bool lhc_search_only, int num_lhc_samples, bool * restrict found_flag,\n    UniformRandomGenerator * uniform_generator, NormalRNG * normal_rng, double * restrict best_points_to_sample);\n\n}  // end namespace optimal_learning\n\n#endif  // MOE_OPTIMAL_LEARNING_CPP_GPP_MATH_HPP_\n", "meta": {"hexsha": "106d7edfe930de9cbbc227eeaa8e2c8b155f8bb2", "size": 111985, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "moe/optimal_learning/cpp/gpp_math.hpp", "max_stars_repo_name": "AliBaheri/Cornell-MOE", "max_stars_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "moe/optimal_learning/cpp/gpp_math.hpp", "max_issues_repo_name": "AliBaheri/Cornell-MOE", "max_issues_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moe/optimal_learning/cpp/gpp_math.hpp", "max_forks_repo_name": "AliBaheri/Cornell-MOE", "max_forks_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T14:48:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-02T14:48:26.000Z", "avg_line_length": 55.3285573123, "max_line_length": 177, "alphanum_fraction": 0.7180068759, "num_tokens": 25177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.44678044334461686}}
{"text": "#include \"LBFGSB.h\"\n#include <Eigen/Core>\n#include <vector>\n#include <memory>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <chrono>\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\nusing namespace LBFGSpp;\n\ntypedef double Scalar;\ntypedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector;\n\nclass Timer\n{\npublic:\n    void start()\n    {\n        m_StartTime = std::chrono::system_clock::now();\n        m_bRunning = true;\n    }\n\n    void stop()\n    {\n        m_EndTime = std::chrono::system_clock::now();\n        m_bRunning = false;\n    }\n\n    double elapsedMilliseconds()\n    {\n        std::chrono::time_point<std::chrono::system_clock> endTime;\n\n        if(m_bRunning)\n        {\n            endTime = std::chrono::system_clock::now();\n        }\n        else\n        {\n            endTime = m_EndTime;\n        }\n\n        return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - m_StartTime).count();\n    }\n\n    double elapsedSeconds()\n    {\n        return elapsedMilliseconds() / 1000.0;\n    }\n\nprivate:\n    std::chrono::time_point<std::chrono::system_clock> m_StartTime;\n    std::chrono::time_point<std::chrono::system_clock> m_EndTime;\n    bool                                               m_bRunning = false;\n};\n\nclass SegmentCCDF {\nprivate:\n    std::vector<long> occCounts;\n    std::vector<long> occCountFrequency;\npublic:\n    SegmentCCDF(\n            std::vector<long>&& occCounts_,\n            std::vector<long>&& occCountFrequency_\n            ) {\n        occCounts = std::move(occCounts_);\n        occCountFrequency = std::move(occCountFrequency_);\n    }\n    void compute(double bias, double* totalResult, double* gradientResult) const {\n        size_t n = occCounts.size();\n        double total = 0;\n        double totalDeriv = 0;\n        for (size_t i = 0; i < n; i++) {\n            if (occCounts[i] > bias) {\n                total += (occCounts[i] - bias) * occCountFrequency[i];\n                totalDeriv -= occCountFrequency[i];\n            }\n        }\n        *totalResult = total;\n        *gradientResult = totalDeriv;\n    }\n    void print() const {\n        for (long x : occCounts) {\n            std::cout << x << \" \";\n        }\n        std::cout << std::endl;\n        for (long x : occCountFrequency) {\n            std::cout << x << \" \";\n        }\n        std::cout << std::endl;\n    }\n};\n\nclass RMSErrorFunction\n{\nprivate:\n    std::vector<SegmentCCDF> segments;\n    std::vector<int> segmentSpaces;\npublic:\n    RMSErrorFunction(\n            std::vector<SegmentCCDF>&& segments_,\n            std::vector<int>&& segmentSpaces_\n            ) {\n        segments = std::move(segments_);\n        segmentSpaces = std::move(segmentSpaces_);\n    }\n\n    Scalar operator()(const Vector& xBuffer, Vector& grad)\n    {\n        int nSeg = segments.size();\n        double biasTerm = 0;\n        double varTerm = 0;\n\n        double ni, dni;\n        for (int i = 0; i < nSeg; i++) {\n            double x = xBuffer[i];\n            const SegmentCCDF& segCDF = segments[i];\n//            std::cout << \"cdf: \" << i << std::endl;\n//            segCDF.print();\n            segCDF.compute(x, &ni, &dni);\n\n            biasTerm += x;\n            double scaledTotal = ni / segmentSpaces[i];\n            varTerm += .25*scaledTotal*scaledTotal;\n            grad[i] = .5*scaledTotal*dni/segmentSpaces[i];\n        }\n\n        for (int i = 0; i < nSeg; i++) {\n            grad[i] += 2*biasTerm;\n        }\n        return biasTerm*biasTerm + varTerm;\n    }\n\n    int dim() {\n        return segmentSpaces.size();\n    }\n};\n\nRMSErrorFunction testFunction(int n) {\n    std::vector<long> occCounts {1, 2, 3, 5};\n    std::vector<long> occCountFreqs {50, 30, 10, 10};\n\n    SegmentCCDF ccdf (\n            std::move(occCounts),\n            std::move(occCountFreqs)\n            );\n\n    std::vector<SegmentCCDF> segments;\n    std::vector<int> segmentSpaces;\n    for (int i = 0; i < n; i++) {\n        segments.push_back(ccdf);\n        segmentSpaces.push_back(5);\n    }\n    return RMSErrorFunction(\n            std::move(segments),\n            std::move(segmentSpaces)\n            );\n}\n\nRMSErrorFunction parseFile(const std::string& filePath) {\n    std::vector<int> segmentSpaces;\n    std::vector<SegmentCCDF> segments;\n\n    std::ifstream infile;\n    infile.open(filePath.c_str());\n\n    std::string line;\n    std::istringstream iss;\n    long number;\n    int numInt;\n\n    std::getline(infile, line);\n    iss = std::istringstream(line);\n    while (iss >> numInt) {\n        segmentSpaces.push_back(numInt);\n    }\n\n    int numSegments = segmentSpaces.size();\n\n    for (int i = 0; i < numSegments; i++) {\n        std::getline(infile, line);\n        iss = std::istringstream(line);\n        std::vector<long> occCounts;\n        occCounts.reserve(line.size());\n        while (iss >> number) {\n            occCounts.push_back(number);\n        }\n\n        std::getline(infile, line);\n        iss = std::istringstream(line);\n        std::vector<long> occCountFrequency;\n        occCountFrequency.reserve(occCounts.size());\n        while (iss >> number) {\n            occCountFrequency.push_back(number);\n        }\n\n        segments.emplace_back(\n                std::move(occCounts),\n                std::move(occCountFrequency)\n                );\n    }\n\n    return RMSErrorFunction(\n            std::move(segments),\n            std::move(segmentSpaces)\n            );\n}\n\nint main(int argc, char *argv[])\n{\n    LBFGSBParam<double> param;\n    param.max_iterations = 30;\n    LBFGSBSolver<double> solver(param);\n\n//    const int n = 10;\n//    RMSErrorFunction fun = testFunction(n);\n    Timer parseTimer;\n    parseTimer.start();\n    RMSErrorFunction fun = parseFile(argv[1]);\n    parseTimer.stop();\n    std::cerr << \"Parse Time: \" << parseTimer.elapsedMilliseconds() << std::endl;\n    int n = fun.dim();\n\n    Vector lb = Vector::Constant(n, 0.0);\n    Vector ub = Vector::Constant(n, std::numeric_limits<Scalar>::infinity());\n    VectorXd x = VectorXd::Zero(n);\n    double fx = 0;\n\n    VectorXd g = VectorXd::Zero(n);\n    int niter = solver.minimize(fun, x, fx, lb, ub);\n\n//    std::cout << niter << \" iterations\" << std::endl;\n//    std::cout << \"x = \\n\" << x.transpose() << std::endl;\n//    std::cout << \"f(x) = \" << fx << std::endl;\n    std::cout << x.transpose() << std::endl;\n    return 0;\n}\n\n", "meta": {"hexsha": "15de83b3080a990c7f1ae2d96dc00a17b5f30623", "size": 6279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/main.cpp", "max_stars_repo_name": "stanford-futuredata/sketchstore", "max_stars_repo_head_hexsha": "c209e4d01343a05dc5aecdb7a9801fc639019fd3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T02:25:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T07:54:42.000Z", "max_issues_repo_path": "cpp/main.cpp", "max_issues_repo_name": "stanford-futuredata/sketchstore", "max_issues_repo_head_hexsha": "c209e4d01343a05dc5aecdb7a9801fc639019fd3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-31T20:04:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-31T20:04:59.000Z", "max_forks_repo_path": "cpp/main.cpp", "max_forks_repo_name": "stanford-futuredata/sketchstore", "max_forks_repo_head_hexsha": "c209e4d01343a05dc5aecdb7a9801fc639019fd3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-06T20:39:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-06T20:39:05.000Z", "avg_line_length": 26.0539419087, "max_line_length": 100, "alphanum_fraction": 0.557891384, "num_tokens": 1567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4467152375685961}}
{"text": "/* Copyright (C) 2017 IBM Corp.\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific\n * language governing permissions and limitations under the License. \n */\n/*******************************************************************\nGaussian1Dsampler: defines a 1D pseudo-random number sampler, either\nusing Martin Albresht's online library or implementing two optional\nmethods, Box–Muller transform Marsaglia polar method\n********************************************************************/\n#include <NTL/ZZ.h>\n#include <NTL/mat_lzz_p.h>\n#include <limits>\n#include <NTL/BasicThreadPool.h>\n#include <NTL/ZZ.h>\n#include <NTL/FFT.h>\n#include <NTL/SmartPtr.h>\n\nNTL_CLIENT\n#include \"mat_l.h\"\n#include \"vec_l.h\"\n#include \"DGaussSampler.h\"\n#include \"utils/tools.h\"\n\n\n#ifdef NTL_HAVE_AVX\n#warning \"HAVE_AVX\"\n\n#include <immintrin.h>\n\n#ifdef NTL_HAVE_FMA\n#define MUL_ADD(a, b, c) a = _mm256_fmadd_pd(b, c, a)\n#else\n#define MUL_ADD(a, b, c) a = _mm256_add_pd(a, _mm256_mul_pd(b, c))\n#endif\n#endif\n\n\n// Two static variables for debugging purposes\nstd::atomic<double> Gaussian1Dsampler::maxSigma(0.0);// keep largest stdev we've seen\nstd::atomic<int> Gaussian1Dsampler::maxSample(0);   // keep largest sample ever drawn\n\n\nlong Gaussian1Dsampler::writeToFile(FILE* handle)\n{\n    FHE_TIMER_START;\n    long count = fwrite(&sigma,sizeof(sigma),1,handle);\n\n    return count;\n}\n\nlong Gaussian1Dsampler::readFromFile(FILE* handle)\n{\n    FHE_TIMER_START;\n    long count = fread(&sigma,sizeof(sigma),1,handle);\n\n    return count;\n}\n\n#ifdef CONTINUOUS_GAUSSIAN_SAMPLING\n/* generateGaussianNoiseMars uses Marsaglia polar method\n * to generate Gaussian samples\n */\nNTL::Pair<double,double>\nGaussian1Dsampler::generateGaussianNoiseMars(double mean, double stdDev)\n{\n    FHE_TIMER_START;\n    double u, v, s;\n    do    // choose (u,v) in the square [-1,1] x [-1,1]\n    {\n        u = (NTL::RandomBnd(NTL_SP_BOUND)/((double)NTL_SP_BOUND)) *2.0 -1.0;\n        v = (NTL::RandomBnd(NTL_SP_BOUND)/((double)NTL_SP_BOUND)) *2.0 -1.0;\n        s = u * u + v * v;\n    }\n    while( (s >= 1.0) || (s == 0.0) );// until you find a pair in the unit sphere\n\n    s = sqrt(-2.0 * log(s) / s);\n    double sample1 = mean + stdDev * u * s;\n    double sample2 = mean + stdDev * v * s;\n\n    return NTL::Pair<double,double>(sample1,sample2);\n}\n\n/* generateGaussianNoiseBox uses Box-Muller to generate Gaussian Samples\n */\nNTL::Pair<double,double>\nGaussian1Dsampler::generateGaussianNoiseBox(double mu, double stDev)\n{\n    FHE_TIMER_START;\n    const double epsilon = std::numeric_limits<double>::min();\n    const double two_pi = 2.0*3.14159265358979323846;\n\n    double u1, u2;\n    do\n    {\n        u1 = ((NTL::RandomBnd(NTL_SP_BOUND))/((double)NTL_SP_BOUND));\n        u2 = ((NTL::RandomBnd(NTL_SP_BOUND))/((double)NTL_SP_BOUND));\n    }\n    while ( u1 <= epsilon );\n\n    double z0 = sqrt(-2.0 * log(u1)) * cos(two_pi * u2);\n    double z1 = sqrt(-2.0 * log(u1)) * sin(two_pi * u2);\n\n    double sample1 = z0 * stDev + mu;\n    double sample2 = z1 * stDev + mu;\n\n    return NTL::Pair<double,double>(sample1,sample2);\n}\n#endif // ifdef CONTINUOUS_GAUSSIAN_SAMPLING\n", "meta": {"hexsha": "0c716102efe23c88310d3f40ee7caf92a6dcb670", "size": 3533, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Gaussian1Dsampler.cpp", "max_stars_repo_name": "shaih/BPobfus", "max_stars_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-25T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T03:19:43.000Z", "max_issues_repo_path": "Gaussian1Dsampler.cpp", "max_issues_repo_name": "shaih/BPobfus", "max_issues_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Gaussian1Dsampler.cpp", "max_forks_repo_name": "shaih/BPobfus", "max_forks_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-12-23T04:03:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-12T07:42:29.000Z", "avg_line_length": 30.4568965517, "max_line_length": 85, "alphanum_fraction": 0.6654401359, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.44671522497349037}}
{"text": "\n#include \"HasseLiftExt.h\"\n#include \"Util.h\"\n#include \"BaseChange.h\"\n#include \"MultipointEval.h\"\n#include \"FrobComp.h\"\n#include \"MultiComposeMod.h\"\n#include \"BalancedMul.h\"\n#include \"HasseLift.h\"\n#include <NTL/matrix.h>\n#include <cmath>\n#include <NTL/ZZX.h>\n\nHasseLiftExt::HasseLiftExt(const ZZ_pX &g,\n                           const ZZ_pX &delta,\n                           const ZZ_pXModulus &F) {\n    this->g = g;\n    this->delta = delta;\n    this->F = F;\n    PowerXMod(this->frobenius, ZZ_p::modulus(), F);\n}\n\nHasseLiftExt::~HasseLiftExt() {\n    this->g.kill();\n    this->delta.kill();\n    this->F.f.kill();\n    this->frobenius.kill();\n    this->evalModulus.f.kill();\n}\n\nvoid HasseLiftExt::computeNaive(ZZ_pX& result, long n) {\n    long l = (long) pow(n, BETA);\n    long m = n / l;\n    n = m * l + l + 1;\n\n    ZZ_pX r0;\n    ZZ_pX r1;\n    ZZ_pX gTemp;\n    ZZ_pX deltaTemp;\n    ZZ_pX xq;\n    ZZ_pX x;\n    ZZ_pX temp1;\n    ZZ_pX temp2;\n\n    set(r0);\n    r1 = g;\n    PowerMod(gTemp, g, ZZ_p::modulus(), F);\n    deltaTemp = delta;\n    SetX(x);\n    xq = this->frobenius;\n\n    for (long i = 2; i <= n; i++) {\n        sub(temp1, xq, x);\n        MulMod(temp1, temp1, deltaTemp, F);\n        MulMod(temp1, temp1, r0, F);\n        MulMod(temp2, gTemp, r1, F);\n        r0 = r1;\n        sub(r1, temp2, temp1);\n\n        PowerMod(gTemp, gTemp, ZZ_p::modulus(), F);\n        PowerMod(deltaTemp, deltaTemp, ZZ_p::modulus(), F);\n        PowerMod(xq, xq, ZZ_p::modulus(), F);\n    }\n\n    result = r1;\n\n    r0.kill();\n    r1.kill();\n    gTemp.kill();\n    deltaTemp.kill();\n    xq.kill();\n    x.kill();\n    temp1.kill();\n    temp2.kill();\n}\n\nvoid HasseLiftExt::compute(ZZ_pX& result, long n, int verbose) {\n\n    long l = (long) pow(n, BETA);\n    long m = n / l;\n\n    ZZ_pE::init(F.f);\n\n    Mat<ZZ_pEX> B;\n    B.SetDims(2, 2);\n    buildInitialMatrix(B);\n\n    Util util;\n    long start = util.getTimeMillis();\n    // compute x, tau^{-l}(x), tau^{-2l}(x), ..., tau^{-lm}(x)\n    Vec<ZZ_pX> inverseFrobs;\n    inverseFrobs.SetLength(m + 1);\n    FrobComp frobComp;\n    frobComp.computeInverseFrobes(inverseFrobs, m, l, frobenius, F);\n    buildEvalModulus(inverseFrobs);\n    if (verbose == 1)\n        cout << \"computeInverseFrobes: \" << util.getTimeMillis() - start << endl;\n\n    start = util.getTimeMillis();\n    // compute the product tau^{l - 1}(A)...tau(A)A\n    computeFrobProduct(B, B, l);\n    if (verbose == 1)\n        cout << \"computeFrobProduct: \" << util.getTimeMillis() - start << endl;\n\n    start = util.getTimeMillis();\n    // compute B(inverseFrobs[0]), ..., B(inverseFrobs[m])\n    Mat<Vec < ZZ_pX>> BEval;\n    BEval.SetDims(2, 2);\n    evaluate(BEval, B, inverseFrobs);\n    if (verbose == 1)\n        cout << \"evaluate BEval: \" << util.getTimeMillis() - start << endl;\n\n    start = util.getTimeMillis();\n    // compute the product tau^{lm}(BEval(i))...tau^{l}(BEval(i)) BEval(i)\n    Mat<ZZ_pX> frobProduct;\n    frobProduct.SetDims(2, 2);\n    computeFrobProduct(frobProduct, BEval, l);\n    if (verbose == 1)\n        cout << \"computeFrobProduct2: \" << util.getTimeMillis() - start << endl;\n\n    MulMod(result, frobProduct[1][1], g, F);\n    add(result, result, frobProduct[1][0]);\n\n    B.kill();\n    inverseFrobs.kill();\n    BEval.kill();\n    frobProduct.kill();\n}\n\nvoid HasseLiftExt::buildEvalModulus(const Vec<ZZ_pX> &inverseFrobs) {\n    long m = inverseFrobs.length();\n    Vec<ZZ_pEX> tempVec;\n    tempVec.SetLength(m);\n\n    for (long i = 0; i < m; i++) {\n        clear(tempVec[i]);\n        SetCoeff(tempVec[i], 0, -to_ZZ_pE(inverseFrobs[i]));\n        SetCoeff(tempVec[i], 1, 1);\n    }\n\n    BalancedMul balancedMul;\n    balancedMul.compute(tempVec);\n    evalModulus = tempVec[0];\n    tempVec.kill();\n}\n\nvoid HasseLiftExt::evaluate(Mat<Vec<ZZ_pX> >& result,\n                            const Mat<ZZ_pEX>& A,\n                            const Vec<ZZ_pX>& points) {\n\n    MultipointEval multiPointEval(points);\n\n    for (int i = 0; i < 2; i++) {\n        for (int j = 0; j < 2; j++) {\n\n            result[i][j].SetLength(points.length());\n            multiPointEval.eval(result[i][j], A[i][j]);\n        }\n    }\n}\n\nvoid HasseLiftExt::buildInitialMatrix(Mat<ZZ_pEX>& result) {\n    clear(result[0][0]);\n    set(result[0][1]);\n\n    ZZ_pX temp;\n\n    MulMod(temp, frobenius, delta, F);\n    NTL::negate(temp, temp);\n    clear(result[1][0]);\n    SetCoeff(result[1][0], 0, to_ZZ_pE(temp));\n    SetCoeff(result[1][0], 1, to_ZZ_pE(delta));\n\n    MultiComposeMod().compose(temp, g, frobenius, F);\n    clear(result[1][1]);\n    SetCoeff(result[1][1], 0, to_ZZ_pE(temp));\n\n    temp.kill();\n}\n\n//void HasseLiftExt::computeFrobProduct(Mat<ZZ_pEX>& result,\n//                                      const Mat<ZZ_pEX>& A,\n//                                      long l) {\n//    Vec<ZZ_pX> frobCompos;\n//    frobCompos.SetLength(3);\n//    frobCompos[0] = coeff(A[1][0], 1)._ZZ_pE__rep;\n//    frobCompos[1] = coeff(A[1][1], 0)._ZZ_pE__rep;\n//    frobCompos[2] = coeff(A[1][0], 0)._ZZ_pE__rep;\n//\n//    Mat<ZZ_p> frobMat;\n//    ZZ_pXMultiplier frobMultiplier;\n//    MultiComposeMod multiComposeMod;\n//    multiComposeMod.precompute(frobMat, frobMultiplier, 3, frobenius, F);\n//\n//    Vec<Mat<ZZ_pEX>> tempVec;\n//    tempVec.SetLength(l);\n//    \n//    for (long i = 0; i < l; i++)\n//        tempVec[i].SetDims(2, 2);\n//    \n//    tempVec[l - 1] = A;\n//\n//    for (long i = l - 2; i >= 0; i--) {\n//        multiComposeMod.compose(frobCompos, frobCompos, frobMat,\n//                                frobMultiplier, F);\n//        \n//        clear(tempVec[i][0][0]);\n//        set(tempVec[i][0][1]);\n//        clear(tempVec[i][1][0]);\n//        clear(tempVec[i][1][1]);        \n//        SetCoeff(tempVec[i][1][0], 1, to_ZZ_pE(frobCompos[0]));\n//        SetCoeff(tempVec[i][1][1], 0, to_ZZ_pE(frobCompos[1]));\n//        SetCoeff(tempVec[i][1][0], 0, to_ZZ_pE(frobCompos[2]));\n//    }\n//\n//    BalancedMul balancedMul;\n//    balancedMul.compute(tempVec, evalModulus);\n//    result = tempVec[0];\n//\n//    frobCompos.kill();\n//    frobMat.kill();\n//    frobMultiplier.b.kill();\n//    for (long i = 0; i < l; i++)\n//        tempVec[i].kill();\n//    tempVec.kill();\n//}\n\n\n//void HasseLiftExt::computeFrobProduct(Mat<ZZ_pEX>& result,\n//                                      const Mat<ZZ_pEX>& A,\n//                                      long l) {\n//    Vec<ZZ_pX> frobCompos;\n//    frobCompos.SetLength(3);\n//    frobCompos[0] = coeff(A[1][0], 1)._ZZ_pE__rep;\n//    frobCompos[1] = coeff(A[1][1], 0)._ZZ_pE__rep;\n//    frobCompos[2] = coeff(A[1][0], 0)._ZZ_pE__rep;\n//\n//\n//    Vec<Mat < ZZ_pEX>> tempVec;\n//    tempVec.SetLength(l);\n//\n//    for (long i = 0; i < l; i++)\n//        tempVec[i].SetDims(2, 2);\n//\n//    tempVec[l - 1] = A;\n//\n//    Util util;\n//    long start = util.getTimeMillis();\n//    for (long i = l - 2; i >= 0; i--) {\n//        for (long j = 0; j < frobCompos.length(); j++)\n//            PowerMod(frobCompos[j], frobCompos[j], ZZ_p::modulus(), F);\n//\n//        clear(tempVec[i][0][0]);\n//        set(tempVec[i][0][1]);\n//        clear(tempVec[i][1][0]);\n//        clear(tempVec[i][1][1]);\n//        SetCoeff(tempVec[i][1][0], 1, to_ZZ_pE(frobCompos[0]));\n//        SetCoeff(tempVec[i][1][1], 0, to_ZZ_pE(frobCompos[1]));\n//        SetCoeff(tempVec[i][1][0], 0, to_ZZ_pE(frobCompos[2]));\n//    }\n//    cout << \"powering time: \" << util.getTimeMillis() - start << endl;\n//    \n//    start = util.getTimeMillis();\n//    BalancedMul balancedMul;\n//    balancedMul.compute(tempVec, evalModulus);\n//    result = tempVec[0];\n//    cout << \"balanced mul time: \" << util.getTimeMillis() - start << endl;\n//\n//    frobCompos.kill();\n//    for (long i = 0; i < l; i++)\n//        tempVec[i].kill();\n//    tempVec.kill();\n//}\n\nvoid HasseLiftExt::computeFrobProduct(Mat<ZZ_pEX>& result,\n                                      const Mat<ZZ_pEX>& A,\n                                      long l) {\n\n    Vec<ZZ_pEX> tempVec;\n    Mat<ZZ_pEX> tempMat;\n\n    tempVec.SetLength(2);\n    tempVec[0] = A[1][0];\n    tempVec[1] = A[1][1];\n    tempMat = A;\n\n    BalancedMul balancedMul;\n    for (long i = l - 2; i >= 0; i--) {\n\n        SetCoeff(tempVec[0], 0, power(coeff(tempVec[0], 0), ZZ_p::modulus()));\n        SetCoeff(tempVec[0], 1, power(coeff(tempVec[0], 1), ZZ_p::modulus()));\n        SetCoeff(tempVec[1], 0, power(coeff(tempVec[1], 0), ZZ_p::modulus()));\n\n        balancedMul.mul_ZZ_pEXMatSpec(tempMat, tempVec, tempMat, evalModulus);\n    }\n\n    result = tempMat;\n\n    tempVec.kill();\n    tempMat.kill();\n}\n\nvoid HasseLiftExt::computeFrobProduct(Mat<ZZ_pX> &result,\n                                      Mat<Vec<ZZ_pX>> &B,\n                                      long l) {\n    long m = B[0][0].length();\n    ZZ_pX xqInit;\n    SetX(xqInit);\n    FrobComp frobComp;\n    frobComp.computeFrobPower(xqInit, xqInit, l, frobenius, F);\n\n    // compute tau^2, tau^4, ..., tau^{2^k}\n    // where k = floor(log m)\n    Vec<ZZ_pX> frobPowers;\n    frobPowers.SetLength(NumBits(m - 1));\n    frobPowers[0] = xqInit;\n    MultiComposeMod multiComposeMod;\n    for (long i = 1; i < frobPowers.length(); i++)\n        multiComposeMod.compose(frobPowers[i], frobPowers[i - 1],\n                                frobPowers[i - 1], F);\n\n    for (int i = 0; i < 2; i++)\n        for (int j = 0; j < 2; j++)\n            actFrobPowers(B[i][j], frobPowers);\n\n    Mat<ZZ_pX> tempMat;\n    tempMat.SetDims(2, 2);\n\n    result[0][0] = B[0][0][0];\n    result[0][1] = B[0][1][0];\n    result[1][0] = B[1][0][0];\n    result[1][1] = B[1][1][0];\n\n    BalancedMul balancedMul;\n    for (long i = 1; i < m; i++) {\n        for (int j = 0; j < 2; j++)\n            for (int k = 0; k < 2; k++) {\n                tempMat[j][k] = B[j][k][i];\n            }\n\n        balancedMul.mul_ZZ_pXMat(result, tempMat, result, F);\n    }\n\n    xqInit.kill();\n    frobPowers.kill();\n    tempMat.kill();\n}\n\nvoid HasseLiftExt::actFrobPowers(Vec<ZZ_pX> &vec,\n                                 const Vec<ZZ_pX> &frobPowers) {\n    long n = vec.length();\n    long m = 1;\n    long frobIndex = 0;\n\n    Vec<ZZ_pX> tempVec;\n    MultiComposeMod multiComposeMod;\n\n    while (m < n) {\n        for (long i = 0; i < n; i++) {\n            if ((i & m) != 0)\n                tempVec.append(vec[i]);\n        }\n\n        multiComposeMod.compose(tempVec, tempVec, frobPowers[frobIndex], F);\n\n        long k = 0;\n        for (long i = 0; i < n; i++) {\n            if ((i & m) != 0) {\n                vec[i] = tempVec[k];\n                k++;\n            }\n        }\n\n        tempVec.SetLength(0);\n        m <<= 1;\n        frobIndex++;\n    }\n\n    tempVec.kill();\n}\n\n", "meta": {"hexsha": "f18bb0c96a9946b9b1cd276299b5fe34ff8f83d9", "size": 10517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ss_drinfeld_impl/HasseLiftExt.cpp", "max_stars_repo_name": "javad-doliskani/supersingular_drinfeld_factoring", "max_stars_repo_head_hexsha": "fe402f03f2cec57a36fdf83f9b9e2d72241e6568", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-05-31T17:36:46.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-18T03:04:49.000Z", "max_issues_repo_path": "ss_drinfeld_impl/HasseLiftExt.cpp", "max_issues_repo_name": "javad-doliskani/supersingular_drinfeld_factoring", "max_issues_repo_head_hexsha": "fe402f03f2cec57a36fdf83f9b9e2d72241e6568", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ss_drinfeld_impl/HasseLiftExt.cpp", "max_forks_repo_name": "javad-doliskani/supersingular_drinfeld_factoring", "max_forks_repo_head_hexsha": "fe402f03f2cec57a36fdf83f9b9e2d72241e6568", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5314136126, "max_line_length": 81, "alphanum_fraction": 0.5316154797, "num_tokens": 3466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.44671522497349037}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2016, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** \\example iterative-armadillo.cpp\n*\n*   The following tutorial shows how to use the iterative solvers in ViennaCL with objects from the <a href=\"http://eigen.tuxfamily.org/\">Eigen Library</a> directly.\n*\n*   \\note Eigen provides its own iterative solvers in the meanwhile. Check these first.\n*\n*   We begin with including the necessary headers:\n**/\n\n// System headers\n#include <iostream>\n\n#ifndef NDEBUG\n #define NDEBUG\n#endif\n\n// Armadillo headers (disable BLAS and LAPACK to avoid linking issues)\n#define ARMA_DONT_USE_BLAS\n#define ARMA_DONT_USE_LAPACK\n#include <armadillo>\n\n// IMPORTANT: Must be set prior to any ViennaCL includes if you want to use ViennaCL algorithms on Armadillo objects\n#define VIENNACL_WITH_ARMADILLO 1\n\n// ViennaCL headers\n#include \"viennacl/linalg/cg.hpp\"\n#include \"viennacl/linalg/bicgstab.hpp\"\n#include \"viennacl/linalg/gmres.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n\n\n// Some helper functions for this tutorial:\n#include \"vector-io.hpp\"\n\n/**\n*  In the following we run the CG method, the BiCGStab method, and the GMRES method with Armadillo types directly.\n*  First, the matrices are set up, then the respective solvers are called.\n**/\nint main(int, char *[])\n{\n  typedef float ScalarType;\n\n  /**\n  * Read system from file. This is a little tricky, since Armadillo does not provide a fast enough element-insertion.\n  * Therefore, we read the matrix market file to an STL-matrix and then pass the data on when creating the Armadillo sparse matrix object.\n  **/\n  std::vector<std::map<unsigned int, ScalarType> > stl_matrix;\n  std::cout << \"Reading matrix (this might take some time)...\" << std::endl;\n  if (!viennacl::io::read_matrix_market_file(stl_matrix, \"../examples/testdata/mat65k.mtx\"))\n  {\n    std::cout << \"Error reading Matrix file. Make sure you run from the build/-folder.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  // Copy over to Armadillo sparse matrix by putting the indices into a matrix and the values into a vector:\n  std::size_t num_nnz = 0;\n  for (std::size_t i=0; i<stl_matrix.size(); ++i)\n    num_nnz += stl_matrix[i].size();\n\n  arma::Mat<arma::uword>  arma_indices(2, num_nnz);\n  arma::Col<ScalarType>   arma_values(num_nnz);\n\n  std::size_t index = 0;\n  for (std::size_t i=0; i<stl_matrix.size(); ++i)\n  {\n    for (std::map<unsigned int, ScalarType>::const_iterator it = stl_matrix[i].begin(); it != stl_matrix[i].end(); ++it)\n    {\n      arma_indices(0, index) = i;\n      arma_indices(1, index) = it->first;\n      arma_values(index) = it->second;\n      ++index;\n    }\n  }\n  std::cout << \"Done: reading matrix\" << std::endl;\n\n\n\n  /**\n  * Initialize Armadillo types for iterative solvers\n  **/\n  arma::SpMat<ScalarType> arma_matrix(arma_indices, arma_values, 65025, 65025);\n  arma::Col<ScalarType>   arma_rhs;\n  arma::Col<ScalarType>   arma_result;\n  arma::Col<ScalarType>   residual;\n\n  /**\n   * Read the right hand side as well as the result vector from files:\n   **/\n  if (!readVectorFromFile(\"../examples/testdata/rhs65025.txt\", arma_rhs))\n  {\n    std::cout << \"Error reading RHS file\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  if (!readVectorFromFile(\"../examples/testdata/result65025.txt\", arma_result))\n  {\n    std::cout << \"Error reading Result file\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  /**\n  *  Conjugate Gradient (CG) solver:\n  **/\n  std::cout << \"----- Running CG -----\" << std::endl;\n  arma_result = viennacl::linalg::solve(arma_matrix, arma_rhs, viennacl::linalg::cg_tag());\n\n  residual = arma_matrix * arma_result - arma_rhs;\n  std::cout << \"Relative residual: \" << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(arma_rhs) << std::endl;\n\n  /**\n  *  Stabilized Bi-Conjugate Gradient (BiCGStab) solver:\n  **/\n  std::cout << \"----- Running BiCGStab -----\" << std::endl;\n  arma_result = viennacl::linalg::solve(arma_matrix, arma_rhs, viennacl::linalg::bicgstab_tag());\n\n  residual = arma_matrix * arma_result - arma_rhs;\n  std::cout << \"Relative residual: \" << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(arma_rhs) << std::endl;\n\n  /**\n  *  Generalized Minimum Residual (GMRES) solver:\n  **/\n  std::cout << \"----- Running GMRES -----\" << std::endl;\n  arma_result = viennacl::linalg::solve(arma_matrix, arma_rhs, viennacl::linalg::gmres_tag());\n\n  residual = arma_matrix * arma_result - arma_rhs;\n  std::cout << \"Relative residual: \" << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(arma_rhs) << std::endl;\n\n  /**\n  *   That's it. Print a success message and exit.\n  **/\n  std::cout << std::endl;\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n  std::cout << std::endl;\n}\n\n", "meta": {"hexsha": "66737ccf3715f6f71baed9e5764fda327c005ae1", "size": 5402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/iterative-armadillo.cpp", "max_stars_repo_name": "yuchengs/viennacl-dev", "max_stars_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 224.0, "max_stars_repo_stars_event_min_datetime": "2015-02-15T21:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:27:03.000Z", "max_issues_repo_path": "examples/tutorial/iterative-armadillo.cpp", "max_issues_repo_name": "yuchengs/viennacl-dev", "max_issues_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 189.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T17:08:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T06:23:22.000Z", "max_forks_repo_path": "examples/tutorial/iterative-armadillo.cpp", "max_forks_repo_name": "yuchengs/viennacl-dev", "max_forks_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 84.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T14:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T14:51:17.000Z", "avg_line_length": 35.3071895425, "max_line_length": 165, "alphanum_fraction": 0.645501666, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679957, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.44660058165155264}}
{"text": "#ifndef PARMCB_DETAIL_FVS_HPP_\n#define PARMCB_DETAIL_FVS_HPP_\n\n//    Copyright (C) Dimitrios Michail 2019 - 2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n\n#include <boost/scoped_array.hpp>\n#include <boost/throw_exception.hpp>\n#include <boost/functional/hash.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/property_map/function_property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/heap/pairing_heap.hpp>\n\nnamespace parmcb {\n\n    namespace detail {\n\n        template<class Vertex>\n        struct LessVertex {\n            LessVertex(std::map<Vertex, double> &priority) :\n                    priority(priority) {\n            }\n\n            bool operator()(const Vertex &v, const Vertex &u) const {\n                return priority[v] >= priority[u];\n            }\n\n            std::map<Vertex, double> &priority;\n        };\n\n    } // detail\n\n    template<class Graph, class VertexOutputIterator>\n    void greedy_fvs(const Graph &g, VertexOutputIterator out) {\n\n        typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n        typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIt;\n        typedef typename boost::property_map<Graph, boost::vertex_index_t>::type VertexIndexMapType;\n        typedef typename boost::heap::pairing_heap<Vertex, boost::heap::compare<detail::LessVertex<Vertex>>>::handle_type HeapHandleType;\n\n        std::size_t n = boost::num_vertices(g);\n        std::vector<bool> exists(n);\n        std::vector<std::size_t> degree(n);\n        std::vector<HeapHandleType> handle(n);\n        std::map<Vertex, double> priority;\n        boost::heap::pairing_heap<Vertex, boost::heap::compare<detail::LessVertex<Vertex>>> heap(\n                detail::LessVertex<Vertex> { priority });\n\n        const VertexIndexMapType &index_map = boost::get(boost::vertex_index, g);\n        boost::associative_property_map<std::map<Vertex, double>> priority_map(priority);\n\n        // initialize\n        std::deque<Vertex> forRemoval;\n        VertexIt vi, viend;\n        for (boost::tie(vi, viend) = boost::vertices(g); vi != viend; ++vi) {\n            auto v = *vi;\n            auto vindex = index_map[v];\n            auto d = boost::out_degree(v, g);\n            exists[vindex] = true;\n            if ((degree[vindex] = d) <= 1) {\n                forRemoval.push_front(v);\n            } else {\n                priority[v] = 1.0 / d;\n            }\n        }\n\n        // cleanup\n        // repeatedly remove degree 0 or 1\n        while (!forRemoval.empty()) {\n            Vertex u = forRemoval.front();\n            forRemoval.pop_front();\n            auto uindex = index_map[u];\n            exists[uindex] = false;\n\n            auto eiRange = boost::out_edges(u, g);\n            for (auto ei = eiRange.first; ei != eiRange.second; ++ei) {\n                auto w = boost::target(*ei, g);\n                auto windex = index_map[w];\n                if (!exists[windex]) {\n                    continue;\n                }\n                degree[windex]--;\n                if (degree[windex] <= 1) {\n                    // collect for removal\n                    forRemoval.push_front(w);\n                } else {\n                    priority[w] = 1.0 / degree[windex];\n                }\n            }\n        }\n\n        // add remaining vertices into the priority queue\n        for (boost::tie(vi, viend) = boost::vertices(g); vi != viend; ++vi) {\n            auto v = *vi;\n            auto vindex = index_map[v];\n            if (!exists[vindex]) {\n                continue;\n            }\n            handle[vindex] = heap.push(v);\n        }\n\n        // main loop\n        while (!heap.empty()) {\n            auto v = heap.top();\n            auto vindex = index_map[v];\n            heap.pop();\n\n            if (!exists[vindex]) {\n                continue;\n            }\n\n            // add to feedback vertex set\n            *out++ = v;\n\n            // remove from graph\n            exists[vindex] = false;\n\n            auto eiRange = boost::out_edges(v, g);\n            for (auto ei = eiRange.first; ei != eiRange.second; ++ei) {\n                auto u = boost::target(*ei, g);\n                auto uindex = index_map[u];\n                if (!exists[uindex]) {\n                    continue;\n                }\n                degree[uindex]--;\n                if (degree[uindex] <= 1) {\n                    // collect for removal\n                    forRemoval.push_front(u);\n                } else {\n                    priority[u] = 1.0 / degree[uindex];\n                    heap.decrease(handle[uindex]);\n                }\n            }\n\n            // cleanup\n            while (!forRemoval.empty()) {\n                Vertex u = forRemoval.front();\n                forRemoval.pop_front();\n                auto uindex = index_map[u];\n                exists[uindex] = false;\n\n                eiRange = boost::out_edges(u, g);\n                for (auto ei = eiRange.first; ei != eiRange.second; ++ei) {\n                    auto w = boost::target(*ei, g);\n                    auto windex = index_map[w];\n                    if (!exists[windex]) {\n                        continue;\n                    }\n                    degree[windex]--;\n                    if (degree[windex] <= 1) {\n                        // collect for removal\n                        forRemoval.push_front(w);\n                    } else {\n                        priority[w] = 1.0 / degree[windex];\n                        heap.decrease(handle[windex]);\n                    }\n\n                }\n\n            }\n\n        }\n\n    }\n\n} // parmcb\n\n#endif\n", "meta": {"hexsha": "0969d0f2bc6be4a7be6b9084837ca689fbb9b4fd", "size": 5824, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/parmcb/detail/fvs.hpp", "max_stars_repo_name": "d-michail/parmcb", "max_stars_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/parmcb/detail/fvs.hpp", "max_issues_repo_name": "d-michail/parmcb", "max_issues_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/parmcb/detail/fvs.hpp", "max_forks_repo_name": "d-michail/parmcb", "max_forks_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0909090909, "max_line_length": 137, "alphanum_fraction": 0.5037774725, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.44660057424450467}}
{"text": "// Copyright (C) 2011-2012 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Jeremiah Willcock\n//           Andrew Lumsdaine\n\n#ifndef BOOST_SPLITTABLE_ECUYER1988_HPP\n#define BOOST_SPLITTABLE_ECUYER1988_HPP\n\n#include <boost/cstdint.hpp>\n#include <boost/iterator.hpp>\n#include <boost/iterator/iterator_facade.hpp>\n#include <utility>\n\nnamespace boost { namespace graph { namespace random {\n\n    template <typename Base> // To get around incomplete class issues\n    class generic_split_iterator: public boost::iterator_facade<generic_split_iterator<Base>, Base, std::input_iterator_tag, Base> {\n      public:\n      Base base;\n      uint32_t new_multiplier1, new_multiplier2;\n\n      generic_split_iterator(Base base, uint32_t new_multiplier1, uint32_t new_multiplier2)\n\t: base(base), new_multiplier1(new_multiplier1), new_multiplier2(new_multiplier2) {}\n\n      generic_split_iterator(): base(), new_multiplier1(0), new_multiplier2(0) {}\n\n      Base dereference() const {\n\tBase result = base;\n\tresult.multiplier1 = new_multiplier1;\n\tresult.multiplier2 = new_multiplier2;\n\treturn result;\n      }\n\n      bool equal(const generic_split_iterator& it) const {\n\treturn base.state1 == it.base.state1 && base.state2 == it.base.state2;\n      }\n\n      void increment() {\n\tbase(); // Advance seeds\n      }\n    };\n\n    class splittable_ecuyer1988 {\n      uint32_t state1, state2, multiplier1, multiplier2;\n\n      static const uint64_t modulus1 = 2147483563;\n      static const uint64_t modulus2 = 2147483399;\n\n      template <uint64_t Modulus>\n      static uint32_t mul_mod(uint32_t a, uint32_t b) {\n\treturn uint32_t((uint64_t(a) * b) % Modulus);\n      }\n\n      template <uint64_t Modulus>\n      static uint32_t exp_mod(uint32_t a, uint32_t b) {\n\tif (b == 0) {\n\t  return 1;\n\t} else if (b == 1) {\n\t  return a;\n\t} else {\n\t  uint32_t temp = exp_mod<Modulus>(a, b>>1);\n\t  temp = mul_mod<Modulus>(temp, temp);\n\t  if (b % 2) temp = mul_mod<Modulus>(a, temp);\n\t  return temp;\n\t}\n      }\n\n      public:\n      splittable_ecuyer1988(): state1(1), state2(1), multiplier1(40014), multiplier2(40692) {}\n      splittable_ecuyer1988(uint32_t seed1, uint32_t seed2): state1(seed1), state2(seed2), multiplier1(40014), multiplier2(40692) {}\n\n      void seed(uint32_t seed1, uint32_t seed2) {\n\tstate1 = seed1;\n\tstate2 = seed2;\n      }\n\n      void split(splittable_ecuyer1988& a, splittable_ecuyer1988& b) const {\n\ta = *this;\n\ta.multiplier1 = mul_mod<modulus1>(a.multiplier1, a.multiplier1);\n\ta.multiplier2 = mul_mod<modulus2>(a.multiplier2, a.multiplier2);\n\tb = *this;\n\tb();\n\tb.multiplier1 = a.multiplier1;\n\tb.multiplier2 = a.multiplier2;\n      }\n\n      typedef generic_split_iterator<splittable_ecuyer1988> split_iterator;\n      typedef std::pair<split_iterator, split_iterator> split_iterator_pair;\n      friend class generic_split_iterator<splittable_ecuyer1988>;\n\n      split_iterator_pair split_n(uint32_t n) const { // This RNG is not usable after the split\n\tsplit_iterator begin(*this, exp_mod<modulus1>(multiplier1, n), exp_mod<modulus2>(multiplier2, n));\n\tsplit_iterator end(*this, begin.new_multiplier1, begin.new_multiplier2);\n\tend.base.state1 = mul_mod<modulus1>(end.base.state1, end.new_multiplier1);\n\tend.base.state2 = mul_mod<modulus2>(end.base.state2, end.new_multiplier2);\n\treturn std::make_pair(begin, end);\n      }\n\n      split_iterator_pair split_off_n(uint32_t n) { // Allows this RNG to keep being used\n\tsplit_iterator_pair p = split_n(n + 1);\n\t*this = *p.first;\n\t++p.first;\n\treturn p;\n      }\n\n      typedef uint32_t result_type;\n\n      uint32_t operator()() {\n\tstate1 = mul_mod<modulus1>(state1, multiplier1);\n\tstate2 = mul_mod<modulus2>(state2, multiplier2);\n\treturn (state1 + modulus1 - 1 - state2) % (modulus1 - 1);\n      }\n\n      BOOST_STATIC_CONSTANT(bool, has_fixed_range = true);\n      BOOST_STATIC_CONSTANT(uint32_t, min_value = 0);\n      BOOST_STATIC_CONSTANT(uint32_t, max_value = modulus1 - 1);\n      uint32_t min BOOST_PREVENT_MACRO_SUBSTITUTION () const {return min_value;}\n      uint32_t max BOOST_PREVENT_MACRO_SUBSTITUTION () const {return max_value;}\n\n      static bool validation(uint32_t x) {\n\treturn x == 831582319;\n      }\n    };\n\n    template <typename Gen>\n    class uniform_01_wrapper {\n      Gen& gen;\n\n      public:\n      uniform_01_wrapper(Gen& gen): gen(gen) {}\n\n      double operator()() const {return boost::uniform_01<double>()(gen);}\n    };\n\n} } } // end namespace boost::graph::random\n\n#endif // BOOST_SPLITTABLE_ECUYER1988_HPP\n", "meta": {"hexsha": "bee0ca3865cb77b5305b7b56d930e0700b58a3ff", "size": 4636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/random/splittable_ecuyer1988.hpp", "max_stars_repo_name": "thejkane/AGM", "max_stars_repo_head_hexsha": "4d5cfe9522461d207ceaef7d90c1cd10ce9b469c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T10:22:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T10:22:04.000Z", "max_issues_repo_path": "boost/graph/random/splittable_ecuyer1988.hpp", "max_issues_repo_name": "thejkane/AGM", "max_issues_repo_head_hexsha": "4d5cfe9522461d207ceaef7d90c1cd10ce9b469c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/graph/random/splittable_ecuyer1988.hpp", "max_forks_repo_name": "thejkane/AGM", "max_forks_repo_head_hexsha": "4d5cfe9522461d207ceaef7d90c1cd10ce9b469c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6478873239, "max_line_length": 132, "alphanum_fraction": 0.7031924072, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4466005742445046}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MTL_MAX_OF_SUMS_INCLUDE\n#define MTL_MAX_OF_SUMS_INCLUDE\n\n#include <boost/numeric/mtl/concept/magnitude.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/linear_algebra/operators.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/range_generator.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#include <numeric>\n#include <cmath>\n\n\nnamespace mtl { namespace impl {\n\n// We need property map of the minor index \ntemplate <typename Matrix, typename MinorIndex>\ntypename RealMagnitude<typename Collection<Matrix>::value_type>::type\ninline max_of_sums(const Matrix& matrix, bool aligned, MinorIndex minor_index, std::size_t dim2)\n{\n    vampir_trace<2012> tracer;\n    using std::max; using std::abs; using math::zero;\n\n    typedef typename Collection<Matrix>::value_type   value_type;\n    typedef typename RealMagnitude<value_type>::type  real_type;\n    real_type ref, my_zero= zero(ref);\n\n    // If matrix is empty then the result is the identity from the default-constructed value\n    if (num_rows(matrix) == 0 || num_cols(matrix) == 0)\n\treturn my_zero;\n\n    typedef typename traits::range_generator<tag::major, Matrix>::type     cursor_type;\n    typedef typename traits::range_generator<tag::nz, cursor_type>::type   icursor_type;\n    typename traits::const_value<Matrix>::type                             value(matrix); \n\n    if (aligned) {\n\treal_type maxv= my_zero;\n\tfor (cursor_type cursor = begin<tag::major>(matrix), cend = end<tag::major>(matrix); cursor != cend; ++cursor) {\n\t    real_type sum= my_zero;\n\t    for (icursor_type icursor = begin<tag::nz>(cursor), icend = end<tag::nz>(cursor); icursor != icend; ++icursor)\n\t\tsum+= abs(value(*icursor));\n\t    maxv= max(maxv, sum);\n\t}\n\treturn maxv;\n    }\n\n    // If matrix has other orientation, we compute all sums in a vector\n    dense_vector<real_type>   sums(dim2, my_zero);\n    for (cursor_type cursor = begin<tag::major>(matrix), cend = end<tag::major>(matrix); cursor != cend; ++cursor)\n\tfor (icursor_type icursor = begin<tag::nz>(cursor), icend = end<tag::nz>(cursor); icursor != icend; ++icursor)\n\t    sums[minor_index(*icursor)]+= abs(value(*icursor));\n    // replace by mtl::accumulate<8>\n    return std::accumulate(sums.begin(), sums.end(), my_zero, math::max<real_type>());\n}\n\n\n}} // namespace mtl::impl\n\n#endif // MTL_MAX_OF_SUMS_INCLUDE\n", "meta": {"hexsha": "43907d5cba8abda3084247de82c78e8e0ee39787", "size": 2929, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/max_of_sums.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/mtl/operation/max_of_sums.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/mtl/operation/max_of_sums.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 39.0533333333, "max_line_length": 115, "alphanum_fraction": 0.7132127006, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.4465309490732592}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_GaussKronrodQuadratureSetTraits.hpp\n//! \\author Luke Kersting\n//! \\brief  Gauss-Kronrod quadrature set traits\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_GAUSS_KRONROD_QUADRATURE_SET_TRAITS_HPP\n#define UTILITY_GAUSS_KRONROD_QUADRATURE_SET_TRAITS_HPP\n\n// Boost Includes\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_floating_point.hpp>\n\n// FRENSIE Includes\n#include \"Utility_GaussKronrodQuadratureSetTraitsDecl.hpp\"\n#include \"Utility_IsFloatingPoint.hpp\"\n\nnamespace Utility{\n\n// Gauss-Kronrod quadrature set traits 15 point rule\ntemplate<typename FloatType>\nstruct GaussKronrodQuadratureSetTraits<15,FloatType,typename boost::enable_if<IsFloatingPoint<FloatType> >::type>\n{\n  // Valid rule\n  static const bool valid_rule = true;\n\n  // Gauss quadrature weights\n  static const std::vector<FloatType> gauss_weights;\n\n  // Kronrod quadrature weights\n  static const std::vector<FloatType> kronrod_weights;\n\n  // Kronrod quadrature abscissae\n  static const std::vector<FloatType> kronrod_abscissae;\n\nprivate:\n\n  // Initialize the gauss weight array\n  static std::vector<FloatType> initializeGaussWeights();\n\n  // Initialize the kronrod weight array\n  static std::vector<FloatType> initializeKronrodWeights();\n\n  // Initialize the gauss weight array\n  static std::vector<FloatType> initializeKronrodAbscissae();\n};\n\n// Gauss-Kronrod quadrature set traits 21 point rule\ntemplate<typename FloatType>\nstruct GaussKronrodQuadratureSetTraits<21,FloatType,typename boost::enable_if<IsFloatingPoint<FloatType> >::type>\n{\n  // Valid rule\n  static const bool valid_rule = true;\n\n  // Gauss quadrature weights\n  static const std::vector<FloatType> gauss_weights;\n\n  // Kronrod quadrature weights\n  static const std::vector<FloatType> kronrod_weights;\n\n  // Kronrod quadrature abscissae\n  static const std::vector<FloatType> kronrod_abscissae;\n\nprivate:\n\n  // Initialize the gauss weight array\n  static std::vector<FloatType> initializeGaussWeights();\n\n  // Initialize the kronrod weight array\n  static std::vector<FloatType> initializeKronrodWeights();\n\n  // Initialize the gauss weight array\n  static std::vector<FloatType> initializeKronrodAbscissae();\n};\n\n// Gauss-Kronrod quadrature set traits 31 point rule\ntemplate<typename FloatType>\nstruct GaussKronrodQuadratureSetTraits<31,FloatType,typename boost::enable_if<IsFloatingPoint<FloatType> >::type>\n{\n  // Valid rule\n  static const bool valid_rule = true;\n\n  // Gauss quadrature weights\n  static const std::vector<FloatType> gauss_weights;\n\n  // Kronrod quadrature weights\n  static const std::vector<FloatType> kronrod_weights;\n\n  // Kronrod quadrature abscissae\n  static const std::vector<FloatType> kronrod_abscissae;\n\nprivate:\n\n  // Initialize the gauss weight array\n  static std::vector<FloatType> initializeGaussWeights();\n\n  // Initialize the kronrod weight array\n  static std::vector<FloatType> initializeKronrodWeights();\n\n  // Initialize the gauss weight array\n  static std::vector<FloatType> initializeKronrodAbscissae();\n};\n\n// Gauss-Kronrod quadrature set traits 41 point rule\ntemplate<typename FloatType>\nstruct GaussKronrodQuadratureSetTraits<41,FloatType,typename boost::enable_if<IsFloatingPoint<FloatType> >::type>\n{\n  // Valid rule\n  static const bool valid_rule = true;\n\n  // Gauss quadrature weights\n  static const std::vector<FloatType> gauss_weights;\n\n  // Kronrod quadrature weights\n  static const std::vector<FloatType> kronrod_weights;\n\n  // Kronrod quadrature abscissae\n  static const std::vector<FloatType> kronrod_abscissae;\n\nprivate:\n\n  // Initialize the gauss weight array\n  static std::vector<FloatType> initializeGaussWeights();\n\n  // Initialize the kronrod weight array\n  static std::vector<FloatType> initializeKronrodWeights();\n\n  // Initialize the gauss weight array\n  static std::vector<FloatType> initializeKronrodAbscissae();\n};\n\n// Gauss-Kronrod quadrature set traits 51 point rule\ntemplate<typename FloatType>\nstruct GaussKronrodQuadratureSetTraits<51,FloatType,typename boost::enable_if<IsFloatingPoint<FloatType> >::type>\n{\n  // Valid rule\n  static const bool valid_rule = true;\n\n  // Gauss quadrature weights\n  static const std::vector<FloatType> gauss_weights;\n\n  // Kronrod quadrature weights\n  static const std::vector<FloatType> kronrod_weights;\n\n  // Kronrod quadrature abscissae\n  static const std::vector<FloatType> kronrod_abscissae;\n\nprivate:\n\n  // Initialize the gauss weight array\n  static std::vector<FloatType> initializeGaussWeights();\n\n  // Initialize the kronrod weight array\n  static std::vector<FloatType> initializeKronrodWeights();\n\n  // Initialize the gauss weight array\n  static std::vector<FloatType> initializeKronrodAbscissae();\n};\n\n// Gauss-Kronrod quadrature set traits 61 point rule\ntemplate<typename FloatType>\nstruct GaussKronrodQuadratureSetTraits<61,FloatType,typename boost::enable_if<IsFloatingPoint<FloatType> >::type>\n{\n  // Valid rule\n  static const bool valid_rule = true;\n\n  // Gauss quadrature weights\n  static const std::vector<FloatType> gauss_weights;\n\n  // Kronrod quadrature weights\n  static const std::vector<FloatType> kronrod_weights;\n\n  // Kronrod quadrature abscissae\n  static const std::vector<FloatType> kronrod_abscissae;\n\nprivate:\n\n  // Initialize the gauss weight array\n  static std::vector<FloatType> initializeGaussWeights();\n\n  // Initialize the kronrod weight array\n  static std::vector<FloatType> initializeKronrodWeights();\n\n  // Initialize the gauss weight array\n  static std::vector<FloatType> initializeKronrodAbscissae();\n};\n\n} // end Utility namespace\n\n//---------------------------------------------------------------------------//\n// Template Includes\n//---------------------------------------------------------------------------//\n\n#include \"Utility_GaussKronrodQuadratureSetTraits_def.hpp\"\n\n//---------------------------------------------------------------------------//\n\n#endif // end UTILITY_GAUSS_KRONROD_QUADRATURE_SET_TRAITS_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_GaussKronrodQuadratureSetTraits.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "657692ecb3bfc62299cd033ca7e3e79533410f2e", "size": 6283, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/integrator/src/Utility_GaussKronrodQuadratureSetTraits.hpp", "max_stars_repo_name": "bam241/FRENSIE", "max_stars_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-14T19:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T17:44:09.000Z", "max_issues_repo_path": "packages/utility/integrator/src/Utility_GaussKronrodQuadratureSetTraits.hpp", "max_issues_repo_name": "bam241/FRENSIE", "max_issues_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T19:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T03:36:08.000Z", "max_forks_repo_path": "packages/utility/integrator/src/Utility_GaussKronrodQuadratureSetTraits.hpp", "max_forks_repo_name": "bam241/FRENSIE", "max_forks_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T18:59:51.000Z", "avg_line_length": 30.6487804878, "max_line_length": 113, "alphanum_fraction": 0.7130351743, "num_tokens": 1439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.44653094080402944}}
{"text": "/*\n *  model_gmm.cpp\n *\n *  Created by Ania M. Kedzierska on 11/11/11.\n *  Copyright 2011 Politecnic University of Catalonia, Center for Genomic Regulation.  This is program can be redistributed, modified or else as given by the terms of the GNU General Public License.\n *\n */\n\n\n#include \"model_gmm.h\"\n#include \"model_ssm.h\"\n#include \"random.h\"\n#include \"parameters.h\"\n#include <cstdlib>\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include \"expm.hpp\"\n\n#include \"miscelania.h\"\n\n#include <stdexcept>\n\n\n//////////////////////////////////////////////////////////////////\n// This file implements functions specific to the GMM model\n//////////////////////////////////////////////////////////////////\n\n// Fills in a GMM row\nvoid GMM_row(double a, double b, double c, double d, long r, TMatrix &tm) {\n  tm[r][0] = a;\n  tm[r][1] = b;\n  tm[r][2] = c;\n  tm[r][3] = d;\n}\n\n\n\nlong GMM_matrix_structure(long i, long j) {\n  return 4*i + j;\n}\n\n\nlong GMM_root_structure(long i) {\n  return i;\n}\n\nPermutation GMM_perm(long a, long b, long c, long d) {\n  Permutation p;\n  p.resize(4);\n  p[0] = a; p[1] = b; p[2] = c; p[3] = d;\n  return p;\n}\n\nvoid GMM_list_permutations(std::list<Permutation> &L) {\n  L.clear();\n  L.push_back(GMM_perm(0,1,2,3));\n  L.push_back(GMM_perm(0,1,3,2));\n  L.push_back(GMM_perm(0,2,1,3));\n  L.push_back(GMM_perm(0,2,3,1));\n  L.push_back(GMM_perm(0,3,1,2));\n  L.push_back(GMM_perm(0,3,2,1));\n\n  L.push_back(GMM_perm(1,0,2,3));\n  L.push_back(GMM_perm(1,0,3,2));\n  L.push_back(GMM_perm(1,2,0,3));\n  L.push_back(GMM_perm(1,2,3,0));\n  L.push_back(GMM_perm(1,3,0,2));\n  L.push_back(GMM_perm(1,3,2,0));\n\n  L.push_back(GMM_perm(2,0,1,3));\n  L.push_back(GMM_perm(2,0,3,1));\n  L.push_back(GMM_perm(2,1,0,3));\n  L.push_back(GMM_perm(2,1,3,0));\n  L.push_back(GMM_perm(2,3,0,1));\n  L.push_back(GMM_perm(2,3,1,0));\n\n  L.push_back(GMM_perm(3,0,1,2));\n  L.push_back(GMM_perm(3,0,2,1));\n  L.push_back(GMM_perm(3,1,0,2));\n  L.push_back(GMM_perm(3,1,2,0));\n  L.push_back(GMM_perm(3,2,0,1));\n  L.push_back(GMM_perm(3,2,1,0));\n}\n\n\n\n// Computes the mle for the transition matrix of a given edge from the\n// the marginalization of the counts on that edge.\n// N is a matrix representing the counts on that edge\n// tm is the matrix where the mle is stored. tm must be a stochastic matrix\nvoid GMM_mle_edge(TMatrix &N, TMatrix &tm) {\n    double s[4];\n    long i,j;\n\n    for (i=0; i < 4; i++) {\n      s[i] = 0;\n      for(j=0; j < 4; j++) {\n        s[i] = s[i] + N[i][j];\n      }\n    }\n\n    tm[0][0] = N[0][0] / s[0];\n    tm[0][1] = N[0][1] / s[0];\n    tm[0][2] = N[0][2] / s[0];\n    tm[0][3] = N[0][3] / s[0];\n\n    tm[1][0] = N[1][0] / s[1];\n    tm[1][1] = N[1][1] / s[1];\n    tm[1][2] = N[1][2] / s[1];\n    tm[1][3] = N[1][3] / s[1];\n\n    tm[2][0] = N[2][0] / s[2];\n    tm[2][1] = N[2][1] / s[2];\n    tm[2][2] = N[2][2] / s[2];\n    tm[2][3] = N[2][3] / s[2];\n\n    tm[3][0] = N[3][0] / s[3];\n    tm[3][1] = N[3][1] / s[3];\n    tm[3][2] = N[3][2] / s[3];\n    tm[3][3] = N[3][3] / s[3];\n}\n\n// Computes the mle for the root distribution of a given edge from the\n// marginalization of the counts to the root node.\n// s is a vector representing the counts on the root\n// r is a vector where the root distribution is stored.\nvoid GMM_mle_root(Root &s, Root &r) {\n  long i;\n  double sum;\n  sum = s[0] + s[1] + s[2] + s[3];\n\n  for (i=0; i < 4; i++) {\n    r[i] = s[i] / sum;\n  }\n}\n\n// Uniform random stochastic vector of length 3.\nvoid GMM_random_stochastic_vector3(std::vector<double> &v) {\n  v[1] = uniform_real(0,1);\n  v[2] = uniform_real(0,1);\n\n  if (v[1] + v[2] > 1) {\n    v[1] = 1 - v[1];\n    v[2] = 1 - v[2];\n  }\n\n  v[0] = 1 - v[1] - v[2];\n}\n\n// Uniform random stochastic vector of length 4.\nvoid GMM_random_stochastic_vector4(std::vector<double> &v) {\n  double s;\n\n  // A uniform point with x1 + ... + x3 <= 1 is generated\n  // by producing a point with x1 + ... + x3 = 1 and scaling\n  // by s, s is distributed according to f(x) = 3x^2 (cdf is F(x)=x^3).\n  GMM_random_stochastic_vector3(v);\n\n  s = uniform_real(0,1);\n  s = s*s*s;\n\n  for (long i=0; i < 3; i++) {\n    v[i] = s*v[i];\n  }\n  v[3] = 1 - s;\n}\n\n\n// Produces a random GMM root distribution.\nvoid GMM_random_root(Root &r) {\n  GMM_random_stochastic_vector4(r);\n}\n\n// Produces a random GMM transition matrix\nvoid GMM_random_edge(TMatrix &tm) {\n  GMM_random_stochastic_vector4(tm[0]);\n  GMM_random_stochastic_vector4(tm[1]);\n  GMM_random_stochastic_vector4(tm[2]);\n  GMM_random_stochastic_vector4(tm[3]);\n}\n\n\nvoid GMM_random_rate_matrix(double tr, TMatrix &Q) {\n  std::vector<double> v;\n  v.resize(Q.size());\n\n  // Fill in the diagonal\n  GMM_random_stochastic_vector4(v);\n  for(long i=0; i < 4; i++) {\n    Q[i][i] = tr*v[i];\n  }\n\n  // Complete the rows.\n  long k;\n  for(long i=0; i < 4; i++) {\n    GMM_random_stochastic_vector3(v);\n    k=0;\n    for(long j=0; j < 4; j++) {\n      if (j == i) continue;\n      Q[i][j] = -Q[i][i] * v[k];\n      k++;\n    }\n  }\n}\n\n// translating transition matrix to 'our' format\nvoid GMM_matrix_exponential(TMatrix &Q, TMatrix &A) {\n  using namespace boost::numeric;\n\n  ublas::matrix<double> QQ(4,4);\n  ublas::matrix<double> AA(4,4);\n\n  for(unsigned long i = 0; i < Q.size(); i++) {\n    for(unsigned long j = 0; j < Q.size(); j++) {\n      QQ(i,j) = Q[i][j];\n    }\n  }\n\n  AA = expm_pad(QQ);\n\n  for(unsigned long i = 0; i < Q.size(); i++) {\n    for(unsigned long j = 0; j < Q.size(); j++) {\n      A[i][j] = AA(i,j);\n    }\n  }\n}\n\n\n// Random GMM transition matrix of a given branch length\nvoid GMM_random_edge_length(double len, TMatrix &tm) {\n  double t;\n  TMatrix Q, A, B;\n  Q.resize(tm.size());\n  A.resize(tm.size());\n  B.resize(tm.size());\n  for(unsigned long l=0; l < tm.size(); l++) {\n    Q[l].resize(tm.size());\n    A[l].resize(tm.size());\n    B[l].resize(tm.size());\n  }\n\n  t = uniform_real(-4*len, 0);\n  GMM_random_rate_matrix(t, Q);\n  GMM_matrix_exponential(Q, A);\n\n  SSM_random_edge_length(len + t/4, B);\n\n\n  for(long i = 0; i < 4; i++) {\n    for(long j=0; j < 4; j++) {\n      tm[i][j] = 0;\n      for(long k=0; k < 4; k++) {\n        tm[i][j] = tm[i][j] + B[i][k]*A[k][j];\n      }\n    }\n  }\n}\n\n\n\n// Generates a biologically meaningful GMM matrix (Chang's DLC condition)\nvoid GMM_random_edge_bio_length(double len, TMatrix &tm) {\n  TMatrix tmaux;\n  long j, k;\n  Permutation p;\n  p.resize(4);\n\n  tmaux.resize(4);\n  for(j=0; j < 4; j++) {\n    tmaux[j].resize(4);\n  }\n\n  // Loop until there is a permutation that puts it into the DLC form.\n  long timeout=0;\n  do {\n    GMM_random_edge_length(len, tmaux);\n\n    p[0] = max_in_col(tmaux, 0);\n    p[1] = max_in_col(tmaux, 1);\n    p[2] = max_in_col(tmaux, 2);\n    p[3] = max_in_col(tmaux, 3);\n\n    timeout++;\n  } while(!(is_permutation(p) && permutation_sign(p) == 1) && (timeout < 1000));\n\n  if (timeout >= 1000) {\n    throw std::length_error(\"ERROR: In sampling for GMM model. Can't generate DLC matrix of length \" );\n  }\n\n  for(j=0; j < 4; j++) {\n    for(k=0; k < 4; k++) {\n      tm[j][k] = tmaux[p[j]][k];\n    }\n  }\n}\n", "meta": {"hexsha": "e9be0575512bc44c579a656b57f2fd3848ec0c01", "size": 7034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/model_gmm.cpp", "max_stars_repo_name": "Algebraicphylogenetics/Empar", "max_stars_repo_head_hexsha": "1c2b4eec4ac0917c65786acf36de4b906d95715c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/model_gmm.cpp", "max_issues_repo_name": "Algebraicphylogenetics/Empar", "max_issues_repo_head_hexsha": "1c2b4eec4ac0917c65786acf36de4b906d95715c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/model_gmm.cpp", "max_forks_repo_name": "Algebraicphylogenetics/Empar", "max_forks_repo_head_hexsha": "1c2b4eec4ac0917c65786acf36de4b906d95715c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3687707641, "max_line_length": 198, "alphanum_fraction": 0.5749218084, "num_tokens": 2572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.44652224662172435}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RWLIBS_ALGORITHMS_QPCONTROLLER_QPSOLVER_HPP\n#define RWLIBS_ALGORITHMS_QPCONTROLLER_QPSOLVER_HPP\n\n/**\n * @file QPSolver.hpp\n */\n\n#include <Eigen/Core>\n\nnamespace rwlibs { namespace algorithms { namespace qpcontroller {\n\n    /**\n     * @brief Class providing an algorithms for solving the quadratic optimization\n     * problem associated with the QPController\n     */\n    class QPSolver\n    {\n      public:\n        /**\n         * @brief Enumeration used to indicate status\n         */\n        enum Status {\n            SUCCESS = 0, /* Solved */\n            SUBOPTIMAL, /* Constraint satisfied but the result may be suboptimal. This may occur due\n                           to round off errors */\n            FAILURE     /* Could not find a solution statisfying all the constraints */\n        };\n\n        /**\n         * Solves the quadratic problem of minimizing 1/2 x^T.G.x+d^T.x subject\n         * to A.x>=b The method used is an iterative method from \"Numerical\n         * Optimization\" by Jorge Nocedal and Stephen J. Wright, Springer 1999.\n         * In this implementation we'll require that b<= s.t. x=0 is a feasible\n         * initial value\n         *\n         * \\param G [in] The G matrix. It is required that G is n times n and is\n         * positive semidefinite\n         *\n         * \\param d [in] Vector of length n\n         *\n         * \\param A [in] Matrix used to represent the linear inequality constraints.\n         * The dimensions should be m times n\n         *\n         * \\param b [in] Vector with the lower limit for the constraints. We'll\n         * assume that b<=0. The length of b should be m\n         *\n         * \\param xstart [in] Default start configuration of the iterative algorithm\n         *\n         * \\param status [out] Gives the status of the solving\n         */\n        static Eigen::VectorXd inequalitySolve (const Eigen::MatrixXd& G, const Eigen::VectorXd& d,\n                                                Eigen::MatrixXd& A, const Eigen::VectorXd& b,\n                                                const Eigen::VectorXd& xstart, Status& status);\n\n        // TODO Investigate the possibility of making a hot-start of the\n        // algorithm for better performance\n\n      private:\n        static Eigen::VectorXd getInitialConfig (Eigen::MatrixXd& A, const Eigen::VectorXd& b);\n\n        static Eigen::VectorXd safeApprox (Eigen::MatrixXd& A, const Eigen::VectorXd& b);\n    };\n\n}}}    // namespace rwlibs::algorithms::qpcontroller\n\n#endif    // end include guard\n", "meta": {"hexsha": "2cd5f9eecebdfcb57e27a3810d8b95ce9195c1b8", "size": 3370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rwlibs/algorithms/qpcontroller/QPSolver.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rwlibs/algorithms/qpcontroller/QPSolver.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rwlibs/algorithms/qpcontroller/QPSolver.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.119047619, "max_line_length": 100, "alphanum_fraction": 0.6029673591, "num_tokens": 714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.44625687504310196}}
{"text": "// An RLC bandpass filter using Boost.odeint for simulation and Eigen for circuit manipulation\n// Author: Jeff Trull <edaskel@att.net>\n\n/*\nCopyright (c) 2014 Jeffrey E. Trull\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n#include <iostream>\n#include <array>\n#include <cmath>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\n#include \"mna.hpp\"\n\ntypedef std::array<double, 2> state_t;   // 0 = V_out, 1 = I_L\n\nstruct circuit {\n    circuit(double r, double l, double c) : circuit(r, l, c, 0, true) {}\n\n    circuit(double r, double l, double c,\n            double freq,        // cycles per second for sine wave\n            bool   step=false   // step response instead\n        ) : freq_(boost::math::constants::two_pi<double>() * freq),  // radian/s conversion\n        step_(step) {\n\n        using namespace Eigen;\n\n        typedef Matrix<double, 5, 5> matrix5_t;\n        matrix5_t G = matrix5_t::Zero();\n        matrix5_t C = matrix5_t::Zero();\n\n        // state assignment: 0, 1, 2 = node voltages; 3 = I_L, 4 = I_in\n        stamp_r(G, C, 2, r);\n        stamp_c(G, C, 1, 2, c);\n        stamp_l(G, C, 0, 1, 3, l);     // n1, n2, I_L\n        stamp_i(G, C, 0, 4);           // V_in, I_in\n\n        // input application vector - connects single input to appropriate equation\n        typedef Matrix<double, 5, 1> vector5_t;\n        vector5_t B;\n        B << 0, 0, 0, 0, -1;\n\n        // output extraction vector - connects state element to output\n        Matrix<double, 1, 5> D;\n        D << 0, 0, 1, 0, 0;         // state element idx 2 = V_out\n\n        Matrix<double, 1, 1> E = Matrix<double, 1, 1>::Zero();\n        Matrix<double, 5, 1> DT = D.transpose();\n        auto momentvec = moments(G, C, B, DT, E, 4);\n\n        // Now we have C*dX/dt = -G*X + B*u, and the output is = D * X\n\n        // we could not use Su regularization here because after LU factorization Cprime was\n        // not square (UL elements were 2x3 because one row was -1 times another row)\n        Matrix<double, Dynamic, Dynamic> Gnew, Cnew;\n        Matrix<double, Dynamic, 1> Bnew, Dnew;\n        Matrix<double, 1, 1> Enew;\n        std::tie(Gnew, Cnew, Bnew, Dnew, Enew) = regularize(G, C, B, DT);\n\n        Matrix<double, Dynamic, 1> DNT = Dnew.transpose();\n        momentvec = moments(Gnew, Cnew, Bnew, DNT, E, 4);\n\n        // verify the new C is non-singular\n        assert(Cnew.rows() == Cnew.fullPivLu().rank());\n        // and there is no feedthrough term\n        assert(Enew.isZero());\n\n        // factor Cnew out of our equation by multiplying both sides by Cnew^-1\n        // new equation will be dX/dt = - Cnew^-1 * Gnew * X + Cnew^-1 * Bnew * u\n        drift_term_ = - Cnew.fullPivLu().solve(Gnew);\n        input_term_ =   Cnew.fullPivLu().solve(Bnew);\n\n        // Vout may have been moved in the reduction process, so we must supply a map\n        s2o_        = Dnew;\n\n        // calculate poles of resulting system\n        // they are the eigenvalues of the drift term (a.k.a. the \"system matrix\")\n        auto evs = EigenSolver<MatrixXd>(drift_term_).eigenvalues();\n        std::cerr << \"poles are:\\n\" << std::endl;\n        for (int row = 0; row < drift_term_.rows(); ++row) {\n            // convert to standard frequency (cycles/s) and display\n            std::cerr << evs(row, 0).real() / boost::math::constants::two_pi<double>() << std::endl;\n        }\n        \n\n    }\n\n    double state2output(state_t const& x) const {\n        Eigen::Map<const Eigen::Matrix<double, 2, 1> > xvec(x.data());\n\n        return (s2o_ * xvec)(0, 0);\n    }\n\n    void operator()(state_t const& x, state_t& dxdt, double t) {\n        using namespace Eigen;\n\n        Map<const Matrix<double, 2, 1> > xvec(x.data());\n        Map<Matrix<double, 2, 1> > result(dxdt.data());\n        \n        Matrix<double, 1, 1> input;\n        if (step_) {\n            input << 1.0;\n        } else {\n            // calculate current value of sine wave input\n            input << std::sin(freq_ * t);\n        }\n\n        result = drift_term_ * xvec + input_term_ * input;\n\n    }\n\nprivate:\n    Eigen::MatrixXd drift_term_;            // connects current state to development over time\n    Eigen::MatrixXd input_term_;            // connects input to development\n    Eigen::Matrix<double, 1, Eigen::Dynamic> s2o_; // transforms state to output\n    double freq_;                           // remembers frequency for calculating input\n    bool   step_;                           // indicates using step function instead of sine wave\n};\n\nint main() {\n    using namespace boost::numeric::odeint;\n    const double freq = 50e3;\n    circuit ckt(100.0, 20e-6, 20e-9, freq);\n    state_t x{0.0, 0.0};                    // initial conditions\n\n    integrate( ckt, x, 0.0, 10/freq, 0.1e-6,  // time range and increment\n               [ckt,freq](state_t const& x, double t) {\n                   double inp = std::sin(freq*boost::math::constants::two_pi<double>()*t);\n                   std::cout << t << \" \" << inp << \" \" << ckt.state2output(x) << std::endl;\n               });\n}\n", "meta": {"hexsha": "5d63e7720be17d7da67d553c095d9886742c5a14", "size": 6067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bandpass.cpp", "max_stars_repo_name": "jefftrull/CktSimLightningTalk", "max_stars_repo_head_hexsha": "3eb582da43149c5efa8930fc0576f025cb7c72fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T10:52:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-03T00:49:12.000Z", "max_issues_repo_path": "bandpass.cpp", "max_issues_repo_name": "jefftrull/CktSimLightningTalk", "max_issues_repo_head_hexsha": "3eb582da43149c5efa8930fc0576f025cb7c72fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bandpass.cpp", "max_forks_repo_name": "jefftrull/CktSimLightningTalk", "max_forks_repo_head_hexsha": "3eb582da43149c5efa8930fc0576f025cb7c72fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3961038961, "max_line_length": 100, "alphanum_fraction": 0.6116696885, "num_tokens": 1644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4462568686006788}}
{"text": "#include <boost/python.hpp>\n#include <numpy/arrayobject.h>\n\n#include <cassert>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <numpy_eigen.h>\n#include <vector>\n#include <iostream>\n\nPyObject* ewald_sum(const int &NLa, const double &CLa, const int &NSr, const double &CSr, PyObject *nV, const int &Nxy, const int &Nz)\n{\n    assert(((PyArrayObject *)nV)->dimensions[0] == NLa + NSr);\n    import_array1(NULL);\n    double sigma = M_PI;\n    int N = NLa + NSr;\n    double *C = new double[2*N],\n           *pt_nV = (double *) PyArray_DATA((PyArrayObject *) nV);\n    double *x = new double[2*N],\n           *y = new double[2*N],\n           *z = new double[2*N],\n           *Vsi = new double[N];\n    std::complex<double>  *Vli = new std::complex<double>[N];\n    double sum_nV = 0.;\n    for (int i = 0; i < N; ++i)\n        sum_nV += pt_nV[i];\n\n    for (int i = 0; i < N; ++i) {\n        C[i] = pt_nV[i]/sum_nV * (-NLa*CLa - NSr*CSr);\n        C[N+i] = (i < NLa) ? CLa : CSr;\n        x[i] = y[i] = 0.;\n        x[N+i] = y[N+i] = 0.5;\n        z[i] = double(i);\n        z[N+i] = -0.5+double(i);\n        Vsi[i] = 0.;\n        Vli[i] = std::complex<double>(0., 0.);\n    }\n\n\n    double e_charge = -1.;\n    int Nx = Nxy, Ny = Nxy;\n    double *R = new double[2*N],\n           kv[3], ksquare = 0.;\n\n    for (int i = 0; i < N; ++i) \n        for (int m = -Nx; m < Nx; ++m) \n            for (int n = -Ny; n < Ny; ++n) \n                for (int l = - Nz; l < Nz; ++l) {\n                    for (int k = 0; k < 2*N; ++k)\n                        R[k] = sqrt(pow(m+x[k], 2) + pow(n+y[k],2) + pow(N*l+z[i]-z[k], 2));\n                    // for short-range terms\n                    if (m == 0 and n == 0 and l == 0) {\n                        for (int k = 0; k < 2*N; ++k)\n                            if (k != i)\n                                Vsi[i] += e_charge*C[k] / R[k] * erfc(R[k]/sqrt(2)/sigma);\n                        continue;\n                    }\n                    for (int k = 0; k < 2*N; ++k)\n                        Vsi[i] += e_charge * C[k] / R[k] * erfc(R[k]/sqrt(2)/sigma);\n                    \n                    // for long-range terms\n                    kv[0] = 2*M_PI*n;\n                    kv[1] = 2*M_PI*m;\n                    kv[2] = 2*M_PI/N*l;\n                    ksquare = pow(kv[0], 2) + pow(kv[1], 2) + pow(kv[2], 2);\n                    for (int k = 0; k < 2*N; ++k) \n                        Vli[i] += 4*M_PI/N * e_charge*C[k] / ksquare * \n                            exp(std::complex<double>(0., -kv[0]*x[k] - kv[1]*y[k] + kv[2]*(z[i] - z[k]))) * exp(-pow(sigma,2)*ksquare/2.);\n                }\n    npy_intp Nconvert = npy_intp(N);\n    PyArrayObject *result = (PyArrayObject *)PyArray_SimpleNew(1, &Nconvert, NPY_DOUBLE);\n    Py_INCREF(result);\n    double *result_buf = (double *)PyArray_DATA(result);\n    for (int i = 0; i < N; ++i)\n        result_buf[i] = Vsi[i] + Vli[i].real() - e_charge*C[i]*sqrt(2/M_PI)*1./sigma;\n\n    delete[] R;\n    delete[] C;\n    delete[] x;\n    delete[] y;\n    delete[] z;\n    delete[] Vsi;\n    delete[] Vli;\n\n    return PyArray_Return(result);\n}\n\n\nusing namespace Eigen;\n\ntypedef struct {\n    Vector3d r; // position in the unitcell\n    double C;   // ion charge\n    double ne;  // electron occupation \n    double V;   // dimensionless electric potential (whose unit is smt like V :)\n} AtomInfo;\ntypedef std::vector<AtomInfo> UnitCell;\n\nvoid general_ewald_sum(UnitCell &uc, const Vector3d &a1, const Vector3d &a2, const Vector3d &a3, const Vector3i &Rcutoff);\n\n\nPyObject* new_ewald_sum(const int &NLa, const double &CLa, const int &NSr, const double &CSr, PyObject *nVpy, const int &Nxy, const int &Nz)\n{\n    try {\n        int N = NLa + NSr;\n        VectorXd nV;\n        numpy::from_numpy(nVpy, nV);\n\n        UnitCell uc(2*N);\n        for (int i = 0; i < N; ++i) {\n            uc[2*i].C = (i < NLa) ? CLa : CSr;\n            uc[2*i].ne = 0;\n            uc[2*i].r << 0.5, 0.5, -0.5 + double(i);\n\n            uc[2*i+1].C = 0;\n            uc[2*i+1].ne = nV(i);\n            uc[2*i+1].r << 0, 0, i;\n        }\n\n        Vector3d a1(1,0,0), a2(0,1,0), a3(0,0,N);\n        Vector3i Rcutoff(Nxy, Nxy, Nz);\n        general_ewald_sum(uc, a1, a2, a3, Rcutoff);\n\n        VectorXd out(N);\n        for (int i = 0; i < N; ++i) \n            out(i) = -uc[2*i+1].V;\n        return numpy::to_numpy(out);\n    } catch (const char *str) {\n        std::cerr << str << std::endl;\n        return Py_None;\n    }\n}\n\n\nvoid general_ewald_sum(UnitCell &uc, const Vector3d &a1, const Vector3d &a2, const Vector3d &a3, const Vector3i &Rcutoff)\n{\n    int N = uc.size();\n    const double sigma = M_PI;\n\n    // renormalize electron occupation\n    double unrenorm_Ne = 0, Ne = 0;\n    for (UnitCell::iterator it = uc.begin(); it < uc.end(); ++it) {\n        unrenorm_Ne += it->ne;\n        Ne += it->C;\n    }\n    for (UnitCell::iterator it = uc.begin(); it < uc.end(); ++it) \n        it->ne *= Ne/unrenorm_Ne;\n\n    // get reciprocal vectors\n    Vector3d b1, b2, b3;\n    double uc_vol = a1.dot(a2.cross(a3));\n    b1 = 2*M_PI*a2.cross(a3)/uc_vol;\n    b2 = 2*M_PI*a3.cross(a1)/uc_vol;\n    b3 = 2*M_PI*a1.cross(a2)/uc_vol;\n    \n    // Ewald sum\n    double Vs, Vl;\n    Vector3d k;\n    for (int id = 0; id < N; ++id) {\n        Vs = 0; Vl = 0;\n        for (int m = -Rcutoff[0]; m < Rcutoff[0]; ++m)\n            for (int n = -Rcutoff[1]; n < Rcutoff[1]; ++n)\n                for (int l = -Rcutoff[2]; l < Rcutoff[2]; ++l) {\n                    k = n*b1 + m*b2 + l*b3;\n                    double ksquare = k.dot(k);\n                    for (int i = 0; i < N; ++i) {\n                        double dR = (uc[id].r - (uc[i].r + m*a1 + n*a2 + l*a3)).norm();\n                        // for long-range terms\n                        if ( !(m == 0 && n == 0 && l == 0) )\n                            Vl += 4*M_PI/uc_vol*(uc[i].C-uc[i].ne)/ksquare * cos(k.dot(uc[id].r-uc[i].r)) * exp(-pow(sigma,2)*ksquare/2.);\n                        \n                        // for short-range terms\n                        if ( !(m == 0 && n == 0 && l == 0 && i == id) )\n                            Vs += (uc[i].C - uc[i].ne) / dR * erfc(dR/sqrt(2)/sigma);\n                    }\n                }\n        uc[id].V = Vs + Vl - (uc[id].C - uc[id].ne)*sqrt(2/M_PI)/sigma;\n    }\n}\n\n", "meta": {"hexsha": "da6090990adbdd1a09561ae5fbe9bcad0b0d99db", "size": 6248, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppext/others.cpp", "max_stars_repo_name": "hungdt/scf_dmft", "max_stars_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-06-05T17:44:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:55:13.000Z", "max_issues_repo_path": "cppext/others.cpp", "max_issues_repo_name": "hungdt/scf_dmft", "max_issues_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppext/others.cpp", "max_forks_repo_name": "hungdt/scf_dmft", "max_forks_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3296703297, "max_line_length": 140, "alphanum_fraction": 0.4564660691, "num_tokens": 2092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594354, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.44625564664273365}}
{"text": "/****************************\n * 题目：给定一组世界坐标系下的3D点(p3d.txt)以及它在相机中对应的坐标(p2d.txt)，以及相机的内参矩阵。\n * 使用bundle adjustment 方法（g2o库实现）来估计相机的位姿T。初始位姿T为单位矩阵。\n *\n* 本程序学习目标：\n * 熟悉g2o库编写流程，熟悉顶点定义方法。\n *\n * 公众号：计算机视觉life。发布于公众号旗下知识星球：从零开始学习SLAM\n * 时间：2019.02\n****************************/\n\n#include <vector>\n#include <fstream>\n#include <iostream>\n#include <opencv2/core/core.hpp>\n\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n\nusing namespace Eigen;\n\nusing namespace cv;\nusing namespace std;\n\n\nstring p3d_file = \"/home/lab-307/LIO-SAM_ws/src/Scout-LIO/test/data/p3d.txt\";\nstring p2d_file = \"/home/lab-307/LIO-SAM_ws/src/Scout-LIO/test/data/p2d.txt\";\n\n\n//// 自定义顶点，6DOF的姿态\nclass myVertex : public g2o::BaseVertex<6, g2o::SE3Quat>{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    myVertex() = default;\n    bool read(std::istream& is) override{};\n    bool write(std::ostream& os) const override{};\n    void setToOriginImpl() override {\n        //// 初始值设置为 SE3单位矩阵\n        _estimate = g2o::SE3Quat();\n    }\n\n    void oplusImpl(const number_t* update_) override {\n        Eigen::Map<const g2o::Vector6> update(update_);\n        setEstimate(g2o::SE3Quat::exp(update)*estimate());        //更新方式\n    }\n};\n\n\n//// 自定义边\nclass myEdge: public g2o::BaseBinaryEdge<2, g2o::Vector2 , g2o::VertexSBAPointXYZ, g2o::VertexSE3Expmap>\n{\npublic:\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    myEdge() = default;\n    bool read(istream& in) override{};\n    bool write(ostream& out) const override{};\n    void computeError() override\n    {\n        const g2o::VertexSE3Expmap* v1 = static_cast<const g2o::VertexSE3Expmap*>(_vertices[1]);\n        const g2o::VertexSBAPointXYZ* v2 = static_cast<const g2o::VertexSBAPointXYZ*>(_vertices[0]);\n        const g2o::CameraParameters * cam\n                = static_cast<const g2o::CameraParameters *>(parameter(0));\n        g2o::Vector2 obs(_measurement);\n        _error = obs-cam->cam_map(v1->estimate().map(v2->estimate()));\n    }\n\n    void linearizeOplus() override\n    {\n        g2o::VertexSE3Expmap * vj = static_cast<g2o::VertexSE3Expmap *>(_vertices[1]);\n        g2o::SE3Quat T(vj->estimate());\n        g2o::VertexSBAPointXYZ* vi = static_cast<g2o::VertexSBAPointXYZ*>(_vertices[0]);\n        g2o::Vector3 xyz = vi->estimate();\n        g2o::Vector3 xyz_trans = T.map(xyz);\n\n        double x = xyz_trans[0];\n        double y = xyz_trans[1];\n        double z = xyz_trans[2];\n        double z_2 = z*z;\n\n        const g2o::CameraParameters * cam = static_cast<const g2o::CameraParameters *>(parameter(0));\n\n        Matrix<double,2,3,Eigen::ColMajor> tmp;\n        tmp(0,0) = cam->focal_length;\n        tmp(0,1) = 0;\n        tmp(0,2) = -x/z*cam->focal_length;\n\n        tmp(1,0) = 0;\n        tmp(1,1) = cam->focal_length;\n        tmp(1,2) = -y/z*cam->focal_length;\n\n        _jacobianOplusXi =  -1./z * tmp * T.rotation().toRotationMatrix();\n\n        _jacobianOplusXj(0,0) =  x*y/z_2 *cam->focal_length;\n        _jacobianOplusXj(0,1) = -(1+(x*x/z_2)) *cam->focal_length;\n        _jacobianOplusXj(0,2) = y/z *cam->focal_length;\n        _jacobianOplusXj(0,3) = -1./z *cam->focal_length;\n        _jacobianOplusXj(0,4) = 0;\n        _jacobianOplusXj(0,5) = x/z_2 *cam->focal_length;\n\n        _jacobianOplusXj(1,0) = (1+y*y/z_2) *cam->focal_length;\n        _jacobianOplusXj(1,1) = -x*y/z_2 *cam->focal_length;\n        _jacobianOplusXj(1,2) = -x/z *cam->focal_length;\n        _jacobianOplusXj(1,3) = 0;\n        _jacobianOplusXj(1,4) = -1./z *cam->focal_length;\n        _jacobianOplusXj(1,5) = y/z_2 *cam->focal_length;\n    }\nprivate:\n    // data\n};\n\n\nvoid bundleAdjustment (\n        const vector<Point3f> points_3d,\n        const vector<Point2f> points_2d,\n        Mat& K,\n        bool useDefaultEdge\n        );\n\n\nint main(int argc, char **argv) {\n\n    bool useDefaultEdge = true;\n    vector< Point3f > p3d;\n    vector< Point2f > p2d;\n\n    Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n\n    // 导入3D点和对应的2D点\n\n    ifstream fp3d(p3d_file);\n    if (!fp3d){\n        cout<< \"No p3d.text file\" << endl;\n        return -1;\n    }\n    else {\n        while (!fp3d.eof()){\n            double pt3[3] = {0};\n            for (auto &p:pt3) {\n                fp3d >> p;\n            }\n            p3d.push_back(Point3f(pt3[0],pt3[1],pt3[2]));\n        }\n    }\n    ifstream fp2d(p2d_file);\n    if (!fp2d){\n        cout<< \"No p2d.text file\" << endl;\n        return -1;\n    }\n    else {\n        while (!fp2d.eof()){\n            double pt2[2] = {0};\n            for (auto &p:pt2) {\n                fp2d >> p;\n            }\n            Point2f p2(pt2[0],pt2[1]);\n            p2d.push_back(p2);\n        }\n    }\n\n    assert(p3d.size() == p2d.size());\n\n    int iterations = 100;\n    double cost = 0, lastCost = 0;\n    int nPoints = p3d.size();\n    cout << \"points: \" << nPoints << endl;\n\n    bundleAdjustment ( p3d, p2d, K , useDefaultEdge);\n    return 0;\n}\n\n\nvoid bundleAdjustment (\n        const vector< Point3f > points_3d,\n        const vector< Point2f > points_2d,\n        Mat& K,\n        bool useDefaultEdge )\n{\n    // creat g2o\n    // new g2o version. Ref:https://www.cnblogs.com/xueyuanaichiyu/p/7921382.html\n\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose 维度为 6, landmark 维度为 3\n    // 第1步：创建一个线性求解器LinearSolver\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>();\n\n    // 第2步：创建 BlockSolver。并用上面定义的线性求解器初始化\n    Block* solver_ptr = new Block (  std::unique_ptr<Block::LinearSolverType>(linearSolver) );\n\n    // 第3步：创建总求解器solver。并从GN, LM, DogLeg 中选一个，再用上述块求解器BlockSolver初始化\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( std::unique_ptr<Block>(solver_ptr) );\n\n    // 第4步：创建稀疏优化器\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm ( solver );\n    optimizer.setVerbose(true);\n//    // old g2o version\n//    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose 维度为 6, landmark 维度为 3\n//    Block::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>(); // 线性方程求解器\n//    Block* solver_ptr = new Block ( linearSolver );     // 矩阵块求解器\n//    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr );\n//    g2o::SparseOptimizer optimizer;\n//    optimizer.setAlgorithm ( solver );\n\n    // 第5步：定义图的顶点和边。并添加到SparseOptimizer中\n\n    // ----------------------开始你的代码：设置并添加顶点，初始位姿为单位矩阵\n\n//    g2o::VertexSE3Expmap *pose = new g2o::VertexSE3Expmap();\n//    pose->setId(0);\n//    pose->setEstimate(g2o::SE3Quat());\n//    optimizer.addVertex(pose);\n    myVertex *pose = new myVertex();\n    pose->setId(0);\n    pose->setEstimate(g2o::SE3Quat());\n    optimizer.addVertex(pose);\n\n    int index = 1;\n    for ( const Point3f p:points_3d )   // landmarks\n    {\n        g2o::VertexSBAPointXYZ *point = new g2o::VertexSBAPointXYZ();\n        point->setId ( index++ );\n        point->setEstimate ( Eigen::Vector3d ( p.x, p.y, p.z ) );\n        point->setMarginalized ( true );\n        optimizer.addVertex ( point );\n    }\n    // ----------------------结束你的代码\n\n    // 设置相机内参\n    g2o::CameraParameters* camera = new g2o::CameraParameters (\n            K.at<double> ( 0,0 ), Eigen::Vector2d ( K.at<double> ( 0,2 ), K.at<double> ( 1,2 ) ), 0);\n    camera->setId ( 0 );\n    optimizer.addParameter ( camera );\n\n    // 设置边\n    if (useDefaultEdge){\n        index = 1;\n        for ( const Point2f p:points_2d )\n        {\n            g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();\n            edge->setId ( index );\n            edge->setVertex ( 0, dynamic_cast<g2o::VertexSBAPointXYZ*> ( optimizer.vertex ( index ) ) );\n            edge->setVertex ( 1, pose );\n            edge->setMeasurement ( Eigen::Vector2d ( p.x, p.y ) );  //设置观测值\n            edge->setParameterId ( 0,0 );\n            edge->setInformation ( Eigen::Matrix2d::Identity() );\n            optimizer.addEdge ( edge );\n            index++;\n        }\n    } else {\n        index = 1;\n        for( const Point2f p:points_2d )\n        {\n            myEdge *XYZ2UV = new myEdge();\n            XYZ2UV->setId(index);\n            XYZ2UV->setVertex ( 0, dynamic_cast<g2o::VertexSBAPointXYZ*> ( optimizer.vertex ( index ) ) );\n            XYZ2UV->setVertex ( 1, pose );\n            XYZ2UV->setMeasurement ( Eigen::Vector2d ( p.x, p.y ) );  //设置观测值\n            XYZ2UV->setParameterId ( 0,0 );\n            XYZ2UV->setInformation ( Eigen::Matrix2d::Identity() );\n            optimizer.addEdge ( XYZ2UV );\n            index++;\n        }\n    }\n\n\n    // 第6步：设置优化参数，开始执行优化\n    optimizer.setVerbose ( false );\n    optimizer.initializeOptimization();\n    optimizer.optimize ( 100 );\n\n    // 输出优化结果\n    cout<< endl <<\"after optimization:\"<<endl;\n    cout<< \"T=\" << endl << Eigen::Isometry3d ( pose->estimate() ).matrix() << endl;\n}\n\n", "meta": {"hexsha": "4b59c028f2655f0be3072f2f191f93dc96aab175", "size": 9066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_BA-3Dto2D.cpp", "max_stars_repo_name": "KUO847219959/Scout-LIO", "max_stars_repo_head_hexsha": "93ea256d575832f3ed3b31086f4a268bb59a7038", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-01T04:00:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:21:42.000Z", "max_issues_repo_path": "test/test_BA-3Dto2D.cpp", "max_issues_repo_name": "KUO847219959/Scout-LIO", "max_issues_repo_head_hexsha": "93ea256d575832f3ed3b31086f4a268bb59a7038", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_BA-3Dto2D.cpp", "max_forks_repo_name": "KUO847219959/Scout-LIO", "max_forks_repo_head_hexsha": "93ea256d575832f3ed3b31086f4a268bb59a7038", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-30T15:36:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T15:36:28.000Z", "avg_line_length": 32.035335689, "max_line_length": 129, "alphanum_fraction": 0.5994926098, "num_tokens": 3068, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.44621735534190565}}
{"text": "\r\n\r\n#include <NTL/LLL.h>\r\n#include <NTL/fileio.h>\r\n\r\n#include <NTL/new.h>\r\n\r\nNTL_START_IMPL\r\n\r\n\r\n\r\n\r\nstatic void RowTransform(vec_ZZ& A, vec_ZZ& B, const ZZ& MU1)\r\n// x = x - y*MU\r\n{\r\n   NTL_ZZRegister(T);\r\n   NTL_ZZRegister(MU);\r\n   long k;\r\n\r\n   long n = A.length();\r\n   long i;\r\n\r\n   MU = MU1;\r\n\r\n   if (MU == 1) {\r\n      for (i = 1; i <= n; i++)\r\n         sub(A(i), A(i), B(i));\r\n\r\n      return;\r\n   }\r\n\r\n   if (MU == -1) {\r\n      for (i = 1; i <= n; i++)\r\n         add(A(i), A(i), B(i));\r\n\r\n      return;\r\n   }\r\n\r\n   if (MU == 0) return;\r\n\r\n   if (NumTwos(MU) >= NTL_ZZ_NBITS) \r\n      k = MakeOdd(MU);\r\n   else\r\n      k = 0;\r\n\r\n\r\n   if (MU.WideSinglePrecision()) {\r\n      long mu1;\r\n      conv(mu1, MU);\r\n\r\n      for (i = 1; i <= n; i++) {\r\n         mul(T, B(i), mu1);\r\n         if (k > 0) LeftShift(T, T, k);\r\n         sub(A(i), A(i), T);\r\n      }\r\n   }\r\n   else {\r\n      for (i = 1; i <= n; i++) {\r\n         mul(T, B(i), MU);\r\n         if (k > 0) LeftShift(T, T, k);\r\n         sub(A(i), A(i), T);\r\n      }\r\n   }\r\n}\r\n\r\nstatic void RowTransform2(vec_ZZ& A, vec_ZZ& B, const ZZ& MU1)\r\n// x = x + y*MU\r\n{\r\n   NTL_ZZRegister(T);\r\n   NTL_ZZRegister(MU);\r\n   long k;\r\n\r\n   long n = A.length();\r\n   long i;\r\n\r\n   MU = MU1;\r\n\r\n   if (MU == 1) {\r\n      for (i = 1; i <= n; i++)\r\n         add(A(i), A(i), B(i));\r\n\r\n      return;\r\n   }\r\n\r\n   if (MU == -1) {\r\n      for (i = 1; i <= n; i++)\r\n         sub(A(i), A(i), B(i));\r\n\r\n      return;\r\n   }\r\n\r\n   if (MU == 0) return;\r\n\r\n   if (NumTwos(MU) >= NTL_ZZ_NBITS) \r\n      k = MakeOdd(MU);\r\n   else\r\n      k = 0;\r\n\r\n   if (MU.WideSinglePrecision()) {\r\n      long mu1;\r\n      conv(mu1, MU);\r\n\r\n      for (i = 1; i <= n; i++) {\r\n         mul(T, B(i), mu1);\r\n         if (k > 0) LeftShift(T, T, k);\r\n         add(A(i), A(i), T);\r\n      }\r\n   }\r\n   else {\r\n      for (i = 1; i <= n; i++) {\r\n         mul(T, B(i), MU);\r\n         if (k > 0) LeftShift(T, T, k);\r\n         add(A(i), A(i), T);\r\n      }\r\n   }\r\n}\r\n\r\nvoid ComputeGS(const mat_ZZ& B, mat_RR& B1, \r\n               mat_RR& mu, vec_RR& b, \r\n               vec_RR& c, long k, const RR& bound, long st, \r\n               vec_RR& buf, const RR& bound2)\r\n{\r\n   long i, j;\r\n   RR s, t, t1;\r\n   ZZ T1;\r\n\r\n   if (st < k) {\r\n      for (i = 1; i < st; i++)\r\n         mul(buf(i), mu(k,i), c(i));\r\n   }\r\n\r\n   for (j = st; j <= k-1; j++) {\r\n      InnerProduct(s, B1(k), B1(j));\r\n\r\n      sqr(t1, s);\r\n      mul(t1, t1, bound);\r\n      mul(t, b(k), b(j));\r\n\r\n      if (t >= bound2 && t >= t1) {\r\n         InnerProduct(T1, B(k), B(j));\r\n         conv(s, T1);\r\n      }\r\n\r\n      clear(t1);\r\n      for (i = 1; i <= j-1; i++) {\r\n         mul(t, mu(j, i), buf(i));\r\n         add(t1, t1, t);\r\n      }\r\n\r\n      sub(t, s, t1);\r\n      buf(j) = t;\r\n      div(mu(k, j), t, c(j));\r\n   }\r\n\r\n\r\n   clear(s);\r\n   for (j = 1; j <= k-1; j++) {\r\n      mul(t, mu(k, j), buf(j));\r\n      add(s, s, t);\r\n   }\r\n\r\n   sub(c(k), b(k), s);\r\n}\r\n\r\nNTL_THREAD_LOCAL static RR red_fudge;\r\nNTL_THREAD_LOCAL static long log_red = 0;\r\n\r\nstatic void init_red_fudge()\r\n{\r\n   log_red = long(0.50*RR::precision());\r\n\r\n   power2(red_fudge, -log_red);\r\n}\r\n\r\nstatic void inc_red_fudge()\r\n{\r\n\r\n   mul(red_fudge, red_fudge, 2);\r\n   log_red--;\r\n\r\n   cerr << \"LLL_RR: warning--relaxing reduction (\" << log_red << \")\\n\";\r\n\r\n   if (log_red < 4)\r\n      ResourceError(\"LLL_RR: can not continue...sorry\");\r\n}\r\n\r\n\r\n\r\n\r\nNTL_THREAD_LOCAL static long verbose = 0;\r\nNTL_THREAD_LOCAL static unsigned long NumSwaps = 0;\r\nNTL_THREAD_LOCAL static double StartTime = 0;\r\nNTL_THREAD_LOCAL static double LastTime = 0;\r\n\r\n\r\n\r\nstatic void LLLStatus(long max_k, double t, long m, const mat_ZZ& B)\r\n{\r\n   cerr << \"---- LLL_RR status ----\\n\";\r\n   cerr << \"elapsed time: \";\r\n   PrintTime(cerr, t-StartTime);\r\n   cerr << \", stage: \" << max_k;\r\n   cerr << \", rank: \" << m;\r\n   cerr << \", swaps: \" << NumSwaps << \"\\n\";\r\n\r\n   ZZ t1;\r\n   long i;\r\n   double prodlen = 0;\r\n\r\n   for (i = 1; i <= m; i++) {\r\n      InnerProduct(t1, B(i), B(i));\r\n      if (!IsZero(t1))\r\n         prodlen += log(t1);\r\n   }\r\n\r\n   cerr << \"log of prod of lengths: \" << prodlen/(2.0*log(2.0)) << \"\\n\";\r\n\r\n   if (LLLDumpFile) {\r\n      cerr << \"dumping to \" << LLLDumpFile << \"...\";\r\n\r\n      ofstream f;\r\n      OpenWrite(f, LLLDumpFile);\r\n      \r\n      f << \"[\";\r\n      for (i = 1; i <= m; i++) {\r\n         f << B(i) << \"\\n\";\r\n      }\r\n      f << \"]\\n\";\r\n\r\n      f.close();\r\n\r\n      cerr << \"\\n\";\r\n   }\r\n\r\n   LastTime = t;\r\n   \r\n}\r\n\r\n\r\n\r\nstatic\r\nlong ll_LLL_RR(mat_ZZ& B, mat_ZZ* U, const RR& delta, long deep, \r\n           LLLCheckFct check, mat_RR& B1, mat_RR& mu, \r\n           vec_RR& b, vec_RR& c, long m, long init_k, long &quit)\r\n{\r\n   long n = B.NumCols();\r\n\r\n   long i, j, k, Fc1;\r\n   ZZ MU;\r\n   RR mu1, t1, t2, cc;\r\n   ZZ T1;\r\n\r\n   RR bound;\r\n\r\n      // we tolerate a 15% loss of precision in computing\r\n      // inner products in ComputeGS.\r\n\r\n   power2(bound, 2*long(0.15*RR::precision()));\r\n\r\n\r\n   RR bound2;\r\n\r\n   power2(bound2, 2*RR::precision());\r\n\r\n\r\n   quit = 0;\r\n   k = init_k;\r\n\r\n   vec_long st_mem;\r\n   st_mem.SetLength(m+2);\r\n   long *st = st_mem.elts();\r\n\r\n   for (i = 1; i < k; i++)\r\n      st[i] = i;\r\n\r\n   for (i = k; i <= m+1; i++)\r\n      st[i] = 1;\r\n\r\n   vec_RR buf;\r\n   buf.SetLength(m);\r\n\r\n   long rst;\r\n   long counter;\r\n\r\n   long trigger_index;\r\n   long small_trigger;\r\n   long cnt;\r\n\r\n   RR half;\r\n   conv(half,  0.5);\r\n   RR half_plus_fudge;\r\n   add(half_plus_fudge, half, red_fudge);\r\n\r\n   long max_k = 0;\r\n   double tt;\r\n\r\n   while (k <= m) {\r\n\r\n      if (k > max_k) {\r\n         max_k = k;\r\n      }\r\n\r\n      if (verbose) {\r\n         tt = GetTime();\r\n\r\n         if (tt > LastTime + LLLStatusInterval)\r\n            LLLStatus(max_k, tt, m, B);\r\n      }\r\n\r\n\r\n      if (st[k] == k)\r\n         rst = 1;\r\n      else\r\n         rst = k;\r\n\r\n      if (st[k] < st[k+1]) st[k+1] = st[k];\r\n      ComputeGS(B, B1, mu, b, c, k, bound, st[k], buf, bound2);\r\n      st[k] = k;\r\n\r\n      counter = 0;\r\n      trigger_index = k;\r\n      small_trigger = 0;\r\n      cnt = 0;\r\n\r\n      do {\r\n         // size reduction\r\n\r\n         counter++;\r\n         if (counter > 10000) {\r\n            cerr << \"LLL_XD: warning--possible infinite loop\\n\";\r\n            counter = 0;\r\n         }\r\n\r\n\r\n         Fc1 = 0;\r\n\r\n         for (j = rst-1; j >= 1; j--) {\r\n            abs(t1, mu(k,j));\r\n            if (t1 > half_plus_fudge) {\r\n\r\n               if (!Fc1) {\r\n                  if (j > trigger_index ||\r\n                      (j == trigger_index && small_trigger)) {\r\n\r\n                     cnt++;\r\n\r\n                     if (cnt > 10) {\r\n                        inc_red_fudge();\r\n                        add(half_plus_fudge, half, red_fudge);\r\n                        cnt = 0;\r\n                     }\r\n                  }\r\n\r\n                  trigger_index = j;\r\n                  small_trigger = (t1 < 4);\r\n               }\r\n\r\n               Fc1 = 1;\r\n   \r\n               mu1 = mu(k,j);\r\n               if (sign(mu1) >= 0) {\r\n                  sub(mu1, mu1, half);\r\n                  ceil(mu1, mu1);\r\n               }\r\n               else {\r\n                  add(mu1, mu1, half);\r\n                  floor(mu1, mu1);\r\n               }\r\n\r\n               if (mu1 == 1) {\r\n                  for (i = 1; i <= j-1; i++)\r\n                     sub(mu(k,i), mu(k,i), mu(j,i));\r\n               }\r\n               else if (mu1 == -1) {\r\n                  for (i = 1; i <= j-1; i++)\r\n                     add(mu(k,i), mu(k,i), mu(j,i));\r\n               }\r\n               else {\r\n                  for (i = 1; i <= j-1; i++) {\r\n                     mul(t2, mu1, mu(j,i));\r\n                     sub(mu(k,i), mu(k,i), t2);\r\n                  }\r\n               }\r\n\r\n   \r\n               conv(MU, mu1);\r\n\r\n               sub(mu(k,j), mu(k,j), mu1);\r\n   \r\n               RowTransform(B(k), B(j), MU);\r\n               if (U) RowTransform((*U)(k), (*U)(j), MU);\r\n            }\r\n         }\r\n\r\n         if (Fc1) {\r\n            for (i = 1; i <= n; i++)\r\n               conv(B1(k, i), B(k, i));\r\n   \r\n            InnerProduct(b(k), B1(k), B1(k));\r\n            ComputeGS(B, B1, mu, b, c, k, bound, 1, buf, bound2);\r\n         }\r\n      } while (Fc1);\r\n\r\n      if (check && (*check)(B(k))) \r\n         quit = 1;\r\n\r\n      if (IsZero(b(k))) {\r\n         for (i = k; i < m; i++) {\r\n            // swap i, i+1\r\n            swap(B(i), B(i+1));\r\n            swap(B1(i), B1(i+1));\r\n            swap(b(i), b(i+1));\r\n            if (U) swap((*U)(i), (*U)(i+1));\r\n         }\r\n\r\n         for (i = k; i <= m+1; i++) st[i] = 1;\r\n\r\n         m--;\r\n         if (quit) break;\r\n         continue;\r\n      }\r\n\r\n      if (quit) break;\r\n\r\n      if (deep > 0) {\r\n         // deep insertions\r\n   \r\n         cc = b(k);\r\n         long l = 1;\r\n         while (l <= k-1) { \r\n            mul(t1, delta, c(l));\r\n            if (t1 > cc) break;\r\n            sqr(t1, mu(k,l));\r\n            mul(t1, t1, c(l));\r\n            sub(cc, cc, t1);\r\n            l++;\r\n         }\r\n   \r\n         if (l <= k-1 && (l <= deep || k-l <= deep)) {\r\n            // deep insertion at position l\r\n   \r\n            for (i = k; i > l; i--) {\r\n               // swap rows i, i-1\r\n               swap(B(i), B(i-1));\r\n               swap(B1(i), B1(i-1));\r\n               swap(mu(i), mu(i-1));\r\n               swap(b(i), b(i-1));\r\n               if (U) swap((*U)(i), (*U)(i-1));\r\n            }\r\n   \r\n            k = l;\r\n            continue;\r\n         }\r\n      } // end deep insertions\r\n\r\n      // test LLL reduction condition\r\n\r\n      if (k <= 1) {\r\n         k++;\r\n      }\r\n      else {\r\n         sqr(t1, mu(k,k-1));\r\n         mul(t1, t1, c(k-1));\r\n         add(t1, t1, c(k));\r\n         mul(t2, delta, c(k-1));\r\n         if (t2 > t1) {\r\n            // swap rows k, k-1\r\n            swap(B(k), B(k-1));\r\n            swap(B1(k), B1(k-1));\r\n            swap(mu(k), mu(k-1));\r\n            swap(b(k), b(k-1));\r\n            if (U) swap((*U)(k), (*U)(k-1));\r\n   \r\n            k--;\r\n            NumSwaps++;\r\n         }\r\n         else {\r\n            k++;\r\n         }\r\n      }\r\n   }\r\n\r\n   if (verbose) {\r\n      LLLStatus(m+1, GetTime(), m, B);\r\n   }\r\n\r\n\r\n   return m;\r\n}\r\n\r\nstatic\r\nlong LLL_RR(mat_ZZ& B, mat_ZZ* U, const RR& delta, long deep, \r\n           LLLCheckFct check)\r\n{\r\n   long m = B.NumRows();\r\n   long n = B.NumCols();\r\n\r\n   long i, j;\r\n   long new_m, dep, quit;\r\n   RR s;\r\n   ZZ MU;\r\n   RR mu1;\r\n\r\n   RR t1;\r\n   ZZ T1;\r\n\r\n   init_red_fudge();\r\n\r\n   if (U) ident(*U, m);\r\n\r\n   mat_RR B1;  // approximates B\r\n   B1.SetDims(m, n);\r\n\r\n\r\n   mat_RR mu;\r\n   mu.SetDims(m, m);\r\n\r\n   vec_RR c;  // squared lengths of Gramm-Schmidt basis vectors\r\n   c.SetLength(m);\r\n\r\n   vec_RR b; // squared lengths of basis vectors\r\n   b.SetLength(m);\r\n\r\n\r\n   for (i = 1; i <=m; i++)\r\n      for (j = 1; j <= n; j++) \r\n         conv(B1(i, j), B(i, j));\r\n\r\n\r\n         \r\n   for (i = 1; i <= m; i++) {\r\n      InnerProduct(b(i), B1(i), B1(i));\r\n   }\r\n\r\n\r\n   new_m = ll_LLL_RR(B, U, delta, deep, check, B1, mu, b, c, m, 1, quit);\r\n   dep = m - new_m;\r\n   m = new_m;\r\n\r\n   if (dep > 0) {\r\n      // for consistency, we move all of the zero rows to the front\r\n\r\n      for (i = 0; i < m; i++) {\r\n         swap(B(m+dep-i), B(m-i));\r\n         if (U) swap((*U)(m+dep-i), (*U)(m-i));\r\n      }\r\n   }\r\n\r\n\r\n   return m;\r\n}\r\n\r\n         \r\n\r\nlong LLL_RR(mat_ZZ& B, double delta, long deep, \r\n            LLLCheckFct check, long verb)\r\n{\r\n   verbose = verb;\r\n   NumSwaps = 0;\r\n   if (verbose) {\r\n      StartTime = GetTime();\r\n      LastTime = StartTime;\r\n   }\r\n\r\n   if (delta < 0.50 || delta >= 1) LogicError(\"LLL_RR: bad delta\");\r\n   if (deep < 0) LogicError(\"LLL_RR: bad deep\");\r\n   RR Delta;\r\n   conv(Delta, delta);\r\n   return LLL_RR(B, 0, Delta, deep, check);\r\n}\r\n\r\nlong LLL_RR(mat_ZZ& B, mat_ZZ& U, double delta, long deep, \r\n           LLLCheckFct check, long verb)\r\n{\r\n   verbose = verb;\r\n   NumSwaps = 0;\r\n   if (verbose) {\r\n      StartTime = GetTime();\r\n      LastTime = StartTime;\r\n   }\r\n\r\n   if (delta < 0.50 || delta >= 1) LogicError(\"LLL_RR: bad delta\");\r\n   if (deep < 0) LogicError(\"LLL_RR: bad deep\");\r\n   RR Delta;\r\n   conv(Delta, delta);\r\n   return LLL_RR(B, &U, Delta, deep, check);\r\n}\r\n\r\n\r\n\r\nNTL_THREAD_LOCAL static vec_RR BKZConstant;\r\n\r\nstatic\r\nvoid ComputeBKZConstant(long beta, long p)\r\n{\r\n   RR c_PI;\r\n   ComputePi(c_PI);\r\n\r\n   RR LogPI = log(c_PI);\r\n\r\n   BKZConstant.SetLength(beta-1);\r\n\r\n   vec_RR Log;\r\n   Log.SetLength(beta);\r\n\r\n\r\n   long i, j, k;\r\n   RR x, y;\r\n\r\n   for (j = 1; j <= beta; j++)\r\n      Log(j) = log(to_RR(j));\r\n\r\n   for (i = 1; i <= beta-1; i++) {\r\n      // First, we compute x = gamma(i/2)^{2/i}\r\n\r\n      k = i/2;\r\n\r\n      if ((i & 1) == 0) { // i even\r\n         x = 0;\r\n         for (j = 1; j <= k; j++)\r\n            x += Log(j);\r\n          \r\n         x = exp(x/k);\r\n\r\n      }\r\n      else { // i odd\r\n         x = 0;\r\n         for (j = k + 2; j <= 2*k + 2; j++)\r\n            x += Log(j);\r\n\r\n         x += 0.5*LogPI - 2*(k+1)*Log(2);\r\n\r\n         x = exp(2*x/i);\r\n      }\r\n\r\n      // Second, we compute y = 2^{2*p/i}\r\n\r\n      y = exp(-(2*p/to_RR(i))*Log(2));\r\n\r\n      BKZConstant(i) = x*y/c_PI;\r\n   }\r\n\r\n}\r\n\r\nNTL_THREAD_LOCAL static vec_RR BKZThresh;\r\n\r\nstatic \r\nvoid ComputeBKZThresh(RR *c, long beta)\r\n{\r\n   BKZThresh.SetLength(beta-1);\r\n\r\n   long i;\r\n   RR x;\r\n   RR t1;\r\n\r\n   x = 0;\r\n\r\n   for (i = 1; i <= beta-1; i++) {\r\n      log(t1, c[i-1]);\r\n      add(x, x, t1);\r\n      div(t1, x, i);\r\n      exp(t1, t1);\r\n      mul(BKZThresh(i), t1, BKZConstant(i));\r\n   }\r\n}\r\n\r\n\r\n\r\n\r\nstatic \r\nvoid BKZStatus(double tt, double enum_time, unsigned long NumIterations, \r\n               unsigned long NumTrivial, unsigned long NumNonTrivial, \r\n               unsigned long NumNoOps, long m, \r\n               const mat_ZZ& B)\r\n{\r\n   cerr << \"---- BKZ_RR status ----\\n\";\r\n   cerr << \"elapsed time: \";\r\n   PrintTime(cerr, tt-StartTime);\r\n   cerr << \", enum time: \";\r\n   PrintTime(cerr, enum_time);\r\n   cerr << \", iter: \" << NumIterations << \"\\n\";\r\n   cerr << \"triv: \" << NumTrivial;\r\n   cerr << \", nontriv: \" << NumNonTrivial;\r\n   cerr << \", no ops: \" << NumNoOps;\r\n   cerr << \", rank: \" << m;\r\n   cerr << \", swaps: \" << NumSwaps << \"\\n\";\r\n\r\n\r\n\r\n   ZZ t1;\r\n   long i;\r\n   double prodlen = 0;\r\n\r\n   for (i = 1; i <= m; i++) {\r\n      InnerProduct(t1, B(i), B(i));\r\n      if (!IsZero(t1))\r\n         prodlen += log(t1);\r\n   }\r\n\r\n   cerr << \"log of prod of lengths: \" << prodlen/(2.0*log(2.0)) << \"\\n\";\r\n\r\n\r\n   if (LLLDumpFile) {\r\n      cerr << \"dumping to \" << LLLDumpFile << \"...\";\r\n\r\n      ofstream f;\r\n      OpenWrite(f, LLLDumpFile);\r\n      \r\n      f << \"[\";\r\n      for (i = 1; i <= m; i++) {\r\n         f << B(i) << \"\\n\";\r\n      }\r\n      f << \"]\\n\";\r\n\r\n      f.close();\r\n\r\n      cerr << \"\\n\";\r\n   }\r\n\r\n   LastTime = tt;\r\n   \r\n}\r\n\r\n\r\n\r\n\r\nstatic\r\nlong BKZ_RR(mat_ZZ& BB, mat_ZZ* UU, const RR& delta, \r\n         long beta, long prune, LLLCheckFct check)\r\n{\r\n   long m = BB.NumRows();\r\n   long n = BB.NumCols();\r\n   long m_orig = m;\r\n   \r\n   long i, j;\r\n   ZZ MU;\r\n\r\n   RR t1, t2;\r\n   ZZ T1;\r\n\r\n   init_red_fudge();\r\n\r\n   mat_ZZ B;\r\n   B = BB;\r\n\r\n   B.SetDims(m+1, n);\r\n\r\n\r\n   mat_RR B1;\r\n   B1.SetDims(m+1, n);\r\n\r\n   mat_RR mu;\r\n   mu.SetDims(m+1, m);\r\n\r\n   vec_RR c;\r\n   c.SetLength(m+1);\r\n\r\n   vec_RR b;\r\n   b.SetLength(m+1);\r\n\r\n   RR cbar;\r\n\r\n   vec_RR ctilda;\r\n   ctilda.SetLength(m+1);\r\n\r\n   vec_RR vvec;\r\n   vvec.SetLength(m+1);\r\n\r\n   vec_RR yvec;\r\n   yvec.SetLength(m+1);\r\n\r\n   vec_RR uvec;\r\n   uvec.SetLength(m+1);\r\n\r\n   vec_RR utildavec;\r\n   utildavec.SetLength(m+1);\r\n\r\n   vec_long Deltavec;\r\n   Deltavec.SetLength(m+1);\r\n\r\n   vec_long deltavec;\r\n   deltavec.SetLength(m+1);\r\n\r\n   mat_ZZ Ulocal;\r\n   mat_ZZ *U;\r\n\r\n   if (UU) {\r\n      Ulocal.SetDims(m+1, m);\r\n      for (i = 1; i <= m; i++)\r\n         conv(Ulocal(i, i), 1);\r\n      U = &Ulocal;\r\n   }\r\n   else\r\n      U = 0;\r\n\r\n   long quit;\r\n   long new_m;\r\n   long z, jj, kk;\r\n   long s, t;\r\n   long h;\r\n\r\n\r\n   for (i = 1; i <=m; i++)\r\n      for (j = 1; j <= n; j++) \r\n         conv(B1(i, j), B(i, j));\r\n\r\n         \r\n   for (i = 1; i <= m; i++) {\r\n      InnerProduct(b(i), B1(i), B1(i));\r\n   }\r\n\r\n   // cerr << \"\\n\";\r\n   // cerr << \"first LLL\\n\";\r\n\r\n   m = ll_LLL_RR(B, U, delta, 0, check, B1, mu, b, c, m, 1, quit);\r\n\r\n   double tt;\r\n\r\n   double enum_time = 0;\r\n   unsigned long NumIterations = 0;\r\n   unsigned long NumTrivial = 0;\r\n   unsigned long NumNonTrivial = 0;\r\n   unsigned long NumNoOps = 0;\r\n\r\n   long verb = verbose;\r\n\r\n   verbose = 0;\r\n\r\n\r\n   if (m < m_orig) {\r\n      for (i = m_orig+1; i >= m+2; i--) {\r\n         // swap i, i-1\r\n\r\n         swap(B(i), B(i-1));\r\n         if (U) swap((*U)(i), (*U)(i-1));\r\n      }\r\n   }\r\n\r\n   long clean = 1;\r\n\r\n   if (!quit && m > 1) {\r\n      // cerr << \"continuing\\n\";\r\n\r\n      if (beta > m) beta = m;\r\n\r\n      if (prune > 0)\r\n         ComputeBKZConstant(beta, prune);\r\n\r\n      z = 0;\r\n      jj = 0;\r\n   \r\n      while (z < m-1) {\r\n         jj++;\r\n         kk = min(jj+beta-1, m);\r\n   \r\n         if (jj == m) {\r\n            jj = 1;\r\n            kk = beta;\r\n            clean = 1;\r\n         }\r\n\r\n         if (verb) {\r\n            tt = GetTime();\r\n            if (tt > LastTime + LLLStatusInterval)\r\n               BKZStatus(tt, enum_time, NumIterations, NumTrivial,\r\n                         NumNonTrivial, NumNoOps, m, B);\r\n         }\r\n\r\n         // ENUM\r\n\r\n         double tt1;\r\n\r\n         if (verb) {\r\n            tt1 = GetTime();\r\n         }\r\n\r\n         if (prune > 0)\r\n            ComputeBKZThresh(&c(jj), kk-jj+1);\r\n\r\n         cbar = c(jj);\r\n         conv(utildavec(jj), 1);\r\n         conv(uvec(jj), 1);\r\n   \r\n         conv(yvec(jj), 0);\r\n         conv(vvec(jj), 0);\r\n         Deltavec(jj) = 0;\r\n   \r\n   \r\n         s = t = jj;\r\n         deltavec(jj) = 1;\r\n   \r\n         for (i = jj+1; i <= kk+1; i++) {\r\n            conv(ctilda(i), 0);\r\n            conv(uvec(i), 0);\r\n            conv(utildavec(i), 0);\r\n            conv(yvec(i), 0);\r\n            Deltavec(i) = 0;\r\n            conv(vvec(i), 0);\r\n            deltavec(i) = 1;\r\n         }\r\n\r\n         long enum_cnt = 0;\r\n   \r\n         while (t <= kk) {\r\n            if (verb) {\r\n               enum_cnt++;\r\n               if (enum_cnt > 100000) {\r\n                  enum_cnt = 0;\r\n                  tt = GetTime();\r\n                  if (tt > LastTime + LLLStatusInterval) {\r\n                     enum_time += tt - tt1;\r\n                     tt1 = tt;\r\n                     BKZStatus(tt, enum_time, NumIterations, NumTrivial,\r\n                               NumNonTrivial, NumNoOps, m, B);\r\n                  }\r\n               }\r\n            }\r\n\r\n\r\n            add(t1, yvec(t), utildavec(t));\r\n            sqr(t1, t1);\r\n            mul(t1, t1, c(t));\r\n            add(ctilda(t), ctilda(t+1), t1);\r\n\r\n            if (prune > 0 && t > jj) \r\n               sub(t1, cbar, BKZThresh(t-jj));\r\n            else\r\n               t1 = cbar;\r\n\r\n   \r\n            if (ctilda(t) <t1) {\r\n               if (t > jj) {\r\n                  t--;\r\n                  clear(t1);\r\n                  for (i = t+1; i <= s; i++) {\r\n                     mul(t2, utildavec(i), mu(i,t));\r\n                     add(t1, t1, t2);\r\n                  }\r\n\r\n                  yvec(t) = t1;\r\n                  negate(t1, t1);\r\n                  if (sign(t1) >= 0) {\r\n                     sub(t1, t1, 0.5);\r\n                     ceil(t1, t1);\r\n                  }\r\n                  else {\r\n                     add(t1, t1, 0.5);\r\n                     floor(t1, t1);\r\n                  }\r\n\r\n                  utildavec(t) = t1;\r\n                  vvec(t) = t1;\r\n                  Deltavec(t) = 0;\r\n\r\n                  negate(t1, t1);\r\n\r\n                  if (t1 < yvec(t)) \r\n                     deltavec(t) = -1;\r\n                  else\r\n                     deltavec(t) = 1;\r\n               }\r\n               else {\r\n                  cbar = ctilda(jj);\r\n                  for (i = jj; i <= kk; i++) {\r\n                     uvec(i) = utildavec(i);\r\n                  }\r\n               }\r\n            }\r\n            else {\r\n               t++;\r\n               s = max(s, t);\r\n               if (t < s) Deltavec(t) = -Deltavec(t);\r\n               if (Deltavec(t)*deltavec(t) >= 0) Deltavec(t) += deltavec(t);\r\n               add(utildavec(t), vvec(t), Deltavec(t));\r\n            }\r\n         }\r\n         \r\n         if (verb) {\r\n            tt1 = GetTime() - tt1;\r\n            enum_time += tt1;\r\n         }\r\n\r\n         NumIterations++;\r\n   \r\n         h = min(kk+1, m);\r\n\r\n         mul(t1, red_fudge, -8);\r\n         add(t1, t1, delta);\r\n         mul(t1, t1, c(jj));\r\n   \r\n         if (t1 > cbar) {\r\n \r\n            clean = 0;\r\n\r\n            // we treat the case that the new vector is b_s (jj < s <= kk)\r\n            // as a special case that appears to occur most of the time.\r\n   \r\n            s = 0;\r\n            for (i = jj+1; i <= kk; i++) {\r\n               if (uvec(i) != 0) {\r\n                  if (s == 0)\r\n                     s = i;\r\n                  else\r\n                     s = -1;\r\n               }\r\n            }\r\n   \r\n            if (s == 0) LogicError(\"BKZ_RR: internal error\");\r\n   \r\n            if (s > 0) {\r\n               // special case\r\n               // cerr << \"special case\\n\";\r\n\r\n               NumTrivial++;\r\n   \r\n               for (i = s; i > jj; i--) {\r\n                  // swap i, i-1\r\n                  swap(B(i-1), B(i));\r\n                  swap(B1(i-1), B1(i));\r\n                  swap(b(i-1), b(i));\r\n                  if (U) swap((*U)(i-1), (*U)(i));\r\n               }\r\n   \r\n               new_m = ll_LLL_RR(B, U, delta, 0, check, \r\n                                B1, mu, b, c, h, jj, quit);\r\n               if (new_m != h) LogicError(\"BKZ_RR: internal error\");\r\n               if (quit) break;\r\n            }\r\n            else {\r\n               // the general case\r\n\r\n               NumNonTrivial++;\r\n   \r\n               for (i = 1; i <= n; i++) conv(B(m+1, i), 0);\r\n\r\n               if (U) {\r\n                  for (i = 1; i <= m_orig; i++)\r\n                     conv((*U)(m+1, i), 0);\r\n               }\r\n\r\n               for (i = jj; i <= kk; i++) {\r\n                  if (uvec(i) == 0) continue;\r\n                  conv(MU, uvec(i));\r\n                  RowTransform2(B(m+1), B(i), MU);\r\n                  if (U) RowTransform2((*U)(m+1), (*U)(i), MU);\r\n               }\r\n      \r\n               for (i = m+1; i >= jj+1; i--) {\r\n                  // swap i, i-1\r\n                  swap(B(i-1), B(i));\r\n                  swap(B1(i-1), B1(i));\r\n                  swap(b(i-1), b(i));\r\n                  if (U) swap((*U)(i-1), (*U)(i));\r\n               }\r\n      \r\n               for (i = 1; i <= n; i++)\r\n                  conv(B1(jj, i), B(jj, i));\r\n      \r\n               InnerProduct(b(jj), B1(jj), B1(jj));\r\n      \r\n               if (b(jj) == 0) LogicError(\"BKZ_RR: internal error\"); \r\n      \r\n               // remove linear dependencies\r\n   \r\n               // cerr << \"general case\\n\";\r\n               new_m = ll_LLL_RR(B, U, delta, 0, 0, B1, mu, b, c, kk+1, jj, quit);\r\n              \r\n               if (new_m != kk) LogicError(\"BKZ_RR: internal error\"); \r\n\r\n               // remove zero vector\r\n      \r\n               for (i = kk+2; i <= m+1; i++) {\r\n                  // swap i, i-1\r\n                  swap(B(i-1), B(i));\r\n                  swap(B1(i-1), B1(i));\r\n                  swap(b(i-1), b(i));\r\n                  if (U) swap((*U)(i-1), (*U)(i));\r\n               }\r\n      \r\n               quit = 0;\r\n               if (check) {\r\n                  for (i = 1; i <= kk; i++)\r\n                     if ((*check)(B(i))) {\r\n                        quit = 1;\r\n                        break;\r\n                     }\r\n               }\r\n\r\n               if (quit) break;\r\n   \r\n               if (h > kk) {\r\n                  // extend reduced basis\r\n   \r\n                  new_m = ll_LLL_RR(B, U, delta, 0, check, \r\n                                   B1, mu, b, c, h, h, quit);\r\n   \r\n                  if (new_m != h) LogicError(\"BKZ_RR: internal error\");\r\n                  if (quit) break;\r\n               }\r\n            }\r\n   \r\n            z = 0;\r\n         }\r\n         else {\r\n            // LLL_RR\r\n            // cerr << \"progress\\n\";\r\n\r\n            NumNoOps++;\r\n\r\n            if (!clean) {\r\n               new_m = \r\n                  ll_LLL_RR(B, U, delta, 0, check, B1, mu, b, c, h, h, quit);\r\n               if (new_m != h) LogicError(\"BKZ_RR: internal error\");\r\n               if (quit) break;\r\n            }\r\n   \r\n            z++;\r\n         }\r\n      }\r\n   }\r\n\r\n   if (verb) {\r\n      BKZStatus(GetTime(), enum_time, NumIterations, NumTrivial, NumNonTrivial,\r\n                NumNoOps, m, B);\r\n   }\r\n\r\n\r\n   // clean up\r\n\r\n   if (m_orig > m) {\r\n      // for consistency, we move zero vectors to the front\r\n\r\n      for (i = m+1; i <= m_orig; i++) {\r\n         swap(B(i), B(i+1));\r\n         if (U) swap((*U)(i), (*U)(i+1));\r\n      }\r\n\r\n      for (i = 0; i < m; i++) {\r\n         swap(B(m_orig-i), B(m-i));\r\n         if (U) swap((*U)(m_orig-i), (*U)(m-i));\r\n      }\r\n   }\r\n\r\n   B.SetDims(m_orig, n);\r\n   BB = B;\r\n\r\n   if (U) {\r\n      U->SetDims(m_orig, m_orig);\r\n      *UU = *U;\r\n   }\r\n\r\n   return m;\r\n}\r\n\r\nlong BKZ_RR(mat_ZZ& BB, mat_ZZ& UU, double delta, \r\n         long beta, long prune, LLLCheckFct check, long verb)\r\n{\r\n   verbose = verb;\r\n   NumSwaps = 0;\r\n   if (verbose) {\r\n      StartTime = GetTime();\r\n      LastTime = StartTime;\r\n   }\r\n\r\n   if (delta < 0.50 || delta >= 1) LogicError(\"BKZ_RR: bad delta\");\r\n   if (beta < 2) LogicError(\"BKZ_RR: bad block size\");\r\n\r\n   RR Delta;\r\n   conv(Delta, delta);\r\n\r\n   return BKZ_RR(BB, &UU, Delta, beta, prune, check);\r\n}\r\n\r\nlong BKZ_RR(mat_ZZ& BB, double delta, \r\n         long beta, long prune, LLLCheckFct check, long verb)\r\n{\r\n   verbose = verb;\r\n   NumSwaps = 0;\r\n   if (verbose) {\r\n      StartTime = GetTime();\r\n      LastTime = StartTime;\r\n   }\r\n\r\n   if (delta < 0.50 || delta >= 1) LogicError(\"BKZ_RR: bad delta\");\r\n   if (beta < 2) LogicError(\"BKZ_RR: bad block size\");\r\n\r\n   RR Delta;\r\n   conv(Delta, delta);\r\n\r\n   return BKZ_RR(BB, 0, Delta, beta, prune, check);\r\n}\r\n\r\n\r\n\r\n\r\nvoid NearVector(vec_ZZ& ww, const mat_ZZ& BB, const vec_ZZ& a)\r\n{\r\n   long n = BB.NumCols();\r\n\r\n   if (n != BB.NumRows())\r\n      LogicError(\"NearVector: matrix must be square\");\r\n\r\n   if (n != a.length())\r\n      LogicError(\"NearVector: dimension mismatch\");\r\n\r\n   long i, j;\r\n   mat_ZZ B;\r\n\r\n   B.SetDims(n+1, n);\r\n   for (i = 1; i <= n; i++)\r\n      B(i) = BB(i);\r\n\r\n   B(n+1) = a;\r\n\r\n   mat_RR B1, mu;\r\n   vec_RR b, c;\r\n\r\n   B1.SetDims(n+1, n);\r\n   mu.SetDims(n+1, n+1);\r\n   b.SetLength(n+1);\r\n   c.SetLength(n+1);\r\n\r\n   vec_RR buf;\r\n   buf.SetLength(n+1);\r\n\r\n\r\n   for (i = 1; i <= n+1; i++)\r\n      for (j = 1; j <= n; j++)\r\n         conv(B1(i, j), B(i, j));\r\n\r\n   for (i = 1; i <= n+1; i++)\r\n      InnerProduct(b(i), B1(i), B1(i));\r\n\r\n   \r\n\r\n   RR bound;\r\n   power2(bound, 2*long(0.15*RR::precision()));\r\n\r\n   RR bound2;\r\n   power2(bound2, 2*RR::precision());\r\n\r\n\r\n   for (i = 1; i <= n+1; i++)\r\n      ComputeGS(B, B1, mu, b, c, i, bound, 1, buf, bound2);\r\n\r\n   init_red_fudge();\r\n\r\n   RR half;\r\n   conv(half,  0.5);\r\n   RR half_plus_fudge;\r\n   add(half_plus_fudge, half, red_fudge);\r\n\r\n   RR t1, t2, mu1;\r\n   ZZ MU;\r\n\r\n   long trigger_index = n+1;\r\n   long small_trigger = 0;\r\n   long cnt = 0;\r\n\r\n   long Fc1;\r\n\r\n   vec_ZZ w;\r\n   w.SetLength(n);\r\n   clear(w);\r\n\r\n   do {\r\n      Fc1 = 0;\r\n\r\n      for (j = n; j >= 1; j--) {\r\n         abs(t1, mu(n+1,j));\r\n         if (t1 > half_plus_fudge) {\r\n\r\n            if (!Fc1) {\r\n               if (j > trigger_index ||\r\n                   (j == trigger_index && small_trigger)) {\r\n\r\n                  cnt++;\r\n\r\n                  if (cnt > 10) {\r\n                     inc_red_fudge();\r\n                     add(half_plus_fudge, half, red_fudge);\r\n                     cnt = 0;\r\n                  }\r\n               }\r\n\r\n               trigger_index = j;\r\n               small_trigger = (t1 < 4);\r\n            }\r\n\r\n            Fc1 = 1;\r\n\r\n            mu1 = mu(n+1,j);\r\n            if (sign(mu1) >= 0) {\r\n               sub(mu1, mu1, half);\r\n               ceil(mu1, mu1);\r\n            }\r\n            else {\r\n               add(mu1, mu1, half);\r\n               floor(mu1, mu1);\r\n            }\r\n\r\n            if (mu1 == 1) {\r\n               for (i = 1; i <= j-1; i++)\r\n                  sub(mu(n+1,i), mu(n+1,i), mu(j,i));\r\n            }\r\n            else if (mu1 == -1) {\r\n               for (i = 1; i <= j-1; i++)\r\n                  add(mu(n+1,i), mu(n+1,i), mu(j,i));\r\n            }\r\n            else {\r\n               for (i = 1; i <= j-1; i++) {\r\n                  mul(t2, mu1, mu(j,i));\r\n                  sub(mu(n+1,i), mu(n+1,i), t2);\r\n               }\r\n            }\r\n\r\n\r\n            conv(MU, mu1);\r\n\r\n            sub(mu(n+1,j), mu(n+1,j), mu1);\r\n\r\n            RowTransform(B(n+1), B(j), MU);\r\n            RowTransform2(w, B(j), MU);\r\n         }\r\n      }\r\n\r\n      if (Fc1) {\r\n         for (i = 1; i <= n; i++)\r\n            conv(B1(n+1, i), B(n+1, i));\r\n\r\n         InnerProduct(b(n+1), B1(n+1), B1(n+1));\r\n         ComputeGS(B, B1, mu, b, c, n+1, bound, 1, buf, bound2);\r\n      }\r\n   } while (Fc1);\r\n\r\n   ww = w;\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "6f2a827ed522de63bbdbceb5d7469b2e74d88b20", "size": 28946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/LLL_RR.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WinNTL-8_1_2/src/LLL_RR.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WinNTL-8_1_2/src/LLL_RR.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.6014925373, "max_line_length": 83, "alphanum_fraction": 0.3791888344, "num_tokens": 8767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4462173458794934}}
{"text": "// ============================================================================\n//\n// Copyright (c) 2001-2006 Max-Planck-Institut Saarbruecken (Germany).\n// All rights reserved.\n//\n// This file is part of EXACUS (http://www.mpi-inf.mpg.de/projects/EXACUS/).\n// You can redistribute it and/or modify it under the terms of the GNU\n// General Public License as published by the Free Software Foundation,\n// either version 3 of the License, or (at your option) any later version.\n//\n// Licensees holding a valid commercial license may use this file in\n// accordance with the commercial license agreement provided with the software.\n//\n// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE\n// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n//\n// ----------------------------------------------------------------------------\n//\n// Library       : NiX\n// File          : NiX/poly2ntl.C\n// NiX_release   : $Name:  $\n// Revision      : $Revision: 1.1 $\n// Revision_date : $Date: 2009-06-30 13:14:58 $\n//\n// Author(s)     : ... ?\n//\n// ============================================================================\n\n/*! \\file NiX/poly2ntl.C\n *  \n *  Conversion of polynomials to NTL format & back\n */\n\n\n#include <CGAL/config.h>\n\n#define NDEBUG 1\n// #define CGAL_POLYNOMIAL_USE_NTL_MUL\n\n// #define CGAL_ACK_BENCHMARK_RES\n\n#ifdef CGAL_POLYNOMIAL_USE_NTL_MUL\n\n//#include <CGAL/leda_integer.h>\n#include <CGAL/CORE/BigInt.h>\n#include <NTL/ZZX.h>\n\n#include <CGAL/Arithmetic_kernel.h>\n#include <CGAL/Polynomial.h>\n#include <CGAL/Timer.h>\n\n#define POLY_NTL_MIN_DEGREE 10 // minimal degree of polynomials to multiply\n                                // using NTL\n\n#endif // CGAL_POLYNOMIAL_USE_NTL_MUL\n\nnamespace CGAL {\n\n#ifdef CGAL_POLYNOMIAL_USE_NTL_MUL\n\n// namespace internal {\n// int *primes = CGAL::CGALi::primes;\n// }  \n\nstruct NTL_bigint_rep {\n    long alloc;\n    long size;\n    mp_limb_t data;\n};\n\n#endif\n\n#ifdef CGAL_POLYNOMIAL_USE_NTL_MUL\n\nnamespace {\n\n// typedef leda_integer CCC_int;\ntypedef CORE::BigInt Integer;\n\ntypedef Polynomial< Integer > Poly_1;\n\nvoid poly2ntl(const Poly_1& p, NTL::ZZX& q) {\n\n//     if(p.is_zero()) { // TODO should be handled earlier\n//         //special handling\n//         //a is zero if a.rep.length() == 0;\n//         q = NTL::ZZX();\n//     } \n    q.rep.SetLength(p.degree() + 1);\n    \n    int i;\n    Poly_1::const_iterator pit;\n    for(i = 0, pit = p.begin(); pit != p.end(); pit++, i++) {\n\n        NTL::ZZ& zz = q.rep[i];\n        mpz_srcptr tmp = pit->get_mp();\n        int sz = tmp->_mp_size;\n        if(sz == 0)\n            continue;\n        if(sz < 0)\n            sz = -sz;\n        \n        zz.SetSize(sz);\n        NTL_bigint_rep *rep = (NTL_bigint_rep *)zz.rep;\n        rep->size = tmp->_mp_size;\n        // copy limbs directly\n        memcpy(&rep->data, tmp->_mp_d, sz*sizeof(mp_limb_t));\n         //std::cerr << \"pit = \" << *pit << \"; and \" <<\n            //zz << \"\\n\\n\";\n    }\n}\n\n} // anonymous namespace\n\n#endif\n\n#ifdef CGAL_ACK_BENCHMARK_RES\n#warning timing resultants\nextern Timer res_tm;\n#endif\n\n#ifdef CGAL_POLYNOMIAL_USE_NTL_MUL\n\n#warning using NTL\n\ntemplate <>\nPoly_1& Poly_1::operator *= (const Poly_1& p2) {\n\n    Poly_1 p1 = *this;\n\n    if(p1.is_zero() || p2.is_zero()) {\n//         std::cout << \"mul NTL: zero poly\\n\";\n        return (*this) = Poly_1(Integer(0));\n    }\n//  TODO: use this if poly size is small..\n    if(p1.degree() <= POLY_NTL_MIN_DEGREE &&\n        p2.degree() <= POLY_NTL_MIN_DEGREE) {\n\n        internal::Creation_tag TAG;\n        Poly_1 p(TAG, p1.degree() + p2.degree() + 1);\n        for (int i=0; i <= p1.degree(); ++i)\n          for (int j=0; j <= p2.degree(); ++j)\n            p.coeff(i+j) += (p1[i]*p2[j]); \n        p.reduce();\n//         std::cout << \"mul usual: \" << p << \"\\n\\n\";;\n        return (*this) = p ;\n    }\n    NTL::ZZX q, q2;\n    poly2ntl(p1, q);\n    poly2ntl(p2, q2);\n\n    q *= q2;\n\n    int d = NTL::deg(q);\n//     if(d == -1) {\n//         std::cout << \"Fatal: zero poly\\n\";\n//         throw -1;\n//     }\n\n    this->copy_on_write(); // ??\n    this->coeffs().resize(d + 1);\n\n    // TODO: use reduce ??\n    mpz_t tmp;\n     mpz_init(tmp);\n    for(int i = 0; i <= d; i++) {\n        \n        const NTL::ZZ& zz = q.rep[i];\n        if(NTL::IsZero(zz)) {\n            coeff(i) = Integer(0);\n            continue;\n        } \n\n        NTL_bigint_rep *rep = (NTL_bigint_rep *)zz.rep;\n        int sz = rep->size;\n        if(sz < 0)\n            sz = -sz;\n         \n        mpz_realloc2(tmp, sz * GMP_NUMB_BITS);\n        tmp->_mp_size = rep->size;\n        memcpy(tmp->_mp_d, &rep->data, sz*sizeof(mp_limb_t));\n         \n//         coeff(i).makeCopy();\n//         mpz_ptr mpd = coeff(i).get_mp();\n//         mpd->_mp_size = rep->size;\n//         mpz_realloc2(mpd, sz * GMP_NUMB_BITS);\n//         memcpy(mpd->_mp_d, &rep->data, sz*sizeof(mp_limb_t));\n        coeff(i) = Integer(tmp);\n    \n//          mpz_init_set(coeff(i).get_mp(), tmp);\n    }\n    mpz_clear(tmp);\n   \n//         CGALi::Creation_tag TAG;\n//         Poly_1 p(TAG, p1.degree() + p2.degree() + 1);\n//         for (int i=0; i <= p1.degree(); ++i)\n//           for (int j=0; j <= p2.degree(); ++j)\n//             p.coeff(i+j) += (p1[i]*p2[j]);\n//         //p.reduce();\n// //         std::cout << \"mul usual: \" << p << \"\\n\\n\";;\n//\n//     if(*this != p) {\n//\n//         std::cout << \"------------ p1: \" << p1 << \"---------- p2: \" <<\n//                 p2 << \"\\n\";\n//         std::cout << \"FATAL: \" << *this << \"----------- and \" << p << \"\\n\";\n//\n//     }\n\n//     Poly_1 pp(vec.begin(), vec.end());\n    //p.reduce();\n//       std::cout << \"mul NTL: \" << *this << \"\\n\";\n    return (*this);// = pp;\n}\n\ntemplate <> \nInteger prs_resultant_ufd< Integer >(Poly_1 A, Poly_1 B) {\n\n#ifdef CGAL_ACK_BENCHMARK_RES\n// std::cout << \"start res \" << \"\\n\";\nres_tm.start();\n#endif\n\n    // implemented using the subresultant algorithm for resultant computation\n    // see [Cohen, 1993], algorithm 3.3.7\n\n    typedef Integer NT;\n\n    if (A.is_zero() || B.is_zero()) return NT(0);\n\n    NTL::ZZX q1, q2;\n    poly2ntl(A, q1);\n    poly2ntl(B, q2);\n\n    NTL::ZZ zz;\n    NTL::resultant(zz, q1, q2);\n\n    if(NTL::IsZero(zz))\n        return Integer(0);\n    \n    Integer res;\n    NTL_bigint_rep *rep = (NTL_bigint_rep *)zz.rep;\n    int sz = rep->size;\n    if(sz < 0)\n        sz = -sz;\n       \n    mpz_ptr tmp = res.get_mp();  \n    mpz_realloc2(tmp, sz * GMP_NUMB_BITS);\n    tmp->_mp_size = rep->size;\n    memcpy(tmp->_mp_d, &rep->data, sz*sizeof(mp_limb_t));\n\n\n//     std::cout << \"stop res \" << \"\\n\";\n#ifdef CGAL_ACK_BENCHMARK_RES\n// std::cout << \"stop res \" << \"\\n\";\nres_tm.stop();\n#endif\n\n    return res;\n}\n#else // CGAL_POLYNOMIAL_USE_NTL_MUL\n\n#if 0\ntemplate <> \nInteger prs_resultant_ufd< Integer >(Poly_1 A, Poly_1 B) {\n\n#ifdef CGAL_ACK_BENCHMARK_RES\nres_tm.start();\n#endif\n\n    // implemented using the subresultant algorithm for resultant computation\n    // see [Cohen, 1993], algorithm 3.3.7\n\n    typedef Integer NT;\n\n    if (A.is_zero() || B.is_zero()) return NT(0);\n\n    int signflip;\n    if (A.degree() <123 B.degree()) {\n        Polynomial<NT> T = A; A = B; B = T;\n        signflip = (A.degree() & B.degree() & 1);\n    } else {\n        signflip = 0;\n    }\n\n    NT a = A.content(), b = B.content();\n    NT g(1), h(1), t = CGAL::ipower(a, B.degree()) * CGAL::ipower(b, A.degree());\n    Polynomial<NT> Q, R; NT d;\n    int delta;\n\n    A /= a; B /= b;\n    do {\n        signflip ^= (A.degree() & B.degree() & 1);\n        Polynomial<NT>::pseudo_division(A, B, Q, R, d);\n        delta = A.degree() - B.degree();\n        typedef CGAL::Algebraic_structure_traits<NT>::Is_exact\n          Is_exact;\n    \n        A = B;\n        B = R / (g * CGAL::ipower(h, delta));\n        g = A.lcoeff();\n        // h = h^(1-delta) * g^delta\n        CGALi::hgdelta_update(h, g, delta);\n    } while (B.degree() > 0);\n    // h = h^(1-deg(A)) * lcoeff(B)^deg(A)\n    delta = A.degree();\n    g = B.lcoeff();\n    CGALi::hgdelta_update(h, g, delta);\n    h = signflip ? -(t*h) : t*h;\n    Algebraic_structure_traits<NT>::Simplify simplify;\n    simplify(h);\n\n   return h;\n}\n#endif\n\n#endif // CGAL_POLYNOMIAL_USE_NTL_MUL\n\n} // namespace CGAL\n\n", "meta": {"hexsha": "73b2b8aba831e8d934d5983e4a6bad56d524891d", "size": 8153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Arrangement_on_surface_2/demo/Arr_algebraic_segment_traits_2/xalci/poly2ntl.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Arrangement_on_surface_2/demo/Arr_algebraic_segment_traits_2/xalci/poly2ntl.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Arrangement_on_surface_2/demo/Arr_algebraic_segment_traits_2/xalci/poly2ntl.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3987538941, "max_line_length": 81, "alphanum_fraction": 0.5325647001, "num_tokens": 2445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4460974058220106}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_IFLOOR_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_IFLOOR_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing ifloor capabilities\n\n    Computes the integer conversion of the floor of its parameter.\n\n    @par semantic:\n    For any given value @c x of type @c T:\n\n    @code\n    as_integer_t<T> r = ifloor(x);\n    @endcode\n\n    is equivalent to:\n\n    @code\n    as_integer_t<T> r = saturated_(toint)(floor(x));\n    @endcode\n\n    @par Note:\n    This operation is properly saturated\n\n  **/\n  as_integer_T<Value> ifloor(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/ifloor.hpp>\n#include <boost/simd/function/simd/ifloor.hpp>\n\n#endif\n", "meta": {"hexsha": "ca5a0eff6ee42e701c609ceaf078bf96344d9b7a", "size": 1158, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/ifloor.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/function/ifloor.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/ifloor.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 23.16, "max_line_length": 100, "alphanum_fraction": 0.5898100173, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4460973987523881}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MTL_TWO_NORM_INCLUDE\n#define MTL_TWO_NORM_INCLUDE\n\n#include <iostream>\n#include <cmath>\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/concept/magnitude.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/vector/lazy_reduction.hpp>\n#include <boost/numeric/mtl/vector/reduction.hpp>\n#include <boost/numeric/mtl/vector/reduction_functors.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl {\n\n    namespace vec {\n\n\ttemplate <unsigned long Unroll, typename Value>\n\ttypename RealMagnitude<typename Collection<Value>::value_type>::type\n\tinline two_norm(const Value& value)\n\t{\n\t    using std::sqrt;\n\t    vampir_trace<2039> tracer;\n\t    typedef typename RealMagnitude<typename Collection<Value>::value_type>::type result_type;\n\t    return sqrt(reduction<Unroll, two_norm_functor, result_type>::apply(value));\n\t}\n\n\t\n\t/*! Two-norm for vectors: two_norm(x) \\f$\\rightarrow |x|_2\\f$.\n\t    \\retval The magnitude type of the respective value type, see Magnitude.\n\t    The norms are defined as \\f$|v|_2=\\sqrt{\\sum_i |v_i|^2}\\f$.\n\t    \n\t    Vector norms are unrolled 8-fold by default. \n\t    An n-fold unrolling can be generated with two_norm<n>(x).\n\t    The maximum for n is 8 (it might be increased later).\n\t**/\n\ttemplate <typename Value>\n\ttypename RealMagnitude<typename Collection<Value>::value_type>::type\n\tinline two_norm(const Value& value)\n\t{\n\t    return two_norm<4>(value);\n\t}\n\n\ttemplate <typename Vector>\n\tlazy_reduction<Vector, two_norm_functor> inline lazy_two_norm(const Vector& v)\n\t{  return lazy_reduction<Vector, two_norm_functor>(v); \t}\n\t\n\n    } // namespace vector\n\n    // two_norm for matrices not implemented (would need enable_if like one_norm)\n\n    using vec::two_norm;\n    using vec::lazy_two_norm;\n\n} // namespace mtl\n\n#endif // MTL_TWO_NORM_INCLUDE\n", "meta": {"hexsha": "4f6bc6bec70b91d8a04170bfc3a7e77277444c57", "size": 2336, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/two_norm.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/mtl/operation/two_norm.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/mtl/operation/two_norm.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5675675676, "max_line_length": 94, "alphanum_fraction": 0.7324486301, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.446097398752388}}
{"text": "////////////////////////////////////////////////////////////////\n// Orkid Media Engine\n// Copyright 1996-2020, Michael T. Mayers.\n// Distributed under the Boost Software License - Version 1.0 - August 17, 2003\n// see http://www.boost.org/LICENSE_1_0.txt\n////////////////////////////////////////////////////////////////\n\n#include <ork/lev2/config.h>\n#if defined(ENABLE_IGL)\n\n#include <ork/kernel/orklut.hpp>\n#include <ork/math/plane.h>\n#include <ork/lev2/gfx/meshutil/submesh.h>\n#include <ork/lev2/gfx/meshutil/igl.h>\n#include <iostream>\n\n#include <Eigen/Core>\n#include <igl/gaussian_curvature.h>\n#include <igl/principal_curvature.h>\n#include <igl/cotmatrix.h>\n#include <igl/massmatrix.h>\n#include <igl/invert_diag.h>\n\nnamespace ork::meshutil {\niglprinciplecurvature_ptr_t IglMesh::computePrincipleCurvature() const {\n  auto rval = std::make_shared<IglPrincipleCurvature>();\n  // Alternative discrete mean curvature\n  Eigen::MatrixXd HN;\n  Eigen::SparseMatrix<double> L, M, Minv;\n  igl::cotmatrix(_verts, _faces, L);\n  igl::massmatrix(_verts, _faces, igl::MASSMATRIX_TYPE_VORONOI, M);\n  igl::invert_diag(M, Minv);\n  // Laplace-Beltrami of position\n  HN = -Minv * (L * _verts);\n  // Extract magnitude as mean curvature\n  rval->H = HN.rowwise().norm();\n\n  // Compute curvature directions via quadric fitting\n  igl::principal_curvature(_verts, _faces, rval->PD1, rval->PD2, rval->PV1, rval->PV2);\n  // mean curvature\n  rval->H = 0.5 * (rval->PV1 + rval->PV2);\n  return rval;\n}\n\nEigen::VectorXd IglMesh::computeGaussianCurvature() const {\n  Eigen::VectorXd rval;\n  igl::gaussian_curvature(_verts, _faces, rval);\n  // Compute mass matrix\n  Eigen::SparseMatrix<double> M, Minv;\n  igl::massmatrix(_verts, _faces, igl::MASSMATRIX_TYPE_DEFAULT, M);\n  igl::invert_diag(M, Minv);\n  // Divide by area to get integral average\n  rval = (Minv * rval).eval();\n  return rval;\n}\n\n} // namespace ork::meshutil\n\n#endif", "meta": {"hexsha": "273dce8f8bb5e46aad7ab839ef1447ee19e2e50d", "size": 1897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ork.lev2/src/gfx/meshutil/submesh_igl_curvature.cpp", "max_stars_repo_name": "tweakoz/orkid", "max_stars_repo_head_hexsha": "e3f78dfb3375853fd512a9d0828b009075a18345", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T04:21:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T05:19:27.000Z", "max_issues_repo_path": "ork.lev2/src/gfx/meshutil/submesh_igl_curvature.cpp", "max_issues_repo_name": "tweakoz/orkid", "max_issues_repo_head_hexsha": "e3f78dfb3375853fd512a9d0828b009075a18345", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 113.0, "max_issues_repo_issues_event_min_datetime": "2019-08-23T04:52:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T04:04:11.000Z", "max_forks_repo_path": "ork.lev2/src/gfx/meshutil/submesh_igl_curvature.cpp", "max_forks_repo_name": "tweakoz/orkid", "max_forks_repo_head_hexsha": "e3f78dfb3375853fd512a9d0828b009075a18345", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-02-20T18:17:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-28T03:47:55.000Z", "avg_line_length": 32.1525423729, "max_line_length": 87, "alphanum_fraction": 0.6726410121, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.44607455476782837}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n#include <OpenMesh/Core/IO/MeshIO.hh>\n#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>\n#include <string>\n#include <iostream>\n#include <vector>\n//#include \"include/pybind11/pybind11.h\"\n//#include \"include/pybind11/numpy.h\"\n//#include \"include/pybind11/stl.h\"\n#include <pybind11/numpy.h>\n#include <pybind11/pybind11.h>\n#include <fstream>\n\nstruct TriTraits : public OpenMesh::DefaultTraits\n{\n  /// Use double precision points\n  typedef OpenMesh::Vec3d Point;\n  /// Use double precision Normals\n  typedef OpenMesh::Vec3d Normal;\n  /// Use double precision TexCood2D\n  typedef OpenMesh::Vec2d TexCoord2D;\n};\n\n/// Simple Name for Mesh\ntypedef OpenMesh::TriMesh_ArrayKernelT<TriTraits>  TriMesh;\n\nnamespace py=pybind11;\n\n// compute matrix exp\nEigen::Matrix3d exp(Eigen::Matrix3d angle_cross_axis){\n        Eigen::Matrix3d test=angle_cross_axis+angle_cross_axis.transpose();\n        if(test.norm()>1e-6)\n        {\n            std::cout<<\"rotation_log_exp::exp3::input matrix isn't skew-matrix!!!\"<<std::endl;\n            return Eigen::Matrix3d::Identity();\n        }\n\n        Eigen::Vector3d angle_axis;\n        angle_axis(0)=angle_cross_axis(2,1);\n        angle_axis(1)=angle_cross_axis(0,2);\n        angle_axis(2)=angle_cross_axis(1,0);\n        double angle=sqrt(angle_axis(0)*angle_axis(0)+angle_axis(1)*angle_axis(1)+angle_axis(2)*angle_axis(2));\n        if(angle<1e-6)\n            return Eigen::Matrix3d::Identity();\n        Eigen::Matrix3d cross_axis=angle_cross_axis/angle;\n\n        test=cross_axis+cross_axis.transpose();\n        if(test.norm()>1e-6)\n        {\n            std::cout<<\"rotation_log_exp::exp2::input matrix isn't skew-matrix!!!\"<<std::endl;\n            return Eigen::Matrix3d::Identity();\n        }\n\n        return Eigen::Matrix3d::Identity()+sin(angle)*cross_axis+(1.0-cos(angle))*cross_axis*cross_axis;\n}\n\npy::array_t<double> get_mesh(std::string file, py::array_t<double> feature_input){\n    TriMesh ref_mesh_;\n    if(!OpenMesh::IO::read_mesh(ref_mesh_, file)){\n        std::cerr<<\"Read Mesh error\"<<std::endl;\n    }\n    int nver=ref_mesh_.n_vertices();\n    OpenMesh::EPropHandleT<double> LB_weights;\n    ref_mesh_.add_property(LB_weights);\n\n    // compute LB weight\n    TriMesh::EdgeIter e_it, e_end(ref_mesh_.edges_end());\n    TriMesh::HalfedgeHandle    h0, h1, h2;\n    TriMesh::VertexHandle      v0, v1;\n    TriMesh::Point             p0, p1, p2, d0, d1;\n    TriMesh::Scalar w;\n    for (e_it=ref_mesh_.edges_begin(); e_it!=e_end; e_it++)\n    {\n        w  = 0.0;\n        if(ref_mesh_.is_boundary(*e_it))\n        {\n            h0 = ref_mesh_.halfedge_handle(e_it.handle(),0);\n            if(ref_mesh_.is_boundary(h0))\n                h0 = ref_mesh_.opposite_halfedge_handle(h0);\n\n            v0 = ref_mesh_.to_vertex_handle(h0);\n            v1 = ref_mesh_.from_vertex_handle(h0);\n            p0 = ref_mesh_.point(v0);\n            p1 = ref_mesh_.point(v1);\n            h1 = ref_mesh_.next_halfedge_handle(h0);\n            p2 = ref_mesh_.point(ref_mesh_.to_vertex_handle(h1));\n            d0 = (p0-p2).normalize();\n            d1 = (p1-p2).normalize();\n            w += 2.0 / tan(acos(std::min(0.99, std::max(-0.99, (d0|d1)))));\n            if(std::isnan(w))\n                std::cout<<\"Some weight NAN\"<<std::endl;\n            ref_mesh_.property(LB_weights,e_it) = w;\n            continue;\n        }\n        h0 = ref_mesh_.halfedge_handle(e_it.handle(),0);\n        v0 = ref_mesh_.to_vertex_handle(h0);\n        p0 = ref_mesh_.point(v0);\n\n        h1 = ref_mesh_.opposite_halfedge_handle(h0);\n        v1 = ref_mesh_.to_vertex_handle(h1);\n        p1 = ref_mesh_.point(v1);\n\n        h2 = ref_mesh_.next_halfedge_handle(h0);\n        p2 = ref_mesh_.point(ref_mesh_.to_vertex_handle(h2));\n        d0 = (p0 - p2).normalize();\n        d1 = (p1 - p2).normalize();\n        w += 1.0/ tan(acos(std::max(-1.0, std::min(1.0, dot(d1,d0) ))));\n\n        h2 = ref_mesh_.next_halfedge_handle(h1);\n        p2 = ref_mesh_.point(ref_mesh_.to_vertex_handle(h2));\n        d0 = (p0 - p2).normalize();\n        d1 = (p1 - p2).normalize();\n        w += 1.0 / tan(acos(std::max(-1.0, std::min(1.0, dot(d1,d0)))));\n\n        if(std::isnan(w))\n            std::cout<<\"Some weight is NAN\"<<std::endl;\n        ref_mesh_.property(LB_weights,e_it) = w;\n    }\n\n    // prepare Sparse A_ matrix\n    Eigen::SparseMatrix<double> A_;\n    A_.resize(3*nver,3*nver);\n    std::vector<Eigen::Triplet<double> > tripletlist;\n    TriMesh::VertexIter v_it = ref_mesh_.vertices_begin();\n    for(;v_it!=ref_mesh_.vertices_end();v_it++)\n    {\n        // fix one point\n        TriMesh::VertexEdgeIter ve_iter = ref_mesh_.ve_iter(*v_it);\n        int center_id = (*v_it).idx();\n        double center_val[3]={0.0,0.0,0.0};\n        for(;ve_iter.is_valid();ve_iter++)\n        {\n            double w = ref_mesh_.property(LB_weights,*ve_iter);\n            TriMesh::VertexHandle to_v = ref_mesh_.to_vertex_handle(ref_mesh_.halfedge_handle(*ve_iter,0));\n            if(to_v.idx() == center_id)\n                to_v = ref_mesh_.from_vertex_handle(ref_mesh_.halfedge_handle(*ve_iter,0));\n            for(int i =0;i<3;i++)\n            {\n                center_val[i]+=w;\n                tripletlist.push_back(Eigen::Triplet<double>(3*center_id+i,3*to_v.idx()+i,-w));\n//                outfile << 3*center_id + i << \" \" << 3*to_v.idx()+i << \" \"<< -w << '\\n';\n            }\n        }\n        for(int i =0;i<3;i++)\n        {\n            tripletlist.push_back(Eigen::Triplet<double>(3*center_id+i,3*center_id+i,center_val[i]));\n        }\n    }\n    A_.setFromTriplets(tripletlist.begin(),tripletlist.end());\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double> > A_solver_;\n    A_solver_.compute(A_);\n    // prepare T_matrix\n    py::buffer_info feature_array = feature_input.request();\n    std::vector<Eigen::Matrix3d> T_array;\n    for(int i =0; i<ref_mesh_.n_vertices(); i++)\n    {\n        Eigen::Matrix3d logR;\n        logR<<0,((double*)feature_array.ptr)[9*i+6],((double*)feature_array.ptr)[9*i+7],-((double*)feature_array.ptr)[9*i+6],0,((double*)feature_array.ptr)[9*i+8],-((double*)feature_array.ptr)[9*i+7],-((double*)feature_array.ptr)[9*i+8],0;\n        Eigen::Matrix3d S;\n        S<<((double*)feature_array.ptr)[9*i+0],((double*)feature_array.ptr)[9*i+1],((double*)feature_array.ptr)[9*i+2],((double*)feature_array.ptr)[9*i+1],((double*)feature_array.ptr)[9*i+3],((double*)feature_array.ptr)[9*i+4],((double*)feature_array.ptr)[9*i+2],((double*)feature_array.ptr)[9*i+4],((double*)feature_array.ptr)[9*i+5];\n        T_array.push_back(exp(logR)*S);\n    }\n\n    // compute b_\n    Eigen::VectorXd b_;\n    b_.resize(3*nver);\n    b_.setZero();\n    v_it = ref_mesh_.vertices_begin();\n    for(;v_it!=ref_mesh_.vertices_end();v_it++)\n    {\n        TriMesh::VertexEdgeIter ve_iter = ref_mesh_.ve_iter(*v_it);\n        Eigen::Vector3d temp(0.0,0.0,0.0);\n        for(;ve_iter.is_valid();ve_iter++)\n        {\n            TriMesh::VertexHandle v0 = ref_mesh_.to_vertex_handle(ref_mesh_.halfedge_handle(*ve_iter,0));\n            if(v0.idx() == (*v_it).idx())\n                v0 = ref_mesh_.from_vertex_handle(ref_mesh_.halfedge_handle(*ve_iter,0));\n            OpenMesh::Vec3d Pj,Pk;\n            Pj = ref_mesh_.point(*v_it);\n            Pk = ref_mesh_.point(v0);\n            Eigen::Vector3d e1jk(Pj[0]-Pk[0],Pj[1]-Pk[1],Pj[2]-Pk[2]);\n            double cjk = ref_mesh_.property(LB_weights,*ve_iter);\n\n            temp+= cjk*( T_array[v0.idx()] + T_array[(*v_it).idx()] )*e1jk;\n        }\n        temp*=0.5;\n        b_.block<3,1>(3*(*v_it).idx(),0) = temp;\n    }\n\n    // solve \n    Eigen::VectorXd out;\n    out.resize(3*nver);\n    out = A_solver_.solve(b_);\n\n    // std::vector<double> P_;\n        // std::cout<<\"dahsdas\"<<std::endl;\n    \n    // std::memcpy(P_.data(), out.data(), out.size()*sizeof(double));\n    // Eigen::VectorXd::Map(&P_[0], out.size()) = out;\n    std::vector<double> P_(out.data(), out.data()+out.size());\n    auto result = py::array_t<double>(P_.size());\n    auto result_buffer = result.request();\n    double *result_ptr = (double *)result_buffer.ptr;\n\n    std::memcpy(result_ptr, P_.data(), P_.size()*sizeof(double));\n\n    // std::cout<<result[0]<<std::endl;\n    return result;\n\n    // for(int i =0; i< P_.rows(); i++)\n    // std::cout<<P_[i]<<std::endl;\n    // std::vector<size_t> strides = {sizeof(double)};\n    // std::vector<size_t> shape = {feature_array.shape[0]/3};\n    // size_t ndim = 1;\n    // return py::array(py::buffer_info(P_.data(), sizeof(double), py::format_descriptor<double>::value, ndim, feature_array.shape, strides));\n    // return py::array(nver, P_.data());\n}\n PYBIND11_MODULE(get_mesh, m){\n    m.doc() = \"get mesh\";\n    m.def(\"get_mesh\", &get_mesh, \"get_mesh\"); \n }\n", "meta": {"hexsha": "6e12916989b8935468d65a5e824812d1b4ec7d3e", "size": 8733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/get_mesh_py/get_mesh.cpp", "max_stars_repo_name": "QianyiWu/DR-Learning-for-3D-Face", "max_stars_repo_head_hexsha": "fee8931e9bed5c1e3f69c290783fcaf4bcf967c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-24T12:39:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-24T12:39:24.000Z", "max_issues_repo_path": "third_party/get_mesh_py/get_mesh.cpp", "max_issues_repo_name": "QianyiWu/DR-Learning-for-3D-Face", "max_issues_repo_head_hexsha": "fee8931e9bed5c1e3f69c290783fcaf4bcf967c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/get_mesh_py/get_mesh.cpp", "max_forks_repo_name": "QianyiWu/DR-Learning-for-3D-Face", "max_forks_repo_head_hexsha": "fee8931e9bed5c1e3f69c290783fcaf4bcf967c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9866071429, "max_line_length": 335, "alphanum_fraction": 0.6049467537, "num_tokens": 2567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4460745505066565}}
{"text": "#include <iostream>\n#include <mtl/strided1D.h>\n#include <mtl/light1D.h>\n#include <mtl/mtl.h>\n\nint\nmain()\n{\n  using namespace mtl;\n\n  double dx[20], dy[20];\n  for (int i = 0; i < 20; ++i) {\n    if (i % 2 == 0) {\n      dx[i] = i;\n      dy[i] = 2*i;\n    } else {\n      dx[i] = 0;\n      dy[i] = 0;\n    }\n  }\n  light1D<double> x(dx, 20);\n  strided1D< light1D<double> > sx(x, -2);\n\n  light1D<double> y(dy, 20);\n  strided1D< light1D<double> > sy(y, -2);\n\n  if (dot(sx, sy) == dot(x, y))\n    std::cout << \"success\" << std::endl;\n  else\n    std::cout << \"failure\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "9feb586b230339dec521ad3fa46f70ffc8ea03b5", "size": 584, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/neg_stride.cc", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/neg_stride.cc", "max_issues_repo_name": "parasol-ppl/PPL_utils", "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stapl_release/tools/mtl-2.0/contrib/examples/neg_stride.cc", "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.1764705882, "max_line_length": 41, "alphanum_fraction": 0.5102739726, "num_tokens": 234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4460407945719605}}
{"text": "/*\n * gpcxx/app/benchmark_problems/keijzer.hpp\n * Date: 2015-06-24\n * Author: Karsten Ahnert (karsten.ahnert@gmx.de)\n * Copyright: Karsten Ahnert\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef GPCXX_APP_BENCHMARK_PROBLEMS_KEIJZER_HPP_INCLUDED\n#define GPCXX_APP_BENCHMARK_PROBLEMS_KEIJZER_HPP_INCLUDED\n\n#include <gpcxx/app/generate_evenly_spaced_test_data.hpp>\n#include <gpcxx/app/generate_uniform_distributed_test_data.hpp>\n#include <gpcxx/util/assert.hpp>\n\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n\n\nnamespace gpcxx {\n\n    \ndouble keijzer_func4( double x ) { return 0.3 * x * sin( 2.0 * boost::math::double_constants::pi * x ); }\n\ndouble keijzer_func5( double x ) {\n    double sx = sin( x );\n    double cx = cos( x );\n    return x * x * x * exp( - x ) * cx * sx * ( sx * sx * cx - 1.0 );\n}\n\ndouble keijzer_func6( double x , double y , double z ) { return 30.0 * x * z / ( x - 10.0 ) / y / y; }\n\ndouble keijzer_func7( double x ) {\n    GPCXX_ASSERT( x >= 1.0 );\n    double n = static_cast< double >( static_cast< int >( x ) );\n    return n * ( n - 1 ) / 2.0;\n}\n\ndouble keijzer_func8( double x ) { return std::log( x ); }\n\ndouble keijzer_func9( double x ) { return std::sqrt( x ); }\n\ndouble keijzer_func10( double x ) { return std::asinh( x ); }\n\ndouble keijzer_func11( double x , double y ) { return std::pow( x , y ); }\n\ndouble keijzer_func12( double x , double y ) { return x * y + sin( ( x -1.0 ) * ( y-1.0 ) ); }\n\ndouble keijzer_func13( double x , double y ) { return x * x * x * x - x * x * x + 0.5 * y * y - y; }\n\ndouble keijzer_func14( double x , double y ) { return 6.0 * sin( x ) * cos( x ); }\n\ndouble keijzer_func15( double x , double y ) { return 8.0 / ( 2.0 + x * x + y * y ); }\n\ndouble keijzer_func16( double x , double y ) { return x * x * x / 3.0 + y * y * y / 2.0 - y - x; }\n\n\n\n\nauto generate_keijzer1( void ) {\n    return gpcxx::generate_evenly_spaced_test_data< 1 >( -1.0 , 1.0 , 0.1 , keijzer_func4 );\n}\n\nauto generate_keijzer2( void ) {\n    return gpcxx::generate_evenly_spaced_test_data< 1 >( -2.0 , 2.0 , 0.1 , keijzer_func4 );\n}\n\nauto generate_keijzer3( void ) {\n    return gpcxx::generate_evenly_spaced_test_data< 1 >( -3.0 , 3.0 , 0.1 , keijzer_func4 );\n}\n\nauto generate_keijzer4( void ) {\n    return gpcxx::generate_evenly_spaced_test_data< 1 >( 0.0 , 10.0 , 0.05  , keijzer_func5 );\n}\n\ntemplate< typename Rng >\nauto generate_keijzer5( Rng& rng ) {\n    return gpcxx::generate_uniform_distributed_test_data< 3 >( rng , 1000 ,\n        std::array< std::pair< double , double > , 3 >{{ std::make_pair( -1.0 , 1.0 ) , std::make_pair( 1.0 , 2.0 ) , std::make_pair( -1.0 , 1.0 )  }} ,\n        keijzer_func6 );\n}\n\nauto generate_keijzer6( void ) {\n    return gpcxx::generate_evenly_spaced_test_data< 1 >( 1.0 , 50.0 , 1.0 , keijzer_func7 );\n}\n\nauto generate_keijzer7( void ) {\n    return gpcxx::generate_evenly_spaced_test_data< 1 >( 1.0 , 100.0 , 1.0 , keijzer_func8 );\n}\n\nauto generate_keijzer8( void ) {\n    return gpcxx::generate_evenly_spaced_test_data< 1 >( 0.0 , 100.0 , 1.0 , keijzer_func9 );\n}\n    \nauto generate_keijzer9( void ) {\n    return gpcxx::generate_evenly_spaced_test_data< 1 >( 0.0 , 100.0 , 1.0 , keijzer_func10 );\n}\n\ntemplate< typename Rng >\nauto generate_keijzer10( Rng& rng ) {\n    return gpcxx::generate_uniform_distributed_test_data< 2 >( rng , 100 , 0.0 , 1.0 , keijzer_func11 );\n}\n\ntemplate< typename Rng >\nauto generate_keijzer11( Rng& rng ) {\n    return gpcxx::generate_uniform_distributed_test_data< 2 >( rng , 20 , -3.0 , 3.0 , keijzer_func12 );\n}\n\ntemplate< typename Rng >\nauto generate_keijzer12( Rng& rng ) {\n    return gpcxx::generate_uniform_distributed_test_data< 2 >( rng , 20 , -3.0 , 3.0 , keijzer_func13 );\n}\n\ntemplate< typename Rng >\nauto generate_keijzer13( Rng& rng ) {\n    return gpcxx::generate_uniform_distributed_test_data< 2 >( rng , 20 , -3.0 , 3.0 , keijzer_func14 );\n}\n\ntemplate< typename Rng >\nauto generate_keijzer14( Rng& rng ) {\n    return gpcxx::generate_uniform_distributed_test_data< 2 >( rng , 20 , -3.0 , 3.0 , keijzer_func15 );\n}\n\ntemplate< typename Rng >\nauto generate_keijzer15( Rng& rng ) {\n    return gpcxx::generate_uniform_distributed_test_data< 2 >( rng , 20 , -3.0 , 3.0 , keijzer_func16 );\n}\n\n\n\n\n} // namespace gpcxx\n\n\n#endif // GPCXX_APP_BENCHMARK_PROBLEMS_KEIJZER_HPP_INCLUDED\n", "meta": {"hexsha": "952b1b84e6ee9b074e9567b927f5235b4d632a2a", "size": 4414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gpcxx/app/benchmark_problems/keijzer.hpp", "max_stars_repo_name": "gchoinka/gpcxx", "max_stars_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T08:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T07:28:54.000Z", "max_issues_repo_path": "include/gpcxx/app/benchmark_problems/keijzer.hpp", "max_issues_repo_name": "gchoinka/gpcxx", "max_issues_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-26T23:48:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-29T14:16:37.000Z", "max_forks_repo_path": "include/gpcxx/app/benchmark_problems/keijzer.hpp", "max_forks_repo_name": "gchoinka/gpcxx", "max_forks_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T21:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T05:14:08.000Z", "avg_line_length": 31.7553956835, "max_line_length": 152, "alphanum_fraction": 0.6653828727, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.44604078774379896}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <iostream>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"dpmeans.hpp\"\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\n\ntemplate<class T>\nclass DPvMFMeans : public DPMeans<T>\n{\npublic:\n  DPvMFMeans(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx, uint32_t K0,\n      double lambda, boost::mt19937* pRndGen);\n  virtual ~DPvMFMeans();\n\n//  virtual void updateLabels();\n//  virtual void updateCenters();\n  \n  \n  virtual T dist(const Matrix<T,Dynamic,1>& a, const Matrix<T,Dynamic,1>& b);\n  virtual bool closer(T a, T b);\n  virtual uint32_t indOfClosestCluster(int32_t i);\n  virtual Matrix<T,Dynamic,1> computeCenter(uint32_t k);\n\n//protected:\n//  double lambda_;\n};\n// --------------------------- impl -------------------------------------------\n\ntemplate<class T>\nDPvMFMeans<T>::DPvMFMeans(\n    const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx, uint32_t K0, double lambda,\n    boost::mt19937* pRndGen)\n  : DPMeans<T>(spx,K0, lambda, pRndGen)\n{\n  assert(-2.0 < this->lambda_ && this->lambda_ < 0.0);\n}\n\ntemplate<class T>\nDPvMFMeans<T>::~DPvMFMeans()\n{}\n\ntemplate<class T>\nT DPvMFMeans<T>::dist(const Matrix<T,Dynamic,1>& a, const Matrix<T,Dynamic,1>& b)\n{\n//  return acos(min(1.0,max(-1.0,(a.transpose()*b)(0)))); // angular similarity\n  return a.transpose()*b; // cosine similarity \n};\n\ntemplate<class T>\nbool DPvMFMeans<T>::closer(T a, T b)\n{\n//  return a<b; // if dist a is greater than dist b a is closer than b (angular dist)\n  return a>b; // if dist a is greater than dist b a is closer than b (cosine dist)\n};\n\ntemplate<class T>\nMatrix<T,Dynamic,1> DPvMFMeans<T>::computeCenter(uint32_t k)\n{\n  this->Ns_(k) = 0.0;\n  Matrix<T,Dynamic,1> mean_k(this->D_);\n  mean_k.setZero(this->D_);\n  for(uint32_t i=0; i<this->N_; ++i)\n    if(this->z_(i) == k)\n    {\n      mean_k += this->spx_->col(i); \n      this->Ns_(k) ++;\n    }\n  if(this->Ns_(k) > 0)\n    return mean_k/mean_k.norm();\n  else\n    return mean_k;\n}\n\ntemplate<class T>\nuint32_t DPvMFMeans<T>::indOfClosestCluster(int32_t i)\n{\n  // use cosine similarity because it is faster since acos is not computed\n  int z_i = this->K_;\n  T sim_closest = this->lambda_ +1.;// new formulation -2<lambda<0\n  for(uint32_t k=0; k<this->K_; ++k)\n  {\n    T sim_k = this->ps_.col(k).transpose()* this->spx_->col(i);\n    if( sim_k > sim_closest) // because of cosine distance\n    {\n      sim_closest = sim_k;\n      z_i = k;\n    }\n  }\n  return z_i;\n};\n\n//template<class T>\n//void DPvMFMeans<T>::updateLabels()\n//{\n////#pragma omp parallel for \n//// TODO not sure how to parallelize\n//  for(uint32_t i=0; i<this->N_; ++i)\n//  {\n//\n////    Matrix<T,Dynamic,1> sim(this->K_+1);\n////    sim(this->K_) = lambda_;\n////    for(uint32_t k=0; k<this->K_; ++k)\n////      sim(k) = this->ps_.col(k).transpose()*this->spx_->col(i);\n////    int z_i,dummy;\n//////    cout<<sim.transpose()<<endl;\n////    sim.maxCoeff(&z_i,&dummy);\n//\n//    int z_i = this->K_;\n//    T sim_max = lambda_;\n//    for (uint32_t k=0; k<this->K_; ++k)\n//    {\n//      T sim_k = this->ps_.col(k).transpose()*this->spx_->col(i);\n//      if(sim_k > sim_max)\n//      {\n//        sim_max = sim_k;\n//        z_i = k;\n//      }\n//    }\n//\n//    if(z_i == this->K_) \n//    {\n//      MatrixXd psNew(this->D_,this->K_+1);\n//      psNew.leftCols(this->K_) = this->ps_;\n//      psNew.col(this->K_) = this->spx_->col(i);\n//      this->ps_ = psNew;\n//      this->K_ ++;\n//    }\n//    this->z_(i) = z_i;\n//  }\n//}\n//\n//template<class T>\n//void DPvMFMeans<T>::updateCenters()\n//{\n//  vector<bool> toDelete(this->K_,false);\n//#pragma omp parallel for \n//  for(uint32_t k=0; k<this->K_; ++k)\n//  {\n//    T N_k=0;\n//    Matrix<T,Dynamic,1> mean_k(this->D_);\n//    mean_k.setZero(this->D_);\n//    for(uint32_t i=0; i<this->N_; ++i)\n//      if(this->z_(i) == k)\n//      {\n//        mean_k += this->spx_->col(i); \n//        N_k ++;\n//      }\n//    if (N_k > 0) \n//      this->ps_.col(k) = mean_k/mean_k.norm();\n//    else\n//      toDelete[k] = true;\n//  }\n//\n//  uint32_t kNew = this->K_;\n//  for(int32_t k=this->K_-1; k>-1; --k)\n//    if(toDelete[k])\n//    {\n//      cout<<\"cluster k \"<<k<<\" empty\"<<endl;\n//#pragma omp parallel for \n//      for(uint32_t i=0; i<this->N_; ++i)\n//      {\n//        if(this->z_(i) >= k) this->z_(i)--;\n//      }\n//      kNew --;\n//    }\n//\n//  MatrixXd psNew(this->D_,kNew);\n//  int32_t offset = 0;\n//  for(uint32_t k=0; k<this->K_; ++k)\n//    if(toDelete[k])\n//    {\n//      offset ++;\n//    }else{\n//      psNew.col(k-offset) = this->ps_.col(k);\n//    }\n//  this->ps_ = psNew;\n//  this->K_ = kNew;\n//\n////  cout<<\"centers=\"<<endl<<this->ps_<<endl;\n//}\n//\n\n", "meta": {"hexsha": "072bfa21c46d1cfad59d4550851b4da8bd8eff79", "size": 4675, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/deprecated/dpvMFmeans.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/deprecated/dpvMFmeans.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/deprecated/dpvMFmeans.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 24.4764397906, "max_line_length": 89, "alphanum_fraction": 0.5670588235, "num_tokens": 1538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4460407877437989}}
{"text": "/**\n * \\file dcs/math/stats/distribution/mmpp.hpp\n *\n * \\brief Markov-modulated Poisson Process (MMPP).\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_MATH_STATS_DISTRIBUTION_MMPP_HPP\n#define DCS_MATH_STATS_DISTRIBUTION_MMPP_HPP\n\n\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/operation/diag.hpp>\n#include <cstddef>\n#include <dcs/math/policies/policy.hpp>\n#include <dcs/math/stats/distribution/base_distribution.hpp>\n#include <dcs/math/stats/distribution/map.hpp>\n#include <dcs/math/stats/function/rand.hpp>\n#include <iostream>\n#include <vector>\n\n\nnamespace dcs { namespace math { namespace stats {\n\ntemplate <\n\ttypename RealT = double,\n\ttypename PolicyT = ::dcs::math::policies::policy<>\n>\nclass mmpp_distribution//: public base_distribution<RealT>\n{\n\tpublic: typedef RealT value_type;\n\tpublic: typedef value_type support_type;\n\tpublic: typedef ::boost::numeric::ublas::matrix<support_type> matrix_type;\n\tpublic: typedef ::boost::numeric::ublas::vector<support_type> vector_type;\n\tpublic: typedef ::std::size_t size_type;\n\tprivate: typedef map_distribution<RealT,PolicyT> map_distribution_type;\n\n\n\tpublic: template <typename VectorExprT, typename MatrixExprT>\n\t\tmmpp_distribution(::boost::numeric::ublas::vector_expression<VectorExprT> const& lambda,\n\t\t\t\t\t\t ::boost::numeric::ublas::matrix_expression<MatrixExprT> const& Q)\n\t: //base_type(),\n\t  map_(Q-::boost::numeric::ublasx::diag(lambda), ::boost::numeric::ublasx::diag(lambda))\n\t{\n\t}\n\n\n\t// Compiler-generated copy-constructor, copy-assignment, and destructor\n\t// are fine.\n\n\n\tpublic: vector_type lambda() const\n\t{\n\t\treturn ::boost::numeric::ublasx::diag(map_.D1());\n\t}\n\n\n\tpublic: matrix_type Q() const\n\t{\n\t\treturn map_.D0()+map_.D1();\n\t}\n\n\n/*\n\tprivate: value_type do_rand(::dcs::math::random::any_generator<value_type>& rng) const\n\t{\n\t\treturn rand_sample(rng);\n\t}\n\n\tprivate: value_type do_rand(::dcs::math::random::base_generator<value_type>& rng) const\n\t{\n\t\treturn rand_sample(rng);\n\t}\n*/\n\n\tpublic: template <typename URNG>\n\t\tvalue_type rand(URNG& rng) const\n\t{\n\t\treturn map_.rand(rng);\n\t}\n\n\n\t/**\n\t * The following algorithm is an adaptation of the one found in the MMPP-QN\n\t * toolbox (by G. Casale et al, http://www.cs.wm.edu/MMPPQN/).\n\t */\n\tpublic: template <typename URNG>\n\t\t::std::vector<value_type> rand(URNG& rng, size_type n) const\n\t{\n\t\treturn map_.rand(rng, n);\n\t}\n\n\n\tprivate: map_distribution_type map_;\n};\n\n\ntemplate <\n\ttypename CharT,\n\ttypename CharTraitsT,\n\ttypename RealT,\n\ttypename PolicyT\n>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os, mmpp_distribution<RealT,PolicyT> const& dist)\n{\n\treturn os << \"MMPP(\"\n\t\t\t  << \"lambda=\" <<  dist.lambda()\n\t\t\t  << \",Q=\" <<  dist.Q()\n\t\t\t  << \")\";\n}\n\n}}} // Namespace dcs:math::stats\n\n\n#endif // DCS_MATH_STATS_DISTRIBUTION_MMPP_HPP\n", "meta": {"hexsha": "b715ee164026f92d0fdcf164afc6cd60307af96a", "size": 3704, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/stats/distribution/mmpp.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/math/stats/distribution/mmpp.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/math/stats/distribution/mmpp.hpp", "max_forks_repo_name": "sguazt/dcsxx-commons", "max_forks_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8405797101, "max_line_length": 142, "alphanum_fraction": 0.7281317495, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.44604078091563715}}
{"text": "/*=========================================================================\n *\n *  Copyright 2011-2013 The University of North Carolina at Chapel Hill\n *  All rights reserved.\n *\n *  Licensed under the MADAI Software License. You may obtain a copy of\n *  this license at\n *\n *         https://madai-public.cs.unc.edu/visualization/software-license/\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*/\n\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <vector>\n\n#include <Eigen/Dense>\n#include \"GaussianProcessEmulatorTestGenerator.h\"\n#include \"GaussianProcessEmulator.h\"\n#include \"GaussianProcessEmulatorDirectoryFormatIO.h\"\n#include \"Paths.h\"\n\nconst char DEFAULT_MODEL_OUTPUT_DIRECTORY[] = \"model_output\";\nconst char DEFAULT_EXPERIMENTAL_RESULTS_FILE[] = \"experimental_results.dat\";\n\ninline double LogisticFunction(double x) {\n  return 1.0 / (1.0 + std::exp(-x));\n}\ninline double sinc(double x) {\n  if (x==0) return 1.0;\n  x *= 3.141592653589793;\n  return std::sin(x) / x;\n}\nvoid model(const std::vector< double > & params, std::vector< double > & out) {\n  const double & x = params[0];\n  const double & y = params[1];\n  out.at(0) = sinc(std::sqrt((x * x) + (y * y) + (0.5 * x * y)));\n  out.at(1) = LogisticFunction(x - 0.25 * y);\n}\n\n\nint main( int, char *[] ) {\n  static const int N = 100;\n\n  madai::Parameter param0( \"param_0\", -1, 1 );\n  madai::Parameter param1( \"param_1\", -1, 1 );\n  std::vector< madai::Parameter > parameters;\n  parameters.push_back( param0 );\n  parameters.push_back( param1 );\n\n  GaussianProcessEmulatorTestGenerator generator( &model,2,2,N, parameters);\n\n  std::string TempDirectory = \"../Testing/Temporary/GaussianProcessEmulatorTest\";\n  if ( !generator.WriteDirectoryStructure(TempDirectory) ) {\n    std::cerr << \"Error writing directory structure\\n\";\n    return EXIT_FAILURE;\n  }\n\n  std::string MOD = TempDirectory + madai::Paths::SEPARATOR +\n    DEFAULT_MODEL_OUTPUT_DIRECTORY;\n  std::string ERF = TempDirectory + madai::Paths::SEPARATOR +\n    DEFAULT_EXPERIMENTAL_RESULTS_FILE;\n\n  madai::GaussianProcessEmulator gpe;\n  madai::GaussianProcessEmulatorDirectoryFormatIO directoryReader;\n  if ( !directoryReader.LoadTrainingData( &gpe, MOD, TempDirectory, ERF ) ) {\n    std::cerr << \"Error loading from created directory structure\\n\";\n    return EXIT_FAILURE;\n  }\n\n  if ( !gpe.PrincipalComponentDecompose() ) {\n    std::cerr << \"Error decomposing model data.\\n\";\n    return EXIT_FAILURE;\n  }\n\n  std::string PCAFileName = TempDirectory + madai::Paths::SEPARATOR\n      + madai::Paths::PCA_DECOMPOSITION_FILE;\n  std::ofstream PCAFile( PCAFileName.c_str() );\n  if ( !PCAFile ) {\n    std::cerr << \"Could not open file '\" << PCAFileName << \"'\\n\";\n    return EXIT_FAILURE;\n  }\n\n  madai::GaussianProcessEmulatorDirectoryFormatIO directoryFormatIO;\n  directoryFormatIO.WritePCA( &gpe, PCAFile );\n  PCAFile.close();\n\n  double fractionResolvingPower = 0.999;\n  madai::GaussianProcessEmulator::CovarianceFunctionType covarianceFunction\n      = madai::GaussianProcessEmulator::SQUARE_EXPONENTIAL_FUNCTION;\n  int regressionOrder = 1;\n  double defaultNugget = 1e-3;\n  double amplitude = 1.0;\n  double scale = 1e-2;\n\n  if (! gpe.RetainPrincipalComponents( fractionResolvingPower ) )\n    return EXIT_FAILURE;\n\n  if (! gpe.BasicTraining(\n          covarianceFunction,\n          regressionOrder,\n          defaultNugget,\n          amplitude,\n          scale))\n    return EXIT_FAILURE;\n\n  std::string EmulatorStateFileName = TempDirectory + madai::Paths::SEPARATOR\n      + madai::Paths::EMULATOR_STATE_FILE;\n  std::ofstream EmulatorStateFile( EmulatorStateFileName.c_str() );\n  if ( !EmulatorStateFile ) {\n    std::cerr << \"Could not open file '\" << EmulatorStateFileName << \"'\\n\";\n    return EXIT_FAILURE;\n  }\n\n  directoryFormatIO.Write( &gpe, EmulatorStateFile );\n  EmulatorStateFile.close();\n\n  if (! gpe.MakeCache()) {\n    std::cerr << \"Error while makeing cache.\\n\";\n    return false;\n  }\n\n  std::cout.precision(17);\n  double error = 0.0;\n\n  std::vector< double > x(2,0.0);\n  std::vector< double > y(2,0.0);\n  for (int i = 0; i < N; ++i) {\n    x[0] = generator.m_X(i,0);\n    x[1] = generator.m_X(i,1);\n    if (! gpe.GetEmulatorOutputs(x, y))\n      return EXIT_FAILURE;\n    error += std::abs(y[0] - generator.m_Y(i,0));\n    error += std::abs(y[1] - generator.m_Y(i,1));\n  }\n  std::cout << \"Sum of errors at training points: \" << error << '\\n';\n\n  error = 0.0;\n  std::vector< double > y2(2,0.0);\n  double range_over_N = 2.0 / static_cast< double >(N);\n  double half_range_over_N = 0.5 * range_over_N;\n  for (int i = 0; i < N; ++i) {\n    x[0] = range_over_N * i + half_range_over_N;\n    for (int j = 0; j < N; ++j) {\n      x[1] = range_over_N * j + half_range_over_N;\n      gpe.GetEmulatorOutputs(x, y);\n      model(x, y2);\n      error = std::max(error, std::abs(y[0] - y2[0]));\n      error = std::max(error, std::abs(y[1] - y2[1]));\n    }\n  }\n  std::cout << \"Maximum error over all space: \" << error << '\\n';\n\n  std::string ThetaFileName = TempDirectory + madai::Paths::SEPARATOR + \"thetas.dat\";\n  std::ofstream ThetaFile( ThetaFileName.c_str() );\n  if(! directoryFormatIO.PrintThetas(&gpe,ThetaFile)) {\n    std::cerr << \"Error printing Thetas.\\n\";\n    return EXIT_FAILURE;\n  }\n  ThetaFile.close();\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "3599fc0650d5c24270a113766bb4db1631d2cbde", "size": 5608, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/GaussianProcessEmulatorTest.cxx", "max_stars_repo_name": "scottedwardpratt/MADAI", "max_stars_repo_head_hexsha": "9f9ee0dac704d77492d9905b4d90a57746201912", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-28T20:14:23.000Z", "max_issues_repo_path": "test/GaussianProcessEmulatorTest.cxx", "max_issues_repo_name": "scottedwardpratt/MADAI", "max_issues_repo_head_hexsha": "9f9ee0dac704d77492d9905b4d90a57746201912", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/GaussianProcessEmulatorTest.cxx", "max_forks_repo_name": "scottedwardpratt/MADAI", "max_forks_repo_head_hexsha": "9f9ee0dac704d77492d9905b4d90a57746201912", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-08-20T14:07:41.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-28T20:15:23.000Z", "avg_line_length": 32.7953216374, "max_line_length": 85, "alphanum_fraction": 0.6576319544, "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.44604078091563715}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2018 Adeel Ahmad, Islamabad, Pakistan.\n\n// Contributed and/or modified by Adeel Ahmad, as part of Google Summer of Code 2018 program.\n\n// This file was modified by Oracle on 2019.\n// Modifications copyright (c) 2019 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from GeographicLib, https://geographiclib.sourceforge.io\n// GeographicLib is originally written by Charles Karney.\n\n// Author: Charles Karney (2008-2017)\n\n// Last updated version of GeographicLib: 1.49\n\n// Original copyright notice:\n\n// Copyright (c) Charles Karney (2008-2017) <charles@karney.com> and licensed\n// under the MIT/X11 License. For more information, see\n// https://geographiclib.sourceforge.io\n\n#ifndef BOOST_GEOMETRY_FORMULAS_KARNEY_INVERSE_HPP\n#define BOOST_GEOMETRY_FORMULAS_KARNEY_INVERSE_HPP\n\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/series_expansion.hpp>\n#include <boost/geometry/util/normalize_spheroidal_coordinates.hpp>\n\n#include <boost/geometry/formulas/flattening.hpp>\n#include <boost/geometry/formulas/result_inverse.hpp>\n\n\nnamespace boost { namespace geometry { namespace math {\n\n// TODO: Moved temporarily because of C++11 is used\n\n/*!\n\\brief The exact difference of two angles reduced to (-180deg, 180deg].\n*/\ntemplate<typename T>\ninline T difference_angle(T const& x, T const& y, T& e)\n{\n    T t, d = math::sum_error(std::remainder(-x, T(360)), std::remainder(y, T(360)), t);\n\n    normalize_azimuth<degree, T>(d);\n\n    // Here y - x = d + t (mod 360), exactly, where d is in (-180,180] and\n    // abs(t) <= eps (eps = 2^-45 for doubles).  The only case where the\n    // addition of t takes the result outside the range (-180,180] is d = 180\n    // and t > 0.  The case, d = -180 + eps, t = -eps, can't happen, since\n    // sum_error would have returned the exact result in such a case (i.e., given t = 0).\n    return math::sum_error(d == 180 && t > 0 ? -180 : d, t, e);\n}\n\n}}} // namespace boost::geometry::math\n\n\nnamespace boost { namespace geometry { namespace formula\n{\n\nnamespace se = series_expansion;\n\n/*!\n\\brief The solution of the inverse problem of geodesics on latlong coordinates,\n       after Karney (2011).\n\\author See\n- Charles F.F Karney, Algorithms for geodesics, 2011\nhttps://arxiv.org/pdf/1109.4448.pdf\n*/\ntemplate <\n    typename CT,\n    bool EnableDistance,\n    bool EnableAzimuth,\n    bool EnableReverseAzimuth = false,\n    bool EnableReducedLength = false,\n    bool EnableGeodesicScale = false,\n    size_t SeriesOrder = 8\n>\nclass karney_inverse\n{\n    static const bool CalcQuantities = EnableReducedLength || EnableGeodesicScale;\n    static const bool CalcAzimuths = EnableAzimuth || EnableReverseAzimuth || CalcQuantities;\n    static const bool CalcFwdAzimuth = EnableAzimuth || CalcQuantities;\n    static const bool CalcRevAzimuth = EnableReverseAzimuth || CalcQuantities;\n\npublic:\n    typedef result_inverse<CT> result_type;\n\n    template <typename T1, typename T2, typename Spheroid>\n    static inline result_type apply(T1 const& lo1,\n                                    T1 const& la1,\n                                    T2 const& lo2,\n                                    T2 const& la2,\n                                    Spheroid const& spheroid)\n    {\n        static CT const c0 = 0;\n        static CT const c0_001 = 0.001;\n        static CT const c0_1 = 0.1;\n        static CT const c1 = 1;\n        static CT const c2 = 2;\n        static CT const c3 = 3;\n        static CT const c8 = 8;\n        static CT const c16 = 16;\n        static CT const c90 = 90;\n        static CT const c180 = 180;\n        static CT const c200 = 200;\n        static CT const pi = math::pi<CT>();\n        static CT const d2r = math::d2r<CT>();\n        static CT const r2d = math::r2d<CT>();\n\n        result_type result;\n\n        CT lat1 = la1;\n        CT lat2 = la2;\n\n        CT lon1 = lo1;\n        CT lon2 = lo2;\n\n        CT const a = CT(get_radius<0>(spheroid));\n        CT const b = CT(get_radius<2>(spheroid));\n        CT const f = formula::flattening<CT>(spheroid);\n        CT const one_minus_f = c1 - f;\n        CT const two_minus_f = c2 - f;\n\n        CT const tol0 = std::numeric_limits<CT>::epsilon();\n        CT const tol1 = c200 * tol0;\n        CT const tol2 = sqrt(tol0);\n\n        // Check on bisection interval.\n        CT const tol_bisection = tol0 * tol2;\n\n        CT const etol2 = c0_1 * tol2 /\n            sqrt((std::max)(c0_001, std::abs(f)) * (std::min)(c1, c1 - f / c2) / c2);\n\n        CT tiny = std::sqrt((std::numeric_limits<CT>::min)());\n\n        CT const n = f / two_minus_f;\n        CT const e2 = f * two_minus_f;\n        CT const ep2 = e2 / math::sqr(one_minus_f);\n\n        // Compute the longitudinal difference.\n        CT lon12_error;\n        CT lon12 = math::difference_angle(lon1, lon2, lon12_error);\n\n        int lon12_sign = lon12 >= 0 ? 1 : -1;\n\n        // Make points close to the meridian to lie on it.\n        lon12 = lon12_sign * lon12;\n        lon12_error = (c180 - lon12) - lon12_sign * lon12_error;\n\n        // Convert to radians.\n        CT lam12 = lon12 * d2r;\n        CT sin_lam12;\n        CT cos_lam12;\n\n        if (lon12 > c90)\n        {\n            math::sin_cos_degrees(lon12_error, sin_lam12, cos_lam12);\n            cos_lam12 *= -c1;\n        }\n        else\n        {\n            math::sin_cos_degrees(lon12, sin_lam12, cos_lam12);\n        }\n\n        // Make points close to the equator to lie on it.\n        lat1 = math::round_angle(std::abs(lat1) > c90 ? c90 : lat1);\n        lat2 = math::round_angle(std::abs(lat2) > c90 ? c90 : lat2);\n\n        // Arrange points in a canonical form, as explained in\n        // paper, Algorithms for geodesics, Eq. (44):\n        //\n        //     0 <= lon12 <= 180\n        //     -90 <= lat1 <= 0\n        //     lat1 <= lat2 <= -lat1\n        int swap_point = std::abs(lat1) < std::abs(lat2) ? -1 : 1;\n\n        if (swap_point < 0)\n        {\n            lon12_sign *= -1;\n            swap(lat1, lat2);\n        }\n\n        // Enforce lat1 to be <= 0.\n        int lat_sign = lat1 < 0 ? 1 : -1;\n        lat1 *= lat_sign;\n        lat2 *= lat_sign;\n\n        CT sin_beta1, cos_beta1;\n        math::sin_cos_degrees(lat1, sin_beta1, cos_beta1);\n        sin_beta1 *= one_minus_f;\n\n        math::normalize_unit_vector<CT>(sin_beta1, cos_beta1);\n        cos_beta1 = (std::max)(tiny, cos_beta1);\n\n        CT sin_beta2, cos_beta2;\n        math::sin_cos_degrees(lat2, sin_beta2, cos_beta2);\n        sin_beta2 *= one_minus_f;\n\n        math::normalize_unit_vector<CT>(sin_beta2, cos_beta2);\n        cos_beta2 = (std::max)(tiny, cos_beta2);\n\n        // If cos_beta1 < -sin_beta1, then cos_beta2 - cos_beta1 is a\n        // sensitive measure of the |beta1| - |beta2|. Alternatively,\n        // (cos_beta1 >= -sin_beta1), abs(sin_beta2) + sin_beta1 is\n        // a better measure.\n        // Sometimes these quantities vanish and in that case we\n        // force beta2 = +/- bet1a exactly.\n        if (cos_beta1 < -sin_beta1)\n        {\n            if (cos_beta1 == cos_beta2)\n            {\n                sin_beta2 = sin_beta2 < 0 ? sin_beta1 : -sin_beta1;\n            }\n        }\n        else\n        {\n            if (std::abs(sin_beta2) == -sin_beta1)\n            {\n                cos_beta2 = cos_beta1;\n            }\n        }\n\n        CT const dn1 = sqrt(c1 + ep2 * math::sqr(sin_beta1));\n        CT const dn2 = sqrt(c1 + ep2 * math::sqr(sin_beta2));\n\n        CT sigma12;\n        CT m12x, s12x, M21;\n\n        // Index zero element of coeffs_C1 is unused.\n        se::coeffs_C1<SeriesOrder, CT> const coeffs_C1(n);\n\n        bool meridian = lat1 == -90 || sin_lam12 == 0;\n\n        CT cos_alpha1, sin_alpha1;\n        CT cos_alpha2, sin_alpha2;\n\n        if (meridian)\n        {\n            // Endpoints lie on a single full meridian.\n\n            // Point to the target latitude.\n            cos_alpha1 = cos_lam12;\n            sin_alpha1 = sin_lam12;\n\n            // Heading north at the target.\n            cos_alpha2 = c1;\n            sin_alpha2 = c0;\n\n            CT sin_sigma1 = sin_beta1;\n            CT cos_sigma1 = cos_alpha1 * cos_beta1;\n\n            CT sin_sigma2 = sin_beta2;\n            CT cos_sigma2 = cos_alpha2 * cos_beta2;\n\n            CT sigma12 = std::atan2((std::max)(c0, cos_sigma1 * sin_sigma2 - sin_sigma1 * cos_sigma2),\n                                                   cos_sigma1 * cos_sigma2 + sin_sigma1 * sin_sigma2);\n\n            CT dummy;\n            meridian_length(n, ep2, sigma12, sin_sigma1, cos_sigma1, dn1,\n                                             sin_sigma2, cos_sigma2, dn2,\n                                             cos_beta1, cos_beta2, s12x,\n                                             m12x, dummy, result.geodesic_scale,\n                                             M21, coeffs_C1);\n\n            if (sigma12 < c1 || m12x >= c0)\n            {\n                if (sigma12 < c3 * tiny)\n                {\n                    sigma12  = m12x = s12x = c0;\n                }\n\n                m12x *= b;\n                s12x *= b;\n            }\n            else\n            {\n                // m12 < 0, i.e., prolate and too close to anti-podal.\n                meridian = false;\n            }\n        }\n\n        CT omega12;\n\n        if (!meridian && sin_beta1 == c0 &&\n            (f <= c0 || lon12_error >= f * c180))\n        {\n            // Points lie on the equator.\n            cos_alpha1 = cos_alpha2 = c0;\n            sin_alpha1 = sin_alpha2 = c1;\n\n            s12x = a * lam12;\n            sigma12 = omega12 = lam12 / one_minus_f;\n            m12x = b * sin(sigma12);\n\n            if (BOOST_GEOMETRY_CONDITION(EnableGeodesicScale))\n            {\n                result.geodesic_scale = cos(sigma12);\n            }\n        }\n        else if (!meridian)\n        {\n            // If point1 and point2 belong within a hemisphere bounded by a\n            // meridian and geodesic is neither meridional nor equatorial.\n\n            // Find the starting point for Newton's method.\n            CT dnm;\n            sigma12 = newton_start(sin_beta1, cos_beta1, dn1,\n                                   sin_beta2, cos_beta2, dn2,\n                                   lam12, sin_lam12, cos_lam12,\n                                   sin_alpha1, cos_alpha1,\n                                   sin_alpha2, cos_alpha2,\n                                   dnm, coeffs_C1, ep2,\n                                   tol1, tol2, etol2,\n                                   n, f);\n\n            if (sigma12 >= c0)\n            {\n                // Short lines case (newton_start sets sin_alpha2, cos_alpha2, dnm).\n                s12x = sigma12 * b * dnm;\n                m12x = math::sqr(dnm) * b * sin(sigma12 / dnm);\n                if (BOOST_GEOMETRY_CONDITION(EnableGeodesicScale))\n                {\n                    result.geodesic_scale = cos(sigma12 / dnm);\n                }\n\n                // Convert to radians.\n                omega12 = lam12 / (one_minus_f * dnm);\n            }\n            else\n            {\n                // Apply the Newton's method.\n                CT sin_sigma1 = c0, cos_sigma1 = c0;\n                CT sin_sigma2 = c0, cos_sigma2 = c0;\n                CT eps = c0, diff_omega12 = c0;\n\n                // Bracketing range.\n                CT sin_alpha1a = tiny, cos_alpha1a = c1;\n                CT sin_alpha1b = tiny, cos_alpha1b = -c1;\n\n                size_t iteration = 0;\n                size_t max_iterations = 20 + std::numeric_limits<size_t>::digits + 10;\n\n                for (bool tripn = false, tripb = false;\n                     iteration < max_iterations;\n                     ++iteration)\n                {\n                    CT dv;\n                    CT v = lambda12(sin_beta1, cos_beta1, dn1,\n                                    sin_beta2, cos_beta2, dn2,\n                                    sin_alpha1, cos_alpha1,\n                                    sin_lam12, cos_lam12,\n                                    sin_alpha2, cos_alpha2,\n                                    sigma12,\n                                    sin_sigma1, cos_sigma1,\n                                    sin_sigma2, cos_sigma2,\n                                    eps, diff_omega12,\n                                    iteration < max_iterations,\n                                    dv, f, n, ep2, tiny, coeffs_C1);\n\n                    // Reversed test to allow escape with NaNs.\n                    if (tripb || !(std::abs(v) >= (tripn ? c8 : c1) * tol0))\n                        break;\n\n                    // Update bracketing values.\n                    if (v > c0 && (iteration > max_iterations ||\n                        cos_alpha1 / sin_alpha1 > cos_alpha1b / sin_alpha1b))\n                    {\n                        sin_alpha1b = sin_alpha1;\n                        cos_alpha1b = cos_alpha1;   \n                    }\n                    else if (v < c0 && (iteration > max_iterations ||\n                             cos_alpha1 / sin_alpha1 < cos_alpha1a / sin_alpha1a))\n                    {\n                        sin_alpha1a = sin_alpha1;\n                        cos_alpha1a = cos_alpha1;\n                    }\n\n                    if (iteration < max_iterations && dv > c0)\n                    {\n                        CT diff_alpha1 = -v / dv;\n\n                        CT sin_diff_alpha1 = sin(diff_alpha1);\n                        CT cos_diff_alpha1 = cos(diff_alpha1);\n\n                        CT nsin_alpha1 = sin_alpha1 * cos_diff_alpha1 +\n                            cos_alpha1 * sin_diff_alpha1;\n\n                        if (nsin_alpha1 > c0 && std::abs(diff_alpha1) < pi)\n                        {\n                            cos_alpha1 = cos_alpha1 * cos_diff_alpha1 - sin_alpha1 * sin_diff_alpha1;\n                            sin_alpha1 = nsin_alpha1;\n                            math::normalize_unit_vector<CT>(sin_alpha1, cos_alpha1);\n\n                            // In some regimes we don't get quadratic convergence because\n                            // slope -> 0. So use convergence conditions based on epsilon\n                            // instead of sqrt(epsilon).\n                            tripn = std::abs(v) <= c16 * tol0;\n                            continue;\n                        }\n                    }\n\n                    // Either dv was not positive or updated value was outside legal\n                    // range. Use the midpoint of the bracket as the next estimate.\n                    // This mechanism is not needed for the WGS84 ellipsoid, but it does\n                    // catch problems with more eeccentric ellipsoids. Its efficacy is\n                    // such for the WGS84 test set with the starting guess set to alp1 =\n                    // 90deg:\n                    // the WGS84 test set: mean = 5.21, sd = 3.93, max = 24\n                    // WGS84 and random input: mean = 4.74, sd = 0.99\n                    sin_alpha1 = (sin_alpha1a + sin_alpha1b) / c2;\n                    cos_alpha1 = (cos_alpha1a + cos_alpha1b) / c2;\n                    math::normalize_unit_vector<CT>(sin_alpha1, cos_alpha1);\n                    tripn = false;\n                    tripb = (std::abs(sin_alpha1a - sin_alpha1) + (cos_alpha1a - cos_alpha1) < tol_bisection ||\n                             std::abs(sin_alpha1 - sin_alpha1b) + (cos_alpha1 - cos_alpha1b) < tol_bisection);\n                }\n\n                CT dummy;\n                se::coeffs_C1<SeriesOrder, CT> const coeffs_C1_eps(eps);\n                // Ensure that the reduced length and geodesic scale are computed in\n                // a \"canonical\" way, with the I2 integral.\n                meridian_length(eps, ep2, sigma12, sin_sigma1, cos_sigma1, dn1,\n                                                   sin_sigma2, cos_sigma2, dn2,\n                                                   cos_beta1, cos_beta2, s12x,\n                                                   m12x, dummy, result.geodesic_scale,\n                                                   M21, coeffs_C1_eps);\n\n                m12x *= b;\n                s12x *= b;\n            }\n        }\n\n        if (swap_point < 0)\n        {\n            swap(sin_alpha1, sin_alpha2);\n            swap(cos_alpha1, cos_alpha2);\n            swap(result.geodesic_scale, M21);\n        }\n\n        sin_alpha1 *= swap_point * lon12_sign;\n        cos_alpha1 *= swap_point * lat_sign;\n\n        sin_alpha2 *= swap_point * lon12_sign;\n        cos_alpha2 *= swap_point * lat_sign;\n\n        if (BOOST_GEOMETRY_CONDITION(EnableReducedLength))\n        {\n            result.reduced_length = m12x;\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(CalcAzimuths))\n        {\n            if (BOOST_GEOMETRY_CONDITION(CalcFwdAzimuth))\n            {\n                result.azimuth = atan2(sin_alpha1, cos_alpha1) * r2d;\n            }\n\n            if (BOOST_GEOMETRY_CONDITION(CalcRevAzimuth))\n            {\n                result.reverse_azimuth = atan2(sin_alpha2, cos_alpha2) * r2d;\n            }\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(EnableDistance))\n        {\n            result.distance = s12x;\n        }\n\n        return result;\n    }\n\n    template <typename CoeffsC1>\n    static inline void meridian_length(CT const& epsilon, CT const& ep2, CT const& sigma12,\n                                       CT const& sin_sigma1, CT const& cos_sigma1, CT const& dn1,\n                                       CT const& sin_sigma2, CT const& cos_sigma2, CT const& dn2,\n                                       CT const& cos_beta1, CT const& cos_beta2,\n                                       CT& s12x, CT& m12x, CT& m0,\n                                       CT& M12, CT& M21,\n                                       CoeffsC1 const& coeffs_C1)\n    {\n        static CT const c1 = 1;\n\n        CT A12x = 0, J12 = 0;\n        CT expansion_A1, expansion_A2;\n\n        // Evaluate the coefficients for C2.\n        se::coeffs_C2<SeriesOrder, CT> coeffs_C2(epsilon);\n\n        if (BOOST_GEOMETRY_CONDITION(EnableDistance) ||\n            BOOST_GEOMETRY_CONDITION(EnableReducedLength) ||\n            BOOST_GEOMETRY_CONDITION(EnableGeodesicScale))\n        {\n            // Find the coefficients for A1 by computing the\n            // series expansion using Horner scehme.\n            expansion_A1 = se::evaluate_A1<SeriesOrder>(epsilon);\n\n            if (BOOST_GEOMETRY_CONDITION(EnableReducedLength) ||\n                BOOST_GEOMETRY_CONDITION(EnableGeodesicScale))\n            {\n                // Find the coefficients for A2 by computing the\n                // series expansion using Horner scehme.\n                expansion_A2 = se::evaluate_A2<SeriesOrder>(epsilon);\n\n                A12x = expansion_A1 - expansion_A2;\n                expansion_A2 += c1;\n            }\n            expansion_A1 += c1;\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(EnableDistance))\n        {\n            CT B1 = se::sin_cos_series(sin_sigma2, cos_sigma2, coeffs_C1)\n                  - se::sin_cos_series(sin_sigma1, cos_sigma1, coeffs_C1);\n\n            s12x = expansion_A1 * (sigma12 + B1);\n\n            if (BOOST_GEOMETRY_CONDITION(EnableReducedLength) ||\n                BOOST_GEOMETRY_CONDITION(EnableGeodesicScale))\n            {\n                CT B2 = se::sin_cos_series(sin_sigma2, cos_sigma2, coeffs_C2)\n                      - se::sin_cos_series(sin_sigma1, cos_sigma1, coeffs_C2);\n\n                J12 = A12x * sigma12 + (expansion_A1 * B1 - expansion_A2 * B2);\n            }\n        }\n        else if (BOOST_GEOMETRY_CONDITION(EnableReducedLength) ||\n                 BOOST_GEOMETRY_CONDITION(EnableGeodesicScale))\n        {\n            for (size_t i = 1; i <= SeriesOrder; ++i)\n            {\n                coeffs_C2[i] = expansion_A1 * coeffs_C1[i] -\n                               expansion_A2 * coeffs_C2[i];\n            }\n\n            J12 = A12x * sigma12 +\n                   (se::sin_cos_series(sin_sigma2, cos_sigma2, coeffs_C2)\n                  - se::sin_cos_series(sin_sigma1, cos_sigma1, coeffs_C2));\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(EnableReducedLength))\n        {\n            m0 = A12x;\n\n            m12x = dn2 * (cos_sigma1 * sin_sigma2) -\n                   dn1 * (sin_sigma1 * cos_sigma2) -\n                   cos_sigma1 * cos_sigma2 * J12;\n        }\n\n        if (BOOST_GEOMETRY_CONDITION(EnableGeodesicScale))\n        {\n            CT cos_sigma12 = cos_sigma1 * cos_sigma2 + sin_sigma1 * sin_sigma2;\n            CT t = ep2 * (cos_beta1 - cos_beta2) *\n                         (cos_beta1 + cos_beta2) / (dn1 + dn2);\n\n            M12 = cos_sigma12 + (t * sin_sigma2 - cos_sigma2 * J12) * sin_sigma1 / dn1;\n            M21 = cos_sigma12 - (t * sin_sigma1 - cos_sigma1 * J12) * sin_sigma2 / dn2;\n        }\n    }\n\n    /*\n     Return a starting point for Newton's method in sin_alpha1 and\n     cos_alpha1 (function value is -1). If Newton's method\n     doesn't need to be used, return also sin_alpha2 and\n     cos_alpha2 and function value is sig12.\n    */\n    template <typename CoeffsC1>\n    static inline CT newton_start(CT const& sin_beta1, CT const& cos_beta1, CT const& dn1,\n                                  CT const& sin_beta2, CT const& cos_beta2, CT dn2,\n                                  CT const& lam12, CT const& sin_lam12, CT const& cos_lam12,\n                                  CT& sin_alpha1, CT& cos_alpha1,\n                                  CT& sin_alpha2, CT& cos_alpha2,\n                                  CT& dnm, CoeffsC1 const& coeffs_C1, CT const& ep2,\n                                  CT const& tol1, CT const& tol2, CT const& etol2, CT const& n, CT const& f)\n    {\n        static CT const c0 = 0;\n        static CT const c0_01 = 0.01;\n        static CT const c0_1 = 0.1;\n        static CT const c0_5 = 0.5;\n        static CT const c1 = 1;\n        static CT const c2 = 2;\n        static CT const c6 = 6;\n        static CT const c1000 = 1000;\n        static CT const pi = math::pi<CT>();\n\n        CT const one_minus_f = c1 - f;\n        CT const x_thresh = c1000 * tol2;\n\n        // Return a starting point for Newton's method in sin_alpha1\n        // and cos_alpha1 (function value is -1). If Newton's method\n        // doesn't need to be used, return also sin_alpha2 and\n        // cos_alpha2 and function value is sig12.\n        CT sig12 = -c1;\n\n        // bet12 = bet2 - bet1 in [0, pi); beta12a = bet2 + bet1 in (-pi, 0]\n        CT sin_beta12 = sin_beta2 * cos_beta1 - cos_beta2 * sin_beta1;\n        CT cos_beta12 = cos_beta2 * cos_beta1 + sin_beta2 * sin_beta1;\n\n        CT sin_beta12a = sin_beta2 * cos_beta1 + cos_beta2 * sin_beta1;\n\n        bool shortline = cos_beta12 >= c0 && sin_beta12 < c0_5 &&\n            cos_beta2 * lam12 < c0_5;\n\n        CT sin_omega12, cos_omega12;\n\n        if (shortline)\n        {\n            CT sin_beta_m2 = math::sqr(sin_beta1 + sin_beta2);\n\n            sin_beta_m2 /= sin_beta_m2 + math::sqr(cos_beta1 + cos_beta2);\n            dnm = math::sqrt(c1 + ep2 * sin_beta_m2);\n\n            CT omega12 = lam12 / (one_minus_f * dnm);\n\n            sin_omega12 = sin(omega12);\n            cos_omega12 = cos(omega12);\n        }\n        else\n        {\n            sin_omega12 = sin_lam12;\n            cos_omega12 = cos_lam12;\n        }\n\n        sin_alpha1 = cos_beta2 * sin_omega12;\n        cos_alpha1 = cos_omega12 >= c0 ?\n            sin_beta12 + cos_beta2 * sin_beta1 * math::sqr(sin_omega12) / (c1 + cos_omega12) :\n            sin_beta12a - cos_beta2 * sin_beta1 * math::sqr(sin_omega12) / (c1 - cos_omega12);\n\n        CT sin_sigma12 = boost::math::hypot(sin_alpha1, cos_alpha1);\n        CT cos_sigma12 = sin_beta1 * sin_beta2 + cos_beta1 * cos_beta2 * cos_omega12;\n\n        if (shortline && sin_sigma12 < etol2)\n        {\n            sin_alpha2 = cos_beta1 * sin_omega12;\n            cos_alpha2 = sin_beta12 - cos_beta1 * sin_beta2 *\n                (cos_omega12 >= c0 ? math::sqr(sin_omega12) /\n                (c1 + cos_omega12) : c1 - cos_omega12);\n\n            math::normalize_unit_vector<CT>(sin_alpha2, cos_alpha2);\n            // Set return value.\n            sig12 = atan2(sin_sigma12, cos_sigma12);\n        }\n        // Skip astroid calculation if too eccentric.\n        else if (std::abs(n) > c0_1 ||\n                 cos_sigma12 >= c0 ||\n                 sin_sigma12 >= c6 * std::abs(n) * pi *\n                 math::sqr(cos_beta1))\n        {\n            // Nothing to do, zeroth order spherical approximation will do.\n        }\n        else\n        {\n            // Scale lam12 and bet2 to x, y coordinate system where antipodal\n            // point is at origin and singular point is at y = 0, x = -1.\n            CT lambda_scale, beta_scale;\n\n            CT y;\n            volatile CT x;\n\n            CT lam12x = atan2(-sin_lam12, -cos_lam12);\n            if (f >= c0)\n            {\n                CT k2 = math::sqr(sin_beta1) * ep2;\n                CT eps = k2 / (c2 * (c1 + sqrt(c1 + k2)) + k2);\n\n                se::coeffs_A3<SeriesOrder, CT> const coeffs_A3(n);\n\n                CT const A3 = math::horner_evaluate(eps, coeffs_A3.begin(), coeffs_A3.end());\n\n                lambda_scale = f * cos_beta1 * A3 * pi;\n                beta_scale = lambda_scale * cos_beta1;\n\n                x = lam12x / lambda_scale;\n                y = sin_beta12a / beta_scale;\n            }\n            else\n            {\n                CT cos_beta12a = cos_beta2 * cos_beta1 - sin_beta2 * sin_beta1;\n                CT beta12a = atan2(sin_beta12a, cos_beta12a);\n\n                CT m12b, m0, dummy;\n                meridian_length(n, ep2, pi + beta12a,\n                                sin_beta1, -cos_beta1, dn1,\n                                sin_beta2, cos_beta2, dn2,\n                                cos_beta1, cos_beta2, dummy,\n                                m12b, m0, dummy, dummy, coeffs_C1);\n\n                x = -c1 + m12b / (cos_beta1 * cos_beta2 * m0 * pi);\n                beta_scale = x < -c0_01\n                           ? sin_beta12a / x\n                           : -f * math::sqr(cos_beta1) * pi;\n                lambda_scale = beta_scale / cos_beta1;\n\n                y = lam12x / lambda_scale;\n            }\n\n            if (y > -tol1 && x > -c1 - x_thresh)\n            {\n                // Strip near cut.\n                if (f >= c0)\n                {\n                    sin_alpha1 = (std::min)(c1, -CT(x));\n                    cos_alpha1 = - math::sqrt(c1 - math::sqr(sin_alpha1));\n                }\n                else\n                {\n                    cos_alpha1 = (std::max)(CT(x > -tol1 ? c0 : -c1), CT(x));\n                    sin_alpha1 = math::sqrt(c1 - math::sqr(cos_alpha1));\n                }\n            }\n            else\n            {\n                // Solve the astroid problem.\n                CT k = astroid(CT(x), y);\n\n                CT omega12a = lambda_scale * (f >= c0 ? -x * k /\n                    (c1 + k) : -y * (c1 + k) / k);\n\n                sin_omega12 = sin(omega12a);\n                cos_omega12 = -cos(omega12a);\n\n                // Update spherical estimate of alpha1 using omgega12 instead of lam12.\n                sin_alpha1 = cos_beta2 * sin_omega12;\n                cos_alpha1 = sin_beta12a - cos_beta2 * sin_beta1 *\n                    math::sqr(sin_omega12) / (c1 - cos_omega12);\n            }\n        }\n\n        // Sanity check on starting guess. Backwards check allows NaN through.\n        if (!(sin_alpha1 <= c0))\n        {\n            math::normalize_unit_vector<CT>(sin_alpha1, cos_alpha1);\n        }\n        else\n        {\n            sin_alpha1 = c1;\n            cos_alpha1 = c0;\n        }\n\n        return sig12;\n    }\n\n    /*\n     Solve the astroid problem using the equation:\n     κ4 + 2κ3 + (1 − x2 − y 2 )κ2 − 2y 2 κ − y 2 = 0.\n\n     For details, please refer to Eq. (65) in,\n     Geodesics on an ellipsoid of revolution, Charles F.F Karney,\n     https://arxiv.org/abs/1102.1215\n    */\n    static inline CT astroid(CT const& x, CT const& y)\n    {\n        static CT const c0 = 0;\n        static CT const c1 = 1;\n        static CT const c2 = 2;\n        static CT const c3 = 3;\n        static CT const c4 = 4;\n        static CT const c6 = 6;\n\n        CT k;\n\n        CT p = math::sqr(x);\n        CT q = math::sqr(y);\n        CT r = (p + q - c1) / c6;\n\n        if (!(q == c0 && r <= c0))\n        {\n            // Avoid possible division by zero when r = 0 by multiplying\n            // equations for s and t by r^3 and r, respectively.\n            CT S = p * q / c4;\n            CT r2 = math::sqr(r);\n            CT r3 = r * r2;\n\n            // The discriminant of the quadratic equation for T3. This is\n            // zero on the evolute curve p^(1/3)+q^(1/3) = 1.\n            CT discriminant = S * (S + c2 * r3);\n\n            CT u = r;\n\n            if (discriminant >= c0)\n            {\n                CT T3 = S + r3;\n\n                // Pick the sign on the sqrt to maximize abs(T3). This minimizes\n                // loss of precision due to cancellation. The result is unchanged\n                // because of the way the T is used in definition of u.\n                T3 += T3 < c0 ? -std::sqrt(discriminant) : std::sqrt(discriminant);\n\n                CT T = std::cbrt(T3);\n\n                // T can be zero; but then r2 / T -> 0.\n                u += T + (T != c0 ? r2 / T : c0);\n            }\n            else\n            {\n                CT ang = std::atan2(std::sqrt(-discriminant), -(S + r3));\n\n                // There are three possible cube roots. We choose the root which avoids\n                // cancellation. Note that discriminant < 0 implies that r < 0.\n                u += c2 * r * cos(ang / c3);\n            }\n\n            CT v = std::sqrt(math::sqr(u) + q);\n\n            // Avoid loss of accuracy when u < 0.\n            CT uv = u < c0 ? q / (v - u) : u + v;\n            CT w = (uv - q) / (c2 * v);\n\n            // Rearrange expression for k to avoid loss of accuracy due to\n            // subtraction. Division by 0 not possible because uv > 0, w >= 0.\n            k = uv / (std::sqrt(uv + math::sqr(w)) + w);\n        }\n        else // q == 0 && r <= 0\n        {\n            // y = 0 with |x| <= 1. Handle this case directly.\n            // For y small, positive root is k = abs(y)/sqrt(1-x^2).\n            k = c0;\n        }\n        return k;\n    }\n\n    template <typename CoeffsC1>\n    static inline CT lambda12(CT const& sin_beta1, CT const& cos_beta1, CT const& dn1,\n                              CT const& sin_beta2, CT const& cos_beta2, CT const& dn2,\n                              CT const& sin_alpha1, CT cos_alpha1,\n                              CT const& sin_lam120, CT const& cos_lam120,\n                              CT& sin_alpha2, CT& cos_alpha2,\n                              CT& sigma12,\n                              CT& sin_sigma1, CT& cos_sigma1,\n                              CT& sin_sigma2, CT& cos_sigma2,\n                              CT& eps, CT& diff_omega12,\n                              bool diffp, CT& diff_lam12,\n                              CT const& f, CT const& n, CT const& ep2, CT const& tiny,\n                              CoeffsC1 const& coeffs_C1)\n    {\n        static CT const c0 = 0;\n        static CT const c1 = 1;\n        static CT const c2 = 2;\n\n        CT const one_minus_f = c1 - f;\n\n        if (sin_beta1 == c0 && cos_alpha1 == c0)\n        {\n            // Break degeneracy of equatorial line.\n            cos_alpha1 = -tiny;\n        }\n\n\n        CT sin_alpha0 = sin_alpha1 * cos_beta1;\n        CT cos_alpha0 = boost::math::hypot(cos_alpha1, sin_alpha1 * sin_beta1);\n\n        CT sin_omega1, cos_omega1;\n        CT sin_omega2, cos_omega2;\n        CT sin_omega12, cos_omega12;\n\n        CT lam12;\n\n        sin_sigma1 = sin_beta1;\n        sin_omega1 = sin_alpha0 * sin_beta1;\n\n        cos_sigma1 = cos_omega1 = cos_alpha1 * cos_beta1;\n\n        math::normalize_unit_vector<CT>(sin_sigma1, cos_sigma1);\n\n        // Enforce symmetries in the case abs(beta2) = -beta1.\n        // Otherwise, this can yield singularities in the Newton iteration.\n\n        // sin(alpha2) * cos(beta2) = sin(alpha0).\n        sin_alpha2 = cos_beta2 != cos_beta1 ?\n            sin_alpha0 / cos_beta2 : sin_alpha1;\n\n        cos_alpha2 = cos_beta2 != cos_beta1 || std::abs(sin_beta2) != -sin_beta1 ?\n            sqrt(math::sqr(cos_alpha1 * cos_beta1) +\n                (cos_beta1 < -sin_beta1 ?\n                    (cos_beta2 - cos_beta1) * (cos_beta1 + cos_beta2) :\n                    (sin_beta1 - sin_beta2) * (sin_beta1 + sin_beta2))) / cos_beta2 :\n            std::abs(cos_alpha1);\n\n        sin_sigma2 = sin_beta2;\n        sin_omega2 = sin_alpha0 * sin_beta2;\n\n        cos_sigma2 = cos_omega2 =\n            (cos_alpha2 * cos_beta2);\n\n        // Break degeneracy of equatorial line.\n        math::normalize_unit_vector<CT>(sin_sigma2, cos_sigma2);\n\n\n        // sig12 = sig2 - sig1, limit to [0, pi].\n        sigma12 = atan2((std::max)(c0, cos_sigma1 * sin_sigma2 - sin_sigma1 * cos_sigma2),\n                                          cos_sigma1 * cos_sigma2 + sin_sigma1 * sin_sigma2);\n\n        // omg12 = omg2 - omg1, limit to [0, pi].\n        sin_omega12 = (std::max)(c0, cos_omega1 * sin_omega2 - sin_omega1 * cos_omega2);\n        cos_omega12 = cos_omega1 * cos_omega2 + sin_omega1 * sin_omega2;\n\n        // eta = omg12 - lam120.\n        CT eta = atan2(sin_omega12 * cos_lam120 - cos_omega12 * sin_lam120,\n                       cos_omega12 * cos_lam120 + sin_omega12 * sin_lam120);\n\n        CT B312;\n        CT k2 = math::sqr(cos_alpha0) * ep2;\n\n        eps = k2 / (c2 * (c1 + std::sqrt(c1 + k2)) + k2);\n\n        se::coeffs_C3<SeriesOrder, CT> const coeffs_C3(n, eps);\n\n        B312 = se::sin_cos_series(sin_sigma2, cos_sigma2, coeffs_C3)\n             - se::sin_cos_series(sin_sigma1, cos_sigma1, coeffs_C3);\n\n        se::coeffs_A3<SeriesOrder, CT> const coeffs_A3(n);\n\n        CT const A3 = math::horner_evaluate(eps, coeffs_A3.begin(), coeffs_A3.end());\n\n        diff_omega12 = -f * A3 * sin_alpha0 * (sigma12 + B312);\n        lam12 = eta + diff_omega12;\n\n        if (diffp)\n        {\n            if (cos_alpha2 == c0)\n            {\n                diff_lam12 = - c2 * one_minus_f * dn1 / sin_beta1;\n            }\n            else\n            {\n                CT dummy;\n                meridian_length(eps, ep2, sigma12, sin_sigma1, cos_sigma1, dn1,\n                                                   sin_sigma2, cos_sigma2, dn2,\n                                                   cos_beta1, cos_beta2, dummy,\n                                                   diff_lam12, dummy, dummy,\n                                                   dummy, coeffs_C1);\n\n                diff_lam12 *= one_minus_f / (cos_alpha2 * cos_beta2);\n            }\n        }\n        return lam12;\n    }\n\n};\n\n}}} // namespace boost::geometry::formula\n\n\n#endif // BOOST_GEOMETRY_FORMULAS_KARNEY_INVERSE_HPP\n", "meta": {"hexsha": "f3a72fa23a2124f049823e7a7d633f81a601f07f", "size": 35118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/formulas/karney_inverse.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T12:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:14:38.000Z", "max_issues_repo_path": "boost/geometry/formulas/karney_inverse.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "boost/geometry/formulas/karney_inverse.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T04:03:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T18:53:47.000Z", "avg_line_length": 36.6959247649, "max_line_length": 111, "alphanum_fraction": 0.510365055, "num_tokens": 9015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4460022945713672}}
{"text": "#include <stdio.h>\n#include \"Substrate.h\"\n#include \"Mathematix.h\"\n#include \"finiteDifferences.h\"\n//#include <boost/lambda/lambda.hpp>\n\n#define DX 13.\n\n#define EXPLICIT        0\n#define IMPLICIT        1\n#define CRANK_NICHOLSON 2\n#define ADI             3\n\n//#define DIFFUSION_METHODE           EXPLICIT\n//#define DIFFUSION_METHODE           IMPLICIT\n//#define DIFFUSION_METHODE           CRANK_NICHOLSON\n#define DIFFUSION_METHODE           ADI\n#define DIFFUSION_REACTION_SEPARAT FALSE\n//#define DIFFUSION_REACTION_SEPARAT TRUE\n\n//#define DT 0.01\n\n\nfloat **A;\nfloat *b;//[20];\nfloat *x;//[20];\nint ADI_direction = 1;\n\nvoid initMatrix( VoronoiDiagram *voronoiDiagram/*, int imax, int iimax*/)\n{\n\tint matrixDim = voronoiDiagram->xN[0];\n\n\tfor( int dim=1; dim<DIMENSIONS; dim++)\n\t\tif(voronoiDiagram->xN[dim]>matrixDim)\n\t\t\tmatrixDim = voronoiDiagram->xN[dim];\n\n\tA = newMatrix( matrixDim, matrixDim);\n\t\n\tb = (float*) malloc( matrixDim * sizeof(float));\n\tx = (float*) malloc( matrixDim * sizeof(float));\n/*\tfor( int i=0; i<imax; i++)\n\t\tfor( int ii=0; ii<iimax; ii++){\n\t\t\tA[i][ii] = voronoiDiagram->voronoiCells[i + ii*20];\n\t\t}\n*/}\ndouble factor = 1.;\n\n/*void setupMatrixOxygenX( VoronoiDiagram *voronoiDiagram, int iset, double timeStep)\n{\n\tdouble r = factor*Oxygen_Diffusion * timeStep/(DX*DX);\n\t\n\tfor( int m=0; m<20; m++)\n\t\tfor( int n=0; n<20; n++)\n\t\t\tA[m][n] = 0;\n\n\tfor( int m=0; m<20; m++){\n\t\tA[m][m]   = 1;\n\n\t\tif( m>0){\n\t\t\tA[m][m-1] = -r;\n\t\t\tA[m][m]  += r;\n\t\t}\n\t\tif( m<19){\n\t\t\tA[m][m]  += r;\n\t\t\tA[m][m+1] = -r;\n\t\t}\n\t\t\n\t\tb[m] = voronoiDiagram->voronoiCells[iset + m*20]->oxygen - timeStep * voronoiDiagram->voronoiCells[iset + m*20]->oxygen * GiveMeTheOxygenRate(  voronoiDiagram->voronoiCells[iset + m*20]);\n\t}\n}\n\nvoid setupMatrixOxygenY( VoronoiDiagram *voronoiDiagram, int iiset, double timeStep)\n{\n\tdouble r = factor*Oxygen_Diffusion * timeStep/(DX*DX);\n\t\n\tfor( int m=0; m<20; m++)\n\t\tfor( int n=0; n<20; n++)\n\t\t\tA[m][n] = 0;\n\n\tfor( int m=0; m<20; m++){\n\t\tA[m][m]   = 1;\n\n\t\tif( m>0){\n\t\t\tA[m][m-1] = -r;\n\t\t\tA[m][m]  += r;\n\t\t}\n\t\tif( m<19){\n\t\t\tA[m][m]  += r;\n\t\t\tA[m][m+1] = -r;\n\t\t}\n\t\t\n\t\tb[m] = voronoiDiagram->voronoiCells[m + iiset*20]->oxygen - timeStep * voronoiDiagram->voronoiCells[m+iiset*20]->oxygen * GiveMeTheOxygenRate(  voronoiDiagram->voronoiCells[m+iiset*20]);\n\t}\n}*/\n\nvoid setupMatrix( VoronoiDiagram *voronoiDiagram, int base_index, double timeStep, char molecule, char direction)\n{\n\tdouble r;\n\t//double consumption;\n\t\n\tif( molecule == 'o'){\n\t\tr = factor*Oxygen_Diffusion * timeStep/(DX*DX);\n\t}else{\n\t\tr = factor*Glucose_Diffusion * timeStep/(DX*DX);\t\n\t}\n\t\n\tfor( int m=0; m<voronoiDiagram->xN[(int)direction]/*20*/; m++)\n\t\tfor( int n=0; n<voronoiDiagram->xN[(int)direction]/*20*/; n++)\n\t\t\tA[m][n] = 0;\n\n\tfor( int m=0; m<voronoiDiagram->xN[(int)direction]/*20*/; m++){\n\t\tif( m>0 && m<voronoiDiagram->xN[(int)direction]-1){\n\t\t\tA[m][m-1] = -r;\n\t\t\tA[m][m]   =  1 + 2*r;\n\t\t\tA[m][m+1] = -r;\n\t\t}\n\t\telse{\n\t\t\tA[m][m]   = 1;\n\t\t}\n\t\t\n\t\tint di = (int)pow(voronoiDiagram->xN[(int)direction],direction);\n\t\tint index = base_index + (int)(m*di);\n\t\t//fprintf(stderr, \"m=%i, dir=%i,  %i + %i => %i (< %i)\\n\", m, direction, base_index, (int)(m*pow(20,direction)), index, (int)pow(20,3));\n\n\t\tif( molecule == 'o')\n\t\t\tb[m] = voronoiDiagram->voronoiCells[index]->oxygen\n#if DIFFUSION_REACTION_SEPARAT == FALSE\n\t\t\t     - timeStep/DIMENSIONS * voronoiDiagram->voronoiCells[index]->oxygen * GiveMeTheOxygenRate(  voronoiDiagram->voronoiCells[index])\n#endif\n\t\t\t    ;\n\t\telse\n\t\t\tb[m] = voronoiDiagram->voronoiCells[index]->glucose\n#if DIFFUSION_REACTION_SEPARAT == FALSE\n\t\t\t     - timeStep/DIMENSIONS * voronoiDiagram->voronoiCells[index]->glucose * GiveMeTheGlucoseRate(  voronoiDiagram->voronoiCells[index])\n#endif\n\t\t\t    ;\n\t\t/*for( int n=0; n<20; n++)\n\t\t\tfprintf( stderr, \"%lf \", A[m][n]);\n\t\tfprintf( stderr, \"| %lf\\n\", b[m]);*/\n\t}\n}\n\nvoid setupMatrixADI( VoronoiDiagram *voronoiDiagram, int base_index, double timeStep, char molecule, char direction)\n{\n\tdouble r;\n\t//double consumption;\n\t\n\tif( molecule == 'o'){\n\t\tr = factor*Oxygen_Diffusion * timeStep/(DX*DX);\n\t}else{\n\t\tr = factor*Glucose_Diffusion * timeStep/(DX*DX);\t\n\t}\n\t\n\tfor( int m=0; m<voronoiDiagram->xN[(int)direction]/*20*/; m++)\n\t\tfor( int n=0; n<voronoiDiagram->xN[(int)direction]/*20*/; n++)\n\t\t\tA[m][n] = 0;\n\n\tfor( int m=0; m<voronoiDiagram->xN[(int)direction]/*20*/; m++){\n\t\tif( m>0 && m<voronoiDiagram->xN[(int)direction]-1){\n\t\t\tA[m][m-1] = -r;\n\t\t\tA[m][m]   =  1 + 2*r;\n\t\t\tA[m][m+1] = -r;\n\t\t}\n\t\telse{\n\t\t\tA[m][m]   = 1;\n\t\t}\n\t\t/*if( m>0){\n\t\t\tA[m][m-1] = -r;\n\t\t\tA[m][m]  += r;\n\t\t}\n\t\tif( m<voronoiDiagram->xN[(int)direction]-1){\n\t\t\tA[m][m]  += r;\n\t\t\tA[m][m+1] = -r;\n\t\t}*/\n\t\t\n\t\tint di = (int)pow(voronoiDiagram->xN[(int)direction],direction);\n\t\tint index = base_index + (int)(m*di);\n\t\t//fprintf(stderr, \"m=%i, dir=%i,  %i + %i => %i (< %i)\\n\", m, direction, base_index, (int)(m*pow(20,direction)), index, (int)pow(20,3));\n\n\t\tif( molecule == 'o')\n\t\t\tb[m] = voronoiDiagram->voronoiCells[index]->oxygen\n#if DIFFUSION_REACTION_SEPARAT == FALSE\n\t\t\t     - timeStep/DIMENSIONS * voronoiDiagram->voronoiCells[index]->oxygen * GiveMeTheOxygenRate(  voronoiDiagram->voronoiCells[index])\n#endif\n\t\t\t    ;\n\t\telse\n\t\t\tb[m] = voronoiDiagram->voronoiCells[index]->glucose\n#if DIFFUSION_REACTION_SEPARAT == FALSE\n\t\t\t     - timeStep/DIMENSIONS * voronoiDiagram->voronoiCells[index]->glucose * GiveMeTheGlucoseRate(  voronoiDiagram->voronoiCells[index])\n#endif\n\t\t\t    ;\n\t\t/*for( int n=0; n<20; n++)\n\t\t\tfprintf( stderr, \"%lf \", A[m][n]);\n\t\tfprintf( stderr, \"| %lf\\n\", b[m]);*/\n\t}\n}\n\nvoid setupMatrixCrankNicholson( VoronoiDiagram *voronoiDiagram, int base_index, double timeStep, char molecule, char direction)\n{\n\tdouble r;\n\t//double consumption;\n\t\n\tif( molecule == 'o'){\n\t\tr = Oxygen_Diffusion * timeStep/(DX*DX);\n\t}else{\n\t\tr = Glucose_Diffusion * timeStep/(DX*DX);\t\n\t}\n\t\n\tfor( int m=0; m<20; m++)\n\t\tfor( int n=0; n<20; n++)\n\t\t\tA[m][n] = 0;\n\n\tfor( int m=0; m<20; m++){\n\t\t//A[m][m]   = 2;\n\n\t\tif( m>0){\n\t\t\tA[m][m-1] = -r;\n\t\t\tA[m][m]  += 1+r;\n\t\t}\n\t\tif( m<19){\n\t\t\tA[m][m]  += 1+r;\n\t\t\tA[m][m+1] = -r;\n\t\t}\n\t\t\n\t\tint index, index_minus, index_plus;\n\t\t\n\t\tindex = base_index + (int)(m*pow(20,direction));\n\t\tindex_plus  = base_index + (int)((m+1)*pow(20,direction));\n\t\tindex_minus = base_index + (int)((m-1)*pow(20,direction));\n\t\t\n\t\t\n\t\tdouble factor, factor_minus, factor_plus;\n\t\tfactor       = 1-r;\n\t\tfactor_plus  = 0;\n\t\tfactor_minus = 0;\n\n#if DIFFUSION_REACTION_SEPARAT == FALSE\n\t\tif( molecule == 'o'){\n\t\t\tfactor       -= GiveMeTheOxygenRate(  voronoiDiagram->voronoiCells[index]);\n\t\t\tif( m<19)factor_plus  = 1 - GiveMeTheOxygenRate(  voronoiDiagram->voronoiCells[index_plus]);\n\t\t\tif( m>0) factor_minus = 1 - GiveMeTheOxygenRate(  voronoiDiagram->voronoiCells[index_minus]);\n\t\t}else{\n\t\t\tfactor       -= GiveMeTheGlucoseRate(  voronoiDiagram->voronoiCells[index]);\n\t\t\tif( m<19)factor_plus  = 1 - GiveMeTheGlucoseRate(  voronoiDiagram->voronoiCells[index_plus]);\n\t\t\tif( m>0) factor_minus = 1 - GiveMeTheGlucoseRate(  voronoiDiagram->voronoiCells[index_minus]);\n\t\t}\n#endif\n\t\tb[m] = 0.;\n\t\tif( molecule == 'o'){\n\t\t\tif( m>0){\n\t\t\t\tb[m] += timeStep/DIMENSIONS * factor * voronoiDiagram->voronoiCells[index]->oxygen + timeStep/DIMENSIONS * factor_minus * voronoiDiagram->voronoiCells[index_minus]->oxygen;\n\t\t\t}\n\t\t\tif( m<19){\n\t\t\t\tb[m] += timeStep/DIMENSIONS * factor * voronoiDiagram->voronoiCells[index]->oxygen + timeStep/DIMENSIONS * factor_plus * voronoiDiagram->voronoiCells[index_plus]->oxygen;\n\t\t\t}\n\t\t}else{\n\t\t\tif( m>0){\n\t\t\t\tb[m] += timeStep/DIMENSIONS * factor * voronoiDiagram->voronoiCells[index]->glucose + timeStep/DIMENSIONS * factor_minus * voronoiDiagram->voronoiCells[index_minus]->glucose;\n\t\t\t}\n\t\t\tif( m<19){\n\t\t\t\tb[m] += timeStep/DIMENSIONS * factor * voronoiDiagram->voronoiCells[index]->glucose +timeStep/DIMENSIONS *  factor_plus * voronoiDiagram->voronoiCells[index_plus]->glucose;\n\t\t\t}\n\t\t}\n\t\t/*for( int n=0; n<20; n++)\n\t\t\tfprintf( stderr, \"%lf \", A[m][n]);\n\t\tfprintf( stderr, \"| %lf\\n\", b[m]);*/\n\t}\n}\n\ndouble secondDerivationOxygen( VoronoiCell * cell, VoronoiDiagram *voronoiDiagram)\n{\n\tdouble temp = 0.;\n\n/*\ttemp = - ((double)cell->countNeighborCells) * cell->oxygen;\n\n\tfor( int i=0; i<cell->countNeighborCells; i++)\n\t\ttemp += cell->neighborCells[i]->oxygen;\n\t\t\n\treturn temp/(DX*DX) * 4./(double)cell->countNeighborCells;\n*/\n\tint i   = 0, \n\t    ii  = 0,\n\t    iii = 0;\n\t\n\tint index = cell->index;\n\t\n#if DIMENSIONS > 2\n\tiii = index / (20*20);\n\tindex = index - iii*20*20;\n#endif\n#if DIMENSIONS > 1\n\tii = index / 20;\n\tindex = index - ii*20;\n#endif\n\ti = index;\n\t//fprintf( stderr, \"%i: (%i,%i,%i) => %i\\n\", cell->index, i, ii, iii, i + 20*ii + 20*20*iii);\n\t\n\tif( i>0)\n\t\ttemp += voronoiDiagram->voronoiCells[i-1 + 20*ii + 20*20*iii]->oxygen - cell->oxygen;\n\tif( i<19)\n\t\ttemp += voronoiDiagram->voronoiCells[i+1 + 20*ii + 20*20*iii]->oxygen - cell->oxygen;\n#if DIMENSIONS > 1\n\tif( ii>0)\n\t\ttemp += voronoiDiagram->voronoiCells[i + 20*(ii-1) + 20*20*iii]->oxygen - cell->oxygen;\n\tif( ii<19)\n\t\ttemp += voronoiDiagram->voronoiCells[i + 20*(ii+1) + 20*20*iii]->oxygen - cell->oxygen;\n#endif\n#if DIMENSIONS > 2\n\tif( iii>0)\n\t\ttemp += voronoiDiagram->voronoiCells[i + 20*ii + 20*20*(iii-1)]->oxygen - cell->oxygen;\n\tif( iii<19)\n\t\ttemp += voronoiDiagram->voronoiCells[i + 20*ii + 20*20*(iii+1)]->oxygen - cell->oxygen;\n#endif\n\t\n\treturn temp/(DX*DX);\n}\n\ndouble secondDerivationGlucose( VoronoiCell * cell, VoronoiDiagram *voronoiDiagram)\n{\n\tdouble temp = 0.;\n\n/*\ttemp = - ((double)cell->countNeighborCells) * cell->glucose;\n\n\tfor( int i=0; i<cell->countNeighborCells; i++)\n\t\ttemp += cell->neighborCells[i]->glucose;\n\t\t\n\treturn temp/(DX*DX) * 4./(double)cell->countNeighborCells;\n*/\n\tint i   = 0, \n\t    ii  = 0,\n\t    iii = 0;\n\t\n\tint index = cell->index;\n\t\n#if DIMENSIONS > 2\n\tiii = index / (20*20);\n\tindex = index - iii*20*20;\n#endif\n#if DIMENSIONS > 1\n\tii = index / 20;\n\tindex = index - ii*20;\n#endif\n\ti = index;\n\t//fprintf( stderr, \"%i: (%i,%i,%i) => %i\\n\", cell->index, i, ii, iii, i + 20*ii + 20*20*iii);\n\t\n\tif( i>0)\n\t\ttemp += voronoiDiagram->voronoiCells[i-1 + 20*ii + 20*20*iii]->glucose - cell->glucose;\n\tif( i<19)\n\t\ttemp += voronoiDiagram->voronoiCells[i+1 + 20*ii + 20*20*iii]->glucose - cell->glucose;\n#if DIMENSIONS > 1\n\tif( ii>0)\n\t\ttemp += voronoiDiagram->voronoiCells[i + 20*(ii-1) + 20*20*iii]->glucose - cell->glucose;\n\tif( ii<19)\n\t\ttemp += voronoiDiagram->voronoiCells[i + 20*(ii+1) + 20*20*iii]->glucose - cell->glucose;\n#endif\n#if DIMENSIONS > 2\n\tif( iii>0)\n\t\ttemp += voronoiDiagram->voronoiCells[i + 20*ii + 20*20*(iii-1)]->glucose - cell->glucose;\n\tif( iii<19)\n\t\ttemp += voronoiDiagram->voronoiCells[i + 20*ii + 20*20*(iii+1)]->glucose - cell->glucose;\n#endif\n\t\n\treturn temp/(DX*DX);\n}\n\n\n\n/*#if (DIFFUSION_METHODE != ADI)\n\ndouble UpdateSystem( VoronoiDiagram *voronoiDiagram, double timeStep, double timeDifference){\n\t\n\tdouble time;\n\t\n\tint direction = (int)((myRand()*DIMENSIONS)/2.);\n\t\n\tfor( time = 0; time+timeStep <= timeDifference; time += timeStep){\n\t\t\n#if DIFFUSION_METHODE == EXPLICIT\n\n\t\t//fprintf( stderr, \"EXPLICIT\\n\");\n\t\t// Finite Differences: explicit method\t\n\t\tfor( int i=0; i<voronoiDiagram->countVoronoiCells; i++){\n\t\t\t\n\t\t\tvoronoiDiagram->voronoiCells[i]->doxygen  = timeStep * (Oxygen_Diffusion  * secondDerivationOxygen(  voronoiDiagram->voronoiCells[i], voronoiDiagram) // diffusion\n\t#if DIFFUSION_REACTION_SEPARAT == FALSE\n\t\t\t                                          - voronoiDiagram->voronoiCells[i]->oxygen  * GiveMeTheOxygenRate(  voronoiDiagram->voronoiCells[i]) // reaction\n\t#endif\n\t\t\t                                          );\n\t\t\tvoronoiDiagram->voronoiCells[i]->dglucose = timeStep * (Glucose_Diffusion * secondDerivationGlucose( voronoiDiagram->voronoiCells[i], voronoiDiagram) // diffusion\n\t#if DIFFUSION_REACTION_SEPARAT == FALSE\n\t\t\t                                          - voronoiDiagram->voronoiCells[i]->glucose * GiveMeTheGlucoseRate( voronoiDiagram->voronoiCells[i]) // reaction\n\t#endif\n\t\t\t                                          );\t\t\t                                          \n\t\t}\n\n#endif\n\t\t\n#if (DIFFUSION_METHODE == IMPLICIT) || (DIFFUSION_METHODE == CRANK_NICHOLSON) || (DIFFUSION_METHODE == ADI)\n\t\t// Finite Differences: alternating direction implicit (ADI)\n\t\tdouble weight = 1.;\n\t\t// diffusion in x-direction\n\t\tfor( int iset=0; iset<20; iset++){\n\t\t\t//setupMatrixOxygenX( voronoiDiagram, iset, timeStep);\n\t#if   DIFFUSION_METHODE == CRANK_NICHOLSON\n\t\t\tsetupMatrixCrankNicholson( voronoiDiagram, iset, timeStep, 'o', 0);\n\t\t\t//fprintf( stderr, \"CRANK_NICHOLSON\\n\");\n\t#elif DIFFUSION_METHODE == ADI\n\t\t\tsetupMatrixADI( voronoiDiagram, iset, timeStep, 'o', direction);\n\t#else\n\t\t\t//fprintf( stderr, \"ADI\\n\");\n\t\t\tsetupMatrix( voronoiDiagram, iset, 0.5*timeStep, 'o', 0);\n\t#endif\n\t\t\tsolveLinearSystem( A, b, x, 20);\n\t\t\tfor( int ii=0; ii<20; ii++)\n\t\t\t\tvoronoiDiagram->voronoiCells[iset + ii*20]->doxygen = weight*(b[ii] - voronoiDiagram->voronoiCells[iset + ii*20]->oxygen);\n\n\t#if DIFFUSION_METHODE == CRANK_NICHOLSON\n\t\t\tsetupMatrixCrankNicholson( voronoiDiagram, iset, timeStep, 'g', 0);\n\t#elif DIFFUSION_METHODE == ADI\n\t\t\tsetupMatrixADI( voronoiDiagram, iset, timeStep, 'g', direction);\n\t#else\n\t\t\tsetupMatrix( voronoiDiagram, iset, 0.5*timeStep, 'g', 0);\n\t#endif\n\t\t\tsolveLinearSystem( A, b, x, 20);\n\t\t\tfor( int ii=0; ii<20; ii++)\n\t\t\t\tvoronoiDiagram->voronoiCells[iset + ii*20]->dglucose = weight*(b[ii] - voronoiDiagram->voronoiCells[iset + ii*20]->glucose);\n\t\t}\n\t#if DIFFUSION_METHODE == ADI\n\t\tfor( int i=0; i<voronoiDiagram->countVoronoiCells; i++){\n\t\t\tif( voronoiDiagram->voronoiCells[i]->position[0]>voronoiDiagram->xMin[0]+1\n\t\t\t && voronoiDiagram->voronoiCells[i]->position[0]<voronoiDiagram->xMax[0]-1 \n\t\t\t && voronoiDiagram->voronoiCells[i]->position[1]>voronoiDiagram->xMin[1]+1\n\t\t\t && voronoiDiagram->voronoiCells[i]->position[1]<voronoiDiagram->xMax[1]-1\n\t\t#if DIMENSIONS > 2\n\t\t\t && voronoiDiagram->voronoiCells[i]->position[2]>voronoiDiagram->xMin[2]+1\n\t\t\t && voronoiDiagram->voronoiCells[i]->position[2]<voronoiDiagram->xMax[2]-1 \n\t\t#endif\n\t\t\t){\t\n\t\t\t\tvoronoiDiagram->voronoiCells[i]->oxygen  += voronoiDiagram->voronoiCells[i]->doxygen;\n\t\t\t\tif( voronoiDiagram->voronoiCells[i]->oxygen < 0.) voronoiDiagram->voronoiCells[i]->oxygen = 0.;\n\t\t\t\tvoronoiDiagram->voronoiCells[i]->glucose += voronoiDiagram->voronoiCells[i]->dglucose;\n\t\t\t\tif( voronoiDiagram->voronoiCells[i]->glucose < 0.) voronoiDiagram->voronoiCells[i]->glucose = 0.;\n\t\t\t}\n\t\t}\n\t\tdirection = (direction+1)%DIMENSIONS;\n\t#endif\n\n\t\t// diffusion in y-direction\n\t\tfor( int iiset=0; iiset<20; iiset++){\n//\t\t\tsetupMatrixOxygenY( voronoiDiagram, iiset, timeStep);\n\t#if DIFFUSION_METHODE == CRANK_NICHOLSON\n\t\t\tsetupMatrixCrankNicholson( voronoiDiagram, iiset, timeStep, 'o', 1);\n\t#elif DIFFUSION_METHODE == ADI\n\t\t\tsetupMatrixADI( voronoiDiagram, iiset, timeStep, 'o', direction);\n\t#else\n\t\t\tsetupMatrix( voronoiDiagram, iiset, 0.5*timeStep, 'o', 1);\n\t#endif\n\t\t\tsolveLinearSystem( A, b, x, 20);\n\t\t\tfor( int i=0; i<20; i++){\n\t\t\t\tvoronoiDiagram->voronoiCells[i+iiset*20]->doxygen += weight*(b[i] - voronoiDiagram->voronoiCells[i+iiset*20]->oxygen);\n\t\t\t}\n\n\t#if DIFFUSION_METHODE == CRANK_NICHOLSON\n\t\t\tsetupMatrixCrankNicholson( voronoiDiagram, iiset, timeStep, 'g', 1);\n\t#elif DIFFUSION_METHODE == ADI\n\t\t\tsetupMatrixADI( voronoiDiagram, iiset, timeStep, 'g', direction);\n\t#else\n\t\t\tsetupMatrix( voronoiDiagram, iiset, 0.5*timeStep, 'g', 1);\n\t#endif\n\t\t\tsolveLinearSystem( A, b, x, 20);\n\t\t\tfor( int i=0; i<20; i++){\n\t\t\t\tvoronoiDiagram->voronoiCells[i+iiset*20]->dglucose += weight*(b[i] - voronoiDiagram->voronoiCells[i+iiset*20]->glucose);\n\t\t\t}\n\t\t}\n\n\n#endif\n\n\t\t// Update\n\t\tfor( int i=0; i<voronoiDiagram->countVoronoiCells; i++){\n\t\t\tif( voronoiDiagram->voronoiCells[i]->position[0]>voronoiDiagram->xMin[0]+1\n\t\t\t && voronoiDiagram->voronoiCells[i]->position[0]<voronoiDiagram->xMax[0]-1 \n\t\t\t && voronoiDiagram->voronoiCells[i]->position[1]>voronoiDiagram->xMin[1]+1\n\t\t\t && voronoiDiagram->voronoiCells[i]->position[1]<voronoiDiagram->xMax[1]-1\n#if DIMENSIONS > 2\n\t\t\t && voronoiDiagram->voronoiCells[i]->position[2]>voronoiDiagram->xMin[2]+1\n\t\t\t && voronoiDiagram->voronoiCells[i]->position[2]<voronoiDiagram->xMax[2]-1 \n#endif\n\t\t\t){\t\n\t\t\t\tvoronoiDiagram->voronoiCells[i]->oxygen  += voronoiDiagram->voronoiCells[i]->doxygen\n#if DIFFUSION_REACTION_SEPARAT == TRUE\n\t\t\t\t                                          - timeStep * voronoiDiagram->voronoiCells[i]->oxygen  * GiveMeTheOxygenRate(  voronoiDiagram->voronoiCells[i])\n#endif\n\t\t\t\t                                          ;\n\t\t\t\tif( voronoiDiagram->voronoiCells[i]->oxygen < 0.) voronoiDiagram->voronoiCells[i]->oxygen = 0.;\n\t\t\t\tvoronoiDiagram->voronoiCells[i]->glucose += voronoiDiagram->voronoiCells[i]->dglucose\n#if DIFFUSION_REACTION_SEPARAT == TRUE\n\t\t\t\t                                          - timeStep * voronoiDiagram->voronoiCells[i]->glucose * GiveMeTheGlucoseRate( voronoiDiagram->voronoiCells[i])\n#endif\n\t\t\t\t                                          ;\n\t\t\t\tif( voronoiDiagram->voronoiCells[i]->glucose < 0.) voronoiDiagram->voronoiCells[i]->glucose = 0.;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn timeDifference - time;\n}\n\n#else*/\n\ndouble UpdateSystem( VoronoiDiagram *voronoiDiagram, double timeStep, double timeDifference){\n\t\n\tdouble time;\n\t\n\t//int direction = (int)(myRand()*DIMENSIONS+0.5);\n\tint direction = ADI_direction; ADI_direction = (ADI_direction+1)%DIMENSIONS;\n\t\n\t\n\tfor( time = 0; time+timeStep <= timeDifference; time += timeStep){\n\n#if DIFFUSION_METHODE == EXPLICIT\n\n\t\t//fprintf( stderr, \"EXPLICIT\\n\");\n\t\t// Finite Differences: explicit method\t\n\t\tfor( int i=0; i<voronoiDiagram->countVoronoiCells; i++){\n\t\t\t\n\t\t\tvoronoiDiagram->voronoiCells[i]->doxygen  = timeStep * (Oxygen_Diffusion  * secondDerivationOxygen(  voronoiDiagram->voronoiCells[i], voronoiDiagram) // diffusion\n\t#if DIFFUSION_REACTION_SEPARAT == FALSE\n\t\t\t                                          - voronoiDiagram->voronoiCells[i]->oxygen  * GiveMeTheOxygenRate(  voronoiDiagram->voronoiCells[i]) // reaction\n\t#endif\n\t\t\t                                          );\n\t\t\tvoronoiDiagram->voronoiCells[i]->dglucose = timeStep * (Glucose_Diffusion * secondDerivationGlucose( voronoiDiagram->voronoiCells[i], voronoiDiagram) // diffusion\n\t#if DIFFUSION_REACTION_SEPARAT == FALSE\n\t\t\t                                          - voronoiDiagram->voronoiCells[i]->glucose * GiveMeTheGlucoseRate( voronoiDiagram->voronoiCells[i]) // reaction\n\t#endif\n\t\t\t                                          );\t\t\t                                          \n\t\t}\n\n#else\n\n\n\tfor( int d=0; d<DIMENSIONS; d++){\n\t//fprintf(stderr, \"dir=%i\\n\", direction);\n\t\t// Finite Differences: alternating direction implicit (ADI)\n\t\tdouble weight = 1.;\n\t\t\n\t\t//int i = 0;\n\t\t//int ii = 0;\n\t\t//int iii = 0;\n\t\t\n\t\tfor( int iset=0; iset<voronoiDiagram->xN[(d==0?1:0)]/*20*/; iset++){\n\t\t\tfor( int iiset=0; iiset<voronoiDiagram->xN[(d<=1?2:1)]/*20*/; iiset++){\n\n\t\t\t\t// base index\n\t\t\t\tint index=0;\n\t\t\t\tint index_count = 0;\n\t\t\t\tfor( int dd=0; dd<DIMENSIONS; dd++){\n\t\t\t\t\tif( dd!=direction){\n\t\t\t\t\t\tif(index_count==0)\n\t\t\t\t\t\t\tindex += (int)( iset*pow( voronoiDiagram->xN[(d==0?1:0)]/*20*/, dd));\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tindex += (int)( iiset*pow( voronoiDiagram->xN[(d<=1?2:1)]/*20*/, dd));\n\t\t\t\t\t\tindex_count++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//fprintf(stderr, \"setupMatrixADI(o): %i <= (%i,%i)\\n\", index, iset, iiset);\n\n\t#if   DIFFUSION_METHODE == CRANK_NICHOLSON\n\t\t\t\tsetupMatrixCrankNicholson( voronoiDiagram, index, timeStep, 'o', direction);\n\t\t\t\t//fprintf( stderr, \"CRANK_NICHOLSON\\n\");\n\t#elif DIFFUSION_METHODE == ADI\n\t\t\t\tsetupMatrixADI( voronoiDiagram, index, timeStep, 'o', direction);\n\t#elif DIFFUSION_METHODE == IMPLICIT\n\t\t\t\t//fprintf( stderr, \"ADI\\n\");\n\t\t\t\tsetupMatrix( voronoiDiagram, index, timeStep, 'o', direction);\n\t#endif\n\t\t\t\t//setupMatrixADI( voronoiDiagram, index, timeStep, 'o', direction);\n\t\t\t\t//fprintf(stderr, \"solve\\n\");\n\t\t\t\t//solveLinearSystemTridiagonalMatrix( A, b, x, voronoiDiagram->xN[d]);\n\t\t\t\tsolveLinearSystem( A, b, x, voronoiDiagram->xN[d]/*20*/);\n\t\t\t\tfor( int i=0; i<voronoiDiagram->xN[d]/*20*/; i++)\n\t#if DIFFUSION_METHODE == IMPLICIT\n\t\t\t\t\tif( d!=0)\n\t\t\t\t\t\tvoronoiDiagram->voronoiCells[(int)(index+i*pow( voronoiDiagram->xN[d]/*20*/, direction))]->doxygen += weight*(b[i] - voronoiDiagram->voronoiCells[(int)(index+i*pow( voronoiDiagram->xN[d]/*20*/, direction))]->oxygen);\n\t\t\t\t\telse\n\t#endif\n\t\t\t\t\t\tvoronoiDiagram->voronoiCells[(int)(index+i*pow( voronoiDiagram->xN[d]/*20*/, direction))]->doxygen = weight*(b[i] - voronoiDiagram->voronoiCells[(int)(index+i*pow( voronoiDiagram->xN[d]/*20*/, direction))]->oxygen);\n\n\t\t\t\t//fprintf(stderr, \"setupMatrixADI(g): %i <= (%i,%i)\\n\", index, iset, iiset);\n\n\t#if   DIFFUSION_METHODE == CRANK_NICHOLSON\n\t\t\t\tsetupMatrixCrankNicholson( voronoiDiagram, index, timeStep, 'g', direction);\n\t\t\t\t//fprintf( stderr, \"CRANK_NICHOLSON\\n\");\n\t#elif DIFFUSION_METHODE == ADI\n\t\t\t\tsetupMatrixADI( voronoiDiagram, index, timeStep, 'g', direction);\n\t#elif DIFFUSION_METHODE == IMPLICIT\n\t\t\t\t//fprintf( stderr, \"Implicit\\n\");\n\t\t\t\tsetupMatrix( voronoiDiagram, index, timeStep, 'g', direction);\n\t#endif\n\t\t\t\t//setupMatrixADI( voronoiDiagram, index, timeStep, 'g', direction);\n\t\t\t\tsolveLinearSystem( A, b, x, voronoiDiagram->xN[d]/*20*/);\n\t\t\t\t//solveLinearSystemTridiagonalMatrix( A, b, x, voronoiDiagram->xN[d]);\n\t\t\t\tfor( int i=0; i<voronoiDiagram->xN[d]/*20*/; i++)\n\t#if DIFFUSION_METHODE == IMPLICIT\n\t\t\t\t\tif( d!=0)\n\t\t\t\t\t\t//add differences\n\t\t\t\t\t\tvoronoiDiagram->voronoiCells[(int)(index+i*pow( voronoiDiagram->xN[d]/*20*/, direction))]->dglucose += weight*(b[i] - voronoiDiagram->voronoiCells[(int)(index+i*pow( voronoiDiagram->xN[d]/*20*/, direction))]->glucose);\n\t\t\t\t\telse\n\t#endif\n\t\t\t\t\t\t// set differences\n\t\t\t\t\t\tvoronoiDiagram->voronoiCells[(int)(index+i*pow( voronoiDiagram->xN[d]/*20*/, direction))]->dglucose = weight*(b[i] - voronoiDiagram->voronoiCells[(int)(index+i*pow( voronoiDiagram->xN[d]/*20*/, direction))]->glucose);\n\t\t\t}\n\t\t}\n#endif\n\t\t\n\n#if DIFFUSION_METHODE == IMPLICIT\n\t\tif(d+1==DIMENSIONS)\n#endif\n\t\t// update half time step\n\t\t{//fprintf(stderr, \"update half time step\\n\");\n\t\tfor( int i=0; i<voronoiDiagram->countVoronoiCells; i++){\n\t\t\tif( voronoiDiagram->voronoiCells[i]->position[0]>voronoiDiagram->xMin[0]+1\n\t\t\t && voronoiDiagram->voronoiCells[i]->position[0]<voronoiDiagram->xMax[0]-1 \n\t\t\t && voronoiDiagram->voronoiCells[i]->position[1]>voronoiDiagram->xMin[1]+1\n\t\t\t && voronoiDiagram->voronoiCells[i]->position[1]<voronoiDiagram->xMax[1]-1\n\t\t#if DIMENSIONS > 2\n\t\t\t && voronoiDiagram->voronoiCells[i]->position[2]>voronoiDiagram->xMin[2]+1\n\t\t\t && voronoiDiagram->voronoiCells[i]->position[2]<voronoiDiagram->xMax[2]-1 \n\t\t#endif\n\t\t\t){\t\n\t\t\t\tvoronoiDiagram->voronoiCells[i]->oxygen  += voronoiDiagram->voronoiCells[i]->doxygen;\n\t\t\t\tif( voronoiDiagram->voronoiCells[i]->oxygen < 0.) voronoiDiagram->voronoiCells[i]->oxygen = 0.;\n\t\t\t\tvoronoiDiagram->voronoiCells[i]->glucose += voronoiDiagram->voronoiCells[i]->dglucose;\n\t\t\t\tif( voronoiDiagram->voronoiCells[i]->glucose < 0.) voronoiDiagram->voronoiCells[i]->glucose = 0.;\n\t\t\t}\n\t\t}}\n\n\t\t// change direction\n\t\tdirection = (direction+1)%DIMENSIONS;\n\t}\n\n#if DIFFUSION_REACTION_SEPARAT == TRUE\n\t// reaction\n\tfor( int i=0; i<voronoiDiagram->countVoronoiCells; i++){\n\t\tif( voronoiDiagram->voronoiCells[i]->position[0]>voronoiDiagram->xMin[0]+1\n\t\t && voronoiDiagram->voronoiCells[i]->position[0]<voronoiDiagram->xMax[0]-1 \n\t\t && voronoiDiagram->voronoiCells[i]->position[1]>voronoiDiagram->xMin[1]+1\n\t\t && voronoiDiagram->voronoiCells[i]->position[1]<voronoiDiagram->xMax[1]-1\n\t#if DIMENSIONS > 2\n\t\t && voronoiDiagram->voronoiCells[i]->position[2]>voronoiDiagram->xMin[2]+1\n\t\t && voronoiDiagram->voronoiCells[i]->position[2]<voronoiDiagram->xMax[2]-1 \n\t#endif\n\t\t){\t\n\t\t\tvoronoiDiagram->voronoiCells[i]->oxygen  += - timeStep * voronoiDiagram->voronoiCells[i]->oxygen  * GiveMeTheOxygenRate(  voronoiDiagram->voronoiCells[i]);\n\t\t\tif( voronoiDiagram->voronoiCells[i]->oxygen < 0.) voronoiDiagram->voronoiCells[i]->oxygen = 0.;\n\t\t\tvoronoiDiagram->voronoiCells[i]->glucose += - timeStep * voronoiDiagram->voronoiCells[i]->glucose * GiveMeTheGlucoseRate( voronoiDiagram->voronoiCells[i]);\n\t\t\tif( voronoiDiagram->voronoiCells[i]->glucose < 0.) voronoiDiagram->voronoiCells[i]->glucose = 0.;\n\t\t}\n\t}\n#endif\n#if DIFFUSION_METHODE != EXPLICIT\n\t}\n#endif\n\treturn timeDifference - time;\n}\n\n//#endif\n\n//////////////////////////////////////////////////////////////////////////////////////\n\nvoid initMatrixImplicit( VoronoiDiagram *voronoiDiagram)\n{\n\tint matrixDim = 1;\n\t\n\tfor( int d=0; d<DIMENSIONS; d++)\n\t\tmatrixDim *= voronoiDiagram->xN[d];\n\n\tb = (float*) malloc( matrixDim * sizeof(float));\n\n\tx = (float*) malloc( matrixDim * sizeof(float));\n\t\t\n\tA = newMatrix( matrixDim, matrixDim);\n}\n\n\nvoid setupMatrixImplicit( VoronoiDiagram *voronoiDiagram, double timeStep, char molecule)\n{\n\tint di   = 1;\n\tint dii  = voronoiDiagram->xN[0];\n\tint diii = voronoiDiagram->xN[0]*voronoiDiagram->xN[1];\n\t\n\tdouble r = Glucose_Diffusion * timeStep/(DX*DX);\n\t\n\tint N = voronoiDiagram->xN[0]*voronoiDiagram->xN[1]*voronoiDiagram->xN[2];\n\t\n\tfor( int iii=0; iii<voronoiDiagram->xN[2]; iii++)\n\tfor( int ii=0; ii<voronoiDiagram->xN[1]; ii++)\n\tfor( int i=0; i<voronoiDiagram->xN[0]; i++)\n\t{\n\t\t// actual element\n\t\tint m = i*di + ii*dii + iii*diii;\n\t\t//fprintf( stderr, \"%i \", m);\n\n\t\t// init matrix row\n\t\tfor( int n=0; n<N; n++)\n\t\t\tA[m][n] = 0.;\t\t\t\n\t\t\n\t\t//matrix\n\t\tA[m][m] = 1;\n\t\t\n\t\t// x\n\t\t/*if( i>0){\n\t\t\tA[m][m] = r;\n\t\t\tA[m][m-di] = -r; \n\t\t}\n\t\tif( i<voronoiDiagram->xN[0]-1){\n\t\t\tA[m][m] = r;\n\t\t\tA[m][m+di] = -r; \n\t\t}\n\t\t\n\t\t// y\n\t\tif( ii>0){\n\t\t\tA[m][m] = r;\n\t\t\tA[m][m-dii] = -r; \n\t\t}\n\t\tif( ii<voronoiDiagram->xN[1]-1){\n\t\t\tA[m][m] = r;\n\t\t\tA[m][m+dii] = -r; \n\t\t}\n\t\t\n\t\t// z\n\t\tif( iii>0){\n\t\t\tA[m][m] = r;\n\t\t\tA[m][m-diii] = -r; \n\t\t}\n\t\tif( iii<voronoiDiagram->xN[2]-1){\n\t\t\tA[m][m] = r;\n\t\t\tA[m][m+diii] = -r; \n\t\t}*/\n\t\tif( i>0 && i<voronoiDiagram->xN[0]-1 && ii>0 && ii<voronoiDiagram->xN[1]-1 && iii>0 && iii<voronoiDiagram->xN[2]-1)\n\t\t{\n\t\t\tA[m][m] += 6*r;\t\t\t\n\t\t\tA[m][m-di] = -r; \n\t\t\tA[m][m+di] = -r; \n\t\t\tA[m][m-dii] = -r; \n\t\t\tA[m][m+dii] = -r; \n\t\t\tA[m][m-diii] = -r; \n\t\t\tA[m][m+diii] = -r; \n\t\t}\n\t\t\n\t\t// vector\n\t\tb[m] = voronoiDiagram->voronoiCells[m]->glucose * ( 1. - timeStep * GiveMeTheGlucoseRate(  voronoiDiagram->voronoiCells[m]));\n\t\t\n\t}\n}\n\n\ndouble UpdateSystemImplicit( VoronoiDiagram *voronoiDiagram, double timeStep, double timeDifference)\n{\n\n\tdouble time;\n\t\n\tint N = voronoiDiagram->xN[0]*voronoiDiagram->xN[1]*voronoiDiagram->xN[2];\n\t//float **B = newMatrix( N, N);\n\t\n\tfor( time = 0; time+timeStep <= timeDifference; time += timeStep){\n\t\t//fprintf( stderr, \"%i. iteration:\\nSetup Matrix\\n\", (int)(time / timeStep + 0.5));\n\t\tint passedTime = clock();\n\t\tfprintf( stderr, \"Set Matrix... \\n\");\n\t\tsetupMatrixImplicit( voronoiDiagram, timeStep, 'G');\n\t\tfprintf( stderr, \"...finished ( %li clocks, %.3lf sec)\\n\", (clock() - passedTime), (float)(clock() - passedTime)/CLOCKS_PER_SEC);\n\n\t\t/*for(int m=0; m<N; m++){\n\t\t\tfor(int n=0; n<N; n++)\n\t\t\t\tfprintf( stderr, \"%6.0lf \", A[m][n]);\n\t\t\tfprintf( stderr, \"\\n\");\n\t\t}*/\n\t\t/*for(int m=0; m<N; m++){\n\t\t\tfor(int n=0; n<N; n++)\n\t\t\t\tfprintf( stdout, \"%i %i %lf \\n\", m, n, (A[m][n]!=0.?1.:0.));\n\t\t\t//fprintf( stderr, \"\\n\");\n\t\t}*/\n\t\t\n\t\t/*fprintf( stderr, \"Solve Matrix\\n\");\n\t\tsolveLinearSystemB( A, b, x, N, B);\n\t\t\n\t\tfprintf( stderr, \"Actualize Values\\n\");\n\t\tfor(int m=0; m<N; m++)\n\t\t\tvoronoiDiagram->voronoiCells[m]->glucose = b[m];\n\t\t*/\t\n\t\tfor(int m=0; m<N; m++)\n\t\t\tx[m] = voronoiDiagram->voronoiCells[m]->glucose;\n\n\t\tpassedTime = clock();\n\t\tfprintf( stderr, \"ConjugateGradient... \\n\");\n\t\tConjugateGradient( A, b, x, N, 1);\n\t\tfprintf( stderr, \"...finished ( %li clocks, %.3lf sec)\\n\", (clock() - passedTime), (float)(clock() - passedTime)/CLOCKS_PER_SEC);\n\t\t//fprintf( stderr, \"...finished ( %lisec)\\n\", (clock() - passedTime)/CLOCKS_PER_SEC);\n\n\t\tfor(int m=0; m<N; m++)\n\t\t\tvoronoiDiagram->voronoiCells[m]->glucose = x[m];\n\t}\n\n\treturn timeDifference - time;\n\t\n}\n\nvoid ConjugateGradient_old( float **A, float *b, float *x, int N, int iterations)\n{\n\tfloat r[N];\n\tfloat r2[N];\n\t\n\tfloat p[N];\n\tfloat q[N];\n\n\t//float beta[N];\n\t//float alpha[N];\n\tfloat beta;\n\tfloat alpha;\n\t\n\tfloat temp[N];\n\t\n\t\n\t// initialization of residual vector: r_0\n\tmatrixVectorProduct( A, x, temp, N);\n\tvectorDifference( b, temp, r, N);\n\t\n\t// initialization of p_0\n\tvectorCopy( r, p, N);\n\n\n\t\n\tfor( int i=0; i<iterations; i++){\n\t\t// q_k\n\t\tmatrixVectorProduct( A, p, q, N);\n\t\t\n\t\talpha = dotProduct( r, r, N);\n\t\t\n\t\tif(i>0){\n\t\t\tbeta = alpha / dotProduct( r2, r2, N);\n\t\t\t\n\t\t\tvectorScale( p, beta, p, N);\n\t\t\tvectorSum( r, p, p, N);\n\t\t}\n\t\t\n\t\talpha /= dotProduct( p, q, N);\n\n\t\t// next p\n\t\tvectorScale( p, alpha, temp, N);\n\t\tvectorSum( p, temp, p, N);\n\t\t\n\t\t// next x\n\t\tvectorScale( x, alpha, temp, N);\n\t\tvectorSum( x, temp, x, N);\n\t}\n}\n\nvoid ConjugateGradient3( float **A, float *b, float *x, int N, int iterations)\n{\n\tfloat r[N];\n\tfloat r2[N];\n\t\n\tfloat p[N];\n\tfloat q[N];\n\n\t//float beta[N];\n\t//float alpha[N];\n\tfloat beta;\n\tfloat alpha;\n\t\n\tfloat temp[N];\n\t\n\t\n\t// initialization of residual vector: r_0\n\tmatrixVectorProduct( A, x, temp, N);\n\tvectorDifference( b, temp, r, N);\n\t\n\t// initialization of p_0\n\tvectorCopy( r, p, N);\n\n\n\t\n\tfor( int i=0; i<iterations; i++){\n\t\t// q_k\n\t\tmatrixVectorProduct( A, p, q, N);\n\t\t\n\t\talpha = dotProduct( r, r, N);\n\t\t\n\t\tif(i>0){\n\t\t\tbeta = alpha / dotProduct( r2, r2, N);\n\t\t\t\n\t\t\tvectorScale( p, beta, p, N);\n\t\t\tvectorSum( r, p, p, N);\n\t\t}\n\t\t\n\t\talpha /= dotProduct( p, q, N);\n\n\t\t// next x\n\t\tvectorScale( p, alpha, temp, N);\n\t\tvectorSum( x, temp, x, N);\n\t\t\n\t\t// old r\n\t\tvectorCopy( r, r2, N);\n\t\t\n\t\t// next r\n\t\tvectorScale( q, -alpha, temp, N);\n\t\tvectorSum( r, temp, r, N);\n\t\t\n\t\t//float *pointer ;\n\t}\n}\nvoid ConjugateGradient( float **A, float *b, float *x, int N, int iterations)\n{\n\t// vectors\n\tfloat r[N];\n\tfloat w[N];\n\tfloat z[N];\n\t\n\t// scalars\n\tfloat alpha;\n\tfloat beta;\n\t\n\tfloat temp[N];\n\t\n\t\n\t// initialization of residual vector: r\n\tmatrixVectorProduct( A, x, temp, N);\n\tvectorDifference( b, temp, r, N);\n\t\n\t// w\n\tvectorScale( r, -1, w, N);\n\t\n\t// z\n\tmatrixVectorProduct( A, w, z, N);\n\t\n\t// alpha\n\talpha = dotProduct( r, w, N) / dotProduct( w, z, N);\n\t\n\t// beta\n\tbeta = 0.;\n\t\n\t// x\n\tvectorScale( w, alpha, temp, N);\n\tvectorSum( x, temp, x, N);\n\t\n\tfor( int i=0; i<iterations; i++){\n\t\tvectorScale( z, alpha, temp, N);\n\t\tvectorDifference( r, temp, r, N);\n\t\t\n\t\tif( sqrt( dotProduct( r, r, N)) < 1e-10)\n\t\t\treturn;\n\t\t\n\t\t// B = (r'*z)/(w'*z);\n\t\tbeta = dotProduct( r, z, N) / dotProduct( w, z, N);\n\t\t\n\t\t// w = -r + B*w;\n\t\tvectorScale( w, beta, w, N);\n\t\tvectorDifference( w, r, w, N);\n\t\t\n\t\t// z = A*w;\n\t\tmatrixVectorProduct( A, w, z, N);\n\t\t\n\t\t// a = (r'*w)/(w'*z);\n\t\talpha = dotProduct( r, w, N) / dotProduct( w, z, N);\n\t\t\n\t\t// x = x + a*w;\n\t\tvectorScale( w, alpha, temp, N);\n\t\tvectorSum( x, temp, x, N);\n\t}\n}\n", "meta": {"hexsha": "36cbd7b5ab6f90e26fd750afd5daacb875816930", "size": 30561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tumor2d/src/finiteDifferences.cpp", "max_stars_repo_name": "ICB-DCM/lookahead-study", "max_stars_repo_head_hexsha": "b9849ce2b0cebbe55d6c9f7a248a5f4dff191007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-20T14:14:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T21:21:18.000Z", "max_issues_repo_path": "tumor2d/src/finiteDifferences.cpp", "max_issues_repo_name": "ICB-DCM/lookahead-study", "max_issues_repo_head_hexsha": "b9849ce2b0cebbe55d6c9f7a248a5f4dff191007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-01-20T23:11:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-15T14:36:39.000Z", "max_forks_repo_path": "tumor2d/src/finiteDifferences.cpp", "max_forks_repo_name": "ICB-DCM/lookahead-study", "max_forks_repo_head_hexsha": "b9849ce2b0cebbe55d6c9f7a248a5f4dff191007", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4090441932, "max_line_length": 224, "alphanum_fraction": 0.6289388436, "num_tokens": 10888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4459836555557431}}
{"text": "#include \"PPXTF.hpp\"\r\n\r\n#include \"common.hpp\"\r\n#include <cstdio>\r\n#include <string>\r\n#include <map>\r\n#include <fstream>\r\n#include <utility>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <random>\r\n#include <tuple>\r\n#include <utility>\r\n#include <cassert>\r\n#include <iostream>\r\n#include <cstdlib>\r\n\r\n// eigen\r\n#include <Eigen/Core>\r\n\r\n// stats\r\n#define STATS_DONT_USE_OPENMP\r\n#define STATS_ENABLE_EIGEN_WRAPPERS\r\n//#define STATS_ENABLE_STDVEC_WRAPPERS\r\n//#define STATS_ENABLE_INTERNAL_VEC_FEATURES\r\n#include <stats.hpp>\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\nconstexpr int BUF_SIZE = 1000;\r\n\r\nusing p_t = pair<int, int>;\r\nusing r_t = vector<map<p_t, double> >;\r\nusing mat_t = MatrixXd;\r\nusing vec_mat_t = vector<mat_t>;\r\n\r\nstd::mt19937_64 engine;\r\n\r\nconst map<int, double> Count2Rating = {\r\n  {1,1.0},\r\n  {2,2.0},\r\n  {3,3.0},\r\n  {4,4.0},\r\n  {5,5.0},\r\n  {6,6.0},\r\n  {7,7.0},\r\n  {8,8.0},\r\n  {9,9.0},\r\n  {10,10.0}\r\n};\r\n\r\nvector<int> seq(int n){\r\n  vector<int> v(n);\r\n  for(int i = 0; i < n; ++i){v[i] = i;}\r\n  return v;\r\n}\r\n\r\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n// random\r\n\r\nvector<int> random_index(int n){\r\n  vector<int> res = seq(n);\r\n  shuffle(res.begin(), res.end(), engine);\r\n  return res;\r\n}\r\n\r\n// m \\times n matrix\r\n// numbers are uniformly random and in the [0,1] range\r\nmat_t random_mat(int m, int n){\r\n  return 0.5 * (mat_t::Random(m, n).array() + 1);\r\n}\r\n\r\n// Cholesky decomposition\r\ninline mat_t chol(const mat_t& A){\r\n  return A.llt().matrixL();\r\n}\r\n\r\n// https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Drawing_values_from_the_distribution\r\n// https://qiita.com/jhako/items/30f420033b5c126eedc1\r\n// mu[K,1]\r\n// Sigma[K,K]\r\n// ret[K,1]\r\nmat_t multivariate_normal(const mat_t& mu, const mat_t& Sigma){\r\n  int K = Sigma.rows();\r\n  assert(mu.rows() == K);\r\n  const mat_t L = chol(Sigma); // L * L' = Sigma\r\n  mat_t r = mat_t::Zero(K, 1);\r\n  for(int i = 0; i < K; ++i){r(i, 0) = stats::rnorm(0, 1, engine);}\r\n  return mu + L * r;\r\n}\r\n\r\n// https://www.math.wustl.edu/~sawyer/hmhandouts/Wishart.pdf\r\n// scale[K, K]\r\n// res[K, K]\r\nmat_t wishart_rvs(int df, const mat_t& scale){\r\n  int K = scale.rows();\r\n  mat_t A = chol(scale); // A * A' = scale\r\n  mat_t T = mat_t::Zero(K, K); // T * T' = B; B ~ W(I_d, d, n)\r\n  for(int i = 1; i < K; ++i){ // T_{i,j} ~ N(0,1) for j < i\r\n    for(int j = 0; j < i; ++j){\r\n      T(i, j) = stats::rnorm(0 ,1, engine);\r\n    }\r\n  }\r\n  for(int i = 0; i < K; ++i){ // T_{i,i} ~ \\chi^2(df-i)\r\n    T(i, i) = std::sqrt(stats::rchisq(df - i, engine));\r\n  }\r\n  mat_t AT = A * T;\r\n  return AT * AT.transpose(); // A * B * A' ~ W(scale, d, n); AT * AT' = A * T * T' * A' = A * B * A'\r\n}\r\n\r\nvoid seeding(unsigned seed){\r\n  //std::random_device seed_gen;\r\n  //engine = std::mt19937_64(seed_gen());\r\n  engine = std::mt19937_64(seed);\r\n  srand(seed); // for eigen\r\n}\r\n\r\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\ndouble count2rating(int count){\r\n  auto it = Count2Rating.lower_bound(count);\r\n  if(it == Count2Rating.end()){\r\n    return Count2Rating.rbegin()->second;\r\n  }else{\r\n    return it->second;\r\n  }\r\n}\r\n\r\ninline void write_to_tensor(r_t& r1, r_t& r2, r_t& r3,\r\n\t\t\t    int i, int j, int k,\r\n\t\t\t    double value){\r\n  r1[i][p_t(j,k)] = value;\r\n  r2[j][p_t(i,k)] = value;\r\n  r3[k][p_t(i,j)] = value;\r\n}\r\n\r\nvoid read_tensor(r_t& r1, r_t& r2, r_t& r3, const string& infile){\r\n  ifstream ifs(infile);\r\n  string line;\r\n  getline(ifs, line); // header\r\n  while(getline(ifs, line)){\r\n    auto row = split(line);\r\n    assert(row.size() >= 4);\r\n    int i = atoi(row[0].c_str());\r\n    int j = atoi(row[1].c_str());\r\n    int k = atoi(row[2].c_str());\r\n    double value = count2rating(atoi(row[3].c_str()));\r\n    write_to_tensor(r1, r2, r3, i, j, k, value);\r\n  }\r\n}\r\n\r\n/*\r\n  ###################### Read a training transition tensor ######################\r\n  # [input1]: N -- Number of users\r\n  # [input2]: M -- Number of POIs\r\n  # [output1]: RT1_observed ([user_index]{poi_index_from, poi_index_to: value})\r\n  # [output2]: RT2_observed ([poi_index_from]{user_index, poi_index_to: value})\r\n  # [output3]: RT3_observed ([poi_index_to]{user_index, poi_index_from: value})\r\n */\r\ntuple<r_t, r_t, r_t> ReadTrainTransTensor(int N, int M, int ZeroNum, const string& infile){\r\n  r_t RT1_observed(N), RT2_observed(M), RT3_observed(M);\r\n  // Read a training tensor --> (RT1,RT2,RT3)_observed\r\n  read_tensor(RT1_observed, RT2_observed, RT3_observed, infile);\r\n  // Randomly assign ZeroNum zero-values --> (RT1,RT2,RT3)_observed\r\n  if(ZeroNum > 0){\r\n    int MM = M * M;\r\n    for(int user_index = 0; user_index < N; ++user_index){\r\n      auto rand_index = random_index(MM);\r\n      int zero_num = 0;\r\n      for(int i = 0; i < MM; ++i){\r\n\tint poi_index_from = rand_index[i] % M;\r\n\tint poi_index_to = rand_index[i] / M;\r\n\tauto& a = RT1_observed[user_index];\r\n\tif(a.find(p_t(poi_index_from,poi_index_to)) == a.end()){\r\n\t  write_to_tensor(RT1_observed, RT2_observed, RT3_observed, user_index, poi_index_from, poi_index_to, 0);\r\n\t  zero_num += 1;\r\n\t  if(zero_num == ZeroNum){break;}\r\n\t}\r\n      }\r\n    }\r\n  }else if(ZeroNum == -1){\r\n    for(int user_index = 0; user_index < N; ++user_index){\r\n      for(int poi_index_from = 0; poi_index_from < M; ++poi_index_from){\r\n\tfor(int poi_index_to = 0; poi_index_to < M; ++poi_index_to){\r\n\t  auto& a = RT1_observed[user_index];\r\n\t  auto p = p_t(poi_index_from,poi_index_to);\r\n\t  if(a.find(p) == a.end()){\r\n\t    write_to_tensor(RT1_observed, RT2_observed, RT3_observed, user_index, poi_index_from, poi_index_to, 0);\r\n\t  }\r\n\t}\r\n      }\r\n    }\r\n  }\r\n  return forward_as_tuple(RT1_observed, RT2_observed, RT3_observed);\r\n}\r\n/*\r\n  ######################## Read a training visit tensor #########################\r\n  # [input1]: N -- Number of users\r\n  # [input2]: M -- Number of POIs\r\n  # [input3]: T (Number of time slots)\r\n  # [output1]: RV1_observed ([user_index]{poi_index_from, time_slot: value})\r\n  # [output2]: RV2_observed ([poi_index_from]{user_index, time_slot: value})\r\n  # [output3]: RV3_observed ([time_slot]{user_index, poi_index_from: value})\r\n */\r\ntuple<r_t, r_t, r_t> ReadTrainVisitTensor(int N, int M, int T, int ZeroNum, const string& infile){\r\n  r_t RV1_observed(N), RV2_observed(M), RV3_observed(T);\r\n  // Read a training tensor --> (RV1,RV2,RV3)_observed\r\n  read_tensor(RV1_observed, RV2_observed, RV3_observed, infile);\r\n  // Randomly assign ZeroNum zero-values --> (RV1,RV2,RV3)_observed\r\n  if(ZeroNum > 0){\r\n    int MT = M * T;\r\n    for(int user_index = 0; user_index < N; ++user_index){\r\n      auto rand_index = random_index(MT);\r\n      int zero_num = 0;\r\n      for(int i = 0; i < MT; ++i){\r\n\tint poi_index_from = rand_index[i] % M;\r\n\tint time_slot = rand_index[i] / M;\r\n\tauto& a = RV1_observed[user_index];\r\n\tif(a.find(p_t(poi_index_from,time_slot)) == a.end()){\r\n\t  write_to_tensor(RV1_observed, RV2_observed, RV3_observed, user_index, poi_index_from, time_slot, 0);\r\n\t  zero_num += 1;\r\n\t  if(zero_num == ZeroNum){break;}\r\n\t}\r\n      }\r\n    }\r\n  }else if(ZeroNum == -1){\r\n    for(int user_index = 0; user_index < N; ++user_index){\r\n      for(int poi_index_from = 0; poi_index_from < M; ++poi_index_from){\r\n\tfor(int time_slot = 0; time_slot < T; ++time_slot){\r\n\t  auto& a = RV1_observed[user_index];\r\n\t  auto p = p_t(poi_index_from,time_slot);\r\n\t  if(a.find(p) == a.end()){\r\n\t    write_to_tensor(RV1_observed, RV2_observed, RV3_observed, user_index, poi_index_from, time_slot, 0);\r\n\t  }\r\n\t}\r\n      }\r\n    }\r\n  }\r\n  return forward_as_tuple(RV1_observed, RV2_observed, RV3_observed);\r\n}\r\n\r\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n// io\r\n\r\nvoid puts_mat(FILE* fout, const mat_t& A){\r\n  int m = A.rows();\r\n  int n = A.cols();\r\n  assert(n > 0);\r\n  for(int i = 0; i < m; ++i){\r\n    fprintf(fout, \"%lf\", A(i,0));\r\n    for(int j = 1; j < n; ++j){\r\n      fprintf(fout, \",%lf\", A(i,j));\r\n    }\r\n    fprintf(fout, \"\\n\");\r\n  }\r\n}\r\n\r\nvoid savetxt(const string& outfile, const mat_t& A){\r\n  FILE* fp = fopen(outfile.c_str(), \"w\");\r\n  puts_mat(fp, A);\r\n  fclose(fp);\r\n}\r\n\r\nvoid save_parameters(int K, int ItrNum, const string& prefix, const string& name, const vec_mat_t& A, const mat_t& mu_A, const mat_t& Lam_A, const string& X){\r\n  char buf[BUF_SIZE];\r\n  sprintf(buf, \"%s_Itr%d_%s%s.csv\", prefix.c_str(), ItrNum, name.c_str(), X.c_str());\r\n  savetxt(buf, A[ItrNum]);\r\n  sprintf(buf, \"%s_Itr%d_mu_%s%s.csv\", prefix.c_str(), ItrNum, name.c_str(), X.c_str());\r\n  savetxt(buf, mu_A);\r\n  sprintf(buf, \"%s_Itr%d_Lam_%s%s.csv\", prefix.c_str(), ItrNum, name.c_str(), X.c_str());\r\n  savetxt(buf, Lam_A);\r\n}\r\n\r\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n// ppmft\r\n\r\ntuple<mat_t, mat_t> sample_Lam_X_mu_X(const mat_t& X, int N, int nu0, const mat_t& W0, double beta0, double mu0, int K){\r\n  // Sample Lam_X\r\n  // S_bar = np.sum([np.outer(A[itr, n, :], A[itr, n, :]) for n in range(N)], axis=0) / N\r\n  mat_t S_bar = X.transpose() * X / N; // [K, K]\r\n  // a_bar = np.sum(A[itr], axis=0) / N\r\n  mat_t x_bar = X.colwise().sum() / N; // [1, K]\r\n  // nu_ast = nu0 + n\r\n  int nu_ast = nu0 + N; // 1\r\n  // W0_ast = inv(inv(W0) + N * S_bar + (beta0 * N / (beta0 + N)) * np.outer(mu0 - a_bar, mu0 - a_bar))\r\n  mat_t t = mat_t::Constant(1, K, mu0) - x_bar; // [1, K]\r\n  mat_t W0_ast = (W0.inverse() + N * S_bar + (beta0 * N / (beta0 + N)) * (t.transpose() * t)).inverse(); // [K, K]\r\n  // Lam_A = wishart.rvs(df=nu_ast, scale=W0_ast)\r\n  //mat_t Lam_X = stats::rwish(W0_ast, nu_ast); // [K, K]\r\n  mat_t Lam_X = wishart_rvs(nu_ast, W0_ast); // [K, K]\r\n\r\n  // Sample mu_X\r\n  // mu0_ast = (beta0 * mu0 + N * a_bar) / (beta0 + N)\r\n  mat_t mu0_ast = ((mat_t::Constant(1, K, beta0 * mu0) + N * x_bar) / (beta0 + N)).transpose(); // [K, 1]\r\n  // mu_A = multivariate_normal(mu0_ast, inv((beta0 + N) * Lam_A))\r\n  mat_t mu_X = multivariate_normal(mu0_ast, ((beta0 + N) * Lam_X).inverse()); // [K, 1]\r\n  return forward_as_tuple(Lam_X, mu_X);\r\n}\r\n\r\ntuple<mat_t, mat_t> calc_XYXY_XYR(int K, const mat_t& B, const mat_t& C, const map<p_t, double>& rt1){\r\n  mat_t BC_BC = mat_t::Zero(K, K);\r\n  mat_t BC_R = mat_t::Zero(1, K);\r\n  for(auto kv : rt1){\r\n    int i = kv.first.first, j = kv.first.second;\r\n    double value = kv.second;\r\n    mat_t bc_ij = B.row(i).array() * C.row(j).array(); // hadamard product\r\n    mat_t bc_bc = bc_ij.transpose() * bc_ij; // [K,K]\r\n    mat_t bc_r = bc_ij * value; // [1,K]\r\n    BC_BC = BC_BC + bc_bc;\r\n    BC_R = BC_R + bc_r;\r\n  }\r\n  return forward_as_tuple(BC_BC, BC_R.transpose());\r\n}\r\n", "meta": {"hexsha": "8ed1902a3a01bbe33f7f48f101f739b1b525594f", "size": 10708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/PPXTF.cpp", "max_stars_repo_name": "LocSyn/LocSyn", "max_stars_repo_head_hexsha": "285a037d8c934195140e15bc2c997bce260ad0ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/PPXTF.cpp", "max_issues_repo_name": "LocSyn/LocSyn", "max_issues_repo_head_hexsha": "285a037d8c934195140e15bc2c997bce260ad0ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/PPXTF.cpp", "max_forks_repo_name": "LocSyn/LocSyn", "max_forks_repo_head_hexsha": "285a037d8c934195140e15bc2c997bce260ad0ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9936507937, "max_line_length": 159, "alphanum_fraction": 0.5752708256, "num_tokens": 3378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.44598365555574304}}
{"text": "/*\n * Copyright (c) 2013-2017 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef JOINTRANGE_HPP\n#define JOINTRANGE_HPP\n\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n#include <kv/affine.hpp>\n#include <kv/matplotlib.hpp>\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate<class T>\nvoid jointrange(const affine<T>& x, const affine<T>& y, const matplotlib& g, const char *color = \"blue\")\n{\n\tint n, i, j, s;\n\tT tmp;\n\tT dx, dy;\n\tub::vector<T> vx, vy;\n\tub::matrix<int> signcache;\n\n\tn = std::max(x.a.size(), y.a.size()) - 1;\n\n#if AFFINE_SIMPLE >= 1\n\tvx.resize(n+3);\n\tvy.resize(n+3);\n#else\n\tvx.resize(n+1);\n\tvy.resize(n+1);\n#endif\n\n\tfor (i=0; i<x.a.size(); i++) {\n\t\tvx(i) = x.a(i);\n\t}\n\tfor (i=x.a.size(); i<=n; i++) {\n\t\tvx(i) = 0.;\n\t}\n\tfor (i=0; i<y.a.size(); i++) {\n\t\tvy(i) = y.a(i);\n\t}\n\tfor (i=y.a.size(); i<=n; i++) {\n\t\tvy(i) = 0.;\n\t}\n\n#if AFFINE_SIMPLE >= 1\n\tvx(n+1) = x.er;\n\tvy(n+1) = 0.;\n\tvx(n+2) = 0.;\n\tvy(n+2) = y.er;\n\tn += 2;\n#endif\n\n\tsigncache.resize(n+1, n+1);\n\tfor (i=1; i<=n; i++) {\n\t\tfor (j=i+1; j<=n; j++) {\n\t\t\ttmp = vy(i) * vx(j) - vx(i) * vy(j);\n\t\t\tif (tmp >= 0.) s = 1;\n\t\t\telse s = -1;\n\t\t\tsigncache(i, j) = s;\n\t\t\tsigncache(j, i) = -s;\n\t\t}\n\t}\n\n\tfor (i=1; i<=n; i++) {\n\t\tdx = 0.;\n\t\tdy = 0.;\n\t\tfor (j=1; j<=n; j++) {\n\t\t\tif (j == i) continue;\n\t\t\t// tmp = vy(i) * vx(j) - vx(i) * vy(j);\n\t\t\t// if (tmp >= 0.) s = 1;\n\t\t\t// else s = -1;\n\t\t\ts = signcache(i, j);\n\t\t\tdx += s * vx(j);\n\t\t\tdy += s * vy(j);\n\t\t}\n\t\tg.line(vx(0)+dx+vx(i), vy(0)+dy+vy(i), \n\t\t       vx(0)+dx-vx(i), vy(0)+dy-vy(i), color);\n\t\tg.line(vx(0)-dx+vx(i), vy(0)-dy+vy(i), \n\t\t       vx(0)-dx-vx(i), vy(0)-dy-vy(i), color);\n\t}\n}\n\n} // namespace kv\n\n#endif // JOINTRANGE_HPP\n", "meta": {"hexsha": "6ea5d54fc4f1805946b07b6e22f3c65ab1f47492", "size": 1671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/jointrange.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "src/interval/kv/jointrange.hpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "src/interval/kv/jointrange.hpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 18.1630434783, "max_line_length": 104, "alphanum_fraction": 0.5068821065, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4459457827031326}}
{"text": "#include \"StdAfx.h\"\n#include \"OptApp.h\"\n#include <boost/filesystem.hpp>\n#include <g2o/types/slam3d/edge_se3.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/solvers/pcg/linear_solver_pcg.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include \"vertigo/vertex_switchLinear.h\"\n#include \"vertigo/edge_switchPrior.h\"\n#include \"vertigo/edge_se3Switchable.h\"\n\ntypedef g2o::BlockSolver< g2o::BlockSolverTraits<6, 3> >  SlamBlockSolver;\ntypedef g2o::LinearSolverCSparse<SlamBlockSolver::PoseMatrixType> SlamLinearCSparseSolver;\ntypedef g2o::LinearSolverPCG<SlamBlockSolver::PoseMatrixType> SlamLinearPCGSolver;\ntypedef std::tr1::unordered_map<int, g2o::HyperGraph::Vertex*>     VertexIDMap;\ntypedef std::pair<int, g2o::HyperGraph::Vertex*> VertexIDPair;\ntypedef std::set<g2o::HyperGraph::Edge*> EdgeSet;\n\nCOptApp::COptApp(void)\n{\n}\n\nCOptApp::~COptApp(void)\n{\n}\n\nbool COptApp::Init()\n{\n\tnamespace fs = boost::filesystem;\n\tif ( fs::exists( fs::path( odometry_log_file_ ) ) ) {\n\t\todometry_traj_.LoadFromFile( odometry_log_file_ );\n\t\tif ( fs::exists( fs::path( odometry_info_file_ ) ) ) {\n\t\t\todometry_info_.LoadFromFile( odometry_info_file_ );\n\t\t}\n\t}\n\tif ( fs::exists( fs::path( loop_log_file_ ) ) ) {\n\t\tloop_traj_.LoadFromFile( loop_log_file_ );\n\t\tif ( fs::exists( fs::path( loop_info_file_ ) ) ) {\n\t\t\tloop_info_.LoadFromFile( loop_info_file_ );\n\t\t}\n\t}\n\tpose_traj_.data_.clear();\n\tpose_traj_.data_.push_back( FramedTransformation( 0, 0, 1, Eigen::Matrix4d::Identity() ) );\n\tfor ( int i = 0; i < ( int )odometry_traj_.data_.size(); i++ ) {\n\t\tpose_traj_.data_.push_back( FramedTransformation( i + 1, i + 1, i + 2, pose_traj_.data_[ i ].transformation_ * odometry_traj_.data_[ i ].transformation_ ) );\n\t}\n\treturn ( odometry_traj_.data_.size() > 0 );\n}\n\nvoid COptApp::OptimizeSwitchable()\n{\n\tstruct SwitchableEdge {\n\tpublic:\n\t\tVertexSwitchLinear * v_;\n\t\tEdgeSwitchPrior * ep_;\n\t\tEdgeSE3Switchable * e_;\n\t\tFramedTransformation * t_;\n\t};\n\n    g2o::SparseOptimizer* optimizer;\n\toptimizer = new g2o::SparseOptimizer();\n\toptimizer->setVerbose(true);\n\tSlamBlockSolver * solver = NULL;\n\tSlamLinearCSparseSolver* linearSolver = new SlamLinearCSparseSolver();\n\tlinearSolver->setBlockOrdering(false);\n\tsolver = new SlamBlockSolver(linearSolver);\n\tg2o::OptimizationAlgorithmLevenberg* algo = new g2o::OptimizationAlgorithmLevenberg(solver);\n\toptimizer->setAlgorithm(algo);\n\n\tstd::vector< SwitchableEdge > switch_edge;\n\n\tEigen::Matrix< double, 6, 6 > default_information;\n\tdefault_information = Eigen::Matrix< double, 6, 6 >::Identity();\n\n\tfor ( int i = 0; i < ( int )pose_traj_.data_.size(); i++ ) {\n\t\tg2o::VertexSE3 * v = new g2o::VertexSE3();\n\t\tv->setId( i );\n\t\tv->setEstimate( Eigen2G2O( pose_traj_.data_[ i ].transformation_ ) );\n\t\tif ( i == 0 ) {\n\t\t\tv->setFixed( true );\n\t\t}\n\t\toptimizer->addVertex( v );\n\n\t\tif ( i > 0 ) {\n\t\t\tg2o::EdgeSE3* g2o_edge = new g2o::EdgeSE3();\n\t\t\tg2o_edge->vertices()[0] = dynamic_cast<g2o::VertexSE3*>(optimizer->vertex( i - 1 ));\n\t\t\tg2o_edge->vertices()[1] = dynamic_cast<g2o::VertexSE3*>(optimizer->vertex( i ));\n\t\t\tg2o_edge->setMeasurement( g2o::internal::fromSE3Quat( Eigen2G2O( odometry_traj_.data_[ i - 1 ].transformation_ ) ) );\n\t\t\tif ( odometry_info_.data_.size() > 0 ) {\n\t\t\t\tg2o_edge->setInformation( odometry_info_.data_[ i - 1 ].information_ );\n\t\t\t} else {\n\t\t\t\tg2o_edge->setInformation( default_information );\n\t\t\t}\n\t\t\toptimizer->addEdge( g2o_edge );\n\t\t}\n\t}\n\n\tfor ( int i = 0; i < ( int )loop_traj_.data_.size(); i++ ) {\n\t\tFramedTransformation & t = loop_traj_.data_[ i ];\n\n\t\tSwitchableEdge edge;\n\t\tedge.t_ = &t;\n\n\t\tedge.v_ = new VertexSwitchLinear();\n\t\tedge.v_->setId( optimizer->vertices().size() );\n\t\tedge.v_->setEstimate( 1.0 );\n\t\toptimizer->addVertex( edge.v_ );\n\n\t\tedge.ep_ = new EdgeSwitchPrior();\n\t\tedge.ep_->vertices()[0] = edge.v_;\n\t\tedge.ep_->setMeasurement( 1.0 );\n\t\tedge.ep_->setInformation( Eigen::Matrix<double,1,1>::Identity() * weight_ );\n\t\toptimizer->addEdge( edge.ep_ );\n\n\t\tedge.e_ = new EdgeSE3Switchable();\n\t\tedge.e_->vertices()[0] = dynamic_cast<g2o::VertexSE3*>(optimizer->vertex( t.id1_ ));\n\t\tedge.e_->vertices()[1] = dynamic_cast<g2o::VertexSE3*>(optimizer->vertex( t.id2_ ));\n\t\tedge.e_->vertices()[2] = edge.v_;\n\t\tedge.e_->setMeasurement( g2o::internal::fromSE3Quat( Eigen2G2O( t.transformation_ ) ) );\n\t\tif ( loop_info_.data_.size() > 0 ) {\n\t\t\tedge.e_->setInformation( loop_info_.data_[ i ].information_ );\n\t\t} else {\n\t\t\tedge.e_->setInformation( default_information );\n\t\t}\n\t\toptimizer->addEdge( edge.e_ );\n\t\tswitch_edge.push_back( edge );\n\t}\n\n\toptimizer->initializeOptimization();\n\toptimizer->optimize( max_iteration_ );\n\n\tfor ( int i = 0; i < ( int )pose_traj_.data_.size(); i++ ) {\n\t\tg2o::VertexSE3 * v = dynamic_cast< g2o::VertexSE3 * >( optimizer->vertex( i ) );\n\t\tpose_traj_.data_[ i ].transformation_ = G2O2Matrix4d( v->estimateAsSE3Quat() );\n\t}\n\tpose_traj_.SaveToFile( pose_log_file_ );\n\n\tloop_remain_traj_.data_.clear();\n\tfor ( int i = 0; i < ( int )switch_edge.size(); i++ ) {\n\t\tSwitchableEdge & edge = switch_edge[ i ];\n\t\tif ( edge.v_->estimate() > 0.5 ) {\n\t\t\tloop_remain_traj_.data_.push_back( loop_traj_.data_[ i ] );\n\t\t}\n\t}\n\tloop_remain_traj_.SaveToFile( loop_remain_log_file_ );\n\n\trefine_traj_.data_.clear();\n\tfor ( int i = 0; i < ( int )odometry_traj_.data_.size(); i++ ) {\n\t\trefine_traj_.data_.push_back( odometry_traj_.data_[ i ] );\n\t}\n\tfor ( int i = 0; i < ( int )switch_edge.size(); i++ ) {\n\t\tSwitchableEdge & edge = switch_edge[ i ];\n\t\tif ( edge.v_->estimate() > 0.5 && loop_traj_.data_[ i ].id1_ + 1 < loop_traj_.data_[ i ].id2_ ) {\n\t\t\trefine_traj_.data_.push_back( loop_traj_.data_[ i ] );\n\t\t}\n\t}\n\trefine_traj_.SaveToFile( refine_log_file_ );\n}\n\nvoid COptApp::OptimizeEM()\n{\n\tstruct SwitchableEdge {\n\tpublic:\n\t\tdouble weight_;\n\t\tg2o::EdgeSE3 * e_;\n\t\tFramedTransformation * t_;\n\t};\n\n\tg2o::SparseOptimizer* optimizer;\n\toptimizer = new g2o::SparseOptimizer();\n\toptimizer->setVerbose(true);\n\tSlamBlockSolver * solver = NULL;\n\tSlamLinearCSparseSolver* linearSolver = new SlamLinearCSparseSolver();\n\tlinearSolver->setBlockOrdering(false);\n\tsolver = new SlamBlockSolver(linearSolver);\n\tg2o::OptimizationAlgorithmLevenberg* algo = new g2o::OptimizationAlgorithmLevenberg(solver);\n\toptimizer->setAlgorithm(algo);\n\n\tstd::vector< SwitchableEdge > switch_edge;\n\n\tEigen::Matrix< double, 6, 6 > default_information;\n\tdefault_information = Eigen::Matrix< double, 6, 6 >::Identity();\n\n\tfor ( int i = 0; i < ( int )pose_traj_.data_.size(); i++ ) {\n\t\tg2o::VertexSE3 * v = new g2o::VertexSE3();\n\t\tv->setId( i );\n\t\tv->setEstimate( Eigen2G2O( pose_traj_.data_[ i ].transformation_ ) );\n\t\tif ( i == 0 ) {\n\t\t\tv->setFixed( true );\n\t\t}\n\t\toptimizer->addVertex( v );\n\n\t\tif ( i > 0 ) {\n\t\t\tg2o::EdgeSE3* g2o_edge = new g2o::EdgeSE3();\n\t\t\tg2o_edge->vertices()[0] = dynamic_cast<g2o::VertexSE3*>(optimizer->vertex( i - 1 ));\n\t\t\tg2o_edge->vertices()[1] = dynamic_cast<g2o::VertexSE3*>(optimizer->vertex( i ));\n\t\t\tg2o_edge->setMeasurement( g2o::internal::fromSE3Quat( Eigen2G2O( odometry_traj_.data_[ i - 1 ].transformation_ ) ) );\n\t\t\tif ( odometry_info_.data_.size() > 0 ) {\n\t\t\t\tg2o_edge->setInformation( odometry_info_.data_[ i - 1 ].information_ );\n\t\t\t} else {\n\t\t\t\tg2o_edge->setInformation( default_information );\n\t\t\t}\n\t\t\toptimizer->addEdge( g2o_edge );\n\t\t}\n\t}\n\n\tfor ( int i = 0; i < ( int )loop_traj_.data_.size(); i++ ) {\n\t\tFramedTransformation & t = loop_traj_.data_[ i ];\n\t\tSwitchableEdge edge;\n\t\tedge.t_ = &t;\n\t\tedge.weight_ = 0.0;\n\n\t\tedge.e_ = new g2o::EdgeSE3();\n\t\tedge.e_->vertices()[0] = dynamic_cast<g2o::VertexSE3*>(optimizer->vertex( t.id1_ ));\n\t\tedge.e_->vertices()[1] = dynamic_cast<g2o::VertexSE3*>(optimizer->vertex( t.id2_ ));\n\t\tedge.e_->setMeasurement( g2o::internal::fromSE3Quat( Eigen2G2O( t.transformation_ ) ) );\n\t\tif ( loop_info_.data_.size() > 0 ) {\n\t\t\tedge.e_->setInformation( loop_info_.data_[ i ].information_ );\n\t\t} else {\n\t\t\tedge.e_->setInformation( default_information );\n\t\t}\n\t\toptimizer->addEdge( edge.e_ );\n\t\tswitch_edge.push_back( edge );\n\t}\n\n\tfor ( int itr = 0; itr < max_iteration_; itr++ ) {\n\t\t// E step\n\t\tfor ( int i = 0; i < ( int )switch_edge.size(); i++ ) {\n\t\t\tSwitchableEdge & edge = switch_edge[ i ];\n\t\t\tif ( loop_info_.data_.size() > 0 ) {\n\t\t\t\tedge.e_->setInformation( loop_info_.data_[ i ].information_ );\n\t\t\t} else {\n\t\t\t\tedge.e_->setInformation( default_information );\n\t\t\t}\n\t\t\tedge.e_->computeError();\n\t\t\tedge.weight_ = ( weight_ * weight_ ) / ( weight_ * weight_ + switch_edge[ i ].e_->chi2() );\n\n\t\t\tif ( loop_info_.data_.size() > 0 ) {\n\t\t\t\tedge.e_->setInformation( loop_info_.data_[ i ].information_ * sqrt( edge.weight_ ) );\n\t\t\t} else {\n\t\t\t\tedge.e_->setInformation( default_information * sqrt( edge.weight_ ) );\n\t\t\t}\n\t\t}\n\n\t\t// M step\n\t\toptimizer->initializeOptimization();\n\t\toptimizer->optimize( 1 );\n\t}\n\n\tfor ( int i = 0; i < ( int )pose_traj_.data_.size(); i++ ) {\n\t\tg2o::VertexSE3 * v = dynamic_cast< g2o::VertexSE3 * >( optimizer->vertex( i ) );\n\t\tpose_traj_.data_[ i ].transformation_ = G2O2Matrix4d( v->estimateAsSE3Quat() );\n\t}\n\tpose_traj_.SaveToFile( pose_log_file_ );\n\n\tloop_remain_traj_.data_.clear();\n\tfor ( int i = 0; i < ( int )switch_edge.size(); i++ ) {\n\t\tSwitchableEdge & edge = switch_edge[ i ];\n\t\tif ( edge.weight_ > 0.25 ) {\n\t\t\tloop_remain_traj_.data_.push_back( loop_traj_.data_[ i ] );\n\t\t}\n\t}\n\tloop_remain_traj_.SaveToFile( loop_remain_log_file_ );\n}", "meta": {"hexsha": "80d83f109a35f26529fa6cbae1255473651d81ad", "size": 9323, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphOptimizer/OptApp.cpp", "max_stars_repo_name": "ZhaozhengPlus/ElasticReconstruction", "max_stars_repo_head_hexsha": "6ba46b2cef168249a75abfcb14c8863e2917f724", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 545.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T14:00:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:07:37.000Z", "max_issues_repo_path": "GraphOptimizer/OptApp.cpp", "max_issues_repo_name": "apprisi/ElasticReconstruction", "max_issues_repo_head_hexsha": "6ba46b2cef168249a75abfcb14c8863e2917f724", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2016-02-29T06:11:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T08:52:10.000Z", "max_forks_repo_path": "GraphOptimizer/OptApp.cpp", "max_forks_repo_name": "apprisi/ElasticReconstruction", "max_forks_repo_head_hexsha": "6ba46b2cef168249a75abfcb14c8863e2917f724", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 212.0, "max_forks_repo_forks_event_min_datetime": "2015-02-02T06:44:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:49:36.000Z", "avg_line_length": 35.1811320755, "max_line_length": 159, "alphanum_fraction": 0.6826128928, "num_tokens": 3027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.44592014647175365}}
{"text": "/* \n * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <votca/tools/akimaspline.h>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <votca/tools/linalg.h>\n#include <iostream>\n\nnamespace votca { namespace tools {\n\nusing namespace std;\n\nvoid AkimaSpline::Interpolate(ub::vector<double> &x, ub::vector<double> &y)\n{    \n    if(x.size() != y.size())\n        throw std::invalid_argument(\"error in AkimaSpline::Interpolate : sizes of vectors x and y do not match\");\n    \n    // Akima splines require at least 4 points\n    if(x.size()<4)\n        throw std::invalid_argument(\"error in AkimaSpline::Interpolate : vectors x and y have to contain at least 4 points\");\n\n    const int N = x.size();\n    \n    // adjust the grid\n    _r.resize(N);\n    \n    // copy the grid points into f\n    _r = x;\n    \n    // initialize vectors p1,p2,p3,p4 and t\n    p0 = ub::zero_vector<double>(N);\n    p1 = ub::zero_vector<double>(N);\n    p2 = ub::zero_vector<double>(N);\n    p3 = ub::zero_vector<double>(N);\n    t = ub::zero_vector<double>(N);\n\n    double m1,m2,m3,m4;\n\n    double temp, g0, g1, g2, x1, x2, y1, y2, x4, x5, y4, y5, m5;\n    \n    // boundary conditions\n    // >> determine t(0), t(1) and t(N-2), t(N-1)\n    switch(_boundaries) {\n        case splineNormal:\n            // Akima method: estimation of two more points on each side using a\n            // degree two polyomial\n            // resulting slopes t(0), t(1), t(N-2), t(N-1) are directly calculated\n\n            // left side: t(0), t(1)\n            temp = (x(1)-x(0))/(x(2)-x(0));\n            temp = temp*temp;\n            g0 = y(0);\n            g1 = ( (y(1)-y(0)) - temp*(y(2)-y(0)) ) / ( (x(1)-x(0)) - temp*(x(2)-x(0)) );\n            g2 = ( (y(2)-y(0)) - g1*(x(2)-x(0)) ) / ( (x(2)-x(0))*(x(2)-x(0)) );\n            x1 = x(0) - (x(2)-x(0));\n            x2 = x(1) - (x(2)-x(0));\n            y1 = g0 + g1*(x1-x(0)) + g2*(x1-x(0))*(x1-x(0));\n            y2 = g0 + g1*(x2-x(0)) + g2*(x2-x(0))*(x2-x(0));\n            m1 = (y2-y1)/(x2-x1);\n            m2 = (y(0)-y2)/(x(0)-x2);\n            m3 = (y(1)-y(0))/(x(1)-x(0));\n            m4 = (y(2)-y(1))/(x(2)-x(1));\n            t(0) = getSlope(m1,m2,m3,m4);\n            m5 = (y(3)-y(2))/(x(3)-x(2));\n            t(1) = getSlope(m2,m3,m4,m5);\n\n            // right side: t(N-2), t(N-1)\n            temp = (x(N-2)-x(N-1))/(x(N-3)-x(N-1));\n            temp = temp*temp;\n            g0 = y(N-1);\n            g1 = ( (y(N-2)-y(N-1)) - temp*(y(N-3)-y(N-1)) ) / ( (x(N-2)-x(N-1)) - temp*(x(N-3)-x(N-1)) );\n            g2 = ( (y(N-3)-y(N-1)) - g1*(x(N-3)-x(N-1)) ) / ( (x(N-3)-x(N-1))*(x(N-3)-x(N-1)) );\n            x4 = x(N-2) + (x(N-1)-x(N-3));\n            x5 = x(N-1) + (x(N-1)-x(N-3));\n            y4 = g0 + g1*(x4-x(N-1)) + g2*(x4-x(N-1))*(x4-x(N-1));\n            y5 = g0 + g1*(x5-x(N-1)) + g2*(x5-x(N-1))*(x5-x(N-1));\n            m1 = (y(N-3)-y(N-4))/(x(N-3)-x(N-4));\n            m2 = (y(N-2)-y(N-3))/(x(N-2)-x(N-3));\n            m3 = (y(N-1)-y(N-2))/(x(N-1)-x(N-2));\n            m4 = (y4-y(N-1))/(x4-x(N-1));\n            m5 = (y5-y4)/(x5-x4);\n            t(N-2) = getSlope(m1,m2,m3,m4);\n            t(N-1) = getSlope(m2,m3,m4,m5);\n            break;\n        case splinePeriodic:\n            // left: last two points determine the slopes t(0), t(1)\n            m1 = (y(N-1)-y(N-2))/(x(N-1)-x(N-2));\n            m2 = (y(0)-y(N-1))/(x(0)-x(N-1));\n            m3 = (y(1)-y(0))/(x(1)-x(0));\n            m4 = (y(2)-y(1))/(x(2)-x(1));\n            m5 = (y(3)-y(2))/(x(3)-x(2));\n            t(0) = getSlope(m1,m2,m3,m4);\n            t(1) = getSlope(m2,m3,m4,m5);\n            // right: first two points determine the slopes t(N-2), t(N-1)\n            m1 = (y(N-3)-y(N-4))/(x(N-3)-x(N-4));\n            m2 = (y(N-2)-y(N-3))/(x(N-2)-x(N-3));\n            m3 = (y(N-1)-y(N-2))/(x(N-1)-x(N-2));\n            m4 = (y(0)-y(N-1))/(x(0)-x(N-1));\n            m5 = (y(1)-y(0))/(x(1)-x(0));\n            t(N-2) = getSlope(m1,m2,m3,m4);\n            t(N-1) = getSlope(m2,m3,m4,m5);\n            break;\n        case splineDerivativeZero:\n\t    throw std::runtime_error(\"erro in AkimaSpline::Interpolate: case splineDerivativeZero not implemented yet\");\n\t    break;\n    }\n    \n    // calculate t's for all inner points [2,N-3]\n    for (int i=2; i<N-2; i++) {\n        m1 = (y(i-1)-y(i-2))/(x(i-1)-x(i-2));\n        m2 = (y(i)-y(i-1))/(x(i)-x(i-1));\n        m3 = (y(i+1)-y(i))/(x(i+1)-x(i));\n        m4 = (y(i+2)-y(i+1))/(x(i+2)-x(i+1));\n        t(i) = getSlope(m1,m2,m3,m4);\n    }\n\n    // calculate p0,p1,p2,p3 for all intervals 0..(N-2), where interval\n    // [x(i),x(i+1)] shall have number i (this means that the last interval\n    // has number N-2)\n    for (int i=0; i<N-1; i++) {\n        p0(i) = y(i);\n        p1(i) = t(i);\n        p2(i) = ( 3.0*(y(i+1)-y(i))/(x(i+1)-x(i)) - 2.0*t(i) - t(i+1) ) / (x(i+1)-x(i));\n        p3(i) = ( t(i) + t(i+1) - 2.0*(y(i+1)-y(i))/(x(i+1)-x(i)) ) / ( (x(i+1)-x(i))*(x(i+1)-x(i)) );\n    }\n}\n\nvoid AkimaSpline::Fit(ub::vector<double> &x, ub::vector<double> &y)\n{\n    throw std::runtime_error(\"Akima fit not implemented.\");\n}\n\n}}\n", "meta": {"hexsha": "e5ea7a4e0020f535cd0596709ccc085808d24819", "size": 5704, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/akimaspline.cc", "max_stars_repo_name": "vaidyanathanms/votca.tools", "max_stars_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libtools/akimaspline.cc", "max_issues_repo_name": "vaidyanathanms/votca.tools", "max_issues_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libtools/akimaspline.cc", "max_forks_repo_name": "vaidyanathanms/votca.tools", "max_forks_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0266666667, "max_line_length": 125, "alphanum_fraction": 0.4786115007, "num_tokens": 2161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4459201464717536}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file analyticpdfhestonengine.cpp\n    \\brief Analytic engine for arbitrary European payoffs under the Heston model\n*/\n\n#include <ql/math/functional.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/experimental/exoticoptions/analyticpdfhestonengine.hpp>\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n\n#include <boost/bind.hpp>\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\n#include <cmath>\n#include <complex>\n\nnamespace QuantLib {\n\n    namespace {\n        struct HestonParams {\n            Real v0, kappa, theta, sigma, rho;\n        };\n\n        HestonParams getHestonParams(\n            const boost::shared_ptr<HestonModel>& model) {\n            const HestonParams p = { model->v0(),    model->kappa(),\n                                     model->theta(), model->sigma(),\n                                     model->rho() };\n            return p;\n        }\n\n        std::complex<Real> gamma(const HestonParams& p, Real p_x) {\n            return std::complex<Real>(p.kappa, p.rho*p.sigma*p_x);\n        }\n\n        std::complex<Real> omega(const HestonParams& p, Real p_x) {\n           const std::complex<Real> g = gamma(p, p_x);\n           return std::sqrt(g*g\n                  + p.sigma*p.sigma*std::complex<Real>(p_x*p_x, -p_x));\n        }\n\n        class CpxPv_Helper\n            : public std::unary_function<Real, Real > {\n          public:\n            CpxPv_Helper(const HestonParams& p, Real x, Time t)\n              : p_(p), t_(t), x_(x),\n                c_inf_(std::min(10.0, std::max(0.0001,\n                      std::sqrt(1.0-square<Real>()(p_.rho))/p_.sigma))\n                      *(p_.v0 + p_.kappa*p_.theta*t))  {}\n\n            Real operator()(Real x) const {\n                return std::real(transformPhi(x));\n            }\n\n            Real p0(Real p_x) const {\n                if (p_x < QL_EPSILON) {\n                    return 0.0;\n                }\n\n                const Real u_x = std::max(QL_EPSILON, -std::log(p_x)/c_inf_);\n                return std::real(phi(u_x)\n                        *std::exp(std::complex<Real>(0.0, -2*u_x*x_))\n                        /((p_x*c_inf_)*std::complex<Real>(0.0, u_x)));\n            }\n\n          private:\n            std::complex<Real> transformPhi(Real x) const {\n                if (x < QL_EPSILON) {\n                    return std::complex<Real>(0.0, 0.0);\n                }\n\n                const Real u_x = -std::log(x)/c_inf_;\n                return phi(u_x)/(x*c_inf_);\n            }\n\n            std::complex<Real> phi(Real p_x) const {\n                const Real sigma2 = p_.sigma*p_.sigma;\n                const std::complex<Real> g = gamma(p_, p_x);\n                const std::complex<Real> o = omega(p_, p_x);\n                const std::complex<Real> gamma = (g-o)/(g+o);\n\n                return 2.0*std::exp(std::complex<Real>(0.0, p_x*x_)\n                        - p_.v0*std::complex<Real>(p_x*p_x, -p_x)\n                          /(g+o*(1.0+std::exp(-o*t_))/(1.0-std::exp(-o*t_)))\n                         +p_.kappa*p_.theta/sigma2*(\n                           (g-o)*t_ - 2.0*std::log((1.0-gamma*std::exp(-o*t_))\n                                                               /(1.0-gamma))));\n            }\n\n            const HestonParams& p_;\n            const Time t_;\n            const Real x_, c_inf_;\n        };\n    }\n\n    AnalyticPDFHestonEngine::AnalyticPDFHestonEngine(\n        const boost::shared_ptr<HestonModel>& model,\n        Real gaussLobattoEps,\n        Size gaussLobattoIntegrationOrder)\n    : gaussLobattoIntegrationOrder_(gaussLobattoIntegrationOrder),\n      gaussLobattoEps_(gaussLobattoEps),\n      model_(model) {  }\n\n    void AnalyticPDFHestonEngine::calculate() const {\n        // this is an European option pricer\n        QL_REQUIRE(arguments_.exercise->type() == Exercise::European,\n                   \"not an European option\");\n\n        const boost::shared_ptr<HestonProcess>& process = model_->process();\n\n        const Time t = process->time(arguments_.exercise->lastDate());\n\n        const Real xMax = 8.0 * std::sqrt(process->theta()*t\n            + (process->v0() - process->theta())\n                *(1-std::exp(-process->kappa()*t))/process->kappa());\n\n        results_.value = GaussLobattoIntegral(\n            gaussLobattoIntegrationOrder_, gaussLobattoEps_)(\n            boost::bind(&AnalyticPDFHestonEngine::weightedPayoff, this,_1, t),\n                         -xMax, xMax);\n    }\n\n    Real AnalyticPDFHestonEngine::Pv(Real x_t, Time t) const {\n        return GaussLobattoIntegral(\n            gaussLobattoIntegrationOrder_, 0.1*gaussLobattoEps_)(\n                CpxPv_Helper(getHestonParams(model_), x_t, t),\n                0.0, 1.0)/M_TWOPI;\n    }\n\n    Real AnalyticPDFHestonEngine::cdf(Real s, Time t) const {\n        const boost::shared_ptr<HestonProcess>& process = model_->process();\n        const DiscountFactor d=  process->riskFreeRate()->discount(t)\n                               / process->dividendYield()->discount(t);\n\n        const Real s_t = process->s0()->value()/d;\n        const Real x = std::log(s_t/s);\n\n        return GaussLobattoIntegral(\n            gaussLobattoIntegrationOrder_, gaussLobattoEps_)(\n                boost::bind(&CpxPv_Helper::p0,\n                    CpxPv_Helper(getHestonParams(model_), x, t), _1),\n                0.0, 1.0)/M_TWOPI + 0.5;\n    }\n\n    Real AnalyticPDFHestonEngine::weightedPayoff(Real x_t, Time t) const {\n        const boost::shared_ptr<HestonProcess>& process = model_->process();\n\n        const Real s_0 = process->s0()->value();\n        const DiscountFactor rD = process->riskFreeRate()->discount(t);\n        const DiscountFactor dD = process->dividendYield()->discount(t);\n\n        const Real s_t = s_0*std::exp(x_t)*dD/rD;\n        const Real payoff = (*arguments_.payoff)(s_t);\n\n        return (payoff != 0.0) ? payoff*Pv(x_t, t)*rD : 0.0;\n    }\n}\n\n", "meta": {"hexsha": "7dd20f3c62d492b9f364e2a4dbf766973942c923", "size": 6866, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLib/ql/experimental/exoticoptions/analyticpdfhestonengine.cpp", "max_stars_repo_name": "txu2014/quantlib", "max_stars_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantLib/ql/experimental/exoticoptions/analyticpdfhestonengine.cpp", "max_issues_repo_name": "txu2014/quantlib", "max_issues_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/ql/experimental/exoticoptions/analyticpdfhestonengine.cpp", "max_forks_repo_name": "txu2014/quantlib", "max_forks_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3152173913, "max_line_length": 87, "alphanum_fraction": 0.5655403437, "num_tokens": 1796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.44586552846838656}}
{"text": "#include <iostream>\n#include <memory>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <functional>\n#include <Eigen/Dense>\n#include \"../include/sample_network.h\"\n#include \"../include/numerical_gradient.h\"\n\nnamespace MyDL{\n\n    using namespace Eigen;\n    using std::shared_ptr;\n    using std::make_shared;\n    using std::string;\n    using std::vector;\n    using std::unordered_map;\n    using std::cout;\n    using std::endl;\n\n    TwoLayerNet::TwoLayerNet(int input_size, int hidden_size, int output_size, double weight_init_std)\n    {\n        // 内部保持パラメータ\n        _input_size = input_size;\n        _hidden_size = hidden_size;\n        _output_size = output_size;\n        _weight_init_std = weight_init_std;\n\n        // Affine Layer用のパラメータ -> スマートポインタで保持し、それをパラメータのリストに格納\n        auto W1 = make_shared<MatrixXd>(input_size, hidden_size);\n        auto W2 = make_shared<MatrixXd>(hidden_size, output_size);\n        auto b1 = make_shared<MatrixXd>(1, hidden_size);\n        auto b2 = make_shared<MatrixXd>(1, output_size);\n\n        *W1 = weight_init_std * MatrixXd::Random(input_size, hidden_size);\n        *W2 = weight_init_std * MatrixXd::Random(hidden_size, output_size);\n        *b1 = MatrixXd::Zero(1, hidden_size);\n        *b2 = MatrixXd::Zero(1, output_size);\n\n        // Layer作成 -> スマートポインタで実装(コンストラクタを抜けた時に、実体が消されないようにするため)\n        // 左辺の型はautoにしてはいけない(BaseLayerで統一し、コンテナに格納する ※ポリモーフィズムの実現)\n        shared_ptr<BaseLayer> affine1    = make_shared<MyDL::Affine>(W1, b1);\n        shared_ptr<BaseLayer> affine2    = make_shared<MyDL::Affine>(W2, b2);\n        shared_ptr<BaseLayer> relu1      = make_shared<ReLU>();\n        shared_ptr<BaseLayer> last_layer = make_shared<SoftmaxWithLoss>(); // predictではaffine2の出力、lossではlastlayerの出力を使うので分ける\n\n        // 生のポインタを格納すると実体がスコープ外となり解放されてしまうので、shared_ptrで対処\n        _layers[\"Affine1\"] = affine1;\n        _layers[\"ReLU1\"] = relu1;\n        _layers[\"Affine2\"] = affine2;\n        _last_layer = last_layer;\n\n        // 各パラメータへのポインタを格納\n        if (auto cast_affine1 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine1\"]))\n        {\n            params[\"W1\"] = cast_affine1->pW;\n            params[\"b1\"] = cast_affine1->pb;\n        }\n        if (auto cast_affine2 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine2\"]))\n        {\n            params[\"W2\"] = cast_affine2->pW;\n            params[\"b2\"] = cast_affine2->pb;\n        }\n\n        // unordered_mapでは追加順が保存されないので、別途順番通り名称を格納したコンテナを用意\n        _layer_list.push_back(\"Affine1\");\n        _layer_list.push_back(\"BatchNorm\"); // for batchnorm debug 21/03/21追加\n        _layer_list.push_back(\"ReLU1\");\n        _layer_list.push_back(\"Affine2\");\n\n        // ------------------------------------------------\n        // for batchnorm debug 21/03/21追加\n        // ------------------------------------------------\n        auto gamma = make_shared<MatrixXd>(1, hidden_size);\n        auto beta = make_shared<MatrixXd>(1, hidden_size);\n        *gamma = weight_init_std * MatrixXd::Random(1, hidden_size);\n        *beta = MatrixXd::Zero(1, hidden_size);\n        shared_ptr<BaseLayer> batch_norm = make_shared<BatchNorm>(gamma, beta);\n        _layers[\"BatchNorm\"] = batch_norm;\n        if (auto cast_batchnorm = std::dynamic_pointer_cast<BatchNorm>(_layers[\"BatchNorm\"]))\n        {\n            params[\"gamma\"] = cast_batchnorm->pgamma;\n            params[\"beta\"]  = cast_batchnorm->pbeta;\n        }\n    }\n\n    vector<MatrixXd> TwoLayerNet::predict(vector<MatrixXd> inputs)\n    {\n        // inputのバリデーションをしておくか？\n        vector<MatrixXd> X = inputs;// 入力もvectorなので、そのまま受ければOK\n        vector<MatrixXd> tmp_X;\n\n        // mapのrange-forは内部的にstd::pairが返される\n        for(auto layer : _layer_list)\n        {\n            // cout << layer << endl;\n            tmp_X = _layers[layer]->forward(X);\n            X.swap(tmp_X); // 中身入れ替え\n        }\n        return X;\n    }\n\n    vector<MatrixXd> TwoLayerNet::loss(vector<MatrixXd> inputs)\n    {\n        vector<MatrixXd> pred_input, pred_out, loss_inputs, loss_output;\n        pred_input.push_back(inputs[0]);\n        pred_out = predict(pred_input);\n\n        loss_inputs = inputs;\n        loss_inputs[0] = pred_out[0];\n\n        loss_output = _last_layer->forward(loss_inputs);\n        return loss_output;\n    }\n\n    double TwoLayerNet::accuracy(vector<MatrixXd> inputs)\n    {\n        vector<MatrixXd> pred_input, pred_out;\n        pred_input.push_back(inputs[0]);\n        pred_out = predict(pred_input);\n\n        MatrixXd y, t;\n        y = pred_out[0];\n        t = inputs[1];\n        double batch_size = t.rows();\n        double accuracy = 0;\n\n        MatrixXd::Index y_row, y_col, t_row, t_col;\n        for (int i = 0; i < batch_size; i++)\n        {\n            y.row(i).maxCoeff(&y_row, &y_col);\n            t.row(i).maxCoeff(&t_row, &t_col);\n\n            accuracy += (double)(y_col == t_col);\n        }\n\n        return accuracy / batch_size;\n    }\n\n    unordered_map<string, MatrixXd> TwoLayerNet::gradient(vector<MatrixXd> inputs)\n    {\n        // Forward\n        vector<MatrixXd> output;\n        output = loss(inputs); // forward -> 逆伝播計算に必要な情報を各レイヤにキャッシュ\n\n        // Backward\n        vector<MatrixXd> dout, tmp_dout;\n        dout.push_back(MatrixXd::Ones(1,1));\n\n        dout = _last_layer->backward(dout);\n\n        // 逆順ループ → Boostライブラリのboost::adaptors::reverse()を使う方がEasyではある\n        for (auto it = _layer_list.rbegin(); it != _layer_list.rend(); it++)\n        {\n            string layer = *it;\n            tmp_dout = _layers[layer]->backward(dout);\n            dout.swap(tmp_dout);\n        }\n\n        unordered_map<string, MatrixXd> grads;\n        // _layersに格納している変数はBaseLayerにアップキャストしているので、ダウンキャストが必要 -> nullptrのときは実行しないようにする\n        if(shared_ptr<MyDL::Affine> affine1 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine1\"]))\n        {\n            grads[\"W1\"] = affine1->dW;\n            grads[\"b1\"] = affine1->db;\n        }\n        if(shared_ptr<MyDL::Affine> affine2 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine2\"]))\n        {\n            grads[\"W2\"] = affine2->dW;\n            grads[\"b2\"] = affine2->db;\n        }\n\n        // for batchnorm debug 21/03/21追加\n        if(auto batchnorm = std::dynamic_pointer_cast<BatchNorm>(_layers[\"BatchNorm\"]))\n        {\n            grads[\"gamma\"] = batchnorm->dgamma;\n            grads[\"beta\"]  = batchnorm->dbeta;\n        }\n\n        return grads;\n    }\n\n    unordered_map<string, MatrixXd> TwoLayerNet::numerical_gradient(vector<MatrixXd> inputs)\n    {\n        // [&]は、スコープ外の変数を参照するというキャプチャー(ここではthisポインタを使うために指定)\n        std::function<vector<MatrixXd>(MatrixXd)> loss_W = [this, &inputs](MatrixXd W) -> vector<MatrixXd> { return this->loss(inputs); };\n        std::function<vector<MatrixXd>(VectorXd)> loss_W2 = [this, &inputs](VectorXd W) -> vector<MatrixXd> { return this->loss(inputs); };\n        unordered_map<string, MatrixXd> grads;\n\n        MatrixXd dW1, dW2, db1, db2;\n\n        // 直接内部のレイヤのパラメータにアクセスするので、ダウンキャストが必要\n        if (shared_ptr<MyDL::Affine> affine1 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine1\"]))\n        {\n            dW1 = MyDL::numerical_gradient(loss_W, affine1->_W);\n            db1 = MyDL::numerical_gradient(loss_W2, affine1->_b);\n        }\n        if (shared_ptr<MyDL::Affine> affine2 = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine2\"]))\n        {\n            dW2 = MyDL::numerical_gradient(loss_W, affine2->_W);\n            db2 = MyDL::numerical_gradient(loss_W2, affine2->_b);\n        }\n\n        grads[\"dW1\"] = dW1;\n        grads[\"dW2\"] = dW2;\n        grads[\"db1\"] = db1;\n        grads[\"db2\"] = db2;\n\n        return grads;\n    }\n\n    // -----------------------------------------------------------\n    // MultiLayerNet: Weight Decay の検証用\n    // 【21/04/06】\n    // とりあえず動作することを目指すので、最初はreluで構成\n    // 後ほどsigmoid含めて動くように変更。初期値も XavierとHeの両方を選択できるようにする。\n    // -----------------------------------------------------------\n\n    MultiLayerNet::MultiLayerNet(const int input_size,\n                                 const vector<int> hidden_size, \n                                 const int output_size,\n                                 const double weight_decay_lambda)\n    {\n        _input_size = input_size;\n        _hidden_size_list = hidden_size;\n        _output_size = output_size;\n        _weight_decay_lambda = weight_decay_lambda;\n\n        // 各パラメータの初期化\n\n        _layers[\"Affine1\"] = make_shared<MyDL::Affine>(_input_size, _hidden_size_list[0]);\n        _layers[\"ReLU1\"] = make_shared<ReLU>();\n        _layer_list.push_back(\"Affine1\");\n        _layer_list.push_back(\"ReLU1\");\n        for (int i=0; i<_hidden_size_list.size()-1; i++)\n        {\n            string tmp_num_str = std::to_string(i+2);\n            _layers[\"Affine\" + tmp_num_str] = make_shared<MyDL::Affine>(_hidden_size_list[i], _hidden_size_list[i + 1]);\n            _layers[\"ReLU\" + tmp_num_str] = make_shared<ReLU>();\n            _layer_list.push_back(\"Affine\" + tmp_num_str);\n            _layer_list.push_back(\"ReLU\" + tmp_num_str);\n        }\n        string tmp_num_str = std::to_string(_hidden_size_list.size()+1);\n        _layers[\"Affine\" + tmp_num_str] = make_shared<MyDL::Affine>(_hidden_size_list[_hidden_size_list.size() - 1], _output_size);\n        _layers[\"ReLU\" + tmp_num_str] = make_shared<ReLU>();\n        _layer_list.push_back(\"Affine\" + tmp_num_str);\n        _layer_list.push_back(\"ReLU\" + tmp_num_str);\n\n        _last_layer = make_shared<SoftmaxWithLoss>(); // Loss Layer\n\n        for (int layer_num = 1; layer_num <= _hidden_size_list.size()+1; layer_num++)\n        {\n            if (auto cast_affine = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine\" + std::to_string(layer_num)]))\n            {\n                params[\"W\" + std::to_string(layer_num)] = cast_affine->pW;\n                params[\"b\" + std::to_string(layer_num)] = cast_affine->pb;\n            }\n        }        \n\n    }\n\n\n    vector<MatrixXd> MultiLayerNet::predict(vector<MatrixXd> inputs)\n    {\n        vector<MatrixXd> X = inputs;\n        vector<MatrixXd> tmp_X;\n\n        for (auto layer : _layer_list)\n        {\n            tmp_X = _layers[layer]->forward(X);\n            X.swap(tmp_X);\n        }\n        return X;\n    }\n\n    vector<MatrixXd> MultiLayerNet::loss(vector<MatrixXd> inputs, MatrixXd& t)\n    {\n        vector<MatrixXd> pred_input, pred_out, loss_inputs, loss_output;\n        pred_input.push_back(inputs[0]);\n        pred_out = predict(pred_input);\n\n        loss_inputs.push_back(pred_out[0]);\n        loss_inputs.push_back(t);\n\n        loss_output = _last_layer->forward(loss_inputs);\n\n        // あとは Weight Decay の項も計算してLossに加える\n        double weight_decay = 0;\n        for (auto param: params)\n        {\n            weight_decay += 0.5 * _weight_decay_lambda * (*(param.second)).sum();\n        }\n\n        loss_output[0](0) = loss_output[0](0) + weight_decay;\n\n        return loss_output;\n    }\n\n    double MultiLayerNet::accuracy(vector<MatrixXd> inputs, MatrixXd& t)\n    {\n        vector<MatrixXd> pred_out;\n        pred_out = predict(inputs);\n\n        MatrixXd y;\n        y = pred_out[0];\n        double batch_size = t.rows();\n        double accuracy = 0;\n\n        MatrixXd::Index y_row, y_col, t_row, t_col;\n        for (int i = 0; i < batch_size; i++)\n        {\n            y.row(i).maxCoeff(&y_row, &y_col);\n            t.row(i).maxCoeff(&t_row, &t_col);\n\n            accuracy += (double)(y_col == t_col);\n        }\n\n        return accuracy / batch_size;\n    }\n\n    unordered_map<string, MatrixXd> MultiLayerNet::gradient(vector<MatrixXd> inputs, MatrixXd& t)\n    {\n        // Forward\n        vector<MatrixXd> output;\n        output = loss(inputs, t);\n\n        // Backward\n        vector<MatrixXd> dout, tmp_dout;\n        dout.push_back(MatrixXd::Ones(1,1));\n\n        dout = _last_layer->backward(dout);\n\n        for (auto it = _layer_list.rbegin(); it != _layer_list.rend(); it++)\n        {\n            string layer = *it;\n            tmp_dout = _layers[layer]->backward(dout);\n            dout.swap(tmp_dout);\n        }\n\n        unordered_map<string, MatrixXd> grads;\n\n        for (int i = 1; i <= _hidden_size_list.size()+1; i++)\n        {\n            if(auto tmp_affine = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine\" + std::to_string(i)]))\n            {\n                grads[\"W\" + std::to_string(i)] = tmp_affine->dW + _weight_decay_lambda * (*(tmp_affine->pW));\n                grads[\"b\" + std::to_string(i)] = tmp_affine->db;\n            }\n        }\n\n        return grads;\n    }\n\n\n\n    // -----------------------------------------------------------\n    // AffineLayer デバッグ用クラス → 参照先の更新確認\n    // -----------------------------------------------------------\n    DebugAffine::DebugAffine(int input_size, int output_size, double weight_init_std)\n    {\n        _input_size = input_size;\n        _output_size = output_size;\n\n        MatrixXd W = weight_init_std * MatrixXd::Random(input_size, output_size);\n        MatrixXd b = MatrixXd::Zero(1, output_size);\n\n        shared_ptr<BaseLayer> affine = std::make_shared<MyDL::Affine>(W, b);\n        _layers[\"Affine\"] = affine;\n\n        if(shared_ptr<MyDL::Affine> tmp_affine = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine\"]))\n        {\n            params[\"W\"] = tmp_affine->_W; // ここではコピーコンストラクタが走る\n            params[\"b\"] = tmp_affine->_b;\n        }\n    }\n\n    void DebugAffine::PrintLayerParams(void)\n    {\n        if (shared_ptr<MyDL::Affine> tmp_affine = std::dynamic_pointer_cast<MyDL::Affine>(_layers[\"Affine\"]))\n        {\n            cout << \"--- parameter W ---\" << endl;\n            cout << tmp_affine->_W << endl;\n            cout << \"--- parameter b ---\" << endl;\n            cout << tmp_affine->_b << endl;\n        }\n    }\n\n}", "meta": {"hexsha": "0190acc2a9700cf3fabb7b65c14558a000abfff6", "size": 13643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sample_network.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "src/sample_network.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sample_network.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0719794344, "max_line_length": 139, "alphanum_fraction": 0.5800043979, "num_tokens": 3871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.44586552846838656}}
{"text": "#include <utils.h>\n#include <cmath>\n#include <vector>\n#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <boost/lexical_cast.hpp>\n#include <iomanip>\n#include <ros/package.h>\n\n\n#define DEG2RAD 0.01745329\npalette GetPalette(palette::palettetypes pal)\n{\n  palette ret;\n\n  int i, r, g, b;\n  float f;\n\n  switch (pal)\n  {\n    case palette::Linear_red_palettes:\n      /*\n       * Linear red palettes.\n       */\n      for (i = 0; i < 256; i++)\n      {\n        ret.colors[i].rgbBlue = 0;\n        ret.colors[i].rgbGreen = 0;\n        ret.colors[i].rgbRed = i;\n      }\n      break;\n    case palette::GammaLog_red_palettes:\n      /*\n       * GammaLog red palettes.\n       */\n      for (i = 0; i < 256; i++)\n      {\n        f = log10(pow((i / 255.0), 1.0) * 9.0 + 1.0) * 255.0;\n        ret.colors[i].rgbBlue = 0;\n        ret.colors[i].rgbGreen = 0;\n        ret.colors[i].rgbRed = f;\n      }\n      break;\n    case palette::Inversion_red_palette:\n      /*\n       * Inversion red palette.\n       */\n      for (i = 0; i < 256; i++)\n      {\n        ret.colors[i].rgbBlue = 0;\n        ret.colors[i].rgbGreen = 0;\n        ret.colors[i].rgbRed = 255 - i;\n      }\n      break;\n    case palette::Linear_palettes:\n      /*\n       * Linear palettes.\n       */\n      for (i = 0; i < 256; i++)\n      {\n        ret.colors[i].rgbBlue = ret.colors[i].rgbGreen = ret.colors[i].rgbRed = i;\n      }\n      break;\n    case palette::GammaLog_palettes:\n      /*\n       * GammaLog palettes.\n       */\n      for (i = 0; i < 256; i++)\n      {\n        f = log10(pow((i / 255.0), 1.0) * 9.0 + 1.0) * 255.0;\n        ret.colors[i].rgbBlue = ret.colors[i].rgbGreen = ret.colors[i].rgbRed = f;\n      }\n      break;\n    case palette::Inversion_palette:\n      /*\n       * Inversion palette.\n       */\n      for (i = 0; i < 256; i++)\n      {\n        ret.colors[i].rgbBlue = ret.colors[i].rgbGreen = ret.colors[i].rgbRed = 255 - i;\n      }\n      break;\n    case palette::False_color_palette1:\n      /*\n       * False color palette #1.\n       */\n      for (i = 0; i < 256; i++)\n      {\n        r = (sin((i / 255.0 * 360.0 - 120.0 > 0 ? i / 255.0 * 360.0 - 120.0 : 0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n        g = (sin((i / 255.0 * 360.0 + 60.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n        b = (sin((i / 255.0 * 360.0 + 140.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n        ret.colors[i].rgbBlue = b;\n        ret.colors[i].rgbGreen = g;\n        ret.colors[i].rgbRed = r;\n      }\n      break;\n    case palette::False_color_palette2:\n      /*\n       * False color palette #2.\n       */\n      for (i = 0; i < 256; i++)\n      {\n        r = (sin((i / 255.0 * 360.0 + 120.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n        g = (sin((i / 255.0 * 360.0 + 240.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n        b = (sin((i / 255.0 * 360.0 + 0.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n        ret.colors[i].rgbBlue = b;\n        ret.colors[i].rgbGreen = g;\n        ret.colors[i].rgbRed = r;\n      }\n      break;\n    case palette::False_color_palette3:\n      /*\n       * False color palette #3.\n       */\n      for (i = 0; i < 256; i++)\n      {\n        r = (sin((i / 255.0 * 360.0 + 240.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n        g = (sin((i / 255.0 * 360.0 + 0.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n        b = (sin((i / 255.0 * 360.0 + 120.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n        ret.colors[i].rgbBlue = b;\n        ret.colors[i].rgbGreen = g;\n        ret.colors[i].rgbRed = r;\n      }\n      break;\n\n    case palette::False_color_palette4:\n      /*\n       * False color palette #4. Matlab JET\n       */\n\n      enum\n      {\n        nsep = 64, nvals = 192, n = 256\n      };\n\n      std::vector<double> vals;\n      vals.resize(nvals, 0);\n\n      int idx = 0;\n      for (int i = 0; i < nsep; ++i)\n      {\n        vals.at(idx++) = (i / (double)nsep);\n      }\n\n      for (int i = 0; i < nsep; ++i){\n        vals.at(idx + i) = 1.;\n      }\n\n      idx += nsep;\n      for (int i = nsep - 1; i >= 0; --i)\n      {\n        vals.at(idx++) = i / (double)nsep;\n      }\n\n      std::vector<int> r;\n      r.resize(nvals);\n      std::vector<int> g;\n      g.resize(nvals);\n      std::vector<int> b;\n      b.resize(nvals);\n      for (std::size_t i = 0; i < nvals; ++i)\n      {\n        g.at(i) = ceil(nsep / 2) - 1 + i;\n        r.at(i) = g.at(i) + nsep;\n        b.at(i) = g.at(i) - nsep;\n      }\n\n      int idxr = 0;\n      int idxg = 0;\n\n      for (int i = 0; i < nvals; ++i)\n      {\n        if (r.at(i) >= 0 && r.at(i) < n)\n          ret.colors[r.at(i)].rgbRed = vals.at(idxr++) * 255.;\n\n        if (g.at(i) >= 0 && g.at(i) < n)\n          ret.colors[g.at(i)].rgbGreen = vals.at(idxg++) * 255.;\n      }\n\n      int idxb = 0;\n      int cntblue = 0;\n      for (int i = 0; i < nvals; ++i)\n      {\n        if (b.at(i) >= 0 && b.at(i) < n)\n          cntblue++;\n      }\n\n      for (int i = 0; i < nvals; ++i)\n      {\n        if (b.at(i) >= 0 && b.at(i) < n)\n          ret.colors[b.at(i)].rgbBlue = vals.at(nvals - 1 - cntblue + idxb++) * 255.;\n      }\n      break;\n  }\n  return ret;\n}\n\npalette GetPalette(const std::string &pal_choice)\n{ \n  palette ret;\n\n  int i, r, g, b;\n  float f;\n\n  if(pal_choice == \"Linear_red_palettes\")\n  {\n    /*\n      * Linear red palettes.\n      */\n    for (i = 0; i < 256; i++)\n    {\n      ret.colors[i].rgbBlue = 0;\n      ret.colors[i].rgbGreen = 0;\n      ret.colors[i].rgbRed = i;\n    }\n  }\n  else if(pal_choice == \"GammaLog_red_palettes\")\n  {\n    /*\n      * GammaLog red palettes.\n      */\n    for (i = 0; i < 256; i++)\n    {\n      f = log10(pow((i / 255.0), 1.0) * 9.0 + 1.0) * 255.0;\n      ret.colors[i].rgbBlue = 0;\n      ret.colors[i].rgbGreen = 0;\n      ret.colors[i].rgbRed = f;\n    }\n  }\n  else if(pal_choice == \"Inversion_red_palette\")\n  {\n    /*\n      * Inversion red palette.\n      */\n    for (i = 0; i < 256; i++)\n    {\n      ret.colors[i].rgbBlue = 0;\n      ret.colors[i].rgbGreen = 0;\n      ret.colors[i].rgbRed = 255 - i;\n    }\n  }\n  else if(pal_choice == \"Linear_palettes\")\n  {  \n    /*\n      * Linear palettes.\n      */\n    for (i = 0; i < 256; i++)\n    {\n      ret.colors[i].rgbBlue = ret.colors[i].rgbGreen = ret.colors[i].rgbRed = i;\n    }\n  }\n  else if(pal_choice == \"GammaLog_palettes\")\n  {\n    /*\n      * GammaLog palettes.\n      */\n    for (i = 0; i < 256; i++)\n    {\n      f = log10(pow((i / 255.0), 1.0) * 9.0 + 1.0) * 255.0;\n      ret.colors[i].rgbBlue = ret.colors[i].rgbGreen = ret.colors[i].rgbRed = f;\n    }\n  }\n  else if(pal_choice == \"Inversion_palette\")\n  {\n    /*\n      * Inversion palette.\n      */\n    for (i = 0; i < 256; i++)\n    {\n      ret.colors[i].rgbBlue = ret.colors[i].rgbGreen = ret.colors[i].rgbRed = 255 - i;\n    }\n  }\n  else if(pal_choice == \"False_color_palette1\")\n  {\n    /*\n      * False color palette #1.\n      */\n    for (i = 0; i < 256; i++)\n    {\n      r = (sin((i / 255.0 * 360.0 - 120.0 > 0 ? i / 255.0 * 360.0 - 120.0 : 0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n      g = (sin((i / 255.0 * 360.0 + 60.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n      b = (sin((i / 255.0 * 360.0 + 140.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n      ret.colors[i].rgbBlue = b;\n      ret.colors[i].rgbGreen = g;\n      ret.colors[i].rgbRed = r;\n    }\n  }\n  else if(pal_choice == \"False_color_palette2\")\n  {\n    /*\n      * False color palette #2.\n      */\n    for (i = 0; i < 256; i++)\n    {\n      r = (sin((i / 255.0 * 360.0 + 120.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n      g = (sin((i / 255.0 * 360.0 + 240.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n      b = (sin((i / 255.0 * 360.0 + 0.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n      ret.colors[i].rgbBlue = b;\n      ret.colors[i].rgbGreen = g;\n      ret.colors[i].rgbRed = r;\n    }\n  }\n  else if(pal_choice == \"False_color_palette3\")\n  {\n    /*\n      * False color palette #3.\n      */\n    for (i = 0; i < 256; i++)\n    {\n      r = (sin((i / 255.0 * 360.0 + 240.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n      g = (sin((i / 255.0 * 360.0 + 0.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n      b = (sin((i / 255.0 * 360.0 + 120.0) * DEG2RAD) * 0.5 + 0.5) * 255.0;\n      ret.colors[i].rgbBlue = b;\n      ret.colors[i].rgbGreen = g;\n      ret.colors[i].rgbRed = r;\n    }\n  }\n  else if(pal_choice == \"False_color_palette4\")\n  {\n      /*\n       * False color palette #4. Matlab JET\n       */\n\n      enum\n      {\n        nsep = 64, nvals = 192, n = 256\n      };\n\n      std::vector<double> vals;\n      vals.resize(nvals, 0);\n\n      int idx = 0;\n      for (int i = 0; i < nsep; ++i)\n      {\n        vals.at(idx++) = (i / (double)nsep);\n      }\n\n      for (int i = 0; i < nsep; ++i){\n        vals.at(idx + i) = 1.;\n      }\n\n      idx += nsep;\n      for (int i = nsep - 1; i >= 0; --i)\n      {\n        vals.at(idx++) = i / (double)nsep;\n      }\n\n      std::vector<int> r;\n      r.resize(nvals);\n      std::vector<int> g;\n      g.resize(nvals);\n      std::vector<int> b;\n      b.resize(nvals);\n      for (std::size_t i = 0; i < nvals; ++i)\n      {\n        g.at(i) = ceil(nsep / 2) - 1 + i;\n        r.at(i) = g.at(i) + nsep;\n        b.at(i) = g.at(i) - nsep;\n      }\n\n      int idxr = 0;\n      int idxg = 0;\n\n      for (int i = 0; i < nvals; ++i)\n      {\n        if (r.at(i) >= 0 && r.at(i) < n)\n          ret.colors[r.at(i)].rgbRed = vals.at(idxr++) * 255.;\n\n        if (g.at(i) >= 0 && g.at(i) < n)\n          ret.colors[g.at(i)].rgbGreen = vals.at(idxg++) * 255.;\n      }\n\n      int idxb = 0;\n      int cntblue = 0;\n      for (int i = 0; i < nvals; ++i)\n      {\n        if (b.at(i) >= 0 && b.at(i) < n)\n          cntblue++;\n      }\n\n      for (int i = 0; i < nvals; ++i)\n      {\n        if (b.at(i) >= 0 && b.at(i) < n)\n          ret.colors[b.at(i)].rgbBlue = vals.at(nvals - 1 - cntblue + idxb++) * 255.;\n      }\n  }\n  return ret;\n}\n#undef DEG2RAD\n\nvoid convertFalseColor(const cv::Mat& srcmat, cv::Mat& dstmat, const palette &pal, bool drawlegend, double mintemp, double maxtemp)\n{\n  dstmat.create(srcmat.rows, srcmat.cols, CV_8UC3);\n\n  cv::Size sz = srcmat.size();\n  const unsigned char* src = srcmat.data;\n  unsigned char* dst = dstmat.data;\n\n\n  if (srcmat.isContinuous() && dstmat.isContinuous())\n  {\n    sz.width *= sz.height;\n    sz.height = 1;\n  }\n\n  for (int i = 0; i < sz.width; ++i)\n  {\n    for (int j = 0; j < sz.height; ++j)\n    {\n      int idx = j * sz.width + i;\n      uint8_t val = src[idx];\n      dst[idx * dstmat.channels() + 0] = pal.colors[val].rgbBlue;\n      dst[idx * dstmat.channels() + 1] = pal.colors[val].rgbGreen;\n      dst[idx * dstmat.channels() + 2] = pal.colors[val].rgbRed;\n    }\n  }\n\n  //draw a legend if true Temperatures\n  if(drawlegend){\n\n    //get min max to scale the legend\n    double max_val;\n    double min_val;\n    cv::minMaxIdx(srcmat, &min_val, &max_val);\n\n    enum{\n      legenddiscretization = 5,\n      legendnumbers = 5,\n      legendwidth = 5,\n      x_0 = 20,\n      y_0 = 10,\n    };\n    double stepsize;\n\n    //    std::cout<<\"mintemp \"<<mintemp<<\" maxtemp \"<<maxtemp<<std::endl;\n\n    //draw legend color bar\n    for(int i = y_0 ; i < dstmat.rows - y_0 ; ++i){\n      int py = dstmat.rows - i;\n      int val = (i - y_0) / (double)(dstmat.rows - y_0 * 2) * 255.;\n      cv::rectangle(dstmat, cv::Point(x_0, py), cv::Point(x_0 + legendwidth, py + 1),\n                    CV_RGB(pal.colors[val].rgbRed, pal.colors[val].rgbGreen, pal.colors[val].rgbBlue ), -1);\n    }\n\n    //draw temp tick labels\n    stepsize = (dstmat.rows - y_0 * 2) / (double)legendnumbers;\n    for(int i = 0 ; i <= legendnumbers ; ++i){\n      int py = y_0 + (legendnumbers - i) * stepsize + 5; //bottom up\n      double tempval = (mintemp - 273.15) + i * (maxtemp - mintemp) / (double)legendnumbers;\n      std::stringstream ss;\n      ss<<std::setprecision(2)<<tempval<<\" C\";\n      cv::putText(dstmat, ss.str(), cv::Point(x_0 + 20, py), CV_FONT_HERSHEY_SIMPLEX, 0.4, CV_RGB(255,255,255), 1);\n    }\n\n    //draw ticks into legends\n    stepsize = (dstmat.rows - y_0 * 2) / (double)legenddiscretization;\n    for(int i = 0 ; i <= legenddiscretization ; ++i){\n      int py = y_0 + (legenddiscretization - i) * stepsize; //bottom up\n      cv::line(dstmat, cv::Point(x_0 - 2, py), cv::Point(x_0 + legendwidth + 2, py), CV_RGB(255,255,255), 1);\n    }\n  }\n\n}\n\nconverter_16_8::converter_16_8()\n{\n  min_ = std::numeric_limits<uint16_t>::max();\n  max_ = 0;\n  firstframe_ = true;\n}\n\nconverter_16_8::~converter_16_8()\n{\n  delete inst_;\n  inst_ = NULL;\n}\n\ndouble converter_16_8::getMin(){\n  return min_;\n}\ndouble converter_16_8::getMax(){\n  return max_;\n}\n// void converter_16_8::toneMapping(const cv::Mat& img16, cv::Mat& img8){\n//   if(!retina_){\n//     retina_.reset(new cv::Retina(img16.size(), false));\n//     retina_->setup(ros::package::getPath(\"brisk\") + \"/include/flir/retina_params\");\n//   }\n//   retina_->run(img16);\n//   retina_->getParvo(img8);\n// }\n\n//adjustment -3 for slightly wrong fit\ndouble powerToK4(double power){\n  double slope = 2.58357167114001779457e-07;\n  double y_0 = 2.26799217314804718626e+03;\nreturn sqrt(sqrt(((double)power - y_0) / slope)) - 3;\n}\n\n\nvoid converter_16_8::convert_to8bit(const cv::Mat& img16, cv::Mat& img8, bool doTempConversion)\n{\n  if(img8.empty()){ //make an image if the user has provided nothing\n    img8.create(cvSize(img16.cols, img16.rows), CV_8UC1);\n  }\n\n  double min = std::numeric_limits<uint16_t>::max();\n  double max = 0;\n\n  //make a histogram of intensities\n  typedef std::map<double, int> hist_t;\n  hist_t hist;\n\n  double bucketwidth = 2.; //bucketwidth in degrees K\n\n  for (int i = 0; i < img16.cols; ++i)\n  {\n    for (int j = 0; j < img16.rows; ++j)\n    {\n      double power = img16.at<uint16_t>(j, i);\n      double temp;\n      if(doTempConversion){\n        temp = powerToK4(power);\n      }else{\n        temp = power;\n      }\n      temp = round(temp / bucketwidth) * bucketwidth;\n      hist[temp]++;\n    }\n  }\n\n  //find the main section of the histogram\n  for (hist_t::const_iterator it = hist.begin(); it != hist.end(); ++it)\n  {\n    if (it->second > histminmembersperbucket)\n    {\n      if (it->first > max)\n      {\n        max = it->first;\n      }\n      if (it->first < min)\n      {\n        min = it->first;\n      }\n    }\n  }\n\n  if (firstframe_)\n  {\n    min_ = min;\n    max_ = max;\n  }\n\n  //  std::cout<<\"min: \"<<min-273.15<<\" max: \"<<max-273.15<<\" sm: min: \"<<min_-273.15<<\" max: \"<<max_-273.15<<std::endl;\n\n  //exp smoothing\n  double expsm = 0.95;\n  min_ = expsm * min_ + (1. - expsm) * min;\n  max_ = expsm * max_ + (1. - expsm) * max;\n\n  for (int i = 0; i < img16.cols; ++i)\n  {\n    for (int j = 0; j < img16.rows; ++j)\n    {\n      double temp;\n      if(doTempConversion){\n        temp = powerToK4(img16.at<uint16_t>(j, i));\n      }else{\n        temp = (double)(img16.at<uint16_t>(j, i));\n      }\n\n      int val = (((temp - min_) / (max_ - min_)) * 255);\n\n      val = val > std::numeric_limits<uint8_t>::max() ? std::numeric_limits<uint8_t>::max() : val < 0 ? 0 : val; //saturate\n      img8.at<uint8_t>(j, i) = (uint8_t)val;\n    }\n  }\n\n  firstframe_ = false;\n}\n\nconverter_16_8* converter_16_8::inst_ = NULL;\n", "meta": {"hexsha": "cb0407ee04f25ebc1816b451f80be53e32b62211", "size": 14866, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ir_convert/src/utils.cpp", "max_stars_repo_name": "GCaptainNemo/FLIR-thermal-camera-ROS", "max_stars_repo_head_hexsha": "1cf10cb608559456a9f7e7402f4337ef2ef87853", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ir_convert/src/utils.cpp", "max_issues_repo_name": "GCaptainNemo/FLIR-thermal-camera-ROS", "max_issues_repo_head_hexsha": "1cf10cb608559456a9f7e7402f4337ef2ef87853", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ir_convert/src/utils.cpp", "max_forks_repo_name": "GCaptainNemo/FLIR-thermal-camera-ROS", "max_forks_repo_head_hexsha": "1cf10cb608559456a9f7e7402f4337ef2ef87853", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4554794521, "max_line_length": 131, "alphanum_fraction": 0.4993945917, "num_tokens": 5296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.44585889638929754}}
{"text": "//=======================================================================\n// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file lp_row_generation.hpp\n * @brief\n * @author Piotr Godlewski, Robert Rosołek\n * @version 1.0\n * @date 2013-06-04\n */\n#ifndef PAAL_LP_ROW_GENERATION_HPP\n#define PAAL_LP_ROW_GENERATION_HPP\n\n#include \"paal/lp/lp_base.hpp\"\n#include \"paal/lp/problem_type.hpp\"\n#include \"paal/utils/rotate.hpp\"\n\n#include <boost/range/counting_range.hpp>\n\nnamespace paal {\nnamespace lp {\n\n/**\n * Finds an extreme point solution to the LP using row generation:\n * solves the initial LP and then ask the separation oracle if the found\n * solution is a feasible solution to the complete problem. If not,\n * adds a new row (generated by the oracle) to the LP and re-optimizes it.\n * This procedure is iterated until a feasible solution to the full LP\n * is found.\n */\ntemplate <class TryAddViolated, class SolveLp>\n    problem_type row_generation(TryAddViolated try_add_violated, SolveLp solve_lp)\n    {\n        problem_type res;\n        do res = solve_lp(); while (res == OPTIMAL && try_add_violated());\n        return res;\n    }\n\n/**\n * @brief functor for adding maximum violated constraint\n *\n * @tparam GetCandidates\n * @tparam HowViolated\n * @tparam AddViolated\n * @tparam CompareHow\n */\ntemplate<\n    class GetCandidates,\n    class HowViolated,\n    class AddViolated,\n    class CompareHow\n>\nclass add_max_violated {\n   GetCandidates m_get_candidates;\n   HowViolated m_how_violated;\n   AddViolated m_add_violated;\n   CompareHow m_cmp;\n\n   public:\n      ///contructor\n      add_max_violated(GetCandidates get_candidates,\n            HowViolated how_violated, AddViolated add_violated, CompareHow cmp)\n         : m_get_candidates(get_candidates), m_how_violated(how_violated),\n            m_add_violated(add_violated), m_cmp(cmp) {}\n\n      ///operator()\n      bool operator()() {\n         auto&& cands = m_get_candidates();\n         using how_violated_t = puretype(m_how_violated(*std::begin(cands)));\n         using cand_it_t = puretype(std::begin(cands));\n         boost::optional<std::pair<how_violated_t, cand_it_t>> most;\n         for (auto cand : boost::counting_range(cands)) {\n            auto const how = m_how_violated(*cand);\n            if (!how) continue;\n            if (!most || m_cmp(most->first, how))\n               most = std::make_pair(std::move(how), cand);\n         }\n         if (!most) return false;\n         m_add_violated(*most->second);\n         return true;\n      }\n};\n\n///functor computing add_max_violated\nstruct max_violated_separation_oracle {\n   template <\n      class GetCandidates,\n      class HowViolated,\n      class AddViolated,\n      class CompareHow = utils::less\n   >\n   ///operator()\n   auto operator()(\n      GetCandidates get_candidates,\n      HowViolated is_violated,\n      AddViolated add_violated,\n      CompareHow compare_how = CompareHow{}\n   ) const {\n      return add_max_violated<GetCandidates, HowViolated, AddViolated,\n         CompareHow>(get_candidates, is_violated, add_violated, compare_how);\n   }\n};\n\n///functor\ntemplate <class GetCandidates,\n          class HowViolated,\n          class AddViolated,\n          class ReorderCandidates>\nclass add_first_violated {\n   GetCandidates m_get_candidates;\n   HowViolated m_how_violated;\n   AddViolated m_add_violated;\n   ReorderCandidates m_reorder_candidates;\n\n   public:\n      ///constructor\n      add_first_violated(\n         GetCandidates get_candidates,\n         HowViolated how_violated,\n         AddViolated add_violated,\n         ReorderCandidates reorder_candidates\n      ) : m_get_candidates(get_candidates),\n         m_how_violated(how_violated),\n         m_add_violated(add_violated),\n         m_reorder_candidates(std::move(reorder_candidates)) {}\n\n      ///operator()\n      bool operator()() {\n         auto&& cands = m_get_candidates();\n         auto reordered =\n            m_reorder_candidates(std::forward<decltype(cands)>(cands));\n         for (auto c : boost::counting_range(reordered)) {\n            if (m_how_violated(*c)) {\n                m_add_violated(*c);\n                return true;\n            }\n         }\n         return false;\n      }\n};\n\n///functor computing add_first_violated\nstruct first_violated_separation_oracle {\n   template <\n      class GetCandidates,\n      class HowViolated,\n      class AddViolated,\n      class ReorderCandidates = utils::identity_functor\n   >\n   ///operator()\n   auto operator() (\n      GetCandidates get_candidates,\n      HowViolated how_violated,\n      AddViolated add_violated,\n      ReorderCandidates reorder_candidates = ReorderCandidates{}\n   ) const {\n      return add_first_violated<GetCandidates, HowViolated, AddViolated,\n         ReorderCandidates>(get_candidates, how_violated, add_violated,\n            reorder_candidates);\n   }\n};\n\nnamespace detail {\ntemplate <class URNG>\nclass random_rotate {\n   URNG m_g;\n   public:\n      random_rotate(URNG&& g)\n         : m_g(std::forward<URNG>(g)) {}\n      template <class ForwardRange>\n      auto operator()(const ForwardRange& rng)\n      {\n         auto const len = boost::distance(rng);\n         std::uniform_int_distribution<decltype(len)> d(0, len);\n         return utils::rotate(rng, d(m_g));\n      }\n};\n\ntemplate <class URNG = std::default_random_engine>\nauto make_random_rotate(URNG&& g = URNG{})\n{\n   return random_rotate<URNG>(std::forward<URNG>(g));\n}\n} //! detail\n\n///functor returning add_first_violated\n///Separation oracle for the row generation,\n///using the random violated strategy.\nstruct random_violated_separation_oracle {\n   template <\n      class GetCandidates,\n      class HowViolated,\n      class AddViolated,\n      class URNG = std::default_random_engine\n   >\n   ///operator()\n   auto operator() (\n      GetCandidates get_candidates,\n      HowViolated how_violated,\n      AddViolated add_violated,\n      URNG&& g = URNG{}\n   ) const {\n      return first_violated_separation_oracle{}(get_candidates,\n            how_violated, add_violated, detail::make_random_rotate(std::forward<URNG>(g)));\n   }\n};\n\n\n} // lp\n} // paal\n\n#endif // PAAL_LP_ROW_GENERATION_HPP\n", "meta": {"hexsha": "b5c3aa371d02c5f2288a5349b6c38f1e56072328", "size": 6310, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/lp/lp_row_generation.hpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/paal/lp/lp_row_generation.hpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/paal/lp/lp_row_generation.hpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 29.0783410138, "max_line_length": 91, "alphanum_fraction": 0.6549920761, "num_tokens": 1540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4458588963892975}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_CONSTANTS_DEGINRAD_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_DEGINRAD_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\n\nnamespace nt2\n{\n  namespace tag\n  {\n   /*!\n     @brief Deginrad generic tag\n\n     Represents the Deginrad constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    BOOST_SIMD_CONSTANT_REGISTER( Deginrad, double\n                                , 0, 0x3c8efa35\n                                , 0x3f91df46a2529d39ll\n                                )\n  }\n  namespace ext\n  {\n   template<class Site, class... Ts>\n   BOOST_FORCEINLINE generic_dispatcher<tag::Deginrad, Site> dispatching_Deginrad(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n   {\n     return generic_dispatcher<tag::Deginrad, Site>();\n   }\n   template<class... Args>\n   struct impl_Deginrad;\n  }\n  /*!\n    Constant radian in Degree multiplier, \\f$\\frac{180}\\pi\\f$.\n\n    @par Semantic:\n\n    For type T0:\n\n    @code\n    T0 r = Deginrad<T0>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T0 r = _180<T0>()/Pi<T0>() ;\n    @endcode\n\n    @see  @funcref{inrad}, @funcref{indeg}, @funcref{Radindeg}, @funcref{Radindegr}\n    @return a value of type T0\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::Deginrad, Deginrad);\n\n}\n\n#endif\n\n", "meta": {"hexsha": "e1866f3dc33e34e869a7024f331736887dbfb94e", "size": 1905, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/deginrad.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/deginrad.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/deginrad.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6086956522, "max_line_length": 172, "alphanum_fraction": 0.5795275591, "num_tokens": 496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.44585586457068127}}
{"text": "/*\n * Copyright (c) 2013-2018 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef AUTODIF_HPP\n#define AUTODIF_HPP\n\n// Automatic Differentiation by bottom up algorithm\n\n#include <iostream>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <cmath>\n\n#include <kv/convert.hpp>\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T> class autodif;\ntemplate <class C, class T> struct convertible<C, autodif<T> > {\n\tstatic const bool value = convertible<C, T>::value || boost::is_same<C, autodif<T> >::value;\n};\ntemplate <class C, class T> struct acceptable_n<C, autodif<T> > {\n\tstatic const bool value = convertible<C, T>::value;\n};\n\n\ntemplate <class T> class autodif {\n\tpublic:\n\tT v;\n\tub::vector<T> d;\n\n\ttypedef T base_type;\n\n\tautodif() {\n\t\tv = 0.;\n\t\td.resize(0);\n\t}\n\n\ttemplate <class C> explicit autodif(const C& x, typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value >::type* =0) {\n\t\tv = x;\n\t\td.resize(0);\n\t}\n\n\ttemplate <class C> typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif& >::type operator=(const C& x) {\n\t\tv = x;\n\t\td.resize(0);\n\t\treturn *this;\n\t}\n\n\tfriend autodif operator+(const autodif& a, const autodif& b) {\n\t\tautodif r;\n\n\t\tr.v = a.v + b.v;\n\n\t\tif (a.d.size() == 0) {\n\t\t\tr.d = b.d;\n\t\t} else if (b.d.size() == 0) {\n\t\t\tr.d = a.d;\n\t\t} else {\n\t\t\tr.d = a.d + b.d;\n\t\t}\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif >::type operator+(const autodif& a, const C& b) {\n\t\tautodif r;\n\n\t\tr.v = a.v + b;\n\t\tr.d = a.d;\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif >::type operator+(const C& a, const autodif& b) {\n\t\tautodif r;\n\n\t\tr.v = a + b.v;\n\t\tr.d = b.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif& operator+=(autodif& a, const autodif& b) {\n\t\ta = a + b;\n\t\treturn a;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif& >::type operator+=(autodif& a, const C& b) {\n\t\ta.v += b;\n\t\treturn a;\n\t}\n\n\tfriend autodif operator-(const autodif& a, const autodif& b) {\n\t\tautodif r;\n\n\t\tr.v = a.v - b.v;\n\n\t\tif (a.d.size() == 0) {\n\t\t\tr.d = - b.d;\n\t\t} else if (b.d.size() == 0) {\n\t\t\tr.d = a.d;\n\t\t} else {\n\t\t\tr.d = a.d - b.d;\n\t\t}\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif >::type operator-(const autodif& a, const C& b) {\n\t\tautodif r;\n\n\t\tr.v = a.v - b;\n\t\tr.d = a.d;\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif >::type operator-(const C& a, const autodif& b) {\n\t\tautodif r;\n\n\t\tr.v = a - b.v;\n\t\tr.d = - b.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif& operator-=(autodif& a, const autodif& b) {\n\t\ta = a - b;\n\t\treturn a;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif& >::type operator-=(autodif& a, const C& b) {\n\t\ta.v -= b;\n\t\treturn a;\n\t}\n\n\tfriend autodif operator-(const autodif& a) {\n\t\tautodif r;\n\n\t\tr.v = - a.v;\n\t\tr.d = - a.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif operator*(const autodif& a, const autodif& b) {\n\t\tautodif r;\n\n\t\tr.v = a.v * b.v;\n\n\t\tif (a.d.size() == 0) {\n\t\t\tr.d = a.v * b.d;\n\t\t} else if (b.d.size() == 0) {\n\t\t\tr.d = b.v * a.d;\n\t\t} else {\n\t\t\tr.d = b.v * a.d + a.v * b.d;\n\t\t}\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif >::type operator*(const autodif& a, const C& b) {\n\t\tautodif r;\n\n\t\tr.v = a.v * b;\n\t\t// r.d = b * a.d;\n\t\tr.d = T(b) * a.d; // assist for VC++\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif >::type operator*(const C& a, const autodif& b) {\n\t\tautodif r;\n\n\t\tr.v = a * b.v;\n\t\t// r.d = a * b.d;\n\t\tr.d = T(a) * b.d; // assist for VC++\n\n\t\treturn r;\n\t}\n\n\tfriend autodif& operator*=(autodif& a, const autodif& b) {\n\t\ta = a * b;\n\t\treturn a;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif& >::type operator*=(autodif& a, const C& b) {\n\t\ta.v *= b;\n\t\t// a.d *= b;\n\t\ta.d *= T(b); // assist for VC++\n\t\treturn a;\n\t}\n\n\tfriend autodif operator/(const autodif& a, const autodif& b) {\n\t\tautodif r;\n\n\t\tr.v = a.v / b.v;\n\n\t\tif (a.d.size() == 0) {\n\t\t\tr.d = b.d * (-a.v/(b.v*b.v));\n\t\t} else if (b.d.size() == 0) {\n\t\t\tr.d = a.d / b.v;\n\t\t} else {\n\t\t\tr.d = a.d / b.v + b.d * (-a.v/(b.v*b.v));\n\t\t}\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif >::type operator/(const autodif& a, const C& b) {\n\t\tautodif r;\n\n\t\tr.v = a.v / b;\n\t\t// r.d = a.d / b;\n\t\tr.d = a.d / T(b); // assist for VC++\n\n\t\treturn r;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif >::type operator/(const C& a, const autodif& b) {\n\t\tautodif r;\n\n\t\tr.v = a / b.v;\n\t\tr.d = b.d * (-a/(b.v*b.v));\n\n\t\treturn r;\n\t}\n\n\tfriend autodif& operator/=(autodif& a, const autodif& b) {\n\t\ta = a / b;\n\t\treturn a;\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif& >::type operator/=(autodif& a, const C& b) {\n\t\ta.v /= b;\n\t\t// a.d /= b;\n\t\ta.d /= T(b); // assist for VC++\n\t\treturn a;\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream& s, const autodif& x) {\n\t\tint i;\n\t\tint n = x.d.size();\n\t\ts << x.v;\n\t\ts << '<';\n\t\tfor (i=0; i<n; i++) {\n\t\t\ts << x.d(i);\n\t\t\tif (i != n-1) {\n\t\t\t\ts << ',';\n\t\t\t}\n\t\t}\n\t\ts << '>';\n\t\treturn s;\n\t}\n\n\tfriend autodif pow(const autodif& x, int y) {\n\t\tautodif r;\n\n\t\tusing std::pow;\n\t\tr.v = pow(x.v, y);\n\t\tif (y == 0) {\n\t\t\tr.d = T(0.) * x.d;\n\t\t} else {\n\t\t\tr.d = (y * pow(x.v, y - 1)) * x.d;\n\t\t}\n\t\treturn r;\n\t}\n\n\tfriend autodif pow(const autodif& x, const autodif& y) {\n\t\treturn exp(y * log(x));\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value && ! boost::is_integral<C>::value, autodif >::type pow(const autodif& a, const C& b) {\n\t\treturn pow(a, autodif(b));\n\t}\n\n\ttemplate <class C> friend typename boost::enable_if_c< kv::acceptable_n<C, autodif>::value, autodif >::type pow(const C& a, const autodif& b) {\n\t\treturn pow(autodif(a), b);\n\t}\n\n\tfriend autodif exp (const autodif& x) {\n\t\tautodif r;\n\n\t\tusing std::exp;\n\t\tr.v = exp(x.v);\n\t\t// r.d = exp(x.v) * x.d;\n\t\tr.d = r.v * x.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif log (const autodif& x) {\n\t\tautodif r;\n\n\t\tusing std::log;\n\t\tr.v = log(x.v);\n\t\tr.d = x.d / x.v;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif sqrt (const autodif& x) {\n\t\tautodif r;\n\n\t\tusing std::sqrt;\n\t\tr.v = sqrt(x.v);\n\t\t// r.d = 1./(2. * sqrt(x.v)) * x.d;\n\t\tr.d = x.d / (2. * r.v);\n\n\t\treturn r;\n\t}\n\n\tfriend autodif sin (const autodif& x) {\n\t\tautodif r;\n\n\t\tusing std::sin;\n\t\tusing std::cos;\n\t\tr.v = sin(x.v);\n\t\tr.d = cos(x.v) * x.d;\n\n\t\treturn r;\n\t}\n\n\n\tfriend autodif cos (const autodif& x) {\n\t\tautodif r;\n\n\t\tusing std::sin;\n\t\tusing std::cos;\n\t\tr.v = cos(x.v);\n\t\tr.d = -sin(x.v) * x.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif tan (const autodif& x) {\n\t\tautodif r;\n\t\tT tmp;\n\n\t\tusing std::tan;\n\t\tusing std::cos;\n\t\tr.v = tan(x.v);\n\t\ttmp = cos(x.v);\n\t\ttmp = 1. / (tmp * tmp);\n\t\tr.d = tmp * x.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif asin (const autodif& x) {\n\t\tautodif r, tmp;\n\n\t\tusing std::asin;\n\t\tusing std::sqrt;\n\t\tr.v = asin(x.v);\n\t\tr.d = (1. / sqrt(1. - x.v * x.v)) * x.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif acos (const autodif& x) {\n\t\tautodif r;\n\n\t\tusing std::acos;\n\t\tusing std::sqrt;\n\t\tr.v = acos(x.v);\n\t\tr.d = (-1. / sqrt(1. - x.v * x.v)) * x.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif atan (const autodif& x) {\n\t\tautodif r;\n\n\t\tusing std::atan;\n\t\tr.v = atan(x.v);\n\t\tr.d = (1. / (1. + x.v * x.v)) * x.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif sinh (const autodif& x) {\n\t\tautodif r;\n\n\t\tusing std::sinh;\n\t\tusing std::cosh;\n\t\tr.v = sinh(x.v);\n\t\tr.d = cosh(x.v) * x.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif cosh (const autodif& x) {\n\t\tautodif r;\n\n\t\tusing std::sinh;\n\t\tusing std::cosh;\n\t\tr.v = cosh(x.v);\n\t\tr.d = sinh(x.v) * x.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif tanh (const autodif& x) {\n\t\tautodif r;\n\t\tT tmp;\n\n\t\tusing std::tanh;\n\t\tusing std::cosh;\n\t\tr.v = tanh(x.v);\n\t\ttmp = cosh(x.v);\n\t\ttmp = 1. / (tmp * tmp);\n\t\tr.d = tmp * x.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif asinh (const autodif& x) {\n\t\tautodif r, tmp;\n\n\t\t// using std::asinh;\n\t\tusing std::sqrt;\n\t\tr.v = asinh(x.v);\n\t\tr.d = (1. / sqrt(x.v * x.v + 1.)) * x.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif acosh (const autodif& x) {\n\t\tautodif r;\n\n\t\t// using std::acosh;\n\t\tusing std::sqrt;\n\t\tr.v = acosh(x.v);\n\t\tr.d = (1. / sqrt(x.v * x.v - 1.)) * x.d;\n\n\t\treturn r;\n\t}\n\n\tfriend autodif atanh (const autodif& x) {\n\t\tautodif r;\n\n\t\t// using std::atanh;\n\t\tr.v = atanh(x.v);\n\t\tr.d = (1. / (1. - x.v * x.v)) * x.d;\n\n\t\treturn r;\n\t}\n\n\t// n-dimensional version\n\tstatic ub::vector<autodif> init (const ub::vector<T>& in) {\n\t\tint i, j;\n\t\tint n = in.size();\n\t\tub::vector<autodif> out(n);\n\n\t\tfor (i=0; i<n; i++) {\n\t\t\tout(i).v = in(i);\n\t\t\tout(i).d.resize(n);\n\t\t\tfor (j=0; j<n; j++) {\n\t\t\t\tout(i).d(j) = (i==j) ? 1. : 0.;\n\t\t\t}\n\t\t}\n\n\t\treturn out;\n\t}\n\n\t// 1-dimensional version\n\tstatic autodif init (const T& in) {\n\t\tint j;\n\t\tautodif out;\n\n\t\tout.v = in;\n\t\tout.d.resize(1);\n\t\tout.d(0) = 1.;\n\n\t\treturn out;\n\t}\n\n\t// for functions R^n -> R^m\n\tstatic void split (const ub::vector<autodif>& in, ub::vector<T>& v, ub::matrix<T>& d) {\n\t\tint i, j, n, tmp;\n\t\tint m = in.size();\n\n\t\tif (in.size() == 0) return;\n\t\tn = in(0).d.size();\n\t\tfor (i=1; i<m; i++) {\n\t\t\ttmp = in(i).d.size();\n\t\t\tif (tmp > n) n = tmp;\n\t\t}\n\n\t\tv.resize(m);\n\t\td.resize(m, n);\n\t\tfor (i=0; i<m; i++) {\n\t\t\tv(i) = in(i).v;\n\t\t\ttmp = in(i).d.size();\n\t\t\tfor (j=0; j<tmp; j++) {\n\t\t\t\td(i, j) = in(i).d(j);\n\t\t\t}\n\t\t\tfor (j=tmp; j<n; j++) {\n\t\t\t\td(i, j) = 0.;\n\t\t\t}\n\t\t}\n\t}\n\n\t// for functions R^n -> R\n\tstatic void split (const autodif& in, T& v, ub::vector<T>& d) {\n\t\tint j, n;\n\n\t\tn = in.d.size();\n\t\td.resize(n);\n\n\t\tv = in.v;\n\t\tfor (j=0; j<n; j++) {\n\t\t\td(j) = in.d(j);\n\t\t}\n\t}\n\n\t// for functions R -> R^m\n\tstatic void split (const ub::vector<autodif>& in, ub::vector<T>& v, ub::vector<T>& d) {\n\t\tint i;\n\t\tint m = in.size();\n\n\t\tif (in.size() == 0) return;\n\n\t\tv.resize(m);\n\t\td.resize(m);\n\t\tfor (i=0; i<m; i++) {\n\t\t\tv(i) = in(i).v;\n\t\t\td(i) = in(i).d(0);\n\t\t}\n\t}\n\n\t// for functions R -> R\n\tstatic void split (const autodif& in, T& v, T& d) {\n\t\tv = in.v;\n\t\td = in.d(0);\n\t}\n\n\tstatic ub::vector<autodif>\n\tcompress (const ub::vector<autodif>& in, ub::matrix<T>& save) {\n\t\tub::vector<autodif> out;\n\t\tint i, j, m, tmp;\n\t\tint n = in.size();\n\n\t\tout.resize(n);\n\n\t\tm = in(0).d.size();\n\t\tfor (i=1; i<n; i++) {\n\t\t\ttmp = in(i).d.size();\n\t\t\tif (tmp > m) m = tmp;\n\t\t}\n\n\t\tsave.resize(n, m);\n\n\t\tfor (i=0; i<n; i++) {\n\t\t\tout(i).v = in(i).v;\n\t\t\ttmp = in(i).d.size();\n\t\t\tfor (j=0; j<tmp; j++) {\n\t\t\t\tsave(i, j) = in(i).d(j);\n\t\t\t}\n\t\t\tfor (j=tmp; j<m; j++) {\n\t\t\t\tsave(i, j) = 0.;\n\t\t\t}\n\t\t\tout(i).d.resize(n);\n\t\t\tfor (j=0; j<n; j++) {\n\t\t\t\tout(i).d(j) = (i==j) ? 1 : 0;\n\t\t\t}\n\t\t}\n\n\t\treturn out;\n\t}\n\n\tstatic autodif\n\texpand (const autodif& in, const ub::matrix<T>& save) {\n\t\tautodif out;\n\n\t\tout.v = in.v;\n\t\tout.d = prod(in.d, save);\n\n\t\treturn out;\n\t}\n\n\tstatic ub::vector<autodif>\n\texpand (const ub::vector<autodif>& in, const ub::matrix<T>& save) {\n\t\tub::vector<autodif> out;\n\t\tint i;\n\t\tint s = in.size();\n\n\t\tout.resize(s);\n\n\t\tfor (i=0; i<s; i++) {\n\t\t\tout(i) = expand(in(i), save);\n\t\t}\n\n\t\treturn out;\n\t}\n};\n\n} // namespace kv\n\n#endif //AUTODIF_HPP\n", "meta": {"hexsha": "bbb6addfa9b5b41caa50366817a2de68aa0054f4", "size": 11345, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/autodif.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "src/interval/kv/autodif.hpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "src/interval/kv/autodif.hpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 18.6288998358, "max_line_length": 178, "alphanum_fraction": 0.5512560599, "num_tokens": 4353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.6959583313396338, "lm_q1q2_score": 0.4458558605307153}}
{"text": "#ifndef N_BODY_DATA_HPP\n#define N_BODY_DATA_HPP\n\n#include <array>\n#include <boost/serialization/access.hpp>\n#include <boost/serialization/array.hpp>\n#include <boost/serialization/nvp.hpp>\n#include <boost/serialization/vector.hpp>\n#include <cmath>\n#include <cstddef>\n#include <memory>\n#include <tuple>\n#include <vector>\n\nnamespace n_body::data {\n\ntemplate <typename T, std::size_t Dimension>\nusing Vector = std::array<T, Dimension>;\n\ntemplate <typename T> using Scalar = T;\n\ntemplate <typename T, std::size_t Dimension> struct Body {\n  using vector_type = Vector<T, Dimension>;\n  using scalar_type = Scalar<T>;\n\n  vector_type position;\n  vector_type velocity;\n  scalar_type mass;\n\nprivate:\n  /* serialization */\n  friend class boost::serialization::access;\n  template <typename Archive>\n  void serialize(Archive &ar, const unsigned int /* version */) {\n    ar &BOOST_SERIALIZATION_NVP(position);\n    ar &BOOST_SERIALIZATION_NVP(velocity);\n    ar &BOOST_SERIALIZATION_NVP(mass);\n  }\n};\n\ntemplate <typename T, std::size_t Dimension>\nusing Bodies = std::vector<Body<T, Dimension>>;\n\ntemplate <typename T, std::size_t Dimension> struct Space {\n  using vector_type = Vector<T, Dimension>;\n\n  vector_type min;\n  vector_type max;\n  vector_type center;\n\nprivate:\n  /* serialization */\n  friend class boost::serialization::access;\n  template <typename Archive>\n  void serialize(Archive &ar, const unsigned int /* version */) {\n    ar &BOOST_SERIALIZATION_NVP(min);\n    ar &BOOST_SERIALIZATION_NVP(max);\n    ar &BOOST_SERIALIZATION_NVP(center);\n  }\n};\n\ntemplate <typename T, std::size_t Dimension>\nVector<T, Dimension> operator+(const Vector<T, Dimension> &v1,\n                               const Vector<T, Dimension> &v2) {\n  Vector<T, Dimension> result;\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    result[d] = v1[d] + v2[d];\n  }\n  return result;\n}\n\ntemplate <typename T, std::size_t Dimension>\nVector<T, Dimension> &operator+=(Vector<T, Dimension> &v1,\n                                 const Vector<T, Dimension> &v2) {\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    v1[d] += v2[d];\n  }\n  return v1;\n}\n\ntemplate <typename T, std::size_t Dimension>\nVector<T, Dimension> operator-(const Vector<T, Dimension> &v1,\n                               const Vector<T, Dimension> &v2) {\n  Vector<T, Dimension> result;\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    result[d] = v1[d] - v2[d];\n  }\n  return result;\n}\n\ntemplate <typename T, std::size_t Dimension>\nVector<T, Dimension> operator-(const Vector<T, Dimension> &v) {\n  Vector<T, Dimension> result;\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    result[d] = -v[d];\n  }\n  return result;\n}\n\ntemplate <typename T, std::size_t Dimension>\nScalar<T> module_of(const Vector<T, Dimension> &v) {\n  T sum = 0;\n  for (auto x : v) {\n    sum += x * x;\n  }\n  return std::sqrt(sum);\n}\n\ntemplate <typename T, std::size_t Dimension>\nVector<T, Dimension> &operator-=(Vector<T, Dimension> &v1,\n                                 const Vector<T, Dimension> &v2) {\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    v1[d] -= v2[d];\n  }\n  return v1;\n}\n\ntemplate <typename T, std::size_t Dimension>\nVector<T, Dimension> operator*(const Scalar<T> &s,\n                               const Vector<T, Dimension> &v) {\n  Vector<T, Dimension> result{};\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    result[d] = v[d] * s;\n  }\n  return result;\n}\n\ntemplate <typename T, std::size_t Dimension>\nVector<T, Dimension> operator*(const Vector<T, Dimension> &v,\n                               const Scalar<T> &s) {\n  return s * v;\n}\n\ntemplate <typename T, std::size_t Dimension>\nVector<T, Dimension> &operator*=(Vector<T, Dimension> &v, const Scalar<T> &s) {\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    v[d] *= s;\n  }\n  return v;\n}\n\ntemplate <typename T, std::size_t Dimension>\nVector<T, Dimension> operator/(const Vector<T, Dimension> &v,\n                               const Scalar<T> &s) {\n  Vector<T, Dimension> result;\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    result[d] = v[d] / s;\n  }\n  return result;\n}\n\ntemplate <typename T, std::size_t Dimension>\nVector<T, Dimension> &operator/=(Vector<T, Dimension> &v, const Scalar<T> &s) {\n  for (std::size_t d = 0; d < Dimension; ++d) {\n    v[d] /= s;\n  }\n  return v;\n}\n\ntemplate <typename T, std::size_t Dimension>\nstd::tuple<Vector<T, Dimension>, Scalar<T>> average_position_by_mass(\n    const Vector<T, Dimension> &position1, const Scalar<T> &mass1,\n    const Vector<T, Dimension> &position2, const Scalar<T> &mass2) {\n  auto sum = mass1 * position1 + mass2 * position2;\n  auto sum_mass = mass1 + mass2;\n  return {\n      sum / sum_mass,\n      sum_mass,\n  };\n}\n\ntemplate <typename T, std::size_t Dimension>\nvoid average_position_by_mass_in_place(Vector<T, Dimension> &position1,\n                                       Scalar<T> &mass1,\n                                       const Vector<T, Dimension> &position2,\n                                       const Scalar<T> &mass2) {\n  position1 *= mass1;\n  position1 += position2 * mass2;\n  mass1 += mass2;\n  position1 /= mass1;\n}\n\n} // namespace n_body::data\n\n#endif\n", "meta": {"hexsha": "da761549873666e70cb1bd7d3cb7fbfdd1296e50", "size": 5109, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/data.hpp", "max_stars_repo_name": "linyinfeng/n-body", "max_stars_repo_head_hexsha": "e40c859689d76a3f36cd08e072d7ee24685e8be4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-28T15:13:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T15:13:06.000Z", "max_issues_repo_path": "src/data.hpp", "max_issues_repo_name": "linyinfeng/n-body", "max_issues_repo_head_hexsha": "e40c859689d76a3f36cd08e072d7ee24685e8be4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/data.hpp", "max_forks_repo_name": "linyinfeng/n-body", "max_forks_repo_head_hexsha": "e40c859689d76a3f36cd08e072d7ee24685e8be4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-10T14:01:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-10T14:01:55.000Z", "avg_line_length": 27.4677419355, "max_line_length": 79, "alphanum_fraction": 0.6277157957, "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.4458558564907495}}
{"text": "/******************************************************************************\nCopyright (c) 2021, Farbod Farshidian. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n******************************************************************************/\n\n#include \"ocs2_core/loopshaping/LoopshapingPropertyTree.h\"\n\n#include <boost/property_tree/info_parser.hpp>\n#include \"ocs2_core/misc/LoadData.h\"\n\nnamespace ocs2 {\nnamespace loopshaping_property_tree {\nFilter readSISOFilter(const boost::property_tree::ptree& pt, std::string filterName, bool invert) {\n  // Get Sizes\n  const auto numRepeats = pt.get<size_t>(filterName + \".numRepeats\", 1);\n  const auto numPoles = pt.get<size_t>(filterName + \".numPoles\", 0);\n  const auto numZeros = pt.get<size_t>(filterName + \".numZeros\", 0);\n  const auto scaling = pt.get<scalar_t>(filterName + \".scaling\", 1.0);\n  const size_t numStates = invert ? numZeros : numPoles;\n  const size_t numInputs = 1;\n\n  // Setup Filter, convention a0*s^n + a1*s^(n-1) + ... + an\n  vector_t numerator(numZeros + 1);\n  numerator.setZero();\n  numerator(0) = 1.0;\n  for (size_t z = 0; z < numZeros; z++) {\n    auto zero = pt.get<scalar_t>(filterName + \".zeros.\" + \"(\" + std::to_string(z) + \")\");\n    numerator.segment(1, z + 1) -= zero * numerator.segment(0, z + 1).eval();\n  }\n  numerator *= scaling;  // Apply scale to numerator\n\n  vector_t denominator(numPoles + 1);\n  denominator.setZero();\n  denominator(0) = 1.0;\n  for (size_t p = 0; p < numPoles; p++) {\n    auto pole = pt.get<scalar_t>(filterName + \".poles.\" + \"(\" + std::to_string(p) + \")\");\n    denominator.segment(1, p + 1) -= pole * denominator.segment(0, p + 1).eval();\n  }\n\n  // Print frequency domain information\n  std::cerr << \"Read filter \" << filterName << (invert ? \" (before inversion)\" : \"\") << \", convention: a0*s^n + a1*s^(n-1) + ... + an \\n\";\n  std::cerr << \"\\tnumerator: [\" << numerator.transpose() << \"]\\n\";\n  std::cerr << \"\\tdenominator: [\" << denominator.transpose() << \"]\\n\";\n  std::cerr << \"\\tDC gain: \" << numerator(numZeros) / denominator(numPoles) << \"\\n\";\n  std::cerr << \"\\tInf gain: \";\n  if (numZeros > numPoles) {\n    std::cerr << \"Inf\\n\";\n  }\n  if (numZeros < numPoles) {\n    std::cerr << 0.0 << \"\\n\";\n  }\n  if (numZeros == numPoles) {\n    std::cerr << numerator(0) / denominator(0) << \"\\n\";\n  }\n\n  if (invert) {\n    vector_t temp;\n    temp = numerator;\n    numerator = denominator;\n    denominator = temp;\n  }\n\n  // Convert to state space\n  matrix_t a, b, c, d;\n  ocs2::tf2ss(numerator, denominator, a, b, c, d);\n\n  matrix_t A = matrix_t::Zero(numRepeats * numStates, numRepeats * numStates);\n  matrix_t B = matrix_t::Zero(numRepeats * numStates, numRepeats * numInputs);\n  matrix_t C = matrix_t::Zero(numRepeats * numInputs, numRepeats * numStates);\n  matrix_t D = matrix_t::Zero(numRepeats * numInputs, numRepeats * numInputs);\n  for (size_t r = 0; r < numRepeats; r++) {\n    A.block(r * numStates, r * numStates, numStates, numStates) = a;\n    B.block(r * numStates, r * numInputs, numStates, numInputs) = b;\n    C.block(r * numInputs, r * numStates, numInputs, numStates) = c;\n    D.block(r * numInputs, r * numInputs, numInputs, numInputs) = d;\n  }\n\n  return Filter(A, B, C, D);\n}\n\nFilter readMIMOFilter(const boost::property_tree::ptree& pt, std::string filterName, bool invert) {\n  const auto numFilters = pt.get<size_t>(filterName + \".numFilters\", 0);\n  if (numFilters > 0) {\n    // Read the sisoFilters\n    std::vector<Filter> sisoFilters;\n    size_t numStates(0), numInputs(0), numOutputs(0);\n    for (size_t i = 0; i < numFilters; ++i) {\n      // Read filter\n      std::string sisoFilterName = filterName + \".Filter\" + std::to_string(i);\n      sisoFilters.emplace_back(readSISOFilter(pt, sisoFilterName, invert));\n\n      // Track sizes\n      numStates += sisoFilters.back().getNumStates();\n      numInputs += sisoFilters.back().getNumInputs();\n      numOutputs += sisoFilters.back().getNumOutputs();\n    }\n\n    // Concatenate siso matrices into one MIMO filter\n    matrix_t A = matrix_t::Zero(numStates, numStates);\n    matrix_t B = matrix_t::Zero(numStates, numInputs);\n    matrix_t C = matrix_t::Zero(numOutputs, numStates);\n    matrix_t D = matrix_t::Zero(numOutputs, numInputs);\n    size_t statecount(0), inputcount(0), outputcount(0);\n    for (const auto& filt : sisoFilters) {\n      A.block(statecount, statecount, filt.getNumStates(), filt.getNumStates()) = filt.getA();\n      B.block(statecount, inputcount, filt.getNumStates(), filt.getNumInputs()) = filt.getB();\n      C.block(outputcount, statecount, filt.getNumOutputs(), filt.getNumStates()) = filt.getC();\n      D.block(outputcount, inputcount, filt.getNumOutputs(), filt.getNumInputs()) = filt.getD();\n      statecount += filt.getNumStates();\n      inputcount += filt.getNumInputs();\n      outputcount += filt.getNumOutputs();\n    }\n    return Filter(A, B, C, D);\n  } else {\n    return Filter();\n  }\n}\n\nstd::shared_ptr<LoopshapingDefinition> load(const std::string& settingsFile) {\n  // Read from settings File\n  boost::property_tree::ptree pt;\n  boost::property_tree::read_info(settingsFile, pt);\n  Filter r_filter = loopshaping_property_tree::readMIMOFilter(pt, \"r_filter\");\n  Filter s_filter = loopshaping_property_tree::readMIMOFilter(pt, \"s_inv_filter\", /*invert=*/true);\n\n  if (r_filter.getNumOutputs() > 0 && s_filter.getNumOutputs() > 0) {\n    throw std::runtime_error(\"[LoopshapingDefinition] using both r and s filter not implemented\");\n  }\n\n  if (r_filter.getNumOutputs() > 0) {\n    return std::make_shared<LoopshapingDefinition>(LoopshapingType::outputpattern, r_filter);\n  }\n  if (s_filter.getNumOutputs() > 0) {\n    return std::make_shared<LoopshapingDefinition>(LoopshapingType::eliminatepattern, s_filter);\n  }\n\n  throw std::runtime_error(\"[LoopshapingDefinition] error loading loopshaping definition, no valid filter found\");\n}\n\n}  // namespace loopshaping_property_tree\n}  // namespace ocs2\n", "meta": {"hexsha": "40b72446d780d4b35c9672b573d75dfbf49e937d", "size": 7293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ocs2_core/src/loopshaping/LoopshapingPropertyTree.cpp", "max_stars_repo_name": "RIVeR-Lab/ocs2", "max_stars_repo_head_hexsha": "399d3fad27b4a49e48e075a544f2f717944c5da9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ocs2_core/src/loopshaping/LoopshapingPropertyTree.cpp", "max_issues_repo_name": "RIVeR-Lab/ocs2", "max_issues_repo_head_hexsha": "399d3fad27b4a49e48e075a544f2f717944c5da9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ocs2_core/src/loopshaping/LoopshapingPropertyTree.cpp", "max_forks_repo_name": "RIVeR-Lab/ocs2", "max_forks_repo_head_hexsha": "399d3fad27b4a49e48e075a544f2f717944c5da9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9337349398, "max_line_length": 138, "alphanum_fraction": 0.681064034, "num_tokens": 1930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.640635847978761, "lm_q1q2_score": 0.4458558517156841}}
{"text": "/***\n *  $Id$\n **\n *  File: graph_dijkstra.hpp\n *  Created: May 9, 2012\n *\n *  Author: Olga Wodo, Baskar Ganapathysubramanian\n *  Copyright (c) 2012 Olga Wodo, Baskar Ganapathysubramanian\n *  See accompanying LICENSE.\n *\n *  This file is part of GraSPI.\n */\n\n#ifndef GRAPH_DIJKSTRA_HPP\n#define GRAPH_DIJKSTRA_HPP\n\n#include \"graspi_types.hpp\"\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/filtered_graph.hpp>\n\n\nnamespace graspi {\n    /// This function determines the shortest paths in the fitered graph.\n    ///\n    /// This function determines the shortest paths in the filtered graph.\n    /// The shortest paths and the lengths (distances) are computed from the source vertex to all vertices in the filtered graph.\n    /// The filtered graph is determined using predicate Pred.\n    /// @tparam Pred is the predicate used to filter the graph\n    /// @param G is the input graph\n    /// @param W is the map storing the weights of the edges\n    /// @param source is the source vertex with respect to which distances are to be determine_shortest_distanced\n    /// @param pred is the predicate used to filter the graph\n    /// @param d is the vector of distance to be determined as a result of this function\n    template<typename Pred>\n    inline void determine_shortest_distances(graph_t*G,\n                                             const edge_weights_t& W,\n                                             vertex_t source,\n                                             const Pred& pred,\n                                             std::vector<float>& d){\n        boost::filtered_graph<graph_t, Pred> FG(*G,pred);\n        unsigned int n = boost::num_vertices(*G);\n        std::vector<vertex_t> p(n);\n        std::fill(d.begin(), d.end(), 0.0);\n        for (unsigned int i = 0; i < n; ++i) p[i] = i;\n\n        boost::dijkstra_shortest_paths(FG, source,\n                                       boost::predecessor_map(&p[0])\n                                       .\n                                       distance_map(&d[0]).weight_map(W));\n    }\n}//graspi-namespace\n\n#endif\n", "meta": {"hexsha": "9d048c197da256a6e5556a4701808b0139e435ed", "size": 2093, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/graph_dijkstra.hpp", "max_stars_repo_name": "owodolab/graspi", "max_stars_repo_head_hexsha": "4319cad2d5490903998094cdee85f039f70a4ff6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-24T15:07:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T00:22:14.000Z", "max_issues_repo_path": "src/graph_dijkstra.hpp", "max_issues_repo_name": "owodolab/graspi", "max_issues_repo_head_hexsha": "4319cad2d5490903998094cdee85f039f70a4ff6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-21T21:33:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-08T16:17:12.000Z", "max_forks_repo_path": "src/graph_dijkstra.hpp", "max_forks_repo_name": "owodolab/graspi", "max_forks_repo_head_hexsha": "4319cad2d5490903998094cdee85f039f70a4ff6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-11-19T22:18:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T11:13:22.000Z", "avg_line_length": 38.7592592593, "max_line_length": 129, "alphanum_fraction": 0.596751075, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210895, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.44585584841081755}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string.h>\n#include <math.h> \n#include <Eigen/Dense>\n#include <algorithm>\n\n#include \"matrix.h\"\n#include \"kdtree_nano.h\"\n\nusing namespace std;\n\n\n/**\n * @brief SparsifyData Sparsify a point cloud\n * @param M Input Point cloud\n * @param M_num Number of points in M\n * @param dim Dimemsion of points\n * @param idx_sparse Output binary masks indicating which point should be preserved\n * @param idx_size Output number of points to be preserved\n * @param min_dist Minimum distance for sparsifying\n * @param out_dist Distance for removing outliers\n * @param idx_start Start sparsifying from the specific point\n */\nvoid SparsifyData (double *M,int32_t M_num,int32_t dim,int32_t* idx_sparse,int32_t &idx_size,double min_dist,double out_dist,int32_t idx_start) {\n  \n  // copy model data to kdtree\n  PointCloud<double> cloud;\n  for (int32_t m=0; m<M_num; m++) {\n      cloud.pts.push_back(Point<double>((double)M[m*dim], (double)M[m*dim+1], (double)M[m*dim+2]));  }\n\n  // build a kd tree from the model point cloud\n  KDtree<double>* tree = new KDtree<double>(cloud);\n \n  // for all data points do\n  for (int32_t i=0; i<M_num; i++) {\n    \n    if (i>=idx_start) {\n      \n      vector<size_t> result;\n      vector<double> dist;\n      tree->radiusSearch(cloud.pts[i], min_dist, result, dist);\n\n      bool neighbor_exists = false;\n      for (int32_t j=0; j<result.size(); j++)\n        neighbor_exists |= (bool)idx_sparse[result[j]];\n\n      if (!neighbor_exists) {\n        idx_sparse[i] = 1;\n        idx_size++;\n      }\n      \n    // simply add\n    } else {\n      idx_sparse[i] = 1;\n      idx_size++;\n    }\n  }\n\n  \n  // remove outliers\n  if (out_dist>0) {\n    for (int32_t i=idx_start; i<M_num; i++) {\n\n      if (idx_sparse[i] == 1) {\n\n        vector<size_t> result;\n        vector<double> dist;\n        tree->radiusSearch(cloud.pts[i], out_dist, result, dist);\n\n        int32_t num_neighbors = 0;\n        for (int32_t j=1; j<result.size(); j++) {\n          if (idx_sparse[result[j]]==1)\n            num_neighbors++;\n        }\n        \n        if (num_neighbors==0) {\n          idx_sparse[i] = 0;\n          idx_size--;\n        }\n      }    \n    }\n  }\n  \n  // release memory of kd tree\n  delete tree;\n}\n\n\n/**\n * @brief ExtractCols Extract columns of a matrix given indices\n * @param input Input matrix\n * @param output Output matrix\n * @param idx_sparse Binary masks indicate which columns should be preserved\n * @param idx_size Number of columns to be preserved\n */\nvoid ExtractCols(Eigen::MatrixXd &input, Eigen::MatrixXd &output, int32_t *idx_sparse, int32_t idx_size){\n\n    output.resize(input.rows(), idx_size);\n\n    int32_t k=0;\n    for (int i=0; i<input.cols(); i++){\n        if (idx_sparse[i]){\n            for (int c=0; c<input.rows(); c++){\n                output(c,k) = input(c, i);\n            }\n            k++;\n        }\n    }\n}\n\n/**\n * @brief ExtractCols Extract columns of a matrix given indices\n * @param input Input matrix\n * @param output Output matrix\n * @param idx Indices of columns to extract\n */\nvoid ExtractCols(Eigen::MatrixXd &input, Eigen::MatrixXd &output, vector<int> idx){\n\n    int dim=input.rows();\n    output.resize(dim, idx.size());\n    for (int i=0; i<idx.size(); i++){\n        for (int c=0; c<dim; c++){\n            output(c, i) = input(c, idx[i]);\n        }\n    }\n}\n\n/**\n * @brief ExtractCols Extract columns of a matrix given indices\n * @param input Input matrix\n * @param output Output matrix\n * @param idx Indices of rows to extract\n */\nvoid ExtractRows(Eigen::MatrixXd &input, Eigen::MatrixXd &output, vector<int> idx){\n\n    int dim=input.cols();\n    output.resize(idx.size(), dim);\n    for (int i=0; i<idx.size(); i++){\n        for (int c=0; c<dim; c++){\n            output(i, c) = input(idx[i], c);\n        }\n    }\n}\n\n/**\n *@brief RemoveBlindSpot Remove the points within a sector\n *@param matIn Input point cloud\n *@param matOut Output point cloud\n *@param blind_splot_angle Sector angle\n */\nvoid RemoveBlindSpot(Eigen::MatrixXd &matIn, Eigen::MatrixXd &matOut, float blind_splot_angle){\n    if (blind_splot_angle<=0){\n        matOut = matIn;\n        return;\n    }\n    Eigen::MatrixXd matInSub = matIn.block(0,0,matIn.rows(),2);\n    Eigen::MatrixXd matNorm = matInSub.rowwise().norm();\n\n    matInSub = matIn.block(0,0,matIn.rows(),1);\n    Eigen::ArrayXd v = - matInSub.array() / matNorm.array();\n\n    float angle = cos(blind_splot_angle/2);\n\n    int k=0;\n    matOut.resize(matIn.rows(), matIn.cols());\n    for (int i=0; i<matIn.rows(); i++){\n        if (v(i, 0)<=angle){\n            matOut.block(k,0,1,matIn.cols()) = matIn.block(i,0,1,matIn.cols());\n            k++;\n        }\n    }\n    Eigen::MatrixXd matrixSlice = matOut.block(0,0,k,matIn.cols());\n    matOut = matrixSlice;\n}\n\n/**\n *@brief CropVelodyneData Crop velodyne data given max and min distance\n *@param matIn Input point cloud\n *@param matOut Output point cloud\n *@param minDist Minimum distance to crop data\n *@param maxDist Maximum distance to crop data\n */\nvoid CropVelodyneData (Eigen::MatrixXd &matIn, Eigen::MatrixXd &matOut, float minDist, float maxDist){\n\n    Eigen::MatrixXd matNorm = matIn.rowwise().norm();\n\n    int k = 0;\n    matOut.resize(matIn.rows(), matIn.cols());\n    for (int i=0; i<matIn.rows(); i++){\n        if (matNorm(i,0) > minDist && matNorm(i,0) < maxDist){\n            matOut.block(k,0,1,matIn.cols()) = matIn.block(i,0,1,matIn.cols());\n            k++;\n        }\n    }\n    Eigen::MatrixXd matrixSlice = matOut.block(0,0,k,matIn.cols());\n    matOut = matrixSlice;\n\n}\n\n/**\n *@brief CropVelodyneData Crop velodyne data given max and min distance\n *@param matIn Input point cloud\n *@param matOut Output indices of preserved points\n *@param minDist Minimum distance to crop data\n *@param maxDist Maximum distance to crop data\n */\nvoid CropVelodyneData (Eigen::MatrixXd &matIn, vector<int> &idxOut, float minDist, float maxDist){\n\n    Eigen::MatrixXd matNorm = matIn.rowwise().norm();\n\n    idxOut.clear();\n    for (int i=0; i<matIn.rows(); i++){\n        if (matNorm(i,0) > minDist && matNorm(i,0) < maxDist){\n            idxOut.push_back(i);\n        }\n    }\n}\n\n/**\n *@brief CurlVelodyneData Transform velodyne data given curl parameters\n *@param velo_in Input velodyne data\n *@param velo_out Output velodyne data\n *@param r Rotation matrix for curl\n *@param t Translation vector for curl\n */\nvoid CurlVelodyneData (Eigen::MatrixXd &velo_in, Eigen::MatrixXd &velo_out, Eigen::Vector3d r, Eigen::Vector3d t){\n  \n  // for all points do\n  int dim = velo_in.cols(); // 3\n  int pt_num = velo_in.rows();\n  velo_out.resize(pt_num, dim);\n  for (int32_t i=0; i<pt_num; i++) {\n    \n    double vx = velo_in(i, 0);\n    double vy = velo_in(i, 1);\n    double vz = velo_in(i, 2);\n    \n    double s = 0.5*atan2(vy,vx)/M_PI;\n    \n    double rx = s*r(0);\n    double ry = s*r(1);\n    double rz = s*r(2);\n    \n    double tx = s*t(0);\n    double ty = s*t(1);\n    double tz = s*t(2);\n    \n    double theta = sqrt(rx*rx+ry*ry+rz*rz);\n    \n    if (theta>1e-10) {\n      \n      double kx = rx/theta;\n      double ky = ry/theta;\n      double kz = rz/theta;\n      \n      double ct = cos(theta);\n      double st = sin(theta);\n      \n      double kv = kx*vx+ky*vy+kz*vz;\n      \n      velo_out(i, 0) = vx*ct + (ky*vz-kz*vy)*st + kx*kv*(1-ct) + tx;\n      velo_out(i, 1) = vy*ct + (kz*vx-kx*vz)*st + ky*kv*(1-ct) + ty;\n      velo_out(i, 2) = vz*ct + (kx*vy-ky*vx)*st + kz*kv*(1-ct) + tz;\n      \n      \n    } else {\n      \n      velo_out(i, 0) = vx + tx;\n      velo_out(i, 1) = vy + ty;\n      velo_out(i, 2) = vz + tz;\n      \n    }\n    \n    // intensity\n    // velo_out[i*4+3] = velo_in[i*4+3];\n  }\n}\n\n/**\n *@brief GetHalfPoints Get either forward or backward points\n *@param matIn Input matrix\n *@param matOut Output matrix\n *@param direction Bool value indicating forward (true) or backward (false) \n */\nvoid GetHalfPoints(Eigen::MatrixXd &matIn, Eigen::MatrixXd &matOut, bool direction){\n\n    int k = 0;\n    matOut.resize(matIn.rows(), matIn.cols());\n    for (int i=0; i<matIn.cols(); i++){\n        if ((direction && matIn(0,i)>0) || (!direction && matIn(0,i)<0)){\n            matOut.block(0,k,matIn.rows(),1) = matIn.block(0,i,matIn.rows(),1);\n            k++;\n        }\n    }\n    Eigen::MatrixXd matrixSlice = matOut.block(0,0,matIn.rows(),k);\n    matOut = matrixSlice;\n}\n\ntypedef struct {\n    double r,g,b;\n} COLOUR;\n\n/**\n *@brief GetColour Turn a double into a color vector\n *@param v Input value\n *@param vmin Min value for coloring\n *@param vmax Max value for coloring\n */\nCOLOUR GetColour(double v,double vmin,double vmax)\n{\n   COLOUR c = {1.0,1.0,1.0}; // white\n   double dv;\n\n   if (v < vmin)\n      v = vmin;\n   if (v > vmax)\n      v = vmax;\n   dv = vmax - vmin;\n\n   if (v < (vmin + 0.25 * dv)) {\n      c.r = 0;\n      c.g = 4 * (v - vmin) / dv;\n   } else if (v < (vmin + 0.5 * dv)) {\n      c.r = 0;\n      c.b = 1 + 4 * (vmin + 0.25 * dv - v) / dv;\n   } else if (v < (vmin + 0.75 * dv)) {\n      c.r = 4 * (v - vmin - 0.5 * dv) / dv;\n      c.b = 0;\n   } else {\n      c.g = 1 + 4 * (vmin + 0.75 * dv - v) / dv;\n      c.b = 0;\n   }\n\n   return(c);\n}\n\n/**\n *@brief GetColorToHeight Assign a color to each point according to its height\n *@param pose Input point cloud\n *@param color Output color \n */\nvoid GetColorToHeight(Eigen::MatrixXd &pose, Eigen::MatrixXd &color){\n    // get height from poses\n    Eigen::VectorXd height = pose.block(0,2,pose.rows(),1);\n\n    // sort and get the quantiles\n    sort(height.data(),height.data()+height.size());\n    int idxL = (int)(ceil((double)height.size()*0.05));\n    int idxH = (int)(floor((double)height.size()*0.95));\n    double heightL = height(idxL);\n    double heightH = height(idxH);\n\n    for (int i=0; i<height.size(); i++){\n        COLOUR c = GetColour(pose(i, 2), heightL, heightH);\n        color(i, 0) = c.r;\n        color(i, 1) = c.g;\n        color(i, 2) = c.b;\n    }\n}", "meta": {"hexsha": "d3d1339a02e50eb394f6dde928626efe0541a2b1", "size": 9849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kitti360scripts/devkits/accumuLaser/src/utils.cpp", "max_stars_repo_name": "carloradice/kitti360Scripts", "max_stars_repo_head_hexsha": "3b5bfde63eb98e5a05b06e20d051059e470305ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 214.0, "max_stars_repo_stars_event_min_datetime": "2020-10-06T16:22:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:05:19.000Z", "max_issues_repo_path": "kitti360scripts/devkits/accumuLaser/src/utils.cpp", "max_issues_repo_name": "carloradice/kitti360Scripts", "max_issues_repo_head_hexsha": "3b5bfde63eb98e5a05b06e20d051059e470305ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 50.0, "max_issues_repo_issues_event_min_datetime": "2020-10-21T08:37:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T15:11:26.000Z", "max_forks_repo_path": "kitti360scripts/devkits/accumuLaser/src/utils.cpp", "max_forks_repo_name": "carloradice/kitti360Scripts", "max_forks_repo_head_hexsha": "3b5bfde63eb98e5a05b06e20d051059e470305ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38.0, "max_forks_repo_forks_event_min_datetime": "2020-10-06T16:33:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T10:15:28.000Z", "avg_line_length": 27.3583333333, "max_line_length": 145, "alphanum_fraction": 0.5970149254, "num_tokens": 2933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.44573604265087075}}
{"text": "#ifndef ALEPH_GEOMETRY_HEAT_KERNEL_HH__\n#define ALEPH_GEOMETRY_HEAT_KERNEL_HH__\n\n#include <aleph/config/Eigen.hh>\n\n#ifdef ALEPH_WITH_EIGEN\n  #include <Eigen/Core>\n  #include <Eigen/Eigenvalues>\n#endif\n\n#include <aleph/math/KahanSummation.hh>\n\n#include <algorithm>\n#include <unordered_map>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\n#include <cmath>\n\n#define THROW_EIGEN_REQUIRED_ERROR()\\\n{\\\n  auto message =  std::string( __FILE__ )           \\\n                + std::string( \":\" )                \\\n                + std::to_string( __LINE__ )        \\\n                + std::string( \" in \" )             \\\n                + std::string( __PRETTY_FUNCTION__ )\\\n                + std::string( \":\" )                \\\n                + std::string( \" Eigen is required for this function to work properly\" );\\\n  \\\n  throw std::runtime_error( message );\\\n}\n\nnamespace aleph\n{\n\nnamespace geometry\n{\n\n#ifdef ALEPH_WITH_EIGEN\n\n/**\n  Extracts a weighted adjacency matrix from a simplicial complex. At\n  present, this function only supports adjacencies between edges, so\n  the resulting matrix is a graph adjacency matrix.\n\n  @param K Simplicial complex\n\n  @returns Weighted adjacency matrix. The indices of rows and columns\n           follow the order of the vertices in the complex.\n*/\n\ntemplate <class SimplicialComplex> auto weightedAdjacencyMatrix( const SimplicialComplex& K ) -> Eigen::Matrix<typename SimplicialComplex::ValueType::DataType, Eigen::Dynamic, Eigen::Dynamic>\n{\n  using Simplex    = typename SimplicialComplex::ValueType;\n  using VertexType = typename Simplex::VertexType;\n  using DataType   = typename Simplex::DataType;\n  using Matrix     = Eigen::Matrix<DataType, Eigen::Dynamic, Eigen::Dynamic>;\n\n#if EIGEN_VERSION_AT_LEAST(3,3,0)\n  using IndexType  = Eigen::Index;\n#else\n  using IndexType  = typename Matrix::Index;\n#endif\n\n  // Prepare map from vertex to index ----------------------------------\n\n  std::unordered_map<VertexType, IndexType> vertex_to_index;\n  IndexType n = IndexType();\n\n  {\n    std::vector<VertexType> vertices;\n    K.vertices( std::back_inserter( vertices ) );\n\n    IndexType index = IndexType();\n\n    for( auto&& vertex : vertices )\n      vertex_to_index[vertex] = index++;\n\n    n = static_cast<IndexType>( vertices.size() );\n  }\n\n  // Prepare matrix ----------------------------------------------------\n\n  Matrix W = Matrix::Zero( n, n );\n\n  for(auto&& s : K )\n  {\n    if( s.dimension() != 1 )\n      continue;\n\n    auto&& u = s[0];\n    auto&& v = s[1];\n    auto&& i = vertex_to_index.at( u );\n    auto&& j = vertex_to_index.at( v );\n\n    W(i,j)   = s.data();\n    W(j,i)   = W(i,j);\n  }\n\n  return W;\n}\n\n/**\n  Calculates the weighted Laplacian matrix of a given simplicial\n  complex and returns it.\n\n  @param K Simplicial complex\n\n  @returns Weighted Laplacian matrix. The indices of rows and columns\n           follow the order of the vertices in the complex.\n*/\n\ntemplate <class SimplicialComplex> auto weightedLaplacianMatrix( const SimplicialComplex& K ) -> Eigen::Matrix<typename SimplicialComplex::ValueType::DataType, Eigen::Dynamic, Eigen::Dynamic>\n{\n  auto W          = weightedAdjacencyMatrix( K );\n  using Matrix    = decltype(W);\n  using IndexType = typename Matrix::Index;\n\n  Matrix L = Matrix::Zero( W.rows(), W.cols() );\n\n  auto V = W.rowwise().sum();\n\n  for( IndexType i = 0; i < V.size(); i++ )\n    L(i,i) = V(i);\n\n  return L - W;\n}\n\n/**\n  Calculates the Moore--Penrose pseudo-inverse of the weighted Laplacian\n  matrix of a given simplicial complex and returns it.\n\n  @param K Simplicial complex\n\n  @returns Moore--Penrose pseudo-inverse matrix. The indices of rows and\n           columns follow the order of the vertices in the complex.\n*/\n\ntemplate <class SimplicialComplex> auto pinvWeightedLaplacianMatrix( const SimplicialComplex& K ) -> Eigen::Matrix<typename SimplicialComplex::ValueType::DataType, Eigen::Dynamic, Eigen::Dynamic>\n{\n  auto L = weightedLaplacianMatrix( K );\n  auto n = L.rows();\n\n  using Matrix    = decltype(L);\n  using Simplex   = typename SimplicialComplex::ValueType;\n  using DataType  = typename Simplex::DataType;\n\n  Matrix M = Matrix::Constant( L.rows(), L.cols(), static_cast<DataType>( 1/ n ) );\n\n  return (M+L).inverse() - M;\n}\n\n#endif\n\n/**\n  @class HeatKernel\n  @brief Calculates the heat kernel for simplicial complexes\n\n  This class acts as a query functor for the heat kernel values of\n  vertices in a weighted simplicial complex. It will pre-calculate\n  the heat matrix and permit queries about the progression of heat\n  values for *all* vertices for some time \\f$t\\f$.\n*/\n\nclass HeatKernel\n{\npublic:\n\n  using T = double;\n\n#ifdef ALEPH_WITH_EIGEN\n  using Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n  using Vector = Eigen::Matrix<T, 1, Eigen::Dynamic>;\n\n#if EIGEN_VERSION_AT_LEAST(3,3,0)\n  using IndexType  = Eigen::Index;\n#else\n  using IndexType  = typename Matrix::Index;\n#endif\n\n#else\n  // This declares a fallback index type in case Eigen is not available,\n  // making sure that the interface of the class remains the same.\n  using IndexType = unsigned;\n#endif\n\n  /**\n    Constructs a heat kernel from a given simplicial complex. Afterwards,\n    the functor will be ready for queries.\n\n    @param K Simplicial complex\n  */\n\n  template <class SimplicialComplex> HeatKernel( const SimplicialComplex& K )\n  {\n#ifdef ALEPH_WITH_EIGEN\n\n    auto L = weightedLaplacianMatrix( K );\n\n    Eigen::SelfAdjointEigenSolver< decltype(L) > solver;\n    solver.compute( L );\n\n    auto&& eigenvalues  = solver.eigenvalues(). template cast<T>();\n    auto&& eigenvectors = solver.eigenvectors().template cast<T>();\n\n    _eigenvalues.reserve( std::size_t( eigenvalues.size() ) );\n    _eigenvectors.reserve( std::size_t( eigenvectors.size() ) );\n\n    using IndexType_ = typename decltype(L)::Index;\n\n    // If configured, skip both the first eigenvector and the first\n    // eigenvalue because they do not contribute anything later on.\n    for( IndexType_ i = _skip ? 1 : 0; i < eigenvalues.size(); i++ )\n      _eigenvalues.push_back( eigenvalues(i) );\n\n    for( IndexType_ i = _skip ? 1 : 0; i < eigenvectors.cols(); i++ )\n      _eigenvectors.push_back( eigenvectors.col(i) );\n\n#else\n  (void) K;\n\n  THROW_EIGEN_REQUIRED_ERROR();\n#endif\n\n  }\n\n  /**\n    Evaluates the heat kernel for *all* vertices at a given time \\f$t\\f$\n    and returns the resulting values. This function is guaranteed to be\n    more efficient than calling the per-element functions repeatedly.\n  */\n\n  std::vector<T> operator()( T t )\n  {\n#ifdef ALEPH_WITH_EIGEN\n\n    Vector result = Vector();\n\n    for( std::size_t k = 0; k < _eigenvalues.size(); k++ )\n    {\n      auto&& lk  = std::exp( -t * _eigenvalues[k] );\n      auto&& uk = _eigenvectors[k];\n\n      result += lk * uk * uk.transpose();\n    }\n\n    return std::vector<T>( result.data(), result.data() + result.size() );\n\n#else\n    (void) t;\n\n    THROW_EIGEN_REQUIRED_ERROR();\n#endif\n  }\n\n  /**\n    Evaluates the heat kernel for two vertices \\f$i\\f$ and \\f$j\\f$ at\n    a given time \\f$t\\f$ and returns the result.\n  */\n\n  T operator()( IndexType i, IndexType j, T t )\n  {\n#ifdef ALEPH_WITH_EIGEN\n\n    aleph::math::KahanSummation<T> result = T();\n\n    for( std::size_t k = 0; k < _eigenvalues.size(); k++ )\n    {\n      auto&& lk  = std::exp( -t * _eigenvalues[k] );\n      auto&& uik = _eigenvectors[k](i);\n      auto&& ujk = _eigenvectors[k](j);\n\n      result += lk * uik * ujk;\n    }\n\n    return result;\n\n#else\n  (void) i;\n  (void) j;\n  (void) t;\n\n  THROW_EIGEN_REQUIRED_ERROR();\n#endif\n  }\n\n  /**\n    Calculates the auto-diffusion for a given vertex \\f$i\\f$ and a given\n    time \\f$t\\f$ and returns it.\n  */\n\n  T operator()( IndexType i, T t )\n  {\n#ifdef ALEPH_WITH_EIGEN\n\n    // Note that this function could have been implemented in terms of\n    // operator(i,j,t), but this implementation is a *little* bit more\n    // efficient as it defines the multiplication explicitly.\n\n    aleph::math::KahanSummation<T> result = T();\n\n    for( std::size_t k = 0; k < _eigenvalues.size(); k++ )\n    {\n      auto&& lk  = std::exp( -t * _eigenvalues[k] );\n      auto&& uik = _eigenvectors[k](i);\n\n      result += lk * uik * uik;\n    }\n\n    return result;\n\n#else\n  (void) i;\n  (void) t;\n\n  THROW_EIGEN_REQUIRED_ERROR();\n#endif\n  }\n\n  /**\n    Calculates the *trace* of the heat kernel for a given time \\f$t\\f$\n    and returns it.\n  */\n\n  T trace( T t ) const\n  {\n    aleph::math::KahanSummation<T> result = T();\n\n    for( auto&& eigenvalue : _eigenvalues )\n      result += std::exp( -t * eigenvalue );\n\n    return result;\n  }\n\n  /**\n    Calculates the *determinant* of the heat kernel for a given time\n    \\f$t\\f$ and returns it.\n  */\n\n  T determinant( T t) const\n  {\n    T result = T();\n\n    for( auto&& eigenvalue : _eigenvalues )\n      result = result * std::exp( -t * eigenvalue );\n\n    return result;\n  }\n\n  // Sampling intervals ------------------------------------------------\n\n  /**\n    Uses a heuristic to determine a sampling interval for the time\n    parameter \\f$t\\f$ of the heat kernel. This heuristic was first\n    described by Sun et al. in their paper *A Concise and Provably\n    Informative Multi-Scale Signature Based on Heat Diffusion*.\n\n    @param n Number of sampling points\n    @returns Vector of sampling points\n  */\n\n  std::vector<T> logarithmicSamplingInterval( unsigned n ) const\n  {\n    auto t_min  = 4 * std::log( 10 ) / _eigenvalues.back();\n    auto t_max  = 4 * std::log( 10 ) / ( _skip ? _eigenvalues.front() : *( _eigenvalues.begin() + 1 ) );\n    auto offset = ( std::log( t_max ) - std::log( t_min ) ) / ( n - 1 );\n\n    std::vector<T> samples;\n    samples.reserve( n );\n\n    for( unsigned i = 0; i < n; i++ )\n      samples.push_back( std::log( t_min ) + i * offset );\n\n    std::transform( samples.begin(), samples.end(),\n                    samples.begin(),\n                    [] ( const T x )\n                    {\n                      return std::pow( std::exp(1), x );\n                    } );\n\n    return samples;\n  }\n\n  // Configuration -----------------------------------------------------\n\n  void setSkip( bool value = true ) { _skip = value; }\n  bool skip() const noexcept        { return _skip;  }\n\nprivate:\n\n  /** If set, skips the first eigenvector and eigenvalue */\n  bool _skip = false;\n\n  /**\n    Stores the eigenvalues of the heat matrix, or, more precisely, the\n    eigenvalues of the Laplacian. They will be used for the evaluation\n    of the heat kernel.\n  */\n\n  std::vector<T> _eigenvalues;\n\n#ifdef ALEPH_WITH_EIGEN\n\n  /** Stores the eigenvectors of the heat matrix */\n  std::vector<Vector> _eigenvectors;\n\n  /**\n    Heat matrix; will be created automatically upon constructing this\n    functor class.\n  */\n\n  Matrix _H;\n#endif\n\n};\n\n} // namespace geometry\n\n} // namespace aleph\n\n#endif\n", "meta": {"hexsha": "712c1bb11af4dae1ab3a3a3a592e19455526caa3", "size": 10756, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/aleph/geometry/HeatKernel.hh", "max_stars_repo_name": "maexlich/Aleph", "max_stars_repo_head_hexsha": "772244ec0cf64250a20579b349deb02523ca3fc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/aleph/geometry/HeatKernel.hh", "max_issues_repo_name": "maexlich/Aleph", "max_issues_repo_head_hexsha": "772244ec0cf64250a20579b349deb02523ca3fc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/aleph/geometry/HeatKernel.hh", "max_forks_repo_name": "maexlich/Aleph", "max_forks_repo_head_hexsha": "772244ec0cf64250a20579b349deb02523ca3fc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4278959811, "max_line_length": 195, "alphanum_fraction": 0.6330420231, "num_tokens": 2876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4456927352129281}}
{"text": "/*\n * Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n#include <string>\n#include <ros/ros.h>\n\n#include <sensor_msgs/JointState.h>\n#include <std_msgs/Float64.h>\n#include <geometry_msgs/Twist.h>\n\n#include <kdl_parser/kdl_parser.hpp>\n#include <kdl/chainfksolvervel_recursive.hpp>\n#include <kdl/chainjnttojacsolver.hpp>\n#include <kdl/frames.hpp>\n#include <kdl/jntarray.hpp>\n#include <kdl/jntarrayvel.hpp>\n\n#include <Eigen/Dense>\n#include <kdl_conversions/kdl_msg.h>\n\nclass DebugEvaluateJointStates\n{\n    ros::NodeHandle nh_;\n    ros::Subscriber jointstate_sub_;\n    ros::Publisher manipulability_pub_;\n    ros::Publisher twist_current_pub_;\n\n    std::string chain_base_link_;\n    std::string chain_tip_link_;\n\n    KDL::Chain chain_;\n    KDL::ChainFkSolverVel_recursive* p_fksolver_vel_;\n    KDL::ChainJntToJacSolver* p_jnt2jac_;\n\npublic:\n    int init()\n    {\n        if (!nh_.getParam(\"chain_base_link\", this->chain_base_link_))\n        {\n            ROS_ERROR(\"Failed to get parameter \\\"chain_base_link\\\".\");\n            return -1;\n        }\n\n        if (!nh_.getParam(\"chain_tip_link\", this->chain_tip_link_))\n        {\n            ROS_ERROR(\"Failed to get parameter \\\"chain_tip_link\\\".\");\n            return -2;\n        }\n\n        /// parse robot_description and generate KDL chains\n        KDL::Tree my_tree;\n        if (!kdl_parser::treeFromParam(\"/robot_description\", my_tree))\n        {\n            ROS_ERROR(\"Failed to construct kdl tree\");\n            return -3;\n        }\n\n        my_tree.getChain(this->chain_base_link_, this->chain_tip_link_, chain_);\n        if (chain_.getNrOfJoints() == 0)\n        {\n            ROS_ERROR(\"Failed to initialize kinematic chain\");\n            return -4;\n        }\n\n        p_fksolver_vel_ = new KDL::ChainFkSolverVel_recursive(chain_);\n        p_jnt2jac_ = new KDL::ChainJntToJacSolver(chain_);\n\n        /// initialize ROS interfaces\n        jointstate_sub_ = nh_.subscribe(\"joint_states\", 1, &DebugEvaluateJointStates::jointstateCallback, this);\n        manipulability_pub_ = nh_.advertise<std_msgs::Float64> (\"debug/manipulability\", 1);\n        twist_current_pub_ = nh_.advertise<geometry_msgs::Twist> (\"debug/twist_current\", 1);\n\n        return 0;\n    }\n\n    void jointstateCallback(const sensor_msgs::JointState::ConstPtr& msg)\n    {\n        KDL::JntArray q = KDL::JntArray(chain_.getNrOfJoints());\n        KDL::JntArray q_dot = KDL::JntArray(chain_.getNrOfJoints());\n\n        for (unsigned int i = 0; i < msg->name.size(); i++)\n        {\n            q(i) = msg->position[i];\n            q_dot(i) = msg->velocity[i];\n        }\n\n        /// compute current twist\n        KDL::FrameVel FrameVel;\n        KDL::JntArrayVel jntArrayVel = KDL::JntArrayVel(q, q_dot);\n        if (p_fksolver_vel_->JntToCart(jntArrayVel, FrameVel, -1) >= 0)\n        {\n            geometry_msgs::Twist twist_msg;\n            tf::twistKDLToMsg(FrameVel.GetTwist(), twist_msg);\n            twist_current_pub_.publish(twist_msg);\n        }\n\n        /// compute manipulability\n        KDL::Jacobian jac(chain_.getNrOfJoints());\n        p_jnt2jac_->JntToJac(q, jac);\n        Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> prod = jac.data * jac.data.transpose();\n        double d = prod.determinant();\n        double kappa = std::sqrt(std::abs(d));\n        std_msgs::Float64 manipulability_msg;\n        manipulability_msg.data = kappa;\n        manipulability_pub_.publish(manipulability_msg);\n    }\n};\n\n\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"debug_evaluate_jointstates_node\");\n\n    DebugEvaluateJointStates dejs;\n    if (dejs.init() != 0)\n    {\n        ROS_ERROR(\"Failed to initialize DebugEvaluateJointStates.\");\n        return -1;\n    }\n\n    ros::spin();\n}\n", "meta": {"hexsha": "60d73330a4de8035ff2cc49f145c7b39815b012f", "size": 4303, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/debug/debug_evaluate_jointstates_node.cpp", "max_stars_repo_name": "nbfigueroa-rlic/robot_kinematics_kdl", "max_stars_repo_head_hexsha": "6f471c4e8f781e87c4309f348104a0fd299f66ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/debug/debug_evaluate_jointstates_node.cpp", "max_issues_repo_name": "nbfigueroa-rlic/robot_kinematics_kdl", "max_issues_repo_head_hexsha": "6f471c4e8f781e87c4309f348104a0fd299f66ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/debug/debug_evaluate_jointstates_node.cpp", "max_forks_repo_name": "nbfigueroa-rlic/robot_kinematics_kdl", "max_forks_repo_head_hexsha": "6f471c4e8f781e87c4309f348104a0fd299f66ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-02T17:31:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T17:31:42.000Z", "avg_line_length": 31.4087591241, "max_line_length": 112, "alphanum_fraction": 0.6537299558, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4456492245336003}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_EXPX2_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_EXPX2_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/detail/constant/expx2c1.hpp>\n#include <boost/simd/detail/constant/expx2c2.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/detail/constant/maxlog.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/floor.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/plus.hpp>\n#include <boost/simd/function/signnz.hpp>\n#include <boost/simd/function/sqr.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/function/is_equal.hpp>\n#endif\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF( expx2_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n     BOOST_FORCEINLINE A0 operator()(const A0& a0) const\n      {\n        A0 x =  bs::abs(a0);\n        // Represent x as an exact multiple of 1/32 plus a residual.\n        A0 m = Expx2c1<A0>()*bs::floor(fma(Expx2c2<A0>(), x, bs::Half<A0>()));\n        A0 f =  x-m;\n        // x**2 = m**2 + 2mf + f**2\n        A0 u = bs::sqr(m);\n        A0 u1 = fma(m+m,f,sqr(f));\n        // u is exact, u1 is small.\n        A0 r = bs::if_else(bs::is_greater(u+u1, bs::Maxlog<A0>()),\n                            bs::Inf<A0>(),\n                            bs::exp(u)*bs::exp(u1));\n        #ifndef BOOST_SIMD_NO_INFINITIES\n        r =  bs::if_else(is_equal(x, Inf<A0>()), x, r);\n        #endif\n        return r;\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD_IF( expx2_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n     BOOST_FORCEINLINE A0 operator()(const A0& a0,  const A0 & s) const\n      {\n        A0 sgn =  signnz(s);\n        A0 x =  a0*sgn;\n        // Represent x as an exact multiple of 1/32 plus a residual.\n        A0 m = Expx2c1<A0>()*bs::floor(fma(Expx2c2<A0>(), x, bs::Half<A0>()));\n        A0 f =  x-m;\n        // x**2 = m**2 + 2mf + f**2\n        A0 u = sgn*bs::sqr(m);\n        A0 u1 = sgn*fma(m+m,f,sqr(f));\n        // u is exact, u1 is small.\n        A0 r = bs::if_else(bs::is_greater(u+u1, bs::Maxlog<A0>()),\n                            bs::Inf<A0>(),\n                            bs::exp(u)*bs::exp(u1));\n        #ifndef BOOST_SIMD_NO_INFINITIES\n        r =  bs::if_else(is_equal(x, Inf<A0>()), x, r);\n        #endif\n        return r;\n      }\n   };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "bbfbc24fd67707ddef615da17af8d80de10dbcb1", "size": 3526, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/expx2.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/simd/function/expx2.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/simd/function/expx2.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 35.6161616162, "max_line_length": 100, "alphanum_fraction": 0.5246738514, "num_tokens": 948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711802609599, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.44558378995104264}}
{"text": "#ifndef TRACE_RAYTRACE_\n#define TRACE_RAYTRACE_\n#include <headers/setup.hpp>\n#include <headers/geometry.hpp>\n#include <boost/iterator/indirect_iterator.hpp>\n\nnamespace raytrace {\n\n    using geometry::Point;\n    using geometry::Vector;\n    using geometry::Sphere;\n    using geometry::Line;\n    using geometry::SphPoint;\n\n    struct ExpGeometry\n    {\n        static constexpr float rho = 1000.0;                           //mm\n        static constexpr float d = 60.0;                               //mm\n        static constexpr float l1 = 195.0;                             //mm\n        static constexpr float l2 = 185.0;                             //mm\n        static constexpr float L = 60.0;                               //mm\n    };\n\n    class Surface\n    {\n        private:\n            setup::Spline delta_;\n            setup::Spline gamma_;                                       //Permettivity = 1 - delta + i * gamma\n            double RMSHeight_;                                          //RMS Height [nm]\n            double CorrLength_;                                         //Correlation length [um]\n            double alpha_;                                              //alpha parameter in PSD ABC model\n\n            double k(double wl) const {return 2 * Constants::pi / wl; }\n            double mu0(double th0, double corl, double wl) const {return corl * 1e3 * pow(sin(th0), 2) / (2 * wl); }\n            std::complex<double> muc(double corl, double wl) const {return corl * 1e3 * (1.0 - permettivity(wl)) / (2 * wl); }\n            double F(double tau, double alpha) const {return 2.0 / sqrt(Constants::pi) * tgamma(alpha + 0.5) / tgamma(alpha) / pow(1 + tau * tau, alpha + 0.5); }\n        public:\n            Surface(double RMSHeight = Constants::RMSHeight,\n            double CorrLength = Constants::CorrLength, double alpha = Constants::alpha, const std::string & str = \"Al2O3.txt\");\n            std::complex<double> permettivity (double wl = Constants::WL) const;\n            double Rf (double th0, double wl = Constants::WL) const;\n            double TIS (double th0, double rmsh, double corl, double alpha, double wl = Constants::WL) const;\n            double Indicatrix1D (double th, double th0, double wl = Constants::WL) const;\n            double Indicatrix2D (double th, double phi, double th0, double wl = Constants::WL) const;\n            double PSD1D (double p) const noexcept;                              //PSD 1D ([micrometer ^ -1]) [micrometer ^ 3]\n            double PSD2D (double p1, double p2) const noexcept;                  //PSD 2D ([micrometer ^ -1]) [micrometer ^ 4]\n            double CritAng(double wl = Constants::WL) const {return sqrt(1.0 - real(permettivity(wl))); }\n            double RMSHeight() const noexcept {return RMSHeight_; }\n            double & RMSHeight() noexcept {return RMSHeight_; }\n            double CorrLength() const noexcept {return CorrLength_; }\n            double & CorrLength() noexcept {return CorrLength_; }\n            double alpha() const noexcept {return alpha_; }\n    };\n\n    class ExpSetup\n    {\n        private:\n            double wl_, inc_ang_, src_dist_, det_dist_, src_l_;\n            Surface surf_;\n            std::vector<Sphere> sphs_;\n        public:\n            ExpSetup (double inc_ang = 0.0, double RMSHeight = Constants::RMSHeight, double CorrLength = Constants::CorrLength) :\n            surf_(Surface(RMSHeight, CorrLength)), sphs_(std::vector<Sphere>{Sphere(0.0, 0.0, ExpGeometry::rho, ExpGeometry::rho, ExpGeometry::d, Sphere::LOWER)}), inc_ang_(inc_ang),\n            wl_(Constants::WL), src_dist_(ExpGeometry::l1), det_dist_(ExpGeometry::l2), src_l_(ExpGeometry::L) {}\n\n            const Sphere & substrate() const noexcept {return sphs_.front(); }\n            Sphere & substrate() noexcept {return sphs_.front(); }\n            const std::vector<Sphere> & spheres() const noexcept {return sphs_; }\n            const Surface & surface() const noexcept {return surf_; }\n            Surface & surface() noexcept {return surf_; }\n            const double & IncAngle() const noexcept {return inc_ang_; }\n            double & IncAngle() noexcept {return inc_ang_; }\n            const double wavelength() const noexcept {return wl_; }\n            const double source_distance() const noexcept {return src_dist_; }\n            const double source_length() const noexcept {return src_l_; }\n            const double detector_distance() const noexcept {return det_dist_; }\n            void add_sphere(const Sphere & sph) noexcept {sphs_.emplace_back(sph); }\n            void add_sphere(double x, double y, double height, double radius) noexcept;\n            void add_sphere(const std::vector<Sphere> & sphs) noexcept {sphs_.insert(sphs_.end(), sphs.cbegin(), sphs.cend()); }\n            void add_sphere(const std::vector<double> & x, const std::vector<double> & y, const std::vector<double> & height, const std::vector<double> & radius);\n            void reset_sphere() noexcept {if(sphs_.size() > 1) sphs_.erase(sphs_.cbegin() + 1,sphs_.cend()); }\n    };\n\n    class Beam : public Line\n    {\n        private:\n            static constexpr double intersect_limit = 1e-8;\n        public:\n            using Line::Line;\n            double Delta (const Sphere & sph) const noexcept;\n            std::vector<SphPoint> Intersect(const Sphere & sph) const;\n            std::vector<SphPoint> Intersect(const std::vector<Sphere> & sphs) const;\n            bool is_intersect (const Sphere & sph) const noexcept;\n            bool is_intersect (const std::vector<Sphere> & sphs) const noexcept;\n            double IncAng (const SphPoint & spt) const;\n            Vector SpecVec (const SphPoint & spt) const;\n            virtual Vector ScatVec(const SphPoint & pt, const Surface & surf, double wl) const = 0;\n    };\n\n    class Beam2D : public Beam\n    {\n        public:\n            using Beam::Beam;\n            virtual Vector ScatVec(const SphPoint & spt, const Surface & surf, double wl) const override;\n    };\n\n    class SphBeam2D : public Beam2D\n    {\n        public:\n            using Beam2D::Beam2D;\n            SphBeam2D (const Sphere & sph, double inc_ang, double src_dist);\n            SphBeam2D (const ExpSetup & setup) : SphBeam2D(setup.substrate(), setup.IncAngle(), setup.source_distance()) {}\n    };\n\n    class PlaneBeam2D : public Beam2D\n    {\n        public:\n            using Beam2D::Beam2D;\n            PlaneBeam2D (const Sphere & sph, double inc_ang, double src_dist);\n            PlaneBeam2D (const ExpSetup & setup) : PlaneBeam2D(setup.substrate(), setup.IncAngle(), setup.source_distance()) {}\n    };\n\n    class Beam3D : public Beam\n    {\n        public:\n            using Beam::Beam;\n            virtual Vector ScatVec(const SphPoint & spt, const Surface & surf, double wl) const override;\n    };\n\n    class SphBeam3D : public Beam3D\n    {\n        public:\n            using Beam3D::Beam3D;\n            SphBeam3D(const Sphere & sph, double inc_ang, double src_dist, double src_len);\n            SphBeam3D(const ExpSetup & setup) : SphBeam3D(setup.substrate(), setup.IncAngle(), setup.source_distance(), setup.source_length()) {}\n    };\n\n    class PlaneBeam3D : public Beam3D\n    {\n        public:\n            using Beam3D::Beam3D;\n            PlaneBeam3D(const Sphere & sph, double inc_ang, double src_dist);\n            PlaneBeam3D(const ExpSetup & setup) : PlaneBeam3D(setup.substrate(), setup.IncAngle(), setup.source_distance()) {}\n    };\n\n    class TestBeam3D : public Beam3D\n    {\n        public:\n            using Beam3D::Beam3D;\n            TestBeam3D(const Sphere & sph, double h, double src_dist);\n            TestBeam3D(const ExpSetup & setup, double h) : TestBeam3D(setup.substrate(), h, setup.source_distance()) {}\n    };\n\n    struct TracePoint\n    {\n        Point det_point;\n        bool is_scattered;\n        bool is_transmitted;\n        TracePoint (const Point & pt, bool is_tr, bool is_sc) : det_point(pt), is_transmitted(is_tr), is_scattered(is_sc) {}\n    };\n\n    class Trace\n    {\n        private:\n            std::vector<std::unique_ptr<Beam>> trace_;\n            bool is_transmitted_ {};\n            bool is_scattered_ {};\n        public:\n            using iterator = boost::indirect_iterator<std::vector<std::unique_ptr<Beam>>::iterator>;\n            using const_iterator = boost::indirect_iterator<std::vector<std::unique_ptr<Beam>>::const_iterator>;\n            iterator begin() {return iterator(trace_.begin()); }\n            iterator end() {return iterator(trace_.end()); }\n            const_iterator begin() const {return const_iterator(trace_.begin()); }\n            const_iterator end() const {return const_iterator(trace_.end()); }\n\n            template <typename T, typename Object>\n            Trace (T && line, const Surface & surf, const Object & sphs, double wl)\n            {\n                trace_.emplace_back(std::make_unique<std::decay_t<T>>(std::forward<T>(line)));\n                is_transmitted_ = trace_.back()->is_intersect(sphs); \n                if (is_transmitted_)\n                {\n                    double sw = setup::dist(setup::gen);\n                    auto spts = trace_.back()->Intersect(sphs);\n                    assert(spts.size() != 0);\n                    auto next_spt_ = *std::min_element(spts.cbegin(), spts.cend(), [](const SphPoint & a, const SphPoint & b) {return a.point().y() < b.point().y(); });\n                    is_transmitted_ = sw < surf.Rf(trace_.back()->IncAng(next_spt_), wl);\n                    while (is_transmitted_)\n                    {\n                        if (sw < surf.TIS(trace_.back()->IncAng(next_spt_), surf.RMSHeight(), surf.CorrLength(), surf.alpha(), wl))\n                        {\n                            trace_.emplace_back(std::make_unique<std::decay_t<T>>(next_spt_.point(), trace_.back()->ScatVec(next_spt_, surf, wl)));\n                            is_scattered_ = true;\n                        }\n                        else\n                            trace_.emplace_back(std::make_unique<std::decay_t<T>>(next_spt_.point(), trace_.back()->SpecVec(next_spt_)));\n                        spts = trace_.back()->Intersect(sphs);\n                        if (spts.size() == 0)\n                            break;\n                        next_spt_ = *std::min_element(spts.cbegin(), spts.cend(), [](const SphPoint & a, const SphPoint & b) {return a.point().y() < b.point().y(); });\n                        sw = setup::dist(setup::gen);\n                        is_transmitted_ = sw < surf.Rf(trace_.back()->IncAng(next_spt_), wl);\n                    }  \n                }\n            }\n\n            template <typename T>\n            Trace (T && line, const ExpSetup & setup) : Trace(std::forward<T>(line), setup.surface(), setup.spheres(), setup.wavelength()) {}\n\n            TracePoint det_res(double det_dist) const noexcept;\n            bool is_transmitted() const noexcept {return is_transmitted_; }\n            bool is_scattered() const noexcept {return is_scattered_; }\n            int size() const noexcept {return trace_.size(); }\n    };\n\n    template <typename T>\n    Trace make_trace(const ExpSetup & setup)\n    {\n        return Trace (T(setup), setup);\n    }\n\n}\n\n#endif", "meta": {"hexsha": "e13edd8a907df4dd1800c068079cda12ee91534b", "size": 11175, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "headers/trace.hpp", "max_stars_repo_name": "simply-nicky/raytrace", "max_stars_repo_head_hexsha": "ee7ccfb8b93876809283db7b24cedf2cb6ceb230", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "headers/trace.hpp", "max_issues_repo_name": "simply-nicky/raytrace", "max_issues_repo_head_hexsha": "ee7ccfb8b93876809283db7b24cedf2cb6ceb230", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "headers/trace.hpp", "max_forks_repo_name": "simply-nicky/raytrace", "max_forks_repo_head_hexsha": "ee7ccfb8b93876809283db7b24cedf2cb6ceb230", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.8883928571, "max_line_length": 182, "alphanum_fraction": 0.5721700224, "num_tokens": 2655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.445583785348705}}
{"text": "#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <iostream>\n#include <numeric>\n#include <sps/plane.hpp>\n#include <vector>\n\n// This implementation is general but slow because it needs to solve linear systems. It is possible to implement this\n// function much faster for specific plane types.\nEigen::VectorXd sps::AbstractPlane::CalcParameters(const Eigen::Vector2d& coords) const\n{\n    const Eigen::Vector2d              g_c(+0.0, +0.0);\n    const std::vector<Eigen::Vector2d> g = {\n        {-1.0, -1.0},\n        {+1.0, -1.0},\n        {+1.0, +1.0},\n        {-1.0, +1.0},\n    };\n\n    const auto vertex_indices = [&]() -> std::pair<unsigned, unsigned> {\n        if (coords(0) >= coords(1) && coords(0) <= -coords(1))\n        {\n            return {0, 1};\n        }\n        if (coords(0) >= coords(1) && coords(0) >= -coords(1))\n        {\n            return {1, 2};\n        }\n        if (coords(0) <= coords(1) && coords(0) >= -coords(1))\n        {\n            return {2, 3};\n        }\n        if (coords(0) <= coords(1) && coords(0) <= -coords(1))\n        {\n            return {3, 0};\n        }\n\n        assert(false);\n        return {0, 0};\n    }();\n\n    // Prepare to calculate the barycentric coordinates\n    const Eigen::Matrix3d R = [&]() {\n        Eigen::Matrix3d R = Eigen::Matrix3d::Ones();\n\n        R.block<2, 1>(0, 0) = g_c;\n        R.block<2, 1>(0, 1) = g[std::get<0>(vertex_indices)];\n        R.block<2, 1>(0, 2) = g[std::get<1>(vertex_indices)];\n\n        return R;\n    }();\n    const Eigen::Vector3d r(coords(0), coords(1), 1.0);\n\n    // Find the barycentric coordinates\n    const Eigen::Vector3d barycentric_coords = Eigen::FullPivLU<Eigen::Matrix3d>(R).solve(r);\n\n    return barycentric_coords(0) * m_center + barycentric_coords(1) * m_vertices[std::get<0>(vertex_indices)] +\n           barycentric_coords(2) * m_vertices[std::get<1>(vertex_indices)];\n}\n\nEigen::VectorXd sps::AbstractPlane::CalcGridParameters(const GridCellIndex&              grid_cell,\n                                                       const unsigned int                num_candidates,\n                                                       const double                      inter_level_scale,\n                                                       const std::vector<GridCellIndex>& prev_grid_cells) const\n{\n    assert(num_candidates % 2 == 1);\n\n    const int    grid_radius         = (num_candidates - 1) / 2;\n    const double grid_to_coord_scale = (1.0 / static_cast<double>(grid_radius));\n\n    // Find the coordinates in the top-level grid coordinate system\n    auto zoom_transform = Eigen::Affine2d::Identity();\n    for (auto& prev_grid_cell : prev_grid_cells)\n    {\n        const auto prev_unscaled_grid_coords = Eigen::Vector2d(static_cast<double>(std::get<0>(prev_grid_cell)),\n                                                               static_cast<double>(std::get<1>(prev_grid_cell)));\n        const auto center                    = grid_to_coord_scale * prev_unscaled_grid_coords;\n        zoom_transform =\n            zoom_transform * Eigen::Translation2d(center) * Eigen::UniformScaling<double>(inter_level_scale);\n    }\n    const auto unscaled_grid_coords =\n        Eigen::Vector2d(static_cast<double>(std::get<0>(grid_cell)), static_cast<double>(std::get<1>(grid_cell)));\n    const Eigen::Vector2d finest_level_coords   = grid_to_coord_scale * unscaled_grid_coords;\n    const Eigen::Vector2d coarsest_level_coords = zoom_transform * finest_level_coords;\n\n    return CalcParameters(coarsest_level_coords);\n}\n\ndouble sps::AbstractPlane::CalcArea() const\n{\n    const auto triangle_area_evaluator =\n        [](const Eigen::VectorXd& v_0, const Eigen::VectorXd& v_1, const Eigen::VectorXd& v_2) {\n            const Eigen::VectorXd r_0      = v_1 - v_0;\n            const Eigen::VectorXd r_1      = v_2 - v_0;\n            const double          dot_prod = r_0.dot(r_1);\n\n            return 0.5 * std::sqrt(r_0.squaredNorm() * r_1.squaredNorm() - dot_prod * dot_prod);\n        };\n\n    std::array<double, 4> areas;\n\n    areas[0] = triangle_area_evaluator(m_center, m_vertices[0], m_vertices[1]);\n    areas[1] = triangle_area_evaluator(m_center, m_vertices[1], m_vertices[2]);\n    areas[2] = triangle_area_evaluator(m_center, m_vertices[2], m_vertices[3]);\n    areas[3] = triangle_area_evaluator(m_center, m_vertices[3], m_vertices[0]);\n\n    return std::accumulate(areas.begin(), areas.end(), 0.0);\n}\n", "meta": {"hexsha": "98e2d8587bda462615260957941fade0ae5cf9f7", "size": 4398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sps/src/plane.cpp", "max_stars_repo_name": "yuki-koyama/sequential-gallery", "max_stars_repo_head_hexsha": "693d7c061377580522c454c789750fa25a468967", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T11:07:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T07:55:45.000Z", "max_issues_repo_path": "sps/src/plane.cpp", "max_issues_repo_name": "yuki-koyama/sequential-gallery", "max_issues_repo_head_hexsha": "693d7c061377580522c454c789750fa25a468967", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sps/src/plane.cpp", "max_forks_repo_name": "yuki-koyama/sequential-gallery", "max_forks_repo_head_hexsha": "693d7c061377580522c454c789750fa25a468967", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-10T03:03:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T16:01:26.000Z", "avg_line_length": 40.3486238532, "max_line_length": 117, "alphanum_fraction": 0.5891314234, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117898012104, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4455837830475361}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <cppad/cppad.hpp>\n\n// copy of eigen_mat_inv from CppAD to make the reverse pass codegen compatible (not assume double scalar)\n\nnamespace tds {\ntemplate <class Base>\nclass atomic_eigen_mat_inv : public CppAD::atomic_base<Base> {\n public:\n  // -----------------------------------------------------------\n  // type of elements during calculation of derivatives\n  typedef Base scalar;\n  // type of elements during taping\n  typedef CppAD::AD<scalar> ad_scalar;\n  // type of matrix during calculation of derivatives\n  typedef Eigen::Matrix<scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n      matrix;\n  // type of matrix during taping\n  typedef Eigen::Matrix<ad_scalar, Eigen::Dynamic, Eigen::Dynamic,\n                        Eigen::RowMajor>\n      ad_matrix;\n  /* %$$\n  $subhead Constructor$$\n  $srccode%cpp% */\n  // constructor\n  atomic_eigen_mat_inv(void)\n      : CppAD::atomic_base<Base>(\"atom_eigen_mat_inv\",\n                                 CppAD::atomic_base<Base>::set_sparsity_enum) {}\n  /* %$$\n  $subhead op$$\n  $srccode%cpp% */\n  // use atomic operation to invert an AD matrix\n  ad_matrix op(const ad_matrix& arg) {\n    size_t nr = size_t(arg.rows());\n    size_t ny = nr * nr;\n    size_t nx = 1 + ny;\n    assert(nr == size_t(arg.cols()));\n    // -------------------------------------------------------------------\n    // packed version of arg\n    CPPAD_TESTVECTOR(ad_scalar) packed_arg(nx);\n    packed_arg[0] = ad_scalar(nr);\n    for (size_t i = 0; i < ny; i++) packed_arg[1 + i] = arg.data()[i];\n    // -------------------------------------------------------------------\n    // packed version of result = arg^{-1}.\n    // This is an atomic_base function call that CppAD uses to\n    // store the atomic operation on the tape.\n    CPPAD_TESTVECTOR(ad_scalar) packed_result(ny);\n    (*this)(packed_arg, packed_result);\n    // -------------------------------------------------------------------\n    // unpack result matrix\n    ad_matrix result(nr, nr);\n    for (size_t i = 0; i < ny; i++) result.data()[i] = packed_result[i];\n    return result;\n  }\n  /* %$$\n$head Private$$\n\n$subhead Variables$$\n$srccode%cpp% */\n private:\n  // -------------------------------------------------------------\n  // one forward mode vector of matrices for argument and result\n  CppAD::vector<matrix> f_arg_, f_result_;\n  // one reverse mode vector of matrices for argument and result\n  CppAD::vector<matrix> r_arg_, r_result_;\n  // -------------------------------------------------------------\n  /* %$$\n  $subhead forward$$\n  $srccode%cpp% */\n  // forward mode routine called by CppAD\n  virtual bool forward(\n      // lowest order Taylor coefficient we are evaluating\n      size_t p,\n      // highest order Taylor coefficient we are evaluating\n      size_t q,\n      // which components of x are variables\n      const CppAD::vector<bool>& vx,\n      // which components of y are variables\n      CppAD::vector<bool>& vy,\n      // tx [ j * (q+1) + k ] is x_j^k\n      const CppAD::vector<scalar>& tx,\n      // ty [ i * (q+1) + k ] is y_i^k\n      CppAD::vector<scalar>& ty) {\n    size_t n_order = q + 1;\n    size_t nr = size_t(CppAD::Integer(tx[0 * n_order + 0]));\n    size_t ny = nr * nr;\n#ifndef NDEBUG\n    size_t nx = 1 + ny;\n#endif\n    assert(vx.size() == 0 || nx == vx.size());\n    assert(vx.size() == 0 || ny == vy.size());\n    assert(nx * n_order == tx.size());\n    assert(ny * n_order == ty.size());\n    //\n    // -------------------------------------------------------------------\n    // make sure f_arg_ and f_result_ are large enough\n    assert(f_arg_.size() == f_result_.size());\n    if (f_arg_.size() < n_order) {\n      f_arg_.resize(n_order);\n      f_result_.resize(n_order);\n      //\n      for (size_t k = 0; k < n_order; k++) {\n        f_arg_[k].resize(long(nr), long(nr));\n        f_result_[k].resize(long(nr), long(nr));\n      }\n    }\n    // -------------------------------------------------------------------\n    // unpack tx into f_arg_\n    for (size_t k = 0; k < n_order; k++) {  // unpack arg values for this order\n      for (size_t i = 0; i < ny; i++)\n        f_arg_[k].data()[i] = tx[(1 + i) * n_order + k];\n    }\n    // -------------------------------------------------------------------\n    // result for each order\n    // (we could avoid recalculting f_result_[k] for k=0,...,p-1)\n    //\n    f_result_[0] = f_arg_[0].inverse();\n    for (size_t k = 1; k < n_order; k++) {  // initialize sum\n      matrix f_sum = matrix::Zero(long(nr), long(nr));\n      // compute sum\n      for (size_t ell = 1; ell <= k; ell++)\n        f_sum -= f_arg_[ell] * f_result_[k - ell];\n      // result_[k] = arg_[0]^{-1} * sum_\n      f_result_[k] = f_result_[0] * f_sum;\n    }\n    // -------------------------------------------------------------------\n    // pack result_ into ty\n    for (size_t k = 0; k < n_order; k++) {\n      for (size_t i = 0; i < ny; i++)\n        ty[i * n_order + k] = f_result_[k].data()[i];\n    }\n    // -------------------------------------------------------------------\n    // check if we are computing vy\n    if (vx.size() == 0) return true;\n    // ------------------------------------------------------------------\n    // This is a very dumb algorithm that over estimates which\n    // elements of the inverse are variables (which is not efficient).\n    bool var = false;\n    for (size_t i = 0; i < ny; i++) var |= vx[1 + i];\n    for (size_t i = 0; i < ny; i++) vy[i] = var;\n    return true;\n  }\n  /* %$$\n  $subhead reverse$$\n  $srccode%cpp% */\n  // reverse mode routine called by CppAD\n  virtual bool reverse(\n      // highest order Taylor coefficient that we are computing derivative of\n      size_t q,\n      // forward mode Taylor coefficients for x variables\n      const CppAD::vector<Base>& tx,\n      // forward mode Taylor coefficients for y variables\n      const CppAD::vector<Base>& ty,\n      // upon return, derivative of G[ F[ {x_j^k} ] ] w.r.t {x_j^k}\n      CppAD::vector<Base>& px,\n      // derivative of G[ {y_i^k} ] w.r.t. {y_i^k}\n      const CppAD::vector<Base>& py) {\n    size_t n_order = q + 1;\n    size_t nr = size_t(CppAD::Integer(tx[0 * n_order + 0]));\n    size_t ny = nr * nr;\n#ifndef NDEBUG\n    size_t nx = 1 + ny;\n#endif\n    //\n    assert(nx * n_order == tx.size());\n    assert(ny * n_order == ty.size());\n    assert(px.size() == tx.size());\n    assert(py.size() == ty.size());\n    // -------------------------------------------------------------------\n    // make sure f_arg_ is large enough\n    assert(f_arg_.size() == f_result_.size());\n    // must have previous run forward with order >= n_order\n    assert(f_arg_.size() >= n_order);\n    // -------------------------------------------------------------------\n    // make sure r_arg_, r_result_ are large enough\n    assert(r_arg_.size() == r_result_.size());\n    if (r_arg_.size() < n_order) {\n      r_arg_.resize(n_order);\n      r_result_.resize(n_order);\n      //\n      for (size_t k = 0; k < n_order; k++) {\n        r_arg_[k].resize(long(nr), long(nr));\n        r_result_[k].resize(long(nr), long(nr));\n      }\n    }\n    // -------------------------------------------------------------------\n    // unpack tx into f_arg_\n    for (size_t k = 0; k < n_order; k++) {  // unpack arg values for this order\n      for (size_t i = 0; i < ny; i++)\n        f_arg_[k].data()[i] = tx[(1 + i) * n_order + k];\n    }\n    // -------------------------------------------------------------------\n    // unpack py into r_result_\n    for (size_t k = 0; k < n_order; k++) {\n      for (size_t i = 0; i < ny; i++)\n        r_result_[k].data()[i] = py[i * n_order + k];\n    }\n    // -------------------------------------------------------------------\n    // initialize r_arg_ as zero\n    for (size_t k = 0; k < n_order; k++)\n      r_arg_[k] = matrix::Zero(long(nr), long(nr));\n    // -------------------------------------------------------------------\n    // matrix reverse mode calculation\n    //\n    for (size_t k1 = n_order; k1 > 1; k1--) {\n      size_t k = k1 - 1;\n      // bar{R}_0 = bar{R}_0 + bar{R}_k (A_0 R_k)^T\n      r_result_[0] +=\n          r_result_[k] * f_result_[k].transpose() * f_arg_[0].transpose();\n      //\n      for (size_t ell = 1; ell <= k;\n           ell++) {  // bar{A}_l = bar{A}_l - R_0^T bar{R}_k R_{k-l}^T\n        r_arg_[ell] -= f_result_[0].transpose() * r_result_[k] *\n                       f_result_[k - ell].transpose();\n        // bar{R}_{k-l} = bar{R}_{k-1} - (R_0 A_l)^T bar{R}_k\n        r_result_[k - ell] -=\n            f_arg_[ell].transpose() * f_result_[0].transpose() * r_result_[k];\n      }\n    }\n    r_arg_[0] -=\n        f_result_[0].transpose() * r_result_[0] * f_result_[0].transpose();\n    // -------------------------------------------------------------------\n    // pack r_arg into px\n    for (size_t k = 0; k < n_order; k++) {\n      for (size_t i = 0; i < ny; i++)\n        px[(1 + i) * n_order + k] = r_arg_[k].data()[i];\n    }\n    //\n    return true;\n  }\n};\n}  // namespace tds", "meta": {"hexsha": "1d8282a1dd21a8fe8c7c33350a71733412ad88e7", "size": 8960, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/cppad/eigen_mat_inv.hpp", "max_stars_repo_name": "slowy07/tiny-differentiable-simulator", "max_stars_repo_head_hexsha": "209f937f4d69ad5749703c1057471985f70daddb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 862.0, "max_stars_repo_stars_event_min_datetime": "2020-05-14T19:22:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T20:23:24.000Z", "max_issues_repo_path": "src/math/cppad/eigen_mat_inv.hpp", "max_issues_repo_name": "slowy07/tiny-differentiable-simulator", "max_issues_repo_head_hexsha": "209f937f4d69ad5749703c1057471985f70daddb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 82.0, "max_issues_repo_issues_event_min_datetime": "2020-05-26T11:41:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T16:46:00.000Z", "max_forks_repo_path": "src/math/cppad/eigen_mat_inv.hpp", "max_forks_repo_name": "slowy07/tiny-differentiable-simulator", "max_forks_repo_head_hexsha": "209f937f4d69ad5749703c1057471985f70daddb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 93.0, "max_forks_repo_forks_event_min_datetime": "2020-05-15T05:37:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T09:09:50.000Z", "avg_line_length": 38.1276595745, "max_line_length": 106, "alphanum_fraction": 0.4877232143, "num_tokens": 2404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.4454466121945236}}
{"text": "#include <scitbx/array_family/boost_python/flex_fwd.h>\n\n#include <boost/python/module.hpp>\n#include <boost/python/def.hpp>\n#include <boost/python/args.hpp>\n#include <scitbx/array_family/boost_python/utils.h>\n#include <scitbx/array_family/versa.h>\n#include <scitbx/array_family/accessors/c_grid.h>\n#include <string>\n\n#include <fftw3.h>\n\nnamespace {\n\n  namespace af = scitbx::af;\n\n  void\n  complex_to_complex_in_place(\n    af::ref<std::complex<double> > const& data,\n    int exp_sign)\n  {\n    SCITBX_ASSERT(exp_sign == FFTW_FORWARD || exp_sign == FFTW_BACKWARD);\n    int n = static_cast<int>(data.size());\n    fftw_complex *in = reinterpret_cast<fftw_complex*>(data.begin());\n    fftw_plan p = fftw_plan_dft_1d(\n      n, in, in, exp_sign, FFTW_ESTIMATE);\n    fftw_execute(p);\n    fftw_destroy_plan(p);\n  }\n\n  void\n  complex_to_complex_3d_in_place(\n    af::ref<std::complex<double>, af::c_grid<3> > const& data,\n    int exp_sign)\n  {\n    SCITBX_ASSERT(exp_sign == FFTW_FORWARD || exp_sign == FFTW_BACKWARD);\n    int nx = static_cast<int>(data.accessor()[0]);\n    int ny = static_cast<int>(data.accessor()[1]);\n    int nz = static_cast<int>(data.accessor()[2]);\n    fftw_complex *in = reinterpret_cast<fftw_complex*>(data.begin());\n    fftw_plan p = fftw_plan_dft_3d(\n      nx, ny, nz, in, in, exp_sign, FFTW_ESTIMATE);\n    fftw_execute(p);\n    fftw_destroy_plan(p);\n  }\n\n  af::versa<std::complex<double>, af::flex_grid<> >\n  real_to_complex_in_place(\n    af::versa<double, af::flex_grid<> >& data)\n  {\n    af::boost_python::assert_0_based_1d(data.accessor());\n    int m = static_cast<int>(data.accessor().all()[0]);\n    int n = static_cast<int>(data.accessor().focus()[0]);\n    SCITBX_ASSERT(m == 2*(n/2+1));\n    double* in = data.begin();\n    fftw_complex *out = reinterpret_cast<fftw_complex*>(in);\n    fftw_plan p = fftw_plan_dft_r2c_1d(\n      n, in, out, FFTW_ESTIMATE);\n    fftw_execute(p);\n    fftw_destroy_plan(p);\n    return af::versa<std::complex<double>, af::flex_grid<> >(\n      data.handle(), af::flex_grid<>(m/2));\n  }\n\n  af::versa<double, af::flex_grid<> >\n  complex_to_real_in_place(\n    af::versa<std::complex<double>, af::flex_grid<> >& data,\n    int n)\n  {\n    af::boost_python::assert_0_based_1d(data.accessor());\n    SCITBX_ASSERT(!data.accessor().is_padded());\n    int m = static_cast<int>(data.accessor().all()[0]) * 2;\n    SCITBX_ASSERT(m == 2*(n/2+1));\n    fftw_complex *in = reinterpret_cast<fftw_complex*>(data.begin());\n    double* out = reinterpret_cast<double*>(in);\n    fftw_plan p = fftw_plan_dft_c2r_1d(\n      n, in, out, FFTW_ESTIMATE);\n    fftw_execute(p);\n    fftw_destroy_plan(p);\n    return af::versa<double, af::flex_grid<> >(\n      data.handle(), af::flex_grid<>(m).set_focus(n));\n  }\n\n  af::versa<std::complex<double>, af::flex_grid<> >\n  real_to_complex_3d_in_place(\n    af::versa<double, af::flex_grid<> >& data)\n  {\n    af::boost_python::assert_0_based_3d(data.accessor());\n    int mx = static_cast<int>(data.accessor().all()[0]);\n    int my = static_cast<int>(data.accessor().all()[1]);\n    int mz = static_cast<int>(data.accessor().all()[2]);\n    int nx = static_cast<int>(data.accessor().focus()[0]);\n    int ny = static_cast<int>(data.accessor().focus()[1]);\n    int nz = static_cast<int>(data.accessor().focus()[2]);\n    SCITBX_ASSERT(mx == nx);\n    SCITBX_ASSERT(my == ny);\n    SCITBX_ASSERT(mz == 2*(nz/2+1));\n    double* in = data.begin();\n    fftw_complex *out = reinterpret_cast<fftw_complex*>(in);\n    fftw_plan p = fftw_plan_dft_r2c_3d(\n      nx, ny, nz, in, out, FFTW_ESTIMATE);\n    fftw_execute(p);\n    fftw_destroy_plan(p);\n    return af::versa<std::complex<double>, af::flex_grid<> >(\n      data.handle(),\n      af::flex_grid<>((af::adapt(af::tiny<int, 3>(mx,my,mz/2)))));\n  }\n\n  af::versa<double, af::flex_grid<> >\n  complex_to_real_3d_in_place(\n    af::versa<std::complex<double>, af::flex_grid<> >& data,\n    af::tiny<int, 3> const& n)\n  {\n    af::boost_python::assert_0_based_3d(data.accessor());\n    SCITBX_ASSERT(!data.accessor().is_padded());\n    int mx = static_cast<int>(data.accessor().all()[0]);\n    int my = static_cast<int>(data.accessor().all()[1]);\n    int mz = static_cast<int>(data.accessor().all()[2]) * 2;\n    int nx = n[0];\n    int ny = n[1];\n    int nz = n[2];\n    SCITBX_ASSERT(mx == nx);\n    SCITBX_ASSERT(my == ny);\n    SCITBX_ASSERT(mz == 2*(nz/2+1));\n    fftw_complex *in = reinterpret_cast<fftw_complex*>(data.begin());\n    double* out = reinterpret_cast<double*>(in);\n    fftw_plan p = fftw_plan_dft_c2r_3d(\n      nx, ny, nz, in, out, FFTW_ESTIMATE);\n    fftw_execute(p);\n    fftw_destroy_plan(p);\n    return af::versa<double, af::flex_grid<> >(\n      data.handle(),\n      af::flex_grid<>((af::adapt(af::tiny<int, 3>(nx,ny,mz))))\n        .set_focus(af::adapt(n)));\n  }\n\n  void\n  wrap_fftw3()\n  {\n    using namespace boost::python;\n    scope().attr(\"fftw_version\") = std::string(fftw_version);\n    def(\"complex_to_complex_in_place\", complex_to_complex_in_place, (\n      arg(\"data\"), arg(\"exp_sign\")));\n    def(\"complex_to_complex_3d_in_place\", complex_to_complex_3d_in_place, (\n      arg(\"data\"), arg(\"exp_sign\")));\n    def(\"real_to_complex_in_place\", real_to_complex_in_place, (\n      arg(\"data\")));\n    def(\"complex_to_real_in_place\", complex_to_real_in_place, (\n      arg(\"data\"), arg(\"n\")));\n    def(\"real_to_complex_3d_in_place\", real_to_complex_3d_in_place, (\n      arg(\"data\")));\n    def(\"complex_to_real_3d_in_place\", complex_to_real_3d_in_place, (\n      arg(\"data\"), arg(\"n\")));\n  }\n\n} // namespace <anonymous>\n\nBOOST_PYTHON_MODULE(fftw3tbx_ext)\n{\n  wrap_fftw3();\n}\n", "meta": {"hexsha": "70b2e570d1080109426c2050f97aafba90340b1b", "size": 5558, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fftw3tbx/ext.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "fftw3tbx/ext.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "fftw3tbx/ext.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 34.3086419753, "max_line_length": 75, "alphanum_fraction": 0.6518531846, "num_tokens": 1677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4453361483100427}}
{"text": "#define ARMA_DONT_PRINT_ERRORS\n\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <armadillo>\n\nnamespace py = pybind11;\n\nusing namespace arma;\n\n\ntypedef py::array_t<double, py::array::f_style | py::array::forcecast> array_tf;\ntypedef py::array_t<double, py::array::c_style | py::array::forcecast> array_tc;\n\n\ncube array_to_cube(array_tf m) {\n\n    py::buffer_info _m_buff = m.request();\n    int n_rows = _m_buff.shape[0];\n    int n_cols = _m_buff.shape[1];\n    int n_slices = _m_buff.shape[2];\n\n    cube _m_arma((double *)_m_buff.ptr, n_rows, n_cols, n_slices);\n\n    return _m_arma;\n}\n\n\nmat array_to_mat(array_tf m) {\n\n    py::buffer_info _m_buff = m.request();\n    int n_rows = _m_buff.shape[0];\n    int n_cols = _m_buff.shape[1];\n\n    mat _m_arma((double *)_m_buff.ptr, n_rows, n_cols);\n\n    return _m_arma;\n}\n\n\nvec array_to_vec(array_tf m) {\n\n    py::buffer_info _m_buff = m.request();\n    int n_rows = _m_buff.shape[0];\n\n    vec _m_vec((double *)_m_buff.ptr, n_rows);\n\n    return _m_vec;\n}\n\n\narray_tf cube_to_array(cube m) {\n\n    auto _m_array = array_tf({m.n_rows, m.n_cols, m.n_slices});\n\n    py::buffer_info _m_buff = _m_array.request();\n    std::memcpy(_m_buff.ptr, m.memptr(), sizeof(double) * m.n_rows * m.n_cols * m.n_slices);\n\n    return _m_array;\n}\n\n\narray_tf mat_to_array(mat m) {\n\n    auto _m_array = array_tf({m.n_rows, m.n_cols});\n\n    py::buffer_info _m_buff = _m_array.request();\n    std::memcpy(_m_buff.ptr, m.memptr(), sizeof(double) * m.n_rows * m.n_cols);\n\n    return _m_array;\n}\n\n\narray_tf vec_to_array(vec m) {\n\n    auto _m_array = array_tf({m.n_rows});\n\n    py::buffer_info _m_buff = _m_array.request();\n    std::memcpy(_m_buff.ptr, m.memptr(), sizeof(double) * m.n_rows);\n\n    return _m_array;\n}\n\n\npy::tuple policy_divergence(array_tf _p_K, array_tf _p_kff, array_tf _p_sigma_ctl,\n                            array_tf _q_K, array_tf _q_kff, array_tf _q_sigma_ctl,\n                            array_tf _mu_x, array_tf _sigma_x,\n                            int dm_state, int dm_act, int nb_steps) {\n\n    cube p_K = array_to_cube(_p_K);\n    mat p_kff = array_to_mat(_p_kff);\n    cube p_sigma_ctl = array_to_cube(_p_sigma_ctl);\n\n    cube q_K = array_to_cube(_q_K);\n    mat q_kff = array_to_mat(_q_kff);\n    cube q_sigma_ctl = array_to_cube(_q_sigma_ctl);\n\n    mat mu_x  = array_to_mat(_mu_x);\n    cube sigma_x = array_to_cube(_sigma_x);\n\n    vec kl(nb_steps);\n\n    for(int i = 0; i < nb_steps; i++) {\n        mat q_lambda_ctl = inv_sympd(q_sigma_ctl.slice(i));\n\n        mat diff_K = (q_K.slice(i) - p_K.slice(i)).t() * q_lambda_ctl * (q_K.slice(i) - p_K.slice(i));\n        mat diff_crs = (q_K.slice(i) - p_K.slice(i)).t() * q_lambda_ctl * (- q_kff.col(i) + p_kff.col(i));\n        mat diff_kff = (- q_kff.col(i) + p_kff.col(i)).t() * q_lambda_ctl * (- q_kff.col(i) + p_kff.col(i));\n\n        kl(i) = as_scalar(0.5 * log( det(q_sigma_ctl.slice(i)) / det(p_sigma_ctl.slice(i)) )\n\t\t                  + 0.5 * trace(q_lambda_ctl * p_sigma_ctl.slice(i))\n\t\t                  - 0.5 * dm_act\n\t\t                  + 0.5 * trace(diff_K * sigma_x.slice(i))\n\t\t                  + 0.5 * mu_x.col(i).t() * diff_K * mu_x.col(i)\n\t\t                  - mu_x.col(i).t() * diff_crs\n\t\t                  + 0.5 * diff_kff);\n    }\n\n    array_tf _kl = vec_to_array(kl);\n\n    py::tuple output = py::make_tuple(_kl);\n    return output;\n}\n\npy::tuple gaussian_divergence(array_tf _mu_p, array_tf _sigma_p,\n                              array_tf _mu_q, array_tf _sigma_q,\n                              int dm_state, int nb_steps) {\n\n    mat mu_p = array_to_mat(_mu_p);\n    cube sigma_p = array_to_cube(_sigma_p);\n\n    mat mu_q = array_to_mat(_mu_q);\n    cube sigma_q = array_to_cube(_sigma_q);\n\n    vec kl(nb_steps);\n\n    for(int i = 0; i < nb_steps; i++) {\n        mat lambda_q = inv_sympd(sigma_q.slice(i));\n\n        vec diff = mu_q.col(i) - mu_p.col(i);\n        double quad = as_scalar(diff.t() * lambda_q * diff);\n        double _trace = as_scalar(trace(lambda_q * sigma_p.slice(i)));\n        double log_det = as_scalar(log( det(sigma_q.slice(i)) / det(sigma_p.slice(i)) ));\n\n        kl(i) = 0.5 * (_trace + quad + log_det - dm_state);\n    }\n\n    array_tf _kl = vec_to_array(kl);\n\n    py::tuple output = py::make_tuple(_kl);\n    return output;\n}\n\n\npy::tuple gaussian_interp_w2(array_tf _mu_q, array_tf _sigma_q,\n                             array_tf _mu_p, array_tf _sigma_p,\n                             double alpha, int dim, int nb_steps) {\n\n    mat mu_q = array_to_mat(_mu_q);\n    cube sigma_q = array_to_cube(_sigma_q);\n\n    mat mu_p = array_to_mat(_mu_p);\n    cube sigma_p = array_to_cube(_sigma_p);\n\n    mat mu(dim, nb_steps);\n    cube sigma(dim, dim, nb_steps);\n\n    for(int i = 0; i < nb_steps; i++) {\n        mu.col(i) = (1. - alpha) * mu_q.col(i) + alpha * mu_p.col(i);\n\n        mat chol_sigma_q = real(sqrtmat(sigma_q.slice(i)));\n        mat inv_chol_sigma_q = inv_sympd(chol_sigma_q);\n        mat _sigma = (1. - alpha) * sigma_q.slice(i)\n                     + alpha * real(sqrtmat(chol_sigma_q * sigma_p.slice(i) * chol_sigma_q));\n\n        sigma.slice(i) = inv_chol_sigma_q * _sigma * _sigma * inv_chol_sigma_q;\n    }\n\n    // transform outputs to numpy\n    array_tf _mu = mat_to_array(mu);\n    array_tf _sigma = cube_to_array(sigma);\n\n    py::tuple output = py::make_tuple(_mu, _sigma);\n    return output;\n}\n\n\npy::tuple gaussian_interp_kl(array_tf _mu_q, array_tf _sigma_q,\n                             array_tf _mu_p, array_tf _sigma_p,\n                             double alpha, int dim, int nb_steps) {\n\n    mat mu_q = array_to_mat(_mu_q);\n    cube sigma_q = array_to_cube(_sigma_q);\n\n    mat mu_p = array_to_mat(_mu_p);\n    cube sigma_p = array_to_cube(_sigma_p);\n\n    mat mu(dim, nb_steps);\n    cube sigma(dim, dim, nb_steps);\n\n    for(int i = 0; i < nb_steps; i++) {\n        mat lambda_q = inv_sympd(sigma_q.slice(i));\n        mat lambda_p = inv_sympd(sigma_p.slice(i));\n\n        sigma.slice(i) = inv_sympd(alpha * lambda_p + (1. - alpha) * lambda_q);\n        mu.col(i) = sigma.slice(i) * (alpha * lambda_p * mu_p.col(i) + (1. - alpha) * lambda_q * mu_q.col(i));\n    }\n\n    // transform outputs to numpy\n    array_tf _mu = mat_to_array(mu);\n    array_tf _sigma = cube_to_array(sigma);\n\n    py::tuple output = py::make_tuple(_mu, _sigma);\n    return output;\n}\n\n\ndouble quad_expectation(array_tf _mu, array_tf _sigma_s,\n                        array_tf _Q, array_tf _q, double _q0) {\n\n    vec mu  = array_to_vec(_mu);\n    mat sigma_s = array_to_mat(_sigma_s);\n\n    mat Q = array_to_mat(_Q);\n    vec q = array_to_vec(_q);\n\n\tdouble result = as_scalar(mu.t() * Q * mu) + as_scalar(mu.t() * q) + _q0 + trace(Q * sigma_s);\n\treturn result;\n}\n\n\npy::tuple cubature_forward_pass(array_tf _mu_x0, array_tf _sigma_x0,\n                                array_tf _mu_param, array_tf _sigma_param, array_tf _sigma_dyn,\n                                array_tf _K, array_tf _kff, array_tf _sigma_ctl,\n                                int dm_state, int dm_act, int nb_steps) {\n\n    // inputs\n    vec mu_x0 = array_to_vec(_mu_x0);\n    mat sigma_x0 = array_to_mat(_sigma_x0);\n\n    mat mu_param = array_to_mat(_mu_param);\n    cube sigma_param = array_to_cube(_sigma_param);\n    cube sigma_dyn = array_to_cube(_sigma_dyn);\n\n    mat A(dm_state, dm_state);\n    mat B(dm_state, dm_act);\n    vec c(dm_state);\n\n    // cubature\n\n    // particles for state, action, constant, ...\n    // ... sigma_param, sigma_dyn\n    int dm_augmented = dm_state + dm_act + 1 + dm_state;\n    vec mu_augmented(dm_augmented);\n    mat chol_sigma_augmented = 1e-8 * eye(dm_augmented, dm_augmented);\n\n    mat input_cubature_points(dm_augmented, 2 * dm_augmented);\n    mat output_cubature_points(dm_state, 2 * dm_augmented);\n\n    cube K = array_to_cube(_K);\n    mat kff = array_to_mat(_kff);\n    cube sigma_ctl = array_to_cube(_sigma_ctl);\n\n    // outputs\n    mat mu_x(dm_state, nb_steps + 1);\n    cube sigma_x(dm_state, dm_state, nb_steps + 1);\n\n    mat mu_u(dm_act, nb_steps);\n    cube sigma_u(dm_act, dm_act, nb_steps);\n\n    mat mu_xu(dm_state + dm_act, nb_steps + 1);\n    cube sigma_xu(dm_state + dm_act, dm_state + dm_act, nb_steps + 1);\n\n    mu_x.col(0) = mu_x0;\n    sigma_x.slice(0) = sigma_x0;\n\n    for (int i = 0; i < nb_steps; i++) {\n        // get matrices from parameter distribution mean vector\n        // reshape here is appled column-wise\n        mat At = mu_param(span(0, dm_state * dm_state - 1), i);\n        mat Bt = mu_param(span(dm_state * dm_state,\n                               dm_state * dm_state + dm_state * dm_act - 1), i);\n        vec ct = mu_param(span(dm_state * dm_state + dm_state * dm_act,\n                               dm_state * dm_state + dm_state * dm_act + dm_state - 1), i);\n\n        A = reshape(At, size(A));\n        B = reshape(Bt, size(B));\n        c = reshape(ct, size(c));\n\n        // mu_u = K * mu_x + k\n        mu_u.col(i) = K.slice(i) * mu_x.col(i) + kff.col(i);\n\n        // sigma_u = sigma_ctl + K * sigma_x * K_T\n        sigma_u.slice(i) = sigma_ctl.slice(i) + K.slice(i) * sigma_x.slice(i) * K.slice(i).t();\n        sigma_u.slice(i) = 0.5 * (sigma_u.slice(i) + sigma_u.slice(i).t());\n        sigma_u.slice(i) += 1e-8 * eye(dm_act, dm_act);\n\n        // sigma_xu =   [[sigma_x,      sigma_x * K_T],\n        //               [K * sigma_x,    sigma_u    ]]\n        sigma_xu.slice(i) = join_vert(join_horiz(sigma_x.slice(i), sigma_x.slice(i) * K.slice(i).t()),\n                                      join_horiz(K.slice(i) * sigma_x.slice(i), sigma_u.slice(i)));\n        sigma_xu.slice(i) = 0.5 * (sigma_xu.slice(i) + sigma_xu.slice(i).t());\n        sigma_xu.slice(i) += 1e-8 * eye(dm_state + dm_act, dm_state + dm_act);\n\n        // mu_xu =  [[mu_x],\n        //           [mu_u]],\n        mu_xu.col(i) = join_vert(mu_x.col(i), mu_u.col(i));\n\n        // form augmented state mean and covariance\n        mu_augmented = join_vert(mu_xu.col(i), ones(1), zeros<vec>(dm_state));\n\n        chol_sigma_augmented.fill(0.0);\n        chol_sigma_augmented.submat(0, 0, dm_state + dm_act - 1, dm_state + dm_act - 1) = chol(symmatu(sigma_xu.slice(i)), \"lower\");\n        chol_sigma_augmented.submat(dm_state + dm_act + 1, dm_state + dm_act + 1, dm_augmented - 1, dm_augmented - 1) = eye(dm_state, dm_state);\n\n        // calculate cubature points\n        input_cubature_points = join_horiz(chol_sigma_augmented, - chol_sigma_augmented);\n        input_cubature_points *= sqrt(dm_augmented);\n        input_cubature_points.each_col() += mu_augmented;\n\n        // propagate cubature points\n         for (int j = 0; j < 2 * dm_augmented; j++){\n            vec vec_xu = input_cubature_points.col(j);\n\n            mat mat_xu = kron(vec_xu(span(0, dm_state + dm_act)).t(), eye(dm_state, dm_state));\n            mat total_covar = sigma_dyn.slice(i) + mat_xu * sigma_param.slice(i) * mat_xu.t();\n            total_covar = 0.5 * (total_covar + total_covar.t());\n\n            mat chol_covar = chol(symmatu(total_covar), \"lower\");\n            output_cubature_points.col(j) = join_horiz(A, B, c, chol_covar) * vec_xu;\n        }\n\n        // estimate new mean and covariance\n        mu_x.col(i+1) = mean(output_cubature_points, 1);\n\n        output_cubature_points.each_col() -= mu_x.col(i+1);\n\n        sigma_x.slice(i+1).fill(0.0);\n        output_cubature_points.each_col([&sigma_x, i] (vec& col){\n            sigma_x.slice(i+1) += col * col.t();\n        });\n        sigma_x.slice(i+1) /= 2 * dm_augmented;\n        sigma_x.slice(i+1) = 0.5 * (sigma_x.slice(i+1) + sigma_x.slice(i+1).t());\n\n        if(i == nb_steps - 1) {\n            mu_xu.col(i+1) = join_vert(mu_x.col(i+1), zeros<vec>(dm_act));\n            sigma_xu.slice(i+1).submat(0, 0, dm_state - 1, dm_state - 1) = sigma_x.slice(i+1);\n        }\n    }\n\n    // transform outputs to numpy\n    array_tf _mu_x = mat_to_array(mu_x);\n    array_tf _sigma_x = cube_to_array(sigma_x);\n    array_tf _mu_u =  mat_to_array(mu_u);\n    array_tf _sigma_u = cube_to_array(sigma_u);\n    array_tf _mu_xu =  mat_to_array(mu_xu);\n    array_tf _sigma_xu = cube_to_array(sigma_xu);\n\n    py::tuple output = py::make_tuple(_mu_x, _sigma_x, _mu_u, _sigma_u, _mu_xu, _sigma_xu);\n    return output;\n}\n\n\npy::tuple policy_augment_cost(array_tf _Cxx, array_tf _cx, array_tf _Cuu,\n                              array_tf _cu, array_tf _Cxu, array_tf _c0,\n                              array_tf _K, array_tf _kff, array_tf _sigma_ctl,\n                              array_tf _alpha, int dm_state, int dm_act, int nb_steps) {\n\n    // inputs\n    cube Cxx = array_to_cube(_Cxx);\n    mat cx = array_to_mat(_cx);\n    cube Cuu = array_to_cube(_Cuu);\n    mat cu = array_to_mat(_cu);\n    cube Cxu = array_to_cube(_Cxu);\n    vec c0 = array_to_vec(_c0);\n\n    cube K = array_to_cube(_K);\n    mat kff = array_to_mat(_kff);\n    cube sigma_ctl = array_to_cube(_sigma_ctl);\n\n    vec alpha = array_to_vec(_alpha);\n\n    // outputs\n    cube agCxx(dm_state, dm_state, nb_steps + 1);\n    mat agcx(dm_state, nb_steps + 1);\n    cube agCuu(dm_act, dm_act, nb_steps + 1);\n    mat agcu(dm_act, nb_steps + 1);\n    cube agCxu(dm_state, dm_act, nb_steps + 1);\n    vec agc0(nb_steps + 1);\n\n    for (int i = 0; i < nb_steps; i++) {\n        mat lambda_ctl = inv_sympd(sigma_ctl.slice(i));\n\n        agCxx.slice(i) = Cxx.slice(i) + 0.5 * alpha(i) * K.slice(i).t() * lambda_ctl * K.slice(i);\n        agCuu.slice(i) = Cuu.slice(i) + 0.5 * alpha(i) * lambda_ctl;\n        agCxu.slice(i) = Cxu.slice(i) - 0.5 * alpha(i) * K.slice(i).t() * lambda_ctl;\n        agcx.col(i) = cx.col(i) + alpha(i) * K.slice(i).t() * lambda_ctl * kff.col(i);\n        agcu.col(i) = cu.col(i) - alpha(i) * lambda_ctl * kff.col(i);\n        agc0(i) = as_scalar(c0(i) + 0.5 * alpha(i) * log( det(2. * datum::pi * sigma_ctl.slice(i)) )\n                            + 0.5 * alpha(i) * kff.col(i).t() * lambda_ctl * kff.col(i));\n    }\n\n    // last time step\n    agCxx.slice(nb_steps) = Cxx.slice(nb_steps);\n    agcx.col(nb_steps) = cx.col(nb_steps);\n    agCuu.slice(nb_steps) = Cuu.slice(nb_steps);\n    agcu.col(nb_steps) = cu.col(nb_steps);\n    agCxu.slice(nb_steps) = Cxu.slice(nb_steps);\n    agc0(nb_steps) = c0(nb_steps);\n\n    // transform outputs to numpy\n    array_tf _agCxx = cube_to_array(agCxx);\n    array_tf _agcx = mat_to_array(agcx);\n    array_tf _agCuu =  cube_to_array(agCuu);\n    array_tf _agcu = mat_to_array(agcu);\n    array_tf _agCxu =  cube_to_array(agCxu);\n    array_tf _agc0 = vec_to_array(agc0);\n\n    py::tuple output = py::make_tuple(_agCxx, _agcx, _agCuu, _agcu, _agCxu, _agc0);\n    return output;\n}\n\n\npy::tuple policy_backward_pass(array_tf _Cxx, array_tf _cx, array_tf _Cuu,\n                               array_tf _cu, array_tf _Cxu, array_tf _c0,\n                               array_tf _mu_param, array_tf _sigma_param, array_tf _sigma_dyn,\n                               array_tf _alpha, int dm_state, int dm_act, int nb_steps) {\n\n    // inputs\n    cube Cxx = array_to_cube(_Cxx);\n    mat cx = array_to_mat(_cx);\n    cube Cuu = array_to_cube(_Cuu);\n    mat cu = array_to_mat(_cu);\n    cube Cxu = array_to_cube(_Cxu);\n    vec c0 = array_to_vec(_c0);\n\n    mat mu_param = array_to_mat(_mu_param);\n    cube sigma_param = array_to_cube(_sigma_param);\n    cube sigma_dyn = array_to_cube(_sigma_dyn);\n\n    vec alpha = array_to_vec(_alpha);\n\n    mat A(dm_state, dm_state);\n    mat B(dm_state, dm_act);\n    vec c(dm_state);\n\n    mat P(dm_state + dm_act + 1, dm_state + dm_act + 1);\n    mat Pxx(dm_state, dm_state);\n    mat Pxu(dm_state, dm_act);\n    mat Puu(dm_act, dm_act);\n    vec px(dm_state);\n    vec pu(dm_act);\n    double p0;\n\n    // outputs\n    cube Q(dm_state + dm_act, dm_state + dm_act, nb_steps);\n    cube Qxx(dm_state, dm_state, nb_steps);\n    cube Qux(dm_act, dm_state, nb_steps);\n    cube Quu(dm_act, dm_act, nb_steps);\n    cube Quu_inv(dm_act, dm_act, nb_steps);\n    mat qx(dm_state, nb_steps);\n    mat qu(dm_act, nb_steps);\n    vec q0(nb_steps);\n\n    cube V(dm_state, dm_state, nb_steps + 1);\n    mat v(dm_state, nb_steps + 1);\n    vec v0(nb_steps + 1);\n\n    cube K(dm_act, dm_state, nb_steps);\n    mat kff(dm_act, nb_steps);\n    cube sigma_ctl(dm_act, dm_act, nb_steps);\n    cube lambda_ctl(dm_act, dm_act, nb_steps);\n\n    int _diverge = -1;\n\n    // last time step\n    V.slice(nb_steps) = Cxx.slice(nb_steps);\n    v.col(nb_steps) = cx.col(nb_steps);\n    v0(nb_steps) = c0(nb_steps);\n\n\tfor(int i = nb_steps - 1; i>= 0; --i)\n\t{\n        // get matrices from parameter distribution mean vector\n        // reshape here is appled column-wise\n        mat At = mu_param(span(0, dm_state * dm_state - 1), i);\n        mat Bt = mu_param(span(dm_state * dm_state, dm_state * dm_state + dm_state * dm_act - 1), i);\n        vec ct = mu_param(span(dm_state * dm_state + dm_state * dm_act, dm_state * dm_state + dm_state * dm_act + dm_state - 1), i);\n\n        A = reshape(At, size(A));\n        B = reshape(Bt, size(B));\n        c = reshape(ct, size(c));\n\n        // extra terms due to parameter distribution\n         for (int j = 0; j < dm_state + dm_act + 1; j++){\n            for (int k = 0; k < dm_state + dm_act + 1; k++){\n                P(j, k) = trace(sigma_param.slice(i).submat(j * dm_state, k * dm_state,\n                                                            (j + 1) * dm_state - 1, (k + 1) * dm_state - 1) * V.slice(i+1));\n            }\n         }\n\n        Pxx = P.submat(0, 0, dm_state - 1, dm_state - 1);\n        Puu = P.submat(dm_state, dm_state, dm_state + dm_act - 1, dm_state + dm_act - 1);\n        Pxu = P.submat(0, dm_state, dm_state - 1, dm_state + dm_act - 1);\n\n        px = P.submat(0, dm_state + dm_act, dm_state - 1, dm_state + dm_act);\n        pu = P.submat(dm_state, dm_state + dm_act, dm_state + dm_act - 1, dm_state + dm_act);\n        p0 = P(dm_state + dm_act, dm_state + dm_act);\n\n        Qxx.slice(i) = - (Cxx.slice(i) + A.t() * V.slice(i+1) * A + Pxx) / alpha(i);\n        Quu.slice(i) = - (Cuu.slice(i) + B.t() * V.slice(i+1) * B + Puu) / alpha(i);\n        Qux.slice(i) = - (Cxu.slice(i) + A.t() * V.slice(i+1) * B + Pxu).t() / alpha(i);\n\n        qu.col(i) = - (cu.col(i) + 2.0 * B.t() * V.slice(i+1) * c + B.t() * v.col(i+1) + 2. * pu) / alpha(i);\n        qx.col(i) = - (cx.col(i) + 2.0 * A.t() * V.slice(i+1) * c + A.t() * v.col(i+1) + 2. * px) / alpha(i);\n        q0(i) = - as_scalar(c0(i) + v0(i+1) + c.t() * V.slice(i+1) * c +\n                            + trace(V.slice(i+1) * sigma_dyn.slice(i)) + v.col(i+1).t() * c + p0) / alpha(i);\n\n        if ((Quu.slice(i)).is_sympd()) {\n            _diverge = i;\n            break;\n        }\n\n        Quu_inv.slice(i) = inv(Quu.slice(i));\n        K.slice(i) = - Quu_inv.slice(i) * Qux.slice(i);\n        kff.col(i) = - 0.5 * Quu_inv.slice(i) * qu.col(i);\n\n        sigma_ctl.slice(i) = - 0.5 * Quu_inv.slice(i);\n        sigma_ctl.slice(i) = 0.5 * (sigma_ctl.slice(i).t() + sigma_ctl.slice(i));\n\n        lambda_ctl.slice(i) = - (Quu.slice(i).t() + Quu.slice(i));\n        lambda_ctl.slice(i) = 0.5 * (lambda_ctl.slice(i).t() + lambda_ctl.slice(i));\n\n        V.slice(i) = - alpha(i) * (Qxx.slice(i) + Qux.slice(i).t() * K.slice(i));\n        V.slice(i) = 0.5 * (V.slice(i) + V.slice(i).t());\n\n        v.col(i) = - alpha(i) * (qx.col(i) + 2. * Qux.slice(i).t() * kff.col(i));\n        v0(i) = - alpha(i) * (as_scalar(0.5 * qu.col(i).t() * kff.col(i)) + q0(i)\n                              + 0.5 * (dm_act * log (2. * datum::pi) - log(det(- 2. * Quu.slice(i)))));\n\t}\n\n    // transform outputs to numpy\n    array_tf _Qxx = cube_to_array(Qxx);\n    array_tf _Qux = cube_to_array(Qux);\n    array_tf _Quu = cube_to_array(Quu);\n\n    array_tf _qx = mat_to_array(qx);\n    array_tf _qu = mat_to_array(qu);\n    array_tf _q0 = mat_to_array(q0);\n\n    array_tf _V = cube_to_array(V);\n    array_tf _v = mat_to_array(v);\n    array_tf _v0 = vec_to_array(v0);\n\n    array_tf _K = cube_to_array(K);\n    array_tf _kff = mat_to_array(kff);\n    array_tf _sigma_ctl = cube_to_array(sigma_ctl);\n\n    py::tuple output =  py::make_tuple(_Qxx, _Qux, _Quu, _qx, _qu, _q0,\n                                        _V, _v, _v0,\n                                        _K, _kff, _sigma_ctl, _diverge);\n\n    return output;\n}\n\n\npy::tuple parameter_augment_cost(array_tf _mu_nominal, array_tf _sigma_nominal,\n                                 double beta, int dm_param, int nb_steps) {\n\n    // inputs\n    mat mu_nominal = array_to_mat(_mu_nominal);\n    cube sigma_nominal = array_to_cube(_sigma_nominal);\n\n    // outputs\n    cube agCxx(dm_param, dm_param, nb_steps);\n    mat agcx(dm_param, nb_steps);\n    vec agc0(nb_steps);\n\n    for (int i = 0; i < nb_steps; i++) {\n        mat lambda_nominal = inv_sympd(sigma_nominal.slice(i));\n\n        agCxx.slice(i) = 0.5 * beta * lambda_nominal;\n        agcx.col(i) = - beta * lambda_nominal * mu_nominal.col(i);\n        agc0(i) = as_scalar(0.5 * beta * log( det(2. * datum::pi * sigma_nominal.slice(i)) )\n                            + 0.5 * beta * mu_nominal.col(i).t() * lambda_nominal * mu_nominal.col(i));\n    }\n\n    // transform outputs to numpy\n    array_tf _agCxx = cube_to_array(agCxx);\n    array_tf _agcx = mat_to_array(agcx);\n    array_tf _agc0 = vec_to_array(agc0);\n\n    py::tuple output = py::make_tuple(_agCxx, _agcx, _agc0);\n    return output;\n}\n\npy::tuple regularized_parameter_augment_cost(array_tf _mu_last, array_tf _sigma_last,\n                                             double eta, int dm_param, int nb_steps) {\n\n    // inputs\n    mat mu_last = array_to_mat(_mu_last);\n    cube sigma_last = array_to_cube(_sigma_last);\n\n    // outputs\n    cube agCxx(dm_param, dm_param, nb_steps);\n    mat agcx(dm_param, nb_steps);\n    vec agc0(nb_steps);\n\n    for (int i = 0; i < nb_steps; i++) {\n        mat lambda_last = inv_sympd(sigma_last.slice(i));\n\n        agCxx.slice(i) = 0.5 * eta * lambda_last;\n        agcx.col(i) = - eta * lambda_last * mu_last.col(i);\n        agc0(i) = as_scalar(0.5 * eta * log( det(2. * datum::pi * sigma_last.slice(i)) )\n                            + 0.5 * eta * mu_last.col(i).t() * lambda_last * mu_last.col(i));\n    }\n\n    // transform outputs to numpy\n    array_tf _agCxx = cube_to_array(agCxx);\n    array_tf _agcx = mat_to_array(agcx);\n    array_tf _agc0 = vec_to_array(agc0);\n\n    py::tuple output = py::make_tuple(_agCxx, _agcx, _agc0);\n    return output;\n}\n\npy::tuple parameter_backward_pass(array_tf _mu_x, array_tf _sigma_x,\n                                  array_tf _K, array_tf _kff, array_tf _sigma_ctl, array_tf _sigma_dyn,\n                                  array_tf _cx, array_tf _Cxx, array_tf _Cuu,\n                                  array_tf _cu, array_tf _Cxu, array_tf _c0,\n                                  array_tf _agCpp, array_tf _agcp, array_tf _agc0,\n                                  double beta, double eta, int dm_state, int dm_act, int dm_param, int nb_steps) {\n\n    // inputs\n    mat mu_x = array_to_mat(_mu_x);\n    cube sigma_x = array_to_cube(_sigma_x);\n\n    cube K = array_to_cube(_K);\n    mat kff = array_to_mat(_kff);\n    cube sigma_ctl = array_to_cube(_sigma_ctl);\n\n    cube sigma_dyn = array_to_cube(_sigma_dyn);\n\n    cube Cxx = array_to_cube(_Cxx);\n    mat cx = array_to_mat(_cx);\n    cube Cuu = array_to_cube(_Cuu);\n    mat cu = array_to_mat(_cu);\n    cube Cxu = array_to_cube(_Cxu);\n    vec c0 = array_to_vec(_c0);\n\n    cube agCpp = array_to_cube(_agCpp);\n    mat agcp = array_to_mat(_agcp);\n    vec agc0 = array_to_vec(_agc0);\n\n    // recreate state-action-offset dist.\n    mat mu_u(dm_act, nb_steps);\n    cube sigma_u(dm_act, dm_act, nb_steps);\n\n    mat mu_xu(dm_state + dm_act + 1, nb_steps + 1);\n    cube sigma_xu(dm_state + dm_act + 1, dm_state + dm_act + 1, nb_steps + 1);\n\n    for (int i = 0; i < nb_steps; i++) {\n        // mu_u = K * mu_x + k\n        mu_u.col(i) = K.slice(i) * mu_x.col(i) + kff.col(i);\n\n        // sigma_u = sigma_ctl + K * sigma_x * K_T\n        sigma_u.slice(i) = sigma_ctl.slice(i) + K.slice(i) * sigma_x.slice(i) * K.slice(i).t();\n        sigma_u.slice(i) = 0.5 * (sigma_u.slice(i) + sigma_u.slice(i).t());\n        sigma_u.slice(i) += 1e-8 * eye(dm_act, dm_act);\n\n        // sigma_xu =   [[sigma_x,        sigma_x * K_T,   0.],\n        //               [K * sigma_x,    sigma_u,         0.],\n        //               [0.              0.               0.]]\n        sigma_xu.slice(i) = join_vert( join_horiz(sigma_x.slice(i), sigma_x.slice(i) * K.slice(i).t(), zeros(dm_state, 1)),\n                                       join_horiz(K.slice(i) * sigma_x.slice(i), sigma_u.slice(i), zeros(dm_act, 1)),\n                                       join_horiz(zeros(1, dm_state), zeros(1, dm_act), zeros(1, 1)) );\n        sigma_xu.slice(i) = 0.5 * (sigma_xu.slice(i) + sigma_xu.slice(i).t());\n        sigma_xu.slice(i) += 1e-8 * eye(dm_state + dm_act + 1, dm_state + dm_act + 1);\n\n        // mu_xu =  [[mu_x],\n        //           [mu_u],\n        //           [1],\n        mu_xu.col(i) = join_vert(mu_x.col(i), mu_u.col(i), ones(1));\n    }\n\n    mu_xu.col(nb_steps) = join_vert(mu_x.col(nb_steps), zeros(dm_act), ones(1));\n    sigma_xu.slice(nb_steps).submat(0, 0, dm_state - 1, dm_state - 1) = sigma_x.slice(nb_steps);\n\n    // temp\n    mat W(dm_param, dm_param);\n    vec w(dm_param);\n\n    mat A(dm_state, dm_state);\n    mat B(dm_state, dm_act);\n    vec c(dm_state);\n\n    mat A_cl(dm_state, dm_state);\n    vec c_cl(dm_state);\n    mat sigma_block(dm_state + dm_act + 1, dm_state + dm_act + 1);\n\n    mat P(dm_state + dm_act + 1, dm_state + dm_act + 1);\n    mat Pxx(dm_state, dm_state);\n    mat Pxu(dm_state, dm_act);\n    mat Puu(dm_act, dm_act);\n    vec px(dm_state);\n    vec pu(dm_act);\n    double p0;\n\n    // outputs\n    mat mu_optimal(dm_param, nb_steps);\n    cube sigma_optimal(dm_param, dm_param, nb_steps);\n\n    cube V(dm_state, dm_state, nb_steps + 1);\n    mat v(dm_state, nb_steps + 1);\n    vec v0(nb_steps + 1);\n\n    int _diverge = -1;\n\n    // last time step\n    V.slice(nb_steps) = - Cxx.slice(nb_steps);\n    v.col(nb_steps) = - cx.col(nb_steps);\n    v0(nb_steps) = - c0(nb_steps);\n\n\tfor(int i = nb_steps - 1; i >= 0; --i)\n\t{\n\t    mat mat_mu_xu = kron(mu_xu.col(i).t(), eye(dm_state, dm_state));\n\n\t    mat Vpp = mat_mu_xu.t() * V.slice(i + 1) * mat_mu_xu + kron(sigma_xu.slice(i), V.slice(i + 1));\n\t    vec vp =  mat_mu_xu.t() * v.col(i + 1);\n\n        W = 2.0 * (agCpp.slice(i) + Vpp) / (beta + eta);\n        W = 0.5 * (W.t() + W);\n\n        w = - (agcp.col(i) + vp) / (beta + eta);\n\n        try {\n            sigma_optimal.slice(i) = inv_sympd(W);\n        } catch ( const std::runtime_error ) {\n            _diverge = i;\n            break;\n        }\n        sigma_optimal.slice(i) = 0.5 * (sigma_optimal.slice(i).t() + sigma_optimal.slice(i));\n\n        mu_optimal.col(i) = sigma_optimal.slice(i) * w;\n\n        mat At = mu_optimal(span(0, dm_state * dm_state - 1), i);\n        mat Bt = mu_optimal(span(dm_state * dm_state, dm_state * dm_state + dm_state * dm_act - 1), i);\n        vec ct = mu_optimal(span(dm_state * dm_state + dm_state * dm_act, dm_state * dm_state + dm_state * dm_act + dm_state - 1), i);\n\n        A = reshape(At, size(A));\n        B = reshape(Bt, size(B));\n        c = reshape(ct, size(c));\n\n        // extra terms due to parameter distribution\n         for (int j = 0; j < dm_state + dm_act + 1; j++){\n            for (int k = 0; k < dm_state + dm_act + 1; k++){\n                P(j, k) = trace(sigma_optimal.slice(i).submat(j * dm_state, k * dm_state,\n                                                              (j + 1) * dm_state - 1, (k + 1) * dm_state - 1) * V.slice(i+1));\n            }\n         }\n\n        Pxx = P.submat(0, 0, dm_state - 1, dm_state - 1);\n        Puu = P.submat(dm_state, dm_state, dm_state + dm_act - 1, dm_state + dm_act - 1);\n        Pxu = P.submat(0, dm_state, dm_state - 1, dm_state + dm_act - 1);\n\n        px = P.submat(0, dm_state + dm_act, dm_state - 1, dm_state + dm_act);\n        pu = P.submat(dm_state, dm_state + dm_act, dm_state + dm_act - 1, dm_state + dm_act);\n        p0 = P(dm_state + dm_act, dm_state + dm_act);\n\n        A_cl = A + B * K.slice(i);\n        c_cl = c + B * kff.col(i);\n        sigma_block.submat(dm_state, dm_state, dm_state + dm_act - 1, dm_state + dm_act - 1) = sigma_ctl.slice(i);\n\n        V.slice(i) = (- Cxx.slice(i) + Pxx) + K.slice(i).t() * (- Cuu.slice(i) + Puu) * K.slice(i)\n                      + A_cl.t() * V.slice(i + 1) * A_cl + 2. * (- Cxu.slice(i) + Pxu) * K.slice(i);\n        V.slice(i) = 0.5 * (V.slice(i) + V.slice(i).t());\n\n        v.col(i) = (- cx.col(i) + 2. * px) + 2. * K.slice(i).t() * (- Cuu.slice(i) + Puu) * kff.col(i)\n                    + 2. * (- Cxu.slice(i) + Pxu) * kff.col(i) + K.slice(i).t() * (- cu.col(i) + 2. * pu)\n                    + 2. * A_cl.t() * V.slice(i + 1) * c_cl + A_cl.t() * v.col(i + 1);\n\n        v0(i) = as_scalar( (- c0(i) + p0) + kff.col(i).t() * (- Cuu.slice(i) + Puu) * kff.col(i) + kff.col(i).t() * (- cu.col(i) + 2. * pu)\n                            - trace(Cuu.slice(i + 1) * sigma_ctl.slice(i)) + v0(i + 1) + trace(V.slice(i + 1) * sigma_dyn.slice(i))\n                            + mu_optimal.col(i).t() * kron(sigma_block, V.slice(i + 1)) * mu_optimal.col(i) + trace(kron(sigma_block, V.slice(i + 1)) * sigma_optimal.slice(i))\n                            + c_cl.t() * V.slice(i + 1) * c_cl + c_cl.t() * v.col(i + 1) );\n\t}\n\n    // transform outputs to numpy\n    array_tf _V = cube_to_array(V);\n    array_tf _v = mat_to_array(v);\n    array_tf _v0 = vec_to_array(v0);\n\n    array_tf _mu_optimal = mat_to_array(mu_optimal);\n    array_tf _sigma_optimal = cube_to_array(sigma_optimal);\n\n    py::tuple output = py::make_tuple(_V, _v, _v0, _mu_optimal, _sigma_optimal, _diverge);\n\n    return output;\n}\n\nPYBIND11_MODULE(core, m)\n{\n    m.def(\"policy_divergence\", &policy_divergence);\n    m.def(\"gaussian_divergence\", &gaussian_divergence);\n    m.def(\"gaussian_interp_w2\", &gaussian_interp_w2);\n    m.def(\"gaussian_interp_kl\", &gaussian_interp_kl);\n    m.def(\"quad_expectation\", &quad_expectation);\n    m.def(\"cubature_forward_pass\", &cubature_forward_pass);\n    m.def(\"policy_augment_cost\", &policy_augment_cost);\n    m.def(\"policy_backward_pass\", &policy_backward_pass);\n    m.def(\"parameter_augment_cost\", &parameter_augment_cost);\n    m.def(\"parameter_backward_pass\", &parameter_backward_pass);\n    m.def(\"regularized_parameter_augment_cost\", &regularized_parameter_augment_cost);\n}\n", "meta": {"hexsha": "44580a21d4ecaebe12892e1013a8930c28a90e1c", "size": 30161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trajopt/rgps/src/util.cpp", "max_stars_repo_name": "hanyas/trajopt", "max_stars_repo_head_hexsha": "1cad9010be45851ec12fe4156ae73d9261304cb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2019-06-17T11:49:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:56.000Z", "max_issues_repo_path": "trajopt/rgps/src/util.cpp", "max_issues_repo_name": "hanyas/trajopt", "max_issues_repo_head_hexsha": "1cad9010be45851ec12fe4156ae73d9261304cb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-10T13:40:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T09:22:47.000Z", "max_forks_repo_path": "trajopt/rgps/src/util.cpp", "max_forks_repo_name": "hanyas/trajopt", "max_forks_repo_head_hexsha": "1cad9010be45851ec12fe4156ae73d9261304cb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-07-05T11:29:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T12:56:56.000Z", "avg_line_length": 37.0528255528, "max_line_length": 175, "alphanum_fraction": 0.5830708531, "num_tokens": 9251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.44532234194113923}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2015 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <iostream>\n\n//#define BOOST_DISABLE_ASSERTS\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n#include \"dune/grid/uggrid.hh\"\n#include \"dune/istl/solvers.hh\"\n\n#include \"fem/assemble.hh\"\n#include \"fem/lagrangespace.hh\"\n#include \"fem/embedded_errorest.hh\"\n#include \"linalg/trivialpreconditioner.hh\"\n#include \"linalg/jacobiPreconditioner.hh\"\n#include \"linalg/uzawa.hh\"\n#include \"linalg/direct.hh\"\n#include \"io/vtk.hh\"\n#include \"utilities/kaskopt.hh\" // property_tree\n#include \"utilities/gridGeneration.hh\"\n\nusing namespace Kaskade;\n#include \"stokes-adaptive.hh\"\n\nint main(int argc, char *argv[])\n{\n  using namespace boost::fusion;\n\n\n  int verbosity = 1;  // print to console if arguments are changed\n  bool dump = false; // do not write properties into file\n  std::unique_ptr<boost::property_tree::ptree> pt = getKaskadeOptions(argc, argv, verbosity, dump);\n\n  std::cout << \"Start Stokes tutorial programm\" << std::endl;\n  std::cout << \"using addaptive refinement based on embedded error estimation.\" << std::endl;\n  std::cout << \"Note: use FixedFractionCriterion as refinement strategy!\" << std::endl << std::endl;\n\n  constexpr int dim = 2;\n  constexpr int uIdx = 0;\n  constexpr int pIdx = 1;\n\n  // command line parameters\n  int refinements = getParameter(pt, \"refinements\", 2);   // initial mesh is refined \"refinements\" times\n  int order = getParameter(pt, \"order\", 3);               // order for velocity space, order for pressure space is (order-1)\n  int steps = getParameter(pt, \"steps\", 5);               // adaptive refinement steps\n\n  bool direct = getParameter(pt, \"direct\", true);\n  DirectType directType = static_cast<DirectType>(getParameter(pt, \"directSolver\", 4)); // 4: DirectType::UMFPACK3264\n\n\n  // grid generation\n  using Grid = Dune::UGGrid<dim>;\n  using H1Space = FEFunctionSpace<ContinuousLagrangeMapper<double,Grid::LeafGridView> >;\n  using Spaces = vector<H1Space const*,H1Space const*>;\n  using VariableDescriptions = vector<Variable<SpaceIndex<1>,Components<2>,VariableId<uIdx> >,\n                                      Variable<SpaceIndex<0>,Components<1>,VariableId<pIdx> > >;\n  using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;\n  using CoefficientVectors = VariableSet::CoefficientVectorRepresentation<>::type;\n  using Functional = StokesFunctional<double,VariableSet>;\n  using Assembler = VariationalFunctionalAssembler<LinearizationAt<Functional> >;\n\n  Dune::FieldVector<double,dim> x0(0.0), length(1.0);\n  GridManager<Grid> gridManager( createRectangle<Grid>(x0,length,1.0));\n  gridManager.globalRefine(refinements);\n\n  // construct involved spaces.\n  H1Space pressureSpace(gridManager,gridManager.grid().leafGridView(),order-1);\n  H1Space velocitySpace(gridManager,gridManager.grid().leafGridView(),order);\n\n  Spaces spaces(&pressureSpace,&velocitySpace);\n\n  // construct variable list.\n  std::string varNames[2] = { \"u\", \"p\" };\n\n  VariableSet variableSet(spaces,varNames);\n\n  // construct variational functional.\n  Functional F;\n\n  // construct Galerkin representation\n  Assembler assembler(spaces);\n  VariableSet::VariableSet x(variableSet);\n  VariableSet::VariableSet dx(variableSet);\n\n  // accuracy in space\n  std::vector<std::pair<double,double> > tol(variableSet.noOfVariables);\n  tol[0] = std::make_pair(1e0,1e-2);   // u\n  tol[1] = std::make_pair(1e0,1e-2);   // p\n  bool accurate = 0;\n\n  for (int i=0; i<steps; ++i)    // adaptive refinement loop\n  {\n    std::cout << \"\\nstep = \" << i+1 << std::endl;\n    size_t nnz = assembler.nnz(0,2,0,2,false);\n    size_t dof = variableSet.degreesOfFreedom(0,2);\n    std::cout << \"overall degrees of freedom: \" << dof << std::endl;\n    //std::cout << \"(structurally) nonzero elements: \" << nnz << std::endl;\n\n    x = 0;\n    assembler.assemble(linearization(F,x));\n\n    if(direct)\n    {\n      CoefficientVectors solution(VariableSet::CoefficientVectorRepresentation<>::init(spaces));\n      CoefficientVectors rhs(assembler.rhs());\n\n      // solve performing one Newton step\n      directInverseOperator(AssembledGalerkinOperator<Assembler>(assembler),directType).applyscaleadd(-1.0,rhs,solution);\n      x.data = solution.data;\n    }\n    else // Uzawa Solver\n    {\n      using VectorOfU = VariableSet::CoefficientVectorRepresentation<uIdx,uIdx+1>::type;\n      using VectorOfP = VariableSet::CoefficientVectorRepresentation<pIdx,pIdx+1>::type;\n      using Assembler_UU = AssembledGalerkinOperator<Assembler,uIdx,uIdx+1,uIdx,uIdx+1>;\n      using Assembler_PU = AssembledGalerkinOperator<Assembler,pIdx,pIdx+1,uIdx,uIdx+1>;\n      using Assembler_UP = AssembledGalerkinOperator<Assembler,uIdx,uIdx+1,pIdx,pIdx+1>;\n      using PreconAdapt = MatrixRepresentedOperator<MatrixAsTriplet<double>, VectorOfP, VectorOfP>;\n      using UzSo = UzawaSolver<VectorOfU,VectorOfP>;\n\n      Assembler_UU A(assembler);\n      Assembler_PU B(assembler);\n      Assembler_UP Bt(assembler);\n\n      JacobiPreconditioner<Assembler_UU> jacobiPreconditioner(A);\n      // inexact inner solver for upper left block\n      Dune::CGSolver<VectorOfU> cg(A,jacobiPreconditioner,1e-14,300,0);\n\n      TrivialPreconditioner<PreconAdapt> trivialPreconditioner;\n\n      VectorOfU f(assembler.rhs<uIdx,uIdx+1>());\n      VectorOfP g(assembler.rhs<pIdx,pIdx+1>());\n      VectorOfU u(VariableSet::CoefficientVectorRepresentation<uIdx,uIdx+1>::init(spaces));\n      VectorOfP p(VariableSet::CoefficientVectorRepresentation<pIdx,pIdx+1>::init(spaces));\n\n      UzSo uzawa(A,cg,B,Bt,trivialPreconditioner,1e-4,100,2);\n\n      Dune::InverseOperatorResult res;\n      UzSo::Domain solution(vector<VectorOfU,VectorOfP>(u,p));\n      UzSo::Range rhs(vector<VectorOfU,VectorOfP>(f,g));\n      rhs *= -1.0; // change sign as rhs is -'F while the assembler returns F'\n      uzawa.apply(solution,rhs,res);\n\n      at_c<uIdx>(x.data).coefficients() = at_c<0>(at_c<uIdx>(solution.data).data);\n      at_c<pIdx>(x.data).coefficients() = at_c<0>(at_c<pIdx>(solution.data).data);\n    }\n\n    writeVTKFile(gridManager.grid().leafGridView(),x,\"stokes-adaptive\", IoOptions(), 1);\n\n    VariableSet::VariableSet e = x;\n    projectHierarchically(variableSet,e);\n    e -= x;\n\n    accurate = embeddedErrorEstimator(variableSet,e,x,IdentityScaling(),tol,gridManager,1);\n    dof = variableSet.degreesOfFreedom(0,2);\n    std::cout << \"degrees of freedom after refinement = \" << dof << std::endl;\n\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "5e8cd16e31fe06de4d1e637dc21248130aed2070", "size": 7231, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/stokes/stokes-adaptive.cpp", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/tutorial/stokes/stokes-adaptive.cpp", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/tutorial/stokes/stokes-adaptive.cpp", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 41.5574712644, "max_line_length": 124, "alphanum_fraction": 0.6513621906, "num_tokens": 1915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4453223343875586}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if !defined(DIRICHLET_DISTRIBUTION_HPP)\n#define DIRICHLET_DISTRIBUTION_HPP\n\n#if defined(_MSC_VER)\n#\tpragma warning(disable: 4267)\t// warning about loss of data when converting size_t to int\n#endif\n\n//#include <cmath>\n//#include \"ncl/nxsdefs.h\"\n\n//#include \"phycas/src/states_patterns.hpp\"\n\n//#include <boost/shared_ptr.hpp>\n//#include <boost/format.hpp>\n#include \"multivariate_probability_distribution.hpp\"\n//#include \"phycas/src/basic_cdf.hpp\"\n//#include \"phycas/src/basic_lot.hpp\"\n//#include \"phycas/src/phycas_string.hpp\"\n//#if defined(PYTHON_ONLY) && defined(USING_NUMARRAY)\n//#\tinclude <boost/python/tuple.hpp>\n//#\tinclude <boost/python/numeric.hpp>\n//#\tinclude \"thirdparty/num_util/num_util.h\"\n//#endif\n//#include \"phycas/src/xprobdist.hpp\"\n\nnamespace phycas\n{\n\n/*------------------------------------------------------------------------------------------------------------------------------------------------------------------\n|\tThe Dirichlet distribution, with the number of parameters determined by the number of params supplied to the constructor.\n*/\nclass DirichletDistribution : public MultivariateProbabilityDistribution\n\t{\n\tpublic:\n                                                    DirichletDistribution();\n                                                    DirichletDistribution(const std::vector<double> & params);\n                                                    DirichletDistribution(const DirichletDistribution & other);\n\t\tvirtual                                     ~DirichletDistribution();\n\n        DirichletDistribution *                     cloneAndSetLot(Lot * other) const;\n        DirichletDistribution *                     Clone() const;\n\t\tvirtual void\t\t\t\t\t\t\t\tSetLot(Lot * other);\n\t\tvirtual void\t\t\t\t\t\t\t\tResetLot();\n\t\tvirtual void\t\t\t\t\t\t\t\tSetSeed(unsigned rnseed);\n\n\t\tvirtual bool\t\t\t\t\t\t\t\tIsDiscrete() const;\n\t\tvirtual std::string \t\t\t\t\t\tGetDistributionName() const;\n\t\tvirtual std::string \t\t\t\t\t\tGetDistributionDescription() const;\n\t\tstd::string                                 GetDescriptionForPython() const;\n\t\tvirtual std::vector<double>\t\t\t\t\tGetMean() const;\n\t\tvirtual std::vector<double> \t\t\t\tGetVar() const;\n\t\tvirtual std::vector<double> \t\t\t\tGetStdDev() const;\n\t\tvirtual std::vector<double>\t\t\t\t\tSample() const;\n\t\tvirtual double\t\t\t\t\t\t\t\tApproxCDF(const std::vector<double> &x, unsigned nsamples = 10000) const;\n\t\tvirtual double\t\t\t\t\t\t\t\tGetLnPDF(const std::vector<double> &x) const;\n\t\tvirtual double\t\t\t\t\t\t\t\tGetRelativeLnPDF(const std::vector<double> &x) const;\n\t\tvirtual void \t\t\t\t\t\t\t\tSetMeanAndVariance(const std::vector<double> &m, const std::vector<double> &v);\n#\t\tif defined(PYTHON_ONLY)\n#\t\t\tif defined(USING_NUMARRAY)\n\t\t\t\tvoid                                AltSetMeanAndVariance(boost::python::numeric::array m, boost::python::numeric::array v);\n\t\t\t\tboost::python::numeric::array       GetVarCovarMatrix();\n#\t\t\telse\n\t\t\t\tvoid                                AltSetMeanAndVariance(std::vector<double> m, std::vector<double> v);\n\t\t\t\tstd::vector<double>\t\t\t\t\tGetVarCovarMatrix();\n#\t\t\tendif\n#\t\tendif\n\n\t\tvirtual unsigned\t\t\t\t\t\t\tGetNParams() const;\n\t\tconst GammaDistribution &                   GetDistributionOnParameter(unsigned i) const;\n\n\n    protected:\n\n\t\tvoid                                        initialize(const double_vect_t & params);\n\n    protected:\n\n\t\tstd::vector<double>                         dirParams;\n\t\tstd::vector<GammaDistribution>              paramDistributions;\n\t\tmutable std::vector<double>                 scratchSpace;\n\t};\n\n} // namespace phycas\n\n#endif\n", "meta": {"hexsha": "ebd81af1a19e0532bf4264b2f379eb8f048a7e0a", "size": 4948, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/dirichlet_distribution.hpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/dirichlet_distribution.hpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/dirichlet_distribution.hpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 47.1238095238, "max_line_length": 164, "alphanum_fraction": 0.5567906225, "num_tokens": 989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4451932739277362}}
{"text": "///1\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <tuple>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Triangulation_face_base_2.h>\n\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef std::size_t                                            Index;\ntypedef CGAL::Triangulation_vertex_base_with_info_2<Index,K>   Vb;\ntypedef CGAL::Triangulation_face_base_2<K>                     Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb,Fb>            Tds;\ntypedef CGAL::Delaunay_triangulation_2<K,Tds>                  Delaunay;\ntypedef std::pair<K::Point_2,Index> IPoint;\ntypedef std::tuple<int,int> Edge;\ntypedef std::vector<Edge> EdgeV;\ntypedef Tds::Vertex_handle Vh;\n\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> graph;\ntypedef boost::graph_traits<graph>::vertex_descriptor vertex_desc;\ntypedef boost::graph_traits<graph>::edge_iterator edge_it;\n\nusing namespace std;\n\n// Strategy:\n// - Binary search for the best k\n//   - For a given k, construct a Graph that contains only points p_k...p_{n-1}\n//   - Find the largest connected component\nvoid solve() {\n  int n;\n  long r;\n  cin >> n >> r;\n  long r2 = r * r;\n  \n  vector<IPoint> points;\n  points.reserve(n);\n  int x, y;\n  for (int i = 0; i < n; ++i) {\n    cin >> x >> y;\n    points.emplace_back(K::Point_2(x, y), i);\n  }\n \n\n  // Start binary search\n  int a = 1;\n  int b = n;\n  while (a < b - 1) {\n\n    int empireSize = (a + b) / 2;\n\n    // Use delaunay to quickly construct graph of points outside the empire\n    Delaunay dt;\n    dt.insert(points.begin() + empireSize, points.end());\n\n    graph G(n - empireSize);\n    for (auto e = dt.finite_edges_begin(); e != dt.finite_edges_end(); ++e) {\n      int u = e->first->vertex((e->second+1)%3)->info();\n      int v = e->first->vertex((e->second+2)%3)->info();\n      if (dt.segment(e).squared_length() <= r2) {\n        boost::add_edge(u - empireSize, v - empireSize, G);\n      }\n    }\n\n    // Compute largest connected component\n    std::vector<int> component_map(n);\n    int ncc = boost::connected_components(G, boost::make_iterator_property_map(component_map.begin(), boost::get(boost::vertex_index, G))); \n\n    int largestComponent = 0;\n    vector<int> componentSize(ncc, 0);\n    for (int i = 0; i < n - empireSize; ++i) {\n      int c = component_map[i];\n      componentSize[c]++;\n      largestComponent = max(largestComponent, int(componentSize[c]));\n    }\n\n    // Continue binary search\n    if (empireSize <= largestComponent) { \n      // Invalid solution, the empire must be at least as large as the rebel alliance (both expand equally fast)\n      // => Expand empire\n      a = empireSize;\n    }\n    else {\n      b = empireSize;\n    }\n  }\n  cout << a << endl;\n}\n\nint main() {\n    ios_base::sync_with_stdio(false);\n    int t; cin >> t;\n    while (t--) {\n        solve();\n    }\n    return 0;\n}\n\n", "meta": {"hexsha": "bee1c1bd0d22927fc1792a61a44f3917fd05fdde", "size": 3128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sith.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/sith.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sith.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 29.7904761905, "max_line_length": 140, "alphanum_fraction": 0.6502557545, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.44518190917063954}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2014 MetaScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_HYPOT_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/hypot.hpp>\n#include <boost/simd/include/functions/simd/abs.hpp>\n#include <boost/simd/include/functions/simd/min.hpp>\n#include <boost/simd/include/functions/simd/max.hpp>\n#include <boost/simd/include/functions/simd/plus.hpp>\n#include <boost/simd/include/functions/simd/unary_minus.hpp>\n#include <boost/simd/include/functions/simd/exponent.hpp>\n#include <boost/simd/include/functions/simd/ldexp.hpp>\n#include <boost/simd/include/functions/simd/sqr.hpp>\n#include <boost/simd/include/functions/simd/sqrt.hpp>\n#include <boost/simd/include/constants/maxexponentm1.hpp>\n#include <boost/simd/include/constants/minexponent.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/sdk/meta/as_logical.hpp>\n#include <boost/simd/include/functions/simd/if_else.hpp>\n#include <boost/simd/include/functions/simd/logical_and.hpp>\n#include <boost/simd/include/functions/simd/logical_or.hpp>\n#include <boost/simd/include/functions/simd/is_inf.hpp>\n#include <boost/simd/include/functions/simd/is_nan.hpp>\n#include <boost/simd/include/constants/inf.hpp>\n#endif\n\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( hypot_, tag::cpu_\n                                    , (A0)(X)\n                                    , ((simd_<floating_<A0>,X>))\n                                      ((simd_<floating_<A0>,X>))\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename dispatch::meta::as_integer<result_type>::type   iA0;\n      result_type r =  boost::simd::abs(a0);\n      result_type i =  boost::simd::abs(a1);\n      iA0 e =  exponent(boost::simd::max(i, r));\n      e = boost::simd::min(boost::simd::max(e,Minexponent<A0>()),Maxexponentm1<A0>());\n      result_type res =  ldexp(sqrt(sqr(ldexp(r, -e))+sqr(ldexp(i, -e))), e);\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      typedef typename meta::as_logical<result_type>::type             lA0;\n      lA0 test = logical_or(logical_and(is_nan(a0), is_inf(a1)),\n                            logical_and(is_nan(a1), is_inf(a0)));\n      return if_else(test, Inf<result_type>(), res);\n      #else\n      return res;\n      #endif\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "ab39e4aa156333d896135ad602358c359eb350ca", "size": 2969, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/common/hypot.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/common/hypot.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/common/hypot.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 43.0289855072, "max_line_length": 86, "alphanum_fraction": 0.6335466487, "num_tokens": 712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916029436189, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.4451819055457481}}
{"text": "#include <math.h>\n#include <iostream>\n#include <Eigen/Cholesky>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\n#include \"fastQP.h\"\n#include \"gurobiQP.h\"\n\n#define _USE_MATH_DEFINES\n\n#define MAX_CONSTRS 1000\n#define MAX_STATE   1000\n#define MAX_ITER    10\n\n\nusing namespace Eigen;\nusing namespace std;\n\n\n//template <typename tA, typename tB, typename tC, typename tD, typename tE, typename tF, typename tG>\n//int fastQPThatTakesQinv(vector< MatrixBase<tA>* > QinvblkDiag, const MatrixBase<tB>& f, const MatrixBase<tC>& Aeq, const MatrixBase<tD>& beq, const MatrixBase<tE>& Ain, const MatrixBase<tF>& bin, set<int>& active, MatrixBase<tG>& x)\nint fastQPThatTakesQinv(vector< MatrixXd* > QinvblkDiag, const VectorXd& f, const MatrixXd& Aeq, const VectorXd& beq, const MatrixXd& Ain, const VectorXd& bin, set<int>& active, VectorXd& x)\n{\n  int i,d;\n  int iterCnt = 0;\n  \n  int M_in = bin.size();\n  int M = Aeq.rows();\n  int N = Aeq.cols();\n  \n  if (f.rows() != N) { cerr << \"size of f (\" << f.rows() << \" by \" << f.cols() << \") doesn't match cols of Aeq (\" << Aeq.rows() << \" by \" << Aeq.cols() << \")\" << endl; return 2; }\n  if (beq.rows() !=M) { cerr << \"size of beq doesn't match rows of Aeq\" << endl; return 2; }\n  if (Ain.cols() !=N) { cerr << \"cols of Ain doesn't match cols of Aeq\" << endl; return 2; };\n  if (bin.rows() != Ain.rows()) { cerr << \"bin rows doesn't match Ain rows\" << endl; return 2; };\n  if (x.rows() != N) { cerr << \"x doesn't match Aeq\" << endl; return 2; }\n  int n_active = active.size();\n\n  MatrixXd Aact = MatrixXd(n_active, N);\n  VectorXd bact = VectorXd(n_active);\n\n  MatrixXd QinvAteq(N,M);\n  VectorXd minusQinvf(N);\n\n  // calculate a bunch of stuff that is constant during each iteration\n  int startrow=0;\n//  for (typename vector< MatrixBase<tA>* >::iterator iterQinv=QinvblkDiag.begin(); iterQinv!=QinvblkDiag.end(); iterQinv++) {\n//  \tMatrixBase<tA> *thisQinv = *iterQinv;\n  for (vector< MatrixXd* >::iterator iterQinv=QinvblkDiag.begin(); iterQinv!=QinvblkDiag.end(); iterQinv++) {\n  \tMatrixXd *thisQinv = *iterQinv;\n  \tint numRow = thisQinv->rows();\n  \tint numCol = thisQinv->cols();\n\n  \tif (numRow == 1 || numCol == 1) {  // it's a vector\n  \t\td = numRow*numCol;\n  \t\tif (M>0) QinvAteq.block(startrow,0,d,M)= thisQinv->asDiagonal()*Aeq.block(0,startrow,M,d).transpose();  // Aeq.transpo\u001bODse().block(startrow,0,d,N)\n\t\t\tminusQinvf.segment(startrow,d) = -thisQinv->cwiseProduct(f.segment(startrow,d));\n\t\t\tstartrow=startrow+d;\n  \t} else { // potentially dense matrix\n\t\t\td = numRow;\n\t\t\tif (numRow!=numCol) {\n\t\t\t\t\tcerr << \"Q is not square! \" << numRow << \"x\" << numCol << \"\\n\";\n\t\t\t\t\treturn -2;\n\t\t\t}\n\t\t\tif (M>0) QinvAteq.block(startrow,0,d,M) = thisQinv->operator*(Aeq.block(0,startrow,M,d).transpose());  // Aeq.transpose().block(startrow,0,d,N)\n\t\t\tminusQinvf.segment(startrow,d) = -thisQinv->operator*(f.segment(startrow,d));\n\t\t\tstartrow=startrow+d;\n\t\t}\n  \tif (startrow>N) {\n\t\t\tcerr << \"Q is too big!\" << endl;\n\t\t\treturn -2;\n\t\t}\n  }\n  if (startrow!=N) { cerr << \"Q is the wrong size.  Got \" << startrow << \"by\" << startrow << \" but needed \" << N << \"by\" << N << endl; return -2; }\n\n  MatrixXd A;\n  VectorXd b;\n  MatrixXd QinvAt;\n  VectorXd lam, lamIneq;\n  VectorXd violated(M_in);\n  VectorXd violation;\n  \n  while(1) {\n    iterCnt++;\n\n    n_active = active.size();\n    Aact.resize(n_active,N);\n    bact.resize(n_active);\n\n    i=0;\n    for (set<int>::iterator iter=active.begin(); iter!=active.end(); iter++) {\n    \tif (*iter<0 || *iter>=Ain.rows()) {\n    \t\treturn -3;  // active set is invalid.  exit quietly, because this is expected behavior in normal operation (e.g. it means I should immediately kick out to gurobi)\n    \t}\n      Aact.row(i) = Ain.row(*iter);\n      bact(i++) = bin(*iter);\n    }\n\n    A.resize(Aeq.rows() + Aact.rows(),N);\n    b.resize(beq.size() + bact.size());\n    A << Aeq,Aact;\n    b << beq,bact;\n    \n    if (A.rows() > 0) {\n      //Solve H * [x;lam] = [-f;b] using Schur complements, H = [Q,At';A,0];\n      QinvAt.resize(QinvAteq.rows(), QinvAteq.cols() + Aact.rows());\n\n      if (n_active>0) {\n\t\t\t\tint startrow=0;\n\t\t\t\tfor (vector< MatrixXd* >::iterator iterQinv=QinvblkDiag.begin(); iterQinv!=QinvblkDiag.end(); iterQinv++) {\n\t\t\t\t\tMatrixXd* thisQinv = (*iterQinv);\n\t\t\t\t\td = thisQinv->rows();\n\t\t\t\t\tint numCol = thisQinv->cols();\n\n\t\t\t\t\tif (numCol == 1) {  // it's a vector\n\t\t\t\t\t\tQinvAt.block(startrow,0,d,M+n_active) << QinvAteq.block(startrow,0,d,M), thisQinv->asDiagonal()*Aact.block(0,startrow,n_active,d).transpose();\n\t\t\t\t\t} else { // it's a matrix\n\t\t\t\t\t\tQinvAt.block(startrow,0,d,M+n_active) << QinvAteq.block(startrow,0,d,M), thisQinv->operator*(Aact.block(0,startrow,n_active,d).transpose());\n\t\t\t\t\t}\n\n\t\t\t\t\tstartrow=startrow+d;\n\t\t\t\t}\n      } else {\n      \tQinvAt = QinvAteq;\n      }\n      \n      lam.resize(QinvAt.cols());\n      lam = -(A*QinvAt).ldlt().solve(b + (f.transpose()*QinvAt).transpose());\n      x = minusQinvf - QinvAt*lam;\n      lamIneq = lam.tail(lam.size() - M);\n    } else {\n      x = minusQinvf;\n      lamIneq.resize(0);\n    }\n  \n    if(Ain.rows() == 0) {\n      active.clear();\n      break;\n    }\n    \n    set<int> new_active;\n\n    violation = Ain*x - bin;\n    for (i=0; i<M_in; i++)\n      if (violation(i) >= 1e-6)\n      \tnew_active.insert(i);\n    \n    bool all_pos_mults = true;\n    for (i=0; i<n_active; i++) {\n    \tif (lamIneq(i)<0) {\n    \t\tall_pos_mults = false;\n    \t\tbreak;\n    \t}\n    }\n    if (new_active.empty() && all_pos_mults) {\n    \t// existing active was AOK\n    \tbreak;\n    }\n\n    i=0;\n    set<int>::iterator iter=active.begin(), tmp;\n    while (iter!=active.end()) { // to accomodating inloop erase\n  \t\ttmp = iter++;\n    \tif (lamIneq(i++)<0) {\n    \t\tactive.erase(tmp);\n    \t}\n    }\n    active.insert(new_active.begin(),new_active.end());\n\n    if (iterCnt > MAX_ITER) {\n      //Default to calling this method\n//      cout << \"FastQP max iter reached.\" << endl;\n//       mexErrMsgIdAndTxt(\"Drake:approximateIKmex:Error\", \"Max iter reached. Problem is likely infeasible\");\n      return -1;\n    }\n  }  \n  return iterCnt;\n}\n\n//template <typename tA, typename tB, typename tC, typename tD, typename tE, typename tF, typename tG>\n//int fastQP(vector< MatrixBase<tA>* > QblkDiag, const MatrixBase<tB>& f, const MatrixBase<tC>& Aeq, const MatrixBase<tD>& beq, const MatrixBase<tE>& Ain, const MatrixBase<tF>& bin, set<int>& active, MatrixBase<tG>& x)\nint fastQP(vector< MatrixXd* > QblkDiag, const VectorXd& f, const MatrixXd& Aeq, const VectorXd& beq, const MatrixXd& Ain, const VectorXd& bin, set<int>& active, VectorXd& x)\n{\n  /* min 1/2 * x'QblkDiag'x + f'x s.t A x = b, Ain x <= bin\n   * using active set method.  Iterative solve a linearly constrained\n   * quadratic minimization problem where linear constraints include\n   * Ain(active,:)x == bin(active).  Quit if all dual variables associated\n   * with these equations are positive (i.e. they satisfy KKT conditions).\n   *\n   * Note:\n   * fails if QP is infeasible.\n   * active == initial rows of Ain to treat as equations.\n   * Frank Permenter - June 6th 2013\n   *\n   * @retval  if feasible then iterCnt, else -1 for infeasible, -2 for input error\n   */\n\n\tint N = f.rows();\n\n  MatrixXd* Qinv = new MatrixXd[QblkDiag.size()];\n  vector< MatrixXd* > Qinvmap;\n\n\t#define REG 1e-13\n  // calculate a bunch of stuff that is constant during each iteration\n  int startrow=0;\n  //typedef typename vector< MatrixBase<tA> >::iterator Qiterator;\n\n  int i=0;\n  for (vector< MatrixXd* >::iterator iterQ=QblkDiag.begin(); iterQ!=QblkDiag.end(); iterQ++) {\n  \tMatrixXd* thisQ = *iterQ;\n  \tint numRow = thisQ->rows();\n  \tint numCol = thisQ->cols();\n\n  \tif (numCol == 1) {  // it's a vector\n  \t\tVectorXd Qdiag_mod = thisQ->operator+(VectorXd::Constant(numRow,REG)); // regularize\n  \t\tQinv[i] = Qdiag_mod.cwiseInverse();\n  \t\tQinvmap.push_back( &Qinv[i] );\n  \t\tstartrow=startrow+numRow;\n\t\t} else { // potentially dense matrix\n\t\t\tif (numRow!=numCol) {\n\t\t\t\tif (numRow==1)\n\t\t\t\t\tcerr << \"diagonal Q's must be set as column vectors\" << endl;\n\t\t\t\telse\n\t\t\t\t\tcerr << \"Q is not square! \" << numRow << \"x\" << numCol << endl;\n\t\t\t\treturn -2;\n\t\t\t}\n\n\t\t\tMatrixXd Q_mod = thisQ->operator+(REG*MatrixXd::Identity(numRow,numRow));\n\t\t\tQinv[i] = Q_mod.inverse();\n  \t\tQinvmap.push_back( &Qinv[i] );\n  \t\tstartrow=startrow+numRow;\n\t\t}\n//  \tcout << \"Qinv{\" << i << \"} = \" << Qinv[i] << endl;\n\t\tif (startrow>N) {\n\t\t\tcerr << \"Q is too big!\" << endl;\n\t\t\treturn -2;\n\t\t}\n\t\ti++;\n  }\n  if (startrow!=N) { cerr << \"Q is the wrong size.  Got \" << startrow << \"by\" << startrow << \" but needed \" << N << \"by\" << N << endl; return -2; }\n\n  int info = fastQPThatTakesQinv(Qinvmap,f,Aeq,beq,Ain,bin,active,x);\n\n  delete[] Qinv;\n  return info;\n}\n\n/* Example call (allocate inequality matrix, call function, resize inequalites:\n  VectorXd binBnd = VectorXd(2*N);\n  AinBnd.setZero();\n  int numIneq = boundToIneq(ub,lb,AinBnd,binBnd);\n  AinBnd.resize(numIneq,N);\n  binBnd.resize(numIneq);\n*/\n/*\nint boundToIneq(const VectorXd& uB,const VectorXd& lB, MatrixXd& Ain, VectorXd& bin)\n{\n    int rCnt = 0;\n    int cCnt = 0;\n\n    if (uB.rows()+lB.rows() > A.rows() ) {\n        cerr << \"not enough memory allocated\";\n    }\n\n    if (uB.rows()+lB.rows() > b.rows() ) {\n        cerr << \"not enough memory allocated\";\n    }\n\n    for (int i = 0; i < lB.rows(); i++ ) {\n        if (!isinf(lB(i))) {\n            cout << lB(i);\n            cout << i;\n            Ain(rCnt,cCnt++) = -1;//lB(i);\n            bin(rCnt++) = -lB(i);\n        }\n    }\n    cCnt = 0;\n    for (int i = 0; i < uB.rows(); i++ ) {\n        if (!isinf(uB(i))) {\n            Ain(rCnt,cCnt++) = 1;//uB(i);\n            bin(rCnt++) = uB(i);\n        }\n    }\n\n    //resizing inside function all causes exception (why??)\n    //A.resize(rCnt,uB.rows());\n    return rCnt;\n}\n*/\n\n\n\ntemplate <typename DerivedA,typename DerivedB>\nint myGRBaddconstrs(GRBmodel *model, MatrixBase<DerivedA> const & A, MatrixBase<DerivedB> const & b, char sense, double sparseness_threshold = 1e-14)\n{\n  int i,j,nnz,error=0;\n/*\n  // todo: it seems like I should just be able to do something like this:\n  SparseMatrix<double,RowMajor> sparseAeq(Aeq.sparseView());\n  sparseAeq.makeCompressed();\n  error = GRBaddconstrs(model,nq_con,sparseAeq.nonZeros(),sparseAeq.InnerIndices(),sparseAeq.OuterStarts(),sparseAeq.Values(),beq.data(),NULL);\n*/\n\n  int *cind = new int[A.cols()];\n  double* cval = new double[A.cols()];\n  for (i=0; i<A.rows(); i++) {\n    nnz=0;\n    for (j=0; j<A.cols(); j++) {\n      if (abs(A(i,j))>sparseness_threshold) {\n        cval[nnz] = A(i,j);\n        cind[nnz++] = j;\n      }\n    }\n    error = GRBaddconstr(model,nnz,cind,cval,sense,b(i),NULL);\n    if (error) break;\n  }\n\n  delete[] cind;\n  delete[] cval;\n  return error;\n}\n\n//template <typename tA, typename tB, typename tC, typename tD, typename tE>\n//GRBmodel* gurobiQP(GRBenv *env, vector< MatrixBase<tA>* > QblkDiag, VectorXd& f, const MatrixBase<tB>& Aeq, const MatrixBase<tC>& beq, const MatrixBase<tD>& Ain, const MatrixBase<tE>& bin, VectorXd& lb, VectorXd& ub, set<int>& active, VectorXd& x)\nGRBmodel* gurobiQP(GRBenv *env, vector< MatrixXd* > QblkDiag, VectorXd& f, const MatrixXd& Aeq, const VectorXd& beq, \n  const MatrixXd& Ain, const VectorXd& bin, VectorXd& lb, VectorXd& ub, set<int>& active, VectorXd& x, double active_set_slack_tolerance)\n{\n\t// Note: f,lb, and ub are VectorXd instead of const MatrixBase templates because i want to be able to call f.data() on them\n\n\t// NOTE:  this allocates memory for a new GRBmodel and returns it. (you should delete this object when you're done with it)\n\t// NOTE:  by convention here, the active set indices correspond to Ain,bin first, then lb, then ub.\n\n  GRBmodel *model = NULL;\n\n  int method;  GRBgetintparam(env,\"method\",&method);\n\n  int i,j,nparams = f.rows(),Qi,Qj;\n  double *lbdata = NULL, *ubdata=NULL;\n  if (lb.rows()==nparams) lbdata = lb.data();\n  if (ub.rows()==nparams) ubdata = ub.data();\n  CGE (GRBnewmodel(env,&model,\"QP\",nparams,NULL,lbdata,ubdata,NULL,NULL), env);\n\n  int startrow=0,d;\n  for (vector< MatrixXd* >::iterator iterQ=QblkDiag.begin(); iterQ!=QblkDiag.end(); iterQ++) {\n  \tMatrixXd* Q=*iterQ;\n    \n    // WARNING:  If there are no constraints, then gurobi clearly solves a different problem: min 1/2 x'Qx + f'x\n    //  \t\t\t\t This is very strange; see the solveWGUROBI method in QuadraticProgram\n    if (method==2) //&& (Aeq.rows()+Ain.rows()>0))\n      *Q = .5* (*Q);\n    \n  \tif (Q->rows() == 1 || Q->cols() == 1) {  // it's a vector\n  \t\td = Q->rows()*Q->cols();\n  \t  for (i=0; i<d; i++) {\n  \t  \tQi=i+startrow;\n  \t  \tCGE (GRBaddqpterms(model,1,&Qi,&Qi,&(Q->operator()(i))), env);\n  \t  }\n  \t  startrow=startrow+d;\n  \t} else { // potentially dense matrix\n  \t\td = Q->rows();\n  \t\tif (d!=Q->cols()) {\n  \t\t\tcerr << \"Q is not square! \" << Q->rows() << \"x\" << Q->cols() << \"\\n\";\n  \t\t\treturn NULL;\n  \t\t}\n\n  \t  for (i=0; i<d; i++)\n    \t  for (j=0; j<d; j++) {\n    \t  \tQi=i+startrow; Qj = j+startrow;\n    \t  \tCGE (GRBaddqpterms(model,1,&Qi,&Qj,&(Q->operator()(i,j))), env);\n    \t  }\n  \t  startrow=startrow+d;\n  \t}\n  \tif (startrow>nparams) {\n  \t\tcerr << \"Q is too big!\" << endl;\n  \t\treturn NULL;\n  \t}\n  }\n\n  CGE (GRBsetdblattrarray(model,\"Obj\",0,nparams,f.data()), env);\n\n  if (Aeq.rows()>0) CGE (myGRBaddconstrs(model,Aeq,beq,GRB_EQUAL, 1e-18), env);\n  if (Ain.rows()>0) CGE (myGRBaddconstrs(model,Ain,bin,GRB_LESS_EQUAL, 1e-18), env);\n\n  CGE (GRBupdatemodel(model), env);\n  CGE (GRBoptimize(model), env);\n\n  CGE (GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, nparams, x.data()), env);\n\n  VectorXd slack(Ain.rows());\n  CGE (GRBgetdblattrarray(model, \"Slack\", Aeq.rows(), Ain.rows(), slack.data()), env);\n\n  int offset=0;\n  active.clear();\n  for (int i=0; i<Ain.rows(); i++) {\n  \tif (slack(i)<active_set_slack_tolerance)\n  \t\tactive.insert(i);\n  }\n  offset = Ain.rows();\n  if (lb.rows()==nparams)\n  \tfor (int i=0; i<nparams; i++)\n  \t\tif (x(i)-lb(i) < active_set_slack_tolerance)\n  \t\t\tactive.insert(offset+i);\n  if (ub.rows()==nparams)\n  \tfor (int i=0; i<nparams; i++)\n  \t\tif (ub(i)-x(i) < active_set_slack_tolerance)\n  \t\t\tactive.insert(offset+i+nparams);\n\n  return model;\n}\n\n\nGRBmodel* gurobiActiveSetQP(GRBenv *env, vector< MatrixXd* > QblkDiag, VectorXd& f, const MatrixXd& Aeq, const VectorXd& beq, \n  const MatrixXd& Ain, const VectorXd& bin, VectorXd& lb, VectorXd& ub, int* &vbasis, int vbasis_len, int* &cbasis, int cbasis_len, VectorXd& x)\n{\n  // NOTE:  this allocates memory for a new GRBmodel and returns it. (you should delete this object when you're done with it)\n  // NOTE:  by convention here, the active set indices correspond to Ain,bin first, then lb, then ub.\n  GRBmodel *model = NULL;\n\n  int method;  GRBgetintparam(env,\"method\",&method);\n  if (!(method==0 || method==1)) {\n    cerr<< \"gurobiActiveSetQP: method should be 0 or 1\" << endl;\n    return NULL;\n  }\n\n  int i,j,nparams = f.rows(),Qi,Qj;\n  double *lbdata = NULL, *ubdata=NULL;\n  if (lb.rows()==nparams) lbdata = lb.data();\n  if (ub.rows()==nparams) ubdata = ub.data();\n  CGE (GRBnewmodel(env,&model,\"QP\",nparams,NULL,lbdata,ubdata,NULL,NULL), env);\n\n  int startrow=0,d;\n  for (vector< MatrixXd* >::iterator iterQ=QblkDiag.begin(); iterQ!=QblkDiag.end(); iterQ++) {\n    MatrixXd* Q=*iterQ;\n    \n\t*Q = .5* (*Q);\n    \n    if (Q->rows() == 1 || Q->cols() == 1) {  // it's a vector\n      d = Q->rows()*Q->cols();\n      for (i=0; i<d; i++) {\n        Qi=i+startrow;\n        CGE (GRBaddqpterms(model,1,&Qi,&Qi,&(Q->operator()(i))), env);\n      }\n      startrow=startrow+d;\n    } else { // potentially dense matrix\n      d = Q->rows();\n      if (d!=Q->cols()) {\n        cerr << \"Q is not square! \" << Q->rows() << \"x\" << Q->cols() << \"\\n\";\n        return NULL;\n      }\n\n      for (i=0; i<d; i++)\n        for (j=0; j<d; j++) {\n          Qi=i+startrow; Qj = j+startrow;\n          CGE (GRBaddqpterms(model,1,&Qi,&Qj,&(Q->operator()(i,j))), env);\n        }\n      startrow=startrow+d;\n    }\n    if (startrow>nparams) {\n      cerr << \"Q is too big!\" << endl;\n      return NULL;\n    }\n  }\n\n  CGE (GRBsetdblattrarray(model,\"Obj\",0,nparams,f.data()), env);\n\n  if (Aeq.rows()>0) CGE (myGRBaddconstrs(model,Aeq,beq,GRB_EQUAL, 1e-18), env);\n  if (Ain.rows()>0) CGE (myGRBaddconstrs(model,Ain,bin,GRB_LESS_EQUAL, 1e-18), env);\n\n  CGE (GRBupdatemodel(model), env);\n\n  int numvars; CGE(GRBgetintattr(model,\"NumVars\",&numvars), env);\n  if (numvars == vbasis_len) {\n    CGE (GRBsetintattrarray(model, \"VBasis\", 0, numvars, vbasis), env);\n  }\n  else {\n    delete[] vbasis;\n    vbasis = new int[numvars];\n  }\n\n  int numconstr; CGE(GRBgetintattr(model,\"NumConstrs\",&numconstr),env);\n  if (numconstr == cbasis_len) {\n    CGE (GRBsetintattrarray(model, \"CBasis\", 0, numconstr, cbasis), env);\n  }\n  else {\n    delete[] cbasis;\n    cbasis = new int[numconstr];\n  }\n  CGE (GRBoptimize(model), env);\n\n  CGE (GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, nparams, x.data()), env);\n\n  CGE (GRBgetintattrarray(model, \"VBasis\", 0, numvars, vbasis), env);\n  CGE (GRBgetintattrarray(model, \"CBasis\", 0, numconstr, cbasis), env);\n\n  return model;\n}\n\n\n\n/*\ntemplate int fastQP(vector< MatrixBase<MatrixXd>* > QblkDiag, const MatrixBase< Map<VectorXd> >&, const MatrixBase< Map<MatrixXd> >&, const MatrixBase< Map<VectorXd> >&, const MatrixBase< Map<MatrixXd> >&, const MatrixBase< Map<VectorXd> >&, set<int>&, MatrixBase< Map<VectorXd> >&);\ntemplate GRBmodel* gurobiQP(GRBenv *env, vector< MatrixBase<MatrixXd>* > QblkDiag, VectorXd& f, const MatrixBase< Map<MatrixXd> >& Aeq, const MatrixBase< Map<VectorXd> >& beq, const MatrixBase< Map<MatrixXd> >& Ain, const MatrixBase< Map<VectorXd> >&bin, VectorXd& lb, VectorXd& ub, set<int>&, VectorXd&);\ntemplate GRBmodel* gurobiQP(GRBenv *env, vector< MatrixBase<MatrixXd>* > QblkDiag, VectorXd& f, const MatrixBase< MatrixXd >& Aeq, const MatrixBase< VectorXd >& beq, const MatrixBase< MatrixXd >& Ain, const MatrixBase< VectorXd >&bin, VectorXd&lb, VectorXd&ub, set<int>&, VectorXd&);\n*/\n\n/*\ntemplate int fastQP(vector< MatrixBase< VectorXd > >, const MatrixBase< VectorXd >&, const MatrixBase< Matrix<double,-1,-1,RowMajor,1000,-1> >&, const MatrixBase< Matrix<double,-1,1,0,1000,1> >&, const MatrixBase< Matrix<double,-1,-1,RowMajor,1000,-1> >&, const MatrixBase< Matrix<double,-1,1,0,1000,1> >&, set<int>&, MatrixBase< VectorXd >&);\n*/\n\n\n\n", "meta": {"hexsha": "269da69c3f93ac12fd93fce5461d58bfcc5bd143", "size": 18152, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solvers/QP.cpp", "max_stars_repo_name": "jacob-izr/drake", "max_stars_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T09:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T21:59:27.000Z", "max_issues_repo_path": "solvers/QP.cpp", "max_issues_repo_name": "jacob-izr/drake", "max_issues_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/QP.cpp", "max_forks_repo_name": "jacob-izr/drake", "max_forks_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-08-24T20:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-24T20:32:03.000Z", "avg_line_length": 35.453125, "max_line_length": 343, "alphanum_fraction": 0.6196011459, "num_tokens": 5979, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.44507106646183203}}
{"text": "/**\n   \\file aga.hpp\n   \\brief asexual genetic algorithm method\n   \\author Junhua Gu\n*/\n\n#ifndef AGA_METHOD\n#define AGA_METHOD\n#define OPT_HEADER\n#include <core/optimizer.hpp>\n//#include <blitz/array.h>\n#include <limits>\n#include <cstdlib>\n#include <core/opt_traits.hpp>\n#include <cassert>\n#include <cmath>\n#include <ctime>\n#include <vector>\n#include <algorithm>\n/*\n *\n*/\n#include <iostream>\nusing std::cout;\nusing std::endl;\n\nnamespace opt_utilities\n{\n\n  template <typename rT,typename pT>\n  struct vp_pair\n  {\n    rT v;\n    pT p;\n  };\n  \n  template <typename rT,typename pT>\n  class vp_comp\n  {\n  public:\n    bool operator()(const vp_pair<rT,pT>& x1,\n\t\t    const vp_pair<rT,pT>& x2)\n    {\n      return x1.v<x2.v;\n    }\n  };\n\n\n  /**\n     \\brief Implement of the asexual genetic algorithm\n     2009A&A...501.1259C\n     http://adsabs.harvard.edu/abs/2009arXiv0905.3712C\n     \\tparam rT return type of the object function\n     \\tparam pT parameter type of the object function\n   */\n  template <typename rT,typename pT>\n  class aga_method\n    :public opt_method<rT,pT>\n  {\n  public:\n    typedef pT array1d_type;\n  private:\n    int n1,n2,n0;\n    func_obj<rT,pT>* p_fo;\n    optimizer<rT,pT>* p_optimizer;\n    rT threshold;\n    pT lower_bound;\n    pT upper_bound;\n    \n    typename element_type_trait<pT>::element_type decay_factor;\n    pT reproduction_box;\n    std::vector<vp_pair<rT,pT> > samples;\n    std::vector<pT> buffer;\n    mutable bool bstop;\n  private:\n    typename element_type_trait<pT>::element_type uni_rand\n    (typename element_type_trait<pT>::element_type x1,\n     typename element_type_trait<pT>::element_type x2)\n    {\n      return rand()/(double)RAND_MAX*(x2-x1)+x1;\n    }\n    \n  private:\n    const char* do_get_type_name()const\n    {\n      return \"asexual genetic algorithm\";\n    }\n    \n    rT func(const pT& x)\n    {\n      assert(p_fo!=0);\n      return p_fo->eval(x);\n    }\n\n  public:\n    aga_method(int _n1,int _n2)\n      :n1(_n1),n2(_n2),n0(n1*n2+n1),\n       p_fo(0),p_optimizer(0),threshold(1e-4),\n       decay_factor(.999),\n       samples(n1*n2+n1)      \n    {\n    }\n    \n    aga_method()\n      :n1(50),n2(20),n0(n1*n2+n1),\n       p_fo(0),p_optimizer(0),threshold(1e-4),\n       decay_factor(.999),\n       samples(n1*n2+n1)      \n    {\n    }\n    \n\n    virtual ~aga_method()\n    {     \n    };\n    \n    aga_method(const aga_method<rT,pT>& rhs)\n      :n1(rhs.n1),n2(rhs.n2),n0(rhs.n0),\n       p_fo(rhs.p_fo),p_optimizer(rhs.p_optimizer),\n       threshold(rhs.threshold),\n       decay_factor(rhs.decay_factor),\n       samples(rhs.samples)\n    {\n    }\n\n    aga_method<rT,pT>& operator=(const aga_method<rT,pT>& rhs)\n    {\n      threshold=rhs.threshold;\n      p_fo=rhs.p_fo;\n      p_optimizer=rhs.p_optimizer;\n      samples=rhs.samples;\n      n1=rhs.n1;\n      n2=rhs.n2;\n      n0=rhs.n0;\n    }\n\n    void set_decay_factor(typename element_type_trait<pT>::element_type _decay_factor)\n    {\n      decay_factor=_decay_factor;\n    }\n\n    \n    opt_method<rT,pT>* do_clone()const\n    {\n      return new aga_method<rT,pT>(*this);\n    }\n    \n    void do_set_start_point(const array1d_type& p)\n    {\n      for(size_t i=0;i<samples.size();++i)\n\t{\n\t  //  cout<<i<<\" \";\n\t  resize(samples[i].p,get_size(p));\n\t  //\t  std::cout<<samples[i].p.size()<<std::endl;;\n\t  for(size_t j=0;j<get_size(p);++j)\n\t    {\n\t      set_element(samples[i].p,j,\n\t\t\t  uni_rand(get_element(lower_bound,j),\n\t\t\t\t   get_element(upper_bound,j))\n\t\t\t  );\n\t    }\n\t}\n      \n    }\n\n    array1d_type do_get_start_point()const\n    {\n      return array1d_type();\n    }\n    \n    void do_set_lower_limit(const array1d_type& p)\n    {\n      opt_eq(lower_bound,p);\n    }\n\n    array1d_type do_get_lower_limit()const\n    {\n      return lower_bound;\n    }\n    \n    void do_set_upper_limit(const array1d_type& p)\n    {\n      opt_eq(upper_bound,p);\n    }\n\n    array1d_type do_get_upper_limit()const\n    {\n      return upper_bound;\n    }\n    \n\n    void do_set_precision(rT t)\n    {\n      threshold=t;\n    }\n\n    rT do_get_precision()const\n    {\n      return threshold;\n    }\n\n    void do_set_optimizer(optimizer<rT,pT>& o)\n    {\n      p_optimizer=&o;\n      p_fo=p_optimizer->ptr_func_obj();\n    }\n    \n    bool iter()\n    {\n      rT sum2=0;\n      rT sum=0;\n      for(size_t i=0;i<samples.size();++i)\n\t{\n\t  samples[i].v=func(samples[i].p);\n\t  sum2+=samples[i].v*samples[i].v;\n\t  sum+=samples[i].v;\n\t}\n      \n      std::sort(samples.begin(),samples.end(),vp_comp<rT,pT>());\n      if(sum2/samples.size()-pow(sum/samples.size(),2)<threshold)\n\t{\n\t  return false;\n\t}\n      pT lb(get_size(samples[0].p));\n      pT ub(get_size(samples[0].p));\n      for(int i=0;i<n2&&!bstop;++i)\n\t{\n\t  pT p(samples[i].p);\n\t  for(size_t j=0;j<get_size(p);++j)\n\t    {\n\t      if(i==0)\n\t\t{\n\t\t  ub[j]=p[j];\n\t\t  lb[j]=p[j];\n\t\t}\n\t      ub[j]=std::max(ub[j],p[j]);\n\t      lb[j]=std::min(lb[j],p[j]);\n\t      \n\t      set_element(p,j,\n\t\t\t  get_element(p,j)+\n\t\t\t  uni_rand(-get_element(reproduction_box,j),\n\t\t\t\t   get_element(reproduction_box,j)));\n\t      if(get_element(p,j)>get_element(upper_bound,j))\n\t\t{\n\t\t  set_element(p,j,get_element(upper_bound,j));\n\t\t}\n\t      if(get_element(p,j)<get_element(lower_bound,j))\n\t\t{\n\t\t  set_element(p,j,get_element(lower_bound,j));\n\t\t}\n\t    }\n\t  buffer[i]=p;\n\t}\n      if(bstop)\n\t{\n\t  return false;\n\t}\n      for(int i=0;i<n1&&!bstop;++i)\n\t{\n\t  for(int j=0;j<n2&&!bstop;++j)\n\t    {\n\t      pT p(samples[i].p);\n\t      for(size_t k=0;k<get_size(p);++k)\n\t\t{\n\t\t  set_element(samples[i*n2+j+n1].p,k,\n\t\t\t      (get_element(samples[i].p,k)+\n\t\t\t       get_element(buffer[j],k))/2.);\n\t\t  \n\n\t\t  ub[k]=std::max(ub[k],samples[i*n2+j+n1].p[k]);\n\t\t  lb[k]=std::min(lb[k],samples[i*n2+j+n1].p[k]);\n\t\t}\n\t    }\n\t}\n      if(bstop)\n\t{\n\t  return false;\n\t}\n      double n_per_dim=pow((double)n0,1./get_size(lower_bound));\n      for(size_t i=0;i<get_size(reproduction_box);++i)\n\t{\n\t  //\t  set_element(reproduction_box,i,\n\t  //get_element(reproduction_box,i)*decay_factor);\n\t  set_element(reproduction_box,i,\n\t\t      (get_element(ub,i)-\n\t\t       get_element(ub,i))/n_per_dim);\n\t  \n\t}\n      return true;\n    }\n      \n    pT do_optimize()\n    {\n      bstop=false;\n      srand(time(0));\n      buffer.resize(n2);\n      double n_per_dim=pow((double)n0,1./get_size(lower_bound));\n      resize(reproduction_box,get_size(lower_bound));\n      \n      for(size_t i=0;i<get_size(lower_bound);++i)\n\t{\n\t  \n\t  set_element(reproduction_box,i,\n\t\t      (get_element(upper_bound,i)-\n\t\t       get_element(lower_bound,i))/n_per_dim);\n\t}\n      \n      while(iter()&&!bstop){}\n      \n      return samples.begin()->p;\n    }\n    \n    void do_stop()\n    {\n      bstop=true;\n    }\n\n  };\n\n}\n\n\n#endif\n//EOF\n", "meta": {"hexsha": "624540a6752af37d88c69250a36a3ef1a3105608", "size": 6602, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "methods/aga/aga.hpp", "max_stars_repo_name": "liweitianux/opt_utilities", "max_stars_repo_head_hexsha": "17363d2b870c88db108984a9a59d79c12d677e93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "methods/aga/aga.hpp", "max_issues_repo_name": "liweitianux/opt_utilities", "max_issues_repo_head_hexsha": "17363d2b870c88db108984a9a59d79c12d677e93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "methods/aga/aga.hpp", "max_forks_repo_name": "liweitianux/opt_utilities", "max_forks_repo_head_hexsha": "17363d2b870c88db108984a9a59d79c12d677e93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T16:14:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-05T16:14:44.000Z", "avg_line_length": 20.3138461538, "max_line_length": 86, "alphanum_fraction": 0.584822781, "num_tokens": 1992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.44505758117626204}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2017 Adam Wulkiewicz, Lodz, Poland.\r\n\r\n// Copyright (c) 2016-2018 Oracle and/or its affiliates.\r\n// Contributed and/or modified by Vissarion Fisikopoulos, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_AREA_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_AREA_HPP\r\n\r\n\r\n#include <boost/geometry/formulas/area_formulas.hpp>\r\n#include <boost/geometry/srs/sphere.hpp>\r\n#include <boost/geometry/strategies/area.hpp>\r\n#include <boost/geometry/strategies/spherical/get_radius.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace area\r\n{\r\n\r\n\r\n/*!\r\n\\brief Spherical area calculation\r\n\\ingroup strategies\r\n\\details Calculates area on the surface of a sphere using the trapezoidal rule\r\n\\tparam RadiusTypeOrSphere \\tparam_radius_or_sphere\r\n\\tparam CalculationType \\tparam_calculation\r\n\r\n\\qbk{\r\n[heading See also]\r\n[link geometry.reference.algorithms.area.area_2_with_strategy area (with strategy)]\r\n}\r\n*/\r\ntemplate\r\n<\r\n    typename RadiusTypeOrSphere = double,\r\n    typename CalculationType = void\r\n>\r\nclass spherical\r\n{\r\n    // Enables special handling of long segments\r\n    static const bool LongSegment = false;\r\n\r\npublic:\r\n    template <typename Geometry>\r\n    struct result_type\r\n        : strategy::area::detail::result_type\r\n            <\r\n                Geometry,\r\n                CalculationType\r\n            >\r\n    {};\r\n\r\n    template <typename Geometry>\r\n    class state\r\n    {\r\n        friend class spherical;\r\n\r\n        typedef typename result_type<Geometry>::type return_type;\r\n\r\n    public:\r\n        inline state()\r\n            : m_sum(0)\r\n            , m_crosses_prime_meridian(0)\r\n        {}\r\n\r\n    private:\r\n        template <typename RadiusType>\r\n        inline return_type area(RadiusType const& r) const\r\n        {\r\n            return_type result;\r\n            return_type radius = r;\r\n\r\n            // Encircles pole\r\n            if(m_crosses_prime_meridian % 2 == 1)\r\n            {\r\n                size_t times_crosses_prime_meridian\r\n                        = 1 + (m_crosses_prime_meridian / 2);\r\n\r\n                result = return_type(2)\r\n                         * geometry::math::pi<return_type>()\r\n                         * times_crosses_prime_meridian\r\n                         - geometry::math::abs(m_sum);\r\n\r\n                if(geometry::math::sign<return_type>(m_sum) == 1)\r\n                {\r\n                    result = - result;\r\n                }\r\n\r\n            } else {\r\n                result =  m_sum;\r\n            }\r\n\r\n            result *= radius * radius;\r\n\r\n            return result;\r\n        }\r\n\r\n        return_type m_sum;\r\n\r\n        // Keep track if encircles some pole\r\n        size_t m_crosses_prime_meridian;\r\n    };\r\n\r\npublic :\r\n\r\n    // For backward compatibility reasons the radius is set to 1\r\n    inline spherical()\r\n        : m_radius(1.0)\r\n    {}\r\n\r\n    template <typename RadiusOrSphere>\r\n    explicit inline spherical(RadiusOrSphere const& radius_or_sphere)\r\n        : m_radius(strategy_detail::get_radius\r\n                    <\r\n                        RadiusOrSphere\r\n                    >::apply(radius_or_sphere))\r\n    {}\r\n\r\n    template <typename PointOfSegment, typename Geometry>\r\n    inline void apply(PointOfSegment const& p1,\r\n                      PointOfSegment const& p2,\r\n                      state<Geometry>& st) const\r\n    {\r\n        if (! geometry::math::equals(get<0>(p1), get<0>(p2)))\r\n        {\r\n            typedef geometry::formula::area_formulas\r\n                <\r\n                    typename result_type<Geometry>::type\r\n                > area_formulas;\r\n\r\n            st.m_sum += area_formulas::template spherical<LongSegment>(p1, p2);\r\n\r\n            // Keep track whenever a segment crosses the prime meridian\r\n            if (area_formulas::crosses_prime_meridian(p1, p2))\r\n            {\r\n                st.m_crosses_prime_meridian++;\r\n            }\r\n        }\r\n    }\r\n\r\n    template <typename Geometry>\r\n    inline typename result_type<Geometry>::type\r\n        result(state<Geometry> const& st) const\r\n    {\r\n        return st.area(m_radius);\r\n    }\r\n\r\nprivate :\r\n    typename strategy_detail::get_radius\r\n        <\r\n            RadiusTypeOrSphere\r\n        >::type m_radius;\r\n};\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\nnamespace services\r\n{\r\n\r\n\r\ntemplate <>\r\nstruct default_strategy<spherical_equatorial_tag>\r\n{\r\n    typedef strategy::area::spherical<> type;\r\n};\r\n\r\n// Note: spherical polar coordinate system requires \"get_as_radian_equatorial\"\r\ntemplate <>\r\nstruct default_strategy<spherical_polar_tag>\r\n{\r\n    typedef strategy::area::spherical<> type;\r\n};\r\n\r\n} // namespace services\r\n\r\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\n\r\n}} // namespace strategy::area\r\n\r\n\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_AREA_HPP\r\n", "meta": {"hexsha": "0f4b646612560c53591ff52e7d31f8363fdaa41d", "size": 5154, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/geometry/strategies/spherical/area.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "deps/boost/include/boost/geometry/strategies/spherical/area.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "deps/boost/include/boost/geometry/strategies/spherical/area.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 26.2959183673, "max_line_length": 84, "alphanum_fraction": 0.6049670159, "num_tokens": 1096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.44505758117626193}}
{"text": "/// @brief Eigen wrappers for the exact CCD methods.\n\n#pragma once\n\n#include <Eigen/Core>\n\nnamespace IPC {\nnamespace ExactCCD {\n\n/// @brief Methods of geometrically exact continous collision detection.\nenum Method {\n    NONE, ///< @brief Do not use exact CCD.\n    ROOT_PARITY, ///< @brief Root parity method of Brochu et al. [2012].\n    BSC, ///< @brief Bernstein sign classification method of Tang et al. [2014].\n    RATIONAL_ROOT_PARITY ///< @brief Teseo's reimplementation of Brochu et al. [2012] using rationals\n};\n\n/**\n * @brief Detect collisions between two edges as they move.\n *\n * Looks for collisions between edges (q0start, p0start) and (q1start, p1start)\n * as they move towards (q0end, p0end) and (q1end, p1end). Returns true if the\n * edges collide.\n *\n * @param[in]  q0start  Start position of the first edge's first vertex.\n * @param[in]  p0start  Start position of the first edge's second vertex.\n * @param[in]  q1start  Start position of the second edge's first vertex.\n * @param[in]  p1start  Start position of the second edge's second vertex.\n * @param[in]  q0end    End position of the first edge's first vertex.\n * @param[in]  p0end    End position of the first edge's second vertex.\n * @param[in]  q1end    End position of the second edge's first vertex.\n * @param[in]  p1end    End position of the second edge's second vertex.\n * @param[in]  method   Method of exact CCD.\n *\n * @returns True if the edges collide.\n */\nbool edgeEdgeCCD(\n    const Eigen::Vector3d& q0start,\n    const Eigen::Vector3d& p0start,\n    const Eigen::Vector3d& q1start,\n    const Eigen::Vector3d& p1start,\n    const Eigen::Vector3d& q0end,\n    const Eigen::Vector3d& p0end,\n    const Eigen::Vector3d& q1end,\n    const Eigen::Vector3d& p1end,\n    const Method method);\n\n/**\n * @brief Detect collisions between a vertex and a triangular face.\n *\n * Looks for collisions between the vertex q0start and the face\n * (q1start, q2start, q3start) as they move towards q0end and\n * (q1end, q2end, q3end). Returns true if the vertex and face collide.\n *\n * @param[in]  q0start  Start position of the vertex.\n * @param[in]  q1start  Start position of the first vertex of the face.\n * @param[in]  q2start  Start position of the second vertex of the face.\n * @param[in]  q3start  Start position of the third vertex of the face.\n * @param[in]  q0end    End position of the vertex.\n * @param[in]  q1end    End position of the first vertex of the face.\n * @param[in]  q2end    End position of the second vertex of the face.\n * @param[in]  q3end    End position of the third vertex of the face.\n * @param[in]  method   Method of exact CCD.\n *\n * @returns  True if the vertex and face collide.\n */\nbool vertexFaceCCD(\n    const Eigen::Vector3d& q0start,\n    const Eigen::Vector3d& q1start,\n    const Eigen::Vector3d& q2start,\n    const Eigen::Vector3d& q3start,\n    const Eigen::Vector3d& q0end,\n    const Eigen::Vector3d& q1end,\n    const Eigen::Vector3d& q2end,\n    const Eigen::Vector3d& q3end,\n    const Method method);\n\n}\n} // namespace IPC::ExactCCD\n", "meta": {"hexsha": "293d6ffaa22e363fe265d7caed8ed3ce3db721aa", "size": 3036, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/CCD/ExactCCD.hpp", "max_stars_repo_name": "asmaloney/IPC", "max_stars_repo_head_hexsha": "fcf72a951c072d0ea1755ccf27cbb03df0f2f8ea", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T18:39:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:19:14.000Z", "max_issues_repo_path": "src/CCD/ExactCCD.hpp", "max_issues_repo_name": "Kirkice/IPC", "max_issues_repo_head_hexsha": "ad40d232c09360cd4851b5badbc899df37b851a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-03T18:47:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T19:41:49.000Z", "max_forks_repo_path": "src/CCD/ExactCCD.hpp", "max_forks_repo_name": "Kirkice/IPC", "max_forks_repo_head_hexsha": "ad40d232c09360cd4851b5badbc899df37b851a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-03T18:57:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T06:43:37.000Z", "avg_line_length": 37.95, "max_line_length": 101, "alphanum_fraction": 0.7002635046, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4450575811762619}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2009, Willow Garage, Inc.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n#include \"precomp.hpp\"\n\n// Eigen\n#include <Eigen/Core>\n\n// OpenCV\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/sfm/projection.hpp>\n#include <opencv2/sfm/triangulation.hpp>\n#include <opencv2/sfm/fundamental.hpp>\n#include <opencv2/sfm/numeric.hpp>\n#include <opencv2/sfm/conditioning.hpp>\n\n// libmv headers\n#include \"libmv/multiview/fundamental.h\"\n\n#include <iostream>\nusing namespace std;\n\nnamespace cv\n{\nnamespace sfm\n{\n  template<typename T>\n  void\n  projectionsFromFundamental( const Mat_<T> &F,\n                              Mat_<T> P1,\n                              Mat_<T> P2 )\n  {\n    P1 << 1, 0, 0, 0,\n          0, 1, 0, 0,\n          0, 0, 1, 0;\n\n    Vec<T,3> e2;\n    cv::SVD::solveZ(F.t(), e2);\n\n    Mat_<T> P2cols = skew(e2) * F;\n    for(char j=0;j<3;++j) {\n      for(char i=0;i<3;++i)\n        P2(j,i) = P2cols(j,i);\n      P2(j,3) = e2(j);\n    }\n\n  }\n\n  void\n  projectionsFromFundamental( InputArray _F,\n                              OutputArray _P1,\n                              OutputArray _P2 )\n  {\n    const Mat F = _F.getMat();\n    const int depth = F.depth();\n    CV_Assert(F.cols == 3 && F.rows == 3 && (depth == CV_32F || depth == CV_64F));\n\n    _P1.create(3, 4, depth);\n    _P2.create(3, 4, depth);\n\n    Mat P1 = _P1.getMat(),  P2 = _P2.getMat();\n\n    // type\n    if( depth == CV_32F )\n    {\n      projectionsFromFundamental<float>(F, P1, P2);\n    }\n    else\n    {\n      projectionsFromFundamental<double>(F, P1, P2);\n    }\n\n  }\n\n  template<typename T>\n  void\n  fundamentalFromProjections( const Mat_<T> &P1,\n                              const Mat_<T> &P2,\n                              Mat_<T> F )\n  {\n    Mat_<T> X[3];\n    vconcat( P1.row(1), P1.row(2), X[0] );\n    vconcat( P1.row(2), P1.row(0), X[1] );\n    vconcat( P1.row(0), P1.row(1), X[2] );\n\n    Mat_<T> Y[3];\n    vconcat( P2.row(1), P2.row(2), Y[0] );\n    vconcat( P2.row(2), P2.row(0), Y[1] );\n    vconcat( P2.row(0), P2.row(1), Y[2] );\n\n    Mat_<T> XY;\n    for (int i = 0; i < 3; ++i)\n      for (int j = 0; j < 3; ++j)\n      {\n        vconcat(X[j], Y[i], XY);\n        F(i, j) = determinant(XY);\n      }\n  }\n\n  void\n  fundamentalFromProjections( InputArray _P1,\n                              InputArray _P2,\n                              OutputArray _F )\n  {\n    const Mat P1 = _P1.getMat(), P2 = _P2.getMat();\n    const int depth = P1.depth();\n    CV_Assert((P1.cols == 4 && P1.rows == 3) && P1.rows == P2.rows && P1.cols == P2.cols);\n    CV_Assert((depth == CV_32F || depth == CV_64F) && depth == P2.depth());\n\n    _F.create(3, 3, depth);\n\n    Mat F = _F.getMat();\n\n    // type\n    if( depth == CV_32F )\n    {\n      fundamentalFromProjections<float>(P1, P2, F);\n    }\n    else\n    {\n      fundamentalFromProjections<double>(P1, P2, F);\n    }\n\n  }\n\n  template<typename T>\n  void\n  normalizedEightPointSolver( const Mat_<T> &_x1,\n                              const Mat_<T> &_x2,\n                              Mat_<T> _F )\n  {\n    libmv::Mat x1, x2;\n    libmv::Mat3 F;\n\n    cv2eigen(_x1, x1);\n    cv2eigen(_x2, x2);\n\n    libmv::NormalizedEightPointSolver(x1, x2, &F);\n\n    eigen2cv(F, _F);\n  }\n\n  void\n  normalizedEightPointSolver( InputArray _x1, InputArray _x2, OutputArray _F )\n  {\n    const Mat x1 = _x1.getMat(), x2 = _x2.getMat();\n    const int depth = x1.depth();\n    CV_Assert(x1.dims == 2 && x1.dims == x2.dims && (depth == CV_32F || depth == CV_64F));\n\n    _F.create(3, 3, depth);\n\n    Mat F = _F.getMat();\n\n    // type\n    if( depth == CV_32F )\n    {\n      normalizedEightPointSolver<float>(x1, x2, F);\n    }\n    else\n    {\n      normalizedEightPointSolver<double>(x1, x2, F);\n    }\n\n  }\n\n  template<typename T>\n  void\n  relativeCameraMotion( const Mat_<T> &R1,\n                        const Mat_<T> &t1,\n                        const Mat_<T> &R2,\n                        const Mat_<T> &t2,\n                        Mat_<T> R,\n                        Mat_<T> t )\n  {\n    R = R2 * R1.t();\n    t = t2 - R * t1;\n  }\n\n  void\n  relativeCameraMotion( InputArray _R1, InputArray _t1, InputArray _R2,\n                        InputArray _t2, OutputArray _R, OutputArray _t )\n  {\n    const Mat R1 = _R1.getMat(), t1 = _t1.getMat(), R2 = _R2.getMat(), t2 = _t2.getMat();\n    const int depth = R1.depth();\n    CV_Assert((R1.cols == 3 && R1.rows == 3) && (R1.size() == R2.size()));\n    CV_Assert((t1.cols == 1 && t1.rows == 3) && (t1.size() == t2.size()));\n    CV_Assert((depth == CV_32F || depth == CV_64F) && depth == R2.depth() && depth == t1.depth() && depth == t2.depth());\n\n    _R.create(3, 3, depth);\n    _t.create(3, 1, depth);\n\n    Mat R = _R.getMat(), t = _t.getMat();\n\n    // type\n    if( depth == CV_32F )\n    {\n      relativeCameraMotion<float>(R1, t1, R2, t2, R, t);\n    }\n    else\n    {\n      relativeCameraMotion<double>(R1, t1, R2, t2, R, t);\n    }\n\n  }\n\n  template<typename T>\n  void\n  motionFromEssential( const Mat_<T> &_E,\n                       std::vector<Mat> &_Rs,\n                       std::vector<Mat> &_ts )\n  {\n    libmv::Mat3 E;\n    std::vector < libmv::Mat3 > Rs;\n    std::vector < libmv::Vec3 > ts;\n\n    cv2eigen(_E, E);\n\n    libmv::MotionFromEssential(E, &Rs, &ts);\n\n    _Rs.clear();\n    _ts.clear();\n\n    int n = Rs.size();\n    CV_Assert(ts.size() == n);\n\n    for ( int i = 0; i < n; ++i )\n    {\n      Mat_<T> R_temp, t_temp;\n\n      eigen2cv(Rs[i], R_temp);\n      _Rs.push_back(R_temp);\n\n      eigen2cv(ts[i], t_temp);\n      _ts.push_back(t_temp);\n    }\n\n  }\n\n  void\n  motionFromEssential( InputArray _E, OutputArrayOfArrays _Rs,\n                       OutputArrayOfArrays _ts )\n  {\n    const Mat E = _E.getMat();\n    const int depth = E.depth(), cn = 4;\n    CV_Assert(E.cols == 3 && E.rows == 3 && (depth == CV_32F || depth == CV_64F));\n\n    _Rs.create(cn, 1, depth);\n    _ts.create(cn, 1, depth);\n    for (int i = 0; i < cn; ++i)\n    {\n      _Rs.create(Size(3,3), depth, i);\n      _ts.create(Size(3,1), depth, i);\n    }\n\n    std::vector<Mat> Rs, ts;\n    _Rs.getMatVector(Rs);\n    _ts.getMatVector(ts);\n\n    // type\n    if( depth == CV_32F )\n    {\n      motionFromEssential<float>(E, Rs, ts);\n    }\n    else\n    {\n      motionFromEssential<double>(E, Rs, ts);\n    }\n\n    for (int i = 0; i < cn; ++i)\n    {\n      Rs[i].copyTo(_Rs.getMatRef(i));\n      ts[i].copyTo(_ts.getMatRef(i));\n    }\n\n  }\n\n  template<typename T>\n  int motionFromEssentialChooseSolution( const std::vector<Mat> &Rs,\n                                         const std::vector<Mat> &ts,\n                                         const Mat_<T> &K1,\n                                         const Mat_<T> &x1,\n                                         const Mat_<T> &K2,\n                                         const Mat_<T> &x2 )\n  {\n    Mat_<T> P1, P2, R1 = Mat_<T>::eye(3,3);\n\n    T val = static_cast<T>(0.0);\n    Vec<T,3> t1(val, val, val);\n\n    projectionFromKRt(K1, R1, t1, P1);\n\n    std::vector<Mat_<T> > points2d;\n    points2d.push_back(x1);\n    points2d.push_back(x2);\n\n    for ( int i = 0; i < 4; ++i )\n    {\n      const Mat_<T> R2 = Rs[i];\n      const Vec<T,3> t2 = ts[i];\n      projectionFromKRt(K2, R2, t2, P2);\n\n      std::vector<Mat_<T> > Ps;\n      Ps.push_back(P1);\n      Ps.push_back(P2);\n\n      Vec<T,3> X;\n      triangulatePoints(points2d, Ps, X);\n\n      T d1 = depth(R1, t1, X);\n      T d2 = depth(R2, t2, X);\n\n      // Test if point is front to the two cameras.\n      if ( d1 > 0 && d2 > 0 )\n      {\n        return i;\n      }\n    }\n\n    return -1;\n  }\n\n  int motionFromEssentialChooseSolution( InputArrayOfArrays _Rs,\n                                         InputArrayOfArrays _ts,\n                                         InputArray _K1,\n                                         InputArray _x1,\n                                         InputArray _K2,\n                                         InputArray _x2 )\n  {\n    std::vector<Mat> Rs, ts;\n    _Rs.getMatVector(Rs);\n    _ts.getMatVector(ts);\n    const Mat K1 = _K1.getMat(), x1 = _x1.getMat(), K2 = _K2.getMat(), x2 = _x2.getMat();\n    const int depth = K1.depth();\n    CV_Assert( Rs.size() == 4 && ts.size() == 4 );\n    CV_Assert((K1.cols == 3 && K1.rows == 3) && (K1.size() == K2.size()));\n    CV_Assert((x1.cols == 1 && x1.rows == 2) && (x1.size() == x2.size()));\n    CV_Assert((depth == CV_32F || depth == CV_64F) && depth == K2.depth() && depth == x1.depth() && depth == x2.depth());\n\n    int solution = 0;\n\n    // type\n    if( depth == CV_32F )\n    {\n      solution = motionFromEssentialChooseSolution<float>(Rs, ts, K1, x1, K2, x2);\n    }\n    else\n    {\n      solution = motionFromEssentialChooseSolution<double>(Rs, ts, K1, x1, K2, x2);\n    }\n\n    return solution;\n  }\n\n  template<typename T>\n  void\n  fundamentalFromEssential( const Mat_<T> &E,\n                            const Mat_<T> &K1,\n                            const Mat_<T> &K2,\n                            Mat_<T> F )\n  {\n    F = K2.inv().t() * E * K1.inv();\n  }\n\n  void\n  fundamentalFromEssential( InputArray _E,\n                            InputArray _K1,\n                            InputArray _K2,\n                            OutputArray _F )\n  {\n    const Mat E = _E.getMat(), K1 = _K1.getMat(), K2 = _K2.getMat();\n    const int depth =  E.depth();\n    CV_Assert(E.cols == 3 && E.rows == 3 && E.size() == _K1.size() && E.size() == _K2.size() && (depth == CV_32F || depth == CV_64F));\n\n    _F.create(3, 3, depth);\n\n    Mat F = _F.getMat();\n\n    // type\n    if( depth == CV_32F )\n    {\n      fundamentalFromEssential<float>(E, K1, K2, F);\n    }\n    else\n    {\n      fundamentalFromEssential<double>(E, K1, K2, F);\n    }\n\n  }\n\n  template<typename T>\n  void\n  essentialFromFundamental( const Mat_<T> &F,\n                            const Mat_<T> &K1,\n                            const Mat_<T> &K2,\n                            Mat_<T> E )\n  {\n    E = K2.t() * F * K1;\n  }\n\n  void\n  essentialFromFundamental( InputArray _F,\n                            InputArray _K1,\n                            InputArray _K2,\n                            OutputArray _E )\n  {\n    const Mat F = _F.getMat(), K1 = _K1.getMat(), K2 = _K2.getMat();\n    const int depth =  F.depth();\n    CV_Assert(F.cols == 3 && F.rows == 3 && F.size() == _K1.size() && F.size() == _K2.size() && (depth == CV_32F || depth == CV_64F));\n\n    _E.create(3, 3, depth);\n\n    Mat E = _E.getMat();\n\n    // type\n    if( depth == CV_32F )\n    {\n      essentialFromFundamental<float>(F, K1, K2, E);\n    }\n    else\n    {\n      essentialFromFundamental<double>(F, K1, K2, E);\n    }\n  }\n\n  template<typename T>\n  void\n  essentialFromRt( const Mat_<T> &_R1,\n                   const Mat_<T> &_t1,\n                   const Mat_<T> &_R2,\n                   const Mat_<T> &_t2,\n                   Mat_<T> _E )\n  {\n    libmv::Mat3 E;\n    libmv::Mat3 R1, R2;\n    libmv::Vec3 t1, t2;\n\n    cv2eigen( _R1, R1 );\n    cv2eigen( _t1, t1 );\n    cv2eigen( _R2, R2 );\n    cv2eigen( _t2, t2 );\n\n    libmv::EssentialFromRt( R1, t1, R2, t2, &E );\n\n    eigen2cv( E, _E );\n  }\n\n  void\n  essentialFromRt( InputArray _R1,\n                   InputArray _t1,\n                   InputArray _R2,\n                   InputArray _t2,\n                   OutputArray _E )\n  {\n    const Mat R1 = _R1.getMat(), t1 = _t1.getMat(), R2 = _R2.getMat(), t2 = _t2.getMat();\n    const int depth = R1.depth();\n    CV_Assert((R1.cols == 3 && R1.rows == 3) && (R1.size() == R2.size()));\n    CV_Assert((t1.cols == 1 && t1.rows == 3) && (t1.size() == t2.size()));\n    CV_Assert((depth == CV_32F || depth == CV_64F) && depth == R2.depth() && depth == t1.depth() && depth == t2.depth());\n\n    _E.create(3, 3, depth);\n\n    Mat E = _E.getMat();\n\n    // type\n    if( depth == CV_32F )\n    {\n      essentialFromRt<float>(R1, t1, R2, t2, E);\n    }\n    else\n    {\n      essentialFromRt<double>(R1, t1, R2, t2, E);\n    }\n\n  }\n\n  template<typename T>\n  void\n  normalizeFundamental( const Mat_<T> &F, Mat_<T> F_normalized )\n  {\n    F_normalized = F * (1.0/norm(F,NORM_L2));  // Frobenius Norm\n\n    if ( F_normalized(2,2) < 0 )\n    {\n        F_normalized *= -1;\n    }\n  }\n\n  void\n  normalizeFundamental( InputArray _F,\n                        OutputArray _F_normalized )\n  {\n    const Mat F = _F.getMat();\n    const int depth =  F.depth();\n    CV_Assert(F.cols == 3 && F.rows == 3 && (depth == CV_32F || depth == CV_64F));\n\n    _F_normalized.create(3, 3, depth);\n\n    Mat F_normalized = _F_normalized.getMat();\n\n    // type\n    if( depth == CV_32F )\n    {\n      normalizeFundamental<float>(F, F_normalized);\n    }\n    else\n    {\n      normalizeFundamental<double>(F, F_normalized);\n    }\n  }\n\n  template<typename T>\n  void\n  computeOrientation( const Mat_<T> &x1,\n                      const Mat_<T> &x2,\n                      Mat_<T> R,\n                      Mat_<T> t,\n                      T s )\n  {\n    Mat_<T> rr, rl, rt, lt;\n    normalizePoints(x1, rr, rt);\n    normalizePoints(x2, rl, lt);\n\n    Mat_<T> rrBar, rlBar, rVar, lVar;\n    meanAndVarianceAlongRows(rr, rrBar, rVar);\n    meanAndVarianceAlongRows(rl, rlBar, lVar);\n\n    Mat_<T> rrp, rlp;\n    rrp = rr - repeat(rrBar, x1.rows, x1.cols);\n    rlp = rl - repeat(rlBar, x2.rows, x2.cols);\n\n    // TODO: finish implementation\n    // https://github.com/vrabaud/sfm_toolbox/blob/master/sfm/computeOrientation.m#L44\n  }\n\n  void\n  computeOrientation( InputArrayOfArrays _x1,\n                      InputArrayOfArrays _x2,\n                      OutputArray _R,\n                      OutputArray _t,\n                      double s )\n  {\n    const Mat x1 = _x1.getMat(), x2 = _x2.getMat();\n    const int depth =  x1.depth();\n    CV_Assert(x1.size() == x2.size() && (depth == CV_32F || depth == CV_64F));\n\n    _R.create(3, 3, depth);\n    _t.create(3, 1, depth);\n\n    Mat R = _R.getMat(), t = _t.getMat();\n\n    // type\n    if( depth == CV_32F )\n    {\n      computeOrientation<float>(x1, x2, R, t, s);\n    }\n    else\n    {\n      computeOrientation<double>(x1, x2, R, t, s);\n    }\n  }\n\n} /* namespace sfm */\n} /* namespace cv */\n", "meta": {"hexsha": "ca0523ee0884ff1d4e4dd3762ee0423502358476", "size": 15471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/sfm/src/fundamental.cpp", "max_stars_repo_name": "Nondzu/opencv_contrib", "max_stars_repo_head_hexsha": "0b0616a25d4239ee81fda965818b49b721620f56", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7158.0, "max_stars_repo_stars_event_min_datetime": "2016-07-04T22:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:54:32.000Z", "max_issues_repo_path": "modules/sfm/src/fundamental.cpp", "max_issues_repo_name": "Nondzu/opencv_contrib", "max_issues_repo_head_hexsha": "0b0616a25d4239ee81fda965818b49b721620f56", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2184.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T12:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T19:10:12.000Z", "max_forks_repo_path": "modules/sfm/src/fundamental.cpp", "max_forks_repo_name": "Nondzu/opencv_contrib", "max_forks_repo_head_hexsha": "0b0616a25d4239ee81fda965818b49b721620f56", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5535.0, "max_forks_repo_forks_event_min_datetime": "2016-07-06T12:01:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:13:24.000Z", "avg_line_length": 25.9580536913, "max_line_length": 134, "alphanum_fraction": 0.5250468619, "num_tokens": 4804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4450575811762619}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2011 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <complex>\n#include <iostream>\n#include <iomanip>\n#include <cstdlib>\n#include <utility> // std::move\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n\n#include \"dune/common/stdstreams.hh\"\n#include \"dune/grid/sgrid.hh\"\n#include \"dune/grid/uggrid.hh\"\n#include \"dune/grid/common/gridinfo.hh\"\n\n#include \"fem/assemble.hh\"\n#include \"fem/gridmanager.hh\"\n#include \"fem/lagrangespace.hh\"\n#include \"fem/functional_aux.hh\"\n#include \"fem/coarsening.hh\"\n#include \"fem/norms.hh\"\n\n#include \"linalg/umfpack_solve.hh\"\n\n#include \"timestepping/limexWithoutJens.hh\"\n#include \"timestepping/semieuler.hh\"\n#include \"timestepping/extrapolation.hh\"\n\n#include \"io/vtk.hh\"\n\n#include \"integrate.hh\"\n#include \"movingsource.hh\"\n\n//#include \"io/lossystorageDUNE.hh\"\n#include \"io/lossystorageWithoutTemporalPred.hh\"\n// #include \"io/lossystorage.hh\"\n\nusing namespace Kaskade;\n\ntemplate <class Grid>\nstd::unique_ptr<Grid> RefineGrid(int refinements, int heapSize=500)\n{\n  Grid::setDefaultHeapSize(heapSize);\n  Dune::GridFactory<Grid> factory;\n  Dune::FieldVector<double,2> v;\n  // vertices\n  v[0]=0; v[1]=0;\n  factory.insertVertex(v);\n  v[0]=1; v[1]=0;\n  factory.insertVertex(v);\n  v[0]=1; v[1]=1;\n  factory.insertVertex(v);\n  v[0]=0; v[1]=1;\n  factory.insertVertex(v);\n  // elements\n  std::vector<unsigned int> vid(3);\n  vid[0]=0; vid[1]=1; vid[2]=2;\n  factory.insertElement(Dune::GeometryType(Dune::GeometryType::simplex,2),vid);\n  vid[0]=0; vid[1]=2; vid[2]=3;\n  factory.insertElement(Dune::GeometryType(Dune::GeometryType::simplex,2),vid);\n  std::unique_ptr<Grid> grid( factory.createGrid() ) ;\n  grid->globalRefine(refinements);  \n  return grid;\n}\n\n\nstruct InitialValue \n{\n  typedef double Scalar;\n  static int const components = 1;\n  typedef Dune::FieldVector<Scalar,components> ValueType;\n\n  InitialValue(int c): component(c) {}\n  \n  template <class Cell> int order(Cell const&) const { return std::numeric_limits<int>::max(); }\n  template <class Cell>\n  ValueType value(Cell const& cell,\n                  Dune::FieldVector<typename Cell::ctype,Cell::dimension> const& localCoordinate) const \n  {\n    Dune::FieldVector<typename Cell::ctype,Cell::dimensionworld> x = cell.geometry().global(localCoordinate);\n\n\tdouble vx = x[0]-0.5;\n\tdouble vy = x[1]-0.75;\n\n    return 0.8*exp(-80.0*(vx*vx + vy*vy));\n  }\n\nprivate:\n  int component;\n};\n\n\nint main(int argc, char *argv[])\n  {\n    int const dim = 2;\n    int refinements = 7, order = 1, extrapolOrder = 1, maxSteps = 10, heapSize = 1000 ;\n    double dt = 0.1, maxDT = 1.0, T = 10.0, rTolT = 1.0e-2, aTolT = 1.0e-2, rTolX = 1.0e-4, aTolX = 1.0e-4, writeInterval = 1.0;\n\n    typedef Dune::UGGrid<dim> Grid;\n    std::unique_ptr<Grid> grid( RefineGrid<Grid>(refinements,heapSize) );\n    \n    std::cout << \"Grid: \" << grid->size(0) << \" \" << grid->size(1) << \" \" << grid->size(2) << std::endl << std::endl;\n\n    GridManager<Grid> gridManager(std::move(grid));\n  \n    // construct involved spaces and define equation\n    typedef Grid::LeafGridView LeafView;\n    typedef FEFunctionSpace<ContinuousLagrangeMapper<double,LeafView> > H1Space;\n\n    H1Space temperatureSpace(gridManager,gridManager.grid().leafView(),order);\n\n    typedef boost::fusion::vector<H1Space const*> Spaces;\n    Spaces spaces(&temperatureSpace);\n\n    typedef boost::fusion::vector<VariableDescription<0,1,0> > VariableDescriptions;\n    std::string varNames[1] = { \"u\" };\n  \n    typedef VariableSetDescription<Spaces,VariableDescriptions> VariableSet;\n    VariableSet variableSet(spaces,varNames);\n\n    typedef MovingSourceEquation<double,VariableSet> Equation;\n    Equation Eq;\n\n    std::vector<VariableSet::VariableSet> solutions;\n    \n    // prepare lossy storage\n    std::vector<double> times ;\n    \n    int coarseLevel = 0 ;\n    double qTol = 1e-5 ;   // quantization error tolerance\n    \n    typedef FEFunctionSpace<ContinuousLagrangeMapper<double,Grid::LevelGridView> > HierarchicH1Space;\n    typedef UniformQuantizationPolicy<VariableSet,Grid> QuantizationPolicy ;\n    typedef LossyStorage<Grid,VariableSet,HierarchicH1Space,QuantizationPolicy> Storage ;\n    \n    QuantizationPolicy quantizationPolicy ;\n    Storage lossyStorage( gridManager, variableSet, coarseLevel, qTol, true, quantizationPolicy ) ;  \n\n    // integrate equation\n    Eq.time(0);\n    VariableSet::VariableSet x(variableSet);\n    Eq.scaleInitialValue<0>(InitialValue(0),x);\n    \n    x = integrate(gridManager,Eq,variableSet,spaces,gridManager.grid(),\n\t\t  dt,maxDT,T,maxSteps,rTolT,aTolT,rTolX,aTolX,extrapolOrder,\n\t\t  std::back_inserter(solutions),writeInterval,x,DirectType::UMFPACK,times,lossyStorage);\n\n    // decode files & check error \n    // decode backwards in time (necessary if temporal prediction/differential\n    // encoding is used)\n    std::cout << \"\\n\\nckecking error:\\n\" ;\n    \n    VariableSet::VariableSet state_data(variableSet) ;\n    L2Norm l2 ; \n    \n    std::ostringstream fn ; \n    fn.width(3);  fn.fill('0');\n    fn.setf(std::ios_base::right,std::ios_base::adjustfield);  \n    for( int t = times.size()-1 ; t >= 0 ; t-- )\n    {\n      fn << \"graph/quant\" ;\n      fn << t ;\n      fn.flush();\n      lossyStorage.decode( gridManager, state_data, fn.str() ) ;\n      \n      // write reconstructed states as vtu-files\n//       writeVTKFile(gridManager.grid().leafView(), variableSet, state_data, fn.str());\n      \n      fn.clear() ; fn.str(\"\");     \n      \n      // compute and print L^\\infty error \n      state_data -= solutions[t] ;\n      std::vector<double> foo( gridManager.grid().size(dim) ) ;\n      state_data.write( foo.begin() ) ;\n      double absQuantErr = fabs(*std::max_element(foo.begin(),foo.end(),abscompare)) ;\n      std::cout << \"t = \" << times[t] << \"\\tL^\\\\infty = \" << absQuantErr ;  \n      absQuantErr = sqrt(l2.square( boost::fusion::at_c<0>(state_data.data) ));\n      std::cout << \"\\tL^2 = \" << absQuantErr << \"\\n\" ;\n    }\n    \n    return 0;\n    \n    \n//     std::cout << times.size() << \" timesteps.\\n\" ;\n//     for( int i = 0 ; i < times.size() ; i++ ) std::cout << times[i] << \"   \" ;\n//     std::cout << \"\\n\\n\" ;\n//     std::cout << \"Solution vector contains \" << solutions.size() << \" entries.\\n\" ;\n//     \n//     int windowSize = 2 ; \n//     \n//     for( int i = 0 ; i < times.size()-windowSize ; i++ )\n//     {\n//     \n//       VariableSet::VariableSet a = solutions[i+1] , b = solutions[i+0] ;\n//       a -= solutions[i+0] ; a *= 1.0/(times[i+1]-times[i+0]) ;\n// \n//       VariableSet::VariableSet pred = b ;\n//       pred.axpy(times[i+2]-times[i+0],a);\n//     \n//       typedef Grid::LeafGridView LeafGridView;\n//       LeafGridView leafView = gridManager.grid().leafView();\n//       std::ostringstream fn ; \n//       fn.width(3);  fn.fill('0');\n//       fn.setf(std::ios_base::right,std::ios_base::adjustfield);\n//       fn << \"graph/pred\" ;\n//       fn << i+2 ;\n//       fn.flush();\n//       writeVTKFile(leafView,variableSet,pred,fn.str() );\n//       \n//       lossyStorage.encode( pred, fn.str() ) ;\n//     \n//       fn.str(\"\") ; \n//       fn << \"graph/diff\" ;\n//       fn << i+2 ;\n//       fn.flush();\n//       pred -= solutions[i+2] ; \n//       writeVTKFile(leafView,variableSet,pred,fn.str());\n//       \n//       lossyStorage.encode( pred, fn.str() ) ;\n//     }\n  }\n", "meta": {"hexsha": "d9750e2c2465af250d3714a11aac47c10cac7df4", "size": 8080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tests/compression/movingsource.cpp", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/tests/compression/movingsource.cpp", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:33.000Z", "max_forks_repo_path": "Kaskade/tests/compression/movingsource.cpp", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 34.5299145299, "max_line_length": 128, "alphanum_fraction": 0.5945544554, "num_tokens": 2285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.4450575748269226}}
{"text": "/*    Copyright (c) 2010-2016, Delft University of Technology\n *    All rights reserved.\n *\n *    Redistribution and use in source and binary forms, with or without modification, are\n *    permitted provided that the following conditions are met:\n *      - Redistributions of source code must retain the above copyright notice, this list of\n *        conditions and the following disclaimer.\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\n *        conditions and the following disclaimer in the documentation and/or other materials\n *        provided with the distribution.\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\n *        may be used to endorse or promote products derived from this software without specific\n *        prior written permission.\n *\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *    Changelog\n *      YYMMDD    Author            Comment\n *      160406    M. Van den Broeck Creation\n *      <YYMMDD>  <author name>     <comment>\n *\n *    References\n *      Vittaldev, V. (2010). The Unified State Model: Derivation and application in astrodynamics\n *          and navigation. Master's thesis, Delft University of Technology.\n *      <Second reference>\n *\n *    Notes\n *\n */\n\n#include <cmath>\n\n#include <boost/exception/all.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h\"\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/missionGeometry.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/unifiedStateModelElementConversions.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\n\nnamespace tudat\n{\n\nnamespace orbital_element_conversions\n{\n\n//! Convert Keplerian elements to Unified State Model elements.\nEigen::Matrix< double, 7, 1 > convertKeplerianToUnifiedStateModelElements(\n        const basic_mathematics::Vector6d& keplerianElements,\n        const double centralBodyGravitationalParameter )\n{\n    using mathematical_constants::PI;\n\n    // Declaring eventual output vector.\n    Eigen::Matrix< double, 7, 1 > convertedUnifiedStateModelElements = Eigen::Matrix< double, 7, 1 >::Zero( );\n\n    // Define the tolerance of a singularity\n    double singularityTolerance = 1.0e-15; // Based on tolerance chosen in\n                                           // orbitalElementConversions.cpp in Tudat Core.\n\n    // If eccentricity is outside range [0,inf)\n    if ( keplerianElements( eccentricityIndex ) < 0.0 )\n    {\n        //Define the error message\n        std::stringstream errorMessage;\n        errorMessage << \"Eccentricity is expected in range [0,inf)\\n\"\n                     << \"Specified eccentricity: \" << keplerianElements( eccentricityIndex ) << std::endl;\n\n        // Throw exception\n        boost::throw_exception( std::runtime_error( errorMessage.str( ) ) );\n    }\n\n    // If inclination is outside range [0,PI]\n    if ( ( keplerianElements( inclinationIndex ) < 0.0 ) || ( keplerianElements( inclinationIndex ) > PI ) )\n    {\n        // Define the error message.\n        std::stringstream errorMessage;\n        errorMessage << \"Inclination is expected in range [0,\" << PI << \"]\\n\"\n                     << \"Specified inclination: \" << keplerianElements( inclinationIndex ) << \" rad.\" << std::endl;\n\n        // Throw exception.\n        boost::throw_exception( std::runtime_error( errorMessage.str( ) ) );\n    }\n\n    // If argument of pericenter is outside range [0,2.0 * PI]\n    if ( ( keplerianElements( argumentOfPeriapsisIndex ) < 0.0 ) || ( keplerianElements( argumentOfPeriapsisIndex ) >\n                                                                      2.0 * PI ) )\n    {\n        // Define the error message.\n        std::stringstream errorMessage;\n        errorMessage << \"RAAN is expected in range [0,\" << 2.0 * PI << \"]\\n\"\n                     << \"Specified inclination: \" << keplerianElements( argumentOfPeriapsisIndex ) << \" rad.\" << std::endl;\n\n        // Throw exception.\n        boost::throw_exception( std::runtime_error( errorMessage.str( ) ) );\n    }\n\n    // If right ascension of ascending node is outside range [0,2.0 * PI]\n    if ( ( keplerianElements( longitudeOfAscendingNodeIndex ) < 0.0 ) ||\n         ( keplerianElements( longitudeOfAscendingNodeIndex ) > 2.0 * PI ) )\n    {\n        // Define the error message.\n        std::stringstream errorMessage;\n        errorMessage << \"RAAN is expected in range [0,\" << 2.0 * PI << \"]\\n\"\n                     << \"Specified inclination: \" << keplerianElements( longitudeOfAscendingNodeIndex ) << \" rad.\"\n                     << std::endl;\n\n        // Throw exception.\n        boost::throw_exception( std::runtime_error( errorMessage.str( ) ) );\n    }\n\n    // If true anomaly is outside range [0,2.0 * PI]\n    if ( ( keplerianElements( trueAnomalyIndex ) < 0.0 ) || ( keplerianElements( trueAnomalyIndex ) > 2.0 * PI ) )\n    {\n        // Define the error message.\n        std::stringstream errorMessage;\n        errorMessage << \"RAAN is expected in range [0,\" << 2.0 * PI << \"]\\n\"\n                     << \"Specified inclination: \" << keplerianElements( trueAnomalyIndex ) << \" rad.\" << std::endl;\n\n        // Throw exception.\n        boost::throw_exception( std::runtime_error( errorMessage.str( ) ) );\n    }\n\n    // If inclination is zero and the right ascension of ascending node is non-zero\n    if ( ( std::fabs( keplerianElements( inclinationIndex ) ) < singularityTolerance ) &&\n         ( std::fabs( keplerianElements( longitudeOfAscendingNodeIndex ) ) > singularityTolerance ) )\n    {\n        // Define the error message.\n        std::stringstream errorMessage;\n        errorMessage << \"When the inclination is zero, the right ascending node should be zero by definition\\n\"\n                     << \"Specified right ascension of ascending node: \" <<\n                        keplerianElements( longitudeOfAscendingNodeIndex ) << \" rad.\" << std::endl;\n\n        // Throw exception.\n        boost::throw_exception( std::runtime_error( errorMessage.str( ) ) );\n    }\n\n    // If eccentricity is zero and the argument of pericenter is non-zero\n    if ( ( std::fabs( keplerianElements( eccentricityIndex ) ) < singularityTolerance ) &&\n         ( std::fabs( keplerianElements( argumentOfPeriapsisIndex ) ) > singularityTolerance ) )\n    {\n        // Define the error message.\n        std::stringstream errorMessage;\n        errorMessage << \"When the eccentricity is zero, the argument of pericenter should be zero by definition\\n\"\n                     << \"Specified argument of pericenter: \" <<\n                        keplerianElements( argumentOfPeriapsisIndex ) << \" rad.\" << std::endl;\n\n        // Throw exception.\n        boost::throw_exception( std::runtime_error( errorMessage.str( ) ) );\n    }\n\n    // If semi-major axis is negative and the eccentricity is smaller or equal to one\n    if ( ( keplerianElements( semiMajorAxisIndex ) < 0.0 ) && ( keplerianElements( eccentricityIndex ) <= 1.0 ) )\n    {\n        // Define the error message.\n        std::stringstream errorMessage;\n        errorMessage << \"When the semi-major axis is negative, the eccentricity should be larger than one\\n\"\n                     << \"Specified semi-major axis: \" << keplerianElements( semiMajorAxisIndex ) << \" m.\\n\"\n                     << \"Specified eccentricity: \" << keplerianElements( eccentricityIndex ) << \" rad.\" << std::endl;\n\n        // Throw exception.\n        boost::throw_exception( std::runtime_error( errorMessage.str( ) ) );\n    }\n\n    // If semi-major axis is positive and the eccentricity is larger than one\n    if ( ( keplerianElements( semiMajorAxisIndex ) > 0.0 ) && ( keplerianElements( eccentricityIndex ) > 1.0 ) )\n    {\n        // Define the error message.\n        std::stringstream errorMessage;\n        errorMessage << \"When the semi-major axis is positive, the eccentricity should be smaller than or equal to one\\n\"\n                     << \"Specified semi-major axis: \" << keplerianElements( semiMajorAxisIndex ) << \" m.\\n\"\n                     << \"Specified eccentricity: \" << keplerianElements( eccentricityIndex ) << \" rad.\" << std::endl;\n\n        // Throw exception.\n        boost::throw_exception( std::runtime_error( errorMessage.str( ) ) );\n    }\n    //Else, nothing wrong and continue\n\n    // Compute the C hodograph element of the Unified State Model\n    if ( std::fabs( keplerianElements( eccentricityIndex ) - 1.0) < singularityTolerance )\n            // parabolic orbit -> semi-major axis is not defined\n    {\n        convertedUnifiedStateModelElements( CHodographIndex ) =\n                std::sqrt( centralBodyGravitationalParameter / keplerianElements( semiLatusRectumIndex ) );\n    }\n    else\n    {\n        convertedUnifiedStateModelElements( CHodographIndex ) =\n                std::sqrt( centralBodyGravitationalParameter / ( keplerianElements( semiMajorAxisIndex )\n                                                  * ( 1 - keplerianElements( eccentricityIndex ) *\n                                                      keplerianElements( eccentricityIndex ) ) ) );\n    }\n\n    // Calculate the additional R hodograph parameter\n    double RHodographElement = keplerianElements( eccentricityIndex ) *\n            convertedUnifiedStateModelElements( CHodographIndex );\n\n    // Compute the Rf1 hodograph element of the Unified State Model\n    convertedUnifiedStateModelElements( Rf1HodographIndex ) =\n            - RHodographElement * std::sin( keplerianElements( longitudeOfAscendingNodeIndex )\n                                            + keplerianElements( argumentOfPeriapsisIndex ) );\n\n    // Compute the Rf2 hodograph element of the Unified State Model\n    convertedUnifiedStateModelElements( Rf2HodographIndex ) =\n              RHodographElement * std::cos( keplerianElements( longitudeOfAscendingNodeIndex )\n                                            + keplerianElements( argumentOfPeriapsisIndex ) );\n\n    // Calculate the additional argument of longitude u\n    double argumentOfLongitude = keplerianElements( argumentOfPeriapsisIndex ) +\n            keplerianElements( trueAnomalyIndex );\n\n    // Compute the epsilon1 quaternion of the Unified State Model\n    convertedUnifiedStateModelElements( epsilon1QuaternionIndex ) =\n            std::sin( 0.5 * keplerianElements( inclinationIndex ) ) *\n            std::cos( 0.5 * ( keplerianElements( longitudeOfAscendingNodeIndex ) - argumentOfLongitude ) );\n\n    // Compute the epsilon2 quaternion of the Unified State Model\n    convertedUnifiedStateModelElements( epsilon2QuaternionIndex ) =\n            std::sin( 0.5 * keplerianElements( inclinationIndex ) ) *\n            std::sin( 0.5 * ( keplerianElements( longitudeOfAscendingNodeIndex ) - argumentOfLongitude ) );\n\n    // Compute the epsilon3 quaternion of the Unified State Model\n    convertedUnifiedStateModelElements( epsilon3QuaternionIndex ) =\n            std::cos( 0.5 * keplerianElements( inclinationIndex ) ) *\n            std::sin( 0.5 * ( keplerianElements( longitudeOfAscendingNodeIndex ) + argumentOfLongitude ) );\n\n    // Compute the eta quaternion of the Unified State Model\n    convertedUnifiedStateModelElements( etaQuaternionIndex ) =\n            std::cos( 0.5 * keplerianElements( inclinationIndex ) ) *\n            std::cos( 0.5 * ( keplerianElements( longitudeOfAscendingNodeIndex ) + argumentOfLongitude ) );\n\n    // Give back result\n    return convertedUnifiedStateModelElements;\n\n}\n\n//! Convert Unified State Model elements to Keplerian elements.\nbasic_mathematics::Vector6d convertUnifiedStateModelToKeplerianElements(\n        const Eigen::Matrix< double, 7, 1 >& unifiedStateModelElements,\n        const double centralBodyGravitationalParameter )\n{\n    using mathematical_constants::PI;\n\n    // Declaring eventual output vector.\n    basic_mathematics::Vector6d convertedKeplerianElements = basic_mathematics::\n            Vector6d::Zero( 6 );\n\n    // Define the tolerance of a singularity\n    double singularityTolerance = 1.0e-15; // Based on tolerance chosen in\n                                           // orbitalElementConversions.cpp in Tudat Core.\n\n    // Declare auxiliary parameters before using them in the if loop\n    double cosineLambda = 0.0;\n    double sineLambda = 0.0;\n    double lambdaFromSineAndCosine = 0.0;\n\n    // Check whether the Unified State Model elements are within expected limits\n    // If inclination is zero and the right ascension of ascending node is non-zero\n    const double normOfQuaternionElements = std::sqrt( std::pow( unifiedStateModelElements( epsilon1QuaternionIndex ), 2 ) +\n                                                       std::pow( unifiedStateModelElements( epsilon2QuaternionIndex ), 2 ) +\n                                                       std::pow( unifiedStateModelElements( epsilon3QuaternionIndex ), 2 ) +\n                                                       std::pow( unifiedStateModelElements( etaQuaternionIndex ), 2 ) );\n\n    if ( std::fabs( normOfQuaternionElements - 1.0 ) > singularityTolerance )\n    {\n        // Define the error message.\n        std::stringstream errorMessage;\n        errorMessage << \"The norm of the quaternion should be equal to one.\\n\"\n                     << \"Norm of the specified quaternion is: \" << normOfQuaternionElements << \" .\" << std::endl;\n\n        // Throw exception.\n        boost::throw_exception( std::runtime_error( errorMessage.str( ) ) );\n    }\n    //Else, nothing wrong and continue\n\n    // Compute auxiliary parameters cosineLambda, sineLambda and Lambda\n    if ( ( std::fabs( unifiedStateModelElements( epsilon3QuaternionIndex ) ) < singularityTolerance )\n        && ( std::fabs( unifiedStateModelElements( etaQuaternionIndex ) ) < singularityTolerance ) )\n            // pure-retrograde orbit -> inclination  = pi\n    {\n        //Define the error message\n        std::stringstream errorMessage;\n        errorMessage << \"Pure-retrograde orbit (inclination = pi).\\n\"\n                     << \"Unified State Model elements cannot be transformed to Kepler elements.\" << std::endl;\n\n        // Throw exception\n        boost::throw_exception( std::runtime_error( errorMessage.str( ) ) );\n    }\n    else\n    {\n        cosineLambda = ( unifiedStateModelElements( etaQuaternionIndex ) *\n                                unifiedStateModelElements( etaQuaternionIndex ) -\n                                unifiedStateModelElements( epsilon3QuaternionIndex ) *\n                                unifiedStateModelElements( epsilon3QuaternionIndex ) )\n                / ( unifiedStateModelElements( epsilon3QuaternionIndex ) *\n                    unifiedStateModelElements( epsilon3QuaternionIndex ) +\n                    unifiedStateModelElements( etaQuaternionIndex ) *\n                    unifiedStateModelElements( etaQuaternionIndex ) );\n        sineLambda = ( 2.0 *\n                              unifiedStateModelElements( epsilon3QuaternionIndex ) *\n                              unifiedStateModelElements( etaQuaternionIndex ) )\n                / ( unifiedStateModelElements( epsilon3QuaternionIndex ) *\n                    unifiedStateModelElements( epsilon3QuaternionIndex ) +\n                    unifiedStateModelElements( etaQuaternionIndex ) *\n                    unifiedStateModelElements( etaQuaternionIndex ) );\n        lambdaFromSineAndCosine = std::atan2( sineLambda, cosineLambda );\n    }\n\n    // Compute auxiliary parameters auxiliaryParameter1 and auxiliaryParameter2\n    double auxiliaryParameter1 = unifiedStateModelElements( Rf1HodographIndex ) * cosineLambda +\n            unifiedStateModelElements( Rf2HodographIndex ) * sineLambda;\n    double auxiliaryParameter2 = unifiedStateModelElements( CHodographIndex ) -\n            unifiedStateModelElements( Rf1HodographIndex ) * sineLambda +\n            unifiedStateModelElements( Rf2HodographIndex ) * cosineLambda;\n\n    // Compute auxiliary R hodograph parameter\n    double RHodographElement = std::sqrt( unifiedStateModelElements( Rf1HodographIndex )\n                                          * unifiedStateModelElements( Rf1HodographIndex )\n                                          + unifiedStateModelElements( Rf2HodographIndex )\n                                          * unifiedStateModelElements( Rf2HodographIndex ));\n\n    // Compute eccentricity\n    convertedKeplerianElements( eccentricityIndex ) =\n            RHodographElement / unifiedStateModelElements( CHodographIndex );\n\n    // Compute semi-major axis or, in case of a parabolic orbit, the semi-latus rectum.\n    if ( std::fabs( convertedKeplerianElements( eccentricityIndex ) - 1.0 ) < singularityTolerance )\n            // parabolic orbit -> semi-major axis is not defined. Use semi-latus rectum instead.\n    {\n        convertedKeplerianElements( semiLatusRectumIndex ) = centralBodyGravitationalParameter /\n                ( unifiedStateModelElements( CHodographIndex ) * unifiedStateModelElements( CHodographIndex ) );\n    }\n    else\n    {\n        convertedKeplerianElements( semiMajorAxisIndex ) =\n                centralBodyGravitationalParameter /\n                ( 2.0 * unifiedStateModelElements( CHodographIndex ) * auxiliaryParameter2 -\n                    ( auxiliaryParameter1 * auxiliaryParameter1 + auxiliaryParameter2 * auxiliaryParameter2 ) );\n    }\n\n    // Compute inclination\n    convertedKeplerianElements( inclinationIndex ) =\n            std::acos( 1.0 - 2.0 * ( unifiedStateModelElements( epsilon1QuaternionIndex ) *\n                                     unifiedStateModelElements( epsilon1QuaternionIndex ) +\n                                     unifiedStateModelElements( epsilon2QuaternionIndex ) *\n                                     unifiedStateModelElements( epsilon2QuaternionIndex ) ) );\n        // This acos is always defined correctly because the inclination is always below pi rad.\n\n    // Compute longitude of ascending node\n    if ( ( ( std::fabs( unifiedStateModelElements( epsilon1QuaternionIndex ) ) < singularityTolerance )\n           && ( std::fabs( unifiedStateModelElements( epsilon2QuaternionIndex ) ) < singularityTolerance ) ) ||\n         ( ( std::fabs( unifiedStateModelElements( epsilon3QuaternionIndex ) ) < singularityTolerance )\n         && ( std::fabs( unifiedStateModelElements( etaQuaternionIndex ) ) < singularityTolerance ) ) )\n            // pure-prograde or pure-retrograde orbit\n    {\n        convertedKeplerianElements( longitudeOfAscendingNodeIndex ) = 0.0; // by definition\n    }\n    else\n    {\n        convertedKeplerianElements( longitudeOfAscendingNodeIndex ) =\n                std::atan2( ( ( unifiedStateModelElements( epsilon1QuaternionIndex ) *\n                                unifiedStateModelElements( epsilon3QuaternionIndex ) +\n                                unifiedStateModelElements( epsilon2QuaternionIndex ) *\n                                unifiedStateModelElements( etaQuaternionIndex ) )\n                           / ( std::sqrt( ( unifiedStateModelElements( epsilon1QuaternionIndex ) *\n                                               unifiedStateModelElements( epsilon1QuaternionIndex ) +\n                                               unifiedStateModelElements( epsilon2QuaternionIndex ) *\n                                               unifiedStateModelElements( epsilon2QuaternionIndex ) ) *\n                                          ( unifiedStateModelElements( etaQuaternionIndex ) *\n                                               unifiedStateModelElements( etaQuaternionIndex ) +\n                                               unifiedStateModelElements( epsilon3QuaternionIndex ) *\n                                               unifiedStateModelElements( epsilon3QuaternionIndex ) ) ) ) ),\n                            ( ( unifiedStateModelElements( epsilon1QuaternionIndex ) *\n                             unifiedStateModelElements( etaQuaternionIndex ) -\n                             unifiedStateModelElements( epsilon2QuaternionIndex ) *\n                             unifiedStateModelElements( epsilon3QuaternionIndex ) )\n                        / ( std::sqrt( ( unifiedStateModelElements( epsilon1QuaternionIndex ) *\n                                            unifiedStateModelElements( epsilon1QuaternionIndex ) +\n                                            unifiedStateModelElements( epsilon2QuaternionIndex ) *\n                                            unifiedStateModelElements( epsilon2QuaternionIndex ) ) *\n                                       ( unifiedStateModelElements( etaQuaternionIndex ) *\n                                            unifiedStateModelElements( etaQuaternionIndex ) +\n                                            unifiedStateModelElements( epsilon3QuaternionIndex ) *\n                                            unifiedStateModelElements( epsilon3QuaternionIndex ) ) ) ) ) );\n\n        // Round off small values of the right ascension of ascending node to zero\n        if ( std::fabs( convertedKeplerianElements( longitudeOfAscendingNodeIndex ) ) < singularityTolerance )\n        {\n            convertedKeplerianElements( longitudeOfAscendingNodeIndex ) = 0.0;\n        }\n        // Ensure the longitude of ascending node is positive\n        while ( convertedKeplerianElements( longitudeOfAscendingNodeIndex ) < 0.0 )\n                // Because of the previous if loop, if the longitude of ascending node is smaller than 0, it will\n                // always be smaller than -singularityTolerance\n        {\n            convertedKeplerianElements( longitudeOfAscendingNodeIndex ) =\n                    convertedKeplerianElements( longitudeOfAscendingNodeIndex ) + 2.0 * PI;\n        }\n    }\n\n    // Compute true anomaly and argument of periapsis\n    if ( std::fabs( RHodographElement ) < singularityTolerance ) // circular orbit\n    {\n        convertedKeplerianElements( argumentOfPeriapsisIndex ) = 0.0; // by definition\n        convertedKeplerianElements( trueAnomalyIndex ) =\n                lambdaFromSineAndCosine - convertedKeplerianElements( longitudeOfAscendingNodeIndex );\n\n        // Round off small theta to zero\n        if ( std::fabs( convertedKeplerianElements( trueAnomalyIndex ) ) < singularityTolerance )\n        {\n            convertedKeplerianElements( trueAnomalyIndex ) = 0.0;\n        }\n\n        // Ensure the true anomaly is positive\n        while ( convertedKeplerianElements( trueAnomalyIndex ) < 0.0 )\n                // Because of the previous if loop, if the true anomaly is smaller than zero, it will always be smaller than\n                // -singularityTolerance\n        {\n            convertedKeplerianElements( trueAnomalyIndex ) =\n                    convertedKeplerianElements( trueAnomalyIndex ) + 2.0 * PI;\n        }\n    }\n    else\n    {\n        convertedKeplerianElements( trueAnomalyIndex ) =\n                std::atan2( ( auxiliaryParameter1 / RHodographElement ),\n                            ( ( auxiliaryParameter2 - unifiedStateModelElements( CHodographIndex ) )\n                           / RHodographElement ) );\n\n        // Round off small theta to zero\n        if ( std::fabs( convertedKeplerianElements( trueAnomalyIndex ) ) < singularityTolerance )\n        {\n            convertedKeplerianElements( trueAnomalyIndex ) = 0.0;\n        }\n\n        // Ensure the true anomaly is positive\n        while ( convertedKeplerianElements( trueAnomalyIndex ) < 0.0 )\n            // Because of the previous if loop, if the true anomaly is smaller than zero, it will always\n            // be smaller than -singularityTolerance\n        {\n            convertedKeplerianElements( trueAnomalyIndex ) =\n                    convertedKeplerianElements( trueAnomalyIndex ) + 2.0 * PI;\n        }\n\n        convertedKeplerianElements( argumentOfPeriapsisIndex ) =\n                lambdaFromSineAndCosine -\n                convertedKeplerianElements( longitudeOfAscendingNodeIndex ) -\n                convertedKeplerianElements( trueAnomalyIndex );\n\n        // Round off small omega to zero\n        if ( std::fabs( convertedKeplerianElements( argumentOfPeriapsisIndex ) ) < singularityTolerance )\n        {\n            convertedKeplerianElements( argumentOfPeriapsisIndex ) = 0.0;\n        }\n\n        // Ensure the argument of periapsis is positive\n        while ( convertedKeplerianElements( argumentOfPeriapsisIndex ) < 0.0 )\n            // Because of the previous if loop, if the argument of pericenter is smaller than zero,\n            // it will be smaller than -singularityTolerance\n        {\n            convertedKeplerianElements( argumentOfPeriapsisIndex ) =\n                    convertedKeplerianElements( argumentOfPeriapsisIndex ) + 2.0 * PI;\n        }\n    }\n\n    // Give back result\n    return convertedKeplerianElements;\n}\n\n} // close namespace orbital_element_conversions\n\n} // close namespace tudat\n", "meta": {"hexsha": "755ce42a354264b8a1256ef04f5f04008680ffe3", "size": 25627, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/unifiedStateModelElementConversions.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/unifiedStateModelElementConversions.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/unifiedStateModelElementConversions.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 53.0579710145, "max_line_length": 124, "alphanum_fraction": 0.6388184337, "num_tokens": 5503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.44505757482692254}}
{"text": "/**\n\n\\file\n\\author Datta Ramadasan\n//==============================================================================\n//         Copyright 2015 INSTITUT PASCAL UMR 6602 CNRS/Univ. Clermont II\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n\n*/\n\n#ifndef __OPTIMISATION2_ALGO_LM_MANY_CLASSES_LEVMAR_HPP__\n#define __OPTIMISATION2_ALGO_LM_MANY_CLASSES_LEVMAR_HPP__\n\n#include <boost/fusion/include/for_each.hpp>\n#include <boost/mpl/copy_if.hpp>\n#include <libv/lma/lm/ba/bas.hpp>\n#include <libv/lma/lm/ba/initialize.hpp>\n#include <libv/lma/lm/ba/fill_hessien.hpp>\n#include <libv/lma/lm/bundle/cost_and_save.hpp>\n#include <libv/lma/lm/container/map_container.hpp>\n#include <libv/lma/lm/container/container.hpp>\n#include <libv/lma/lm/function/function.hpp>\n#include <libv/lma/lm/trait/use_estimator.hpp>\n#include <libv/lma/time/tictoc.hpp>\n\nnamespace lma\n{\n  template<class F> struct MakeResidualVector : bf::pair<F,AlignVector<std::pair<typename Function<F>::ErreurType,bool>>> {};\n\n  template<> struct MakeResidualVector<mpl::_1>{};\n\n  template<class A, class A_, class B, class B_, class C, class C_>\n  void prod_v_v_h(VectorColumn<A,A_>& a, const VectorColumn<B,B_>& b, const DiagonalTable<C,C_>& c)\n  {\n    for(auto i = c.first() ; i < c.size() ; ++i)\n      a(i) += b(i) * c(i);\n  }\n  \n  template<class A, class A_, class B, class B_, class _>\n  void prod_v_v_h(VectorColumn<B,B_>& r, const VectorColumn<A,A_>& delta, const Table<A,B,_>& h)\n  {\n    for(auto i = h.first() ; i < h.size() ; ++i)\n      for(auto j = h.first(i) ; j < h.size(i) ; ++j)\n        r(h.indice(i,j)) += delta(i) * h(i,j);\n  }\n  \n  template<class A, class A_, class B, class B_, class _>\n  void prod_v_v_h_t(VectorColumn<A,A_>& r, const VectorColumn<B,B_>& delta, const Table<A,B,_>& h)\n  {\n    for(auto i = h.first() ; i < h.size() ; ++i)\n      for(auto j = h.first(i) ; j < h.size(i) ; ++j)\n        r(i) += delta(h.indice(i,j)) * transpose(h(i,j));\n  }\n  \n  template<class A, class B, class C, class C_>\n  void prod_v_v_h_dispatch(A& r, const B& delta, const DiagonalTable<C,C_>& c)\n  {\n    prod_v_v_h(bf::at_key<C>(r),bf::at_key<C>(delta),c);\n  }\n  \n  template<class A, class B, class C1, class C2, class _>\n  void prod_v_v_h_dispatch(A& r, const B& delta, const Table<C1,C2,_>& c)\n  {\n    prod_v_v_h(bf::at_key<C2>(r),bf::at_key<C1>(delta),c);\n    prod_v_v_h_t(bf::at_key<C1>(r),bf::at_key<C2>(delta),c);\n  }\n\n  struct GetMax\n  {\n    double& lambda;\n    GetMax(double& d):lambda(d){}\n    template<class Table> void operator()(const Table& table){ lambda = std::max(lambda,table.max_lambda());}\n  };\n\n  struct ComputeScale\n  {\n    double &scale;\n    double &lambda;\n    ComputeScale(double& scale_, double& lambda_):scale(scale_),lambda(lambda_){}\n    template<class Delta, class Jte> void operator() (const Delta& delta, const Jte& jte)\n    {\n      for(auto i = delta.first() ; i < delta.size() ; ++i)\n        for(size_t k = 0 ; k < delta.I; ++k)\n          scale += (delta(i)[k] * (lambda * delta(i)[k] + jte(i)[k]));\n    };\n  };\n    \n  template<class Policy> struct LevMar : Policy\n  {\n    typedef LevMar<Policy> type;\n    \n    typedef utils::Tic<false> Tic;\n    typedef typename Policy::Bundle Bundle;\n    typedef typename Policy::Ba Ba;\n    typedef typename Ba::Keys Keys;\n\n    Ba ba_;\n    const Ba& ba() const { return ba_; }\n\n    double residual_evaluations;\n    double jacobian_evaluations;\n    double norm_eq_;\n    double preprocess;\n\n    double prev_lambda;\n    double erreur_,previous_erreur_;\n    double nb_used_fonctor;\n\n    typedef MultiContainer<typename Bundle::ListFunction,MakeResidualVector<mpl::_1>> ContainerMapErreur;\n\n    utils::Tic<true> free_tic;\n\n    ContainerMapErreur map_erreur;\n    \n    static std::string name(){ return ttt::name<LevMar<Policy>>(); }\n    \n    template<class Config>\n    LevMar(Config config):Policy(config),prev_lambda(-1.0),erreur_(-1.0),previous_erreur_(-1.0)\n    {\n      residual_evaluations = 0;\n      preprocess = norm_eq_ = jacobian_evaluations = 0;\n    }\n\n    typedef typename\n    mpl::copy_if<\n                  typename Bundle::ListFunction,\n                  detail::IsMEstimator<mpl::_1>\n                >::type MEstimatorList;\n                \n    typedef typename \n      br::as_map<\n                  typename mpl::transform<\n                                          MEstimatorList,\n                                          bf::pair<mpl::_1,double>\n                                         >::type\n                >::type Meds;\n    Meds meds;//bf::tuple< pair<F1,double>, pair<F2,double> ...>\n\n    void init(Bundle& bundle_)\n    {\n      free_tic.tic();\n      bundle_.update();\n      initialize(bundle_,ba_);\n      Policy::init(bundle_,ba_);\n      cost_and_save_mad<Meds>(bundle_,meds);\n      preprocess = free_tic.toc();\n    }\n\n    void restore_erreur()\n    {\n      assert(erreur_!=-1.0);//! l'erreur a déjà été calculé au moins une fois\n      erreur_ = previous_erreur_;\n    }\n\n    double get_erreur() const\n    {\n      assert(erreur_!=-1.0);\n      return erreur_;\n    }\n\n    \n    std::pair<double,int> compute_erreur(const Bundle& bundle_)\n    {\n      free_tic.tic();\n      if (erreur_!=-1.0)\n        previous_erreur_ = erreur_;\n      std::tie(erreur_,nb_used_fonctor) =  cost_and_save(bundle_,map_erreur,meds);\n      if (erreur_==-1)\n\t     std::cerr << \" LMA::compute_erreur \" << erreur_ << \" \" << previous_erreur_ << std::endl;\n      assert(erreur_!=-1.0);\n      residual_evaluations += free_tic.toc();\n      return {erreur_,nb_used_fonctor};\n    }\n\n    double compute_scale(double lambda) const\n    {\n      double scale = 0.0;\n      ComputeScale cs(scale,lambda);\n      for_each<MetaBinary<typename Ba::Keys>>(std::tie(ba_.delta,ba_.jte),cs);\n      return scale;\n    }\n    \n    double init_lambda()\n    {\n      double lambda = 0;\n      GetMax gm(lambda);\n//       for_each<MetaUnary<typename Ba::ListeDiag>>(std::tie(ba_.h),[&lambda](auto& table){ lambda = std::max(lambda,table.max_lambda());});\n      for_each<MetaUnary<typename Ba::ListeDiag>>(std::tie(ba_.h),gm);\n      return lambda * 1e-5;\n    }\n    \n//     double prediction(const Bundle& bundle_)\n//     {\n//       double pred=0;\n//       double alpha=0;\n//       typename Ba::Vectors v = ba_.jte;\n//       \n//       bf::for_each(v,[](auto& pair){ pair.second.set_zero(); });\n//       bf::for_each(ba_.h,[&](auto& pair){prod_v_v_h_dispatch(v,ba_.delta,pair.second);});\n//       for_each<MetaBinary<typename Ba::Keys>>(std::tie(v,ba_.delta),[&alpha](auto& a, auto& b){\n//         for(auto i = a.first() ; i < a.size() ; ++i)\n//           alpha += a(i)*b(i);\n//       });\n//       alpha /= 2.0;\n//       std::cout << \" alpha : \" << alpha << std::endl;\n// //       abort();\n//       bf::for_each(ba_.jacob,\n//         [&](auto& pair)\n//         {\n//           typedef typename std::decay<decltype(pair)>::type Pair;\n//           typedef typename Pair::first_type Obs;\n//           auto& jacobs = pair.second;\n//           TooN::Vector<2,double> vec = TooN::Ones;\n//           vec *= alpha;\n//                 \n//           for(size_t iobs = 0 ; iobs < jacobs.size() ; ++iobs)\n//           {\n//             bf::for_each(jacobs.at(iobs),\n//               [&]\n//               (auto& pair_block_jacob)\n//               {\n//                 typedef typename std::decay<decltype(pair_block_jacob)>::type PairBlockJacob;\n//                 typedef typename PairBlockJacob::first_type ParamType;\n//                 auto& block = pair_block_jacob.second;\n//                 auto& container_delta = bf::at_key<ParamType>(ba_.delta);\n//                 typedef typename std::decay<decltype(container_delta)>::type::MatrixTag MatrixTag;\n//                 const auto& map_indice = bundle_.spi2.indices(ttt::Indice<Obs>(iobs));// vector<Indice,...>\n//                 auto& indice = *bf::find<ttt::Indice<ParamType>>(map_indice);\n// \n//                 pred += \n//                         squared_norm(make_view(map_erreur.template at_key<Obs>().at(iobs).first,ttt::wrap<MatrixTag>())\n//                         +\n//                         block * container_delta(indice)\n//                         + vec);\n//               });\n//           }\n//         });\n//       // now I'm damned\n//       return pred;\n//     }\n    \n//     void compute(Bundle& bundle_, double& lambda, bool recalcul, double& pred)\n//     {\n//       set_zero_(ba_);\n//       Policy::init_zero();\n// \n//       if (recalcul)\n//       {\n//         bf::for_each(ba_.h,detail::SetZero());\n//         bf::for_each(ba_.jte,detail::SetZero());\n//         // compute H = JtJ & Jte\n//         detail::fill_hessien_residu33<Derivator<typename Policy::MatrixTag>>(bundle_,ba_,map_erreur);\n//         Policy::save_h(ba_.h);\n//       }\n//       else\n//       {\n//         Policy::reload_h(ba_.h,-prev_lambda);\n//       }\n// \n//       prev_lambda = lambda;\n//       for_each<MetaUnary<typename Ba::ListeDiag>>(std::tie(ba_.h),LambdaDiag(lambda));\n//       Policy::solve(ba_,bundle_);\n//       \n//       pred = prediction(bundle_);\n//       \n//       for_each<MetaBinary<typename Ba::Keys>>(std::tie(bundle_.opt_container.map(),ba_.delta),Correct());\n//     }\n    \n    void compute(Bundle& bundle_, double& lambda, bool recalcul)\n    {\n      Tic tic(\"compute all\");\n      assert(bundle_.nb_obs()!=0);\n      try\n      {\n        set_zero_(ba_);\n        Policy::init_zero();\n\n        free_tic.tic();\n        Tic tic_h(\"compute H\");\n        if (recalcul)\n        {\n          bf::for_each(ba_.h,detail::SetZero());\n          bf::for_each(ba_.jte,detail::SetZero());\n          // compute H = JtJ & Jte\n          detail::fill_hessien<typename Policy::MatrixTag>(bundle_,ba_,map_erreur,meds);\n          Policy::save_h(ba_.h);\n        }\n        else\n        {\n          Policy::reload_h(ba_.h,-prev_lambda);\n        }\n        tic_h.disp();\n        jacobian_evaluations += free_tic.toc();\n\n        free_tic.tic();\n\n        \n        // H += Eye(H)*lambda\n        if (lambda==-1)\n        {\n          lambda = init_lambda();\n        }\n\n        prev_lambda = lambda;\n        for_each<MetaUnary<typename Ba::ListeDiag>>(std::tie(ba_.h),LambdaDiag(lambda));\n        Tic tic_schur(\"SolveDelta\");\n\n\n//         clement(ba_.h);\n//         std::cout << ba_.h << std::endl;\n//           auto a = to_mat<typename Ba::Keys,typename Ba::ListeHessien>(ba_.h,size_tuple<mpl::size<typename Ba::Keys>::value>(ba_.delta));\n          \n//         auto u = Blocker<2,2>::view(a,0,0);\n//         auto v = Blocker<2,2>::view(a,2,2);\n//         auto w = Blocker<2,2>::view(a,0,2);\n//         \n//         std::cout << \" A :\\n\" << a << std::endl << std::endl << std::endl;\n//         std::cout << \" V :\\n\" << v << std::endl;\n//         std::cout << \" W :\\n\" << w << std::endl;\n//         \n//         auto b = to_matv(ba_.jte());\n//         auto ea = Blocker<2,1>::view(b,0,0);\n//         auto eb = Blocker<2,1>::view(b,2,0);\n//         std::cout << \" jte : \" << b.transpose() << std::endl;\n//         std::cout << \" ea  : \" << ea.transpose() << std::endl;\n//         std::cout << \" eb  : \" << eb.transpose() << std::endl;\n//         \n//         auto y = w*v.inverse();\n//         auto s = u - y * w.transpose();\n//         auto e = ea - y * eb;\n//         \n//         auto da = (s.template selfadjointView<Eigen::Upper>().llt().solve(e)).eval();\n//         auto db = v.inverse()*(eb - w.transpose() * da);\n//         \n//         std::cout << \" S : \\n\" << s << std::endl;\n//         std::cout << std::endl;\n//         \n//         std::cout << da.transpose() << \" \" << db.transpose() << std::endl;\n        \n        Policy::solve(ba_,bundle_);\n        \n//         std::cout << to_matv(ba_.delta()).transpose() << std::endl;\n//         std::cout << std::endl;\n        tic_schur.disp();\n        \n        for_each<MetaBinary<typename Ba::Keys>>(std::tie(bundle_.opt_container.map(),ba_.delta),Correct());\n        \n        norm_eq_ += free_tic.toc();\n      }\n      catch(NAN_ERROR& e)\n      {\n        std::cout << \" Optimization failure : \" <<  e.what() << std::endl;\n      }\n      tic.disp();\n    }\n  };\n}\n\nnamespace ttt\n{\n  template<class A> struct Name< lma::LevMar<A> > { static std::string name(){ return \"LevMar<\" + ttt::name<A>() + \">\";} };\n}\n\n#endif\n\n", "meta": {"hexsha": "5c25f55dc92e8859f0690f031a3052aec0d8db5b", "size": 12380, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/libv/lma/lm/algo/levmar.hpp", "max_stars_repo_name": "bezout/LMA", "max_stars_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-12-08T12:07:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T21:23:01.000Z", "max_issues_repo_path": "src/libv/lma/lm/algo/levmar.hpp", "max_issues_repo_name": "ayumizll/LMA", "max_issues_repo_head_hexsha": "e945452e12a8b05bd17400b46a20a5322aeda01d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-07-11T16:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T13:33:00.000Z", "max_forks_repo_path": "src/libv/lma/lm/algo/levmar.hpp", "max_forks_repo_name": "bezout/LMA", "max_forks_repo_head_hexsha": "9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-12-21T01:52:27.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-26T02:26:55.000Z", "avg_line_length": 33.4594594595, "max_line_length": 141, "alphanum_fraction": 0.5436187399, "num_tokens": 3428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4450575748269225}}
{"text": "#pragma once\n\n#include <iostream>\n#include <experimental/filesystem>\n#include <fstream>\n#include <random>\n\n#define EIGEN_DONT_PARALLELIZE 1\n\n#include <Eigen/Dense>\n\n// Function: read_mnist_label\ninline auto read_mnist_label(const std::experimental::filesystem::path& path) {\n  \n  // Helper lambda.\n  auto reverse_int = [](int i) {\n    unsigned char c1, c2, c3, c4;\n    c1 = i         & 255;\n    c2 = (i >> 8)  & 255;\n    c3 = (i >> 16) & 255;\n    c4 = (i >> 24) & 255;\n    return ((int)c1 << 24) + ((int)c2 << 16) + ((int)c3 << 8) + c4;\n  };\n  \n  // Read the image.\n  std::ifstream ifs(path, std::ios::binary);\n  \n  if(!ifs) {\n    assert(false);\n  }\n\n  int magic_number = 0;\n  int num_imgs = 0;\n\n  ifs.read((char*)&magic_number, sizeof(magic_number));\n  magic_number = reverse_int(magic_number);\n\n  ifs.read((char*)&num_imgs, sizeof(num_imgs));\n  num_imgs = reverse_int(num_imgs);\n  \n  Eigen::VectorXi labels(num_imgs);\n  for (int i = 0; i<num_imgs; ++i) {\n    unsigned char temp = 0;  // must use unsigned\n    ifs.read((char*)&temp, sizeof(temp));\n    labels[i] = static_cast<int>(temp);\n  }\n  return labels;\n}\n\n\ninline auto read_mnist_image(const std::experimental::filesystem::path& path) {\n  \n  // Helper lambda.\n  auto reverse_int = [] (int i) {\n    unsigned char c1, c2, c3, c4;\n    c1 = i         & 255;\n    c2 = (i >> 8)  & 255;\n    c3 = (i >> 16) & 255;\n    c4 = (i >> 24) & 255;\n    return ((int)c1 << 24) + ((int)c2 << 16) + ((int)c3 << 8) + c4;\n  };\n  \n  // Read the image.\n  std::ifstream ifs(path, std::ios::binary);\n\n  if(!ifs) {\n    assert(false);\n  }\n\n  int magic_number = 0;\n  int num_imgs = 0;\n  int num_rows = 0;\n  int num_cols = 0;\n\n  ifs.read((char*)&magic_number, sizeof(magic_number));\n  magic_number = reverse_int(magic_number);\n\n  ifs.read((char*)&num_imgs, sizeof(num_imgs));\n  num_imgs = reverse_int(num_imgs);\n\n  ifs.read((char*)&num_rows, sizeof(num_rows));\n  num_rows = reverse_int(num_rows);\n\n  ifs.read((char*)&num_cols, sizeof(num_cols));\n  num_cols = reverse_int(num_cols);\n \n  Eigen::MatrixXf images(num_imgs, num_rows*num_cols);\n\n  for(int i = 0; i < num_imgs; ++i) {\n    for(int r = 0; r < num_rows; ++r) {\n      for(int c = 0; c < num_cols; ++c) {\n        unsigned char p = 0;  // must use unsigned\n        ifs.read((char*)&p, sizeof(p));\n        images(i, r*num_cols + c) = static_cast<float>(p);\n      }\n    }\n  }\n\n  for(int i=0; i<images.rows(); i++) {\n    for(int j=0; j<images.cols(); j++) {\n      images(i, j) /= 255.0;\n    }\n  }\n  return images;\n}\n\ninline auto time_diff(\n  std::chrono::time_point<std::chrono::high_resolution_clock> &t1, \n  std::chrono::time_point<std::chrono::high_resolution_clock> &t2\n) {\n  return std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();\n}\n\n\n\n// ------------------------------------------------------------------------------------------------\n\n\nenum class Activation {\n  NONE,\n  RELU,\n  SIGMOID\n};\n\n// Procedure: sigmoid\ninline void sigmoid(Eigen::MatrixXf& x) {\n  x = ((1.0f + (-x).array().exp()).inverse()).matrix();\n}\n\n// Procedure: relu\ninline void relu(Eigen::MatrixXf& x) {\n  for(int j=0; j<x.cols(); ++j) {\n    for(int i=0; i<x.rows(); ++i) {\n      if(x(i, j) <= 0.0f) {\n        x(i, j) = 0.0f;\n      }   \n    }   \n  }\n}\n\ninline void activate(Eigen::MatrixXf& mat, Activation act) {\n  switch(act) {\n    case Activation::NONE:  return;\n    case Activation::SIGMOID: sigmoid(mat); return;\n    case Activation::RELU: relu(mat); return;\n  };\n}\n\n\n// Function: drelu\ninline void drelu(Eigen::MatrixXf& x) {\n  for(int j=0; j<x.cols(); ++j) {\n    for(int i=0; i<x.rows(); ++i) {\n      x(i, j) = x(i, j) > 0.0f ? 1.0f : 0.0f;\n    }\n  }\n}\n\n// Function: dsigmoid\ninline void dsigmoid(Eigen::MatrixXf& x) {\n  x = x.array() * (1 - x.array());\n}\n\ninline void deactivate(Eigen::MatrixXf& mat, Activation act) {\n  switch(act) {\n    case Activation::NONE:    mat = Eigen::MatrixXf::Ones(mat.rows(), mat.cols()); return; \n    case Activation::SIGMOID: dsigmoid(mat); return ;\n    case Activation::RELU:    drelu(mat); return;\n  };\n}\n\n\n// ----------------------------------------------------------------------------\n\nstruct MNIST_DNN {\n  // Ctor\n  MNIST_DNN() = default;\n\n  void add_layer(size_t in_degree, size_t out_degree, Activation act) {\n    acts.emplace_back(act);\n    Ys.emplace_back().resize(batch_size, out_degree);\n    Ws.push_back(Eigen::MatrixXf::Random(in_degree, out_degree));\n    Bs.push_back(Eigen::MatrixXf::Random(1, out_degree));\n\n    dW.emplace_back().resize(in_degree, out_degree);\n    dB.emplace_back().resize(1, out_degree);\n  }\n\n  void forward(size_t layer, const Eigen::MatrixXf& mat) {\n    Ys[layer] = mat * Ws[layer] + Bs[layer].replicate(mat.rows(), 1);\n    activate(Ys[layer], acts[layer]);\n  }\n\n  void loss(const Eigen::VectorXi& labels) {\n    delta = Ys.back();\n    delta = (delta - delta.rowwise().maxCoeff().replicate(1, delta.cols())).array().exp().matrix();\n    delta = delta.cwiseQuotient(delta.rowwise().sum().replicate(1, delta.cols()));\n    for(size_t i=beg_row, j=0; j<batch_size; i++, j++) {\n      delta(j, labels[i]) -= 1.0;\n    }\n  }\n\n  void backward(size_t layer, const Eigen::MatrixXf& Xin) {\n    deactivate(Ys[layer], acts[layer]);\n    delta = delta.cwiseProduct(Ys[layer]);\n    dB[layer] = delta.colwise().sum();\n    dW[layer] = Xin.transpose() * delta;\n\n    if(layer > 0) {\n      delta = delta * Ws[layer].transpose();\n    }\n  }\n\n  void update(size_t layer) {\n    Ws[layer] -= lrate*(dW[layer] + decay*Ws[layer]);\n    Bs[layer] -= lrate*(dB[layer] + decay*Bs[layer]); \n  }\n\n  // Testing images # = 10000 x 784 (28 x 28)\n  void validate(Eigen::MatrixXf& test_images, Eigen::VectorXi& test_labels) {\n    Eigen::MatrixXf res = test_images; \n    //auto t1 = std::chrono::high_resolution_clock::now();\n    for(size_t i=0; i<acts.size(); i++) {\n      res = res * Ws[i] + Bs[i].replicate(res.rows(), 1);\n      if(acts[i] == Activation::RELU) {\n        relu(res);\n      }\n      else if(acts[i] == Activation::SIGMOID) {\n        sigmoid(res);\n      }\n    }\n    //auto t2 = std::chrono::high_resolution_clock::now();\n    //std::cout << \"Infer runtime: \" << time_diff(t1, t2) << \" ms\\n\";\n\n    size_t correct_num {0};\n    for(int k=0; k<res.rows(); k++) {\n      int pred ; \n      res.row(k).maxCoeff(&pred);\n      if(pred == test_labels[k]) {\n        correct_num ++;\n      }\n    }\n    //std::cout << \"Accuracy: \" << correct_num << '/' << res.rows() << '\\n';\n  }\n\n  // Parameter functions ------------------------------------------------------\n  auto& epoch_num(unsigned e) {\n    epoch = e;\n    return *this;\n  }\n  auto& batch(size_t b) {\n    batch_size = b;\n    //assert(images->rows()%batch_size == 0);\n    return *this;\n  }\n  auto& learning_rate(float l) {\n    lrate = l;\n    return *this;\n  }\n\n  auto num_layers() const {\n    return acts.size();\n  }\n\n  std::vector<Eigen::MatrixXf> Ys;\n  std::vector<Eigen::MatrixXf> Ws;\n  std::vector<Eigen::MatrixXf> Bs;\n  std::vector<Eigen::MatrixXf> dW;\n  std::vector<Eigen::MatrixXf> dB;\n\n  std::vector<Activation> acts;\n\n  // Training images # = 60000 x 784 (28 x 28)\n  //Eigen::MatrixXf* images;\n  //Eigen::VectorXi* labels;\n  Eigen::MatrixXf delta;\n\n  int beg_row {0};\n\n  float lrate {0.01f};\n  float decay {0.01f};\n\n  unsigned epoch {0};\n  size_t batch_size {1};\n};\n\ninline Eigen::MatrixXf IMAGES;\ninline Eigen::VectorXi LABELS;\ninline Eigen::MatrixXf TEST_IMAGES;\ninline Eigen::VectorXi TEST_LABELS;\n\n// A workable DNN setting:\n//   BATCH = 100 (or 50~100)\n//   NUM_ITERATIONS = 60000/BATCH\n//   dnn.add_layer(784, 100, Activation::RELU);\n//   dnn.add_layer(100, 30, Activation::RELU);\n//   dnn.add_layer(30, 10, Activation::NONE); \n\n// The total number of training data = 60000\ninline constexpr size_t BATCH {60};\ninline constexpr size_t NUM_ITERATIONS {60000/BATCH};\ninline constexpr size_t NUM_DNNS {10};\n\ninline void init_dnn(MNIST_DNN& dnn, float rate) {\n  //dnn.batch(BATCH).learning_rate(0.001);\n  //dnn.add_layer(784, 100, Activation::RELU);\n  //dnn.add_layer(100, 30, Activation::RELU);\n  //dnn.add_layer(30, 10, Activation::NONE); \n\n  dnn.batch(BATCH).learning_rate(rate);\n  dnn.add_layer(784, 64, Activation::RELU);\n  dnn.add_layer(64, 32, Activation::RELU);\n  dnn.add_layer(32, 16, Activation::RELU);\n  dnn.add_layer(16, 8, Activation::RELU);\n  dnn.add_layer(8, 10, Activation::NONE); \n}\n\ninline void forward_task(MNIST_DNN& D,  \n  Eigen::MatrixXf& mat, \n  Eigen::VectorXi& vec) {\n\n  for(size_t i=0; i<D.acts.size(); i++) {\n    if(i == 0){\n      D.forward(i, mat.middleRows(D.beg_row, D.batch_size));\n    }\n    else {\n      D.forward(i, D.Ys[i-1]);\n    }\n  }\n\n  D.loss(vec);\n}\n\ninline void backward_task(MNIST_DNN& D, size_t i, Eigen::MatrixXf& mat) {\n  if(i > 0) {\n    //D.backward(i, D.Ys[i-1].transpose());       \n    D.backward(i, D.Ys[i-1]);       \n  }\n  else {\n    //D.backward(i, mat.middleRows(D.beg_row, D.batch_size).transpose());\n    D.backward(i, mat.middleRows(D.beg_row, D.batch_size));\n\n    D.beg_row += D.batch_size;\n    if(D.beg_row >= IMAGES.rows()) {\n      D.beg_row = 0;\n    }\n  }\n}\n\ninline void shuffle(Eigen::MatrixXf& mat, Eigen::VectorXi& vec) {\n\n  static thread_local std::mt19937 gen(0); \n\n  Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> p(mat.rows());\n  p.setIdentity();\n  std::shuffle(p.indices().data(), p.indices().data() + p.indices().size(), gen);\n\n  mat = p * mat;\n  vec = p * vec;\n}\n\n\ninline void report_runtime(std::chrono::time_point<std::chrono::high_resolution_clock>& t1) {\n  auto t2 = std::chrono::high_resolution_clock::now();\n  std::cout << \"One iteration runtime: \"\n            << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << \" ms\\n\";\n  t1 = std::chrono::high_resolution_clock::now();\n}\n\ninline float rand_rate() {\n  return static_cast<float>(rand())/static_cast<float>(RAND_MAX);\n}\n\nvoid run_tbb(const unsigned, const unsigned);\nvoid run_taskflow(const unsigned, const unsigned);\nvoid run_omp(const unsigned, const unsigned);\nvoid run_sequential(unsigned, unsigned);\n\n", "meta": {"hexsha": "14cac68d6fc068ff23ac800e4af23c315675155c", "size": 9934, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sandbox/parallel_dnn/dnn.hpp", "max_stars_repo_name": "sdmg15/taskflow", "max_stars_repo_head_hexsha": "eb61d6e0d410a67e214414d34d5992c8e401e1fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-06-06T17:21:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T13:16:40.000Z", "max_issues_repo_path": "sandbox/parallel_dnn/dnn.hpp", "max_issues_repo_name": "sdmg15/taskflow", "max_issues_repo_head_hexsha": "eb61d6e0d410a67e214414d34d5992c8e401e1fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sandbox/parallel_dnn/dnn.hpp", "max_forks_repo_name": "sdmg15/taskflow", "max_forks_repo_head_hexsha": "eb61d6e0d410a67e214414d34d5992c8e401e1fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-10T17:53:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-23T19:03:09.000Z", "avg_line_length": 26.2110817942, "max_line_length": 99, "alphanum_fraction": 0.6005637206, "num_tokens": 3041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.672331699179286, "lm_q1q2_score": 0.4450317318458662}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <opencv2/opencv.hpp>\n\n#include \"structures.h\"\n#include \"transformations.h\"\n#include \"cauchy.h\"\n#include \"perspective_camera_with_intrinsics_tait_bryan_cw_jacobian.h\"\n#include \"perspective_camera_with_intrinsics_rodrigues_cw_jacobian.h\"\n#include \"perspective_camera_with_intrinsics_quaternion_cw_jacobian.h\"\n#include \"quaternion_constraint_jacobian.h\"\n#include \"perspective_camera_tait_bryan_wc_jacobian.h\"\n\ndouble k1 = 0.1686;\ndouble k2 = -0.515827;\ndouble k3 = 0.446983;\ndouble k4 = 0.0;\ndouble k5 = 0.0;\ndouble k6 = 0.0;\ndouble p1 = -0.00138148;\ndouble p2 = 0.000127175;\n\ndouble k1tmp;\ndouble k2tmp;\ndouble k3tmp;\ndouble k4tmp;\ndouble k5tmp;\ndouble k6tmp;\ndouble p1tmp;\ndouble p2tmp;\n\nstruct KeyPoint{\n\tdouble u;\n\tdouble v;\n\tstd::pair<int,int> index_to_tie_point;\n};\n\nstruct Camera{\n\tEigen::Affine3d pose;\n\tstd::vector<std::vector<KeyPoint>> key_points;\n};\n\nstd::vector<std::vector<Eigen::Vector3d>> tie_points;\nstd::vector<Camera> cameras;\nPerspectiveCameraParams cam_params;\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = -62, rotate_y = 21;\nfloat translate_z = -12.4502;\nfloat translate_x = -0.899999, translate_y = -1.49993;\nbool show_only_one = true;\n\nbool initGL(int *argc, char **argv);\nvoid display();\nvoid keyboard(unsigned char key, int x, int y);\nvoid mouse(int button, int state, int x, int y);\nvoid motion(int x, int y);\nvoid reshape(int w, int h);\nvoid printHelp();\n\nint main(int argc, char *argv[]){\n\tk1tmp = k1;\n\tk2tmp = k2;\n\tk3tmp = k3;\n\tp1tmp = p1;\n\tp2tmp = p2;\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tcam_params.fx = 1727;\n\tcam_params.fy = 1727;\n\tcam_params.cx = 985;\n\tcam_params.cy = 522;\n\n\tfor(size_t i = 0 ; i < 8; i++){\n\t\tstd::vector<Eigen::Vector3d> tps;\n\t\tfor(size_t j = 0 ; j < 8; j++){\n\t\tEigen::Vector3d p;\n\t\tp.x() = i;\n\t\tp.y() = j;\n\t\tp.z() = 0;\n\t\ttps.push_back(p);\n\t\t}\n\t\ttie_points.push_back(tps);\n\t}\n\n\tfor(float i = 3 ; i < 5; i+=0.5){\n\t\tCamera c;\n\t\tc.pose = Eigen::Affine3d::Identity();\n\t\tc.pose(0,3) = 4;\n\t\tc.pose(1,3) = i;\n\t\tc.pose(2,3) = -10;\n\t\tcameras.push_back(c);\n\t}\n\n\tfor(size_t i = 0 ; i < cameras.size(); i++){\n\t\tfor(size_t j = 0; j < tie_points.size(); j++){\n\t\t\tstd::vector<KeyPoint> kps;\n\t\t\tfor(size_t k = 0; k < tie_points[j].size(); k++){\n\t\t\t\tKeyPoint kp;\n\t\t\t\tkp.index_to_tie_point = std::pair<int,int>(j,k);\n\n\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(cameras[i].pose.inverse());\n\t\t\t\tprojection_perspective_camera_with_intrinsics_tait_bryan_cw(kp.u, kp.v, cam_params.fx, cam_params.fy, cam_params.cx, cam_params.cy, pose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka,\n\t\t\t\t\t\ttie_points[j][k].x(), tie_points[j][k].y(), tie_points[j][k].z(),  k1,  k2,  k3, p1, p2);\n\t\t\t\tkps.push_back(kp);\n\t\t\t}\n\t\t\tcameras[i].key_points.push_back(kps);\n\t\t}\n\t}\n\n\tk1 = 0.0;\n\tk2 = 0.0;\n\tp1 = 0.0;\n\tp2 = 0.0;\n\tk3 = 0.0;\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"perspective_camera_intrinsic_calibration\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01,\n\t\t\t10000.0);\n\tglutReshapeFunc(reshape);\n\n\treturn true;\n}\n\nEigen::Vector3d get_intersection(float u, float v, Eigen::Affine3d camera_pose_wc){\n\tcv::Mat mat(1, 2, CV_32F);\n\tmat.at<float>(0, 0) = u;\n\tmat.at<float>(0, 1) = v;\n\n\tcv::Mat cv_cam_matrix = (cv::Mat_<float>(3, 3) << cam_params.fx, 0, cam_params.cx, 0, cam_params.fy, cam_params.cy, 0, 0, 1);\n\tcv::Mat cv_dist_params = (cv::Mat_<float>(5, 1) << k1, k2, p1, p2, k3);\n\n\tmat = mat.reshape(2);\n\tcv::undistortPoints(mat, mat, cv_cam_matrix, cv_dist_params, cv::Mat(), cv_cam_matrix,\n\t\t\t\t\t\tcv::TermCriteria(cv::TermCriteria::EPS | cv::TermCriteria::MAX_ITER, 20, 1e-6));\n\tmat = mat.reshape(1);\n\n\tdouble undistorted_u = mat.at<float>(0, 0);\n\tdouble undistorted_v = mat.at<float>(0, 1);\n\n\tEigen::Matrix3d K;\n\tK(0,0) = cam_params.fx;\n\tK(0,1) = 0;\n\tK(0,2) = cam_params.cx;\n\tK(1,0) = 0;\n\tK(1,1) = cam_params.fy;\n\tK(1,2) = cam_params.cy;\n\tK(2,0) = 0;\n\tK(2,1) = 0;\n\tK(2,2) = 1;\n\n\tEigen::Vector3d p(undistorted_u, undistorted_v, 1);\n\tEigen::Vector3d r =  K.inverse() * p;\n\tEigen::Matrix3d R = camera_pose_wc.rotation();\n\tEigen::Vector3d T = camera_pose_wc.translation();\n\tEigen::Vector3d rt = R*r + T;\n\n\tEigen::Vector3d n(0,0,-1);\n\tEigen::Vector3d a(camera_pose_wc(0,3), camera_pose_wc(1,3), camera_pose_wc(2,3));\n\tEigen::Vector3d b = rt;\n\n\tEigen::Vector3d ba = b-a;\n\tEigen::Vector3d intersection = a + (((0 - n.dot(a))/n.dot(ba)) * ba);\n\treturn intersection;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tglLineWidth(2);\n\tglColor3f(1,0,0);\n\tglBegin(GL_LINES);\n\tfor(size_t i = 0 ; i < tie_points.size(); i++){\n\t\tfor(size_t j = 0 ; j < tie_points[i].size(); j++){\n\t\t\tif(j+1 < tie_points[i].size()){\n\t\t\t\tglVertex3f(tie_points[i][j].x(), tie_points[i][j].y(), tie_points[i][j].z());\n\t\t\t\tglVertex3f(tie_points[i][j+1].x(), tie_points[i][j+1].y(), tie_points[i][j+1].z());\n\t\t\t}\n\n\t\t\tif(i+1 < tie_points.size()){\n\t\t\t\tglVertex3f(tie_points[i][j].x(), tie_points[i][j].y(), tie_points[i][j].z());\n\t\t\t\tglVertex3f(tie_points[i+1][j].x(), tie_points[i+1][j].y(), tie_points[i+1][j].z());\n\t\t\t}\n\t\t}\n\t}\n\tglEnd();\n\n\tfor(size_t i = 0 ; i < cameras.size(); i++){\n\t\tEigen::Affine3d m = cameras[i].pose;\n\n\t\tglBegin(GL_LINES);\n\t\t\tglColor3f(1.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\t\tglVertex3f(m(0,3) + m(0,0), m(1,3) + m(1,0), m(2,3) + m(2,0));\n\n\t\t\tglColor3f(0.0f, 1.0f, 0.0f);\n\t\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\t\tglVertex3f(m(0,3) + m(0,1), m(1,3) + m(1,1), m(2,3) + m(2,1));\n\n\t\t\tglColor3f(0.0f, 0.0f, 1.0f);\n\t\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\t\tglVertex3f(m(0,3) + m(0,2), m(1,3) + m(1,2), m(2,3) + m(2,2));\n\t\tglEnd();\n\t}\n\n\tint number_cameras = 1;\n\tif(!show_only_one){\n\t\tnumber_cameras = cameras.size();\n\t}\n\tglColor3f(0,1,0);\n\tglBegin(GL_LINES);\n\tfor(size_t i = 0; i < number_cameras; i++){\n\t\tfor(size_t j = 0; j < cameras[i].key_points.size(); j++){\n\t\t\tfor(size_t k = 0; k < cameras[i].key_points[j].size(); k++){\n\t\t\t\tif(k+1 < tie_points[j].size()){\n\t\t\t\t\tEigen::Vector3d intersection = get_intersection(cameras[i].key_points[j][k].u, cameras[i].key_points[j][k].v, cameras[i].pose);\n\t\t\t\t\tglVertex3f(intersection.x(), intersection.y(), intersection.z());\n\n\t\t\t\t\tintersection = get_intersection(cameras[i].key_points[j][k+1].u, cameras[i].key_points[j][k+1].v, cameras[i].pose);\n\t\t\t\t\tglVertex3f(intersection.x(), intersection.y(), intersection.z());\n\t\t\t\t}\n\n\t\t\t\tif(j+1 < tie_points.size()){\n\t\t\t\t\tEigen::Vector3d intersection = get_intersection(cameras[i].key_points[j][k].u, cameras[i].key_points[j][k].v, cameras[i].pose);\n\t\t\t\t\tglVertex3f(intersection.x(), intersection.y(), intersection.z());\n\n\t\t\t\t\tintersection = get_intersection(cameras[i].key_points[j+1][k].u, cameras[i].key_points[j+1][k].v, cameras[i].pose);\n\t\t\t\t\tglVertex3f(intersection.x(), intersection.y(), intersection.z());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tglEnd();\n\tglPointSize(1);\n\n\tglutSwapBuffers();\n}\n\nvoid keyboard(unsigned char key, int /*x*/, int /*y*/) {\n\tswitch (key) {\n\t\tcase (27): {\n\t\t\tglutDestroyWindow(glutGetWindow());\n\t\t\treturn;\n\t\t}\n\t\tcase 'c':{\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tTaitBryanPose pose;\n\t\t\t\tpose.px = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1;\n\t\t\t\tpose.py = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1;\n\t\t\t\tpose.pz = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1;\n\t\t\t\tpose.om = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.1;\n\t\t\t\tpose.fi = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.1;\n\t\t\t\tpose.ka = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.1;\n\n\t\t\t\tEigen::Affine3d m = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\tcameras[i].pose = cameras[i].pose * m;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 't':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tint number_intrinsic_paramters = 5;\n\n\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < cameras[i].key_points.size(); j++){\n\t\t\t\t\tfor(size_t k = 0; k < cameras[i].key_points[j].size(); k++){\n\t\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(cameras[i].pose.inverse());\n\n\t\t\t\t\t\tEigen::Matrix<double, 2, 1> delta;\n\t\t\t\t\t\tobservation_equation_perspective_camera_with_intrinsics_tait_bryan_cw(delta, cam_params.fx, cam_params.fy, cam_params.cx, cam_params.cy,\n\t\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka,\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].x(),\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].y(),\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].z(),\n\t\t\t\t\t\t\t\tstd::floor(cameras[i].key_points[j][k].u), std::floor(cameras[i].key_points[j][k].v), k1, k2, k3, p1, p2);\n\n\t\t\t\t\t\tEigen::Matrix<double, 2, 14> jacobian;\n\t\t\t\t\t\tobservation_equation_perspective_camera_with_intrinsics_tait_bryan_cw_jacobian(jacobian, cam_params.fx, cam_params.fy,\n\t\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka,\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].x(),\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].y(),\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].z(),\n\t\t\t\t\t\t\t\tk1, k2, k3, p1, p2);\n\n\t\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\t\tint ic_camera = i * 6;\n\n\t\t\t\t\t\tfor(size_t l = 0; l < number_intrinsic_paramters; l++){\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir     , l, -jacobian(0,l));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor(size_t l = 0; l < number_intrinsic_paramters; l++){\n\t\t\t\t\t\t\ttripletListA.emplace_back(ir + 1  , l, -jacobian(1,l));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera     + number_intrinsic_paramters, -jacobian(0,0 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 1 + number_intrinsic_paramters, -jacobian(0,1 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 2 + number_intrinsic_paramters, -jacobian(0,2 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 3 + number_intrinsic_paramters, -jacobian(0,3 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 4 + number_intrinsic_paramters, -jacobian(0,4 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 5 + number_intrinsic_paramters, -jacobian(0,5 + number_intrinsic_paramters));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera     + number_intrinsic_paramters, -jacobian(1,0 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 1 + number_intrinsic_paramters, -jacobian(1,1 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 2 + number_intrinsic_paramters, -jacobian(1,2 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 3 + number_intrinsic_paramters, -jacobian(1,3 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 4 + number_intrinsic_paramters, -jacobian(1,4 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 5 + number_intrinsic_paramters, -jacobian(1,5 + number_intrinsic_paramters));\n\n\t\t\t\t\t\ttripletListP.emplace_back(ir    , ir    , cauchy(delta(0,0), 1));\n\t\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, cauchy(delta(1,0), 1));\n\n\t\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta(1,0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), cameras.size() * 6 + number_intrinsic_paramters);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(cameras.size() * 6 + number_intrinsic_paramters, cameras.size() * 6 + number_intrinsic_paramters);\n\t\t\tEigen::SparseMatrix<double> AtPB(cameras.size() * 6 + number_intrinsic_paramters, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == cameras.size() * 6 + number_intrinsic_paramters){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tk1 += h_x[counter++];\n\t\t\t\tk2 += h_x[counter++];\n\t\t\t\tk3 += h_x[counter++];\n\t\t\t\tp1 += h_x[counter++];\n\t\t\t\tp2 += h_x[counter++];\n\n\t\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(cameras[i].pose.inverse());\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\n\t\t\t\t\tcameras[i].pose = affine_matrix_from_pose_tait_bryan(pose).inverse();\n\t\t\t\t}\n\n\t\t\t\tstd::cout << \"desired intrinsic parameters:\" << std::endl;\n\t\t\t\tstd::cout << \"k1: \" << k1tmp << \" k2: \" << k2tmp << \" k3: \" << k3tmp << \" k4: \" << k4tmp << \" k5: \" << k5tmp << \" k6: \" << k6tmp << \" p1: \" << p1tmp << \" p2: \" << p2tmp << std::endl;\n\t\t\t\tstd::cout << \"computer intrinsic parameters:\" << std::endl;\n\t\t\t\tstd::cout << \"k1: \" << k1 << \" k2: \" << k2 << \" k3: \" << k3 << \" k4: \" << k4 << \" k5: \" << k5 << \" k6: \" << k6 << \" p1: \" << p1 << \" p2: \" << p2 << std::endl;\n\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'r':{\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tTaitBryanPose posetb = pose_tait_bryan_from_affine_matrix(cameras[i].pose);\n\t\t\t\tposetb.px += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.py += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.pz += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.om += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.fi += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.ka += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tcameras[i].pose = affine_matrix_from_pose_tait_bryan(posetb);\n\t\t\t}\n\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tint number_intrinsic_paramters = 5;\n\n\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < cameras[i].key_points.size(); j++){\n\t\t\t\t\tfor(size_t k = 0; k < cameras[i].key_points[j].size(); k++){\n\n\t\t\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(cameras[i].pose.inverse());\n\n\t\t\t\t\t\tEigen::Matrix<double, 2, 1> delta;\n\t\t\t\t\t\tobservation_equation_perspective_camera_with_intrinsics_rodrigues_cw(delta, cam_params.fx, cam_params.fy, cam_params.cx, cam_params.cy,\n\t\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.sx, pose.sy, pose.sz,\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].x(),\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].y(),\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].z(),\n\t\t\t\t\t\t\t\tstd::floor(cameras[i].key_points[j][k].u), std::floor(cameras[i].key_points[j][k].v), k1, k2, k3, p1, p2);\n\n\t\t\t\t\t\tEigen::Matrix<double, 2, 14> jacobian;\n\t\t\t\t\t\tobservation_equation_perspective_camera_with_intrinsics_rodrigues_cw_jacobian(jacobian, cam_params.fx, cam_params.fy,\n\t\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.sx, pose.sy, pose.sz,\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].x(),\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].y(),\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].z(),\n\t\t\t\t\t\t\t\tk1, k2, k3, p1, p2);\n\n\t\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\t\tint ic_camera = i * 6;\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , 0, -jacobian(0,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , 1, -jacobian(0,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , 2, -jacobian(0,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , 3, -jacobian(0,3));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , 4, -jacobian(0,4));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , 0, -jacobian(1,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , 1, -jacobian(1,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , 2, -jacobian(1,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , 3, -jacobian(1,3));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , 4, -jacobian(1,4));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera     + number_intrinsic_paramters, -jacobian(0,0 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 1 + number_intrinsic_paramters, -jacobian(0,1 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 2 + number_intrinsic_paramters, -jacobian(0,2 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 3 + number_intrinsic_paramters, -jacobian(0,3 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 4 + number_intrinsic_paramters, -jacobian(0,4 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 5 + number_intrinsic_paramters, -jacobian(0,5 + number_intrinsic_paramters));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera     + number_intrinsic_paramters, -jacobian(1,0 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 1 + number_intrinsic_paramters, -jacobian(1,1 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 2 + number_intrinsic_paramters, -jacobian(1,2 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 3 + number_intrinsic_paramters, -jacobian(1,3 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 4 + number_intrinsic_paramters, -jacobian(1,4 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 5 + number_intrinsic_paramters, -jacobian(1,5 + number_intrinsic_paramters));\n\n\t\t\t\t\t\ttripletListP.emplace_back(ir    , ir    , cauchy(delta(0,0), 1));\n\t\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, cauchy(delta(1,0), 1));\n\n\t\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta(1,0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), cameras.size() * 6 + number_intrinsic_paramters);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(cameras.size() * 6 + number_intrinsic_paramters, cameras.size() * 6 + number_intrinsic_paramters);\n\t\t\tEigen::SparseMatrix<double> AtPB(cameras.size() * 6 + number_intrinsic_paramters, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == cameras.size() * 6 + number_intrinsic_paramters){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tk1 += h_x[counter++];\n\t\t\t\tk2 += h_x[counter++];\n\t\t\t\tk3 += h_x[counter++];\n\t\t\t\tp1 += h_x[counter++];\n\t\t\t\tp2 += h_x[counter++];\n\n\t\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(cameras[i].pose.inverse());\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.sx += h_x[counter++];\n\t\t\t\t\tpose.sy += h_x[counter++];\n\t\t\t\t\tpose.sz += h_x[counter++];\n\n\t\t\t\t\tcameras[i].pose = affine_matrix_from_pose_rodrigues(pose).inverse();\n\t\t\t\t}\n\n\t\t\t\tstd::cout << \"desired intrinsic parameters:\" << std::endl;\n\t\t\t\tstd::cout << \"k1: \" << k1tmp << \" k2: \" << k2tmp << \" k3: \" << k3tmp << \" p1: \" << p1tmp << \" p2: \" << p2tmp << std::endl;\n\t\t\t\tstd::cout << \"computer intrinsic parameters:\" << std::endl;\n\t\t\t\tstd::cout << \"k1: \" << k1 << \" k2: \" << k2 << \" k3: \" << k3 << \" p1: \" << p1 << \" p2: \" << p2 << std::endl;\n\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'q':{\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tTaitBryanPose posetb = pose_tait_bryan_from_affine_matrix(cameras[i].pose);\n\t\t\t\tposetb.px += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.000001;\n\t\t\t\tposetb.py += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.000001;\n\t\t\t\tposetb.pz += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.000001;\n\t\t\t\tposetb.om += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.000001;\n\t\t\t\tposetb.fi += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.000001;\n\t\t\t\tposetb.ka += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.000001;\n\t\t\t\tcameras[i].pose = affine_matrix_from_pose_tait_bryan(posetb);\n\t\t\t}\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tint number_intrinsic_paramters = 5;\n\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < cameras[i].key_points.size(); j++){\n\t\t\t\t\tfor(size_t k = 0; k < cameras[i].key_points[j].size(); k++){\n\t\t\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(cameras[i].pose.inverse());\n\n\t\t\t\t\t\tEigen::Matrix<double, 2, 1> delta;\n\t\t\t\t\t\tobservation_equation_perspective_camera_with_intrinsics_quaternion_cw(delta, cam_params.fx, cam_params.fy, cam_params.cx, cam_params.cy,\n\t\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.q0, pose.q1, pose.q2, pose.q3,\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].x(),\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].y(),\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].z(),\n\t\t\t\t\t\t\t\tstd::floor(cameras[i].key_points[j][k].u), std::floor(cameras[i].key_points[j][k].v), k1, k2, k3, p1, p2);\n\n\t\t\t\t\t\tEigen::Matrix<double, 2, 15> jacobian;\n\t\t\t\t\t\tobservation_equation_perspective_camera_with_intrinsics_quaternion_cw_jacobian(jacobian, cam_params.fx, cam_params.fy,\n\t\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.q0, pose.q1, pose.q2, pose.q3,\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].x(),\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].y(),\n\t\t\t\t\t\t\t\ttie_points[cameras[i].key_points[j][k].index_to_tie_point.first][cameras[i].key_points[j][k].index_to_tie_point.second].z(),\n\t\t\t\t\t\t\t\tk1, k2, k3, p1, p2);\n\n\t\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\t\tint ic_camera = i * 7;\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , 0, -jacobian(0,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , 1, -jacobian(0,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , 2, -jacobian(0,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , 3, -jacobian(0,3));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , 4, -jacobian(0,4));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , 0, -jacobian(1,0));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , 1, -jacobian(1,1));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , 2, -jacobian(1,2));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , 3, -jacobian(1,3));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , 4, -jacobian(1,4));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera     + number_intrinsic_paramters, -jacobian(0,0 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 1 + number_intrinsic_paramters, -jacobian(0,1 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 2 + number_intrinsic_paramters, -jacobian(0,2 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 3 + number_intrinsic_paramters, -jacobian(0,3 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 4 + number_intrinsic_paramters, -jacobian(0,4 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 5 + number_intrinsic_paramters, -jacobian(0,5 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 6 + number_intrinsic_paramters, -jacobian(0,6 + number_intrinsic_paramters));\n\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera     + number_intrinsic_paramters, -jacobian(1,0 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 1 + number_intrinsic_paramters, -jacobian(1,1 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 2 + number_intrinsic_paramters, -jacobian(1,2 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 3 + number_intrinsic_paramters, -jacobian(1,3 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 4 + number_intrinsic_paramters, -jacobian(1,4 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 5 + number_intrinsic_paramters, -jacobian(1,5 + number_intrinsic_paramters));\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 6 + number_intrinsic_paramters, -jacobian(1,6 + number_intrinsic_paramters));\n\n\t\t\t\t\t\ttripletListP.emplace_back(ir    , ir    , cauchy(delta(0,0), 1));\n\t\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, cauchy(delta(1,0), 1));\n\n\t\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta(1,0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << \"joo2\" << std::endl;\n\t\t\tfor(size_t i = 0 ; i < cameras.size(); i++){\n\t\t\t\tint ic = i * 7 + number_intrinsic_paramters;\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(cameras[i].pose);\n\n\t\t\t\tdouble delta;\n\t\t\t\tquaternion_constraint(delta, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\tEigen::Matrix<double, 1, 4> jacobian;\n\t\t\t\tquaternion_constraint_jacobian(jacobian, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\ttripletListA.emplace_back(ir, ic + 3 , -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 4 , -jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 5 , -jacobian(0,2));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 6 , -jacobian(0,3));\n\n\t\t\t\ttripletListP.emplace_back(ir, ir, 1000000.0);\n\n\t\t\t\ttripletListB.emplace_back(ir, 0, delta);\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), cameras.size() * 7 + number_intrinsic_paramters);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(cameras.size() * 7 + number_intrinsic_paramters, cameras.size() * 7 + number_intrinsic_paramters);\n\t\t\tEigen::SparseMatrix<double> AtPB(cameras.size() * 7 + number_intrinsic_paramters, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == cameras.size() * 7 + number_intrinsic_paramters){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tk1 += h_x[counter++];\n\t\t\t\tk2 += h_x[counter++];\n\t\t\t\tk3 += h_x[counter++];\n\t\t\t\tp1 += h_x[counter++];\n\t\t\t\tp2 += h_x[counter++];\n\n\t\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(cameras[i].pose.inverse());\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.q0 += h_x[counter++];\n\t\t\t\t\tpose.q1 += h_x[counter++];\n\t\t\t\t\tpose.q2 += h_x[counter++];\n\t\t\t\t\tpose.q3 += h_x[counter++];\n\n\t\t\t\t\tcameras[i].pose = affine_matrix_from_pose_quaternion(pose).inverse();\n\t\t\t\t}\n\n\t\t\t\tstd::cout << \"desired intrinsic parameters:\" << std::endl;\n\t\t\t\tstd::cout << \"k1: \" << k1tmp << \" k2: \" << k2tmp << \" k3: \" << k3tmp << \" p1: \" << p1tmp << \" p2: \" << p2tmp << std::endl;\n\t\t\t\tstd::cout << \"computer intrinsic parameters:\" << std::endl;\n\t\t\t\tstd::cout << \"k1: \" << k1 << \" k2: \" << k2 << \" k3: \" << k3 << \" p1: \" << p1 << \" p2: \" << p2 << std::endl;\n\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase '1':{\n\t\t\tk1 -= 0.01;\n\t\t\tstd::cout << \"k1: \" << k1 << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '2':{\n\t\t\tk1 += 0.01;\n\t\t\tstd::cout << \"k1: \" << k1 << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '3':{\n\t\t\tk2 -= 0.01;\n\t\t\tstd::cout << \"k2: \" << k2 << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '4':{\n\t\t\tk2 += 0.01;\n\t\t\tstd::cout << \"k2: \" << k2 << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '5':{\n\t\t\tk3 -= 0.01;\n\t\t\tstd::cout << \"k3: \" << k3 << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '6':{\n\t\t\tk3 += 0.01;\n\t\t\tstd::cout << \"k3: \" << k3 << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '7':{\n\t\t\tp1 -= 0.01;\n\t\t\tstd::cout << \"p1: \" << p1 << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '8':{\n\t\t\tp1 += 0.01;\n\t\t\tstd::cout << \"p1: \" << p1 << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '9':{\n\t\t\tp2 -= 0.01;\n\t\t\tstd::cout << \"p2: \" << p2 << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '0':{\n\t\t\tp2 += 0.01;\n\t\t\tstd::cout << \"p2: \" << p2 << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'e':{\n\t\t\tshow_only_one =! show_only_one;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"t: optimize (Tait-Bryan wc)\" << std::endl;\n\tstd::cout << \"r: optimize (Rodriguez cw)\" << std::endl;\n\tstd::cout << \"q: optimize (Quaternion cw)\" << std::endl;\n\tstd::cout << \"c: add noise to cameras\" << std::endl;\n\tstd::cout << \"1: k1 -= 0.01\" << std::endl;\n\tstd::cout << \"2: k1 += 0.01\" << std::endl;\n\tstd::cout << \"3: k2 -= 0.01\" << std::endl;\n\tstd::cout << \"4: k2 += 0.01\" << std::endl;\n\tstd::cout << \"5: k3 -= 0.01\" << std::endl;\n\tstd::cout << \"6: k3 += 0.01\" << std::endl;\n\tstd::cout << \"7: p1 -= 0.01\" << std::endl;\n\tstd::cout << \"8: p1 += 0.01\" << std::endl;\n\tstd::cout << \"9: p2 -= 0.01\" << std::endl;\n\tstd::cout << \"0: p2 += 0.01\" << std::endl;\n\tstd::cout << \"e: show_only_one=!show_only_one\" << std::endl;\n}\n\n\n\n\n", "meta": {"hexsha": "48af0712cec4b4d5da9908df260aa20143ba5155", "size": 34599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/perspective_camera_intrinsic_calibration.cpp", "max_stars_repo_name": "karolmajek/observation_equations", "max_stars_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-11T13:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T22:04:00.000Z", "max_issues_repo_path": "codes/c++Examples/src/perspective_camera_intrinsic_calibration.cpp", "max_issues_repo_name": "karolmajek/observation_equations", "max_issues_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/c++Examples/src/perspective_camera_intrinsic_calibration.cpp", "max_forks_repo_name": "karolmajek/observation_equations", "max_forks_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-30T22:33:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T18:21:21.000Z", "avg_line_length": 38.6149553571, "max_line_length": 189, "alphanum_fraction": 0.6436024163, "num_tokens": 11751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.44502202716405037}}
{"text": "/*--------------------------------------------------------------------\n\nSearch for LCG multiplier using the LLL-Spectral Test!  January 2000\n\nAuthors: Karl Entacher, Karl.Entacher@fh-sbg.ac.at \n\n         Thomas Schell, Dept. of Scientific Computing, Univ. Salzburg\n\n--------------------------------------------------------------------*/\n\n\n\n/*-------------Libraries (needs Victor Shoups NTL-Lib----------------*/\n\n#include <iostream>\n\n#include <fstream>\n\n#include <time.h>\n\n#include <sys/resource.h>\n\n#include <math.h>\n\n#include <float.h>\n\n#include <NTL/ZZ.h>\n\n#include <NTL/RR.h>\n\n#include <NTL/mat_ZZ.h>\n\n#include <NTL/LLL.h>\n\n\n\nusing namespace std;\nusing namespace NTL;\n\n\n/*------------------------ Definitions ------------------------------*/\n\n\n\nZZ lambda, modul, *m_primes;\n\n\n\nstruct {\n\n  ZZ lambda;\n\n  double min_norm_x_x;\n\n} best;\n\n\n\ndouble fact[8];\n\n\n\nconst int x_xmax = 8;       /* Test for dimensions <= 8 */\n\nconst ZZ n_min=to_ZZ(1);\n\n//const ZZ n_max=to_ZZ(10000);\nconst ZZ n_max=to_ZZ(10000000);\n\n\n\n/*-----------------------------------------------------------------------\n\n   Call the function with:\n\n        lll_search [\"output-file\"] [modulus] [prim-factors of modulus-1] \n\n   Example:\n\n        lll_search \"output-file\" 2147483647 2 3 7 11 31 151 331\n\n  ----------------------------------------------------------------------*/\n\n\n\nint main(int argc, char *argv[]) {\n\n\n\n/*--------------------------    Input-Check        -----------------------*/\n\n  if (!(argc >= 2)) {\n\n    cout << \"lll_search_rnd <output-file-name> <modul> <prime factors of modul-1>\" << endl;\n\n    exit(0);\n\n  }\n\n\n\n/*--------- reads the input-parameters: \"file\" modulus primefactors ------*/\n\n  ofstream out_file(argv[1], ios::out);\n\n  modul = to_ZZ(argv[2]);\n\n  if (argc-5 > 0) {\n\n    m_primes = new ZZ [argc-3];\n\n    for (int i = 3; i < argc; i++)\n\n      m_primes[i-3] = to_ZZ(argv[i]);\n\n  }\n\n\n\n/*------------- output of modulus and factors of modulus-1 ---------------*/\n\n  out_file << modul;\n\n  for (int i = 0; i < argc-3; i++)\n\n    out_file << \" \" << m_primes[i];\n\n  out_file << endl;\n\n\n\n/*-----------------Search for the first primitiv root and its output-------*/\n\n  int is_primitive_root;\n\n  ZZ pr = to_ZZ(1);\n\n  do {\n\n    int k = 0;\n\n    pr++;\n\n    while (k < argc-3 && (is_primitive_root = (PowerMod(pr, (modul-1) / m_primes[k++], modul) != 1)));\n\n  } while (!is_primitive_root);\n\n  cout << \"primitive root \" << pr << endl;\n\n\n\n/*------------- Constants for the normalized Spectral Test   -----------------*/\n\n  fact[0] = 0.0;                                // intentionally left uninitialized -> not used\n\n  fact[1] = to_double(to_RR(1.0) / pow(to_RR(4.0/3.0), to_RR(1.0/4.0)) / pow(to_RR(modul), to_RR(1.0/2.0)));\n\n  fact[2] = to_double(to_RR(1.0) / pow(to_RR(2.0), to_RR(1.0/6.0)) / pow(to_RR(modul), to_RR(1.0/3.0)));\n\n  fact[3] = to_double(to_RR(1.0) / pow(to_RR(2.0), to_RR(1.0/4.0)) / pow(to_RR(modul), to_RR(1.0/4.0)));\n\n  fact[4] = to_double(to_RR(1.0) / pow(to_RR(2.0), to_RR(3.0/10.0)) / pow(to_RR(modul), to_RR(1.0/5.0)));\n\n  fact[5] = to_double(to_RR(1.0) / pow(to_RR(64.0/3.0), to_RR(1.0/12.0)) / pow(to_RR(modul), to_RR(1.0/6.0)));\n\n  fact[6] = to_double(to_RR(1.0) / pow(to_RR(2.0), to_RR(3.0/7.0)) / pow(to_RR(modul), to_RR(1.0/7.0)));\n\n  fact[7] = to_double(to_RR(1.0) / pow(to_RR(2.0), to_RR(1.0/2.0)) / pow(to_RR(modul), to_RR(1.0/8.0)));\n\n\n\n/*------------Search, Matrix (Basis) Input, LLL und Output -------------*/\n\n  best.lambda = to_ZZ(0);\n\n  best.min_norm_x_x = 0.0;\n\n  ZZ t_h = to_ZZ(10);\n\n  struct rusage cur_ru;\n\n  for (ZZ n = n_min; n <= n_max; n++) {\n\n    double min_norm_x_x = 0.0;\n\n    if (GCD(n, modul - 1) == 1) {\n\n      lambda = PowerMod(pr, n, modul);\n\n      mat_ZZ x;\n\n      x.SetDims(x_xmax, x_xmax);\n\n      min_norm_x_x = 1.0;\n\n      for (int j = 2; j <= x_xmax; j++) {\n\n    x.SetDims(j,j);\n\n    x[0][0] = modul;     // first index = rows, second index = columns\n\n    for (int i = 1; i < j; i++)          // fill in the 1s\n\n      x[i][i] = 1;\n\n    for (int i = 1; i < j; i++)\n\n      x[i][0] =-(power(lambda, i)); \n\n    ZZ det, rg;\n\n    rg = LLL(det, x, 0);\n\n    double min_x_x = to_double(x[0] * x[0]);\n\n    for (int i = 1; i < j; i++) {\n\n      double x_x = to_double(x[i] * x[i]);\n\n      if (min_x_x > x_x)\n\n        min_x_x = x_x;\n\n    }\n\n    double norm_x_x = fact[j-1] * sqrt(min_x_x);\n\n    if (min_norm_x_x > norm_x_x)\n\n      min_norm_x_x = norm_x_x;\n\n      }\n\n      if (min_norm_x_x > best.min_norm_x_x) {\n\n    best.min_norm_x_x = min_norm_x_x;\n\n    best.lambda = lambda;\n\n    getrusage(RUSAGE_SELF, &cur_ru);\n\n    out_file << \"time\\t\" << cur_ru.ru_utime.tv_sec << \"\\tn\\t\" << n << \"\\tl\\t\" << lambda << \"\\t\" << min_norm_x_x << endl;\n\n      }\n\n    }\n\n    ZZ n_ = n - n_min;\n\n    if (n_ >= t_h) {\n\n      getrusage(RUSAGE_SELF, &cur_ru);\n\n      cout << n_ << \"\\t\" << cur_ru.ru_utime.tv_sec << endl;\n\n      t_h *= 10;\n\n    }\n\n  }\n\n  getrusage(RUSAGE_SELF, &cur_ru);\n\n  cout << \"total time elapsed\\t\" << cur_ru.ru_utime.tv_sec << endl;\n\n  out_file << \"time\\t\" << cur_ru.ru_utime.tv_sec << \"\\tl\\t\" << best.lambda << \"\\t\" << best.min_norm_x_x << endl;\n\n  out_file.close();\n\n}\n", "meta": {"hexsha": "273516ddab36bfd179d7adafc980a986295c4597", "size": 5104, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spectraltest/lll_search.cpp", "max_stars_repo_name": "dcurrie/minstd64e", "max_stars_repo_head_hexsha": "4394167cae18052e84bbcb3f20df28508a8ecf26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spectraltest/lll_search.cpp", "max_issues_repo_name": "dcurrie/minstd64e", "max_issues_repo_head_hexsha": "4394167cae18052e84bbcb3f20df28508a8ecf26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spectraltest/lll_search.cpp", "max_forks_repo_name": "dcurrie/minstd64e", "max_forks_repo_head_hexsha": "4394167cae18052e84bbcb3f20df28508a8ecf26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8339483395, "max_line_length": 120, "alphanum_fraction": 0.5078369906, "num_tokens": 1690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.44502202716405037}}
{"text": "// Run like this\r\n//./prediction --dataL competition/S1a/dataset6_training.csv --dataT competition/S1b/dataset6_testing.csv --sigma=1.14683 --length=0.0825932 --nu=0.600677 --tau=3.49e-14 --ldl\r\n// Developed by Alexander Litvinenko (RWTH Aachen) and Ronald Kriemann (MIS MPG Leipzig)\r\n// Based on the HLIBPro library (v. 2.9) www.hlibpro.com\r\n// No warranties.\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <string>\r\n\r\n#include <boost/format.hpp>\r\n#include <boost/program_options.hpp>\r\n\r\n#include <gsl/gsl_multimin.h>\r\n\r\n#include \"hlib.hh\"\r\n\r\nusing namespace std;\r\nusing boost::format;\r\nusing namespace HLIB;\r\nusing namespace boost::program_options;\r\nusing  real_t    = HLIB::real;\r\n\r\nenum {\r\n    IDX_SIGMA  = 0,\r\n    IDX_LENGTH = 1,\r\n    IDX_NU     = 2,\r\n    IDX_TAU    = 3\r\n};\r\n\r\n// global options\r\nint        nmin      = CFG::Cluster::nmin;\r\ndouble     eps       = 1e-6;\r\ndouble     fac_eps   = 1e-6;\r\ndouble     shift     = 1e-7;\r\nbool       use_ldl   = false;\r\n\r\n//\r\n// read dataset from file\r\n//\r\nvoid\r\nread_data ( const std::string &       datafile,\r\n            std::vector< T2Point > &  vertices,\r\n            BLAS::Vector< double > &  Z_data_ )\r\n{\r\n    std::ifstream  in( datafile );\r\n    \r\n    if ( ! in ) // error\r\n        exit( 1 );\r\n\r\n    size_t  N_vtx = 0;\r\n    \r\n    #if 1\r\n\r\n    std::string  line;\r\n    \r\n    std::getline( in, line );\r\n\r\n    if ( line == \"x,y,values\" )\r\n    {\r\n        std::list< T2Point >  pos;\r\n        std::list< double >   vals;\r\n\r\n        while ( std::getline( in, line ) )\r\n        {\r\n            auto    parts = split( line, \",\" );\r\n            double  x = atof( parts[0].c_str() );\r\n            double  y = atof( parts[1].c_str() );\r\n            double  v = atof( parts[2].c_str() );\r\n            \r\n            pos.push_back( T2Point( x, y ) );\r\n            vals.push_back( v );\r\n        }// while\r\n\r\n        N_vtx = pos.size();\r\n\r\n        std::cout << \"learning dataset\" << std::endl;\r\n        std::cout << N_vtx << std::endl;\r\n        \r\n        vertices.resize( N_vtx );\r\n        Z_data_ = BLAS::Vector< double >( N_vtx );\r\n\r\n        int  i = 0;\r\n\r\n        for ( auto  p : pos )\r\n            vertices[ i++ ] = p;\r\n\r\n        i = 0;\r\n        int j=0;\r\n        for ( auto  v : vals )\r\n        {\r\n          Z_data_( i++ ) = v;\r\n        }\r\n         \r\n         \r\n   }// if\r\n    if ( line == \"x,y,ignor\" )\r\n    {\r\n        std::list< T2Point >  pos;\r\n        std::list< double >   vals;\r\n\r\n        while ( std::getline( in, line ) )\r\n        {\r\n            auto    parts = split( line, \",\" );\r\n            double  x = atof( parts[0].c_str() );\r\n            double  y = atof( parts[1].c_str() );\r\n            double  v = atof( parts[2].c_str() );\r\n            \r\n            pos.push_back( T2Point( x, y ) );\r\n           // vals.push_back( v );\r\n        }// while\r\n\r\n        N_vtx = pos.size();\r\n\r\n        std::cout << \"learning dataset\" << std::endl;\r\n        std::cout << N_vtx << std::endl;\r\n        \r\n        vertices.resize( N_vtx );\r\n        Z_data_ = BLAS::Vector< double >( N_vtx );\r\n\r\n        int  i = 0;\r\n\r\n        for ( auto  p : pos )\r\n            vertices[ i++ ] = p;\r\n\r\n        i = 0;\r\n        \r\n        for ( auto  v : vals )\r\n           Z_data_( i++ ) = 0.0;\r\n    }// if\r\n   \r\n    if ( line == \"x,y\" )\r\n    {\r\n        std::list< T2Point >  pos;\r\n\r\n        while ( std::getline( in, line ) )\r\n        {\r\n            auto    parts = split( line, \",\" );\r\n            double  x = atof( parts[0].c_str() );\r\n            double  y = atof( parts[1].c_str() );\r\n            \r\n            pos.push_back( T2Point( x, y ) );\r\n        }// while\r\n\r\n        N_vtx = pos.size();\r\n        std::cout << \"testing dataset\" << std::endl;\r\n        std::cout << N_vtx << std::endl;\r\n        \r\n        vertices.resize( N_vtx );\r\n\r\n        int  i = 0;\r\n\r\n        for ( auto  p : pos )\r\n            vertices[ i++ ] = p;\r\n    }// if\r\n    //else\r\n    //{\r\n    //    std::cout << \"you should not be here\" << std::endl;\r\n    //    HERROR( ERR_NOT_IMPL, \"\", \"\" );\r\n    //}\r\n    \r\n    #else\r\n    \r\n    in >> N_vtx;\r\n\r\n    std::cout << \"reading \" << N_vtx << \" datapoints\" << std::endl;\r\n    \r\n    vertices.resize( N_vtx );\r\n    Z_data_ = BLAS::Vector< double >( N_vtx );\r\n        \r\n    for ( idx_t  i = 0; i < idx_t(N_vtx); ++i )\r\n    {\r\n        int     index = i;\r\n        double  x, y, z;\r\n        // double  v     = 0.0;\r\n        \r\n        in >> index >> x >> y >> z;\r\n        // in >> index >> x >> y >> z >> v;\r\n\r\n        vertices[ index ] = T2Point( x, y );\r\n        //Z_data( index )   = v;\r\n    }// for\r\n\r\n    #endif\r\n    \r\n    //\r\n    // for visualization of data, export 2D points with v value in csv file\r\n    //\r\n\r\n    // std::ofstream  out( \"data.csv\" );\r\n\r\n    // out << \"x,y,z,v\" << std::endl;\r\n    // out << \"x,y,z\" << std::endl;\r\n    \r\n    //for ( uint  i = 0; i < N_vtx; ++i )\r\n    //   out << vertices[i].x() << \",\" << vertices[i].y() << \",0\" << std::endl;\r\n//      out << vertices[i].x() << \",\" << vertices[i].y() << \",0,\" << Z_data( i ) << std::endl;\r\n}\r\n\r\n//\r\n// define PredictionProblem to forecast unknown values in new locations\r\n//\r\nstruct PredictionProblem\r\n{\r\n    std::vector< T2Point >                vertices;\r\n    std::vector< T2Point >                vertices_predict;\r\n    std::unique_ptr< TCoordinate >        coord;\r\n    std::unique_ptr< TCoordinate >        coord_predict;\r\n    std::unique_ptr< TClusterTree >       ct;\r\n    std::unique_ptr< TClusterTree >       ct_predict;\r\n    std::unique_ptr< TBlockClusterTree >  bct;\r\n    std::unique_ptr< TBlockClusterTree >  bct_predict;\r\n    std::unique_ptr< TVector >            Z;\r\n    std::unique_ptr< TVector >            Z_predict;\r\n\r\n    PredictionProblem ( const std::string &  datafile, const std::string &  datafile_predict )\r\n    {\r\n        init( datafile, datafile_predict );\r\n    }\r\n\r\n    void\r\n    init ( const std::string &  datafile, const std::string &  datafile_predict )\r\n    {\r\n        BLAS::Vector< double >  Z_data;\r\n        BLAS::Vector< double >  Z_data_predict;\r\n\r\n        read_data( datafile, vertices, Z_data );\r\n        read_data( datafile_predict, vertices_predict, Z_data_predict );\r\n\r\n        std::cout << \"both datasets are succesfully read\" << std::endl;\r\n        coord = std::make_unique< TCoordinate >( vertices );\r\n        coord_predict = std::make_unique< TCoordinate >( vertices_predict );\r\n      \r\n        TAutoBSPPartStrat  part_strat;\r\n        TBSPCTBuilder      ct_builder( & part_strat, nmin );\r\n    \r\n        ct = ct_builder.build( coord.get() );\r\n        \r\n        //print_vtk( & coord, \"ct_coord\" );\r\n        ct_predict = ct_builder.build( coord_predict.get() );\r\n        //print_vtk( & coord_predict, \"ct_coord_predict\" );\r\n        \r\n    \r\n        TStdGeomAdmCond    adm_cond( 2.0, use_min_diam );\r\n        TBCBuilder         bct_builder;\r\n   \r\n        bct = bct_builder.build( ct.get(), ct.get(), & adm_cond );\r\n        bct_predict = bct_builder.build( ct_predict.get(), ct.get(), & adm_cond );\r\n  \r\n        Z   = std::make_unique< TScalarVector >( *ct->root(), std::move( Z_data ) );\r\n        Z_predict   = std::make_unique< TScalarVector >( *ct_predict->root(), std::move( Z_data_predict ) );\r\n        ct->perm_e2i()->permute( Z.get() );\r\n    }\r\n    \r\n    //BLAS::Vector< double > \r\n    std::unique_ptr< TVector > \r\n    eval ( const double  sigma,\r\n           const double  length,\r\n           const double  nu,\r\n           const double tau )\r\n    {\r\n  \r\n        TMaternCovCoeffFn< T2Point >  matern_coefffn( sigma, length, nu,  vertices );\r\n        \r\n        TMaternCovCoeffFn< T2Point >  matern_coefffn_predict( sigma, length, nu, vertices_predict, vertices );\r\n        TPermCoeffFn< double >        coefffn( & matern_coefffn, ct->perm_i2e(), ct->perm_i2e() );\r\n        TPermCoeffFn< double >        coefffn_predict( & matern_coefffn_predict, ct_predict->perm_i2e(), ct->perm_i2e() );\r\n  \r\n        TACAPlus< double >            aca( & coefffn );\r\n        TACAPlus< double >            aca_predict( & coefffn_predict );\r\n        auto                          acc = fixed_prec( eps );\r\n        TDenseMatBuilder< double >    h_builder( & coefffn, & aca );\r\n        TDenseMatBuilder< double >    h_builder_predict( & coefffn_predict, & aca_predict );\r\n    \r\n        auto                          C        = h_builder.build( bct.get(), acc );\r\n        //TPSMatrixVis  mvis;\r\n        \r\n        //mvis.svd(true).print( C.get(), \"myC\" ); Output matrix C as a .eps file \r\n        \r\n\r\n       \r\n        auto   C_predict= h_builder_predict.build( bct_predict.get(), unsymmetric, acc ); //A_21 - rectangular matrix\r\n        \r\n        if ( shift != 0.0 )\r\n            add_identity( C.get(), tau*tau );\r\n  \r\n        auto                          fac_acc  = fixed_prec( fac_eps );\r\n        auto                          C_fac    = C->copy();\r\n        auto                          fac_opts = fac_options_t{ point_wise, CFG::Arith::storage_type, false };\r\n    \r\n        if ( use_ldl )\r\n        {\r\n            ldl( C_fac.get(), fac_acc, fac_opts );\r\n            //std::cout <<  \"LDL is used \" << std::endl;\r\n        }\r\n        else\r\n        {\r\n            chol( C_fac.get(), fac_acc ); \r\n            //std::cout <<  \"Cholesky is used \" << std::endl;\r\n        }\r\n        //std::cout << \"    |С|_F             = \" << norm_F( C.get() ) << std::endl;\r\n        //std::cout << \"    |С|_2             = \" << norm_2( C.get() ) << std::endl;\r\n        //std::cout << \"    |С_fac|_F             = \" << norm_F( C_fac.get() ) << std::endl;\r\n        //std::cout << \"    |С_fac|_2             = \" << norm_2( C_fac.get() ) << std::endl;\r\n        \r\n        std::unique_ptr< TFacInvMatrix >   C_inv;\r\n\r\n        if ( use_ldl )\r\n        {\r\n            C_inv = std::make_unique< TLDLInvMatrix >( C_fac.get(), symmetric, point_wise );\r\n        }\r\n        else\r\n        {\r\n            C_inv = std::make_unique< TLLInvMatrix >( C_fac.get(), symmetric );\r\n        }\r\n        //std::cout << \"    |С_inv|_2             = \" << norm_2( C_inv.get() ) << std::endl;\r\n        \r\n        const size_t                  N     = vertices.size();\r\n        \r\n        TStopCriterion                sstop( 350, 1e-16, 0.0 );\r\n        TCG                           solver( sstop );\r\n        auto                          sol = C->row_vector();\r\n        \r\n        auto                          Z_predict = C_predict->row_vector();\r\n        \r\n        FILE* f1; \r\n  \r\n        \r\n        solver.solve( C.get(), sol.get(), Z.get(), C_inv.get() );\r\n        \r\n    \r\n        //DBG::write( C_predict.get(), \"A12.mat\", \"A12\" );\r\n        //std::cout << \"  ||invC_Z|| = \" << sol->norm2() << std::endl;\r\n        mul_vec( real_t(1), C_predict.get(), sol.get(), real_t(0), Z_predict.get(), apply_normal );\r\n        \r\n\r\n        //std::cout << \"  ||Z_predict|| = \" << Z_predict->norm2() << std::endl;\r\n        //C_predict->mul_vec( 1.0, sol.get(), 0.0, Z_predict.get(), apply_normal );\r\n        \r\n\r\n        ct_predict->perm_i2e()->permute( Z_predict.get() );\r\n        //TMatlabVectorIO  vio;\r\n        //vio.write( Z_predict,  \"x.mat\", \"x\" );\r\n\r\n        f1 = fopen(\"111prediction.txt\", \"w\");\r\n        for ( size_t  i = 0; i < Z_predict->size(); i++ )\r\n          fprintf(f1,\" %.6f, %.6f, %.6f\\n\",   vertices_predict[i].x(),  vertices_predict[i].y(), Z_predict->entry(i));\r\n        fclose(f1);\r\n        return std::move( Z_predict );\r\n    }\r\n};\r\n\r\n//\r\n// wrapper from GSL to LogLikeliHoodProblem\r\n//\r\n/*double\r\n  eval_logli ( const gsl_vector *  param,\r\n  void *              data )\r\n  {\r\n  double sigma  = gsl_vector_get( param, IDX_SIGMA );\r\n  double length = gsl_vector_get( param, IDX_LENGTH );\r\n  double nu     = gsl_vector_get( param, IDX_NU );\r\n  double tau    = gsl_vector_get( param, IDX_TAU );\r\n\r\n  LogLikeliHoodProblem *  problem = static_cast< LogLikeliHoodProblem * >( data );\r\n\r\n  return - problem->eval( sigma, length, nu, tau );\r\n  }\r\n*/\r\n//\r\n// optimization function using GSL\r\n//\r\n\r\n//\r\n// main function\r\n//\r\nint\r\nmain ( int      argc,\r\n       char **  argv )\r\n{\r\n    \r\n    //CFG::set_verbosity( 3 );\r\n    INIT();\r\n    \r\n    //std::string  datafile = \"datafile.txt\";\r\n    //std::string  datafile_predict = \"datafile_predict.txt\";\r\n    std::string  datafile = \"LearningSet.txt\";\r\n    std::string  datafile_predict = \"TestingSet.txt\";\r\n\r\n    double  sigma  = 2.7779; //take these values from previous experiments (Part 1a)\r\n    double  length = 0.07; \r\n    double  nu     = 1.0365;\r\n    double  tau    = 4.2045e-8;\r\n    \r\n    //\r\n    // define command line options\r\n    //\r\n\r\n    options_description             all_opts;\r\n    options_description             vis_opts( \"usage: loglikelihood [options] datafile\\n  where options include\" );\r\n    options_description             hid_opts( \"Hidden options\" );\r\n    positional_options_description  pos_opts;\r\n    variables_map                   vm;\r\n\r\n    // standard options\r\n    vis_opts.add_options()\r\n        ( \"help,h\",                       \": print this help text\" )\r\n        ( \"threads,t\",   value<int>(),    \": number of parallel threads\" )\r\n        ( \"verbosity,v\", value<int>(),    \": verbosity level\" )\r\n        ( \"nmin\",        value<int>(),    \": set minimal cluster size\" )\r\n        ( \"eps,e\",       value<double>(), \": set H accuracy\" )\r\n        ( \"epslu\",       value<double>(), \": set only H factorization accuracy\" )\r\n        ( \"shift\",       value<double>(), \": regularization parameter\" )\r\n        ( \"ldl\",                          \": use LDL factorization\" )\r\n        ( \"sigma\",       value<double>(), \": sigma parameter\" )\r\n        ( \"nu\",          value<double>(), \": nu parameter\" )\r\n        ( \"length\",      value<double>(), \": length parameter\" )\r\n        ( \"tau\",         value<double>(), \": tau paramater\" )\r\n        ;\r\n    \r\n    hid_opts.add_options()\r\n        ( \"dataL\",        value<std::string>(), \": datafile defining learning problem\" )\r\n        ( \"dataT\",        value<std::string>(), \": datafile defining testing problem\" )\r\n        ;\r\n\r\n    // options for command line parsing\r\n    all_opts.add( vis_opts ).add( hid_opts );\r\n\r\n    // all \"non-option\" arguments should be \"--data\" arguments\r\n    pos_opts.add( \"dataL\", -1 );\r\n    pos_opts.add( \"dataT\", -1 );\r\n\r\n    //\r\n    // parse command line options\r\n    //\r\n\r\n    try\r\n    {\r\n        store( command_line_parser( argc, argv ).options( all_opts ).positional( pos_opts ).run(), vm );\r\n        notify( vm );\r\n    }// try\r\n    catch ( required_option &  e )\r\n    {\r\n        std::cout << e.get_option_name() << \" requires an argument, try \\\"-h\\\"\" << std::endl;\r\n        exit( 1 );\r\n    }// catch\r\n    catch ( unknown_option &  e )\r\n    {\r\n        std::cout << e.what() << \", try \\\"-h\\\"\" << std::endl;\r\n        exit( 1 );\r\n    }// catch\r\n\r\n    //\r\n    // eval command line options\r\n    //\r\n\r\n    if ( vm.count( \"help\") )\r\n    {\r\n        std::cout << vis_opts << std::endl;\r\n        exit( 1 );\r\n    }// if\r\n\r\n    if ( vm.count( \"nmin\"      ) ) nmin     = vm[\"nmin\"].as<int>();\r\n    if ( vm.count( \"eps\"       ) ) eps      = vm[\"eps\"].as<double>();\r\n    if ( vm.count( \"epslu\"     ) ) fac_eps  = vm[\"epslu\"].as<double>();\r\n    if ( vm.count( \"shift\"     ) ) shift    = vm[\"shift\"].as<double>();\r\n    if ( vm.count( \"threads\"   ) ) CFG::set_nthreads( vm[\"threads\"].as<int>() );\r\n    if ( vm.count( \"verbosity\" ) ) CFG::set_verbosity( vm[\"verbosity\"].as<int>() );\r\n    if ( vm.count( \"ldl\"       ) ) use_ldl  = true;\r\n    if ( vm.count( \"sigma\"     ) ) sigma    = vm[\"sigma\"].as<double>();\r\n    if ( vm.count( \"nu\"        ) ) nu       = vm[\"nu\"].as<double>();\r\n    if ( vm.count( \"length\"    ) ) length   = vm[\"length\"].as<double>();\r\n    if ( vm.count( \"tau\"       ) ) tau      = vm[\"tau\"].as<double>();\r\n\r\n    // default to general eps\r\n    if ( fac_eps == -1 )\r\n        fac_eps = eps;\r\n    \r\n    if ( vm.count( \"dataL\" ) )\r\n        datafile = vm[\"dataL\"].as<std::string>();\r\n    else\r\n    {\r\n        std::cout << \"usage: loglikelihood [options] datafile\" << std::endl;\r\n        exit( 1 );\r\n    }// if\r\n\r\n    if ( vm.count( \"dataT\" ) )\r\n        datafile_predict = vm[\"dataT\"].as<std::string>();\r\n    else\r\n    {\r\n        std::cout << \"usage: loglikelihood [options] datafile\" << std::endl;\r\n        exit( 1 );\r\n    }// if\r\n\r\n   \r\n    std::cout << \"parameters : \" << \" σ = \" << sigma << \", ℓ = \" << length << \", ν = \" << nu << \", τ = \" << tau << std::endl;\r\n    \r\n\r\n    PredictionProblem  problem( datafile, datafile_predict );\r\n    problem.eval( sigma, length, nu, tau);\r\n\r\n    DONE();\r\n}\r\n", "meta": {"hexsha": "ff4ea5b20f5e9a81f2b2ed5f95bb06ab3e121c81", "size": 16408, "ext": "cc", "lang": "C++", "max_stars_repo_path": "prediction.cc", "max_stars_repo_name": "litvinen/large_random_fields", "max_stars_repo_head_hexsha": "c6eb60ee53171d296c02dd73d26476e072360f6c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-03T05:25:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T23:04:12.000Z", "max_issues_repo_path": "prediction.cc", "max_issues_repo_name": "litvinen/large_random_fields", "max_issues_repo_head_hexsha": "c6eb60ee53171d296c02dd73d26476e072360f6c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "prediction.cc", "max_forks_repo_name": "litvinen/large_random_fields", "max_forks_repo_head_hexsha": "c6eb60ee53171d296c02dd73d26476e072360f6c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T11:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T11:27:29.000Z", "avg_line_length": 32.5555555556, "max_line_length": 176, "alphanum_fraction": 0.4853729888, "num_tokens": 4423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4450220204302907}}
{"text": "\n\n\n\n#include <NTL/lzz_pEX.h>\n#include <NTL/vec_vec_lzz_p.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\n\nconst zz_pEX& zz_pEX::zero()\n{\n   static zz_pEX z;\n   return z;\n}\n\n\nistream& operator>>(istream& s, zz_pEX& x)\n{\n   s >> x.rep;\n   x.normalize();\n   return s;\n}\n\nostream& operator<<(ostream& s, const zz_pEX& a)\n{\n   return s << a.rep;\n}\n\n\nvoid zz_pEX::normalize()\n{\n   long n;\n   const zz_pE* p;\n\n   n = rep.length();\n   if (n == 0) return;\n   p = rep.elts() + n;\n   while (n > 0 && IsZero(*--p)) {\n      n--;\n   }\n   rep.SetLength(n);\n}\n\n\nlong IsZero(const zz_pEX& a)\n{\n   return a.rep.length() == 0;\n}\n\n\nlong IsOne(const zz_pEX& a)\n{\n    return a.rep.length() == 1 && IsOne(a.rep[0]);\n}\n\nlong operator==(const zz_pEX& a, long b)\n{\n   if (b == 0)\n      return IsZero(a);\n\n   if (b == 1)\n      return IsOne(a);\n\n   long da = deg(a);\n\n   if (da > 0) return 0;\n\n   NTL_zz_pRegister(bb);\n   bb = b;\n\n   if (da < 0)\n      return IsZero(bb);\n\n   return a.rep[0] == bb;\n}\n\nlong operator==(const zz_pEX& a, const zz_p& b)\n{\n   if (IsZero(b))\n      return IsZero(a);\n\n   long da = deg(a);\n\n   if (da != 0)\n      return 0;\n\n   return a.rep[0] == b;\n}\n\nlong operator==(const zz_pEX& a, const zz_pE& b)\n{\n   if (IsZero(b))\n      return IsZero(a);\n\n   long da = deg(a);\n\n   if (da != 0)\n      return 0;\n\n   return a.rep[0] == b;\n}\n\n\n\n\n\nvoid SetCoeff(zz_pEX& x, long i, const zz_pE& a)\n{\n   long j, m;\n\n   if (i < 0) \n      Error(\"SetCoeff: negative index\");\n\n   if (NTL_OVERFLOW(i, 1, 0))\n      Error(\"overflow in SetCoeff\");\n\n   m = deg(x);\n\n   if (i > m && IsZero(a)) return; \n\n   if (i > m) {\n      /* careful: a may alias a coefficient of x */\n\n      long alloc = x.rep.allocated();\n\n      if (alloc > 0 && i >= alloc) {\n         zz_pE aa = a;\n         x.rep.SetLength(i+1);\n         x.rep[i] = aa;\n      }\n      else {\n         x.rep.SetLength(i+1);\n         x.rep[i] = a;\n      }\n\n      for (j = m+1; j < i; j++)\n         clear(x.rep[j]);\n   }\n   else\n      x.rep[i] = a;\n\n   x.normalize();\n}\n\n\nvoid SetCoeff(zz_pEX& x, long i, const zz_p& aa)\n{\n   long j, m;\n\n   if (i < 0)\n      Error(\"SetCoeff: negative index\");\n\n   if (NTL_OVERFLOW(i, 1, 0))\n      Error(\"overflow in SetCoeff\");\n\n   NTL_zz_pRegister(a);  // watch out for aliases!\n   a = aa;\n\n   m = deg(x);\n\n   if (i > m && IsZero(a)) return; \n\n   if (i > m) {\n      x.rep.SetLength(i+1);\n      for (j = m+1; j < i; j++)\n         clear(x.rep[j]);\n   }\n   x.rep[i] = a;\n   x.normalize();\n}\n\nvoid SetCoeff(zz_pEX& x, long i, long a)\n{\n   if (a == 1)\n      SetCoeff(x, i);\n   else {\n      NTL_zz_pRegister(T);\n      T = a;\n      SetCoeff(x, i, T);\n   }\n}\n\n\n\nvoid SetCoeff(zz_pEX& x, long i)\n{\n   long j, m;\n\n   if (i < 0) \n      Error(\"coefficient index out of range\");\n\n   if (NTL_OVERFLOW(i, 1, 0))\n      Error(\"overflow in SetCoeff\");\n\n   m = deg(x);\n\n   if (i > m) {\n      x.rep.SetLength(i+1);\n      for (j = m+1; j < i; j++)\n         clear(x.rep[j]);\n   }\n   set(x.rep[i]);\n   x.normalize();\n}\n\n\nvoid SetX(zz_pEX& x)\n{\n   clear(x);\n   SetCoeff(x, 1);\n}\n\n\nlong IsX(const zz_pEX& a)\n{\n   return deg(a) == 1 && IsOne(LeadCoeff(a)) && IsZero(ConstTerm(a));\n}\n      \n      \n\nconst zz_pE& coeff(const zz_pEX& a, long i)\n{\n   if (i < 0 || i > deg(a))\n      return zz_pE::zero();\n   else\n      return a.rep[i];\n}\n\n\nconst zz_pE& LeadCoeff(const zz_pEX& a)\n{\n   if (IsZero(a))\n      return zz_pE::zero();\n   else\n      return a.rep[deg(a)];\n}\n\nconst zz_pE& ConstTerm(const zz_pEX& a)\n{\n   if (IsZero(a))\n      return zz_pE::zero();\n   else\n      return a.rep[0];\n}\n\n\n\nvoid conv(zz_pEX& x, const zz_pE& a)\n{\n   if (IsZero(a))\n      x.rep.SetLength(0);\n   else {\n      x.rep.SetLength(1);\n      x.rep[0] = a;\n   }\n}\n\nvoid conv(zz_pEX& x, long a)\n{\n   if (a == 0) \n      clear(x);\n   else if (a == 1)\n      set(x);\n   else {\n      NTL_zz_pRegister(T);\n      T = a;\n      conv(x, T);\n   }\n}\n\nvoid conv(zz_pEX& x, const ZZ& a)\n{\n   NTL_zz_pRegister(T);\n   conv(T, a);\n   conv(x, T);\n}\n\nvoid conv(zz_pEX& x, const zz_p& a)\n{\n   if (IsZero(a)) \n      clear(x);\n   else if (IsOne(a))\n      set(x);\n   else {\n      x.rep.SetLength(1);\n      conv(x.rep[0], a);\n      x.normalize();\n   }\n}\n\nvoid conv(zz_pEX& x, const zz_pX& aa)\n{\n   zz_pX a = aa; // in case a aliases the rep of a coefficient of x\n\n   long n = deg(a)+1;\n   long i;\n\n   x.rep.SetLength(n);\n   for (i = 0; i < n; i++)\n      conv(x.rep[i], coeff(a, i));\n}\n\n\nvoid conv(zz_pEX& x, const vec_zz_pE& a)\n{\n   x.rep = a;\n   x.normalize();\n}\n\n\nvoid add(zz_pEX& x, const zz_pEX& a, const zz_pEX& b)\n{\n   long da = deg(a);\n   long db = deg(b);\n   long minab = min(da, db);\n   long maxab = max(da, db);\n   x.rep.SetLength(maxab+1);\n\n   long i;\n   const zz_pE *ap, *bp; \n   zz_pE* xp;\n\n   for (i = minab+1, ap = a.rep.elts(), bp = b.rep.elts(), xp = x.rep.elts();\n        i; i--, ap++, bp++, xp++)\n      add(*xp, (*ap), (*bp));\n\n   if (da > minab && &x != &a)\n      for (i = da-minab; i; i--, xp++, ap++)\n         *xp = *ap;\n   else if (db > minab && &x != &b)\n      for (i = db-minab; i; i--, xp++, bp++)\n         *xp = *bp;\n   else\n      x.normalize();\n}\n\n\nvoid add(zz_pEX& x, const zz_pEX& a, const zz_pE& b)\n{\n   long n = a.rep.length();\n   if (n == 0) {\n      conv(x, b);\n   }\n   else if (&x == &a) {\n      add(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else if (x.rep.MaxLength() == 0) {\n      x = a;\n      add(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else {\n      // ugly...b could alias a coeff of x\n\n      zz_pE *xp = x.rep.elts();\n      add(xp[0], a.rep[0], b);\n      x.rep.SetLength(n);\n      xp = x.rep.elts();\n      const zz_pE *ap = a.rep.elts();\n      long i;\n      for (i = 1; i < n; i++)\n         xp[i] = ap[i];\n      x.normalize();\n   }\n}\n\nvoid add(zz_pEX& x, const zz_pEX& a, const zz_p& b)\n{\n   long n = a.rep.length();\n   if (n == 0) {\n      conv(x, b);\n   }\n   else if (&x == &a) {\n      add(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else if (x.rep.MaxLength() == 0) {\n      x = a;\n      add(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else {\n      // ugly...b could alias a coeff of x\n\n      zz_pE *xp = x.rep.elts();\n      add(xp[0], a.rep[0], b);\n      x.rep.SetLength(n);\n      xp = x.rep.elts();\n      const zz_pE *ap = a.rep.elts();\n      long i;\n      for (i = 1; i < n; i++)\n         xp[i] = ap[i];\n      x.normalize();\n   }\n}\n\n\nvoid add(zz_pEX& x, const zz_pEX& a, long b)\n{\n   if (a.rep.length() == 0) {\n      conv(x, b);\n   }\n   else {\n      if (&x != &a) x = a;\n      add(x.rep[0], x.rep[0], b);\n      x.normalize();\n   }\n}\n\n\nvoid sub(zz_pEX& x, const zz_pEX& a, const zz_pEX& b)\n{\n   long da = deg(a);\n   long db = deg(b);\n   long minab = min(da, db);\n   long maxab = max(da, db);\n   x.rep.SetLength(maxab+1);\n\n   long i;\n   const zz_pE *ap, *bp; \n   zz_pE* xp;\n\n   for (i = minab+1, ap = a.rep.elts(), bp = b.rep.elts(), xp = x.rep.elts();\n        i; i--, ap++, bp++, xp++)\n      sub(*xp, (*ap), (*bp));\n\n   if (da > minab && &x != &a)\n      for (i = da-minab; i; i--, xp++, ap++)\n         *xp = *ap;\n   else if (db > minab)\n      for (i = db-minab; i; i--, xp++, bp++)\n         negate(*xp, *bp);\n   else\n      x.normalize();\n}\n\n\nvoid sub(zz_pEX& x, const zz_pEX& a, const zz_pE& b)\n{\n   long n = a.rep.length();\n   if (n == 0) {\n      conv(x, b);\n      negate(x, x);\n   }\n   else if (&x == &a) {\n      sub(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else if (x.rep.MaxLength() == 0) {\n      x = a;\n      sub(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else {\n      // ugly...b could alias a coeff of x\n\n      zz_pE *xp = x.rep.elts();\n      sub(xp[0], a.rep[0], b);\n      x.rep.SetLength(n);\n      xp = x.rep.elts();\n      const zz_pE *ap = a.rep.elts();\n      long i;\n      for (i = 1; i < n; i++)\n         xp[i] = ap[i];\n      x.normalize();\n   }\n}\n\nvoid sub(zz_pEX& x, const zz_pEX& a, const zz_p& b)\n{\n   long n = a.rep.length();\n   if (n == 0) {\n      conv(x, b);\n      negate(x, x);\n   }\n   else if (&x == &a) {\n      sub(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else if (x.rep.MaxLength() == 0) {\n      x = a;\n      sub(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else {\n      // ugly...b could alias a coeff of x\n\n      zz_pE *xp = x.rep.elts();\n      sub(xp[0], a.rep[0], b);\n      x.rep.SetLength(n);\n      xp = x.rep.elts();\n      const zz_pE *ap = a.rep.elts();\n      long i;\n      for (i = 1; i < n; i++)\n         xp[i] = ap[i];\n      x.normalize();\n   }\n}\n\n\nvoid sub(zz_pEX& x, const zz_pEX& a, long b)\n{\n   if (a.rep.length() == 0) {\n      conv(x, b);\n      negate(x, x);\n   }\n   else {\n      if (&x != &a) x = a;\n      sub(x.rep[0], x.rep[0], b);\n      x.normalize();\n   }\n}\n\nvoid sub(zz_pEX& x, const zz_pE& b, const zz_pEX& a)\n{\n   long n = a.rep.length();\n   if (n == 0) {\n      conv(x, b);\n   }\n   else if (x.rep.MaxLength() == 0) {\n      negate(x, a);\n      add(x.rep[0], x.rep[0], b);\n      x.normalize();\n   }\n   else {\n      // ugly...b could alias a coeff of x\n\n      zz_pE *xp = x.rep.elts();\n      sub(xp[0], b, a.rep[0]);\n      x.rep.SetLength(n);\n      xp = x.rep.elts();\n      const zz_pE *ap = a.rep.elts();\n      long i;\n      for (i = 1; i < n; i++)\n         negate(xp[i], ap[i]);\n      x.normalize();\n   }\n}\n\n\nvoid sub(zz_pEX& x, const zz_p& a, const zz_pEX& b)\n{\n   NTL_zz_pRegister(T);   // avoids aliasing problems\n   T = a;\n   negate(x, b);\n   add(x, x, T);\n}\n\nvoid sub(zz_pEX& x, long a, const zz_pEX& b)\n{\n   NTL_zz_pRegister(T); \n   T = a;\n   negate(x, b);\n   add(x, x, T);\n}\n\nvoid mul(zz_pEX& c, const zz_pEX& a, const zz_pEX& b)\n{\n   if (&a == &b) {\n      sqr(c, a);\n      return;\n   }\n\n   if (IsZero(a) || IsZero(b)) {\n      clear(c);\n      return;\n   }\n\n   if (deg(a) == 0) {\n      mul(c, b, ConstTerm(a));\n      return;\n   } \n\n   if (deg(b) == 0) {\n      mul(c, a, ConstTerm(b));\n      return;\n   }\n\n   // general case...Kronecker subst\n\n   zz_pX A, B, C;\n\n   long da = deg(a);\n   long db = deg(b);\n\n   long n = zz_pE::degree();\n   long n2 = 2*n-1;\n\n   if (NTL_OVERFLOW(da+db+1, n2, 0))\n      Error(\"overflow in zz_pEX mul\");\n\n\n   long i, j;\n\n   A.rep.SetLength((da+1)*n2);\n\n   for (i = 0; i <= da; i++) {\n      const zz_pX& coeff = rep(a.rep[i]);\n      long dcoeff = deg(coeff);\n      for (j = 0; j <= dcoeff; j++)\n         A.rep[n2*i + j] = coeff.rep[j]; \n   }\n\n   A.normalize();\n\n   B.rep.SetLength((db+1)*n2);\n\n   for (i = 0; i <= db; i++) {\n      const zz_pX& coeff = rep(b.rep[i]);\n      long dcoeff = deg(coeff);\n      for (j = 0; j <= dcoeff; j++)\n         B.rep[n2*i + j] = coeff.rep[j]; \n   }\n\n   B.normalize();\n\n   mul(C, A, B);\n\n   long Clen = C.rep.length();\n   long lc = (Clen + n2 - 1)/n2;\n   long dc = lc - 1;\n\n   c.rep.SetLength(dc+1);\n\n   zz_pX tmp;\n   \n   for (i = 0; i <= dc; i++) {\n      tmp.rep.SetLength(n2);\n      for (j = 0; j < n2 && n2*i + j < Clen; j++)\n         tmp.rep[j] = C.rep[n2*i + j];\n      for (; j < n2; j++)\n         clear(tmp.rep[j]);\n      tmp.normalize();\n      conv(c.rep[i], tmp);\n   }\n  \n   c.normalize();\n}\n\n\nvoid mul(zz_pEX& x, const zz_pEX& a, const zz_pE& b)\n{\n   if (IsZero(b)) {\n      clear(x);\n      return;\n   }\n\n   zz_pE t;\n   t = b;\n\n   long i, da;\n\n   const zz_pE *ap;\n   zz_pE* xp;\n\n   da = deg(a);\n   x.rep.SetLength(da+1);\n   ap = a.rep.elts();\n   xp = x.rep.elts();\n\n   for (i = 0; i <= da; i++)\n      mul(xp[i], ap[i], t);\n\n   x.normalize();\n}\n\n\n\nvoid mul(zz_pEX& x, const zz_pEX& a, const zz_p& b)\n{\n   if (IsZero(b)) {\n      clear(x);\n      return;\n   }\n\n   NTL_zz_pRegister(t);\n   t = b;\n\n   long i, da;\n\n   const zz_pE *ap;\n   zz_pE* xp;\n\n   da = deg(a);\n   x.rep.SetLength(da+1);\n   ap = a.rep.elts();\n   xp = x.rep.elts();\n\n   for (i = 0; i <= da; i++)\n      mul(xp[i], ap[i], t);\n\n   x.normalize();\n}\n\n\nvoid mul(zz_pEX& x, const zz_pEX& a, long b)\n{\n   NTL_zz_pRegister(t);\n   t = b;\n   mul(x, a, t);\n}\n\nvoid sqr(zz_pEX& c, const zz_pEX& a)\n{\n   if (IsZero(a)) {\n      clear(c);\n      return;\n   }\n\n   if (deg(a) == 0) {\n      zz_pE res;\n      sqr(res, ConstTerm(a));\n      conv(c, res);\n      return;\n   } \n\n   // general case...Kronecker subst\n\n   zz_pX A, C;\n\n   long da = deg(a);\n\n   long n = zz_pE::degree();\n   long n2 = 2*n-1;\n\n   if (NTL_OVERFLOW(2*da+1, n2, 0))\n      Error(\"overflow in zz_pEX sqr\");\n\n   long i, j;\n\n   A.rep.SetLength((da+1)*n2);\n\n   for (i = 0; i <= da; i++) {\n      const zz_pX& coeff = rep(a.rep[i]);\n      long dcoeff = deg(coeff);\n      for (j = 0; j <= dcoeff; j++)\n         A.rep[n2*i + j] = coeff.rep[j]; \n   }\n\n   A.normalize();\n\n   sqr(C, A);\n\n   long Clen = C.rep.length();\n   long lc = (Clen + n2 - 1)/n2;\n   long dc = lc - 1;\n\n   c.rep.SetLength(dc+1);\n\n   zz_pX tmp;\n   \n   for (i = 0; i <= dc; i++) {\n      tmp.rep.SetLength(n2);\n      for (j = 0; j < n2 && n2*i + j < Clen; j++)\n         tmp.rep[j] = C.rep[n2*i + j];\n      for (; j < n2; j++)\n         clear(tmp.rep[j]);\n      tmp.normalize();\n      conv(c.rep[i], tmp);\n   }\n  \n  \n   c.normalize();\n}\n\n\nvoid MulTrunc(zz_pEX& x, const zz_pEX& a, const zz_pEX& b, long n)\n{\n   if (n < 0) Error(\"MulTrunc: bad args\");\n\n   zz_pEX t;\n   mul(t, a, b);\n   trunc(x, t, n);\n}\n\nvoid SqrTrunc(zz_pEX& x, const zz_pEX& a, long n)\n{\n   if (n < 0) Error(\"SqrTrunc: bad args\");\n\n   zz_pEX t;\n   sqr(t, a);\n   trunc(x, t, n);\n}\n\n\nvoid CopyReverse(zz_pEX& x, const zz_pEX& a, long hi)\n\n   // x[0..hi] = reverse(a[0..hi]), with zero fill\n   // input may not alias output\n\n{\n   long i, j, n, m;\n\n   n = hi+1;\n   m = a.rep.length();\n\n   x.rep.SetLength(n);\n\n   const zz_pE* ap = a.rep.elts();\n   zz_pE* xp = x.rep.elts();\n\n   for (i = 0; i < n; i++) {\n      j = hi-i;\n      if (j < 0 || j >= m)\n         clear(xp[i]);\n      else\n         xp[i] = ap[j];\n   }\n\n   x.normalize();\n} \n\n\nvoid trunc(zz_pEX& x, const zz_pEX& a, long m)\n\n// x = a % X^m, output may alias input \n\n{\n   if (m < 0) Error(\"trunc: bad args\");\n\n   if (&x == &a) {\n      if (x.rep.length() > m) {\n         x.rep.SetLength(m);\n         x.normalize();\n      }\n   }\n   else {\n      long n;\n      long i;\n      zz_pE* xp;\n      const zz_pE* ap;\n\n      n = min(a.rep.length(), m);\n      x.rep.SetLength(n);\n\n      xp = x.rep.elts();\n      ap = a.rep.elts();\n\n      for (i = 0; i < n; i++) xp[i] = ap[i];\n\n      x.normalize();\n   }\n}\n\n\nvoid random(zz_pEX& x, long n)\n{\n   long i;\n\n   x.rep.SetLength(n);\n\n   for (i = 0; i < n; i++)\n      random(x.rep[i]);\n\n   x.normalize();\n}\n\nvoid negate(zz_pEX& x, const zz_pEX& a)\n{\n   long n = a.rep.length();\n   x.rep.SetLength(n);\n\n   const zz_pE* ap = a.rep.elts();\n   zz_pE* xp = x.rep.elts();\n   long i;\n\n   for (i = n; i; i--, ap++, xp++)\n      negate((*xp), (*ap));\n}\n\n\n\nstatic\nvoid MulByXModAux(zz_pEX& h, const zz_pEX& a, const zz_pEX& f)\n{\n   long i, n, m;\n   zz_pE* hh;\n   const zz_pE *aa, *ff;\n\n   zz_pE t, z;\n\n   n = deg(f);\n   m = deg(a);\n\n   if (m >= n || n == 0) Error(\"MulByXMod: bad args\");\n\n   if (m < 0) {\n      clear(h);\n      return;\n   }\n\n   if (m < n-1) {\n      h.rep.SetLength(m+2);\n      hh = h.rep.elts();\n      aa = a.rep.elts();\n      for (i = m+1; i >= 1; i--)\n         hh[i] = aa[i-1];\n      clear(hh[0]);\n   }\n   else {\n      h.rep.SetLength(n);\n      hh = h.rep.elts();\n      aa = a.rep.elts();\n      ff = f.rep.elts();\n      negate(z, aa[n-1]);\n      if (!IsOne(ff[n]))\n         div(z, z, ff[n]);\n      for (i = n-1; i >= 1; i--) {\n         mul(t, z, ff[i]);\n         add(hh[i], aa[i-1], t);\n      }\n      mul(hh[0], z, ff[0]);\n      h.normalize();\n   }\n}\n\nvoid MulByXMod(zz_pEX& h, const zz_pEX& a, const zz_pEX& f)\n{\n   if (&h == &f) {\n      zz_pEX hh;\n      MulByXModAux(hh, a, f);\n      h = hh;\n   }\n   else\n      MulByXModAux(h, a, f);\n}\n\n\n\nvoid PlainMul(zz_pEX& x, const zz_pEX& a, const zz_pEX& b)\n{\n   long da = deg(a);\n   long db = deg(b);\n\n   if (da < 0 || db < 0) {\n      clear(x);\n      return;\n   }\n\n   long d = da+db;\n\n\n\n   const zz_pE *ap, *bp;\n   zz_pE *xp;\n   \n   zz_pEX la, lb;\n\n   if (&x == &a) {\n      la = a;\n      ap = la.rep.elts();\n   }\n   else\n      ap = a.rep.elts();\n\n   if (&x == &b) {\n      lb = b;\n      bp = lb.rep.elts();\n   }\n   else\n      bp = b.rep.elts();\n\n   x.rep.SetLength(d+1);\n\n   xp = x.rep.elts();\n\n   long i, j, jmin, jmax;\n   static zz_pX t, accum;\n\n   for (i = 0; i <= d; i++) {\n      jmin = max(0, i-db);\n      jmax = min(da, i);\n      clear(accum);\n      for (j = jmin; j <= jmax; j++) {\n\t mul(t, rep(ap[j]), rep(bp[i-j]));\n\t add(accum, accum, t);\n      }\n      conv(xp[i], accum);\n   }\n   x.normalize();\n}\n\nvoid SetSize(vec_zz_pX& x, long n, long m)\n{\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      x[i].rep.SetMaxLength(m);\n}\n\n\n\nvoid PlainDivRem(zz_pEX& q, zz_pEX& r, const zz_pEX& a, const zz_pEX& b)\n{\n   long da, db, dq, i, j, LCIsOne;\n   const zz_pE *bp;\n   zz_pE *qp;\n   zz_pX *xp;\n\n\n   zz_pE LCInv, t;\n   zz_pX s;\n\n   da = deg(a);\n   db = deg(b);\n\n   if (db < 0) Error(\"zz_pEX: division by zero\");\n\n   if (da < db) {\n      r = a;\n      clear(q);\n      return;\n   }\n\n   zz_pEX lb;\n\n   if (&q == &b) {\n      lb = b;\n      bp = lb.rep.elts();\n   }\n   else\n      bp = b.rep.elts();\n\n   if (IsOne(bp[db]))\n      LCIsOne = 1;\n   else {\n      LCIsOne = 0;\n      inv(LCInv, bp[db]);\n   }\n\n   vec_zz_pX x;\n\n   SetSize(x, da+1, 2*zz_pE::degree());\n\n   for (i = 0; i <= da; i++) \n      x[i] = rep(a.rep[i]);\n\n   xp = x.elts();\n\n   dq = da - db;\n   q.rep.SetLength(dq+1);\n   qp = q.rep.elts();\n\n   for (i = dq; i >= 0; i--) {\n      conv(t, xp[i+db]);\n      if (!LCIsOne)\n\t mul(t, t, LCInv);\n      qp[i] = t;\n      negate(t, t);\n\n      for (j = db-1; j >= 0; j--) {\n\t mul(s, rep(t), rep(bp[j]));\n\t add(xp[i+j], xp[i+j], s);\n      }\n   }\n\n   r.rep.SetLength(db);\n   for (i = 0; i < db; i++)\n      conv(r.rep[i], xp[i]);\n   r.normalize();\n}\n\n\nvoid PlainRem(zz_pEX& r, const zz_pEX& a, const zz_pEX& b, vec_zz_pX& x)\n{\n   long da, db, dq, i, j, LCIsOne;\n   const zz_pE *bp;\n   zz_pX *xp;\n\n\n   zz_pE LCInv, t;\n   zz_pX s;\n\n   da = deg(a);\n   db = deg(b);\n\n   if (db < 0) Error(\"zz_pEX: division by zero\");\n\n   if (da < db) {\n      r = a;\n      return;\n   }\n\n   bp = b.rep.elts();\n\n   if (IsOne(bp[db]))\n      LCIsOne = 1;\n   else {\n      LCIsOne = 0;\n      inv(LCInv, bp[db]);\n   }\n\n   for (i = 0; i <= da; i++)\n      x[i] = rep(a.rep[i]);\n\n   xp = x.elts();\n\n   dq = da - db;\n\n   for (i = dq; i >= 0; i--) {\n      conv(t, xp[i+db]);\n      if (!LCIsOne)\n\t mul(t, t, LCInv);\n      negate(t, t);\n\n      for (j = db-1; j >= 0; j--) {\n\t mul(s, rep(t), rep(bp[j]));\n\t add(xp[i+j], xp[i+j], s);\n      }\n   }\n\n   r.rep.SetLength(db);\n   for (i = 0; i < db; i++)\n      conv(r.rep[i], xp[i]);\n   r.normalize();\n}\n\n\nvoid PlainDivRem(zz_pEX& q, zz_pEX& r, const zz_pEX& a, const zz_pEX& b, \n     vec_zz_pX& x)\n{\n   long da, db, dq, i, j, LCIsOne;\n   const zz_pE *bp;\n   zz_pE *qp;\n   zz_pX *xp;\n\n\n   zz_pE LCInv, t;\n   zz_pX s;\n\n   da = deg(a);\n   db = deg(b);\n\n   if (db < 0) Error(\"zz_pEX: division by zero\");\n\n   if (da < db) {\n      r = a;\n      clear(q);\n      return;\n   }\n\n   zz_pEX lb;\n\n   if (&q == &b) {\n      lb = b;\n      bp = lb.rep.elts();\n   }\n   else\n      bp = b.rep.elts();\n\n   if (IsOne(bp[db]))\n      LCIsOne = 1;\n   else {\n      LCIsOne = 0;\n      inv(LCInv, bp[db]);\n   }\n\n   for (i = 0; i <= da; i++)\n      x[i] = rep(a.rep[i]);\n\n   xp = x.elts();\n\n   dq = da - db;\n   q.rep.SetLength(dq+1);\n   qp = q.rep.elts();\n\n   for (i = dq; i >= 0; i--) {\n      conv(t, xp[i+db]);\n      if (!LCIsOne)\n\t mul(t, t, LCInv);\n      qp[i] = t;\n      negate(t, t);\n\n      for (j = db-1; j >= 0; j--) {\n\t mul(s, rep(t), rep(bp[j]));\n\t add(xp[i+j], xp[i+j], s);\n      }\n   }\n\n   r.rep.SetLength(db);\n   for (i = 0; i < db; i++)\n      conv(r.rep[i], xp[i]);\n   r.normalize();\n}\n\n\nvoid PlainDiv(zz_pEX& q, const zz_pEX& a, const zz_pEX& b)\n{\n   long da, db, dq, i, j, LCIsOne;\n   const zz_pE *bp;\n   zz_pE *qp;\n   zz_pX *xp;\n\n\n   zz_pE LCInv, t;\n   zz_pX s;\n\n   da = deg(a);\n   db = deg(b);\n\n   if (db < 0) Error(\"zz_pEX: division by zero\");\n\n   if (da < db) {\n      clear(q);\n      return;\n   }\n\n   zz_pEX lb;\n\n   if (&q == &b) {\n      lb = b;\n      bp = lb.rep.elts();\n   }\n   else\n      bp = b.rep.elts();\n\n   if (IsOne(bp[db]))\n      LCIsOne = 1;\n   else {\n      LCIsOne = 0;\n      inv(LCInv, bp[db]);\n   }\n\n   vec_zz_pX x;\n   SetSize(x, da+1-db, 2*zz_pE::degree());\n\n   for (i = db; i <= da; i++)\n      x[i-db] = rep(a.rep[i]);\n\n   xp = x.elts();\n\n   dq = da - db;\n   q.rep.SetLength(dq+1);\n   qp = q.rep.elts();\n\n   for (i = dq; i >= 0; i--) {\n      conv(t, xp[i]);\n      if (!LCIsOne)\n\t mul(t, t, LCInv);\n      qp[i] = t;\n      negate(t, t);\n\n      long lastj = max(0, db-i);\n\n      for (j = db-1; j >= lastj; j--) {\n\t mul(s, rep(t), rep(bp[j]));\n\t add(xp[i+j-db], xp[i+j-db], s);\n      }\n   }\n}\n\nvoid PlainRem(zz_pEX& r, const zz_pEX& a, const zz_pEX& b)\n{\n   long da, db, dq, i, j, LCIsOne;\n   const zz_pE *bp;\n   zz_pX *xp;\n\n\n   zz_pE LCInv, t;\n   zz_pX s;\n\n   da = deg(a);\n   db = deg(b);\n\n   if (db < 0) Error(\"zz_pEX: division by zero\");\n\n   if (da < db) {\n      r = a;\n      return;\n   }\n\n   bp = b.rep.elts();\n\n   if (IsOne(bp[db]))\n      LCIsOne = 1;\n   else {\n      LCIsOne = 0;\n      inv(LCInv, bp[db]);\n   }\n\n   vec_zz_pX x;\n   SetSize(x, da + 1, 2*zz_pE::degree());\n\n   for (i = 0; i <= da; i++)\n      x[i] = rep(a.rep[i]);\n\n   xp = x.elts();\n\n   dq = da - db;\n\n   for (i = dq; i >= 0; i--) {\n      conv(t, xp[i+db]);\n      if (!LCIsOne)\n\t mul(t, t, LCInv);\n      negate(t, t);\n\n      for (j = db-1; j >= 0; j--) {\n\t mul(s, rep(t), rep(bp[j]));\n\t add(xp[i+j], xp[i+j], s);\n      }\n   }\n\n   r.rep.SetLength(db);\n   for (i = 0; i < db; i++)\n      conv(r.rep[i], xp[i]);\n   r.normalize();\n}\n\n\n\nvoid RightShift(zz_pEX& x, const zz_pEX& a, long n)\n{\n   if (IsZero(a)) {\n      clear(x);\n      return;\n   }\n\n   if (n < 0) {\n      if (n < -NTL_MAX_LONG) Error(\"overflow in RightShift\");\n      LeftShift(x, a, -n);\n      return;\n   }\n\n   long da = deg(a);\n   long i;\n \n   if (da < n) {\n      clear(x);\n      return;\n   }\n\n   if (&x != &a)\n      x.rep.SetLength(da-n+1);\n\n   for (i = 0; i <= da-n; i++)\n      x.rep[i] = a.rep[i+n];\n\n   if (&x == &a)\n      x.rep.SetLength(da-n+1);\n\n   x.normalize();\n}\n\nvoid LeftShift(zz_pEX& x, const zz_pEX& a, long n)\n{\n   if (IsZero(a)) {\n      clear(x);\n      return;\n   }\n\n   if (n < 0) {\n      if (n < -NTL_MAX_LONG) \n         clear(x);\n      else\n         RightShift(x, a, -n);\n      return;\n   }\n\n   if (NTL_OVERFLOW(n, 1, 0))\n      Error(\"overflow in LeftShift\");\n\n   long m = a.rep.length();\n\n   x.rep.SetLength(m+n);\n\n   long i;\n   for (i = m-1; i >= 0; i--)\n      x.rep[i+n] = a.rep[i];\n\n   for (i = 0; i < n; i++)\n      clear(x.rep[i]);\n}\n\n\n\nvoid NewtonInv(zz_pEX& c, const zz_pEX& a, long e)\n{\n   zz_pE x;\n\n   inv(x, ConstTerm(a));\n\n   if (e == 1) {\n      conv(c, x);\n      return;\n   }\n\n   static vec_long E;\n   E.SetLength(0);\n   append(E, e);\n   while (e > 1) {\n      e = (e+1)/2;\n      append(E, e);\n   }\n\n   long L = E.length();\n\n   zz_pEX g, g0, g1, g2;\n\n\n   g.rep.SetMaxLength(E[0]);\n   g0.rep.SetMaxLength(E[0]);\n   g1.rep.SetMaxLength((3*E[0]+1)/2);\n   g2.rep.SetMaxLength(E[0]);\n\n   conv(g, x);\n\n   long i;\n\n   for (i = L-1; i > 0; i--) {\n      // lift from E[i] to E[i-1]\n\n      long k = E[i];\n      long l = E[i-1]-E[i];\n\n      trunc(g0, a, k+l);\n\n      mul(g1, g0, g);\n      RightShift(g1, g1, k);\n      trunc(g1, g1, l);\n\n      mul(g2, g1, g);\n      trunc(g2, g2, l);\n      LeftShift(g2, g2, k);\n\n      sub(g, g, g2);\n   }\n\n   c = g;\n}\n\nvoid InvTrunc(zz_pEX& c, const zz_pEX& a, long e)\n{\n   if (e < 0) Error(\"InvTrunc: bad args\");\n   if (e == 0) {\n      clear(c);\n      return;\n   }\n\n   if (NTL_OVERFLOW(e, 1, 0))\n      Error(\"overflow in InvTrunc\");\n\n   NewtonInv(c, a, e);\n}\n\n\n\n\nconst long zz_pEX_MOD_PLAIN = 0;\nconst long zz_pEX_MOD_MUL = 1;\n\n\nvoid build(zz_pEXModulus& F, const zz_pEX& f)\n{\n   long n = deg(f);\n\n   if (n <= 0) Error(\"build(zz_pEXModulus,zz_pEX): deg(f) <= 0\");\n\n   if (NTL_OVERFLOW(n, zz_pE::degree(), 0))\n      Error(\"build(zz_pEXModulus,zz_pEX): overflow\");\n\n   F.tracevec.SetLength(0);\n\n   F.f = f;\n   F.n = n;\n\n   if (F.n < zz_pE::ModCross()) {\n      F.method = zz_pEX_MOD_PLAIN;\n   }\n   else {\n      F.method = zz_pEX_MOD_MUL;\n      zz_pEX P1;\n      zz_pEX P2;\n\n      CopyReverse(P1, f, n);\n      InvTrunc(P2, P1, n-1);\n      CopyReverse(P1, P2, n-2);\n      trunc(F.h0, P1, n-2);\n      trunc(F.f0, f, n);\n      F.hlc = ConstTerm(P2);\n   }\n}\n\n\n\nzz_pEXModulus::zz_pEXModulus()\n{\n   n = -1;\n   method = zz_pEX_MOD_PLAIN;\n}\n\n\nzz_pEXModulus::~zz_pEXModulus() \n{ \n}\n\n\n\nzz_pEXModulus::zz_pEXModulus(const zz_pEX& ff)\n{\n   n = -1;\n   method = zz_pEX_MOD_PLAIN;\n\n   build(*this, ff);\n}\n\n\nvoid UseMulRem21(zz_pEX& r, const zz_pEX& a, const zz_pEXModulus& F)\n{\n   zz_pEX P1;\n   zz_pEX P2;\n\n   RightShift(P1, a, F.n);\n   mul(P2, P1, F.h0);\n   RightShift(P2, P2, F.n-2);\n   if (!IsOne(F.hlc)) mul(P1, P1, F.hlc);\n   add(P2, P2, P1);\n   mul(P1, P2, F.f0);\n   trunc(P1, P1, F.n);\n   trunc(r, a, F.n);\n   sub(r, r, P1);\n}\n\nvoid UseMulDivRem21(zz_pEX& q, zz_pEX& r, const zz_pEX& a, const zz_pEXModulus& F)\n{\n   zz_pEX P1;\n   zz_pEX P2;\n\n   RightShift(P1, a, F.n);\n   mul(P2, P1, F.h0);\n   RightShift(P2, P2, F.n-2);\n   if (!IsOne(F.hlc)) mul(P1, P1, F.hlc);\n   add(P2, P2, P1);\n   mul(P1, P2, F.f0);\n   trunc(P1, P1, F.n);\n   trunc(r, a, F.n);\n   sub(r, r, P1);\n   q = P2;\n}\n\nvoid UseMulDiv21(zz_pEX& q, const zz_pEX& a, const zz_pEXModulus& F)\n{\n   zz_pEX P1;\n   zz_pEX P2;\n\n   RightShift(P1, a, F.n);\n   mul(P2, P1, F.h0);\n   RightShift(P2, P2, F.n-2);\n   if (!IsOne(F.hlc)) mul(P1, P1, F.hlc);\n   add(P2, P2, P1);\n   q = P2;\n\n}\n\n\nvoid rem(zz_pEX& x, const zz_pEX& a, const zz_pEXModulus& F)\n{\n   if (F.method == zz_pEX_MOD_PLAIN) {\n      PlainRem(x, a, F.f);\n      return;\n   }\n\n   long da = deg(a);\n   long n = F.n;\n\n   if (da <= 2*n-2) {\n      UseMulRem21(x, a, F);\n      return;\n   }\n\n   zz_pEX buf(INIT_SIZE, 2*n-1);\n\n   long a_len = da+1;\n\n   while (a_len > 0) {\n      long old_buf_len = buf.rep.length();\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      buf.rep.SetLength(old_buf_len+amt);\n\n      long i;\n\n      for (i = old_buf_len+amt-1; i >= amt; i--)\n         buf.rep[i] = buf.rep[i-amt];\n\n      for (i = amt-1; i >= 0; i--)\n         buf.rep[i] = a.rep[a_len-amt+i];\n\n      buf.normalize();\n\n      UseMulRem21(buf, buf, F);\n\n      a_len -= amt;\n   }\n\n   x = buf;\n}\n\nvoid DivRem(zz_pEX& q, zz_pEX& r, const zz_pEX& a, const zz_pEXModulus& F)\n{\n   if (F.method == zz_pEX_MOD_PLAIN) {\n      PlainDivRem(q, r, a, F.f);\n      return;\n   }\n\n   long da = deg(a);\n   long n = F.n;\n\n   if (da <= 2*n-2) {\n      UseMulDivRem21(q, r, a, F);\n      return;\n   }\n\n   zz_pEX buf(INIT_SIZE, 2*n-1);\n   zz_pEX qbuf(INIT_SIZE, n-1);\n\n   zz_pEX qq;\n   qq.rep.SetLength(da-n+1);\n\n   long a_len = da+1;\n   long q_hi = da-n+1;\n\n   while (a_len > 0) {\n      long old_buf_len = buf.rep.length();\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      buf.rep.SetLength(old_buf_len+amt);\n\n      long i;\n\n      for (i = old_buf_len+amt-1; i >= amt; i--)\n         buf.rep[i] = buf.rep[i-amt];\n\n      for (i = amt-1; i >= 0; i--)\n         buf.rep[i] = a.rep[a_len-amt+i];\n\n      buf.normalize();\n\n      UseMulDivRem21(qbuf, buf, buf, F);\n      long dl = qbuf.rep.length();\n      a_len = a_len - amt;\n      for(i = 0; i < dl; i++)\n         qq.rep[a_len+i] = qbuf.rep[i];\n      for(i = dl+a_len; i < q_hi; i++)\n         clear(qq.rep[i]);\n      q_hi = a_len;\n   }\n\n   r = buf;\n\n   qq.normalize();\n   q = qq;\n}\n\nvoid div(zz_pEX& q, const zz_pEX& a, const zz_pEXModulus& F)\n{\n   if (F.method == zz_pEX_MOD_PLAIN) {\n      PlainDiv(q, a, F.f);\n      return;\n   }\n\n   long da = deg(a);\n   long n = F.n;\n\n   if (da <= 2*n-2) {\n      UseMulDiv21(q, a, F);\n      return;\n   }\n\n   zz_pEX buf(INIT_SIZE, 2*n-1);\n   zz_pEX qbuf(INIT_SIZE, n-1);\n\n   zz_pEX qq;\n   qq.rep.SetLength(da-n+1);\n\n   long a_len = da+1;\n   long q_hi = da-n+1;\n\n   while (a_len > 0) {\n      long old_buf_len = buf.rep.length();\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      buf.rep.SetLength(old_buf_len+amt);\n\n      long i;\n\n      for (i = old_buf_len+amt-1; i >= amt; i--)\n         buf.rep[i] = buf.rep[i-amt];\n\n      for (i = amt-1; i >= 0; i--)\n         buf.rep[i] = a.rep[a_len-amt+i];\n\n      buf.normalize();\n\n      a_len = a_len - amt;\n      if (a_len > 0)\n         UseMulDivRem21(qbuf, buf, buf, F);\n      else\n         UseMulDiv21(qbuf, buf, F);\n\n      long dl = qbuf.rep.length();\n      for(i = 0; i < dl; i++)\n         qq.rep[a_len+i] = qbuf.rep[i];\n      for(i = dl+a_len; i < q_hi; i++)\n         clear(qq.rep[i]);\n      q_hi = a_len;\n   }\n\n   qq.normalize();\n   q = qq;\n}\n\n\n\n\nvoid MulMod(zz_pEX& c, const zz_pEX& a, const zz_pEX& b, const zz_pEXModulus& F)\n{\n   if (deg(a) >= F.n || deg(b) >= F.n) Error(\"MulMod: bad args\");\n\n   zz_pEX t;\n   mul(t, a, b);\n   rem(c, t, F);\n}\n\n\nvoid SqrMod(zz_pEX& c, const zz_pEX& a, const zz_pEXModulus& F)\n{\n   if (deg(a) >= F.n) Error(\"MulMod: bad args\");\n\n   zz_pEX t;\n   sqr(t, a);\n   rem(c, t, F);\n}\n\n\n\nvoid UseMulRem(zz_pEX& r, const zz_pEX& a, const zz_pEX& b)\n{\n   zz_pEX P1;\n   zz_pEX P2;\n\n   long da = deg(a);\n   long db = deg(b);\n\n   CopyReverse(P1, b, db);\n   InvTrunc(P2, P1, da-db+1);\n   CopyReverse(P1, P2, da-db);\n\n   RightShift(P2, a, db);\n   mul(P2, P1, P2);\n   RightShift(P2, P2, da-db);\n   mul(P1, P2, b);\n   sub(P1, a, P1);\n   \n   r = P1;\n}\n\nvoid UseMulDivRem(zz_pEX& q, zz_pEX& r, const zz_pEX& a, const zz_pEX& b)\n{\n   zz_pEX P1;\n   zz_pEX P2;\n\n   long da = deg(a);\n   long db = deg(b);\n\n   CopyReverse(P1, b, db);\n   InvTrunc(P2, P1, da-db+1);\n   CopyReverse(P1, P2, da-db);\n\n   RightShift(P2, a, db);\n   mul(P2, P1, P2);\n   RightShift(P2, P2, da-db);\n   mul(P1, P2, b);\n   sub(P1, a, P1);\n   \n   r = P1;\n   q = P2;\n}\n\nvoid UseMulDiv(zz_pEX& q, const zz_pEX& a, const zz_pEX& b)\n{\n   zz_pEX P1;\n   zz_pEX P2;\n\n   long da = deg(a);\n   long db = deg(b);\n\n   CopyReverse(P1, b, db);\n   InvTrunc(P2, P1, da-db+1);\n   CopyReverse(P1, P2, da-db);\n\n   RightShift(P2, a, db);\n   mul(P2, P1, P2);\n   RightShift(P2, P2, da-db);\n   \n   q = P2;\n}\n\n\n\nvoid DivRem(zz_pEX& q, zz_pEX& r, const zz_pEX& a, const zz_pEX& b)\n{\n   long sa = a.rep.length();\n   long sb = b.rep.length();\n\n   if (sb < zz_pE::DivCross() || sa-sb < zz_pE::DivCross())\n      PlainDivRem(q, r, a, b);\n   else if (sa < 4*sb)\n      UseMulDivRem(q, r, a, b);\n   else {\n      zz_pEXModulus B;\n      build(B, b);\n      DivRem(q, r, a, B);\n   }\n}\n\nvoid div(zz_pEX& q, const zz_pEX& a, const zz_pEX& b)\n{\n   long sa = a.rep.length();\n   long sb = b.rep.length();\n\n   if (sb < zz_pE::DivCross() || sa-sb < zz_pE::DivCross())\n      PlainDiv(q, a, b);\n   else if (sa < 4*sb)\n      UseMulDiv(q, a, b);\n   else {\n      zz_pEXModulus B;\n      build(B, b);\n      div(q, a, B);\n   }\n}\n\nvoid div(zz_pEX& q, const zz_pEX& a, const zz_pE& b)\n{\n   zz_pE T;\n   inv(T, b);\n   mul(q, a, T);\n}\n\nvoid div(zz_pEX& q, const zz_pEX& a, const zz_p& b)\n{\n   NTL_zz_pRegister(T);\n   inv(T, b);\n   mul(q, a, T);\n}\n\nvoid div(zz_pEX& q, const zz_pEX& a, long b)\n{\n   NTL_zz_pRegister(T);\n   T = b;\n   inv(T, T);\n   mul(q, a, T);\n}\n\nvoid rem(zz_pEX& r, const zz_pEX& a, const zz_pEX& b)\n{\n   long sa = a.rep.length();\n   long sb = b.rep.length();\n\n   if (sb < zz_pE::DivCross() || sa-sb < zz_pE::DivCross())\n      PlainRem(r, a, b);\n   else if (sa < 4*sb)\n      UseMulRem(r, a, b);\n   else {\n      zz_pEXModulus B;\n      build(B, b);\n      rem(r, a, B);\n   }\n}\n\nvoid GCD(zz_pEX& x, const zz_pEX& a, const zz_pEX& b)\n{\n   zz_pE t;\n\n   if (IsZero(b))\n      x = a;\n   else if (IsZero(a))\n      x = b;\n   else {\n      long n = max(deg(a),deg(b)) + 1;\n      zz_pEX u(INIT_SIZE, n), v(INIT_SIZE, n);\n\n      vec_zz_pX tmp;\n      SetSize(tmp, n, 2*zz_pE::degree());\n\n      u = a;\n      v = b;\n      do {\n         PlainRem(u, u, v, tmp);\n         swap(u, v);\n      } while (!IsZero(v));\n\n      x = u;\n   }\n\n   if (IsZero(x)) return;\n   if (IsOne(LeadCoeff(x))) return;\n\n   /* make gcd monic */\n\n\n   inv(t, LeadCoeff(x)); \n   mul(x, x, t); \n}\n\n\n\n         \n\nvoid XGCD(zz_pEX& d, zz_pEX& s, zz_pEX& t, const zz_pEX& a, const zz_pEX& b)\n{\n   zz_pE z;\n\n\n   if (IsZero(b)) {\n      set(s);\n      clear(t);\n      d = a;\n   }\n   else if (IsZero(a)) {\n      clear(s);\n      set(t);\n      d = b;\n   }\n   else {\n      long e = max(deg(a), deg(b)) + 1;\n\n      zz_pEX temp(INIT_SIZE, e), u(INIT_SIZE, e), v(INIT_SIZE, e), \n            u0(INIT_SIZE, e), v0(INIT_SIZE, e), \n            u1(INIT_SIZE, e), v1(INIT_SIZE, e), \n            u2(INIT_SIZE, e), v2(INIT_SIZE, e), q(INIT_SIZE, e);\n\n\n      set(u1); clear(v1);\n      clear(u2); set(v2);\n      u = a; v = b;\n\n      do {\n         DivRem(q, u, u, v);\n         swap(u, v);\n         u0 = u2;\n         v0 = v2;\n         mul(temp, q, u2);\n         sub(u2, u1, temp);\n         mul(temp, q, v2);\n         sub(v2, v1, temp);\n         u1 = u0;\n         v1 = v0;\n      } while (!IsZero(v));\n\n      d = u;\n      s = u1;\n      t = v1;\n   }\n\n   if (IsZero(d)) return;\n   if (IsOne(LeadCoeff(d))) return;\n\n   /* make gcd monic */\n\n   inv(z, LeadCoeff(d));\n   mul(d, d, z);\n   mul(s, s, z);\n   mul(t, t, z);\n}\n\nNTL_vector_impl(zz_pEX,vec_zz_pEX)\n\nNTL_eq_vector_impl(zz_pEX,vec_zz_pEX)\n\nNTL_io_vector_impl(zz_pEX,vec_zz_pEX)\n\nvoid IterBuild(zz_pE* a, long n)\n{\n   long i, k;\n   zz_pE b, t;\n\n   if (n <= 0) return;\n\n   negate(a[0], a[0]);\n\n   for (k = 1; k <= n-1; k++) {\n      negate(b, a[k]);\n      add(a[k], b, a[k-1]);\n      for (i = k-1; i >= 1; i--) {\n         mul(t, a[i], b);\n         add(a[i], t, a[i-1]);\n      }\n      mul(a[0], a[0], b);\n   }\n}\n\nvoid BuildFromRoots(zz_pEX& x, const vec_zz_pE& a)\n{\n   long n = a.length();\n\n   if (n == 0) {\n      set(x);\n      return;\n   }\n\n   x.rep.SetMaxLength(n+1);\n   x.rep = a;\n   IterBuild(&x.rep[0], n);\n   x.rep.SetLength(n+1);\n   SetCoeff(x, n);\n}\n\nvoid eval(zz_pE& b, const zz_pEX& f, const zz_pE& a)\n// does a Horner evaluation\n{\n   zz_pE acc;\n   long i;\n\n   clear(acc);\n   for (i = deg(f); i >= 0; i--) {\n      mul(acc, acc, a);\n      add(acc, acc, f.rep[i]);\n   }\n\n   b = acc;\n}\n\nvoid eval(vec_zz_pE& b, const zz_pEX& f, const vec_zz_pE& a)\n// naive algorithm:  repeats Horner\n{\n   if (&b == &f.rep) {\n      vec_zz_pE bb;\n      eval(bb, f, a);\n      b = bb;\n      return;\n   }\n\n   long m = a.length();\n   b.SetLength(m);\n   long i;\n   for (i = 0; i < m; i++)\n      eval(b[i], f, a[i]);\n}\n\n\nvoid interpolate(zz_pEX& f, const vec_zz_pE& a, const vec_zz_pE& b)\n{\n   long m = a.length();\n   if (b.length() != m) Error(\"interpolate: vector length mismatch\");\n\n   if (m == 0) {\n      clear(f);\n      return;\n   }\n\n   vec_zz_pE prod;\n   prod = a;\n\n   zz_pE t1, t2;\n\n   long k, i;\n\n   vec_zz_pE res;\n   res.SetLength(m);\n\n   for (k = 0; k < m; k++) {\n\n      const zz_pE& aa = a[k];\n\n      set(t1);\n      for (i = k-1; i >= 0; i--) {\n         mul(t1, t1, aa);\n         add(t1, t1, prod[i]);\n      }\n\n      clear(t2);\n      for (i = k-1; i >= 0; i--) {\n         mul(t2, t2, aa);\n         add(t2, t2, res[i]);\n      }\n\n\n      inv(t1, t1);\n      sub(t2, b[k], t2);\n      mul(t1, t1, t2);\n\n      for (i = 0; i < k; i++) {\n         mul(t2, prod[i], t1);\n         add(res[i], res[i], t2);\n      }\n\n      res[k] = t1;\n\n      if (k < m-1) {\n         if (k == 0)\n            negate(prod[0], prod[0]);\n         else {\n            negate(t1, a[k]);\n            add(prod[k], t1, prod[k-1]);\n            for (i = k-1; i >= 1; i--) {\n               mul(t2, prod[i], t1);\n               add(prod[i], t2, prod[i-1]);\n            }\n            mul(prod[0], prod[0], t1);\n         }\n      }\n   }\n\n   while (m > 0 && IsZero(res[m-1])) m--;\n   res.SetLength(m);\n   f.rep = res;\n}\n   \nvoid InnerProduct(zz_pEX& x, const vec_zz_pE& v, long low, long high, \n                   const vec_zz_pEX& H, long n, vec_zz_pX& t)\n{\n   zz_pX s;\n   long i, j;\n\n   for (j = 0; j < n; j++)\n      clear(t[j]);\n\n   high = min(high, v.length()-1);\n   for (i = low; i <= high; i++) {\n      const vec_zz_pE& h = H[i-low].rep;\n      long m = h.length();\n      const zz_pX& w = rep(v[i]);\n\n      for (j = 0; j < m; j++) {\n         mul(s, w, rep(h[j]));\n         add(t[j], t[j], s);\n      }\n   }\n\n   x.rep.SetLength(n);\n   for (j = 0; j < n; j++)\n      conv(x.rep[j], t[j]);\n   x.normalize();\n}\n\n\n\nvoid CompMod(zz_pEX& x, const zz_pEX& g, const zz_pEXArgument& A, \n             const zz_pEXModulus& F)\n{\n   if (deg(g) <= 0) {\n      x = g;\n      return;\n   }\n\n\n   zz_pEX s, t;\n   vec_zz_pX scratch;\n   SetSize(scratch, deg(F), 2*zz_pE::degree());\n\n   long m = A.H.length() - 1;\n   long l = ((g.rep.length()+m-1)/m) - 1;\n\n   const zz_pEX& M = A.H[m];\n\n   InnerProduct(t, g.rep, l*m, l*m + m - 1, A.H, F.n, scratch);\n   for (long i = l-1; i >= 0; i--) {\n      InnerProduct(s, g.rep, i*m, i*m + m - 1, A.H, F.n, scratch);\n      MulMod(t, t, M, F);\n      add(t, t, s);\n   }\n\n   x = t;\n}\n\n\nvoid build(zz_pEXArgument& A, const zz_pEX& h, const zz_pEXModulus& F, long m)\n{\n   long i;\n\n   if (m <= 0 || deg(h) >= F.n)\n      Error(\"build: bad args\");\n\n   if (m > F.n) m = F.n;\n\n   if (zz_pEXArgBound > 0) {\n      double sz = zz_p::storage();\n      sz = sz*zz_pE::degree();\n      sz = sz + NTL_VECTOR_HEADER_SIZE + sizeof(vec_zz_p);\n      sz = sz*F.n;\n      sz = sz + NTL_VECTOR_HEADER_SIZE + sizeof(vec_zz_pE);\n      sz = sz/1024;\n      m = min(m, long(zz_pEXArgBound/sz));\n      m = max(m, 1);\n   }\n\n\n\n   A.H.SetLength(m+1);\n\n   set(A.H[0]);\n   A.H[1] = h;\n   for (i = 2; i <= m; i++)\n      MulMod(A.H[i], A.H[i-1], h, F);\n}\n\nlong zz_pEXArgBound = 0;\n\n\n\n\nvoid CompMod(zz_pEX& x, const zz_pEX& g, const zz_pEX& h, const zz_pEXModulus& F)\n   // x = g(h) mod f\n{\n   long m = SqrRoot(g.rep.length());\n\n   if (m == 0) {\n      clear(x);\n      return;\n   }\n\n   zz_pEXArgument A;\n\n   build(A, h, F, m);\n\n   CompMod(x, g, A, F);\n}\n\n\n\n\nvoid Comp2Mod(zz_pEX& x1, zz_pEX& x2, const zz_pEX& g1, const zz_pEX& g2,\n              const zz_pEX& h, const zz_pEXModulus& F)\n\n{\n   long m = SqrRoot(g1.rep.length() + g2.rep.length());\n\n   if (m == 0) {\n      clear(x1);\n      clear(x2);\n      return;\n   }\n\n   zz_pEXArgument A;\n\n   build(A, h, F, m);\n\n   zz_pEX xx1, xx2;\n\n   CompMod(xx1, g1, A, F);\n   CompMod(xx2, g2, A, F);\n\n   x1 = xx1;\n   x2 = xx2;\n}\n\nvoid Comp3Mod(zz_pEX& x1, zz_pEX& x2, zz_pEX& x3, \n              const zz_pEX& g1, const zz_pEX& g2, const zz_pEX& g3,\n              const zz_pEX& h, const zz_pEXModulus& F)\n\n{\n   long m = SqrRoot(g1.rep.length() + g2.rep.length() + g3.rep.length());\n\n   if (m == 0) {\n      clear(x1);\n      clear(x2);\n      clear(x3);\n      return;\n   }\n\n   zz_pEXArgument A;\n\n   build(A, h, F, m);\n\n   zz_pEX xx1, xx2, xx3;\n\n   CompMod(xx1, g1, A, F);\n   CompMod(xx2, g2, A, F);\n   CompMod(xx3, g3, A, F);\n\n   x1 = xx1;\n   x2 = xx2;\n   x3 = xx3;\n}\n\nvoid build(zz_pEXTransMultiplier& B, const zz_pEX& b, const zz_pEXModulus& F)\n{\n   long db = deg(b);\n\n   if (db >= F.n) Error(\"build TransMultiplier: bad args\");\n\n   zz_pEX t;\n\n   LeftShift(t, b, F.n-1);\n   div(t, t, F);\n\n   // we optimize for low degree b\n\n   long d;\n\n   d = deg(t);\n   if (d < 0)\n      B.shamt_fbi = 0;\n   else\n      B.shamt_fbi = F.n-2 - d; \n\n   CopyReverse(B.fbi, t, d);\n\n   // The following code optimizes the case when \n   // f = X^n + low degree poly\n\n   trunc(t, F.f, F.n);\n   d = deg(t);\n   if (d < 0)\n      B.shamt = 0;\n   else\n      B.shamt = d;\n\n   CopyReverse(B.f0, t, d);\n\n   if (db < 0)\n      B.shamt_b = 0;\n   else\n      B.shamt_b = db;\n\n   CopyReverse(B.b, b, db);\n}\n\nvoid TransMulMod(zz_pEX& x, const zz_pEX& a, const zz_pEXTransMultiplier& B,\n               const zz_pEXModulus& F)\n{\n   if (deg(a) >= F.n) Error(\"TransMulMod: bad args\");\n\n   zz_pEX t1, t2;\n\n   mul(t1, a, B.b);\n   RightShift(t1, t1, B.shamt_b);\n\n   mul(t2, a, B.f0);\n   RightShift(t2, t2, B.shamt);\n   trunc(t2, t2, F.n-1);\n\n   mul(t2, t2, B.fbi);\n   if (B.shamt_fbi > 0) LeftShift(t2, t2, B.shamt_fbi);\n   trunc(t2, t2, F.n-1);\n   LeftShift(t2, t2, 1);\n\n   sub(x, t1, t2);\n}\n\n\nvoid ShiftSub(zz_pEX& U, const zz_pEX& V, long n)\n// assumes input does not alias output\n{\n   if (IsZero(V))\n      return;\n\n   long du = deg(U);\n   long dv = deg(V);\n\n   long d = max(du, n+dv);\n\n   U.rep.SetLength(d+1);\n   long i;\n\n   for (i = du+1; i <= d; i++)\n      clear(U.rep[i]);\n\n   for (i = 0; i <= dv; i++)\n      sub(U.rep[i+n], U.rep[i+n], V.rep[i]);\n\n   U.normalize();\n}\n\n\nvoid UpdateMap(vec_zz_pE& x, const vec_zz_pE& a,\n         const zz_pEXTransMultiplier& B, const zz_pEXModulus& F)\n{\n   zz_pEX xx;\n   TransMulMod(xx, to_zz_pEX(a), B, F);\n   x = xx.rep;\n}\n\nstatic\nvoid ProjectPowers(vec_zz_pE& x, const zz_pEX& a, long k, \n                   const zz_pEXArgument& H, const zz_pEXModulus& F)\n{\n   if (k < 0 || NTL_OVERFLOW(k, 1, 0) || deg(a) >= F.n)\n      Error(\"ProjectPowers: bad args\");\n\n   long m = H.H.length()-1;\n   long l = (k+m-1)/m - 1;\n\n   zz_pEXTransMultiplier M;\n   build(M, H.H[m], F);\n\n   zz_pEX s;\n   s = a;\n\n   x.SetLength(k);\n\n   long i;\n\n   for (i = 0; i <= l; i++) {\n      long m1 = min(m, k-i*m);\n      for (long j = 0; j < m1; j++)\n         InnerProduct(x[i*m+j], H.H[j].rep, s.rep);\n      if (i < l)\n         TransMulMod(s, s, M, F);\n   }\n}\n\nstatic\nvoid ProjectPowers(vec_zz_pE& x, const zz_pEX& a, long k, const zz_pEX& h, \n                   const zz_pEXModulus& F)\n{\n   if (k < 0 || deg(a) >= F.n || deg(h) >= F.n)\n      Error(\"ProjectPowers: bad args\");\n\n   if (k == 0) {\n      x.SetLength(0);;\n      return;\n   }\n\n   long m = SqrRoot(k);\n\n   zz_pEXArgument H;\n   build(H, h, F, m);\n\n   ProjectPowers(x, a, k, H, F);\n}\n\nvoid ProjectPowers(vec_zz_pE& x, const vec_zz_pE& a, long k,\n                   const zz_pEXArgument& H, const zz_pEXModulus& F)\n{\n   ProjectPowers(x, to_zz_pEX(a), k, H, F);\n}\n\nvoid ProjectPowers(vec_zz_pE& x, const vec_zz_pE& a, long k,\n                   const zz_pEX& h, const zz_pEXModulus& F)\n{\n   ProjectPowers(x, to_zz_pEX(a), k, h, F);\n}\n\n\n\n\nvoid BerlekampMassey(zz_pEX& h, const vec_zz_pE& a, long m)\n{\n   zz_pEX Lambda, Sigma, Temp;\n   long L;\n   zz_pE Delta, Delta1, t1;\n   long shamt;\n\n   // cerr << \"*** \" << m << \"\\n\";\n\n   Lambda.SetMaxLength(m+1);\n   Sigma.SetMaxLength(m+1);\n   Temp.SetMaxLength(m+1);\n\n   L = 0;\n   set(Lambda);\n   clear(Sigma);\n   set(Delta);\n   shamt = 0;\n\n   long i, r, dl;\n\n   for (r = 1; r <= 2*m; r++) {\n      // cerr << r << \"--\";\n      clear(Delta1);\n      dl = deg(Lambda);\n      for (i = 0; i <= dl; i++) {\n         mul(t1, Lambda.rep[i], a[r-i-1]);\n         add(Delta1, Delta1, t1);\n      }\n\n      if (IsZero(Delta1)) {\n         shamt++;\n         // cerr << \"case 1: \" << deg(Lambda) << \" \" << deg(Sigma) << \" \" << shamt << \"\\n\";\n      }\n      else if (2*L < r) {\n         div(t1, Delta1, Delta);\n         mul(Temp, Sigma, t1);\n         Sigma = Lambda;\n         ShiftSub(Lambda, Temp, shamt+1);\n         shamt = 0;\n         L = r-L;\n         Delta = Delta1;\n         // cerr << \"case 2: \" << deg(Lambda) << \" \" << deg(Sigma) << \" \" << shamt << \"\\n\";\n      }\n      else {\n         shamt++;\n         div(t1, Delta1, Delta);\n         mul(Temp, Sigma, t1);\n         ShiftSub(Lambda, Temp, shamt);\n         // cerr << \"case 3: \" << deg(Lambda) << \" \" << deg(Sigma) << \" \" << shamt << \"\\n\";\n      }\n   }\n\n   // cerr << \"finished: \" << L << \" \" << deg(Lambda) << \"\\n\"; \n\n   dl = deg(Lambda);\n   h.rep.SetLength(L + 1);\n\n   for (i = 0; i < L - dl; i++)\n      clear(h.rep[i]);\n\n   for (i = L - dl; i <= L; i++)\n      h.rep[i] = Lambda.rep[L - i];\n}\n\n\n\n\nvoid MinPolySeq(zz_pEX& h, const vec_zz_pE& a, long m)\n{\n   if (m < 0 || NTL_OVERFLOW(m, 1, 0)) Error(\"MinPoly: bad args\");\n   if (a.length() < 2*m) Error(\"MinPoly: sequence too short\");\n\n   BerlekampMassey(h, a, m);\n}\n\n\nvoid DoMinPolyMod(zz_pEX& h, const zz_pEX& g, const zz_pEXModulus& F, long m, \n               const zz_pEX& R)\n{\n   vec_zz_pE x;\n\n   ProjectPowers(x, R, 2*m, g, F);\n   MinPolySeq(h, x, m);\n}\n\nvoid ProbMinPolyMod(zz_pEX& h, const zz_pEX& g, const zz_pEXModulus& F, long m)\n{\n   long n = F.n;\n   if (m < 1 || m > n) Error(\"ProbMinPoly: bad args\");\n\n   zz_pEX R;\n   random(R, n);\n\n   DoMinPolyMod(h, g, F, m, R);\n}\n\nvoid ProbMinPolyMod(zz_pEX& h, const zz_pEX& g, const zz_pEXModulus& F)\n{\n   ProbMinPolyMod(h, g, F, F.n);\n}\n\nvoid MinPolyMod(zz_pEX& hh, const zz_pEX& g, const zz_pEXModulus& F, long m)\n{\n   zz_pEX h, h1;\n   long n = F.n;\n   if (m < 1 || m > n) Error(\"MinPoly: bad args\");\n\n   /* probabilistically compute min-poly */\n\n   ProbMinPolyMod(h, g, F, m);\n   if (deg(h) == m) { hh = h; return; }\n   CompMod(h1, h, g, F);\n   if (IsZero(h1)) { hh = h; return; }\n\n   /* not completely successful...must iterate */\n\n   zz_pEX h2, h3;\n   zz_pEX R;\n   zz_pEXTransMultiplier H1;\n   \n\n   for (;;) {\n      random(R, n);\n      build(H1, h1, F);\n      TransMulMod(R, R, H1, F);\n      DoMinPolyMod(h2, g, F, m-deg(h), R);\n\n      mul(h, h, h2);\n      if (deg(h) == m) { hh = h; return; }\n      CompMod(h3, h2, g, F);\n      MulMod(h1, h3, h1, F);\n      if (IsZero(h1)) { hh = h; return; }\n   }\n}\n\nvoid IrredPolyMod(zz_pEX& h, const zz_pEX& g, const zz_pEXModulus& F, long m)\n{\n   if (m < 1 || m > F.n) Error(\"IrredPoly: bad args\");\n\n   zz_pEX R;\n   set(R);\n\n   DoMinPolyMod(h, g, F, m, R);\n}\n\n\n\nvoid IrredPolyMod(zz_pEX& h, const zz_pEX& g, const zz_pEXModulus& F)\n{\n   IrredPolyMod(h, g, F, F.n);\n}\n\n\n\nvoid MinPolyMod(zz_pEX& hh, const zz_pEX& g, const zz_pEXModulus& F)\n{\n   MinPolyMod(hh, g, F, F.n);\n}\n\nvoid diff(zz_pEX& x, const zz_pEX& a)\n{\n   long n = deg(a);\n   long i;\n\n   if (n <= 0) {\n      clear(x);\n      return;\n   }\n\n   if (&x != &a)\n      x.rep.SetLength(n);\n\n   for (i = 0; i <= n-1; i++) {\n      mul(x.rep[i], a.rep[i+1], i+1);\n   }\n\n   if (&x == &a)\n      x.rep.SetLength(n);\n\n   x.normalize();\n}\n\n\n\nvoid MakeMonic(zz_pEX& x)\n{\n   if (IsZero(x))\n      return;\n\n   if (IsOne(LeadCoeff(x)))\n      return;\n\n   zz_pE t;\n\n   inv(t, LeadCoeff(x));\n   mul(x, x, t);\n}\n\n\nlong divide(zz_pEX& q, const zz_pEX& a, const zz_pEX& b)\n{\n   if (IsZero(b)) {\n      if (IsZero(a)) {\n         clear(q);\n         return 1;\n      }\n      else\n         return 0;\n   }\n\n   zz_pEX lq, r;\n   DivRem(lq, r, a, b);\n   if (!IsZero(r)) return 0; \n   q = lq;\n   return 1;\n}\n\nlong divide(const zz_pEX& a, const zz_pEX& b)\n{\n   if (IsZero(b)) return IsZero(a);\n   zz_pEX lq, r;\n   DivRem(lq, r, a, b);\n   if (!IsZero(r)) return 0; \n   return 1;\n}\n\n\n\nstatic\nlong OptWinSize(long n)\n// finds k that minimizes n/(k+1) + 2^{k-1}\n\n{\n   long k;\n   double v, v_new;\n\n\n   v = n/2.0 + 1.0;\n   k = 1;\n\n   for (;;) {\n      v_new = n/(double(k+2)) + double(1L << k);\n      if (v_new >= v) break;\n      v = v_new;\n      k++;\n   }\n\n   return k;\n}\n      \n\n\nvoid PowerMod(zz_pEX& h, const zz_pEX& g, const ZZ& e, const zz_pEXModulus& F)\n// h = g^e mod f using \"sliding window\" algorithm\n{\n   if (deg(g) >= F.n) Error(\"PowerMod: bad args\");\n\n   if (e == 0) {\n      set(h);\n      return;\n   }\n\n   if (e == 1) {\n      h = g;\n      return;\n   }\n\n   if (e == -1) {\n      InvMod(h, g, F);\n      return;\n   }\n\n   if (e == 2) {\n      SqrMod(h, g, F);\n      return;\n   }\n\n   if (e == -2) {\n      SqrMod(h, g, F);\n      InvMod(h, h, F);\n      return;\n   }\n\n\n   long n = NumBits(e);\n\n   zz_pEX res;\n   res.SetMaxLength(F.n);\n   set(res);\n\n   long i;\n\n   if (n < 16) {\n      // plain square-and-multiply algorithm\n\n      for (i = n - 1; i >= 0; i--) {\n         SqrMod(res, res, F);\n         if (bit(e, i))\n            MulMod(res, res, g, F);\n      }\n\n      if (e < 0) InvMod(res, res, F);\n\n      h = res;\n      return;\n   }\n\n   long k = OptWinSize(n);\n   k = min(k, 3);\n\n   vec_zz_pEX v;\n\n   v.SetLength(1L << (k-1));\n\n   v[0] = g;\n \n   if (k > 1) {\n      zz_pEX t;\n      SqrMod(t, g, F);\n\n      for (i = 1; i < (1L << (k-1)); i++)\n         MulMod(v[i], v[i-1], t, F);\n   }\n\n\n   long val;\n   long cnt;\n   long m;\n\n   val = 0;\n   for (i = n-1; i >= 0; i--) {\n      val = (val << 1) | bit(e, i); \n      if (val == 0)\n         SqrMod(res, res, F);\n      else if (val >= (1L << (k-1)) || i == 0) {\n         cnt = 0;\n         while ((val & 1) == 0) {\n            val = val >> 1;\n            cnt++;\n         }\n\n         m = val;\n         while (m > 0) {\n            SqrMod(res, res, F);\n            m = m >> 1;\n         }\n\n         MulMod(res, res, v[val >> 1], F);\n\n         while (cnt > 0) {\n            SqrMod(res, res, F);\n            cnt--;\n         }\n\n         val = 0;\n      }\n   }\n\n   if (e < 0) InvMod(res, res, F);\n\n   h = res;\n}\n\nvoid InvMod(zz_pEX& x, const zz_pEX& a, const zz_pEX& f)\n{\n   if (deg(a) >= deg(f) || deg(f) == 0) Error(\"InvMod: bad args\");\n\n   zz_pEX d, t;\n\n   XGCD(d, x, t, a, f);\n   if (!IsOne(d))\n      Error(\"zz_pEX InvMod: can't compute multiplicative inverse\");\n}\n\nlong InvModStatus(zz_pEX& x, const zz_pEX& a, const zz_pEX& f)\n{\n   if (deg(a) >= deg(f) || deg(f) == 0) Error(\"InvModStatus: bad args\");\n   zz_pEX d, t;\n\n   XGCD(d, x, t, a, f);\n   if (!IsOne(d)) {\n      x = d;\n      return 1;\n   }\n   else\n      return 0;\n}\n\n\nvoid MulMod(zz_pEX& x, const zz_pEX& a, const zz_pEX& b, const zz_pEX& f)\n{\n   if (deg(a) >= deg(f) || deg(b) >= deg(f) || deg(f) == 0)\n      Error(\"MulMod: bad args\");\n\n   zz_pEX t;\n\n   mul(t, a, b);\n   rem(x, t, f);\n}\n\nvoid SqrMod(zz_pEX& x, const zz_pEX& a, const zz_pEX& f)\n{\n   if (deg(a) >= deg(f) || deg(f) == 0) Error(\"SqrMod: bad args\");\n\n   zz_pEX t;\n\n   sqr(t, a);\n   rem(x, t, f);\n}\n\n\nvoid PowerXMod(zz_pEX& hh, const ZZ& e, const zz_pEXModulus& F)\n{\n   if (F.n < 0) Error(\"PowerXMod: uninitialized modulus\");\n\n   if (IsZero(e)) {\n      set(hh);\n      return;\n   }\n\n   long n = NumBits(e);\n   long i;\n\n   zz_pEX h;\n\n   h.SetMaxLength(F.n);\n   set(h);\n\n   for (i = n - 1; i >= 0; i--) {\n      SqrMod(h, h, F);\n      if (bit(e, i))\n         MulByXMod(h, h, F.f);\n   }\n\n   if (e < 0) InvMod(h, h, F);\n\n   hh = h;\n}\n\n\nvoid reverse(zz_pEX& x, const zz_pEX& a, long hi)\n{\n   if (hi < 0) { clear(x); return; }\n   if (NTL_OVERFLOW(hi, 1, 0))\n      Error(\"overflow in reverse\");\n\n   if (&x == &a) {\n      zz_pEX tmp;\n      CopyReverse(tmp, a, hi);\n      x = tmp;\n   }\n   else\n      CopyReverse(x, a, hi);\n}\n\n\nvoid power(zz_pEX& x, const zz_pEX& a, long e)\n{\n   if (e < 0) {\n      Error(\"power: negative exponent\");\n   }\n\n   if (e == 0) {\n      x = 1;\n      return;\n   }\n\n   if (a == 0 || a == 1) {\n      x = a;\n      return;\n   }\n\n   long da = deg(a);\n\n   if (da == 0) {\n      x = power(ConstTerm(a), e);\n      return;\n   }\n\n   if (da > (NTL_MAX_LONG-1)/e)\n      Error(\"overflow in power\");\n\n   zz_pEX res;\n   res.SetMaxLength(da*e + 1);\n   res = 1;\n   \n   long k = NumBits(e);\n   long i;\n\n   for (i = k - 1; i >= 0; i--) {\n      sqr(res, res);\n      if (bit(e, i))\n         mul(res, res, a);\n   }\n\n   x = res;\n}\n\n\n\nstatic\nvoid FastTraceVec(vec_zz_pE& S, const zz_pEXModulus& f)\n{\n   long n = deg(f);\n\n   zz_pEX x = reverse(-LeftShift(reverse(diff(reverse(f)), n-1), n-1)/f, n-1);\n\n   S.SetLength(n);\n   S[0] = n;\n\n   long i;\n   for (i = 1; i < n; i++)\n      S[i] = coeff(x, i);\n}\n\n\nvoid PlainTraceVec(vec_zz_pE& S, const zz_pEX& ff)\n{\n   if (deg(ff) <= 0)\n      Error(\"TraceVec: bad args\");\n\n   zz_pEX f;\n   f = ff;\n\n   MakeMonic(f);\n\n   long n = deg(f);\n\n   S.SetLength(n);\n\n   if (n == 0)\n      return;\n\n   long k, i;\n   zz_pX acc, t;\n   zz_pE t1;\n\n   S[0] = n;\n\n   for (k = 1; k < n; k++) {\n      mul(acc, rep(f.rep[n-k]), k);\n\n      for (i = 1; i < k; i++) {\n         mul(t, rep(f.rep[n-i]), rep(S[k-i]));\n         add(acc, acc, t);\n      }\n\n      conv(t1, acc);\n      negate(S[k], t1);\n   }\n}\n\nvoid TraceVec(vec_zz_pE& S, const zz_pEX& f)\n{\n   if (deg(f) < zz_pE::DivCross())\n      PlainTraceVec(S, f);\n   else\n      FastTraceVec(S, f);\n}\n\nstatic\nvoid ComputeTraceVec(const zz_pEXModulus& F)\n{\n   vec_zz_pE& S = *((vec_zz_pE *) &F.tracevec);\n\n   if (S.length() > 0)\n      return;\n\n   if (F.method == zz_pEX_MOD_PLAIN) {\n      PlainTraceVec(S, F.f);\n   }\n   else {\n      FastTraceVec(S, F);\n   }\n}\n\nvoid TraceMod(zz_pE& x, const zz_pEX& a, const zz_pEXModulus& F)\n{\n   long n = F.n;\n\n   if (deg(a) >= n)\n      Error(\"trace: bad args\");\n\n   if (F.tracevec.length() == 0) \n      ComputeTraceVec(F);\n\n   InnerProduct(x, a.rep, F.tracevec);\n}\n\nvoid TraceMod(zz_pE& x, const zz_pEX& a, const zz_pEX& f)\n{\n   if (deg(a) >= deg(f) || deg(f) <= 0)\n      Error(\"trace: bad args\");\n\n   project(x, TraceVec(f), a);\n}\n\n\nvoid PlainResultant(zz_pE& rres, const zz_pEX& a, const zz_pEX& b)\n{\n   zz_pE res;\n \n   if (IsZero(a) || IsZero(b))\n      clear(res);\n   else if (deg(a) == 0 && deg(b) == 0) \n      set(res);\n   else {\n      long d0, d1, d2;\n      zz_pE lc;\n      set(res);\n\n      long n = max(deg(a),deg(b)) + 1;\n      zz_pEX u(INIT_SIZE, n), v(INIT_SIZE, n);\n      vec_zz_pX tmp;\n      SetSize(tmp, n, 2*zz_pE::degree());\n\n      u = a;\n      v = b;\n\n      for (;;) {\n         d0 = deg(u);\n         d1 = deg(v);\n         lc = LeadCoeff(v);\n\n         PlainRem(u, u, v, tmp);\n         swap(u, v);\n\n         d2 = deg(v);\n         if (d2 >= 0) {\n            power(lc, lc, d0-d2);\n            mul(res, res, lc);\n            if (d0 & d1 & 1) negate(res, res);\n         }\n         else {\n            if (d1 == 0) {\n               power(lc, lc, d0);\n               mul(res, res, lc);\n            }\n            else\n               clear(res);\n        \n            break;\n         }\n      }\n\n      rres = res;\n   }\n}\n\nvoid resultant(zz_pE& rres, const zz_pEX& a, const zz_pEX& b)\n{\n   PlainResultant(rres, a, b); \n}\n\n\nvoid NormMod(zz_pE& x, const zz_pEX& a, const zz_pEX& f)\n{\n   if (deg(f) <= 0 || deg(a) >= deg(f)) \n      Error(\"norm: bad args\");\n\n   if (IsZero(a)) {\n      clear(x);\n      return;\n   }\n\n   zz_pE t;\n   resultant(t, f, a);\n   if (!IsOne(LeadCoeff(f))) {\n      zz_pE t1;\n      power(t1, LeadCoeff(f), deg(a));\n      inv(t1, t1);\n      mul(t, t, t1);\n   }\n\n   x = t;\n}\n\n\n\n// tower stuff...\n\n\n\nvoid InnerProduct(zz_pEX& x, const vec_zz_p& v, long low, long high,\n                   const vec_zz_pEX& H, long n, vec_zz_pE& t)\n{\n   zz_pE s;\n   long i, j;\n\n   for (j = 0; j < n; j++)\n      clear(t[j]);\n\n   high = min(high, v.length()-1);\n   for (i = low; i <= high; i++) {\n      const vec_zz_pE& h = H[i-low].rep;\n      long m = h.length();\n      const zz_p& w = v[i];\n\n      for (j = 0; j < m; j++) {\n         mul(s, h[j], w);\n         add(t[j], t[j], s);\n      }\n   }\n\n   x.rep.SetLength(n);\n   for (j = 0; j < n; j++)\n      x.rep[j] = t[j];\n\n   x.normalize();\n}\n\n\n\nvoid CompTower(zz_pEX& x, const zz_pX& g, const zz_pEXArgument& A,\n             const zz_pEXModulus& F)\n{\n   if (deg(g) <= 0) {\n      conv(x, g);\n      return;\n   }\n\n\n   zz_pEX s, t;\n   vec_zz_pE scratch;\n   scratch.SetLength(deg(F));\n\n   long m = A.H.length() - 1;\n   long l = ((g.rep.length()+m-1)/m) - 1;\n\n   const zz_pEX& M = A.H[m];\n\n   InnerProduct(t, g.rep, l*m, l*m + m - 1, A.H, F.n, scratch);\n   for (long i = l-1; i >= 0; i--) {\n      InnerProduct(s, g.rep, i*m, i*m + m - 1, A.H, F.n, scratch);\n      MulMod(t, t, M, F);\n      add(t, t, s);\n   }\n   x = t;\n}\n\n\nvoid CompTower(zz_pEX& x, const zz_pX& g, const zz_pEX& h, \n             const zz_pEXModulus& F)\n   // x = g(h) mod f\n{\n   long m = SqrRoot(g.rep.length());\n\n   if (m == 0) {\n      clear(x);\n      return;\n   }\n\n\n   zz_pEXArgument A;\n\n   build(A, h, F, m);\n\n   CompTower(x, g, A, F);\n}\n\nvoid PrepareProjection(vec_vec_zz_p& tt, const vec_zz_pE& s,\n                       const vec_zz_p& proj)\n{\n   long l = s.length();\n   tt.SetLength(l);\n\n   zz_pXMultiplier M;\n   long i;\n\n   for (i = 0; i < l; i++) {\n      build(M, rep(s[i]), zz_pE::modulus());\n      UpdateMap(tt[i], proj, M, zz_pE::modulus());\n   }\n}\n\nvoid ProjectedInnerProduct(zz_p& x, const vec_zz_pE& a, \n                           const vec_vec_zz_p& b)\n{\n   long n = min(a.length(), b.length());\n\n   zz_p t, res;\n\n   res = 0;\n\n   long i;\n   for (i = 0; i < n; i++) {\n      project(t, b[i], rep(a[i]));\n      res += t;\n   }\n\n   x = res;\n}\n\n\n   \nvoid PrecomputeProj(vec_zz_p& proj, const zz_pX& f)\n{\n   long n = deg(f);\n\n   if (n <= 0) Error(\"PrecomputeProj: bad args\");\n\n   if (ConstTerm(f) != 0) {\n      proj.SetLength(1);\n      proj[0] = 1;\n   }\n   else {\n      proj.SetLength(n);\n      clear(proj);\n      proj[n-1] = 1;\n   }\n}\n\n\nvoid ProjectPowersTower(vec_zz_p& x, const vec_zz_pE& a, long k,\n                   const zz_pEXArgument& H, const zz_pEXModulus& F,\n                   const vec_zz_p& proj)\n\n{\n   long n = F.n;\n\n   if (a.length() > n || k < 0 || NTL_OVERFLOW(k, 1, 0))\n      Error(\"ProjectPowers: bad args\");\n\n   long m = H.H.length()-1;\n   long l = (k+m-1)/m - 1;\n\n   zz_pEXTransMultiplier M;\n   build(M, H.H[m], F);\n\n   vec_zz_pE s(INIT_SIZE, n);\n   s = a;\n\n   x.SetLength(k);\n\n   vec_vec_zz_p tt;\n\n   for (long i = 0; i <= l; i++) {\n      long m1 = min(m, k-i*m);\n      zz_p* w = &x[i*m];\n\n      PrepareProjection(tt, s, proj);\n\n      for (long j = 0; j < m1; j++)\n         ProjectedInnerProduct(w[j], H.H[j].rep, tt);\n      if (i < l)\n         UpdateMap(s, s, M, F);\n   }\n}\n\n\n\n\nvoid ProjectPowersTower(vec_zz_p& x, const vec_zz_pE& a, long k,\n                   const zz_pEX& h, const zz_pEXModulus& F,\n                   const vec_zz_p& proj)\n\n{\n   if (a.length() > F.n || k < 0) Error(\"ProjectPowers: bad args\");\n\n   if (k == 0) {\n      x.SetLength(0);\n      return;\n   }\n\n   long m = SqrRoot(k);\n\n   zz_pEXArgument H;\n\n   build(H, h, F, m);\n   ProjectPowersTower(x, a, k, H, F, proj);\n}\n\n\nvoid DoMinPolyTower(zz_pX& h, const zz_pEX& g, const zz_pEXModulus& F, long m,\n               const vec_zz_pE& R, const vec_zz_p& proj)\n{\n   vec_zz_p x;\n\n   ProjectPowersTower(x, R, 2*m, g, F, proj);\n   \n   MinPolySeq(h, x, m);\n}\n\n\nvoid ProbMinPolyTower(zz_pX& h, const zz_pEX& g, const zz_pEXModulus& F, \n                      long m)\n{\n   long n = F.n;\n   if (m < 1 || m > n*zz_pE::degree()) Error(\"ProbMinPoly: bad args\");\n\n   vec_zz_pE R;\n   R.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      random(R[i]);\n\n   vec_zz_p proj;\n   PrecomputeProj(proj, zz_pE::modulus());\n\n   DoMinPolyTower(h, g, F, m, R, proj);\n}\n\n\nvoid ProbMinPolyTower(zz_pX& h, const zz_pEX& g, const zz_pEXModulus& F, \n                      long m, const vec_zz_p& proj)\n{\n   long n = F.n;\n   if (m < 1 || m > n*zz_pE::degree()) Error(\"ProbMinPoly: bad args\");\n\n   vec_zz_pE R;\n   R.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      random(R[i]);\n\n   DoMinPolyTower(h, g, F, m, R, proj);\n}\n\nvoid MinPolyTower(zz_pX& hh, const zz_pEX& g, const zz_pEXModulus& F, long m)\n{\n   zz_pX h;\n   zz_pEX h1;\n   long n = F.n;\n   if (m < 1 || m > n*zz_pE::degree()) {\n      Error(\"MinPoly: bad args\");\n   }\n\n   vec_zz_p proj;\n   PrecomputeProj(proj, zz_pE::modulus());\n\n   /* probabilistically compute min-poly */\n\n   ProbMinPolyTower(h, g, F, m, proj);\n   if (deg(h) == m) { hh = h; return; }\n   CompTower(h1, h, g, F);\n   if (IsZero(h1)) { hh = h; return; }\n\n   /* not completely successful...must iterate */\n\n   long i;\n\n   zz_pX h2;\n   zz_pEX h3;\n   vec_zz_pE R;\n   zz_pEXTransMultiplier H1;\n   \n\n   for (;;) {\n      R.SetLength(n);\n      for (i = 0; i < n; i++) random(R[i]);\n      build(H1, h1, F);\n      UpdateMap(R, R, H1, F);\n      DoMinPolyTower(h2, g, F, m-deg(h), R, proj);\n\n      mul(h, h, h2);\n      if (deg(h) == m) { hh = h; return; }\n      CompTower(h3, h2, g, F);\n      MulMod(h1, h3, h1, F);\n      if (IsZero(h1)) { hh = h; return; }\n   }\n}\n\nvoid IrredPolyTower(zz_pX& h, const zz_pEX& g, const zz_pEXModulus& F, long m)\n{\n   if (m < 1 || m > deg(F)*zz_pE::degree()) Error(\"IrredPoly: bad args\");\n\n   vec_zz_pE R;\n   R.SetLength(1);\n   R[0] = 1;\n\n   vec_zz_p proj;\n   proj.SetLength(1);\n   proj[0] = 1;\n\n   DoMinPolyTower(h, g, F, m, R, proj);\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "52a6d709fcd6b2b3b761c3095ac4e40a48f58130", "size": 58912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/lzz_pEX.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RUNETag/WinNTL/src/lzz_pEX.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/src/lzz_pEX.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 17.220695703, "max_line_length": 91, "alphanum_fraction": 0.4812092613, "num_tokens": 21858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.7025300511670689, "lm_q1q2_score": 0.4449897449513397}}
{"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__SPLINE__FIT_HPP_\n#define SMOOTH__SPLINE__FIT_HPP_\n\n/**\n * @file\n * @brief Fit Spline and Bspline from data.\n */\n\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n#include <Eigen/SparseLU>\n\n#include <cassert>\n#include <ranges>\n\n#include \"smooth/manifold_vector.hpp\"\n#include \"smooth/optim.hpp\"\n\n#include \"bspline.hpp\"\n#include \"spline.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief Spline specification.\n */\ntemplate<typename T>\nconcept SplineSpec = requires(T t)\n{\n  // clang-format off\n  { T::Degree } -> std::convertible_to<int>;\n  { T::OptDeg } -> std::convertible_to<int>;\n  { T::InnCnt } -> std::convertible_to<int>;\n  { t.LeftDeg };\n  { t.RghtDeg };\n  // clang-format on\n};\n\nnamespace spline_specs\n{\n\n  /**\n   * @brief SplineSpec without boundary constraints\n   *\n   * @tparam K spline degree (must be 0 or 1)\n   */\n  template<LieGroup G, std::size_t K>\n  struct NoConstraints\n  {\n    /// @brief Polynomial degree\n    static constexpr int Degree = K;\n    /// @brief Optimization degree (absolute integral of derivative OptDeg is minimized)\n    static constexpr int OptDeg = -1;\n    /// @brief Number of derivatives to enforce continuity for\n    static constexpr int InnCnt = int(K) - 1;\n\n    /// @brief Degrees of left-side boundary constraints (no constraints)\n    static constexpr std::array<int, 0> LeftDeg{};\n    /// @brief Values of left-side boundary constraints\n    std::array<Tangent<G>, 0> left_values{};\n\n    /// @brief Degrees of right-side boundary constraints (no constraints)\n    static constexpr std::array<int, 0> RghtDeg{};\n    /// @brief Values of right-side boundary constraints\n    std::array<Tangent<G>, 0> rght_values{};\n  };\n\n  /// @brief SplineSpec for a piecewise constant function\n  template<LieGroup G>\n  using PiecewiseConstant = NoConstraints<G, 0>;\n\n  /// @brief SplineSpec for a piecewise linear function\n  template<LieGroup G>\n  using PiecewiseLinear = NoConstraints<G, 1>;\n\n  /**\n   * @brief SplineSpec for a cubic spline with two boundary conditions.\n   *\n   * @tparam P1 order of left boundary contraint (must be 1 or 2).\n   * @tparam P2 order of right boundary contraint (must be 1 or 2).\n   */\n  template<LieGroup G, std::size_t P1 = 2, std::size_t P2 = P1>\n  struct FixedDerCubic\n  {\n    /// @brief Polynomial degree\n    static constexpr int Degree = 3;\n    /// @brief Optimization degree (absolute integral of derivative OptDeg is minimized)\n    static constexpr int OptDeg = -1;\n    /// @brief Number of derivatives to enforce continuity for\n    static constexpr int InnCnt = 2;\n\n    /// @brief Degrees of left-side boundary constraints: P1\n    static constexpr std::array<int, 1> LeftDeg{P1};\n    /// @brief Values of left-side boundary constraints\n    std::array<Tangent<G>, 1> left_values{Tangent<G>::Zero()};\n\n    /// @brief Degrees of right-side boundary constraints: P2\n    static constexpr std::array<int, 1> RghtDeg{P2};\n    /// @brief Values of right-side boundary constraints\n    std::array<Tangent<G>, 1> rght_values{Tangent<G>::Zero()};\n  };\n\n  /**\n   * @brief SplineSpec for optimized spline.\n   *\n   * @tparam K spline degree\n   * @tparam O order to optimize\n   * @tparam P continuity order\n   */\n  template<LieGroup G, std::size_t K = 6, std::size_t O = 3, std::size_t P = 3>\n  struct MinDerivative\n  {\n    /// @brief Polynomial degree\n    static constexpr int Degree = K;\n    /// @brief Optimization degree (absolute integral of derivative OptDeg is minimized)\n    static constexpr int OptDeg = O;\n    /// @brief Number of derivatives to enforce continuity for\n    static constexpr int InnCnt = P;\n\n    /// @brief Degrees of left-side boundary constraints: 1, 2, ..., P-1\n    static constexpr std::array<int, P - 1> LeftDeg = []() {\n      std::array<int, P - 1> ret;\n      for (auto i = 0u; i < P - 1; ++i) { ret[i] = i + 1; }\n      return ret;\n    }();\n\n    /// @brief Values of left-side boundary constraints\n    std::array<Tangent<G>, P - 1> left_values = []() {\n      std::array<Tangent<G>, P - 1> ret;\n      ret.fill(Tangent<G>::Zero());\n      return ret;\n    }();\n\n    /// @brief Degrees of left-side boundary constraints: 1, 2, ..., P-1\n    static constexpr std::array<int, P - 1> RghtDeg = LeftDeg;\n    /// @brief Values of right-side boundary constraints\n    std::array<Tangent<G>, P - 1> rght_values = left_values;\n  };\n\n}  // namespace spline_specs\n\n// \\cond\nnamespace detail {\n\ntemplate<SplineSpec SS>\nconstexpr int splinespec_max_deriv()\n{\n  int ret = std::max<int>(0, SS::InnCnt);\n\n  for (const auto & x : SS::LeftDeg) { ret = std::max(ret, x); }\n  for (const auto & x : SS::RghtDeg) { ret = std::max(ret, x); }\n\n  return ret;\n}\n\ntemplate<SplineSpec T>\nstruct splinespec_extract;\n\ntemplate<template<LieGroup, std::size_t...> typename T, LieGroup G, std::size_t... Is>\nstruct splinespec_extract<T<G, Is...>>\n{\n  using group = G;\n};\n\ntemplate<SplineSpec T, LieGroup Gnew>\nstruct splinespec_rebind;\n\ntemplate<\n  template<LieGroup, std::size_t...>\n  typename T,\n  LieGroup Gold,\n  LieGroup Gnew,\n  std::size_t... Is>\nstruct splinespec_rebind<T<Gold, Is...>, Gnew>\n{\n  using type = T<Gnew, Is...>;\n};\n\ntemplate<SplineSpec SS>\nauto splinespec_project(const SS & ss, std::size_t k)\n{\n  using Scalar = Scalar<typename splinespec_extract<SS>::group>;\n\n  typename splinespec_rebind<SS, Scalar>::type ret;\n  for (auto i = 0u; i < ss.LeftDeg.size(); ++i) {\n    ret.left_values[i] = ss.left_values[i].template segment<1>(k);\n  }\n  for (auto i = 0u; i < ss.RghtDeg.size(); ++i) {\n    ret.rght_values[i] = ss.rght_values[i].template segment<1>(k);\n  }\n  return ret;\n}\n\n}  // namespace detail\n// \\endcond\n\n/**\n * @brief Find N degree K Bernstein polynomials p_i(t) for i = 0, ..., N s.t that satisfies\n * constraints and s.t.\n * \\f[\n *   p_i(0) = 0 \\\\\n *   p_i(\\delta t) = \\delta x\n * \\f]\n *\n * @param dt_r range of parameter differences \\f$ \\delta_t \\f$\n * @param dx_r range of value differences \\f$ \\delta_x \\f$\n * @param ss spline specification\n * @return vector \\f$ \\alpha \\f$ of size (K + 1) * N s.t. \\f$ \\beta = \\alpha_{i (K + 1): (i + 1) (K\n * + 1) } \\f$ defines polynomial \\f$ p_i \\f$ as \\f[ p_i(t) = \\sum_{\\nu = 0}^K \\beta_\\nu b_{\\nu, k}\n * \\left( \\frac{t}{\\delta t} \\right), \\f] where \\f$ \\delta t \\f$ is the i:th member of \\p dt_r.\n *\n * @note Allocates heap memory.\n */\nEigen::VectorXd fit_spline_1d(\n  std::ranges::sized_range auto && dt_r,\n  std::ranges::sized_range auto && dx_r,\n  const SplineSpec auto & ss)\n{\n  using namespace std::views;\n\n  using SS = std::decay_t<decltype(ss)>;\n\n  const std::size_t N = std::min(std::ranges::size(dt_r), std::ranges::size(dx_r));\n\n  // coefficient layout is\n  //   [ x0 x1   ...   Xn ]\n  // where p_i(t) = \\sum_k x_i[k] * b_{i,k}(t) defines p on [tvec(i), tvec(i+1)]\n\n  static constexpr auto K = SS::Degree;\n  static constexpr auto D = detail::splinespec_max_deriv<SS>();\n\n  static_assert(K >= D, \"K >= D\");\n\n  // compile-time matrix algebra\n  static constexpr auto B_s    = polynomial_basis<PolynomialBasis::Bernstein, K>();\n  static constexpr auto U0_s   = monomial_derivatives<K, D>(0.);\n  static constexpr auto U1_s   = monomial_derivatives<K, D>(1.);\n  static constexpr auto U0tB_s = U0_s * B_s;\n  static constexpr auto U1tB_s = U1_s * B_s;\n\n  Eigen::Map<const Eigen::Matrix<double, D + 1, K + 1, Eigen::RowMajor>> U0tB(U0tB_s[0].data());\n  Eigen::Map<const Eigen::Matrix<double, D + 1, K + 1, Eigen::RowMajor>> U1tB(U1tB_s[0].data());\n\n  // d:th derivative of basis polynomial at 0 (resp. 1) is now U0tB.row(d) * x (resp. U1tB.row(d) *\n  // x), where x are the coefficients.\n\n  const std::size_t N_coef = (K + 1) * N;\n  const std::size_t N_eq   = ss.LeftDeg.size()                            // left endpoint\n                         + N                                              // value left-segment\n                         + (SS::InnCnt >= 0 ? N : 0)                      // value rght-segment\n                         + (SS::InnCnt > 0 ? (N - 1) * (SS::InnCnt) : 0)  // derivative continuity\n                         + ss.RghtDeg.size();                             // right endpiont\n\n  assert(N_coef >= N_eq);\n\n  // CONSTRAINT MATRICES A, b\n\n  Eigen::SparseMatrix<double, Eigen::ColMajor> A(N_eq, N_coef);\n  Eigen::VectorXi A_pattern(N_coef);\n  A_pattern.head(K + 1).setConstant(1 + ss.LeftDeg.size() + (SS::InnCnt >= 0 ? 1 + SS::InnCnt : 0));\n  if (N >= 2) {\n    A_pattern.segment(K + 1, (N - 2) * (K + 1))\n      .setConstant(1 + (SS::InnCnt >= 0 ? 1 + 2 * SS::InnCnt : 0));\n  }\n  A_pattern.tail(K + 1).setConstant(1 + ss.RghtDeg.size() + (SS::InnCnt >= 0 ? 1 + SS::InnCnt : 0));\n  A.reserve(A_pattern);\n\n  Eigen::VectorXd b = Eigen::VectorXd::Zero(N_eq);\n\n  // current inequality counter\n  std::size_t M = 0;\n\n  // curve beg derivative constraints\n  for (auto i = 0u; i < ss.LeftDeg.size(); ++i) {\n    for (auto j = 0u; j < K + 1; ++j) { A.insert(M, j) = U0tB(ss.LeftDeg[i], j); }\n    b(M++) = ss.left_values[i].x();\n  }\n\n  // interval beg + end value constraint\n  for (const auto & [i, dx] : utils::zip(iota(0u), dx_r)) {\n    for (auto j = 0; j < K + 1; ++j) { A.insert(M, i * (K + 1) + j) = U0tB(0, j); }\n    b(M++) = 0;\n    if (SS::InnCnt >= 0) {\n      for (auto j = 0; j < K + 1; ++j) { A.insert(M, i * (K + 1) + j) = U1tB(0, j); }\n      b(M++) = dx;\n    }\n  }\n\n  // inner derivative continuity constraint\n  for (const auto & [k, dt, dt_next] : utils::zip(iota(0u, N - 1), dt_r, dt_r | drop(1))) {\n    for (auto d = 1; d <= SS::InnCnt; ++d) {\n      const double fac1 = 1. / std::pow(dt, d);\n      const double fac2 = 1. / std::pow(dt_next, d);\n      for (auto j = 0; j < K + 1; ++j) {\n        A.insert(M, k * (K + 1) + j)       = U1tB(d, j) * fac1;\n        A.insert(M, (k + 1) * (K + 1) + j) = -U0tB(d, j) * fac2;\n      }\n      b(M++) = 0;\n    }\n  }\n\n  // curve end derivative constraints\n  for (auto i = 0u; i < ss.RghtDeg.size(); ++i) {\n    for (auto j = 0u; j < K + 1; ++j) {\n      A.insert(M, (K + 1) * (N - 1) + j) = U1tB(ss.RghtDeg[i], j);\n    }\n    b(M++) = ss.rght_values[i].x();\n  }\n\n  A.prune(1e-9);  // there are typically a lot of zeros (depends on basis)..\n  A.makeCompressed();\n\n  if constexpr (SS::OptDeg < 0) {\n    // No optimization, solve directly\n    assert(N_eq == N_coef);\n    Eigen::SparseLU<decltype(A)> lu(A);\n    return lu.solve(b);\n  } else {\n    static_assert(K >= SS::OptDeg, \"K >= OptDeg\");\n\n    // COST MATRIX P\n\n    // cost function is ∫ | p^{(D)} (t) |^2 dt,  t : 0 -> T,\n    // or (1 / T)^{2D - 1} ∫ | p^{(D)} (u) |^2 du,  u : 0 -> 1\n    //\n    // p(u) = u^{(D)}^T B x, so p^{(D)} (u)^2 = x' B' u^{(D)}' u^{(D)} B x\n    //\n    // Let M = \\int_{0}^1 u^{(D)} u^{(D)}' du   u : 0 -> 1, then the cost matrix P\n    // is (1 / T)^{2D - 1} * B' * M * B\n\n    static constexpr auto Mmat = monomial_integral<K, SS::OptDeg, double>();\n    static constexpr StaticMatrix<double, K + 1, K + 1> P_s = B_s.transpose() * Mmat * B_s;\n\n    Eigen::Map<const Eigen::Matrix<double, K + 1, K + 1, Eigen::RowMajor>> P(P_s[0].data());\n\n    // SOLVE QP\n\n    // We solve\n    //   min_{x : Ax = b}  (1/2) x' Q x\n    // by solving the KKT equations\n    //   [Q A'; A 0] [x; l] =   [0; b]\n    // via LDLt factorization\n\n    Eigen::SparseMatrix<double> H(N_coef + N_eq, N_coef + N_eq);\n\n    Eigen::Matrix<int, -1, 1> H_pattern(N_coef + N_eq);\n    for (auto i = 0u; i != N_coef; ++i) {\n      H_pattern(i) = (K + 1) + A.outerIndexPtr()[i + 1] - A.outerIndexPtr()[i];\n    }\n    H_pattern.tail(N_eq).setZero();\n\n    H.reserve(H_pattern);\n\n    for (const auto & [i, dt] : utils::zip(iota(0u), dt_r | take(int64_t(N)))) {\n      const double fac = std::pow(dt, 1 - 2 * int(D));\n      for (auto ki = 0u; ki != K + 1; ++ki) {\n        for (auto kj = 0u; kj != K + 1; ++kj) {\n          H.insert(i * (K + 1) + ki, i * (K + 1) + kj) = (ki == kj ? 1e-6 : 0.) + fac * P(ki, kj);\n        }\n      }\n    }\n\n    for (auto col = 0u; col != N_coef; ++col) {\n      for (typename decltype(A)::InnerIterator it(A, col); it; ++it) {\n        H.insert(N_coef + it.index(), col) = it.value();\n      }\n    }\n\n    H.makeCompressed();\n\n    Eigen::VectorXd rhs(N_coef + N_eq);\n    rhs.head(N_coef).setZero();\n    rhs.tail(N_eq) = b;\n\n    const Eigen::SimplicialLDLT<decltype(H), Eigen::Lower> ldlt(H);\n    return ldlt.solve(rhs).head(N_coef);\n  }\n}\n\n/**\n * @brief Fit a Spline to given points.\n *\n * @tparam G LieGroup\n * @tparam K Spline degree\n * @param ts range of times\n * @param gs range of values\n * @param ss spline specification\n * @return Spline c s.t. \\f$ c(t_i) = g_i \\f$ for \\f$(t_i, g_i) \\in zip(ts, gs) \\f$\n *\n * @note Allocates heap memory.\n */\nauto fit_spline(\n  std::ranges::random_access_range auto && ts,\n  std::ranges::random_access_range auto && gs,\n  const SplineSpec auto & ss)\n{\n  using namespace std::views;\n\n  using SS = std::decay_t<decltype(ss)>;\n  using G  = PlainObject<std::ranges::range_value_t<std::decay_t<decltype(gs)>>>;\n\n  assert(std::ranges::adjacent_find(ts, std::ranges::greater_equal()) == ts.end());\n\n  static constexpr auto K = SS::Degree;\n  const auto N            = std::min(std::ranges::size(ts), std::ranges::size(gs));\n\n  assert(N >= 2);\n\n  static constexpr auto sub     = [](const auto & x1, const auto & x2) { return x2 - x1; };\n  static constexpr auto sub_lie = [](const auto & x1, const auto & x2) { return rminus(x2, x1); };\n\n  auto dts = ts | utils::views::pairwise_transform(sub);\n  auto dgs = gs | utils::views::pairwise_transform(sub_lie);\n\n  Eigen::Matrix<double, Dof<G>, -1> V(Dof<G>, (N - 1) * (K + 1));\n\n  for (auto k = 0u; k < Dof<G>; ++k) {\n    const auto ss_proj = detail::splinespec_project(ss, k);\n    V.row(k) = fit_spline_1d(dts, dgs | transform([k](const auto & v) { return v(k); }), ss_proj);\n  }\n\n  Spline<K, G> ret;\n  ret.reserve(N);\n\n  for (const auto & [i, dt, g, g_next] : utils::zip(iota(0u), dts, gs, gs | drop(1))) {\n    // spline is in cumulative form, need to get cumulative coefficients\n    Eigen::Matrix<double, Dof<G>, K> cum_coefs =\n      V.template block<Dof<G>, K>(0, i * (K + 1) + 1) - V.template block<Dof<G>, K>(0, i * (K + 1));\n\n    if constexpr (K > 2) {\n      // modify segment to ensure it is interpolating\n      // want exp(v1) * ... * exp(vK) = inv(g) * gnext\n      auto mid = K / 2;\n\n      G midval = composition<G>(::smooth::inverse<G>(g), g_next);\n      for (auto k = 0; k < mid; ++k) {\n        midval = composition<G>(::smooth::exp<G>(-cum_coefs.col(k)), midval);\n      }\n      for (auto k = K - 1; k > mid; --k) {\n        midval = composition<G>(midval, ::smooth::exp<G>(-cum_coefs.col(k)));\n      }\n      cum_coefs.col(mid) = ::smooth::log<G>(midval);\n    }\n\n    ret.concat_global(Spline<K, G>(dt, std::move(cum_coefs), g));\n  }\n\n  ret.concat_global(gs[N - 1]);\n\n  return ret;\n}\n\n/**\n * @brief Fit a cubic Spline with natural boundary conditions\n *\n * @param ts range of times\n * @param gs range of values\n * @return Spline c s.t. \\f$ c(t_i) = g_i \\f$ for \\f$(t_i, g_i) \\in zip(ts, gs) \\f$\n *\n * @note Allocates heap memory.\n */\nauto fit_spline_cubic(std::ranges::range auto && ts, std::ranges::range auto && gs)\n{\n  using G = std::ranges::range_value_t<std::decay_t<decltype(gs)>>;\n  return fit_spline(\n    std::forward<decltype(ts)>(ts),\n    std::forward<decltype(gs)>(gs),\n    spline_specs::FixedDerCubic<G, 2, 2>{});\n}\n\n/**\n * @brief Objective struct for Bspline fitting with analytic jacobian.\n */\ntemplate<std::size_t K, std::ranges::range Rs, std::ranges::range Rg>\nstruct fit_bspline_objective\n{\n  using G = std::ranges::range_value_t<Rg>;\n\n  Rs ts;\n  Rg gs;\n\n  double t0, t1, dt;\n\n  std::size_t NumData, NumPts;\n\n  static constexpr auto M_s = polynomial_cumulative_basis<PolynomialBasis::Bspline, K>();\n  inline static const Eigen::Map<const Eigen::Matrix<double, K + 1, K + 1, Eigen::RowMajor>> M =\n    Eigen::Map<const Eigen::Matrix<double, K + 1, K + 1, Eigen::RowMajor>>(M_s[0].data());\n\n  fit_bspline_objective(\n    std::ranges::range auto && tsin, std::ranges::range auto && gsin, double dtin)\n      : ts(std::forward<decltype(tsin)>(tsin)), gs(std::forward<decltype(gsin)>(gsin)), dt(dtin)\n  {\n    const auto [rt0, rt1] = std::ranges::minmax(ts);\n\n    t0 = rt0;\n    t1 = rt1;\n\n    NumData = std::min(std::ranges::size(ts), std::ranges::size(gs));\n    NumPts  = K + static_cast<std::size_t>((t1 - t0 + dt) / dt);\n  }\n\n  Eigen::VectorXd operator()(const ManifoldVector<G> & var) const\n  {\n    using namespace std::views;\n\n    Eigen::VectorXd ret(Dof<G> * NumData);\n\n    for (const auto & [i, t, g] : utils::zip(iota(0u), ts, gs)) {\n      const int64_t istar = static_cast<int64_t>((t - t0) / dt);\n      const double u      = (t - t0 - istar * dt) / dt;\n\n      // gcc 11.1 bug can't handle uint64_t\n      const auto g_spline = cspline_eval<K>(var | drop(istar) | take(int64_t(K + 1)), M, u);\n\n      ret.segment<Dof<G>>(i * Dof<G>) = rminus(g_spline, g);\n    }\n\n    return ret;\n  }\n\n  Eigen::SparseMatrix<double> jacobian(const ManifoldVector<G> & var) const\n  {\n    using namespace std::views;\n\n    Eigen::SparseMatrix<double, Eigen::RowMajor> Jac;\n    Jac.resize(Dof<G> * NumData, Dof<G> * NumPts);\n    Jac.reserve(Eigen::Matrix<int, -1, 1>::Constant(Dof<G> * NumData, Dof<G> * (K + 1)));\n\n    for (const auto & [i, t, g] : utils::zip(iota(0u), ts, gs)) {\n      const int64_t istar = static_cast<int64_t>((t - t0) / dt);\n      const double u      = (t - t0 - istar * dt) / dt;\n\n      Eigen::Matrix<double, Dof<G>, (K + 1) * Dof<G>> d_vali_pts;\n      // gcc 11.1 bug can't handle uint64_t\n      auto g_spline =\n        cspline_eval<K>(var | drop(istar) | take(int64_t(K + 1)), M, u, {}, {}, d_vali_pts);\n\n      const Tangent<G> resi = rminus(g_spline, g);\n\n      const Eigen::Matrix<double, Dof<G>, Dof<G>> d_resi_vali          = dr_expinv<G>(resi);\n      const Eigen::Matrix<double, Dof<G>, (K + 1) * Dof<G>> d_resi_pts = d_resi_vali * d_vali_pts;\n\n      for (auto r = 0u; r != Dof<G>; ++r) {\n        for (auto c = 0u; c != Dof<G> * (K + 1); ++c) {\n          Jac.insert(i * Dof<G> + r, istar * Dof<G> + c) = d_resi_pts(r, c);\n        }\n      }\n    }\n\n    Jac.makeCompressed();\n\n    return Jac;\n  }\n};\n\n/**\n * @brief Fit a bpsline to data points \\f$(t_i, g_i)\\f$\n *        by solving the optimization problem\n *\n * \\f[\n *   \\min_{p}  \\left\\| p(t_i) - g_i \\right\\|^2\n * \\f]\n *\n * @tparam K bspline degree\n * @param ts time values t_i (doubles, strictly increasing)\n * @param gs data values t_i\n * @param dt distance between spline control points\n *\n * @note Allocates heap memory.\n */\ntemplate<std::size_t K>\nauto fit_bspline(std::ranges::range auto && ts, std::ranges::range auto && gs, const double dt)\n{\n  using namespace std::views;\n  using G = PlainObject<std::ranges::range_value_t<std::decay_t<decltype(gs)>>>;\n\n  assert(std::ranges::adjacent_find(ts, std::ranges::greater_equal()) == ts.end());\n\n  using obj_t = fit_bspline_objective<K, decltype(ts), decltype(gs)>;\n\n  obj_t obj(std::forward<decltype(ts)>(ts), std::forward<decltype(gs)>(gs), dt);\n\n  // create optimization variable\n  ManifoldVector<G> ctrl_pts(obj.NumPts);\n\n  // create initial guess\n  auto t_iter = std::ranges::begin(ts);\n  auto g_iter = std::ranges::begin(gs);\n  for (auto i = 0u; i != obj.NumPts; ++i) {\n    const double t_target = obj.t0 + (i - static_cast<double>(K - 1) / 2) * dt;\n    while (t_iter + 1 < std::ranges::end(ts)\n           && std::abs(t_target - *(t_iter + 1)) < std::abs(t_target - *t_iter)) {\n      ++t_iter;\n      ++g_iter;\n    }\n    ctrl_pts[i] = *g_iter;\n  }\n\n  // fit to data with loose convergence criteria\n  const MinimizeOptions opts{\n    .ptol     = 1e-3,\n    .ftol     = 1e-3,\n    .max_iter = 10,\n    .verbose  = false,\n  };\n  minimize<diff::Type::Analytic>(obj, smooth::wrt(ctrl_pts), opts);\n\n  return BSpline<K, G>(obj.t0, dt, std::move(ctrl_pts));\n}\n\n}  // namespace smooth\n\n#endif  // SMOOTH__SPLINE__FIT_HPP_\n", "meta": {"hexsha": "54b67639e62ee117fc9c351b4e9cfddb4c2e76dd", "size": 20918, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/spline/fit.hpp", "max_stars_repo_name": "pettni/smooth", "max_stars_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T21:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T13:26:44.000Z", "max_issues_repo_path": "include/smooth/spline/fit.hpp", "max_issues_repo_name": "pettni/lie", "max_issues_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2021-07-07T21:13:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T04:40:37.000Z", "max_forks_repo_path": "include/smooth/spline/fit.hpp", "max_forks_repo_name": "pettni/lie", "max_forks_repo_head_hexsha": "46270a5e6f95b7f5625eb8ce4da35c3133257e64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T07:16:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T14:29:44.000Z", "avg_line_length": 32.684375, "max_line_length": 100, "alphanum_fraction": 0.606128693, "num_tokens": 6648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4449897391730784}}
{"text": "//\n//  LinSysSolver.hpp\n//  OptCuts\n//\n//  Created by Minchen Li on 6/30/18.\n//\n\n#ifndef LinSysSolver_hpp\n#define LinSysSolver_hpp\n\n#include \"Types.hpp\"\n\n#include <Eigen/Eigen>\n#include <Eigen/Sparse>\n\n#include <set>\n#include <map>\n#include <iostream>\n\nnamespace OptCuts {\n    \n    template <typename vectorTypeI, typename vectorTypeS>\n    class LinSysSolver\n    {\n    protected:\n        int numRows;\n        Eigen::VectorXi ia, ja;\n        std::vector<std::map<int, int>> IJ2aI;\n        Eigen::VectorXd a;\n        \n    public:\n        virtual ~LinSysSolver(void) {};\n        \n    public:\n        virtual void set_type(int threadAmt, int _mtype, bool is_upper_half = false) = 0;\n        \n        virtual void set_pattern(const std::vector<std::set<int>>& vNeighbor,\n                                 const std::set<int>& fixedVert)\n        {\n            numRows = static_cast<int>(vNeighbor.size()) * DIM;\n            ia.resize(vNeighbor.size() * DIM + 1);\n            ia[0] = 1; // 1 + nnz above row i\n            ja.resize(0); // colI of each element\n            IJ2aI.resize(0); // map from matrix index to ja index\n            IJ2aI.resize(vNeighbor.size() * DIM);\n            for(int rowI = 0; rowI < vNeighbor.size(); rowI++) {\n                if(fixedVert.find(rowI) == fixedVert.end()) {\n                    int oldSize_ja = static_cast<int>(ja.size());\n                    IJ2aI[rowI * DIM][rowI * DIM] = oldSize_ja;\n                    IJ2aI[rowI * DIM][rowI * DIM + 1] = oldSize_ja + 1;\n                    if(DIM == 3) {\n                        IJ2aI[rowI * DIM][rowI * DIM + 2] = oldSize_ja + 2;\n                    }\n                    ja.conservativeResize(oldSize_ja + DIM);\n                    ja[oldSize_ja] = rowI * DIM + 1;\n                    ja[oldSize_ja + 1] = rowI * DIM + 2;\n                    if(DIM == 3) {\n                        ja[oldSize_ja + 2] = rowI * DIM + 3;\n                    }\n                    \n                    int nnz_rowI = 1;\n                    for(const auto& colI : vNeighbor[rowI]) {\n                        if(fixedVert.find(colI) == fixedVert.end()) {\n                            if(colI > rowI) {\n                                // only the lower-left part\n                                // colI > rowI means upper-right, but we are preparing CSR here\n                                // in a row-major manner and CHOLMOD is actually column-major\n                                int oldSize_ja_temp = static_cast<int>(ja.size());\n                                IJ2aI[rowI * DIM][colI * DIM] = oldSize_ja_temp;\n                                IJ2aI[rowI * DIM][colI * DIM + 1] = oldSize_ja_temp + 1;\n                                if(DIM == 3) {\n                                    IJ2aI[rowI * DIM][colI * DIM + 2] = oldSize_ja_temp + 2;\n                                }\n                                ja.conservativeResize(oldSize_ja_temp + DIM);\n                                ja[oldSize_ja_temp] = colI * DIM + 1;\n                                ja[oldSize_ja_temp + 1] = colI * DIM + 2;\n                                if(DIM == 3) {\n                                    ja[oldSize_ja_temp + 2] = colI * DIM + 3;\n                                }\n                                nnz_rowI++;\n                            }\n                        }\n                    }\n                    \n                    // another row for y,\n                    // excluding the left-bottom entry on the diagonal band\n                    IJ2aI[rowI * DIM + 1] = IJ2aI[rowI * DIM];\n                    for(auto& IJ2aI_newRow : IJ2aI[rowI * DIM + 1]) {\n                        IJ2aI_newRow.second += nnz_rowI * DIM - 1;\n                    }\n                    ja.conservativeResize(ja.size() + nnz_rowI * DIM - 1);\n                    ja.bottomRows(nnz_rowI * DIM - 1) = ja.block(oldSize_ja + 1, 0, nnz_rowI * DIM - 1, 1);\n                    \n                    if(DIM == 3) {\n                        // third row for z\n                        IJ2aI[rowI * DIM + 2] = IJ2aI[rowI * DIM + 1];\n                        for(auto& IJ2aI_newRow : IJ2aI[rowI * DIM + 2]) {\n                            IJ2aI_newRow.second += nnz_rowI * DIM - 2;\n                        }\n                        ja.conservativeResize(ja.size() + nnz_rowI * DIM - 2);\n                        ja.bottomRows(nnz_rowI * DIM - 2) = ja.block(oldSize_ja + 2, 0, nnz_rowI * DIM - 2, 1);\n                        \n                        IJ2aI[rowI * DIM + 2].erase(rowI * DIM);\n                        IJ2aI[rowI * DIM + 2].erase(rowI * DIM + 1);\n                    }\n                    IJ2aI[rowI * DIM + 1].erase(rowI * DIM);\n                    \n                    ia[rowI * DIM + 1] = ia[rowI * DIM] + nnz_rowI * DIM;\n                    ia[rowI * DIM + 2] = ia[rowI * DIM + 1] + nnz_rowI * DIM - 1;\n                    if(DIM == 3) {\n                        ia[rowI * DIM + 3] = ia[rowI * DIM + 2] + nnz_rowI * DIM - 2;\n                    }\n                }\n                else {\n                    int oldSize_ja = static_cast<int>(ja.size());\n                    IJ2aI[rowI * DIM][rowI * DIM] = oldSize_ja;\n                    IJ2aI[rowI * DIM + 1][rowI * DIM + 1] = oldSize_ja + 1;\n                    if(DIM == 3) {\n                        IJ2aI[rowI * DIM + 2][rowI * DIM + 2] = oldSize_ja + 2;\n                    }\n                    ja.conservativeResize(oldSize_ja + DIM);\n                    ja[oldSize_ja] = rowI * DIM + 1;\n                    ja[oldSize_ja + 1] = rowI * DIM + 2;\n                    if(DIM == 3) {\n                        ja[oldSize_ja + 2] = rowI * DIM + 3;\n                    }\n                    ia[rowI * DIM + 1] = ia[rowI * DIM] + 1;\n                    ia[rowI * DIM + 2] = ia[rowI * DIM + 1] + 1;\n                    if(DIM == 3) {\n                        ia[rowI * DIM + 3] = ia[rowI * DIM + 2] + 1;\n                    }\n                }\n            }\n            a.resize(ja.size());\n        }\n        virtual void set_pattern(const Eigen::SparseMatrix<double>& mtr) = 0; //NOTE: mtr must be SPD\n        \n        virtual void update_a(const vectorTypeI &II,\n                              const vectorTypeI &JJ,\n                              const vectorTypeS &SS)\n        {\n            //TODO: faster O(1) indices!!\n            \n            assert(II.size() == JJ.size());\n            assert(II.size() == SS.size());\n            \n            a.setZero(ja.size());\n            for(int tripletI = 0; tripletI < II.size(); tripletI++) {\n                int i = II[tripletI], j = JJ[tripletI];\n                if(i <= j) {\n                    //        if((i <= j) && (i != 2) && (j != 2)) {\n                    assert(i < IJ2aI.size());\n                    const auto finder = IJ2aI[i].find(j);\n                    assert(finder != IJ2aI[i].end());\n                    a[finder->second] += SS[tripletI];\n                }\n            }\n            //    a[IJ2aI[2].find(2)->second] = 1.0;\n        }\n        virtual void update_a(const Eigen::SparseMatrix<double>& mtr)\n        {\n            assert(0 && \"please implement in subclass!\");\n        }\n        \n        virtual void analyze_pattern(void) = 0;\n        \n        virtual bool factorize(void) = 0;\n        \n        virtual void solve(Eigen::VectorXd &rhs,\n                           Eigen::VectorXd &result) = 0;\n        \n        virtual void multiply(const Eigen::VectorXd& x,\n                              Eigen::VectorXd& Ax)\n        {\n            assert(x.size() == numRows);\n            assert(IJ2aI.size() == numRows);\n            \n            Ax.setZero(numRows);\n            for(int rowI = 0; rowI < numRows; ++rowI) {\n                for(const auto& colI : IJ2aI[rowI]) {\n                    Ax[rowI] += colI.second * x[colI.first];\n                    if(rowI != colI.first) {\n                        Ax[colI.first] += colI.second * x[rowI];\n                    }\n                }\n            }\n        }\n        \n    public:\n        virtual double coeffMtr(int rowI, int colI) const {\n            if(rowI > colI) {\n                // return only upper right part for symmetric matrix\n                int temp = rowI;\n                rowI = colI;\n                colI = temp;\n            }\n            assert(rowI < IJ2aI.size());\n            const auto finder = IJ2aI[rowI].find(colI);\n            if(finder != IJ2aI[rowI].end()) {\n                return a[finder->second];\n            }\n            else {\n                return 0.0;\n            }\n        }\n        virtual void getCoeffMtr(Eigen::SparseMatrix<double>& mtr) const {\n            mtr.resize(numRows, numRows);\n            mtr.setZero();\n            mtr.reserve(a.size() * 2 - numRows);\n            for(int rowI = 0; rowI < numRows; rowI++) {\n                for(const auto& colIter : IJ2aI[rowI]) {\n                    mtr.insert(rowI, colIter.first) = a[colIter.second];\n                    if(rowI != colIter.first) {\n                        mtr.insert(colIter.first, rowI) = a[colIter.second];\n                    }\n                }\n            }\n        }\n        virtual void setCoeff(int rowI, int colI, double val) {\n            //TODO: faster O(1) indices!!\n            \n            if(rowI <= colI) {\n                assert(rowI < IJ2aI.size());\n                const auto finder = IJ2aI[rowI].find(colI);\n                assert(finder != IJ2aI[rowI].end());\n                a[finder->second] = val;\n            }\n        }\n        virtual void setZero(void) {\n            a.setZero();\n        }\n        virtual void addCoeff(int rowI, int colI, double val) {\n            //TODO: faster O(1) indices!!\n            \n            if(rowI <= colI) {\n                assert(rowI < IJ2aI.size());\n                const auto finder = IJ2aI[rowI].find(colI);\n                assert(finder != IJ2aI[rowI].end());\n                a[finder->second] += val;\n            }\n        }\n        \n        virtual int getNumRows(void) const {\n            return numRows;\n        }\n        virtual int getNumNonzeros(void) const {\n            return a.size();\n        }\n        virtual const std::vector<std::map<int, int>>& getIJ2aI(void) const {\n            return IJ2aI;\n        }\n        virtual Eigen::VectorXi& get_ia(void) { return ia; }\n        virtual Eigen::VectorXi& get_ja(void) { return ja; }\n        virtual Eigen::VectorXd& get_a(void) { return a; }\n        virtual const Eigen::VectorXd& get_a(void) const { return a; }\n    };\n    \n}\n\n#endif /* LinSysSolver_hpp */\n", "meta": {"hexsha": "a92930283eedbff9ea384c67c8e6ad3f18e1294f", "size": 10483, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/LinSysSolver/LinSysSolver.hpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "src/LinSysSolver/LinSysSolver.hpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "src/LinSysSolver/LinSysSolver.hpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 40.1647509579, "max_line_length": 111, "alphanum_fraction": 0.415434513, "num_tokens": 2656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.44492776471970097}}
{"text": "// Copyright (c) 2017 University of Minnesota\n// \n// MCLSCENE Uses the BSD 2-Clause License (http://www.opensource.org/licenses/BSD-2-Clause)\n// Redistribution and use in source and binary forms, with or without modification, are\n// permitted provided that the following conditions are met:\n// 1. Redistributions of source code must retain the above copyright notice, this list of\n//    conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list\n//    of conditions and the following disclaimer in the documentation and/or other materials\n//    provided with the distribution.\n// THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR  A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF MINNESOTA, DULUTH OR CONTRIBUTORS BE \n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// By Matt Overby (http://www.mattoverby.net)\n\n#ifndef MCL_VEC3_H\n#define MCL_VEC3_H 1\n\n// Helper to hush api warnings\n#define MCL_UNUSED(x) (void)(x)\n\n#include <Eigen/Geometry>\n\nnamespace mcl {\n\n\t// Common types that I don't feel like typing out all the time:\n\ttemplate <typename T> using Vec4 = Eigen::Matrix<T,4,1>;\n\ttemplate <typename T> using Vec3 = Eigen::Matrix<T,3,1>;\n\ttemplate <typename T> using Vec2 = Eigen::Matrix<T,2,1>;\n\ttypedef Vec4<float> Vec4f;\n\ttypedef Vec3<float> Vec3f;\n\ttypedef Vec2<float> Vec2f;\n\ttypedef Vec4<double> Vec4d;\n\ttypedef Vec3<double> Vec3d;\n\ttypedef Vec2<double> Vec2d;\n\ttypedef Vec4<int> Vec4i;\n\ttypedef Vec3<int> Vec3i;\n\ttypedef Vec2<int> Vec2i;\n\nnamespace vec {\n\n\ttemplate <typename T> // Returns a normalized vector\n\tstatic inline Vec3<T> normalized(const Vec3<T> &v){ Vec3<T> t=v; t.normalize(); return t; }\n\n\ttemplate <typename T, size_t D> // Vec output as transpose with spaces instead of tabs\n\tstatic inline std::string to_str(const Eigen::Matrix<T,D,1> &v){\n\t\tstd::stringstream ss; ss << v[0];\n\t\tfor( size_t i=1; i<D; ++i ){ ss << ' ' << v[i]; }\n\t\treturn ss.str();\n\t}\n\n\ttemplate <typename T> // Compute barycentric coords for a point on a triangle\n\tstatic inline Vec3<T> barycoords(const Vec3<T> &p, const Vec3<T> &p0, const Vec3<T> &p1, const Vec3<T> &p2){\n\t\tVec3<T> v0 = p1 - p0, v1 = p2 - p0, v2 = p - p0;\n\t\tT d00 = v0.dot(v0);\n\t\tT d01 = v0.dot(v1);\n\t\tT d11 = v1.dot(v1);\n\t\tT d20 = v2.dot(v0);\n\t\tT d21 = v2.dot(v1);\n\t\tT invDenom = 1.0 / (d00 * d11 - d01 * d01);\n\t\tVec3<T> r;\n\t\tr[1] = (d11 * d20 - d01 * d21) * invDenom;\n\t\tr[2] = (d00 * d21 - d01 * d20) * invDenom;\n\t\tr[0] = 1.0 - r[1] - r[2];\n\t\treturn r;\n\t}\n\n\ttemplate <typename T> // scalar triple product\n\tstatic inline T scalar_triple_product( const Vec3<T> &u, const Vec3<T> &v, const Vec3<T> &w ){ return u.dot(v.cross(w)); }\n\t\n\ttemplate <typename T> // Compute barycentric coords for a point in a tet\n\tstatic inline Vec4<T> barycoords(const Vec3<T> &p, const Vec3<T> &a, const Vec3<T> &b, const Vec3<T> &c, const Vec3<T> &d){\n\t\tVec3<T> vap = p - a;\n\t\tVec3<T> vbp = p - b;\n\t\tVec3<T> vab = b - a;\n\t\tVec3<T> vac = c - a;\n\t\tVec3<T> vad = d - a;\n\t\tVec3<T> vbc = c - b;\n\t\tVec3<T> vbd = d - b;\n\t\tT va6 = scalar_triple_product(vbp, vbd, vbc);\n\t\tT vb6 = scalar_triple_product(vap, vac, vad);\n\t\tT vc6 = scalar_triple_product(vap, vad, vab);\n\t\tT vd6 = scalar_triple_product(vap, vab, vac);\n\t\tT v6 = 1.0 / scalar_triple_product(vab, vac, vad);\n\t\treturn Vec4<T>(va6*v6, vb6*v6, vc6*v6, vd6*v6);\n\t}\n\t\n\ttemplate <typename T> // Spherical coords to cartesian\n\tstatic inline Vec3<T> spherical_to_cartesian(T theta, T phi){\n\t\tT sin_t = std::sin(theta); T cos_t = std::cos(theta);\n\t\tT sin_p = std::sin(phi); T cos_p = std::cos(phi);\n\t\treturn Vec3<T>( sin_t * sin_p, sin_t * cos_p, cos_t );\n\t}\n\n\ttemplate <typename T>  // Cartesian coords to spherical\n\tstatic inline Vec2<T> cartesian_to_spherical(const Vec3<T> &v){\n\t\tVec2<T> r( std::acos(v[2]), std::atan2(v[1], v[0]) );\n\t\tif(r[1] < 0){ r[1] += 2*M_PI; }\n\t\treturn r;\n\t}\n\n} // end namespace vec\n\n// Randoms (u1, u2, etc...): 0 to 1\n// Putting it here until I find a better spot\nnamespace sample {\n\n\ttemplate<typename T> // Uniformly samples a cone (e.g. spotlight)\n\tstatic inline Vec3<T> uniform_cone( T u1, T u2, T max_theta ){\n\t\tT cos_theta = (1 - u1) + u1 * std::cos(max_theta);\n\t\tT sin_theta = std::sqrt(1 - cos_theta*cos_theta);\n\t\tT phi = u2 * 2 * M_PI;\n\t\treturn Vec3<T>( std::cos(phi)*sin_theta, std::sin(phi)*sin_theta, cos_theta );\n\t}\n\n\ttemplate<typename T> // Cosine weighted hemisphere sampling (e.g. diffuse reflection)\n\tstatic inline Vec3<T> cosine_hemisphere( T u1, T u2 ){\n\t\tT r = std::sqrt( u1 );\n\t\tT theta = 2 * M_PI * u2;\n\t\treturn Vec3<T>( r * std::cos(theta), r * std::sin(theta), std::sqrt( std::max(T(0), T(1.f-u1)) ) );\n\t}\n\n}; // end namespace sample\n\n} // end namespace mcl\n\n/*\n//\n//\ttrimesh and mcl::Vec xforms:\n//\nnamespace trimesh {\n\n\ttemplate <typename T, typename U>\n\tstatic inline mcl::Vec3<T> operator*(const trimesh::XForm<U> &m, const mcl::Vec3<T> &v){\n\t\tmcl::Vec3<T> r;\n\t\tr[0] = m[0]*v[0]+m[4]*v[1]+m[8]*v[2]+m[12];\n\t\tr[1] = m[1]*v[0]+m[5]*v[1]+m[9]*v[2]+m[13];\n\t\tr[2] = m[2]*v[0]+m[6]*v[1]+m[10]*v[2]+m[14];\n\t\treturn r;\n\t}\n\n\ttemplate <typename T, typename U>\n\tstatic inline mcl::Vec4<T> operator*(const trimesh::XForm<U> &m, const mcl::Vec4<T> &v){\n\t\tmcl::Vec4<T> r;\n\t\tr[0] = m[0]*v[0]+m[4]*v[1]+m[8]*v[2]+m[12]*v[3];\n\t\tr[1] = m[1]*v[0]+m[5]*v[1]+m[9]*v[2]+m[13]*v[3];\n\t\tr[2] = m[2]*v[0]+m[6]*v[1]+m[10]*v[2]+m[14]*v[3];\n\t\tr[3] = m[3]*v[0]+m[7]*v[1]+m[11]*v[2]+m[15]*v[3];\n\t\treturn r;\n\t}\n\n} // end namespace trimesh\n*/\n\n#endif\n", "meta": {"hexsha": "9c4c0c537eb37326aed4240db26f0135960fcdb1", "size": 6003, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "admm_anderson_xzu/deps/mclscene/include/MCL/Vec.hpp", "max_stars_repo_name": "bldeng/AA-ADMM", "max_stars_repo_head_hexsha": "d954518e8e379c378fd40ac72e2bcc64ff01cc57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2019-11-07T15:05:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T00:40:12.000Z", "max_issues_repo_path": "admm_anderson_xzu/deps/mclscene/include/MCL/Vec.hpp", "max_issues_repo_name": "wangxihao/AA-ADMM", "max_issues_repo_head_hexsha": "d954518e8e379c378fd40ac72e2bcc64ff01cc57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "admm_anderson_xzu/deps/mclscene/include/MCL/Vec.hpp", "max_forks_repo_name": "wangxihao/AA-ADMM", "max_forks_repo_head_hexsha": "d954518e8e379c378fd40ac72e2bcc64ff01cc57", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T02:47:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T07:00:44.000Z", "avg_line_length": 37.0555555556, "max_line_length": 124, "alphanum_fraction": 0.658837248, "num_tokens": 2044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.44479055474229706}}
{"text": "#include <utility>\n#include <random>\n#include \"Gain.h\"\n#include <Eigen/Core>\n#include <Eigen/Eigen>\n#include <Gain.h>\n#include <valarray>\n#include <set>\n#include <iostream>\n#include \"RNG.h\"\n#include \"Utils.h\"\n\nusing Eigen::VectorXd;\nusing Eigen::MatrixXd;\n\n\nGain::Gain(std::set<double> new_times_amp, std::set<double> new_times_phase) :\n    logamp_amp(-3.0),\n    logamp_phase(-2.0),\n    logscale_amp(7.0),\n    logscale_phase(5.0),\n    phase_mean(0.0)\n\n    {\n    // Get unique times of gain amplitudes\n    std::vector<double> times_amp_vec;\n    times_amp_vec.assign(new_times_amp.begin(), new_times_amp.end());\n    // Get unique times of gain phases\n    std::vector<double> times_phase_vec;\n    times_phase_vec.assign(new_times_phase.begin(), new_times_phase.end());\n    // Convert to Eigen VectorXd\n    times_amp = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(times_amp_vec.data(), times_amp_vec.size());\n    times_phase = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(times_phase_vec.data(), times_phase_vec.size());\n\n    amplitudes = std::valarray<double>(1.0, times_amp.size());\n    phases = std::valarray<double>(0.0, times_amp.size());\n    v_amp = std::valarray<double>(0.0, times_amp.size());\n    v_phase = std::valarray<double>(0.0, times_phase.size());\n    C_amp = MatrixXd(times_amp.size(), times_amp.size());\n    C_phase = MatrixXd(times_phase.size(), times_phase.size());\n    L_amp = MatrixXd(times_amp.size(), times_amp.size());\n    L_phase = MatrixXd(times_phase.size(), times_phase.size());\n\n    calculate_C_amp();\n    calculate_C_phase();\n    calculate_L_amp();\n    calculate_L_phase();\n    }\n\n\nGain::Gain(std::set<double> new_times) :\n    logamp_amp(-3.0),\n    logamp_phase(-2.0),\n    logscale_amp(7.0),\n    logscale_phase(5.0),\n    phase_mean(0.0)\n\n    {\n    // Get unique times of gain amplitude & phase\n    std::vector<double> times_vec;\n    times_vec.assign(new_times.begin(), new_times.end());\n    // Convert to Eigen VectorXd\n    times_amp = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(times_vec.data(), times_vec.size());\n    times_phase = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(times_vec.data(), times_vec.size());\n\n    amplitudes = std::valarray<double>(1.0, times_amp.size());\n    phases = std::valarray<double>(0.0, times_amp.size());\n    v_amp = std::valarray<double>(0.0, times_amp.size());\n    v_phase = std::valarray<double>(0.0, times_phase.size());\n    C_amp = MatrixXd(times_amp.size(), times_amp.size());\n    C_phase = MatrixXd(times_phase.size(), times_phase.size());\n    L_amp = MatrixXd(times_amp.size(), times_amp.size());\n    L_phase = MatrixXd(times_phase.size(), times_phase.size());\n\n    calculate_C_amp();\n    calculate_C_phase();\n    calculate_L_amp();\n    calculate_L_phase();\n    }\n\n\n//Gain::Gain(const Gain &other) {\n//    logamp_amp = other.logamp_amp;\n//    logamp_phase = other.logamp_phase;\n//    logscale_amp = other.logscale_amp;\n//    logscale_phase = other.logscale_phase;\n//    times_amp = other.times_amp;\n//    times_phase = other.times_phase;\n//    amplitudes =other.amplitudes;\n//    phases = other.phases;\n//    v_amp = other.v_amp;\n//    v_phase = other.v_phase;\n//    C_amp = other.C_amp;\n//    C_phase = other.C_phase;\n//    L_amp = other.L_amp;\n//    L_phase = other.L_phase;\n//}\n\n\nvoid Gain::print_times(std::ostream &out) const\n{\n    out << \"times amp = \" << std::endl;\n    for (int i=0; i<times_amp.size(); i++) {\n        out << times_amp[i] << \", \";\n    }\n    out << std::endl;\n\n    out << \"times phase = \" << std::endl;\n    for (int i=0; i<times_phase.size(); i++) {\n        out << times_phase[i] << \", \";\n    }\n    out << std::endl;\n\n}\n\n\nvoid Gain::print_hp(std::ostream &out) const\n{\n    out << \"For amplitude: logamplitude = \" << logamp_amp << \", \" << \"logscale = \" << logscale_amp << std::endl;\n    out << \"For phase: logamplitude = \" << logamp_phase << \", \" << \"logscale = \" << logscale_phase << std::endl;\n\n}\n\n\nvoid Gain::print_v(std::ostream &out) const\n{\n    out << \"v amp = \" << std::endl;\n    for (int i=0; i<v_amp.size(); i++) {\n        out << v_amp[i] << \", \";\n    }\n    out << std::endl;\n\n    out << \"v_phase = \" << std::endl;\n    for (int i=0; i<v_phase.size(); i++) {\n        out << v_phase[i] << \", \";\n    }\n    out << std::endl;\n}\n\n\nvoid Gain::print_C(std::ostream &out) const\n{\n    out << \"C amp = \" << std::endl;\n    out << C_amp << std::endl;\n    out << \"C phase = \" << std::endl;\n    out << C_phase << std::endl;\n}\n\n\nvoid Gain::print_L(std::ostream &out) const\n{\n    out << \"L amp = \" << std::endl;\n    out << L_amp << std::endl;\n    out << \"L phase= \" << std::endl;\n    out << L_phase << std::endl;\n}\n\n\nvoid Gain::set_hp_amp(std::valarray<double> params) {\n    logamp_amp = params[0];\n    logscale_amp = params[1];\n}\n\n\nvoid Gain::set_hp_phase(std::valarray<double> params) {\n    logamp_phase = params[0];\n    logscale_phase = params[1];\n}\n\n\n//void Gain::set_v_amp(std::valarray<double> params) {\n//    v_amp = std::move(params);\n//}\n//\n//\n//void Gain::set_v_phase(std::valarray<double> params) {\n//    v_phase = std::move(params);\n//}\n\n\nvoid Gain::from_prior_v_amp() {\n    //v_amp = make_normal_random(size_amp());\n    v_amp = std::valarray<double> (0.0, size_amp());\n}\n\n\nvoid Gain::from_prior_v_phase() {\n    //v_phase = make_normal_random(size_phase());\n    v_phase = std::valarray<double> (0.0, size_phase());\n}\n\n\nvoid Gain::from_prior_phase_mean(DNest4::RNG& rng) {\n    //phase_mean = -1.0*M_PI + 2.0*M_PI*rng.rand();\n    phase_mean = 0.0;\n}\n\n\nvoid Gain::from_prior_hp_amp(DNest4::RNG& rng) {\n    //std::cout << \"Generating from prior Gain HP AMP\" << std::endl;\n    //logamp_amp = -3.0 + 1.0*rng.randn();\n    //logscale_amp = 7.0 + 1.0*rng.randn();\n    logamp_amp = -3.0;\n    logscale_amp = 7.0;\n}\n\n\nvoid Gain::from_prior_hp_phase(DNest4::RNG& rng) {\n    //logamp_phase = -3.0 + 1.0*rng.randn();\n    //logscale_phase = 5.0 + 1.0*rng.randn();\n    logamp_phase = -2.0;\n    logscale_phase = 5.0;\n}\n\n\nvoid Gain::calculate_C_amp() {\n    //std::cout << \"Calculating C of amp GP\" << std::endl;\n    Eigen::MatrixXd sqdist = - 2*times_amp*times_amp.transpose();\n    sqdist.rowwise() += times_amp.array().square().transpose().matrix();\n    sqdist.colwise() += times_amp.array().square().matrix();\n    sqdist *= (-0.5/(exp(2.0*logscale_amp)));\n    C_amp = exp(logamp_amp) * sqdist.array().exp();\n}\n\n\nvoid Gain::calculate_C_phase() {\n    Eigen::MatrixXd sqdist = - 2*times_phase*times_phase.transpose();\n    sqdist.rowwise() += times_phase.array().square().transpose().matrix();\n    sqdist.colwise() += times_phase.array().square().matrix();\n    sqdist *= (-0.5/(exp(2.0*logscale_phase)));\n    C_phase = exp(logamp_phase) * sqdist.array().exp();\n}\n\n\nvoid Gain::calculate_L_amp() {\n    //std::cout << \"Calculating L of amp GP\" << std::endl;\n    // perform the Cholesky decomposition of covariance matrix\n    Eigen::LLT<Eigen::MatrixXd> cholesky = C_amp.llt();\n    // get the lower triangular matrix L\n    L_amp = cholesky.matrixL();\n}\n\n\nvoid Gain::calculate_L_phase() {\n    // perform the Cholesky decomposition of covariance matrix\n    Eigen::LLT<Eigen::MatrixXd> cholesky = C_phase.llt();\n    // get the lower triangular matrix L\n    L_phase = cholesky.matrixL();\n}\n\n\nint Gain::size_amp() {\n    return times_amp.size();\n}\n\n\nint Gain::size_phase() {\n    return times_phase.size();\n}\n\n\nstd::valarray<double>& Gain::get_amplitudes() {\n    return amplitudes;\n}\n\n\nstd::valarray<double>& Gain::get_phases() {\n    return phases;\n}\n\n\nvoid Gain::calculate_amplitudes() {\n    //std::cout << \"Calculating amplitudes\" << std::endl;\n    // Convert std::valarray ``v_amp`` to Eigen::VectorXd\n    VectorXd v_amp_vec = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(&v_amp[0], v_amp.size());\n\n\n    //// Debug print out v\n    //std::valarray<double> v_amp = std::valarray<double>(v_amp_vec.data(), v_amp_vec.size());\n    ////std::cout << \"V amplitudes = \" << std::endl;\n    //for (int i=0; i < times_amp.size(); i++) {\n    //    std::cout << v_amp[i] << \", \";\n    //}\n    //std::cout << std::endl;\n\n\n    VectorXd amp = L_amp*v_amp_vec;\n    // Convert Eigen::VectorXd to std::valarray\n    amplitudes = 1.0 + std::valarray<double>(amp.data(), amp.size());\n    //std::cout << \"Calculated amplitudes: \" << std::endl;\n    //print_amplitudes(std::cout);\n\n}\n\n\nvoid Gain::calculate_phases() {\n    // Convert std::valarray ``v_amp`` to Eigen::VectorXd\n    VectorXd v_phase_vec = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(&v_phase[0], v_phase.size());\n\n    VectorXd phase = L_phase*v_phase_vec;\n\n\n    //// Debug print out v\n    //std::valarray<double> v_phases = std::valarray<double>(v_phase_vec.data(), v_phase_vec.size());\n    //std::cout << \"V phases = \" << std::endl;\n    //for (int i=0; i < times_phase.size(); i++) {\n    //    std::cout << v_phases[i] << \", \";\n    //}\n    //std::cout << std::endl;\n\n\n    // Convert Eigen::VectorXd to std::valarray\n    phases = phase_mean + std::valarray<double>(phase.data(), phase.size());\n    //std::cout << \"Calculated phases: \" << std::endl;\n    //print_phases(std::cout);\n\n}\n\n\nvoid Gain::print_amplitudes(std::ostream &out) const {\n    out << \"amplitudes = \" << std::endl;\n    for (int i=0; i < times_amp.size(); i++) {\n        out << amplitudes[i] << \", \";\n    }\n    out << std::endl;\n}\n\n\nvoid Gain::print_phases(std::ostream &out) const {\n    out << \"phases = \" << std::endl;\n    for (int i=0; i < times_phase.size(); i++) {\n        out << phases[i] << \", \";\n    }\n    out << std::endl;\n}\n\n\ndouble Gain::perturb(DNest4::RNG &rng) {\n    double logH = 0.;\n\n    int which = rng.rand_int(2);\n    // Amplitude GP\n    if(which == 0) {\n\n        // Choose what value to perturb\n        int which = rng.rand_int(amplitudes.size());\n\n        logH -= -0.5*pow(v_amp[which], 2.0);\n        v_amp[which] += rng.randn();\n        logH += -0.5*pow(v_amp[which], 2.0);\n\n        // Pre-reject\n        if(rng.rand() >= exp(logH)) {\n            return -1E300;\n        }\n        else\n            logH = 0.0;\n\n        calculate_amplitudes();\n    }\n    // Phase GP\n    else {\n\n        // More often perturb phase latent variables\n        if(rng.rand() <= 0.9) {\n\n            // Choose what value to perturb\n            int which = rng.rand_int(phases.size());\n\n            logH -= -0.5*pow(v_phase[which], 2.0);\n            v_phase[which] += rng.randn();\n            logH += -0.5*pow(v_phase[which], 2.0);\n\n            // Pre-reject\n            if (rng.rand() >= exp(logH)) {\n                return -1E300;\n            } else\n                logH = 0.0;\n\n        }\n        else {\n            //logH -= -0.5*pow(phase_mean/1.5, 2.0);\n            phase_mean += 2.0*M_PI*rng.randh();\n            //logH += -0.5*pow(phase_mean/1.5, 2.0);\n            DNest4::wrap(phase_mean, -1.0*M_PI, M_PI);\n\n            //// Pre-reject\n            //if (rng.rand() >= exp(logH)) {\n            //    return -1E300;\n            //} else\n            //    logH = 0.0;\n        }\n\n        calculate_phases();\n\n    }\n\n    return logH;\n}\n\n\nstd::string Gain::description() const {\n    std::string descr;\n    for (int i = 0; i < times_amp.size(); i++) {\n        descr += (\"amp\" + std::to_string(i) + \" \");\n    }\n    descr += \"phase_mean \";\n    for (int i = 0; i < times_phase.size(); i++) {\n        descr += (\"phase\" + std::to_string(i) + \" \");\n    }\n    descr.pop_back();\n    return descr;\n}\n\n\nvoid Gain::print(std::ostream &out) const {\n    for (int i = 0; i < times_amp.size(); i++) {\n        out << amplitudes[i] << '\\t';\n    }\n    out << phase_mean << '\\t';\n    for (int i = 0; i < times_phase.size(); i++) {\n        out << phases[i] << '\\t';\n    }\n}\n\n\nstd::valarray<double> make_normal_random(int number)\n{\n    std::random_device rd;\n    std::normal_distribution<double> normalDistr(0, 1);\n    std::minstd_rand generator(rd());\n    std::valarray<double> randNums(number);\n\n    for (int i=0; i<number; i++) {\n        randNums[i] = normalDistr(generator);\n    }\n    return randNums;\n}", "meta": {"hexsha": "0b6b1830b4829ffea7e5f46e134dbcef6d23db14", "size": 11858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Gain.cpp", "max_stars_repo_name": "ipashchenko/bsc", "max_stars_repo_head_hexsha": "04d36db88fcd0ec2e4b7da4b0c68085491d653b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Gain.cpp", "max_issues_repo_name": "ipashchenko/bsc", "max_issues_repo_head_hexsha": "04d36db88fcd0ec2e4b7da4b0c68085491d653b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Gain.cpp", "max_forks_repo_name": "ipashchenko/bsc", "max_forks_repo_head_hexsha": "04d36db88fcd0ec2e4b7da4b0c68085491d653b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0730593607, "max_line_length": 112, "alphanum_fraction": 0.5898127846, "num_tokens": 3434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430562234877, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4447433433491077}}
{"text": "\n/*!\n * @file \n * @brief \n * @copyright alphya 2021\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef NYARUGA_UTIL_ALGEBRA_HPP\n#define NYARUGA_UTIL_ALGEBRA_HPP\n\n#pragma once\n\n#include <functional>\n#include <iostream>\n#include <concepts>\n#include <ranges>\n#include <ratio>\n#include <complex>\n#include <type_traits>\n#include <array>\n#include <algorithm>\n#include <utility>\n#include <boost/hana/functional/arg.hpp>\n\n#include <nyaruga_util/config.hpp>\n\n#ifdef NYARUGA_UTIL_HAS_TCBRINDLER_RATIONAL\n#    include <tcb/rational.hpp> // https://github.com/tcbrindle/rational.git\n#endif\n\nnamespace nyaruga {\n\nnamespace util {\n\nnamespace detail {\n\ntemplate <std::unsigned_integral  T = unsigned int>\nstruct N {\n    using value_type = T;\n    T value; \n    friend constexpr auto operator<=>(const N&, const N&) noexcept = default;\n    constexpr operator T() const noexcept { return value; }\n    constexpr N(T&& v) noexcept : value(std::forward<decltype(v)>(v)) {}\n};\n\ntemplate <std::floating_point T = double>\nstruct R {\n    using value_type = T;\n    T value; \n    friend constexpr auto operator<=>(const R&, const R&) noexcept = default;\n    constexpr operator T() const noexcept { return value; }\n    constexpr R(T&& v) noexcept : value(std::forward<decltype(v)>(v)) {}\n};\n\ntemplate <std::integral T = int>\nstruct Z {\n    using value_type = T;\n    T value; \n    friend constexpr auto operator<=>(const Z&, const Z&) noexcept = default;\n    constexpr operator T() const noexcept { return value; }\n    constexpr Z(T&& v) noexcept : value(std::forward<decltype(v)>(v)) {}\n};\n\ntemplate <typename T>\nconcept  arithmetic = std::is_arithmetic_v<T>;\n\n} // namespace detail\n\n// Number\n\nusing detail::N;\n\nusing detail::Z;\n\nusing detail::R;\n\n#ifdef NYARUGA_UTIL_HAS_TCBRINDLER_RATIONAL\ntemplate <std::integral T = int>\nusing Q = tcb::rational<T>;\n#endif\n\ntemplate <detail::arithmetic T = double>\nusing C = std::complex<T>;\n\n\nnamespace detail {\n\n// 足し算ができる\ntemplate <class T, class U>\nconcept weak_addable = requires (const std::remove_reference_t<T>& a, const std::remove_reference_t<U>& b) {\n  {a + b} -> std::common_with<T>;\n  {b + a} -> std::common_with<T>;\n  {a + b} -> std::common_with<U>;\n  {b + a} -> std::common_with<U>;\n};\n\n// 引き算ができる\ntemplate <class T, class U>\nconcept weak_subtractable = requires (const std::remove_reference_t<T>& a, const std::remove_reference_t<U>& b) {\n  {a - b} -> std::common_with<T>;\n  {b - a} -> std::common_with<T>;\n  {a - b} -> std::common_with<U>;\n  {b - a} -> std::common_with<U>;\n};\n\n// 掛け算ができる\ntemplate <class T, class U>\nconcept weak_multipliable = requires (const std::remove_reference_t<T>& a, const std::remove_reference_t<U>& b) {\n  {a * b} -> std::common_with<T>;\n  {b * a} -> std::common_with<T>;\n  {a * b} -> std::common_with<U>;\n  {b * a} -> std::common_with<U>;\n};\n\n//割り算ができる\ntemplate <class T, class U>\nconcept weak_dividable = requires (const std::remove_reference_t<T>& a, const std::remove_reference_t<U>& b){\n  {a / b} -> std::common_with<T>;\n  {b / a} -> std::common_with<T>;\n  {a / b} -> std::common_with<U>;\n  {b / a} -> std::common_with<U>;\n};\n\n} // namespace detail\n\n\n// concept\n\ntemplate <typename T>\nconcept addable = detail::weak_addable<T,T>;\n\ntemplate <typename T>\nconcept subtractable = detail::weak_subtractable<T,T>;\n\ntemplate <typename T>\nconcept multipliable = detail::weak_multipliable<T,T>;\n\ntemplate <typename T>\nconcept dividable = detail::weak_dividable<T,T>;\n\ntemplate <class T, class U>\nconcept addable_with =\n  addable<T> &&\n  addable<U> &&\n  std::common_reference_with<\n    const std::remove_reference_t<T>&,\n    const std::remove_reference_t<U>&> &&\n  addable<\n    std::common_reference_t<\n      const std::remove_reference_t<T>&,\n      const std::remove_reference_t<U>&>> &&\n  detail::weak_addable<T, U>;\n\ntemplate <class T, class U>\nconcept subtractable_with =\n  subtractable<T> &&\n  subtractable<U> &&\n  std::common_reference_with<\n    const std::remove_reference_t<T>&,\n    const std::remove_reference_t<U>&> &&\n  subtractable<\n    std::common_reference_t<\n      const std::remove_reference_t<T>&,\n      const std::remove_reference_t<U>&>> &&\n  detail::weak_subtractable<T, U>;\n\ntemplate <class T, class U>\nconcept multipliable_with =\n  multipliable<T> &&\n  multipliable<U> &&\n  std::common_reference_with<\n    const std::remove_reference_t<T>&,\n    const std::remove_reference_t<U>&> &&\n  multipliable<\n    std::common_reference_t<\n      const std::remove_reference_t<T>&,\n      const std::remove_reference_t<U>&>> &&\n  detail::weak_multipliable<T, U>;\n\ntemplate <class T, class U>\nconcept dividable_with =\n  dividable<T> &&\n  dividable<U> &&\n  std::common_reference_with<\n    const std::remove_reference_t<T>&,\n    const std::remove_reference_t<U>&> &&\n  dividable<\n    std::common_reference_t<\n      const std::remove_reference_t<T>&,\n      const std::remove_reference_t<U>&>> &&\n  detail::weak_dividable<T, U>;\n\ntemplate <typename T>\nconcept group = // std::equality_comparable<T> && // 等しさの検証が難しい対象もあるため ex) 関数環\n                                 addable<T> &&\n                                 subtractable<T>;\n\ntemplate <typename T>\nconcept abelian_group =  // C++ 上で普通の群と見分ける方法なし\n                                 // std::equality_comparable<T> &&\n                                 addable<T> &&\n                                 subtractable<T>;\n\ntemplate <typename T>\nconcept ring = // std::equality_comparable<T> &&\n                             addable<T> &&\n                             subtractable<T> && \n                             multipliable<T>;\n\ntemplate <typename T>\nconcept commutative_ring =  // C++ 上で普通の環と見分ける方法なし\n                             // std::equality_comparable<T> &&\n                             addable<T> &&\n                             subtractable<T> && \n                             multipliable<T>;\n\ntemplate <typename T>\nconcept field = // std::equality_comparable<T> &&\n                              addable<T> && \n                              subtractable<T> && \n                              multipliable<T> && \n                              dividable<T>;\n\n\nnamespace detail {\n\ntemplate <ring A = R<double>, size_t rank = 1>\nstruct module : std::array<A, rank>\n{\n    using std::array<A,rank>::array;\n    constexpr module() noexcept = default;\n    constexpr module(const std::array<A,rank>& a) : std::array<A,rank>::array(a) {};\n    constexpr module(std::array<A,rank>&& a) : std::array<A,rank>::array(std::move(a)) {};\n    template <std::same_as<A> ... T>\n    constexpr module(T ... list) : std::array<A,rank>::array({list...}) {};\n    friend constexpr auto operator<=>(const module&, const module&) noexcept = default;\n\n};\n\ntemplate <typename ... T>\nmodule(T ... list) -> module<std::remove_cvref_t<decltype(boost::hana::arg<1>(list...))> ,sizeof...(list)>;\n\nnamespace my_detail {\n\ntemplate <typename T, size_t N, size_t... I>\nconstexpr std::array<std::remove_cv_t<T>, N>\n    array_plus_impl(const std::array<T,N>& a, const std::array<T,N>& b, std::index_sequence<I...>)\n{\n    return { {(a[I]+b[I])...} };\n}\n\ntemplate <typename T, size_t N, size_t... I>\nconstexpr std::array<std::remove_cv_t<T>, N>\n    array_mult_impl(const T& a, const std::array<T,N>& b, std::index_sequence<I...>)\n{\n    return { {(a*b[I])...} };\n}\n\n}\n \ntemplate <typename T, size_t N>\nconstexpr module<T,N>  operator+(std::array<T,N>& a, std::array<T,N>& b)\n{\n    return my_detail::array_plus_impl(a, b,std::make_index_sequence<N>{});\n}\n\ntemplate <typename T, size_t N>\nconstexpr module<T,N>  operator*(const T& a, std::array<T,N>& b)\n{\n    return my_detail::array_mult_impl(a, b,std::make_index_sequence<N>{});\n}\n\n} // namespace detail\n\n\n// 加群\ntemplate <ring A, size_t rank>\nusing module_t = detail::module<A, rank>;\n\ntemplate <typename A, typename G>\nconcept module = ring<A> && abelian_group<G> &&\nrequires(const std::remove_reference_t<A>& a, const std::remove_reference_t<A>& b, \nconst std::remove_reference_t<G>& g, const std::remove_reference_t<G>&  h)\n{\n     {a*g} -> std::common_with<G>;\n     {g+h} -> std::common_with<G>;\n     {g-h} -> std::common_with<G>;\n     {a+b} -> std::common_with<A>;\n     {a*b}-> std::common_with<A>;\n     // { (a + b)(g + h) == (a+b)*g+(a+b)*h };\n};\n\n// 多元環または代数(algebra) 係数環の可換性を確かめられないので、C++上だと加群と変わらず\ntemplate <commutative_ring A, size_t rank>\nusing algebra_t = detail::module<A, rank>;\n\ntemplate <typename A, typename G>\nconcept algebra = module<A,G>;\n\n} // namespace util\n\n} // namespace nyaruga\n\n#endif // #ifndef NYARUGA_UTIL_ALGEBRA_HPP\n", "meta": {"hexsha": "508bf51e4abedc75027a1376fbd9e381b4ba0b50", "size": 8564, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nyaruga_util/algebra.hpp", "max_stars_repo_name": "alphya/nyaruga_util", "max_stars_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nyaruga_util/algebra.hpp", "max_issues_repo_name": "alphya/nyaruga_util", "max_issues_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nyaruga_util/algebra.hpp", "max_forks_repo_name": "alphya/nyaruga_util", "max_forks_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8957654723, "max_line_length": 113, "alphanum_fraction": 0.6335824381, "num_tokens": 2377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.44456123691432853}}
{"text": "/*=========================================================================\n\n  Program:   Visualization Toolkit\n  Module:    vtkRansacPlaneModel.cxx\n  Author: Pierre Guilbert\n\n  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n  All rights reserved.\n  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n  This software is distributed WITHOUT ANY WARRANTY; without even\n  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n  PURPOSE.  See the above copyright notice for more information.\n\n=========================================================================*/\n\n// LOCAL\n#include \"vtkRansacPlaneModel.h\"\n\n#include \"vtkConversions.h\"\n\n// STD\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n\n// VTK\n#include <vtkCellArray.h>\n#include <vtkCellData.h>\n#include <vtkDataArray.h>\n#include <vtkFloatArray.h>\n#include <vtkInformation.h>\n#include <vtkInformationVector.h>\n#include <vtkMath.h>\n#include <vtkNew.h>\n#include <vtkObjectFactory.h>\n#include <vtkPointData.h>\n#include <vtkPoints.h>\n#include <vtkPolyData.h>\n#include <vtkPolyLine.h>\n#include <vtkSmartPointer.h>\n#include <vtkStreamingDemandDrivenPipeline.h>\n#include <vtkTransform.h>\n#include <vtkTupleInterpolator.h>\n#include <vtkUnsignedCharArray.h>\n#include <vtkUnsignedIntArray.h>\n#include <vtkUnsignedShortArray.h>\n\n// BOOST\n#include <boost/algorithm/string.hpp>\n\n// Eigen\n#include <Eigen/Dense>\n\n//----------------------------------------------------------------------------\nstruct RansacSampleInfo\n{\npublic:\n  RansacSampleInfo() {}\n\n  RansacSampleInfo(unsigned int nInliers, unsigned int index1,\n                   unsigned int index2, unsigned int index3)\n  {\n    this->NInliers = nInliers;\n    this->Index1 = index1;\n    this->Index2 = index2;\n    this->Index3 = index3;\n  }\n\n  unsigned int NInliers;\n  unsigned int Index1;\n  unsigned int Index2;\n  unsigned int Index3;\n};\n\n//----------------------------------------------------------------------------\nvoid RefineRansac(std::vector<Eigen::Matrix<double, 3, 1> >& Points, vtkPolyData* output,\n                  RansacSampleInfo sampleInfo, double threshold, double PlaneParam[4])\n{\n  // Create inliers / outliers array information\n  vtkNew<vtkUnsignedIntArray> inliersArray;\n  inliersArray->SetName(\"ransac_plane_inliers\");\n\n  // compute plane PlaneParameters\n  Eigen::Matrix<double, 3, 1> pointPlane = Points[sampleInfo.Index1];\n  Eigen::Matrix<double, 3, 1> normalPlane = (Points[sampleInfo.Index3] - pointPlane).cross(Points[sampleInfo.Index2] - pointPlane);\n  normalPlane.normalize();\n\n  // compute inliers\n  std::vector<Eigen::Matrix<double, 3, 1> > inliersPoints;\n  for (unsigned int k = 0; k < Points.size(); ++k)\n  {\n    if (std::abs((Points[k] - pointPlane).dot(normalPlane)) < threshold)\n    {\n      inliersPoints.push_back(Points[k]);\n      inliersArray->InsertNextValue(1);\n    }\n    else\n    {\n      inliersArray->InsertNextValue(0);\n    }\n  }\n\n  // Now, compute the best plane using all inliers\n  Eigen::MatrixXd centeredSamples(3, inliersPoints.size());\n  Eigen::Matrix<double, 3, 1> center = Eigen::Matrix<double, 3, 1>::Zero();\n  for (unsigned int k = 0; k < inliersPoints.size(); ++k)\n  {\n    centeredSamples.col(k) = inliersPoints[k];\n    center += inliersPoints[k];\n  }\n  center /= static_cast<double>(inliersPoints.size());\n  for (unsigned int k = 0; k < inliersPoints.size(); ++k)\n  {\n    centeredSamples.col(k) -= center;\n  }\n  Eigen::Matrix<double, 3, 3> varianceCovariance = centeredSamples * centeredSamples.transpose();\n  varianceCovariance /= static_cast<double>(inliersPoints.size());\n\n  // since the variance covariance matrix is a real\n  // symmetric matrix it can be diagonalized in a orthonormal\n  // basis. We will use the AutoAdjoint eigen solver\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double, 3, 3> > eigenSolver(varianceCovariance);\n\n  // PlaneParameters\n  normalPlane = eigenSolver.eigenvectors().col(0);\n  pointPlane = center;\n  PlaneParam[0] = normalPlane(0);\n  PlaneParam[1] = normalPlane(1);\n  PlaneParam[2] = normalPlane(2);\n  PlaneParam[3] = -normalPlane.dot(pointPlane);\n\n  output->GetPointData()->AddArray(inliersArray.Get());\n}\n\n\n//----------------------------------------------------------------------------\nunsigned int ComputeNumberOfInlier(std::vector<Eigen::Matrix<double, 3, 1> >& Points, Eigen::Matrix<double, 3, 1> planePoint,\n                                   Eigen::Matrix<double, 3, 1> planeNormal, double threshold)\n{\n  unsigned int nInliers = 0;\n  for (unsigned int k = 0; k < Points.size(); ++k)\n  {\n    if (std::abs((Points[k] - planePoint).dot(planeNormal)) < threshold)\n    {\n      nInliers++;\n    }\n  }\n\n  return nInliers;\n}\n\n// Implementation of the New function\nvtkStandardNewMacro(vtkRansacPlaneModel)\n\n//----------------------------------------------------------------------------\nvtkRansacPlaneModel::vtkRansacPlaneModel()\n{\n  // 500 maximal ransac iteration\n  this->MaxRansacIteration = 500;\n\n  // 50 cm distance to plane threshold\n  this->Threshold = 0.5;\n\n  // 30% of inliers required\n  this->RatioInliersRequired = 0.30;\n\n  // fill PlaneParams with 0 values\n  std::fill(this->PlaneParam, this->PlaneParam + 4, 0);\n\n  this->AlignOutput = false;\n  this->TemporalAveraging = true;\n  this->MaxTemporalAngleChange = 45.0;\n  this->PreviousEstimationWeight = 0.9;\n}\n\n//----------------------------------------------------------------------------\nvtkRansacPlaneModel::~vtkRansacPlaneModel()\n{\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkRansacPlaneModel::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os, indent);\n}\n\n//-----------------------------------------------------------------------------\nint vtkRansacPlaneModel::RequestData(vtkInformation *vtkNotUsed(request),\n  vtkInformationVector **inputVector, vtkInformationVector *outputVector)\n{\n  // Save the previous plane estimate\n  double prevPlaneEst[4];\n  std::copy(this->PlaneParam, this->PlaneParam + 4, prevPlaneEst);\n\n  // Get the input\n  vtkPolyData * input = vtkPolyData::GetData(inputVector[0]->GetInformationObject(0));\n\n  // Get the output\n  vtkPolyData *output = vtkPolyData::GetData(outputVector->GetInformationObject(0));\n  output->ShallowCopy(input);\n\n  // Convert the point cloud in Eigen data structure point cloud\n  std::vector<Eigen::Vector3d> Points = vtkPointsToEigenVector(input->GetPoints());\n\n  // Create a random order of points index\n  std::vector<double> randomIndex(input->GetNumberOfPoints(), 0);\n  for (unsigned int k = 0; k < randomIndex.size(); ++k)\n  {\n    randomIndex[k] = k;\n  }\n  std::random_shuffle(randomIndex.begin(), randomIndex.end());\n\n  // information variable about ransac iterations\n  bool shouldStopRansac = false;\n  unsigned int iterationMade = 0;\n  unsigned int iterationPointer = 0;\n\n  // keep information of iterations\n  std::vector<RansacSampleInfo> samplesInfo;\n  unsigned int maxInliers = 0;\n  unsigned int indexMaxInliers = 0;\n\n  // Affine plane PlaneParameters\n  Eigen::Matrix<double, 3, 1> planeNormal, planePoint;\n\n  // indicate if ransac has \"converged\"\n  bool hasConverged = false;\n\n  // Ransac loop\n  while (!shouldStopRansac)\n  {\n    // if we went throught the all random index we need\n    // to random shuffle again\n    if ((iterationPointer + 2) >= randomIndex.size())\n    {\n      std::random_shuffle(randomIndex.begin(), randomIndex.end());\n      iterationPointer = 0;\n    }\n\n    // Compute current sample plane PlaneParameters\n    planePoint = Points[randomIndex[iterationPointer]];\n    planeNormal = (Points[randomIndex[iterationPointer + 2]] - planePoint).cross(Points[randomIndex[iterationPointer + 1]] - planePoint);\n    planeNormal.normalize();\n\n    // Compute the number of inliers / outliers\n    unsigned int nInliers = ComputeNumberOfInlier(Points, planePoint, planeNormal, this->Threshold);\n\n    // keep info\n    RansacSampleInfo info(nInliers, randomIndex[iterationPointer], randomIndex[iterationPointer + 1], randomIndex[iterationPointer + 2]);\n    samplesInfo.push_back(info);\n\n    if (nInliers > maxInliers)\n    {\n      maxInliers = nInliers;\n      indexMaxInliers = iterationMade;\n    }\n\n    // Check that the number of inliers is enought to\n    // break the ransac algorithm loop\n    if (nInliers > input->GetNumberOfPoints() * this->RatioInliersRequired)\n    {\n      shouldStopRansac = true;\n      hasConverged = true;\n    }\n\n    // check if the maximum iteration has been reached\n    if (iterationMade > this->MaxRansacIteration)\n    {\n      shouldStopRansac = true;\n    }\n\n    // Updates iterations index\n    iterationMade++;\n    iterationPointer += 3; \n  }\n\n  // Now refine using all inliers\n  RefineRansac(Points, output, samplesInfo[indexMaxInliers], this->Threshold, this->PlaneParam);\n\n  // output info\n  std::cout << \"ransac algorithm has converged: \" << hasConverged << std::endl;\n  std::cout << \"number of iteration made: \" << iterationMade << std::endl;\n  std::cout << \"number of inliers: \" << maxInliers << \", \" << samplesInfo[indexMaxInliers].NInliers << std::endl;\n  std::cout << \"plane PlaneParams: [\" << this->PlaneParam[0] << \",\" << this->PlaneParam[1] << \",\" << this->PlaneParam[2] << \",\" << this->PlaneParam[3] << \"]\" << std::endl;\n\n  // flip normal if needed\n  if (this->PlaneParam[2] < 0)\n  {\n    this->PlaneParam[0] *= -1.0;\n    this->PlaneParam[1] *= -1.0;\n    this->PlaneParam[2] *= -1.0;\n    this->PlaneParam[3] *= -1.0;\n  }\n\n  double d = this->PlaneParam[3];\n  Eigen::Vector3d n(this->PlaneParam[0], this->PlaneParam[1], this->PlaneParam[2]);\n  n.normalize();\n\n  // previous normal and bias estimation\n  Eigen::Vector3d nPrev(prevPlaneEst[0], prevPlaneEst[1], prevPlaneEst[2]);\n  double dPrev = prevPlaneEst[3];\n\n  double newEstimationWeight = 1.0 - this->PreviousEstimationWeight;  // how much do we trust the new plane estimate\n\n  if (this->TemporalAveraging && std::abs(nPrev.norm() - 1) < 1e-3)   // if the previous estimate is valid\n  {\n    // if the angle between the new normal estimate and the previous is larger than the threshold,\n    // the current normal is discarded\n    if (std::asin(n.cross(nPrev).norm()) > vtkMath::RadiansFromDegrees(MaxTemporalAngleChange))\n    {\n      n = nPrev;\n      d = dPrev;\n    }\n    else\n    {\n      // update the plane estimate with the current one\n      n = newEstimationWeight * n + this->PreviousEstimationWeight * nPrev;\n      d = newEstimationWeight * d + this->PreviousEstimationWeight * dPrev;\n    }\n  }\n  n.normalize();\n\n  this->PlaneParam[0] = n[0];\n  this->PlaneParam[1] = n[1];\n  this->PlaneParam[2] = n[2];\n  this->PlaneParam[3] = d;\n\n  // transform output if enabled\n  if (this->AlignOutput)\n  {\n    Eigen::Vector3d v = n.cross(Eigen::Vector3d::UnitZ());\n    double angle = std::asin(v.norm());\n    Eigen::AngleAxisd rot(angle, v.normalized());\n    Eigen::Vector3d shift(0.0, 0.0, d);\n\n    // transform points\n    for (auto& pt : Points)\n    {\n      pt =  rot * pt + shift;\n    }\n    // copy points to output\n    output->SetPoints(eigenVectorToVTKPoints(Points));\n  }\n\n  return 1;\n}\n", "meta": {"hexsha": "1b65dfc2cdd961a7a0d199023ff747b44e87692e", "size": 11034, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "VelodyneHDL/Filter/Ransac/vtkRansacPlaneModel.cxx", "max_stars_repo_name": "zhihua-wang/VeloView", "max_stars_repo_head_hexsha": "609d3e4c0cf722c512f4b0b2a615208557bb7757", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-10-28T07:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-28T07:03:50.000Z", "max_issues_repo_path": "VelodyneHDL/Filter/Ransac/vtkRansacPlaneModel.cxx", "max_issues_repo_name": "zactodd/VeloView", "max_issues_repo_head_hexsha": "e0bd72a32464a9f62385ac5ce25df33580ed3cc2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-17T13:25:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T21:26:11.000Z", "max_forks_repo_path": "VelodyneHDL/Filter/Ransac/vtkRansacPlaneModel.cxx", "max_forks_repo_name": "zactodd/VeloView", "max_forks_repo_head_hexsha": "e0bd72a32464a9f62385ac5ce25df33580ed3cc2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-08T11:28:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T11:28:59.000Z", "avg_line_length": 31.6160458453, "max_line_length": 171, "alphanum_fraction": 0.6471814392, "num_tokens": 2871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.444561230420087}}
{"text": "/*\n\nCopyright (c) 2005-2018, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#ifndef CELLWISESOURCEELLIPTICPDE_HPP_\n#define CELLWISESOURCEELLIPTICPDE_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"AbstractCellPopulation.hpp\"\n#include \"AbstractLinearEllipticPde.hpp\"\n\n/**\n * An elliptic PDE to be solved numerically using the finite element method, for\n * coupling to a cell-based simulation.\n *\n * The PDE takes the form\n *\n * Grad.(Grad(u)) + k*u*rho(x) = 0,\n *\n * where the scalar k is specified by the member mSourceCoefficient, whose value must\n * be set in the constructor.\n *\n * For a node of the finite element mesh with location x, the function rho(x)\n * equals one if there is a non-apoptotic cell associated with x, and\n * zero otherwise. Here, 'associated with' takes a different meaning for each\n * cell population class, and is encoded in the method IsPdeNodeAssociatedWithNonApoptoticCell().\n *\n * \\todo make member names and methods consistent with those of CellwiseSourceParabolicPde\n */\ntemplate<unsigned DIM>\nclass CellwiseSourceEllipticPde : public AbstractLinearEllipticPde<DIM,DIM>\n{\n    friend class TestCellBasedEllipticPdes;\n\nprivate:\n\n    /** Needed for serialization.*/\n    friend class boost::serialization::access;\n    /**\n     * Serialize the PDE and its member variables.\n     *\n     * @param archive the archive\n     * @param version the current version of this class\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n       archive & boost::serialization::base_object<AbstractLinearEllipticPde<DIM, DIM> >(*this);\n       archive & mSourceCoefficient;\n    }\n\nprotected:\n\n    /** The cell population member. */\n    AbstractCellPopulation<DIM, DIM>& mrCellPopulation;\n\n    /** Coefficient of the source term. */\n    double mSourceCoefficient;\n\npublic:\n\n    /**\n     * Constructor.\n     *\n     * @param rCellPopulation reference to the cell population\n     * @param sourceCoefficient the source term coefficient (defaults to 0.0)\n     */\n    CellwiseSourceEllipticPde(AbstractCellPopulation<DIM, DIM>& rCellPopulation, double sourceCoefficient=0.0);\n\n    /**\n     * @return const reference to the cell population (used in archiving).\n     */\n    const AbstractCellPopulation<DIM>& rGetCellPopulation() const;\n\n    /**\n     * @return mSourceCoefficient (used in archiving).\n     */\n    double GetCoefficient() const;\n\n    /**\n     * Overridden ComputeConstantInUSourceTerm() method.\n     *\n     * @param rX The point in space\n     * @param pElement The element\n     *\n     * @return the constant in u part of the source term, i.e g(x) in\n     *  Div(D Grad u)  +  f(x)u + g(x) = 0.\n     */\n    virtual double ComputeConstantInUSourceTerm(const ChastePoint<DIM>& rX, Element<DIM,DIM>* pElement);\n\n    /**\n     * Overridden ComputeLinearInUCoeffInSourceTerm() method.\n     *\n     * @param rX The point in space\n     * @param pElement the element\n     *\n     * @return the coefficient of u in the linear part of the source term, i.e f(x) in\n     *  Div(D Grad u)  +  f(x)u + g(x) = 0.\n     */\n    virtual double ComputeLinearInUCoeffInSourceTerm(const ChastePoint<DIM>& rX, Element<DIM,DIM>* pElement);\n\n    /**\n     * Overridden ComputeLinearInUCoeffInSourceTermAtNode() method.\n     *\n     * @param rNode reference to the node\n     * @return the coefficient of u in the linear part of the source term, i.e f(x) in\n     *  Div(D Grad u)  +  f(x)u + g(x) = 0.\n     */\n    virtual double ComputeLinearInUCoeffInSourceTermAtNode(const Node<DIM>& rNode);\n\n    /**\n     * Overridden ComputeDiffusionTerm() method.\n     *\n     * @param rX The point in space at which the diffusion term is computed\n     *\n     * @return a matrix.\n     */\n    virtual c_matrix<double,DIM,DIM> ComputeDiffusionTerm(const ChastePoint<DIM>& rX);\n};\n\n#include \"SerializationExportWrapper.hpp\"\nEXPORT_TEMPLATE_CLASS_SAME_DIMS(CellwiseSourceEllipticPde)\n\nnamespace boost\n{\nnamespace serialization\n{\n/**\n * Serialize information required to construct a CellwiseSourceEllipticPde.\n */\ntemplate<class Archive, unsigned DIM>\ninline void save_construct_data(\n    Archive & ar, const CellwiseSourceEllipticPde<DIM>* t, const unsigned int file_version)\n{\n    // Save data required to construct instance\n    const AbstractCellPopulation<DIM, DIM>* p_cell_population = &(t->rGetCellPopulation());\n    ar & p_cell_population;\n}\n\n/**\n * De-serialize constructor parameters and initialise a CellwiseSourceEllipticPde.\n */\ntemplate<class Archive, unsigned DIM>\ninline void load_construct_data(\n    Archive & ar, CellwiseSourceEllipticPde<DIM>* t, const unsigned int file_version)\n{\n    // Retrieve data from archive required to construct new instance\n    AbstractCellPopulation<DIM, DIM>* p_cell_population;\n    ar >> p_cell_population;\n\n    // Invoke inplace constructor to initialise instance\n    ::new(t)CellwiseSourceEllipticPde<DIM>(*p_cell_population);\n}\n}\n} // namespace ...\n\n#endif /*CELLWISESOURCEELLIPTICPDE_HPP_*/\n", "meta": {"hexsha": "f5a9ff26132c239cd85d0b40b84e6d3b1d8f0a9e", "size": 6660, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/cell_based_pde/pdes/CellwiseSourceEllipticPde.hpp", "max_stars_repo_name": "DGermano8/ChasteDom", "max_stars_repo_head_hexsha": "539a3a811698214c0938489b0cfdffd1abccf667", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cell_based/src/cell_based_pde/pdes/CellwiseSourceEllipticPde.hpp", "max_issues_repo_name": "DGermano8/ChasteDom", "max_issues_repo_head_hexsha": "539a3a811698214c0938489b0cfdffd1abccf667", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cell_based/src/cell_based_pde/pdes/CellwiseSourceEllipticPde.hpp", "max_forks_repo_name": "DGermano8/ChasteDom", "max_forks_repo_head_hexsha": "539a3a811698214c0938489b0cfdffd1abccf667", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8691099476, "max_line_length": 111, "alphanum_fraction": 0.733033033, "num_tokens": 1566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.44456123042008694}}
{"text": "#include <iostream>\n#include <boost/numeric/mtl/mtl.hpp>\n\nint main(int, char**)\n{\n    using namespace mtl; using mtl::iall;\n\n    typedef std::complex<double>      cdouble;\n    const unsigned                    xd= 2, yd= 5, n= xd * yd;\n    dense2D<cdouble>                  A(n, n);\n    mat::laplacian_setup(A, xd, yd); \n\n    // Fill imaginary part of the matrix\n    A*= cdouble(1, -1);\n    std::cout << \"A is\\n\" << with_format(A, 7, 1) << \"\\n\";\n\n    std::cout << \"sub_matrix(A, 2, 4, 1, 7) is\\n\" \n\t      << with_format(sub_matrix(A, 2, 4, 1, 7), 7, 1) << \"\\n\";\n\n    //col-vector from matrix\n    dense_vector<cdouble>   v_c(A[iall][0]);\n\n    std::cout << \"col-vector v_c is\\n\" << v_c << \"\\n\";\n\n    //row-vector from matrix\n    dense_vector<cdouble, mtl::vec::parameters<tag::row_major> > v_r(A[0][iall]);\n\n    std::cout << \"row-vector v_r is\\n\" << v_r << \"\\n\";\n\n    //row-vector in matrix\n    RowInMatrix<dense2D<cdouble> >::type v_r2(A[0][iall]);\n\n    std::cout << \"row-vector v_r2 is\\n\" << v_r2 << \"\\n\";\n\n    //submatrix from matrix per begin and end of row and column\n    dense2D<cdouble> B= sub_matrix(A, 2, 4, 1, 7);\n    B[1][2]= 88;\n\n    std::cout << \"B is\\n\" << B << \"\\n\";\n\n    //submatrix from matrix per irange\n    using mtl::irange;\n    irange row(2, 4), col(1, 7);\n    dense2D<cdouble> B1= A[row][col];\n\n    std::cout << \"B1 is\\n\" << B1 << \"\\n\";\n\n    //scalar from matrix\n    cdouble C= A[1][1];\n\n    std::cout << \"C is\\n\" << C << \"\\n\";\n\n    return 0;\n}\n", "meta": {"hexsha": "51e104eabf1711e9d12ac4a42fa3c55118e46b89", "size": 1465, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/matrix_functions3.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/matrix_functions3.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/matrix_functions3.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 26.6363636364, "max_line_length": 81, "alphanum_fraction": 0.5419795222, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4445612239258452}}
{"text": "// Define this to enable debugging\n// #define BOOST_SPIRIT_QI_DEBUG\n\n#include <boost/config/warning_disable.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/variant/recursive_variant.hpp>\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/fusion/include/adapt_struct.hpp>\n#include <boost/spirit/include/phoenix_function.hpp>\n#include <boost/optional.hpp>\n\n#include <iostream>\n#include <string>\n\nnamespace ast\n{\n    struct Nil;\n\n    struct Signed;\n\n    struct Expression;\n\n    struct RightAssocExpr;\n\n    struct Arg;\n\n    struct FunctionCall;\n\n    typedef boost::variant<\n            Nil\n          , double\n          , boost::recursive_wrapper< Signed >\n          , boost::recursive_wrapper< Expression >\n          , boost::recursive_wrapper< RightAssocExpr >\n          , boost::recursive_wrapper< Arg >\n          , boost::recursive_wrapper< FunctionCall >\n        >\n    Operand;\n\n    struct Nil\n    {\n    };\n\n    inline std::ostream & operator<<( std::ostream & out, Nil ) { out << \"nil\"; return out; }\n\n    struct Signed\n    {\n        char sign_;\n        Operand operand_;\n    };\n\n    struct Arg\n    {\n        char digit_;\n    };\n\n    struct RightAssocExpr\n    {\n        Operand left_;\n        boost::optional< Operand > right_;\n    };\n\n    struct FunctionCall\n    {\n        std::string name_;\n        Operand arg_;\n    };\n\n    struct Operation\n    {\n        std::string operator_;\n        Operand operand_;\n    };\n\n    struct Expression\n    {\n        Operand head_;\n        std::list< Operation > tail_;\n    };\n\n}\n\nBOOST_FUSION_ADAPT_STRUCT(\n    ast::Signed,\n    ( char, sign_ )\n    ( ast::Operand, operand_ )\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n    ast::Arg,\n    ( char, digit_ )\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n    ast::RightAssocExpr,\n    ( ast::Operand, left_ )\n    ( boost::optional< ast::Operand >, right_ )\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n    ast::FunctionCall,\n    ( std::string, name_ )\n    ( ast::Operand, arg_ )\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n    ast::Operation,\n    ( std::string, operator_ )\n    ( ast::Operand, operand_ )\n)\n\nBOOST_FUSION_ADAPT_STRUCT(\n    ast::Expression,\n    ( ast::Operand, head_ )\n    ( std::list< ast::Operation >, tail_ )\n)\n\nnamespace ast\n{\n    struct Calc\n    {\n    public:\n\n        typedef double result_type;\n\n    private:\n\n        template< typename... TDoubles >\n        void assign( double * args, int index, double head, TDoubles &&... tail )\n        {\n            args[ index ] = head;\n            assign( args, index+1, std::forward< TDoubles >( tail )... );\n        }\n\n        void assign( double * args, int index )\n        {\n        }\n\n    public:\n\n        template< typename... Doubles >\n        Calc( Doubles &&... ds )\n        {\n            static_assert( sizeof...( Doubles ) < 10, \"sizeof...(Doubles) has to be less then 10\" );\n            args_[ 0 ] = sizeof...( Doubles );\n\n            assign( & args_[ 0 ], 1, std::forward< Doubles >( ds )... );\n        }\n\n        double operator()( Nil ) const\n        {\n            BOOST_ASSERT( 0 ); return 0;\n        }\n\n        double operator()( double n ) const\n        {\n            return n;\n        }\n\n        double operator()( Operation const & x, double lhs ) const\n        {\n            if( x.operator_ == \"&&\" )\n            {\n                if( fabs( lhs ) < 0.000001 ){\n                    return 0;\n                }\n                else{\n                    return boost::apply_visitor( *this, x.operand_ );\n                }\n            }\n\n            if( x.operator_ == \"||\" )\n            {\n                if( fabs( lhs ) < 0.000001 ){\n                    return boost::apply_visitor( *this, x.operand_ );\n                }\n                else{\n                    return lhs;\n                }\n            }\n\n            double const rhs = boost::apply_visitor( *this, x.operand_ );\n\n            if( x.operator_ == \"+\" ){\n                return lhs + rhs;\n            }\n\n            if( x.operator_ == \"-\" ){\n                return lhs - rhs;\n            }\n\n            if( x.operator_ == \"*\" ){\n                return lhs * rhs;\n            }\n\n            if( x.operator_ == \"/\" ){\n                return lhs / rhs;\n            }\n\n            if( x.operator_ == \"<\" ){\n                return lhs < rhs;\n            }\n\n            if( x.operator_ == \"<=\" ){\n                return lhs <= rhs;\n            }\n\n            if( x.operator_ == \">\" ){\n                return lhs > rhs;\n            }\n\n            if( x.operator_ == \">=\" ){\n                return lhs >= rhs;\n            }\n\n            if( x.operator_ == \"==\" ){\n                return lhs == rhs;\n            }\n\n            if( x.operator_ == \"!=\" ){\n                return lhs != rhs;\n            }\n\n            return 0;\n        }\n\n        double operator()( Signed const & x ) const\n        {\n            double const rhs = boost::apply_visitor( *this, x.operand_ );\n\n            switch( x.sign_ )\n            {\n                case '-':\n                    return - rhs;\n\n                case '+':\n                    return + rhs;\n\n                case '!':\n                    return ( fabs( rhs ) < 0.000001 ) ? 1 : 0;\n\n                default:\n                    BOOST_ASSERT( 0 );\n            }\n        }\n\n        double operator()( Arg const & x ) const\n        {\n            return args_[ x.digit_ - '0' ];\n        }\n\n        double operator()( RightAssocExpr const & x ) const\n        {\n            double const base = boost::apply_visitor( *this, x.left_ );\n\n            if( ! x.right_ ){\n                return base;\n            }\n            \n            double const exp = boost::apply_visitor( *this, x.right_.get() );\n\n            return std::pow( base, exp );\n        }\n\n        double operator()( FunctionCall const & x ) const\n        {\n            if( x.name_ == \"pi\" ){\n                return M_PI;\n            }\n            \n            if( x.name_ == \"e\" ){\n                return std::exp( 1.0 );\n            }\n\n            double const arg = boost::apply_visitor( *this, x.arg_ );\n\n            if( x.name_ == \"sin\" ){\n                return sin( arg );\n            }\n            \n            if( x.name_ == \"cos\" ){\n                return cos( arg );\n            }\n            \n            if( x.name_ == \"tan\" ){\n                return tan( arg );\n            }\n            \n            if( x.name_ == \"abs\" ){\n                return fabs( arg );\n            }\n            \n            if( x.name_ == \"rad\" ){\n                return arg * 2 * M_PI / 360;\n            }\n\n            if( x.name_ == \"deg\" ){\n                return arg * 360 / 2 / M_PI;\n            }\n\n            if( x.name_ == \"log\" ){\n                return log( arg );\n            }\n\n            if( x.name_ == \"log10\" ){\n                return log10( arg );\n            }\n\n            if( x.name_ == \"log2\" ){\n                return log2( arg );\n            }\n\n            return 0;\n        }\n\n        double operator()( Expression const & x ) const\n        {\n            double state = boost::apply_visitor( *this, x.head_ );\n\n            for( Operation const & oper : x.tail_ )\n            {\n                state = ( *this )( oper, state );\n            }\n\n            return state;\n        }\n    \n    private:\n\n        double args_[ 10 ];\n    };\n}\n\nnamespace qi = boost::spirit::qi;\nnamespace ascii = boost::spirit::ascii;\nusing boost::phoenix::function;\n\nstruct error_handler_\n{\n    template< typename, typename, typename >\n    struct result { typedef void type; };\n\n    template< typename TIterator >\n    void operator()(\n        qi::info const & what\n      , TIterator err_pos, TIterator last ) const\n    {\n        std::cout\n            << \"Error! Expecting \"\n            << what\n            << \" here: \\\"\"\n            << std::string( err_pos, last )\n            << \"\\\"\"\n            << std::endl\n        ;\n    }\n};\n\nfunction< error_handler_ > const error_handler = error_handler_();\n\ntemplate< typename TIterator >\nstruct Calculator\n    : qi::grammar< TIterator, ast::Expression(), ascii::space_type >\n{\n    Calculator()\n        : Calculator::base_type( expression )\n    {\n        qi::char_type char_;\n        qi::digit_type digit_;\n        qi::double_type double_;\n        qi::lit_type lit_;\n        qi::string_type string_;\n        qi::alpha_type alpha_;\n        qi::alnum_type alnum_;\n\n        using qi::on_error;\n        using qi::fail;\n        using qi::lexeme;\n\n        expression =\n            relationalExpression\n            >> *(   (string_( \"&&\" ) > relationalExpression )\n                |   (string_( \"||\" ) > relationalExpression )\n                )\n            ;\n\n        relationalExpression =\n            additiveExpression\n            >> *(   (string_( \"<=\" ) > additiveExpression )\n                |   (string_( \"<\" ) > additiveExpression )\n                |   (string_( \">=\" ) > additiveExpression )\n                |   (string_( \">\" ) > additiveExpression )\n                |   (string_( \"!=\" ) > additiveExpression )\n                |   (string_( \"==\" ) > additiveExpression )\n                )\n            ;\n\n        additiveExpression =\n            multiplicativeExpression\n            >> *(   (char_( '+' ) > multiplicativeExpression )\n                |   (char_( '-' ) > multiplicativeExpression )\n                )\n            ;\n\n        multiplicativeExpression =\n            exponentialExpression\n            >> *(   ( char_( '*' ) > exponentialExpression )\n                |   ( char_( '/' ) > exponentialExpression )\n                )\n            ;\n\n        exponentialExpression =\n            unaryExpression\n            >> -( '^' >> exponentialExpression );\n        \n        unaryExpression =\n                ( char_( '-' ) > unaryExpression )\n            |   ( char_( '+' ) > unaryExpression )\n            |   ( char_( '!' ) > unaryExpression )\n            |   primaryExpression\n            ;\n\n        primaryExpression =\n                double_\n            |   arg\n            |   functionCall\n            |   '(' > expression > ')'\n            ;\n\n        arg =\n            ( '_' > digit_ )\n            ;\n\n        functionCall =\n            ( +alnum_ > '(' > -unaryExpression > ')' )\n            ;\n\n        BOOST_SPIRIT_DEBUG_NODE( expression );\n        BOOST_SPIRIT_DEBUG_NODE( relationalExpression );\n        BOOST_SPIRIT_DEBUG_NODE( additiveExpression );\n        BOOST_SPIRIT_DEBUG_NODE( multiplicativeExpression );\n        BOOST_SPIRIT_DEBUG_NODE( exponentialExpression );\n        BOOST_SPIRIT_DEBUG_NODE( unaryExpression );\n        BOOST_SPIRIT_DEBUG_NODE( primaryExpression );\n        BOOST_SPIRIT_DEBUG_NODE( arg );\n        BOOST_SPIRIT_DEBUG_NODE( functionCall );\n\n        on_error< fail >(\n            expression,\n            error_handler( qi::_4_type(), qi::_3_type(), qi::_2_type() )\n        );\n    }\n\nprivate:\n\n    qi::rule< TIterator, ast::Expression(), ascii::space_type > expression;\n    qi::rule< TIterator, ast::Expression(), ascii::space_type > relationalExpression;\n    qi::rule< TIterator, ast::Expression(), ascii::space_type > additiveExpression;\n    qi::rule< TIterator, ast::Expression(), ascii::space_type > multiplicativeExpression;\n    qi::rule< TIterator, ast::RightAssocExpr(), ascii::space_type > exponentialExpression;\n    qi::rule< TIterator, ast::Operand(), ascii::space_type > unaryExpression;\n    qi::rule< TIterator, ast::Operand(), ascii::space_type > primaryExpression;\n    qi::rule< TIterator, ast::Arg(), ascii::space_type > arg;\n    qi::rule< TIterator, ast::FunctionCall(), ascii::space_type > functionCall;\n};\n\ntemplate< typename... TDoubles>\ndouble calc(\n    std::string const & expr,\n    TDoubles... ds\n)\n{\n    std::string::const_iterator iter = expr.begin();\n    std::string::const_iterator end = expr.end();\n\n    Calculator< std::string::const_iterator > calc;\n    \n    boost::spirit::ascii::space_type space;\n\n    ast::Expression expression;\n\n    bool const r = phrase_parse( iter, end, calc, space, expression );\n\n    if( r && iter == end )\n    {\n        ast::Calc calc( std::forward< TDoubles >( ds )... );\n        return calc( expression );\n    }\n    \n    throw std::runtime_error( \"Parsing failed: \" + std::string( iter, end ) );\n}\n\nvoid test()\n{\n    assert( calc( \"1+2*3\" ) == 7 );\n    assert( calc( \"2^3^2\" ) == 512 );\n    assert( calc( \"(1+2)*(3+4)\" ) == 21 );\n\n    assert( calc( \"1+-1\" ) == 0 );\n    assert( calc( \"1--1\" ) == 2 );\n\n    assert( calc( \"4/2\" ) == 2 );\n    assert( calc( \"4.5/2\" ) == 2.25 );\n    assert( calc( \"5/2\" ) == 2.5 );\n\n    assert( calc( \"!1\" ) == 0 );\n    assert( calc( \"!0\" ) == 1 );\n\n    assert( calc( \"pi()\" ) == double(M_PI) );\n    assert( calc( \"e()\" ) == std::exp( 1.0 ) );\n\n    assert( calc( \"12||(1/0)\" ) == 12 );\n    assert( calc( \"0&&(1/0)\" ) == 0 );\n    assert( calc( \"1&&2\" ) == 2 );\n    assert( calc( \"2||1\" ) == 2 );\n    assert( calc( \"0||2\" ) == 2 );\n\n    assert( calc( \"1<2\" ) == 1 );\n    assert( calc( \"2<1\" ) == 0 );\n\n    assert( calc( \"1>2\" ) == 0 );\n    assert( calc( \"2>1\" ) == 1 );\n\n    assert( calc( \"1<=2\" ) == 1 );\n    assert( calc( \"2<=2\" ) == 1 );\n    assert( calc( \"3<=2\" ) == 0 );\n\n    assert( calc( \"1>=2\" ) == 0 );\n    assert( calc( \"2>=2\" ) == 1 );\n    assert( calc( \"3>=2\" ) == 1 );\n\n    assert( calc( \"abs(1)\" ) == 1 );\n    assert( calc( \"abs(-1)\" ) == 1 );\n\n    assert( calc( \"sin(rad(0))\" ) == 0 );\n    assert(( fabs( calc( \"sin(rad(90))\" ) - 1.0 ) < 0.000001 ));\n\n    assert( calc( \"cos(rad(0))\" ) == 1 );\n    assert(( fabs( calc( \"cos(rad(90))\" ) - 0.0 ) < 0.0000001 ));\n\n    assert( calc( \"log10(1)\" ) == 0 );\n    assert( calc( \"log10(10)\" ) == 1 );\n    assert( calc( \"log10(100)\" ) == 2 );\n\n    assert( calc( \"log2(1)\" ) == 0 );\n    assert( calc( \"log2(2)\" ) == 1 );\n    assert( calc( \"log2(4)\" ) == 2 );\n\n    assert( calc( \"_1+_2+_3+_4+_5+_6+_7+_8+_9\", 1, 2, 3, 4, 5, 6, 7, 8, 9 ) == 45 );\n    assert( calc( \"_0\" ) == 0 );\n    assert( calc( \"_0\", 1 ) == 1 );\n    assert( calc( \"_0\", 1, 2 ) == 2 );\n    assert( calc( \"_0\", 1, 2, 3 ) == 3 );\n}\n\nint main( int argc, char* argv[] )\n{\n    test();\n\n    using std::cout;\n    using std::endl;\n    using std::stof;\n\n    try\n    {\n        if( argc == 2 ){\n            cout << calc( argv[1] ) << endl;\n        }\n        else if( argc == 3 ){\n            cout << calc( argv[1], stof(argv[2]) ) << endl;\n        }\n        else if( argc == 4 ){\n            cout << calc( argv[1], stof(argv[2]), stof(argv[3]) ) << endl;\n        }\n        else if( argc == 5 ){\n            cout << calc( argv[1], stof(argv[2]), stof(argv[3]),\n                stof(argv[4]) ) << endl;\n        }\n        else if( argc == 6 ){\n            cout << calc( argv[1], stof(argv[2]), stof(argv[3]),\n                stof(argv[4]), stof(argv[5]) ) << endl;\n        }\n        else if( argc == 7 ){\n            cout << calc( argv[1], stof(argv[2]), stof(argv[3]),\n                stof(argv[4]), stof(argv[5]), stof(argv[6]) ) << endl;\n        }\n        else if( argc == 8 ){\n            cout << calc( argv[1], stof(argv[2]), stof(argv[3]),\n                stof(argv[4]), stof(argv[5]), stof(argv[6]),\n                stof(argv[7]) ) << endl;\n        }\n        else if( argc == 9 ){\n            cout << calc( argv[1], stof(argv[2]), stof(argv[3]),\n                stof(argv[4]), stof(argv[5]), stof(argv[6]),\n                stof(argv[7]), stof(argv[8]) ) << endl;\n        }\n        else if( argc == 10 ){\n            cout << calc( argv[1], stof(argv[2]), stof(argv[3]),\n                stof(argv[4]), stof(argv[5]), stof(argv[6]),\n                stof(argv[7]), stof(argv[8]), stof(argv[9]) ) << endl;\n        }\n        else if( argc == 11 ){\n            cout << calc( argv[1], stof(argv[2]), stof(argv[3]),\n                stof(argv[4]), stof(argv[5]), stof(argv[6]),\n                stof(argv[7]), stof(argv[8]), stof(argv[9]),\n                stof(argv[10]) ) << endl;\n        }\n    }\n    catch( std::runtime_error const & e ){\n        std::cerr << e.what() << std::endl;\n    }\n}\n\n", "meta": {"hexsha": "3c0680021921c6c2d65658b2d95bb03de14ae9fa", "size": 15832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calc.cpp", "max_stars_repo_name": "wo3kie/Calc", "max_stars_repo_head_hexsha": "c36ca86658a79907d9e008c0e0f2de80d3cc2746", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-10-26T22:06:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-24T18:13:01.000Z", "max_issues_repo_path": "calc.cpp", "max_issues_repo_name": "wo3kie/Calc", "max_issues_repo_head_hexsha": "c36ca86658a79907d9e008c0e0f2de80d3cc2746", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calc.cpp", "max_forks_repo_name": "wo3kie/Calc", "max_forks_repo_head_hexsha": "c36ca86658a79907d9e008c0e0f2de80d3cc2746", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7850162866, "max_line_length": 100, "alphanum_fraction": 0.4623547246, "num_tokens": 4058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.44456122392584513}}
{"text": "/// @file  cmp.hpp\n/// @brief Declarations for embedding methods using classic ordinal constraints\n\n#pragma once\n#ifndef OGT_EMBED_CMP_HPP\n#define OGT_EMBED_CMP_HPP\n\n#include <ogt/config.hpp>\n#include <ogt/core/oracle.hpp>\n#include <ogt/embed/embed.hpp>\n#include <Eigen/Dense>\n#include <vector>\n\nnamespace OGT_NAMESPACE {\nnamespace embed {\n\n/// An ordinal constraint specifying that dist(a,b) < dist(c,d).\nstruct CmpConstraint {\n\n\t/// Default constructor.\n\tCmpConstraint() : a(0), b(0), c(0), d(0) {}\n\n\t/// Constructor with four points\n\tCmpConstraint(size_t a, size_t b, size_t c, size_t d)\n\t\t: a(a), b(b), c(c), d(d) {}\n\n\t/// Constructor with three points: dist(a,b) < dist(a,c).\n\tCmpConstraint(size_t a, size_t b, size_t c)\n\t\t: CmpConstraint(a, b, c, a) {}\n\n\t/// Constructor from an oracle comparison\n\tCmpConstraint(const OGT_NAMESPACE::core::CmpOutcome& cmp)\n\t\t: CmpConstraint(\n\t\t\tcmp.a,\n\t\t\tcmp.cmp == OGT_NAMESPACE::core::AB_LT_AC ? cmp.b : cmp.c,\n\t\t\tcmp.cmp == OGT_NAMESPACE::core::AB_LT_AC ? cmp.c : cmp.b) {}\n\n\t/// The objects being constrained\n\tsize_t a, b, c, d;\n};\n\n/// Embeds a dataset by recovering a dissimilarity kernel using the Crowd Kernel\n/// embedding algorithm.\n/// The parameter lambda effects the scaling of the embedding.\n///\n/// Citation: O. Tamuz, C. Liu, S. Belongie, O. Shamir, and A. T. Kalai,\n/// \"Adaptively Learning the Crowd Kernel,\" International Conference on Machine\n/// Learning, 2011.\nEmbedResult embedCmpWithCKForK(std::vector<CmpConstraint> cons,\n\tconst Eigen::MatrixXd& K0, double lambda, EmbedConfig config);\n\n/// Embeds a dataset using the Crowd Kernel embedding algorithm.\n/// The parameter lambda effects the scaling of the embedding.\n///\n/// Citation: O. Tamuz, C. Liu, S. Belongie, O. Shamir, and A. T. Kalai,\n/// \"Adaptively Learning the Crowd Kernel,\" International Conference on Machine\n/// Learning, 2011.\nEmbedResult embedCmpWithCKForX(std::vector<CmpConstraint> cons,\n\tconst Eigen::MatrixXd& X0, double lambda, EmbedConfig config);\n\n/// Embeds a dataset by recovering a dissimilarity kernel using Generalized\n/// Non-metric Multidimensional Scaling.\n/// The lambda parameter specifies the amount of regularization to apply to\n/// keep the rank small.\n/// An embedding can be recovered from the kernel using, for instance,\n/// embeddingFromKernelSVD().\n///\n/// Citation: S. Agarwal, J. Wills, and L. Cayton, \"Generalized non-metric\n/// multidimensional scaling,\"\" International Conference on Machine Learning,\n/// 2007.\nEmbedResult embedCmpWithGNMDSForK(std::vector<CmpConstraint> cons,\n\tconst Eigen::MatrixXd& K0, double lambda, EmbedConfig config);\n\n/// Embeds a dataset using Generalized Non-metric Multidimensional Scaling.\n/// The lambda parameter specifies the amount of regularization to apply to\n/// keep the rank small.\n///\n/// Citation: S. Agarwal, J. Wills, and L. Cayton, \"Generalized non-metric\n/// multidimensional scaling,\"\" International Conference on Machine Learning,\n/// 2007.\nEmbedResult embedCmpWithGNMDSForX(std::vector<CmpConstraint> cons,\n\tconst Eigen::MatrixXd& X0, double lambda, EmbedConfig config);\n\n/// Embeds a dataset using Soft Ordinal Embedding.\n/// This method uses the margin parameter to set the scale. A default value of\n/// 0.1 will be used if no margin is provided.\n///\n/// Citation: Y. Terada and U. von Luxburg, \"Local ordinal embedding,\" presented\n/// at the Proceedings of the 31st International Conference on Machine Learning,\n/// 2014.\nEmbedResult embedCmpWithSOE(std::vector<CmpConstraint> cons,\n\tconst Eigen::MatrixXd& X0, EmbedConfig config);\n\n/// Embeds using a weighted variant of Soft Ordinal Embedding. The loss function\n/// is modified so that each constraint has a corresponding weight which is\n/// multiplied to the loss incurred when that constraint is violated.\n/// It is assumed, but not verified, that the weights are non-negative and sum\n/// to one.\nEmbedResult embedCmpWithSOEWeighted(std::vector<CmpConstraint> cons,\n\tconst Eigen::VectorXd &weights, const Eigen::MatrixXd &X0,\n\tEmbedConfig config);\n\n/// Embeds a point to satisfy a ranking of some set of fixed points, as much\n/// as possible.\n/// rank is an ordered list of rows from X. The resulting row in EmbedResult.X\n/// gives a position which satisfies this ranking, if possible.\nEmbedResult embedPtRankingWithSOE(const std::vector<size_t> &rank,\n\tconst Eigen::MatrixXd& X, const Eigen::VectorXd& pos0, EmbedConfig config);\n\n/// Embeds a dataset using Local Ordinal Embedding.\n/// This method uses the margin parameter to set the scale. A default value of\n/// 0.1 will be used if no margin is provided.\n///\n/// Citation: Y. Terada and U. von Luxburg, \"Local ordinal embedding,\" presented\n/// at the Proceedings of the 31st International Conference on Machine Learning,\n/// 2014.\nEmbedResult embedKnnWithLOE(const Eigen::MatrixXi& knn,\n\tconst Eigen::MatrixXd& X0, EmbedConfig config);\n\n/// Pick an optimal SOE scale parameter for the embedding.\ndouble fitSOEScale(std::vector<CmpConstraint> cons, const Eigen::MatrixXd& X);\n\n/// Embeds a dataset by recovering a dissimilarity kernel using Stochastic\n/// Triplet Embedding.\n/// The lambda parameter specifies the degree of regularization.\n///\n/// Citation: L. Van der Maaten and K. Weinberger, \"Stochastic triplet\n/// embedding,\" 2012 IEEE International Workshop on Machine Learning for Signal\n/// Processing (MLSP), 2012.\nEmbedResult embedCmpWithSTEForK(std::vector<CmpConstraint> cons,\n\tconst Eigen::MatrixXd& K0, double lambda, EmbedConfig config);\n\n/// Embeds a dataset using Stochastic Triplet Embedding.\n/// The lambda parameter specifies the degree of regularization.\n///\n/// Citation: L. Van der Maaten and K. Weinberger, \"Stochastic triplet\n/// embedding,\" 2012 IEEE International Workshop on Machine Learning for Signal\n/// Processing (MLSP), 2012.\nEmbedResult embedCmpWithSTEForX(std::vector<CmpConstraint> cons,\n\tconst Eigen::MatrixXd& X0, double lambda, EmbedConfig config);\n\n/// Embeds a dataset using t-Distributed Stochastic Triplet Embedding.\n/// The lambda parameter specifies the degree of regularization.\n/// The alpha parameter indicates the degrees of freedom for the Student's-t\n/// distribution.\n///\n/// Citation: L. Van der Maaten and K. Weinberger, \"Stochastic triplet\n/// embedding,\" 2012 IEEE International Workshop on Machine Learning for Signal\n/// Processing (MLSP), 2012.\nEmbedResult embedCmpWithTSTE(std::vector<CmpConstraint> cons,\n\tconst Eigen::MatrixXd& X0, double lambda, double alpha, EmbedConfig config);\n\n/// Embeds a dataset using Rank-d Projected Gradient Descent (PGD), adapted\n/// to work directly on a n x d matrix X rather than to project after each step.\n///\n/// Citation: L. Jain, K. Jamieson, and R. Nowak, \"Finite Sample Prediction and\n/// Recovery Bounds for Ordinal Embedding,\" NIPS, 2016.\nEmbedResult embedCmpWithPGDForX(std::vector<CmpConstraint> cons,\n\tconst Eigen::MatrixXd& X0, EmbedConfig config);\n\n/// Embeds a dataset using Rank-d Projected Gradient Descent (PGD).\n/// This is the original version of the algorithm.\n/// After each learning step, we project to the nearest rank d Gram matrix.\n///\n/// Citation: L. Jain, K. Jamieson, and R. Nowak, \"Finite Sample Prediction and\n/// Recovery Bounds for Ordinal Embedding,\" NIPS, 2016.\nEmbedResult embedCmpWithPGDForK(std::vector<CmpConstraint> cons,\n\tconst Eigen::MatrixXd& X0, EmbedConfig config);\n\n/// Embeds a dataset using Nuclear Norm Projected Gradient Descent.\n/// After each learning step, we project onto the nuclear norm ball, which has\n/// the effect of minimizing the rank.\n///\n/// Citation: L. Jain, K. Jamieson, and R. Nowak, \"Finite Sample Prediction and\n/// Recovery Bounds for Ordinal Embedding,\" NIPS, 2016.\nEmbedResult embedCmpWithNNPGD(std::vector<CmpConstraint> cons,\n\tconst Eigen::MatrixXd& X0, double lambda, EmbedConfig config);\n\n/// Embeds a dataset using Nuclear Norm Projected Gradient Descent Debiased.\n/// This is similar to embedCmpWithNNPGD() but with an extra debiasing step.\n/// This debiasing improves accuracy by rescaling the non-zero eigenvalues\n/// to prevent them from shrinking toward zero. It is the default behavior.\n///\n/// Citation: L. Jain, K. Jamieson, and R. Nowak, \"Finite Sample Prediction and\n/// Recovery Bounds for Ordinal Embedding,\" NIPS, 2016.\nEmbedResult embedCmpWithNNPGDDebiased(std::vector<CmpConstraint> cons,\n\tconst Eigen::MatrixXd& X0, double lambda, EmbedConfig config);\n\n/// Compute a kernel matrix where K_ij is derived by how similarly points i and\n/// j are ranked by the provided comparisons.\n/// The parameters k1 and k2 indicate how much of the two possible kernels to\n/// mix into the final output; k1 corresponds to an anchor-based kernel while k2\n/// corresponds to a tail-based kernel.\n///\n/// Citation: M. Kleindessner and U. von Luxburg, “Kernel functions based on\n/// triplet similarity comparisons,” arXiv.org, vol. stat.ML. 28-Jul-2016.\nEmbedResult embedCmpWithTauForK(std::vector<CmpConstraint> cons, double k1,\n\tdouble k2);\n\n} // end namespace embed\n} // end namespace OGT_NAMESPACE\n#endif /* OGT_EMBED_CMP_HPP */\n", "meta": {"hexsha": "728f75aa79175be1c2e7be31ae96c7c601657e36", "size": 9020, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ogt/embed/cmp.hpp", "max_stars_repo_name": "jesand/lloe", "max_stars_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-11T21:31:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-30T09:23:04.000Z", "max_issues_repo_path": "include/ogt/embed/cmp.hpp", "max_issues_repo_name": "jesand/lloe", "max_issues_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ogt/embed/cmp.hpp", "max_forks_repo_name": "jesand/lloe", "max_forks_repo_head_hexsha": "66235b16fb8cfbb39f72a289c320e701bde94159", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-11T21:31:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-27T20:57:26.000Z", "avg_line_length": 44.4334975369, "max_line_length": 80, "alphanum_fraction": 0.7506651885, "num_tokens": 2252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4444854888179667}}
{"text": "/*\n * Copyright 2022 Sean McBane\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#ifndef LINEAR_ELASTICITY_HPP\n#define LINEAR_ELASTICITY_HPP\n\n#include <Eigen/Core>\n#include <cassert>\n#include <exception>\n\n#include \"C0_triangles.hpp\"\n#include \"Galerkin.hpp\"\n#include \"SymSparse.hpp\"\n#include \"mesh_traits.hpp\"\n#include \"src/FunctionBase.hpp\"\n\nnamespace Elasticity\n{\n\ntemplate <class Element>\nstruct basis_size_struct\n{\n};\n\ntemplate <>\nstruct basis_size_struct<C0Triangle<1>>\n{\n    constexpr static size_t value = 3;\n};\n\ntemplate <>\nstruct basis_size_struct<C0Triangle<2>>\n{\n    constexpr static size_t value = 6;\n};\n\ntemplate <>\nstruct basis_size_struct<C0Triangle<3>>\n{\n    constexpr static size_t value = 10;\n};\n\ntemplate <>\nstruct basis_size_struct<C0Triangle<4>>\n{\n    constexpr static size_t value = 15;\n};\n\ntemplate <class Element>\nconstexpr size_t basis_size = basis_size_struct<Element>::value;\n\ntemplate <class Element>\nusing coeffs_type = Eigen::Matrix<double, basis_size<Element>, 1>;\n\ntemplate <class Element>\nusing vector_coeffs_type = Eigen::Matrix<double, 2, basis_size<Element>>;\n\ntemplate <class Mesh>\nauto get_scalar_coeffs(const Mesh &mesh, size_t eli, const Eigen::VectorXd &uc)\n{\n    const auto &el_info = mesh.element(eli);\n    Eigen::Matrix<double, std::decay_t<decltype(el_info)>::num_nodes(), 1> coeffs;\n\n    auto nn = el_info.node_numbers();\n    for (size_t i = 0; i < el_info.num_nodes(); ++i)\n    {\n        coeffs[i] = uc[nn[i]];\n    }\n\n    return coeffs;\n}\n\ntemplate <class Mesh>\nauto get_vector_coeffs(const Mesh &mesh, size_t eli, const Eigen::Matrix2Xd &uc)\n{\n    const auto &el_info = mesh.element(eli);\n    Eigen::Matrix<double, 2, std::decay_t<decltype(el_info)>::num_nodes()> coeffs;\n\n    auto nn = el_info.node_numbers();\n    for (size_t i = 0; i < el_info.num_nodes(); ++i)\n    {\n        coeffs.col(i) = uc.col(nn[i]);\n    }\n\n    return coeffs;\n}\n\n/*\n * Given the coefficients of a function u in the finite element basis for el,\n * construct a function object that evaluates that function (and whose\nderivatives,\n * etc. can be used).\n */\ntemplate <class Element>\nauto make_function(const Element &, const coeffs_type<Element> &uc)\n{\n    using Galerkin::Functions::ConstantFunction;\n    return Galerkin::static_sum<1, basis_size<Element>>(\n        [&uc](auto I) { return ConstantFunction(uc[I()]) * Galerkin::get<I()>(Element::basis); },\n        ConstantFunction(uc[0]) * Galerkin::get<0>(Element::basis));\n}\n\n/*\n * Given the coefficients of a *vector* function u in the finite element basis\n * for el, construct 2 function objects evaluating the X and Y parts of the\n * vector function.\n */\ntemplate <class Element>\nauto make_vector_functions(const Element &el, const vector_coeffs_type<Element> &uc)\n{\n    using Galerkin::Functions::ConstantFunction;\n\n    auto ux = Galerkin::static_sum<1, basis_size<Element>>(\n        [&](auto I) { return ConstantFunction(uc(0, I())) * Galerkin::get<I()>(Element::basis); },\n        ConstantFunction(uc(0, 0)) * Galerkin::get<0>(Element::basis));\n    auto uy = Galerkin::static_sum<1, basis_size<Element>>(\n        [&](auto I) { return ConstantFunction(uc(1, I())) * Galerkin::get<I()>(Element::basis); },\n        ConstantFunction(uc(1, 0)) * Galerkin::get<0>(Element::basis));\n\n    return std::pair(ux, uy);\n}\n\ntemplate <class Element>\nusing el_stiffness_type = Eigen::Matrix<double, 2 * basis_size<Element>, 2 * basis_size<Element>>;\n\ntemplate <class Element>\nel_stiffness_type<Element> element_stiffness_matrix(const Element &el, double lambda, double mu);\n\nextern template el_stiffness_type<C0Triangle<1>>\nelement_stiffness_matrix(const C0Triangle<1> &, double, double);\nextern template el_stiffness_type<C0Triangle<2>>\nelement_stiffness_matrix(const C0Triangle<2> &, double, double);\n\n#if ELASTICITY_MAX_ELEMENT_ORDER > 2\nextern template el_stiffness_type<C0Triangle<3>>\nelement_stiffness_matrix(const C0Triangle<3> &, double, double);\n#endif\n\n#if ELASTICITY_MAX_ELEMENT_ORDER > 3\nextern template el_stiffness_type<C0Triangle<4>>\nelement_stiffness_matrix(const C0Triangle<4> &, double, double);\n#endif\n\ntemplate <class Element>\nel_stiffness_type<Element> element_stiffness_matrix(\n    const Element &el, const coeffs_type<Element> &lambda, const coeffs_type<Element> &mu);\n\nextern template el_stiffness_type<C0Triangle<1>> element_stiffness_matrix(\n    const C0Triangle<1> &, const coeffs_type<C0Triangle<1>> &,\n    const coeffs_type<C0Triangle<1>> &);\nextern template el_stiffness_type<C0Triangle<2>> element_stiffness_matrix(\n    const C0Triangle<2> &, const coeffs_type<C0Triangle<2>> &,\n    const coeffs_type<C0Triangle<2>> &);\n\n#if ELASTICITY_MAX_ELEMENT_ORDER > 2\nextern template el_stiffness_type<C0Triangle<3>> element_stiffness_matrix(\n    const C0Triangle<3> &, const coeffs_type<C0Triangle<3>> &,\n    const coeffs_type<C0Triangle<3>> &);\n#endif\n\n#if ELASTICITY_MAX_ELEMENT_ORDER > 3\nextern template el_stiffness_type<C0Triangle<4>> element_stiffness_matrix(\n    const C0Triangle<4> &, const coeffs_type<C0Triangle<4>> &,\n    const coeffs_type<C0Triangle<4>> &);\n#endif\n\ntemplate <class Element>\nEigen::Matrix<double, basis_size<Element>, basis_size<Element>>\nelement_mass_matrix(const Element &el);\n\nextern template Eigen::Matrix<double, basis_size<C0Triangle<1>>, basis_size<C0Triangle<1>>>\nelement_mass_matrix(const C0Triangle<1> &);\nextern template Eigen::Matrix<double, basis_size<C0Triangle<2>>, basis_size<C0Triangle<2>>>\nelement_mass_matrix(const C0Triangle<2> &);\n\n#if ELASTICITY_MAX_ELEMENT_ORDER > 2\nextern template Eigen::Matrix<double, basis_size<C0Triangle<3>>, basis_size<C0Triangle<3>>>\nelement_mass_matrix(const C0Triangle<3> &);\n#endif\n\n#if ELASTICITY_MAX_ELEMENT_ORDER > 3\nextern template Eigen::Matrix<double, basis_size<C0Triangle<4>>, basis_size<C0Triangle<4>>>\nelement_mass_matrix(const C0Triangle<4> &);\n#endif\n\ntemplate <class Mesh>\nauto instantiate_element(const Mesh &mesh, size_t which)\n{\n    constexpr int order = msh::element_order<Mesh>;\n    const auto &el = mesh.element(which);\n    return C0Triangle<order>(\n        mesh.coord(el.control_nodes[0]), mesh.coord(el.control_nodes[1]),\n        mesh.coord(el.control_nodes[2]));\n}\n\nconstexpr auto lame_parameters(double E, double nu) noexcept\n{\n    double lambda = E * nu / ((1 + nu) * (1 - nu));\n    double mu = E / (2 * (1 + nu));\n    return std::make_pair(lambda, mu);\n}\n\ntypedef SymSparse::SymmetricSparseMatrix<double, 2 * max_node_adjacencies> StiffnessType;\n\ntemplate <class Mesh>\nStiffnessType assemble_stiffness(const Mesh &mesh, double E, double nu)\n{\n    StiffnessType K(mesh.num_nodes() * 2);\n    auto [lambda, mu] = lame_parameters(E, nu);\n\n    for (size_t i = 0; i < mesh.num_elements(); ++i)\n    {\n        const auto &el_info = mesh.element(i);\n        const auto nn = el_info.node_numbers();\n        const auto el = instantiate_element(mesh, i);\n        const auto local_K = element_stiffness_matrix(el, lambda, mu);\n        for (size_t j = 0; j < nn.size(); ++j)\n        {\n            for (size_t k = j; k < nn.size(); ++k)\n            {\n                K.insert_entry(nn[j] * 2, nn[k] * 2, local_K(2 * j, 2 * k));\n                if (k != j)\n                {\n                    K.insert_entry(nn[j] * 2 + 1, nn[k] * 2, local_K(2 * j + 1, 2 * k));\n                }\n                K.insert_entry(nn[j] * 2, nn[k] * 2 + 1, local_K(2 * j, 2 * k + 1));\n                K.insert_entry(nn[j] * 2 + 1, nn[k] * 2 + 1, local_K(2 * j + 1, 2 * k + 1));\n            }\n        }\n    }\n    return K;\n}\n\ntemplate <class Mesh>\nStiffnessType\nassemble_stiffness(const Mesh &mesh, const Eigen::VectorXd &lambda, const Eigen::VectorXd &mu)\n{\n    StiffnessType K(mesh.num_nodes() * 2);\n\n    for (size_t eli = 0; eli < mesh.num_elements(); ++eli)\n    {\n        auto lc = get_scalar_coeffs(mesh, eli, lambda);\n        auto uc = get_scalar_coeffs(mesh, eli, mu);\n        const auto &el_info = mesh.element(eli);\n        const auto nn = el_info.node_numbers();\n        const auto el = instantiate_element(mesh, eli);\n        const auto local_K = element_stiffness_matrix(el, lc, uc);\n\n        for (size_t j = 0; j < nn.size(); ++j)\n        {\n            for (size_t k = j; k < nn.size(); ++k)\n            {\n                K.insert_entry(nn[j] * 2, nn[k] * 2, local_K(2 * j, 2 * k));\n                if (k != j)\n                {\n                    K.insert_entry(nn[j] * 2 + 1, nn[k] * 2, local_K(2 * j + 1, 2 * k));\n                }\n                K.insert_entry(nn[j] * 2, nn[k] * 2 + 1, local_K(2 * j, 2 * k + 1));\n                K.insert_entry(nn[j] * 2 + 1, nn[k] * 2 + 1, local_K(2 * j + 1, 2 * k + 1));\n            }\n        }\n    }\n\n    return K;\n}\n\nextern template StiffnessType assemble_stiffness<Mesh1>(const Mesh1 &, double, double);\nextern template StiffnessType\nassemble_stiffness<Mesh1>(const Mesh1 &, const Eigen::VectorXd &, const Eigen::VectorXd &);\nextern template StiffnessType assemble_stiffness<Mesh2>(const Mesh2 &, double, double);\nextern template StiffnessType\nassemble_stiffness<Mesh2>(const Mesh2 &, const Eigen::VectorXd &, const Eigen::VectorXd &);\n\n#if ELASTICITY_MAX_ELEMENT_ORDER > 2\nextern template StiffnessType assemble_stiffness<Mesh3>(const Mesh3 &, double, double);\nextern template StiffnessType\nassemble_stiffness<Mesh3>(const Mesh3 &, const Eigen::VectorXd &, const Eigen::VectorXd &);\n#endif\n\n#if ELASTICITY_MAX_ELEMENT_ORDER > 3\nextern template StiffnessType assemble_stiffness<Mesh4>(const Mesh4 &, double, double);\nextern template StiffnessType\nassemble_stiffness<Mesh4>(const Mesh4 &, const Eigen::VectorXd &, const Eigen::VectorXd &);\n#endif\n\ntemplate <>\ninline StiffnessType\nassemble_stiffness<MeshVariant>(const MeshVariant &mv, double lambda, double mu)\n{\n    return std::visit(\n        [lambda, mu](const auto &mesh) { return assemble_stiffness(mesh, lambda, mu); }, mv);\n}\n\ntemplate <>\ninline StiffnessType assemble_stiffness<MeshVariant>(\n    const MeshVariant &mv, const Eigen::VectorXd &lambda, const Eigen::VectorXd &mu)\n{\n    return std::visit(\n        [&lambda, &mu](const auto &mesh) { return assemble_stiffness(mesh, lambda, mu); }, mv);\n}\n\n/*\n * Add a homogeneous Dirichlet condition on the boundary segment of the mesh\n * indexed by `which`. K is the stiffness matrix obtained from\n * `assemble_stiffness`, and `rhs` is the forcing vector.\n */\ntemplate <class Mesh, class RHS>\nvoid impose_homogeneous_condition(\n    const Mesh &mesh, StiffnessType &K, RHS &rhs, size_t which, double scale = 1.0)\n{\n    if constexpr (std::is_same_v<Mesh, MeshVariant>)\n    {\n        std::visit(\n            [&, which, scale](const auto &mesh)\n            { impose_homogeneous_condition(mesh, K, rhs, which, scale); },\n            mesh);\n    }\n    else\n    {\n        std::vector<size_t> adjacent;\n        adjacent.reserve(2 * max_node_adjacencies);\n        const auto &boundary = mesh.boundary(which);\n\n        for (auto n : boundary.nodes)\n        {\n            adjacent.clear();\n            // Get all of the adjacent DOFs to this one; since there are two\n            // components of displacement there are 2 degrees of freedom (2*n,\n            // 2*n+1) corresponding to each node.\n            for (auto n2 : mesh.adjacent_nodes(n))\n            {\n                adjacent.push_back(2 * n2);\n                adjacent.push_back(2 * n2 + 1);\n            }\n            K.eliminate_dof(2 * n, 0.0, scale, rhs, adjacent);\n            K.eliminate_dof(2 * n + 1, 0.0, scale, rhs, adjacent);\n        }\n    }\n}\n\nstruct PreEliminatedStiffness\n{\n};\n\ntemplate <class Mesh, class RHS>\nvoid impose_homogeneous_condition(\n    const Mesh &mesh, PreEliminatedStiffness, RHS &rhs, size_t which)\n{\n    if constexpr (std::is_same_v<Mesh, MeshVariant>)\n    {\n        std::visit(\n            [&, which](const auto &mesh)\n            { impose_homogeneous_condition(mesh, PreEliminatedStiffness{}, rhs, which); },\n            mesh);\n    }\n    else\n    {\n        const auto &boundary = mesh.boundary(which);\n\n        for (auto n : boundary.nodes)\n        {\n            rhs.row(2 * n).array() = 0;\n            rhs.row(2 * n + 1).array() = 0;\n        }\n    }\n}\n\ntemplate <class Mesh>\nvoid impose_homogeneous_condition(\n    const Mesh &mesh, StiffnessType &K, size_t which, double scale = 1.0)\n{\n    std::vector<size_t> adjacent;\n    adjacent.reserve(2 * max_node_adjacencies);\n    const auto &boundary = mesh.boundary(which);\n\n    for (auto n : boundary.nodes)\n    {\n        adjacent.clear();\n        // Get all of the adjacent DOFs to this one; since there are two\n        // components of displacement there are 2 degrees of freedom (2*n,\n        // 2*n+1) corresponding to each node.\n        for (auto n2 : mesh.adjacent_nodes(n))\n        {\n            adjacent.push_back(2 * n2);\n            adjacent.push_back(2 * n2 + 1);\n        }\n        K.eliminate_dof(2 * n, 0.0, scale, adjacent);\n        K.eliminate_dof(2 * n + 1, 0.0, scale, adjacent);\n    }\n}\n\ntemplate <>\nvoid impose_homogeneous_condition(const MeshVariant &, StiffnessType &, size_t, double);\n\nstruct OutOfBoundsIndex : public std::exception\n{\n    const char *msg;\n    OutOfBoundsIndex(const char *m) : msg(m) {}\n    const char *what() const noexcept { return msg; }\n};\n\ntemplate <class Mesh, class RHS>\nvoid impose_dirichlet_condition(\n    const Mesh &mesh, StiffnessType &K, RHS &rhs, size_t which, const Eigen::Matrix2Xd &value,\n    double scale = 1.0)\n{\n    if constexpr (std::is_same_v<Mesh, MeshVariant>)\n    {\n        std::visit(\n            [&, which, scale](const auto &mesh)\n            { impose_dirichlet_condition(mesh, K, rhs, which, value, scale); },\n            mesh);\n    }\n    else\n    {\n        std::vector<size_t> adjacent;\n        adjacent.reserve(2 * max_node_adjacencies);\n        const auto &boundary = mesh.boundary(which);\n\n        if ((size_t)value.cols() != boundary.nodes.size())\n        {\n            throw OutOfBoundsIndex(\n                \"Matrix given for Dirichlet condition has wrong number of values\");\n        }\n        else if ((size_t)rhs.rows() != mesh.num_nodes() * 2)\n        {\n            throw OutOfBoundsIndex(\"RHS passed has wrong dimension - should be 2 * num_nodes\");\n        }\n\n        size_t i = 0;\n        for (auto n : boundary.nodes)\n        {\n            adjacent.clear();\n            for (auto n2 : mesh.adjacent_nodes(n))\n            {\n                adjacent.push_back(2 * n2);\n                adjacent.push_back(2 * n2 + 1);\n            }\n            K.eliminate_dof(2 * n, value(0, i), scale, rhs, adjacent);\n            K.eliminate_dof(2 * n + 1, value(1, i), scale, rhs, adjacent);\n            i += 1;\n        }\n    }\n}\n\ntemplate <class Force, class RHS>\nvoid add_point_force(const Force &force, size_t node, RHS &F)\n{\n    if (2 * node + 1 > F.size())\n    {\n        throw OutOfBoundsIndex(\"Node is out of bounds for given forcing vector\");\n    }\n    F[2 * node] += force[0];\n    F[2 * node + 1] += force[1];\n}\n\ntemplate <class T, class RHS, int N, class IndexContainer, int... Options>\nvoid add_point_forces(\n    const Eigen::Matrix<T, 2, N, Options...> &force, const IndexContainer &nodes, RHS &F)\n{\n    static_assert(sizeof...(Options) == 3);\n    size_t col = 0;\n    for (size_t n : nodes)\n    {\n        add_point_force(force.col(col), n, F);\n        col += 1;\n    }\n}\n\n/*\n * Where fc is a matrix containing the coefficients of the X and Y components of\n * the volume forcing in the first and second rows, respectively, integrate this\n * volume force to obtain its contribution to the linear form vector.\n */\ntemplate <class Mesh>\nEigen::Matrix2Xd integrate_volume_force(const Mesh &mesh, const Eigen::Matrix2Xd &fc);\n\nextern template Eigen::Matrix2Xd integrate_volume_force(const Mesh1 &, const Eigen::Matrix2Xd &);\nextern template Eigen::Matrix2Xd integrate_volume_force(const Mesh2 &, const Eigen::Matrix2Xd &);\n\n#if ELASTICITY_MAX_ELEMENT_ORDER > 2\nextern template Eigen::Matrix2Xd integrate_volume_force(const Mesh3 &, const Eigen::Matrix2Xd &);\n#endif\n\n#if ELASTICITY_MAX_ELEMENT_ORDER > 3\nextern template Eigen::Matrix2Xd integrate_volume_force(const Mesh4 &, const Eigen::Matrix2Xd &);\n#endif\n\ntemplate <>\ninline Eigen::Matrix2Xd integrate_volume_force(const MeshVariant &mv, const Eigen::Matrix2Xd &fc)\n{\n    return std::visit([&fc](const auto &mesh) { return integrate_volume_force(mesh, fc); }, mv);\n}\n\n/*\n * Where fc is a matrix containing coefficients of the X and Y parts of a\n * traction force on boundary bound_index, integrates this traction force to\n * find its contribution to the linear form vector.\n */\ntemplate <class Mesh>\nEigen::Matrix2Xd\nintegrate_traction_force(const Mesh &mesh, size_t bound_index, const Eigen::Matrix2Xd &fc);\n\nextern template Eigen::Matrix2Xd\nintegrate_traction_force(const Mesh1 &, size_t, const Eigen::Matrix2Xd &);\nextern template Eigen::Matrix2Xd\nintegrate_traction_force(const Mesh2 &, size_t, const Eigen::Matrix2Xd &);\n\n#if ELASTICITY_MAX_ELEMENT_ORDER > 2\nextern template Eigen::Matrix2Xd\nintegrate_traction_force(const Mesh3 &, size_t, const Eigen::Matrix2Xd &);\n#endif\n\n#if ELASTICITY_MAX_ELEMENT_ORDER > 3\nextern template Eigen::Matrix2Xd\nintegrate_traction_force(const Mesh4 &, size_t, const Eigen::Matrix2Xd &);\n#endif\n\ntemplate <>\ninline Eigen::Matrix2Xd\nintegrate_traction_force(const MeshVariant &mv, size_t bound_index, const Eigen::Matrix2Xd &fc)\n{\n    return std::visit(\n        [&fc, bound_index](const auto &mesh)\n        { return integrate_traction_force(mesh, bound_index, fc); },\n        mv);\n}\n\n/*\n * Where 'traction' is an integrated traction force on boundary 'bindex',\n * as returned from 'integrate_traction_force', adds this force to the\n * appropriate columns of 'forcing' (which, for example, might have come from\n * 'integrate_volume_force'.)\n */\nvoid add_traction_force(\n    const MeshVariant &mv, Eigen::Matrix2Xd &forcing, size_t bindex,\n    const Eigen::Matrix2Xd &traction);\n\n/*\n * Where u_true is a function taking X and Y coordinates and u is a matrix with\n * coefficients of X and Y parts of a FEM solution in its columns, compute the\n * L^2 norm of u - u_true and of u_true. Used for manufactured solution\n * verification.\n */\nstd::pair<double, double> integrate_error(\n    const MeshVariant &mesh, const Eigen::Matrix2Xd &u,\n    Eigen::Vector2d (*u_true)(std::array<double, 2>));\n\n} // namespace Elasticity\n\n#endif // LINEAR_ELASTICITY_HPP\n", "meta": {"hexsha": "2769e7c63d448d346991a68598fe2cc6107588d9", "size": 19279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "elasticity.hpp", "max_stars_repo_name": "slmcbane/Elasticity", "max_stars_repo_head_hexsha": "bf3ae6c27659d803b81fc69121a96af797616f3b", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "elasticity.hpp", "max_issues_repo_name": "slmcbane/Elasticity", "max_issues_repo_head_hexsha": "bf3ae6c27659d803b81fc69121a96af797616f3b", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "elasticity.hpp", "max_forks_repo_name": "slmcbane/Elasticity", "max_forks_repo_head_hexsha": "bf3ae6c27659d803b81fc69121a96af797616f3b", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7635726795, "max_line_length": 98, "alphanum_fraction": 0.67052233, "num_tokens": 5023, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.44448548680419186}}
{"text": "/**\n * Author\t: Michael Fonder\n * Year\t\t: 2016\n **/\n\n#include <iostream>\n#include <sstream>\n#include <time.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <math.h>\n#include <Eigen/Dense>\n#include <Eigen/QR>\n#include <Eigen/Dense>\n#include <Eigen/Eigen>\n#include <Eigen/Sparse>\n\n#include <unordered_map>\n#include <unordered_set>\n#include <set>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/video/video.hpp>\n#include <opencv2/opencv.hpp>\n#include \"opencv2/video/tracking.hpp\"\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/core/eigen.hpp>\n\n#include \"dynamicVectorContainer.hpp\"\n#include \"dynamicVectorReference.hpp\"\n#include \"utils.hpp\"\n#include \"imuState.hpp\"\n#include \"MSCKF.hpp\"\n\n#ifndef _CRT_SECURE_NO_WARNINGS\n# define _CRT_SECURE_NO_WARNINGS\n#endif\n\nusing namespace cv;\nusing namespace std;\nusing namespace Eigen;\n\n#define Matrixfd Matrix<float, Eigen::Dynamic, Eigen::Dynamic>\n\n\nMSCKF::MSCKF()\n{\n\timustate = new IMUstate();\n\tfeatureId_cnter = 150;\n\tmaxNbrePoses = 24;\n\tmaxNbreFeatures = 50;\n\tlast_IMU_meas_time=0.0;\n\t\n\tcamera.q_CI = Mat::zeros(4,1,CV_32FC1);\n\t\n\t// normal case orientation\n\tcamera.q_CI.row(0) = 0.5;\n\tcamera.q_CI.row(1) = -0.5;\n\tcamera.q_CI.row(2) = 0.5;\n\tcamera.q_CI.row(3) = -0.5;\n\t\n\tcamProjMat = quatToProjMat(camera.q_CI);\n\t\n\t\n\tcamera.p_CI = Mat::zeros(3,1,CV_32FC1);\t\t\n\tcamera.p_CI = camProjMat*camera.p_CI;\n\t\n\tim_noise \t\t\t= 0.01;\n\ttracking_quality \t= 0.05;\n\ttracking_tresh \t\t= 0.55;\n\tposEst_tresh \t\t= 100;\n\t\n}\n\nvoid MSCKF::setCameraParams(const Mat &p_CI, const Mat &q_CI)\n{\n\tq_CI.copyTo(camera.q_CI);\n\tcamProjMat = quatToProjMat(camera.q_CI);\n\tcamera.p_CI = camProjMat*p_CI;\t\t\n}\n\nvoid MSCKF::setFilterParams(const Mat &params)\n{\n\tim_noise \t\t\t= params.at<float>(0,0);\n\tmaxNbrePoses \t\t= params.at<float>(1,0);\n\tmaxNbreFeatures \t= params.at<float>(2,0);\n}\n\n// Input == last measurement\nvoid MSCKF::propagateIMUStateAndCovar(const Measurement &measurements, float timestamp)\n{\n\tlast_IMU_meas_time = timestamp;\n\timustate->propagateState(measurements);\n\tMat Phi = imustate->propagateCovar(measurements);\n\tif(cameraPoses.size() > 0)\n\t\timuCamCovar = Phi*imuCamCovar;\n}\t\n\n/**\n* Returns current position estimation\n**/\nMat MSCKF::getPosition()\n{\n\treturn imustate->p_G;\n}\n\n/**\n* Returns current attitude estimation\n**/\nMat MSCKF::getOrientation()\n{\n\treturn imustate->q_IG;\n}\n\n/**\n* Returns current filter covariance\n**/\nMat MSCKF::getCovar()\n{\n\treturn imustate->covar;\n}\n\nvoid MSCKF::updateStateAndCovar()\n{\n\tif(features_to_residualize.size() == 0)\n\t\treturn;\n}\n\n// Augment state when new frame available\nvoid MSCKF::augmentState(const Mat &frame, float timestamp)//const Feature &feature)\n{\n\tMat Jt;\n\tCameraPose cameraPose;\n\timustate->getDelayedPose(cameraPose.pose, Jt, timestamp-last_IMU_meas_time);\n\t\n\t\n\t// store new IMU pose \t\t\n\tsize_t N = cameraPoses.size();\n\tcameraPose.pose.p.copyTo(cameraPose.p_CG);\n\tcameraPose.pose.q.copyTo(cameraPose.q_CG);\n\tcameraPoses.push_back(cameraPose);\n\t\n\taddFrame(frame);\n\t\n\tif(points.size()==0) // If no features detected for current frame, remove current camera pose\n\t\tposesToPrune.insert(cameraPoses.last());\n\t\n\t// Build MSCKF covariance matrix for state augmentation\n\tsize_t L = imustate->stateLength; // just for increased lisibility of the code\n\tMat P = Mat::zeros(L+6*N, L+6*N, CV_32FC1);\n\t(imustate->covar).copyTo(P.rowRange(0,L).colRange(0,L));\n\tif(N>0)\n\t{\n\t\tcamCovar.copyTo(P.rowRange(L, L+6*N).colRange(L,L+6*N));\n\t\ttranspose(imuCamCovar, P.rowRange(L,L+6*N).colRange(0,L));\n\t\timuCamCovar.copyTo(P.rowRange(0,L).colRange(L,L+6*N));\n\t}\n\t\n\t// Augment state\n\tMat J = calcJ(N, Jt, cameraPose, timestamp-last_IMU_meas_time+imustate->delay);\n\tMat p_aug = Mat::eye(6+L+6*N,L+6*N, CV_32FC1);\n\tJ.copyTo(p_aug.rowRange(L+6*N,6+L+6*N).colRange(0,L+6*N));\n\t\n\tp_aug = p_aug*P*(p_aug.t());\n\t\n\t// assign result\n\tp_aug.rowRange(0,L)\t\t\t.colRange(0,L)\t\t\t.copyTo(imustate->covar);\n\tp_aug.rowRange(L,L+6+6*N)\t.colRange(L,L+6+6*N)\t.copyTo(camCovar);\n\tp_aug.rowRange(0,L)\t\t\t.colRange(L, L+6+6*N)\t.copyTo(imuCamCovar);\n\t\n}\n\t\n/**\n* Extract and track features for a new incomming frame\n* Params:\n*\tframe\t: the new frame\n* Returns the number of features tracked\n**/\nint MSCKF::addFrame(const Mat &frame)\n{\n\tvector<uchar> status;\n\tvector<float> err;\n\tvector<float> err1;\n\t\n\tTermCriteria termcrit(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 20, tracking_quality);\n\tSize subPixWinSize(10,10), winSize(7,7);\n\t\n\tconst int MAX_COUNT = 10;\n\tint discontinued = 0;\n\t\n\tif(cameraPoses.size()>1 && points.size()!= 0)\n\t{\n\t\tvector<Point2f> p1(points);\n\t\tvector<Point2f> p0r(points);\n\t\t\n\t\t// doc : http://docs.opencv.org/2.4/modules/video/doc/motion_analysis_and_object_tracking.html#calcopticalflowpyrlk\n\t\tcalcOpticalFlowPyrLK(previous_frame, frame,points, p1, status, err, Size(39, 39), 4, termcrit, OPTFLOW_USE_INITIAL_FLOW);\n\t\tcalcOpticalFlowPyrLK(frame, previous_frame,p1, p0r, status, err1, Size(39, 39), 4, termcrit, OPTFLOW_USE_INITIAL_FLOW);\n\t\t\n\t\tfor(size_t i=0; i<points.size(); ++i)\n\t\t{\n\t\t\tif(norm(points[i]-p0r[i])>tracking_tresh)\n\t\t\t{\n\t\t\t\tstatus[i]= 0;\n\t\t\t\tdiscontinued++;\n\t\t\t}\n\t\t\telse\n\t\t\t\tpoints[i] = p1[i];\n\t\t}\n\t}\n\t\n\t\n\tint sx = frame.cols, sy= frame.rows;\n\t\n\tMat mask = Mat::zeros(frame.rows, frame.cols,  CV_8UC1)*255;\n\trectangle( mask, Point( sx*0.15, sy*0.15 ), Point( sx*0.85, sy*0.85), 255, -1, 8 );\n\tint size_circle = int(30*float(features.size()-discontinued)/float(maxNbreFeatures));\n\tfor(size_t i=0; i<points.size(); ++i)\n\t\tcircle(mask, points[i], size_circle, 0, -1);\n\t\n\t// Detect new features only if required\n\tif(features.size()-discontinued < maxNbreFeatures || float(countNonZero(mask))/float(sx*sy)>0.25)// && (cameraPoses.size()-1)%1 == 0)\n\t{\n\t\t\n\t\timshow(\"mask\", mask);\n\t\t\n\t\tMat descriptors1;\n\t\tvector<KeyPoint> keypoints;\n\t\tBRISK extractor(48,3,1.5);\n\t\textractor(frame, mask, keypoints, descriptors1);\n\t\t\n\t\tfor(size_t i=0; i<keypoints.size(); ++i)\n\t\t{\n\t\t\tpoints.push_back(keypoints[i].pt);\n\t\t\tids.push_back(featureId_cnter);\n\t\t\tstatus.push_back(1);\n\t\t\tFeature tmp;\n\t\t\tfeatures.insert({featureId_cnter, tmp});\n\t\t\t++featureId_cnter;\n\t\t}\n\t}\n\t\n\t// Highlight tracked features in the image\n\tmask = frame;\n\tfor(size_t i=0; i<points.size(); ++i)\n\t\tcircle(mask, points[i], 3, 255, -1);\n\t\n\timshow(\"frame\", mask);\n\twaitKey(1);\n\t\t\n\t\t\n\tfor(size_t i=0; i<points.size(); i++)\n\t{\n\t\tint x, y;\n\t\tx = points[i].x;\n\t\ty = points[i].y;\n\t\t\n\t\t// Discard features too close from the borders of the image\n\t\tif(status[i] == 1 && (x<0.15*sx || x>0.85*sx || y<0.15*sy || y>0.85*sy))\n\t\t{\n\t\t\tstatus[i] = 0;\n\t\t}\n\t}\n\t\n\t// Add point updates to data structure\n\tint longest = -1, max_size = 0;\n\tfor(size_t i=0; i<points.size(); )\n\t{\n\t\tif(max_size<features[ids[i]].positions.size())\n\t\t{\n\t\t\tlongest  = i;\n\t\t\tmax_size = features[ids[i]].positions.size();\n\t\t}\n\t\t\n\t\tif(status[i] == 1)\n\t\t{\n\t\t\tMat matPoint(1,1,CV_32FC2);\n\t\t\tfloat x = 160, y=120;\n\t\t\tmatPoint = {points[i].x, points[i].y};\n\t\t\tundistortPoints(matPoint, matPoint,camera.intrisic, camera.distCoeffs);\n\t\t\tint test = ids[i];\n\t\t\tfeatures[ids[i]].positions.push_back(matPoint.reshape(1,2));\n\t\t\tfeatures[ids[i]].cameraPoses.push_back(cameraPoses.last());\n\t\t\t(cameraPoses.last())->featuresId.insert(ids[i]);\n\t\t\t++i;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfeatures_to_residualize.insert(ids[i]);\n\t\t\tpoints.erase(points.begin()+i);\n\t\t\tids.erase(ids.begin()+i);\n\t\t\tstatus.erase(status.begin()+i);\n\t\t}\n\t}\n\t\n\tif(features_to_residualize.size() < 1 && longest >= 0)\n\t{\n\t\tfeatures_to_residualize.insert(ids[longest]);\n\t\tpoints.erase(points.begin()+longest);\n\t\tids.erase(ids.begin()+longest);\n\t\tstatus.erase(status.begin()+longest);\n\t}\n\t\n\tframe.copyTo(previous_frame);\n}\n\n/**\n* Performs the EKF update step\n**/\nvoid MSCKF::update()\n{\t\t\n\textractVariablesToPrune();\n\t\n\t// Exit function if nothing has to be done\n\tif(features_to_residualize.size() == 0 && posesToPrune.size()==0)\n\t\treturn;\n\t\n\t\n\t// Assemble covariance matrix\n\tsize_t N = imustate->stateLength + imuCamCovar.cols;\n\tMat P = Mat::zeros(N,N,CV_32FC1);\n\timustate->covar.copyTo(P.rowRange(0,imustate->stateLength).colRange(0, imustate->stateLength));\n\timuCamCovar.copyTo(P.rowRange(0,imustate->stateLength).colRange(imustate->stateLength, N));\n\ttranspose(imuCamCovar, P.rowRange(imustate->stateLength, N).colRange(0, imustate->stateLength));\n\tcamCovar.copyTo(P.rowRange(imustate->stateLength, N).colRange(imustate->stateLength, N));\n\t\n\tMat Ho, ro, Ro;\n\t\n\tint accepted_features = 0;\n\t\n\tfor(std::unordered_set<int32_t>::iterator it = features_to_residualize.begin(); it != features_to_residualize.end(); it++)\n\t{\n\t\tMat p_f_G, Hoj, Aj;\n\t\tint test = *it;\n\t\tFeature feature = features.find(*it)->second;\n\t\t\n\t\tif(feature.cameraPoses.size() < 3)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tfloat d = calcGNPosEst(features[*it], p_f_G);\n\t\tif(d/float(features[*it].positions.size())>posEst_tresh)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tcalcHoj(p_f_G, feature, Hoj, Aj);\n\t\t\n\t\t//Compute residuals\n\t\tMat rj(2*feature.positions.size(), 1, CV_32FC1); // NOTE : Previously : Mat rj = Mat::zeros(2*feature.positions.size(), 1, CV_32FC1);\n\t\tfor(size_t i=0; i<feature.positions.size(); ++i)\n\t\t{\n\t\t\tMat C_CG = camProjMat*quatToProjMat((feature.cameraPoses[i]).q_CG);\n\t\t\tMat p_f_C = C_CG*(p_f_G-(feature.cameraPoses[i]).p_CG)-camera.p_CI;\n\t\t\t\n\t\t\trj.at<float>(2*i,  0) = p_f_C.at<float>(0,0)/p_f_C.at<float>(2,0);\n\t\t\trj.at<float>(2*i+1,0) = p_f_C.at<float>(1,0)/p_f_C.at<float>(2,0);\n\t\t\trj.rowRange(2*i, 2*i+2) = feature.positions[i] - rj.rowRange(2*i, 2*i+2);\n\t\t}\n\t\t\n\t\trj = Aj.t()*rj;\t\n\t\t\n\t\t// Mahanalobis gating test\n\t\tMat Rj = Mat::eye(rj.rows, rj.rows, CV_32FC1)*im_noise;\n\t\tMat S = Hoj*P*Hoj.t()+Rj;\n\t\tMat MD;\n\t\tMat tmp3;\n\t\tmySolve(S,rj,MD);\n\t\tMD = rj.t()*MD;\ncout << \"MD : \" << MD <<chiSquared(rj.rows) << endl;\n\t\tif(isnan(abs(MD.at<float>(0,0))) || MD.at<float>(0,0) > chiSquared(rj.rows))\n\t\t\tcontinue;\n\t\t\n\t\t// Project matrices on the left nullspace\n\t\tHo.push_back(Hoj);\n\t\t\n\t\n\t\tro.push_back(rj);\n\t\t\n\t\t// Push Rj on the diag of Ro\n\t\tMat tmp = Mat::zeros(Ro.rows+Rj.rows, Ro.cols+Rj.cols, CV_32FC1);\n\t\tRo.copyTo(tmp.rowRange(0, Ro.rows).colRange(0, Ro.cols));// += Ro;\n\t\tRj.copyTo(tmp.rowRange(Ro.rows, Ro.rows+Rj.rows).colRange(Ro.cols,Ro.cols+Rj.cols));// += Rj;\n\t\ttmp.copyTo(Ro);\n\t\t\n\t\t++accepted_features;\n\t}\n\t\n\t\n\tif(accepted_features > 0) //Do filter update only if there are some residuals to process\n\t{\n\t\tMat Q1, Th;\n\t\t{\t// Compute range space of Ho to speed up following computations\n\t\t\tMatrixXf eigenHo;\n\t\t\tcv2eigen(Ho, eigenHo);\n\t\t\tFullPivHouseholderQR<MatrixXf> qr(eigenHo);\n\t\t\tMatrixXf Q = qr.matrixQ();\n\t\t\tMatrixXf R = qr.matrixQR().triangularView<Eigen::Upper>();\n\t\t\tR = R*qr.colsPermutation().inverse();\n\t\t\tcout << \"range space computed\"<<endl;\n\t\t\t\n\t\t\teigen2cv(Q, Q1);\n\t\t\teigen2cv(R, Th);\n\t\t}\n\t\t\n\t\t// Speed boost by eliminating noise from the residuals\n\t\tfor(size_t i=0; i<Th.rows; ++i)\n\t\t{\n\t\t\tsize_t j=0;\n\t\t\tfor(; j<Th.cols;++j)\n\t\t\t\tif(Th.at<float>(i,j)!=0)\n\t\t\t\t\tbreak;\n\t\t\tif(j==Th.cols)\n\t\t\t{\n\t\t\t\tTh.rowRange(0,i).copyTo(Th);\n\t\t\t\tQ1.colRange(0,i).copyTo(Q1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tRo = Q1.t()*Ro*Q1;\n\t\tMat rn = Q1.t()*ro;\n\t\trn.copyTo(ro);\n\t\t\n\t\t\n\t\tMat tmp2 = Th*P*Th.t()+Ro;\t\t\t\n\t\tMat K;\n\t\t{\n\t\t\tMatrixXf A, b;\n\t\t\tcv2eigen(tmp2.t(), A);\n\t\t\tcv2eigen((P*Th.t()).t(), b);\n\t\t\t\n\t\t\t// Choose your own solving method\n// \t\t\t\tMatrixXf K2 = A.colPivHouseholderQr().solve(b);\n\t\t\tMatrixXf K2 = A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b);\n//\t\t\t\tMatrixXf K2 = A.householderQr().solve(b);\n\t\t\t\n\t\t\teigen2cv(K2, K);\n\t\t}\n\t\ttranspose(K,K);\n\t\t\n\t\t// State correction term\n\t\tMat deltaX = K*ro;\n\t\tcout << \"DeltaX : \" << endl << deltaX << endl;\n\t\t\n\t\t\n\t\tif(isnan(abs(deltaX.at<float>(0,0))) || isinf(abs(deltaX.at<float>(0,0))))\n\t\t{\n\t\t\tcout << \"Warning ill conditionned matrices : State correction failed\" << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tupdateState(deltaX);\n\t\t\t\n\t\t\t// Covariance correction\n\t\t\tMat tmp = Mat::eye(N,N, CV_32FC1) - K*Th;\n\t\t\tP = tmp*P*tmp.t() + K*Ro*K.t(); // P corrected\n\t\t\t\n\t\t\tP.rowRange(0,imustate->stateLength).colRange(0,imustate->stateLength)  .copyTo(imustate->covar);\n\t\t\tP.rowRange(0, imustate->stateLength).colRange(imustate->stateLength,N) .copyTo(imuCamCovar);\n\t\t\tP.rowRange(imustate->stateLength, N).colRange(imustate->stateLength, N).copyTo(camCovar);\n\t\t}\n\t}\n\t\n\t// State pruning\n\tpruneState();\n}\n\n/**\n* Computes Jacobian used to augment the state\n* Params:\n*\tN \t\t\t: Number of camera poses stored in the state;\n*\tJt\t\t\t: Jacobian of the time delay;\n* \tcameraPose \t: camera pose;\n* \ttimeStep\t: timestep between last received IMU measurements and current frame;\n* Returns the Jacobian martix\n**/\nMatExpr MSCKF::calcJ(size_t N, const Mat &Jt, CameraPose &cameraPose, float timeStep)\n{\n\tMat rotMat = quatToProjMat(cameraPose.pose.q);\n\tMat J = Mat::zeros(6, (imustate->stateLength)+6*N, CV_32FC1);\n\tJ.rowRange(0,3).colRange(0,3) = Mat::eye(3,3,CV_32FC1);\n\tJ.rowRange(3,6).colRange(12,15) = Mat::eye(3,3,CV_32FC1);\n\tJ.rowRange(3,6).colRange(6,9) = Mat::eye(3,3,CV_32FC1)*timeStep;\n\tJ.rowRange(0,6).colRange(15,16) = Jt;\n\t\n\treturn J+0.0;\t\t\n}\n\n/**\n* Computes Jacobian of a feature track for the state update\n* Params:\n*\tp_f_G \t: feature position in the global frame;\n*\tfeature\t: feature track;\n* \tHoj \t: resulting matrix;\n* \tAj\t\t: nullspace of Hfi\n**/\nvoid MSCKF::calcHoj(const Mat &p_f_G, const Feature &feature, Mat &Hoj, Mat &Aj) //const &feature?\n{\n\tsize_t IMU = imustate->stateLength; // length of IMU state\n\tsize_t N = cameraPoses.size();\n\tsize_t M = feature.positions.size();\n\tMat Hfj = Mat::zeros(2*M, 3, CV_32FC1);\n\tMat Hxj = Mat::zeros(2*M, IMU+6*N, CV_32FC1);\n\t\n\t\n\tfor(size_t i=0; i<feature.positions.size(); i++)\n\t{\n\t\tint camPoseIndex = cameraPoses.getIndex(feature.cameraPoses.at(i));\n\t\tMat p_CG = (feature.cameraPoses[i]).pose.p;\n\t\tMat q_CG = (feature.cameraPoses[i]).pose.q;\n\t\t\n\t\t// Express feature position in the camera frame\n\t\tMat p_f_C = camProjMat*quatToProjMat((feature.cameraPoses[i]).q_CG)*(p_f_G-(feature.cameraPoses[i]).p_CG)-camera.p_CI;\n\t\tMat C_CG = camProjMat*quatToProjMat(q_CG);\n\t\t\n\t\tMat Ji = Mat::zeros(2,3, CV_32FC1);\n\t\tJi.at<float>(0,0) = 1;\n\t\tJi.at<float>(1,1) = 1;\n\t\tJi.at<float>(0,2) = -p_f_C.at<float>(0,0)/p_f_C.at<float>(2,0);\n\t\tJi.at<float>(1,2) = -p_f_C.at<float>(1,0)/p_f_C.at<float>(2,0);\n\t\tJi /= p_f_C.at<float>(2,0);\n\t\t\n\t\t\n\t\tMat pos_diff = p_f_G-p_CG;\n\t\tMat tmp = Mat::zeros(2,6, CV_32FC1);\n\t\t\n\t\t// Jacobian of the residual with respect to the feature position\n\t\tHfj.rowRange(2*i, 2*i+2) = Ji*camProjMat*quatToProjMat((feature.cameraPoses[i]).q_CG);\n\t\t\n\t\t// Jacobian of the residual with respect to the IMU pose\n\t\ttmp.colRange(0, 3) = Hfj.rowRange(2*i, 2*i+2)*crossMat(pos_diff);//Ji*C_CG*crossMat(pos_diff);\n\t\ttmp.colRange(3, 6) = -Hfj.rowRange(2*i, 2*i+2);//Ji*C_CG;\n\t\ttmp.copyTo(Hxj.rowRange(2*i, 2*i+2).colRange(IMU+6*camPoseIndex, IMU+6*camPoseIndex+6));\n\t\t\n\t\t// Jacobian of the residual with respect to the time delay\n\t\tHxj.rowRange(2*i, 2*i+2).colRange(15, 16) = -Ji*camProjMat*(crossMat((feature.cameraPoses[i]).pose.ang_vel).t())*quatToProjMat((feature.cameraPoses[i]).q_CG)*pos_diff-Ji*C_CG*(feature.cameraPoses[i]).pose.v;\n\t\t\n\t\t// Jacobian of the residual with respect to the camera pose\n\t\tHxj.rowRange(2*i, 2*i+2).colRange(16, 19) = Ji*camProjMat*crossMat(quatToProjMat(q_CG)*pos_diff);\n\t\tJi.copyTo(Hxj.rowRange(2*i, 2*i+2).colRange(19, 22));\n\t}\n\t\n\t// QR decomposition to have nullspace\n\tMatrixXf eigenHfj;\n\tcv2eigen(Hfj, eigenHfj);\n\tColPivHouseholderQR<MatrixXf> qr(eigenHfj);\n\tMatrixXf Q = qr.matrixQ();\n\tQ = Q.rightCols(eigenHfj.rows()-eigenHfj.cols());\n\teigen2cv(Q, Aj);\n\t\n\t// projection on the nullspace of the Jacobian of the residual with respect to the feature position\n\tHoj = Aj.t()*Hxj;\n}\n\n/**\n* Builds camera matrix from camera orientation and location\n* Params:\n*\tC \t: rotation matrix;\n*\tt \t: translation matrix;\n* Returns camera matrix\n**/\t\nMat MSCKF::buildCameraMatrix(const Mat &C, const Mat &t)\n{\n\tMat matrix = Mat::zeros(3,4, CV_32FC1);\n\tC.copyTo(matrix.colRange(0,3));\n\tt.copyTo(matrix.col(3));\n\treturn matrix+0.0;\n}\n\n\n/**\n* Solves the AX=b linear system\n* Params:\n*\tA \t: A matrix;\n*\tb \t: b matrix;\n* \tres : matrix to store the result;\n**/\t\nvoid MSCKF::mySolve(const Mat &A, const Mat &b, Mat &res)\n{\n\tMatrixfd eigA, eigb;\n\tcv2eigen(A, eigA);\n\tcv2eigen(b, eigb);\n\tMatrixfd eigRes = eigA.colPivHouseholderQr().solve(eigb);\n\teigen2cv(eigRes, res);\n}\n\n\n/**\n* Performs Gauss-Newton regression on a set of points corresponding to a same feature to estimate its 3d location\n* Params:\n*\tfeature : the feature whose position needs to be estimated;\n*\tpos \t: a matrix to store the result;\n**/\t\nfloat MSCKF::calcGNPosEst(const Feature &feature, Mat &pos)\n{\n\tpos = Mat::zeros(3,1, CV_32FC1);\t\t\n\tMat posCop;\n\tMat p_IC = camProjMat.t()*camera.p_CI;\n\t\n\t{\t// get estimate of feature position by triangulation for state initialisation\n\t\tMat point_4d;\n\t\tMat C1 = camProjMat*quatToProjMat(feature.cameraPoses.front().q_CG);\n\t\tMat C2 = camProjMat*quatToProjMat(feature.cameraPoses.back().q_CG);\n\t\tMat t1 = C1*feature.cameraPoses.front().p_CG+camera.p_CI;\n\t\tMat t2 = C2*feature.cameraPoses.back().p_CG+camera.p_CI;\n\t\t\n\t\ttriangulatePoints( buildCameraMatrix(C1, -t1), buildCameraMatrix(C2, -t2),\n\t\t\t\t\t\tfeature.positions.front(), feature.positions.back(), point_4d);\n\t\t\n\t\tfor(size_t i=0; i<3; ++i)\n\t\t\tpos.at<float>(i,0) = point_4d.at<float>(i,0)/point_4d.at<float>(3,0);\n\t\t\n\t\tpos = C1*(pos)-t1;\n\t}\n\t\n\t//Inverse depth parametrisation\n\tMat xEst = Mat::ones(3,1, CV_32FC1);\n\txEst.at<float>(0,0) = pos.at<float>(0,0)/pos.at<float>(2,0); //alphaBar\n\txEst.at<float>(1,0) = pos.at<float>(1,0)/pos.at<float>(2,0); //betaBar\n\txEst.at<float>(2,0) /= pos.at<float>(2,0);\t\t\t //rhoBar\n\t\n\tsize_t n = feature.cameraPoses.size();\n\tint maxIter = 10;\n\t\n\tMat prov;\t\t\n\tCameraPose cp_1;\n\tprov = quatLeftComp(camera.q_CI)*feature.cameraPoses.front().q_CG;\n\tprov = prov/norm(prov);\n\tprov.copyTo(cp_1.q_CG);\n\tprov = feature.cameraPoses.front().p_CG + quatToProjMat(cp_1.q_CG).t()*camera.p_CI;\n\tprov.copyTo(cp_1.p_CG);\n\t\n\t\n\tMat sqrErr_prev = Mat::zeros(1,1,CV_32FC1);\n\tMat sqrErr;\n\tfor(size_t iter=0; iter<maxIter; iter++)\n\t{\n\t\tMat E = Mat::zeros(2*n, 3, CV_32FC1);\n\t\tMat errorVec = Mat::zeros(2*n,1, CV_32FC1);\n\t\t\n\t\tfor(size_t i=0; i<n; i++)\n\t\t{\t\t\t\n\t\t\tCameraPose cp_i;\n\t\t\tprov = quatLeftComp(camera.q_CI)*feature.cameraPoses[i].q_CG;\n\t\t\tprov = prov/norm(prov);\n\t\t\tprov.copyTo(cp_i.q_CG);\n\t\t\tprov = feature.cameraPoses[i].p_CG + quatToProjMat(cp_i.q_CG).t()*camera.p_CI;\n\t\t\tprov.copyTo(cp_i.p_CG);\n\t\t\t\n\t\t\t// Compute evolution between first and current camera pose\t\n\t\t\tMat C_i1 = quatToProjMat(cp_i.q_CG)*(quatToProjMat(cp_1.q_CG).t());\n\t\t\tMat t_i1 = quatToProjMat(cp_i.q_CG)*(cp_1.p_CG - cp_i.p_CG);\n\t\t\t\n\t\t\t// Compute residuals\n\t\t\tMat tmp = Mat::ones(3,1, CV_32FC1);\n\t\t\txEst.rowRange(0,2).copyTo(tmp.rowRange(0,2));\n\t\t\tMat h = C_i1*tmp + xEst.at<float>(2,0)*t_i1;\n\t\t\ttmp = Mat::ones(2,1,CV_32FC1);\n\t\t\ttmp.at<float>(0,0) = h.at<float>(0,0)/h.at<float>(2,0);\n\t\t\ttmp.at<float>(1,0) = h.at<float>(1,0)/h.at<float>(2,0);\n\t\t\t\n\t\t\t// Reproject estimated feature location in the 2d plane to compute the residuals\n\t\t\terrorVec.rowRange(2*i,2*i+2) = feature.positions[i]-tmp;\n\t\t\t\n\t\t\t// Form the Jacobian from eq. (39) in TR_MSCKF\n\t\t\t\n\t\t\t//dEdalpha\n\t\t\tE.at<float>(2*i, 0)   = -C_i1.at<float>(0,0)/h.at<float>(2,0) + (h.at<float>(0,0)/(h.at<float>(2,0)*h.at<float>(2,0)))*C_i1.at<float>(2,0);\n\t\t\tE.at<float>(2*i+1, 0) = -C_i1.at<float>(1,0)/h.at<float>(2,0) + (h.at<float>(1,0)/(h.at<float>(2,0)*h.at<float>(2,0)))*C_i1.at<float>(2,0);\n\t\t\t//dEdbeta\n\t\t\tE.at<float>(2*i, 1)   = -C_i1.at<float>(0,1)/h.at<float>(2,0) + (h.at<float>(0,0)/(h.at<float>(2,0)*h.at<float>(2,0)))*C_i1.at<float>(2,1);\n\t\t\tE.at<float>(2*i+1, 1) = -C_i1.at<float>(1,1)/h.at<float>(2,0) + (h.at<float>(1,0)/(h.at<float>(2,0)*h.at<float>(2,0)))*C_i1.at<float>(2,1);\n\t\t\t//dEdrho\n\t\t\tE.at<float>(2*i, 2)   = -t_i1.at<float>(0,0)/h.at<float>(2,0) + (h.at<float>(0,0)/(h.at<float>(2,0)*h.at<float>(2,0)))*t_i1.at<float>(2,0);\n\t\t\tE.at<float>(2*i+1, 2) = -t_i1.at<float>(1,0)/h.at<float>(2,0) + (h.at<float>(1,0)/(h.at<float>(2,0)*h.at<float>(2,0)))*t_i1.at<float>(2,0);\n\t\t}\n\t\t\n\t\tMat delta;\n\n\t\tmySolve(E.t()*E, E.t()*errorVec, delta);\n\t\txEst -= delta;\n\t\t\n\t\tsqrErr = 0.5*errorVec.t()*errorVec;\n\t\tMat err = (sqrErr-sqrErr_prev)/n;//sqrErr;\n\t\tsqrErr.copyTo(sqrErr_prev);\n\t\t\n\t\t// Stop if gain in precision is too small\n\t\tif(err.at<float>(0,0) < 0.0000001)\n\t\t\tbreak;\t\t\t\n\t}\n\t\n\t// Reproject the feature location into the global referential\n\tMat tmp = Mat::ones(3,1, CV_32FC1);\n\txEst.rowRange(0,2).copyTo(tmp.rowRange(0,2));\n\tpos = (1/xEst.at<float>(2,0))*(quatToProjMat(cp_1.q_CG).t())*tmp +cp_1.p_CG;\n\treturn sqrErr.at<float>(0,0);\n}\n\n/**\n* Extracts the data to use for an EKF filter update\n**/\nvoid MSCKF::extractVariablesToPrune()\n{\n\t// Prepare features pruning\n\tfor(std::unordered_set<int32_t>::iterator it = features_to_residualize.begin(); it != features_to_residualize.end(); it++)\n\t{\n\t\tFeature feature = features.find(*it)->second;\n\t\tfor(size_t i=0; i<feature.cameraPoses.size(); ++i)\n\t\t{\n\t\t\tfeature.cameraPoses[i].featuresId.erase(*it);\n\t\t\tif(feature.cameraPoses[i].featuresId.size() == 0)\n\t\t\t\tposesToPrune.insert(feature.cameraPoses.at(i));\n\t\t}\n\t}\n\t\n\t// Prepare camera states pruning if too much poses in memory\n\tif(cameraPoses.size()-posesToPrune.size() < maxNbrePoses)\n\t\treturn;\n\t\n\tstd::unordered_map<int32_t, int32_t> features_correspondance;\n\t\n\t// Going through poses to prune\n\tfor(size_t i=1; i<cameraPoses.size(); i+=3)\n\t{\n\t\t// Going through each feature detected for current pose\n\t\t\n\t\tfor(std::unordered_set<int32_t>::iterator it = cameraPoses[i].featuresId.begin(); it != cameraPoses[i].featuresId.end(); ++it)\n\t\t{\n\t\t\tif(features_to_residualize.find(*it) != features_to_residualize.end())\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tif(features_correspondance.find(*it) == features_correspondance.end())\n\t\t\t{\n\t\t\t\t// Create temporary features to store information of features present in camera poses to prune\n\t\t\t\tfeatures_correspondance.insert({*it, featureId_cnter});\n\t\t\t\tint index = features[*it].cameraPoses.getIndex(cameraPoses.at(i));\n\t\t\t\tFeature feature;\n\t\t\t\tfeatures.insert({featureId_cnter, feature});\n\t\t\t\tfeatures[*it].truePos.copyTo(features[featureId_cnter].truePos);\n\t\t\t\tfeatures_to_residualize.insert(featureId_cnter);\n\t\t\t\t++featureId_cnter;\n\t\t\t\t\n\t\t\t\tfeatures_to_prune.push_back(*it);\n\t\t\t}\n\t\t\t\n\t\t\t// If feature present in previous camstates, transfer information to correct temporary feature\n\t\t\tint id = features_correspondance[*it];\n\t\t\tint index = features[*it].cameraPoses.getIndex(cameraPoses.at(i));\n\t\t\tfeatures[id].cameraPoses.push_back(cameraPoses.at(i));\n\t\t\tfeatures[id].positions.push_back(features[*it].positions[index]);\n\t\t\tfeatures[*it].positionsToPrune.insert(features[*it].positions.at(index));\n\t\t}\n\t\tposesToPrune.insert(cameraPoses.at(i));\n\t}\n}\n\n/**\n* Deletes the data to use for an EKF filter update\n**/\nvoid MSCKF::pruneState()\n{\n\tsize_t nbre_remaining_states = cameraPoses.size() - posesToPrune.size();\n\tsize_t L = imustate->stateLength;\n\tsize_t N = 6*cameraPoses.size();\n\tMat new_imuCamCovar = Mat:: zeros(L,6*nbre_remaining_states, CV_32FC1);\n\t\n\tsize_t j=0;\n\tfor(size_t i=0; i<cameraPoses.size(); ++i)\n\t{\n\t\tif(posesToPrune.find(cameraPoses.at(i)) != posesToPrune.end())\n\t\t{\n\t\t\tN = camCovar.rows-6; //6*(i-j);\n\t\t\tsize_t size = camCovar.rows;\n\t\t\tMat new_camCovar(N, N, CV_32FC1);\n\t\t\t\n\t\t\tif(j!=0)\n\t\t\t\tcamCovar.rowRange(0, 6*j).colRange(0,6*j)\t\t\t.copyTo(new_camCovar.rowRange(0, 6*j).colRange(0,6*j));\n\t\t\tif(j!=nbre_remaining_states)\n\t\t\t{\n\t\t\t\tif(j!=0)\n\t\t\t\t{\n\t\t\t\tcamCovar.rowRange(6*j+6, size).colRange(0,6*j)\t\t.copyTo(new_camCovar.rowRange(6*j, N).colRange(0,6*j));\n\t\t\t\tcamCovar.rowRange(0,6*j).colRange(6*j+6, size)\t\t.copyTo(new_camCovar.rowRange(0,6*j).colRange(6*j, N));\n\t\t\t\t}\n\t\t\t\tcamCovar.rowRange(6*j+6, size).colRange(6*j+6, size).copyTo(new_camCovar.rowRange(6*j, N).colRange(6*j, N));\n\t\t\t}\n\t\t\tnew_camCovar.copyTo(camCovar);\n\t\t}\n\t\telse\n\t\t{\n\t\t\timuCamCovar.colRange(6*i, 6*i+6).copyTo(new_imuCamCovar.colRange(6*j, 6*j+6));\n\t\t\t++j;\n\t\t}\n\t\t\n\t\t\n\t}\n\tnew_imuCamCovar.copyTo(imuCamCovar);\n\tfor(std::unordered_set<int32_t>::iterator it = features_to_residualize.begin(); it != features_to_residualize.end(); ++it)\n\t\tfeatures.erase(*it);\n\tfor(size_t i=0; i<features_to_prune.size(); ++i)\n\t{\n\t\tint32_t id = features_to_prune[i];\n\t\tfeatures[id].positions.remove(features[id].positionsToPrune);\n\t\tfeatures[id].cameraPoses.remove(posesToPrune);\n\t\tfeatures[id].positionsToPrune.clear();\n\t}\n\t\n\tcameraPoses.remove(posesToPrune);\n\tposesToPrune.clear();\n\tfeatures_to_residualize.clear();\n\tfeatures_to_prune.clear();\n}\n\n/**\n* Applies the correction step\n**/\nvoid MSCKF::updateState(const Mat &deltaX)\n{\n\n\t// Update IMU state\n\timustate->q_IG \t= quatLeftComp( imustate->q_IG) *buildUpdateQuat(deltaX.rowRange(0,3));\n\timustate->q_IG \t= imustate->q_IG/norm(imustate->q_IG);\n\timustate->bg \t+= deltaX.rowRange(3,6);\n\t\n\timustate->v_G \t+= deltaX.rowRange(6,9);\n\timustate->ba \t+= deltaX.rowRange(9,12);\n\timustate->p_G \t+= deltaX.rowRange(12,15);\n\t\n\t\n\timustate->delay += deltaX.at<float>(16,1);\n\tcamera.q_CI \t= quatLeftComp(camera.q_CI) *buildUpdateQuat(deltaX.rowRange(16,19));\n\tcamera.q_CI \t/= float(norm(camera.q_CI));\n\tcamProjMat \t\t= quatToProjMat(camera.q_CI);\n\tcamera.p_CI \t+= camProjMat*deltaX.rowRange(19,22);\n\t\n\tcout << \"Estimated time delay : \" << imustate->delay << endl;\n\t\n\t// Update camera states\n\tsize_t L = imustate->stateLength;\n\tfor(size_t i=0; i<cameraPoses.size(); ++i)\n\t{\n\t\tcameraPoses[i].p_CG += deltaX.rowRange(L+6*i+3, L+6*i+6);\n\t\tcameraPoses[i].q_CG = quatLeftComp(cameraPoses[i].q_CG)*buildUpdateQuat(deltaX.rowRange(L+6*i, L+6*i+3));\n\t\tcameraPoses[i].q_CG /= float(norm(cameraPoses[i].q_CG));\n\t}\n}", "meta": {"hexsha": "6445d3fbee99dd68045d9a26a041802ba5f2b06a", "size": 25477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MSCKF/MSCKF.cpp", "max_stars_repo_name": "michael-fonder/fonder_thesis-2016", "max_stars_repo_head_hexsha": "59631865169857f935a52ffd89a07243fe00e7d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2016-09-22T08:41:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T02:49:45.000Z", "max_issues_repo_path": "MSCKF/MSCKF.cpp", "max_issues_repo_name": "michael-fonder/fonder_thesis-2016", "max_issues_repo_head_hexsha": "59631865169857f935a52ffd89a07243fe00e7d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2016-09-06T11:25:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-31T12:29:50.000Z", "max_forks_repo_path": "MSCKF/MSCKF.cpp", "max_forks_repo_name": "michael-fonder/fonder_thesis-2016", "max_forks_repo_head_hexsha": "59631865169857f935a52ffd89a07243fe00e7d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-08-30T07:17:51.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-08T07:29:18.000Z", "avg_line_length": 29.937720329, "max_line_length": 209, "alphanum_fraction": 0.6746869726, "num_tokens": 8812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.779992900254107, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.444481022294021}}
{"text": "// Copyright 2018 Autoware Foundation. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"shape_estimation/model/bounding_box.hpp\"\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <autoware_perception_msgs/msg/shape.hpp>\n\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <tf2/LinearMath/Quaternion.h>\n#include <tf2_geometry_msgs/tf2_geometry_msgs.h>\n\n#include <algorithm>\n#include <cmath>\n#include <utility>\n#include <vector>\n\n#define EIGEN_MPL2_ONLY\n\n#include <Eigen/Core>\n\nconstexpr float epsilon = 0.001;\n\nBoundingBoxShapeModel::BoundingBoxShapeModel() : reference_yaw_(boost::none) {}\n\nBoundingBoxShapeModel::BoundingBoxShapeModel(const boost::optional<float> & reference_yaw)\n: reference_yaw_(reference_yaw)\n{\n}\n\nbool BoundingBoxShapeModel::estimate(\n  const pcl::PointCloud<pcl::PointXYZ> & cluster,\n  autoware_perception_msgs::msg::Shape & shape_output, geometry_msgs::msg::Pose & pose_output)\n{\n  float min_angle, max_angle;\n  if (reference_yaw_) {\n    min_angle = reference_yaw_.get() - autoware_utils::deg2rad(3);\n    max_angle = reference_yaw_.get() + autoware_utils::deg2rad(3);\n  } else {\n    min_angle = 0.0;\n    max_angle = M_PI / 2.0;\n  }\n  return fitLShape(cluster, min_angle, max_angle, shape_output, pose_output);\n}\n\nbool BoundingBoxShapeModel::fitLShape(\n  const pcl::PointCloud<pcl::PointXYZ> & cluster, const float min_angle, const float max_angle,\n  autoware_perception_msgs::msg::Shape & shape_output, geometry_msgs::msg::Pose & pose_output)\n{\n  // calc min and max z for height\n  float min_z = cluster.empty() ? 0.0 : cluster.at(0).z;\n  float max_z = cluster.empty() ? 0.0 : cluster.at(0).z;\n  for (const auto & point : cluster) {\n    min_z = std::min(point.z, min_z);\n    max_z = std::max(point.z, max_z);\n  }\n\n  /*\n   * Paper : IV2017, Efficient L-Shape Fitting for Vehicle Detection Using Laser Scanners\n   * Authors : Xio Zhang, Wenda Xu, Chiyu Dong and John M. Dolan\n   */\n\n  // Paper : Algo.2 Search-Based Rectangle Fitting\n  std::vector<std::pair<float /*theta*/, float /*q*/>> Q;\n  constexpr float angle_resolution = M_PI / 180.0;\n  for (float theta = min_angle; theta <= max_angle + epsilon; theta += angle_resolution) {\n    Eigen::Vector2f e_1;\n    e_1 << std::cos(theta), std::sin(theta);  // col.3, Algo.2\n    Eigen::Vector2f e_2;\n    e_2 << -std::sin(theta), std::cos(theta);  // col.4, Algo.2\n    std::vector<float> C_1;                    // col.5, Algo.2\n    std::vector<float> C_2;                    // col.6, Algo.2\n    for (const auto & point : cluster) {\n      C_1.push_back(point.x * e_1.x() + point.y * e_1.y());\n      C_2.push_back(point.x * e_2.x() + point.y * e_2.y());\n    }\n    float q = calcClosenessCriterion(C_1, C_2);  // col.7, Algo.2\n    Q.push_back(std::make_pair(theta, q));       // col.8, Algo.2\n  }\n\n  float theta_star{0.0};  // col.10, Algo.2\n  float max_q = 0.0;\n  for (size_t i = 0; i < Q.size(); ++i) {\n    if (max_q < Q.at(i).second || i == 0) {\n      max_q = Q.at(i).second;\n      theta_star = Q.at(i).first;\n    }\n  }\n  const float sin_theta_star = std::sin(theta_star);\n  const float cos_theta_star = std::cos(theta_star);\n\n  Eigen::Vector2f e_1_star;  // col.11, Algo.2\n  Eigen::Vector2f e_2_star;\n  e_1_star << cos_theta_star, sin_theta_star;\n  e_2_star << -sin_theta_star, cos_theta_star;\n  std::vector<float> C_1_star;  // col.11, Algo.2\n  std::vector<float> C_2_star;  // col.11, Algo.2\n  for (const auto & point : cluster) {\n    C_1_star.push_back(point.x * e_1_star.x() + point.y * e_1_star.y());\n    C_2_star.push_back(point.x * e_2_star.x() + point.y * e_2_star.y());\n  }\n\n  // col.12, Algo.2\n  const float min_C_1_star = *std::min_element(C_1_star.begin(), C_1_star.end());\n  const float max_C_1_star = *std::max_element(C_1_star.begin(), C_1_star.end());\n  const float min_C_2_star = *std::min_element(C_2_star.begin(), C_2_star.end());\n  const float max_C_2_star = *std::max_element(C_2_star.begin(), C_2_star.end());\n\n  const float a_1 = cos_theta_star;\n  const float b_1 = sin_theta_star;\n  const float c_1 = min_C_1_star;\n  const float a_2 = -1.0 * sin_theta_star;\n  const float b_2 = cos_theta_star;\n  const float c_2 = min_C_2_star;\n  const float a_3 = cos_theta_star;\n  const float b_3 = sin_theta_star;\n  const float c_3 = max_C_1_star;\n  const float a_4 = -1.0 * sin_theta_star;\n  const float b_4 = cos_theta_star;\n  const float c_4 = max_C_2_star;\n\n  // calc center of bounding box\n  float intersection_x_1 = (b_1 * c_2 - b_2 * c_1) / (a_2 * b_1 - a_1 * b_2);\n  float intersection_y_1 = (a_1 * c_2 - a_2 * c_1) / (a_1 * b_2 - a_2 * b_1);\n  float intersection_x_2 = (b_3 * c_4 - b_4 * c_3) / (a_4 * b_3 - a_3 * b_4);\n  float intersection_y_2 = (a_3 * c_4 - a_4 * c_3) / (a_3 * b_4 - a_4 * b_3);\n\n  // calc dimension of bounding box\n  Eigen::Vector2f e_x;\n  Eigen::Vector2f e_y;\n  e_x << a_1 / (std::sqrt(a_1 * a_1 + b_1 * b_1)), b_1 / (std::sqrt(a_1 * a_1 + b_1 * b_1));\n  e_y << a_2 / (std::sqrt(a_2 * a_2 + b_2 * b_2)), b_2 / (std::sqrt(a_2 * a_2 + b_2 * b_2));\n  Eigen::Vector2f diagonal_vec;\n  diagonal_vec << intersection_x_1 - intersection_x_2, intersection_y_1 - intersection_y_2;\n\n  // calc yaw\n  tf2::Quaternion quat;\n  quat.setEuler(/* roll */ 0, /* pitch */ 0, /* yaw */ std::atan2(e_1_star.y(), e_1_star.x()));\n\n  // output\n  shape_output.type = autoware_perception_msgs::msg::Shape::BOUNDING_BOX;\n  shape_output.dimensions.x = std::fabs(e_x.dot(diagonal_vec));\n  shape_output.dimensions.y = std::fabs(e_y.dot(diagonal_vec));\n  shape_output.dimensions.z = std::max((max_z - min_z), epsilon);\n  pose_output.position.x = (intersection_x_1 + intersection_x_2) * 0.5;\n  pose_output.position.y = (intersection_y_1 + intersection_y_2) * 0.5;\n  pose_output.position.z = min_z + shape_output.dimensions.z * 0.5;\n  pose_output.orientation = tf2::toMsg(quat);\n  // check wrong output\n  shape_output.dimensions.x = std::max(static_cast<float>(shape_output.dimensions.x), epsilon);\n  shape_output.dimensions.y = std::max(static_cast<float>(shape_output.dimensions.y), epsilon);\n\n  return true;\n}\n\nfloat BoundingBoxShapeModel::calcClosenessCriterion(\n  const std::vector<float> & C_1, const std::vector<float> & C_2)\n{\n  // Paper : Algo.4 Closeness Criterion\n  const float min_c_1 = *std::min_element(C_1.begin(), C_1.end());  // col.2, Algo.4\n  const float max_c_1 = *std::max_element(C_1.begin(), C_1.end());  // col.2, Algo.4\n  const float min_c_2 = *std::min_element(C_2.begin(), C_2.end());  // col.3, Algo.4\n  const float max_c_2 = *std::max_element(C_2.begin(), C_2.end());  // col.3, Algo.4\n\n  std::vector<float> D_1;  // col.4, Algo.4\n  for (const auto & c_1_element : C_1) {\n    const float v = std::min(max_c_1 - c_1_element, c_1_element - min_c_1);\n    D_1.push_back(v * v);\n  }\n\n  std::vector<float> D_2;  // col.5, Algo.4\n  for (const auto & c_2_element : C_2) {\n    const float v = std::min(max_c_2 - c_2_element, c_2_element - min_c_2);\n    D_2.push_back(v * v);\n  }\n  constexpr float d_min = 0.1 * 0.1;\n  constexpr float d_max = 0.4 * 0.4;\n  float beta = 0;  // col.6, Algo.4\n  for (size_t i = 0; i < D_1.size(); ++i) {\n    if (d_max < std::min(D_1.at(i), D_2.at(i))) {\n      continue;\n    }\n    const float d = std::max(std::min(D_1.at(i), D_2.at(i)), d_min);\n    beta += 1.0 / d;\n  }\n  return beta;\n}\n", "meta": {"hexsha": "3c713ba86b42a24784ef949a6f69c68b515fdd85", "size": 7886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception/object_recognition/detection/shape_estimation/lib/model/bounding_box.cpp", "max_stars_repo_name": "loop-perception/AutowareArchitectureProposal.iv", "max_stars_repo_head_hexsha": "5d8dff0db51634f0c42d2a3e87ca423fbee84348", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-09T05:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T05:53:04.000Z", "max_issues_repo_path": "perception/object_recognition/detection/shape_estimation/lib/model/bounding_box.cpp", "max_issues_repo_name": "loop-perception/AutowareArchitectureProposal.iv", "max_issues_repo_head_hexsha": "5d8dff0db51634f0c42d2a3e87ca423fbee84348", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2022-01-07T21:21:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T21:25:37.000Z", "max_forks_repo_path": "perception/object_recognition/detection/shape_estimation/lib/model/bounding_box.cpp", "max_forks_repo_name": "loop-perception/AutowareArchitectureProposal.iv", "max_forks_repo_head_hexsha": "5d8dff0db51634f0c42d2a3e87ca423fbee84348", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-09T00:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T10:23:36.000Z", "avg_line_length": 38.6568627451, "max_line_length": 95, "alphanum_fraction": 0.6749936597, "num_tokens": 2585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.44442557020609186}}
{"text": "#include <Eigen/Sparse>\n#include <Eigen/Eigenvalues>\n#include <Eigen/StdVector>\n#include <cstdlib>\n#include <iostream>\n#include <iomanip>\n#include <mpi.h>\n#include <mkl.h>\n#include <mkl_spblas.h>\n#include <fstream>\n#include <iterator>\n#include <vector>\n#include <algorithm>\n#include <complex>\n#include <sstream>\n#include <math.h>\n#include <omp.h>\n#include <numeric>\n#include <chrono>\n#include <ctime>\n#include <limits>\n#include <lyra/lyra.hpp>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <cusparse.h>\n#include <cusolverDn.h>\n#include <cuComplex.h>\n#include \"cuda.h\"\n#include \"cuda_runtime_api.h\"\n#include \"CUDAaccelerated.h\"\n#include \"bsplines.h\"\n#include \"InputParameter.h\"\n\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n\n#define watch(x) cout << (#x) << \" is \" << (x) << endl\n#define pwatch(x) cout <<\"rank \" << rank <<\" \"<< (#x) << \" is \" << (x) << endl\n#define bp(x) cout << \"breakpoint\" << (#x) << endl\n\nusing namespace Eigen;\nusing namespace std::complex_literals;\nusing namespace std::chrono;\nusing std::cout;\nusing std::endl;\n\n\n\nint dim;\nint rank,p,p_omp;\nint64_t nnz_rank;\nint states_chan_rank;\nint states_chan_rank_begin;\nint states_chan_rank_end;\n\n//This is a COO matrix that holds a tupel of values for every matrix cell\nclass SpMatrix{\n    //idea write a matrix class that has the functionality of init memory, write element,\n    //multiply\n    public: \n        std::vector<int> nnz;\n        int dim;\n        int nmbrLEGO=3;\n\n        //The COO matrix\n        std::vector<std::vector<int> > Row;\n        std::vector<std::vector<int> > Col;\n        std::vector<std::vector<double> > Value;\n        \n        //The CSR matrix\n        std::vector<std::vector<int> > RowCSR;\n        std::vector<std::vector<int> > ColCSR;\n        std::vector<std::vector<double> > ValueCSR;\n\n        //GPU accelerated matrix vector\n        //pointers to the device memory \n        std::vector<int*> LEGO_d_cooCols;\n        std::vector<int*> LEGO_d_rowPtr;\n        std::vector<double* > LEGO_d_cooVals_sorted;\n        std::vector<int*> LEGO_d_cscRows;\n        std::vector<int*>  LEGO_d_cscColPtr;\n        std::vector<double*> LEGO_d_cscVals; \n\n    void initMatrix(int nnz_input){\n        Row.resize(nmbrLEGO);\n        Col.resize(nmbrLEGO);\n        Value.resize(nmbrLEGO);\n\n        RowCSR.resize(nmbrLEGO);\n        ColCSR.resize(nmbrLEGO);\n        ValueCSR.resize(nmbrLEGO);\n\n        LEGO_d_cooVals_sorted.resize(nmbrLEGO);\n        LEGO_d_cooCols.resize(nmbrLEGO);\n        LEGO_d_rowPtr.resize(nmbrLEGO);\n        LEGO_d_cscVals.resize(nmbrLEGO);\n        LEGO_d_cscColPtr.resize(nmbrLEGO);\n        LEGO_d_cscRows.resize(nmbrLEGO);\n\n        for(int i = 0; i < nmbrLEGO; i++){\n            Row[i].resize(nnz_input);\n            Col[i].resize(nnz_input);\n            Value[i].resize(nnz_input);\n        }\n        nnz.resize(nmbrLEGO);\n\n    }\n\n\n    void writeElement(int ind, int row, int col, int LEGOind,double value){\n        //writes an element to the matrix\n        Row[LEGOind][ind] = row;\n        Col[LEGOind][ind] = col;\n        Value[LEGOind][ind] = value;\n    }\n\n    void CSRMKL(){\n        //allocate the memeory for the CSR matrices \n        watch(nmbrLEGO);\n        for(int i = 0; i < nmbrLEGO; i++){\n            watch(i);\n            watch(nnz[i]);\n            RowCSR[i].resize(dim+2);\n            ColCSR[i].resize(nnz[i]);\n            ValueCSR[i].resize(nnz[i]);\n        }\n        bp(\"Allocate memory\");\n\n        //build the CSR matrix\n        for (int i = 0; i< nmbrLEGO;i++){\n            int job[5] = {2,0,0,nnz[i],0};\n            int info = 0;\n            mkl_dcsrcoo(job,\n                    &dim,\n                    ValueCSR[i].data(),\n                    ColCSR[i].data(),\n                    RowCSR[i].data(),\n                    &nnz[i],\n                    Value[i].data(),\n                    Row[i].data(),\n                    Col[i].data(),\n                    &info\n                );\n        }\n        \n    }\n\n    void CSRonDevice(){\n        //converts the matrices stored in COO on the host to CSR on the device by \n        //calling the accoarding CUDA function\n        //iterate over the LEGO bricks\n        if(rank==0){\n             int i=0;\n             makeCSR(nnz[i],dim,Row[i].data(),Col[i].data(),Value[i].data(),LEGO_d_cooCols[i],\n                    LEGO_d_rowPtr[i], LEGO_d_cooVals_sorted[i],\n                    LEGO_d_cscRows[i],\n                    LEGO_d_cscColPtr[i], \n                    LEGO_d_cscVals[i]);\n        }\n        for(int i=1; i < nmbrLEGO; i++){\n            makeCSR(nnz[i],dim,Row[i].data(),Col[i].data(),Value[i].data(),LEGO_d_cooCols[i],\n                    LEGO_d_rowPtr[i], LEGO_d_cooVals_sorted[i],\n                    LEGO_d_cscRows[i],\n                    LEGO_d_cscColPtr[i], \n                    LEGO_d_cscVals[i]);\n\n       }\n    }\n\n    void matrixVectorUpper(int LEGO,VectorXcd &x,VectorXcd &b,VectorXcd &ft){ \n       //This is a COO matrix vector product M * x = b\n#pragma omp parallel\n        {\n        VectorXcd b_private= VectorXcd::Zero(dim);\n#pragma omp for \n        for(int  i = 0; i < nnz[LEGO]; i++)\n        {\n                b_private(Row[LEGO][i]) += Value[LEGO][i] * x(Col[LEGO][i]) * ft(LEGO);\n            if (Row[LEGO][i] != Col[LEGO][i]){\n                b_private(Col[LEGO][i]) += Value[LEGO][i] * x(Row[LEGO][i]) * std::conj(ft[LEGO]);\n            }\n        }\n#pragma omp critical \n        for(int i=0; i < dim; i++){\n            b(i) += b_private(i);\n        }\n        }\n    }\n\n    //wrapper for MKL CSR SpMV\n    void matrixVectorMKL(VectorXcd &x,VectorXcd &b,VectorXcd &ft){\n        //as the matrix is real we seperate the vectors in real and iamg parts \n        //this allows a real double multiplications\n        VectorXd dydx_rank_real = b.real();\n        VectorXd dydx_rank_imag = b.imag();\n\n       char transa = 'N';\n        char matdescra[] = {\n            'G', // type of matrix\n            ' ', // triangular indicator (ignored in multiplication)\n            ' ', // diagonal indicator (ignored in multiplication)\n            'C'  // type of indexing\n        };\n\n        double beta = 1.0;\n        for(int j = 0; j < nmbrLEGO; j++){\n            VectorXcd y_local = x * ft(j);\n            VectorXd y_local_real = y_local.real();\n            VectorXd y_local_imag = y_local.imag();\n\n            //SpMVCuda\n            double alpha=1.0;\n            //non transpose real x, real y, alpha = 1 \n            mkl_dcsrmv(&transa,\n                    &dim,\n                    &dim,\n                    &alpha, \n                    matdescra, \n                    ValueCSR[j].data(),\n                    ColCSR[j].data(),\n                    RowCSR[j].data(),\n                    RowCSR[j].data()+1,\n                    y_local_real.data(),\n                    &beta,\n                    dydx_rank_real.data());\n\n            //non transpose imag x, imag y, alpha = 1 \n             mkl_dcsrmv(&transa,\n                    &dim,\n                    &dim,\n                    &alpha, \n                    matdescra, \n                    ValueCSR[j].data(),\n                    ColCSR[j].data(),\n                    RowCSR[j].data(),\n                    RowCSR[j].data()+1,\n                    y_local_imag.data(),\n                    &beta,\n                    dydx_rank_imag.data());\n   \n            if (j != 0){\n                alpha=-1.0;\n                char transa = 'T';\n                //transpose real x, real y , alpha = -1 \n                mkl_dcsrmv(&transa,\n                    &dim,\n                    &dim,\n                    &alpha, \n                    matdescra, \n                    ValueCSR[j].data(),\n                    ColCSR[j].data(),\n                    RowCSR[j].data(),\n                    RowCSR[j].data()+1,\n                    y_local_real.data(),\n                    &beta,\n                    dydx_rank_real.data());\n   \n                //transpose imag x, imag y , alpha = -1 \n                mkl_dcsrmv(&transa,\n                    &dim,\n                    &dim,\n                    &alpha, \n                    matdescra, \n                    ValueCSR[j].data(),\n                    ColCSR[j].data(),\n                    RowCSR[j].data(),\n                    RowCSR[j].data()+1,\n                    y_local_imag.data(),\n                    &beta,\n                    dydx_rank_imag.data());\n   \n\n            }\n        }\n        //join into b \n        b.real()=dydx_rank_real;\n        b.imag()=dydx_rank_imag;\n\n    }\n};\n\nvoid Propergator(InputParameter &Inp,SpMatrix &H_rank,std::string PATH);\n\nvoid BuildMatrix(InputParameter &Inp,SpMatrix &H_rank);\n\nvoid getEigenStates(InputParameter Inp, int l,int states_chan,double dX,double &tmp_d,ArrayXd &weights,\n        ArrayXd &x,ArrayXXd &B, ArrayXXd &d_B,ArrayXXd &diff_B,ArrayXXd &psi,ArrayXXd &d_psi\n        ,ArrayXXd &diff_psi , MatrixXd &H_base, MatrixXd &S, ArrayXd &Energy);\n \n\nvoid helperEigenStates(InputParameter Inp,int states_chan,double dX,double &tmp_d,\n        ArrayXd &weights, ArrayXd &x,ArrayXXd &B,ArrayXXd &diff_B,MatrixXd &H_base, \n        MatrixXd &S);\n\nvoid polarization(SpMatrix &M,int states_chan, int &ind, int index,int l,int lm_index_L,int \n        lm_index_R, double LM_faktor,double dX,ArrayXd &weights, ArrayXd &x, ArrayXXd &psi_1,\n        ArrayXXd  &psi_2,ArrayXXd &d_psi_2);\nvoid lanczos(InputParameter Inp,SpMatrix &A, int m,VectorXcd &y , MatrixXcd &Q, MatrixXcd &h,  \n        VectorXcd &FT);\n\n\nauto stoportho = high_resolution_clock::now();\nauto startortho = high_resolution_clock::now();\nauto durationortho = duration_cast<milliseconds>(startortho-startortho);\n\n\nint main(int argc, const char** argv){\n    //Read in the sparse matrix representing the Hamiltonian\n    //The matrix is in COO format(also called matrix market format)\n    //The data is stored in 4 different files each of them \n    //obtains a vector. 2 files hold the indices for our sparse matrix and \n    //2 hold the values that belong to the to indices. One is the value \n    //belonging to the Hamiltion the other one is an integer telling us which \n    //ft to use\n    MPI_Init(NULL,NULL);\n\n    MPI_Comm_size(MPI_COMM_WORLD, &p);\n    MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n    cout << \"rank: \" << rank << \" of \" << p << \" is here\" << endl;\n    InputParameter Inp;\n\n    //map the ranks to the devices(grpahic cards)\n    //local rank within a node for multi node version\n    //this has to be chagned \n    int local_rank = rank; \n\n    p_omp = omp_get_num_threads();\n    watch(p_omp);\n    \n    //int id = omp_get_thread_num();\n    std::setprecision (15);\n   \n    //Inp.ReadInput(argc,argv);\n    auto cli   \n        =   lyra::opt(Inp.nnz, \"nnz\")\n            [\"-nnz\"][\"--nnz\"]\n            (\"Number of max nnz\")\n        | lyra::opt(Inp.om, \"om\")\n            [\"-om\"][\"--om\"]\n            (\"Photon Energy\")\n        | lyra::opt(Inp.E0, \"E0\")\n            [\"-E0\"][\"--E0\"]\n            (\"Electric field strength\")\n        |lyra::opt(Inp.T_cycle, \"T_cycle\")\n            [\"-T\"][\"--T_cycle\"]\n            (\"length of pulse in cycles\")\n        |lyra::opt(Inp.timesteps, \"timesteps\")\n            [\"-t\"][\"--timesteps\"]\n            (\"Number of timesteps\")\n        |lyra::opt(Inp.b,\"b\")\n            [\"-b\"][\"--b\"]\n            (\"Boxsize\")\n        |lyra::opt(Inp.N_b,\"N_b\")\n            [\"-N_b\"][\"--N_b\"]\n            (\"Number of gridpoints\")\n        |lyra::opt(Inp.Lmax,\"Lmax\")\n            [\"-Lmax\"][\"--Lmax\"]\n            (\"Maximum angular momentum\")\n        |lyra::opt(Inp.Mmax,\"Mmax\")\n            [\"-Mmax\"][\"--Mmax\"]\n            (\"Maximum magnetic quantum number\")\n        |lyra::opt(Inp.Emax,\"Emax\")\n            [\"-Emax\"][\"--Emax\"]\n            (\"Maximum Energy in simulation\")\n        |lyra::opt(Inp.I0,\"I0\")\n            [\"-I0\"][\"--I0\"]\n            (\"Laser Intensity in 1e12\")\n        |lyra::opt(Inp.init_state,\"Initial state\")\n            [\"-init\"][\"--init\"]\n            (\"Initial state of system\")\n        |lyra::opt(Inp.Accelerator, \"Accelerator\")\n            [\"-acc\"][\"--acc\"]\n            (\"Use CPU or GPU as accelerator\")\n        |lyra::opt(Inp.zComp, \"z-Comp\")\n            [\"-zComp\"][\"--zComp\"]\n            (\"z comp\")\n        |lyra::opt(Inp.xComp, \"x-comp\")\n            [\"-xComp\"][\"--xComp\"]\n            (\"x Comp\")\n        |lyra::opt(Inp.xft, \"x-ft\")\n            [\"-xft\"][\"--xft\"]\n            (\"x ft\")\n        |lyra::opt(Inp.zft, \"z-ft\")\n            [\"-zft\"][\"--zft\"]\n            (\"z ft\")\n        |lyra::opt(Inp.l_quantum,\"l Quantum number\")\n            [\"-lq\"][\"--l_q\"]\n            (\"l Quantum number of initial state\")\n        |lyra::opt(Inp.m_quantum,\"n Quantum number\")\n            [\"-mq\"][\"--m_q\"]\n            (\"m Quantum number of initial state\")\n        |lyra::opt(Inp.n_quantum,\"n Quantum number\")\n            [\"-nq\"][\"--n_q\"]\n            (\"n Quantum number of initial state\");\n\n        auto result = cli.parse({ argc, argv });\n        if ( !result )\n        {\n                std::cerr << \"Error in command line: \" << result.errorMessage() << std::endl;\n                    exit(1);\n        }\n\n    //number of accelerators in the system\n    int num_devices = 0;\n    if (Inp.Accelerator == \"GPU\" ||  Inp.Accelerator == \"GPUFull\"){\n        setupGPUs(local_rank,num_devices);\n        watch(num_devices);\n    }\n\n    SpMatrix H_rank;\n    H_rank.nmbrLEGO = 1 + Inp.zComp +  Inp.xComp;\n    BuildMatrix(Inp,H_rank);\n    std::string PATH;\n    Propergator(Inp,H_rank,PATH);\n\n    if (Inp.Accelerator == \"GPU\" ||  Inp.Accelerator == \"GPUFull\"){\n        CUDAFinalize(H_rank.nmbrLEGO,\n                H_rank.LEGO_d_rowPtr,H_rank.LEGO_d_cooCols,H_rank.LEGO_d_cooVals_sorted,\n                H_rank.LEGO_d_cscRows,H_rank.LEGO_d_cscColPtr,H_rank.LEGO_d_cscVals);\n    }\n    watch(rank);\n    MPI_Finalize();\n    cout << \"MPI has been finalized\" << endl;\n    return 0;\n        \n}\n\nvoid BuildMatrix(InputParameter &Inp,SpMatrix &H_rank){\n    //recalculate variables that depend on command line input\n        //spacing between breakpoints \n    VectorXd x_break(Inp.N_b);\n    double dX = (Inp.b - Inp.a)/ (Inp.N_b-1);\n    x_break = ArrayXd::LinSpaced(Inp.N_b,Inp.a,Inp.b);\n\n    int states_chan = (int) round(Inp.b/M_PI*sqrt(2*Inp.Emax));\n\n    if (rank==0){\n        //print the Input parameters\n        watch(Inp.nnz);\n        watch(Inp.a);\n        watch(Inp.b);\n        watch(Inp.Lmax);\n        watch(Inp.Mmax);\n        watch(Inp.Emax);\n        watch(Inp.N_b);\n        watch(states_chan);\n        watch(Inp.zComp);\n        watch(Inp.xComp);\n        watch(Inp.zft);\n        watch(Inp.xft);\n\n        watch(Inp.Accelerator);\n        watch(Inp.l_quantum);\n        watch(Inp.m_quantum);\n        watch(Inp.n_quantum);\n        watch(Inp.init_state);\n        watch(Inp.om);\n        watch(Inp.I0);\n        watch(Inp.E0);\n        watch(Inp.T_puls);\n        watch(Inp.T_cycle);\n        watch(Inp.Tint);\n        watch(Inp.timesteps);\n\n    }\n\n    auto start = system_clock::now();\n      nnz_rank = Inp.nnz/p;\n    states_chan_rank=states_chan/p;\n    //distribute the remaining channels if states_cahn%p != 0\n    if(rank < states_chan%p){\n        states_chan_rank++;\n    }\n    //offset describes how many ranks have an extra channel \n    int offset = std::min(states_chan%p,rank);\n    states_chan_rank_begin=states_chan/p*rank+offset;\n    states_chan_rank_end=states_chan/p*rank+states_chan_rank+offset;\n\n    pwatch(states_chan_rank);\n    pwatch(offset);\n    pwatch(states_chan_rank_begin);\n    pwatch(states_chan_rank_end);\n\n    pwatch(\"matrix obj is created\");\n    bp(\"before memory is allocated\");\n    H_rank.initMatrix(Inp.nnz/p);\n    H_rank.nnz[0] = nnz_rank;\n    bp(\"after memory is allocated\");\n    \n    //this is the ind on every rank his is a vector that holds the ind for all \n    //different matrices linked to the different LEGO bricks\n    std::vector< int>ind(H_rank.nmbrLEGO,0);\n\n    //the matrix will be generated on different MPI ranks\n    //generating the B-spliens does not take much time therefore all ranks generate \n    //their own set. They also for now all hold their own set of psi \n\n    //Gaus Legendre integration set up\n    ArrayXd x((Inp.N_b-1)*Inp.n);\n    ArrayXd weights((Inp.N_b-1)*Inp.n);\n    bp(\"before gaus set up\");\n    gausLegendreSetup(Inp.n,Inp.N_b,x_break,x,weights);\n    //gauss legendre returns same weights and x as python script\n    //allocating a vector of Eigenvector matrices \n    \n    bp(\"after gaus set up\");\n\n    ArrayXXd B = ArrayXXd::Zero(x.size(),Inp.N_b-1+2*Inp.n);\n    ArrayXXd d_B = ArrayXXd::Zero(x.size(),Inp.N_b-1+2*Inp.n);\n    ArrayXXd diff_B = ArrayXXd::Zero(x.size(),Inp.N_b-1+2*Inp.n);\n\n    int dim_H = Inp.N_b+Inp.n-3;  \n    generateBsplines(Inp,dX,x,B,d_B,diff_B);\n    bp(\"bsplines generated\");\n    //Memory declaration\n    ArrayXXd psi_1 = ArrayXXd::Zero(x.size(),states_chan);\n    ArrayXXd d_psi_1 = ArrayXXd::Zero(x.size(),states_chan);\n    ArrayXXd diff_psi_1 = ArrayXXd::Zero(x.size(),states_chan);\n    ArrayXd E1 = ArrayXd::Zero(dim_H);\n    \n    ArrayXXd psi_2 = ArrayXXd::Zero(x.size(),states_chan);\n    ArrayXXd d_psi_2 = ArrayXXd::Zero(x.size(),states_chan);\n    ArrayXXd diff_psi_2 = ArrayXXd::Zero(x.size(),states_chan);\n    ArrayXd E2 = ArrayXd::Zero(dim_H);\n    \n    ArrayXXd psi_3 = ArrayXXd::Zero(x.size(),states_chan);\n    ArrayXXd d_psi_3 = ArrayXXd::Zero(x.size(),states_chan);\n    ArrayXXd diff_psi_3 = ArrayXXd::Zero(x.size(),states_chan);\n    ArrayXd E3 = ArrayXd::Zero(dim_H);\n\n    MatrixXd H_base = MatrixXd::Zero(dim_H,dim_H);\n    MatrixXd S = MatrixXd::Zero(dim_H,dim_H);\n    double tmp_d;\n    helperEigenStates(Inp,states_chan,dX,tmp_d,weights, x, B,diff_B,H_base,S);\n     getEigenStates(Inp,Inp.Lmin,states_chan,dX,tmp_d,weights,x,B,d_B,diff_B,psi_1,d_psi_1,diff_psi_1,H_base,S,E1);\n     bp(\"First set of psi\");\n\n    getEigenStates(Inp,Inp.Lmin+1,states_chan,dX,tmp_d,weights,x,B,d_B,diff_B,psi_2,d_psi_2,diff_psi_2,H_base,S,E2);\n\n     bp(\"second set of psi\");\n\n     ArrayXd Input_Energies = ArrayXd::Zero(5000000);\n    int ind2 =0;\n   int lm_index_L =-1; \n    for (int l=Inp.Lmin; l < Inp.Lmax+1; l++){\n        pwatch(l);\n       getEigenStates(Inp,l+2,states_chan,dX,tmp_d,weights,x,B,d_B,diff_B,psi_3,d_psi_3,diff_psi_3,H_base,S,E3);\n\n        for(int m=-std::min(Inp.Mmax,l); m < std::min(Inp.Mmax,l)+1; m++){\n            lm_index_L++;\n            int lm_index_R=-1;\n            for(int l2 = Inp.Lmin; l2 < Inp.Lmax+1; l2++){\n                for(int m2 = -std::min(Inp.Mmax,l2);m2 < std::min(Inp.Mmax,l2)+1;m2++){\n                    lm_index_R++;\n                    if (l2==l+1 && m2 ==m){\n                        //z-polarization\n                        //< l m | x | l+1 m>:\n                        if(Inp.zComp == 1){\n                            double LM_faktor=sqrt(((l+1)*(l+1)-m*m)/(double) (4*((l+1)*(l+1))-1));\n                            polarization(H_rank,states_chan, ind[Inp.zft],Inp.zft,l,lm_index_L,lm_index_R, \n                                LM_faktor,dX,weights,x,psi_1,psi_2,d_psi_2);\n                        }\n                    }\n                    if(l2== l+1 && m2 == m+1){\n                        //x-polarization\n                        //%< l m | p_x | l+1 m+1>:\n                        if(Inp.xComp == 1){\n                            double LM_faktor=-sqrt((l+m+1)*(l+m+2)/(double) (4*(2*l+1)*(2*l+3)));\n                            polarization(H_rank,states_chan, ind[Inp.xft],Inp.xft,l,lm_index_L,lm_index_R, \n                                LM_faktor,dX,weights,x,psi_1,psi_2,d_psi_2);\n                        }    \n                    }\n                    if(l2== l+1 && m2 == m-1){\n                        //x-polarization\n                        //< l m | p_x | l+1 m-1>: \n                        if(Inp.xComp == 1){\n                            double LM_faktor=sqrt((l-m+1)*(l-m+2)/(double) (4*(2*l+1)*(2*l+3)));\n                            polarization(H_rank,states_chan, ind[Inp.xft],Inp.xft,l,lm_index_L,lm_index_R, \n                                    LM_faktor,dX,weights,x,psi_1,psi_2,d_psi_2);\n                        } \n                    }\n                }\n            }\n\n            //Lego brick 4 will unperturbated states will be only calculated on rank 0 as they are\n            //not many. We also need the Input_Energies later as a txt file \n            if(rank==0){\n               //Lego brick 4 \n                for(int j= 0; j < states_chan;j++){\n                    H_rank.writeElement(ind[0],lm_index_L*states_chan+j,lm_index_L*states_chan+j,0,E1(j));\n                    Input_Energies(ind2)=std::real(E1(j));\n                    ind[0]++;\n                    ind2++;\n\n                }\n            }\n        \n        }\n        //so we do not have to calculate the psi1,psi2 again\n        //psi3 -> psi2, psi2 -> psi1\n        E1=E2;\n        psi_1=psi_2;\n        d_psi_1=d_psi_2;\n        diff_psi_1=diff_psi_2;\n\n        E2=E3;\n        psi_2=psi_3;\n        d_psi_2=d_psi_3;\n        diff_psi_2=diff_psi_3;\n        if(rank==0){\n            int nnzRank=0;\n            for(int k=0; k < H_rank.nmbrLEGO; k++){\n                watch(ind[k]);\n                nnzRank+=ind[k];\n            }\n            watch(nnzRank);\n            cout << \"Total number of elements in 1e+6: \" << (long long) p * nnzRank / 1.0e6 << endl; \n        }\n    }\n    //the number of elements every matrix on every rank holds\n    nnz_rank=ind[0];\n    for(int i = 0; i < H_rank.nmbrLEGO; i++){\n        H_rank.nnz[i]=ind[i];\n    }\n    //write to file \n    if(rank ==0){\n        dim=ind2;\n        watch(ind2);\n        std::ofstream f6 (\"Energies_Input_shago.txt\");\n        cout << \"Begin to write file\" << endl;\n                \n              if (f6.is_open()){\n               for (int i = 0; i < ind2; i++){\n                    f6 << Input_Energies(i) << \"\\n\";\n               }\n           }\n\n         else cout << \"Unable to open file\";\n\n        //End of timing \n        auto stop = system_clock::now();\n        auto duration = duration_cast<milliseconds>(stop - start);\n        cout << \"Time taken for generating the matrix: \" << (double) duration.count()/1000 << \"seconds\" << endl;\n    }\n\n    //Broadcast the dimension of the vector;\n    MPI_Bcast(&dim,1,MPI_INT,0,MPI_COMM_WORLD);\n\n    cout << \"rank\" << \" \" << rank << \" holds elemets: \" << nnz_rank << endl;\n    H_rank.dim=dim;\n    pwatch(dim);\n    pwatch(nnz_rank);\n \n    //transform the matrix to CSR after the read in is done\n    //we use less memory and obtain a better performance\n    auto startSort = system_clock::now();\n    if(Inp.Accelerator == \"GPU\" || Inp.Accelerator == \"GPUFull\"){\n        bp(\"Before create CSR-GPU\");\n        H_rank.CSRonDevice();\n        bp(\"After create CSR-GPU\");\n    }\n    else if(Inp.Accelerator == \"MKL\"){\n        bp(\"Before create CSR-MKL\");\n        H_rank.CSRMKL();\n        bp(\"After create CSR-MKL\");\n    }\n    else if(Inp.Accelerator != \"CPU\"){\n        cout << \"Inp.Accelerator is not a vaild accelerator [CPU,GPU,MKL]\" << endl;\n        exit(EXIT_FAILURE);\n\n    }\n    auto stopSort = system_clock::now();\n    auto durationSort = duration_cast<milliseconds>(stopSort - startSort);\n    cout << \"Time taken for sorting the matrix: \" << (double) durationSort.count()/1000 << \"seconds\" << endl;\n    \n}//End of matrix build up \n\nvoid Propergator(InputParameter &Inp,SpMatrix &H_rank,std::string PATH){\n    Inp.E0 = 5.338*sqrt(Inp.I0*1e12)*1e-9;\n    Inp.T_puls = Inp.T_cycle * 2 * M_PI / Inp.om;\n    \n    int states_chan = (int) round(Inp.b/M_PI*sqrt(2*Inp.Emax));\n    //the initial state mind that C++ index starts at 0\n    //this depends on Lmax,Mmax & qunatum number n,l,m\n    int l_states= std::min(Inp.l_quantum,Inp.Mmax);\n    int m_states= std::min(Inp.m_quantum,Inp.Mmax);\n    Inp.init_state = states_chan * (Inp.l_quantum * (l_states+1) + m_states)\n         +  Inp.n_quantum-Inp.l_quantum-1;\n\n   if(rank ==0){\n        //Input param propagator\n        watch(Inp.Accelerator);\n        watch(Inp.l_quantum);\n        watch(Inp.m_quantum);\n        watch(Inp.n_quantum);\n        watch(Inp.init_state);\n        watch(Inp.om);\n        watch(Inp.I0);\n        watch(Inp.E0);\n        watch(Inp.T_puls);\n        watch(Inp.T_cycle);\n        watch(Inp.Tint);\n        watch(Inp.timesteps);\n    }\n\n    //initalize the state vector y \n    VectorXcd y = VectorXcd::Zero(dim);\n    //For the TDSE we start with the electron in the lowest possible state s1\n    y(Inp.init_state) = 1.0;\n    VectorXcd y_init(dim);\n    VectorXcd p_init(Inp.timesteps);\n    VectorXcd p_excited_1(Inp.timesteps);\n    VectorXcd p_excited_2(Inp.timesteps);\n    y_init << y;\n    //Time propagator\n    double dt = (Inp.T_puls-Inp.Tint)/Inp.timesteps;\n\n    //Only needed on rank 0 but they are small\n    MatrixXcd Q = MatrixXcd::Zero(dim,Inp.dim_kryl);  //Eigenvectors\n    MatrixXcd h = MatrixXcd::Zero(Inp.dim_kryl,Inp.dim_kryl); //Eigenvalues\n    VectorXcd d = VectorXcd::Zero(Inp.dim_kryl);\n    VectorXd od = VectorXd::Zero(Inp.dim_kryl-1);\n\n    if(rank==0)\n        cout << \"decleration of variables finished\" << endl;\n\n    //Start timing the propagation\n    auto start2 = system_clock::now();\n\n    if(rank==0)\n        cout << \"start timepropagation\" << endl; \n\n    MPI_Barrier(MPI_COMM_WORLD);\n    if (Inp.Accelerator == \"GPUFull\"){\n        cuDoubleComplex *dQ;\n        cuDoubleComplex *dd;\n        cuDoubleComplex *dy;\n        double *od;\n         cusparseHandle_t handle_sparse;\n         cublasHandle_t handle_blas;\n        cusolverDnHandle_t handle_solver;\n        allocateMemoryPropagator(Inp,H_rank.dim,dQ,dd,od,dy,y.data());\n        for(int i = 1; i < Inp.timesteps+1;i++){\n            //normalize y \n            \n            double normStart;\n       \n            double t = dt *i;\n            //get ft \n            VectorXcd ft =  VectorXcd(116);\n            ft_calc(Inp,t, ft.data());\n            \n        \n            lanczosCUDA(\n                        H_rank.nnz,H_rank.dim,Inp.dim_kryl, H_rank.nmbrLEGO,\n                        normStart,\n                            H_rank.LEGO_d_cooCols,\n                            H_rank.LEGO_d_rowPtr,\n                            H_rank.LEGO_d_cooVals_sorted,\n                            H_rank.LEGO_d_cscRows,\n                            H_rank.LEGO_d_cscColPtr,\n                            H_rank.LEGO_d_cscVals,\n                            dy,ft.data(),\n                            od,dQ,dd);\n\n            //physical propergator \n            if (rank ==0){\n                physPropagator(Inp,Inp.dim_kryl,dim,normStart,dt,dQ,dd,od,dy,y.data());\n\n                if(i%20 == 0){\n                    cout << \"Timesteps: \" << i << endl;\n                    double norm = y.norm();\n                watch(y(Inp.init_state));\n                watch(y(Inp.init_state+1));\n                watch(y(Inp.init_state+2));\n                cout << \"norm: \" << norm << endl;\n                cout << \"Pinit: \" <<  abs(y(Inp.init_state))*abs(y(Inp.init_state)) << endl;\n\n                }\n\n            }\n        }   \n\n        freeMemoryPropagator(Inp,H_rank.dim,dQ,dd,od,dy,y.data());\n                watch(y(Inp.init_state));\n                watch(y(Inp.init_state+1));\n                watch(y(Inp.init_state+2));\n                cout << \"Pinit: \" <<  abs(y(Inp.init_state))*abs(y(Inp.init_state)) << endl;\n\n\n    }\n    else{\n        for(int i = 1; i < Inp.timesteps+1; i++){ \n            double norm;\n            if (rank==0){ \n                norm = y.norm();\n                y = y/norm;\n            }\n            \n            //get the ft values \n            VectorXcd ft =  VectorXcd(116);\n            double t = dt * i; \n            ft_calc(Inp,t, ft.data());\n\n            //Lanzcos with GPU for SpMV\n            if(Inp.Accelerator == \"CPU\" || Inp.Accelerator == \"MKL\"){\n                lanczos(Inp, H_rank,  dim, y , Q, h, ft);\n            }\n            cout << \"h\" << endl;\n            cout << h << endl;\n            //To get the matrix exponential first diaganolize the matrix the exponate its\n            //elements.\n            if(rank == 0){\n                 startortho = high_resolution_clock::now();\n\n                SelfAdjointEigenSolver<MatrixXcd> ces;\n                ces.compute(h);\n                MatrixXcd D = (-1i * dt * ces.eigenvalues()).array().exp().matrix().asDiagonal();\n                MatrixXcd P = ces.eigenvectors();\n                y = norm * Q * (P * D * P.inverse()).col(0);\n\n                stoportho = high_resolution_clock::now();\n                durationortho += duration_cast<milliseconds>(stoportho - startortho);\n\n                //write data \n                p_init(i-1)=abs(y(Inp.init_state))*abs(y(Inp.init_state));\n                p_excited_1(i-1)=abs(y(Inp.init_state+1))*abs(y(Inp.init_state+1));\n                p_excited_2(i-1)=abs(y(Inp.init_state+2))*abs(y(Inp.init_state+2));\n               if(i%20 == 0){\n                    cout << \"Timesteps: \" << i << endl;\n                    norm = y.norm();\n                    watch(y(Inp.init_state));\n                    watch(y(Inp.init_state+1));\n                    watch(y(Inp.init_state+2));\n                    cout << \"norm: \" << norm << endl;\n                    cout << \"Pinit: \" <<  abs(y(Inp.init_state))*abs(y(Inp.init_state)) << endl;\n\n                }\n            }\n        }        \n    }\n    watch(rank);\n    //End of timing \n    auto stop2 = system_clock::now();\n    auto duration2 = duration_cast<milliseconds>(stop2 - start2);\n    if (rank==0){\n        cout << \"Time taken by propagating the matrix: \" << (double) duration2.count()/1000 << \"seconds\" << endl;\n     \n        cout << \"Time taken by the actual propergator \" << (double) durationortho.count()/1000\n            <<\"seconds\" << endl;\n\n       //write the output\n        std::ofstream f1 (PATH + \"fort.88\");\n        f1.precision(15);\n        if (f1.is_open()){\n            for (int i = 0; i < dim; i++){\n                f1 << abs(y(i)) * abs(y(i)) << \"\\n\";\n            }\n        }\n        else cout << \"Unable to open file\";\n        cout << \"fort.88 is written\" << endl; \n        std::ofstream f2 (PATH +\"fort.89\");\n        if (f2.is_open()){\n            for (int i = 0; i < dim; i++){\n                f2 << i << \" \" <<  y(i).real() << \" \" << y(i).imag() << \"\\n\";\n            }\n        }\n        else cout << \"Unable to open file\";\n        cout << \"fort.89 is written\" << endl; \n        //write the output\n        std::ofstream f3 (PATH + \"pinit.dat\");\n        f3.precision(15);\n        if (f3.is_open()){\n            for (int i = 0; i < Inp.timesteps; i++){\n                double time = (i+1) * Inp.T_puls/Inp.timesteps;\n                f3 << time <<\" \" << p_init(i).real() << \"\\n\";\n            }\n        }\n        else cout << \"Unable to open file\";\n\n        std::ofstream f4 (PATH +\"pexcited_1.dat\");\n        f4.precision(15);\n        if (f4.is_open()){\n            for (int i = 0; i < Inp.timesteps; i++){\n                double time = (i+1) * Inp.T_puls/Inp.timesteps;\n                f4 << time <<\" \" << p_excited_1(i).real() << \"\\n\";\n            }\n        }\n        else cout << \"Unable to open file\";\n\n        std::ofstream f5 (PATH +\"pexcited_2.dat\");\n        f5.precision(15);\n        if (f5.is_open()){\n            for (int i = 0; i < Inp.timesteps; i++){\n                double time = (i+1) * Inp.T_puls/Inp.timesteps;\n                f5 << time <<\" \" << p_excited_2(i).real() << \"\\n\";\n            }\n        }\n        else cout << \"Unable to open file\";\n        cout << \"pinit,pexcited are written\" << endl;\n        \n    }\n}\n\nvoid lanczos(InputParameter Inp,SpMatrix &H_rank, int m,VectorXcd &y ,MatrixXcd &Q, MatrixXcd &h,  \n        VectorXcd &FT){\n    /* Input\n    H_rank: mxm matrix \n    b: initial vector\n    Inp.drim_kryl: dimension of Krylov subspace L in morten code\n    m: dimesion of matrix H_rank\n    Output:\n    Q: orthogonal Krylov space \n    h: tridiagonal matrix \n    */\n    VectorXcd d = VectorXcd::Zero(Inp.dim_kryl);\n    VectorXcd od = VectorXcd::Zero(Inp.dim_kryl-1); //L-1 from morten \n    VectorXcd dydx_rank = VectorXcd::Zero(dim);\n    //will only be used on rank0\n    VectorXcd dydx = VectorXcd::Zero(dim);\n   \n    Q.setZero();\n    Q.col(0) = y;\n    h.setZero();\n\n    for (int i = 0; i < Inp.dim_kryl; i++){\n        dydx_rank.setZero(dim);\n        //broadcast changeing vector y to all ranks \n        MPI_Bcast(y.data(),dim*2,MPI_DOUBLE,0,MPI_COMM_WORLD);\n\n        //Matrix vector product this is the only loop that get executed in parallel \n        //iterate over all LEGO bricks\n\n        //the cpu COO version \n        if(Inp.Accelerator == \"CPU\"){\n            for(int j = 0; j < H_rank.nmbrLEGO; j++){\n                H_rank.matrixVectorUpper(j,y,dydx_rank,FT);\n            }\n        }\n\n        if(Inp.Accelerator == \"MKL\"){\n        // the cpu MKL CSR version\n            bp(\"Before Matrix Vector\");\n            H_rank.matrixVectorMKL(y,dydx_rank,FT);\n            bp(\"After matrix Vector\");\n        }\n      //sum the local dydx_rank into dydx on rank 0\n        MPI_Reduce(dydx_rank.data(),dydx.data(),dim*2,MPI_DOUBLE,MPI_SUM, 0,MPI_COMM_WORLD);\n        \n        if(rank==0){\n            d(i) = y.adjoint() * dydx; \n               //Full reorthogonalization (x2):\n            dydx = dydx - Q.block(0,0,dim,i+1) * ( Q.block(0,0,dim,i+1).adjoint() * dydx);\n            dydx = dydx - Q.block(0,0,dim,i+1) * ( Q.block(0,0,dim,i+1).adjoint() * dydx);\n            if (i < Inp.dim_kryl-1){\n                od(i) = dydx.norm();\n                if (abs(od(i)) == 0){\n                    cout << \"devision by 0 during renormalizing\" <<endl;\n                    break;\n                }\n                y = dydx/od(i);\n                Q.col(i+1) = y;\n                //adaptivly control the dimension of the Krylov space. At most we do dim_kryl\n                //iterations if we converge earlier we terminate \n                if((Q.col(i+1)-Q.col(i)).norm()  < Inp.eps){\n                    for(int j = i+1; j < Inp.dim_kryl-1 ; j++){\n                        //fill the remaining vectors \n                        Q.col(j+1) = y;\n                        d(j) = d(i);\n                        od(j) = od(i);\n\n                    }\n                    d(Inp.dim_kryl-1)=d(i);\n                    cout << \"Krylov space converged after: \" << i << \" iterations\\n\"; \n                    break;\n                    \n                }\n            }\n        }\n           \n    }\n    //set the h Matrix mortens TT matrix\n    for (int i = 1; i < Inp.dim_kryl; i++){\n        h(i,i-1) = od(i-1);\n        h(i-1,i) = od(i-1);\n    }\n    for (int i = 0; i < Inp.dim_kryl; i++){\n        h(i,i) = d(i);\n    }\n   return;\n}\n\nvoid polarization(SpMatrix &M,int states_chan, int &ind, int index,int l,int lm_index_L,int lm_index_R,\n        double LM_faktor,double dX,ArrayXd &weights, ArrayXd &x, ArrayXXd &psi_1,ArrayXXd\n        &psi_2,ArrayXXd &d_psi_2){\n    //Lego brick 1 + 2 \n#pragma omp parallel for collapse(2)  \n    for(int j =  states_chan_rank_begin; j < states_chan_rank_end; j++){\n        for(int i = 0; i < states_chan; i++){\n                M.writeElement(ind+j*states_chan+i,\n                        lm_index_L*states_chan+j,\n                        lm_index_R*states_chan+i,\n                        index,\n                        dX/2*(weights*psi_1.col(j)*psi_2.col(i)/x).sum()*LM_faktor*(l+1)\n                        +dX/2*(weights*psi_1.col(j)*d_psi_2.col(i)).sum()*LM_faktor);\n          }\n\n    }\n   \n    //number of elements written on one rank over all threads\n    ind = ind + (states_chan_rank_end-states_chan_rank_begin) * states_chan;\n}\n\nvoid helperEigenStates(InputParameter Inp, int states_chan,double dX,double &tmp_d,\n        ArrayXd &weights, ArrayXd &x,ArrayXXd &B,ArrayXXd &diff_B,MatrixXd &H_base, \n        MatrixXd &S){\n    //This function should speed up the calculation\n    //S and large aprts of H are always the same, by storing them and passing them to\n    //getEigenStates redundant computation can be avoided \n    //S and the kinetic Energy are the same for all l, \n\n    int dim_H = Inp.N_b+Inp.n-3;  \n    for (int i = 0; i < dim_H ; i++){ \n        for (int j = 0; j < dim_H; j++){\n            H_base(i,j) = - 0.5 * dX * 0.5 * (weights * B.col(i+1)*diff_B.col(j+1)).sum(); \n            ArrayXd tmp = dX * 0.5 * (weights * B.col(i+1)*B.col(j+1));\n            H_base(i,j) += (tmp * -1/x).sum(); \n            S(i,j) = (tmp).sum();\n        }\n    }\n\n}\n\n\nvoid getEigenStates(InputParameter Inp, int l,int states_chan,double dX,double &tmp_d,ArrayXd &weights,\n        ArrayXd &x,ArrayXXd &B, ArrayXXd &d_B,ArrayXXd &diff_B,ArrayXXd &psi,ArrayXXd &d_psi\n        ,ArrayXXd &diff_psi , MatrixXd &H_base, MatrixXd &S, ArrayXd &Energy ){\n    //The H and S matrix \n    int dim_H = Inp.N_b+Inp.n-3;  //this equals to s_H\n    MatrixXd H = MatrixXd::Zero(dim_H,dim_H);\n    ArrayXd tmp_l = (l*(1+l)/(2*x*x)); \n\n//only works on rect loops\n#pragma omp parallel for collapse(2) \n    for (int i = 0; i < dim_H ; i++){ \n        for (int j = 0; j < dim_H; j++){\n             //Kinetic Engergy \n            H(i,j) = H_base(i,j); \n            //potential Energy V\n            ArrayXd tmp =  dX * 0.5 * weights * B.col(i+1)*B.col(j+1);\n            H(i,j) += (tmp * tmp_l).sum();\n       }\n    }\n    \n    //Start timing the solver\n    auto start2 = system_clock::now();\n    //The Gen Eigenvalue solver on CPU\n    MatrixXd Eigenvectors =  MatrixXd::Zero(dim_H,dim_H);\n    if(Inp.Accelerator == \"CPU\" || Inp.Accelerator== \"MKL\")\n    {\n        GeneralizedSelfAdjointEigenSolver<MatrixXd> ges(H,S);\n        Eigenvectors = ges.eigenvectors();\n        Energy = ges.eigenvalues();\n    }\n   //Gen Eigenvalue solver on GPU\n    //H,S are in coloum major, 0 index format\n    //Cusolver assumes col-major no conversion needed\n    //lda,ldb,m are all the same as dim W,V = Eigenvalues,Eigenvectors\n    if(Inp.Accelerator == \"GPU\" || Inp.Accelerator ==\"GPUFull\")\n    {\n        //VectorXd Eigenvalues =  VectorXd::Zero(dim_H);\n        genEigenSolverCUDA(dim_H,H.data(),S.data(),Energy.data(),Eigenvectors.data());\n    }\n   \n    auto stop2 = system_clock::now();\n    auto duration2 = duration_cast<milliseconds>(stop2 - start2);\n    if (rank==0){\n        cout << \"Time taken by the solver in l: \"<< l << \" : \"  << (double) duration2.count()/1000\n            << \"seconds\" << endl;}\n    \n    //set the psi to 0 \n    psi.setZero();\n    d_psi.setZero();\n    diff_psi.setZero();\n    \n    //watch(Energy);\n    //watch(Eigenvectors);\n#pragma omp parallel for collapse(2)\n    for(int i = 0; i < states_chan; i++){\n        for(int j=0; j < dim_H; j++){\n            psi.col(i) = psi.col(i) + Eigenvectors(j,i) * B.col(j+1);\n            d_psi.col(i) = d_psi.col(i) + Eigenvectors(j,i) * d_B.col(j+1);\n            diff_psi.col(i) = diff_psi.col(i) + Eigenvectors(j,i) * diff_B.col(j+1);\n       }\n } \n    }\n\n", "meta": {"hexsha": "d68f90565c411a6bbf6d8d1da5a7d85f29e5e651", "size": 38501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulationMultiGPU.cpp", "max_stars_repo_name": "krygol/GPU-Accelerated-Propagator", "max_stars_repo_head_hexsha": "4d0af7e1739e39813bab6dac760b8d1589116c20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulationMultiGPU.cpp", "max_issues_repo_name": "krygol/GPU-Accelerated-Propagator", "max_issues_repo_head_hexsha": "4d0af7e1739e39813bab6dac760b8d1589116c20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulationMultiGPU.cpp", "max_forks_repo_name": "krygol/GPU-Accelerated-Propagator", "max_forks_repo_head_hexsha": "4d0af7e1739e39813bab6dac760b8d1589116c20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0646630237, "max_line_length": 116, "alphanum_fraction": 0.5260642581, "num_tokens": 10743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4444175683938527}}
{"text": "// -*- mode: c++; fill-column: 80; indent-tabs-mode: nil; -*-\n\n#ifndef ARMA_LAPACK_EXTRA_HPP\n#define ARMA_LAPACK_EXTRA_HPP\n\n#include <armadillo>\n\n#if !defined(ARMA_BLAS_CAPITALS)\n\n#define arma_sbdsqr sbdsqr\n#define arma_dbdsqr dbdsqr\n\n/* Least-square problem */\n#define arma_sgglse sgglse\n#define arma_dgglse dgglse\n#define arma_cgglse cgglse\n#define arma_zgglse zgglse\n\n/* QR factorization with column pivoting */\n#define arma_sgeqp3 sgeqp3\n#define arma_dgeqp3 dgeqp3\n#define arma_cgeqp3 cgeqp3\n#define arma_zgeqp3 zgeqp3\n\n/* Eigenvalue decomposition of upper Hessenberg matrix */\n#define arma_shseqr shseqr\n#define arma_dhseqr dhseqr\n#define arma_chseqr chseqr\n#define arma_zhseqr zhseqr\n\n/* Jacobi SVD */\n#define arma_sgesvj sgesvj\n#define arma_dgesvj dgesvj\n#define arma_cgesvj cgesvj\n#define arma_zgesvj zgesvj\n\n/* Another Jacobi SVD */\n#define arma_sgejsv sgejsv\n#define arma_dgejsv dgejsv\n#define arma_cgejsv cgejsv\n#define arma_zgejsv zgejsv\n\n#else\n\n#define arma_sbdsqr SBDSQR\n#define arma_dbdsqr DBDSQR\n\n/* Least-square problem */\n#define arma_sgglse SGGLSE\n#define arma_dgglse DGGLSE\n#define arma_cgglse CGGLSE\n#define arma_zgglse ZGGLSE\n\n/* QR factorization with column pivoting */\n#define arma_sgeqp3 SGEQP3\n#define arma_dgeqp3 DGEQP3\n#define arma_cgeqp3 CGEQP3\n#define arma_zgeqp3 ZGEQP3\n\n/* Eigenvalue decomposition of upper Hessenberg matrix */\n#define arma_shseqr SHSEQR\n#define arma_dhseqr DHSEQR\n#define arma_chseqr CHSEQR\n#define arma_zhseqr ZHSEQR\n\n/* Jacobi SVD */\n#define arma_sgesvj SGESVJ\n#define arma_dgesvj DGESVJ\n#define arma_cgesvj CGESVJ\n#define arma_zgesvj ZGESVJ\n\n/* Another Jacobi SVD */\n#define arma_sgejsv SGEJSV\n#define arma_dgejsv DGEJSV\n#define arma_cgejsv CGEJSV\n#define arma_zgejsv ZGEJSV\n\n#endif /* ARMA_BLAS_CAPITALS */\n\nnamespace arma\n{\n\nextern \"C\" {\n// SVD of real bidiagonal matrix\nvoid arma_fortran_noprefix(arma_sbdsqr)(char* uplo, blas_int* n, blas_int* ncvt,\n                                        blas_int* nru, blas_int* ncc, float* d,\n                                        float* e, float* vt, blas_int* ldvt,\n                                        float* u, blas_int* ldu, float* c,\n                                        blas_int* ldc, float* work,\n                                        blas_int* info);\n\nvoid arma_fortran_noprefix(arma_dbdsqr)(char* uplo, blas_int* n, blas_int* ncvt,\n                                        blas_int* nru, blas_int* ncc, double* d,\n                                        double* e, double* vt, blas_int* ldvt,\n                                        double* u, blas_int* ldu, double* c,\n                                        blas_int* ldc, double* work,\n                                        blas_int* info);\n\n// Solve generalized eigenvalue problem\nvoid arma_fortran_noprefix(arma_sggev)(char* jobl, char* jobr, blas_int* n,\n                                       float* a, blas_int* lda, float* b,\n                                       blas_int* ldb, float* alphar,\n                                       float* alphai, float* beta, float* vl,\n                                       blas_int* ldvl, float* vr,\n                                       blas_int* ldvr, float* work,\n                                       blas_int* lwork, blas_int* info);\n\nvoid arma_fortran_noprefix(arma_dggev)(char* jobl, char* jobr, blas_int* n,\n                                       double* a, blas_int* lda, double* b,\n                                       blas_int* ldb, double* alphar,\n                                       double* alphai, double* beta, double* vl,\n                                       blas_int* ldvl, double* vr,\n                                       blas_int* ldvr, double* work,\n                                       blas_int* lwork, blas_int* info);\n\nvoid arma_fortran_noprefix(arma_cggev)(\n    char* jobl, char* jobr, blas_int* n, void* a, blas_int* lda, void* b,\n    blas_int* ldb, void* alpha, void* beta, void* vl, blas_int* ldvl, void* vr,\n    blas_int* ldvr, void* work, blas_int* lwork, float* rwork, blas_int* info);\n\nvoid arma_fortran_noprefix(arma_zggev)(\n    char* jobl, char* jobr, blas_int* n, void* a, blas_int* lda, void* b,\n    blas_int* ldb, void* alpha, void* beta, void* vl, blas_int* ldvl, void* vr,\n    blas_int* ldvr, void* work, blas_int* lwork, double* rwork, blas_int* info);\n\n// linear equality-constrained least squares problem (LSE)\nvoid arma_fortran_noprefix(arma_sgglse)(blas_int* m, blas_int* n, blas_int* p,\n                                        float* a, blas_int* lda, float* b,\n                                        blas_int* ldb, float* c, float* d,\n                                        float* x, float* work, blas_int* lwork,\n                                        blas_int* info);\n\nvoid arma_fortran_noprefix(arma_dgglse)(blas_int* m, blas_int* n, blas_int* p,\n                                        double* a, blas_int* lda, double* b,\n                                        blas_int* ldb, double* c, double* d,\n                                        double* x, double* work,\n                                        blas_int* lwork, blas_int* info);\n\nvoid arma_fortran_noprefix(arma_cgglse)(blas_int* m, blas_int* n, blas_int* p,\n                                        void* a, blas_int* lda, void* b,\n                                        blas_int* ldb, void* c, void* d,\n                                        void* x, void* work, blas_int* lwork,\n                                        blas_int* info);\n\nvoid arma_fortran_noprefix(arma_zgglse)(blas_int* m, blas_int* n, blas_int* p,\n                                        void* a, blas_int* lda, void* b,\n                                        blas_int* ldb, void* c, void* d,\n                                        void* x, void* work, blas_int* lwork,\n                                        blas_int* info);\n// QR factorization with column pivoting\nvoid arma_fortran_noprefix(arma_sgeqp3)(blas_int* m, blas_int* n, float* a,\n                                        blas_int* lda, blas_int* jpiv,\n                                        float* tau, float* work,\n                                        blas_int* lwork, blas_int* info);\n\nvoid arma_fortran_noprefix(arma_dgeqp3)(blas_int* m, blas_int* n, double* a,\n                                        blas_int* lda, blas_int* jpiv,\n                                        double* tau, double* work,\n                                        blas_int* lwork, blas_int* info);\n\nvoid arma_fortran_noprefix(arma_cgeqp3)(blas_int* m, blas_int* n, void* a,\n                                        blas_int* lda, blas_int* jpiv,\n                                        void* tau, void* work, blas_int* lwork,\n                                        float* rwork, blas_int* info);\nvoid arma_fortran_noprefix(arma_zgeqp3)(blas_int* m, blas_int* n, void* a,\n                                        blas_int* lda, blas_int* jpiv,\n                                        void* tau, void* work, blas_int* lwork,\n                                        double* rwork, blas_int* info);\n\n// xHSEQR --- Eigendecomposition of upper Hessenberg matrix by mutishift QR\nvoid arma_fortran_noprefix(arma_shseqr)(char* job, char* compz, blas_int* n,\n                                        blas_int* ilo, blas_int* ihi, float* h,\n                                        blas_int* ldh, float* wr, float* wi,\n                                        float* z, blas_int* ldz, float* work,\n                                        blas_int* lwork, blas_int* info);\n\nvoid arma_fortran_noprefix(arma_dhseqr)(char* job, char* compz, blas_int* n,\n                                        blas_int* ilo, blas_int* ihi, double* h,\n                                        blas_int* ldh, double* wr, double* wi,\n                                        double* z, blas_int* ldz, double* work,\n                                        blas_int* lwork, blas_int* info);\n\nvoid arma_fortran_noprefix(arma_chseqr)(char* job, char* compz, blas_int* n,\n                                        blas_int* ilo, blas_int* ihi, void* h,\n                                        blas_int* ldh, void* w, void* z,\n                                        blas_int* ldz, void* work,\n                                        blas_int* lwork, blas_int* info);\n\nvoid arma_fortran_noprefix(arma_zhseqr)(char* job, char* compz, blas_int* n,\n                                        blas_int* ilo, blas_int* ihi, void* h,\n                                        blas_int* ldh, void* w, void* z,\n                                        blas_int* ldz, void* work,\n                                        blas_int* lwork, blas_int* info);\n\n// xGESVJ --- Jacobi SVD\nvoid arma_fortran_noprefix(arma_sgesvj)(char* joba, char* jobu, char* jobv,\n                                        blas_int* m, blas_int* n, float* a,\n                                        blas_int* lda, float* sva, blas_int* mv,\n                                        float* v, blas_int* ldv, float* work,\n                                        blas_int* lwork, blas_int* info);\nvoid arma_fortran_noprefix(arma_dgesvj)(char* joba, char* jobu, char* jobv,\n                                        blas_int* m, blas_int* n, double* a,\n                                        blas_int* lda, double* sva,\n                                        blas_int* mv, double* v, blas_int* ldv,\n                                        double* work, blas_int* lwork,\n                                        blas_int* info);\nvoid arma_fortran_noprefix(arma_cgesvj)(char* joba, char* jobu, char* jobv,\n                                        blas_int* m, blas_int* n, void* a,\n                                        blas_int* lda, float* sva, blas_int* mv,\n                                        void* v, blas_int* ldv, void* cwork,\n                                        blas_int* lwork, float* rwork,\n                                        blas_int* lrwork, blas_int* info);\nvoid arma_fortran_noprefix(arma_zgesvj)(char* joba, char* jobu, char* jobv,\n                                        blas_int* m, blas_int* n, void* a,\n                                        blas_int* lda, double* sva,\n                                        blas_int* mv, void* v, blas_int* ldv,\n                                        void* cwork, blas_int* lwork,\n                                        double* rwork, blas_int* lrwork,\n                                        blas_int* info);\n\n// xGEJSV --- Jacobi SVD\nvoid arma_fortran_noprefix(arma_sgejsv)(char* joba, char* jobu, char* jobv,\n                                        char* jobr, char* jobt, char* jobp,\n                                        blas_int* m, blas_int* n, float* a,\n                                        blas_int* lda, float* sva, float* u,\n                                        blas_int* ldu, float* v, blas_int* ldv,\n                                        float* work, blas_int* lwork,\n                                        blas_int* iwork, blas_int* info);\n\nvoid arma_fortran_noprefix(arma_dgejsv)(char* joba, char* jobu, char* jobv,\n                                        char* jobr, char* jobt, char* jobp,\n                                        blas_int* m, blas_int* n, double* a,\n                                        blas_int* lda, double* sva, double* u,\n                                        blas_int* ldu, double* v, blas_int* ldv,\n                                        double* work, blas_int* lwork,\n                                        blas_int* iwork, blas_int* info);\n\nvoid arma_fortran_noprefix(arma_cgejsv)(\n    char* joba, char* jobu, char* jobv, char* jobr, char* jobt, char* jobp,\n    blas_int* m, blas_int* n, void* a, blas_int* lda, float* sva, void* u,\n    blas_int* ldu, void* v, blas_int* ldv, void* cwork, blas_int* lwork,\n    float* rwork, blas_int* lrwork, blas_int* iwork, blas_int* info);\n\nvoid arma_fortran_noprefix(arma_zgejsv)(\n    char* joba, char* jobu, char* jobv, char* jobr, char* jobt, char* jobp,\n    blas_int* m, blas_int* n, void* a, blas_int* lda, double* sva, void* u,\n    blas_int* ldu, void* v, blas_int* ldv, void* cwork, blas_int* lwork,\n    double* rwork, blas_int* lrwork, blas_int* iwork, blas_int* info);\n}\n\nnamespace lapack\n{\n\n// xBDSQR\ninline void bdsqr(char* uplo, blas_int* n, blas_int* ncvt, blas_int* nru,\n                  blas_int* ncc, float* d, float* e, float* vt, blas_int* ldvt,\n                  float* u, blas_int* ldu, float* c, blas_int* ldc, float* work,\n                  blas_int* info)\n{\n    arma_fortran_noprefix(arma_sbdsqr)(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt,\n                                       u, ldu, c, ldc, work, info);\n}\n\ninline void bdsqr(char* uplo, blas_int* n, blas_int* ncvt, blas_int* nru,\n                  blas_int* ncc, double* d, double* e, double* vt,\n                  blas_int* ldvt, double* u, blas_int* ldu, double* c,\n                  blas_int* ldc, double* work, blas_int* info)\n{\n    arma_fortran_noprefix(arma_dbdsqr)(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt,\n                                       u, ldu, c, ldc, work, info);\n}\n\n// xGGLSE\ninline void gglse(blas_int* m, blas_int* n, blas_int* p, float* a,\n                  blas_int* lda, float* b, blas_int* ldb, float* c, float* d,\n                  float* x, float* work, blas_int* lwork, blas_int* info)\n{\n    arma_fortran_noprefix(arma_sgglse)(m, n, p, a, lda, b, ldb, c, d, x, work,\n                                       lwork, info);\n}\n\ninline void gglse(blas_int* m, blas_int* n, blas_int* p, double* a,\n                  blas_int* lda, double* b, blas_int* ldb, double* c, double* d,\n                  double* x, double* work, blas_int* lwork, blas_int* info)\n{\n    arma_fortran_noprefix(arma_dgglse)(m, n, p, a, lda, b, ldb, c, d, x, work,\n                                       lwork, info);\n}\n\ninline void gglse(blas_int* m, blas_int* n, blas_int* p, std::complex<float>* a,\n                  blas_int* lda, std::complex<float>* b, blas_int* ldb,\n                  std::complex<float>* c, std::complex<float>* d,\n                  std::complex<float>* x, std::complex<float>* work,\n                  blas_int* lwork, blas_int* info)\n{\n    arma_fortran_noprefix(arma_cgglse)(m, n, p, a, lda, b, ldb, c, d, x, work,\n                                       lwork, info);\n}\n\ninline void gglse(blas_int* m, blas_int* n, blas_int* p,\n                  std::complex<double>* a, blas_int* lda,\n                  std::complex<double>* b, blas_int* ldb,\n                  std::complex<double>* c, std::complex<double>* d,\n                  std::complex<double>* x, std::complex<double>* work,\n                  blas_int* lwork, blas_int* info)\n{\n    arma_fortran_noprefix(arma_zgglse)(m, n, p, a, lda, b, ldb, c, d, x, work,\n                                       lwork, info);\n}\n\n// xGEQP3\ninline void geqp3(blas_int* m, blas_int* n, float* a, blas_int* lda,\n                  blas_int* jpiv, float* tau, float* work, blas_int* lwork,\n                  blas_int* info)\n{\n    arma_fortran_noprefix(sgeqp3)(m, n, a, lda, jpiv, tau, work, lwork, info);\n}\n\ninline void geqp3(blas_int* m, blas_int* n, double* a, blas_int* lda,\n                  blas_int* jpiv, double* tau, double* work, blas_int* lwork,\n                  blas_int* info)\n{\n    arma_fortran_noprefix(dgeqp3)(m, n, a, lda, jpiv, tau, work, lwork, info);\n}\n\ninline void geqp3(blas_int* m, blas_int* n, std::complex<float>* a,\n                  blas_int* lda, blas_int* jpiv, std::complex<float>* tau,\n                  std::complex<float>* work, blas_int* lwork, float* rwork,\n                  blas_int* info)\n{\n    arma_fortran_noprefix(cgeqp3)(m, n, a, lda, jpiv, tau, work, lwork, rwork,\n                                  info);\n}\n\ninline void geqp3(blas_int* m, blas_int* n, std::complex<double>* a,\n                  blas_int* lda, blas_int* jpiv, std::complex<double>* tau,\n                  std::complex<double>* work, blas_int* lwork, double* rwork,\n                  blas_int* info)\n{\n    arma_fortran_noprefix(zgeqp3)(m, n, a, lda, jpiv, tau, work, lwork, rwork,\n                                  info);\n}\n\n// xHSEQR\ninline void hseqr(char* job, char* compz, blas_int* n, blas_int* ilo,\n                  blas_int* ihi, float* h, blas_int* ldh, float* wr, float* wi,\n                  float* z, blas_int* ldz, float* work, blas_int* lwork,\n                  blas_int* info)\n{\n    arma_fortran_noprefix(arma_shseqr)(job, compz, n, ilo, ihi, h, ldh, wr, wi,\n                                       z, ldz, work, lwork, info);\n}\n\ninline void hseqr(char* job, char* compz, blas_int* n, blas_int* ilo,\n                  blas_int* ihi, double* h, blas_int* ldh, double* wr,\n                  double* wi, double* z, blas_int* ldz, double* work,\n                  blas_int* lwork, blas_int* info)\n{\n    arma_fortran_noprefix(arma_dhseqr)(job, compz, n, ilo, ihi, h, ldh, wr, wi,\n                                       z, ldz, work, lwork, info);\n}\n\ninline void hseqr(char* job, char* compz, blas_int* n, blas_int* ilo,\n                  blas_int* ihi, std::complex<float>* h, blas_int* ldh,\n                  std::complex<float>* w, std::complex<float>* z, blas_int* ldz,\n                  std::complex<float>* work, blas_int* lwork, blas_int* info)\n{\n    arma_fortran_noprefix(arma_chseqr)(job, compz, n, ilo, ihi, h, ldh, w, z,\n                                       ldz, work, lwork, info);\n}\n\ninline void hseqr(char* job, char* compz, blas_int* n, blas_int* ilo,\n                  blas_int* ihi, std::complex<double>* h, blas_int* ldh,\n                  std::complex<double>* w, std::complex<double>* z,\n                  blas_int* ldz, std::complex<double>* work, blas_int* lwork,\n                  blas_int* info)\n{\n    arma_fortran_noprefix(arma_zhseqr)(job, compz, n, ilo, ihi, h, ldh, w, z,\n                                       ldz, work, lwork, info);\n}\n\n// Jacobi SVD\ninline void gesvj(char* joba, char* jobu, char* jobv, blas_int* m, blas_int* n,\n                  float* a, blas_int* lda, float* sva, blas_int* mv, float* v,\n                  blas_int* ldv, float* work, blas_int* lwork, blas_int* info)\n{\n    arma_fortran_noprefix(arma_sgesvj)(joba, jobu, jobv, m, n, a, lda, sva, mv,\n                                       v, ldv, work, lwork, info);\n}\n\ninline void gesvj(char* joba, char* jobu, char* jobv, blas_int* m, blas_int* n,\n                  double* a, blas_int* lda, double* sva, blas_int* mv,\n                  double* v, blas_int* ldv, double* work, blas_int* lwork,\n                  blas_int* info)\n{\n    arma_fortran_noprefix(arma_dgesvj)(joba, jobu, jobv, m, n, a, lda, sva, mv,\n                                       v, ldv, work, lwork, info);\n}\n\ninline void gesvj(char* joba, char* jobu, char* jobv, blas_int* m, blas_int* n,\n                  std::complex<float>* a, blas_int* lda, float* sva,\n                  blas_int* mv, std::complex<float>* v, blas_int* ldv,\n                  std::complex<float>* cwork, blas_int* lwork, float* rwork,\n                  blas_int* lrwork, blas_int* info)\n{\n    using complex_t = std::complex<float>;\n    arma_fortran_noprefix(arma_cgesvj)(\n        joba, jobu, jobv, m, n, (complex_t*)a, lda, sva, mv, (complex_t*)v, ldv,\n        (complex_t*)cwork, lwork, rwork, lrwork, info);\n}\n\ninline void gesvj(char* joba, char* jobu, char* jobv, blas_int* m, blas_int* n,\n                  std::complex<double>* a, blas_int* lda, double* sva,\n                  blas_int* mv, std::complex<double>* v, blas_int* ldv,\n                  std::complex<double>* cwork, blas_int* lwork, double* rwork,\n                  blas_int* lrwork, blas_int* info)\n{\n    using complex_t = std::complex<float>;\n    arma_fortran_noprefix(arma_zgesvj)(\n        joba, jobu, jobv, m, n, (complex_t*)a, lda, sva, mv, (complex_t*)v, ldv,\n        (complex_t*)cwork, lwork, rwork, lrwork, info);\n}\n\n// Another Jacobi SVD\ninline void gejsv(char* joba, char* jobu, char* jobv, char* jobr, char* jobt,\n                  char* jobp, blas_int* m, blas_int* n, float* a, blas_int* lda,\n                  float* sva, float* u, blas_int* ldu, float* v, blas_int* ldv,\n                  float* work, blas_int* lwork, blas_int* iwork, blas_int* info)\n{\n    arma_fortran_noprefix(arma_sgejsv)(joba, jobu, jobv, jobr, jobt, jobp, m, n,\n                                       a, lda, sva, u, ldu, v, ldv, work, lwork,\n                                       iwork, info);\n}\n\ninline void gejsv(char* joba, char* jobu, char* jobv, char* jobr, char* jobt,\n                  char* jobp, blas_int* m, blas_int* n, double* a,\n                  blas_int* lda, double* sva, double* u, blas_int* ldu,\n                  double* v, blas_int* ldv, double* work, blas_int* lwork,\n                  blas_int* iwork, blas_int* info)\n{\n    arma_fortran_noprefix(arma_dgejsv)(joba, jobu, jobv, jobr, jobt, jobp, m, n,\n                                       a, lda, sva, u, ldu, v, ldv, work, lwork,\n                                       iwork, info);\n}\n\ninline void gejsv(char* joba, char* jobu, char* jobv, char* jobr, char* jobt,\n                  char* jobp, blas_int* m, blas_int* n, std::complex<float>* a,\n                  blas_int* lda, float* sva, std::complex<float>* u,\n                  blas_int* ldu, std::complex<float>* v, blas_int* ldv,\n                  std::complex<float>* cwork, blas_int* lwork, float* rwork,\n                  blas_int* lrwork, blas_int* iwork, blas_int* info)\n{\n    arma_fortran_noprefix(arma_cgejsv)(joba, jobu, jobv, jobr, jobt, jobp, m, n,\n                                       a, lda, sva, u, ldu, v, ldv, cwork,\n                                       lwork, rwork, lrwork, iwork, info);\n}\n\ninline void gejsv(char* joba, char* jobu, char* jobv, char* jobr, char* jobt,\n                  char* jobp, blas_int* m, blas_int* n, std::complex<double>* a,\n                  blas_int* lda, double* sva, std::complex<double>* u,\n                  blas_int* ldu, std::complex<double>* v, blas_int* ldv,\n                  std::complex<double>* cwork, blas_int* lwork, double* rwork,\n                  blas_int* lrwork, blas_int* iwork, blas_int* info)\n{\n    arma_fortran_noprefix(arma_zgejsv)(joba, jobu, jobv, jobr, jobt, jobp, m, n,\n                                       a, lda, sva, u, ldu, v, ldv, cwork,\n                                       lwork, rwork, lrwork, iwork, info);\n}\n\n} // namespace: lapack\n} // namespace: arma\n\n#endif /* ARMA_LAPACK_EXTRA_HPP */\n", "meta": {"hexsha": "eb1fcfbbe21b35f1877c2a9d5e029d00d4f22c22", "size": 22384, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arma/lapack_extra.hpp", "max_stars_repo_name": "hide-ikeno/expsum", "max_stars_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/arma/lapack_extra.hpp", "max_issues_repo_name": "hide-ikeno/expsum", "max_issues_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/arma/lapack_extra.hpp", "max_forks_repo_name": "hide-ikeno/expsum", "max_forks_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.223628692, "max_line_length": 80, "alphanum_fraction": 0.5194335239, "num_tokens": 6139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.44436176226690877}}
{"text": "#include <iostream>\n#include <vector>\n#include <random>\n#include <fstream>\n#include <omp.h>\n#include <boost/numeric/odeint.hpp>\n#include \"cahnhilliard_thermal.h\"\n#include \"utils_ch.h\"\n\n#include <petscvec.h>\n#include <petscksp.h>\n#include <petscsnes.h>\n#include <petscts.h>\n\n  /*\n  Cahn-Hilliard:\n  \n  dc/dt = laplacian( u*c^3 - b*c ) - eps_2*biharm(c) - sigma*(c - m) + sigma_noise * N(0,1^2)\n  \n  expanding out RHS into individual differentials:\n  D*laplacian( u*c^3 - b*c) - D*eps_2*biharm(c)\n  assuming constant eps_2.\n\n  need a d^4 and a d^2 operator.\n  */\n\nCahnHilliard2DRHS_thermal::CahnHilliard2DRHS_thermal(CHparamsScalar& chp , SimInfo& info)\n  : noise_dist_(0.0,1.0) , info_(info) , petsc_context_(*this)\n  {    \n    chpV_.eps_2    = std::vector<double>( info_.nx*info_.ny , chp.eps_2     );\n    chpV_.b        = std::vector<double>( info_.nx*info_.ny , chp.b         );\n    chpV_.u        = std::vector<double>( info_.nx*info_.ny , chp.u         );\n    chpV_.sigma    = std::vector<double>( info_.nx*info_.ny , chp.sigma     );\n    chpV_.m        = std::vector<double>( info_.nx*info_.ny , chp.m  );\n    chpV_.DT       = std::vector<double>( info_.nx*info_.ny , chp.DT  );\n    chpV_.f_T      = std::vector<double>( info_.nx*info_.ny , chp.f_T  );\n    chpV_.sigma_noise    = chp.sigma_noise;\n\n    if ( info.bc.compare(\"dirichlet\") == 0) {\n      ch_rhs_ = &compute_ch_nonlocal_stationary_boundaries;\n      std::cout << \"Initialized Cahn-Hilliard equation: scalar parameters, dirichlet BCs, thermal coefficient dependence, thermal diffusion\" << std::endl;\n    }\n    else if ( info.bc.compare(\"neumann\") == 0) {\n      ch_rhs_ = &compute_ch_nonlocal_neumannBC;\n      std::cout << \"Initialized Cahn-Hilliard equation: scalar parameters, neumann BCs, thermal coefficient dependence, thermal diffusion\" << std::endl;\n    }\n    else {\n      ch_rhs_ = &compute_ch_nonlocal;\n      std::cout << \"Initialized Cahn-Hilliard equation: scalar parameters, periodic BCs, thermal coefficient dependence, thermal diffusion\" << std::endl;\n    }\n    \n  }\n\nCahnHilliard2DRHS_thermal::CahnHilliard2DRHS_thermal(CHparamsVector& chp , SimInfo& info)\n  : noise_dist_(0.0,1.0) , chpV_(chp) , info_(info) , petsc_context_(*this)\n  {\n\n    if ( info.bc.compare(\"dirichlet\") == 0) {\n      ch_rhs_ = &compute_ch_nonlocal_stationary_boundaries;\n      std::cout << \"Initialized Cahn-Hilliard equation: spatial-field parameters, dirichlet BCs, thermal coefficient dependence, thermal diffusion\" << std::endl;\n    }\n    if ( info.bc.compare(\"neumann\") == 0) {\n      ch_rhs_ = &compute_ch_nonlocal_neumannBC;\n      std::cout << \"Initialized Cahn-Hilliard equation: spatial-field parameters, neumann BCs, thermal coefficient dependence, thermal diffusion\" << std::endl;\n    }\n    else {\n      ch_rhs_ = &compute_ch_nonlocal;\n      std::cout << \"Initialized Cahn-Hilliard equation: spatial-field parameters, periodic BCs, thermal coefficient dependence, thermal diffusion\" << std::endl;\n    }\n    \n  }\n\nCahnHilliard2DRHS_thermal::~CahnHilliard2DRHS_thermal() { };\n\nvoid CahnHilliard2DRHS_thermal::rhs(const std::vector<double> &ct, std::vector<double> &dcTdt, const double t)\n  {\n    dcTdt.resize(2 * info_.nx * info_.ny);\n    std::vector<double> c = std::vector<double>( ct.begin() , ct.begin() + info_.nx*info_.ny );\n    std::vector<double> T = std::vector<double>( ct.begin() + info_.nx*info_.ny , ct.end() );\n\n    // enforce thermal BC: dT/dnormal = 0\n    # pragma omp parallel for\n    for (int i = 0; i < info_.nx; ++i) {\n      T[info_.idx2d(0,i)]          = T[info_.idx2d(1,i)];\n      T[info_.idx2d(info_.ny-1,i)] = T[info_.idx2d(info_.ny-2,i)];\n    }\n\n    # pragma omp parallel for\n    for (int i = 0; i < info_.ny; ++i) {\n      T[info_.idx2d(i,0)]          = T[info_.idx2d(i,1)];\n      T[info_.idx2d(i,info_.nx-1)] = T[info_.idx2d(i,info_.nx-2)];\n    }\n\n    // evaluate CH parameter dependencies on temperature\n    //chpV_ = compute_chparams_using_temperature( chpV_ , info_ , T );\n    chpV_ = compute_eps2_and_sigma_from_polymer_params( chpV_ , info_ , T );\n\n    // evaluate deterministic nonlocal dynamics\n    compute_ch_nonlocal(c, dcTdt, t, chpV_, info_);\n    \n    // evaluate thermal diffusion\n    # pragma omp parallel for\n    for (int i = 0; i < info_.ny; ++i) {\n      for (int j = 0; j < info_.nx; ++j) {\n        \n        const double T_i   = T[info_.idx2d(i, j)];\n        const double T_im1 = T[info_.idx2d(i - 1, j)];\n        const double T_ip1 = T[info_.idx2d(i + 1, j)];\n        const double T_jm1 = T[info_.idx2d(i, j - 1)];\n        const double T_jp1 = T[info_.idx2d(i, j + 1)];\n\n        double dxx = 1.0 / (info_.dx * info_.dx) * (T_jm1 + T_jp1 - 2.0 * T_i);\n        double dyy = 1.0 / (info_.dy * info_.dy) * (T_im1 + T_ip1 - 2.0 * T_i);\n        \n        dcTdt[info_.idx2d(i, j) + info_.nx*info_.ny]  = chpV_.DT[info_.idx2d(i, j)] * (dxx + dyy) + chpV_.f_T[info_.idx2d(i, j)];\n        \n      }\n    }\n\n    // enforce thermal BC: dT/dnormal = 0\n    # pragma omp parallel for\n    for (int i = 0; i < info_.nx; ++i) {\n      dcTdt[info_.idx2d(0,i) + info_.nx*info_.ny]          = 0;\n      dcTdt[info_.idx2d(info_.ny-1,i) + info_.nx*info_.ny] = 0;\n    }\n\n    # pragma omp parallel for\n    for (int i = 0; i < info_.ny; ++i) {\n      dcTdt[info_.idx2d(i,0) + info_.nx*info_.ny]          = 0;\n      dcTdt[info_.idx2d(i,info_.nx-1) + info_.nx*info_.ny] = 0;\n    }\n    \n  }\n\n\nvoid CahnHilliard2DRHS_thermal::setInitialConditions(std::vector<double> &x)\n  {\n    x.resize(2 * info_.nx * info_.ny);\n\n    std::default_random_engine generator;\n    std::uniform_real_distribution<double> distribution(-1.0,1.0);\n\n    for (int i = 0; i < info_.ny; ++i) {\n      for (int j = 0; j < info_.nx; ++j) {\n        x[info_.idx2d(i,j)]                     = distribution(generator) * 0.005;\n\tx[info_.idx2d(i,j) + info_.nx*info_.ny] = chpV_.T_min;\n      }\n    }\n\n    // Set BCs if needed\n    if ( info_.bc.compare(\"dirichlet\") == 0) {\n      x = apply_dirichlet_bc( x , info_ );\n    }\n    else if ( info_.bc.compare(\"neumann\") == 0 ) {\n      x = apply_neumann_bc( x , info_ );\n    }\n\n  }\n\n\nvoid CahnHilliard2DRHS_thermal::write_state(const std::vector<double> &x , const int idx , const int nx , const int ny , std::string& outdir)\n{\n  if ( outdir.back() != '/' )\n    outdir += '/';\n  std::ofstream outC;\n  std::ofstream outT;\n  outC.open( outdir + \"C_\" + std::to_string(idx) + \".out\" );\n  outT.open( outdir + \"T_\" + std::to_string(idx) + \".out\" );\n  outC.precision(16);\n  outT.precision(16);\n  \n  for (int i = 0; i < ny; ++i){\n    for (int j = 0; j < nx; ++j){\n      outC << x[i * ny + j] << \" \";\n      outT << x[i * ny + j + nx*ny] << \" \";\n    }\n  }\n\n  outC.close();\n  outT.close();\n};\n", "meta": {"hexsha": "3ad9501cd19e5ebab0c00af7bbf04c1becda50c2", "size": 6653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/cahnhilliard_thermal.cpp", "max_stars_repo_name": "exalearn/cahnhilliard_2d", "max_stars_repo_head_hexsha": "cbf272bbac8080ff97c1cc93e7e7246bee04e075", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-23T23:53:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T06:16:24.000Z", "max_issues_repo_path": "cpp/src/cahnhilliard_thermal.cpp", "max_issues_repo_name": "exalearn/cahnhilliard_2d", "max_issues_repo_head_hexsha": "cbf272bbac8080ff97c1cc93e7e7246bee04e075", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/cahnhilliard_thermal.cpp", "max_forks_repo_name": "exalearn/cahnhilliard_2d", "max_forks_repo_head_hexsha": "cbf272bbac8080ff97c1cc93e7e7246bee04e075", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5549450549, "max_line_length": 161, "alphanum_fraction": 0.610701939, "num_tokens": 2236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.44436176226690877}}
{"text": "// MIT License\n//\n// Copyright (c) 2018 Lennart Braun\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <cstdint>\n#include <boost/asio.hpp>\n#include <botan/blake2b.h>\n#include <botan/hex.h>\n#include \"ot_hl17.hpp\"\n#include \"util/threading.hpp\"\n\n\nOT_HL17::OT_HL17(Connection& connection) : connection_(connection)\n{\n}\n\n// Notation\n// * Group GG\n// * of prime order p\n// * with generator g\n//\n// * random oracle G: GG -> GG\n// * random oracle H: GG^3 -> K\n\n\nvoid OT_HL17::hash_point(curve25519::ge_p3& output, const curve25519::ge_p3& input)\n{\n    std::array<uint8_t, 32> hash_input;\n    std::array<uint8_t, 64> hash_output{};\n    auto hash(Botan::Blake2b(256));\n\n    curve25519::ge_p3_tobytes(hash_input.data(), &input);\n    hash.update(hash_input.data(), hash_input.size());\n    hash.final(hash_output.data());\n    curve25519::x25519_sc_reduce(hash_output.data());\n\n    curve25519::x25519_ge_scalarmult_base(&output, hash_output.data());\n}\n\nvoid OT_HL17::send_0(Sender_State& state,\n                     std::array<uint8_t, curve25519_ge_byte_size>& message_out)\n{\n    // sample y <- Zp\n    curve25519::sc_random(state.y);\n\n    // S = g^y\n    curve25519::x25519_ge_scalarmult_base(&state.S, state.y);\n\n    curve25519::ge_p3_tobytes(message_out.data(), &state.S);\n}\n\nvoid OT_HL17::send_1(Sender_State& state)\n{\n    // T = G(S)\n    hash_point(state.T, state.S);\n}\n\nstd::pair<bytes_t, bytes_t> OT_HL17::send_2(Sender_State& state,\n                                            const std::array<uint8_t, curve25519_ge_byte_size>& message_in)\n{\n    // // assert R in GG\n    if (!x25519_ge_frombytes_vartime(&state.R, message_in.data()))\n        std::terminate();\n\n    auto hash(Botan::Blake2b(128));\n\n    auto output = std::make_pair<>(bytes_t(16), bytes_t(16));\n    assert(output.first.size() == hash.output_length());\n    assert(output.second.size() == hash.output_length());\n\n    std::array<uint8_t, 3*curve25519_ge_byte_size> hash_input;\n    curve25519::ge_p3_tobytes(hash_input.data(), &state.S);\n    curve25519::ge_p3_tobytes(hash_input.data() + 32, &state.R);\n\n    // j = 0:\n    // y*R\n    curve25519::ge_p2 y_times_R_p2;\n    curve25519::x25519_ge_scalarmult(&y_times_R_p2, state.y, &state.R);\n    curve25519::x25519_ge_tobytes(hash_input.data() + 64, &y_times_R_p2);\n\n    // H(S, R, y*R)\n    hash.update(hash_input.data(), hash_input.size());\n    hash.final(reinterpret_cast<uint8_t*>(output.first.data()));\n\n\n    // j = 1:\n    // y*R + (-y)*T = y*(R - T)\n    {\n        curve25519::ge_cached T_cached;\n        curve25519::x25519_ge_p3_to_cached(&T_cached, &state.T);\n\n        curve25519::ge_p1p1 R_minus_T_p1p1;\n        curve25519::x25519_ge_sub(&R_minus_T_p1p1, &state.R, &T_cached);\n\n        curve25519::ge_p3 R_minus_T_p3;\n        curve25519::x25519_ge_p1p1_to_p3(&R_minus_T_p3, &R_minus_T_p1p1);\n\n        curve25519::ge_p2 y_times_R_minus_T_p2;\n        curve25519::x25519_ge_scalarmult(&y_times_R_minus_T_p2, state.y, &R_minus_T_p3);\n        curve25519::x25519_ge_tobytes(hash_input.data() + 64, &y_times_R_minus_T_p2);\n\n    }\n\n    // H(S, R, y*R - y*T)\n    hash.update(hash_input.data(), hash_input.size());\n    hash.final(reinterpret_cast<uint8_t*>(output.second.data()));\n\n    return output;\n}\n\nvoid OT_HL17::recv_0(Receiver_State& state, bool choice)\n{\n    state.choice = choice;\n    // sample x <- Zp\n    curve25519::sc_random(state.x);\n}\n\n\nvoid OT_HL17::recv_1(Receiver_State& state,\n                     std::array<uint8_t, curve25519_ge_byte_size>& message_out,\n                     const std::array<uint8_t, curve25519_ge_byte_size>& message_in)\n{\n    // recv S\n    auto res = curve25519::x25519_ge_frombytes_vartime(&state.S, message_in.data());\n    // assert S in GG\n    if (res == 0)\n        std::terminate();\n\n    // T = G(S)\n    hash_point(state.T, state.S);\n\n    // R = T^c * g^x\n\n    // R = g^x\n    curve25519::x25519_ge_scalarmult_base(&state.R, state.x);\n\n    // FIXME: not constant time\n    if (state.choice == 1)\n    {\n        curve25519::ge_p1p1 R_p1p1;\n        curve25519::ge_cached T_cached;\n        curve25519::x25519_ge_p3_to_cached(&T_cached, &state.T);\n        curve25519::x25519_ge_add(&R_p1p1, &state.R, &T_cached);\n        curve25519::x25519_ge_p1p1_to_p3(&state.R, &R_p1p1);\n    }\n\n    bytes_t R_bytes(32);\n    curve25519::ge_p3_tobytes(message_out.data(), &state.R);\n}\n\nbytes_t OT_HL17::recv_2(Receiver_State& state)\n{\n    // k_R = H_(S,R)(S^x)\n    //     = H_(S,R)(g^xy)\n\n    bytes_t hash_output(16);\n\n    std::array<uint8_t, 3*32> hash_input;\n    curve25519::ge_p3_tobytes(hash_input.data(), &state.S);\n    curve25519::ge_p3_tobytes(hash_input.data() + 32, &state.R);\n\n    curve25519::ge_p2 S_to_the_x;\n    curve25519::x25519_ge_scalarmult(&S_to_the_x, state.x, &state.S);\n    curve25519::x25519_ge_tobytes(hash_input.data() + 64, &S_to_the_x);\n\n\n    auto hash(Botan::Blake2b(128));\n    assert(hash_output.size() == hash.output_length());\n    hash.update(hash_input.data(), hash_input.size());\n    hash.final(reinterpret_cast<uint8_t*>(hash_output.data()));\n\n\n    return hash_output;\n}\n\n\nstd::pair<bytes_t, bytes_t> OT_HL17::send()\n{\n    Sender_State state;\n    std::array<uint8_t, curve25519_ge_byte_size> msg_s0;\n    std::array<uint8_t, curve25519_ge_byte_size> msg_r1;\n\n    send_0(state, msg_s0);\n    connection_.send(msg_s0.data(), msg_s0.size());\n    send_1(state);\n    connection_.recv(msg_r1.data(), msg_r1.size());\n    return send_2(state, msg_r1);\n}\n\n\nbytes_t OT_HL17::recv(bool choice)\n{\n    Receiver_State state;\n    std::array<uint8_t, curve25519_ge_byte_size> msg_s0;\n    std::array<uint8_t, curve25519_ge_byte_size> msg_r1;\n\n    recv_0(state, choice);\n    connection_.recv(msg_s0.data(), msg_s0.size());\n    recv_1(state, msg_r1, msg_s0);\n    connection_.send(msg_r1.data(), msg_r1.size());\n    return recv_2(state);\n}\n\n\nstd::vector<std::pair<bytes_t, bytes_t>> OT_HL17::send(size_t number_ots)\n{\n    std::vector<Sender_State> states(number_ots);\n    std::vector<std::array<uint8_t, curve25519_ge_byte_size>> msgs_s0(number_ots);\n    std::vector<std::array<uint8_t, curve25519_ge_byte_size>> msgs_r1(number_ots);\n    std::vector<std::pair<bytes_t, bytes_t>> output(number_ots);\n\n    for (size_t i = 0; i < number_ots; ++i)\n    {\n        send_0(states[i], msgs_s0[i]);\n    }\n\n    auto fut_send_msg_s0 = connection_.async_send(reinterpret_cast<uint8_t*>(msgs_s0.data()), msgs_s0.size() * curve25519_ge_byte_size);\n    auto fut_recv_msg_r1 = connection_.async_recv(reinterpret_cast<uint8_t*>(msgs_r1.data()), msgs_r1.size() * curve25519_ge_byte_size);\n\n    for (size_t i = 0; i < number_ots; ++i)\n    {\n        send_1(states[i]);\n    }\n\n    auto msg_r1_size = fut_recv_msg_r1.get();\n    assert(msg_r1_size == msgs_r1.size() * curve25519_ge_byte_size);\n\n    for (size_t i = 0; i < number_ots; ++i)\n    {\n        output[i] = send_2(states[i], msgs_r1[i]);\n    }\n\n    auto msg_s0_size = fut_send_msg_s0.get();\n    assert(msg_s0_size == msgs_s0.size() * curve25519_ge_byte_size);\n\n    return output;\n}\n\nstd::vector<bytes_t> OT_HL17::recv(const std::vector<bool>& choices)\n{\n    auto number_ots = choices.size();\n    std::vector<Receiver_State> states(number_ots);\n    std::vector<std::array<uint8_t, curve25519_ge_byte_size>> msgs_s0(number_ots);\n    std::vector<std::array<uint8_t, curve25519_ge_byte_size>> msgs_r1(number_ots);\n    std::vector<bytes_t> output(number_ots);\n\n    auto fut_recv_msg_s0 = connection_.async_recv(reinterpret_cast<uint8_t*>(msgs_s0.data()), msgs_s0.size() * curve25519_ge_byte_size);\n\n    for (size_t i = 0; i < number_ots; ++i)\n    {\n        recv_0(states[i], choices[i]);\n    }\n\n    auto msg_s0_size = fut_recv_msg_s0.get();\n    assert(msg_s0_size == msgs_s0.size() * curve25519_ge_byte_size);\n\n    for (size_t i = 0; i < number_ots; ++i)\n    {\n        recv_1(states[i], msgs_r1[i], msgs_s0[i]);\n    }\n\n    auto fut_send_msg_r1 = connection_.async_send(reinterpret_cast<uint8_t*>(msgs_r1.data()), msgs_r1.size() * curve25519_ge_byte_size);\n\n    for (size_t i = 0; i < number_ots; ++i)\n    {\n        output[i] = recv_2(states[i]);\n    }\n\n    auto msg_r1_size = fut_send_msg_r1.get();\n    assert(msg_r1_size == msgs_s0.size() * curve25519_ge_byte_size);\n\n    return output;\n}\n\n\nstd::vector<std::pair<bytes_t, bytes_t>> OT_HL17::parallel_send(size_t number_ots, size_t number_threads, boost::asio::thread_pool& thread_pool)\n{\n    std::vector<Sender_State> states(number_ots);\n    std::vector<std::array<uint8_t, curve25519_ge_byte_size>> msgs_s0(number_ots);\n    std::vector<std::array<uint8_t, curve25519_ge_byte_size>> msgs_r1(number_ots);\n    std::vector<std::pair<bytes_t, bytes_t>> output(number_ots);\n\n    compute(thread_pool, number_ots, number_threads, [this, &states, &msgs_s0](size_t index){ send_0(states[index], msgs_s0[index]); });\n\n    auto fut_send_msg_s0 = connection_.async_send(reinterpret_cast<uint8_t*>(msgs_s0.data()), msgs_s0.size() * curve25519_ge_byte_size);\n    auto fut_recv_msg_r1 = connection_.async_recv(reinterpret_cast<uint8_t*>(msgs_r1.data()), msgs_r1.size() * curve25519_ge_byte_size);\n\n\n    compute(thread_pool, number_ots, number_threads, [this, &states](size_t index){ send_1(states[index]); });\n\n    auto msg_r1_size = fut_recv_msg_r1.get();\n    assert(msg_r1_size == msgs_r1.size() * curve25519_ge_byte_size);\n\n    compute(thread_pool, number_ots, number_threads, [this, &states, &msgs_r1, &output](size_t index){ output[index] = send_2(states[index], msgs_r1[index]); });\n\n    auto msg_s0_size = fut_send_msg_s0.get();\n    assert(msg_s0_size == msgs_s0.size() * curve25519_ge_byte_size);\n\n    return output;\n}\n\n\nstd::vector<bytes_t> OT_HL17::parallel_recv(const std::vector<bool>& choices, size_t number_threads, boost::asio::thread_pool& thread_pool)\n{\n    auto number_ots = choices.size();\n    std::vector<Receiver_State> states(number_ots);\n    std::vector<std::array<uint8_t, curve25519_ge_byte_size>> msgs_s0(number_ots);\n    std::vector<std::array<uint8_t, curve25519_ge_byte_size>> msgs_r1(number_ots);\n    std::vector<bytes_t> output(number_ots);\n\n    auto fut_recv_msg_s0 = connection_.async_recv(reinterpret_cast<uint8_t*>(msgs_s0.data()), msgs_s0.size() * curve25519_ge_byte_size);\n\n    compute(thread_pool, number_ots, number_threads, [this, &states, &choices](size_t index){ recv_0(states[index], choices[index]); });\n\n    auto msg_s0_size = fut_recv_msg_s0.get();\n    assert(msg_s0_size == msgs_s0.size() * curve25519_ge_byte_size);\n\n    compute(thread_pool, number_ots, number_threads, [this, &states, &msgs_r1, &msgs_s0](size_t index){ recv_1(states[index], msgs_r1[index], msgs_s0[index]); });\n\n    auto fut_send_msg_r1 = connection_.async_send(reinterpret_cast<uint8_t*>(msgs_r1.data()), msgs_r1.size() * curve25519_ge_byte_size);\n\n    compute(thread_pool, number_ots, number_threads, [this, &states, &output](size_t index){ output[index] = recv_2(states[index]); });\n\n    auto msg_r1_size = fut_send_msg_r1.get();\n    assert(msg_r1_size == msgs_s0.size() * curve25519_ge_byte_size);\n\n    return output;\n}\n", "meta": {"hexsha": "db55aeebeb819cdcc10b9aa9c1f0834d6f5b68b4", "size": 12029, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ot/ot_hl17.cpp", "max_stars_repo_name": "lenerd/libparty", "max_stars_repo_head_hexsha": "5afd551303dbb9141f722d3540a81946feedc6e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-06-06T21:44:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-06T21:44:34.000Z", "max_issues_repo_path": "src/ot/ot_hl17.cpp", "max_issues_repo_name": "lenerd/libparty", "max_issues_repo_head_hexsha": "5afd551303dbb9141f722d3540a81946feedc6e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ot/ot_hl17.cpp", "max_forks_repo_name": "lenerd/libparty", "max_forks_repo_head_hexsha": "5afd551303dbb9141f722d3540a81946feedc6e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3685714286, "max_line_length": 162, "alphanum_fraction": 0.691994347, "num_tokens": 3504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4443617622669087}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n#ifndef WRAPPERS_H\n#define WRAPPERS_H\n\n#include <algorithm>\n#include <cmath>\n#include <complex>\n#include <functional>\n#include <limits>\n#include <numeric>\n#include <sstream>\n#include <string>\n#include <type_traits>\n#include <vector>\n#include <Eigen/Core>\n#include <boost/lexical_cast.hpp>\n\n#include \"dilog.hpp\"\n#include \"eigen_tensor.hpp\"\n\nnamespace flexiblesusy {\n\nstatic const double Pi = M_PI;\nstatic const double oneOver16PiSqr = 1./(16. * M_PI * M_PI);\nstatic const double twoLoop = oneOver16PiSqr * oneOver16PiSqr;\nstatic const double threeLoop = oneOver16PiSqr * oneOver16PiSqr * oneOver16PiSqr;\nstatic const bool True = true;\n\ntemplate <typename T>\nT Abs(T a)\n{\n   return std::abs(a);\n}\n\ntemplate <typename T>\nT Abs(const std::complex<T>& z)\n{\n   return std::abs(z);\n}\n\ntemplate <typename Scalar, int M, int N>\nEigen::Array<Scalar, M, N> Abs(const Eigen::Array<Scalar, M, N>& a)\n{\n   return a.cwiseAbs();\n}\n\ntemplate <class T>\nstd::vector<T> Abs(std::vector<T> v)\n{\n   for (typename std::vector<T>::iterator it = v.begin(),\n           end = v.end(); it != end; ++it)\n      *it = Abs(*it);\n   return v;\n}\n\ninline double AbsSqr(double z)\n{\n   return z * z;\n}\n\ninline double AbsSqr(const std::complex<double>& z)\n{\n   return std::norm(z);\n}\n\ninline double AbsSqrt(double x)\n{\n   return std::sqrt(std::fabs(x));\n}\n\ntemplate <typename Derived>\nDerived AbsSqrt(const Eigen::MatrixBase<Derived>& m)\n{\n   return m.cwiseAbs().cwiseSqrt();\n}\n\ntemplate <typename Derived>\nDerived AbsSqrt(const Eigen::ArrayBase<Derived>& m)\n{\n   return m.cwiseAbs().cwiseSqrt();\n}\n\n/**\n * Calculates the mass of a singlet from a (possibly complex)\n * numerical value by taking the magnitude of the value.\n *\n * @param value numerical value\n * @return mass\n */\ntemplate <typename T>\ndouble calculate_singlet_mass(T value)\n{\n   return std::abs(value);\n}\n\n/**\n * Calculates the mass of a Majoran fermion singlet from a (possibly\n * complex) numerical value by taking the magnitude of the value.\n *\n * The phase is set to exp(i theta/2), where theta is the phase angle\n * of the complex value.  If the value is pure real, then the phase\n * will be set to 1.  If the value is purely imaginary, then the phase\n * will be set to \\f$e^{i \\pi/2}\\f$.\n *\n * @param value numerical value\n * @param[out] phase phase\n * @return mass\n */\ntemplate <typename T>\ndouble calculate_majorana_singlet_mass(T value, std::complex<double>& phase)\n{\n   phase = std::polar(1., 0.5 * std::arg(std::complex<double>(value)));\n   return std::abs(value);\n}\n\n/**\n * Calculates the mass of a Dirac fermion singlet from a (possibly\n * complex) numerical value by taking the magnitude of the value.\n *\n * The phase is set to exp(i theta), where theta is the phase angle of\n * the complex value.  If the value is pure real, then the phase will\n * be set to 1.  If the value is purely imaginary, then the phase will\n * be set to \\f$e^{i \\pi}\\f$.\n *\n * @param value numerical value\n * @param[out] phase phase\n * @return mass\n */\ntemplate <typename T>\ndouble calculate_dirac_singlet_mass(T value, std::complex<double>& phase)\n{\n   phase = std::polar(1., std::arg(std::complex<double>(value)));\n   return std::abs(value);\n}\n\ninline double ArcTan(double a)\n{\n   return std::atan(a);\n}\n\ninline double ArcSin(double a)\n{\n   return std::asin(a);\n}\n\ninline double ArcCos(double a)\n{\n   return std::acos(a);\n}\n\ninline double Arg(const std::complex<double>& z)\n{\n   return std::arg(z);\n}\n\ninline double Conj(double a)\n{\n   return a;\n}\n\ninline std::complex<double> Conj(const std::complex<double>& a)\n{\n   return std::conj(a);\n}\n\ntemplate <class T>\nT Conjugate(T a)\n{\n   return Conj(a);\n}\n\ntemplate <typename T>\nT Exp(T z)\n{\n   return std::exp(z);\n}\n\ninline double Tan(double a)\n{\n   return std::tan(a);\n}\n\ninline double Cos(double x)\n{\n   return std::cos(x);\n}\n\ninline double Sin(double x)\n{\n   return std::sin(x);\n}\n\ninline double Sec(double x)\n{\n   return 1./Cos(x);\n}\n\ninline double Csc(double x)\n{\n   return 1./Sin(x);\n}\n\ninline int Delta(int i, int j)\n{\n   return i == j;\n}\n\ntemplate <typename T>\nT If(bool c, T a, T b) { return c ? a : b; }\n\ntemplate <typename T>\nT If(bool c, int a, T b) { return c ? T(a) : b; }\n\ntemplate <typename T>\nT If(bool c, T a, int b) { return c ? a : T(b); }\n\ninline bool IsClose(double a, double b,\n                    double eps = std::numeric_limits<double>::epsilon())\n{\n   return std::abs(a - b) < eps;\n}\n\ninline bool IsCloseRel(double a, double b,\n                       double eps = std::numeric_limits<double>::epsilon())\n{\n   if (IsClose(a, b, std::numeric_limits<double>::epsilon()))\n      return true;\n\n   if (std::abs(a) < std::numeric_limits<double>::epsilon())\n      return IsClose(a, b, eps);\n\n   return std::abs((a - b)/a) < eps;\n}\n\ninline bool IsFinite(double x)\n{\n   return std::isfinite(x);\n}\n\ninline bool IsFinite(const std::complex<double>& x)\n{\n   return std::isfinite(x.real()) && std::isfinite(x.imag());\n}\n\ntemplate <class Derived>\nbool IsFinite(const Eigen::DenseBase<Derived>& m)\n{\n   return m.allFinite();\n}\n\ninline int KroneckerDelta(int i, int j)\n{\n   return i == j;\n}\n\ntemplate <class Derived>\ntypename Eigen::MatrixBase<Derived>::PlainObject Diag(const Eigen::MatrixBase<Derived>& m)\n{\n   static_assert(Eigen::MatrixBase<Derived>::RowsAtCompileTime ==\n                 Eigen::MatrixBase<Derived>::ColsAtCompileTime,\n                 \"Diag is only defined for squared matrices\");\n\n   typename Eigen::MatrixBase<Derived>::PlainObject diag(m);\n\n   for (int i = 0; i < Eigen::MatrixBase<Derived>::RowsAtCompileTime; ++i)\n      for (int k = i + 1; k < Eigen::MatrixBase<Derived>::ColsAtCompileTime; ++k)\n         diag(i,k) = 0.0;\n\n   for (int i = 0; i < Eigen::MatrixBase<Derived>::RowsAtCompileTime; ++i)\n      for (int k = 0; k < i; ++k)\n         diag(i,k) = 0.0;\n\n   return diag;\n}\n\ninline double FiniteLog(double a)\n{\n   return (std::isfinite(a) && a > std::numeric_limits<double>::epsilon())\n      ? std::log(a) : 0;\n}\n\n/**\n * Fills lower triangle of hermitian matrix from values\n * in upper triangle.\n *\n * @param m matrix\n */\ntemplate <typename Derived>\nvoid Hermitianize(Eigen::MatrixBase<Derived>& m)\n{\n   static_assert(Eigen::MatrixBase<Derived>::RowsAtCompileTime ==\n                 Eigen::MatrixBase<Derived>::ColsAtCompileTime,\n                 \"Hermitianize is only defined for squared matrices\");\n\n   for (int i = 0; i < Eigen::MatrixBase<Derived>::RowsAtCompileTime; i++)\n      for (int k = 0; k < i; k++)\n         m(i,k) = Conj(m(k,i));\n}\n\ninline double Log(double a)\n{\n   return std::log(a);\n}\n\ndouble MaxRelDiff(double, double);\n\ntemplate <class Derived>\ndouble MaxRelDiff(const Eigen::MatrixBase<Derived>& a,\n                  const Eigen::MatrixBase<Derived>& b)\n{\n   typename Eigen::MatrixBase<Derived>::PlainObject sumTol(a.rows());\n\n   assert(a.rows() == b.rows());\n\n   for (int i = 0; i < a.rows(); i++)\n      sumTol(i) = MaxRelDiff(a(i), b(i));\n\n   return sumTol.maxCoeff();\n}\n\ntemplate <class Derived>\ndouble MaxRelDiff(const Eigen::ArrayBase<Derived>& a,\n                  const Eigen::ArrayBase<Derived>& b)\n{\n   return MaxRelDiff(a.matrix(), b.matrix());\n}\n\ninline double MaxAbsValue(double x)\n{\n   return Abs(x);\n}\n\ninline double MaxAbsValue(const std::complex<double>& x)\n{\n   return Abs(x);\n}\n\ntemplate <class Derived>\ndouble MaxAbsValue(const Eigen::MatrixBase<Derived>& x)\n{\n   return x.cwiseAbs().maxCoeff();\n}\n\ninline int Sign(double x)\n{\n   return (x >= 0.0 ? 1 : -1);\n}\n\ninline int Sign(int x)\n{\n   return (x >= 0 ? 1 : -1);\n}\n\ntemplate <typename T>\nT PolyLog(int n, T z) {\n   if (n == 2)\n      return gm2calc::dilog(z);\n   assert(false && \"PolyLog(n!=2) not implemented\");\n}\n\ntemplate <typename Base, typename Exponent>\nBase Power(Base base, Exponent exp)\n{\n   return std::pow(base, exp);\n}\n\n\ninline double Re(double x)\n{\n   return x;\n}\n\ninline double Re(const std::complex<double>& x)\n{\n   return std::real(x);\n}\n\ntemplate<int M, int N>\nEigen::Matrix<double,M,N> Re(const Eigen::Matrix<double,M,N>& x)\n{\n   return x;\n}\n\ntemplate<class Derived>\ntypename Eigen::Matrix<\n   double,\n   Eigen::MatrixBase<Derived>::RowsAtCompileTime,\n   Eigen::MatrixBase<Derived>::ColsAtCompileTime>\nRe(const Eigen::MatrixBase<Derived>& x)\n{\n   return x.real();\n}\n\ninline double Im(double)\n{\n   return 0.;\n}\n\ninline double Im(const std::complex<double>& x)\n{\n   return std::imag(x);\n}\n\ntemplate<int M, int N>\nEigen::Matrix<double,M,N> Im(const Eigen::Matrix<double,M,N>& x)\n{\n   return Eigen::Matrix<double,M,N>::Zero();\n}\n\ntemplate<class Derived>\ntypename Eigen::Matrix<\n   double,\n   Eigen::MatrixBase<Derived>::RowsAtCompileTime,\n   Eigen::MatrixBase<Derived>::ColsAtCompileTime>\nIm(const Eigen::MatrixBase<Derived>& x)\n{\n   return x.imag();\n}\n\nnamespace {\n   struct CompareAbs_d {\n      bool operator() (double a, double b) { return std::abs(a) < std::abs(b); }\n   };\n}\n\ntemplate <typename T>\nT RelDiff(T a, T b, T eps = std::numeric_limits<T>::epsilon())\n{\n   const T max = std::max(a, b);\n\n   if (std::abs(max) < eps)\n      return T();\n\n   return (a - b) / max;\n}\n\ninline int Round(double a)\n{\n   return static_cast<int>(a >= 0. ? a + 0.5 : a - 0.5);\n}\n\ntemplate<int N>\nvoid Sort(Eigen::Array<double, N, 1>& v)\n{\n   std::sort(v.data(), v.data() + v.size(), CompareAbs_d());\n}\n\ninline double SignedAbsSqrt(double a)\n{\n   return Sign(a) * AbsSqrt(a);\n}\n\nnamespace {\n   inline double SignedAbsSqrt_d(double a)\n   {\n      return SignedAbsSqrt(a);\n   }\n}\n\ntemplate <typename Derived>\nDerived SignedAbsSqrt(const Eigen::ArrayBase<Derived>& m)\n{\n   return m.unaryExpr(std::ptr_fun(SignedAbsSqrt_d));\n}\n\ntemplate <class T, typename = typename std::enable_if<std::is_floating_point<T>::value,T>::type>\nT Sqrt(T a)\n{\n   return std::sqrt(a);\n}\n\ntemplate <class T, typename = typename std::enable_if<std::is_integral<T>::value,T>::type>\ndouble Sqrt(T a)\n{\n   return std::sqrt(static_cast<double>(a));\n}\n\ntemplate <typename Scalar, int M, int N>\nEigen::Array<Scalar, M, N> Sqrt(const Eigen::Array<Scalar, M, N>& m)\n{\n   return m.unaryExpr(std::ptr_fun(Sqrt<Scalar>));\n}\n\ntemplate <class T>\nstd::vector<T> Sqrt(std::vector<T> v)\n{\n   for (typename std::vector<T>::iterator it = v.begin(),\n           end = v.end(); it != end; ++it)\n      *it = Sqrt(*it);\n   return v;\n}\n\ntemplate <typename T>\nT Sqr(T a)\n{\n   return a * a;\n}\n\ntemplate <typename Scalar, int M, int N>\nEigen::Array<Scalar, M, N> Sqr(const Eigen::Array<Scalar, M, N>& a)\n{\n   return a.unaryExpr(std::ptr_fun(Sqr<Scalar>));\n}\n\ntemplate <class T>\nstd::vector<T> Sqr(std::vector<T> v)\n{\n   for (typename std::vector<T>::iterator it = v.begin(),\n           end = v.end(); it != end; ++it)\n      *it = Sqr(*it);\n   return v;\n}\n\n#define DEFINE_COMMUTATIVE_OPERATOR_COMPLEX_INT(op)                     \\\n   template <typename T>                                                \\\n   std::complex<T> operator op(const std::complex<T>& lhs, int rhs)     \\\n   {                                                                    \\\n      return lhs op static_cast<T>(rhs);                                \\\n   }                                                                    \\\n                                                                        \\\n   template <typename T>                                                \\\n   std::complex<T> operator op(int lhs, const std::complex<T>& rhs)     \\\n   {                                                                    \\\n      return static_cast<T>(lhs) op rhs;                                \\\n   }\n\nDEFINE_COMMUTATIVE_OPERATOR_COMPLEX_INT(*)\nDEFINE_COMMUTATIVE_OPERATOR_COMPLEX_INT(/)\nDEFINE_COMMUTATIVE_OPERATOR_COMPLEX_INT(+)\nDEFINE_COMMUTATIVE_OPERATOR_COMPLEX_INT(-)\n\n/**\n * Fills lower triangle of symmetric matrix from values in upper\n * triangle.\n *\n * @param m matrix\n */\ntemplate <typename Derived>\nvoid Symmetrize(Eigen::MatrixBase<Derived>& m)\n{\n   static_assert(Eigen::MatrixBase<Derived>::RowsAtCompileTime ==\n                 Eigen::MatrixBase<Derived>::ColsAtCompileTime,\n                 \"Symmetrize is only defined for squared matrices\");\n\n   for (int i = 0; i < Eigen::MatrixBase<Derived>::RowsAtCompileTime; i++)\n      for (int k = 0; k < i; k++)\n         m(i,k) = m(k,i);\n}\n\n#define UNITMATRIX(rows)             Eigen::Matrix<double,rows,rows>::Identity()\n#define ZEROMATRIX(rows,cols)        Eigen::Matrix<double,rows,cols>::Zero()\n#define ZEROTENSOR3(d1,d2,d3)        ZeroTensor3<double,d1,d2,d3>()\n#define ZEROTENSOR4(d1,d2,d3,d4)     ZeroTensor4<double,d1,d2,d3,d4>()\n#define ZEROVECTOR(rows)             Eigen::Matrix<double,rows,1>::Zero()\n#define ZEROARRAY(rows)              Eigen::Array<double,rows,1>::Zero()\n#define UNITMATRIXCOMPLEX(rows)      Eigen::Matrix<std::complex<double>,rows,rows>::Identity()\n#define ZEROMATRIXCOMPLEX(rows,cols) Eigen::Matrix<std::complex<double>,rows,cols>::Zero()\n#define ZEROVECTORCOMPLEX(rows)      Eigen::Matrix<std::complex<double>,rows,1>::Zero()\n#define ZEROTENSOR3COMPLEX(d1,d2,d3) ZeroTensor3<std::complex<double>,d1,d2,d3>()\n#define ZEROTENSOR4COMPLEX(d1,d2,d3,d4) ZeroTensor4<std::complex<double>,d1,d2,d3,d4>()\n#define ZEROARRAYCOMPLEX(rows)       Eigen::Array<std::complex<double>,rows,1>::Zero()\n\n// MxN matrix projection operator, which projects on the (X,Y)\n// component\n#define PROJECTOR Proj\n#define DEFINE_PROJECTOR(M,N,X,Y)                                       \\\n   Eigen::Matrix<double,M,N> Proj(Eigen::Matrix<double,M,N>::Zero());   \\\n   Proj(X-1,Y-1) = 1;\n\ntemplate<class Scalar, int M>\nEigen::Matrix<Scalar,M,M> ToMatrix(const Eigen::Array<Scalar,M,1>& a)\n{\n   return Eigen::Matrix<Scalar,M,M>(a.matrix().asDiagonal());\n}\n\ntemplate<class Scalar, int M, int N>\nEigen::Matrix<Scalar,M,N> ToMatrix(const Eigen::Matrix<Scalar,M,N>& a)\n{\n   return a;\n}\n\ntemplate <typename T>\nstd::string ToString(T a)\n{\n   return boost::lexical_cast<std::string>(a);\n}\n\ntemplate <class T>\nT Total(const std::vector<T>& v)\n{\n   return std::accumulate(v.begin(), v.end(), T(0));\n}\n\ntemplate <typename Scalar, int M, int N>\nScalar Total(const Eigen::Array<Scalar, M, N>& a)\n{\n   return a.sum();\n}\n\ntemplate <class Scalar, int M, int N>\nEigen::Array<Scalar,M,N> Total(const std::vector<Eigen::Array<Scalar,M,N> >& v)\n{\n   if (v.empty()) {\n      Eigen::Array<Scalar,M,N> result(0,0);\n      result.setZero();\n      return result;\n   }\n\n   Eigen::Array<Scalar,M,N> result(v[0].rows(), v[0].cols());\n   result.setZero();\n\n   for (std::size_t i = 0; i < v.size(); i++)\n      result += v[i];\n\n   return result;\n}\n\n/// step function (0 for x < 0, 1 otherwise)\ntemplate <typename T>\nunsigned UnitStep(T x)\n{\n   return x < T() ? 0 : 1;\n}\n\ntemplate <typename T>\nT Which(bool cond, T value)\n{\n   return cond ? value : T(0);\n}\n\ntemplate<typename T, typename ... Trest>\nT Which(bool cond, T value, Trest... rest)\n{\n   return cond ? value : Which(rest...);\n}\n\ninline double ZeroSqrt(double x)\n{\n   return (x > 0.0 ? std::sqrt(x) : 0.0);\n}\n\nnamespace {\n  inline double ZeroSqrt_d(double x)\n  {\n    return ZeroSqrt(x);\n  }\n}\n\ntemplate <typename Derived>\nDerived ZeroSqrt(const Eigen::ArrayBase<Derived>& m)\n{\n   return m.unaryExpr(std::ptr_fun(ZeroSqrt_d));\n}\n\n}\n\n#endif\n", "meta": {"hexsha": "e66b703c434c64e84f6c5c8329ca1bdf57264005", "size": 15864, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/wrappers.hpp", "max_stars_repo_name": "aaronvincent/gambit_aaron", "max_stars_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/src/wrappers.hpp", "max_issues_repo_name": "aaronvincent/gambit_aaron", "max_issues_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/src/wrappers.hpp", "max_forks_repo_name": "aaronvincent/gambit_aaron", "max_forks_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5022222222, "max_line_length": 96, "alphanum_fraction": 0.6313035804, "num_tokens": 4263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.44424403591866607}}
{"text": "// Pulse clas implimentation\n// standard includes\n#include <cmath>\n#include <iterator>\n\n\n// my headers\n#include <Pulse.hpp>\n#include <boost/math/interpolators/barycentric_rational.hpp>\n#include <fftw3.h>\n#include <algorithm>\n#include <Constants.hpp>\n#include <boost/lexical_cast.hpp>\n#include <DataOps.hpp>\n#include <random>\n#include <cassert>\n#include <cstdint> // for appendwavelegth() and int32_t\n\nusing namespace Constants;\nusing namespace DataOps;\n\nPulseFreq::PulseFreq(const double omcenter_in=(0.55*fsPau<double>()),const double omwidth_in=(0.15*fsPau<double>()),const double omonoff_in=(0.1*fsPau<double>()), double tspan_in=(10000.0/fsPau<double>())):\n\tomega_center(omcenter_in),\n\tomega_width(omwidth_in ),\n\tomega_high( std::max(4.0*(omcenter_in + omwidth_in),10.0*omcenter_in) ),\n\tdomega( 2.0*pi<double>()/tspan_in),\n\tintime(false),\n\tinfreq(true),\n\tm_noisescale(1e-3),\n\tm_sampleinterval(2),\n\tm_saturate(4096),\n\tm_gain(1000000),\n\tm_lamsamples(1024),\n\tsampleround(1000),\n\tcvec(NULL),\n\tr_vec(NULL),\n\thc_vecFT(NULL),\n\tr_vec_2x(NULL),\n\thc_vec_2xFT(NULL)\n{\n\tstd::cout << \"In constructor PulseFreq()\" << std::endl;\n\ti_low =  (unsigned)(double( atof( getenv(\"nu_low\") ) )* twopi<double>()*fsPau<double>()/domega);\n\ti_high =  (unsigned)(double( atof( getenv(\"nu_high\") ) )* twopi<double>()*fsPau<double>()/domega);\n\tsamples = (( (unsigned)(2.0 * omega_high / domega))/sampleround + 1 ) *sampleround;// dt ~ .1fs, Dt ~ 10000fs, dom = 2*pi/1e4, omhigh = 2*pi/.1fs, samples = omhigh/dom*2\n\tdtime = tspan_in/double(samples);\n\tomega_onwidth = omega_offwidth = omega_width/2.0; // forcing sin2 gaussian spectrum\n\tbuildvectors(samples);\n\tnu0=omcenter_in/(2.0*pi<double>())*fsPau<double>();\n\tphase_GDD=phase_TOD=phase_4th=phase_5th=0.0;\n\tm_lamsamples = (size_t)atoi(getenv(\"lamsamples\"));\n\tm_gain = boost::lexical_cast<float>( getenv(\"gain\"));\n\tm_noisescale = boost::lexical_cast<double>( getenv(\"noisescale\") ) ;\n\tm_sampleinterval = boost::lexical_cast<size_t>(getenv(\"sampleinterval\"));\n\tm_saturate = uint16_t( boost::lexical_cast<int>( getenv(\"saturate\")));\n\tstd::cout << \"exiting constructor PulseFreq()\" << std::endl;\n}\n\n\nPulseFreq::PulseFreq(const PulseFreq &rhs) // deep-ish copy constructor\n\t:samples(rhs.samples)\n\t,omega_center(rhs.omega_center)\n\t,omega_width(rhs.omega_width)\n\t,omega_high(rhs.omega_high)\n\t,omega_onwidth(rhs.omega_onwidth)\n\t,domega(rhs.domega)\n\t,intime(rhs.intime)\n\t,infreq(rhs.infreq)\n\t,i_low(rhs.i_low) \n\t,i_high(rhs.i_high)\n\t,m_noisescale(rhs.m_noisescale)\n\t,m_sampleinterval(rhs.m_sampleinterval)\n\t,m_saturate(rhs.m_saturate)\n\t,m_gain(rhs.m_gain)\n\t,m_lamsamples(rhs.m_lamsamples)\n\t,sampleround(1000)\n{\n\t//std::cerr << \"\\t\\t\\t+++++  Copy constructor of PulseFreq::PulseFreq(PulseFreq &rhs)\\n\\t\\tsamples = \" << samples << \"\\n\" << std::flush;\n\tDataOps::clone(omega,rhs.omega);\n\tDataOps::clone(time,rhs.time);\n\n\tstartind = rhs.startind;stopind=rhs.stopind;onwidth=rhs.onwidth;offwidth=rhs.offwidth;\n\ttspan = rhs.tspan;\n\tlambda_center=rhs.lambda_center;lambda_width=rhs.lambda_width;\n\tphase_GDD=rhs.phase_GDD;phase_TOD=rhs.phase_TOD;phase_4th=rhs.phase_4th;phase_5th=rhs.phase_5th;\n\n\tdtime = rhs.dtime;time_center=rhs.time_center;time_wdith=rhs.time_wdith;\n\n\n\tnu0=rhs.nu0;\n\tFTplan_forwardPtr = rhs.FTplan_forwardPtr; \n\tFTplan_backwardPtr = rhs.FTplan_backwardPtr; \n\tbuildvectors(samples);\n\n\tDataOps::clone(rhovec,rhs.rhovec);\n\tDataOps::clone(phivec,rhs.phivec);\n\tDataOps::clone(cvec,rhs.cvec,samples);\n\tDataOps::clone(r_vec,rhs.r_vec,samples);\n\tDataOps::clone(hc_vecFT,rhs.hc_vecFT,samples);\n\tDataOps::clone(r_vec_2x,rhs.r_vec_2x,2*samples);\n\tDataOps::clone(hc_vec_2xFT,rhs.hc_vec_2xFT,2*samples);\n\n\tDataOps::clone(modamp,rhs.modamp);\n\tDataOps::clone(modphase,rhs.modphase);\n}\n\nPulseFreq & PulseFreq::operator=(const PulseFreq & rhs) // shallow-ish assignment\n{\n\t//std::cerr << \"\\n\\n\\t\\t########### !!!!!!! copying into a PulseFreq, make sure same enumber of samples !!!!!! ##########\\n\\n\" << std::flush;\n\t//std::cerr << \"\\t\\t\\t+++++  assignment copy of PulseFreq::operator= with \" << samples << \" samples and \" << rhs.getsamples() << \" on rhs \\n\" << std::flush;\n\tsamples=rhs.samples;\n\tomega_center=rhs.omega_center;\n\tomega_width=rhs.omega_width;\n\tomega_high=rhs.omega_high;\n\tomega_onwidth=rhs.omega_onwidth;\n\tdomega=rhs.domega;\n\tintime=rhs.intime;\n\tinfreq=rhs.infreq;\n\tomega=rhs.omega; // these are static vectors... i'm trying not to make copies just yet\n\ttime=rhs.time; // these are static vectors... i'm trying not to make copies just yet\n\ti_low=rhs.i_low; \n\ti_high=rhs.i_high; \n\tm_noisescale=rhs.m_noisescale;\n\tm_sampleinterval=rhs.m_sampleinterval;\n\tm_saturate=rhs.m_saturate;\n\tm_gain=rhs.m_gain;\n\tm_lamsamples=rhs.m_lamsamples;\n\n\tstartind = rhs.startind;stopind=rhs.stopind;onwidth=rhs.onwidth;offwidth=rhs.offwidth;\n\ttspan = rhs.tspan;\n\tlambda_center=rhs.lambda_center;lambda_width=rhs.lambda_width;\n\tphase_GDD=rhs.phase_GDD;phase_TOD=rhs.phase_TOD;phase_4th=rhs.phase_4th;phase_5th=rhs.phase_5th;\n\n\tdtime = rhs.dtime;time_center=rhs.time_center;time_wdith=rhs.time_wdith;\n\n\tnu0=rhs.nu0;\n\tFTplan_forwardPtr = rhs.FTplan_forwardPtr; \n\tFTplan_backwardPtr = rhs.FTplan_backwardPtr; \n\n\tDataOps::clone(rhovec,rhs.rhovec);\n\tDataOps::clone(phivec,rhs.phivec);\n\tDataOps::clone(cvec,rhs.cvec,samples);\n\tDataOps::clone(r_vec,rhs.r_vec,samples);\n\tDataOps::clone(hc_vecFT,rhs.hc_vecFT,samples);\n\tDataOps::clone(r_vec_2x,rhs.r_vec_2x,2*samples);\n\tDataOps::clone(hc_vec_2xFT,rhs.hc_vec_2xFT,2*samples);\n\n\tDataOps::clone(modamp,rhs.modamp);\n\tDataOps::clone(modphase,rhs.modphase);\n\treturn *this;\n}\n\nPulseFreq::~PulseFreq(void){\n\tkillvectors();\n}\n\n\nvoid PulseFreq::rhophi2cvec(void)\n{\n\tfor (size_t i=0;i<samples;i++){\n\t\tcvec[i] = std::polar(rhovec[i],phivec[i]);\n\t}\n}\nvoid PulseFreq::cvec2rhophi(void)\n{\n\tfor (size_t i=0;i<samples;i++){\n\t\trhovec[i] = std::abs(cvec[i]);\n\t\tphivec[i] = std::arg(cvec[i]);\n\t}\n}\n\nPulseFreq & PulseFreq::operator+=(const PulseFreq &rhs){\n\tDataOps::sum(cvec,rhs.cvec,samples);\n\tcvec2rhophi();\n\treturn *this;\n}\n\nPulseFreq & PulseFreq::operator-=(const PulseFreq &rhs){\n\tDataOps::diff(cvec,rhs.cvec,samples);\n\tcvec2rhophi();\n        return *this;\n}\n\nPulseFreq & PulseFreq::operator*=(const PulseFreq &rhs){\n\tDataOps::mul(cvec,rhs.cvec,samples);\n\tcvec2rhophi();\n\treturn *this;\n}\n\nPulseFreq & PulseFreq::operator*=(const double s){\n\tDataOps::mul(cvec,s,samples);\n\tcvec2rhophi();\n\treturn *this;\n}\n\nPulseFreq & PulseFreq::operator/=(const PulseFreq &rhs){\n\tDataOps::div(cvec,rhs.cvec,samples);\n\tcvec2rhophi();\n        return *this;\n}\n\nPulseFreq & PulseFreq::interfere(const PulseFreq &rhs){\n\t*this += rhs;\n        return *this;\n}\n\nPulseFreq & PulseFreq::diffamps(const PulseFreq &rhs){\n\trhovec -= rhs.rhovec;\n\tstd::fill(phivec.begin(),phivec.end(),0);\n\trhophi2cvec();\n        return *this;\n}\n\nPulseFreq & PulseFreq::normamps(const PulseFreq &rhs){\n\trhovec /= rhs.rhovec;\n\tstd::fill(phivec.begin(),phivec.end(),0);\n\trhophi2cvec();\n        return *this;\n}\n\nvoid PulseFreq::print_amp(std::ofstream & outfile)\n{\n\toutfile << \"# amp\\n\";\n\toutfile << rhovec << std::endl;\n}\nvoid PulseFreq::print_phase(std::ofstream & outfile)\n{\n\toutfile << \"# phase\\n\";\n\toutfile << phivec << std::endl;\n}\nvoid PulseFreq::print_phase_powerspectrum(std::ofstream & outfile)\n{\n/*\n\tdouble * phase = (double *) fftw_malloc(sizeof(double) * samples);\n\tdouble * phaseFT = (double *) fftw_malloc(sizeof(double) * samples);\n\tfftw_plan plan_r2hc = fftw_plan_r2r_1d(samples,\n\t\t\tphase,\n\t\t\tphaseFT,\n\t\t\tFFTW_R2HC,\n\t\t\tFFTW_MEASURE\n\t\t\t);\n*/\n\tstd::copy(phivec.begin(),phivec.end(),r_vec);\n\tfftw_execute_r2r(*FTplan_r2hcPtr.get(),r_vec,hc_vecFT);\n\t\n\n\toutfile << \"# power spectrum of the Fourier phase\\n\";\n\toutfile << std::pow(hc_vecFT[0],int(2)) << \"\\n\";\n\tfor (size_t i = 1; i<samples/2;++i){\n\t\toutfile << std::pow(hc_vecFT[i],int(2)) + std::pow(hc_vecFT[samples-i],int(2)) << \"\\n\";\n\t}\n\toutfile << std::pow(hc_vecFT[samples/2],int(2)) << std::endl;\n\toutfile << std::endl;\n}\n\nbool PulseFreq::addrandomphase(void)\n{\n\tif (!infreq){\n\t\tstd::cerr << \"died here at addrandomphase()\" << std::endl;\n\t\treturn false;\n\t}\n\tsize_t sz = samples*2; // doubling the vector to mirror it so that DFT hansles the phase well\n\n\tdouble * randphase = (double *) fftw_malloc(sizeof(double) * sz);\n\tdouble * randphaseFT = (double *) fftw_malloc(sizeof(double) * sz);\n/*\n\n\tfftw_plan plan_r2hc = fftw_plan_r2r_1d(sz,\n\t\t\trandphase,\n\t\t\trandphaseFT,\n\t\t\tFFTW_R2HC,\n\t\t\tFFTW_MEASURE\n\t\t\t);\n\tfftw_plan plan_hc2r = fftw_plan_r2r_1d(sz,\n\t\t\trandphaseFT,\n\t\t\trandphase,\n\t\t\tFFTW_HC2R,\n\t\t\tFFTW_MEASURE\n\t\t\t);\n\n*/\n\n\n\tstd::uniform_real_distribution<double> distribution(\n\t\t(double(atof(getenv(\"randphase_mean\")))-double(atof(getenv(\"randphase_std\"))))*Constants::pi<double>(),\n\t\t(double(atof(getenv(\"randphase_mean\")))+double(atof(getenv(\"randphase_std\"))))*Constants::pi<double>()\n\t\t);\n\n\tdouble phase = distribution(rng);\n\trandphase[0] = phase;\n\trandphase[samples/2] = -phase;\n\tfor (size_t i = 1; i<samples/2;i++){\n\t\tphase = distribution(rng);\n\t\trandphase[i] = phase;\n\t\trandphase[samples-i] = -phase;\n\t}\n\tfor (size_t i=sz-1;i>sz/2-1;--i){\n\t\trandphase[i] = randphase[sz-i];\n\t}\n\n\tsize_t lowpass = boost::lexical_cast<size_t>(atoi(getenv(\"phaseNoiseLowpass\")));\n\tstd::cerr << \"\\n======== lowpass is \" << lowpass << \" =======\\n\" << std::flush;\n\n\tfftw_execute_r2r(*FTplan_r2hc_2xPtr.get(),randphase,randphaseFT);\n\tstd::fill(randphaseFT+lowpass,randphaseFT+sz-lowpass,0.);\n\tfor (size_t i=1;i<lowpass;++i){\n\t\tdouble filter = std::pow(std::cos(double(i)/(double(lowpass)) * Constants::half_pi<double>() ),int(2));\n\t\trandphaseFT[i] *= filter;\n\t\trandphaseFT[sz-i] *= filter;\n\t}\n\trandphaseFT[sz/2] = 0.;\n\tfftw_execute_r2r(*FTplan_hc2r_2xPtr.get(),randphaseFT,randphase);\n\n\tfor (size_t i=0;i<samples;++i){\n\t\tphivec[i] += randphase[i]/samples;\n\t}\n\trhophi2cvec();\n\treturn true;\n}\n\n\nvoid PulseTime::setstrength(const double in)\n{\n  strength = in * auenergy<double>()/Eh<double>() * std::pow(aufor10PW<double>(),int(2));\n}\n\nvoid PulseTime::setwidth(const double in)\n{\n  Ctau = in * Constants::root_pi<double>()/ Constants::fsPau<double>() / 2.0;\n}\n\nvoid PulseTime::sett0(const double in)\n{\n  t0 = in / fsPau<double>();\n}\n\nvoid PulseFreq::attenuate(double attenfactor){\n\trhovec *= attenfactor;\n\trhophi2cvec();\n}\nvoid PulseFreq::phase(double phasein){ // expects delay in units of pi , i.e. 1.0 = pi phase flip \n\tif(intime){\n\t\tfft_tofreq();\n\t}\n\tphivec += phasein*Constants::pi<double>();\n\trhophi2cvec();\n\tif(intime){\n\t\tfft_totime();\n\t}\n}\nvoid PulseFreq::delay(double delayin){ // expects delay in fs\n\tif(intime){\n\t\tfft_tofreq();\n\t}\n\tfor (unsigned i=0;i<samples;i++){\n\t\tphivec[i] += omega[i]*delayin/fsPau<double>();\n\t}\n\trhophi2cvec();\n\tif(intime){\n\t\tfft_totime();\n\t}\n}\n\n\nvoid PulseFreq::printfrequency(std::ofstream * outfile){\n\tdouble nu,lambda;\n\t(*outfile) << (\"#omega[fs^-1]\\tlambda[nm]\\trho\\tphi\\n\");\n\tfor (unsigned i = i_low;i<i_high;i+=(unsigned)(atoi(getenv(\"sampleinterval\")))){\n\t\tnu = (omega[i]/(2.0*pi<double>())/fsPau<double>());\n\t\tlambda = C_nmPfs<double>()/nu;\n\t\t(*outfile) << nu << \"\\t\" << lambda << \"\\t\" << std::pow(rhovec[i],int(2)) << \"\\t\" << phivec[i] << \"\\n\";\n\t}\n}\nvoid PulseFreq::printwavelengthbins(std::ofstream * outfile)\n{\n\tstd::vector<double> x(2);\n\tx.front() = C_nmPfs<double>()*2.0*pi<double>()*fsPau<double>()/omega[i_low];\n\tx.back() = C_nmPfs<double>()*2.0*pi<double>()*fsPau<double>()/omega[i_high-1];\n\tdouble dlam = (x.front()-x.back())/double(m_lamsamples);\n        for (size_t i = 0;i<m_lamsamples;++i){\n\t\t(*outfile) << x.back() + i*dlam << \"\\t\";\n        }\n\t(*outfile) << \"\\n\";\n\treturn;\n}\nvoid PulseFreq::appendwavelength(std::ofstream * outfile)\n{\n\tstd::vector<double> x(i_high-i_low);\n\tstd::vector<double> y(i_high-i_low);\t\n\tfor (size_t i=0;i<y.size();++i){\n\t\tx[i] = C_nmPfs<double>()*2.0*pi<double>()*fsPau<double>()/omega[i_low+i];\n\t\t//y[i] = std::pow(rhovec[i_low+i],int(2)) * 200000000000;\n\t\ty[i] = std::min(std::pow(rhovec[i_low+i],int(2)) * m_gain,double(m_saturate));\n\t}\n\tdouble dlam = (x.front()-x.back())/double(m_lamsamples);\n\tboost::math::barycentric_rational<double> interpolant(x.data(), y.data(), y.size());\n\tfor (size_t i=0;i<m_lamsamples;++i){\n\t\t(*outfile) << uint16_t(interpolant(x.back()+i*dlam)) << \"\\t\";\n\t}\n\t(*outfile) << std::endl;\n\treturn;\n}\nvoid PulseFreq::appendwavelength_bin(std::ofstream * outfile)\n{\n\tstd::vector<double> x(i_high-i_low);\n\tstd::vector<double> y(i_high-i_low);\t\n\tfor (size_t i=0;i<y.size();++i){\n\t\tx[i] = C_nmPfs<double>()*2.0*pi<double>()*fsPau<double>()/omega[i_low+i];\n\t\t//y[i] = std::pow(rhovec[i_low+i],int(2)) * 200000000000;\n\t\ty[i] = std::min(std::pow(rhovec[i_low+i],int(2)) * m_gain,double(m_saturate));\n\t}\n\tdouble dlam = (x.front()-x.back())/double(m_lamsamples);\n\tboost::math::barycentric_rational<double> interpolant(x.data(), y.data(), y.size());\n\tfor (size_t i=0;i<m_lamsamples;++i){\n\t\t(*outfile) << int32_t(interpolant(x.back()+i*dlam));\n\t}\n\treturn;\n}\nvoid PulseFreq::appendfrequency(std::ofstream * outfile){\n        for (unsigned i = i_low;i<i_high;i+=m_sampleinterval){ \n\t\tuint16_t val = std::min(uint16_t(rhovec[i] * m_gain),uint16_t(m_saturate));\n       \t\t(*outfile) << std::pow(val,int(2)) << \"\\t\";\n        }\n\t(*outfile) << std::endl;\n}\n\nvoid PulseFreq::appendnoisy(std::ofstream * outfile){\n\tstd::normal_distribution<double> norm_dist( 0.0, m_noisescale);\n        for (unsigned i = i_low;i<i_high;i+=m_sampleinterval){ \n\t\tdouble outval = std::pow(rhovec[i],int(2)) + norm_dist(rng);\n       \t\t(*outfile) << outval << \"\\t\" ;\n        }\n\t(*outfile) << std::endl;\n}\n\nvoid PulseFreq::printfrequencybins(std::ofstream * outfile){\n\tdouble nu,lam;\n        for (unsigned i = i_low;i<i_high;i+=(unsigned)(atoi(getenv(\"sampleinterval\")))){\n\t\tnu = (omega[i]/(2.0*pi<double>())/fsPau<double>());\n\t\tlam = C_nmPfs<double>()/nu;\n       \t\t(*outfile) << nu << \"\\t\" << lam << \"\\n\";\n        }\n\t(*outfile) << \"\\n\";\n}\nvoid PulseFreq::appendfrequencybins(std::ofstream * outfile){\n\tdouble nu,lam;\n        for (unsigned i = i_low;i<i_high;i+=(unsigned)(atoi(getenv(\"sampleinterval\")))){\n\t\tnu = (omega[i]/(2.0*pi<double>())/fsPau<double>());\n       \t\t(*outfile) << nu << \"\\t\";\n        }\n\t(*outfile) << \"\\n\";\n}\nvoid PulseFreq::printfrequencydelay(std::ofstream * outfile, const double *delay){\n\tdouble nu,lambda,thisdelay;\n\tthisdelay = (*delay)*fsPau<double>();\n\t(*outfile) << (\"#omega[fs^-1]\\tlambda[nm]\\trho\\tphi\\tdelay[fs]\\n\");\n\tfor (unsigned i = i_low;i<i_high;i+=(unsigned)(atoi(getenv(\"sampleinterval\")))){\n\t\tnu = (omega[i]/(2.0*pi<double>())/fsPau<double>());\n\t\tlambda = C_nmPfs<double>()/nu;\n\t\t(*outfile) << nu << \"\\t\" << lambda << \"\\t\" << rhovec[i] << \"\\t\" << phivec[i] << \"\\t\" << thisdelay << \"\\n\";\n\t}\n\t(*outfile) << \"\\n\";\n}\nvoid PulseFreq::printfrequencydelaychirp(std::ofstream * outfile, const double *delay,const double *chirp){\n\tdouble nu,lambda,thisdelay,thischirp,reltime;\n\tthisdelay = (*delay)*fsPau<double>();\n\tthischirp = (*chirp)*std::pow(fsPau<double>(),int(2));\n\t(*outfile) << (\"#omega[fs^-1]\\tlambda[nm]\\trho\\tphi\\tdelay[fs]\\tchirp[fs^2]\\treldelays[fs]\\n\");\n\tfor (unsigned i = i_low;i<i_high;i+=(unsigned)(atoi(getenv(\"sampleinterval\")))){\n\t\tnu = (omega[i]/(2.0*pi<double>())/fsPau<double>());\n\t\tlambda = C_nmPfs<double>()/nu;\n\t\treltime = (nu-nu0)*thischirp*10.0;\n\t\t(*outfile) << nu << \"\\t\" << lambda << \"\\t\" << rhovec[i] << \"\\t\" << phivec[i] << \"\\t\" << thisdelay << \"\\t\" << thischirp << \"\\t\" << reltime << \"\\n\";\n\t}\n\t(*outfile) << \"\\n\";\n}\n\nvoid PulseFreq::printwavelength(std::ofstream * outfile,const double *delay){\n\tdouble nu,lambda,lamlast;\n\tlamlast=0;\n        for (unsigned i = i_high;i>i_low;i-=(unsigned)(atoi(getenv(\"sampleinterval\")))){\n                nu = (omega[i]/(2.0*pi<double>())/fsPau<double>());\n                lambda = (double)((int)((C_nmPfs<double>()/nu)*10.0))/10.0;\n\t\tif (lambda>lamlast & (int)(lambda*10)%5 == 0){\n                \t(*outfile) << lambda << \"\\t\" << (*delay) << \"\\t\" << std::pow(rhovec[i],int(2)) << \"\\n\";\n\t\t\tlamlast = lambda;\n\t\t}\n        }\n\t(*outfile) << \"\\n\";\n}\n\nvoid PulseFreq::printtime(std::ofstream * outfile){\n\t(*outfile) << (\"#time\\treal\\timag\\n\");\n\tfor (unsigned i = samples/2;i<samples;i++){\n\t\t(*outfile) << (time[i]*fsPau<double>()) << \"\\t\" << cvec[i].real() << \"\\t\" << cvec[i].imag() << \"\\n\";\n\t}\n\tfor (unsigned i = 0;i<samples/2;i++){\n\t\t(*outfile) << (time[i]*fsPau<double>()) << \"\\t\" << cvec[i].real() << \"\\t\" << cvec[i].imag() << \"\\n\";\n\t}\n\n} \n\n\nvoid PulseFreq::buildvectors(const size_t s){\n\t//std::cerr << \"allocating with fftw_malloc with samples = \" << samples << std::endl;\n\tcvec = (std::complex<double> *) fftw_malloc(sizeof(std::complex<double>) * size_t(s));\n        std::fill(cvec,cvec + samples,std::complex<double>(0));\n\tr_vec = (double *) fftw_malloc(sizeof(double) * size_t(s));\n        std::fill(r_vec,r_vec + s,double(0));\n\t//std::cerr << \"\\t\\t...allocated with fftw_malloc with samples = \" << samples << std::endl;\n\thc_vecFT = (double *) fftw_malloc(sizeof(double) * size_t(s));\n        std::fill(hc_vecFT,hc_vecFT + s,double(0));\n\t//std::cerr << \"allocating with fftw_malloc with samples = \" << (2*samples) << std::endl;\n\tr_vec_2x = (double *) fftw_malloc(sizeof(double) * size_t(s) * 2);\n        //std::fill(r_vec_2x,r_vec_2x + 2*samples,double(0));\n\thc_vec_2xFT = (double *) fftw_malloc(sizeof(double) * size_t(s) * 2);\n        std::fill(hc_vec_2xFT,hc_vec_2xFT + 2*s,double(0));\n\t//std::cerr << \"\\t\\t...allocated with fftw_malloc with 2*samples = \" << (2*samples) << std::endl;\n\n\trhovec.resize(s,0.0);\n\tphivec.resize(s,0.0);\n\tmodamp.resize(s,1.0);\n\tmodphase.resize(s,0.0);\n\tomega.resize(s);\n\ttime.resize(s);\n\n\tomega[0] = 0.0;\n\ttime[0] = 0.0;\n\tomega[s/2] = -(double)(s/2)*domega;\n\ttime[s/2] = -(double)(s/2)*dtime;\n\n\tstartind = (unsigned)((omega_center-(omega_width/2.0))/domega);\n\tstopind = (unsigned)((omega_center+(omega_width/2.0))/domega);\n\tonwidth = (unsigned)(omega_onwidth/domega); // 2.0)/domega);//  /10.0)/domega);// sin^2 goes from0..1 in 0..pi/2\n\toffwidth = (unsigned)(omega_offwidth/domega); // 2.0)/domega);//  /10.0)/domega);// sin^2 goes from0..1 in 0..pi/2\n\tfor (unsigned i = 1; i<startind;i++){\n\t\tomega[i] = domega*i;\n\t\ttime[i] = dtime*i;\n\t\tomega[samples-i] = -domega*i;\n\t\ttime[samples-i] = -dtime*i;\n\t}\n\tfor (unsigned i = startind;i<startind+onwidth; i++){\n\t\tomega[i] = domega*i;\n\t\ttime[i] = dtime*i;\n\t\trhovec[i] = rising(i);\n\t\tcvec[i] = std::polar(rhovec[i],phivec[i]);\n\t\tomega[s-i] = -domega*(double)i;\n\t\ttime[s-i] = -dtime*(double)i;\n\t\trhovec[s-i] = rising(i);\n\t\tcvec[s-i] = std::polar(rhovec[s-i],phivec[s-i]);\n\t}\n\tfor (unsigned i = startind+onwidth;i<stopind-offwidth; i++){\n\t\tomega[i] = domega*i;\n\t\ttime[i] = dtime*i;\n\t\trhovec[i] = 1.0;\n\t\tcvec[i] = std::polar(rhovec[i],phivec[i]);\n\t\tomega[s-i] = -domega*(double)i;\n\t\ttime[s-i] = -dtime*(double)i;\n\t\trhovec[s-i] = 1.0;\n\t\tcvec[s-i] = std::polar(rhovec[s-i],phivec[s-i]);\n\t}\n\tfor (unsigned i = stopind-offwidth;i<stopind; i++){\n\t\tomega[i] = domega*i;\n\t\ttime[i] = dtime*i;\n\t\trhovec[i] = falling(i);\n\t\tcvec[i] = std::polar(rhovec[i],phivec[i]);\n\t\tomega[s-i] = -domega*i;\n\t\ttime[s-i] = -dtime*i;\n\t\trhovec[s-i] = falling(i);\n\t\tcvec[s- i] = std::polar(rhovec[s- i],phivec[s- i]);\n\t}\n\tfor (unsigned i = stopind;i<s/2; i++){\n\t\tomega[i] = domega*i;\n\t\ttime[i] = dtime*i;\n\t\tomega[s-i] = -domega*i;\n\t\ttime[s-i] = -dtime*i;\n\t}\n\t\n}\nvoid PulseFreq::killvectors(void){\n\tfftw_free(cvec);\n\tfftw_free(r_vec);\n\tfftw_free(hc_vecFT);\n\tfftw_free(r_vec_2x);\n\tfftw_free(hc_vec_2xFT);\n\tcvec = NULL;\n\tr_vec = hc_vecFT = r_vec_2x = hc_vec_2xFT = NULL;\n}\n\nvoid PulseFreq::setplans(const PulseFreq & rhs)\n{\n\tFTplan_forwardPtr = rhs.FTplan_forwardPtr;\n\tFTplan_backwardPtr = rhs.FTplan_backwardPtr;\n}\nvoid PulseFreq::setmasterplans(fftw_plan * const forward,fftw_plan * const backward)\n{\n\tassert(FTplan_forwardPtr.use_count()==0 && FTplan_backwardPtr.use_count()==0);\n\t*forward = fftw_plan_dft_1d(samples, \n\t\t\treinterpret_cast<fftw_complex*>(cvec),\n\t\t\treinterpret_cast<fftw_complex*>(cvec), \n\t\t\tFFTW_FORWARD, FFTW_ESTIMATE);\n\t*backward = fftw_plan_dft_1d(samples, \n\t\t\treinterpret_cast<fftw_complex*>(cvec), \n\t\t\treinterpret_cast<fftw_complex*>(cvec), \n\t\t\tFFTW_BACKWARD, FFTW_ESTIMATE);\n\tFTplan_forwardPtr = std::make_shared<fftw_plan> (*forward);\n\tFTplan_backwardPtr = std::make_shared<fftw_plan> (*backward);\n}\nvoid PulseFreq::setancillaryplans(fftw_plan * const r2hc,fftw_plan * const hc2r,fftw_plan * const r2hc_2x,fftw_plan * const hc2r_2x)\n{\n\n\tassert(FTplan_r2hcPtr.use_count()==0\n\t\t\t&& FTplan_hc2rPtr.use_count()==0\n\t\t\t&& FTplan_r2hc_2xPtr.use_count()==0\n\t\t\t&& FTplan_hc2r_2xPtr.use_count()==0);\n\t*r2hc = fftw_plan_r2r_1d(samples,\n\t\t\tr_vec,\n\t\t\thc_vecFT,\n\t\t\tFFTW_R2HC,\n\t\t\tFFTW_MEASURE\n\t\t\t);\n\t*hc2r = fftw_plan_r2r_1d(samples,\n\t\t\thc_vecFT,\n\t\t\tr_vec,\n\t\t\tFFTW_HC2R,\n\t\t\tFFTW_MEASURE\n\t\t\t);\n\t*r2hc_2x = fftw_plan_r2r_1d(2*samples,\n\t\t\tr_vec_2x,\n\t\t\thc_vec_2xFT,\n\t\t\tFFTW_R2HC,\n\t\t\tFFTW_MEASURE\n\t\t\t);\n\t*hc2r_2x = fftw_plan_r2r_1d(2*samples,\n\t\t\thc_vec_2xFT,\n\t\t\tr_vec_2x,\n\t\t\tFFTW_HC2R,\n\t\t\tFFTW_MEASURE\n\t\t\t);\n\tFTplan_r2hcPtr = std::make_shared<fftw_plan> (*r2hc);\n\tFTplan_hc2rPtr = std::make_shared<fftw_plan> (*hc2r);\n\tFTplan_r2hc_2xPtr = std::make_shared<fftw_plan> (*r2hc_2x);\n\tFTplan_hc2r_2xPtr = std::make_shared<fftw_plan> (*hc2r_2x);\n\n}\n", "meta": {"hexsha": "e03a469000c5c61cd5bf1a7c081f15b644e82847", "size": 20971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Pulse.cpp", "max_stars_repo_name": "ryancoffee/2dtimetool_simulation", "max_stars_repo_head_hexsha": "4ca4b585f35a04e81111a67c5bf6aaef931ee03c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Pulse.cpp", "max_issues_repo_name": "ryancoffee/2dtimetool_simulation", "max_issues_repo_head_hexsha": "4ca4b585f35a04e81111a67c5bf6aaef931ee03c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Pulse.cpp", "max_forks_repo_name": "ryancoffee/2dtimetool_simulation", "max_forks_repo_head_hexsha": "4ca4b585f35a04e81111a67c5bf6aaef931ee03c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5131782946, "max_line_length": 206, "alphanum_fraction": 0.6667302465, "num_tokens": 7117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4442440290387409}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Jose Aparicio\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifndef quantlib_default_latent_model_hpp\n#define quantlib_default_latent_model_hpp\n\n#include <ql/experimental/credit/basket.hpp>\n#include <ql/experimental/math/latentmodel.hpp>\n#include <ql/experimental/math/gaussiancopulapolicy.hpp>\n#include <boost/dynamic_bitset.hpp>\n\nnamespace QuantLib {\n\n    /*! \\brief Default event Latent Model.\n\n     This is a model for joint default events based on a generic Latent \n      Model. It models solely the default events in a portfolio, not making any \n      reference to severities, exposures, etc...\n     An implicit correspondence is stablished between the variables modelled and\n     the names in the basket given by the basket and model variable access \n     indices.\n     The class is parametric on the Latent Model copula.\n\n     \\todo Consider QL_REQUIRE(basket_, \"No portfolio basket set.\") test in \n     debug model only for performance reasons.\n    */\n    template<class copulaPolicy>\n    class DefaultLatentModel : public LatentModel<copulaPolicy> {\n        // import template members\n    protected:\n        using LatentModel<copulaPolicy>::factorWeights_;\n        using LatentModel<copulaPolicy>::idiosyncFctrs_;\n        using LatentModel<copulaPolicy>::copula_;\n    public:\n        using LatentModel<copulaPolicy>::inverseCumulativeY;\n        using LatentModel<copulaPolicy>::cumulativeZ;\n        using LatentModel<copulaPolicy>::integratedExpectedValue;// which one?\n    protected:\n        // not a handle, the model doesnt keep any cached magnitudes, no need \n        //  for notifications, still...\n        mutable ext::shared_ptr<Basket> basket_;\n        ext::shared_ptr<LMIntegration> integration_;\n    private:\n        typedef typename copulaPolicy::initTraits initTraits;\n    public:\n        /*!\n        @param factorWeights Latent model independent factors weights for each \n            variable.\n        @param integralType Integration type.\n        @param ini Copula initialization if any.\n\n        \\warning Baskets with realized defaults not tested/WIP.\n        */\n        DefaultLatentModel(\n            const std::vector<std::vector<Real> >& factorWeights,\n            LatentModelIntegrationType::LatentModelIntegrationType integralType,\n            const initTraits& ini = initTraits()\n            ) \n        : LatentModel<copulaPolicy>(factorWeights, ini),\n          integration_(LatentModel<copulaPolicy>::IntegrationFactory::\n            createLMIntegration(factorWeights[0].size(), integralType))\n        { }\n        DefaultLatentModel(\n            const Handle<Quote>& mktCorrel,\n            Size nVariables,\n            LatentModelIntegrationType::LatentModelIntegrationType integralType,\n            const initTraits& ini = initTraits()\n            )\n        : LatentModel<copulaPolicy>(mktCorrel, nVariables, ini),\n          integration_(LatentModel<copulaPolicy>::IntegrationFactory::\n            createLMIntegration(1, integralType))\n        { }\n        /* \\todo\n            Add other constructors as in LatentModel for ease of use. (less \n            dimensions, factors, etcc...)\n        */\n\n        /* To interface with loss models. It is possible to change the basket \n        since there are no cached magnitudes.\n        */\n        void resetBasket(const ext::shared_ptr<Basket> basket) const {\n            basket_ = basket;\n            // in the future change 'size' to 'liveSize'\n            QL_REQUIRE(basket_->size() == factorWeights_.size(), \n                \"Incompatible new basket and model sizes.\");\n        }\n    public:\n        /*! Returns the probability of default of a given name conditional on\n        the realization of a given set of values of the model independent\n        factors. The date at which the probability is given is implicit in the\n        probability since theres not other time dependence in this model.\n        @param prob Unconditional probability of default.\n        @param iName desired name.\n        @param mktFactors Value of LM independent factors.\n        \\warning Most often it is preferred to use the method below avoiding the\n        cumulative inversion.\n        */\n        Probability conditionalDefaultProbability(Probability prob, Size iName,\n            const std::vector<Real>& mktFactors) const \n        {\n            // we can be called from the outside (from an integrable loss model)\n            //   but we are called often at integration points. This or\n            //   consider a list of friends.\n        #if defined(QL_EXTRA_SAFETY_CHECKS)\n            QL_REQUIRE(basket_, \"No portfolio basket set.\");\n        #endif\n            /*Avoid redundant call to minimum value inversion (might be \\infty),\n            and this independently of the copula function.\n            */\n            if (prob < 1.e-10) return 0.;// use library macro...\n            return conditionalDefaultProbabilityInvP(\n                inverseCumulativeY(prob, iName), iName, mktFactors);\n        }\n    protected:\n        void update() {\n            if(basket_) basket_->notifyObservers();\n            LatentModel<copulaPolicy>::update();\n        }\n    public:// open since users access it for performance on joint integrations.\n\n        /*! Returns the probability of default of a given name conditional on\n        the realization of a given set of values of the model independent\n        factors. The date at which the probability is given is implicit in the\n        probability since theres not other time dependent in this model.\n        Same intention as above but provides a performance opportunity, if the\n        integration is along the market factors (as usually is) avoids computing\n        the inverse of the probability on each call.\n        @param invCumYProb Inverse cumul of the unconditional probability of \n          default, has to follow the same copula law for results to be coherent\n        @param iName desired name.\n        @param m Value of LM independent factors.\n        */\n        Probability conditionalDefaultProbabilityInvP(Real invCumYProb, \n            Size iName, \n            const std::vector<Real>& m) const {\n            Real sumMs = \n                std::inner_product(factorWeights_[iName].begin(), \n                    factorWeights_[iName].end(), m.begin(), 0.);\n            Real res = cumulativeZ((invCumYProb - sumMs) / \n                    idiosyncFctrs_[iName] );\n            #if defined(QL_EXTRA_SAFETY_CHECKS)\n            QL_REQUIRE (res >= 0. && res <= 1.,\n                        \"conditional probability \" << res << \"out of range\");\n            #endif\n        \n            return res;\n        }\n    protected:\n        /*! Returns the probability of default of a given name conditional on\n        the realization of a given set of values of the model independent\n        factors.\n        @param date The date for the probability of default.\n        @param iName desired name.\n        @param mktFactors Value of LM independent factors.\n\n        Same intention as the above methods. Usage of this one is typically more\n        expensive because most often the date we call this method with\n        repeats itself and with this one the probability can not be cached\n        outside the call.\n        */\n        Probability conditionalDefaultProbability(const Date& date, Size iName,\n            const std::vector<Real>& mktFactors) const \n        {\n            const ext::shared_ptr<Pool>& pool = basket_->pool();\n            Probability pDefUncond =\n                pool->get(pool->names()[iName]).\n                defaultProbability(basket_->defaultKeys()[iName])\n                  ->defaultProbability(date);\n            return conditionalDefaultProbability(pDefUncond, iName, mktFactors);\n        }\n        /*! Conditional default probability product, intermediate step in the \n            correlation calculation.*/\n        Probability condProbProduct(Real invCumYProb1, Real invCumYProb2, \n            Size iName1, Size iName2, \n            const std::vector<Real>& mktFactors) const {\n            return \n                conditionalDefaultProbabilityInvP(invCumYProb1, iName1, \n                    mktFactors) *\n                conditionalDefaultProbabilityInvP(invCumYProb2, iName2, \n                    mktFactors);\n        }\n        //! Conditional probability of n default events or more.\n        // \\todo: check the issuer has not defaulted.\n        Real conditionalProbAtLeastNEvents(Size n, const Date& date,\n            const std::vector<Real>& mktFactors) const;\n        //! access to integration:\n        const ext::shared_ptr<LMIntegration>& \n            integration() const { return integration_; }\n    public:\n        /*! Computes the unconditional probability of default of a given name. \n        Trivial method for testing\n        */\n        Probability probOfDefault(Size iName, const Date& d) const {\n            QL_REQUIRE(basket_, \"No portfolio basket set.\");\n            const ext::shared_ptr<Pool>& pool = basket_->pool();\n            // avoid repeating this in the integration:\n            Probability pUncond = pool->get(pool->names()[iName]).\n                defaultProbability(basket_->defaultKeys()[iName])\n                ->defaultProbability(d);\n            if (pUncond < 1.e-10) return 0.;\n\n            return integratedExpectedValue(\n              ext::function<Real (const std::vector<Real>& v1)>(\n                ext::bind(\n                &DefaultLatentModel<copulaPolicy>\n                    ::conditionalDefaultProbabilityInvP,\n                this,\n                inverseCumulativeY(pUncond, iName),\n                iName, \n                ext::placeholders::_1)\n              ));\n        }\n        /*! Pearsons' default probability correlation. \n            Users should consider specialization on the copula type for specific\n            distributions since that might simplify the integrations, most \n            importantly if this is to be used in calibration of observations for\n            factor coefficients as it is expensive to integrate directly.\n        */\n        Real defaultCorrelation(const Date& d, Size iNamei, Size iNamej) const;\n\n        /*! Returns the probaility of having a given or larger number of \n        defaults in the basket portfolio at a given time.\n        */\n        Probability probAtLeastNEvents(Size n, const Date& date) const {\n            return integratedExpectedValue(\n             ext::function<Real (const std::vector<Real>& v1)>(\n              ext::bind(\n              &DefaultLatentModel<copulaPolicy>::conditionalProbAtLeastNEvents,\n              this,\n              n,\n              ext::cref(date),\n              ext::placeholders::_1)\n             ));\n        }\n    };\n\n\n    //---- Defines -----------------------------------------------------------\n\n    template<class CP>\n    Real DefaultLatentModel<CP>::defaultCorrelation(const Date& d, \n        Size iNamei, Size iNamej) const \n    {\n        QL_REQUIRE(basket_, \"No portfolio basket set.\");\n\n        const ext::shared_ptr<Pool>& pool = basket_->pool();\n        // unconditionals:\n        Probability pi = pool->get(pool->names()[iNamei]).\n            defaultProbability(basket_->defaultKeys()[iNamei])\n            ->defaultProbability(d);\n        Probability pj = pool->get(pool->names()[iNamej]).\n            defaultProbability(basket_->defaultKeys()[iNamej])\n            ->defaultProbability(d);\n        Real pipj = pi * pj;\n        Real invPi = inverseCumulativeY(pi, iNamei);\n        Real invPj = inverseCumulativeY(pj, iNamej);\n        // avoid repetitive calls when i=j?\n        Real E1i1j; // joint default covariance term\n        if(iNamei !=iNamej) {\n            E1i1j = integratedExpectedValue(\n              ext::function<Real (const std::vector<Real>& v1)>(\n                ext::bind(\n                &DefaultLatentModel<CP>::condProbProduct,\n                this, invPi, invPj, iNamei, iNamej,\n                ext::placeholders::_1) ));\n        }else{\n            E1i1j = pi;\n        }\n        return (E1i1j - pipj )/std::sqrt(pipj*(1.-pi)*(1.-pj));\n    }\n\n\n    template<class CP>\n    Real DefaultLatentModel<CP>::conditionalProbAtLeastNEvents(Size n, \n        const Date& date,\n        const std::vector<Real>& mktFactors) const {\n            QL_REQUIRE(basket_, \"No portfolio basket set.\");\n\n            /* \\todo \n            This algorithm traverses all permutations starting form the\n            lowest one. This is inneficient, there shouldnt be any need to \n            go through the invalid ones. Use combinations of n elements.\n\n            See integration in O'Kane for homogeneous ntds.\n            */\n            // first position with as many defaults as desired:\n            Size poolSize = basket_->size();//move to 'livesize'\n            const ext::shared_ptr<Pool>& pool = basket_->pool();\n\n            BigNatural limit = \n                static_cast<BigNatural>(std::pow(2., (int)(poolSize)));\n\n            // Precalc conditional probabilities\n            std::vector<Probability> pDefCond;\n            for(Size i=0; i<poolSize; i++)\n                pDefCond.push_back(conditionalDefaultProbability(\n                    pool->get(pool->names()[i]).\n                    defaultProbability(basket_->defaultKeys()[i])->\n                    defaultProbability(date), i, mktFactors));\n\n            Probability probNEventsOrMore = 0.;\n            for(BigNatural mask = \n                  static_cast<BigNatural>(std::pow(2., (int)(n))-1);\n                mask < limit; mask++) \n            {\n                // cheap permutations\n                boost::dynamic_bitset<> bsetMask(poolSize, mask);\n                if(bsetMask.count() >= n) {\n                    Probability pConfig = 1;\n                    for(Size i=0; i<bsetMask.size(); i++)\n                        pConfig *= \n                          (bsetMask[i] ? pDefCond[i] : (1.- pDefCond[i]));\n                    probNEventsOrMore += pConfig;\n                }\n            }\n            return probNEventsOrMore;\n        }\n\n\n    // often used:\n    typedef DefaultLatentModel<GaussianCopulaPolicy> GaussianDefProbLM;\n    typedef DefaultLatentModel<TCopulaPolicy> TDefProbLM;\n}\n\n#endif\n", "meta": {"hexsha": "17fe480813beee3145f18844522ae1061026367b", "size": 14876, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/credit/defaultprobabilitylatentmodel.hpp", "max_stars_repo_name": "j053g/QuantLib", "max_stars_repo_head_hexsha": "86869ef7429ce1a975c9e0ef15a69a9a3db8e0f4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-30T17:51:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-30T17:51:09.000Z", "max_issues_repo_path": "ql/experimental/credit/defaultprobabilitylatentmodel.hpp", "max_issues_repo_name": "j053g/QuantLib", "max_issues_repo_head_hexsha": "86869ef7429ce1a975c9e0ef15a69a9a3db8e0f4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T06:35:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:00:09.000Z", "max_forks_repo_path": "ql/experimental/credit/defaultprobabilitylatentmodel.hpp", "max_forks_repo_name": "j053g/QuantLib", "max_forks_repo_head_hexsha": "86869ef7429ce1a975c9e0ef15a69a9a3db8e0f4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-04T15:19:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T08:24:37.000Z", "avg_line_length": 43.4970760234, "max_line_length": 80, "alphanum_fraction": 0.6164291476, "num_tokens": 3171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4442373901161655}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_BESSEL_SECOND_KIND_HPP\n#define STAN_MATH_PRIM_FUN_BESSEL_SECOND_KIND_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/functor/apply_scalar_binary.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n *\n   \\f[\n   \\mbox{bessel\\_second\\_kind}(v, x) =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x \\leq 0 \\\\\n     Y_v(x) & \\mbox{if } x > 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{bessel\\_second\\_kind}(v, x)}{\\partial x} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x \\leq 0 \\\\\n     \\frac{\\partial\\, Y_v(x)}{\\partial x} & \\mbox{if } x > 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   Y_v(x)=\\frac{J_v(x)\\cos(v\\pi)-J_{-v}(x)}{\\sin(v\\pi)}\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, Y_v(x)}{\\partial x} = \\frac{v}{x}Y_v(x)-Y_{v+1}(x)\n   \\f]\n *\n */\ntemplate <typename T2, require_arithmetic_t<T2>* = nullptr>\ninline T2 bessel_second_kind(int v, const T2 z) {\n  return boost::math::cyl_neumann(v, z);\n}\n\n/**\n * Enables the vectorised application of the bessel second kind function, when\n * the first and/or second arguments are containers.\n *\n * @tparam T1 type of first input\n * @tparam T2 type of second input\n * @param a First input\n * @param b Second input\n * @return Bessel second kind function applied to the two inputs.\n */\ntemplate <typename T1, typename T2, require_any_container_t<T1, T2>* = nullptr>\ninline auto bessel_second_kind(const T1& a, const T2& b) {\n  return apply_scalar_binary(a, b, [&](const auto& c, const auto& d) {\n    return bessel_second_kind(c, d);\n  });\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "e77b78cbf19b94291f6b9cef80742bedd8d184ad", "size": 1735, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/bessel_second_kind.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "stan/math/prim/fun/bessel_second_kind.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/fun/bessel_second_kind.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 26.2878787879, "max_line_length": 79, "alphanum_fraction": 0.6438040346, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4442373661026417}}
{"text": "// Boost.Geometry\n// This file is manually converted from PROJ4\n\n// This file was modified by Oracle on 2018.\n// Modifications copyright (c) 2018, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// This file was converted to Geometry Library by Adam Wulkiewicz\n\n// Original copyright notice:\n// Author:   Frank Warmerdam, warmerdam@pobox.com\n\n// Copyright (c) 2000, Frank Warmerdam\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#ifndef BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_PJ_APPLY_GRIDSHIFT_HPP\n#define BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_PJ_APPLY_GRIDSHIFT_HPP\n\n\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n\n#include <boost/geometry/srs/projections/impl/pj_gridlist.hpp>\n\n\nnamespace boost { namespace geometry { namespace projections\n{\n\nnamespace detail\n{\n\n// Originally implemented in nad_intr.c\ntemplate <typename CalcT>\ninline void nad_intr(CalcT in_lon, CalcT in_lat,\n                     CalcT & out_lon, CalcT & out_lat,\n                     pj_ctable const& ct)\n{\n\tpj_ctable::lp_t frct;\n\tpj_ctable::ilp_t indx;\n\tboost::int32_t in;\n\n\tindx.lam = int_floor(in_lon /= ct.del.lam);\n\tindx.phi = int_floor(in_lat /= ct.del.phi);\n\tfrct.lam = in_lon - indx.lam;\n\tfrct.phi = in_lat - indx.phi;\n    // TODO: implement differently\n\tout_lon = out_lat = HUGE_VAL;\n\tif (indx.lam < 0) {\n\t\tif (indx.lam == -1 && frct.lam > 0.99999999999) {\n\t\t\t++indx.lam;\n\t\t\tfrct.lam = 0.;\n\t\t} else\n\t\t\treturn;\n\t} else if ((in = indx.lam + 1) >= ct.lim.lam) {\n\t\tif (in == ct.lim.lam && frct.lam < 1e-11) {\n\t\t\t--indx.lam;\n\t\t\tfrct.lam = 1.;\n\t\t} else\n\t\t\treturn;\n\t}\n\tif (indx.phi < 0) {\n\t\tif (indx.phi == -1 && frct.phi > 0.99999999999) {\n\t\t\t++indx.phi;\n\t\t\tfrct.phi = 0.;\n\t\t} else\n\t\t\treturn;\n\t} else if ((in = indx.phi + 1) >= ct.lim.phi) {\n\t\tif (in == ct.lim.phi && frct.phi < 1e-11) {\n\t\t\t--indx.phi;\n\t\t\tfrct.phi = 1.;\n\t\t} else\n\t\t\treturn;\n\t}\n\tboost::int32_t index = indx.phi * ct.lim.lam + indx.lam;\n\tpj_ctable::flp_t const& f00 = ct.cvs[index++];\n\tpj_ctable::flp_t const& f10 = ct.cvs[index];\n\tindex += ct.lim.lam;\n\tpj_ctable::flp_t const& f11 = ct.cvs[index--];\n\tpj_ctable::flp_t const& f01 = ct.cvs[index];\n    CalcT m00, m10, m01, m11;\n\tm11 = m10 = frct.lam;\n\tm00 = m01 = 1. - frct.lam;\n\tm11 *= frct.phi;\n\tm01 *= frct.phi;\n\tfrct.phi = 1. - frct.phi;\n\tm00 *= frct.phi;\n\tm10 *= frct.phi;\n\tout_lon = m00 * f00.lam + m10 * f10.lam +\n\t\t\t  m01 * f01.lam + m11 * f11.lam;\n\tout_lat = m00 * f00.phi + m10 * f10.phi +\n\t\t\t  m01 * f01.phi + m11 * f11.phi;\n}\n\n// Originally implemented in nad_cvt.c\ntemplate <bool Inverse, typename CalcT>\ninline void nad_cvt(CalcT const& in_lon, CalcT const& in_lat,\n                    CalcT & out_lon, CalcT & out_lat,\n                    pj_gi const& gi)\n{\n    static const int max_iterations = 10;\n    static const CalcT tol = 1e-12;\n    static const CalcT toltol = tol * tol;\n    static const CalcT pi = math::pi<CalcT>();\n\n    // horizontal grid expected\n    BOOST_GEOMETRY_ASSERT_MSG(gi.format != pj_gi::gtx,\n        \"Vertical grid cannot be used in horizontal shift.\");\n\n    pj_ctable const& ct = gi.ct;\n\n    // TODO: implement differently\n    if (in_lon == HUGE_VAL)\n    {\n        out_lon = HUGE_VAL;\n        out_lat = HUGE_VAL;\n        return;\n    }\n\n    // normalize input to ll origin\n    pj_ctable::lp_t tb;\n    tb.lam = in_lon - ct.ll.lam;\n    tb.phi = in_lat - ct.ll.phi;\n    tb.lam = adjlon (tb.lam - pi) + pi;\n\n    pj_ctable::lp_t t;\n    nad_intr(tb.lam, tb.phi, t.lam, t.phi, ct);\n    if (t.lam == HUGE_VAL)\n    {\n        out_lon = HUGE_VAL;\n        out_lat = HUGE_VAL;\n        return;\n    }\n\n    if (! Inverse)\n    {\n        out_lon = in_lon - t.lam;\n        out_lat = in_lat - t.phi;\n        return;\n    }\n\n    t.lam = tb.lam + t.lam;\n    t.phi = tb.phi - t.phi;\n\n    int i = max_iterations;\n    pj_ctable::lp_t del, dif;\n    do\n    {\n        nad_intr(t.lam, t.phi, del.lam, del.phi, ct);\n\n        // This case used to return failure, but I have\n        // changed it to return the first order approximation\n        // of the inverse shift.  This avoids cases where the\n        // grid shift *into* this grid came from another grid.\n        // While we aren't returning optimally correct results\n        // I feel a close result in this case is better than\n        // no result.  NFW\n        // To demonstrate use -112.5839956 49.4914451 against\n        // the NTv2 grid shift file from Canada.\n        if (del.lam == HUGE_VAL)\n        {\n            // Inverse grid shift iteration failed, presumably at grid edge. Using first approximation.\n            break;\n        }\n\n        dif.lam = t.lam - del.lam - tb.lam;\n        dif.phi = t.phi + del.phi - tb.phi;\n        t.lam -= dif.lam;\n        t.phi -= dif.phi;\n\n    }\n    while (--i && (dif.lam*dif.lam + dif.phi*dif.phi > toltol)); // prob. slightly faster than hypot()\n\n    if (i==0)\n    {\n        // Inverse grid shift iterator failed to converge.\n        out_lon = HUGE_VAL;\n        out_lat = HUGE_VAL;\n        return;\n    }\n\n    out_lon = adjlon (t.lam + ct.ll.lam);\n    out_lat = t.phi + ct.ll.phi;\n}\n\n\n/************************************************************************/\n/*                             find_grid()                              */\n/*                                                                      */\n/*    Determine which grid is the correct given an input coordinate.    */\n/************************************************************************/\n\n// Originally find_ctable()\n// here divided into grid_disjoint(), find_grid() and load_grid()\n\ntemplate <typename T>\ninline bool grid_disjoint(T const& lam, T const& phi,\n                          pj_ctable const& ct)\n{\n    double epsilon = (fabs(ct.del.phi)+fabs(ct.del.lam))/10000.0;\n    return ct.ll.phi - epsilon > phi\n        || ct.ll.lam - epsilon > lam\n        || (ct.ll.phi + (ct.lim.phi-1) * ct.del.phi + epsilon < phi)\n        || (ct.ll.lam + (ct.lim.lam-1) * ct.del.lam + epsilon < lam);\n}\n\ntemplate <typename T>\ninline pj_gi * find_grid(T const& lam,\n                         T const& phi,\n                         std::vector<pj_gi>::iterator first,\n                         std::vector<pj_gi>::iterator last)\n{\n    pj_gi * gip = NULL;\n\n    for( ; first != last ; ++first )\n    {\n        // skip tables that don't match our point at all.\n        if (! grid_disjoint(lam, phi, first->ct))\n        {\n            // skip vertical grids\n            if (first->format != pj_gi::gtx)\n            {\n                gip = boost::addressof(*first);\n                break;\n            }\n        }\n    }\n\n    // If we didn't find a child then nothing more to do\n    if( gip == NULL )\n        return gip;\n\n    // Otherwise use the child, first checking it's children\n    pj_gi * child = find_grid(lam, phi, first->children.begin(), first->children.end());\n    if (child != NULL)\n        gip = child;\n\n    return gip;\n}\n\ntemplate <typename T>\ninline pj_gi * find_grid(T const& lam,\n                         T const& phi,\n                         pj_gridinfo & grids,\n                         std::vector<std::size_t> const& gridindexes)\n{\n    pj_gi * gip = NULL;\n\n    // keep trying till we find a table that works\n    for (std::size_t i = 0 ; i < gridindexes.size() ; ++i)\n    {\n        pj_gi & gi = grids[gridindexes[i]];\n\n        // skip tables that don't match our point at all.\n        if (! grid_disjoint(lam, phi, gi.ct))\n        {\n            // skip vertical grids\n            if (gi.format != pj_gi::gtx)\n            {\n                gip = boost::addressof(gi);\n                break;\n            }\n        }\n    }\n\n    if (gip == NULL)\n        return gip;\n\n    // If we have child nodes, check to see if any of them apply.\n    pj_gi * child = find_grid(lam, phi, gip->children.begin(), gip->children.end());\n    if (child != NULL)\n        gip = child;\n\n    // if we get this far we have found a suitable grid\n    return gip;\n}\n\n\ntemplate <typename StreamPolicy>\ninline bool load_grid(StreamPolicy const& stream_policy, pj_gi_load & gi)\n{\n    // load the grid shift info if we don't have it.\n    if (gi.ct.cvs.empty())\n    {\n        typename StreamPolicy::stream_type is;\n        stream_policy.open(is, gi.gridname);\n\n        if (! pj_gridinfo_load(is, gi))\n        {\n            //pj_ctx_set_errno( ctx, PJD_ERR_FAILED_TO_LOAD_GRID );\n            return false;\n        }\n    }\n\n    return true;\n}\n\n\n/************************************************************************/\n/*                        pj_apply_gridshift_3()                        */\n/*                                                                      */\n/*      This is the real workhorse, given a gridlist.                   */\n/************************************************************************/\n\ntemplate <bool Inverse, typename CalcT, typename StreamPolicy, typename Range>\ninline bool pj_apply_gridshift_3(StreamPolicy const& stream_policy,\n                                 Range & range,\n                                 srs::grids & grids,\n                                 std::vector<std::size_t> const& gridindexes)\n{\n    typedef typename boost::range_size<Range>::type size_type;\n\n    // If the grids are empty the indexes are as well\n    if (gridindexes.empty())\n    {\n        //pj_ctx_set_errno(ctx, PJD_ERR_FAILED_TO_LOAD_GRID);\n        //return PJD_ERR_FAILED_TO_LOAD_GRID;\n        return false;\n    }\n\n    size_type point_count = boost::size(range);\n\n    for (size_type i = 0 ; i < point_count ; ++i)\n    {\n        typename boost::range_reference<Range>::type\n            point = range::at(range, i);\n\n        CalcT in_lon = geometry::get_as_radian<0>(point);\n        CalcT in_lat = geometry::get_as_radian<1>(point);\n\n        pj_gi * gip = find_grid(in_lon, in_lat, grids.gridinfo, gridindexes);\n\n        if ( gip != NULL )\n        {\n            // load the grid shift info if we don't have it.\n            if (! gip->ct.cvs.empty() || load_grid(stream_policy, *gip))\n            {\n                // TODO: use set_invalid_point() or similar mechanism\n                CalcT out_lon = HUGE_VAL;\n                CalcT out_lat = HUGE_VAL;\n\n                nad_cvt<Inverse>(in_lon, in_lat, out_lon, out_lat, *gip);\n\n                // TODO: check differently\n                if ( out_lon != HUGE_VAL )\n                {\n                    geometry::set_from_radian<0>(point, out_lon);\n                    geometry::set_from_radian<1>(point, out_lat);\n                }\n            }\n        }\n    }\n\n    return true;\n}\n\n\n/************************************************************************/\n/*                        pj_apply_gridshift_2()                        */\n/*                                                                      */\n/*      This implementation uses the gridlist from a coordinate         */\n/*      system definition.  If the gridlist has not yet been            */\n/*      populated in the coordinate system definition we set it up      */\n/*      now.                                                            */\n/************************************************************************/\n\ntemplate <bool Inverse, typename Par, typename Range, typename ProjGrids>\ninline bool pj_apply_gridshift_2(Par const& defn, Range & range, ProjGrids const& grids)\n{\n    /*if( defn->catalog_name != NULL )\n        return pj_gc_apply_gridshift( defn, inverse, point_count, point_offset,\n                                      x, y, z );*/\n\n    /*std::vector<std::size_t> gridindexes;\n    pj_gridlist_from_nadgrids(pj_get_param_s(defn.params, \"nadgrids\"),\n                              grids.storage_ptr->stream_policy,\n                              grids.storage_ptr->grids,\n                              gridindexes);*/\n\n    BOOST_GEOMETRY_ASSERT(grids.storage_ptr != NULL);\n\n    // At this point the grids should be initialized\n    if (grids.hindexes.empty())\n        return false;\n\n    return pj_apply_gridshift_3\n            <\n                Inverse, typename Par::type\n            >(grids.storage_ptr->stream_policy,\n              range,\n              grids.storage_ptr->hgrids,\n              grids.hindexes);\n}\n\ntemplate <bool Inverse, typename Par, typename Range>\ninline bool pj_apply_gridshift_2(Par const& , Range & , srs::detail::empty_projection_grids const& )\n{\n    return false;\n}\n\n\n} // namespace detail\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_SRS_PROJECTIONS_IMPL_PJ_APPLY_GRIDSHIFT_HPP\n", "meta": {"hexsha": "143f39574fda71cc24d0474a342d301099a5298c", "size": 13795, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/srs/projections/impl/pj_apply_gridshift.hpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/srs/projections/impl/pj_apply_gridshift.hpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/boost/geometry/srs/projections/impl/pj_apply_gridshift.hpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 32.0813953488, "max_line_length": 103, "alphanum_fraction": 0.5638274737, "num_tokens": 3445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4441402723643509}}
{"text": "/* Copyright © 2017 Apple Inc. All rights reserved.\n *\n * Use of this source code is governed by a BSD-3-clause license that can\n * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n */\n#ifndef TURI_NN_DISTANCE_FUNCTIONS_H_\n#define TURI_NN_DISTANCE_FUNCTIONS_H_\n\n#include <string>\n#include <Eigen/SparseCore>\n#include <Eigen/Core>\n#include <memory>\n#include <util/logit_math.hpp>\n#include <unity/toolkits/util/algorithmic_utils.hpp>\n#include <flexible_type/flexible_type_base_types.hpp>\n#include <unity/lib/toolkit_function_macros.hpp>\n#include <boost/algorithm/string.hpp>\n\nnamespace turi {\nnamespace nearest_neighbors {\n\ntypedef Eigen::VectorXd DenseVector;\ntypedef Eigen::MatrixXd DenseMatrix;\ntypedef Eigen::SparseVector<double> SparseVector;\ntypedef Eigen::SparseMatrix<double, 1> SparseMatrix; // row-major\n\n/**\n * Compute the Euclidean distance between the Cartesian product of rows in two\n * matrices.\n */\nvoid inline all_pairs_squared_euclidean(const DenseMatrix& A,\n                                        const DenseMatrix& B, \n                                        DenseMatrix& dists) {\n\n  DASSERT_EQ(A.cols(), B.cols());\n  DASSERT_EQ(A.rows(), dists.rows());\n  DASSERT_EQ(B.rows(), dists.cols());\n\n  dists = -2 * A * B.transpose();\n\n  for (size_t i = 0; i < (size_t)A.rows(); ++i) {\n    dists.row(i).array() += A.row(i).squaredNorm();\n  }\n\n  for (size_t j = 0; j < (size_t)B.rows(); ++j) {\n    dists.col(j).array() += B.row(j).squaredNorm();\n  }\n}\n\n\nvoid inline all_pairs_cosine(const DenseMatrix& A, const DenseMatrix& B, \n                             DenseMatrix& dists) {\n\n  DASSERT_EQ(A.cols(), B.cols());\n  DASSERT_EQ(A.rows(), dists.rows());\n  DASSERT_EQ(B.rows(), dists.cols());\n\n  dists = -1 * A * B.transpose();\n\n  for (size_t i = 0; i < (size_t)A.rows(); ++i) {\n    double row_norm = std::max(1e-16, A.row(i).norm());\n    dists.row(i).array() /= row_norm;\n  }\n\n  for (size_t j = 0; j < (size_t)B.rows(); ++j) {\n    double col_norm = std::max(1e-16, B.row(j).norm());\n    dists.col(j).array() /= col_norm;\n  }\n\n  dists.array() += 1;\n}\n\n\nvoid inline all_pairs_dot_product(const DenseMatrix& A, const DenseMatrix& B, \n                                  DenseMatrix& dists) {\n\n  DASSERT_EQ(A.cols(), B.cols());\n  DASSERT_EQ(A.rows(), dists.rows());\n  DASSERT_EQ(B.rows(), dists.cols());\n\n  dists = A * B.transpose();\n  dists = dists.cwiseMax(1e-10).cwiseInverse();\n}\n\n\nvoid inline all_pairs_transformed_dot_product(const DenseMatrix& A,\n                                              const DenseMatrix& B, \n                                              DenseMatrix& dists) {\n\n  DASSERT_EQ(A.cols(), B.cols());\n  DASSERT_EQ(A.rows(), dists.rows());\n  DASSERT_EQ(B.rows(), dists.cols());\n\n  dists = A * B.transpose();\n  dists = dists.unaryExpr([](double x) { return log1pen(x); });\n}\n\n\nstruct distance_metric {\n\n  virtual ~distance_metric() = default;\n\n  // factory methods\n  static inline std::shared_ptr<distance_metric> make_dist_instance(const std::string& dist_name);\n\n  static inline std::shared_ptr<distance_metric> make_distance_metric(\n    function_closure_info fn); \n\n  virtual double distance(const DenseVector& a, const DenseVector& b) const {\n    ASSERT_MSG(false, \"Dense vector type not supported by this distance metric.\");\n    ASSERT_UNREACHABLE();\n  }\n\n  virtual double distance(const SparseVector& a, const SparseVector& b) const {\n    ASSERT_MSG(false, \"Sparse vector type not supported by this distance metric.\");\n    ASSERT_UNREACHABLE();\n  }\n\n  virtual double distance(const std::string& a, const std::string& b) const {\n    ASSERT_MSG(false, \"String type not supported by this distance metric.\");\n    ASSERT_UNREACHABLE();\n  }\n\n  virtual double distance(const std::vector<double>& a, const std::vector<double>& b) const {\n    ASSERT_MSG(false, \"Vector of double type not supported by this distance metric.\");\n    ASSERT_UNREACHABLE();\n  }\n\n};\n\n/** squared_euclidean distance.\n */\nstruct gaussian_kernel final : public distance_metric {\n\n  double distance(const DenseVector& a, const DenseVector& b) const  {\n    return 1 - std::exp( - ( (a - b).squaredNorm() ) );\n  }\n\n  double distance(const SparseVector& a, const SparseVector& b) const  {\n    return 1 - std::exp(-( (a.squaredNorm() + b.squaredNorm() - 2 * (a.dot(b))) ));\n  }\n\n};\n\n/** squared_euclidean distance.\n */\nstruct squared_euclidean final : public distance_metric {\n\n  double distance(const DenseVector& a, const DenseVector& b) const  {\n    return (a - b).squaredNorm();\n  }\n\n  double distance(const SparseVector& a, const SparseVector& b) const  {\n    return (a.squaredNorm() + b.squaredNorm() - 2 * (a.dot(b)));\n  }\n\n};\n\n/** euclidean distance.\n */\nstruct euclidean final : public distance_metric {\n\n  double distance(const DenseVector& a, const DenseVector& b) const {\n    DASSERT_TRUE(a.size() == b.size());\n    DASSERT_TRUE(a.size() > 0);\n    return std::sqrt((a - b).squaredNorm());\n  }\n\n  double distance(const SparseVector& a, const SparseVector& b) const {\n    return std::sqrt(a.squaredNorm() + b.squaredNorm() - 2 * (a.dot(b)));\n  }\n\n};\n\n/** manhattan distance.\n */\nstruct manhattan final : public distance_metric {\n\n  double distance(const DenseVector& a, const DenseVector& b) const {\n    DASSERT_TRUE(a.size() == b.size());\n    DASSERT_TRUE(a.size() > 0);\n    return (a - b).cwiseAbs().sum();\n  }\n\n  double distance(const SparseVector& a, const SparseVector& b) const {\n    return (a - b).cwiseAbs().sum();\n  }\n\n};\n\n/** cosine distance.\n */\nstruct cosine final : public distance_metric {\n\n  double distance(const DenseVector& a, const DenseVector& b) const {\n    DASSERT_TRUE(a.size() == b.size());\n    DASSERT_TRUE(a.size() > 0);\n\n    double similarity = (double)a.dot(b) / std::max(1e-16, a.norm() * b.norm());\n    return  1 - similarity;\n  }\n\n  double distance(const SparseVector& a, const SparseVector& b) const {\n    double similarity = (double)a.dot(b) / std::max(1e-16, a.norm() * b.norm());\n    return  1 - similarity;\n  }\n\n};\n\n/* dot_product distance\n */\nstruct dot_product final : public distance_metric {\n\n  double distance(const DenseVector& a, const DenseVector& b) const {\n    DASSERT_TRUE(a.size() == b.size());\n    DASSERT_TRUE(a.size() > 0);\n\n    double dot_product = (double)a.dot(b);\n    return 1.0 / std::max(dot_product, 1e-10);\n  }\n\n  double distance(const SparseVector& a, const SparseVector& b) const {\n    double dot_product = (double)a.dot(b);\n    return 1.0 / std::max(dot_product, 1e-10);\n  }\n};\n\n/* transformed_dot_product distance\n */\nstruct transformed_dot_product final : public distance_metric {\n\n  double distance(const DenseVector& a, const DenseVector& b) const {\n    DASSERT_TRUE(a.size() == b.size());\n    DASSERT_TRUE(a.size() > 0);\n\n    double dot_product = (double)a.dot(b);\n    return log1pen(dot_product);\n  }\n\n  double distance(const SparseVector& a, const SparseVector& b) const {\n    double dot_product = (double)a.dot(b);\n    return log1pen(dot_product);\n  }\n};\n\n/* jaccard distance \n */\nstruct jaccard final : public distance_metric {\n  using distance_metric::distance;\n  \n  double distance(const DenseVector& a, const DenseVector& b) const {\n    DASSERT_EQ(a.size(), b.size());\n    double intersection_size = 0.;\n    double union_size = 0.;    \n    for(size_t idx = 0; idx < std::min<size_t>(a.size(), b.size()); ++idx) {\n      if (a(idx) > 0. || b(idx) > 0.) {\n        union_size += 1.;\n        if (a(idx) > 0. && b(idx) > 0.) {\n          intersection_size += 1.;\n        }  \n      }\n    }\n    if (union_size == 0.) return 1.;\n    return 1. - intersection_size / union_size;\n  }\n\n  double distance(const SparseVector& a, const SparseVector& b) const GL_HOT_FLATTEN {\n\n    size_t intersection_size = 0;\n\n    SparseVector::InnerIterator it_a(a, 0);\n    SparseVector::InnerIterator it_b(b, 0);\n\n    while(it_a && it_b) {\n      if(it_a.index() < it_b.index()) {\n        ++it_a;\n      } else if(it_a.index() > it_b.index()) {\n        ++it_b;\n      } else {\n        ++intersection_size;\n        ++it_a, ++it_b;\n      }\n    }\n\n    size_t d = a.nonZeros() + b.nonZeros() - intersection_size;\n    \n    return 1.0 - double(intersection_size) / d;\n  }\n\n  double distance(std::vector<size_t>& av,\n                  std::vector<size_t>& bv) const {\n    DASSERT_TRUE(av.size() > 0);\n    DASSERT_TRUE(bv.size() > 0);\n\n    std::sort(av.begin(), av.end());\n    std::sort(bv.begin(), bv.end());\n\n    // Use an efficient accumulate function\n    size_t n = count_intersection(av.begin(), av.end(),\n                                  bv.begin(), bv.end());\n    size_t d = av.size() + bv.size() - n;\n    DASSERT_TRUE(d > 0);\n\n    return 1 - double(n) / d;\n  }\n\n};\n\n/* weighted jaccard distance \n */\nstruct weighted_jaccard final : public distance_metric {\n\n  double distance(const SparseVector& a, const SparseVector& b) const {\n\n    SparseVector::InnerIterator it_a(a, 0);\n    SparseVector::InnerIterator it_b(b, 0);\n\n    double cwise_min_sum = 0; \n    double cwise_max_sum = 0; \n\n    while(it_a && it_b) {\n      if(it_a.index() < it_b.index()) {\n        cwise_max_sum += it_a.value();\n        ++it_a;\n      } else if(it_a.index() > it_b.index()) {\n        cwise_max_sum += it_b.value();\n        ++it_b;\n      } else {\n        cwise_min_sum += std::min(it_a.value(), it_b.value());\n        cwise_max_sum += std::max(it_a.value(), it_b.value());\n        ++it_a, ++it_b;\n      }\n    }\n\n    while(it_a) {\n      cwise_max_sum += it_a.value();\n      ++it_a; \n    }\n\n    while(it_b) {\n      cwise_max_sum += it_b.value();\n      ++it_b; \n    }\n    \n    double similarity = cwise_min_sum / cwise_max_sum; \n    return 1 - similarity;\n  }\n\n};\n\n\n/* levenshtein distance\n */\nstruct levenshtein final : public distance_metric {\n\n  double distance(const std::string& a, const std::string& b) const {\n\n    std::string s;\n    std::string t;\n    size_t len_s;\n    size_t len_t;\n\n    // if 't' is not the longer string, switch them so 't' is the longer string\n    if (a.length() > b.length()) {\n      t = a;\n      s = b;\n    } else {\n      s = a;\n      t = b;\n    }\n\n    // trim common prefix - these cannot add anything to the distance\n    size_t idx_start = 0;\n    while ((s[idx_start] == t[idx_start]) && (idx_start < s.length())) {\n      idx_start++;\n    }\n\n    if (idx_start == t.length()) {  // if the entire strings match, distance is 0\n      return 0;\n    }\n\n    s = s.substr(idx_start);\n    t = t.substr(idx_start);\n\n    len_s = s.length();\n    len_t = t.length();\n\n    // if either trimmed string has length 0, the distance is the length of the\n    // other string. Since 's' is the shorter string, this should capture all\n    // cases.\n    if (len_s == 0)\n      return len_t;\n\n    // initialize the rows\n    std::vector<size_t> v0(len_t + 1, 0);\n    std::vector<size_t> v1(len_t + 1, 0);\n\n    for (size_t i = 0; i < v0.size(); i++) {\n      v0[i] = i;\n    }\n\n    size_t cost;\n\n    // For each letter in the shorter string...\n    for (size_t i = 0; i < len_s; i++) {\n      v1[0] = i + 1;\n      \n      // Fill in the second row\n      for (size_t j = 0; j < len_t; j++) {\n        cost = (s[i] == t[j]) ? 0 : 1;\n        v1[j+1] = std::min({v0[j] + cost, v0[j+1] + 1, v1[j] + 1});\n      }\n\n      // Copy the second row into the first row\n      for (size_t j = 0; j < v0.size(); j++) {\n        v0[j] = v1[j];\n      }\n    }\n\n    return v1[t.length()];\n  }\n};\n\nstruct custom_distance final : public distance_metric {\n\n  // std::function<double(const std::vector<double>, const std::vector<double>)> fn;\n  std::function<double(const flexible_type, const flexible_type)> fn;\n\n  double distance(const std::vector<double>& a, const std::vector<double>& b) const {\n    return fn(a, b);\n  }\n\n  double distance(const std::string& a, const std::string& b) const {\n    return fn(a, b);\n  }\n};\n\nstd::shared_ptr<distance_metric> inline distance_metric::make_distance_metric(\n    function_closure_info fn) {\n  auto fn_name = fn.native_fn_name;\n  distance_metric d;\n  if (boost::algorithm::ends_with(fn_name, \".euclidean\")) {\n    return  distance_metric::make_dist_instance(\"euclidean\");\n  } else if (boost::algorithm::ends_with(fn_name, \".squared_euclidean\")) {\n    return distance_metric::make_dist_instance(\"squared_euclidean\");\n  } else if (boost::algorithm::ends_with(fn_name, \".gaussian_kernel\")) {\n    return distance_metric::make_dist_instance(\"gaussian_kernel\");\n  } else if (boost::algorithm::ends_with(fn_name, \".manhattan\")) {\n    return distance_metric::make_dist_instance(\"manhattan\");\n  } else if (boost::algorithm::ends_with(fn_name, \".cosine\")) {\n    return distance_metric::make_dist_instance(\"cosine\");\n  } else if (boost::algorithm::ends_with(fn_name, \".dot_product\")) {\n    return distance_metric::make_dist_instance(\"dot_product\");\n  } else if (boost::algorithm::ends_with(fn_name, \".transformed_dot_product\")) {\n    return distance_metric::make_dist_instance(\"transformed_dot_product\");\n  } else if (boost::algorithm::ends_with(fn_name, \".jaccard\")) {\n    return distance_metric::make_dist_instance(\"jaccard\");\n  } else if (boost::algorithm::ends_with(fn_name, \".weighted_jaccard\")) {\n    return distance_metric::make_dist_instance(\"weighted_jaccard\");\n  } else if (boost::algorithm::ends_with(fn_name, \".levenshtein\")) {\n    return distance_metric::make_dist_instance(\"levenshtein\");\n  } else {\n    // Create a distance metric that uses the user-provided function.\n    // Only functions that take dense vectors are currently supported.\n    auto actual_fn = variant_get_value< std::function<double(const std::vector<double>, const std::vector<double>)> >(fn);\n    auto d = nearest_neighbors::custom_distance();\n    d.fn = actual_fn;\n    auto sp = std::make_shared<distance_metric>(d);\n    return sp;\n  }\n}\n\nstd::shared_ptr<distance_metric> inline distance_metric::make_dist_instance(\n  const std::string& dist_name) {\n  \n  std::shared_ptr<distance_metric> dist_ptr;\n\n  if (dist_name == \"euclidean\") \n    dist_ptr.reset(new euclidean); \n  else if(dist_name == \"squared_euclidean\")\n    dist_ptr.reset(new squared_euclidean);\n  else if(dist_name == \"gaussian_kernel\")\n    dist_ptr.reset(new gaussian_kernel);\n  else if (dist_name == \"manhattan\")\n    dist_ptr.reset(new manhattan);\n  else if (dist_name == \"cosine\")\n    dist_ptr.reset(new cosine);\n  else if (dist_name == \"dot_product\")\n    dist_ptr.reset(new dot_product);\n  else if (dist_name == \"transformed_dot_product\")\n    dist_ptr.reset(new transformed_dot_product);\n  else if (dist_name == \"jaccard\")\n    dist_ptr.reset(new jaccard);\n  else if (dist_name == \"weighted_jaccard\")\n    dist_ptr.reset(new weighted_jaccard);\n  else if (dist_name == \"levenshtein\")\n    dist_ptr.reset(new levenshtein);\n  else\n    log_and_throw(\"Unrecognized distance: \" + dist_name);\n\n  return dist_ptr;\n}\n\n\n}}\n\n#endif  // TURI_NN_DISTANCE_FUNCTIONS_H_\n", "meta": {"hexsha": "c6a2028613cf757a3db6b46f183ccac641823936", "size": 14758, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/unity/toolkits/nearest_neighbors/distance_functions.hpp", "max_stars_repo_name": "LeeCenY/turicreate", "max_stars_repo_head_hexsha": "fb2f3bf313e831ceb42a2e10aacda6e472ea8d93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/unity/toolkits/nearest_neighbors/distance_functions.hpp", "max_issues_repo_name": "LeeCenY/turicreate", "max_issues_repo_head_hexsha": "fb2f3bf313e831ceb42a2e10aacda6e472ea8d93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-01-13T04:03:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T01:02:31.000Z", "max_forks_repo_path": "src/unity/toolkits/nearest_neighbors/distance_functions.hpp", "max_forks_repo_name": "ZeroInfinite/turicreate", "max_forks_repo_head_hexsha": "dd210c2563930881abd51fd69cb73007955b33fd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0511811024, "max_line_length": 122, "alphanum_fraction": 0.6385689118, "num_tokens": 3951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079209, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.44396007196634374}}
{"text": "/*\n * Copyright (c) 2018 Nicholas Corgan (n.corgan@gmail.com)\n *\n * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt\n * or copy at http://opensource.org/licenses/MIT)\n */\n\n#include <pkmn/config.hpp>\n \n// http://stackoverflow.com/q/6884093\n#ifdef PKMN_PLATFORM_WIN32\n#define NOMINMAX\n#include <windows.h>\n#endif\n\n#include \"exception_internal.hpp\"\n#include \"utils/misc.hpp\"\n#include \"types/rng.hpp\"\n#include \"utils/floating_point_comparison.hpp\"\n\n#include <pkmn/calculations/personality.hpp>\n\n#include <pkmn/calculations/shininess.hpp>\n#include <pkmn/database/pokemon_entry.hpp>\n#include <pkmn/enums/gender.hpp>\n\n#include <boost/assign/list_of.hpp>\n\n#include <algorithm>\n#include <stdexcept>\n#include <vector>\n\nnamespace pkmn { namespace calculations {\n\n    static uint32_t get_gender_threshold(\n        float chance_male\n    )\n    {\n        uint32_t ret = 0;\n\n        if(pkmn::fp_compare_equal(chance_male, 0.875f))\n        {\n            ret = 31;\n        }\n        else if(pkmn::fp_compare_equal(chance_male, 0.75f))\n        {\n            ret = 64;\n        }\n        else if(pkmn::fp_compare_equal(chance_male, 0.5f))\n        {\n            ret = 127;\n        }\n        else\n        {\n            ret = 191;\n        }\n\n        return ret;\n    }\n\n    uint32_t generate_personality(\n        pkmn::e_species species,\n        uint32_t trainer_id,\n        bool shiny,\n        pkmn::e_ability ability,\n        pkmn::e_gender gender,\n        pkmn::e_nature nature\n    )\n    {\n        pkmn::enforce_value_in_vector(\n            \"Gender\",\n            gender,\n            {pkmn::e_gender::MALE, pkmn::e_gender::FEMALE, pkmn::e_gender::GENDERLESS}\n        );\n\n        if((species == pkmn::e_species::NONE) || (species == pkmn::e_species::INVALID))\n        {\n            throw std::invalid_argument(\"Species cannot be None or Invalid.\");\n        }\n        if(nature == pkmn::e_nature::NONE)\n        {\n            throw std::invalid_argument(\"Nature cannot be None.\");\n        }\n\n        uint32_t ret = 0;\n\n        pkmn::database::pokemon_entry entry(species, pkmn::e_game::OMEGA_RUBY, \"\");\n        pkmn::ability_pair_t abilities = entry.get_abilities();\n        pkmn::e_ability hidden_ability = entry.get_hidden_ability();\n        float chance_male = entry.get_chance_male();\n        float chance_female = entry.get_chance_female();\n\n        // Validate ability input.\n        uint32_t ability_modulo = 0; // If first or hidden ability, keep this\n        if(ability == abilities.second)\n        {\n            if(ability != pkmn::e_ability::NONE)\n            {\n                ability_modulo = 1;\n            }\n            else\n            {\n                throw std::invalid_argument(\"You cannot use NONE.\");\n            }\n        }\n        else if((ability != abilities.first) && (ability != hidden_ability))\n        {\n            throw std::invalid_argument(\"Invalid ability.\");\n        }\n\n        // Validate gender input.\n        if(pkmn::fp_compare_equal((chance_male + chance_female), 0.0f))\n        {\n            if(gender != pkmn::e_gender::GENDERLESS)\n            {\n                throw std::invalid_argument(\"This Pokémon is genderless.\");\n            }\n        }\n        else if(pkmn::fp_compare_equal(chance_male, 1.0f))\n        {\n            if(gender != pkmn::e_gender::MALE)\n            {\n                throw std::invalid_argument(\"This Pokémon is male-only.\");\n            }\n        }\n        else if(pkmn::fp_compare_equal(chance_female, 1.0f))\n        {\n            if(gender != pkmn::e_gender::FEMALE)\n            {\n                throw std::invalid_argument(\"This Pokémon is female-only.\");\n            }\n        }\n        else if(gender != pkmn::e_gender::MALE and gender != pkmn::e_gender::FEMALE)\n        {\n            throw std::invalid_argument(\"Valid genders: Male, Female\");\n        }\n\n        // TODO: validate\n        uint32_t nature_index = static_cast<uint32_t>(nature) - 1;\n        static const size_t NUM_NATURES = 25;\n\n        // Start trying to find a valid value.\n        uint32_t gender_threshold = get_gender_threshold(chance_male);\n        bool found = false;\n        pkmn::rng<uint32_t> rng;\n        do\n        {\n            ret = rng.rand();\n\n            // Set the gender if applicable.\n            if(gender == pkmn::e_gender::MALE)\n            {\n                ret &= ~0xFF;\n                ret |= (rng.rand() % (0xFF - gender_threshold) + gender_threshold);\n            }\n            else if(gender == pkmn::e_gender::FEMALE)\n            {\n                ret &= ~0xFF;\n                ret |= (rng.rand() % gender_threshold);\n            }\n\n            if((modern_shiny(ret, trainer_id) == shiny) &&\n               ((ret % NUM_NATURES) == nature_index) &&\n               ((ret % 2) == ability_modulo)\n            )\n            {\n                found = true;\n            }\n        }\n        while(!found);\n\n        return ret;\n    }\n\n}}\n", "meta": {"hexsha": "9c98799789d88524e491ddd6184306d168fe5a58", "size": 4901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/calculations/personality.cpp", "max_stars_repo_name": "ncorgan/libpkmn", "max_stars_repo_head_hexsha": "c683bf8b85b03eef74a132b5cfdce9be0969d523", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-06-10T13:21:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-30T21:20:19.000Z", "max_issues_repo_path": "lib/calculations/personality.cpp", "max_issues_repo_name": "PMArkive/libpkmn", "max_issues_repo_head_hexsha": "c683bf8b85b03eef74a132b5cfdce9be0969d523", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2017-04-05T11:13:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-03T14:31:03.000Z", "max_forks_repo_path": "lib/calculations/personality.cpp", "max_forks_repo_name": "PMArkive/libpkmn", "max_forks_repo_head_hexsha": "c683bf8b85b03eef74a132b5cfdce9be0969d523", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-22T21:02:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-30T21:20:20.000Z", "avg_line_length": 27.8465909091, "max_line_length": 87, "alphanum_fraction": 0.5435625383, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.44396006669223925}}
{"text": "// Copyright 2015 National ICT Australia Limited (NICTA)\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"KluSolver.h\"\n\n#include <klu.h>\n\n#include <armadillo>\n\nusing namespace arma;\n\nbool kluSolve(const arma::SpMat<double>& a, const arma::Col<double>& b, arma::Col<double>& result)\n{\n    auto n = b.size();\n    auto nnz = a.n_nonzero;\n\n    int* ap = new int[n + 1];\n    for (unsigned int i = 0; i <= n; ++i) ap[i] = static_cast<int>(a.col_ptrs[i]);\n\n    int* ai = new int[nnz];\n    for (unsigned int i = 0; i < nnz; ++i) ai[i] = static_cast<int>(a.row_indices[i]);\n\n    double* ax = new double[nnz];\n    for (unsigned int i = 0; i < nnz; ++i) ax[i] = a.values[i];\n\n    double* b1 = new double[n];\n    for (unsigned int i = 0; i < n; ++i) b1[i] = b(i);\n\n    klu_symbolic *Symbolic;\n    klu_numeric *Numeric;\n    klu_common Common;\n\n    klu_defaults (&Common);\n    Symbolic = klu_analyze (static_cast<int>(n), ap, ai, &Common);\n    Numeric = klu_factor (ap, ai, ax, Symbolic, &Common);\n    bool ok = klu_solve(Symbolic, Numeric, static_cast<int>(n), 1, b1, &Common) == 1;\n\n    if (!ok)\n    {\n        std::cerr << \"KLU failed.\" << std::endl;\n        std::cerr << \"Status = \" << Common.status << std::endl;\n    }\n\n    klu_free_symbolic (&Symbolic, &Common);\n    klu_free_numeric (&Numeric, &Common);\n\n    result = arma::Col<double>(n, fill::none);\n    for (arma::uword i = 0; i < n; ++i)\n    {\n        result(i) = b1[i];\n    }\n\n    delete[] ap;\n    delete[] ai;\n    delete[] ax;\n    delete[] b1;\n\n    return ok;\n}\n", "meta": {"hexsha": "3c6b557ed48a24471e35888b1c58d4b9e6d949c4", "size": 2030, "ext": "cc", "lang": "C++", "max_stars_repo_path": "SgtCore/KluSolver.cc", "max_stars_repo_name": "dexterurbane/SmartGridToolbox", "max_stars_repo_head_hexsha": "ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SgtCore/KluSolver.cc", "max_issues_repo_name": "dexterurbane/SmartGridToolbox", "max_issues_repo_head_hexsha": "ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SgtCore/KluSolver.cc", "max_forks_repo_name": "dexterurbane/SmartGridToolbox", "max_forks_repo_head_hexsha": "ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5915492958, "max_line_length": 98, "alphanum_fraction": 0.621182266, "num_tokens": 598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4439589783054335}}
{"text": "/*\n  Copyright (c) <2014> <Thomas Mörwald, Vienna University of Technology>\n\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted (subject to the limitations in the disclaimer\n  below) provided that the following conditions are met:\n\n   * Redistributions of source code must retain the above copyright\n     notice, this list of conditions and the following disclaimer.\n\n   * Redistributions in binary form must reproduce the above copyright\n     notice, this list of conditions and the following disclaimer in the\n     documentation and/or other materials provided with the distribution.\n\n   * Neither the name of <Owner Organization> nor the names of its\n     contributors may be used to endorse or promote products derived from this\n     software without specific prior written permission.\n\n  NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS\n  LICENSE.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE\n  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n// This file contains mathematical definitions derifed from CGAL and Eigen\n// It implements some helper functions like arithmetic mean, principal component\n// analysis (PCA) and comparison of floating point values and vectors\n\n#ifndef _TSPLINE_MATH_H_\n#define _TSPLINE_MATH_H_\n\n#include <vector>\n#include <stdio.h>\n#include <stdexcept>\n#include <limits>\n\n#undef Success\n#include <Eigen/Eigen>\n\n#include <CGAL/Cartesian.h>\n#include <CGAL/MP_Float.h>\n#include <CGAL/Quotient.h>\n#include <CGAL/Arr_segment_traits_2.h>\n#include <CGAL/Arrangement_2.h>\n#include <CGAL/Arr_extended_dcel.h>\n\n#define SIZE_T_MAX std::numeric_limits<std::size_t>::max()\n\nnamespace tspline\n{\n\n// derive algebraic objects from CGAL types\ntypedef CGAL::Cartesian<double> Kernel;\ntypedef CGAL::Arr_segment_traits_2<Kernel> Traits_2;\ntypedef Kernel::Point_2 Point2d;\ntypedef Kernel::Point_3 Point3d;\ntypedef Kernel::Vector_2 Vector2d;\ntypedef Kernel::Vector_3 Vector3d;\ntypedef Kernel::Ray_3 Ray;\ntypedef Kernel::Direction_3 Direction3d;\ntypedef Traits_2::X_monotone_curve_2 Segment2;\n\n// numerical limits\nstatic double epsilon = 10.0 * std::numeric_limits<float>::epsilon(); // float because tgModel using OpenGL is float\nstatic double digits = 1e10;\nstatic double div_digits = 1e-10;\n\n/** @brief extends Point3d by the weight entry for control points  (weight is 1.0 by default) */\nclass Point4d : public Point3d\n{\nprotected:\n  double weight;\n\npublic:\n  Point4d() : Point3d(), weight(1.0) { }\n  Point4d(const Point3d& a, const double& w=1.0) : Point3d(a), weight(w) { }\n  Point4d(const double& x, const double& y, const double& z, const double& w) :\n    Point3d(x,y,z), weight(w) { }\n  Point4d(const double& x, const double& y, const double& z) :\n    Point3d(x,y,z), weight(1.0) { }\n\n  void operator=(const Point3d& a)\n  {\n    *this = Point4d(a);\n  }\n\n  double w() const { return weight; }\n\n};\n\n/** @brief aligned Eigen::Vector classes */\ntypedef std::vector<Eigen::Vector4d, Eigen::aligned_allocator<Eigen::Vector4d> > vector_vec4d;\ntypedef std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > vector_vec3d;\ntypedef std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d> > vector_vec2d;\n\n/** @brief compute the arithmetic mean of a vector of Vector3d\n *  @param data input data */\ninline Eigen::Vector3d compute_mean (const vector_vec3d &data)\n{\n  Eigen::Vector3d u (0.0, 0.0, 0.0);\n\n  unsigned s = unsigned (data.size ());\n  double ds = 1.0 / s;\n\n  for (unsigned i = 0; i < s; i++)\n    u += (data[i] * ds);\n\n  return u;\n}\n\n/** @brief compute the principal components of a vector of Vector3d\n *  @param data in: input data\n *  @param mean out: the arithmetic mean of the data\n *  @param eigenvectors out: the eigenvectors sorted descending by their eigenvalues\n *  @param eigenvalues out: descending eigenvalues */\ninline void pca (const vector_vec3d &data, Eigen::Vector3d &mean, Eigen::Matrix3d &eigenvectors,\n                 Eigen::Vector3d &eigenvalues)\n{\n  if (data.empty ())\n    throw std::runtime_error (\"[Math::pca] Error, data is empty\\n\");\n\n  mean = compute_mean (data);\n\n  unsigned s = unsigned (data.size ());\n\n  Eigen::MatrixXd Q (3, s);\n\n  for (unsigned i = 0; i < s; i++)\n    Q.col (i) << (data[i] - mean);\n\n  Eigen::Matrix3d C = Q * Q.transpose ();\n\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver (C);\n  if (eigensolver.info () != Eigen::Success)\n    throw std::runtime_error (\"[Math::pca] Can not find eigenvalues.\\n\");\n\n  // reverse ordering of eigenvalues and eigenvectors\n  for (int i = 0; i < 3; ++i)\n  {\n    eigenvalues (i) = eigensolver.eigenvalues () (2 - i);\n    if (i == 2)\n      eigenvectors.col (2) = eigenvectors.col (0).cross (eigenvectors.col (1));\n    else\n      eigenvectors.col (i) = eigensolver.eigenvectors ().col (2 - i);\n  }\n}\n\n// comparison functions for floating point data types\n\n// ==\nstatic bool equal(const double& a, const double& b)\n{\n  if(std::abs<double>(a-b) < epsilon)\n    return true;\n  else\n    return false;\n}\n\n// >\nstatic bool greater(const double &a, const double &b)\n{\n  if(equal(a,b)) // equal\n    return false;\n  else if(a < b)\n    return false;\n  else\n    return true;\n}\n\n// <\nstatic bool smaller(const double &a, const double &b)\n{\n  if(equal(a,b)) // equal\n    return false;\n  else if(a > b)\n    return false;\n  else\n    return true;\n}\n\n// >=\nstatic bool gequal(const double &a, const double &b)\n{\n  if(equal(a,b)) // equal\n    return true;\n  else if(a > b)\n    return true;\n  else\n    return false;\n}\n\n// <=\nstatic bool sequal(const double &a, const double &b)\n{\n  if(equal(a,b))\n    return true;\n  else if(a < b)\n    return true;\n  else\n    return false;\n}\n\n// ==\nstatic bool equal( const Point2d& a, const Point2d& b)\n{\n  if(equal(a.x(), b.x()) && equal(a.y(), b.y()))\n    return true;\n  else\n    return false;\n}\n\n// ==\nstatic bool equal( const Point3d& a, const Point3d& b)\n{\n  if(equal(a.x(), b.x()) && equal(a.y(), b.y()) && equal(a.z(), b.z()))\n    return true;\n  else\n    return false;\n}\n\n// ==\nstatic bool equal( const Eigen::Vector3d& a, const Eigen::Vector3d& b)\n{\n  if(equal(a(0), b(0)) && equal(a(1), b(1)) && equal(a(2),b(2)))\n    return true;\n  else\n    return false;\n}\n\n/** @brief adjust a double value to a grid of minimal resolution */\nstatic double adjust(const double &a)\n{\n  return a;\n//  return double(float(a));\n  double b = round(a * digits) * div_digits;\n//  if(equal(b,0.0))\n//    b = 0.0;\n  return b;\n}\n\n/** @brief adjust a Point2D value to a grid of minimal resolution */\nstatic Point2d adjust(const Point2d &p)\n{\n  return Point2d(adjust(p.x()), adjust(p.y()));\n}\n\n/** @brief adjust a Point3D value to a grid of minimal resolution */\nstatic Point3d adjust(const Point3d &p)\n{\n  return Point3d(adjust(p.x()), adjust(p.y()), adjust(p.z()));\n}\n\n/** @brief dot product of CGAL::Vector3d (NOT Eigen)*/\nstatic double dot( const Vector3d& a, const Vector3d& b )\n{\n  return ( a.x()*b.x() + a.y()*b.y() + a.z()*b.z() );\n}\n\n/** @brief L2 norm of CGAL::Vector3d (NOT Eigen) */\nstatic double norm( const Vector3d& a )\n{\n  return sqrt(a.squared_length());\n}\n\n/** @brief angle between two CGAL::Vector3d (NOT Eigen) */\nstatic double angle( const Vector3d& a, const Vector3d& b )\n{\n  return acos( dot(a,b) / (norm(a) * norm(b)) );\n}\n\n}\n\n#endif\n", "meta": {"hexsha": "081ca16402d03ab589e8018ab2aefe6424b4b096", "size": 7975, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Tspline/Math.hpp", "max_stars_repo_name": "quadmotor/OpenTspline", "max_stars_repo_head_hexsha": "919725956ea38ec4ae7fef3cb56c58a959a3eb02", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2015-03-01T17:11:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T10:42:57.000Z", "max_issues_repo_path": "Tspline/Math.hpp", "max_issues_repo_name": "quadmotor/OpenTspline", "max_issues_repo_head_hexsha": "919725956ea38ec4ae7fef3cb56c58a959a3eb02", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-04-07T15:43:45.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-31T04:12:54.000Z", "max_forks_repo_path": "Tspline/Math.hpp", "max_forks_repo_name": "OpenTspline/OpenTspline", "max_forks_repo_head_hexsha": "919725956ea38ec4ae7fef3cb56c58a959a3eb02", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2015-03-26T03:05:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T08:17:40.000Z", "avg_line_length": 28.1802120141, "max_line_length": 116, "alphanum_fraction": 0.6899059561, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4439589716657752}}
{"text": "#ifndef SVD_HPP\n\n#define SVD_HPP\n\n#include \"print.hpp\"\n#include \"modify.hpp\"\n#include \"sub.hpp\"\n#include \"multiply.hpp\"\n#include \"special.hpp\"\n#include \"../workspace.hpp\"\n#include \"../tools.hpp\"\n#include <mkl.h>\n\n#include <boost/timer/timer.hpp>\n#include <boost/chrono.hpp>\n\n#include <vector>\n#include <utility>\n\ninline bool comparator ( const max_pair& l, const max_pair& r) { return l.first > r.first; }\n\nnamespace dqmc {\n    namespace la {\n\n\t// extern \"C\" {\n\t//     void dgejsv_( char* joba, char* jobu, char* jobv, char* jobr, char* jobt,\n\t// \t\t  char* jobp,\n\t// \t\t  const int* m, const int* n, double* a, const int* lda,\n\t// \t\t  double* sva, double* u, const int* ldu,\n\t// \t\t  double* v, const int* ldv, double* work,\n\t// \t\t  const int* lwork, int* iwork, int* info );\n\n\t//     int LAPACKE_dgejsv( int matrix_layout, char joba, char jobu, char jobv, \n\t//     \t\t\tchar jobr, char jobt, char jobp, int m, \n\t//     \t\t\tint n, const double* a, \n\t//     \t\t\tint lda, double* sva, double* u,\n\t//     \t\t\tint ldu, double* v, int ldv,\n\t//     \t\t\tdouble* stat, int* istat );\n\n\t//     void dgesvj_( const char* joba, const char* jobu, const char* jobv,\n\t// \t\t  const int* m, const int* n, double* a,\n\t// \t\t  const int* lda, double* sva, const int* mv, double* v,\n\t// \t\t  const int* ldv, double* work, int* lwork,\n\t// \t\t  int* info );\n\t// }\n\t\n\ttemplate <typename M, typename V>\n\tinline void close_svd(int sites, M&__restrict__ U, V&__restrict__ D,\n\t\t\t      M&__restrict__ T, \n\t\t\t      M&__restrict__ out) {\n\t    using namespace std;\n\t    \n\t    for (int col = sites - 1; col >= 0; col--) {\n\t\tfor (int row = sites - 1; row >= 0; row--) {\n\t\t    out(row, col) = 0.;\n\t\t    for (int k = sites - 1; k >= 0; k--) {\n\t\t\tif (U(row, k) != 0 && T(k, col) != 0 && D(k) != 0) \n\t\t\t    out(row, col) += ( U(row, k) * T(k, col)) * D(k);\n\t\t    }\n\t\t}\n\t    }\n\t}\n\n\ttemplate <typename M, typename V>\n\tinline void close_svd_inv_diag(int sites, M&__restrict__ U, V&__restrict__ D,\n\t\t\t\t       M&__restrict__ T,\n\t\t\t\t       M& out) {\n\t    using namespace std;\n\t    \n\t    for (int col = sites - 1; col >= 0; col--) {\n\t\tfor (int row = sites - 1; row >= 0; row--) {\n\t\t    out(row, col) = 0.;\n\t\t    for (int k = sites - 1; k >= 0; k--) {\n\t\t\tif (U(row, k) != 0 && T(k, col) != 0 && D(k) != 0) \n\t\t\t    out(row, col) += ( U(row, k) * T(k, col)) / D(k);\n\t\t    }\n\t\t}\n\t    }\n\t}\n\n\tinline int decompose_dgejsv_nt(pmat_t&__restrict__ in, pmat_t&__restrict__ U,\n\t\t\t\t       pvec_t&__restrict__ D, pmat_t&__restrict__ Tt,\n\t\t\t\t       pvec_t& work, ivec& ivywork) {\n\t    using namespace std;\n\n\t    int info;\n\t    int lwork = work.size() - 10;\n\n\t    char f = 'F';\n\t    char j = 'J';\n\t    char n = 'N';\n\t    char p = 'P';\n\t    int rows = U.rows();\n\t    int cols = U.cols();\n\t    int T_rows = Tt.rows();\n\t    // arma::vec work(6);\n\t    ivec iwork(in.rows() + 3 * in.cols());\n\t    work.setZero();\n\t    iwork.setZero();\n\n\t    dgejsv_( &f, &f, &j, &n, &n, &p, \n\t    \t     &rows, &cols, in.data(), &rows,\n\t    \t     D.data(), U.data(), &rows,\n\t    \t     Tt.data(), &T_rows, work.data(),\n\t    \t     &lwork, iwork.data(), &info);\n\t    return info;\n\t    // info = LAPACKE_dgejsv_work( 102, f, f, j, n, n, p, \n\t    // \t\t\t\trows, cols, in.data(), rows,\n\t    // \t\t\t\tD.data(), U.data(), rows,\n\t    // \t\t\t\tTt.data(), T_rows, work.data(),\n\t    // \t\t\t\twork.size(),\n\t    // \t\t\t\tiwork.data());\n\n\t    // return info;\n\t}\n\n\n\tinline int decompose_dgejsv_col_nt(pmat_t&__restrict__ in, pmat_t&__restrict__ U,\n\t\t\t\t       pvec_t&__restrict__ D, pmat_t&__restrict__ Tt,\n\t\t\t\t       pvec_t& work, ivec& iwork) {\n\t    using namespace std;\n\n\t    int info;\n\t    int lwork = work.size() - 10; //std::max(1024, int(in.rows()*in.rows()*in.rows()));\n\t    // pvec_t work(lwork);\n\t    // ivec iwork(std::max(1024, int(in.rows() * in.cols())));\n\n\t    char c = 'C';\n\t    char u = 'U';\n\t    char j = 'J';\n\t    char n = 'N';\n\t    char p = 'P';\n\t    int rows = U.rows();\n\t    int cols = U.cols();\n\t    int T_rows = Tt.rows();\n\n\t    work.setZero();\n\t    iwork.setZero();\n\t    // info = LAPACKE_dgejsv_work( 102, c, j, j, n, n, p, \n\t    // \t\t\t   rows, cols, in.data(), rows,\n\t    // \t\t\t   D.data(), U.data(), rows,\n\t    // \t\t\t   Tt.data(), T_rows, work.data(),\n\t    // \t\t\t\twork.size(),\n\t    // \t\t\t   iwork.data());\n\n\t    dgejsv_( &c, &u, &j, &n, &n, &p, // 6\n\t    \t     &rows, &cols, in.data(), &rows, //10\n\t    \t     D.data(), U.data(), &rows, // 13\n\t    \t     Tt.data(), &T_rows, work.data(),\n\t    \t     &lwork, iwork.data(), &info); // 17\n\t    // std::cout << info << std::endl;\n\t    return info;\n\t}\n\n       \n\tinline int decompose_jsvd_nt(pmat_t&__restrict__ in, pmat_t&__restrict__ U,\n\t\t\t\t     pvec_t&__restrict__ D, pmat_t&__restrict__ Tt) {\n\t    using namespace std;\n\n\t    char joba = 'G';\n\t    char jobu = 'U';\n\t    char jobv = 'V';\n\n\t    U = in;\n\n\t    int rows = in.rows();\n\t    int cols = in.cols();\n\t    int U_rows = in.rows();\n\t    int T_rows = Tt.rows();\n\n\t    int lwork = max(1024, rows * cols);\n\t    pvec_t work(lwork);\n\t    work.setOnes();\n\t    int mv = 0;\n\t    int info;\n\t    \n\t    dgesvj_(&joba, &jobu, &jobv, &rows, &cols, U.data(), &rows,\n\t\t    D.data(), &mv, Tt.data(), &T_rows, work.data(), &lwork, &info);\n\t\t\t  \n\t    if (work(0) != 1.) {\n\t\tcout << \"MKL ERROR: SVD HAVE TO BE SCALED! \" << work(0) << endl;\n\t\tthrow std::runtime_error(\"SVD Error\");\n\t    }\n\t    \n\t    return info;\n\t}\n\n\n\tinline int decompose_jsvd_nt(pmat_t&__restrict__ in, pmat_t&__restrict__ U,\n\t\t\t\t     pvec_t&__restrict__ D, pmat_t&__restrict__ Tt,\n\t\t\t\t     pvec_t&__restrict__ work) {\n\t    using namespace std;\n\n\t    char joba = 'G';\n\t    char jobu = 'U';\n\t    char jobv = 'V';\n\n\t    U = in;\n\n\t    int rows = in.rows();\n\t    int cols = in.cols();\n\t    int U_rows = in.rows();\n\t    int T_rows = Tt.rows();\n\n\t    int lwork = work.size();\n\t    //pvec_t work(lwork);\n\t    work.setOnes();\n\t    int mv = 0;\n\t    int info;\n\t    \n\t    dgesvj_(&joba, &jobu, &jobv, &rows, &cols, U.data(), &rows,\n\t\t    D.data(), &mv, Tt.data(), &T_rows, work.data(), &lwork, &info);\n\t\t\t  \n\t    if (work(0) != 1.) {\n\t\tcout << \"MKL ERROR: SVD HAVE TO BE SCALED! \" << work(0) << endl;\n\t\tthrow std::runtime_error(\"SVD Error\");\n\t    }\n\t    \n\t    return info;\n\t}\n\n\tinline perm_mat row_sort(mat&__restrict in, mat&__restrict out) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\t    vector<int> max_index(in.rows());\n\t    vector<max_pair> max_indices;\n\t    vec max_vals(in.rows());\n\t    for(int i = 0; i < in.rows(); ++i) {\n\t\tmax_vals(i) = in.cwiseAbs().row(i).maxCoeff( &max_index[i] );\n\t\tmax_indices.push_back(max_pair(max_vals(i), i));\n\t    }\n\t    std::sort(max_indices.begin(), max_indices.end(), comparator);\n\n\t    ivec row_ids(in.rows());\n\t    for (std::vector<max_pair>::iterator it=max_indices.begin(); it != max_indices.end(); ++it) {\n\t\trow_ids((*it).second) = std::distance(max_indices.begin(), it);\n\t\t// cout << row_ids((*it).second) <<  \" \";\n\t    }\n\t    // cout << endl;\n\t    perm_mat row_perm(row_ids);\n\t    \n\t    out = row_perm * in;\n\t    return row_perm;\n\t}\n\n\n\tinline perm_mat col_sort(mat&__restrict in, mat&__restrict out) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\t    vector<int> max_index(in.cols());\n\t    vector<max_pair> max_indices;\n\t    vec max_vals(in.cols());\n\t    for(int i = 0; i < in.cols(); ++i) {\n\t\tmax_vals(i) = in.cwiseAbs().col(i).maxCoeff( &max_index[i] );\n\t\tmax_indices.push_back(max_pair(max_vals(i), i));\n\t    }\n\t    std::sort(max_indices.begin(), max_indices.end(), comparator);\n\n\t    ivec col_ids(in.cols());\n\t    for (std::vector<max_pair>::iterator it=max_indices.begin();\n\t\t it != max_indices.end(); ++it) {\n\t\tcol_ids((*it).second) = std::distance(max_indices.begin(), it);\n\t\t// cout << row_ids((*it).second) <<  \" \";\n\t    }\n\t    // cout << endl;\n\t    perm_mat col_perm(col_ids);\n\t    \n\t    out = in * col_perm;\n\t    return col_perm;\n\t}\n\n\n\tinline void decompose_udt_full_piv(mat&__restrict__ in, mat&__restrict__ U, vec&__restrict__ D, mat&__restrict__ T) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\n\t    if (U.rows() != in.rows() || U.cols() != in.cols())\n\t\tthrow std::runtime_error(\"dimensions of U are wrong\");\n\t    \n\t    if (D.size() != in.cols()) {\n\t\tcout << D.size() << endl;\n\t\tthrow std::runtime_error(\"dimensions of D are wrong\");\n\t    }\n\t    \n\t    if (T.rows() != in.cols() || U.cols() != in.cols())\n\t\tthrow std::runtime_error(\"dimensions of T are wrong\");\n\n\t    double scale = pow(in.cwiseAbs().maxCoeff(), 0.5);\n\t    Eigen::FullPivHouseholderQR<mat> qr(in);\n\t    in /= scale;\n\t     \n\t    qr.compute(in);\n\t    U = qr.matrixQ().block(0, 0, in.rows(), in.cols());\n\t    mat upper = qr.matrixQR().triangularView<Upper>();// .block(0, 0, in.cols(), in.cols());\n\t    D = upper.block(0, 0, in.cols(), in.cols()).diagonal();\n\t    vec d_inv = D;\n\t    \n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tif (D(i) == 0.) {\t\t    \n\t\t    std::cout << \"culprit \" << D(i) << \" was \"\n\t\t\t      << upper(i, i) << std::endl;\n\t\t    throw std::runtime_error(\"Invalid upper triangle\"); }\t\n\t\td_inv(i) = 1./D(i);\n\t\tif (D(i) < 0) {\n\t\t    D(i) *= -1.;\n\t\t    d_inv(i) *= -1.; }\n\t    }\n\t    \n\t    T = (d_inv.asDiagonal() * upper.block(0, 0, in.cols(), in.cols()))\n\t\t* qr.colsPermutation().transpose();\n\t    D *= scale;\n\t    if (D(0) != D(0)) std::cout << \"NaN alert\" << endl;\n\t}\n\n\n\n\tinline void decompose_udt_full_sort(mat&__restrict__ in, mat&__restrict__ U, vec&__restrict__ D, mat&__restrict__ T) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\n\t    if (U.rows() != in.rows() || U.cols() != in.cols())\n\t\tthrow std::runtime_error(\"dimensions of U are wrong\");\n\t    \n\t    if (D.size() != in.cols()) {\n\t\tcout << D.size() << endl;\n\t\tthrow std::runtime_error(\"dimensions of D are wrong\");\n\t    }\n\t    \n\t    if (T.rows() != in.cols() || U.cols() != in.cols())\n\t\tthrow std::runtime_error(\"dimensions of T are wrong\");\n\n\t    mat scaled_in = mat::Zero(in.rows(), in.cols());\n\t    perm_mat row_perm = dqmc::la::row_sort(in, scaled_in);\n\t    perm_mat col_perm = dqmc::la::col_sort(scaled_in, in);\n\t    \n\t    // Very crude scaling...\n\t    double scale = pow(in.cwiseAbs().maxCoeff(), 0.5);\n\n\t    vec taus(in.cols());\n\t    ivec iwork(in.cols());\n\t    \n\t    // vec work(in.rows() * in.rows() * in.rows());\n\t    int lwork = -1;\n\t    int info = 0;\n\t    int M = in.rows();\n\t    int N = in.cols();\n\t    \n\t    scaled_in.block(0, 0, in.rows(), in.cols()) = in/scale;\n\t    iwork.setZero();\n\t    // cout << iwork.size() << \" \" << work.size() << \" \" << taus.size() << endl;\n\t    lwork = -1;\n\t    dgeqp3_(&M, &N, scaled_in.data(), &M, iwork.data(),\n\t\t    taus.data(), taus.data(),\n\t\t    &lwork, &info);\n\t    lwork = taus(0);\n\t    vec work(lwork);\n\t    work.setZero();\n\t    taus.setZero();\n\t    \n\t    dgeqp3_(&M, &N, scaled_in.data(), &M, iwork.data(),\n\t\t    taus.data(), work.data(),\n\t\t    &lwork, &info);\n\n\t    mat upper = scaled_in.triangularView<Upper>();\n\t    D = upper.block(0, 0, in.cols(), in.cols()).diagonal();\n\t    vec d_inv = D;\n\t    \n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tif (D(i) == 0.) {\t\t    \n\t\t    std::cout << \"culprit \" << D(i) << \" was \"\n\t\t\t      << upper(i, i) << std::endl;\n\t\t    throw std::runtime_error(\"Invalid upper triangle\"); }\t\n\t\td_inv(i) = 1./D(i);\n\t\tif (D(i) < 0) { D(i) *= -1.;\n\t\t    d_inv(i) *= -1.; }\n\t    }\n\t    lwork = -1;\n\t    dorgqr_(&M, &N, &N, scaled_in.data(), &M, taus.data(),\n\t\t    work.data(), &lwork, &info);\n\t    // if (work(0) > work.size()) {\n\t    // \tcout << \"Need more lwork for dorgqr\" << endl;\n\t    // }\n\t    lwork = work(0);\n\t    work.resize(lwork);\t    \n\t    // cout << \"in\" << endl << scaled_in << endl << endl;\n\t    dorgqr_(&M, &N, &N, scaled_in.data(), &M, taus.data(),\n\t\t    work.data(), &lwork, &info);\n\t    // cout << \"out\" << endl << scaled_in << endl << endl;\n\t    U = row_perm.inverse() * scaled_in.block(0, 0, in.rows(), in.cols());  \n\t    ivec col_ids(in.cols());\n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tcol_ids(i) = iwork(i) - 1;\n\t    }\n\t    \n\t    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> lapack_col_perm(col_ids);\n\t    T = (d_inv.asDiagonal() * upper.block(0, 0, in.cols(), in.cols()))\n\t\t* lapack_col_perm.transpose() * col_perm.transpose();\n\t    D *= scale;\n\t    if (D(0) != D(0)) std::cout << \"NaN alert\" << endl;\n\t}\n\t\n\tinline void decompose_udt_row_sort(mat&__restrict__ in, mat&__restrict__ U, vec&__restrict__ D, mat&__restrict__ T) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\n\t    if (U.rows() != in.rows() || U.cols() != in.cols())\n\t\tthrow std::runtime_error(\"dimensions of U are wrong\");\n\t    \n\t    if (D.size() != in.cols()) {\n\t\tcout << D.size() << endl;\n\t\tthrow std::runtime_error(\"dimensions of D are wrong\");\n\t    }\n\t    \n\t    if (T.rows() != in.cols() || U.cols() != in.cols())\n\t\tthrow std::runtime_error(\"dimensions of T are wrong\");\n\n\t    \n\t    vector<int> max_index(in.rows());\n\t    vector<max_pair> max_indices;\n\t    vec max_vals(in.rows());\n\t    for(int i = 0; i < in.rows(); ++i) {\n\t\tmax_vals(i) = in.cwiseAbs().row(i).maxCoeff( &max_index[i] );\n\t\tmax_indices.push_back(max_pair(max_vals(i), i));\n\t    }\n\t    std::sort(max_indices.begin(), max_indices.end(), comparator);\n\n\t    ivec row_ids(in.rows());\n\t    for (std::vector<max_pair>::iterator it=max_indices.begin(); it != max_indices.end(); ++it) {\n\t\trow_ids((*it).second) = std::distance(max_indices.begin(), it);\n\t\t// cout << row_ids((*it).second) <<  \" \";\n\t    }\n\t    // cout << endl;\n\t    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> row_perm(row_ids);\n\n\t    // Very crude scaling...\n\t    double scale = pow(in.cwiseAbs().maxCoeff(), 0.5);\n\n\t    vec taus(in.cols());\n\t    ivec iwork(in.cols());\n\t    \n\t    // vec work(in.rows() * in.rows() * in.rows());\n\t    int lwork = -1;\n\t    int info = 0;\n\t    int M = in.rows();\n\t    int N = in.cols();\n\t    mat scaled_in = mat::Zero(in.rows(), in.cols());\n\t    \n\t    scaled_in.block(0, 0, in.rows(), in.cols()) = (row_perm * in)/scale;\n\t    iwork.setZero();\n\t    // cout << iwork.size() << \" \" << work.size() << \" \" << taus.size() << endl;\n\t    lwork = -1;\n\t    dgeqp3_(&M, &N, scaled_in.data(), &M, iwork.data(),\n\t\t    taus.data(), taus.data(),\n\t\t    &lwork, &info);\n\t    lwork = taus(0);\n\t    vec work(lwork);\n\t    work.setZero();\n\t    taus.setZero();\n\t    \n\t    dgeqp3_(&M, &N, scaled_in.data(), &M, iwork.data(),\n\t\t    taus.data(), work.data(),\n\t\t    &lwork, &info);\n\n\t    mat upper = scaled_in.triangularView<Upper>();\n\t    D = upper.block(0, 0, in.cols(), in.cols()).diagonal();\n\t    vec d_inv = D;\n\t    \n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tif (D(i) == 0.) {\t\t    \n\t\t    std::cout << \"culprit \" << D(i) << \" was \"\n\t\t\t      << upper(i, i) << std::endl;\n\t\t    throw std::runtime_error(\"Invalid upper triangle\"); }\t\n\t\td_inv(i) = 1./D(i);\n\t\tif (D(i) < 0) { D(i) *= -1.;\n\t\t    d_inv(i) *= -1.; }\n\t    }\n\t    lwork = -1;\n\t    dorgqr_(&M, &N, &N, scaled_in.data(), &M, taus.data(),\n\t\t    work.data(), &lwork, &info);\n\t    // if (work(0) > work.size()) {\n\t    // \tcout << \"Need more lwork for dorgqr\" << endl;\n\t    // }\n\t    lwork = work(0);\n\t    work.resize(lwork);\t    \n\t    // cout << \"in\" << endl << scaled_in << endl << endl;\n\t    dorgqr_(&M, &N, &N, scaled_in.data(), &M, taus.data(),\n\t\t    work.data(), &lwork, &info);\n\t    // cout << \"out\" << endl << scaled_in << endl << endl;\n\t    U = row_perm.inverse() * scaled_in.block(0, 0, in.rows(), in.cols());  \n\t    ivec col_ids(in.cols());\n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tcol_ids(i) = iwork(i) - 1;\n\t    }\n\t    \n\t    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> col_perm(col_ids);\n\t    T = (d_inv.asDiagonal() * upper.block(0, 0, in.cols(), in.cols()))\n\t\t* col_perm.transpose();\n\t    D *= scale;\n\t    if (D(0) != D(0)) std::cout << \"NaN alert\" << endl;\n\t}\n\n\tinline void decompose_udt_row_sort_sqr_q(mat&__restrict__ in, mat&__restrict__ U, vec&__restrict__ D, mat&__restrict__ T) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\t    \n\t    vector<int> max_index(in.rows());\n\t    vector<max_pair> max_indices;\n\t    vec max_vals(in.rows());\n\t    for(int i = 0; i < in.rows(); ++i) {\n\t\tmax_vals(i) = in.cwiseAbs().row(i).maxCoeff( &max_index[i] );\n\t\tmax_indices.push_back(max_pair(max_vals(i), i));\n\t    }\n\t    std::sort(max_indices.begin(), max_indices.end(), comparator);\n\n\t    ivec row_ids(in.rows());\n\t    for (std::vector<max_pair>::iterator it=max_indices.begin(); it != max_indices.end(); ++it) {\n\t\trow_ids((*it).second) = std::distance(max_indices.begin(), it);\n\t\t// cout << row_ids((*it).second) <<  \" \";\n\t    }\n\t    // cout << endl;\n\t    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> row_perm(row_ids);\n\n\t    // Very crude scaling...\n\t    double scale = pow(in.cwiseAbs().maxCoeff(), 0.3);\n\n\t    vec taus(in.rows());\n\t    // vec work(in.rows() * in.rows() * in.rows());\n\t    int lwork = -1;\n\t    ivec iwork(in.rows());\n\t    int info = 0;\n\t    int M = in.rows();\n\t    int N = in.cols();\n\t    mat scaled_in = mat::Zero(in.rows(), in.rows());\n\t    \n\t    scaled_in.block(0, 0, in.rows(), in.cols()) = (row_perm * in)/scale;\n\t    iwork.setZero();\n\t    // cout << iwork.size() << \" \" << work.size() << \" \" << taus.size() << endl;\n\t    lwork = -1;\n\t    dgeqp3_(&M, &N, scaled_in.data(), &M, iwork.data(),\n\t\t    taus.data(), taus.data(),\n\t\t    &lwork, &info);\n\t    lwork = taus(0);\n\t    vec work(lwork);\n\t    dgeqp3_(&M, &N, scaled_in.data(), &M, iwork.data(),\n\t\t    taus.data(), work.data(),\n\t\t    &lwork, &info);\n\n\t    {\n\t\t{\t\t\n\t\t    mat upper = scaled_in.triangularView<Upper>();\n\t\t    D = upper.block(0, 0, in.cols(), in.cols()).diagonal();\n\t\t    vec d_inv = D;\n\t    \n\t\t    for (int i = 0; i < in.cols(); ++i) {\n\t\t\tif (D(i) == 0.) {\t\t    \n\t\t\t    std::cout << \"culprit \" << D(i) << \" was \"\n\t\t\t\t      << upper(i, i) << std::endl;\n\t\t\t    throw std::runtime_error(\"Invalid upper triangle\"); }\t\n\t\t\td_inv(i) = 1./D(i);\n\t\t\tif (D(i) < 0) { D(i) *= -1.;\n\t\t\t    d_inv(i) *= -1.; }\n\t\t    }\t    \t    \n\t\t    dorgqr_(&M, &M, &N, scaled_in.data(), &M, taus.data(),\n\t\t\t    work.data(), &lwork, &info);\n\t\t    U = row_perm.inverse() * scaled_in.block(0, 0, in.rows(), in.cols());  \n\t\t    ivec col_ids(in.cols());\n\t\t    for (int i = 0; i < in.cols(); ++i) {\n\t\t\tcol_ids(i) = iwork(i) - 1;\n\t\t    }\n\t    \n\t\t    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> col_perm(col_ids);\n\t\t    T = (d_inv.asDiagonal() * upper.block(0, 0, in.cols(), in.cols()))\n\t\t\t* col_perm.transpose();\n\t\t    D *= scale;\n\t\t    if (D(0) != D(0)) std::cout << \"NaN alert\" << endl;\n\t\t}\n\t    }\t    \n\t}\n\n#ifdef USE_DD\n\tinline void decompose_udt_row_sort_dd(mat&__restrict__ in, mat&__restrict__ U, vec&__restrict__ D, mat&__restrict__ T) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\t    \n\t    vector<int> max_index(in.rows());\n\t    vector<max_pair> max_indices;\n\t    vec max_vals(in.rows());\n\t    for(int i = 0; i < in.rows(); ++i) {\n\t\tmax_vals(i) = in.cwiseAbs().row(i).maxCoeff( &max_index[i] );\n\t\tmax_indices.push_back(max_pair(max_vals(i), i));\n\t    }\n\t    std::sort(max_indices.begin(), max_indices.end(), comparator);\n\n\t    ivec row_ids(in.rows());\n\t    for (std::vector<max_pair>::iterator it=max_indices.begin(); it != max_indices.end(); ++it) {\n\t\trow_ids((*it).second) = std::distance(max_indices.begin(), it);\n\t\t// cout << row_ids((*it).second) <<  \" \";\n\t    }\n\t    // cout << endl;\n\t    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> row_perm(row_ids);\n\n\t    // Very crude scaling...\n\t    double scale = pow(in.cwiseAbs().maxCoeff(), 0.5);\n\n\t    vec taus(in.rows());\n\t    // vec work(in.rows() * in.rows() * in.rows());\n\t    int lwork = -1;\n\t    ivec iwork(in.rows());\n\t    int info = 0;\n\t    int M = in.rows();\n\t    int N = in.cols();\n\t    mat temp = mat::Zero(in.rows(), in.cols());\n\t    dd_mat dd_temp = dd_mat::Zero(in.cols(), in.cols());\n\t    dd_mat scaled_in = dd_mat::Zero(in.rows(), in.cols());\n\t    temp = ((row_perm * in)/scale);\n\t    scaled_in.block(0, 0, in.rows(), in.cols()) = temp.cast<ddouble>();\n\t    Eigen::FullPivHouseholderQR<dd_mat> qr(scaled_in);\n\t    // cout << scaled_in << endl << endl;\n\t    qr.compute(scaled_in);\n\t    dd_temp = qr.matrixQR().block(0, 0, in.cols(), in.cols()).triangularView<Upper>();\n\t    mat upper = mat::Zero(in.cols(), in.cols());\t    \n\t    // cout << \"from dd_temp\" << endl << endl << upper << endl << endl;\n\t    // cout << dd_temp.rows() << \" x \" << dd_temp.cols() << \" - \" <<\n\t    // \tupper.rows() << \" x \" << upper.cols() << endl;\n\t    dqmc::la::copy_from_dd(dd_temp, upper);\n\t    // cout << \"from dd_temp\" << endl << endl << upper << endl << endl;\n\t    D = upper.block(0, 0, in.cols(), in.cols()).diagonal();\n\t    vec d_inv = D;\n\t    \n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tif (D(i) == 0.) {\t\t    \n\t\t    std::cout << \"culprit \" << D(i) << \" was \"\n\t\t\t      << upper(i, i) << std::endl;\n\t\t    throw std::runtime_error(\"Invalid upper triangle\"); }\t\n\t\td_inv(i) = 1./D(i);\n\t\tif (D(i) < 0) { D(i) *= -1.;\n\t\t    d_inv(i) *= -1.; }\n\t    }\t    \t    \n\t    //dd_mat qrQ  = qr.householderQ();\n\t    dd_mat qrQ  = qr.matrixQ();\n\t    dd_temp = qrQ.block(0, 0, in.rows(), in.cols());\n\n\t    dqmc::la::copy_from_dd(dd_temp, temp);\n\t    // temp = dd_temp.cast<double>();\n\t    U = row_perm.inverse() * temp;\n\t    \n\t    T = (d_inv.asDiagonal() * upper.block(0, 0, in.cols(), in.cols()))\n\t\t* qr.colsPermutation().transpose();\n\t    D *= scale;\n\t    if (D(0) != D(0)) std::cout << \"NaN alert\" << endl;\n\t}\n#endif\n\t\n\tinline void decompose_udt_row_sort(mat &__restrict__ in, mat &__restrict__ U, vec &__restrict__ D, mat &__restrict__ T,\n\t\t\t\t\t   mat &__restrict__ scaled_in, mat &__restrict__ T_temp,\t\t\t\t\t   \n\t\t\t\t\t   ivec &__restrict__ row_ids, ivec &__restrict__ col_ids,\n\t\t\t\t\t   ivec &__restrict__ max_index, vec &__restrict__ max_vals, std::vector<max_pair>& max_pairs,  \n\t\t\t\t\t   vec &__restrict__ taus, vec &__restrict__ work_old, ivec &__restrict__ iwork_old ) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\n\t    max_pairs.clear();\t    \n\t    for(int i = 0; i < in.rows(); ++i) {\n\t\tmax_vals(i) = in.cwiseAbs().row(i).maxCoeff( &max_index(i) );\n\t\tmax_pairs.push_back(max_pair(max_vals(i), i));\n\t\t// cout << i << endl;\n\t    }\n\n\t    // for (std::vector<max_pair>::iterator it=max_pairs.begin(); it != max_pairs.end(); ++it) {\n\t    // \trow_ids((*it).second) = std::distance(max_pairs.begin(), it);\n\t    // \tcout << (*it).second << \" | \" << std::distance(max_pairs.begin(), it) << \"   \";\n\t    // }\n\t    // cout << endl;\n\n\t    std::sort(max_pairs.begin(), max_pairs.end(), comparator);\n\t    // cout << \"Sorted\" << endl;\n\t    // cout << row_ids.size();\n\t    for (std::vector<max_pair>::iterator it=max_pairs.begin(); it != max_pairs.end(); ++it) {\n\t\trow_ids((*it).second) = std::distance(max_pairs.begin(), it);\n\t\t// cout << (*it).second << \" | \" << std::distance(max_pairs.begin(), it) << \"   \";\n\t    }\n\t    // cout << endl;\n\t    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> row_perm(row_ids);\n\t    // cout << \"permutation\" << endl;\n\n\t    \n\t    // Very crude scaling...\n\t    double scale = pow(in.cwiseAbs().maxCoeff(), 0.3);\n\t    int lwork; // = work.size();\n\t    // vec work(in.rows() * in.rows() * in.rows());\n\t    // int lwork = work.size();\n\n\t    int info = 0;\n\t    int M = in.rows();\n\t    int N = in.cols();\n\t    ivec iwork(in.cols());\n\n\t    // cout << \"Scaled\" << endl;\n\t    // cout << row_perm.indices().transpose() << endl << endl;\n\t    // cout << row_perm.toDenseMatrix() << endl << endl;\n\t    // cout << in << endl << endl;\n\t    {\n\t\t{\n\t\t    scaled_in = (row_perm * in)/scale;\n\t\t    // cout << scaled_in << endl << endl;\n\t\t    iwork.setZero();\n\t\t    // cout << \"QRing\" << endl;\t\t    \n\t\t    // cout << iwork.size() << \" \" << work.size() << \" \" << taus.size() << endl;\n\t\t    // ivec iwork(4*in.rows());\n\t\t    lwork = -1;\n\t\t    dgeqp3_(&M, &N, scaled_in.data(), &M, iwork.data(),\n\t\t\t    taus.data(), taus.data(),\n\t\t\t    &lwork, &info);\n\t\t    lwork = taus(0);\n\t\t    vec work(lwork);\n\n\t\t    dgeqp3_(&M, &N, scaled_in.data(), &M, iwork.data(),\n\t\t\t    taus.data(), work.data(),\n\t\t\t    &lwork, &info);\t\t    \n\t\t}\n\t    }\n\t    {\n\t\t{\n\t\t\n\t\t    // cout << \"To zero!\" << endl;\n\t\t    // cout << \"Getting diagonal\" << endl;\n\t\t    D = scaled_in.diagonal();\n\t\t    vec d_inv = D;\n\t\t    // cout << \"Gitgotthat\" << endl;\n\t    \n\t\t    for (int i = 0; i < in.cols(); ++i) {\n\t\t\tif (D(i) == 0.) {\t\t    \n\t\t\t    std::cout << \"culprit \" << D(i) << std::endl;\n\t\t\t    throw std::runtime_error(\"Invalid upper triangle\"); }\n\t\t\n\t\t\td_inv(i) = 1./D(i);\n\t\t\tif (D(i) < 0) { D(i) *= -1.;\n\t\t\t    d_inv(i) *= -1.; }\n\t\t    }\t    \t    \n\t    \n\t\t    for (int i = 0; i < in.cols(); ++i) col_ids(i) = iwork(i) - 1;\t    \n\t\t    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> col_perm(col_ids);\n\t\t    T_temp = scaled_in.triangularView<Upper>();\n\t\t    T = (d_inv.asDiagonal() * T_temp) * col_perm.transpose();\n\t\t    // cout << T << endl << endl;\n\n\t\t    D *= scale;\n\t\t    if (D(0) != D(0)) std::cout << \"NaN alert\" << endl;\n\t\t    lwork = -1;\n\t\t    dorgqr_(&M, &M, &N, scaled_in.data(), &M, taus.data(), taus.data(), &lwork, &info);\n\t\t    lwork = taus(0);\n\t\t    vec work(lwork);\n\t\t    dorgqr_(&M, &M, &N, scaled_in.data(), &M, taus.data(), work.data(), &lwork, &info);\n\t\t    U = row_perm.inverse() * scaled_in;\n\t\t}\n\t    }\n\t    return;\n\t}\n\n\n\tinline void decompose_udt_col_piv(mat&__restrict__ in,\n\t\t\t\t\t  mat&__restrict__ U,\n\t\t\t\t\t  vec&__restrict__ D,\n\t\t\t\t\t  mat&__restrict__ T) {\n\t    using namespace std;\n\t    using namespace Eigen;\n\t    if (U.rows() != in.rows() || U.cols() != in.cols() || U.cols() == 0) {\n\t\tcout << U.rows() << \" \" << U.cols() << endl;\n\t\tthrow std::runtime_error(\"dimensions of U are wrong\");\n\t    }\n\t    \n\t    if (D.size() != in.cols() || D.size() == 0) {\n\t\tcout << D.size() << endl;\n\t\tthrow std::runtime_error(\"dimensions of D are wrong\");\n\t    }\n\t    \n\t    if (T.rows() != in.cols() || T.cols() == 0)\n\t\tthrow std::runtime_error(\"dimensions of T are wrong\");\n\n\t    \n\t    mat_t scaled_in = mat_t::Zero(in.rows(), in.cols());\n\n\t    vec_t taus(in.cols());\n\t    ivec iwork(in.cols());\n\t    \n\t    int lwork = -1;\n\t    int M = in.rows();\n\t    int N = in.cols();\n\t    \n\t    perm_mat row_sort_perm = row_sort(in, scaled_in);\n\t    // scaled_in.block(0, 0, in.rows(), in.cols()) = in;\n\t    iwork.setZero();\n\t    lapack_int info = LAPACKE_dgeqp3( LAPACK_COL_MAJOR, M, N, scaled_in.data(),\n\t\t\t\t\t      M, iwork.data(), taus.data() );\n\t    \n\t    mat_t upper = scaled_in.triangularView<Upper>();\n\t    D = upper.block(0, 0, in.cols(), in.cols()).diagonal();\n\t    vec d_inv = D;\n\t    \n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tif (D(i) == 0.) {\t\t    \n\t\t    // std::cout << \"culprit \" << D(i) << \" was \"\n\t\t    // \t      << upper(i, i) << std::endl;\n\t\t    throw std::runtime_error(\"Invalid upper triangle\"); }\t\n\t\td_inv(i) = 1./D(i);\n\t\tif (D(i) < 0) { D(i) *= -1.;\n\t\t    d_inv(i) *= -1.; }\n\t    }\n\t    lwork = -1;\n\n\t    info = LAPACKE_dorgqr( LAPACK_COL_MAJOR, M, N, N,\n\t\t\t\t   scaled_in.data(), M, taus.data() );\n\n\t    U = (row_sort_perm.inverse() * scaled_in).block(0, 0, in.rows(), in.cols());  \n\t    ivec col_ids(in.cols());\n\t    for (int i = 0; i < in.cols(); ++i) {\n\t\tcol_ids(i) = iwork(i) - 1;\n\t\tif (col_ids(i) == -1) {\n\t\t    dqmc::tools::abort(\"Permutation fails\");\n\t\t}\n\t    }\n\t    Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> lapack_col_perm(col_ids);\n\t    \n\t    T = (d_inv.asDiagonal()\n\t\t * upper.block(0, 0, in.cols(), in.cols()))\n\t\t* lapack_col_perm.transpose();\n\t    if (D(0) != D(0)) std::cout << \"NaN alert\" << endl;\n\t}\n\n    }\n}\n#endif\n", "meta": {"hexsha": "2d5f146724337c2b40ee31207c9dbbf987e20c5f", "size": 27209, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libdqmc/la/svd.hpp", "max_stars_repo_name": "pebroecker/DQMC", "max_stars_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libdqmc/la/svd.hpp", "max_issues_repo_name": "pebroecker/DQMC", "max_issues_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libdqmc/la/svd.hpp", "max_forks_repo_name": "pebroecker/DQMC", "max_forks_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6638655462, "max_line_length": 124, "alphanum_fraction": 0.5340879856, "num_tokens": 8537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.44395897166577514}}
{"text": "/*\n * Copyright (c) 2019 Opticks Team. All Rights Reserved.\n *\n * This file is part of Opticks\n * (see https://bitbucket.org/simoncblyth/opticks).\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); \n * you may not use this file except in compliance with the License.  \n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software \n * distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  \n * See the License for the specific language governing permissions and \n * limitations under the License.\n */\n\n#include <iomanip>\n#include <cassert>\n\n#include \"NPY.hpp\"\n#include \"GLMPrint.hpp\"\n#include \"GLMFormat.hpp\"\n\n#include \"Camera.hh\"\n#include \"View.hh\"\n\n\n#include \"OPTICKS_LOG.hh\"\n#include \"Opticks.hh\"\n#include \"Composition.hh\"\n\n\n\n#include <boost/math/constants/constants.hpp>\n\nvoid test_rotate()\n{\n    glm::vec3 X(1,0,0);\n    glm::vec3 Y(0,1,0);\n    glm::vec3 Z(0,0,1);\n\n    float angle = 0.f ; \n    for(unsigned int i=0 ; i < 6 ; i++)\n    {\n        switch(i)\n        {\n            case 0:angle = 0.f ; break;   \n            case 1:angle = 30.f ; break;   \n            case 2:angle = 45.f ; break;   \n            case 3:angle = 60.f ; break;   \n            case 4:angle = 90.f ; break;   \n            case 5:angle = 180.f ; break;   \n        }\n\n        float pi = boost::math::constants::pi<float>() ;\n        float a = angle*pi/180. ; \n        printf(\" angle %10.4f a %10.4f \\n\", angle, a );\n\n        glm::mat4 rotX = glm::rotate(glm::mat4(1.0), a, X );\n        glm::mat4 rotY = glm::rotate(glm::mat4(1.0), a, Y );\n        glm::mat4 rotZ = glm::rotate(glm::mat4(1.0), a, Z );\n\n        glm::mat4 irotX = glm::transpose(rotX);\n        glm::mat4 irotY = glm::transpose(rotY);\n        glm::mat4 irotZ = glm::transpose(rotZ);\n\n        print(rotX, \"rotX\"); \n        print(irotX, \"irotX\"); \n\n        print(rotY, \"rotY\"); \n        print(irotY, \"irotY\"); \n\n        print(rotZ, \"rotZ\"); \n        print(irotZ, \"irotZ\"); \n\n   }\n}\n\n\n\nvoid test_center_extent(Opticks* ok)\n{\n   NPY<float>* dom = NPY<float>::load(\"domain\", \"1\", \"dayabay\");\n   if(!dom) return ; \n\n   dom->dump();\n   glm::vec4 ce = dom->getQuad(0,0);\n   print(ce, \"ce\");\n\n   Composition c(ok) ; \n   c.setCenterExtent(ce);\n   c.update();\n   c.dumpAxisData();\n}\n\n\nvoid test_depth(Opticks* ok)\n{\n   Composition* comp = new Composition(ok) ;\n   View* view = comp->getView();\n   Camera* cam = comp->getCamera();\n\n   float s = 100.0 ; \n\n   glm::vec4 ce(0.,0.,0.,s);\n\n    // extent normalized inputs to view\n   view->setEye(-1,0,0) ;   \n   view->setLook(0,0,0) ;\n   view->setUp(0,1,0) ;\n\n   bool autocam ;  \n   comp->setCenterExtent(ce, autocam=true );\n\n   cam->Summary(\"test_depth cam\");\n   view->Summary(\"test_depth view\");\n\n   glm::vec4 vp = comp->getViewpoint();\n   glm::vec4 lp = comp->getLookpoint();\n   glm::vec4 gaze = comp->getGaze();\n   glm::vec4 front = glm::normalize(gaze);\n\n   print(vp, \"viewpoint\");\n   print(lp, \"lookpoint\");\n   print(gaze, \"gaze\");\n   print(front, \"front\");\n\n\n   comp->update();\n\n   glm::vec4 zproj ; \n   cam->fillZProjection(zproj);\n\n   print(zproj, \"zproj\");\n\n   //unsigned int ix = cam->getWidth()/2 ;  \n   //unsigned int iy = cam->getHeight()/2 ;  \n   float near = cam->getNear();\n   float far  = cam->getFar();\n\n   std::cout\n        << \" near \" << near \n        << \" far \" << far\n        << std::endl ;  \n  \n\n   std::cout << \" step along the gaze direction, from near to far  \" << std::endl ; \n   // (world frame : X axis from -100 to 0)\n   // (eye frame   : Z axis from    0 to -100 ) \n\n   int N = 20 ;\n   for(int i=0 ; i <= N ; i++)\n   {\n       float t = near + (far - near)*float(i)/float(N)  ;\n\n       const glm::vec4 p_world = vp + front*t ;\n       const glm::vec4 p_eye = comp->transformWorldToEye(p_world);\n       const glm::vec3 p_ndc = comp->getNDC(p_world); \n       const glm::vec3 p_ndc2 = comp->getNDC2(p_world); \n\n       float eyeDist = p_eye.z ;   // from eye frame definition, this is general\n       assert(eyeDist <= 0.f ); \n       float ndc_z = -zproj.z - zproj.w/eyeDist ;     // range -1:1 for visibles\n       float ndc_z2 = comp->getNDCDepth(p_world); \n\n\n       float clip_z = 0.5f*ndc_z + 0.5f ;             // range  0:1 \n       float depth = clip_z ; \n       float clip_z2 = comp->getClipDepth(p_world);\n\n       glm::vec3 unp = comp->unProject(0,0,-depth); // ix,iy ??\n\n       std::cout << \" t \" << std::setw(5) << t\n                 << \" p_world \" << std::setw(30) << gformat(p_world)\n                 << \" p_eye   \" << std::setw(30) << gformat(p_eye)\n                 << \" p_ndc \" << std::setw(30) << gformat(p_ndc)\n                 << \" p_ndc2 \" << std::setw(30) << gformat(p_ndc2)\n                 << \" eyeDist \" << std::setw(8) << eyeDist\n                 << \" ndc_z \" << std::setw(8) << ndc_z\n                 << \" ndc_z2 \" << std::setw(8) << ndc_z2\n                 << \" clip_z \" << std::setw(8) << clip_z\n                 << \" clip_z2 \" << std::setw(8) << clip_z2\n                 << \" unp   \" << std::setw(20) << gformat(unp)\n                 << std::endl ; \n\n   } \n}\n\n\n\n\n\n/*\n\nw2m\n   scale+translate 3D object of arbitrary center/extent into unit box \n\n\n      m2w 500.000   0.000   0.000   0.000 \n            0.000 500.000   0.000   0.000 \n            0.000   0.000 500.000   0.000 \n          100.000 100.000 100.000   1.000 \n\n      w2m   0.002   0.000   0.000   0.000 \n            0.000   0.002   0.000   0.000 \n            0.000   0.000   0.002   0.000 \n           -0.200  -0.200  -0.200   1.000 \n\n\n*/\n\n\nvoid test_setCenterExtent()\n{\n    glm::vec4 ce(100.,100.,100.,500.);\n    glm::vec3 sc(ce.w);              // scale factor from 1 to extent\n    glm::vec3 tr(ce.x, ce.y, ce.z);  // translation from origin to center\n\n    glm::vec3 isc(1.f/ce.w);\n\n    glm::mat4 m_model_to_world = glm::scale( glm::translate(glm::mat4(1.0), tr), sc); \n\n    glm::mat4 m_world_to_model = glm::translate( glm::scale(glm::mat4(1.0), isc), -tr); \n \n\n    glm::mat4 check = m_world_to_model * m_model_to_world ;\n\n    print(m_model_to_world, \"m_model_to_world\");\n    print(m_world_to_model, \"m_world_to_model\");\n    print(check, \"check\");\n\n\n   std::cout << gpresent(\"m2w\", m_model_to_world ) << std::endl ; \n   std::cout << gpresent(\"w2m\", m_world_to_model ) << std::endl ; \n\n\n   std::vector<glm::vec4> world ;\n   world.push_back( { ce.x       , ce.y        , ce.z       , 1.0 } );\n   world.push_back( { ce.x + ce.w, ce.y + ce.w,  ce.z + ce.w, 1.0 } );\n   world.push_back( { ce.x - ce.w, ce.y - ce.w,  ce.z - ce.w, 1.0 } );\n\n   for(unsigned i=0 ; i < world.size() ; i++)\n   {\n       const glm::vec4& wpos = world[i] ; \n\n       glm::vec4 mpos = m_world_to_model * wpos ; \n\n       std::cout \n               << gpresent(\"w\", wpos ) \n               << gpresent(\"m\", mpos ) \n               << std::endl ; \n\n\n   }\n\n\n\n\n}\n\n\n\n\nint main(int argc, char** argv)\n{\n    OPTICKS_LOG(argc, argv); \n\n    Opticks ok(argc, argv); \n    ok.configure(); \n\n\n   //test_rotate();\n   //test_center_extent(&ok);\n   test_setCenterExtent();\n   //test_depth(&ok);\n\n    \n   return 0 ;\n}\n\n", "meta": {"hexsha": "00bce8c753864c4899da6ee005b74e51279dbcc7", "size": 7162, "ext": "cc", "lang": "C++", "max_stars_repo_path": "optickscore/tests/CompositionTest.cc", "max_stars_repo_name": "seriksen/opticks", "max_stars_repo_head_hexsha": "2173ea282bdae0bbd1abf4a3535bede334413ec1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T06:55:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-13T06:55:49.000Z", "max_issues_repo_path": "optickscore/tests/CompositionTest.cc", "max_issues_repo_name": "seriksen/opticks", "max_issues_repo_head_hexsha": "2173ea282bdae0bbd1abf4a3535bede334413ec1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optickscore/tests/CompositionTest.cc", "max_forks_repo_name": "seriksen/opticks", "max_forks_repo_head_hexsha": "2173ea282bdae0bbd1abf4a3535bede334413ec1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2183098592, "max_line_length": 88, "alphanum_fraction": 0.5421669925, "num_tokens": 2292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4439340217803158}}
{"text": "// Std includes\n#include <cmath>\n#include <iostream>\n#include <memory>\n// Thirdparties includes\n#include <Eigen/Dense>\n// Lib includes\n#include \"s0s/runge_kutta_fehlberg.h\"\n#include \"sl0/point.h\"\n#include \"sl0/chain/dynamic.h\"\n// Simple includes\n#include \"flow.h\"\n\nusing TypeScalar = double;\n// State\ntemplate<int Size>\nusing TypeVector = Eigen::Matrix<TypeScalar, Size, 1>;\n// Space\nconstexpr unsigned int DIM = 2;\nusing TypeSpaceVector = Eigen::Matrix<TypeScalar, DIM, 1>;\n// Ref and View\ntemplate<typename ...Args>\nusing TypeRef = Eigen::Ref<Args...>;\ntemplate<typename ...Args>\nusing TypeView = Eigen::Map<Args...>;\n// Group Parameters\nusing TypeStepPoint = sl0::StepPoint<TypeVector, DIM, TypeView, Flow>;\n// Solver\nusing TypeSolver = s0s::SolverRungeKuttaFehlberg<TypeVector<-1>, TypeView>;\n\nconst unsigned int np = 11;\n\nint main () { \n    // Parameters\n    TypeSpaceVector x0 = TypeSpaceVector::Zero();\n    TypeScalar t0 = 0.0;\n    TypeScalar dt = 1e-3;\n    unsigned int nt = std::round(1.0 / dt);\n    double dl = 0.1;\n    double l = 1.0;\n    // Create chain\n    std::shared_ptr<TypeStepPoint> sStepPoint = std::make_shared<TypeStepPoint>(std::make_shared<Flow>());\n    sl0::ChainDynamic<TypeVector, DIM, TypeView, TypeRef, TypeStepPoint, TypeSolver> chain(sStepPoint, dl, 4);\n    // Init\n    for(std::size_t i = 0; i < np; i++) {\n        chain.sStep->addMember(chain.state);\n        sStepPoint->x(chain.sStep->memberState(chain.state.data(), i)) = x0;\n        sStepPoint->x(chain.sStep->memberState(chain.state.data(), i))[0] += i * dl;\n    }\n    std::cout << \"Init Length : \" << \"\\n\" << chain.sStep->length(chain.state.data()) << \"\\n\";\n    std::cout << \"Init Size : \" << \"\\n\" << chain.sStep->size() << \"\\n\";\n    chain.t = t0;\n    // Computation\n    std::cout << \"Computing\" << \"\\n\";\n    for(std::size_t i = 0; i < nt; i++) {\n        chain.update(dt);\n    }\n    // out\n    std::cout << \"\\n\";\n    std::cout << \"Chain advected following a an exponential flow, exp(\" << chain.t << \") = \" << \"\\n\";\n    std::cout << \"\\n\";\n    std::cout << \"Final Length : \" << \"\\n\" << chain.sStep->length(chain.state.data()) << \"\\n\";\n    std::cout << \"Final Size : \" << \"\\n\" << chain.sStep->size() << \"\\n\";\n    std::cout << std::endl;\n}\n\n", "meta": {"hexsha": "d4f62efc8aeb4f36f6f2017e8bbb977fd82750d1", "size": 2224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/chain/dynamic/main.cpp", "max_stars_repo_name": "C0PEP0D/sl0", "max_stars_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/chain/dynamic/main.cpp", "max_issues_repo_name": "C0PEP0D/sl0", "max_issues_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/chain/dynamic/main.cpp", "max_forks_repo_name": "C0PEP0D/sl0", "max_forks_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1940298507, "max_line_length": 110, "alphanum_fraction": 0.6200539568, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.44384358802094187}}
{"text": "//#ifndef AMPAR_GILLESPIE_CLASS_HPP_INCLUDED\n//#define AMPAR_GILLESPIE_CLASS_HPP_INCLUDED\n\n#include <iostream>\n#include <stdlib.h>\n#include <cmath>\n#include <vector>\n#include <ctime>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/generator_iterator.hpp>\n#include <boost/random/linear_congruential.hpp>\n\n#include \"astron_utility_functions.hpp\"\n#include \"stl_vector_operation_functions.hpp\"\n#include \"boost_vector_matrix_operation_functions.hpp\"\n\nnamespace bno=boost::numeric::odeint;\nnamespace bnu=boost::numeric::ublas;\n\ntypedef double value_type;\ntypedef bnu::matrix< value_type > matrix_type;\n\nclass stochastic_ampar\n{\n   private:\n      unsigned int seed;\n      boost::minstd_rand rng;   //Boost random number generator\n      boost::uniform_real<double> uni_dist;   //Uniform random number distribution which produces values b/w 0 and 1 (0 inclusive, 1 exlusive).\n      boost::variate_generator<boost::minstd_rand&, boost::uniform_real< double> > uni_rand;// variate generator\n      //--------------\n      double kf1 = 4.59E06;    //M^-1 S^-1\n      double kb1 = 4.26E03;    //S^-1\n      double kf2 = 28.4E06;    //M^-1 * S^-1\n      double kb2 = 3.26E03;    //S^-1\n      double kf3 = 1.27E06;    //M^-1 S^-1\n      double kb3 = 45.7;       //S^-1\n      double a0 = 4.24E03;     //S^-1\n      double b0 = 900.0;       //S^-1\n      double a1 = 2.89E03;     //S^-1\n      double b1 = 39.2;        //S^-1\n      double a2 = 172.0;       //S^-1\n      double b2 = 0.727;       //S^-1\n      double a3 = 17.7;        //S^-1\n      double b3 = 4.0;         //S^-1\n      double a4 = 16.8;        //S^-1\n      double b4 = 190.4;       //S^-1\n      double Volume = 1.0;\n   public:\n      //Construct vectors\n      matrix_type X;       // A matrix to hold the states\n      matrix_type P;       // A matrix that holds the probability at time t\n      matrix_type T;       // The transition probability matrix\n      matrix_type Q;       // The infinitly small matrix, Q matrix\n      /* stochastic_ampar class constructor */\n      stochastic_ampar(matrix_type X_, unsigned int seed_=std::time(0)):   seed(seed_),\n                                                                        uni_dist(boost::uniform_real<double>(0,1)),\n                                                                        uni_rand(boost::variate_generator<boost::minstd_rand&, boost::uniform_real<double> >(rng, uni_dist)),\n                                                                        X(X_)\n      {\n         rng.seed(seed);\n         std::vector<double> Tv;\n         Tv = {\n      };\n      //------------------ Function declarations\n      void operator() (  matrix_type &p, matrix_type &dpdt , const double  t )\n      {\n         dpdt = bnu::prod(p,Q);\n      };\n};\nint main(int argc, char **argv)\n{\n   matrix_type mat(3,2);\n   mat(2,1) = 32;\n   stochastic_ampar test(mat);\n   std::cout << test.X << std::endl;\n}\n\n", "meta": {"hexsha": "584346cffcab629914ecb99098503420913f1549", "size": 3094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/ampar_stochastic_ode.cpp", "max_stars_repo_name": "anupgp/astron", "max_stars_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/old/src/old/ampar_stochastic_ode.cpp", "max_issues_repo_name": "anupgp/astron", "max_issues_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/old/src/old/ampar_stochastic_ode.cpp", "max_forks_repo_name": "anupgp/astron", "max_forks_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4, "max_line_length": 173, "alphanum_fraction": 0.5795087266, "num_tokens": 835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940926, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.44383908888403417}}
{"text": "#include <QApplication>\n\n#include <boost/qvm/all.hpp>\n#include \"qvm_eigen.h\"\n#include \"qvm_osg.h\"\n\n//#include \"rtcvImage.h\"\n\n#include \"Roi3DF_osg.h\"\n\n#include \"QtOsgWidget.h\"\n#include \"OsgGeometryManager.h\"\n#include \"osg_utils.h\"\n\n#include \"DisplayableAreaLights.h\"\n#include \"DisplayableCameras.h\"\n#include \"DisplayableCoordinateSystem.h\"\n#include \"DisplayableGrid.h\"\n\n#include \"CoordinateTransform.h\"\n#include \"CoordinateSystem.h\"\n\n#include \"Camera.h\"\n#include \"Rotation.h\"\n\n#include \"commonTypes.h\"\n\nstruct UnrealTag {};\n\nusing UnrealCoordinateSystem = CoordinateSystem<3, ScalarType, UnrealTag>;\n\nusing UnrealVector = NamedType<UnrealCoordinateSystem::Vector, UnrealCoordinateSystem, VectorTypeSkills>;\nusing UnrealTransform = NamedType<UnrealCoordinateSystem::AffineTransform, UnrealCoordinateSystem>;\n\nusing UnrealToWorld = CoordinateTransform<UnrealCoordinateSystem, WorldCoordinateSystem>;\n\nusing UnrealRotation = Rotation<UnrealCoordinateSystem>;\n\n\nUnrealTransform getCameraTransformation_ue(Degrees yaw, Degrees pitch, Degrees roll)\n{\n\tconst Radians angle_rotZ = deg2rad<ScalarType>(yaw);\n\tconst Radians angle_rotY = deg2rad<ScalarType>(pitch);\n\tconst Radians angle_rotX = deg2rad<ScalarType>(roll);\n\n\tconst float cZ = cos(angle_rotZ.get());\n\tconst float cY = cos(angle_rotY.get());\n\tconst float cX = cos(angle_rotX.get());\n\n\tconst float sZ = sin(angle_rotZ.get());\n\tconst float sY = sin(angle_rotY.get());\n\tconst float sX = sin(angle_rotX.get());\n\n\tMatrix33 mat_rotZ;\n\tMatrix33 mat_rotX;\n\tMatrix33 mat_rotY;\n\n\tmat_rotZ <<\n\t\tcZ , -sZ , 0 ,\n\t\tsZ , cZ , 0 ,\n\t\t0 , 0 , 1;\n\n\tmat_rotY <<\n\t\tcY , 0 , -sY ,\n\t\t0 , 1 , 0 ,\n\t\tsY , 0 , cY;\n\n\tmat_rotX <<\n\t\t1 , 0 , 0 ,\n\t\t0 , cX , sX ,\n\t\t0 , -sX , cX;\n\n\tMatrix33 mat_rot = mat_rotZ * mat_rotY * mat_rotX;\n\n\treturn UnrealTransform(Transform(mat_rot));\n}\n\n\nCameraGeometry::Info makeInfo(const Camera<WorldCoordinateSystem> & cam)\n{\n\tusing namespace boost::qvm;\n\n\tusing Size = Camera<WorldCoordinateSystem>::Size;\n\n\tconst osg::Vec3 origin = convert_to<osg::Vec3>(cam.getOrigin().get());\n\n\tconst Size imageSize = cam.getImageSize();\n\n\tconst ImagePoint topLeft = make_named<ImagePoint>(0, 0);\n\tconst ImagePoint topRight = make_named<ImagePoint>(imageSize(0), 0);\n\tconst ImagePoint bottomLeft = make_named<ImagePoint>(0, imageSize(1));\n\tconst ImagePoint bottomRight = make_named<ImagePoint>(imageSize(0), imageSize(1));\n\n\tconst ViewRay<WorldCoordinateSystem> dir_topLeft = cam.imageToWorld(topLeft);\n\tconst ViewRay<WorldCoordinateSystem> dir_topRight = cam.imageToWorld(topRight);\n\tconst ViewRay<WorldCoordinateSystem> dir_bottomLeft = cam.imageToWorld(bottomLeft);\n\tconst ViewRay<WorldCoordinateSystem> dir_bottomRight = cam.imageToWorld(bottomRight);\n\n\treturn CameraGeometry::Info\n\t{\n\t\torigin,\n\t\tconvert_to<osg::Vec3>(dir_topLeft.direction.get()),\n\t\tconvert_to<osg::Vec3>(dir_topRight.direction.get()),\n\t\tconvert_to<osg::Vec3>(dir_bottomLeft.direction.get()),\n\t\tconvert_to<osg::Vec3>(dir_bottomRight.direction.get())\n\t};\n}\n\n\nclass DisplayablePoints : public OsgDisplayable\n{\npublic:\n\tDisplayablePoints(const std::vector<osg::Vec3> & points, float size) :\n\t\tm_points(points),\n\t\tm_size(size)\n\t{\n\t\t// empty\n\t}\n\n\tosg::ref_ptr<osg::Group> getGeometry() const override\n\t{\n\t\tosg::ref_ptr<osg::Group> camGroup = new osg::Group();\n\t\tfor (const auto & p : m_points)\n\t\t{\n\t\t\tosg::ref_ptr<osg::ShapeDrawable> sd = new osg::ShapeDrawable(osg::ref_ptr<osg::Sphere>(new osg::Sphere(p, m_size)));\n\t\t\tsd->setColor(osg::Vec4(1, 0, 0, 1));\n\t\t\tcamGroup->addChild(sd);\n\t\t}\n\n\t\treturn camGroup;\n\t}\n\nprivate:\n\tstd::vector<osg::Vec3> m_points;\n\tfloat m_size;\n};\n\n\nint main(int argc, char ** argv)\n{\n\tUnrealCoordinateSystem::setDirections({ Vector3(1, 0, 0), Vector3(0, -1, 0), Vector3(0, 0, 1) });\n\tWorldCoordinateSystem::setDirections({ Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1) });\n\n\tCamera<WorldCoordinateSystem> camera;\n\t\n\tusing Vector = WorldCoordinateSystem::Vector;\n\tusing FocalLength = decltype(camera)::FocalLength;\n\tusing Size = decltype(camera)::Size;\n\n\tcamera.setBaseDirections(\n\t\t{\n\t\t\tmake_named<WorldVector>(0.f, -1.f, 0.f),\n\t\t\tmake_named<WorldVector>(0.f, 0.f, -1.f),\n\t\t\tmake_named<WorldVector>(1.f, 0.f, 0.f)\n\t\t}\n\t);\n\n\tconst Degrees yaw(223.12f);\n\tconst Degrees pitch(316.78f);\n\tconst Degrees roll(0.f);\n\n\tconst UnrealVector ue_cameraPos(Vector(31.61f, 28.6f, 23.54f));\n\tconst UnrealRotation ue_cameraRotation = UnrealRotation(yaw, pitch, roll);\n\n\tstd::cout << ue_cameraPos(0) << \", \" << ue_cameraPos(1) << \", \" << ue_cameraPos(2) << std::endl;\n\n\tWorldVector w_cameraPos = UnrealToWorld::sourceToTarget(ue_cameraPos);\n\tWorldVector w_cameraPos2 = convertTo<WorldCoordinateSystem>(ue_cameraPos);\n\tWorldRotation w_cameraRotation(ue_cameraRotation);\n\n\tcamera.extrinsicTransform(w_cameraRotation);\n\tcamera.extrinsicTransform(make_named<WorldTransform>(Translation(w_cameraPos.get())));\n\n\tcamera.setFocalLength(FocalLength(713.2f));\n\tcamera.setOpticalCenter(make_named<ImagePoint>(400, 300));\n\tcamera.setImageSize(make_named<Size>(800, 600));\n\n\tstd::ofstream(\"C:/TEMP/cam.txt\") << camera;\n\tdecltype(camera) loaded;\n\tstd::ifstream(\"C:/TEMP/cam.txt\") >> loaded;\n\n\tstd::cout << std::boolalpha << (camera == camera) << std::endl;\n\tstd::cout << std::boolalpha << (camera == Camera<WorldCoordinateSystem>()) << std::endl;\n\tstd::cout << std::boolalpha << (camera == loaded) << std::endl;\n\n\tstd::vector<UnrealVector> ue_points =\n\t{\n\t\tmake_named<UnrealVector>(0.f, 0.f, 0.f),\n\t\tmake_named<UnrealVector>(0.f, -15.f, 0.f),\n\t\tmake_named<UnrealVector>(-10.f, -10.f, 0.f),\n\t\tmake_named<UnrealVector>(19.f, 13.f, 0.f),\n\t\tmake_named<UnrealVector>(-8.f, 16.f, 0.f)\n\t};\n\n\tstd::vector<WorldVector> w_points;\n\tstd::transform(ue_points.begin(), ue_points.end(), std::back_inserter(w_points),\n\t               [](const UnrealVector & ue_v)\n\t               {\n\t\t               return UnrealToWorld::sourceToTarget(ue_v);\n\t               }\n\t);\n\n\tfor (const auto & w_p : w_points)\n\t{\n\t\tstd::cout << w_p.get() << std::endl << std::endl;\n\t}\n\n\tstd::cout << std::endl << std::endl;\n\n\tstd::vector<decltype(camera)::CameraVector> cam_points;\n\tstd::transform(w_points.begin(), w_points.end(), std::back_inserter(cam_points),\n\t               [&camera](const WorldVector & w_v)\n\t               {\n\t\t               return camera.worldToCamera(w_v);\n\t               });\n\n\tfor (const auto & cam_p : cam_points)\n\t{\n\t\tstd::cout << cam_p.get() << std::endl << std::endl;\n\t}\n\n\tstd::cout << std::endl << std::endl;\n\n\tstd::vector<ImagePoint> img_points;\n\tstd::transform(w_points.begin(), w_points.end(), std::back_inserter(img_points),\n\t               [&camera](const WorldVector & w_v)\n\t               {\n\t\t               return camera.worldToImage(w_v);\n\t               });\n\n\tfor (const auto & img_p : img_points)\n\t{\n\t\tstd::cout << img_p.get() << std::endl << std::endl;\n\t}\n\n\tstd::cout << std::endl << std::endl;\n\n\tstd::vector<decltype(camera)::CameraVector> cam_points_reconstructed;\n\tstd::transform(img_points.begin(), img_points.end(), std::back_inserter(cam_points_reconstructed),\n\t\t[&camera](const ImagePoint & p)\n\t{\n\t\treturn camera.imageToCamera(p);\n\t});\n\n\tfor (const auto & cam_p : cam_points_reconstructed)\n\t{\n\t\tstd::cout << cam_p.get() << std::endl << std::endl;\n\t}\n\n\tstd::cout << std::endl << std::endl;\n\n\tstd::vector<ViewRay<WorldCoordinateSystem>> viewRays;\n\tstd::transform(img_points.begin(), img_points.end(), std::back_inserter(viewRays),\n\t\t[&camera](const ImagePoint & p)\n\t{\n\t\treturn camera.imageToWorld(p);\n\t});\n\n\n\tfor (int i = 0; i < viewRays.size(); ++i)\n\t{\n\t\tconst auto & v = viewRays[i];\n\t\tconst float dist = (w_points[i].get() - v.origin.get()).norm();\n\t\tstd::cout << v.origin.get() + dist * v.direction.get() << std::endl << std::endl;\n\t}\n\n\t/*rtcvImageRgba img;\n\timg.resize(800, 600);\n\timg.fill(rtcvRgbaValue(20, 20, 20));\n\n\tfor(const auto & p : img_points)\n\t{\n\t\timg.drawRoi(rtcvRoi(rtcvPoint(p.get()(0), p.get()(1)), 10, 10), rtcvRed);\n\t}\n\n\timg.writeToFile(\"C:/TEMP/testImg.ppm\");*/\n\n\n\tQApplication app(argc, argv);\n\n\tRoi3DF area(osg::Vec3(-30, -30, 0), osg::Vec3(30, 30, 20));\n\n\tQtOsgWidget widget(nullptr);\n\n\tosg::StateSet * rootStateSet = widget.getRoot()->getOrCreateStateSet();\n\trootStateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);\n\trootStateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);\n\n\t//widget.addNodeToScene(createLightsFromUsableArea(area));\n\n\tGeometryManager manager(&widget);\n\n\tmanager.switchGeometry(std::make_unique<DisplayableAreaLight>(area));\n\tmanager.switchGeometry(std::make_unique<DisplayableGrid>(area, osg::Vec3(1, 1, 1)));\n\tmanager.switchGeometry(std::make_unique<DisplayableCoordinateSystem>(osg::Vec3(0, 0, 0), 0.5f, 5.f));\n\n\tstd::vector<CameraGeometry::Info> camerasToDisplay = { makeInfo(camera) };\n\tmanager.switchGeometry(std::make_unique<DisplayableCameras>(camerasToDisplay, 1.f, 5.f));\n\n\tstd::vector<osg::Vec3> pointsToDisplay;\n\tstd::transform(w_points.begin(), w_points.end(), std::back_inserter(pointsToDisplay),\n\t\t[](const WorldVector & v)\n\t{\n\t\treturn boost::qvm::convert_to<osg::Vec3>(v.get());\n\t}\n\t);\n\n\tmanager.switchGeometry(std::make_unique<DisplayablePoints>(pointsToDisplay, 1.f));\n\n\twidget.show();\n\n\n\treturn app.exec();\n}\n", "meta": {"hexsha": "359214eed9a1c761801f028f7c8f87353ecbc50d", "size": 9097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_coordinate_transform/src/main.cpp", "max_stars_repo_name": "MatthiasMichael/Geometry", "max_stars_repo_head_hexsha": "d2308a39a8a2c693dbe4bc10260a352358ea291d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_coordinate_transform/src/main.cpp", "max_issues_repo_name": "MatthiasMichael/Geometry", "max_issues_repo_head_hexsha": "d2308a39a8a2c693dbe4bc10260a352358ea291d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_coordinate_transform/src/main.cpp", "max_forks_repo_name": "MatthiasMichael/Geometry", "max_forks_repo_head_hexsha": "d2308a39a8a2c693dbe4bc10260a352358ea291d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8793650794, "max_line_length": 119, "alphanum_fraction": 0.6966032758, "num_tokens": 2577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.817574471748733, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4438311619715438}}
{"text": "/*\n * Copyright (c) Huawei Technologies Co., Ltd. 2020-2030. All rights reserved.\n * Description:  Implementation of different 3D Plane Detection Algorithm.\n * Author: Created by huangjingwei 589411\n * Create date: 2021-08-13\n */\n// STL includes.\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <string>\n#include <vector>\n\n// CGAL includes.\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/pca_estimate_normals.h>\n#include <CGAL/Point_set_3.h>\n#include <CGAL/Point_set_3/IO.h>\n#include <CGAL/Random.h>\n#include <CGAL/Shape_detection/Region_growing/Region_growing.h>\n#include <CGAL/Shape_detection/Region_growing/Region_growing_on_point_set.h>\n#include <CGAL/Timer.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n// Type declarations.\nusing Kernel = CGAL::Exact_predicates_inexact_constructions_kernel;\nusing FT = typename Kernel::FT;\nusing Point_3 = typename Kernel::Point_3;\nusing Vector_3 = typename Kernel::Vector_3;\nusing Input_range = CGAL::Point_set_3<Point_3>;\nusing Point_map = typename Input_range::Point_map;\nusing Normal_map = typename Input_range::Vector_map;\nusing Neighbor_query =\n    CGAL::Shape_detection::Point_set::K_neighbor_query<Kernel, Input_range,\n                                                       Point_map>;\n// using Neighbor_query =\n// CGAL::Shape_detection::Point_set::Sphere_neighbor_query<Kernel, Input_range,\n// Point_map>;\nusing Region_type =\n    CGAL::Shape_detection::Point_set::Least_squares_plane_fit_region<\n        Kernel, Input_range, Point_map, Normal_map>;\nusing Region_growing =\n    CGAL::Shape_detection::Region_growing<Input_range, Neighbor_query,\n                                          Region_type>;\nusing Indices = std::vector<std::size_t>;\nusing Output_range = CGAL::Point_set_3<Point_3>;\nusing Points_3 = std::vector<Point_3>;\n\ntypedef std::pair<Point_3, Vector_3> PointVectorPair;\ntypedef std::vector<PointVectorPair> PointList;\n\n// Concurrency\ntypedef CGAL::Parallel_if_available_tag Concurrency_tag;\n\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n    MatrixD;\ntypedef Eigen::Matrix<FT, 3, 1> Vector3;\n\nstruct Pointcloud {\n  MatrixD P, N, C;\n};\n\nvoid ComputePointNormals(\n    Pointcloud& pc,                         // input points + output normals\n    unsigned int nb_neighbors_pca_normals)  // number of neighbors\n{\n  PointList points(pc.P.rows());\n  for (int i = 0; i < points.size(); ++i) {\n    auto p = pc.P.row(i);\n    points[i].first = Point_3(p[0], p[1], p[2]);\n  }\n  CGAL::Timer task_timer;\n  task_timer.start();\n\n  // Estimates normals direction.\n  // Note: pca_estimate_normals() requires an iterator over points\n  // as well as property maps to access each point's position and normal.\n  CGAL::pca_estimate_normals<Concurrency_tag>(\n      points, nb_neighbors_pca_normals,\n      CGAL::parameters::point_map(\n          CGAL::First_of_pair_property_map<PointVectorPair>())\n          .normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>()));\n\n  std::size_t memory = CGAL::Memory_sizer().virtual_size();\n  pc.N.conservativeResize(points.size(), 3);\n  for (int i = 0; i < points.size(); ++i) {\n    pc.P.row(i) =\n        Vector3(points[i].first.x(), points[i].first.y(), points[i].first.z());\n    pc.N.row(i) = Vector3(points[i].second.x(), points[i].second.y(),\n                          points[i].second.z());\n    if (pc.N.row(i).dot(Vector3(1, 1, 1)) < 0) pc.N.row(i) = -pc.N.row(i);\n  }\n}\n\n// Define an insert iterator. \nint PlaneDetectRegion(Pointcloud& pc,\n                      std::vector<std::pair<Vector3, FT> >& plane_parameters,\n                      std::vector<int>& new_instances,\n                      double dist_thres, double angle_thres, int min_points,\n                      int num_neigbhors) {\n  const bool with_normal_map = true;\n  Input_range input_range(with_normal_map);\n  for (int i = 0; i < pc.P.rows(); ++i) {\n    input_range.insert(Kernel::Point_3(pc.P(i, 0), pc.P(i, 1), pc.P(i, 2)));\n  }\n  auto it = input_range.begin();\n  for (int i = 0; i < pc.N.rows(); ++i) {\n    input_range.normal(*(it++)) =\n        Kernel::Vector_3(pc.N(i, 0), pc.N(i, 1), pc.N(i, 2));\n  }\n  // Default parameter values for the data file point_set_3.xyz.\n  const std::size_t k = num_neigbhors;\n  const FT max_distance_to_plane = dist_thres;\n  const FT max_accepted_angle = angle_thres;\n  const std::size_t min_region_size = min_points;\n\n  // Create instances of the classes Neighbor_query and Region_type.\n  Neighbor_query neighbor_query(input_range, k, input_range.point_map());\n  Region_type region_type(input_range, max_distance_to_plane,\n                          max_accepted_angle, min_region_size,\n                          input_range.point_map(), input_range.normal_map());\n  // Create an instance of the region growing class.\n  Region_growing region_growing(input_range, neighbor_query, region_type);\n  // Run the algorithm.\n  Output_range output_range;\n  std::size_t number_of_regions = 0;\n\n  std::vector<std::vector<std::size_t> > regions;\n  region_growing.detect(std::back_inserter(regions));\n  plane_parameters.resize(regions.size());\n  new_instances.resize(pc.P.rows(), -1);\n\n  for (int i = 0; i < regions.size(); ++i) {\n    Vector3 c(0, 0, 0);\n    for (auto& idx : regions[i]) {\n      new_instances[idx] = i;\n      c += pc.P.row(idx);\n    }\n    c /= (double)regions[i].size();\n\n    MatrixD C = MatrixD::Zero(3, 3);\n    for (auto& idx : regions[i]) {\n      Vector3 diff = pc.P.row(idx);\n      diff -= c;\n      C += diff * diff.transpose();\n    }\n    Eigen::JacobiSVD<MatrixD> svd(C, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Vector3 N = svd.matrixU().col(2);\n    plane_parameters[i] = std::make_pair(N, -N.dot(c));\n  }\n  return regions.size();\n}\n\nint main(int argc, char** argv) {\n\n  const int kNeighbors = 16;\n  const double kDistThres = 1e-1;\n  const double kAngleThres = 20;\n  const int kMinPoints = 200;\n\n  // simulate a box\n  std::vector<Vector3> points;\n  for (int i = 0; i < 100; ++i) {\n    for (int j = 0; j < 100; ++j) {\n      points.push_back(Vector3(i * 0.01, j * 0.01, 0));\n      points.push_back(Vector3(i * 0.01, j * 0.01, 1));\n      points.push_back(Vector3(i * 0.01, 0, j * 0.01));\n      points.push_back(Vector3(i * 0.01, 1, j * 0.01));\n      points.push_back(Vector3(0, i * 0.01, j * 0.01));\n      points.push_back(Vector3(1, i * 0.01, j * 0.01));\n    }\n  }\n  for (auto& p : points) {\n    double dx = rand() % 256 / 256.0 - 0.5;\n    double dy = rand() % 256 / 256.0 - 0.5;\n    double dz = rand() % 256 / 256.0 - 0.5;\n    p += Vector3(dx * 0.01, dy * 0.01, dz * 0.01);\n  }\n\n  Pointcloud pc;\n  pc.P.resize(points.size(), 3);\n  memcpy(pc.P.data(), points.data(), sizeof(Vector3) * points.size());\n\n  ComputePointNormals(pc, kNeighbors);\n\n  std::vector<std::pair<Vector3, double> > plane_parameters;\n  std::vector<int> plane_instances;\n  int num_inst = PlaneDetectRegion(pc, plane_parameters, plane_instances,\n    kDistThres, kAngleThres, kMinPoints, kNeighbors);\n\n  printf(\"Num inst: %d\\n\", num_inst);\n  printf(\"Params:\\n\");\n  for (auto& p : plane_parameters) {\n    printf(\"%f %f %f %f\\n\", p.first[0], p.first[1], p.first[2], p.second);\n  }\n  std::vector<Vector3> colors(num_inst);\n  for (auto& c : colors) {\n    c = Vector3(rand() % 256 / 256.0,\n      rand() % 256 / 256.0, rand() % 256 / 256.0);\n  }\n\n  std::ofstream os(\"result.obj\");\n  for (int i = 0; i < points.size(); ++i) {\n    auto p = points[i];\n    auto c = Vector3(0, 0, 0);\n    if (plane_instances[i] >= 0)\n      c = colors[plane_instances[i]];\n    os << \"v \" << p[0] << \" \" << p[1] << \" \" << p[2] << \" \"\n      << c[0] << \" \" << c[1] << \" \" << c[2] << \"\\n\";\n  }\n  os.close();\n  return 0;\n}", "meta": {"hexsha": "d44c81adbd75c355e3ac43f4bb72fd9458591d5e", "size": 7669, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PlaneDetection3D/region_growing_3d.cpp", "max_stars_repo_name": "hjwdzh/PrimitiveFitting", "max_stars_repo_head_hexsha": "8ab1a356a26a3a730ecc7c951be7969a8ce02799", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-09-27T13:19:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T10:21:14.000Z", "max_issues_repo_path": "PlaneDetection3D/region_growing_3d.cpp", "max_issues_repo_name": "hjwdzh/PrimitiveFitting", "max_issues_repo_head_hexsha": "8ab1a356a26a3a730ecc7c951be7969a8ce02799", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PlaneDetection3D/region_growing_3d.cpp", "max_forks_repo_name": "hjwdzh/PrimitiveFitting", "max_forks_repo_head_hexsha": "8ab1a356a26a3a730ecc7c951be7969a8ce02799", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5046296296, "max_line_length": 80, "alphanum_fraction": 0.6449341505, "num_tokens": 2208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4438166883848272}}
{"text": "#pragma once\n\n#include \"geometry/any_rect2d.hpp\"\n#include \"geometry/point2d.hpp\"\n\n#include \"base/exception.hpp\"\n#include \"base/math.hpp\"\n\n#include <vector>\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wcomma\"\n#include <boost/geometry.hpp>\n#pragma clang diagnostic pop\n#include <boost/geometry/geometries/adapted/boost_tuple.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n\nnamespace geometry\n{\ndouble constexpr kPenaltyScore = -1.0;\nDECLARE_EXCEPTION(NotAPolygonException, RootException);\n\nnamespace impl\n{\nusing PointXY = boost::geometry::model::d2::point_xy<double>;\nusing Polygon = boost::geometry::model::polygon<PointXY>;\nusing MultiPolygon = boost::geometry::model::multi_polygon<Polygon>;\n}  // namespace impl\n\ntemplate <typename Container>\nimpl::Polygon PointsToPolygon(Container const & points);\ntemplate <typename Container>\nimpl::MultiPolygon TrianglesToPolygon(Container const & points);\n\n// The return value is a real number from [-1.0, 1.0].\n// * Returns positive value when the geometries intersect (returns intersection area divided by union area).\n//   In particular, returns 1.0 when the geometries are equal.\n// * Returns zero when the geometries do not intersect.\n// * Returns kPenaltyScore as penalty. It is possible when any of the geometries is empty or invalid.\n/// |lhs| and |rhs| are any areal boost::geometry types.\ntemplate <typename LGeometry, typename RGeometry>\ndouble GetIntersectionScore(LGeometry const & lhs, RGeometry const & rhs)\n{\n  if (!boost::geometry::is_valid(lhs) || !boost::geometry::is_valid(rhs) ||\n      boost::geometry::is_empty(lhs) || boost::geometry::is_empty(rhs))\n  {\n    return kPenaltyScore;\n  }\n\n  auto const lhsArea = boost::geometry::area(lhs);\n  auto const rhsArea = boost::geometry::area(rhs);\n  impl::MultiPolygon result;\n  boost::geometry::intersection(lhs, rhs, result);\n  auto const intersectionArea = boost::geometry::area(result);\n  auto const unionArea = lhsArea + rhsArea - intersectionArea;\n\n  auto const score = intersectionArea / unionArea;\n\n  return score;\n}\n\n/// Throws NotAPolygonException exception.\n/// For detailed info see comment for\n/// double GetIntersectionScore(LPolygon const & lhs, RPolygon const & rhs).\n/// |lhs| and |rhs| are any standard container of m2::Point with random access iterator.\n/// |toPolygonConverter| is a method which converts |lhs| and |rhs| to boost::geometry areal type.\ntemplate <typename Container, typename Converter>\ndouble GetIntersectionScore(Container const & lhs, Container const & rhs,\n                            Converter const & toPolygonConverter)\n{\n  auto const lhsPolygon = toPolygonConverter(lhs);\n  if (boost::geometry::is_empty(lhsPolygon))\n    return kPenaltyScore;\n\n  auto const rhsPolygon = toPolygonConverter(rhs);\n  if (boost::geometry::is_empty(rhsPolygon))\n    return kPenaltyScore;\n\n  return GetIntersectionScore(lhsPolygon, rhsPolygon);\n}\n\n/// Throws NotAPolygonException exception.\n/// For detailed info see comment for\n/// double GetIntersectionScore(LPolygon const & lhs, RPolygon const & rhs).\n/// |lhs| and |rhs| are any standard containers of m2::Point with random access iterator.\ntemplate <typename Container>\ndouble GetIntersectionScoreForPoints(Container const & lhs, Container const & rhs)\n{\n  return GetIntersectionScore<Container>(lhs, rhs, PointsToPolygon<Container>);\n}\n\n/// Throws NotAPolygonException exception.\n/// For detailed info see comment for\n/// double GetIntersectionScore(LPolygon const & lhs, RPolygon const & rhs).\n/// |lhs| and |rhs| are any standard containers of m2::Point with random access iterator.\ntemplate <typename Container>\ndouble GetIntersectionScoreForTriangulated(Container const & lhs, Container const & rhs)\n{\n  return GetIntersectionScore<Container>(lhs, rhs, TrianglesToPolygon<Container>);\n}\n\n/// |points| is any standard container of m2::Point with random access iterator.\ntemplate <typename Container>\nimpl::Polygon PointsToPolygon(Container const & points)\n{\n  impl::Polygon polygon;\n  for (auto const & point : points)\n    polygon.outer().push_back(impl::PointXY(point.x, point.y));\n  boost::geometry::correct(polygon);\n  if (!boost::geometry::is_valid(polygon))\n    MYTHROW(geometry::NotAPolygonException, (\"The points is not valid polygon\"));\n\n  return polygon;\n}\n\n/// |points| is any standard container of m2::Point with random access iterator.\ntemplate <typename Container>\nimpl::MultiPolygon TrianglesToPolygon(Container const & points)\n{\n  size_t const kTriangleSize = 3;\n  if (points.size() % kTriangleSize != 0)\n    MYTHROW(geometry::NotAPolygonException, (\"Count of points must be multiple of\", kTriangleSize));\n\n  std::vector<impl::MultiPolygon> polygons;\n  for (size_t i = 0; i < points.size(); i += kTriangleSize)\n  {\n    impl::MultiPolygon polygon;\n    polygon.resize(1);\n    auto & p = polygon[0];\n    auto & outer = p.outer();\n    for (size_t j = i; j < i + kTriangleSize; ++j)\n      outer.push_back(impl::PointXY(points[j].x, points[j].y));\n    boost::geometry::correct(p);\n    if (!boost::geometry::is_valid(polygon))\n      MYTHROW(geometry::NotAPolygonException, (\"The triangle is not valid\"));\n    polygons.push_back(polygon);\n  }\n\n  if (polygons.empty())\n    return {};\n\n  auto & result = polygons[0];\n  for (size_t i = 1; i < polygons.size(); ++i)\n  {\n    impl::MultiPolygon u;\n    boost::geometry::union_(result, polygons[i], u);\n    u.swap(result);\n  }\n  return result;\n}\n}  // namespace geometry\n", "meta": {"hexsha": "feda32b87e3899c2a772fd4119c624a816bf07f0", "size": 5483, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry/intersection_score.hpp", "max_stars_repo_name": "smartyw/organicmaps", "max_stars_repo_head_hexsha": "9b10eb9d3ed6833861cef294c2416cc98b15e10d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 127.0, "max_stars_repo_stars_event_min_datetime": "2021-01-03T08:17:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-05T18:33:21.000Z", "max_issues_repo_path": "geometry/intersection_score.hpp", "max_issues_repo_name": "smartyw/organicmaps", "max_issues_repo_head_hexsha": "9b10eb9d3ed6833861cef294c2416cc98b15e10d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 226.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T11:40:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T07:25:55.000Z", "max_forks_repo_path": "geometry/intersection_score.hpp", "max_forks_repo_name": "smartyw/organicmaps", "max_forks_repo_head_hexsha": "9b10eb9d3ed6833861cef294c2416cc98b15e10d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2020-12-28T20:00:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-04T20:34:31.000Z", "avg_line_length": 35.8366013072, "max_line_length": 108, "alphanum_fraction": 0.7342695605, "num_tokens": 1303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835248143777, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.4438166796807427}}
{"text": "/*\n\nProject: icp alignment for localization\nDate: 20/08/20\n@Author: ALL\nDetail: align two clouds in the localization, \n        so as to get the global pose of the current frame\nScenario: localization\n\n*/\n#include <boost/make_shared.hpp>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_representation.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/filters/filter.h>\n#include <pcl/filters/radius_outlier_removal.h>\n#include <pcl/registration/icp.h>\n#include <pcl/filters/uniform_sampling.h>\n#include <pcl/common/transforms.h>\n#include <vector>\n\n#include <sys/types.h>\n#include <sys/ipc.h>\n#include <sys/shm.h>\n#include <sys/sem.h>\n\n#include <string.h>\n#include <dirent.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\n#include <unistd.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n\n#include \"../include/Lidar.h\"\n#include \"../include/ipc.h\"\n#include \"../include/QuadTree.h\" //structure define and the other shits\n#include \"../include/Localizate.h\"\n#include \"../include/ProcessCom.h\"\n\nusing namespace std;\ntypedef pcl::PointXYZ PointT;\ntypedef pcl::PointCloud<PointT> PointCloud;\ntypedef pcl::PointNormal PointNormalT;\ntypedef pcl::PointCloud<PointNormalT> PointCloudWithNormal;\n\n\nstruct information_of_barrier\n{\n    float centerx;\n    float centery;\n};\nint num_of_barrier;\n\nstruct Posemat\n{\n    Eigen::Matrix4f global_transform;\n};\n\n//uniform sampling func\n//data acquired: Cloud's ptr for processing.\nvoid uniform_sampling (PointCloud::Ptr cloud)\n{\n    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::UniformSampling<pcl::PointXYZ> US;\n    US.setInputCloud(cloud);\n    US.setRadiusSearch(0.2f);\n    US.filter(*cloud_filtered);\n    *cloud = *cloud_filtered;\n}\n\n//icp point align algorithm\n//data acquired: 1 & 2 is the Cloud's ptr for aligning, 3 is the Cloud's ptr for output, 4 is transformation matrix, 5 is unclear.\nvoid pairAlign (const PointCloud::Ptr cloud_src, const PointCloud::Ptr cloud_tgt, PointCloud::Ptr output, Eigen::Matrix4f&final_transform)\n{\n    int iterations = 100;\n    pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;\n    icp.setInputSource(cloud_src);\n    icp.setInputTarget(cloud_tgt);\n    icp.setTransformationEpsilon(1e-15);\n    icp.setMaxCorrespondenceDistance(2);\n    icp.setEuclideanFitnessEpsilon(0.001);\n    icp.setMaximumIterations(iterations);\n    icp.align(*output);\n    final_transform = icp.getFinalTransformation();\n}\n\n// func from raw pose values to the eigen transformation mat\nvoid six2Trans(float roll, float pitch, float yaw, float x, float y, float z, Eigen::Matrix4f& transform)\n{\n    Eigen::Vector3f eulerAngle(yaw, pitch, roll);\n    Eigen::AngleAxisf rollAngle(Eigen::AngleAxisf(eulerAngle(2),Eigen::Vector3f::UnitX()));\n    Eigen::AngleAxisf pitchAngle(Eigen::AngleAxisf(eulerAngle(1),Eigen::Vector3f::UnitY()));\n    Eigen::AngleAxisf yawAngle(Eigen::AngleAxisf(eulerAngle(0),Eigen::Vector3f::UnitZ()));\n\n    Eigen::Matrix3f rotation;\n    rotation = yawAngle * pitchAngle * rollAngle;\n\n    Eigen::Translation3f translation(x, y, z);\n    transform = (translation * rotation).matrix();\n}\n\nvoid quaterniond2eulerangle(Eigen::Quaternionf& q, float& roll, float& pitch, float& yaw)\n{\n    double sinr_cosp = +2.0*(q.w()*q.x() + q.y()*q.z());\n    double cosr_cosp = +1.0 - 2.0*(q.x()*q.x() + q.y()*q.y());\n    roll = atan2(sinr_cosp, cosr_cosp);\n\n    double sinp = +2.0*(q.w()*q.y() - q.z()*q.x());\n    if(fabs(sinp) >= 1) pitch = copysign(M_PI/2, sinp);\n    else pitch = asin(sinp);\n\n    double siny_cosp = +2.0*(q.w()*q.z() + q.x()*q.y());\n    double cosy_cosp = +1.0 - 2.0*(q.y()*q.y() + q.z()*q.z());\n    yaw = atan2(siny_cosp, cosy_cosp);\n}\n\nvector<information_of_barrier> remove_duplicates( vector<vector<float>> &data)\n{\n    for(int i = 0; i < data.size(); i++)\n    {\n        data[i][0] = (float)round(data[i][0]*4);\n        data[i][1] = (float)round(data[i][1]*4);\n    }\n    sort(data.begin(),data.end());\n    data.erase(unique(data.begin(), data.end()),data.end());\n    std::vector<information_of_barrier> Information_of_barrier;\n    for(int i = 0; i < data.size(); i++)\n    {\n        if(data[i][0]<=12&&data[i][0]>=0&&data[i][1]<=8&&data[i][1]>=-8){\n        information_of_barrier barrier;\n        barrier.centerx = data[i][0]/4;\n        barrier.centery = data[i][1]/4;\n        Information_of_barrier.push_back(barrier);\n        }\n    \n    }\n    return Information_of_barrier;\n}\n\nint main(int argc, char** argv)\n{\n    InitLocalizate();\n\n    float x;\n    float y;\n    float z;\n    float roll;\n    float pitch;\n    float yaw;\n\n    struct QuadTreeNode root;\n    struct Region root_region;\n    struct ElePoint ele;\n    struct ElePoint old_ele; \n    initRegion(&root_region, -50, 100, -50, 100);\n    initNode(&root, 1, root_region);\n\n    std::vector<std::vector<float>> data3d;\n    std::vector<std::vector<float>> data_after;\n    std::vector<float> data2d;\n    std::vector<Posemat> Pose;\n    int line = 0;\n     \n    ifstream fin(\"../pose.txt\"); \n    Eigen::Matrix4f GlobalTransform = Eigen::Matrix4f::Identity();\n    while(!fin.eof())\n    {\n        fin >> line >> x >> y >> z >> yaw >> pitch >> roll;\n        cout << \"Checking No. \" << line << \" Pose.\" << endl;\n        six2Trans(roll, pitch, yaw, x, y, z, GlobalTransform);\n        Posemat a;\n        a.global_transform = GlobalTransform;\n        cout << \"global: \\n\" << GlobalTransform << endl; \n        Pose.push_back(a);\n        ele.x = x;\n        ele.y = y;\n        ele.index = line;\n        insertEle(&root, ele);\n        if (!fin.good()) break;\n    }\n\n    pthread_mutex_init(&LidarMutex,NULL);\n    lidar.InitLidar();//start get lidar data\n    sleep(3);\n\n    InitSem(LidarOccPosSemId, LidarOccPosSemKey, 1, IPC_CREAT|0777); \n    MessageQueueInit(LidarOccPosMsgId, LidarOccPosMsgKey, IPC_CREAT|0777);\n    InitShareMemory(LidarOccPosShmId, LidarOccPosShmKey,4096, IPC_CREAT|0777);\n\n    V_sem(LidarOccPosSemId, 0);\n    V_sem(PosSemId, 0);\n\n\n    while(1)\n    {\n        PointCloud::Ptr source(new PointCloud);\n        PointCloud::Ptr target(new PointCloud);\n        PointCloud::Ptr temp(new PointCloud);\n        PointCloud::Ptr Lidarcloud(new PointCloud);\n\n        pthread_mutex_lock(&LidarMutex);\n        pcl::copyPointCloud(*safecloud, *Lidarcloud);\n        //end updata lidar data\n\n        for(int i = 0; i<Lidarcloud->size(); i++)\n        {\n            if(Lidarcloud->points[i].x >= 0.0 && Lidarcloud->points[i].x <= 3.0 && Lidarcloud->points[i].y >= -2 && Lidarcloud->points[i].y <= 2)\n            {\n                data2d.push_back(Lidarcloud->points[i].x);\n                data2d.push_back(Lidarcloud->points[i].y);\n                data3d.push_back(data2d);\n                data2d.clear();\n            }\n        }\n        std::vector<information_of_barrier> Information_of_barrier = remove_duplicates(data3d);\n        //std::cout<<\"*********\"<<Information_of_barrier.size()<<std::endl;\n        \n        //链接内存\n        void* lidarOccPosMemory;\n        lidarOccPosMemory = AttachShareMemory(LidarOccPosShmId);\n\n        if(lidarOccPosMemory == (void*)(-1))\n        {\n            std::cout << \"Get occPosMemoy failed\" << std::endl;\n            return -1;      \n        }\n\n        P_sem(LidarOccPosSemId, 0);//使用互斥量\n        int occNum = Information_of_barrier.size();\n        //std::cout << \"occNum\" << occNum << std::endl;\n        WriteShareMemory(lidarOccPosMemory, &occNum, sizeof(int));\n        for(int loop = 0; loop < occNum; loop++)\n        {\n            WriteShareMemory((void*)(lidarOccPosMemory + sizeof(int) + loop * sizeof(information_of_barrier)), &Information_of_barrier[loop], sizeof(information_of_barrier));\n        }\n        V_sem(LidarOccPosSemId, 0);\n\n        int ret = DisattachShareMemory(lidarOccPosMemory);\n        if(ret != 0)\n        {\n            std::cout << \"Failed detached memory\" << std::endl;\n        }\n\n        //get the index from quad_tree\n        float x_now, y_now, z_now, roll_now, pitch_now, yaw_now, v_now, w_now;\n        x_now = y_now = z_now = roll_now = pitch_now = yaw_now = v_now = w_now = 0; \n        PriorLocation(x_now, y_now, z_now, roll_now, pitch_now, yaw_now, v_now, w_now);\n        //float d = 1;\n        //float disturbance[9][2] = {{d, 0}, {d, d}, {0, d}, {0, 0}, {-d, d}, {-d, 0}, {-d, -d}, {0, -d}, {d, -d}};\n        float candidate[MAX_ELE_NUM*9 + 1][3] = {0};\n        float min_distance = 1000;\n        float distance = 0;\n        int found_index = -1;\n        \n        //find possible index\n        //for(int i = 0; i < 9; i++)\n        //{   \n            struct ElePoint test;\n            test.x = x_now;// + disturbance[i][0];\n            test.y = y_now; // + disturbance[i][1];\n            queryEle(root, test, candidate, candidate[MAX_ELE_NUM*9][0]);  \n        //}\n\n        //find closest index\n        for(int k = 0; k < candidate[MAX_ELE_NUM*9][0]; k++)\n        {\n            distance = hypot(x_now - candidate[k][0], y_now - candidate[k][1]);\n            //cout << \"candidate_index: \" << candidate[k][2] << \" , distance: \" << distance << endl;\n            //1. to eradicate the keyframes on the time-related sequence \n            //2. to find the closest point to the determined pose\n            if(distance < min_distance)\n            {\n                min_distance = distance;\n                found_index = candidate[k][2];\n            } \n        }\n        cout << \"found_index: \" << found_index << \" , mindistance: \" << min_distance << endl;\n        //pseudo mat    \n        Eigen::Matrix4f globalTransform_curr = Eigen::Matrix4f::Identity(); // for the result store\n        Eigen::Matrix4f pairTransform        = Eigen::Matrix4f::Identity();\n        Eigen::Matrix4f priorTransform       = Eigen::Matrix4f::Identity(); \n        Eigen::Matrix4f relateTransform      = Eigen::Matrix4f::Identity();\n        float min = 0;\n\n\n        cout << \"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\" << endl;\n        cout << \"x: \" << x_now << \", y: \" <<  y_now  << \", yaw: \"<< yaw_now << endl;\n        six2Trans(roll_now, pitch_now, yaw_now, x_now, y_now, z_now, priorTransform); \n  \n        cout << \"prior: \\n\" << priorTransform << endl;\n        cout << \"keyframe: \\n\" << Pose[found_index].global_transform << endl;\n        relateTransform = Pose[found_index].global_transform.inverse() * priorTransform;\n        cout << \"relate: \\n\" << relateTransform << endl;\n\n        min = hypot(relateTransform(0,3), relateTransform(1,3));\n        float x_new, y_new, z_new, roll_new, pitch_new, yaw_new;\n        if(min < 0.4)\n        {\n            char namebuf[30];\n            sprintf(namebuf, \"../data/%d.pcd\", found_index+1);\n            pcl::io::loadPCDFile (namebuf, *source);    //get source cloud from keyframe inventory\n\n            uniform_sampling(Lidarcloud);\n            uniform_sampling(source);\n            cout << \"size after filter:\" << Lidarcloud->size() << endl;\n\n            pcl::transformPointCloud(*Lidarcloud, *target, relateTransform);\n            pairAlign(target, source, temp, pairTransform);\n            cout << \"pair: \\n\" << pairTransform << endl;\n            cout << \"pair inverse: \\n\" <<  pairTransform.inverse() << endl;\n            globalTransform_curr = Pose[found_index].global_transform * pairTransform * relateTransform;\n            cout << \"ture: \\n\" << globalTransform_curr<< endl;\n\n            //sent to local\n            Eigen::Matrix3f rotation_matrix = globalTransform_curr.block<3,3>(0,0);\n            Eigen::Quaternionf quaternion(rotation_matrix);\n            quaterniond2eulerangle(quaternion, roll_new, pitch_new, yaw_new);\n            x_new = globalTransform_curr(0,3);\n            y_new = globalTransform_curr(1,3);\n            z_new = globalTransform_curr(2,3);\n            PosteriorLocation(x_new, y_new, z_new, roll_new, pitch_new, yaw_new, v_now, w_now);\n        }\n        else\n        {\n            PosteriorLocation(x_now, y_now, z_now, roll_now, pitch_now, yaw_now, v_now, w_now);\n        }\n        pthread_mutex_unlock(&LidarMutex);\n    }\n    DestoryLocalizate();\n    return 0;\n}\n", "meta": {"hexsha": "35d3498b9e39af912ec2fb7c6c92c1f23de601be", "size": 12038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Localization_merged/src/LocalAlign.cpp", "max_stars_repo_name": "wangarcher/examine", "max_stars_repo_head_hexsha": "e04c923f0db397558ea765d7fbf1050fe4aec3dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Localization_merged/src/LocalAlign.cpp", "max_issues_repo_name": "wangarcher/examine", "max_issues_repo_head_hexsha": "e04c923f0db397558ea765d7fbf1050fe4aec3dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Localization_merged/src/LocalAlign.cpp", "max_forks_repo_name": "wangarcher/examine", "max_forks_repo_head_hexsha": "e04c923f0db397558ea765d7fbf1050fe4aec3dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5103244838, "max_line_length": 174, "alphanum_fraction": 0.6156338262, "num_tokens": 3271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4438154776675358}}
{"text": "/****************************\n * 题目：给定一组世界坐标系下的3D点(p3d.txt)以及它在相机中对应的坐标(p2d.txt)，以及相机的内参矩阵。\n * 使用bundle adjustment 方法（g2o库实现）来估计相机的位姿T。初始位姿T为单位矩阵。\n *\n* 本程序学习目标：\n * 熟悉g2o库编写流程，熟悉顶点定义方法。\n *\n * 公众号：计算机视觉life。发布于公众号旗下知识星球：从零开始学习SLAM\n * 时间：2019.02\n****************************/\n\n#include <vector>\n#include <fstream>\n#include <iostream>\n#include <opencv2/core/core.hpp>\n\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Dense>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n\nusing namespace Eigen;\n\nusing namespace cv;\nusing namespace std;\n\n\nstring p3d_file = \"./../p3d.txt\";\nstring p2d_file = \"./../p2d.txt\";\n\nvoid bundleAdjustment (\n        const vector<Point3f> points_3d,\n        const vector<Point2f> points_2d,\n        Mat& K );\n\nint main(int argc, char **argv) {\n\n\n    vector< Point3f > p3d;//保存世界坐标系下的3D点\n    vector< Point2f > p2d;//保存相机坐标系下对应的2D点\n\n    Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n\n    // 导入3D点和对应的2D点\n\n    ifstream fp3d(p3d_file);\n    if (!fp3d){\n        cout<< \"No p3d.text file\" << endl;\n        return -1;\n    }\n    else {\n        while (!fp3d.eof()){\n            double pt3[3] = {0};\n            for (auto &p:pt3) {\n                fp3d >> p;\n            }\n            p3d.push_back(Point3f(pt3[0],pt3[1],pt3[2]));\n        }\n    }\n    ifstream fp2d(p2d_file);\n    if (!fp2d){\n        cout<< \"No p2d.text file\" << endl;\n        return -1;\n    }\n    else {\n        while (!fp2d.eof()){\n            double pt2[2] = {0};\n            for (auto &p:pt2) {\n                fp2d >> p;\n            }\n            Point2f p2(pt2[0],pt2[1]);\n            p2d.push_back(p2);\n        }\n    }\n\n    assert(p3d.size() == p2d.size());\n\n    int iterations = 100;\n    double cost = 0, lastCost = 0;\n    int nPoints = p3d.size();\n    cout << \"points: \" << nPoints << endl;\n\n    bundleAdjustment ( p3d, p2d, K );\n    return 0;\n}\n\nvoid bundleAdjustment (\n        const vector< Point3f > points_3d,\n        const vector< Point2f > points_2d,\n        Mat& K   )\n{\n    // creat g2o\n    // new g2o version. Ref:https://www.cnblogs.com/xueyuanaichiyu/p/7921382.html\n\n    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose 维度为 6, landmark 维度为 3\n    // 第1步：创建一个线性求解器LinearSolver\n    Block::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>();\n\n    // 第2步：创建BlockSolver。并用上面定义的线性求解器初始化\n    //Block* solver_ptr = new Block (std::unique_ptr<Block::LinearSolverType>(linearSolver));\n\t    Block* solver_ptr = new Block (linearSolver);\n    // 第3步：创建总求解器solver。并从GN, LM, DogLeg 中选一个，再用上述块求解器BlockSolver初始化\n    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr );\n\n    // 第4步：创建稀疏优化器\n    g2o::SparseOptimizer optimizer;\n    optimizer.setAlgorithm ( solver );\n\n//    // old g2o version\n//    typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block;  // pose 维度为 6, landmark 维度为 3\n//    Block::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>(); // 线性方程求解器\n//    Block* solver_ptr = new Block ( linearSolver );     // 矩阵块求解器\n//    g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr );\n//    g2o::SparseOptimizer optimizer;\n//    optimizer.setAlgorithm ( solver );\n\n    // 第5步：定义图的顶点和边。并添加到SparseOptimizer中\n\t\n\t// ----------------------开始你的代码：设置并添加顶点，初始位姿为单位矩阵\n\t\n\t//添加相机的位姿，这里为待优化的变量，直接设置为单位矩阵\n    g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap(); // camera pose，g2o内定的类型\n    Eigen::Matrix3d R_mat;\n    \n    R_mat.setIdentity(3,3);\n    pose->setId ( 0 );\n    pose->setEstimate ( g2o::SE3Quat (\n                            R_mat,\n                            Eigen::Vector3d ( 0, 0, 0) )\n                        );\n    optimizer.addVertex ( pose );\n    \n    //g2o中世界坐标系的3维坐标才是顶点（vertex），而其对应的相机坐标系下的点是评估（estimate）点!!!!!!\n    int index=1;\n    for(const Point3f p:points_3d)\n    {\n\t\tg2o::VertexSBAPointXYZ* point = new g2o::VertexSBAPointXYZ();\n        point->setId ( index++ );\n        point->setEstimate ( Eigen::Vector3d ( p.x, p.y, p.z ) );//只有观测点\n        point->setMarginalized ( true ); // g2o 中必须设置 marg 参见第十讲内容\n        optimizer.addVertex ( point );    \t\n    }\n    \n \n\t// ----------------------结束你的代码\n\t\n\t\n    // 设置相机内参\n    g2o::CameraParameters* camera = new g2o::CameraParameters (\n            K.at<double> ( 0,0 ), Eigen::Vector2d ( K.at<double> ( 0,2 ), K.at<double> ( 1,2 ) ), 0);\n    camera->setId ( 0 );\n    optimizer.addParameter ( camera );\n\n    // 设置边\n    index = 1;\n    for ( const Point2f p:points_2d )\n    {\n        g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();\n        edge->setId ( index );\n        edge->setVertex ( 0, dynamic_cast<g2o::VertexSBAPointXYZ*> ( optimizer.vertex ( index ) ) );\n        edge->setVertex ( 1, pose );\n        edge->setMeasurement ( Eigen::Vector2d ( p.x, p.y ) );  //设置观测值\n        edge->setParameterId ( 0,0 );\n        edge->setInformation ( Eigen::Matrix2d::Identity() );\n        optimizer.addEdge ( edge );\n        index++;\n    }\n\n\n    // 第6步：设置优化参数，开始执行优化\n    optimizer.setVerbose ( false );\n    optimizer.initializeOptimization();\n    optimizer.optimize ( 100 );\n\n    // 输出优化结果\n    cout<<endl<<\"after optimization:\"<<endl;\n    cout<<\"T=\"<<endl<<Eigen::Isometry3d ( pose->estimate() ).matrix() <<endl;\n}\n", "meta": {"hexsha": "4b47a6599e0c3615c68463b6bdf2171d4c098b6d", "size": 5518, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch11/练习17-g2o顶点代码框架/BA-3Dto2D.cpp", "max_stars_repo_name": "Shelfcol/slam-book-master_GaoXiang", "max_stars_repo_head_hexsha": "0581b5ca7afb553e10073e216a699397b9447621", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-09T11:11:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-08T04:43:52.000Z", "max_issues_repo_path": "ch11/练习17-g2o顶点代码框架/BA-3Dto2D.cpp", "max_issues_repo_name": "Shelfcol/slam-book-master_GaoXiang", "max_issues_repo_head_hexsha": "0581b5ca7afb553e10073e216a699397b9447621", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch11/练习17-g2o顶点代码框架/BA-3Dto2D.cpp", "max_forks_repo_name": "Shelfcol/slam-book-master_GaoXiang", "max_forks_repo_head_hexsha": "0581b5ca7afb553e10073e216a699397b9447621", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T02:07:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T08:53:37.000Z", "avg_line_length": 29.827027027, "max_line_length": 111, "alphanum_fraction": 0.5973178688, "num_tokens": 1987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.44381547141086236}}
{"text": "/*\n * LineIterator.hpp\n *\n *  Created on: Nov 13, 2014\n *      Author: Péter Fankhauser\n *   Institute: ETH Zurich, Autonomous Systems Lab\n */\n\n#pragma once\n\n#include \"grid_map_core/GridMap.hpp\"\n#include \"grid_map_core/iterators/SubmapIterator.hpp\"\n\n#include <Eigen/Core>\n\nnamespace grid_map {\n\n/*!\n * Iterator class to iterate over a line in the map.\n * Based on Bresenham Line Drawing algorithm.\n */\nclass LineIterator\n{\npublic:\n\n  /*!\n   * Constructor.\n   * @param gridMap the grid map to iterate on.\n   * @param start the starting point of the line.\n   * @param end the ending point of the line.\n   */\n  LineIterator(const grid_map::GridMap& gridMap, const Position& start, const Position& end);\n\n  /*!\n   * Constructor.\n   * @param gridMap the grid map to iterate on.\n   * @param start the starting index of the line.\n   * @param end the ending index of the line.\n   */\n  LineIterator(const grid_map::GridMap& gridMap, const Index& start, const Index& end);\n\n  /*!\n   * Assignment operator.\n   * @param iterator the iterator to copy data from.\n   * @return a reference to *this.\n   */\n  LineIterator& operator =(const LineIterator& other);\n\n  /*!\n   * Compare to another iterator.\n   * @return whether the current iterator points to a different address than the other one.\n   */\n  bool operator !=(const LineIterator& other) const;\n\n  /*!\n   * Dereference the iterator with const.\n   * @return the value to which the iterator is pointing.\n   */\n  const Index& operator *() const;\n\n  /*!\n   * Increase the iterator to the next element.\n   * @return a reference to the updated iterator.\n   */\n  LineIterator& operator ++();\n\n  /*!\n   * Indicates if iterator is past end.\n   * @return true if iterator is out of scope, false if end has not been reached.\n   */\n  bool isPastEnd() const;\n\nprivate:\n\n\n  /*!\n   * Construct function.\n   * @param gridMap the grid map to iterate on.\n   * @param start the starting index of the line.\n   * @param end the ending index of the line.\n   * @return true if successful, false otherwise.\n   */\n  bool initialize(const grid_map::GridMap& gridMap, const Index& start, const Index& end);\n\n  /*!\n   * Computes the parameters requires for the line drawing algorithm.\n   */\n  void initializeIterationParameters();\n\n  /*!\n   * Finds the index of a position on a line within the limits of the map.\n   * @param[in] gridMap the grid map that defines the map boundaries.\n   * @param[in] start the position that will be limited to the map range.\n   * @param[in] end the ending position of the line.\n   * @param[out] index the index of the moved start position.\n   * @return true if successful, false otherwise.\n   */\n  bool getIndexLimitedToMapRange(const grid_map::GridMap& gridMap, const Position& start,\n                                 const Position& end, Index& index);\n\n  //! Current index.\n  Index index_;\n\n  //! Starting index of the line.\n  Index start_;\n\n  //! Ending index of the line.\n  Index end_;\n\n  //! Current cell number.\n  unsigned int iCell_;\n\n  //! Number of cells in the line.\n  unsigned int nCells_;\n\n  //! Helper variables for Bresenham Line Drawing algorithm.\n  Size increment1_, increment2_;\n  int denominator_, numerator_, numeratorAdd_;\n\n  //! Map information needed to get position from iterator.\n  Length mapLength_;\n  Position mapPosition_;\n  double resolution_;\n  Size bufferSize_;\n  Index bufferStartIndex_;\n\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n} /* namespace */\n", "meta": {"hexsha": "d758a8b7ace96fbc35674b04a264bd8a62632f35", "size": 3432, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_map_core/include/grid_map_core/iterators/LineIterator.hpp", "max_stars_repo_name": "saikrn112/grid_map", "max_stars_repo_head_hexsha": "f64a471c6fc9059a7db7e3327ff94a65f862d95c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-11-15T10:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-19T15:52:30.000Z", "max_issues_repo_path": "grid_map_core/include/grid_map_core/iterators/LineIterator.hpp", "max_issues_repo_name": "saikrn112/grid_map", "max_issues_repo_head_hexsha": "f64a471c6fc9059a7db7e3327ff94a65f862d95c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_core/include/grid_map_core/iterators/LineIterator.hpp", "max_forks_repo_name": "saikrn112/grid_map", "max_forks_repo_head_hexsha": "f64a471c6fc9059a7db7e3327ff94a65f862d95c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-02-20T17:33:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-18T20:48:36.000Z", "avg_line_length": 26.0, "max_line_length": 93, "alphanum_fraction": 0.6864801865, "num_tokens": 813, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.4437312984681471}}
{"text": "//igl\r\n#include <igl/opengl/glfw/Viewer.h>\r\n#include <igl/readMESH.h>\r\n#include <igl/readOBJ.h>\r\n#include <igl/writeOBJ.h>\r\n#include <igl/per_vertex_normals.h>\r\n#include <igl/per_corner_normals.h>\r\n#include <igl/boundary_facets.h>\r\n#include <igl/lbs_matrix.h>\r\n#include <igl/deform_skeleton.h>\r\n#include <igl/mat_max.h>\r\n#include <igl/mat_min.h>\r\n#include <igl/PI.h>\r\n#include <igl/volume.h>\r\n#include <igl/cat.h>\r\n#include <igl/png/writePNG.h>\r\n\r\n//internal\r\n#include <json.hpp>\r\n#include <read_data_from_json.h>\r\n#include <lumped_mass_matrix.h>\r\n#include <lbs_matrix.h>\r\n#include <create_mask_matrix.h>\r\n#include <line_search.h>\r\n#include <util.h>\r\n\r\n//Bartels\r\n#include <linear_tetmesh_dphi_dX.h>\r\n#include <linear_tetmesh_arap_dq.h>\r\n#include <linear_tetmesh_arap_dq2.h>\r\n#include <linear_tetmesh_arap_q.h>\r\n#include <linear_tetmesh_neohookean_dq.h>\r\n#include <linear_tetmesh_neohookean_dq2.h>\r\n#include <linear_tetmesh_neohookean_q.h>\r\n#include <linear_tetmesh_stvk_dq.h>\r\n#include <linear_tetmesh_stvk_dq2.h>\r\n#include <linear_tetmesh_stvk_q.h>\r\n#include <linear_tetmesh_corotational_dq.h>\r\n#include <linear_tetmesh_corotational_dq2.h>\r\n#include <linear_tetmesh_corotational_q.h>\r\n#include <simple_psd_fix.h>\r\n#include <Eigen/Sparse>\r\n#include <Eigen/Core>\r\n\r\n#include <iostream>\r\n#include <filesystem>\r\n\r\n\r\nconst Eigen::Vector3d red(255./255.,0./255.,0./255.);\r\nint frame = 0;\r\n\r\nvoid export_png_seq(igl::opengl::glfw::Viewer& viewer, const std::vector<Eigen::MatrixXd>& Vn_list, \r\n                    const std::string& json_path, const std::string& physic_model)\r\n{\r\n  frame = 0;\r\n  viewer.callback_pre_draw = [&](igl::opengl::glfw::Viewer &) -> bool\r\n\t{\r\n\t\tif(viewer.core().is_animating)\r\n\t\t{\r\n      Eigen::MatrixXd Vn = Vn_list[frame];\r\n      // viewer.data().set_mesh(Vn,F);\r\n      viewer.data().set_vertices(Vn);\r\n      viewer.data().compute_normals();\r\n\r\n      const std::string dir = igl::dirname(json_path) + PATH_SEPARATOR;;\r\n      size_t dot_found = json_path.find_last_of(\".\");\r\n      std::string model = std::string(json_path.begin()+dir.size(),json_path.begin()+dot_found);\r\n\r\n      std::string output_folder = \"../showcases\";\r\n      std::string output_path = output_folder+\"/\"+model+\"_\"+physic_model;\r\n      if(!std::filesystem::exists(output_path)){\r\n        std::filesystem::create_directory(output_path);\r\n      }\r\n\r\n      std::string numstr = std::to_string(frame);\r\n      int strlen = numstr.length();\r\n\r\n      std::string seqstr;\r\n      for(int k=0; k<(4-strlen); k++){\r\n          seqstr.append(\"0\");\r\n      }\r\n      seqstr.append(numstr);\r\n      std::string save_path = output_path+\"/\"+model+\"_\"+physic_model+\"_\"+seqstr+\".png\";\r\n\r\n      Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> R(1280,800);\r\n      Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> G(1280,800);\r\n      Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> B(1280,800);\r\n      Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic> A(1280,800);\r\n\r\n      // Draw the scene in the buffers\r\n      viewer.core().draw_buffer(viewer.data(),true,R,G,B,A);\r\n      igl::png::writePNG(R,G,B,A,save_path);\r\n\r\n\t\t\tframe++;\r\n      if(frame == Vn_list.size()){\r\n        viewer.core().is_animating = !viewer.core().is_animating;\r\n        frame = 0;\r\n      }\r\n\t\t}\r\n\t\treturn false;\r\n\t};\r\n}\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n  Eigen::MatrixXd V,C,W,VM; //V: vertices of tet-mesh, C: joint positions, W: skinning weight, VM: lbs matrix\r\n  Eigen::MatrixXi T,F,BE; //T: tet indices  of tet-mesh, F: face indices of tet-mesh, BE: edge indices of bone handle\r\n  Eigen::VectorXi PI; //PI: point indices of point handle\r\n\r\n  std::vector<Eigen::MatrixXd> TF_list; //list of transformation\r\n  double dt, YM, pr, scale; //dt: time step, YM: young's modulus, pr: poisson ratio, scale: custom scale of mesh\r\n\r\n  std::string json_path = argc>1?std::string(argv[1]):\"../examples/sphere/sphere.json\";\r\n  std::string physic_model;\r\n  read_json_data(json_path,V,T,F,C,PI,BE,W,TF_list,dt,YM,pr,scale,physic_model);\r\n\r\n  std::string str = argc>2?std::string(argv[2]):\"\";\r\n  bool export_objs = false;\r\n  if(str==\"export\")\r\n    export_objs=true;\r\n\r\n  double lambda, mu;\r\n  emu_to_lame(YM,pr,lambda,mu);\r\n\r\n  Eigen::MatrixXd params(T.rows(),2);\r\n  params.col(0) = 0.5*lambda*Eigen::VectorXd::Ones(T.rows());\r\n  params.col(1) = mu*Eigen::VectorXd::Ones(T.rows());\r\n\r\n  igl::boundary_facets(T, F);\r\n  F = F.rowwise().reverse().eval();\r\n\r\n\tigl::lbs_matrix(V,W,VM);\r\n\r\n  Eigen::VectorXd vol;\r\n  igl::volume(V,T,vol);\r\n\r\n  Eigen::MatrixXd dX;\r\n  sim::linear_tetmesh_dphi_dX(dX,V,T);\r\n\r\n  Eigen::SparseMatrix<double> M;\r\n  lumped_mass_matrix(V,T,M);\r\n  M = M*1000;\r\n\r\n  Eigen::SparseMatrix<double> A;\r\n  lbs_matrix_column(V,W,A);\r\n\r\n  Eigen::SparseMatrix<double> phi;\r\n  create_poisson_mask_matrix(V,T,phi);\r\n\r\n  Eigen::SparseMatrix<double> Aeq = A.transpose()*M*phi;\r\n  Eigen::VectorXd Beq = Eigen::VectorXd::Zero(A.cols());\r\n\r\n  Eigen::MatrixXd TF = TF_list[0];\r\n\r\n  Eigen::MatrixXd Vr = VM*TF;\r\n  Eigen::MatrixXd U = Vr-V;\r\n\r\n  int nc = V.rows()*V.cols();\r\n\r\n  Eigen::VectorXd UCol = vectorize(U);\r\n\r\n  Eigen::VectorXd VCol = vectorize(V);\r\n\r\n  Eigen::VectorXd UdCol = Eigen::VectorXd::Zero(nc);\r\n  Eigen::VectorXd UcCol = Eigen::VectorXd::Zero(nc);\r\n\r\n  std::vector<Eigen::MatrixXd> Vn_list(TF_list.size());\r\n  int max_iter = 20;\r\n  for(int ai=0; ai<TF_list.size(); ai++){\r\n    std::cout<<\"frame: \"<<ai<<std::endl;\r\n\r\n    Eigen::MatrixXd TF = TF_list[ai];\r\n\r\n    Eigen::VectorXd UCol0 = UCol;\r\n    Eigen::VectorXd UdCol0 = UdCol;\r\n    Eigen::VectorXd UcCol0 = UcCol;\r\n\r\n    Vr = VM*TF;\r\n    Eigen::MatrixXd Ur = Vr-V;\r\n    Eigen::VectorXd UrCol = vectorize(Ur);\r\n\r\n    for(int i=0; i<max_iter; i++)\r\n    {\r\n      Eigen::VectorXd q = VCol+UrCol+UcCol;\r\n      Eigen::VectorXd G;\r\n      Eigen::SparseMatrix<double> K;\r\n\r\n      if(physic_model==\"arap\"){\r\n        sim::linear_tetmesh_arap_dq(G,V,T,q,dX,vol,params);\r\n        sim::linear_tetmesh_arap_dq2(K,V,T,q,dX,vol,params,[](auto &a) {sim::simple_psd_fix(a, 1e-3);});\r\n      }\r\n      else if(physic_model==\"neohookean\"){\r\n        sim::linear_tetmesh_neohookean_dq(G,V,T,q,dX,vol,params);\r\n        sim::linear_tetmesh_neohookean_dq2(K,V,T,q,dX,vol,params,[](auto &a) {sim::simple_psd_fix(a, 1e-3);});\r\n      }\r\n      else if(physic_model==\"stvk\"){\r\n        sim::linear_tetmesh_stvk_dq(G,V,T,q,dX,vol,params);\r\n        sim::linear_tetmesh_stvk_dq2(K,V,T,q,dX,vol,params,[](auto &a) {sim::simple_psd_fix(a, 1e-3);});\r\n      }\r\n      else if(physic_model==\"corotational\"){\r\n        sim::linear_tetmesh_corotational_dq(G,V,T,q,dX,vol,params);\r\n        sim::linear_tetmesh_corotational_dq2(K,V,T,q,dX,vol,params,[](auto &a) {sim::simple_psd_fix(a, 1e-3);});\r\n      }\r\n      Eigen::VectorXd tmp_g = M/(dt*dt) * (UrCol+UcCol) - M*(UCol0/(dt*dt)+UdCol0/dt) + G;\r\n      Eigen::SparseMatrix<double> tmp_H = M/(dt*dt) + K;\r\n      tmp_H = 0.5 * (tmp_H+Eigen::SparseMatrix<double>(tmp_H.transpose()));\r\n\r\n      Eigen::SparseMatrix<double> AR1, AR2, AA;\r\n      igl::cat(2,tmp_H,Eigen::SparseMatrix<double>(Aeq.transpose()),AR1);\r\n      Eigen::SparseMatrix<double> SI(Aeq.rows(), Aeq.rows());\r\n      SI.setZero();\r\n      igl::cat(2,Aeq,SI,AR2);\r\n      igl::cat(1,AR1,AR2,AA);\r\n\r\n      Eigen::VectorXd b(tmp_g.size()+Beq.size());\r\n      b.head(tmp_g.size())=-tmp_g;\r\n      b.tail(Beq.size())=Beq;\r\n\r\n      Eigen::SimplicialLDLT<Eigen::SparseMatrix<double > > ldlt(AA);\r\n      Eigen::VectorXd dUc = ldlt.solve(b).head(tmp_g.size());\r\n\r\n      if(tmp_g.transpose()*dUc > -1e-6)\r\n        break;\r\n\r\n      std::function<double(const Eigen::VectorXd &, const Eigen::VectorXd &)> f;\r\n      f = [&](const Eigen::VectorXd &UrColi, const Eigen::VectorXd &UcColi){\r\n        double e = 0.5*(UrColi+UcColi-UCol0-dt*UdCol0).transpose()*M/(dt*dt)*(UrColi+UcColi-UCol0-dt*UdCol0);\r\n        if(physic_model==\"arap\"){\r\n          return e + sim::linear_tetmesh_arap_q(V, T, VCol+UrColi+UcColi, dX, vol, params);\r\n        }\r\n        else if(physic_model==\"neohookean\"){\r\n          return e + sim::linear_tetmesh_neohookean_q(V, T, VCol+UrColi+UcColi, dX, vol, params);\r\n        }\r\n        else if(physic_model==\"stvk\"){\r\n          return e + sim::linear_tetmesh_stvk_q(V, T, VCol+UrColi+UcColi, dX, vol, params);\r\n        }\r\n        else if(physic_model==\"corotational\"){\r\n          return e + sim::linear_tetmesh_corotational_q(V, T, VCol+UrColi+UcColi, dX, vol, params);\r\n        }\r\n      };\r\n      double alpha = line_search(f,tmp_g,dUc,UrCol,UcCol);\r\n      UcCol = UcCol + alpha * dUc;\r\n    }\r\n    UCol = UrCol + UcCol;\r\n    UdCol = (UCol-UCol0)/dt;\r\n\r\n    Eigen::MatrixXd Vn = V + matrixize(UCol);\r\n    Vn_list[ai] = Vn;\r\n\r\n  }\r\n  if(export_objs)\r\n  {\r\n    const std::string dir = igl::dirname(json_path) + PATH_SEPARATOR;;\r\n    size_t dot_found = json_path.find_last_of(\".\");\r\n    std::string model = std::string(json_path.begin()+dir.size(),json_path.begin()+dot_found);\r\n\r\n    std::string output_folder = \"../output\";\r\n    if(!std::filesystem::exists(output_folder)){\r\n      std::filesystem::create_directory(output_folder);\r\n    }\r\n    std::string output_path = output_folder+\"/\"+model+\"_\"+physic_model;\r\n    if(!std::filesystem::exists(output_path)){\r\n      std::filesystem::create_directory(output_path);\r\n    }\r\n    for(int ai=0; ai<Vn_list.size(); ai++)\r\n    {\r\n      Eigen::MatrixXd Vn = Vn_list[ai];\r\n      std::string numstr = std::to_string(ai);\r\n      int strlen = numstr.length();\r\n\r\n      std::string seqstr;\r\n      for(int k=0; k<(4-strlen); k++){\r\n          seqstr.append(\"0\");\r\n      }\r\n      seqstr.append(numstr);\r\n      std::string save_path = output_path+\"/\"+model+\"_\"+physic_model+\"_\"+seqstr+\".obj\";\r\n      igl::writeOBJ(save_path,Vn,F);\r\n    }\r\n  }\r\n\r\n\r\n\tigl::opengl::glfw::Viewer viewer;\r\n  viewer.data().set_mesh(V, F);\r\n  viewer.core().align_camera_center(V);\r\n  viewer.core().is_animating = true;\r\n  viewer.core().animation_max_fps = 24.;\r\n  viewer.data().show_lines = true;\r\n  viewer.data().show_overlay_depth = false;\r\n  viewer.core().background_color=Eigen::Vector4f::Ones();\r\n  viewer.callback_pre_draw = [&](igl::opengl::glfw::Viewer &) -> bool\r\n\t{\r\n\t\tif(viewer.core().is_animating)\r\n\t\t{\r\n      Eigen::MatrixXd Vn = Vn_list[frame];\r\n      viewer.data().set_vertices(Vn);\r\n      viewer.data().compute_normals();\r\n\t\t\tframe++;\r\n      if(frame == Vn_list.size()){\r\n        //viewer.core().is_animating = !viewer.core().is_animating;\r\n        frame = 0;\r\n      }\r\n\t\t}\r\n\t\treturn false;\r\n\t};\r\n\r\n\r\n  viewer.callback_key_down = [&](igl::opengl::glfw::Viewer &, unsigned int key, int mod)\r\n  {\r\n    if(key==' '){\r\n      viewer.core().is_animating = !viewer.core().is_animating;\r\n    }\r\n    if(key=='e' || key=='E'){\r\n      std::cout<<\"export png seq\"<<std::endl;\r\n      viewer.core().is_animating = true;\r\n      export_png_seq(viewer,Vn_list,json_path,physic_model);\r\n    }\r\n    return false;\r\n  };\r\n  viewer.launch();\r\n}\r\n", "meta": {"hexsha": "28ab2933392dc77dd67e78d09f4185b0e0edaa34", "size": 10855, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/complementary_dynamics.cpp", "max_stars_repo_name": "seungbaebang/complementary-dynamics-cpp", "max_stars_repo_head_hexsha": "a80f9579d714352fe541518cf89554d62b72a4f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2021-08-23T21:46:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T09:29:19.000Z", "max_issues_repo_path": "demo/complementary_dynamics.cpp", "max_issues_repo_name": "seungbaebang/complementary-dynamics-cpp", "max_issues_repo_head_hexsha": "a80f9579d714352fe541518cf89554d62b72a4f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/complementary_dynamics.cpp", "max_forks_repo_name": "seungbaebang/complementary-dynamics-cpp", "max_forks_repo_head_hexsha": "a80f9579d714352fe541518cf89554d62b72a4f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-08-23T21:39:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T14:49:40.000Z", "avg_line_length": 33.8161993769, "max_line_length": 118, "alphanum_fraction": 0.629571626, "num_tokens": 3209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.640635841117624, "lm_q1q2_score": 0.44373128758804237}}
{"text": "// BSD 3-Clause License\n\n// Copyright (c) 2021, Chenyu\n// All rights reserved.\n\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n\n// 1. Redistributions of source code must retain the above copyright notice, this\n//    list of conditions and the following disclaimer.\n\n// 2. Redistributions in binary form must reproduce the above copyright notice,\n//    this list of conditions and the following disclaimer in the documentation\n//    and/or other materials provided with the distribution.\n\n// 3. Neither the name of the copyright holder nor the names of its\n//    contributors may be used to endorse or promote products derived from\n//    this software without specific prior written permission.\n\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"rbr_sdp_solver.h\"\n\n#include <ceres/rotation.h>\n\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n\n#include \"bcm_sdp_solver.h\"\n#include \"math/matrix_square_root.h\"\n\nnamespace gopt {\nnamespace solver {\n\nRBRSDPSolver::RBRSDPSolver(const size_t n, const size_t block_dim)\n    : RBRSDPSolver(n, block_dim, solver::SDPSolverOptions()) {}\n\nRBRSDPSolver::RBRSDPSolver(\n    const size_t n, const size_t block_dim,\n    const solver::SDPSolverOptions& options)\n    : BCMSDPSolver(n, block_dim, options){\n  X_ = Eigen::MatrixXd::Identity(dim_ * n, dim_ * n);\n}\n\nvoid RBRSDPSolver::Solve(solver::Summary& summary) {\n  double prev_func_val = std::numeric_limits<double>::max();\n  double cur_func_val = this->EvaluateFuncVal();\n  double duration = 0.0;\n  double error = 0.0;\n\n  summary.begin_time = std::chrono::high_resolution_clock::now();\n  while (summary.total_iterations_num < sdp_solver_options_.max_iterations) {\n    if (sdp_solver_options_.verbose) {\n      this->LogToStd(summary.total_iterations_num, prev_func_val, cur_func_val,\n                     error, duration);\n    }\n\n    if (IsConverge(prev_func_val, cur_func_val, sdp_solver_options_.tolerance, &error)) {\n      break;\n    }\n\n    // convergence rate? Take it for consideration.\n    for (size_t k = 0; k < n_; k++) {\n      // Eliminating the k-th row and column from Y to form Bk\n      Eigen::MatrixXd B = Eigen::MatrixXd::Zero(3 * (n_ - 1), 3 * (n_ - 1));\n      this->ReformingB(k, B);\n\n      // Eliminating the k-th column and all but the k-th row from R to form Wk\n      Eigen::MatrixXd W = Eigen::MatrixXd::Zero(3 * (n_ - 1), 3);\n      this->ReformingW(k, W);\n\n      Eigen::MatrixXd B_multi_W = B * W;\n      Eigen::MatrixXd WtBW = W.transpose() * B_multi_W;\n\n      // FIXME: (chenyu) Solving matrix square root with\n      // SVD and LDL^T would generate different result\n      Eigen::MatrixXd WtBW_sqrt = MatrixSquareRoot(WtBW);\n      // Eigen::MatrixXd WtBW_sqrt =\n      // MatrixSquareRootForSemidefinitePositiveMat(WtBW);\n\n      // FIXME: (chenyu) Eigen 3.3.0 is required for the use of\n      // CompleteOrthogonalDecomposition<>\n      // Eigen::CompleteOrthogonalDecomposition<Eigen::MatrixXd> cqr(WtBW_sqrt);\n      // Eigen::Matrix3d moore_penrose_pseinv = cqr.pseudoInverse();\n      Eigen::Matrix3d moore_penrose_pseinv = WtBW_sqrt.inverse();\n\n      // compute S by fixing the error of Equ.(47) in Erikson's paper\n      Eigen::MatrixXd S = -B_multi_W * moore_penrose_pseinv;\n\n      // reordering X\n      this->ReorderingUnknown(k, B, S);\n    }\n\n    summary.total_iterations_num++;\n    duration = summary.Duration();\n\n    // Update function value\n    prev_func_val = cur_func_val;\n    cur_func_val = this->EvaluateFuncVal();\n  }\n\n  summary.total_iterations_num++;\n  if (sdp_solver_options_.verbose) {\n    this->LogToStd(summary.total_iterations_num, prev_func_val, cur_func_val,\n                   error, duration);\n  }\n}\n\ndouble RBRSDPSolver::EvaluateFuncVal() const {\n  return EvaluateFuncVal(X_);\n}\n\ndouble RBRSDPSolver::EvaluateFuncVal(const Eigen::MatrixXd& Y) const {\n  return (Q_ * Y).trace();\n}\n\nvoid RBRSDPSolver::ReformingB(const size_t k, Eigen::MatrixXd& B) {\n  size_t r = 0, c = 0;  // the row and column index of matrix B\n\n  for (size_t i = 0; i < n_; i++) {\n    if (i == k) continue;\n    c = 0;\n    for (size_t j = 0; j < n_; j++) {\n      if (j == k) continue;\n\n      B.block(3 * r, 3 * c, 3, 3) = X_.block(3 * i, 3 * j, 3, 3);\n      c++;\n    }\n    r++;\n  }\n}\n\nvoid RBRSDPSolver::ReformingW(const size_t k, Eigen::MatrixXd& W) {\n  size_t r = 0;  // row index of matrix W\n\n  for (size_t i = 0; i < n_; i++) {\n    if (i == k) continue;\n\n    W.block(3 * r, 0, 3, 3) = Q_.block(3 * i, 3 * k, 3, 3);\n    r++;\n  }\n}\n\nvoid RBRSDPSolver::ReorderingUnknown(const size_t k, const Eigen::MatrixXd& B,\n                                     const Eigen::MatrixXd& S) {\n  // Reordering X according to [Algorithm 1] in paper:\n  // - Z. Wen, D. Goldfarb, S. Ma, and K. Scheinberg.\n  //   Row by row methods for semidefinite programming.\n  //   Technical report, Columbia University, 2009. 7\n\n  // Update X(k, k)\n  X_.block(3 * k, 3 * k, 3, 3) = Eigen::Matrix3d::Identity();\n\n  // Update the k-th column of Y, except Y(k, k)\n  size_t j = 0;  // the j-th block of S\n  for (size_t i = 0; i < n_; i++) {\n    if (i == k) continue;\n    X_.block(3 * i, 3 * k, 3, 3) = S.block(3 * j, 0, 3, 3);\n    j++;\n  }\n\n  // Update the k-th row of Y, except Y(k, k)\n  size_t i = 0;  // the i-th block of S\n  for (size_t j = 0; j < n_; j++) {\n    if (j == k) continue;\n    X_.block(3 * k, 3 * j, 3, 3) = S.block(3 * i, 0, 3, 3).transpose();\n    i++;\n  }\n}\n\n}  // namespace solver\n}  // namespace gopt\n", "meta": {"hexsha": "d5328747e83c087c945eca1a1bed41297e8afdba", "size": 6330, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/solver/rbr_sdp_solver.cc", "max_stars_repo_name": "AIBluefisher/GraphOptim", "max_stars_repo_head_hexsha": "0c32f945cba0c158c58b14b4e146e91911738357", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 82.0, "max_stars_repo_stars_event_min_datetime": "2021-04-18T16:34:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T12:08:36.000Z", "max_issues_repo_path": "src/solver/rbr_sdp_solver.cc", "max_issues_repo_name": "whuaegeanse/GraphOptim", "max_issues_repo_head_hexsha": "0c32f945cba0c158c58b14b4e146e91911738357", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-04-19T15:09:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T15:01:06.000Z", "max_forks_repo_path": "src/solver/rbr_sdp_solver.cc", "max_forks_repo_name": "whuaegeanse/GraphOptim", "max_forks_repo_head_hexsha": "0c32f945cba0c158c58b14b4e146e91911738357", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2021-04-19T02:14:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T05:53:00.000Z", "avg_line_length": 33.670212766, "max_line_length": 89, "alphanum_fraction": 0.6660347551, "num_tokens": 1806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.443731280834382}}
{"text": "#include \"farm_ng/calibration/visual_odometer.h\"\n\n#include <opencv2/highgui.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/imgproc.hpp>\n#include <opencv2/video.hpp>\n\n#include <Eigen/Geometry>\n\n#include <ceres/ceres.h>\n\n#include \"farm_ng/blobstore.h\"\n#include \"farm_ng/ipc.h\"\n#include \"farm_ng/sophus_protobuf.h\"\n\n#include \"farm_ng/calibration/camera_model.h\"\n#include \"farm_ng/calibration/eigen_cv.h\"\n#include \"farm_ng/calibration/kinematics.h\"\n#include \"farm_ng/calibration/local_parameterization.h\"\n\nnamespace farm_ng {\nnamespace {\n\nvoid SavePly(std::string ply_path, const std::vector<Eigen::Vector3d>& points) {\n  LOG(INFO) << ply_path << \" npoints: \" << points.size();\n  std::ofstream out(ply_path);\n  out << \"ply\\n\";\n  out << \"format ascii 1.0\\n\";\n  out << \"element vertex \" << points.size() << \"\\n\";\n  out << \"property float x\\n\";\n  out << \"property float y\\n\";\n  out << \"property float z\\n\";\n  out << \"end_header\\n\";\n  for (auto p : points) {\n    out << float(p.x()) << \" \" << float(p.y()) << \" \" << float(p.z()) << \"\\n\";\n  }\n  out.close();\n}\nstruct ProjectionCostFunctor {\n  ProjectionCostFunctor(const CameraModel& camera_model,\n                        const Eigen::Vector2d& point_image)\n      : camera_model_(camera_model), point_image_(point_image) {}\n\n  template <class T>\n  bool operator()(T const* const raw_camera_pose_world,\n                  T const* const raw_point_world, T* raw_residuals) const {\n    Eigen::Map<Sophus::SE3<T> const> const camera_pose_world(\n        raw_camera_pose_world);\n\n    Eigen::Map<Eigen::Matrix<T, 3, 1> const> const point_world(raw_point_world);\n    Eigen::Map<Eigen::Matrix<T, 2, 1>> residuals(raw_residuals);\n    residuals =\n        ProjectPointToPixel<T>(camera_model_, camera_pose_world * point_world) -\n        point_image_.cast<T>();\n    return true;\n  }\n  const CameraModel& camera_model_;\n  Eigen::Vector2d point_image_;\n};\n\nstruct PoseCostFunctor {\n  PoseCostFunctor(const Sophus::SE3d& camera_start_pose_camera_end)\n      : camera_end_pose_camera_start_(camera_start_pose_camera_end.inverse()) {}\n\n  template <class T>\n  bool operator()(T const* const raw_camera_pose_world_start,\n                  T const* const raw_camera_pose_world_end,\n                  T* raw_residuals) const {\n    Eigen::Map<Sophus::SE3<T> const> const camera_pose_world_start(\n        raw_camera_pose_world_start);\n\n    Eigen::Map<Sophus::SE3<T> const> const camera_pose_world_end(\n        raw_camera_pose_world_end);\n\n    auto camera_start_pose_camera_end_est =\n        camera_pose_world_start * camera_pose_world_end.inverse();\n\n    auto camera_end_pose_camera_end_est =\n        camera_end_pose_camera_start_.cast<T>() *\n        camera_start_pose_camera_end_est;\n\n    Eigen::Map<Eigen::Matrix<T, 6, 1>> residuals(raw_residuals);\n    residuals = T(100) * camera_end_pose_camera_end_est.log();\n    return true;\n  }\n  Sophus::SE3d camera_end_pose_camera_start_;\n};\n}  // namespace\nVisualOdometer::VisualOdometer(const CameraModel& camera_model,\n                               const BaseToCameraModel& base_to_camera_model,\n                               size_t max_history)\n    : camera_model_(camera_model),\n      flow_(camera_model, max_history),\n      base_to_camera_model_(base_to_camera_model),\n      odometry_pose_base_(Sophus::SE3d::rotX(0.0)) {\n  ProtoToSophus(base_to_camera_model_.base_pose_camera().a_pose_b(),\n                &base_pose_camera_);\n}\n\nvoid VisualOdometer::AddWheelMeasurements(\n    const BaseToCameraModel::WheelMeasurement& measurements) {\n  wheel_measurements_.insert(measurements);\n}\n\nVisualOdometerResult VisualOdometer::AddImage(\n    cv::Mat image, google::protobuf::Timestamp stamp) {\n  VisualOdometerResult result;\n  if (const FlowImage* prev_flow_image = flow_.PreviousFlowImage()) {\n    auto wheel_measurements =\n        wheel_measurements_.find_range(prev_flow_image->stamp, stamp);\n\n    Sophus::SE3d base_pose_basep = TractorStartPoseTractorEnd(\n        base_to_camera_model_.wheel_radius(),\n        base_to_camera_model_.wheel_baseline(), wheel_measurements.first,\n        wheel_measurements.second);\n    Sophus::SE3d odometry_pose_base_wheel_only =\n        (base_pose_camera_ * prev_flow_image->camera_pose_world).inverse() *\n        base_pose_basep;\n\n    odometry_pose_base_ = odometry_pose_base_wheel_only;\n    if ((true || base_pose_basep.log().norm() > 0.001) &&\n        !wheel_measurements_.empty()) {\n      auto start = MakeTimestampNow();\n\n      flow_.AddImage(image, stamp,\n                     odometry_pose_base_wheel_only * base_pose_camera_, true);\n      debug_image_ = flow_.GetDebugImage();\n      auto after_flow = MakeTimestampNow();\n\n      SolvePose(true);\n      odometry_pose_base_ =\n          (base_pose_camera_ * flow_.PreviousFlowImage()->camera_pose_world)\n              .inverse();\n\n      wheel_measurements_.RemoveBefore(flow_.EarliestFlowImage()->stamp);\n      auto after_solve = MakeTimestampNow();\n      LOG_EVERY_N(INFO, 100)\n          << \"VO took: \"\n          << google::protobuf::util::TimeUtil::DurationToMilliseconds(\n                 after_solve - start)\n          << \" ms flow: \"\n          << google::protobuf::util::TimeUtil::DurationToMilliseconds(\n                 after_flow - start)\n          << \" ms solve: \"\n          << google::protobuf::util::TimeUtil::DurationToMilliseconds(\n                 after_solve - after_flow);\n\n      if (false && flow_.LastImageId() % 100 == 0) {\n        DumpFlowPointsWorld(\"/tmp/flow_points_world.\" +\n                            std::to_string(flow_.LastImageId()) + \".ply\");\n      }\n    }\n\n  } else {\n    flow_.AddImage(image, stamp, odometry_pose_base_ * base_pose_camera_, true);\n    debug_image_ = flow_.GetDebugImage();\n  }\n\n  if (goal_image_id_) {\n    // TODO(ethanrublee) this is goal pose stuff here is a HACK, should be moved\n    // somewhere else, tracking camera can produce some generic poses which can\n    // be used for a variety of control and path following modes.\n    //\n    // Here the base_pose_goal is the start of the planned path (parameterized\n    // as the x+ axis of this frame). For convenience downstream, we'll project\n    // the tractor's goal (nearest point on this path + some reasonable\n    // distance) onto this path.\n    Sophus::SE3d base_pose_goal = base_pose_camera_ * camera_pose_base_goal_;\n    // The path is the parameterized line passing through the origin of goal\n    // frame and along the X axis.\n    // This line is in the base frame.\n    auto path_base = Eigen::ParametrizedLine<double, 3>::Through(\n        base_pose_goal.translation(),\n        base_pose_goal * Eigen::Vector3d(1.0, 0, 0));\n\n    // Project the origin of the base frame onto the line, this is the closest\n    // point on the path. Here we transform the point into the goal's reference\n    // frame. We expect this point to be non zero in X, and zero in y,z as it\n    // lies on the X-axis of the goal reference frame.\n    Eigen::Vector3d closest_path_point_goal =\n        base_pose_goal.inverse() *\n        path_base.projection(Eigen::Vector3d(0, 0, 0));\n    CHECK_NEAR(closest_path_point_goal.y(), 0.0, 1e-6);\n    CHECK_NEAR(closest_path_point_goal.z(), 0.0, 1e-6);\n\n    // Here we add 3 meters to the nearest point on the line.  Think of this\n    // like a carrot on a stick hanging 3 meters front of the robot on the\n    // planned path line.\n    // NOTE this distance will effect the move to goal controller behavior.  If\n    // its large, then the heading corrections will be less and the tractor will\n    // gradually correct to get onto the path.  If its too small, the tractor\n    // will pivot dramatically trying to stay on the line.\n\n    Sophus::SE3d base_pose_goal_carrot =\n        base_pose_goal *\n        Sophus::SE3d::transX(closest_path_point_goal.x() + 10.0);\n    SophusToProto(base_pose_goal_carrot,\n                  result.base_pose_goal.mutable_a_pose_b());\n    if (!debug_image_.empty()) {\n      cv::circle(debug_image_,\n                 EigenToCvPoint(ProjectPointToPixel(\n                     camera_model_, base_pose_camera_.inverse() *\n                                        base_pose_goal_carrot.translation())),\n                 10, cv::Scalar(255, 0, 0), 3);\n    }\n  } else {\n    SophusToProto(Sophus::SE3d::rotZ(0.0),\n                  result.base_pose_goal.mutable_a_pose_b());\n  }\n  result.base_pose_goal.mutable_a_pose_b()->mutable_stamp()->CopyFrom(stamp);\n  result.base_pose_goal.set_frame_a(\"tractor/base\");\n  result.base_pose_goal.set_frame_b(\"goal\");\n\n  SophusToProto(odometry_pose_base_,\n                result.odometry_vo_pose_base.mutable_a_pose_b());\n  result.odometry_vo_pose_base.mutable_a_pose_b()->mutable_stamp()->CopyFrom(\n      stamp);\n  result.odometry_vo_pose_base.set_frame_a(\"odometry/vo\");\n  result.odometry_vo_pose_base.set_frame_b(\"tractor/base\");\n\n  return result;\n}\n\nvoid VisualOdometer::AddFlowBlockToProblem(ceres::Problem* problem,\n                                           const FlowBlock& flow_block) {\n  ceres::CostFunction* cost_function1 =\n      new ceres::AutoDiffCostFunction<ProjectionCostFunctor, 2,\n                                      Sophus::SE3d::num_parameters, 3>(\n          new ProjectionCostFunctor(\n              camera_model_,\n              flow_block.flow_point_image.point_image.cast<double>()));\n\n  problem->AddParameterBlock(flow_block.flow_point_world->point_world.data(),\n                             3);\n  problem->AddResidualBlock(cost_function1, new ceres::CauchyLoss(2),\n                            flow_block.flow_image->camera_pose_world.data(),\n                            flow_block.flow_point_world->point_world.data());\n}\n\nvoid VisualOdometer::AddFlowImageToProblem(FlowImage* flow_image,\n                                           ceres::Problem* problem,\n                                           FlowBlocks* flow_blocks) {\n  problem->AddParameterBlock(flow_image->camera_pose_world.data(),\n                             Sophus::SE3d::num_parameters,\n                             new LocalParameterizationSE3);\n\n  for (const auto& id_flow_point : flow_image->flow_points) {\n    const FlowPointImage& flow_point = id_flow_point.second;\n\n    FlowPointWorld* flow_point_world =\n        flow_.MutableFlowPointWorld(flow_point.id);\n    if (flow_point_world->image_ids.size() < 5) {\n      continue;\n    }\n    if (true) {  // flow_blocks->size() < 100 ||\n                 // flow_blocks->count(flow_point_world->id)) {\n      FlowBlock flow_block({flow_image, flow_point_world, flow_point});\n      (*flow_blocks)[flow_point_world->id].push_back(flow_block);\n      AddFlowBlockToProblem(problem, flow_block);\n    }\n  }\n}\nvoid VisualOdometer::SolvePose(bool debug) {\n  ceres::Problem problem;\n\n  std::set<uint64_t> flow_image_ids;\n  FlowBlocks flow_blocks;\n  {\n    uint64_t image_id(flow_.LastImageId());\n    if (image_id < 5) {\n      return;\n    }\n    uint64_t begin_id =\n        std::max(int(flow_.EarliestFlowImage()->id), int(image_id) - 50);\n    flow_image_ids.insert(image_id);\n    if (goal_image_id_) {\n      if (int(image_id) - int(*goal_image_id_) < 50) {\n        flow_image_ids.insert(*goal_image_id_);\n      }\n    }\n    uint64_t skip = std::max(1, (int(image_id) - int(begin_id)) / 5);\n    while (begin_id < image_id) {\n      flow_image_ids.insert(begin_id);\n      begin_id += skip;\n    }\n  }\n  // debugging which images are used.\n  if (false) {\n    std::stringstream ss;\n    for (auto id : flow_image_ids) {\n      ss << \" \" << id;\n    }\n    LOG(INFO) << \"Num images: \" << flow_image_ids.size() << ss.str();\n  }\n\n  for (auto image_id : flow_image_ids) {\n    FlowImage* flow_image = flow_.MutableFlowImage(image_id);\n    AddFlowImageToProblem(flow_image, &problem, &flow_blocks);\n  }\n\n  for (auto start = flow_image_ids.begin(), end = ++flow_image_ids.begin();\n       end != flow_image_ids.end(); ++start, ++end) {\n    FlowImage* flow_image_start = flow_.MutableFlowImage(*start);\n    FlowImage* flow_image_end = flow_.MutableFlowImage(*end);\n\n    auto wheel_measurements = wheel_measurements_.find_range(\n        flow_image_start->stamp, flow_image_end->stamp);\n    VLOG(2) << std::distance(wheel_measurements.first,\n                             wheel_measurements.second)\n            << \" Wheel measurements\";\n\n    Sophus::SE3d base_start_pose_base_end = TractorStartPoseTractorEnd(\n        base_to_camera_model_.wheel_radius(),\n        base_to_camera_model_.wheel_baseline(), wheel_measurements.first,\n        wheel_measurements.second);\n\n    Sophus::SE3d camera_start_pose_camera_end = base_pose_camera_.inverse() *\n                                                base_start_pose_base_end *\n                                                base_pose_camera_;\n    ceres::CostFunction* cost_function1 =\n        new ceres::AutoDiffCostFunction<PoseCostFunctor, 6,\n                                        Sophus::SE3d::num_parameters,\n                                        Sophus::SE3d::num_parameters>(\n            new PoseCostFunctor(camera_start_pose_camera_end));\n\n    problem.AddResidualBlock(cost_function1, new ceres::CauchyLoss(1.0),\n                             flow_image_start->camera_pose_world.data(),\n                             flow_image_end->camera_pose_world.data());\n  }\n\n  if (false && goal_image_id_ && flow_image_ids.count(*goal_image_id_)) {\n    problem.SetParameterBlockConstant(\n        flow_.MutableFlowImage(*goal_image_id_)->camera_pose_world.data());\n  }\n\n  // Set solver options (precision / method)\n  ceres::Solver::Options options;\n  // options.linear_solver_type = ceres::SPARSE_SCHUR;\n  options.gradient_tolerance = 1e-4;\n  options.function_tolerance = 1e-4;\n  options.parameter_tolerance = 1e-4;\n  // options.num_threads = 1;\n  options.max_num_iterations = 30;\n\n  // Solve\n  ceres::Solver::Summary summary;\n  //  options.logging_type = ceres::PER_MINIMIZER_ITERATION;\n  options.minimizer_progress_to_stdout = false;\n  ceres::Solve(options, &problem, &summary);\n  LOG_EVERY_N(INFO, 100) << summary.BriefReport();\n  if (!summary.IsSolutionUsable()) {\n    LOG(INFO) << summary.FullReport();\n  }\n\n  double all_rmse = 0;\n  double all_n = 0;\n  for (auto id_blocks : flow_blocks) {\n    uint64_t point_world_id = id_blocks.first;\n    double rmse = 0;\n    double n = 0;\n    for (auto block : id_blocks.second) {\n      Eigen::Vector3d point_camera = block.flow_image->camera_pose_world *\n                                     block.flow_point_world->point_world;\n      Eigen::Vector2d point_image_proj =\n          ProjectPointToPixel(camera_model_, point_camera);\n\n      if (point_camera.z() < 0) {\n        flow_.RemoveBlock(block);\n        continue;\n      }\n\n      if (point_camera.norm() > 5e2) {\n        flow_.RemoveBlock(block);\n        continue;\n      }\n      double err2 =\n          (point_image_proj - block.flow_point_image.point_image.cast<double>())\n              .squaredNorm();\n      if (err2 > (4 * 4)) {\n        flow_.RemoveBlock(block);\n      } else {\n        rmse += err2;\n        n += 1;\n      }\n    }\n    auto flow_point_world = flow_.MutableFlowPointWorld(point_world_id);\n    if (flow_point_world->image_ids.size() < 5 ||\n        flow_point_world->point_world.norm() > 1e3) {\n      flow_.RemovePointWorld(point_world_id);\n    } else {\n      flow_.MutableFlowPointWorld(point_world_id)->rmse = std::sqrt(rmse / n);\n      all_rmse += rmse;\n      all_n += n;\n    }\n  }\n  LOG_EVERY_N(INFO, 100) << \"RMSE: \"\n                         << std::sqrt(all_rmse / std::max(all_n, 1.0))\n                         << \" N: \" << all_n;\n\n  FlowImage* flow_image = flow_.MutablePreviousFlowImage();\n\n  if (goal_image_id_) {\n    auto base_pose_world_goal =\n        camera_pose_base_goal_.inverse() *\n        flow_.MutableFlowImage(*goal_image_id_)->camera_pose_world;\n\n    auto camera_pose_base_goal =\n        flow_image->camera_pose_world * base_pose_world_goal.inverse();\n\n    goal_image_id_ = flow_image->id;\n    camera_pose_base_goal_ = camera_pose_base_goal;\n  }\n\n  if (debug) {\n    cv::Mat reprojection_image = debug_image_;\n    if (reprojection_image.empty()) {\n      cv::cvtColor(*(flow_image->image), reprojection_image,\n                   cv::COLOR_GRAY2BGR);\n    }\n\n    for (const auto& id_flow_point : flow_image->flow_points) {\n      const auto& flow_point = id_flow_point.second;\n      FlowPointWorld* flow_point_world =\n          flow_.MutableFlowPointWorld(flow_point.id);\n      if (flow_point_world->rmse == 0.0) {\n        continue;\n      }\n      Eigen::Vector2d point_image_proj =\n          ProjectPointToPixel(camera_model_, flow_image->camera_pose_world *\n                                                 flow_point_world->point_world);\n      cv::line(reprojection_image, EigenToCvPoint(flow_point.point_image),\n               EigenToCvPoint(point_image_proj), flow_.Color(flow_point.id));\n\n      cv::circle(reprojection_image, EigenToCvPoint(point_image_proj), 2,\n                 flow_.Color(flow_point.id), -1);\n      cv::circle(reprojection_image, EigenToCvPoint(flow_point.point_image), 5,\n                 flow_.Color(flow_point.id));\n    }\n    if (goal_image_id_) {\n      for (int i = 0; i < 1000; ++i) {\n        Eigen::Vector3d p1 =\n            camera_pose_base_goal_ * Eigen::Vector3d(0.1 * i, 0.0, 0.0);\n        Eigen::Vector3d p2 =\n            camera_pose_base_goal_ * Eigen::Vector3d(0.1 * (i + 1), 0.0, 0.0);\n        if (p1.z() > 0.0 && p2.z() > 0.00) {\n          cv::line(reprojection_image,\n                   EigenToCvPoint(ProjectPointToPixel(camera_model_, p1)),\n                   EigenToCvPoint(ProjectPointToPixel(camera_model_, p2)),\n                   cv::Scalar(0, 255, 0), 3);\n        }\n      }\n    }\n    auto camera_pose_base = base_pose_camera_.inverse();\n    for (int i = 0; i < 1000; ++i) {\n      Eigen::Vector3d ap1 =\n          camera_pose_base * Eigen::Vector3d(0.1 * i, 0.0, 0.0);\n      Eigen::Vector3d ap2 =\n          camera_pose_base * Eigen::Vector3d(0.1 * (i + 1), 0.0, 0.0);\n      cv::line(reprojection_image,\n               EigenToCvPoint(ProjectPointToPixel(camera_model_, ap1)),\n               EigenToCvPoint(ProjectPointToPixel(camera_model_, ap2)),\n               cv::Scalar(0, 0, 255), 1);\n    }\n    debug_image_ = reprojection_image;\n  }\n}\n\nvoid VisualOdometer::DumpFlowPointsWorld(std::string ply_path) {\n  std::vector<Eigen::Vector3d> points;\n  for (auto it : flow_.FlowPointsWorld()) {\n    if (it.second.image_ids.size() >= 5) {\n      points.push_back(it.second.point_world);\n    }\n  }\n  SavePly(ply_path, points);\n}\n\nvoid VisualOdometer::SetGoal() {\n  if (flow_.LastImageId() < 10) {\n    return;\n  }\n  goal_image_id_ = flow_.LastImageId();\n  camera_pose_base_goal_ = base_pose_camera_.inverse();\n}\n\nvoid VisualOdometer::AdjustGoalAngle(double theta) {\n  if (!goal_image_id_) {\n    return;\n  }\n  camera_pose_base_goal_ = camera_pose_base_goal_ * Sophus::SE3d::rotZ(theta);\n}\n\n}  // namespace farm_ng\n", "meta": {"hexsha": "48db7ecbf6dd648c8dc0130c517d5c94a7ef2a1f", "size": 18763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/farm_ng/calibration/visual_odometer.cpp", "max_stars_repo_name": "jinfwhuang/tractor", "max_stars_repo_head_hexsha": "66450b8695f10633b619a1525669d41e1d213843", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/farm_ng/calibration/visual_odometer.cpp", "max_issues_repo_name": "jinfwhuang/tractor", "max_issues_repo_head_hexsha": "66450b8695f10633b619a1525669d41e1d213843", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/farm_ng/calibration/visual_odometer.cpp", "max_forks_repo_name": "jinfwhuang/tractor", "max_forks_repo_head_hexsha": "66450b8695f10633b619a1525669d41e1d213843", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9817813765, "max_line_length": 80, "alphanum_fraction": 0.64904333, "num_tokens": 4670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4435870120263027}}
{"text": "// Copyright (c) 2014 The Pebblecoin developers\n// Distributed under the MIT/X11 software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\n#include <cassert>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"contract_grading.h\"\n\nnamespace cryptonote\n{\n  uint64_t grade_amount(uint64_t full_amount, uint32_t grade, uint32_t fee_scale)\n  {\n    assert(grade <= GRADE_SCALE_MAX);\n    assert(fee_scale <= GRADE_SCALE_MAX);\n    \n    // amount_left will be rounded down\n    boost::multiprecision::uint128_t graded_amount = full_amount;\n    graded_amount *= grade;\n    graded_amount /= GRADE_SCALE_MAX;\n    assert(graded_amount == (uint64_t)graded_amount);\n    \n    // calculate fee\n    boost::multiprecision::uint128_t fee = graded_amount;\n    fee *= fee_scale;\n    fee /= GRADE_SCALE_MAX;\n    assert(fee == (uint64_t)fee);\n    // round fee taken up to prevent coins from being created via fee rounding\n    while (fee_scale > 0 && fee * GRADE_SCALE_MAX / fee_scale < graded_amount)\n    {\n      fee += 1;\n    }\n    assert(fee <= graded_amount);\n    \n    boost::multiprecision::uint128_t amount_left = graded_amount - fee;\n    assert(amount_left == amount_left.convert_to<uint64_t>());\n    return amount_left.convert_to<uint64_t>();\n  }\n  \n  uint64_t grade_contract_amount(uint64_t contract_amount, uint32_t grade, uint32_t fee_scale)\n  {\n    // coins resolve to the grade\n    return grade_amount(contract_amount, grade, fee_scale);\n  }\n\n  uint64_t grade_backing_amount(uint64_t locked_amount, uint32_t grade, uint32_t fee_scale)\n  {\n    // the backing coins resolve to the other side of the contract\n    assert(grade <= GRADE_SCALE_MAX);\n    return grade_amount(locked_amount, GRADE_SCALE_MAX - grade, fee_scale);\n  }\n  \n  \n  uint64_t calculate_total_fee(uint64_t total_contract_coins, uint32_t fee_scale)\n  {\n    assert(fee_scale <= GRADE_SCALE_MAX);\n    \n    // round fee reward down\n    boost::multiprecision::uint128_t fee = total_contract_coins;\n    fee *= fee_scale;\n    fee /= GRADE_SCALE_MAX;\n    assert(fee == fee.convert_to<uint64_t>());\n    \n    return fee.convert_to<uint64_t>();\n  }\n}\n", "meta": {"hexsha": "5f4161dfe75c31a334cf9ed60364c847216f259e", "size": 2149, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cryptonote_core/contract_grading.cpp", "max_stars_repo_name": "Camellia73/cryonote", "max_stars_repo_head_hexsha": "f1cf0779507226ad8b411321e3e4d9f4122f1d61", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-07-10T11:40:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T01:09:13.000Z", "max_issues_repo_path": "src/cryptonote_core/contract_grading.cpp", "max_issues_repo_name": "Camellia73/cryonote", "max_issues_repo_head_hexsha": "f1cf0779507226ad8b411321e3e4d9f4122f1d61", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-11-23T19:14:36.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-08T17:46:45.000Z", "max_forks_repo_path": "src/cryptonote_core/contract_grading.cpp", "max_forks_repo_name": "Camellia73/cryonote", "max_forks_repo_head_hexsha": "f1cf0779507226ad8b411321e3e4d9f4122f1d61", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-03-14T03:14:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-09T11:48:58.000Z", "avg_line_length": 31.6029411765, "max_line_length": 94, "alphanum_fraction": 0.7156817124, "num_tokens": 532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.44338636768248685}}
{"text": "#ifndef __COMMON_HPP__\r\n#define __COMMON_HPP__\r\n\r\n/******************************\r\n      Author: Joel Veness\r\n        Date: 2011\r\n******************************/\r\n\r\n#include <vector>\r\n#include <cmath>\r\n\r\n// boost includes\r\n#include <boost/cstdint.hpp>\r\n#include <boost/dynamic_bitset.hpp>\r\n\r\n#include \"Neighbours.hpp\"\r\n\r\n// define a bit type\r\ntypedef uint8_t bit_t;\r\n\r\n// stores symbol occurrence counts\r\ntypedef float count_t;\r\n\r\n// holds context weights\r\ntypedef double weight_t;\r\n\r\n// describe a binary context\r\ntypedef std::vector<bit_t> context_t;\r\n\r\n// describe a binary history\r\ntypedef Neighbours history_t;\r\n\r\n/* given log(x) and log(y), compute log(x+y). uses the following identity:\r\n   log(x + y) = log(x) + log(1 + y/x) = log(x) + log(1+exp(log(y)-log(x)))*/\r\ninline double logAdd(double log_x, double log_y) {\r\n\r\n    // ensure log_y >= log_x, can save some expensive log/exp calls\r\n    if (log_x > log_y) {\r\n        double t = log_x; log_x = log_y; log_y = t;\r\n    }\r\n\r\n    // only replace log(1+exp(log(y)-log(x))) with log(y)-log(x)\r\n    // if the the difference is small enough to be meaningful\r\n    double tmp = log_y - log_x;\r\n\r\n    if (tmp < 100.0) {\r\n        return std::log(1.0 + std::exp(tmp)) + log_x;\r\n    } else {\r\n        return log_y;\r\n    }\r\n}\r\n\r\n\r\n// compressor interface\r\nclass Compressor {\r\n\r\n    public:\r\n\r\n        virtual ~Compressor() {}\r\n\r\n        // the probability of seeing a particular symbol next\r\n        virtual double prob(bit_t b) = 0;\r\n\r\n        // the logarithm of the probability of all processed experience\r\n        virtual double logBlockProbability() const = 0;\r\n\r\n        // process a new piece of sensory experience\r\n        virtual void update(bit_t b) = 0;\r\n\r\n        // file extension\r\n        virtual const char *fileExtension() const = 0;\r\n};\r\n\r\n\r\n#endif // __COMMON_HPP__\r\n\r\n", "meta": {"hexsha": "3c0260e1ecb0c3a52d4a6f7408da9bb684456dc3", "size": 1834, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common.hpp", "max_stars_repo_name": "lake4790k/pseudo-count-atari", "max_stars_repo_head_hexsha": "a64e9688da115a9cbc21206ac0768f5c94410546", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-06-29T22:25:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T16:06:00.000Z", "max_issues_repo_path": "src/common.hpp", "max_issues_repo_name": "lake4790k/pseudo-count-atari", "max_issues_repo_head_hexsha": "a64e9688da115a9cbc21206ac0768f5c94410546", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common.hpp", "max_forks_repo_name": "lake4790k/pseudo-count-atari", "max_forks_repo_head_hexsha": "a64e9688da115a9cbc21206ac0768f5c94410546", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8181818182, "max_line_length": 77, "alphanum_fraction": 0.5997818975, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.44338636768248685}}
{"text": "// Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.\n\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef UUID_3DCF6B90AE0E11DE9A315BE555D89593\n#define UUID_3DCF6B90AE0E11DE9A315BE555D89593\n\n#include <boost/qvm/inline.hpp>\n#include <boost/qvm/mat_traits_array.hpp>\n#include <boost/qvm/static_assert.hpp>\n\nnamespace boost {\nnamespace qvm {\nnamespace qvm_detail {\ntemplate <int N> struct det_size {};\n\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL typename mat_traits<M>::scalar_type\ndeterminant_impl_(M const &a, det_size<2>) {\n  return mat_traits<M>::template read_element<0, 0>(a) *\n             mat_traits<M>::template read_element<1, 1>(a) -\n         mat_traits<M>::template read_element<1, 0>(a) *\n             mat_traits<M>::template read_element<0, 1>(a);\n}\n\ntemplate <class M, int N>\nBOOST_QVM_INLINE_RECURSION typename mat_traits<M>::scalar_type\ndeterminant_impl_(M const &a, det_size<N>) {\n  typedef typename mat_traits<M>::scalar_type T;\n  T m[N - 1][N - 1];\n  T det = T(0);\n  for (int j1 = 0; j1 != N; ++j1) {\n    for (int i = 1; i != N; ++i) {\n      int j2 = 0;\n      for (int j = 0; j != N; ++j) {\n        if (j == j1)\n          continue;\n        m[i - 1][j2] = mat_traits<M>::read_element_idx(i, j, a);\n        ++j2;\n      }\n    }\n    T d = determinant_impl_(m, det_size<N - 1>());\n    if (j1 & 1)\n      d = -d;\n    det += mat_traits<M>::read_element_idx(0, j1, a) * d;\n  }\n  return det;\n}\n\ntemplate <class M>\nBOOST_QVM_INLINE_TRIVIAL typename mat_traits<M>::scalar_type\ndeterminant_impl(M const &a) {\n  BOOST_QVM_STATIC_ASSERT(mat_traits<M>::rows == mat_traits<M>::cols);\n  return determinant_impl_(a, det_size<mat_traits<M>::rows>());\n}\n} // namespace qvm_detail\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "b8bd27109005f90b004c9268a0b0aab37bb5f029", "size": 1851, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/detail/determinant_impl.hpp", "max_stars_repo_name": "henrywarhurst/matrix", "max_stars_repo_head_hexsha": "317a2a7c35c1c7e3730986668ad2270dc19809ef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/boost_1_72_0/boost/qvm/detail/determinant_impl.hpp", "max_issues_repo_name": "henrywarhurst/matrix", "max_issues_repo_head_hexsha": "317a2a7c35c1c7e3730986668ad2270dc19809ef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/boost_1_72_0/boost/qvm/detail/determinant_impl.hpp", "max_forks_repo_name": "henrywarhurst/matrix", "max_forks_repo_head_hexsha": "317a2a7c35c1c7e3730986668ad2270dc19809ef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8548387097, "max_line_length": 79, "alphanum_fraction": 0.6645056726, "num_tokens": 582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.44338636128150416}}
{"text": "/*\n        Program is testing out a prototype for\n        game tree solvers. Tick Tack Toe is \n        especially nice as it's super simple,\n        but has some interesting characteristsics\n           - Game tree has many nodes\n             which are invarant, ie one\n             node can be represented by\n             a rotation or mirror of \n             another node, which means \n             can have a system which \"merges\"\n             nodes\n           - We know a-prori that their is\n             a solved solution, which we \n             can visually check\n           - We can create the static game \n             tree, not need to worry about\n             the complexity\n          \n\n        One thing to consider with these sorts\n        or designs, is that we done want to\n        have redendant data, \n\n\n                   \n        <start> -- (0,0) -- (1,1) -- ...\n                \\- (1,0)\n                ...\n                \\- (3,3) -- (1,1)\n\n        Once we have this static game tree, we\n        can then work backwards to figure \n        out of an optmial strategy\n                \n\n */\n\n#include <iostream>\n#include <tuple>\n#include <map>\n#include <cassert>\n#include <sstream>\n#include <random>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include <bitset>\n#include <boost/lexical_cast.hpp>\n\n#define PRINT(X) do{ std::cout << #X << \" = \" << ( X ) << \"\\n\"; }while(0)\n\n/*\n        Hero villian is arbitary,\n        just convention, with Hero\n        begin player who does the first\n        move\n */\nenum Player{\n        Player_NotAPlayer,\n        Player_Hero,         // first\n        Player_Villian       // second\n};\ninline char PlayerToken(Player p){\n        switch (p) {\n        case Player_NotAPlayer:\n                return ' ';\n        case Player_Hero:\n                return 'X';\n        case Player_Villian:\n                return 'O';\n        }\n}\n\ntemplate<class To, class From>\ninline To Cast(From ptr){\n        //PRINT( ptr->GetType() );\n        //PRINT( std::remove_pointer_t<To>::__type__() );\n        if( ptr->GetType() == std::remove_pointer_t<To>::__type__())\n                return reinterpret_cast<To>(ptr);\n        std::stringstream fmt;\n        fmt << \"casting \" << ptr->GetType() << \" to \" << std::remove_pointer_t<To>::__type__();\n        throw std::domain_error(fmt.str());\n}\n\nenum Eval{\n        Eval_Win   = 0x01,\n        Eval_Draw  = 0x02,\n        Eval_Lose  = 0x04,\n};\nstd::string EvalToString(Eval e) {\n        switch (e) {\n        case Eval_Win:\n                return \"Eval_Win\";\n        case Eval_Draw:\n                return \"Eval_Draw\";\n        case Eval_Lose:\n                return \"Eval_Lose\";\n        }\n}\n\n\nnamespace Detail{\n        struct PictureBox{\n                PictureBox(){\n                        lines_.emplace_back();\n                }\n                void NewLine(){\n                        lines_.emplace_back();\n                }\n                void Append(std::string const& s){\n                        lines_.back() += s;\n                }\n                void Append(char c){\n                        lines_.back() += c;\n                }\n                void Display(){\n                        for( size_t i=lines_.size();i!=0;){\n                                --i;\n                                std::cout << lines_[i] << \"\\n\";\n                        }\n                }\n                PictureBox& operator+=(PictureBox const& that){\n                       for(; lines_.size() < that.lines_.size();)\n                              NewLine(); \n                       for(size_t i=0;i!=std::min(lines_.size(), that.lines_.size());++i){\n                               lines_[i] += that.lines_[i];\n                       }\n                       return *this;\n                }\n                static PictureBox Make(std::string const& s){\n                        PictureBox result;\n                        for( char c : s){\n                                switch(c){\n                                case '\\n':\n                                        result.NewLine();\n                                        break;\n                                default:\n                                        result.Append(c);\n                                        break;\n                                }\n                        }\n                        return std::move(result);\n                }\n        private:\n                std::vector<std::string> lines_;\n        };\n} // Detail\n\nstruct Board{\n        /*\n                For each pair of bits, we have\n\n                +----+-----------+\n                |Mask|    Data   |\n                +----+-----------+\n                | 00 | NotAPlayer|\n                | 01 |  Hero     |\n                | 10 | Villian   |\n                +----+-----------+\n         */\n        Player GetTile(int x, int y)const{\n                auto offset = Map_(x,y);\n                return static_cast<Player>(( mask_ & ( 0x3 << offset ) ) >> offset);\n        }\n        void SetTile(int x, int y, Player p){\n                assert( GetTile(x,y) == 0 && \"Tile already set\");\n                auto offset = Map_(x,y);\n                mask_ |= ( p << offset );\n                assert( GetTile(x,y) == p  && \"post condition failed\");\n        }\n\n        friend std::ostream& operator<<(std::ostream& ostr, Board const& board){\n                static const char* lineBreak = \"+---+---+---+\";\n                for(int y=3;y!=0;){\n                        --y;\n\n                        if( y == 2 ){\n                                ostr << lineBreak << \"\\n\";\n                        }\n\n                        for(int x=0;x!=3;++x){\n                                ostr << \"| \" << PlayerToken(board.GetTile(x,y)) << \" \";\n                                if( x == 2 )\n                                        ostr << \"|\\n\";\n                        }\n                        ostr << lineBreak;\n                        if( y != 0 )\n                                ostr << \"\\n\";\n                }\n                return ostr;\n        }\n        std::string ToString()const{\n                std::stringstream sstr;\n                sstr << *this;\n                return sstr.str();\n        }\n        auto GetMask()const{ return mask_; }\n\n        auto GetInvariant()const{\n                /*\n                        a b c\n                        d e f\n                        g h i\n                 */\n                auto a = 0;\n                auto b = 1;\n                auto c = 2;\n                auto d = 3;\n                auto e = 4;\n                auto f = 5;\n                auto g = 6;\n                auto h = 7;\n                auto i = 8;\n\n                std::vector<std::vector<int> > perms = {\n                        /*\n                        Normal Case (Rotate 0)\n                         */\n                        { a, b, c,\n                          d, e, f,\n                          g, h, i },\n                        /*\n                        Rotate 90\n                         */\n                        {  g, d, a,\n                           h, e, b,\n                           i, f, c },\n                        \n                        /*\n                        Rotate 180\n                         */\n                        {  i, h, g,\n                           f, e, d,\n                           c, b, a },\n                        /*\n                        Rotate 270\n                         */\n                        {  c, f, i,\n                           b, e, h,\n                           a, d, g },\n                        /*\n                        Mirror Above\n                         */\n                        {  g, h, i,\n                           d, e, f,\n                           a, b, c },\n                        \n                        /*\n                        Mirror Center\n                         */\n                        {  c, b, a,\n                           f, e, d,\n                           i, h, g } \n                };\n\n                std::vector<std::uint32_t> masks;\n                for( auto const& p : perms ){\n                        static std::vector<std::pair<int, int> > cord = {\n                                { 0, 0},\n                                { 1, 0},\n                                { 2, 0},\n                                { 0, 1},\n                                { 1, 1},\n                                { 2, 1},\n                                { 0, 2},\n                                { 1, 2},\n                                { 2, 2}\n                        };\n                        Board aux;\n                        for(size_t idx=0;idx!=9;++idx){\n                                auto tok = GetTile(cord[idx].first, cord[idx].second);\n                                aux.SetTile(cord[p[idx]].first, cord[p[idx]].second, tok);\n                        }\n                        masks.push_back(aux.GetMask());\n                }\n                return *std::min_element(masks.begin(), masks.end());\n        }\nprivate:\n        static int Map_(int x, int y){\n                return 2 * ( x * 3 + y );\n        }\n        std::uint32_t mask_ = 0;\n};\n\n/*\n        Only one thing in the context, whos turn is it\n        Obviously the Board is part of the context,\n        but we have 2-tuples\n                (B,C),\n        to represent this\n*/\n\nenum GameCtrl{\n        GameCtrl_Continue,\n        GameCtrl_HeroWins,\n        GameCtrl_VillianWins,\n        GameCtrl_Draw\n};\nconst char* GameCtrlToString(GameCtrl e) {\n        switch (e) {\n        case GameCtrl_Continue:\n                return \"GameCtrl_Continue\";\n        case GameCtrl_HeroWins:\n                return \"GameCtrl_HeroWins\";\n        case GameCtrl_VillianWins:\n                return \"GameCtrl_VillianWins\";\n        case GameCtrl_Draw:\n                return \"GameCtrl_Draw\";\n        }\n}\n\nstruct GameContext{\n        explicit GameContext(Board board = Board{}):board_{std::move(board)}{}\n        explicit GameContext(Player active):active_{active}{}\n        auto const& GetBoard()const{ return board_; }\n        auto& GetBoard(){ return board_; }\n        auto ActivePlayer()const{ return active_; }\n        char ActivePlayerToken()const{\n                return ( ActivePlayer() == 0 ? 'x' : 'o' );\n        }\n        void NextPlayer(){\n                switch(active_){\n                case Player_Hero:\n                        active_ = Player_Villian;\n                        break;\n                case Player_Villian:\n                        active_ = Player_Hero;\n                        break;\n                // stop compiler warning\n                case Player_NotAPlayer:\n                        break;\n                }\n        }\n        auto GetCtrl()const{ return ctrl_; }\n        auto SetCtrl(GameCtrl ctrl){ ctrl_ = ctrl; }\n        friend bool operator<(GameContext const& lp, GameContext const& rp){\n                #if 1\n                return std::make_tuple(lp.board_.GetInvariant(), lp.ctrl_, lp.active_ )\n                     < std::make_tuple(rp.board_.GetInvariant(), rp.ctrl_, rp.active_ );\n                #else\n                return std::make_tuple(lp.board_.GetMask(), lp.ctrl_, lp.active_ )\n                     < std::make_tuple(rp.board_.GetMask(), rp.ctrl_, rp.active_ );\n                #endif\n        }\nprivate:\n        Board board_;\n        GameCtrl ctrl_{ GameCtrl_Continue };\n        Player active_{ Player_Hero };\n};\n\nstruct TickTackToeLogic{\n        GameContext Next(GameContext ctx, size_t x, size_t y){\n                assert( ctx.GetCtrl()  == GameCtrl_Continue && \"precondition failed\");\n                assert( ctx.GetBoard().GetTile(x,y)    == 0          && \"precondition failed\");\n\n                ctx.GetBoard().SetTile(x,y, ctx.ActivePlayer() );\n\n                // First need to check to see if someone has made a line\n                auto triple = [&](auto x0, auto y0,\n                                 auto x1, auto y1,\n                                 auto x2, auto y2){\n                        auto tok = ctx.GetBoard().GetTile(x0, y0);\n                        if( tok == Player_NotAPlayer )\n                                return false;\n                        return \n                                tok == ctx.GetBoard().GetTile(x1,y1) &&\n                                tok == ctx.GetBoard().GetTile(x2,y2);\n                };\n\n                static std::vector< std::vector<size_t> > protos = \n                {\n                        { 0, 0, 0, 1, 0, 2}, \n                        { 1, 0, 1, 1, 1, 2}, \n                        { 2, 0, 2, 1, 2, 2}, \n                        { 0, 0, 1, 0, 2, 0}, \n                        { 0, 1, 1, 1, 2, 1}, \n                        { 0, 2, 1, 2, 2, 2}, \n                        { 0, 0, 1, 1, 2, 2}, \n                        { 0, 2, 1, 1, 2, 0}\n                };\n\n                for( auto const& p : protos){\n                        if( triple( p[0], p[1], p[2], p[3], p[4], p[5]) ){\n                                if( ctx.GetBoard().GetTile(p[0], p[1]) == Player_Hero){\n                                        ctx.SetCtrl( GameCtrl_HeroWins );\n                                } else {\n                                        ctx.SetCtrl( GameCtrl_VillianWins );\n                                }\n                                return std::move(ctx);\n                        }\n                }\n\n                // If we get here, their isn't a winner\n                auto is_full = [&](){\n                        for( size_t i=0;i!=3;++i){\n                                for( size_t j=0;j!=3;++j){\n                                        if( ctx.GetBoard().GetTile(i,j) == 0 )\n                                                return false;\n\n                                }\n                        }\n                        return true;\n                };\n\n                if( is_full() )\n                        ctx.SetCtrl( GameCtrl_Draw );\n                else\n                        ctx.NextPlayer();\n                return std::move(ctx);\n        }\n};\n\n\nstruct Node{\n        enum Type{\n                Type_Choice,\n                Type_Payoff\n        };\npublic:\n        Type GetType()const{ return type_; }\n        GameContext const& GetContext()const{ return ctx_; }\nprotected:\n        explicit Node(Type type, GameContext ctx):\n                type_{type},\n                ctx_{std::move(ctx)}\n        {}\nprivate:\n        Type type_;\n        GameContext ctx_;\n};\n\nstruct ChoiceNode : Node{\n        explicit ChoiceNode(GameContext ctx):\n                Node{Type_Choice, std::move(ctx)}\n        {}\n        // only when Choice\n        void RegisterChild(Node* ptr){\n                next_.push_back(ptr);\n        }\n        auto NumChildren()const{\n                return next_.size();\n        }\n        auto begin()const{ return next_.begin(); }\n        auto end()const{ return next_.end(); }\n        static Type __type__(){ return Type_Choice; }\nprivate:\n        std::vector<Node*> next_;\n};\n\nstruct PayoffNode : Node{\n        explicit PayoffNode(GameContext ctx, Eval eval):\n                Node{Type_Payoff, std::move(ctx)}\n                ,eval_{eval}\n        {}\n        auto GetPayoff()const{ return eval_; }\n        static Type __type__(){ return Type_Payoff; }\nprivate:\n        Eval eval_;\n};\n\n// TODO, rather than create a new graph, use this\nstruct NodeReference{\nprivate:\n        Node* ptr_;\n        std::vector<Node*> next_;\n};\n\nstruct GameTree{\n        GameTree(Node* root):root_{root}{\n                Register(root);\n        }\n        void AppendTerminal(Node* ptr){\n                terminals_.push_back(ptr);\n        }\n        auto GetRoot()const{\n                return root_;\n        }\n        auto const& GetTerminals()const{ return terminals_; }\n        void Register(Node* ptr){\n                world_.emplace(ptr->GetContext(), ptr);\n                aux_.push_back(ptr);\n        }\n        Node const* Lookup(GameContext const& ctx)const{\n                auto iter = world_.find(ctx);\n                if( iter == world_.end())\n                        return nullptr;\n                return iter->second;\n        }\n        auto begin()const{ return aux_.begin(); }\n        auto end()const{ return aux_.end(); }\nprivate:\n        Node* root_;\n        std::vector<Node*> terminals_;\n        std::map< GameContext, Node* > world_;\n        std::vector<Node*> aux_;\n};\n\n\n/*\n        Idea here, is that when creating a board\n        which is invariant to anoher already \n        created, we can return the reference\n */\nstruct NodeFactory{\n        std::pair<bool, Node*> Make(GameContext ctx){\n                auto iter = world_.find(ctx);\n                if( iter != world_.end() )\n                        return std::make_pair(false, iter->second);\n\n                Node* ptr = nullptr;\n                switch(ctx.GetCtrl()){\n                case GameCtrl_Continue:\n                        ptr = new ChoiceNode{ctx};\n                        break;\n                case GameCtrl_HeroWins:\n                        ptr = new PayoffNode{ctx, Eval_Win};\n                        break;\n                case GameCtrl_VillianWins:\n                        ptr = new PayoffNode{ctx, Eval_Lose};\n                        break;\n                case GameCtrl_Draw:\n                        ptr = new PayoffNode{ctx, Eval_Draw};\n                        break;\n                }\n                world_.emplace(ctx, ptr);\n                return std::make_pair(true, ptr);\n        }\n\nprivate:\n        std::map< GameContext, Node* > world_;\n};\n\n/*\n        this is used to abstrauct the construction of\n        the game tree\n*/\nstruct GameTreeBuilder{\n        void Generate(GameTree& tree, ChoiceNode* parent, GameContext ctx){\n                static TickTackToeLogic logic;\n                for( int x=0;x!=3;++x){\n                        for( int y=0;y!=3;++y){\n                                if( ctx.GetBoard().GetTile(x,y) == 0 ){\n                                        \n                                        auto nextCtx = logic.Next(ctx, x,y);\n\n                                        auto makeRet = fac_.Make(nextCtx);\n                                        auto ptr = makeRet.second;\n                                        if( makeRet.first){\n                                                // New node\n\n                                                // First time here\n                                                tree.Register(ptr);\n\n                                                switch(nextCtx.GetCtrl()){\n                                                case GameCtrl_Continue:\n                                                        Generate(tree, Cast<ChoiceNode*>(ptr), nextCtx);\n                                                        break;\n                                                case GameCtrl_HeroWins:\n                                                case GameCtrl_VillianWins:\n                                                case GameCtrl_Draw:\n                                                        tree.AppendTerminal(ptr);\n                                                        break;\n                                                }\n                                        }\n                                        parent->RegisterChild(ptr);\n                                }\n                        }\n                }\n        }\n        GameTree Make(GameContext ctx){\n                auto ptr = new ChoiceNode{ctx};\n                GameTree tree{ptr};\n                // Assume board isn't finished\n                Generate(tree, ptr, ctx);\n                return std::move(tree);\n        }\nprivate:\n        NodeFactory fac_;\n};\n\n\nvoid test0(){\n        GameContext ctx;\n        Board board;\n        TickTackToeLogic logic;\n\n        std::vector< std::tuple<int, int> > todo = {\n                { 0, 0 },\n                { 1, 1 },\n                { 0, 1 },\n                { 0, 2 },\n                { 1, 2 },\n                { 2, 0 }\n        };\n\n        for( auto const& m : todo ){\n                ctx = logic.Next(ctx, std::get<0>(m), std::get<1>(m) );\n                PRINT(GameCtrlToString(ctx.GetCtrl()));\n                //std::cout << board;\n        }\n\n\n}\n\nvoid DisplayImpl(std::vector<Node*> history){\n        if( history.size() == 0 )\n                return;\n        auto target = history.back();\n        size_t indent_width = ( history.size() - 1 ) * 17;\n        Detail::PictureBox indent;\n        for(size_t i=7;i!=0;){\n                --i;\n                indent.Append(std::string(indent_width, ' ') );\n                if( i != 0 )\n                        indent.NewLine();\n        }\n        \n        if( history.back()->GetType() == Node::Type_Payoff ){\n                static auto spacer = [](){\n                        Detail::PictureBox proto;\n                        proto.Append(\"    \");\n                        proto.NewLine();\n                        proto.Append(\"    \");\n                        proto.NewLine();\n                        proto.Append(\"    \");\n                        proto.NewLine();\n                        proto.Append(\" => \");\n                        proto.NewLine();\n                        proto.Append(\"    \");\n                        proto.NewLine();\n                        proto.Append(\"    \");\n                        proto.NewLine();\n                        proto.Append(\"    \");\n                        return std::move(proto);\n                }();\n\n                Detail::PictureBox picture;\n                #if 0\n                picture += indent;\n                picture += Detail::PictureBox::Make( history.back()->GetContext().GetBoard().ToString() );\n                #endif\n                for( auto ptr : history){\n                        picture += Detail::PictureBox::Make( ptr->GetContext().GetBoard().ToString() );\n                        picture += spacer;\n\n                }\n                picture += spacer;\n\n                Detail::PictureBox leaf;\n                leaf.NewLine();\n                leaf.NewLine();\n                leaf.NewLine();\n                leaf.Append(\"Payoff \" + boost::lexical_cast<std::string>(Cast<PayoffNode*>(target)->GetPayoff()));\n\n                picture += leaf;\n                picture.Display();\n\n        } else {\n                #if 0\n                Detail::PictureBox picture;\n                picture += indent;\n                picture += Detail::PictureBox::Make( history.back()->GetContext().GetBoard().ToString() );\n                picture.Display();\n                #endif\n                for( auto ptr : *Cast<ChoiceNode*>(target)){\n                        history.push_back(ptr);\n                        DisplayImpl(history);\n                        history.pop_back();\n\n                }\n        }\n\n}\nvoid Display(Node* ptr){\n        std::vector<Node*> history = {ptr};\n        DisplayImpl(history);\n}\n\n\n/*\n        Need to iterate the game tree, and evaluate each node.\n        For nodes where it's the player, need to decide \n        which is the best move by backwards induction\n\n\n        From a payoff node, We find the most recent move the \n        player made, and mark is a Never.\n\n\n        Idea here is that for every move we do, we try to\n        take the move with is gurenteed a win, else we take\n        the move with a either a win or draw (depending on opp), \n        then we take move with is only draw, then we take move\n        which is win or lose, then take move with is win lose draw\n\n\n        Note that in the game theory sense of a strategy, we\n        need a move for every possible board, so this includeds\n        taking a move we know will lose, even though we won't get\n        their following out path.\n\n        On nodes where it's the opponents move, we basically \n        assume that he is going to take the optimum move, if their\n        is a move we can take, which results in a node with\n */\n\n\nstruct EvalMetric{\n        struct Result{\n                unsigned Mask()const{ return mask_; }\n                auto begin()const{ return next_.begin(); }\n                auto end()const{ return next_.end(); }\n        private:\n                friend struct EvalMetric;\n                unsigned mask_;\n                std::vector<Node const*> next_;\n        };\n        static std::unique_ptr<EvalMetric> MakeForHero(GameTree const& tree){\n                auto ptr = std::make_unique<EvalMetric>();\n                ptr->Populate_(Player_Hero, tree.GetRoot());\n                return std::move(ptr);\n        }\n        auto const& operator()(GameContext const& ctx)const{\n                auto iter = eval_.find(ctx);\n                if( iter == eval_.end()){\n                        throw std::domain_error(\"not in tree\");\n                }\n                return iter->second;\n        }\nprivate:\n\n\n        unsigned Populate_(Player p, Node const* node){\n                auto ctx = node->GetContext();\n                if( eval_.count(ctx) != 0 )\n                        return eval_[ctx].mask_;\n\n                if( node->GetType() == Node::Type_Payoff ){\n                        static std::map<Eval,Eval> invMap = {{Eval_Lose, Eval_Win}, {Eval_Draw, Eval_Draw}, {Eval_Win, Eval_Lose}};\n                        auto payoff = Cast<PayoffNode const*>(node)->GetPayoff();\n                        if( p  == Player_Villian ){\n                                payoff = invMap[payoff];\n                        }\n                        eval_[ctx].mask_ = payoff;\n                        return eval_[ctx].mask_;\n                }\n\n                using aggregator_t = std::function<Eval(std::vector<Eval>const&)>;\n\n                aggregator_t hero_agg_ = [](std::vector<Eval> const& v){\n                        return v.front();\n                };\n\n                \n                auto choicePtr = Cast<ChoiceNode const*>(node);\n\n\n                if(ctx.ActivePlayer() == p ){\n                        [&](){\n                                /*\n                                        Want to find the path in this order,\n                                        first we want to find nodes where we win,\n                                        then win or draw (depending on opps move),\n                                        etc\n                                 */\n                                static std::vector<unsigned> ticker = {\n                                        Eval_Win,\n                                        Eval_Win | Eval_Draw,\n                                        Eval_Draw,\n                                        Eval_Win | Eval_Lose,\n                                        Eval_Win | Eval_Draw | Eval_Lose,\n                                        Eval_Draw | Eval_Lose,\n                                        Eval_Lose\n                                };\n                                for( auto t : ticker ){\n                                        bool found = false;\n                                        for( auto child : *choicePtr){\n                                                if( Populate_(p, child) == t ){\n                                                        // Their may be more than one\n                                                        found = true;\n                                                        eval_[ctx].mask_ = t;\n                                                        eval_[ctx].next_.push_back(child);\n                                                }\n                                        }\n                                        if( found )\n                                                return;\n                                }\n                                assert( choicePtr->NumChildren() == 0 );\n                        }();\n                        return eval_[ctx].mask_;\n                } else {\n                        unsigned e = 0;\n                        auto& ref = eval_[ctx];\n                        for( auto child : *choicePtr){\n                                e |= Populate_(p, child);\n                                ref.next_.push_back(child);\n                        }\n                        ref.mask_ = e;\n                        return e;\n                }\n        }\n        std::map<GameContext, Result> eval_;\n};\n\nstruct StrategyBuilder{\n        GameTree Build(GameTree const& tree){\n                NodeFactory fac;\n\n                auto rootRet = fac.Make(tree.GetRoot()->GetContext());\n                auto root = rootRet.second;\n\n                GameTree stratTree{root};\n\n                auto metric = EvalMetric::MakeForHero(tree);\n\n                std::vector<Node*> stack;\n                stack.push_back(root);\n                for(;stack.size();){\n                        auto ptr = stack.back();\n                        stack.pop_back();\n\n                        if( ptr->GetType() == Node::Type_Payoff)\n                                continue;\n\n                        auto choicePtr = Cast<ChoiceNode*>(ptr);\n\n                        switch(ptr->GetContext().ActivePlayer()){\n                        case Player_Hero:{\n\n                                auto item = (*metric)(ptr->GetContext());\n\n                                for( auto branch : item ){\n                                        auto makeRet =fac.Make(branch->GetContext()); \n                                        auto next = makeRet.second;\n                                        if( makeRet.first ){\n                                                stratTree.Register(next);\n                                                stack.push_back(next);\n                                        }\n                                        choicePtr->RegisterChild(next);\n                                        break;\n                                }\n                                break;\n                        }\n                        /*\n                                For villian we just need to copy\n                                every possible move\n                        */\n                        case Player_Villian: {\n                                auto aux = tree.Lookup(ptr->GetContext());\n                                if( aux == nullptr ){\n                                        std::cerr << \"Can't find :(\\n\";\n                                        break;\n                                }\n                                for( auto child : *Cast<ChoiceNode const*>(aux)){\n\n                                        auto makeRet = fac.Make(child->GetContext());\n                                        auto next = makeRet.second;\n                                        if( makeRet.first ){\n                                                stratTree.Register(next);\n                                                stack.push_back(next);\n                                        }\n                                        choicePtr->RegisterChild(next);\n                                }\n                                break;\n                        }\n                        default:\n                                break;\n                        }\n                }\n\n                return std::move(stratTree);\n        }\n};\n\nvoid RenderToDot(GameTree const& tree){\n        std::cout << \"digraph structs{\\n\";\n        std::cout << \"node [shape=record]\\n\";\n\n        unsigned terminalMask = 0;\n\n        auto tag = [](Node const* ptr){\n                return \"Node\" + boost::lexical_cast<std::string>(ptr);\n        };\n\n        for( auto ptr : tree){\n                auto t = tag(ptr);\n                auto const& b = ptr->GetContext().GetBoard();\n                std::cout \n                        << t << \" [shape=record,label=\\\"\"\n                        << \"{\"\n                                << \"{\"\n                                << PlayerToken(b.GetTile(0,0)) << \"|\"\n                                << PlayerToken(b.GetTile(1,0)) << \"|\"\n                                << PlayerToken(b.GetTile(2,0))\n                                << \"}\"\n                        << \"|\"\n                                << \"{\"\n                                << PlayerToken(b.GetTile(0,1)) << \"|\"\n                                << PlayerToken(b.GetTile(1,1)) << \"|\"\n                                << PlayerToken(b.GetTile(2,1))\n                                << \"}\"\n                        << \"|\"\n                                << \"{\"\n                                << PlayerToken(b.GetTile(0,2)) << \"|\"\n                                << PlayerToken(b.GetTile(1,2)) << \"|\"\n                                << PlayerToken(b.GetTile(2,2))\n                                << \"}\"\n                        << \"}\\\"];\\n\";\n                if( ptr->GetType() == Node::Type_Choice ){\n                        for( auto next : *Cast<ChoiceNode*>(ptr)){\n                                std::cout << t << \" -> \" << tag(next) << \";\\n\";\n                        }\n                }\n\n                if( ptr->GetType() == Node::Type_Payoff ){\n                        auto payoff = Cast<PayoffNode*>(ptr)->GetPayoff();\n                        std::cout << t << \" -> \" << EvalToString(payoff) << \";\\n\";\n                        terminalMask |= payoff;\n                }\n        }\n\n        std::cout << \"}\";\n}\n\nenum RenderOpt{\n        RenderOpt_Solve,\n};\nvoid render(Player p, RenderOpt opt){\n\n        TickTackToeLogic logic;\n        GameTreeBuilder builder;\n        GameContext ctx(p);\n        auto tree = builder.Make(ctx);\n        \n        switch(opt){\n        case RenderOpt_Solve:{\n                StrategyBuilder sb;\n                auto ret = sb.Build(tree);\n                RenderToDot(ret);\n        }\n                break;\n        }\n}\n\nvoid test2(){\n        Detail::PictureBox first, second;\n        first.Append(\"hello\");\n        first.NewLine();\n        first.Append(\"world\");\n        second.Append(\" oh \");\n        second.NewLine();\n        second.Append(\"yeah\");\n        first += second;\n        first.Display();\n}\n\n\nvoid driver(){\n        GameContext ctx{Player_Villian};\n        GameTreeBuilder builder;\n        TickTackToeLogic logic;\n        auto tree = builder.Make(ctx);\n\n        StrategyBuilder sb;\n        auto strat = sb.Build(tree);\n\n        std::random_device gen;\n        std::uniform_int_distribution<int> dist(0,666);\n        \n\n        for(;ctx.GetCtrl() == GameCtrl_Continue;){\n                std::cout << ctx.GetBoard() << \"\\n\";\n\n                switch(ctx.ActivePlayer()){\n                case Player_Hero: {\n                        auto move = Cast<ChoiceNode const*>(strat.Lookup(ctx));\n\n                        assert( !! move );\n\n                        // dedeuce move\n                        auto randomOffset = dist(gen) % move->NumChildren();\n                        auto nextMove = *std::next(move->begin(), randomOffset );\n                        PRINT(move->NumChildren());\n                        auto t = [&](){\n                                for(size_t i=0;i!=3;++i){\n                                        for(size_t j=0;j!=3;++j){\n                                                if(     move->GetContext().GetBoard().GetTile(i,j) !=\n                                                    nextMove->GetContext().GetBoard().GetTile(i,j) ){\n                                                        return std::make_tuple(i,j);\n                                                }\n\n                                        }\n                                }\n                                throw std::domain_error(\"not move\");\n                        }();\n                        \n                        ctx = logic.Next(ctx, std::get<0>(t), std::get<1>(t));\n                        break;\n                }\n                case Player_Villian: {\n                        char x_s, y_s;\n                        std::cin >> x_s >> y_s;\n                        do{\n                                if(! ( std::isdigit(x_s) && std::isdigit(y_s))){\n                                        std::cerr << \"Invalid Move\\n\";\n                                        break;\n                                }\n                                int x = x_s - '0';\n                                int y = y_s - '0';\n                                if( ctx.GetBoard().GetTile(x,y) != Player_NotAPlayer ){\n                                        std::cerr << \"Invalid Move\\n\";\n                                        break;\n                                }\n                                ctx = logic.Next(ctx, x - '0', y - '0');\n                        }while(0);\n                        break;\n                }\n                default:\n                        break;\n                }\n        }\n        std::cout << ctx.GetBoard() << \"\\n\";\n        switch(ctx.GetCtrl()){\n        case GameCtrl_Continue:\n                break;\n        case GameCtrl_HeroWins:\n                std::cout << \"Computer Won\\n\";\n                break;\n        case GameCtrl_VillianWins:\n                std::cout << \"You Won\\n\";\n                break;\n        case GameCtrl_Draw:\n                std::cout << \"Draw\\n\";\n                break;\n        default:\n                return;\n        }\n}\n\n\n\nint main(int argc, char* argv[]){\n        try{\n                switch(argc){\n                case 1:\n                        driver();\n                        break;\n                case 2: {\n                        std::string arg = argv[1];\n                        if( arg == \"--hero\" ){\n                                render(Player_Hero, RenderOpt_Solve);\n                        } else if(arg == \"--villian\"){\n                                render(Player_Villian, RenderOpt_Solve);\n                        } else if(arg == \"--driver\"){\n                                driver();\n                        } else{\n                        }\n                        break;\n                }\n                default:\n                        std::cerr  << \"unknown args\\n\";\n                        return EXIT_FAILURE;\n                }\n        } catch(std::exception const& e){\n                std::cerr << e.what() << \"\\n\";\n                return EXIT_FAILURE;\n        }\n}\n\n", "meta": {"hexsha": "fc50ab7a6e7b10fe07e5d47eb4ac26d9230a620b", "size": 37947, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ttt.cpp", "max_stars_repo_name": "sweeterthancandy/ttt", "max_stars_repo_head_hexsha": "29efa3af712da8d8f06a396b2bc76ab175723d19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ttt.cpp", "max_issues_repo_name": "sweeterthancandy/ttt", "max_issues_repo_head_hexsha": "29efa3af712da8d8f06a396b2bc76ab175723d19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ttt.cpp", "max_forks_repo_name": "sweeterthancandy/ttt", "max_forks_repo_head_hexsha": "29efa3af712da8d8f06a396b2bc76ab175723d19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.431372549, "max_line_length": 131, "alphanum_fraction": 0.3688302106, "num_tokens": 7004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.44338636128150405}}
{"text": "// Copyright John Maddock 2008.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_DISTRIBUTIONS_DETAIL_MODE_HPP\n#define BOOST_MATH_DISTRIBUTIONS_DETAIL_MODE_HPP\n\n#include <boost/math/tools/minima.hpp> // function minimization for mode\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/distributions/fwd.hpp>\n\nnamespace boost{ namespace math{ namespace detail{\n\ntemplate <class Dist>\nstruct pdf_minimizer\n{\n   pdf_minimizer(const Dist& d)\n      : dist(d) {}\n\n   typename Dist::value_type operator()(const typename Dist::value_type& x)\n   {\n      return -pdf(dist, x);\n   }\nprivate:\n   Dist dist;\n};\n\ntemplate <class Dist>\ntypename Dist::value_type generic_find_mode(const Dist& dist, typename Dist::value_type guess, const char* function, typename Dist::value_type step = 0)\n{\n   BOOST_MATH_STD_USING\n   typedef typename Dist::value_type value_type;\n   typedef typename Dist::policy_type policy_type;\n   //\n   // Need to begin by bracketing the maxima of the PDF:\n   //\n   value_type maxval;\n   value_type upper_bound = guess;\n   value_type lower_bound;\n   value_type v = pdf(dist, guess);\n   if(v == 0)\n   {\n      //\n      // Oops we don't know how to handle this, or even in which\n      // direction we should move in, treat as an evaluation error:\n      //\n      policies::raise_evaluation_error(\n         function, \n         \"Could not locate a starting location for the search for the mode, original guess was %1%\", guess, policy_type());\n   }\n   do\n   {\n      maxval = v;\n      if(step != 0)\n         upper_bound += step;\n      else\n         upper_bound *= 2;\n      v = pdf(dist, upper_bound);\n   }while(maxval < v);\n\n   lower_bound = upper_bound;\n   do\n   {\n      maxval = v;\n      if(step != 0)\n         lower_bound -= step;\n      else\n         lower_bound /= 2;\n      v = pdf(dist, lower_bound);\n   }while(maxval < v);\n\n   boost::uintmax_t max_iter = policies::get_max_root_iterations<policy_type>();\n\n   value_type result = tools::brent_find_minima(\n      pdf_minimizer<Dist>(dist), \n      lower_bound, \n      upper_bound, \n      policies::digits<value_type, policy_type>(), \n      max_iter).first;\n   if(max_iter >= policies::get_max_root_iterations<policy_type>())\n   {\n      return policies::raise_evaluation_error<value_type>(\n         function, \n         \"Unable to locate solution in a reasonable time:\"\n         \" either there is no answer to the mode of the distribution\"\n         \" or the answer is infinite.  Current best guess is %1%\", result, policy_type());\n   }\n   return result;\n}\n//\n// As above,but confined to the interval [0,1]:\n//\ntemplate <class Dist>\ntypename Dist::value_type generic_find_mode_01(const Dist& dist, typename Dist::value_type guess, const char* function)\n{\n   BOOST_MATH_STD_USING\n   typedef typename Dist::value_type value_type;\n   typedef typename Dist::policy_type policy_type;\n   //\n   // Need to begin by bracketing the maxima of the PDF:\n   //\n   value_type maxval;\n   value_type upper_bound = guess;\n   value_type lower_bound;\n   value_type v = pdf(dist, guess);\n   do\n   {\n      maxval = v;\n      upper_bound = 1 - (1 - upper_bound) / 2;\n      if(upper_bound == 1)\n         return 1;\n      v = pdf(dist, upper_bound);\n   }while(maxval < v);\n\n   lower_bound = upper_bound;\n   do\n   {\n      maxval = v;\n      lower_bound /= 2;\n      if(lower_bound < tools::min_value<value_type>())\n         return 0;\n      v = pdf(dist, lower_bound);\n   }while(maxval < v);\n\n   boost::uintmax_t max_iter = policies::get_max_root_iterations<policy_type>();\n\n   value_type result = tools::brent_find_minima(\n      pdf_minimizer<Dist>(dist), \n      lower_bound, \n      upper_bound, \n      policies::digits<value_type, policy_type>(), \n      max_iter).first;\n   if(max_iter >= policies::get_max_root_iterations<policy_type>())\n   {\n      return policies::raise_evaluation_error<value_type>(\n         function, \n         \"Unable to locate solution in a reasonable time:\"\n         \" either there is no answer to the mode of the distribution\"\n         \" or the answer is infinite.  Current best guess is %1%\", result, policy_type());\n   }\n   return result;\n}\n\n}}} // namespaces\n\n#endif // BOOST_MATH_DISTRIBUTIONS_DETAIL_MODE_HPP\n", "meta": {"hexsha": "085dc691cdd7e5eb7073b0c65456a8a5ac0bb0f0", "size": 4342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/math/distributions/detail/generic_mode.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 159.0, "max_stars_repo_stars_event_min_datetime": "2017-03-24T21:07:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:44:40.000Z", "max_issues_repo_path": "boost/boost/math/distributions/detail/generic_mode.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1667.0, "max_issues_repo_issues_event_min_datetime": "2017-03-27T14:41:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:50:06.000Z", "max_forks_repo_path": "boost/boost/math/distributions/detail/generic_mode.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 95.0, "max_forks_repo_forks_event_min_datetime": "2017-03-24T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T17:30:22.000Z", "avg_line_length": 28.9466666667, "max_line_length": 152, "alphanum_fraction": 0.6653615845, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.44338636128150405}}
{"text": "/*\n   Boneh, Di Crescenzo, Ostrovsky & Persiano\n   Public Key Encryption with keyword Search\n\n   See http://eprint.iacr.org/2003/195.pdf\n   Section 3.1\n\n   (From reading the protocol to a working implementation - 10 minutes!)\n\n   Compile with modules as specified below\n\n   For MR_PAIRING_CP curve\n   cl /O2 /GX peks.cpp cp_pair.cpp zzn2.cpp big.cpp zzn.cpp ecn.cpp miracl.lib\n\n   For MR_PAIRING_MNT curve\n   cl /O2 /GX peks.cpp mnt_pair.cpp zzn6a.cpp ecn3.cpp zzn3.cpp zzn2.cpp big.cpp zzn.cpp ecn.cpp miracl.lib\n\t\n   For MR_PAIRING_BN curve\n   cl /O2 /GX peks.cpp bn_pair.cpp zzn12a.cpp ecn2.cpp zzn4.cpp zzn2.cpp big.cpp zzn.cpp ecn.cpp miracl.lib\n\n   For MR_PAIRING_KSS curve\n   cl /O2 /GX peks.cpp kss_pair.cpp zzn18.cpp zzn6.cpp ecn3.cpp zzn3.cpp big.cpp zzn.cpp ecn.cpp miracl.lib\n\n   For MR_PAIRING_BLS curve\n   cl /O2 /GX peks.cpp bls_pair.cpp zzn24.cpp zzn8.cpp zzn4.cpp zzn2.cpp ecn4.cpp big.cpp zzn.cpp ecn.cpp miracl.lib\n\n   Test program \n*/\n#include <cstring>\n#include \"big.h\"\n#include <ctime>\n#include <string>\n#include <set>\n#include <fstream>\n#include <iostream>\n#include <stdlib.h>\n#include <assert.h>\n#include \"zzn.h\"\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <sstream>\n#include \"params-peks.h\"\n#include <zmq.hpp>\n \nusing namespace std;\n\n//********* choose just one of these pairs **********\n//#define MR_PAIRING_CP      // AES-80 security   \n//#define AES_SECURITY 80\n\n//#define MR_PAIRING_MNT\t// AES-80 security\n//#define AES_SECURITY 80\n\n//#define MR_PAIRING_BN    // AES-128 or AES-192 security\n//#define AES_SECURITY 128\n//#define AES_SECURITY 192\n\n//#define MR_PAIRING_KSS    // AES-192 security\n//#define AES_SECURITY 192\n\n//#define MR_PAIRING_BLS    // AES-256 security\n//#define AES_SECURITY 256\n//*********************************************\n#include \"pairing_3.h\"\n#include \"ecn.h\"\n#include \"miracl.h\"\n\nPFC pfc(AES_SECURITY);  // initialise pairing-friendly curve\n\n\n\t\nvoid keyGen(string path,G1\t&g, Big &alpha, G1& h );\nvoid boneh_Peks(G1 g,G1 h, G1 &PA, Big &PB,string keyword);\nvoid boneh_Trapdoor(Big alpha,G2 &TW, string keyword);\nbool boneh_Test(G2 TW, G1 PA, Big PB);\n//==========================================================================================================\nstring to_string(int i)\n{\n    stringstream ss;\n    ss << i;\n    return ss.str();\n}\n\nconst char* const delimiter = \"`-=[]\\\\;\\',./~!@#$%^&*()+{}|:\\\"<>? \\n\\t\\v\\b\\r\\f\\a\"; \nbool is_word(std::string& s){\n\tbool flagd =true, flagc = false;  int count = 0;\n\tstd::string::iterator it = s.begin();\n    for (it = s.begin();it != s.end(); ++it)  {\n\t\tcount++;\n\t\tif (std::isalpha(*it)){}\n\t\telse{\n\t\t\tflagd = false; \t\n\t\t\t}\n\t\tif (count > 2)  flagc = true;\n\t}\n\t\n\t\n    return (flagd && flagc);\n}\nint extractWords_using_find_first_of(TYPE_KEYWORD_DICTIONARY &rKeywordsDictionary,\n\t\tTYPE_COUNTER *pKeywordNum,\n\t\tifstream &rFin){\n\n\tbool capture = false;\n\tstring line, word;\n\twhile(getline(rFin, line)) \n    {\n\t\tint counter = 0;\n\t\tsize_t prev = 0, pos;\n\t\tboost::trim(line);\n\t\twhile ((pos = line.find_first_of(delimiter, prev)) != std::string::npos)\n\t\t{\n\t\t\tif (pos > prev)\n            {\n\t\t\t\tword = line.substr(prev, pos-prev);\n\t\t\t\tboost::trim(word);\n                //convert the word to lower case\n                std::transform(word.begin(),word.end(),word.begin(),::tolower);\n\t\t\t\t//if (word == \"dfossum\")\n\t\t\t\tcapture=true;\n\t\t\t\tif (is_word(word) && capture &&   rKeywordsDictionary.size()<numOfKeywords){\n                rKeywordsDictionary.insert(word);\n\t\t\t\t*pKeywordNum = *pKeywordNum + 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprev = pos+1;\n\t\t}\n\t\tif (prev < line.length()){\n\t\t\tword = line.substr(prev, std::string::npos);\n\t\t\tboost::trim(word);\n\n            //convert the word to lower case\n            std::transform(word.begin(),word.end(),word.begin(),::tolower);\n\t\t\tif (word == \"dfossum\") capture=true;\n\t\t\tif (is_word(word)&& capture && rKeywordsDictionary.size()<numOfKeywords){\n\t\t\t\trKeywordsDictionary.insert(word);\n\t\t\t\t*pKeywordNum = *pKeywordNum + 1;\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn 0;\n}\nint extractKeywords(TYPE_KEYWORD_DICTIONARY &rKeywordsDictionary,\n\t\tstring file_name ,string path) \n{ \n\tTYPE_COUNTER keyword_num = 0;\n\tstring fname_with_path;\n\n\t// create a file-reading object\n\tifstream fin;\n\n\tfname_with_path.append(path);\n\tfname_with_path.append(file_name);\n\t//fname_with_path.append(\".txt\");\n\n\t// open a file\n\tfin.open(fname_with_path.c_str(),std::fstream::in);\n\tif (!fin.good()){\n\t\tcout << \"No such file exist\"<<endl; // exit if file not found\n\t}\n\t// Extract keywords from a file\n\textractWords_using_find_first_of(rKeywordsDictionary, &keyword_num, fin);\n\n\tfin.close();\n\n\treturn 0;\n}\n// Function gets the file info and a set of keywords and writes them on the file for the future use. \nvoid writeKeywords(TYPE_KEYWORD_DICTIONARY keywordSet, string file_name, string path){\n\t\n\tstring fname_with_path;\n\tset<string>::iterator it;\n\n\tfname_with_path.append(path);\n\tfname_with_path.append(file_name);\n\tfname_with_path.append(\"kw\");\n\t// Opening file to write the keywords on it. \n\tofstream myfile;\n\tmyfile.open (fname_with_path.c_str(), ios::out | ios::binary); \n\tfor (it=keywordSet.begin(); it!=keywordSet.end(); ++it){\n\t\tmyfile << ' ' << *it;\n\t}\n\tmyfile.close();\n\t\n\t\n}\n// Function to read keywords from file\nvoid extractKeywordFile(string *keywordExtracted, int &keywordCounter, string file_name, string path)\n{\n    ifstream ifile;\n\tstring fname_with_path;\n\tfname_with_path.append(path);\n\tfname_with_path.append(file_name);\n\tfname_with_path.append(\"kw\");\n\t// Opening file to read the keywords from it. \n    ifile.open(fname_with_path.c_str());\n    if (!ifile.is_open()) \n\t\t{cout << \"No such file exist\"<<endl;}\n\tstring word;\n\tkeywordCounter = 0; \n    while (ifile >> word)\n    {\n\t\tkeywordExtracted[keywordCounter] = word;\n\t\tkeywordCounter++;\n     }\n\tfor (int key = 0;key<numOfKeywords;key++)\n\t\tcout << file_name << \"   \"<< keywordExtracted[key]<<endl;\n\tifile.close();\n}\n\n// Stores the PEKS obtained from the function below in the file. \n\nvoid writePEKStoFile(string file_name, string path, G1  PA, Big PB){\n\t\n\tchar testing[200]; \n\tcout << \"PA = \" << PA.g << endl;\n\n\tBig x = 1;\n\tBig y = 1;\n\tPA.g.getxy(x,y);\n\n\n\tstring fname_with_path;\n\t//recreate the file name\n\tfname_with_path.append(path);\n\tfname_with_path.append(file_name);\n\tfname_with_path.append(\"sc\");\n\t\n\tofstream ofile;\n\tofile.open (fname_with_path.c_str(), ios_base::app | ios::binary); \n\tofile<<x ;\n\ttesting << x;\n\tofile<<endl;\n\tofile << y << endl;\n\t\n\tofile << PB;\n\tofile<<endl;\n\tofile.close();\n}\n\t\n//Function to encrypt keywords and store them in file using writePEKStoFile function\n\nvoid KeywordstoPEKS(G1  PA, Big PB,string file_name, string path, G1 g, G1 h, string keywordExtracted[numOfKeywords], int  keywordCounter)\n\t{\n\tstring keyword;\n\tfor (int i = 0; i < numOfKeywords; i++){\n\t\t\tkeyword = keywordExtracted[i];\n\t\t\tboneh_Peks(g, h, PA, PB, keyword);\n\t\t//\tFinished Boneh Peks, writing PEKS to file\";\n\t\t\twritePEKStoFile(file_name,path,PA, PB);\n\t\t\n\t}\n\n\n}\n\n//void boneh_Trapdoor(Big alpha,G2 &TW, string keyword)\nvoid myTrapdoorGenerator(Big alpha,G2 &TW, string& keyword){\n\t\n\tstring word;\n\tcout << endl<<\"Please keyin the keyword you would like to be searched: \";\n\tcin >> keyword;\n\tboneh_Trapdoor(alpha, TW, keyword);\n\n\n}\n\nvoid findFileByKeywords(TYPE_KEYWORD_DICTIONARY & listOfFiles, string file_name, string path, G2 TW){\n\tcout << \"We are in Find FILE BY KEYWORD now: \"<<endl<<endl;\n\tint rep;\n\tbool flagvalid = false; \n\n\tint counter = 0;\n\n    string line1 = \"\";\n    string line2 = \"\";\t\n\tstring temp1,temp2=\"\",fileNameforList=\"\", fname_with_path;\n\tfstream ifile;\n\n\t\n\tfor (int filecount = 1; filecount < numOfFiles; filecount++)\n\t{\t    \n\t\tstring line1 = \"\";string line0 = \"\";\n\t\tstring line2 = \"\";\t\n\t\tstring line3 = \"\";\n\t\t \n\t\t\n\t\tfstream ifile;\n\t\tfname_with_path = \"\";\n\t\tfname_with_path.append(path);\n\t\tfile_name = \"\";\n\t\tfile_name.append(\"/\");\n\t\ttemp1 = std::to_string(filecount);\n\n\t\tfile_name.append(temp1);\n\t\tfileNameforList.append(file_name);\n\t\t//fileNameforList.append(\".\");\n\t\tfile_name.append(\"sc\");\n\t\tfname_with_path.append(file_name);\n\n\t\tifile.open(fname_with_path.c_str());\n\t\tif (!ifile.is_open()){cout << \"The file \"<<fname_with_path<< \"is NOT fine \\n\"<<endl;}\n\t\tstring word =\"\";\n\t\tstring target = \"\";\n\t\tint i = 0;\n\t\t\n\t\twhile (i < numOfKeywords){\n\n\t\t\tepoint *temp;\n\n\t\t\tBig x = 1;\n\t\t\tBig y = 1;\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\t\tBig  PB =1; G1 PA;\n\n\t\t\tifile>>x;\n\t\t\tifile>>y;\n\t\t\t\n\t\t\tifile>>PB;\n\t\t\t\n\t\t\tECn point;\n\t\t\tbool flag = point.set(x,y);\n\t\t\tif(flag == true)\n\t\t\t{\n\t\t\t\tcout<<\"Good!\"<<endl;\n\t\t\t}\n\t\t\t\n\t\t\tPA.g = point;\n\n\n\t\t\ti++;\n\n\t\t\tif (boneh_Test( TW, PA, PB)){\n\t\t\t\tlistOfFiles.insert(file_name);\n\t\t\t}\n\n\t\t}\n\t\t\t\n\n\n\t\t\n\t}\n\tifile.close();\n\n}\n\n\n\nvoid writekeystoFile( string path,const G1 g, const Big alpha, const G1 h){\n\t\n\tcout << \"g = \" << g.g << endl;\n\tcout << \"h = \" << h.g << endl;\n\tBig x = 1;\n\tBig y = 1;\n\tBig xx =1;\n\tBig yy =1;\n\tg.g.getxy(x,y);\n\th.g.getxy(xx,yy);\n\n\tstring fname_with_path;\n\t//recreate the file name\n\tfname_with_path.append(path);\n\tfname_with_path.append(\"/keyfile\");\n\tcout << fname_with_path<<endl;\n\tofstream ofile;\n\tofile.open (fname_with_path.c_str(),  ios::binary); \n\tofile << x ;\n\t\n\n\t//cout << \"/n/n/n/\"<< \"Hi This is x -----> \"<< testing<<endl;\n\tofile<<endl;\n\tofile << y << endl;\n\tofile<< alpha<<endl;\n\tofile << xx<<endl;\n\tofile << yy<<endl;\n\tofile.close();\n}\nvoid readKeyFromFile ( string path, G1& g, Big& alpha, G1& h){\n\t\n\t\tstring fname_with_path_key;\n\t\tfstream ifile;\n\t\tfname_with_path_key = \"\";\n\t\tfname_with_path_key.append(path);\n\n\t\tfname_with_path_key.append(\"/keyfile\");\n\t\tifile.open(fname_with_path_key.c_str());\n\t\t\n\tepoint *temp;\n\n\tBig x = 1;\n\tBig y = 1;\n\tBig xx = 1;\n\tBig yy = 1;\n\n\tifile>>x;\n\tifile>>y;\n\t\n\tifile>>alpha;\n\tifile >> xx;\n\tifile>>yy;\n\tECn point1;\n\tbool flag = point1.set(x,y);\n\tif(flag == false)\n\t{\n\t\tcout<<\"Error in loading keys!\"<<endl;\n\t}\n\t\n\tg.g = point1;\n\t\n\tECn point2;\n\tbool flag1 = point2.set(xx,yy);\n\tif(flag1 == false)\n\t{\n\t\tcout<<\"Error in loading keys1!\"<<endl;\n\t}\n\th.g = point2;\n\t\n\t\n\t\n\t}\n//= ===== write trapdoor to file \n\n\nvoid writeTrapdoorFile(string fname_with_path,  G2 TW){\n\t\n\tZZn3 x;\nchar a[2] = {'0','1'};\nZZn mya(a);\n\tZZn3 y;\n\tZZn atx;\n\tZZn btx;\n\tZZn ctx;\n\tZZn aty;\n\tZZn bty;\n\tZZn cty;\n\tECn3 mypoint; \n\tmypoint = TW.g;\n\tcout << \"The value of mypoint is : \"<<mypoint<<endl;\n\tcout << \"The value of Trapdoor is : \"<<TW.g<<endl;\n\tmypoint.get(x,y);\n\tcout << \"The value of x is : \"<<x<<endl;\n\tcout << \"The value of y is : \"<<y<<endl;\n\tx.get(atx,btx,ctx);\n\tcout << \"The value of a is : \"<<atx<<endl;\n\tcout << \"The value of b is : \"<<btx<<endl;\n\tcout << \"The value of c is : \"<<ctx\t<<endl;\n\tx.get(atx,btx,ctx);\n\tcout << \"The value of aaaa is : \"<<a\t<<endl;\n\ty.get(aty,bty,cty);\n\n\t//string fname_with_path;\n\t//recreate the file name\n\n\tfname_with_path.append(\"trapdoor\");\n\t\n\tofstream ofile;\n\tofile.open (fname_with_path.c_str(),  ios::binary); \n\tofile << atx <<endl<<btx <<endl<<ctx<<endl <<aty<<endl<<bty<<endl<<cty<<endl ;\n\n\n\tofile.close();\n}\n\n\nvoid sendTrapdoorToServer(string file_name, string path){\n    zmq::context_t context(1);\n\tzmq::socket_t socket(context,ZMQ_REQ);\n\tprintf(\"   Connecting to server...\");\n\t//socket.connect (\"tcp://localhost:5559\");\n\tsocket.connect (\"tcp://52.26.80.225:5559\");\n\tprintf(\"OK!\\n\");\n\tstring line1 = \"\";\n\tstring fname_with_path;\n\tsize_t sizeLine1 = 0;\n\tauto start = time_now;\n    auto end = time_now;\n\tfloat sum = 0.0;\n\t\n\tfstream ifile;\n\tfname_with_path = \"\";\n\tfname_with_path.append(path);\n\t//file_name = \"\";\n\t//file_name.append(\"/\");\n\tfname_with_path.append(file_name);\n\tsize_t size1;\n\tifile.open(fname_with_path.c_str());\n\tif (!ifile.is_open()){cout << \"The file \"<<fname_with_path<< \"is NOT fine \\n\"<<endl;}\n\t\twhile(ifile >> line1){\n\t\t\tcout << \"The lines in sendTrapdoor \"<<line1<<endl;\n\t\t\tsizeLine1 = (size_t)line1.length();\n\t\t\tzmq::message_t request_line1(sizeLine1);\n\t\t\tmemcpy (request_line1.data (), line1.c_str(), sizeLine1);\n\t\t\t\n\t\t\tstart = time_now;\n\t\t\tsocket.send (request_line1);\n\t\t\tzmq::message_t reply;\n\t\t\tsocket.recv (&reply);\n\t\t\tend = time_now;\n\t\t\tsum += (float)(std::chrono::duration_cast<std::chrono::microseconds>(end-start).count());\n\t\t}\n\n\tcout<<\t\"Sending Trapdoor takes   \"<<sum<<\" microseconds\"<<endl;\n\t\t\n\t\t\t\n\tifile.close();\n\tsocket.close();\n\n\n\t\t\n\t}\n\n\n\n\n\n\n\n\n\n\n\n\n//=== Send data to server\n\n\nvoid sendPeksToServer(string file_name, string serverPath){\n    zmq::context_t context(1);\n\tzmq::socket_t socket(context,ZMQ_REQ);\n\tprintf(\"   Connecting to server...\");\n\t//socket.connect (\"tcp://localhost:5560\");\n\tsocket.connect (\"tcp://52.26.80.225:5560\");\n\tprintf(\"OK!\\n\");\n\tstring line1 = \"\";\n    string line2 = \"\"; string line3 = \"\";\t\t\n\tstring fname_with_path;\n\tfstream ifile;\n\tsize_t sizeLine1 = 0;\n\tsize_t sizeLine2 = 0;\n\tsize_t sizeLine3 = 0;\n\tauto start = time_now;\n    auto end = time_now;\n\tfloat sum = 0.0;\n\tstring line22 = \"Hello there how are you0\";\n\tfor (int filecount = 1; filecount < numOfFiles; filecount++)\n\t{\t    \n\t\t\n\t\tstring temp1 = \"\";\n\t\tfstream ifile;\n\t\tfname_with_path = \"\";\n\t\tfname_with_path.append(serverPath);\n\t\tfile_name = \"\";\n\t\tfile_name.append(\"/\");\n\t\ttemp1 = std::to_string(filecount);\n\t\tfile_name.append(temp1);\n\t\tfile_name.append(\"sc\");\n\t\tfname_with_path.append(file_name);\n\t\tsize_t size1, size2,size3;\n\t\tifile.open(fname_with_path.c_str());\n\t\tif (!ifile.is_open()){cout << \"The file \"<<fname_with_path<< \"is NOT fine \\n\"<<endl;}\n\t\tint i = 0;\n\t\twhile (i < numOfKeywords){\n\t\t\t\n\t\t\tline1 = \"\";line2 = \"\";line3 = \"\";\n\t\t\tifile>>line1;\n\t\t\tifile>>line2;\n\t\t\tifile>>line3;\n\t\t\tsizeLine1 = (size_t)line1.length();\n\t\t\tzmq::message_t request_line1(sizeLine1);\n\t\t\tmemcpy (request_line1.data (), line1.c_str(), sizeLine1);\n\t\t\t\n\t\t\tsizeLine2 = (size_t)line2.length();\n\t\t\tzmq::message_t request_line2(sizeLine2);\n\t\t\tmemcpy (request_line2.data (), line2.c_str(), sizeLine2);\n\t\t\t\n\t\t\tsizeLine3 = (size_t)line3.length();\n\t\t\tzmq::message_t request_line3(sizeLine3);\n\t\t\tmemcpy (request_line3.data (), line3.c_str(), sizeLine3);\n\t\t\tstart = time_now;\n\t\t\tsocket.send (request_line1);\n\t\t\tzmq::message_t reply;\n\t\t\tsocket.recv (&reply);\n\t     \tsocket.send (request_line2);\n\t\t\tsocket.recv (&reply);\n\t\t\tsocket.send (request_line3);\n\t\t\tsocket.recv (&reply);\n\t\t\tend = time_now;\n\t\t\tsum += (float)(std::chrono::duration_cast<std::chrono::microseconds>(end-start).count());\n\t\t\ti++;\n\t\t}\n\n\t}\n\t\n\tcout<<\t\"Sending PEKS, each file takes   \"<<sum/(numOfFiles*numOfKeywords)<<\" microseconds on average\"<<endl;\n\t\n\tcout << \"All files have been received and stored in \"<< serverPath << \"folder \"<< endl;\n\tifile.close();\n\tsocket.close();\n\n\n\t\t\n\t}\n\t\n\t\n\t\n// ================== SERVER SIDE\nvoid writePEKStoFileServer(string fname_with_path, string fname,  string x, string y, string pb){\n\t\n\t \n\t\n\n\t//string fname_with_path;\n\t//recreate the file name\n\n\tfname_with_path.append(fname);\n\t\n\tofstream ofile;\n\tofile.open (fname_with_path.c_str(), ios_base::app | ios::binary); \n\tofile << x ;\n\n\tofile<<endl;\n\tofile << y << endl;\n\t\n\tofile << pb;\n\tofile<<endl;\n\tofile.close();\n}\n\n\n\n\nvoid writeTrapdoortoFileServer(string fname_with_path,  string x){\n\t\n\t \n\t\n\n\t//string fname_with_path;\n\t//recreate the file name\n\n\tfname_with_path.append(\"trapdoor\");\n\t\n\tofstream ofile;\n\tofile.open (fname_with_path.c_str(), ios_base::app | ios::binary); \n\tofile << x ;\n\n\tofile<<endl;\n\n\tofile.close();\n}\n\nvoid receivingPeksServer(string serverPath){\n\t\n\t\n\tzmq::context_t context (1);\n    zmq::socket_t socket (context, ZMQ_REP);\n    socket.bind (\"tcp://*:5560\");\n\tint counterKeywords; \n\n\tfor (int filecount = 1; filecount < numOfFiles; filecount++)\n\t{\t    \n\t\t\n\t\tstring temp1 = \"\";\n\t\tofstream ofile;\n\t\tstring fname_with_path1 = \"\";\n\t\tfname_with_path1.append(serverPath);\n\t\tstring file_name = \"\";\n\t\tfile_name.append(\"/\");\n\t\ttemp1 = std::to_string(filecount);\n\t\tfile_name.append(temp1);\n\t\tfile_name.append(\"sc\");\n\t\tfname_with_path1.append(file_name);\n\t\tsize_t size1, size2,size3;\n\t\tofile.open (fname_with_path1.c_str(),  ios::binary); \n\n\n\tcounterKeywords = 0;\n    while (counterKeywords < numOfKeywords) {\n\t\t\n        zmq::message_t request1;\n        socket.recv (&request1);\n        string rpl1 = string(static_cast<char*>(request1.data()), request1.size());\n        cout <<  rpl1<< endl;\n\t\t\n\t\tzmq::message_t reply1 (8);\n        memcpy (reply1.data (), \"World\", 8);\n        socket.send (reply1);\n\t\t\n\t//sleep(1);\n\t\tzmq::message_t request2;\n\t\tsocket.recv (&request2);\n        string rpl2 = string(static_cast<char*>(request2.data()), request2.size());\n        cout <<  rpl2<< endl;\t\n\n        zmq::message_t reply2 (8);\n        memcpy (reply2.data (), \"World\", 8);\n        socket.send (reply2);\t\n\t\t\n\t\t\n\t//sleep(1);\t\n\t//sleep(1);\t\n\t\tzmq::message_t request3;\n\t\tsocket.recv (&request3);\n        string rpl3 = string(static_cast<char*>(request3.data()), request3.size());\n        cout <<  rpl3<< endl;\n\t\t\n\t\tzmq::message_t reply3 (8);\n        memcpy (reply3.data (), \"World\", 8);\n        socket.send (reply3);\n\t\twritePEKStoFileServer(serverPath ,file_name, rpl1, rpl2,rpl3);\n\n\t\tcounterKeywords++; \n\n        //  Do some 'work'\n\n        //  Send reply back to client\n\n    }\n}\n\n\t\n\tcout << \"All files have been received and stored in \"<< serverPath << \"folder \"<< endl;\n\tsocket.close();\n\t\n}\n\n\n\n\n\n\nvoid receivingTrapdoorServer(string serverPath){\n\t\n\t\n\tzmq::context_t context (1);\n    zmq::socket_t socket (context, ZMQ_REP);\n    socket.bind (\"tcp://*:5559\");\n\n\t\tofstream ofile;\n\t\tstring fname_with_path1 = \"\";\n\t\tfname_with_path1.append(serverPath);\n\t\tstring file_name = \"trapdoor\";\n\t\tfname_with_path1.append(file_name);\n\t\tsize_t size1;\n\t\tofile.open (fname_with_path1.c_str(),  ios::binary); \n\n\n\tint numOfLinesTrapdoor = 0;\n    while (numOfLinesTrapdoor < 6) {\n\t\t\n        zmq::message_t request1;\n        socket.recv (&request1);\n        string rpl1 = string(static_cast<char*>(request1.data()), request1.size());\n        cout <<  rpl1<< endl;\n\t\t\n\t\tzmq::message_t reply1 (8);\n        memcpy (reply1.data (), \"World\", 8);\n        socket.send (reply1);\n\t\t\n\t\twriteTrapdoortoFileServer(serverPath, rpl1);\n\n\t\tnumOfLinesTrapdoor++; \n\n\n\n    }\n\n\n\t\n\tcout << \"All files have been received and stored in \"<< serverPath << \"folder \"<< endl;\n\tsocket.close();\n\t\n}\n\n\n\n\nvoid findFileByKeywordsServer(TYPE_KEYWORD_DICTIONARY & listOfFiles, string file_name, string path, string serverPath){\n\t\n\t\n\tG2 TW;\n\tstring tdfname = \"\";\n\ttdfname.append(serverPath);\n\ttdfname.append(\"trapdoor\");\n\tZZn3 x; ZZn3 y;\n\tECn3 point;\n\tBig aux1 = 1;\tBig aux2 = 1;\n\tBig aux3 = 1;\tBig aux4 = 1;\n\tBig aux5 = 1;\tBig aux6 = 1;\n\tifstream fileTrapdoor;\n\tfileTrapdoor.open(tdfname.c_str());\n\tfileTrapdoor >> aux1;fileTrapdoor >> aux2;\n\tfileTrapdoor >> aux3;fileTrapdoor >> aux4;\n\tfileTrapdoor >> aux5;fileTrapdoor >> aux6;\n\tZZn atx(aux1);\n\tZZn btx(aux2);\n\tZZn ctx(aux3);\n\tZZn aty(aux4);\n\tZZn bty(aux5);\n\tZZn cty(aux6);\n\tx.set(atx,btx,ctx);\n\ty.set(aty,bty,cty);\n\tpoint.set(x,y);\n\tTW.g = point;\n\tcout << \"We are in THE TESTING FUNC and the value is \"<<TW.g<<endl;\n\tsleep(3);\n\tfileTrapdoor.close();\n\t\n\t\n\tint rep;\n\tbool flagvalid = false; \n\n\tint counter = 0;\n\n    string line1 = \"\";\n    string line2 = \"\";\t\n\tstring temp1,temp2=\"\",fileNameforList=\"\", fname_with_path;\n\tfstream ifile;\n\t\t\n\t\n\tfor (int filecount = 1; filecount < numOfFiles; filecount++)\n\t{\t    \n\t\tstring line1 = \"\";string line0 = \"\";\n\t\tstring line2 = \"\";\t\n\t\tstring line3 = \"\";\n\t\t \n\t\t\n\t\tfstream ifile;\n\t\tfname_with_path = \"\";\n\t\tfname_with_path.append(path);\n\t\tfile_name = \"\";\n\t\tfile_name.append(\"/\");\n\t\ttemp1 = std::to_string(filecount);\n\n\t\tfile_name.append(temp1);\n\t\tfileNameforList.append(file_name);\n\t\t//fileNameforList.append(\".\");\n\t\tfile_name.append(\"sc\");\n\t\tfname_with_path.append(file_name);\n\n\t\tifile.open(fname_with_path.c_str());\n\t\tif (!ifile.is_open()){cout << \"The file \"<<fname_with_path<< \"is NOT fine \\n\"<<endl;}\n\t\tstring word =\"\";\n\t\tstring target = \"\";\n\t\tint i = 0;\n\t\t\n\t\twhile (i < numOfKeywords){\n\n\t\t\tepoint *temp;\n\n\t\t\tBig x = 1;\n\t\t\tBig y = 1;\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\t\tBig  PB =1; G1 PA;\n\n\t\t\tifile>>x;\n\t\t\tifile>>y;\n\t\t\t\n\t\t\tifile>>PB;\n\t\t\t\n\t\t\tECn point;\n\t\t\tbool flag = point.set(x,y);\n\t\t\tif(flag == true)\n\t\t\t{\n\t\t\t\tcout<<\"Good!\"<<endl;\n\t\t\t}\n\t\t\t\n\t\t\tPA.g = point;\n\n\n\t\t\ti++;\n\n\t\t\tif (boneh_Test(TW, PA, PB)){\n\t\t\t\tlistOfFiles.insert(file_name);\n\t\t\t}\n\n\t\t}\n\t\t\t\n\n\n\t\t\n\t}\n\tifile.close();\n\n}\n\n\n//=========================================================================================================\n\nvoid mainMenu(){\n\tcout << \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n\tcout << \"Select one of the following: \\n\";\n\tcout << \"(1) Sender\\n\";\n\tcout << \"(2) Receiver\\n\";\n\tcout << \"(3) Server\\n\";\n\tcout << \"(4) Exit\\n\";\n\n\tcout << \"Choice: \";\n\n}\nvoid senderMenu(string path, const bool flagEnc, int numOfFiles){\n\t//int choiceSender = 0;\n\tcout << \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n\tcout << \"The default path for the email files is: \\n\";\n\tcout << path<<endl;\n\tcout << \"The  number of email files is: \";\n\tcout << numOfFiles <<endl;\n\tcout << \"Select one of the following: \\n\";\n\tcout << \"(1) Change the default path\\n\";\n\tcout << \"(2) Change the default number of files\\n\";\n\tcout << \"(3) Extract and encrypt keywords for each file \"; if (flagEnc){ cout << \"(Done)\\n\"; } else cout << \"\\n\"; \n\tcout << \"(4) Send encrypted files to the server\\n\";\n\tcout << \"(5) Return to the main menu\\n\";\n\tcout << \"Choice: \";\n}\n\nvoid receiverMenu(const bool flagTrapdoor, string path){\n\tstring filename = \"/keyfile\";\n\tstring filename_with_path = \"\";\n\tfilename_with_path.append(path);\n\tfilename_with_path.append(filename);\n\tcout << filename_with_path<<endl;\n\tifstream keyfile (filename_with_path.c_str()); \n\t\n\tcout << \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n\tcout << \"Select one of the following: \\n\"; \n\tcout << \"(1) Generate keys \";  if (keyfile) { cout<< \"(Done!) \\n\";} else cout <<\"\\n\";\n\tcout << \"(2) Generate trapdoor \"; if (flagTrapdoor){ cout << \"(Done!)\\n\"; } else cout << \"\\n\"; \n\tcout << \"(3) Send Trapdoor to server (trapdoor should have been genrated first.)\\n\";\n\tcout << \"(4) Find files by keyword (trapdoor should have been genrated first.)\\n\";\n\tcout << \"(5) Return to the main menu\\n\";\n\tcout << \"Choice: \";\n}\n\nvoid serverMenu(){\n\tcout << \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n\tcout << \"Select one of the following: \\n\";\n\tcout << \"(1) Receive Trapdoor\\n\";\n\tcout << \"(2) Receive PEKS\\n\";\n\tcout << \"(3) Return to the main menu\\n\";\n\n\tcout << \"Choice: \";\n\n}\n\t\n\n\n\nint main()\n{   \n\t\n\tbool flagEnc = false; bool flagTrapdoor = false;\n\ttime_t seed;\n\ttime(&seed);\n    irand((long)seed);\n    clock_t t1, t2;  \n\tfloat diff;\n\tG1 g,h,PA,PA1;\n\tBig alpha,r,PB;\n\tGT t;\n\tG2 HW,TW;\n\tTYPE_KEYWORD_DICTIONARY listOfFiles;\n\tstring keyword;\n\tconst unsigned int nb_trdb = 100;\n    const unsigned int nb_crypb = 100;\n\tunsigned int i;\n\tstring path = \"/home/bob/Desktop/80BonehPeks/80BonehPeks/textfiles\";\n\tstring file_name; \n\tint keywordCounter;\n\tint choiceMain, choiceSender,choiceReceiver,serverChoice;\n\tauto start = time_now;\n    auto end = time_now;\n\tfloat sum = 0.0;\n// This function is run by Alice, the reciever,  to generate pk and sk. \n\n\tlabelMain: mainMenu( );\n\tstring fname_with_path_key;\n\tfstream ifiles;\n\tfname_with_path_key = \"\";\n\tfname_with_path_key.append(path);\n\n\tfname_with_path_key.append(\"/keyfile\");\n\tifiles.open(fname_with_path_key.c_str());\n\tif (ifiles.is_open()){ \n\treadKeyFromFile (path,g,alpha,h);\n\t}\n\n\tcin >> choiceMain;\n\tcout << \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n\nif (choiceMain == 1){\n\tlabelSenderMenu:\n\tsenderMenu( path,   flagEnc, numOfFiles);\n\tcin >> choiceSender;\n\tif (choiceSender == 1){\n\t\tcout << \"Please keyin the new path: \";\n\t\tcin >> path;\n\t\tgoto labelSenderMenu;\n\t}\n\telse if (choiceSender == 2){\n\t\tcout << \"Please keyin the number of files: \";\n\t\tcin >> numOfFiles;\n\t\tgoto labelSenderMenu;\n\t}\n\telse if (choiceSender == 3){\n\t\t\n\t\t\n\t\tfor (int j = 1; j < numOfFiles; j++){\n\t\n\t\t\tstring keywordExtracted[25];\n\t\t\tstring temp;\n\t\t\tint rep[numOfKeywords] = {0};\n\t\t\tTYPE_KEYWORD_DICTIONARY myset;\n\t\t\tfile_name = \"/\";\n\t\t\ttemp = std::to_string(j);\n\t\t\tfile_name.append(temp);\n\t\t//\tfile_name.append(\".\");\n\t\t\textractKeywords(myset, file_name, path);\n\t\t\twriteKeywords(myset, file_name, path);\n\t\t\textractKeywordFile(keywordExtracted, keywordCounter, file_name,path);\n\t\t\tstart = time_now;\n\t\t\tKeywordstoPEKS(PA, PB,file_name, path,g,h, keywordExtracted, keywordCounter);\n\t\t\tend = time_now;\n\t\t\tsum += (float)(std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count());\n\t\t\tcout << \"Keywords have been successfully extracted and stored in .kw files. \\n\";\n\t\t\tcout << \"Keywords have been encrypted for each file and stored in .sc files. \\n\";\tcout << \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n\t\t\n\t\t}\n\t\tcout<<\"Generate PEKS, each file takes   \"<<sum/numOfFiles<<\" ms on average\"<<endl;\n\t\tflagEnc = true;\n\n\t}\n\telse if (choiceSender == 4){\n\t\tsendPeksToServer(file_name,path);\n\t\tgoto labelSenderMenu;\n\t}\n\t\t\n\t\n\telse if (choiceSender == 5){ goto labelMain;}\n\tsleep(1);\n\tgoto labelSenderMenu;\n\t\n\t\n\t\n\t\n\t\n\t\n}\n\t\nif (choiceMain == 2){\n\tlabelReceiverMenu: \n\treceiverMenu(flagTrapdoor,path);\n\tcin >> choiceReceiver;\n\tif (choiceReceiver == 1 ){\n\t\tkeyGen(path, g, alpha,h);\n\t\tcout << \"Keys have been succefully generated. \\n\";\tcout << \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n\t\tsleep (1);\n\t\tgoto labelReceiverMenu;\n\t}\n\t\n\tif (choiceReceiver == 2 ){\n\t\tflagTrapdoor = true;\n\t\tmyTrapdoorGenerator( alpha,TW, keyword);\n\t\tcout << \"Trapdoor has been succefully generated. \\n\";\tcout << \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n\t\tsleep (1);\n\t\tgoto labelReceiverMenu;\n\t}\n\n\telse if (choiceReceiver == 3){ sendTrapdoorToServer(\"trapdoor\", \"/home/bob/Desktop/80BonehPeks/80BonehPeks/textfiles/server/\");  goto labelReceiverMenu;}\n\t\n\t\n\t\telse if (choiceReceiver == 4 ){\n\t\t//findFileByKeywords(listOfFiles,  file_name,  path,  TW);\n\t\tstart = time_now;\n\t\tfindFileByKeywordsServer( listOfFiles,  file_name,  \"/home/bob/Desktop/80BonehPeks/80BonehPeks/textfiles/server\", \"/home/bob/Desktop/80BonehPeks/80BonehPeks/textfiles/server2/\");\n\t\tend = time_now;\n\t\n\t\tcout<<\"Search time    \"<<std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count()/numOfFiles<<\" ms\"<<endl;\n\t\tfor (set<string>::iterator it = listOfFiles.begin(); it != listOfFiles.end(); ++it) {\n\t\t\tcout <<\"The file name is\" << *it <<endl<<endl;\n\t\t}\n\t\tif (listOfFiles.size() == 0) cout << \"No email was found for the keyword: \"<< keyword << \"\\n\";\n\t\t\tcout << \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n\t\t\tsleep(1);\n\t\t\t goto labelMain;\n\t}\n\t\n\t\n\telse if (choiceReceiver == 5){ goto labelMain;}\n\t\n}\n\nif (choiceMain == 3){ \n\tlabelServerMenu:\n\tserverMenu();\n\tcin >> serverChoice;\n\n\tif (serverChoice == 1){\n\t\treceivingTrapdoorServer(\"/home/bob/Desktop/80BonehPeks/80BonehPeks/textfiles/server2/\"); goto labelServerMenu;\n\t}\n\telse if (serverChoice == 2 ){\n\treceivingPeksServer(\"/home/bob/Desktop/80BonehPeks/80BonehPeks/textfiles/server\"); goto labelServerMenu;\n\t}\n\telse if (serverChoice == 3) {goto labelMain;}\n}\n\nif (choiceMain == 4){exit(1);}\n\n\t\t\t\t\n\t\n\n    return 0;\n}\n\nvoid keyGen(string path,G1& g, Big& alpha, G1& h) {\n\tauto start = time_now;\n    auto end = time_now;\n\tstart = time_now;\n\tpfc.random(g);\t\n\tpfc.precomp_for_mult(g);  // precompute on fixed g\n\tpfc.random(alpha);\t\t  // private key\n\th=pfc.mult(g,alpha);      // public key\n\tpfc.precomp_for_mult(h);\n\tend = time_now;\n\t\n\tcout<<\"Key Generation took    \"<<std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count()<<\" ms\"<<endl;\n\twritekeystoFile(path,g,alpha,h);\n}\n\nvoid boneh_Peks(G1 g,G1 h, G1 &PA,Big &PB, string keyword)\n{\n\tBig r;\n\tGT t;\n\tG2 HW;\n\tpfc.random(r);\n\tpfc.hash_and_map(HW,(char *)keyword.c_str());\n\tt=pfc.pairing(HW,pfc.mult(h,r));\n\tPA=pfc.mult(g,r);\n\tPB=pfc.hash_to_aes_key(t);    // [PA,PB] added to ciphertext\n}\n\nvoid boneh_Trapdoor(Big alpha,G2 &TW, string keyword)\n{\t\n\tauto start = time_now;\n    auto end = time_now;\n\tstart = time_now;\n\tG2 HW;\n\tpfc.hash_and_map(HW,(char *)keyword.c_str()); // key word we are looking for\n\tTW=pfc.mult(HW,alpha);\n\tpfc.precomp_for_pairing(TW);\n\t\n\tend = time_now;\n\t\n\tcout<<\"Trapdoor Generation took    \"<<std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count()<<\" ms\"<<endl;\n\t\n\tcout << \"This is what you want in file  \"<< TW.g<<endl;\n\twriteTrapdoorFile(\"/home/bob/Desktop/80BonehPeks/80BonehPeks/textfiles/server/\",TW);\n}\nbool boneh_Test(G2 TW, G1 PA, Big PB)\n{\n\tif (pfc.hash_to_aes_key(pfc.pairing(TW,PA))==PB){\n\t\tcout << \"yes it does work\" << endl;\n\t\treturn true;\n\t}\n\t\n\telse{\n\t\tcout << \"It did not work\"<<endl;\n\t\treturn false;\n\t}\n\t\n}\n", "meta": {"hexsha": "0bc177fc6366b38b36102d2a019a56e7336714fc", "size": 27983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Boneh-PEKS/peks.cpp", "max_stars_repo_name": "Rbehnia/Full_PEKS", "max_stars_repo_head_hexsha": "6a841872579f9a079075049b1186be41b3a6f886", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-12-28T22:18:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T08:25:19.000Z", "max_issues_repo_path": "Boneh-PEKS/80BonehPeks/peks.cpp", "max_issues_repo_name": "Rbehnia/Full_PEKS", "max_issues_repo_head_hexsha": "6a841872579f9a079075049b1186be41b3a6f886", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-12-19T09:58:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-31T12:56:22.000Z", "max_forks_repo_path": "Boneh-PEKS/80BonehPeks/peks.cpp", "max_forks_repo_name": "Rbehnia/Full_PEKS", "max_forks_repo_head_hexsha": "6a841872579f9a079075049b1186be41b3a6f886", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T05:28:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T08:17:57.000Z", "avg_line_length": 23.7345207803, "max_line_length": 180, "alphanum_fraction": 0.6444984455, "num_tokens": 8196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.44338636128150405}}
{"text": "#include <iostream>\r\n#include <cstdio>\r\n#include <string>\r\n#include <vector>\r\n#include <fstream>\r\n#include <Eigen/Eigenvalues>\r\n#include <opencv2/opencv.hpp>\r\n#include <algorithm> \r\n#include <math.h>\r\n\r\n\r\n#include \"information.h\"\r\n#include \"functionn.h\"\r\n#include \"read.h\"\r\n\r\nusing namespace std;\r\nusing Eigen::MatrixXd;\r\nusing Eigen::EigenSolver;\r\nusing Eigen::VectorXcd;\r\nusing Eigen::MatrixXcd;\r\n\r\n\r\nstring input,indicator1,indicator2 ;\r\nstring dataset = \"ATT/\";\r\nstring dash = \"_\";\r\nstring file_type = \".png\";\r\n\r\ndouble all_image_matrix[number_of_dataset][figure_height*figure_width] = { 0 };             //Create a vector*vector to store all image\r\nvector<double> average_face;\r\nvector<double> each_eigenvector(figure_height*figure_width,0);\r\nvector<vector<double>> eigenvectors(number_of_eigenvectors,each_eigenvector);\r\nvector<vector<double>> Wfldupeigenvectors(number_of_eigenvectors, each_eigenvector);\r\nvector<vector<double>> Wflddowneigenvectors(number_of_eigenvectors, each_eigenvector);\r\ndouble class_average_face[number_of_face_class][figure_height*figure_width] = { 0 };\r\ndouble class_w[number_of_face_class][number_of_eigenvectors] = { 0 };\r\nint test_index;\r\nint main() {\r\n\r\n\timage_content image;                                                   //Create a class call \"image_content\" to store the information of image\r\n\tdouble each[figure_height*figure_width] = {0};                       //Create a vector to store one image\r\n\r\n\r\n\r\n\t//Data all_data;\r\n\t\r\n\r\n\t//Read and store the data from figure and store it into to image_matrix\r\n\tfor (int i = 0, q = 1, w = 1; i < number_of_dataset && q < 41 && w < 11; i++) {\r\n\t\tindicator1 = to_string(q);\r\n\t\tindicator2 = to_string(w);\r\n\t\tinput = dataset + indicator1 + dash + indicator2 + file_type;      //Read the file by substituting the character.\r\n\t\timage = read::figure(input);                                       //Via opencv to read the image and acquire the data in class \"image_content\" form.\r\n\t\tfor (int j = 0; j < figure_height*figure_width; j++) {\r\n\t\t\teach[j] = (image.content[j]);                                  // Assign the data from class \"image_content\" to vector variable \"each\".\r\n\t\t}\r\n\r\n\t\t//Store information of each figure to the image_matrix\r\n\t\tfor (int k = 0; k < figure_height*figure_width; k++) {\r\n\t\t\tall_image_matrix[i][k] = each[k];\r\n\t\t}\r\n\r\n\t\t//This is just for the pointer.\r\n\t\tif (w < 11) { w++; }\r\n\t\tif (w == 11) { w = 1; q++; }\r\n\t}\r\n\r\n\taverage_face = functionn::averagee(all_image_matrix);    //Feed the image_matrix to the function and acquire the average face.\r\n\r\n\tfunctionn::save_one_face(average_face);                     //This part is saving the average face to a txt, in order to double check the average face is normal or not.\r\n\r\n\r\n\t//********\r\n\tfunctionn::calculate_St();\r\n\tfunctionn::calculate_Sb();\r\n\tfunctionn::calculate_Sw();\r\n\t//return Wopt\r\n\r\n\r\n\t//We got A!  (A = A_matrix)\r\n\t//********\r\n\r\n\t///////////////////////////////////////////////////////////////////////////////\r\n\t// Let's calculate eigenvectors!\r\n\r\n\t//We have two ways to calculate eigenvectors, first is via Matlab, the other is eigen.\r\n\r\n\t//This part is reading the eigenvector and eigenvalue which are calculated from matlab.\r\n\t//Read 6 eigenvalues and its relevant eigenvetors.\r\n\tstring file_name = \"For_matlab/eigenvector\";\r\n\tstring file_type = \".txt\";\r\n\tifstream eigenvector_file;\r\n\tfor (int i = 1; i <= number_of_eigenvectors; i++) {\r\n\t\tint j = 0;\r\n\t\tcout << file_name + to_string(i) + file_type << endl;\r\n\t\teigenvector_file.open(file_name + to_string(i) + file_type, ios::in);\r\n\t\tstring line;\r\n\t\tdouble tem;\r\n\t\twhile (getline(eigenvector_file, line)) {\r\n\t\t\ttem = stod(line);\r\n\t\t\teigenvectors[i - 1][j] = tem;\r\n\t\t\tj++;\r\n\t\t}\r\n\t\teigenvector_file.close();\r\n\t}\r\n\r\n\t\r\n\t//Now we have the essiential item to recognize face!\r\n\tint per = 0;\r\n\tint test_index = 0;\r\n\twhile (true) {\r\n\t\t//cout << \"Please tell me which image do you want to test? (0~49) or enter -1 to exit\" << endl;\r\n\t\t//cin >> test_index;\r\n\t\t//cout << endl;\r\n\r\n\t\tclass_information all;\r\n\t\t//First calculate the aveverge face of each class\r\n\t\tall.calculate_all_average_face();\r\n\r\n\t\t//Let's calculate each omega of all classes\r\n\t\tall.calculate_all_w();\r\n\r\n\r\n\t\tclassify result;\r\n\r\n\t\tresult.calculate_w(all_image_matrix[test_index]);\r\n\t\tresult.criteria_each();                          //Calculate the Euclidian distance\r\n\t\tint d_ans=result.determine_result();\r\n\r\n\r\n\r\n\t\tint ans;\r\n\t\tif (test_index < 10) {\r\n\t\t\tans = 0;\r\n\t\t}\r\n\t\telse if (test_index < 20) {\r\n\t\t\tans = 1;\r\n\t\t}\r\n\t\telse if (test_index < 30) {\r\n\t\t\tans = 2;\r\n\t\t}\r\n\t\telse if (test_index < 40) {\r\n\t\t\tans = 3;\r\n\t\t}\r\n\t\telse if (test_index < 50) {\r\n\t\t\tans = 4;\r\n\t\t}\r\n\t\telse if (test_index < 60) {\r\n\t\t\tans = 5;\r\n\t\t}\r\n\t\telse if (test_index < 70) {\r\n\t\t\tans = 6;\r\n\t\t}\r\n\t\telse if (test_index < 80) {\r\n\t\t\tans = 7;\r\n\t\t}\r\n\t\telse if (test_index < 90) {\r\n\t\t\tans = 8;\r\n\t\t}\r\n\t\telse if (test_index < 100) {\r\n\t\t\tans = 9;\r\n\t\t}\r\n\r\n\t\t//cout << \"And the ground truth is \" << ans << \" !\" << endl;\r\n\r\n\r\n\r\n\t\t//cout << endl;\r\n\r\n\r\n\t\tif (ans == d_ans) {\r\n\t\t\tper = per + 1;\r\n\t\t}\r\n\r\n\t\tif (test_index == number_of_dataset) {\r\n\t\t\tdouble acc = double(per) / double(number_of_dataset);\r\n\t\t\tcout << \"Accuracy=\" << acc*100 << \" %\" << \" !\" << endl;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\ttest_index = test_index + 1;\r\n\t}\r\n\tsystem(\"pause\");\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "e05a1cb87613ede82c93c2a582284761634cdcf0", "size": 5270, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Face_recognition_fisher/main.cpp", "max_stars_repo_name": "yoyotv/Face-detection", "max_stars_repo_head_hexsha": "df998e4ddca063fe2c0878177b8bb61aa7a9e301", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Face_recognition_fisher/main.cpp", "max_issues_repo_name": "yoyotv/Face-detection", "max_issues_repo_head_hexsha": "df998e4ddca063fe2c0878177b8bb61aa7a9e301", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Face_recognition_fisher/main.cpp", "max_forks_repo_name": "yoyotv/Face-detection", "max_forks_repo_head_hexsha": "df998e4ddca063fe2c0878177b8bb61aa7a9e301", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4864864865, "max_line_length": 170, "alphanum_fraction": 0.6174573055, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4433581520548606}}
{"text": "/*\n * CommutingSetGenerator.hpp\n *\n *  Created on: Aug 4, 2017\n *      Author: aqw\n */\n\n#ifndef VQE_TRANSFORMATION_COMMUTINGSETGENERATOR_HPP_\n#define VQE_TRANSFORMATION_COMMUTINGSETGENERATOR_HPP_\n\n#include \"PauliOperator.hpp\"\n#include <Eigen/Core>\n#include <numeric>\n\nnamespace xacc {\n\nnamespace vqe {\nclass CommutingSetGenerator {\n\nprivate:\n\n\tstd::pair<Eigen::VectorXi, Eigen::VectorXi> bv(Term& op, int nQubits) {\n\t\tEigen::VectorXi vx = Eigen::VectorXi::Zero(nQubits);\n\t\tEigen::VectorXi vz = Eigen::VectorXi::Zero(nQubits);\n\n\t\tfor (auto term : op.ops()) {\n\t\t\tif (term.second == \"X\") {\n\t\t\t\tvx(term.first) += 1;\n\t\t\t} else if (term.second == \"Z\") {\n\t\t\t\tvz(term.first) += 1;\n\t\t\t} else if (term.second == \"Y\") {\n\t\t\t\tvx(term.first) += 1;\n\t\t\t\tvz(term.first) += 1;\n\t\t\t}\n\t\t}\n\n\t\treturn std::make_pair(vx, vz);\n\t};\n\n\tint bv_commutator(Term& term1, Term& term2, int nQubits) {\n\t\t\tauto pair1 = bv(term1, nQubits);\n\t\t\tauto pair2 = bv(term2, nQubits);\n\t\t\tauto scalar = pair1.first.dot(pair2.second) + pair1.second.dot(pair2.first);\n\t\t\treturn scalar % 2;\n\t\t};\n\npublic:\n\n\tstd::vector<std::vector<Term>> getCommutingSet(\n\t\t\tPauliOperator& composite, int n_qubits) {\n\n\t\tstd::vector<std::vector<Term>> commuting_ops;\n\t\tstd::vector<Term> allTerms;\n\t\tfor (auto& kv : composite.getTerms()) {\n\t\t\tallTerms.push_back(kv.second);\n\t\t}\n\n\t\tfor (int i = 0; i < allTerms.size(); i++) {\n\n\t\t\tauto t_i = allTerms[i];\n\n\t\t\tif (i == 0) {\n\t\t\t\tcommuting_ops.push_back({t_i});\n\t\t\t} else {\n\t\t\t\tauto comm_ticker = 0;\n\t\t\t\tfor (int j = 0; j < commuting_ops.size(); j++) {\n\t\t\t\t\tauto j_op_list = commuting_ops[j];\n\t\t\t\t\tint sum = 0;\n\t\t\t\t\tint innerCounter = 0;\n\t\t\t\t\tfor (auto j_op : j_op_list) {\n\t\t\t\t\t\tauto t_jopPtr = allTerms[innerCounter];\n\t\t\t\t\t\tsum += bv_commutator(t_i, t_jopPtr,\n\t\t\t\t\t\t\t\tn_qubits);\n\t\t\t\t\t\tinnerCounter++;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (sum == 0) {\n\t\t\t\t\t\tcommuting_ops[j].push_back(t_i);\n\t\t\t\t\t\tcomm_ticker += 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (comm_ticker == 0) {\n\t\t\t\t\tcommuting_ops.push_back({t_i});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn commuting_ops;\n\t}\n\n};\n\n}\n}\n\n#endif\n", "meta": {"hexsha": "4aa4b894d1e5af78323677e6036a0b6b5289eaed", "size": 2022, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ir/algorithms/uccsd/CommutingSetGenerator.hpp", "max_stars_repo_name": "czhao39/xacc-vqe", "max_stars_repo_head_hexsha": "4ad1d9308794e28c37772b7ea29cd3923388168a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ir/algorithms/uccsd/CommutingSetGenerator.hpp", "max_issues_repo_name": "czhao39/xacc-vqe", "max_issues_repo_head_hexsha": "4ad1d9308794e28c37772b7ea29cd3923388168a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ir/algorithms/uccsd/CommutingSetGenerator.hpp", "max_forks_repo_name": "czhao39/xacc-vqe", "max_forks_repo_head_hexsha": "4ad1d9308794e28c37772b7ea29cd3923388168a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4242424242, "max_line_length": 79, "alphanum_fraction": 0.6152324431, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.44333557666603485}}
{"text": "\r\n\r\n#include <NTL/lzz_pE.h>\r\n\r\n#include <NTL/new.h>\r\n\r\nNTL_START_IMPL\r\n\r\nzz_pEInfoT::zz_pEInfoT(const zz_pX& NewP)\r\n{\r\n   build(p, NewP);\r\n\r\n   _card_base = zz_p::modulus();\r\n   _card_exp = deg(NewP);\r\n}\r\n\r\nconst ZZ& zz_pE::cardinality()\r\n{\r\n   if (!zz_pEInfo) LogicError(\"zz_pE::cardinality: undefined modulus\");\r\n\r\n\r\n   do { // NOTE: thread safe lazy init\r\n      Lazy<ZZ>::Builder builder(zz_pEInfo->_card);\r\n      if (!builder()) break;\r\n      UniquePtr<ZZ> p;\r\n      p.make();\r\n      power(*p, zz_pEInfo->_card_base, zz_pEInfo->_card_exp);\r\n      builder.move(p);\r\n   } while (0);\r\n\r\n   return *zz_pEInfo->_card;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nNTL_THREAD_LOCAL SmartPtr<zz_pEInfoT> zz_pEInfo = 0; \r\n\r\n\r\nvoid zz_pE::init(const zz_pX& p)\r\n{\r\n   zz_pEContext c(p);\r\n   c.restore();\r\n}\r\n\r\n\r\nvoid zz_pEContext::save()\r\n{\r\n   ptr = zz_pEInfo;\r\n}\r\n\r\nvoid zz_pEContext::restore() const\r\n{\r\n   zz_pEInfo = ptr;\r\n}\r\n\r\n\r\nzz_pEBak::~zz_pEBak()\r\n{\r\n   if (MustRestore) c.restore();\r\n}\r\n\r\nvoid zz_pEBak::save()\r\n{\r\n   c.save();\r\n   MustRestore = true;\r\n}\r\n\r\n\r\nvoid zz_pEBak::restore()\r\n{\r\n   c.restore();\r\n   MustRestore = false;\r\n}\r\n\r\n\r\n\r\nconst zz_pE& zz_pE::zero()\r\n{\r\n   NTL_THREAD_LOCAL static zz_pE z(INIT_NO_ALLOC);\r\n   return z;\r\n}\r\n\r\n\r\n\r\n\r\nistream& operator>>(istream& s, zz_pE& x)\r\n{\r\n   zz_pX y;\r\n\r\n   NTL_INPUT_CHECK_RET(s, s >> y);\r\n   conv(x, y);\r\n\r\n   return s;\r\n}\r\n\r\nvoid div(zz_pE& x, const zz_pE& a, const zz_pE& b)\r\n{\r\n   zz_pE t;\r\n\r\n   inv(t, b);\r\n   mul(x, a, t);\r\n}\r\n\r\nvoid div(zz_pE& x, const zz_pE& a, long b)\r\n{\r\n   NTL_zz_pRegister(B);\r\n   B = b;\r\n   inv(B, B);\r\n   mul(x, a, B);\r\n}\r\n\r\nvoid div(zz_pE& x, const zz_pE& a, const zz_p& b)\r\n{\r\n   NTL_zz_pRegister(B);\r\n   B = b;\r\n   inv(B, B);\r\n   mul(x, a, B);\r\n}\r\n\r\nvoid div(zz_pE& x, long a, const zz_pE& b)\r\n{\r\n   zz_pE t;\r\n   inv(t, b);\r\n   mul(x, a, t);\r\n}\r\n\r\nvoid div(zz_pE& x, const zz_p& a, const zz_pE& b)\r\n{\r\n   zz_pE t;\r\n   inv(t, b);\r\n   mul(x, a, t);\r\n}\r\n\r\n\r\n\r\nvoid inv(zz_pE& x, const zz_pE& a)\r\n{\r\n   InvMod(x._zz_pE__rep, a._zz_pE__rep, zz_pE::modulus());\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "96206c59417516f829785d53fbe0d9fdcb039d64", "size": 2037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/lzz_pE.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WinNTL-8_1_2/src/lzz_pE.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WinNTL-8_1_2/src/lzz_pE.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.1458333333, "max_line_length": 72, "alphanum_fraction": 0.558173785, "num_tokens": 699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553658, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.44333556668957574}}
{"text": "#ifndef GRAPH_HPP\n#define GRAPH_HPP\n\n#include <algorithm>           // std::all_of\n#include <Eigen/Dense>\n#include <limits>\n\n#include \"readGraphOBJ.hpp\"\n#include \"writeGraphOBJ.hpp\"\n#include \"graphOptions.hpp\"\n\n\n/* TODO: check adjacency_list\n *       add linear triconnectivity implementation\n * \n * \t\t- merge \tGraph(Eigen::MatrixXd nodes, Eigen::MatrixXi adjacency_matrix)\n * \t\t\t\t\tGraph(Eigen::MatrixXd nodes, Eigen::Matrix<int, Eigen::Dynamic, 2> edges)\n */\nnamespace libgraphcpp\n{\n\n\tclass Graph\n\t{\n\tprivate:\n\t\tgraphOptions opts_;                                                      // Store all visualization infos\n\n\t\t// basic structure for edges and nodes\n\t\tEigen::MatrixXd nodes_;                                             // should be a N by 3 matrix of doubles\n\t\tEigen::MatrixXi edges_;                                             // should be a M by 2 matrix of integers\n\t\tint num_nodes_;                                                     // set to N\n\t\tint num_edges_;                                                     // set to M\n\t\tdouble scale_;                                                      // used to trim the tree in simplify_tree \n\t\tdouble cycle_ratio_ = 2;\n        double triangle_ratio_ = 0.9;\n\t\t\n\t\t// structures used for fast circulation through data\n\t\tstd::vector< std::vector<int> > adjacency_list_;                    // contains for each nodes, its nodes neighbors\n\t\tstd::vector< std::vector<int> > adjacency_edge_list_;               // contains for each nodes, its edges neighbors\n\t\tEigen::VectorXd edges_length_;                                      // used only for Dijkstra\n\t\tEigen::MatrixXi adjacency_matrix_;\n\n\t\t// connectivity properties\n\t\tint is_connected_ = -1;                                             // 0 no, 1 yes, -1 undefined\n\t\tint is_biconnected_ = -1;                                           // 0 no, 1 yes, -1 undefined\n\t\tint is_triconnected_ = -1;                                          // 0 no, 1 yes, -1 undefined\n\t\tint has_bridges_ = -1;                                              // 0 no, 1 yes, -1 undefined\n\t\tint has_cycle_ = -1;                                                // 0 no, 1 yes, -1 undefined\n\n\t\t// storing of the cut sets\n\t\tstd::vector< int > one_cut_vertices_;                               // set of articulation points : vector of nodes ids\n\t\tstd::vector< std::pair<int, int> > two_cut_vertices_;               // set of two-cut vertices    : vector of nodes ids pair\n\t\tstd::vector<int> bridges_;                                          // set of briges              : vector of edges ids\n\t\tstd::vector< std::vector<int> > cycles_;                            // set of cycles\n\t\t\n\t\t// internal functions: tools (defined at the bottom of the file)\n\t\tinline void removeRow(Eigen::MatrixXd& matrix, unsigned int rowToRemove);\n\t\tinline void removeRow(Eigen::MatrixXi& matrix, unsigned int rowToRemove);\n\t\tinline void removeDuplicates(std::vector<std::pair<int, int>>& v);\n\t\tinline bool is_element_in_vector(int a, std::vector<int> & A);\n\n\t\t// internal functions: iterative functions (defined at the bottom of the file)\n\t\tinline void DFSUtil(int u, std::vector< std::vector<int> > adj, std::vector<bool> &visited);\n\t\tinline void APUtil(int u, std::vector<bool> & visited, int disc[], int low[], std::vector<int> & parent, std::vector<bool> & ap);\n\t\tinline void bridgeUtil(int u, std::vector<bool> & visited, int disc[], int low[], std::vector<int> & parent, std::vector<int> & bridges);\n\n\tpublic:\n\t\t// creators\n\t\tinline Graph(std::string file_name);\n\t\tinline Graph(std::string file_name, graphOptions opts);\n\t\tinline Graph(Eigen::MatrixXd nodes, Eigen::MatrixXi edges);\n\t\tinline Graph(Eigen::MatrixXd nodes, Eigen::MatrixXi edges, graphOptions opts);\n\n\t\t// destructor\n\t\tinline ~Graph(){};\n\n\t\t// initialisation of the private variables\n\t\tinline void init();\n\t\tinline void set_adjacency_lists();\n\n\n\t\t// save graph as OBJ file\n\t\tinline void save(std::string output_file);\n\t\tinline void print_isolated_vertices();\n\n\n\t\t// accessors\n\t\tint num_nodes();\n\t\tint num_edges();\n\t\tEigen::MatrixXd get_nodes();\n\t\tEigen::Vector3d get_node(int i);\n\t\tEigen::MatrixXi get_edges();\n\t\tEigen::Vector2i get_edge(int i);\n\t\tstd::vector <int> get_adjacency_list(int i);\n\t\tint get_adjacency_list(int i, int j);\n        int find_edge_from_nodes(int node_1, int node_2);\n\n\n\t\t// modifiers for nodes\n\t\tinline void add_node(Eigen::Vector3d node, std::vector<int> neighbours);\n\t\tinline void remove_node(int nodeToRemove);\n\t\tinline void merge_nodes(std::vector<int> nodes);\n\t\tinline void update_node(int node_id, Eigen::Vector3d new_node);\n\t\tinline void update_nodes(Eigen::MatrixXd new_nodes);\n\n\t\t// modifiers for edges\n\t\tinline void add_edge(Eigen::Vector2i edge);\n\t\tinline void remove_edge(int edgeToRemove);\n\t\tinline void collapse_edge(int edge_id);\n\n\n\t\t/* CONNECTIVITY TESTS */\n\t\tinline void connectivity_tests();\n\t\tinline bool is_connected();\n\t\tinline bool is_biconnected(std::vector<int>& one_cut_vertices);\n\t\tinline bool is_biconnected();\n\t\tinline bool is_triconnected(std::vector< std::pair<int, int> >& two_cut_vertices);\n\t\tinline bool is_triconnected();\n\t\tinline bool has_bridges(std::vector<int>& bridges);\n\t\tinline bool has_bridges();\n\t\tinline bool has_cycles(std::vector <std::vector<int>>& cycle_basis, std::vector<double>& cycle_lengths);\n\t\tinline bool has_cycles();\n\n\n\t\t// graph manipulation\n\t\tinline std::vector<std::vector <int> > make_tree(Eigen::MatrixXi& deleted_edges);\n\t\tinline std::vector<std::vector <int> > make_tree();\n\t\tinline void simplify_tree();\n\t\tinline void symplify_graph();\n        inline void remove_flat_triangles();\n\t\tinline void transform (double scale, Eigen::Vector3d move);\n\t\tinline double dijkstra(int source, int target, std::vector<int>& node_path);\n\t\tinline double dijkstra(int source, int target);\n\n\n\t\t/* TO BE REMOVED? This apply only for directional graph */\n\t\tinline int edge_source(int i);\n\t\tinline int edge_target(int i);\n\t\tinline void swap_edge(int i);\n\n\t};\n\n\n\n\n\n\tinline Graph::Graph(std::string file_name)\n\t{\n\t\treadGraphOBJ(file_name, nodes_, edges_);\n\n\t\tinit();\n\t};\n\n\t// overload with options\n\tinline Graph::Graph(std::string file_name, graphOptions opts) : Graph(file_name) \n\t{\n\t\topts_ = opts;\n\t};\n\n\tinline Graph::Graph(Eigen::MatrixXd nodes, Eigen::MatrixXi edges)\n\t{\n\t\t// test if edges is m by 2 (explicit edges) or n by n (adjacency matrix)\n\t\tif ( edges.cols() == 2 )\n\t\t{\n\t\t\tnodes_ = nodes;\n\t\t\tedges_ = edges;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tEigen::MatrixXi adjacency_matrix;\n\t\t\tadjacency_matrix = edges;\n\n\t\t\tif (adjacency_matrix.rows() != adjacency_matrix.cols() || adjacency_matrix.rows() != nodes.rows()) {\n\t\t\t\tstd::cout << \"\\nLibGraphCpp error: wrong input size in the class definition\\n\";\n\t\t\t\tstd::cout << \"Error thrown while assessing: adjacency_matrix.rows() != adjacency_matrix.cols() || adjacency_matrix.rows() != nodes.rows()\\n \";\n\t\t\t\tstd::cout << \"size of the nodes matrix: \" << nodes.rows() << \", \" << nodes.cols() << \"\\n\";\n\t\t\t\tstd::cout << \"size of the edges matrix: \" << edges.rows() << \", \" << edges.cols() << \"\\n\";\n\t\t\t\tstd::exit(EXIT_FAILURE);\n\t\t\t}\n\t\t\tif (adjacency_matrix.transpose() != adjacency_matrix)\n\t\t\t{\n\t\t\t\tstd::cout << \"\\nLibGraphCpp error: the adjacency_matrix should be symmetric\\n \";\n\t\t\t\tstd::exit(EXIT_FAILURE);\n\t\t\t}\n\n\t\t\tnodes_ = nodes;\n\t\t\tEigen::MatrixXi edges((adjacency_matrix.array() != 0).count(), 2);\n\n\t\t\t// explore the upper triangle of the adjacency_matrix (without the diagonal)\n\t\t\tint num_edges = 0;\n\t\t\tfor (int i=0; i<adjacency_matrix.rows(); i++)\n\t\t\t\tfor (int j=i+1; j<adjacency_matrix.cols(); j++) {\n\t\t\t\t\tif (adjacency_matrix(i,j) != 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tedges(num_edges, 0) = i;\n\t\t\t\t\t\tedges(num_edges, 1) = j;\n\t\t\t\t\t\tnum_edges ++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tedges.conservativeResize(num_edges, 2);\n\n\t\t\tedges_ = edges;\n\t\t\tadjacency_matrix_  = adjacency_matrix;\n\t\t}\n\n\t\tinit();\n\t};\n\n\t// overload with options\n\tinline Graph::Graph(Eigen::MatrixXd nodes, Eigen::MatrixXi edges, graphOptions opts) : Graph(nodes, edges) \n\t{\n\t\topts_ = opts;\n\t};\n\n\t// initialisation of the private variables\n\tinline void Graph::init()\n\t{\n\t\tif (nodes_.cols()!=3 || edges_.cols()!=2) {\n\t\t\tstd::cout << \"\\nLibGraphCpp error: wrong graph dimensions in the class initialization\" << std::endl;\n\t\t\tstd::cout << \"nodes size: \" << nodes_.rows() << \" * \" << nodes_.cols()<< std::endl;\n\t\t\tstd::cout << \"edges size: \" << edges_.rows() << \" * \" << edges_.cols()<< std::endl;\n\t\t\tstd::exit(EXIT_FAILURE);\n\t\t}\n\n\t\tone_cut_vertices_.clear();\n\t\ttwo_cut_vertices_.clear();\n\t\tbridges_.clear();\n\n\t\t// set up properties\n\t\tnum_nodes_ = nodes_.rows();\n\t\tnum_edges_ = edges_.rows();\n\n\t\t// get scale\n\t\tEigen::MatrixXd max_point = nodes_.colwise().maxCoeff();\n\t\tEigen::MatrixXd min_point = nodes_.colwise().minCoeff();\n\t\tscale_ = (max_point - min_point).norm();\n\n\t\t// set up edges_length\n\t\tedges_length_ = Eigen::VectorXd::Zero(num_edges_);\n\t\tfor (int i=0; i<num_edges_; i++) {\n\t\t\tif ( (edges_(i, 0) >= num_nodes_) || (edges_(i, 1) >= num_nodes_) ||\n\t\t\t\t\t(edges_(i, 0) < 0) || (edges_(i, 1) < 0) ) {\n\t\t\t\tstd::cout << \"\\nLibGraphCpp error: wrong edge given in the class initialization\" << std::endl;\n\t\t\t\tstd::cout << \"the edge: (\" << edges_(i, 0) << \", \" << edges_(i, 1) << \") does not works for \" << num_nodes_ << \" nodes.\" << std::endl;\n\t\t\t\tstd::exit(EXIT_FAILURE);\n\t\t\t}\n\t\t\tedges_length_(i) = (nodes_.row(edges_(i,0)) - nodes_.row(edges_(i,1)) ).norm();\n\t\t}\n\t\t\n\t\t// set up the adjacency list\n\t\tset_adjacency_lists();\n\t};\n\n\tinline void Graph::set_adjacency_lists()\n\t{\n\t\t// TODO: - the if statement should be removed for undirected graphs as they are not needed\n\t\t//       - is the adjacency_edge_list_ needed?\n\n\t\t// make sure the lists are empty to start with\n\t\tadjacency_list_.clear();\n\t\tadjacency_edge_list_.clear();\n\t\t\n\t\tadjacency_list_.resize(num_nodes_);\n\t\tadjacency_edge_list_.resize(num_nodes_);\n\t\t\n\t\tfor (int i=0; i<num_edges_; i++)\n\t\t{\n\t\t\t// the if statements check if the node has already been inserted\n\t\t\tif (std::find (adjacency_list_[edges_(i, 0)].begin(), adjacency_list_[edges_(i, 0)].end(), edges_(i, 1))==adjacency_list_[edges_(i, 0)].end())\n\t\t\t\tadjacency_list_[edges_(i, 0)].push_back(edges_(i, 1));\n\t\t\tif (std::find (adjacency_list_[edges_(i, 1)].begin(), adjacency_list_[edges_(i, 1)].end(), edges_(i, 0))==adjacency_list_[edges_(i, 1)].end())\n\t\t\t\tadjacency_list_[edges_(i, 1)].push_back(edges_(i, 0));\n\t\t\tadjacency_edge_list_[edges_(i, 0)].push_back(i);\n\t\t\tadjacency_edge_list_[edges_(i, 1)].push_back(i);\n\t\t}\n\t};\n\n\n\t// save graph as OBJ file\n\tinline void Graph::save(std::string output_file)\n\t{\n\t\twriteGraphOBJ(nodes_, edges_, output_file);\n\t};\n\n\tinline void Graph::print_isolated_vertices()\n\t{\n\t\tfor (int i=0; i<num_nodes_; i++)\n\t\t\tif (adjacency_list_[i].size() == 0)\n\t\t\t\tstd::cout << \"Isolated vertices at: \" << i << std::endl;\n\t};\n\n\n\t// accessors\n\tinline int Graph::num_nodes() { return num_nodes_; };\n\tinline int Graph::num_edges() { return num_edges_; };\n\tinline Eigen::MatrixXd Graph::get_nodes() { return nodes_; };\n\tinline Eigen::Vector3d Graph::get_node(int i) { return nodes_.row(i); };\n\tinline Eigen::MatrixXi Graph::get_edges() { return edges_; };\n\tinline Eigen::Vector2i Graph::get_edge(int i) { return edges_.row(i); };\n\tinline std::vector <int> Graph::get_adjacency_list(int i) { return adjacency_list_[i]; };\n\tinline int Graph::get_adjacency_list(int i, int j) { return adjacency_list_[i][j]; };\n\n\tinline int Graph::find_edge_from_nodes(int node_1, int node_2)\n\t{\n\t\tfor (int i=0; i<num_edges_; i++) {\n\t\t\tif (edges_(i, 0) == node_1 && edges_(i, 1) == node_2)\n\t\t\t\treturn i;\n\t\t\tif (edges_(i, 0) == node_2 && edges_(i, 1) == node_1)\n\t\t\t\treturn i;\n\t\t}\n\t\treturn -1;\n\t};\n\n\t// modifiers for nodes\n\tinline void Graph::add_node(Eigen::Vector3d node, std::vector<int> neighbours)\n\t{\n\t\t// add node\n\t\tEigen::MatrixXd temp_nodes = nodes_;\n\t\tnodes_.resize(nodes_.rows()+1, 3);\n\t\tnodes_ << temp_nodes, node.transpose();\n\t\t\n\t\t// add related edges\n\t\tEigen::MatrixXi temp_edges = edges_;\n\t\tEigen::MatrixXi edges_to_add(neighbours.size(), 2);\n\t\tfor (int edge_iterator=0; edge_iterator<neighbours.size(); edge_iterator++)\n\t\t\tedges_to_add.row(edge_iterator) << nodes_.rows()-1, neighbours[edge_iterator];\n\t\t\n\t\tedges_.resize(temp_edges.rows()+edges_to_add.rows(), 2);\n\t\tedges_ << temp_edges, edges_to_add;\n\n\t\tinit();\n\t};\n\n\tinline void Graph::remove_node(int nodeToRemove) \n\t{\n\t\t// remove node\n\t\tremoveRow(nodes_, nodeToRemove);\n\n\t\t// remove related edges\n\t\tstd::vector<int> edges_to_remove = adjacency_edge_list_[nodeToRemove];\n\t\tstd::sort(edges_to_remove.begin(), edges_to_remove.end(), std::greater<int>());\n\t\tfor (int edge_iterator=0; edge_iterator<edges_to_remove.size(); edge_iterator++)\n\t\t\tremoveRow(edges_, edges_to_remove[edge_iterator]);\n\n\t\t// update the edge nodes index (we have one less node now)\n\t\tfor (int i=0; i<edges_.rows(); i++)\n\t\t\tfor (int j=0; j<edges_.cols(); j++)\n\t\t\t\tif (edges_(i,j) >= nodeToRemove)\n\t\t\t\t\tedges_(i,j)--;\n\n\t\tinit();\n\t};\n\n\tinline void Graph::merge_nodes(std::vector<int> nodes)\n\t{\n\t\t// make sure there is no duplicates\n\t\tsort( nodes.begin(), nodes.end() );\n\t\tnodes.erase( unique( nodes.begin(), nodes.end() ), nodes.end() );\n\n\t\t// store connected elements first\n\t\tstd::vector<int> neighbours;\n\t\tfor (int node : nodes)\n\t\t\tfor (int neighour : adjacency_list_[node])\n\t\t\t\tneighbours.push_back(neighour);\n\n\t\tstd::sort(neighbours.begin(), neighbours.end());\n\t\tneighbours.erase( std::unique( neighbours.begin(), neighbours.end() ), neighbours.end() );\n\n\t\t// find node position\n\t\tEigen::Vector3d merged_node;\n\t\tmerged_node << 0,0,0;\n\t\tfor (int node : nodes)\n\t\t\tmerged_node += nodes_.row(node);\n\t\tmerged_node /= nodes.size();\n\n\t\t// add merged node (it is stacked at the end so it has to be done before deleting the nodes)\n\t\tadd_node(merged_node, neighbours);\n\t\t\n\t\t// delete other nodes\n\t\tstd::sort(nodes.begin(), nodes.end(), std::greater<int> ());\n\t\tfor (int node : nodes)\n\t\t\tremove_node(node);\n\t};\n\n\tinline void Graph::update_node(int node_id, Eigen::Vector3d new_node)\n\t{\n\t\tnodes_.row(node_id) = new_node;\n\t}\n\n\tinline void Graph::update_nodes(Eigen::MatrixXd new_nodes)\n\t{\n\t\tif (nodes_.rows() == new_nodes.rows() && nodes_.cols() == new_nodes.cols()) {\n\t\t\tnodes_ = new_nodes;\n\t\t} else {\n\t\t\tstd::cout << \"Error: wrong dimension:\\n\"; \n\t\t\tstd::cout << \"nodes_.rows() == new_nodes.rows() && nodes_.cols() == new_nodes.cols() returned False \\n \";\n\t\t\tstd::exit(0);\n\t\t}\n\t};\n\n\t// modifiers for edges\n\tinline void Graph::add_edge(Eigen::Vector2i edge)\n\t{\n\t\t// add node\n\t\tEigen::MatrixXi temp_edges = edges_;\n\t\tedges_.resize(edges_.rows()+1, 3);\n\t\tedges_ << temp_edges, edge.transpose();\n\t\t\n\t\tinit();\n\t};\n\n\tinline void Graph::remove_edge(int edgeToRemove) \n\t{\n\t\t// remove edge\n\t\tremoveRow(edges_, edgeToRemove);\n\n\t\tinit();\n\t};\n\n\t// replace an edge and its two connected nodes by a single node\n\tinline void Graph::collapse_edge(int edge_id)\n\t{\n\t\t// get nodes_id:\n\t\tint node_1 = edges_(edge_id, 0);\n\t\tint node_2 = edges_(edge_id, 1);\n\n\t\t// merge the two previous ones\n\t\tEigen::Vector3d fused_node = (nodes_.row(node_1) + nodes_.row(node_2) ) / 2;\n\n\t\t// get the connected neighbours\n\t\tstd::vector<int> neighbours;\n\t\tneighbours = adjacency_list_[node_1];\n\t\tneighbours.insert( neighbours.end(), adjacency_list_[node_2].begin(), adjacency_list_[node_2].end() );\n\n\t\t// remove old nodes\n\t\tneighbours.erase(std::remove(neighbours.begin(), neighbours.end(), node_1), neighbours.end());\n\t\tneighbours.erase(std::remove(neighbours.begin(), neighbours.end(), node_2), neighbours.end());\n\n\t\tsort( neighbours.begin(), neighbours.end() );\n\t\tneighbours.erase( unique( neighbours.begin(), neighbours.end() ), neighbours.end() );\n\n\t\t// add node\n\t\tadd_node(fused_node, neighbours);\n\t\t\n\t\t// remove the previous nodes (the order matter)\n\t\tif (node_2<node_1) {\n\t\t\tremove_node(node_1);\n\t\t\tremove_node(node_2);\n\t\t} else {\n\t\t\tremove_node(node_2);\n\t\t\tremove_node(node_1);\n\t\t}\n\t};\n\n\n\t/* CONNECTIVITY TESTS */\n\tinline void Graph::connectivity_tests()\n\t{\n\t\tis_connected();\n\t\tis_biconnected();\n\t\tis_triconnected();\n\t\thas_bridges();\n\t};\n\n\tinline bool Graph::is_connected()\n\t{\n\t\tif (is_connected_ == -1) {\n\t\t\t// check for graph connectivity using DFS:\n\t\t\tstd::vector<bool> visited(num_nodes_, false);\n\t\t\tDFSUtil(0, adjacency_list_, visited);\n\t\t\tis_connected_ = std::all_of(visited.begin(), visited.end(), [](bool v) { return v; });\n\n\t\t\tif (opts_.verbose)\n\t\t\t\tstd::cout << \"graph is connected: \" << is_connected_ << std::endl;\n\n\t\t\t// if not connected, update the next ones\n\t\t\tif (is_connected_ == 0) {\n\t\t\t\tis_biconnected_ = 0;\n\t\t\t\tis_triconnected_ = 0;\n\t\t\t}\n\t\t}\n\t\treturn is_connected_;\n\t};\n\n\t// return the set of one cut vertices\n\tinline bool Graph::is_biconnected(std::vector<int>& one_cut_vertices)\n\t{\n\t\tif (is_biconnected_ == -1) {\n\t\t\t// check for 2 node connectivity:\n\t\t\tstd::vector<bool> visited(num_nodes_, false);\n\t\t\tstd::vector<int> parent(num_nodes_, -1);\n\t\t\tstd::vector<bool> ap(num_nodes_, false);\n\t\t\tint *disc = new int[num_nodes_];\n\t\t\tint *low = new int[num_nodes_];\n\t\t\t// Call the recursive helper function to find articulation points \n\t\t\t// in DFS tree rooted with vertex '0' \n\t\t\tfor (int i = 0; i < num_nodes_; i++) \n\t\t\t\tif (visited[i] == false) \n\t\t\t\t\tAPUtil(i, visited, disc, low, parent, ap);\n\t\t\t\n\t\t\t// Now ap[] contains articulation points, print them and store them into one_cut_vertices_\n\t\t\tone_cut_vertices.clear();\n\t\t\tfor (int i = 0; i < num_nodes_; i++) \n\t\t\t\tif (ap[i] == true) {\n\t\t\t\t\tone_cut_vertices.push_back(i);\n\t\t\t\t\tif (opts_.verbose)\n\t\t\t\t\t\tstd::cout << \"Articulation point \" << i << \" at: \"  << nodes_.row(i) << std::endl;\n\t\t\t\t}\n\t\t\tis_biconnected_ = std::none_of(ap.begin(), ap.end(), [](bool v) { return v; });\n\t\t\t\n\t\t\tone_cut_vertices_ = one_cut_vertices;\n\t\t} else {\n\t\t\tone_cut_vertices = one_cut_vertices_;\n\t\t}\n\n\t\tif (opts_.verbose)\n\t\t\tstd::cout << \"graph is 2-connected: \" << is_biconnected_ << std::endl;\n\n\t\treturn is_biconnected_;\n\t};\n\n\t// overload is_biconnected\n\tinline bool Graph::is_biconnected()\n\t{\n\t\tstd::vector< int > one_cut_vertices;\n\t\treturn is_biconnected(one_cut_vertices);\n\t};\n\n\t// return the set of two cut vertices\n\tinline bool Graph::is_triconnected(std::vector< std::pair<int, int> >& two_cut_vertices)\n\t{ \n\t\t/* this function run in quadratic time, this is not the most efficient way to do it\n\t\t* for alternative, see these papers:\n\t\t* - Finding the Triconnected Components of a Graph (1972)\n\t\t* - A Linear Time Implementation of SPQR-Trees (2000)\n\t\t* and these implementations:\n\t\t* - http://www.ogdf.net/doku.php\n\t\t* - https://github.com/adrianN/Triconnectivity\n\t\t*/\n\t\tgraphOptions opts = opts_;\n\t\topts.verbose = false;\n\t\tif (is_triconnected_ == -1) {\n\t\t\tis_triconnected_ = true;\n\t\t\tfor (int i=0; i<num_nodes_; i++) {\n\t\t\t\tstd::vector< int > one_cut_vertices;\n\t\t\t\tGraph reduced_graph(nodes_, edges_, opts);\n\t\t\t\treduced_graph.init();\n\t\t\t\treduced_graph.remove_node(i);\n\t\t\t\tbool reduced_graph_is_biconnected = reduced_graph.is_biconnected(one_cut_vertices);\n\n\t\t\t\tif (not reduced_graph_is_biconnected)\n\t\t\t\t\tfor (int j=0; j<one_cut_vertices.size(); j++) {\n\t\t\t\t\t\tint node_offset = (one_cut_vertices[j]>=i); // offset needed because a node has been deleted\n\t\t\t\t\t\ttwo_cut_vertices.push_back(std::make_pair(i, one_cut_vertices[j]+node_offset));\n\t\t\t\t\t}\n\t\t\t\tis_triconnected_ &= reduced_graph_is_biconnected;\n\t\t\t}\n\n\t\t\tremoveDuplicates(two_cut_vertices);\n\t\t\ttwo_cut_vertices_ = two_cut_vertices;\n\t\t} else {\n\t\t\ttwo_cut_vertices = two_cut_vertices_;\n\t\t}\n\n\t\tif (opts_.verbose) {\n\t\t\tstd::cout << \"graph is 3-connected: \" << is_triconnected_ << std::endl;\n\t\t\tfor (int i = 0; i<two_cut_vertices.size(); i++)\n\t\t\t\tstd::cout << \"two_cut_vertices between node \" << two_cut_vertices[i].first <<\" and node \" << two_cut_vertices[i].second << std::endl;\n\t\t}\n\n\t\treturn is_triconnected_;\n\t};\n\t\n\t// overload is_triconnected\n\tinline bool Graph::is_triconnected()\n\t{ \n\t\tstd::vector< std::pair<int, int> > two_cut_vertices;\n\t\treturn is_triconnected(two_cut_vertices);\n\t};\n\n\t// return the set of bridges\n\tinline bool Graph::has_bridges(std::vector<int>& bridges)\n\t{\n\t\tif (has_bridges_ == -1) {\n\t\t\t// check for bridges:\n\n\t\t\tstd::vector<bool> visited(num_nodes_, false);\n\t\t\tstd::vector<int> parent(num_nodes_, -1);\n\t\t\tint *disc = new int[num_nodes_]; \n\t\t\tint *low = new int[num_nodes_];\n\t\t\t\n\t\t\t// Call the recursive helper function to find Bridges \n\t\t\t// in DFS tree rooted with vertex 'i' \n\t\t\tfor (int i = 0; i < num_nodes_; i++) \n\t\t\t\tif (visited[i] == false) \n\t\t\t\t\tbridgeUtil(i, visited, disc, low, parent, bridges);\n\t\t\t\n\t\t\tdelete[] disc;\n\t\t\tdelete[] low;\n\n\t\t\tif (bridges.size() == 0)\n\t\t\t\thas_bridges_ = 0;\n\t\t\telse\n\t\t\t\thas_bridges_ = 1;\n\t\t\t\n\t\t\tbridges_ = bridges;\n\t\t} else {\n\t\t\tbridges = bridges_;\n\t\t}\n\n\t\tif (opts_.verbose)\n\t\t\tstd::cout << \"graph has bridges: \" << has_bridges_ << std::endl;\n\t\t\n\t\treturn has_bridges_;\n\t};\n\n\t// overload has_bridges\n\tinline bool Graph::has_bridges()\n\t{\n\t\tstd::vector<int> bridges;\n\t\treturn has_bridges(bridges);\n\t};\n\n\t// return a fundamental cycles basis (see: An Algorithm for Finding a Fundamental Set of Cycles of a Graph)\n\t// should use DFS or BFS for generating the tree\n\tinline bool Graph::has_cycles(std::vector <std::vector<int>>& cycle_basis, std::vector<double>& cycle_lengths)\n\t{\n\t\tgraphOptions opts = opts_;\n\t\topts.verbose = false;\n\t\tGraph spanning_tree(nodes_, edges_, opts);\n\t\tEigen::MatrixXi deleted_edges;\n\t\tspanning_tree.make_tree(deleted_edges);\n\n\t\tfor (int i=0; i<deleted_edges.rows(); i++) {\n\t\t\tstd::vector<int> cycle;\n\t\t\tdouble cycle_length;\n\t\t\tcycle_length = spanning_tree.dijkstra(deleted_edges(i, 0), deleted_edges(i, 1), cycle);\n\n\n\t\t\tdouble deleted_edge_length = (spanning_tree.get_node(deleted_edges(i, 0)) - spanning_tree.get_node(deleted_edges(i, 1))).norm();\n\t\t\tcycle_length = cycle_length + deleted_edge_length;\n\t\t\tcycle_basis.push_back(cycle);\n\t\t\tcycle_lengths.push_back(cycle_length);\n\t\t}\n\t\t\n\t\tif (cycle_basis.size() != 0)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t};\n\n\t// overload has_cycle\n\tinline bool Graph::has_cycles()\n\t{\n\t\tstd::vector <std::vector <int>> cycles;\n\t\tstd::vector<double> cycle_lengths;\n\t\treturn has_cycles(cycles, cycle_lengths);\n\t};\n\n\n\tinline std::vector<std::vector <int> > Graph::make_tree(Eigen::MatrixXi& deleted_edges)\n\t{\n\t\tstd::vector<std::vector <int> > nodes_references(num_nodes_);\n\t\tfor (int i=0; i<num_nodes_; i++)\n\t\t\tnodes_references[i].push_back(i);\n\t\t\n\t\tbool verbose_temp = opts_.verbose;\n\t\topts_.verbose = false;\n\n\t\t// check for bridges\n\t\thas_bridges_ = -1;\n\t\thas_bridges();\n\n\t\tdeleted_edges.resize(num_edges_ - num_nodes_ + 1, 2); // cycle rank * 2\n\t\tint counter = 0;\n\n\t\twhile (bridges_.size() != num_edges_)\n\t\t{\n\n\t\t\t// list all non bridges\n\t\t\tstd::vector <int> edges_to_edit;\n\t\t\tstd::vector <double> edges_length;\n\t\t\tfor (int i=0; i<num_edges_; i++)\n\t\t\t\tif (find (bridges_.begin(), bridges_.end(), i) == bridges_.end()) {\n\t\t\t\t\tedges_to_edit.push_back(i);\n\t\t\t\t\tedges_length.push_back(edges_length_(i));\n\t\t\t\t}\n\n\t\t\t// sort edges by decreasing length\n\t\t\tstd::vector<std::pair<double, int>> sorting_container;\n\t\t\tsorting_container.reserve(edges_to_edit.size());\n\t\t\tstd::transform(edges_length.begin(), edges_length.end(), edges_to_edit.begin(), std::back_inserter(sorting_container),\n\t\t\t\t[](double a, int b) { return std::make_pair(a, b); });\n\n\t\t\tstd::sort(sorting_container.begin(), sorting_container.end()); \n\t\t\tstd::reverse(sorting_container.begin(), sorting_container.end());\n\n\t\t\t// store edges\n\t\t\tdeleted_edges.row(counter) << edges_.row(sorting_container[0].second);\n\t\t\tcounter ++;\n\n\t\t\t// actually store the edges\n\t\t\t//collapse_edge(edges_to_edit[0]);\n\t\t\tremove_edge(sorting_container[0].second);\n\t\t\t\n\t\t\t// check for bridges\n\t\t\thas_bridges_ = -1;\n\t\t\thas_bridges();\n\t\t}\n\n\t\topts_.verbose = verbose_temp;\n\t\treturn nodes_references;\n\t};\n\n\t// overload make_tree if deleted edges are not needed\n\tinline std::vector<std::vector <int> > Graph::make_tree()\n\t{\n\t\tEigen::MatrixXi deleted_edges;\n\t\treturn make_tree(deleted_edges);\n\t};\n\n\tinline void Graph::simplify_tree()\n\t{\n\t\t/* \n\t\t\t* for each junctions:\n\t\t\t* if the distance between two junction is \"small\"\n\t\t\t* then merge all the nodes in the path\n\t\t\t*/\n\t\tstd::vector<int> junction_list;\n\t\tstart_junction_checking:\n\t\tjunction_list.clear();\n\t\tfor (int i=0; i<adjacency_list_.size(); i++)\n\t\t\tif (adjacency_list_[i].size()>2)\n\t\t\t\tjunction_list.push_back(i);\n\n\t\tfor (int i = 0; i<junction_list.size(); i++) {\n\t\t\tfor (int j = i+1; j<junction_list.size(); j++) {\n\t\t\t\tstd::vector<int> path;\n\t\t\t\tdouble junctions_distance = dijkstra(junction_list[i], junction_list[j], path);\n\n\t\t\t\tif (junctions_distance < scale_/10)\n\t\t\t\t{\n\t\t\t\t\tmerge_nodes(path);\n\t\t\t\t\tgoto start_junction_checking; // went throwing up after writing this\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* \n\t\t\t* for each leaf:\n\t\t\t* if the distance to the closest junction is \"small\"\n\t\t\t* then delete all nodes until this node is reached\n\t\t\t*/\n\t\tstd::vector<int> leaves_list;\n\t\tjunction_list.clear();\n\t\tfor (int i=0; i<adjacency_list_.size(); i++){\n\t\t\tif (adjacency_list_[i].size()==1)\n\t\t\t\tleaves_list.push_back(i);\n\t\t\t\n\t\t\tif (adjacency_list_[i].size()>2)\n\t\t\t\tjunction_list.push_back(i);\n\t\t}\n\n\t\t// for each leaves check the distance to each junction\n\t\tstd::vector<int> nodes_to_delete;\n\t\tfor (int leaf: leaves_list) {\n\t\t\tfor (int junction: junction_list) {\n\t\t\t\tstd::vector<int> path;\n\t\t\t\tdouble leaf_to_junction_distance = dijkstra(leaf, junction, path);\n\n\t\t\t\tif (leaf_to_junction_distance < scale_/10)\n\t\t\t\t{\n\t\t\t\t\tfor (int node_id : path)\n\t\t\t\t\t\tif (node_id != junction)\n\t\t\t\t\t\t\tnodes_to_delete.push_back(node_id);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (nodes_to_delete.size() != 0) {\n\t\t\tstd::sort(nodes_to_delete.begin(), nodes_to_delete.end(), std::greater<int>());\n\t\t\tnodes_to_delete.erase( std::unique( nodes_to_delete.begin(), nodes_to_delete.end() ), nodes_to_delete.end() );\n\t\t\tfor (int node_id : nodes_to_delete)\n\t\t\t\tremove_node(node_id);\n\t\t}\n\n\t};\n\n\tinline void Graph::symplify_graph()\n\t{\n\t\t// list all cycles\n\t\tstd::vector< std::vector< int > > cycle_basis;\n\t\tstd::vector< double > cycle_lengths;\n\t\thas_cycles(cycle_basis, cycle_lengths);\n\n\t\t// remove large cycles\n\t\tfor(int i=0; i<cycle_lengths.size();) {\n\t\t\tif(cycle_lengths[i] > scale_/cycle_ratio_) {\n\t\t\t\tcycle_lengths.erase(cycle_lengths.begin()+i); \n\t\t\t\tcycle_basis.erase(cycle_basis.begin() + i);\n\t\t\t} else {\n\t\t\t\t++i;\n\t\t\t}\n\t\t}\n\n\t\t// find set of clustered nodes\n\t\tstd::vector< std::vector< int > > clusters;\n\t\tbool clusters_found = false;\n\t\twhile (!clusters_found) {\n\t\t\tstd::vector <int> cluster_temp;\n\t\t\tcluster_temp = cycle_basis[0];\n\t\t\tcycle_basis.erase(cycle_basis.begin());\n\n\t\t\tfor(int i=0; i<cycle_basis.size(); )\n\t\t\t{\n\t\t\t\t// check for intersection\n\t\t\t\tstd::vector <int> v1, v2;\n\t\t\t\tv1 = cluster_temp;\n\t\t\t\tv2 = cycle_basis[i];\n\n\t\t\t\tsort(v1.begin(), v1.end());\n\t\t\t\tsort(v2.begin(), v2.end());\n\n\t\t\t\tstd::vector<int> v(v1.size() + v2.size()); \n\t\t\t\tstd::vector<int>::iterator it, st; \n\n\t\t\t\tit = set_intersection(v1.begin(), \n\t\t\t\t\t\t\t\t\t\tv1.end(), \n\t\t\t\t\t\t\t\t\t\tv2.begin(), \n\t\t\t\t\t\t\t\t\t\tv2.end(), \n\t\t\t\t\t\t\t\t\t\tv.begin());\n\n\t\t\t\tbool each_cycle_have_common_elements = false;\n\t\t\t\tfor (st = v.begin(); st != it; ++st)\n\t\t\t\t\teach_cycle_have_common_elements = true;\n\n\t\t\t\tif(each_cycle_have_common_elements) {\n\t\t\t\t\tcluster_temp.insert( cluster_temp.end(), cycle_basis[i].begin(), cycle_basis[i].end() );\n\t\t\t\t\tcycle_basis.erase(cycle_basis.begin()+i);\n\t\t\t\t\ti = 0;\n\t\t\t\t} else {\n\t\t\t\t\t++i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// add sort + unique\n\t\t\tsort( cluster_temp.begin(), cluster_temp.end() );\n\t\t\tcluster_temp.erase( unique( cluster_temp.begin(), cluster_temp.end() ), cluster_temp.end() );\n\t\t\tclusters.push_back(cluster_temp);\n\n\t\t\tif (cycle_basis.size() == 0)\n\t\t\t\tclusters_found = true;\n\t\t}\n\t\t\n\t\t// merge nodes\n\t\tfor (int i=0; i<clusters.size(); i++) {\n\t\t\tstd::vector<int> empty_set;\n\t\t\tmerge_nodes(clusters[i]);\n\t\t\t// each time a node is removed, the other lists should be updated to avoid deleting the wrong nodes\n\t\t\tfor (int j=i+1; j<clusters.size(); j++)\n\t\t\t\tfor (int k=0; k<clusters[j].size(); k++) {\n\t\t\t\t\tint offset = 0;\n\t\t\t\t\tfor (int merged_node : clusters[i]) {\n\t\t\t\t\t\t// first check if the point is shared (it would then be the last node)\n\t\t\t\t\t\tif (clusters[j][k] == merged_node)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\toffset = 0;\n\t\t\t\t\t\t\tclusters[j][k] = num_nodes_-1;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// otherwise check if the merged point is lower, then the node has to be shifted of one position\n\t\t\t\t\t\tif (clusters[j][k] > merged_node)\n\t\t\t\t\t\t\toffset ++;\n\t\t\t\t\t}\n\t\t\t\t\tclusters[j][k] -= offset;\n\t\t\t\t}\n\t\t}\n\t};\n\n\t// the listing of the triangles should be performed differently\n\t// -> listing the fundamental cycles basis can be inacurate\n\t// -> or replace by the minimal cycle basis\n\tinline void Graph::remove_flat_triangles()\n\t{\n\t\t// list all cycles\n\t\tstd::vector< std::vector< int > > cycle_basis;\n\t\tstd::vector< double > cycle_lengths;\n\t\thas_cycles(cycle_basis, cycle_lengths);\n\n\t\t// go through each cycles\n\t\tfor (int i=0; i<cycle_basis.size(); i++) {\n\t\t\tif (cycle_basis[i].size() == 3) {\n\t\t\t\tint edge_1 = find_edge_from_nodes(cycle_basis[i][0], cycle_basis[i][1]);\n\t\t\t\tint edge_2 = find_edge_from_nodes(cycle_basis[i][1], cycle_basis[i][2]);\n\t\t\t\tint edge_3 = find_edge_from_nodes(cycle_basis[i][2], cycle_basis[i][0]);\n\n\t\t\t\tstd::vector<std::pair<double, int>> triangle_distance(3);\n\t\t\t\ttriangle_distance[0] = std::make_pair( edges_length_(edge_1), edge_1);\n\t\t\t\ttriangle_distance[1] = std::make_pair( edges_length_(edge_2), edge_2);\n\t\t\t\ttriangle_distance[2] = std::make_pair( edges_length_(edge_3), edge_3);\n\n\t\t\t\tsort(triangle_distance.begin(), triangle_distance.end());\n\n\t\t\t\tif (triangle_distance[2].first > (triangle_distance[0].first + triangle_distance[1].first)*triangle_ratio_)\n\t\t\t\t\tremove_edge(triangle_distance[2].second);\n\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t};\n\n\tinline void Graph::transform (double scale, Eigen::Vector3d move) \n\t{\n\t\tnodes_ /= scale;\n\t\tnodes_ += move.transpose();\n\t};\n\n\tinline double Graph::dijkstra(int source, int target, std::vector<int>& node_path) \n\t{\n\t\t// initialization\n\t\tdouble distance_source_to_target;\n\t\tstd::vector<double> min_distance(num_nodes_, std::numeric_limits<double>::infinity());\n\t\tstd::vector<int> previous_node(num_nodes_, -1);\n\n\t\t// set the set of visited nodes:\n\t\tstd::vector<int> visited;\n\t\tstd::vector<int> to_visit;\n\n\t\t// initialize the node to start from\n\t\tint u = source;\n\t\tmin_distance.at(source) = 0;\n\n\t\t// start searching\n\t\tbool target_found;\n\t\twhile (!target_found) {\n\t\t\t// check all neighbours of \"u\"\n\t\t\tfor (int i = 0; i < adjacency_list_.at(u).size(); ++i) {\n\t\t\t\tint neighbour_node = adjacency_list_.at(u).at(i);\n\t\t\t\tdouble edge_length = edges_length_(adjacency_edge_list_.at(u).at(i));\n\t\t\t\tif (not is_element_in_vector(neighbour_node, to_visit))\n\t\t\t\t\tif (not is_element_in_vector(neighbour_node, visited))\n\t\t\t\t\t\tto_visit.push_back(neighbour_node);\n\t\t\t\t\n\t\t\t\tif ( min_distance.at(u) + edge_length < min_distance.at( neighbour_node ) ) {\n\t\t\t\t\tmin_distance.at( neighbour_node ) = min_distance.at(u) +  edge_length;\n\t\t\t\t\tprevious_node.at( neighbour_node ) = u;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvisited.push_back(u);\n\n\t\t\t// check if the visited point is in sub_V\n\t\t\ttarget_found = is_element_in_vector(target, visited);\n\n\t\t\t// set next u\n\t\t\tint index_of_next_point = 0;\n\t\t\tfor (int i = 0; i < to_visit.size(); ++i)\n\t\t\t\tif (min_distance.at( to_visit.at(i) ) < min_distance.at( to_visit.at( index_of_next_point) ) )\n\t\t\t\t\tindex_of_next_point = i;\n\n\n\t\t\t// check if all vertices have been visited:\n\t\t\tif (to_visit.size() == 0)\n\t\t\t\tbreak;\n\n\t\t\tu = to_visit.at(index_of_next_point);\n\t\t\tto_visit.erase(to_visit.begin() + index_of_next_point);\n\t\t}\n\t\t\n\t\t// backtracking to generate path\n\t\tif (min_distance.at(target) != std::numeric_limits<double>::infinity()) {\n\t\t\tint backtracking_node = target;\n\t\t\tnode_path.insert(node_path.begin(), backtracking_node);\n\t\t\t\n\t\t\twhile (backtracking_node != source) {\n\t\t\t\tnode_path.insert(node_path.begin(), previous_node[backtracking_node]);\n\t\t\t\tbacktracking_node = previous_node[backtracking_node];\n\t\t\t}\n\t\t}\n\n\t\treturn min_distance.at(target);\n\t};\n\n\tinline double Graph::dijkstra(int source, int target)\n\t{\n\t\tstd::vector<int> node_path;\n\t\treturn  dijkstra(source, target, node_path);\n\t};\n\n\n\t/* TO BE REMOVED? This apply just for directional graph */\n\n\tinline int Graph::edge_source(int i)\n\t{\n\t\treturn edges_(i, 0);\n\t};\n\n\tinline int Graph::edge_target(int i) \n\t{\n\t\treturn edges_(i, 1);\n\t};\n\n\tinline void Graph::swap_edge(int i) \n\t{\n\t\tint temp = edges_(i,0);\n\t\tedges_(i,0) = edges_(i,1);\n\t\tedges_(i,1) = temp;\n\t};\n\n\n\n\n\n\n\t/*\n\t * PRIVATE FUNCTIONS:\n\t */\n\n\t//https://stackoverflow.com/a/46303314/2562693\n\tvoid Graph::removeRow(Eigen::MatrixXd& matrix, unsigned int rowToRemove)\n\t{\n\t\tunsigned int numRows = matrix.rows()-1;\n\t\tunsigned int numCols = matrix.cols();\n\n\t\tif( rowToRemove < numRows )\n\t\t\tmatrix.block(rowToRemove,0,numRows-rowToRemove,numCols) = matrix.bottomRows(numRows-rowToRemove);\n\n\t\tmatrix.conservativeResize(numRows,numCols);\n\t};\n\n\tvoid Graph::removeRow(Eigen::MatrixXi& matrix, unsigned int rowToRemove)\n\t{\n\t\tunsigned int numRows = matrix.rows()-1;\n\t\tunsigned int numCols = matrix.cols();\n\n\t\tif( rowToRemove < numRows )\n\t\t\tmatrix.block(rowToRemove,0,numRows-rowToRemove,numCols) = matrix.bottomRows(numRows-rowToRemove);\n\n\t\tmatrix.conservativeResize(numRows,numCols);\n\t};\n\n\t//https://stackoverflow.com/a/32842128/2562693\n\tvoid Graph::removeDuplicates(std::vector<std::pair<int, int>>& v)\n\t{\n\t\t\n\t\t//Normalize == sort the pair members\n\t\tfor(auto& p : v){\n\t\t\tint x = std::max(p.first, p.second), y = std::min(p.first, p.second);\n\t\t\tp.first = x; p.second = y;\n\t\t}\n\n\t\t//Sort the pairs\n\t\tstd::sort(v.begin(), v.end());\n\n\t\t//Unique the vector\n\t\tauto last = unique(v.begin(), v.end() );\n\t\tv.erase(last, v.end());\n\t};\n\n\tbool Graph::is_element_in_vector(int a, std::vector<int> & A)\n\t{\n\t\tauto it = std::find(A.begin(), A.end(), a);\n\t\treturn it != A.end();\n\t}\n\n\t// used for checking connectivity:\n\t//\n\t// for reference, see Kosaraju's algorithm (https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm)\n\t//\n\t// from: https://www.geeksforgeeks.org/graph-implementation-using-stl-for-competitive-programming-set-1-dfs-of-unweighted-and-undirected/\n\t// A utility function to do DFS of graph \n\t// recursively from a given vertex u. \n\tvoid Graph::DFSUtil(int u, std::vector< std::vector<int> > adj, std::vector<bool> &visited) \n\t{ \n\t\tvisited[u] = true;\n\t\tfor (int i=0; i<adj[u].size(); i++) \n\t\t\tif (visited[adj[u][i]] == false) \n\t\t\t\tDFSUtil(adj[u][i], adj, visited); \n\t};\n\n\t// used for finding articulation points (1-node-connectivity):\n\t//\n\t// for reference, see Tarjan’s algorithm\n\t//\n\t// from: https://www.geeksforgeeks.org/articulation-points-or-cut-vertices-in-a-graph/\n\t// A recursive function that find articulation points using DFS traversal \n\t// u --> The vertex to be visited next \n\t// visited[] --> keeps tract of visited vertices \n\t// disc[] --> Stores discovery times of visited vertices \n\t// parent[] --> Stores parent vertices in DFS tree \n\t// ap[] --> Store articulation points \n\tvoid Graph::APUtil(int u, std::vector<bool> & visited, int disc[],  \n\t\t\t\t\t\t\t\t\t\tint low[], std::vector<int> & parent, std::vector<bool> & ap) \n\t{ \n\t\t// A static variable is used for simplicity, we can avoid use of static \n\t\t// variable by passing a pointer. \n\t\tstatic int time = 0; \n\n\t\t// Count of children in DFS Tree \n\t\tint children = 0; \n\n\t\t// Mark the current node as visited \n\t\tvisited[u] = true; \n\n\t\t// Initialize discovery time and low value \n\t\tdisc[u] = low[u] = ++time; \n\n\t\tfor (int i=0; i<adjacency_list_[u].size(); i++) { \n\t\t\tint v = adjacency_list_[u][i];  // v is current adjacent of u \n\n\t\t\t// If v is not visited yet, then make it a child of u \n\t\t\t// in DFS tree and recur for it \n\t\t\tif (!visited[v]) { \n\t\t\t\tchildren++; \n\t\t\t\tparent[v] = u; \n\t\t\t\tAPUtil(v, visited, disc, low, parent, ap); \n\n\t\t\t\t// Check if the subtree rooted with v has a connection to \n\t\t\t\t// one of the ancestors of u \n\t\t\t\tlow[u]  = std::min(low[u], low[v]); \n\n\t\t\t\t// u is an articulation point in following cases \n\n\t\t\t\t// (1) u is root of DFS tree and has two or more chilren. \n\t\t\t\tif (parent[u] == -1 && children > 1) \n\t\t\t\tap[u] = true; \n\n\t\t\t\t// (2) If u is not root and low value of one of its child is more \n\t\t\t\t// than discovery value of u. \n\t\t\t\tif (parent[u] != -1 && low[v] >= disc[u]) \n\t\t\t\tap[u] = true; \n\t\t\t} \n\n\t\t\t// Update low value of u for parent function calls. \n\t\t\telse if (v != parent[u]) \n\t\t\t\tlow[u]  = std::min(low[u], disc[v]); \n\t\t} \n\t};\n\n\t// used for finding articulation points (1-node-connectivity):\n\t//\n\t// for reference, see Tarjan’s algorithm\n\t//\n\t// from: https://www.geeksforgeeks.org/bridge-in-a-graph/\n\t// A recursive function that finds and prints bridges using \n\t// DFS traversal \n\t// u --> The vertex to be visited next \n\t// visited[] --> keeps tract of visited vertices \n\t// disc[] --> Stores discovery times of visited vertices \n\t// parent[] --> Stores parent vertices in DFS tree\n\tvoid Graph::bridgeUtil(int u, \n\t\t\t\t\t\tstd::vector<bool> & visited, \n\t\t\t\t\t\tint disc[], \n\t\t\t\t\t\tint low[], \n\t\t\t\t\t\tstd::vector<int> & parent, \n\t\t\t\t\t\tstd::vector<int> & bridges) \n\t{ \n\t\t// A static variable is used for simplicity, we can  \n\t\t// avoid use of static variable by passing a pointer. \n\t\tstatic int time = 0; \n\t\n\t\t// Mark the current node as visited \n\t\tvisited[u] = true; \n\t\n\t\t// Initialize discovery time and low value \n\t\tdisc[u] = low[u] = ++time; \n\t\n\t\t// Go through all vertices aadjacent to this \n\t\tfor (int i=0; i<adjacency_list_[u].size(); i++) { \n\t\t\t\n\t\t\tint v = adjacency_list_[u][i];\n\n\t\t\t// If v is not visited yet, then recur for it \n\t\t\tif (!visited[v]) { \n\t\t\t\tparent[v] = u;\n\n\t\t\t\tbridgeUtil(v, visited, disc, low, parent, bridges); \n\t\n\t\t\t\t// Check if the subtree rooted with v has a  \n\t\t\t\t// connection to one of the ancestors of u \n\t\t\t\tlow[u]  = std::min(low[u], low[v]); \n\t\n\t\t\t\tif (low[v] > disc[u]) {\n\t\t\t\t\tbridges.push_back(adjacency_edge_list_[u][i]);\n\t\t\t\t}\n\t\t\t\t\t\n\n\t\t\t\t// If the lowest vertex reachable from subtree  \n\t\t\t\t// under v is  below u in DFS tree, then u-v  \n\t\t\t\t// is a bridge \n\t\t\t\tif (low[v] > disc[u] && opts_.verbose) \n\t\t\t\tstd::cout << \"Bridge at: \" << u << \" \" << v << std::endl;\n\t\t\t} \n\t\n\t\t\t// Update low value of u for parent function calls. \n\t\t\telse if (v != parent[u]) \n\t\t\t\tlow[u]  = std::min(low[u], disc[v]); \n\t\t}\n\t};\n\n\n};\n\n\n\n#endif\n", "meta": {"hexsha": "4f1ae7870eef0f766e11297846d29ca7f9e84d7b", "size": 37851, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/libGraphCpp/graph.hpp", "max_stars_repo_name": "rFalque/libGraphCpp", "max_stars_repo_head_hexsha": "a01a13496f683325f45a8ec8e72390cbe8624ace", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-06-30T13:10:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T03:17:50.000Z", "max_issues_repo_path": "include/libGraphCpp/graph.hpp", "max_issues_repo_name": "rFalque/libGraphCpp", "max_issues_repo_head_hexsha": "a01a13496f683325f45a8ec8e72390cbe8624ace", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/libGraphCpp/graph.hpp", "max_forks_repo_name": "rFalque/libGraphCpp", "max_forks_repo_head_hexsha": "a01a13496f683325f45a8ec8e72390cbe8624ace", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4116182573, "max_line_length": 146, "alphanum_fraction": 0.6536947505, "num_tokens": 10588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6224593171945417, "lm_q1q2_score": 0.443335559085352}}
{"text": "/**\n* \\file auxiliaryFunctions.cpp\n* \\brief functions for the module auxiliaryFunctions\n* \\author Guillaume St-Onge\n* \\version 1.0\n* \\date 08/11/2017\n*/\n\n#include \"auxiliaryFunctions.hpp\"\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/discrete_distribution.hpp>\n\nusing namespace std;\n\nnamespace DynNet\n{//start of namespace DynNet\n\ntypedef boost::random::uniform_int_distribution<> uniform_int;\n\n\n/**\n * \\fn void order(edge p_edge)\n * \\brief Assure the edge is in ascending order\n * \\param[in] p_edge \n */\nvoid order(edge& p_edge)\n{\n\tif (p_edge.first > p_edge.second)\n\t{\n\t\tswap(p_edge.first,p_edge.second);\n\t}\n}\n\n/**\n * \\fn vector<edge> input_edgeList(string p_path)\n * \\brief Input the edge list from file\n * \\param[in] p_path path name to the file\n */\nvector<edge> input_edgeList(string p_path)\n{\n\tifstream inStream;\n\tinStream.open(p_path, ios::in);\n\tstring line;\n\n\tvector<edge> edgeList;\n\n\twhile(getline(inStream,line))\n\t{\n\t\tedge e;\n\t\tstringstream line_stream(line);\n\t\tline_stream >> e.first >> e.second;\n\t\t//swap edge to assure ascending order\n\t\torder(e);\n\t\tedgeList.push_back(e);\n\t}\n\tinStream.close();\n\n\treturn edgeList;\n}\n\n/**\n * \\fn pair<double,double> update_estimator(DynamicNetwork& p_net, edge& p_chosenEdge,\n\tpair<double,double>& p_est_param)ble,double>& p_model_param,\n\tedge& p_chosenEdge, double& p_degreeNormalization)\n * \\brief Get likelihood for the new edge and update normalisation.\n * \\param[in] p_net Structure of a network in reconstruction.\n * \\param[in] p_chosenEdge new edge\n * \\param[in] p_est_param Estimated parameter\n */\npair<double,double> update_estimator(DynamicNetwork& p_net, edge& p_chosenEdge,\n\tpair<double,double>& p_est_param)\n{\n\tdouble n = p_net.get_currentDegreeMap().size();\n\tdouble m = p_net.get_currentEdgeList().size();\n\tdouble kavg = 2*m/n;\n\tdouble ksum = kavg*n;\n\tdouble k2avg = p_est_param.first + kavg*kavg;\n\tdouble k2sum = n*k2avg;\n\n\tunordered_map<node, unsigned int> currentDegreeMap = p_net.get_currentDegreeMap();\n\n\t//update parameter according to new node\n\tm += 1;\n\tksum += 2;\n\tif (currentDegreeMap.find(p_chosenEdge.first) != \n\t\tcurrentDegreeMap.end())\n\t{\n\t\tif (currentDegreeMap.find(p_chosenEdge.second) != \n\t\tcurrentDegreeMap.end())\n\t\t{\n\t\t\t//2 old nodes, n stays the same\n\t\t\t//check if self-loop\n\t\t\tif (p_chosenEdge.first == p_chosenEdge.second)\n\t\t\t{\n\t\t\t\tk2sum -= (currentDegreeMap[p_chosenEdge.first]) * (currentDegreeMap[p_chosenEdge.first]);\n\t\t\t\tk2sum += (currentDegreeMap[p_chosenEdge.first] + 2) * (currentDegreeMap[p_chosenEdge.first] + 2);\n\t\t\t\t// k2sum -= pow(currentDegreeMap[p_chosenEdge.first],2.);\n\t\t\t\t// k2sum += pow(currentDegreeMap[p_chosenEdge.first] + 2,2.);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t// \tk2sum -= pow(currentDegreeMap[p_chosenEdge.first],2.);\n\t\t\t// \tk2sum += pow(currentDegreeMap[p_chosenEdge.first] + 1,2.);\n\t\t\t// \tk2sum -= pow(currentDegreeMap[p_chosenEdge.second],2.);\n\t\t\t// \tk2sum += pow(currentDegreeMap[p_chosenEdge.second] + 1,2.);\n\t\t\t\tk2sum -= (currentDegreeMap[p_chosenEdge.first]) * (currentDegreeMap[p_chosenEdge.first]);\n\t\t\t\tk2sum += (currentDegreeMap[p_chosenEdge.first] + 1) * (currentDegreeMap[p_chosenEdge.first] + 1);\n\t\t\t\tk2sum -= (currentDegreeMap[p_chosenEdge.second]) * (currentDegreeMap[p_chosenEdge.second]);\n\t\t\t\tk2sum += (currentDegreeMap[p_chosenEdge.second] + 1) * (currentDegreeMap[p_chosenEdge.second] + 1);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//first is old, second is new\n\t\t\tn += 1;\n\t\t\t// k2sum -= pow(currentDegreeMap[p_chosenEdge.first],2.);\n\t\t\t// k2sum += pow(currentDegreeMap[p_chosenEdge.first] + 1,2.);\n\t\t\tk2sum -= (currentDegreeMap[p_chosenEdge.first]) *  (currentDegreeMap[p_chosenEdge.first]);\n\t\t\tk2sum += (currentDegreeMap[p_chosenEdge.first] + 1) * (currentDegreeMap[p_chosenEdge.first] + 1);\n\t\t\tk2sum += 1;\n\t\t}\n\t}\n\telse\n\t{\n\t\t//first is new, second is old\n\t\tn += 1;\n\t\t// k2sum -= pow(currentDegreeMap[p_chosenEdge.second],2.);\n\t\t// k2sum += pow(currentDegreeMap[p_chosenEdge.second] + 1,2.);\n\t\tk2sum -= (currentDegreeMap[p_chosenEdge.second]) * (currentDegreeMap[p_chosenEdge.second]);\n\t\tk2sum += (currentDegreeMap[p_chosenEdge.second] + 1) * (currentDegreeMap[p_chosenEdge.second] + 1);\n\t\tk2sum += 1;\n\t}\n\n\t// pair<double,double> new_est_param(k2sum/n - pow(ksum/n, 2.),(n-2)/(m-1));\n\tpair<double,double> new_est_param(k2sum/n - (ksum/n) * (ksum/n), (n-2)/(m-1));\n\n\treturn new_est_param;\n}\n\t\t\n\n/**\n * \\fn double update_modelLikelihood(DynamicNetwork& p_net, pair<double,\n \tdouble>& p_model_param,\tedge& p_chosenEdge, double& p_degreeNormalization)\n * \\brief Get likelihood for the new edge and update normalisation.\n * \\param[in] p_net Structure of a network in reconstruction.\n * \\param[in] p_model_param Model parameters\n * \\param[in] p_chosenEdge new edge\n * \\param[in] p_degreeNormalization Normalization factor for probability\n */\ndouble update_modelLikelihood(DynamicNetwork& p_net, \n\tpair<double,double>& p_model_param, edge& p_chosenEdge, \n\tdouble& p_degreeNormalization)\n{\n\tdouble model_likelihood = 1.;\n\tif (p_net.get_currentDegreeMap().find(p_chosenEdge.first) != \n\t\tp_net.get_currentDegreeMap().end())\n\t{\n\t\tif (p_net.get_currentDegreeMap().find(p_chosenEdge.second) != \n\t\tp_net.get_currentDegreeMap().end())\n\t\t{\n\t\t\t//2 old nodes\n\t\t\tdouble k1 = p_net.get_currentDegreeMap().at(p_chosenEdge.first);\n\t\t\tdouble k2 = p_net.get_currentDegreeMap().at(p_chosenEdge.second);\n\t\t\tmodel_likelihood *= (1 - p_model_param.second)*pow(k1*k2,\n\t\t\t\tp_model_param.first)/pow(p_degreeNormalization,2.);\n\t\t\t//check if self-loop\n\t\t\tif (p_chosenEdge.first == p_chosenEdge.second)\n\t\t\t{\n\t\t\t\tp_degreeNormalization -= pow(k1,p_model_param.first);\n\t\t\t\tp_degreeNormalization += pow(k1+2,p_model_param.first);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tp_degreeNormalization -= pow(k1,p_model_param.first);\n\t\t\t\tp_degreeNormalization -= pow(k2,p_model_param.first);\n\t\t\t\tp_degreeNormalization += pow(k1+1,p_model_param.first);\n\t\t\t\tp_degreeNormalization += pow(k2+1,p_model_param.first);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//first is old, second is new\n\t\t\tdouble k1 = p_net.get_currentDegreeMap().at(p_chosenEdge.first);\n\t\t\tmodel_likelihood *= p_model_param.second*pow(k1,\n\t\t\t\tp_model_param.first)/p_degreeNormalization;\n\t\t\tp_degreeNormalization -= pow(k1,p_model_param.first);\n\t\t\tp_degreeNormalization += pow(k1+1,p_model_param.first)+1;\n\t\t}\n\t}\n\telse\n\t{\n\t\t//first is new, second is old\n\t\tdouble k2 = p_net.get_currentDegreeMap().at(p_chosenEdge.second);\n\t\tmodel_likelihood *= p_model_param.second*pow(k2,\n\t\t\tp_model_param.first)/p_degreeNormalization;\n\t\tp_degreeNormalization -= pow(k2,p_model_param.first);\n\t\tp_degreeNormalization += pow(k2+1,p_model_param.first)+1;\n\t}\n\n\treturn model_likelihood;\n}\n\n/**\n * \\fn void add_edge(DynamicNetwork& p_net, pair<double,double>& p_model_param,\n\tpair<double,double>& p_target_param, pair<double,double>& p_est_param, \n\tpair<double,double>& p_bias_param, RNGType& gen)\n * \\brief Add a new edge to the network following to the growth model.\n * \\param[in] p_net Structure of a network in reconstruction.\n * \\param[in] p_model_param Model parameters\n * \\param[in] p_target_param Target parameter for bias\n * \\param[in] p_est_param Estimated parameter for bias\n * \\param[in] p_bias_param Tunable parameter for bias\n * \\param[in] p_degreeNormalization Normalization factor for probability\n * \\param[in] gen Random number generator.\n */\nvoid add_edge(DynamicNetwork& p_net, pair<double,double>& p_model_param,\n\tpair<double,double>& p_target_param, pair<double,double>& p_est_param, \n\tpair<double,double>& p_bias_param, double& p_degreeNormalization,\n\tRNGType& gen)\n{\n\t//this add_edge method is used with important_sampling\n\n\tedgeSet reachableEdgeSet = p_net.get_reachableEdgeSet();\n\tunordered_map<unsigned int, edge> indexMap;\n\tvector<double> weightList(reachableEdgeSet.size(), 0);\n\t// vector<double> weightList;\n\tdouble weightNorm = 0.;\n\tbool oldSeed = false;\n\tbool oldTarget = false;\n\n\t//get weights\n\tunsigned int index = 0;\n\tfor (auto iter = reachableEdgeSet.begin(); \n\t\titer != reachableEdgeSet.end(); ++iter)\n\t{\n\t\tindexMap[index] = *iter;\n\n\t\tdouble weight = p_net.get_remainingEdgeMap().at(*iter); //bias for multiple edges\n\t\tedge possibleEdge = *iter;\n\t\tpair<double,double> new_est_param = update_estimator(p_net, possibleEdge, \n\t\t\tp_est_param);\n\t\t// weight *= exp(-p_bias_param.first*(new_est_param.second \n\t\t// \t- p_target_param.second));\n\t\t// weight *= exp(-p_bias_param.second*(new_est_param.first\n\t\t// \t- p_target_param.first));\n\t\tweight *= exp(-p_bias_param.first*(new_est_param.second- p_target_param.second) * (new_est_param.second- p_target_param.second));  // density\n\t\tweight *= exp(-p_bias_param.second*(new_est_param.first- p_target_param.first) * (new_est_param.first- p_target_param.first));  // variance\n\n\t\t// weightList.push_back(weight);\n\n\t\tweightList[index] = weight;\n\t\tweightNorm += weight;\n\n\t\tindex += 1;\n\t}\n\n\t//Get a new random edge\n\tboost::random::discrete_distribution<int> edgeDist(weightList.begin(), weightList.end());\n\tunsigned int newEdgeIndex = edgeDist(gen);\n\tedge chosenEdge = indexMap[newEdgeIndex];\n\n\t//determine the model likelihood\n\tdouble model_likelihood = update_modelLikelihood(p_net, p_model_param, chosenEdge, \n\t\tp_degreeNormalization);\n\n\t//update the estimator\n\tp_est_param = update_estimator(p_net, chosenEdge, p_est_param);\n\t\n\t// cout << p_est_param.first << \" \" << p_est_param.second << \"\\n\";\n\n\t//add the edge with according probability ratio (model_likelihood/bias_prob)\n\tdouble ratio = model_likelihood*weightNorm/(weightList[newEdgeIndex]);\n\t//account for multiple edge indistinguishability\n\tratio *= p_net.get_remainingEdgeMap().at(chosenEdge);\n\n\tp_net.add(chosenEdge, ratio);\n}\n\n/**\n * \\fn void add_edge(DynamicNetwork& p_net, pair<double,double>& p_param,\n\tdouble& p_degreeNormalization, RNGType& gen)\n * \\brief Add a new edge to the network following to the growth model.\n * \\param[in] p_net Structure of a network in reconstruction.\n * \\param[in] p_param Model parameters\n * \\param[in] p_degreeNormalization Normalization factor for probability\n * \\param[in] gen Random number generator.\n */\nvoid add_edge(DynamicNetwork& p_net, pair<double,double>& p_param,\n\tdouble& p_degreeNormalization, RNGType& gen)\n{\n\tedgeSet reachableEdgeSet = p_net.get_reachableEdgeSet();\n\tuniform_int indexDist(0, p_net.get_reachableEdge()-1);\n\n\t// cout << reachableEdgeSet.size() << \" \" << p_net.get_reachableEdge() << endl;\n\tint index = indexDist(gen);\n\n\tauto iter = reachableEdgeSet.begin();\n\t//count multiple edge with remaining map\n\twhile (index >= 0)\n\t{\n\t\tunsigned int remaining = p_net.get_remainingEdgeMap().at(*iter);\n\t\tindex -= remaining;\n\t\tif (index >= 0)\n\t\t{\n\t\t\titer++ ;\n\t\t}\n\t}\n\n\tbool oldSeed = false;\n\tbool oldTarget = false;\n\tif (p_net.get_currentDegreeMap().find(iter->first) != \n\t\tp_net.get_currentDegreeMap().end())\n\t{\n\t\toldSeed = true;\n\t}\n\telse\n\t{\n\t\toldSeed = false;\n\t}\n\tif (p_net.get_currentDegreeMap().find(iter->second) != \n\t\tp_net.get_currentDegreeMap().end())\n\t{\n\t\toldTarget = true;\n\t}\n\telse\n\t{\n\t\toldTarget = false;\n\t}\n\n\tdouble weight = p_net.get_reachableEdge();\n\tif (oldSeed)\n\t{\n\t\tif (oldTarget)\n\t\t{\n\t\t\tdouble k1 = p_net.get_currentDegreeMap().at(iter->first);\n\t\t\tdouble k2 = p_net.get_currentDegreeMap().at(iter->second);\n\t\t\tweight *= (1- p_param.second)/pow(p_degreeNormalization,2.);\n\t\t\tweight *= pow(k1, p_param.first);\n\t\t\tweight *= pow(k2, p_param.first);\n\t\t\tif (iter->second == iter->first)\t\n\t\t\t{\n\t\t\t\tp_degreeNormalization -= pow(k1, p_param.first);\n\t\t\t\tp_degreeNormalization += pow(k1+2, p_param.first);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tp_degreeNormalization -= pow(k1, p_param.first);\n\t\t\t\tp_degreeNormalization -= pow(k2, p_param.first);\n\t\t\t\tp_degreeNormalization += pow(k1+1., p_param.first);\n\t\t\t\tp_degreeNormalization += pow(k2+1., p_param.first);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble k1 = p_net.get_currentDegreeMap().at(iter->first);\n\t\t\tweight *= p_param.second/p_degreeNormalization;\n\t\t\tweight *= pow(k1, p_param.first);\n\t\t\tp_degreeNormalization -= pow(k1, p_param.first);\n\t\t\tp_degreeNormalization += pow(k1+1., p_param.first) + 1;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (oldTarget)\n\t\t{\n\t\t\tdouble k2 = p_net.get_currentDegreeMap().at(iter->second);\n\t\t\tweight *= p_param.second/p_degreeNormalization;\n\t\t\tweight *= pow(k2, p_param.first);\n\t\t\t// weight *= p_net.get_remainingEdgeMap().at(*iter);//bias to account\n\t\t\tp_degreeNormalization -= pow(k2, p_param.first);\n\t\t\tp_degreeNormalization += pow(k2+1., p_param.first) + 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//impossible to have 2 new nodes\n\t\t\tcout << \"ERROR : two new nodes\" << endl;\n\t\t}\n\t}\n\n\tp_net.add(*iter, weight);\n}\n\n/**\n * \\fn void update_meanMarginal(DynamicNetwork& p_net, unordered_map< edge, \n \tvector<double>, boost::hash<edge> > p_meanMarginalMap, \n \tdouble meanLogweight, double& p_effectiveWeightSum)\n * \\brief Update mean marginal evaluation from a network sample.\n * \\param[in] p_net Structure of a network in reconstruction.\n * \\param[in] p_meanMarginalMap Map of the mean marginal.\n * \\param[in] p_meanLogweight Mean value of the logweight.\n * \\param[in] p_effectiveWeightSum Normalization value to update.\n */\nvoid update_meanMarginal(DynamicNetwork& p_net, unordered_map< edge, \n\tvector<double>, boost::hash<edge> >& p_meanMarginalMap, \n\tdouble meanLogweight, double& p_effectiveWeightSum)\n{\n\tedgeIntMap edgeCountMap;\n\tdouble effectiveWeight = exp(p_net.get_logweight()-meanLogweight);\n\tdouble t = 0.;\n\tfor (auto iter = p_net.get_currentEdgeList().begin(); \n\t\titer != p_net.get_currentEdgeList().end(); ++iter)\n\t{\n\t\tp_meanMarginalMap[*iter][edgeCountMap[*iter]] += t*effectiveWeight;\n\t\tedgeCountMap[*iter] += 1;\n\t\tt += 1.;\n\t}\n\tp_effectiveWeightSum += effectiveWeight;\n}\n\n/**\n * \\fn bool update_meanMarginal(DynamicNetwork& p_net, unordered_map< edge, \n \tvector<double>, boost::hash<edge> > p_meanMarginalMap,\n \tdouble meanLogweight, double& p_effectiveWeightSum, double p_rtol)\n * \\brief Update mean marginal evaluation from a network sample.\n * \\param[in] p_net Structure of a network in reconstruction.\n * \\param[in] p_meanMarginalMap Map of the mean marginal.\n * \\param[in] p_meanLogweight Mean value of the logweight.\n * \\param[in] p_effectiveWeightSum Normalization value to update.\n * \\param[in] p_rtol Tolerance for convergence.\n */\nbool update_meanMarginal(DynamicNetwork& p_net, unordered_map< edge, \n\tvector<double>, boost::hash<edge> >& p_meanMarginalMap, \n\tdouble meanLogweight, double& p_effectiveWeightSum, double p_rtol,\n\tunsigned int sampleSize)\n{\n\tedgeIntMap edgeCountMap;\n\tbool converged = true;\n\tdouble effectiveWeight = exp(p_net.get_logweight()-meanLogweight);\n\tp_effectiveWeightSum += effectiveWeight;\n\tdouble t = 0.;\n\tfor (auto iter = p_net.get_currentEdgeList().begin(); \n\t\titer != p_net.get_currentEdgeList().end(); ++iter)\n\t{\n\t\tp_meanMarginalMap[*iter][edgeCountMap[*iter]] += t*effectiveWeight;\n\t\tdouble avg_t = (p_meanMarginalMap[*iter][edgeCountMap[*iter]]\n\t\t\t/p_effectiveWeightSum);\n\t\tif (abs(t-avg_t)/sqrt(sampleSize) > p_rtol) //comportement moyen\n\t\t{\n\t\t\tconverged = false;\n\t\t}\n\t\tedgeCountMap[*iter] += 1;\n\t\tt += 1.;\n\t}\n\n\treturn converged;\n}\n\n}//end of namespace DynNet", "meta": {"hexsha": "8fac2d0ffc0ff3f60f270e4e94e4c22a143af0ba", "size": 14972, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/bins/importance_sampling_cpp/lib/auxiliaryFunctions.cpp", "max_stars_repo_name": "junipertcy/network-archaeology", "max_stars_repo_head_hexsha": "7cef0de7a388e8dde812e746d50470d167da8a9b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/bins/importance_sampling_cpp/lib/auxiliaryFunctions.cpp", "max_issues_repo_name": "junipertcy/network-archaeology", "max_issues_repo_head_hexsha": "7cef0de7a388e8dde812e746d50470d167da8a9b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/bins/importance_sampling_cpp/lib/auxiliaryFunctions.cpp", "max_forks_repo_name": "junipertcy/network-archaeology", "max_forks_repo_head_hexsha": "7cef0de7a388e8dde812e746d50470d167da8a9b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1238938053, "max_line_length": 143, "alphanum_fraction": 0.7226823404, "num_tokens": 4161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.44325004036539817}}
{"text": "#include <iostream>\n#include <fstream>\n\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <vector>\n#include <cmath>\n\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\n#include \"TwoChQSz.hpp\"\n\n#ifndef pi\n#define pi 3.141592653589793238462643383279502884197169\n#endif\n\n\n\nbool AeqB(CNRGbasisarray *pAeigCut, int ibl1,int ibl2){\n\n  return (ibl1==ibl2);\n\n}\n\ndouble AtimesB(CNRGbasisarray *pAeig, CNRGbasisarray *pSingleSite, \n\t       int ibl1,int ibl2){\n\n  return((double)ibl1*ibl2);\n\n}\n\n\n\n\nint main (){\n\n  CNRGarray Aeig(2);\n\n  CNRGbasisarray AeigCut(2);\n\n  CNRGbasisarray Abasis(2);\n\n  CNRGbasisarray SingleSite(2);\n\n  // STL vector\n\n  CNRGmatrix Qm1fNQ[2];\n\n  CNRGmatrix MQQp1;\n\n  double U,ed,Gamma1,Gamma2;\n  vector<double> Params;\n  double Lambda;\n  double HalfLambdaFactor;\n  double Dband=1.0;\n  int calcdens;\n\n  double DN=0.0;\n  double TM=0.0;\n  double betabar=0.727;\n  double Temp=0.0;\n  double Sus=0.0;\n  //vector<double> SuscepChain;\n  char arqSus[32],arqname[32];\n\n\n\n  double chi_m1,chi_N[2];\n  double daux[4];\n\n  int Nsites,Nsitesmax=2;\n\n  int Ncutoff=700;\n  int UpdateBefCut=0;\n  int auxIn;\n\n  // outstream\n  ofstream OutFile;\n  // instream\n  ifstream InFile;\n\n\n  int ii,jj,i1,i2;\n\n  // STL iterator:\n\n  vector<double>::iterator diter;\n\n  // Test\n  CNRGmatrix HN;\n\n  HN.CheckForMatEl=AeqB;\n  HN.CalcMatEl=AtimesB;\n  if (HN.CheckForMatEl(&Abasis,2,2)) cout << \"TRUE!\" << endl;\n  else cout << \"FALSE!\" << endl;\n  cout << HN.CalcMatEl(&Abasis,&SingleSite,3,4) << endl;\n  exit(0);\n\n\n  ///            ///\n  /// Begin code ///\n  ///            ///\n  U=0.5;\n  ed=-0.5*U;\n  Gamma1=0.0282691;\n  Gamma2=0.0;\n  Lambda=2.5;\n  \n  // Steps: Input parameters\n  InFile.open(\"nrg_input_TwoChAnderson.dat\");\n  if (InFile.is_open())\n    {\n      InFile >> Nsitesmax;\n      InFile >> Ncutoff;\n      InFile >> U;\n      InFile >> Gamma1;\n      InFile >> Gamma2;\n      InFile >> ed;\n      InFile >> Lambda;\n      InFile >> Dband;\n      InFile >> auxIn;\n      InFile >> UpdateBefCut;\n      InFile >> calcdens;\n    }\n  else cout << \"can't open nrg_input_TwoChAnderson.dat\" << endl;\n\n  InFile.close();\n\n\n  ///////////////////////////\n  ///////////////////////////\n\n  if (calcdens==2)\n    {\n      //SuscepChain.clear();\n      strcpy(arqSus,\"SuscepImp_25_726.dat\");\n  \n      strcpy(arqname,\"SuscepChain.dat\");\n      InFile.open(arqname);\n      if (InFile.fail())\n\t{\n\t  cout << \"Can't find \" << arqname << endl;\n\t  strcpy(arqSus,\"SuscepChain.dat\");\n\t  calcdens=3;\n\t}\n///////////////////////\n//       else\n// \t{\n// \t  while (!InFile.eof())\n// \t    {\n// \t      InFile >> Temp >> daux[0] >> daux[0] >> Sus;\n// \t      SuscepChain.push_back(Sus);\n// \t    }\n// \t  SuscepChain.pop_back();\n// \t  if (SuscepChain.size()<Nsitesmax-1)\n// \t    {\n// \t      cout << \"Nsuscep = \" << SuscepChain.size() << \" Nsitesmax = \" << Nsitesmax << endl;\n// \t      cout << \" Longer SuscepChain needed! Doing it all over...\" << endl;\n// \t      SuscepChain.clear();\n// \t      strcpy(arqSus,\"SuscepChain.dat\");\n// \t      calcdens=3;\n// \t    } \n// \t}\n//       InFile.close();\n//////////////////////////\n     }\n  if (calcdens==3)\n    {\n      strcpy(arqSus,\"SuscepChain.dat\");\n      U=0.0;ed=0.0;Gamma1=0.0;Gamma2=0.0;\n    }\n\n  ///////////////////////////\n  ///////////////////////////\n\n  HalfLambdaFactor=0.5*(1.0+(1.0/Lambda));\n  chi_m1=sqrt(2.0*Gamma1/pi)/(sqrt(Lambda)*HalfLambdaFactor);\n\n  double U_tilde=0.5*U/HalfLambdaFactor;\n  double ed_tilde=ed/HalfLambdaFactor;\n  double Gamma1_tilde=Gamma1*(2.0/pi)/(HalfLambdaFactor*HalfLambdaFactor);\n  double Gamma2_tilde=Gamma2*(2.0/pi)/(HalfLambdaFactor*HalfLambdaFactor);\n\n\n  OutFile.open(\"NRG_in.txt\");\n  OutFile << \"Begin NRG 2-ch calculation\" << endl;\n  OutFile << \" Nsitesmax    = \" << Nsitesmax-1 << endl;\n  OutFile << \" Ncutoff      = \" << Ncutoff << endl;\n  OutFile << \" U            = \" << U << endl;\n  OutFile << \" Gamma1        = \" << Gamma1 << endl;\n  OutFile << \" Gamma2        = \" << Gamma2 << endl;\n  OutFile << \" ed           = \" << ed << endl;\n  OutFile << \" Lambda       = \" << Lambda << endl;\n  OutFile << \" Dband        = \" << Dband << endl;\n  OutFile << \" UpdateBefCut = \" << UpdateBefCut << endl;\n  OutFile << \" calcdens     = \" << calcdens << endl;\n  OutFile << \"=================================\" << endl;\n  OutFile << \"U~ = \" << U_tilde << endl;\n  OutFile << \"ed~ = \" <<  ed_tilde << endl;\n  OutFile << \"Gamma1~ = \" <<  Gamma1_tilde<< endl;\n  OutFile << \"Gamma2~ = \" <<  Gamma2_tilde<< endl;\n  OutFile << \"=================================\" << endl;\n  OutFile.close();\n\n\n\n  // Define H0 (impurity + 1s site)\n  // Output:\n  //       Aeig,\n  //       fd_{1sigma} and fd_{2sigma} matrix elements\n  //\n\n  // Set single site (use pointers in the subroutines!!)\n\n  TwoChQSz_SetSingleSite(&SingleSite);\n\n\n  Params.push_back(U_tilde/sqrt(Lambda));\n  Params.push_back(ed_tilde/sqrt(Lambda));\n  Params.push_back(sqrt(Gamma1_tilde/Lambda));\n  Params.push_back(sqrt(Gamma2_tilde/Lambda));\n\n  Nsites=0;\n  DN=HalfLambdaFactor*pow(Lambda,(-(Nsites-1)/2.0) );\n  TM=DN/betabar;\n  cout << \"DN = \" << DN << \"TM = \" << TM << endl;\n\n  //TwoChQSz_SetH0Anderson(Params,&SingleSite,&Aeig,Qm1fNQ);\n  TwoChQSz_SetH0Anderson(Params,&SingleSite,&Aeig,&Abasis);\n\n  Aeig.PrintEn();\n\n  // Calculate Susceptibility\n\n  if ( (calcdens==2)||(calcdens==3) )\n    {\n      TM=DN/betabar;\n      Params.clear();\n      Params.push_back(betabar);\n      Sus=CalcSuscep(Params,&Aeig,1,false);\n      double Sus0=0.0;\n      int nlines=0;\n      if (calcdens==2)\n\t{\n\t  InFile.open(\"SuscepChain.dat\");\n\t  InFile.clear(); \n\t  InFile.seekg(0, ios::beg); // rewind\n\t  if (InFile.fail())\n\t    {\n\t      cout << \"Can't open  SuscepChain.dat\"<< endl;\n\t    }\n\t  else\n\t    {\n\t      while ( (!InFile.eof())&&(nlines<=Nsites) ) \n\t\t{\n\t\t  InFile >> daux[0] >> daux[0] >> daux[0] >> Sus0;\n\t\t  nlines++;\n\t\t}\n\t    }\n\t  InFile.close();\n\t}\n      //if (calcdens==2) Sus0=SuscepChain[Nsites];\n      else Sus-=1.0/8.0; // exclude dot site in the chain.\n      if (Nsites==0) OutFile.open(arqSus);\n      else OutFile.open(arqSus,ofstream::app);\n      OutFile.precision(20);\n      OutFile << scientific << TM << \" \" << Sus << \" \" << Sus0 << \" \" << Sus-Sus0 << endl;\n      OutFile.close();\n\n    }\n\n  TwoChQSz_UpdateQm1fQ(&SingleSite,&Aeig,&Abasis,Qm1fNQ);\n\n  // Check Matrix\n  for (int ich=1;ich<=2;ich++)\n    {\n      cout << \" Printing Qm1fQ channel: \" << ich << endl;\n      for (int ibl=0; ibl<Qm1fNQ[ich-1].NumMatBlocks();ibl++)\n\t{\n\t  Qm1fNQ[ich-1].PrintMatBlock(ibl);\n\t}\n    }\n\n  // Loop on Nsites: start from Nsites=0 (imp+1)\n  //\n\n  Nsites=1;\n  while (Nsites<=Nsitesmax)\n    {\n\n      DN=HalfLambdaFactor*pow(Lambda,(-(Nsites-1)/2.0) );\n      TM=DN/betabar;\n      cout << \"DN = \" << DN << \"TM = \" << TM << endl;\n\n      // 0 - Update chi_N, eps_N\n\n      daux[0]=(double)( 1.0-pow(Lambda,(-Nsites)) );\n      daux[1]=(double)sqrt( 1.0-pow(Lambda,-(2*Nsites-1)) );\n      daux[2]=(double)sqrt( 1.0-pow(Lambda,-(2*Nsites+1)) );  \n      daux[3]=0.5*(1.0+(1.0/Lambda))*(double)sqrt(Lambda);\n\n      chi_N[0]=daux[0]/(daux[1]*daux[2]);\n      chi_N[1]=daux[0]/(daux[1]*daux[2]);\n\n      cout << \"chi_N = \" << chi_N[0] << \"  \" << chi_N[1] << endl;\n\n\n      cout << \"Nsites = \" << Nsites << endl;\n      cout << \"BEG Eig Nshell = \" << Aeig.Nshell << endl;\n\n      // 1 - Eliminate states and Build Abasis\n\n      cout << \"Cutting states...\" << endl;\n      AeigCut.CNRGbasisarray::ClearAll();\n      AeigCut=CutStates(&Aeig, Ncutoff);\n\n      cout << \"... done cutting states.\" << endl;\n\n      // Calculate new matrix elements using the CUT basis:\n      // update Qm1fNQ, Qm1cdQ, etc.\n\n      if ( (UpdateBefCut==0)&&(Nsites>1) )\n\t{\n\t  cout << \"Updating matrices after cutting... \" << endl;    \n\t  TwoChQSz_UpdateMatrixAfterCutting(&SingleSite,\n\t\t\t\t\t    &AeigCut, &Abasis, Qm1fNQ, &MQQp1);\n\t  cout << \"... done updating matrices. \" << endl;\n\t}\n\n\n\n      //Q1Q2Sz_BuildBasis(&AeigCut,&Abasis,&SingleSite,UpdateBefCut); \n      // doesnt work\n      QSz_BuildBasis(&AeigCut,&Abasis,&SingleSite,UpdateBefCut);\n\n\n      cout << \"No blocks = \" << Abasis.NumBlocks() << endl;\n      \n      cout << \"No states = \" << Abasis.Nstates() << endl;\n\n      //Abasis.PrintAll();\n\n\n      // 2 - Build and diagonalize H_N+1\n\n      Params.clear();\n      Params.push_back(chi_N[0]);\n      Params.push_back(chi_N[1]);\n      Params.push_back(Lambda);\n\n      cout << \"Diagonalizing HN... \" << endl;    \n\n      TwoChQSz_DiagHN(Params,&Abasis,&SingleSite,Qm1fNQ,&Aeig);\n\n      Aeig.PrintEn();\n\n      cout << \"..done diagonalizing HN. \" << endl;    \n\n      // 3 - Update Qm1f1NQ, Qm1f2Q, Qm1cdQ, etc.\n\n      if ( (UpdateBefCut==1)&&(Nsites<Nsitesmax) )\n\t{\n\t  cout << \"Updating matrices before cutting... \" << endl;\n\t  TwoChQSz_UpdateQm1fQ(&SingleSite,&Aeig,&Abasis,Qm1fNQ);\n\t  cout << \"... done updating matrices. \" << endl;\n\n\t}\n\n\n      // Calculate Susceptibility\n\n      if ( (calcdens==2)||(calcdens==3) )\n\t{\n\t  TM=DN/betabar;\n\t  Params.clear();\n\t  Params.push_back(betabar);\n\t  Sus=CalcSuscep(Params,&Aeig,1,false);\n\t  double Sus0=0.0;\n\t  int nlines=0;\n\t  // Gets SuscepChain iteration by iteration\n\t  if (calcdens==2)\n\t    {\n\t      InFile.open(\"SuscepChain.dat\");\n\t      InFile.clear(); \n\t      InFile.seekg(0, ios::beg); // rewind\n\t      if (InFile.fail())\n\t\t{\n\t\t  cout << \"Can't find \" << arqname << endl;\n\t\t}\n\t      else\n\t\t{\n\t\t  while ( (!InFile.eof())&&(nlines<=Nsites) ) \n\t\t    {\n\t\t      InFile >> daux[0] >> daux[0] >> daux[0] >> Sus0;\n\t\t      nlines++;\n\t\t    }\n\t\t}\n\t      InFile.close();\n\t    }\n\t  //if (calcdens==2) Sus0=SuscepChain[Nsites];\n\t  else Sus-=1.0/8.0; // exclude dot site in the chain.\n\n\t  if (Nsites==0) OutFile.open(arqSus);\n\t  else OutFile.open(arqSus,ofstream::app);\n\t  OutFile.precision(20);\n\t  OutFile << scientific << TM << \" \" << Sus << \" \" << Sus0 << \" \" << Sus-Sus0 << endl;\n\t  OutFile.close();\n\t}\n\n      // 4 - Update Nsites\n\n      Nsites++;\n\n    }\n \n  cout << \"=== Calculation Finished! ==== \"<< endl;\n  OutFile.open(\"NRG_end.txt\");\n  OutFile << \"END NRG calculation\" << endl;\n  OutFile.close();\n  \n  cout << \"Calling destructors \" << endl;\n\n}\n//END code\n\n\n", "meta": {"hexsha": "3de07e3228478dd41f74a7a5f8596348aa464120", "size": 10078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TwoChQSz/TwoChQSz.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/TwoChQSz/TwoChQSz.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TwoChQSz/TwoChQSz.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4372093023, "max_line_length": 93, "alphanum_fraction": 0.5633062115, "num_tokens": 3363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.44325004036539806}}
{"text": "// Filename: CirculationModel.cpp\n// Created on 20 Aug 2007 by Boyce Griffith\n\n// Modified 2019, Alexander D. Kaiser\n\n#include \"CirculationModel.h\"\n\n/////////////////////////////// INCLUDES /////////////////////////////////////\n\n#ifndef included_IBAMR_config\n#include <IBAMR_config.h>\n#define included_IBAMR_config\n#endif\n\n#ifndef included_SAMRAI_config\n#include <SAMRAI_config.h>\n#define included_SAMRAI_config\n#endif\n\n// SAMRAI INCLUDES\n#include <CartesianGridGeometry.h>\n#include <CartesianPatchGeometry.h>\n#include <PatchLevel.h>\n#include <SideData.h>\n#include <tbox/RestartManager.h>\n#include <tbox/SAMRAI_MPI.h>\n#include <tbox/Utilities.h>\n\n// C++ STDLIB INCLUDES\n#include <cassert>\n#include <cmath>\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\n/////////////////////////////// STATIC ///////////////////////////////////////\n\n#define MIN_PER_L_T0_SEC_PER_ML 60.0e-3   // 60/1000\n#define MMHG_TO_CGS 1333.22368\n\n\n#define USE_WINDKESSEL\n// If not defined then this only computes fluxes\n// Pressure is set to zero\n// Currently hard coded for upper boundary\n\nnamespace\n{\n    // Name of output file.\n    static const string DATA_FILE_NAME = \"bc_data.m\";\n\n    // constants \n    static const double C_PA         =  4.12; // Pulmonary artery compliance, ml / mmHg \n    static const double C_LA_relaxed =  3*1.6;  // Left atrial compliance ml / mmHg\n    static const double C_PV         = 10.0 - C_LA_relaxed;  // Pulmonary vein compliance, ml / mmHg \n        \n    static const double R_P  = (9.0/5.6) * MIN_PER_L_T0_SEC_PER_ML; // Pulmonary resistance, mmHg / (ml/s)\n    \n    static const double beat_time = 0.8; \n    static const double T_on = .53;   // Pulmonary valve open \n    static const double T_off = .75;  // Pulmonary valve closes  \n    static const double T_peak = T_on + 0.4 * (T_off - T_on); // Peak pulmonary valve flow \n    static const double stroke_volume = 75.0; // ml \n    static const double h = 2.0 * stroke_volume / (T_off - T_on); // Peak flow to get given stroke volume\n    \n    static const bool   atrial_kick_on = true;\n    static const double atrial_kick_center = .44;\n    static const double atrial_kick_time_radius = .09;\n    static const double atrial_kick_time_width = 2.0 * atrial_kick_time_radius;\n    \n    inline double compute_Q_R(double t){\n        // Triangle wave flux \n        \n        double t_reduced = t - beat_time * floor(t/beat_time); \n        \n        if (t_reduced <= T_on)\n            return 0.0; \n        else if (t_reduced <= T_peak)\n            return ( h/(T_peak - T_on) )*t_reduced - (h/(T_peak - T_on)  )*T_on;\n        else if (t_reduced <= T_off)\n            return (-h/(T_off - T_peak))*t_reduced + (h/(T_off -  T_peak))*T_off;\n        else if (t_reduced <= beat_time)\n            return 0.0;\n        \n        TBOX_ERROR(\"Valid time for flux not found.\");\n        return 0.0;\n    }\n    \n    inline double compute_C_LA(double t){\n        \n        if(atrial_kick_on){\n            double t_reduced = t - beat_time * floor(t/beat_time);\n        \n            if (abs(t_reduced - atrial_kick_center) < atrial_kick_time_radius)\n                return C_LA_relaxed * (1.0 - pow(cos(M_PI * (t_reduced - atrial_kick_center) / atrial_kick_time_width),2));\n            else\n                return C_LA_relaxed;\n        }\n        \n        return C_LA_relaxed;\n    }\n    \n    \n    // Backward Euler update for windkessel model.\n    inline void\n    windkessel_be_update(double& Q_R, double& P_PA, double& Q_P, double& P_LA, const double Q_mi, const double t, const double dt)\n    {\n     \n        Q_R = compute_Q_R(t);\n        \n        double C_LA_current = compute_C_LA(t);\n        double C_LA_next    = compute_C_LA(t + dt);\n        \n        double a = C_PA/dt + 1/R_P; \n        double b = -1/R_P; \n        double c = -1/R_P; \n        double d = (C_PV + C_LA_next)/dt + 1/R_P;\n        \n        double rhs[2];  \n        rhs[0] = (C_PA/dt)*P_PA + Q_R;\n        rhs[1] = ((C_PV + C_LA_current)/dt)*P_LA - Q_mi;\n        \n        double det = a*d - b*c; \n        \n        // Closed form linear system solution \n        P_PA = (1/det) * ( d*rhs[0] + -b*rhs[1]);\n        P_LA = (1/det) * (-c*rhs[0] +  a*rhs[1]);\n                \n        Q_P = (1/R_P) * (P_PA - P_LA);\n                \n        return;\n    } // windkessel_be_update\n\n}\n\n/////////////////////////////// PUBLIC ///////////////////////////////////////\n\nCirculationModel::CirculationModel(const string& object_name, double P_PA_0, double P_LA_0, double t, bool register_for_restart)\n    : d_object_name(object_name),\n      d_registered_for_restart(register_for_restart),\n      d_time(t),\n      d_nsrc(1),           // number of sets of variables\n      d_psrc(d_nsrc, 0.0), // pressure\n      d_qsrc(d_nsrc, 0.0), // flux\n      d_srcname(d_nsrc),\n      d_P_PA(P_PA_0),\n      d_P_LA(P_LA_0), \n      d_Q_R(0.0),\n      d_Q_P(0.0), \n      d_Q_mi(0.0),\n      d_bdry_interface_level_number(numeric_limits<int>::max())\n{\n#if !defined(NDEBUG)\n    assert(!object_name.empty());\n#endif\n    if (d_registered_for_restart)\n    {\n        RestartManager::getManager()->registerRestartItem(d_object_name, this);\n    }\n\n    // Initialize object with data read from the input and restart databases.\n    const bool from_restart = RestartManager::getManager()->isFromRestart();\n    if (from_restart)\n    {\n        getFromRestart();\n    }\n    else\n    {\n        //   nsrcs = the number of sources in the valve tester:\n        //           (1) left atrium\n        d_srcname[0] = \"left atrium       \";        \n    }\n    return;\n} // CirculationModel\n\nCirculationModel::~CirculationModel()\n{\n    return;\n} // ~CirculationModel\n\nvoid\nCirculationModel::advanceTimeDependentData(const double dt,\n                                           const double Q_mi)\n{\n    /* \n    // Compute the mean flow rates in the vicinity of the inflow and outflow\n    // boundaries.\n    std::fill(d_qsrc.begin(), d_qsrc.end(), 0.0);\n    for (int ln = 0; ln <= hierarchy->getFinestLevelNumber(); ++ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = hierarchy->getPatchLevel(ln);\n        for (PatchLevel<NDIM>::Iterator p(level); p; p++)\n        {\n            Pointer<Patch<NDIM> > patch = level->getPatch(p());\n            Pointer<CartesianPatchGeometry<NDIM> > pgeom = patch->getPatchGeometry();\n            if (pgeom->getTouchesRegularBoundary())\n            {\n                Pointer<SideData<NDIM, double> > U_data = patch->getPatchData(U_idx);\n                Pointer<SideData<NDIM, double> > wgt_sc_data = patch->getPatchData(wgt_sc_idx);\n                const Box<NDIM>& patch_box = patch->getBox();\n                // const double* const x_lower = pgeom->getXLower();\n                const double* const dx = pgeom->getDx();\n                double dV = 1.0;\n                for (int d = 0; d < NDIM; ++d)\n                {\n                    dV *= dx[d];\n                }\n\n                static const int axis = 2;  // Always z axis here\n                const int side = 1;         // Compute flux at the top only\n\n                const bool is_lower = side == 0;\n                if (pgeom->getTouchesRegularBoundary(axis, side))\n                {\n                    \n                    Vector n;\n                    for (int d = 0; d < NDIM; ++d)\n                    {\n                        n[d] = axis == d ? (is_lower ? -1.0 : +1.0) : 0.0;\n                    }\n                    Box<NDIM> side_box = patch_box;\n                    if (is_lower)\n                    {\n                        side_box.lower(axis) = patch_box.lower(axis);\n                        side_box.upper(axis) = patch_box.lower(axis);\n                    }\n                    else\n                    {\n                        side_box.lower(axis) = patch_box.upper(axis) + 1;\n                        side_box.upper(axis) = patch_box.upper(axis) + 1;\n                    }\n                    for (Box<NDIM>::Iterator b(side_box); b; b++)\n                    {\n                        const Index<NDIM>& i = b();\n                        \n                        // no conditional here, just add the flux in\n                        const SideIndex<NDIM> i_s(i, axis, SideIndex<NDIM>::Lower);\n                        if ((*wgt_sc_data)(i_s) > std::numeric_limits<double>::epsilon())\n                        {\n                            double dA = n[axis] * dV / dx[axis];\n                            d_qsrc[0] += (*U_data)(i_s)*dA;\n                            \n                            // pout << \"adding \" << (*U_data)(i_s)*dA << \"to the flux\\n\";  \n                            \n                        }\n                    }\n                }\n            }\n        }\n    }\n    SAMRAI_MPI::sumReduction(&d_qsrc[0], d_nsrc);\n\n    // pout << \"computed flux = \" << d_qsrc[0] << \"\\n\"; \n    */ \n    \n\n    // The downstream (Atrial) pressure is determined by a zero-d model \n    const double t = d_time;\n\n    double& Q_R  = d_Q_R;\n    double& P_PA = d_P_PA;\n    double& Q_P  = d_Q_P;\n    double& P_LA = d_P_LA;\n\n    // Mitral flux passed in \n    d_Q_mi = Q_mi;\n    \n    windkessel_be_update(Q_R, P_PA, Q_P, P_LA, d_Q_mi, t, dt);\n    \n    // model in mmHg, body force converts \n    d_psrc[0] = d_P_LA;\n\n    // Update the current time.\n    d_time += dt;\n\n    // Output the updated values.\n    const long precision = plog.precision();\n    plog.unsetf(ios_base::showpos);\n    plog.unsetf(ios_base::scientific);\n\n    plog.precision(12);\n\n    plog << \"============================================================================\\n\"\n         << \"Circulation model variables at time \" << d_time << \":\\n\";\n\n    plog << \"P_PA (mmHg)\\t P_LA (mmHg)\\t Q_R (ml/s)\\t Q_P (ml/s)\\t Q_mi (ml/s)\\n\";\n    plog.setf(ios_base::showpos);\n    plog.setf(ios_base::scientific);\n    \n    plog << d_P_PA << \",\\t \" << d_P_LA << \",\\t \" << d_Q_R << \",\\t \" << d_Q_P << \",\\t \" << d_Q_mi << \"\\n\";\n    plog << \"============================================================================\\n\";\n\n    plog.unsetf(ios_base::showpos);\n    plog.unsetf(ios_base::scientific);\n    plog.precision(precision);\n    \n\n    // Write the current state to disk.\n    writeDataFile();\n    return;\n} // advanceTimeDependentData\n\nvoid\nCirculationModel::putToDatabase(Pointer<Database> db)\n{\n    db->putDouble(\"d_time\", d_time);\n    db->putInteger(\"d_nsrc\", d_nsrc);\n    db->putDoubleArray(\"d_qsrc\", &d_qsrc[0], d_nsrc);\n    db->putDoubleArray(\"d_psrc\", &d_psrc[0], d_nsrc);\n    db->putStringArray(\"d_srcname\", &d_srcname[0], d_nsrc);\n    db->putDouble(\"d_P_PA\", d_P_PA);\n    db->putDouble(\"d_P_LA\", d_P_LA);\n    db->putDouble(\"d_Q_R\", d_Q_R);\n    db->putDouble(\"d_Q_P\", d_Q_P);\n    db->putDouble(\"d_Q_mi\", d_Q_mi);\n    db->putInteger(\"d_bdry_interface_level_number\", d_bdry_interface_level_number);\n    return;\n} // putToDatabase\n\n\nvoid CirculationModel::write_plot_code()\n{\n    static const int mpi_root = 0;\n    if (SAMRAI_MPI::getRank() == mpi_root)\n    {\n        ofstream fout(DATA_FILE_NAME.c_str(), ios::app);\n        fout.setf(ios_base::scientific);\n        fout.setf(ios_base::showpos);\n        fout.precision(10);\n        fout << \"];\\n\";  \n        fout << \"fig = figure;\\n\";\n        fout << \"subplot(3,2,1)\\n\";\n        fout << \"plot(bc_vals(:,1), bc_vals(:,2))\\n\";\n        fout << \"title('P_{PA}')\\n\";\n        fout << \"subplot(3,2,2)\\n\";\n        fout << \"plot(bc_vals(:,1), bc_vals(:,3))\\n\";\n        fout << \"title('P_{LA}')\\n\";\n        fout << \"subplot(3,2,3)\\n\";\n        fout << \"plot(bc_vals(:,1), bc_vals(:,4))\\n\";\n        fout << \"title('Q_{R}')\\n\";\n        fout << \"subplot(3,2,4)\\n\";\n        fout << \"plot(bc_vals(:,1), bc_vals(:,5))\\n\";\n        fout << \"title('Q_{P}')\\n\";\n        fout << \"subplot(3,2,5)\\n\";\n        fout << \"plot(bc_vals(:,1), bc_vals(:,6))\\n\";\n        fout << \"title('Q_{mi}')\\n\";\n        fout << \"dt = bc_vals(2,1) - bc_vals(1,1);\\n\"; \n        fout << \"net_flux = dt*cumsum(bc_vals(:,6));\\n\";\n        fout << \"subplot(3,2,6)\\n\";\n        fout << \"plot(bc_vals(:,1), net_flux)\\n\";\n        fout << \"title('net Q')\\n\";\n        fout << \"printfig(fig, 'bc_model_variables')\\n\";\n    }\n    return;\n}\n\n\n\n\n\n\n\n\n\n/////////////////////////////// PROTECTED ////////////////////////////////////\n\n/////////////////////////////// PRIVATE //////////////////////////////////////\n\nvoid\nCirculationModel::writeDataFile() const\n{\n    static const int mpi_root = 0;\n    if (SAMRAI_MPI::getRank() == mpi_root)\n    {\n        static bool file_initialized = false;\n        const bool from_restart = RestartManager::getManager()->isFromRestart();\n        if (!from_restart && !file_initialized)\n        {\n            ofstream fout(DATA_FILE_NAME.c_str(), ios::out);\n            fout << \"% time \\t P_PA (mmHg)\\t d_P_LA (mmHg)\\t Q_R (ml/s)\\t Q_P (ml/s)\\t Q_mi (ml/s)\"\n                 << \"\\n\"\n                 << \"bc_vals = [\";\n            file_initialized = true;\n        }\n\n        ofstream fout(DATA_FILE_NAME.c_str(), ios::app);\n        for (int n = 0; n < d_nsrc; ++n)\n        {\n            fout << d_time;\n            fout.setf(ios_base::scientific);\n            fout.setf(ios_base::showpos);\n            fout.precision(10);\n            fout << \" \" << d_P_PA << \" \" << d_P_LA << \" \" << d_Q_R << \" \" << d_Q_P << \" \" << d_Q_mi << \"; \\n\";\n        }\n    }\n    return;\n} // writeDataFile\n\nvoid\nCirculationModel::getFromRestart()\n{\n    Pointer<Database> restart_db = RestartManager::getManager()->getRootDatabase();\n    Pointer<Database> db;\n    if (restart_db->isDatabase(d_object_name))\n    {\n        db = restart_db->getDatabase(d_object_name);\n    }\n    else\n    {\n        TBOX_ERROR(\"Restart database corresponding to \" << d_object_name << \" not found in restart file.\");\n    }\n\n    d_time = db->getDouble(\"d_time\");\n    d_nsrc = db->getInteger(\"d_nsrc\");\n    d_qsrc.resize(d_nsrc);\n    d_psrc.resize(d_nsrc);\n    d_srcname.resize(d_nsrc);\n    db->getDoubleArray(\"d_qsrc\", &d_qsrc[0], d_nsrc);\n    db->getDoubleArray(\"d_psrc\", &d_psrc[0], d_nsrc);\n    db->getStringArray(\"d_srcname\", &d_srcname[0], d_nsrc);\n    d_P_PA = db->getDouble(\"d_P_PA\");\n    d_P_LA = db->getDouble(\"d_P_LA\");\n    d_Q_R  = db->getDouble(\"d_Q_R\");\n    d_Q_P  = db->getDouble(\"d_Q_P\");\n    d_Q_mi = db->getDouble(\"d_Q_mi\");\n    d_bdry_interface_level_number = db->getInteger(\"d_bdry_interface_level_number\");\n    return;\n} // getFromRestart\n\n/////////////////////////////// NAMESPACE ////////////////////////////////////\n\n/////////////////////////////// TEMPLATE INSTANTIATION ///////////////////////\n\n//////////////////////////////////////////////////////////////////////////////", "meta": {"hexsha": "a8d6e75c839c70c63c507107089650f67fcf8cac", "size": 14529, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CirculationModel_la.cpp", "max_stars_repo_name": "alexkaiser/heart_valves", "max_stars_repo_head_hexsha": "53f30ec3680503542890a84949b7fb51d1734272", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CirculationModel_la.cpp", "max_issues_repo_name": "alexkaiser/heart_valves", "max_issues_repo_head_hexsha": "53f30ec3680503542890a84949b7fb51d1734272", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CirculationModel_la.cpp", "max_forks_repo_name": "alexkaiser/heart_valves", "max_forks_repo_head_hexsha": "53f30ec3680503542890a84949b7fb51d1734272", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3233944954, "max_line_length": 130, "alphanum_fraction": 0.5240553376, "num_tokens": 3932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4432500335799584}}
{"text": "\n#include <NTL/ZZXFactoring.h>\n#include <NTL/lzz_pXFactoring.h>\n#include <NTL/vec_vec_long.h>\n#include <NTL/vec_vec_ulong.h>\n#include <NTL/vec_double.h>\n\n#include <NTL/LLL.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\nlong ZZXFac_van_Hoeij = 1;\n\nstatic\nlong ok_to_abandon = 0;\n\nstruct LocalInfoT {\n   long n;\n   long NumPrimes;\n   long NumFactors;\n   vec_long p;\n   vec_vec_long pattern;\n   ZZ PossibleDegrees;\n   PrimeSeq s;\n};\n\n\n\nstatic\nvoid mul(ZZ_pX& x, vec_ZZ_pX& a)\n// this performs multiplications in close-to-optimal order,\n// and kills a in the process\n{\n   long n = a.length();\n\n   // first, deal with some trivial cases\n\n   if (n == 0) {\n      set(x);\n      a.kill();\n      return;\n   }\n   else if (n == 1) {\n      x = a[0];\n      a.kill();\n      return;\n   }\n\n   long i, j;\n\n   // assume n > 1 and all a[i]'s are nonzero\n\n   // sort into non-increasing degrees\n\n   for (i = 1; i <= n - 1; i++)\n      for (j = 0; j <= n - i - 1; j++)\n         if (deg(a[j]) < deg(a[j+1]))\n            swap(a[j], a[j+1]);\n\n   ZZ_pX g;\n\n   while (n > 1) {\n      // replace smallest two poly's by their product\n      mul(g, a[n-2], a[n-1]);\n      a[n-2].kill();\n      a[n-1].kill();\n      swap(g, a[n-2]);\n      n--;\n\n      // re-establish order\n\n      i = n-1;\n      while (i > 0 && deg(a[i-1]) < deg(a[i])) {\n         swap(a[i-1], a[i]);\n         i--;\n      }\n   }\n\n   x = a[0];\n\n   a[0].kill();\n   a.SetLength(0);\n}\n\n\nvoid mul(ZZX& x, const vec_pair_ZZX_long& a)\n{\n   long l = a.length();\n   ZZX res;\n   long i, j;\n\n   set(res);\n   for (i = 0; i < l; i++)\n      for (j = 0; j < a[i].b; j++)\n         mul(res, res, a[i].a);\n\n   x = res;\n}\n\n\nvoid SquareFreeDecomp(vec_pair_ZZX_long& u, const ZZX& ff)\n// input is primitive \n{\n   ZZX f = ff;\n\n   ZZX d, v, w, s, t1;\n   long i;\n\n   u.SetLength(0);\n\n   if (deg(f) <= 0)\n      return;\n\n   diff(t1, f);\n   GCD(d, f, t1);\n\n   if (deg(d) == 0) {\n      append(u, cons(f, 1));\n      return;\n   }\n\n   divide(v, f, d); \n   divide(w, t1, d);\n   i = 0;\n\n   for (;;) {\n      i = i + 1;\n\n      diff(t1, v);\n      sub(s, w, t1);\n\n      if (IsZero(s)) {\n         if (deg(v) != 0) append(u, cons(v, i));\n         return;\n      }\n\n      GCD(d, v, s);\n      divide(v, v, d);\n      divide(w, s, d);\n\n      if (deg(d) != 0) append(u, cons(d, i));\n   }\n}\n\n\n\n\nstatic\nvoid HenselLift(ZZX& Gout, ZZX& Hout, ZZX& Aout, ZZX& Bout,\n                const ZZX& f, const ZZX& g, const ZZX& h,\n                const ZZX& a, const ZZX& b, const ZZ& p) \n{\n   ZZX c, g1, h1, G, H, A, B;\n\n   mul(c, g, h);\n   sub(c, f, c);\n\n   if (!divide(c, c, p))\n      Error(\"inexact division\");\n\n   ZZ_pX cc, gg, hh, aa, bb, tt, gg1, hh1;\n\n   conv(cc, c);\n   conv(gg, g);\n   conv(hh, h);\n   conv(aa, a);\n   conv(bb, b);\n\n   ZZ_pXModulus GG;\n   ZZ_pXModulus HH;\n\n   build(GG, gg);\n   build(HH, hh);\n\n   ZZ_pXMultiplier AA;\n   ZZ_pXMultiplier BB;\n\n   build(AA, aa, HH);\n   build(BB, bb, GG);\n\n   rem(gg1, cc, GG);\n   MulMod(gg1, gg1, BB, GG);\n   \n   rem(hh1, cc, HH);\n   MulMod(hh1, hh1, AA, HH);\n\n   conv(g1, gg1);\n   mul(g1, g1, p);\n   add(G, g, g1);\n\n   conv(h1, hh1);\n   mul(h1, h1, p);\n   add(H, h, h1);\n\n   /* lift inverses */\n\n   ZZX t1, t2, r;\n\n   mul(t1, a, G);\n   mul(t2, b, H);\n   add(t1, t1, t2);\n   add(t1, t1, -1);\n   negate(t1, t1);\n\n   if (!divide(r, t1, p))\n      Error(\"inexact division\");\n\n   ZZ_pX rr, aa1, bb1;\n\n   conv(rr, r);\n   \n   rem(aa1, rr, HH);\n   MulMod(aa1, aa1, AA, HH);\n   rem(bb1, rr, GG);\n   MulMod(bb1, bb1, BB, GG);\n\n   ZZX a1, b1;\n\n   conv(a1, aa1);\n   mul(a1, a1, p);\n   add(A, a, a1);\n\n   conv(b1, bb1);\n   mul(b1, b1, p);\n   add(B, b, b1);\n\n   Gout = G;\n   Hout = H;\n   Aout = A;\n   Bout = B;\n}\n\nstatic\nvoid HenselLift1(ZZX& Gout, ZZX& Hout, \n                const ZZX& f, const ZZX& g, const ZZX& h,\n                const ZZX& a, const ZZX& b, const ZZ& p) \n{\n   ZZX c, g1, h1, G, H;\n\n   mul(c, g, h);\n   sub(c, f, c);\n\n   if (!divide(c, c, p))\n      Error(\"inexact division\");\n\n   ZZ_pX cc, gg, hh, aa, bb, tt, gg1, hh1;\n\n   conv(cc, c);\n   conv(gg, g);\n   conv(hh, h);\n   conv(aa, a);\n   conv(bb, b);\n\n   ZZ_pXModulus GG;\n   ZZ_pXModulus HH;\n\n   build(GG, gg);\n   build(HH, hh);\n\n   rem(gg1, cc, GG);\n   MulMod(gg1, gg1, bb, GG);\n   \n   rem(hh1, cc, HH);\n   MulMod(hh1, hh1, aa, HH);\n\n   conv(g1, gg1);\n   mul(g1, g1, p);\n   add(G, g, g1);\n\n   conv(h1, hh1);\n   mul(h1, h1, p);\n   add(H, h, h1);\n\n   Gout = G;\n   Hout = H;\n}\n\nstatic\nvoid BuildTree(vec_long& link, vec_ZZX& v, vec_ZZX& w,\n               const vec_zz_pX& a)\n{\n   long k = a.length();\n\n   if (k < 2) Error(\"bad arguments to BuildTree\");\n\n   vec_zz_pX V, W;\n\n   V.SetLength(2*k-2);\n   W.SetLength(2*k-2);\n   link.SetLength(2*k-2);\n\n   long i, j, s;\n   long minp, mind;\n\n   for (i = 0; i < k; i++) {\n      V[i] = a[i];\n      link[i] = -(i+1);\n   }\n\n   for (j = 0; j < 2*k-4; j += 2) {\n      minp = j;\n      mind = deg(V[j]);\n\n      for (s = j+1; s < i; s++)\n         if (deg(V[s]) < mind) {\n            minp = s;\n            mind = deg(V[s]);\n         }\n\n      swap(V[j], V[minp]);\n      swap(link[j], link[minp]);\n\n      minp = j+1;\n      mind = deg(V[j+1]);\n\n      for (s = j+2; s < i; s++)\n         if (deg(V[s]) < mind) {\n            minp = s;\n            mind = deg(V[s]);\n         }\n\n      swap(V[j+1], V[minp]);\n      swap(link[j+1], link[minp]);\n\n      mul(V[i], V[j], V[j+1]);\n      link[i] = j;\n      i++;\n   }\n\n   zz_pX d;\n\n   for (j = 0; j < 2*k-2; j += 2) {\n      XGCD(d, W[j], W[j+1], V[j], V[j+1]);\n      if (!IsOne(d))\n         Error(\"relatively prime polynomials expected\");\n   }\n\n   v.SetLength(2*k-2);\n   for (j = 0; j < 2*k-2; j++)\n      conv(v[j], V[j]);\n\n   w.SetLength(2*k-2);\n   for (j = 0; j < 2*k-2; j++)\n      conv(w[j], W[j]);\n}\n\nstatic\nvoid RecTreeLift(const vec_long& link, vec_ZZX& v, vec_ZZX& w,\n                 const ZZ& p, const ZZX& f, long j, long inv)\n{\n   if (j < 0) return;\n\n   if (inv)\n      HenselLift(v[j], v[j+1], w[j], w[j+1],\n                 f, v[j], v[j+1], w[j], w[j+1], p);\n   else\n      HenselLift1(v[j], v[j+1], f, v[j], v[j+1], w[j], w[j+1], p);\n\n   RecTreeLift(link, v, w, p, v[j], link[j], inv);\n   RecTreeLift(link, v, w, p, v[j+1], link[j+1], inv);\n}\n\nstatic\nvoid TreeLift(const vec_long& link, vec_ZZX& v, vec_ZZX& w, \n              long e0, long e1, const ZZX& f, long inv)\n\n// lift from p^{e0} to p^{e1}\n\n{\n   ZZ p0, p1;\n\n   power(p0, zz_p::modulus(), e0);\n   power(p1, zz_p::modulus(), e1-e0);\n\n   ZZ_pBak bak;\n   bak.save();\n   ZZ_p::init(p1);\n\n   RecTreeLift(link, v, w, p0, f, v.length()-2, inv);\n\n   bak.restore();\n} \n\nvoid MultiLift(vec_ZZX& A, const vec_zz_pX& a, const ZZX& f, long e,\n               long verbose)\n\n{\n   long k = a.length();\n   long i;\n\n   if (k < 2 || e < 1 || NTL_OVERFLOW(e, 1, 0)) Error(\"MultiLift: bad args\");\n\n   if (!IsOne(LeadCoeff(f)))\n      Error(\"MultiLift: bad args\");\n\n   for (i = 0; i < a.length(); i++)\n      if (!IsOne(LeadCoeff(a[i])))\n         Error(\"MultiLift: bad args\");\n\n   if (e == 1) {\n      A.SetLength(k);\n      for (i = 0; i < k; i++)\n         conv(A[i], a[i]);\n      return;\n   }\n\n   vec_long E;\n   append(E, e);\n   while (e > 1) {\n      e = (e+1)/2;\n      append(E, e);\n   }\n   long l = E.length();\n\n   vec_ZZX v, w;\n   vec_long link;\n\n   double t;\n\n   if (verbose) {\n      cerr << \"building tree...\";\n      t = GetTime();\n   }\n\n   BuildTree(link, v, w, a);\n\n   if (verbose) cerr << (GetTime()-t) << \"\\n\";\n\n\n   for (i = l-1; i > 0; i--) {\n      if (verbose) {\n         cerr << \"lifting to \" << E[i-1] << \"...\";\n         t = GetTime();\n      }\n      \n      TreeLift(link, v, w, E[i], E[i-1], f, i != 1);\n\n      if (verbose) cerr << (GetTime()-t) << \"\\n\";\n   }\n\n   A.SetLength(k);\n   for (i = 0; i < 2*k-2; i++) {\n      long t = link[i];\n      if (t < 0)\n         A[-(t+1)] = v[i];\n   }\n}\n\nstatic\nvoid inplace_rev(ZZX& f)\n{\n   long n = deg(f);\n   long i, j;\n\n   i = 0;\n   j = n;\n   while (i < j) {\n      swap(f.rep[i], f.rep[j]);\n      i++;\n      j--;\n   }\n\n   f.normalize();\n}\n\nlong ZZXFac_InitNumPrimes = 7;\nlong ZZXFac_MaxNumPrimes = 50;\n\nstatic \nvoid RecordPattern(vec_long& pat, vec_pair_zz_pX_long& fac)\n{\n   long n = pat.length()-1;\n   long i;\n\n   for (i = 0; i <= n; i++)\n      pat[i] = 0;\n\n   long k = fac.length();\n\n   for (i = 0; i < k; i++) {\n      long d = fac[i].b;\n      long m = deg(fac[i].a)/d;\n\n      pat[d] = m;\n   }\n}\n\nstatic\nlong NumFactors(const vec_long& pat)\n{\n   long n = pat.length()-1;\n\n   long i;\n   long res = 0;\n\n   for (i = 0; i <= n; i++) \n      res += pat[i];\n\n   return res;\n}\n\nstatic\nvoid CalcPossibleDegrees(ZZ& pd, const vec_long& pat)\n{\n   long n = pat.length()-1;\n   set(pd);\n\n   long d, j;\n   ZZ t1;\n\n   for (d = 1; d <= n; d++) \n      for (j = 0; j < pat[d]; j++) {\n         LeftShift(t1, pd, d);\n         bit_or(pd, pd, t1);\n      }\n}\n\nstatic \nvoid CalcPossibleDegrees(vec_ZZ& S, const vec_ZZ_pX& fac, long k)\n\n// S[i] = possible degrees of the product of any subset of size k\n//        among fac[i...], encoded as a bit vector.      \n\n{\n   long r = fac.length();\n\n   S.SetLength(r);\n\n   if (r == 0)\n      return;\n\n   if (k < 1 || k > r)\n      Error(\"CalcPossibleDegrees: bad args\");\n\n   long i, l;\n   ZZ old, t1;\n\n   set(S[r-1]);\n   LeftShift(S[r-1], S[r-1], deg(fac[r-1]));\n\n   for (i = r-2; i >= 0; i--) {\n      set(t1);\n      LeftShift(t1, t1, deg(fac[i]));\n      bit_or(S[i], t1, S[i+1]);\n   }\n\n   for (l = 2; l <= k; l++) {\n      old = S[r-l];\n      LeftShift(S[r-l], S[r-l+1], deg(fac[r-l]));\n\n      for (i = r-l-1; i >= 0; i--) {\n         LeftShift(t1, old, deg(fac[i]));\n         old = S[i];\n         bit_or(S[i], S[i+1], t1);\n      }\n   }\n}\n\n\n\nstatic\nvec_zz_pX *\nSmallPrimeFactorization(LocalInfoT& LocalInfo, const ZZX& f,\n                            long verbose)\n\n{\n   long n = deg(f);\n   long i;\n   double t;\n\n   LocalInfo.n = n;\n   long& NumPrimes = LocalInfo.NumPrimes;\n   NumPrimes = 0;\n\n   LocalInfo.NumFactors = 0;\n\n   // some sanity checking...\n\n   if (ZZXFac_InitNumPrimes < 1 || ZZXFac_InitNumPrimes > 10000)\n      Error(\"bad ZZXFac_InitNumPrimes\");\n\n   if (ZZXFac_MaxNumPrimes < ZZXFac_InitNumPrimes || ZZXFac_MaxNumPrimes > 10000)\n      Error(\"bad ZZXFac_MaxNumPrimes\");\n\n   LocalInfo.p.SetLength(ZZXFac_InitNumPrimes);\n   LocalInfo.pattern.SetLength(ZZXFac_InitNumPrimes);\n  \n   // set bits 0..n of LocalInfo.PossibleDegrees \n   SetBit(LocalInfo.PossibleDegrees, n+1);\n   add(LocalInfo.PossibleDegrees, LocalInfo.PossibleDegrees, -1);\n\n   long minr = n+1;\n   long irred = 0;\n\n   vec_pair_zz_pX_long *bestfac = 0;\n   zz_pX *besth = 0;\n   vec_zz_pX *spfactors = 0;\n   zz_pContext bestp;\n   long bestp_index;\n\n   long maxroot = NextPowerOfTwo(deg(f))+1;\n\n   for (; NumPrimes < ZZXFac_InitNumPrimes;) {\n      long p = LocalInfo.s.next();\n      if (!p) Error(\"out of small primes\");\n      if (divide(LeadCoeff(f), p)) {\n         if (verbose) cerr << \"skipping \" << p << \"\\n\";\n         continue;\n      }\n      zz_p::init(p, maxroot);\n\n      zz_pX ff, ffp, d;\n\n      conv(ff, f);\n      MakeMonic(ff);\n      diff(ffp, ff);\n\n      GCD(d, ffp, ff);\n      if (!IsOne(d)) {\n         if (verbose)  cerr << \"skipping \" << p << \"\\n\";\n         continue;\n      }\n\n\n      if (verbose) {\n         cerr << \"factoring mod \" << p << \"...\";\n         t = GetTime();\n      }\n\n      vec_pair_zz_pX_long thisfac;\n      zz_pX thish; \n\n      SFCanZass1(thisfac, thish, ff, 0);\n\n      LocalInfo.p[NumPrimes] = p;\n\n      vec_long& pattern = LocalInfo.pattern[NumPrimes];\n      pattern.SetLength(n+1);\n\n      RecordPattern(pattern, thisfac);\n      long r = NumFactors(pattern);\n      \n      if (verbose) {\n         cerr << (GetTime()-t) << \"\\n\";\n         cerr << \"degree sequence: \";\n         for (i = 0; i <= n; i++)\n            if (pattern[i]) {\n               cerr << pattern[i] << \"*\" << i << \" \";\n            }\n         cerr << \"\\n\";\n      }\n\n      if (r == 1) {\n         irred = 1;\n         break;\n      }\n\n      // update admissibility info\n\n      ZZ pd;\n\n      CalcPossibleDegrees(pd, pattern);\n      bit_and(LocalInfo.PossibleDegrees, LocalInfo.PossibleDegrees, pd);\n\n      if (weight(LocalInfo.PossibleDegrees) == 2) {\n         irred = 1;\n         break;\n      }\n\n\n      if (r < minr) {\n         minr = r;\n         delete bestfac;\n         bestfac = NTL_NEW_OP vec_pair_zz_pX_long;\n         *bestfac = thisfac;\n         delete besth;\n         besth = NTL_NEW_OP zz_pX;\n         *besth = thish;\n         bestp.save();\n         bestp_index = NumPrimes;\n      }\n\n      NumPrimes++;\n   }\n\n   if (!irred) {\n      // delete best prime from LocalInfo\n      swap(LocalInfo.pattern[bestp_index], LocalInfo.pattern[NumPrimes-1]);\n      LocalInfo.p[bestp_index] = LocalInfo.p[NumPrimes-1];\n      NumPrimes--;\n\n      bestp.restore();\n\n      spfactors = NTL_NEW_OP vec_zz_pX;\n\n      if (verbose) {\n         cerr << \"p = \" << zz_p::modulus() << \", completing factorization...\";\n         t = GetTime();\n      }\n      SFCanZass2(*spfactors, *bestfac, *besth, 0);\n      if (verbose) {\n         cerr << (GetTime()-t) << \"\\n\";\n      }\n   }\n\n   delete bestfac;\n   delete besth;\n\n   return spfactors;\n}\n\n\nstatic\nlong ConstTermTest(const vec_ZZ_pX& W, \n                  const vec_long& I,\n                  const ZZ& ct,\n                  const ZZ_p& lc,\n                  vec_ZZ_p& prod,\n                  long& ProdLen) \n{\n   long k = I.length();\n   ZZ_p t;\n   ZZ t1, t2;\n   long i;\n\n   if (ProdLen == 0) {\n      mul(prod[0], lc, ConstTerm(W[I[0]]));\n      ProdLen++;\n   }\n\n   for (i = ProdLen; i < k; i++)\n      mul(prod[i], prod[i-1], ConstTerm(W[I[i]]));\n\n   ProdLen = k-1;\n\n   // should make this a routine in ZZ_p\n   t1 = rep(prod[k-1]);\n   RightShift(t2, ZZ_p::modulus(), 1);\n   if (t1 > t2)\n      sub(t1, t1, ZZ_p::modulus());\n\n   return divide(ct, t1);\n}\n\nstatic\nvoid BalCopy(ZZX& g, const ZZ_pX& G)\n{\n   const ZZ& p = ZZ_p::modulus();\n   ZZ p2, t;\n   RightShift(p2, p, 1);\n\n   long n = G.rep.length();\n   long i;\n\n   g.rep.SetLength(n);\n   for (i = 0; i < n; i++) {\n      t = rep(G.rep[i]);\n      if (t > p2) sub(t, t, p);\n      g.rep[i] = t;\n   }\n}\n\n\n\n\nstatic\nvoid mul(ZZ_pX& g, const vec_ZZ_pX& W, const vec_long& I)\n{\n   vec_ZZ_pX w;\n   long k = I.length();\n   w.SetLength(k);\n   long i;\n\n   for (i = 0; i < k; i++)\n      w[i] = W[I[i]];\n\n   mul(g, w);\n}\n\n\n\n\nstatic\nvoid InvMul(ZZ_pX& g, const vec_ZZ_pX& W, const vec_long& I)\n{\n   vec_ZZ_pX w;\n   long k = I.length();\n   long r = W.length();\n   w.SetLength(r-k);\n   long i, j;\n\n   i = 0;\n   for (j = 0; j < r; j++) {\n      if (i < k && j == I[i])\n         i++;\n      else\n         w[j-i] = W[j];\n   } \n\n   mul(g, w);\n}\n\n\n\n\nstatic\nvoid RemoveFactors(vec_ZZ_pX& W, const vec_long& I)\n{\n   long k = I.length();\n   long r = W.length();\n   long i, j;\n\n   i = 0;\n   for (j = 0; j < r; j++) {\n      if (i < k && j == I[i])\n         i++;\n      else\n         swap(W[j-i], W[j]); \n   }\n\n   W.SetLength(r-k);\n}\n\nstatic\nvoid unpack(vec_long& x, const ZZ& a, long n)\n{\n   x.SetLength(n+1);\n   long i;\n\n   for (i = 0; i <= n; i++)\n      x[i] = bit(a, i);\n}\n\nstatic\nvoid SubPattern(vec_long& p1, const vec_long& p2)\n{\n   long l = p1.length();\n\n   if (p2.length() != l)\n      Error(\"SubPattern: bad args\");\n\n   long i;\n\n   for (i = 0; i < l; i++) {\n      p1[i] -= p2[i];\n      if (p1[i] < 0)\n         Error(\"SubPattern: internal error\");\n   }\n}\n\nstatic\nvoid UpdateLocalInfo(LocalInfoT& LocalInfo, vec_ZZ& pdeg,\n                     const vec_ZZ_pX& W, const vec_ZZX& factors,\n                     const ZZX& f, long k, long verbose)\n{\n   static long cnt = 0;\n\n   if (verbose) {\n      cnt = (cnt + 1) % 100;\n      if (!cnt) cerr << \"#\";\n   }\n\n   double t;\n   long i, j;\n\n   if (LocalInfo.NumFactors < factors.length()) {\n      zz_pBak bak;\n      bak.save();\n\n      vec_long pattern;\n      pattern.SetLength(LocalInfo.n+1);\n\n      ZZ pd;\n\n      if (verbose) {\n         cerr << \"updating local info...\";\n         t = GetTime();\n      }\n\n      for (i = 0; i < LocalInfo.NumPrimes; i++) {\n         zz_p::init(LocalInfo.p[i], NextPowerOfTwo(LocalInfo.n)+1);\n\n         for (j = LocalInfo.NumFactors; j < factors.length(); j++) {\n            vec_pair_zz_pX_long thisfac;\n            zz_pX thish; \n\n            zz_pX ff;\n            conv(ff, factors[j]);\n            MakeMonic(ff);\n\n            SFCanZass1(thisfac, thish, ff, 0);\n            RecordPattern(pattern, thisfac);\n            SubPattern(LocalInfo.pattern[i], pattern);\n         }\n\n         CalcPossibleDegrees(pd, LocalInfo.pattern[i]);\n         bit_and(LocalInfo.PossibleDegrees, LocalInfo.PossibleDegrees, pd);\n\n      }\n\n      bak.restore();\n      LocalInfo.NumFactors = factors.length();\n\n      CalcPossibleDegrees(pdeg, W, k);\n\n      if (verbose) cerr << (GetTime()-t) << \"\\n\";\n   }\n\n   if (!ZZXFac_van_Hoeij && LocalInfo.NumPrimes + 1 < ZZXFac_MaxNumPrimes) {\n      if (verbose)\n         cerr << \"adding a prime\\n\";\n\n      zz_pBak bak;\n      bak.save();\n\n      for (;;) {\n         long p = LocalInfo.s.next();\n         if (!p)\n            Error(\"UpdateLocalInfo: out of primes\");\n\n         if (divide(LeadCoeff(f), p)) {\n            if (verbose) cerr << \"skipping \" << p << \"\\n\";\n            continue;\n         }\n\n         zz_p::init(p, NextPowerOfTwo(deg(f))+1);\n\n         zz_pX ff, ffp, d;\n   \n         conv(ff, f);\n         MakeMonic(ff);\n         diff(ffp, ff);\n   \n         GCD(d, ffp, ff);\n         if (!IsOne(d)) {\n            if (verbose)  cerr << \"skipping \" << p << \"\\n\";\n            continue;\n         }\n\n         vec_pair_zz_pX_long thisfac;\n         zz_pX thish;\n\n         if (verbose) {\n            cerr << \"factoring mod \" << p << \"...\";\n            t = GetTime();\n         }\n\n         SFCanZass1(thisfac, thish, ff, 0);\n\n         LocalInfo.p.SetLength(LocalInfo.NumPrimes+1);\n         LocalInfo.pattern.SetLength(LocalInfo.NumPrimes+1);\n\n         LocalInfo.p[LocalInfo.NumPrimes] = p;\n         vec_long& pattern = LocalInfo.pattern[LocalInfo.NumPrimes];\n\n         pattern.SetLength(LocalInfo.n+1);\n         RecordPattern(pattern, thisfac);\n\n         if (verbose) {\n            cerr << (GetTime()-t) << \"\\n\";\n            cerr << \"degree sequence: \";\n            for (i = 0; i <= LocalInfo.n; i++)\n               if (pattern[i]) {\n                  cerr << pattern[i] << \"*\" << i << \" \";\n               }\n            cerr << \"\\n\";\n         }\n\n         ZZ pd;\n         CalcPossibleDegrees(pd, pattern);\n         bit_and(LocalInfo.PossibleDegrees, LocalInfo.PossibleDegrees, pd);\n\n         LocalInfo.NumPrimes++;\n\n         break;\n      }\n\n      bak.restore();\n   }\n}\n\n\n\nconst int ZZX_OVERLIFT = NTL_BITS_PER_LONG;\n  // number of bits by which we \"overlift\"....this enables, in particular,\n  // the \"n-1\" test.  \n  // Must lie in the range 4..NTL_BITS_PER_LONG.\n\n\n#define EXTRA_BITS (1)\n// Any small number, like 1, 2 or 3, should be OK.\n\n\nstatic\nvoid CardinalitySearch(vec_ZZX& factors, ZZX& f, \n                       vec_ZZ_pX& W, \n                       LocalInfoT& LocalInfo, \n                       long k,\n                       long bnd,\n                       long verbose)\n{\n   double start_time, end_time;\n\n   if (verbose) {\n      start_time = GetTime();\n      cerr << \"\\n************ \";\n      cerr << \"start cardinality \" << k << \"\\n\";\n   }\n\n   vec_long I, D;\n   I.SetLength(k);\n   D.SetLength(k);\n\n   long r = W.length();\n\n   vec_ZZ_p prod;\n   prod.SetLength(k);\n   long ProdLen;\n\n   vec_ZZ pdeg;\n   CalcPossibleDegrees(pdeg, W, k);\n\n   ZZ pd;\n   vec_long upd;\n\n   long i, state;\n\n   long cnt = 0;\n\n   ZZ ct;\n   mul(ct, ConstTerm(f), LeadCoeff(f));\n\n   ZZ_p lc;\n   conv(lc, LeadCoeff(f));\n\n   ZZ_pX gg;\n   ZZX g, h;\n\n   I[0] = 0;  \n\n   while (I[0] <= r-k) {\n      bit_and(pd, pdeg[I[0]], LocalInfo.PossibleDegrees);\n\n      if (IsZero(pd)) {\n         if (verbose) cerr << \"skipping\\n\";\n         goto done;\n      }\n\n      unpack(upd, pd, LocalInfo.n);\n\n      D[0] = deg(W[I[0]]);\n      i = 1;\n      state = 0;\n      ProdLen = 0;\n\n      for (;;) {\n         if (i < ProdLen)\n            ProdLen = i;\n\n         if (i == k) {\n            // process indices I[0], ..., I[k-1]\n\n            if (cnt > 2000000) { \n               cnt = 0;\n               UpdateLocalInfo(LocalInfo, pdeg, W, factors, f, k, verbose);\n               bit_and(pd, pdeg[I[0]], LocalInfo.PossibleDegrees);\n               if (IsZero(pd)) {\n                  if (verbose) cerr << \"skipping\\n\";\n                  goto done;\n               }\n               unpack(upd, pd, LocalInfo.n);\n            }\n\n            state = 1;  // default continuation state\n\n\n            if (!upd[D[k-1]]) {\n               i--;\n               cnt++;\n               continue;\n            }\n\n            if (!ConstTermTest(W, I, ct, lc, prod, ProdLen)) {\n               i--;\n               cnt += 100;\n               continue;\n            }\n\n            if (verbose) {\n               cerr << \"+\";\n            }\n\n            cnt += 1000;\n\n            if (2*D[k-1] <= deg(f)) {\n               mul(gg, W, I);\n               mul(gg, gg, lc);\n               BalCopy(g, gg);\n               if(MaxBits(g) > bnd) {\n                  i--;\n                  continue;\n               }\n               if (verbose) {\n                  cerr << \"*\";\n               }\n               PrimitivePart(g, g);\n               if (!divide(h, f, g)) {\n                  i--;\n                  continue;\n               }\n               \n               // factor found!\n               append(factors, g);\n               if (verbose) {\n                 cerr << \"degree \" << deg(g) << \" factor found\\n\";\n               }\n               f = h;\n               mul(ct, ConstTerm(f), LeadCoeff(f));\n               conv(lc, LeadCoeff(f));\n            }\n            else {\n               InvMul(gg, W, I);\n               mul(gg, gg, lc);\n               BalCopy(g, gg);\n               if(MaxBits(g) > bnd) {\n                  i--;\n                  continue;\n               }\n               if (verbose) {\n                  cerr << \"*\";\n               }\n               PrimitivePart(g, g);\n               if (!divide(h, f, g)) {\n                  i--;\n                  continue;\n               }\n\n               // factor found!\n               append(factors, h);\n               if (verbose) {\n                 cerr << \"degree \" << deg(h) << \" factor found\\n\";\n               }\n               f = g;\n               mul(ct, ConstTerm(f), LeadCoeff(f));\n               conv(lc, LeadCoeff(f));\n            }\n\n            RemoveFactors(W, I);\n            r = W.length();\n            cnt = 0;\n\n            if (2*k > r) \n               goto done;\n            else \n               break;\n         }\n         else if (state == 0) {\n            I[i] = I[i-1] + 1;\n            D[i] = D[i-1] + deg(W[I[i]]);\n            i++;\n         }\n         else { // state == 1\n            I[i]++;\n            if (i == 0) break;\n\n            if (I[i] > r-k+i)\n               i--;\n            else {\n               D[i] = D[i-1] + deg(W[I[i]]);\n               i++;\n               state = 0;\n            }\n         }\n      }\n   }\n\n\n   done: \n\n\n   if (verbose) {\n      end_time = GetTime();\n      cerr << \"\\n************ \";\n      cerr << \"end cardinality \" << k << \"\\n\";\n      cerr << \"time: \" << (end_time-start_time) << \"\\n\";\n   }\n}\n\n\n\ntypedef unsigned long TBL_T;\n\n#if (NTL_BITS_PER_LONG >= 64)\n\n// for 64-bit machines\n\n#define TBL_MSK (63)\n#define TBL_SHAMT (6)\n\n#else\n\n// for 32-bit machines\n\n#define TBL_MSK (31)\n#define TBL_SHAMT (5)\n\n#endif\n\n\n#if 0\n\n// recursive version\n\nstatic\nvoid RecInitTab(TBL_T ***lookup_tab, long i, const vec_ulong& ratio, \n             long r, long k, unsigned long thresh1, long **shamt_tab,\n             unsigned long sum, long card, long j)\n{\n   if (j >= i || card >= k-1) {\n      if (card > 1) {\n         long shamt = shamt_tab[i][card];\n         unsigned long index1 = ((-sum) >> shamt);\n         lookup_tab[i][card][index1 >> TBL_SHAMT] |= (1UL << (index1 & TBL_MSK));\n         unsigned long index2 = ((-sum+thresh1) >> shamt);\n         if (index1 != index2)\n            lookup_tab[i][card][index2 >> TBL_SHAMT] |= (1UL << (index2 & TBL_MSK));\n\n      }\n\n      return;\n   }\n\n\n   RecInitTab(lookup_tab, i, ratio, r, k, thresh1, shamt_tab, sum, card, j+1);\n   RecInitTab(lookup_tab, i, ratio, r, k, thresh1, shamt_tab, \n              sum+ratio[r-1-j], card+1, j+1);\n}\n\n\nstatic\nvoid DoInitTab(TBL_T ***lookup_tab, long i, const vec_ulong& ratio, \n               long r, long k, unsigned long thresh1, long **shamt_tab)\n{\n   RecInitTab(lookup_tab, i, ratio, r, k, thresh1, shamt_tab, 0, 0, 0);\n}\n\n#else\n\n// iterative version\n\n\nstatic\nvoid DoInitTab(TBL_T ***lookup_tab, long i, const vec_ulong& ratio,\n               long r, long k, unsigned long thresh1, long **shamt_tab)\n{\n   vec_long sum_vec, card_vec, location_vec;\n   sum_vec.SetLength(i+1);\n   card_vec.SetLength(i+1);\n   location_vec.SetLength(i+1);\n\n   long j = 0;\n   sum_vec[0] = 0;\n   card_vec[0] = 0;\n\n   unsigned long sum;\n   long  card, location;\n\n   location = 0;\n\n   while (j >= 0) {\n      sum = sum_vec[j];\n      card = card_vec[j];\n\n      switch (location) {\n\n      case 0:\n\n         if (j >= i || card >= k-1) {\n            if (card > 1) {\n               long shamt = shamt_tab[i][card];\n               unsigned long index1 = ((-sum) >> shamt);\n               lookup_tab[i][card][index1 >> TBL_SHAMT] |= (1UL << (index1 & TBL_MSK));\n               unsigned long index2 = ((-sum+thresh1) >> shamt);\n               if (index1 != index2)\n                  lookup_tab[i][card][index2 >> TBL_SHAMT] |= (1UL << (index2 & TBL_MSK));\n      \n            }\n      \n            location = location_vec[j];\n            j--;\n            continue;\n         }\n\n\n         sum_vec[j+1] = sum;\n         card_vec[j+1] = card;\n         location_vec[j+1] = 1;\n         j++;\n         location = 0;\n         continue;\n\n      case 1:\n\n         sum_vec[j+1] = sum+ratio[r-1-j];\n         card_vec[j+1] = card+1;\n         location_vec[j+1] = 2;\n         j++;\n         location = 0;\n         continue;  \n\n      case 2:\n\n         location = location_vec[j];\n         j--;\n         continue;\n      }\n   }\n}\n         \n#endif\n   \n   \n\nstatic\nvoid InitTab(TBL_T ***lookup_tab, const vec_ulong& ratio, long r, long k,\n             unsigned long thresh1, long **shamt_tab, long pruning)\n{\n   long i, j, t;\n\n   if (pruning) {\n      for (i = 2; i <= pruning; i++) {\n         long len = min(k-1, i);\n         for (j = 2; j <= len; j++) {\n            long ub = (((1L << (NTL_BITS_PER_LONG-shamt_tab[i][j])) \n                      + TBL_MSK) >> TBL_SHAMT); \n            for (t = 0; t < ub; t++)\n               lookup_tab[i][j][t] = 0;\n         }\n   \n         DoInitTab(lookup_tab, i, ratio, r, k, thresh1, shamt_tab);\n      }\n   }\n}\n\n\nstatic\nvoid RatioInit1(vec_ulong& ratio, const vec_ZZ_pX& W, const ZZ_p& lc,\n                long pruning, TBL_T ***lookup_tab, \n                vec_vec_ulong& pair_ratio, long k, unsigned long thresh1, \n                long **shamt_tab)\n{\n   long r = W.length();\n   long i, j;\n\n   ZZ_p a;\n\n   ZZ p;\n   p = ZZ_p::modulus();\n\n   ZZ aa;\n\n   for (i = 0; i < r; i++) {\n      long m = deg(W[i]);\n      mul(a, W[i].rep[m-1], lc);\n      LeftShift(aa, rep(a), NTL_BITS_PER_LONG);\n      div(aa, aa, p);\n      ratio[i] = to_ulong(aa);\n   }\n\n   InitTab(lookup_tab, ratio, r, k, thresh1, shamt_tab, pruning);\n\n   for (i = 0; i < r; i++)\n      for (j = 0; j < i; j++) {\n         mul(a, W[i].rep[deg(W[i])-1], W[j].rep[deg(W[j])-1]);\n         mul(a, a, lc);\n         LeftShift(aa, rep(a), NTL_BITS_PER_LONG);\n         div(aa, aa, p);\n         pair_ratio[i][j] = to_ulong(aa);\n      }\n\n   for (i = 0; i < r; i++) {\n      long m = deg(W[i]);\n      if (m >= 2) {\n         mul(a, W[i].rep[m-2], lc);\n         LeftShift(aa, rep(a), NTL_BITS_PER_LONG);\n         div(aa, aa, p);\n         pair_ratio[i][i] = to_ulong(aa);\n      }\n      else\n         pair_ratio[i][i] = 0;\n   }\n}\n\nstatic \nlong SecondOrderTest(const vec_long& I_vec, const vec_vec_ulong& pair_ratio_vec,\n                     vec_ulong& sum_stack_vec, long& SumLen)\n{\n   long k = I_vec.length();\n   const long *I = I_vec.elts();\n   unsigned long *sum_stack = sum_stack_vec.elts();\n\n   unsigned long sum, thresh1;\n\n   if (SumLen == 0) {\n      unsigned long epsilon = (1UL << (NTL_BITS_PER_LONG-ZZX_OVERLIFT));\n      unsigned long delta = (unsigned long) ((k*(k+1)) >> 1);\n      unsigned long thresh = epsilon + delta;\n      thresh1 = (epsilon << 1) + delta;\n\n      sum = thresh;\n      sum_stack[k] = thresh1;\n   }\n   else {\n      sum = sum_stack[SumLen-1];\n      thresh1 = sum_stack[k];\n   }\n\n   long i, j;\n\n   for (i = SumLen; i < k; i++) {\n      const unsigned long *p = pair_ratio_vec[I[i]].elts();\n      for (j = 0; j <= i; j++) {\n         sum += p[I[j]];\n      }\n\n      sum_stack[i] = sum;\n   }\n\n   SumLen = k-1;\n\n   return (sum <= thresh1);\n}\n\n\nstatic\nZZ choose_fn(long r, long k)\n{\n   ZZ a, b;\n\n   a = 1; \n   b = 1;\n\n   long i;\n   for (i = 0; i < k; i++) {\n      a *= r-i;\n      b *= k-i;\n   }\n\n   return a/b;\n}\n\nstatic\nvoid PrintInfo(const char *s, const ZZ& a, const ZZ& b)\n{\n   cerr << s << a << \" / \" << b << \" = \";\n   \n   double x = to_double(a)/to_double(b);\n\n   if (x == 0) \n      cerr << \"0\"; \n   else {\n      int n;\n      double f;\n\n      f = frexp(x, &n);\n      cerr << f << \"*2^\" << n;\n   }\n\n   cerr << \"\\n\";\n}\n\nstatic\nvoid RemoveFactors1(vec_long& W, const vec_long& I, long r)\n{\n   long k = I.length();\n   long i, j;\n\n   i = 0;\n   for (j = 0; j < r; j++) {\n      if (i < k && j == I[i])\n         i++;\n      else\n         swap(W[j-i], W[j]); \n   }\n}\n\nstatic\nvoid RemoveFactors1(vec_vec_long& W, const vec_long& I, long r)\n{\n   long k = I.length();\n   long i, j;\n\n   i = 0;\n   for (j = 0; j < r; j++) {\n      if (i < k && j == I[i])\n         i++;\n      else\n         swap(W[j-i], W[j]); \n   }\n\n   for (i = 0; i < r-k; i++)\n      RemoveFactors1(W[i], I, r);\n}\n\n\n// should this swap go in tools.h?\n// Maybe not...I don't want to pollute the interface too much more.\n\nstatic inline \nvoid swap(unsigned long& a, unsigned long& b)  \n   { unsigned long t;  t = a; a = b; b = t; }\n\nstatic\nvoid RemoveFactors1(vec_ulong& W, const vec_long& I, long r)\n{\n   long k = I.length();\n   long i, j;\n\n   i = 0;\n   for (j = 0; j < r; j++) {\n      if (i < k && j == I[i])\n         i++;\n      else\n         swap(W[j-i], W[j]); \n   }\n}\n\nstatic\nvoid RemoveFactors1(vec_vec_ulong& W, const vec_long& I, long r)\n{\n   long k = I.length();\n   long i, j;\n\n   i = 0;\n   for (j = 0; j < r; j++) {\n      if (i < k && j == I[i])\n         i++;\n      else\n         swap(W[j-i], W[j]); \n   }\n\n   for (i = 0; i < r-k; i++)\n      RemoveFactors1(W[i], I, r);\n}\n\n\nstatic\nvoid RemoveFactors1(vec_ZZ_p& W, const vec_long& I, long r)\n{\n   long k = I.length();\n   long i, j;\n\n   i = 0;\n   for (j = 0; j < r; j++) {\n      if (i < k && j == I[i])\n         i++;\n      else\n         swap(W[j-i], W[j]);\n   }\n}\n\nstatic\nvoid SumCoeffs(ZZ& sum, const ZZX& a)\n{\n   ZZ res;\n   res = 0;\n   long i;\n   long n = a.rep.length();\n   for (i = 0; i < n; i++)\n      res += a.rep[i];\n\n   sum = res;\n}\n\nstatic\nvoid SumCoeffs(ZZ_p& sum, const ZZ_pX& a)\n{\n   ZZ_p res;\n   res = 0;\n   long i;\n   long n = a.rep.length();\n   for (i = 0; i < n; i++)\n      res += a.rep[i];\n\n   sum = res;\n}\n\n\nstatic\nlong ConstTermTest(const vec_ZZ_p& W, \n                  const vec_long& I,\n                  const ZZ& ct,\n                  const ZZ_p& lc,\n                  vec_ZZ_p& prod,\n                  long& ProdLen) \n{\n   long k = I.length();\n   ZZ_p t;\n   ZZ t1, t2;\n   long i;\n\n   if (ProdLen == 0) {\n      mul(prod[0], lc, W[I[0]]);\n      ProdLen++;\n   }\n\n   for (i = ProdLen; i < k; i++)\n      mul(prod[i], prod[i-1], W[I[i]]);\n\n   ProdLen = k-1;\n\n   // should make this a routine in ZZ_p\n   t1 = rep(prod[k-1]);\n   RightShift(t2, ZZ_p::modulus(), 1);\n   if (t1 > t2)\n      sub(t1, t1, ZZ_p::modulus());\n\n   return divide(ct, t1);\n}\n\n\nlong ZZXFac_MaxPrune = 10;\n\n\n\nstatic\nlong pruning_bnd(long r, long k)\n{\n   double x = 0; \n\n   long i;\n   for (i = 0; i < k; i++) {\n      x += log(double(r-i)/double(k-i));\n   }\n\n   return long((x/log(2.0)) * 0.75);\n}\n\nstatic\nlong shamt_tab_init(long pos, long card, long pruning, long thresh1_len)\n{\n   double x = 1;\n   long i;\n\n   for (i = 0; i < card; i++) {\n      x *= double(pos-i)/double(card-i);\n   }\n\n   x *= pruning;  // this can be adjusted to control the density\n   if (pos <= 6) x *= 2;  // a little boost that costs very little\n      \n\n   long t = long(ceil(log(x)/log(2.0)));\n\n   t = max(t, TBL_SHAMT); \n\n   t = min(t, NTL_BITS_PER_LONG-thresh1_len);\n\n\n   return NTL_BITS_PER_LONG-t;\n}\n\n// The following routine should only be called for k > 1,\n// and is only worth calling for k > 2.\n\n\nstatic\nvoid CardinalitySearch1(vec_ZZX& factors, ZZX& f, \n                       vec_ZZ_pX& W, \n                       LocalInfoT& LocalInfo, \n                       long k,\n                       long bnd,\n                       long verbose)\n{\n   double start_time, end_time;\n\n   if (verbose) {\n      start_time = GetTime();\n      cerr << \"\\n************ \";\n      cerr << \"start cardinality \" << k << \"\\n\";\n   }\n\n   if (k <= 1) Error(\"internal error: call CardinalitySearch\");\n\n   // This test is needed to ensure correcntes of \"n-2\" test\n   if (NumBits(k) > NTL_BITS_PER_LONG/2-2)\n      Error(\"Cardinality Search: k too large...\");\n\n   vec_ZZ pdeg;\n   CalcPossibleDegrees(pdeg, W, k);\n   ZZ pd;\n\n   bit_and(pd, pdeg[0], LocalInfo.PossibleDegrees);\n   if (pd == 0) {\n      if (verbose) cerr << \"skipping\\n\";\n      return;\n   }\n\n   vec_long I, D;\n   I.SetLength(k);\n   D.SetLength(k);\n\n   long r = W.length();\n\n   long initial_r = r;\n\n   vec_ulong ratio, ratio_sum;\n   ratio.SetLength(r);\n   ratio_sum.SetLength(k);\n\n   unsigned long epsilon = (1UL << (NTL_BITS_PER_LONG-ZZX_OVERLIFT));\n   unsigned long delta = (unsigned long) k;\n   unsigned long thresh = epsilon + delta;\n   unsigned long thresh1 = (epsilon << 1) + delta;\n\n   long thresh1_len = NumBits(long(thresh1)); \n\n   long pruning;\n\n   pruning = min(r/2, ZZXFac_MaxPrune);\n   pruning = min(pruning, pruning_bnd(r, k));\n   pruning = min(pruning, NTL_BITS_PER_LONG-EXTRA_BITS-thresh1_len);\n\n   if (pruning <= 4) pruning = 0;\n\n   long init_pruning = pruning;\n\n   TBL_T ***lookup_tab = 0;\n\n   long **shamt_tab = 0;\n\n   if (pruning) {\n      typedef long *long_p;\n\n      long i, j;\n\n      shamt_tab = NTL_NEW_OP long_p[pruning+1];\n      if (!shamt_tab) Error(\"out of mem\");\n      shamt_tab[0] = shamt_tab[1] = 0;\n\n      for (i = 2; i <= pruning; i++) {\n         long len = min(k-1, i);\n         shamt_tab[i] = NTL_NEW_OP long[len+1];\n         if (!shamt_tab[i]) Error(\"out of mem\");\n         shamt_tab[i][0] = shamt_tab[i][1] = 0;\n\n         for (j = 2; j <= len; j++)\n            shamt_tab[i][j] = shamt_tab_init(i, j, pruning, thresh1_len);\n      }\n\n      typedef  TBL_T *TBL_T_p;\n      typedef  TBL_T **TBL_T_pp;\n\n      lookup_tab = NTL_NEW_OP TBL_T_pp[pruning+1];\n      if (!lookup_tab) Error(\"out of mem\");\n\n      lookup_tab[0] = lookup_tab[1] = 0;\n\n      for (i = 2; i <= pruning; i++) {\n         long len = min(k-1, i);\n         lookup_tab[i] = NTL_NEW_OP TBL_T_p[len+1];\n         if (!lookup_tab[i]) Error(\"out of mem\");\n\n         lookup_tab[i][0] = lookup_tab[i][1] = 0;\n\n         for (j = 2; j <= len; j++) {\n            lookup_tab[i][j] = NTL_NEW_OP TBL_T[((1L << (NTL_BITS_PER_LONG-shamt_tab[i][j]))+TBL_MSK) >> TBL_SHAMT];\n            if (!lookup_tab[i][j]) Error(\"out of mem\");\n         }\n      }\n   }\n\n   if (verbose) {\n      cerr << \"pruning = \" << pruning << \"\\n\";\n   }\n\n   vec_ZZ_p prod;\n   prod.SetLength(k);\n   long ProdLen;\n\n   vec_ZZ_p prod1;\n   prod1.SetLength(k);\n   long ProdLen1;\n\n   vec_ulong sum_stack;\n   sum_stack.SetLength(k+1);\n   long SumLen;\n\n   vec_long upd;\n\n   long i, state;\n\n   long cnt = 0;\n\n   ZZ ct;\n   mul(ct, ConstTerm(f), LeadCoeff(f));\n\n   ZZ_p lc;\n   conv(lc, LeadCoeff(f));\n\n   vec_vec_ulong pair_ratio;\n   pair_ratio.SetLength(r);\n   for (i = 0; i < r; i++)\n      pair_ratio[i].SetLength(r);\n\n   RatioInit1(ratio, W, lc, pruning, lookup_tab, pair_ratio, k, thresh1, shamt_tab);\n\n   ZZ c1;\n   SumCoeffs(c1, f);\n   mul(c1, c1, LeadCoeff(f));\n\n   vec_ZZ_p sum_coeffs;\n   sum_coeffs.SetLength(r);\n   for (i = 0; i < r; i++)\n      SumCoeffs(sum_coeffs[i], W[i]);\n\n   vec_long degv;\n   degv.SetLength(r);\n\n   for (i = 0; i < r; i++)\n      degv[i] = deg(W[i]);\n\n   ZZ_pX gg;\n   ZZX g, h;\n\n   I[0] = 0;  \n\n   long loop_cnt = 0, degree_cnt = 0, n2_cnt = 0, sl_cnt = 0, ct_cnt = 0, \n        pl_cnt = 0, c1_cnt = 0, pl1_cnt = 0, td_cnt = 0;\n\n   ZZ loop_total, degree_total, n2_total, sl_total, ct_total, \n      pl_total, c1_total, pl1_total, td_total;\n\n   while (I[0] <= r-k) {\n      bit_and(pd, pdeg[I[0]], LocalInfo.PossibleDegrees);\n\n      if (IsZero(pd)) {\n         if (verbose) cerr << \"skipping\\n\";\n         goto done;\n      }\n\n      unpack(upd, pd, LocalInfo.n);\n\n      D[0] = degv[I[0]];\n      ratio_sum[0] = ratio[I[0]] + thresh;\n      i = 1;\n      state = 0;\n      ProdLen = 0;\n      ProdLen1 = 0;\n      SumLen = 0;\n\n      for (;;) {\n         cnt++;\n\n         if (cnt > 2000000) { \n            if (verbose) {\n               loop_total += loop_cnt;  loop_cnt = 0;\n               degree_total += degree_cnt;  degree_cnt = 0;\n               n2_total += n2_cnt;  n2_cnt = 0;\n               sl_total += sl_cnt;  sl_cnt = 0;\n               ct_total += ct_cnt;  ct_cnt = 0;\n               pl_total += pl_cnt;  pl_cnt = 0;\n               c1_total += c1_cnt;  c1_cnt = 0;\n               pl1_total += pl1_cnt;  pl1_cnt = 0;\n               td_total += td_cnt;  td_cnt = 0;\n            }\n\n            cnt = 0;\n            UpdateLocalInfo(LocalInfo, pdeg, W, factors, f, k, verbose);\n            bit_and(pd, pdeg[I[0]], LocalInfo.PossibleDegrees);\n            if (IsZero(pd)) {\n               if (verbose) cerr << \"skipping\\n\";\n               goto done;\n            }\n            unpack(upd, pd, LocalInfo.n);\n         }\n\n         if (i == k-1) {\n\n            unsigned long ratio_sum_last = ratio_sum[k-2];\n            long I_last = I[k-2];\n\n\n            {\n               long D_last = D[k-2];\n   \n               unsigned long rs;\n               long I_this;\n               long D_this;\n   \n               for (I_this = I_last+1; I_this < r; I_this++) {\n                  loop_cnt++;\n   \n                  rs = ratio_sum_last + ratio[I_this];\n                  if (rs > thresh1) {\n                     cnt++;\n                     continue;\n                  }\n\n                  degree_cnt++;\n   \n                  D_this = D_last + degv[I_this];\n   \n                  if (!upd[D_this]) {\n                     cnt++;\n                     continue;\n                  }\n   \n                  n2_cnt++;\n                  sl_cnt += (k-SumLen);\n\n                  I[k-1] = I_this;\n\n                  if (!SecondOrderTest(I, pair_ratio, sum_stack, SumLen)) {\n                     cnt += 2;\n                     continue;\n                  }\n\n                  c1_cnt++;\n                  pl1_cnt += (k-ProdLen1);\n\n                  if (!ConstTermTest(sum_coeffs, I, c1, lc, prod1, ProdLen1)) {\n                     cnt += 100;\n                     continue;\n                  }\n\n                  ct_cnt++;\n                  pl_cnt += (k-ProdLen);\n\n                  D[k-1] = D_this;\n\n                  if (!ConstTermTest(W, I, ct, lc, prod, ProdLen)) {\n                     cnt += 100;\n                     continue;\n                  }\n\n                  td_cnt++;\n   \n                  if (verbose) {\n                     cerr << \"+\";\n                  }\n   \n                  cnt += 1000;\n   \n                  if (2*D[k-1] <= deg(f)) {\n                     mul(gg, W, I);\n                     mul(gg, gg, lc);\n                     BalCopy(g, gg);\n                     if(MaxBits(g) > bnd) {\n                        continue;\n                     }\n                     if (verbose) {\n                        cerr << \"*\";\n                     }\n                     PrimitivePart(g, g);\n                     if (!divide(h, f, g)) {\n                        continue;\n                     }\n                  \n                     // factor found!\n                     append(factors, g);\n                     if (verbose) {\n                       cerr << \"degree \" << deg(g) << \" factor found\\n\";\n                     }\n                     f = h;\n                     mul(ct, ConstTerm(f), LeadCoeff(f));\n                     conv(lc, LeadCoeff(f));\n                  }\n                  else {\n                     InvMul(gg, W, I);\n                     mul(gg, gg, lc);\n                     BalCopy(g, gg);\n                     if(MaxBits(g) > bnd) {\n                        continue;\n                     }\n                     if (verbose) {\n                        cerr << \"*\";\n                     }\n                     PrimitivePart(g, g);\n                     if (!divide(h, f, g)) {\n                        continue;\n                     }\n      \n                     // factor found!\n                     append(factors, h);\n                     if (verbose) {\n                       cerr << \"degree \" << deg(h) << \" factor found\\n\";\n                     }\n                     f = g;\n                     mul(ct, ConstTerm(f), LeadCoeff(f));\n                     conv(lc, LeadCoeff(f));\n                  }\n      \n                  RemoveFactors(W, I);\n                  RemoveFactors1(degv, I, r);\n                  RemoveFactors1(sum_coeffs, I, r);\n                  RemoveFactors1(ratio, I, r);\n                  RemoveFactors1(pair_ratio, I, r);\n\n                  r = W.length();\n                  cnt = 0;\n\n                  pruning = min(pruning, r/2);\n                  if (pruning <= 4) pruning = 0;\n\n                  InitTab(lookup_tab, ratio, r, k, thresh1, shamt_tab, pruning);\n\n                  if (2*k > r) \n                     goto done;\n                  else \n                     goto restart;\n               } /* end of inner for loop */ \n\n            }\n\n            i--;\n            state = 1;  \n         }\n         else {\n            if (state == 0) {\n               long I_i = I[i-1] + 1;\n               I[i] = I_i;\n\n               long pruned;\n\n               if (pruning && r-I_i <= pruning) {\n                  long pos = r-I_i;\n                  unsigned long rs = ratio_sum[i-1];\n                  unsigned long index1 = (rs >> shamt_tab[pos][k-i]);\n                  if (lookup_tab[pos][k-i][index1 >> TBL_SHAMT] & (1UL << (index1&TBL_MSK)))\n                     pruned = 0;\n                  else\n                     pruned = 1;\n               }\n               else\n                  pruned = 0; \n\n               if (pruned) {\n                  i--;\n                  state = 1;\n               }\n               else {\n                  D[i] = D[i-1] + degv[I_i];\n                  ratio_sum[i] = ratio_sum[i-1] + ratio[I_i];\n                  i++;\n               }\n            }\n            else { // state == 1\n      \n               loop_cnt++;\n      \n               if (i < ProdLen)\n                  ProdLen = i;\n      \n               if (i < ProdLen1)\n                  ProdLen1 = i;\n      \n               if (i < SumLen)\n                  SumLen = i;\n\n               long I_i = (++I[i]);\n\n               if (i == 0) break;\n   \n               if (I_i > r-k+i) {\n                  i--;\n               }\n               else {\n\n                  long pruned;\n\n                  if (pruning && r-I_i <= pruning) {\n                     long pos = r-I_i;\n                     unsigned long rs = ratio_sum[i-1];\n                     unsigned long index1 = (rs >> shamt_tab[pos][k-i]);\n                     if (lookup_tab[pos][k-i][index1 >> TBL_SHAMT] & (1UL << (index1&TBL_MSK)))\n                        pruned = 0;\n                     else\n                        pruned = 1;\n                  }\n                  else\n                     pruned = 0; \n   \n\n                  if (pruned) {\n                     i--;\n                  }\n                  else {\n                     D[i] = D[i-1] + degv[I_i];\n                     ratio_sum[i] = ratio_sum[i-1] + ratio[I_i];\n                     i++;\n                     state = 0;\n                  }\n               }\n            }\n         }\n      }\n\n      restart: ;\n   }\n\n   done:\n\n   if (lookup_tab) {\n      long i, j;\n      for (i = 2; i <= init_pruning; i++) {\n         long len = min(k-1, i);\n         for (j = 2; j <= len; j++) {\n            delete [] lookup_tab[i][j];\n         }\n\n         delete [] lookup_tab[i];\n      }\n\n      delete [] lookup_tab;\n   }\n\n   if (shamt_tab) {\n      long i;\n      for (i = 2; i <= init_pruning; i++) {\n         delete [] shamt_tab[i];\n      }\n\n      delete [] shamt_tab;\n   }\n\n   if (verbose) { \n      end_time = GetTime();\n      cerr << \"\\n************ \";\n      cerr << \"end cardinality \" << k << \"\\n\";\n      cerr << \"time: \" << (end_time-start_time) << \"\\n\";\n      ZZ loops_max = choose_fn(initial_r+1, k);\n      ZZ tuples_max = choose_fn(initial_r, k);\n\n      loop_total += loop_cnt;\n      degree_total += degree_cnt;\n      n2_total += n2_cnt;\n      sl_total += sl_cnt;\n      ct_total += ct_cnt;\n      pl_total += pl_cnt;\n      c1_total += c1_cnt;\n      pl1_total += pl1_cnt;\n      td_total += td_cnt;\n\n      cerr << \"\\n\";\n      PrintInfo(\"loops: \", loop_total, loops_max);\n      PrintInfo(\"degree tests: \", degree_total, tuples_max);\n\n      PrintInfo(\"n-2 tests: \", n2_total, tuples_max);\n\n      cerr << \"ave sum len: \";\n      if (n2_total == 0) \n         cerr << \"--\";\n      else\n         cerr << (to_double(sl_total)/to_double(n2_total));\n      cerr << \"\\n\";\n\n      PrintInfo(\"f(1) tests: \", c1_total, tuples_max);\n\n      cerr << \"ave prod len: \";\n      if (c1_total == 0) \n         cerr << \"--\";\n      else\n         cerr << (to_double(pl1_total)/to_double(c1_total));\n      cerr << \"\\n\";\n\n      PrintInfo(\"f(0) tests: \", ct_total, tuples_max);\n\n      cerr << \"ave prod len: \";\n      if (ct_total == 0) \n         cerr << \"--\";\n      else\n         cerr << (to_double(pl_total)/to_double(ct_total));\n      cerr << \"\\n\";\n\n      PrintInfo(\"trial divs: \", td_total, tuples_max);\n   }\n}\n\n\n\nstatic\nvoid FindTrueFactors(vec_ZZX& factors, const ZZX& ff, \n                     const vec_ZZX& w, const ZZ& P, \n                     LocalInfoT& LocalInfo,\n                     long verbose,\n                     long bnd)\n{\n   ZZ_pBak bak;\n   bak.save();\n   ZZ_p::init(P);\n\n   long r = w.length();\n\n   vec_ZZ_pX W;\n   W.SetLength(r);\n\n   long i;\n   for (i = 0; i < r; i++)\n      conv(W[i], w[i]);\n\n\n   ZZX f;\n\n   f = ff;\n\n   long k;\n\n   k = 1;\n   factors.SetLength(0);\n   while (2*k <= W.length()) {\n      if (k <= 1)\n         CardinalitySearch(factors, f, W, LocalInfo, k, bnd, verbose);\n      else\n         CardinalitySearch1(factors, f, W, LocalInfo, k, bnd, verbose);\n      k++;\n   }\n\n   append(factors, f);\n\n   bak.restore();\n}\n\n\n\n\n\n/**********************************************************************\\\n\n                        van Hoeij's algorithm \n\n\\**********************************************************************/\n\n\n\nconst long van_hoeij_size_thresh = 12; \n// Use van Hoeij's algorithm if number of modular factors exceeds this bound.\n// Must be >= 1.\n\nconst long van_hoeij_card_thresh = 3;\n// Switch to knapsack method if cardinality of candidate factors\n// exceeds this bound.\n// Must be >= 1.\n\n\n\n\n// This routine assumes that the input f is a non-zero polynomial\n// of degree n, and returns the value f(a).\n\nstatic \nZZ PolyEval(const ZZX& f, const ZZ& a)\n{\n   if (f == 0) Error(\"PolyEval: internal error\");\n\n   long n = deg(f);\n\n   ZZ acc, t1, t2;\n   long i;\n\n   acc = f.rep[n];\n\n   for (i = n-1; i >= 0; i--) {\n      mul(t1, acc, a);\n      add(acc, t1, f.rep[i]);\n   }\n\n   return acc;\n}\n\n\n// This routine assumes that the input f is a polynomial with non-zero constant\n// term, of degree n, and with leading coefficient c; it returns \n// an upper bound on the absolute value of the roots of the\n// monic, integer polynomial g(X) =  c^{n-1} f(X/c).\n\nstatic \nZZ RootBound(const ZZX& f)\n{\n   if (ConstTerm(f) == 0) Error(\"RootBound: internal error\");\n\n   long n = deg(f);\n\n   ZZX g;\n   long i;\n\n   g = f;\n\n   if (g.rep[n] < 0) negate(g.rep[n], g.rep[n]);\n   for (i = 0; i < n; i++) {\n      if (g.rep[i] > 0) negate(g.rep[i], g.rep[i]);\n   }\n\n   ZZ lb, ub, mb;\n\n\n   lb = 0;\n\n   ub = 1;\n   while (PolyEval(g, ub) < 0) {\n      ub = 2*ub;\n   }\n\n   // lb < root <= ub\n\n   while (ub - lb > 1) {\n      ZZ mb = (ub + lb)/2;\n\n      if (PolyEval(g, mb) < 0) \n         lb = mb;\n      else \n         ub = mb;\n   }\n\n   return ub*g.rep[n];\n}\n\n\n// This routine takes as input an n x m integer matrix M, where the rows of M \n// are assumed to be linearly independent.\n// It is also required that both n and m are non-zero.\n// It computes an integer d, along with an n x m matrix R, such that\n// R*d^{-1} is the reduced row echelon form of M.\n// The routine is probabilistic: the output is always correct, but the\n// routine may abort the program with negligible probability\n// (specifically, if GenPrime returns a composite, and the modular\n// gauss routine can't invert a non-zero element).\n\nstatic\nvoid gauss(ZZ& d_out, mat_ZZ& R_out, const mat_ZZ& M)\n{\n   long n = M.NumRows();\n   long m = M.NumCols();\n\n   if (n == 0 || m == 0) Error(\"gauss: internal error\");\n\n   zz_pBak bak;\n   bak.save();\n\n   for (;;) {\n      long p = GenPrime_long(NTL_SP_NBITS);\n      zz_p::init(p);\n\n      mat_zz_p MM;\n      conv(MM, M);\n\n      long r = gauss(MM);\n      if (r < n) continue;\n\n      // compute pos(1..n), so that pos(i) is the index \n      // of the i-th pivot column\n\n      vec_long pos;\n      pos.SetLength(n);\n\n      long i, j;\n      for (i = j = 1; i <= n; i++) {\n         while (MM(i, j) == 0) j++;\n         pos(i) = j;\n         j++;\n      } \n\n      // compute the n x n sub-matrix consisting of the\n      // pivot columns of M\n\n      mat_ZZ S;\n      S.SetDims(n, n);\n\n      for (i = 1; i <= n; i++)\n         for (j = 1; j <= n; j++)\n            S(i, j) = M(i, pos(j));\n\n      mat_ZZ S_inv;\n      ZZ d;\n\n      inv(d, S_inv, S);\n      if (d == 0) continue;\n\n      mat_ZZ R;\n      mul(R, S_inv, M);\n\n      // now check that R is of the right form, which it will be\n      // if we were not unlucky\n\n      long OK = 1;\n\n      for (i = 1; i <= n && OK; i++) {\n         for (j = 1; j < pos(i) && OK; j++)\n            if (R(i, j) != 0) OK = 0;\n\n         if (R(i, pos(i)) != d) OK = 0;\n\n         for (j = 1; j < i && OK; j++)\n            if (R(j, pos(i)) != 0) OK = 0;\n      }\n\n      if (!OK) continue;\n\n      d_out = d;\n      R_out = R;\n      break;\n   }\n}\n\n\n// The input polynomial f should be monic, and deg(f) > 0.\n// The input P should be > 1.\n// Tr.length() >= d, and Tr(i), for i = 1..d-1, should be the\n// Tr_i(f) mod P (in van Hoeij's notation).\n// The quantity Tr_d(f) mod P is computed, and stored in Tr(d).\n\n\nvoid ComputeTrace(vec_ZZ& Tr, const ZZX& f, long d, const ZZ& P)\n{\n   long n = deg(f);\n\n   // check arguments\n\n   if (n <= 0 || LeadCoeff(f) != 1) \n      Error(\"ComputeTrace: internal error (1)\");\n\n   if (d <= 0)\n      Error(\"ComputeTrace: internal error (2)\");\n\n   if (Tr.length() < d)\n      Error(\"ComputeTrace: internal error (3)\");\n\n   if (P <= 1)\n      Error(\"ComputeTrace: internal error (4)\");\n\n   // treat d > deg(f) separately\n\n   if (d > n) {\n      ZZ t1, t2;\n      long i;\n\n      t1 = 0;\n\n      for (i = 1; i <= n; i++) {\n         mul(t2, Tr(i + d - n - 1), f.rep[i-1]); \n         add(t1, t1, t2);\n      }\n\n      rem(t1, t1, P);\n      NegateMod(t1, t1, P);\n      Tr(d) = t1;\n   }\n   else {\n      ZZ t1, t2;\n      long i;\n\n      mul(t1, f.rep[n-d], d);\n\n      for (i = 1; i < d; i++) {\n         mul(t2, Tr(i), f.rep[n-d+i]);\n         add(t1, t1, t2);\n      }\n\n      rem(t1, t1, P);\n      NegateMod(t1, t1, P);\n      Tr(d) = t1;\n   }\n}\n\n// Tr(1..d) are traces as computed above.\n// C and pb have length at least d.\n// For i = 1..d, pb(i) = p^{a_i} for a_i > 0.\n// pdelta = p^delta for delta > 0.\n// P = p^a for some a >= max{ a_i : i=1..d }.\n\n// This routine computes C(1..d), where \n// C(i) = C_{a_i}^{a_i + delta}( Tr(i)*lc^i ) for i = 1..d.\n\n\nvoid ChopTraces(vec_ZZ& C, const vec_ZZ& Tr, long d,\n                const vec_ZZ& pb, const ZZ& pdelta, const ZZ& P, const ZZ& lc)\n{\n   if (d <= 0) Error(\"ChopTraces: internal error (1)\");\n   if (C.length() < d) Error(\"ChopTraces: internal error (2)\");\n   if (Tr.length() < d) Error(\"ChopTraces: internal error (3)\");\n   if (pb.length() < d) Error(\"ChopTraces: internal error (4)\");\n   if (P <= 1) Error(\"ChopTraces: internal error (5)\");\n\n   ZZ lcpow, lcred;\n   lcpow = 1;\n   rem(lcred, lc, P);\n\n   ZZ pdelta_2;\n   RightShift(pdelta_2, pdelta, 1);\n\n   ZZ t1, t2;\n\n   long i;\n   for (i = 1; i <= d; i++) {\n      MulMod(lcpow, lcpow, lcred, P);\n      MulMod(t1, lcpow, Tr(i), P);\n\n      RightShift(t2, pb(i), 1);\n      add(t1, t1, t2);\n      div(t1, t1, pb(i));\n      rem(t1, t1, pdelta);\n      if (t1 > pdelta_2)\n         sub(t1, t1, pdelta);\n\n      C(i) = t1;\n   }\n}\n\n\n// Similar to above, but computes a linear combination of traces.\n\n\nstatic\nvoid DenseChopTraces(vec_ZZ& C, const vec_ZZ& Tr, long d, long d1, \n                     const ZZ& pb_eff, const ZZ& pdelta, const ZZ& P, \n                     const ZZ& lc, const mat_ZZ& A)\n{\n\n   ZZ pdelta_2;\n   RightShift(pdelta_2, pdelta, 1);\n\n   ZZ pb_eff_2;\n   RightShift(pb_eff_2, pb_eff, 1);\n\n   ZZ acc, t1, t2;\n\n   long i, j;\n\n   ZZ lcpow, lcred;\n   rem(lcred, lc, P);\n\n   for (i = 1; i <= d1; i++) {\n      lcpow = 1;\n      acc = 0;\n\n      for (j = 1; j <= d; j++) {\n         MulMod(lcpow, lcpow, lcred, P);\n         MulMod(t1, lcpow, Tr(j), P);\n         rem(t2, A(i, j), P);\n         MulMod(t1, t1, t2, P);\n         AddMod(acc, acc, t1, P);\n      }\n\n      t1 = acc;\n      add(t1, t1, pb_eff_2);\n      div(t1, t1, pb_eff);\n      rem(t1, t1, pdelta);\n      if (t1 > pdelta_2)\n         sub(t1, t1, pdelta);\n\n      C(i) = t1;\n   }\n}\n\n\nstatic\nvoid Compute_pb(vec_long& b,vec_ZZ& pb, long p, long d, \n                const ZZ& root_bound, long n)\n{\n   ZZ t1, t2;\n   long i;\n\n   t1 = 2*power(root_bound, d)*n;\n\n   if (d == 1) {\n      i = 0;\n      t2 = 1;\n   }\n   else {\n      i = b(d-1);\n      t2 = pb(d-1);\n   }\n\n   while (t2 <= t1) {\n      i++;\n      t2 *= p;\n   }\n\n   b.SetLength(d);\n   b(d) = i;\n\n   pb.SetLength(d);\n   pb(d) = t2;\n}\n\nstatic\nvoid Compute_pdelta(long& delta, ZZ& pdelta, long p, long bit_delta)\n{\n   ZZ t1;\n   long i;\n\n   i = delta;\n   t1 = pdelta;\n\n   while (NumBits(t1) <= bit_delta) {\n      i++;\n      t1 *= p;\n   }\n\n   delta = i;\n   pdelta = t1;\n}\n\nstatic\nvoid BuildReductionMatrix(mat_ZZ& M, long& C, long r, long d, const ZZ& pdelta,\n                          const vec_vec_ZZ& chop_vec, \n                          const mat_ZZ& B_L, long verbose)\n{\n   long s = B_L.NumRows();\n\n   C = long( sqrt(double(d) * double(r)) / 2.0 ) + 1;\n\n   M.SetDims(s+d, r+d);\n   clear(M);\n\n\n   long i, j, k;\n   ZZ t1, t2;\n\n   for (i = 1; i <= s; i++)\n      for (j = 1; j <= r; j++)\n         mul(M(i, j), B_L(i, j), C);\n\n   ZZ pdelta_2;\n\n   RightShift(pdelta_2, pdelta, 1);\n\n   long maxbits = 0;\n\n   for (i = 1; i <= s; i++)\n      for (j = 1; j <= d; j++) {\n         t1 = 0;\n         for (k = 1; k <= r; k++) {\n            mul(t2, B_L(i, k), chop_vec(k)(j));\n            add(t1, t1, t2);\n         }\n\n         rem(t1, t1, pdelta);\n         if (t1 > pdelta_2)\n            sub(t1, t1, pdelta);\n\n         maxbits = max(maxbits, NumBits(t1));\n\n         M(i, j+r) = t1;\n      }\n  \n\n   for (i = 1; i <= d; i++)\n      M(i+s, i+r) = pdelta;\n\n   if (verbose) \n      cerr << \"ratio = \" << double(maxbits)/double(NumBits(pdelta))\n           << \"; \";\n}\n\n\nstatic\nvoid CutAway(mat_ZZ& B1, vec_ZZ& D, mat_ZZ& M, \n             long C, long r, long d)\n{\n   long k = M.NumRows();\n   ZZ bnd = 4*to_ZZ(C)*to_ZZ(C)*to_ZZ(r) + to_ZZ(d)*to_ZZ(r)*to_ZZ(r);\n\n   while (k >= 1 && 4*D[k] > bnd*D[k-1]) k--;\n\n   mat_ZZ B2;\n\n   B2.SetDims(k, r);\n   long i, j;\n\n   for (i = 1; i <= k; i++)\n      for (j = 1; j <= r; j++)\n         div(B2(i, j), M(i, j), C);\n\n   M.kill(); // save space\n   D.kill();\n\n   ZZ det2;\n   long rnk;\n\n   rnk = image(det2, B2);\n\n   B1.SetDims(rnk, r);\n   for (i = 1; i <= rnk; i++)\n      for (j = 1; j <= r; j++)\n         B1(i, j) = B2(i + k - rnk, j);\n}\n\n\n\n\nstatic\nlong GotThem(vec_ZZX& factors, \n             const mat_ZZ& B_L,\n             const vec_ZZ_pX& W, \n             const ZZX& f, \n             long bnd,\n             long verbose)\n{\n   double tt0, tt1;\n   ZZ det;\n   mat_ZZ R;\n   long s, r;\n   long i, j, cnt;\n\n   if (verbose) {\n      cerr << \"   checking A (s = \" << B_L.NumRows() \n           << \"): gauss...\";\n   }\n\n   tt0 = GetTime();\n\n   gauss(det, R, B_L);\n\n   tt1 = GetTime();\n\n   if (verbose) cerr << (tt1-tt0) << \"; \";\n\n   // check if condition A holds\n\n   s = B_L.NumRows();\n   r = B_L.NumCols();\n\n   for (j = 0; j < r; j++) {\n      cnt = 0;\n      for (i = 0; i < s; i++) {\n         if (R[i][j] == 0) continue;\n         if (R[i][j] != det) {\n            if (verbose) cerr << \"failed.\\n\";\n            return 0;\n         }\n         cnt++;\n      }\n\n      if (cnt != 1) {\n         if (verbose) cerr << \"failed.\\n\";\n         return 0;\n      }\n   }\n\n   if (verbose) {\n      cerr << \"passed.\\n\";\n      cerr << \"   checking B...\";\n   }\n\n   // extract relevant information from R\n\n   vec_vec_long I_vec;\n   I_vec.SetLength(s);\n\n   vec_long deg_vec;\n   deg_vec.SetLength(s);\n\n   for (i = 0; i < s; i++) {\n      long dg = 0;\n\n      for (j = 0; j < r; j++) {\n         if (R[i][j] != 0) append(I_vec[i], j);\n         dg += deg(W[j]);\n      }\n\n      deg_vec[i] = dg;\n   }\n\n   R.kill(); // save space\n\n\n   // check if any candidate factor is the product of too few\n   // modular factors\n\n   for (i = 0; i < s; i++)\n      if (I_vec[i].length() <= van_hoeij_card_thresh) {\n         if (verbose) cerr << \"X\\n\";\n         return 0;\n      }\n\n   if (verbose) cerr << \"1\";\n\n\n   // sort deg_vec, I_vec in order of increasing degree\n\n   for (i = 0; i < s-1; i++)\n      for (j = 0; j < s-1-i; j++)\n         if (deg_vec[j] > deg_vec[j+1]) {\n            swap(deg_vec[j], deg_vec[j+1]);\n            swap(I_vec[j], I_vec[j+1]);\n         }\n\n\n   // perform constant term tests\n\n   ZZ ct;\n   mul(ct, LeadCoeff(f), ConstTerm(f));\n\n   ZZ half_P;\n   RightShift(half_P, ZZ_p::modulus(), 1);\n\n   ZZ_p lc, prod;\n   conv(lc, LeadCoeff(f));\n\n   ZZ t1;\n\n   for (i = 0; i < s; i++) {\n      vec_long& I = I_vec[i];\n      prod = lc;\n      for (j = 0; j < I.length(); j++)\n         mul(prod, prod, ConstTerm(W[I[j]]));\n\n      t1 = rep(prod);\n      if (t1 > half_P)\n         sub(t1, t1, ZZ_p::modulus());\n\n      if (!divide(ct, t1)) {\n          if (verbose) cerr << \"X\\n\";\n          return 0;\n      }\n   }\n\n   if (verbose) cerr << \"2\";\n\n\n   // multiply out polynomials and perform size tests\n\n   vec_ZZX fac;\n   ZZ_pX gg;\n   ZZX g;\n\n   for (i = 0; i < s-1; i++) {\n      vec_long& I = I_vec[i];\n      mul(gg, W, I);\n      mul(gg, gg, lc);\n      BalCopy(g, gg);\n      if (MaxBits(g) > bnd) {\n         if (verbose) cerr << \"X\\n\";\n         return 0;\n      }\n      PrimitivePart(g, g);\n      append(fac, g);\n   }\n\n   if (verbose) cerr << \"3\";\n\n\n   // finally...trial division\n\n   ZZX f1 = f;\n   ZZX h;\n\n   for (i = 0; i < s-1; i++) {\n      if (!divide(h, f1, fac[i])) {\n         cerr << \"X\\n\";\n         return 0;\n      }\n\n      f1 = h;\n   }\n\n   // got them!\n\n   if (verbose) cerr << \"$\\n\";\n\n   append(factors, fac);\n   append(factors, f1);\n\n   return 1;\n}\n\n\nvoid AdditionalLifting(ZZ& P1, \n                       long& e1, \n                       vec_ZZX& w1, \n                       long p, \n                       long new_bound,\n                       const ZZX& f, \n                       long doubling,\n                       long verbose)\n{\n   long new_e1;\n\n   if (doubling)\n      new_e1 = max(2*e1, new_bound); // at least double e1\n   else\n      new_e1 = new_bound;\n\n   if (verbose) {\n      cerr << \">>> additional hensel lifting to \" << new_e1 << \"...\\n\";\n   }\n\n   ZZ new_P1;\n\n   power(new_P1, p, new_e1);\n\n   ZZX f1;\n   ZZ t1, t2;\n   long i;\n   long n = deg(f);\n\n   if (LeadCoeff(f) == 1)\n      f1 = f;\n   else if (LeadCoeff(f) == -1)\n      negate(f1, f);\n   else {\n      rem(t1, LeadCoeff(f), new_P1);\n      InvMod(t1, t1, new_P1);\n      f1.rep.SetLength(n+1); \n      for (i = 0; i <= n; i++) {\n         mul(t2, f.rep[i], t1);\n         rem(f1.rep[i], t2, new_P1);\n      }\n   }\n\n   zz_pBak bak;\n   bak.save();\n\n   zz_p::init(p, NextPowerOfTwo(n)+1);\n\n   long r = w1.length();\n\n   vec_zz_pX ww1;\n   ww1.SetLength(r);\n   for (i = 0; i < r; i++)\n      conv(ww1[i], w1[i]);\n\n   w1.kill();\n\n   double tt0, tt1;\n\n   tt0 = GetTime();\n\n   MultiLift(w1, ww1, f1, new_e1, verbose);\n\n   tt1 = GetTime();\n\n   if (verbose) {\n      cerr << \"lifting time: \" << (tt1-tt0) << \"\\n\\n\";\n   }\n\n   P1 = new_P1;\n   e1 = new_e1;\n\n   bak.restore();\n}\n\nstatic\nvoid Compute_pb_eff(long& b_eff, ZZ& pb_eff, long p, long d, \n                    const ZZ& root_bound,  \n                    long n, long ran_bits)\n{\n   ZZ t1, t2;\n   long i;\n\n   if (root_bound == 1)\n      t1 = (to_ZZ(d)*to_ZZ(n)) << (ran_bits + 1);\n   else\n      t1 = (power(root_bound, d)*n) << (ran_bits + 2);\n\n   i = 0;\n   t2 = 1;\n\n   while (t2 <= t1) {\n      i++;\n      t2 *= p;\n   }\n\n   b_eff = i;\n   pb_eff = t2;\n}\n\n\n\nstatic\nlong d1_val(long bit_delta, long r, long s)\n{\n   return long( 0.30*double(r)*double(s)/double(bit_delta) ) + 1;\n}\n\n\n\n\n// Next comes van Hoeij's algorithm itself.\n// Some notation that differs from van Hoeij's paper:\n//   n = deg(f)\n//   r = # modular factors\n//   s = dim(B_L)  (gets smaller over time)\n//   d = # traces used\n//   d1 = number of \"compressed\" traces\n//\n// The algorithm starts with a \"sparse\" version of van Hoeij, so that\n// at first the traces d = 1, 2, ... are used in conjunction with\n// a d x d identity matrix for van Hoeij's matrix A.\n// The number of \"excess\" bits used for each trace, bit_delta, is initially\n// 2*r.\n// \n// When d*bit_delta exceeds 0.25*r*s, we switch to \n// a \"dense\" mode, where we use only about 0.25*r*s \"compressed\" traces.\n// These bounds follow from van Hoeij's heuristic estimates.\n//\n// In sparse mode, d and bit_delta increase exponentially (but gently).\n// In dense mode, but d increases somewhat more aggressively,\n// and bit_delta is increased more gently.\n\n\nstatic\nvoid FindTrueFactors_vH(vec_ZZX& factors, const ZZX& ff, \n                        const vec_ZZX& w, const ZZ& P, \n                        long p, long e,\n                        LocalInfoT& LocalInfo,\n                        long verbose,\n                        long bnd)\n{\n   const long SkipSparse = 0;\n\n   ZZ_pBak bak;\n   bak.save();\n   ZZ_p::init(P);\n\n   long r = w.length();\n\n   vec_ZZ_pX W;\n   W.SetLength(r);\n\n   long i, j;\n\n   for (i = 0; i < r; i++)\n      conv(W[i], w[i]);\n\n\n   ZZX f;\n\n   f = ff;\n\n   long k;\n\n   k = 1;\n   factors.SetLength(0);\n   while (2*k <= W.length() && \n      (k <= van_hoeij_card_thresh || W.length() <= van_hoeij_size_thresh)) {\n\n      if (k <= 1)\n         CardinalitySearch(factors, f, W, LocalInfo, k, bnd, verbose);\n      else\n         CardinalitySearch1(factors, f, W, LocalInfo, k, bnd, verbose);\n      k++;\n   }\n\n   if (2*k > W.length()) {\n      // rest is irreducible, so we're done\n\n      append(factors, f);\n   }\n   else {\n\n      // now we apply van Hoeij's algorithm proper to f\n   \n      double time_start, time_stop, lll_time, tt0, tt1;\n\n      time_start = GetTime();\n      lll_time = 0;\n   \n      if (verbose) {\n         cerr << \"\\n\\n*** starting knapsack procedure\\n\";\n      }\n   \n      ZZ P1 = P;\n      long e1 = e;    // invariant: P1 = p^{e1}\n   \n      r = W.length();\n   \n      vec_ZZX w1;\n      w1.SetLength(r);\n      for (i = 0; i < r; i++)\n         conv(w1[i], W[i]);\n   \n      long n = deg(f);\n   \n      mat_ZZ B_L;            // van Hoeij's lattice\n      ident(B_L, r);\n   \n      long d = 0;            // number of traces\n      \n      long bit_delta = 0;    // number of \"excess\" bits\n\n      vec_long b;\n      vec_ZZ pb;             // pb(i) = p^{b(i)}\n\n      long delta = 0;\n      ZZ pdelta = to_ZZ(1);  // pdelta = p^delta\n      pdelta = 1;\n   \n      vec_vec_ZZ trace_vec;\n      trace_vec.SetLength(r);\n   \n      vec_vec_ZZ chop_vec;\n      chop_vec.SetLength(r);\n   \n      ZZ root_bound = RootBound(f);\n   \n      if (verbose) {\n         cerr << \"NumBits(root_bound) = \" << NumBits(root_bound) << \"\\n\";\n      }\n\n      long dense = 0;\n      long ran_bits = 32;\n\n      long loop_cnt = 0;\n\n\n      long s = r;\n\n      for (;;) {\n\n         loop_cnt++;\n   \n         // if we are using the power hack, then we do not try too hard...\n         // this is really a hack on a hack!\n\n         if (ok_to_abandon && \n             ((d >= 2 && s > 128) || (d >= 3 && s > 32) || (d >= 4 && s > 8) ||\n              d >= 5) ) {\n            if (verbose) cerr << \"   abandoning\\n\";\n            append(factors, f);\n            break;\n         }\n\n         long d_last, d_inc, d_index;\n\n         d_last = d;\n\n         // set d_inc: \n\n         if (!dense) {\n            d_inc = 1 + d/8;\n         }\n         else {\n            d_inc = 1 + d/4; \n         }\n\n         d_inc = min(d_inc, n-1-d);\n            \n         d += d_inc;\n\n         // set bit_delta:\n   \n         if (bit_delta == 0) {\n            // set initial value...don't make it any smaller than 2*r\n\n            bit_delta = 2*r; \n         }\n         else {\n            long extra_bits;\n\n            if (!dense) {\n               extra_bits = 1 + bit_delta/8;\n            }\n            else if (d_inc != 0) {\n               if (d1_val(bit_delta, r, s) > 1)\n                  extra_bits = 1 + bit_delta/16; \n               else\n                  extra_bits = 0;\n            }\n            else\n               extra_bits = 1 + bit_delta/8;\n\n            bit_delta += extra_bits;\n         }\n\n         if (d > d1_val(bit_delta, r, s)) \n            dense = 1;\n   \n         Compute_pdelta(delta, pdelta, p, bit_delta);\n\n         long d1;\n         long b_eff;\n         ZZ pb_eff;\n\n         if (!dense) {\n            for (d_index = d_last + 1; d_index <= d; d_index++)\n               Compute_pb(b, pb, p, d_index, root_bound, n);\n\n            d1 = d;\n            b_eff = b(d);\n            pb_eff = pb(d);\n         }\n         else {\n            d1 = d1_val(bit_delta, r, s);\n            Compute_pb_eff(b_eff, pb_eff, p, d, root_bound, n, ran_bits); \n         }\n\n         if (verbose) {\n            cerr << \"*** d = \" << d \n                 << \"; s = \" << s \n                 << \"; delta = \" << delta \n                 << \"; b_eff = \" << b_eff;\n\n            if (dense) cerr << \"; dense [\" << d1 << \"]\";\n            cerr << \"\\n\";\n         }\n   \n         if (b_eff + delta > e1) {\n            long doubling;\n\n            doubling = 1;\n\n            AdditionalLifting(P1, e1, w1, p, b_eff + delta, f, \n                              doubling, verbose);\n\n            if (verbose) {\n               cerr << \">>> recomputing traces...\";\n            }\n\n            tt0 = GetTime();\n\n            trace_vec.kill();\n            trace_vec.SetLength(r);\n\n            for (i = 0; i < r; i++) {\n               trace_vec[i].SetLength(d_last);\n\n               for (d_index = 1; d_index <= d_last; d_index++) {\n                  ComputeTrace(trace_vec[i], w1[i], d_index, P1);\n               }\n            }\n\n            tt1 = GetTime();\n            if (verbose) cerr << (tt1-tt0) << \"\\n\";\n         }\n   \n         if (verbose) cerr << \"   trace...\"; \n   \n         tt0 = GetTime();\n\n         mat_ZZ A;\n\n         if (dense) {\n            A.SetDims(d1, d);\n            for (i = 1; i <= d1; i++)\n               for (j = 1; j <= d; j++) {\n                  RandomBits(A(i, j), ran_bits);\n                  if (RandomBnd(2)) negate(A(i, j), A(i, j));\n               }\n         }\n      \n   \n         for (i = 0; i < r; i++) {\n            trace_vec[i].SetLength(d);\n            for (d_index = d_last + 1; d_index <= d; d_index++)\n               ComputeTrace(trace_vec[i], w1[i], d_index, P1);\n   \n            chop_vec[i].SetLength(d1);\n\n            if (!dense)\n               ChopTraces(chop_vec[i], trace_vec[i], d, pb, pdelta, \n                          P1, LeadCoeff(f));\n            else\n               DenseChopTraces(chop_vec[i], trace_vec[i], d, d1, pb_eff, \n                               pdelta, P1, LeadCoeff(f), A);\n         }\n\n         A.kill();\n   \n         tt1 = GetTime();\n   \n         if (verbose) cerr << (tt1-tt0) << \"\\n\";\n   \n         mat_ZZ M;\n         long C;\n   \n         if (verbose) cerr << \"   building matrix...\";\n   \n         tt0 = GetTime();\n   \n         BuildReductionMatrix(M, C, r, d1, pdelta, chop_vec, B_L, verbose);\n   \n         tt1 = GetTime();\n   \n         if (verbose) cerr << (tt1-tt0) << \"\\n\";\n\n         if (SkipSparse) {   \n            if (!dense) {\n               if (verbose) cerr << \"skipping LLL\\n\";\n               continue;\n            }\n         }\n\n         if (verbose) cerr << \"   LLL...\";\n   \n         tt0 = GetTime();\n   \n         vec_ZZ D;\n         long rnk = LLL_plus(D, M);\n   \n         tt1 = GetTime();\n\n         lll_time += (tt1-tt0);\n   \n         if (verbose) cerr << (tt1-tt0) << \"\\n\";\n   \n         if (rnk != s + d1) {\n            Error(\"van Hoeij -- bad rank\");\n         }\n   \n         mat_ZZ B1;\n   \n         if (verbose) cerr << \"   CutAway...\";\n   \n         tt0 = GetTime();\n   \n         CutAway(B1, D, M, C, r, d1);\n   \n         tt1 = GetTime();\n   \n         if (verbose) cerr << (tt1-tt0) << \"\\n\";\n   \n         if (B1.NumRows() >= s) continue;\n         // no progress...try again\n\n         // otherwise, update B_L and test if we are done\n   \n         swap(B1, B_L);\n         B1.kill();\n         s = B_L.NumRows();\n   \n         if (s == 0)\n            Error(\"oops! s == 0 should not happen!\");\n   \n         if (s == 1) {\n            if (verbose) cerr << \"   irreducible!\\n\";\n            append(factors, f);\n            break;\n         }\n   \n         if (s > r / (van_hoeij_card_thresh + 1)) continue;\n         // dimension too high...we can't be done\n   \n         if (GotThem(factors, B_L, W, f, bnd, verbose)) break;\n      }\n\n      time_stop = GetTime();\n\n      if (verbose) {\n         cerr << \"*** knapsack finished: total time = \" \n              << (time_stop - time_start) << \"; LLL time = \"\n              << lll_time << \"\\n\";\n      }\n   }\n\n   bak.restore();\n}\n\n\nstatic\nvoid ll_SFFactor(vec_ZZX& factors, const ZZX& ff, \n                 long verbose,\n                 long bnd)\n\n// input is primitive and square-free, with positive leading\n// coefficient\n{\n   if (deg(ff) <= 1) {\n      factors.SetLength(1);\n      factors[0] = ff;\n      if (verbose) {\n         cerr << \"*** SFFactor, trivial case 1.\\n\";\n      }\n      return;\n   }\n\n   // remove a factor of X, if necessary\n\n   ZZX f;\n   long xfac;\n   long rev;\n\n   double t;\n\n   if (IsZero(ConstTerm(ff))) {\n      RightShift(f, ff, 1);\n      xfac = 1;\n   }\n   else {\n      f = ff;\n      xfac = 0;\n   }\n\n   // return a factor of X-1 if necessary\n\n   long x1fac = 0;\n\n   ZZ c1;\n   SumCoeffs(c1, f);\n\n   if (c1 == 0) {\n      x1fac = 1;\n      div(f, f, ZZX(1,1) - 1);\n   }\n\n   SumCoeffs(c1, f);\n\n   if (deg(f) <= 1) {\n      long r = 0;\n      factors.SetLength(0);\n      if (deg(f) > 0) {\n         factors.SetLength(r+1);\n         factors[r] = f;\n         r++;\n      }\n      if (xfac) {\n         factors.SetLength(r+1);\n         SetX(factors[r]);\n         r++;\n      }\n\n      if (x1fac) {\n         factors.SetLength(r+1);\n         factors[r] = ZZX(1,1) - 1;\n         r++;\n      }\n\n      if (verbose) {\n         cerr << \"*** SFFactor: trivial case 2.\\n\";\n      }\n\n      return;\n   }\n\n   if (verbose) {\n      cerr << \"*** start SFFactor.\\n\";\n   }\n\n   // reverse f if this makes lead coefficient smaller\n\n   ZZ t1, t2;\n\n   abs(t1, LeadCoeff(f));\n   abs(t2, ConstTerm(f));\n\n   if (t1 > t2) {\n      inplace_rev(f);\n      rev = 1;\n   }\n   else \n      rev = 0;\n\n   // obtain factorization modulo small primes\n\n   if (verbose) {\n      cerr << \"factorization modulo small primes...\\n\";\n      t = GetTime();\n   }\n\n   LocalInfoT LocalInfo;\n\n   zz_pBak bak;\n   bak.save();\n\n   vec_zz_pX *spfactors =\n       SmallPrimeFactorization(LocalInfo, f, verbose);\n\n   if (!spfactors) {\n      // f was found to be irreducible \n\n      bak.restore();\n\n      if (verbose) {\n         t = GetTime()-t;\n         cerr << \"small prime time: \" << t << \", irreducible.\\n\";\n      }\n\n      if (rev)\n         inplace_rev(f);\n\n      long r = 0;\n\n      factors.SetLength(r+1);\n      factors[r] = f;\n      r++;\n\n      if (xfac) {\n         factors.SetLength(r+1);\n         SetX(factors[r]);\n         r++;\n      }\n\n      if (x1fac) {\n         factors.SetLength(r+1);\n         factors[r] = ZZX(1,1) - 1;\n         r++;\n      }\n\n      return;\n   }\n\n   if (verbose) {\n      t = GetTime()-t;\n      cerr << \"small prime time: \";\n      cerr << t << \", number of factors = \" << spfactors->length() << \"\\n\";\n   }\n\n   // prepare for Hensel lifting\n\n   // first, calculate bit bound \n\n   long bnd1;\n   long n = deg(f);\n   long i;\n   long e;\n   ZZ P;\n   long p;\n   \n   bnd1 = MaxBits(f) + (NumBits(n+1)+1)/2;\n\n   if (!bnd || bnd1 < bnd)\n      bnd = bnd1;\n\n   i = n/2;\n   while (!bit(LocalInfo.PossibleDegrees, i))\n      i--;\n\n   long lc_bnd = NumBits(LeadCoeff(f));\n\n   long coeff_bnd = bnd + lc_bnd + i;\n\n   long lift_bnd;\n\n   lift_bnd = coeff_bnd + 15;  \n   // +15 helps avoid trial divisions...can be any number >= 0\n\n   lift_bnd = max(lift_bnd, bnd + lc_bnd + 2*NumBits(n) + ZZX_OVERLIFT);\n   // facilitates \"n-1\" and \"n-2\" tests\n\n   lift_bnd = max(lift_bnd, lc_bnd + NumBits(c1));\n   // facilitates f(1) test\n\n   lift_bnd += 2;\n   // +2 needed to get inequalities right\n\n\n   p = zz_p::modulus();\n\n   e = long(double(lift_bnd)/(log(double(p))/log(double(2))));\n   power(P, p, e);\n\n   while (NumBits(P) <= lift_bnd) { \n      mul(P, P, p);\n      e++;\n   }\n\n   if (verbose) {\n      cerr << \"lifting bound = \" << lift_bnd << \" bits.\\n\";\n      cerr << \"Hensel lifting to exponent \" << e << \"...\\n\";\n      t = GetTime();\n   }\n\n   // third, compute f1 so that it is monic and equal to f mod P\n\n   ZZX f1;\n\n   if (LeadCoeff(f) == 1)\n      f1 = f;\n   else if (LeadCoeff(f) == -1)\n      negate(f1, f);\n   else {\n      rem(t1, LeadCoeff(f), P);\n      if (sign(P) < 0)\n         Error(\"whoops!!!\");\n      InvMod(t1, t1, P);\n      f1.rep.SetLength(n+1);\n      for (i = 0; i <= n; i++) {\n         mul(t2, f.rep[i], t1);\n         rem(f1.rep[i], t2, P);\n      }\n   }\n\n\n   // Do Hensel lift\n\n   vec_ZZX w;\n\n   MultiLift(w, *spfactors, f1, e, verbose);\n\n\n   if (verbose) {\n      t = GetTime()-t;\n      cerr << \"\\nlifting time: \";\n      cerr << t << \"\\n\\n\";\n   }\n\n   // We're done with zz_p...restore\n\n   delete spfactors;\n   bak.restore();\n\n   // search for true factors\n\n   if (verbose) {\n      cerr << \"searching for true factors...\\n\";\n      t = GetTime();\n   }\n\n   if (ZZXFac_van_Hoeij && w.length() > van_hoeij_size_thresh)\n      FindTrueFactors_vH(factors, f, w, P, p, e, \n                         LocalInfo, verbose, coeff_bnd);\n   else\n      FindTrueFactors(factors, f, w, P, LocalInfo, verbose, coeff_bnd);\n\n   if (verbose) {\n      t = GetTime()-t;\n      cerr << \"factor search time \" << t << \"\\n\";\n   }\n\n   long r = factors.length();\n\n   if (rev) {\n      for (i = 0; i < r; i++) {\n         inplace_rev(factors[i]);\n         if (sign(LeadCoeff(factors[i])) < 0)\n            negate(factors[i], factors[i]);\n      }\n   }\n\n   if (xfac) {\n      factors.SetLength(r+1);\n      SetX(factors[r]);\n      r++;\n   }\n\n   if (x1fac) {\n      factors.SetLength(r+1);\n      factors[r] = ZZX(1,1)-1;\n      r++;\n   }\n\n   // that's it!!\n\n   if (verbose) {\n      cerr << \"*** end SFFactor.  degree sequence:\\n\";\n      for (i = 0; i < r; i++)\n         cerr << deg(factors[i]) << \" \";\n      cerr << \"\\n\";\n   }\n}\n\n\n\nstatic \nlong DeflationFactor(const ZZX& f)\n{\n   long n = deg(f);\n   long m = 0;\n   long i;\n\n   for (i = 1; i <= n && m != 1; i++) {\n      if (f.rep[i] != 0)\n         m = GCD(m, i);\n   }\n\n   return m;\n}\n\nstatic\nvoid inflate(ZZX& g, const ZZX& f, long m)\n// input may not alias output\n{\n   long n = deg(f);\n   long i;\n\n   g = 0;\n   for (i = n; i >= 0; i--) \n      SetCoeff(g, i*m, f.rep[i]);\n}\n\nstatic\nvoid deflate(ZZX& g, const ZZX& f, long m)\n// input may not alias output\n{\n   long n = deg(f);\n   long i;\n\n   g = 0;\n   for (i = n; i >= 0; i -= m) \n      SetCoeff(g, i/m, f.rep[i]);\n}\n\nstatic\nvoid MakeFacList(vec_long& v, long m)\n{\n   if (m <= 0) Error(\"internal error: MakeFacList\");\n\n   v.SetLength(0);\n\n   long p = 2;\n   while (m > 1) {\n      while (m % p == 0)  {\n         append(v, p);\n         m = m / p;\n      }\n\n      p++;\n   }\n}\n\nlong ZZXFac_PowerHack = 1;\n\nvoid SFFactor(vec_ZZX& factors, const ZZX& ff, \n              long verbose,\n              long bnd)\n\n// input is primitive and square-free, with positive leading\n// coefficient\n\n{\n   if (ff == 0) \n      Error(\"SFFactor: bad args\");\n\n   if (deg(ff) <= 0) {\n      factors.SetLength(0);\n      return;\n   }\n\n\n   if (!ZZXFac_PowerHack) {\n      ok_to_abandon = 0;\n      ll_SFFactor(factors, ff, verbose, bnd);\n      return;\n   }\n\n   long m = DeflationFactor(ff);\n\n   if (m == 1) {\n      if (verbose) {\n         cerr << \"SFFactor -- no deflation\\n\";\n      }\n\n      ok_to_abandon = 0;\n      ll_SFFactor(factors, ff, verbose, bnd);\n      return;\n   }\n\n\n   vec_long v;\n   MakeFacList(v, m);\n   long l = v.length();\n\n   if (verbose) {\n      cerr << \"SFFactor -- deflation: \" << v << \"\\n\";\n   }\n\n   vec_ZZX res;\n   res.SetLength(1);\n   deflate(res[0], ff, m);\n\n   long done;\n   long j, k;\n\n   done = 0;\n   k = l-1;\n\n   while (!done) {\n      vec_ZZX res1;\n      res1.SetLength(0);\n      for (j = 0; j < res.length(); j++) {\n         vec_ZZX res2;\n         double t;\n         if (verbose) {\n            cerr << \"begin - step \" << k << \", \" << j << \"; deg = \" \n                 << deg(res[j]) << \"\\n\";\n            t = GetTime();\n         }\n\n         if (k < 0)\n            ok_to_abandon = 0;\n         else\n            ok_to_abandon = 1;\n\n         ll_SFFactor(res2, res[j], verbose, k < 0 ? bnd : 0);\n\n         if (verbose) {\n            t = GetTime()-t;\n            cerr << \"end   - step \" << k << \", \" << j << \"; time = \"\n                 << t << \"\\n\\n\";\n         }\n\n         append(res1, res2);\n      }\n\n      if (k < 0) {\n         done = 1;\n         swap(res, res1);\n      }\n      else {\n         vec_ZZX res2;\n         res2.SetLength(res1.length());\n         for (j = 0; j < res1.length(); j++)\n            inflate(res2[j], res1[j], v[k]);\n         k--;\n         swap(res, res2);\n      }\n   }\n\n   factors = res;\n}\n\n\n\n\n\nvoid factor(ZZ& c,\n            vec_pair_ZZX_long& factors,\n            const ZZX& f,\n            long verbose,\n            long bnd)\n\n{\n   ZZX ff = f;\n\n   if (deg(ff) <= 0) {\n      c = ConstTerm(ff);\n      factors.SetLength(0);\n      return;\n   }\n\n   content(c, ff);\n   divide(ff, ff, c);\n\n   long bnd1 = MaxBits(ff) + (NumBits(deg(ff)+1)+1)/2;\n   if (!bnd || bnd > bnd1)\n      bnd = bnd1;\n\n   vec_pair_ZZX_long sfd;\n\n   double t;\n\n   if (verbose) { cerr << \"square-free decomposition...\"; t = GetTime(); }\n   SquareFreeDecomp(sfd, ff);\n   if (verbose) cerr << (GetTime()-t) << \"\\n\";\n\n   factors.SetLength(0);\n\n   vec_ZZX x;\n\n   long i, j;\n\n   for (i = 0; i < sfd.length(); i++) {\n      if (verbose) {\n         cerr << \"factoring multiplicity \" << sfd[i].b\n              << \", deg = \" << deg(sfd[i].a) << \"\\n\";\n         t = GetTime();\n      }\n\n      SFFactor(x, sfd[i].a, verbose, bnd);\n\n      if (verbose) {\n         t = GetTime()-t;\n         cerr << \"total time for multiplicity \" \n              << sfd[i].b << \": \" << t << \"\\n\";\n      }\n\n      for (j = 0; j < x.length(); j++)\n         append(factors, cons(x[j], sfd[i].b));\n   }\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "a9254772c2908d22040456bc87b3f5294bdc998c", "size": 79186, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/ZZXFactoring.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RUNETag/WinNTL/src/ZZXFactoring.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/src/ZZXFactoring.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 20.4826694258, "max_line_length": 116, "alphanum_fraction": 0.4570378602, "num_tokens": 24548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4432500267945186}}
{"text": "// SPDX-License-Identifier: MIT\n// Copyright 2021 Ricerca Security, Inc.\n\n#include <cstdint>\n#include <vector>\n#include <iterator>\n#include <iostream>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/phoenix.hpp>\n\nnamespace qi {\n  template <typename InputIterator>\n  class calc : public boost::spirit::qi::grammar< InputIterator, int() > {\n    enum class op_t {\n      add,\n      sub,\n      mul,\n      div,\n      mod\n    };\n    public:\n      calc() : calc::base_type( l2 ) {\n        namespace qi = boost::spirit::qi;\n        namespace phx = boost::phoenix;\n        l0 = qi::skip( qi::standard::space )[\n          ( '(' >> l2 >> ')' ) | qi::int_\n        ];\n        l1oper.add\n          ( \"*\", op_t::mul )\n          ( \"/\", op_t::div )\n          ( \"%\", op_t::mod );\n        l2oper.add\n          ( \"+\", op_t::add )\n          ( \"-\", op_t::sub );\n        l1 = qi::skip( qi::standard::space )[\n          ( l0 >> *( l1oper >> l0 ) )[ qi::_pass = phx::bind( &calc::calculate, qi::_val, qi::_1, qi::_2 ) ]\n        ];\n        l2 = qi::skip( qi::standard::space )[\n          ( l1 >> *( l2oper >> l1 ) )[ qi::_pass = phx::bind( &calc::calculate, qi::_val, qi::_1, qi::_2 ) ]\n        ];\n      }\n    private:\n      static bool calculate( int &dest, int head, const std::vector< boost::fusion::vector< op_t, int > > &tail ) {\n        dest = head;\n        for( const auto &v: tail ) {\n          const auto op = boost::fusion::at_c< 0 >( v );\n          const auto right = boost::fusion::at_c< 1 >( v );\n          if( op == op_t::add ) dest += right;\n          else if( op == op_t::sub ) dest -= right;\n          else if( op == op_t::mul ) dest *= right;\n          else if( op == op_t::div ) dest /= right;\n          else if( op == op_t::mod ) dest %= right;\n        }\n        return true;\n      }\n      boost::spirit::qi::symbols< char, op_t > l1oper;\n      boost::spirit::qi::symbols< char, op_t > l2oper;\n      boost::spirit::qi::rule< InputIterator, int() > l0;\n      boost::spirit::qi::rule< InputIterator, int() > l1;\n      boost::spirit::qi::rule< InputIterator, int() > l2;\n  };\n}\nint main() {\n  std::vector< char > data(\n    std::istreambuf_iterator< char >{ std::cin },\n    std::istreambuf_iterator< char >{}\n  );\n  int parsed;\n  {\n    const qi::calc< std::vector< char >::const_iterator > rule;\n    auto iter = data.cbegin();\n    if( !boost::spirit::qi::parse( iter, data.cend(), rule, parsed ) )\n      return 1;\n  }\n  std::cout << parsed << std::flush;\n}\n\n", "meta": {"hexsha": "d80b7567d5b0e788e7828b1ac9414a5315b8d761", "size": 2454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/calc/calc.cpp", "max_stars_repo_name": "fuzzuf/fuzz_toys", "max_stars_repo_head_hexsha": "e2952a17f54653e4ff8a9d1d3f96e6b46d70e8bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T02:48:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T02:48:00.000Z", "max_issues_repo_path": "src/calc/calc.cpp", "max_issues_repo_name": "fuzzuf/fuzz_toys", "max_issues_repo_head_hexsha": "e2952a17f54653e4ff8a9d1d3f96e6b46d70e8bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/calc/calc.cpp", "max_forks_repo_name": "fuzzuf/fuzz_toys", "max_forks_repo_head_hexsha": "e2952a17f54653e4ff8a9d1d3f96e6b46d70e8bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-03T07:22:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T07:22:15.000Z", "avg_line_length": 31.4615384615, "max_line_length": 115, "alphanum_fraction": 0.5191524042, "num_tokens": 716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4431726198312635}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2013 John Maddock\n//  Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_BERNOULLI_DETAIL_HPP_\n#define BOOST_MATH_BERNOULLI_DETAIL_HPP_\n\n#include \"../math_fwd.hpp\"\n#include <boost/config.hpp>\n#include <boost/detail/lightweight_mutex.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/math/tools/toms748_solve.hpp>\n\n#ifdef BOOST_HAS_THREADS\n\n#ifndef BOOST_NO_CXX11_HDR_ATOMIC\n#  include <atomic>\n#  define BOOST_MATH_ATOMIC_NS std\n#if ATOMIC_INT_LOCK_FREE == 2\ntypedef std::atomic<int> atomic_counter_type;\ntypedef int atomic_integer_type;\n#elif ATOMIC_SHORT_LOCK_FREE == 2\ntypedef std::atomic<short> atomic_counter_type;\ntypedef short atomic_integer_type;\n#elif ATOMIC_LONG_LOCK_FREE == 2\ntypedef std::atomic<long> atomic_counter_type;\ntypedef long atomic_integer_type;\n#elif ATOMIC_LLONG_LOCK_FREE == 2\ntypedef std::atomic<long long> atomic_counter_type;\ntypedef long long atomic_integer_type;\n#else\n#  define BOOST_MATH_NO_ATOMIC_INT\n#endif\n\n#else // BOOST_NO_CXX11_HDR_ATOMIC\n//\n// We need Boost.Atomic, but on any platform that supports auto-linking we do\n// not need to link against a separate library:\n//\n#define BOOST_ATOMIC_NO_LIB\n#include <boost/atomic.hpp>\n#  define BOOST_MATH_ATOMIC_NS boost\n\nnamespace boost{ namespace math{ namespace detail{\n\n//\n// We need a type to use as an atomic counter:\n//\n#if BOOST_ATOMIC_INT_LOCK_FREE == 2\ntypedef boost::atomic<int> atomic_counter_type;\ntypedef int atomic_integer_type;\n#elif BOOST_ATOMIC_SHORT_LOCK_FREE == 2\ntypedef boost::atomic<short> atomic_counter_type;\ntypedef short atomic_integer_type;\n#elif BOOST_ATOMIC_LONG_LOCK_FREE == 2\ntypedef boost::atomic<long> atomic_counter_type;\ntypedef long atomic_integer_type;\n#elif BOOST_ATOMIC_LLONG_LOCK_FREE == 2\ntypedef boost::atomic<long long> atomic_counter_type;\ntypedef long long atomic_integer_type;\n#else\n#  define BOOST_MATH_NO_ATOMIC_INT\n#endif\n\n}}} // namespaces\n\n#endif  // BOOST_NO_CXX11_HDR_ATOMIC\n\n#endif // BOOST_HAS_THREADS\n\nnamespace boost{ namespace math{ namespace detail{\n//\n// Asymptotic expansion for B2n due to\n// Luschny LogB3 formula (http://www.luschny.de/math/primes/bernincl.html)\n//\ntemplate <class T, class Policy>\nT b2n_asymptotic(int n)\n{\n   BOOST_MATH_STD_USING\n   const T nx = static_cast<T>(n);\n   const T nx2(nx * nx);\n\n   const T approximate_log_of_bernoulli_bn =\n        ((boost::math::constants::half<T>() + nx) * log(nx))\n        + ((boost::math::constants::half<T>() - nx) * log(boost::math::constants::pi<T>()))\n        + (((T(3) / 2) - nx) * boost::math::constants::ln_two<T>())\n        + ((nx * (T(2) - (nx2 * 7) * (1 + ((nx2 * 30) * ((nx2 * 12) - 1))))) / (((nx2 * nx2) * nx2) * 2520));\n   return ((n / 2) & 1 ? 1 : -1) * (approximate_log_of_bernoulli_bn > tools::log_max_value<T>()\n      ? policies::raise_overflow_error<T>(\"boost::math::bernoulli_b2n<%1%>(std::size_t)\", 0, nx, Policy())\n      : static_cast<T>(exp(approximate_log_of_bernoulli_bn)));\n}\n\ntemplate <class T, class Policy>\nT t2n_asymptotic(int n)\n{\n   BOOST_MATH_STD_USING\n   // Just get B2n and convert to a Tangent number:\n   T t2n = fabs(b2n_asymptotic<T, Policy>(2 * n)) / (2 * n);\n   T p2 = ldexp(T(1), n);\n   if(tools::max_value<T>() / p2 < t2n)\n      return policies::raise_overflow_error<T>(\"boost::math::tangent_t2n<%1%>(std::size_t)\", 0, T(n), Policy());\n   t2n *= p2;\n   p2 -= 1;\n   if(tools::max_value<T>() / p2 < t2n)\n      return policies::raise_overflow_error<T>(\"boost::math::tangent_t2n<%1%>(std::size_t)\", 0, Policy());\n   t2n *= p2;\n   return t2n;\n}\n//\n// We need to know the approximate value of /n/ which will\n// cause bernoulli_b2n<T>(n) to return infinity - this allows\n// us to elude a great deal of runtime checking for values below\n// n, and only perform the full overflow checks when we know that we're\n// getting close to the point where our calculations will overflow.\n// We use Luschny's LogB3 formula (http://www.luschny.de/math/primes/bernincl.html)\n// to find the limit, and since we're dealing with the log of the Bernoulli numbers\n// we need only perform the calculation at double precision and not with T\n// (which may be a multiprecision type).  The limit returned is within 1 of the true\n// limit for all the types tested.  Note that although the code below is basically\n// the same as b2n_asymptotic above, it has been recast as a continuous real-valued\n// function as this makes the root finding go smoother/faster.  It also omits the\n// sign of the Bernoulli number.\n//\nstruct max_bernoulli_root_functor\n{\n   max_bernoulli_root_functor(long long t) : target(static_cast<double>(t)) {}\n   double operator()(double n)\n   {\n      BOOST_MATH_STD_USING\n\n      // Luschny LogB3(n) formula.\n\n      const double nx2(n * n);\n\n      const double approximate_log_of_bernoulli_bn\n         =   ((boost::math::constants::half<double>() + n) * log(n))\n           + ((boost::math::constants::half<double>() - n) * log(boost::math::constants::pi<double>()))\n           + (((double(3) / 2) - n) * boost::math::constants::ln_two<double>())\n           + ((n * (2 - (nx2 * 7) * (1 + ((nx2 * 30) * ((nx2 * 12) - 1))))) / (((nx2 * nx2) * nx2) * 2520));\n\n      return approximate_log_of_bernoulli_bn - target;\n   }\nprivate:\n   double target;\n};\n\ntemplate <class T, class Policy>\ninline std::size_t find_bernoulli_overflow_limit(const mpl::false_&)\n{\n   long long t = lltrunc(boost::math::tools::log_max_value<T>());\n   max_bernoulli_root_functor fun(t);\n   boost::math::tools::equal_floor tol;\n   boost::uintmax_t max_iter = boost::math::policies::get_max_root_iterations<Policy>();\n   return static_cast<std::size_t>(boost::math::tools::toms748_solve(fun, sqrt(double(t)), double(t), tol, max_iter).first) / 2;\n}\n\ntemplate <class T, class Policy>\ninline std::size_t find_bernoulli_overflow_limit(const mpl::true_&)\n{\n   return max_bernoulli_index<bernoulli_imp_variant<T>::value>::value;\n}\n\ntemplate <class T, class Policy>\nstd::size_t b2n_overflow_limit()\n{\n   // This routine is called at program startup if it's called at all:\n   // that guarantees safe initialization of the static variable.\n   typedef mpl::bool_<(bernoulli_imp_variant<T>::value >= 1) && (bernoulli_imp_variant<T>::value <= 3)> tag_type;\n   static const std::size_t lim = find_bernoulli_overflow_limit<T, Policy>(tag_type());\n   return lim;\n}\n\n//\n// The tangent numbers grow larger much more rapidly than the Bernoulli numbers do....\n// so to compute the Bernoulli numbers from the tangent numbers, we need to avoid spurious\n// overflow in the calculation, we can do this by scaling all the tangent number by some scale factor:\n//\ntemplate <class T>\ninline typename enable_if_c<std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::radix == 2), T>::type tangent_scale_factor()\n{\n   BOOST_MATH_STD_USING\n   return ldexp(T(1), std::numeric_limits<T>::min_exponent + 5);\n}\ntemplate <class T>\ninline typename disable_if_c<std::numeric_limits<T>::is_specialized && (std::numeric_limits<T>::radix == 2), T>::type tangent_scale_factor()\n{\n   return tools::min_value<T>() * 16;\n}\n//\n// Initializer: ensure all our constants are initialized prior to the first call of main:\n//\ntemplate <class T, class Policy>\nstruct bernoulli_initializer\n{\n   struct init\n   {\n      init()\n      {\n         //\n         // We call twice, once to initialize our static table, and once to\n         // initialize our dymanic table:\n         //\n         boost::math::bernoulli_b2n<T>(2, Policy());\n#ifndef BOOST_NO_EXCEPTIONS\n         try{\n#endif\n            boost::math::bernoulli_b2n<T>(max_bernoulli_b2n<T>::value + 1, Policy());\n#ifndef BOOST_NO_EXCEPTIONS\n         } catch(const std::overflow_error&){}\n#endif\n         boost::math::tangent_t2n<T>(2, Policy());\n      }\n      void force_instantiate()const{}\n   };\n   static const init initializer;\n   static void force_instantiate()\n   {\n      initializer.force_instantiate();\n   }\n};\n\ntemplate <class T, class Policy>\nconst typename bernoulli_initializer<T, Policy>::init bernoulli_initializer<T, Policy>::initializer;\n\n//\n// We need something to act as a cache for our calculated Bernoulli numbers.  In order to\n// ensure both fast access and thread safety, we need a stable table which may be extended\n// in size, but which never reallocates: that way values already calculated may be accessed\n// concurrently with another thread extending the table with new values.\n//\n// Very very simple vector class that will never allocate more than once, we could use\n// boost::container::static_vector here, but that allocates on the stack, which may well\n// cause issues for the amount of memory we want in the extreme case...\n//\ntemplate <class T>\nstruct fixed_vector : private std::allocator<T>\n{\n   typedef unsigned size_type;\n   typedef T* iterator;\n   typedef const T* const_iterator;\n   fixed_vector() : m_used(0)\n   {\n      std::size_t overflow_limit = 5 + b2n_overflow_limit<T, policies::policy<> >();\n      m_capacity = static_cast<unsigned>((std::min)(overflow_limit, static_cast<std::size_t>(100000u)));\n      m_data = this->allocate(m_capacity);\n   }\n   ~fixed_vector()\n   {\n      for(unsigned i = 0; i < m_used; ++i)\n         this->destroy(&m_data[i]);\n      this->deallocate(m_data, m_capacity);\n   }\n   T& operator[](unsigned n) { BOOST_ASSERT(n < m_used); return m_data[n]; }\n   const T& operator[](unsigned n)const { BOOST_ASSERT(n < m_used); return m_data[n]; }\n   unsigned size()const { return m_used; }\n   unsigned size() { return m_used; }\n   void resize(unsigned n, const T& val)\n   {\n      if(n > m_capacity)\n      {\n         BOOST_THROW_EXCEPTION(std::runtime_error(\"Exhausted storage for Bernoulli numbers.\"));\n      }\n      for(unsigned i = m_used; i < n; ++i)\n         new (m_data + i) T(val);\n      m_used = n;\n   }\n   void resize(unsigned n) { resize(n, T()); }\n   T* begin() { return m_data; }\n   T* end() { return m_data + m_used; }\n   T* begin()const { return m_data; }\n   T* end()const { return m_data + m_used; }\n   unsigned capacity()const { return m_capacity; }\nprivate:\n   T* m_data;\n   unsigned m_used, m_capacity;\n};\n\ntemplate <class T, class Policy>\nclass bernoulli_numbers_cache\n{\npublic:\n   bernoulli_numbers_cache() : m_overflow_limit((std::numeric_limits<std::size_t>::max)())\n#if defined(BOOST_HAS_THREADS) && !defined(BOOST_MATH_NO_ATOMIC_INT)\n      , m_counter(0)\n#endif\n   {}\n\n   typedef fixed_vector<T> container_type;\n\n   void tangent(std::size_t m)\n   {\n      static const std::size_t min_overflow_index = b2n_overflow_limit<T, Policy>() - 1;\n      tn.resize(static_cast<typename container_type::size_type>(m), T(0U));\n\n      BOOST_MATH_INSTRUMENT_VARIABLE(min_overflow_index);\n\n      std::size_t prev_size = m_intermediates.size();\n      m_intermediates.resize(m, T(0U));\n\n      if(prev_size == 0)\n      {\n         m_intermediates[1] = tangent_scale_factor<T>() /*T(1U)*/;\n         tn[0U] = T(0U);\n         tn[1U] = tangent_scale_factor<T>()/* T(1U)*/;\n         BOOST_MATH_INSTRUMENT_VARIABLE(tn[0]);\n         BOOST_MATH_INSTRUMENT_VARIABLE(tn[1]);\n      }\n\n      for(std::size_t i = std::max<size_t>(2, prev_size); i < m; ++i)\n      {\n         bool overflow_check = false;\n         if(i >= min_overflow_index && (boost::math::tools::max_value<T>() / (i-1) < m_intermediates[1]) )\n         {\n            std::fill(tn.begin() + i, tn.end(), boost::math::tools::max_value<T>());\n            break;\n         }\n         m_intermediates[1] = m_intermediates[1] * (i-1);\n         for(std::size_t j = 2; j <= i; ++j)\n         {\n            overflow_check =\n                  (i >= min_overflow_index) && (\n                  (boost::math::tools::max_value<T>() / (i - j) < m_intermediates[j])\n                  || (boost::math::tools::max_value<T>() / (i - j + 2) < m_intermediates[j-1])\n                  || (boost::math::tools::max_value<T>() - m_intermediates[j] * (i - j) < m_intermediates[j-1] * (i - j + 2))\n                  || ((boost::math::isinf)(m_intermediates[j]))\n                );\n\n            if(overflow_check)\n            {\n               std::fill(tn.begin() + i, tn.end(), boost::math::tools::max_value<T>());\n               break;\n            }\n            m_intermediates[j] = m_intermediates[j] * (i - j) + m_intermediates[j-1] * (i - j + 2);\n         }\n         if(overflow_check)\n            break; // already filled the tn...\n         tn[static_cast<typename container_type::size_type>(i)] = m_intermediates[i];\n         BOOST_MATH_INSTRUMENT_VARIABLE(i);\n         BOOST_MATH_INSTRUMENT_VARIABLE(tn[static_cast<typename container_type::size_type>(i)]);\n      }\n   }\n\n   void tangent_numbers_series(const std::size_t m)\n   {\n      BOOST_MATH_STD_USING\n      static const std::size_t min_overflow_index = b2n_overflow_limit<T, Policy>() - 1;\n\n      typename container_type::size_type old_size = bn.size();\n\n      tangent(m);\n      bn.resize(static_cast<typename container_type::size_type>(m));\n\n      if(!old_size)\n      {\n         bn[0] = 1;\n         old_size = 1;\n      }\n\n      T power_two(ldexp(T(1), static_cast<int>(2 * old_size)));\n\n      for(std::size_t i = old_size; i < m; ++i)\n      {\n         T b(static_cast<T>(i * 2));\n         //\n         // Not only do we need to take care to avoid spurious over/under flow in\n         // the calculation, but we also need to avoid overflow altogether in case\n         // we're calculating with a type where \"bad things\" happen in that case:\n         //\n         b  = b / (power_two * tangent_scale_factor<T>());\n         b /= (power_two - 1);\n         bool overflow_check = (i >= min_overflow_index) && (tools::max_value<T>() / tn[static_cast<typename container_type::size_type>(i)] < b);\n         if(overflow_check)\n         {\n            m_overflow_limit = i;\n            while(i < m)\n            {\n               b = std::numeric_limits<T>::has_infinity ? std::numeric_limits<T>::infinity() : tools::max_value<T>();\n               bn[static_cast<typename container_type::size_type>(i)] = ((i % 2U) ? b : T(-b));\n               ++i;\n            }\n            break;\n         }\n         else\n         {\n            b *= tn[static_cast<typename container_type::size_type>(i)];\n         }\n\n         power_two = ldexp(power_two, 2);\n\n         const bool b_neg = i % 2 == 0;\n\n         bn[static_cast<typename container_type::size_type>(i)] = ((!b_neg) ? b : T(-b));\n      }\n   }\n\n   template <class OutputIterator>\n   OutputIterator copy_bernoulli_numbers(OutputIterator out, std::size_t start, std::size_t n, const Policy& pol)\n   {\n      //\n      // There are basically 3 thread safety options:\n      //\n      // 1) There are no threads (BOOST_HAS_THREADS is not defined).\n      // 2) There are threads, but we do not have a true atomic integer type,\n      //    in this case we just use a mutex to guard against race conditions.\n      // 3) There are threads, and we have an atomic integer: in this case we can\n      //    use the double-checked locking pattern to avoid thread synchronisation\n      //    when accessing values already in the cache.\n      //\n      // First off handle the common case for overflow and/or asymptotic expansion:\n      //\n      if(start + n > bn.capacity())\n      {\n         if(start < bn.capacity())\n         {\n            out = copy_bernoulli_numbers(out, start, bn.capacity() - start, pol);\n            n -= bn.capacity() - start;\n            start = static_cast<std::size_t>(bn.capacity());\n         }\n         if(start < b2n_overflow_limit<T, Policy>() + 2u)\n         {\n            for(; n; ++start, --n)\n            {\n               *out = b2n_asymptotic<T, Policy>(static_cast<typename container_type::size_type>(start * 2U));\n               ++out;\n            }\n         }\n         for(; n; ++start, --n)\n         {\n            *out = policies::raise_overflow_error<T>(\"boost::math::bernoulli_b2n<%1%>(std::size_t)\", 0, T(start), pol);\n            ++out;\n         }\n         return out;\n      }\n   #if !defined(BOOST_HAS_THREADS)\n      //\n      // Single threaded code, very simple:\n      //\n      if(start + n >= bn.size())\n      {\n         std::size_t new_size = (std::min)((std::max)((std::max)(std::size_t(start + n), std::size_t(bn.size() + 20)), std::size_t(50)), std::size_t(bn.capacity()));\n         tangent_numbers_series(new_size);\n      }\n\n      for(std::size_t i = (std::max)(std::size_t(max_bernoulli_b2n<T>::value + 1), start); i < start + n; ++i)\n      {\n         *out = (i >= m_overflow_limit) ? policies::raise_overflow_error<T>(\"boost::math::bernoulli_b2n<%1%>(std::size_t)\", 0, T(i), pol) : bn[i];\n         ++out;\n      }\n   #elif defined(BOOST_MATH_NO_ATOMIC_INT)\n      //\n      // We need to grab a mutex every time we get here, for both readers and writers:\n      //\n      boost::detail::lightweight_mutex::scoped_lock l(m_mutex);\n      if(start + n >= bn.size())\n      {\n         std::size_t new_size = (std::min)((std::max)((std::max)(std::size_t(start + n), std::size_t(bn.size() + 20)), std::size_t(50)), std::size_t(bn.capacity()));\n         tangent_numbers_series(new_size);\n      }\n\n      for(std::size_t i = (std::max)(std::size_t(max_bernoulli_b2n<T>::value + 1), start); i < start + n; ++i)\n      {\n         *out = (i >= m_overflow_limit) ? policies::raise_overflow_error<T>(\"boost::math::bernoulli_b2n<%1%>(std::size_t)\", 0, T(i), pol) : bn[i];\n         ++out;\n      }\n\n   #else\n      //\n      // Double-checked locking pattern, lets us access cached already cached values\n      // without locking:\n      //\n      // Get the counter and see if we need to calculate more constants:\n      //\n      if(static_cast<std::size_t>(m_counter.load(BOOST_MATH_ATOMIC_NS::memory_order_consume)) < start + n)\n      {\n         boost::detail::lightweight_mutex::scoped_lock l(m_mutex);\n\n         if(static_cast<std::size_t>(m_counter.load(BOOST_MATH_ATOMIC_NS::memory_order_consume)) < start + n)\n         {\n            if(start + n >= bn.size())\n            {\n               std::size_t new_size = (std::min)((std::max)((std::max)(std::size_t(start + n), std::size_t(bn.size() + 20)), std::size_t(50)), std::size_t(bn.capacity()));\n               tangent_numbers_series(new_size);\n            }\n            m_counter.store(static_cast<atomic_integer_type>(bn.size()), BOOST_MATH_ATOMIC_NS::memory_order_release);\n         }\n      }\n\n      for(std::size_t i = (std::max)(static_cast<std::size_t>(max_bernoulli_b2n<T>::value + 1), start); i < start + n; ++i)\n      {\n         *out = (i >= m_overflow_limit) ? policies::raise_overflow_error<T>(\"boost::math::bernoulli_b2n<%1%>(std::size_t)\", 0, T(i), pol) : bn[static_cast<typename container_type::size_type>(i)];\n         ++out;\n      }\n\n   #endif\n      return out;\n   }\n\n   template <class OutputIterator>\n   OutputIterator copy_tangent_numbers(OutputIterator out, std::size_t start, std::size_t n, const Policy& pol)\n   {\n      //\n      // There are basically 3 thread safety options:\n      //\n      // 1) There are no threads (BOOST_HAS_THREADS is not defined).\n      // 2) There are threads, but we do not have a true atomic integer type,\n      //    in this case we just use a mutex to guard against race conditions.\n      // 3) There are threads, and we have an atomic integer: in this case we can\n      //    use the double-checked locking pattern to avoid thread synchronisation\n      //    when accessing values already in the cache.\n      //\n      //\n      // First off handle the common case for overflow and/or asymptotic expansion:\n      //\n      if(start + n > bn.capacity())\n      {\n         if(start < bn.capacity())\n         {\n            out = copy_tangent_numbers(out, start, bn.capacity() - start, pol);\n            n -= bn.capacity() - start;\n            start = static_cast<std::size_t>(bn.capacity());\n         }\n         if(start < b2n_overflow_limit<T, Policy>() + 2u)\n         {\n            for(; n; ++start, --n)\n            {\n               *out = t2n_asymptotic<T, Policy>(static_cast<typename container_type::size_type>(start));\n               ++out;\n            }\n         }\n         for(; n; ++start, --n)\n         {\n            *out = policies::raise_overflow_error<T>(\"boost::math::bernoulli_b2n<%1%>(std::size_t)\", 0, T(start), pol);\n            ++out;\n         }\n         return out;\n      }\n   #if !defined(BOOST_HAS_THREADS)\n      //\n      // Single threaded code, very simple:\n      //\n      if(start + n >= bn.size())\n      {\n         std::size_t new_size = (std::min)((std::max)((std::max)(start + n, std::size_t(bn.size() + 20)), std::size_t(50)), std::size_t(bn.capacity()));\n         tangent_numbers_series(new_size);\n      }\n\n      for(std::size_t i = start; i < start + n; ++i)\n      {\n         if(i >= m_overflow_limit)\n            *out = policies::raise_overflow_error<T>(\"boost::math::bernoulli_b2n<%1%>(std::size_t)\", 0, T(i), pol);\n         else\n         {\n            if(tools::max_value<T>() * tangent_scale_factor<T>() < tn[static_cast<typename container_type::size_type>(i)])\n               *out = policies::raise_overflow_error<T>(\"boost::math::bernoulli_b2n<%1%>(std::size_t)\", 0, T(i), pol);\n            else\n               *out = tn[static_cast<typename container_type::size_type>(i)] / tangent_scale_factor<T>();\n         }\n         ++out;\n      }\n   #elif defined(BOOST_MATH_NO_ATOMIC_INT)\n      //\n      // We need to grab a mutex every time we get here, for both readers and writers:\n      //\n      boost::detail::lightweight_mutex::scoped_lock l(m_mutex);\n      if(start + n >= bn.size())\n      {\n         std::size_t new_size = (std::min)((std::max)((std::max)(start + n, std::size_t(bn.size() + 20)), std::size_t(50)), std::size_t(bn.capacity()));\n         tangent_numbers_series(new_size);\n      }\n\n      for(std::size_t i = start; i < start + n; ++i)\n      {\n         if(i >= m_overflow_limit)\n            *out = policies::raise_overflow_error<T>(\"boost::math::bernoulli_b2n<%1%>(std::size_t)\", 0, T(i), pol);\n         else\n         {\n            if(tools::max_value<T>() * tangent_scale_factor<T>() < tn[static_cast<typename container_type::size_type>(i)])\n               *out = policies::raise_overflow_error<T>(\"boost::math::bernoulli_b2n<%1%>(std::size_t)\", 0, T(i), pol);\n            else\n               *out = tn[static_cast<typename container_type::size_type>(i)] / tangent_scale_factor<T>();\n         }\n         ++out;\n      }\n\n   #else\n      //\n      // Double-checked locking pattern, lets us access cached already cached values\n      // without locking:\n      //\n      // Get the counter and see if we need to calculate more constants:\n      //\n      if(static_cast<std::size_t>(m_counter.load(BOOST_MATH_ATOMIC_NS::memory_order_consume)) < start + n)\n      {\n         boost::detail::lightweight_mutex::scoped_lock l(m_mutex);\n\n         if(static_cast<std::size_t>(m_counter.load(BOOST_MATH_ATOMIC_NS::memory_order_consume)) < start + n)\n         {\n            if(start + n >= bn.size())\n            {\n               std::size_t new_size = (std::min)((std::max)((std::max)(start + n, std::size_t(bn.size() + 20)), std::size_t(50)), std::size_t(bn.capacity()));\n               tangent_numbers_series(new_size);\n            }\n            m_counter.store(static_cast<atomic_integer_type>(bn.size()), BOOST_MATH_ATOMIC_NS::memory_order_release);\n         }\n      }\n\n      for(std::size_t i = start; i < start + n; ++i)\n      {\n         if(i >= m_overflow_limit)\n            *out = policies::raise_overflow_error<T>(\"boost::math::bernoulli_b2n<%1%>(std::size_t)\", 0, T(i), pol);\n         else\n         {\n            if(tools::max_value<T>() * tangent_scale_factor<T>() < tn[static_cast<typename container_type::size_type>(i)])\n               *out = policies::raise_overflow_error<T>(\"boost::math::bernoulli_b2n<%1%>(std::size_t)\", 0, T(i), pol);\n            else\n               *out = tn[static_cast<typename container_type::size_type>(i)] / tangent_scale_factor<T>();\n         }\n         ++out;\n      }\n\n   #endif\n      return out;\n   }\n\nprivate:\n   //\n   // The caches for Bernoulli and tangent numbers, once allocated,\n   // these must NEVER EVER reallocate as it breaks our thread\n   // safety guarentees:\n   //\n   fixed_vector<T> bn, tn;\n   std::vector<T> m_intermediates;\n   // The value at which we know overflow has already occurred for the Bn:\n   std::size_t m_overflow_limit;\n#if !defined(BOOST_HAS_THREADS)\n#elif defined(BOOST_MATH_NO_ATOMIC_INT)\n   boost::detail::lightweight_mutex m_mutex;\n#else\n   boost::detail::lightweight_mutex m_mutex;\n   atomic_counter_type m_counter;\n#endif\n};\n\ntemplate <class T, class Policy>\ninline bernoulli_numbers_cache<T, Policy>& get_bernoulli_numbers_cache()\n{\n   //\n   // Force this function to be called at program startup so all the static variables\n   // get initailzed then (thread safety).\n   //\n   bernoulli_initializer<T, Policy>::force_instantiate();\n   static bernoulli_numbers_cache<T, Policy> data;\n   return data;\n}\n\n}}}\n\n#endif // BOOST_MATH_BERNOULLI_DETAIL_HPP\n", "meta": {"hexsha": "b4838ec4cc6142b80a83f4bdca0c183758cdf974", "size": 24983, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/core/boost_backport/detail/bernoulli_details.hpp", "max_stars_repo_name": "steva44/mlpack", "max_stars_repo_head_hexsha": "a766ea292e968f0cf1783f8293f36f47510fc6ad", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 4216.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T02:06:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T19:12:06.000Z", "max_issues_repo_path": "src/mlpack/core/boost_backport/detail/bernoulli_details.hpp", "max_issues_repo_name": "shayusuf/mlpack", "max_issues_repo_head_hexsha": "a854a0f03faff37b4d2338656267c9b80228402f", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 2621.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T01:41:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:01:26.000Z", "max_forks_repo_path": "src/mlpack/core/boost_backport/detail/bernoulli_details.hpp", "max_forks_repo_name": "shayusuf/mlpack", "max_forks_repo_head_hexsha": "a854a0f03faff37b4d2338656267c9b80228402f", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 1972.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T23:37:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T06:03:41.000Z", "avg_line_length": 37.7957639939, "max_line_length": 195, "alphanum_fraction": 0.6234239283, "num_tokens": 6605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.44317261983126344}}
{"text": "//\n// Created by sean on 10/07/16.\n//\n\n#ifndef PCL_OBJECT_DETECT_BATCH_MODE_LINALG_HPP\n#define PCL_OBJECT_DETECT_BATCH_MODE_LINALG_HPP\n\n\n#include <Eigen/Core>\n\n#include \"pcltools/common.hpp\"\n\n\nusing namespace pcltools::literals;\n\nnamespace pcltools {\n\nnamespace linalg {\n\n/**\n * Converts a 4x4 rigid transformation matrix to a quaternion and translation vector pair\n * @param transformation  A 4x4 matrix representing a rigid transformation.\n * @return                A quaternion and vector pair representing the passed transformation.\n */\ntemplate <typename Scalar>\nauto getQuaternionAndTranslation (Eigen::Matrix <Scalar, 4, 4> const & transformation)\n-> std::pair <Eigen::Quaternion <Scalar>, Eigen::Matrix <Scalar, 3, 1>> {\n  auto rotation_matrix =\n  Eigen::Matrix <Scalar, 3, 3> {transformation.block (0, 0, 3, 3)};\n  auto translation_vector =\n      static_cast <Eigen::Matrix <Scalar, 3, 1>> (transformation.block (0, 3, 3, 1));\n  return std::make_pair (Eigen::Quaternion <Scalar> (rotation_matrix), translation_vector);\n}\n\n\n/**\n * Converts a quaternion and translation vector representing a rigid transformation to 4x4 matrix\n * @param quaternion  The quaternion representing the rigid rotation.\n * @param translation The translation represented as a vector (a 3x1 matrix).\n * @return            The 4x4 matrix that represents a rigid body transformation.\n */\ntemplate <typename Scalar>\nauto getTransformationMatrix (Eigen::Quaternion <Scalar> const & quaternion,\n                              Eigen::Matrix <Scalar, 3, 1> const & translation)\n-> Eigen::Matrix <Scalar, 4, 4> {\n  auto rotation = Eigen::Matrix <Scalar, 3, 3> {quaternion.toRotationMatrix ()};\n  auto transformation = Eigen::Matrix <Scalar, 4, 4> {Eigen::Matrix <Scalar, 4, 4>::Identity ()};\n\n  for (auto col = 0_sz; col < rotation.cols (); ++col)\n    for (auto row = 0_sz; row < rotation.rows (); ++row)\n      transformation (row, col) = rotation (row, col);\n\n  for (auto index = 0_sz; index < translation.size (); ++index)\n    transformation (index, transformation.cols () - 1) = translation (index);\n\n  return transformation;\n}\n\n}\n}\n\n#endif //PCL_OBJECT_DETECT_BATCH_MODE_LINALG_HPP\n", "meta": {"hexsha": "63e73678937264fc1110aa58738594cfe432c737", "size": 2159, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pcltools/linalg.hpp", "max_stars_repo_name": "leaveitout/pcltools", "max_stars_repo_head_hexsha": "02659bfbcd6aa737f9a1aadb77c60a9db15513c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/pcltools/linalg.hpp", "max_issues_repo_name": "leaveitout/pcltools", "max_issues_repo_head_hexsha": "02659bfbcd6aa737f9a1aadb77c60a9db15513c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/pcltools/linalg.hpp", "max_forks_repo_name": "leaveitout/pcltools", "max_forks_repo_head_hexsha": "02659bfbcd6aa737f9a1aadb77c60a9db15513c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2698412698, "max_line_length": 97, "alphanum_fraction": 0.7086614173, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4431726198312634}}
{"text": "/*\n\nProject: basic icp\nDate: 20/08/04\n@Author: Yang, Wang.\nDetail: align numberous pointclouds \nScenario: VO\n\n*/\n\n\n#include <boost/make_shared.hpp>\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_representation.h>\n#include <pcl/io/pcd_io.h>\n\n\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/filters/filter.h>\n#include <pcl/filters/radius_outlier_removal.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n#include <pcl/features/normal_3d.h>\n\n\n#include <pcl/registration/icp.h>\n#include <pcl/registration/ndt.h>\n#include <pcl/registration/icp_nl.h>\n#include <pcl/registration/transforms.h>\n#include <pcl/registration/transformation_estimation_lm.h>\n\n\n#include <pcl/keypoints/uniform_sampling.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <sys/types.h>\n#include <string.h>\n#include <dirent.h>\n#include <stdio.h>\n#include <chrono>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n\nusing namespace std;\nusing pcl::visualization::PointCloudColorHandlerGenericField;\nusing pcl::visualization::PointCloudColorHandlerCustom;\ntypedef pcl::PointXYZ PointT;\ntypedef pcl::PointCloud<PointT> PointCloud;\ntypedef pcl::PointNormal PointNormalT;\ntypedef pcl::PointCloud<PointNormalT> PointCloudWithNormal;\n//typedef Eigen::Matrix<double, 4, 4> Matrix4f;\n\n\n//#pragma pack(1)\n\nstruct PCDMap\n{\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    int index =0;\n    PointCloud::Ptr cloud;\n    Eigen::Matrix4f global_transform;\n\n    //Eigen::Vector3d move;\n    //Eigen::Quaterniond q;\n\n    //Eigen::Vector3d move_after_g2o;\n    //Eigen::Quaterniond q_after_g2o;\n    bool doing_g2o = false;\n    PCDMap():cloud(new PointCloud){};\n};\n\n//uniform sampling func\n//data acquired: Cloud's ptr for processing.\nvoid uniform_sampling (PointCloud::Ptr cloud)\n{\n\tpcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZ>);\n\t//cout << \"原始点云个数：\" << cloud->points.size() << endl;\n\tpcl::UniformSampling<pcl::PointXYZ> US;\n   \tUS.setInputCloud(cloud);\n    \tUS.setRadiusSearch(0.2f);\n    \tUS.filter(*cloud_filtered);\n\t*cloud = *cloud_filtered;\n    \t//cout << \"均匀采样之后点云的个数：\" << cloud->points.size() << endl;\n}\n\n//remove singel func\n//data acquired: Cloud's ptr for processing.\nvoid remove_single (PointCloud::Ptr cloud)\n{\n\tpcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZ>);\n        //cout << \"原始点云个数：\" << cloud->points.size() << endl;\n\tpcl::RadiusOutlierRemoval<pcl::PointXYZ> RS;\n\tRS.setInputCloud(cloud);\n\tRS.setRadiusSearch(0.5);\n\tRS.setMinNeighborsInRadius(4);\n\tRS.filter(*cloud_filtered);\n        *cloud = *cloud_filtered;\n\t//cout << \"除去离群点后点云的个数：\" << cloud->points.size() << endl;\n}\n\n//another new filter to remove the point faraway from the origin\n//added on 7/30 by Wang\n//data acquired: pcl::PointCloud<PointNormal> PointCloudN\nvoid remove_distant (PointCloud::Ptr cloud)\n{\n    PointCloud::Ptr cloud_filtered(new PointCloud);\n    //cout << \"Cloud points number is:\" << cloud->points.size() << endl;\n    pcl::StatisticalOutlierRemoval<PointT> RD;\n    RD.setInputCloud(cloud);    \n    RD.setMeanK(50);\n    RD.setStddevMulThresh(1.0);\n    RD.filter(*cloud_filtered);\n    *cloud = *cloud_filtered;\n    //cout << \"Cloud points number after remove distant:\" << cloud->points.size() << endl;\n}\n\n\n//icp point align algorithm\n//data acquired: 1 & 2 is the Cloud's ptr for aligning, 3 is the Cloud's ptr for output, 4 is transformation matrix, 5 is unclear.\nvoid pairAlign (const PointCloud::Ptr cloud_src, const PointCloud::Ptr cloud_tgt, PointCloud::Ptr output, Eigen::Matrix4f&final_transform, int n)\n{\n\tint iterations = 100;\n\tpcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;\n\ticp.setInputSource(cloud_src);\n        icp.setInputTarget(cloud_tgt);\n        icp.setTransformationEpsilon(1e-15);\n\ticp.setMaxCorrespondenceDistance(2);\n        icp.setEuclideanFitnessEpsilon(0.001);\n        icp.setMaximumIterations(iterations);\n         \n\ticp.align(*output);\n\t//cout<<\"\\nThe \"<<n<< \" frame and the \"<<n+1<<\" frame have converged and score is \"<<icp.getFitnessScore()<<endl;\n\t//cout<<\"Transformation is\\n\"<<icp.getFinalTransformation()<<endl;\n\tfinal_transform = icp.getFinalTransformation();\n}\n\n//.pcd viewer related\n//data acquired: Cloud's ptr for display\nvoid showPCD (const PointCloud::Ptr clouddata)\n{\n\tboost::shared_ptr<pcl::visualization::PCLVisualizer>viewer_final (new pcl::visualization::PCLVisualizer(\"result1\"));\n        viewer_final->setBackgroundColor(0, 0, 0);\n\n        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ>clouddatacolor (clouddata, 0, 255, 0);\n        viewer_final->addPointCloud<pcl::PointXYZ> (clouddata, clouddatacolor, \"cloud data\");\n        viewer_final->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, \"cloud data\");\n\twhile (!viewer_final->wasStopped())\n        {\n                viewer_final->spinOnce(100);\n\t}\n\n}\n\n\n\n\nint main(int argc, char** argv)\n{\n    vector<PCDMap> data;\n    vector<PCDMap> secdata;\n    vector<PCDMap> thidata;\n    vector<PCDMap> findata;\n\n    string data_c1 = argv[1];\n    string data_c2 = argv[2];\n    //string data_c3 = argv[3];\n    int data_s = stoi(data_c1);\n    int data_e = stoi(data_c2);\n    //int data_num = stoi(data_c3);\n    chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n    for(int i = data_s; i < data_e; i=i+2)\n    {\n        char namebuf[20];\n        sprintf(namebuf, \"../%d.pcd\", i);\n        cout<<namebuf<<endl;\n        PCDMap m;\n        pcl::io::loadPCDFile (namebuf, *m.cloud); // set the struct.cloud\n        m.index = i;                              // set the struct.index\n        //m.afterg2o = Eigen::Matrix4d::Identity();\n        data.push_back(m);\n    }\n\n    PointCloud::Ptr source, target;\n    int j = 0;\n    int l = 0;\n    int n = 0;\n\n    //refinied 20/08/07\n    //the first loop of align, for pre-process\n    cout<<data.size()<<endl;\n    Eigen::Matrix4f GlobalTransform = Eigen::Matrix4f::Identity (), pairTransform;\n    for(size_t i = 0; i<data.size()-6; i=i+5)\n    {\n        target = data[i].cloud;\n        uniform_sampling(target);\n        remove_single(target);\n\n        PointCloud::Ptr mid (new PointCloud);\n        for(int fif = 1; fif < 6; fif++)\n        {\n            source = data[i+fif].cloud;\n            uniform_sampling(source);\n            remove_single(source);\n\n            PointCloud::Ptr temp (new PointCloud);\n            pairAlign(source, target, temp, pairTransform, i);\n            pcl::transformPointCloud(*source, *mid, pairTransform);\n            uniform_sampling(target);\n            remove_single(target);\n            remove_distant(target);\n            *target = *target + *mid;\n        }\n        cout<<\"1st: \"<< j <<endl;\n        GlobalTransform = pairTransform*GlobalTransform;\n        PointCloud::Ptr target_1st (new PointCloud);\n        pcl::transformPointCloud(*target, *target_1st, GlobalTransform);\n        j++;                 \n        PCDMap m_1st;\n        *m_1st.cloud = *target_1st;\n        m_1st.index = j;\n        m_1st.global_transform = GlobalTransform;\n        secdata.push_back(m_1st);\n    }\n\n\n\n\n    //the second loop of align, for the keyframe\n    cout<<secdata.size()<<endl;\n    PointCloud::Ptr source2, target2;\n    Eigen::Matrix4f GlobalTransform2 = Eigen::Matrix4f::Identity (), pairTransform2;\n    for(size_t k = 0; k< secdata.size()-4; k=k+3)\n    {\n        target2 = secdata[k].cloud;\n        PointCloud::Ptr mid2 (new PointCloud);\n        for(int fif = 1; fif < 4; fif++)\n        {\n            source2 = secdata[k+fif].cloud;\n            PointCloud::Ptr temp (new PointCloud);\n            pairAlign(source2, target2, temp, pairTransform2, k);\n            pcl::transformPointCloud(*source2, *mid2, pairTransform2);\n            *target2 = *target2 + *mid2;\n            uniform_sampling(target2);\n            remove_single(target2);\n\n        }\n        cout<<\"2nd: \"<< l <<endl;\n        GlobalTransform2 = pairTransform2*GlobalTransform2;\n        PointCloud::Ptr target_2nd (new PointCloud);\n        pcl::transformPointCloud(*target2, *target_2nd, GlobalTransform2);\n        l++;                 \n        PCDMap m_2nd;\n        *m_2nd.cloud = *target_2nd;\n        m_2nd.index = l;\n        m_2nd.global_transform = GlobalTransform2;\n        thidata.push_back(m_2nd);\n    }\n\n    //the third loop of align, for the result\n    cout<<thidata.size()<<endl;\n    PointCloud::Ptr source3, target3;\n    Eigen::Matrix4f GlobalTransform3 = Eigen::Matrix4f::Identity (), pairTransform3;\n    PointCloud::Ptr result (new PointCloud);\n    result = thidata[0].cloud;\n    for(size_t m = 1; m < thidata.size();m++)\n    {    \n        target3 = thidata[m-1].cloud;\n        source3 = thidata[m].cloud;\n        PointCloud::Ptr temp (new PointCloud);\n        PointCloud::Ptr mid3 (new PointCloud);\n        pairAlign(source3, target3, temp, pairTransform3, m);\n        GlobalTransform3 = pairTransform3*GlobalTransform3;\n        pcl::transformPointCloud(*source3, *mid3, GlobalTransform3);\n        *result = *result + *mid3;\n\n        PCDMap m_fin;\n        m_fin.index = n;\n        m_fin.global_transform = GlobalTransform3;\n        findata.push_back(m_fin);\n\n    }\n\n    //get the estimated global transform of the No. num keyframe\n    //int num = data_num;\n    for(size_t o = 0; o < secdata.size()-5;o++)\n    {\n        Eigen::Matrix4f GlobalTransform_real = Eigen::Matrix4f::Identity ();\n        cout << \"We would like to have the global transform of the No. \" << o << \" frame\" << endl;\n        GlobalTransform_real = secdata[o].global_transform * thidata[o/3].global_transform * findata[o/3].global_transform;\n        cout << GlobalTransform_real << endl;\n    }\n\n    uniform_sampling(result);\n    remove_single(result);\n    chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n    chrono::duration<double> time_used = chrono::duration_cast < chrono::duration < double >> (t2 - t1);\n    cout << \"time cost is \" << time_used.count() << \" seconds.\" << endl;\n    pcl::io::savePCDFileASCII (\"../test.pcd\", *result);\n    showPCD(result);\n\n\n}\n\n", "meta": {"hexsha": "3e65993e579c80f52ffb1f7b182cd9fcdb59ed0d", "size": 10019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cloud_align/cloud_align.cpp", "max_stars_repo_name": "wangarcher/examine", "max_stars_repo_head_hexsha": "e04c923f0db397558ea765d7fbf1050fe4aec3dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cloud_align/cloud_align.cpp", "max_issues_repo_name": "wangarcher/examine", "max_issues_repo_head_hexsha": "e04c923f0db397558ea765d7fbf1050fe4aec3dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cloud_align/cloud_align.cpp", "max_forks_repo_name": "wangarcher/examine", "max_forks_repo_head_hexsha": "e04c923f0db397558ea765d7fbf1050fe4aec3dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9572368421, "max_line_length": 145, "alphanum_fraction": 0.6580497056, "num_tokens": 2691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4431726125636714}}
{"text": "#ifndef _DIMENSIONAL_ANALYSIS_HPP_\n#define _DIMENSIONAL_ANALYSIS_HPP_\n\n#include \"MathLibDefinitions.h\"\n#include <boost\\units\\systems\\si\\acceleration.hpp>\n#include <boost\\units\\systems\\si\\force.hpp>\n#include <boost\\units\\systems\\si\\length.hpp>\n#include <boost\\units\\systems\\si\\energy.hpp>\n#include <boost\\units\\systems\\si\\current.hpp>\n#include <boost\\units\\systems\\si\\io.hpp>\n\nusing namespace boost::units;\nusing namespace boost::units::si;\n\nnamespace   mathlib{\n\n\t\n\tnamespace physics {\n\n\n\t\tvoid test(){\n\n\t\t\tquantity<force, double> Force = quantity<force, double>(2.0 * newton);\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t}\n\n\t\t/*\n\n\t\t     *** SIForce   wrapper  class around boost::unit quantity<force,T> *** \n\t\t*/\n\n\t\ttemplate<typename T>  class SIForce {\n\n\n\n\t\tpublic:\n\n\t\t\t/*\n\t\t\t@brief   Zero-force unit.\n\t\t\t*/\n\n\t\tconstexpr\tSIForce() : m_magnitude{ static_cast<T>(0) } { this->m_oForce = quantity<force, T>(this->m_magnitude * newton); }\n\t\t\t\t         \n\t\t\t\n\n\t\t\t/*\n\t\t\t@brief    Create Force object with user passed magnitude value.\n\t\t\t*/\n\n\t\t    SIForce(_In_ T const mag) : m_magnitude{ mag } { this->m_oForce = quantity<force, T>(this->m_magnitude * newton); }\n\t\t\t\t\n\t\t\t\n\n\t\t\t/*\n\t\t\t@brief  Copy-Ctor\n\t\t\t*/\n\t\t\tSIForce(_In_ const SIForce &rhs) : m_magnitude{ rhs.m_magnitude }, m_oForce{ rhs.m_oForce }{}\n\t\t\t\t\n\t\t\t\n\n\t\t\t/*\n\t\t\t@brief   Move-Ctor\n\t\t\t*/\n\t\t\tSIForce(_In_ SIForce &&rhs) : m_magnitude{ std::forward<T>(rhs.m_magnitude) }, m_oForce{ std::forward<T>(rhs.m_oForce) } {}\n\t\t\t\n\n\t\t\t/*\n\t\t\t@brief  Dtor == default\n\t\t\t*/\n\t\t\t~SIForce() = default;\n\n\t\t\t/*\n\n\t\t\t      ****   Member functions  ****\n\t\t\t*/\n\n\t\t\t/*  Returns  this->m_magnitude  */\n\t\t\t__forceinline     auto       Magnitude()->const T {\n\n\t\t\t\treturn (this->m_magnitude);\n\t\t\t}\n\n\t\t\t/*  Returns  this->m_oForce  */\n\t\t\t__forceinline    auto Force()->const quantity<force,T>{\n\n\t\t\t\treturn (this->m_oForce);\n\t\t\t}\n\n\t\t\t/*\n\n\t\t\t      ***  Member operators  ***  \n\t\t\t*/\n\t\t\t\n\n\t\t\t/* \n\t\t\t@brief    *this = const &rhs\n\t\t\t*/\n\t\t\tSIForce &     operator=(_In_ const SIForce &rhs) {\n\n\t\t\t\tif (this == &rhs) return (*this);\n\n\t\t\t\tthis->m_magnitude = rhs.m_magnitude;\n\t\t\t\tthis->m_oForce.operator=(rhs.m_oForce);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief    *this = &&rhs\n\t\t\t*/\n\t\t\tSIForce &     operator=(_In_ SIForce &&rhs) {\n\n\t\t\t\tif (this == &rhs) return (*this);\n\n\t\t\t\tthis->m_magnitude = std::forward<T>(rhs.m_magnitude);\n\t\t\t\tthis->m_oForce.operator=(std::forward<T>(rhs.m_oForce));\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief    *this +=   const  &rhs\n\t\t   */\n\t\t\tSIForce &      operator+=(_In_ const SIForce &rhs) {\n\n\t\t\t\tthis->m_magnitude += rhs.m_magnitude;\n\t\t\t\tthis->m_oForce.operator+=(rhs.m_oForce);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t\n\n\t\t\t/*\n\t\t\t@brief     *this +=    &&rhs\n\t\t\t*/\n\t\t\tSIForce  &      operator+=(_In_ SIForce &&rhs) {\n\n\t\t\t\tthis->m_magnitude += rhs.m_magnitude;\n\t\t\t\tthis->m_oForce.operator+=(std::forward<T>(rhs.m_oForce));\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief     *this -=    const  &rhs\n\t\t\t*/\n\t\t\tSIForce  &       operator-=(_In_ const SIForce &rhs) {\n\n\t\t\t\tthis->m_magnitude -= rhs.m_magnitude;\n\t\t\t\tthis->m_oForce.operator-=(rhs.m_oForce);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief      *this -=   &&rhs\n\t\t\t*/\n\t\t\tSIForce  &       operator-=(_In_ SIForce &&rhs) {\n\n\t\t\t\tthis->m_magnitude -= rhs.m_magnitude;\n\t\t\t\tthis->m_oForce.operator-=(std::forward<T>(rhs.m_oForce));\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief       *this *=  const &rhs\n\t\t\t*/\n\t\t\tSIForce  &       operator*=(_In_  const SIForce &rhs) {\n\n\t\t\t\tthis->m_magnitude *= rhs.m_magnitude;\n\t\t\t\tthis->m_oForce.operator*=(rhs.m_oForce);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief       *this *=  &&rhs\n\t\t\t*/\n\t\t\tSIForce  &       operator*=(_In_  SIForce &&rhs) {\n\n\t\t\t\tthis->m_magnitude *= rhs.m_magnitude;\n\t\t\t\tthis->m_oForce.operator*=(std::forward<T>(rhs.m_oForce));\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief        *this /=  const &rhs\n\t\t\t*/\n\t\t\tSIForce  &       operator/=(_In_ const SIForce &rhs) {\n\n\t\t\t\tthis->m_magnitude /= rhs.m_magnitude;\n\t\t\t\tthis->m_oForce.operator/=(rhs.m_oForce);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief        *this /=   &&rhs\n\t\t\t*/\n\t\t\tSIForce  &       operator/=(_In_ SIForce &&rhs) {\n\n\t\t\t\tthis->m_magnitude /= rhs.m_magnitude;\n\t\t\t\tthis->m_oForce.operator/=(std::forward<T>(rhs.m_oForce));\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief         *this == rhs\n\t\t\t*/\n\t\t\tauto             operator==(_In_ const SIForce &rhs)->const bool {\n\n\t\t\t\treturn (this->m_oForce.value() == rhs.m_oForce.value() &&\n\t\t\t\t\tthis->m_magnitude == rhs.m_magnitude);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief           *this != rhs\n\t\t\t*/\n\t\t\tauto              operator!=(_In_ const SIForce &rhs)->const bool {\n\n\t\t\t\treturn !(this->operator==(rhs));\n\t\t\t}\n\n\t\t\t\n\t\t\t/*\n\t\t\t@brief      operator<<\n\t\t\t*/\n\t\t\tfriend\tstd::ostream &      operator<<(_In_ std::ostream &os, _In_   SIForce &rhs) {\n\t\t\t\t\n\t\t\t\tos << \"Force = \" << rhs.Force().value() << \" N\" << std::endl;\n\t\t\t\treturn os;\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\t/*\n\t\t\t@brief   Amount of force in unit of newton.\n\t\t\t*/\n\t\t\tT   m_magnitude;\n\n\t\t\t/*\n\t\t\t@brief   unit of Force.\n\t\t\t*/\n\t\t\tquantity<force, T> m_oForce;\n\t\t};\n\n\t\t/*\n\t\t          ***  Wrapper class for the boost::units quantity of Length.\n\t\t\t\t  \n\t\t*/\n\n\t\ttemplate<typename T>   class SILength {\n\n\n\n\t\tpublic:\n\n\t\t\t/*    \n\t\t\t    Zero-length Default Ctor\n\t\t\t*/\n\t\t\tSILength() : m_magnitude{ static_cast<T>(0) } { this->m_oLength = quantity<length, T>(this->m_magnitude * meter) }\n\n\t\t\t/*\n\t\t\t    One-arg Ctor.\n\t\t\t*/\n\t\t\tSILength(const T &mag) : m_magnitude{ mag } { this->m_oLength = quantity<length, T>(this->m_magnitude * meter); }\n\n\t\t\t/*\n\t\t\t    Two-arg Ctor.\n\t\t\t*/\n\t\t\tSILength(const T &rhs, const quantity<length, T> &lhs) : m_magnitude{ rhs }, m_oLength{ lhs } {};\n\t\t\t/*\n\t\t\t    Copy-Ctor\n\t\t\t*/\n\t\t\tSILength(const SILength &rhs) : m_magnitude{ rhs.m_magnitude }, m_oLength{ rhs.m_oLength } {}\n\n\t\t\t/*\n\t\t\t    Move-Ctor\n\t\t\t*/\n\t\t\tSILength(SILength &&rhs) : m_magnitude{ std::move(rhs.m_magnitude) }, m_oLength{ std::move(rhs.m_oLength) } {}\n\n\t\t\t/*\n\t\t\t    Dtor = default\n\t\t\t*/\n\t\t\t~SILength() noexcept(true) = default;\n\n\t\t\t/*\n\n\t\t\t         ***   Member accessors  ***\n\t\t\t*/\n\n\n\t\t\t/*\n\t\t\t     Returns magnitude argument.\n\t\t\t*/\n\t\t\t__forceinline  auto   Magnitude()->const T{\n\n\t\t\t\treturn (this->m_magnitude);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief   Returns  m_oLength class variable.\n\t\t\t*/\n\t\t\t__forceinline  auto   Length()->const quantity<length, T> {\n\n\t\t\t\treturn (this->m_oLength);\n\t\t\t}\n\n\t\t\t\n\n\t\t\t/*\n\n\t\t\t     ***   Class member and friend operators.  *** \n\t\t\t*/\n\n\t\t\t/*\n\t\t\t@brief     copy-assignment.\n\t\t\t*/\n\t\t\tauto  operator=(_In_ const SILength &rhs)->SILength<T> & {\n\n\t\t\t\tif (this == &rhs) return (*this);\n\n\t\t\t\tthis->m_magnitude = rhs.m_magnitude;\n\t\t\t\tthis->m_oLength = rhs.m_oLength;\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief      move-assignment.\n\t\t\t*/\n\t\t\tauto  operator=(_In_ SILength &&rhs)->SILength<T> & {\n\n\t\t\t\tif (this == &rhs) return (*this);\n\n\t\t\t\tthis->m_magnitude = std::forward<T>(rhs.m_magnitude);\n\t\t\t\tthis->m_oLength = std::forward<T>(rhs.m_oLength);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief     *this += rhs\n\t\t\t*/\n\t\t\tauto   operator+=(_In_ const SILength &rhs)->SILength<T> & {\n\n\t\t\t\tthis->m_magnitude += rhs.m_magnitude;\n\t\t\t\tthis->m_oLength.operator+=(rhs.m_oLength);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief    *this += rhs (move)\n\t\t\t*/\n\t\t\tauto    operator+=(_In_  SILength<T> &&rhs)->SILength<T> & {\n\n\t\t\t\tthis->m_magnitude += std::move(rhs.m_magnitude);\n\t\t\t\tthis->m_oLength.operator+=(std::move(rhs.m_oLength));\n\t\t\t\treturn (*this);\n\t\t\t}\n\t\t\t  \n\t\t\t/*\n\t\t\t@brief     *this -= rhs\n\t\t\t*/\n\t\t\tauto   operator-=(_In_ const SILength &rhs)->SILength<T> & {\n\n\t\t\t\tthis->m_magnitude -= rhs.m_magnitude;\n\t\t\t\tthis->m_oLength.operator-=(rhs.m_oLength);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief      *this -= rhs (move)\n\t\t\t*/\n\t\t\tauto    operator-=(_In_ SILength &&rhs)->SILength<T> & {\n\n\t\t\t\tthis->m_magnitude -= std::move(rhs.m_magnitude);\n\t\t\t\tthis->m_oLength.operator-=(std::move(rhs.m_oLength));\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief     *this *= rhs\n\t\t\t*/\n\t\t\tauto    operator*=(_In_ const SILength &rhs)->SILength<T> & {\n\n\t\t\t\tthis->m_magnitude *= rhs.m_magnitude;\n\t\t\t\tthis->m_oLength.operator*=(rhs.m_oLength);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief      *this /= rhs\n\t\t\t*/\n\t\t\tauto    operator/=(_In_ SILength &&rhs)->SILength<T> & {\n\n\t\t\t\tthis->Magnitude = std::move(rhs.m_magnitude);\n\t\t\t\tthis->m_oLength.operator*=(std::move(rhs.m_oLength));\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief    *this /= rhs\n\t\t\t*/\n\t\t\tauto    operator/=(_In_ const SILength &rhs)->SILength<T> & {\n\n\t\t\t\tthis->m_magnitude /= rhs.m_magnitude;\n\t\t\t\tthis->m_oLength.operator/=(rhs.m_oLength);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t\n\t\t\t/*\n\t\t\t@brief        *this == rhs\n\t\t    */\n\t\t\tauto    operator==(_In_ const SILength &rhs)->const bool {\n\n\t\t\t\treturn (this->m_oLength.value() == rhs.m_oLength.value() &&\n\t\t\t\t\tthis->m_magnitude == rhs.m_magnitude);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief        *this != rhs\n\t\t\t*/\n\t\t\tauto    operator!=(_In_ const SILength &rhs)->const bool {\n\n\t\t\t\treturn (!(this->operator==(rhs)));\n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief    operator<<\n\t\t\t*/\n\t\t\tfriend  std::ostream &   operator<<(_In_ std::ostream &os, _In_   SILength &rhs) {\n\n\t\t\t\tos << \"Length = \" << rhs.Length().value() << \" m\" << std::endl;\n\t\t\t\treturn os;\n\t\t\t}\n\n\t\t\t\n\t\t\t\t  \n\t\t\t\n\n\t\tprivate:\n\n\t\t\t/*  \n\t\t\t    T m_magnitude class variable \n\t\t\t*/\n\t\t\tT    m_magnitude;\n\n\t\t\t/*\n\t\t\t    T m_oLength class variable\n            \n\t\t\t*/\n\n\t\t\tquantity<length, T> m_oLength;\n\t\t\t\n\t\t};\n\n\t\t/*\n\n\t\t        ***  Generic class Work   ***\n\t\t\t\t\n\t\t*/\n\n\t\ttemplate<class Force, class Distance, typename T>  \n\t\tclass SIWork {\n\n\n\t\tpublic:\n\n\t\t\t/*\n\t\t\t@brief Surpress creation of Default Ctor\n\t\t\t*/\n\t\t\tSIWork() = delete;\n\n\n\t\t\t/*\n\t\t\t @brief    One-arg Ctor\n\t\t\t*/\n\n\t\t    \n\t\t\tSIWork(_In_  Force &f, _In_  Distance &d) : m_oWork{ f.Force() * d.Length() } {}\n\n\t\t\t/*\n\t\t\t@brief     Copy-Ctor.\n\t\t\t*/\n\t\t\tSIWork(_In_ const SIWork &rhs) : m_oWork{ rhs.m_oWork } {}\n\n\t\t\t/*\n\t\t\t@brief     Move-Ctor\n\t\t\t*/\n\t\t\tSIWork(_In_ SIWork &&rhs) : m_oWork{ std::move(rhs.m_oWork) } {}\n\n\t\t\t/*\n\t\t\t@brief   Dtor\n\t\t\t*/\n\t\t\t~SIWork() noexcept(true) = default;\n\n\t\t\t\n\n\t\t\t/*\n\n\t\t\t      Class member operators, and accessor.\n\n\t\t\t*/\n\n\t\t\tauto     Work()->const SIWork<Force, Distance, T> {\n\n\t\t\t\treturn (this->m_oWork);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t         *this = rhs (copy)\n\t\t\t*/\n\t\t\tauto     operator=(_In_ const SIWork &rhs)->SIWork<Force, Distance, T> & {\n\n\t\t\t\tif (this == &rhs) return (*this);\n\t\t\t\tthis->m_oWork.operator=(rhs.m_oWork);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t         *this = rhs (move)\n\t\t\t*/\n\t\t\tauto      operator=(_In_ SIWork &&rhs)->SIWork<Force, Distance, T> & {\n\n\t\t\t\tif (this == &rhs) return (*this);\n\t\t\t\tthis->m_oWork.operator=(rhs.m_oWork);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t             *this += rhs\n\t\t\t */\n\t\t\tauto      operator+=(_In_ const SIWork &rhs)->SIWork<Force, Distance, T> & {\n\n\t\t\t\tthis->m_oWork.operator+=(rhs.m_oWork);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t            *this += rhs (move)\n\t\t\t*/\n\t\t\tauto       operator+=(_In_ SIWork &&rhs)->SIWork<Force, Distance, T> & {\n\n\t\t\t\tthis->m_oWork.operator+=(std::move(rhs.m_oWork));\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t              *this -= rhs\n\t\t\t*/\n\t\t\tauto      operator-=(_In_ const SIWork &rhs)->SIWork<Force, Distance, T> & {\n\n\t\t\t\tthis->m_oWork.operator-=(rhs.m_oWork);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t               *this -= rhs\n\t\t\t*/\n\t\t\tauto       operator-=(_In_ SIWork &&rhs)->SIWork<Force, Distance, T> & {\n\n\t\t\t\tthis->m_oWork.operator-=(std::move(rhs.m_oWork));\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\n\n\n\t\t\t/*\n\t\t\t              *this *= rhs\n\t\t\t*/\n\t\t\tauto       operator*=(_In_ const SIWork &rhs)->SIWork<Force, Distance, T> & {\n\n\t\t\t\tthis->m_oWork.operator*=(rhs.m_oWork);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\n\t\t\t/*\n\t\t\t               *this *= rhs (move)\n\t\t\t */\n\t\t\tauto       operator*=(_In_ SIWork &&rhs)->SIWork<Force, Distance, T> & {\n\n\t\t\t\tthis->m_oWork.operator*=(std::move(rhs.m_oWork));\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t               *this /= rhs\n\t\t\t*/\n\t\t\tauto        operator/=(_In_ const SIWork &rhs)->SIWork<Force, Distance, T> & {\n\n\t\t\t\tthis->m_oWork.operator/=(rhs.m_oWork);\n\t\t\t\treturn (*this);\n\t\t\t}\n\n\t\t\t/*\n\t\t\t               *this /= rhs (move)\n\t\t\t*/\n\t\t\tauto        operator/=(_In_ SIWork &&rhs)->SIWork<Force, Distance, T> & {\n\n\t\t\t\tthis->m_oWork.operator/=(std::move(rhs.m_oWork));\n\t\t\t\treturn (*this);\n\t\t\t}\n\t\t\t\n\t\t\t/*\n\t\t\t               *this == rhs\n\t\t    */\n\t\t\tauto         operator==(_In_ const SIWork &rhs)->const bool {\n\t\t\t\treturn (this->m_oWork.value() == rhs.m_oWork.value());\n\t\t\t}\n\n\t\t\t/*\n\t\t\t               *this == rhs (move)\n\t\t\t*/\n\t\t\tauto          operator==(_In_ SIWork &&rhs)-> const bool {\n\t\t\t\treturn (std::move(this->m_oWork.value() == std::move(this->m_oWork.value())));\n\t\t\t}\n\t\t\t/*\n\t\t\t               *this != rhs\n\t\t    */\n\t\t\tauto         operator!=(_In_ const SIWork &rhs)->const bool {\n\t\t\t\treturn (!(this->operator==(rhs)));\n\t\t\t}\n\n\t\t\t/*\n\t\t\t               std::cout << *this\n\t\t\t\t\t\t   \n\t\t\t*/\n\t\t\tauto     display()->const void {\n\n\t\t\t\tstd::printf(\"Work = %4.16f J\\n\", this->m_oWork.value());\n\t\t\t}\n\n\n\t\tprivate:\n\n\t\t\t/*\n\t\t\t@brief    Energy(Work) class variable m_oWork\n\t\t\t*/\n\t\t\tquantity<energy, T> m_oWork;\n\n\t\t};\n\n\t\t/*\n\t\t\n\t\t             Wrapper class for boost::units::current\n\t\t       \n\t\t*/\n\n\t\t/*  primary template */\n\n\t\ttemplate<typename T>  class SICurrent {\n\n\n\t\tpublic:\n\n\t\t\t/*\n\t\t\t@brief    Zero-current default Ctor\n\t\t\t*/\n\t\t\tSICurrent() : m_Magnitude{ static_cast<T>(0.0) }, m_oCurrent{ m_Magnitude * amperes } {}\n\n\t\t\t/*\n\t\t\t@brief    One-arg Ctor , constructs object of type Current.\n\t\t\t*/\n\t\t\tSICurrent(_In_ const T mag) : m_Magnitude{ mag }, m_oCurrent{ m_Magnitude * amperes } {}\n\n\t\t\t/*\n\t\t\t@brief    Copy-Ctor.\n\t\t\t*/\n\t\t\tSICurrent(_In_ const SICurrent &rhs) : m_Magnitude{ rhs.m_Magnitude }, m_oCurrent{ rhs.m_oCurrent } {}\n\n\t\t\t/*\n\t\t\t@brief    Move-Ctor\n\t\t\t*/\n\t\t\tSICurrent(_In_ SICurrent &&rhs) : m_Magnitude{ std::move(rhs.m_Magnitude) }, m_oCurrent{ std::move(rhs.m_oCurrent) } {}\n\n\t\t\t/*\n\t\t\t@brief    Dtor  = default.\n\t\t\t*/\n\t\t\t~SICurrent() noexcept(true) = default;\n\n\n\t\t\t/*\n\n\t\t\tClass member accessors and operators.\n\n\t\t\t*/\n\n\t\t\t/*\n\t\t\t@brief     this->m_Magnitude\n\t\t\t*/\n\t\t\t__forceinline  auto         Magnitude()->const T{\n\n\t\t\t\treturn (this->m_Magnitude); \n\t\t\t}\n\n\t\t\t/*\n\t\t\t@brief     this->m_oCurrent\n\t\t\t*/\n\t\t   __forceinline auto            Current()->const quantity<current, T> {\n\n\t\t\t  return (this->m_oCurrent);\n\t\t\t}\n\n\t\t    /*\n\t\t    @brief      *this = rhs (copy)\n\t\t    */\n\t\t   auto        operator=(_In_ const SICurrent &rhs)->SICurrent<T> {\n\n\t\t\t   if (this == &rhs) return (*this);\n\n\t\t\t   this->m_Magnitude = rhs.m_Magnitude;\n\t\t\t   this->m_oCurrent.operator=(rhs.m_oCurrent);\n\t\t\t   return (*this);\n\t\t   }\n\n\t\t   /*\n\t\t   @brief        *this = rhs (move)\n\t\t   */\n\t\t   auto         operator=(_In_ SICurrent &&rhs)->SICurrent<T> & {\n\n\t\t\t   if (this == &rhs) return (*this);\n\n\t\t\t   this->m_Magnitude = std::move(rhs.m_Magnitude);\n\t\t\t   this->m_oCurrent.operator=(std::move(rhs.m_oCurrent));\n\t\t\t   return (*this);\n\t\t   }\n\n\t\t   /*\n\t\t   @brief         *this += rhs\n\t\t   */\n\t\t   auto          operator+=(_In_ const SICurrent &rhs)->SICurrent<T> & {\n\n\t\t\t   this->m_Magnitude += rhs.m_Magnitude;\n\t\t\t   this->m_oCurrent.operator+=(rhs.m_oCurrent);\n\t\t\t   return (*this);\n\t\t   }\n\n\t\t   /*\n\t\t   @brief         *this += rhs (move)\n\t\t   */\n\t\t   auto           operator+=(_In_ SICurrent &&rhs)->SICurrent<T> & {\n\n\t\t\t   this->m_Magnitude += std::move(rhs.m_Magnitude);\n\t\t\t   this->m_oCurrent.operator+=(std::move(rhs.m_oCurrent));\n\t\t\t   return (*this);\n\t\t   }\n\n\t\t   /*\n\t\t   @brief         *this -= rhs\n\t\t   */\n\t\t   auto            operator-=(_In_ const SICurrent &rhs)->SICurrent<T> & {\n\n\t\t\t   this->m_Magnitude -= rhs.m_Magnitude;\n\t\t\t   this->m_oCurrent.operator-=(rhs.m_oCurrent);\n\t\t\t   return (*this);\n\t\t   }\n\n\t\t   /*\n\t\t   @brief          *this -= rhs (move)\n\t\t   */\n\t\t   auto             operator-=(_In_ SICurrent &&rhs)->SICurrent<T> & {\n\n\t\t\t   this->m_Magnitude -= std::move(rhs.m_Magnitude);\n\t\t\t   this->m_oCurrent.operator-=(rhs.m_oCurrent);\n\t\t\t   return (*this);\n\t\t   }\n\n\t\t   /*\n\t\t   @brief         *this *= rhs \n\t\t   */\n\t\t   auto             operator*=(_In_ const SICurrent &rhs)->SICurrent<T> & {\n\n\t\t\t   this->m_Magnitude *= rhs.m_Magnitude;\n\t\t\t   this->m_oCurrent.operator*=(rhs.m_oCurrent);\n\t\t\t   return (*this);\n\t\t   }\n\n\t\t   /*\n\t\t   @brief          *this *= rhs (move)\n\t\t   */\n\t\t   auto             operator*=(_In_ SICurrent &&rhs)->SICurrent<T> & {\n\n\t\t\t   this->m_Magnitude *= std::move(rhs.m_Magnitude);\n\t\t\t   this->m_oCurrent.operator*=(std::move(rhs.m_oCurrent));\n\t\t\t   return (*this);\n\t\t   }\n\n\t\t   /*\n\t\t   @brief           *this /= rhs\n\t\t   */\n\t\t   auto              operator/=(_In_ const SICurrent &rhs)->SICurrent<T> & {\n\n\t\t\t   this->m_Magnitude /= rhs.m_Magnitude;\n\t\t\t   this->m_oCurrent.operator/=(rhs.m_oCurrent);\n\t\t\t   return (*this);\n\t\t   }\n\n\t\t   /*\n\t\t   @brief            *this /= rhs (move)\n\t\t   */\n\t\t   auto              operator/=(_In_ SICurrent &&rhs)->SICurrent<T> & {\n\n\t\t\t   this->m_Magnitude /= std::move(rhs.m_Magnitude);\n\t\t\t   this->m_oCurrent.operator/=(std::move(rhs.m_oCurrent));\n\t\t\t   return (*this);\n\t\t   }\n\n\t\t   /*\n\t\t   @brief              *this == rhs\n\t\t   */\n\t\t   auto              operator==(_In_ const SICurrent &rhs)->const bool {\n\n\t\t\t   return (this->m_Magnitude == rhs.m_Magnitude &&\n\t\t\t\t   this->m_oCurrent.value() == rhs.m_oCurrent.value());\n\t\t   }\n\n\t\t   /*\n\t\t   @brief                *this !=  rhs\n\t\t   */\n\t\t   auto              operator!=(_In_ const SICurrent &rhs)->const bool {\n\n\t\t\t   return (!(this->operator==(rhs)));\n\t\t   }\n\n\t\t   /*\n\t\t   @brief               operator<< , specialized only for std::complex<T> type.\n\t\t   */\n\t\t   friend  std::enable_if<std::is_class<std::complex<T>>::value,std::ostream &>::type \n\t\t\t   operator<<(_In_ std::ostream &os, _In_ const SICurrent<T> &rhs) {\n\n\t\t\t\t       os << \"Current=\" << rhs.Magnitude().real() << \"Re\" << \"+\" << \n\t\t\t\t\t   rhs.Magnitude().imag() << std::endl;\n\t\t\t   }\n\n\t\t   /*\n\t\t   @brief         displays the value of this->m_oCurrent in Ampere unit. Displayed value of\n\t\t                   Ampere defualted to double-precision.\n\t\t   */\n\t\t   auto         display()->void {\n\n\t\t\t   std::printf(\"Current=%4.16f A/n\", this->m_oCurrent.value());\n\t\t   }\n\n\n\t\tprivate:\n\n\t\t\t/*\n\t\t\t@brief   quantity magnitude m_oMagnitude.\n\t\t\t*/\n\t\t\tT   m_Magnitude;\n\n\t\t\t/*\n\t\t\t@brief   quantity of current m_oCurrent\n\t\t\t*/\n\t\t\tquantity<current, T>  m_oCurrent;\n\n\t\t};\n\n\t\t/*\n\n\t\t          Wrapper class for boost::unit::quantity<resistance,T>\n\n\t\t*/\n\n\n\t\ttemplate<typename T> class SIResistance {\n\n\n\t\t   public:\n\n\n\t\t\t   /*\n\t\t\t         Zero-resistance Ctor.\n\t\t\t   */\n\t\t\t   SIResistance() : m_Magnitude{ static_cast<T>(0.0) }, m_oResistance{ m_Magnitude * ohm } {}\n\n\t\t\t   /*\n\t\t\t         Variable-resistance Ctor.\n\t\t\t   */\n\t\t\t   SIResistance(_In_ const T &mag) : m_Magnitude{ mag }, m_oResistance{ m_Magnitude * ohm } {}\n\n\t\t\t   /*\n\t\t\t          Copy-Ctor.\n\t\t\t   */\n\t\t\t   SIResistance(_In_ const SIResistance &rhs) : m_Magnitude{ rhs.m_Magnitude }, m_oResistance{ rhs.m_oResistance } {}\n\n\t\t\t   /*\n\t\t\t           Move-Ctor.\n\t\t\t   */\n\t\t\t   SIResistance(_In_ SIResistance &&rhs) : m_Magnitude{ std::move(rhs.m_Magnitude) }, m_oResistance{ std::move(rhs.m_oResistance) } {}\n\n\t\t\t   /*\n\t\t\t           Dtor = default.\n\t\t\t   */\n\t\t\t   ~SIResistance() noexcept(true) = default;\n\n\n\t\t\t   /*\n\n\t\t\t   Accessor and member operators.\n\n\t\t\t   */\n\n\t\t\t   /*\n\t\t\t             Returns this->m_Magnitude\n\t\t\t   */\n\t\t\t   __forceinline auto            Magnitude()->const T{\n\n\t\t\t\t   return (this->m_Magnitude);\n\t\t\t   }\n\n\t\t\t   /*\n\t\t\t             Returns this->m_oResistance.\n\t\t\t   */\n\t\t\t   __forceinline  auto           Resistance()->const quantity<resistance, T> {\n\n\t\t\t\t   return (this->m_oResistance);\n\t\t\t   }\n\n\t\t\t   /*\n\t\t\t                 *this = rhs (copy)\n\t\t\t   */\n\t\t\t   auto            operator=(_In_ const SIResistance &rhs)->SIResistance<T> & {\n\n\t\t\t\t   if (this == &rhs) return (*this);\n\n\t\t\t\t   this->m_Magnitude = rhs.m_Magnitude;\n\t\t\t\t   this->m_oResistance.operator=(rhs.m_oResistance);\n\t\t\t\t   return (*this);\n\t\t\t   }\n\n\t\t\t   /*\n\t\t\t                  *this = rhs (move)\n\t\t\t   */\n\t\t\t   auto            operator=(_In_ SIResistance &&rhs)->SIResistance<T> & {\n\n\t\t\t\t   if (this == &rhs) return (*this);\n\n\t\t\t\t   this->m_Magnitude = std::move(rhs.m_Magnitude);\n\t\t\t\t   this->m_oResistance = std::move(rhs.m_oResistance);\n\t\t\t\t   return (*this);\n\t\t\t   }\n\n\t\t\t   /*\n\t\t\t                    *this += rhs\n\t\t\t\t*/\n\t\t\t   auto             operator+=(_In_ const SIResistance &rhs)->SIResistance<T> & {\n\n\t\t\t\t   this->m_Magnitude += rhs.m_Magnitude;\n\t\t\t\t   this->m_oResistance.operator+=(rhs.m_oResistance);\n\t\t\t\t   return (*this);\n\t\t\t   }\n\n\t\t\t   /*\n\t\t\t                     *this += rhs (move)\n\t\t\t   */\n\t\t\t   auto              operator+=(_In_ SIResistance &&rhs)->SIResistance<T> & {\n\n\t\t\t\t   this->m_Magnitude += std::move(rhs.m_Magnitude);\n\t\t\t\t   this->m_oResistance.operator+=(std::move(rhs.m_oResistance));\n\t\t\t\t   return (*this);\n\t\t\t   }\n\n\t\t\t   /*\n\t\t\t                      *this -= rhs\n\t\t\t\t*/\n\t\t\t   auto              operator-=(_In_ const SIResistance &rhs)->SIResistance<T> & {\n\n\t\t\t\t   this->m_Magnitude -= rhs.m_Magnitude;\n\t\t\t\t   this->m_oResistance.operator-=(rhs.m_oResistance);\n\t\t\t\t   return (*this);\n\t\t\t   }\n\n\t\t\t   /*\n\t\t\t                       *this -= rhs (move)\n\t\t\t\t*/\n\t\t\t   auto              operator-=(_In_ SIResistance &&rhs)->SIResistance<T> & {\n\n\t\t\t\t   this->m_Magnitude -= std::move(rhs.m_Magnitude);\n\t\t\t\t   this->m_oResistance.operator-=(std::move(rhs.m_oResistance));\n\t\t\t\t   return (*this);\n\t\t\t   }\n\n\t\t\t   /*\n\t\t\t                       *this *= rhs\n\t\t\t   */\n\t\t\t   auto               operator*=(_In_ const SIResistance &rhs)->SIResistance<T> & {\n\n\t\t\t\t   this->m_Magnitude *= rhs.m_Magnitude;\n\t\t\t\t   this->m_oResistance.operator*=(rhs.m_oResistance);\n\t\t\t\t   return (*this);\n\t\t\t   }\n\n\t\t\t   /*\n\t\t\t                        *this *= rhs  (move)\n\t\t\t   */\n\t\t\t   auto               operator*=(_In_ SIResistance &&rhs)->SIResistance<T> & {\n\n\t\t\t\t   this->m_Magnitude *= std::move(rhs.m_Magnitude);\n\t\t\t\t   this->m_oResistance.operator*=(std::move(rhs.m_oResistance));\n\t\t\t\t   return (*this);\n\t\t\t   }\n\n\t\t\t   /*\n\t\t\t                         *this /= rhs            \n\t\t\t   */\n\t\t\t   auto                operator/=(_In_ const SIResistance &rhs)->SIResistance<T> & {\n\n\t\t\t\t   this->m_Magnitude /= rhs.m_Magnitude;\n\t\t\t\t   this->m_oResistance.operator/=(rhs.m_oResistance);\n\t\t\t\t   return (*this);\n\t\t\t   }\n\n\t\t\t   /*\n\t\t\t                         *this /= rhs\n\t\t\t\t*/\n\t\t\t   auto                operator/=(_In_ SIResistance &&rhs)->SIResistance<T> & {\n\n\t\t\t\t   this->m_Magnitude /= std::move(rhs.m_Magnitude);\n\t\t\t\t   this->m_oResistance.operator/=(std::move(rhs.m_oResistance));\n\t\t\t\t   return (*this);\n\t\t\t   }\n\n\t\t\t   /*\n\t\t\t                         *this == rhs\n\t\t\t\t*/\n\t\t   private:\n                \n\t\t\t   /*\n\t\t\t   @brief       magnitude of quantity<resistance,ohm>\n\t\t\t   */\n\n\t\t\t   T     m_Magnitude;\n\n\t\t\t   /*\n\t\t\t   @brief        quantity<resistance,ohm>\n\t\t\t   */\n\t\t\t   quantity<resistance, T> m_oResistance;\n\n\t\t};\n\n\t\t/*\n\t\t             mathlib::physics::SIForce namespace operators\n\t\t*/\n\n\t\t/*\n\t\t     c = a + b\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator+(_In_ const mathlib::physics::SIForce<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SIForce<T> &rhs)->mathlib::physics::SIForce<T> {\n\n\t\t\tSIForce<T> ret_val = SIForce<T>{lhs.operator+=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t     c  = a * b\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator*(_In_ const mathlib::physics::SIForce<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SIForce<T> &rhs)->mathlib::physics::SIForce<T> {\n\n\t\t\tSIForce<T> ret_val = SIForce<T>{lhs.operator*=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t     c = a - b\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator-(_In_ const mathlib::physics::SIForce<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SIForce<T> &rhs)->mathlib::physics::SIForce<T> {\n\n\t\t\tSIForce<T> ret_val = SIForce<T>{lhs.operator-=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t     c  = a / b\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator/(_In_ const mathlib::physics::SIForce<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SIForce<T> &rhs)->mathlib::physics::SIForce<T> {\n\n\t\t\tSIForce<T> ret_val = SIForce<T>{lhs.operator/=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t       a == b\n\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator==(_In_ const mathlib::physics::SIForce<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SIForce<T> &rhs)->mathlib::physics::SIForce<T> {\n\n\t\t\treturn (lhs.operator==(rhs));\n\t\t}\n\n\t\t/*\n\t\t       a !=  b\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator!=(_In_ const mathlib::physics::SIForce<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SIForce<T> &rhs)->mathlib::physics::SIForce<T> {\n\n\t\t\treturn (lhs.operator==(rhs));\n\t\t}\n\n\n\t\t/*\n\t\t\n\t\t                  mathlib::physics::SILength namespace operators\n\n\t\t*/\n\n\n\t\t/*\n\t\t      c = a + b\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator+(_In_  mathlib::physics::SILength<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SILength<T> &rhs)->mathlib::physics::SILength<T> {\n\n\t\t\tSILength<T> ret_val = SILength<T>{lhs.operator+=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\n\n\t\t/*\n\t\t      c =  a * b\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator*(_In_ const mathlib::physics::SILength<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SILength<T> &rhs)->mathlib::physics::SILength<T> {\n\n\t\t\tSILength<T> ret_val = SILength<T>{lhs.operator*=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\n\t\t/*\n\t\t       c = a - b\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator-(_In_ const mathlib::physics::SILength<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SILength<T> &rhs)->mathlib::physics::SILength<T> {\n\n\t\t\tSILength<T> ret_val = SILength<T>{lhs.operator-=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t        c =  a / b\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator/(_In_ const mathlib::physics::SILength<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SILength<T> &rhs)->mathlib::physics::SILength<T> {\n\n\t\t\tSILength<T> ret_val = SILength<T>{lhs.operator/=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t        a == b\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator==(_In_ const mathlib::physics::SILength<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SILength<T> &rhs)->bool {\n\n\t\t\treturn (lhs.operator==(rhs));\n\t\t}\n\n\t\t/*\n\t\t       a != b\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator!=(_In_ const mathlib::physics::SILength<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SILength<T> &rhs)->bool {\n\n\t\t\treturn (lhs.operator!=(rhs));\n\t\t}\n\n\t\t/*\n\n\t\t           mathlib::physics::SIWork namespace operators.\n\n\t\t*/\n\n\t\t/*\n\t\t         c  = lhs + rhs\n\t\t*/\n\t\ttemplate<class Force, class Distance, typename T> __forceinline auto operator+(_In_ const mathlib::physics::SIWork<Force, Distance, T> &lhs,\n\t\t\t_In_ const mathlib::physics::SIWork<Force, Distance, T> &rhs)->mathlib::physics::SIWork<Force, Distance, T> {\n\n\t\t\tSIWork<Force, Distance, T> ret_val = SIWork<Force, Distance, T>{lhs.operator+=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t\n\n\t\t/*\n\t\t         c = lhs - rhs\n\t\t*/\n\t\ttemplate<class Force, class Distance, typename T> __forceinline auto operator-(_In_ const mathlib::physics::SIWork<Force, Distance, T> &lhs,\n\t\t\t_In_ const mathlib::physics::SIWork<Force, Distance, T> &rhs)->mathlib::physics::SIWork<Force, Distance, T> {\n\n\t\t\tSIWork<Force, Distance, T> ret_val = SIWork<Force, Distance, T>{lhs.operator-=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t        c = lhs * rhs\n\t\t*/\n\t\ttemplate<class Force, class Distance, typename T> __forceinline auto operator*(_In_ const mathlib::physics::SIWork<Force, Distance, T> &lhs,\n\t\t\t_In_ const mathlib::physics::SIWork<Force, Distance, T> &rhs)->mathlib::physics::SIWork<Force, Distance, T> {\n\n\t\t\tSIWork<Force, Distance, T> ret_val = SIWork<Force, Distance, T>{lhs.operator*=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t         c = lhs / rhs\n\t\t*/\n\t\ttemplate<class Force, class Distance, typename T> __forceinline auto operator/(_In_ const mathlib::physics::SIWork<Force, Distance, T> &lhs,\n\t\t\t_In_ const mathlib::physics::SIWork<Force, Distance, T> &rhs)->mathlib::physics::SIWork<Force, Distance, T> {\n\n\t\t\tSIWork<Force, Distance, T> ret_val = SIWork<Force, Distance, T>{lhs.operator/=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t        lhs == rhs\n\t\t*/\n\t\ttemplate<class Force, class Distance, typename T> __forceinline auto operator==(_In_ const mathlib::physics::SIWork<Force, Distance, T> &lhs,\n\t\t\t_In_ const mathlib::physics::SIWork<Force, Distance, T> &rhs)->bool {\n\n\t\t\treturn (lhs.operator==(rhs));\n\t\t}\n\n\t\t/*\n\t\t        lhs != rhs\n\t\t*/\n\t\ttemplate<class Force, class Distance, typename T> __forceinline auto operator!=(_In_ const mathlib::physics::SIWork<Force, Distance, T> &lhs,\n\t\t\t_In_ const mathlib::physics::SIWork<Force, Distance, T> &rhs)->bool {\n\n\t\t\treturn (lhs.operator!=(rhs));\n\t\t}\n\n\t\t/*\n\n\t\t              mathlib::physics::SICurrent namespace operators.\n\n\t\t*/\n\n\t\t/*\n\t\t                 c = lhs + rhs\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto  operator+(_In_ const mathlib::physics::SICurrent<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SICurrent<T> &rhs)->SICurrent<T> {\n\n\t\t\tSICurrent<T> ret_val = SICurrent<T>{lhs.operator+=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t                c = lhs - rhs\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator-(_In_ const mathlib::physics::SICurrent<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SICurrent<T> &rhs)->SICurrent<T> {\n\n\t\t\tSICurrent<T> ret_val = SICurrent<T>{lhs.operator-=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t                c = lhs * rhs\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator*(_In_ const mathlib::physics::SICurrent<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SICurrent<T> &rhs)->SICurrent<T> {\n\n\t\t\tSICurrent<T> ret_val = SICurrent<T>{lhs.operator*=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t                c =  lhs / rhs\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator/(_In_ const mathlib::physics::SICurrent<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SICurrent<T> &rhs)->SICurrent<T> {\n\n\t\t\tSICurrent<T> ret_val = SICurrent<T>{lhs.operator/=(rhs)};\n\t\t\treturn (ret_val);\n\t\t}\n\n\t\t/*\n\t\t                 rhs == lhs\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator==(_In_ const mathlib::physics::SICurrent<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SICurrent<T> &rhs)->bool {\n\n\t\t\treturn (lhs.operator==(rhs));\n\t\t}\n\n\t\t/*\n\t\t                 rhs != lhs\n\t\t*/\n\t\ttemplate<typename T> __forceinline auto operator!=(_In_ const mathlib::physics::SICurrent<T> &lhs,\n\t\t\t_In_ const mathlib::physics::SICurrent<T> &rhs)->bool {\n\n\t\t\treturn (lhs.operator!=(rhs));\n\t\t}\n\t}\n}\n#endif   /*_DIMENSIONAL_ANALYSIS_HPP_*/", "meta": {"hexsha": "cc23f417b2a94f9e394cf139691f13bd6ee0c382", "size": 30230, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "MathLib/Include/DimensionalAnalysis.hpp", "max_stars_repo_name": "bgin/MissileSimulation", "max_stars_repo_head_hexsha": "90adcbf1c049daafb939f3fe9f9dfe792f26d5df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2016-08-28T23:20:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T14:43:58.000Z", "max_issues_repo_path": "MathLib/Include/DimensionalAnalysis.hpp", "max_issues_repo_name": "bgin/MissileSimulation", "max_issues_repo_head_hexsha": "90adcbf1c049daafb939f3fe9f9dfe792f26d5df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-02T21:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-05T05:59:31.000Z", "max_forks_repo_path": "MathLib/Include/DimensionalAnalysis.hpp", "max_forks_repo_name": "bgin/MissileSimulation", "max_forks_repo_head_hexsha": "90adcbf1c049daafb939f3fe9f9dfe792f26d5df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-04T22:38:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-04T22:38:22.000Z", "avg_line_length": 23.2003069839, "max_line_length": 143, "alphanum_fraction": 0.5550446576, "num_tokens": 8891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4431726125636714}}
{"text": "//\r\n//  Copyright (c) 2012, Institue of Cancer Research.\r\n//  All rights reserved.\r\n//\r\n// Redistribution and use in source and binary forms, with or without\r\n//modification, are permitted provided that the following conditions are\r\n// met:\r\n//\r\n//     * Redistributions of source code must retain the above copyright\r\n//       notice, this list of conditions and the following disclaimer.\r\n//     * Redistributions in binary form must reproduce the above\r\n//       copyright notice, this list of conditions and the following\r\n//       disclaimer in the documentation and/or other materials provided\r\n//       with the distribution.\r\n//     * Neither the name of Institue of Cancer Research.\r\n//       nor the names of its contributors may be used to endorse or promote\r\n//       products derived from this software without specific prior written permission.\r\n//\r\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n//\r\n// For more information on the Plane of Best Fit please see http://pubs.acs.org/doi/abs/10.1021/ci300293f\r\n//\r\n//  If this code has been useful to you, please include the reference\r\n//  in any work which has made use of it:\r\n\r\n//  Plane of Best Fit: A Novel Method to Characterize the Three-Dimensionality of Molecules, Nicholas C. Firth, Nathan Brown, and Julian Blagg, Journal of Chemical Information and Modeling 2012 52 (10), 2516-2525\r\n\r\n//\r\n//\r\n// Created by Nicholas Firth, November 2011\r\n// Modified by Greg Landrum for inclusion in the RDKit distribution November 2012\r\n//\r\n\r\n#include \"PBFRDKit.h\"\r\n#include <Numerics/Matrix.h>\r\n#include <Numerics/SquareMatrix.h>\r\n#include <Numerics/SymmMatrix.h>\r\n#include <boost/foreach.hpp>\r\n\r\n#include <Eigen/Dense>\r\nusing namespace RDKit;\r\n\r\nvoid getSmallestEigenVector(double fSumXX,double fSumXY,double fSumXZ,\r\n                            double fSumYY,double fSumYZ,double fSumZZ,\r\n                            double &x,double &y, double &z);\r\n\r\ndouble distanceFromAPlane(const RDGeom::Point3D &pt,const std::vector<double> &plane, double denom){\r\n  double numer=0.0;\r\n  numer = std::fabs(pt.x*plane[0]+pt.y*plane[1]+pt.z*plane[2]+plane[3]);\r\n\r\n  return numer/denom;\r\n}\r\n\r\nbool getBestFitPlane(const std::vector<RDGeom::Point3D> &points,\r\n                     std::vector<double> &plane,\r\n                     const std::vector<double> *weights) {\r\n  PRECONDITION((!weights || weights->size()>=points.size()),\"bad weights vector\");\r\n  RDGeom::Point3D origin(0,0,0);\r\n  double wSum=0.0;\r\n\r\n  for(unsigned int i=0;i<points.size();++i){\r\n    if(weights){\r\n      double w=(*weights)[i];\r\n      wSum+=w;\r\n      origin+=points[i]*w;\r\n    } else {\r\n      wSum+=1;\r\n      origin+=points[i];\r\n    }\r\n  }\r\n  origin /= wSum;\r\n\r\n  double sumXX=0,sumXY=0,sumXZ=0,sumYY=0,sumYZ=0,sumZZ=0;\r\n  for(unsigned int i=0;i<points.size();++i){\r\n    RDGeom::Point3D delta=points[i]-origin;\r\n    if(weights){\r\n      double w=(*weights)[i];\r\n      delta *= w;\r\n    }\r\n    sumXX += delta.x*delta.x;\r\n    sumXY += delta.x*delta.y;\r\n    sumXZ += delta.x*delta.z;\r\n    sumYY += delta.y*delta.y;\r\n    sumYZ += delta.y*delta.z;\r\n    sumZZ += delta.z*delta.z;\r\n  }\r\n  sumXX/=wSum;\r\n  sumXY/=wSum;\r\n  sumXZ/=wSum;\r\n  sumYY/=wSum;\r\n  sumYZ/=wSum;\r\n  sumZZ/=wSum;\r\n\r\n  Eigen::Matrix3d mat;\r\n  mat << sumXX, sumXY, sumXZ,\r\n    sumXY, sumYY, sumYZ,\r\n    sumXZ, sumYZ, sumZZ;\r\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(mat);\r\n  if(eigensolver.info()!=Eigen::Success){\r\n    BOOST_LOG(rdErrorLog)<<\"eigenvalue calculation did not converge\"<<std::endl;\r\n    return 0.0;\r\n  }\r\n  RDGeom::Point3D normal;\r\n  normal.x=eigensolver.eigenvectors()(0,0);\r\n  normal.y=eigensolver.eigenvectors()(1,0);\r\n  normal.z=eigensolver.eigenvectors()(2,0);\r\n\r\n  plane[0] = normal.x;\r\n  plane[1] = normal.y;\r\n  plane[2] = normal.z;\r\n  plane[3] = -1*normal.dotProduct(origin);\r\n  \r\n}\r\n\r\ndouble PBFRD(ROMol& mol,int confId){\r\n  PRECONDITION(mol.getNumConformers()>=1,\"molecule has no conformers\")\r\n  int numAtoms = mol.getNumAtoms();\r\n  if(numAtoms<4) return 0;\r\n\r\n  const Conformer &conf = mol.getConformer(confId);\r\n  if(!conf.is3D()) return 0 ;\r\n\r\n  std::vector<RDGeom::Point3D> points;\r\n  points.reserve(numAtoms);\r\n  for(unsigned int i=0; i<numAtoms; ++i){\r\n    points.push_back(conf.getAtomPos(i));\r\n  } \r\n    \r\n  std::vector<double> plane(4);\r\n  getBestFitPlane(points,plane,0);\r\n\r\n  double denom=0.0;\r\n  for(unsigned int i=0; i<3; ++i){\r\n    denom += plane[i]*plane[i];\r\n  }\r\n  denom = pow(denom,0.5);\r\n    \r\n  double res=0.0;\r\n  for(unsigned int i=0; i<numAtoms; ++i){\r\n    res+= distanceFromAPlane(points[i], plane, denom);\r\n  }\r\n  res /= numAtoms;\r\n\r\n  return res;\r\n}\r\n\r\n", "meta": {"hexsha": "b9a7fab7a90698e03f18f0a6e589849c7f2d42f5", "size": 5355, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modified_rdkit/Contrib/PBF/PBFRDKit.cpp", "max_stars_repo_name": "hjuinj/RDKit_mETKDG", "max_stars_repo_head_hexsha": "b270e765caa61d289e9e33595d4264b156f9062e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T04:00:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-31T01:32:13.000Z", "max_issues_repo_path": "modified_rdkit/Contrib/PBF/PBFRDKit.cpp", "max_issues_repo_name": "hjuinj/RDKit_mETKDG", "max_issues_repo_head_hexsha": "b270e765caa61d289e9e33595d4264b156f9062e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-23T17:31:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-26T06:52:47.000Z", "max_forks_repo_path": "modified_rdkit/Contrib/PBF/PBFRDKit.cpp", "max_forks_repo_name": "hjuinj/RDKit_mETKDG", "max_forks_repo_head_hexsha": "b270e765caa61d289e9e33595d4264b156f9062e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-03-30T04:00:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-25T23:11:52.000Z", "avg_line_length": 34.1082802548, "max_line_length": 213, "alphanum_fraction": 0.6633053221, "num_tokens": 1434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4431726125636713}}
{"text": "// Copyright (c) 2016 Till Kolditz\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/*\n * File:   Euclidean.hpp\n * Author: Till Kolditz <till.kolditz@gmail.com>\n *\n * Created on 6. Dezember 2016, 00:55\n */\n\n#ifndef EUCLIDEAN_HPP\n#define EUCLIDEAN_HPP\n\n#include <iostream>\n#include <vector>\n#include <cinttypes>\n#include <exception>\n#include <climits>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint128_t;\n\nnamespace Private {\n    template<typename T, typename S>\n    struct extractor {\n    };\n\n    template<typename T>\n    struct extractor<T, uint128_t> {\n        static T doIt(\n                const uint128_t source) {\n            const constexpr unsigned nBitsLimb = sizeof(boost::multiprecision::limb_type) * CHAR_BIT; // size of limb in bits\n            boost::multiprecision::limb_type target = 0;\n            const unsigned nLimbs = source.backend().size(); // number of limbs\n            auto pLimbs = source.backend().limbs();\n            for (unsigned i = 0; i < nLimbs && ((i * nBitsLimb) < (sizeof(T) * CHAR_BIT)); ++i) {\n                target |= (pLimbs[i]) << (i * nBitsLimb);\n            }\n            return static_cast<T>(target);\n        }\n    };\n}\n\n/*\n * This algorithm actually computes the modulo inverse of the given first argument\n * b0 in the residual class ring modulo <codewidth> (the second argument). One\n * requirement of this algorithm is, that template type <T> is large enough to\n * store <codewidth>+1 bits!\n */\ntemplate<typename T>\nT ext_euclidean(\n        T b0,\n        size_t codewidth) {\n    if ((sizeof(T) * CHAR_BIT) <= codewidth) {\n        throw std::runtime_error(\"The template datatype is too small!\");\n    }\n    T a0(1);\n    a0 <<= codewidth;\n    // T a[20], b[20], q[20], r[20], s[20], t[20];\n    std::vector<T> a(32), b(32), q(32), r(32), s(32), t(32);\n    // std::vector<uint128_t> a(32), b(32), q(32), r(32), s(32), t(32);\n    uint8_t aI = 1, bI = 1, qI = 0, rI = 0, sI = 1, tI = 1;\n    a[0] = a0;\n    b[0] = b0;\n    s[0] = 0;\n    t[0] = 0;\n    ssize_t i = 0;\n    do {\n        q[qI++] = a[i] / b[i];\n        r[rI++] = a[i] % b[i];\n        a[aI++] = b[i];\n        b[bI++] = r[i];\n        s[sI++] = 0;\n        t[tI++] = 0;\n    } while (b[++i] > 0);\n    s[i] = 1;\n    t[i] = 0;\n\n    for (ssize_t j = i; j > 0; --j) {\n        s[j - 1] = t[j];\n        t[j - 1] = s[j] - q[j - 1] * t[j];\n    }\n    T result = ((b0 * t[0]) % a0);\n    result += result < 0 ? a0 : 0;\n    if (result == 1) {\n        if constexpr (std::is_fundamental_v<T>) {\n            return t[0];\n        } else if constexpr (std::is_base_of_v<T, uint128_t>) {\n            return Private::extractor<T, uint128_t>::doIt(t[0]);\n        } else {\n            throw std::runtime_error(\"ext_euclidean not supported for this type!\");\n        }\n    }\n    return 0;\n}\n\n#endif /* EUCLIDEAN_HPP */\n", "meta": {"hexsha": "f7183f7ffc248c17d5f14095f292debf92e1cc0c", "size": 3332, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Util/Euclidean.hpp", "max_stars_repo_name": "tuddbresilience/coding_benchmark", "max_stars_repo_head_hexsha": "f4bab7b57fcb57d98d94a4efc3b8adad2bad6767", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Util/Euclidean.hpp", "max_issues_repo_name": "tuddbresilience/coding_benchmark", "max_issues_repo_head_hexsha": "f4bab7b57fcb57d98d94a4efc3b8adad2bad6767", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Util/Euclidean.hpp", "max_forks_repo_name": "tuddbresilience/coding_benchmark", "max_forks_repo_head_hexsha": "f4bab7b57fcb57d98d94a4efc3b8adad2bad6767", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2909090909, "max_line_length": 125, "alphanum_fraction": 0.5762304922, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.443146150279747}}
{"text": "/**\n * Created by Beck on 3/7/2018\n * Indirect Extended Kalman Filter for the translation of the camera\n * fusing visual information with the accelerometer, given the pose;\n * With imu in 400Hz and camera translation in 30Hz\n * V1: estimation for rotation only\n * V2: give the translation of the shield\n */\n#include <iostream>\n#include <ros/ros.h>\n#include <std_msgs/String.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/PoseWithCovarianceStamped.h>\n#include <geometry_msgs/Vector3Stamped.h>\n#include <geometry_msgs/TwistStamped.h>\n#include <nav_msgs/Odometry.h>\n#include <sensor_msgs/Imu.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <queue>\n//#include \"rm_cv/ArmorRecord.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nros::Publisher pose_pub, debug_pub, odom_pub, debug_propagate_pub;\nstring imu_topic, pose_topic, visual_topic;\nstring debug_topic, publisher_topic;\ndouble acc_weight;\ndouble visual_q_weight, visual_t_weight;\nint sleep_time;\n\n/**\n * Define states:\n *      x = [translation_x, y, z; velocity_x, y, z]\n * Define inputs:\n *      u = [acc], raw accelerometer\n * Define noises:\n *      n = [n_acc]\n */\nVectorXd x(6);         // state\nMatrixXd P = MatrixXd::Identity(6, 6); // covariance\nMatrixXd R = MatrixXd::Identity(3, 3); // prediction noise covariance\nMatrixXd Q = MatrixXd::Identity(3, 3); // observation noise covariance\n\n// buffers to save gyro and visual reading\nqueue<sensor_msgs::Imu::ConstPtr> imu_buf;\nqueue<geometry_msgs::TwistStamped::ConstPtr> visual_buf;\nqueue<Matrix<double, 6, 1>> x_history;\nqueue<Matrix<double, 6, 6>> P_history;\nVector3d G = {0, 0, 9.8}; // Consider to add initialization later\n\ndouble t_prev;          // previous propagated time\n\n// Initialization\nconst int IMU_INIT_COUNT = 10;\nconst int MAX_GYRO_QUEUE_SIZE = 400;\nconst double IMU_UPDATE_TIME = 0.0025; // 1 / 400Hz\nint imu_count  = 0;\nbool imu_initialized = false;\nbool visual_initialized = false;\nbool visual_valid = false;\nMatrixXd imu_R_camera = MatrixXd::Identity(3, 3); // rotation matrix from camera to imu\nVector3d imu_T_camera = MatrixXd::Zero(3, 1);\n\n//// DEBUG only\ndouble t_prev_update;   // previous update time\nVector3d world_T_shield_prev = MatrixXd::Zero(3, 1); // previous visual translation\n\nvoid pub_shield_odom(const std_msgs::Header& header)\n{\n    nav_msgs::Odometry odom;\n    odom.header = header;\n    odom.child_frame_id = \"world\";\n    odom.pose.pose.position.x = x(0);\n    odom.pose.pose.position.y = x(1);\n    odom.pose.pose.position.z = x(2);\n    odom.twist.twist.linear.x = x(3);\n    odom.twist.twist.linear.y = x(4);\n    odom.twist.twist.linear.z = x(5);\n\n    odom.pose.covariance[0]  = P(0, 0);\n    odom.pose.covariance[7]  = P(1, 1);\n    odom.pose.covariance[14] = P(2, 2);\n    odom.pose.covariance[21] = P(3, 3);\n    odom.pose.covariance[28] = P(4, 4);\n    odom.pose.covariance[35] = P(5, 5);\n    odom.pose.covariance[3]  = P(0, 3);\n    odom.pose.covariance[10] = P(1, 4);\n    odom.pose.covariance[17] = P(2, 5);\n    odom.pose.covariance[18] = P(3, 0);\n    odom.pose.covariance[25] = P(4, 1);\n    odom.pose.covariance[32] = P(5, 2);\n    odom_pub.publish(odom);\n}\n\nvoid pub_debug_update(const std_msgs::Header& header,\n                      const Ref<const Vector3d> p,\n                      const Quaterniond& q,\n                      double t_update)\n{\n    nav_msgs::Odometry odom;\n    odom.header = header;\n    odom.child_frame_id = \"world\";\n    odom.pose.pose.position.x = p[0];\n    odom.pose.pose.position.y = p[1];\n    odom.pose.pose.position.z = p[2];\n    odom.pose.pose.orientation.w = q.w();\n    odom.pose.pose.orientation.x = q.x();\n    odom.pose.pose.orientation.y = q.y();\n    odom.pose.pose.orientation.z = q.z();\n    if (visual_initialized) {\n        double dt_update = t_update - t_prev_update;\n        odom.twist.twist.linear.x = (p[0] - world_T_shield_prev[0]) / dt_update;\n        odom.twist.twist.linear.y = (p[1] - world_T_shield_prev[1]) / dt_update;\n        odom.twist.twist.linear.z = (p[2] - world_T_shield_prev[2]) / dt_update;\n\n        world_T_shield_prev = p;\n        t_prev_update = t_update;\n    }\n    else {\n        odom.twist.twist.linear.x = 0;\n        odom.twist.twist.linear.y = 0;\n        odom.twist.twist.linear.z = 0;\n        world_T_shield_prev = p;\n        t_prev_update = t_update;\n    }\n\n    debug_pub.publish(odom);\n}\n\nvoid pub_debug_propagate(const std_msgs::Header& header,\n                         const Ref<const Vector3d> v,\n                         const Ref<const Vector3d> a_int)\n{\n    geometry_msgs::TwistStamped acc_compare;\n    acc_compare.header = header;\n    acc_compare.twist.linear.x = v[0];\n    acc_compare.twist.linear.y = v[1];\n    acc_compare.twist.linear.z = v[2];\n    acc_compare.twist.angular.x= a_int[0];\n    acc_compare.twist.angular.y= a_int[1];\n    acc_compare.twist.angular.z= a_int[2];\n    debug_propagate_pub.publish(acc_compare);\n}\n\n// DEBUG only\nVector3d a_int = MatrixXd::Zero(3, 1);\nVector3d a_int_int = MatrixXd::Zero(3, 1);\nvoid propagate(const sensor_msgs::Imu &imu)\n{\n    double cur_t = imu.header.stamp.toSec();\n    Vector3d a, acc_wo_g;\n    a(0) = imu.linear_acceleration.x;\n    a(1) = imu.linear_acceleration.y;\n    a(2) = imu.linear_acceleration.z;\n    Quaterniond world_R_imu(imu.orientation.w, imu.orientation.x, imu.orientation.y, imu.orientation.z);\n\n    double dt = cur_t - t_prev;\n    dt = (dt < IMU_UPDATE_TIME * 5) ? dt : IMU_UPDATE_TIME * 5;\n    ROS_INFO(\"dt in propagate is %f, at the cur_t %f\", dt, cur_t);\n    acc_wo_g = world_R_imu.toRotationMatrix() * a - G;\n    x.segment<3>(0) += x.segment<3>(3) * dt + 0.5 * acc_wo_g * dt * dt;\n    x.segment<3>(3) += acc_wo_g * dt;\n\n    a_int_int += a_int * dt + 0.5 * acc_wo_g * dt * dt;\n    a_int += acc_wo_g * dt;\n    pub_debug_propagate(imu.header, acc_wo_g, a_int_int);\n\n    MatrixXd A = MatrixXd::Zero(6, 6);\n    A.block<3, 3>(0, 3) = MatrixXd::Identity(3, 3);\n\n    MatrixXd U = -MatrixXd::Zero(6, 3);\n    U.block<3, 3>(3, 0) = -world_R_imu.toRotationMatrix();\n\n    MatrixXd F, V;\n    F = MatrixXd::Identity(6, 6) + dt * A;\n    V = dt * U;\n//    cout << \"F \" << endl << F << endl;\n//    cout << \"R \" << endl << R << endl;\n//    cout << \"V \" << endl << V << endl;\n    P = F * P * F.transpose() + V * R * V.transpose();\n\t\n    t_prev = cur_t;\n//    cout << \"P \" << endl << P << endl;\n//    cout << \"x \" << endl << x.transpose() << endl;\n}\n\nstatic void throwState(double current_time)\n{\n    while(imu_buf.size() > 1 &&\n          imu_buf.front()->header.stamp.toSec() < current_time)\n    {\n        // trace backward the time to the imu timestamp\n        t_prev = imu_buf.front()->header.stamp.toSec();\n        ROS_INFO(\"throw state with time: %f\", t_prev);\n        imu_buf.pop();\n        x_history.pop();\n        P_history.pop();\n    }\n}\n\nstatic void repropagate()\n{\n    while (!x_history.empty()) x_history.pop();\n    while (!P_history.empty()) P_history.pop();\n\n    queue <sensor_msgs::Imu::ConstPtr> temp_imu_buf;\n    while (!imu_buf.empty() && imu_buf.size() > 1)\n    {\n        propagate(*imu_buf.front());\n        temp_imu_buf.push(imu_buf.front());\n        x_history.push(x);\n        P_history.push(P);\n        imu_buf.pop();\n    }\n    if (!temp_imu_buf.empty()) {\n        pub_shield_odom(temp_imu_buf.back()->header);\n    }\n    swap(imu_buf, temp_imu_buf);\n}\n\nstatic void update(const geometry_msgs::TwistStamped &pnp)\n{\n    double cur_t = pnp.header.stamp.toSec();\n    Vector3d camera_T_shield;\n\n    camera_T_shield[0] = pnp.twist.linear.x;\n    camera_T_shield[1] = pnp.twist.linear.y;\n    camera_T_shield[2] = pnp.twist.linear.z;\n    Vector3d imu_T_shield = imu_R_camera * camera_T_shield + imu_T_camera;\n\n    imu_T_shield *= 0.001; // Convert millimeter to meter\n\n    throwState(cur_t);\n\n    ROS_INFO(\"Update, at time %f\", cur_t);\n    Quaterniond world_R_imu;\n\n    if (imu_buf.empty()) {\n        world_R_imu.setIdentity();\n    }\n    else {\n        world_R_imu = Quaterniond(imu_buf.front()->orientation.w,\n                                  imu_buf.front()->orientation.x,\n                                  imu_buf.front()->orientation.y,\n                                  imu_buf.front()->orientation.z);\n    }\n    Vector3d world_T_shield = world_R_imu.toRotationMatrix() * imu_T_shield;\n    pub_debug_update(pnp.header, world_T_shield, world_R_imu, cur_t);\n\n    MatrixXd C = MatrixXd::Zero(3, 6);\n    C.block<3, 3>(0, 0) = MatrixXd::Identity(3, 3);\n\n    Matrix3d W = MatrixXd::Identity(3, 3);\n\n    MatrixXd K(6, 3);\n    K = P * C.transpose() * (C * P * C.transpose() + W * Q * W.transpose()).inverse();\n//    cout << \"C \" << endl << C << endl;\n//    cout << \"K \" << endl << K << endl;\n//    cout << \"Q \" << endl << Q << endl;\n    x = x + K * (world_T_shield - C * x);\n    P = P - K * C * P;\n//    cout << \"P \" << endl << P << endl;\n//    cout << \"x \" << endl << x.transpose() << endl;\n\n    if (imu_buf.size() > 1) {\n        // repropagate();\n    }\n}\n\n/**\n * initialize the imu messages\n * @param imu\n */\nstatic void initialize_imu(const sensor_msgs::Imu::ConstPtr &imu)\n{\n    t_prev = imu->header.stamp.toSec();\n    x_history.push(x);\n    P_history.push(P);\n    imu_buf.push(imu);\n    imu_count++;\n    if (imu_count == IMU_INIT_COUNT) {\n        imu_initialized = true;\n    }\n}\n\n/**\n * initialization of the state and convariance from visual\n * @param pnp\n */\nstatic void initialize_visual(const geometry_msgs::TwistStamped::ConstPtr &pnp)\n{\n    double cur_t = pnp->header.stamp.toSec();\n    Vector3d camera_T_shield;\n    ROS_INFO(\"visual init at %f\", cur_t);\n\n    camera_T_shield[0] = pnp->twist.linear.x;\n    camera_T_shield[1] = pnp->twist.linear.y;\n    camera_T_shield[2] = pnp->twist.linear.z;\n    Vector3d imu_T_shield = imu_R_camera * camera_T_shield + imu_T_camera;\n\n    imu_T_shield *= 0.001; // Convert millimeter to meter\n\n    throwState(cur_t);\n\n    Quaterniond world_R_imu;\n\n    if (imu_buf.empty()) {\n        world_R_imu.setIdentity();\n    }\n    else {\n        world_R_imu = Quaterniond(imu_buf.front()->orientation.w,\n                                  imu_buf.front()->orientation.x,\n                                  imu_buf.front()->orientation.y,\n                                  imu_buf.front()->orientation.z);\n    }\n    Vector3d world_T_shield = world_R_imu.toRotationMatrix() * imu_T_shield;\n    pub_debug_update(pnp->header, world_T_shield, world_R_imu, cur_t);\n\n    x.setZero();\n    x.segment<3>(0) = world_T_shield;\n    x.segment<3>(3) << 0, 0, 0;\n\n    cout << \"DEBUG: x initialized with \" << endl << x.transpose() << endl;\n\n    visual_initialized = true;\n\n    // repropagate();\n}\n\n/**\n * handle, save, and process visual messages\n * @param pnp\n */\nvoid visual_callback(const geometry_msgs::TwistStamped::ConstPtr &pnp)\n{\n    visual_valid = !(pnp->twist.linear.x == 0 &&\n        pnp->twist.linear.y == 0 &&\n        pnp->twist.linear.z == 0 );\n\n    if (visual_valid) {\n        if (visual_initialized) {\n            update(*pnp);\n        }\n        else {\n            initialize_visual(pnp);\n        }\n    }\n}\n\n/**\n * handle 400Hz raw imu data\n * @param imu\n */\nvoid imu_callback(const sensor_msgs::Imu::ConstPtr &imu)\n{\n    if (!imu_initialized) {\n        initialize_imu(imu);\n    }\n    else {\n        propagate(*imu);\n        x_history.push(x);\n        P_history.push(P);\n        imu_buf.push(imu);\n\t\tif (imu_buf.size() > MAX_GYRO_QUEUE_SIZE) {\n\t\t\tx_history.pop();\n\t\t\tP_history.pop();\n\t\t\timu_buf.pop();\n\t\t}\n        pub_shield_odom(imu->header);\n    }\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"visual_gyro_fused\");\n    ros::NodeHandle n(\"~\");\n\n//    n.param(\"imu_raw\", imu_topic, string(\"/dji_sdk/imu\")); // 400Hz\n    n.param(\"imu_pose\", pose_topic, string(\"/attitude_estimator/imu\")); // 400Hz\n    n.param(\"visual_topic\", visual_topic, string(\"/pnp_twist\"));\n    n.param(\"publisher_topic\", publisher_topic, string(\"/visual_ekf/shield_T_world\"));\n    n.param(\"debug_topic\", debug_topic, string(\"/visual_ekf/debug_odom\"));\n    n.param(\"accelerometer_noise_weight\", acc_weight, 1000.0);\n    n.param(\"visual_pose_weight\", visual_q_weight, 10.0);\n    n.param(\"node_sleep_time\", sleep_time, 0);\n\n    ros::Duration(sleep_time).sleep();\n\n    // TODO: initalize the R and Q matrix\n    R =      acc_weight * MatrixXd::Identity(3, 3); // accelerometer noise\n    Q = visual_q_weight * MatrixXd::Identity(3, 3); // observation noise\n\n    x.setZero();\n\n    imu_R_camera <<  0, 0, 1,\n                    -1, 0, 0,\n                     0,-1, 0;\n\n    imu_T_camera <<  200, 50, 0; // in millimeter\n\n    ros::Subscriber s2 = n.subscribe(visual_topic, 10, visual_callback);\n    ros::Subscriber s3 = n.subscribe(pose_topic, 100, imu_callback);\n//    pose_pub = n.advertise<geometry_msgs::PoseStamped>(publisher_topic, 100);\n    odom_pub = n.advertise<nav_msgs::Odometry>(publisher_topic, 100);\n    debug_pub= n.advertise<nav_msgs::Odometry>(debug_topic, 100);\n    debug_propagate_pub = n.advertise<geometry_msgs::TwistStamped>(string(\"/visual_ekf/propagate\"), 100);\n\n    ros::Rate r(100);\n    ros::spin();\n}\n\n/**\n *  0   T_x     translation of the shield in world frame\n *  1   T_y\n *  2   T_z\n *  3   v_x     velocity of the shield in world frame\n *  4   v_y\n *  5   v_z\n */\n", "meta": {"hexsha": "b24c69c7399c2480c748cb4f9e61ffa04082386e", "size": 13118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3_estimator/history/visual_ekf/src/visual_ekf_node_translation_wo_bias.cpp", "max_stars_repo_name": "huying163/ros_environment", "max_stars_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-01-30T11:40:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T05:52:47.000Z", "max_issues_repo_path": "3_estimator/history/visual_ekf/src/visual_ekf_node_translation_wo_bias.cpp", "max_issues_repo_name": "huying163/ros_environment", "max_issues_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3_estimator/history/visual_ekf/src/visual_ekf_node_translation_wo_bias.cpp", "max_forks_repo_name": "huying163/ros_environment", "max_forks_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-23T08:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T08:14:57.000Z", "avg_line_length": 31.0853080569, "max_line_length": 105, "alphanum_fraction": 0.62517152, "num_tokens": 3790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.44314614558312754}}
{"text": "#include <iostream>\n#include <fstream>\n#include <ctime>\n#include <cmath>\n#include <vector>\n#include <set>\n#include <map>\n#include <sstream>\n#include <algorithm>\n\n// #define CMG_VERBOSE\n#define MEMORYBOOKKEEPING\n\n#include \"Model.h\"\n\n#include \"Map.h\"\n#include \"ChompMap.h\"\n#include \"MorseGraph.h\"\n#include \"Compute_Morse_Graph.h\"\n#include \"RectGeo.h\"\n\n#include \"SingleOutput.h\"\n#include \"simple_interval.h\"\n\n#include \"Configuration.h\"\n\n#include \"libgp/libgp.hpp\"\n\n#include <boost/serialization/export.hpp>\n#include \"SuccinctGrid.h\"\nBOOST_CLASS_EXPORT_IMPLEMENT(SuccinctGrid);\n#include \"PointerGrid.h\"\nBOOST_CLASS_EXPORT_IMPLEMENT(PointerGrid);\n\nstd::pair<MorseGraph, MapGraph> ComputeConleyMorseGraph ( Model const& model ) {\n  std::shared_ptr<const Map> map = model . map ();\n  MorseGraph morsegraph ( model . phaseSpace () );\n  std::shared_ptr < Grid > phase_space = morsegraph . phaseSpace ();\n\n  int phase_subdiv_init = model . phase_subdiv_init ();\n  int phase_subdiv_min = model . phase_subdiv_min ();\n  int phase_subdiv_max = model . phase_subdiv_max ();\n  int phase_subdiv_limit = model . phase_subdiv_limit ();\n\n  // Compute Morse graph\n  Compute_Morse_Graph ( & morsegraph, phase_space, map, phase_subdiv_init,\n                        phase_subdiv_min, phase_subdiv_max, phase_subdiv_limit );\n\n  std::shared_ptr < TreeGrid > phase_space_chomp =\n    std::dynamic_pointer_cast<TreeGrid> ( morsegraph . phaseSpace () );\n\n  if ( not phase_space_chomp ) {\n    throw std::runtime_error ( \"Cannot interface with chomp for this grid type!\" );\n  }\n\n  typedef std::vector < Grid::GridElement > Subset;\n  for ( size_t v = 0; v < morsegraph . NumVertices (); ++ v) {\n    Subset subset = phase_space_chomp -> subset ( * morsegraph . grid ( v ) );\n    std::shared_ptr<chomp::ConleyIndex_t> conley ( new chomp::ConleyIndex_t );\n    morsegraph . conleyIndex ( v ) = conley;\n    ChompMap chomp_map ( map );\n    chomp::ConleyIndex ( conley . get (), *phase_space_chomp, subset, chomp_map );\n  }\n\n  // Compute multi-valued map digraph\n  MapGraph map_graph ( phase_space, map );\n\n  return std::make_pair ( morsegraph, map_graph );\n}\n\nstd::pair<MorseGraph, MapGraph> ComputeMorseGraph ( Model const& model ) {\n  std::shared_ptr<const Map> map = model . map ();\n  MorseGraph morsegraph ( model . phaseSpace () );\n  std::shared_ptr < Grid > phase_space = morsegraph . phaseSpace ();\n\n  int phase_subdiv_init = model . phase_subdiv_init ();\n  int phase_subdiv_min = model . phase_subdiv_min ();\n  int phase_subdiv_max = model . phase_subdiv_max ();\n  int phase_subdiv_limit = model . phase_subdiv_limit ();\n\n  // Compute Morse graph\n  Compute_Morse_Graph ( & morsegraph, phase_space, map, phase_subdiv_init,\n                        phase_subdiv_min, phase_subdiv_max, phase_subdiv_limit );\n\n  // Compute multi-valued map digraph\n  MapGraph map_graph ( phase_space, map );\n\n  return std::make_pair ( morsegraph, map_graph );\n}\n\nvoid computeMorseGraph ( MorseGraph & morsegraph,\n                         std::shared_ptr<const Map> map,\n                         const int SINGLECMG_INIT_PHASE_SUBDIVISIONS,\n                         const int SINGLECMG_MIN_PHASE_SUBDIVISIONS,\n                         const int SINGLECMG_MAX_PHASE_SUBDIVISIONS,\n                         const int SINGLECMG_COMPLEXITY_LIMIT,\n                         const char * outputfile ) {\n#ifdef CMG_VERBOSE\n  std::cout << \"SingleCMG: computeMorseGraph.\\n\";\n#endif\n  std::shared_ptr < Grid > phase_space = morsegraph . phaseSpace ();\n  clock_t start_time = clock ();\n  Compute_Morse_Graph ( & morsegraph,\n                        phase_space,\n                        map,\n                        SINGLECMG_INIT_PHASE_SUBDIVISIONS,\n                        SINGLECMG_MIN_PHASE_SUBDIVISIONS,\n                        SINGLECMG_MAX_PHASE_SUBDIVISIONS,\n                        SINGLECMG_COMPLEXITY_LIMIT );\n  clock_t stop_time = clock ();\n  if ( outputfile != NULL ) {\n    morsegraph . save ( outputfile );\n  }\n  std::ofstream stats_file ( \"SingleCMG_statistics.txt\" );\n  stats_file << \"Morse Graph calculation resource usage statistics.\\n\";\n  stats_file << \"The final grid has \" << phase_space -> size () << \" grid elements.\\n\";\n  stats_file << \"The computation took \" << ((double)(stop_time-start_time)/(double)CLOCKS_PER_SEC)\n             << \" seconds.\\n\";\n  stats_file << \"All memory figures are in bytes:\\n\";\n  stats_file << \"grid_memory_use = \" << phase_space -> memory () << \"\\n\";\n  stats_file << \"max_graph_memory = \" << max_graph_memory << \"\\n\";\n  stats_file << \"max_scc_memory_internal = \" << max_scc_memory_internal << \"\\n\";\n  stats_file << \"max_scc_memory_external = \" << max_scc_memory_external << \"\\n\";\n  stats_file . close ();\n}\n\nMorseGraph MorseGraphIntvalMap ( int phase_subdiv_min, int phase_subdiv_max,\n                                 std::vector<double> const& phase_lower_bounds,\n                                 std::vector<double> const& phase_upper_bounds,\n                                 std::vector<double> const& params,\n                                 std::string output_file_name ) {\n  std::vector<double> param_lower_bounds = params;\n  std::vector<double> param_upper_bounds = params;\n  int param_dim = params . size();\n  int phase_dim = phase_lower_bounds . size();\n  std::vector<bool> phase_periodic ( phase_dim, false );\n  int phase_subdiv_init = 0;\n  int phase_subdiv_limit = 10000;\n\n  Model model;\n  model . initialize ( param_dim, phase_dim,\n                       phase_subdiv_min, phase_subdiv_max,\n                       phase_subdiv_init, phase_subdiv_limit,\n                       param_lower_bounds, param_upper_bounds,\n                       phase_lower_bounds, phase_upper_bounds,\n                       phase_periodic );\n  std::shared_ptr<const Map> map = model . map ();\n\n  MorseGraph morsegraph ( model . phaseSpace () );\n\n  // INITIALIZE THE PHASE SPACE SUBDIVISION PARAMETERS\n  int SINGLECMG_INIT_PHASE_SUBDIVISIONS = phase_subdiv_init;\n  int SINGLECMG_MIN_PHASE_SUBDIVISIONS = phase_subdiv_min;\n  int SINGLECMG_MAX_PHASE_SUBDIVISIONS = phase_subdiv_max;\n  int SINGLECMG_COMPLEXITY_LIMIT= phase_subdiv_limit;\n\n  // COMPUTE MORSE GRAPH\n  computeMorseGraph ( morsegraph, map,\n                      SINGLECMG_INIT_PHASE_SUBDIVISIONS,\n                      SINGLECMG_MIN_PHASE_SUBDIVISIONS,\n                      SINGLECMG_MAX_PHASE_SUBDIVISIONS,\n                      SINGLECMG_COMPLEXITY_LIMIT,\n                      output_file_name . c_str () );\n\n  std::cout << \"Total Time for Finding Morse Sets \";\n  std::cout << \"and reachability relation: \";\n  std::cout << \": \";\n\n  // Always output the Morse Graph\n  // std::cout << \"Creating graphviz .dot file...\\n\";\n  // CreateDotFile ( \"morsegraph.gv\", conleymorsegraph );\n\n  return morsegraph;\n}\n\nMorseGraph MorseGraphMap ( int phase_subdiv_min, int phase_subdiv_max,\n                           std::vector<double> const& phase_lower_bounds,\n                           std::vector<double> const& phase_upper_bounds,\n                           std::string output_file_name,\n                           std::function<std::vector<double>(std::vector<double>)> const& F ) {\n  std::vector<double> params {0.0};\n  std::vector<double> param_lower_bounds = params;\n  std::vector<double> param_upper_bounds = params;\n  int param_dim = params . size();\n  int phase_dim = phase_lower_bounds . size();\n  std::vector<bool> phase_periodic ( phase_dim, false );\n  int phase_subdiv_init = 0;\n  int phase_subdiv_limit = 10000;\n\n  Model model;\n  model . initialize ( param_dim, phase_dim,\n                       phase_subdiv_min, phase_subdiv_max,\n                       phase_subdiv_init, phase_subdiv_limit,\n                       param_lower_bounds, param_upper_bounds,\n                       phase_lower_bounds, phase_upper_bounds,\n                       phase_periodic, F );\n  std::shared_ptr<const Map> map = model . map ();\n\n  MorseGraph morsegraph ( model . phaseSpace () );\n\n  // INITIALIZE THE PHASE SPACE SUBDIVISION PARAMETERS\n  int SINGLECMG_INIT_PHASE_SUBDIVISIONS = phase_subdiv_init;\n  int SINGLECMG_MIN_PHASE_SUBDIVISIONS = phase_subdiv_min;\n  int SINGLECMG_MAX_PHASE_SUBDIVISIONS = phase_subdiv_max;\n  int SINGLECMG_COMPLEXITY_LIMIT= phase_subdiv_limit;\n\n  // COMPUTE MORSE GRAPH\n  computeMorseGraph ( morsegraph, map,\n                      SINGLECMG_INIT_PHASE_SUBDIVISIONS,\n                      SINGLECMG_MIN_PHASE_SUBDIVISIONS,\n                      SINGLECMG_MAX_PHASE_SUBDIVISIONS,\n                      SINGLECMG_COMPLEXITY_LIMIT,\n                      output_file_name . c_str () );\n\n  std::cout << \"Total Time for Finding Morse Sets \";\n  std::cout << \"and reachability relation: \";\n  std::cout << \": \";\n\n  // Always output the Morse Graph\n  // std::cout << \"Creating graphviz .dot file...\\n\";\n  // CreateDotFile ( \"morsegraph.gv\", conleymorsegraph );\n\n  return morsegraph;\n}\n\n/// Python Bindings\n\n#include <pybind11/pybind11.h>\n#include <pybind11/functional.h>\n#include <pybind11/stl.h>\n\nnamespace py = pybind11;\n\nPYBIND11_MODULE(_cmgdb, m) {\n  ModelBinding(m);\n  GridBinding(m);\n  MapGraphBinding(m);\n  MorseGraphBinding(m);\n\n  m.doc() = \"Conley Morse Graph Database Module\";\n\n  m.def(\"ComputeConleyMorseGraph\", &ComputeConleyMorseGraph);\n  m.def(\"ComputeMorseGraph\", &ComputeMorseGraph);\n  m.def(\"MorseGraphIntvalMap\", &MorseGraphIntvalMap);\n  m.def(\"MorseGraphMap\", &MorseGraphMap);\n}\n", "meta": {"hexsha": "babb3332028f7c8be20c5c67c85e26c327744ee2", "size": 9337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CMGDB/_cmgdb/CMGDB.cpp", "max_stars_repo_name": "marciogameiro/CMGDB_temp2", "max_stars_repo_head_hexsha": "4abb284c5f6b7a471a449e402893901b21d76986", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-11T21:07:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T21:07:58.000Z", "max_issues_repo_path": "src/CMGDB/_cmgdb/CMGDB.cpp", "max_issues_repo_name": "marciogameiro/CMGDB_temp2", "max_issues_repo_head_hexsha": "4abb284c5f6b7a471a449e402893901b21d76986", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CMGDB/_cmgdb/CMGDB.cpp", "max_forks_repo_name": "marciogameiro/CMGDB_temp2", "max_forks_repo_head_hexsha": "4abb284c5f6b7a471a449e402893901b21d76986", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-25T21:13:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T18:47:00.000Z", "avg_line_length": 37.8016194332, "max_line_length": 98, "alphanum_fraction": 0.6607047231, "num_tokens": 2261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788903594355, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.4431197307376583}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020 Ilias Khairullin <ilias@nil.foundation>\n// Copyright (c) 2020 Mikhail Komarov <nemo@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_HASH_POSEIDON_CONSTANTS_HPP\n#define CRYPTO3_HASH_POSEIDON_CONSTANTS_HPP\n\n#include <nil/crypto3/hash/detail/poseidon/poseidon_policy.hpp>\n#include <nil/crypto3/hash/detail/poseidon/poseidon_mds_matrix.hpp>\n#include <nil/crypto3/hash/detail/poseidon/poseidon_lfsr.hpp>\n\n#include <boost/assert.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace hashes {\n            namespace detail {\n                template<typename FieldType, std::size_t Arity, std::size_t PartRounds>\n                struct poseidon_constants_operator {\n                    typedef FieldType field_type;\n                    typedef poseidon_policy<field_type, Arity, PartRounds> policy_type;\n                    typedef poseidon_mds_matrix<field_type, Arity, PartRounds> matrix_policy_type;\n                    typedef poseidon_lfsr<field_type, Arity, PartRounds> constants_generator_policy_type;\n\n                    typedef typename field_type::value_type element_type;\n                    typedef typename matrix_policy_type::state_vector_type state_vector_type;\n\n                    constexpr static const std::size_t state_words = policy_type::state_words;\n                    typedef typename policy_type::state_type state_type;\n\n                    constexpr static const std::size_t full_rounds = policy_type::full_rounds;\n                    constexpr static const std::size_t half_full_rounds = policy_type::half_full_rounds;\n                    constexpr static const std::size_t part_rounds = policy_type::part_rounds;\n\n                    constexpr static const std::size_t round_constants_size = (full_rounds + part_rounds) * state_words;\n                    constexpr static const std::size_t equivalent_round_constants_size =\n                        (full_rounds + 1) * state_words + part_rounds - 1;\n                    typedef algebra::vector<element_type, equivalent_round_constants_size>\n                        equivalent_round_constants_type;\n\n                    /*\n                     * =========================================================\n                     * Optimized\n                     * =========================================================\n                     */\n\n                    inline void arc_sbox_mds_full_round_optimized_first(state_vector_type &A,\n                                                                        std::size_t round_number) const {\n                        BOOST_ASSERT_MSG(round_number < half_full_rounds,\n                                         \"wrong using: arc_sbox_mds_full_round_optimized_first\");\n                        std::size_t constant_number_base = round_number * state_words;\n                        for (std::size_t i = 0; i < state_words; i++) {\n                            A[i] += get_equivalent_round_constant(constant_number_base + i);\n                            A[i] = A[i] * A[i] * A[i] * A[i] * A[i];\n                        }\n                        policy_matrix.product_with_mds_matrix(A);\n                    }\n\n                    inline void arc_sbox_mds_full_round_optimized_last(state_vector_type &A,\n                                                                       std::size_t round_number) const {\n                        BOOST_ASSERT_MSG(round_number >= half_full_rounds + part_rounds,\n                                         \"wrong using: arc_sbox_mds_full_round_optimized_last\");\n                        std::size_t constant_number_base =\n                            (half_full_rounds + 1) * state_words + (part_rounds - 1) +\n                            (round_number - half_full_rounds - part_rounds) * state_words;\n                        for (std::size_t i = 0; i < state_words; i++) {\n                            A[i] += get_equivalent_round_constant(constant_number_base + i);\n                            A[i] = A[i] * A[i] * A[i] * A[i] * A[i];\n                        }\n                        policy_matrix.product_with_mds_matrix(A);\n                    }\n\n                    inline void arc_mds_part_round_optimized_init(state_vector_type &A,\n                                                                  std::size_t round_number) const {\n                        BOOST_ASSERT_MSG(round_number == half_full_rounds,\n                                         \"wrong using: arc_mds_part_round_optimized_init\");\n                        std::size_t constant_number_base = half_full_rounds * state_words;\n                        for (std::size_t i = 0; i < state_words; i++) {\n                            A[i] += get_equivalent_round_constant(constant_number_base + i);\n                        }\n                        policy_matrix.product_with_equivalent_mds_matrix_init(A, round_number);\n                    }\n\n                    inline void sbox_arc_mds_part_round_optimized(state_vector_type &A,\n                                                                  std::size_t round_number) const {\n                        BOOST_ASSERT_MSG(round_number >= half_full_rounds &&\n                                             round_number < half_full_rounds + part_rounds - 1,\n                                         \"wrong using: sbox_arc_mds_part_round_optimized\");\n                        std::size_t constant_number_base =\n                            (half_full_rounds + 1) * state_words + (round_number - half_full_rounds - 1) + 1;\n                        A[0] = A[0] * A[0] * A[0] * A[0] * A[0];\n                        A[0] += get_equivalent_round_constant(constant_number_base);\n                        policy_matrix.product_with_equivalent_mds_matrix(A, round_number);\n                    }\n\n                    inline void sbox_mds_part_round_optimized_last(state_vector_type &A,\n                                                                   std::size_t round_number) const {\n                        BOOST_ASSERT_MSG(round_number == half_full_rounds + part_rounds - 1,\n                                         \"wrong using: sbox_mds_part_round_optimized_last\");\n                        A[0] = A[0] * A[0] * A[0] * A[0] * A[0];\n                        policy_matrix.product_with_equivalent_mds_matrix(A, round_number);\n                    }\n\n                    /*\n                     * =========================================================\n                     * Default\n                     * =========================================================\n                     */\n\n                    inline void arc_sbox_mds_full_round(state_vector_type &A, std::size_t round_number) const {\n                        BOOST_ASSERT_MSG(round_number < half_full_rounds ||\n                                             round_number >= half_full_rounds + part_rounds,\n                                         \"wrong using: arc_sbox_mds_full_round\");\n                        for (std::size_t i = 0; i < state_words; i++) {\n                            A[i] += get_round_constant(round_number * state_words + i);\n                            A[i] = A[i] * A[i] * A[i] * A[i] * A[i];\n                        }\n                        policy_matrix.product_with_mds_matrix(A);\n                    }\n\n                    inline void arc_sbox_mds_part_round(state_vector_type &A, std::size_t round_number) const {\n                        BOOST_ASSERT_MSG(round_number >= half_full_rounds &&\n                                             round_number < half_full_rounds + part_rounds,\n                                         \"wrong using: arc_sbox_mds_part_round\");\n                        for (std::size_t i = 0; i < state_words; i++) {\n                            A[i] += get_round_constant(round_number * state_words + i);\n                        }\n                        A[0] = A[0] * A[0] * A[0] * A[0] * A[0];\n                        policy_matrix.product_with_mds_matrix(A);\n                    }\n\n                    // private:\n                    constexpr inline const element_type &get_round_constant(std::size_t constant_number) const {\n                        return round_constants_generator.round_constants[constant_number];\n                    }\n\n                    constexpr inline state_vector_type\n                        get_round_constants_slice(std::size_t constants_number_base) const {\n                        return algebra::slice<state_words>(round_constants_generator.round_constants,\n                                                           constants_number_base);\n                    }\n\n#ifdef CRYPTO3_HASH_POSEIDON_COMPILE_TIME\n                    constexpr\n#endif\n                    inline void generate_equivalent_round_constants() {\n                        state_vector_type inv_cip1;\n                        state_vector_type agregated_round_constants;\n                        std::size_t equivalent_constant_number_base =\n                            (half_full_rounds + 1) * state_words - half_full_rounds;\n\n                        for (std::size_t i = 0; i < half_full_rounds * state_words; i++) {\n                            equivalent_round_constants[i] = get_round_constant(i);\n                            equivalent_round_constants[equivalent_round_constants_size - i - 1] =\n                                get_round_constant(round_constants_size - i - 1);\n                        }\n\n                        for (std::size_t i = half_full_rounds * state_words;\n                             i < half_full_rounds * state_words + state_words;\n                             i++) {\n                            equivalent_round_constants[i] = get_round_constant(i);\n                        }\n\n                        for (std::size_t r = half_full_rounds + part_rounds - 2; r >= half_full_rounds; r--) {\n                            agregated_round_constants = get_round_constants_slice((r + 1) * state_words) + inv_cip1;\n                            policy_matrix.product_with_inverse_mds_matrix_noalias(agregated_round_constants, inv_cip1);\n                            equivalent_round_constants[equivalent_constant_number_base + r] = inv_cip1[0];\n                            inv_cip1[0] = 0;\n                        }\n\n                        policy_matrix.product_with_inverse_mds_matrix_noalias(agregated_round_constants, inv_cip1);\n                        inv_cip1[0] = 0;\n                        for (std::size_t i = 0; i < state_words; i++) {\n                            equivalent_round_constants[half_full_rounds * state_words + i] += inv_cip1[i];\n                        }\n                    }\n\n                    inline const element_type &get_equivalent_round_constant(std::size_t constant_number) const {\n                        return equivalent_round_constants[constant_number];\n                    }\n\n#ifdef CRYPTO3_HASH_POSEIDON_COMPILE_TIME\n                    constexpr\n#endif\n                    poseidon_constants_operator() :\n                        policy_matrix(), round_constants_generator(), equivalent_round_constants() {\n                        generate_equivalent_round_constants();\n                    }\n\n                    matrix_policy_type policy_matrix;\n                    constants_generator_policy_type round_constants_generator;\n                    equivalent_round_constants_type equivalent_round_constants;\n                };\n            }    // namespace detail\n        }        // namespace hashes\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_HASH_POSEIDON_CONSTANTS_HPP\n", "meta": {"hexsha": "5d1ca01cc4908c142e5c676131423af17a7fb80e", "size": 11857, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/hash/detail/poseidon/poseidon_constants_operator.hpp", "max_stars_repo_name": "JasonCoombs/crypto3-hash", "max_stars_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "include/nil/crypto3/hash/detail/poseidon/poseidon_constants_operator.hpp", "max_issues_repo_name": "JasonCoombs/crypto3-hash", "max_issues_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T23:11:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T00:09:30.000Z", "max_forks_repo_path": "include/nil/crypto3/hash/detail/poseidon/poseidon_constants_operator.hpp", "max_forks_repo_name": "JasonCoombs/crypto3-hash", "max_forks_repo_head_hexsha": "a4f330d14029b0b0330a5697ef24e825137ffded", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-06-04T07:42:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T21:05:07.000Z", "avg_line_length": 57.8390243902, "max_line_length": 120, "alphanum_fraction": 0.5032470271, "num_tokens": 2142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.44300147562867653}}
{"text": "#if !defined(_GATE_EST_BA_HPP_)\n#define _GATE_EST_BA_HPP_\n\n#include <Eigen/Dense>\n#include <ceres/ceres.h>\n\nnamespace gate_est {\n\n  class CostFunctionReProjection {\n    public:\n    inline CostFunctionReProjection(\n      const Eigen::Vector3d& pt,\n      const Eigen::MatrixXd& t,\n      const Eigen::Matrix3d& cm,\n      const Eigen::Vector2d& uv)\n      : fx_(cm(0, 0)), fy_(cm(1, 1)), cx_(cm(0, 2)), cy_(cm(1, 2)),\n        u_(uv[0]), v_(uv[1]),\n        t_(t),\n        pt_x_(pt[0]), pt_y_(pt[1]), pt_z_(pt[2]) { }\n\n    template <typename T>\n    inline bool operator() (const T* const point, T* residual) const {\n      auto x = point[0] + T(pt_x_);\n      auto y = point[1] + T(pt_y_);\n      auto z = point[2] + T(pt_z_);\n\n      auto px = T(t_(0, 0)) * x + T(t_(0, 1)) * y + T(t_(0, 2)) * z  + T(t_(0, 3));\n      auto py = T(t_(1, 0)) * x + T(t_(1, 1)) * y + T(t_(1, 2)) * z  + T(t_(1, 3));\n      auto pz = T(t_(2, 0)) * x + T(t_(2, 1)) * y + T(t_(2, 2)) * z  + T(t_(2, 3));\n\n      auto u = T(fx_) * px / pz + T(cx_);\n      auto v = T(fy_) * py / pz + T(cy_);\n\n      residual[0] = T(u_) - u;\n      residual[1] = T(v_) - v;\n\n      return true;\n    }\n\n    private:\n      const double fx_;\n      const double fy_;\n      const double cx_;\n      const double cy_;\n      const double u_;\n      const double v_;\n      const double pt_x_;\n      const double pt_y_;\n      const double pt_z_;\n      const Eigen::MatrixXd t_;\n  };\n  \n} // gate_est\n\n\n#endif // _GATE_EST_BA_HPP_\n", "meta": {"hexsha": "f5b72298f85d18261fa20c8d894f68ac0d825168", "size": 1462, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gate_est/src/ba.hpp", "max_stars_repo_name": "Veilkrand/drone_race", "max_stars_repo_head_hexsha": "7391f1a94bfe354aab3e24be61b76e1595481ad9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gate_est/src/ba.hpp", "max_issues_repo_name": "Veilkrand/drone_race", "max_issues_repo_head_hexsha": "7391f1a94bfe354aab3e24be61b76e1595481ad9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gate_est/src/ba.hpp", "max_forks_repo_name": "Veilkrand/drone_race", "max_forks_repo_head_hexsha": "7391f1a94bfe354aab3e24be61b76e1595481ad9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-15T10:34:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-09T15:08:20.000Z", "avg_line_length": 25.649122807, "max_line_length": 83, "alphanum_fraction": 0.5266757866, "num_tokens": 513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.44300146988989125}}
{"text": "/**\n * @file\n * This file is part of SeisSol.\n *\n * @author Carsten Uphoff (c.uphoff AT tum.de, http://www5.in.tum.de/wiki/index.php/Carsten_Uphoff,_M.Sc.)\n * @author Sebastian Wolf (wolf.sebastian AT in.tum.de, https://www5.in.tum.de/wiki/index.php/Sebastian_Wolf,_M.Sc.)\n *\n * @section LICENSE\n * Copyright (c) 2017 - 2020, SeisSol Group\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its\n *    contributors may be used to endorse or promote products derived from this\n *    software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * @section DESCRIPTION\n * \n **/\n#include <Eigen/Eigenvalues>\n#include <Kernels/precision.hpp>\n#include <Initializer/typedefs.hpp>\n\n#include <PUML/PUML.h>\n#include <PUML/Downward.h>\n#include <PUML/Upward.h>\n#include \"LtsWeights.h\"\n\n#include <Eigen/Dense>\n\n#include <Initializer/ParameterDB.h>\n#include <Parallel/MPI.h>\n\n#include <generated_code/tensor.h>\n#include <generated_code/init.h>\n\nclass FaceSorter {\nprivate:\n\tstd::vector<PUML::TETPUML::face_t> const& m_faces;\n\npublic:\n\tFaceSorter(std::vector<PUML::TETPUML::face_t> const& faces) : m_faces(faces) {}\n\n\tbool operator()(unsigned int a, unsigned int b) const {\n\t\treturn m_faces[a].gid() < m_faces[b].gid();\n\t}\n};\n\nvoid seissol::initializers::time_stepping::LtsWeights::computeMaxTimesteps( PUML::TETPUML const&  mesh,\n                                                                            std::vector<double> const& pWaveVel,\n                                                                            std::vector<double>& timestep ) {\n  std::vector<PUML::TETPUML::cell_t> const& cells = mesh.cells();\n  std::vector<PUML::TETPUML::vertex_t> const& vertices = mesh.vertices();\n\n  for (unsigned cell = 0; cell < cells.size(); ++cell) {\n    // Compute insphere radius\n    Eigen::Vector3d barycentre(0.,0.,0.);\n    Eigen::Vector3d x[4];\n    unsigned vertLids[4];\n    PUML::Downward::vertices(mesh, cells[cell], vertLids);\n    for (unsigned vtx = 0; vtx < 4; ++vtx) {\n      for (unsigned d = 0; d < 3; ++d) {\n        x[vtx](d) = vertices[ vertLids[vtx] ].coordinate()[d];\n      }\n    }\n    Eigen::Matrix4d A;\n    A << x[0](0), x[0](1), x[0](2), 1.0,\n         x[1](0), x[1](1), x[1](2), 1.0,\n         x[2](0), x[2](1), x[2](2), 1.0,\n         x[3](0), x[3](1), x[3](2), 1.0;\n\n    double alpha = A.determinant();\n    double Nabc = ( (x[1]-x[0]).cross(x[2]-x[0]) ).norm();\n    double Nabd = ( (x[1]-x[0]).cross(x[3]-x[0]) ).norm();\n    double Nacd = ( (x[2]-x[0]).cross(x[3]-x[0]) ).norm();\n    double Nbcd = ( (x[2]-x[1]).cross(x[3]-x[1]) ).norm();\n    double insphere = std::fabs(alpha) / (Nabc + Nabd + Nacd + Nbcd);\n    \n    // Compute maximum timestep (CFL=1)\n    timestep[cell] = 2.0 * insphere / (pWaveVel[cell] * (2*CONVERGENCE_ORDER-1));\n  }\n}\n\nint seissol::initializers::time_stepping::LtsWeights::getCluster( double    timestep,\n                                                                  double    globalMinTimestep,\n                                                                  unsigned  rate ) {\n  if (rate == 1) {\n    return 0;\n  }\n\n  double upper;\n  upper = rate * globalMinTimestep;\n\n  int cluster = 0;\n  while (upper <= timestep) {\n    upper *= rate;\n    ++cluster;\n  }\n  return cluster;\n}\n\nint seissol::initializers::time_stepping::LtsWeights::getBoundaryCondition( int const* boundaryCond,\n                                                                            unsigned cell,\n                                                                            unsigned face ) {\n  int bcCurrentFace = ((boundaryCond[cell] >> (face*8)) & 0xFF);\n  if (bcCurrentFace > 64) {\n     bcCurrentFace = 3;\n  }\n  return bcCurrentFace;\n}\n\nint seissol::initializers::time_stepping::LtsWeights::ipow(int x, int y) {\n  assert(y >= 0);\n\n  if (y == 0) {\n    return 1;\n  }\n  int result = x;\n  while(--y) {\n    result *= x;\n  }\n  return result;\n}\n\nvoid seissol::initializers::time_stepping::LtsWeights::computeWeights(PUML::TETPUML const& mesh) {\n  logInfo(seissol::MPI::mpi.rank()) << \"Computing LTS weights.\";\n\n  std::vector<PUML::TETPUML::cell_t> const& cells = mesh.cells();\n  int const* boundaryCond = mesh.cellData(1);\n\n  std::vector<double> pWaveVel;\n  pWaveVel.resize(cells.size());\n  \n  seissol::initializers::ElementBarycentreGeneratorPUML queryGen(mesh);  \n  //up to now we only distinguish between anisotropic elastic any other isotropic material\n#ifdef USE_ANISOTROPIC\n  std::vector<seissol::model::AnisotropicMaterial> materials(cells.size());\n  seissol::initializers::MaterialParameterDB<seissol::model::AnisotropicMaterial> parameterDB;\n#else\n  std::vector<seissol::model::ElasticMaterial> materials(cells.size());\n  seissol::initializers::MaterialParameterDB<seissol::model::ElasticMaterial> parameterDB;\n#endif \n  parameterDB.setMaterialVector(&materials);\n  parameterDB.evaluateModel(m_velocityModel, queryGen);\n  for(unsigned cell = 0; cell < cells.size(); ++cell) {\n    pWaveVel[cell] = materials[cell].getMaxWaveSpeed();\n  }\n  std::vector<double> timestep;\n  timestep.resize(cells.size());\n  computeMaxTimesteps(mesh, pWaveVel, timestep);\n\n  double localMinTimestep = *std::min_element(timestep.begin(), timestep.end());\n  double localMaxTimestep = *std::max_element(timestep.begin(), timestep.end());\n  double globalMinTimestep;\n  double globalMaxTimestep;\n#ifdef USE_MPI\n  MPI_Allreduce(&localMinTimestep, &globalMinTimestep, 1, MPI_DOUBLE, MPI_MIN, seissol::MPI::mpi.comm());\n  MPI_Allreduce(&localMaxTimestep, &globalMaxTimestep, 1, MPI_DOUBLE, MPI_MAX, seissol::MPI::mpi.comm());\n#else\n  globalMinTimestep = localMinTimestep;\n  globalMaxTimestep = localMaxTimestep;\n#endif\n\n  int* cluster = new int[cells.size()];\n  for (unsigned cell = 0; cell < cells.size(); ++cell) {\n    cluster[cell] = getCluster(timestep[cell], globalMinTimestep, m_rate);\n  } \n  \n  int totalNumberOfReductions = enforceMaximumDifference(mesh, cluster);\n\n  delete[] m_vertexWeights;\n  //m_ncon = 2;\n  m_ncon = 1;\n  m_vertexWeights = new int[cells.size() * m_ncon];\n  int maxCluster = getCluster(globalMaxTimestep, globalMinTimestep, m_rate);\n  int drToCellRatio = 1;\n  for (unsigned cell = 0; cell < cells.size(); ++cell) {    \n    int dynamicRupture = 0;\n    for (unsigned face = 0; face < 4; ++face) {\n      dynamicRupture += ( getBoundaryCondition(boundaryCond, cell, face) == 3) ? 1 : 0;\n    }\n    \n    m_vertexWeights[m_ncon * cell] = (1 + drToCellRatio*dynamicRupture) * ipow(m_rate, maxCluster - cluster[cell]);\n    //m_vertexWeights[m_ncon * cell + 1] = (dynamicRupture > 0) ? 1 : 0;\n  }\n\n  delete[] cluster;\n\n  logInfo(seissol::MPI::mpi.rank()) << \"Computing LTS weights. Done. \" << utils::nospace << '(' << totalNumberOfReductions << \" reductions.)\";\n}\n\nint seissol::initializers::time_stepping::LtsWeights::enforceMaximumDifference(PUML::TETPUML const& mesh, int* cluster) {\n  int totalNumberOfReductions = 0;\n  int globalNumberOfReductions;\n  do {\n    int localNumberOfReductions = enforceMaximumDifferenceLocal(mesh, cluster);\n\n#ifdef USE_MPI\n    MPI_Allreduce(&localNumberOfReductions, &globalNumberOfReductions, 1, MPI_INT, MPI_SUM, seissol::MPI::mpi.comm());    \n#else\n    globalNumberOfReductions = localNumberOfReductions;\n#endif // USE_MPI\n    totalNumberOfReductions += globalNumberOfReductions;\n  } while (globalNumberOfReductions > 0);\n  return totalNumberOfReductions;\n}\n\nint seissol::initializers::time_stepping::LtsWeights::enforceMaximumDifferenceLocal(PUML::TETPUML const& mesh, int* cluster, int maxDifference) {\n  int numberOfReductions = 0;\n  \n  std::vector<PUML::TETPUML::cell_t> const& cells = mesh.cells();\n  std::vector<PUML::TETPUML::face_t> const& faces = mesh.faces();\n\tint const* boundaryCond = mesh.cellData(1);\n\n#ifdef USE_MPI\n  std::unordered_map<int, std::vector<int>> rankToSharedFaces;\n  std::unordered_map<int, int> localFaceIdToLocalCellId;\n#endif // USE_MPI\n\n  for (unsigned cell = 0; cell < cells.size(); ++cell) {\n    int timeCluster = cluster[cell];\n\n\t\tunsigned int faceids[4];\n\t\tPUML::Downward::faces(mesh, cells[cell], faceids);\n    for (unsigned f = 0; f < 4; ++f) {\n      int difference = maxDifference;\n      int boundary = getBoundaryCondition(boundaryCond, cell, f);\n      // Continue for regular, dynamic rupture, and periodic boundary cells\n      if (boundary == 0 || boundary == 3 || boundary == 6) {\n        // We treat MPI neighbours later\n        auto const& face = faces[ faceids[f] ];\n        if (!face.isShared()) {\n          int cellIds[2];\n          PUML::Upward::cells(mesh, face, cellIds);\n\n          int neighbourCell = (cellIds[0] == static_cast<int>(cell)) ? cellIds[1] : cellIds[0];\n          int otherTimeCluster = cluster[neighbourCell];\n          \n          if (boundary == 3) {\n            difference = 0;\n          }\n\n          if (timeCluster > otherTimeCluster + difference) {\n            timeCluster = otherTimeCluster + difference;\n            ++numberOfReductions;\n          }\n        }\n#ifdef USE_MPI\n        else {\n          rankToSharedFaces[ face.shared()[0] ].push_back(faceids[f]);\n          localFaceIdToLocalCellId[ faceids[f] ] = cell;\n        }\n#endif // USE_MPI\n      }\n    }\n    cluster[cell] = timeCluster;\n  }\n\n#ifdef USE_MPI\n  FaceSorter faceSorter(faces);\n  for (auto& sharedFaces: rankToSharedFaces) {\n    std::sort(sharedFaces.second.begin(), sharedFaces.second.end(), faceSorter);\n  }\n  \n  auto numExchanges = rankToSharedFaces.size();\n  MPI_Request* requests = new MPI_Request[2*numExchanges];\n  int** ghost = new int*[numExchanges];\n  int** copy = new int*[numExchanges];\n  auto exchange = rankToSharedFaces.begin();\n  for (unsigned ex = 0; ex < numExchanges; ++ex) {\n    auto exchangeSize = exchange->second.size();\n    ghost[ex] = new int[ exchangeSize ];\n    copy[ex]  = new int[ exchangeSize ];\n    \n    for (unsigned n = 0; n < exchangeSize; ++n) {\n      copy[ex][n] = cluster[ localFaceIdToLocalCellId[ exchange->second[n] ] ];\n    }\n    MPI_Isend( copy[ex], exchangeSize, MPI_INT, exchange->first, 0, seissol::MPI::mpi.comm(), &requests[ex]);\n    MPI_Irecv(ghost[ex], exchangeSize, MPI_INT, exchange->first, 0, seissol::MPI::mpi.comm(), &requests[numExchanges + ex]);\n    ++exchange;\n  }\n  \n  MPI_Waitall(2*numExchanges, requests, MPI_STATUSES_IGNORE);\n\n  exchange = rankToSharedFaces.begin();\n  for (unsigned ex = 0; ex < numExchanges; ++ex) {\n    auto exchangeSize = exchange->second.size();\n    for (unsigned n = 0; n < exchangeSize; ++n) {\n      int difference = maxDifference;\n      int otherTimeCluster = ghost[ex][n];\n      \n      int cellIds[2];\n      PUML::Upward::cells(mesh, faces[ exchange->second[n] ], cellIds);\n      int cell = (cellIds[0] >= 0) ? cellIds[0] : cellIds[1];\n\n      unsigned int faceids[4];\n      PUML::Downward::faces(mesh, cells[cell], faceids);\n      unsigned f = 0;\n      for (; f < 4 && static_cast<int>(faceids[f]) != exchange->second[n]; ++f);\n      assert(f != 4);\n      \n      int boundary = getBoundaryCondition(boundaryCond, cell, f);\n      if (boundary == 3) {\n        difference = 0;\n      }\n\n      if (cluster[cell] > otherTimeCluster + difference) {\n        cluster[cell] = otherTimeCluster + difference;\n        ++numberOfReductions;\n      }\n    }\n    ++exchange;\n  }  \n  \n  for (unsigned ex = 0; ex < numExchanges; ++ex) {\n    delete[] copy[ex];\n    delete[] ghost[ex];\n  }\n  delete[] copy;\n  delete[] ghost;\n  delete[] requests;\n#endif // USE_MPI\n\n  return numberOfReductions;\n}\n", "meta": {"hexsha": "04d72a20742788e4989c4541f161d566c97f1847", "size": 12681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Initializer/time_stepping/LtsWeights.cpp", "max_stars_repo_name": "VMPW/SeisSol", "max_stars_repo_head_hexsha": "641e6a2d1e49173142f85688fbf8e40828f0c37a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Initializer/time_stepping/LtsWeights.cpp", "max_issues_repo_name": "VMPW/SeisSol", "max_issues_repo_head_hexsha": "641e6a2d1e49173142f85688fbf8e40828f0c37a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Initializer/time_stepping/LtsWeights.cpp", "max_forks_repo_name": "VMPW/SeisSol", "max_forks_repo_head_hexsha": "641e6a2d1e49173142f85688fbf8e40828f0c37a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-09T14:02:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T14:02:59.000Z", "avg_line_length": 36.5446685879, "max_line_length": 145, "alphanum_fraction": 0.6493178771, "num_tokens": 3481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.44300146988989125}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_FFT_FFTWBACKEND_HPP\n  #define BOOST_MATH_FFT_FFTWBACKEND_HPP\n  \n  #include <memory>\n\n  #if defined(__GNUC__)\n  #include <fftw3.h>\n  #endif\n  #include <boost/math/fft/dft_api.hpp>\n  #include <boost/math/fft/multiprecision_complex.hpp>\n\n  namespace boost { namespace math {  namespace fft {\n\n  namespace detail {\n\n  #if defined(__GNUC__)\n  template<typename T>\n  struct fftw_traits_c_interface;\n\n  template<>\n  struct fftw_traits_c_interface<float>\n  {\n    using plan_type = fftwf_plan;\n\n    using real_value_type = float;\n\n    using complex_value_type = real_value_type[2U];\n\n    static plan_type plan_construct(\n      int n, complex_value_type* in, complex_value_type* out, int sign, unsigned int flags) \n    { \n      return ::fftwf_plan_dft_1d(n, in, out, sign, flags); \n    }\n    static plan_type plan_construct_r2c(\n      int n, real_value_type* in, complex_value_type* out, unsigned int flags) \n    { \n      return ::fftwf_plan_dft_r2c_1d(n, in, out, flags); \n    }\n    static plan_type plan_construct_c2r(\n      int n, complex_value_type* in, real_value_type* out, unsigned int flags) \n    { \n      return ::fftwf_plan_dft_c2r_1d(n, in, out, flags); \n    }\n    static plan_type plan_construct_r2r(\n      int n, real_value_type* in, real_value_type* out, fftw_r2r_kind kind, unsigned int flags) \n    { \n      return ::fftwf_plan_r2r_1d(n, in, out, kind, flags); \n    }\n    \n    static void plan_execute(\n      plan_type plan, complex_value_type* in, complex_value_type* out) \n    { \n      ::fftwf_execute_dft(plan, in, out); \n    }\n    static void plan_execute_r2c(\n      plan_type plan, real_value_type* in, complex_value_type* out) \n    { \n      ::fftwf_execute_dft_r2c(plan, in, out); \n    }\n    static void plan_execute_c2r(\n      plan_type plan, complex_value_type* in, real_value_type* out) \n    { \n      ::fftwf_execute_dft_c2r(plan, in, out); \n    }\n    static void plan_execute_r2r(\n      plan_type plan, real_value_type* in, real_value_type* out) \n    { \n      ::fftwf_execute_r2r(plan, in, out); \n    }\n\n    static void plan_destroy(plan_type p) { ::fftwf_destroy_plan(p); }\n    \n    static int alignment_of(real_value_type* p) { return ::fftwf_alignment_of(p); }\n  };\n\n  template<>\n  struct fftw_traits_c_interface<double>\n  {\n    using plan_type = fftw_plan;\n\n    using real_value_type = double;\n\n    using complex_value_type = real_value_type[2U];\n\n    static plan_type plan_construct(\n      int n, complex_value_type* in, complex_value_type* out, int sign, unsigned int flags) \n    { \n      return ::fftw_plan_dft_1d(n, in, out, sign, flags); \n    }\n    static plan_type plan_construct_r2c(\n      int n, real_value_type* in, complex_value_type* out, unsigned int flags) \n    { \n      return ::fftw_plan_dft_r2c_1d(n, in, out, flags); \n    }\n    static plan_type plan_construct_c2r(\n      int n, complex_value_type* in, real_value_type* out, unsigned int flags) \n    { \n      return ::fftw_plan_dft_c2r_1d(n, in, out, flags); \n    }\n    static plan_type plan_construct_r2r(\n      int n, real_value_type* in, real_value_type* out, fftw_r2r_kind kind, unsigned int flags) \n    { \n      return ::fftw_plan_r2r_1d(n, in, out, kind, flags); \n    }\n\n    static void plan_execute(\n      plan_type plan, complex_value_type* in, complex_value_type* out) \n    { \n      ::fftw_execute_dft(plan, in, out); \n    }\n    static void plan_execute_r2c(\n      plan_type plan, real_value_type* in, complex_value_type* out) \n    { \n      ::fftw_execute_dft_r2c(plan, in, out); \n    }\n    static void plan_execute_c2r(\n      plan_type plan, complex_value_type* in, real_value_type* out) \n    { \n      ::fftw_execute_dft_c2r(plan, in, out); \n    }\n    static void plan_execute_r2r(\n      plan_type plan, real_value_type* in, real_value_type* out) \n    { \n      ::fftw_execute_r2r(plan, in, out); \n    }\n\n    static void plan_destroy(plan_type p) { ::fftw_destroy_plan(p); }\n    \n    static int alignment_of(real_value_type* p) { return ::fftw_alignment_of(p); }\n  };\n\n  template<>\n  struct fftw_traits_c_interface<long double>\n  {\n    using plan_type = fftwl_plan;\n\n    using real_value_type = long double;\n\n    using complex_value_type = real_value_type[2U];\n\n    static plan_type plan_construct(\n      int n, complex_value_type* in, complex_value_type* out, int sign, unsigned int flags) \n    { \n      return ::fftwl_plan_dft_1d(n, in, out, sign, flags); \n    }\n    static plan_type plan_construct_r2c(\n      int n, real_value_type* in, complex_value_type* out, unsigned int flags) \n    { \n      return ::fftwl_plan_dft_r2c_1d(n, in, out, flags); \n    }\n    static plan_type plan_construct_c2r(\n      int n, complex_value_type* in, real_value_type* out, unsigned int flags) \n    { \n      return ::fftwl_plan_dft_c2r_1d(n, in, out, flags); \n    }\n    \n    static plan_type plan_construct_r2r(\n      int n, real_value_type* in, real_value_type* out, fftw_r2r_kind kind, unsigned int flags) \n    { \n      return ::fftwl_plan_r2r_1d(n, in, out, kind, flags); \n    }\n\n    static void plan_execute(\n      plan_type plan, complex_value_type* in, complex_value_type* out) \n    { \n      ::fftwl_execute_dft(plan, in, out); \n    }\n    static void plan_execute_r2c(\n      plan_type plan, real_value_type* in, complex_value_type* out) \n    { \n      ::fftwl_execute_dft_r2c(plan, in, out); \n    }\n    static void plan_execute_c2r(\n      plan_type plan, complex_value_type* in, real_value_type* out) \n    { \n      ::fftwl_execute_dft_c2r(plan, in, out); \n    }\n    static void plan_execute_r2r(\n      plan_type plan, real_value_type* in, real_value_type* out) \n    { \n      ::fftwl_execute_r2r(plan, in, out); \n    }\n\n    static void plan_destroy(plan_type p) { ::fftwl_destroy_plan(p); }\n    \n    static int alignment_of(real_value_type* p) { return ::fftwl_alignment_of(p); }\n  };\n  #endif\n\n  #ifdef BOOST_MATH_USE_FLOAT128\n  template<>\n  struct fftw_traits_c_interface<boost::multiprecision::float128>\n  {\n    using plan_type = fftwq_plan;\n\n    // Type casting for fftw:\n    using real_value_type = boost::float128_t;\n\n    using complex_value_type = boost::multiprecision::complex128;\n\n    static plan_type plan_construct(\n      int n, complex_value_type* in, complex_value_type* out, int sign, unsigned int flags)\n    {\n      return ::fftwq_plan_dft_1d(n, (real_value_type(*)[2])in, (real_value_type(*)[2])out, sign, flags);\n    }\n    static plan_type plan_construct_r2c(\n      int n, real_value_type* in, complex_value_type* out, unsigned int flags) \n    { \n      return ::fftwq_plan_dft_r2c_1d(n, in, (real_value_type(*)[2])out, flags); \n    }\n    static plan_type plan_construct_c2r(\n      int n, complex_value_type* in, real_value_type* out, unsigned int flags) \n    { \n      return ::fftwq_plan_dft_c2r_1d(n, (real_value_type(*)[2])in, out, flags); \n    }\n    \n    static plan_type plan_construct_r2r(\n      int n, real_value_type* in, real_value_type* out, fftw_r2r_kind kind, unsigned int flags) \n    { \n      return ::fftwq_plan_r2r_1d(n, in, out, kind, flags); \n    }\n\n    static void plan_execute(\n      plan_type plan, complex_value_type* in, complex_value_type* out)\n    {\n      ::fftwq_execute_dft(plan, (real_value_type(*)[2])in, (real_value_type(*)[2])out);\n    }\n    static void plan_execute_r2c(\n      plan_type plan, real_value_type* in, complex_value_type* out) \n    { \n      ::fftwq_execute_dft_r2c(plan, in, (real_value_type(*)[2]) out); \n    }\n    static void plan_execute_c2r(\n      plan_type plan, complex_value_type* in, real_value_type* out) \n    { \n      ::fftwq_execute_dft_c2r(plan,(real_value_type(*)[2]) in, out); \n    }\n    static void plan_execute_r2r(\n      plan_type plan, real_value_type* in, real_value_type* out) \n    { \n      ::fftwq_execute_r2r(plan, in, out); \n    }\n\n    static void plan_destroy(plan_type p) { ::fftwq_destroy_plan(p); }\n    \n    static int alignment_of(real_value_type* p) { return ::fftwq_alignment_of(p); }\n  };\n  #endif\n\n  #if defined(__GNUC__)\n  template<class NativeComplexType, class Allocator_t >\n  class fftw_backend\n  {\n  public:\n    using value_type     = NativeComplexType;\n    using allocator_type = Allocator_t;\n\n  private:\n    using real_value_type    = typename NativeComplexType::value_type;\n    using plan_type          = typename detail::fftw_traits_c_interface<real_value_type>::plan_type;\n    using complex_value_type = boost::multiprecision::complex<real_value_type>;\n    using fftw_real_value_type = typename detail::fftw_traits_c_interface<real_value_type>::real_value_type;\n   \n    void execute(plan_type plan, plan_type unaligned_plan, const complex_value_type* in, complex_value_type* out) const\n    {\n      using local_complex_type = typename detail::fftw_traits_c_interface<real_value_type>::complex_value_type;\n      \n      if(in!=out) // We have to copy, because fftw plan is forced to be in-place: from: nullptr, to: nullptr\n        std::copy(in,in+size(),out);\n      \n      const int out_alignment = detail::fftw_traits_c_interface<real_value_type>::alignment_of(\n                reinterpret_cast<fftw_real_value_type*>(out));\n                \n      if(out_alignment==ref_alignment)\n        detail::fftw_traits_c_interface<real_value_type>::plan_execute\n        (\n          plan,\n          reinterpret_cast<local_complex_type*>(out),\n          reinterpret_cast<local_complex_type*>(out)\n        );\n      else\n        detail::fftw_traits_c_interface<real_value_type>::plan_execute\n        (\n          unaligned_plan,\n          reinterpret_cast<local_complex_type*>(out),\n          reinterpret_cast<local_complex_type*>(out)\n        );\n    }\n    \n    void free()\n    {\n      detail::fftw_traits_c_interface<real_value_type>::plan_destroy(my_forward_plan);\n      detail::fftw_traits_c_interface<real_value_type>::plan_destroy(my_backward_plan);\n      detail::fftw_traits_c_interface<real_value_type>::plan_destroy(my_forward_unaligned_plan);\n      detail::fftw_traits_c_interface<real_value_type>::plan_destroy(my_backward_unaligned_plan);\n    }\n    void alloc()\n    {\n      my_forward_plan = \n        detail::fftw_traits_c_interface<real_value_type>::plan_construct\n        (\n          size(), \n          nullptr, \n          nullptr, \n          FFTW_FORWARD,  \n          FFTW_ESTIMATE | FFTW_PRESERVE_INPUT\n        );\n      my_backward_plan =\n        detail::fftw_traits_c_interface<real_value_type>::plan_construct\n        (\n          size(), \n          nullptr, \n          nullptr, \n          FFTW_BACKWARD, \n          FFTW_ESTIMATE | FFTW_PRESERVE_INPUT\n        );\n      my_forward_unaligned_plan = \n        detail::fftw_traits_c_interface<real_value_type>::plan_construct\n        (\n          size(), \n          nullptr, \n          nullptr, \n          FFTW_FORWARD,  \n          FFTW_ESTIMATE | FFTW_PRESERVE_INPUT | FFTW_UNALIGNED\n        );\n      my_backward_unaligned_plan =\n        detail::fftw_traits_c_interface<real_value_type>::plan_construct\n        (\n          size(), \n          nullptr, \n          nullptr, \n          FFTW_BACKWARD, \n          FFTW_ESTIMATE | FFTW_PRESERVE_INPUT | FFTW_UNALIGNED\n        );\n    }\n\n  public:\n    fftw_backend(std::size_t n, const allocator_type& = allocator_type{} )\n      : my_size{ n },\n        ref_alignment{\n            detail::fftw_traits_c_interface<real_value_type>::alignment_of(nullptr)}\n    {\n      // For C++11, this line needs to be constexpr-ified.\n      // Then we could restore the constexpr-ness of this constructor.\n      alloc();\n    }\n\n    ~fftw_backend()\n    {\n      free();\n    }\n    \n    void resize(std::size_t new_size)\n    {\n      if(size()!=new_size)\n      {\n        free();\n        my_size = new_size;\n        alloc();\n      }\n    }\n\n    constexpr std::size_t size() const { return my_size; }\n    \n    void forward(const complex_value_type* in, complex_value_type* out) const\n    {\n      execute(my_forward_plan, my_forward_unaligned_plan, in, out);  \n    }\n\n    void backward(const complex_value_type* in, complex_value_type* out) const\n    {\n      execute(my_backward_plan, my_backward_unaligned_plan, in, out);  \n    }\n  private:\n    std::size_t my_size;\n    const int   ref_alignment;\n    \n    plan_type   my_forward_plan;\n    plan_type   my_backward_plan;\n    plan_type   my_forward_unaligned_plan;\n    plan_type   my_backward_unaligned_plan;\n  };\n  #endif\n\n  #if defined(__GNUC__)\n  template<class T, class Allocator_t >\n  class fftw_rfft_backend\n  {\n  public:\n    // using value_type     = T;\n    using allocator_type = Allocator_t;\n  \n  private:\n    using real_value_type    = T;\n    using plan_type          = typename detail::fftw_traits_c_interface<real_value_type>::plan_type;\n    using fftw_real_value_type     = typename detail::fftw_traits_c_interface<real_value_type>::real_value_type;\n    using fftw_complex_value_type  = typename detail::fftw_traits_c_interface<real_value_type>::complex_value_type;\n      \n    template<class U>\n    using vector_t = std::vector<U, typename std::allocator_traits<allocator_type>::template rebind_alloc<U> >;\n   \n    void execute(plan_type plan, plan_type unaligned_plan, const real_value_type* in, real_value_type* out) const\n    // precondition:\n    // size(in)  >= size()\n    // size(out) >= size()\n    {\n      const int out_alignment = detail::fftw_traits_c_interface<real_value_type>::alignment_of(\n                reinterpret_cast<fftw_real_value_type*>(out));\n                \n      if(in!=out) // We have to copy, because fftw plan is forced to be in-place: from: nullptr, to: nullptr\n        std::copy(in,in+size(),out);\n                \n      if(out_alignment==ref_alignment)\n        detail::fftw_traits_c_interface<real_value_type>::plan_execute_r2r\n        (\n          plan,\n          reinterpret_cast<fftw_real_value_type*>(out),\n          reinterpret_cast<fftw_real_value_type*>(out)\n        );\n      else\n        detail::fftw_traits_c_interface<real_value_type>::plan_execute_r2r\n        (\n          unaligned_plan,\n          reinterpret_cast<fftw_real_value_type*>(out),\n          reinterpret_cast<fftw_real_value_type*>(out)\n        );\n    }\n    \n    void free()\n    {\n      detail::fftw_traits_c_interface<real_value_type>::plan_destroy(my_r2hc_plan);\n      detail::fftw_traits_c_interface<real_value_type>::plan_destroy(my_hc2r_plan);\n      detail::fftw_traits_c_interface<real_value_type>::plan_destroy(my_r2hc_unaligned_plan);\n      detail::fftw_traits_c_interface<real_value_type>::plan_destroy(my_hc2r_unaligned_plan);\n    }\n    void alloc()\n    {\n      my_r2hc_plan = \n        detail::fftw_traits_c_interface<real_value_type>::plan_construct_r2r\n        (\n          size(), \n          nullptr, \n          nullptr, \n          FFTW_R2HC,\n          FFTW_ESTIMATE\n        );\n      my_hc2r_plan =\n        detail::fftw_traits_c_interface<real_value_type>::plan_construct_r2r\n        (\n          size(), \n          nullptr, \n          nullptr, \n          FFTW_HC2R,\n          FFTW_ESTIMATE\n        );\n      my_r2hc_unaligned_plan = \n        detail::fftw_traits_c_interface<real_value_type>::plan_construct_r2r\n        (\n          size(), \n          nullptr, \n          nullptr, \n          FFTW_R2HC,\n          FFTW_ESTIMATE | FFTW_UNALIGNED\n        );\n      my_hc2r_unaligned_plan =\n        detail::fftw_traits_c_interface<real_value_type>::plan_construct_r2r\n        (\n          size(), \n          nullptr, \n          nullptr, \n          FFTW_HC2R,\n          FFTW_ESTIMATE | FFTW_UNALIGNED\n        );\n    }\n    void pack_halfcomplex(real_value_type* out) const\n    // precondition:\n    // -> size(out) >= N\n    {\n      const std::size_t N = size();\n      for(unsigned int i=1,j=N-1;i<j;++i,--j)\n        out[j] = -out[j];\n    }\n    void unpack_halfcomplex(real_value_type* out) const\n    // precondition:\n    // -> size(out) >= N\n    {\n      pack_halfcomplex(out);  \n    }\n\n  public:\n    fftw_rfft_backend(std::size_t n, const allocator_type& A = allocator_type{} )\n      : my_size{ n },\n        ref_alignment{\n            detail::fftw_traits_c_interface<real_value_type>::alignment_of(nullptr)},\n        my_allocator{A}\n    {\n      // For C++11, this line needs to be constexpr-ified.\n      // Then we could restore the constexpr-ness of this constructor.\n      alloc();\n    }\n\n    ~fftw_rfft_backend()\n    {\n      free();\n    }\n    \n    void resize(std::size_t new_size)\n    {\n      if(size()!=new_size)\n      {\n        free();\n        my_size = new_size;\n        alloc();\n      }\n    }\n\n    constexpr std::size_t size() const { return my_size; }\n    constexpr std::size_t unique_complex_size() const {return my_size/2 + 1;}\n     \n    void real_to_halfcomplex(const real_value_type* in, real_value_type* out) const\n    {\n      execute(my_r2hc_plan,my_r2hc_unaligned_plan,in,out);\n      pack_halfcomplex(out);\n    }\n    void halfcomplex_to_real(const real_value_type* in, real_value_type* out) const\n    {\n      std::copy(in,in+size(),out);\n      unpack_halfcomplex(out);\n      execute(my_hc2r_plan,my_hc2r_unaligned_plan,out,out);\n    }\n\n  private:\n    std::size_t my_size;\n    const int   ref_alignment;\n    allocator_type my_allocator;\n    \n    plan_type   my_r2hc_plan;\n    plan_type   my_hc2r_plan;\n    plan_type   my_r2hc_unaligned_plan;\n    plan_type   my_hc2r_unaligned_plan;\n  };\n  #endif\n\n  } // namespace detail\n\n  #if defined(__GNUC__)\n  template<class RingType = std::complex<double>, class Allocator_t = std::allocator<RingType> >\n  using fftw_dft = detail::complex_dft<detail::fftw_backend,RingType,Allocator_t>;\n  \n  template<class T = double, class Allocator_t = std::allocator<T> >\n  using fftw_rdft = detail::real_dft<detail::fftw_rfft_backend,T,Allocator_t>;\n\n  using fftw_transform = transform< fftw_dft<> >;\n  using fftw_real_transform = transform< fftw_rdft<> >;\n  #endif\n\n  } } } // namespace boost::math::fft\n\n#endif // BOOST_MATH_FFT_FFTWBACKEND_HPP\n", "meta": {"hexsha": "c9fbc803f534be81eb5a20ea6e4372caf0212bd5", "size": 18052, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/fft/fftw_backend.hpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/math/fft/fftw_backend.hpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "include/boost/math/fft/fftw_backend.hpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 31.7816901408, "max_line_length": 119, "alphanum_fraction": 0.6568801241, "num_tokens": 4791, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140728, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4430014641511059}}
{"text": "/*\n * MathUtils.cpp\n *\n * Author:\n *       Oleg Kalashev\n *\n * Copyright (c) 2020 Institute for Nuclear Research, RAS\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n#ifdef USE_BOOST\n\n#include <boost/numeric/odeint/config.hpp>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/stepper/bulirsch_stoer.hpp>\n#include <boost/numeric/odeint/stepper/bulirsch_stoer_dense_out.hpp>\n\n#endif\n\n#include \"Utils.h\"\n#include \"MathUtils.h\"\n#include <gsl/gsl_errno.h>\n#include \"gsl/gsl_sf_erf.h\"\n#include <gsl/gsl_math.h>\n#include \"TableFunction.h\"\n#include \"nr/odeint.h\"\n#include \"nr/stepperdopr5.h\"\n\n\nnamespace Utils {\n#ifdef USE_BOOST\n\tusing namespace boost::numeric::odeint;\n\n\ttemplate< class Obj , class Mem >\n\tclass ode_wrapper\n\t{\n\t\tObj* m_pObj;\n\t\tMem m_mem;\n\n\tpublic:\n\n\t\tode_wrapper( Obj* obj , Mem mem ) : m_pObj(obj ) , m_mem(mem ) { }\n\n\t\ttemplate< class State , class Deriv , class Time >\n\t\tvoid operator()( const State &x , Deriv &dxdt , Time t )\n\t\t{\n\t\t\t((*m_pObj).*m_mem)(x , dxdt , t );\n\t\t}\n\t};\n\n\ttemplate< class Obj , class Mem >\n\tode_wrapper< Obj , Mem > make_ode_wrapper( Obj* obj , Mem mem )\n\t{\n\t\treturn ode_wrapper< Obj , Mem >( obj , mem );\n\t}\n\n\n\ttemplate< class Obj , class Mem >\n\tclass observer_wrapper\n\t{\n\t\tObj* m_pObj;\n\t\tMem m_mem;\n\n\tpublic:\n\n\t\tobserver_wrapper( Obj* obj , Mem mem ) : m_pObj(obj ) , m_mem(mem ) { }\n\n\t\ttemplate< class State , class Time >\n\t\tvoid operator()( const State &x , Time t )\n\t\t{\n\t\t\t((*m_pObj).*m_mem)(x , t );\n\t\t}\n\t};\n\n\ttemplate< class Obj , class Mem >\n\tobserver_wrapper< Obj , Mem > make_observer_wrapper( Obj* obj , Mem mem )\n\t{\n\t\treturn observer_wrapper< Obj , Mem >( obj , mem );\n\t}\n\n\ttemplate< class X=double >\n\tclass Sampler4 : public ISampler<X> {\n\t\t//typedef runge_kutta_dopri5<X> dopri5_type;\n\t\t//typedef controlled_runge_kutta< dopri5_type > controlled_dopri5_type;\n\t\t//typedef dense_output_runge_kutta< controlled_dopri5_type > dense_output_dopri5_type;\n\t\t//typedef bulirsch_stoer_dense_out<X> dopri5_type;\n\tpublic:\n\t\tSampler4(){\n\t\t\tfIntermediateVals=new std::vector<X>;\n\t\t\tfIntermediateTs=new std::vector<X>;\n\t\t\tfIntermediateTs->reserve(256);\n\t\t\tfIntermediateVals->reserve(256);\n\t\t}\n\n\t\t~Sampler4(){\n\t\t\tdelete fIntermediateVals;\n\t\t\tdelete fIntermediateTs;\n\t\t}\n\n\t\tvoid System(const X &x , X &dxdt , X t ){\n\t\t\tdxdt=fFunc->f(t);\n\t\t}\n\n\t\tvoid Output(const X &x , X t ){\n\t\t\tif(fMaxX>0 && x>=fMaxX){\n\t\t\t\tX lastT = *(fIntermediateTs->end()-1);\n\t\t\t\tX lastX = *(fIntermediateVals->end()-1);\n\t\t\t\tif((t-lastT)/(t+lastT)<fRelErr && t-lastT<fAbsErr){\n\t\t\t\t\tX result = lastT + (t-lastT)/(x-lastX)*(fMaxX-lastX);\n\t\t\t\t\tthrow result;\n\t\t\t\t}\n\t\t\t\tX totRate = x-lastX;\n\t\t\t\tthrow sample(*fFunc, lastT, t, (fMaxX-lastX)/(x-lastX), totRate, fRelErr, fAbsErr);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfIntermediateVals->push_back(x);\n\t\t\t\tfIntermediateTs->push_back(t);\n\t\t\t}\n\t\t}\n\n\t\t/// If total rate is known it should be passed via aTotRate argument\n\t\t/// Otherwize aTotRate should be set to 0 (it will be calculated by function)\n\t\tX sample(const FunctionX<X>& f, X aTmin, X aTmax, X aRand,\n\t\t\t\t X & aTotRate, X aRelErr, X aAbsErr = 1e300){\n\t\t\tfMaxX = aTotRate*aRand;\n\t\t\tfRelErr = aRelErr;\n\t\t\tfAbsErr = aAbsErr;\n\n\t\t\tsize_t nPoints = (size_t)((aTmax-aTmin)/aRelErr+0.5)/2+1;\n\t\t\tX step= (aTmax-aTmin)/nPoints;\n\n\t\t\tfIntermediateTs->resize(0);//this will not decrease capacity of vectors\n\t\t\tfIntermediateVals->resize(0);\n\n\t\t\tX curT=aTmin;\n\t\t\tfFunc = &f;\n\t\t\taTotRate = 0.;\n\n\t\t\tX dt = (aTmax - aTmin) * aRelErr;\n\n\t\t\ttry {\n\t\t\t\t//dense_output_dopri5_type dopri5 = make_dense_output( aAbsErr , aRelErr , dopri5_type() );\n\t\t\t\tbulirsch_stoer_dense_out< X > stepper( aAbsErr , aRelErr);\n\t\t\t\tintegrate_adaptive( stepper , make_ode_wrapper(this,&Sampler4::System) , aTotRate , aTmin , aTmax , dt , make_observer_wrapper(this, &Sampler4::Output) );\n\t\t\t\t//integrate_const\n\t\t\t\t//integrate_adaptive(dopri5, make_ode_wrapper(this,&Sampler3::System), aTotRate, aTmin, aTmax, dt,\n\t\t\t\t\t\t\t\t   //make_observer_wrapper(this, &Sampler3::Output));\n\t\t\t}catch (X aValue){\n\t\t\t\treturn aValue;\n\t\t\t}\n\t\t\tif(aTotRate<=0){\n\t\t\t\treturn aTmax;\n\t\t\t}\n\t\t\tstd::vector<X>& intermediateVals = *fIntermediateVals;\n\t\t\tstd::vector<X>& intermediateTs = *fIntermediateTs;\n\t\t\tX searchVal = aTotRate * aRand;\n\t\t\tsize_t i2= intermediateVals.size();\n\t\t\tsize_t i1=0;\n\t\t\tfor(size_t i=(i2+i1)/2; i2-i1>1; i=(i2+i1)/2)\n\t\t\t{\n\t\t\t\tif(intermediateVals[i] < searchVal)\n\t\t\t\t\ti1 = i;\n\t\t\t\telse\n\t\t\t\t\ti2 = i;\n\t\t\t}\n\t\t\tX t1 = intermediateTs[i1];\n\t\t\tX t2 = intermediateTs[i2];\n\t\t\tX x1 = intermediateVals[i1];\n\t\t\tX x2 = intermediateVals[i2];\n\t\t\tif((t2-t1)/(t2+t1)<fRelErr && t2-t1<fAbsErr){\n\t\t\t\treturn t1 + (t2-t1)/(x2-x1)*(searchVal-x1);\n\t\t\t}\n\t\t\tX totRate=x2-x1;\n\t\t\treturn sample(*fFunc, t1, t2, (searchVal-x1)/(x2-x1), totRate, fRelErr, fAbsErr);\n\t\t}\n\tprivate:\n\t\tconst FunctionX<X>* fFunc;\n\t\tstd::vector<X>* fIntermediateVals;\n\t\tstd::vector<X>* fIntermediateTs;\n\t\tX      fMaxX;\n\t\tX      fRelErr;\n\t\tX      fAbsErr;\n\t};\n\n\ttemplate< class X=double >\n\tclass Sampler3 : public ISampler<X> {\n\t\ttypedef runge_kutta_dopri5<X> dopri5_type;\n\t\ttypedef controlled_runge_kutta< dopri5_type > controlled_dopri5_type;\n\t\ttypedef dense_output_runge_kutta< controlled_dopri5_type > dense_output_dopri5_type;\n\tpublic:\n\t\tSampler3(){\n\t\t\tfIntermediateVals=new std::vector<X>;\n\t\t\tfIntermediateTs=new std::vector<X>;\n\t\t\tfIntermediateTs->reserve(256);\n\t\t\tfIntermediateVals->reserve(256);\n\t\t}\n\n\t\t~Sampler3(){\n\t\t\tdelete fIntermediateVals;\n\t\t\tdelete fIntermediateTs;\n\t\t}\n\n\t\tvoid System(const X &x , X &dxdt , X t ){\n\t\t\tdxdt=fFunc->f(t);\n\t\t}\n\n\t\tvoid Output(const X &x , X t ){\n\t\t\tif(fMaxX>0 && x>=fMaxX){\n\t\t\t\tX lastT = *(fIntermediateTs->end()-1);\n\t\t\t\tX lastX = *(fIntermediateVals->end()-1);\n\t\t\t\tif((t-lastT)/(t+lastT)<fRelErr && t-lastT<fAbsErr){\n\t\t\t\t\tX result = lastT + (t-lastT)/(x-lastX)*(fMaxX-lastX);\n\t\t\t\t\tthrow result;\n\t\t\t\t}\n\t\t\t\tX totRate = x-lastX;\n\t\t\t\tthrow sample(*fFunc, lastT, t, (fMaxX-lastX)/(x-lastX), totRate, fRelErr, fAbsErr);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfIntermediateVals->push_back(x);\n\t\t\t\tfIntermediateTs->push_back(t);\n\t\t\t}\n\t\t}\n\n\t\t/// If total rate is known it should be passed via aTotRate argument\n\t\t/// Otherwize aTotRate should be set to 0 (it will be calculated by function)\n\t\tX sample(const FunctionX<X>& f, X aTmin, X aTmax, X aRand,\n\t\t\t\t X & aTotRate, X aRelErr, X aAbsErr = 1e300){\n\t\t\tfMaxX = aTotRate*aRand;\n\t\t\tfRelErr = aRelErr;\n\t\t\tfAbsErr = aAbsErr;\n\n\t\t\tsize_t nPoints = (size_t)((aTmax-aTmin)/aRelErr+0.5)/2+1;\n\t\t\tX step= (aTmax-aTmin)/nPoints;\n\n\t\t\tfIntermediateTs->resize(0);//this will not decrease capacity of vectors\n\t\t\tfIntermediateVals->resize(0);\n\n\t\t\tX curT=aTmin;\n\t\t\tfFunc = &f;\n\t\t\taTotRate = 0.;\n\t\t\tdense_output_dopri5_type dopri5 = make_dense_output( aAbsErr , aRelErr , dopri5_type() );\n\t\t\tX dt = (aTmax - aTmin) * aRelErr;\n\n\t\t\ttry {\n\t\t\t\tintegrate_adaptive(dopri5, make_ode_wrapper(this,&Sampler3::System), aTotRate, aTmin, aTmax, dt,\n\t\t\t\t\t\t\t\t   make_observer_wrapper(this, &Sampler3::Output));\n\t\t\t}catch (X aValue){\n\t\t\t\treturn aValue;\n\t\t\t}\n\t\t\tif(aTotRate<=0){\n\t\t\t\treturn aTmax;\n\t\t\t}\n\t\t\tstd::vector<X>& intermediateVals = *fIntermediateVals;\n\t\t\tstd::vector<X>& intermediateTs = *fIntermediateTs;\n\t\t\tX searchVal = aTotRate * aRand;\n\t\t\tsize_t i2= intermediateVals.size();\n\t\t\tsize_t i1=0;\n\t\t\tfor(size_t i=(i2+i1)/2; i2-i1>1; i=(i2+i1)/2)\n\t\t\t{\n\t\t\t\tif(intermediateVals[i] < searchVal)\n\t\t\t\t\ti1 = i;\n\t\t\t\telse\n\t\t\t\t\ti2 = i;\n\t\t\t}\n\t\t\tX t1 = intermediateTs[i1];\n\t\t\tX t2 = intermediateTs[i2];\n\t\t\tX x1 = intermediateVals[i1];\n\t\t\tX x2 = intermediateVals[i2];\n\t\t\tif((t2-t1)/(t2+t1)<fRelErr && t2-t1<fAbsErr){\n\t\t\t\treturn t1 + (t2-t1)/(x2-x1)*(searchVal-x1);\n\t\t\t}\n\t\t\tX totRate=x2-x1;\n\t\t\treturn sample(*fFunc, t1, t2, (searchVal-x1)/(x2-x1), totRate, fRelErr, fAbsErr);\n\t\t}\n\tprivate:\n\t\tconst FunctionX<X>* fFunc;\n\t\tstd::vector<X>* fIntermediateVals;\n\t\tstd::vector<X>* fIntermediateTs;\n\t\tX      fMaxX;\n\t\tX      fRelErr;\n\t\tX      fAbsErr;\n\t};\n\n\ttemplate<typename X = double >\n\tclass Sampler : public ISampler<X> {\n\t\ttypedef runge_kutta_dopri5<X> dopri5_type;\n\t\ttypedef controlled_runge_kutta< dopri5_type > controlled_dopri5_type;\n\t\ttypedef dense_output_runge_kutta< controlled_dopri5_type > dense_output_dopri5_type;\n\tpublic:\n\t\tSampler(){\n\t\t\tfIntermediateVals=0;\n\t\t\tfIntermediateTs=0;\n\t\t}\n\t\tvoid operator()(const X &x , X &dxdt , const X t ){\n\t\t\tdxdt=fFunc->f(t);\n\t\t}\n\t\tvoid operator()(const X &x , const X t ){\n\t\t\t(*fIntermediateVals)[fLastStep++]=x;\n\t\t\tdouble a=(*fIntermediateVals)[fLastStep-1];\n\t\t\ta=a+1;\n\t\t}\n\n\t\tX sample(const FunctionX<X>& f, X aTmin, X aTmax, X aRand,\n\t\t\t\t X & aTotRate, X aRelErr, X aAbsErr = 1e300){\n\t\t\t// create a vector with observation time points\n\t\t\tsize_t nPoints = (size_t)((aTmax-aTmin)/aRelErr/2+0.5);\n\t\t\tX step= (aTmax-aTmin)/nPoints;\n\t\t\tstd::vector<X> intermediateVals(nPoints + 1);\n\t\t\tstd::vector<X> intermediateTs(nPoints + 1);\n\t\t\tfIntermediateVals=&intermediateVals;\n\t\t\tfIntermediateTs=&intermediateTs;\n\t\t\tX curT=aTmin;\n\t\t\tfor( size_t i=0 ; i<=nPoints ; ++i, curT+=step )\n\t\t\t\tintermediateTs[i] = curT;\n\n\t\t\tfFunc = &f;\n\t\t\taTotRate = 0.;\n\t\t\tdense_output_dopri5_type dopri5 = make_dense_output( aAbsErr , aRelErr , dopri5_type() );\n\t\t\tX dt = (aTmax - aTmin) * aRelErr;\n\n\t\t\tfLastStep=0;\n\t\t\tintegrate_times(dopri5 , (*this) , aTotRate , intermediateTs, dt , (*this) );\n\t\t\tif(aTotRate==0.){\n\t\t\t\t//aTotRate=0.;\n\t\t\t\treturn aTmax;\n\t\t\t}\n\n\t\t\tX searchVal = aTotRate * aRand;\n\t\t\tsize_t i2= intermediateVals.size();\n\t\t\tsize_t i1=0;\n\t\t\tfor(size_t i=(i2+i1)/2; i2-i1>1; i=(i2+i1)/2)\n\t\t\t{\n\t\t\t\tif(intermediateVals[i] < searchVal)\n\t\t\t\t\ti1 = i;\n\t\t\t\telse\n\t\t\t\t\ti2 = i;\n\t\t\t}\n\t\t\tX t1 = intermediateTs[i1];\n\t\t\tX t2 = intermediateTs[i2];\n\t\t\tX x1 = intermediateVals[i1];\n\t\t\tX x2 = intermediateVals[i2];\n\t\t\treturn t1 + (t2 - t1) / (x2 - x1) * (searchVal - x1);\n\t\t}\n\n\t\tconst FunctionX<X>* fFunc;\n\t\tstd::vector<X>* fIntermediateVals;\n\t\tstd::vector<X>* fIntermediateTs;\n\n\t\tsize_t      fLastStep;\n\t};\n\n\ttemplate<typename X = double >\n\tclass LogSampler : public ISampler<X> {\n\t\ttypedef runge_kutta_dopri5<X> dopri5_type;\n\t\ttypedef controlled_runge_kutta< dopri5_type > controlled_dopri5_type;\n\t\ttypedef dense_output_runge_kutta< controlled_dopri5_type > dense_output_dopri5_type;\n\tpublic:\n\t\tLogSampler(){\n\t\t\tfIntermediateVals=0;\n\t\t\tfIntermediateTs=0;\n\t\t}\n\t\tvoid operator()(const X &x , X &dxdt , const X t ){\n\t\t\tdxdt=fFunc->f(t);\n\t\t}\n\t\tvoid operator()(const X &x , const X t ){\n\t\t\t(*fIntermediateVals)[fLastStep++]=x;\n\t\t\tdouble a=(*fIntermediateVals)[fLastStep-1];\n\t\t\ta=a+1;\n\t\t}\n\n\t\tX sample(const FunctionX<X>& f, X aTmin, X aTmax, X aRand,\n\t\t\t\t X & aTotRate, X aRelErr, X aAbsErr = 1e300){\n\t\t\t// create a vector with observation time points\n\t\t\tsize_t nPoints = (size_t)(log(aTmax/aTmin)/log(1.0+aRelErr)/2+0.5);\n\t\t\tX step= pow(aTmax/aTmin, 1./nPoints);\n\t\t\tstd::vector<X> intermediateVals(nPoints + 1);\n\t\t\tstd::vector<X> intermediateTs(nPoints + 1);\n\t\t\tfIntermediateVals=&intermediateVals;\n\t\t\tfIntermediateTs=&intermediateTs;\n\t\t\tX curT=aTmin;\n\t\t\tfor( size_t i=0 ; i<=nPoints ; ++i, curT*=step )\n\t\t\t\tintermediateTs[i] = curT;\n\n\t\t\tfFunc = &f;\n\t\t\taTotRate = 0.;\n\t\t\tdense_output_dopri5_type dopri5 = make_dense_output( aAbsErr , aRelErr , dopri5_type() );\n\t\t\tX dt = (aTmax - aTmin) * aRelErr;\n\n\t\t\tfLastStep=0;\n\t\t\tintegrate_times(dopri5 , (*this) , aTotRate , intermediateTs, dt , (*this) );\n\t\t\tif(aTotRate==0.){\n\t\t\t\t//aTotRate=0.;\n\t\t\t\treturn aTmax;\n\t\t\t}\n\n\t\t\tX searchVal = aTotRate * aRand;\n\t\t\tsize_t i2= intermediateVals.size();\n\t\t\tsize_t i1=0;\n\t\t\tfor(size_t i=(i2+i1)/2; i2-i1>1; i=(i2+i1)/2)\n\t\t\t{\n\t\t\t\tif(intermediateVals[i] < searchVal)\n\t\t\t\t\ti1 = i;\n\t\t\t\telse\n\t\t\t\t\ti2 = i;\n\t\t\t}\n\t\t\tX t1 = intermediateTs[i1];\n\t\t\tX t2 = intermediateTs[i2];\n\t\t\tX x1 = intermediateVals[i1];\n\t\t\tX x2 = intermediateVals[i2];\n\t\t\treturn t1 + (t2 - t1) / (x2 - x1) * (searchVal - x1);\n\t\t}\n\n\t\tconst FunctionX<X>* fFunc;\n\t\tstd::vector<X>* fIntermediateVals;\n\t\tstd::vector<X>* fIntermediateTs;\n\n\t\tsize_t      fLastStep;\n\t};\n\n\ttemplate<typename X = double >\n\tclass Sampler2 : public ISampler<X> {\n\t\ttypedef runge_kutta_dopri5<X> dopri5_type;\n\t\ttypedef controlled_runge_kutta< dopri5_type > controlled_dopri5_type;\n\t\ttypedef dense_output_runge_kutta< controlled_dopri5_type > dense_output_dopri5_type;\n\tpublic:\n\t\tSampler2(){\n\t\t\tfIntermediateVals=0;\n\t\t\tfIntermediateTs=0;\n\t\t}\n\t\t~Sampler2()\n\t\t{\n\t\t\tfIntermediateVals=0;\n\t\t\tfIntermediateTs=0;\n\t\t}\n\t\tvoid operator()(const X &x , X &dxdt , const double t ){\n\t\t\tdxdt=fFunc->f(t);\n\t\t}\n\t\tvoid operator()(const X &x , const X t ){\n\t\t\tif(fMaxX>0 && x>=fMaxX){\n\t\t\t\tX lastT = *(fIntermediateTs->end()-1);\n\t\t\t\tX lastX = *(fIntermediateVals->end()-1);\n\t\t\t\tif((t-lastT)/(t+lastT)<fRelErr && t-lastT<fAbsErr){\n\t\t\t\t\tX result = lastT + (t-lastT)/(x-lastX)*(fMaxX-lastX);\n\t\t\t\t\tthrow result;\n\t\t\t\t}\n\t\t\t\tX totRate = x-lastX;\n\t\t\t\tthrow sample(*fFunc, lastT, t, (fMaxX-lastX)/(x-lastX), totRate, fRelErr, fAbsErr);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfIntermediateVals->push_back(x);\n\t\t\t\tfIntermediateTs->push_back(t);\n\t\t\t}\n\t\t}\n\n\t\t/// If total rate is known it should be passed via aTotRate argument\n\t\t/// Otherwize aTotRate should be set to 0 (it will be calculated by function)\n\t\tX sample(const FunctionX<X>& f, X aTmin, X aTmax, X aRand,\n\t\t\t\t X & aTotRate, X aRelErr, X aAbsErr = 1e300){\n\t\t\tfMaxX = aTotRate*aRand;\n\t\t\t//fTmin = aTmin;\n\t\t\t//fTmax = aTmax;\n\t\t\t//fTotRate = aTotRate;\n\t\t\tfRelErr = aRelErr;\n\t\t\tfAbsErr = aAbsErr;\n\n\t\t\tsize_t nPoints = 128;//(size_t)((aTmax-aTmin)/aRelErr+0.5)/2+1;\n\t\t\t//X step= (aTmax-aTmin)/nPoints;\n\t\t\tstd::vector<X> intermediateVals;\n\t\t\tstd::vector<X> intermediateTs;\n\t\t\tintermediateTs.reserve(nPoints);\n\t\t\tintermediateVals.reserve(nPoints);\n\t\t\tfIntermediateVals=&intermediateVals;\n\t\t\tfIntermediateTs=&intermediateTs;\n\t\t\tX curT=aTmin;\n\t\t\tfFunc = &f;\n\t\t\taTotRate = 0.;\n\n\t\t\t///TODO: try different steppers\n\n\t\t\tdense_output_dopri5_type dopri5 = make_dense_output( aAbsErr , aRelErr , dopri5_type() );\n\t\t\tX dt = (aTmax - aTmin) * aRelErr;\n\n\t\t\ttry {\n\t\t\t\tintegrate_adaptive(dopri5, (*this), aTotRate, aTmin, aTmax, dt,\n\t\t\t\t\t\t\t\t   (*this));//this will create two copies of (*this)\n\t\t\t\t/* //this one is a bit slower than dense_output_dopri5_type\n\t\t\t\ttypedef runge_kutta_cash_karp54< X > error_stepper_type;\n\t\t\t\tintegrate_adaptive( make_controlled< error_stepper_type >( aAbsErr , aRelErr ) ,\n\t\t\t\t\t\t\t\t\t(*this) , aTotRate , aTmin, aTmax, dt,\n\t\t\t\t\t\t\t\t\t(*this));*/\n\n\t\t\t}catch (X aValue){\n\t\t\t\treturn aValue;\n\t\t\t}\n\t\t\tif(aTotRate<=0){\n\t\t\t\treturn aTmax;\n\t\t\t}\n\n\t\t\tX searchVal = aTotRate * aRand;\n\t\t\tsize_t i2= intermediateVals.size();\n\t\t\tsize_t i1=0;\n\t\t\tfor(size_t i=(i2+i1)/2; i2-i1>1; i=(i2+i1)/2)\n\t\t\t{\n\t\t\t\tif(intermediateVals[i] < searchVal)\n\t\t\t\t\ti1 = i;\n\t\t\t\telse\n\t\t\t\t\ti2 = i;\n\t\t\t}\n\t\t\tX t1 = intermediateTs[i1];\n\t\t\tX t2 = intermediateTs[i2];\n\t\t\tX x1 = intermediateVals[i1];\n\t\t\tX x2 = intermediateVals[i2];\n\t\t\tif((t2-t1)/(t2+t1)<fRelErr && t2-t1<fAbsErr){\n\t\t\t\treturn t1 + (t2-t1)/(x2-x1)*(searchVal-x1);\n\t\t\t}\n\t\t\tX totRate=x2-x1;\n\t\t\treturn sample(*fFunc, t1, t2, (searchVal-x1)/(x2-x1), totRate, fRelErr, fAbsErr);\n\t\t}\n\n\t\tconst FunctionX<X>* fFunc;\n\t\tstd::vector<X>* fIntermediateVals;\n\t\tstd::vector<X>* fIntermediateTs;\n\t\tX      fMaxX;\n\t\tX      fRelErr;\n\t\tX      fAbsErr;\n\t};\n\n#endif //#ifdef USE_BOOST\n\n\ttemplate<typename X = double >\n\tclass NRSampler : public ISampler<X> {\n\t\tX sample(const FunctionX<X>& f, X aTmin, X aTmax, X aRand,\n\t\t\t\t X & aTotRate, X aRelErr, X aAbsErr = 1e300){\n\t\t\tX x;\n\t\t\tMathUtils::SampleLogDistributionNR(f,aRand,x,aTotRate,aTmin,aTmax,aRelErr);\n\t\t}\n\t};\n\n\tdouble MathUtils::SolveEquation(\n\t\t\tgsl_function F,\tdouble x_lo, double x_hi,\n\t\t\tconst double relError, const int max_iter,\n\t\t\tconst gsl_root_fsolver_type *T)\n{\n    double r = 0;\n\tint status;\n\tint iter = 0;\n\n\tgsl_root_fsolver *solver = gsl_root_fsolver_alloc (T);\n\tgsl_root_fsolver_set (solver, &F, x_lo, x_hi);\n\tdo\n\t{\n\t \titer++;\n\t    status = gsl_root_fsolver_iterate (solver);\n\t    r = gsl_root_fsolver_root (solver);\n\t    x_lo = gsl_root_fsolver_x_lower (solver);\n\t    x_hi = gsl_root_fsolver_x_upper (solver);\n\t    status = gsl_root_test_interval (x_lo, x_hi, 0, relError);\n\t}\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\tASSERT(status == GSL_SUCCESS);\n\tgsl_root_fsolver_free (solver);\n\tif (status != GSL_SUCCESS)\n\t{\n\t\tif(iter >= max_iter)\n\t\t\tException::Throw(\"Failed to solve equation: maximal number of iterations achieved\");\n\t  \telse\n\t  \t\tException::Throw(\"Failed to solve equation: GSL status \" + ToString(status));\n\t}\n\treturn r;\n}\n\ndouble MathUtils::SolveEquation(\n\t\tdouble (*aEquation) (double, void*),\n\t\tdouble x_lo, double x_hi, void* aEquationPars,\n\t\tconst double relError, const int max_iter,\n\t\tconst gsl_root_fsolver_type *T)\n{\n\tgsl_function F;\n\tF.function = aEquation;\n\tF.params = aEquationPars;\n\treturn SolveEquation(F,\tx_lo, x_hi, relError, max_iter, T);\n}\n\nMathUtils::MathUtils():\ngslQAGintegrator(0)\n{\n\n}\n\nMathUtils::~MathUtils()\n{\n\tif(gslQAGintegrator)\n\t\tgsl_integration_workspace_free (gslQAGintegrator);\n}\n\n\ttemplate<class X> class GaussDisr : public FunctionX<X>{\n\tpublic:\n\t\tX mean;\n\t\tX sigma;\n\t\tGaussDisr(X aMean, X aSigma):mean(aMean),sigma(aSigma){}\n\t\tvirtual X f(X _x) const{\n\t\t\tX diff = (_x-mean)/sigma;\n\t\t\treturn exp(-diff*diff*0.5)/sigma*0.398942280401433;\n\t\t}\n\t};\n\n\ttemplate<class X> void ISampler<X>::UnitTest()\n\t{\n\n\t\tX mean = 1e10;\n\t\tX sigma = 1e9;\n\t\tX minX=1e9;\n\t\tX maxX=1e11;\n\t\tX minI = 0.5*(1+gsl_sf_erf((minX-mean)/sigma/sqrt(2.0)));\n\t\tX maxI = 0.5*(1+gsl_sf_erf((maxX-mean)/sigma/sqrt(2.0)));\n\t\tX totI=maxI-minI;\n\n\t\tGaussDisr<X> gd(mean,sigma);\n\t\tX relError = 1e-6;\n\t\tint nSteps = 10000;\n//gnuplot command: 0.5*(1+erf((x-mean)/sigma/sqrt(2.0))) w l\n\n\t\tfor(int i=1; i<nSteps; i++){\n\t\t\tX rand = 1./nSteps*i;\n\t\t\tX totRate = 0;\n\t\t\tX curX = sample(gd, minX, maxX, rand, totRate, relError);\n\t\t\tX exactFrac = (0.5*(1+gsl_sf_erf((curX-mean)/sigma/sqrt(2.0)))-minI)/totI;\n\t\t\tstd::cout << curX << \"\\t\" << rand << \"\\t\"  << exactFrac << std::endl;\n\t\t}\n\t}\n\n\ttemplate void ISampler<double>::UnitTest();\n\ttemplate void ISampler<long double>::UnitTest();\n\n\ttemplate<typename X> bool MathUtils::SampleLogscaleDistribution(const Function& aDistrib, double aRand, X& aOutputX, X& aOutputIntegral, int nStepsS, X xMin, X xMax, double aRelError)\n{\n\tstd::vector<X> sArray,ratesArray;\n\tdouble distrXmin = aDistrib.Xmin();\n\tif(xMin < distrXmin)\n\t\txMin = distrXmin;\n\tdouble distrXmax = aDistrib.Xmax();\n\tif(xMax > distrXmax)\n\t\txMax = distrXmax;\n\tASSERT(xMin>0. && xMin<xMax);\n\tdouble stepS = pow(xMax/xMin,1./nStepsS);\n\n\tsArray.push_back(0);\n\tratesArray.push_back(0);\n\n\tX taleAccLimit;\n\tRelAccuracy<X>(taleAccLimit);\n\ttaleAccLimit*=10;\n\tint maxIntervals = (int)(0.1/aRelError + 10.5);\n\taOutputIntegral=0.;\n\tdouble deltaLogS = log(stepS);\n\tdouble s=xMin;\n\tfor(int iS=1; iS<=nStepsS; iS++)\n\t{\n\t\tdouble s2=s*stepS;\n\t\tX rate = Integration_qag(aDistrib,s,s2,1e-300,aRelError,maxIntervals);\n\t\tASSERT_VALID_NO(rate);\n\t\tif(rate==0. && aOutputIntegral==0.)\n\t\t{//move Smax\n\t\t\tsArray[0] = deltaLogS*iS;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(rate==0 || (aOutputIntegral>0 && rate/aOutputIntegral < taleAccLimit))\n\t\t\t\trate = aOutputIntegral*taleAccLimit;//avoiding zero derivative (inverse function must be defined everywhere)\n\t\t\taOutputIntegral += rate;\n\t\t\tsArray.push_back(deltaLogS*iS);\n\t\t\tratesArray.push_back(aOutputIntegral);\n\t\t}\n\t\ts=s2;\n\t}\n\tif(aOutputIntegral>0)\n\t{//sampling s\n\t\tASSERT(sArray.size()>1);\n\t\tdouble randRate = aRand*aOutputIntegral;\n\t\tfor(int i = ratesArray.size()-1;i>=0; i--)\n\t\t\tratesArray[i]-=randRate;\n\t\tGSLTableFunc func(sArray, ratesArray, 0, 0, gsl_interp_cspline);\n\t\tfunc.SetAutoLimits();\n\t\tdouble logError = aRelError/(nStepsS*deltaLogS);\n\t\tif(logError>aRelError)\n\t\t\tlogError = aRelError;\n\t\taOutputX = SolveEquation(func, 0, nStepsS*deltaLogS, logError);\n\t\taOutputX = xMin*exp(aOutputX);\n\t\tASSERT(aOutputX>=xMin && aOutputX<=xMax);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nclass MathUtilsODE\n{\npublic:\n\tMathUtilsODE(const Function& aDistrib):fDistrib(aDistrib)\n\t{}\n\tvoid operator() (const nr::Doub x, nr::VecDoub_I &y, nr::VecDoub_O &dydx) {\n\t\tdouble val = fDistrib(x);\n\t\tif(val!=0)\n\t\t\tdydx[0]= val;\n\t\telse\n\t\t\tdydx[0]= 0.;\n\t\tASSERT(val > -1.6e308 && val < 1.6e308);\n\t}\nprivate:\n\tconst Function& fDistrib;\n};\n\nIFunctionCallHandlerX<double>* MathUtils::fLogger = 0;\n\nbool MathUtils::SampleDistribution(const Function& aDistrib, double aRand, double& aOutputX, double& aOutputIntegral, double xMin, double xMax, double aRelError)\n{\n\tconst Function* distrib = &aDistrib;\n\tSafePtr<DebugFunctionX<double> > func;\n\tif(fLogger)\n\t{\n\t\tfunc = new DebugFunctionX<double>(aDistrib, *fLogger);\n\t\tdistrib = func;\n\t}\n\n\tdouble distrXmin = distrib->Xmin();\n\tif(xMin < distrXmin)\n\t\txMin = distrXmin;\n\tdouble distrXmax = distrib->Xmax();\n\tif(xMax > distrXmax)\n\t\txMax = distrXmax;\n\tASSERT(xMax>xMin);\n\n\tdouble initialStep = aRelError*(xMax-xMin);\n\n\tMathUtilsODE d(*distrib);\n\n\tconst nr::Doub atol=0.;//1.0e-3;\n\tconst nr::Doub hmin=0.0;//minimal step (can be zero)\n\tnr::VecDoub ystart(1);\n\tystart[0]=0.;\n\tnr::Output out(-1); //output is saved at every integration step\n\tnr::Odeint<nr::StepperDopr5<MathUtilsODE> > ode(ystart,xMin,xMax,atol,aRelError,initialStep,hmin,out,d);\n\tode.integrate();\n\taOutputIntegral = ystart[0];\n\tif(aOutputIntegral<=0)\n\t\treturn false;\n\taRand *= aOutputIntegral;\n\tint i1=0;\n\tint i2=out.count-1;\n\tdouble* ysave = out.ysave[0];\n\tfor(int i=(i1+i2)/2; i2-i1>1; i=(i1+i2)/2)\n\t{\n\t\tdouble y = ysave[i];\n\t\tif(y<aRand)\n\t\t\ti1 = i;\n\t\telse\n\t\t\ti2 = i;\n\t}\n\tdouble y1=ysave[i1];\n\tdouble y2=ysave[i2];\n\tdouble x1=out.xsave[i1];\n\tdouble x2=out.xsave[i2];\n\taRand -= y1;\n\taOutputX = x1 + (x2-x1)/(y2-y1)*aRand;//make a linear estimate of X\n\tif(fabs((x2-x1)/aOutputX)<=aRelError)\n\t\treturn true;\n\tystart[0]=0.;\n\tinitialStep = aRelError*(aOutputX>0 ? aOutputX : (x2-x1));\n\tnr::Output out2(2+(int)fabs((x2-x1)/initialStep));\n\n\tnr::Odeint<nr::StepperDopr5<MathUtilsODE> > ode2(ystart,x1,x2,atol,aRelError,initialStep,hmin,out2,d);\n\tode2.integrate();\n\ti1=0;\n\ti2=out2.count-1;\n\tysave = out2.ysave[0];\n\tfor(int i=(i1+i2)/2; i2-i1>1; i=(i1+i2)/2)\n\t{\n\t\tdouble y = ysave[i];\n\t\tif(y<aRand)\n\t\t\ti1 = i;\n\t\telse\n\t\t\ti2 = i;\n\t}\n\ty1=ysave[i1];\n\ty2=ysave[i2];\n\tx1=out2.xsave[i1];\n\tx2=out2.xsave[i2];\n\taOutputX = x1 + (x2-x1)/(y2-y1)*(aRand-y1);//make a linear estimate of X\n\treturn true;\n}\n\nclass MathUtilsLogODE\n{\npublic:\n\tMathUtilsLogODE(const Function& aDistrib):fDistrib(aDistrib)\n\t{}\n\tvoid operator() (const nr::Doub x, nr::VecDoub_I &y, nr::VecDoub_O &dydx) {\n\t\tdouble xx = exp(x);\n\t\tdouble val = xx*fDistrib(xx);\n\t\tif(val!=0)\n\t\t\tdydx[0]= val;\n\t\telse\n\t\t\tdydx[0]= 0.;\n\t\tASSERT(val > -1.6e308 && val < 1.6e308);\n\t}\nprivate:\n\tconst Function& fDistrib;\n};\n\nbool MathUtils::SampleLogDistribution(const Function& aDistrib, double aRand, double& aOutputX, double& aOutputIntegral, double xMin, double xMax, double aRelError)\n{\n#ifdef USE_BOOST\n    return SampleLogDistributionBoost(aDistrib, aRand, aOutputX, aOutputIntegral, xMin, xMax, aRelError);\n#else\n\treturn SampleLogDistributionNR(aDistrib, aRand, aOutputX, aOutputIntegral, xMin, xMax, aRelError);\n#endif\n}\n\nbool MathUtils::SampleLogDistributionNR(const Function& aDistrib, double aRand, double& aOutputX, double& aOutputIntegral, double xMin, double xMax, double aRelError)\n{\n\tASSERT(aRelError>0 && aRelError<=0.1);\n\n\tconst Function* distrib = &aDistrib;\n\tSafePtr<DebugFunctionX<double> > func;\n\tif(fLogger)\n\t{\n\t\tfunc = new DebugFunctionX<double>(aDistrib, *fLogger);\n\t\tdistrib = func;\n\t}\n\n\tdouble distrXmin = distrib->Xmin();\n\tif(xMin < distrXmin)\n\t\txMin = distrXmin;\n\tdouble distrXmax = distrib->Xmax();\n\tif(xMax > distrXmax)\n\t\txMax = distrXmax;\n\tASSERT(xMax>xMin && xMin>0);\n\txMin=log(xMin);\n\txMax=log(xMax);\n\n\tdouble initialStep = 0.5*(xMax-xMin);\n//\tif(aRelError<initialStep)\n//\t\tinitialStep=aRelError;\n\n\tMathUtilsLogODE d(*distrib);\n\n\tconst nr::Doub atol=0;\n\tconst nr::Doub hmin=0.0;//minimal step (can be zero)\n\tnr::VecDoub ystart(1);\n\tystart[0]=0.;\n\tnr::Output out(-1); //output is saved at every integration step\n\tnr::Odeint<nr::StepperDopr5<MathUtilsLogODE> > ode(ystart,xMin,xMax,atol,aRelError,initialStep,hmin,out,d);\n\tode.integrate();\n\taOutputIntegral = ystart[0];\n\tif(aOutputIntegral<=0)\n\t\treturn false;\n\tdouble yRand = aRand*aOutputIntegral;\n\tint i1=0;\n\tint i2=out.count-1;\n\tdouble* ysave = out.ysave[0];\n\tfor(int i=(i1+i2)/2; i2-i1>1; i=(i1+i2)/2)\n\t{\n\t\tdouble y = ysave[i];\n\t\tif(y<yRand)\n\t\t\ti1 = i;\n\t\telse\n\t\t\ti2 = i;\n\t}\n\tdouble y1=ysave[i1];\n\tdouble y2=ysave[i2];\n\tdouble x1=out.xsave[i1];\n\tdouble x2=out.xsave[i2];\n\tdouble yFrac = (yRand-y1)/(y2-y1);\n\tif((x2-x1)<aRelError)\n\t{\n\t\taOutputX = x1 + (x2-x1)*yFrac;//make a linear estimate of X in log scale\n\t\tASSERT(aOutputX>=xMin && aOutputX<=xMax);\n\t}\n\telse\n\t{\n\t\tystart[0]=0.;\n\t\tinitialStep = 0.5*(x2-x1);//aRelError;\n\t\tnr::Output out2(2+(int)fabs((x2-x1)/initialStep));\n\t\tnr::Odeint<nr::StepperDopr5<MathUtilsLogODE> > ode2(ystart,x1,x2,atol,aRelError,initialStep,hmin,out2,d);\n\t\tode2.integrate();\n\t\tyRand = ystart[0]*yFrac;\n\t\ti1=0;\n\t\ti2=out2.count-1;\n\t\tysave = out2.ysave[0];\n\t\tfor(int i=(i1+i2)/2; i2-i1>1; i=(i1+i2)/2)\n\t\t{\n\t\t\tdouble y = ysave[i];\n\t\t\tif(y<yRand)\n\t\t\t\ti1 = i;\n\t\t\telse\n\t\t\t\ti2 = i;\n\t\t}\n\t\ty1=ysave[i1];\n\t\ty2=ysave[i2];\n\t\tx1=out2.xsave[i1];\n\t\tx2=out2.xsave[i2];\n\t\taOutputX = x1 + (x2-x1)/(y2-y1)*(yRand-y1);//make a linear estimate of X in log scale\n\t\tASSERT(aOutputX>=xMin && aOutputX<=xMax);\n\t}\n\taOutputX = exp(aOutputX);\n\tASSERT_VALID_NO(aOutputX);\n\treturn true;\n}\n\n\nbool MathUtils::SampleLogDistributionBoost(const Function& aDistrib, double aRand, double& aOutputX, double& aOutputIntegral, double xMin, double xMax, double aRelError)\n\t{\n#ifdef USE_BOOST\n\t\tASSERT(aRelError>0 && aRelError<=0.1);\n\t\tASSERT(xMin>0 && xMax>xMin);\n\t\tLogSampler<double> dil;//slower 25 sec\n\t\t//Sampler2<double> dil;// 20 sec (todo: fix memory leaks)\n\t\t//Sampler3<double> dil;// 20 sec (todo: fix memory leaks)\n\t\taOutputIntegral=0.;\n\n\t\taOutputX=dil.sample(aDistrib, xMin, xMax, aRand, aOutputIntegral, aRelError);\n\n\t\tASSERT_VALID_NO(aOutputX);\n\t\treturn true;\n#else\n\tException::Throw(\"MathUtils::SampleLogDistributionBoost boostlib support is disabled\");\n\treturn false;//avoid compiler warning\n#endif\n\t}\n\ntemplate<typename X> void MathUtils::RelAccuracy(X& aOutput)\n{\n\tNOT_IMPLEMENTED\n}\n\ntemplate<> void MathUtils::RelAccuracy<double>(double& aOutput)\n{\n\taOutput = 1e-15;\n}\n\ntemplate<> void MathUtils::RelAccuracy<long double>(long double& aOutput)\n{\n\taOutput = 1e-18L;\n}\n\ntemplate bool MathUtils::SampleLogscaleDistribution<double>(const Function& aDistrib, double aRand, double& aOutputX, double& aOutputIntegral, int nStepsS, double xMin, double xMax, double aRelError);\n//template bool MathUtils::SampleLogscaleDistribution<long double>(const Function& aDistrib, double aRand, long double& aOutput, int nStepsS, long double xMin, long double xMax, double aRelError);\n\n\tint MathUtils::UnitTest(){\n\t\t//LogSampler<double> dil;//slower 25 sec\n\t\t//Sampler2<double> dil;// 20 sec (todo: fix memory leaks)\n\t\t//Sampler3<double> dil;// 20 sec (todo: fix memory leaks)\n\t\t//Sampler4<double> dil;\n\t\tNRSampler<double> dil;\n\t\tdil.UnitTest();\n\t}\n\ndouble MathUtils::Integration_qag (\n\t\tgsl_function aFunction,\n\t\tdouble aXmin,\n\t\tdouble aXmax,\n\t\tdouble epsabs,\n\t\tdouble epsrel,\n\t\tsize_t limit,\n\t\tint key)\n{\n\tif(gslQAGintegrator==0)\n\t\tgslQAGintegrator = gsl_integration_workspace_alloc (limit);\n\telse if(gslQAGintegrator->limit < limit)\n\t{\n\t\tgsl_integration_workspace_free (gslQAGintegrator);\n\t\tgslQAGintegrator = gsl_integration_workspace_alloc (limit);\n\t}\n\tdouble result, abserr;\n\ttry{\n\t\tif(epsabs==0)\n\t\t\tepsabs = std::numeric_limits<double>::min();\n\t\tint failed = gsl_integration_qag (&aFunction, aXmin, aXmax, epsabs, epsrel, limit, key, gslQAGintegrator, &result, &abserr);\n\t\tif(failed)\n\t\t{\n\t\t\tASSERT(0);\n\t\t\tException::Throw(\"Integration failed with code \" + ToString(failed));\n\t\t}\n\t}catch(Exception* ex)\n\t{\n#ifdef _DEBUG\n\t\tGslProxyFunction f(aFunction,aXmin,aXmax);\n\t\tstd::cerr << \"\\n\\n#Integration_qag debug output:\" << std::endl;\n\t\tbool logscale = aXmin>0 && aXmax/aXmin > 100;\n\t\tf.Print(std::cerr, 100, logscale, aXmin, aXmax);\n\t\tstd::cerr << \"\\n\\n#end of Integration_qag debug output\" << std::endl;\n#endif\n\t\tthrow ex;\n\t}\n\treturn result;\n}\n\n} /* namespace Utils */\n", "meta": {"hexsha": "c1bf7beb12f33c52bd2c0302dbb19e13d515bf52", "size": 28810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/MathUtils.cpp", "max_stars_repo_name": "alexkorochkin/mcray", "max_stars_repo_head_hexsha": "2cfa58d2cd6f872612f6396d65781ad83211c06c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-12-16T08:23:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T22:56:26.000Z", "max_issues_repo_path": "src/lib/MathUtils.cpp", "max_issues_repo_name": "alexkorochkin/mcray", "max_issues_repo_head_hexsha": "2cfa58d2cd6f872612f6396d65781ad83211c06c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/MathUtils.cpp", "max_forks_repo_name": "alexkorochkin/mcray", "max_forks_repo_head_hexsha": "2cfa58d2cd6f872612f6396d65781ad83211c06c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-16T08:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T21:05:54.000Z", "avg_line_length": 28.3562992126, "max_line_length": 200, "alphanum_fraction": 0.6748351267, "num_tokens": 9684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.44300146415110586}}
{"text": "#pragma once\n#include <memory> // shared_ptr\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include <opt/constrained_problem.hpp>\n#include <opt/optimization_problem.hpp>\n#include <opt/optimization_results.hpp>\n#include <solvers/lcp_solver.hpp>\n#include <solvers/optimization_solver.hpp>\n\nnamespace ccd {\nnamespace opt {\n\n    /**\n     * @brief Method for updating candidate solution during NCP iterations\n     *\n     * Update: \\f$ x_{i+1} = x_{i} + \\Delta x \\f$\n     */\n    enum class NCPUpdate {\n        /// \\f$\\Delta x = A^{-1} \\nabla g(x_i)^T \\lambda_i\\f$\n        G_GRADIENT,\n        /// \\f$\\Delta x = A^{-1} \\nabla g(x_i)^T \\lambda_i + A^{-1}b - x_i\\f$\n        LINEAR\n    };\n\n    class NCPSolver : public OptimizationSolver {\n    public:\n        NCPSolver();\n        virtual ~NCPSolver() = default;\n\n        /// Initialize the state of the solver using the settings saved in JSON\n        virtual void settings(const nlohmann::json& json) override;\n        /// Export the state of the solver using the settings saved in JSON\n        virtual nlohmann::json settings() const override;\n\n        /// An identifier for the solver class\n        static std::string solver_name() { return \"ncp_solver\"; }\n        /// An identifier for this solver\n        virtual std::string name() const override\n        {\n            return NCPSolver::solver_name();\n        }\n\n        void set_problem(OptimizationProblem& problem) override\n        {\n            assert(problem.is_constrained_problem());\n            problem_ptr = dynamic_cast<ConstrainedProblem*>(&problem);\n        }\n\n        /// Initialize the solver state for a new solve\n        void init_solve(const Eigen::VectorXd& x0) override;\n        /// Solve the saved optimization problem to completion\n        virtual OptimizationResults solve(const Eigen::VectorXd& x0) override;\n        OptimizationResults\n        solve(const Eigen::VectorXd& x0, const bool use_grad);\n        /// Perform a single step of solving the optimization problem\n        virtual OptimizationResults step_solve() override;\n\n        // --------------------------------------------------------------------\n        // Configuration\n        // --------------------------------------------------------------------\n        bool do_line_search;\n        bool solve_for_active_cstr;\n        double convergence_tolerance;\n        NCPUpdate update_type;\n        LCPSolver lcp_solver;\n        int max_iterations;\n\n        // --------------------------------------------------------------------\n        // Optimization Status\n        // --------------------------------------------------------------------\n        std::shared_ptr<Eigen::SparseLU<Eigen::SparseMatrix<double>>> Asolver;\n        Eigen::VectorXd g_xi;\n        Eigen::MatrixXd jac_g_xi;\n\n        // --------------------------------------------------------------------\n        // Optimization results\n        // --------------------------------------------------------------------\n        Eigen::VectorXd xi;\n        Eigen::VectorXd lambda_i;\n\n    protected:\n        void compute_linear_system(ConstrainedProblem& problem_ptr_);\n        void compute_initial_solution();\n\n        /**\n         * @brief Linearize the problem and solve for primal variables (xᵢ₊₁)\n         * and dual variables (λᵢ).\n         *\n         * Linearization:\n         * \\f{aligned}{\n         *      A x_{i+1} = b + \\nabla g(x_i)^T \\lambda_i \\\\\n         *      0 \\leq \\lambda_i \\perp g(x_i) + \\nabla g(x_i) Δx \\geq 0\n         * \\f}\n         * Update:\n         * \\f{aligned}{\n         *      x_{i+1} = x_i + \\Delta x\n         * \\f}\n         * \\f$\\Delta x\\f$:\n         * * g_gradient update: \\f$\\Delta x = A^{-1} [\\nabla g(x_i)]^T \\lambda_i\n         *      \\f$\n         * * linearized update: \\f$\\Delta x = A^{-1} [\\nabla g(x_i)]^T \\lambda_i\n         *      + A^{-1}b - x_i\\f$\n         *\n         * We want to take our problem to the form\n         * \\f{aligned}{\n         *      s = q + N (M\\lambda_i + p) \\\\\n         *      0 \\leq \\lambda_i \\perp s \\geq 0\n         * \\f}\n         * where\n         * \\f{aligned}{\n         *      q &= g(x_i) \\\\\n         *      N &= \\nabla g(x_i) \\\\\n         *      M &= A^{-1} [\\nabla g(x_i)]^{T} \\\\\n         *      p &= \\Delta x - A^{-1} [\\nabla g(x_i)]^{T} \\lambda_i\n         * \\f}\n         */\n        Eigen::VectorXd solve_lcp();\n\n        /**\n         * @brief Compute \\f$A^{-1}x\\f$.\n         *\n         * Uses a precomputed decomposition of A to solve the system in\n         * \\f$O(n^2)\\f$.\n         */\n        Eigen::VectorXd Ainv(const Eigen::VectorXd& x) const;\n\n        // --------------------------------------------------------------------\n        // Fields\n        // --------------------------------------------------------------------\n        Eigen::SparseMatrix<double> A;\n        Eigen::VectorXd b;\n        ConstrainedProblem* problem_ptr;\n\n        /// @brief Current number of outer iterations completed.\n        int num_outer_iterations_;\n        std::string name_;\n        bool m_use_gradient = true;\n    };\n\n    void\n    zero_out_fixed_dof(const Eigen::VectorXb& is_fixed, Eigen::MatrixXd& jac);\n} // namespace opt\n} // namespace ccd\n", "meta": {"hexsha": "41b80921ed2f96312adee9406d350f7021eb49a8", "size": 5131, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "comparisons/STIV/src/solvers/ncp_solver.hpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "comparisons/STIV/src/solvers/ncp_solver.hpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "comparisons/STIV/src/solvers/ncp_solver.hpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 34.9047619048, "max_line_length": 80, "alphanum_fraction": 0.4958097837, "num_tokens": 1189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.44295639690619004}}
{"text": "#include \"MCHMM.h\"\n#include <cmath>\n#include \"Sampler.h\"\n#include <random>\n#include <chrono>\n#include <glog/logging.h>\n#include <cassert>\n#include <boost/math/distributions/students_t.hpp>\nusing namespace std;\nusing namespace google;\n\nMCHMM::MCHMM(){\n    pi = new vector<Sample>();\n    m = new vector<Sample>();\n    v = new vector<Sample>();\n}\n\n/**\n * @brief MCHMM::forward Goes one step forward in time according to the HMM distributions\n * @param observations Observations needed to do the reasoning based on the HMM\n * @param N Number of samples used in the resampling step of any sampling inside this method\n * @return Alpha DETree for the next time step distribution\n */\nDETree * MCHMM::forward(vector<Observation> *observations, size_t N){\n    vector<Sample> alpha_samples[2];\n    Sampler sampler;\n    size_t T = observations->size();\n\n    alpha_samples[0] = sampler.resample_from(pi_tree, N);\n\n    // STEP 2\n    size_t t = 0;\n    for (t = 1; t < T; t++){\n        // STEP 2(a)\n        vector<Sample> temp = sampler.likelihood_weighted_resampler(alpha_samples[(t - 1) % 2], N);\n        double sum_densities = 0.0;\n\n        for (size_t i = 0; i < temp.size(); i++){\n            // STEP 2(b)\n            Sample x = sampler.sample_given(m_tree, temp[i]);\n\n            for (size_t i = 0; i < temp[i].size(); i++){\n                x.values.pop_back();\n            }\n\n            // STEP 2(c)\n            Sample v_temp = (*observations)[t].combine(x);\n            double density = v_tree->density_value(v_temp, rho);\n            x.p = density;\n\n            sum_densities += density;\n            temp[i] = x;\n        }\n\n        // Normalizing the probabilities\n        for (size_t i = 0; i < temp.size(); i++){\n            temp[i].p = temp[i].p / sum_densities;\n        }\n\n        // STEP 2(d)\n        alpha_samples[t % 2] = temp;\n    }\n\n    vector<Sample> temp = sampler.likelihood_weighted_resampler(alpha_samples[(t - 1) % 2], N);\n    for (size_t i = 0; i < temp.size(); i++){\n        // STEP 2(b)\n        Sample x = sampler.sample_given(m_tree, temp[i]);\n        x.p = 1.0 / temp.size();\n        temp[i] = x;\n    }\n\n    return new DETree(temp, pi_low_limit, pi_high_limit);\n}\n\n/**\n * @brief MCHMM::gamma It perform the forward-backward algorithms and combine the results to get the\n * gamma distribution, it is useful mostly for getting the most probable states\n * @param observations Observations needed to do the reasoning based on the HMM\n * @param N Number of samples used in the resampling step of any sampling inside this method\n * @return Gamma DETrees for each observation\n */\nvector<DETree *> MCHMM::gamma(vector<Observation> *observations, size_t N){\n    Sampler sampler;\n    size_t T = observations->size();\n\n    vector<Sample> alpha_samples[2];\n    vector<Sample> beta_samples[2];\n\n    vector<DETree*> alpha_trees;\n    vector<DETree*> beta_trees;\n    vector<DETree*> gamma_trees;\n\n    // STEP 1\n    alpha_samples[0] = sampler.resample_from(pi_tree, N);\n    alpha_trees.push_back(new DETree(alpha_samples[0], pi_low_limit, pi_high_limit));\n\n    // STEP 2\n    for (size_t t = 1; t < T; t++){\n        // STEP 2(a)\n        vector<Sample> temp = sampler.likelihood_weighted_resampler(alpha_samples[(t - 1) % 2], N);\n        double sum_densities = 0.0;\n\n        for (size_t i = 0; i < temp.size(); i++){\n            // STEP 2(b)\n            Sample x = sampler.sample_given(m_tree, temp[i]);\n\n            for (size_t i = 0; i < temp[i].size(); i++){\n                x.values.pop_back();\n            }\n\n            // STEP 2(c)\n            Sample v_temp = (*observations)[t].combine(x);\n            double density = v_tree->density_value(v_temp, rho);\n            x.p = density;\n\n            sum_densities += density;\n            temp[i] = x;\n        }\n\n        // Normalizing the probabilities\n        for (size_t i = 0; i < temp.size(); i++){\n            temp[i].p = temp[i].p / sum_densities;\n        }\n\n        // STEP 2(d)\n        alpha_samples[t % 2] = temp;\n        alpha_trees.push_back(new DETree(temp, pi_low_limit, pi_high_limit));\n    }\n\n    // STEP 3\n    beta_samples[0] = sampler.uniform_sampling(pi_low_limit, pi_high_limit, N);\n    beta_trees.push_back(new DETree(beta_samples[0], pi_low_limit, pi_high_limit));\n\n    // STEP 4\n    for (size_t t = T - 1; t >= 1; t--){\n        // STEP 4(a)\n        int index_t = ((T) - (t + 1)) % 2;\n        vector<Sample> temp = sampler.likelihood_weighted_resampler(beta_samples[index_t], N);\n        double sum_densities = 0.0;\n\n        for (size_t i = 0; i < temp.size(); i++){\n            // STEP 4(b)\n            Sample x = sampler.sample_given(m_tree, temp[i]);\n\n            for (size_t i = 0; i < temp[i].size(); i++){\n                x.values.pop_back();\n            }\n\n            // STEP 4(c)\n            Sample v_temp = (*observations)[t].combine(x);\n            double density = v_tree->density_value(v_temp, rho);\n            x.p = density;\n\n            sum_densities += density;\n            temp[i] = x;\n        }\n\n        // Normalizing the probabilities\n        for (size_t i = 0; i < temp.size(); i++){\n            temp[i].p = temp[i].p / sum_densities;\n        }\n\n        // STEP 4(d)\n        beta_samples[(index_t + 1) % 2] = temp;\n        beta_trees.push_back(new DETree(temp, pi_low_limit, pi_high_limit));\n    }\n\n    // STEP 5\n    for (size_t t = 0; t < T; t++){\n        vector<Sample> temp;\n        double sum_density = 0.0;\n\n        int index_t = (T) - (t + 1);\n\n        // STEP 5(a)\n        for (size_t j = 0; j < N / 2; j++){\n            Sample sample = sampler.sample(alpha_trees[t]);\n            sample.p = (*beta_trees[index_t]).density_value(sample, rho);\n            sum_density += sample.p;\n            temp.push_back(sample);\n        }\n\n        // STEP 5(b)\n        for (size_t j = 0; j < N - (N / 2); j++){\n            Sample sample = sampler.sample(beta_trees[index_t]);\n            sample.p = (*alpha_trees[t]).density_value(sample, rho);\n            sum_density += sample.p;\n            temp.push_back(sample);\n        }\n\n        // Normalizing the probabilities\n        for (size_t i = 0; i < temp.size(); i++){\n            temp[i].p = temp[i].p / sum_density;\n        }\n\n        gamma_trees.push_back(new DETree(temp, pi_low_limit, pi_high_limit));\n    }\n\n    alpha_samples[0].clear();\n    alpha_samples[1].clear();\n    beta_samples[0].clear();\n    beta_samples[1].clear();\n\n    for (size_t i = 0; i < alpha_trees.size(); i++){\n        delete alpha_trees[i];\n    }\n\n    for (size_t i = 0; i < beta_trees.size(); i++){\n        delete beta_trees[i];\n    }\n\n    assert(gamma_trees.size() == T);\n\n    return gamma_trees;\n}\n\n/**\n * @brief MCHMM::learn_hmm it takes in some observations and perform the EM as many iterations as the max_iteration arg\n * @param observations Observations needed for learning the HMM distributions\n * @param max_iteration Maximum number of iterations performed for the EM\n * @param N Number of samples used in the resampling step of any sampling inside this method\n */\nvoid MCHMM::learn_hmm_KL(vector<Observation> *observations, double threshold, size_t max_iteration, int N){\n    if (observations->size() < 2){\n        LOG(ERROR) << \"Not enough observation data!\";\n        return;\n    }\n\n    Sampler sampler;\n    size_t T = observations->size();\n\n    if (pi->size() < 1 || v->size() < 1 || m->size() < 1){\n        LOG(INFO) << \"Init HMM Randomly!\";\n        init_hmm_randomly(N, N, N);\n    }\n\n    bool cond = true;\n    size_t iteration = 0;\n    DETree* old_gamma_tree = NULL;\n\n    vector<Sample> test_samples = sampler.uniform_sampling(pi_low_limit, pi_high_limit, 1000);\n\n    while (cond){\n        vector<Sample> alpha_samples[2];\n        vector<Sample> beta_samples[2];\n\n        vector<DETree*> alpha_trees;\n        vector<DETree*> beta_trees;\n        vector<DETree*> gamma_trees;\n\n        /////////////////E STEP/////////////////\n        {\n            // STEP 1\n            alpha_samples[0] = sampler.resample_from(pi_tree, N);\n            alpha_trees.push_back(new DETree(alpha_samples[0], pi_low_limit, pi_high_limit));\n\n            // STEP 2\n            for (size_t t = 1; t < T; t++){\n                // STEP 2(a)\n                vector<Sample> temp = sampler.likelihood_weighted_resampler(alpha_samples[(t - 1) % 2], N);\n                double sum_densities = 0.0;\n\n                for (size_t i = 0; i < temp.size(); i++){\n                    // STEP 2(b)\n                    Sample x = sampler.sample_given(m_tree, temp[i]);\n\n                    for (size_t i = 0; i < temp[i].size(); i++){\n                        x.values.pop_back();\n                    }\n\n                    // STEP 2(c)\n                    Sample v_temp = (*observations)[t].combine(x);\n                    double density = v_tree->density_value(v_temp, rho);\n                    x.p = density;\n\n                    sum_densities += density;\n                    temp[i] = x;\n                }\n\n                // Normalizing the probabilities\n                for (size_t i = 0; i < temp.size(); i++){\n                    temp[i].p = temp[i].p / sum_densities;\n                }\n\n                // STEP 2(d)\n                alpha_samples[t % 2] = temp;\n                alpha_trees.push_back(new DETree(temp, pi_low_limit, pi_high_limit));\n            }\n\n            // STEP 3\n            beta_samples[0] = sampler.uniform_sampling(pi_low_limit, pi_high_limit, N);\n            beta_trees.push_back(new DETree(beta_samples[0], pi_low_limit, pi_high_limit));\n\n            // STEP 4\n            for (size_t t = T - 1; t >= 1; t--){\n                // STEP 4(a)\n                int index_t = ((T) - (t + 1)) % 2;\n                vector<Sample> temp = sampler.likelihood_weighted_resampler(beta_samples[index_t], N);\n                double sum_densities = 0.0;\n\n                for (size_t i = 0; i < temp.size(); i++){\n                    // STEP 4(b)\n                    Sample x = sampler.sample_given(m_tree, temp[i]);\n\n                    for (size_t i = 0; i < temp[i].size(); i++){\n                        x.values.pop_back();\n                    }\n\n                    // STEP 4(c)\n                    Sample v_temp = (*observations)[t].combine(x);\n                    double density = v_tree->density_value(v_temp, rho);\n                    x.p = density;\n\n                    sum_densities += density;\n                    temp[i] = x;\n                }\n\n                // Normalizing the probabilities\n                for (size_t i = 0; i < temp.size(); i++){\n                    temp[i].p = temp[i].p / sum_densities;\n                }\n\n                // STEP 4(d)\n                beta_samples[(index_t + 1) % 2] = temp;\n                beta_trees.push_back(new DETree(temp, pi_low_limit, pi_high_limit));\n            }\n\n            // STEP 5\n            for (size_t t = 1; t < T; t++){\n                vector<Sample> temp;\n                double sum_density = 0.0;\n\n                int index_t = (T) - (t);\n\n                // STEP 5(a)\n                for (int j = 0; j < N / 2; j++){\n                    Sample sample = sampler.sample(alpha_trees[t]);\n                    sample.p = (*beta_trees[index_t]).density_value(sample, rho);\n                    sum_density += sample.p;\n                    temp.push_back(sample);\n                }\n\n                // STEP 5(b)\n                for (int j = 0; j < N - (N / 2); j++){\n                    Sample sample = sampler.sample(beta_trees[index_t]);\n                    sample.p = (*alpha_trees[t]).density_value(sample, rho);\n                    sum_density += sample.p;\n                    temp.push_back(sample);\n                }\n\n                // Normalizing the probabilities\n                for (size_t i = 0; i < temp.size(); i++){\n                    temp[i].p = temp[i].p / sum_density;\n                }\n\n                gamma_trees.push_back(new DETree(temp, pi_low_limit, pi_high_limit));\n            }\n\n            alpha_samples[0].clear();\n            alpha_samples[1].clear();\n            beta_samples[0].clear();\n            beta_samples[1].clear();\n\n            LOG(INFO) << \"End of E Step at iteration: \" << iteration;\n        }\n\n        /////////////////M STEP/////////////////\n        {\n            unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n            std::default_random_engine gen(seed);\n\n            vector<Sample> * temp_m = new vector<Sample>();\n            vector<Sample> * temp_v = new vector<Sample>();\n            vector<Sample> * temp_pi = new vector<Sample>();\n\n            // STEP 1\n            for (int i = 0; i < N; i++){\n                uniform_real_distribution<double> dist(1, T - 2);\n                int t = dist(gen);\n\n                Sample x = sampler.sample(gamma_trees[t]);\n                Sample x_prime = sampler.sample(gamma_trees[t + 1]);\n\n                Sample temp = x.combine(x_prime.values);\n                temp.p = 1.0 / N;\n                temp_m->push_back(temp);\n            }\n\n            // STEP 2\n            for (int i = 0; i < N; i++){\n                uniform_real_distribution<double> dist(1, T - 1);\n                int t = dist(gen);\n\n                Sample x = sampler.sample(gamma_trees[t]);\n\n                Sample temp = (*observations)[t].combine(x);\n                temp.p = 1.0 / N;\n                temp_v->push_back(temp);\n            }\n\n            // STEP 3\n            int pi_size = pi->size();\n            for (int i = 0; i < pi_size; i++){\n                temp_pi->push_back(sampler.sample(gamma_trees[0]));\n            }\n\n            delete pi;\n            pi = temp_pi;\n            pi_tree->create_tree(*pi, pi_low_limit, pi_high_limit);\n\n            delete m;\n            m =  temp_m;\n            m_tree->create_tree(*m, m_low_limit, m_high_limit);\n\n            delete v;\n            v = temp_v;\n            v_tree->create_tree(*v, v_low_limit, v_high_limit);\n\n            LOG(INFO) << \"End of M Step at iteration: \" << iteration;\n\n        }\n\n        /////////////////ANNEALING/////////////////\n        if (rho > 0.01)\n            rho = rho * rho_bar;\n\n        /////////////////SAMPLE SET SIZE/////////////////\n        if (N < (int)max_sample_size)\n            N = N; // * eta;\n\n        /////////////////STOP CONDITION/////////////////\n        {\n            LOG(INFO) << \"Iteration \" << iteration + 1 << \" Finished!\" << \"\\n\";\n            iteration++;\n            if (iteration >= max_iteration){\n                cond = false;\n            }\n\n            if (iteration > 1){ // Do the KL if we have at least on previous HMM parameters set!!!\n                // Generate a lot of samples uniformly\n\n                // Find the density estimations for each generated sample\n                vector<double> estimates_old;\n                vector<double> estimates_new;\n                double sum_old = 0.0;\n                double sum_new = 0.0;\n                for (size_t r = 0; r < test_samples.size(); r++){\n                    estimates_old.push_back(old_gamma_tree->density_value(test_samples[r], 0.5));\n                    estimates_new.push_back(gamma_trees.back()->density_value(test_samples[r], 0.5));\n\n                    sum_old += estimates_old.back();\n                    sum_new += estimates_new.back();\n                }\n\n                // Normalize the density values\n                for (size_t r = 0; r < test_samples.size(); r++){\n                    estimates_old[r] = estimates_old[r] / sum_old;\n                    estimates_new[r] = estimates_new[r] / sum_new;\n                }\n\n                // Compute the KL divergence factor\n                double KLD = KLD_compute(estimates_old, estimates_new);\n\n                LOG(ERROR) << \"KLD: \" << KLD;\n\n                // If KLD < threshold --> STOP\n                if (KLD < threshold){\n                    cond = false;\n                }\n            }\n        }\n\n        for (size_t i = 0; i < alpha_trees.size(); i++){\n            delete alpha_trees[i];\n        }\n\n        for (size_t i = 0; i < beta_trees.size(); i++){\n            delete beta_trees[i];\n        }\n\n        for (size_t i = 0; i < gamma_trees.size() - 1; i++){\n            delete gamma_trees[i];\n        }\n\n        if (old_gamma_tree){\n            delete old_gamma_tree;\n        }\n\n        old_gamma_tree = gamma_trees.back();\n    }\n\n    initialized = true;\n}\n\n/**\n * @brief MCHMM::KLD_compute computes the Kullback-Leibler divergence of two distributions\n * @param P The true distribution (in this application, the true is our old distribution)\n * @param Q The estimated distribution (in this application, the estimated is our new distribution)\n * @return KLD value\n */\ndouble MCHMM::  KLD_compute(vector<double> P, vector<double> Q){\n    double KLD = 0.0;\n    for (size_t i = 0; i < P.size(); i++){\n        KLD += P[i] * std::log(P[i] / Q[i]);\n    }\n    return KLD;\n}\n\nvector<Sample> MCHMM::get_uniform_samples_from_pi(size_t N){\n    Sampler sampler;\n    return sampler.uniform_sampling(pi_low_limit, pi_high_limit, N);\n}\n\n/**\n * @brief MCHMM::learn_hmm it takes in some observations and perform the EM as many iterations as the max_iteration arg\n * @param observations Observations needed for learning the HMM distributions\n * @param max_iteration Maximum number of iterations performed for the EM\n * @param N Number of samples used in the resampling step of any sampling inside this method\n */\nvoid MCHMM::learn_hmm(vector<Observation> *observations, size_t max_iteration, int N){\n\n    if (observations->size() < 2){\n        LOG(ERROR) << \"Not enough observation data!\";\n        return;\n    }\n\n    Sampler sampler;\n    size_t T = observations->size();\n\n    if (pi->size() < 1 || v->size() < 1 || m->size() < 1){\n        LOG(INFO) << \"Init HMM Randomly!\";\n        init_hmm_randomly(N, N, N);\n    }\n\n    bool cond = true;\n    size_t iteration = 0;\n\n    while (cond){\n        vector<Sample> alpha_samples[2];\n        vector<Sample> beta_samples[2];\n\n        vector<DETree*> alpha_trees;\n        vector<DETree*> beta_trees;\n        vector<DETree*> gamma_trees;\n\n        /////////////////E STEP/////////////////\n        {\n            // STEP 1\n            alpha_samples[0] = sampler.resample_from(pi_tree, N);\n            alpha_trees.push_back(new DETree(alpha_samples[0], pi_low_limit, pi_high_limit));\n\n            // STEP 2\n            for (size_t t = 1; t < T; t++){\n                // STEP 2(a)\n                vector<Sample> temp = sampler.likelihood_weighted_resampler(alpha_samples[(t - 1) % 2], N);\n                double sum_densities = 0.0;\n\n                for (size_t i = 0; i < temp.size(); i++){\n                    // STEP 2(b)\n                    Sample x = sampler.sample_given(m_tree, temp[i]);\n\n                    for (size_t i = 0; i < temp[i].size(); i++){\n                        x.values.pop_back();\n                    }\n\n                    // STEP 2(c)\n                    Sample v_temp = (*observations)[t].combine(x);\n                    double density = v_tree->density_value(v_temp, rho);\n                    x.p = density;\n\n                    sum_densities += density;\n                    temp[i] = x;\n                }\n\n                // Normalizing the probabilities\n                for (size_t i = 0; i < temp.size(); i++){\n                    temp[i].p = temp[i].p / sum_densities;\n                }\n\n                // STEP 2(d)\n                alpha_samples[t % 2] = temp;\n                alpha_trees.push_back(new DETree(temp, pi_low_limit, pi_high_limit));\n            }\n\n            // STEP 3\n            beta_samples[0] = sampler.uniform_sampling(pi_low_limit, pi_high_limit, N);\n            beta_trees.push_back(new DETree(beta_samples[0], pi_low_limit, pi_high_limit));\n\n            // STEP 4\n            for (size_t t = T - 1; t >= 1; t--){\n                // STEP 4(a)\n                int index_t = ((T) - (t + 1)) % 2;\n                vector<Sample> temp = sampler.likelihood_weighted_resampler(beta_samples[index_t], N);\n                double sum_densities = 0.0;\n\n                for (size_t i = 0; i < temp.size(); i++){\n                    // STEP 4(b)\n                    Sample x = sampler.sample_given(m_tree, temp[i]);\n\n                    for (size_t i = 0; i < temp[i].size(); i++){\n                        x.values.pop_back();\n                    }\n\n                    // STEP 4(c)\n                    Sample v_temp = (*observations)[t].combine(x);\n                    double density = v_tree->density_value(v_temp, rho);\n                    x.p = density;\n\n                    sum_densities += density;\n                    temp[i] = x;\n                }\n\n                // Normalizing the probabilities\n                for (size_t i = 0; i < temp.size(); i++){\n                    temp[i].p = temp[i].p / sum_densities;\n                }\n\n                // STEP 4(d)\n                beta_samples[(index_t + 1) % 2] = temp;\n                beta_trees.push_back(new DETree(temp, pi_low_limit, pi_high_limit));\n            }\n\n            // STEP 5\n            for (size_t t = 1; t < T; t++){\n                vector<Sample> temp;\n                double sum_density = 0.0;\n\n                int index_t = (T) - (t);\n\n                // STEP 5(a)\n                for (int j = 0; j < N / 2; j++){\n                    Sample sample = sampler.sample(alpha_trees[t]);\n                    sample.p = (*beta_trees[index_t]).density_value(sample, rho);\n                    sum_density += sample.p;\n                    temp.push_back(sample);\n                }\n\n                // STEP 5(b)\n                for (int j = 0; j < N - (N / 2); j++){\n                    Sample sample = sampler.sample(beta_trees[index_t]);\n                    sample.p = (*alpha_trees[t]).density_value(sample, rho);\n                    sum_density += sample.p;\n                    temp.push_back(sample);\n                }\n\n                // Normalizing the probabilities\n                for (size_t i = 0; i < temp.size(); i++){\n                    temp[i].p = temp[i].p / sum_density;\n                }\n\n                gamma_trees.push_back(new DETree(temp, pi_low_limit, pi_high_limit));\n            }\n\n            alpha_samples[0].clear();\n            alpha_samples[1].clear();\n            beta_samples[0].clear();\n            beta_samples[1].clear();\n\n            LOG(INFO) << \"End of E Step at iteration: \" << iteration;\n        }\n\n        /////////////////M STEP/////////////////\n        {\n            unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n            std::default_random_engine gen(seed);\n\n            vector<Sample> * temp_m = new vector<Sample>();\n            vector<Sample> * temp_v = new vector<Sample>();\n            vector<Sample> * temp_pi = new vector<Sample>();\n\n            // STEP 1\n            for (int i = 0; i < N; i++){\n                uniform_real_distribution<double> dist(1, T - 2);\n                int t = dist(gen);\n\n                Sample x = sampler.sample(gamma_trees[t]);\n                Sample x_prime = sampler.sample(gamma_trees[t + 1]);\n\n                Sample temp = x.combine(x_prime.values);\n                temp.p = 1.0 / N;\n                temp_m->push_back(temp);\n            }\n\n            // STEP 2\n            for (int i = 0; i < N; i++){\n                uniform_real_distribution<double> dist(1, T - 1);\n                int t = dist(gen);\n\n                Sample x = sampler.sample(gamma_trees[t]);\n\n                Sample temp = (*observations)[t].combine(x);\n                temp.p = 1.0 / N;\n                temp_v->push_back(temp);\n            }\n\n            // STEP 3\n            int pi_size = pi->size();\n            for (int i = 0; i < pi_size; i++){\n                temp_pi->push_back(sampler.sample(gamma_trees[0]));\n            }\n\n            delete pi;\n            pi = temp_pi;\n            pi_tree->create_tree(*pi, pi_low_limit, pi_high_limit);\n\n            delete m;\n            m =  temp_m;\n            m_tree->create_tree(*m, m_low_limit, m_high_limit);\n\n            delete v;\n            v = temp_v;\n            v_tree->create_tree(*v, v_low_limit, v_high_limit);\n\n            LOG(INFO) << \"End of M Step at iteration: \" << iteration;\n\n        }\n\n        /////////////////ANNEALING/////////////////\n        if (rho > 0.01)\n            rho = rho * rho_bar;\n\n        /////////////////SAMPLE SET SIZE/////////////////\n        if (N < (int)max_sample_size)\n            N = N; // * eta;\n\n        /////////////////STOP CONDITION/////////////////\n        LOG(INFO) << \"Iteration \" << iteration + 1 << \" Finished!\" << \"\\n\";\n        iteration++;\n        if (iteration >= max_iteration){\n            cond = false;\n        }\n\n        for (size_t i = 0; i < alpha_trees.size(); i++){\n            delete alpha_trees[i];\n        }\n\n        for (size_t i = 0; i < beta_trees.size(); i++){\n            delete beta_trees[i];\n        }\n\n        for (size_t i = 0; i < gamma_trees.size(); i++){\n            delete gamma_trees[i];\n        }\n    }\n\n    initialized = true;\n}\n\n/**\n * @brief MCHMM::set_distributions Instead of learning the distributions one can use this to prime the HMM with pre-collected samples\n * @param pi Samples collected for the initial state distribution PI\n * @param m Samples collected for the transition distribution M\n * @param v Samples collected for the observation distribution NU\n * @param rho Amount of effect that different levels of the DETree have on the computed density value (default: 0.5)\n */\nvoid MCHMM::set_distributions(vector<Sample> *pi, vector<Sample> *m, vector<Sample> *v, double rho){\n    this->pi = new vector<Sample>();\n    this->m = new vector<Sample>();\n    this->v = new vector<Sample>();\n\n    for (size_t i = 0; i < pi->size(); i++){\n        this->pi->push_back((*pi)[i]);\n    }\n\n    for (size_t i = 0; i < m->size(); i++){\n        this->m->push_back((*m)[i]);\n    }\n\n    for (size_t i = 0; i < v->size(); i++){\n        this->v->push_back((*v)[i]);\n    }\n\n    this->rho = rho;\n\n    pi_tree = new DETree(*pi, pi_low_limit, pi_high_limit);\n    m_tree = new DETree(*m, m_low_limit, m_high_limit);\n    v_tree = new DETree(*v, v_low_limit, v_high_limit);\n\n    initialized = true;\n}\n\nvoid MCHMM::set_limits(vector<double> *pi_low_limit, vector<double> *pi_high_limit,\n                       vector<double> *m_low_limit, vector<double> *m_high_limit,\n                       vector<double> *v_low_limit, vector<double> *v_high_limit\n                       )\n{\n    this->pi_low_limit = pi_low_limit;\n    this->pi_high_limit = pi_high_limit;\n\n    this->m_low_limit = m_low_limit;\n    this->m_high_limit = m_high_limit;\n\n    this->v_low_limit = v_low_limit;\n    this->v_high_limit = v_high_limit;\n}\n\nvoid MCHMM::init_hmm_randomly(int sample_size_pi, int sample_size_m, int sample_size_v){\n\n    if (pi_low_limit == NULL){\n        LOG(FATAL) << \"Please set the limits first and then run this method!!!\";\n    }\n\n    for (int i = 0; i < sample_size_pi; i++){\n        Sample sample;\n        sample.init_rand(pi_low_limit, pi_high_limit);\n        sample.p = 1.0 / sample_size_pi;\n        pi->push_back(sample);\n    }\n\n    for (int i = 0; i < sample_size_m; i++){\n        Sample sample;\n        sample.init_rand(m_low_limit, m_high_limit);\n        sample.p = 1.0 / sample_size_m;\n        m->push_back(sample);\n    }\n\n    for (int i = 0; i < sample_size_v; i++){\n        Sample sample;\n        sample.init_rand(v_low_limit, v_high_limit);\n        sample.p = 1.0 / sample_size_v;\n        v->push_back(sample);\n    }\n\n    pi_tree = new DETree(*pi, pi_low_limit, pi_high_limit);\n    m_tree = new DETree(*m, m_low_limit, m_high_limit);\n    v_tree = new DETree(*v, v_low_limit, v_high_limit);\n\n    initialized = true;\n}\n\ndouble MCHMM::_rho(){\n    return this->rho;\n}\n\nbool MCHMM::initialized_(){\n    return initialized;\n}\n\nDETree* MCHMM::pi_tree_(){\n    return pi_tree;\n}\n", "meta": {"hexsha": "6ea2dfa02b806b9e4e853bca1c91bbb9411a1936", "size": 27730, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MCHMM.cpp", "max_stars_repo_name": "sina-cb/ContinuousFactorialHMM", "max_stars_repo_head_hexsha": "c7ae4c8627a07b77e946daeea642bb3ff5348cbd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MCHMM.cpp", "max_issues_repo_name": "sina-cb/ContinuousFactorialHMM", "max_issues_repo_head_hexsha": "c7ae4c8627a07b77e946daeea642bb3ff5348cbd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MCHMM.cpp", "max_forks_repo_name": "sina-cb/ContinuousFactorialHMM", "max_forks_repo_head_hexsha": "c7ae4c8627a07b77e946daeea642bb3ff5348cbd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9334916865, "max_line_length": 133, "alphanum_fraction": 0.5099891814, "num_tokens": 6699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.44295639690619004}}
{"text": "\n#ifdef _WIN32\n#pragma warning(disable:4503)\n#pragma warning(push)\n#pragma warning(disable:4996 4251 4275 4800 4190 4244)\n#endif\n#include <vector>\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/imgcodecs.hpp\"\n\n#ifdef _MSC_VER\n#include <intrin.h>\n#define __builtin_popcount __popcnt\n#endif\n\n#ifdef _WIN32\n#pragma warning(pop)\n#endif\n\n#include <boost/math/special_functions/erf.hpp>\n#include \"Block.h\"\n#include \"ParamValidator.h\"\n\nusing std::vector;\nusing std::string;\nusing cv::Mat;\n\nnamespace charliesoft\n{\n  BLOCK_BEGIN_INSTANTIATION(CORE_filter);\n  inline double hamming_distance(char* vals1, char* vals2, int nbVals)\n  {\n    int output = 0;\n    int i;\n    int nbValsPacked = nbVals - 3;\n    for (i = 0; i < nbValsPacked; i += 4) {\n      output += __builtin_popcount(\n        *((uint32_t *)(&vals1[i])) ^ *((uint32_t *)(&vals2[i])));\n    }\n    //if nbVals is not 4bytes packed\n    for (; i < nbVals; i++)\n      output += __builtin_popcount((unsigned char)vals1[i] ^ (unsigned char)vals2[i]);\n    return output;\n  };\n\n  template<typename T>\n  inline double euclidean2_distance(T* vals1, T* vals2, int nbVals)\n  {\n    double output = 0;\n    int i;\n    for (i = 0; i < nbVals; i ++) {\n      T tmp = vals1[i] - vals2[i];\n      output += static_cast<double>(tmp*tmp);\n    }\n    return output;\n  };\n\n  template<typename T>\n  cv::Mat get_distances_float_opt(cv::Mat features, float sigma, cv::Mat points, double boostThreshold)\n  {\n    static cv::Mat output(cv::Size(features.rows, features.rows), CV_64FC1);\n    if (output.rows != features.rows)\n      output = Mat(cv::Size(features.rows, features.rows), CV_64FC1);\n\n    double* tmp = new double[features.cols];\n    float* tmpP = new float[points.cols];\n    float* ptrP = points.ptr<float>();\n\n    double sigma_carre = 2 * sigma*sigma;\n\n    double* ptr = output.ptr<double>();\n    T* val = features.ptr<T>();\n    int nbFeatures = features.cols;\n    int totalSwitch = 0;\n    for (int i = 0; i < output.rows; i++)\n    {\n      int realAdress = i*output.cols;\n      ptr[realAdress + i] = 1;\n\n      T* val1 = &val[i*features.cols];\n      int nbCopy = 1;\n      for (int j = i + 1; j < output.cols; j++)\n      {\n        double test = ptr[realAdress + j] = exp(\n          -euclidean2_distance(val1, &val[j*nbFeatures], nbFeatures)\n          / sigma_carre);\n        if (test > boostThreshold)//points are the same!\n        {\n          if (i + nbCopy < j)\n          {\n            //switch (i+nbCopy)th line with jth feature:\n            memcpy(tmp, &val[j*nbFeatures], sizeof(T)*nbFeatures);\n            memcpy(&val[j*nbFeatures], &val[(i + nbCopy)*nbFeatures], sizeof(T)*nbFeatures);\n            memcpy(&val[(i + nbCopy)*nbFeatures], tmp, sizeof(T)*nbFeatures);\n\n            //switch also the points\n            float* pt1 = &ptrP[j*points.cols];\n            float* pt2 = &ptrP[(i + nbCopy)*points.cols];\n            memcpy(tmpP, pt1, sizeof(float)*points.cols);\n            memcpy(pt1, pt2, sizeof(float)*points.cols);\n            memcpy(pt2, tmpP, sizeof(float)*points.cols);\n            \n            //also switch the value of previously computed distance:\n            for (int cpt = 0; cpt <= i; cpt++)\n              std::swap(ptr[cpt*output.cols + j], ptr[cpt*output.cols + i + nbCopy]);\n\n          }\n          nbCopy++;\n        }\n      }\n      //copy the distances of ith point:\n      for (int cpt = 1; cpt < nbCopy; cpt++)\n        memcpy(&ptr[realAdress + cpt*output.cols + i + cpt], &ptr[realAdress + i + cpt], sizeof(double)*(output.cols - (i + cpt)));\n      \n      nbCopy--;\n      i += nbCopy;//skip the same points...\n      totalSwitch += nbCopy;\n    }\n    delete[] tmp;\n    delete[] tmpP;\n    cv::Mat cleanImg;\n    output.convertTo(cleanImg, CV_8UC1, 512);\n    cv::imwrite(\"avecOpt.bmp\", cleanImg);\n    return output;\n  }\n\n  cv::Mat get_distances_binary_opt(cv::Mat features, double mu, int nbBits, cv::Mat points, double boostThreshold)\n  {\n    static cv::Mat output(cv::Size(features.rows, features.rows), CV_64FC1);\n    if (output.rows != features.rows)\n      output = Mat(cv::Size(features.rows, features.rows), CV_64FC1);\n\n    double* tmp = new double[features.cols];\n    float* tmpP = new float[points.cols];\n    float* ptrP = points.ptr<float>();\n\n    double* ptr = output.ptr<double>();\n    char* val = features.ptr<char>();\n\n    int nbFeatures = features.cols;\n    int sizeFeatures = features.cols * 8;\n    int totalSwitch = 0;\n    for (int i = 0; i < output.rows; i++)\n    {\n      int realAdress = i*output.cols;\n      ptr[realAdress + i] = 1;\n\n      char* val1 = &val[i*features.cols];\n      int nbCopy = 1;\n      for (int j = i + 1; j < output.cols; j++)\n      {\n        double distTmp = hamming_distance(\n          val1, &val[j*features.cols], nbFeatures);\n\n        double test = ptr[realAdress + j] = (pow(mu, (int)distTmp) * pow(1. - mu, (int)(nbBits - distTmp)));\n\n        if (distTmp / nbBits > boostThreshold)//points are the same!\n        {\n          if (i + nbCopy < j)\n          {\n            //switch (i+nbCopy)th line with jth feature:\n            memcpy(tmp, &val[j*nbFeatures], nbFeatures);\n            memcpy(&val[j*nbFeatures], &val[(i + nbCopy)*nbFeatures], nbFeatures);\n            memcpy(&val[(i + nbCopy)*nbFeatures], tmp, nbFeatures);\n\n            //switch also the points\n            float* pt1 = &ptrP[j*points.cols];\n            float* pt2 = &ptrP[(i + nbCopy)*points.cols];\n            memcpy(tmpP, pt1, sizeof(float)*points.cols);\n            memcpy(pt1, pt2, sizeof(float)*points.cols);\n            memcpy(pt2, tmpP, sizeof(float)*points.cols);\n\n            //also switch the value of previously computed distance:\n            for (int cpt = 0; cpt <= i; cpt++)\n              std::swap(ptr[cpt*output.cols + j], ptr[cpt*output.cols + i + nbCopy]);\n          }\n          nbCopy++;\n        }\n      }\n      //copy the distances of ith point:\n      for (int cpt = 1; cpt < nbCopy; cpt++)\n        memcpy(&ptr[realAdress + cpt*output.cols + i + cpt], &ptr[realAdress + i + cpt], sizeof(double)*(output.cols - (i + cpt)));\n\n      nbCopy--;\n      i += nbCopy;//skip the same points...\n      totalSwitch += nbCopy;\n    }\n    delete[] tmp;\n    delete[] tmpP;\n    return output;\n  }\n\n  template<typename T>\n  cv::Mat get_distances_float(cv::Mat features, float sigma)\n  {\n    static cv::Mat output(cv::Size(features.rows, features.rows), CV_64FC1);\n    if (output.rows != features.rows)\n      output = Mat(cv::Size(features.rows, features.rows), CV_64FC1);\n\n    float sigma_carre = 2 * sigma*sigma;\n\n    double* ptr = output.ptr<double>();\n    T* val = features.ptr<T>();\n    int nbFeatures = features.cols;\n    for (int i = 0; i < features.rows; i++)\n    {\n      int realAdress = i*features.rows;\n      ptr[realAdress + i] = 0;//diagonal distance is null...\n      T* val1 = &val[i*features.cols];\n      for (int j = i + 1; j < features.rows; j++)\n      {\n        ptr[realAdress + j] = exp(\n          -euclidean2_distance(val1, &val[j*features.cols], nbFeatures)\n          / sigma_carre);\n      }\n    }\n    return output;\n  }\n\n  cv::Mat get_distances_binary(cv::Mat features, double mu, int nbBits)\n  {\n    static cv::Mat output(cv::Size(features.rows, features.rows), CV_64FC1);\n    if (output.rows != features.rows)\n      output = Mat(cv::Size(features.rows, features.rows), CV_64FC1);\n    output.setTo(0);\n\n    double* ptr = output.ptr<double>();\n    char* val = features.ptr<char>();\n    int nbFeatures = features.cols;\n    for (int i = 0; i < features.rows; i++)\n    {\n      int realAdress = i*features.rows;\n      char* val1 = &val[i*features.cols];\n      for (int j = i + 1; j < features.rows; j++)\n      {\n        double dist = hamming_distance(\n          val1, &val[j*features.cols], nbFeatures);\n\n        ptr[realAdress + j] = (pow(mu, (int)dist)) * (pow(1. - mu, (int)(nbBits - dist)));\n      }\n    }\n    return output;\n  }\n\n\n  std::vector<double> get_criterions(cv::Mat distances)\n  {\n    std::vector<double> output;\n    for (int i = 0; i < distances.cols; i++)\n      output.push_back(0);\n    //double divisor = 1.;// (1. / ((distances.rows - 1.) * pow((sigma*sqrt(2 * CV_PI)), D)));\n\n    for (int i = 0; i < distances.cols; i++)\n    {\n      double* dist_i = distances.ptr<double>(i);\n      double crit_i = 0;\n      for (int j = i + 1; j < distances.rows; j++)\n      {\n        double crit_i = dist_i[j];\n        output[i] += crit_i;\n        output[j] += crit_i;\n      }\n    }\n\n    return output;\n  };\n\n  double get_threshold_float(double p, double D, double sigma, double N)\n  {\n    double gamma = 2.*pow(boost::math::erf_inv(2 * p - 1), 2);\n    double v = sigma * sigma * (D + 2. * sqrt(gamma*(D - gamma))) / (D - 2 * gamma);\n    double Ci = pow(2. * CV_PI * v, -D / 2.);\n\n    return Ci*(N - 1)*pow(sqrt(CV_PI*2.) * sigma, D);\n  }\n\n  double get_threshold_binary(double p, double D, double mu, double N)\n  {\n    double v = 0;\n    double gamma = 2.*pow(boost::math::erf_inv(2 * p - 1), 2);\n\n    if (p < 0.5)\n      v = (2 * mu*D + gamma + sqrt(gamma * (8 * mu * D + gamma))) / (2.*D);\n    if (p > 0.5)\n      v = (2 * mu*D + gamma - sqrt(gamma * (8 * mu * D + gamma))) / (2.*D);\n    if (p == 0.5)\n      v = mu;\n\n    double Ci = pow(1. - v, D);\n\n    return Ci;\n  }\n\n\n  BLOCK_END_INSTANTIATION(CORE_filter, AlgoType::imgProcess, BLOCK__CORE_NAME);\n\n  BEGIN_BLOCK_INPUT_PARAMS(CORE_filter);\n  //Add parameters, with following parameters:\n  ADD_PARAMETER(toBeLinked, Matrix, \"BLOCK__CORE_IN_POINTS\", \"BLOCK__CORE_IN_POINTS_HELP\");\n  ADD_PARAMETER(toBeLinked, Matrix, \"BLOCK__CORE_IN_DESC\", \"BLOCK__CORE_IN_DESC_HELP\");\n  ADD_PARAMETER_FULL(false, Float, \"BLOCK__CORE_IN_THRESHOLD\", \"BLOCK__CORE_IN_THRESHOLD_HELP\", 90.f);\n  ADD_PARAMETER_FULL(false, Float, \"BLOCK__CORE_IN_OPTIM_THRESHOLD\", \"BLOCK__CORE_IN_OPTIM_THRESHOLD_HELP\", .75f);\n  END_BLOCK_PARAMS();\n\n  BEGIN_BLOCK_OUTPUT_PARAMS(CORE_filter);\n  ADD_PARAMETER(toBeLinked, Matrix, \"BLOCK__CORE_OUT_POINTS\", \"BLOCK__CORE_OUT_POINTS_HELP\");\n  ADD_PARAMETER(toBeLinked, Matrix, \"BLOCK__CORE_OUT_DESC\", \"BLOCK__CORE_OUT_DESC_HELP\");\n  END_BLOCK_PARAMS();\n\n  BEGIN_BLOCK_SUBPARAMS_DEF(CORE_filter);\n  END_BLOCK_PARAMS();\n\n  CORE_filter::CORE_filter() :Block(\"BLOCK__CORE_NAME\", true){\n    _myInputs[\"BLOCK__CORE_IN_POINTS\"].addValidator({ new ValNeeded() });\n    _myInputs[\"BLOCK__CORE_IN_THRESHOLD\"].addValidator({ new ValRange(0,100) });\n  };\n\n  template <typename T>\n  vector<size_t> sort_indexes(const vector<T> &v) {\n\n    // initialize original index locations\n    vector<size_t> idx(v.size());\n    for (size_t i = 0; i != idx.size(); ++i) idx[i] = i;\n\n    // sort indexes based on comparing values in v\n    std::sort(idx.begin(), idx.end(),\n      [&v](size_t i1, size_t i2) {return v[i1] < v[i2]; });\n\n    return idx;\n  }\n\n  bool CORE_filter::run(bool oneShot){\n    double percent = _myInputs[\"BLOCK__CORE_IN_THRESHOLD\"].get<double>() / 100.;\n    double percentOpt = _myInputs[\"BLOCK__CORE_IN_OPTIM_THRESHOLD\"].get<double>();\n    cv::Mat points = _myInputs[\"BLOCK__CORE_IN_POINTS\"].get<cv::Mat>().clone();\n    cv::Mat desc = _myInputs[\"BLOCK__CORE_IN_DESC\"].get<cv::Mat>().clone();\n    if (points.empty() || desc.empty())\n    {\n      _myOutputs[\"BLOCK__CORE_OUT_POINTS\"] = points;\n      _myOutputs[\"BLOCK__CORE_OUT_DESC\"] = desc;\n      return true;//not a problem, just nothing to produce...\n    }\n    int nbChanels = points.channels();\n    if (nbChanels != 1)\n      points = points.reshape(1, points.rows);\n    if (points.depth() != CV_32F)\n      points.convertTo(points, CV_32F);\n\n    float sigma = 32.135f;\n    double mu = 0.1;\n\n    int dataSize = 8 * desc.cols;\n    bool isBinary = true, isFloat = false;\n    if (desc.depth() == CV_16U || desc.depth() == CV_16S)\n      dataSize = 16 * desc.cols;\n    if (desc.depth() == CV_32S)\n      dataSize = 32 * desc.cols;\n    if (desc.depth() == CV_32F)\n    {\n      dataSize = desc.cols;//we just need the number of values, not the number of bytes...\n      isBinary = false;\n      isFloat = true;\n    }\n    if (desc.depth() == CV_64F)\n    {\n      dataSize = desc.cols;//we just need the number of values, not the number of bytes...\n      isBinary = false;\n      isFloat = false;\n    }\n    std::vector<double> crit;\n    cv::Mat distances;\n    if (isBinary)\n    {\n      if (percentOpt >= 1)\n        distances = get_distances_binary(desc, mu, dataSize);\n      else\n      {\n        auto tick = boost::posix_time::microsec_clock::local_time();/*\n        distances = get_distances_binary_opt(desc, 0.1, dataSize, points, percentOpt);\n        distances = get_distances_binary_opt(desc, 0.1, dataSize, points, percentOpt);\n        distances = get_distances_binary_opt(desc, 0.1, dataSize, points, percentOpt);\n        distances = get_distances_binary_opt(desc, 0.1, dataSize, points, percentOpt);\n        distances = get_distances_binary_opt(desc, 0.1, dataSize, points, percentOpt);*/\n        distances = get_distances_binary_opt(desc, mu, dataSize, points, percentOpt);\n        auto now = boost::posix_time::microsec_clock::local_time();\n        static long long elapsed = 0;\n        static int nbEchantillons = 0;\n        nbEchantillons++;\n        elapsed += (now - tick).total_microseconds();\n\n        tick = boost::posix_time::microsec_clock::local_time();\n        cv::Mat distances1 = get_distances_binary(desc, mu, dataSize);/*\n        distances1 = get_distances_binary(desc, 0.1, dataSize);\n        distances1 = get_distances_binary(desc, 0.1, dataSize);\n        distances1 = get_distances_binary(desc, 0.1, dataSize);\n        distances1 = get_distances_binary(desc, 0.1, dataSize);\n        distances1 = get_distances_binary(desc, 0.1, dataSize);*/\n        now = boost::posix_time::microsec_clock::local_time();\n        static long long elapsed1 = 0;\n        elapsed1 += (now - tick).total_microseconds();\n        std::cout << elapsed / nbEchantillons << \" sans optim : \" << elapsed1 / nbEchantillons << \" gain : \" << elapsed * 100 / elapsed1 << std::endl;\n        distances1.ptr<double>();\n      }\n    }\n    else\n    {\n      if (percentOpt >= 1)\n      {\n        if (isFloat)\n          distances = get_distances_float<float>(desc, sigma);\n        else\n          distances = get_distances_float<double>(desc, sigma);\n      }\n      else\n      {\n        if (isFloat)\n        {\n          auto tick = boost::posix_time::microsec_clock::local_time();\n          distances = get_distances_float_opt<float>(desc, sigma, points, percentOpt);/*\n          distances = get_distances_float_opt<float>(desc, sigma, points, percentOpt);\n          distances = get_distances_float_opt<float>(desc, sigma, points, percentOpt);\n          distances = get_distances_float_opt<float>(desc, sigma, points, percentOpt);\n          distances = get_distances_float_opt<float>(desc, sigma, points, percentOpt);\n          distances = get_distances_float_opt<float>(desc, sigma, points, percentOpt);*/\n          auto now = boost::posix_time::microsec_clock::local_time();\n          auto elapsed = (now - tick).total_microseconds();\n\n          tick = boost::posix_time::microsec_clock::local_time();\n          cv::Mat distances1 = get_distances_float<float>(desc, sigma);/*\n          distances1 = get_distances_float<float>(desc, sigma);\n          distances1 = get_distances_float<float>(desc, sigma);\n          distances1 = get_distances_float<float>(desc, sigma);\n          distances1 = get_distances_float<float>(desc, sigma);\n          distances1 = get_distances_float<float>(desc, sigma);*/\n          now = boost::posix_time::microsec_clock::local_time();\n          auto elapsed1 = (now - tick).total_microseconds();\n          std::cout << elapsed << \" sans optim : \" << elapsed1 << \" gain : \" << elapsed * 100 / elapsed1 << std::endl;\n          distances1.ptr<double>();\n        }\n        else\n          distances = get_distances_float_opt<double>(desc, sigma, points, percentOpt);\n      }\n    }\n    crit = get_criterions(distances);\n\n    std::vector<size_t> indices = sort_indexes(crit);\n\n    int nbVals = 0;\n    if (!isBinary)\n    {\n      //first count the correct values:\n      double threshold = get_threshold_float(percent, desc.cols, sigma, crit.size());\n      for (size_t i = 0; i < crit.size(); i++) {\n        if (crit[i] < threshold)\n          nbVals++;\n        else\n          break;\n      }\n    }\n    else\n    {\n      //first count the correct values:\n      double threshold = get_threshold_binary(percent, desc.cols, mu, crit.size());\n      for (size_t i = 0; i < crit.size(); i++) {\n        if (crit[i] < threshold)\n          nbVals++;\n        else\n          break;\n      }\n    }\n    //nbVals = (int)(points.rows*percent);\n\n    cv::Mat outPoints(cv::Size(points.cols, nbVals), points.type());\n    cv::Mat outDesc(cv::Size(desc.cols, nbVals), desc.type());\n    for (int i = 0; i < nbVals; i++) {\n      int bestIndice = indices[i];\n      memcpy(outPoints.ptr<float>(i), points.ptr<float>(bestIndice), points.cols*sizeof(float));\n\n      if (desc.depth() == CV_8U || desc.depth() == CV_8S)\n        memcpy(outDesc.ptr<char>(i), desc.ptr<char>(bestIndice), desc.cols*sizeof(char));\n\n      if (desc.depth() == CV_16U || desc.depth() == CV_16S)\n        memcpy(outDesc.ptr<short>(i), desc.ptr<short>(bestIndice), desc.cols*sizeof(short));\n\n      if (desc.depth() == CV_32S || desc.depth() == CV_32F)\n        memcpy(outDesc.ptr<float>(i), desc.ptr<float>(bestIndice), desc.cols*sizeof(float));\n\n      if (desc.depth() == CV_64F)\n        memcpy(outDesc.ptr<double>(i), desc.ptr<double>(bestIndice), desc.cols*sizeof(double));\n    }\n    _myOutputs[\"BLOCK__CORE_OUT_POINTS\"] = outPoints;\n    _myOutputs[\"BLOCK__CORE_OUT_DESC\"] = outDesc;\n\n\n    return true;\n  };\n};", "meta": {"hexsha": "4c24ea165b755a2685906af0901a1eda482f8cef", "size": 17529, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sources/blocks/CORE_filter.cpp", "max_stars_repo_name": "Petititi/imGraph", "max_stars_repo_head_hexsha": "068890ffe2f8fa1fb51bc95b8d9296cc79737fac", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T11:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2015-03-25T18:24:38.000Z", "max_issues_repo_path": "Sources/blocks/CORE_filter.cpp", "max_issues_repo_name": "Petititi/imGraph", "max_issues_repo_head_hexsha": "068890ffe2f8fa1fb51bc95b8d9296cc79737fac", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T11:59:07.000Z", "max_issues_repo_issues_event_max_datetime": "2015-04-24T13:02:01.000Z", "max_forks_repo_path": "Sources/blocks/CORE_filter.cpp", "max_forks_repo_name": "Petititi/imGraph", "max_forks_repo_head_hexsha": "068890ffe2f8fa1fb51bc95b8d9296cc79737fac", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-20T12:18:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-20T12:18:18.000Z", "avg_line_length": 35.2696177062, "max_line_length": 150, "alphanum_fraction": 0.6065377375, "num_tokens": 4790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.44294638683425397}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Hidekazu Ikeno\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n///\n/// \\file fast_esprit.hpp\n///\n#ifndef MXPFIT_ESPRIT_HPP\n#define MXPFIT_ESPRIT_HPP\n\n#include <algorithm>\n#include <type_traits>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/SVD>\n\n#include <mxpfit/exponential_sum.hpp>\n#include <mxpfit/prony_like_method_common.hpp>\n\nnamespace mxpfit\n{\n///\n/// ### ESPRIT\n///\n/// \\brief ESPRIT method for finding parameters of exponential sum\n/// approximation from sampled data on uniform grid.\n///\n/// \\tparam T  Scalar type of function values.\n///\n/// #### Description\n///\n/// This class implements the Estimation of Signal Parameters via Rotational\n/// Invariance Techniques (ESPRIT) method for parameter estimation of decaying\n/// exponential sum funcitons.\n///\n/// This class is implemented only for the benchmarking purpose to compare with\n/// the fast ESPRIT algorithm. DO NOT use the class for practical applications,\n/// use `FastESPRIT` class instead, which is much faster than ESPRIT.\n///\n///\n/// #### References\n///\n/// 1. D. Potts and M. Tasche,\"Parameter estimation for nonincreasing\n///    exponential sums by Prony-like methods\", Linear Algebra Appl. **439**\n///    (2013) 1024-1039.\n///    [DOI: https://doi.org/10.1016/j.laa.2012.10.036]\n///\ntemplate <typename T>\nclass ESPRIT\n{\npublic:\n    using Scalar        = T;\n    using RealScalar    = typename Eigen::NumTraits<Scalar>::Real;\n    using ComplexScalar = std::complex<RealScalar>;\n    using Index         = Eigen::Index;\n\n    using Vector        = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using RealVector    = Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>;\n    using ComplexVector = Eigen::Matrix<ComplexScalar, Eigen::Dynamic, 1>;\n\n    using Matrix = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using RealMatrix =\n        Eigen::Matrix<RealScalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using ComplexMatrix =\n        Eigen::Matrix<ComplexScalar, Eigen::Dynamic, Eigen::Dynamic>;\n\n    using ResultType =\n        typename detail::gen_prony_like_method_result<T>::ResultType;\n\nprivate:\n    enum\n    {\n        IsComplex = Eigen::NumTraits<Scalar>::IsComplex,\n        Alignment = Eigen::internal::traits<Matrix>::Alignment\n    };\n\n    Index m_rows;\n    Index m_cols;\n    Index m_max_terms;\n    Matrix m_matH;\n\npublic:\n    ///\n    /// Default constructor\n    ///\n    ESPRIT() = default;\n\n    ///\n    /// Constructor with memory preallocation\n    ///\n    /// \\param[in] N  Number of sampling points\n    /// \\param[in] L  Window size. This is equals to the number of rows of\n    ///               generalized Hankel matrix.\n    /// \\param[in] M  Maxumum number of terms used for the exponential sum.\n    /// \\pre  `N >= M >= 1` and `N - L + 1 >= M >= 1`.\n    ///\n    ESPRIT(Index N, Index L, Index M)\n        : m_rows(L), m_cols(N - L + 1), m_max_terms(M), m_matH(m_rows, m_cols)\n    {\n        assert(m_rows >= M && m_cols >= M && M >= 1);\n    }\n\n    ///\n    /// Destructor\n    ///\n    ~ESPRIT()\n    {\n    }\n\n    ///\n    /// Memory reallocation\n    ///\n    /// \\param[in] N  Number of sampling points\n    /// \\param[in] L  Window size. This is equals to the number of rows of\n    ///               generalized Hankel matrix.\n    /// \\param[in] M  Maxumum number of terms used for the exponential sum.\n    /// \\pre  `N >= M >= 1` and `N - L + 1 >= M >= 1`.\n    ///\n    void resize(Index N, Index L, Index M)\n    {\n        m_rows = L;\n        m_cols = N - L + 1;\n        assert(m_rows >= M && m_cols >= M && M >= 1);\n        m_max_terms = M;\n        m_matH.resize(m_rows, m_cols);\n    }\n\n    ///\n    /// \\return Number of sampling points.\n    ///\n    Index size() const\n    {\n        return m_rows + m_cols - 1;\n    }\n\n    ///\n    /// Fit signals by a exponential sum\n    ///\n    /// \\param[in] f The array of signals sampled on the equispaced grid. The\n    ///    first `size()` elemnets of `nterms` are used as a sampled data. In\n    ///    case `f.size() < size()` then, last `size() - f.size()` elements are\n    ///    padded by zeros.\n    /// \\param[in] eps  Small positive number `(0 < eps < 1)` that\n    ///    controlls the accuracy of the fit.\n    /// \\param[in] x0  Argument of first sampling point\n    /// \\param[in] delta Spacing between neighboring sample points.\n    ///\n    template <typename VectorT>\n    ResultType compute(const Eigen::MatrixBase<VectorT>& h, RealScalar x0,\n                       RealScalar delta, RealScalar eps);\n};\n\ntemplate <typename T>\ntemplate <typename VectorT>\ntypename ESPRIT<T>::ResultType\nESPRIT<T>::compute(const Eigen::MatrixBase<VectorT>& h, RealScalar x0,\n                   RealScalar delta, RealScalar eps)\n{\n    assert(h.size() == size() && \"Number of data points mismatch.\");\n    //\n    // Form rectangular Hankel matrix from sequance h.\n    //\n    for (Index j = 0; j < m_cols; ++j)\n    {\n        for (Index i = 0; i < m_rows; ++i)\n        {\n            m_matH.coeffRef(i, j) = h(i + j);\n        }\n    }\n    // const Index nr = m_matH.rows();\n    const Index nc = m_matH.cols();\n\n    //-------------------------------------------------------------------------\n    // Compute roots of Prony polynomials H = U * S * W^H\n    //-------------------------------------------------------------------------\n    Eigen::BDCSVD<Matrix> svd(m_matH, Eigen::ComputeThinV);\n\n    const auto& sigma = svd.singularValues();\n    Index nterms      = 0;\n    // extract rank of matrix H from singular values\n    while (nterms < m_max_terms)\n    {\n        if (sigma(nterms) < eps)\n        {\n            break;\n        }\n        ++nterms;\n    }\n\n    if (nterms == 0)\n    {\n        return ResultType();\n    }\n\n    ComplexVector roots(nterms);\n    ComplexVector weights(nterms);\n\n    {\n        // --- Form the views of matrix W\n        // Matrix W excluding the last row\n        auto W0 = svd.matrixV().block(0, 0, nc - 1, nterms);\n        // Matrix W excluding the first row\n        auto W1 = svd.matrixV().block(1, 0, nc - 1, nterms);\n        // adjoint of the last row of matrix W\n        auto nu = svd.matrixV().block(nc - 1, 0, 1, nterms).adjoint();\n        //\n        // Compute the spectral matrix G = pinv(W0) * W1, where pinv indicate\n        // the Moore-Penrose pseudo-inverse. The computation of the\n        // pseudo-inverse of W0 can be avoided.\n        //\n        Matrix G(W0.adjoint() * W1);\n        Vector phi(G.adjoint() * nu);\n        auto scal = RealScalar(1) / (RealScalar(1) - nu.squaredNorm());\n        G += scal * nu * phi.adjoint();\n        //\n        // Prony roots \\f$\\{z_i\\{\\}\\f$ are the eigenvalues of matrix G. The\n        // exponents for approximation are obtained as \\f$ \\log z_i \\f$\n        //\n        roots = G.eigenvalues();\n    }\n\n    //----------------------------------------------------------------------\n    // Solve overdetermined Vandermonde system to obtain the weights\n    //----------------------------------------------------------------------\n    {\n        // Create Vandermonde matrix from prony roots\n        ComplexMatrix matV(h.size(), nterms);\n        for (Index j = 0; j < matV.cols(); ++j)\n        {\n            auto x     = roots(j);\n            auto v     = ComplexScalar(1);\n            matV(0, j) = v;\n            for (Index i = 1; i < matV.rows(); ++i)\n            {\n                v *= x;\n                matV(i, j) = v;\n            }\n        }\n        // Solve least-squares problem V x = h\n        weights = matV.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV)\n                      .solve(h.template cast<ComplexScalar>());\n    }\n\n    // Rescale the exponents and weights, and return the result\n    return detail::gen_prony_like_method_result<T>::create(\n        roots.array(), weights.array(), x0, delta);\n}\n\n} // namespace mxpfit\n\n#endif /* MXPFIT_ESPRIT_HPP */\n", "meta": {"hexsha": "3d3679307bcbbb805bc24285a853472448c381db", "size": 8849, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/esprit.hpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "include/mxpfit/esprit.hpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "include/mxpfit/esprit.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4139194139, "max_line_length": 80, "alphanum_fraction": 0.5858289072, "num_tokens": 2233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4429149320596691}}
{"text": "#pragma once\n\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <iostream>\n\nnamespace boltzmann {\n\ntemplate <int dim, typename InVector>\ndouble\ncompute_mean_value(const dealii::DoFHandler<dim>& dh, const InVector& v)\n{\n  dealii::QGauss<dim> quad(2);\n  return dealii::VectorTools::compute_mean_value(dh, quad, v, 0);\n}\n\nnamespace mpi {\n\ntemplate <int dim>\nstd::vector<double>\ncompute_mean_value(const dealii::DoFHandler<dim>& dh, const Epetra_MultiVector& src)\n{\n  unsigned int pid = dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);\n  dealii::QGauss<dim> quad(2);\n  dealii::UpdateFlags flags =\n      dealii::update_values | dealii::update_JxW_values | dealii::update_quadrature_points;\n  dealii::FEValues<dim> fe_values(dh.get_fe(), quad, flags);\n\n  int nvec = src.NumVectors();\n\n  std::vector<double> lsum(nvec, 0.0);\n\n  unsigned int dofs_per_cell = fe_values.dofs_per_cell;\n  std::vector<unsigned int> local_dof_indices(dofs_per_cell);\n  for (auto cell = dh.begin_active(); cell != dh.end(); ++cell) {\n    if (cell->subdomain_id() == pid) {\n      fe_values.reinit(cell);\n      cell->get_dof_indices(local_dof_indices);\n      for (int k = 0; k < nvec; ++k) {\n        for (unsigned int ix = 0; ix < dofs_per_cell; ++ix) {\n          int lid = src.Map().LID(int(local_dof_indices[ix]));\n          BOOST_ASSERT(lid >= 0);\n          // if (lid < 0) std::cout << \"lid \" << lid << \" gid \" << local_dof_indices[ix] << \"\\n\";\n          for (unsigned int q = 0; q < quad.size(); ++q) {\n            lsum[k] += src[k][lid] * fe_values.shape_value(ix, q) * fe_values.JxW(q);\n          }\n        }\n      }\n    }\n  }\n\n  std::vector<double> sum(nvec, 0.0);\n  MPI_Allreduce(lsum.data(), sum.data(), nvec, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n  return sum;\n}\n}  // namespace mpi\n\n}  // namespace boltzmann\n", "meta": {"hexsha": "97fd2e5e7e719c56da25c651efe2185c6ed70c3b", "size": 1910, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/post_processing/compute_mean_value.hpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/post_processing/compute_mean_value.hpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/post_processing/compute_mean_value.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3114754098, "max_line_length": 97, "alphanum_fraction": 0.6554973822, "num_tokens": 566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.44285203088788716}}
{"text": "/*!\n  @file main.cpp\n  @author Klaus K. Holst\n  @copyright 2018-2021, Klaus Kähler Holst\n\n  @brief Example file\n\n*/\n\n#include <armadillo>\n#include <cstdio>  // remove\n#include <algorithm>  // max\n#include <target/target.hpp>\n#include <target/utils.hpp>\n\nusing namespace arma;\n\nint main(int argc, char **argv) {\n  vec y, w, p;\n  mat a, x1, x2;\n  if (argc == 1) {\n    std::cout << \"* Simulating data...\\n\\n\";\n    arma_rng::set_seed(1);\n    unsigned n = 5;\n    y = vec(n, 1);\n    y.randn();\n    w = mat(n, 1);\n    w.fill(1);\n    a = randi<mat>(n, 1, distr_param(0, 1));\n    x2 = mat(n, 2);\n    x2.randn();\n    x1 = mat(n, 1);\n    x1.fill(1);\n    p = vec(4);\n    p.fill(0.5);\n  } else {\n    const char *infile = argv[1];\n    std::cout << \"* Reading from '\" << infile << \"'\\n\\n\";\n  }\n\n  unsigned n = std::min(3, (int)y.n_elem);\n  std::cout << \" Response:\\n\"\n            << target::BLUE << y.rows(0, n - 1)\n            << \"\\t...\" << target::COL_RESET\n            << std::endl;\n  std::cout << \" Exposure:\\n\"\n            << target::CYAN << a.rows(0, n - 1)\n            << \"\\t...\" << target::COL_RESET\n            << std::endl;\n  std::cout << \" X1:\\n\"\n            << target::YELLOW << x1.rows(0, n - 1) << \"\\t...\"\n            << target::COL_RESET << std::endl;\n  std::cout << \" X2:\\n\"\n            << target::YELLOW << x2.rows(0, n - 1) << \"\\t...\"\n            << target::COL_RESET << std::endl;\n  std::cout << \"\\n parameter: \" << target::GREEN << p.t()\n            << target::COL_RESET\n            << std::endl;\n\n  target::RD<double> model(y, a, x1, x2, x2, p, w);\n  vec res = model.loglik();\n  std::cout << \" loglik=\\n\"\n            << target::RED << res << std::endl\n            << target::COL_RESET;\n\n  mat U = model.score(true);\n  std::cout << \" score=\\n\"\n            << target::RED << U << std::endl\n            << target::COL_RESET;\n\n  arma::vec alpha2(1); alpha2.fill(1);\n  U = model.est(alpha2);\n  std::cout << \" U=\\n\" << target::RED << U <<\n    std::endl << target::COL_RESET;\n\n  //arma::mat pp = model.target::TargetBinary<double>::pa();\n  //std::cout << \"pp=\\n\" << pp << std::endl;\n  // const char *filen = \"tmp/a.h5\";\n  // std::remove(filen);\n  // y.save(hdf5_name(filen, \"y\", hdf5_opts::append+hdf5_opts::trans));\n  // a.save(hdf5_name(filen, \"a\", hdf5_opts::append+hdf5_opts::trans));\n  // w.save(hdf5_name(filen, \"w\", hdf5_opts::append+hdf5_opts::trans));\n  // x1.save(hdf5_name(filen, \"x1\", hdf5_opts::append+hdf5_opts::trans));\n  // x2.save(hdf5_name(filen, \"x2\", hdf5_opts::append+hdf5_opts::trans));\n  // p.save(hdf5_name(filen, \"p\", hdf5_opts::append+hdf5_opts::trans));\n\n  return 0;\n}\n", "meta": {"hexsha": "53b486ccd4a8deb25166f2ff6ab08aa8d7251737", "size": 2595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/dredemo.cpp", "max_stars_repo_name": "kkholst/target", "max_stars_repo_head_hexsha": "a63f3121efeae2c3441d7d2d2261fdf85038868e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-17T19:01:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T19:01:21.000Z", "max_issues_repo_path": "misc/dredemo.cpp", "max_issues_repo_name": "kkholst/target", "max_issues_repo_head_hexsha": "a63f3121efeae2c3441d7d2d2261fdf85038868e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/dredemo.cpp", "max_forks_repo_name": "kkholst/target", "max_forks_repo_head_hexsha": "a63f3121efeae2c3441d7d2d2261fdf85038868e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1573033708, "max_line_length": 73, "alphanum_fraction": 0.523699422, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4428520243420016}}
{"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <cstdlib>\n#include <time.h>\n#include <math.h>\n#include <dirent.h>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <string>\n#include <algorithm>\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/algorithm/string/replace.hpp>\n#include <boost/math/distributions/normal.hpp>\n\n#include \"opencv2/opencv.hpp\"\n#include \"opencv2/core/core.hpp\"\n#include \"opencv2/features2d/features2d.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include \"opencv2/imgproc/imgproc.hpp\"\n#include \"opencv2/calib3d/calib3d.hpp\"\n#include \"opencv2/nonfree/features2d.hpp\"\n#include \"opencv2/flann/flann.hpp\"\n\n#include \"FastEMD/emd_hat.hpp\"\n#include \"FastEMD/emd_hat_signatures_interface.hpp\"\n#include \"RubnerEMD/emd.hpp\"\n#include \"FastEMD/tictoc.hpp\"\n\nusing namespace cv;\nusing namespace std;\n\nnamespace fs = boost::filesystem;\n\n#define IMAGE_WIDTH 1000\n\n// TODO: config\n/* CONFIGURATIONS */\nint keypoint_filter_threshold = 1;\nbool filter_kp = 0;\nint sort_type = -1;\nbool show_images = 0;\n/* END CONFIGURATIONS */\n\nvoid help();\nvoid find_images(const char *path);\nvoid print_progress(time_t start, int total, int& completed, int per_cout);\nvoid print_keypoints(const vector<KeyPoint>& kp);\n\nbool extract_descriptors(int index, int fc, vector<KeyPoint>& kps, Mat& descs);\nvoid select_keypoints(vector<KeyPoint>& k, vector<KeyPoint>& s, int fc);\nvoid filter_keypoints(vector<KeyPoint>& k, vector<KeyPoint>& f);\nvoid calc_response_density_img(const Mat& img, vector<KeyPoint> kp, Mat& ds);\nvoid calc_reponse_response_density_space(const vector<KeyPoint>& kp);\nvoid calc_scale_density_img(const Mat& img, vector<KeyPoint> kp, Mat& ds);\nvoid calc_scale_response_density_space(const vector<KeyPoint>& kp);\nfloat keypoint_dist(const KeyPoint& k1, const KeyPoint& k2);\nfloat point_dist(const Point2f& p1, const Point2f& p2);\nbool response_comparator(const KeyPoint& p1, const KeyPoint& p2);\nfloat get_density(const KeyPoint& k);\nbool density_comparator(const KeyPoint& p1, const KeyPoint& p2);\nfloat get_scale_density(const KeyPoint& k);\nbool scale_density_comparator(const KeyPoint& p1, const KeyPoint& p2);\nbool scale_comparator(const KeyPoint& p1, const KeyPoint& p2);\n\nvector<fs::path> img_paths;\n\nfloat response_density_space[IMAGE_WIDTH][IMAGE_WIDTH];\nfloat scale_response_density_space[IMAGE_WIDTH][IMAGE_WIDTH];\nMat current_img;\n\nvector<KeyPoint> filtered_keypoints;\nstruct response_density_classcomp {\n\tbool operator()(const int& lhs, const int& rhs) const {\n\t\tKeyPoint kp1, kp2;\n\t\tkp1 = filtered_keypoints[lhs];\n\t\tkp2 = filtered_keypoints[rhs];\n\t\treturn density_comparator(kp1, kp2);\n\t}\n};\nstruct scale_response_density_classcomp {\n\tbool operator()(const int& lhs, const int& rhs) const {\n\t\tKeyPoint kp1, kp2;\n\t\tkp1 = filtered_keypoints[lhs];\n\t\tkp2 = filtered_keypoints[rhs];\n\t\treturn scale_density_comparator(kp1, kp2);\n\t}\n};\n\nint main(int argc, char *argv[]) {\n\tif (argc < 4) {\n\t\thelp();\n\t\treturn -1;\n\t}\n\n\tint fc = atoi(argv[1]);\n\tsort_type = atoi(argv[2]);\n\tconst char *imgs_path = argv[3];\n\tconst char *index_path = argv[4];\n\n\tcout << \"Reading image paths from \" << imgs_path << endl;\n\tstring img_path;\n\tint img_count;\n\tifstream imgs_file(imgs_path);\n\timgs_file >> img_count;\n\tfor (int i = 0; i < img_count; ++i) {\n\t\timgs_file >> img_path;\n\t\timg_paths.push_back(img_path);\n\t}\n\tcout << img_count << \" images found\" << endl;\n\n\tint total_process = img_count;\n\tint completed_process = 0;\n\ttime_t start = time(0);\n\n\tcout << \"Building index...\" << endl;\n\n\ttictoc timer;\n\ttimer.tic();\n\n\tvector<KeyPoint> kps;\n\tMat descs;\n\tFileStorage fs(index_path, FileStorage::WRITE);\n\tfs << \"index\" << \"[\";\n\tfor (int i = 0; i < img_count; ++i) {\n\t\tif (extract_descriptors(i, fc, kps, descs)) {\n\t\t\tfs << \"{\";\n\t\t\tfs << \"path\" << img_paths[i].string();\n\t\t\tfs << \"keypoints\" << kps;\n\t\t\tfs << \"descriptors\" << descs;\n\t\t\tfs << \"}\";\n\t\t}\n\t}\n\tfs << \"]\";\n\tfs.release();\n\n\ttimer.toc();\n\tcout << \"Time in seconds: \" << timer.totalTimeSec() << endl;\n\n\treturn 0;\n}\n\nvoid help() {\n\tcout << \"Usage: ./build_index <fc> <sort_type> <imgs_path> <index_path>\" << endl;\n}\n\nvoid print_progress(time_t start, int total, int& completed, int per_count) {\n\t++completed;\n\tif (completed % per_count != 0)\n\t\treturn;\n\tint remaining_process = total - completed;\n\ttime_t current = time(0);\n\tfloat elapsed_time = difftime(current, start);\n\tfloat remaining_time = elapsed_time * remaining_process / completed;\n\tcout << fixed << setprecision(3);\n\tcout << \"\\rRemaining time: \";\n\tcout << remaining_time / 60 << \"min\";\n}\n\nvoid print_keypoints(const vector<KeyPoint>& kp) {\n\tKeyPoint k;\n\tcout << setprecision(3) << fixed;\n\tfor (int i = 0; i < (int) kp.size(); ++i) {\n\t\tk = kp[i];\n\t\tcout << \"(\" << k.pt.x << \"\\t\" << k.pt.y << \"):\\t\" << k.response << \"\\t\" << k.size << \"\\t\" << get_scale_density(k) << endl;\n\t}\n}\n\nvoid find_images(const char *path) {\n\tfs::path dir_path(path);\n\tfs::recursive_directory_iterator end_iter;\n\n\tfor (fs::recursive_directory_iterator iter(dir_path); iter != end_iter; ++iter) {\n\t\tif (fs::is_regular_file(iter->status())) {\n\t\t\tif (!boost::algorithm::ends_with(iter->path().c_str(), \".png\"))\n\t\t\t\tcontinue;\n\t\t\timg_paths.push_back(iter->path());\n\t\t}\n\t}\n\n\tsort(img_paths.begin(), img_paths.end());\n}\n\nbool extract_descriptors(int index, int fc, vector<KeyPoint>& kps, Mat& descs) {\n\tstring img_path = img_paths[index].string();\n\tfs::path yaml = img_paths[index];\n\tstring yaml_path = yaml.replace_extension(\".yml\").string();\n\t\n\t// cout << \"Calc img matrix: \" << img_path << endl;\n\tcurrent_img = imread(img_path.c_str(), CV_LOAD_IMAGE_GRAYSCALE);\n\n\tif (!current_img.data) {\n\t\tcout << \"Error reading image: \" << img_path << endl;\n\t\treturn 0;\n\t}\n\n\tvector<KeyPoint> keypoints;\n\tif (fs::exists(yaml_path)) {\n\t\tFileStorage fs(yaml_path.c_str(), FileStorage::READ);\n\t\tread(fs[\"keypoints\"], keypoints);\n\t} else {\n\t\tSiftFeatureDetector detector;\n\t\tdetector.detect(current_img, keypoints);\n\t\tFileStorage fs(yaml_path.c_str(), FileStorage::WRITE);\n\t\tfs << \"keypoints\" << keypoints;\n\t}\n\t// print_keypoints(keypoints);\n\n\t// int fc = keypoints.size() * fc / 100;\n\t// fc = fc > 10 ? fc : 10;\n\n\t// not enough feature, dont use them\n\tif (keypoints.size() == 0) {\n\t\tcout << \"Image \" << img_path << \" has no feature\" << endl;\n\t\treturn 0;\n\t}\n\n\tvector<KeyPoint> selected_keypoints;\n\tif (fc == 0) {\n\t\tselected_keypoints = keypoints;\n\t} else {\n\t\tselect_keypoints(keypoints, selected_keypoints, fc);\n\t}\n\n\tcout << setw(50) << left << img_path\n\t\t\t<< setw(10) << right << keypoints.size()\n\t\t\t<< setw(10) << selected_keypoints.size() << endl;\n\n\t// extract descriptors\n\tMat descriptors;\n\tSiftDescriptorExtractor extractor;\n\textractor.compute(current_img, selected_keypoints, descriptors);\n\n\t// cout << img_path << \":\" << endl;\n\t// print_keypoints(selected_keypoints);\n\t// cout << descriptors << endl;\n\n\tif (show_images) {\n\t\tMat white = Mat::ones(current_img.rows, current_img.cols, CV_8UC1) * 255;\n\t\tMat black = Mat::zeros(current_img.rows, current_img.cols, CV_8UC1);\n\t\tMat img_density = Mat::zeros(current_img.rows, current_img.cols, CV_8UC1);\n\t\tMat img(current_img);\n\n\t\tdrawKeypoints(current_img, keypoints, img, Scalar::all(-1), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);\n\t\timshow(\"kp_on_img\", img);\n\n\t\tdrawKeypoints(black, keypoints, img, Scalar::all(-1), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);\n\t\timshow(\"kp_on_black\", img);\n\t\t\n\t\tdrawKeypoints(black, selected_keypoints, img, Scalar::all(-1), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);\n\t\timshow(\"selected_kp_on_white\", img);\n\n\t\tcalc_scale_density_img(current_img, keypoints, img_density);\n\t\timshow(\"density\", img_density);\n\n\t\tdrawKeypoints(img_density, selected_keypoints, img, Scalar::all(-1), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);\n\t\timshow(\"selected_kp_on_density\", img);\n\n\t\timshow(\"img\", current_img);\n\t\twaitKey(0);\n\t}\n\n\tdescs = descriptors;\n\tkps = selected_keypoints;\n\treturn 1;\n}\n\nvoid select_keypoints(vector<KeyPoint>& k, vector<KeyPoint>& s, int fc) {\n\t// filter keypoints\n\tfiltered_keypoints.clear();\n\tif (filter_kp) {\n\t\tfilter_keypoints(k, filtered_keypoints);\n\t} else {\n\t\tfiltered_keypoints = k;\n\t}\n\tint filtered_kp_size = filtered_keypoints.size();\n\n\tif (sort_type == -5) { // scale + scale density\n\t\tsort(filtered_keypoints.begin(), filtered_keypoints.end(), scale_comparator);\n\t\tvector<KeyPoint> scale_selected;\n\t\tfor (int i = 0; i < 2 * fc && i < filtered_kp_size; ++i) {\n\t\t\tscale_selected.push_back(filtered_keypoints[i]);\n\t\t}\n\t\tcalc_scale_response_density_space(scale_selected);\n\t\tsort(scale_selected.begin(), scale_selected.end(), scale_density_comparator);\n\t\tfor (int i = 0; i < fc && i < filtered_kp_size; ++i) {\n\t\t\ts.push_back(scale_selected[i]);\n\t\t}\n\t} else if (sort_type == -4) { // scale density with substrating\n\t\tcalc_scale_response_density_space(filtered_keypoints);\n\t\tsort(filtered_keypoints.begin(), filtered_keypoints.end(), scale_density_comparator);\n\n\t\tfor (int i = 0; i < fc && i < filtered_kp_size; ++i) {\n\t\t\tKeyPoint keypoint = filtered_keypoints[0];\n\t\t\ts.push_back(keypoint);\n\n\t\t\t// subtract the contribution of this keypoint\n\t\t\tfor (int j = 0; j < filtered_kp_size; j++) {\n\t\t\t\tKeyPoint kp = filtered_keypoints[i];\n\t\t\t\tfloat dist = keypoint_dist(kp, keypoint);\n\t\t\t\tboost::math::normal_distribution<> norm_dist(0.0, 1 / keypoint.size);\n\t\t\t\tfloat density = boost::math::pdf(norm_dist, dist);\n\t\t\t\tint x = kp.pt.x;\n\t\t\t\tint y = kp.pt.y;\n\t\t\t\tscale_response_density_space[x][y] -= density;\n\t\t\t}\n\n\t\t\t// delete the selected keypoint\n\t\t\tfiltered_keypoints.erase(filtered_keypoints.begin());\n\t\t\t// resort\n\t\t\tsort(filtered_keypoints.begin(), filtered_keypoints.end(), scale_density_comparator);\n\t\t}\n\t} else if (sort_type == -3) { // scale density with kdtree\n\t\tcalc_scale_response_density_space(filtered_keypoints);\n\n\t\t// create keypoint map for easy deletion\n\t\tmap<int, KeyPoint, scale_response_density_classcomp> mk;\n\t\tmap<int, KeyPoint>::iterator it;\n\n\t\t// create kd-tree index\n\t\tMat coord = Mat::zeros(filtered_kp_size, 2, CV_32F);\n\t\tfor (int i = 0; i < filtered_kp_size; ++i) {\n\t\t\tmk[i] = filtered_keypoints[i];\n\t\t\tcoord.ptr<float>(i)[0] = filtered_keypoints[i].pt.x;\n\t\t\tcoord.ptr<float>(i)[1] = filtered_keypoints[i].pt.y;\n\t\t}\n\t\t\n\t\tflann::Index kdtree_index(coord, flann::KDTreeIndexParams(4));\n\n\t\tint max_count = 100;\n\t\tMat indices = Mat::zeros(1, max_count, CV_32F);\n\t\tMat dists = Mat::zeros(1, max_count, CV_32F);\n\n\t\tfor (int i = 0; i < fc && i < filtered_kp_size; ++i) {\n\t\t\tif (mk.size() == 0)\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tKeyPoint query_keypoint = mk.begin()->second;\n\n\t\t\ts.push_back(query_keypoint);\n\n\t\t\tMat query = Mat::zeros(1, 2, CV_32F);\n\t\t\tquery.ptr<float>(0)[0] = query_keypoint.pt.x;\n\t\t\tquery.ptr<float>(0)[1] = query_keypoint.pt.y;\n\t\t\tfloat radius = query_keypoint.size * query_keypoint.size / 4;\n\t\t\tint found_count = kdtree_index.radiusSearch(query, indices, dists, radius, max_count, flann::SearchParams());\n\t\t\tfor (int j = 0; j < found_count; ++j) {\n\t\t\t\tmk.erase(indices.at<int>(j));\n\t\t\t}\n\t\t}\n\t} else if (sort_type == -2) { // scale density\n\t\tcalc_scale_response_density_space(filtered_keypoints);\n\t\tsort(filtered_keypoints.begin(), filtered_keypoints.end(), scale_density_comparator);\n\t\tfor (int i = 0; i < fc && i < filtered_kp_size; ++i) {\n\t\t\ts.push_back(filtered_keypoints[i]);\n\t\t}\n\t} else if (sort_type == -1) { // scale\n\t\tsort(filtered_keypoints.begin(), filtered_keypoints.end(), scale_comparator);\n\t\tfor (int i = 0; i < fc && i < filtered_kp_size; ++i) {\n\t\t\ts.push_back(filtered_keypoints[i]);\n\t\t}\n\t} else if (sort_type == 1) { // response\n\t\tsort(filtered_keypoints.begin(), filtered_keypoints.end(), response_comparator);\n\t\tfor (int i = 0; i < fc && i < filtered_kp_size; ++i) {\n\t\t\ts.push_back(filtered_keypoints[i]);\n\t\t}\n\t} else if (sort_type == 2) { // response density\n\t\tcalc_reponse_response_density_space(filtered_keypoints);\n\t\tsort(filtered_keypoints.begin(), filtered_keypoints.end(), density_comparator);\n\t\tfor (int i = 0; i < fc && i < filtered_kp_size; ++i) {\n\t\t\ts.push_back(filtered_keypoints[i]);\n\t\t}\n\t} else if (sort_type == 3) { // response density with kdtree\n\t\tcalc_reponse_response_density_space(filtered_keypoints);\n\n\t\t// create keypoint map for easy deletion\n\t\tmap<int, KeyPoint, response_density_classcomp> mk;\n\t\tmap<int, KeyPoint>::iterator it;\n\n\t\t// create kd-tree index\n\t\tMat coord = Mat::zeros(filtered_kp_size, 2, CV_32F);\n\t\tfor (int i = 0; i < filtered_kp_size; ++i) {\n\t\t\tmk[i] = filtered_keypoints[i];\n\t\t\tcoord.ptr<float>(i)[0] = filtered_keypoints[i].pt.x;\n\t\t\tcoord.ptr<float>(i)[1] = filtered_keypoints[i].pt.y;\n\t\t}\n\t\t\n\t\tflann::Index kdtree_index(coord, flann::KDTreeIndexParams(4));\n\n\t\tint max_count = 100;\n\t\tMat indices = Mat::zeros(1, max_count, CV_32F);\n\t\tMat dists = Mat::zeros(1, max_count, CV_32F);\n\n\t\tfor (int i = 0; i < fc && i < filtered_kp_size; ++i) {\n\t\t\tif (mk.size() == 0)\n\t\t\t\tbreak;\n\n\t\t\tKeyPoint query_keypoint = mk.begin()->second;\n\n\t\t\ts.push_back(query_keypoint);\n\n\t\t\tMat query = Mat::zeros(1, 2, CV_32F);\n\t\t\tquery.ptr<float>(0)[0] = query_keypoint.pt.x;\n\t\t\tquery.ptr<float>(0)[1] = query_keypoint.pt.y;\n\t\t\tfloat radius = query_keypoint.size * query_keypoint.size / 4;\n\t\t\tint found_count = kdtree_index.radiusSearch(query, indices, dists, radius, max_count, flann::SearchParams());\n\t\t\tfor (int j = 0; j < found_count; ++j) {\n\t\t\t\tmk.erase(indices.at<int>(j));\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid filter_keypoints(vector<KeyPoint>& k, vector<KeyPoint>& f) {\n\tif (sort_type < 0)\n\t\tsort(k.begin(), k.end(), scale_comparator);\n\telse\n\t\tsort(k.begin(), k.end(), response_comparator);\n\n\tfor (int i = k.size() - 1; i >= 0; --i) {\n\t\tKeyPoint k1 = k[i];\n\t\tbool add = 1;\n\t\tfor (int j = 0; j < f.size(); ++j) {\n\t\t\tKeyPoint k2 = f[j];\n\t\t\tfloat dist = keypoint_dist(k1, k2);\n\t\t\tif (dist < keypoint_filter_threshold) {\n\t\t\t\tadd = 0;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (add)\n\t\t\tf.push_back(k1);\n\t}\n}\n\nvoid calc_response_density_img(const Mat& img, vector<KeyPoint> kp, Mat& ds) {\n\tint rows = img.rows;\n\tint cols = img.cols;\n\tint size = kp.size();\n\tMat tmp = Mat::zeros(rows, cols, CV_32F);\n\n\tfloat max_value = 0, min_value = 9999999;\n\tfor (int i = 0; i < cols; i++) {\n\t\tfor (int j = 0; j < rows; j++) {\n\t\t\tfloat sum = 0;\n\t\t\tfor (int k = 0; k < size; k++) {\n\t\t\t\tKeyPoint p = kp[k];\n\t\t\t\tfloat dist = sqrt(pow(i - p.pt.x, 2) + pow(j - p.pt.y, 2));\n\t\t\t\tboost::math::normal_distribution<> norm_dist(0.0, 1 / p.response * 100);\n\t\t\t\tsum += boost::math::pdf(norm_dist, dist);\n\t\t\t}\n\t\t\ttmp.ptr<float>(j)[i] = sum;\n\t\t\tif (sum > max_value)\n\t\t\t\tmax_value = sum;\n\t\t\tif (sum < min_value)\n\t\t\t\tmin_value = sum;\n\t\t}\n\t}\n\n\tds = Mat(rows, cols, CV_8UC1);\n\tfor (int i = 0; i < cols; i++) {\n\t\tfor (int j = 0; j < rows; j++) {\n\t\t\tds.at<uchar>(j, i) = (tmp.at<float>(j, i) - min_value) / (max_value - min_value) * 255;\n\t\t}\n\t}\n\n\tequalizeHist(ds, ds);\n}\n\nvoid calc_reponse_response_density_space(const vector<KeyPoint>& kp) {\n\tint kp_size = kp.size();\n\tfor (int i = 0; i < kp_size; i++) {\n\t\tKeyPoint ki = kp[i];\n\t\tfloat density = 0;\n\t\tfor (int j = 0; j < kp_size; j++) {\n\t\t\tKeyPoint kj = kp[j];\n\t\t\tfloat dist = keypoint_dist(ki, kj);\n\t\t\tboost::math::normal_distribution<> norm_dist(0.0, 1 / kj.response * 100);\n\t\t\tdensity += boost::math::pdf(norm_dist, dist);\n\t\t}\n\t\tint x = ki.pt.x;\n\t\tint y = ki.pt.y;\n\t\tresponse_density_space[x][y] = density;\n\t}\n}\n\nvoid calc_scale_density_img(const Mat& img, vector<KeyPoint> kp, Mat& ds) {\n\tint rows = img.rows;\n\tint cols = img.cols;\n\tint size = kp.size();\n\tMat tmp = Mat::zeros(rows, cols, CV_32F);\n\n\tfloat max_value = 0, min_value = 9999999;\n\tfor (int i = 0; i < cols; i++) {\n\t\tfor (int j = 0; j < rows; j++) {\n\t\t\tfloat sum = 0;\n\t\t\tfor (int k = 0; k < size; k++) {\n\t\t\t\tKeyPoint p = kp[k];\n\t\t\t\tfloat dist = sqrt(pow(i - p.pt.x, 2) + pow(j - p.pt.y, 2));\n\t\t\t\tboost::math::normal_distribution<> norm_dist(0.0, 20 / p.size);\n\t\t\t\tsum += boost::math::pdf(norm_dist, dist);\n\t\t\t}\n\t\t\ttmp.ptr<float>(j)[i] = sum;\n\t\t\tif (sum > max_value)\n\t\t\t\tmax_value = sum;\n\t\t\tif (sum < min_value)\n\t\t\t\tmin_value = sum;\n\t\t}\n\t}\n\n\tds = Mat(rows, cols, CV_8UC1);\n\tfor (int i = 0; i < cols; i++) {\n\t\tfor (int j = 0; j < rows; j++) {\n\t\t\tds.at<uchar>(j, i) = (tmp.at<float>(j, i) - min_value) / (max_value - min_value) * 255;\n\t\t}\n\t}\n\n\tequalizeHist(ds, ds);\n}\n\nvoid calc_scale_response_density_space(const vector<KeyPoint>& kp) {\n\tint kp_size = kp.size();\n\tfor (int i = 0; i < kp_size; i++) {\n\t\tKeyPoint ki = kp[i];\n\t\tfloat density = 0;\n\t\tfor (int j = 0; j < kp_size; j++) {\n\t\t\tKeyPoint kj = kp[j];\n\t\t\tfloat dist = keypoint_dist(ki, kj);\n\t\t\tboost::math::normal_distribution<> norm_dist(0.0, 20 / kj.size);\n\t\t\tdensity += boost::math::pdf(norm_dist, dist);\n\t\t}\n\t\tint x = ki.pt.x;\n\t\tint y = ki.pt.y;\n\t\tscale_response_density_space[x][y] = density;\n\t}\n}\n\nfloat keypoint_dist(const KeyPoint& k1, const KeyPoint& k2) {\n\tfloat dist = point_dist(k1.pt, k2.pt);\n\treturn dist;\n}\n\nfloat point_dist(const Point2f& p1, const Point2f& p2) {\n\tfloat x_dist = p1.x - p2.x;\n\tfloat y_dist = p1.y - p2.y;\n\tfloat dist = sqrt(x_dist*x_dist + y_dist*y_dist);\n\treturn dist;\n}\n\nbool response_comparator(const KeyPoint& p1, const KeyPoint& p2) {\n\treturn p1.response > p2.response;\n}\n\nfloat get_density(const KeyPoint& k) {\n\tint x = k.pt.x;\n\tint y = k.pt.y;\n\treturn response_density_space[x][y];\n}\n\nbool density_comparator(const KeyPoint& p1, const KeyPoint& p2) {\n\treturn get_density(p1) > get_density(p2);\n}\n\nfloat get_scale_density(const KeyPoint& k) {\n\tint x = k.pt.x;\n\tint y = k.pt.y;\n\treturn scale_response_density_space[x][y];\n}\n\nbool scale_density_comparator(const KeyPoint& p1, const KeyPoint& p2) {\n\treturn get_scale_density(p1) > get_scale_density(p2);\n}\n\nbool scale_comparator(const KeyPoint& p1, const KeyPoint& p2) {\n\treturn p1.size > p2.size;\n}\n", "meta": {"hexsha": "c7f48c20a6b08d04b47a2d0a6900b550a508ede1", "size": 17560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "build_index.cpp", "max_stars_repo_name": "byildiz/feature-selection", "max_stars_repo_head_hexsha": "822484374b5a1a5ce385045e908148abfc4d2901", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "build_index.cpp", "max_issues_repo_name": "byildiz/feature-selection", "max_issues_repo_head_hexsha": "822484374b5a1a5ce385045e908148abfc4d2901", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "build_index.cpp", "max_forks_repo_name": "byildiz/feature-selection", "max_forks_repo_head_hexsha": "822484374b5a1a5ce385045e908148abfc4d2901", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.275862069, "max_line_length": 124, "alphanum_fraction": 0.6757972665, "num_tokens": 5209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645725, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4428124673748186}}
{"text": "#include <Eigen/Core>\n#include <filesystem/resolver.h>\n#include <fstream>\n#include <nori/integrator.h>\n#include <nori/ray.h>\n#include <nori/scene.h>\n#include <random>\n#include <sh/default_image.h>\n#include <sh/spherical_harmonics.h>\n#include <stb_image.h>\n\nNORI_NAMESPACE_BEGIN\n\nnamespace ProjEnv\n{\n    std::vector<std::unique_ptr<float[]>>\n    LoadCubemapImages(const std::string &cubemapDir, int &width, int &height,\n                      int &channel)\n    {\n        std::vector<std::string> cubemapNames{\"negx.jpg\", \"posx.jpg\", \"posy.jpg\",\n                                              \"negy.jpg\", \"posz.jpg\", \"negz.jpg\"};\n        std::vector<std::unique_ptr<float[]>> images(6);\n        for (int i = 0; i < 6; i++)\n        {\n            std::string filename = cubemapDir + \"/\" + cubemapNames[i];\n            int w, h, c;\n            float *image = stbi_loadf(filename.c_str(), &w, &h, &c, 3);\n            if (!image)\n            {\n                std::cout << \"Failed to load image: \" << filename << std::endl;\n                exit(-1);\n            }\n            if (i == 0)\n            {\n                width = w;\n                height = h;\n                channel = c;\n            }\n            else if (w != width || h != height || c != channel)\n            {\n                std::cout << \"Dismatch resolution for 6 images in cubemap\" << std::endl;\n                exit(-1);\n            }\n            images[i] = std::unique_ptr<float[]>(image);\n            int index = (0 * 128 + 0) * channel;\n            // std::cout << images[i][index + 0] << \"\\t\" << images[i][index + 1] << \"\\t\"\n            //           << images[i][index + 2] << std::endl;\n        }\n        return images;\n    }\n\n    const Eigen::Vector3f cubemapFaceDirections[6][3] = {\n        {{0, 0, 1}, {0, -1, 0}, {-1, 0, 0}},  // negx\n        {{0, 0, 1}, {0, -1, 0}, {1, 0, 0}},   // posx\n        {{1, 0, 0}, {0, 0, -1}, {0, -1, 0}},  // negy\n        {{1, 0, 0}, {0, 0, 1}, {0, 1, 0}},    // posy\n        {{-1, 0, 0}, {0, -1, 0}, {0, 0, -1}}, // negz\n        {{1, 0, 0}, {0, -1, 0}, {0, 0, 1}},   // posz\n    };\n\n    float CalcPreArea(const float &x, const float &y)\n    {\n        return std::atan2(x * y, std::sqrt(x * x + y * y + 1.0));\n    }\n\n    float CalcArea(const float &u_, const float &v_, const int &width,\n                   const int &height)\n    {\n        // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]\n        // ( 0.5 is for texel center addressing)\n        float u = (2.0 * (u_ + 0.5) / width) - 1.0;\n        float v = (2.0 * (v_ + 0.5) / height) - 1.0;\n\n        // shift from a demi texel, mean 1.0 / size  with u and v in [-1..1]\n        float invResolutionW = 1.0 / width;\n        float invResolutionH = 1.0 / height;\n\n        // u and v are the -1..1 texture coordinate on the current face.\n        // get projected area for this texel\n        float x0 = u - invResolutionW;\n        float y0 = v - invResolutionH;\n        float x1 = u + invResolutionW;\n        float y1 = v + invResolutionH;\n        float angle = CalcPreArea(x0, y0) - CalcPreArea(x0, y1) -\n                      CalcPreArea(x1, y0) + CalcPreArea(x1, y1);\n\n        return angle;\n    }\n\n    // template <typename T> T ProjectSH() {}\n\n    template <size_t SHOrder>\n    std::vector<Eigen::Array3f> PrecomputeCubemapSH(const std::vector<std::unique_ptr<float[]>> &images,\n                                                    const int &width, const int &height,\n                                                    const int &channel)\n    {\n        /// cubemapDirs，保存了cubemap 6张贴图上每个像素对应的单位向量\n        std::vector<Eigen::Vector3f> cubemapDirs;\n        cubemapDirs.reserve(6 * width * height);\n\n        /// 写入cubemapDirs\n        for (int i = 0; i < 6; i++)\n        {\n            Eigen::Vector3f faceDirX = cubemapFaceDirections[i][0];\n            Eigen::Vector3f faceDirY = cubemapFaceDirections[i][1];\n            Eigen::Vector3f faceDirZ = cubemapFaceDirections[i][2];\n            for (int y = 0; y < height; y++)\n            {\n                for (int x = 0; x < width; x++)\n                {\n                    float u = 2 * ((x + 0.5) / width) - 1;\n                    float v = 2 * ((y + 0.5) / height) - 1;\n                    // Eigen::Vector3f dir = (faceDirX * u + faceDirY * v + faceDirZ).normalized();\n                    // cubemapDirs.push_back(dir);\n                    cubemapDirs.emplace_back((faceDirX * u + faceDirY * v + faceDirZ).normalized());\n                }\n            }\n        }\n\n        constexpr int SHNum = (SHOrder + 1) * (SHOrder + 1);\n\n        //        std::vector<Eigen::Array3f> SHCoeffiecents(SHNum);\n        //        for (int i = 0; i < SHNum; i++)\n        //            SHCoeffiecents[i] = Eigen::Array3f(0);\n        std::vector<Eigen::Array3f> SHCoeffiecents(SHNum, Eigen::Array3f(0));\n        /// fill up SHCoeffiecents\n\n        /// unused?\n        // float sumWeight = 0;\n        for (int i = 0; i < 6; i++)\n        {\n            for (int y = 0; y < height; y++)\n            {\n                for (int x = 0; x < width; x++)\n                {\n                    // TODO: here you need to compute light sh of each face of cubemap of each pixel\n                    // TODO: 此处你需要计算每个像素下cubemap某个面的球谐系数\n\n                    /// Note: requiring double in EvalSH()\n                    const Eigen::Vector3d dir = cubemapDirs[i * width * height + y * width + x].cast<double>().normalized();\n                    int index = (y * width + x) * channel;\n                    /// L_env, environment light\n                    Eigen::Array3f Le(images[i][index + 0], images[i][index + 1], images[i][index + 2]);\n\n                    /// finish code here\n                    for (int level = 0; level <= SHOrder; ++level)\n                    {\n                        for (int m = -level; m <= level; ++m)\n                        {\n                            SHCoeffiecents[sh::GetIndex(level, m)] += Le * sh::EvalSH(level, m, dir) * CalcArea(x, y, width, height);\n                        }\n                    }\n                }\n            }\n        }\n        return SHCoeffiecents;\n    }\n} // namespace ProjEnv\n\nclass PRTIntegrator : public Integrator\n{\npublic: // static\n    static constexpr int SHOrder = 2;\n\n    static constexpr int SHCoeffLength = (SHOrder + 1) * (SHOrder + 1);\n\npublic: // class definition\n    enum class Type\n    {\n        Unshadowed = 0,\n        Shadowed = 1,\n        Interreflection = 2\n    };\n\npublic: // constructor\n    PRTIntegrator(const PropertyList &props)\n    {\n        /* No parameters this time */\n        m_SampleCount = props.getInteger(\"PRTSampleCount\", 100);\n        m_CubemapPath = props.getString(\"cubemap\");\n        auto type = props.getString(\"type\", \"unshadowed\");\n        if (type == \"unshadowed\")\n        {\n            m_Type = Type::Unshadowed;\n        }\n        else if (type == \"shadowed\")\n        {\n            m_Type = Type::Shadowed;\n        }\n        else if (type == \"interreflection\")\n        {\n            m_Type = Type::Interreflection;\n            m_Bounce = props.getInteger(\"bounce\", 1);\n        }\n        else\n        {\n            throw NoriException(\"Unsupported type: %s.\", type);\n        }\n    }\n\npublic: // virtual func\n    void preprocess(const Scene *scene) override\n    {\n        // Here only compute one mesh\n        const auto mesh = scene->getMeshes()[0];\n        // Projection environment\n        /// get cubePath (file path)\n        auto cubePath = getFileResolver()->resolve(m_CubemapPath);\n\n        int width, height, channel;\n        std::vector<std::unique_ptr<float[]>> images = ProjEnv::LoadCubemapImages(cubePath.str(), width, height, channel);\n\n        /// write\n        auto lightPath = cubePath / \"light.txt\";\n        auto transPath = cubePath / \"transport.txt\";\n\n        std::ofstream lightFout(lightPath.str());\n        std::ofstream fout(transPath.str());\n\n        /// get pre-computed SH coeffs\n        auto envCoeffs = ProjEnv::PrecomputeCubemapSH<SHOrder>(images, width, height, channel);\n\n        m_LightCoeffs.resize(3, SHCoeffLength);\n        for (int i = 0; i < envCoeffs.size(); i++)\n        {\n            lightFout << (envCoeffs)[i].x() << \" \" << (envCoeffs)[i].y() << \" \" << (envCoeffs)[i].z() << std::endl;\n            m_LightCoeffs.col(i) = (envCoeffs)[i];\n        }\n        std::cout << \"Computed light sh coeffs from: \" << cubePath.str() << \" to: \" << lightPath.str() << std::endl;\n\n        // Projection transport\n        /// (SHOrder+1)^2 rows, VertexCount cols\n        /// SHCoeffLength = (SHOrder+1)^2\n        m_TransportSHCoeffs.resize(SHCoeffLength, mesh->getVertexCount());\n        /// write in file\n        fout << mesh->getVertexCount() << std::endl;\n\n        for (int i = 0; i < mesh->getVertexCount(); i++)\n        {\n            const Point3f &v = mesh->getVertexPositions().col(i);\n            const Normal3f &n = mesh->getVertexNormals().col(i);\n\n            /// input: w_i, output: L(w_i) * max(0, cos(\\theta)).\n            auto shFunc = [&](double phi, double theta) -> double\n            {\n                Eigen::Array3d d = sh::ToVector(phi, theta);\n\n                /// sample vector\n                const auto wi = Vector3f(d.x(), d.y(), d.z());\n\n                double H = wi.dot(n);\n\n                if (H < 0.0)\n                    return 0.0;\n                if (m_Type == Type::Unshadowed)\n                {\n                    return H;\n                    // TODO: here you need to calculate unshadowed transport term of a given direction\n                    // TODO: 此处你需要计算给定方向下的unshadowed传输项球谐函数值\n                    // return 0;\n                }\n                else\n                {\n                    // test if there should be shadow\n                    return (scene->rayIntersect(Ray3f(v, wi))) ? 0.0 : H;\n\n                    // TODO: here you need to calculate shadowed transport term of a given direction\n                    // TODO: 此处你需要计算给定方向下的shadowed传输项球谐函数值\n                    // return 0;\n                }\n            };\n\n            /// lambda is passed to sh::ProjectFunction\n            /// sh::ProjectFunction returns std::vector<double>\n            auto shCoeff = sh::ProjectFunction(SHOrder, shFunc, m_SampleCount);\n            for (int j = 0; j < shCoeff->size(); j++)\n            {\n                m_TransportSHCoeffs.col(i).coeffRef(j) = (*shCoeff)[j];\n            }\n        }\n        if (m_Type == Type::Interreflection)\n        {\n            Eigen::MatrixXf interreflectionCoefs;\n            interreflectionCoefs.resize(SHCoeffLength, mesh->getVertexCount());\n\n            for (int i = 0; i < mesh->getVertexCount(); ++i)\n            {\n                bool vis = false;\n                for (int j = 0; j < SHCoeffLength; ++j)\n                {\n                    if (m_TransportSHCoeffs.col(i).coeffRef(j) != 0)\n                    {\n                        vis = true;\n                        break;\n                    }\n                }\n                if (vis)\n                    continue;\n                const Point3f v = mesh->getVertexPositions().col(i);\n                const Normal3f n = mesh->getVertexNormals().col(i);\n                auto shFunc = [&](double phi, double theta) -> std::vector<double>\n                {\n                    Eigen::Array3d d = sh::ToVector(phi, theta);\n\n                    /// sample vector\n                    const auto wi = Vector3f(d.x(), d.y(), d.z());\n\n                    double H = wi.dot(n);\n                    std::vector<double> ans(SHCoeffLength, 0.0);\n                    if (H < 0.0)\n                        return ans;\n                    Intersection it;\n                    bool intersect = scene->rayIntersect(Ray3f(v, wi), it);\n                    if (!intersect)\n                        return ans;\n                    auto a = m_TransportSHCoeffs.col(it.tri_index.x());\n                    auto b = m_TransportSHCoeffs.col(it.tri_index.y());\n                    auto c = m_TransportSHCoeffs.col(it.tri_index.z());\n                    auto x = it.bary.x();\n                    auto y = it.bary.y();\n                    auto z = it.bary.z();\n                    auto result = (a * x + b * y + c * z) * H;\n                    for (int i = 0; i < ans.size(); ++i)\n                    {\n                        ans[i] = result[i];\n                    }\n                    return ans;\n                };\n\n                const int sample_side = static_cast<int>(floor(sqrt(m_SampleCount)));\n                // auto shCoeff = sh::ProjectFunction(SHOrder, shFunc, m_SampleCount);\n\n                std::random_device rd;\n                std::mt19937 gen(rd());\n                std::uniform_real_distribution<> rng(0.0, 1.0);\n                for (int t = 0; t < sample_side; t++)\n                {\n                    for (int p = 0; p < sample_side; p++)\n                    {\n                        double alpha = (t + rng(gen)) / sample_side;\n                        double beta = (p + rng(gen)) / sample_side;\n                        // See http://www.bogotobogo.com/Algorithms/uniform_distribution_sphere.php\n                        double phi = 2.0 * M_PI * beta;\n                        double theta = acos(2.0 * alpha - 1.0);\n\n                        // evaluate the analytic function for the current spherical coords\n                        auto func_value = shFunc(phi, theta);\n\n                        // evaluate the SH basis functions up to band O, scale them by the\n                        // function's value and accumulate them over all generated samples\n                        for (int j = 0; j < SHCoeffLength; ++j)\n                        {\n                            interreflectionCoefs.col(i).coeffRef(j) += func_value[j];\n                        }\n                    }\n                }\n\n                // scale by the probability of a particular sample, which is\n                // 4pi/sample_side^2. 4pi for the surface area of a unit sphere, and\n                // 1/sample_side^2 for the number of samples drawn uniformly.\n                interreflectionCoefs.col(i) *= 4.0 * M_PI / (sample_side * sample_side);\n            }\n            // TODO: leave for bonus\n\n            for (int i = 0; i < mesh->getVertexCount(); ++i)\n            {\n                m_TransportSHCoeffs.col(i) += interreflectionCoefs.col(i);\n            }\n        }\n\n        // Save in face format\n        for (int f = 0; f < mesh->getTriangleCount(); f++)\n        {\n            const MatrixXu &F = mesh->getIndices();\n            uint32_t idx0 = F(0, f), idx1 = F(1, f), idx2 = F(2, f);\n            for (int j = 0; j < SHCoeffLength; j++)\n            {\n                fout << m_TransportSHCoeffs.col(idx0).coeff(j) << \" \";\n            }\n            fout << std::endl;\n            for (int j = 0; j < SHCoeffLength; j++)\n            {\n                fout << m_TransportSHCoeffs.col(idx1).coeff(j) << \" \";\n            }\n            fout << std::endl;\n            for (int j = 0; j < SHCoeffLength; j++)\n            {\n                fout << m_TransportSHCoeffs.col(idx2).coeff(j) << \" \";\n            }\n            fout << std::endl;\n        }\n        std::cout << \"Computed SH coeffs\"\n                  << \" to: \" << transPath.str() << std::endl;\n    }\n\npublic: // member func\n    Color3f Li(const Scene *scene, Sampler *sampler, const Ray3f &ray) const\n    {\n        Intersection its;\n        if (!scene->rayIntersect(ray, its))\n            return Color3f(0.0f);\n\n        const Eigen::Matrix<Vector3f::Scalar, SHCoeffLength, 1> sh0 = m_TransportSHCoeffs.col(its.tri_index.x()),\n                                                                sh1 = m_TransportSHCoeffs.col(its.tri_index.y()),\n                                                                sh2 = m_TransportSHCoeffs.col(its.tri_index.z());\n        const Eigen::Matrix<Vector3f::Scalar, SHCoeffLength, 1> rL = m_LightCoeffs.row(0), gL = m_LightCoeffs.row(1), bL = m_LightCoeffs.row(2);\n\n        Color3f c0 = Color3f(rL.dot(sh0), gL.dot(sh0), bL.dot(sh0)),\n                c1 = Color3f(rL.dot(sh1), gL.dot(sh1), bL.dot(sh1)),\n                c2 = Color3f(rL.dot(sh2), gL.dot(sh2), bL.dot(sh2));\n\n        const Vector3f &bary = its.bary;\n        Color3f c = bary.x() * c0 + bary.y() * c1 + bary.z() * c2;\n        // TODO: you need to delete the following four line codes after finishing your calculation to SH,\n        //       we use it to visualize the normals of model for debug.\n        // TODO: 在完成了球谐系数计算后，你需要删除下列四行，这四行代码的作用是用来可视化模型法线\n        // if (c.isZero()) {\n        //     auto n_ = its.shFrame.n.cwiseAbs();\n        //     return Color3f(n_.x(), n_.y(), n_.z());\n        // }\n        return c;\n    }\n\n    std::string toString() const\n    {\n        return \"PRTIntegrator[]\";\n    }\n\nprivate:\n    Type m_Type;\n    int m_Bounce = 1;\n    int m_SampleCount = 100;\n    std::string m_CubemapPath;\n    Eigen::MatrixXf m_TransportSHCoeffs;\n    Eigen::MatrixXf m_LightCoeffs;\n};\n\nNORI_REGISTER_CLASS(PRTIntegrator, \"prt\");\nNORI_NAMESPACE_END\n", "meta": {"hexsha": "031177147489d68c1841a726c06b33e4451eadb7", "size": 16946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "assignment2/prt/src/prt.cpp", "max_stars_repo_name": "Antares0982/GAMES202", "max_stars_repo_head_hexsha": "a230acb11024950ce2095b9e599e87bb25e78ee2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "assignment2/prt/src/prt.cpp", "max_issues_repo_name": "Antares0982/GAMES202", "max_issues_repo_head_hexsha": "a230acb11024950ce2095b9e599e87bb25e78ee2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "assignment2/prt/src/prt.cpp", "max_forks_repo_name": "Antares0982/GAMES202", "max_forks_repo_head_hexsha": "a230acb11024950ce2095b9e599e87bb25e78ee2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5136363636, "max_line_length": 144, "alphanum_fraction": 0.4757464888, "num_tokens": 4477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.44281245645342815}}
{"text": "// Copyright (c) Dietmar Wolz.\r\n//\r\n// This source code is licensed under the MIT license found in the\r\n// LICENSE file in the root directory.\r\n\r\n// Eigen based implementation of differential evolution using on the DE/best/1 strategy.\r\n// Uses two deviations from the standard DE algorithm:\r\n// a) temporal locality introduced in \r\n// https://www.researchgate.net/publication/309179699_Differential_evolution_for_protein_folding_optimization_based_on_a_three-dimensional_AB_off-lattice_model\r\n// b) reinitialization of individuals based on their age. \r\n// requires https://github.com/imneme/pcg-cpp\r\n// To be used to further optimize a given solution. Initial population is created using a normal distribition\r\n// with mean=init and sdev=sigma (normalized over the bounds, defined separately for each variable).\r\n\r\n#include <Eigen/Core>\r\n#include <iostream>\r\n#include <float.h>\r\n#include <ctime>\r\n#include <random>\r\n#include \"pcg_random.hpp\"\r\n#include \"call_java.hpp\"\r\n\r\nusing namespace std;\r\n\r\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> vec;\r\ntypedef Eigen::Matrix<int, Eigen::Dynamic, 1> ivec;\r\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat;\r\n\r\ntypedef double (*callback_type)(int, double[]);\r\n\r\nnamespace l_differential_evolution {\r\n\r\nstatic uniform_real_distribution<> distr_01 = std::uniform_real_distribution<>(\r\n        0, 1);\r\nstatic normal_distribution<> gauss_01 = std::normal_distribution<>(0, 1);\r\n\r\nstatic vec zeros(int n) {\r\n    return Eigen::MatrixXd::Zero(n, 1);\r\n}\r\n\r\nstatic vec constant(int n, double val) {\r\n    return vec::Constant(n, val);\r\n}\r\n\r\nstatic Eigen::MatrixXd uniform(int dx, int dy, pcg64 &rs) {\r\n    return Eigen::MatrixXd::NullaryExpr(dx, dy, [&]() {\r\n        return distr_01(rs);\r\n    });\r\n}\r\n\r\nstatic Eigen::MatrixXd uniformVec(int dim, pcg64 &rs) {\r\n    return Eigen::MatrixXd::NullaryExpr(dim, 1, [&]() {\r\n        return distr_01(rs);\r\n    });\r\n}\r\n\r\nstatic double normreal(double mean, double sdev, pcg64 &rs) {\r\n    return gauss_01(rs) * sdev + mean;\r\n}\r\n\r\nstatic vec normalVec(const vec &mean, const vec &sdev, int dim, pcg64 &rs) {\r\n    vec nv = Eigen::MatrixXd::NullaryExpr(dim, 1, [&]() {\r\n        return gauss_01(rs);\r\n    });\r\n    return (nv.array() * sdev.array()).matrix() + mean;\r\n}\r\n\r\nstatic int index_min(vec &v) {\r\n    double minv = DBL_MAX;\r\n    int mi = -1;\r\n    for (int i = 0; i < v.size(); i++) {\r\n        if (v[i] < minv) {\r\n            mi = i;\r\n            minv = v[i];\r\n        }\r\n    }\r\n    return mi;\r\n}\r\n\r\nstruct IndexVal {\r\n    int index;\r\n    double val;\r\n};\r\n\r\n// wrapper around the fittness function, scales according to boundaries\r\n\r\nclass Fitness {\r\n\r\npublic:\r\n\r\n    Fitness(CallJava *func_, int dim_, const vec &lower_limit,\r\n            const vec &upper_limit, const vec &guess_, const vec &sigma_,\r\n            pcg64 &rs_) {\r\n        func = func_;\r\n        dim = dim_;\r\n        lower = lower_limit;\r\n        upper = upper_limit;\r\n        // initial guess for the arguments of the fitness function\r\n        guess = guess_;\r\n        xmean = vec(guess);\r\n        rs = rs_;\r\n        evaluationCounter = 0;\r\n        if (lower.size() > 0) // bounds defined\r\n            scale = (upper - lower);\r\n        else\r\n            scale = constant(dim, 1.0);\r\n        invScale = scale.cwiseInverse();\r\n        maxSigma = 0.25 * scale;\r\n        // individual sigma values - initial search volume. inputSigma determines\r\n        // the initial coordinate wise standard deviations for the search.\r\n        if (sigma_.size() == 1)\r\n            sigma0 =\r\n                    0.5\r\n                            * (scale.array()\r\n                                    * (vec::Constant(dim, sigma_[0])).array()).matrix();\r\n        else\r\n            sigma0 = 0.5 * (scale.array() * sigma_.array()).matrix();\r\n        sigma = vec(sigma0);\r\n    }\r\n\r\n    void updateSigma(const vec &X) {\r\n        vec delta = (xmean - X).cwiseAbs() * 0.5;\r\n        sigma = delta.cwiseMin(maxSigma);\r\n        xmean = X;\r\n    }\r\n\r\n    vec normX() {\r\n        return distr_01(rs) < 0.5 ?\r\n                getClosestFeasible(normalVec(xmean, sigma0, dim, rs)) :\r\n                getClosestFeasible(normalVec(xmean, sigma, dim, rs));\r\n    }\r\n\r\n    double normXi(int i) {\r\n        double nx;\r\n        if (distr_01(rs) < 0.5) {\r\n            do {\r\n                nx = normreal(xmean[i], sigma0[i], rs);\r\n            } while (!feasible(i, nx));\r\n        } else {\r\n            do {\r\n                nx = normreal(xmean[i], sigma[i], rs);\r\n            } while (!feasible(i, nx));\r\n        }\r\n        return nx;\r\n    }\r\n\r\n    bool feasible(int i, double x) {\r\n        return lower.size() == 0 || (x >= lower[i] && x <= upper[i]);\r\n    }\r\n\r\n    vec sample() {\r\n        if (lower.size() > 0) {\r\n            vec rv = uniformVec(dim, rs);\r\n            return (rv.array() * scale.array()).matrix() + lower;\r\n        } else\r\n            return normX();\r\n    }\r\n\r\n    double sample_i(int i) {\r\n        if (lower.size() > 0)\r\n            return lower[i] + scale[i] * distr_01(rs);\r\n        else\r\n            return normXi(i);\r\n    }\r\n\r\n    vec getClosestFeasible(const vec &X) const {\r\n        if (lower.size() > 0) {\r\n            return X.cwiseMin(upper).cwiseMax(lower);\r\n        }\r\n        return X;\r\n    }\r\n\r\n    double eval(const vec &X) {\r\n        int n = X.size();\r\n        double parg[n];\r\n        for (int i = 0; i < n; i++)\r\n            parg[i] = X(i);\r\n        double res = func->evalJava1(n, parg);\r\n        evaluationCounter++;\r\n        return res;\r\n    }\r\n\r\n    int getEvaluations() {\r\n        return evaluationCounter;\r\n    }\r\n\r\n    vec guess;\r\n\r\nprivate:\r\n    CallJava *func;\r\n    int dim;\r\n    vec lower;\r\n    vec upper;\r\n    vec xmean;\r\n    vec sigma0;\r\n    vec sigma;\r\n    vec maxSigma;\r\n    pcg64 rs;\r\n    long evaluationCounter;\r\n    vec scale;\r\n    vec invScale;\r\n};\r\n\r\nclass LDeOptimizer {\r\n\r\npublic:\r\n\r\n    LDeOptimizer(long runid_, Fitness *fitfun_, int dim_, pcg64 *rs_,\r\n            int popsize_, int maxEvaluations_, double keep_,\r\n            double stopfitness_, double F_, double CR_) {\r\n        // runid used to identify a specific run\r\n        runid = runid_;\r\n        // fitness function to minimize\r\n        fitfun = fitfun_;\r\n        // Number of objective variables/problem dimension\r\n        dim = dim_;\r\n        // Population size\r\n        popsize = popsize_ > 0 ? popsize_ : 15 * dim;\r\n        // maximal number of evaluations allowed.\r\n        maxEvaluations = maxEvaluations_ > 0 ? maxEvaluations_ : 50000;\r\n        // keep best young after each iteration.\r\n        keep = keep_ > 0 ? keep_ : 30;\r\n        // Limit for fitness value.\r\n        stopfitness = stopfitness_;\r\n        F0 = F_ > 0 ? F_ : 0.5;\r\n        CR0 = CR_ > 0 ? CR_ : 0.9;\r\n        // Number of iterations already performed.\r\n        iterations = 0;\r\n        bestY = DBL_MAX;\r\n        // stop criteria\r\n        stop = 0;\r\n        rs = rs_;\r\n        init();\r\n    }\r\n\r\n    ~LDeOptimizer() {\r\n        delete rs;\r\n    }\r\n\r\n    double rnd01() {\r\n        return distr_01(*rs);\r\n    }\r\n\r\n    double rnd02() {\r\n        double rnd = distr_01(*rs);\r\n        return rnd * rnd;\r\n    }\r\n\r\n    int rndInt(int max) {\r\n        return (int) (max * distr_01(*rs));\r\n    }\r\n\r\n    void doOptimize() {\r\n\r\n        // -------------------- Generation Loop --------------------------------\r\n        for (iterations = 1; fitfun->getEvaluations() < maxEvaluations;\r\n                iterations++) {\r\n\r\n            double CR = iterations % 2 == 0 ? 0.5 * CR0 : CR0;\r\n            double F = iterations % 2 == 0 ? 0.5 * F0 : F0;\r\n\r\n            for (int p = 0; p < popsize; p++) {\r\n                vec xp = popX.col(p);\r\n                vec xb = popX.col(bestI);\r\n\r\n                int r1, r2;\r\n                do {\r\n                    r1 = rndInt(popsize);\r\n                } while (r1 == p || r1 == bestI);\r\n                do {\r\n                    r2 = rndInt(popsize);\r\n                } while (r2 == p || r2 == bestI || r2 == r1);\r\n                vec x1 = popX.col(r1);\r\n                vec x2 = popX.col(r2);\r\n                int r = rndInt(dim);\r\n                vec x = vec(xp);\r\n                for (int j = 0; j < dim; j++) {\r\n                    if (j == r || rnd01() < CR) {\r\n                        x[j] = xb[j] + F * (x1[j] - x2[j]);\r\n                        if (!fitfun->feasible(j, x[j]))\r\n                            x[j] = fitfun->normXi(j);\r\n                    }\r\n                }\r\n                double y = fitfun->eval(x);\r\n                if (isfinite(y) && y < popY[p]) {\r\n                    // temporal locality\r\n                    vec x2 = fitfun->getClosestFeasible(xb + ((x - xp) * 0.5));\r\n                    double y2 = fitfun->eval(x2);\r\n                    if (isfinite(y2) && y2 < y) {\r\n                        y = y2;\r\n                        x = x2;\r\n                    }\r\n                    popX.col(p) = x;\r\n                    popY(p) = y;\r\n                    popIter[p] = iterations;\r\n                    if (y < popY[bestI]) {\r\n                        bestI = p;\r\n                        if (y < bestY) {\r\n                            fitfun->updateSigma(x);\r\n                            bestY = y;\r\n                            bestX = x;\r\n                            if (isfinite(stopfitness) && bestY < stopfitness) {\r\n                                stop = 1;\r\n                                return;\r\n                            }\r\n                        }\r\n                    }\r\n                } else {\r\n                    // reinitialize individual\r\n                    if (keep * rnd01() < iterations - popIter[p]) {\r\n                        popX.col(p) = fitfun->normX();\r\n                        popY[p] = fitfun->eval(popX.col(p)); // compute fitness\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    void init() {\r\n        popX = mat(dim, popsize);\r\n        popY = vec(popsize);\r\n        for (int p = 0; p < popsize; p++) {\r\n            popX.col(p) = fitfun->guess;\r\n            popY[p] = DBL_MAX; // compute fitness\r\n        }\r\n        bestI = 0;\r\n        bestX = popX.col(bestI);\r\n        popIter = zeros(popsize);\r\n    }\r\n\r\n    vec getBestX() {\r\n        return bestX;\r\n    }\r\n\r\n    double getBestValue() {\r\n        return bestY;\r\n    }\r\n\r\n    double getIterations() {\r\n        return iterations;\r\n    }\r\n\r\n    double getStop() {\r\n        return stop;\r\n    }\r\n\r\nprivate:\r\n    long runid;\r\n    Fitness *fitfun;\r\n    int popsize; // population size\r\n    int dim;\r\n    int maxEvaluations;\r\n    double keep;\r\n    double stopfitness;\r\n    int iterations;\r\n    double bestY;\r\n    vec bestX;\r\n    int bestI;\r\n    int stop;\r\n    double F0;\r\n    double CR0;\r\n    pcg64 *rs;\r\n    mat popX;\r\n    vec popY;\r\n    vec popIter;\r\n};\r\n\r\n// see https://cvstuff.wordpress.com/2014/11/27/wraping-c-code-with-python-ctypes-memory-and-pointers/\r\n\r\n}\r\n\r\nusing namespace l_differential_evolution;\r\n\r\n/*\r\n * Class:     fcmaes_core_Jni\r\n * Method:    optimizeLDE\r\n * Signature: (Lfcmaes/core/Fitness;[D[D[D[DIDIDDDJI)I\r\n */\r\nJNIEXPORT jint JNICALL Java_fcmaes_core_Jni_optimizeLDE(JNIEnv *env, jclass cls,\r\n        jobject func, jdoubleArray jlower, jdoubleArray jupper,\r\n        jdoubleArray jinit, jdoubleArray jsigma, jint maxEvals,\r\n        jdouble stopfitness, jint popsize, jdouble keep, jdouble F, jdouble CR,\r\n        jlong seed, jint runid) {\r\n\r\n    double *init = env->GetDoubleArrayElements(jinit, JNI_FALSE);\r\n    double *lower = env->GetDoubleArrayElements(jlower, JNI_FALSE);\r\n    double *upper = env->GetDoubleArrayElements(jupper, JNI_FALSE);\r\n    double *sigma = env->GetDoubleArrayElements(jsigma, JNI_FALSE);\r\n    int dim = env->GetArrayLength(jinit);\r\n\r\n    vec guess(dim), lower_limit(dim), upper_limit(dim), inputSigma(dim);\r\n    bool useLimit = false;\r\n    for (int i = 0; i < dim; i++) {\r\n        guess[i] = init[i];\r\n        inputSigma[i] = sigma[i];\r\n        lower_limit[i] = lower[i];\r\n        upper_limit[i] = upper[i];\r\n        useLimit |= (lower[i] != 0);\r\n        useLimit |= (upper[i] != 0);\r\n    }\r\n    if (useLimit == false) {\r\n        lower_limit.resize(0);\r\n        upper_limit.resize(0);\r\n    }\r\n    pcg64 *rs = new pcg64(seed);\r\n    CallJava callJava(func, env);\r\n    Fitness fitfun(&callJava, dim, lower_limit, upper_limit, guess, inputSigma,\r\n            *rs);\r\n    LDeOptimizer opt(runid, &fitfun, dim, rs, popsize, maxEvals, keep,\r\n            stopfitness, F, CR);\r\n    try {\r\n        opt.doOptimize();\r\n        vec bestX = opt.getBestX();\r\n        double bestY = opt.getBestValue();\r\n\r\n        for (int i = 0; i < dim; i++)\r\n            init[i] = bestX[i];\r\n\r\n        env->SetDoubleArrayRegion(jinit, 0, dim, (jdouble*) init);\r\n        env->ReleaseDoubleArrayElements(jinit, init, 0);\r\n        env->ReleaseDoubleArrayElements(jupper, upper, 0);\r\n        env->ReleaseDoubleArrayElements(jlower, lower, 0);\r\n        env->ReleaseDoubleArrayElements(jsigma, sigma, 0);\r\n        return fitfun.getEvaluations();\r\n\r\n    } catch (std::exception &e) {\r\n        cout << e.what() << endl;\r\n        return fitfun.getEvaluations();\r\n    }\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "580bc4cbcdfabe787ab376a130346b0c8c88fe15", "size": 13067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppsrc/ldeoptimizer.cpp", "max_stars_repo_name": "dietmarwo/fcmaes-java", "max_stars_repo_head_hexsha": "ec1704199783e93628f6fde42295c9b79cb48dde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-11-08T14:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T12:41:38.000Z", "max_issues_repo_path": "cppsrc/ldeoptimizer.cpp", "max_issues_repo_name": "dietmarwo/fcmaes-java", "max_issues_repo_head_hexsha": "ec1704199783e93628f6fde42295c9b79cb48dde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppsrc/ldeoptimizer.cpp", "max_forks_repo_name": "dietmarwo/fcmaes-java", "max_forks_repo_head_hexsha": "ec1704199783e93628f6fde42295c9b79cb48dde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-08T14:27:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-08T14:27:15.000Z", "avg_line_length": 30.1778290993, "max_line_length": 160, "alphanum_fraction": 0.5072319584, "num_tokens": 3257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.442789948642895}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <iostream>\n#include <numeric>\n#include <unordered_map>\n#include <vector>\n\n#include <misc3d/common/normal_estimation.h>\n#include <misc3d/logging.h>\n#include <misc3d/utils.h>\n\nnamespace misc3d {\nnamespace common {\n\nvoid VectorToPointer(const std::vector<Eigen::Vector3d> &data, double *ptr) {\n    const size_t num = data.size();\n#pragma omp parallel for\n    for (int i = 0; i < num; i++) {\n        ptr[3 * i] = data[i](0);\n        ptr[3 * i + 1] = data[i](1);\n        ptr[3 * i + 2] = data[i](2);\n    }\n}\n\nvoid PointerToVector(const double *ptr, int num,\n                     std::vector<Eigen::Vector3d> &data) {\n    data.resize(num);\n#pragma omp parallel for\n    for (int i = 0; i < num; i++) {\n        Eigen::Vector3d d(ptr[i * 3], ptr[i * 3 + 1], ptr[i * 3 + 2]);\n        data[i] = d;\n    }\n}\n\ntemplate <typename T0, typename T1>\nvoid SumDense(const T0 *data, const bool *mask, const unsigned int w,\n              const unsigned int h, const unsigned int k, T1 *dst) {\n    const size_t range_rows[2] = {k, h - k}, range_cols[2] = {k + 1, w - k},\n                 double_k = 2 * k;\n#pragma omp parallel for\n    for (int r = (int)range_rows[0]; r < (int)range_rows[1]; r++) {\n        size_t idx_r = (size_t)r * w;\n        T1 *ptr = dst + idx_r + k;\n        *ptr = 0;\n        for (size_t r0 = (size_t)r - k, idx_r0; r0 <= (size_t)r + k; r0++) {\n            idx_r0 = r0 * w;\n            for (size_t c0 = 0; c0 <= double_k; c0++) {\n                *ptr += data[idx_r0 + c0];\n            }\n        }\n        ptr++;\n        for (size_t c = range_cols[0]; c < range_cols[1]; c++, ptr++) {\n            *ptr = *(ptr - 1);\n            for (size_t r0 = (size_t)r - k, c0 = c - k - 1, c1 = c + k;\n                 r0 <= (size_t)r + k; r0++) {\n                *ptr += *(data + r0 * w + c1) - *(data + r0 * w + c0);\n            }\n        }\n    }\n}\n\nvoid CalcNormalsFromPointMap(const double *xyzs, const unsigned int w,\n                             const unsigned int h, const unsigned int k,\n                             double *normals, const double view_point[3]) {\n    size_t expand_w = w + 2 * k, expand_h = h + 2 * k,\n           expand_wh = expand_w * expand_h;\n    const size_t range_rows[2] = {k, expand_h - k},\n                 range_cols[2] = {k, expand_w - k};\n    bool *mask = (bool *)calloc(expand_wh, sizeof(bool));\n    double *buffer0 = (double *)calloc(expand_wh * 9, sizeof(double));\n    double *x = buffer0;\n    double *y = x + expand_wh;\n    double *z = y + expand_wh;\n    double *xx = z + expand_wh;\n    double *xy = xx + expand_wh;\n    double *xz = xy + expand_wh;\n    double *yy = xz + expand_wh;\n    double *yz = yy + expand_wh;\n    double *zz = yz + expand_wh;\n\n#pragma omp parallel for\n    for (int r = (int)range_rows[0]; r < (int)range_rows[1]; r++) {\n        size_t idx_r = (size_t)r * expand_w, idx;\n        const double *xyz = xyzs + ((size_t)r - k) * w * 3;\n        for (size_t c = range_cols[0]; c < range_cols[1]; c++, xyz += 3) {\n            idx = idx_r + c;\n            if (xyz[2] == xyz[2]) {\n                mask[idx] = true;\n                x[idx] = xyz[0];\n                y[idx] = xyz[1];\n                z[idx] = xyz[2];\n                xx[idx] = xyz[0] * xyz[0];\n                xy[idx] = xyz[0] * xyz[1];\n                xz[idx] = xyz[0] * xyz[2];\n                yy[idx] = xyz[1] * xyz[1];\n                yz[idx] = xyz[1] * xyz[2];\n                zz[idx] = xyz[2] * xyz[2];\n            }\n        }\n    }\n\n    size_t *neighbor_nums = new size_t[expand_wh];\n    double *buffer1 = (double *)malloc(expand_wh * 9 * sizeof(double));\n    double *sum_x = buffer1;\n    double *sum_y = sum_x + expand_wh;\n    double *sum_z = sum_y + expand_wh;\n    double *sum_xx = sum_z + expand_wh;\n    double *sum_xy = sum_xx + expand_wh;\n    double *sum_xz = sum_xy + expand_wh;\n    double *sum_yy = sum_xz + expand_wh;\n    double *sum_yz = sum_yy + expand_wh;\n    double *sum_zz = sum_yz + expand_wh;\n\n    SumDense(x, mask, (unsigned int)expand_w, (unsigned int)expand_h, k, sum_x);\n    SumDense(y, mask, (unsigned int)expand_w, (unsigned int)expand_h, k, sum_y);\n    SumDense(z, mask, (unsigned int)expand_w, (unsigned int)expand_h, k, sum_z);\n    SumDense(xx, mask, (unsigned int)expand_w, (unsigned int)expand_h, k,\n             sum_xx);\n    SumDense(xy, mask, (unsigned int)expand_w, (unsigned int)expand_h, k,\n             sum_xy);\n    SumDense(xz, mask, (unsigned int)expand_w, (unsigned int)expand_h, k,\n             sum_xz);\n    SumDense(yy, mask, (unsigned int)expand_w, (unsigned int)expand_h, k,\n             sum_yy);\n    SumDense(yz, mask, (unsigned int)expand_w, (unsigned int)expand_h, k,\n             sum_yz);\n    SumDense(zz, mask, (unsigned int)expand_w, (unsigned int)expand_h, k,\n             sum_zz);\n    SumDense(mask, mask, (unsigned int)expand_w, (unsigned int)expand_h, k,\n             neighbor_nums);\n\n#pragma omp parallel for\n    for (int r = (int)range_rows[0]; r < (int)range_rows[1]; r++) {\n        size_t idx_r = (size_t)r * expand_w, idx;\n        for (size_t c = range_cols[0]; c < range_cols[1]; c++) {\n            idx = idx_r + c;\n            if (!mask[idx])\n                continue;\n            double scale = 1. / neighbor_nums[idx];\n            double hat_x = sum_x[idx] * scale, hat_y = sum_y[idx] * scale,\n                   hat_z = sum_z[idx] * scale;\n            double covariance[3][3] = {sum_xx[idx] * scale - hat_x * hat_x,\n                                       sum_xy[idx] * scale - hat_x * hat_y,\n                                       sum_xz[idx] * scale - hat_x * hat_z,\n                                       0,\n                                       sum_yy[idx] * scale - hat_y * hat_y,\n                                       sum_yz[idx] * scale - hat_y * hat_z,\n                                       0,\n                                       0,\n                                       sum_zz[idx] * scale - hat_z * hat_z};\n            covariance[1][0] = covariance[0][1];\n            covariance[2][0] = covariance[0][2];\n            covariance[2][1] = covariance[1][2];\n\n            Eigen::Matrix<double, 3, 3, Eigen::RowMajor | Eigen::DontAlign>\n                covariance_matrix(covariance[0]);\n            Eigen::SelfAdjointEigenSolver<\n                Eigen::Matrix<double, 3, 3, Eigen::RowMajor | Eigen::DontAlign>>\n                solver;\n            solver.compute(covariance_matrix, Eigen::ComputeEigenvectors);\n            Eigen::Vector3d v0 = solver.eigenvectors().col(0);\n            double *temp_n = v0.data();\n            if ((view_point[0] - x[idx]) * temp_n[0] +\n                    (view_point[1] - y[idx]) * temp_n[1] +\n                    (view_point[2] - z[idx]) * temp_n[2] <\n                0) {\n                temp_n[0] *= -1;\n                temp_n[1] *= -1;\n                temp_n[2] *= -1;\n            }\n            memcpy(normals + (((size_t)r - k) * w + c - k) * 3, v0.data(),\n                   sizeof(double) * 3);\n        }\n    }\n\n    delete[] neighbor_nums;\n    free(buffer0);\n    free(buffer1);\n    free(mask);\n}\n\nvoid EstimateNormalsFromMap(const PointCloudPtr &pc,\n                            const std::tuple<int, int> shape, int k,\n                            const std::array<double, 3> &view_point) {\n    const size_t num = pc->points_.size();\n    const int w = std::get<0>(shape);\n    const int h = std::get<1>(shape);\n\n    if (num != w * h) {\n        misc3d::LogError(\n            \"The point cloud size is not equal to given point map size.\");\n        return;\n    }\n\n    double *normals_ptr = new double[num * 3];\n    double *points_ptr = new double[num * 3];\n    VectorToPointer(pc->points_, points_ptr);\n    CalcNormalsFromPointMap(points_ptr, w, h, k, normals_ptr,\n                            view_point.data());\n\n    // assign normals\n    std::vector<Eigen::Vector3d> normals;\n    PointerToVector(normals_ptr, num, normals);\n    pc->normals_ = normals;\n\n    delete[] normals_ptr;\n    delete[] points_ptr;\n}\n\n}  // namespace common\n}  // namespace misc3d", "meta": {"hexsha": "c451659499bd393f9a0ea7be9b470c002d346334", "size": 8022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/normal_estimation.cpp", "max_stars_repo_name": "mushroom-x/Misc3D", "max_stars_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2022-02-09T11:56:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:45:04.000Z", "max_issues_repo_path": "src/normal_estimation.cpp", "max_issues_repo_name": "mushroom-x/Misc3D", "max_issues_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2022-02-26T08:58:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T11:19:05.000Z", "max_forks_repo_path": "src/normal_estimation.cpp", "max_forks_repo_name": "mushroom-x/Misc3D", "max_forks_repo_head_hexsha": "10f05c970eda9684b19de42a128224502e23b89b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2022-02-16T06:59:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:03:11.000Z", "avg_line_length": 38.018957346, "max_line_length": 80, "alphanum_fraction": 0.5120917477, "num_tokens": 2310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.44278994864289495}}
{"text": "#include \"config.h\"\n#include \"Scene_points_with_normal_item.h\"\n#include \"Scene_polygon_soup_item.h\"\n#include \"Scene_surface_mesh_item.h\"\n#include <CGAL/Three/Scene_group_item.h>\n\n#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>\n#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>\n#include <CGAL/Three/Scene_group_item.h>\n\n#include <CGAL/Orthogonal_k_neighbor_search.h>\n#include <CGAL/Fuzzy_sphere.h>\n#include <CGAL/Search_traits_3.h>\n#include <CGAL/Search_traits_adapter.h>\n\n#include <CGAL/linear_least_squares_fitting_3.h>\n\n#include <CGAL/Random.h>\n#include <CGAL/Real_timer.h>\n\n#include <CGAL/Shape_detection.h>\n#include <CGAL/Regularization.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Alpha_shape_2.h>\n#include <CGAL/Alpha_shape_face_base_2.h>\n#include <CGAL/Alpha_shape_vertex_base_2.h>\n\n#include <CGAL/structure_point_set.h>\n\n#include <QObject>\n#include <QAction>\n#include <QMainWindow>\n#include <QApplication>\n#include <QtPlugin>\n#include <QMessageBox>\n\n#include <boost/iterator/function_output_iterator.hpp>\n\n#include \"run_with_qprogressdialog.h\"\n\n#include \"ui_Point_set_shape_detection_plugin.h\"\n\ntemplate <typename Shape_detection>\nstruct Detect_shapes_functor\n  : public Functor_with_signal_callback\n{\n  Shape_detection& shape_detection;\n  typename Shape_detection::Parameters& op;\n\n  Detect_shapes_functor (Shape_detection& shape_detection,\n                         typename Shape_detection::Parameters& op)\n    : shape_detection (shape_detection), op (op)\n  { }\n\n  void operator()()\n  {\n    shape_detection.detect(op, *(this->callback()));\n  }\n};\n\nstruct build_from_pair\n{\n  Point_set& m_pts;\n\n  build_from_pair (Point_set& pts) : m_pts (pts) { }\n\n  void operator() (const std::pair<Point_set::Point, Point_set::Vector>& pair)\n  {\n    m_pts.insert (pair.first, pair.second);\n  }\n\n\n};\n\nclass Point_set_demo_point_set_shape_detection_dialog : public QDialog, public Ui::PointSetShapeDetectionDialog\n{\n  Q_OBJECT\npublic:\n  Point_set_demo_point_set_shape_detection_dialog(QWidget * /*parent*/ = nullptr)\n  {\n    setupUi(this);\n    m_normal_tolerance_field->setMaximum(1.0);\n    m_probability_field->setRange(0.00001, 1.0);\n    m_epsilon_field->setMinimum(0.000001);\n    m_normal_tolerance_field->setMinimum(0.01);\n    m_cluster_epsilon_field->setMinimum(0.000001);\n  }\n\n  bool region_growing() const { return m_region_growing->isChecked(); }\n  double cluster_epsilon() const { return m_cluster_epsilon_field->value(); }\n  double epsilon() const { return m_epsilon_field->value(); }\n  unsigned int min_points() const { return m_min_pts_field->value(); }\n  double normal_tolerance() const { return m_normal_tolerance_field->value(); }\n  double search_probability() const { return m_probability_field->value(); }\n  double gridCellSize() const { return 1.0; }\n  bool detect_plane() const { return planeCB->isChecked(); }\n  bool detect_sphere() const { return sphereCB->isChecked(); }\n  bool detect_cylinder() const { return cylinderCB->isChecked(); }\n  bool detect_torus() const { return torusCB->isChecked(); }\n  bool detect_cone() const { return coneCB->isChecked(); }\n  bool add_property() const { return m_add_property->isChecked(); }\n  bool generate_colored_point_set() const { return m_one_colored_point_set->isChecked(); }\n  bool generate_subset() const { return m_point_subsets->isChecked(); }\n  bool generate_alpha() const { return m_alpha_shapes->isChecked(); }\n  bool regularize() const { return m_regularize->isChecked(); }\n  bool generate_structured() const { return m_generate_structured->isChecked(); }\n};\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Epic_kernel;\ntypedef Epic_kernel::Point_3 Point;\nusing namespace CGAL::Three;\nclass Polyhedron_demo_point_set_shape_detection_plugin :\n  public QObject,\n  public Polyhedron_demo_plugin_helper\n{\n  Q_OBJECT\n    Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)\n    Q_PLUGIN_METADATA(IID \"com.geometryfactory.PolyhedronDemo.PluginInterface/1.0\")\n\n  QAction* actionDetect;\n  QAction* actionEstimateParameters;\n  QAction* actionDetectShapesSM;\n\n  typedef Point_set_3<Kernel>::Point_map PointPMap;\n  typedef Point_set_3<Kernel>::Vector_map NormalPMap;\n\n  typedef CGAL::Shape_detection::Efficient_RANSAC_traits<Epic_kernel, Point_set, PointPMap, NormalPMap> Traits;\n\npublic:\n  void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface, Messages_interface*) {\n    scene = scene_interface;\n    mw = mainWindow;\n    actionDetect = new QAction(tr(\"Point Set Shape Detection\"), mainWindow);\n    actionDetect->setObjectName(\"actionDetect\");\n    actionEstimateParameters = new QAction(tr(\"Point Set Shape Detection (parameter estimation)\"), mainWindow);\n    actionEstimateParameters->setObjectName(\"actionEstimateParameters\");\n    actionDetectShapesSM = new QAction(tr(\"Surface Mesh Shape Detection\"), mainWindow);\n    actionDetectShapesSM->setObjectName(\"actionDetectShapesSM\");\n    autoConnectActions();\n  }\n\n  bool applicable(QAction* action) const {\n\n    Scene_points_with_normal_item* item =\n      qobject_cast<Scene_points_with_normal_item*>(scene->item(scene->mainSelectionIndex()));\n    Scene_surface_mesh_item* sm_item =\n      qobject_cast<Scene_surface_mesh_item*>(scene->item(scene->mainSelectionIndex()));\n\n    if (action->objectName() == \"actionDetectShapesSM\") {\n      if (sm_item)\n        return true;\n      else return false;\n    }\n    if (item && item->has_normals()) return true;\n    return false;\n  }\n\n  QList<QAction*> actions() const {\n    return QList<QAction*>() << actionDetect << actionEstimateParameters << actionDetectShapesSM;\n  }\n\n  public Q_SLOTS:\n    void on_actionDetect_triggered();\n    void on_actionEstimateParameters_triggered();\n    void on_actionDetectShapesSM_triggered();\n\nprivate:\n\n  typedef Kernel::Plane_3 Plane_3;\n  typedef Kernel::Point_3 Point_3;\n  typedef Kernel::Vector_3 Vector_3;\n\n  // RANSAC can handle all types of shapes\n  template <typename Traits, typename Shape>\n  void add_shape (CGAL::Shape_detection::Efficient_RANSAC<Traits>& ransac,\n                  const Shape&)\n  {\n    ransac.template add_shape_factory<Shape>();\n  }\n\n  void detect_shapes_with_region_growing_sm (\n    Scene_surface_mesh_item* sm_item,\n    Point_set_demo_point_set_shape_detection_dialog& dialog) {\n\n    using Face_range = typename SMesh::Face_range;\n\n    using Neighbor_query =\n    CGAL::Shape_detection::Polygon_mesh::One_ring_neighbor_query<SMesh>;\n    using Region_type =\n    CGAL::Shape_detection::Polygon_mesh::Least_squares_plane_fit_region<Kernel, SMesh>;\n\n    using Vertex_to_point_map = typename Region_type::Vertex_to_point_map;\n    using Region_growing = CGAL::Shape_detection::Region_growing<Face_range, Neighbor_query, Region_type>;\n\n    CGAL::Random rand(static_cast<unsigned int>(time(nullptr)));\n    const SMesh& mesh = *(sm_item->polyhedron());\n    scene->setSelectedItem(-1);\n    const Face_range face_range = faces(mesh);\n\n    // Set parameters.\n    const double max_distance_to_plane =\n    dialog.epsilon();\n    const double max_accepted_angle =\n    dialog.normal_tolerance();\n    const std::size_t min_region_size =\n    dialog.min_points();\n\n    // Region growing.\n    Neighbor_query neighbor_query(mesh);\n    const Vertex_to_point_map vertex_to_point_map(get(CGAL::vertex_point, mesh));\n    Region_type region_type(\n      mesh,\n      max_distance_to_plane, max_accepted_angle, min_region_size,\n      vertex_to_point_map);\n\n    Region_growing region_growing(\n      face_range, neighbor_query, region_type);\n\n    std::vector< std::vector<std::size_t> > regions;\n    region_growing.detect(std::back_inserter(regions));\n\n    std::cerr << \"* \" << regions.size() <<\n    \" regions have been found\"\n    << std::endl;\n\n    // Output result as a new colored item.\n    Scene_surface_mesh_item *colored_item = new Scene_surface_mesh_item;\n    colored_item->setName(QString(\"%1 (region growing)\").arg(sm_item->name()));\n    SMesh& fg = *(colored_item->polyhedron());\n\n    fg = mesh;\n    const Face_range fr = faces(fg);\n\n    colored_item->setItemIsMulticolor(true);\n    colored_item->computeItemColorVectorAutomatically(false);\n    auto& color_vector = colored_item->color_vector();\n    color_vector.clear();\n\n    for (std::size_t i = 0; i < regions.size(); ++i) {\n      for (const std::size_t idx : regions[i]) {\n        const auto fit = fr.begin() + idx;\n        fg.property_map<face_descriptor, int>(\"f:patch_id\").first[*fit] =\n        static_cast<int>(i);\n      }\n      CGAL::Random rnd(static_cast<unsigned int>(i));\n      color_vector.push_back(QColor(\n        64 + rnd.get_int(0, 192),\n        64 + rnd.get_int(0, 192),\n        64 + rnd.get_int(0, 192)));\n    }\n    if(color_vector.empty())\n    {\n      for(const auto& f : faces(fg))\n      {\n        fg.property_map<face_descriptor, int>(\"f:patch_id\").first[f] =\n            static_cast<int>(0);\n      }\n      CGAL::Random rnd(static_cast<unsigned int>(0));\n      color_vector.push_back(QColor(\n        64 + rnd.get_int(0, 192),\n        64 + rnd.get_int(0, 192),\n        64 + rnd.get_int(0, 192)));\n    }\n    colored_item->invalidateOpenGLBuffers();\n    scene->addItem(colored_item);\n  }\n\n  void detect_shapes_with_region_growing (\n    Scene_points_with_normal_item* item,\n    Point_set_demo_point_set_shape_detection_dialog& dialog) {\n\n    using Point_map = typename Point_set::Point_map;\n    using Normal_map = typename Point_set::Vector_map;\n\n    using Neighbor_query =\n    CGAL::Shape_detection::Point_set::Sphere_neighbor_query<Kernel, Point_set, Point_map>;\n    using Region_type =\n    CGAL::Shape_detection::Point_set::Least_squares_plane_fit_region<Kernel, Point_set, Point_map, Normal_map>;\n    using Region_growing =\n    CGAL::Shape_detection::Region_growing<Point_set, Neighbor_query, Region_type>;\n\n    // Set parameters.\n    const double search_sphere_radius =\n    dialog.cluster_epsilon();\n    const double max_distance_to_plane =\n    dialog.epsilon();\n    const double max_accepted_angle =\n    dialog.normal_tolerance();\n    const std::size_t min_region_size =\n    dialog.min_points();\n\n    // Get a point set.\n    CGAL::Random rand(static_cast<unsigned int>(time(nullptr)));\n    Point_set* points = item->point_set();\n\n    scene->setSelectedItem(-1);\n    Scene_points_with_normal_item *colored_item =\n    new Scene_points_with_normal_item;\n\n    colored_item->setName(QString(\"%1 (region growing)\").arg(item->name()));\n    if (dialog.generate_colored_point_set()) {\n\n      colored_item->point_set()->template add_property_map<unsigned char>(\"r\", 128);\n      colored_item->point_set()->template add_property_map<unsigned char>(\"g\", 128);\n      colored_item->point_set()->template add_property_map<unsigned char>(\"b\", 128);\n      colored_item->point_set()->check_colors();\n      scene->addItem(colored_item);\n    }\n    std::string& comments = item->comments();\n\n    Point_set::Property_map<int> shape_id;\n    if (dialog.add_property()) {\n      bool added = false;\n      boost::tie(shape_id, added) = points->template add_property_map<int> (\"shape\", -1);\n      if (!added) {\n        for (auto it = points->begin(); it != points->end(); ++ it)\n          shape_id[*it] = -1;\n      }\n\n      // Remove previously detected shapes from comments.\n      std::string new_comment;\n\n      std::istringstream stream(comments);\n      std::string line;\n      while (getline(stream, line)) {\n        std::string tag;\n        std::stringstream iss(line);\n\n        if (iss >> tag && tag == \"shape\")\n          continue;\n        new_comment += line + \"\\n\";\n      }\n      comments = new_comment;\n      comments += \"shape -1 no assigned shape\\n\";\n    }\n    QApplication::setOverrideCursor(Qt::BusyCursor);\n\n    // Region growing set up.\n    Neighbor_query neighbor_query(\n      *points,\n      search_sphere_radius,\n      points->point_map());\n\n    Region_type region_type(\n      *points,\n      max_distance_to_plane, max_accepted_angle, min_region_size,\n      points->point_map(), points->normal_map());\n\n    Region_growing region_growing(\n      *points, neighbor_query, region_type);\n\n    std::vector<Scene_group_item *> groups;\n    groups.resize(1);\n    if (dialog.detect_plane()){\n      groups[0] = new Scene_group_item(\"Planes\");\n      groups[0]->setRenderingMode(Points);\n    }\n\n    // The actual shape detection.\n    CGAL::Real_timer t;\n    t.start();\n    std::vector< std::vector<std::size_t> > regions;\n    region_growing.detect(std::back_inserter(regions));\n    t.stop();\n\n    std::cout << regions.size() <<\n      \" shapes found in \" << t.time() << \" second(s)\" << std::endl;\n\n    std::vector<Plane_3> planes;\n    CGAL::Shape_detection::internal::create_planes_from_points(\n      *points, points->point_map(), regions, planes);\n\n    if (dialog.regularize()) {\n\n      std::cerr << \"Regularization of planes... \" << std::endl;\n      CGAL::regularize_planes(\n        *points,\n        points->point_map(),\n        planes,\n        CGAL::Identity_property_map<Plane_3>(),\n        CGAL::Shape_detection::RG::Point_to_shape_index_map(*points, regions),\n        true, true, true, true,\n        max_accepted_angle,\n        max_distance_to_plane);\n\n      std::cerr << \"done\" << std::endl;\n    }\n    std::map<Point_3, QColor> color_map;\n\n    int index = 0;\n    for (const auto& plane : planes) {\n\n      if (dialog.add_property()) {\n        std::ostringstream oss;\n        oss << \"shape \" << index;\n        oss << \" plane \" << plane << std::endl;\n        comments += oss.str();\n      }\n      Scene_points_with_normal_item *point_item =\n      new Scene_points_with_normal_item;\n\n      for (const std::size_t idx : regions[index]) {\n        point_item->point_set()->insert(points->point(*(points->begin() + idx)));\n        if (dialog.add_property())\n          shape_id[*(points->begin() + idx)] = index;\n      }\n\n      unsigned char r, g, b;\n      r = static_cast<unsigned char>(64 + rand.get_int(0, 192));\n      g = static_cast<unsigned char>(64 + rand.get_int(0, 192));\n      b = static_cast<unsigned char>(64 + rand.get_int(0, 192));\n      point_item->setRgbColor(r, g, b);\n\n      std::size_t nb_colored_pts = 0;\n      if (dialog.generate_colored_point_set()) {\n        for(std::size_t idx : regions[index]) {\n          auto it = colored_item->point_set()->insert(\n            points->point(*(points->begin() + idx)));\n          ++nb_colored_pts;\n          colored_item->point_set()->set_color(*it, r, g, b);\n        }\n        colored_item->invalidateOpenGLBuffers();\n      }\n\n      // Providing a useful name consisting of the order of detection,\n      // name of type and number of inliers.\n      std::stringstream ss;\n      ss << item->name().toStdString() << \"_plane_\";\n\n      Vector_3 plane_normal = plane.orthogonal_vector();\n      const double normal_length = CGAL::sqrt(plane_normal.squared_length());\n      CGAL_precondition(normal_length > 0.0);\n      plane_normal /= normal_length;\n\n      Kernel::Point_3 ref = CGAL::ORIGIN + plane_normal;\n      if (color_map.find(ref) == color_map.end()) {\n\n        ref = CGAL::ORIGIN + (-1.0) * plane_normal;\n        if (color_map.find(ref) == color_map.end())\n          color_map[ref] = point_item->color();\n        else\n          point_item->setColor(color_map[ref]);\n\n      } else point_item->setColor(color_map[ref]);\n\n      if (dialog.generate_colored_point_set()) {\n        for (std::size_t i = 0; i < nb_colored_pts; ++i) {\n          colored_item->point_set()->set_color(\n            *(colored_item->point_set()->end() - 1 - i),\n            color_map[ref].red(),\n            color_map[ref].green(),\n            color_map[ref].blue());\n        }\n      }\n      ss << \"(\" << ref << \")_\";\n\n      if (dialog.generate_alpha()) {\n        // If plane, build alpha shape\n        Scene_surface_mesh_item* sm_item = nullptr;\n        sm_item = new Scene_surface_mesh_item;\n\n        using Plane = CGAL::Shape_detection::RG::Plane<Kernel>;\n        boost::shared_ptr<Plane> rg_plane(new Plane(*points, points->point_map(), regions[index], plane));\n        build_alpha_shape(\n          *(point_item->point_set()), rg_plane,\n          sm_item, search_sphere_radius);\n\n        if (sm_item){\n          sm_item->setColor(point_item->color ());\n          sm_item->setName(QString(\"%1%2_alpha_shape\").arg(QString::fromStdString(ss.str()))\n          .arg(QString::number(regions[index].size())));\n          sm_item->setRenderingMode(Flat);\n          sm_item->invalidateOpenGLBuffers();\n          scene->addItem(sm_item);\n          if (scene->item_id(groups[0]) == -1)\n            scene->addItem(groups[0]);\n          scene->changeGroup(sm_item, groups[0]);\n        }\n      }\n      ss << regions[index].size();\n\n      point_item->setName(QString::fromStdString(ss.str()));\n      point_item->setRenderingMode(item->renderingMode());\n\n      if (dialog.generate_subset()){\n        point_item->invalidateOpenGLBuffers();\n        scene->addItem(point_item);\n        point_item->point_set()->add_normal_map();\n\n        // Set normals for point_item to the plane's normal.\n        for (auto it = point_item->point_set()->begin();\n        it != point_item->point_set()->end(); ++it)\n          point_item->point_set()->normal(*it) = plane_normal;\n\n        if (scene->item_id(groups[0]) == -1)\n          scene->addItem(groups[0]);\n        point_item->invalidateOpenGLBuffers();\n        scene->changeGroup(point_item, groups[0]);\n      }\n      else delete point_item;\n      ++index;\n    }\n\n    Q_FOREACH(Scene_group_item* group, groups)\n      if(group && group->getChildren().empty())\n        delete group;\n\n    if (dialog.generate_structured()) {\n      std::cerr << \"Structuring point set... \";\n\n      Scene_points_with_normal_item *pts_full = new Scene_points_with_normal_item;\n      pts_full->point_set()->add_normal_map();\n\n      CGAL::structure_point_set(\n        *points,\n        planes,\n        boost::make_function_output_iterator(build_from_pair((*(pts_full->point_set())))),\n        search_sphere_radius,\n        points->parameters().\n        plane_map(CGAL::Identity_property_map<Plane_3>()).\n        plane_index_map(CGAL::Shape_detection::RG::Point_to_shape_index_map(*points, regions)));\n\n      if (pts_full->point_set()->empty())\n        delete pts_full;\n      else {\n        pts_full->point_set()->unselect_all();\n        pts_full->setName(tr(\"%1 (structured)\").arg(item->name()));\n        pts_full->setRenderingMode(PointsPlusNormals);\n        pts_full->setColor(Qt::blue);\n        pts_full->invalidateOpenGLBuffers();\n        scene->addItem(pts_full);\n      }\n      std::cerr << \"done\" << std::endl;\n    }\n\n    // Updates scene.\n    scene->itemChanged(index);\n    QApplication::restoreOverrideCursor();\n    item->setVisible(false);\n  }\n\n  void detect_shapes_with_ransac (Scene_points_with_normal_item* item,\n                      Point_set_demo_point_set_shape_detection_dialog& dialog)\n  {\n    typedef Point_set::Point_map PointPMap;\n    typedef Point_set::Vector_map NormalPMap;\n\n    typedef CGAL::Shape_detection::Efficient_RANSAC_traits<Epic_kernel, Point_set, PointPMap, NormalPMap> Traits;\n    typedef CGAL::Shape_detection::Efficient_RANSAC<Traits> Ransac;\n\n    Ransac::Parameters op;\n    op.probability = dialog.search_probability();       // probability to miss the largest primitive on each iteration.\n    op.min_points = dialog.min_points();          // Only extract shapes with a minimum number of points.\n    op.epsilon = dialog.epsilon();          // maximum euclidean distance between point and shape.\n    op.cluster_epsilon = dialog.cluster_epsilon();    // maximum euclidean distance between points to be clustered.\n    op.normal_threshold = std::cos(CGAL_PI * dialog.normal_tolerance() / 180.);   // normal_threshold < dot(surface_normal, point_normal);\n\n    CGAL::Random rand(static_cast<unsigned int>(time(nullptr)));\n    // Gets point set\n    Point_set* points = item->point_set();\n\n    Scene_points_with_normal_item::Bbox bb = item->bbox();\n\n    double diam = CGAL::sqrt((bb.xmax()-bb.xmin())*(bb.xmax()-bb.xmin()) + (bb.ymax()-bb.ymin())*(bb.ymax()-bb.ymin()) + (bb.zmax()-bb.zmin())*(bb.zmax()-bb.zmin()));\n\n    scene->setSelectedItem(-1);\n    Scene_points_with_normal_item *colored_item\n      = new Scene_points_with_normal_item;\n    colored_item->setName (QString(\"%1 (ransac)\").arg(item->name()));\n    if (dialog.generate_colored_point_set())\n    {\n      colored_item->point_set()->template add_property_map<unsigned char>(\"r\", 128);\n      colored_item->point_set()->template add_property_map<unsigned char>(\"g\", 128);\n      colored_item->point_set()->template add_property_map<unsigned char>(\"b\", 128);\n      colored_item->point_set()->check_colors();\n      scene->addItem(colored_item);\n    }\n\n    std::string& comments = item->comments();\n\n    Point_set::Property_map<int> shape_id;\n    if (dialog.add_property())\n    {\n      bool added = false;\n      boost::tie (shape_id, added) = points->template add_property_map<int> (\"shape\", -1);\n      if (!added)\n      {\n        for (Point_set::iterator it = points->begin(); it != points->end(); ++ it)\n          shape_id[*it] = -1;\n      }\n\n      // Remove previously detected shapes from comments\n      std::string new_comment;\n\n      std::istringstream stream (comments);\n      std::string line;\n      while (getline(stream, line))\n      {\n        std::stringstream iss (line);\n        std::string tag;\n        if (iss >> tag && tag == \"shape\")\n          continue;\n        new_comment += line + \"\\n\";\n      }\n      comments = new_comment;\n      comments += \"shape -1 no assigned shape\\n\";\n    }\n\n    QApplication::setOverrideCursor(Qt::BusyCursor);\n\n    Ransac ransac;\n    ransac.set_input(*points, points->point_map(), points->normal_map());\n\n    std::vector<Scene_group_item *> groups;\n    groups.resize(5);\n    // Shapes to be searched for are registered by using the template Shape_factory\n    if(dialog.detect_plane()){\n      groups[0] = new Scene_group_item(\"Planes\");\n      groups[0]->setRenderingMode(Points);\n      add_shape<Traits> (ransac, CGAL::Shape_detection::Plane<Traits>());\n    }\n    if(dialog.detect_cylinder()){\n      groups[1] = new Scene_group_item(\"Cylinders\");\n      groups[1]->setRenderingMode(Points);\n      add_shape<Traits> (ransac, CGAL::Shape_detection::Cylinder<Traits>());\n    }\n    if(dialog.detect_torus()){\n      groups[2] = new Scene_group_item(\"Torus\");\n      groups[2]->setRenderingMode(Points);\n      add_shape<Traits> (ransac, CGAL::Shape_detection::Torus<Traits>());\n    }\n    if(dialog.detect_cone()){\n      groups[3] = new Scene_group_item(\"Cones\");\n      groups[3]->setRenderingMode(Points);\n      add_shape<Traits> (ransac, CGAL::Shape_detection::Cone<Traits>());\n    }\n    if(dialog.detect_sphere()){\n      groups[4] = new Scene_group_item(\"Spheres\");\n      groups[4]->setRenderingMode(Points);\n      add_shape<Traits> (ransac, CGAL::Shape_detection::Sphere<Traits>());\n    }\n\n    // The actual shape detection.\n    CGAL::Real_timer t;\n    t.start();\n    Detect_shapes_functor<Ransac> functor (ransac, op);\n    run_with_qprogressdialog<CGAL::Sequential_tag> (functor, \"Detecting shapes...\", mw);\n    t.stop();\n\n    std::cout << ransac.shapes().size() << \" shapes found in \"\n              << t.time() << \" second(s)\" << std::endl;\n\n    if (dialog.regularize ())\n      {\n        std::cerr << \"Regularization of planes... \" << std::endl;\n        typename Ransac::Plane_range planes = ransac.planes();\n        CGAL::regularize_planes (*points,\n                                 points->point_map(),\n                                 planes,\n                                 CGAL::Shape_detection::Plane_map<Traits>(),\n                                 CGAL::Shape_detection::Point_to_shape_index_map<Traits>(*points, planes),\n                                 true, true, true, true,\n                                 op.normal_threshold, op.epsilon);\n\n        std::cerr << \"done\" << std::endl;\n      }\n\n    std::map<Kernel::Point_3, QColor> color_map;\n\n    int index = 0;\n    for(boost::shared_ptr<typename Ransac::Shape> shape : ransac.shapes())\n    {\n      CGAL::Shape_detection::Cylinder<Traits> *cyl;\n      cyl = dynamic_cast<CGAL::Shape_detection::Cylinder<Traits> *>(shape.get());\n      if (cyl != nullptr){\n        if(cyl->radius() > diam){\n          continue;\n        }\n      }\n\n      if (dialog.add_property())\n      {\n        std::ostringstream oss;\n        oss << \"shape \" << index;\n        if (CGAL::Shape_detection::Plane<Traits>* s\n            = dynamic_cast<CGAL::Shape_detection::Plane<Traits> *>(shape.get()))\n          oss << \" plane \" << Kernel::Plane_3(*s) << std::endl;\n        else if (CGAL::Shape_detection::Cylinder<Traits>* s\n            = dynamic_cast<CGAL::Shape_detection::Cylinder<Traits> *>(shape.get()))\n          oss << \" cylinder axis = [\" << s->axis() << \"] radius = \" << s->radius() << std::endl;\n        else if (CGAL::Shape_detection::Cone<Traits>* s\n            = dynamic_cast<CGAL::Shape_detection::Cone<Traits> *>(shape.get()))\n          oss << \" cone apex = [\" << s->apex() << \"] axis = [\" << s->axis()\n              << \"] angle = \" << s->angle() << std::endl;\n        else if (CGAL::Shape_detection::Torus<Traits>* s\n            = dynamic_cast<CGAL::Shape_detection::Torus<Traits> *>(shape.get()))\n          oss << \" torus center = [\" << s->center() << \"] axis = [\" << s->axis()\n              << \"] R = \" << s->major_radius() << \" r = \" << s->minor_radius() << std::endl;\n        else if (CGAL::Shape_detection::Sphere<Traits>* s\n            = dynamic_cast<CGAL::Shape_detection::Sphere<Traits> *>(shape.get()))\n          oss << \" sphere center = [\" << s->center() << \"] radius = \" << s->radius() << std::endl;\n\n        comments += oss.str();\n      }\n\n      Scene_points_with_normal_item *point_item = new Scene_points_with_normal_item;\n\n      for(std::size_t i : shape->indices_of_assigned_points())\n      {\n        point_item->point_set()->insert(points->point(*(points->begin()+i)));\n        if (dialog.add_property())\n          shape_id[*(points->begin()+i)] = index;\n      }\n\n      unsigned char r, g, b;\n\n      r = static_cast<unsigned char>(64 + rand.get_int(0, 192));\n      g = static_cast<unsigned char>(64 + rand.get_int(0, 192));\n      b = static_cast<unsigned char>(64 + rand.get_int(0, 192));\n\n      point_item->setRgbColor(r, g, b);\n\n      std::size_t nb_colored_pts = 0;\n      if (dialog.generate_colored_point_set())\n      {\n        for(std::size_t i : shape->indices_of_assigned_points())\n        {\n          Point_set::iterator it = colored_item->point_set()->insert(points->point(*(points->begin()+i)));\n          ++ nb_colored_pts;\n          colored_item->point_set()->set_color(*it, r, g, b);\n        }\n        colored_item->invalidateOpenGLBuffers();\n      }\n\n      // Providing a useful name consisting of the order of detection, name of type and number of inliers\n      std::stringstream ss;\n      if (dynamic_cast<CGAL::Shape_detection::Cylinder<Traits> *>(shape.get())){\n        CGAL::Shape_detection::Cylinder<Traits> * cyl\n          = dynamic_cast<CGAL::Shape_detection::Cylinder<Traits> *>(shape.get());\n        ss << item->name().toStdString() << \"_cylinder_\" << cyl->radius() << \"_\";\n      }\n      else if (dynamic_cast<CGAL::Shape_detection::Plane<Traits> *>(shape.get()))\n        {\n          ss << item->name().toStdString() << \"_plane_\";\n\n          boost::shared_ptr<CGAL::Shape_detection::Plane<Traits> > pshape\n            = boost::dynamic_pointer_cast<CGAL::Shape_detection::Plane<Traits> > (shape);\n\n          Kernel::Point_3 ref = CGAL::ORIGIN + pshape->plane_normal ();\n\n          if (color_map.find (ref) == color_map.end ())\n            {\n              ref = CGAL::ORIGIN + (-1.) * pshape->plane_normal ();\n              if (color_map.find (ref) == color_map.end ())\n                color_map[ref] = point_item->color ();\n              else\n                point_item->setColor (color_map[ref]);\n            }\n          else\n            point_item->setColor (color_map[ref]);\n\n          if (dialog.generate_colored_point_set())\n          {\n            for (std::size_t i = 0; i < nb_colored_pts; ++ i)\n            {\n              colored_item->point_set()->set_color(*(colored_item->point_set()->end() - 1 - i), color_map[ref].red(),\n                                                   color_map[ref].green(),\n                                                   color_map[ref].blue());\n            }\n          }\n\n          ss << \"(\" << ref << \")_\";\n\n          if (dialog.generate_alpha ())\n            {\n              // If plane, build alpha shape\n              Scene_surface_mesh_item* sm_item = nullptr;\n                sm_item = new Scene_surface_mesh_item;\n\n\n              build_alpha_shape (*(point_item->point_set()), pshape,\n                                 sm_item, dialog.cluster_epsilon());\n\n              if(sm_item){\n                sm_item->setColor(point_item->color ());\n                sm_item->setName(QString(\"%1%2_alpha_shape\").arg(QString::fromStdString(ss.str()))\n                                   .arg (QString::number (shape->indices_of_assigned_points().size())));\n                sm_item->setRenderingMode (Flat);\n                sm_item->invalidateOpenGLBuffers();\n                scene->addItem(sm_item);\n                if(scene->item_id(groups[0]) == -1)\n                  scene->addItem(groups[0]);\n                scene->changeGroup(sm_item, groups[0]);\n              }\n            }\n        }\n      else if (dynamic_cast<CGAL::Shape_detection::Cone<Traits> *>(shape.get()))\n        ss << item->name().toStdString() << \"_cone_\";\n      else if (dynamic_cast<CGAL::Shape_detection::Torus<Traits> *>(shape.get()))\n        ss << item->name().toStdString() << \"_torus_\";\n      else if (dynamic_cast<CGAL::Shape_detection::Sphere<Traits> *>(shape.get()))\n        ss << item->name().toStdString() << \"_sphere_\";\n      ss << shape->indices_of_assigned_points().size();\n\n      //names[i] = ss.str(\n      point_item->setName(QString::fromStdString(ss.str()));\n      point_item->setRenderingMode(item->renderingMode());\n\n      if (dialog.generate_subset()){\n        point_item->invalidateOpenGLBuffers();\n        scene->addItem(point_item);\n        if (dynamic_cast<CGAL::Shape_detection::Cylinder<Traits> *>(shape.get()))\n        {\n          if(scene->item_id(groups[1]) == -1)\n             scene->addItem(groups[1]);\n          scene->changeGroup(point_item, groups[1]);\n        }\n        else if (dynamic_cast<CGAL::Shape_detection::Plane<Traits> *>(shape.get()))\n        {\n          point_item->point_set()->add_normal_map();\n          CGAL::Shape_detection::Plane<Traits> * plane = dynamic_cast<CGAL::Shape_detection::Plane<Traits> *>(shape.get());\n          //set normals for point_item to the plane's normal\n          for(Point_set::iterator it = point_item->point_set()->begin(); it != point_item->point_set()->end(); ++it)\n            point_item->point_set()->normal(*it) = plane->plane_normal();\n\n          if(scene->item_id(groups[0]) == -1)\n            scene->addItem(groups[0]);\n\n          point_item->invalidateOpenGLBuffers();\n          scene->changeGroup(point_item, groups[0]);\n        }\n        else if (dynamic_cast<CGAL::Shape_detection::Cone<Traits> *>(shape.get()))\n        {\n          if(scene->item_id(groups[3]) == -1)\n             scene->addItem(groups[3]);\n          scene->changeGroup(point_item, groups[3]);\n        }\n        else if (dynamic_cast<CGAL::Shape_detection::Torus<Traits> *>(shape.get()))\n        {\n          if(scene->item_id(groups[2]) == -1)\n             scene->addItem(groups[2]);\n          scene->changeGroup(point_item, groups[2]);\n        }\n        else if (dynamic_cast<CGAL::Shape_detection::Sphere<Traits> *>(shape.get()))\n        {\n          if(scene->item_id(groups[4]) == -1)\n             scene->addItem(groups[4]);\n          scene->changeGroup(point_item, groups[4]);\n        }\n      }\n      else\n        delete point_item;\n\n      ++index;\n    }\n    Q_FOREACH(Scene_group_item* group, groups)\n      if(group && group->getChildren().empty())\n        delete group;\n\n    if (dialog.generate_structured ())\n      {\n        std::cerr << \"Structuring point set... \";\n\n        Scene_points_with_normal_item *pts_full = new Scene_points_with_normal_item;\n        pts_full->point_set()->add_normal_map();\n\n        typename Ransac::Plane_range planes = ransac.planes();\n        CGAL::structure_point_set (*points,\n                                   planes,\n                                   boost::make_function_output_iterator (build_from_pair ((*(pts_full->point_set())))),\n                                   op.cluster_epsilon,\n                                   points->parameters().\n                                   plane_map(CGAL::Shape_detection::Plane_map<Traits>()).\n                                   plane_index_map(CGAL::Shape_detection::Point_to_shape_index_map<Traits>(*points, planes)));\n\n        if (pts_full->point_set ()->empty ())\n          delete pts_full;\n        else\n          {\n            pts_full->point_set ()->unselect_all();\n            pts_full->setName(tr(\"%1 (structured)\").arg(item->name()));\n            pts_full->setRenderingMode(PointsPlusNormals);\n            pts_full->setColor(Qt::blue);\n            pts_full->invalidateOpenGLBuffers();\n            scene->addItem (pts_full);\n          }\n        std::cerr << \"done\" << std::endl;\n      }\n\n    // Updates scene\n    scene->itemChanged(index);\n\n    QApplication::restoreOverrideCursor();\n\n    item->setVisible(false);\n  }\n\n  Kernel::Point_2 to_2d (const Point_3& centroid,\n                         const Vector_3& base1,\n                         const Vector_3& base2,\n                         const Point_3& query)\n  {\n    Vector_3 v (centroid, query);\n    return Kernel::Point_2 (v * base1, v * base2);\n  }\n\n  Point_3 to_3d (const Point_3& centroid,\n                 const Vector_3& base1,\n                 const Vector_3& base2,\n                 const Kernel::Point_2& query)\n  {\n    return centroid + query.x() * base1 + query.y() * base2;\n  }\n\n    template<typename Plane>\n    void build_alpha_shape (Point_set& points, boost::shared_ptr<Plane> plane,\n                          Scene_surface_mesh_item* sm_item, double epsilon);\n\n}; // end Polyhedron_demo_point_set_shape_detection_plugin\n\nvoid Polyhedron_demo_point_set_shape_detection_plugin::on_actionDetectShapesSM_triggered() {\n\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n\n  Scene_surface_mesh_item* sm_item =\n  qobject_cast<Scene_surface_mesh_item*>(scene->item(index));\n\n  if(sm_item) {\n\n    // Get a surface mesh.\n    SMesh* mesh = sm_item->polyhedron();\n    if(mesh == nullptr) return;\n\n    Point_set_demo_point_set_shape_detection_dialog dialog;\n\n    dialog.ransac->setEnabled(false);\n    dialog.m_regularize->setEnabled(false);\n    dialog.m_generate_structured->setEnabled(false);\n    dialog.label_4->setEnabled(false);\n    dialog.m_cluster_epsilon_field->setEnabled(false);\n    dialog.groupBox_3->setEnabled(false);\n    //todo: check default values\n    dialog.m_epsilon_field->setValue(0.01*sm_item->diagonalBbox());\n    std::size_t nb_faces = mesh->number_of_faces();\n    dialog.m_min_pts_field->setValue((std::max)(static_cast<int>(0.01*nb_faces), 1));\n    if(!dialog.exec()) return;\n\n    if(dialog.min_points() > static_cast<unsigned int>(nb_faces))\n      dialog.m_min_pts_field->setValue(static_cast<unsigned int>(nb_faces));\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n    if (dialog.region_growing()) {\n      detect_shapes_with_region_growing_sm(sm_item, dialog);\n    }\n\n    dialog.ransac->setEnabled(true);\n    dialog.m_regularize->setEnabled(true);\n    dialog.m_generate_structured->setEnabled(true);\n    dialog.label_4->setEnabled(true);\n    dialog.m_cluster_epsilon_field->setEnabled(true);\n    dialog.groupBox_3->setEnabled(true);\n\n    // Update scene.\n    scene->itemChanged(index);\n    QApplication::restoreOverrideCursor();\n    sm_item->setVisible(false);\n  }\n}\n\nvoid Polyhedron_demo_point_set_shape_detection_plugin::on_actionDetect_triggered() {\n\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n\n  Scene_points_with_normal_item* item =\n    qobject_cast<Scene_points_with_normal_item*>(scene->item(index));\n\n  if(item)\n    {\n      // Gets point set\n      Point_set* points = item->point_set();\n\n      if(points == nullptr)\n        return;\n\n      //Epic_kernel::FT diag = sqrt(((points->bounding_box().max)() - (points->bounding_box().min)()).squared_length());\n\n      // Gets options\n      Point_set_demo_point_set_shape_detection_dialog dialog;\n      if(!dialog.exec())\n        return;\n      if(dialog.min_points() > static_cast<unsigned int>(points->size()))\n        dialog.m_min_pts_field->setValue(static_cast<unsigned int>(points->size()));\n\n      QApplication::setOverrideCursor(Qt::WaitCursor);\n      if (dialog.region_growing())\n      {\n        detect_shapes_with_region_growing(item, dialog);\n      }\n      else\n      {\n        detect_shapes_with_ransac(item, dialog);\n      }\n\n      // Updates scene\n      scene->itemChanged(index);\n\n      QApplication::restoreOverrideCursor();\n\n      item->setVisible(false);\n    }\n}\n\ntemplate<typename Plane>\nvoid Polyhedron_demo_point_set_shape_detection_plugin::build_alpha_shape\n(Point_set& points,  boost::shared_ptr<Plane> plane, Scene_surface_mesh_item* sm_item, double epsilon)\n{\n  typedef Kernel::Point_2  Point_2;\n  typedef CGAL::Alpha_shape_vertex_base_2<Kernel> Vb;\n  typedef CGAL::Alpha_shape_face_base_2<Kernel>  Fb;\n  typedef CGAL::Triangulation_data_structure_2<Vb,Fb> Tds;\n  typedef CGAL::Delaunay_triangulation_2<Kernel,Tds> Triangulation_2;\n  typedef CGAL::Alpha_shape_2<Triangulation_2>  Alpha_shape_2;\n\n\n  std::vector<Point_2> projections;\n  projections.reserve (points.size ());\n\n  for (Point_set::const_iterator it = points.begin(); it != points.end(); ++ it)\n    projections.push_back (plane->to_2d (points.point(*it)));\n\n  Alpha_shape_2 ashape (projections.begin (), projections.end (), epsilon);\n\n  std::map<Alpha_shape_2::Vertex_handle, std::size_t> map_v2i;\n\n  Scene_polygon_soup_item *soup_item = new Scene_polygon_soup_item;\n\n  soup_item->init_polygon_soup(points.size(), ashape.number_of_faces ());\n  std::size_t current_index = 0;\n\n  for (Alpha_shape_2::Finite_faces_iterator it = ashape.finite_faces_begin ();\n       it != ashape.finite_faces_end (); ++ it)\n    {\n      if (ashape.classify (it) != Alpha_shape_2::INTERIOR)\n        continue;\n\n      for (int i = 0; i < 3; ++ i)\n        {\n          if (map_v2i.find (it->vertex (i)) == map_v2i.end ())\n            {\n              map_v2i.insert (std::make_pair (it->vertex (i), current_index ++));\n              Point p = plane->to_3d (it->vertex (i)->point ());\n              soup_item->new_vertex (p.x (), p.y (), p.z ());\n            }\n        }\n      soup_item->new_triangle (map_v2i[it->vertex (0)],\n                               map_v2i[it->vertex (1)],\n                               map_v2i[it->vertex (2)]);\n    }\n\n  soup_item->orient();\n  if(sm_item){\n    soup_item->exportAsSurfaceMesh (sm_item->polyhedron());\n  }\n\n  if (soup_item->isEmpty ())\n    {\n      std::cerr << \"POLYGON SOUP EMPTY\" << std::endl;\n      for (std::size_t i = 0; i < projections.size (); ++ i)\n        std::cerr << projections[i] << std::endl;\n\n    }\n\n  delete soup_item;\n}\n\nvoid Polyhedron_demo_point_set_shape_detection_plugin::on_actionEstimateParameters_triggered() {\n\n  CGAL::Random rand(static_cast<unsigned int>(time(nullptr)));\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n\n  Scene_points_with_normal_item* item =\n    qobject_cast<Scene_points_with_normal_item*>(scene->item(index));\n\n  if(item)\n    {\n      // Gets point set\n      Point_set* points = item->point_set();\n\n      if(points == nullptr)\n        return;\n\n      if (points->nb_selected_points() == 0)\n        {\n          QMessageBox::information(nullptr,\n                                   tr(\"Warning\"),\n                                   tr(\"Selection is empty.\\nTo estimate parameters, please select a planar section.\"));\n          return;\n        }\n\n      QApplication::setOverrideCursor(Qt::WaitCursor);\n\n      typedef CGAL::Search_traits_3<Kernel> SearchTraits_3;\n      typedef CGAL::Search_traits_adapter <Point_set::Index,\n                                           Point_set::Point_map, SearchTraits_3> Search_traits;\n      typedef CGAL::Orthogonal_k_neighbor_search<Search_traits> Neighbor_search;\n      typedef Neighbor_search::Tree Tree;\n      typedef Neighbor_search::Distance Distance;\n\n      // build kdtree\n      Tree tree(points->first_selected(),\n                points->end(),\n                Tree::Splitter(),\n                Search_traits (points->point_map())\n                );\n      Distance tr_dist(points->point_map());\n\n      Plane_3 plane;\n      CGAL::linear_least_squares_fitting_3(boost::make_transform_iterator\n                                           (points->first_selected(),\n                                            CGAL::Property_map_to_unary_function<Point_set::Point_map>\n                                            (points->point_map())),\n                                           boost::make_transform_iterator\n                                           (points->end(),\n                                            CGAL::Property_map_to_unary_function<Point_set::Point_map>\n                                            (points->point_map())),\n                                           plane,\n                                           CGAL::Dimension_tag<0>());\n\n      std::vector<double> epsilon, dispersion, cluster_epsilon;\n\n      Vector_3 norm = plane.orthogonal_vector();\n      norm = norm / std::sqrt (norm * norm);\n      for (Point_set::iterator it = points->first_selected(); it != points->end(); ++ it)\n        {\n          double dist = CGAL::squared_distance (plane, points->point(*it));\n          epsilon.push_back(dist);\n\n          double disp = std::fabs (norm * points->normal(*it));\n          dispersion.push_back (disp);\n\n          Neighbor_search search(tree, points->point(*it), 2, 0, true, tr_dist);\n          Neighbor_search::iterator nit = search.begin();\n          ++ nit;\n          double eps = nit->second;\n          cluster_epsilon.push_back(eps);\n        }\n\n      std::sort (epsilon.begin(), epsilon.end());\n      std::sort (dispersion.begin(), dispersion.end());\n      std::sort (cluster_epsilon.begin(), cluster_epsilon.end());\n\n      QApplication::restoreOverrideCursor();\n\n\n      QMessageBox::information(nullptr,\n                               tr(\"Estimated Parameters\"),\n                               tr(\"Epsilon = [%1 ; %2 ; %3 ; %4 ; %5]\\nNormal Tolerance = [%6 ; %7 ; %8 ; %9 ; %10]\\nMinimum Number of Points = %11\\nConnectivity Epsilon = [%12 ; %13 ; %14 ; %15 ; %16]\")\n                               .arg(std::sqrt(epsilon.front()))\n                               .arg(std::sqrt(epsilon[epsilon.size() / 10]))\n                               .arg(std::sqrt(epsilon[epsilon.size() / 2]))\n                               .arg(std::sqrt(epsilon[9 * epsilon.size() / 10]))\n                               .arg(std::sqrt(epsilon.back()))\n                               .arg(dispersion.back())\n                               .arg(dispersion[9 * dispersion.size() / 10])\n                               .arg(dispersion[dispersion.size() / 2])\n                               .arg(dispersion[dispersion.size() / 10])\n                               .arg(dispersion.front())\n                               .arg(points->nb_selected_points())\n                               .arg(std::sqrt(cluster_epsilon.front()))\n                               .arg(std::sqrt(cluster_epsilon[cluster_epsilon.size() / 10]))\n                               .arg(std::sqrt(cluster_epsilon[cluster_epsilon.size() / 2]))\n                               .arg(std::sqrt(cluster_epsilon[9 * cluster_epsilon.size() / 10]))\n                               .arg(std::sqrt(cluster_epsilon.back())));\n    }\n}\n\n#include <QtPlugin>\n\n#include \"Point_set_shape_detection_plugin.moc\"\n", "meta": {"hexsha": "e91df2c695e9948ed37a710208bde4206e554aba", "size": 43903, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_shape_detection_plugin.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-20T17:02:24.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-20T17:02:24.000Z", "max_issues_repo_path": "Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_shape_detection_plugin.cpp", "max_issues_repo_name": "antoniospg/cgal", "max_issues_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-10T13:32:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T12:23:20.000Z", "max_forks_repo_path": "Polyhedron/demo/Polyhedron/Plugins/Point_set/Point_set_shape_detection_plugin.cpp", "max_forks_repo_name": "antoniospg/cgal", "max_forks_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T15:26:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-21T15:26:25.000Z", "avg_line_length": 37.2374893978, "max_line_length": 203, "alphanum_fraction": 0.6237386967, "num_tokens": 10251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.44278994262131144}}
{"text": "/*\r\nCopyright (c) 2017 InversePalindrome\r\nInPal - CalculusPanel.cpp\r\nInversePalindrome.com\r\n*/\r\n\r\n\r\n#include \"CalculusPanel.hpp\"\r\n\r\n#include <wx/sizer.h>\r\n#include <wx/button.h>\r\n#include <wx/stattext.h>\r\n\r\n#include <boost/format.hpp>\r\n#include <boost/algorithm/string/trim.hpp>\r\n#include <boost/algorithm/string/replace.hpp>\r\n\r\n\r\nCalculusPanel::CalculusPanel(wxWindow* parent, MathDataDefault* mathData) :\r\n    wxPanel(parent, wxID_ANY),\r\n    mathData(mathData),\r\n    derivativeChoice(),\r\n    derivativeEntry(new wxTextCtrl(this, wxID_ANY)),\r\n    xPositionEntry(new wxTextCtrl(this, wxID_ANY)),\r\n    derivativeSolution(new wxTextCtrl(this, wxID_ANY, \"\", wxDefaultPosition, wxDefaultSize, wxTE_READONLY)),\r\n    integralEntry(new wxTextCtrl(this, wxID_ANY)),\r\n    initialXEntry(new wxTextCtrl(this, wxID_ANY)),\r\n    finalXEntry(new wxTextCtrl(this, wxID_ANY)),\r\n    integralSolution(new wxTextCtrl(this, wxID_ANY, \"\", wxDefaultPosition, wxDefaultSize, wxTE_READONLY))\r\n{\r\n    SetBackgroundColour(wxColor(128u, 128u, 128u));\r\n\r\n    auto* topSizer = new wxBoxSizer(wxVERTICAL);\r\n    auto* derivativeSizer = new wxBoxSizer(wxHORIZONTAL);\r\n    auto* derivativeButtonSizer = new wxBoxSizer(wxHORIZONTAL);\r\n    auto* integralSizer = new wxBoxSizer(wxHORIZONTAL);\r\n    auto* integralButtonSizer = new wxBoxSizer(wxHORIZONTAL);\r\n\r\n    auto* derivativeText = new wxStaticText(this, wxID_ANY, \"Derivative\");\r\n    auto* derivativeFunctionText = new wxStaticText(this, wxID_ANY, \"Function\");\r\n    auto* xPositionText = new wxStaticText(this, wxID_ANY, \"Position(X):\");\r\n\r\n    auto* integralText = new wxStaticText(this, wxID_ANY, \"Integral\");\r\n    auto* integralFunctionText = new wxStaticText(this, wxID_ANY, \"Function\");\r\n    auto* integralInitialXText = new wxStaticText(this, wxID_ANY, \"Starting Position(X):\");\r\n    auto* integralFinalXText = new wxStaticText(this, wxID_ANY, \"Final Position(X):\");\r\n\r\n    auto& font = wxFont(8u, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD);\r\n\r\n    derivativeText->SetFont(font);\r\n    xPositionText->SetFont(font);\r\n    derivativeFunctionText->SetFont(font);\r\n    integralText->SetFont(font);\r\n    integralFunctionText->SetFont(font);\r\n    integralInitialXText->SetFont(font);\r\n    integralFinalXText->SetFont(font);\r\n\r\n    wxArrayString derivativeChoices;\r\n    derivativeChoices.Add(\"First Derivative\");\r\n    derivativeChoices.Add(\"Second Derivative\");\r\n    derivativeChoices.Add(\"Third Derivative\");\r\n\r\n    derivativeChoice = new wxChoice(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, derivativeChoices);\r\n    derivativeChoice->SetStringSelection(\"First Derivative\");\r\n\r\n    auto* solveDerivativeButton = new wxButton(this, wxID_ANY, \"Solve\");\r\n    auto* solveIntegralButton = new wxButton(this, wxID_ANY, \"Solve\");\r\n\r\n    auto* clearDerivativeButton = new wxButton(this, wxID_ANY, \"Clear\");\r\n    auto* clearIntegralButton = new wxButton(this, wxID_ANY, \"Clear\");\r\n\r\n    derivativeSizer->Add(derivativeChoice, 0u, wxALL, 10u);\r\n    derivativeSizer->Add(xPositionText, 0u, wxALL, 10u);\r\n    derivativeSizer->Add(xPositionEntry, 0u, wxALL, 10u);\r\n\r\n    derivativeButtonSizer->Add(solveDerivativeButton, 0u, wxALL, 5u);\r\n    derivativeButtonSizer->Add(clearDerivativeButton, 0u, wxALL, 5u);\r\n\r\n    integralSizer->Add(integralInitialXText, 0u, wxALL, 10u);\r\n    integralSizer->Add(initialXEntry, 0u, wxALL, 10u);\r\n    integralSizer->Add(integralFinalXText, 0u, wxALL, 10u);\r\n    integralSizer->Add(finalXEntry, 0u, wxALL, 10u);\r\n\r\n    integralButtonSizer->Add(solveIntegralButton, 0u, wxALL, 5u);\r\n    integralButtonSizer->Add(clearIntegralButton, 0u, wxALL, 5u);\r\n\r\n    topSizer->AddSpacer(55u);\r\n    topSizer->Add(derivativeText, 0u, wxALL, 5u);\r\n    topSizer->Add(derivativeSolution, 0u, wxEXPAND | wxALL, 5u);\r\n    topSizer->Add(derivativeFunctionText, 0u, wxEXPAND | wxALL, 5u);\r\n    topSizer->Add(derivativeEntry, 0u, wxEXPAND | wxALL, 5u);\r\n    topSizer->Add(derivativeSizer, 0u, wxALIGN_CENTER | wxALL, 5u);\r\n    topSizer->Add(derivativeButtonSizer, 0u, wxALIGN_CENTER | wxALL, 5u);\r\n    topSizer->AddSpacer(30u);\r\n    topSizer->Add(integralText, 0u, wxALL, 5u);\r\n    topSizer->Add(integralSolution, 0u, wxEXPAND | wxALL, 5u);\r\n    topSizer->Add(integralFunctionText, 0u, wxEXPAND | wxALL, 5u);\r\n    topSizer->Add(integralEntry, 0u, wxEXPAND | wxALL, 5u);\r\n    topSizer->Add(integralSizer, 0u, wxALIGN_CENTER | wxALL, 5u);\r\n    topSizer->Add(integralButtonSizer, 0u, wxALIGN_CENTER | wxALL, 5u);\r\n\r\n    topSizer->Fit(this);\r\n    topSizer->SetSizeHints(this);\r\n\r\n    SetSizer(topSizer);\r\n\r\n    solveDerivativeButton->Bind(wxEVT_LEFT_DOWN, &CalculusPanel::OnSolveDerivative, this);\r\n    solveIntegralButton->Bind(wxEVT_LEFT_DOWN, &CalculusPanel::OnSolveIntegral, this);\r\n\r\n    clearDerivativeButton->Bind(wxEVT_LEFT_DOWN, &CalculusPanel::OnClearDerivative, this);\r\n    clearIntegralButton->Bind(wxEVT_LEFT_DOWN, &CalculusPanel::OnClearIntegral, this);\r\n}\r\n\r\nvoid CalculusPanel::OnSolveDerivative(wxMouseEvent& event)\r\n{\r\n    auto& functionEquation = this->derivativeEntry->GetValue().ToStdString();\r\n\r\n    boost::replace_all(functionEquation, \"x\", \"derivativeVariable\");\r\n\r\n    this->mathData->mathSolver.setTask(functionEquation);\r\n\r\n    long double derivativeVariable;\r\n    try\r\n    {\r\n        derivativeVariable = std::stold(this->xPositionEntry->GetValue().ToStdString());\r\n    }\r\n    catch (const std::invalid_argument & e)\r\n    {\r\n        derivativeVariable = 0;\r\n    }\r\n\r\n    this->mathData->mathSolver.addVariable(\"derivativeVariable\", derivativeVariable);\r\n\r\n    if (this->mathData->mathSolver.solve())\r\n    {\r\n        long double derivative;\r\n\r\n        if (this->derivativeChoice->GetStringSelection() == \"First Derivative\")\r\n        {\r\n            derivative = this->mathData->mathSolver.getDerivative(derivativeVariable);\r\n        }\r\n        else if (this->derivativeChoice->GetStringSelection() == \"Second Derivative\")\r\n        {\r\n            derivative = this->mathData->mathSolver.getSecondDerivative(derivativeVariable);\r\n        }\r\n        else if (this->derivativeChoice->GetStringSelection() == \"Third Derivative\")\r\n        {\r\n            derivative = this->mathData->mathSolver.getThirdDerivative(derivativeVariable);\r\n        }\r\n\r\n        auto& result = boost::str(boost::format(\"%.18f\") %\r\n            derivative);\r\n\r\n        boost::trim_right_if(result, boost::is_any_of(\"0\"));\r\n        boost::trim_right_if(result, boost::is_any_of(\".\"));\r\n\r\n        this->derivativeSolution->SetValue(result);\r\n    }\r\n}\r\n\r\nvoid CalculusPanel::OnSolveIntegral(wxMouseEvent& event)\r\n{\r\n    auto& functionEquation = this->integralEntry->GetValue().ToStdString();\r\n\r\n    boost::replace_all(functionEquation, \"x\", \"integralVariable\");\r\n\r\n    this->mathData->mathSolver.setTask(functionEquation);\r\n\r\n    long double integralVariable = 0.0;\r\n    long double initialX;\r\n    long double finalX;\r\n\r\n    this->mathData->mathSolver.addVariable(\"integralVariable\", integralVariable);\r\n\r\n    try\r\n    {\r\n        initialX = std::stold(this->initialXEntry->GetValue().ToStdString());\r\n        finalX = std::stold(this->finalXEntry->GetValue().ToStdString());\r\n    }\r\n    catch (const std::invalid_argument & e)\r\n    {\r\n        initialX = 0.0;\r\n        finalX = 1.0;\r\n    }\r\n\r\n    if (this->mathData->mathSolver.solve())\r\n    {\r\n        auto& result = boost::str(boost::format(\"%.18f\") %\r\n            this->mathData->mathSolver.getIntegral(integralVariable, initialX, finalX));\r\n        boost::trim_right_if(result, boost::is_any_of(\"0\"));\r\n        boost::trim_right_if(result, boost::is_any_of(\".\"));\r\n\r\n        this->integralSolution->SetValue(result);\r\n    }\r\n}\r\n\r\nvoid CalculusPanel::OnClearDerivative(wxMouseEvent& event)\r\n{\r\n    this->derivativeSolution->Clear();\r\n    this->derivativeEntry->Clear();\r\n    this->xPositionEntry->Clear();\r\n}\r\n\r\nvoid CalculusPanel::OnClearIntegral(wxMouseEvent& event)\r\n{\r\n    this->integralSolution->Clear();\r\n    this->integralEntry->Clear();\r\n    this->initialXEntry->Clear();\r\n    this->finalXEntry->Clear();\r\n}", "meta": {"hexsha": "70f8b7a5a329b0b7aa68b1cf0025f329a2ad0c27", "size": 7993, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CalculusPanel.cpp", "max_stars_repo_name": "saktheeswaranswan/InPalgrapher", "max_stars_repo_head_hexsha": "2afa5d327a9fffbc9aede62d8b826ef76d69405a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-07-21T14:15:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-25T21:40:47.000Z", "max_issues_repo_path": "src/CalculusPanel.cpp", "max_issues_repo_name": "InversePalindrome/Prime-Numbers", "max_issues_repo_head_hexsha": "2afa5d327a9fffbc9aede62d8b826ef76d69405a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CalculusPanel.cpp", "max_forks_repo_name": "InversePalindrome/Prime-Numbers", "max_forks_repo_head_hexsha": "2afa5d327a9fffbc9aede62d8b826ef76d69405a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0619047619, "max_line_length": 109, "alphanum_fraction": 0.6908544977, "num_tokens": 2082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.44274714126678305}}
{"text": "/**\n * \\file dcs/math/random/uniform_real_adaptor.hpp\n *\n * \\brief Adaptor for generating random numbers in [0,1] from a base generator.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_MATH_RANDOM_UNIFORM_REAL_ADAPTOR_HPP\n#define DCS_MATH_RANDOM_UNIFORM_REAL_ADAPTOR_HPP\n\n\n#include <dcs/detail/config/boost.hpp>\n\n\n#if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(101500) // 1.15\n#\terror \"Required Boost library version >= 1.15\"\n#endif // DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION\n\n\n#include <boost/random/uniform_real_distribution.hpp>\n#include <dcs/math/random/base_generator.hpp>\n#include <dcs/type_traits/remove_reference.hpp>\n#include <dcs/util/holder.hpp>\n#include <limits>\n\n\nnamespace dcs { namespace math { namespace random {\n\n/**\n * \\brief Adaptor for generating random numbers uniformly distributed in a real\n *  interval from a base random number generator.\n *\n * \\tparam BaseRandomGeneratorT The base random number generator type.\n * \\tparam RealT The result type.\n *\n * Wraps a random number generator of type \\a BaseGeneratorT for generating\n * random numbers uniformly distributed in real interval.\n * Random numbers are generated according the algorithm provided by\n * \\a BaseRandomGeneratorT.\n *\n * \\todo Make it a derived class of base_generator.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate <typename BaseRandomGeneratorT, typename RealT>\nclass uniform_real_adaptor: public base_generator<RealT>\n{\n\tprivate: typedef base_generator<RealT> base_type;\n    public: typedef BaseRandomGeneratorT base_engine_type;\n    public: typedef typename ::dcs::type_traits::remove_reference<BaseRandomGeneratorT>::type::result_type input_type;\n    public: typedef typename base_type::result_type result_type;\n    public: typedef typename base_type::ulonglong_type ulonglong_type;\n    private: typedef ::boost::random::uniform_real_distribution<result_type> adaptor_impl_type;\n\n\n    public: explicit uniform_real_adaptor(result_type min_arg = 0.0, result_type max_arg = 1.0)\n        : base_type(),\n\t\t  rng_(),\n\t\t  impl_(min_arg, max_arg)\n//\t\t  min_(min_arg),\n//\t\t  max_(max_arg)\n    {\n\t\t// empty\n    }\n\n\n\t/// Seed constructor.\n    public: uniform_real_adaptor(input_type seed, result_type min_arg, result_type max_arg)\n        : base_type(),\n\t\t  rng_(seed),\n\t\t  impl_(min_arg, max_arg)\n//\t\t  min_(min_arg),\n//\t\t  max_(max_arg)\n    {\n\t\t// empty\n    }\n\n\n\t/// Seed constructor.\n    public: uniform_real_adaptor(input_type seed)\n        : base_type(),\n\t\t  rng_(seed),\n\t\t  impl_()\n    {\n//\t\tmin_ = static_cast<result_type>((rng_.min)());\n//\t\tmax_ = static_cast<result_type>((rng_.max)());\n    }\n\n\n\t/// Copy constructor.\n    public: uniform_real_adaptor(uniform_real_adaptor const& that)\n        : base_type(that),\n\t\t  rng_(that.rng_),\n\t\t  impl_(that.impl_)\n//\t\t  min_(that.min_),\n//\t\t  max_(that.max_)\n    {\n\t\t// empty\n    }\n\n\n\t/// A Constructor: copy the base generator.\n\tpublic: uniform_real_adaptor(base_engine_type rng, result_type min_arg, result_type max_arg)\n\t\t: base_type(),\n\t\t  rng_(rng),\n\t\t  impl_(min_arg, max_arg)\n//\t\t  min_(min_arg),\n//\t\t  max_(max_arg)\n\t{\n\t\t// empty\n\t}\n\n\n\t/// A Constructor: copy the base generator.\n\tpublic: uniform_real_adaptor(base_engine_type rng)\n\t\t: base_type(),\n\t\t  rng_(rng),\n\t\t  impl_()\n//\t\t  min_((rng.min)()),\n//\t\t  max_((rng.max)())\n\t{\n\t\t// empty\n\t}\n\n\n// Support of reference-to-refernce qualifier is only available from C++0x.\n#if __cplusplus >= 201103L\n\n\t/// A constructor: move the base generator.\n    //public: uniform_real_adaptor(base_engine_type&& rng)\n    public: uniform_real_adaptor(base_engine_type& rng, result_type min_arg, result_type max_arg)\n        : base_type(),\n\t\t  rng_(rng),\n\t\t  impl_(min_arg, max_arg)\n//\t\t  min_(min_arg),\n//\t\t  max_(max_arg)\n    {\n\t\t// empty\n    }\n\n\n\t/// A constructor: move the base generator.\n    //public: uniform_real_adaptor(base_engine_type&& rng)\n    public: uniform_real_adaptor(base_engine_type& rng)\n        : base_type(),\n\t\t  rng_(rng),\n\t\t  impl_()\n//\t\t  min_((rng.min)()),\n//\t\t  max_((rng.max)())\n    {\n\t\t// empty\n    }\n\n#else\n\n\t/// A constructor: move the base generator.\n    public: uniform_real_adaptor(::dcs::util::holder<base_engine_type>& rng, result_type min_arg, result_type max_arg)\n        : base_type(),\n\t\t  rng_(rng),\n\t\t  impl_(min_arg, max_arg)\n//\t\t  min_(min_arg),\n//\t\t  max_(max_arg)\n    {\n\t\t// empty\n    }\n\n\n\t/// A constructor: move the base generator.\n    public: uniform_real_adaptor(::dcs::util::holder<base_engine_type>& rng)\n        : base_type(),\n\t\t  rng_(rng),\n\t\t  impl_()\n//\t\t  min_((rng.min)()),\n//\t\t  max_((rng.max)())\n    {\n\t\t// empty\n    }\n\n#endif\n\n\tpublic: base_engine_type base() const\n\t{\n\t\treturn rng_;\n\t}\n\n\n    private: result_type do_generate()\n    {\n//\t\tresult_type factor;\n//\t\tresult_type result;\n//\n//\t\tdo\n//\t\t{\n//\t\t\tfactor = (max_-min_)\n//\t\t\t\t\t / (\n//\t\t\t\t\t\t\tstatic_cast<result_type>(\n//\t\t\t\t\t\t\t(rng_.max)()-(rng_.min)()\n//\t\t\t\t\t\t)\n//\t\t\t\t\t\t+ static_cast<result_type>(\n//\t\t\t\t\t\t\t::std::numeric_limits<input_type>::is_integer\n//\t\t\t\t\t\t\t? 1\n//\t\t\t\t\t\t\t: 0\n//\t\t\t\t\t\t)\n//\t\t\t);\n//\t\t\tresult = static_cast<result_type>(rng_()-(rng_.min)()) * factor + min_;\n//\t\t}\n//\t\twhile (result >= max_);\n//\n//\t\treturn result;\n\n\t\treturn impl_(rng_);\n    }\n\n\n\tprivate: void do_seed()\n\t{\n\t\tthis->rng_.seed();\n\t}\n\n\n\tprivate: void do_seed(result_type s)\n\t{\n\t\trng_.seed(s);\n\t}\n\n\n\tprivate: void do_discard(ulonglong_type z)\n\t{\n\t\twhile (z--)\n\t\t{\n\t\t\trng_();\n\t\t}\n\t}\n\n\n\tprivate: result_type do_min() const\n\t{\n\t\treturn impl_.min();\n\t}\n\n\n\tprivate: result_type do_max() const\n\t{\n\t\treturn impl_.max();\n\t}\n\n    private: base_engine_type rng_;\n\tprivate: adaptor_impl_type impl_;\n};\n\n\n// Template specialization for avoid auto-wrapping (i.e., when the base\n// generator is itself a uniform_real_adaptor)\ntemplate <typename RandomNumberGeneratorT, typename RealT>\nclass uniform_real_adaptor< uniform_real_adaptor<RandomNumberGeneratorT,RealT>, RealT >: public uniform_real_adaptor<RandomNumberGeneratorT,RealT>\n{\n    public: typedef RandomNumberGeneratorT base_engine_type;\n    public: typedef typename ::dcs::type_traits::remove_reference<RandomNumberGeneratorT>::type::result_type input_type;\n    public: typedef RealT result_type;\n};\n\n}}} // Namespace dcs::math::random\n\n\n#endif // DCS_MATH_RANDOM_UNIFORM_REAL_ADAPTOR_HPP\n", "meta": {"hexsha": "3a218846142ed448f30db03dfd1708b23391583e", "size": 6877, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/random/uniform_real_adaptor.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/math/random/uniform_real_adaptor.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/math/random/uniform_real_adaptor.hpp", "max_forks_repo_name": "sguazt/dcsxx-commons", "max_forks_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3003533569, "max_line_length": 146, "alphanum_fraction": 0.6869274393, "num_tokens": 1790, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.668880247169804, "lm_q1q2_score": 0.4427471368058916}}
{"text": "/**\n * @file\n * @license BSD 3-clause\n * @copyright Copyright (c) 2020, New York University and Max Planck\n * Gesellschaft\n *\n * @brief Implements the \"Walking Control Based on Step Timing Adaptation\" foot\n * trajectory QP. The pdf can be found in https://arxiv.org/abs/1704.01271, and\n * in the `doc/` folder in this repository.\n */\n\n#pragma once\n\n#include <eigen-quadprog/QuadProg.h>\n#include <Eigen/Eigen>\n\nnamespace reactive_planners\n{\n/**\n * @brief\n */\nclass PolynomialEndEffectorTrajectory\n{\n    /*\n     * Private methods\n     */\npublic:\n    /** @brief Constructor. */\n    PolynomialEndEffectorTrajectory();\n\n    /** @brief Destructor. */\n    ~PolynomialEndEffectorTrajectory();\n\n    bool compute(const Eigen::Ref<const Eigen::Vector3d> &start_pose,\n                 const Eigen::Ref<const Eigen::Vector3d> &current_pose,\n                 const Eigen::Ref<const Eigen::Vector3d> &current_velocity,\n                 const Eigen::Ref<const Eigen::Vector3d> &current_acceleration,\n                 const Eigen::Ref<const Eigen::Vector3d> &target_pose,\n                 const double &start_time,\n                 const double &current_time,\n                 const double &end_time);\n\n    void get_next_state(const double &next_time,\n                        Eigen::Ref<Eigen::Vector3d> next_pose,\n                        Eigen::Ref<Eigen::Vector3d> next_velocity,\n                        Eigen::Ref<Eigen::Vector3d> next_acceleration);\n\n    /** @brief Display the matrices of the Problem. */\n    void print_solver() const;\n\n    /** @brief Convert the inner data to a string format. */\n    std::string to_string() const;\n\n    /*\n     * Getters\n     */\n\n    /** @brief Get the height of the flying foot. */\n    double get_mid_air_height()\n    {\n        return mid_air_height_;\n    }\n\n    /** @brief Get the last end time taken into account during the foot\n     * trajectory computation. */\n    double get_last_end_time_taken_into_account()\n    {\n        return last_end_time_seen_;\n    }\n\n    /*\n     * Setters\n     */\n\n    /** @brief Set the height of the flying foot.\n     *\n     * @param mid_air_height\n     */\n    void set_mid_air_height(double mid_air_height)\n    {\n        mid_air_height_ = mid_air_height;\n    }\n    /** @brief Set the costs of x, y, z axes, and hessian regularization.\n     *\n     * @param cost_x\n     * @param cost_y\n     * @param cost_z\n     * @param hess_regularization\n     */\n    void set_costs(double cost_x,\n                   double cost_y,\n                   double cost_z,\n                   double hess_regularization)\n    {\n        cost_x_ = cost_x;\n        cost_y_ = cost_y;\n        cost_z_ = cost_z;\n        Q_regul_ =\n            Eigen::MatrixXd::Identity(nb_var_, nb_var_) * hess_regularization;\n    }\n    /*\n     * Private methods\n     */\nprivate:\n    /**\n     * @brief Compute the time vector: \\f$ [1, t, ..., t^{ORDER}] \\f$.\n     *\n     * @param time\n     * @param time_vec\n     */\n    void t_vec(const double &time, Eigen::VectorXd &time_vec)\n    {\n        time_vec(0) = 1.0;\n        for (int i = 1; i < time_vec.size(); ++i)\n        {\n            time_vec(i) = std::pow(time, i);\n        }\n    }\n\n    /**\n     * @brief Compute the time vector first derivative.\n     *\n     * \\f[ t_vec =  [0, 1, 2*t, ..., ORDER * t^{ORDER-1}] \\f]\n     *\n     * @param time\n     * @param time_vec\n     */\n    void dt_vec(const double &time, Eigen::VectorXd &time_vec)\n    {\n        time_vec(0) = 0.0;\n        time_vec(1) = 1.0;\n        for (int i = 2; i < time_vec.size(); ++i)\n        {\n            double id = i;\n            time_vec(i) = id * std::pow(time, i - 1);\n        }\n    }\n\n    /**\n     * @brief Compute the time vector second derivative:\n     *\n     * \\f[ t_vec =  [0, 0, 2, 3*2*t..., ORDER * (ORDER-1) * t^{ORDER-2}] \\f]\n     *\n     * @param time\n     * @param time_vec\n     */\n    void ddt_vec(const double &time, Eigen::VectorXd &time_vec)\n    {\n        time_vec(0) = 0.0;\n        time_vec(1) = 0.0;\n        time_vec(2) = 2.0;\n        for (int i = 3; i < time_vec.size(); ++i)\n        {\n            double id = i;\n            time_vec(i) = id * (id - 1.0) * std::pow(time, i - 2);\n        }\n    }\n\n    /*\n     * Attributes\n     */\nprivate:\n    /*\n     * Constant problem parameters.\n     */\n\n    /** @brief Flying foot apex to be reach mid-air. */\n    double mid_air_height_;\n\n    /** @brief Number of the polynome coefficient for the trajectory on the\n     * X-axis. */\n    int nb_var_x_;\n\n    /** @brief Number of the polynome coefficient for the trajectory on the\n     * Y-axis. */\n    int nb_var_y_;\n\n    /** @brief Number of the polynome coefficient for the trajectory on the\n     * Z-axis. */\n    int nb_var_z_;\n\n    /*\n     * Variable problem parameters.\n     */\n\n    /** @brief Time vector used to compute X(t). */\n    Eigen::VectorXd time_vec_x_;\n\n    /** @brief Time vector used to compute Y(t). */\n    Eigen::VectorXd time_vec_y_;\n\n    /** @brief Time vector used to compute Z(t). */\n    Eigen::VectorXd time_vec_z_;\n\n    /** @brief Initial position before the motion. */\n    Eigen::Vector3d start_pose_;\n\n    /** @brief Current position. */\n    Eigen::Vector3d current_pose_;\n\n    /** @brief Previous computed position from the QP. */\n    Eigen::Vector3d previous_solution_pose_;\n\n    /** @brief Current velocity. */\n    Eigen::Vector3d current_velocity_;\n\n    /** @brief Current acceleration. */\n    Eigen::Vector3d current_acceleration_;\n\n    /** @brief Target pose after the motion. */\n    Eigen::Vector3d target_pose_;\n\n    /** @brief Initial time. */\n    double start_time_;\n\n    /** @brief Current time. */\n    double current_time_;\n\n    /** @brief Final time and the end of the motion. */\n    double end_time_;\n\n    /** @brief Last end time register when we computed the QP. */\n    double last_end_time_seen_;\n\n    /*\n     * QP variables\n     */\n\n    /** @brief Number of variabes in the optimization problem. */\n    int nb_var_;\n\n    /** @brief Number of equality constraints in the optimization problem. */\n    int nb_eq_;\n\n    /** @brief Number of inequality in the optimization problem. */\n    int nb_ineq_;\n\n    /** @brief Quadratic program solver.\n     *\n     * This is an eigen wrapper around the quad_prog fortran solver.\n     */\n    Eigen::QuadProgDense qp_solver_;\n\n    /** @brief Solution of the optimization problem.\n     * @see PolynomialEndEffectorTrajectory */\n    Eigen::VectorXd x_opt_;\n\n    /** @brief Lower Bound on the solution of the optimization problem.\n     * @see PolynomialEndEffectorTrajectory */\n    Eigen::VectorXd x_opt_lb_;\n\n    /** @brief Upper Bound on the solution of the optimization problem.\n     * @see PolynomialEndEffectorTrajectory */\n    Eigen::VectorXd x_opt_ub_;\n\n    /** @brief Quadratic term of the quadratic cost.\n     * @see PolynomialEndEffectorTrajectory */\n    Eigen::MatrixXd Q_;\n\n    /** @brief Quadratic term added to the quadratic cost in order regularize\n     * the system.\n     * @see PolynomialEndEffectorTrajectory */\n    Eigen::MatrixXd Q_regul_;\n\n    /** @brief Cost weights for the X-axis. */\n    double cost_x_;\n\n    /** @brief Cost weights for the Y-axis. */\n    double cost_y_;\n\n    /** @brief Cost weights for the Z-axis. */\n    double cost_z_;\n\n    /** @brief Linear term of the quadratic cost.\n     * @see PolynomialEndEffectorTrajectory */\n    Eigen::VectorXd q_;\n\n    /** @brief Linear equality matrix.\n     * @see PolynomialEndEffectorTrajectory */\n    Eigen::MatrixXd A_eq_;\n\n    /** @brief Linear equality vector.\n     * @see PolynomialEndEffectorTrajectory */\n    Eigen::VectorXd B_eq_;\n\n    /** @brief Linear inequality matrix.\n     * @see PolynomialEndEffectorTrajectory */\n    Eigen::MatrixXd A_ineq_;\n\n    /** @brief Linear inequality vector.\n     * @see PolynomialEndEffectorTrajectory */\n    Eigen::VectorXd B_ineq_;\n};\n\n}  // namespace reactive_planners\n", "meta": {"hexsha": "aa7748d5b01543a89a2c1d5adc66900eb3d7dc5a", "size": 7795, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/reactive_planners/polynomial_end_effector_trajectory.hpp", "max_stars_repo_name": "Lhumd/reactive_planners-1", "max_stars_repo_head_hexsha": "5d8bd04da3d06fb2f968aa23a0c6713dcd773f44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-09-13T10:25:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T21:55:25.000Z", "max_issues_repo_path": "include/reactive_planners/polynomial_end_effector_trajectory.hpp", "max_issues_repo_name": "Lhumd/reactive_planners-1", "max_issues_repo_head_hexsha": "5d8bd04da3d06fb2f968aa23a0c6713dcd773f44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-11-28T04:02:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T16:33:43.000Z", "max_forks_repo_path": "include/reactive_planners/polynomial_end_effector_trajectory.hpp", "max_forks_repo_name": "Lhumd/reactive_planners-1", "max_forks_repo_head_hexsha": "5d8bd04da3d06fb2f968aa23a0c6713dcd773f44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T09:07:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T21:28:10.000Z", "avg_line_length": 26.3344594595, "max_line_length": 79, "alphanum_fraction": 0.5974342527, "num_tokens": 1962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.44269037042165593}}
{"text": "/*\n * PACDEncrypter.cpp\n *\n *  Created on: 25 Jun 2018\n *      Author: scsjd\n */\n\n#include \"PolyACDEncrypter.h\"\n\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <jsoncpp/json/json.h>\n#include <string>\n#include <sstream>\n\n/*\n * \\param lambda the bit length of k1\n * \\param mu the size of the polynomial coefficients in bits\n * \\param the degree of the polynomial k2\n */\nPolyACDEncrypter::PolyACDEncrypter(int lambda, int mu, int d) {\n\tthis->mu = mu;\n\tRandomLen(k1,lambda);\n\tk2.SetLength(d+1);\n\tfor(int i =0; i < d; i++){\n\t\tNTL::ZZ tmp;\n\t\tRandomBits(tmp,mu);\n\t\tSetCoeff(k2,i,tmp);\n\t}\n\tSetCoeff(k2,d,1);\n}\n\nPolyACDEncrypter::PolyACDEncrypter(int mu, std::string& secrets) {\n\tthis->mu = mu;\n\tJson::Value root;   // will contains the root value after parsing.\n\tJson::Reader reader;\n\tbool parsingSuccessful = reader.parse(secrets,root);\n\tif (parsingSuccessful){\n\t\tstd::istringstream k1buf(root[\"k1\"].asString());\n\t\tk1buf >> k1;\n\t\tstd::istringstream k2buf(root[\"k2\"].asString());\n\t\tk2buf >> k2;\n\t}\n}\n\nPolyACDEncrypter::~PolyACDEncrypter() {\n}\n\n/*\n * Converts the key k1 (a large integer) to a string and k2 (a polynomial) to an array of strings, then writes JSON string\n */\nstd::string PolyACDEncrypter::writeSecretsToJSON(){\n\tJson::Value root;\n\tstd::ostringstream k1buf;\n\tk1buf << k1;\n\troot[\"k1\"]= k1buf.str();\n\tstd::ostringstream k2buf;\n\tk2buf << k2;\n\troot[\"k2\"]= k2buf.str();\n\tJson::FastWriter writer;\n\treturn writer.write(root);\n}\n\nNTL::ZZX PolyACDEncrypter::encrypt(NTL::ZZX& plaintext){\n\tNTL::ZZX p = k2*plaintext;\n\tlong degree = deg(p);\n\tNTL::ZZ m_n = LeadCoeff(plaintext);\n\tNTL::ZZX p2;\n\tp2.SetLength(degree-1);\n\tfor (int i = 0; i < degree-1; i++){\n\t\tSetCoeff(p2,i,NTL::coeff(p,i));\n\t}\n\tSetCoeff(p2,degree-1,p[degree-1]+k1*m_n);\n\tNTL::ZZX r;\n\tlong d = deg(k2);\n\tr.SetLength(d-1);\n\tfor(int i =0; i < d; i++){\n\t\tNTL::ZZ tmp;\n\t\tRandomBits(tmp,mu);\n\t\tSetCoeff(r,i,tmp);\n\t}\n\treturn p2+r;\n}\n\nNTL::ZZX PolyACDEncrypter::encrypt(NTL::vec_ZZ& plaintext){\n\tNTL::ZZX ptext = to_ZZX(plaintext);\n\treturn encrypt(ptext);\n}\n\nstd::pair<NTL::ZZ,NTL::ZZX> PolyACDEncrypter::getKey(){\n\treturn (std::pair<NTL::ZZ,NTL::ZZX>(k1,k2));\n}\n", "meta": {"hexsha": "39062ec9fc0d608034a823640b2aa654b0440a7b", "size": 2117, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ope_terasort/polygen/src/worker/PolyACDEncrypter.cpp", "max_stars_repo_name": "TANGO-Project/cryptango", "max_stars_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ope_terasort/polygen/src/worker/PolyACDEncrypter.cpp", "max_issues_repo_name": "TANGO-Project/cryptango", "max_issues_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ope_terasort/polygen/src/worker/PolyACDEncrypter.cpp", "max_forks_repo_name": "TANGO-Project/cryptango", "max_forks_repo_head_hexsha": "be6a2d74d238bffd3f3e899ea0eea01966097ebe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7634408602, "max_line_length": 122, "alphanum_fraction": 0.6688710439, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.44269036291271896}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb\n Copyright (C) 2005, 2006 StatPro Italia srl\n Copyright (C) 2015 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file timegrid.hpp\n    \\brief discrete time grid\n*/\n\n#ifndef quantlib_time_grid_hpp\n#define quantlib_time_grid_hpp\n\n#include <ql/errors.hpp>\n#include <ql/math/comparison.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_float.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include <vector>\n#include <numeric>\n\nnamespace QuantLib {\n\n    //! time grid class\n    class TimeGrid {\n      public:\n        //! \\name Constructors\n        //@{\n        TimeGrid() {}\n        //! Regularly spaced time-grid\n        TimeGrid(Time end, Size steps, Time start = 0.0);\n        //! Time grid with mandatory time points\n        /*! Mandatory points are guaranteed to belong to the grid.\n            No additional points are added.\n        */\n        template <class Iterator>\n        TimeGrid(Iterator begin, Iterator end)\n            : mandatoryTimes_(begin, end) {\n            initialize(begin, end, 0.0);\n        }\n        template <class Iterator, class T>\n        TimeGrid(Iterator begin, Iterator end, T start,\n                 typename boost::enable_if<boost::is_float<T> >::type* = 0)\n            : mandatoryTimes_(begin, end) {\n            initialize(begin, end, start);\n        }\n        //! Time grid with mandatory time points\n        /*! Mandatory points are guaranteed to belong to the grid.\n            Additional points are then added with regular spacing\n            between pairs of mandatory times in order to reach the\n            desired number of steps.\n        */\n        template <class Iterator, class T>\n        TimeGrid(Iterator begin, Iterator end, T steps, Time start = 0.0,\n                 typename boost::enable_if<boost::is_integral<T> >::type* = 0)\n            : mandatoryTimes_(begin, end) {\n            initialize(begin, end, steps, start);\n        }\n        //@}\n        //! \\name Time grid interface\n        //@{\n        //! returns the index i such that grid[i] = t\n        Size index(Time t) const;\n        //! returns the index i such that grid[i] is closest to t\n        Size closestIndex(Time t) const;\n        //! returns the time on the grid closest to the given t\n        Time closestTime(Time t) const {\n            return times_[closestIndex(t)];\n        }\n        const std::vector<Time>& mandatoryTimes() const {\n            return mandatoryTimes_;\n        }\n        Time dt(Size i) const { return dt_[i]; }\n        //@}\n        //! \\name sequence interface\n        //@{\n        typedef std::vector<Time>::const_iterator const_iterator;\n        typedef std::vector<Time>::const_reverse_iterator\n                                          const_reverse_iterator;\n\n        Time operator[](Size i) const { return times_[i]; }\n        Time at(Size i) const { return times_.at(i); }\n        Size size() const { return times_.size(); }\n        bool empty() const { return times_.empty(); }\n        const_iterator begin() const { return times_.begin(); }\n        const_iterator end() const { return times_.end(); }\n        const_reverse_iterator rbegin() const { return times_.rbegin(); }\n        const_reverse_iterator rend() const { return times_.rend(); }\n        Time front() const { return times_.front(); }\n        Time back() const { return times_.back(); }\n        //@}\n      private:\n        template <class Iterator>\n        void initialize(Iterator begin, Iterator end, Time start);\n        template <class Iterator>\n        void initialize(Iterator begin, Iterator end, Size steps, Time start);\n        std::vector<Time> times_;\n        std::vector<Time> dt_;\n        std::vector<Time> mandatoryTimes_;\n    };\n\n    template <class Iterator>\n    void TimeGrid::initialize(Iterator begin, Iterator end, Time start) {\n        std::sort(mandatoryTimes_.begin(), mandatoryTimes_.end());\n        QL_REQUIRE(mandatoryTimes_.front() >= start,\n                   \"times (\" << mandatoryTimes_.front() << \") less than start (\"\n                             << start << \") not allowed\");\n        std::vector<Time>::iterator e =\n            std::unique(mandatoryTimes_.begin(), mandatoryTimes_.end(),\n                        std::ptr_fun(close_enough));\n        mandatoryTimes_.resize(e - mandatoryTimes_.begin());\n\n        if (mandatoryTimes_[0] > start)\n            times_.push_back(start);\n\n        times_.insert(times_.end(), mandatoryTimes_.begin(),\n                      mandatoryTimes_.end());\n\n        std::adjacent_difference(times_.begin() + 1, times_.end(),\n                                 std::back_inserter(dt_));\n    }\n\n    template <class Iterator>\n    void TimeGrid::initialize(Iterator begin, Iterator end, Size steps, Time start) {\n        std::sort(mandatoryTimes_.begin(), mandatoryTimes_.end());\n        QL_REQUIRE(mandatoryTimes_.front() >= start,\n                   \"times less than start (\" << start << \") not allowed\");\n        std::vector<Time>::iterator e =\n            std::unique(mandatoryTimes_.begin(), mandatoryTimes_.end(),\n                        std::ptr_fun(close_enough));\n        mandatoryTimes_.resize(e - mandatoryTimes_.begin());\n\n        Time last = mandatoryTimes_.back();\n        Time dtMax;\n        // The resulting timegrid have points at times listed in the input\n        // list. Between these points, there are inner-points which are\n        // regularly spaced.\n        if (steps == 0) {\n            std::vector<Time> diff;\n            std::adjacent_difference(mandatoryTimes_.begin(),\n                                     mandatoryTimes_.end(),\n                                     std::back_inserter(diff));\n            if (diff.front() == 0.0)\n                diff.erase(diff.begin());\n            dtMax = *(std::min_element(diff.begin(), diff.end()));\n        } else {\n            dtMax = (last - start) / steps;\n        }\n\n        Time periodBegin = start;\n        times_.push_back(periodBegin);\n        for (std::vector<Time>::const_iterator t = mandatoryTimes_.begin();\n             t < mandatoryTimes_.end(); t++) {\n            Time periodEnd = *t;\n            if (periodEnd != start) {\n                // the nearest integer\n                Size nSteps = Size((periodEnd - periodBegin) / dtMax + 0.5);\n                // at least one time step!\n                nSteps = (nSteps != 0 ? nSteps : 1);\n                Time dt = (periodEnd - periodBegin) / nSteps;\n                times_.reserve(times_.size() + nSteps);\n                for (Size n = 1; n <= nSteps; ++n)\n                    times_.push_back(periodBegin + n * dt);\n            }\n            periodBegin = periodEnd;\n        }\n\n        std::adjacent_difference(times_.begin() + 1, times_.end(),\n                                 std::back_inserter(dt_));\n    }\n\n} // namespace QuantLib\n\n#endif\n", "meta": {"hexsha": "0781990012f1934a3ac2b79d8d526e45596368b8", "size": 7563, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/timegrid.hpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/timegrid.hpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/timegrid.hpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 39.8052631579, "max_line_length": 85, "alphanum_fraction": 0.5865397329, "num_tokens": 1653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.4426749614284245}}
{"text": "// Copyright 2013-2020 Lawrence Livermore National Security, LLC and other\n// HavoqGT Project Developers. See the top-level LICENSE file for details.\n//\n// SPDX-License-Identifier: MIT\n\n#include <math.h>\n#include <stdint.h>\n#include <assert.h>\n#include <utility>\n#include <boost/random.hpp>\n\n\n\nnamespace havoqgt { namespace detail {\n\ntemplate <typename DUMMY=uint64_t>\nclass preferential_attachment_helper {\npublic:\n  typedef uint64_t                  vertex_descriptor;\n  typedef typename std::pair<uint64_t,uint64_t> edge_type;\n\n  preferential_attachment_helper(uint64_t k, uint64_t m, double beta, uint64_t rng_seed=5489)\n    : m_rng(rng_seed) \n  {\n    m_k = k;\n    m_num_edges = m;\n    m_koffset = m_k*(m_k+1)/2;\n    m_ptr_mask =  ~(std::numeric_limits<vertex_descriptor>::max() >> 1);\n    m_alpha = (beta / double(m_k) + double(1)) / (beta / double(m_k) + 2);\n    //std::cout << \"beta = \" << beta << \", alpha = \" << m_alpha << std::endl;\n  }\n\n  edge_type gen_edge(uint64_t _edge_index) {\n    edge_type to_return;\n    to_return.first = calc_source(_edge_index);\n    if(_edge_index >= m_koffset)  {\n      //\n      // Generate random edge_list location based on beta model\n      boost::random::uniform_01<boost::random::mt19937> rand_prob(m_rng);\n      boost::random::uniform_int_distribution<uint64_t> uid(0,_edge_index-1);\n      uint64_t rand = uid(m_rng) * 2;\n      if(rand_prob() > m_alpha) {\n        ++rand;\n      } \n      if(rand % 2 == 0) { //this is a source vertex, we can calc!\n        to_return.second = calc_source(rand/2);\n      } else {\n        uint64_t edge_rand = rand/2;\n        if(edge_rand < m_koffset) {  //this is an early edge we can calc!\n          to_return.second = calc_target(edge_rand);\n        } else {\n          to_return.second = make_pointer(edge_rand);\n        }\n      }\n    } else {\n      to_return.second = calc_target(_edge_index);\n    }\n    return to_return;\n  }\n\n  uint64_t calc_source(uint64_t i) {\n    uint64_t to_return;\n    if(i+1>m_koffset) {\n      to_return = ((i-m_koffset)/m_k)+m_k+1;\n    } else {\n      to_return = (uint64_t) floor(double(-0.5f) + \n                  sqrt(double(0.25f)+double(2)*double(i))+1);\n    }\n    return to_return;\n  }\n\n\n  uint64_t calc_target(uint64_t i) {\n    uint64_t to_return;\n    if(i+1>m_koffset) {\n      assert(false);\n      to_return = i;\n    } else {\n      double tmp = double(-0.5f) + sqrt(double(0.25f)+double(2)*double(i))+1;\n      to_return = (uint64_t) ((tmp - floor(tmp)) * floor(tmp));\n    }\n    return to_return;\n  }\n\n  vertex_descriptor make_pointer(vertex_descriptor i) {\n    return i | m_ptr_mask;\n  }\n\n  bool is_pointer(vertex_descriptor i) {\n    return (i & m_ptr_mask) > 0;\n  }\n\n  //dereferences point\n  uint64_t value_of_pointer(vertex_descriptor i, uint64_t _num_partitions=1) {\n    i = i & ~m_ptr_mask;\n    uint64_t my_partition = i%_num_partitions;\n    uint64_t my_partition_offset = i/_num_partitions;\n    uint64_t edges_per_partition = m_num_edges / _num_partitions;\n    return my_partition * edges_per_partition + my_partition_offset;\n  }\n\n\nprivate:\n  boost::random::mt19937 m_rng;\n  uint64_t               m_k;\n  uint64_t               m_koffset;\n  vertex_descriptor      m_ptr_mask;\n  uint64_t               m_num_edges;\n  double                 m_alpha;\n};\n\n\n}} //end namespace havoqgt::detail\n", "meta": {"hexsha": "9675db66cdda3456502750a0482f370786a5ee58", "size": 3301, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/havoqgt/detail/preferential_attachment.hpp", "max_stars_repo_name": "niklas-uhl/havoqgt", "max_stars_repo_head_hexsha": "24df89686c8ca52b9f18ac86ba4e94689da2242e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2017-05-15T08:33:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T17:28:03.000Z", "max_issues_repo_path": "include/havoqgt/detail/preferential_attachment.hpp", "max_issues_repo_name": "niklas-uhl/havoqgt", "max_issues_repo_head_hexsha": "24df89686c8ca52b9f18ac86ba4e94689da2242e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-25T15:32:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-16T15:39:35.000Z", "max_forks_repo_path": "include/havoqgt/detail/preferential_attachment.hpp", "max_forks_repo_name": "niklas-uhl/havoqgt", "max_forks_repo_head_hexsha": "24df89686c8ca52b9f18ac86ba4e94689da2242e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-02-09T15:30:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-13T10:19:26.000Z", "avg_line_length": 28.9561403509, "max_line_length": 93, "alphanum_fraction": 0.6401090579, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.442570993778553}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen/Dense>\n#include <iomanip>\n#include <vector>\n#include <algorithm>\n#include <cassert>\n#include <math.h>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <experimental/filesystem>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include \"opencv2/opencv.hpp\"\n#include <limits>\n#include <chrono>\n#include <omp.h>\n#include <array>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace std::chrono;\nnamespace fs = std::experimental::filesystem;\nnamespace ba = boost::algorithm;\n\nstring LIDAR_FILE = \"\";\n\nclass projection{\npublic:\n  projection(){\n    Eigen::initParallel();\n    Eigen::setNbThreads(12);\n    MatrixXf data = readbinfile(LIDAR_FILE);\n\n    MatrixXf P;\n    P.resize(3, 4);\n    P << 609.6954, -721.4216, -1.2513,   -123.0418,\n         180.3842,  7.6448,   -719.6515, -101.0167,\n         0.9999,    1.2437e-4, 0.0105,   -0.2694;\n    auto start = high_resolution_clock::now();  \n\n    data = points_filter(P, data); \n    cv::Mat result = DenseMap(data, 4);\n    auto stop = high_resolution_clock::now();\n    auto duration = duration_cast<microseconds>(stop - start);\n    cout << duration.count() << \" microseconds\" << endl;\n\n    double minVal, maxVal;\n    cv::Point minLoc, maxLoc;\n    cv::minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc);\n    result = 255 * (result - minVal) / (maxVal - minVal);\n    result.convertTo(result, CV_8UC1);\n    cv::imshow(\"result\", result);\n    cv::waitKey(0);\n  }\n\n  MatrixXf readbinfile(const string dir){\n\n    ifstream fin(dir.c_str(), ios::binary);\n    assert(fin);\n  \n    fin.seekg(0, ios::end);\n    const size_t num_elements = fin.tellg() / sizeof(float);\n    fin.seekg(0, ios::beg);\n  \n    vector<float> l_data(num_elements);\n    fin.read(reinterpret_cast<char*>(&l_data[0]), num_elements*sizeof(float));\n  \n    MatrixXf data = Map<MatrixXf>(l_data.data(), 4, l_data.size()/4);\n  \n    return data;\n  }\n\n  MatrixXf points_filter(MatrixXf &P, MatrixXf &data){\n    data = P * data;\n    vector<int> v;\n    omp_set_num_threads(16);\n    #pragma omp parallel\n    {\n      vector<int> v1;\n      #pragma omp for nowait\n      for (int j = 0; j < data.cols(); j++){\n        if (data(2, j) > 0){\n          float x = data(0, j) / data(2, j);\n          float y = data(1, j) / data(2, j);\n          if ( (x > 0 && x < COL - 0.5) && (y > 0 && y < ROW - 0.5) )\n            v1.push_back(j);\n        }\n      }\n      #pragma omp critical\n      v.insert(v.end(), v1.begin(), v1.end());\n    }\n    MatrixXf result;\n    result.resize(3, v.size());\n    result.fill(0.);\n    cout << data.rows() << \" \" << data.cols() << endl;\n    omp_set_num_threads(16);\n    #pragma omp parallel\n    { \n      MatrixXf res_private;\n      res_private.resize(3, v.size());\n      res_private.fill(0.);\n      #pragma omp for nowait\n      for (auto i = 0; i < v.size(); i++){\n        res_private(0, i) = data(0, v[i]) / data(2, v[i]);\n        res_private(1, i) = data(1, v[i]) / data(2, v[i]);\n        res_private(2, i) = data(2, v[i]);\n\n      }\n      #pragma omp critical\n      result += res_private;\n    }\n    return result;\n  }\n\n  cv::Mat DenseMap(MatrixXf &data, int grid){\n    int ng = 2 * grid + 1;\n\n    cv::Mat map, mD;\n    map = cv::Mat::zeros(ROW, COL, CV_32FC1);\n    mD = cv::Mat::zeros(ROW, COL, CV_32FC1);\n    omp_set_num_threads(8);\n    #pragma omp parallel\n    {\n      #pragma omp for nowait\n      for (auto i = 0; i < data.cols(); i++){\n        map.at<float>(round(data(1, i)), round(data(0, i))) = \n          sqrt(pow(data(0, i) - round(data(0, i)), 2) + \n               pow(data(1, i) - round(data(1, i)), 2));\n        mD.at<float>(round(data(1, i)), round(data(0, i))) = data(2, i);\n      }\n    }\n\n    cv::Mat output;\n    output = cv::Mat::zeros(ROW, COL, CV_32FC1);\n    omp_set_num_threads(128);\n    #pragma omp parallel\n    {\n      #pragma omp for nowait\n      for (auto i = 0; i < ROW; i++){\n        for (auto j = 0; j < COL; j++){\n          if (i - grid < 0 || i + grid >= ROW)\n            continue;\n          if (j - grid < 0 || j + grid >= COL) \n            continue;\n          float s = 0;\n          for (auto r = -grid; r < grid + 1; r++){\n            for (auto c = -grid; c < grid + 1; c++){\n              float map_val = map.at<float>(i+r, j+c);\n              if (map_val != 0){\n                output.at<float>(i, j) += \n                  mD.at<float>(i+r, j+c) / map.at<float>(i+r, j+c);\n                s += 1 / map.at<float>(i+r, j+c);\n              }\n            }\n          }\n          if (s == 0){\n            s = 1;\n          }\n          output.at<float>(i, j) /= s;\n        }\n      }\n    }\n    return output;\n  }\n\nprivate:\n  const int ROW = 375;\n  const int COL = 1242;\n\n};\n\nint main(){\n  projection p;\n}", "meta": {"hexsha": "92f01b91c0da61f82696373d22b8263f0f3eebb5", "size": 4794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bilateral.cpp", "max_stars_repo_name": "fangkd8/DenseDepthMap", "max_stars_repo_head_hexsha": "f30497bdd2c611eaf4270cfc7fb033a669e3b69c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-10-10T17:50:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T08:47:14.000Z", "max_issues_repo_path": "bilateral.cpp", "max_issues_repo_name": "fangkd8/DenseDepthMap", "max_issues_repo_head_hexsha": "f30497bdd2c611eaf4270cfc7fb033a669e3b69c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bilateral.cpp", "max_forks_repo_name": "fangkd8/DenseDepthMap", "max_forks_repo_head_hexsha": "f30497bdd2c611eaf4270cfc7fb033a669e3b69c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T12:37:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T12:37:23.000Z", "avg_line_length": 27.2386363636, "max_line_length": 78, "alphanum_fraction": 0.5442219441, "num_tokens": 1468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4425597857185211}}
{"text": "//-------------------------------------------------------------------\n// The code was written by Vikas C. Raykar\n// and is copyrighted under the Lessr GPL:\n//\n// Copyright (C) 2006 Vikas C. Raykar\n//\n// This program is free software; you can redistribute it and/or modify\n// it under the terms of the GNU Lesser General Public License as\n// published by the Free Software Foundation; version 2.1 or later.\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n// See the GNU Lesser General Public License for more details.\n// You should have received a copy of the GNU Lesser General Public\n// License along with this program; if not, write to the Free Software\n// Foundation, Inc., 59 Temple Place - Suite 330, Boston,\n// MA 02111-1307, USA.\n//\n// The author may be contacted via email at: vikas(at)cs(.)umd(.)edu\n//-------------------------------------------------------------------\n\n//-------------------------------------------------------------\n// File    : FastUnivariateDensityDerivative.cpp\n// Purpose : Implementation for for FastUnivariateDensityDerivative\n// Author  : Vikas C. Raykar (vikas@cs.umd.edu)\n// Date    : September 17, 2005\n//-------------------------------------------------------------\n\n#include <math.h>\n#include <boost/python.hpp>\n#define min(a, b) (((a) < (b)) ? (a) : (b))\n#define max(a, b) (((a) > (b)) ? (a) : (b))\n#define P_UL 500\n#define R 1.0\nnamespace python = boost::python;\n//-------------------------------------------------------------------\n// Constructor.\n//\n// PURPOSE\n// -------\n// Initialize the class.\n// Read the parameters.\n// Choose the parameter for the algorithm.\n// Space subdivision.\n// Compute the constant a.\n// Compute B or all the clusters.\n//\n// PARAMETERS\n// ----------\n// NSources\t\t      --> number of sources, N.\n// MTargets\t\t      --> number of targets, M.\n// pSources\t\t      --> pointer to sources, px(N).\n// pTargets           --> pointer to the targets, py(M).\n// Bandwidth\t\t  --> the source bandwidth, h.\n// Order              --> order of the derivative, r.\n// epsilon            --> desired error, eps.\n// pDensityDerivative --> pointer the the evaluated Density\n//-------------------------------------------------------------------\n\nclass FastUnivariateDensityDerivative {\n\npublic:\n    //constructor\n    FastUnivariateDensityDerivative(\n        int     NSources,\n        int     MTargets,\n        python::list pSources,\n        python::list pTargets,\n        double  Bandwidth,\n        int     Order,\n        double  epsilon);\n\n    python::list pDensityDerivative;\n\n    //destructor\n    ~FastUnivariateDensityDerivative();\n\n    //function to evaluate the Density Derivative\n    void evaluate();\n\n    //function to evaluate the Hermite polynomial.\n    double hermite(double x, int r);\n\nprivate:\n    int N; //number of sources.\n    int M; //number of targets.\n    double* px; //pointer to sources, (N).\n    double* py; //pointer to the targets, (M).\n    double h; //the source bandwidth.\n    int r; //the rth density derivative.\n    double eps; //the desired error\n    double* pD; //pointer to the evaluated Density Derivative, (M).\n\n\n    double rx;\n    double rr;\n    double ry;\n    int K;\n    int p;\n    double h_square;\n    double two_h_square;\n\n    double* pClusterCenter;\n    int* pClusterIndex;\n\n    int num_of_a_terms;\n    double* a_terms;\n\n    int num_of_b_terms;\n    double* b_terms;\n\n    double pi;\n    double q;\n\n    void* operator new[](size_t s) { return malloc(s); }\n    void operator delete[](void* mem) { free(mem); }\n\n    int factorial(int n);\n    double* converter_double(python::list lis);\n    python::list converter_list(double* lis);\n    void choose_parameters();\n    void space_sub_division();\n    void compute_a();\n    void compute_b();\n};\n\nFastUnivariateDensityDerivative::FastUnivariateDensityDerivative(\n    int NSources,\n    int MTargets,\n    python::list pSources,\n    python::list pTargets,\n    double Bandwidth,\n    int Order,\n    double epsilon)\n{\n    // Read the arguments.\n    N = NSources;\n    M = MTargets;\n    px = converter_double(pSources);\n    h = Bandwidth;\n    r = Order;\n    py = converter_double(pTargets);\n    pD = new double[N];\n    eps = epsilon;\n\n    h_square = h * h;\n    two_h_square = 2 * h_square;\n\n    pi = 3.14159265358979;\n    q = (pow(-1, r)) / (sqrt(2 * pi) * N * (pow(h, (r + 1))));\n\n    // Choose the parameters for the algorithm.\n    choose_parameters();\n\n    // Space sub-division\n    space_sub_division();\n\n    // Compute the constant a\n    compute_a();\n\n    // Compute the constant B\n    compute_b();\n}\n\ndouble* FastUnivariateDensityDerivative::converter_double(python::list lis)\n{\n    int length = len(lis);\n    double* temp = new double[length];\n    for (int i = 0; i < length; i++)\n    {\n        temp[i] = python::extract<double>(lis[i]);\n    }\n    return temp;\n}\n\npython::list FastUnivariateDensityDerivative::converter_list(double* lis)\n{\n    python::list temp;\n    for (int i = 0; i < N; i++)\n    {\n        temp.append(lis[i]);\n    }\n    return temp;\n}\n//-------------------------------------------------------------------\n// Destructor.\n//-------------------------------------------------------------------\nFastUnivariateDensityDerivative::~FastUnivariateDensityDerivative()\n{\n    delete[] a_terms;\n    delete[] b_terms;\n}\n\n//-------------------------------------------------------------------\n// Compute the factorial.\n//-------------------------------------------------------------------\nint FastUnivariateDensityDerivative::factorial(int n)\n{\n    int fact = 1;\n    for (int i = 1; i <= n; i++) {\n        fact = fact * i;\n    }\n    return fact;\n}\n\n//-------------------------------------------------------------------\n// Choose the parameters\n// 1. rx --> interval length.\n// 2. K  --> number of intervals.\n// 3. rr --> cutoff radius.\n// 4. ry --> cluster cutoff radius.\n// 5. p  --> truncation number.\n//-------------------------------------------------------------------\n\nvoid FastUnivariateDensityDerivative::choose_parameters()\n{\n    // 1. rx --> interval length.\n    rx = h / 2;\n\n    // 2. K  --> number of intervals.\n    K = (int)ceil(1.0 / rx);\n    rx = 1.0 / K;\n    double rx_square = rx * rx;\n\n    // 3. rr --> cutoff radius.\n    double r_term = sqrt((double)factorial(r));\n    rr = min(R, 2 * h * sqrt(log(r_term / eps)));\n\n    // 4. ry --> cluster cutoff radius.\n    ry = rx + rr;\n\n    // 5. p  --> truncation number.\n    p = 0;\n    double error = 1;\n    double temp = 1;\n    double comp_eps = eps / r_term;\n    while ((error > comp_eps) & (p <= P_UL)) {\n        p++;\n        double b = min(((rx + sqrt((rx_square) + (8 * p * h_square))) / 2), ry);\n        double c = rx - b;\n        temp = temp * (((rx * b) / h_square) / p);\n        error = temp * (exp(-(c * c) / 2 * two_h_square));\n    }\n    p = p + 1;\n}\n\n//-------------------------------------------------------------------\n// Space subdivision\n//-------------------------------------------------------------------\nvoid FastUnivariateDensityDerivative::space_sub_division()\n{\n\n    // 1. Cluster Centers\n    pClusterCenter = new double[K];\n    for (int i = 0; i < K; i++) {\n        pClusterCenter[i] = (i * rx) + (rx / 2);\n    }\n\n    //2. Allocate each source to the corresponding interval\n    pClusterIndex = new int[N];\n    for (int i = 0; i < N; i++) {\n        pClusterIndex[i] = min((int)floor(px[i] / rx), K - 1);\n    }\n}\n\n//-------------------------------------------------------------------\n// Compute the contant term a_{lm}.\n// l=0...floor(r/2)\n// m=0...r-2l\n//-------------------------------------------------------------------\nvoid FastUnivariateDensityDerivative::compute_a()\n{\n    double r_factorial = (double)factorial(r);\n    double* l_constant;\n    l_constant = new double[((int)floor((double)r / 2)) + 1];\n    l_constant[0] = 1;\n    for (int l = 1; l <= (int)floor((double)r / 2); l++) {\n        l_constant[l] = l_constant[l - 1] * (-1.0 / (2 * l));\n    }\n    double* m_constant;\n    m_constant = new double[r + 1];\n    m_constant[0] = 1;\n    for (int m = 1; m <= r; m++) {\n        m_constant[m] = m_constant[m - 1] * (-1.0 / m);\n    }\n    num_of_a_terms = 0;\n    for (int l = 0; l <= (int)floor((double)r / 2); l++) {\n        for (int m = 0; m <= r - (2 * l); m++) {\n            num_of_a_terms++;\n        }\n    }\n    a_terms = new double[num_of_a_terms];\n    int k = 0;\n    for (int l = 0; l <= (int)floor((double)r / 2); l++) {\n        for (int m = 0; m <= r - (2 * l); m++) {\n            a_terms[k] = (l_constant[l] * m_constant[m] * r_factorial) / ((double)factorial(r - (2 * l) - m));\n            k++;\n        }\n    }\n\n    delete[] l_constant;\n    delete[] m_constant;\n}\n\n//-------------------------------------------------------------------\n// Compute the contant term B^{n}_{km} for all the clusters.\n// n=0...K-1\n// k=0...p-1\n// m=0...r\n//-------------------------------------------------------------------\nvoid FastUnivariateDensityDerivative::compute_b()\n{\n    num_of_b_terms = K * p * (r + 1);\n    b_terms = new double[num_of_b_terms];\n    double* k_factorial;\n    k_factorial = new double[p];\n    k_factorial[0] = 1;\n    for (int i = 1; i < p; i++) {\n        k_factorial[i] = k_factorial[i - 1] / i;\n    }\n    double* temp3;\n    temp3 = new double[p + r];\n    for (int n = 0; n < K; n++) {\n        for (int k = 0; k < p; k++) {\n            for (int m = 0; m < r + 1; m++) {\n                b_terms[(n * p * (r + 1)) + ((r + 1) * k) + m] = 0.0;\n            }\n        }\n    }\n    for (int i = 0; i < N; i++) {\n        int cluster_number = pClusterIndex[i];\n        double temp1 = (px[i] - pClusterCenter[cluster_number]) / h;\n        double temp2 = exp(-temp1 * temp1 / 2);\n        temp3[0] = 1;\n        for (int k = 1; k < p + r; k++) {\n            temp3[k] = temp3[k - 1] * temp1;\n        }\n        for (int k = 0; k < p; k++) {\n            for (int m = 0; m < r + 1; m++) {\n                b_terms[(cluster_number * p * (r + 1)) + ((r + 1) * k) + m] += (temp2 * temp3[k + m]);\n            }\n        }\n    }\n    for (int n = 0; n < K; n++) {\n        for (int k = 0; k < p; k++) {\n            for (int m = 0; m < r + 1; m++) {\n                b_terms[(n * p * (r + 1)) + ((r + 1) * k) + m] *= (k_factorial[k] * q);\n            }\n        }\n    }\n\n    delete[] k_factorial;\n    delete[] temp3;\n}\n\n//-------------------------------------------------------------------\n// Actual function to evaluate the Univariate Density Derivative.\n//-------------------------------------------------------------------\nvoid FastUnivariateDensityDerivative::evaluate()\n{\n    double* temp3 = new double[p + r];\n    for (int j = 0; j < M; j++) {\n        pD[j] = 0.0;\n        int target_cluster_number = min((int)floor(py[j] / rx), K - 1);\n        double temp1 = py[j] - pClusterCenter[target_cluster_number];\n        double dist = abs(temp1);\n        while (dist <= ry && target_cluster_number < K && target_cluster_number >= 0) {\n            double temp2 = exp(-temp1 * temp1 / two_h_square);\n            double temp1h = temp1 / h;\n            temp3[0] = 1;\n            for (int i = 1; i < p + r; i++) {\n                temp3[i] = temp3[i - 1] * temp1h;\n            }\n            for (int k = 0; k <= p - 1; k++) {\n                int dummy = 0;\n                for (int l = 0; l <= (int)floor((double)r / 2); l++) {\n                    for (int m = 0; m <= r - (2 * l); m++) {\n                        pD[j] = pD[j] + (a_terms[dummy] * b_terms[(target_cluster_number * p * (r + 1)) + ((r + 1) * k) + m] * temp2 * temp3[k + r - (2 * l) - m]);\n                        dummy++;\n                    }\n                }\n            }\n            target_cluster_number++;\n            temp1 = py[j] - pClusterCenter[target_cluster_number];\n            dist = abs(temp1);\n        }\n        target_cluster_number = min((int)floor(py[j] / rx), K - 1) - 1;\n        if (target_cluster_number >= 0) {\n            double temp1 = py[j] - pClusterCenter[target_cluster_number];\n            double dist = abs(temp1);\n            while (dist <= ry && target_cluster_number < K && target_cluster_number >= 0) {\n                double temp2 = exp(-temp1 * temp1 / two_h_square);\n                double temp1h = temp1 / h;\n                temp3[0] = 1;\n                for (int i = 1; i < p + r; i++) {\n                    temp3[i] = temp3[i - 1] * temp1h;\n                }\n                for (int k = 0; k <= p - 1; k++) {\n                    int dummy = 0;\n                    for (int l = 0; l <= (int)floor((double)r / 2); l++) {\n                        for (int m = 0; m <= r - (2 * l); m++) {\n                            pD[j] = pD[j] + (a_terms[dummy] * b_terms[(target_cluster_number * p * (r + 1)) + ((r + 1) * k) + m] * temp2 * temp3[k + r - (2 * l) - m]);\n                            dummy++;\n                        }\n                    }\n                }\n                target_cluster_number--;\n                temp1 = py[j] - pClusterCenter[target_cluster_number];\n                dist = abs(temp1);\n            }\n        }\n    }\n    pDensityDerivative = converter_list(pD);\n    delete[] temp3;\n}\n\nBOOST_PYTHON_MODULE(fast_deriv)\n{\n    namespace python = boost::python;\n    python::class_<FastUnivariateDensityDerivative>(\"FastUnivariateDensityDerivative\", \n        python::init<int, \n                     int, \n                     python::list,\n                     python::list,\n                     double,\n                     int,\n                     double\n                    >())\n        .def(\"evaluate\", &FastUnivariateDensityDerivative::evaluate)\n        .def_readonly(\"pD\", &FastUnivariateDensityDerivative::pDensityDerivative)\n    ;\n\n}\n", "meta": {"hexsha": "61bef1ba23227337dfe02ab12e8f5ec973b23488", "size": 13694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fast_deriv.cpp", "max_stars_repo_name": "maskarb/fisher_information", "max_stars_repo_head_hexsha": "947affe310752222920cffc0bf006d80706d696f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fast_deriv.cpp", "max_issues_repo_name": "maskarb/fisher_information", "max_issues_repo_head_hexsha": "947affe310752222920cffc0bf006d80706d696f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fast_deriv.cpp", "max_forks_repo_name": "maskarb/fisher_information", "max_forks_repo_head_hexsha": "947affe310752222920cffc0bf006d80706d696f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5529953917, "max_line_length": 167, "alphanum_fraction": 0.4817438294, "num_tokens": 3586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.4425546843839258}}
{"text": "// from http://perso.ens-lyon.fr/philippe.theveny/cise.pdf\n\n#include <iostream>\n#include <utility>\n#include <cmath> // _Decimal64?\n\n#include <boost/tr1/cmath.hpp>\n#include <boost/math/special_functions.hpp>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n\ntypedef boost::multiprecision::number<\n            boost::multiprecision::backends::cpp_bin_float<\n                106,\n                boost::multiprecision::backends::digit_base_2,\n                void,\n                boost::int16_t, -1022, 1023>,\n            boost::multiprecision::et_off>\n        cpp_bin_float_double_double;\n\ntypedef boost::multiprecision::number<\n            boost::multiprecision::backends::cpp_bin_float<\n                1000,\n                boost::multiprecision::backends::digit_base_2,\n                void,\n                boost::int16_t, -1022, 1023>,\n            boost::multiprecision::et_off>\n        cpp_bin_float_1000b;\n\nusing boost::multiprecision::cpp_dec_float;\nusing boost::multiprecision::cpp_bin_float_single;\nusing boost::multiprecision::cpp_bin_float_double;\nusing boost::multiprecision::cpp_bin_float_double_extended;\nusing boost::multiprecision::cpp_bin_float_quad;\n\ntypedef boost::multiprecision::number<cpp_dec_float<64> > mp_type;\n\n// This is busted: https://svn.boost.org/trac/boost/ticket/11764\n//typedef boost::multiprecision::cpp_bin_float_single mp_type;\n\n//typedef boost::multiprecision::cpp_bin_float_double mp_type;\n//typedef boost::multiprecision::cpp_bin_float_double_extended mp_type;\n//typedef boost::multiprecision::cpp_bin_float_quad mp_type;\n//typedef cpp_bin_float_double_double mp_type;\n//typedef cpp_bin_float_1000b mp_type;\n\n//typedef _Decimal64 mp_type;\n\nint main (void)\n{\n    mp_type a = sin((mp_type)1e22);\n    mp_type b = log((mp_type)17.1);\n    mp_type c = exp((mp_type)0.42);\n    mp_type d = 173746*a + 94228*b - 78487*c;\n    std::cout << std::setprecision(std::numeric_limits<mp_type>::max_digits10) << d << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "6035698ac93189cccdd9313afdf5d2ce7e96e852", "size": 2018, "ext": "cc", "lang": "C++", "max_stars_repo_path": "boost/theveny.cc", "max_stars_repo_name": "jeffhammond/multiprecision", "max_stars_repo_head_hexsha": "6006d27e542c2eaa0f10f8074a0704263923986e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-06T16:59:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T16:24:15.000Z", "max_issues_repo_path": "boost/theveny.cc", "max_issues_repo_name": "jeffhammond/multiprecision", "max_issues_repo_head_hexsha": "6006d27e542c2eaa0f10f8074a0704263923986e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/theveny.cc", "max_forks_repo_name": "jeffhammond/multiprecision", "max_forks_repo_head_hexsha": "6006d27e542c2eaa0f10f8074a0704263923986e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-08T23:27:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-08T23:27:36.000Z", "avg_line_length": 34.7931034483, "max_line_length": 97, "alphanum_fraction": 0.7061446977, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.44253103341794264}}
{"text": "/**\n * Could really represent any coordinate that has X/Y/Z axises.\n *\n * Copyright 2013 Bruce Ide\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n */\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#ifndef _HPP_XYZ_COORDINATE\n#define _HPP_XYZ_COORDINATE\n\nnamespace fr {\n\n  namespace coordinates {\n\n    class xyz_coordinate {\n    protected:\n      double x,y,z;\n\n      inline double limit(double val, double lower, double upper)\n      {\n\tassert(upper > lower);\n\tdouble retval = val;\n\tif (val > upper) {\n\t  retval = upper;\n\t} else if (val < lower) {\n\t  retval = lower;\n\t}\n\treturn retval;\n      }\n\n      inline Eigen::Vector3d unit_vec(const Eigen::Vector3d &vec)\n      {\n\tEigen::Vector3d retval;\n\tdouble nrm = vec.norm();\n\tretval = vec / nrm;\n\treturn retval;\n      }\n\n      // Generic interpolate between two points\n\n      Eigen::Vector3d interpolate_3x3(const Eigen::Vector3d &this_vec, const double &time_now, const Eigen::Vector3d &next_vec, const double &time_other, const double &time_between)\n      {\n\tEigen::Quaternion<double> quat(1.0, 0.0, 0.0, 0.0);\n\tdouble this_norm = this_vec.norm();\n\tdouble next_norm = next_vec.norm();\n\tEigen::Vector3d this_uv = unit_vec(this_vec);\n\tEigen::Vector3d next_uv = unit_vec(next_vec);\n\tdouble x = this_uv.dot(next_uv);\n\tdouble y = limit(x,-1.0, 1.0);\n\tdouble theta = acos(y);\n\tdouble adjust = (time_between - time_now) / (time_other - time_now);\n\tdouble factor = ((next_norm - this_norm) * adjust + this_norm) / this_norm;\n\ttheta = theta * adjust;\n\tdouble sto2 = sin(theta / 2.0);\n\tEigen::Vector3d ax = next_vec.cross(this_vec);\n\tEigen::Vector3d ax_uv = unit_vec(ax);\n\tdouble qx, qy, qz, qw;\n\tqx = ax_uv(0) * sto2;\n\tqy = ax_uv(1) * sto2;\n\tqz = ax_uv(2) * sto2;\n\tqw = cos(theta/2.0);\n\tquat = Eigen::Quaternion<double>(qw,qx,qy,qz);\n\tEigen::Vector3d z = this_vec * factor;\n\tEigen::Quaternion<double> z_q(0.0, z(0), z(1), z(2));\n\tEigen::Quaternion<double> q1 = z_q * quat;\n\tEigen::Quaternion<double> retaq = quat.inverse();\n\tEigen::Quaternion<double> q2 = retaq * q1;\n\treturn q2.vec();\n      }\n\n    public:\n      xyz_coordinate(const double &x, const double &y, const double &z) : x(x), y(y), z(z) \n      {\n      }\n\n      xyz_coordinate(const xyz_coordinate &copy) : x(copy.get_x()), y(copy.get_y()), z(copy.get_z())\n      {\n      }\n\n      // Ah ah, ah ha! Yep, I'm planning children classes!\n      virtual ~xyz_coordinate()\n      {\n      }\n\n      virtual double get_x() const { return x; }\n      virtual double get_y() const { return y; }\n      virtual double get_z() const { return z; }\n\n      virtual Eigen::Vector3d get_xyz() const\n      {\n\tEigen::Vector3d retval;\n\tretval << x,y,z;\n\treturn retval;\n      }\n\n    };\n\n  }\n}\n\n#endif\n", "meta": {"hexsha": "b0da2c90cb78812355c3873cf29f683abff22c35", "size": 3193, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "xyz_coordinate.hpp", "max_stars_repo_name": "FlyingRhenquest/coordinates", "max_stars_repo_head_hexsha": "b6558b7e49e9927b4867456f4ce9fd81ec8bab81", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xyz_coordinate.hpp", "max_issues_repo_name": "FlyingRhenquest/coordinates", "max_issues_repo_head_hexsha": "b6558b7e49e9927b4867456f4ce9fd81ec8bab81", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T12:28:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-10T06:36:53.000Z", "max_forks_repo_path": "xyz_coordinate.hpp", "max_forks_repo_name": "FlyingRhenquest/coordinates", "max_forks_repo_head_hexsha": "b6558b7e49e9927b4867456f4ce9fd81ec8bab81", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-02-08T16:17:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T14:48:59.000Z", "avg_line_length": 27.525862069, "max_line_length": 181, "alphanum_fraction": 0.6567491387, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4425310272534924}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#include <cmath>\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\n#include \"cavity/Cavity.hpp\"\n#include \"cavity/Element.hpp\"\n#include \"green/IGreensFunction.hpp\"\n#include \"utils/MathUtils.hpp\"\n\n/*! \\file SolverImpl.cpp\n *  \\brief Functions common to all solvers\n *  \\author Roberto Di Remigio\n *  \\date 2015\n */\n\n/*! \\brief Builds the **anisotropic** IEFPCM matrix\n *  \\param[in] cav the discretized cavity\n *  \\param[in] gf_i Green's function inside the cavity\n *  \\param[in] gf_o Green's function outside the cavity\n *  \\return the \\f$ \\mathbf{K} = \\mathbf{T}^{-1}\\mathbf{R}\\mathbf{A} \\f$ matrix\n *\n *  This function calculates the PCM matrix. We use the following definitions:\n *  \\f[\n *     \\begin{align}\n *       \\mathbf{T} &=\n *      \\left(2\\pi\\mathbf{I} - \\mathbf{D}_\\mathrm{e}\\mathbf{A}\\right)\\mathbf{S}_\\mathrm{i}\n *      +\\mathbf{S}_\\mathrm{e}\\left(2\\pi\\mathbf{I} +\n *      \\mathbf{A}\\mathbf{D}_\\mathrm{i}^\\dagger\\right) \\\\\n *      \\mathbf{R} &=\n *      \\left(2\\pi\\mathbf{A}^{-1} - \\mathbf{D}_\\mathrm{e}\\right) -\n *      \\mathbf{S}_\\mathrm{e}\\mathbf{S}^{-1}_\\mathrm{i}\\left(2\\pi\\mathbf{A}^{-1}-\\mathbf{D}_\\mathrm{i}\\right)\n *     \\end{align}\n *  \\f]\n *  The matrix is not symmetrized and is not symmetry packed.\n */\ninline Eigen::MatrixXd anisotropicIEFMatrix(const Cavity & cav, const IGreensFunction & gf_i, const IGreensFunction & gf_o)\n{\n  // The total size of the cavity\n  PCMSolverIndex cavitySize = cav.size();\n  // The number of irreps in the group\n  int nrBlocks = cav.pointGroup().nrIrrep();\n  // The size of the irreducible portion of the cavity\n  int dimBlock = cav.irreducible_size();\n\n  // Compute SI, DI and SE, DE on the whole cavity, regardless of symmetry\n  TIMER_ON(\"Computing SI\");\n  Eigen::MatrixXd SI = gf_i.singleLayer(cav.elements());\n  TIMER_OFF(\"Computing SI\");\n  TIMER_ON(\"Computing DI\");\n  Eigen::MatrixXd DI = gf_i.doubleLayer(cav.elements());\n  TIMER_OFF(\"Computing DI\");\n  TIMER_ON(\"Computing SE\");\n  Eigen::MatrixXd SE = gf_o.singleLayer(cav.elements());\n  TIMER_OFF(\"Computing SE\");\n  TIMER_ON(\"Computing DE\");\n  Eigen::MatrixXd DE = gf_o.doubleLayer(cav.elements());\n  TIMER_OFF(\"Computing DE\");\n\n  // Perform symmetry blocking\n  // If the group is C1 avoid symmetry blocking, we will just pack the fullPCMMatrix\n  // into \"block diagonal\" when all other manipulations are done.\n  if (cav.pointGroup().nrGenerators() != 0) {\n    TIMER_ON(\"Symmetry blocking\");\n    symmetryBlocking(DI, cavitySize, dimBlock, nrBlocks);\n    symmetryBlocking(SI, cavitySize, dimBlock, nrBlocks);\n    symmetryBlocking(DE, cavitySize, dimBlock, nrBlocks);\n    symmetryBlocking(SE, cavitySize, dimBlock, nrBlocks);\n    TIMER_OFF(\"Symmetry blocking\");\n  }\n\n  Eigen::MatrixXd a = cav.elementArea().asDiagonal();\n  Eigen::MatrixXd Id = Eigen::MatrixXd::Identity(cavitySize, cavitySize);\n\n  TIMER_ON(\"Assemble T matrix\");\n  Eigen::MatrixXd T = ((2 * M_PI * Id - DE * a) * SI + SE * (2 * M_PI * Id + a * DI.adjoint().eval()));\n  TIMER_OFF(\"Assemble T matrix\");\n\n  TIMER_ON(\"Assemble R matrix\");\n  Eigen::MatrixXd R = ((2 * M_PI * Id - DE * a) - SE * SI.ldlt().solve((2 * M_PI * Id - DI * a)));\n  TIMER_OFF(\"Assemble R matrix\");\n\n  TIMER_ON(\"Assemble T^-1R matrix\");\n  Eigen::MatrixXd fullPCMMatrix = T.partialPivLu().solve(R);\n  TIMER_OFF(\"Assemble T^-1R matrix\");\n\n  return fullPCMMatrix;\n}\n\n/*! \\brief Builds the **isotropic** IEFPCM matrix\n *  \\param[in] cav the discretized cavity\n *  \\param[in] gf_i Green's function inside the cavity\n *  \\param[in] epsilon permittivity outside the cavity\n *  \\return the \\f$ \\mathbf{K} = \\mathbf{T}^{-1}\\mathbf{R}\\mathbf{A} \\f$ matrix\n *\n *  This function calculates the PCM matrix. We use the following definitions:\n *  \\f[\n *     \\begin{align}\n *       \\mathbf{T} &=\n *      \\left(2\\pi\\frac{\\varepsilon+1}{\\varepsilon-1}\\mathbf{I} - \\mathbf{D}_\\mathrm{i}\\mathbf{A}\\right)\\mathbf{S}_\\mathrm{i} \\\\\n *      \\mathbf{R} &=\n *      \\left(2\\pi\\mathbf{A}^{-1} - \\mathbf{D}_\\mathrm{i}\\right)\n *     \\end{align}\n *  \\f]\n *  The matrix is not symmetrized and is not symmetry packed.\n */\ninline Eigen::MatrixXd isotropicIEFMatrix(const Cavity & cav, const IGreensFunction & gf_i, double epsilon)\n{\n  // The total size of the cavity\n  PCMSolverIndex cavitySize = cav.size();\n  // The number of irreps in the group\n  int nrBlocks = cav.pointGroup().nrIrrep();\n  // The size of the irreducible portion of the cavity\n  int dimBlock = cav.irreducible_size();\n\n  // Compute SI and DI on the whole cavity, regardless of symmetry\n  TIMER_ON(\"Computing SI\");\n  Eigen::MatrixXd SI = gf_i.singleLayer(cav.elements());\n  TIMER_OFF(\"Computing SI\");\n  TIMER_ON(\"Computing DI\");\n  Eigen::MatrixXd DI = gf_i.doubleLayer(cav.elements());\n  TIMER_OFF(\"Computing DI\");\n\n  // Perform symmetry blocking\n  // If the group is C1 avoid symmetry blocking, we will just pack the fullPCMMatrix\n  // into \"block diagonal\" when all other manipulations are done.\n  if (cav.pointGroup().nrGenerators() != 0) {\n    TIMER_ON(\"Symmetry blocking\");\n    symmetryBlocking(DI, cavitySize, dimBlock, nrBlocks);\n    symmetryBlocking(SI, cavitySize, dimBlock, nrBlocks);\n    TIMER_OFF(\"Symmetry blocking\");\n  }\n\n  Eigen::MatrixXd a = cav.elementArea().asDiagonal();\n  Eigen::MatrixXd Id = Eigen::MatrixXd::Identity(cavitySize, cavitySize);\n\n  // Tq = -Rv -> q = -(T^-1 * R)v = -Kv\n  // T = (2 * M_PI * fact * aInv - DI) * a * SI; R = (2 * M_PI * aInv - DI)\n  // fullPCMMatrix_ = K = T^-1 * R * a\n  // 1. Form T\n  double fact = (epsilon + 1.0)/(epsilon - 1.0);\n  TIMER_ON(\"Assemble T matrix\");\n  Eigen::MatrixXd T = (2 * M_PI * fact * Id - DI * a) * SI;\n  TIMER_OFF(\"Assemble T matrix\");\n\n  TIMER_ON(\"Assemble R matrix\");\n  Eigen::MatrixXd R = (2 * M_PI * Id - DI * a);\n  TIMER_OFF(\"Assemble R matrix\");\n\n  TIMER_ON(\"Assemble T^-1R matrix\");\n  Eigen::MatrixXd fullPCMMatrix = T.partialPivLu().solve(R);\n  TIMER_OFF(\"Assemble T^-1R matrix\");\n\n  return fullPCMMatrix;\n}\n\n/*! \\brief Builds the **anisotropic** \\f$ \\mathbf{T}_\\varepsilon \\f$ matrix\n *  \\param[in] cav the discretized cavity\n *  \\param[in] gf_i Green's function inside the cavity\n *  \\param[in] gf_o Green's function outside the cavity\n *  \\return the \\f$ \\mathbf{T}_\\varepsilon \\f$ matrix\n *\n *  We use the following definition:\n *  \\f[\n *      \\mathbf{T}_\\varepsilon =\n *      \\left(2\\pi\\mathbf{I} - \\mathbf{D}_\\mathrm{e}\\mathbf{A}\\right)\\mathbf{S}_\\mathrm{i}\n *      +\\mathbf{S}_\\mathrm{e}\\left(2\\pi\\mathbf{I} +\n *      \\mathbf{A}\\mathbf{D}_\\mathrm{i}^\\dagger\\right)\n *  \\f]\n *  The matrix is not symmetrized and is not symmetry packed.\n */\ninline Eigen::MatrixXd anisotropicTEpsilon(const Cavity & cav, const IGreensFunction & gf_i, const IGreensFunction & gf_o)\n{\n  // The total size of the cavity\n  PCMSolverIndex cavitySize = cav.size();\n  // The number of irreps in the group\n  int nrBlocks = cav.pointGroup().nrIrrep();\n  // The size of the irreducible portion of the cavity\n  int dimBlock = cav.irreducible_size();\n\n  // Compute SI, DI and SE, DE on the whole cavity, regardless of symmetry\n  Eigen::MatrixXd SI = gf_i.singleLayer(cav.elements());\n  Eigen::MatrixXd DI = gf_i.doubleLayer(cav.elements());\n  Eigen::MatrixXd SE = gf_o.singleLayer(cav.elements());\n  Eigen::MatrixXd DE = gf_o.doubleLayer(cav.elements());\n\n  // Perform symmetry blocking\n  // If the group is C1 avoid symmetry blocking, we will just pack the matrix\n  // into \"block diagonal\" when all other manipulations are done.\n  if (cav.pointGroup().nrGenerators() != 0) {\n    symmetryBlocking(DI, cavitySize, dimBlock, nrBlocks);\n    symmetryBlocking(SI, cavitySize, dimBlock, nrBlocks);\n    symmetryBlocking(DE, cavitySize, dimBlock, nrBlocks);\n    symmetryBlocking(SE, cavitySize, dimBlock, nrBlocks);\n  }\n\n  Eigen::MatrixXd a = cav.elementArea().asDiagonal();\n  Eigen::MatrixXd Id = Eigen::MatrixXd::Identity(cavitySize, cavitySize);\n\n  // Form T\n  return ((2 * M_PI * Id - DE * a) * SI + SE * (2 * M_PI * Id + a * DI.adjoint().eval()));\n}\n\n/*! \\brief Builds the **isotropic** \\f$ \\mathbf{T}_\\varepsilon \\f$ matrix\n *  \\param[in] cav the discretized cavity\n *  \\param[in] gf_i Green's function inside the cavity\n *  \\param[in] epsilon permittivity outside the cavity\n *  \\return the \\f$ \\mathbf{T}_\\varepsilon \\f$ matrix\n *\n *  We use the following definition:\n *  \\f[\n *      \\mathbf{T}_\\varepsilon =\n *      \\left(2\\pi\\frac{\\varepsilon+1}{\\varepsilon-1}\\mathbf{I} - \\mathbf{D}_\\mathrm{i}\\mathbf{A}\\right)\\mathbf{S}_\\mathrm{i}\n *  \\f]\n *  The matrix is not symmetrized and is not symmetry packed.\n */\ninline Eigen::MatrixXd isotropicTEpsilon(const Cavity & cav, const IGreensFunction & gf_i, double epsilon)\n{\n  // The total size of the cavity\n  PCMSolverIndex cavitySize = cav.size();\n  // The number of irreps in the group\n  int nrBlocks = cav.pointGroup().nrIrrep();\n  // The size of the irreducible portion of the cavity\n  int dimBlock = cav.irreducible_size();\n\n  // Compute SI, DI and SE, DE on the whole cavity, regardless of symmetry\n  Eigen::MatrixXd SI = gf_i.singleLayer(cav.elements());\n  Eigen::MatrixXd DI = gf_i.doubleLayer(cav.elements());\n\n  // Perform symmetry blocking\n  // If the group is C1 avoid symmetry blocking, we will just pack the matrix\n  // into \"block diagonal\" when all other manipulations are done.\n  if (cav.pointGroup().nrGenerators() != 0) {\n    symmetryBlocking(DI, cavitySize, dimBlock, nrBlocks);\n    symmetryBlocking(SI, cavitySize, dimBlock, nrBlocks);\n  }\n\n  Eigen::MatrixXd a = cav.elementArea().asDiagonal();\n  Eigen::MatrixXd Id = Eigen::MatrixXd::Identity(cavitySize, cavitySize);\n\n  double fact = (epsilon + 1.0)/(epsilon - 1.0);\n  return (2 * M_PI * fact * Id - DI * a) * SI;\n}\n\n/*! \\brief Builds the **anisotropic** \\f$ \\mathbf{R}_\\infty \\f$ matrix\n *  \\param[in] cav the discretized cavity\n *  \\param[in] gf_i Green's function inside the cavity\n *  \\param[in] gf_o Green's function outside the cavity\n *  \\return the \\f$ \\mathbf{R}_\\infty\\mathbf{A} \\f$ matrix\n *\n *  We use the following definition:\n *  \\f[\n *      \\mathbf{R}_\\infty =\n *      \\left(2\\pi\\mathbf{A}^{-1} - \\mathbf{D}_\\mathrm{e}\\right) -\n *      \\mathbf{S}_\\mathrm{e}\\mathbf{S}^{-1}_\\mathrm{i}\\left(2\\pi\\mathbf{A}^{-1}-\\mathbf{D}_\\mathrm{i}\\right)\n *  \\f]\n *  The matrix is not symmetrized and is not symmetry packed.\n */\ninline Eigen::MatrixXd anisotropicRinfinity(const Cavity & cav, const IGreensFunction & gf_i, const IGreensFunction & gf_o)\n{\n  // The total size of the cavity\n  PCMSolverIndex cavitySize = cav.size();\n  // The number of irreps in the group\n  int nrBlocks = cav.pointGroup().nrIrrep();\n  // The size of the irreducible portion of the cavity\n  int dimBlock = cav.irreducible_size();\n\n  // Compute SI, DI and SE, DE on the whole cavity, regardless of symmetry\n  Eigen::MatrixXd SI = gf_i.singleLayer(cav.elements());\n  Eigen::MatrixXd DI = gf_i.doubleLayer(cav.elements());\n  Eigen::MatrixXd SE = gf_o.singleLayer(cav.elements());\n  Eigen::MatrixXd DE = gf_o.doubleLayer(cav.elements());\n\n  // Perform symmetry blocking\n  // If the group is C1 avoid symmetry blocking, we will just pack the matrix\n  // into \"block diagonal\" when all other manipulations are done.\n  if (cav.pointGroup().nrGenerators() != 0) {\n    symmetryBlocking(DI, cavitySize, dimBlock, nrBlocks);\n    symmetryBlocking(SI, cavitySize, dimBlock, nrBlocks);\n    symmetryBlocking(DE, cavitySize, dimBlock, nrBlocks);\n    symmetryBlocking(SE, cavitySize, dimBlock, nrBlocks);\n  }\n\n  Eigen::MatrixXd a = cav.elementArea().asDiagonal();\n  Eigen::MatrixXd Id = Eigen::MatrixXd::Identity(cavitySize, cavitySize);\n\n  // Form R\n  return ((2 * M_PI * Id - DE * a) - SE * SI.ldlt().solve((2 * M_PI * Id - DI * a)));\n}\n\n/*! \\brief Builds the **isotropic** \\f$ \\mathbf{R}_\\infty \\f$ matrix\n *  \\param[in] cav the discretized cavity\n *  \\param[in] gf_i Green's function inside the cavity\n *  \\return the \\f$ \\mathbf{R}_\\infty\\mathbf{A} \\f$ matrix\n *\n *  We use the following definition:\n *  \\f[\n *      \\mathbf{R}_\\infty =\n *      \\left(2\\pi\\mathbf{A}^{-1} - \\mathbf{D}_\\mathrm{i}\\right)\n *  \\f]\n *  The matrix is not symmetrized and is not symmetry packed.\n */\ninline Eigen::MatrixXd isotropicRinfinity(const Cavity & cav, const IGreensFunction & gf_i)\n{\n  // The total size of the cavity\n  PCMSolverIndex cavitySize = cav.size();\n  // The number of irreps in the group\n  int nrBlocks = cav.pointGroup().nrIrrep();\n  // The size of the irreducible portion of the cavity\n  int dimBlock = cav.irreducible_size();\n\n  // Compute SI, DI and SE, DE on the whole cavity, regardless of symmetry\n  Eigen::MatrixXd DI = gf_i.doubleLayer(cav.elements());\n\n  // Perform symmetry blocking\n  // If the group is C1 avoid symmetry blocking, we will just pack the matrix\n  // into \"block diagonal\" when all other manipulations are done.\n  if (cav.pointGroup().nrGenerators() != 0) {\n    symmetryBlocking(DI, cavitySize, dimBlock, nrBlocks);\n  }\n\n  Eigen::MatrixXd a = cav.elementArea().asDiagonal();\n  Eigen::MatrixXd Id = Eigen::MatrixXd::Identity(cavitySize, cavitySize);\n\n  return (2 * M_PI * Id - DI * a);\n}\n", "meta": {"hexsha": "727896078634aa575d50396d638d00ddfd0033df", "size": 14066, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/solver/SolverImpl.hpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/solver/SolverImpl.hpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/solver/SolverImpl.hpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7344632768, "max_line_length": 128, "alphanum_fraction": 0.6785866629, "num_tokens": 4156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.442531021089042}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n\n/**\n * @file PIR.cpp\n * @brief A simple PIR implementation\n */\n#include <cstdint>\n#include <NTL/GF2X.h>\n#include <NTL/BasicThreadPool.h>\n#include \"intraSlot.h\"\n#include \"matmul.h\"\n\n#if (defined(__unix__) || defined(__unix) || defined(unix))\n#include <sys/time.h>\n#include <sys/resource.h>\n#endif\n\nNTL_CLIENT\n\n// Simplistic un-optimized encoding/decoding routines\nstatic void encodeBits(GF2X& poly,\n                       const vector<uint8_t>& data, long idx, long d)\n{\n  FHE_TIMER_START;\n  for (long i=0; i<d; i++, idx++) {\n    // compute byte index from bit index\n    long byteIdx = idx / 8;\n    if (byteIdx < lsize(data)) {\n      long coef = (data[byteIdx] >> (idx % 8))&1;\n      NTL::SetCoeff(poly, i, coef);\n    }\n  }\n}\nstatic void decodeBits(vector<uint8_t>& data, long idx,\n                       const GF2X& poly, long d)\n{\n  FHE_TIMER_START;\n  for (long i=0; i<d; i++, idx++) {\n    // compute byte index from bit index\n    long byteIdx = idx / 8;\n    if (byteIdx < lsize(data)) {\n      uint8_t coef = NTL::conv<uint>(NTL::coeff(poly,i)) & 1;\n      data[byteIdx] |= (coef << (idx % 8));\n    }\n  }\n}\n\nstatic void decodeDBentry(vector<uint8_t>& entry,\n                          const vector<GF2X>& encoded, long d)\n{\n  long dbSize = divc(lsize(encoded)*d, 8); // size in bytes\n  \n}\n\n\n// Encoding a \"database\" in a matrix, the number of entries in the\n// database is upto the size of the 1st dimension, i.e. sizeOfDim(0).\n// The number of bits per entry is upto phi(m)/sizeOfDim(0).\nclass DBMatrix : public MatMul1D_derived<PA_GF2> {\npublic:\n  PA_INJECT(PA_GF2)\n\nprivate:\n  vector< vector< vector< RX > > > data;\n  const EncryptedArray& ea;\n\npublic:\n  virtual ~DBMatrix() {}\n  DBMatrix(const EncryptedArray& _ea, const vector< vector<uint8_t> >&db):\n    ea(_ea)\n  {\n    RBak bak; bak.save(); ea.getAlMod().restoreContext();\n    long n = ea.size();\n    long d = ea.getDegree();\n    long D = ea.sizeOfDimension(0);\n\n    // vector< vector<uint8_t> > db2(lsize(db)); // sanity check\n    // for (long i=0; i<lsize(db); i++)\n    //   db2[i].resize(db[i].size(), 0);\n\n    // Allocate space for the matrices\n    data.resize(n/D);\n    for (long k=0; k < n/D; k++) {\n      data[k].resize(D);\n      for (long i=0; i<D; i++)\n\tdata[k][i].resize(D, RX()); // initialize to D empty polynomials\n    }\n\n    /* Each database entry is encoded in upto n/D partial rows, each partial\n     * row has D cells of d bits each. In the picture here D=3, n/D=2.\n     *\n     *  (X1 X2 X3 | X4 X5 X6)  // database entry X\n     *  (Y1 Y2 Y3 | Y4 Y5 Y6)  // database entry Y\n     *  (Z1 Z2 Z3 | Z4 Z5 Z6)  // database entry Z\n     * \n     *  For example, the database entry Z is encoded in the two row vectors\n     *  (Z1 Z2 Z3), (Z4 Z5 Z6). Each Zi is a degree-d binary polynomial.\n     */\n\n    for (long k=0; k<n/D; k++) { // go over row vectors\n\n      // Encode the next d*D bits of each entry db[i]\n      for (long i=0; i<D; i++) {  \n\tfor (long j=0; j<D; j++) { // encode next d bit of db[i]\n          long dataIdx= (k*D+j)*d; // how many bits were already encoded\n          if (dataIdx < 8*lsize(db[i])) { // more bits to encode\n            encodeBits(data[k][i][j], db[i], dataIdx, d);\n            // decodeBits(db2[i], dataIdx, data[k][i][j], d);\n          }\n\t}\n      }\n    }\n    // for (long i=0; i<lsize(db); i++)\n    //   for (long j=0; j<lsize(db[i]); j++)\n    //     assert(db[i][j] == db2[i][j]);\n  }\n\n  const EncryptedArray& getEA() const override { return ea; }\n  bool multipleTransforms() const override { return true; }\n  long getDim() const override { return 0; }\n\n  bool get(RX& out, long i, long j, long k) const override {\n    long n = ea.size();\n    long D = ea.sizeOfDimension(0);\n\n    assert(i >= 0 && i < D);\n    assert(j >= 0 && j < D);\n    assert(k >= 0 && k < n/D);\n    if (IsZero(data[k][i][j])) return true;\n    out = data[k][i][j];\n    return false;\n  }\n};\n\n\nstatic MatMul1D*\nbuildDBMatrix(const EncryptedArray& ea, const vector< vector<uint8_t> >&db)\n{\n  FHE_TIMER_START;\n  assert (ea.getTag()==PA_GF2_tag);\n  return new DBMatrix(ea, db);\n}\n\nstatic vector< vector<uint8_t> >*\nbuildRandomDB(const EncryptedArray& ea)\n{\n  FHE_TIMER_START;\n  assert (ea.getTag()==PA_GF2_tag);\n  vector< vector<uint8_t> >* v = new(vector< vector<uint8_t> >);\n  v->resize(ea.sizeOfDimension(0));\n  long entrySize = ea.size()/(ea.sizeOfDimension(0)*8);\n  for (long i=0; i<ea.sizeOfDimension(0); i++) {\n    (*v)[i].resize(entrySize);\n    for (long j=0; j<entrySize; j++)\n      (*v)[i][j] = NTL::RandomBits_long(8);\n  }\n  return v;\n}\n\nbool DoTest(const EncryptedArray& ea, \n            const SecKey& secretKey, bool minimal, bool verbose)\n{\n  // choose a random database that fits in one ciphertext\n  std::unique_ptr<vector< vector<uint8_t> > > db(buildRandomDB(ea));\n\n  // Encode the database as a matrix\n  FHE_NTIMER_START(PIR_EncodeDBasMatrix);\n  std::unique_ptr< MatMul1D > mat(buildDBMatrix(ea, *db));\n  MatMul1D::ExecType mat_exec(*mat, minimal);\n  mat_exec.upgrade();\n  FHE_NTIMER_STOP(PIR_EncodeDBasMatrix);\n\n  // Choose a random index into the database\n  long idx = NTL::RandomBnd(lsize(*db));\n\n  // Encrypt index as a unit vector\n  FHE_NTIMER_START(PIR_EncryptSelectionAsVector);\n  Ctxt ctxt(secretKey);\n  {vector<long> slots(ea.size(), 0);\n  for (long i=0; i<ea.size(); i++) {\n    if (ea.coordinate(0,i) == idx)\n      slots[i]=1;\n  }\n  ea.encrypt(ctxt, secretKey, slots);\n  }\n  FHE_NTIMER_STOP(PIR_EncryptSelectionAsVector);\n\n  // Do the matrix-vector multiply\n  mat_exec.mul(ctxt);\n\n  // Decrypt and check the result\n  FHE_NTIMER_START(PIR_Decrypt_Result);\n\n  vector<ZZX> slots;\n  ea.decrypt(ctxt, secretKey, slots); // decrypt the ciphertext vector\n\n  // maximum size of an entry in bits\n  long d = ea.getDegree();\n  long nOverD = ea.size()/ea.sizeOfDimension(0);\n  long entrySize = (ea.size()*d) / ea.sizeOfDimension(0);\n  vector<uint8_t> dbEntry(divc(entrySize,8), 0);\n\n  // Go over the slots and put each one in its right place\n  for (long i=0; i<ea.size(); i++) {\n    // represent i as (ii,jj) with ii index along dim 0 and jj the rest\n    std::pair<long,long> pp = ea.getAlMod().getZMStar().breakIndexByDim(i,0);\n    long idxx = pp.first*ea.sizeOfDimension(0) + pp.second;\n    decodeBits(dbEntry, idxx*d, conv<GF2X>(slots[i]), d);\n  }\n  FHE_NTIMER_STOP(PIR_Decrypt_Result);\n\n  // check that we've got the right answer\n  for (long i=0; i<std::min(lsize(dbEntry), lsize((*db)[idx])); i++)\n    if (dbEntry[i] != (*db)[idx][i]) {\n      cout << \"Grrr@*, entry[\"<<i<<\"]=\"<<((int)dbEntry[i])<<\"!=db[\"<<idx<<\"][\"\n           <<i<<\"]=\"<<((int)(*db)[idx][i])<<endl;\n      return false;\n    }\n  return true;\n}\n\n\nint ks_strategy = 0;\n// 0 == default\n// 1 == full\n// 2 == BSGS\n// 3 == minimal\n\n\nvoid  TestIt(Context& context, bool verbose)\n{\n  if (verbose) {\n    context.zMStar.printout();\n    std::cout <<\"  #threads=\"<<NTL::AvailableThreads()\n              <<\", security=\" << context.securityLevel()<<endl<< endl;\n  }\n\n  SecKey secretKey(context);\n  const PubKey& publicKey = secretKey;\n  secretKey.GenSecKey(/*w=*/64); // A Hamming-weight-w secret key\n\n  bool minimal = (ks_strategy == 3);\n\n  // we call addSomeFrbMatrices for all strategies except minimal\n\n  switch (ks_strategy) {\n  case 0: \n    addSome1DMatrices(secretKey);\n    addSomeFrbMatrices(secretKey);\n    break;\n  case 1: \n    add1DMatrices(secretKey);\n    addSomeFrbMatrices(secretKey);\n    break;\n  case 2: \n    addBSGS1DMatrices(secretKey);\n    addSomeFrbMatrices(secretKey);\n    break;\n  case 3: \n    addMinimal1DMatrices(secretKey);\n    addMinimalFrbMatrices(secretKey);\n    break;\n\n   default:\n     Error(\"bad ks_strategy\");\n   }\n  EncryptedArray ea(context, context.alMod);\n  bool okSoFar=true;\n\n  cout << \" * \"<<ea.sizeOfDimension(0)<<\"-entry DB, |entry|=\"\n       << (ea.size()*ea.getDegree()) << \" bits. \";\n  for (long i=0; i<5; i++)\n    if (!DoTest(ea, secretKey, minimal, verbose)) {\n      okSoFar = false;\n      break;\n    }\n  if (okSoFar)\n    cout << \"Nice!!\\n\\n\";\n\n  if (verbose) {\n    printAllTimers(cout);\n#if (defined(__unix__) || defined(__unix) || defined(unix))\n      struct rusage rusage;\n      getrusage( RUSAGE_SELF, &rusage );\n      cout << \"  rusage.ru_maxrss=\"<<rusage.ru_maxrss << endl;\n#endif\n  }\n\n}\n\n\nint main(int argc, char *argv[]) \n{\n  ArgMapping amap;\n\n  long m=2047;\n  amap.arg(\"m\", m, \"defines the cyclotomic polynomial Phi_m(X)\");\n  long p=2;\n  long L=3;\n  amap.arg(\"L\", L, \"# of levels in the modulus chain\");\n  long verbose=0;\n  amap.arg(\"verbose\", verbose, \"print timing and other info\");\n  long nt=1;\n  amap.arg(\"nt\", nt, \"# threads\");\n\n  amap.arg(\"force_bsgs\", fhe_test_force_bsgs, \n           \"1 to force on, -1 to force off\"); \n  amap.arg(\"force_hoist\", fhe_test_force_hoist, \n           \"-1 to force off\"); \n  amap.arg(\"ks_strategy\", ks_strategy,\n           \"0: default, 1:full, 2:bsgs, 3:minimal\"); \n\n  NTL::Vec<long> gens;\n  amap.arg(\"gens\", gens, \"use specified vector of generators\", NULL);\n  amap.note(\"e.g., gens='[562 1871 751]'\");\n  NTL::Vec<long> ords;\n  amap.arg(\"ords\", ords, \"use specified vector of orders\", NULL);\n  amap.note(\"e.g., ords='[4 2 -4]', negative means 'bad'\");\n\n  amap.parse(argc, argv);\n\n  if (verbose) {\n    cout << \"*** matmul1D: m=\" << m\n\t << \", p^r=2\"\n\t << \", L=\" << L\n\t << \", nt=\" << nt\n\t << \", force_bsgs=\" << fhe_test_force_bsgs\n\t << \", force_hoist=\" << fhe_test_force_hoist\n\t << \", ks_strategy=\" << ks_strategy\n\t << endl;\n   }\n\n  vector<long> gens1, ords1;\n  convert(gens1, gens);\n  convert(ords1, ords);\n\n  if (nt > 1) SetNumThreads(nt);\n\n  setTimersOn();\n\n  Context context(m, 2, 1, gens1, ords1);\n  buildModChain(context, L, /*c=*/3);\n\n  TestIt(context, verbose);\n}\n", "meta": {"hexsha": "fd8c665041ceed1a6b801a62505a03c97e3f57b1", "size": 10234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/PIR.cpp", "max_stars_repo_name": "lparth/homeenc-HElib", "max_stars_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-06T09:26:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T09:26:23.000Z", "max_issues_repo_path": "misc/PIR.cpp", "max_issues_repo_name": "lparth/homeenc-HElib", "max_issues_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc/PIR.cpp", "max_forks_repo_name": "lparth/homeenc-HElib", "max_forks_repo_head_hexsha": "072ffc8af2662876c445ad5ae8614ca65f20c10b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7471910112, "max_line_length": 78, "alphanum_fraction": 0.6197967559, "num_tokens": 3202, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.44243560084915917}}
{"text": "#pragma once\n\n#include <cassert>\n#include <vector>\n\n#include <Eigen/Core>\n\n#include <FMath/detail/Expression_Function.hpp>\n#include <FMath/detail/Expression_Lambda.hpp>\n#include <FMath/detail/Expression_Slice.hpp>\n#include <FMath/detail/Expression_SubSet.hpp>\n#include <FMath/detail/Using.hpp>\n\nnamespace FMath::detail\n{\n    template<typename T, typename Container = std::vector<T>>\n    class Field\n    {\n        Container _container;\n\n        // Assignment function which explicitly evaluates an expression\n        template<typename Container2>\n        void assign(const Container2 & container_from);\n        void assign(const T & value);\n\n      public:\n        using value_type = T;\n\n        ///////////// Constructors //////////////////////////////////////////////////////\n\n        // Field with initial size\n        Field(const std::size_t n) : _container(n) {}\n\n        // Field with initial size and value\n        Field(const std::size_t n, const T & value) : _container(n, value) {}\n\n        // Field via initializer list\n        Field(const std::initializer_list<T> & list) : _container(list) {}\n\n        // Constructor for underlying container\n        Field(const Container & other) : _container(other) {}\n\n        // A Field can be constructed such as to force its evaluation.\n        template<typename T2, typename R2>\n        Field(const Field<T2, R2> & other) : _container(other.size())\n        {\n            static_assert(\n                std::is_same_v<T, T2>, \"FMATH USAGE ERROR: Field<> template parameter \"\n                                       \"must be identical for assignment to work\");\n            if constexpr (std::is_same_v<T, T2>)\n            {\n                this->assign(other);\n            }\n        }\n\n        // Assignment operator for Field of same type (copy assignment)\n        Field & operator=(const Field & other)\n        {\n            assert(size() == other.size());\n            this->assign(other);\n            return *this;\n        }\n\n        ///////////// Assignment ////////////////////////////////////////////////////////\n\n        // Assignment operator for Field of different type\n        template<typename T2, typename R2>\n        Field & operator=(const Field<T2, R2> & other)\n        {\n            static_assert(\n                std::is_same_v<T, T2>, \"FMATH USAGE ERROR: Field<> template parameter \"\n                                       \"must be identical for assignment to work\");\n            if constexpr (std::is_same_v<T, T2>)\n            {\n                assert(size() == other.size());\n                this->assign(other);\n                return *this;\n            }\n        }\n\n        // Assignment operator for entity\n        Field & operator=(const T & value)\n        {\n            this->assign(value);\n            return *this;\n        }\n\n        ///////////// Basics ////////////////////////////////////////////////////////////\n\n        void resize(const std::size_t size)\n        {\n            _container.resize(size);\n        }\n        void resize(const std::size_t size, const T & value)\n        {\n            _container.resize(size, value);\n        }\n\n        // If the container is a std::vector, data can be retrieved as a pointer\n        T * data()\n        {\n            static_assert(\n                std::is_same_v<Container, std::vector<T>>,\n                \"FMATH USAGE ERROR: data() is only available for evaluated \"\n                \"Fields, not Expressions\");\n            if constexpr (std::is_same_v<Container, std::vector<T>>)\n            {\n                return _container.data();\n            }\n        }\n\n        // Size of underlying container\n        auto size() const\n        {\n            return _container.size();\n        }\n\n        // Index operators\n        T operator[](const std::size_t i) const\n        {\n            return _container[i];\n        }\n        T & operator[](const std::size_t i)\n        {\n            return _container[i];\n        }\n\n        // Returns the underlying data\n        const Container & contents() const\n        {\n            return _container;\n        }\n        Container & contents()\n        {\n            return _container;\n        }\n\n        ///////////// Transformation ////////////////////////////////////////////////////\n\n        // Re-interpretation as a reference to an Eigen::VectorX\n        template<typename RefT>\n        Eigen::Ref<RefT> asRef()\n        {\n            // Field<Vector3> to VectorX of size 3*N\n            if constexpr (std::is_same_v<T, Vector3>)\n                return Eigen::Ref<RefT>(\n                    Eigen::Map<RefT>(this->_container[0].data(), 3 * this->size()));\n            // Field<scalar> etc. to VectorX of size N\n            else\n                return Eigen::Ref<RefT>(Eigen::Map<RefT>(this->data(), this->size()));\n        }\n\n        ///////////// Lambda ////////////////////////////////////////////////////////////\n\n        // Applies a given lambda to every entry of the Field.\n        // The lambda is passed the index and the entry corresponding to the index.\n        // This function is applied immediately, not on assignment.\n        template<typename Lambda>\n        void apply_lambda(const Lambda & lambda)\n        {\n            static_assert(\n                std::is_convertible<\n                    Lambda, std::function<void(std::size_t, const T &)>>::value,\n                \"FMATH USAGE ERROR: you cannot use apply_lambda with a type that \"\n                \"is not convertible to std::function<void(std::size_t, const T &)>.\");\n            if constexpr (\n                std::is_convertible<\n                    Lambda, std::function<void(std::size_t, const T &)>>::value)\n            {\n                this->assign(Field<T, FieldLambda<T, Container, Lambda>>(\n                    FieldLambda<T, Container, Lambda>(this->contents(), lambda)));\n            }\n        }\n\n        // Applies a given lambda to every entry of the Field.\n        // The lambda is passed the index and the entry corresponding to the index.\n        template<typename Lambda>\n        auto applied_lambda(const Lambda & lambda)\n        {\n            static_assert(\n                std::is_convertible<\n                    Lambda, std::function<void(std::size_t, const T &)>>::value,\n                \"FMATH USAGE ERROR: you cannot use applied_lambda with a type that \"\n                \"is not convertible to std::function<void(std::size_t, const T &)>.\");\n            if constexpr (\n                std::is_convertible<\n                    Lambda, std::function<void(std::size_t, const T &)>>::value)\n            {\n                return Field<T, FieldLambda<T, Container, Lambda>>(\n                    FieldLambda<T, Container, Lambda>(this->contents(), lambda));\n            }\n        }\n\n        ///////////// Reductions ////////////////////////////////////////////////////////\n\n        // Returns the sum over all entries of the Field\n        T sum() const;\n\n        // Returns the average over all entries of the Field\n        T mean() const;\n\n        // This is only valid for scalar contents\n        // This will return the minimum value.\n        scalar min() const;\n\n        // This is only valid for scalar contents\n        // This will return the maximum value.\n        scalar max() const;\n\n        // This is only valid for scalar contents\n        // This will return the minimum and maximum value.\n        std::pair<scalar, scalar> minmax() const;\n\n        // This is only valid for Vector3 contents\n        // Returns the minium and maximum value of the components of all vectorfield\n        // entries\n        scalar min_component() const;\n\n        // This is only valid for Vector3 contents\n        // Returns the minium and maximum value of the components of all vectorfield\n        // entries\n        scalar max_component() const;\n\n        // This is only valid for Vector3 contents\n        // Returns the minium and maximum value of the components of all vectorfield\n        // entries\n        std::pair<scalar, scalar> minmax_component() const;\n\n        ///////////// VectorField Operations on self ////////////////////////////////////\n\n        // For a VectorField, this returns a Field of the Vector3 norms\n        auto norm() const\n        {\n            static_assert(\n                std::is_same_v<T, Vector3>,\n                \"FMATH USAGE ERROR: norm() is only available on Field<Vector3>\");\n            if constexpr (std::is_same_v<T, Vector3>)\n            {\n                return Field<scalar, NormEx<T, Container>>(\n                    NormEx<T, Container>(this->contents()));\n            }\n        }\n\n        // For a VectorField, this returns a Field of the squared Vector3 norms\n        auto squaredNorm() const\n        {\n            static_assert(\n                std::is_same_v<T, Vector3>,\n                \"FMATH USAGE ERROR: squaredNorm() is only available on \"\n                \"Field<Vector3>\");\n            if constexpr (std::is_same_v<T, Vector3>)\n            {\n                return Field<scalar, SquaredNormEx<T, Container>>(\n                    SquaredNormEx<T, Container>(this->contents()));\n            }\n        }\n\n        // Normalizes the Vector3 entries of a VectorField to norm 1.\n        // If a norm is zero, nothing is done.\n        // This function is applied immediately, not on assignment.\n        void normalize()\n        {\n            static_assert(\n                std::is_same_v<T, Vector3>,\n                \"FMATH USAGE ERROR: normalize() is only available on Field<Vector3>\");\n            if constexpr (std::is_same_v<T, Vector3>)\n            {\n                this->assign(Field<T, NormalizedEx<T, Container>>(\n                    NormalizedEx<T, Container>(this->contents())));\n            }\n        }\n\n        // Normalizes the Vector3 entries of a VectorField to norm 1.\n        // If a norm is zero, nothing is done.\n        auto normalized() const\n        {\n            static_assert(\n                std::is_same_v<T, Vector3>,\n                \"FMATH USAGE ERROR: normalized() is only available on \"\n                \"Field<Vector3>\");\n            if constexpr (std::is_same_v<T, Vector3>)\n            {\n                return Field<T, NormalizedEx<T, Container>>(\n                    NormalizedEx<T, Container>(this->contents()));\n            }\n        }\n\n        ///////////// VectorField Operations with others ////////////////////////////////\n\n        // Element-wise dot-product between vector-fields, yielding a scalar-field\n        template<typename Container2>\n        auto dot(const Field<Vector3, Container2> & field) const\n        {\n            static_assert(\n                std::is_same_v<T, Vector3>,\n                \"FMATH USAGE ERROR: dot() is only available on Field<Vector3>\");\n            if constexpr (std::is_same_v<T, Vector3>)\n            {\n                return Field<scalar, FieldDotFieldEx<T, Container, Container2>>(\n                    FieldDotFieldEx<T, Container, Container2>(\n                        this->contents(), field.contents()));\n            }\n        }\n\n        // Element-wise dot-product between a vector-field and a vector, yielding a scalar-field\n        auto dot(const Vector3 & vec) const\n        {\n            static_assert(\n                std::is_same_v<T, Vector3>,\n                \"FMATH USAGE ERROR: dot() is only available on Field<Vector3>\");\n            if constexpr (std::is_same_v<T, Vector3>)\n            {\n                return Field<scalar, VectorDotFieldEx<T, Container>>(\n                    VectorDotFieldEx<T, Container>(this->contents(), vec));\n            }\n        }\n\n        // Element-wise cross-product between vector-fields, yielding a vector-field\n        template<typename Container2>\n        auto cross(const Field<Vector3, Container2> & field) const\n        {\n            static_assert(\n                std::is_same_v<T, Vector3>,\n                \"FMATH USAGE ERROR: cross() is only available on Field<Vector3>\");\n            if constexpr (std::is_same_v<T, Vector3>)\n            {\n                return Field<Vector3, FieldCrossFieldEx<T, Container, Container2>>(\n                    FieldCrossFieldEx<T, Container, Container2>(\n                        this->contents(), field.contents()));\n            }\n        }\n\n        // Element-wise cross-product between a vector-field and a vector, yielding a vector-field\n        auto cross(const Vector3 & vec) const\n        {\n            static_assert(\n                std::is_same_v<T, Vector3>,\n                \"FMATH USAGE ERROR: cross() is only available on Field<Vector3>\");\n            if constexpr (std::is_same_v<T, Vector3>)\n            {\n                return Field<Vector3, VectorCrossFieldEx<T, Container>>(\n                    VectorCrossFieldEx<T, Container>(this->contents(), vec));\n            }\n        }\n\n        ///////////// SubSet Extraction /////////////////////////////////////////////////\n\n        // Extract a 1D slice of a Field\n        auto slice(\n            const std::size_t begin = 0, const std::optional<std::size_t> end = {},\n            const std::size_t stride = 1)\n        {\n            return Field<T, SliceEx<T, Container>>(\n                SliceEx<T, Container>(this->contents(), begin, end, stride));\n        }\n\n        // Extract a subset of a Field's values via a list of indices\n        auto operator[](const std::vector<std::size_t> & indices)\n        {\n            return Field<T, SubSetEx<T, Container>>(\n                SubSetEx<T, Container>(this->contents(), indices));\n        }\n    };\n}", "meta": {"hexsha": "854164075a34c5d3072912b1c528053f24286f83", "size": 13477, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/FMath/detail/Field.hpp", "max_stars_repo_name": "Trick-17/FMath", "max_stars_repo_head_hexsha": "7c67597e0c725784bd82a62d40762dffd3f81529", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-01T12:32:27.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-27T14:59:52.000Z", "max_issues_repo_path": "include/FMath/detail/Field.hpp", "max_issues_repo_name": "Trick-17/FMath", "max_issues_repo_head_hexsha": "7c67597e0c725784bd82a62d40762dffd3f81529", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-01-01T12:41:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T23:14:16.000Z", "max_forks_repo_path": "include/FMath/detail/Field.hpp", "max_forks_repo_name": "Trick-17/FMath", "max_forks_repo_head_hexsha": "7c67597e0c725784bd82a62d40762dffd3f81529", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0247252747, "max_line_length": 98, "alphanum_fraction": 0.5192550271, "num_tokens": 2699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4424355989305095}}
{"text": "#include <algorithm>\nusing namespace std;\n \n#include \"regression_tree.h\"\n#include <boost/bind.hpp>\n#include <boost/thread/thread.hpp>\nusing namespace boost;\n\nextern vector<vector<int> > fInds;\n\nint feature_to_split_on;\n\n/*bool mysortpred(const tuple* d1, const tuple* d2) {\n  return d1->features[feature_to_split_on] < d2->features[feature_to_split_on];\n}\n*/\n/*void sort_data_by_feature(vector<tuple*>& data, int f) {\n  feature_to_split_on = f;\n  sort(data.begin(), data.end(), mysortpred);\n}\n*/\n\nvoid sort_data_by_feature(vector<int>& location,  vector<int> dataCount, vector<int> invertIdx, int f){\n\tint cur=0;\n        for (int i = 0; i < fInds[f].size(); i ++){\n                int z = fInds[f][i];\n\t\tint loc=invertIdx[z];\n                for (int j = 0; j < dataCount[z]; j ++)\n\t\t\tlocation[cur++]=loc;\n        }\n}\n\n\n/*bool mysortpred2(const pair<tuple*, int> tk1, const pair<tuple*, int> tk2) {\n  return tk1.first->features[tk1.second] < tk2.first->features[tk2.second];\n}*/\n/////////\n\n\n\n//double best_fc_in_feature(vector<tuple*> data, int f, pair<int, double>& fc) {\ndouble best_fc_in_feature(vector<tuple*> data, vector<int> dataCount, vector<int> invertIdx, int f, int& fs, double& vs, const args_t& args) {  //if (!XX)\n/*  vector< pair<tuple*, int> > tk;\n  int z;\n\n  for (z = 0; z < data.size(); z++)\n    tk.push_back( pair<tuple*,int>(data[z], f) );\n  sort(tk.begin(), tk.end(), mysortpred2);\n  for (z = 0; z < data.size(); z++)\n    data[z] = tk[z].first;\n*/\n  int n = data.size(), i;\n  double min = MY_DBL_MAX;\n        vector<int> location(n, -1);\n        sort_data_by_feature(location, dataCount, invertIdx, f);\n\n\n  // get impurity (squared loss) for missing data\n  double M = 0.0;\n  double W = 0.0;\n  int missing = 0;\n\tint loc = location[missing];\n  while (data[loc]->features[f] == UNKNOWN && missing < n-1) {\n    //M += data[missing]->target * 1.0;\n\tM += data[loc]->target * data[loc]->weight;\n\tW += data[loc]->weight;\n    \tmissing++;\n\tloc = location[missing];\n  }\n  if (missing == n-1) // all data is missing\n    return MY_DBL_MAX;\n  if (missing) {\n    //double mbar = M * 1.0 / missing;\n\tdouble mbar = M/W;\n    M = 0.0;\n    for (i = 0; i < missing; i++){\n\tloc = location[i];\n      M += data[loc]->weight * (data[loc]->target - mbar) * (data[loc]->target - mbar);\n    }\n  }\n  int nn = n - missing; // number of data points that arent missing\n \n  // we have impurity = E_{i=0..n} (yi - ybar)^2  (E = summation)\n  // this factors to impurty = E(yi^2) + (n+1)ybar^2 - 2*(n+1)*ybar^2\n  // we want the impurity for left and right splits for all splits k\n  // let ybl = ybar left, ybr = ybar right\n  //     s = E_{i=0..k} yi^2\n  //     r = E_{i=k+1..n} yi^2\n\n  //impurity =\\sum_i  wi (yi - ybar)^2 = \\sum_i wi*yi^2 - 2*(\\sum_i wi*yi)*ybar + (\\sum_i wi) ybar^2 \n  // ybar = (\\sum_i wi*yi) / (sum_i wi) = ywr/WR\n  //  r = \\sum_i wi*yi^2, ywr = \\sum_i wi*yi,  WR = \\sum_i wi\n  // impurity = r - 2*ywr*ywr/WR + ywr*ywr/WR = r - ywr*ywr/WR\n  double ybl, ybr, s, r, L, R, I, ywl, ywr, WL, WR;\n  ybl = ybr = s = r = ywl = ywr = WL = WR = 0.0;\n  \n  // put all data into right side R\n  // get ybar right and r\n  int start = missing;\n  for (i = start; i < n; i++) {\n\tloc = location[i];\n    \tr += data[loc]->target * data[loc]->target * data[loc]->weight;\n    \t//ybr += data[i]->target;\n    \tywr += data[loc]->target * data[loc]->weight;\n    \tWR += data[loc]->weight;\n  }\n  //ybr /= 1.0 * nn;\n  //r += 0.0000000001 for precision errors\n  \n  // for every i\n  // put yi into left side, remove it from the right side, and calculate squared lost\n  // impurity of putting all data points into the right tree equals putting all the data into the left tree (such cases are not considered)\n  for (i = start; i < n-1; i++) {\n    int j = i - missing; \n    double yn = data[location[i]]->target;\n    double w = data[location[i]]->weight;\n\n    s += w *  yn * yn;\n    r -= w * yn * yn;\n    ywr -= w * yn;\n    ywl += w * yn;\n    WL += w;\n    WR -= w;\n    \n    if (r < 0 && r > -0.000001) r = 0;\n    if (r < 0) r = 0;\n    \n    //ybl = (j*ybl + yn) / (j+1.0);\n    //ybr = ((nn-j)*ybr - yn) / (nn-j-1.0);\n\n    //L = s + WL*ybl*ybl - 2*ybl*ywl;\n    //R = r + WR*ybr*ybr - 2*ybr*ywr;\n    L = s - ywl*ywl/WL;\n    R = r - ywr*ywr/WR; \n    \n    //L = s + (j+1)*ybl*ybl - 2*(j+1)*ybl*ybl;\n    //R = r + (nn-j-1.0)*ybr*ybr - 2*(nn-j-1.0)*ybr*ybr;\n    \n    // precision errors?\n    if (L < 0 && L > -0.0000001) L = 0; \n    if (R < 0 && R > -0.0000001) R = 0;\n    if (R < 0) R = 0;\n    if (L < 0) L = 0;\n\n    if(0)\n    if (L < 0 || R < 0 || r < 0)\n      printf(\"Problem %lf %lf %lf\\n\", L, R, r);\n    \n    // do not consider splitting here if data is the same as next\n    if (data[location[i]]->features[f] == data[location[i+1]]->features[f])\n      continue;\n    \n    I = L + R;// + M;\n    I = L + R + M;\n\n\n    if (I < min) {\n      min = I;\n      fs = f;\n      vs = (data[location[i]]->features[f] + data[location[i+1]]->features[f]) / 2;\n    }\n  }\n\n  return min;\n}\n\n\n// find best feature to split on in range [start, end)\n// store results int I, fs, vs : impurity, feature, value\n//void find_split_in_range(vector<tuple*> data, vector<int> dataCount, vector<int> invertIdx, int start, int  end, int& fs, double& vs, double& I, vector<bool> skip, const args_t& args) {\nvoid find_split_in_range(vector<tuple*> data, vector<int> dataCount, vector<int> invertIdx, pair<int,int> range, int& fs, double& vs, double& I, vector<bool>skip, const args_t& args) {\n\n  double min = MY_DBL_MAX;\n\tint start = range.first, end = range.second;\n\n  for (int i = start; i < end; i++) {\n    int f = i + 1;\n    if (skip[f]) continue;\n\n    int fi;\n    double vi, Ii;\n    Ii = best_fc_in_feature(data, dataCount, invertIdx, f, fi, vi, args);\n    if (Ii < min) {\n      min = Ii;\n      fs = fi;\n      vs = vi;\n    }\n  }\n\n  I = min;\n}\n\nbool find_split_p(vector<tuple*> data, vector<int> dataCount, vector<int> invertIdx, int NF, int& f_split, double& v_split, vector<bool>& skip, const args_t& args) {\n\n  f_split = -1;\n  double min = MY_DBL_MAX;\n  int n = data.size(), i;\n\n  pair<int, double>* fc = new pair<int,double>[NF];\n  double* I = new double[NF];\n\n  int numthreads = args.processors;\n  thread** threads = new thread*[numthreads];\n  \n  int* F = new int[numthreads];\n  double* V = new double[numthreads];\n  double* Imp = new double[numthreads];\n\n  for (i = 0; i < numthreads; i++)\n//\tfind_split_in_range(data, dataCount, invertIdx, i*(NF-1)/numthreads, (i+1)*(NF-1)/numthreads, F[i], V[i], Imp[i], skip, args);\n//    threads[i] = new thread(find_split_in_range, data, dataCount, invertIdx, i*(NF-1)/numthreads, (i+1)*(NF-1)/numthreads, ref(F[i]), ref(V[i]), ref(Imp[i]), ref(skip), cref(args));\n\tthreads[i] = new thread(bind(find_split_in_range, data, dataCount, invertIdx, make_pair(i*(NF-1)/numthreads, (i+1)*(NF-1)/numthreads), ref(F[i]), ref(V[i]), ref(Imp[i]), ref(skip), cref(args) ));\n  for (i = 0; i < numthreads; i++) {\n    threads[i]->join(); \n    delete threads[i];\n  }\n  delete[] threads;\n\n  for (i = 0; i < numthreads;i++)\n    if (Imp[i] < min) {\n      min = Imp[i];\n      f_split = F[i];\n      v_split = V[i];\n    }\n\n  delete[] fc;  delete[] I;  delete[] V;  delete[] Imp; delete[] F;\n  return min != MY_DBL_MAX;\n}\n\n///////////////////////\n\nbool dt_node::entropy_split(data_t data, vector<int> dataCount, vector<int> invertIdx, int NF, int& f_split, double& v_split, int K, bool par) {\n  f_split = -1;\n  double min = MY_DBL_MAX;\n  int n = data.size(), i;\n  \n  vector<bool> skip;\n\n  //min E(i=1..k) pi * log(1/pi)\n  \n  for (i = 0; i <= NF; i++)\n    skip.push_back( (K > 0) ? true : false);\n\n  for (i = 0; i < K; i++) {\n    int f;\n    do\n      f = rand() % (NF-2) + 1;\n    while (!skip[f]);\n    skip[f] = false;\n  }\n\n\n  //if (K <= 0)\n  //return find_split_p(data, NF, f_split, v_split, skip);\n\n  vector<int> location(n, -1);\n  for (int f = 1; f < NF; f++) {\n\tif (skip[f]) continue;\n\tsort_data_by_feature(location, dataCount, invertIdx, f);\n    //sort_data_by_feature(data,f);\n\n    //if (skip[f]) continue;\n\n    /*\n vector< pair<tuple*, int> > tk;\n  int z;\n\n  for (z = 0; z < data.size(); z++)\n  tk.push_back( pair<tuple*,int>(data[z], f) );\n  sort(tk.begin(), tk.end(), mysortpred2);\n\n\n  for (z = 0; z < data.size(); z++)\n  data[z] = tk[z].first;\n    */\n\n\n  int num_c = 7;\n  vector<double> c_miss, c_left, c_right;\n  //vector<double> p_miss, p_left, p_right;\n  //vector<int> freq;\n  //int n_left = 0, n_right = 0;\n  for (i=0;i<num_c;i++) {\n\tc_miss.push_back(0.0);\n//\tp_miss.push_back(0.0);\n    c_left.push_back(0.0);\n    c_right.push_back(0.0);\n//    p_left.push_back(0.0);\n//    p_right.push_back(0.0);\n//    freq.push_back(0);\n  }\n\n\n\n    // get impurity (entropy) for missing data\n    double M = 0.0, L, R, W_miss = 0.0, W_left = 0.0, W_right = 0.0;\n    int missing = 0;\n\tint loc = location[missing];\n    while (data[loc]->features[f] == UNKNOWN && missing < n-1) {\n\tc_miss[(int)data[loc]->target] += data[loc]->weight;\n\tW_miss += data[loc]->weight;\n        missing++;\n\tloc = location[missing];\n    }\n\n    if (missing == n-1) // all data is missing\n      continue;\n\n    int nn = n - missing; // number of data points that arent missing\n    // entropy\n    // put all data into right side R\n    int start = missing;\n    for (i = start; i < n; i++) {\n\tloc = location[i];\n      \tc_right[(int)data[loc]->target]+=data[loc]->weight;\n      \tW_right+=data[loc]->weight;\n    }\n\tif (W_right){\n    \t\tfor (i = 0; i < num_c; i++) {\n      \t\t\tif (c_right[i])\n\t\t\t\tR += c_right[i]/W_right * log(W_right / c_right[i]);\n    \t\t}\n\t}\n\n    \tif (missing && W_miss) {\n                for (i = 0; i < num_c; i ++){\n                        if (c_miss[i])\n                                M += c_miss[i]/W_miss * log(W_miss/c_miss[i]);\n                }\n    \t}\n    \tL = 0.0;\n\n    // for every i\n    // put yi into left side, remove it from the right side, and calculate squared lost\n    for (i = start; i < n-1; i++) {\n      int j = i - missing; \n      int yn = (int)data[loc]->target;\n\n\tW_right -= data[loc]->weight;\n\tW_left += data[loc]->weight;\n      //n_right--;\n      //n_left++;\n\tc_left[yn] += data[loc]->weight;\n\tc_right[yn] -= data[loc]->weight;\n      //c_left[yn]++;\n      //c_right[yn]--;\n\n      //p_left[yn] += 1.0 / freq[yn];\n      //p_right[yn] -= 1.0 / freq[yn];\n\n      // do not consider splitting here if data is the same as next\n      if (data[location[i]]->features[f] == data[location[i+1]]->features[f])\n\tcontinue;\n\n      L = 0.0;\n      int k;\n      for (k = 0; k < num_c; k++) {\n      \tif (c_left[k])\n\t  L +=  c_left[k]/W_left * log(W_left / c_left[k]); \n      }\n      R = 0.0;\n      for (k = 0; k < num_c; k++) {\n\tif (c_right[k])\n\t  R += c_right[k]/W_right * log(W_right / c_right[k]);   \n      }\n      double ssum = W_left+W_right+W_miss;\n      double I = W_left/ssum * L +  W_right/ssum * R + W_miss/ssum * M;\n      //I = 1.0*n_left/n * \n\n      /*\n      L = 0.0, R = 0.0;\n      for (i = 0; i < num_c; i++)\n\tL += p_left;\n      */\n\n      if (I < min) {\n\tmin = I;\n\tf_split = f;\n\tv_split = (data[location[i]]->features[f] + data[location[i+1]]->features[f])/2;\n      }\n    }\n  }\n\n  return min != MY_DBL_MAX;\n}\n\n\n\n\n\n\n//////////////////////\n\n\nbool dt_node::find_split(vector<tuple*> data, vector<int> dataCount, vector<int> invertIdx, int NF, int& f_split, double& v_split, int K, bool par, const args_t& args) {\n  if (args.loss == ALG_ENTROPY)\n    return entropy_split(data, dataCount, invertIdx, NF, f_split, v_split, K, par);\n\n  f_split = -1;\n  double min = MY_DBL_MAX;\n  int n = data.size(), i;\n  \n  vector<bool> skip;\n\n  //K = NF/2;\n\n  // pick K random features to split on, if specified\n  for (i = 0; i <= NF; i++)\n    skip.push_back( (K > 0) ? true : false);\n  for (i = 0; i < K; i++) {\n    int f;\n    do\n      f = rand() % (NF-2) + 1;\n    while (!skip[f]);\n    skip[f] = false;\n  }\n\n  //if (K >= 10)\n  if (args.alg != ALG_FOREST && args.processors!=1)\n    return find_split_p(data, dataCount, invertIdx, NF, f_split, v_split, skip, args);\n\n\tvector<int> location(n, -1);\n  for (int f = 1; f < NF; f++) {\n        if (skip[f]) continue;\n    // sort data\n/*    vector< pair<tuple*, int> > tk;\n    int z;\n    for (z = 0; z < data.size(); z++)\n      tk.push_back( pair<tuple*,int>(data[z], f) );\n    sort(tk.begin(), tk.end(), mysortpred2);\n    for (z = 0; z < data.size(); z++)\n      data[z] = tk[z].first;\n*/\n\tsort_data_by_feature(location, dataCount, invertIdx, f);\n\n    // get impurity (squared loss) for missing data\n/*    double M = 0.0;\n    int missing = 0;\n    while (data[missing]->features[f] == UNKNOWN && missing < n-1) {\n      M += data[missing]->target * 1.0;\n      missing++;\n    }\n    if (missing == n-1) // all data is missing\n      continue;\n    if (missing) {\n      double mbar = M * 1.0 / missing;\n      M = 0.0;\n      for (i = 0; i < missing; i++)\n\tM += (data[i]->target - mbar) * (data[i]->target - mbar);\n    }\n    int nn = n - missing; // number of data points that arent missing\n*/\n  double M = 0.0;\n  double W = 0.0;\n  int missing = 0;\n\tint loc = location[missing];\n  while (data[loc]->features[f] == UNKNOWN && missing < n-1) {\n    //M += data[missing]->target * 1.0;\n        M += data[loc]->target * data[loc]->weight;\n        W += data[loc]->weight;\n    \tmissing++;\n\tloc = location[missing];\n  }\n  if (missing == n-1) // all data is missing\n    return MY_DBL_MAX;\n  if (missing) {\n    //double mbar = M * 1.0 / missing;\n        double mbar = M/W;\n    M = 0.0;\n    for (i = 0; i < missing; i++){\n\tloc = location[i];\n      M += data[loc]->weight * (data[loc]->target - mbar) * (data[loc]->target - mbar);\n   }\n  }\n \n  double ybl, ybr, s, r, L, R, I, ywl, ywr, WL, WR;\n  ybl = ybr = s = r = ywl = ywr = WL = WR = 0.0;\n\n  // put all data into right side R\n  // get ybar right and r\n  int start = missing;\n  for (i = start; i < n; i++) {\n\tloc = location[i];\n    \tr += data[loc]->target * data[loc]->target * data[loc]->weight;\n    \t//ybr += data[i]->target;\n    \tywr += data[loc]->target * data[loc]->weight;\n    \tWR += data[loc]->weight;\n  }\n  //ybr /= 1.0 * nn;\n  //r += 0.0000000001 for precision errors\n\n  // for every i\n  // put yi into left side, remove it from the right side, and calculate squared lost\n  // impurity of putting all data points into the right tree equals putting all the data into the left tree (such cases are not considered)\n  for (i = start; i < n-1; i++) {\n    int j = i - missing;\n    double yn = data[location[i]]->target;\n    double w = data[location[i]]->weight;\n\n    s += w *  yn * yn;\n    r -= w * yn * yn;\n    ywr -= w * yn;\n    ywl += w * yn;\n    WL += w;\n    WR -= w;\n\n    if (r < 0 && r > -0.000001) r = 0;\n    if (r < 0) r = 0;\n    //ybl = (j*ybl + yn) / (j+1.0);\n    //ybr = ((nn-j)*ybr - yn) / (nn-j-1.0);\n    //L = s + WL*ybl*ybl - 2*ybl*ywl;\n    //R = r + WR*ybr*ybr - 2*ybr*ywr;\n    L = s - ywl*ywl/WL;\n    R = r - ywr*ywr/WR;\n    // precision errors?\n    if (L < 0 && L > -0.0000001) L = 0;\n    if (R < 0 && R > -0.0000001) R = 0;\n    if (R < 0) R = 0;\n    if (L < 0) L = 0;\n\n    if(0)\n    if (L < 0 || R < 0 || r < 0)\n      printf(\"Problem %lf %lf %lf\\n\", L, R, r);\n\n    // do not consider splitting here if data is the same as next\n    if (data[location[i]]->features[f] == data[location[i+1]]->features[f])\n      continue;\n\n    I = L + R + M ;\n\n      if (I < min) {\n        min = I;\n        f_split = f;\n        v_split = (data[location[i]]->features[f] + data[location[i+1]]->features[f])/2;\n      }\n\n  }\n}\n  return min != MY_DBL_MAX;\n}\n\n", "meta": {"hexsha": "5ccd5998782913ccb6ad45e9e89e1ec2426860db", "size": 15369, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rt-rank_1.5/cart/impurity.cpp", "max_stars_repo_name": "HeBing/fcar_v0.1", "max_stars_repo_head_hexsha": "938a85fa10d86288e2de17ade05e6a1d71d6a6c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rt-rank_1.5/cart/impurity.cpp", "max_issues_repo_name": "HeBing/fcar_v0.1", "max_issues_repo_head_hexsha": "938a85fa10d86288e2de17ade05e6a1d71d6a6c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rt-rank_1.5/cart/impurity.cpp", "max_forks_repo_name": "HeBing/fcar_v0.1", "max_forks_repo_head_hexsha": "938a85fa10d86288e2de17ade05e6a1d71d6a6c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3560885609, "max_line_length": 196, "alphanum_fraction": 0.5483766023, "num_tokens": 5251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.442435588122868}}
{"text": "#include <engine/Neighbours.hpp>\r\n#include <engine/Vectormath.hpp>\r\n#include <engine/Manifoldmath.hpp>\r\n#include <utility/Logging.hpp>\r\n#include <utility/Exception.hpp>\r\n\r\n#include <Eigen/Dense>\r\n\r\n#include <numeric>\r\n#include <iostream>\r\n#include <cstdio>\r\n#include <cmath>\r\n#include <algorithm>\r\n\r\nusing namespace Utility;\r\n\r\nnamespace Engine\r\n{\r\n\tnamespace Neighbours\r\n\t{\r\n\t\tstd::vector<scalar> Get_Shell_Radius(const Data::Geometry & geometry, const int n_shells)\r\n\t\t{\r\n\t\t\tauto shell_radius = std::vector<scalar>(n_shells);\r\n\t\t\t\r\n\t\t\tVector3 a = geometry.bravais_vectors[0];\r\n\t\t\tVector3 b = geometry.bravais_vectors[1];\r\n\t\t\tVector3 c = geometry.bravais_vectors[2];\r\n\r\n\t\t\tscalar current_radius=0, dx, min_distance=0;\r\n\t\t\tint i=0, j=0, k=0;\r\n\t\t\tint ii, jj, kk;\r\n\r\n\t\t\t// The 15 is a value that is big enough by experience to \r\n\t\t\t// produce enough needed shells, but is small enough to run sufficiently fast\r\n\t\t\tint imax = 15, jmax = 15, kmax = 15;\r\n\t\t\tVector3 x0={0,0,0}, x1={0,0,0};\r\n\r\n\t\t\t// Abort condidions for all 3 vectors\r\n\t\t\tif (a.norm() == 0.0) imax = 0;\r\n\t\t\tif (b.norm() == 0.0) jmax = 0;\r\n\t\t\tif (c.norm() == 0.0) kmax = 0;\r\n\r\n\t\t\tfor (int n = 0; n < n_shells; ++n)\r\n\t\t\t{\r\n\t\t\t\tcurrent_radius = min_distance;\r\n\t\t\t\tmin_distance = 1e10;\r\n\t\t\t\tfor (int iatom = 0; iatom < geometry.n_cell_atoms; ++iatom)\r\n\t\t\t\t{\r\n\t\t\t\t    x0 = geometry.cell_atoms[iatom][0] * a + geometry.cell_atoms[iatom][1] * b + geometry.cell_atoms[iatom][2] * c;\r\n\t\t\t\t\tfor (ii = imax; ii >= -imax; --ii)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (jj = jmax; jj >= -jmax; --jj)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tfor (kk = kmax; kk >= -kmax; --kk)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tfor (int jatom = 0; jatom < geometry.n_cell_atoms; ++jatom)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tif ( !( iatom==jatom && ii==0 && jj==0 && kk==0 ) )\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t    x1 = geometry.cell_atoms[jatom][0] * a + geometry.cell_atoms[jatom][1] * b + geometry.cell_atoms[jatom][2] * c + ii*a + jj*b + kk*c;\r\n\t\t\t\t\t\t\t\t\t\tdx = (x0-x1).norm();\r\n\r\n\t\t\t\t\t\t\t\t\t\tif (dx - current_radius > 1e-6 && dx < min_distance)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tmin_distance = dx;\r\n\t\t\t\t\t\t\t\t\t\t\tshell_radius[n] = dx;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}//endfor jatom\r\n\t\t\t\t\t\t\t}//endfor kk\r\n\t\t\t\t\t\t}//endfor jj\r\n\t\t\t\t\t}//endfor ii\r\n\t\t\t\t}//endfor iatom\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\treturn shell_radius;\r\n\t\t}\r\n\t\t\r\n\t\tpairfield Get_Pairs_in_Shells(const Data::Geometry & geometry, int nShells)\r\n\t\t{\r\n\t\t\tauto pairs = pairfield(0);\r\n\r\n\t\t\tauto shell_radius = Get_Shell_Radius(geometry, nShells);\r\n\t\t\t\r\n\t\t\tVector3 a = geometry.bravais_vectors[0];\r\n\t\t\tVector3 b = geometry.bravais_vectors[1];\r\n\t\t\tVector3 c = geometry.bravais_vectors[2];\r\n\r\n\t\t\t// The nShells + 10 is a value that is big enough by experience to \r\n\t\t\t// produce enough needed shells, but is small enough to run sufficiently fast\r\n\t\t\tint tMax = nShells + 10;\r\n\t\t\tint imax = tMax, jmax = tMax, kmax = tMax;\r\n\t\t\tint i,j,k;\r\n\t\t\tscalar dx, delta, radius;\r\n\t\t\tVector3 x0={0,0,0}, x1={0,0,0};\r\n\r\n\t\t\t// Abort condidions for all 3 vectors\r\n\t\t\tif (a.norm() == 0.0) imax = 0;\r\n\t\t\tif (b.norm() == 0.0) jmax = 0;\r\n\t\t\tif (c.norm() == 0.0) kmax = 0;\r\n\r\n\t\t\tfor (int iatom = 0; iatom < geometry.n_cell_atoms; ++iatom)\r\n\t\t\t{\r\n\t\t\t\tx0 = geometry.cell_atoms[iatom];\r\n\t\t\t\tfor (int ishell = 0; ishell < nShells; ++ishell)\r\n\t\t\t\t{\r\n\t\t\t\t\tradius = shell_radius[ishell];\r\n\t\t\t\t\tfor (i = imax; i >= -imax; --i)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (j = jmax; j >= -jmax; --j)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tfor (k = kmax; k >= -kmax; --k)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tfor (int jatom = 0; jatom < geometry.n_cell_atoms; ++jatom)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tx1 = geometry.cell_atoms[jatom] + i*a + j*b + k*c;\r\n\t\t\t\t\t\t\t\t\tdx = (x0-x1).norm();\r\n\t\t\t\t\t\t\t\t\tdelta = std::abs(dx - radius);\r\n\t\t\t\t\t\t\t\t\tif (delta < 1e-6)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tpairs.push_back( {iatom, jatom, {i, j, k} } );\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}//endfor jatom\r\n\t\t\t\t\t\t\t}//endfor k\r\n\t\t\t\t\t\t}//endfor j\r\n\t\t\t\t\t}//endfor i\r\n\t\t\t\t}//endfor ishell\r\n\t\t\t}//endfor iatom\r\n\r\n\t\t\treturn pairs;\r\n\t\t}\r\n\r\n\t\tneighbourfield Get_Neighbours_in_Shells(const Data::Geometry & geometry, int nShells)\r\n\t\t{\r\n\t\t\tauto neighbours = neighbourfield(0);\r\n\r\n\t\t\tauto shell_radius = Get_Shell_Radius(geometry, nShells);\r\n\t\t\t\r\n\t\t\tVector3 a = geometry.bravais_vectors[0];\r\n\t\t\tVector3 b = geometry.bravais_vectors[1];\r\n\t\t\tVector3 c = geometry.bravais_vectors[2];\r\n\r\n\t\t\t// The nShells + 10 is a value that is big enough by experience to \r\n\t\t\t// produce enough needed shells, but is small enough to run sufficiently fast\r\n\t\t\tint tMax = nShells + 10;\r\n\t\t\tint imax = std::min(tMax, geometry.n_cells[0]-1), jmax = std::min(tMax, geometry.n_cells[1]-1), kmax = std::min(tMax, geometry.n_cells[2]-1);\r\n\t\t\tint i,j,k;\r\n\t\t\tscalar dx, delta, radius;\r\n\t\t\tVector3 x0={0,0,0}, x1={0,0,0};\r\n\r\n\t\t\t// Abort condidions for all 3 vectors\r\n\t\t\tif (a.norm() == 0.0) imax = 0;\r\n\t\t\tif (b.norm() == 0.0) jmax = 0;\r\n\t\t\tif (c.norm() == 0.0) kmax = 0;\r\n\r\n\t\t\tfor (int iatom = 0; iatom < geometry.n_cell_atoms; ++iatom)\r\n\t\t\t{\r\n\t\t\t\tx0 = geometry.cell_atoms[iatom][0] * a + geometry.cell_atoms[iatom][1] * b + geometry.cell_atoms[iatom][2] * c;\r\n\t\t\t\tfor (int ishell = 0; ishell < nShells; ++ishell)\r\n\t\t\t\t{\r\n\t\t\t\t\tradius = shell_radius[ishell];\r\n\t\t\t\t\tfor (i = imax; i >= -imax; --i)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (j = jmax; j >= -jmax; --j)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tfor (k = kmax; k >= -kmax; --k)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tfor (int jatom = 0; jatom < geometry.n_cell_atoms; ++jatom)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tx1 = geometry.cell_atoms[jatom][0] * a + geometry.cell_atoms[jatom][1] * b + geometry.cell_atoms[jatom][2] * c + i*a + j*b + k*c;\r\n\t\t\t\t\t\t\t\t\tdx = (x0-x1).norm();\r\n\t\t\t\t\t\t\t\t\tdelta = std::abs(dx - radius);\r\n\t\t\t\t\t\t\t\t\tif (delta < 1e-6)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tNeighbour neigh;\r\n\t\t\t\t\t\t\t\t\t\tneigh.i = iatom;\r\n\t\t\t\t\t\t\t\t\t\tneigh.j = jatom;\r\n\t\t\t\t\t\t\t\t\t\tneigh.translations[0] = i;\r\n\t\t\t\t\t\t\t\t\t\tneigh.translations[1] = j;\r\n\t\t\t\t\t\t\t\t\t\tneigh.translations[2] = k;\r\n\t\t\t\t\t\t\t\t\t\tneigh.idx_shell = ishell;\r\n\t\t\t\t\t\t\t\t\t\tneighbours.push_back( neigh );\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}//endfor jatom\r\n\t\t\t\t\t\t\t}//endfor k\r\n\t\t\t\t\t\t}//endfor j\r\n\t\t\t\t\t}//endfor i\r\n\t\t\t\t}//endfor ishell\r\n\t\t\t}//endfor iatom\r\n\r\n\t\t\treturn neighbours;\r\n\t\t}\r\n\r\n\r\n\t\tpairfield Get_Pairs_in_Radius(const Data::Geometry & geometry, scalar radius)\r\n\t\t{\r\n\t\t\tauto pairs = pairfield(0);\r\n\r\n\t\t\tif (radius > 1e-6)\r\n\t\t\t{\r\n\t\t\t\tVector3 a = geometry.bravais_vectors[0];\r\n\t\t\t\tVector3 b = geometry.bravais_vectors[1];\r\n\t\t\t\tVector3 c = geometry.bravais_vectors[2];\r\n\r\n\t\t\t\tVector3 bounds_diff = geometry.bounds_max - geometry.bounds_min;\r\n\t\t\t\tVector3 ratio = {\r\n\t\t\t\t\tbounds_diff[0]/std::max(1, geometry.n_cells[0]),\r\n\t\t\t\t\tbounds_diff[1]/std::max(1, geometry.n_cells[1]),\r\n\t\t\t\t\tbounds_diff[2]/std::max(1, geometry.n_cells[2]) };\r\n\r\n\t\t\t\t// This should give enough translations to contain all DDI pairs\r\n\t\t\t\tint imax = 0, jmax = 0, kmax = 0;\r\n\t\t\t\tif ( bounds_diff[0] > 0 )\r\n\t\t\t\t\timax = std::min(geometry.n_cells[0], (int)(1.1 * radius * geometry.n_cells[0] / bounds_diff[0]));\r\n\t\t\t\tif ( bounds_diff[1] > 0 )\r\n\t\t\t\t\tjmax = std::min(geometry.n_cells[1], (int)(1.1 * radius * geometry.n_cells[1] / bounds_diff[1]));\r\n\t\t\t\tif ( bounds_diff[2] > 0 )\r\n\t\t\t\t\tkmax = std::min(geometry.n_cells[2], (int)(1.1 * radius * geometry.n_cells[2] / bounds_diff[2]));\r\n\r\n\t\t\t\tint i,j,k;\r\n\t\t\t\tscalar dx;\r\n\t\t\t\tVector3 x0={0,0,0}, x1={0,0,0};\r\n\r\n\t\t\t\t// Abort condidions for all 3 vectors\r\n\t\t\t\tif (a.norm() == 0.0) imax = 0;\r\n\t\t\t\tif (b.norm() == 0.0) jmax = 0;\r\n\t\t\t\tif (c.norm() == 0.0) kmax = 0;\r\n\r\n\t\t\t\tfor (int iatom = 0; iatom < geometry.n_cell_atoms; ++iatom)\r\n\t\t\t\t{\r\n\t\t\t\t\tx0 = geometry.cell_atoms[iatom];\r\n\t\t\t\t\tfor (i = imax; i >= -imax; --i)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (j = jmax; j >= -jmax; --j)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tfor (k = kmax; k >= -kmax; --k)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tfor (int jatom = 0; jatom < geometry.n_cell_atoms; ++jatom)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tx1 = geometry.cell_atoms[jatom] + i*a + j*b + k*c;\r\n\t\t\t\t\t\t\t\t\tdx = (x0-x1).norm();\r\n\t\t\t\t\t\t\t\t\tif (dx < radius)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tpairs.push_back( {iatom, jatom, {i, j, k} } );\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}//endfor jatom\r\n\t\t\t\t\t\t\t}//endfor k\r\n\t\t\t\t\t\t}//endfor j\r\n\t\t\t\t\t}//endfor i\r\n\t\t\t\t}//endfor iatom\r\n\t\t\t}\r\n\r\n\t\t\treturn pairs;\r\n\t\t}\r\n\r\n\r\n\t\tneighbourfield Get_Neighbours_in_Radius(const Data::Geometry & geometry, scalar radius)\r\n\t\t{\r\n\t\t\tauto neighbours = neighbourfield(0);\r\n\r\n\t\t\tif (radius > 1e-6)\r\n\t\t\t{\r\n\t\t\t\tVector3 a = geometry.bravais_vectors[0];\r\n\t\t\t\tVector3 b = geometry.bravais_vectors[1];\r\n\t\t\t\tVector3 c = geometry.bravais_vectors[2];\r\n\r\n\t\t\t\tVector3 bounds_diff = geometry.bounds_max - geometry.bounds_min;\r\n\t\t\t\tVector3 ratio = {\r\n\t\t\t\t\tbounds_diff[0]/std::max(1, geometry.n_cells[0]),\r\n\t\t\t\t\tbounds_diff[1]/std::max(1, geometry.n_cells[1]),\r\n\t\t\t\t\tbounds_diff[2]/std::max(1, geometry.n_cells[2]) };\r\n\t\t\t\t\t\r\n\t\t\t\t// This should give enough translations to contain all DDI pairs\r\n\t\t\t\tint imax = 0, jmax = 0, kmax = 0;\r\n\t\t\t\tif ( bounds_diff[0] > 0 )\r\n\t\t\t\t\timax = std::min(geometry.n_cells[0], (int)(1.1 * radius * geometry.n_cells[0] / bounds_diff[0]));\r\n\t\t\t\tif ( bounds_diff[1] > 0 )\r\n\t\t\t\t\tjmax = std::min(geometry.n_cells[1], (int)(1.1 * radius * geometry.n_cells[1] / bounds_diff[1]));\r\n\t\t\t\tif ( bounds_diff[2] > 0 )\r\n\t\t\t\t\tkmax = std::min(geometry.n_cells[2], (int)(1.1 * radius * geometry.n_cells[2] / bounds_diff[2]));\r\n\t\t\t\t\t\r\n\t\t\t\tint i, j, k;\r\n\t\t\t\tscalar dx;\r\n\t\t\t\tVector3 x0 = { 0,0,0 }, x1 = { 0,0,0 };\r\n\r\n\t\t\t\t// Abort condidions for all 3 vectors\r\n\t\t\t\tif (a.norm() == 0.0) imax = 0;\r\n\t\t\t\tif (b.norm() == 0.0) jmax = 0;\r\n\t\t\t\tif (c.norm() == 0.0) kmax = 0;\r\n\r\n\t\t\t\tfor (int iatom = 0; iatom < geometry.n_cell_atoms; ++iatom)\r\n\t\t\t\t{\r\n\t\t\t\t\tx0 = geometry.cell_atoms[iatom];\r\n\t\t\t\t\tfor (i = imax; i >= -imax; --i)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (j = jmax; j >= -jmax; --j)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tfor (k = kmax; k >= -kmax; --k)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tfor (int jatom = 0; jatom < geometry.n_cell_atoms; ++jatom)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tx1 = geometry.cell_atoms[jatom] + i*a + j*b + k*c;\r\n\t\t\t\t\t\t\t\t\tdx = (x0 - x1).norm();\r\n\t\t\t\t\t\t\t\t\tif (dx < radius)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tNeighbour neigh;\r\n\t\t\t\t\t\t\t\t\t\tneigh.i = iatom;\r\n\t\t\t\t\t\t\t\t\t\tneigh.j = jatom;\r\n\t\t\t\t\t\t\t\t\t\tneigh.translations[0] = i;\r\n\t\t\t\t\t\t\t\t\t\tneigh.translations[1] = j;\r\n\t\t\t\t\t\t\t\t\t\tneigh.translations[2] = k;\r\n\t\t\t\t\t\t\t\t\t\tneigh.idx_shell = 0;\r\n\t\t\t\t\t\t\t\t\t\tneighbours.push_back( neigh );\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}//endfor jatom\r\n\t\t\t\t\t\t\t}//endfor k\r\n\t\t\t\t\t\t}//endfor j\r\n\t\t\t\t\t}//endfor i\r\n\t\t\t\t}//endfor iatom\r\n\t\t\t}\r\n\r\n\t\t\treturn neighbours;\r\n\t\t}\r\n\r\n\r\n\t\tVector3 DMI_Normal_from_Pair(const Data::Geometry & geometry, const Pair & pair, int chirality)\r\n\t\t{\r\n\t\t\tVector3 ta = geometry.bravais_vectors[0];\r\n\t\t\tVector3 tb = geometry.bravais_vectors[1];\r\n\t\t\tVector3 tc = geometry.bravais_vectors[2];\r\n\r\n\t\t\tint da = pair.translations[0];\r\n\t\t\tint db = pair.translations[1];\r\n\t\t\tint dc = pair.translations[2];\r\n\r\n\t\t\tVector3 ipos = geometry.cell_atoms[pair.i];\r\n\t\t\tVector3 jpos = geometry.cell_atoms[pair.j] + da*ta + db*tb + dc*tc;\r\n\r\n\t\t\tif (chirality == 1)\r\n\t\t\t{\r\n\t\t\t\t// Bloch chirality\r\n\t\t\t\treturn (jpos - ipos).normalized();\r\n\t\t\t}\r\n\t\t\telse if (chirality == -1)\r\n\t\t\t{\r\n\t\t\t\t// Inverse Bloch chirality\r\n\t\t\t\treturn (ipos - jpos).normalized();\r\n\t\t\t}\r\n\t\t\telse if (chirality == 2)\r\n\t\t\t{\r\n\t\t\t\t// Neel chirality (surface)\r\n\t\t\t\treturn (jpos - ipos).normalized().cross(Vector3{0,0,1});\r\n\t\t\t}\r\n\t\t\telse if (chirality == -2)\r\n\t\t\t{\r\n\t\t\t\t// Inverse Neel chirality (surface)\r\n\t\t\t\treturn Vector3{0,0,1}.cross((jpos - ipos).normalized());\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\treturn Vector3{ 0,0,0 };\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid DDI_from_Pair(const Data::Geometry & geometry, const Pair & pair, scalar & magnitude, Vector3 & normal)\r\n\t\t{\r\n\t\t\tVector3 ta = geometry.bravais_vectors[0];\r\n\t\t\tVector3 tb = geometry.bravais_vectors[1];\r\n\t\t\tVector3 tc = geometry.bravais_vectors[2];\r\n\r\n\t\t\tint da = pair.translations[0];\r\n\t\t\tint db = pair.translations[1];\r\n\t\t\tint dc = pair.translations[2];\r\n\r\n\t\t\tVector3 ipos = geometry.cell_atoms[pair.i];\r\n\t\t\tVector3 jpos = geometry.cell_atoms[pair.j] + da*ta + db*tb + dc*tc;\r\n\r\n\t\t\t// Calculate positions and difference vector\r\n\t\t\tVector3 vector_ij = jpos - ipos;\r\n\r\n\t\t\t// Length of difference vector\r\n\t\t\tmagnitude = vector_ij.norm();\r\n\t\t\tnormal = vector_ij.normalized();\r\n\t\t}\r\n\r\n\t}// end Namespace Neighbours\r\n}// end Namespace Engine\r\n", "meta": {"hexsha": "8f079add0c8a242352a690309e0921cbc0c63e25", "size": 11917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/engine/Neighbours.cpp", "max_stars_repo_name": "SpiritSuperUser/spirit", "max_stars_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T13:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T09:10:27.000Z", "max_issues_repo_path": "core/src/engine/Neighbours.cpp", "max_issues_repo_name": "SpiritSuperUser/spirit", "max_issues_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/src/engine/Neighbours.cpp", "max_forks_repo_name": "SpiritSuperUser/spirit", "max_forks_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7139175258, "max_line_length": 146, "alphanum_fraction": 0.5579424352, "num_tokens": 3880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.44243374814337677}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// IncompressibleBalloonEnergy.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//  Implementation of the incompressible neo-Hookean-based strain energy\n//  density used in Skouras 2014: Designing Inflatable Structures (before\n//  homogenizing away the wrinkles using a relaxed energy density).\n//\n//  This energy is implemented as a function of the right Green-Green\n//  deformation tensor.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Created:  04/04/2019 18:19:10\n////////////////////////////////////////////////////////////////////////////////\n#ifndef INCOMPRESSIBLEBALLOONENERGY_HH\n#define INCOMPRESSIBLEBALLOONENERGY_HH\n\n#include <Eigen/Dense>\n#include <array>\n#include <MeshFEM/EnergyDensities/Tensor.hh>\n\ntemplate<typename Real>\nstruct IncompressibleBalloonEnergy {\n    using V2d  = Eigen::Matrix<Real, 2, 1>;\n    using M2d  = Eigen::Matrix<Real, 2, 2>;\n\n    IncompressibleBalloonEnergy() { }\n\n    template<typename Derived>\n    IncompressibleBalloonEnergy(const Eigen::MatrixBase<Derived> &C) { setMatrix(C); }\n\n    template<typename Derived>\n    void setMatrix(const Eigen::MatrixBase<Derived> &C) {\n        static_assert((Derived::RowsAtCompileTime == 2) && (Derived::ColsAtCompileTime == 2), \"Only 2x2 supported for now\");\n\n        Real a = C(0, 0),\n             b = C(0, 1),\n             c = C(1, 1);\n        if (std::abs(b - C(1, 0)) > 1e-15) throw std::runtime_error(\"Asymmetric matrix\");\n\n        m_C = C;\n        m_trace_C = C.trace();\n        m_det_C = a * c - b * b;\n        m_grad_det_C <<  c, -b,\n                        -b,  a;\n    }\n\n    Real energy() const {\n        return stiffness * (m_trace_C + 1.0 / m_det_C - 3.0);\n    }\n\n    Real denergy(const M2d &dC) const {\n        return stiffness * (dC.trace() - (1.0 / (m_det_C * m_det_C)) * doubleContract(m_grad_det_C, dC));\n    }\n\n    M2d denergy() const {\n        return stiffness * (M2d::Identity() - (1.0 / (m_det_C * m_det_C)) * m_grad_det_C);\n    }\n\n    Real d2energy(const M2d &dC_a, const M2d &dC_b) const {\n        return stiffness * ((2.0 / (m_det_C * m_det_C * m_det_C)) * doubleContract(m_grad_det_C, dC_a) * doubleContract(m_grad_det_C, dC_b)\n                          - (1.0 / (m_det_C * m_det_C)) * (dC_a(1, 1) * dC_b(0, 0) + dC_a(0, 0) * dC_b(1, 1) - 2 * dC_a(0, 1) * dC_b(0, 1)));\n    }\n\n    M2d delta_denergy(const M2d &dC) const {\n        M2d adj_dC;\n        adj_dC << dC(1, 1), -dC(0, 1),\n                 -dC(1, 0),  dC(0, 0);\n        return (((2.0 * stiffness / (m_det_C * m_det_C * m_det_C)) * doubleContract(m_grad_det_C, dC)) * m_grad_det_C\n                     - (stiffness / (m_det_C * m_det_C))                                               * adj_dC);\n    }\n\n    // Second derivatives evaluated at the reference configuration\n    M2d delta_denergy_undeformed(const M2d &dC) const {\n        return stiffness * (dC.trace() * M2d::Identity() + dC);\n    }\n\n    Real stiffness = 1.0;\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    Real m_trace_C, m_det_C;\n    M2d m_grad_det_C;\n    M2d m_C;\n};\n\n#endif /* end of include guard: INCOMPRESSIBLEBALLOONENERGY_HH */\n", "meta": {"hexsha": "139b6759f0561a3925a3ca406857233b8226a599", "size": 3213, "ext": "hh", "lang": "C++", "max_stars_repo_path": "IncompressibleBalloonEnergy.hh", "max_stars_repo_name": "jpanetta/Inflatables", "max_stars_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T18:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:35:04.000Z", "max_issues_repo_path": "IncompressibleBalloonEnergy.hh", "max_issues_repo_name": "jpanetta/Inflatables", "max_issues_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IncompressibleBalloonEnergy.hh", "max_forks_repo_name": "jpanetta/Inflatables", "max_forks_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-24T22:26:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-14T21:51:18.000Z", "avg_line_length": 36.5113636364, "max_line_length": 141, "alphanum_fraction": 0.5642701525, "num_tokens": 960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799253, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4424337412119467}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2014, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/* Computation of eigenvalues of a symmetric, tridiagonal matrix using\n * bisection.\n */\n\n#ifndef NDEBUG\n  #define NDEBUG\n#endif\n\n// includes, system\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n\n\n// includes, project\n\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n\n#include \"viennacl/linalg/bisect_gpu.hpp\"\n#include \"viennacl/linalg/bisect.hpp\"\n#include \"viennacl/linalg/tql2.hpp\"\n\n#include <examples/benchmarks/benchmark-utils.hpp>\n//#include <Eigen/Eigenvalues>\n//using namespace Eigen;\n\n#define EPS 10.0e-4\n\ntypedef float NumericT;\n\n////////////////////////////////////////////////////////////////////////////////\n/// \\brief initInputData   Initialize the diagonal and superdiagonal elements of\n///                        the matrix\n/// \\param diagonal        diagonal elements of the matrix\n/// \\param superdiagonal   superdiagonal elements of the matrix\n/// \\param mat_size        Dimension of the matrix\n///\nvoid\ninitInputData(viennacl::vector<NumericT> &diagonal, viennacl::vector<NumericT> &superdiagonal, const unsigned int mat_size)\n{\n\n  srand(time(NULL));\n\n#define RANDOM_VALUES 0\n  if (RANDOM_VALUES == true)\n  {\n    // Initialize diagonal and superdiagonal elements with random values\n    for (unsigned int i = 0; i < mat_size; ++i)\n    {\n        diagonal[i] =      static_cast<NumericT>(2.0 * (((double)rand()\n                                     / (double) RAND_MAX) - 0.5));\n        superdiagonal[i] = static_cast<NumericT>(2.0 * (((double)rand()\n                                     / (double) RAND_MAX) - 0.5));\n    }\n  }\n  else\n  {\n    // Initialize diagonal and superdiagonal elements with modulo values\n    // This will cause in many multiple eigenvalues.\n    for (unsigned int i = 0; i < mat_size; ++i)\n    {\n       diagonal[i] = ((NumericT)(i % 37)) - 4.5f;\n       superdiagonal[i] = ((NumericT)(i % 5)) - 4.5f;\n    }\n  }\n  // the first element of s is used as padding on the device (thus the\n  // whole vector is copied to the device but the kernels are launched\n  // with (s+1) as start address\n  superdiagonal[0] = 0.0f;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n//! Run a simple test\n////////////////////////////////////////////////////////////////////////////////\nbool\nrunTest(const int mat_size, std::vector<double> &av_time_all, unsigned int time_index)\n    {\n    bool bResult = false;\n    viennacl::vector<NumericT> diagonal(mat_size);\n    viennacl::vector<NumericT> superdiagonal(mat_size);\n    viennacl::vector<NumericT> eigenvalues_bisect(mat_size);\n    std::vector<NumericT> eigenvalues_bisect_cpu(mat_size);\n\n\n    // -------Start the bisection algorithm------------\n    std::cout << \"Matrix size: \" << mat_size << std::endl;\n\n    unsigned int iterations = 10;\n    double time_all     = 0.0;\n\n    for(unsigned int i = 0; i < iterations; i++)\n    {\n      initInputData(diagonal, superdiagonal, mat_size);\n\n      Timer timer;\n      timer.start();\n\n      // bisection - gpu\n      bResult = viennacl::linalg::bisect(diagonal, superdiagonal, eigenvalues_bisect);\n      viennacl::backend::finish();     // sync\n      //---Run the tql algorithm-----------------------------------\n     // viennacl::linalg::tql1<NumericT>(mat_size, diagonal, superdiagonal);\n     // bResult = true;\n\n      // Run the bisect algorithm for CPU only\n      //eigenvalues_bisect_cpu = viennacl::linalg::bisect(diagonal, superdiagonal);\n      // bResult = true;\n\n      time_all     += timer.get() * 1000;\n      if (bResult == false)\n       return false;\n\n    }\n\n\n    std::cout << \"Time: \\t\" << time_all / (double)iterations << \"ms\" << std::endl << std::endl;\n\n    av_time_all[time_index] = time_all / (double)iterations;\n\n  return bResult;\n\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n// Program main\n////////////////////////////////////////////////////////////////////////////////\nint\nmain(int argc, char **argv)\n{\n    bool test_result = true;\n    unsigned int time_index = 0;\n    std::vector<double> av_time_all(500);\n    std::vector<unsigned int> mat_sizes(500);\n\n    for( unsigned int mat_size = 16;\n         mat_size < 600;\n         mat_size = mat_size * 1.15, time_index++)\n      {\n      test_result = runTest(mat_size, av_time_all, time_index);\n      mat_sizes[time_index] = mat_size;\n\n\n      if(test_result == true)\n      {\n        //std::cout << \"Success!\" << std::endl << std::endl;\n      }\n      else\n      {\n        std::cout << \"---FAIL---\" << std::endl;\n        exit(EXIT_FAILURE);\n      }\n    }\n\n    std::cout << \"Times\" << std::endl;\n    for(unsigned int i = 0; i < time_index; i++)\n    {\n      std::cout <<  mat_sizes[i] << \"\\t\" << av_time_all[i] << std::endl;\n    }\n\n\n\n\n}\n\n", "meta": {"hexsha": "4a01793031d275ebd40f037783220421b048947a", "size": 5526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/src/bisect_bench.cpp", "max_stars_repo_name": "denis14/ViennaCL-1.5.2", "max_stars_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/src/bisect_bench.cpp", "max_issues_repo_name": "denis14/ViennaCL-1.5.2", "max_issues_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/src/bisect_bench.cpp", "max_forks_repo_name": "denis14/ViennaCL-1.5.2", "max_forks_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.550802139, "max_line_length": 123, "alphanum_fraction": 0.5434310532, "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.4423863404922818}}
{"text": "#include <iostream>\n\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n\n#include <unsupported/Eigen/SparseExtra> // For reading MatrixMarket files\n\n#include <amgcl/backend/eigen.hpp>\n#include <amgcl/make_solver.hpp>\n#include <amgcl/solver/bicgstab.hpp>\n#include <amgcl/amg.hpp>\n#include <amgcl/coarsening/smoothed_aggregation.hpp>\n#include <amgcl/relaxation/spai0.hpp>\n\nint main(int argc, char *argv[]) {\n    if (argc < 2) {\n        std::cerr << \"Usage: \" << argv[0] << \" <matrix.mm>\" << std::endl;\n        return 1;\n    }\n\n    // Read sparse matrix from MatrixMarket format.\n    // In general this should come pre-assembled.\n    Eigen::SparseMatrix<double, Eigen::RowMajor> A;\n    Eigen::loadMarket(A, argv[1]);\n\n    // Use vector of ones as RHS for simplicity:\n    Eigen::VectorXd f = Eigen::VectorXd::Constant(A.rows(), 1.0);\n\n    // Zero initial approximation:\n    Eigen::VectorXd x = Eigen::VectorXd::Zero(A.rows());\n\n    // Setup the solver:\n    typedef amgcl::make_solver<\n        amgcl::amg<\n            amgcl::backend::eigen<double>,\n            amgcl::coarsening::smoothed_aggregation,\n            amgcl::relaxation::spai0\n            >,\n        amgcl::solver::bicgstab<amgcl::backend::eigen<double> >\n        > Solver;\n\n    Solver solve(A);\n    std::cout << solve << std::endl;\n\n    // Solve the system for the given RHS:\n    int    iters;\n    double error;\n    std::tie(iters, error) = solve(f, x);\n\n    std::cout << iters << \" \" << error << std::endl;\n}", "meta": {"hexsha": "f77c1fa629e50c3234637a53fff2998619dd5f7e", "size": 1463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "docs/codes/AMG/main.cpp", "max_stars_repo_name": "ziyiyin97/FwiFlow.jl", "max_stars_repo_head_hexsha": "a7f16b7585524fdbc44b44050d6d7f7ad2ab204b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-12-24T16:50:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T02:54:35.000Z", "max_issues_repo_path": "docs/codes/AMG/main.cpp", "max_issues_repo_name": "ziyiyin97/FwiFlow.jl", "max_issues_repo_head_hexsha": "a7f16b7585524fdbc44b44050d6d7f7ad2ab204b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-08-13T17:00:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T13:48:59.000Z", "max_forks_repo_path": "docs/codes/AMG/main.cpp", "max_forks_repo_name": "ziyiyin97/FwiFlow.jl", "max_forks_repo_head_hexsha": "a7f16b7585524fdbc44b44050d6d7f7ad2ab204b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-01-20T06:16:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T03:05:45.000Z", "avg_line_length": 28.6862745098, "max_line_length": 74, "alphanum_fraction": 0.6261107314, "num_tokens": 409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4423721865034699}}
{"text": "#pragma once\r\n\r\n#include \"Material.hpp\"\r\n#include \"Vec3.hpp\"\r\n#include \"Ray.hpp\"\r\n#include \"Color.hpp\"\r\n\r\n#include <boost\\optional.hpp>\r\n\r\n#ifdef USE_AMP\r\n#include <amp_math.h>\r\n#endif\r\n\r\nnamespace Smurf {\r\n    enum ActiveMaterial { ActiveMatte, ActiveGlossy };\r\n\r\n    struct RayHit {\r\n        RayHit() : depth{0}, hitPoint{0.0, 0.0, 0.0}, tMin{0.0}  { }\r\n        RayHit(double tMin) : tMin{tMin} { }\r\n        RayHit(double tMin, Vec3<double> hitPoint, int depth) : depth{depth}, hitPoint{hitPoint}, tMin{tMin} { }\r\n\r\n        int depth;\r\n        Vec3<double> hitPoint;\r\n        double tMin;\r\n    };\r\n\r\n    struct GeometricObject {\r\n        GeometricObject() : color{0.7F, 0.65F, 1.0F} { }\r\n        GeometricObject(Color color) : color{color} { }\r\n        GeometricObject(Color color, Matte material) : color{ color }, matte{ material }, active{ ActiveMaterial::ActiveMatte } { }\r\n        GeometricObject(Color color, Glossy material) : color{ color }, glossy{ material }, active{ ActiveMaterial::ActiveGlossy } { }\r\n        virtual boost::optional<RayHit> onRayCast(const Ray& ray) = 0;\r\n        virtual ~GeometricObject() { }\r\n        // Probably replace this later\r\n        Color color;\r\n        Matte matte;\r\n        Glossy glossy;\r\n        ActiveMaterial active;\r\n    };\r\n\r\n    class Plane : public GeometricObject {\r\n    public:\r\n        Plane() : point{0.0, 0.0, 0.0}, normal{0.0, 1.0, 0.0} { }\r\n        Plane(const Vec3<double>& point, const Vec3<double>& normal, Color color) : GeometricObject{color},\r\n                                                                                    point{point},\r\n                                                                                    normal{normal} { }\r\n        Plane(const Vec3<double>& point, const Vec3<double>& normal, Color color, Matte matte) : GeometricObject{ color, matte },\r\n                                                                                                 point{ point },\r\n                                                                                                 normal{ normal } { }\r\n        Plane(const Vec3<double>& point, const Vec3<double>& normal, Color color, Glossy glossy) : GeometricObject{ color, glossy },\r\n                                                                                                   point{ point },\r\n                                                                                                   normal{ normal } { }\r\n        boost::optional<RayHit> onRayCast(const Ray& ray) override {\r\n            auto t = (point - ray.origin) * normal / (ray.direction * normal);\r\n            if (t > 0) {\r\n                RayHit hit(t);\r\n                return boost::optional<RayHit>(hit);\r\n            }\r\n            // Didn't hit\r\n            return boost::optional<RayHit>();\r\n        }\r\n        #ifdef USE_AMP\r\n        const Vec3<double>& getPoint() {\r\n            return point;\r\n        }\r\n        const Vec3<double>& getNormal() {\r\n            return normal;\r\n        }\r\n        #endif\r\n    private:\r\n        Vec3<double> point;\r\n        Vec3<double> normal;\r\n    };\r\n\r\n    class Sphere : public GeometricObject {\r\n    public:\r\n        Sphere() : center{0.0, 0.0, 0.0}, radius{1.0} { }\r\n        Sphere(const Vec3<double>& center, double radius) : center{center},\r\n                                                            radius{radius} { }\r\n        Sphere(const Vec3<double>& center, double radius, Matte material) : GeometricObject{ {0.0F, 0.0F, 0.0F}, material },\r\n                                                                            center{ center },\r\n                                                                            radius{ radius } { }\r\n        Sphere(const Vec3<double>& center, double radius, Glossy material) : GeometricObject{ { 0.0F, 0.0F, 0.0F }, material },\r\n                                                                            center{ center },\r\n                                                                            radius{ radius } { }\r\n        boost::optional<RayHit> onRayCast(const Ray& ray) override {\r\n            auto temp = ray.origin - center;\r\n            auto a = ray.direction * ray.direction;\r\n            auto b = ray.direction * (2.0 * temp);\r\n            auto c = temp * temp - radius * radius;\r\n            auto discriminant = b * b - (4.0 * a * c);\r\n\r\n            // Didn't hit\r\n            if (discriminant < 0.0) return boost::optional<RayHit>();\r\n\r\n            auto e = sqrt(discriminant);\r\n            auto quadraticDenominator = 2.0 * a;\r\n\r\n            auto finalize = [](double tMin) -> boost::optional<RayHit> {\r\n                RayHit hit(tMin);\r\n                return boost::optional<RayHit>(hit);\r\n            };\r\n\r\n            auto t = (-b - e) / quadraticDenominator;\r\n            if (t > 0) return finalize(t);\r\n\r\n            t = (-b + e) / quadraticDenominator;\r\n            if (t > 0) return finalize(t);\r\n\r\n            // Didn't hit\r\n            return boost::optional<RayHit>();\r\n        }\r\n        #ifdef USE_AMP\r\n        const Vec3<double>& getCenter() {\r\n            return center;\r\n        }\r\n        double getRadius() {\r\n            return radius;\r\n        }\r\n        #endif\r\n    private:\r\n        Vec3<double> center;\r\n        double radius;\r\n    };\r\n\r\n    class Rectangle : public GeometricObject {\r\n    public:\r\n        Rectangle() : point{0.0, 0.0, 0.0}, a{5.0, 0.0, 0.0}, b{0.0, -5.0, 0.0}, normal{0.0, 0.0, 1.0} { }\r\n        Rectangle(Vec3<double> point, Vec3<double> a, Vec3<double> b, Vec3<double> normal) : point{point}, a{a}, b{b}, normal{normal} { }\r\n        Rectangle(Vec3<double> point, Vec3<double> a, Vec3<double> b, Vec3<double> normal, Matte material) : GeometricObject{ { 0.0F, 0.0F, 0.0F }, material }, point{ point }, a{ a }, b{ b }, normal{ normal } { }\r\n        Rectangle(Vec3<double> point, Vec3<double> a, Vec3<double> b, Vec3<double> normal, Glossy material) : GeometricObject{ { 0.0F, 0.0F, 0.0F }, material }, point{ point }, a{ a }, b{ b }, normal{ normal } { }\r\n\r\n        boost::optional<RayHit> onRayCast(const Ray& ray) override {\r\n            double t = (point - ray.origin) * normal / (ray.direction * normal);\r\n            if (t <= 0) return {};\r\n\r\n            auto temp = ray.origin + t * ray.direction;\r\n            auto tempDir = temp - point;\r\n\r\n            auto tempDirDotSide = tempDir * a;\r\n            if (tempDirDotSide > a.lengthSquared() || tempDirDotSide < 0.0) {\r\n                return {};\r\n            }\r\n\r\n            tempDirDotSide = tempDir * b;\r\n            if (tempDirDotSide > b.lengthSquared() || tempDirDotSide < 0.0) {\r\n                return {};\r\n            }\r\n\r\n            return {{t}};\r\n        }\r\n        #ifdef USE_AMP\r\n        const Vec3<double>& getPoint() {\r\n            return point;\r\n        }\r\n        const Vec3<double>& getA() {\r\n            return a;\r\n        }\r\n        const Vec3<double>& getB() {\r\n            return b;\r\n        }\r\n        const Vec3<double>& getNormal() {\r\n            return normal;\r\n        }\r\n        #endif\r\n    private:\r\n        Vec3<double> point;\r\n        Vec3<double> a, b;\r\n        Vec3<double> normal;\r\n    };\r\n    #ifdef USE_AMP\r\n\r\n    struct g_Plane {\r\n    public:\r\n        g_Plane() restrict(cpu, amp) : point{ 0.0, 0.0, 0.0 }, normal{ 0.0, 1.0, 0.0 }, matte{}, active{ ActiveMaterial::ActiveMatte } { }\r\n        g_Plane(const Vec3<double>& point, const Vec3<double>& normal, const Matte& material) restrict(cpu, amp) : point{ point },\r\n                                                                                                                   normal{ normal },\r\n                                                                                                                   matte{ material },\r\n                                                                                                                   active{ ActiveMaterial::ActiveMatte } { }\r\n        g_Plane(const Vec3<double>& point, const Vec3<double>& normal, const Glossy& material) restrict(cpu, amp) : point{ point },\r\n                                                                                                                    normal{ normal },\r\n                                                                                                                    glossy{ material },\r\n                                                                                                                    active{ ActiveMaterial::ActiveGlossy } { }\r\n        Vec3<double> point;\r\n        Vec3<double> normal;\r\n        ActiveMaterial active;\r\n        Matte matte;\r\n        Glossy glossy;\r\n    };\r\n\r\n    struct g_Sphere {\r\n        g_Sphere() restrict(amp) : center{ 0.0, 0.0, 0.0 }, radius{ 1.0 }, matte{}, active{ ActiveMaterial::ActiveMatte } { }\r\n        g_Sphere(const Vec3<double>& center, double radius, const Matte& material) restrict(cpu, amp) : center{center},\r\n                                                                                                        radius{radius},\r\n                                                                                                        matte{material},\r\n                                                                                                        active{ ActiveMaterial::ActiveMatte } { }\r\n        g_Sphere(const Vec3<double>& center, double radius, const Glossy& material) restrict(cpu, amp) : center{ center },\r\n                                                                                                        radius{ radius },\r\n                                                                                                        glossy{ material },\r\n                                                                                                        active{ ActiveMaterial::ActiveGlossy } { }\r\n        ActiveMaterial active;\r\n        Vec3<double> center;\r\n        double radius;\r\n        Matte matte;\r\n        Glossy glossy;\r\n    };\r\n\r\n    struct g_Rectangle {\r\n        g_Rectangle() restrict(cpu, amp) : point{0.0, 0.0, 0.0}, a{5.0, 0.0, 0.0}, b{0.0, -5.0, 0.0}, normal{0.0, 0.0, 1.0} { }\r\n        g_Rectangle(const Vec3<double>& point, const Vec3<double>& a, const Vec3<double>& b, const Vec3<double>& normal, const Matte& matte) restrict(cpu, amp) : point{ point }, a{ a }, b{ b }, normal{ normal }, matte{ matte }, active{ ActiveMaterial::ActiveMatte } { }\r\n        g_Rectangle(const Vec3<double>& point, const Vec3<double>& a, const Vec3<double>& b, const Vec3<double>& normal, const Glossy& glossy) restrict(cpu, amp) : point{ point }, a{ a }, b{ b }, normal{ normal }, glossy{ glossy }, active{ ActiveMaterial::ActiveGlossy } { }\r\n        g_Rectangle(const g_Rectangle& other) restrict(cpu, amp) : point{ other.point }, a{ other.a }, b{ other.b }, normal{ other.normal }, matte{ other.matte }, glossy{ other.glossy }, active{ other.active } { }\r\n        g_Rectangle(g_Rectangle&& other) restrict(cpu, amp) : point{static_cast<Vec3<double>&&>(other.point)},\r\n                                                              a{static_cast<Vec3<double>&&>(other.a)},\r\n                                                              b{static_cast<Vec3<double>&&>(other.b)},\r\n                                                              normal{static_cast<Vec3<double>&&>(other.normal)},\r\n                                                              matte{static_cast<Matte&&>(other.matte)},\r\n                                                              glossy{ static_cast<Glossy&&>(other.glossy)},\r\n                                                              active{ static_cast<ActiveMaterial&&>(other.active) } { }\r\n        g_Rectangle& operator=(const g_Rectangle& other) restrict(cpu, amp) {\r\n            point = other.point;\r\n            a = other.a;\r\n            b = other.b;\r\n            normal = other.normal;\r\n            active = other.active;\r\n            return *this;\r\n        }\r\n\r\n        ActiveMaterial active;\r\n        Vec3<double> point;\r\n        Vec3<double> a, b;\r\n        Vec3<double> normal;\r\n        Matte matte;\r\n        Glossy glossy;\r\n    };\r\n\r\n    struct g_RayHit {\r\n        g_RayHit() restrict(amp) : hasHit{false} { }\r\n        g_RayHit(double tMin, const Vec3<double>& normal, ActiveMaterial active) restrict(amp) : tMin{ tMin }, normal{ normal }, hasHit{ true }, active{ active } { }\r\n\r\n        operator bool() const restrict(amp) {\r\n            return hasHit;\r\n        }\r\n\r\n        Ray ray;\r\n        int depth;\r\n        ActiveMaterial active;\r\n        Vec3<double> hitPoint;\r\n        Vec3<double> normal;\r\n        Matte matte;\r\n        Glossy glossy;\r\n        double tMin;\r\n        bool hasHit;\r\n    };\r\n\r\n    struct g_ShadowRayHit {\r\n        g_ShadowRayHit() restrict(amp) : hasHit{false} { }\r\n        g_ShadowRayHit(float t) restrict(amp) : t{t}, hasHit{true} { }\r\n\r\n        operator bool() const restrict(amp) {\r\n            return hasHit;\r\n        }\r\n\r\n        float t;\r\n        bool hasHit;\r\n    };\r\n\r\n    namespace OnRayCastAspect {\r\n        static float const GetEpsilon() restrict(cpu, amp) {\r\n            return 0.0001F;\r\n        }\r\n\r\n        g_RayHit onRayCast(const g_Plane& plane, const Ray& ray) restrict(amp) {\r\n            auto t = (plane.point - ray.origin) * plane.normal / (ray.direction * plane.normal);\r\n            if (t > GetEpsilon()) {\r\n                g_RayHit hit{t, plane.normal, plane.active};\r\n                return hit;\r\n            }\r\n            // Didn't hit\r\n            return {};\r\n        }\r\n\r\n        g_ShadowRayHit onShadowRayCast(const g_Plane& plane, const Ray& ray) restrict(amp) {\r\n            auto t = static_cast<float>((plane.point - ray.origin) * plane.normal / (ray.direction * plane.normal));\r\n            if (t > GetEpsilon()) {\r\n                return {t};\r\n            }\r\n            return {};\r\n        }\r\n\r\n        g_RayHit onRayCast(const g_Sphere& sphere, const Ray& ray) restrict(amp) {\r\n            auto temp = ray.origin - sphere.center;\r\n            auto a = ray.direction * ray.direction;\r\n            auto b = ray.direction * (2.0 * temp);\r\n            auto c = temp * temp - sphere.radius * sphere.radius;\r\n            auto discriminant = b * b - (4.0 * a * c);\r\n\r\n            // Didn't hit\r\n            if (discriminant < 0.0) return {};\r\n\r\n            auto e = Concurrency::fast_math::sqrt(static_cast<float>(discriminant));\r\n            auto quadraticDenominator = 2.0 * a;\r\n\r\n            auto finalize = [](double tMin, const Vec3<double>& normal, const g_Sphere& sphere) restrict(amp) {\r\n                return g_RayHit{tMin, normal, sphere.active};\r\n            };\r\n\r\n            auto t = (-b - e) / quadraticDenominator;\r\n            if (t > GetEpsilon()) return finalize(t, (temp + t * ray.direction).normalizeAndReturn(), sphere);\r\n\r\n            t = (-b + e) / quadraticDenominator;\r\n            if (t > GetEpsilon()) return finalize(t, (temp + t * ray.direction).normalizeAndReturn(), sphere);\r\n\r\n            // Didn't hit\r\n            return {};\r\n        }\r\n\r\n        g_ShadowRayHit onShadowRayCast(const g_Sphere& sphere, const Ray& ray) restrict(amp) {\r\n            auto temp = ray.origin - sphere.center;\r\n            auto a = ray.direction * ray.direction;\r\n            auto b = ray.direction * (2.0 * temp);\r\n            auto c = temp * temp - sphere.radius * sphere.radius;\r\n            auto discriminant = b * b - (4.0 * a * c);\r\n\r\n            // Didn't hit\r\n            if (discriminant < 0.0) return {};\r\n\r\n            auto e = Concurrency::fast_math::sqrt(static_cast<float>(discriminant));\r\n            auto quadraticDenominator = 2.0 * a;\r\n\r\n            auto t = static_cast<float>((-b - e) / quadraticDenominator);\r\n            if (t > GetEpsilon()) return {t};\r\n\r\n            t = static_cast<float>((-b + e) / quadraticDenominator);\r\n            if (t > GetEpsilon()) return {t};\r\n\r\n            // Didn't hit\r\n            return {};\r\n        }\r\n\r\n        g_RayHit onRayCast(const g_Rectangle& rect, const Ray& ray) restrict(amp) {\r\n            double t = (rect.point - ray.origin) * rect.normal / (ray.direction * rect.normal);\r\n            \r\n            // Didn't hit\r\n            if (t <= 0) return {};\r\n\r\n            auto temp = ray.origin + t * ray.direction;\r\n            auto tempDir = temp - rect.point;\r\n\r\n            auto tempDirDotSide = tempDir * rect.a;\r\n            if (tempDirDotSide > rect.a.lengthSquared() || tempDirDotSide < 0.0) {\r\n                // Didn't hit\r\n                return {};\r\n            }\r\n\r\n            tempDirDotSide = tempDir * rect.b;\r\n            if (tempDirDotSide > rect.b.lengthSquared() || tempDirDotSide < 0.0) {\r\n                // Didn't hit\r\n                return {};\r\n            }\r\n\r\n            return {t, rect.normal, rect.active};\r\n        }\r\n\r\n        g_ShadowRayHit onShadowRayCast(const g_Rectangle& rect, const Ray& ray) restrict(amp) {\r\n            double t = (rect.point - ray.origin) * rect.normal / (ray.direction * rect.normal);\r\n\r\n            // Didn't hit\r\n            if (t <= 0) return {};\r\n\r\n            auto temp = ray.origin + t * ray.direction;\r\n            auto tempDir = temp - rect.point;\r\n\r\n            auto tempDirDotSide = tempDir * rect.a;\r\n            if (tempDirDotSide > rect.a.lengthSquared() || tempDirDotSide < 0.0) {\r\n                // Didn't hit\r\n                return {};\r\n            }\r\n\r\n            tempDirDotSide = tempDir * rect.b;\r\n            if (tempDirDotSide > rect.b.lengthSquared() || tempDirDotSide < 0.0) {\r\n                // Didn't hit\r\n                return {};\r\n            }\r\n\r\n            return {static_cast<float>(t)};\r\n        }\r\n    } // namespace OnRayCastAspect\r\n    #endif\r\n} // namespace Smurf", "meta": {"hexsha": "6d2ef0483242d96863734cea5c7a69380b119f46", "size": 17619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GeometricObject.hpp", "max_stars_repo_name": "Ferinko/CPPAmpRaytracer", "max_stars_repo_head_hexsha": "459d9804cadd0489eea335cf4b6ba4a1256f76dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GeometricObject.hpp", "max_issues_repo_name": "Ferinko/CPPAmpRaytracer", "max_issues_repo_head_hexsha": "459d9804cadd0489eea335cf4b6ba4a1256f76dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GeometricObject.hpp", "max_forks_repo_name": "Ferinko/CPPAmpRaytracer", "max_forks_repo_head_hexsha": "459d9804cadd0489eea335cf4b6ba4a1256f76dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1769230769, "max_line_length": 275, "alphanum_fraction": 0.4625688178, "num_tokens": 3901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.44236386884272844}}
{"text": "// Copyright (c) 2012-2017 VideoStitch SAS\n// Copyright (c) 2018 stitchEm\n\n#ifndef __JACOBIANS__HPP\n#define __JACOBIANS__HPP\n\n#include <Eigen/Dense>\n\nnamespace VideoStitch {\nnamespace Calibration {\n\n/**\n@brief Compute the jacobian of the function which computes a rotation matrix from yaw pitch and roll wrt yaw pitch roll\n@param J the output jacobian matrix\n@param yaw the yaw rotation input parameter\n@param pitch the pitch rotation input parameter\n@param roll the roll rotation input parameter\n*/\nvoid getJacobianRotationWrtYawPitchRoll(Eigen::Matrix<double, 9, 3>& J, double yaw, double pitch, double roll);\n\n/**\n@brief Compute the jacobian of the function which computes yaw pitch roll from a rotation matrix wrt the rotation matrix\n@param J the output jacobian\n@param r the input rotation matrix\n*/\nvoid getJacobianYawPitchRollWrtRotation(Eigen::Matrix<double, 3, 9>& J, const Eigen::Matrix3d& r);\n\n/**\n@brief Compute the jacobian of the logSO3 wrt the input rotation matrix\n@param J the output jacobian\n@param R the input rotation matrix\n*/\nvoid getJacobianAxisAngleWrtRotation(Eigen::Matrix<double, 3, 9>& J, const Eigen::Matrix3d& R);\n\n/**\n@brief Compute the jacobian of matrix multiplication A*B.t() wrt A\n@param J the result jacobian\n@param A the first operand\n@param B the second operand\n*/\nvoid computedABtdA(Eigen::Matrix<double, 9, 9>& J, const Eigen::Matrix3d& A, const Eigen::Matrix3d& B);\n\n/**\n@brief Compute the jacobian of matrix multiplication A*B.t() wrt B\n@param J the result jacobian\n@param A the first operand\n@param B the second operand\n*/\nvoid computedABtdB(Eigen::Matrix<double, 9, 9>& J, const Eigen::Matrix3d& A, const Eigen::Matrix3d& B);\n\n}  // namespace Calibration\n}  // namespace VideoStitch\n\n#endif\n", "meta": {"hexsha": "88ea077bdbe6f5c7010d3b7eae859a1de90b3e3a", "size": 1735, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/src/calibration/jacobians.hpp", "max_stars_repo_name": "tlalexander/stitchEm", "max_stars_repo_head_hexsha": "cdff821ad2c500703e6cb237ec61139fce7bf11c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 182.0, "max_stars_repo_stars_event_min_datetime": "2019-04-19T12:38:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T16:48:20.000Z", "max_issues_repo_path": "lib/src/calibration/jacobians.hpp", "max_issues_repo_name": "doymcc/stitchEm", "max_issues_repo_head_hexsha": "20693a55fa522d7a196b92635e7a82df9917c2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107.0, "max_issues_repo_issues_event_min_datetime": "2019-04-23T10:49:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T18:12:28.000Z", "max_forks_repo_path": "lib/src/calibration/jacobians.hpp", "max_forks_repo_name": "doymcc/stitchEm", "max_forks_repo_head_hexsha": "20693a55fa522d7a196b92635e7a82df9917c2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2019-06-04T11:27:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T23:49:49.000Z", "avg_line_length": 31.5454545455, "max_line_length": 120, "alphanum_fraction": 0.7648414986, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795402, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.44223341326718546}}
{"text": "// This is a personal academic project. Dear PVS-Studio, please check it.\n// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com\n\n#include <iostream>\n#include <cstdint>\n#include <cmath>\n#include <cassert>\n#include <bitset>\n#include <fstream>\n#include <regex>\n#include <boost/algorithm/string/replace.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/float128.hpp>\n#include \"kyiv.h\"\n#include \"asm_disasm.h\"\ntypedef uint64_t addr_t;\ntypedef uint64_t word_t;\ntypedef int64_t  signed_word_t;\ntypedef uint32_t opcode_t;\ntypedef boost::multiprecision::int128_t mul_word_t;\n\n\nconstexpr addr3_t word_to_addr3(word_t w){\n    constexpr word_t Addr_1_mask_shift = (40-6-11)+1;\n    constexpr word_t Addr_1_mask = 0b11'111'111'111ULL << (Addr_1_mask_shift);  // also was -1\n    constexpr word_t Addr_2_mask_shift = (40-6-12-11)+1;\n    constexpr word_t Addr_2_mask = 0b11'111'111'111ULL << (Addr_2_mask_shift);  // also was -1\n    constexpr word_t Addr_3_mask_shift = 0; // Для одноманітності\n    constexpr word_t Addr_3_mask = 0b11'111'111'111ULL;\n\n    addr3_t res;\n    res.source_1    = (w & Addr_1_mask) >> Addr_1_mask_shift;\n    res.source_2    = (w & Addr_2_mask) >> Addr_2_mask_shift;\n    res.destination = (w & Addr_3_mask);\n    return res;\n}\n\nconstexpr opcode_t word_to_opcode(word_t w) {\n    constexpr word_t op_code_shift = (40-5)+1;\n    constexpr word_t op_code_mask = 0b11'111ULL << (op_code_shift);\n    opcode_t opcode = (w & op_code_mask) >> op_code_shift;\n    return opcode;\n}\n\nstatic constexpr word_t mask_40_bits = (1ULL << 40) - 1; // 0b111...11 -- 40 1-bits, std::pow(2, 41) === 1 << 41\nstatic constexpr word_t mask_41_bit = (1ULL << 40);      // 0b1000...00 -- 40 zeros after the 1\n\n\nconstexpr bool is_negative(word_t w){\n    return w & mask_41_bit; // 0 - додатнє, не нуль -- від'ємне\n}\n\nconstexpr word_t to_negative(word_t w){\n    return w | mask_41_bit;\n}\n\nconstexpr word_t to_positive(word_t w){\n    return w & (~mask_41_bit);\n}\n\nconstexpr uint16_t leftmost_one(word_t w){\n    uint16_t ct = 0;\n    while (w > 1) {\n        ct++;\n        w = w >> 1;\n    }\n    return ct;\n}\n\n//hz looks like kostyl but whatever\nuint16_t leftmost_one(mul_word_t w){\n    uint16_t ct = 0;\n    while (w > 1) {\n        ct++;\n        w = w >> 1;\n    }\n    return ct;\n}\n\nsigned_word_t get_absolute(word_t w){\n    return static_cast<signed_word_t>(w & mask_40_bits);\n}\n\nsigned_word_t word_to_number(word_t w){\n    signed_word_t sign1 = (is_negative(w) ? -1 : 1);\n    signed_word_t abs_val1 = get_absolute(w);\n    return sign1 * abs_val1;\n}\n\nconstexpr bool get_A1(word_t w){\n    constexpr word_t A_1_mask = 1ULL << (40-5);\n    return w & A_1_mask;\n}\n\nconstexpr bool get_A2(word_t w){\n    constexpr word_t A_2_mask = 1ULL << (40-5-12);\n    return w & A_2_mask;\n}\n\nconstexpr bool get_A3(word_t w){\n    constexpr uint64_t A_3_mask = 1ULL << (40-5-24);\n    return w & A_3_mask;\n}\n\nconstexpr addr3_t shift_addr3_byA(addr3_t addr3, uint64_t offset, word_t w){\n    if(get_A1(w))\n        addr3.source_1 += offset;\n    if(get_A2(w))\n        addr3.source_2 += offset;\n    if(get_A3(w))\n        addr3.destination += offset;\n    return  addr3;\n}\n\n\n//! Returns: True -- continue, false -- ситуація останову.\nbool Kyiv_t::execute_opcode(){\n    K_reg = kmem.read_memory(C_reg);\n    std::cout << K_reg << std::endl;\n    opcode_t opcode = word_to_opcode(K_reg);\n\n    if (opcode == 0) {\n        ++C_reg;\n\n    }\n//    std::cout << \"opcode: \" << opcode << std::endl;\n    addr3_t addr3 = word_to_addr3(K_reg); // Парі команд потрібна\n    std::cout << \"A_reg_2: \" << A_reg << std::endl;\n    std::cout << \"Cycle_reg\" << Loop_reg << std::endl;\n    addr3_t addr3_shifted = shift_addr3_byA(addr3, A_reg, K_reg); // Решта використовують цю змінну\n\n    std::cout << \"source 1: \" << addr3_shifted.source_1 << std::endl;\n    std::cout << \"source 2: \" << addr3_shifted.source_2 << std::endl;\n\n    disassembly(K_reg, kmem, addr3_shifted);\n    //! Ймовірно, потім це діло треба буде відрефакторити -- відчуваю, но де буде проблема - поки не знаю :+)\n    switch(opcode){\n\n        //TODO: Тестував лише opcode_add !!! -- решта вважайте невірними, поки не буде тестів. opcode_div\n        case arythm_operations_t::opcode_div: [[fallthrough]];\n        case arythm_operations_t::opcode_norm: [[fallthrough]];\n        case arythm_operations_t::opcode_add: [[fallthrough]];\n        case arythm_operations_t::opcode_sub: [[fallthrough]];\n        case arythm_operations_t::opcode_addcmd: [[fallthrough]];\n        case arythm_operations_t::opcode_subabs: [[fallthrough]];\n        case arythm_operations_t::opcode_mul: [[fallthrough]];\n        case arythm_operations_t::opcode_addcyc: [[fallthrough]];\n        case arythm_operations_t::opcode_mul_round:\n            opcode_arythm(addr3_shifted, opcode);\n            break;\n            //==========================================================================================================\n        case flow_control_operations_t::opcode_jmp_less_or_equal: [[fallthrough]];\n        case flow_control_operations_t::opcode_jmp_abs_less_or_equal: [[fallthrough]];\n        case flow_control_operations_t::opcode_jmp_equal: [[fallthrough]];\n        case flow_control_operations_t::opcode_fork_negative: [[fallthrough]];\n        case flow_control_operations_t::opcode_call_negative: [[fallthrough]];\n        case flow_control_operations_t::opcode_ret: [[fallthrough]];\n        case flow_control_operations_t::opcode_group_op_begin: [[fallthrough]];\n        case flow_control_operations_t::opcode_group_op_end: [[fallthrough]];\n        case flow_control_operations_t::opcode_F: [[fallthrough]];\n        case flow_control_operations_t::opcode_stop:\n            opcode_flow_control(addr3_shifted, opcode, addr3);\n            break;\n//==========================================================================================================\n        case logic_operations_t::opcode_log_shift:{\n            //! TODO: Мені не повністю зрозуміло з обох книг, величина зсуву береться із RAM за адресою,\n            //! чи закодована в команді? Швидше перше -- але перевірити!\n            word_t shift = kmem.read_memory(addr3_shifted.source_1) ; // Глушко-Ющенко, стор 12, сверджує: \"на число разрядов,\n            // равное абсолютной величине константы сдвига, размещаемой в шести младших разрядах ячейки а1\"\n            // 2^6 -- 64, тому решта бітів справді просто дадуть нуль на виході, але все рівно маскую, щоб\n            // не було невизначеної поведінки С. Та й зразу знак викидаємо\n            std::cout << \"shift: \" << shift << std::endl;\n            shift &= 0b111'111;\n            std::cout << \"shift after some and: \" << shift << std::endl;\n            if(is_negative(kmem.read_memory(addr3_shifted.source_1))) {\n                kmem.write_memory(addr3_shifted.destination, kmem.read_memory(addr3_shifted.source_2) >> shift);\n            } else {\n                kmem.write_memory(addr3_shifted.destination , kmem.read_memory(addr3_shifted.source_2) << shift);\n                kmem.write_memory(addr3_shifted.destination,  kmem.read_memory(addr3_shifted.destination) & (mask_40_bits | mask_41_bit)); // Зануляємо зайві біти\n            }\n            ++C_reg;\n        }\n            break;\n        case logic_operations_t::opcode_log_or:{\n            kmem.write_memory(addr3_shifted.destination, kmem.read_memory(addr3_shifted.source_1) | kmem.read_memory(addr3_shifted.source_2));\n            ++C_reg;\n            std::cout << \"orr\" << kmem.read_memory(addr3_shifted.destination) << std::endl;\n        }\n            break;\n        case logic_operations_t::opcode_log_and:{\n\n            kmem.write_memory(addr3_shifted.destination, kmem.read_memory(addr3_shifted.source_1) & kmem.read_memory(addr3_shifted.source_2));\n\n            ++C_reg;\n        }\n            break;\n        case logic_operations_t::opcode_log_xor:{\n            kmem.write_memory(addr3_shifted.destination, kmem.read_memory(addr3_shifted.source_1) ^ kmem.read_memory(addr3_shifted.source_2));\n            ++C_reg;\n        }\n            break;\n//==========================================================================================================\n        case IO_operations_t::opcode_read_perfo_data:{\n                std::ifstream punch_cards;\n                std::string line;\n                std::string perfo;\n                std::vector<std::string> argv;\n                signed_word_t number;\n\n                punch_cards.open(\"../../mem/punch_cards_in.txt\");\n\n                int counter = 0;\n                int num_counter = 0;\n                bool flag;\n\n                while (punch_cards) {\n                    std::getline(punch_cards, line);\n                    if (counter == perfo_num) {\n                        perfo = line.substr(addr3_shifted.destination, line.size());\n                        boost::split(argv, perfo, boost::is_any_of(\" \"), boost::algorithm::token_compress_off);\n                        for(auto num : argv){\n                            if(num_counter == addr3_shifted.source_2 - addr3_shifted.source_1){\n                                flag = true;\n                                break;\n                            }\n                            number = std::stol(num);\n                            if(number >= 0){\n                                kmem.write_memory(addr3_shifted.source_1 + num_counter, number);\n                            }else{\n                                kmem.write_memory(addr3_shifted.source_1 + num_counter, to_negative(std::abs(number)));\n                            }\n                            num_counter++;\n                        }\n                    }else if(counter > num_counter){\n                        perfo = line;\n                        boost::split(argv, perfo, boost::is_any_of(\" \"), boost::algorithm::token_compress_off);\n                        for(auto num : argv){\n                            if(num_counter == addr3_shifted.source_2 - addr3_shifted.source_1){\n                                flag = true;\n                                break;\n                            }\n                            number = std::stoi(num);\n                            if (number >= 0) {\n                                kmem.write_memory(addr3_shifted.source_1 + num_counter, number);\n                            } else {\n                                kmem.write_memory(addr3_shifted.source_1 + num_counter, to_negative(std::abs(number)));\n                            }\n                            num_counter ++;\n                        }\n                    }\n                    if(flag == true){\n                        break;\n                    }\n                    counter++;\n                }\n                punch_cards.close();\n        }\n            break;\n\n        case IO_operations_t::opcode_read_perfo_binary:{\n            std::ifstream punch_cards;\n            std::ifstream heads;\n            std::string head;\n            std::string line;\n\n            punch_cards.open(\"../punched_tape.txt\");\n            heads.open(\"../heads.txt\");\n\n            std::getline(heads, head);\n            std::getline(heads, head);\n            // int num = std::stoi(head);\n            size_t num = h;\n            int counter = 0;\n            int com_counter = 0;\n            bool flag = false;\n\n            while(punch_cards){\n                std::getline(punch_cards, line);\n                int pos = 0;\n                if(counter == num){\n                    if(com_counter < addr3_shifted.source_2 - addr3_shifted.source_1){\n                        kmem.write_memory(addr3_shifted.source_1 + com_counter, std::stol(line, 0, 8));\n                        com_counter++;\n                    }else{\n                        flag = true;\n                        break;\n                    }\n                }else if(counter > num){\n                    if(com_counter < addr3_shifted.source_2 - addr3_shifted.source_1){\n                        kmem.write_memory(addr3_shifted.source_1 + com_counter, std::stol(line, 0, 8));\n                        com_counter ++;\n                    }else{\n                        flag = true;\n                        break;\n                    }\n\n                }\n                if(flag){\n                    break;\n                }\n            }\n            h += com_counter;\n        }\n            break;\n\n        case IO_operations_t::opcode_read_magnetic_drum:{\n            std::ifstream magnetic_drum;\n            std::string line;\n            std::string data;\n            std::vector<std::string> argv;\n            signed_word_t number;\n\n            magnetic_drum.open(\"../../mem/drum_in.txt\");\n\n            int counter = 0;\n            int num_counter = 0;\n            bool flag;\n            while (magnetic_drum) {\n                std::getline(magnetic_drum, line);\n                if(counter == drum_num_read){\n                    data = line.substr(drum_zone_read, line.size());\n                    boost::split(argv, data, boost::is_any_of(\" \"), boost::algorithm::token_compress_off);\n                    for(const auto& num : argv){\n                        if(num_counter == addr3_shifted.source_2 - addr3_shifted.source_1){\n                            flag = true;\n                            break;\n                        }\n                        number = std::stoi(num);\n                        if(number >= 0){\n                            kmem.write_memory(addr3_shifted.source_1 + num_counter, number);\n                        }else{\n                            kmem.write_memory(addr3_shifted.source_1 + num_counter, to_negative(std::abs(number)));\n                        }\n                        num_counter ++;\n                    }\n                }else if(counter > drum_num_read){\n                    data = line;\n                    boost::split(argv, data, boost::is_any_of(\" \"), boost::algorithm::token_compress_off);\n                    for(const auto& num : argv){\n                        if(num_counter == addr3_shifted.source_2 - addr3_shifted.source_1){\n                            flag = true;\n                            break;\n                        }\n                        number = std::stoi(num);\n                        if(number >= 0){\n                            kmem.write_memory(addr3_shifted.source_1 + num_counter, number);\n                        }else{\n                            kmem.write_memory(addr3_shifted.source_1 + num_counter, to_negative(std::abs(number)));\n                        }\n                        num_counter ++;\n                    }\n                }\n                if(flag){\n                    break;\n                }\n                counter ++;\n            }\n\n            magnetic_drum.close();\n        }\n            break;\n\n        case IO_operations_t::opcode_write_perfo_binary:{\n            std::ofstream myfile;\n            myfile.open(\"../punc_cards_out.txt\");\n            if (myfile.is_open())\n            {\n                for(uint64_t i = 0; i <= addr3_shifted.source_2; i++){\n                    myfile << word_to_number(kmem.read_memory(addr3_shifted.source_1 + i));\n                    myfile << ' ';\n                }\n                myfile.close();\n            }else {\n                std::cout << \"Unable to open file\";\n            }\n            C_reg = addr3_shifted.destination;\n            K_reg = kmem.read_memory(C_reg);\n        }\n\n\n        case IO_operations_t::opcode_write_magnetic_drum:{\n            std::ofstream myfile;\n            myfile.open(\"../magnetic_drum.txt\");\n            if (myfile.is_open())\n            {\n                for(uint64_t i = 0; i <= addr3_shifted.source_2; i++){\n                    myfile << word_to_number(kmem.read_memory(addr3_shifted.source_1 + i));\n                    myfile << ' ';\n                }\n                myfile.close();\n            }else {\n                std::cout << \"Unable to open file\";\n            }\n            C_reg = addr3_shifted.destination;\n            K_reg = kmem.read_memory(C_reg);\n        }\n            break;\n\n        case IO_operations_t::opcode_init_magnetic_drum:{\n            if (addr3_shifted.source_1 == 0) {\n                drum_num_read = addr3_shifted.source_2;\n                drum_zone_read = addr3_shifted.destination;\n            } else if (addr3_shifted.source_1 == 1) {\n                drum_num_write = addr3_shifted.source_2;\n                drum_zone_write = addr3_shifted.destination;\n            }\n        }\n            break;\n//==========================================================================================================\n        default:\n            T_reg = true; // ! TODO: Не пам'ятаю, яка там точно реакція на невідому команду\n    }\n    return !T_reg;\n}\n\nvoid Kyiv_t::opcode_arythm(const addr3_t& addr3, opcode_t opcode){\n    //! TODO: Додати перевірку на можливість запису. Що робила машина при спробі запису в ПЗП?\n    //! TODO: Додати перевірку на вихід за границю пам'яті -- воно ніби зациклювалося при тому\n    //! (зверталося до байта add mod 2^11, в сенсі), але точно не знаю.\n    signed_word_t sign1 = (is_negative(kmem.read_memory(addr3.source_1)) ? -1 : 1);\n    signed_word_t sign2 = (is_negative(kmem.read_memory(addr3.source_2)) ? -1 : 1);\n    std::cout << \"sign 2\" << sign2 << std::endl;\n    std::cout << \"gfuigfalhf: \" << addr3.source_2 << std::endl;\n    word_t abs_val1 = static_cast<signed_word_t>(kmem.read_memory(addr3.source_1) & mask_40_bits);\n    word_t abs_val2 = static_cast<signed_word_t>(kmem.read_memory(addr3.source_2) & mask_40_bits);;\n    signed_word_t res = sign1 * (signed_word_t) abs_val1;\n\n    signed_word_t res_for_norm;\n    mul_word_t res_mul;\n    uint16_t power = 40 - leftmost_one(abs_val1) -1;\n\n    std::cout << sign1 * (signed_word_t) abs_val1 << \"gifhdaflvdjasbh\\t\" << sign2 * (signed_word_t) abs_val2 << std::endl;\n    switch(opcode){\n        case arythm_operations_t::opcode_add:\n            res += sign2 * (signed_word_t) abs_val2;\n            break;\n        case arythm_operations_t::opcode_sub:\n            res -= sign2 * (signed_word_t) abs_val2;\n            break;\n        case arythm_operations_t::opcode_addcmd:\n            res += (signed_word_t) abs_val2;\n            break;\n        case arythm_operations_t::opcode_subabs:\n            res = (signed_word_t) abs_val1 - (signed_word_t) abs_val2;\n            break;\n        case arythm_operations_t::opcode_addcyc:\n            res += sign2 * (signed_word_t) abs_val2; // Те ж, що і для opcode_add, але подальша обробка інша\n            break;\n        case arythm_operations_t::opcode_mul: [[fallthrough]];\n        case arythm_operations_t::opcode_mul_round:\n            res_mul = sign1 * (mul_word_t) abs_val1 * sign2 * (mul_word_t) abs_val2;\n            std::cout << \"H : \" << res_mul << std::endl;\n            break;\n        case arythm_operations_t::opcode_norm: {\n            res_for_norm = sign1 * (abs_val1 << power);\n        }\n            break;\n        case arythm_operations_t::opcode_div: {\n            if ((abs_val2 == 0) || (abs_val2 < abs_val1)) {\n                T_reg = true;\n                ++C_reg;\n                return;\n            }\n            res_mul = ((mul_word_t) abs_val1 << 40) / (mul_word_t) abs_val2;\n            // std::cout << \"Div \" << res_mul << std::endl;\n        }\n            break;\n\n        default:\n            assert(false && \"Should never been here!\");\n    }\n\n    if(opcode == arythm_operations_t::opcode_add ||\n       opcode == arythm_operations_t::opcode_sub ||\n       opcode == arythm_operations_t::opcode_subabs     //! TODO: Я не плутаю, результат може мати знак?\n            ) {\n        //! TODO: До речі, а якщо переповнення, воно кінцевий регістр змінювало до останову, чи ні?\n        // Тут я зробив, ніби ні -- але ХЗ, могло. Щоб точно знати -- треба моделювати на рівні схем ;=) --\n        // як ви і поривалися. Але це не має бути важливим.\n        bool is_negative = (res < 0);\n        if (is_negative)\n            res = -res;\n        assert(res >= 0);\n        if (res & mask_41_bit) { // if sum & CPU1.mask_41_bit == 1 -- overflow to sign bit\n            T_reg = true;\n            ++C_reg;\n            return;\n        }\n        kmem.write_memory(addr3.destination, static_cast<uint64_t>(res) & mask_40_bits);\n        // std::cout << -1 * res << std::endl;\n        if (is_negative)\n            kmem.write_memory(addr3.destination, kmem.read_memory(addr3.destination) | mask_41_bit);\n        //! \"Нуль, получаемый как разность двух равных чисел, имеет отрицательный знак\" -- стор. 13 Глушко-Ющенко, опис УПЧ\n        if(opcode == arythm_operations_t::opcode_sub && res == 0\n           && abs_val2 == 0 //! TODO: Моє припущення -- перевірити!\n                ){\n            kmem.write_memory(addr3.destination, res | mask_41_bit);\n            std::cout << \"NEGATIVE 0\" << (res | mask_41_bit) << std::endl;\n        }\n    } else if(opcode == arythm_operations_t::opcode_addcmd){\n        kmem.write_memory(addr3.destination, static_cast<uint64_t>(res) & mask_40_bits);\n        kmem.write_memory(addr3.destination, kmem.read_memory(addr3.destination) | (kmem.read_memory(addr3.source_2) & mask_41_bit)); // Копіюємо біт знаку з source_2 // edited тут наче так має бути\n    } else if(opcode == arythm_operations_t::opcode_addcyc){\n        //! TODO: Вияснити, а як ця команда функціонує.\n        // \"Отличается от обычного сложения лишь тем, что  в нем отсутствует блокировка при выходе\n        // из разполагаемого числа разрядов. Перенос из знакового разряда поступает в младший разряд\n        // сумматора\".\n        // Питання (нумеруючи біти з 1 до 41):\n        // 1. Перенос із 40 в 41 біт тут можливий? З фрази виглядає, що так.\n        // 2. Якщо додавання переносу до молодшого біту виникло переповнення, що далі?\n        //    Так виглядає, що воно не може виникнути, але чи я не помилився? -- не може, десь через переніс буде 0\n        bool is_negative = (res < 0);\n        // std::cout << (res) << std::endl;\n        if (is_negative)\n            res = -res;\n        assert(res >= 0);\n\n        // std::cout << std::bitset<41> (res) << std::endl;\n        if(res & mask_41_bit){\n            res += 1; // Маємо перенос із знакового біту\n        }\n\n        kmem.write_memory(addr3.destination, static_cast<uint64_t>(res) & mask_40_bits);\n        if (is_negative)\n            kmem.write_memory(addr3.destination, kmem.read_memory(addr3.destination) | mask_41_bit);\n    } else if(opcode == arythm_operations_t::opcode_mul ||\n              opcode == arythm_operations_t::opcode_mul_round\n            ) {\n        bool is_negative = (res_mul < 0);\n        //std::cout << res_mul << std::endl;\n        if (is_negative)\n            res_mul = -res_mul;\n        assert(res_mul >= 0);\n\n        uint16_t leftmost = leftmost_one(res_mul);\n\n        if (opcode == arythm_operations_t::opcode_mul_round) {\n            res_mul += 1ULL << 41;\n        }\n        res_mul = res_mul >> 40;\n\n        kmem.write_memory(addr3.destination, static_cast<uint64_t>(res_mul) & mask_40_bits);\n        std::cout << \"DEBUUUUUUUUG2 \" << static_cast<uint64_t>(res_mul) << std::endl;\n        // std::cout << is_negative << std::endl;\n        if (is_negative)\n            kmem.write_memory(addr3.destination, kmem.read_memory(addr3.destination) | mask_41_bit);\n        std::cout << \"DEBUUUUUUUUG \" << word_to_number(kmem.read_memory(addr3.destination)) << std::endl;\n//        std::cout << std::bitset<41>(kmem[addr3.destination]) << std::endl;\n//        std::cout << \"Mult res: \" << word_to_number(kmem[addr3.destination]) << std::endl;\n\n    } else if (opcode == arythm_operations_t::opcode_norm) {\n        bool is_negative = (res_for_norm < 0);\n\n        if (is_negative)\n            res_for_norm = -res_for_norm;\n        assert(res_for_norm >= 0);\n//\n//        std::cout << \"norm_val: \" << (res_for_norm) << std::endl;\n//        std::cout << \"norm_power: \" << (power) << std::endl;\n//        std::cout << \"norm_val_64: \" << std::bitset<64>(res_for_norm) << std::endl;\n//        std::cout << \"norm_val_41: \" << std::bitset<41>(res_for_norm) << std::endl;\n\n        kmem.write_memory(addr3.source_2, power);\n        kmem.write_memory(addr3.destination, static_cast<uint64_t>(res_for_norm) & mask_40_bits);\n        if (is_negative)\n            kmem.write_memory(addr3.destination, kmem.read_memory(addr3.destination) | mask_41_bit);\n//\n//        std::cout << \"norm_val_mem: \" << kmem[addr3.destination] << std::endl;\n//        std::cout << \"norm_val_pow: \" << kmem[addr3.source_2] << std::endl;\n    } else if (opcode == arythm_operations_t::opcode_div) {\n        kmem.write_memory(addr3.destination, static_cast<uint64_t>(res_mul) & mask_40_bits);\n        if ((sign1 * sign2) == -1)\n            kmem.write_memory(addr3.destination, kmem.read_memory(addr3.destination) | mask_41_bit);\n//        std::cout << \"Div res: \" << word_to_number(kmem[addr3.destination]) << std::endl;\n    }\n    ++C_reg;\n}\n\n\nvoid Kyiv_t::opcode_flow_control(const addr3_t& addr3_shifted, opcode_t opcode, const addr3_t &addr3){\n    signed_word_t sign1 = (is_negative(kmem.read_memory(addr3_shifted.source_1)) ? -1 : 1);\n    signed_word_t sign2 = (is_negative(kmem.read_memory(addr3_shifted.source_2)) ? -1 : 1);\n    signed_word_t abs_val1 = static_cast<signed_word_t>(kmem.read_memory(addr3_shifted.source_1) & mask_40_bits);\n    signed_word_t abs_val2 = static_cast<signed_word_t>(kmem.read_memory(addr3_shifted.source_2) & mask_40_bits);;\n\n    switch (opcode) {\n        case flow_control_operations_t::opcode_jmp_less_or_equal: {\n            if((sign1 * abs_val1) <= (sign2 * abs_val2)){\n                C_reg = addr3_shifted.destination;\n            } else {\n                ++C_reg;\n            }\n        }\n            break;\n        case flow_control_operations_t::opcode_jmp_abs_less_or_equal: {\n//            std::cout << \"Num1 \" << get_absolute(kmem[addr3_shifted.source_1]) << std::endl;\n//            std::cout << \"Num2 \" << get_absolute(kmem[addr3_shifted.source_2]) << std::endl;\n            if (abs_val1 <= abs_val2) {\n                C_reg = addr3_shifted.destination;\n            } else {\n                ++C_reg;\n            }\n        }\n            break;\n        case flow_control_operations_t::opcode_jmp_equal: {\n            if( (sign1 * abs_val1) == (sign2 * abs_val2)){\n                C_reg = addr3_shifted.destination;\n            } else {\n                ++C_reg;\n            }\n        }\n            break;\n        case flow_control_operations_t::opcode_fork_negative: {\n            if( is_negative(kmem.read_memory(addr3_shifted.source_1)) ){\n                C_reg = addr3_shifted.destination;\n            }else{\n                C_reg = addr3_shifted.source_2;\n            }\n        }\n            break;\n        case flow_control_operations_t::opcode_call_negative:{\n            if( is_negative(kmem.read_memory(addr3_shifted.source_1)) ){\n                P_reg = addr3_shifted.source_2; //! TODO: Згідно тексту стор 342 (пункт 18) Гнеденко-Королюк-Ющенко-1961\n                //! Глушков-Ющенко, стор 13, УПП не до кінця однозначна -- a1 без штриха, це зрозуміло,\n                //! але з врахуванням A і біта модифікатора, чи без?\n                //! Виглядає, що в таблиці на стор 180 -- помилка ('A2 => P -- зайвий штрих точно помилка,\n                //! чи помилка, що, немає зсуву на А?).\n                //! Однак, в  Гнеденко-Королюк-Ющенко-1961 опкод (32) суперечить опкоду в Глушко-Ющенко.\n                //! Перевірити!\n                C_reg = addr3_shifted.destination;\n            }else{\n                ++C_reg; //! Тут P_reg не мала б змінювати\n            }\n        }\n            break;\n        case flow_control_operations_t::opcode_ret:{\n            C_reg = P_reg;\n        }\n            break;\n        case flow_control_operations_t::opcode_group_op_begin:{\n            // У книжці Глушков-Ющенко на ст. 14, ймовірно, помилка, бо навіть словами пояснено,\n            // що береться значення а1 і а2, але разом із тим наголошено, що береться не 'а1 чи 'а2,\n            // а саме а1 і а2. В кінці цієї книжки та у Гнеденко-Королюк-Ющенко пише,\n            // ніби беруться значення, тому тут реалізовано саме так.\n            Loop_reg =  addr3_shifted.source_1; //word_to_number(kmem.read_memory(addr3_shifted.source_1));\n            A_reg = addr3_shifted.source_2; // word_to_number(kmem.read_memory(addr3_shifted.source_2));\n            if (A_reg == Loop_reg) {\n                C_reg = addr3_shifted.destination;\n            } else {\n                ++C_reg;\n            }\n\n            std::cout << \"A_reg: \" << A_reg << std::endl;\n        }\n            break;\n        case flow_control_operations_t::opcode_group_op_end:{\n            // Такий самий прикол, як з НГО\n            // not a value\n            A_reg += addr3.source_1;// word_to_number(kmem.read_memory(addr3_shifted.source_1));\n            if (A_reg == Loop_reg) {\n                C_reg = word_to_number(addr3_shifted.destination);\n            } else {\n                C_reg = (addr3_shifted.source_2);\n            }\n        }\n            break;\n        case flow_control_operations_t::opcode_F:{\n            // Якщо я правильно розібралася з 2 попередними командами, то тут все зрозуміло і немає суперечностей\n            A_reg = word_to_addr3(kmem.read_memory(addr3_shifted.source_1)).source_2;\n            word_t res = kmem.read_memory(A_reg);\n            kmem.write_memory(addr3_shifted.destination, res);\n            ++C_reg;\n        }\n            break;\n        case flow_control_operations_t::opcode_stop:{ //! TODO: Вона враховує стан кнопки на пульті?\n            // From Glushkov-Iushchenko p. 55\n            // If B_tumb == 0 -> neutral mode -> full stop\n            // If B_tumb > 0 -> just skip one command without full stop\n            // From Glushkov-Iushchenko pp. 163-164\n            // If B_tumb == 1 -> stop by 3d address\n            // If B_tumb == 2 -> stop by command number\n            // I'm not sure what to do with 1st and 2nd B_tumb (maybe that should be handled in main???)\n            if (!B_tumb) {\n                T_reg = true;\n                ++C_reg;\n            }\n            else {\n                C_reg += 2;\n            }\n        }\n            break;\n    }\n}\n", "meta": {"hexsha": "a360e2e40f111165775b0efb18db12a99fb075de", "size": 30170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "oliuba/Kyiv_emulator", "max_stars_repo_head_hexsha": "7c82f9eb22d0eee95e3de6f90f7bc89ce5995234", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-11-01T16:59:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T10:55:48.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "oliuba/Kyiv_emulator", "max_issues_repo_head_hexsha": "7c82f9eb22d0eee95e3de6f90f7bc89ce5995234", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "oliuba/Kyiv_emulator", "max_forks_repo_head_hexsha": "7c82f9eb22d0eee95e3de6f90f7bc89ce5995234", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4100719424, "max_line_length": 198, "alphanum_fraction": 0.556546238, "num_tokens": 8090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4422334080790111}}
{"text": "/*\n * symb_reg_basic_eval.cpp\n * Date: 2013-01-28\n * Author: Karsten Ahnert (karsten.ahnert@gmx.de)\n */\n\n#define FUSION_MAX_VECTOR_SIZE 20\n\n#include <gpcxx/tree.hpp>\n#include <gpcxx/generate.hpp>\n#include <gpcxx/operator.hpp>\n#include <gpcxx/eval.hpp>\n#include <gpcxx/evolve.hpp>\n#include <gpcxx/io.hpp>\n#include <gpcxx/stat.hpp>\n#include <gpcxx/app.hpp>\n\n#include <boost/fusion/include/make_vector.hpp>\n\n#include <iostream>\n#include <random>\n#include <vector>\n#include <functional>\n\nconst std::string tab = \"\\t\";\n\n\nnamespace pl = std::placeholders;\nnamespace fusion = boost::fusion;\n\nint main( int argc , char *argv[] )\n{\n    typedef std::mt19937 rng_type ;\n\n    typedef gpcxx::basic_tree< char > tree_type;\n    typedef gpcxx::regression_context< double , 3 > context_type;\n\n    auto eval = gpcxx::make_static_eval< double , char , context_type >(\n        fusion::make_vector(\n            fusion::make_vector( '1' , []( context_type const& t ) { return 1.0; } )\n          , fusion::make_vector( '2' , []( context_type const& t ) { return 2.0; } )\n          , fusion::make_vector( '3' , []( context_type const& t ) { return 3.0; } )\n          , fusion::make_vector( '4' , []( context_type const& t ) { return 4.0; } )\n          , fusion::make_vector( '5' , []( context_type const& t ) { return 5.0; } )\n          , fusion::make_vector( '6' , []( context_type const& t ) { return 6.0; } )\n          , fusion::make_vector( '7' , []( context_type const& t ) { return 7.0; } )\n          , fusion::make_vector( '8' , []( context_type const& t ) { return 8.0; } )\n          , fusion::make_vector( '9' , []( context_type const& t ) { return 9.0; } )\n          , fusion::make_vector( 'x' , []( context_type const& t ) { return t[0]; } )\n          , fusion::make_vector( 'y' , []( context_type const& t ) { return t[1]; } )\n          , fusion::make_vector( 'z' , []( context_type const& t ) { return t[2]; } )          \n          ) ,\n        fusion::make_vector(\n            fusion::make_vector( 's' , []( double v ) -> double { return std::sin( v ); } )\n          , fusion::make_vector( 'c' , []( double v ) -> double { return std::cos( v ); } ) \n          ) ,\n        fusion::make_vector(\n            fusion::make_vector( '+' , std::plus< double >() )\n          , fusion::make_vector( '-' , std::minus< double >() )\n          , fusion::make_vector( '*' , std::multiplies< double >() ) \n          , fusion::make_vector( '/' , std::divides< double >() ) \n          ) );\n    typedef decltype( eval ) eval_type;\n    \n   \n    size_t population_size = 812;\n    size_t number_elite = 1;\n    double mutation_rate = 0.2;\n    double crossover_rate = 0.6;\n    double reproduction_rate = 0.3;\n    size_t min_tree_height = 4 , max_tree_height = 12;\n    size_t tournament_size = 15;\n    \n    rng_type rng;\n    auto node_generator = eval.get_node_generator< rng_type >();\n    node_generator.set_weight( 0 , 1.0 );\n    node_generator.set_weight( 1 , 1.0 );\n    node_generator.set_weight( 2 , 1.0 );\n    auto tree_generator = gpcxx::make_ramp( rng , node_generator , min_tree_height , max_tree_height , 0.5 );\n\n    typedef std::vector< tree_type > population_type;\n    typedef std::vector< double > fitness_type;\n    typedef gpcxx::static_pipeline< population_type , fitness_type , rng_type > evolver_type;\n\n    evolver_type evolver( number_elite , mutation_rate , crossover_rate , reproduction_rate , rng );\n\n\n    auto fitness_f = gpcxx::regression_fitness< eval_type >( eval );\n    evolver.mutation_function() = gpcxx::make_mutation(\n        gpcxx::make_point_mutation( rng , tree_generator , max_tree_height , 20 ) ,\n        gpcxx::make_tournament_selector( rng , tournament_size ) );\n    evolver.crossover_function() = gpcxx::make_crossover( \n        gpcxx::make_one_point_crossover_strategy( rng , 10 ) ,\n        gpcxx::make_tournament_selector( rng , tournament_size ) );\n    evolver.reproduction_function() = gpcxx::make_reproduce( gpcxx::make_tournament_selector( rng , tournament_size ) );\n    \n    auto c = gpcxx::generate_normal_distributed_test_data< 3 >( rng , 1024 , 0.0 , 1.0 , []( double x1 , double x2 , double x3 )\n            { return  x1 * x1 * x1 + 1.0 / 10.0 * x2 * x2 - 3.0 / 4.0 * x3 + 1.0 ; } );\n\n\n    std::vector< double > fitness( population_size , 0.0 );\n    std::vector< tree_type > population( population_size );\n\n\n    // initialize population with random trees and evaluate fitness\n    for( size_t i=0 ; i<population.size() ; ++i )\n    {\n        tree_generator( population[i] );\n        fitness[i] = fitness_f( population[i] , c );\n    }\n    \n    std::cout << \"Best individuals\" << std::endl << gpcxx::best_individuals( population , fitness ) << std::endl;\n    std::cout << \"Statistics : \" << gpcxx::calc_population_statistics( population ) << std::endl;\n    std::cout << std::endl << std::endl;\n\n    for( size_t i=0 ; i<10 ; ++i )\n    {\n        evolver.next_generation( population , fitness );\n        for( size_t i=0 ; i<population.size() ; ++i )\n            fitness[i] = fitness_f( population[i] , c );\n        \n        std::cout << \"Iteration \" << i << std::endl;\n        std::cout << \"Best individuals\" << std::endl << gpcxx::best_individuals( population , fitness , 1 ) << std::endl;\n        std::cout << \"Statistics : \" << gpcxx::calc_population_statistics( population ) << std::endl << std::endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "a92190b090df8385f792f3465a7b08b07049873f", "size": 5335, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/symbolic_regression/symb_reg_basic_tree.cpp", "max_stars_repo_name": "gchoinka/gpcxx", "max_stars_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T08:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T07:28:54.000Z", "max_issues_repo_path": "examples/symbolic_regression/symb_reg_basic_tree.cpp", "max_issues_repo_name": "gchoinka/gpcxx", "max_issues_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-26T23:48:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-29T14:16:37.000Z", "max_forks_repo_path": "examples/symbolic_regression/symb_reg_basic_tree.cpp", "max_forks_repo_name": "gchoinka/gpcxx", "max_forks_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T21:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T05:14:08.000Z", "avg_line_length": 41.3565891473, "max_line_length": 128, "alphanum_fraction": 0.6099343955, "num_tokens": 1515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.803173791645582, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.44223340548492396}}
{"text": "/*\n * system_propagator.hpp\n *\n * Created on: Mar 21, 2018 15:15\n * Description: a convenience wrapper to propogate system model\n *            with given control input\n * Note: this propagator doesn't consider any additional constraints\n *            to system states, see comments below\n *\n * Copyright (c) 2018 Ruixiang Du (rdu)\n */\n\n#ifndef SYSTEM_PROPAGATOR_HPP\n#define SYSTEM_PROPAGATOR_HPP\n\n#include <cstdint>\n#include <vector>\n\n#include <boost/numeric/odeint.hpp>\n\nnamespace robosw {\ntemplate <typename Model, typename Input>\nclass SystemPropagator {\n public:\n  typename Model::state_type Propagate(typename Model::state_type init_state,\n                                       Input u, double t0, double tf,\n                                       double dt) {\n    typename Model::state_type x = init_state;\n    boost::numeric::odeint::integrate_const(\n        boost::numeric::odeint::runge_kutta4<typename Model::state_type>(),\n        Model(u), x, t0, tf, dt);\n    return x;\n  }\n};\n}  // namespace robosw\n\n#endif /* SYSTEM_PROPAGATOR_HPP */\n", "meta": {"hexsha": "69ac94208d0d6ae516d44f3c96994ab557f84b08", "size": 1049, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/control/model/include/model/system_propagator.hpp", "max_stars_repo_name": "rxdu/libnav", "max_stars_repo_head_hexsha": "d62c5d7d012cf891b4f1567087bdb1c8e2bfd625", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/control/model/include/model/system_propagator.hpp", "max_issues_repo_name": "rxdu/libnav", "max_issues_repo_head_hexsha": "d62c5d7d012cf891b4f1567087bdb1c8e2bfd625", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-03-13T07:28:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T07:43:16.000Z", "max_forks_repo_path": "src/control/model/include/model/system_propagator.hpp", "max_forks_repo_name": "rxdu/libnav", "max_forks_repo_head_hexsha": "d62c5d7d012cf891b4f1567087bdb1c8e2bfd625", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6052631579, "max_line_length": 77, "alphanum_fraction": 0.6568160153, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4422334028908367}}
{"text": "#include <iostream>\n#include <string>\n#include <boost/algorithm/string.hpp>\n\nconst std::string input = R\"(cpy 1 a\ncpy 1 b\ncpy 26 d\njnz c 2\njnz 1 5\ncpy 7 c\ninc d\ndec c\njnz c -2\ncpy a c\ninc a\ndec b\njnz b -2\ncpy c b\ndec d\njnz d -6\ncpy 14 c\ncpy 14 d\ninc a\ndec d\njnz d -2\ndec c\njnz c -5)\";\n\nint64_t run(const std::initializer_list<int64_t> &init_vals)\n{\n    std::vector<std::string> lines;\n    boost::split(lines, input, boost::is_any_of(\"\\n\"));\n\n    std::vector<int64_t> registers(init_vals);\n\n    size_t pc = 0;\n\n    while (pc < lines.size())\n    {\n        //std::cout << pc << \": \" << registers[0] << \", \" << registers[1] << \", \"\n        //    << registers[2] << \", \" << registers[3] << \": \" << lines[pc] << std::endl;\n\n        const std::string &line = lines[pc];\n\n        if (line.substr(0, 4) == \"cpy \")\n        {\n            int64_t copy_val = 0;\n            size_t space_pos = line.find(' ', 4);\n\n            if ((line[4] >= 'a') && (line[4] <= 'd'))\n                copy_val = registers[line[4] - 'a'];\n            else\n                copy_val = atoi(line.substr(4, space_pos - 4).c_str());\n\n            registers[line.back() - 'a'] = copy_val;\n            pc += 1;\n        }\n        else if (line.substr(0, 4) == \"inc \")\n        {\n            registers[line.back() - 'a'] += 1;\n            pc += 1;\n        }\n        else if (line.substr(0, 4) == \"dec \")\n        {\n            registers[line.back() - 'a'] -= 1;\n            pc += 1;\n        }\n        else if (line.substr(0, 4) == \"jnz \")\n        {\n            int64_t test_val = 0;\n            size_t space_pos = line.find(' ', 4);\n\n            if ((line[4] >= 'a') && (line[4] <= 'd'))\n                test_val = registers[line[4] - 'a'];\n            else\n                test_val = atoi(line.substr(4, space_pos - 4).c_str());\n\n            if (test_val != 0)\n            {\n                pc += atoi(line.substr(space_pos + 1).c_str());\n            }\n            else\n            {\n                pc += 1;\n            }\n        }\n    }\n\n    return registers[0];\n}\n\nint main(int argc, char *argv[])\n{\n    int64_t answer1 = run({ 0, 0, 0, 0 });\n    int64_t answer2 = run({ 0, 0, 1, 0 });\n\n    std::cout << \"Answer #1: \" << answer1 << std::endl;\n    std::cout << \"Answer #2: \" << answer2 << std::endl;\n}\n", "meta": {"hexsha": "27994472d9430f4c3ce6cca78ec544f968fab0bf", "size": 2261, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2016/12.cpp", "max_stars_repo_name": "kezenator/adventofcode", "max_stars_repo_head_hexsha": "8c4965df1bb46e174e8388a2b36dd9c9b6cd6f15", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2016/12.cpp", "max_issues_repo_name": "kezenator/adventofcode", "max_issues_repo_head_hexsha": "8c4965df1bb46e174e8388a2b36dd9c9b6cd6f15", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2016/12.cpp", "max_forks_repo_name": "kezenator/adventofcode", "max_forks_repo_head_hexsha": "8c4965df1bb46e174e8388a2b36dd9c9b6cd6f15", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.61, "max_line_length": 88, "alphanum_fraction": 0.4506855374, "num_tokens": 706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.44221166009268853}}
{"text": "/* Author: Wolfgang Bangerth, Texas A&M University, 2006 */\n\n/*    $Id: step-23.cc 27657 2012-11-21 13:19:08Z bangerth $       */\n/*    Version: $Name:  $                                          */\n/*                                                                */\n/*    Copyright (C) 2006-2009, 2011-2012 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n\n// @sect3{Include files}\n\n// We start with the usual assortment of include files that we've seen in so\n// many of the previous tests:\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/constraint_matrix.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/numerics/data_out.h>\n\n#include <fstream>\n#include <iostream>\n\n// Here are the only three include files of some new interest: The first one\n// is already used, for example, for the\n// VectorTools::interpolate_boundary_values and\n// VectorTools::apply_boundary_values functions. However, we here use another\n// function in that class, VectorTools::project to compute our initial values\n// as the $L^2$ projection of the continuous initial values. Furthermore, we\n// use VectorTools::create_right_hand_side to generate the integrals\n// $(f^n,\\phi^n_i)$. These were previously always generated by hand in\n// <code>assemble_system</code> or similar functions in application\n// code. However, we're too lazy to do that here, so simply use a library\n// function:\n#include <deal.II/numerics/vector_tools.h>\n\n// In a very similar vein, we are also too lazy to write the code to assemble\n// mass and Laplace matrices, although it would have only taken copying the\n// relevant code from any number of previous tutorial programs. Rather, we\n// want to focus on the things that are truly new to this program and\n// therefore use the MatrixTools::create_mass_matrix and\n// MatrixTools::create_laplace_matrix functions. They are declared here:\n#include <deal.II/numerics/matrix_tools.h>\n\n// Finally, here is an include file that contains all sorts of tool functions\n// that one sometimes needs. In particular, we need the\n// Utilities::int_to_string class that, given an integer argument, returns a\n// string representation of it. It is particularly useful since it allows for\n// a second parameter indicating the number of digits to which we want the\n// result padded with leading zeros. We will use this to write output files\n// that have the form <code>solution-XXX.gnuplot</code> where <code>XXX</code>\n// denotes the number of the time step and always consists of three digits\n// even if we are still in the single or double digit time steps.\n#include <deal.II/base/utilities.h>\n\n// The last step is as in all previous programs:\nnamespace Step23\n{\n  using namespace dealii;\n\n\n  // @sect3{The <code>WaveEquation</code> class}\n\n  // Next comes the declaration of the main class. It's public interface of\n  // functions is like in most of the other tutorial programs. Worth\n  // mentioning is that we now have to store four matrices instead of one: the\n  // mass matrix $M$, the Laplace matrix $A$, the matrix $M+k^2\\theta^2A$ used\n  // for solving for $U^n$, and a copy of the mass matrix with boundary\n  // conditions applied used for solving for $V^n$. Note that it is a bit\n  // wasteful to have an additional copy of the mass matrix around. We will\n  // discuss strategies for how to avoid this in the section on possible\n  // improvements.\n  //\n  // Likewise, we need solution vectors for $U^n,V^n$ as well as for the\n  // corresponding vectors at the previous time step, $U^{n-1},V^{n-1}$. The\n  // <code>system_rhs</code> will be used for whatever right hand side vector\n  // we have when solving one of the two linear systems in each time\n  // step. These will be solved in the two functions <code>solve_u</code> and\n  // <code>solve_v</code>.\n  //\n  // Finally, the variable <code>theta</code> is used to indicate the\n  // parameter $\\theta$ that is used to define which time stepping scheme to\n  // use, as explained in the introduction. The rest is self-explanatory.\n  template <int dim>\n  class WaveEquation\n  {\n  public:\n    WaveEquation ();\n    void run ();\n\n  private:\n    void setup_system ();\n    void solve_u ();\n    void solve_v ();\n    void output_results () const;\n\n    Triangulation<dim>   triangulation;\n    FE_Q<dim>            fe;\n    DoFHandler<dim>      dof_handler;\n\n    ConstraintMatrix constraints;\n\n    SparsityPattern      sparsity_pattern;\n    SparseMatrix<double> mass_matrix;\n    SparseMatrix<double> laplace_matrix;\n    SparseMatrix<double> matrix_u;\n    SparseMatrix<double> matrix_v;\n\n    Vector<double>       solution_u, solution_v;\n    Vector<double>       old_solution_u, old_solution_v;\n    Vector<double>       system_rhs;\n\n    double time, time_step;\n    unsigned int timestep_number;\n    const double theta;\n  };\n\n\n\n  // @sect3{Equation data}\n\n  // Before we go on filling in the details of the main class, let us define\n  // the equation data corresponding to the problem, i.e. initial and boundary\n  // values for both the solution $u$ and its time derivative $v$, as well as\n  // a right hand side class. We do so using classes derived from the Function\n  // class template that has been used many times before, so the following\n  // should not be a surprise.\n  //\n  // Let's start with initial values and choose zero for both the value $u$ as\n  // well as its time derivative, the velocity $v$:\n  template <int dim>\n  class InitialValuesU : public Function<dim>\n  {\n  public:\n    InitialValuesU () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n\n  template <int dim>\n  class InitialValuesV : public Function<dim>\n  {\n  public:\n    InitialValuesV () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n\n\n  template <int dim>\n  double InitialValuesU<dim>::value (const Point<dim>  & /*p*/,\n                                     const unsigned int component) const\n  {\n    Assert (component == 0, ExcInternalError());\n    return 0;\n  }\n\n\n\n  template <int dim>\n  double InitialValuesV<dim>::value (const Point<dim>  & /*p*/,\n                                     const unsigned int component) const\n  {\n    Assert (component == 0, ExcInternalError());\n    return 0;\n  }\n\n\n\n  // Secondly, we have the right hand side forcing term. Boring as we are, we\n  // choose zero here as well:\n  template <int dim>\n  class RightHandSide : public Function<dim>\n  {\n  public:\n    RightHandSide () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n\n\n  template <int dim>\n  double RightHandSide<dim>::value (const Point<dim>  & /*p*/,\n                                    const unsigned int component) const\n  {\n    Assert (component == 0, ExcInternalError());\n    return 0;\n  }\n\n\n\n  // Finally, we have boundary values for $u$ and $v$. They are as described\n  // in the introduction, one being the time derivative of the other:\n  template <int dim>\n  class BoundaryValuesU : public Function<dim>\n  {\n  public:\n    BoundaryValuesU () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n\n\n\n  template <int dim>\n  class BoundaryValuesV : public Function<dim>\n  {\n  public:\n    BoundaryValuesV () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n\n\n\n  template <int dim>\n  double BoundaryValuesU<dim>::value (const Point<dim> &p,\n                                      const unsigned int component) const\n  {\n    Assert (component == 0, ExcInternalError());\n\n    if ((this->get_time() <= 0.5) &&\n        (p[0] < 0) &&\n        (p[1] < 1./3) &&\n        (p[1] > -1./3))\n      return std::sin (this->get_time() * 4 * numbers::PI);\n    else\n      return 0;\n  }\n\n\n\n  template <int dim>\n  double BoundaryValuesV<dim>::value (const Point<dim> &p,\n                                      const unsigned int component) const\n  {\n    Assert (component == 0, ExcInternalError());\n\n    if ((this->get_time() <= 0.5) &&\n        (p[0] < 0) &&\n        (p[1] < 1./3) &&\n        (p[1] > -1./3))\n      return (std::cos (this->get_time() * 4 * numbers::PI) *\n              4 * numbers::PI);\n    else\n      return 0;\n  }\n\n\n\n\n  // @sect3{Implementation of the <code>WaveEquation</code> class}\n\n  // The implementation of the actual logic is actually fairly short, since we\n  // relegate things like assembling the matrices and right hand side vectors\n  // to the library. The rest boils down to not much more than 130 lines of\n  // actual code, a significant fraction of which is boilerplate code that can\n  // be taken from previous example programs (e.g. the functions that solve\n  // linear systems, or that generate output).\n  //\n  // Let's start with the constructor (for an explanation of the choice of\n  // time step, see the section on Courant, Friedrichs, and Lewy in the\n  // introduction):\n  template <int dim>\n  WaveEquation<dim>::WaveEquation () :\n    fe (1),\n    dof_handler (triangulation),\n    time_step (1./64),\n    theta (0.5)\n  {}\n\n\n  // @sect4{WaveEquation::setup_system}\n\n  // The next function is the one that sets up the mesh, DoFHandler, and\n  // matrices and vectors at the beginning of the program, i.e. before the\n  // first time step. The first few lines are pretty much standard if you've\n  // read through the tutorial programs at least up to step-6:\n  template <int dim>\n  void WaveEquation<dim>::setup_system ()\n  {\n    GridGenerator::hyper_cube (triangulation, -1, 1);\n    triangulation.refine_global (7);\n\n    std::cout << \"Number of active cells: \"\n              << triangulation.n_active_cells()\n              << std::endl;\n\n    dof_handler.distribute_dofs (fe);\n\n    std::cout << \"Number of degrees of freedom: \"\n              << dof_handler.n_dofs()\n              << std::endl\n              << std::endl;\n\n    sparsity_pattern.reinit (dof_handler.n_dofs(),\n                             dof_handler.n_dofs(),\n                             dof_handler.max_couplings_between_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n    sparsity_pattern.compress();\n\n    // Then comes a block where we have to initialize the 3 matrices we need\n    // in the course of the program: the mass matrix, the laplace matrix, and\n    // the matrix $M+k^2\\theta^2A$ used when solving for $U^n$ in each time\n    // step.\n    //\n    // When setting up these matrices, note that they all make use of the same\n    // sparsity pattern object. Finally, the reason why matrices and sparsity\n    // patterns are separate objects in deal.II (unlike in many other finite\n    // element or linear algebra classes) becomes clear: in a significant\n    // fraction of applications, one has to hold several matrices that happen\n    // to have the same sparsity pattern, and there is no reason for them not\n    // to share this information, rather than re-building and wasting memory\n    // on it several times.\n    //\n    // After initializing all of these matrices, we call library functions\n    // that build the Laplace and mass matrices. All they need is a DoFHandler\n    // object and a quadrature formula object that is to be used for numerical\n    // integration. Note that in many respects these functions are better than\n    // what we would usually do in application programs, for example because\n    // they automatically parallelize building the matrices if multiple\n    // processors are available in a machine. The matrices for solving linear\n    // systems will be filled in the run() method because we need to re-apply\n    // boundary conditions every time step.\n    mass_matrix.reinit (sparsity_pattern);\n    laplace_matrix.reinit (sparsity_pattern);\n    matrix_u.reinit (sparsity_pattern);\n    matrix_v.reinit (sparsity_pattern);\n\n    MatrixCreator::create_mass_matrix (dof_handler, QGauss<dim>(3),\n                                       mass_matrix);\n    MatrixCreator::create_laplace_matrix (dof_handler, QGauss<dim>(3),\n                                          laplace_matrix);\n\n    // The rest of the function is spent on setting vector sizes to the\n    // correct value. The final line closes the hanging node constraints\n    // object. Since we work on a uniformly refined mesh, no constraints exist\n    // or have been computed (i.e. there was no need to call\n    // DoFTools::make_hanging_node_constraints as in other programs), but we\n    // need a constraints object in one place further down below anyway.\n    solution_u.reinit (dof_handler.n_dofs());\n    solution_v.reinit (dof_handler.n_dofs());\n    old_solution_u.reinit (dof_handler.n_dofs());\n    old_solution_v.reinit (dof_handler.n_dofs());\n    system_rhs.reinit (dof_handler.n_dofs());\n\n    constraints.close ();\n  }\n\n\n  // @sect4{WaveEquation::solve_u and WaveEquation::solve_v}\n\n  // The next two functions deal with solving the linear systems associated\n  // with the equations for $U^n$ and $V^n$. Both are not particularly\n  // interesting as they pretty much follow the scheme used in all the\n  // previous tutorial programs.\n  //\n  // One can make little experiments with preconditioners for the two matrices\n  // we have to invert. As it turns out, however, for the matrices at hand\n  // here, using Jacobi or SSOR preconditioners reduces the number of\n  // iterations necessary to solve the linear system slightly, but due to the\n  // cost of applying the preconditioner it is no win in terms of run-time. It\n  // is not much of a loss either, but let's keep it simple and just do\n  // without:\n  template <int dim>\n  void WaveEquation<dim>::solve_u ()\n  {\n    SolverControl           solver_control (1000, 1e-8*system_rhs.l2_norm());\n    SolverCG<>              cg (solver_control);\n\n    cg.solve (matrix_u, solution_u, system_rhs,\n              PreconditionIdentity());\n\n    std::cout << \"   u-equation: \" << solver_control.last_step()\n              << \" CG iterations.\"\n              << std::endl;\n  }\n\n\n  template <int dim>\n  void WaveEquation<dim>::solve_v ()\n  {\n    SolverControl           solver_control (1000, 1e-8*system_rhs.l2_norm());\n    SolverCG<>              cg (solver_control);\n\n    cg.solve (matrix_v, solution_v, system_rhs,\n              PreconditionIdentity());\n\n    std::cout << \"   v-equation: \" << solver_control.last_step()\n              << \" CG iterations.\"\n              << std::endl;\n  }\n\n\n\n  // @sect4{WaveEquation::output_results}\n\n  // Likewise, the following function is pretty much what we've done\n  // before. The only thing worth mentioning is how here we generate a string\n  // representation of the time step number padded with leading zeros to 3\n  // character length using the Utilities::int_to_string function's second\n  // argument.\n  template <int dim>\n  void WaveEquation<dim>::output_results () const\n  {\n    DataOut<dim> data_out;\n\n    data_out.attach_dof_handler (dof_handler);\n    data_out.add_data_vector (solution_u, \"U\");\n    data_out.add_data_vector (solution_v, \"V\");\n\n    data_out.build_patches ();\n\n    const std::string filename = \"solution-\" +\n                                 Utilities::int_to_string (timestep_number, 3) +\n                                 \".gnuplot\";\n    std::ofstream output (filename.c_str());\n    data_out.write_gnuplot (output);\n  }\n\n\n\n\n  // @sect4{WaveEquation::run}\n\n  // The following is really the only interesting function of the program. It\n  // contains the loop over all time steps, but before we get to that we have\n  // to set up the grid, DoFHandler, and matrices. In addition, we have to\n  // somehow get started with initial values. To this end, we use the\n  // VectorTools::project function that takes an object that describes a\n  // continuous function and computes the $L^2$ projection of this function\n  // onto the finite element space described by the DoFHandler object. Can't\n  // be any simpler than that:\n  template <int dim>\n  void WaveEquation<dim>::run ()\n  {\n    setup_system();\n\n    VectorTools::project (dof_handler, constraints, QGauss<dim>(3),\n                          InitialValuesU<dim>(),\n                          old_solution_u);\n    VectorTools::project (dof_handler, constraints, QGauss<dim>(3),\n                          InitialValuesV<dim>(),\n                          old_solution_v);\n\n    // The next thing is to loop over all the time steps until we reach the\n    // end time ($T=5$ in this case). In each time step, we first have to\n    // solve for $U^n$, using the equation $(M^n + k^2\\theta^2 A^n)U^n =$\n    // $(M^{n,n-1} - k^2\\theta(1-\\theta) A^{n,n-1})U^{n-1} + kM^{n,n-1}V^{n-1}\n    // +$ $k\\theta \\left[k \\theta F^n + k(1-\\theta) F^{n-1} \\right]$. Note\n    // that we use the same mesh for all time steps, so that $M^n=M^{n,n-1}=M$\n    // and $A^n=A^{n,n-1}=A$. What we therefore have to do first is to add up\n    // $MU^{n-1} - k^2\\theta(1-\\theta) AU^{n-1} + kMV^{n-1}$ and the forcing\n    // terms, and put the result into the <code>system_rhs</code> vector. (For\n    // these additions, we need a temporary vector that we declare before the\n    // loop to avoid repeated memory allocations in each time step.)\n    //\n    // The one thing to realize here is how we communicate the time variable\n    // to the object describing the right hand side: each object derived from\n    // the Function class has a time field that can be set using the\n    // Function::set_time and read by Function::get_time. In essence, using\n    // this mechanism, all functions of space and time are therefore\n    // considered functions of space evaluated at a particular time. This\n    // matches well what we typically need in finite element programs, where\n    // we almost always work on a single time step at a time, and where it\n    // never happens that, for example, one would like to evaluate a\n    // space-time function for all times at any given spatial location.\n    Vector<double> tmp (solution_u.size());\n    Vector<double> forcing_terms (solution_u.size());\n\n    for (timestep_number=1, time=time_step;\n         time<=5;\n         time+=time_step, ++timestep_number)\n      {\n        std::cout << \"Time step \" << timestep_number\n                  << \" at t=\" << time\n                  << std::endl;\n\n        mass_matrix.vmult (system_rhs, old_solution_u);\n\n        mass_matrix.vmult (tmp, old_solution_v);\n        system_rhs.add (time_step, tmp);\n\n        laplace_matrix.vmult (tmp, old_solution_u);\n        system_rhs.add (-theta * (1-theta) * time_step * time_step, tmp);\n\n        RightHandSide<dim> rhs_function;\n        rhs_function.set_time (time);\n        VectorTools::create_right_hand_side (dof_handler, QGauss<dim>(2),\n                                             rhs_function, tmp);\n        forcing_terms = tmp;\n        forcing_terms *= theta * time_step;\n\n        rhs_function.set_time (time-time_step);\n        VectorTools::create_right_hand_side (dof_handler, QGauss<dim>(2),\n                                             rhs_function, tmp);\n\n        forcing_terms.add ((1-theta) * time_step, tmp);\n\n        system_rhs.add (theta * time_step, forcing_terms);\n\n        // After so constructing the right hand side vector of the first\n        // equation, all we have to do is apply the correct boundary\n        // values. As for the right hand side, this is a space-time function\n        // evaluated at a particular time, which we interpolate at boundary\n        // nodes and then use the result to apply boundary values as we\n        // usually do. The result is then handed off to the solve_u()\n        // function:\n        {\n          BoundaryValuesU<dim> boundary_values_u_function;\n          boundary_values_u_function.set_time (time);\n\n          std::map<unsigned int,double> boundary_values;\n          VectorTools::interpolate_boundary_values (dof_handler,\n                                                    0,\n                                                    boundary_values_u_function,\n                                                    boundary_values);\n\n          // The matrix for solve_u() is the same in every time steps, so one\n          // could think that it is enough to do this only once at the\n          // beginning of the simulation. However, since we need to apply\n          // boundary values to the linear system (which eliminate some matrix\n          // rows and columns and give contributions to the right hand side),\n          // we have to refill the matrix in every time steps before we\n          // actually apply boundary data. The actual content is very simple:\n          // it is the sum of the mass matrix and a weighted Laplace matrix:\n          matrix_u.copy_from (mass_matrix);\n          matrix_u.add (theta * theta * time_step * time_step, laplace_matrix);\n          MatrixTools::apply_boundary_values (boundary_values,\n                                              matrix_u,\n                                              solution_u,\n                                              system_rhs);\n        }\n        solve_u ();\n\n\n        // The second step, i.e. solving for $V^n$, works similarly, except\n        // that this time the matrix on the left is the mass matrix (which we\n        // copy again in order to be able to apply boundary conditions, and\n        // the right hand side is $MV^{n-1} - k\\left[ \\theta A U^n +\n        // (1-\\theta) AU^{n-1}\\right]$ plus forcing terms. %Boundary values\n        // are applied in the same way as before, except that now we have to\n        // use the BoundaryValuesV class:\n        laplace_matrix.vmult (system_rhs, solution_u);\n        system_rhs *= -theta * time_step;\n\n        mass_matrix.vmult (tmp, old_solution_v);\n        system_rhs += tmp;\n\n        laplace_matrix.vmult (tmp, old_solution_u);\n        system_rhs.add (-time_step * (1-theta), tmp);\n\n        system_rhs += forcing_terms;\n\n        {\n          BoundaryValuesV<dim> boundary_values_v_function;\n          boundary_values_v_function.set_time (time);\n\n          std::map<unsigned int,double> boundary_values;\n          VectorTools::interpolate_boundary_values (dof_handler,\n                                                    0,\n                                                    boundary_values_v_function,\n                                                    boundary_values);\n          matrix_v.copy_from (mass_matrix);\n          MatrixTools::apply_boundary_values (boundary_values,\n                                              matrix_v,\n                                              solution_v,\n                                              system_rhs);\n        }\n        solve_v ();\n\n        // Finally, after both solution components have been computed, we\n        // output the result, compute the energy in the solution, and go on to\n        // the next time step after shifting the present solution into the\n        // vectors that hold the solution at the previous time step. Note the\n        // function SparseMatrix::matrix_norm_square that can compute\n        // $\\left<V^n,MV^n\\right>$ and $\\left<U^n,AU^n\\right>$ in one step,\n        // saving us the expense of a temporary vector and several lines of\n        // code:\n        output_results ();\n\n        std::cout << \"   Total energy: \"\n                  << (mass_matrix.matrix_norm_square (solution_v) +\n                      laplace_matrix.matrix_norm_square (solution_u)) / 2\n                  << std::endl;\n\n        old_solution_u = solution_u;\n        old_solution_v = solution_v;\n      }\n  }\n}\n\n\n// @sect3{The <code>main</code> function}\n\n// What remains is the main function of the program. There is nothing here\n// that hasn't been shown in several of the previous programs:\nint main ()\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step23;\n\n      deallog.depth_console (0);\n\n      WaveEquation<2> wave_equation_solver;\n      wave_equation_solver.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "f2ec2bdeda0fe52bc1b63095e61b30b46beb5244", "size": 25699, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-23/step-23.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/step-23/step-23.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/step-23/step-23.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 38.4140508221, "max_line_length": 80, "alphanum_fraction": 0.624965952, "num_tokens": 6009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.44217005387268904}}
{"text": "#include \"k52/optimization/steepest_descent_method.h\"\n\n#ifdef BUILD_WITH_MPI\n\n#include <boost/mpi.hpp>\n#include <k52/parallel/mpi/constants.h>\n\n#endif\n\n#include <iostream>\n#include <cmath>\n\n#include <k52/optimization/params/i_continuous_parameters.h>\n\nnamespace\n{\n/// @brief Golden ratio value for GoldenSectionSearch method\n/// @link https://en.wikipedia.org/wiki/Golden_ratio\n\tconst double kAlpha = (1.0 + sqrt(5.0)) / 2.0;\n}\n\nusing ::std::vector;\n\nnamespace k52\n{\nnamespace optimization\n{\n\nSteepestDescentMethod::SteepestDescentMethod(\n    double increment_of_the_argument,\n    size_t max_iteration_number,\n    double precision)\n    : increment_of_the_argument_(increment_of_the_argument)\n    , max_iteration_number_(max_iteration_number)\n    , precision_(precision)\n{\n}\n\nSteepestDescentMethod* SteepestDescentMethod::Clone() const\n{\n    return new SteepestDescentMethod(\n        increment_of_the_argument_,\n        max_iteration_number_,\n        precision_);\n}\n\nstd::string SteepestDescentMethod::get_name() const\n{\n    return \"Steepest Descent Method\";\n}\n\n\n#ifdef BUILD_WITH_MPI\nvoid SteepestDescentMethod::Send(boost::mpi::communicator* communicator, int target) const\n {\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, increment_of_the_argument_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, max_iteration_number_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, precision_);\n}\n\nvoid SteepestDescentMethod::Receive(boost::mpi::communicator* communicator, int source)\n{\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, increment_of_the_argument_);\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, max_iteration_number_);\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, precision_);\n}\n#endif\n\n\nvector<double> SteepestDescentMethod::FindOptimalParameters(const vector<double>& initial_parameters)\n{\n    vector<double> parameters(initial_parameters);\n    size_t counter = 0;\n    double lambda = 1; \n\n    vector<double> next_step_parameters(parameters);\n    do\n    {\n        parameters = next_step_parameters;\n        counter++;\n        vector<double> gradient = CalculateGradient(parameters);\n        vector<double> invert_gradiend = InvertVector(gradient);\n\n        lambda = GoldenSectionSearch(parameters, lambda, invert_gradiend);\n\n        for (size_t i = 0; i < next_step_parameters.size(); ++i)\n        {\n            next_step_parameters[i] = parameters[i] + lambda * invert_gradiend[i];\n        }\n\n    } while (!IsExitCriteriaFulfilled(next_step_parameters) \n        && !(counter == max_iteration_number_));\n\n    return parameters;\n}\n\nbool SteepestDescentMethod::IsExitCriteriaFulfilled(\n    const vector<double>& steps_array) const\n{\n    double temp = 0;\n    vector<double> gradient = CalculateGradient(steps_array);\n    for (size_t i = 0; i < steps_array.size(); ++i)\n    {\n        temp += gradient[i] * gradient[i];\n    }\n    if (sqrt(temp) > precision_)\n    {\n        return false;\n    }\n    return true;\n}\n/// @TODO: needs to replaced copy-pasted method to the method from Math\n/// @Source: conjugate_gradient_method.cpp\n/// @link https://github.com/PavelKovalets/k52/blob/develop/src/optimization/conjugate_gradient_method.cpp#L159\nvector<double> SteepestDescentMethod::CalculateGradient(\n    const vector<double>& parameters) const\n{\n    vector<double> gradient(parameters.size());\n\n    for (size_t i = 0; i<parameters.size(); ++i)\n    {\n        gradient[i] = CalculateDerivative(parameters, i);\n    }\n\n    return gradient;\n}\n\n/// @TODO: needs to replaced copy-pasted method to the method from Math\n/// @Source: conjugate_gradient_method.cpp\n/// @link https://github.com/PavelKovalets/k52/blob/develop/src/optimization/conjugate_gradient_method.cpp#L126\ndouble SteepestDescentMethod::CalculateDerivative(\n    const vector<double>& parameters,\n    const size_t& index) const\n{\n    double half = 0.5;\n    vector<double> decrement_function(parameters);\n    vector<double> increment_function(parameters);\n    decrement_function[index] = parameters[index] - increment_of_the_argument_ * half;\n    increment_function[index] = parameters[index] + increment_of_the_argument_ * half;\n    double increment_function_value = CountObjectiveFunctionValueToMinimize(increment_function);\n    double decrement_function_value = CountObjectiveFunctionValueToMinimize(decrement_function);\n    return (increment_function_value - decrement_function_value) / increment_of_the_argument_;\n}\n\n/// @TODO: needs to replaced to the method from Math\nvector<double> SteepestDescentMethod::InvertVector(\n    const vector<double>& parameters) const\n{\n    vector<double> new_parameters(parameters);\n    for (size_t i = 0; i < new_parameters.size(); ++i)\n    {\n        new_parameters[i] *= -1;\n    }\n    return new_parameters;\n}\n\ndouble SteepestDescentMethod::GoldenSectionSearch(\n    const vector<double>& init_point, \n    const double& step, \n    const vector<double>& direction) const\n{\n    vector<double> next_point(init_point.size());\n    double lambda = 0;\n    double step_for_borders = 0;\n\n    step_for_borders = Localization(init_point, step, direction);\n\t\n    lambda = FindStepLength(init_point, step_for_borders, direction);\n\n    return lambda;\n}\n\ndouble SteepestDescentMethod::FindStepLength(\n    const vector<double>& init_parameters, \n    const double& step_for_borders,\n    const vector<double>& direction) const\n{\n    vector<double> right_border_parameters(init_parameters.size());\n    vector<double> next_left_border_point(init_parameters.size());\n    vector<double> next_right_border_point(init_parameters.size());\n    double left_border = 0;\n    double next_left_border = 0;\n    double next_right_border = 0;\n    double constriction_number = 0.382;\n    double right_border = step_for_borders;\n\t\n    for (size_t i = 0; i < init_parameters.size(); ++i)\n    {\n        right_border_parameters[i] = init_parameters[i] + step_for_borders*direction[i];\n    }\n\t\n    next_left_border = left_border + constriction_number*(right_border - left_border);\n    next_right_border = right_border - constriction_number*(right_border - left_border);\n\n    double last_left_border = 0;\n    double last_right_border = 0;\n    double next_left_border_value = 0;\n    double next_right_border_value = 0;\n    do\n    {\n        for (size_t i = 0; i < init_parameters.size(); ++i)\n        {\n            next_left_border_point[i] = init_parameters[i] + next_left_border*direction[i];\n            next_right_border_point[i] = init_parameters[i] + next_right_border*direction[i];\n        }\n        next_left_border_value = CountObjectiveFunctionValueToMinimize(next_left_border_point);\n        next_right_border_value = CountObjectiveFunctionValueToMinimize(next_right_border_point);\n\n        last_left_border = left_border;\n        last_right_border = right_border;\n\n        if (next_left_border < next_right_border)\n        {\n            if (next_left_border_value > next_right_border_value)\n            {\n                left_border = next_left_border;\n                next_left_border = next_right_border;\n                next_right_border = right_border - constriction_number * (right_border - left_border);\n            }\n            else\n            {\n                right_border = next_right_border;\n                next_right_border = next_left_border;\n                next_left_border = left_border + constriction_number * (right_border - left_border);\n            }\n        }\n        else\n        {\n            if (next_right_border_value > next_left_border_value)\n            {\n                left_border = next_right_border;\n                next_right_border = next_left_border;\n                next_left_border = right_border - constriction_number * (right_border - left_border);\n            }\n            else\n            {\n                right_border = next_left_border;\n                next_left_border = next_right_border;\n                next_right_border = left_border + constriction_number * (right_border - left_border);\n            }\n        }\n        if ((left_border == last_left_border && right_border == last_right_border)) {\n            break;\n        }\n\n    } while ((abs(left_border - right_border) > precision_));\n\n    return (left_border + right_border) / 2;\n}\n\ndouble SteepestDescentMethod::Localization(\n    const vector<double>& init_parameters, \n    const double& init_step, \n    const vector<double>& direction) const\n{\n    vector<double> point(init_parameters.size());\n    double step = init_step*2;\n\n    do {\n\t\tstep /= 2;\n        for (size_t i = 0; i < point.size(); ++i)\n        {\n            point[i] = init_parameters[i] + step*direction[i];\n        }       \t\t\n    } while ((CountObjectiveFunctionValueToMinimize(point) > CountObjectiveFunctionValueToMinimize(init_parameters))\n        && (abs(step) > precision_));\n\n\n    vector<double> next_step_point(point);\n    do\n    {\n        point = next_step_point;\n        step *= kAlpha;\n        for (size_t i = 0; i < point.size(); ++i)\n        {\n        next_step_point[i] = init_parameters[i] + step*direction[i];\n        }\n\n        \n    } while (CountObjectiveFunctionValueToMinimize(next_step_point) <= CountObjectiveFunctionValueToMinimize(point));\n\n    double final_step = 0;\n    for (size_t i = 0; i < next_step_point.size(); ++i)\n    {\n        final_step += (next_step_point[i] - init_parameters[i])*(next_step_point[i] - init_parameters[i]);\n    }\n\n    return sqrt(final_step);\n}\n\n}//optimization\n}//k52", "meta": {"hexsha": "ac7352ba6e53c129946137abdcdafd571769beda", "size": 9524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimization/steepest_descent_method.cpp", "max_stars_repo_name": "PavelKovalets/k52", "max_stars_repo_head_hexsha": "2d2c58cc4e3330e88a9cc6ae03d80749d04bcba7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2016-04-14T07:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-22T22:03:20.000Z", "max_issues_repo_path": "src/optimization/steepest_descent_method.cpp", "max_issues_repo_name": "PavelKovalets/k52", "max_issues_repo_head_hexsha": "2d2c58cc4e3330e88a9cc6ae03d80749d04bcba7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2016-04-05T08:49:05.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-29T07:09:00.000Z", "max_forks_repo_path": "src/optimization/steepest_descent_method.cpp", "max_forks_repo_name": "PavelKovalets/k52", "max_forks_repo_head_hexsha": "2d2c58cc4e3330e88a9cc6ae03d80749d04bcba7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-16T07:53:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-12T21:31:51.000Z", "avg_line_length": 32.6164383562, "max_line_length": 117, "alphanum_fraction": 0.6900461991, "num_tokens": 2173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.44217004877322064}}
{"text": "#include <cmath>\r\n#include <boost/math/special_functions/fpclassify.hpp> // isnan, isinf\r\n#include <ecf/ECF.h>\r\n#include \"SymbRegEvalOp.h\"\r\n#include \"ReadData.h\"\r\n#include \"infixTree.h\"\r\n\r\n// from WriteBest.h\r\nextern bool evaluateVerbose;\r\n\r\n\r\nvoid SymbRegEvalOp::registerParameters(StateP state)\r\n{\r\n\tstate->getRegistry()->registerEntry(\"input_file\", (voidP)(new std::string), ECF::STRING);\r\n\tstate->getRegistry()->registerEntry(\"linear_scaling\", (voidP) (new uint(0)), ECF::UINT);\r\n\tstate->getRegistry()->registerEntry(\"error_weights_file\", (voidP) (new std::string), ECF::STRING);\r\n\tstate->getRegistry()->registerEntry(\"error_metric\", (voidP) (new std::string), ECF::STRING);\r\n\tstate->getRegistry()->registerEntry(\"data_skip\", (voidP) (new uint(1)), ECF::UINT);\r\n\tstate->getRegistry()->registerEntry(\"data_offset\", (voidP) (new uint(0)), ECF::UINT);\r\n}\r\n\r\n\r\nvoid SymbRegEvalOp::createTerminals(StateP state)\r\n{\r\n\tstatic std::string configTerminals = *((std::string*) state->getGenotypes()[0]->getParameterValue(state, \"terminalset\").get());\r\n\t//configTerminals = *((std::string*) state->getRegistry()->getEntry(\"Tree.terminalset\").get());\r\n\r\n\tvarNames.clear();\r\n\tstd::string terminalSet;\r\n\tfor(uint i = 0; i < nVariables; i++) {\r\n\t\tvarNames.push_back (\"x\" + uint2str(i + 1));\r\n\t\tterminalSet += varNames[i] + \" \";\r\n\t}\r\n\r\n\t// set terminal names\r\n\tterminalSet = configTerminals + \" \" + terminalSet;\r\n\tstate->getGenotypes()[0]->setParameterValue(state, \"terminalset\", (voidP) new std::string(terminalSet));\r\n\t//state->getRegistry()->modifyEntry(\"Tree.terminalset\", (voidP) new std::string(terminalSet));\r\n\r\n\t// reinitialize population with updated terminals\r\n\tTree::Tree* hometree = (Tree::Tree*) state->getGenotypes()[0].get();\r\n\thometree->primitiveSet_ = Tree::PrimitiveSetP();\r\n\tstate->getPopulation()->initialize(state);\r\n}\r\n\r\n\r\nbool SymbRegEvalOp::initialize(StateP state)\r\n{\r\n\tstate_ = state;\r\n\trecordResults = false;\r\n\tresults.clear();\r\n\r\n\tvoidP sptr = state->getRegistry()->getEntry(\"data_skip\");\r\n\tuint skip = *((uint*)sptr.get());\r\n\tsptr = state->getRegistry()->getEntry(\"data_offset\");\r\n\tuint offset = *((uint*)sptr.get());\r\n\tsptr = state->getRegistry()->getEntry(\"linear_scaling\");\r\n\tuint scaling = *((uint*)sptr.get());\r\n\tlinearScaling = false;\r\n\tif(scaling != 0)\r\n\t\tlinearScaling = true;\r\n\r\n\tstd::string dataFile = *((std::string*) state->getRegistry()->getEntry(\"input_file\").get());\r\n\t// read from file into Evaluator data\r\n\tif (!readDataFromFile(data, dataFile, offset, skip)) {\r\n\t\treturn false;\r\n\t}\r\n\r\n\tnSamples = data.size();\r\n\tnVariables = data[0].size() - 1;\r\n\tresults.resize(nSamples);\r\n\r\n\t// a) create terminal names for use with canonical GP\r\n\tcreateTerminals(state);\r\n\r\n\t// b) read terminal names from config\r\n\t//varNames.clear();\r\n\t//std::string terminals = *((std::string*) state->getGenotypes()[0]->getParameterValue(state, \"terminalset\").get());\r\n\t//std::stringstream ss(terminals);\r\n\t//std::string terminal;\r\n\t//for(uint i = 0; i < nVariables; i++) {\r\n\t//\tss >> terminal;\r\n\t//\tvarNames.push_back (terminal);\r\n\t//}\r\n\r\n\t// initialize evaluator\r\n\teval.data = &data;\r\n\teval.initialize();\r\n\tfor(uint i = 0; i < nVariables; i++) {\r\n\t\teval.addTerminal(varNames[i]);\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\n\r\nFitnessP SymbRegEvalOp::evaluate(IndividualP individual)\r\n{\r\n\tif(linearScaling == true)\r\n\t\treturn evaluateUsingLinearScaling(individual);\r\n\r\n\t// we try to minimize the function value, so we use FitnessMin fitness (for minimization problems)\r\n\tFitnessP fitness (new FitnessMin);\r\n\r\n\t// get the genotype we defined in the configuration file\r\n\tTree::Tree* tree = (Tree::Tree*) individual->getGenotype().get();\r\n\r\n\t// output tree expression to string\r\n\tstd::stringstream sValue;\r\n\tfor(uint i = 0; i < tree->size(); i++) {\r\n\t\tsValue << (*tree)[i]->primitive_->getName() << \" \";\r\n\t}\r\n\t// send expression to evaluator\r\n\teval.parseExpression(sValue.str(), tree->size());\r\n\r\n\tdouble value = 0;\r\n\tdouble result;\r\n\t// evaluating data from input file\r\n\tfor (uint i = 0; i < nSamples; i++) {\r\n\t\t//// set only defined variables (x1, x2, ...)\r\n\t\t//for(uint term = 0; term < nVariables; term++) {\r\n\t\t//\ttree->setTerminalValue(varNames[term], &data[i][term]);\r\n\t\t//}\r\n\r\n\t\t//// get the f value of the current tree\r\n\t\t//tree->execute(&result);\r\n\r\n\t\tresult = eval.executeParsedExpression(i);\r\n\r\n\t\t// clip the value to [0, 255]\r\n\t\tresult = (int) abs(result);\r\n\t\tif(result > 255)\r\n\t\t\tresult = 255;\r\n\r\n\t\tif(recordResults)\r\n\t\t\tresults[i] = result;\r\n\r\n\t\t// add the absolute difference\r\n\t\t//value += fabs(eval.data[i][nVariables] - result);\r\n\t\t// or squared error\r\n\t\tdouble error = fabs(data[i][nVariables] - result) * fabs(data[i][nVariables] - result);\r\n\t\t\r\n\t\tvalue += error;\r\n\t}\r\n\r\n\tvalue /= nSamples;\t   // MSE\r\n\tvalue = sqrt(value);   // RMSE\r\n\r\n\tfitness->setValue(value);\r\n\r\n\tif(evaluateVerbose) {\r\n\t\tstringstream ss;\r\n\t\tstring infix;\r\n\t\tshowTree(infix, tree);\r\n\t\tss << infix << endl;\r\n\t\tECF_LOG(state_, 1, ss.str());\r\n\t}\r\n\r\n\treturn fitness;\r\n}\r\n\r\n\r\nFitnessP SymbRegEvalOp::evaluateUsingLinearScaling(IndividualP individual)\r\n{\r\n\tFitnessP fitness (new FitnessMin);\r\n\r\n\t// get the genotype we defined in the configuration file\r\n\tTree::Tree* tree = (Tree::Tree*) individual->getGenotype().get();\r\n\r\n\t// output tree expression to string\r\n\tstd::stringstream sValue;\r\n\tfor(uint i = 0; i < tree->size(); i++) {\r\n\t\tsValue << (*tree)[i]->primitive_->getName() << \" \";\r\n\t}\r\n\t// send expression to evaluator\r\n\teval.parseExpression(sValue.str(), tree->size());\r\n\r\n\t//average value of y and t\r\n\tdouble mean_y = 0, mean_t = 0, sum_yt = 0, sum_sqr_y = 0;\r\n\r\n\tfor (uint i = 0 ; i < nSamples ; i++)\r\n\t{\r\n\t\t//// set only defined variables (x1, x2, ...)\r\n\t\t//for(uint term = 0; term < nVariables; term++) {\r\n\t\t//\ttree->setTerminalValue(varNames[term], &data[i][term]);\r\n\t\t//}\r\n\r\n\t\t// get the y value of the current tree\r\n\t\tdouble y;\r\n\t\t//tree->execute(&y);\r\n\t\ty = eval.executeParsedExpression(i);\r\n\r\n\t\t// clip the value to [0, 255]\r\n\t\ty = (int) abs(y);\r\n\t\tif(y > 255)\r\n\t\t\ty = 255;\r\n\r\n\t\tmean_y += y;\r\n\t\tdouble t = data[i][nVariables];\r\n\t\tmean_t += t;\r\n\t\tsum_yt += t*y;\r\n\t\tsum_sqr_y += y*y;\r\n\t}\r\n\r\n\tmean_y /= nSamples;\r\n\tmean_t /= nSamples;\r\n\r\n\t//coefficients for linear regression\r\n\tdouble b = (sum_yt - nSamples*mean_y*mean_t)/(sum_sqr_y - nSamples*mean_y*mean_y);\r\n\tdouble a = mean_t - b*mean_y;\r\n\r\n\tbool isNaN = boost::math::isnan(a) || boost::math::isnan(b);\r\n\tbool isInf = boost::math::isinf(a) || boost::math::isinf(b);\r\n\tif (isNaN || isInf) {\r\n\t\ta = 0;\r\n\t\tb = 1;\r\n//\t\tfitness->setValue(1e14);\r\n//\t\treturn fitness;\r\n\t}\r\n\r\n\tdouble value = 0;\r\n\tdouble var_of_y = 0; //variance of variable result\r\n\r\n\tfor(uint i = 0; i < nSamples; i++) {\r\n\t\t//// set only defined variables (x1, x2, ...)\r\n\t\t//for(uint term = 0; term < nVariables; term++) {\r\n\t\t//\ttree->setTerminalValue(varNames[term], &data[i][term]);\r\n\t\t//}\r\n\r\n\t\tdouble y;\r\n\t\t//tree->execute(&y);\r\n\t\ty = eval.executeParsedExpression(i);\r\n\r\n\t\t// clip the value to [0, 255]\r\n\t\ty = (int) abs(y);\r\n\t\tif(y > 255)\r\n\t\t\ty = 255;\r\n\r\n\t\tvar_of_y += (y-mean_y)*(y-mean_y);\r\n\t\tdouble result = a + b*y;\r\n\t\tresult = (int) result;\r\n\r\n\t\tif(recordResults)\r\n\t\t\tresults[i] = result;\r\n\r\n\t\t// add the absolute difference\r\n\t\t//value += fabs(eval.data[i][nVariables] - result);\r\n\t\t// or squared error\r\n\t\tdouble error = fabs(data[i][nVariables] - result) * fabs(data[i][nVariables] - result);\r\n\t\tvalue += error;\r\n\t}\r\n\r\n\tvalue /= nSamples;\t   // MSE\r\n\tvalue = sqrt(value);   // RMSE\r\n\r\n\tvar_of_y /= nSamples-1;\r\n\r\n\tif (evaluateVerbose) {\r\n\t\tstringstream ss;\r\n\t\tstring infix;\r\n\t\tshowTree(infix, tree);\r\n\t\tss << infix << endl;\r\n\t\tss << \"Linear scaling parameters: scale=\" << b << \" offset=\" << a << std::endl;\r\n\t\tECF_LOG(state_, 1, ss.str());\r\n\t}\r\n\r\n\tfitness->setValue(value);\r\n\r\n\treturn fitness;\r\n}\r\n\r\n", "meta": {"hexsha": "f18b812d4da8248b9efe938ae97009cff0a8d104", "size": 7707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SymbRegEvalOp.cpp", "max_stars_repo_name": "rymoah/CoInGP", "max_stars_repo_head_hexsha": "d9906f7d21211d11e23e085734f7e71aab7d59ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-14T00:35:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T00:35:25.000Z", "max_issues_repo_path": "src/SymbRegEvalOp.cpp", "max_issues_repo_name": "rymoah/CoInGP", "max_issues_repo_head_hexsha": "d9906f7d21211d11e23e085734f7e71aab7d59ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SymbRegEvalOp.cpp", "max_forks_repo_name": "rymoah/CoInGP", "max_forks_repo_head_hexsha": "d9906f7d21211d11e23e085734f7e71aab7d59ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3345588235, "max_line_length": 129, "alphanum_fraction": 0.6356558972, "num_tokens": 2168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.44217004040732794}}
{"text": "/*\n Copyright (C) 2020 Quaternion Risk Management Ltd\n All rights reserved.\n*/\n\n#include <boost/make_shared.hpp>\n#include <ql/math/distributions/chisquaredistribution.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/processes/eulerdiscretization.hpp>\n#include <qle/models/crcirpp.hpp>\n#include <qle/processes/crcirppstateprocess.hpp>\n\nnamespace QuantExt {\n\nCrCirppStateProcess::CrCirppStateProcess(CrCirpp* const model,\n                                         CrCirppStateProcess::Discretization disc)\n    : StochasticProcess(boost::shared_ptr<StochasticProcess::discretization>(new EulerDiscretization)), model_(model),\n      discretization_(disc) {}\n\nSize CrCirppStateProcess::size() const { return 2; }\n\nDisposable<Array> CrCirppStateProcess::initialValues() const {\n    Array res(size(), 0.0);\n    res[0] = model_->parametrization()->y0(0); // y0\n    res[1] = 1.0; // S(0,0) = 1\n    return res;\n}\n\nDisposable<Array> CrCirppStateProcess::drift(Time t, const Array& x) const {\n    QL_FAIL(\"not implemented\");\n}\n\nDisposable<Matrix> CrCirppStateProcess::diffusion(Time t, const Array& x) const {\n    QL_FAIL(\"not implemented\");\n}\n\nDisposable<Array> CrCirppStateProcess::evolve(Time t0, const Array& x0, Time dt, const Array& dw) const {\n    Array retVal(size());\n    Real kappa, theta, sigma, y0;\n    kappa = model_->parametrization()->kappa(t0);\n    theta = model_->parametrization()->theta(t0);\n    sigma = model_->parametrization()->sigma(t0);\n    y0 = model_->parametrization()->y0(t0);\n\n    const Real sdt = std::sqrt(dt);\n    switch (discretization_) {\n\n    case BrigoAlfonsi: {\n        // see D. Brigo and F. Mercurio. Interest Rate Models: Theory and Practice, 2nd\n        // Edition. Springer, 2006.\n        // Ensures non-negative values for \\sigma^2 \\leq 2*\\kappa*\\theta\n        Real temp = (1 - kappa / 2.0 * dt);\n        Real temp2 = temp * std::sqrt(x0[0]) + sigma * sdt * dw[0] / (2.0 * temp);\n        retVal[0] = temp2 * temp2 + (kappa * theta - sigma * sigma / 4) * dt;\n        break;\n    }\n    default:\n        QL_FAIL(\"unknown discretization schema\");\n    }\n\n    // second element is S(0,i)\n    Real SM_ti = model_->defaultCurve()->survivalProbability(t0 + dt);\n    Real SM_ti_pre = model_->defaultCurve()->survivalProbability(t0);\n    Real Pcir_ti = model_->zeroBond(0, t0 + dt, y0);\n    Real Pcir_ti_pre = model_->zeroBond(0, t0, y0);\n    retVal[1] = x0[1] * SM_ti / SM_ti_pre * Pcir_ti_pre / Pcir_ti * exp(-x0[0] * dt);\n\n    return retVal;\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "a041e46b86af4fde81c7d1b63c797fcffeec21eb", "size": 2515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/processes/crcirppstateprocess.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/processes/crcirppstateprocess.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/processes/crcirppstateprocess.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 34.9305555556, "max_line_length": 118, "alphanum_fraction": 0.6632206759, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.44216858161004574}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2013, The University of Texas at Dallas\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of The University of Texas at Dallas nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n */\n \n/*\n * Filename: connectivity.cpp\n * \n * Description: This file contains the ROS node that calculates the control variables\n * for a collection of iRobot Creates.\n * \n * Log\n * ----\n * 2013-09-15 File created by Hazen Eckert\n *\n */\n \n// ROS includes\n#include \"ros/ros.h\"\n#include \"ros/assert.h\"\n#include \"dynamic_reconfigure/server.h\"\n#include \"create_driver/vicon_driver.h\"\n\n// Library includes\n#include <string>\n#include <vector>\n#include <map>\n#include <set>\n#include <algorithm>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Eigenvalues> \n\n// Local Package includes\n#include \"connectivity_controller/EigenConnectivityMsgs.h\"\n#include \"connectivity_controller/ConnectivityVariablesConfig.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n#define RHO1 0.7\n#define RHO2 2.3\n\n// Collision avoidance variables\ndouble R = 0.7;\t  \ndouble r = 0.33;\n\ndouble psi( double x, double rho1, double rho2 )\n{\n\tif ( x <= rho1 ) {\n\t\treturn 1;\n\t} else if ( rho1 < x && x < rho2 ) {\n\t\treturn ( exp(-1/(rho2-x)) / ( exp(-1/(rho2-x)) + exp(1/(rho1-x)) ) );\n\t} else if ( rho2 <= x ) {\n\t\treturn 0;\n\t}\n\treturn 0;\n}\n\ndouble psiPrime( double d )\n{\n\tif ( d <= RHO1 ) {\n\t\treturn 0;\n\t} else if ( RHO1 < d && d < RHO2 ) {\n\t\treturn (-0.5)*( pow((d-RHO1),(-2))+pow((d-RHO2),(-2)) ) / (1+  cosh(  (1/(-d+RHO1))+(1/(-d+RHO2)) )   );\n\t} else if ( RHO2 <= d ) {\n\t\treturn 0;\n\t}\n\treturn 0;\n}\n\nvoid reconfigureCallback(connectivity_controller::ConnectivityVariablesConfig &config, uint32_t level) {\n\tR = config.r_max;\n\tr = config.r_min;\n\n}\n\nint main(int argc, char **argv)\n{\n\t// ROS Initalization\n\tros::init(argc, argv, \"connectivity\");\n\t\n\tros::NodeHandle n;\n\tros::NodeHandle private_n(\"~\");\n\n\tdynamic_reconfigure::Server<connectivity_controller::ConnectivityVariablesConfig> server;\n  \tdynamic_reconfigure::Server<connectivity_controller::ConnectivityVariablesConfig>::CallbackType f;\n  \tf = boost::bind(&reconfigureCallback, _1, _2);\n \tserver.setCallback(f);\n\n\t// ROS Parameters\n\n\t// List of robot names\n\tvector<string> robot_names;\n\tXmlRpc::XmlRpcValue robot_list;\n\tprivate_n.getParam(\"robot_list\", robot_list);\n\tROS_ASSERT(robot_list.getType() == XmlRpc::XmlRpcValue::TypeArray);\n\n\tfor (int i = 0; i < robot_list.size(); i++) \n\t{\n\t\tROS_ASSERT(robot_list[i].getType() == XmlRpc::XmlRpcValue::TypeString);\n\t\trobot_names.push_back(static_cast<string>(robot_list[i]));\n\t}\n\t\n\t// List of formation x positions\n\tvector<double> formation_x;\n\tXmlRpc::XmlRpcValue x_list;\n\tprivate_n.getParam(\"formation_x_list\", x_list);\n\tROS_ASSERT(x_list.getType() == XmlRpc::XmlRpcValue::TypeArray);\n\n\tfor (int i = 0; i < x_list.size(); i++) \n\t{\n\t\tROS_ASSERT(x_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble);\n\t\tformation_x.push_back(static_cast<double>(x_list[i]));\n\t}\n\t\n\t// List of formation y positions\n\tvector<double> formation_y;\n\tXmlRpc::XmlRpcValue y_list;\n\tprivate_n.getParam(\"formation_y_list\", y_list);\n\tROS_ASSERT(y_list.getType() == XmlRpc::XmlRpcValue::TypeArray);\n\n\tfor (int i = 0; i < y_list.size(); i++) \n\t{\n\t\tROS_ASSERT(y_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble);\n\t\tformation_y.push_back(static_cast<double>(y_list[i]));\n\t}\n\t\n\t// Number of robots\n\tconst int num_robots = robot_names.size();\n\t\n\t// ROS Subscribers\n\tmap<string, create_driver::ViconStream> vicon;\n\tvector<string>::iterator name_it;\n\tvector<ros::Subscriber> sub;\n\n\tfor (name_it = robot_names.begin(); name_it != robot_names.end(); name_it++)\n\t{\n\t\tvicon.insert(pair<string, create_driver::ViconStream>(*name_it, create_driver::ViconStream()));\n\t\tsub.push_back(n.subscribe(*name_it + \"/tf\", 10, &create_driver::ViconStream::callback, &vicon[*name_it]));\n\t}\n\t\n\t// ROS Publishers\n\tros::Publisher pub = n.advertise<connectivity_controller::EigenConnectivityMsgs>(\"/connectivity\", 10);\n\t\n\t// ROS loop\n\tros::Rate loop_rate(250); // 250 Hz\n\n\tdouble rho2[] = { 2.3, 2.2, 1.9, 1.5, 1.7, 2.0 };\n\n\n\twhile (ros::ok())\n\t{\n\t\t// Retrieve Vicon Data\n\t\tros::spinOnce();\n\t\t\n\t\t// Calculations\n\t\tMatrixXd adjacency_matrix = MatrixXd::Zero(num_robots, num_robots);\n\t\tMatrixXd P = MatrixXd::Zero(num_robots, num_robots - 1);\n\t\tMatrixXd L = MatrixXd::Zero(num_robots, num_robots);\n\t\tMatrixXd S = MatrixXd::Zero(num_robots, num_robots);\n\t\t\n\t\t// Adjacency Matrix\t\n\t\tfor (int i = 0; i < num_robots; i++) \n\t\t{\n\t\t\tfor (int j = 0; j < num_robots; j++)\n\t\t\t{\n\t\t\t\tif ( i == j )\n\t\t\t\t{\n\t\t\t\t\tadjacency_matrix(i,j) = 0.0;\n\t\t\t\t} else {\n\t\t\t\t\tadjacency_matrix(i,j) = psi(sqrt(\n\t\t\t\t\tpow(vicon[robot_names[j]].x() - vicon[robot_names[i]].x(), 2) + \n\t\t\t\t\tpow(vicon[robot_names[j]].y() - vicon[robot_names[i]].y(), 2)\n\t\t\t\t\t), RHO1, rho2[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tROS_WARN_STREAM(\"Adj matrix:\"  << adjacency_matrix );\n\n\t\t\n\t\t// L Matrix\n\t\tfor (int i = 0; i < num_robots; i++) \n\t\t{\n\t\t\tfor (int j = 0; j < num_robots; j++)\n\t\t\t{\n\t\t\t\tif ( i == j ) {\n\t\t\t\t\tdouble rowSum = 0;\n\t\t\t\t\tfor (int k = 0; k < num_robots; k++) {\n\t\t\t\t\t\trowSum += adjacency_matrix(i,k);\n\t\t\t\t\t}\n\t\t\t\t\tL(i,j) = rowSum - adjacency_matrix(i,j);\n\t\t\t\t} else {\n\t\t\t\t\tL(i,j) = -adjacency_matrix(i,j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tROS_WARN_STREAM(\"L matrix:\"  << L );\n\n\t\t// S Matrix\n\t\tS = MatrixXd::Identity(num_robots, num_robots) - L/((double)num_robots); // S = I - L/n\n\t\t\n\t\tROS_WARN_STREAM(\"S matrix:\"  << S );\n\n\t\t// Get eigenvalues and eigen vectors\n\t\tEigenSolver<MatrixXd> es(S.transpose());\n\t\tVectorXcd eigenvalues = es.eigenvalues();\n\t\tMatrixXcd eigenvectors = es.eigenvectors();\n\t\t\n\t\tROS_WARN_STREAM(\"Eigenvalues\"  << eigenvalues );\n\t\tROS_WARN_STREAM(\"Eigenvectors:\"  << eigenvectors );\n\n\t\tstd::complex<double> max_eigenvalue(0.0,0.0);\n\t\tVectorXcd gamma = VectorXcd::Zero(num_robots);\n\t\t\n\t\tfor (int i = 0; i < num_robots; i++)\n\t\t{\n\t\t\tif (abs(eigenvalues(i)) > abs(max_eigenvalue))\n\t\t\t{\n\t\t\t\tmax_eigenvalue = eigenvalues(i);\n\t\t\t\tgamma = eigenvectors.col(i);\n\t\t\t}\n\t\t}\n\t\t\n\t\t//ROS_WARN_STREAM(\"Max Eigenvalue:\"  << max_eigenvalue );\n\t\tROS_WARN_STREAM(\"Gamma:\"  << gamma );\n\n\t\tMatrixXcd inv_gamma1 = MatrixXcd::Zero(num_robots, num_robots);\n\t\tMatrixXcd inv_gamma2 = MatrixXcd::Zero(num_robots, num_robots);\n\t\tMatrixXcd inv_gamma1m = MatrixXcd::Zero(num_robots, num_robots);;\n\t\tMatrixXcd inv_gamma2m = MatrixXcd::Zero(num_robots, num_robots);;\n\n\t\tdouble control_input_CC_x[num_robots];\n\t\tdouble control_input_CC_y[num_robots];\n\t\t\n\t\tfor (int i = 0; i < num_robots; i++)\n\t\t{\n\t\t\tVectorXcd gammai = VectorXcd::Zero(num_robots);\n\t\t\tfor (int m = 0; m < num_robots; m++)\n\t\t\t{\n\t\t\t\tgammai(m) = abs(gamma(i));\n\t\t\t} \n\n\t\t\t//ROS_WARN_STREAM(\"gammai:\"  << gammai );\n\n\t\t\tinv_gamma1.row(i) = gamma.transpose()/gamma(i);\n\n\t\t\t//ROS_WARN_STREAM(\"inv_gamma1.row(\" << i << \"):\"  << inv_gamma1.row(i) );\n\t\t\t\n\t\t\tVectorXcd temp_inv_gamma2 = VectorXcd::Zero(num_robots);\n\t\t\tfor (int n = 0; n < num_robots; n++)\n\t\t\t{\n\t\t\t\ttemp_inv_gamma2(n) = 1/gamma(n).real();\n\t\t\t}\n\t\t\tinv_gamma2.row(i) = gamma(i)*temp_inv_gamma2.transpose();\n\n\t\t\t//ROS_WARN_STREAM(\"inv_gamma2.row(\" << i << \"):\"  << inv_gamma2.row(i) );\n\t\t\t\n\t\t\tdouble upper_bound_g = 1000.0;\n\t\t\tdouble lower_bound_g = 1.1;\n\t\t\tfor (int k = 0; k < num_robots; k++)\n\t\t\t{\n\t\t\t\tdouble gain_param = inv_gamma1(i,k).real();\n\t\t\t\tif (gain_param > lower_bound_g && gain_param < upper_bound_g)\n\t\t\t\t{\n\t\t\t\t\tinv_gamma1m(i,k) = pow(pow(gain_param,2)-pow(lower_bound_g,2), 2)/pow(pow(gain_param,2) - pow(upper_bound_g,2),2); \n\t\t\t\t}\n\n\t\t\t\tgain_param = inv_gamma2(i,k).real();\n\t\t\t\tif (gain_param > lower_bound_g && gain_param < upper_bound_g)\n\t\t\t\t{\n\t\t\t\t\tinv_gamma2m(i,k) = pow(pow(gain_param,2)-pow(lower_bound_g,2), 2)/pow(pow(gain_param,2) - pow(upper_bound_g,2),2); \n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//ROS_WARN_STREAM(\"inv_gamma1m.row(\" << i << \"):\"  << inv_gamma1m.row(i) );\n\t\t\t//ROS_WARN_STREAM(\"inv_gamma2m.row(\" << i << \"):\"  << inv_gamma2m.row(i) );\n\t\t\t\n\t\t\tset<int> neighbors_out;\n\t\t\tset<int> neighbors_in;\n\t\t\tfor (int j = 0; j < num_robots; j++)\n\t\t\t{\n\t\t\t\tif (adjacency_matrix(i,j) > 0)\n\t\t\t\t\tneighbors_out.insert(j);\n\t\t\t\tif (adjacency_matrix(j,i) > 0)\n\t\t\t\t\tneighbors_in.insert(j);\n\t\t\t}\n\t\t\tvector<int> neighbors(num_robots*2);\n\t\t\tvector<int>::iterator it = set_union(neighbors_out.begin(), neighbors_out.end(), \n\t\t\t\t\t\t\t\t\t\t\t\t\tneighbors_in.begin(), neighbors_in.end(), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tneighbors.begin());\n\t\t\tneighbors.resize(it - neighbors.begin());\n\t\t\t\n\t\t\tint Ni = neighbors.size();\n\t\t\t////////////////////////////////////////////\n\t\t\tstd::stringstream ss1;\n\t\t\tfor (std::set<int>::iterator it = neighbors_out.begin(); it != neighbors_out.end(); ++it)\n\t\t\t{\n\t\t\t\tss1 << ' ' << *it;\n\t\t\t}\n\t\t\t//ROS_WARN_STREAM(\"neighbors_out:\"  << ss1.str() );\n\n\t\t\tstd::stringstream ss2;\n\t\t\tfor (std::set<int>::iterator it = neighbors_in.begin(); it != neighbors_in.end(); ++it)\n\t\t\t{\n\t\t\t\tss2 << ' ' << *it;\n\t\t\t}\n\t\t\t//ROS_WARN_STREAM(\"neighbors_in:\"  << ss2.str() );\n\n\t\t\tstd::stringstream ss3;\n\t\t\tfor (std::vector<int>::iterator it = neighbors.begin(); it != neighbors.end(); ++it)\n\t\t\t{\n\t\t\t\tss3 << ' ' << *it;\n\t\t\t}\n\t\t\t//ROS_WARN_STREAM(\"neighbors:\"  << ss3.str() );\n\t\t\t/////////////////////////////////////\n\t\t\tdouble sumx = 0.0;\n\t\t\tdouble sumy = 0.0;\n\n\t\t\tfor (int k = 0; k < Ni; k++)\n\t\t\t{\n\t\t\t\tsumx = sumx + (-1)*( abs(inv_gamma1m(i,neighbors[k]) ) + abs(inv_gamma2m(i,neighbors[k]) )  ) * (vicon[robot_names[i]].x() - vicon[robot_names[neighbors[k]]].x());\n\t\t\t\tsumy = sumy + (-1)*( abs(inv_gamma1m(i,neighbors[k]) ) + abs(inv_gamma2m(i,neighbors[k]) )  ) * (vicon[robot_names[i]].y() - vicon[robot_names[neighbors[k]]].y());\n\t\t\t}\n\t\t\t\n\t\t\tcontrol_input_CC_x[i] = sumx;\n\t\t\tcontrol_input_CC_y[i] = sumy;\n\n\t\t} \n\t\t\n\t\t// P Matrix\n\t\tif (num_robots == 6) \n\t\t{\n\t\t\tP << \t1/sqrt(2), \t\t-1/sqrt(6.0),\t\t-1/2.0/sqrt(3), \t-1/2.0/sqrt(5), \t-1/sqrt(30),\n\t\t\t\t\t0.0,       \t\tsqrt(2.0/3), \t\t-1/2.0/sqrt(3), \t-1/2.0/sqrt(5), \t-1/sqrt(30),\n\t\t\t\t\t0.0, \t\t \t0.0, \t\t\t\tsqrt(3.0)/2,    \t-1/(2*sqrt(5)),\t\t-1/sqrt(30),\n\t\t\t\t\t0.0, \t\t\t0.0, \t\t\t\t0.0, \t\t\t\t2/sqrt(5), \t\t\t-1/sqrt(30),\n\t\t\t\t\t0.0, \t\t\t0.0, \t\t\t\t0.0,\t\t\t\t0.0, \t\t\t\tsqrt(5.0/6),\n\t\t\t\t\t-1/sqrt(2), \t-1/sqrt(6),\t\t\t-1/2.0/sqrt(3), \t-1/2.0/sqrt(5), \t-1/sqrt(30);\n\t\t} else if (num_robots == 4) {\n\t\t\tP << \t-0.5,        \t\t-0.5,              \t-0.5, \n\t\t\t\t\t 0.833333333333333, -0.166666666666667, -0.166666666666667, \n\t\t\t\t\t-0.166666666666667,  0.833333333333333, -0.166666666666667, \n\t\t\t\t\t-0.166666666666667, -0.166666666666667,  0.833333333333333;\n\t\t}\n\t\t// M Matrix\n\t\tMatrixXd M = P.transpose() * L * P;\n\t\t//std::cerr << \"adjacency_matrix\"  << adjacency_matrix  ;\n\t\t// dLdx and dLdy for each robot\n\t\tMatrixXd dLdx[num_robots];\n\t\tMatrixXd dLdy[num_robots];\n\t\t\n\t\tfor (int i = 0; i < num_robots; i++)\n\t\t{\n\t\t\tdLdx[i] = MatrixXd::Zero(num_robots, num_robots);\n\t\t\tdLdy[i] = MatrixXd::Zero(num_robots, num_robots);\n\t\t}\n\t\t\n\t\tfor(int k = 0; k < num_robots; k++)\n\t\t{\n\t\t\tfor(int i = 0; i < num_robots; i++)\n\t\t\t{\n\t\t\t\tfor (int j = i + 1; j < num_robots; j++) \n\t\t\t\t{\n\t\t\t\t\tdouble D = sqrt(\n\t\t\t\t\tpow(vicon[robot_names[i]].x() - vicon[robot_names[j]].x(), 2) + \n\t\t\t\t\tpow(vicon[robot_names[i]].y() - vicon[robot_names[j]].y(), 2)\n\t\t\t\t\t);\n\t\t\t\t\t\n\t\t\t\t\tdouble dAdD = psiPrime(D);\n\t\t\t\n\t\t\t\t\tif( k == i ) {\n\t\t\t\t\t\tdouble dDdx = (vicon[robot_names[i]].x()-vicon[robot_names[j]].x()) / D;\t\t\t\t\t\t\t\n\t\t\t\t\t\tdouble dDdy = (vicon[robot_names[i]].y()-vicon[robot_names[j]].y()) / D;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdLdx[k](i,j) = dAdD*dDdx;\n\t\t\t\t\t\tdLdy[k](i,j) = dAdD*dDdy;        \t\t\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\tif( k == j ) {\n\t\t\t\t\t\tdouble dDdx = -(vicon[robot_names[i]].x()-vicon[robot_names[j]].x()) /D;\t\t\t\t\t\t\t\n\t\t\t\t\t\tdouble dDdy = -(vicon[robot_names[i]].y()-vicon[robot_names[j]].y()) / D;\n\t\t\t\t\t\t\n\t\t\t\t\t\tdLdx[k](i,j) = dAdD*dDdx;\n\t\t\t\t\t\tdLdy[k](i,j) = dAdD*dDdy;\n\t\t\t\t      \t\t\n\t\t\t\t\t}\n\t\t\t\n\t\t\t   \t\n\t\t\t\t\tdLdx[k](j,i) = dLdx[k](i,j);\n\t\t\t\t\tdLdy[k](j,i) = dLdy[k](i,j);\n\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor(int i = 0; i < num_robots; i++)\n\t\t\t{\n\t\t\t\tdouble sumx = 0;\n\t\t\t\tdouble sumy = 0;\n\t\t\t\tfor(int j = 0; j<num_robots; j++)\n\t\t\t\t{\n\t\t\t\t\tsumx += dLdx[k](i,j);\n\t\t\t\t\tsumy += dLdy[k](i,j);\n\t\t\t\t} \n\t\t\t\tdLdx[k](i,i) = -sumx;\n\t            dLdy[k](i,i) = -sumy;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// dMdx and dMdy for each robot\n\t\tMatrixXd dMdx[num_robots];\n\t\tMatrixXd dMdy[num_robots];\n\t\t\n\t\tfor (int i = 0; i < num_robots; i++)\n\t\t{\n\t\t\tdMdx[i] = P.transpose() * dLdx[i] * P;\n\t\t\tdMdy[i] = P.transpose() * dLdy[i] * P;\n\t\t\t//std:cerr << dMdx[i]  ;\n\t\t}\n\t\t\n\t\t// Collision Avoidance for each robot starts here:\n\t\tMatrixXd CAMatrix_x = MatrixXd::Zero(num_robots,num_robots);\t\t\n\t\tMatrixXd CAMatrix_y = MatrixXd::Zero(num_robots,num_robots);\n\t\t\n\t\tfor(int i = 0; i < num_robots; i++)\n\t\t{\n\t\t\tfor (int j = i + 1; j < num_robots; j++) \n\t\t\t{\n\t\t\t\tdouble D = sqrt( \n\t\t\t\tpow(vicon[robot_names[i]].x() - vicon[robot_names[j]].x(), 2) + \n\t\t\t\tpow(vicon[robot_names[i]].y() - vicon[robot_names[j]].y(), 2)\n\t\t\t\t);\n\t\t\t\tif( D < R && D > r){\n\t\t\t\t\tCAMatrix_x(i,j) = -4*(pow(R,2)-pow(r,2))\n\t\t\t\t\t\t\t\t\t\t*(pow(D,2)-pow(R,2))\n\t\t\t\t\t\t\t\t\t\t/pow((pow(D,2)-pow(r,2)),3)\n\t\t\t\t\t\t\t\t\t\t*(vicon[robot_names[i]].x() \n\t\t\t\t\t\t\t\t\t\t- vicon[robot_names[j]].x());\n\t\t\t\t\t\t\t\t\t\t\n\t\t        \tCAMatrix_y(i,j) = -4*(pow(R,2)-pow(r,2))\n\t\t        \t\t\t\t\t\t*(pow(D,2)-pow(R,2))\n\t\t        \t\t\t\t\t\t/pow((pow(D,2)-pow(r,2)),3)\n\t\t        \t\t\t\t\t\t*(vicon[robot_names[i]].y() \n\t\t        \t\t\t\t\t\t- vicon[robot_names[j]].y());\n            \t} else {\n            \t\tCAMatrix_x(i,j) = 0;\n            \t\tCAMatrix_y(i,j) = 0;\n            \t}\n            \t\n            \tCAMatrix_x(j,i) = -CAMatrix_x(i,j);\n\t       \t\tCAMatrix_y(j,i) = -CAMatrix_y(i,j);\n\t\t\t}\n\t\t}\n\t\t\n\t\tdouble control_input_CA_x[num_robots];\t\t\t\t \t\t \n\t\tdouble control_input_CA_y[num_robots];\t\t\t\t \t\t \n\t\t\n\t\tfor(int i = 0; i < num_robots; i++)\n\t\t{\n\t\t\tdouble sumx = 0;\n\t\t\tdouble sumy = 0;\n\t\t\tfor (int j = 0; j < num_robots; j++) \n\t\t\t{\n\t\t\t\tsumx = sumx + CAMatrix_x(i,j);\n\t\t\t\tsumy = sumy + CAMatrix_y(i,j);\n\t\t\t}\n\t\t\tcontrol_input_CA_x[i] = sumx;\n\t\t\tcontrol_input_CA_y[i] = sumy;\n\t\t}\n\t\t\t\n\t\tdouble control_input_FC_x[num_robots];\t\t\t\t \t\t \n\t\tdouble control_input_FC_y[num_robots];\n\n\t\tfor (int i = 0; i < num_robots; i++)\n\t\t{\n\t\t\tcontrol_input_FC_x[i] = formation_x[i] - vicon[robot_names[i]].x();\n\t\t\tcontrol_input_FC_y[i] = formation_y[i] - vicon[robot_names[i]].y();\n\t\t}\n\n\t\t// Trace of Mx and My for each robot\n\t\tdouble trace_Mx[num_robots];\n\t\tdouble trace_My[num_robots];\n\t\t\n\t\tfor (int i = 0; i < num_robots; i++)\n\t\t{\n\t\t\t//std::cerr << (M.inverse()*dMdx[i])  ;\n\t\t\ttrace_Mx[i] = (M.inverse()*dMdx[i]).trace();\n\t\t\ttrace_My[i] = (M.inverse()*dMdy[i]).trace();\n\t\t}\n\t\t\n\t\tdouble determinant_M = M.determinant();\n\n\t\t// Send msg\n\t\t\n\t\tconnectivity_controller::EigenConnectivityMsgs msg; \n\t\t\n\t\tmsg.trMx.assign(trace_Mx, trace_Mx + num_robots);\n\t\tmsg.trMy.assign(trace_My, trace_My + num_robots);\n\n\t\tmsg.u_cc_x.assign(control_input_CC_x, control_input_CC_x + num_robots);\n\t\tmsg.u_cc_y.assign(control_input_CC_y, control_input_CC_y + num_robots);\n\n\t\tmsg.u_ca_x.assign(control_input_CA_x, control_input_CA_x + num_robots);\n\t\tmsg.u_ca_y.assign(control_input_CA_y, control_input_CA_y + num_robots);\n\n\t\tmsg.u_fc_x.assign(control_input_FC_x, control_input_FC_x + num_robots);\n\t\tmsg.u_fc_y.assign(control_input_FC_y, control_input_FC_y + num_robots);\n\t\tmsg.detM = determinant_M;\n\n\t\tpub.publish(msg);\n\t\t\n\t\t// Sleep\n\t\tloop_rate.sleep();\n\t}\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "a0269cbccc25cd856cd33e6d90d1787f90ae76f3", "size": 16495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/connectivity_controller/src/eigen_connectivity.cpp", "max_stars_repo_name": "rsthomp/UTDchess-RospyXbee", "max_stars_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-09-03T01:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2015-09-03T01:52:06.000Z", "max_issues_repo_path": "src/connectivity_controller/src/eigen_connectivity.cpp", "max_issues_repo_name": "RachaelT/UTDchess-RospyXbee", "max_issues_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/connectivity_controller/src/eigen_connectivity.cpp", "max_forks_repo_name": "RachaelT/UTDchess-RospyXbee", "max_forks_repo_head_hexsha": "f77ef98afadbb082cde7040b2e770be34fbd2999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2660550459, "max_line_length": 167, "alphanum_fraction": 0.6157017278, "num_tokens": 5423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.44216857530192183}}
{"text": "#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include <vector>\n#include <boost/timer/timer.hpp>\n#include <GeomLib.hpp>\n#include <MPILib/include/MPINetworkCode.hpp>\n#include <MPILib/include/RateAlgorithmCode.hpp>\n#include <MPILib/include/SimulationRunParameter.hpp>\n#include <MPILib/include/report/handler/InactiveReportHandler.hpp>\n#include <MPILib/include/WilsonCowanAlgorithm.hpp>\n#include <MPILib/include/RateFunctorCode.hpp>\n#include <MPILib/include/utilities/ProgressBar.hpp>\n#include <MPILib/include/BasicDefinitions.hpp>\n#include <MPILib/include/WilsonCowanParameter.hpp>\n#include <MPILib/include/WilsonCowanAlgorithm.hpp>\n#include <MPILib/include/MiindTvbModelAbstract.hpp>\n\nMPILib::Rate External_RateFunction(MPILib::Time t){\n\treturn 1.0;\n}\n/* This class is designed to be used in conjunction with\n * Miind_WilsonCowan.py only. Any updates to this shared library\n * should be communicated to the TVB team and a new .so file should be provided\n * to be included in the tvb-library source tree (tvb-library/tvb/simulator/models/).\n */\nclass MiindWilsonCowan : public MPILib::MiindTvbModelAbstract<double, MPILib::utilities::CircularDistribution>{\nprivate:\n\tstd::vector<double> E_Initials = std::vector<double> (); // initial excitatory values\n\tstd::vector<double> I_Initials = std::vector<double> (); // initial inhibitory values\n\npublic:\n\n\tMiindWilsonCowan(int num_nodes, double simulation_length, double dt) :\n\t\tMiindTvbModelAbstract(num_nodes, simulation_length) {\n\t\t\tthis->_time_step = dt;\n\t\t}\n\n\t// In general, we won't need to set initial values but we implement it here\n\t// so that we can match TVB's Wilson Cowan example.\n\tvoid setInitialValues(std::vector<double> E_vals, std::vector<double> I_vals) {\n\t\tfor(int i=0; i<_num_nodes; i++) {\n\t\t\tE_Initials.push_back(E_vals[i]);\n\t\t\tI_Initials.push_back(I_vals[i]);\n\t\t}\n\t}\n\n\tvoid init(std::vector<double> params)\n\t{\n\t\t// (TVB : tau_e) population time constant\n\t\tTime   E_tau       = params[4];\n\t\t// (TVB : c_e) maximum rate reached by the sigmoid function\n\t\tRate   E_max_rate  = params[6];\n\t\t// (TVB : a_e) noise term modulates the input (a term in Wilson Cowan)\n\t\tdouble E_noise     = params[10];\n\t\t// (TVB : b_e) bias term shifts the input (theta term in Wilson Cowan)\n\t\tdouble E_bias      = params[12];\n\t\t// (TVB : r_e) smoothing term over output which models refractory dynamics\n\t\tdouble E_smoothing = params[8];\n\t\t// (TVB : tau_i) population time constant\n\t\tTime   I_tau       = params[5];\n\t\t// (TVB : c_i) maximum rate reached by the sigmoid function\n\t\tRate   I_max_rate  = params[7];\n\t\t// (TVB : a_i) noise term modulates the input\n\t\tdouble I_noise     = params[11];\n\t\t// (TVB : b_i) bias term shifts the input\n\t\tdouble I_bias      = params[13];\n\t\t// (TVB : r_e) smoothing term over output which models refractory dynamics\n\t\tdouble I_smoothing = params[9];\n\t\t// (TVB : c_ee) Weight of E->E connection\n\t\tdouble E_E_Weight  = params[0];\n\t\t// (TVB : -c_ie) Weight of E->I connection\n\t\tdouble I_E_Weight  = -params[1];\n\t\t // (TVB : c_ei) Weight of I->E connection\n\t\tdouble E_I_Weight  = params[2];\n\t\t// (TVB : -c_ii) Weight of I->I connection\n\t\tdouble I_I_Weight  = -params[3];\n\t\t// (TVB : P) Some additional drive to excitatory pop\n\t\tdouble P_E_Weight  = params[14];\n\t\t// (TVB : Q) Some additional drive to inhibitory pop\n\t\tdouble Q_I_Weight  = params[15];\n\n\t\ttry {\n\t\t\tstd::vector<NodeId> E_ids = std::vector<NodeId>();\n\t\t\tstd::vector<NodeId> I_ids = std::vector<NodeId>();\n\n\t\t\tfor(int i=0; i<_num_nodes; i++) {\n\t\t\t\tMPILib::WilsonCowanParameter E_param = MPILib::WilsonCowanParameter(\n\t\t\t\t\t\t\t\tE_tau, E_max_rate, E_noise, E_bias, E_Initials[i], E_smoothing);\n\t\t\t\tMPILib::WilsonCowanAlgorithm E_alg(E_param);\n\n\t\t\t\tMPILib::WilsonCowanParameter I_param = MPILib::WilsonCowanParameter(\n\t\t\t\t\t\t\t\tI_tau, I_max_rate, I_noise, I_bias, I_Initials[i], I_smoothing);\n\t\t\t\tMPILib::WilsonCowanAlgorithm I_alg(I_param);\n\n\t\t\t\tMPILib::Rate RateFunction_P(MPILib::Time);\n\t\t\t\tMPILib::RateFunctor<double> rate_functor_p(External_RateFunction);\n\n\t\t\t\tMPILib::Rate RateFunction_Q(MPILib::Time);\n\t\t\t\tMPILib::RateFunctor<double> rate_functor_q(External_RateFunction);\n\n\t\t\t\tMPILib::NodeId id_E = network.addNode(E_alg, MPILib::EXCITATORY_DIRECT);\n\t\t\t\tMPILib::NodeId id_I = network.addNode(I_alg, MPILib::INHIBITORY_DIRECT);\n\t\t\t\tMPILib::NodeId id_P = network.addNode(rate_functor_p, MPILib::NEUTRAL);\n\t\t\t\tMPILib::NodeId id_Q = network.addNode(rate_functor_q, MPILib::NEUTRAL);\n\n\t\t\t\tE_ids.push_back(id_E);\n\t\t\t\tI_ids.push_back(id_I);\n\n\t\t\t\tnetwork.makeFirstInputOfSecond(id_E,id_E,E_E_Weight);\n\t\t\t\tnetwork.makeFirstInputOfSecond(id_I,id_E,I_E_Weight);\n\t\t\t\tnetwork.makeFirstInputOfSecond(id_E,id_I,E_I_Weight);\n\t\t\t\tnetwork.makeFirstInputOfSecond(id_I,id_I,I_I_Weight);\n\t\t\t\tnetwork.makeFirstInputOfSecond(id_P,id_E,P_E_Weight);\n\t\t\t\tnetwork.makeFirstInputOfSecond(id_Q,id_I,Q_I_Weight);\n\n\t\t\t}\n\n\t\t\t// Set each node to have an external successor (for coupling input from TVB)\n\t\t\tfor(auto& id : E_ids) {\n\t\t\t\tnetwork.setNodeExternalSuccessor(id);\n\t\t\t\tnetwork.setNodeExternalPrecursor(id, 1);\n\t\t\t}\n\n\t\t\tfor(auto& id : I_ids) {\n\t\t\t\tnetwork.setNodeExternalSuccessor(id);\n\t\t\t\tnetwork.setNodeExternalPrecursor(id, 1);\n\t\t\t}\n\n\t\t\tstd::string sim_name = \"miind_wc\";\n\t\t\tMPILib::report::handler::InactiveReportHandler handler =\n\t\t\t\t\t\t\t\t\t\t\tMPILib::report::handler::InactiveReportHandler();\n\n\t\t\tSimulationRunParameter par_run( handler,(_simulation_length/_time_step)+1,0,\n\t\t\t\t\t\t\t\t\t\t\t_simulation_length,_time_step,_time_step,sim_name,_time_step);\n\n\t\t\tnetwork.configureSimulation(par_run);\n\n\t\t} catch(std::exception& exc){\n\t\t\tstd::cout << exc.what() << std::endl;\n\t\t}\n\t}\n};\n\nstatic MiindWilsonCowan *model;\n\nstatic PyObject *miind_init(PyObject *self, PyObject *args)\n{\n    int nodes;\n    double sim_time;\n    double time_step;\n\n    if (!PyArg_ParseTuple(args, \"idd\", &nodes, &sim_time, &time_step))\n\treturn NULL;\n    \n    model = new MiindWilsonCowan(nodes, sim_time, time_step);\n\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\nstatic PyObject *miind_initParams(PyObject *self, PyObject *args)\n{\n    PyObject *float_list;\n    int pr_length;\n\n    if (!PyArg_ParseTuple(args, \"O\", &float_list))\n        return NULL;\n    pr_length = PyObject_Length(float_list);\n    if (pr_length < 0)\n        return NULL;\n\n    std::vector<double> params(pr_length);\n\n    for (int index = 0; index < pr_length; index++) {\n        PyObject *item;\n        item = PyList_GetItem(float_list, index);\n        if (!PyFloat_Check(item))\n            params[index] = 0.0;\n        params[index] = PyFloat_AsDouble(item);\n    }\n\n    model->init(params);\n\t\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\nstatic PyObject *miind_setInitialValues(PyObject *self, PyObject *args)\n{\n    PyObject *float_listE;\n    PyObject *float_listI;\n    int pr_length;\n\n    if (!PyArg_ParseTuple(args, \"OO\", &float_listE, &float_listI))\n        return NULL;\n    pr_length = PyObject_Length(float_listE);\n    if (pr_length < 0)\n        return NULL;\n\n    std::vector<double> insE(pr_length);\n    std::vector<double> insI(pr_length);\n\n    for (int index = 0; index < pr_length; index++) {\n        PyObject *item;\n        item = PyList_GetItem(float_listE, index);\n        if (!PyFloat_Check(item))\n            insE[index] = 0.0;\n        insE[index] = PyFloat_AsDouble(item);\n    }\n\n    for (int index = 0; index < pr_length; index++) {\n        PyObject *item;\n        item = PyList_GetItem(float_listI, index);\n        if (!PyFloat_Check(item))\n            insI[index] = 0.0;\n        insI[index] = PyFloat_AsDouble(item);\n    }\n\n    model->setInitialValues(insE,insI);\n\t\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\nstatic PyObject *miind_getTimeStep(PyObject *self, PyObject *args)\n{\n    return Py_BuildValue(\"d\", model->getTimeStep());\n}\n\nstatic PyObject *miind_getSimulationLength(PyObject *self, PyObject *args)\n{\n    return Py_BuildValue(\"d\", model->getSimulationLength());\n}\n\nstatic PyObject *miind_startSimulation(PyObject *self, PyObject *args)\n{\n    model->startSimulation();\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\nstatic PyObject *miind_evolveSingleStep(PyObject *self, PyObject *args)\n{\n    PyObject *float_list;\n    int pr_length;\n\n    if (!PyArg_ParseTuple(args, \"O\", &float_list))\n        return NULL;\n    pr_length = PyObject_Length(float_list);\n    if (pr_length < 0)\n        return NULL;\n\n    std::vector<double> activities(pr_length);\n\n    for (int index = 0; index < pr_length; index++) {\n        PyObject *item;\n        item = PyList_GetItem(float_list, index);\n        if (!PyFloat_Check(item))\n            activities[index] = 0.0;\n        activities[index] = PyFloat_AsDouble(item);\n    }\n\n    std::vector<double> out_activities = model->evolveSingleStep(activities);\n\n    PyObject* tuple = PyTuple_New(pr_length);\n\n    for (int index = 0; index < pr_length; index++) {\n        PyTuple_SetItem(tuple, index, Py_BuildValue(\"d\", out_activities[index]));\n    }\n\n    return tuple;\n}\n\nstatic PyObject *miind_endSimulation(PyObject *self, PyObject *args)\n{\n    model->endSimulation();\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\nstatic PyMethodDef MiindModelMethods[] = {\n    {\"init\",  miind_init, METH_VARARGS, \"Init Miind model.\"},\n    {\"initParams\",  miind_initParams, METH_VARARGS, \"Init Miind model parameters.\"},\n    {\"getTimeStep\",  miind_getTimeStep, METH_VARARGS, \"Get time step.\"},\n    {\"getSimulationLength\",  miind_getSimulationLength, METH_VARARGS, \"Get sim time.\"},\n    {\"startSimulation\",  miind_startSimulation, METH_VARARGS, \"Start simulation.\"},\n    {\"evolveSingleStep\",  miind_evolveSingleStep, METH_VARARGS, \"Evolve one time step.\"},\n    {\"endSimulation\",  miind_endSimulation, METH_VARARGS, \"Clean up.\"},\n    {\"setInitialValues\", miind_setInitialValues, METH_VARARGS, \"Set initial values.\"},\n    {NULL, NULL, 0, NULL}        /* Sentinel */\n};\n\nstatic struct PyModuleDef miindmodule = {\n    PyModuleDef_HEAD_INIT,\n    \"libmiindwc\",   /* name of module */\n    NULL, /* module documentation, may be NULL */\n    -1,       /* size of per-interpreter state of the module,\n                 or -1 if the module keeps state in global variables. */\n    MiindModelMethods\n};\n\nPyMODINIT_FUNC\nPyInit_libmiindwc(void)\n{\n    return PyModule_Create(&miindmodule);\n}\n", "meta": {"hexsha": "4f0649f9718262b68068ed070a8a4383266bd9a8", "size": 10156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/TvbModels/wilsoncowan/tvb_wilsoncowan.cpp", "max_stars_repo_name": "dekamps/miind", "max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z", "max_issues_repo_path": "apps/TvbModels/wilsoncowan/tvb_wilsoncowan.cpp", "max_issues_repo_name": "dekamps/miind", "max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z", "max_forks_repo_path": "apps/TvbModels/wilsoncowan/tvb_wilsoncowan.cpp", "max_forks_repo_name": "dekamps/miind", "max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z", "avg_line_length": 33.0814332248, "max_line_length": 111, "alphanum_fraction": 0.6954509649, "num_tokens": 2820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4421685753019218}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n * Filename    : sphdec.cpp                                                                            *\n * Project     : Planewalker - Schnorr-Euchner sphere decoder simulation for space-time lattice codes  *\n * Authors     : Pasi Pyrrö, Oliver Gnilke                                                             *\n * Version     : 1.0                                                                                   *\n * Copyright   : Aalto University ~ School of Science ~ Department of Mathematics and Systems Analysis *\n * Date        : 9.1.2017                                                                              *\n * Language    : C++ (2011 or newer standard)                                                          *\n * Description : The core algorithm implementations for the simulation + wrapper function for them     *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#define ARMA_NO_DEBUG /* disable Armadillo bound checks for addiotional speed */\n\n#include <iostream>\n#include <armadillo> /* linear algebra library */\n#include <vector>\n#include <complex>\n#include <string>\n\n#include \"sphdec.hpp\"\n#include \"misc.hpp\"\n#include \"algorithms.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\n\n/* Decision feedback equalization on xt[i] \n   i.e. Use the Babai nearest plane algorithm as a starting point in dimension i */\ninline void dfe(int i, int q, vec &xt, const vec &y, vec &delta, const vec &ksi, const mat &R, const vector<int> &S) {\n    /* calculate the \"Babai coeffient\" and \"round\" it to nearest symbol in the symbol set */\n    xt[i] = nearest_symbol((y[i]-ksi[i])/R(i,i), S);\n    if (xt[i] <= S[0]) { /* only feasible way is positive direction */\n        delta[i] = 2;\n    } else if (xt[i] >= S[q - 1]) { /* only feasible way is negative direction */\n        delta[i] = -2;\n    } else { /* there's room to enumerate within signal set */\n        delta[i] = 2*sesd_sign(y[i]-ksi[i]-R(i,i)*xt[i]);\n    }\n}\n\n/* Schnorr-Euchner enumeration step for the sphere decoder i.e. zig-zag around the dfe point.\n   Makes sure we loop over the points in dimension i in non descending order.\n   This enables early stopping criteria when we find a point in dimension i outside the radius, \n   i.e. no points in that sub search tree are inside the sphere because they can only be further away or at the same distance. */\ninline void se_enum(int i, vec &xt, vec &delta) {\n    /* add delta to xt and pick new delta (difference to next symbol in S we want to try) */\n    xt[i] = xt[i] + delta[i];\n    delta[i] = -delta[i] - 2*sesd_sign(delta[i]);\n}\n\n/* Perform some basic checks to ensure that the sphere decoder works as intended */\ninline bool check(double radius, const mat &R, const vec &y) {\n    if (radius <= 0){\n        log_msg(\"sphdec: negative squared initial radius given!\", \"Error\");\n        log_msg(\"aborting simulation round...\");\n        return false;\n    }\n\n    if (R.n_rows != R.n_cols) {\n        log_msg(\"sphdec: R is not a square matrix!\", \"Error\");\n        log_msg(\"aborting simulation round...\");\n        return false;\n    }\n\n    if (y.n_elem != R.n_cols) {\n        log_msg(\"sphdec: vector y dimension mismatch!\", \"Error\");\n        log_msg(\"aborting simulation round...\");\n        return false;\n    }\n    return true;\n}\n\n\n/* Basic sphere decoder algorithm */\nvector<int> sphdec(const vec &y, const mat &R, const vector<int> &S, int &counter, double radius){\n\n    /* Initialize */\n    int k = params[\"no_of_matrices\"];\n    int q = params[\"x-PAM\"];\n    int i = k-1; /* We start from dimension k-1 and iterate all the way down to dimension 0 */\n\n    vector<int> x(k); /* point to decode */\n    vec xt(k), ksi(k), delta(k), dist(k);\n    xt.zeros(); ksi.zeros(); delta.zeros(); dist.zeros();\n    counter = 0; /* counts how many search tree nodes (loop iterations) we went through */\n\n    vec distances(k, fill::zeros);\n    \n    double xidist = 0.0;\n    bool found = false;\n\n    if (!check(radius, R, y))\n        return vector<int>(0);\n\n    /* Initialize xt[k-1] and delta[k-1] */\n    dfe(i, q, xt, y, delta, ksi, R, S);\n\n    while (!exit_flag) {\n\n        counter++;\n        /* Step 3. */\n        xidist = pow(y[i]-ksi[i]-R(i,i)*xt[i], 2);\n\n        distances[i] = dist[i] + xidist;\n        \n        /***** Uncomment line below to debug *****/\n        // cout << i << \": \" << vec2str(xt, k) << \", xidist = \" << xidist + dist[i] << \", C = \" << radius << endl;\n\n        if (radius < dist[i] + xidist) { // current point xt is outside the sphere\n            // Step 4.\n            if (i == k-1) {\n                break;\n            } else {\n                // Step 6.\n                i++;\n                se_enum(i, xt, delta);\n            }\n        } else { // we are inside the sphere\n            if (xt[i] < S[0] || xt[i] > S[q - 1]){ // we are outside the signal set boundaries\n                if ((xt[i] < S[0] && (xt[i] + delta[i]) > S[q - 1]) || (xt[i] > S[q - 1] && (xt[i] + delta[i]) < S[0])){\n                    // Step 4.\n                    if (i == k-1) {\n                        break;\n                    } else {\n                        i++;\n                        se_enum(i, xt, delta);\n                    }\n                } else {\n                    se_enum(i, xt, delta);\n                }\n            } else {\n                if (i > 0) {\n                    ksi[i-1] = 0;\n                    for (int j = i; j < k; j++)\n                        ksi[i-1] += R(i-1, j)*xt[j];\n                    dist[i-1] = dist[i] + xidist;\n                    i--;\n                    dfe(i, q, xt, y, delta, ksi, R, S);\n                } else { // lattice point is found (Step 5)\n                    radius = dist[0] + xidist;\n                    found = true;\n                    x = conv_to<vector<int>>::from(xt);\n                    i++;\n                    se_enum(i, xt, delta);\n                }\n            }\n        }\n    }\n    if (found)\n        return x;\n    else {\n        log_msg(\"Initial squared radius used: \" + to_string(radius), \"Alert\");\n        log_msg(\"distances considered: \" + vec2str(distances, distances.size()), \"Alert\");\n        log_msg(\"sphdec: point not found!\", \"Alert\");\n        return vector<int>(0);\n    }\n}\n\n/* Sphere decoder algorithm that considers the spherical shaping of the codebook */\nvector<int> sphdec_spherical_shaping(const vec &y, const mat &HR, const mat &R, const vector<int> &S,\n                                     int &counter, double P, double radius){\n\n    /* Initialize */\n    int k = params[\"no_of_matrices\"];\n    int q = params[\"x-PAM\"];\n    int i = k-1; /* We start from dimension k-1 and iterate all the way down to dimension 0 */\n\n    vector<int> x(k); /* point to decode */\n    vec xt(k), ksi(k), delta(k), dist(k), curr(k), ener(k);\n    xt.zeros(); ksi.zeros(); delta.zeros(); dist.zeros(); curr.zeros(); ener.zeros();\n    counter = 0; /* counts how many search tree nodes (loop iterations) we went through */\n\n    vec distances(k, fill::zeros);\n    \n    double xidist = 0.0, xiener = 0.0;\n    bool found = false;\n\n    if (!check(radius, HR, y))\n        return vector<int>(0);\n\n    /* Initialize xt[k-1] and delta[k-1] */\n    dfe(i, q, xt, y, delta, ksi, HR, S);\n\n    while (!exit_flag) {\n\n        counter++;\n        // Step 3.\n        xidist = pow(y[i]-ksi[i]-HR(i,i)*xt[i], 2);\n\n        distances[i] = dist[i] + xidist;\n        \n        /***** Uncomment line below to debug *****/\n        // cout << i << \": \" << vec2str(xt, k) << \", xidist = \" << xidist + dist[i] << \", C = \" << radius << endl;\n\n        if (radius < dist[i] + xidist) { /* current point xt is outside the sphere */\n            // Step 4.\n            if (i == k-1) {\n                break;\n            } else {\n                // Step 6.\n                i++;\n                se_enum(i, xt, delta);\n            }\n        } else { /* we are inside the sphere */\n\n            xiener = pow(xt[i]*R(i,i) + curr[i], 2);\n\n            // we are outside the signal set boundaries\n            if (xt[i] < S[0] || xt[i] > S[q - 1] || ener[i] + xiener > P + 10e-6) {\n                if ((xt[i] < S[0] && (xt[i] + delta[i]) > S[q - 1]) || (xt[i] > S[q - 1] && (xt[i] + delta[i]) < S[0])){\n                    // Step 4.\n                    if (i == k-1) {\n                        break;\n                    } else {\n                        i++;\n                        se_enum(i, xt, delta);\n                    }\n                } else \n                    se_enum(i, xt, delta);\n            } else {\n                if (i > 0) {\n                    ksi[i-1] = 0;\n                    curr[i-1] = 0;\n                    for (int j = i; j < k; j++){\n                        ksi[i-1] += HR(i-1, j)*xt[j];\n                        curr[i-1] += xt[j]*R(i-1,j);\n                    }\n                    dist[i-1] = dist[i] + xidist;\n                    ener[i-1] = ener[i] + xiener;\n                    i--;\n                    dfe(i, q, xt, y, delta, ksi, HR, S);\n                } else { // lattice point is found (Step 5)\n                    radius = dist[0] + xidist;\n                    found = true;\n                    x = conv_to<vector<int>>::from(xt);\n                    i++;\n                    se_enum(i, xt, delta);\n                }\n            }\n        }\n    }\n    if (found)\n        return x;\n    else {\n        log_msg(\"Initial squared radius used: \" + to_string(radius), \"Alert\");\n        // mat tmp = y-HR*xt;\n        // cx_mat distasd = cx_mat(tmp, mat(tmp.n_rows, tmp.n_cols, fill::zeros));\n        // log_msg(\"Current squared distance: \" + to_string(frob_norm_squared(distasd)), \"Alert\");\n        // log_msg(\"xidist: \" + to_string(xidist), \"Alert\");\n        log_msg(\"distances considered: \" + vec2str(distances, distances.size()), \"Alert\");\n        log_msg(\"sphdec: point not found!\", \"Alert\");\n        return vector<int>(0);\n    }\n}\n\n/* Wrapper function for the sphere decoder to handle complex to real matrix conversion, \n   QR-decomposition and other mappings */\nvector<int> sphdec_wrapper(const vector<cx_mat> &bases, const mat Rorig, const cx_mat &H, \n                           const cx_mat &X, const cx_mat &N, const vector<int> &symbset, int &visited_nodes, double radius) {\n\n    /* read simulation parameters */\n    int n = params[\"no_of_receiver_antennas\"];\n    int t = params[\"time_slots\"];\n    int k = params[\"no_of_matrices\"];\n    double P = dparams[\"spherical_shaping_max_power\"];\n\n    vector<int> x(k);                          /* decoded point */\n    cx_mat Y(n, t);                            /* received code block */\n    mat B(2*t*n, k), Q, R;                     /* real matrices for QR-decompostion */\n    vec y(2*t*n);                              /* raw input vector for the sphere decoder (unmapped) */\n    vec y2;                                    /* input vector for the sphere decoder (mapped to same space a R) */\n    \n    Y = H*X + N;                               /* Calculate simulated code block that we would receive */          \n    y = to_real_vector(Y);                     /* convert Y to real vector */\n\n    for (int i = 0; i < k; i++)\n        B.col(i) = to_real_vector(H*bases[i]); /* B = (HX1 HX2 ... HXk) = generator matrix of faded lattice */\n\n    qr_econ(Q, R, B);                          /* QR-decomposition of B (omits zero rows in R) */\n    process_qr(Q, R);                          /* Make sure R has positive diagonal elements */\n\n    y2 = Q.st()*y;                             /* Map y to same basis as R */\n\n    /* decide which sphere decoder algorithm to use */\n    if (P <= 0)\n        x = sphdec(y2, R, symbset, visited_nodes, radius); \n    else\n        x = sphdec_spherical_shaping(y2, R, Rorig, symbset, visited_nodes, P, radius);\n\n    return x;\n}", "meta": {"hexsha": "5fa34a6090e6f70813368b620ed942a8f3f59ccb", "size": 11829, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sphdec.cpp", "max_stars_repo_name": "Hyper5phere/sphere-decoder", "max_stars_repo_head_hexsha": "f84cbcb47314547150639bbed017e8e540d32ced", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sphdec.cpp", "max_issues_repo_name": "Hyper5phere/sphere-decoder", "max_issues_repo_head_hexsha": "f84cbcb47314547150639bbed017e8e540d32ced", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sphdec.cpp", "max_forks_repo_name": "Hyper5phere/sphere-decoder", "max_forks_repo_head_hexsha": "f84cbcb47314547150639bbed017e8e540d32ced", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5102739726, "max_line_length": 129, "alphanum_fraction": 0.475695325, "num_tokens": 3031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4421685753019218}}
{"text": "\n#if HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include <boost/bind.hpp>\nusing boost::cref;\n\n#include \"Cosmology.h\"\n#include \"PowerSpectrum.h\"\n#include \"Quadrature.h\"\n#include \"CDE.h\"\n#include \"BSPTN.h\"\n#include \"SPT.h\"\n#include \"Spline.h\"\n#include \"SpecialFunctions.h\"\n#include \"LinearPS.h\"\n\n\n#include <cerrno>\n#include <cstdio>\n#include <cstdlib>\n#include <sys/stat.h>\n#include <math.h>       /* pow */\n\n/////////////////CLUSTERING DARK ENERGY (AND MG RESUMMED SPECTRUM) LIBRARY ///////////////////\n// Load Linear PS\nCDE::CDE(const Cosmology& C, const PowerSpectrum& P_l, double epsrel_)\n: C(C), P_l(P_l)\n{\n    epsrel = epsrel;\n}\n\n\n/* Tree level cross bispectrum for  isosceles or equilateral configurations */\n// vars specifies omega_m, cs^2, w , p3 and scale factor\ndouble CDE::Bcde(int a, double vars[], double k, double p, double x) const {\nIOW iow;\niow.initn_cde_btree(vars[4], k, p, x, vars[0], vars[1], vars[2],vars[3]);\ndouble d =  sqrt(pow2(k) + pow2(p) + 2*p*k*x);\ndouble omega_m = vars[0]/pow3(vars[4]);\ndouble A = -3.*(1.+vars[2]);\ndouble omegaf = pow(vars[4],A);\ndouble omega_q= (1.-vars[0])*omegaf;\ndouble cs2 = vars[1];\ndouble norm = 2./pow4(dnorm_spt);\ndouble terms[3];\nif(d < 1e-6)\n    return 0;\nelse\n    switch(a) {\n      // theta_m density_m density_m\n        case 1:\n\t\t\t\t\t\treturn    norm*(P_l(k)*P_l(p)*G1_nk*F1p_nk[0]*F2A_nk[0] +  P_l(d)*P_l(k)*G1_nk*F2D_nk[0]*F1kmp_nk[0]\n                          + P_l(p)*P_l(d)*G2_nk[0]*F1p_nk[0]*F1kmp_nk[0]);\n            break;\n      // theta_q density_m density_m\n        case 2:\n            return    norm*(P_l(k)*P_l(p)*G1q_nk*F1p_nk[0]*F2A_nk[0] +  P_l(d)*P_l(k)*G1q_nk*F2D_nk[0]*F1kmp_nk[0]\n                      + P_l(p)*P_l(d)*G2q_nk[0]*F1p_nk[0]*F1kmp_nk[0]);\n            break;\n      // theta_m \\delta_q \\delta_q\n        case 3:\n            return    norm*(P_l(k)*P_l(p)*G1_nk*F1pq_nk[0]*F2Aq_nk[0] +  P_l(d)*P_l(k)*G1_nk*F2Dq_nk[0]*F1kmpq_nk[0]\n                      + P_l(p)*P_l(d)*G2_nk[0]*F1pq_nk[0]*F1kmpq_nk[0]);\n            break;\n       // theta_q \\delta_q \\delta_q\n        case 4:\n            return    norm*(P_l(k)*P_l(p)*G1q_nk*F1p_nk[0]*F2A_nk[0] +  P_l(d)*P_l(k)*G1q_nk*F2D_nk[0]*F1kmp_nk[0]\n                      + P_l(p)*P_l(d)*G2q_nk[0]*F1p_nk[0]*F1kmp_nk[0]);\n           break;\n      // theta_m \\delta_m \\delta_q\n        case 5:\n            return    norm*(P_l(k)*P_l(p)*G1_nk*F1p_nk[0]*F2Aq_nk[0] +  P_l(d)*P_l(k)*G1_nk*F2D_nk[0]*F1kmpq_nk[0]\n                      + P_l(p)*P_l(d)*G2_nk[0]*F1p_nk[0]*F1kmpq_nk[0]);\n            break;\n     // theta_q \\delta_m \\delta_q\n        case 6:\n            return    norm*(P_l(k)*P_l(p)*G1q_nk*F1p_nk[0]*F2Aq_nk[0] +  P_l(d)*P_l(k)*G1q_nk*F2D_nk[0]*F1kmpq_nk[0]\n                      + P_l(p)*P_l(d)*G2q_nk[0]*F1p_nk[0]*F1kmpq_nk[0]);\n           break;\n     // theta_m \\delta_t \\delta_t [\\delta_t = \\omega_m*(\\delta_m + \\omega_q/\\omega_m*(1+cs^2)*\\delta_q) ]\n        case 7:\n        // theta_m density_m density_m\n  \t\t\t\t terms[0]= norm*(P_l(k)*P_l(p)*G1_nk*F1p_nk[0]*F2A_nk[0] +  P_l(d)*P_l(k)*G1_nk*F2D_nk[0]*F1kmp_nk[0]\n                         + P_l(p)*P_l(d)*G2_nk[0]*F1p_nk[0]*F1kmp_nk[0]);\n\n        // theta_m \\delta_q \\delta_q\n           terms[1]= norm*(P_l(k)*P_l(p)*G1_nk*F1pq_nk[0]*F2Aq_nk[0] +  P_l(d)*P_l(k)*G1_nk*F2Dq_nk[0]*F1kmpq_nk[0]\n                     + P_l(p)*P_l(d)*G2_nk[0]*F1pq_nk[0]*F1kmpq_nk[0]);\n\n        // theta_m \\delta_m \\delta_q\n           terms[2]= norm*(P_l(k)*P_l(p)*G1_nk*F1p_nk[0]*F2Aq_nk[0] +  P_l(d)*P_l(k)*G1_nk*F2D_nk[0]*F1kmpq_nk[0]\n                     + P_l(p)*P_l(d)*G2_nk[0]*F1p_nk[0]*F1kmpq_nk[0]);\n\n          return pow2(omega_m)*(terms[0] + 2.*omega_q/omega_m*(1.+cs2)*terms[2] + pow2(omega_q/omega_m*(1.+cs2))*terms[1]);\n           break;\n\n           // theta_q \\delta_t \\delta_t [\\delta_t = \\omega_m*(\\delta_m + \\omega_q/\\omega_m*(1+cs^2)*\\delta_q) ]\n       case 8:\n          // theta_q density_m density_m\n            terms[0]= norm*(P_l(k)*P_l(p)*G1q_nk*F1p_nk[0]*F2A_nk[0] +  P_l(d)*P_l(k)*G1q_nk*F2D_nk[0]*F1kmp_nk[0]\n                      + P_l(p)*P_l(d)*G2q_nk[0]*F1p_nk[0]*F1kmp_nk[0]);\n\n          // theta_q \\delta_m \\delta_q\n            terms[1]=  norm*(P_l(k)*P_l(p)*G1q_nk*F1p_nk[0]*F2Aq_nk[0] +  P_l(d)*P_l(k)*G1q_nk*F2D_nk[0]*F1kmpq_nk[0]\n                      + P_l(p)*P_l(d)*G2q_nk[0]*F1p_nk[0]*F1kmpq_nk[0]);\n\n          // theta_q \\delta_q \\delta_q\n            terms[2]=  norm*(P_l(k)*P_l(p)*G1q_nk*F1p_nk[0]*F2A_nk[0] +  P_l(d)*P_l(k)*G1q_nk*F2D_nk[0]*F1kmp_nk[0]\n                      + P_l(p)*P_l(d)*G2q_nk[0]*F1p_nk[0]*F1kmp_nk[0]);\n\n            return pow2(omega_m)*(terms[0] + 2.*omega_q/omega_m*(1.+cs2)*terms[2] + pow2(omega_q/omega_m*(1.+cs2))*terms[1]);\n            break;\n        case 9:\n          // d_m d_m d_m\n          return    norm*(P_l(k)*P_l(p)*F1_nk*F1p_nk[0]*F2A_nk[0] +  P_l(d)*P_l(k)*F1_nk*F2D_nk[0]*F1kmp_nk[0]\n                        + P_l(p)*P_l(d)*F2_nk[0]*F1p_nk[0]*F1kmp_nk[0]);\n          break;\n      default:\n            warning(\"SPT: invalid indices, a = %d\\n\", a);\n            return 0;\n    }\n}\n\n// 1-loop resummed spectrum\n\n// Spline linear growth factors and no wiggle spectra\nSpline F1_spline, G1_spline, EHUNWcde, RENWcde;\ndouble ANWcde,sigmav;\n\n\ndouble KMIN_cde = 1e-4;\ndouble KMAX_cde = 50.;\nvoid CDE::F1_init(int a, double scalef, double omega0, double par1, double par2, double par3) const{\n  IOW iow;\n  vector<double> kval_table, F1_table, G1_table;\n  int n3 = 300;\n  for(int i = 0; i<n3; i++){\n  double k = KMIN_cde*exp(i*log(KMAX_cde/(KMIN_cde))/(n3-1.));\n  iow.initn_lin(a, scalef, k, omega0, par1, par2, par3);\n  double ling1=F1_nk;\n  double ling2=G1_nk;\n\n  kval_table.push_back(k);\n  F1_table.push_back(ling1);\n  G1_table.push_back(ling2);\n\n  }\n  F1_spline = LinearSpline(kval_table,F1_table);\n  G1_spline = LinearSpline(kval_table,G1_table);\n}\n\nstatic double ANWcde_integrand(double q, double k){\nreturn pow2(F1_spline(k))*RENWcde(k)*(1.-j0(k*q))*pow2(q);\n}\n\nstatic double nowig_integrand(const PowerSpectrum& P_l, double k, double q){\ndouble lambda = 0.25*pow(k/0.05,0.04);\nreturn P_l(q)/EHUNWcde(q)*exp(-pow2(log(k/q)/lambda)/2.)/q;\n}\n\n\n////////////////\n// FOR RSD ONLY\n\nstatic double cde_exp(const PowerSpectrum& P_l, double q){\n  return  P_l(q)*pow2(F1_spline(q))/(6.*pow2(M_PI));\n}\n\nstatic void sigv_init(const PowerSpectrum& P_l){\n    sigmav = Integrate(bind(cde_exp,cref(P_l), _1), KMIN_cde, KMAX_cde, 1e-3);\n  }\n//////////////\n\n\n// Initialize the NW power spectrum, A^{nw,0l} and sigma_v\n\n// run this before running other kernel initializations (initn or initn_cde)\n// a chooses cde(1) or mg(0)\nvoid CDE::initcde(int a, double scalef, double omega0, double par1, double par2, double par3) const{\nNoWigglePS now(C, 0. , EisensteinHu);\nIOW iow;\n\n// linear spectrum initialization in range [1e-4,50]\nF1_init(a, scalef, omega0, par1, par2, par3);\n\n// sigma_v iinitialization\n//sigv_init(cref(P_l));\n\n// EHUNWcde initialization\nint n3 = 500;\nvector<double> kval_table, ehu_table, now_table;;\nfor(int i = 0; i<n3; i++ ){\ndouble  k = KMIN_cde*exp(i*log(KMAX_cde/KMIN_cde)/(n3-1.));\ndouble  ehups = now.Evaluate(k);\n  kval_table.push_back(k);\n  ehu_table.push_back(ehups);\n    }\n\nEHUNWcde = LinearSpline(kval_table,ehu_table);\n\n// Renormalized linear spectrum and ANWcde initialization\nconst double qmin = 10.;\nconst double qmax = 300.;\ndouble c[2] = {qmin,KMIN_cde};\ndouble d[2] = {qmax,KMAX_cde};\n\nfor(int i = 0; i<n3; i++ ){\n  double k = kval_table[i];\n\n  double lambda = 0.25*pow(k/0.05,0.04);\n  double nowps = EHUNWcde(k)/sqrt(2*M_PI*pow2(lambda))*Integrate<ExpSub>(bind(nowig_integrand,cref(P_l),k,_1),KMIN_cde,KMAX_cde,epsrel);\n  now_table.push_back(nowps);\n    }\n\n  RENWcde = LinearSpline(kval_table,now_table);\n  ANWcde = 1./((pow3(qmax)-pow3(qmin))*pow2(M_PI))*Integrate<2>(bind(ANWcde_integrand,_1,_2),c,d,1e-3,1e-3);\n\n}\n\n\n// NUMERICAL KERNEL RESUMMED 1-LOOP TERMS\n//Integrating over angle - P22 numerical:\nstatic double F2F(int y, int a,  const PowerSpectrum& P_l, double k, double r){\n\tdouble temp_ps;\n\tdouble myresult=0.;\n\tswitch (a) {\n\t\t\tcase 1:\n\t\t\tfor( int i = 0; i < n1; i++ )\n\t\t\t\t{\n        double d = 1+ r*r - 2*r*x128[i];\n\t\t \t\tif(d < 1e-5){\n\t\t\t \ttemp_ps=0.;\n\t\t \t\t}\n\t\t  \telse {\n\t\t  \ttemp_ps = RENWcde(k*sqrt(d)) * pow2(F2_nk[i*n2 + y]);\n\t\t\t\t}\n        myresult += w128[i] * temp_ps;\n\t\t\t\t}\n        return 2. * r * r * myresult;\n        break;\n\t\t\tcase 2:\n      myresult = 0.;\n\t\t\tfor( int i = 0; i < n1; i++ )\n\t\t\t\t{\n        double d = 1+ r*r - 2*r*x128[i];\n\t\t\t\tif(d < 1e-5){\n\t\t\t\ttemp_ps=0.;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\ttemp_ps = RENWcde(k*sqrt(d)) * G2_nk[i*n2 + y]*F2_nk[i*n2 + y];\n\t\t\t\t}\n        myresult += w128[i] * temp_ps;\n\t\t\t\t}\n        return  2. * r * r * myresult;\n        break;\n\t\t\tcase 3:\n\t\t\tfor( int i = 0; i < n1; i++ )\n\t\t\t\t{\n\t\t\t\tdouble d = 1+ r*r - 2*r*x128[i];\n\t\t\t\tif(d < 1e-5){\n\t\t\t\ttemp_ps=0.;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\ttemp_ps = RENWcde(k*sqrt(d)) * pow2(G2_nk[i*n2 + y]);\n\t\t\t\t}\n        myresult += w128[i] * temp_ps;\n\t\t\t\t}\n        return  2. * r * r * myresult;\n        break;\n\t\t\t}\n\t}\n\n  //Integrating over angle -P13 numerical:\n  static double F3F(int y, int a,  const PowerSpectrum& P_l, double k, double r){\n    double myresult = 0.;\n    // Set the limits of angular integrations\n  \tswitch (a) {\n  \t\t\tcase 1:\n  \t\t\t for( int i = 0; i < n1; i++ )\n  \t\t\t\t{\n  \t\t\t\tmyresult += w128[i] * F1_nk * F3_nk[i*n2 + y];\n  \t\t\t\t}\n        return   6. * r * r * myresult;\n        break;\n  \t\t\tcase 2:\n  \t\t\t for( int i = 0; i < n1; i++ )\n  \t\t\t\t{\n  \t\t\t\t\tmyresult += w128[i] * (G1_nk*F3_nk[i*n2 + y] + F1_nk*G3_nk[i*n2 + y]);\n  \t\t\t\t}\n        return   3. * r * r * myresult;\n        break;\n  \t\t\tcase 3:\n  \t\t\t\tfor( int i = 0; i < n1; i++ )\n  \t\t\t\t{\n  \t\t\t\t\tmyresult += w128[i] * G1_nk * G3_nk[i*n2 + y];\n  \t\t\t\t}\n          return    6. * r * r * myresult;\n          break;\n\n  \t\t}\n    }\n\n/*Selection function for numerical kernel magnitude */\n\ninline int num_selec_mag(double kmin, double kmax, double y){\n      double YMIN =QMINp/kmax;\n      double YMAX = QMAXp/kmin;\n    \tint mag_int;\n  //  \tmag_int = (y-YMIN)*(n2*1.-1)/(YMAX-YMIN); // linear\n    //mag_int = sqrt((y-QMINp/kmax)*kmin/QMAXp)*(n2-1); //quadratic\n    mag_int = (int)round((n2-1)*log(y/YMIN)/log(YMAX/YMIN)); //exponential\n    \t\treturn mag_int;\n}\n\n/* P^{(22)} */\n// a = 1 : delta delta\n// a = 2 : delta theta\n// a = 3 : theta theta\ndouble CDE::P22nres(double kmin, double kmax,  int a, double k) const {\n    \tdouble KMAX = QMAXp/k;\n    \tdouble KMIN = QMINp/k;\n      int y1 = num_selec_mag(kmin, kmax, KMIN);\n      int y2 = num_selec_mag(kmin, kmax, KMAX);\n      double y[n2];\n      double integrand[n2];\n      for (int i = y1; i<=y2; i++){\n      y[i] = QMINp/kmax * exp(i*log(QMAXp*kmax/(QMINp*kmin))/(n2*1.-1.)); // exponential sampling\n  //    y[i] = i*1./(n2-1.)*(QMAXp/kmin-QMINp/kmax)+QMINp/kmax; // linear sampling\n      integrand[i] = RENWcde(k*y[i]) * F2F(i, a, cref(P_l), k, y[i]);\n}\ndouble res = 0.;\n  for( int i = y1+1; i <= y2; ++ i ){\nres += 0.5 * (y[i] - y[i-1])*(integrand[i] + integrand[i-1]);\n}\nreturn  k*k*k/(4*M_PI*M_PI)/pow4(dnorm_spt) * res;\n}\n\ndouble CDE::P13nres(double kmin, double kmax,  int a, double k) const {\n  double KMAX = QMAXp/k;\n  double KMIN = QMINp/k;\n  int y1 = num_selec_mag(kmin, kmax, KMIN);\n  int y2 = num_selec_mag(kmin, kmax, KMAX);\n  double y[n2];\n  double integrand[n2];\n  for (int i = y1; i<=y2; i++){\n  y[i] = QMINp/kmax * exp(i*log(QMAXp*kmax/(QMINp*kmin))/(n2*1.-1.));\n//  y[i] = i*1./(n2-1.)*(QMAXp/kmin-QMINp/kmax)+QMINp/kmax; // linear sampling\n  integrand[i] = RENWcde(k*y[i]) * F3F(i, a, cref(P_l), k, y[i]);\n  }\ndouble res = 0.;\n  for( int i = y1+1; i <= y2; ++ i ){\nres += 0.5 * (y[i] - y[i-1])*(integrand[i] + integrand[i-1]);\n}\n  return  k*k*k/(4*M_PI*M_PI)/pow4(dnorm_spt) * RENWcde(k) * res;\n}\n\n\ndouble CDE::PNWloopn(double kmin, double kmax, double k, int a ) const{\n  switch(a) {\n      case 1:\n          return   pow2(F1_spline(k)/dnorm_spt)*RENWcde(k) + P13nres(kmin, kmax, a, k) + P22nres(kmin, kmax, a, k);\n          break;\n      case 2:\n          return  F1_spline(k)*G1_spline(k)/pow2(dnorm_spt)*RENWcde(k) + P13nres(kmin, kmax, a, k) + P22nres(kmin, kmax, a, k);\n          break;\n      case 3:\n          return  pow2(G1_spline(k)/dnorm_spt)*RENWcde(k) + P13nres(kmin, kmax, a, k) + P22nres(kmin, kmax, a, k);\n          break;\n      default:\n          warning(\"CDE: invalid indices, a = %d\\n\", a);\n          return 0;\n  }\n}\n\n/* Resummed 1-loop spectra a la Fonseca */\n\ndouble CDE::Presumn(double kmin, double kmax, double k, int a) const{\n  SPT spt(C,P_l,epsrel);\n  switch(a){\n  case 1:\n   return   PNWloopn(kmin,kmax,k,1) + exp(-0.5*pow2(k)*ANWcde/pow2(dnorm_spt))*(spt.PLOOPn(kmin,kmax,1,k)-PNWloopn(kmin,kmax,k,1) + 0.5*pow2(k)*ANWcde/pow2(dnorm_spt)*pow2(F1_spline(k)/dnorm_spt)*(P_l(k) - RENWcde(k)));\n      break;\n  case 2:\n   return PNWloopn(kmin,kmax,k,2) + exp(-0.5*pow2(k)*ANWcde/pow2(dnorm_spt))*(spt.PLOOPn(kmin,kmax,2,k)-PNWloopn(kmin,kmax,k,2) + 0.5*pow2(k)*ANWcde/pow2(dnorm_spt)*G1_spline(k)*F1_spline(k)/pow2(dnorm_spt)*(P_l(k) - RENWcde(k)));\n      break;\n  case 3:\n      return PNWloopn(kmin,kmax,k,3) + exp(-0.5*pow2(k)*ANWcde/pow2(dnorm_spt))*(spt.PLOOPn(kmin,kmax,3,k)-PNWloopn(kmin,kmax,k,3) + 0.5*pow2(k)*ANWcde/pow2(dnorm_spt)*pow2(G1_spline(k)/dnorm_spt)*(P_l(k) - RENWcde(k)));\n      break;\n  case 4:\n      return pow2(F1_spline(k)/dnorm_spt)*RENWcde(k);\n      //IR CHECK\n  case 5:\n      return P13nres(kmin, kmax, 1, k) + P22nres(kmin, kmax, 1, k) + exp(-0.5*pow2(k)*ANWcde/pow2(dnorm_spt))*(spt.P22n(kmin,kmax,1,k) + spt.P13n(kmin,kmax,1,k) -(P13nres(kmin, kmax, 1, k) + P22nres(kmin, kmax, 1, k)));\n  default:\n          warning(\"CDE: invalid indices, a = %d\\n\", a);\n          return 0;\n}\n}\n", "meta": {"hexsha": "1b821172aa23a193c8de75caec7a8618097a01bd", "size": 13590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reactions/src/extra_libraries/CDE.cpp", "max_stars_repo_name": "PedroCarrilho/ReACT", "max_stars_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-07-07T11:34:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T12:48:05.000Z", "max_issues_repo_path": "reactions/src/extra_libraries/CDE.cpp", "max_issues_repo_name": "PedroCarrilho/ReACT", "max_issues_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_forks_repo_path": "reactions/src/extra_libraries/CDE.cpp", "max_forks_repo_name": "PedroCarrilho/ReACT", "max_forks_repo_head_hexsha": "507866e9462ecf10c298fcd3e2c81249f32e7d50", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-31T15:35:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-31T15:35:28.000Z", "avg_line_length": 33.8902743142, "max_line_length": 230, "alphanum_fraction": 0.5848417954, "num_tokens": 5524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.4421659693226927}}
{"text": "/*\nCopyright (c) 2019 Matthew H. Reilly (kb1vc)\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n    Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n\n    Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in\n    the documentation and/or other materials provided with the\n    distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n#ifndef POINT_HDR_DEF\n#define POINT_HDR_DEF\n#include <string>\n#include <regex>\n#include <cmath>\n#include <boost/format.hpp>\n\n/**\n * \\class GeoProf::Point\n *\n * \\brief Point implements navigation operations on a geographic point\n * on the surface of the earth. The Point object includes methods to \n * calculate the distance and bearing from one point to another, or the\n * location (point) at a given distance and bearing from a starting location.\n *\n * \\author $Author: kb1vc $\n *\n * \\date $Date: 2005/04/14 14:16:20 $\n *\n * Contact: kb1vc@kb1vc.org\n *\n */\nnamespace GeoProf {\n  class Point {\n  public:      \n    /**\n     * @brief Create a point object from latitude, and longitude\n     * \n     * @param _lat the latitude of the point -- negative values are south of the equator\n     * @param _lon the longitude of the point -- negative values are west of Grenwich\n     * \n     * Note that bearings between the poles are unlikely to make sense.\n     * In places where every direction is \"south\" or \"north\" the math\n     * is often beyond sensible limits.  If your application requires\n     * pole-to-pole paths, then look elsewhere, or just point south.\n     */\n    Point(double _lat = 0.0, double _lon = 0.0) {\n      lat = _lat;\n      lon = _lon;\n    }\n\n    /**\n     * @brief Create a point object from another point object\n     *\n     * @param orig the point that we're cloning. \n     */\n    Point(const Point & orig) {\n      lat = orig.lat;\n      lon = orig.lon;\n    }\n\n    /**\n     * @brief Create a point from a Maidenhead Grid specifier\n     * \n     * @param grid A Maidenhead Grid specifier of the form XXnnxx (capital\n     * letter pair, digit pair, letter pair)\n     */\n    Point(const std::string & grid) {\n      grid2Pt(grid);\n    }\n\n\n    /**\n     * @brief Return degrees latitude (negative is south of the equator)\n     * \n     * @return latitude\n     */\n    double getLatitude() const { return lat; }\n\n    /**\n     * @brief Return degrees longitude (negative is west of the Grenwich)\n     * \n     * @return longitude\n     */\n    double getLongitude() const { return lon; }\n\n    \n    /**\n     * @brief Calculate the bearing (in degrees -- 0 is north) from this point to anothe point\n     * along the shorter great circle route\n     *\n     * @param other the other point\n     * @return bearing in degrees.\n     */\n    double bearingTo(const Point & other) const;\n\n    \n    /**\n     * @brief Calculate the great circle distance (in meters) from this point to another point\n     *\n     * @param other the other point\n     * @return great circle distance in meters\n     */\n    double distanceTo(const Point & other) const;\n\n    /**\n     * @brief Calculate the bearing (in degrees -- 0 is north) and distance (in meters) \n     * from this point to another point\n     * along the shorter great circle route\n     *\n     * @param other the other point\n     * @param bearing (output) direction to the other point along the shorter great circle path\n     * @param reverse_bearing direction of travel from other point to this point (in degrees, 0 is north)\n     * @param distance (output) distance in meters to the other point along the shorter great circle path\n     */\n    void bearingDistanceTo(const Point & other, double & bearing, double & reverse_bearing, double & distance) const;\n\n    /**\n     * @brief Return the point at which one would arrive after traveling on the \n     * great circle path from this point at the specified bearing and for the specified distance.\n     *\n     * @param bearing direction of travel (in degrees, 0 is north)\n     * @param distance of travel in meters\n     * @param next (output) the point at which we'll arrive.\n     */\n    void stepTo(double bearing, double distance, Point & next) const;\n\n    /**\n     * @brief convert this point to its Maidenhead Grid specifier\n     * \n     * @param grid (output) The Maidenhead Grid string XXnnxx\n     */\n    void pt2Grid(std::string & grid) const;\n\n    /**\n     * @brief Set this point to the location of a Maidenhead Grid specifier\n     * \n     * @param grid A Maidenhead Grid specifier of the form XXnnxx (capital\n     * letter pair, digit pair, letter pair)\n     */\n    void grid2Pt(const std::string & grid);\n\n    /**\n     * @brief Set this point from a string describing the location in \n     * degrees-minutes-seconds of latitude and logitude. Specification is\n     * in lat degrees/minutes/seconds and lon degrees/minutes/seconds as \n     * doubles.  North/South/East/West \n     * \n     * @param lat_d latitude degrees\n     * @param lat_m latitude minutes\n     * @param lat_s latitude seconds\n     * @param ns true if latitude is north of the equator\n     * @param lon_d longitude degrees\n     * @param lon_m longitude minutes\n     * @param lon_s longitude seconds\n     * @param ew true if latitude is east of Grenwich\n     */\n    void dms2Pt(double lat_d, double lat_m, double lat_s, char ns,\n\t\t double lon_d, double lon_m, double lon_s, char ew);\n\n    /**\n     * @brief Correct the calculated bearing and distance by iterating\n     * around the calculated values to find the minimum error. \n     *\n     * @param other the other point\n     * @param bearing direction to the other point along the shorter great circle path\n     * @param distance distance in meters to the other point along the shorter great circle path\n     * @param new_bearing (output) corrected bearing\n     * @param new_distance (output) corrected range\n     * \n     */\n    void correctBearingDistanceTo(const Point & other, \n\t\t\t\t  const double bearing, \n\t\t\t\t  const double distance, \n\t\t\t\t  double & new_bearing, \n\t\t\t\t  double & new_distance) const;\n\n\n    std::string toString() const {\n      char ns = ' ';\n      if (lat > 0.) {\n\tns = 'N';\n      }\n      if (lat < 0.0) {\n\tns = 'S';\n      }\n\n      char ew = ' ';\n      if (lon > 0.0) {\n\tew = 'E';\n      }\n      if (lon < 0.0) {\n\tew = 'W';\n      }\n      \n      return (boost::format(\"%g %c %g %c\") % lat % ns % lon % ew).str();\n    }\n  private:\n    /// Latitude South is negative, North is positive. \n    double lat;\n    \n    /// Longitude West is negative, East is positive. \n    double lon;\n\n    static std::regex grid_regexp; //  (\"[A-R][A-R][0-9][0-9][A-X][A-X]\", std::regex_constants::icase);      \n    \n    /**\n     * @brief Validate a string as a Maidenhead Grid specifier\n     *\n     * @param grid A Maidenhead Grid specifier of the form XXnnxx (capital\n     * letter pair, digit pair, letter pair)\n     * @return true if this is a properly formatted grid, false otherwise. \n     */\n    bool checkGrid(const std::string & grid) const;\n    \n    /**\n     * @brief Helper for translating char positions in a grid \n     * locator into double offsets from 0 degrees.\n     */\n    double gridDiff(char v, char s, double mul) const;\n\n    /**\n     * @brief four quadrant arc tangent returning result in the range 0..2pi\n     * \n     * @param y rise\n     * @param x run\n     * @return arctan in range 0..2pi\n     */\n    double atan2Pt(double y, double x) const;\n\n    /**\n     * @brief translate an angle into the range 0..2pi\n     * \n     * @param ang angle in radians\n     * @return angle in range 0..2pi\n     */\n    double inSpan(double ang) const;\n\n    // recursive helper to correctBearingDistanceTo\n    bool recCorrectBearingDistanceTo(const Point & other, \n\t\t\t\t     const double bearing, \n\t\t\t\t     const double distance, \n\t\t\t\t     const double b_span,\n\t\t\t\t     const double d_span,\n\t\t\t\t     double & new_bearing, \n\t\t\t\t     double & new_distance\n\t\t\t\t     ) const;\n    \n    // Useful constants\n    static const double clarke_66_al;    /*Clarke 1866 ellipsoid*/\n    static const double clarke_66_bl;\n    static const double rad_per_deg;\n  }; \n\n}\n#endif\n", "meta": {"hexsha": "ded0d518e72c2dbebbda30a795e68284ee6b674b", "size": 8992, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/Point.hxx", "max_stars_repo_name": "kb1vc/GeoProfII", "max_stars_repo_head_hexsha": "d943d5777017af72b56ab8440d399e98b8d54e54", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Point.hxx", "max_issues_repo_name": "kb1vc/GeoProfII", "max_issues_repo_head_hexsha": "d943d5777017af72b56ab8440d399e98b8d54e54", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Point.hxx", "max_forks_repo_name": "kb1vc/GeoProfII", "max_forks_repo_head_hexsha": "d943d5777017af72b56ab8440d399e98b8d54e54", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6981818182, "max_line_length": 117, "alphanum_fraction": 0.6571396797, "num_tokens": 2175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.44199869132595804}}
{"text": "// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// by G. Mazzola, May-Aug 2018\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n#include \"Utils/all_utils.hpp\"\n#include \"Utils/lookup.hpp\"\n\n#ifndef NETKET_JASTROW_HPP\n#define NETKET_JASTROW_HPP\n\nnamespace netket {\n\n/** Jastrow machine class.\n *\n */\ntemplate <typename T>\nclass Jastrow : public AbstractMachine<T> {\n  using VectorType = typename AbstractMachine<T>::VectorType;\n  using MatrixType = typename AbstractMachine<T>::MatrixType;\n  using VectorRefType = typename AbstractMachine<T>::VectorRefType;\n  using VectorConstRefType = typename AbstractMachine<T>::VectorConstRefType;\n  using VisibleConstType = typename AbstractMachine<T>::VisibleConstType;\n\n  const AbstractHilbert &hilbert_;\n\n  // number of visible units\n  int nv_;\n\n  // number of parameters\n  int npar_;\n\n  // weights\n  MatrixType W_;\n\n  // buffers\n  VectorType thetas_;\n  VectorType thetasnew_;\n\n public:\n  using StateType = typename AbstractMachine<T>::StateType;\n  using LookupType = typename AbstractMachine<T>::LookupType;\n\n  // constructor\n  explicit Jastrow(const AbstractHilbert &hilbert)\n      : hilbert_(hilbert), nv_(hilbert.Size()) {\n    Init();\n  }\n\n  void Init() {\n    if (nv_ < 2) {\n      throw InvalidInputError(\n          \"Cannot construct Jastrow states with less than two visible units\");\n    }\n\n    W_.resize(nv_, nv_);\n    W_.setZero();\n\n    npar_ = (nv_ * (nv_ - 1)) / 2;\n\n    thetas_.resize(nv_);\n    thetasnew_.resize(nv_);\n\n    InfoMessage() << \"Jastrow WF Initizialized with nvisible = \" << nv_\n                  << \" and nparams = \" << npar_ << std::endl;\n  }\n\n  int Nvisible() const override { return nv_; }\n\n  int Npar() const override { return npar_; }\n\n  void InitRandomPars(int seed, double sigma) override {\n    VectorType par(npar_);\n\n    netket::RandomGaussian(par, seed, sigma);\n\n    SetParameters(par);\n  }\n\n  VectorType GetParameters() override {\n    VectorType pars(npar_);\n\n    int k = 0;\n\n    for (int i = 0; i < nv_; i++) {\n      for (int j = i + 1; j < nv_; j++) {\n        pars(k) = W_(i, j);\n        k++;\n      }\n    }\n\n    return pars;\n  }\n\n  void SetParameters(VectorConstRefType pars) override {\n    int k = 0;\n\n    for (int i = 0; i < nv_; i++) {\n      W_(i, i) = T(0.);\n      for (int j = i + 1; j < nv_; j++) {\n        W_(i, j) = pars(k);\n        W_(j, i) = W_(i, j);  // create the lower triangle\n        k++;\n      }\n    }\n  }\n\n  void InitLookup(VisibleConstType v, LookupType &lt) override {\n    if (lt.VectorSize() == 0) {\n      lt.AddVector(v.size());\n    }\n    if (lt.V(0).size() != v.size()) {\n      lt.V(0).resize(v.size());\n    }\n\n    lt.V(0) = (W_.transpose() * v);  // does not matter the transpose W is symm\n  }\n\n  // same as for the RBM\n  void UpdateLookup(VisibleConstType v, const std::vector<int> &tochange,\n                    const std::vector<double> &newconf,\n                    LookupType &lt) override {\n    if (tochange.size() != 0) {\n      for (std::size_t s = 0; s < tochange.size(); s++) {\n        const int sf = tochange[s];\n        lt.V(0) += W_.row(sf) * (newconf[s] - v(sf));\n      }\n    }\n  }\n\n  T LogVal(VisibleConstType v) override { return 0.5 * v.dot(W_ * v); }\n\n  // Value of the logarithm of the wave-function\n  // using pre-computed look-up tables for efficiency\n  T LogVal(VisibleConstType v, const LookupType &lt) override {\n    return 0.5 * v.dot(lt.V(0));\n  }\n\n  // Difference between logarithms of values, when one or more visible variables\n  // are being flipped\n  VectorType LogValDiff(\n      VisibleConstType v, const std::vector<std::vector<int>> &tochange,\n      const std::vector<std::vector<double>> &newconf) override {\n    const std::size_t nconn = tochange.size();\n    VectorType logvaldiffs = VectorType::Zero(nconn);\n\n    thetas_ = (W_.transpose() * v);\n    T logtsum = 0.5 * v.dot(thetas_);\n\n    for (std::size_t k = 0; k < nconn; k++) {\n      if (tochange[k].size() != 0) {\n        thetasnew_ = thetas_;\n        Eigen::VectorXd vnew(v);\n\n        for (std::size_t s = 0; s < tochange[k].size(); s++) {\n          const int sf = tochange[k][s];\n\n          thetasnew_ += W_.row(sf) * (newconf[k][s] - v(sf));\n          vnew(sf) = newconf[k][s];\n        }\n\n        logvaldiffs(k) = 0.5 * vnew.dot(thetasnew_) - logtsum;\n      }\n    }\n    return logvaldiffs;\n  }\n\n  T LogValDiff(VisibleConstType v, const std::vector<int> &tochange,\n               const std::vector<double> &newconf,\n               const LookupType &lt) override {\n    T logvaldiff = 0.;\n\n    if (tochange.size() != 0) {\n      T logtsum = 0.5 * v.dot(lt.V(0));\n      thetasnew_ = lt.V(0);\n      Eigen::VectorXd vnew(v);\n\n      for (std::size_t s = 0; s < tochange.size(); s++) {\n        const int sf = tochange[s];\n\n        thetasnew_ += W_.row(sf) * (newconf[s] - v(sf));\n        vnew(sf) = newconf[s];\n      }\n\n      logvaldiff = 0.5 * vnew.dot(thetasnew_) - logtsum;\n    }\n\n    return logvaldiff;\n  }\n\n  VectorType DerLog(VisibleConstType v) override {\n    VectorType der(npar_);\n\n    int k = 0;\n\n    for (int i = 0; i < nv_; i++) {\n      for (int j = i + 1; j < nv_; j++) {\n        der(k) = v(i) * v(j);\n        k++;\n      }\n    }\n\n    return der;\n  }\n\n  const AbstractHilbert &GetHilbert() const noexcept override {\n    return hilbert_;\n  }\n\n  void to_json(json &j) const override {\n    j[\"Name\"] = \"Jastrow\";\n    j[\"Nvisible\"] = nv_;\n    j[\"W\"] = W_;\n  }\n\n  void from_json(const json &pars) override {\n    if (pars.at(\"Name\") != \"Jastrow\") {\n      throw InvalidInputError(\n          \"Error while constructing Jastrow from Json input\");\n    }\n\n    if (FieldExists(pars, \"Nvisible\")) {\n      nv_ = pars[\"Nvisible\"];\n    }\n    if (nv_ != hilbert_.Size()) {\n      throw InvalidInputError(\n          \"Number of visible units is incompatible with given \"\n          \"Hilbert space\");\n    }\n\n    Init();\n\n    if (FieldExists(pars, \"W\")) {\n      W_ = pars[\"W\"];\n    }\n  }\n};\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "e48aa394e124247c4df71a2f56f9c80ff489e95a", "size": 6486, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Machine/jastrow.hpp", "max_stars_repo_name": "GTorlai/netket", "max_stars_repo_head_hexsha": "0c35bfaadeb1253f611f8052b53c9b3d3d9aec9f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NetKet/Machine/jastrow.hpp", "max_issues_repo_name": "GTorlai/netket", "max_issues_repo_head_hexsha": "0c35bfaadeb1253f611f8052b53c9b3d3d9aec9f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetKet/Machine/jastrow.hpp", "max_forks_repo_name": "GTorlai/netket", "max_forks_repo_head_hexsha": "0c35bfaadeb1253f611f8052b53c9b3d3d9aec9f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4352941176, "max_line_length": 80, "alphanum_fraction": 0.5991366019, "num_tokens": 1875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4419986839122783}}
{"text": "// Copyright (c) 2020 Marcus Valtonen Örnhag\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <Eigen/Dense>\n#include <math.h>  // copysign\n\n#include \"radial.hpp\"\n\nnamespace DronePoseLib {\n    Eigen::MatrixXd radialdistort(const Eigen::MatrixXd& x, double kappa) {\n        // We expect inhomogenous input data\n        assert(x.rows() == 2);\n\n        Eigen::ArrayXd ru2 = x.colwise().squaredNorm();\n        Eigen::ArrayXd ru = ru2.sqrt();\n\n        Eigen::ArrayXd rd;\n        // Compute distorted radius\n        if (kappa == 0) {\n            rd = ru;\n        } else {\n            rd = 0.5 / kappa / ru - copysign(1.0, kappa) * (0.25 / std::pow(kappa, 2) / ru2 - 1.0 / kappa).sqrt();\n        }\n\n        // compute distorted coordinates\n        Eigen::MatrixXd y(2, x.cols());\n        y = (rd / ru).replicate(1, x.rows()).transpose() * x.array();\n\n        // TODO(marcusvaltonen): Avoid divion by zero (centre coordinate - usually synthethic images)\n        // y(isnan(y(:))) = 0;\n\n        return y;\n    }\n\n    Eigen::MatrixXd radialundistort(const Eigen::MatrixXd& x, double kappa) {\n        // We expect inhomogenous input data\n        assert(x.rows() == 2);\n\n        Eigen::VectorXd rd2 = x.colwise().squaredNorm();\n\n        // Compute undistorted coordinates\n        Eigen::MatrixXd y(3, x.cols());\n        y.topRows(2) = x;\n        y.bottomRows(1) = (Eigen::VectorXd::Ones(x.cols()) + kappa * rd2).transpose();\n\n        return y.colwise().hnormalized();\n    }\n}  // namespace DronePoseLib\n", "meta": {"hexsha": "df040ac968efca251c3e51753d61843efda8f561", "size": 2525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/helpers/radial.cpp", "max_stars_repo_name": "marcusvaltonen/DronePoseLib", "max_stars_repo_head_hexsha": "0fb7e85accb41eb0d3c6601830b61a2c8be36232", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-03-17T09:35:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T13:41:20.000Z", "max_issues_repo_path": "src/helpers/radial.cpp", "max_issues_repo_name": "marcusvaltonen/DronePoseLib", "max_issues_repo_head_hexsha": "0fb7e85accb41eb0d3c6601830b61a2c8be36232", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-04-23T17:25:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-27T11:21:44.000Z", "max_forks_repo_path": "src/helpers/radial.cpp", "max_forks_repo_name": "marcusvaltonen/DronePoseLib", "max_forks_repo_head_hexsha": "0fb7e85accb41eb0d3c6601830b61a2c8be36232", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-23T17:40:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T19:04:59.000Z", "avg_line_length": 38.2575757576, "max_line_length": 114, "alphanum_fraction": 0.655049505, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4419986764985984}}
{"text": "/**\n * @file \tmain.cpp\n * @author \tFabian Wegscheider\n * @date \tJul 19, 2017\n */\n\n\n#include <iostream>\n#include <boost/program_options.hpp>\n#include <boost/timer/timer.hpp>\n#include <omp.h>\n#include \"GraphParser.h\"\n#include \"PrimeNumbers.h\"\n#include \"SteinerTreeHeuristic.h\"\n\nusing std::string;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing namespace boost;\nnamespace po = boost::program_options;\n\nusing weight_type = double;\n\nusing CSR_Graph = compressed_sparse_row_graph<directedS, no_property,\n\t\tproperty<edge_weight_t, weight_type>>;\n\n\n/**\n * The main function which reads in a graph from a .gph file, considers all\n * vertices with prime indices as terminals and calculates a steiner tree\n * using an improved shortest-path-heuristic based on Dijkstra\n * @param numargs number of inputs on command line\n * @param args array of inputs on command line\n * @return whether the program operated successfully\n */\nint main(int numargs, char* args[]) {\n\n\ttimer::cpu_timer overall_timer;\n\n\n\t// default values for unspecified options\n\tint N_THREADS = 1;\n\tint N_TERMINALS = 100;\n\n\t/* parsing command line options */\n\tstring input;\n\tbool print_tree_selected;\n\n\ttry {\n\t\tpo::options_description desc(\"Allowed options\");\n\t\tdesc.add_options()\n\t\t\t\t(\"help,h\", \"produce help message\")\n\t\t\t\t(\"showtree,s\", \"print tree\")\n\t\t\t\t(\"threads,t\", po::value<int>(&N_THREADS)->default_value(1),\n\t\t\t\t\t\t\"set number of threads\")\n\t\t\t\t(\"terminals,n\", po::value<int>(&N_TERMINALS)->default_value(100),\n\t\t\t\t\t\t\"set number of starting terminals\")\n\t\t\t\t(\"input-file\", po::value<string>(), \"input file\");\n\n\t\tpo::positional_options_description p;\n\t\tp.add(\"input-file\", 1);\n\t\tp.add(\"terminals\", -1);\n\t\tpo::variables_map vm;\n\t\tpo::store(po::command_line_parser(numargs, args).\n\t\t\t\toptions(desc).positional(p).run(), vm);\n\t\tpo::notify(vm);\n\n\t\tif (vm.count(\"help\")) {\n\t\t\tcout << desc << \"\\n\";\n\t\t\texit(EXIT_SUCCESS);\n\t\t}\n\n\t\tif (vm.count(\"input-file\")) {\n\t\t\tinput = vm[\"input-file\"].as< string >();\n\t\t} else {\n\t\t\tcerr << \"Usage: ./ex10 <file.gph> (<number of starting terminals>) \"\n\t\t\t\t\t<< \"(other options)\" << endl;\n\t\t\tcerr << \"run with -h to see information about options\" << endl;\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tprint_tree_selected = vm.count(\"showtree\");\n\n\t} catch (...) {\n\t\tcerr << \"Usage: ./ex10 <file.gph> (<number of starting terminals>) \"\n\t\t\t\t<< \"(other options)\" << endl;\n\t\tcerr << \"run with -h to see information about options\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\t/* end of parsing command line options */\n\n\n\t/* parsing .gph file */\n\tint num_vertices;\n\tint num_edges;\n\n\tGraphParser parser(input);\n\tif (!parser.opened_successfully) {\n\t\tcerr << \"file could not be read\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t// first line is read to get number of vertices and edges\n\tif (!parser.read_first_line(num_vertices, num_edges)) {\n\t\tcerr << \"error while reading file, not the right format\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t// we use arrays for edges and weights so that we can use a boost graph\n\tEdge* edges = new Edge[num_edges];\n\tweight_type* weights = new double[num_edges];\n\n\t// rest of the file is read and parsed to a graph\n\tif (!parser.read_edge_data(edges, weights)) {\n\t\tcerr << \"error while reading file, not the right format\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\t/* end of file parsing */\n\n\n\t/* initialization and computing */\n\n\t// here the graph is constructed using a CSR graph from boost\n\tconst CSR_Graph g(boost::edges_are_unsorted, &edges[0], &edges[0] + num_edges,\n\t\t\tweights, num_vertices);\n\n\t// all primes in {2,...,num_vertices} are considered to be terminals\n\tvector<int> terminals = PrimeNumbers::find_primes(num_vertices);\n\n\ttimer::cpu_timer algo_timer;\n\n\tconst int iterations = std::min((int) terminals.size(), N_TERMINALS);\n\n\t// The tree is implicitly stored by remembering the predecessor of each\n\t// vertex, a -1 means that the vertex is not in the tree\n\tvector<int> best_tree(num_vertices);\n\n\tweight_type min_value = std::numeric_limits<weight_type>::infinity();\n\tint min_root = -1;\n\n\t// heuristic is called for the specified number of terminals and the best\n\t// solution is kept. It is done in parallel if more than one thread is chosen\n\t#pragma omp parallel for schedule(dynamic) num_threads(N_THREADS)\n\tfor (int i = 0; i < iterations; ++i) {\n\n\t\tvector<int> tree(num_vertices, -1);\n\t\tweight_type objective_value = SteinerTreeHeuristic::compute_steiner_tree(g,\n\t\t\tnum_vertices, terminals[i], tree, terminals);\n\n\t\t#pragma omp critical\n\t\tif (objective_value < min_value) {\n\n\t\t\tmin_value = objective_value;\n\t\t\tmin_root = i;\n\t\t\tbest_tree = tree;\n\t\t}\n\t}\n\n\tstring algo_time = algo_timer.format(3, \"%w\");\n\t/* end of computation */\n\n\n\tassert(SteinerTreeHeuristic::test_tree(g, num_vertices, terminals[min_root],\n\t\t\tbest_tree, terminals));\n\n\t// output is printed, with tree if option was chosen\n\tcout << \"TLEN: \" << min_value << endl;\n\tif (print_tree_selected) {\n\t\tstring edge_string = SteinerTreeHeuristic::print_tree(g,\n\t\t\t\tnum_vertices, terminals[min_root], best_tree, terminals);\n\t\tcout << \"TREE: \" << edge_string << endl;\n\t}\n\tcout << \"TIME: \" << overall_timer.format(3, \"%t\") << endl;\n\tcout << \"WALL: \" << algo_time << endl;\n\n\tdelete[] edges;\n\tdelete[] weights;\n\n\texit(EXIT_SUCCESS);\n}\n\n\n\n\n", "meta": {"hexsha": "7927741f2d714ac98af853ef4ff37d6a952b0f63", "size": 5177, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wegscheider/ex10/ex10.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Wegscheider/ex10/ex10.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Wegscheider/ex10/ex10.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 27.8333333333, "max_line_length": 79, "alphanum_fraction": 0.693258644, "num_tokens": 1333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.44190906985450384}}
{"text": "#ifndef STAN_MATH_TORSTEN_LINODE_HPP\n#define STAN_MATH_TORSTEN_LINODE_HPP\n\n#include <Eigen/Dense>\n#include <stan/math/torsten/ev_manager.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/torsten/ev_solver.hpp>\n#include <stan/math/torsten/to_array_2d.hpp>\n#include <stan/math/torsten/pmx_linode_model.hpp>\n#include <stan/math/torsten/pmx_check.hpp>\n#include <stan/math/prim/err/check_square.hpp>\n#include <vector>\n\nnamespace torsten {\n\n  namespace {\n    template<typename T>\n    using torsten_matrix_dyn_t = Eigen::Matrix<T,-1,-1>;    \n  }\n\n/**\n * Computes the predicted amounts in each compartment at each event\n * for a compartment model, described by a linear system of ordinary\n * differential equations. Uses the stan::math::matrix_exp \n * function.\n *\n * @tparam T0 type of scalar for time of events. \n * @tparam T1 type of scalar for amount at each event.\n * @tparam T2 type of scalar for rate at each event.\n * @tparam T3 type of scalar for inter-dose inteveral at each event.\n * @tparam T4 type of scalar for matrix describing linear ODE system.\n * @tparam T5 type of scalars for bio-variability parameters.\n * @tparam T6 type of scalars for tlag parameters \n * @param[in] time times of events  \n * @param[in] amt amount at each event\n * @param[in] rate rate at each event\n * @param[in] ii inter-dose interval at each event\n * @param[in] evid event identity: \n *                    (0) observation \n *                    (1) dosing\n *                    (2) other\n *                    (3) reset\n *                    (4) reset AND dosing\n * @param[in] cmt compartment number at each event \n * @param[in] addl additional dosing at each event \n * @param[in] ss steady state approximation at each event (0: no, 1: yes)\n * between time-points\n * @param[in] system square matrix describing the linear system of ODEs\n * @param[in] bio-variability at each event\n * @param[in] lag times at each event\n * @return a matrix with predicted amount in each compartment \n * at each event.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3,\n          typename T4, typename T5, typename T6>\nstan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\npmx_solve_linode(const std::vector<T0>& time,\n                 const std::vector<T1>& amt,\n                 const std::vector<T2>& rate,\n                 const std::vector<T3>& ii,\n                 const std::vector<int>& evid,\n                 const std::vector<int>& cmt,\n                 const std::vector<int>& addl,\n                 const std::vector<int>& ss,\n                 const std::vector< Eigen::Matrix<T4, -1, -1> >& system,\n                 const std::vector<std::vector<T5> >& biovar,\n                 const std::vector<std::vector<T6> >& tlag) {\n  using std::vector;\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using boost::math::tools::promote_args;\n\n  static const char* function(\"pmx_solve_linode\");\n  for (size_t i = 0; i < system.size(); i++)\n    stan::math::check_square(function, \"system matrix\", system[i]);\n  int nCmt = system[0].cols();\n\n  using ER = NONMENEventsRecord<T0, T1, T2, T3>;\n  using EM = EventsManager<ER, NonEventParameters<T0, T4, torsten_matrix_dyn_t, std::tuple<T5, T6> >>;\n  const ER events_rec(nCmt, time, amt, rate, ii, evid, cmt, addl, ss);\n\n  Matrix<typename EM::T_scalar, Dynamic, Dynamic> pred =\n    Matrix<typename EM::T_scalar, Dynamic, Dynamic>::Zero(events_rec.num_event_times(), EM::nCmt(events_rec));\n\n  using model_type = torsten::PMXLinODEModel<typename EM::T_par>;\n  EventSolver<model_type, EM> pr;\n  pr.pred(0, events_rec, pred, dsolve::PMXAnalyiticalIntegrator(), system, biovar, tlag, nCmt);\n  return pred;\n}\n\n/**\n * Overload function to allow user to pass a matrix for \n * system.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3,\n          typename T4, typename T_biovar, typename T_tlag>\nstan::matrix_return_t<T0, T1, T2, T3, T4, T_biovar, T_tlag>\npmx_solve_linode(const std::vector<T0>& time,\n                 const std::vector<T1>& amt,\n                 const std::vector<T2>& rate,\n                 const std::vector<T3>& ii,\n                 const std::vector<int>& evid,\n                 const std::vector<int>& cmt,\n                 const std::vector<int>& addl,\n                 const std::vector<int>& ss,\n                 const Eigen::Matrix<T4, -1, -1>& system,\n                 const std::vector<T_biovar>& biovar,\n                 const std::vector<T_tlag>& tlag) {\n  std::vector<Eigen::Matrix<T4, -1, -1> > system_{system};\n  auto biovar_ = torsten::to_array_2d(biovar);\n  auto tlag_ = torsten::to_array_2d(tlag);\n\n  return pmx_solve_linode(time, amt, rate, ii, evid, cmt, addl, ss,\n                          system_, biovar_, tlag_);\n}\n\n/**\n * Overload function to allow user to pass a matrix for \n * system.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3,\n          typename T4, typename T_biovar, typename T_tlag,\n          typename = require_any_not_std_vector_t<T_biovar, T_tlag> >\nstan::matrix_return_t<T0, T1, T2, T3, T4, T_biovar, T_tlag>\npmx_solve_linode(const std::vector<T0>& time,\n                 const std::vector<T1>& amt,\n                 const std::vector<T2>& rate,\n                 const std::vector<T3>& ii,\n                 const std::vector<int>& evid,\n                 const std::vector<int>& cmt,\n                 const std::vector<int>& addl,\n                 const std::vector<int>& ss,\n                 const std::vector< Eigen::Matrix<T4, -1, -1> >& system,\n                 const std::vector<T_biovar>& biovar,\n                 const std::vector<T_tlag>& tlag) {\n  auto biovar_ = torsten::to_array_2d(biovar);\n  auto tlag_ = torsten::to_array_2d(tlag);\n\n  return pmx_solve_linode(time, amt, rate, ii, evid, cmt, addl, ss,\n                          system, biovar_, tlag_);\n}\n\n  // old version by using transpose\ntemplate <typename T0, typename T1, typename T2, typename T3,\n          typename T4, typename T5, typename T6>\nstan::matrix_return_t<T0, T1, T2, T3, T4, T5, T6>\nlinOdeModel(const std::vector<T0>& time,\n            const std::vector<T1>& amt,\n            const std::vector<T2>& rate,\n            const std::vector<T3>& ii,\n            const std::vector<int>& evid,\n            const std::vector<int>& cmt,\n            const std::vector<int>& addl,\n            const std::vector<int>& ss,\n            const std::vector< Eigen::Matrix<T4, Eigen::Dynamic, Eigen::Dynamic> >& system,\n            const std::vector<std::vector<T5> >& biovar,\n            const std::vector<std::vector<T6> >& tlag) {\n  auto x = pmx_solve_linode(time, amt, rate, ii, evid, cmt, addl, ss, system, biovar, tlag);\n  return x.transpose();\n}\n\ntemplate <typename T0, typename T1, typename T2, typename T3,\n          typename T4, typename T_biovar, typename T_tlag>\nstan::matrix_return_t<T0, T1, T2, T3, T4, T_biovar, T_tlag>\nlinOdeModel(const std::vector<T0>& time,\n                 const std::vector<T1>& amt,\n                 const std::vector<T2>& rate,\n                 const std::vector<T3>& ii,\n                 const std::vector<int>& evid,\n                 const std::vector<int>& cmt,\n                 const std::vector<int>& addl,\n                 const std::vector<int>& ss,\n                 const Eigen::Matrix<T4, -1, -1>& system,\n                 const std::vector<T_biovar>& biovar,\n                 const std::vector<T_tlag>& tlag) {\n  auto x = pmx_solve_linode(time, amt, rate, ii, evid, cmt, addl, ss, system, biovar, tlag);\n  return x.transpose();\n}\n\n  template <typename T0, typename T1, typename T2, typename T3,\n            typename T4, typename T_biovar, typename T_tlag,\n            typename = require_any_not_std_vector_t<T_biovar, T_tlag> >\n  stan::matrix_return_t<T0, T1, T2, T3, T4, T_biovar, T_tlag>\n  linOdeModel(const std::vector<T0>& time,\n              const std::vector<T1>& amt,\n              const std::vector<T2>& rate,\n              const std::vector<T3>& ii,\n              const std::vector<int>& evid,\n              const std::vector<int>& cmt,\n              const std::vector<int>& addl,\n              const std::vector<int>& ss,\n              const std::vector< Eigen::Matrix<T4, -1, -1> >& system,\n              const std::vector<T_biovar>& biovar,\n              const std::vector<T_tlag>& tlag) {\n    auto x = pmx_solve_linode(time, amt, rate, ii, evid, cmt, addl, ss,\n                            system, biovar, tlag);\n    return x.transpose();\n  }\n\n}\n#endif\n", "meta": {"hexsha": "420bbf19c48fece5f1dca05ce489a459760fe317", "size": 8396, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pmx_solve_linode.hpp", "max_stars_repo_name": "metrumresearchgroup/torsten_math", "max_stars_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pmx_solve_linode.hpp", "max_issues_repo_name": "metrumresearchgroup/torsten_math", "max_issues_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-27T23:53:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T23:57:43.000Z", "max_forks_repo_path": "pmx_solve_linode.hpp", "max_forks_repo_name": "metrumresearchgroup/torsten_math", "max_forks_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5643564356, "max_line_length": 110, "alphanum_fraction": 0.6106479276, "num_tokens": 2292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893340314393, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.44190875318303485}}
{"text": "#ifndef qlex_svi_interpolation_hpp\n#define qlex_svi_interpolation_hpp\n\n#include <ql/utilities/null.hpp>\n#include <ql/utilities/dataformatters.hpp>\n#include <ql/math/interpolation.hpp>\n#include <ql/math/optimization/method.hpp>\n#include <ql/math/optimization/simplex.hpp>\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/math/optimization/projectedcostfunction.hpp>\n#include <ql/math/optimization/constraint.hpp>\n#include <ql/math/randomnumbers/haltonrsg.hpp>\n\n#include <termstructures/volatility/svi.hpp>\n\n#include <boost/make_shared.hpp>\n#include <boost/assign/list_of.hpp>\n\nusing namespace QuantLib;\n\nnamespace QLExtension {\n\nnamespace detail {\n\tclass SVICoeffHolder {\n\tpublic:\n\t\tSVICoeffHolder(const Time t, const Real &forward, std::vector<Real> params)\n\t\t\t: t_(t), forward_(forward), params_(params),\n\t\t\tweights_(std::vector<Real>()), error_(Null<Real>()),\n\t\t\tmaxError_(Null<Real>()), SVIEndCriteria_(EndCriteria::None) {\n\t\t\tQL_REQUIRE(t > 0.0, \"expiry time must be positive: \" << t\n\t\t\t\t<< \" not allowed\");\n\t\t}\n\t\tvirtual ~SVICoeffHolder() {}\n\n\t\t/*! Expiry, Forward */\n\t\tReal t_;\n\t\tconst Real forward_;\n\t\t/*! Parameters */\n\t\tstd::vector<Real> params_;\n\t\tstd::vector<Real> weights_;\n\t\t/*! Interpolation results */\n\t\tReal error_, maxError_;\n\t\tEndCriteria::Type SVIEndCriteria_;\n\t};\n\n\ttemplate <class I1, class I2>\n\tclass SVIInterpolationImpl : public Interpolation::templateImpl<I1, I2>,\n\t\t\t\t\t\t\t\t public SVICoeffHolder\n\t{\n\tpublic:\n\t\tSVIInterpolationImpl(\n\t\t\tconst I1 &xBegin, const I1 &xEnd, const I2 &yBegin, Time t,\n\t\t\tconst Real &forward, std::vector<Real> params, bool vegaWeighted,\n\t\t\tconst boost::shared_ptr<EndCriteria> &endCriteria,\n\t\t\tconst boost::shared_ptr<OptimizationMethod> &optMethod,\n\t\t\tconst Real errorAccept, const bool useMaxError, const Size maxGuesses)\n\t\t\t: Interpolation::templateImpl<I1, I2>(xBegin, xEnd, yBegin),\n\t\t\tSVICoeffHolder(t, forward, params),\n\t\t\tendCriteria_(endCriteria), optMethod_(optMethod),\n\t\t\terrorAccept_(errorAccept), useMaxError_(useMaxError),\n\t\t\tmaxGuesses_(maxGuesses),  vegaWeighted_(vegaWeighted) {\n\t\t\t\t// if no optimization method or endCriteria is provided, we provide one\n\t\t\t\tif (!optMethod_)\n\t\t\t\t\toptMethod_ = boost::shared_ptr<OptimizationMethod>(\n\t\t\t\t\tnew LevenbergMarquardt(1e-8, 1e-8, 1e-8));\n\t\t\t\t// optMethod_ = boost::shared_ptr<OptimizationMethod>(new\n\t\t\t\t//    Simplex(0.01));\n\t\t\t\tif (!endCriteria_) {\n\t\t\t\t\tendCriteria_ = boost::shared_ptr<EndCriteria>(\n\t\t\t\t\t\tnew EndCriteria(60000, 100, 1e-8, 1e-8, 1e-8));\n\t\t\t\t}\n\t\t\t\t// equal weighted\n\t\t\t\tthis->weights_ = std::vector<Real>(xEnd - xBegin, 1.0 / (xEnd - xBegin));\n\t\t\t\tcompleted_ = false;\n\t\t\t}\n\n\t\t// Optimization\n\t\tvoid update() {\n\t\t\t// we must update weights if it is vegaWeighted\n\t\t\tif (vegaWeighted_) {\n\t\t\t\t// std::vector<Real>::const_iterator x = this->xBegin_;\n\t\t\t\t// std::vector<Real>::const_iterator y = this->yBegin_;\n\t\t\t\t// std::vector<Real>::iterator w = weights_.begin();\n\t\t\t\tthis->weights_.clear();\n\t\t\t\tReal weightsSum = 0.0;\n\t\t\t\tfor (Size i = 0; i<Size(this->xEnd_ - this->xBegin_); ++i) {\n\t\t\t\t\tReal stdDev = std::sqrt((this->yBegin_[i]) * (this->yBegin_[i]) * this->t_);\n\t\t\t\t\tthis->weights_.push_back(\n\t\t\t\t\t\tblackFormulaStdDevDerivative(this->xBegin_[i], forward_, stdDev));\n\t\t\t\t\tweightsSum += this->weights_.back();\n\t\t\t\t}\n\t\t\t\t// weight normalization\n\t\t\t\tstd::vector<Real>::iterator w = this->weights_.begin();\n\t\t\t\tfor (; w != this->weights_.end(); ++w)\n\t\t\t\t\t*w /= weightsSum;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tSVIError costFunction(this);\n\t\t\t\tConstraint constraint = SVIConstraint();\n\n\t\t\t\tArray guess(params_.size());\n\t\t\t\tfor (Size i = 0; i < params_.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tguess[i] = this->params_[i];\n\t\t\t\t}\n\t\t\t\tSize iterations = 0;\n\t\t\t\tReal tmpInterpolationError;\n\t\t\t\tEndCriteria::Type tmpEndCriteria;\n\t\t\t\tdo {\n\t\t\t\t\tProblem problem(costFunction, constraint, guess);\n\t\t\t\t\ttmpEndCriteria = optMethod_->minimize(problem, *endCriteria_);\n\t\t\t\t\tguess = problem.currentValue();\n\t\t\t\t\ttmpInterpolationError = useMaxError_ ? interpolationMaxError()\n\t\t\t\t\t\t: interpolationError();\n\n\t\t\t\t\tswitch (tmpEndCriteria) {\n\t\t\t\t\tcase EndCriteria::None:\n\t\t\t\t\tcase EndCriteria::MaxIterations:\n\t\t\t\t\tcase EndCriteria::Unknown:\n\t\t\t\t\t\tcompleted_ = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tcompleted_ = true;\n\t\t\t\t\t}\n\t\t\t\t} while (++iterations < maxGuesses_ &&\n\t\t\t\t\ttmpInterpolationError > errorAccept_);\n\n\t\t\t\tfor (Size i = 0; i < guess.size(); ++i)\n\t\t\t\t\tthis->params_[i] = guess[i];\n\n\t\t\t\tthis->error_ = interpolationError();\n\t\t\t\tthis->maxError_ = interpolationMaxError();\n\t\t\t}\n\t\t\tcatch (const std::exception& e)\n\t\t\t{\n\t\t\t\tQL_FAIL(\"error in SVI calibration: \" << e.what());\n\t\t\t}\n\t\t}\n\n\t\tReal value(Real x) const {\n\t\t\tQL_REQUIRE(x > 0.0, \"strike must be positive: \" << io::rate(x)\n\t\t\t\t<< \" not allowed\");\n\t\t\treturn sviVolatility(x, forward_, t_, params_[0], params_[1], params_[2], params_[3], params_[4]);\n\t\t}\n\n\t\tReal primitive(Real) const { QL_FAIL(\"SVI primitive not implemented\"); }\n\t\tReal derivative(Real) const { QL_FAIL(\"SVI derivative not implemented\"); }\n\t\tReal secondDerivative(Real) const {\n\t\t\tQL_FAIL(\"SVI secondDerivative not implemented\");\n\t\t}\n\n\t\t// calculate total squared weighted difference (L2 norm)\n\t\tReal interpolationSquaredError() const {\n\t\t\tReal error, totalError = 0.0;\n\t\t\t//std::vector<Real>::const_iterator x = this->xBegin_;\n\t\t\t//std::vector<Real>::const_iterator y = this->yBegin_;\n\t\t\t// std::vector<Real>::const_iterator w = this->weights_.begin();\n\t\t\tfor (Size i = 0; i<Size(this->xEnd_ - this->xBegin_); ++i) {\n\t\t\t\terror = (value(this->xBegin_[i]) - this->yBegin_[i]);\n\t\t\t\ttotalError += error * error * (this->weights_[i]);\n\t\t\t}\n\t\t\treturn totalError;\n\t\t}\n\n\t\t// calculate weighted differences\n\t\tDisposable<Array> interpolationErrors(const Array &) const {\n\t\t\tArray results(Size(this->xEnd_ - this->xBegin_));\n\t\t\t//std::vector<Real>::const_iterator x = this->xBegin_; \n\t\t\t//std::vector<Real>::const_iterator y = this->yBegin_;\n\t\t\t//std::vector<Real>::const_iterator w = this->weights_.begin();\n\t\t\tArray::iterator r = results.begin();\n\t\t\tfor (Size i = 0; i < Size(this->xEnd_ - this->xBegin_); i++)\n\t\t\t{\n\t\t\t\t*r = (value(this->xBegin_[i]) - this->yBegin_[i]) * std::sqrt(this->weights_[i]);\n\t\t\t}\n\t\t\treturn results;\n\t\t}\n\n\t\tReal interpolationError() const {\n\t\t\tSize n = this->xEnd_ - this->xBegin_;\n\t\t\tReal squaredError = interpolationSquaredError();\n\t\t\treturn std::sqrt(n * squaredError / (n - 1));\n\t\t}\n\n\t\tReal interpolationMaxError() const {\n\t\t\tReal error, maxError = QL_MIN_REAL;\n\t\t\tI1 i = this->xBegin_;\n\t\t\tI2 j = this->yBegin_;\n\t\t\tfor (; i != this->xEnd_; ++i, ++j) {\n\t\t\t\terror = std::fabs(value(*i) - *j);\n\t\t\t\tmaxError = std::max(maxError, error);\n\t\t\t}\n\t\t\treturn maxError;\n\t\t}\n\tpublic:\n\t\tboost::shared_ptr<EndCriteria> endCriteria_;\n\t\tboost::shared_ptr<OptimizationMethod> optMethod_;\n\t\tconst Real errorAccept_;\n\t\tconst bool useMaxError_;\n\t\tconst Size maxGuesses_;\n\t\tbool vegaWeighted_;\n\t\tbool completed_;\n\t\tNoConstraint constraint_;\n\n\tprivate:\n\t\tclass SVIError : public CostFunction {\n\t\tpublic:\n\t\t\tSVIError(SVIInterpolationImpl *svi) : svi_(svi) {}\n\n\t\t\t// calculate total squared weighted difference\n\t\t\tReal value(const Array &x) const {\n\t\t\t\tfor (Size i = 0; i < svi_->params_.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tsvi_->params_[i] = x[i];\n\t\t\t\t}\n\n\t\t\t\treturn svi_->interpolationSquaredError();\n\t\t\t}\n\n\t\t\tDisposable<Array> values(const Array &x) const {\n\t\t\t\tfor (Size i = 0; i < svi_->params_.size(); i++)\n\t\t\t\t{\n\t\t\t\t\tsvi_->params_[i] = x[i];\n\t\t\t\t}\n\n\t\t\t\treturn svi_->interpolationErrors(x);\n\t\t\t}\n\n\t\tprivate:\n\t\t\tSVIInterpolationImpl *svi_;\n\t\t};\n\n\t\tclass SVIConstraint : public Constraint {\n\t\tprivate:\n\t\t\tclass Impl : public Constraint::Impl {\n\t\t\tpublic:\n\t\t\t\tbool test(const Array& params) const {\n\t\t\t\t\tif (params[1] < 0)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tif (std::fabs(params[2]) >= 1)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\tif (params[4] <= 0)\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t//if (params[0] + params[1] * params[4] * std::sqrt(1-params[2]*params[2]) < 0)\n\t\t\t\t\t//\treturn false;\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t};\n\t\tpublic:\n\t\t\tSVIConstraint()\n\t\t\t\t: Constraint(boost::shared_ptr<Constraint::Impl>(\n\t\t\t\tnew SVIConstraint::Impl)) {}\n\t\t};\n\t};\n}\t// end of namespace detail\n\n\t//! %SVI smile interpolation between discrete volatility points.\n\tclass SVIInterpolation : public Interpolation {\n\tpublic:\n\t\ttemplate <class I1, class I2>\n\t\tSVIInterpolation(const I1 &xBegin,  // x = strikes\n\t\t\tconst I1 &xEnd,\n\t\t\tconst I2 &yBegin,  // y = volatilities\n\t\t\tTime t,            // option expiry\n\t\t\tconst Real& forward,\n\t\t\tReal a,\n\t\t\tReal b,\n\t\t\tReal rho,\n\t\t\tReal m,\n\t\t\tReal sigma,\n\t\t\tbool vegaWeighted = true,\n\t\t\tconst boost::shared_ptr<EndCriteria>& endCriteria\n\t\t\t= boost::shared_ptr<EndCriteria>(),\n\t\t\tconst boost::shared_ptr<OptimizationMethod>& optMethod\n\t\t\t= boost::shared_ptr<OptimizationMethod>(),\n\t\t\tconst Real errorAccept = 0.0020,\n\t\t\tconst bool useMaxError = false,\n\t\t\tconst Size maxGuesses = 1) {\n\n\t\t\timpl_ = boost::shared_ptr<Interpolation::Impl>(\n\t\t\t\tnew detail::SVIInterpolationImpl<I1, I2>(\n\t\t\t\txBegin, xEnd, yBegin, t, forward,\n\t\t\t\tboost::assign::list_of(a)(b)(rho)(m)(sigma),\n\t\t\t\tvegaWeighted, endCriteria, optMethod, errorAccept, useMaxError,\n\t\t\t\tmaxGuesses));\n\t\t\tcoeffs_ = boost::dynamic_pointer_cast<\n\t\t\t\tdetail::SVICoeffHolder >(impl_);\n\t\t}\n\t\tReal expiry()  const { return coeffs_->t_; }\n\t\tReal forward() const { return coeffs_->forward_; }\n\t\tReal a()   const { return coeffs_->params_[0]; }\n\t\tReal b()    const { return coeffs_->params_[1]; }\n\t\tReal rho()      const { return coeffs_->params_[2]; }\n\t\tReal m()     const { return coeffs_->params_[3]; }\n\t\tReal sigma()     const { return coeffs_->params_[4]; }\n\t\tReal rmsError() const { return coeffs_->error_; }\n\t\tReal maxError() const { return coeffs_->maxError_; }\n\t\tconst std::vector<Real>& interpolationWeights() const {\n\t\t\treturn coeffs_->weights_;\n\t\t}\n\t\tEndCriteria::Type endCriteria() { return coeffs_->SVIEndCriteria_; }\n\n\tprivate:\n\t\tboost::shared_ptr<detail::SVICoeffHolder> coeffs_;\n\t};\n}\t// end of namespace QLExtension\n\n#endif\n", "meta": {"hexsha": "6e80a18b989515778e3aad2728eaa81e7fd4046a", "size": 9914, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CppCoreLibrary/QLExtension/math/interpolations/sviinterpolation.hpp", "max_stars_repo_name": "qg0/EliteQuant_Excel", "max_stars_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-21T23:06:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T17:29:10.000Z", "max_issues_repo_path": "CppCoreLibrary/QLExtension/math/interpolations/sviinterpolation.hpp", "max_issues_repo_name": "qg0/EliteQuant_Excel", "max_issues_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CppCoreLibrary/QLExtension/math/interpolations/sviinterpolation.hpp", "max_forks_repo_name": "qg0/EliteQuant_Excel", "max_forks_repo_head_hexsha": "987bb670e8be0e60525dde656d5a315e9a6ac718", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T13:45:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T11:13:12.000Z", "avg_line_length": 31.7756410256, "max_line_length": 101, "alphanum_fraction": 0.6652208997, "num_tokens": 2895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.44190875081104697}}
{"text": "/*\r\n * hd.cpp\r\n *\r\n * Author: P. Wild (pwild@cosy.sbg.ac.at)\r\n *\r\n * Calculates hamming distance of iris codes\r\n *\r\n */\r\n#include \"version.h\"\r\n#include <cstdio>\r\n#include <map>\r\n#include <vector>\r\n#include <string>\r\n#include <cstring>\r\n#include <algorithm>\r\n#include <fstream>\r\n#include <opencv2/core/core.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <boost/regex.hpp>\r\n#include <boost/filesystem.hpp>\r\n#include <boost/date_time/posix_time/posix_time.hpp>\r\n\r\nusing namespace std;\r\nusing namespace cv;\r\n\r\n/** no globbing in win32 mode **/\r\nint _CRT_glob = 0;\r\n\r\n/** Algorithms **/\r\nstatic const int ALG_MINHD = 0, ALG_MAXHD = 1, ALG_SSF = 2;\r\n/** Program modes **/\r\nstatic const int MODE_MAIN = 1, MODE_HELP = 2;\r\n\r\nstatic const int htlut[256] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8};\r\n\r\n/*\r\n * Print command line usage for this program\r\n */\r\nvoid printUsage() {\r\n    printVersion();\r\n\tprintf(\"+-----------------------------------------------------------------------------+\\n\");\r\n\tprintf(\"| hd - calculates hamming distance of iris codes                              |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| MODES                                                                       |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| (# 1) HD calculation of the input images (cross comparison)                 |\\n\");\r\n\tprintf(\"| (# 2) usage                                                                 |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| ARGUMENTS                                                                   |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n\tprintf(\"| Name | Parameters | # | ? | Description                                     |\\n\");\r\n\tprintf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n\tprintf(\"| -i   | infile1    | 1 | N | source/reference iris codes (use * as wildcard, |\\n\");\r\n\tprintf(\"|      | infile2    |   |   | all other files may refer to n-th * with ?n)    |\\n\");\r\n\tprintf(\"| -s   | param+     | 1 | Y | min max: min/max (0 0) number of bit shifts     |\\n\");\r\n\tprintf(\"|      |            |   | Y | img: shifted src (?n = n-th * in infile1,* =any)|\\n\");\r\n    printf(\"| -ss  | shiftstep  |   | Y | Number of grouped bits to shift for one step of |\\n\");\r\n    printf(\"|      |            |   |   | -s shift.                                       |\\n\");\r\n\tprintf(\"| -m   | maskfile1  | 1 | Y | source/reference iris masks (?n/!n = n-th * in  |\\n\");\r\n\tprintf(\"|      | maskfile2  |   |   | infile1/img, ?n = n-th * in infile2)            |\\n\");\r\n\tprintf(\"| -a   | algorithm  | 1 | Y | HD-based algorithm (minhd)                      |\\n\");\r\n\tprintf(\"|      |            |   |   | minhd: minimum HD for all shifts                |\\n\");\r\n\tprintf(\"|      |            |   |   | maxhd: 1-maximum HD for all shifts              |\\n\");\r\n\tprintf(\"|      |            |   |   | ssf: shift score fusion                         |\\n\");\r\n\tprintf(\"| -n   | from to    | 1 | Y | starting (0) and ending bit (MAX)               |\\n\");\r\n\tprintf(\"| -o   | outfile    | 1 | Y | target text                                     |\\n\");\r\n\tprintf(\"| -owp |            | 1 | Y | write full paths in outfile instead of file only|\\n\");\r\n\tprintf(\"| -q   |            | 1 | Y | quiet mode on (off)                             |\\n\");\r\n\tprintf(\"| -t   |            | 1 | Y | time progress on (off)                          |\\n\");\r\n\tprintf(\"| -#   |            | 1 | N | use memoization if memory is not a concern.     |\\n\");\r\n\tprintf(\"| -b   |            | 1 | N | also record the bit shift at which the HD occurs|\\n\");\r\n\tprintf(\"| -h   |            | 2 | N | prints usage                                    |\\n\");\r\n\tprintf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| EXAMPLE USAGE                                                               |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| -i s1.png s2.png -m s1_mask.png s2_mask.png -o compare.txt                  |\\n\");\r\n    printf(\"| -i *.png *.png -s -7 7 -o compare.txt -q -t                                 |\\n\");\r\n    printf(\"| -i *.png *.png -a ssf -s ?1_shifted_*.png -7 7 -o compare.txt -q -t         |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n\tprintf(\"| AUTHOR                                                                      |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| Peter Wild (pwild@cosy.sbg.ac.at)                                           |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| COPYRIGHT                                                                   |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| (C) 2012 All rights reserved. Do not distribute without written permission. |\\n\");\r\n\tprintf(\"+-----------------------------------------------------------------------------+\\n\");\r\n}\r\n\r\n/**\r\n * Fast hamming distance estimation\r\n * a: sample iris code\r\n * b: reference iris code\r\n * start8: starting 8-bit block\r\n * stop8: ending 8-bit block\r\n */\r\nunsigned int hd(const Mat a, const Mat b, const unsigned int start8, const unsigned int stop8, const Mat mask = Mat()){\r\n\tunsigned int dist = 0;\r\n\tMatConstIterator_<uchar> pa = a.begin<uchar>();\r\n\tMatConstIterator_<uchar> pb = b.begin<uchar>();\r\n\tMatConstIterator_<uchar> enda = pa + stop8;\r\n\tpa += start8;\r\n\tpb += start8;\r\n\tif (!mask.empty()){\r\n\t\tMatConstIterator_<uchar> pm = mask.begin<uchar>();\r\n\t\t//unsigned int * pm = (unsigned int*) mask.data;\r\n\t\tpm += start8;\r\n\t\tfor (;pa<enda; pa++, pb++, pm++){\r\n\t\t\tdist += htlut[(*pa ^*pb) & *pm];\r\n\r\n\t\t\t/*unsigned int val = (*pa ^*pb) & *pm;\r\n\t\t\twhile(val)\r\n\t\t\t{\r\n\t\t\t\t++dist;\r\n\t\t\t\tval &= val - 1;\r\n\t\t\t}*/\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tfor (;pa<enda; pa++, pb++){\r\n\t\t\t//unsigned int val = *pa ^*pb;\r\n\t\t\tdist += htlut[*pa ^*pb];\r\n\t\t\t/*\r\n\t\t\twhile(val)\r\n\t\t\t{\r\n\t\t\t\t++dist;\r\n\t\t\t\tval &= val - 1;\r\n\t\t\t}*/\r\n\t\t}\r\n\t}\r\n\treturn dist;\r\n\r\n}\r\n\r\n/**\r\n * Shifts source by a given shift count\r\n * src: source iris code\r\n * dst: destination (shifted) iris code\r\n * shifts: shift count (positive values indicate left shifts)\r\n */\r\nvoid shift(const Mat src, Mat dst, const int shifts){\r\n\tint size = src.cols*src.rows; // size in bytes\r\n\tMatConstIterator_<uchar> psrc = src.begin<uchar>();\r\n\tMatConstIterator_<uchar> endsrc = src.end<uchar>();\r\n\tMatIterator_<uchar> pdst = dst.begin<uchar>();\r\n\tMatIterator_<uchar> enddst = dst.end<uchar>();\r\n\r\n\tif (shifts >= 0){ // left shift\r\n\t\tunsigned int offset = shifts / 8;\r\n\t\tpsrc += offset;\r\n\t\tunsigned int shiftCount = shifts % 8;\r\n\t\tunsigned int ishiftCount = 8 - shiftCount;\r\n\t\tfor (;pdst<enddst; pdst++){\r\n\t\t\t*pdst = (*psrc << shiftCount);\r\n\t\t\tpsrc++;\r\n\t\t\tif (psrc == endsrc) psrc = src.begin<uchar>();\r\n\t\t\t*pdst |= (*psrc >> (ishiftCount));\r\n\t\t}\r\n\t}\r\n\telse { // right shift\r\n\t\tunsigned int offset = (-shifts) / 8;\r\n\t\toffset = (size-offset-1) % size;\r\n\t\tpsrc += offset;\r\n\t\tunsigned int shiftCount = (-shifts) % 8;\r\n\t\tunsigned int ishiftCount = 8 - shiftCount;\r\n\t\tfor (;pdst<enddst; pdst++){\r\n\t\t\t*pdst = (*psrc << ishiftCount);\r\n\t\t\tpsrc++;\r\n\t\t\tif (psrc == endsrc) psrc = src.begin<uchar>();\r\n\t\t\t*pdst |= (*psrc >> (shiftCount));\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Shifts matrix a by a given shift count and intersects result with b\r\n * a: sample source iris mask\r\n * b: reference source iris mask\r\n * dst: destination (shifted) iris mask\r\n * shifts: shift count (positive values indicate left shifts)\r\n */\r\nvoid intersectShifted(const Mat a, const Mat b, Mat dst, const int shifts){\r\n\tuchar * pb = b.data;\r\n\tuchar * pa = a.data;\r\n\tuchar * pdst = dst.data;\r\n\tunsigned int size = dst.cols;\r\n\tunsigned int offset;\r\n\tif (shifts >= 0){ // left shift\r\n\t\toffset = shifts / 8;\r\n\t\tuchar * enddst = pdst + dst.cols;\r\n\t\tunsigned int shiftCount = shifts % 8;\r\n\t\tunsigned int ishiftCount = 8 - shiftCount;\r\n\t\toffset = (size + offset) % size;\r\n\t\tfor (;pdst<enddst; pdst++, pb++){\r\n\t\t\t*pdst = (pa[offset] << shiftCount);\r\n\t\t\toffset = ((offset+1)%size);\r\n\t\t\t*pdst |= (pa[offset] >> (ishiftCount));\r\n\t\t\t*pdst &= *pb;\r\n\t\t}\r\n\t}\r\n\telse { // right shift\r\n\t\toffset = (-shifts) / 8;\r\n\t\tuchar * enddst = pdst + dst.cols;\r\n\t\tunsigned int shiftCount = (-shifts) % 8;\r\n\t\tunsigned int ishiftCount = 8 - shiftCount;\r\n\t\toffset = (size-offset-1) % size;\r\n\t\tfor (;pdst<enddst; pdst++, pb++){\r\n\t\t\t*pdst = (pa[offset] << ishiftCount);\r\n\t\t\toffset = ((offset+1)%size);\r\n\t\t\t*pdst |= (pa[offset] >> (shiftCount));\r\n\t\t\t*pdst &= *pb;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * determines the best fractional Hamming Distance of two iris codes\r\n * a: first iris code\r\n * b: second iris code\r\n * start8: starting 8-bit block (inclusive)\r\n * stop8: ending 8-bit block (exclusive)\r\n * shifts: number of shifts\r\n * aMask: mask for first iris code\r\n * bMask: mask for second iris code\r\n */\r\nstd::pair<double,int> minHD(const Mat& a, const Mat& b, const unsigned int start8, const unsigned int stop8, const int minShifts, const int maxShifts,const int shiftStep, const Mat aMask, const Mat bMask = Mat()){\r\n    std::pair<double, int> result = {1,0};\r\n\tif (!aMask.empty() && !bMask.empty()){\r\n\t\tMat mask(b.rows,b.cols,CV_8UC1);\r\n\t\tMat zero(b.rows,b.cols,CV_8UC1);\r\n\t\tzero.setTo(Scalar(0));\r\n\t\tdouble hamdist = 1;\r\n\t\tMat imgSmplShifted(a.rows,a.cols,CV_8UC1);\r\n\t\tfor (int ss=minShifts; ss<=maxShifts; ss++){\r\n            int s = ss*shiftStep;\r\n\t\t\tshift(a,imgSmplShifted,s);\r\n\t\t\tintersectShifted(aMask,bMask,mask,s);\r\n\t\t\tint codeLengthBits = hd(mask, zero, start8, stop8);\r\n\t\t\tdouble shiftedHamdist = (codeLengthBits == 0) ? 0 : ((double)hd(imgSmplShifted,b,start8,stop8,mask)) / codeLengthBits;\r\n\t\t\tif (shiftedHamdist < hamdist){\r\n                hamdist = shiftedHamdist;\r\n                result.second = ss;\r\n            }\r\n\t\t}\r\n\t\tresult.first = hamdist;\r\n\t}\r\n\telse {\r\n\t\tint codeLengthBits = 8*(stop8-start8);\r\n\t\tunsigned int hamdist = codeLengthBits;\r\n\t\tMat imgSmplShifted(a.rows,a.cols,CV_8UC1);\r\n\t\tfor (int ss=minShifts; ss<=maxShifts; ss++){\r\n            int s = ss*shiftStep;\r\n\t\t\tshift(a,imgSmplShifted,s);\r\n\t\t\tunsigned int shiftedHamdist = hd(imgSmplShifted,b,start8,stop8);\r\n\t\t\tif (shiftedHamdist < hamdist){\r\n                hamdist = shiftedHamdist;\r\n                result.second = ss;\r\n            }\r\n\t\t}\r\n\t\tresult.first = (((double)hamdist) / (codeLengthBits));\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n/**\r\n * determines the best fractional Hamming Distance of an iris code with a list of shifted versions of this code\r\n * a: shifted versions of first iris code\r\n * b: second iris code\r\n * start8: starting 8-bit block (inclusive)\r\n * stop8: ending 8-bit block (exclusive)\r\n * aMask: masks for corresponding shifted versions of first iris code\r\n * bMask: mask for second iris code\r\n */\r\nstd::pair<double, int> minHD(const vector<Mat>& a, const Mat& b, const unsigned int start8, const unsigned int stop8, const vector<Mat>& aMask, const Mat bMask = Mat()){\r\n    std::pair<double, int> result = {1,0};\r\n\tif (!aMask.empty() && !bMask.empty()){\r\n\t\tCV_Assert(aMask.size() == a.size());\r\n\t\tMat mask(b.rows,b.cols,CV_8UC1);\r\n\t\tMat zero(b.rows,b.cols,CV_8UC1);\r\n\t\tzero.setTo(Scalar(0));\r\n\t\tdouble hamdist = 1;\r\n\t\tfor (unsigned int i=0; i<a.size();i++){\r\n\t\t\tintersectShifted(aMask[i],bMask,mask,0);\r\n\t\t\tint codeLengthBits = hd(mask, zero, start8, stop8);\r\n\t\t\tdouble shiftedHamdist = (codeLengthBits == 0) ? 0 : ((double)hd(a[i],b,start8,stop8,mask)) / codeLengthBits;\r\n\t\t\tif (shiftedHamdist < hamdist){\r\n                hamdist = shiftedHamdist;\r\n                result.second = i;\r\n            }\r\n\t\t}\r\n\t\tresult.first = hamdist;\r\n\t} else {\r\n\t\tint codeLengthBits = 8*(stop8-start8);\r\n\t\tunsigned int hamdist = codeLengthBits;\r\n\t\tfor (unsigned int i=0; i<a.size();i++){\r\n\t\t\tunsigned int shiftedHamdist = hd(a[i],b,start8,stop8);\r\n\t\t\tif (shiftedHamdist < hamdist){\r\n                hamdist = shiftedHamdist;\r\n                result.second = i;\r\n            }\r\n\t\t}\r\n\t\tresult.first = (((double)hamdist) / (codeLengthBits));\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n/**\r\n * determines the worst fractional Hamming Distance of two iris codes\r\n * a: first iris code\r\n * b: second iris code\r\n * start8: starting 8-bit block (inclusive)\r\n * stop8: ending 8-bit block (exclusive)\r\n * shifts: number of shifts\r\n * aMask: mask for first iris code\r\n * bMask: mask for second iris code\r\n */\r\nstd::pair<double, int> maxHD(const Mat& a, const Mat& b, const unsigned int start8, const unsigned int stop8, const int minShifts, const int maxShifts, const int shiftStep, const Mat aMask, const Mat bMask = Mat()){\r\n    std::pair<double, int> result = {0,0};\r\n\tif (!aMask.empty() && !bMask.empty()){\r\n\t\tMat mask(b.rows,b.cols,CV_8UC1);\r\n\t\tMat zero(b.rows,b.cols,CV_8UC1);\r\n\t\tzero.setTo(Scalar(0));\r\n\t\tdouble hamdist = 0;\r\n\t\tMat imgSmplShifted(a.rows,a.cols,CV_8UC1);\r\n\t\tfor (int ss=minShifts; ss<=maxShifts; ss++){\r\n            int s = ss*shiftStep;\r\n\t\t\tshift(a,imgSmplShifted,s);\r\n\t\t\tintersectShifted(aMask,bMask,mask,s);\r\n\t\t\tint codeLengthBits = hd(mask, zero, start8, stop8);\r\n\t\t\tdouble shiftedHamdist = (codeLengthBits == 0) ? 0 : ((double)hd(imgSmplShifted,b,start8,stop8,mask)) / codeLengthBits;\r\n\t\t\tif (shiftedHamdist > hamdist){\r\n                hamdist = shiftedHamdist;\r\n                result.second = ss;\r\n            }\r\n\t\t}\r\n\t\tresult.first = 1 - hamdist;\r\n\t}\r\n\telse {\r\n\r\n\t\tint codeLengthBits = 8*(stop8-start8);\r\n\t\tunsigned int hamdist = 0;\r\n\t\tMat imgSmplShifted(a.rows,a.cols,CV_8UC1);\r\n\t\tfor (int ss=minShifts; ss<=maxShifts; ss++){\r\n            int s = ss*shiftStep;\r\n\t\t\tshift(a,imgSmplShifted,s);\r\n\t\t\tunsigned int shiftedHamdist = hd(imgSmplShifted,b,start8,stop8);\r\n\t\t\tif (shiftedHamdist > hamdist){\r\n                hamdist = shiftedHamdist;\r\n                result.second = ss;\r\n            }\r\n\t\t}\r\n\t\tresult.first = 1-(((double)hamdist) / (codeLengthBits));\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n/**\r\n * determines the worst fractional Hamming Distance of an iris code with a list of shifted versions of this code\r\n * a: shifted versions of first iris code\r\n * b: second iris code\r\n * start8: starting 8-bit block (inclusive)\r\n * stop8: ending 8-bit block (exclusive)\r\n * aMask: masks for corresponding shifted versions of first iris code\r\n * bMask: mask for second iris code\r\n */\r\nstd::pair<double, int> maxHD(const vector<Mat>& a, const Mat& b, const unsigned int start8, const unsigned int stop8, const vector<Mat>& aMask, const Mat bMask = Mat()){\r\n\tstd::pair<double,int>  result = {1,0};\r\n\tif (!aMask.empty() && !bMask.empty()){\r\n\t\tCV_Assert(aMask.size() == a.size());\r\n\t\tMat mask(b.rows,b.cols,CV_8UC1);\r\n\t\tMat zero(b.rows,b.cols,CV_8UC1);\r\n\t\tzero.setTo(Scalar(0));\r\n\t\tdouble hamdist = 0;\r\n\t\tfor (unsigned int i=0; i<a.size();i++){\r\n\t\t\tintersectShifted(aMask[i],bMask,mask,0);\r\n\t\t\tint codeLengthBits = hd(mask, zero, start8, stop8);\r\n\t\t\tdouble shiftedHamdist = (codeLengthBits == 0) ? 0 : ((double)hd(a[i],b,start8,stop8,mask)) / codeLengthBits;\r\n\t\t\tif (shiftedHamdist > hamdist){\r\n                hamdist = shiftedHamdist;\r\n                result.second = i;\r\n            }\r\n\t\t}\r\n\t\tresult.first = 1 - hamdist;\r\n\t}\r\n\telse {\r\n\t\tint codeLengthBits = 8*(stop8-start8);\r\n\t\tunsigned int hamdist = 0;\r\n\t\tfor (unsigned int i=0; i<a.size();i++){\r\n\t\t\tunsigned int shiftedHamdist = hd(a[i],b,start8,stop8);\r\n\t\t\tif (shiftedHamdist > hamdist){\r\n                hamdist = shiftedHamdist;\r\n                result.second = i;\r\n            }\r\n\t\t}\r\n\t\tresult.first = 1- (((double)hamdist) / (codeLengthBits));\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n/**\r\n * determines Shifting Score Fusion of two iris codes\r\n * a: first iris code\r\n * b: second iris code\r\n * start8: starting 8-bit block (inclusive)\r\n * stop8: ending 8-bit block (exclusive)\r\n * shifts: number of shifts\r\n * aMask: mask for first iris code\r\n * bMask: mask for second iris code\r\n */\r\nstd::pair<double,int>  ssf(const Mat& a, const Mat& b, const unsigned int start8, const unsigned int stop8, const int minShifts, const int maxShifts, const int shiftStep, const Mat aMask, const Mat bMask = Mat()){\r\n\tstd::pair<double,int>  result = {0,666};\r\n\tif (!aMask.empty() && !bMask.empty()){\r\n\t\tMat mask(b.rows,b.cols,CV_8UC1);\r\n\t\tMat zero(b.rows,b.cols,CV_8UC1);\r\n\t\tzero.setTo(Scalar(0));\r\n\t\tintersectShifted(aMask,bMask,mask,0);\r\n\t\tdouble hamdist = 1;\r\n\t\tdouble maxhamdist = 0;\r\n\t\tMat imgSmplShifted(a.rows,a.cols,CV_8UC1);\r\n\t\tfor (int ss=minShifts; ss<=maxShifts; ss++){\r\n            int s = ss*shiftStep;\r\n\t\t\tshift(a,imgSmplShifted,s);\r\n\t\t\tintersectShifted(aMask,bMask,mask,s);\r\n\t\t\tint codeLengthBits = hd(mask, zero, start8, stop8);\r\n\t\t\tdouble shiftedHamdist = (codeLengthBits == 0) ? 0 : ((double)hd(imgSmplShifted,b,start8,stop8,mask)) / codeLengthBits;\r\n\t\t\tif (shiftedHamdist < hamdist){\r\n                hamdist = shiftedHamdist;\r\n                result.second = ss;\r\n            }\r\n\t\t\tif (shiftedHamdist > maxhamdist) maxhamdist = shiftedHamdist;\r\n\t\t}\r\n\t\tresult.first = ((1-maxhamdist) +  hamdist)/2;\r\n\t}\r\n\telse {\r\n\t\tint codeLengthBits = 8*(stop8-start8);\r\n\t\tunsigned int hamdist = codeLengthBits;\r\n\t\tunsigned int maxhamdist = 0;\r\n\t\tMat imgSmplShifted(a.rows,a.cols,CV_8UC1);\r\n\t\tfor (int ss=minShifts; ss<=maxShifts; ss++){\r\n            int s = ss*shiftStep;\r\n\t\t\tshift(a,imgSmplShifted,s);\r\n\t\t\tunsigned int shiftedHamdist = hd(imgSmplShifted,b,start8,stop8);\r\n\t\t\tif (shiftedHamdist < hamdist){\r\n                hamdist = shiftedHamdist;\r\n                result.second = ss;\r\n            }\r\n\t\t\tif (shiftedHamdist > maxhamdist) maxhamdist = shiftedHamdist;\r\n\t\t}\r\n\t\tresult.first = ((1-(((double)maxhamdist) / (codeLengthBits))) + (((double)hamdist) / (codeLengthBits)))/2;\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n/**\r\n * determines Shifting Score Fusion of an iris code with a list of shifted versions of this code\r\n * a: shifted versions of first iris code\r\n * b: second iris code\r\n * start8: starting 8-bit block (inclusive)\r\n * stop8: ending 8-bit block (exclusive)\r\n * aMask: masks for corresponding shifted versions of first iris code\r\n * bMask: mask for second iris code\r\n */\r\nstd::pair<double,int>  ssf(const vector<Mat>& a, const Mat& b, const unsigned int start8, const unsigned int stop8, const vector<Mat>& aMask, const Mat bMask = Mat()){\r\n\tstd::pair<double,int>  result = {0,0};\r\n\tif (!aMask.empty() && !bMask.empty()){\r\n\t\tCV_Assert(aMask.size() == a.size());\r\n\t\tMat mask(b.rows,b.cols,CV_8UC1);\r\n\t\tMat zero(b.rows,b.cols,CV_8UC1);\r\n\t\tzero.setTo(Scalar(0));\r\n\t\tint codeLengthBits = 0;\r\n\t\tdouble hamdist = 1;\r\n\t\tdouble maxhamdist = 0;\r\n\t\tfor (unsigned int i=0; i<a.size();i++){\r\n\t\t\tintersectShifted(aMask[i],bMask,mask,0);\r\n\t\t\tcodeLengthBits = hd(mask, zero, start8, stop8);\r\n\t\t\tdouble shiftedHamdist = (codeLengthBits == 0) ? 0 : ((double)hd(a[i],b,start8,stop8,mask)) / codeLengthBits;\r\n\t\t\tif (shiftedHamdist < hamdist){\r\n                hamdist = shiftedHamdist;\r\n                result.second = i;\r\n            }\r\n\t\t\tif (shiftedHamdist > maxhamdist) maxhamdist = shiftedHamdist;\r\n\t\t}\r\n\t\tresult.first = ((1-maxhamdist) +  hamdist)/2;\r\n\t}\r\n\telse {\r\n\t\tint codeLengthBits = 8*(stop8-start8);\r\n\t\tunsigned int hamdist = codeLengthBits;\r\n\t\tunsigned int maxhamdist = 0;\r\n\t\tfor (unsigned int i=0; i<a.size();i++){\r\n\t\t\tunsigned int shiftedHamdist = hd(a[i],b,start8,stop8);\r\n\t\t\tif (shiftedHamdist < hamdist){\r\n                hamdist = shiftedHamdist;\r\n                result.second = i;\r\n            }\r\n\t\t\tif (shiftedHamdist > maxhamdist) maxhamdist = shiftedHamdist;\r\n\t\t}\r\n\t\tresult.first = ((1-(((double)maxhamdist) / (codeLengthBits))) + (((double)hamdist) / (codeLengthBits)))/2;\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n/** ------------------------------- commandline functions ------------------------------- **/\r\n\r\n/**\r\n * Parses a command line\r\n * This routine should be called for parsing command lines for executables.\r\n * Note, that all options require '-' as prefix and may contain an arbitrary\r\n * number of optional arguments.\r\n *\r\n * cmd: commandline representation\r\n * argc: number of parameters\r\n * argv: string array of argument values\r\n */\r\nvoid cmdRead(map<string ,vector<string> >& cmd, int argc, char *argv[]){\r\n\tfor (int i=1; i< argc; i++){\r\n\t\tchar * argument = argv[i];\r\n\t\tif (strlen(argument) > 1 && argument[0] == '-' && (argument[1] < '0' || argument[1] > '9')){\r\n\t\t\tcmd[argument]; // insert\r\n\t\t\tchar * argument2;\r\n\t\t\twhile (i + 1 < argc && (strlen(argument2 = argv[i+1]) <= 1 || argument2[0] != '-'  || (argument2[1] >= '0' && argument2[1] <= '9'))){\r\n\t\t\t\tcmd[argument].push_back(argument2);\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tCV_Error(CV_StsBadArg,\"Invalid command line format\");\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Checks, if each command line option is valid, i.e. exists in the options array\r\n *\r\n * cmd: commandline representation\r\n * validOptions: list of valid options separated by pipe (i.e. |) character\r\n */\r\nvoid cmdCheckOpts(map<string ,vector<string> >& cmd, const string validOptions){\r\n\tvector<string> tokens;\r\n\tconst string delimiters = \"|\";\r\n\tstring::size_type lastPos = validOptions.find_first_not_of(delimiters,0); // skip delimiters at beginning\r\n\tstring::size_type pos = validOptions.find_first_of(delimiters, lastPos); // find first non-delimiter\r\n\twhile (string::npos != pos || string::npos != lastPos){\r\n\t\ttokens.push_back(validOptions.substr(lastPos,pos - lastPos)); // add found token to vector\r\n\t\tlastPos = validOptions.find_first_not_of(delimiters,pos); // skip delimiters\r\n\t\tpos = validOptions.find_first_of(delimiters,lastPos); // find next non-delimiter\r\n\t}\r\n\tsort(tokens.begin(), tokens.end());\r\n\tfor (map<string, vector<string> >::iterator it = cmd.begin(); it != cmd.end(); it++){\r\n\t\tif (!binary_search(tokens.begin(),tokens.end(),it->first)){\r\n\t\t\tCV_Error(CV_StsBadArg,\"Command line parameter '\" + it->first + \"' not allowed.\");\r\n\t\t\ttokens.clear();\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\ttokens.clear();\r\n}\r\n\r\n/*\r\n * Checks, if a specific required option exists in the command line\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n */\r\nvoid cmdCheckOptExists(map<string ,vector<string> >& cmd, const string option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it == cmd.end()) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' is required, but does not exist.\");\r\n}\r\n\r\n/*\r\n * Checks, if a specific option has the appropriate number of parameters\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n * size: appropriate number of parameters for the option\r\n */\r\nvoid cmdCheckOptSize(map<string ,vector<string> >& cmd, const string option, const unsigned int size = 1){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it->second.size() != size) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' has unexpected size.\");\r\n}\r\n\r\n/*\r\n * Checks, if a specific option has the appropriate number of parameters\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n * min: minimum appropriate number of parameters for the option\r\n * max: maximum appropriate number of parameters for the option\r\n */\r\nvoid cmdCheckOptRange(map<string ,vector<string> >& cmd, string option, unsigned int min = 0, unsigned int max = 1){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tunsigned int size = it->second.size();\r\n\tif (size < min || size > max) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' is out of range.\");\r\n}\r\n\r\n/*\r\n * Returns the list of parameters for a given option\r\n *\r\n * cmd: commandline representation\r\n * option: name of the option\r\n */\r\nvector<string> * cmdGetOpt(map<string ,vector<string> >& cmd, const string option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\treturn (it != cmd.end()) ? &(it->second) : 0;\r\n}\r\n\r\n/*\r\n * Returns number of parameters in an option\r\n *\r\n * cmd: commandline representation\r\n * option: name of the option\r\n */\r\nunsigned int cmdSizePars(map<string ,vector<string> >& cmd, const string option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\treturn (it != cmd.end()) ? it->second.size() : 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (int) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nint cmdGetParInt(map<string ,vector<string> >& cmd, string option, unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn atoi(it->second[param].c_str());\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (float) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nfloat cmdGetParFloat(map<string ,vector<string> >& cmd, const string option, const unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn atof(it->second[param].c_str());\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (string) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nstring cmdGetPar(map<string ,vector<string> >& cmd, const string option, const unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn it->second[param];\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/** ------------------------------- timing functions ------------------------------- **/\r\n\r\n/**\r\n * Class for handling timing progress information\r\n */\r\nclass Timing{\r\npublic:\r\n\t/** integer indicating progress with respect tot total **/\r\n\tint progress;\r\n\t/** total count for progress **/\r\n\tint total;\r\n\r\n\t/*\r\n\t * Default constructor for timing initializing time.\r\n\t * Automatically calls init()\r\n\t *\r\n\t * seconds: update interval in seconds\r\n\t * eraseMode: if true, outputs sends erase characters at each print command\r\n\t */\r\n\tTiming(long seconds, bool eraseMode){\r\n\t\tupdateInterval = seconds;\r\n\t\tprogress = 1;\r\n\t\ttotal = 100;\r\n\t\teraseCount=0;\r\n\t\terase = eraseMode;\r\n\t\tinit();\r\n\t}\r\n\r\n\t/*\r\n\t * Destructor\r\n\t */\r\n\t~Timing(){}\r\n\r\n\t/*\r\n\t * Initializes timing variables\r\n\t */\r\n\tvoid init(void){\r\n\t\tstart = boost::posix_time::microsec_clock::universal_time();\r\n\t\tlastPrint = start - boost::posix_time::seconds(updateInterval);\r\n\t}\r\n\r\n\t/*\r\n\t * Clears printing (for erase option only)\r\n\t */\r\n\tvoid clear(void){\r\n\t\tstring erase(eraseCount,'\\r');\r\n\t\terase.append(eraseCount,' ');\r\n\t\terase.append(eraseCount,'\\r');\r\n\t\tprintf(\"%s\",erase.c_str());\r\n\t\teraseCount = 0;\r\n\t}\r\n\r\n\t/*\r\n\t * Updates current time and returns true, if output should be printed\r\n\t */\r\n\tbool update(void){\r\n\t\tcurrent = boost::posix_time::microsec_clock::universal_time();\r\n\t\treturn ((current - lastPrint > boost::posix_time::seconds(updateInterval)) || (progress == total));\r\n\t}\r\n\r\n\t/*\r\n\t * Prints timing object to STDOUT\r\n\t */\r\n\tvoid print(void){\r\n\t\tlastPrint = current;\r\n\t\tfloat percent = 100.f * progress / total;\r\n\t\tboost::posix_time::time_duration passed = (current - start);\r\n\t\tboost::posix_time::time_duration togo = passed * (total - progress) / max(1,progress);\r\n\t\tif (erase) {\r\n\t\t\tstring erase(eraseCount,'\\r');\r\n\t\t\tprintf(\"%s\",erase.c_str());\r\n\t\t\tint newEraseCount = (progress != total) ? printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03i Remaining ca. %i:%02i:%02i.%03i)\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000),togo.hours(),togo.minutes(),togo.seconds(),(int)(togo.total_milliseconds() % 1000)) : printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03d)\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000));\r\n\t\t\tif (newEraseCount < eraseCount) {\r\n\t\t\t\tstring erase(newEraseCount-eraseCount,' ');\r\n\t\t\t\terase.append(newEraseCount-eraseCount,'\\r');\r\n\t\t\t\tprintf(\"%s\",erase.c_str());\r\n\t\t\t}\r\n\t\t\teraseCount = newEraseCount;\r\n\t\t}\r\n\t\telse {\r\n\t\t\teraseCount = (progress != total) ? printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03i Remaining ca. %i:%02i:%02i.%03i)\\n\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000),togo.hours(),togo.minutes(),togo.seconds(),(int)(togo.total_milliseconds() % 1000)) : printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03d)\\n\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000));\r\n\t\t}\r\n\t}\r\nprivate:\r\n\tlong updateInterval;\r\n\tboost::posix_time::ptime start;\r\n\tboost::posix_time::ptime current;\r\n\tboost::posix_time::ptime lastPrint;\r\n\tint eraseCount;\r\n\tbool erase;\r\n};\r\n\r\n/** ------------------------------- file pattern matching functions ------------------------------- **/\r\n\r\n\r\n/*\r\n * Formats a given string, such that it can be used as a regular expression\r\n * I.e. escapes special characters and uses * and ? as wildcards\r\n *\r\n * pattern: regular expression path pattern\r\n * pos: substring starting index\r\n * n: substring size\r\n *\r\n * returning: escaped substring\r\n */\r\nstring patternSubstrRegex(string& pattern, size_t pos, size_t n){\r\n\tstring result;\r\n\tfor (size_t i=pos, e=pos+n; i < e; i++ ) {\r\n\t\tchar c = pattern[i];\r\n\t\tif ( c == '\\\\' || c == '.' || c == '+' || c == '[' || c == '{' || c == '|' || c == '(' || c == ')' || c == '^' || c == '$' || c == '}' || c == ']') {\r\n\t\t\tresult.append(1,'\\\\');\r\n\t\t\tresult.append(1,c);\r\n\t\t}\r\n\t\telse if (c == '*'){\r\n\t\t\tresult.append(\"([^/\\\\\\\\]*)\");\r\n\t\t}\r\n\t\telse if (c == '?'){\r\n\t\t\tresult.append(\"([^/\\\\\\\\])\");\r\n\t\t}\r\n\t\telse {\r\n\t\t\tresult.append(1,c);\r\n\t\t}\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n/*\r\n * Converts a regular expression path pattern into a list of files matching with this pattern by replacing wildcards\r\n * starting in position pos assuming that all prior wildcards have been resolved yielding intermediate directory path.\r\n * I.e. this function appends the files in the specified path according to yet unresolved pattern by recursive calling.\r\n *\r\n * pattern: regular expression path pattern\r\n * files: the list to which new files can be applied\r\n * pos: an index such that positions 0...pos-1 of pattern are already considered/matched yielding path\r\n * path: the current directory (or empty)\r\n */\r\nvoid patternToFiles(string& pattern, vector<string>& files, const size_t& pos, const string& path){\r\n\tsize_t first_unknown = pattern.find_first_of(\"*?\",pos); // find unknown * in pattern\r\n\tif (first_unknown != string::npos){\r\n\t\tsize_t last_dirpath = pattern.find_last_of(\"/\\\\\",first_unknown);\r\n\t\tsize_t next_dirpath = pattern.find_first_of(\"/\\\\\",first_unknown);\r\n\t\tif (next_dirpath != string::npos){\r\n\t\t\tboost::regex expr((last_dirpath != string::npos && last_dirpath > pos) ? patternSubstrRegex(pattern,last_dirpath+1,next_dirpath-last_dirpath-1) : patternSubstrRegex(pattern,pos,next_dirpath-pos));\r\n\t\t\tboost::filesystem::directory_iterator end_itr; // default construction yields past-the-end\r\n\t\t\ttry {\r\n\t\t\t\tfor ( boost::filesystem::directory_iterator itr( ((path.length() > 0) ? path + pattern[pos-1] : (last_dirpath != string::npos && last_dirpath > pos) ? \"\" : \"./\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) : \"\")); itr != end_itr; ++itr )\r\n\t\t\t\t{\r\n\t\t\t\t\tif (boost::filesystem::is_directory(itr->path())){\r\n\t\t\t\t\t\tboost::filesystem::path p = itr->path().filename();\r\n\t\t\t\t\t\tstring s =  p.string();\r\n\t\t\t\t\t\tif (boost::regex_match(s.c_str(), expr)){\r\n\t\t\t\t\t\t\tpatternToFiles(pattern,files,(int)(next_dirpath+1),((path.length() > 0) ? path + pattern[pos-1] : \"\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) + pattern[last_dirpath] : \"\") + s);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch (boost::filesystem::filesystem_error &e){}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tboost::regex expr((last_dirpath != string::npos && last_dirpath > pos) ? patternSubstrRegex(pattern,last_dirpath+1,pattern.length()-last_dirpath-1) : patternSubstrRegex(pattern,pos,pattern.length()-pos));\r\n\t\t\tboost::filesystem::directory_iterator end_itr; // default construction yields past-the-end\r\n\t\t\ttry {\r\n\t\t\t\tfor ( boost::filesystem::directory_iterator itr(((path.length() > 0) ? path +  pattern[pos-1] : (last_dirpath != string::npos && last_dirpath > pos) ? \"\" : \"./\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) : \"\")); itr != end_itr; ++itr )\r\n\t\t\t\t{\r\n\t\t\t\t\tboost::filesystem::path p = itr->path().filename();\r\n\t\t\t\t\tstring s =  p.string();\r\n\t\t\t\t\tif (boost::regex_match(s.c_str(), expr)){\r\n\t\t\t\t\t\tfiles.push_back(((path.length() > 0) ? path + pattern[pos-1] : \"\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) + pattern[last_dirpath] : \"\") + s);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch (boost::filesystem::filesystem_error &e){}\r\n\t\t}\r\n\t}\r\n\telse { // no unknown symbols\r\n\t\tboost::filesystem::path file(((path.length() > 0) ? path + \"/\" : \"\") + pattern.substr(pos,pattern.length()-pos));\r\n\t\tif (boost::filesystem::exists(file)){\r\n\t\t\tfiles.push_back(file.string());\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Converts a regular expression path pattern into a list of files matching with this pattern\r\n *\r\n * pattern: regular expression path pattern\r\n * files: the list to which new files can be applied\r\n */\r\nvoid patternToFiles(string& pattern, vector<string>& files){\r\n\tpatternToFiles(pattern,files,0,\"\");\r\n}\r\n\r\n/*\r\n * Renames a given filename corresponding to the actual file pattern using a renaming pattern.\r\n * Wildcards can be referred to as ?1, ?2, ... in the order they appeared in the file pattern.\r\n *\r\n * pattern: regular expression path pattern\r\n * renamePattern: renaming pattern using ?1, ?2, ... as placeholders for wildcards\r\n * infile: path of the file (matching with pattern) to be renamed\r\n * outfile: path of the renamed file\r\n * par: used parameter (default: '?')\r\n */\r\nvoid patternFileRename(string& pattern, const string& renamePattern, const string& infile, string& outfile, const char par = '?'){\r\n\tsize_t first_unknown = renamePattern.find_first_of(par,0); // find unknown ? in renamePattern\r\n\tif (first_unknown != string::npos){\r\n\t\tstring formatOut = \"\";\r\n\t\tfor (size_t i=0, e=renamePattern.length(); i < e; i++ ) {\r\n\t\t\tchar c = renamePattern[i];\r\n\t\t\tif ( c == par && i+1 < e) {\r\n\t\t\t\tc = renamePattern[i+1];\r\n\t\t\t\tif (c > '0' && c <= '9'){\r\n\t\t\t\t\tformatOut.append(1,'$');\r\n\t\t\t\t\tformatOut.append(1,c);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tformatOut.append(1,par);\r\n\t\t\t\t\tformatOut.append(1,c);\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tformatOut.append(1,c);\r\n\t\t\t}\r\n\t\t}\r\n\t\tboost::regex patternOut(patternSubstrRegex(pattern,0,pattern.length()));\r\n\t\toutfile = boost::regex_replace(infile,patternOut,formatOut,boost::match_default | boost::format_perl);\r\n\t} else {\r\n\t\toutfile = renamePattern;\r\n\t}\r\n}\r\n\r\nstring skipPath(string from){\r\n    string::size_type idx = from.find_last_of(\"/\\\\\"); // / is for linux, \\\\ is for windows\r\n    if( idx == string::npos ) return from; // not found, do nothing\r\n    return from.substr(idx+1); // return after path\r\n}\r\n\r\n/** ------------------------------- Program ------------------------------- **/\r\n\r\nbool use_mem = false;\r\nMat imread_mem( const string& filename, int flags=1){\r\n    if( !use_mem) return imread(filename, flags);\r\n    static map< std::pair<string, int>, Mat> memmap;\r\n    auto key = std::make_pair(filename, flags);\r\n    auto memitem = memmap.find( key );\r\n    Mat ret;\r\n    if( memitem != memmap.end()){\r\n        ret =  memitem->second;\r\n    } else{\r\n        memmap[ key ]=imread(filename, flags);\r\n        ret = memmap[ key ];\r\n    }\r\n    return ret;\r\n}\r\n\r\n\r\n/*\r\n * Main program\r\n */\r\nint main(int argc, char *argv[])\r\n{\r\n\tint mode = MODE_HELP;\r\n\tmap<string,vector<string> > cmd;\r\n\ttry {\r\n\t\tcmdRead(cmd,argc,argv);\r\n\t\tif (cmd.size() == 0 || cmdGetOpt(cmd,\"-h\") != 0) mode = MODE_HELP;\r\n\t\telse mode = MODE_MAIN;\r\n\t\tif (mode == MODE_MAIN){\r\n\t\t\t// validate command line\r\n\t\t\tcmdCheckOpts(cmd,\"-i|-m|-s|-ss|-a|-n|-o|-owp|-q|-t|-#|-b\");\r\n\t\t\tcmdCheckOptExists(cmd,\"-i\");\r\n\t\t\tcmdCheckOptSize(cmd,\"-i\",2);\r\n\t\t\tstring infilesSmpl = cmdGetPar(cmd,\"-i\",0);\r\n\t\t\tstring infilesRef = cmdGetPar(cmd,\"-i\",1);\r\n\t\t\tbool masks = (cmdGetOpt(cmd,\"-m\") != 0);\r\n\t\t\tif (masks) cmdCheckOptSize(cmd,\"-m\",2);\r\n\t\t\tstring masksSmpl = ((masks) ? cmdGetPar(cmd,\"-m\",0) : \"\");\r\n\t\t\tstring masksRef = ((masks) ? cmdGetPar(cmd,\"-m\",1) : \"\");\r\n\t\t\tbool shiftedfiles = (cmdGetOpt(cmd,\"-s\") != 0 && cmdSizePars(cmd,\"-s\") == 1);\r\n\t\t\tstring shiftfiles = ((shiftedfiles) ? cmdGetPar(cmd,\"-s\") : \"\");\r\n\t\t\tint minShifts = 0;\r\n\t\t\tint maxShifts = 0;\r\n\t\t\tif (cmdGetOpt(cmd,\"-s\") != 0 && !shiftedfiles){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-s\",2);\r\n\t\t\t\tminShifts = cmdGetParInt(cmd,\"-s\",0);\r\n\t\t\t\tmaxShifts = cmdGetParInt(cmd,\"-s\",1);\r\n\t\t\t}\r\n\t\t\tint shiftStep = 1;\r\n\t\t\tif (cmdGetOpt(cmd,\"-ss\") != 0 && !shiftedfiles){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-ss\",1);\r\n\t\t\t\tshiftStep = cmdGetParInt(cmd,\"-ss\",0);\r\n\t\t\t}\r\n\t\t\tint alg = ALG_MINHD;\r\n\t\t\tif (cmdGetOpt(cmd,\"-a\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-a\",1);\r\n\t\t\t\tstring algo = cmdGetPar(cmd,\"-a\");\r\n\t\t\t\tif (algo == \"maxhd\"){\r\n\t\t\t\t\talg = ALG_MAXHD;\r\n\t\t\t\t}\r\n\t\t\t\telse if (algo == \"ssf\"){\r\n\t\t\t\t\talg = ALG_SSF;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tunsigned int from = 0;\r\n\t\t\tunsigned int to = INT_MAX;\r\n\t\t\tif (cmdGetOpt(cmd,\"-n\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-n\",2);\r\n\t\t\t\tfrom = cmdGetParInt(cmd,\"-n\",0);\r\n\t\t\t\tCV_Assert(from % 8 == 0);\r\n\t\t\t\tfrom /= 8;\r\n\t\t\t\tto = cmdGetParInt(cmd,\"-n\",1);\r\n\t\t\t\tCV_Assert(to % 8 == 0);\r\n\t\t\t\tto /= 8;\r\n\t\t\t}\r\n\t\t\tstring outfile;\r\n            bool outfile_with_path = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-o\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-o\",1);\r\n\t\t\t\toutfile = cmdGetPar(cmd,\"-o\");\r\n                if( cmdGetOpt(cmd, \"-owp\") != 0){\r\n\t\t\t\t    cmdCheckOptSize(cmd,\"-owp\",0);\r\n                    outfile_with_path = true;\r\n                }\r\n\t\t\t}\r\n\t\t\tbool quiet = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-q\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-q\",0);\r\n\t\t\t\tquiet = true;\r\n\t\t\t}\r\n            bool writebitshift = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-b\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-b\",0);\r\n                writebitshift = true;\r\n\t\t\t}\r\n            //global use_mem\r\n\t\t\tif (cmdGetOpt(cmd,\"-#\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-#\",0);\r\n\t\t\t\tuse_mem = true;\r\n\t\t\t}\r\n\t\t\tbool time = false;\r\n\t\t\tif (cmdGetOpt(cmd,\"-t\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-t\",0);\r\n\t\t\t\ttime = true;\r\n\t\t\t}\r\n\t\t\t// starting routine\r\n\t\t\tTiming timing(1,quiet);\r\n\t\t\tvector<string> filesSmpl;\r\n\t\t\tpatternToFiles(infilesSmpl,filesSmpl);\r\n\t\t\tvector<string> filesRef;\r\n\t\t\tpatternToFiles(infilesRef,filesRef);\r\n\t\t\tCV_Assert(filesSmpl.size() > 0);\r\n\t\t\tCV_Assert(filesRef.size() > 0);\r\n\t\t\ttiming.total = filesSmpl.size() * filesRef.size();\r\n\t\t\tofstream cfile;\r\n\t\t\tif (!outfile.empty()){\r\n\t\t\t\tif (!quiet) printf(\"Opening result file '%s' ...\\n\", outfile.c_str());;\r\n\t\t\t\tcfile.open(outfile.c_str(),ios::out | ios::trunc);\r\n\t\t\t\tif (!(cfile.is_open())) {\r\n\t\t\t\t\tCV_Error(CV_StsError,\"Could not open result file '\" + outfile + \"'\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tfor (vector<string>::iterator infileSmpl = filesSmpl.begin(); infileSmpl != filesSmpl.end(); ++infileSmpl){\r\n\t\t\t\tvector<Mat> imgSmpl;\r\n\t\t\t\tvector<Mat> maskSmpl;\r\n\t\t\t\tif (shiftedfiles){\r\n\t\t\t\t\tstring shiftfile;\r\n\t\t\t\t\tpatternFileRename(infilesSmpl,shiftfiles,*infileSmpl,shiftfile);\r\n\t\t\t\t\tvector<string> shiftsSmpl;\r\n\t\t\t\t\tpatternToFiles(shiftfile,shiftsSmpl);\r\n\t\t\t\t\t// now load virtual files\r\n\t\t\t\t\tfor (vector<string>::iterator shiftSmpl = shiftsSmpl.begin(); shiftSmpl != shiftsSmpl.end(); ++shiftSmpl){\r\n\t\t\t\t\t\tMat img = imread_mem(*shiftSmpl, CV_LOAD_IMAGE_UNCHANGED);\r\n\t\t\t\t\t\tCV_Assert(img.data != 0);\r\n\t\t\t\t\t\tCV_Assert(img.type() == CV_8UC1);\r\n\t\t\t\t\t\tif (imgSmpl.size() > 0) { CV_Assert(imgSmpl.back().size() == img.size());}\r\n\t\t\t\t\t\timgSmpl.push_back(img);\r\n\t\t\t\t\t\tif (masks){\r\n\t\t\t\t\t\t\tstring maskfile1, maskfile2;\r\n\t\t\t\t\t\t\tpatternFileRename(infilesSmpl,masksSmpl,*infileSmpl,maskfile1);\r\n\t\t\t\t\t\t\tpatternFileRename(infilesSmpl,maskfile1,*infileSmpl,maskfile2,'!');\r\n\t\t\t\t\t\t\tMat msk = imread_mem(maskfile2, CV_LOAD_IMAGE_UNCHANGED);\r\n\t\t\t\t\t\t\tCV_Assert(msk.data != 0);\r\n\t\t\t\t\t\t\tCV_Assert(msk.type() == CV_8UC1);\r\n\t\t\t\t\t\t\tCV_Assert(img.size() == msk.size());\r\n\t\t\t\t\t\t\tmaskSmpl.push_back(msk);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tMat img = imread(*infileSmpl, CV_LOAD_IMAGE_UNCHANGED);\r\n\t\t\t\t\tCV_Assert(img.data != 0);\r\n\t\t\t\t\tCV_Assert(img.type() == CV_8UC1);\r\n\t\t\t\t\timgSmpl.push_back(img);\r\n\t\t\t\t\tif (masks){\r\n\t\t\t\t\t\tstring maskSmplFile;\r\n\t\t\t\t\t\tpatternFileRename(infilesSmpl,masksSmpl,*infileSmpl,maskSmplFile);\r\n\t\t\t\t\t\tMat msk = imread_mem(maskSmplFile, CV_LOAD_IMAGE_UNCHANGED);\r\n\t\t\t\t\t\tCV_Assert(msk.data != 0);\r\n\t\t\t\t\t\tCV_Assert(msk.type() == CV_8UC1);\r\n\t\t\t\t\t\tCV_Assert(msk.size() == img.size());\r\n\t\t\t\t\t\tmaskSmpl.push_back(msk);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tSize codeSize = imgSmpl[0].size();\r\n\t\t\t\tunsigned int codeLength = codeSize.height * codeSize.width;\r\n\t\t\t\tunsigned int bitStop = min(to,codeLength);\r\n\t\t\t\t//CV_Assert(codeLength % sizeof(int) == 0);\r\n\t\t\t\tfor (vector<string>::iterator infileRef = filesRef.begin(); infileRef != filesRef.end(); ++infileRef, timing.progress++){\r\n\t\t\t\t\tMat imgRef = imread_mem(*infileRef, CV_LOAD_IMAGE_UNCHANGED);\r\n\t\t\t\t\tCV_Assert(imgRef.data != 0);\r\n\t\t\t\t\tCV_Assert(imgRef.type() == CV_8UC1);\r\n\t\t\t\t\tCV_Assert(imgRef.size() == codeSize);\r\n\t\t\t\t\tMat maskRef;\r\n\t\t\t\t\tif (masks){\r\n\t\t\t\t\t\tstring maskRefFile;\r\n\t\t\t\t\t\tpatternFileRename(infilesRef,masksRef,*infileRef,maskRefFile);\r\n\t\t\t\t\t\tmaskRef = imread_mem(maskRefFile, CV_LOAD_IMAGE_UNCHANGED);\r\n\t\t\t\t\t\tCV_Assert(maskRef.data != 0);\r\n\t\t\t\t\t\tCV_Assert(maskRef.type() == CV_8UC1);\r\n\t\t\t\t\t\tCV_Assert(maskRef.size() == codeSize);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse {\r\n\t\t\t\t\t\tmaskRef = Mat();\r\n\t\t\t\t\t}\r\n                    std::pair<double, int> score = (alg == ALG_MINHD) ? (shiftedfiles) ? minHD(imgSmpl,imgRef,from,bitStop, maskSmpl, maskRef) : minHD(imgSmpl[0],imgRef,from,bitStop,minShifts, maxShifts, shiftStep, (maskSmpl.size() > 0) ? maskSmpl[0] : Mat(), maskRef) :\r\n\t\t\t\t\t\t\t\t(alg == ALG_MAXHD) ? (shiftedfiles) ? maxHD(imgSmpl,imgRef,from,bitStop, maskSmpl, maskRef) : maxHD(imgSmpl[0],imgRef,from,bitStop,minShifts, maxShifts, shiftStep, (maskSmpl.size() > 0) ? maskSmpl[0] : Mat(), maskRef) :\r\n\t\t\t\t\t\t\t\t(shiftedfiles) ? ssf(imgSmpl,imgRef,from,bitStop,maskSmpl, maskRef) : ssf(imgSmpl[0],imgRef,from,bitStop,minShifts, maxShifts, shiftStep, (maskSmpl.size() > 0) ? maskSmpl[0] : Mat(), maskRef);\r\n\t\t\t\t\tif (!quiet){\r\n                        if (writebitshift)\r\n                            printf(\"hd(%s,%s) = %f at %d bits\\n\",(*infileSmpl).c_str(), (*infileRef).c_str(), score.first, score.second);\r\n                        else\r\n                            printf(\"hd(%s,%s) = %f\\n\",(*infileSmpl).c_str(), (*infileRef).c_str(), score.first);\r\n                    }\r\n\r\n\t\t\t\t\tif (!outfile.empty() && cfile.is_open()){\r\n\t\t\t\t\t\tif( outfile_with_path){\r\n                            cfile << *infileSmpl << \" \" << *infileRef;\r\n                        } else {\r\n    \t\t\t\t\t\tcfile << skipPath(*infileSmpl) << \" \" << skipPath(*infileRef);\r\n                        }\r\n                        cfile  << \" \" << score.first;\r\n                        if( writebitshift) cfile << \" \" << score.second;\r\n                        cfile << endl;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (time && timing.update()) timing.print();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (time && quiet) timing.clear();\r\n\t\t\tif (!outfile.empty() && cfile.is_open()){\r\n\t\t\t\tcfile.close();\r\n\t\t\t}\r\n    \t}\r\n    \telse if (mode == MODE_HELP){\r\n\t\t\t// validate command line\r\n\t\t\tcmdCheckOpts(cmd,\"-h\");\r\n\t\t\tif (cmdGetOpt(cmd,\"-h\") != 0) cmdCheckOptSize(cmd,\"-h\",0);\r\n\t\t\t// starting routine\r\n\t\t\tprintUsage();\r\n    \t}\r\n    }\r\n\tcatch (...){\r\n\t   \tprintf(\"Exit with errors.\\n\");\r\n\t   \texit(EXIT_FAILURE);\r\n\t}\r\n    return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "4fee5e279369933f20ebe000c03a9e768ca8216b", "size": 44543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hd.cpp", "max_stars_repo_name": "ngoclamvt123/usit-v2.2.0", "max_stars_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-20T12:40:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T20:04:22.000Z", "max_issues_repo_path": "hd.cpp", "max_issues_repo_name": "ngoclamvt123/usit-v2.2.0", "max_issues_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hd.cpp", "max_forks_repo_name": "ngoclamvt123/usit-v2.2.0", "max_forks_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:51:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T02:49:06.000Z", "avg_line_length": 39.1759014952, "max_line_length": 545, "alphanum_fraction": 0.5826280224, "num_tokens": 12353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6442250996557036, "lm_q1q2_score": 0.44190585601142846}}
{"text": "#include <vector>\n#include <algorithm>\n#include <set>\n#include <iostream>\n#include <armadillo>\n#include <iomanip> \n\n#include \"Util.h\"\n#include \"PostCal.h\"\n\nusing namespace arma;\n\n\nvoid printGSLPrint(mat &A, int row, int col) {\n\tfor(int i = 0; i < row; i++) {\n\t\tfor(int j = 0; j < col; j++)\n\t\t\tprintf(\"%g \", A(i, j));\n\t\tprintf(\"\\n\");\n\t}\t\n}\n\nstring PostCal::convertConfig2String(int * config, int size) {\n\tstring result = \"0\";\n\tfor(int i = 0; i < size; i++)\n\t\tif(config[i]==1)\n\t\t\tresult+= \"_\" + convertInt(i);\n\treturn result;\n}\n\n// We compute dmvnorm(Zcc, mean=rep(0,nrow(Rcc)), Rcc + Rcc %*% Rcc) / dmvnorm(Zcc, rep(0, nrow(Rcc)), Rcc))\n// togheter to avoid numerical over flow\ndouble PostCal::fracdmvnorm(mat Z, mat mean, mat R, mat diagC, double NCP) {\n        mat newR = R + R * diagC  * R;\n        mat ZcenterMean = Z - mean;\n        //mat res1 = trans(ZcenterMean) * inv(R) * (ZcenterMean);\n        //mat res2 = trans(ZcenterMean) * inv(newR) *  (ZcenterMean);\n\tmat res1 = trans(ZcenterMean) * solve(R, eye(size(R))) * (ZcenterMean);\n\tmat res2 = trans(ZcenterMean) * solve(newR, eye(size(newR))) *  (ZcenterMean);\n        double v1 = res1(0,0)/2-res2(0,0)/2;\n\t//CHANGE: MOVE FORM NORMAL CALCULATION TO LOG SPACE\n        //return(exp(v1)/sqrt(det(newR))* sqrt(det(R)));\n        return(v1 - log( sqrt(det(newR)) ) + log( sqrt(det(R)) ) );\n}\n\n// We compute dmvnorm(Zcc, mean=rep(0,nrow(Rcc)), Rcc + Rcc %*% Rcc) / dmvnorm(Zcc, rep(0, nrow(Rcc)), Rcc))\n// togheter to avoid numerical over flow, We deal with singular LD matrix\n// eign decomposition matrx R\n// R = Q M Q^T where M is the diagonal matrix of eign values\ndouble PostCal::fracdmvnorm2(mat Z, mat mean, mat R, mat diagC, double NCP) {\n\tint rowCount = R.n_rows;\n\tdouble MDet=1;\n\tmat Q = zeros(rowCount, rowCount);\n\tmat eignVec;\n\tvec eignVal;\n\tmat MHalfInv = zeros(rowCount, rowCount);\n\tmat MHalf = zeros(rowCount, rowCount);\n\teig_sym(eignVal, eignVec, R);\n\tmat ZcenterMean = Z - mean;\n\tuvec indices;\n\tindices = sort_index(abs(ZcenterMean));\n\tfor(int i = 0 ; i < rowCount; i++){\n\t\tif(eignVal[indices[i]] > 0) {\n\t\t\tMHalfInv(i,i) = 1/sqrt(eignVal[indices[i]]);\n\t\t\tMDet = MDet * eignVal[indices[i]];\n\t\t\tMHalf(i,i) = sqrt(eignVal[indices[i]]);\n\t\t\tfor (int j = 0; j < rowCount; j++){\n\t\t\t\tQ(i,j) = eignVec(indices[i],j);\n\t\t\t}\n\t\t}\n\t}\n\tmat ZcenterMeanTilda = MHalfInv * Q.t() * ZcenterMean; \n\t//mat res1 = ZcenterMeanTilda.t() * ZcenterMeanTilda;\n\t//double v1 = -res1(0,0)/2 - log (sqrt(MDet));\n\tmat MHalfQ = MHalf * Q.t();\n\t//mat res2 = ZcenterMeanTilda.t() * inv(eye(rowCount, rowCount) + MHalfQ * diagC * MHalfQ.t())  * ZcenterMeanTilda;\n\tmat res3 = ZcenterMeanTilda.t() * (inv(eye(rowCount, rowCount) + MHalfQ * diagC * MHalfQ.t())-eye(rowCount,rowCount)) * ZcenterMeanTilda;\n\t//double v2 = -res2(0,0)/2 - log (sqrt(MDet*det(eye(rowCount, rowCount)+diagC*R)));\n\tdouble v3 = -res3(0,0)/2 - log (sqrt(MDet*det(eye(rowCount, rowCount)+diagC*R))) + log (sqrt(MDet));\n\treturn (v3);\n}\n\ndouble PostCal::dmvnorm(mat Z, mat mean, mat R) {\n        mat ZcenterMean = Z - mean;\n        mat res = trans(ZcenterMean) * inv(R) * (ZcenterMean);\n        double v1 = res(0,0);\n        double v2 = log(sqrt(det(R)));\n        return (exp(-v1/2-v2));\n}\n\n// cc=causal SNPs\n// Rcc = LD of causal SNPs\n// Zcc = Z-score of causal SNPs\n// dmvnorm(Zcc, mean=rep(0,nrow(Rcc)), Rcc + Rcc %*% Rcc) / dmvnorm(Zcc, rep(0, nrow(Rcc)), Rcc))\n//\ndouble PostCal::fastLikelihood(int * configure, double * stat, double NCP) {\n\tint causalCount = 0;\n\tvector <int> causalIndex;\n\tfor(int i = 0; i < snpCount; i++) {\n\t\tcausalCount += configure[i];\n\t\tif(configure[i] == 1)\n\t\t\tcausalIndex.push_back(i);\n\t}\n\t\n\tif (causalCount == 0) {\n\t\tint maxVal = 0;\n\t\tfor(int i = 0; i < snpCount; i++) {\n\t\t\tif (maxVal < abs(stat[i]))\n\t\t\t\tmaxVal = stat[i];\n\t\t}\n\t}\n\n\tmat Rcc(causalCount, causalCount, fill::zeros);\n\tmat Zcc(causalCount, 1, fill::zeros);\n\tmat mean(causalCount, 1, fill::zeros);\n\tmat diagC(causalCount, causalCount, fill::zeros);\n\n\tfor (int i = 0; i < causalCount; i++){\n\t\tfor(int j = 0; j < causalCount; j++) {\n\t\t\tRcc(i,j) = sigmaMatrix(causalIndex[i], causalIndex[j]);\n\t\t}\n\t\tZcc(i,0) = stat[causalIndex[i]];\n\t\tdiagC(i,i) = NCP;\n\t}\n\t\t\n\treturn fracdmvnorm(Zcc, mean, Rcc, diagC, NCP);\n}\n\n/*\n * This function is not depricated and invSigmaMatrix is not used anymore\n */\ndouble PostCal::likelihood(int * configure, double * stat, double NCP) {\n\tint causalCount = 0;\n\tint index_C = 0;\n        double matDet = 0;\n\tdouble res    = 0;\n\n\tfor(int i = 0; i < snpCount; i++) \n\t\tcausalCount += configure[i];\n\tif(causalCount == 0){\n\t\tmat tmpResultMatrix1N = statMatrixtTran * invSigmaMatrix;\n\t\tmat tmpResultMatrix11 = tmpResultMatrix1N * statMatrix;\n\t\tres = tmpResultMatrix11(0,0);\t\n\t\tmatDet = sigmaDet;\n\t\treturn( exp(-res/2)/sqrt(abs(matDet)) );\n\t}\n\tmat U(snpCount, causalCount, fill::zeros);\n\tmat V(causalCount, snpCount, fill::zeros);\n\tmat VU(causalCount, causalCount, fill::zeros);\n\t\t\n\tfor(int i = 0; i < snpCount; i++) {\n                if (configure[i] == 0)\tcontinue;\n                else {\n                        for(int j = 0; j < snpCount; j++) \n                                U(j, index_C) = sigmaMatrix(j,i);\n\t\t\tV(index_C, i) = NCP;\n                        index_C++;\n                }\n        }\n\tVU = V * U;\n\tmat I_AA   = mat(snpCount, snpCount, fill::eye);\n\tmat tmp_CC = mat(causalCount, causalCount, fill::eye)+ VU;\n\tmatDet = det(tmp_CC) * sigmaDet;\n\tmat tmp_AA = invSigmaMatrix - (invSigmaMatrix * U) * pinv(tmp_CC) * V ;\n\t//tmp_AA     = invSigmaMatrix * tmp_AA;\n\tmat tmpResultMatrix1N = statMatrixtTran * tmp_AA;\n        mat tmpResultMatrix11 = tmpResultMatrix1N * statMatrix;\n        res = tmpResultMatrix11(0,0);  \n\n\tif(matDet==0) {\n\t\tcout << \"Error the matrix is singular and we fail to fix it.\" << endl;\n\t\texit(0);\n\t}\n\t/*\n\t\tWe compute the log of -res/2-log(det) to see if it is too big or not. \n\t\tIn the case it is too big we just make it a MAX value.\n\t*/\n\tdouble tmplogDet = log(sqrt(abs(matDet)));\n\tdouble tmpFinalRes = -res/2 - tmplogDet;\n\tif(tmpFinalRes > 700) \n\t\treturn(exp(700));\n\treturn( exp(-res/2)/sqrt(abs(matDet)) );\t\n}\n\nint PostCal::nextBinary(int * data, int size) {\n\tint i = 0;\n\tint total_one = 0;\t\n\tint index = size-1;\n        int one_countinus_in_end = 0;\n\n        while(index >= 0 && data[index] == 1) {\n                index = index - 1;\n                one_countinus_in_end = one_countinus_in_end + 1;\n\t}\n\tif(index >= 0) {\n        \twhile(index >= 0 && data[index] == 0) {\n               \t index = index - 1;\t\n\t\t}\n\t}\n        if(index == -1) {\n                while(i <  one_countinus_in_end+1 && i < size) {\n                        data[i] = 1;\n                        i=i+1;\n\t\t}\n                i = 0;\n                while(i < size-one_countinus_in_end-1) {\n                        data[i+one_countinus_in_end+1] = 0;\n                        i=i+1;\n\t\t}\n\t}\n        else if(one_countinus_in_end == 0) {\n                data[index] = 0;\n                data[index+1] = 1;\n\t} else {\n                data[index] = 0;\n                while(i < one_countinus_in_end + 1) {\n                        data[i+index+1] = 1;\n\t\t\tif(i+index+1 >= size)\n\t\t\t\tprintf(\"ERROR3 %d\\n\", i+index+1);\n                        i=i+1;\n\t\t}\n                i = 0;\n                while(i < size - index - one_countinus_in_end - 2) {\n                        data[i+index+one_countinus_in_end+2] = 0;\n\t\t\tif(i+index+one_countinus_in_end+2 >= size) {\n\t\t\t\tprintf(\"ERROR4 %d\\n\", i+index+one_countinus_in_end+2);\n\t\t\t}\n                        i=i+1;\n\t\t}\n\t}\n\ti = 0;\n\ttotal_one = 0;\n\tfor(i = 0; i < size; i++)\n\t\tif(data[i] == 1)\n\t\t\ttotal_one = total_one + 1;\n\t\n\treturn(total_one);\t\t\n}\n\ndouble PostCal::computeTotalLikelihood(double * stat, double NCP) {\t\n\tint num = 0;\n\tdouble sumLikelihood = 0;\n\tdouble tmp_likelihood = 0;\n\tlong int total_iteration = 0 ;\n\tint * configure = (int *) malloc (snpCount * sizeof(int *)); // original data\t\n\n\tfor(long int i = 0; i <= maxCausalSNP; i++)\n\t\ttotal_iteration = total_iteration + nCr(snpCount, i);\n\tcout << \"Max Causal=\" << maxCausalSNP << endl;\n\tfor(long int i = 0; i < snpCount; i++) \n\t\tconfigure[i] = 0;\n\tfor(long int i = 0; i < total_iteration; i++) {\n                tmp_likelihood = fastLikelihood(configure, stat, NCP) + num * log(gamma) + (snpCount-num) * log(1-gamma);\t\n                sumLikelihood = addlogSpace(sumLikelihood, tmp_likelihood);\n\t\tfor(int j = 0; j < snpCount; j++) {\n                        postValues[j] = addlogSpace(postValues[j], tmp_likelihood * configure[j]);\n\t\t}\n\t\thistValues[num] = addlogSpace(histValues[num], tmp_likelihood);\n\t\t/*for (int j = 0; j < snpCount; j++) {\n\t\t\tif (configure[j] != 0)\n\t\t\t\tcout << j << \",\";\n\t\t}\n\t\tcout << \" \" << tmp_likelihood << endl;*/\n\t\tnum = nextBinary(configure, snpCount); \n\t\t//cout << i << \" \"  << exp(tmp_likelihood) << endl;\n\t\tif(i % 1000 == 0)\n\t\t\tcerr << \"\\r                                                                 \\r\" << (double) (i) / (double) total_iteration * 100.0 << \"%\";\n\t}\n\tfor(int i = 0; i <= maxCausalSNP; i++)\n\t\thistValues[i] = exp(histValues[i]-sumLikelihood);\n        free(configure);\n        return(sumLikelihood);\n}\n\nbool PostCal::validConfigutation(int * configure, char * pcausalSet) {\n\tfor(int i = 0; i < snpCount; i++){\n\t\tif(configure[i] == 1 && pcausalSet[i] == '0')\n\t\t\treturn false;\n\t}\n\treturn true;\t\n}\n\n/*\n * This is a auxilary function used to generate all possible causal set that \n * are selected in the p-causal set\n*/\nvoid PostCal::computeALLCausalSetConfiguration(double * stat, double NCP, char * pcausalSet, string outputFileName) {\n\tint num = 0;\n        double sumLikelihood = 0;\n        double tmp_likelihood = 0;\n        long int total_iteration = 0 ;\n        int * configure = (int *) malloc (snpCount * sizeof(int *)); // original data   \n\n        for(long int i = 0; i <= maxCausalSNP; i++)\n                total_iteration = total_iteration + nCr(snpCount, i);\n        for(long int i = 0; i < snpCount; i++)\n                configure[i] = 0;\n        for(long int i = 0; i < total_iteration; i++) {\n\t\tif (validConfigutation(configure, pcausalSet)) {\n\t\t\t//log space\n                \ttmp_likelihood = fastLikelihood(configure, stat, NCP) +  num * log(gamma) + (snpCount-num) * log(1-gamma);\n\t\t\texportVector2File(outputFileName, configure, snpCount);\n\t\t\texport2File(outputFileName, tmp_likelihood);\n\t\t}\n\t\tnum = nextBinary(configure, snpCount);\n\t}\n}\n\n/*\n\tstat is the z-scpres\n\tsigma is the correaltion matrix\n\tG is the map between snp and the gene (snp, gene)\n*/\ndouble PostCal::findOptimalSetGreedy(double * stat, double NCP, char * pcausalSet, int *rank,  double inputRho, string outputFileName) {\n\tint index = 0;\n        double rho = 0;\n        double total_post = 0;\n\n        totalLikeLihoodLOG = computeTotalLikelihood(stat, NCP);\n\t\n\texport2File(outputFileName+\".log\", exp(totalLikeLihoodLOG)); //Output the total likelihood to the log File\n\tfor(int i = 0; i < snpCount; i++)\n\t\ttotal_post = addlogSpace(total_post, postValues[i]);\n\tprintf(\"Total Likelihood= %e SNP=%d \\n\", total_post, snpCount);\n\t\n        std::vector<data> items;\n        std::set<int>::iterator it;\n\t//output the poster to files\n        for(int i = 0; i < snpCount; i++) {\n             //printf(\"%d==>%e \",i, postValues[i]/total_likelihood);\n             items.push_back(data(exp(postValues[i]-total_post), i, 0));\n        }\n        printf(\"\\n\");\n        std::sort(items.begin(), items.end(), by_number());\n        for(int i = 0; i < snpCount; i++)\n                rank[i] = items[i].index1;\n\n        for(int i = 0; i < snpCount; i++)\n                pcausalSet[i] = '0';\n        do{\n                rho += exp(postValues[rank[index]]-total_post);\n                pcausalSet[rank[index]] = '1';\n                printf(\"%d %e\\n\", rank[index], rho);\n                index++;\n        } while( rho < inputRho);\n\n        printf(\"\\n\");\n\treturn(0);\n}\n", "meta": {"hexsha": "37ed1277b97bce4acaffa8c4fbb4238570d0f1c9", "size": 11763, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "caviar/resources/usr/bin/PostCal.cpp", "max_stars_repo_name": "collaborativebioinformatics/DSVifier", "max_stars_repo_head_hexsha": "3b2f2737cb947da96300009b75aebe977bf52801", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "caviar/resources/usr/bin/PostCal.cpp", "max_issues_repo_name": "collaborativebioinformatics/DSVifier", "max_issues_repo_head_hexsha": "3b2f2737cb947da96300009b75aebe977bf52801", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "caviar/resources/usr/bin/PostCal.cpp", "max_forks_repo_name": "collaborativebioinformatics/DSVifier", "max_forks_repo_head_hexsha": "3b2f2737cb947da96300009b75aebe977bf52801", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-07T10:42:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-07T10:42:06.000Z", "avg_line_length": 33.7048710602, "max_line_length": 141, "alphanum_fraction": 0.5848848083, "num_tokens": 3667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916170039421, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.44181182678329634}}
{"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__MANIFOLD_VECTOR_HPP_\n#define SMOOTH__MANIFOLD_VECTOR_HPP_\n\n#include <Eigen/Sparse>\n#include <numeric>\n\n#include \"manifold.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief \\p std::vector based Manifold container.\n *\n * Convenient to treat a collection\n * \\f[\n *   m = (m_1, m_2, ..., m_k) \\in M \\times M \\times ... \\times M\n * \\f]\n * of Manifold elements as a single Manifold element \\f$m\\f$.\n */\ntemplate<Manifold M>\nclass ManifoldVector : public std::vector<M>\n{\nprivate:\n  using Base = std::vector<M>;\n\npublic:\n  //! Default constructor of empty ManifoldVector\n  ManifoldVector() = default;\n  //! Copy constructor\n  ManifoldVector(const ManifoldVector & o) = default;\n  //! Move constructor\n  ManifoldVector(ManifoldVector && o) = default;\n  //! Copy assignment operator\n  ManifoldVector & operator=(const ManifoldVector & o) = default;\n  //! Move assignment operator\n  ManifoldVector & operator=(ManifoldVector && o) = default;\n  ~ManifoldVector()                               = default;\n\n  /**\n   * Forwarding constructor to std::vector.\n   */\n  template<typename... Ts>\n  ManifoldVector(Ts &&... ts) : Base(std::forward<Ts>(ts)...)\n  {}\n\n  /**\n   * @brief Cast to different scalar type.\n   */\n  template<typename NewScalar>\n  ManifoldVector<CastT<NewScalar, M>> cast() const\n  {\n    ManifoldVector<CastT<NewScalar, M>> ret;\n    ret.reserve(size());\n    std::transform(this->begin(), this->end(), std::back_insert_iterator(ret), [](const auto & x) {\n      return ::smooth::cast<NewScalar>(x);\n    });\n    return ret;\n  }\n\n  /**\n   * @brief Number of elements in ManifoldVector.\n   */\n  std::size_t size() const { return Base::size(); }\n\n  /**\n   * @brief Runtime degrees of freedom.\n   *\n   * Sum of the degrees of freedom of constituent elements.\n   */\n  Eigen::Index dof() const\n  {\n    if constexpr (Dof < M >> 0) {\n      return size() * Dof<M>;\n    } else {\n      return std::accumulate(this->begin(), this->end(), 0u, [](auto s, const auto & item) {\n        return s + ::smooth::dof<M>(item);\n      });\n    }\n  }\n\n  /**\n   * @brief In-place addition.\n   *\n   * @note It must hold that dof() == a.dof()\n   */\n  template<typename Derived>\n  ManifoldVector<M> & operator+=(const Eigen::MatrixBase<Derived> & a)\n  {\n    Eigen::Index dof_cntr = 0;\n    for (auto i = 0u; i != this->size(); ++i) {\n      const auto dof_i = ::smooth::dof<M>(this->operator[](i));\n      this->operator[](i) =\n        rplus<M>(this->operator[](i), a.template segment<Dof<M>>(dof_cntr, dof_i));\n      dof_cntr += dof_i;\n    }\n    return *this;\n  }\n\n  /**\n   * @brief Addition.\n   *\n   * @note It must hold that `dof() == a.dof()`\n   */\n  template<typename Derived>\n  ManifoldVector<M> operator+(const Eigen::MatrixBase<Derived> & a) const\n  {\n    ManifoldVector<M> ret = *this;\n    ret += a;\n    return ret;\n  }\n\n  /**\n   * @brief Subtraction.\n   *\n   * @note It must hold that `dof() == o.dof()`\n   */\n  Eigen::VectorX<Scalar<M>> operator-(const ManifoldVector<M> & o) const\n  {\n    std::size_t dof_cnts = 0;\n    if (Dof < M >> 0) {\n      dof_cnts = Dof<M> * size();\n    } else {\n      for (auto i = 0u; i != size(); ++i) { dof_cnts += ::smooth::dof<M>(this->operator[](i)); }\n    }\n\n    Eigen::VectorX<Scalar<M>> ret(dof_cnts);\n    Eigen::Index idx = 0;\n    for (auto i = 0u; i != size(); ++i) {\n      const auto & size_i                       = ::smooth::dof<M>(this->operator[](i));\n      ret.template segment<Dof<M>>(idx, size_i) = rminus<M>(this->operator[](i), o[i]);\n      idx += size_i;\n    }\n\n    return ret;\n  }\n};\n\n/**\n * @brief Manifold interface for ManifoldVector\n */\ntemplate<Manifold M>\nstruct traits::man<ManifoldVector<M>>\n{\n  // \\cond\n  using Scalar      = ::smooth::Scalar<M>;\n  using PlainObject = ManifoldVector<M>;\n  template<typename NewScalar>\n  using CastT = ManifoldVector<typename man<M>::template CastT<NewScalar>>;\n\n  static constexpr Eigen::Index Dof = -1;\n\n  static inline Eigen::Index dof(const ManifoldVector<M> & m) { return m.dof(); }\n\n  static inline PlainObject Default(Eigen::Index dof)\n  {\n    /// @note If underlying M has dynamic size, mdof not uniquely defined\n    const Eigen::Index mdof = ::smooth::Dof<M> != -1 ? ::smooth::Dof<M> : 1;\n    const Eigen::Index size = dof / mdof;\n\n    return PlainObject(size, Default<M>(mdof));\n  }\n\n  template<typename NewScalar>\n  static inline auto cast(const ManifoldVector<M> & m)\n  {\n    return m.template cast<NewScalar>();\n  }\n\n  template<typename Derived>\n  static inline ManifoldVector<M>\n  rplus(const ManifoldVector<M> & m, const Eigen::MatrixBase<Derived> & a)\n  {\n    return m + a;\n  }\n\n  static inline Eigen::Matrix<Scalar, Dof, 1>\n  rminus(const ManifoldVector<M> & m1, const ManifoldVector<M> & m2)\n  {\n    return m1 - m2;\n  }\n  // \\endcond\n};\n\n}  // namespace smooth\n\ntemplate<typename Stream, smooth::Manifold M>\nStream & operator<<(Stream & s, const smooth::ManifoldVector<M> & g)\n{\n  s << \"ManifoldVector with \" << g.size() << \" elements:\\n\";\n  for (auto i = 0u; i != g.size(); ++i) {\n    s << i << \": \" << g[i];\n    if (i != g.size() - 1) { s << '\\n'; }\n  }\n  return s;\n}\n\n#endif  // SMOOTH__MANIFOLD_VECTOR_HPP_\n", "meta": {"hexsha": "5b635b9c20416c3a53f4df1e2498da2e84e14e93", "size": 6364, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/manifold_vector.hpp", "max_stars_repo_name": "tgurriet/smooth", "max_stars_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2021-07-06T21:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T13:26:44.000Z", "max_issues_repo_path": "include/smooth/manifold_vector.hpp", "max_issues_repo_name": "tgurriet/smooth", "max_issues_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2021-07-07T21:13:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T04:40:37.000Z", "max_forks_repo_path": "include/smooth/manifold_vector.hpp", "max_forks_repo_name": "tgurriet/smooth", "max_forks_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-07-09T07:16:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T14:29:44.000Z", "avg_line_length": 28.5381165919, "max_line_length": 99, "alphanum_fraction": 0.6359208045, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.4415938754186453}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_NTHROOT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_NTHROOT_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/constant/mone.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/bitwise_or.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/if_nan_else.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/if_else_zero.hpp>\n#include <boost/simd/function/if_zero_else.hpp>\n#include <boost/simd/function/is_equal.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_even.hpp>\n#include <boost/simd/function/is_inf.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/logical_and.hpp>\n#include <boost/simd/function/logical_andnot.hpp>\n#include <boost/simd/function/logical_or.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/pow.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/if_plus.hpp>\n#include <boost/simd/function/tofloat.hpp>\n#include <boost/simd/function/unary_minus.hpp>\n#include <boost/simd/function/fast.hpp>\n#include <boost/simd/function/log.hpp>\n#include <boost/simd/function/exp.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF( nthroot_\n                          , (typename A0, typename A1, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          , bs::pack_<bd::integer_<A1>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0, const  A1&  a1) const BOOST_NOEXCEPT\n      {\n      using bA0 = bs::as_logical_t<A0>;\n      A0 x =  bs::abs(a0);\n      A0 aa1 = bs::tofloat(a1);\n      A0 y = bs::fast_(bs::pow_abs)(x,rec(aa1));\n      bA0 nul_a1 =  bs::is_eqz(bitwise_cast<A0>(a1));\n      bA0 is_ltza0 = is_ltz(a0);\n      auto is_odda1 = is_odd(a1);\n      A0 p = fast_(bs::pow_abs)(y, aa1);\n      y = bs::if_plus( bs::logical_or(bs::is_nez(y), nul_a1)\n                     , y\n                     , -(p - x)/(aa1*p/y)\n                     );\n      // Correct numerical errors (since, e.g., 64^(1/3) is not exactly 4)\n      // by one iteration of Newton's method\n      bA0 test =  logical_andnot(is_ltza0, is_odda1);\n      bA0 done =  test;\n      y = if_nan_else(test, y);  // a0 < O and a1 is not odd\n      bA0 newtest =  is_equal(x, One<A0>());\n      test  = logical_andnot(newtest, done);\n      done  = logical_or(done, newtest);\n      y = if_else(test, a0, y); // 1^a1 or (-1)^a1\n      newtest =  nul_a1;\n      test  = logical_andnot(newtest, done);\n      done  = logical_or(done, newtest);\n      y =  if_else(test,\n                   if_zero_else(is_less(x, One<A0>()),\n                                sign(a0)*Inf<A0>()\n                               ),\n                   y);\n      newtest =  is_eqz(a0);\n      test  = logical_andnot(newtest, done);\n      done  = logical_or(done, newtest);\n      y =  if_zero_else(test, y);\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      newtest =  is_inf(a0);\n      test  = logical_andnot(newtest, done);\n      done  = logical_or(done, newtest);\n      y =  if_else(test, if_else(is_nez(a1), a0, One<A0>()), y);\n      #endif\n      return bs::bitwise_or(y, bs::bitofsign(a0));\n      }\n   };\n\n   BOOST_DISPATCH_OVERLOAD( nthroot_\n                          , (typename A0, typename A1, typename X)\n                          , bd::cpu_\n                          , bs::fast_tag\n                          , bs::pack_<bd::floating_<A0>, X>\n                          , bs::pack_<bd::integer_<A1>, X>\n                          )\n   {\n     BOOST_FORCEINLINE A0 operator()(const fast_tag &, const A0& a0, const  A1&  a1) const BOOST_NOEXCEPT\n     {\n       auto aa1 =  abs(a1);\n       A0 aa0 = abs(a0);\n       A0 y = sign(a0)*bs::exp(bs::log(aa0)/tofloat(aa1));\n       auto l =  is_ltz(aa1);\n       y =  if_nan_else(logical_and(l, is_even(a1)), y);\n       return if_else(is_ltz(a1), rec(y), y);\n     }\n   };\n\n\n} } }\n\n#endif\n", "meta": {"hexsha": "ff1a32b7e2cb5170aa647ebc4db82d8bc15fde14", "size": 4791, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/function/nthroot.hpp", "max_stars_repo_name": "timblechmann/boost.simd", "max_stars_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "include/boost/simd/arch/common/simd/function/nthroot.hpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/simd/function/nthroot.hpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 38.0238095238, "max_line_length": 105, "alphanum_fraction": 0.5767063244, "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.44151097319311305}}
{"text": "/*\n\nPICCANTE\nThe hottest HDR imaging library!\nhttp://vcg.isti.cnr.it/piccante\n\nCopyright (C) 2014\nVisual Computing Laboratory - ISTI CNR\nhttp://vcg.isti.cnr.it\nFirst author: Francesco Banterle\n\nThis Source Code Form is subject to the terms of the Mozilla Public\nLicense, v. 2.0. If a copy of the MPL was not distributed with this\nfile, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n*/\n\n#ifndef PIC_COMPUTER_VISION_CAMERA_MARTIX_HPP\n#define PIC_COMPUTER_VISION_CAMERA_MARTIX_HPP\n\n#include <vector>\n#include <random>\n#include <stdlib.h>\n\n#include \"../base.hpp\"\n\n#include \"../util/math.hpp\"\n#include \"../util/eigen_util.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n#ifndef PIC_EIGEN_NOT_BUNDLED\n    #include \"../externals/Eigen/Dense\"\n    #include \"../externals/Eigen/SVD\"\n    #include \"../externals/Eigen/Geometry\"\n    #include \"../externals/Eigen/Geometry\"\n    #include \"../externals/Eigen/QR\"\n#else\n    #include <Eigen/Dense>\n    #include <Eigen/SVD>\n    #include <Eigen/Geometry>\n    #include <Eigen/QR>\n#endif\n\n#endif\n\nnamespace pic {\n\n#ifndef PIC_DISABLE_EIGEN\n\n/**\n * @brief computeEpipole computes the epipole of a fundamental matrix F.\n * @param F is a fundamental matrix.\n * @return It returns the epipole of F.\n */\nPIC_INLINE Eigen::Vector3d computeEpipole(Eigen::Matrix3d &F)\n{\n    Eigen::JacobiSVD< Eigen::Matrix3d > svdF(F, Eigen::ComputeFullV);\n    Eigen::Matrix3d V = svdF.matrixV();\n\n    Eigen::Vector3d e;\n\n    e[0] = V(0, 2);\n    e[1] = V(1, 2);\n    e[2] = V(2, 2);\n\n    return e;\n}\n\n/**\n * @brief getCameraMatrixFromHomography\n * @param H is 3x3 homography matrix.\n * @param K\n * @return\n */\nPIC_INLINE Eigen::Matrix34d getCameraMatrixFromHomography(Eigen::Matrix3d &H, Eigen::Matrix3d &K)\n{\n    Eigen::Matrix34d m;\n    m.setZero();\n\n    Eigen::Matrix3d K_inv = K.inverse();\n\n    Eigen::Matrix3d H_p = K_inv * H;\n\n    Eigen::Vector3d r_0(H_p(0, 0), H_p(1, 0), H_p(2, 0));\n    Eigen::Vector3d r_1(H_p(0, 1), H_p(1, 1), H_p(2, 1));\n\n    r_0.normalize();\n    r_1.normalize();\n    Eigen::Vector3d r_2 = r_0.cross(r_1);\n\n    Eigen::Vector3d t(H_p(0, 2), H_p(1, 2), H_p(2, 2));\n\n    m(0, 0) = r_0[0];\n    m(1, 0) = r_0[1];\n    m(2, 0) = r_0[2];\n\n    m(0, 1) = r_1[0];\n    m(1, 1) = r_1[1];\n    m(2, 1) = r_1[2];\n\n    m(0, 2) = r_2[0];\n    m(1, 2) = r_2[1];\n    m(2, 2) = r_2[2];\n\n    m(0 , 3) = t[0];\n    m(1 , 3) = t[1];\n    m(2 , 3) = t[2];\n\n    return K * m;\n}\n\n/**\n * @brief getCameraMatrixIdentity\n * @param K\n * @return\n */\nPIC_INLINE Eigen::Matrix34d getCameraMatrixIdentity(Eigen::Matrix3d &K)\n{\n    Eigen::Matrix34d m;\n    m.setIdentity();\n    return K * m;\n}\n\n/**\n * @brief getCameraMatrix\n * @param K\n * @param R\n * @param t\n * @return\n */\nPIC_INLINE Eigen::Matrix34d getCameraMatrix(Eigen::Matrix3d &K, Eigen::Matrix3d &R, Eigen::Vector3d &t)\n{\n    Eigen::Matrix34d m;\n\n    m(0, 0) = R(0, 0);\n    m(1, 0) = R(1, 0);\n    m(2, 0) = R(2, 0);\n\n    m(0, 1) = R(0, 1);\n    m(1, 1) = R(1, 1);\n    m(2, 1) = R(2, 1);\n\n    m(0, 2) = R(0, 2);\n    m(1, 2) = R(1, 2);\n    m(2, 2) = R(2, 2);\n\n    m(0, 3) = t[0];\n    m(1, 3) = t[1];\n    m(2, 3) = t[2];\n\n    return K * m;\n}\n\n/**\n * @brief decomposeCameraMatrix\n * @param P\n * @param K\n * @param R\n * @param t\n */\nPIC_INLINE void decomposeCameraMatrix(Eigen::Matrix34d &P,\n                                      Eigen::Matrix3d  &K,\n                                      Eigen::Matrix3d  &R,\n                                      Eigen::Vector3d  &t)\n{\n    Eigen::Matrix3d matrix = P.block<3, 3>(0, 0).inverse();\n\n\n    //QR decomposition\n    Eigen::HouseholderQR<Eigen::Matrix3d> qr(matrix.rows(), matrix.cols());\n    qr.compute(matrix);\n\n    Eigen::Matrix3d Q = qr.householderQ();\n    Eigen::Matrix3d U = qr.matrixQR().triangularView<Eigen::Upper>();\n\n    auto U_d = getDiagonalFromMatrix(U);\n    Eigen::Vector3d d = U_d;\n    for(int i = 0; i < 3; i++) {\n        if(d[i] != 0.0) {\n            d[i] = U_d[i] > 0.0 ? 1.0 : -1.0;\n        }\n    }\n    auto D = DiagonalMatrix(d);\n\n    Q = Q * D;\n    U = D * U;\n\n    //compute K, R, and t\n    auto Q_t = Eigen::Transpose< Eigen::Matrix3d >(Q);\n    auto s = Q.determinant();\n\n    R = s * Q_t;\n    t = s * U * P.col(3);\n\n    if(U(2, 2) > 0.0) {\n        U /= U(2, 2);\n    }\n\n    K = U.inverse();\n}\n\n/**\n * @brief cameraMatrixProject projects a point, p, using the camera\n * matrix, M.\n * @param M\n * @param p is a 3D point encoded in homogenous coordinate (4D vector)\n * @return\n */\nPIC_INLINE Eigen::Vector2i cameraMatrixProject(Eigen::Matrix34d &M, Eigen::Vector4d &p)\n{\n    Eigen::Vector3d proj = M * p;\n    proj[0] /= proj[2];\n    proj[1] /= proj[2];\n\n    return Eigen::Vector2i(int(proj[0]), int(proj[1]));\n}\n\n/**\n * @brief cameraMatrixProject projects a point, p, using the camera\n * matrix, M.\n * @param M\n * @param p is a 3D point (3D vector)\n * @return\n */\nPIC_INLINE Eigen::Vector2i cameraMatrixProject(Eigen::Matrix34d &M, Eigen::Vector3d &p)\n{\n    Eigen::Vector4d p4d(p[0], p[1], p[2], 1.0);\n    return cameraMatrixProject(M, p4d);\n}\n\n/**\n * @brief cameraMatrixProjection\n * @param M\n * @param p\n * @param cx\n * @param cy\n * @param fx\n * @param fy\n * @param lambda\n * @return\n */\nPIC_INLINE Eigen::Vector2i cameraMatrixProjection(Eigen::Matrix34d &M, Eigen::Vector3d &p, double cx, double cy, double fx, double fy, double lambda)\n{\n    Eigen::Vector4d p_t = Eigen::Vector4d(p[0], p[1], p[2], 1.0);\n    Eigen::Vector2i out;\n    Eigen::Vector3d proj = M * p_t;\n    proj[0] /= proj[2];\n    proj[1] /= proj[2];\n\n    double x_cx =  (proj[0] - cx);\n    double y_cy =  (proj[1] - cy);\n\n    double dx = x_cx / fx;\n    double dy = y_cy / fy;\n    double rho_sq = dx * dx + dy * dy;\n\n    double factor = 1.0 / (1.0 + rho_sq * lambda);\n\n    proj[0] = x_cx * factor + cx;\n    proj[1] = y_cy * factor + cy;\n\n    out[0] = int(proj[0]);\n    out[1] = int(proj[1]);\n\n    return out;\n}\n\n/**\n * @brief getOpticalCenter\n * @param P the camera matrix of a view\n * @return it returns the camera center of P\n */\nPIC_INLINE Eigen::Vector3d getOpticalCenter(Eigen::Matrix34d &P)\n{\n    Eigen::Matrix3d Q = P.block<3, 3>(0, 0);\n    auto Q_inv = Q.inverse();\n    return - Q_inv * P.col(3);\n}\n\n/**\n * @brief cameraRectify\n * @param K0 intrisic matrix of view0\n * @param R0 rotation matrix of view0\n * @param t0 translation vector of view0\n * @param K1 intrisic matrix of view1\n * @param R1 rotation matrix of view1\n * @param t1 translation vector of view1\n * @param P0 new camera matrix of view0\n * @param P1 new camera matrix of view1\n * @param T0 transformation matrix for view0\n * @param T1 transformation matrix for view1\n */\nPIC_INLINE void cameraRectify(Eigen::Matrix3d &K0, Eigen::Matrix3d &R0, Eigen::Vector3d &t0,\n                              Eigen::Matrix3d &K1, Eigen::Matrix3d &R1, Eigen::Vector3d &t1,\n                              Eigen::Matrix34d &P0_out, Eigen::Matrix34d &P1_out,\n                              Eigen::Matrix3d &T0, Eigen::Matrix3d &T1)\n{\n    auto P0_in = getCameraMatrix(K0, R0, t0);\n    auto P1_in = getCameraMatrix(K1, R1, t1);\n\n    /*\n    auto K0_i = K0.inverse();\n    auto K1_i = K1.inverse();\n\n    auto R0_t = Eigen::Transpose< Eigen::Matrix3d >(R0);\n    auto R1_t = Eigen::Transpose< Eigen::Matrix3d >(R1);\n    auto c0 = -R0_t * K0_i * P0t.col(3);\n    auto c1 = -R1_t * K1_i * P1t.col(3);\n    */\n\n    //compute optical centers\n\n    auto c0 = getOpticalCenter(P0_in);\n    auto c1 = getOpticalCenter(P1_in);\n\n    //compute new rotation matrix\n    Eigen::Vector3d x_axis = c1 - c0;\n    Eigen::Vector3d tmp = R1.row(2);\n    Eigen::Vector3d y_axis = tmp.cross(x_axis);\n    Eigen::Vector3d z_axis = x_axis.cross(y_axis);\n\n    x_axis.normalize();\n    y_axis.normalize();\n    z_axis.normalize();\n\n    Eigen::Matrix3d R;\n\n    R(0, 0) = x_axis[0];\n    R(0, 1) = x_axis[1];\n    R(0, 2) = x_axis[2];\n\n    R(1, 0) = y_axis[0];\n    R(1, 1) = y_axis[1];\n    R(1, 2) = y_axis[2];\n\n    R(2, 0) = z_axis[0];\n    R(2, 1) = z_axis[1];\n    R(2, 2) = z_axis[2];\n\n    //new camera matrices\n    Eigen::Matrix3d K;\n    K.setZero();\n    K(0, 0) = K0(0, 0);\n    K(1, 1) = K0(1, 1);\n    K(0, 2) = (K0(0, 2) + K1(0, 2)) * 0.5;\n    K(1, 2) = (K0(1, 2) + K1(1, 2)) * 0.5;\n    K(2, 2) = 1.0;\n\n    Eigen::Vector3d t0n = -R * c0;\n    P0_out = getCameraMatrix(K, R, t0n);\n\n    Eigen::Vector3d t1n = -R * c1;\n    P1_out = getCameraMatrix(K, R, t1n);\n\n    //transformations\n    auto Q0o = P0_in.block<3, 3>(0, 0);\n    auto Q0n = P0_out.block<3, 3>(0, 0);\n    T0 = Q0n * Q0o.inverse();\n\n    auto Q1o = P1_in.block<3, 3>(0, 0);\n    auto Q1n = P1_out.block<3, 3>(0, 0);\n    T1 = Q1n * Q1o.inverse();\n}\n\n/**\n * @brief cameraRectify\n * @param P0_in\n * @param P1_in\n * @param P0_out\n * @param P1_out\n * @param T0\n * @param T1\n */\nPIC_INLINE void cameraRectify(Eigen::Matrix34d &P0_in, Eigen::Matrix34d &P1_in,\n                              Eigen::Matrix34d &P0_out, Eigen::Matrix34d &P1_out,\n                              Eigen::Matrix3d &T0, Eigen::Matrix3d &T1)\n{\n    Eigen::Matrix3d K0, K1, R0, R1;\n    Eigen::Vector3d t0, t1;\n\n    decomposeCameraMatrix(P0_in, K0, R0, t0);\n\n    decomposeCameraMatrix(P1_in, K1, R1, t1);\n\n    cameraRectify(K0, R0, t0,\n                  K1, R1, t1,\n                  P0_out, P1_out,\n                  T0, T1);\n}\n\n#endif // PIC_DISABLE_EIGEN\n\n} // end namespace pic\n\n#endif // PIC_COMPUTER_VISION_CAMERA_MARTIX_HPP\n", "meta": {"hexsha": "9f7fbe1bed5496117a5d94f1cd698d2353c92684", "size": 9223, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/computer_vision/camera_matrix.hpp", "max_stars_repo_name": "ecarpita93/HPC_projet_1", "max_stars_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/computer_vision/camera_matrix.hpp", "max_issues_repo_name": "ecarpita93/HPC_projet_1", "max_issues_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/computer_vision/camera_matrix.hpp", "max_forks_repo_name": "ecarpita93/HPC_projet_1", "max_forks_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2317380353, "max_line_length": 149, "alphanum_fraction": 0.580938957, "num_tokens": 3349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4415095550305792}}
{"text": "#include <toynet/w2v.h>\n#include <toynet/math.h>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\nnamespace toynet {\n\nstd::vector<int> get_context(const std::vector<int>& words, int index, int historyN, int futureN)\n{\n    std::vector<int> ret;\n    for (int j = std::max(0, index - historyN);  j < index;  ++j)\n        ret.push_back(words[j]);\n    for (int j = 1;  j <= futureN && index+j < words.size();  ++j)\n        ret.push_back(words[index+j]);\n    return ret;\n}\n\nvoid gradient_descent(ublas::matrix<double>& out, const ublas::matrix<double>& gradients, double lr)\n{\n    out -= gradients * lr;\n}\n\nCBOWModelGradients::CBOWModelGradients(int W, int D)\n    : P(ublas::zero_matrix<double>(W, D))\n    , O(ublas::zero_matrix<double>(W, D))\n{\n}\n\nCBOWModel::CBOWModel(int W, int D, int historyN, int futureN)\n    : W(W)\n    , D(D)\n    , historyN(historyN)\n    , futureN(futureN)\n    , P(W, D)\n    , O(W, D)\n{\n}\n\nvoid CBOWModel::save(std::ostream& os) const\n{\n    boost::archive::text_oarchive oa(os);\n    oa << *this;\n}\n\nvoid CBOWModel::load(std::istream& is)\n{\n    boost::archive::text_iarchive ia(is);\n    ia >> *this;\n}\n\nstd::vector<std::pair<double, int>> CBOWModel::predict(const std::vector<int>& context) const\n{\n    ublas::vector<double> smax = predict_helper(context);\n    std::vector<std::pair<double, int>> ret(W);\n    for (int i = 0;  i < W;  ++i)\n        ret[i] = std::make_pair(smax[i], i);\n    std::sort(ret.begin(), ret.end(), std::greater<>());\n    return ret;\n}\n\ndouble CBOWModel::predict(const std::vector<int>& context, int word) const\n{\n    ublas::vector<double> smax = predict_helper(context);\n    return smax[word];\n}\n\nublas::vector<double> CBOWModel::predict_helper(const std::vector<int>& context) const\n{\n    // average embedding of all context words\n    ublas::vector<double> avg(D, 0.0);\n    for (int wordidx : context)\n        avg += ublas::row(P, wordidx);\n    avg /= context.size();\n    // output layer (before softmax)\n    ublas::vector<double> out(W, 0.0);\n    for (int i = 0;  i < W;  ++i)\n        out[i] = dot_product(avg, row(O, i));\n    // softmax\n    ublas::vector<double> smax = softmax(out);\n    return smax;\n}\n\ndouble CBOWModel::avg_log_prob(const std::vector<int>& words) const\n{\n    double sum = 0.0;\n    for (int i = 0;  i < words.size();  ++i) {\n        std::vector<int> context = get_context(words, i, historyN, futureN);\n        double p = predict(context, words[i]);\n        sum += std::log(p);\n    }\n    return sum / words.size();\n}\n\nCBOWModelGradients CBOWModel::gradients() const\n{\n    CBOWModelGradients ret(W, D);\n    // TODO!\n    return ret;\n}\n\nvoid CBOWModel::update(const CBOWModelGradients& gradients, double lr)\n{\n    gradient_descent(P, gradients.P, lr);\n    gradient_descent(O, gradients.O, lr);\n}\n\nSimpleReporter::SimpleReporter(std::ostream& os)\n    : os(os)\n{\n}\n\nSimpleLearningRate::SimpleLearningRate(double lr, int cutoff, double base)\n    : lr(lr)\n    , cutoff(cutoff)\n    , base(base)\n{\n}\n\nvoid SimpleReporter::operator()(const ReportData& data) const\n{\n    os << \"epoch \" << data.epoch\n       << \" prob \" << data.avg_log_prob\n       << \" lr \" << data.lr\n       << \"\\n\";\n}\n\ndouble SimpleLearningRate::operator()(int epoch) const\n{\n    return (epoch <= cutoff)\n         ? lr\n         : lr * std::pow(base, epoch - cutoff);\n}\n\nTrainer::Trainer()\n    : epochs(1)\n    , D(50)\n    , historyN(4)\n    , futureN(4)\n    , initReporter(nullptr)\n    , epochReporter(nullptr)\n    , exitReporter(nullptr)\n    , learningRate(nullptr)\n{\n}\n\nTrainer& Trainer::setEpochs(int epochs)\n{\n    this->epochs = epochs;\n    return *this;\n}\n\nTrainer& Trainer::setEmbeddingSize(int D)\n{\n    this->D = D;\n    return *this;\n}\n\nTrainer& Trainer::setHistoryN(int historyN)\n{\n    this->historyN = historyN;\n    return *this;\n}\n\nTrainer& Trainer::setFutureN(int futureN)\n{\n    this->futureN = futureN;\n    return *this;\n}\n\nTrainer& Trainer::setInitReporter(const Reporter *initReporter)\n{\n    this->initReporter = initReporter;\n    return *this;\n}\n\nTrainer& Trainer::setEpochReporter(const Reporter *epochReporter)\n{\n    this->epochReporter = epochReporter;\n    return *this;\n}\n\nTrainer& Trainer::setExitReporter(const Reporter *exitReporter)\n{\n    this->exitReporter = exitReporter;\n    return *this;\n}\n\nTrainer& Trainer::setLearningRate(const LearningRate *learningRate)\n{\n    this->learningRate = learningRate;\n    return *this;\n}\n\nCBOWModel Trainer::train(const std::vector<int>& corpus) const\n{\n    // Find W, the maximum number of words\n    int W = *std::max_element(corpus.begin(), corpus.end()) + 1;\n    CBOWModel model(W, D, historyN, futureN);\n    int e = 0;\n    double avg_log_prob = model.avg_log_prob(corpus);\n    double lr = (*learningRate)(e);\n    if (initReporter)\n        (*initReporter)({e, avg_log_prob, lr});\n    while (e <= epochs) {\n        ++e;\n        CBOWModelGradients gradients = model.gradients();\n        lr = learningRate ? (*learningRate)(e) : 1.0;\n        model.update(gradients, lr);\n        avg_log_prob = model.avg_log_prob(corpus);\n        if (epochReporter)\n            (*epochReporter)({e, avg_log_prob, lr});\n        // TODO: compute loss on validation data\n    }\n    if (exitReporter)\n        (*exitReporter)({-1, avg_log_prob, lr});\n    return model;\n}\n\n} // namespace toynet\n", "meta": {"hexsha": "79229760730185d1a15252f79349203f8c66271c", "size": 5332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toynet/w2v.cpp", "max_stars_repo_name": "pbrunelle/w2v", "max_stars_repo_head_hexsha": "2ae0d95283c67ae5e27823a81edf05821280dae0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "toynet/w2v.cpp", "max_issues_repo_name": "pbrunelle/w2v", "max_issues_repo_head_hexsha": "2ae0d95283c67ae5e27823a81edf05821280dae0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-28T18:42:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T23:02:51.000Z", "max_forks_repo_path": "toynet/w2v.cpp", "max_forks_repo_name": "pbrunelle/toynet", "max_forks_repo_head_hexsha": "2ae0d95283c67ae5e27823a81edf05821280dae0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1266968326, "max_line_length": 100, "alphanum_fraction": 0.6318454614, "num_tokens": 1505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4415095479531114}}
{"text": "#include <tuple>\n\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n\n#include <Eigen/Core>\n\n#include \"vice/functors.h\"\n#include \"vice/integrate.h\"\n#include \"vice/benchmark.h\"\n\nnamespace py = pybind11;\n\n//\n// Trapezoid functions\n//\ntemplate <typename Scalar, typename ParamType, typename Integrator>\nstd::tuple<Eigen::Matrix<Scalar, Eigen::Dynamic, 1>, Eigen::Matrix<long int, Eigen::Dynamic, 1>, double>\nbenchmark_trapezoid (Scalar depth, Scalar duration, Scalar ingress,\n                     Eigen::Ref<const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>> time, const Scalar texp,\n                     ParamType param)\n{\n  vice::functors::TrapFunctor<Scalar> func(depth, duration, ingress);\n  auto integrator = Integrator();\n  return vice::benchmark::integrate(func, integrator, time, texp, param);\n}\n\ntemplate <typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, 1>\ntrapezoid_exact (Scalar depth, Scalar duration, Scalar ingress,\n                 Eigen::Ref<const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>> time, Scalar texp)\n{\n  Eigen::Matrix<Scalar, Eigen::Dynamic, 1> fluence(time.rows());\n  vice::functors::TrapFunctor<Scalar> func(depth, duration, ingress);\n  for (int i = 0; i < time.rows(); ++i) {\n    Scalar lower = time(i) - 0.5*texp;\n    Scalar upper = time(i) + 0.5*texp;\n    fluence(i) = func.integrate(lower, upper) / texp;\n  }\n  return fluence;\n}\n\ntemplate <typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, 1>\ntrapezoid_flux (Scalar depth, Scalar duration, Scalar ingress,\n                Eigen::Ref<const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>> time)\n{\n  Eigen::Matrix<Scalar, Eigen::Dynamic, 1> flux(time.rows());\n  vice::functors::TrapFunctor<Scalar> func(depth, duration, ingress);\n  for (int i = 0; i < time.rows(); ++i) {\n    flux(i) = func(time(i));\n  }\n  return flux;\n}\n\n\n//\n// Transit functions\n//\ntemplate <typename Scalar, typename ParamType, typename Integrator>\nstd::tuple<Eigen::Matrix<Scalar, Eigen::Dynamic, 1>, Eigen::Matrix<long int, Eigen::Dynamic, 1>, double>\nbenchmark_transit (Eigen::Ref<const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>> u, Scalar r, Scalar b, Scalar tau,\n                   Eigen::Ref<const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>> time, const Scalar texp,\n                   ParamType param)\n{\n  vice::functors::StarryFunctor<Scalar> func(u, r, b, tau);\n  auto integrator = Integrator();\n  return vice::benchmark::integrate(func, integrator, time, texp, param);\n}\n\ntemplate <typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, 1>\ntransit_exact (Eigen::Ref<const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>> u, Scalar r, Scalar b, Scalar tau,\n               Eigen::Ref<const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>> time, Scalar texp,\n               Scalar tol, unsigned max_depth)\n{\n  Eigen::Matrix<Scalar, Eigen::Dynamic, 1> fluence(time.rows());\n  vice::functors::StarryFunctor<Scalar> func(u, r, b, tau);\n  for (int i = 0; i < time.rows(); ++i) {\n    Scalar lower = time(i) - 0.5*texp;\n    Scalar upper = time(i) + 0.5*texp;\n    fluence(i) = func.integrate(lower, upper, tol, max_depth) / texp;\n  }\n  return fluence;\n}\n\ntemplate <typename Scalar>\nEigen::Matrix<Scalar, Eigen::Dynamic, 1>\ntransit_flux (Eigen::Ref<const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>> u, Scalar r, Scalar b, Scalar tau,\n              Eigen::Ref<const Eigen::Matrix<Scalar, Eigen::Dynamic, 1>> time)\n{\n  Eigen::Matrix<Scalar, Eigen::Dynamic, 1> flux(time.rows());\n  vice::functors::StarryFunctor<Scalar> func(u, r, b, tau);\n  for (int i = 0; i < time.rows(); ++i) {\n    flux(i) = func(time(i));\n  }\n  return flux;\n}\n\n//\n// Python interface\n//\nPYBIND11_MODULE(benchmark, m) {\n\n  m.def(\"trapezoid_flux\",            &trapezoid_flux<double>);\n  m.def(\"transit_flux\",              &transit_flux<double>);\n\n  m.def(\"trapezoid_exact\",           &trapezoid_exact<double>);\n  m.def(\"transit_exact\",             &transit_exact<double>,\n                                     py::arg(\"u\"), py::arg(\"r\"), py::arg(\"b\"), py::arg(\"tau\"), py::arg(\"t\"), py::arg(\"texp\"),\n                                     py::arg(\"tol\")=1e-12, py::arg(\"max_depth\")=15);\n\n  m.def(\"trapezoid_riemann\",         &benchmark_trapezoid<double, unsigned, vice::integrate::riemann>);\n  m.def(\"trapezoid_trapezoid_fixed\", &benchmark_trapezoid<double, unsigned, vice::integrate::trapezoid_fixed>);\n  m.def(\"trapezoid_simpson_fixed\",   &benchmark_trapezoid<double, unsigned, vice::integrate::simpson_fixed>);\n  m.def(\"trapezoid_trapezoid_adapt\", &benchmark_trapezoid<double, double, vice::integrate::trapezoid_adapt>);\n  m.def(\"trapezoid_simpson_adapt\",   &benchmark_trapezoid<double, double, vice::integrate::simpson_adapt>);\n  m.def(\"trapezoid_gauss\",           &benchmark_trapezoid<double, double, vice::integrate::quadrature<15>>);\n\n  m.def(\"transit_riemann\",           &benchmark_transit<double, unsigned, vice::integrate::riemann>);\n  m.def(\"transit_trapezoid_fixed\",   &benchmark_transit<double, unsigned, vice::integrate::trapezoid_fixed>);\n  m.def(\"transit_simpson_fixed\",     &benchmark_transit<double, unsigned, vice::integrate::simpson_fixed>);\n  m.def(\"transit_trapezoid_adapt\",   &benchmark_transit<double, double, vice::integrate::trapezoid_adapt>);\n  m.def(\"transit_simpson_adapt\",     &benchmark_transit<double, double, vice::integrate::simpson_adapt>);\n  m.def(\"transit_gauss\",             &benchmark_transit<double, double, vice::integrate::quadrature<15>>);\n\n}\n", "meta": {"hexsha": "f938efdde595e99091e3ba8c318204705eac7340", "size": 5385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vice/benchmark.cpp", "max_stars_repo_name": "dfm/confessional", "max_stars_repo_head_hexsha": "24e0088602ec03cb31bbd1a27bd20465793dcfa4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vice/benchmark.cpp", "max_issues_repo_name": "dfm/confessional", "max_issues_repo_head_hexsha": "24e0088602ec03cb31bbd1a27bd20465793dcfa4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-02T12:00:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-02T12:00:51.000Z", "max_forks_repo_path": "vice/benchmark.cpp", "max_forks_repo_name": "dfm/confessional", "max_forks_repo_head_hexsha": "24e0088602ec03cb31bbd1a27bd20465793dcfa4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0703125, "max_line_length": 125, "alphanum_fraction": 0.6700092851, "num_tokens": 1520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4415095479531114}}
{"text": "/*\nfitting.cpp\n\nCopyright (c) 2014,2015 Terumasa Tadano\n\nThis file is distributed under the terms of the MIT license.\nPlease see the file 'LICENCE.txt' in the root directory \nor http://opensource.org/licenses/mit-license.php for information.\n*/\n\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <string>\n#include <vector>\n#include <set>\n#include <boost/lexical_cast.hpp>\n#include \"fitting.h\"\n#include \"files.h\"\n#include \"error.h\"\n#include \"memory.h\"\n#include \"symmetry.h\"\n#include \"system.h\"\n#include \"fcs.h\"\n#include \"interaction.h\"\n#include \"timer.h\"\n#include \"combination.h\"\n#include \"constants.h\"\n#include \"constraint.h\"\n#include \"mathfunctions.h\"\n\n#ifdef _USE_EIGEN\n#include <Eigen/Dense>\n#endif\n\n#include <time.h>\n\n#ifdef _VSL\n#include \"mkl_vsl.h\"\n\n#else\n#include <cstdlib>\n#endif\n\nusing namespace ALM_NS;\n\n\nFitting::Fitting(ALM *alm): Pointers(alm){\n    seed = (unsigned int) time(NULL);\n#ifdef _VSL\n    brng = VSL_BRNG_MT19937;\n    vslNewStream(&stream, brng, seed);\n#else\n    std::srand(seed);\n#endif\n}\n\nFitting::~Fitting() {\n    if (alm->mode == \"fitting\") {\n        memory->deallocate(params);\n    }\n}\n\nvoid Fitting::fitmain()\n{\n    int i;\n    int nat = system->nat;\n    int natmin = symmetry->natmin;\n    int ntran = symmetry->ntran;\n\n    int ndata = system->ndata;\n    int nstart = system->nstart;\n    int nend = system->nend;\n    int nskip = system->nskip;\n\n    int N, M, N_new;\n    int maxorder = interaction->maxorder;\n    int P = constraint->P;\n\n    int nmulti;\n    int ndata_used = nend - nstart + 1;\n\n    double **u, **f;\n    double **amat, *fsum;\n    double *fsum_orig;\n    double *param_tmp;\n\n    std::cout << \" FITTING\" << std::endl;\n    std::cout << \" =======\" << std::endl << std::endl;\n\n    std::cout << \"  Reference files\" << std::endl;\n    std::cout << \"   Displacement: \" << files->file_disp << std::endl;\n    std::cout << \"   Force       : \" << files->file_force << std::endl;\n    std::cout << std::endl;\n\n    std::cout << \"  NSTART = \" << nstart << \"; NEND = \" << nend << std::endl;\n    std::cout << \"  \" << ndata_used << \" entries will be used for fitting.\" << std::endl << std::endl;\n\n    // Read displacement-force training data set from files\n\n    data_multiplier(nat, ndata, nstart, nend, ndata_used, nmulti, \n                    symmetry->multiply_data, u, f,\n                    files->file_disp, files->file_force);\n\n    N = 0;\n    for (i = 0; i < maxorder; ++i) {\n        N += fcs->ndup[i].size();\n    }\n    std::cout << \"  Total Number of Parameters : \" << N << std::endl << std::endl;\n\n    // Calculate matrix elements for fitting\n\n    M = 3 * natmin * ndata_used * nmulti;\n\n    if (constraint->constraint_algebraic) {\n\n        N_new = 0;\n        for (i = 0; i < maxorder; ++i) {\n            N_new += constraint->index_bimap[i].size();\n        }\n        std::cout << \"  Total Number of Free Parameters : \" << N_new << std::endl << std::endl;\n\n        memory->allocate(amat, M, N_new);\n        memory->allocate(fsum, M);\n        memory->allocate(fsum_orig, M);\n\n        calc_matrix_elements_algebraic_constraint(M, N, N_new, nat, natmin, ndata_used, \n            nmulti, maxorder, u, f, amat, fsum, fsum_orig);\n\n    } else {\n\n        memory->allocate(amat, M, N);\n        memory->allocate(fsum, M);\n\n        calc_matrix_elements(M, N, nat, natmin, ndata_used, nmulti, maxorder, u, f, amat, fsum);\n    }\n\n    memory->deallocate(u);\n    memory->deallocate(f);\n\n    // Execute fitting\n\n    memory->allocate(param_tmp, N);\n\n    if (nskip == 0) {\n\n        // Fitting with singular value decomposition or QR-Decomposition\n\n        if (constraint->constraint_algebraic) {\n            fit_algebraic_constraints(N_new, M, amat, fsum, param_tmp, \n                                      fsum_orig, maxorder);\n\n        } else if (constraint->exist_constraint) {\n            fit_with_constraints(N, M, P, amat, fsum, param_tmp,\n                                 constraint->const_mat, constraint->const_rhs);\n        } else {\n            fit_without_constraints(N, M, amat, fsum, param_tmp);\n        }\n\n    } else if (nskip > 0) {\n\n        // Execute fittings consecutively with different input data.\n\n        if (constraint->exist_constraint) {\n            fit_consecutively(N, P, natmin, ndata_used, nmulti, nskip, amat, fsum, \n                              constraint->const_mat, constraint->const_rhs);\n        } else {\n            error->exit(\"fitmain\", \"nskip has to be 0 when constraint_mode = 0\");\n        }\n    } else {\n\n        // Execute bootstrap simulation for estimating deviations of parameters.\n\n        if (constraint->exist_constraint) {\n            fit_bootstrap(N, P, natmin, ndata_used, nmulti, amat, fsum, \n                          constraint->const_mat, constraint->const_rhs);\n            fit_with_constraints(N, M, P, amat, fsum, param_tmp,\n                                 constraint->const_mat, constraint->const_rhs);\n        } else {\n            error->exit(\"fitmain\", \"bootstrap analysis for LSE without constraint is not supported yet\");\n        }\n    }\n\n    // Copy force constants to public variable \"params\"\n\n    memory->allocate(params, N);\n\n    if (constraint->constraint_algebraic) {\n\n        for (i = 0; i < N; ++i) {\n            params[i] = param_tmp[i];\n        }\n        memory->deallocate(fsum_orig);\n\n    } else {\n\n        for (i = 0; i < N; ++i) params[i] = param_tmp[i];\n\n    }\n\n    memory->deallocate(amat);\n    memory->deallocate(fsum);\n    memory->deallocate(param_tmp);\n\n    std::cout << std::endl;\n    timer->print_elapsed();\n    std::cout << \" --------------------------------------------------------------\" << std::endl;\n    std::cout << std::endl;\n\n}\n\nvoid Fitting::data_multiplier(const int nat, const int ndata, const int nstart, const int nend, \n                              const int ndata_used, int &nmulti, const int multiply_data, double **&u, double **&f,\n                              const std::string file_disp, const std::string file_force) \n{\n    int i, j, k;\n    int idata, itran, isym;\n    int n_mapped;\n    double u_rot[3], f_rot[3];\n    double u_in, f_in;\n    double *u_tmp, *f_tmp;\n    std::vector<int> vec_data;\n    unsigned int nline_f, nline_u;\n    unsigned int nreq;\n\n    std::ifstream ifs_disp, ifs_force;\n\n    ifs_disp.open(file_disp.c_str(), std::ios::in);\n    if (!ifs_disp) error->exit(\"openfiles\", \"cannot open disp file\");\n    ifs_force.open(file_force.c_str(), std::ios::in);\n    if (!ifs_force) error->exit(\"openfiles\", \"cannot open force file\");\n\n    nreq = 3 * nat * ndata;\n\n    memory->allocate(u_tmp, nreq);\n    memory->allocate(f_tmp, nreq);\n\n    // Read displacements from DFILE\n\n    nline_u = 0;\n    while (ifs_disp >> u_in) {\n        u_tmp[nline_u++] = u_in;\n        if (nline_u == nreq) break;\n    }\n    if (nline_u < nreq) error->exit(\"data_multiplier\", \n        \"The number of lines in DFILE is too small for the given NDATA = \", ndata);\n\n    // Read forces from FFILE\n\n    nline_f = 0;\n    while (ifs_force >> f_in) {\n        f_tmp[nline_f++] = f_in;\n        if (nline_f == nreq) break;\n    }\n    if (nline_f < nreq) error->exit(\"data_multiplier\", \n        \"The number of lines in FFILE is too small for the given NDATA = \", ndata);\n\n    // Multiply data\n\n    if (multiply_data == 0) {\n\n        std::cout << \" MULTDAT = 0: Given displacement-force data sets will be used as is.\" << std::endl << std::endl;\n\n        nmulti = 1;\n\n        memory->allocate(u, ndata_used * nmulti, 3 * nat);\n        memory->allocate(f, ndata_used * nmulti, 3 * nat);\n\n        idata = 0;\n\n        for (i = 0; i < ndata; ++i) {\n            if (i < nstart - 1) continue;\n            if (i > nend - 1) break;\n\n            for (j = 0; j < nat; ++j) {\n                for (k = 0; k < 3; ++k) {\n                    u[idata][3 * j + k] = u_tmp[3*nat*i + 3*j + k];\n                    f[idata][3 * j + k] = f_tmp[3*nat*i + 3*j + k];\n                }\n            }\n            ++idata;\n        }\n\n    } else if (multiply_data == 1) {\n\n        std::cout << \"  MULTDAT = 1: Generate symmetrically equivalent displacement-force data sets \" << std::endl;\n        std::cout << \"               by using pure translational operations only.\" << std::endl << std::endl;\n\n        nmulti = symmetry->ntran;\n\n        memory->allocate(u, ndata_used * nmulti, 3 * nat);\n        memory->allocate(f, ndata_used * nmulti, 3 * nat);\n\n        idata = 0;\n\n        for (i = 0; i < ndata; ++i) {\n            if (i < nstart - 1) continue;\n            if (i > nend - 1) break;\n\n            for (itran = 0; itran < symmetry->ntran; ++itran) {\n                for (j = 0; j < nat; ++j) {\n                    n_mapped = symmetry->map_sym[j][symmetry->symnum_tran[itran]];\n\n                    for (k = 0; k < 3; ++k) {\n                        u[idata][3 * n_mapped + k] = u_tmp[3*nat*i + 3*j + k];\n                        f[idata][3 * n_mapped + k] = f_tmp[3*nat*i + 3*j + k];\n                    }\n                }\n                ++idata;\n            }\n        }\n\n    } else if (multiply_data == 2) {\n\n        std::cout << \"  MULTDAT = 2: Generate symmetrically equivalent displacement-force data sets.\" << std::endl;\n        std::cout << \"               (including rotational part) \" << std::endl << std::endl;\n\n        nmulti = symmetry->nsym;\n\n        memory->allocate(u, ndata_used * nmulti, 3 * nat);\n        memory->allocate(f, ndata_used * nmulti, 3 * nat);\n\n        idata = 0;\n\n        for (i = 0; i < ndata; ++i) {\n            if (i < nstart - 1) continue;\n            if (i > nend - 1) break;\n\n#pragma omp parallel for private(j, n_mapped, k, u_rot, f_rot)\n            for (isym = 0; isym < symmetry->nsym; ++isym) {\n                for (j = 0; j < nat; ++j) {\n                    n_mapped = symmetry->map_sym[j][isym];\n\n                    for (k = 0; k < 3; ++k) {\n                        u_rot[k] = u_tmp[3*nat*i + 3*j + k];\n                        f_rot[k] = f_tmp[3*nat*i + 3*j + k];\n                    }\n\n                    rotvec(u_rot, u_rot, symmetry->symrel[isym]);\n                    rotvec(f_rot, f_rot, symmetry->symrel[isym]);\n\n                    for (k = 0; k < 3; ++k) {\n                        u[nmulti * idata + isym][3 * n_mapped + k] = u_rot[k];\n                        f[nmulti * idata + isym][3 * n_mapped + k] = f_rot[k];\n                    }\n                }\n            }\n            ++idata;\n        }\n\n    } else {\n        error->exit(\"data_multiplier\", \"Unsupported MULTDAT\");\n    }\n\n    memory->deallocate(u_tmp);\n    memory->deallocate(f_tmp);\n\n    ifs_disp.close();\n    ifs_force.close();\n}\n\nvoid Fitting::fit_without_constraints(int N, int M, double **amat, double *bvec, double *param_out)\n{\n    int i, j;\n    unsigned long k;\n    int nrhs = 1, nrank, INFO, LWORK;\n    int LMIN, LMAX;\n    double rcond = -1.0;\n    double f_square = 0.0;\n    double *WORK, *S, *amat_mod, *fsum2;\n\n    std::cout << \"  Entering fitting routine: SVD without constraints\" << std::endl;\n\n    LMIN = std::min<int>(M, N);\n    LMAX = std::max<int>(M, N);\n\n    LWORK = 3*LMIN + std::max<int>(2*LMIN, LMAX);\n    LWORK = 2 * LWORK;\n\n    memory->allocate(WORK, LWORK);\n    memory->allocate(S, LMIN);\n\n    // transpose matrix A\n    memory->allocate(amat_mod, M * N);\n    memory->allocate(fsum2, LMAX);\n\n    k = 0;\n    for (j = 0; j < N; ++j) {\n        for (i = 0; i < M; ++i) {\n            amat_mod[k++] = amat[i][j];\n        }\n    }\n    for (i = 0; i < M; ++i) {\n        fsum2[i] = bvec[i];\n        f_square += std::pow(bvec[i], 2);\n    }\n    for (i = M; i < LMAX; ++i) fsum2[i] = 0.0;\n\n    std::cout << \"  SVD has started ... \";\n   \n    // Fitting with singular value decomposition\n    dgelss_(&M, &N, &nrhs, amat_mod, &M, fsum2, &LMAX, S, &rcond, &nrank, WORK, &LWORK, &INFO);\n\n    std::cout << \"finished !\" << std::endl << std::endl;\n\n    std::cout << \"  RANK of the matrix = \" << nrank << std::endl;\n    if (nrank < N) error->warn(\"fit_without_constraints\", \n        \"Matrix is rank-deficient. Force constants could not be determined uniquely :(\");\n\n    if (nrank == N) {\n        double f_residual = 0.0;\n        for (i = N; i < M; ++i) {\n            f_residual += std::pow(fsum2[i], 2);\n        }\n        std::cout << std::endl << \"  Residual sum of squares for the solution: \" << sqrt(f_residual) << std::endl;\n        std::cout << \"  Fitting error (%) : \"<< sqrt(f_residual/f_square) * 100.0 << std::endl;\n    }\n\n    for (i = 0; i < N; ++i) {\n        param_out[i] = fsum2[i];\n    }\n\n    memory->deallocate(WORK);\n    memory->deallocate(S);\n    memory->deallocate(fsum2);\n    memory->deallocate(amat_mod);\n}\n\nvoid Fitting::fit_with_constraints(int N, int M, int P,\n                                   double **amat, double *bvec, double *param_out, \n                                   double **cmat, double *dvec)\n{\n    int i, j;\n    unsigned long k;\n    int nrank;\n    double f_square, f_residual;\n    double *fsum2;\n\n    std::cout << \"  Entering fitting routine: QRD with constraints\" << std::endl;\n\n    memory->allocate(fsum2, M);\n\n#ifdef _USE_EIGEN\n\n    double **mat_tmp2;\n    memory->allocate(mat_tmp2, M + P, N);\n    for (i = 0; i < M; ++i) {\n        for (j = 0; j < N; ++j) {\n            mat_tmp2[i][j] = amat[i][j];\n        }\n    }\n    for (i = 0; i < P; ++i) {\n        for (j = 0; j < N; ++j) {\n            mat_tmp2[M + i][j] = cmat[i][j];\n        }\n    }\n\n    nrank = getRankEigen(M+P, N, mat_tmp2);\n    memory->deallocate(mat_tmp2);\n\n#else\n\n    double *mat_tmp;\n\n    memory->allocate(mat_tmp, (M + P) * N);\n\n    k = 0;\n\n    for (j = 0; j < N; ++j) {\n        for (i = 0; i < M; ++i) {\n            mat_tmp[k++] = amat[i][j];\n        }\n        for (i = 0; i < P; ++i) {\n            mat_tmp[k++] = cmat[i][j];\n        }\n    }\n\n    nrank = rankQRD((M+P), N, mat_tmp, eps12);\n    memory->deallocate(mat_tmp);\n\n#endif\n\n    if (nrank != N) {\n        std::cout << std::endl;\n        std::cout << \" **************************************************************************\" << std::endl;\n        std::cout << \"  WARNING : rank deficient.                                                \" << std::endl;\n        std::cout << \"  rank ( (A) ) ! = N            A: Fitting matrix     B: Constraint matrix \" << std::endl;\n        std::cout << \"       ( (B) )                  N: The number of parameters                \" << std::endl;\n        std::cout << \"  rank = \" << nrank << \" N = \" << N << std::endl << std::endl;\n        std::cout << \"  This can cause a difficulty in solving the fitting problem properly      \" << std::endl;\n        std::cout << \"  with DGGLSE, especially when the difference is large. Please check if    \" << std::endl;\n        std::cout << \"  you obtain reliable force constants in the .fcs file.                    \" << std::endl << std::endl;\n        std::cout << \"  This issue may be resolved by setting MULTDAT = 2 in the &fitting field. \" << std::endl;\n        std::cout << \"  If not, you may need to reduce the cutoff radii and/or increase NDATA    \" << std::endl;\n        std::cout << \"  by giving linearly-independent displacement patterns.                    \" << std::endl;\n        std::cout << \" **************************************************************************\" << std::endl;\n        std::cout << std::endl;\n    }\n\n    f_square = 0.0;\n    for (i = 0; i < M; ++i) {\n        fsum2[i] = bvec[i];\n        f_square += std::pow(bvec[i], 2);\n    }\n    std::cout << \"  QR-Decomposition has started ...\";\n\n    double *amat_mod, *cmat_mod;\n    memory->allocate(amat_mod, M * N);\n    memory->allocate(cmat_mod, P * N);\n\n    // transpose matrix A and C\n    k = 0;\n    for (j = 0; j < N; ++j) {\n        for (i = 0; i < M; ++i) {\n            amat_mod[k++] = amat[i][j];\n        }\n    }\n    k = 0;\n    for (j = 0; j < N; ++j) {\n        for (i = 0; i < P; ++i) {\n            cmat_mod[k++] = cmat[i][j];\n        }\n    }\n\n    // Fitting\n\n    int LWORK = P + std::min<int>(M, N) + 10 * std::max<int>(M, N);\n    int INFO;\n    double *WORK, *x;\n    memory->allocate(WORK, LWORK);\n    memory->allocate(x, N);\n\n    dgglse_(&M, &N, &P, amat_mod, &M, cmat_mod, &P, fsum2, dvec, x, WORK, &LWORK, &INFO);\n\n    std::cout << \" finished. \" << std::endl;\n\n    f_residual = 0.0;\n    for (i = N - P; i < M; ++i) {\n        f_residual += std::pow(fsum2[i], 2);\n    }\n    std::cout << std::endl << \"  Residual sum of squares for the solution: \" << sqrt(f_residual) << std::endl;\n    std::cout << \"  Fitting error (%) : \"<< std::sqrt(f_residual/f_square) * 100.0 << std::endl;\n\n    // copy fcs to bvec\n\n    for (i = 0; i < N; ++i) {\n        param_out[i] = x[i];\n    }\n\n    memory->deallocate(amat_mod);\n    memory->deallocate(cmat_mod);\n    memory->deallocate(WORK);\n    memory->deallocate(x);\n    memory->deallocate(fsum2);\n}\n\nvoid Fitting::fit_algebraic_constraints(int N, int M, double **amat, double *bvec, \n                                        double *param_out, double *bvec_orig,\n                                        const int maxorder)\n{\n    int i, j;\n    unsigned long k;\n    int nrhs = 1, nrank, INFO, LWORK;\n    int LMIN, LMAX;\n    double rcond = -1.0;\n    double f_square = 0.0;\n    double *WORK, *S, *amat_mod, *fsum2;\n\n    std::cout << \"  Entering fitting routine: SVD with constraints considered algebraically.\" << std::endl;\n\n    LMIN = std::min<int>(M, N);\n    LMAX = std::max<int>(M, N);\n\n    LWORK = 3*LMIN + std::max<int>(2*LMIN, LMAX);\n    LWORK = 2 * LWORK;\n\n    memory->allocate(WORK, LWORK);\n    memory->allocate(S, LMIN);\n\n    // transpose matrix A\n    memory->allocate(amat_mod, M * N);\n    memory->allocate(fsum2, LMAX);\n\n    k = 0;\n    for (j = 0; j < N; ++j) {\n        for (i = 0; i < M; ++i) {\n            amat_mod[k++] = amat[i][j];\n        }\n    }\n    for (i = 0; i < M; ++i) {\n        fsum2[i] = bvec[i];\n        f_square += std::pow(bvec_orig[i], 2);\n    }\n    for (i = M; i < LMAX; ++i) fsum2[i] = 0.0;\n\n    std::cout << \"  SVD has started ... \";\n\n    // Fitting with singular value decomposition\n    dgelss_(&M, &N, &nrhs, amat_mod, &M, fsum2, &LMAX, S, &rcond, &nrank, WORK, &LWORK, &INFO);\n\n    std::cout << \"finished !\" << std::endl << std::endl;\n\n    std::cout << \"  RANK of the matrix = \" << nrank << std::endl;\n    if (nrank < N) error->warn(\"fit_without_constraints\", \n        \"Matrix is rank-deficient. Force constants could not be determined uniquely :(\");\n\n    if (nrank == N) {\n        double f_residual = 0.0;\n        for (i = N; i < M; ++i) {\n            f_residual += std::pow(fsum2[i], 2);\n        }\n        std::cout << std::endl << \"  Residual sum of squares for the solution: \" << sqrt(f_residual) << std::endl;\n        std::cout << \"  Fitting error (%) : \"<< sqrt(f_residual/f_square) * 100.0 << std::endl;\n    }\n\n    int ishift = 0;\n    int iparam = 0;\n    double tmp;\n    int inew, iold;\n\n    for (i = 0; i < maxorder; ++i) {\n        for (j = 0; j < constraint->const_fix[i].size(); ++j) {\n            param_out[constraint->const_fix[i][j].p_index_target + ishift] = constraint->const_fix[i][j].val_to_fix;\n        }\n\n        for (boost::bimap<int, int>::const_iterator it = constraint->index_bimap[i].begin(); \n            it != constraint->index_bimap[i].end(); ++it) {\n                inew = (*it).left + iparam;\n                iold = (*it).right + ishift;\n\n                param_out[iold] = fsum2[inew];\n        }\n\n        for (j = 0; j < constraint->const_relate[i].size(); ++j) {\n            tmp = 0.0;\n\n            for (k = 0; k < constraint->const_relate[i][j].alpha.size(); ++k) {\n                tmp += constraint->const_relate[i][j].alpha[k] * param_out[constraint->const_relate[i][j].p_index_orig[k] + ishift];\n            }\n            param_out[constraint->const_relate[i][j].p_index_target + ishift] = -tmp;\n        }\n\n        ishift += fcs->ndup[i].size();\n        iparam += constraint->index_bimap[i].size();\n    }\n\n    memory->deallocate(WORK);\n    memory->deallocate(S);\n    memory->deallocate(fsum2);\n    memory->deallocate(amat_mod);\n}\n\n\nvoid Fitting::fit_bootstrap(int N, int P, int natmin, int ndata_used, int nmulti, \n                            double **amat, double *bvec, double **cmat, double *dvec)\n{\n    int i, j;\n    unsigned long k, l;\n    int M_Start, M_End;\n    int mset;\n    unsigned int iboot;\n    int M;\n\n    mset = 3 * natmin * nmulti;\n\n    M_Start = 0;\n    M_End = mset * ndata_used;\n\n    M = M_End - M_Start;\n\n\n    std::string file_fcs_bootstrap;\n    file_fcs_bootstrap = files->job_title + \".fcs_bootstrap\";\n\n    std::ofstream ofs_fcs_boot;\n    ofs_fcs_boot.open(file_fcs_bootstrap.c_str(), std::ios::out);\n    if(!ofs_fcs_boot) error->exit(\"fit_bootstrap\", \"cannot open file_fcs_bootstrap\");\n\n    ofs_fcs_boot.setf(std::ios::scientific);\n\n    double f_residual, f_square;\n    double *fsum2;\n    int INFO;\n    double *WORK, *x;\n    double *amat_mod, *cmat_mod;\n    double *const_tmp;\n\n    int *rnd_index;\n    int iloc;\n\n    memory->allocate(x, N);\n    memory->allocate(cmat_mod, P * N);\n    memory->allocate(const_tmp, P);\n\n    std::cout << \"  NSKIP < 0: Bootstrap analysis for error estimation.\" << std::endl;\n    std::cout << \"             The number of trials is NBOOT (=\" << nboot << \")\" << std::endl;\n    std::cout << std::endl;\n    std::cout << \"  Relative errors and FCs are stored in file: \" << file_fcs_bootstrap << std::endl;\n\n    ofs_fcs_boot << \"# Relative Error(%), FCs ...\" ;\n\n    for (i = 0; i < interaction->maxorder; ++i) {\n        ofs_fcs_boot << std::setw(10) << fcs->ndup[i].size();\n    }\n    ofs_fcs_boot << std::endl;\n\n    memory->allocate(fsum2, M);\n    memory->allocate(amat_mod, N * M);\n    memory->allocate(rnd_index, ndata_used);\n\n    int LWORK = P + std::min<int>(M, N) + 100 * std::max<int>(M, N);\n    memory->allocate(WORK, LWORK);\n\n    for (iboot = 0; iboot < nboot; ++iboot) {\n#ifdef _VSL\n        // Use Intel MKL VSL if available\n        viRngUniform(VSL_METHOD_IUNIFORM_STD, stream, ndata_used, rnd_index, 0, ndata_used);\n#else\n        for (i = 0; i < ndata_used; ++i) {\n            rnd_index[i] = std::rand() % ndata_used; // random number uniformly distributed in [0, ndata_used)\n        }\n#endif\n\n        f_square = 0.0;\n        k = 0;\n        for (i = 0; i < ndata_used; ++i) {\n            iloc = rnd_index[i];\n            for (j = iloc * mset; j < (iloc + 1) * mset; ++j) {\n                fsum2[k++] = bvec[j];\n                f_square += std::pow(bvec[j], 2);\n            }\n        }\n        l = 0;\n        for (j = 0; j < N; ++j) {\n            for (i = 0; i < ndata_used; ++i) {\n                iloc = rnd_index[i];\n                for (k = iloc * mset; k < (iloc + 1) * mset; ++k) {\n                    amat_mod[l++] = amat[k][j];\n                }\n            }\n        }\n\n        k = 0;\n        for (j = 0; j < N; ++j) {\n            for (i = 0; i < P; ++i) {\n                cmat_mod[k++] = cmat[i][j];\n            }\n        }\n\n        for (i = 0; i < P; ++i) {\n            const_tmp[i] = dvec[i];\n        }     \n\n        dgglse_(&M, &N, &P, amat_mod, &M, cmat_mod, &P, fsum2, const_tmp, x, WORK, &LWORK, &INFO);\n\n        f_residual = 0.0;\n        for (i = N - P; i < M; ++i) {\n            f_residual += std::pow(fsum2[i], 2);\n        }\n\n        ofs_fcs_boot << 100.0 * std::sqrt(f_residual/f_square);\n\n        for (i = 0; i < N; ++i) {\n            ofs_fcs_boot << std::setw(15) << x[i];\n        }\n        ofs_fcs_boot << std::endl;\n    }\n    ofs_fcs_boot.close();\n\n    memory->deallocate(x);\n    memory->deallocate(fsum2);\n    memory->deallocate(cmat_mod);\n    memory->deallocate(const_tmp);\n    memory->deallocate(amat_mod);\n    memory->deallocate(rnd_index);\n    memory->deallocate(WORK);\n\n    std::cout << \"  Bootstrap analysis finished.\" << std::endl;\n    std::cout << \"  Normal fitting will be performed\" << std::endl;\n}\n\nvoid Fitting::fit_consecutively(int N, int P, const int natmin, const int ndata_used, const int nmulti, const int nskip, \n                                double **amat, double *bvec, double **cmat, double *dvec)\n{\n    int i, j;\n    unsigned long k;\n    int iend;\n    int M_Start, M_End;\n    int mset;\n    int M;\n\n    mset = 3 * natmin * nmulti;\n\n    M_Start = 0;\n\n\n    std::string file_fcs_sequence;\n    file_fcs_sequence = files->job_title + \".fcs_sequence\";\n\n    std::ofstream ofs_fcs_seq;\n    ofs_fcs_seq.open(file_fcs_sequence.c_str(), std::ios::out);\n    if(!ofs_fcs_seq) error->exit(\"fit_consecutively\", \"cannot open file_fcs_sequence\");\n\n    ofs_fcs_seq.setf(std::ios::scientific);\n\n    double f_residual, f_square;\n    double *fsum2;\n    int INFO;\n    double *WORK, *x;\n    double *amat_mod, *cmat_mod;\n    double *const_tmp;\n\n    memory->allocate(x, N);\n    memory->allocate(cmat_mod, P * N);\n    memory->allocate(const_tmp, P);\n\n    std::cout << \"  NSKIP > 0: Fitting will be performed consecutively\" << std::endl;\n    std::cout << \"             with variously changing NEND as NEND = NSTART + i*NSKIP\" << std::endl;\n    std::cout << std::endl;\n    std::cout << \"  Relative errors and FCs will be stored in the file \" << file_fcs_sequence << std::endl;\n\n    ofs_fcs_seq << \"# Relative Error(%), FCS...\" ;\n\n    for (i = 0; i < interaction->maxorder; ++i) {\n        ofs_fcs_seq << std::setw(10) << fcs->ndup[i].size();\n    }\n    ofs_fcs_seq << std::endl;\n\n    for (iend = 1; iend <= ndata_used; iend += nskip) {\n\n        M_End = mset * iend;\n        M = M_End - M_Start;\n\n        memory->allocate(fsum2, M);\n\n        f_square = 0.0;\n        j = 0;\n        for (i = M_Start; i < M_End; ++i) {\n            fsum2[j++] = bvec[i];\n            f_square += std::pow(bvec[i], 2);\n        }\n\n        memory->allocate(amat_mod, M * N);\n\n        // Transpose matrix A\n        k = 0;\n        for (j = 0; j < N; ++j) {\n            for (i = M_Start; i < M_End; ++i) {\n                amat_mod[k++] = amat[i][j];\n            }\n        }\n\n        k = 0;\n        for (j = 0; j < N; ++j) {\n            for (i = 0; i < P; ++i) {\n                cmat_mod[k++] = cmat[i][j];\n            }\n        }\n\n        for (i = 0; i < P; ++i) {\n            const_tmp[i] = dvec[i];\n        }\n\n        // Fitting\n\n        int LWORK = P + std::min<int>(M, N) + 100 * std::max<int>(M, N);\n        memory->allocate(WORK, LWORK);\n\n        dgglse_(&M, &N, &P, amat_mod, &M, cmat_mod, &P, fsum2, const_tmp, x, WORK, &LWORK, &INFO);\n\n        memory->deallocate(amat_mod);\n        memory->deallocate(WORK);\n\n        f_residual = 0.0;\n        for (i = N - P; i < M; ++i) {\n            f_residual += std::pow(fsum2[i], 2);\n        }\n\n        ofs_fcs_seq << 100.0 * std::sqrt(f_residual/f_square);\n\n        for (i = 0; i < N; ++i) {\n            ofs_fcs_seq << std::setw(15) << x[i];\n        }\n        ofs_fcs_seq << std::endl;\n        memory->deallocate(fsum2);\n    }\n\n    for (i = 0; i < N; ++i) {\n        bvec[i] = x[i];\n    }\n\n    memory->deallocate(cmat_mod);\n    memory->deallocate(const_tmp);\n    memory->deallocate(x);\n\n    ofs_fcs_seq.close();\n\n    std::cout << \"  Consecutive fitting finished.\" << std::endl;\n}\n\nvoid Fitting::calc_matrix_elements(const int M, const int N, const int nat, const int natmin, \n                                   const int ndata_fit, const int nmulti, const int maxorder, \n                                   double **u, double **f, double **amat, double *bvec)\n{\n    int i, j;\n    int irow;\n    int ncycle;\n\n    std::cout << \"  Calculation of matrix elements for direct fitting started ... \";\n    for (i = 0; i < M; ++i) {\n        for (j = 0; j < N; ++j) {\n            amat[i][j] = 0.0;\n        }\n        bvec[i] = 0.0;\n    }\n\n    ncycle = ndata_fit * nmulti;\n\n#ifdef _OPENMP\n#pragma omp parallel private(irow, i, j)\n#endif\n    { \n        int *ind;\n        int mm, order, iat, k;\n        int im, idata, iparam;\n        double amat_tmp;\n\n        memory->allocate(ind, maxorder + 1);\n\n#ifdef _OPENMP\n#pragma omp for schedule(guided)\n#endif\n        for (irow = 0; irow < ncycle; ++irow) {\n\n            // generate r.h.s vector B\n            for (i = 0; i < natmin; ++i) {\n                iat = symmetry->map_p2s[i][0];\n                for (j = 0; j < 3; ++j) {\n                    im = 3 * i + j + 3 * natmin * irow;\n                    bvec[im] = f[irow][3 * iat + j];\n                }\n            }\n\n            // generate l.h.s. matrix A\n\n            idata = 3 * natmin * irow;\n            iparam = 0;\n\n            for (order = 0; order < maxorder; ++order) {\n\n                mm = 0;\n\n                for (std::vector<int>::iterator iter = fcs->ndup[order].begin(); iter != fcs->ndup[order].end(); ++iter) {\n                    for (i = 0; i < *iter; ++i) {\n                        ind[0] = fcs->fc_set[order][mm].elems[0];\n                        k = idata + inprim_index(fcs->fc_set[order][mm].elems[0]);\n                        amat_tmp = 1.0;\n                        for (j = 1; j < order + 2; ++j) {\n                            ind[j] = fcs->fc_set[order][mm].elems[j];\n                            amat_tmp *= u[irow][fcs->fc_set[order][mm].elems[j]];\n                        }\n                        amat[k][iparam] -= gamma(order + 2, ind) * fcs->fc_set[order][mm].coef * amat_tmp;\n                        ++mm;\n                    }\n                    ++iparam;\n                }\n            }\n        }\n\n        memory->deallocate(ind);\n\n    }\n\n    std::cout << \"done!\" << std::endl << std::endl;\n}\n\n\nvoid Fitting::calc_matrix_elements_algebraic_constraint(const int M, const int N, const int N_new, const int nat, \n                                                        const int natmin, const int ndata_fit, const int nmulti, \n                                                        const int maxorder, double **u, double **f, double **amat, \n                                                        double *bvec, double *bvec_orig)\n{\n    int i, j;\n    int irow;\n    int ncycle;\n\n    std::cout << \"  Calculation of matrix elements for direct fitting started ... \";\n\n    ncycle = ndata_fit * nmulti;\n\n\n#ifdef _OPENMP\n#pragma omp parallel for private(j)\n#endif\n    for (i = 0; i < M; ++i) {\n        for (j = 0; j < N_new; ++j) {\n            amat[i][j] = 0.0;\n        }\n        bvec[i] = 0.0;\n        bvec_orig[i] = 0.0;\n    }\n\n#ifdef _OPENMP\n#pragma omp parallel private(irow, i, j)\n#endif\n    { \n        int *ind;\n        int mm, order, iat, k;\n        int im, idata, iparam;\n        int ishift;\n        int iold, inew;\n        double amat_tmp;\n        double **amat_orig;\n        double **amat_mod;\n\n        memory->allocate(ind, maxorder + 1);\n        memory->allocate(amat_orig, 3 * natmin, N);\n        memory->allocate(amat_mod, 3 * natmin, N_new);\n\n#ifdef _OPENMP\n#pragma omp for schedule(guided)\n#endif\n        for (irow = 0; irow < ncycle; ++irow) {\n\n            // generate r.h.s vector B\n            for (i = 0; i < natmin; ++i) {\n                iat = symmetry->map_p2s[i][0];\n                for (j = 0; j < 3; ++j) {\n                    im = 3 * i + j + 3 * natmin * irow;\n                    bvec[im] = f[irow][3 * iat + j];\n                    bvec_orig[im] = f[irow][3 * iat + j];\n                }\n            }\n\n            for (i = 0; i < 3 * natmin; ++i) {\n                for (j = 0; j < N; ++j) {\n                    amat_orig[i][j] = 0.0;\n                }\n                for (j = 0; j < N_new; ++j) {\n                    amat_mod[i][j] = 0.0;\n                }\n            }\n\n            // generate l.h.s. matrix A\n\n            idata = 3 * natmin * irow;\n            iparam = 0;\n\n            for (order = 0; order < maxorder; ++order) {\n\n                mm = 0;\n\n                for (std::vector<int>::iterator iter = fcs->ndup[order].begin(); iter != fcs->ndup[order].end(); ++iter) {\n                    for (i = 0; i < *iter; ++i) {\n                        ind[0] = fcs->fc_set[order][mm].elems[0];\n                  //      k = idata + inprim_index(fcs->fc_set[order][mm].elems[0]);\n                        k = inprim_index(ind[0]);\n\n                        amat_tmp = 1.0;\n                        for (j = 1; j < order + 2; ++j) {\n                            ind[j] = fcs->fc_set[order][mm].elems[j];\n                            amat_tmp *= u[irow][fcs->fc_set[order][mm].elems[j]];\n                        }\n                        amat_orig[k][iparam] -= gamma(order + 2, ind) * fcs->fc_set[order][mm].coef * amat_tmp;\n                        ++mm;\n                    }\n                    ++iparam;\n                }\n            }\n\n            ishift = 0;\n            iparam = 0;\n\n            for (order = 0; order < maxorder; ++order) {\n\n                for (i = 0; i < constraint->const_fix[order].size(); ++i) {\n\n                    for (j = 0; j < 3 * natmin; ++j) {\n                        bvec[j + idata] -=  constraint->const_fix[order][i].val_to_fix \n                                         * amat_orig[j][ishift + constraint->const_fix[order][i].p_index_target];\n                    }\n                }\n\n                for (boost::bimap<int, int>::const_iterator it = constraint->index_bimap[order].begin(); \n                    it != constraint->index_bimap[order].end(); ++it) {\n                        inew = (*it).left + iparam;\n                        iold = (*it).right + ishift;\n                     \n                    for (j = 0; j < 3 * natmin; ++j) {\n                            amat_mod[j][inew] = amat_orig[j][iold];\n                   }\n                }\n\n                for (i = 0; i < constraint->const_relate[order].size(); ++i) {\n\n                    iold = constraint->const_relate[order][i].p_index_target + ishift;\n\n                    for (j = 0; j < constraint->const_relate[order][i].alpha.size(); ++j) {\n                       \n                        inew = constraint->index_bimap[order].right.at(constraint->const_relate[order][i].p_index_orig[j]) + iparam;\n                        for (k = 0; k < 3 * natmin; ++k) {\n                            amat_mod[k][inew] -= amat_orig[k][iold] * constraint->const_relate[order][i].alpha[j];\n                        }\n                    }\n                }\n\n                ishift += fcs->ndup[order].size();\n                iparam += constraint->index_bimap[order].size();\n            }\n\n            for (i = 0; i < 3 * natmin; ++i) {\n                for (j = 0; j < N_new; ++j) {\n                    amat[i + idata][j] = amat_mod[i][j];\n                }\n            }\n\n        }\n\n        memory->deallocate(ind);\n        memory->deallocate(amat_orig);\n        memory->deallocate(amat_mod);\n    }\n\n    std::cout << \"done!\" << std::endl << std::endl;\n}\n\n\nint Fitting::inprim_index(const int n)\n{\n    int in;\n    int atmn = n / 3;\n    int crdn = n % 3;\n\n    for (int i = 0; i < symmetry->natmin; ++i) {\n        if (symmetry->map_p2s[i][0] == atmn) {\n            in = 3 * i + crdn;\n            break;\n        }\n    }\n    return in;\n}\n\ndouble Fitting::gamma(const int n, const int *arr)\n{\n    int *arr_tmp, *nsame;\n    int i;\n    int ind_front, nsame_to_front;\n\n    memory->allocate(arr_tmp, n);\n    memory->allocate(nsame, n);\n\n    for (i = 0; i < n; ++i) {\n        arr_tmp[i] = arr[i];\n        nsame[i] = 0;\n    }\n\n    ind_front = arr[0];\n    nsame_to_front = 1;\n\n    interaction->insort(n, arr_tmp);\n\n    int nuniq = 1;\n    int iuniq = 0;\n\n    nsame[0] = 1;\n\n    for (i = 1; i < n; ++i) {\n        if (arr_tmp[i] == arr_tmp[i-1]) {\n            ++nsame[iuniq];\n        } else {\n            ++nsame[++iuniq];\n            ++nuniq;\n        }\n\n        if (arr[i] == ind_front) ++nsame_to_front;\n    }\n\n    int denom = 1;\n\n    for (i = 0; i < nuniq; ++i) {\n        denom *= factorial(nsame[i]);\n    }\n\n    memory->deallocate(arr_tmp);\n    memory->deallocate(nsame);\n\n    return static_cast<double>(nsame_to_front) / static_cast<double>(denom);\n}\n\nint Fitting::factorial(const int n)\n{\n    if (n == 1 || n == 0) {\n        return 1;\n    } else {\n        return n * factorial(n - 1);\n    }\n}\n\n#ifdef _USE_EIGEN\nint Fitting::getRankEigen(const int m, const int n, double **mat)\n{\n    using namespace Eigen;\n\n    MatrixXd mat_tmp(m, n);\n\n    int i, j;\n\n    for (i = 0; i < m; ++i) {\n        for (j = 0; j < n; ++j) {\n            mat_tmp(i,j) = mat[i][j];\n        }\n    }\n    ColPivHouseholderQR<MatrixXd> qr(mat_tmp);\n    return qr.rank();\n}\n#endif\n\nint Fitting::rankQRD(const int m, const int n, double *mat, const double tolerance)\n{\n    // Return the rank of matrix mat revealed by the column pivoting QR decomposition\n    // The matrix mat is destroyed.\n\n    int m_ = m;\n    int n_ = n;\n\n    int LDA = m_;\n\n    int LWORK = 10 * n_;\n    int INFO;\n    int *JPVT;\n    double *WORK, *TAU;\n\n    int nmin = std::min<int>(m_, n_);\n\n    memory->allocate(JPVT, n_);\n    memory->allocate(WORK, LWORK);\n    memory->allocate(TAU, nmin);\n\n    for (int i = 0; i < n_; ++i) JPVT[i] = 0;\n\n    dgeqp3_(&m_, &n_, mat, &LDA, JPVT, TAU, WORK, &LWORK, &INFO);\n\n    memory->deallocate(JPVT);\n    memory->deallocate(WORK);\n    memory->deallocate(TAU);\n\n    if (std::abs(mat[0]) < eps) return 0;\n\n    double **mat_tmp;\n    memory->allocate(mat_tmp, m_, n_);\n\n    unsigned long k = 0;\n\n    for (int j = 0; j < n_; ++j) {\n        for (int i = 0; i < m_; ++i) {\n            mat_tmp[i][j] = mat[k++];\n        }\n    }\n\n    int nrank = 0;\n    for (int i = 0; i < nmin; ++i) {\n        if (std::abs(mat_tmp[i][i]) > tolerance * std::abs(mat[0])) ++nrank;\n    }\n\n    memory->deallocate(mat_tmp);\n\n    return nrank;\n}\n\nint Fitting::rankSVD(const int m, const int n, double *mat, const double tolerance)\n{\n    int i;\n    int m_ = m;\n    int n_ = n;\n\n    int LWORK = 10 * m;\n    int INFO;\n    int *IWORK;\n    int ldu = 1, ldvt = 1;\n    double *s, *WORK;\n    double u[1], vt[1];\n\n    int nmin = std::min<int>(m, n);\n\n    memory->allocate(IWORK, 8 * nmin);\n    memory->allocate(WORK, LWORK);\n    memory->allocate(s, nmin);\n\n    char mode[]  = \"N\";\n\n    dgesdd_(mode, &m_, &n_, mat, &m_, s, u, &ldu, vt, &ldvt, WORK, &LWORK, IWORK, &INFO); \n\n    int rank = 0;\n    for (i = 0; i < nmin; ++i) {\n        if (s[i] > s[0] * tolerance) ++rank;\n    }\n\n    memory->deallocate(WORK);\n    memory->deallocate(IWORK);\n    memory->deallocate(s);\n\n    return rank;\n}\n\nint Fitting::rankSVD2(const int m_in, const int n_in, double **mat, const double tolerance) \n{\n    // Reveal the rank of matrix mat without destroying the matrix elements\n\n    int i, j, k;\n    double *arr;\n\n    int m = m_in;\n    int n = n_in;\n\n    memory->allocate(arr, m*n);\n\n    k = 0;\n\n    for (j = 0; j < n; ++j ) {\n        for (i = 0; i < m; ++i) {\n            arr[k++] = mat[i][j];\n        }\n    }\n\n    int LWORK = 10 * m;\n    int INFO;\n    int *IWORK;\n    int ldu = 1, ldvt = 1;\n    double *s, *WORK;\n    double u[1], vt[1];\n\n    int nmin = std::min<int>(m, n);\n\n    memory->allocate(IWORK, 8 * nmin);\n    memory->allocate(WORK, LWORK);\n    memory->allocate(s, nmin);\n\n    char mode[]  = \"N\";\n\n    dgesdd_(mode, &m, &n, arr, &m, s, u, &ldu, vt, &ldvt, WORK, &LWORK, IWORK, &INFO); \n\n    int rank = 0;\n    for (i = 0; i < nmin; ++i){\n        if (s[i] > s[0] * tolerance) ++rank;\n    }\n\n    memory->deallocate(IWORK);\n    memory->deallocate(WORK);\n    memory->deallocate(s);\n    memory->deallocate(arr);\n\n    return rank;\n}\n\n/*\nvoid Fitting::calc_covariance(int m, int n)\n{\nEigen::MatrixXd Atmp(m, n), Hess(n, n);\nint i, j;\n\nfor (i = 0; i < m; ++i){\nfor (j = 0; j < n; ++j){\nAtmp(i,j) = amat[i][j];\n}\n}\n\nHess = (Atmp.transpose()*Atmp).inverse();\n\nfor (i = 0; i < n; ++i){\nfor (j = 0; j < n; ++j){\nvarcovar[i][j] = Hess(i, j);\n}\n}\n\n}\n*/\n", "meta": {"hexsha": "7a453d8f9ffe31c4dc3b30fff5d499d5c1692c12", "size": 39173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "alm/fitting.cpp", "max_stars_repo_name": "dlnguyen/alamode", "max_stars_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "alm/fitting.cpp", "max_issues_repo_name": "dlnguyen/alamode", "max_issues_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alm/fitting.cpp", "max_forks_repo_name": "dlnguyen/alamode", "max_forks_repo_head_hexsha": "f99d333262489f28a3ef4838dfbe3147dc239261", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4480755265, "max_line_length": 132, "alphanum_fraction": 0.4970770684, "num_tokens": 11731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4414904446546489}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/complex.h>\n#include <pybind11/numpy.h>\n\n#include <vector>\n#include <string>\n#include <cstdarg>\n#include <cstring>\n#include <cstddef>\n#include <iterator>\n\n#include <boost/lexical_cast.hpp>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Delaunay_mesh_face_base_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n\nnamespace py = pybind11;\n\nusing K = CGAL::Exact_predicates_inexact_constructions_kernel;\nusing Vb = CGAL::Triangulation_vertex_base_with_info_2<unsigned int, K>;\nusing Tds = CGAL::Triangulation_data_structure_2<Vb>;\nusing DT = CGAL::Delaunay_triangulation_2<K, Tds>;\n\nusing Point = K::Point_2;\nusing Vertex_handle = DT::Vertex_handle;\nusing Vi = DT::Finite_vertices_iterator;\n\n\ntemplate <typename T>\nclass TypedInputIterator\n{\npublic:\n    using iterator_category = std::input_iterator_tag;\n    using difference_type = std::ptrdiff_t;\n    using value_type = T;\n    using pointer = T*;\n    using reference = T&;\n\n    explicit TypedInputIterator(py::iterator& py_iter) :\n        py_iter_(py_iter)\n    {\n    }\n\n    explicit TypedInputIterator(py::iterator&& py_iter) :\n        py_iter_(py_iter)\n    {\n    }\n\n    value_type operator*()\n    {\n        return (*py_iter_).template cast<value_type>();\n    }\n\n    TypedInputIterator operator++(int)\n    {\n        auto copy = *this;\n        ++py_iter_;\n        return copy;\n    }\n\n    TypedInputIterator& operator++()\n    {\n        ++py_iter_;\n        return *this;\n    }\n\n    bool operator!=(TypedInputIterator &rhs)\n    {\n        return py_iter_ != rhs.py_iter_;\n    }\n\n    bool operator==(TypedInputIterator &rhs)\n    {\n        return py_iter_ == rhs.py_iter_;\n    }\n\nprivate:\n    py::iterator py_iter_;\n};\n\n\nPYBIND11_MODULE(delaunay_class, m)\n{\n    py::class_<Point>(m, \"Point\")\n            .def(py::init<int, int>(),  py::arg(\"x\"), py::arg(\"y\"))\n            .def(py::init<double, double>(), py::arg(\"x\"), py::arg(\"y\"))\n            .def_property_readonly(\"x\", &Point::x)\n            .def_property_readonly(\"y\", &Point::y)\n            .def(\"__repr__\",\n            [](const Point &p) {\n                std::string r(\"Point(\");\n                r += boost::lexical_cast<std::string>(p.x());\n                r += \", \";\n                r += boost::lexical_cast<std::string>(p.y());\n                r += \")\";\n                return r;\n            })\n            ;\n\n    py::class_<Vertex_handle>(m, \"VertexHandle\")\n        .def_property_readonly(\n        \"point\",\n        [](const Vertex_handle& vertex_handle)\n        {\n            return vertex_handle->point();\n        })\n        ;\n\n        py::class_<DT>(m, \"DelaunayTriangulation\")\n\n            .def(py::init())\n\n            .def(\"insert\", [](DT & dt, const std::vector<double> & p) {\n                  std::vector< std::pair<Point,unsigned> > points;\n                  int num_points = p.size()/2;\n                  // start adding at the end of the current table\n                  int start = dt.number_of_vertices();\n                  for(std::size_t i = 0; i < num_points; ++i)\n                  {\n                    // add index information to form face table later\n                     points.push_back( std::make_pair( Point(p[i*2+0],p[i*2+1]), start) );\n                     start += 1;\n                  }\n                  return dt.insert(points.begin(),points.end());\n                })\n\n            .def(\"remove\", [](DT & dt, const std::vector<unsigned int> & to_remove) {\n                    int num_to_remove= to_remove.size();\n                    std::vector<Vertex_handle> handles;\n                    for (Vi vi = dt.finite_vertices_begin(); vi != dt.finite_vertices_end(); vi++){\n                        handles.push_back(vi);\n                    }\n                    for(std::size_t i=0; i < num_to_remove; ++i){\n                        dt.remove(handles[to_remove[i]]);\n                    }\n                    return dt;\n                })\n\n            .def(\"move\", [](DT & dt, const std::vector<unsigned int> & to_move, const std::vector<double> & new_positions){\n                    std::vector<Vertex_handle> handles;\n                    std::vector<Point> new_pos;\n                    int num_to_move= to_move.size();\n                    // store all vertex handles\n                    for (Vi vi = dt.finite_vertices_begin(); vi != dt.finite_vertices_end(); vi++){\n                        handles.push_back(vi);\n                    }\n                    // store new positions as a vector of Point\n                    for(std::size_t i = 0; i < num_to_move; ++i)\n                    {\n                       new_pos.push_back(Point(new_positions[2*i], new_positions[2*i+1]));\n                    }\n                    //\n                    for(std::size_t i = 0; i < num_to_move; ++i)\n                    {\n                       dt.move( handles[to_move[i]], new_pos[i] );\n                    }\n                    return dt;\n                    })\n\n            .def(\"number_of_vertices\", &DT::number_of_vertices)\n\n            .def(\"number_of_faces\", [](DT & dt){\n                int count=0;\n                for(DT::Finite_faces_iterator fit = dt.finite_faces_begin();\n                fit != dt.finite_faces_end(); ++fit) {\n                    count += 1;\n                }\n                    return count;\n                })\n\n            .def(\"finite_vertices\", [](DT & dt) -> py::iterator\n             {\n                 return py::make_iterator(dt.finite_vertices_begin(), dt.finite_vertices_end());\n             })\n\n            .def(\"get_finite_cells\", [](DT & dt)\n            {\n              // ouput the face table\n              // YOU MUST CALL get_finite_vertices before if any incremental operations\n              // were performed\n              std::vector<int> faces;\n              faces.resize(dt.number_of_faces()*3);\n\n              int i=0;\n              for(DT::Finite_faces_iterator fit = dt.finite_faces_begin();\n                fit != dt.finite_faces_end(); ++fit) {\n\n                DT::Face_handle face = fit;\n                faces[i*3]=face->vertex(0)->info();\n                faces[i*3+1]=face->vertex(1)->info();\n                faces[i*3+2]=face->vertex(2)->info();\n                i+=1;\n              }\n              ssize_t              soint      = sizeof(int);\n              ssize_t              num_faces = faces.size()/3;\n              ssize_t              ndim      = 2;\n              std::vector<ssize_t> shape     = {num_faces, 3};\n              std::vector<ssize_t> strides   = {soint*3, soint};\n\n              // return 2-D NumPy array\n              return py::array(py::buffer_info(\n                faces.data(),                           /* data as contiguous array  */\n                sizeof(int),                          /* size of one scalar        */\n                py::format_descriptor<int>::format(), /* data type                 */\n                2,                                    /* number of dimensions      */\n                shape,                                   /* shape of the matrix       */\n                strides                                  /* strides for each axis     */\n              ));\n            })\n\n            .def(\"get_finite_vertices\", [](DT & dt)\n             {\n               // ouput the vertices\n               std::vector<double> vertices;\n               vertices.resize(dt.number_of_vertices()*2);\n\n               int i=0;\n               for(DT::Finite_vertices_iterator fit = dt.finite_vertices_begin();\n                 fit != dt.finite_vertices_end(); ++fit) {\n\n                 Vertex_handle vertex = fit;\n                 // critical! update the point index table so faces comes out correctly\n                 vertex->info() = i;\n                 vertices[i*2]=vertex->point().x();\n                 vertices[i*2+1]=vertex->point().y();\n                 i+=1;\n               }\n               ssize_t              sdble   = sizeof(double);\n               ssize_t              num_vertices = vertices.size()/2;\n               ssize_t              ndim      = 2;\n               std::vector<ssize_t> shape     = {num_vertices, 2};\n               std::vector<ssize_t> strides   = {sdble*2, sdble};\n\n               // return 2-D NumPy array\n               return py::array(py::buffer_info(\n                 vertices.data(),                           /* data as contiguous array  */\n                 sizeof(double),                          /* size of one scalar        */\n                 py::format_descriptor<double>::format(), /* data type                 */\n                 2,                                    /* number of dimensions      */\n                 shape,                                   /* shape of the matrix       */\n                 strides                                  /* strides for each axis     */\n               ));\n             })\n            ;\n\n\n    py::class_<DT::Finite_vertices_iterator::value_type>(m, \"Vertex\")\n            .def_property_readonly(\n                \"point\", [](DT::Finite_vertices_iterator::value_type& vertex)\n                {\n                    return vertex.point();\n                }\n            )\n            ;\n\n    py::class_<DT::Finite_faces_iterator::value_type>(m, \"Face\")\n            .def(\"vertex_handle\",\n                [](DT::Finite_faces_iterator::value_type& face, int index)\n                {\n                    return face.vertex(index);\n                },\n                py::arg(\"index\")\n            )\n            ;\n\n}\n", "meta": {"hexsha": "9bb2fe00667fc1ed025cddc921dae25c80c01df7", "size": 9576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SeismicMesh/generation/cpp/delaunay_class.cpp", "max_stars_repo_name": "WPringle/SeismicMesh", "max_stars_repo_head_hexsha": "9e73aac63ecc4411163dc4093941af946cffae37", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SeismicMesh/generation/cpp/delaunay_class.cpp", "max_issues_repo_name": "WPringle/SeismicMesh", "max_issues_repo_head_hexsha": "9e73aac63ecc4411163dc4093941af946cffae37", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SeismicMesh/generation/cpp/delaunay_class.cpp", "max_forks_repo_name": "WPringle/SeismicMesh", "max_forks_repo_head_hexsha": "9e73aac63ecc4411163dc4093941af946cffae37", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4666666667, "max_line_length": 123, "alphanum_fraction": 0.4695071011, "num_tokens": 2033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4414904388651884}}
{"text": "#include <iostream>\n#include <vector>\n#include <cstdio>\n#include <cstdlib>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n\nusing std::vector;\nusing namespace boost;\n\n//a class to hold the coordinates of the straight line embedding\nstruct coord_t\n{\n    std::size_t x;\n    std::size_t y;\n};\n\n\nvector<int> check_k33{ 4060, 13242, 15481, 15751, 21878, 23221, 23371, 26323, 26413, 26862}; // all masks of k33 graph with 6 vertexes\nvector<int> check_k5{ 5871, 11127, 19899, 29149, 32286, 32736};                             // all masks of k5 graph with 6 vertexes\n\nint mask_to_int(std::string &mask) {\n    int ans = 0;\n    for (auto c : mask) {\n        ans <<= 1;\n        if (c == '1')\n            ans += 1;\n    }\n    return ans;\n}\nbool hard_check_k5(std::string mask) {\n    vector<int> deg(6, 0);\n    int cur = 0;\n    for (int i = 1; i < 6; i++) {\n        for (int j = 0; j < i; j++) {\n            if (mask[cur] == '1') {\n                deg[i]++;\n                deg[j]++;\n            }\n            cur++;\n        }\n    }\n\n    int counter = 0;\n    for(auto v : deg) {\n        if (v == 4) \n            counter++;\n    }\n    if (counter == 5) {\n        return true;\n    }  else\n        return false;\n}\n\nbool chek_k5_or_k33(int mask) {\n    for (int check_mask : check_k5) {\n        if ((check_mask & mask) == check_mask)\n            return true;\n    }\n    for (int check_mask : check_k33) {\n        if ((check_mask & mask) == check_mask)\n            return true;\n    }\n    return false;\n}\n\nvoid boost_foo(std::string mask, int size, bool &flag);\n\nvoid solve() {\n    int t;\n    bool flag, flag1;\n    std::string mask, tmp;\n    std::getline(std::cin, tmp);\n    t = atoi(tmp.c_str());\n    for (int i = 0; i < t; ++i) {\n        std::getline(std::cin, mask);\n        size_t size = mask.size();\n        boost_foo(mask, 6, flag);\n        if (size < 10) { // less then 5 vertex\n            //std::cout << \"YES\\n\";\n        } else if (size == 10) {  // when 5 vertex\n            if (mask_to_int(mask) == 1023) { // 1111111111 -- K_{5}\n                //std::cout << \"NO\\n\";\n            } else {\n                //std::cout << \"YES\\n\";\n            }\n        } else if (size == 15) { // when 6 vertex\n            if (chek_k5_or_k33(mask_to_int(mask))) {\n                flag1 = false;//std::cout << \"NO\\n\";\n            } else {\n                flag1 = true;//std::cout << \"YES\\n\";\n            }\n        }\n        if (flag != flag1) {\n            std::cout << \"Error in mask: \" << mask << \"\\n\";\n            std::cout << \"Expected: \";\n            if (flag)\n                std::cout << \"YES\";\n            else\n                std::cout << \"NO\";\n            std::cout << \"\\n\";\n        }\n    }\n}\n\nvoid boost_foo(std::string mask, int size, bool &flag) {\n    typedef adjacency_list<vecS,\n            vecS,\n            undirectedS,\n            property<vertex_index_t, int>\n    > graph;\n\n    graph g(size);\n    int k = 0;\n    for (int i = 1; i < size; i++) {\n        for (int j = 0; j < i; j++) {\n            if (mask[k] == '1') {\n                add_edge(i, j, g);\n            }\n            k++;\n        }\n    }\n\n\n    if (boyer_myrvold_planarity_test(g))\n        flag = true;//std::cout << \"YES --- \";\n    else\n        flag = false;//std::cout << \"NO --- \";\n}\nint main() {\n    freopen(\"planaritycheck.in\", \"r\", stdin);\n    freopen(\"planaritycheck.out\", \"w\", stdout);\n    solve();\n\n    return 0;\n}\n\n\n", "meta": {"hexsha": "6c741c8563453617a8bcf6d9cdada00ca6c752da", "size": 3423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "discrete_math/term_3/lab_2/d.cpp", "max_stars_repo_name": "RevealMind/itmo", "max_stars_repo_head_hexsha": "fc076d385fd46c50056cfb72d1990e10a1369f2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-07-15T10:42:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T08:40:56.000Z", "max_issues_repo_path": "discrete_math/term_3/lab_2/d.cpp", "max_issues_repo_name": "RevealMind/itmo", "max_issues_repo_head_hexsha": "fc076d385fd46c50056cfb72d1990e10a1369f2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-05-09T02:35:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T13:19:03.000Z", "max_forks_repo_path": "discrete_math/term_3/lab_2/d.cpp", "max_forks_repo_name": "RevealMind/itmo", "max_forks_repo_head_hexsha": "fc076d385fd46c50056cfb72d1990e10a1369f2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-18T07:57:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T07:57:31.000Z", "avg_line_length": 24.6258992806, "max_line_length": 134, "alphanum_fraction": 0.4718083552, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4414904388651884}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_FAST_RSQRT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_FAST_RSQRT_HPP_INCLUDED\n\n#include <boost/simd/arithmetic/functions/fast_rsqrt.hpp>\n#include <boost/simd/include/functions/scalar/bitwise_cast.hpp>\n#include <boost/simd/include/functions/scalar/rsqrt.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT          ( fast_rsqrt_\n                                    , tag::cpu_\n                                    , (A0)\n                                    , (scalar_< single_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 a0) const\n    {\n      typedef typename dispatch::meta::as_integer<A0>::type i_t;\n\n      // Quake III Arena RSQRT approximation\n      i_t x = bitwise_cast<i_t>(a0);\n      i_t y = 0x5f3759df - (x >> 1);\n\n      // make negative values be NaN\n      y |= x >> (sizeof(i_t)*CHAR_BIT-1);\n\n      A0 x2 = a0 * 0.5f;\n      A0 y2 = bitwise_cast<A0>(y);\n\n      // Newton-Rhapson refinement steps: 2 NR steps for precision purpose\n      y2    = y2 * ( 1.5f - ( x2 * y2 * y2 ) );\n      return  y2 * ( 1.5f - ( x2 * y2 * y2 ) );\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT          ( fast_rsqrt_\n                                    , tag::cpu_\n                                    , (A0)\n                                    , (scalar_< floating_<A0> >)\n                                    )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 a0) const\n    {\n      return simd::rsqrt(a0);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "6581fcd845cea6900ab0e26922aedc3b74677be9", "size": 2210, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/fast_rsqrt.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/fast_rsqrt.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/scalar/fast_rsqrt.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.53125, "max_line_length": 80, "alphanum_fraction": 0.5171945701, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4414820301190715}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Authors: Fabian Castelli, Karlsruhe Institute of Technology (KIT) \n */ \n\n\n\n// 首先我们包括本教程所需的deal.II库的典型头文件。\n\n#include <deal.II/base/function.h> \n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/base/vectorization.h> \n\n#include <deal.II/dofs/dof_accessor.h> \n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/mapping_q_generic.h> \n\n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_out.h> \n#include <deal.II/grid/manifold_lib.h> \n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/tria_accessor.h> \n#include <deal.II/grid/tria_iterator.h> \n\n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/precondition.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/vector.h> \n\n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/vector_tools.h> \n\n// 特别是，我们需要包括无矩阵框架的头文件。\n\n#include <deal.II/matrix_free/fe_evaluation.h> \n#include <deal.II/matrix_free/matrix_free.h> \n#include <deal.II/matrix_free/operators.h> \n#include <deal.II/matrix_free/tools.h> \n\n// 由于我们要使用几何多网格预处理程序，所以我们还需要多级头文件。\n\n#include <deal.II/multigrid/mg_coarse.h> \n#include <deal.II/multigrid/mg_constrained_dofs.h> \n#include <deal.II/multigrid/mg_matrix.h> \n#include <deal.II/multigrid/mg_smoother.h> \n#include <deal.II/multigrid/mg_tools.h> \n#include <deal.II/multigrid/mg_transfer_matrix_free.h> \n#include <deal.II/multigrid/multigrid.h> \n\n// 最后是一些常用的C++头文件，用于输入和输出。\n\n#include <fstream> \n#include <iostream> \n\nnamespace Step66 \n{ \n  using namespace dealii; \n\n//  @sect3{Matrix-free JacobianOperator}  \n\n// 在开始时，我们定义了雅各布系数的无矩阵算子。作为指导，我们遵循教程  step-37  和  step-48  ，其中广泛记录了  MatrixFreeOperators::Base  类的精确接口。\n\n// 由于我们希望将雅各布（Jacobian）作为系统矩阵使用，并将其传递给线性求解器以及多级预处理类，我们从 MatrixFreeOperators::Base 类派生出 <code>JacobianOperator</code> 类，这样我们就有了正确的接口。我们需要从基类中覆盖的两个函数是 MatrixFreeOperators::Base::apply_add() 和 MatrixFreeOperators::Base::compute_diagonal() 函数。为了允许用浮动精度进行预处理，我们将数字类型定义为模板参数。\n\n// 正如在介绍中提到的，我们需要在最后一个牛顿步骤 $u_h^n$ 中评估雅各布 $F'$ ，以便计算牛顿更新 $s_h^n$ 。为了获得最后一个牛顿步骤 $u_h^n$ 的信息，我们的做法与 step-37 基本相同，在使用无矩阵算子之前，我们将一个系数函数的值存储在一个表中 <code>nonlinear_values</code> 。我们在这里实现的不是一个函数  <code>evaluate_coefficient()</code>  ，而是一个函数  <code>evaluate_newton_step()</code>  。\n\n// 作为 <code>JacobianOperator</code> 的额外私有成员函数，我们实现了 <code>local_apply()</code> 和 <code>local_compute_diagonal()</code> 函数。第一个是矩阵-向量应用的实际工作函数，我们在 <code>apply_add()</code> 函数中将其传递给 MatrixFree::cell_loop() 。后面一个是计算对角线的工作函数，我们把它传递给 MatrixFreeTools::compute_diagonal() 函数。\n\n// 为了提高源代码的可读性，我们进一步为FEEvaluation对象定义了一个别名。\n\n  template <int dim, int fe_degree, typename number> \n  class JacobianOperator \n    : public MatrixFreeOperators:: \n        Base<dim, LinearAlgebra::distributed::Vector<number>> \n  { \n  public: \n    using value_type = number; \n\n    using FECellIntegrator = \n      FEEvaluation<dim, fe_degree, fe_degree + 1, 1, number>; \n\n    JacobianOperator(); \n\n    virtual void clear() override; \n\n    void evaluate_newton_step( \n      const LinearAlgebra::distributed::Vector<number> &newton_step); \n\n    virtual void compute_diagonal() override; \n\n  private: \n    virtual void apply_add( \n      LinearAlgebra::distributed::Vector<number> &      dst, \n      const LinearAlgebra::distributed::Vector<number> &src) const override; \n\n    void \n    local_apply(const MatrixFree<dim, number> &                   data, \n                LinearAlgebra::distributed::Vector<number> &      dst, \n                const LinearAlgebra::distributed::Vector<number> &src, \n                const std::pair<unsigned int, unsigned int> &cell_range) const; \n\n    void local_compute_diagonal(FECellIntegrator &integrator) const; \n\n    Table<2, VectorizedArray<number>> nonlinear_values; \n  }; \n\n//  <code>JacobianOperator</code> 的构造函数只是调用基类 MatrixFreeOperators::Base, 的构造函数，而基类本身就是派生于Subscriptor类。\n\n  template <int dim, int fe_degree, typename number> \n  JacobianOperator<dim, fe_degree, number>::JacobianOperator() \n    : MatrixFreeOperators::Base<dim, \n                                LinearAlgebra::distributed::Vector<number>>() \n  {} \n\n//  <code>clear()</code> 函数重置了保存非线性值的表格，并调用基类的 <code>clear()</code> 函数。\n\n  template <int dim, int fe_degree, typename number> \n  void JacobianOperator<dim, fe_degree, number>::clear() \n  { \n    nonlinear_values.reinit(0, 0); \n    MatrixFreeOperators::Base<dim, LinearAlgebra::distributed::Vector<number>>:: \n      clear(); \n  } \n\n//  @sect4{Evaluation of the old Newton step}  \n\n// 下面的  <code>evaluate_newton_step()</code>  函数是基于  step-37  的  <code>evaluate_coefficient()</code>  函数。然而，它并不评估一个函数对象，而是评估一个代表有限元函数的向量，即雅各布系数所需的最后一个牛顿步骤。因此，我们设置了一个FEEvaluation对象，用 FEEvaluation::read_dof_values_plain() 和 FEEvaluation::evaluate() 函数评估正交点的有限元函数。我们将有限元函数的评估值直接存储在 <code>nonlinear_values</code> 表中。\n\n//这样做会很好，在 <code>local_apply()</code> 函数中我们可以使用存储在表中的值来应用矩阵-向量乘积。然而，我们也可以在这个阶段优化雅各布系数的实现。我们可以直接评估非线性函数 <code>std::exp(newton_step[q])</code> 并将这些值存储在表中。这就跳过了在每次调用 <code>vmult()</code> 函数时对非线性的所有评估。\n\n  template <int dim, int fe_degree, typename number> \n  void JacobianOperator<dim, fe_degree, number>::evaluate_newton_step( \n    const LinearAlgebra::distributed::Vector<number> &newton_step) \n  { \n    const unsigned int n_cells = this->data->n_cell_batches(); \n    FECellIntegrator   phi(*this->data); \n\n    nonlinear_values.reinit(n_cells, phi.n_q_points); \n\n    for (unsigned int cell = 0; cell < n_cells; ++cell) \n      { \n        phi.reinit(cell); \n        phi.read_dof_values_plain(newton_step); \n        phi.evaluate(EvaluationFlags::values); \n\n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          { \n            nonlinear_values(cell, q) = std::exp(phi.get_value(q)); \n          } \n      } \n  } \n\n//  @sect4{Nonlinear matrix-free operator application}  \n\n// 现在在  <code>local_apply()</code>  函数中，实际上实现了系统矩阵的单元格动作，我们可以使用存储在表  <code>nonlinear_values</code>  中的最后一个牛顿步骤的信息。这个函数的其余部分与  step-37  中的基本相同。我们设置 FEEvaluation 对象，收集并评估输入向量的值和梯度  <code>src</code>  ，根据雅各布的形式提交值和梯度，最后调用  FEEvaluation::integrate_scatter()  进行单元积分，将局部贡献分配到全局向量  <code> dst</code>  。\n\n  template <int dim, int fe_degree, typename number> \n  void JacobianOperator<dim, fe_degree, number>::local_apply( \n    const MatrixFree<dim, number> &                   data, \n    LinearAlgebra::distributed::Vector<number> &      dst, \n    const LinearAlgebra::distributed::Vector<number> &src, \n    const std::pair<unsigned int, unsigned int> &     cell_range) const \n  { \n    FECellIntegrator phi(data); \n\n    for (unsigned int cell = cell_range.first; cell < cell_range.second; ++cell) \n      { \n        AssertDimension(nonlinear_values.size(0), \n                        phi.get_matrix_free().n_cell_batches()); \n        AssertDimension(nonlinear_values.size(1), phi.n_q_points); \n\n        phi.reinit(cell); \n\n        phi.gather_evaluate(src, \n                            EvaluationFlags::values | \n                              EvaluationFlags::gradients); \n\n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          { \n            phi.submit_value(-nonlinear_values(cell, q) * phi.get_value(q), q); \n            phi.submit_gradient(phi.get_gradient(q), q); \n          } \n\n        phi.integrate_scatter(EvaluationFlags::values | \n                                EvaluationFlags::gradients, \n                              dst); \n      } \n  } \n\n// 接下来我们使用 MatrixFree::cell_loop() 对所有单元进行实际循环，计算单元对矩阵-向量积的贡献。\n\n  template <int dim, int fe_degree, typename number> \n  void JacobianOperator<dim, fe_degree, number>::apply_add( \n    LinearAlgebra::distributed::Vector<number> &      dst, \n    const LinearAlgebra::distributed::Vector<number> &src) const \n  { \n    this->data->cell_loop(&JacobianOperator::local_apply, this, dst, src); \n  } \n\n//  @sect4{Diagonal of the JacobianOperator}  \n\n// 用于计算对角线的内部工作函数  <code>local_compute_diagonal()</code>  与上述工作函数  <code>local_apply()</code>  类似。然而，作为主要区别，我们不从输入向量中读取数值，也不将任何局部结果分配给输出向量。相反，唯一的输入参数是使用的FEEvaluation对象。\n\n  template <int dim, int fe_degree, typename number> \n  void JacobianOperator<dim, fe_degree, number>::local_compute_diagonal( \n    FECellIntegrator &phi) const \n  { \n    AssertDimension(nonlinear_values.size(0), \n                    phi.get_matrix_free().n_cell_batches()); \n    AssertDimension(nonlinear_values.size(1), phi.n_q_points); \n\n    const unsigned int cell = phi.get_current_cell_index(); \n\n    phi.evaluate(EvaluationFlags::values | EvaluationFlags::gradients); \n\n    for (unsigned int q = 0; q < phi.n_q_points; ++q) \n      { \n        phi.submit_value(-nonlinear_values(cell, q) * phi.get_value(q), q); \n        phi.submit_gradient(phi.get_gradient(q), q); \n      } \n\n    phi.integrate(EvaluationFlags::values | EvaluationFlags::gradients); \n  } \n\n// 最后我们覆盖  MatrixFreeOperators::Base::compute_diagonal()  的基类的  <code>JacobianOperator</code>  的函数。虽然这个函数的名字表明只是计算对角线，但这个函数的作用更大。因为我们实际上只需要矩阵对角线元素的逆值，用于多网格预处理器的切比雪夫平滑器，我们计算对角线并存储逆值元素。因此我们首先初始化 <code>inverse_diagonal_entries</code>  。然后我们通过将工作函数 <code>local_compute_diagonal()</code> 传递给 MatrixFreeTools::compute_diagonal() 函数来计算对角线。最后，我们在对角线上循环，用手反转这些元素。注意，在这个循环过程中，我们捕捉受限的DOF，并手动将其设置为1。\n\n  template <int dim, int fe_degree, typename number> \n  void JacobianOperator<dim, fe_degree, number>::compute_diagonal() \n  { \n    this->inverse_diagonal_entries.reset( \n      new DiagonalMatrix<LinearAlgebra::distributed::Vector<number>>()); \n    LinearAlgebra::distributed::Vector<number> &inverse_diagonal = \n      this->inverse_diagonal_entries->get_vector(); \n    this->data->initialize_dof_vector(inverse_diagonal); \n\n    MatrixFreeTools::compute_diagonal(*this->data, \n                                      inverse_diagonal, \n                                      &JacobianOperator::local_compute_diagonal, \n                                      this); \n\n    for (auto &diagonal_element : inverse_diagonal) \n      { \n        diagonal_element = (std::abs(diagonal_element) > 1.0e-10) ? \n                             (1.0 / diagonal_element) : \n                             1.0; \n      } \n  } \n\n//  @sect3{GelfandProblem class}  \n\n// 在实现了无矩阵运算符之后，我们现在可以为<i>Gelfand problem</i>定义求解器类。这个类是基于之前所有教程程序的共同结构，特别是它是基于 step-15 ，解决的也是一个非线性问题。由于我们使用的是无矩阵框架，所以我们不再需要assemble_system函数，相反，在每次调用 <code>vmult()</code> 函数时都会重建矩阵的信息。然而，对于牛顿方案的应用，我们需要组装线性化问题的右手边并计算残差。因此，我们实现了一个额外的函数 <code>evaluate_residual()</code> ，后来我们在 <code>assemble_rhs()</code> and the <code>compute_residual()</code> 函数中调用了它。最后，这里典型的 <code>solve()</code> 函数实现了牛顿方法，而线性化系统的解是在 <code>compute_update()</code> 函数中计算的。由于MatrixFree框架将拉格朗日有限元方法的多项式程度作为一个模板参数来处理，我们也将其作为问题求解器类的模板参数来声明。\n\n  template <int dim, int fe_degree> \n  class GelfandProblem \n  { \n  public: \n    GelfandProblem(); \n\n    void run(); \n\n  private: \n    void make_grid(); \n\n    void setup_system(); \n\n    void evaluate_residual( \n      LinearAlgebra::distributed::Vector<double> &      dst, \n      const LinearAlgebra::distributed::Vector<double> &src) const; \n\n    void local_evaluate_residual( \n      const MatrixFree<dim, double> &                   data, \n      LinearAlgebra::distributed::Vector<double> &      dst, \n      const LinearAlgebra::distributed::Vector<double> &src, \n      const std::pair<unsigned int, unsigned int> &     cell_range) const; \n\n    void assemble_rhs(); \n\n    double compute_residual(const double alpha); \n\n    void compute_update(); \n\n    void solve(); \n\n    double compute_solution_norm() const; \n\n    void output_results(const unsigned int cycle) const; \n\n// 对于并行计算，我们定义了一个  parallel::distributed::Triangulation.  由于计算域在二维是一个圆，在三维是一个球，我们除了为边界单元分配SphericalManifold外，还为内部单元的映射分配了一个TransfiniteInterpolationManifold对象，它负责处理内部单元的映射。在这个例子中，我们使用了一个等参数的有限元方法，因此使用了MappingQGeneric类。注意，我们也可以创建一个MappingQ类的实例，并在构造函数调用中设置 <code>use_mapping_q_on_all_cells</code> 标志为 <code>true</code>  。关于MappingQ和MappingQGeneric连接的进一步细节，你可以阅读这些类的详细描述。\n\n    parallel::distributed::Triangulation<dim> triangulation; \n    const MappingQGeneric<dim>                mapping; \n\n// 像往常一样，我们接着定义拉格朗日有限元FE_Q和一个DoFHandler。\n\n    FE_Q<dim>       fe; \n    DoFHandler<dim> dof_handler; \n\n// 对于线性化的离散系统，我们定义一个AffineConstraints对象和 <code>system_matrix</code>  ，在本例中它被表示为一个无矩阵算子。\n\n    AffineConstraints<double> constraints; \n    using SystemMatrixType = JacobianOperator<dim, fe_degree, double>; \n    SystemMatrixType system_matrix; \n\n// 多级对象也是基于雅各布系数的无矩阵算子。由于我们需要用最后一个牛顿步骤来评估雅各布，所以我们也需要用最后一个牛顿步骤来评估预处理器的水平算子。因此，除了 <code>mg_matrices</code> 之外，我们还需要一个MGLevelObject来存储每一级的插值解向量。与 step-37 一样，我们对预处理程序使用浮点精度。此外，我们将MGTransferMatrixFree对象定义为一个类变量，因为我们只需要在三角形变化时设置一次，然后可以在每个牛顿步骤中再次使用它。\n\n    MGConstrainedDoFs mg_constrained_dofs; \n    using LevelMatrixType = JacobianOperator<dim, fe_degree, float>; \n    MGLevelObject<LevelMatrixType>                           mg_matrices; \n    MGLevelObject<LinearAlgebra::distributed::Vector<float>> mg_solution; \n    MGTransferMatrixFree<dim, float>                         mg_transfer; \n\n// 当然，我们还需要持有  <code>solution</code>  ,  <code>newton_update</code> and the <code>system_rhs</code>  的向量。这样，我们就可以一直将上一个牛顿步存储在解的向量中，只需添加更新就可以得到下一个牛顿步。\n\n    LinearAlgebra::distributed::Vector<double> solution; \n    LinearAlgebra::distributed::Vector<double> newton_update; \n    LinearAlgebra::distributed::Vector<double> system_rhs; \n\n// 最后我们有一个变量，用来表示线性求解器的迭代次数。\n\n    unsigned int linear_iterations; \n\n// 对于与MPI并行运行的程序中的输出，我们使用ConditionalOStream类来避免不同MPI等级对同一数据的多次输出。\n\n    ConditionalOStream pcout; \n\n// 最后，对于时间测量，我们使用一个TimerOutput对象，它在程序结束后将每个函数的耗时CPU和墙体时间打印在一个格式良好的表格中。\n\n    TimerOutput computing_timer; \n  }; \n\n//  <code>GelfandProblem</code> 的构造函数初始化了类的变量。特别是，我们为 parallel::distributed::Triangulation, 设置了多级支持，将映射度设为有限元度，初始化ConditionalOStream，并告诉TimerOutput，我们只想在需求时看到墙体时间。\n\n  template <int dim, int fe_degree> \n  GelfandProblem<dim, fe_degree>::GelfandProblem() \n    : triangulation(MPI_COMM_WORLD, \n                    Triangulation<dim>::limit_level_difference_at_vertices, \n                    parallel::distributed::Triangulation< \n                      dim>::construct_multigrid_hierarchy) \n    , mapping(fe_degree) \n    , fe(fe_degree) \n    , dof_handler(triangulation) \n    , pcout(std::cout, Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0) \n    , computing_timer(MPI_COMM_WORLD, \n                      pcout, \n                      TimerOutput::never, \n                      TimerOutput::wall_times) \n  {} \n\n//  @sect4{GelfandProblem::make_grid}  \n\n// 作为计算域，我们使用 <code>dim</code>  -维的单位球。我们按照TransfiniteInterpolationManifold类的说明，也为边界指定了一个SphericalManifold。最后，我们将初始网格细化为3\n\n// -  <code>dim</code> 次全局。\n\n  template <int dim, int fe_degree> \n  void GelfandProblem<dim, fe_degree>::make_grid() \n  { \n    TimerOutput::Scope t(computing_timer, \"make grid\"); \n\n    SphericalManifold<dim>                boundary_manifold; \n    TransfiniteInterpolationManifold<dim> inner_manifold; \n\n    GridGenerator::hyper_ball(triangulation); \n\n \n    triangulation.set_all_manifold_ids_on_boundary(0); \n\n    triangulation.set_manifold(0, boundary_manifold); \n\n    inner_manifold.initialize(triangulation); \n    triangulation.set_manifold(1, inner_manifold); \n\n    triangulation.refine_global(3 - dim); \n  } \n\n//  @sect4{GelfandProblem::setup_system}  \n\n//  <code>setup_system()</code> 函数与  step-37  中的函数基本相同。唯一的区别显然是时间测量只有一个 TimerOutput::Scope ，而不是单独测量每个部分，更重要的是对前一个牛顿步骤的内插解向量的MGLevelObject的初始化。另一个重要的变化是MGTransferMatrixFree对象的设置，我们可以在每个牛顿步骤中重复使用它，因为 <code>triangulation</code> 不会被改变。\n\n// 注意我们如何在 <code>JacobianOperator</code> 和多网格预处理程序中两次使用同一个MatrixFree对象。\n\n  template <int dim, int fe_degree> \n  void GelfandProblem<dim, fe_degree>::setup_system() \n  { \n    TimerOutput::Scope t(computing_timer, \"setup system\"); \n\n    system_matrix.clear(); \n    mg_matrices.clear_elements(); \n\n    dof_handler.distribute_dofs(fe); \n    dof_handler.distribute_mg_dofs(); \n\n    IndexSet locally_relevant_dofs; \n    DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs); \n\n    constraints.clear(); \n    constraints.reinit(locally_relevant_dofs); \n    DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             Functions::ZeroFunction<dim>(), \n                                             constraints); \n    constraints.close(); \n\n    { \n      typename MatrixFree<dim, double>::AdditionalData additional_data; \n      additional_data.tasks_parallel_scheme = \n        MatrixFree<dim, double>::AdditionalData::partition_color; \n      additional_data.mapping_update_flags = \n        (update_values | update_gradients | update_JxW_values | \n         update_quadrature_points); \n      auto system_mf_storage = std::make_shared<MatrixFree<dim, double>>(); \n      system_mf_storage->reinit(mapping, \n                                dof_handler, \n                                constraints, \n                                QGauss<1>(fe.degree + 1), \n                                additional_data); \n\n      system_matrix.initialize(system_mf_storage); \n    } \n\n    system_matrix.initialize_dof_vector(solution); \n    system_matrix.initialize_dof_vector(newton_update); \n    system_matrix.initialize_dof_vector(system_rhs); \n\n    const unsigned int nlevels = triangulation.n_global_levels(); \n    mg_matrices.resize(0, nlevels - 1); \n    mg_solution.resize(0, nlevels - 1); \n\n    std::set<types::boundary_id> dirichlet_boundary; \n    dirichlet_boundary.insert(0); \n    mg_constrained_dofs.initialize(dof_handler); \n    mg_constrained_dofs.make_zero_boundary_constraints(dof_handler, \n                                                       dirichlet_boundary); \n\n    mg_transfer.initialize_constraints(mg_constrained_dofs); \n    mg_transfer.build(dof_handler); \n\n    for (unsigned int level = 0; level < nlevels; ++level) \n      { \n        IndexSet relevant_dofs; \n        DoFTools::extract_locally_relevant_level_dofs(dof_handler, \n                                                      level, \n                                                      relevant_dofs); \n\n        AffineConstraints<double> level_constraints; \n        level_constraints.reinit(relevant_dofs); \n        level_constraints.add_lines( \n          mg_constrained_dofs.get_boundary_indices(level)); \n        level_constraints.close(); \n\n        typename MatrixFree<dim, float>::AdditionalData additional_data; \n        additional_data.tasks_parallel_scheme = \n          MatrixFree<dim, float>::AdditionalData::partition_color; \n        additional_data.mapping_update_flags = \n          (update_values | update_gradients | update_JxW_values | \n           update_quadrature_points); \n        additional_data.mg_level = level; \n        auto mg_mf_storage_level = std::make_shared<MatrixFree<dim, float>>(); \n        mg_mf_storage_level->reinit(mapping, \n                                    dof_handler, \n                                    level_constraints, \n                                    QGauss<1>(fe.degree + 1), \n                                    additional_data); \n\n        mg_matrices[level].initialize(mg_mf_storage_level, \n                                      mg_constrained_dofs, \n                                      level); \n        mg_matrices[level].initialize_dof_vector(mg_solution[level]); \n      } \n  } \n\n//  @sect4{GelfandProblem::evaluate_residual}  \n\n// 接下来我们实现一个函数，该函数对给定的输入向量评估非线性离散残差（  $\\texttt{dst} = F(\\texttt{src})$  ）。这个函数随后被用于组装线性化系统的右手边，随后用于计算下一个牛顿步骤的残差，以检查我们是否已经达到了误差容忍度。由于这个函数不应该影响任何类别的变量，我们把它定义为一个常数函数。在内部，我们通过FEEvaluation类和类似于 MatrixFree::cell_loop(), 的 <code>apply_add()</code> function of the <code>JacobianOperator</code> 来利用快速有限元评估。\n\n// 首先我们创建一个指向MatrixFree对象的指针，它被存储在  <code>system_matrix</code>  中。然后，我们将用于残差的单元评估的工作函数  <code>local_evaluate_residual()</code>  以及输入和输出向量传递给  MatrixFree::cell_loop().  此外，我们在循环中启用输出向量的清零，这比之前单独调用<code>dst = 0.0</code>更有效率。\n\n// 注意，使用这种方法，我们不必关心MPI相关的数据交换，因为所有的记账工作都是由  MatrixFree::cell_loop().  完成的。\n  template <int dim, int fe_degree> \n  void GelfandProblem<dim, fe_degree>::evaluate_residual( \n    LinearAlgebra::distributed::Vector<double> &      dst, \n    const LinearAlgebra::distributed::Vector<double> &src) const \n  { \n    auto matrix_free = system_matrix.get_matrix_free(); \n\n    matrix_free->cell_loop( \n      &GelfandProblem::local_evaluate_residual, this, dst, src, true); \n  } \n\n//  @sect4{GelfandProblem::local_evaluate_residual}  \n\n// 这是用于评估残差的内部工作函数。本质上它与  <code>JacobianOperator</code>  的  <code>local_apply()</code>  函数具有相同的结构，在给定的单元格集合  <code>cell_range</code>  上对输入向量  <code>src</code>  进行残差评估。与上述 <code>local_apply()</code> 函数不同的是，我们将 FEEvaluation::gather_evaluate() 函数分成 FEEvaluation::read_dof_values_plain() 和 FEEvaluation::evaluate(), ，因为输入向量可能有受限的DOF。\n\n  template <int dim, int fe_degree> \n  void GelfandProblem<dim, fe_degree>::local_evaluate_residual( \n    const MatrixFree<dim, double> &                   data, \n    LinearAlgebra::distributed::Vector<double> &      dst, \n    const LinearAlgebra::distributed::Vector<double> &src, \n    const std::pair<unsigned int, unsigned int> &     cell_range) const \n  { \n    FEEvaluation<dim, fe_degree, fe_degree + 1, 1, double> phi(data); \n\n    for (unsigned int cell = cell_range.first; cell < cell_range.second; ++cell) \n      { \n        phi.reinit(cell); \n\n        phi.read_dof_values_plain(src); \n        phi.evaluate(EvaluationFlags::values | EvaluationFlags::gradients); \n\n        for (unsigned int q = 0; q < phi.n_q_points; ++q) \n          { \n            phi.submit_value(-std::exp(phi.get_value(q)), q); \n            phi.submit_gradient(phi.get_gradient(q), q); \n          } \n\n        phi.integrate_scatter(EvaluationFlags::values | \n                                EvaluationFlags::gradients, \n                              dst); \n      } \n  } \n\n//  @sect4{GelfandProblem::assemble_rhs}  \n\n// 使用上述函数 <code>evaluate_residual()</code> 来评估非线性残差，组装线性化系统的右手边现在变得非常容易。我们只需调用 <code>evaluate_residual()</code> 函数并将结果乘以减一。\n\n// 经验表明，使用FEEvaluation类要比使用FEValues和co的经典实现快得多。\n\n  template <int dim, int fe_degree> \n  void GelfandProblem<dim, fe_degree>::assemble_rhs() \n  { \n    TimerOutput::Scope t(computing_timer, \"assemble right hand side\"); \n\n    evaluate_residual(system_rhs, solution); \n\n    system_rhs *= -1.0; \n  } \n\n//  @sect4{GelfandProblem::compute_residual}  \n\n// 根据 step-15 ，下面的函数在 $u_h^n + \\alpha s_h^n$ 函数的帮助下计算出解的非线性残差的规范。如果我们使用牛顿方法的自适应版本，牛顿步长 $\\alpha$ 就变得很重要。例如，我们将计算不同步长的残差并比较残差。然而，对于我们的问题，使用 $\\alpha=1$ 的完整牛顿步长是我们能做的最好的。如果我们没有好的初始值，牛顿方法的自适应版本就变得有趣了。请注意，在理论上，牛顿方法是以二次方顺序收敛的，但只有当我们有一个合适的初始值时才会收敛。对于不合适的初始值，牛顿方法甚至在二次方程下也会发散。一个常见的方法是使用阻尼版本 $\\alpha<1$ ，直到牛顿步骤足够好，可以进行完整的牛顿步骤。这在  step-15  中也有讨论。\n\n  template <int dim, int fe_degree> \n  double GelfandProblem<dim, fe_degree>::compute_residual(const double alpha) \n  { \n    TimerOutput::Scope t(computing_timer, \"compute residual\"); \n\n    LinearAlgebra::distributed::Vector<double> residual; \n    LinearAlgebra::distributed::Vector<double> evaluation_point; \n\n    system_matrix.initialize_dof_vector(residual); \n    system_matrix.initialize_dof_vector(evaluation_point); \n\n    evaluation_point = solution; \n    if (alpha > 1e-12) \n      { \n        evaluation_point.add(alpha, newton_update); \n      } \n\n    evaluate_residual(residual, evaluation_point); \n\n    return residual.l2_norm(); \n  } \n\n//  @sect4{GelfandProblem::compute_update}  \n\n// 为了计算每个牛顿步骤中的牛顿更新，我们用CG算法和一个几何多网格预处理程序来解决线性系统。为此，我们首先像在  step-37  中那样，用切比雪夫平滑器设置PreconditionMG对象。\n\n  template <int dim, int fe_degree> \n  void GelfandProblem<dim, fe_degree>::compute_update() \n  { \n    TimerOutput::Scope t(computing_timer, \"compute update\"); \n\n// 我们记得，雅各布系数取决于存储在解决方案向量中的最后一个牛顿步骤。所以我们更新牛顿步骤的鬼魂值，并将其传递给 <code>JacobianOperator</code> 来存储信息。\n\n    solution.update_ghost_values(); \n\n    system_matrix.evaluate_newton_step(solution); \n\n// 接下来我们还要将最后一个牛顿步骤传递给多级运算符。因此，我们需要将牛顿步骤插值到三角形的所有层面。这是用 MGTransferMatrixFree::interpolate_to_mg(). 来完成的。\n    mg_transfer.interpolate_to_mg(dof_handler, mg_solution, solution); \n\n// 现在我们可以设置预处理程序了。我们定义平滑器并将牛顿步的内插向量传递给多级运算器。\n\n    using SmootherType = \n      PreconditionChebyshev<LevelMatrixType, \n                            LinearAlgebra::distributed::Vector<float>>; \n    mg::SmootherRelaxation<SmootherType, \n                           LinearAlgebra::distributed::Vector<float>> \n                                                         mg_smoother; \n    MGLevelObject<typename SmootherType::AdditionalData> smoother_data; \n    smoother_data.resize(0, triangulation.n_global_levels() - 1); \n    for (unsigned int level = 0; level < triangulation.n_global_levels(); \n         ++level) \n      { \n        if (level > 0) \n          { \n            smoother_data[level].smoothing_range     = 15.; \n            smoother_data[level].degree              = 4; \n            smoother_data[level].eig_cg_n_iterations = 10; \n          } \n        else \n          { \n            smoother_data[0].smoothing_range = 1e-3; \n            smoother_data[0].degree          = numbers::invalid_unsigned_int; \n            smoother_data[0].eig_cg_n_iterations = mg_matrices[0].m(); \n          } \n\n        mg_matrices[level].evaluate_newton_step(mg_solution[level]); \n        mg_matrices[level].compute_diagonal(); \n\n        smoother_data[level].preconditioner = \n          mg_matrices[level].get_matrix_diagonal_inverse(); \n      } \n    mg_smoother.initialize(mg_matrices, smoother_data); \n\n    MGCoarseGridApplySmoother<LinearAlgebra::distributed::Vector<float>> \n      mg_coarse; \n    mg_coarse.initialize(mg_smoother); \n\n    mg::Matrix<LinearAlgebra::distributed::Vector<float>> mg_matrix( \n      mg_matrices); \n\n    MGLevelObject<MatrixFreeOperators::MGInterfaceOperator<LevelMatrixType>> \n      mg_interface_matrices; \n    mg_interface_matrices.resize(0, triangulation.n_global_levels() - 1); \n    for (unsigned int level = 0; level < triangulation.n_global_levels(); \n         ++level) \n      { \n        mg_interface_matrices[level].initialize(mg_matrices[level]); \n      } \n    mg::Matrix<LinearAlgebra::distributed::Vector<float>> mg_interface( \n      mg_interface_matrices); \n\n    Multigrid<LinearAlgebra::distributed::Vector<float>> mg( \n      mg_matrix, mg_coarse, mg_transfer, mg_smoother, mg_smoother); \n    mg.set_edge_matrices(mg_interface, mg_interface); \n\n    PreconditionMG<dim, \n                   LinearAlgebra::distributed::Vector<float>, \n                   MGTransferMatrixFree<dim, float>> \n      preconditioner(dof_handler, mg, mg_transfer); \n\n// 最后我们设置了SolverControl和SolverCG来解决当前牛顿更新的线性化问题。实现SolverCG或SolverGMRES的一个重要事实是，持有线性系统解决方案的向量（这里是 <code>newton_update</code>  ）可以用来传递一个起始值。为了使迭代求解器总是以零向量开始，我们在调用 SolverCG::solve(). 之前明确地重置了 <code>newton_update</code> ，然后我们分配了存储在 <code>constraints</code> 中的Dirichlet边界条件，并为以后的输出存储了迭代的步数。\n\n    SolverControl solver_control(100, 1.e-12); \n    SolverCG<LinearAlgebra::distributed::Vector<double>> cg(solver_control); \n\n    newton_update = 0.0; \n\n    cg.solve(system_matrix, newton_update, system_rhs, preconditioner); \n\n    constraints.distribute(newton_update); \n\n    linear_iterations = solver_control.last_step(); \n\n// 然后，为了记账，我们将幽灵值清零。\n\n    solution.zero_out_ghost_values(); \n  } \n\n//  @sect4{GelfandProblem::solve}  \n\n// 现在我们实现非线性问题的实际牛顿求解器。\n\n  template <int dim, int fe_degree> \n  void GelfandProblem<dim, fe_degree>::solve() \n  { \n    TimerOutput::Scope t(computing_timer, \"solve\"); \n\n// 我们定义了牛顿步骤的最大数量和收敛标准的公差。通常情况下，如果有好的起始值，牛顿方法在三到六步内就能收敛，所以最大的十步应该是完全足够的。作为公差，我们使用 $\\|F(u^n_h)\\|<\\text{TOL}_f = 10^{-12}$ 作为残差的规范， $\\|s_h^n\\| < \\text{TOL}_x = 10^{-10}$ 作为牛顿更新的规范。这似乎有点过头了，但我们将看到，对于我们的例子，我们将在几步之后达到这些公差。\n\n    const unsigned int itmax = 10; \n    const double       TOLf  = 1e-12; \n    const double       TOLx  = 1e-10; \n\n    Timer solver_timer; \n    solver_timer.start(); \n\n// 现在我们开始实际的牛顿迭代。\n\n    for (unsigned int newton_step = 1; newton_step <= itmax; ++newton_step) \n      { \n\n// 我们将线性化问题的右侧集合起来，计算牛顿更新。\n\n        assemble_rhs(); \n        compute_update(); \n\n// 然后，我们计算误差，即牛顿更新的规范和残差。注意，在这一点上，我们可以通过改变compute_residual函数的输入参数 $\\alpha$ 来加入牛顿方法的步长控制。然而，在这里我们只是使用 $\\alpha$ 等于1来进行普通的牛顿迭代。\n\n        const double ERRx = newton_update.l2_norm(); \n        const double ERRf = compute_residual(1.0); \n\n// 接下来我们通过将牛顿更新添加到当前的牛顿步骤中来推进牛顿步骤。\n\n        solution.add(1.0, newton_update); \n\n// 一个简短的输出将告知我们当前的牛顿步数。\n\n        pcout << \"   Nstep \" << newton_step << \", errf = \" << ERRf \n              << \", errx = \" << ERRx << \", it = \" << linear_iterations \n              << std::endl; \n\n// 在每个牛顿步骤之后，我们检查收敛标准。如果其中至少有一个得到满足，我们就完成了，并结束循环。如果我们在牛顿迭代的最大数量之后还没有找到一个满意的解决方案，我们就会通知用户这个缺点。\n\n        if (ERRf < TOLf || ERRx < TOLx) \n          { \n            solver_timer.stop(); \n\n            pcout << \"Convergence step \" << newton_step << \" value \" << ERRf \n                  << \" (used wall time: \" << solver_timer.wall_time() << \" s)\" \n                  << std::endl; \n\n            break; \n          } \n        else if (newton_step == itmax) \n          { \n            solver_timer.stop(); \n            pcout << \"WARNING: No convergence of Newton's method after \" \n                  << newton_step << \" steps.\" << std::endl; \n\n            break; \n          } \n      } \n  } \n\n//  @sect4{GelfandProblem::compute_solution_norm}  \n\n// 解的H1-seminorm的计算可以用与 step-59 相同的方法进行。我们更新幽灵值并使用函数  VectorTools::integrate_difference().  最后我们收集所有MPI行列的所有计算，并返回规范。\n\n  template <int dim, int fe_degree> \n  double GelfandProblem<dim, fe_degree>::compute_solution_norm() const \n  { \n    solution.update_ghost_values(); \n\n    Vector<float> norm_per_cell(triangulation.n_active_cells()); \n\n    VectorTools::integrate_difference(mapping, \n                                      dof_handler, \n                                      solution, \n                                      Functions::ZeroFunction<dim>(), \n                                      norm_per_cell, \n                                      QGauss<dim>(fe.degree + 2), \n                                      VectorTools::H1_seminorm); \n\n    solution.zero_out_ghost_values(); \n\n    return VectorTools::compute_global_error(triangulation, \n                                             norm_per_cell, \n                                             VectorTools::H1_seminorm); \n  } \n\n//  @sect4{GelfandProblem::output_results}  \n\n// 我们通过调用  DataOut::write_vtu_with_pvtu_record()  函数，以与  step-37  中相同的方式，一次性生成 vtu 格式的图形输出文件和 pvtu 主文件。此外，与  step-40  一样，我们查询每个单元的  types::subdomain_id  并将三角形在MPI行列中的分布写进输出文件。最后，我们通过调用 DataOut::build_patches(). 生成解决方案的补丁。然而，由于我们的计算域有一个弯曲的边界，我们另外传递 <code>mapping</code> 和有限元度作为细分的数量。但这仍然不足以正确表示解决方案，例如在ParaView中，因为我们将TransfiniteInterpolationManifold附在内部单元上，这导致内部的单元是弯曲的。因此，我们将 DataOut::curved_inner_cells 选项作为第三个参数，这样，内部单元也会使用相应的流形描述来构建补丁。\n\n// 注意，我们可以用标志 DataOutBase::VtkFlags::write_higher_order_cells. 来处理高阶元素，但是由于对ParaView以前版本的兼容性有限，而且VisIt也不支持，所以我们把这个选项留给未来的版本。\n\n  template <int dim, int fe_degree> \n  void \n  GelfandProblem<dim, fe_degree>::output_results(const unsigned int cycle) const \n  { \n    if (triangulation.n_global_active_cells() > 1e6) \n      return; \n\n    solution.update_ghost_values(); \n\n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \"solution\"); \n\n    Vector<float> subdomain(triangulation.n_active_cells()); \n    for (unsigned int i = 0; i < subdomain.size(); ++i) \n      { \n        subdomain(i) = triangulation.locally_owned_subdomain(); \n      } \n    data_out.add_data_vector(subdomain, \"subdomain\"); \n\n    data_out.build_patches(mapping, \n                           fe.degree, \n                           DataOut<dim>::curved_inner_cells); \n\n    DataOutBase::VtkFlags flags; \n    flags.compression_level = DataOutBase::VtkFlags::best_speed; \n    data_out.set_flags(flags); \n    data_out.write_vtu_with_pvtu_record( \n      \"./\", \"solution_\" + std::to_string(dim) + \"d\", cycle, MPI_COMM_WORLD, 3); \n\n    solution.zero_out_ghost_values(); \n  } \n\n//  @sect4{GelfandProblem::run}  \n\n// <i>Gelfand\n problem</i>的求解器类的最后一个缺失的函数是运行函数。在开始的时候，我们打印关于系统规格和我们使用的有限元空间的信息。该问题在一个连续细化的网格上被多次求解。\n\n  template <int dim, int fe_degree> \n  void GelfandProblem<dim, fe_degree>::run() \n  { \n    { \n      const unsigned int n_ranks = \n        Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD); \n      const unsigned int n_vect_doubles = VectorizedArray<double>::size(); \n      const unsigned int n_vect_bits    = 8 * sizeof(double) * n_vect_doubles; \n\n      std::string DAT_header = \"START DATE: \" + Utilities::System::get_date() + \n                               \", TIME: \" + Utilities::System::get_time(); \n      std::string MPI_header = \"Running with \" + std::to_string(n_ranks) + \n                               \" MPI process\" + (n_ranks > 1 ? \"es\" : \"\"); \n      std::string VEC_header = \n        \"Vectorization over \" + std::to_string(n_vect_doubles) + \n        \" doubles = \" + std::to_string(n_vect_bits) + \" bits (\" + \n        Utilities::System::get_current_vectorization_level() + \n        \"), VECTORIZATION_LEVEL=\" + \n        std::to_string(DEAL_II_COMPILER_VECTORIZATION_LEVEL); \n      std::string SOL_header = \"Finite element space: \" + fe.get_name(); \n\n      pcout << std::string(80, '=') << std::endl; \n      pcout << DAT_header << std::endl; \n      pcout << std::string(80, '-') << std::endl; \n\n      pcout << MPI_header << std::endl; \n      pcout << VEC_header << std::endl; \n      pcout << SOL_header << std::endl; \n\n      pcout << std::string(80, '=') << std::endl; \n    } \n\n    for (unsigned int cycle = 0; cycle < 9 - dim; ++cycle) \n      { \n        pcout << std::string(80, '-') << std::endl; \n        pcout << \"Cycle \" << cycle << std::endl; \n        pcout << std::string(80, '-') << std::endl; \n\n// 实际解决问题的第一项任务是生成或完善三角图。\n\n        if (cycle == 0) \n          { \n            make_grid(); \n          } \n        else \n          { \n            triangulation.refine_global(1); \n          } \n\n// 现在我们建立了系统并解决这个问题。这些步骤都伴随着时间测量和文本输出。\n\n        Timer timer; \n\n        pcout << \"Set up system...\" << std::endl; \n        setup_system(); \n\n        pcout << \"   Triangulation: \" << triangulation.n_global_active_cells() \n              << \" cells\" << std::endl; \n        pcout << \"   DoFHandler:    \" << dof_handler.n_dofs() << \" DoFs\" \n              << std::endl; \n        pcout << std::endl; \n\n        pcout << \"Solve using Newton's method...\" << std::endl; \n        solve(); \n        pcout << std::endl; \n\n        timer.stop(); \n        pcout << \"Time for setup+solve (CPU/Wall) \" << timer.cpu_time() << \"/\" \n              << timer.wall_time() << \" s\" << std::endl; \n        pcout << std::endl; \n\n// 在问题被解决后，我们计算出解决方案的法线，并生成图形输出文件。\n\n        pcout << \"Output results...\" << std::endl; \n        const double norm = compute_solution_norm(); \n        output_results(cycle); \n\n        pcout << \"  H1 seminorm: \" << norm << std::endl; \n        pcout << std::endl; \n\n// 最后在每个周期后，我们打印计时信息。\n\n        computing_timer.print_summary(); \n        computing_timer.reset(); \n      } \n  } \n} // namespace Step66 \n\n//  @sect3{The <code>main</code> function}  \n\n// 作为使用MPI并行运行的典型程序，我们设置了MPI框架，并通过限制线程数为1来禁用共享内存并行化。最后，为了运行<i>Gelfand problem</i>的求解器，我们创建一个 <code>GelfandProblem</code> 类的对象并调用运行函数。例如，我们用四阶拉格朗日有限元在二维和三维中各解决一次问题。\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace Step66; \n\n      Utilities::MPI::MPI_InitFinalize mpi_init(argc, argv, 1); \n\n      { \n        GelfandProblem<2, 4> gelfand_problem; \n        gelfand_problem.run(); \n      } \n\n      { \n        GelfandProblem<3, 4> gelfand_problem; \n        gelfand_problem.run(); \n      } \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "0402abf6bc31f0734ccd252263f6e75098f03672", "size": 36849, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-66/step-66.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-66/step-66.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-66/step-66.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5047021944, "max_line_length": 503, "alphanum_fraction": 0.6515237863, "num_tokens": 12586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.44146453037222166}}
{"text": "#include \"mtf/AM/SSDBase.h\"\r\n#include \"mtf/Utilities/miscUtils.h\"\r\n#include \"mtf/Utilities/spiUtils.h\"\r\n\r\n#include <boost/random/random_device.hpp>\r\n#include <boost/random/seed_seq.hpp>\r\n\r\n_MTF_BEGIN_NAMESPACE\r\n\r\nSSDBase::SSDBase(const AMParams *am_params, const int _n_channels) :\r\nAppearanceModel(am_params, _n_channels), ilm(nullptr), likelihood_alpha(1),\r\nI_diff(0, 0){\r\n\tif(am_params){\r\n\t\tilm = am_params->ilm;\r\n\t\tlikelihood_alpha = am_params->likelihood_alpha;\r\n\t}\r\n\tif(ilm){\r\n\t\tilm->setPixHessType(ILMPixHessT::Constant);\r\n\t\tilm_d2f_dIt_type = ilm->getPixHessType();\r\n\t\tstate_size = ilm->getStateSize();\r\n\t\tif(ilm_d2f_dIt_type == ILMPixHessT::General){\r\n\t\t\td2f_dIt2.resize(n_pix, n_pix);\r\n\t\t}\r\n\t}\r\n\tpix_norm_mult = 1;\r\n\tpix_norm_add = 0;\r\n}\r\n\r\nvoid SSDBase::initializeSimilarity(){\r\n\tif(is_initialized.similarity)\r\n\t\treturn;\r\n\r\n\tdf_dI0.resize(patch_size);\r\n\tnew (&I_diff) VectorXdM(df_dI0.data(), patch_size);\r\n\tI_diff.fill(0);\r\n\tf = 0;\r\n\tif(ilm){\r\n\t\tIt_orig.resize(patch_size);\r\n\t\tIt_orig = It;\r\n\t\tp_am.resize(state_size);\r\n\t\tilm->initialize(p_am.data());\r\n\t}\r\n\tis_initialized.similarity = true;\r\n}\r\n\r\nvoid SSDBase::initializeGrad(){\r\n\tif(is_initialized.grad)\r\n\t\treturn;\r\n\r\n\tdf_dIt.resize(patch_size);\r\n\tdf_dIt = df_dI0;\r\n\r\n\tif(ilm){\r\n\t\tdf_dpam.resize(state_size);\r\n\t\tdf_dgt.resize(patch_size);\r\n\t\tdf_dg0.resize(patch_size);\r\n\t\tdf_dg0 = df_dI0;\r\n\t\tdf_dgt = df_dIt;\r\n\t\tilm->cmptParamJacobian(df_dpam.data(), df_dgt.data(), It_orig.data(), p_am.data());\r\n\t\tilm->cmptPixJacobian(df_dIt.data(), df_dgt.data(), It_orig.data(), p_am.data());\r\n\t}\r\n\tis_initialized.grad = true;\r\n}\r\ndouble SSDBase::getLikelihood() const{\r\n\t/**\r\n\tsince SSD can be numerically too large for exponential function to work,\r\n\twe take the square root of the per pixel SSD instead;\r\n\tit is further normalized by dividing with the range of pixel values to avoid\r\n\tvery small numbers that may lead to loss of information due to the limited precision\r\n\tof floating point operations;\r\n\t*/\r\n\treturn exp(-likelihood_alpha * sqrt(-f / (static_cast<double>(patch_size))));\r\n}\r\n\r\nvoid SSDBase::updateSimilarity(bool prereq_only){\r\n\tif(ilm){\r\n\t\t//! I_t actually refers to g(I_t, p_am) to keep the illumination model transparent\r\n\t\t//! and avoid any unnecessary runtime costs if it is not used\r\n\t\tIt_orig = It;\r\n\t\tilm->apply(It.data(), It_orig.data(), p_am.data());\r\n\t}\r\n\tI_diff = It - I0;\r\n\tif(prereq_only){ return; }\r\n#ifndef DISABLE_SPI\r\n\tif(spi_mask){\r\n\t\tVectorXd masked_err_vec = Map<const VectorXb>(spi_mask, n_pix).select(I_diff, 0);\r\n\t\tf = -masked_err_vec.squaredNorm() / 2;\r\n\t} else{\r\n#endif\r\n\t\tf = -I_diff.squaredNorm() / 2;\r\n#ifndef DISABLE_SPI\r\n\t}\r\n#endif\r\n\t//utils::printMatrix(p_am.transpose(), \"p_am\");\r\n\t//printf(\"f: %f\\n\", f);\r\n}\r\nvoid SSDBase::updateState(const VectorXd& state_update){\r\n\tif(ilm){\r\n\t\tassert(state_update.size() == state_size);\r\n\t\tVectorXd p_am_old = p_am;\r\n\t\tilm->update(p_am.data(), p_am_old.data(), state_update.data());\r\n\t\t//utils::printMatrix(state_update.transpose(), \"state_update\");\r\n\t\t//utils::printMatrix(p_am_old.transpose(), \"p_am before update\");\r\n\t\t//utils::printMatrix(p_am.transpose(), \"p_am after update\");\r\n\t}\r\n}\r\nvoid SSDBase::invertState(VectorXd& inv_p, const VectorXd& p){\r\n\tif(ilm){\r\n\t\tassert(inv_p.size() == state_size && p.size() == state_size);\r\n\t\tilm->invert(inv_p.data(), p.data());\r\n\t}\t\r\n}\r\n\r\n// curr_grad is same as negative of init_grad\r\nvoid SSDBase::updateCurrGrad(){\r\n\tdf_dIt = -df_dI0;\r\n\tif(ilm){\r\n\t\tdf_dgt = df_dIt;\r\n\t\tilm->cmptPixJacobian(df_dIt.data(), df_dgt.data(), It_orig.data(), p_am.data());\r\n\t}\r\n}\r\n\r\nvoid SSDBase::cmptInitJacobian(RowVectorXd &df_dp,\r\n\tconst MatrixXd &dI0_dpssm){\r\n\tassert(df_dp.size() == state_size + dI0_dpssm.cols());\r\n\tassert(dI0_dpssm.rows() == patch_size);\r\n\tif(ilm){\r\n\t\tdf_dp.head(dI0_dpssm.cols()).noalias() = df_dI0 * dI0_dpssm;\r\n\t\tilm->cmptParamJacobian(df_dpam.data(), df_dg0.data(), \r\n\t\t\tI0.data(), p_am.data());\r\n\t\tdf_dp.tail(state_size) = df_dpam;\r\n\t} else{\r\n#ifndef DISABLE_SPI\r\n\t\tif(spi_mask){\r\n\t\t\tgetJacobian(df_dp, spi_mask, df_dI0, dI0_dpssm);\r\n\t\t} else{\r\n#endif\r\n\t\t\tdf_dp.noalias() = df_dI0 * dI0_dpssm;\r\n#ifndef DISABLE_SPI\r\n\t\t}\r\n#endif\r\n\t}\r\n}\r\nvoid SSDBase::cmptCurrJacobian(RowVectorXd &df_dp,\r\n\tconst MatrixXd &dIt_dpssm){\r\n\tassert(df_dp.size() == state_size + dIt_dpssm.cols());\r\n\tassert(dIt_dpssm.rows() == patch_size);\r\n\r\n\tif(ilm){\r\n\t\tdf_dp.head(dIt_dpssm.cols()).noalias() = df_dIt * dIt_dpssm;\r\n\t\tilm->cmptParamJacobian(df_dpam.data(), df_dgt.data(), \r\n\t\t\tIt_orig.data(), p_am.data());\r\n\t\tdf_dp.tail(state_size) = df_dpam;\r\n\t} else{\r\n#ifndef DISABLE_SPI\r\n\t\tif(spi_mask){\r\n\t\t\tgetJacobian(df_dp, spi_mask, df_dIt, dIt_dpssm);\r\n\t\t} else{\r\n#endif\r\n\t\t\t//printf(\"df_dp: %ld x %ld\\n\", df_dp.rows(), df_dp.cols());\r\n\t\t\t//printf(\"df_dIt: %ld x %ld\\n\", df_dIt.rows(), df_dIt.cols());\r\n\t\t\t//printf(\"dIt_dpssm: %ld x %ld\\n\", dIt_dpssm.rows(), dIt_dpssm.cols());\r\n\t\t\tdf_dp.noalias() = df_dIt * dIt_dpssm;\r\n#ifndef DISABLE_SPI\r\n\t\t}\r\n#endif\r\n\t}\r\n}\r\nvoid SSDBase::cmptDifferenceOfJacobians(RowVectorXd &df_dp_diff,\r\n\tconst MatrixXd &dI0_dpssm, const MatrixXd &dIt_dpssm){\r\n\tassert(df_dp_diff.size() == state_size + dIt_dpssm.cols());\r\n\tassert(dI0_dpssm.cols() == dIt_dpssm.cols());\r\n\tassert(dIt_dpssm.rows() == patch_size && dI0_dpssm.rows() == patch_size);\r\n\tif(ilm){\r\n\t\tdf_dp_diff.head(dIt_dpssm.cols()).noalias() = df_dIt * (dI0_dpssm + dIt_dpssm);\r\n\t\tVectorXd df_dpam_0(state_size), df_dpam_t(state_size);\r\n\t\tilm->cmptParamJacobian(df_dpam_0.data(), df_dg0.data(), I0.data(), p_am.data());\r\n\t\tilm->cmptParamJacobian(df_dpam_t.data(), df_dgt.data(), It_orig.data(), p_am.data());\r\n\t\tdf_dp_diff.tail(state_size) = df_dpam_t - df_dpam_0;\r\n\t} else{\r\n#ifndef DISABLE_SPI\r\n\t\tif(spi_mask){\r\n\t\t\tgetDifferenceOfJacobians(df_dp_diff, spi_mask, dI0_dpssm, dIt_dpssm);\r\n\t\t} else{\r\n#endif\r\n\t\t\tdf_dp_diff.noalias() = df_dIt * (dI0_dpssm + dIt_dpssm);\r\n#ifndef DISABLE_SPI\r\n\t\t}\r\n#endif\r\n\t}\r\n}\r\n\r\nvoid SSDBase::cmptILMHessian(MatrixXd &d2f_dp2, const MatrixXd &dI_dpssm,\r\n\tconst double* I, const double* df_dg){\r\n\tint ssm_state_size = static_cast<int>(dI_dpssm.cols());\r\n\r\n\tassert(d2f_dp2.rows() == state_size + ssm_state_size);\r\n\tassert(d2f_dp2.cols() == state_size + ssm_state_size);\r\n\r\n\tMatrixXd d2f_dpam2(state_size, state_size);\r\n\tilm->cmptParamHessian(d2f_dpam2.data(), nullptr, df_dg, I, p_am.data());\r\n\td2f_dp2.bottomRightCorner(state_size, state_size) = -d2f_dpam2;\r\n\tswitch(ilm_d2f_dIt_type){\r\n\tcase  ILMPixHessT::Constant:\r\n\t{\r\n\t\tdouble d2f_dIt2_const;\r\n\t\tif(df_dg){\r\n\t\t\tilm->cmptPixHessian(&d2f_dIt2_const, nullptr, df_dg, I, p_am.data());\r\n\t\t} else{\r\n\t\t\tilm->cmptPixHessian(&d2f_dIt2_const, nullptr, I, p_am.data());\r\n\t\t}\r\n\t\t\r\n\t\td2f_dp2.topLeftCorner(ssm_state_size, ssm_state_size).noalias() = -d2f_dIt2_const * dI_dpssm.transpose() * dI_dpssm;\r\n\t\tbreak;\r\n\t}\r\n\tcase  ILMPixHessT::Diagonal:\r\n\t{\r\n\t\tVectorXd d2f_dIt2_diag(patch_size);\r\n\t\tif(df_dg){\r\n\t\t\tilm->cmptPixHessian(d2f_dIt2_diag.data(), nullptr, df_dg, I, p_am.data());\r\n\t\t} else{\r\n\t\t\tilm->cmptPixHessian(d2f_dIt2_diag.data(), nullptr, I, p_am.data());\r\n\t\t}\r\n\t\td2f_dp2.topLeftCorner(ssm_state_size, ssm_state_size).noalias() =\r\n\t\t\t-(dI_dpssm.array().colwise() * d2f_dIt2_diag.array()).matrix().transpose() * dI_dpssm;\r\n\t\tbreak;\r\n\t}\r\n\tcase  ILMPixHessT::General:\r\n\t{\r\n\t\tif(df_dg){\r\n\t\t\tilm->cmptPixHessian(d2f_dIt2.data(), nullptr, df_dg, I, p_am.data());\r\n\t\t} else{\r\n\t\t\tilm->cmptPixHessian(d2f_dIt2.data(), nullptr, I, p_am.data());\r\n\t\t}\r\n\t\td2f_dp2.topLeftCorner(ssm_state_size, ssm_state_size).noalias() = -dI_dpssm.transpose() * d2f_dIt2 * dI_dpssm;\r\n\t\tbreak;\r\n\t}\r\n\tdefault:\r\n\t\tthrow utils::InvalidArgument(\r\n\t\t\tcv::format(\"SSDBase :: ILM has invalid hessian type provided: %d\", ilm_d2f_dIt_type));\r\n\t}\r\n\tif(df_dg){\r\n\t\tilm->cmptCrossHessian(d2f_dpam_dIt.data(), nullptr, df_dg, I, p_am.data());\r\n\t} else{\r\n\t\tilm->cmptCrossHessian(d2f_dpam_dIt.data(), nullptr, I, p_am.data());\r\n\t}\r\n\td2f_dp2.topRightCorner(ssm_state_size, state_size).transpose() =\r\n\t\td2f_dp2.bottomLeftCorner(state_size, ssm_state_size) = -d2f_dpam_dIt*dI_dpssm;\r\n}\r\n\r\nvoid SSDBase::cmptInitHessian(MatrixXd &d2f_dp2, const MatrixXd &dI0_dpssm){\r\n\tassert(d2f_dp2.rows() == dI0_dpssm.cols() + state_size && d2f_dp2.rows() == d2f_dp2.cols());\r\n\tassert(dI0_dpssm.rows() == patch_size);\r\n\tif(ilm){\r\n\t\tcmptILMHessian(d2f_dp2, dI0_dpssm, I0.data());\r\n\t} else{\r\n#ifndef DISABLE_SPI\r\n\t\tif(spi_mask){\r\n\t\t\tgetHessian(d2f_dp2, spi_mask, dI0_dpssm);\r\n\t\t} else{\r\n#endif\r\n\t\t\td2f_dp2.noalias() = -dI0_dpssm.transpose() * dI0_dpssm;\r\n#ifndef DISABLE_SPI\r\n\t\t}\r\n#endif\r\n\t}\r\n}\r\nvoid SSDBase::cmptCurrHessian(MatrixXd &d2f_dp2,\r\n\tconst MatrixXd &dIt_dpssm){\r\n\tassert(d2f_dp2.rows() == dIt_dpssm.cols() + state_size && d2f_dp2.rows() == d2f_dp2.cols());\r\n\tassert(dIt_dpssm.rows() == patch_size);\r\n\tif(ilm){\r\n\t\tcmptILMHessian(d2f_dp2, dIt_dpssm, It_orig.data());\r\n\t} else{\r\n#ifndef DISABLE_SPI\r\n\t\tif(spi_mask){\r\n\t\t\tgetHessian(d2f_dp2, spi_mask, dIt_dpssm);\r\n\t\t} else{\r\n#endif\r\n\t\t\td2f_dp2.noalias() = -dIt_dpssm.transpose() * dIt_dpssm;\r\n#ifndef DISABLE_SPI\r\n\t\t}\r\n#endif\r\n\t}\r\n}\r\n//! analogous to cmptDifferenceOfJacobians except for computing the difference between the current and initial Hessians\r\nvoid SSDBase::cmptSumOfHessians(MatrixXd &d2f_dp2_sum,\r\n\tconst MatrixXd &dI0_dpssm,\tconst MatrixXd &dIt_dpssm){\r\n\tassert(d2f_dp2_sum.cols() == d2f_dp2_sum.rows());\r\n\tassert(dI0_dpssm.rows() == patch_size && dIt_dpssm.rows() == patch_size);\r\n\r\n\tif(ilm){\r\n\t\tMatrixXd d2f_dp2t(d2f_dp2_sum.rows(), d2f_dp2_sum.cols());\r\n\t\tcmptILMHessian(d2f_dp2t, dIt_dpssm, It_orig.data());\r\n\t\tMatrixXd d2f_dp20(d2f_dp2_sum.rows(), d2f_dp2_sum.cols());\r\n\t\tcmptILMHessian(d2f_dp20, dI0_dpssm, I0.data());\r\n\t\td2f_dp2_sum.noalias() = d2f_dp2t + d2f_dp20;\r\n\t} else{\r\n#ifndef DISABLE_SPI\r\n\t\tif(spi_mask){\r\n\t\t\tgetSumOfHessians(d2f_dp2_sum, spi_mask,\r\n\t\t\t\tdI0_dpssm, dIt_dpssm);\r\n\t\t} else{\r\n#endif\r\n\t\t\td2f_dp2_sum.noalias() = -(dI0_dpssm.transpose() * dI0_dpssm\r\n\t\t\t\t+ dIt_dpssm.transpose() * dIt_dpssm);\r\n#ifndef DISABLE_SPI\r\n\t\t}\r\n#endif\r\n\t}\r\n}\r\n\r\nvoid SSDBase::cmptInitHessian(MatrixXd &d2f_dp2, const MatrixXd &dI0_dpssm,\r\n\tconst MatrixXd &d2I0_dpssm2){\r\n\tint ssm_state_size = static_cast<int>(d2f_dp2.rows());\r\n\tassert(d2f_dp2.cols() == ssm_state_size + state_size);\r\n\tassert(d2I0_dpssm2.rows() == ssm_state_size * ssm_state_size && d2I0_dpssm2.cols() == n_channels*n_pix);\r\n\r\n\tassert(d2f_dp2.rows() == dI0_dpssm.cols() + state_size && d2f_dp2.rows() == d2f_dp2.cols());\r\n\tassert(dI0_dpssm.rows() == patch_size);\r\n\tif(ilm){\r\n\t\tcmptILMHessian(d2f_dp2, dI0_dpssm, I0.data(), df_dg0.data());\r\n\t} else{\r\n#ifndef DISABLE_SPI\r\n\t\tif(spi_mask){\r\n\t\t\tgetHessian(d2f_dp2, spi_mask, dI0_dpssm);\r\n\t\t} else{\r\n#endif\r\n\t\t\td2f_dp2.noalias() = -dI0_dpssm.transpose() * dI0_dpssm;\r\n#ifndef DISABLE_SPI\r\n\t\t}\r\n#endif\r\n\t}\r\n\tint ch_pix_id = 0;\r\n\tfor(unsigned int pix_id = 0; pix_id < n_pix; ++pix_id){\r\n\t\tspi_pt_check_mc(spi_mask, pix_id, ch_pix_id);\r\n\t\tfor(unsigned int channel_id = 0; channel_id < n_channels; ++channel_id){\r\n\t\t\td2f_dp2 += Map<const MatrixXd>(d2I0_dpssm2.col(ch_pix_id).data(), ssm_state_size, ssm_state_size) * df_dI0(ch_pix_id);\r\n\t\t\t++ch_pix_id;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid SSDBase::cmptCurrHessian(MatrixXd &d2f_dp2, const MatrixXd &dIt_dpssm,\r\n\tconst MatrixXd &d2It_dpssm2){\r\n\tint ssm_state_size = static_cast<int>(d2f_dp2.rows());\r\n\r\n\tassert(d2f_dp2.cols() == ssm_state_size + state_size);\r\n\tassert(d2It_dpssm2.rows() == ssm_state_size * ssm_state_size && d2It_dpssm2.cols() == n_channels * n_pix);\r\n\r\n\tassert(d2f_dp2.rows() == dIt_dpssm.cols() + state_size && d2f_dp2.rows() == d2f_dp2.cols());\r\n\tassert(dIt_dpssm.rows() == patch_size);\r\n\tif(ilm){\r\n\t\tcmptILMHessian(d2f_dp2, dIt_dpssm, It_orig.data(), df_dgt.data());\r\n\t} else{\r\n#ifndef DISABLE_SPI\r\n\t\tif(spi_mask){\r\n\t\t\tgetHessian(d2f_dp2, spi_mask, dIt_dpssm);\r\n\t\t} else{\r\n#endif\r\n\t\t\td2f_dp2.noalias() = -dIt_dpssm.transpose() * dIt_dpssm;\r\n#ifndef DISABLE_SPI\r\n\t\t}\r\n#endif\r\n\t}\r\n\tint ch_pix_id = 0;\r\n\tfor(unsigned int pix_id = 0; pix_id < n_pix; ++pix_id){\r\n\t\tspi_pt_check_mc(spi_mask, pix_id, ch_pix_id);\r\n\t\tfor(unsigned int channel_id = 0; channel_id < n_channels; ++channel_id){\r\n\t\t\td2f_dp2 += Map<const MatrixXd>(d2It_dpssm2.col(ch_pix_id).data(), ssm_state_size, ssm_state_size) * df_dIt(ch_pix_id);\r\n\t\t\t++ch_pix_id;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid SSDBase::cmptSumOfHessians(MatrixXd &d2f_dp2_sum,\r\n\tconst MatrixXd &dI0_dpssm, const MatrixXd &dIt_dpssm,\r\n\tconst MatrixXd &d2I0_dpssm2, const MatrixXd &d2It_dpssm2){\r\n\r\n\tint ssm_state_size = static_cast<int>(d2f_dp2_sum.rows());\r\n\tassert(d2f_dp2_sum.cols() == ssm_state_size);\r\n\tassert(d2I0_dpssm2.rows() == ssm_state_size * ssm_state_size && d2I0_dpssm2.cols() == n_channels * n_pix);\r\n\tassert(d2It_dpssm2.rows() == ssm_state_size * ssm_state_size && d2It_dpssm2.cols() == n_channels * n_pix);\r\n\r\n\tif(ilm){\r\n\t\tMatrixXd d2f_dp2t(d2f_dp2_sum.rows(), d2f_dp2_sum.cols());\r\n\t\tcmptILMHessian(d2f_dp2t, dIt_dpssm, It_orig.data(), df_dgt.data());\r\n\t\tMatrixXd d2f_dp20(d2f_dp2_sum.rows(), d2f_dp2_sum.cols());\r\n\t\tcmptILMHessian(d2f_dp20, dI0_dpssm, I0.data(), df_dgt.data());\r\n\t\td2f_dp2_sum.noalias() = d2f_dp2t + d2f_dp20;\r\n\t} else{\r\n#ifndef DISABLE_SPI\r\n\t\tif(spi_mask){\r\n\t\t\tgetSumOfHessians(d2f_dp2_sum, spi_mask,\r\n\t\t\t\tdI0_dpssm, dIt_dpssm);\r\n\t\t} else{\r\n#endif\r\n\t\t\td2f_dp2_sum.noalias() = -(dI0_dpssm.transpose() * dI0_dpssm\r\n\t\t\t\t+ dIt_dpssm.transpose() * dIt_dpssm);\r\n#ifndef DISABLE_SPI\r\n\t\t}\r\n#endif\r\n\t}\r\n\r\n\tint ch_pix_id = 0;\r\n\tfor(unsigned int pix_id = 0; pix_id < n_pix; ++pix_id){\r\n\t\tspi_pt_check_mc(spi_mask, pix_id, ch_pix_id);\r\n\t\tfor(unsigned int channel_id = 0; channel_id < n_channels; ++channel_id){\r\n\t\t\td2f_dp2_sum += df_dI0(pix_id)*\r\n\t\t\t\t(Map<const MatrixXd>(d2I0_dpssm2.col(ch_pix_id).data(), ssm_state_size, ssm_state_size)\r\n\t\t\t\t+ Map<const MatrixXd>(d2It_dpssm2.col(ch_pix_id).data(), ssm_state_size, ssm_state_size));\r\n\t\t\t++ch_pix_id;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid SSDBase::getJacobian(RowVectorXd &jacobian, const bool *pix_mask,\r\n\tconst RowVectorXd &df_dI, const MatrixXd &dI_dpssm){\r\n\tassert(dI_dpssm.rows() == patch_size && dI_dpssm.rows() == jacobian.size());\r\n\tjacobian.setZero();\r\n\tint ch_pix_id = 0;\r\n\tfor(unsigned int pix_id = 0; pix_id < n_pix; ++pix_id){\r\n\t\tspi_check_mc(pix_mask, pix_id, ch_pix_id);\r\n\t\tfor(unsigned int channel_id = 0; channel_id < n_channels; ++channel_id){\r\n\t\t\tjacobian += df_dI[ch_pix_id] * dI_dpssm.row(ch_pix_id);\r\n\t\t\t++ch_pix_id;\r\n\t\t}\r\n\r\n\t}\r\n}\r\n\r\nvoid SSDBase::getDifferenceOfJacobians(RowVectorXd &diff_of_jacobians, const bool *pix_mask,\r\n\tconst MatrixXd &dI0_dpssm, const MatrixXd &dIt_dpssm){\r\n\tassert(dI0_dpssm.rows() == n_channels * n_pix && dIt_dpssm.rows() == n_channels * n_pix);\r\n\tassert(dI0_dpssm.rows() == diff_of_jacobians.size());\r\n\r\n\tdiff_of_jacobians.setZero();\r\n\tint ch_pix_id = 0;\r\n\tfor(unsigned int pix_id = 0; pix_id < n_pix; ++pix_id){\r\n\t\tspi_check_mc(pix_mask, pix_id, ch_pix_id);\r\n\t\tfor(unsigned int channel_id = 0; channel_id < n_channels; ++channel_id){\r\n\t\t\tdiff_of_jacobians += df_dIt[ch_pix_id] *\r\n\t\t\t\t(dI0_dpssm.row(ch_pix_id) + dIt_dpssm.row(ch_pix_id));\r\n\t\t\t++ch_pix_id;\r\n\t\t}\r\n\r\n\t}\r\n}\r\n\r\nvoid SSDBase::getHessian(MatrixXd &d2f_dp2, const bool *pix_mask, const MatrixXd &dI_dpssm){\r\n\tassert(dI_dpssm.rows() == n_channels * n_pix);\r\n\r\n\td2f_dp2.setZero();\r\n\tint ch_pix_id = 0;\r\n\tfor(unsigned int pix_id = 0; pix_id < n_pix; ++pix_id){\r\n\t\tspi_check_mc(pix_mask, pix_id, ch_pix_id);\r\n\t\tfor(unsigned int channel_id = 0; channel_id < n_channels; ++channel_id){\r\n\t\t\td2f_dp2 -= dI_dpssm.row(ch_pix_id).transpose()*dI_dpssm.row(ch_pix_id);\r\n\t\t\t++ch_pix_id;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid SSDBase::getSumOfHessians(MatrixXd &d2f_dp2, const bool *pix_mask,\r\n\tconst MatrixXd &dI0_dpssm, const MatrixXd &dIt_dpssm){\r\n\tassert(dI0_dpssm.rows() == n_channels * n_pix && dIt_dpssm.rows() == n_channels * n_pix);\r\n\tassert(d2f_dp2.rows() == d2f_dp2.cols() && d2f_dp2.rows() == dI0_dpssm.cols());\r\n\r\n\td2f_dp2.setZero();\r\n\tunsigned int ch_pix_id = 0;\r\n\tfor(unsigned int pix_id = 0; pix_id < n_pix; ++pix_id){\r\n\t\tspi_check_mc(pix_mask, pix_id, ch_pix_id);\r\n\t\tfor(unsigned int channel_id = 0; channel_id < n_channels; ++channel_id){\r\n\t\t\td2f_dp2 -= dI0_dpssm.row(ch_pix_id).transpose()*dI0_dpssm.row(ch_pix_id)\r\n\t\t\t\t+ dIt_dpssm.row(ch_pix_id).transpose()*dIt_dpssm.row(ch_pix_id);\r\n\t\t\t++ch_pix_id;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n// -------------------------------------------------------------------------- //\r\n// --------------------------- Stochastic Sampler --------------------------- //\r\n// -------------------------------------------------------------------------- //\r\n\r\nvoid SSDBase::initializeSampler(const VectorXd &_state_sigma,\r\n\tconst VectorXd &_state_mean){\r\n\tif(!ilm){ return; }\r\n\r\n\tVectorXd state_sigma(state_size), state_mean(state_size);\r\n\tilm->parseSamplerSigma(state_sigma, _state_sigma);\r\n\tilm->parseSamplerMean(state_mean, _state_mean);\r\n\r\n\tprintf(\"Initializing %s sampler with sigma: \", \r\n\t\tilm ? (name + \"/\" + ilm->name).c_str() : name.c_str());\r\n\tutils::printMatrix(state_sigma.transpose(), nullptr, \"%e\");\r\n\r\n\tstate_perturbation.resize(state_size);\r\n\trand_gen.resize(state_size);\r\n\trand_dist.resize(state_size);\r\n\r\n\tboost::random_device r;\r\n\tfor(int state_id = 0; state_id < state_size; state_id++) {\r\n\t\tboost::random::seed_seq seed{ r(), r(), r(), r(), r(), r(), r(), r() };\r\n\t\trand_gen[state_id] = SampleGenT(seed);\r\n\t\trand_dist[state_id] = SampleDistT(state_mean[state_id], state_sigma[state_id]);\r\n\t}\r\n\tis_initialized.sampler = true;\r\n}\r\n\r\n\r\nvoid SSDBase::setSampler(const VectorXd &_state_sigma,\r\n\tconst VectorXd &_state_mean){\r\n\tif(!ilm){ return; }\r\n\tVectorXd state_sigma(state_size), state_mean(state_size);\r\n\tilm->parseSamplerSigma(state_sigma, _state_sigma);\r\n\tilm->parseSamplerMean(state_mean, _state_mean);\r\n\tfor(int state_id = 0; state_id < state_size; state_id++){\r\n\t\trand_dist[state_id].param(DistParamT(state_mean[state_id], state_sigma[state_id]));\r\n\t}\r\n}\r\n\r\nvoid SSDBase::setSamplerMean(const VectorXd &_state_mean){\r\n\tif(!ilm){ return; }\r\n\tVectorXd state_mean(state_size);\r\n\tilm->parseSamplerMean(state_mean, _state_mean);\r\n\tfor(int state_id = 0; state_id < state_size; state_id++){\r\n\t\tdouble state_sigma = rand_dist[state_id].sigma();\r\n\t\trand_dist[state_id].param(DistParamT(state_mean[state_id], state_sigma));\r\n\t}\r\n}\r\nvoid SSDBase::setSamplerSigma(const VectorXd &_state_sigma){\r\n\tVectorXd state_sigma(state_size);\r\n\tilm->parseSamplerSigma(state_sigma, _state_sigma);\r\n\tfor(int state_id = 0; state_id < state_size; state_id++){\r\n\t\tdouble mean = rand_dist[state_id].mean();\r\n\t\trand_dist[state_id].param(DistParamT(mean, state_sigma[state_id]));\r\n\t}\r\n}\r\n\r\nvoid SSDBase::getSamplerSigma(VectorXd &std){\r\n\tif(!ilm){ return; }\r\n\tassert(std.size() == state_size);\r\n\tfor(int state_id = 0; state_id < state_size; state_id++){\r\n\t\tstd(state_id) = rand_dist[state_id].sigma();\r\n\t}\r\n}\r\nvoid SSDBase::getSamplerMean(VectorXd &mean){\r\n\tif(!ilm){ return; }\r\n\tassert(mean.size() == state_size);\r\n\tfor(int state_id = 0; state_id < state_size; state_id++){\r\n\t\tmean(state_id) = rand_dist[state_id].mean();\r\n\t}\r\n}\r\n\r\nvoid SSDBase::generatePerturbation(VectorXd &perturbation){\r\n\tif(!ilm){ return; }\r\n\tassert(perturbation.size() == state_size);\r\n\tfor(int state_id = 0; state_id < state_size; state_id++){\r\n\t\tperturbation(state_id) = rand_dist[state_id](rand_gen[state_id]);\r\n\t}\r\n}\r\n\r\n\r\n/**\n* Squared Euclidean distance functor, optimized version\n*/\n/**\n*  Compute the squared Euclidean distance between two vectors.\n*\n*\tThis is highly optimized, with loop unrolling, as it is one\n*\tof the most expensive inner loops.\n*\n*\tThe computation of squared root at the end is omitted for\n*\tefficiency.\n*/\ndouble SSDBaseDist::operator()(const double* a, const double* b,\n\tsize_t size, double worst_dist) const{\n\tdouble result = 0;\n\tdouble diff0, diff1, diff2, diff3;\n\tconst double* last = a + size;\n\tconst double* lastgroup = last - 3;\n\n\t/* Process 4 items with each loop for efficiency. */\n\twhile(a < lastgroup){\n\t\tdiff0 = (a[0] - b[0]);\n\t\tdiff1 = (a[1] - b[1]);\n\t\tdiff2 = (a[2] - b[2]);\n\t\tdiff3 = (a[3] - b[3]);\n\t\tresult += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3;\n\t\ta += 4;\n\t\tb += 4;\n\n\t\tif((worst_dist > 0) && (result > worst_dist)){\n\t\t\treturn result;\n\t\t}\n\t}\n\t/* Process last 0-3 pixels.  Not needed for standard vector lengths. */\n\twhile(a < last){\n\t\tdiff0 = (*a++ - *b++);\n\t\tresult += diff0 * diff0;\n\t}\n\treturn result;\n}\r\n\r\n\r\n_MTF_END_NAMESPACE\r\n\r\n", "meta": {"hexsha": "0925949d30cce93ce319297b257fffcfea9e4d91", "size": 20149, "ext": "cc", "lang": "C++", "max_stars_repo_path": "AM/src/SSDBase.cc", "max_stars_repo_name": "abhineet123/MTF", "max_stars_repo_head_hexsha": "6cb45c88d924fb2659696c3375bd25c683802621", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 100.0, "max_stars_repo_stars_event_min_datetime": "2016-12-11T00:34:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T23:03:40.000Z", "max_issues_repo_path": "AM/src/SSDBase.cc", "max_issues_repo_name": "abhineet123/MTF", "max_issues_repo_head_hexsha": "6cb45c88d924fb2659696c3375bd25c683802621", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2017-09-04T06:27:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T19:07:23.000Z", "max_forks_repo_path": "AM/src/SSDBase.cc", "max_forks_repo_name": "abhineet123/MTF", "max_forks_repo_head_hexsha": "6cb45c88d924fb2659696c3375bd25c683802621", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2017-02-19T02:12:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-23T03:47:55.000Z", "avg_line_length": 33.1398026316, "max_line_length": 122, "alphanum_fraction": 0.6851952951, "num_tokens": 6494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.44146453037222166}}
{"text": "//  (C) Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//\r\n// This is not a complete header file, it is included by gamma.hpp\r\n// after it has defined it's definitions.  This inverts the incomplete\r\n// gamma functions P and Q on the first parameter \"a\" using a generic\r\n// root finding algorithm (TOMS Algorithm 748).\r\n//\r\n\r\n#ifndef BOOST_MATH_SP_DETAIL_GAMMA_INVA\r\n#define BOOST_MATH_SP_DETAIL_GAMMA_INVA\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/math/tools/toms748_solve.hpp>\r\n#include <boost/cstdint.hpp>\r\n\r\nnamespace boost{ namespace math{ namespace detail{\r\n\r\ntemplate <class T, class Policy>\r\nstruct gamma_inva_t\r\n{\r\n   gamma_inva_t(T z_, T p_, bool invert_) : z(z_), p(p_), invert(invert_) {}\r\n   T operator()(T a)\r\n   {\r\n      return invert ? p - boost::math::gamma_q(a, z, Policy()) : boost::math::gamma_p(a, z, Policy()) - p;\r\n   }\r\nprivate:\r\n   T z, p;\r\n   bool invert;\r\n};\r\n\r\ntemplate <class T, class Policy>\r\nT inverse_poisson_cornish_fisher(T lambda, T p, T q, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING\r\n   // mean:\r\n   T m = lambda;\r\n   // standard deviation:\r\n   T sigma = sqrt(lambda);\r\n   // skewness\r\n   T sk = 1 / sigma;\r\n   // kurtosis:\r\n   // T k = 1/lambda;\r\n   // Get the inverse of a std normal distribution:\r\n   T x = boost::math::erfc_inv(p > q ? 2 * q : 2 * p, pol) * constants::root_two<T>();\r\n   // Set the sign:\r\n   if(p < 0.5)\r\n      x = -x;\r\n   T x2 = x * x;\r\n   // w is correction term due to skewness\r\n   T w = x + sk * (x2 - 1) / 6;\r\n   /*\r\n   // Add on correction due to kurtosis.\r\n   // Disabled for now, seems to make things worse?\r\n   //\r\n   if(lambda >= 10)\r\n      w += k * x * (x2 - 3) / 24 + sk * sk * x * (2 * x2 - 5) / -36;\r\n   */\r\n   w = m + sigma * w;\r\n   return w > tools::min_value<T>() ? w : tools::min_value<T>();\r\n}\r\n\r\ntemplate <class T, class Policy>\r\nT gamma_inva_imp(const T& z, const T& p, const T& q, const Policy& pol)\r\n{\r\n   BOOST_MATH_STD_USING  // for ADL of std lib math functions\r\n   //\r\n   // Special cases first:\r\n   //\r\n   if(p == 0)\r\n   {\r\n      return tools::max_value<T>();\r\n   }\r\n   if(q == 0)\r\n   {\r\n      return tools::min_value<T>();\r\n   }\r\n   //\r\n   // Function object, this is the functor whose root\r\n   // we have to solve:\r\n   //\r\n   gamma_inva_t<T, Policy> f(z, (p < q) ? p : q, (p < q) ? false : true);\r\n   //\r\n   // Tolerance: full precision.\r\n   //\r\n   tools::eps_tolerance<T> tol(policies::digits<T, Policy>());\r\n   //\r\n   // Now figure out a starting guess for what a may be, \r\n   // we'll start out with a value that'll put p or q\r\n   // right bang in the middle of their range, the functions\r\n   // are quite sensitive so we should need too many steps\r\n   // to bracket the root from there:\r\n   //\r\n   T guess;\r\n   T factor = 8;\r\n   if(z >= 1)\r\n   {\r\n      //\r\n      // We can use the relationship between the incomplete \r\n      // gamma function and the poisson distribution to\r\n      // calculate an approximate inverse, for large z\r\n      // this is actually pretty accurate, but it fails badly\r\n      // when z is very small.  Also set our step-factor according\r\n      // to how accurate we think the result is likely to be:\r\n      //\r\n      guess = 1 + inverse_poisson_cornish_fisher(z, q, p, pol);\r\n      if(z > 5)\r\n      {\r\n         if(z > 1000)\r\n            factor = 1.01f;\r\n         else if(z > 50)\r\n            factor = 1.1f;\r\n         else if(guess > 10)\r\n            factor = 1.25f;\r\n         else\r\n            factor = 2;\r\n         if(guess < 1.1)\r\n            factor = 8;\r\n      }\r\n   }\r\n   else if(z > 0.5)\r\n   {\r\n      guess = z * 1.2f;\r\n   }\r\n   else\r\n   {\r\n      guess = -0.4f / log(z);\r\n   }\r\n   //\r\n   // Max iterations permitted:\r\n   //\r\n   boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\r\n   //\r\n   // Use our generic derivative-free root finding procedure.\r\n   // We could use Newton steps here, taking the PDF of the\r\n   // Poisson distribution as our derivative, but that's\r\n   // even worse performance-wise than the generic method :-(\r\n   //\r\n   std::pair<T, T> r = bracket_and_solve_root(f, guess, factor, false, tol, max_iter, pol);\r\n   if(max_iter >= policies::get_max_root_iterations<Policy>())\r\n      policies::raise_evaluation_error<T>(\"boost::math::gamma_p_inva<%1%>(%1%, %1%)\", \"Unable to locate the root within a reasonable number of iterations, closest approximation so far was %1%\", r.first, pol);\r\n   return (r.first + r.second) / 2;\r\n}\r\n\r\n} // namespace detail\r\n\r\ntemplate <class T1, class T2, class Policy>\r\ninline typename tools::promote_args<T1, T2>::type \r\n   gamma_p_inva(T1 x, T2 p, const Policy& pol)\r\n{\r\n   typedef typename tools::promote_args<T1, T2>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   typedef typename policies::normalise<\r\n      Policy, \r\n      policies::promote_float<false>, \r\n      policies::promote_double<false>, \r\n      policies::discrete_quantile<>,\r\n      policies::assert_undefined<> >::type forwarding_policy;\r\n\r\n   if(p == 0)\r\n   {\r\n      return tools::max_value<result_type>();\r\n   }\r\n   if(p == 1)\r\n   {\r\n      return tools::min_value<result_type>();\r\n   }\r\n\r\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(\r\n      detail::gamma_inva_imp(\r\n         static_cast<value_type>(x), \r\n         static_cast<value_type>(p), \r\n         1 - static_cast<value_type>(p), \r\n         pol), \"boost::math::gamma_p_inva<%1%>(%1%, %1%)\");\r\n}\r\n\r\ntemplate <class T1, class T2, class Policy>\r\ninline typename tools::promote_args<T1, T2>::type \r\n   gamma_q_inva(T1 x, T2 q, const Policy& pol)\r\n{\r\n   typedef typename tools::promote_args<T1, T2>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   typedef typename policies::normalise<\r\n      Policy, \r\n      policies::promote_float<false>, \r\n      policies::promote_double<false>, \r\n      policies::discrete_quantile<>,\r\n      policies::assert_undefined<> >::type forwarding_policy;\r\n\r\n   if(q == 1)\r\n   {\r\n      return tools::max_value<result_type>();\r\n   }\r\n   if(q == 0)\r\n   {\r\n      return tools::min_value<result_type>();\r\n   }\r\n\r\n   return policies::checked_narrowing_cast<result_type, forwarding_policy>(\r\n      detail::gamma_inva_imp(\r\n         static_cast<value_type>(x), \r\n         1 - static_cast<value_type>(q), \r\n         static_cast<value_type>(q), \r\n         pol), \"boost::math::gamma_q_inva<%1%>(%1%, %1%)\");\r\n}\r\n\r\ntemplate <class T1, class T2>\r\ninline typename tools::promote_args<T1, T2>::type \r\n   gamma_p_inva(T1 x, T2 p)\r\n{\r\n   return boost::math::gamma_p_inva(x, p, policies::policy<>());\r\n}\r\n\r\ntemplate <class T1, class T2>\r\ninline typename tools::promote_args<T1, T2>::type\r\n   gamma_q_inva(T1 x, T2 q)\r\n{\r\n   return boost::math::gamma_q_inva(x, q, policies::policy<>());\r\n}\r\n\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#endif // BOOST_MATH_SP_DETAIL_GAMMA_INVA\r\n\r\n\r\n\r\n", "meta": {"hexsha": "86f4a0b5d57e31dfe08465d3cc6705c451ced3e6", "size": 7049, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "windows/include/boost/math/special_functions/detail/gamma_inva.hpp", "max_stars_repo_name": "jaredhoberock/gotham", "max_stars_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-12-29T07:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-29T10:47:38.000Z", "max_issues_repo_path": "windows/include/boost/math/special_functions/detail/gamma_inva.hpp", "max_issues_repo_name": "jaredhoberock/gotham", "max_issues_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "windows/include/boost/math/special_functions/detail/gamma_inva.hpp", "max_forks_repo_name": "jaredhoberock/gotham", "max_forks_repo_head_hexsha": "e3551cc355646530574d086d7cc2b82e41e8f798", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1239316239, "max_line_length": 209, "alphanum_fraction": 0.6080295077, "num_tokens": 1954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.44146451669846304}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// importance_sampling::sampler.hpp                                          //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_IMPORTANCE_SAMPLING_SAMPLER_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_IMPORTANCE_SAMPLING_SAMPLER_HPP_ER_2009\n#include <vector>\n#include <boost/mpl/not.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/call_traits.hpp>\n#include <boost/type_traits.hpp>\n#include <boost/utility.hpp>\n#include <boost/range.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/uniform_real.hpp>\n// TODO #include <boost/random/discrete_distributionhpp> when becomes avail\n#include <boost/random/discrete_distribution_sw_2009.hpp> \n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace importance_sampling{\n\n// Samples by SIR given a set of proposal values and their unnormalized weights\n//\n// Models RandomDistribution\n//\n// R1:  type of a range values \n// W:   type of each weight\ntemplate<typename R1,typename W>\nclass sampler{\n    typedef typename remove_reference<R1>::type         const_values_;\n    typedef typename remove_cv<const_values_>::type     values_t;    \n    typedef typename range_size<values_t>::type         size_;\n    typedef is_reference<R1>                            is_ref_;\n    public:\n    typedef typename range_value<const_values_>::type   result_type;\n    private:\n    typedef random::discrete_distribution<size_,W>      discr_dist_t;\n    public:\n    typedef typename discr_dist_t::input_type           input_type;\n\n    sampler(){}\n    template<typename R0>\n    sampler(\n        const R0& unnormalized_weights,\n        typename call_traits<R1>::param_type values\n    ):discr_dist_(\n        boost::begin(unnormalized_weights),\n        boost::end(unnormalized_weights)\n    ),values_(values){\n        BOOST_ASSERT(\n            boost::size(unnormalized_weights) == boost::size(this->values())\n        );\n    }\n    \n    sampler(const sampler& that)\n        :discr_dist_(that.discr_dist_),values_(that.values_){}\n    \n    sampler& operator=(const sampler& that)\n    {\n        if(&that!=this){\n            discr_dist_ = that.discr_dist_;\n            values_ = that.values_;\n        }\n        return (*this);\n    }\n\n    template<typename U> \n    result_type operator()(U& urng)const\n    {\n        typedef typename discr_dist_t::result_type k_t;\n        k_t k = discr_dist_(urng);\n        BOOST_ASSERT( k < boost::size(this->values()) );\n        return (*boost::next(boost::begin(this->values()),k));\n    }    \n    const discr_dist_t& discrete_distribution()const\n    {\n        return this->discr_dist_;     \n    }\n\n    // TODO os/is\n\n    typename call_traits<R1>::const_reference values()const{\n        return this->values_;\n    }\n\n    private:\n    discr_dist_t discr_dist_;\n    typename call_traits<R1>::value_type values_;\n};\n\n    template<typename R0,typename R1>\n    sampler<\n        R0,\n        typename remove_cv<\n            typename remove_reference<\n                typename range_value<R0>::type\n            >::type\n        >::type\n    >\n    make_sampler(\n        const R0& unnormalized_weights,\n        typename call_traits<R1>::param_type values\n    )\n    {\n        typedef sampler<\n            R0,\n            typename remove_cv<\n                typename remove_reference<\n                    typename range_value<R0>::type\n                >::type\n            >::type\n        > result_;\n        return result_(unnormalized_weights,values);\n    }\n\n}// importance_sampling\n}// detail\n}// statistics\n}// boost\n\n#endif ", "meta": {"hexsha": "55ef7350dd51cfb92a80bb3bf6fcaddc36b0db16", "size": 3958, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "importance_sampling/boost/statistics/detail/importance_sampling/random/sampler.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "importance_sampling/boost/statistics/detail/importance_sampling/random/sampler.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "importance_sampling/boost/statistics/detail/importance_sampling/random/sampler.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4126984127, "max_line_length": 79, "alphanum_fraction": 0.599292572, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.441464516698463}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__FEEDBACK__ASIF_FUNC_HPP_\n#define SMOOTH__FEEDBACK__ASIF_FUNC_HPP_\n\n/**\n * @file\n * @brief Functions for active Set Invariance (ASI) filtering on Lie groups.\n */\n\n#include <Eigen/Core>\n#include <boost/numeric/odeint.hpp>\n#include <smooth/compat/odeint.hpp>\n#include <smooth/diff.hpp>\n#include <smooth/lie_group.hpp>\n\n#include \"common.hpp\"\n#include \"qp.hpp\"\n\nnamespace smooth::feedback {\n\n/**\n * @brief Active set invariance problem definition.\n *\n * The active set invariance problem is\n * \\f[\n * \\begin{cases}\n *  \\min_u        & (u \\ominus u_{des})' W_u (u \\ominus u_{des})  \\\\\n *  \\text{s.t.}   & x(0) = x_0 \\\\\n *                & u \\in ulim \\\\\n *                & h(x(t)) \\geq 0, \\quad t \\in [0, T]    \\\\\n * \\end{cases}\n * \\f]\n * for a system \\f$ \\mathrm{d}^r x_t = f(x(t), u(t)) \\f$.\n */\ntemplate<LieGroup G, Manifold U>\n  requires(Dof<G> > 0 && Dof<U> > 0)\nstruct ASIFProblem\n{\n  /// time horizon\n  double T{1};\n  /// initial state\n  G x0{Default<G>()};\n  /// desired input\n  U u_des{Default<U>()};\n  /// weights on desired input\n  Eigen::Matrix<double, Dof<U>, 1> W_u{Eigen::Matrix<double, Dof<U>, 1>::Ones()};\n  /// input bounds\n  ManifoldBounds<U> ulim{};\n};\n\n/**\n * @brief Parameters for asif_to_qp\n */\nstruct ASIFtoQPParams\n{\n  /// number of constraint instances (equally spaced over the time horizon)\n  std::size_t K{10};\n  /// barrier function time constant \\f$ \\alpha \\f$ s.t. \\f$ \\dot h - \\alpha h \\geq 0 \\f$.\n  double alpha{1};\n  /// maximal integration time step\n  double dt{0.1};\n  /// relaxation cost\n  double relax_cost{100};\n};\n\n/**\n * @brief Allocate QP matrices (part 1 of asif_to_qp())\n *\n * @param[in] K number of constraint instances\n * @param[in] nu_ineq number in inequalities in input constraint\n * @param[in] nh number of barrier constraints\n * @param[out] qp allocated QP with zero matrices\n */\ntemplate<LieGroup G, Manifold U>\n  requires(Dof<G> > 0 && Dof<U> > 0)\nvoid asif_to_qp_allocate(\n  std::size_t K, std::size_t nu_ineq, std::size_t nh, QuadraticProgram<-1, -1, double> & qp)\n{\n  static constexpr int nx = Dof<G>;\n  static constexpr int nu = Dof<U>;\n\n  static_assert(nx > 0, \"State space dimension must be static\");\n  static_assert(nu > 0, \"Input space dimension must be static\");\n\n  const int M = K * nh + nu_ineq + 1;\n  const int N = nu + 1;\n\n  qp.A.setZero(M, N);\n  qp.l.setZero(M);\n  qp.u.setZero(M);\n\n  qp.P.setZero(N, N);\n  qp.q.setZero(N);\n}\n\n/**\n * @brief Fill QP matrices (part 2 of asif_to_qp())\n *\n * Note that the (dense) QP matrices must be pre-allocated and filled with zeros.\n */\ntemplate<\n  LieGroup G,\n  Manifold U,\n  typename Dyn,\n  typename SafeSet,\n  typename BackupU,\n  diff::Type DT = diff::Type::Default>\n  requires(Dof<G> > 0 && Dof<U> > 0)\nvoid asif_to_qp_fill(\n  const ASIFProblem<G, U> & pbm,\n  const ASIFtoQPParams & prm,\n  Dyn && f,\n  SafeSet && h,\n  BackupU && bu,\n  QuadraticProgram<-1, -1, double> & qp)\n{\n  using boost::numeric::odeint::euler, boost::numeric::odeint::vector_space_algebra;\n  using std::placeholders::_1;\n\n  static constexpr int nx = Dof<G>;\n  static constexpr int nu = Dof<U>;\n  static constexpr int nh = std::invoke_result_t<SafeSet, double, G>::SizeAtCompileTime;\n\n  euler<G, double, Tangent<G>, double, vector_space_algebra> state_stepper{};\n  euler<TangentMap<G>, double, TangentMap<G>, double, vector_space_algebra> sensi_stepper{};\n\n  const int nu_ineq = pbm.ulim.A.rows();\n\n  [[maybe_unused]] const int M = prm.K * nh + nu_ineq + 1;\n  [[maybe_unused]] const int N = nu + 1;\n\n  assert(qp.A.rows() == M);\n  assert(qp.A.cols() == N);\n  assert(qp.l.rows() == M);\n  assert(qp.u.rows() == M);\n\n  assert(qp.P.rows() == N);\n  assert(qp.P.cols() == N);\n  assert(qp.q.rows() == N);\n\n  // iteration variables\n  const double tau     = pbm.T / static_cast<double>(prm.K);\n  const double dt      = std::min<double>(prm.dt, tau);\n  double t             = 0;\n  G x                  = pbm.x0;\n  TangentMap<G> dx_dx0 = TangentMap<G>::Identity();\n\n  // define ODEs for closed-loop dynamics and its sensitivity\n  const auto x_ode = [&f, &bu](const G & xx, Tangent<G> & dd, double tt) {\n    dd = f(tt, xx, bu(tt, xx));\n  };\n\n  const auto dx_dx0_ode = [&f, &bu, &x](const auto & S_v, auto & dS_dt_v, double tt) {\n    auto f_cl = [&]<typename T>(const CastT<T, G> & vx) { return f(T(tt), vx, bu(T(tt), vx)); };\n    const auto [fcl, dr_fcl_dx] = diff::dr<1, DT>(std::move(f_cl), wrt(x));\n    dS_dt_v                     = (-ad<G>(fcl) + dr_fcl_dx) * S_v;\n  };\n\n  // value of dynamics at call time\n  const auto [f0, d_f0_du] = diff::dr<1, DT>(\n    [&]<typename T>(const CastT<T, U> & vu) { return f(T(t), cast<T>(x), vu); }, wrt(pbm.u_des));\n\n  // loop over constraint number\n  for (auto k = 0u; k != prm.K; ++k) {\n    // differentiate barrier function w.r.t. x\n    const auto [hval, dh_dtx] = diff::dr<1, DT>(\n      [&h]<typename T>(const T & vt, const CastT<T, G> & vx) { return h(vt, vx); }, wrt(t, x));\n\n    const Eigen::Matrix<double, nh, 1> dh_dt  = dh_dtx.template leftCols<1>();\n    const Eigen::Matrix<double, nh, nx> dh_dx = dh_dtx.template rightCols<nx>();\n\n    // insert barrier constraint\n    const Eigen::Matrix<double, nh, nx> dh_dx0 = dh_dx * dx_dx0;\n    qp.A.template block<nh, nu>(k * nh, 0)     = dh_dx0 * d_f0_du;\n    qp.l.template segment<nh>(k * nh)          = -dh_dt - prm.alpha * hval - dh_dx0 * f0;\n    qp.u.template segment<nh>(k * nh).setConstant(std::numeric_limits<double>::infinity());\n\n    // integrate system and sensitivity forward until next constraint\n    double dt_act = std::min(dt, tau * (k + 1) - t);\n    while (t < tau * (k + 1)) {\n      state_stepper.do_step(x_ode, x, t, dt_act);\n      sensi_stepper.do_step(dx_dx0_ode, dx_dx0, t, dt_act);\n      t += dt_act;\n    }\n  }\n\n  // relaxation of barrier constraints\n  qp.A.block(0, nu, prm.K * nh, 1).setConstant(1);\n\n  // input bounds\n  qp.A.block(prm.K * nh, 0, nu_ineq, nu) = pbm.ulim.A;\n  qp.l.segment(prm.K * nh, nu_ineq)      = pbm.ulim.l - pbm.ulim.A * rminus(pbm.u_des, pbm.ulim.c);\n  qp.u.segment(prm.K * nh, nu_ineq)      = pbm.ulim.u - pbm.ulim.A * rminus(pbm.u_des, pbm.ulim.c);\n\n  // upper and lower bounds on delta\n  qp.A(prm.K * nh + nu_ineq, nu) = 1;\n  qp.l(prm.K * nh + nu_ineq)     = 0;\n  qp.u(prm.K * nh + nu_ineq)     = std::numeric_limits<double>::infinity();\n\n  qp.P.template block<nu, nu>(0, 0) = pbm.W_u.asDiagonal();\n\n  qp.P(nu, nu) = prm.relax_cost;\n  qp.q(nu)     = 0;\n}\n\n/**\n * @brief Convert an ASIFProblem to a QuadraticProgram.\n *\n * The objective is to impose constraints on the current input \\f$ u \\f$ of a system \\f$\n * \\mathrm{d}^r x_t = f(x, u) \\f$ s.t.\n * \\f[\n *    \\frac{\\mathrm{d}}{\\mathrm{d}t} h(\\phi(t; x_0, bu(\\cdot)))\n *    \\geq \\alpha h(\\phi(t; x_0, bu(\\cdot)))\n * \\f]\n * which enforces forward invariance of the set \\f$ \\{ x\n * : h(t, x) \\geq 0 \\} \\f$ along the **backup trajectory** \\f$ bu \\f$. The constraint is enforced at\n * \\f$K\\f$ look-ahead time steps \\f$ t_k = k \\tau\\f$ for \\f$k = 0, \\ldots, K \\f$.\n *\n * This function encodes the problem as a QuadraticProgram that solves\n * \\f[\n *  \\begin{cases}\n *   \\min_{\\mu}  & \\left\\| u - u_{des} \\right\\|^2 \\\\\n *   \\text{s.t.} & \\text{constraint above holds for } u = u_{des} + \\mu\n *   \\end{cases}\n * \\f]\n * A solution \\f$ \\mu^* \\f$ to the QuadraticProgram corresponds to an input \\f$ u_{des} \\oplus \\mu^*\n * \\f$ applied to the system.\n *\n * @tparam G state LieGroup type \\f$\\mathbb{G}\\f$\n * @tparam U input Manifold type \\f$\\mathbb{G}\\f$\n *\n * @param pbm problem definition\n * @param prm algorithm parameters\n * @param f system model \\f$f : \\mathbb{R} \\times \\mathbb{G} \\times \\mathbb{U} \\rightarrow\n * \\mathbb{R}^{\\dim \\mathfrak g}\\f$ s.t. \\f$ \\mathrm{d}^r x_t = f(t, x, u) \\f$\n * @param h safe set \\f$h : \\mathbb{R} \\times \\mathbb{G} \\rightarrow \\mathbb{R}^{n_h}\\f$ s.t. \\f$\n * S(t) = \\{ h(t, x) \\geq 0 \\} \\f$ denotes the safe set at time \\f$ t \\f$\n * @param bu backup controller \\f$ub : \\mathbb{R} \\times \\mathbb{G} \\rightarrow \\mathbb{U} \\f$\n *\n * \\note The algorithm relies on automatic differentiation. The following supplied functions must be\n * differentiable (i.e. be templated on the scalar type if an automatic differentiation method is\n * selected):\n *   * \\p f differentiable w.r.t. x and u\n *   * h differentiable w.r.t. t and x\n *   * bu differentiable w.r.t. x\n *\n * @return QuadraticProgram modeling the ASIF filtering problem\n */\ntemplate<\n  LieGroup G,\n  Manifold U,\n  typename Dyn,\n  typename SS,\n  typename BackupU,\n  diff::Type DT = diff::Type::Default>\nQuadraticProgram<-1, -1, double> asif_to_qp(\n  const ASIFProblem<G, U> & pbm, const ASIFtoQPParams & prm, Dyn && f, SS && h, BackupU && bu)\n{\n  static constexpr int nh = std::invoke_result_t<SS, double, G>::SizeAtCompileTime;\n\n  static_assert(Dof<G> > 0, \"State space dimension must be static\");\n  static_assert(Dof<U> > 0, \"Input space dimension must be static\");\n  static_assert(nh > 0, \"Safe set dimension must be static\");\n\n  const int nu_ineq = pbm.ulim.A.rows();\n  QuadraticProgram<-1, -1, double> qp;\n  asif_to_qp_allocate<G, U>(prm.K, nu_ineq, nh, qp);\n  asif_to_qp_fill(pbm, prm, f, h, bu, qp);\n  return qp;\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__INTERNAL__ASIF_FUNC_HPP_\n", "meta": {"hexsha": "baf83ad7d1ae91f9badb01ad5be2a76ed46c0d73", "size": 10437, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/asif_func.hpp", "max_stars_repo_name": "pettni/smooth_feedback", "max_stars_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "include/smooth/feedback/asif_func.hpp", "max_issues_repo_name": "pettni/smooth_feedback", "max_issues_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "include/smooth/feedback/asif_func.hpp", "max_forks_repo_name": "pettni/smooth_feedback", "max_forks_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 34.9063545151, "max_line_length": 100, "alphanum_fraction": 0.6433841142, "num_tokens": 3340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.44137441675382527}}
{"text": "//=======================================================================\n// Copyright 2015 - 2020 Jeff Linahan\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include \"theorem4.h\"\n#include \"strutil.h\"\n#include \"graphutil.h\"\n#include \"lemmas.h\"\n#include \"BFSVisitor.h\"\n#include <boost/graph/copy.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/is_straight_line_drawing.hpp>\n#include <boost/graph/make_maximal_planar.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/bimap.hpp>\n#include <boost/config.hpp>\n#include <iostream>\nusing namespace std;\nusing namespace boost;\n\n// may be able to inline this and hoist it out of the if blocks of theorem4_disconnected if we're able to get rid of bigger_than_two_thirds\nuint lowest_i(uint n, uint num_components, vector<uint> const& num_verts_per_component)\n{\n        uint total_cost = 0;\n        uint i = 0;\n        for( ; i < num_components; ++i ){\n                total_cost += num_verts_per_component[i];\n                if ( total_cost*3 > n ) return i;\n        } \n\n        return -1;\n}\n\n\n// L[l] = # of vertices on level l\nPartition theorem4_connected(GraphCR g, vector<uint> const& L, uint l[3], uint r, Graph* g_shrunk, BFSVisitorData const* bfs2)\n{\n        uint n = num_vertices(g);\n        cout << \"g:\\n\";\n        //print_graph(g);\n        vertex_t v;\n\n        // l1 = the level such that the sum of costs in levels 0 thru l1-1 < 1/2, but the sum of costs in levels 0 thru l1 is >= 1/2\n        uint total = 0;\n        uint level = 0;\n        while( total < n/2 ){ \n                total += L[level++];\n        }\n\n        uint l1 = level;\n\n        BOOST_ASSERT(1 == L[0]);\n        // Partition the vertices into levels according to their distance from some vertex v.\n        //uint r;\n        /*If r is the maximum distance of any vertex from v, define additional levels -1 and r+1 containing no vertices*/\n        //uint l[3];\n        //(If no such l1 exists, the total cost of all vertices < 1/2, and B = C = {} and return true) */\n        uint k = 0;// = # of vertices on levels 0 thru l1.\n        for( uint i = 0; i <= l1; ++i ) k += L[i];\n\n        /*Find a level l0 such that l0 <= l1 and |L[l0]| + 2(l1-l0) <= 2sqrt(k)\n        Find a level l2 such that l1+1 <= l2 and |L[l2] + 2(l2-l1-1) <= 2sqrt(n-k) */\n        uint sqrtk = 2*sqrt(k);\n        uint sqrtnk = 2*sqrt(n-k);\n\n        uint l0 = l1;\n        while( L[l0] + 2*(l1-l0) > sqrtk ) --l0;\n\n        uint l2 = l1+1;\n        while( L[l2] + 2*(l2-l1-1) > sqrtnk) ++l2;\n        \n        BOOST_ASSERT(l0 <= l1);\n        BOOST_ASSERT(l1+1 <= l2);\n\n        BFSVisitorData bfs(&g, *vertices(g).first);\n        breadth_first_search(g, bfs.root, boost::visitor(BFSVisitor(bfs)));\n        cout << \"bfsroot: \" << bfs.root << '\\n';\n\n        vector<vertex_t> cycle;\n        l1 -= 2;\n        --l2;\n        Partition p = lemma3(g, L, l1, l2, r, bfs, *bfs2, cycle, g_shrunk);\n\n        uint climit = sqrtk - sqrtnk;\n        BOOST_ASSERT(p.verify_edges(g));\n        //BOOST_ASSERT(p.verify_sizes_lemma3(L, l1, l2));\n\n        /*If 2 such levels exist, then by Lemma 3 the vertices of G can be partitioned into three sets A, B, C such that no edge joins a vertex in A with a vertex in B,\n        neither A or C has cost > 2/3, and C contains no more than 2(sqrt(k) + sqrt(n-k)) vertices.\n        But 2(sqrt(k) + sqrt(n-k) <= 2(sqrt(n/2) + sqrt(n/2)) = 2sqrt(2)sqrt(n)\n        Thus the theorem holds if suitable levels l0 and l2 exist\n                Suppose a suitable level l0 does not exist.  Then, for i <= l1, L[i] >= 2sqrt(k) - 2(l1-i)\n                Since L[0] = 1, this means 1 >= 2sqrt(k) - 2l1 and l1 + 1/2 >= sqrt(k).  Thus l1 = floor(l1 + 1/2) > \n                Contradiction*/\n\n        return p; \n}\n\n\nPartition theorem4_ccbigger23(GraphCR g_all, Partition const& biggest_comp_p)\n{ \n        uint alln = num_vertices(g_all);\n        cout << \"alln: \" << alln << '\\n';\n\n        Graph g_comp(g_all); // connected component\n\n        auto g_all_prop_map = get(vertex_index, g_all);\n        auto g_comp_prop_map = get(vertex_index, g_comp);\n\n        auto vertid_to_vert_t = [&](uint id, decltype(get(vertex_index, g_all)) prop_map)\n        { \n                VertIter vit, vjt;\n                tie(vit, vjt) = vertices(g_all); \n                for( ; vit != vjt; ++vit ){\n                        if( prop_map[*vit] == id ) return *vit; \n                } \n                return Graph::null_vertex();\n        };\n\n        // for all vertices v in g_comp,\n        vector<vertex_t> toremove;\n        VertIter vit, vjt;\n        tie(vit, vjt) = vertices(g_comp); \n        for( ; vit != vjt; ++vit ){\n                vertex_t v = *vit;\n                cout << \"currently examining \" << v << \" comp_propmap\" << g_comp_prop_map[v] << '\\n';\n                // cv = lookup the corresponding vertex in g_all\n                vertex_t cv = vertid_to_vert_t(g_all_prop_map[v], g_all_prop_map);\n                cout << \"       with cv \" << cv << \" all_propmap\" << g_all_prop_map[v] << '\\n';\n                // if cv is not in biggest_comp_p,\n                if( !biggest_comp_p.a.contains(cv) && \n                    !biggest_comp_p.b.contains(cv) && \n                    !biggest_comp_p.c.contains(cv) ){ \n                        // delete v from g_comp\n                            toremove.push_back(v);\n                    }\n\n        }\n\n        cout << \"gcomp:\\n\";\n        //print_graph(g_comp);\n        //print_graph_addresses(g_comp);\n\n        uint nremove = toremove.size();\n        cout << \"nremove: \" << nremove << '\\n';\n        for(auto& v : toremove ){\n                cout << \"   nr: \" << v << '\\n'; \n                kill_vertex(v, g_comp); \n        }\n\n        reset_vertex_indices(g_comp);\n\n\n        cout << \"gcomp:\\n\";\n        //print_graph(g_comp);\n        //print_graph_addresses(g_comp);\n        BFSVisitorData vd(&g_comp, *vertices(g_comp).first);\n        breadth_first_search(g_comp, vd.root, boost::visitor(BFSVisitor(vd)));\n\n        // disabled because they don't support multiple connected components\n        //BOOST_ASSERT(assert_verts(g_orig, vis_data_orig));\n        //BOOST_ASSERT(assert_verts(g_copy, vis_data_copy));\n\n        uint n = num_vertices(g_comp);\n\n        vector<uint> L(vd.num_levels + 1, 0);\n\tcout << \"L levels: \" << L.size() << '\\n';\n        for( auto& d : vd.verts ){\n                cout << \"level: \" << d.second.level << '\\n';\n\t       \t++L[d.second.level];\n\t}\n\n        uint k = L[0]; \n        uint l[3];\n        l[1] = 0;\n        while( k <= n/2 ){\n                uint indx = ++l[1];\n                uint lsize = L.size();\n                if( indx >= lsize ) break;\n\t       \tk += L.at(indx);\n\t}\n\n        float sq  = 2 * sqrt(k); \n        float snk = 2 * sqrt(num_vertices(g_comp) - k);\n        cout << \"sq:     \" << sq << '\\n';\n        cout << \"snk:    \" << snk << '\\n';\n        cout << \"L size: \" << L.size() << '\\n';\n\n        l[0] = l[1];\n        cout << \"l[0]:   \" << l[0] << '\\n';\n        while( l[0] < L.size() ){\n                float val = L.at(l[0]) + 2*(l[1] - l[0]);\n                if( val <= sq ) break;\n                --l[0];\n        }\n        cout << \"l0: \" << l[0] << \"     highest level <= l1\\n\";\n\n        l[2] = l[1] + 1;\n        cout << \"l[2]\" << l[2] << '\\n';\n        while( l[2] < L.size() ){\n                float val = L.at(l[2]) + 2*(l[2] - l[1] - 1);\n                if( val <= snk ) break;\n                ++l[2];\n        }\n        cout << \"l2: \" << l[2] << \"     lowest  level >= l1 + 1\\n\";\n\n        uint r = vd.num_levels - 1;\n\n        Partition star_p = theorem4_connected(g_comp, L, l, r, nullptr, nullptr);\n        // ????\n\n        Partition p;\n        p.c = star_p.c;\n        p.b.insert(STLALL(toremove));\n        if( star_p.a.size() > star_p.b.size() ){\n                p.a = star_p.a; \n                p.b.insert(STLALL(star_p.b));\n        } else {\n                p.a = star_p.b;\n                p.b.insert(STLALL(star_p.a));\n        }\n        return p; \n}\n\nPartition theorem4_disconnected(GraphCR g, uint n, uint num_components, associative_property_map<vertex_map> const& vertid_to_component, vector<uint> const& num_verts_per_component, Partition const& biggest_comp_p)\n{\n        vector<vector<VertIter>> vertex_sets; // set of vertex ids, indexed by component number (second vector should be set but compiler did not like call to .insert())\n\n        vertex_sets.resize(num_components);\n\n        // populate vertex sets\n        VertIter vit, vjt;\n        tie(vit, vjt) = vertices(g);\n        for( uint i = 0; vit != vjt; ++vit, ++i ){\n                uint component = vertid_to_component[*vit];\n                vector<VertIter>& vset = vertex_sets[component];\n                vset.push_back(vit);\n        }\n\n        // Let G1, G2, ... , Gk be the connected components of G, with vertex sets V1, V2, ... , Vk respectively.\n        bool bigger_than_one_third = false;\n        bool bigger_than_two_thirds = false;\n        for( uint i = 0; i < num_components; ++i ){\n                if( num_verts_per_component[i] > n    /3.0 ) bigger_than_one_third  = true;\n                if( num_verts_per_component[i] > n*2.0/3.0 ){ bigger_than_two_thirds = true; break;}\n        }\n\n        if( !bigger_than_one_third ){ \n\n                // If no connected component has total vertex cost > 1/3, let i be the minimum index such that the total cost of V1 U V2 U ... U Vi > 1/3\n                int i = lowest_i(n, num_components, num_verts_per_component); // -1 indicates no such index found\n\n                Partition p;\n\n                // populate partition A = V1 U V2 U ... U Vi \n                for( int j = 0; j <= i; ++j ){\n                        vector<VertIter>& vec = vertex_sets[j];\n                        for( VertIter& v : vec ) p.a.insert(*v);\n                }\n\n                // populate partition B = Vi+1 U Vi+2 U ... U Vk\n                for( int j = i+1; j < (int)num_components; ++j ){\n                        vector<VertIter>& vec = vertex_sets[j];\n                        for( VertIter& v : vec ) p.b.insert(*v);\n                }\n\n                // Since i is minimum and the cost of Vi <= 1/3, the cost of A <= 2/3. return true;\n                cout << \"not bigger than one third\\n\";\n                return p;\n        } else if( !bigger_than_two_thirds ){\n                // If some connected component (say Gi) has total vertex cost between 1/3 and 2/3,\n                Partition p; \n\n                int i = lowest_i(n, num_components, num_verts_per_component);\n                BOOST_ASSERT(i >= 0 && num_verts_per_component[i] >= n/3 && num_verts_per_component[i] <= 2*n/3);\n\n                // populate partition A\n                cout << \"!! populating partition A\\n\";\n                for( uint j = 0; j <= i; ++j ){\n                        for( uint v = 0; v < vertex_sets[j].size(); ++v ){\n                                p.a.insert(*vertex_sets[j][v]);\n                        }\n\n                }\n                cout << '\\n';\n\n                // populate partition B, should be everything except what's in partition A\n                cout << \"!! populating partition B\\n\";\n                for( uint j = i+1; j < num_components; ++j ){\n\n                        vector<VertIter>& vset = vertex_sets[j];\n                        for( VertIter& v : vset ){\n                                p.b.insert(*v);\n                                cout << \"v: \" << *v << endl;\n                        }\n                }\n\n                // partition C should be empty \n                BOOST_ASSERT(p.c.empty());\n\n                p.print(&g);\n\n                cout << \"bigger than one third but less than two thirds\\n\";\n                return p;\n        }\n\n        return theorem4_ccbigger23(g, biggest_comp_p);\n}\n\n/* Theorem 4: Let G be any (possibly disconnected) n-vertex planar graph having nonnegative vertex costs summing to no more than one.\nThen the vertices of G can be partitioned into three sets A, B, C such that no edge joins a vertex\nin A with a vertex in B, neither A nor B has total cost exceeding 2/3, and C contains no more than\n2sqrt(2)sqrt(n) vertices :*/\nPartition theorem4(GraphCR g, associative_property_map<vertex_map> const& vertid_to_component, vector<uint> const& num_verts_per_component, Partition const& biggest_comp_p)\n{\n\tuint n = num_vertices(g);\n\tuint num_components = num_verts_per_component.size();\n\tbool is_graph_connected = (num_components == 1);\n\n\tif( is_graph_connected ){\n\t\tcout << \"graph is connected\\n\";\n                vector<uint> L;\n                uint l[3];\n                uint r;\n                BOOST_ASSERT(0);\n                return theorem4_connected(g, L, l, r, nullptr, nullptr);\n\t} else {\n                cout << \"graph is disconnected with \" << num_components << \" components\\n\";\n                return theorem4_disconnected(g, n, num_components, vertid_to_component, num_verts_per_component, biggest_comp_p);\n\t}\n}\n", "meta": {"hexsha": "afc0084cda5ece026775dbf636a9807f26aa1582", "size": 13049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "theorem4.cpp", "max_stars_repo_name": "jeffythedragonslayer/lipton-tarjan", "max_stars_repo_head_hexsha": "d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-05-20T11:20:39.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T15:50:33.000Z", "max_issues_repo_path": "theorem4.cpp", "max_issues_repo_name": "jeffythedragonslayer/lipton-tarjan", "max_issues_repo_head_hexsha": "d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2017-12-02T06:35:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T19:58:56.000Z", "max_forks_repo_path": "theorem4.cpp", "max_forks_repo_name": "jeffythedragonslayer/lipton-tarjan", "max_forks_repo_head_hexsha": "d6f43395ca9d5a459c61cd55ccac6ed6295bc1dd", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-04-19T16:37:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T04:29:33.000Z", "avg_line_length": 38.952238806, "max_line_length": 214, "alphanum_fraction": 0.5223388765, "num_tokens": 3421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4413355834796282}}
{"text": "/**\n * @file EqRoutine.hpp\n * @author A. Domahidi [domahidi@embotech.com]\n * @license (new license) License BSD-3-Clause\n * @copyright Copyright (c) [2012-2015] Automatic Control Lab, ETH Zurich & embotech GmbH, Zurich, Switzerland.\n * @date 2012-2015\n * @brief ECOS - Embedded Conic Solver\n * \n * Modified to c++ code by New York University and Max Planck Gesellschaft, 2017 \n */\n\n#pragma once\n\n#include <memory>\n#include <Eigen/Sparse>\n#include <solver/interface/Cone.hpp>\n#include <solver/interface/SolverSetting.hpp>\n\nnamespace solver {\n\n  /*! Equilibration routine to improve condition number of\n   *  matrices involved in the optimization problem. The method\n   *  provided by default is Ruiz equilibration.\n   */\n  class EqRoutine\n  {\n    public:\n\t  EqRoutine(){}\n\t  ~EqRoutine(){}\n\n\t  void setEquilibration(const Cone& cone, const SolverSetting& stgs, SolverStorage& stg);\n\t  void unsetEquilibration(SolverStorage& stg);\n\t  void scaleVariables(OptimizationVector& opt);\n\n      Vector& equilVec() { return equil_vec_; }\n      const Vector& equilVec() const { return equil_vec_; }\n\n    private:\n\t  void ruizEquilibration(SolverStorage& stg);\n\t  void maxRowsCols(double *row_vec, double *col_vec, const Eigen::SparseMatrix<double>& mat);\n\t  void equilibrateRowsCols(const double *row_vec, const double *col_vec, Eigen::SparseMatrix<double>& mat);\n\t  void unequilibrateRowsCols(const double *row_vec, const double *col_vec, Eigen::SparseMatrix<double>& mat);\n\n    private:\n\t  Vector equil_vec_;\n\t  std::shared_ptr<Cone> cone_;\n\t  std::shared_ptr<SolverSetting> stgs_;\n  };\n\n}\n", "meta": {"hexsha": "1a1c6d521754528c370addd4e622ff56ff6ca46b", "size": 1580, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solver/include/solver/optimizer/EqRoutine.hpp", "max_stars_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_stars_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T17:39:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T00:38:22.000Z", "max_issues_repo_path": "solver/include/solver/optimizer/EqRoutine.hpp", "max_issues_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_issues_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2019-11-11T19:54:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T13:41:47.000Z", "max_forks_repo_path": "solver/include/solver/optimizer/EqRoutine.hpp", "max_forks_repo_name": "ferdinand-wood/kino_dynamic_opt", "max_forks_repo_head_hexsha": "ba6bef170819c55d1d26e40af835a744d1ae663f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-15T14:36:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T10:42:19.000Z", "avg_line_length": 30.9803921569, "max_line_length": 111, "alphanum_fraction": 0.7240506329, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.622459324198198, "lm_q1q2_score": 0.44133557085946085}}
{"text": "/*  $Id: bullcutter.cpp 667 2011-02-14 22:13:45Z anders.e.e.wallin $\n * \n *  Copyright 2010 Anders Wallin (anders.e.e.wallin \"at\" gmail.com)\n *  \n *  This file is part of OpenCAMlib.\n *\n *  OpenCAMlib is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  OpenCAMlib is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <boost/foreach.hpp>\n\n#include \"bullcutter.h\"\n#include \"numeric.h\"\n#include \"ellipse.h\"\n\nnamespace ocl\n{\n\nBullCutter::BullCutter() {\n    std::cout << \" usage: BullCutter( double diameter, double corner_radius, double length ) \\n\";\n    assert(0);\n}\n\nBullCutter::BullCutter(double d, double r, double l) {\n    diameter = d;               assert( d > 0.0 );\n    radius = d/2.0;        // total cutter radius\n    radius1 = d/2.0 - r;   // cylindrical middle part radius\n    radius2 = r;                assert( radius1 > 0.0 ); // corner radius\n    length = l;                 assert( l > 0.0 );\n    xy_normal_length = radius1;\n    normal_length = radius2;\n    center_height = radius2;\n}\n\nMillingCutter* BullCutter::offsetCutter(double d) const {\n    return new BullCutter(diameter+2*d, radius2+d, length+d) ;\n}\n\n// height of cutter at radius r\ndouble BullCutter::height(double r) const {\n    if ( r <= radius1 )\n        return 0.0; // cylinder\n    else if ( r <= radius )\n        return radius2 - sqrt( square(radius2) - square(r-radius1) ); // toroid\n    else {\n        assert(0);\n        return -1;\n    }\n}\n\n// width of cutter at height h\ndouble BullCutter::width(double h) const {\n    return ( h >= radius2 ) ? radius : radius1 + sqrt(square(radius2)-square(radius2-h)) ;\n}\n\n// drop-cutter: vertex and facet are handled in base-class\n\n// drop-cutter: Toroidal cutter edge-test\nCC_CLZ_Pair BullCutter::singleEdgeDropCanonical( const Point& u1, const Point& u2 ) const {\n    if ( isZero_tol( u1.z - u2.z ) ) {  // horizontal edge special case\n        return CC_CLZ_Pair( 0 , u1.z - height(u1.y) );\n    } else { // the general offset-ellipse case\n        double b_axis = radius2;                            // short axis of ellipse = radius2\n        double theta = atan( (u2.z - u1.z) / (u2.x-u1.x) ); // theta is the slope of the line\n        double a_axis = fabs( radius2/sin(theta) );         // long axis of ellipse = radius2/sin(theta)       \n        Point ellcenter(0,u1.y,0);\n        Ellipse e = Ellipse( ellcenter, a_axis, b_axis, radius1);\n        int iters = e.solver_brent();\n        assert( iters < 200 );\n        e.setEllipsePositionHi(u1,u2); // this selects either EllipsePosition1 or EllipsePosition2 and sets it to EllipsePosition_hi\n        // pseudo cc-point on the ellipse/cylinder, in the CL=origo system\n        Point ell_ccp = e.ePointHi();         assert( fabs( ell_ccp.xyNorm() - radius1 ) < 1E-5); // ell_ccp should be on the cylinder-circle  \n        Point cc_tmp_u = ell_ccp.closestPoint(u1,u2); // find real cc-point\n        return CC_CLZ_Pair( cc_tmp_u.x , e.getCenterZ()-radius2);\n    }\n}\n\n// push-cutter: vertex and facet handled by base-class\n\nbool BullCutter::generalEdgePush(const Fiber& f, Interval& i,  const Point& p1, const Point& p2) const {\n    //std::cout << \" BullCutter::generalEdgePush() \\n\";\n    bool result = false;\n    \n    if ( isZero_tol( (p2-p1).xyNorm() ) ) { // this would be a vertical edge\n        return result;\n    }\n    \n    if ( isZero_tol( p2.z-p1.z ) ) // this would be a horizontal edge\n        return result;\n    assert( fabs(p2.z-p1.z) > 0.0 ); // no horiz edges allowed hereafter\n    \n    // p1+t*(p2-p1) = f.p1.z+radius2   =>  \n    double tplane = (f.p1.z + radius2 - p1.z ) / (p2.z-p1.z); // intersect edge with plane at z = ufp1.z\n    Point ell_center = p1+tplane*(p2-p1);                               \n    assert( isZero_tol( fabs(ell_center.z - (f.p1.z+radius2)) ) );\n    Point major_dir = (p2-p1);     \n    assert( major_dir.xyNorm() > 0.0 );               \n    \n    major_dir.z = 0;\n    major_dir.xyNormalize();\n    Point minor_dir = major_dir.xyPerp();\n    double theta = atan( (p2.z - p1.z) / (p2-p1).xyNorm() ); \n    double major_length = fabs( radius2/sin(theta) ) ;\n    double minor_length = radius2;\n    AlignedEllipse e(ell_center, major_length, minor_length, radius1,  major_dir, minor_dir );\n    if ( e.aligned_solver( f ) ) { // now we want the offset-ellipse point to lie on the fiber\n        Point pseudo_cc  = e.ePoint1(); // pseudo cc-point on ellipse and cylinder\n        Point pseudo_cc2 = e.ePoint2();\n        CCPoint cc  = pseudo_cc.closestPoint(p1,p2);\n        CCPoint cc2 = pseudo_cc2.closestPoint(p1,p2);\n        cc.type  = EDGE_POS;\n        cc2.type = EDGE_POS;\n        Point cl  = e.oePoint1() - Point(0,0,center_height);            \n        assert( isZero_tol( fabs(cl.z - f.p1.z)) );\n        Point cl2 = e.oePoint2() - Point(0,0,center_height);            \n        assert( isZero_tol( fabs(cl2.z - f.p1.z)) );\n        double cl_t  = f.tval(cl);\n        double cl_t2 = f.tval(cl2);\n        if ( i.update_ifCCinEdgeAndTrue( cl_t, cc, p1, p2, true ) )\n            result = true;\n        if ( i.update_ifCCinEdgeAndTrue( cl_t2, cc2, p1, p2, true ) )\n            result = true;\n    }\n    //std::cout << \" BullCutter::generalEdgePush() DONE result= \" << result << \"\\n\";\n    return result;\n}\n\nstd::string BullCutter::str() const {\n    std::ostringstream o;\n    o << *this;\n    return o.str();\n}\n\nstd::ostream& operator<<(std::ostream &stream, BullCutter c) {\n  stream << \"BullCutter(d=\" << c.diameter << \", r1=\" << c.radius1 << \" r2=\" << c.radius2 << \", L=\" << c.length <<  \")\";\n  return stream;\n}\n\n} // end namespace\n// end file bullcutter.cpp\n", "meta": {"hexsha": "43004701bae238c863ce17052fd934262241d1fc", "size": 6080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencamlib-read-only/src/cutters/bullcutter.cpp", "max_stars_repo_name": "play113/swer", "max_stars_repo_head_hexsha": "78764c67885dfacb1fa24e494a20681265f5254c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "opencamlib-read-only/src/cutters/bullcutter.cpp", "max_issues_repo_name": "play113/swer", "max_issues_repo_head_hexsha": "78764c67885dfacb1fa24e494a20681265f5254c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "opencamlib-read-only/src/cutters/bullcutter.cpp", "max_forks_repo_name": "play113/swer", "max_forks_repo_head_hexsha": "78764c67885dfacb1fa24e494a20681265f5254c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T13:58:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-04T13:58:00.000Z", "avg_line_length": 40.0, "max_line_length": 143, "alphanum_fraction": 0.6169407895, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.441260785677873}}
{"text": "/*!\n  * \\file\n  * \\brief Include this into the main file to have access to the MHD library and code.\n  */\n#pragma once\n\n// std includes\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <memory>\n// external libraries\n#include <armadillo>\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/gmres.hpp\"\n#include \"viennacl/linalg/bicgstab.hpp\"\n#include \"viennacl/linalg/ilu.hpp\"\n#include \"viennacl/linalg/lu.hpp\"\n#include \"viennacl/linalg/sum.hpp\"\n#include \"viennacl/linalg/maxmin.hpp\"\n#include \"viennacl/tools/random.hpp\"\n#include \"viennacl/linalg/inner_prod.hpp\"\n#include \"viennacl/tools/timer.hpp\"\n#include \"viennacl/forwards.h\"\n\ntypedef viennacl::vector<double> vcl_vec; /*!< GPU arma::vector with ViennaCL */\ntypedef viennacl::compressed_matrix<double> vcl_sp_mat; /*!< GPU sparse matrix with ViennaCL */\ntypedef viennacl::matrix<double> vcl_mat; /*!< GPU dense matrix with ViennaCL */\n\n\n/*!\n * Everything in CoMFi will be in this namespace for safety. This is the top level namespace.\n */\nnamespace comfi\n{\n\n/*!\n* All the classes, enums and types can be found here.\n*/\nnamespace types {\n\n/*!\n * \\struct Settings\n * \\brief The settings for the simulation (used in main loop) are here.\n */\nstruct Settings {\n  /// Maximum number of time steps before simulation end.\n  int max_time_steps = -1;\n  /// Maximum time before simulation end in normalized units. \\f$(t_0)\\f$\n  double max_time = -1.0;\n  /// gmres tolerance\n  double tolerance = 1.e-6;\n  /// Save solution every X time steps\n  int save_dn = -1;\n  /// Save solution every X time steps\n  double save_dt = -1;\n  /// If this run restarts from a previous run\n  bool restart = false;\n  /// Other flags for runtime.\n  uint flags = 0;\n};\n\n/*!\n * \\brief The Boundary Condition enum.\n */\nenum BoundaryCondition {PERIODIC, /*!< Periodic boundary condition (i+1 at right boundary is i=0) */\n                        DIRICHLET, /*!< Dirichlet boundary conditions. Inserting data up to user. */\n                        NEUMANN, /*!< Neumann boundary conditions. (i+1 at right boundary = i) */\n                        MIRROR, /*!< Mirror boundary conditions. (i+1 at right boundary = i or negative that value in case of x component) */\n                        DIMENSIONLESS /*!< This boundary is not in a free dimension. */\n                       };\n\n/*!\n * \\brief The simulation context. Everything needed about the simulation is in here.\n */\nclass Context {\n  /// Current \\f$\\Delta t\\f$ in normalized units of \\ref t_0 .\n  double m_dt = 0.0;\n  /// Current \\f$t\\f$ in normalized units of \\ref t_0 .\n  double m_time_elapsed = 0.0;\n  /// Current step \\f$n\\f$ .\n  uint m_time_step = 0;\n\npublic:\n  // Simulation domain\n  /// Number of grid points in x-direction (horizontal).\n  const arma::uword nx;\n  /// Number of grid points in z-direction (vertical).\n  const arma::uword nz;\n  /// Upper boundary condition in the z-direction.\n  const BoundaryCondition bc_up;\n  /// Lower boundary condition in the z-direction.\n  const BoundaryCondition bc_down;\n  /// Right boundary condition in the x-direction.\n  const BoundaryCondition bc_right;\n  /// Left boundary condition in the x-direction.\n  const BoundaryCondition bc_left;\n\n  /// Settings passed on from main.\n  const Settings settings;\n\n  // Constants\n  /// ratio of specific heats\n  //const double gammamono = 5.0/3.0;\n  const double gammamono = 2.0;\n  /// \\f$alpha_p\\f$ divergence error propogation parameter\n  const double alpha_p = 0.18;\n  /// π\n  const double pi = arma::datum::pi;\n  /// mass of proton in kg\n  const double m_i = arma::datum::m_p;\n  /// permeability of free space\n  const double mu_0 = arma::datum::mu_0;\n  /// boltzmann constant in SI\n  const double k_b = arma::datum::k;\n  /// elementary charge in C\n  const double e_ = arma::datum::ec;\n  // Normalization constants\n  /// Length normalization constant in meters.\n  const double l_0 = 1.0;\n  /// \\f$m^{-3}\\f$ density normalization constant.\n  const double n_0 = 25.0/(36.0*arma::datum::pi);\n  /// Magnetic field normalization constant in Teslas.\n  const double B_0 = 1.0/std::sqrt(4.0*arma::datum::pi);\n  /// Width (x-direction) in normalized units.\n  const double width = l_0;\n  /// Height (z-direction) in normalized units.\n  const double height = l_0;\n  // Derived constants\n  /// \\f$\\Delta x\\f$ in normalized units.\n  const double dx = (width/nx)/l_0;\n  /// \\f$\\Delta z\\f$ in normalized units.\n  const double dz = (height/nz)/l_0;\n  /// \\f$\\Delta s\\f$ (smallest grid length) in normalized units.\n  const double ds = (dx>dz)*dz + (dz>=dx)*dx;\n  /// Normalized mass of electron in kg.\n  const double m_e = arma::datum::m_e/m_i;\n  /// Derived normalization constant of Alfven velocity in m/s. \\f$V_0 = V_A = B_0 / \\sqrt{\\mu_0 n_0 m_i}\\f$\n  const double V_0 = B_0/std::sqrt(mu_0*n_0*m_i);\n  /// Derived normalization constant of time in seconds.\n  const double t_0 = l_0/V_0;\n  /// Derived normalization constant of pressure in Pascals. \\f$p_0 = B_0^2 / \\mu_0\\f$\n  const double p_0 = B_0*B_0/mu_0;\n  /// Derived normalization constant of temperature in Kelvin. \\f$T_0 = p_0 / (n_0 k_b)\\f$\n  const double T_0 = p_0/(n_0*k_b);\n  /// In normalized units, default is sun value of 0.27395 km/s/s.\n  const double g = 0.27395e3*t_0/V_0;\n  /// Derived normalization constant for heat transfer.\n  const double q_0               = p_0*V_0;\n  /// Derived normalization constant for charge in Coulombs.\n  const double e_0               = B_0/(mu_0*n_0*V_0*l_0);\n  /// Normalized elementary charge constant.\n  const double q                 = e_/e_0;\n  /// Derived normalization constant for heat transfer coefficient.\n  const double kappa_0           = q_0*l_0/T_0;\n\n  // Solution index\n  /// Result vector top level index\n  const arma::uword Bx    = 0;\n  /// Result vector top level index\n  const arma::uword Bz    = 1;\n  /// Result vector top level index\n  const arma::uword Bp    = 2;\n  /// Result vector top level index\n  const arma::uword n_n   = 3;\n  /// Result vector top level index\n  const arma::uword Ux    = 4;\n  /// Result vector top level index\n  const arma::uword Uz    = 5;\n  /// Result vector top level index\n  const arma::uword Up    = 6;\n  /// Result vector top level index\n  const arma::uword n_p   = 7;\n  /// Result vector top level index\n  const arma::uword Vx    = 8;\n  /// Result vector top level index\n  const arma::uword Vz    = 9;\n   /// Result vector top level index\n  const arma::uword Vp    = 10;\n  /// Result vector top level index\n  const arma::uword E_n   = 11;\n   /// Result vector top level index\n  const arma::uword E_p   = 12;\n  /// Result vector top level index\n  const arma::uword GLM   = 13;\n\n  // Ranges\n  const viennacl::range r_grid = viennacl::range(0, nx*nz);\n  const viennacl::range r_Np = viennacl::range(n_p, n_p+1);\n  const viennacl::range r_Nn = viennacl::range(n_n, n_n+1);\n  const viennacl::range r_NVx = viennacl::range(Vx, Vx+1);\n  const viennacl::range r_NVz = viennacl::range(Vz, Vz+1);\n  const viennacl::range r_NVp = viennacl::range(Vp, Vp+1);\n  const viennacl::range r_NUx = viennacl::range(Ux, Ux+1);\n  const viennacl::range r_NUz = viennacl::range(Uz, Uz+1);\n  const viennacl::range r_NUp = viennacl::range(Up, Up+1);\n  const viennacl::range r_Ep = viennacl::range(E_p, E_p+1);\n  const viennacl::range r_En = viennacl::range(E_n, E_n+1);\n  const viennacl::range r_Bx = viennacl::range(Bx, Bx+1);\n  const viennacl::range r_Bz = viennacl::range(Bz, Bz+1);\n  const viennacl::range r_Bp = viennacl::range(Bp, Bp+1);\n  const viennacl::range r_GLM = viennacl::range(GLM, GLM+1);\n  const arma::uword num_of_eq = 14;\n\n  Context(arma::uword _nx,\n          arma::uword _nz,\n          BoundaryCondition _bc_up=NEUMANN,\n          BoundaryCondition _bc_down=NEUMANN,\n          BoundaryCondition _bc_right=NEUMANN,\n          BoundaryCondition _bc_left=NEUMANN,\n          const Settings _settings = Settings()\n          ) : nx(_nx), nz(_nz),\n              bc_up(_bc_up),\n              bc_down(_bc_down),\n              bc_right(_bc_right),\n              bc_left(_bc_left),\n              settings(_settings) {\n  }\n\n  /*!\n   * \\brief returns number of grid points per unknown.\n   * \\return Number of grid points per unknown.\n   */\n  arma::uword num_of_grid() const { return nz*nx; }\n\n  /*!\n   * \\brief Set \\f$\\Delta t\\f$ in normalized units of \\ref t_0 .\n   * \\param dt Time step in normalized units of \\ref t_0 .\n   * Since \\ref m_dt is a private member. This variable must be changed through this function.\n   */\n  void set_dt(const double &dt) {\n    m_dt = dt;\n  }\n\n  /*!\n   * \\brief Advance the state of the simulation.\n   * This will advance the state of the simulation so that the \\ref time_elapsed()\n   * and \\ref time_step() are updated.\n   */\n  void advance() {\n    m_time_elapsed += m_dt;\n    m_time_step++;\n  }\n\n  /// Getter of \\f$\\c_h\\f$\n  double c_h() const { return ds/m_dt; }\n  /// Getter of \\f$\\Delta t\\f$\n  double dt() const { return m_dt; }\n  /// Getter of \\f$t\\f$\n  double time_elapsed() const { return m_time_elapsed; }\n  /// Getter of \\f$n\\f$\n  uint time_step() const { return m_time_step; }\n\n  // Matrix range returns\n  inline viennacl::range range(const uint &var) const { return viennacl::range(var, var+1); }\n  inline viennacl::matrix_range<vcl_mat> range(const uint &var, const vcl_mat &xn) {\n    return project(xn, r_grid, range(var));\n  }\n  inline viennacl::matrix_range<vcl_mat> v_Np(const vcl_mat &xn) {\n    return project(xn, r_grid, r_Np);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_Nn(const vcl_mat &xn) {\n    return project(xn, r_grid, r_Nn);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_NVx(const vcl_mat &xn) {\n    return project(xn, r_grid, r_NVx);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_NVz(const vcl_mat &xn) {\n    return project(xn, r_grid, r_NVz);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_NVp(const vcl_mat &xn) {\n    return project(xn, r_grid, r_NVp);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_NUx(const vcl_mat &xn) {\n    return project(xn, r_grid, r_NUx);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_NUz(const vcl_mat &xn) {\n    return project(xn, r_grid, r_NUz);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_NUp(const vcl_mat &xn) {\n    return project(xn, r_grid, r_NUp);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_Bx(const vcl_mat &xn) {\n    return project(xn, r_grid, r_Bx);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_Bz(const vcl_mat &xn) {\n    return project(xn, r_grid, r_Bz);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_Bp(const vcl_mat &xn) {\n    return project(xn, r_grid, r_Bp);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_GLM(const vcl_mat &xn) {\n    return project(xn, r_grid, r_GLM);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_Ep(const vcl_mat &xn) {\n    return project(xn, r_grid, r_Ep);\n  }\n  inline viennacl::matrix_range<vcl_mat> v_En(const vcl_mat &xn) {\n    return project(xn, r_grid, r_En);\n  }\n};\n\n} // namespace types\n\n/*!\n * \\brief Functions to build or apply the 'operators'.\n * Permutations of the matrix.\n */\nnamespace operators {\n\n/*!\n* \\brief Permutate a solution down one cell.\n* \\param xn Solution matrix context.\n* \\param ctx Simulation context.\n* \\return Matrix of \\f$A_{j-1}\\f$\n* Every index is replaced by the cell below it while maintaining boundary conditions.\n*/\nvcl_mat jm1(const vcl_mat &xn, comfi::types::Context ctx);\n\n/*!\n* \\brief Permutate a solution up one cell.\n* \\param xn Solution matrix context.\n* \\param ctx Simulation context.\n* \\return Matrix of \\f$A_{j+1}\\f$\n* Every index is replaced by the cell above it while maintaining boundary conditions.\n*/\nvcl_mat jp1(const vcl_mat &xn, comfi::types::Context ctx);\n\n/*!\n* \\brief Permutate a solution left one cell.\n* \\param xn Solution matrix context.\n* \\param ctx Simulation context.\n* \\return Matrix of \\f$A_{i-1}\\f$\n* Every index is replaced by the cell to the left of it while maintaining boundary conditions.\n*/\nvcl_mat im1(const vcl_mat &xn, comfi::types::Context ctx);\n\n/*!\n* \\brief Permutate a solution right one cell.\n* \\param xn Solution matrix context.\n* \\param ctx Simulation context.\n* \\return Matrix of \\f$A_{i+1}\\f$\n* Every index is replaced by the cell to the right of it while maintaining boundary conditions.\n*/\nvcl_mat ip1(const vcl_mat &xn, comfi::types::Context ctx);\n\n/*!\n * \\brief Permutate a result arma::vector right one cell.\n * \\param ctx Simulation context.\n * \\return Sparse matrix to multiply a result arma::vector by.\n * Every index is replaced by the cell to the right of it while maintaining boundary conditions.\n */\nconst arma::sp_mat buildPip1(comfi::types::Context &ctx);\n\n/*!\n * \\brief Permutate a result arma::vector left one cell.\n * \\param ctx Simulation context.\n * \\return Sparse matrix to multiply a result arma::vector by.\n * Every index is replaced by the cell to the left of it while maintaining boundary conditions.\n */\nconst arma::sp_mat buildPim1(comfi::types::Context &ctx);\n\n} // namespace operators\n\n/*!\n * Utility functions. This namespace contains non-mathematical functions to assist with IO, monitoring, logging and error checking. Also included are RHS and LHS functions.\n */\nnamespace util\n{\n/*!\n * \\brief gettimestr Get current time.\n * \\return const std::string in YYYY-MM-DD-HH-MM format.\n */\nstd::string gettimestr();\n\n/*!\n * \\brief save_solution Saves the solution to the output folder\n * \\param x0 Solution matrix.\n * \\param ctx Simulation context.\n * \\param data_name data set name to save it under in hdf5 tree. Defaults to \"unknowns\"\n * \\return Success or fail.\n */\nbool save_solution(const vcl_mat &x0,\n                   comfi::types::Context &ctx,\n                   const std::string &data_name = \"unknowns\");\n\n/*!\n * \\brief sendtolog Send message to log file.\n * \\param message Message std::string to show in log file.\n * \\param filename The log filename make sure this is always the same.\n */\nvoid sendtolog(const std::string message, const std::string filename);\n\n/*!\n * \\brief Calculate the initial condition based on Orszang-Tang Vortex.\n * \\param ctx Simulation context\n * \\return initial condition matrix\n */\nvcl_mat ot_vortex_ic(comfi::types::Context &ctx);\n\n/*!\n * \\brief Calculate the initial condition based on Sod's Shock Tube.\n * \\param ctx Simulation context\n * \\return initial condition matrix\n */\nvcl_mat shock_tube_ic(comfi::types::Context &ctx);\n\n// Misc\n\n/*!\n * \\brief getmaxV get fast mode speed + local speed OR resistivity speed whichever is faster\n * \\param x0 Solution matrix\n * \\param ctx Simulation context\n * \\return Max characteristic speed in normalized units\n */\ndouble getmaxV(const vcl_mat &x0, comfi::types::Context &ctx);\n\n/*!\n * \\brief vec_to_mat Change a column vector to a viennacl::matrix type with one column\n * \\param vec viennacl::vector\n * \\return viennacl::matrix of one column\n */\nvcl_mat vec_to_mat(const vcl_vec &vec);\n\n/*!\n * \\brief Write a binary file of a field arma::vector. Seperate binary files for each direction.\n * \\param x0 result arma::vector\n * \\param name Name of field, will be used as filename prefix.\n * \\param timestep Time step to save as\n * \\return True if no error.\n */\nbool saveField(const arma::vec &x0, const std::string name, const int timestep);\n\n/*!\n * \\brief Read the arguments passed to the executable and change the Settings struct.\n */\nvoid interpret_arguments(comfi::types::Settings &settings, int argc, char** argv);\n\n/*!\n * \\brief saveScalar Write a binary file of a scalar arma::vector.\n * \\param x0 result arma::vector\n * \\param name Name of scalar, will be used as filename prefix.\n * \\param timestep Time step to save as\n * \\return True if no error.\n */\nbool saveScalar(const arma::vec &x0, const std::string name, const int timestep);\n\n/*!\n * \\brief saveField Write a binary file of a field arma::vector. Seperate binary files for each direction.\n * \\param x0 result arma::vector\n * \\param name Name of field, will be used as filename prefix.\n * \\param timestep Time step to save as\n * \\return True if no error.\n */\nbool saveField(const vcl_vec &x0, const std::string name, const int timestep);\n\n/*!\n * \\brief saveScalar Write a binary file of a scalar arma::vector.\n * \\param x0 result arma::vector\n * \\param name Name of scalar, will be used as filename prefix.\n * \\param timestep Time step to save as\n * \\return True if no error.\n */\nbool saveScalar(const vcl_vec &x0, const std::string name, const int timestep);\n\n} // namespace util\n\n/*!\n * Linear algebra routines and deriving variables and such are all found here.\n */\nnamespace routines\n{\n\n/*!\n * \\brief Build an eigenvalue matrix (wave speeds) for the Lax-Friedrichs scheme in the \\f$x\\f$-direction.\n * \\param p_eig Ion wave speeds.\n * \\param n_eig Neutral wave speeds.\n */\nvcl_mat build_eig_matrix_x(const vcl_mat &xn, comfi::types::Context &ctx);\n\n/*!\n * \\brief Build an eigenvalue matrix (wave speeds) for the Lax-Friedrichs scheme in the \\f$z\\f$-direction.\n * \\param p_eig Ion wave speeds.\n * \\param n_eig Neutral wave speeds.\n */\nvcl_mat build_eig_matrix_z(const vcl_mat &xn, comfi::types::Context &ctx);\n\n/*!\n * \\brief pressure_n Returns the plasma pressure based on the type of energy being used\n * \\param xn Solution matrix\n * \\param ctx Simulation context\n * \\return Simulation pressure matrix in (grid, 1) dimensions\n */\nvcl_mat pressure_p(const vcl_mat &xn, comfi::types::Context &ctx);\n\n/*!\n * \\brief pressure_n Returns the neutral pressure based on the type of energy being used\n * \\param xn Solution matrix\n * \\param ctx Simulation context\n * \\return Simulation pressure matrix in (grid, 1) dimensions\n */\nvcl_mat pressure_n(const vcl_mat &xn, comfi::types::Context &ctx);\n\n/*!\n * \\brief Fx Get flux values in the x direction.\n * \\param xn Solution matrix in the cell edge.\n * \\param xn_ij Solution matrix in the cell center.\n * \\param ctx Simulation context.\n * \\return Flux function matrix results.\n */\nvcl_mat Fx(const vcl_mat &xn, const vcl_mat &xn_ij, comfi::types::Context &ctx);\n\n/*!\n * \\brief Fz Get flux values in the z direction.\n * \\param xn Solution matrix in the cell edge.\n * \\param xn_ij Solution matrix in the cell center.\n * \\param ctx Simulation context.\n * \\return Flux function matrix results.\n */\nvcl_mat Fz(const vcl_mat &xn, const vcl_mat &xn_ij, comfi::types::Context &ctx);\n\n/*!\n * \\brief Re_MUSCL Do flux reconstruction with the MUSCL scheme and any source terms.\n * \\param xn Solution matrix\n * \\param ctx Simulation context\n * \\return Solution.\n */\nvcl_mat Re_MUSCL(const vcl_mat &xn, comfi::types::Context &ctx);\n\n/*!\n * \\brief Flux limiter\n * \\param r ratio of gradients\n * \\return Limiter function values\n */\nvcl_mat fluxl(const vcl_mat &r);\n\n/*!\n * \\brief Get plasma sound speed\n * \\param xn matrix of results\n * \\param ctx Simulation context\n * \\return vector (vcl_mat) of plasma sound speed\n */\nvcl_mat sound_speed_p(const vcl_mat &xn, comfi::types::Context &ctx);\n\n/*!\n * \\brief Get neutral sound speed\n * \\param xn matrix of results\n * \\param ctx Simulation context\n * \\return vector (vcl_mat) of neutral sound speed\n */\nvcl_mat sound_speed_n(const vcl_mat &xn, comfi::types::Context &ctx);\n\n/*!\n * \\brief fast_speed_z Get vertical fast mode speed\n * \\param xn result matrix\n * \\param ctx Simulation context.\n * \\return Column vector vcl_mat of vertical fast mode speed of ions.\n */\nvcl_mat fast_speed_z(const vcl_mat &xn, comfi::types::Context &ctx);\n\n/*!\n * \\brief fast_speed_x Get horizontal fast mode speed\n * \\param xn Result matrix.\n * \\param ctx\tSimulation context.\n * \\return Column vector (vcl_mat) of horizontal fast mode speeds.\n */\nvcl_mat fast_speed_x(const vcl_mat &xn, comfi::types::Context &ctx);\n\n/*!\n * \\brief polyval compute's polynomial using Herner's scheme\n * \\param p polynomial coefficient vector of size (polynomial degree + 1)\n * \\param x vector to be computed\n * \\return result of the polynomial\n */\nvcl_vec polyval(const arma::vec &p, const vcl_vec &x);\n\n/*!\n * \\brief computeRHS_Euler Compute right hand side using Eulerian time stepping.\n * \\param xn Current time step result matrix\n * \\param ctx Simulation context\n * \\return Right hand side result solution matrix\n */\nvcl_mat computeRHS_Euler(const vcl_mat &xn, comfi::types::Context &ctx);\n\n/*!\n * \\brief computeRHS_RK4 Compute right hand side using Runge-Kutta 4 time stepping.\n * \\param xn Current time step result arma::vector\n * \\param dt Change in time\n * \\param t Time elapsed\n * \\param op operators\n * \\param bg Background data\n * \\return  Right hand side result arma::vector\n */\nvcl_mat computeRHS_RK4(const vcl_mat &xn, comfi::types::Context &ctx);\n\n/*!\n * \\brief Shock Tube dirichlet boundary conditions\n * \\param Lxn Left state\n * \\param Rxn Right state\n * \\param ctx Context\n */\nvoid topbc_shock_tube(vcl_mat &Lxn, vcl_mat &Rxn, comfi::types::Context &ctx);\n\n/*!\n * \\brief Shock Tube dirichlet boundary conditions\n * \\param Lxn Left state\n * \\param Rxn Right state\n * \\param ctx Context\n */\nvoid bottombc_shock_tube(vcl_mat &Lxn, vcl_mat &Rxn, comfi::types::Context &ctx);\n\n// inlines\n\n/* inline const vcl_vec div_tvd(const vcl_vec &s_iph, const vcl_vec &s_imh, const vcl_vec &s_jph, const vcl_vec &s_jmh) */\n/* { */\n/*   const vcl_vec xpart = (s_iph-s_imh)/dx; */\n/*   const vcl_vec zpart = (s_jph-s_jmh)/dz; */\n/*   return xpart+zpart; */\n/* } */\n\n} // namespace routines\n\n/*!\n * Solar chromosphere math functions.\n */\nnamespace sol\n{\n\ninline double nu_nn(const double &nn, const double &T, const comfi::types::Context &ctx)\n{\n  const double sigma_nn = 7.73e-19; //m-2\n  const double m_nn = 1.007825*arma::datum::m_u;\n  const double nn_coeff = sigma_nn * std::sqrt(16.0*arma::datum::k/(arma::datum::pi*m_nn));\n  return (nn_coeff * nn * ctx.n_0 * std::sqrt(std::abs(T*ctx.T_0)) * ctx.t_0); // ion-neutral collision rate\n}\n\ninline arma::vec nu_nn(const arma::vec &nn, const arma::vec &T, const comfi::types::Context &ctx)\n{\n  const double sigma_nn = 7.73e-19; //m-2\n  const double m_nn = 1.007825*arma::datum::m_u;\n  const double nn_coeff = sigma_nn * std::sqrt(16.0*arma::datum::k/(arma::datum::pi*m_nn));\n  return (nn_coeff * ctx.n_0 * ctx.t_0 * nn % arma::sqrt(arma::abs(T*ctx.T_0)) ); // ion-neutral collision rate\n}\n\ninline vcl_vec nu_nn(const vcl_vec &nn, const vcl_vec &T, const comfi::types::Context &ctx)\n{\n  const double sigma_nn = 7.73e-19; //m-2\n  const double m_nn = 1.007825*arma::datum::m_u;\n  const double nn_coeff = sigma_nn * std::sqrt(16.0*arma::datum::k/(arma::datum::pi*m_nn));\n  return nn_coeff * ctx.n_0 * ctx.t_0  * viennacl::linalg::element_prod(nn, viennacl::linalg::element_sqrt(T*ctx.T_0)); // ion-neutral collision rate\n}\n\ninline double nu_in(const double &nn, const double &T, const comfi::types::Context &ctx)\n{\n  const double sigma_in = 1.16e-18; //m-2\n  const double m_in = 1.007276466879*1.007825/(1.007276466879+1.007825);\n  const double in_coeff = sigma_in * std::sqrt(8.0*arma::datum::k/(arma::datum::pi*m_in));\n  return (in_coeff * nn * ctx.n_0 * std::sqrt(std::abs(T*ctx.T_0)) * ctx.t_0); // ion-neutral collision rate\n}\n\ninline arma::vec nu_in(const arma::vec &nn, const arma::vec &T, const comfi::types::Context &ctx)\n{\n  const double sigma_in = 1.16e-18; //m-2\n  const double m_in = 1.007276466879*1.007825/(1.007276466879+1.007825);\n  const double in_coeff = sigma_in * std::sqrt(8.0*arma::datum::k/(arma::datum::pi*m_in));\n  return (in_coeff * ctx.n_0 * ctx.t_0 * nn % arma::sqrt(arma::abs(T*ctx.T_0)) ); // ion-neutral collision rate\n}\n\ninline vcl_vec nu_in(const vcl_vec &nn, const vcl_vec &T, const comfi::types::Context &ctx)\n{\n  const double sigma_in = 1.16e-18; //m-2\n  const double m_in = 1.007276466879*1.007825/(1.007276466879+1.007825);\n  const double in_coeff = sigma_in * std::sqrt(8.0*arma::datum::k/(arma::datum::pi*m_in));\n  return in_coeff * ctx.n_0 * ctx.t_0  * viennacl::linalg::element_prod(nn, viennacl::linalg::element_sqrt(T*ctx.T_0)); // ion-neutral collision rate\n}\n\ninline double nu_en(const double &nn, const double &T, const comfi::types::Context &ctx)\n{\n  const double sigma_en = 1.0e-19; //m-2\n  const double m_en = arma::datum::m_e*1.007825*arma::datum::m_u/(arma::datum::m_e+1.007825*arma::datum::m_u);\n  const double en_coeff = sigma_en * std::sqrt(8.0*arma::datum::k/(arma::datum::pi*m_en));\n  return (en_coeff * nn * ctx.n_0 * sqrt(std::abs(T*ctx.T_0)) * ctx.t_0); // electron-neutral collision rate\n}\n\ninline vcl_vec nu_en(const vcl_vec &nn, const vcl_vec &T, const comfi::types::Context &ctx)\n{\n  const double sigma_en = 1.0e-19; //m-2\n  const double m_en = arma::datum::m_e*1.007825*arma::datum::m_u/(arma::datum::m_e+1.007825*arma::datum::m_u);\n  const double en_coeff = sigma_en * std::sqrt(8.0*arma::datum::k/(arma::datum::pi*m_en));\n  return en_coeff * ctx.n_0 * ctx.t_0 * viennacl::linalg::element_prod(nn, viennacl::linalg::element_sqrt(T*ctx.T_0)); // electron-neutral collision rate\n}\n\ninline double nu_ei(const double &ne, const double &T, const comfi::types::Context &ctx)\n{\n  const double coloumb_logarithm = 10.0;\n  const double r = arma::datum::ec*arma::datum::ec/(4.0*arma::datum::pi*arma::datum::eps_0*arma::datum::k);\n  const double sigma_ei = coloumb_logarithm*arma::datum::pi*r*r;\n  const double coeff_ei = (4.0/3.0) * sigma_ei * std::sqrt(2.0*arma::datum::k/(arma::datum::pi*arma::datum::m_e));\n  return (coeff_ei * ne * ctx.n_0 * std::pow(std::abs(T*ctx.T_0),-1.5) * ctx.t_0); // electron-ion collision rate\n}\n\ninline vcl_vec nu_ei(const vcl_vec &ne, const vcl_vec &Te, const comfi::types::Context &ctx)\n{\n  const double coloumb_logarithm = 10.0;\n  const double r = arma::datum::ec*arma::datum::ec/(4.0*arma::datum::pi*arma::datum::eps_0*arma::datum::k);\n  const double sigma_ei = coloumb_logarithm*arma::datum::pi*r*r;\n  const double coeff_ei = (4.0/3.0) * sigma_ei * std::sqrt(2.0*arma::datum::k/(arma::datum::pi*arma::datum::m_e));\n  return coeff_ei * ctx.n_0 * ctx.t_0* viennacl::linalg::element_prod(ne,viennacl::linalg::element_exp(-1.5*viennacl::linalg::element_log(ctx.T_0*Te))); // electron-ion collision rate\n}\n\ninline vcl_vec nu_ii(const vcl_vec &Np, const vcl_vec &Tp, const comfi::types::Context &ctx)\n{\n  const double coloumb_logarithm = 10.0;\n  const double r = arma::datum::ec*arma::datum::ec/(4.0*arma::datum::pi*arma::datum::eps_0*arma::datum::k); //without T\n  const double sigma_ii = coloumb_logarithm*arma::datum::pi*r*r;\n  const double coeff_ii = (4.0/3.0) * sigma_ii * std::sqrt(2.0*arma::datum::k/(arma::datum::pi*arma::datum::m_p));\n  return ctx.t_0 * ctx.n_0 * coeff_ii * viennacl::linalg::element_prod(Np, viennacl::linalg::element_exp(-1.5*viennacl::linalg::element_log(ctx.T_0*Tp))); // electron-ion collision rate\n}\n\ninline double nu_ii(const double &Np, const double &Tp, const comfi::types::Context &ctx)\n{\n  const double coloumb_logarithm = 10.0;\n  const double r = arma::datum::ec*arma::datum::ec/(4.0*arma::datum::pi*arma::datum::eps_0*arma::datum::k); //without T\n  const double sigma_ii = coloumb_logarithm*arma::datum::pi*r*r;\n  const double coeff_ii = (4.0/3.0) * sigma_ii * std::sqrt(2.0*arma::datum::k/(arma::datum::pi*arma::datum::m_p));\n  return coeff_ii * ctx.t_0 * Np * ctx.n_0 * std::exp(-1.5*std::log(ctx.T_0*Tp)); // electron-ion collision rate\n}\n\ninline vcl_vec resistivity(const vcl_vec &Np, const vcl_vec &Nn, const vcl_vec &Tp, const vcl_vec &Tn, const comfi::types::Context &ctx)\n{\n  return (ctx.m_e/(ctx.q*ctx.q))*viennacl::linalg::element_div((nu_ei(Np, Tp, ctx)+nu_en(Nn, 0.5*(Tp+Tn), ctx)),Np);\n}\ninline double resistivity(const double &Np, const double &Nn, const double &Tp, const double &Tn, const comfi::types::Context &ctx)\n{\n  return (ctx.m_e/(ctx.q*ctx.q)) * (nu_ei(Np, Tp, ctx)+nu_en(Nn, 0.5*(Tp+Tn), ctx))/Np;\n}\n\ninline double thermalvel(const double &T, const comfi::types::Context &ctx)\n{\n  return std::sqrt(2.0*arma::datum::k/arma::datum::m_p) * std::sqrt(T*ctx.T_0) / ctx.V_0;\n}\n\ninline vcl_vec thermalvel(const vcl_vec &T, const comfi::types::Context &ctx)\n{\n  using namespace viennacl::linalg;\n  return std::sqrt(2.0*arma::datum::k/arma::datum::m_p) * element_sqrt(T*ctx.T_0) / ctx.V_0;\n}\n\ninline double kappa_n(const double &Tp, const double &Tn, const double &Np, const double &Nn, const comfi::types::Context &ctx)\n{\n  return Nn * thermalvel(Tn, ctx) * thermalvel(Tn, ctx) / nu_nn(Nn, Tn, ctx);\n}\n\ninline vcl_vec kappa_n(const vcl_vec &Tp, const vcl_vec &Tn, const vcl_vec &Np, const vcl_vec &Nn, const comfi::types::Context &ctx)\n{\n  using namespace viennacl::linalg;\n  const vcl_vec v2 = element_prod(thermalvel(Tn, ctx), thermalvel(Tn, ctx));\n  const vcl_vec nv2 = element_prod(Nn, v2);\n  const vcl_vec nunn = nu_nn(Nn, Tn, ctx);\n  return element_div(nv2, nunn);\n}\n\ninline double kappa_p(const double &Tp, const double &Tn, const double &Np, const double &Nn, const comfi::types::Context &ctx)\n{\n  return Np * thermalvel(Tp, ctx) * thermalvel(Tp, ctx) / (nu_in(Nn, 0.5*(Tp+Tn), ctx) + nu_ii(Np, Tp, ctx));\n}\n\ninline vcl_vec kappa_p(const vcl_vec &Tp, const vcl_vec &Tn, const vcl_vec &Np, const vcl_vec &Nn, const comfi::types::Context &ctx)\n{\n  using namespace viennacl::linalg;\n  const vcl_vec v2 = element_prod(thermalvel(Tp, ctx), thermalvel(Tp, ctx));\n  const vcl_vec nv2 = element_prod(Np, v2);\n  const vcl_vec nuin = nu_in(Nn, 0.5*(Tp+Tn), ctx);\n  const vcl_vec nuii = nu_ii(Np, Tp, ctx);\n  return element_div(nv2, nuin+nuii);\n}\n\n/*!\n * \\brief Calculate recombination coefficient for ions to recombine to neutrals.\n * \\param Tp Ion temperature\n * \\return Vector of normalized volumetric recombination rate.\n */\ninline vcl_vec recomb_coeff(const vcl_vec &T, const comfi::types::Context &ctx)\n{\n  using namespace viennacl::linalg;\n  static const vcl_vec one = viennacl::scalar_vector<double>(T.size(), 1.0);\n  const vcl_vec beta = 0.6 * 13.6 * 1.6021766208e-19 * element_div(one, arma::datum::k*ctx.T_0*T);\n  vcl_vec coeff = 0.4288*one + 0.5*element_log(beta) + 0.4698*element_pow(beta, -(1.0/3.0)*one);\n  coeff = element_prod(5.20e-20*element_sqrt(beta), coeff);\n  return ctx.t_0 * ctx.n_0 * coeff;\n}\n\ninline double recomb_coeff(const double &T, const comfi::types::Context &ctx)\n{\n  const double beta = 0.6 * 13.6 * 1.6021766208e-19 / (arma::datum::k*ctx.T_0*T);\n  return ctx.t_0 * ctx.n_0 * 5.20e-20 * std::sqrt(beta) * (0.4288+std::log(beta)+0.4698*std::pow(beta, -(1.0/3.0)));\n}\n\n/*!\n * \\brief Calculate normalized ionization coefficient for neutrals to ionize due to collisions (Draine p 134)\n * \\param Tn Neutral temperature\n * \\return Vector of normalized volumetric ionization rate\n */\ninline vcl_vec ionization_coeff(const vcl_vec &T, const comfi::types::Context &ctx)\n{\n  using namespace viennacl::linalg;\n  static const vcl_vec one = viennacl::scalar_vector<double>(T.size(), 1.0);\n  const vcl_vec beta = 0.6 * 13.6 * 1.6021766208e-19 * element_div(one, arma::datum::k*ctx.T_0*T);\n  const vcl_vec coeff = element_div(2.34e-14*element_exp(-beta), element_sqrt(beta));\n  return ctx.t_0 * ctx.n_0 * coeff;\n\n}\n\ninline double ionization_coeff(const double &T, const comfi::types::Context &ctx)\n{\n  const double beta = 0.6 * 13.6 * 1.6021766208e-19 / (arma::datum::k*ctx.T_0*T);\n  return ctx.t_0 * ctx.n_0 * 2.34e-14 * std::exp(-beta) / std::sqrt(beta);\n}\n} // namespace sol\n\n} // namespace mhdsim\n\n/*!\n * \\brief Find scalar vector index.\n * \\param i Horizontal index.\n * \\param j Vertical index\n * \\return Scalar vector index.\n */\ninline arma::uword inds(const arma::uword &i, const arma::uword &j, comfi::types::Context &ctx)\n{\n  return i+j*ctx.nx;\n}\n\n/*\nvim: tabstop=2\nvim: shiftwidth=2\nvim: smarttab\nvim: expandtab\n*/\n", "meta": {"hexsha": "fd00e6b7c3575a0fdbd844a76be62020da4b3b20", "size": 31377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "comfi.hpp", "max_stars_repo_name": "qalshidi/comfi", "max_stars_repo_head_hexsha": "59835f0ab4f54dea0ecb44405f583c9c06ad21bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-17T22:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T22:10:35.000Z", "max_issues_repo_path": "comfi.hpp", "max_issues_repo_name": "qalshidi/comfi", "max_issues_repo_head_hexsha": "59835f0ab4f54dea0ecb44405f583c9c06ad21bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "comfi.hpp", "max_forks_repo_name": "qalshidi/comfi", "max_forks_repo_head_hexsha": "59835f0ab4f54dea0ecb44405f583c9c06ad21bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2206405694, "max_line_length": 185, "alphanum_fraction": 0.6946808172, "num_tokens": 9511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.6370307875894138, "lm_q1q2_score": 0.4412342680338145}}
{"text": "// -----------------------------------------------------------------------------\n/**\n *  @brief 2D homography motion model (function) in direct methods tracking.\n *  @author Jose M. Buenaposada\n *  @date 2012/10/14\n *  @version $revision$\n *\n *  $id$\n *\n *  Grupo de investigación en Percepción Computacional y Robótica)\n *  (Perception for Computers & Robots research Group)\n *  Facultad de Informática (Computer Science School)\n *  Universidad Politécnica de Madrid (UPM) (Madrid Technical University)\n *  http://www.dia.fi.upm.es/~pcr\n *\n */\n// -----------------------------------------------------------------------------\n\n#include \"homography_2d.hpp\"\n#include \"trace.hpp\"\n#include <limits>\n#include <boost/concept_check.hpp>\n\nnamespace upm { namespace pcr\n{\n  \n// -----------------------------------------------------------------------------\n//\n// Purpose and Method: \n// Inputs: \n// Outputs: \n// Dependencies:\n// Restrictions and Caveats:\n//\n// -----------------------------------------------------------------------------  \nHomography2D::Homography2D\n  () \n{ \n};\n  \n// -----------------------------------------------------------------------------\n//\n// Purpose and Method: \n// Inputs: \n// Outputs: \n// Dependencies:\n// Restrictions and Caveats:\n//\n// -----------------------------------------------------------------------------  \nHomography2D::~Homography2D\n  () \n{\n};\n\n// -----------------------------------------------------------------------------\n//\n// Purpose and Method: \n// Inputs: \n// Outputs: \n// Dependencies:\n// Restrictions and Caveats:\n//\n// -------------------------------------------------------------------------  \n// cv::Mat\n// Homography2D::computeMotionJacobian\n//   (\n//   cv::Mat params  \n//   )\n// {\n// };\n  \n// -----------------------------------------------------------------------------\n//\n// Purpose and Method: \n// Inputs: \n// Outputs: \n// Dependencies:\n// Restrictions and Caveats:\n//\n// -----------------------------------------------------------------------------  \ncv::Mat\nHomography2D::scaleInputImageResolution\n  (\n  cv::Mat params,\n  double scale\n  )\n{\n  cv::Mat newH;\n  cv::Mat new_params = cv::Mat::eye(params.rows, 1, cv::DataType<MAT_TYPE>::type);\n  cv::Mat H          = params.reshape(1,3).t();\n  \n  cv::Mat S    = cv::Mat::eye(3,3,cv::DataType<MAT_TYPE>::type);\n  S.at<MAT_TYPE>(0,0) = scale;\n  S.at<MAT_TYPE>(1,1) = scale;\n\n  newH = S*H;\n  newH = newH.t();\n  newH.reshape(1,9).copyTo(new_params);\n  \n  return new_params;\n}\n\n// -----------------------------------------------------------------------------\n//\n// Purpose and Method: \n// Inputs: \n// Outputs: \n// Dependencies:\n// Restrictions and Caveats:\n//\n//    The motion params are always from template to current image and with this\n//    method we have to use the inverse motion model.\n// -----------------------------------------------------------------------------  \ncv::Mat\nHomography2D::transformCoordsToTemplate\n  (\n  cv::Mat coords,\n  cv::Mat params   \n  )\n{\n  cv::Mat H = params.reshape(1,3).t();\n  cv::Mat invH      = H.inv().t();                                        \n\n  cv::Mat inv_params = invH.reshape(1,9);\n  \n  return transformCoordsToImage(coords, inv_params);  \n};\n\n// -----------------------------------------------------------------------------\n//\n// Purpose and Method: \n// Inputs: \n// Outputs: \n// Dependencies:\n// Restrictions and Caveats:\n//\n// -----------------------------------------------------------------------------  \ncv::Mat\nHomography2D::transformCoordsToImage\n  (\n  cv::Mat coords,\n  cv::Mat params   \n  )\n{\n  assert(coords.cols == 2); // We need two dimensional coordinates\n  \n  cv::Mat H                      = params.reshape(1, 3).t();\n  cv::Mat homogeneous_coords     = cv::Mat::ones(coords.rows, 3, cv::DataType<MAT_TYPE>::type);\n  cv::Mat homogeneous_coords_ref = homogeneous_coords(cv::Range::all(), cv::Range(0, 2));\n  coords.copyTo(homogeneous_coords_ref);\n  \n  cv::Mat homogeneous_new_coords = (homogeneous_coords * H.t());\n  \n  // Divide by the third homogeneous coordinates to get the cartersian coordinates.\n  for (int j=0; j<3; j++)\n  {\n    cv::Mat col     = homogeneous_new_coords.col(j).mul(1.0 / homogeneous_new_coords.col(2));\n    cv::Mat col_new = homogeneous_new_coords.col(j);\n    col.copyTo(col_new);\n  }\n    \n  cv::Mat homogeneous_new_coords_ref = homogeneous_new_coords(cv::Range::all(), cv::Range(0, 2)); \n  cv::Mat new_coords;\n  homogeneous_new_coords_ref.copyTo(new_coords);\n  \n#ifdef DEBUG\n  // write Mat objects to the file\n  cv::FileStorage fs(\"transformCoordsToImage.xml\", cv::FileStorage::WRITE);\n  fs << \"H\" << H;\n  fs << \"coords\" << coords;\n  fs << \"new_coords\" << new_coords;\n  fs.release();\n#endif\n  \n  return new_coords;  \n};\n\n// -----------------------------------------------------------------------------\n//\n// Purpose and Method: \n// Inputs: \n// Outputs: \n// Dependencies:\n// Restrictions and Caveats:\n//\n// -----------------------------------------------------------------------------  \ncv::Mat\nHomography2D::warpImage\n  (\n  cv::Mat image,\n  cv::Mat params,\n  cv::Mat template_coords,\n  std::vector<int>& template_ctrl_points_indices\n  )\n{\n  MAT_TYPE min_x, max_x, min_y, max_y;\n  cv::Mat warped_image;\n\n  cv::Mat M;\n  cv::Mat H = params.reshape(1,3).t();\n  \n  // Find minimum x and minimum y in template coords\n  cv::MatConstIterator_<MAT_TYPE> it;\n  max_x = std::numeric_limits<MAT_TYPE>::min();\n  max_y = std::numeric_limits<MAT_TYPE>::min();\n  min_x = std::numeric_limits<MAT_TYPE>::max();\n  min_y = std::numeric_limits<MAT_TYPE>::max();\n\n  for (int i = 0; i < template_coords.rows; i++)\n  {  \n    MAT_TYPE x = template_coords.at<MAT_TYPE>(i,0);\n    MAT_TYPE y = template_coords.at<MAT_TYPE>(i,1);\n    \n    if (x > max_x) max_x = x;\n    if (x < min_x) min_x = x;\n    if (y > max_y) max_y = y;\n    if (y < min_y) min_y = y;\n  }\n\n  cv::Mat TR  = (cv::Mat_<MAT_TYPE>(3,3) << 1.,    0,    min_x, \n\t\t                            0,    1.,    min_y, \n\t\t                            0,     0,    1.);\n  warped_image = cv::Mat::zeros(max_y-min_y+1, max_x-min_x+1, cv::DataType<uint8_t>::type);\n  \n//   if (scale < 0.000000001)\n//   {\n//     return warped_image;\n//   }\n  \n  // TR is necessary because the Warpers do warping taking\n  // the pixel (0,0) as the left and top most pixel of the template.\n  // So, we have move the (0,0) to the center of the Template.\n  M = H*TR;\n\n#ifdef DEBUG\n  // write Mat objects to the file\n  cv::FileStorage fs(\"template_coords_warpImage.xml\", cv::FileStorage::WRITE);\n  fs << \"template_coords\" << template_coords;\n  fs << \"M\" << M;\n  fs.release();\n#endif  \n\n  cv::warpPerspective(image, warped_image, M, \n\t\t      cv::Size(warped_image.cols,  warped_image.rows), \n\t\t      cv::INTER_AREA | cv::WARP_INVERSE_MAP);\n  return warped_image;\n};\n\n\n// -----------------------------------------------------------------------------\n//\n// Purpose and Method: \n// Inputs: \n// Outputs: \n// Dependencies:\n// Restrictions and Caveats:\n//\n// -----------------------------------------------------------------------------  \nbool\nHomography2D::consistentPoints\n  (\n  cv::Mat points, \n  cv::Mat transformed_points,\n  int t1,\n  int t2,\n  int t3\n  )\n{\n  cv::Mat A = (cv::Mat_<MAT_TYPE>(3, 3) << points.at<MAT_TYPE>(t1, 0), points.at<MAT_TYPE>(t1, 1), 1,\n                                           points.at<MAT_TYPE>(t2, 0), points.at<MAT_TYPE>(t2, 1), 1,\n                                           points.at<MAT_TYPE>(t3, 0), points.at<MAT_TYPE>(t3, 1), 1);\n  cv::Mat B = (cv::Mat_<MAT_TYPE>(3, 3) << transformed_points.at<MAT_TYPE>(t1, 0), transformed_points.at<MAT_TYPE>(t1, 1), 1,\n                                           transformed_points.at<MAT_TYPE>(t2, 0), transformed_points.at<MAT_TYPE>(t2, 1), 1,\n                                           transformed_points.at<MAT_TYPE>(t3, 0), transformed_points.at<MAT_TYPE>(t3, 1), 1);\n\n  double detA = cv::determinant(A);\n  double detB = cv::determinant(B);\n\n  return ((detA*detB) >= 0.0);\n}\n\n// -----------------------------------------------------------------------------\n//\n// Purpose and Method: \n// Inputs: \n// Outputs: \n// Dependencies:\n// Restrictions and Caveats:\n//\n// -----------------------------------------------------------------------------  \nbool\nHomography2D::invalidParams\n  (\n  cv::Mat params\n  )\n{\n  cv::Mat M;\n  cv::Mat H = params.reshape(1,3).t();\n\n  cv::SVD svd(H, cv::SVD::NO_UV);\n  \n  int rank = 0;\n  for (int i=0; i<H.rows; i++)\n  {\n    if (svd.w.at<MAT_TYPE>(i,0)>1.E-6)\n    {\n      rank++;\n    }\n  }\n  \n  SHOW_VALUE(H);\n  \n  // Stablish the \n  cv::Mat points = (cv::Mat_<MAT_TYPE>(4, 2) <<   0, 0,\n                                                100, 0,\n\t\t                                100, 100,\n\t\t                                  0, 100);\n  cv::Mat transformed_points;\n  points.copyTo(transformed_points);\n//   cv::perspectiveTransform(points, transformed_points, H);\n  transformed_points = transformCoordsToImage(points, params);\n\n  double detH = cv::determinant(H);\n  \n//   return (rank<3) || (!consistentPoints(points, transformed_points, 0, 1, 2)) \n//                   || (!consistentPoints(points, transformed_points, 1, 2, 3)) \n//                   || (!consistentPoints(points, transformed_points, 0, 2, 3)) \n//                   || (!consistentPoints(points, transformed_points, 0, 1, 3)); \n  return (rank<3) ||(detH < (1./10.)) || (detH > 10.) \n                  || (!consistentPoints(points, transformed_points, 0, 1, 2)) \n                  || (!consistentPoints(points, transformed_points, 1, 2, 3)) \n                  || (!consistentPoints(points, transformed_points, 0, 2, 3)) \n                  || (!consistentPoints(points, transformed_points, 0, 1, 3)); \n};\n\n\n}; }; // namespace\n", "meta": {"hexsha": "c4858caa5679cd9ddad149862c3d5ebae28637a5", "size": 9665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/homography_2d.cpp", "max_stars_repo_name": "jmbuena/img_align_lib", "max_stars_repo_head_hexsha": "1c9a8f876c20e0b4226ac0ecfab4c76e11d4ec21", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-05-14T19:37:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-25T18:01:06.000Z", "max_issues_repo_path": "src/homography_2d.cpp", "max_issues_repo_name": "jmbuena/img_align_lib", "max_issues_repo_head_hexsha": "1c9a8f876c20e0b4226ac0ecfab4c76e11d4ec21", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-13T10:03:04.000Z", "max_issues_repo_issues_event_max_datetime": "2015-03-13T10:51:19.000Z", "max_forks_repo_path": "src/homography_2d.cpp", "max_forks_repo_name": "jmbuena/img_align_lib", "max_forks_repo_head_hexsha": "1c9a8f876c20e0b4226ac0ecfab4c76e11d4ec21", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-02-02T00:13:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-14T03:37:10.000Z", "avg_line_length": 28.5946745562, "max_line_length": 126, "alphanum_fraction": 0.4982928091, "num_tokens": 2449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.44120472560593393}}
{"text": "/* Copyright (c) 2017, Waterloo Autonomous Vehicles Laboratory (WAVELab),\n * Waterloo Intelligent Systems Engineering Lab (WISELab),\n * University of Waterloo.\n *\n * Refer to the accompanying LICENSE file for license information.\n *\n * ############################################################################\n ******************************************************************************\n |                                                                            |\n |                         /\\/\\__/\\_/\\      /\\_/\\__/\\/\\                       |\n |                         \\          \\____/          /                       |\n |                          '----________________----'                        |\n |                              /                \\                            |\n |                            O/_____/_______/____\\O                          |\n |                            /____________________\\                          |\n |                           /    (#UNIVERSITY#)    \\                         |\n |                           |[**](#OFWATERLOO#)[**]|                         |\n |                           \\______________________/                         |\n |                            |_\"\"__|_,----,_|__\"\"_|                          |\n |                            ! !                ! !                          |\n |                            '-'                '-'                          |\n |       __    _   _  _____  ___  __  _  ___  _    _  ___  ___   ____  ____   |\n |      /  \\  | | | ||_   _|/ _ \\|  \\| |/ _ \\| \\  / |/ _ \\/ _ \\ /     |       |\n |     / /\\ \\ | |_| |  | |  ||_||| |\\  |||_|||  \\/  |||_||||_|| \\===\\ |====   |\n |    /_/  \\_\\|_____|  |_|  \\___/|_| \\_|\\___/|_|\\/|_|\\___/\\___/ ____/ |____   |\n |                                                                            |\n ******************************************************************************\n * ############################################################################\n *\n * File: world_frame_conversions.cpp\n * Desc: Implementation file for world frame conversion functions\n * Auth: Michael Smart <michael.smart@uwaterloo.ca>\n *\n * ############################################################################\n*/\n\n#include <Eigen/Core>\n#include \"wave/geography/world_frame_conversions.hpp\"\n\nnamespace wave {\n\nvoid ecefPointFromLLH(const double llh[3], double ecef[3]) {\n    double latitude = llh[0], longitude = llh[1], height = llh[2];\n\n    GeographicLib::Geocentric earth = GeographicLib::Geocentric::WGS84();\n\n    double X, Y, Z;\n    earth.Forward(latitude, longitude, height, X, Y, Z);\n\n    ecef[0] = X;\n    ecef[1] = Y;\n    ecef[2] = Z;\n}\n\nvoid llhPointFromECEF(const double ecef[3], double llh[3]) {\n    double X = ecef[0], Y = ecef[1], Z = ecef[2];\n\n    GeographicLib::Geocentric earth = GeographicLib::Geocentric::WGS84();\n\n    double latitude, longitude, height;\n    earth.Reverse(X, Y, Z, latitude, longitude, height);\n\n    llh[0] = latitude;\n    llh[1] = longitude;\n    llh[2] = height;\n}\n\nvoid ecefFromENUTransformMatrix(const double datum[3],\n                                double T_ecef_enu[4][4],\n                                bool datum_is_llh) {\n    // Both Forward() and Reverse() return the same rotation matrix from ENU\n    // to ECEF\n    std::vector<double> R_ecef_enu(9, 0.0);\n    GeographicLib::Geocentric earth = GeographicLib::Geocentric::WGS84();\n    double datum_X, datum_Y, datum_Z;\n\n    if (datum_is_llh) {\n        double latitude = datum[0], longitude = datum[1], height = datum[2];\n\n        earth.Forward(\n          latitude, longitude, height, datum_X, datum_Y, datum_Z, R_ecef_enu);\n    } else {\n        // Datum is already given in ECEF\n        datum_X = datum[0];\n        datum_Y = datum[1];\n        datum_Z = datum[2];\n\n        double latitude, longitude, height;\n        earth.Reverse(\n          datum_X, datum_Y, datum_Z, latitude, longitude, height, R_ecef_enu);\n    }\n\n    T_ecef_enu[0][0] = R_ecef_enu[0];\n    T_ecef_enu[0][1] = R_ecef_enu[1];\n    T_ecef_enu[0][2] = R_ecef_enu[2];\n    T_ecef_enu[0][3] = datum_X;\n    T_ecef_enu[1][0] = R_ecef_enu[3];\n    T_ecef_enu[1][1] = R_ecef_enu[4];\n    T_ecef_enu[1][2] = R_ecef_enu[5];\n    T_ecef_enu[1][3] = datum_Y;\n    T_ecef_enu[2][0] = R_ecef_enu[6];\n    T_ecef_enu[2][1] = R_ecef_enu[7];\n    T_ecef_enu[2][2] = R_ecef_enu[8];\n    T_ecef_enu[2][3] = datum_Z;\n    T_ecef_enu[3][0] = 0.0;\n    T_ecef_enu[3][1] = 0.0;\n    T_ecef_enu[3][2] = 0.0;\n    T_ecef_enu[3][3] = 1.0;\n}\n\nvoid enuFromECEFTransformMatrix(const double datum[3],\n                                double T_enu_ecef[4][4],\n                                bool datum_is_llh) {\n    // Get T_ecef_enu and then invert it\n    double T_ecef_enu[4][4];\n    ecefFromENUTransformMatrix(datum, T_ecef_enu, datum_is_llh);\n\n    // Affine inverse: [R | t]^(-1) = [ R^T | - R^T * t]\n    // TODO(msmart/benskikos) - Move these functions to somewhere where we have\n    // matrix classes and ownership since it is ours. Manual transposition is\n    // undesirable. The below should be 2 lines:\n    // R_new = R.transpose(); t_new = - R.transpose()*t;\n    T_enu_ecef[0][0] = T_ecef_enu[0][0];\n    T_enu_ecef[0][1] = T_ecef_enu[1][0];\n    T_enu_ecef[0][2] = T_ecef_enu[2][0];\n    T_enu_ecef[1][0] = T_ecef_enu[0][1];\n    T_enu_ecef[1][1] = T_ecef_enu[1][1];\n    T_enu_ecef[1][2] = T_ecef_enu[2][1];\n    T_enu_ecef[2][0] = T_ecef_enu[0][2];\n    T_enu_ecef[2][1] = T_ecef_enu[1][2];\n    T_enu_ecef[2][2] = T_ecef_enu[2][2];\n\n    // Affine inverse translation component: -R_inverse * b\n    //    with b as the 4th column of T_ecef_enu\n    T_enu_ecef[0][3] = -T_enu_ecef[0][0] * T_ecef_enu[0][3]    //\n                       - T_enu_ecef[0][1] * T_ecef_enu[1][3]   //\n                       - T_enu_ecef[0][2] * T_ecef_enu[2][3];  //\n\n    T_enu_ecef[1][3] = -T_enu_ecef[1][0] * T_ecef_enu[0][3]    //\n                       - T_enu_ecef[1][1] * T_ecef_enu[1][3]   //\n                       - T_enu_ecef[1][2] * T_ecef_enu[2][3];  //\n\n    T_enu_ecef[2][3] = -T_enu_ecef[2][0] * T_ecef_enu[0][3]    //\n                       - T_enu_ecef[2][1] * T_ecef_enu[1][3]   //\n                       - T_enu_ecef[2][2] * T_ecef_enu[2][3];  //\n\n    // Last row is the same\n    T_enu_ecef[3][0] = 0.0;\n    T_enu_ecef[3][1] = 0.0;\n    T_enu_ecef[3][2] = 0.0;\n    T_enu_ecef[3][3] = 1.0;\n}\n\nvoid enuPointFromLLH(const double point_llh[3],\n                     const double enu_datum[3],\n                     double point_enu[3],\n                     bool datum_is_llh) {\n    double enu_datum_llh[3];\n    if (datum_is_llh) {\n        enu_datum_llh[0] = enu_datum[0];\n        enu_datum_llh[1] = enu_datum[1];\n        enu_datum_llh[2] = enu_datum[2];\n    } else {\n        // Datum is ECEF\n        llhPointFromECEF(enu_datum, enu_datum_llh);\n    }\n\n    GeographicLib::Geocentric earth = GeographicLib::Geocentric::WGS84();\n    GeographicLib::LocalCartesian localENU(\n      enu_datum_llh[0], enu_datum_llh[1], enu_datum_llh[2], earth);\n\n    localENU.Forward(point_llh[0],\n                     point_llh[1],\n                     point_llh[2],\n                     point_enu[0],\n                     point_enu[1],\n                     point_enu[2]);\n}\n\nvoid llhPointFromENU(const double point_enu[3],\n                     const double enu_datum[3],\n                     double point_llh[3],\n                     bool datum_is_llh) {\n    double enu_datum_llh[3];\n    if (datum_is_llh) {\n        enu_datum_llh[0] = enu_datum[0];\n        enu_datum_llh[1] = enu_datum[1];\n        enu_datum_llh[2] = enu_datum[2];\n    } else {\n        // Datum is ECEF\n        llhPointFromECEF(enu_datum, enu_datum_llh);\n    }\n\n    GeographicLib::Geocentric earth = GeographicLib::Geocentric::WGS84();\n    GeographicLib::LocalCartesian localENU(\n      enu_datum_llh[0], enu_datum_llh[1], enu_datum_llh[2], earth);\n\n    localENU.Reverse(point_enu[0],\n                     point_enu[1],\n                     point_enu[2],\n                     point_llh[0],\n                     point_llh[1],\n                     point_llh[2]);\n}\n\n}  // namespace wave\n", "meta": {"hexsha": "7bcb463dad45999428763fa88157f7afb465c3ca", "size": 8059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wave_geography/src/world_frame_conversions.cpp", "max_stars_repo_name": "wavelab/wavelib", "max_stars_repo_head_hexsha": "7bebff52859c8b77f088e39913223904988c141e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2017-03-12T18:57:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:44:33.000Z", "max_issues_repo_path": "wave_geography/src/world_frame_conversions.cpp", "max_issues_repo_name": "wavelab/wavelib", "max_issues_repo_head_hexsha": "7bebff52859c8b77f088e39913223904988c141e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 210.0, "max_issues_repo_issues_event_min_datetime": "2017-03-13T15:01:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T03:19:44.000Z", "max_forks_repo_path": "wave_geography/src/world_frame_conversions.cpp", "max_forks_repo_name": "wavelab/wavelib", "max_forks_repo_head_hexsha": "7bebff52859c8b77f088e39913223904988c141e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2017-08-14T16:54:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T06:44:16.000Z", "avg_line_length": 38.9323671498, "max_line_length": 79, "alphanum_fraction": 0.4722670306, "num_tokens": 2413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4412047256059339}}
{"text": "#include \"TensorTopologyEvaluator.hh\"\n\n#include <Eigen/Geometry>\n\n#include <boost/algorithm/cxx11/any_of.hpp>\n#include <boost/range/algorithm/max_element.hpp>\n#include <boost/range/algorithm/min_element.hpp>\n\n#include <tuple>\n#include <utility>\n#include <vector>\n\nusing namespace cpp_utils;\n\nnamespace tl\n{\ntemplate <typename T, std::size_t... Degrees>\nusing TPBT = TensorProductBezierTriangle<T, double, Degrees...>;\n\nstd::array<TPBT<double, 3, 0>, 7> tensorTopologyCoeffs(const TensorInterp& t)\n{\n    using Coords = TPBT<double, 3, 0>::Coords;\n    // Constraint functions according to Zheng et al. 2004\n\n    auto fx = [&](const Coords& coords) -> double {\n        auto tv = t(coords.head<3>());\n        return tv(0, 0) * ((tv(1, 1) * tv(1, 1) - tv(2, 2) * tv(2, 2))\n                           + (tv(0, 1) * tv(0, 1) - tv(0, 2) * tv(0, 2)))\n               + tv(1, 1) * ((tv(2, 2) * tv(2, 2) - tv(0, 0) * tv(0, 0))\n                             + (tv(1, 2) * tv(1, 2) - tv(0, 1) * tv(0, 1)))\n               + tv(2, 2) * ((tv(0, 0) * tv(0, 0) - tv(1, 1) * tv(1, 1))\n                             + (tv(0, 2) * tv(0, 2) - tv(1, 2) * tv(1, 2)));\n    };\n\n    auto fy1 = [&](const Coords& coords) -> double {\n        auto tv = t(coords.head<3>());\n        return tv(1, 2) * (2 * (tv(1, 2) * tv(1, 2) - tv(0, 0) * tv(0, 0))\n                           - (tv(0, 2) * tv(0, 2) + tv(0, 1) * tv(0, 1))\n                           + 2 * (tv(1, 1) * tv(0, 0) + tv(2, 2) * tv(0, 0)\n                                  - tv(1, 1) * tv(2, 2)))\n               + tv(0, 1) * tv(0, 2) * (2 * tv(0, 0) - tv(2, 2) - tv(1, 1));\n    };\n\n    auto fy2 = [&](const Coords& coords) -> double {\n        auto tv = t(coords.head<3>());\n        return tv(0, 2) * (2 * (tv(0, 2) * tv(0, 2) - tv(1, 1) * tv(1, 1))\n                           - (tv(0, 1) * tv(0, 1) + tv(1, 2) * tv(1, 2))\n                           + 2 * (tv(2, 2) * tv(1, 1) + tv(0, 0) * tv(1, 1)\n                                  - tv(2, 2) * tv(0, 0)))\n               + tv(1, 2) * tv(0, 1) * (2 * tv(1, 1) - tv(0, 0) - tv(2, 2));\n    };\n\n    auto fy3 = [&](const Coords& coords) -> double {\n        auto tv = t(coords.head<3>());\n        return tv(0, 1) * (2 * (tv(0, 1) * tv(0, 1) - tv(2, 2) * tv(2, 2))\n                           - (tv(1, 2) * tv(1, 2) + tv(0, 2) * tv(0, 2))\n                           + 2 * (tv(0, 0) * tv(2, 2) + tv(1, 1) * tv(2, 2)\n                                  - tv(0, 0) * tv(1, 1)))\n               + tv(0, 2) * tv(1, 2) * (2 * tv(2, 2) - tv(1, 1) - tv(0, 0));\n    };\n\n    auto fz1 = [&](const Coords& coords) -> double {\n        auto tv = t(coords.head<3>());\n        return tv(1, 2) * (tv(0, 2) * tv(0, 2) - tv(0, 1) * tv(0, 1))\n               + tv(0, 1) * tv(0, 2) * (tv(1, 1) - tv(2, 2));\n    };\n\n    auto fz2 = [&](const Coords& coords) -> double {\n        auto tv = t(coords.head<3>());\n        return tv(0, 2) * (tv(0, 1) * tv(0, 1) - tv(1, 2) * tv(1, 2))\n               + tv(1, 2) * tv(0, 1) * (tv(2, 2) - tv(0, 0));\n    };\n\n    auto fz3 = [&](const Coords& coords) -> double {\n        auto tv = t(coords.head<3>());\n        return tv(0, 1) * (tv(1, 2) * tv(1, 2) - tv(0, 2) * tv(0, 2))\n               + tv(0, 2) * tv(1, 2) * (tv(0, 0) - tv(1, 1));\n    };\n\n    return {TPBT<double, 3, 0>{fx},\n            TPBT<double, 3, 0>{fy1},\n            TPBT<double, 3, 0>{fy2},\n            TPBT<double, 3, 0>{fy3},\n            TPBT<double, 3, 0>{fz1},\n            TPBT<double, 3, 0>{fz2},\n            TPBT<double, 3, 0>{fz3}};\n}\n\n\nusing TSHE = TensorTopologyEvaluator;\n\nTSHE::TensorTopologyEvaluator(const DoubleTri& tri,\n                              const TensorInterp& t,\n                              const Options& opts)\n        : _tri(tri), _target_funcs(tensorTopologyCoeffs(t)), _opts(opts)\n{\n}\n\n\nstd::array<TSHE, 4> TSHE::split() const\n{\n    auto part = [&](std::size_t i) {\n        return TensorTopologyEvaluator(_tri.split<0>(i),\n                                       {_target_funcs[0].split<0>(i),\n                                        _target_funcs[1].split<0>(i),\n                                        _target_funcs[2].split<0>(i),\n                                        _target_funcs[3].split<0>(i),\n                                        _target_funcs[4].split<0>(i),\n                                        _target_funcs[5].split<0>(i),\n                                        _target_funcs[6].split<0>(i)},\n                                       _split_level + 1,\n                                       _opts);\n    };\n    return {part(0), part(1), part(2), part(3)};\n}\n\n\nResult TSHE::eval()\n{\n    // Check if any of the error components can not become zero in the\n    // current subdivision triangles\n    auto has_nonzero =\n            boost::algorithm::any_of(_target_funcs, [](const auto& c) {\n                return sameSign(c.coefficients()) != 0;\n            });\n\n    // Discard triangles if no roots can occur inside\n    if(has_nonzero)\n    {\n        return Result::Discard;\n    }\n\n    // Compute upper bound for target functions\n    auto max_error = abs_max_upper_bound(_target_funcs);\n\n    if(max_error < _opts.tolerance)\n    {\n        return Result::Accept;\n    }\n\n    return Result::Split;\n}\n\n\ndouble TSHE::error() const\n{\n    return upper_bound_norm(_target_funcs);\n}\n\n\ndouble distance(const TSHE& t1, const TSHE& t2)\n{\n    return distance(t1.tris(), t2.tris());\n}\n\n\nbool operator==(const TSHE& t1, const TSHE& t2)\n{\n    return t1._tri == t2._tri && t1._target_funcs == t2._target_funcs\n           && t1._split_level == t2._split_level && t1._opts == t2._opts;\n}\n\n\nbool operator!=(const TSHE& t1, const TSHE& t2)\n{\n    return !(t1 == t2);\n}\n}\n", "meta": {"hexsha": "3cbd9375aaace43c9c5ac4b3e59dacd8ebdfaa36", "size": 5633, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/src/TensorTopologyEvaluator.cc", "max_stars_repo_name": "timo-oster/tensor-lines", "max_stars_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/TensorTopologyEvaluator.cc", "max_issues_repo_name": "timo-oster/tensor-lines", "max_issues_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/TensorTopologyEvaluator.cc", "max_forks_repo_name": "timo-oster/tensor-lines", "max_forks_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-13T00:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T00:08:09.000Z", "avg_line_length": 33.3313609467, "max_line_length": 77, "alphanum_fraction": 0.4466536481, "num_tokens": 1949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4411689166915473}}
{"text": "/*\nCopyright 2013 Henrik Mühe and Florian Funke\n\nThis file is part of CampersCoreBurner.\n\nCampersCoreBurner is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nCampersCoreBurner is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with CampersCoreBurner.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n/*\nCOMMENT SUMMARY FOR THIS FILE:\n\nThis implements two histogram (character frequency) based filters. The histogram of a\nword is an array that gives the number of times each possible letter in the alphabet\noccurs inside a certain word. For the word \"food\", the array would be\n\na b c d e f g h ... o ... z\n0 0 0 1 0 1 0 0 ... 2 ... 0\n\nWe define the delta d between two such histogram arrays as the sum of all absolute\ndifferences of the counts of each pair of characters. Shortened example, see deltaSlow()\nfor the algorithm:\n\nvec a 0 0 1 3 2 1\nvec b 0 1 0 3 2 0\ndelta 0+1+1+0+0+1\n\nThe filter can be used for exact matches, hamming distance and edit distance although\nit is only beneficial for edit distnace as matching exact words and hamming distance if\ncomparatively cheap anyway. For two words to be within edit distance t, their frequency\ndelta must be <= 2*t. This can be improved by looking at the possible edit operations. If\nthe length of the two words differs, that can only be caused by insert or delete operations.\nThese operations change the delta by 1, not 2 like substitution. Therefore, the criterion can\nbe improved to <= 2*t-lengthdiff where lengthdiff is the absolute length difference\nbetween the two words.\n\nWhile not overly costly, the naive way of executing the filter does not yield a sufficient\nresult. We therefore use SSE instructions to impove the filter by about a factor of 3. Also,\nwe have a shortened version of the filter which combines some characters. Its pruning\ncapability is not as good as the full version of the filter but it can be executed on one\nsse register instead of two.\n*/\n\n#pragma once\n\n#include <boost/utility/string_ref.hpp>\n#include <cassert>\n#include <x86intrin.h>\n\n\nnamespace campers {\n\n/// The full 26 character frequency filter\nstruct Frequency {\n    /// Maps each letter in the alphabet to a slot inside two sse 16 byte registers. A good mapping for english words\n    /// was obtained by randomized search while monitoring the prune rate using a script such as:\n    /// #!/bin/bash\n    /// while true; do\n    ///     seq 0 31 | sort -R | head -n 26 | xargs | tr ' ' ',' > include/mapping.hpp\n    ///     make -j >/dev/null 2>&1 && ./driver test_data/inter* | grep prune | awk '{ print $2 }' | tr '\\n' ' ' | cat - include/mapping.hpp\n    /// done\n    ///\n    /// Alternatively, a good but not ideal mapping is simply mapping a-m to the first register and n-z to the second.\n    static constexpr unsigned char charMap[26]={ 24,26,22,2,13,20,14,1,30,27,23,16,5,6,8,4,3,9,25,7,29,28,31,17,21,15 };\n    /// Union trick. We use two sse 128 bit registers to represent 32 char values for 26 characters\n    union { uint64_t l[4]; unsigned char f[32]; __m128i p[2]; };\n\n    /// Comparison for adding Frequency to maps\n    bool operator<(const Frequency& other) const {\n        return std::lexicographical_compare(l,l+4,other.l,other.l+4);\n    }\n\n    /// Comparison for adding Frequency to hash maps\n    bool operator==(const Frequency& other) const {\n        return l[0]==other.l[0]&&l[1]==other.l[1]&&l[2]==other.l[2]&&l[3]==other.l[3];\n    }\n\n    /// Constructor\n    Frequency() {}\n\n    /// Constructor which builds the frequency vector for a given word\n    explicit Frequency(const boost::string_ref& word) {\n        for (unsigned index=0;index!=32;++index) f[index]=0;\n        for (unsigned index=0;index<word.length();++index)\n            ++f[charMap[word[index]-'a']];\n    }\n\n    /// Delta computation using the naive mechanism adding the absolute of each character count difference\n    unsigned deltaSlow(const Frequency& f2) const {\n        unsigned result=0; for (unsigned index=0;index!=26;++index)\n        if (f[index]<f2.f[index])\n            result+=f2.f[index]-f[index];\n        else\n            result+=f[index]-f2.f[index];\n        return result;\n    }\n\n    /// Get coefficient\n    unsigned getCoefficient() const {\n        auto sum1=_mm_sad_epu8(p[0],_mm_setzero_si128());\n        auto fsum1=_mm_extract_epi64(_mm_add_epi8(sum1,_mm_srli_si128(sum1,8)),0);\n        auto sum2=_mm_sad_epu8(p[1],_mm_setzero_si128());\n        auto fsum2=_mm_extract_epi64(_mm_add_epi8(sum2,_mm_srli_si128(sum2,8)),0);\n        return 32+fsum1-fsum2;\n    }\n\n    /// Delta computation using sse, the sse instruction compute the same result as the naive approach but\n    /// in less cycles.\n    unsigned delta(const Frequency& f2) const {\n        __m128i half=_mm_add_epi8(_mm_sad_epu8(p[0],f2.p[0]),_mm_sad_epu8(p[1],f2.p[1]));\n        return _mm_extract_epi64(_mm_add_epi8(half,_mm_srli_si128(half,8)),0);\n    }\n};\n\n/// The frequency filter which maps 26 characters on 16 slots so that it can be evaluated on one sse\n/// register instead of two. The mapping is constructed from a dictionary such that letters which do\n/// not occur together frequently are mapped to the same slot.\nstruct FrequencyFast {\n    /// A mapping compacting the 26 characters of the alphabet into 16 slots of one sse register. The mapping\n    /// was extracted similarly to that of the regular Frequency filter.\n    static constexpr unsigned char charMap[26]={13,0,1,14,9,2,3,4,5,5,6,0,7,15,2,8,9,12,11,6,10,11,12,13,14,15};\n    /// Union trick. We use two sse 128 bit registers to represent 32 char values for 26 characters\n    union { uint64_t l[2]; unsigned char f[16]; __m128i p; };\n\n    /// Comparison for adding Frequency to maps\n    bool operator<(const FrequencyFast& other) const {\n        return _mm_extract_epi64(p,1) < _mm_extract_epi64(other.p,1) ||\n        (_mm_extract_epi64(p,1) == _mm_extract_epi64(other.p,1) && _mm_extract_epi64(p,0) < _mm_extract_epi64(other.p,0));\n    }\n\n    /// Comparison for adding Frequency to hash maps\n    bool operator==(const FrequencyFast& other) const {\n        return l[0]==other.l[0]&&l[1]==other.l[1];\n    }\n\n    /// Constructor\n    FrequencyFast() {}\n\n    /// Constructor which builds the frequency vector for a given word\n    explicit FrequencyFast(const boost::string_ref& word) {\n        for (unsigned index=0;index!=16.;++index) f[index]=0;\n        for (unsigned index=0;index<word.length();++index)\n            ++f[charMap[word[index]-'a']];\n    }\n\n    /// Delta computation using the naive mechanism adding the absolute of each character count difference\n    unsigned deltaSlow(const FrequencyFast& f2) const {\n        unsigned result=0; for (unsigned index=0;index!=16;++index)\n        if (f[index]<f2.f[index])\n            result+=f2.f[index]-f[index];\n        else\n            result+=f[index]-f2.f[index];\n        return result;\n    }\n\n    /// Delta computation using sse, the sse instruction compute the same result as the naive approach but\n    /// in less cycles.\n    unsigned delta(const FrequencyFast& f2) const {\n        __m128i half=_mm_sad_epu8(p,f2.p);\n        return _mm_extract_epi64(_mm_add_epi8(half,_mm_srli_si128(half,8)),0);\n    }\n};\n\n}\n\nnamespace std {\n\n/// Hash for FrequencyFast crc\ntemplate<>\nstruct hash<campers::FrequencyFast> {\n    size_t operator()(const campers::FrequencyFast& f) const {\n        return _mm_crc32_u64(_mm_crc32_u64(0,reinterpret_cast<const uint64_t*>(&f)[0]),reinterpret_cast<const uint64_t*>(&f)[1]);\n    }\n};\n\n/// Hash for Frequency using crc\ntemplate<>\nstruct hash<campers::Frequency> {\n    size_t operator()(const campers::Frequency& f) const {\n        return _mm_crc32_u64(_mm_crc32_u64(_mm_crc32_u64(_mm_crc32_u64(0,reinterpret_cast<const uint64_t*>(&f)[0]),\n            reinterpret_cast<const uint64_t*>(&f)[1]),reinterpret_cast<const uint64_t*>(&f)[2]),(reinterpret_cast<const uint64_t*>(&f)[3]));\n    }\n};\n}\n", "meta": {"hexsha": "c5fbc349619e29e66129f5a9c7a482a32a58305a", "size": 8278, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "admin/winning_teams/campers/Campers/impl/include/frequency.hpp", "max_stars_repo_name": "isj/sigmod", "max_stars_repo_head_hexsha": "8ffd3c50ac288aa12c05218d52b1f05eeb23a085", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-11-27T05:56:25.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-27T05:56:25.000Z", "max_issues_repo_path": "admin/winning_teams/campers/Campers/impl/include/frequency.hpp", "max_issues_repo_name": "isj/sigmod", "max_issues_repo_head_hexsha": "8ffd3c50ac288aa12c05218d52b1f05eeb23a085", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "admin/winning_teams/campers/Campers/impl/include/frequency.hpp", "max_forks_repo_name": "isj/sigmod", "max_forks_repo_head_hexsha": "8ffd3c50ac288aa12c05218d52b1f05eeb23a085", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4512820513, "max_line_length": 140, "alphanum_fraction": 0.6978738826, "num_tokens": 2201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.44112931780042963}}
{"text": "#include <Eigen/Dense>\n#include <aslam/Exceptions.hpp>\n#include <aslam/cameras/OmniCameraGeometry.hpp>\n\nnamespace aslam {\nnamespace cameras {\n\nOmniCameraGeometry::OmniCameraGeometry() { *this = createTestGeometry(); }\n\nOmniCameraGeometry::OmniCameraGeometry(double xi, double k1, double k2, double p1, double p2, double gamma1,\n                                       double gamma2, double u0, double v0, int width, int height)\n    : _xi(xi),\n      _k1(k1),\n      _k2(k2),\n      _p1(p1),\n      _p2(p2),\n      _gamma1(gamma1),\n      _gamma2(gamma2),\n      _u0(u0),\n      _v0(v0),\n      _width(width),\n      _height(height) {\n    updateTemporaries();\n}\n\nOmniCameraGeometry::~OmniCameraGeometry() {}\n\n// This updates the intrinsic parameters with a small step: i <-- i + di\n// The Jacobians above are with respect to this update function.\nvoid OmniCameraGeometry::updateIntrinsicsOplus(double* di) {\n    _xi += di[0];\n    _k1 += di[1];\n    _k2 += di[2];\n    _p1 += di[3];\n    _p2 += di[4];\n    _gamma1 += di[5];\n    _gamma2 += di[6];\n    _u0 += di[7];\n    _v0 += di[8];\n    updateTemporaries();\n}\n\n// The amount of time elapsed between the start of the image and the\n// keypoint. For a global shutter camera, this can return Duration(0).\nDuration OmniCameraGeometry::temporalOffset(const keypoint_t& keypoint) const { return Duration(0); }\n\nOmniCameraGeometry::keypoint_t OmniCameraGeometry::maxKeypoint() const { return keypoint_t(_width, _height); }\n\nOmniCameraGeometry::keypoint_t OmniCameraGeometry::minKeypoint() const { return keypoint_t(0, 0); }\n\nstd::string OmniCameraGeometry::typeName() const { return \"OmniCamera\"; }\n\nOmniCameraGeometry OmniCameraGeometry::createTestGeometry() {\n    return OmniCameraGeometry(1.2080, -2.103030975849235e-01, 1.511327079893021e-02, 6.035288960688402e-04,\n                              -5.277839371727245e-04, 5.671146836756682e+02, 5.665554204210736e+02,\n                              6.196542975873804e+02, 5.106649931478771e+02, 1224, 1024);\n}\n\n/**\n * \\brief Lifts a point from the image plane to the unit sphere\n *\n * \\param u u image coordinate\n * \\param v v image coordinate\n * \\param X X coordinate of the point on the sphere\n * \\param Y Y coordinate of the point on the sphere\n * \\param Z Z coordinate of the point on the sphere\n */\nvoid OmniCameraGeometry::lift_sphere(double u, double v, double* X, double* Y, double* Z) const {\n    double mx_d, my_d, mx_u, my_u;\n    double lambda;\n\n    // Lift points to normalised plane\n    // Matlab points start at 1 (calibration)\n    mx_d = _inv_K11 * (u) + _inv_K13;\n    my_d = _inv_K22 * (v) + _inv_K23;\n\n    // Recursive distortion model\n    // int n = 6;\n    // double dx_u, dy_u;\n    // distortion(mx_d,my_d,&dx_u,&dy_u);\n    // // Approximate value\n    // mx_u = mx_d-dx_u;\n    // my_u = my_d-dy_u;\n\n    // for(int i=1;i<n;i++) {\n    // \tdistortion(mx_u,my_u,&dx_u,&dy_u);\n    // \tmx_u = mx_d-dx_u;\n    // \tmy_u = my_d-dy_u;\n    // }\n    // PTF: March 31, 2012. The above was not that accurate.\n    //      Substitute Gauss-Newton.\n    undistortGN(mx_d, my_d, &mx_u, &my_u);\n\n    // Lift normalised points to the sphere (inv_hslash)\n    lambda = (_xi + sqrt(1 + (1 - _xi * _xi) * (mx_u * mx_u + my_u * my_u))) / (1 + mx_u * mx_u + my_u * my_u);\n    *X = lambda * mx_u;\n    *Y = lambda * my_u;\n    *Z = lambda - _xi;\n}\n\n/**\n * \\brief Lifts a point from the image plane to its projective ray\n *\n * \\param u u image coordinate\n * \\param v v image coordinate\n * \\param X X coordinate of the projective ray\n * \\param Y Y coordinate of the projective ray\n * \\param Z Z coordinate of the projective ray\n */\nvoid OmniCameraGeometry::lift_projective(double u, double v, double* X, double* Y, double* Z) const {\n    double mx_d, my_d, mx_u, my_u;\n    double rho2_d;\n\n    // Lift points to normalised plane\n    // Matlab points start at 1 (calibration)\n    mx_d = _inv_K11 * (u) + _inv_K13;\n    my_d = _inv_K22 * (v) + _inv_K23;\n\n    // Recursive distortion model\n    // int n = 8;\n    // double dx_u, dy_u;\n    // distortion(mx_d,my_d,&dx_u,&dy_u);\n    // // Approximate value\n    // mx_u = mx_d-dx_u;\n    // my_u = my_d-dy_u;\n\n    // for(int i=1;i<n;i++) {\n    // \tdistortion(mx_u,my_u,&dx_u,&dy_u);\n    // \tmx_u = mx_d-dx_u;\n    // \tmy_u = my_d-dy_u;\n    // }\n    // PTF: March 31, 2012. The above was not that accurate.\n    //      Substitute Gauss-Newton.\n    undistortGN(mx_d, my_d, &mx_u, &my_u);\n\n    // std::cout << \"lift projective: u: \" << mx_u << \", v: \" << my_u << std::endl;\n\n    // Obtain a projective ray\n    // Reuse variable\n    rho2_d = mx_u * mx_u + my_u * my_u;\n    *X = mx_u;\n    *Y = my_u;\n    *Z = 1 - _xi * (rho2_d + 1) / (_xi + sqrt(1 + (1 - _xi * _xi) * rho2_d));\n\n    // std::cout << \"lift projective: p: \" << *X << \", \" << *Y << \", \" << *Z << std::endl;\n}\n\n/**\n * \\brief Project a 3D points (\\a x,\\a y,\\a z) to the image plane in (\\a u,\\a v)\n *\n * \\param x 3D point x coordinate\n * \\param y 3D point y coordinate\n * \\param z 3D point z coordinate\n * \\param u return value, contains the image point u coordinate\n * \\param v return value, contains the image point v coordinate\n */\nvoid OmniCameraGeometry::space2plane(double x, double y, double z, double* u, double* v) const {\n    double mx_u, my_u, mx_d, my_d;\n\n    // Project points to the normalised plane\n    z = z + _xi * sqrt(x * x + y * y + z * z);\n    mx_u = x / z;\n    my_u = y / z;\n\n    // Apply distortion\n    double dx_u, dy_u;\n    distortion(mx_u, my_u, &dx_u, &dy_u);\n    mx_d = mx_u + dx_u;\n    my_d = my_u + dy_u;\n\n    // Apply generalised projection matrix\n    // Matlab points start at 1\n    *u = _gamma1 * mx_d + _u0;\n    *v = _gamma2 * my_d + _v0;\n}\n\n/**\n * \\brief Project a 3D points (\\a x,\\a y,\\a z) to the image plane in (\\a u,\\a v)\n *        and calculate jacobian\n *\n * \\param x 3D point x coordinate\n * \\param y 3D point y coordinate\n * \\param z 3D point z coordinate\n * \\param u return value, contains the image point u coordinate\n * \\param v return value, contains the image point v coordinate\n */\nvoid OmniCameraGeometry::space2plane(double x, double y, double z, double* u, double* v, double* dudx, double* dvdx,\n                                     double* dudy, double* dvdy, double* dudz, double* dvdz) const {\n    double mx_u, my_u, mx_d, my_d;\n    double norm, inv_denom;\n    double dxdmx, dydmx, dxdmy, dydmy;\n\n    norm = sqrt(x * x + y * y + z * z);\n    // Project points to the normalised plane\n    inv_denom = 1 / (z + _xi * norm);\n    mx_u = inv_denom * x;\n    my_u = inv_denom * y;\n\n    // Calculate jacobian\n    inv_denom = inv_denom * inv_denom / norm;\n    *dudx = inv_denom * (norm * z + _xi * (y * y + z * z));\n    *dvdx = -inv_denom * _xi * x * y;\n    *dudy = *dvdx;\n    *dvdy = inv_denom * (norm * z + _xi * (x * x + z * z));\n    inv_denom = inv_denom * (-_xi * z - norm);  // reuse variable\n    *dudz = x * inv_denom;\n    *dvdz = y * inv_denom;\n\n    // Apply distortion\n    double dx_u, dy_u;\n    distortion(mx_u, my_u, &dx_u, &dy_u, &dxdmx, &dydmx, &dxdmy, &dydmy);\n    mx_d = mx_u + dx_u;\n    my_d = my_u + dy_u;\n\n    // Make the product of the jacobians\n    // and add projection matrix jacobian\n    inv_denom = _gamma1 * (*dudx * dxdmx + *dvdx * dxdmy);  // reuse\n    *dvdx = _gamma2 * (*dudx * dydmx + *dvdx * dydmy);\n    *dudx = inv_denom;\n\n    inv_denom = _gamma1 * (*dudy * dxdmx + *dvdy * dxdmy);  // reuse\n    *dvdy = _gamma2 * (*dudy * dydmx + *dvdy * dydmy);\n    *dudy = inv_denom;\n\n    inv_denom = _gamma1 * (*dudz * dxdmx + *dvdz * dxdmy);  // reuse\n    *dvdz = _gamma2 * (*dudz * dydmx + *dvdz * dydmy);\n    *dudz = inv_denom;\n\n    // Apply generalised projection matrix\n    // Matlab points start at 1\n    *u = _gamma1 * mx_d + _u0;\n    *v = _gamma2 * my_d + _v0;\n}\n\n/**\n * \\brief Projects an undistorted 2D point (\\a mx_u,\\a my_u) to the image plane in (\\a u,\\a v)\n *\n * \\param mx_u 2D point x coordinate\n * \\param my_u 3D point y coordinate\n * \\param u return value, contains the image point u coordinate\n * \\param v return value, contains the image point v coordinate\n */\nvoid OmniCameraGeometry::undist2plane(double mx_u, double my_u, double* u, double* v) const {\n    double mx_d, my_d;\n\n    // Apply distortion\n    double dx_u, dy_u;\n    distortion(mx_u, my_u, &dx_u, &dy_u);\n    mx_d = mx_u + dx_u;\n    my_d = my_u + dy_u;\n\n    // Apply generalised projection matrix\n    // Matlab points start at 1\n    *u = _gamma1 * mx_d + _u0;\n    *v = _gamma2 * my_d + _v0;\n}\n\n/**\n * \\brief Apply distortion to input point (from the normalised plane)\n *\n * \\param mx_u undistorted x coordinate of point on the normalised plane\n * \\param my_u undistorted y coordinate of point on the normalised plane\n * \\param dx return value, to obtain the distorted point : mx_d = mx_u+dx_u\n * \\param dy return value, to obtain the distorted point : my_d = my_u+dy_u\n */\nvoid OmniCameraGeometry::distortion(double mx_u, double my_u, double* dx_u, double* dy_u) const {\n    double mx2_u, my2_u, mxy_u, rho2_u, rad_dist_u;\n\n    mx2_u = mx_u * mx_u;\n    my2_u = my_u * my_u;\n    mxy_u = mx_u * my_u;\n    rho2_u = mx2_u + my2_u;\n    rad_dist_u = _k1 * rho2_u + _k2 * rho2_u * rho2_u;\n    *dx_u = mx_u * rad_dist_u + 2 * _p1 * mxy_u + _p2 * (rho2_u + 2 * mx2_u);\n    *dy_u = my_u * rad_dist_u + 2 * _p2 * mxy_u + _p1 * (rho2_u + 2 * my2_u);\n}\n\n/**\n * \\brief Apply distortion to input point (from the normalised plane)\n *        and calculate jacobian\n *\n * \\param mx_u undistorted x coordinate of point on the normalised plane\n * \\param my_u undistorted y coordinate of point on the normalised plane\n * \\param dx return value, to obtain the distorted point : mx_d = mx_u+dx_u\n * \\param dy return value, to obtain the distorted point : my_d = my_u+dy_u\n */\nvoid OmniCameraGeometry::distortion(double mx_u, double my_u, double* dx_u, double* dy_u, double* dxdmx, double* dydmx,\n                                    double* dxdmy, double* dydmy) const {\n    double mx2_u, my2_u, mxy_u, rho2_u, rad_dist_u;\n\n    mx2_u = mx_u * mx_u;\n    my2_u = my_u * my_u;\n    mxy_u = mx_u * my_u;\n    rho2_u = mx2_u + my2_u;\n    rad_dist_u = _k1 * rho2_u + _k2 * rho2_u * rho2_u;\n    *dx_u = mx_u * rad_dist_u + 2 * _p1 * mxy_u + _p2 * (rho2_u + 2 * mx2_u);\n    *dy_u = my_u * rad_dist_u + 2 * _p2 * mxy_u + _p1 * (rho2_u + 2 * my2_u);\n\n    *dxdmx = 1 + rad_dist_u + _k1 * 2 * mx2_u + _k2 * rho2_u * 4 * mx2_u + 2 * _p1 * my_u + 6 * _p2 * mx_u;\n    *dydmx = _k1 * 2 * mx_u * my_u + _k2 * 4 * rho2_u * mx_u * my_u + _p1 * 2 * mx_u + 2 * _p2 * my_u;\n    *dxdmy = *dydmx;\n    *dydmy = 1 + rad_dist_u + _k1 * 2 * my2_u + _k2 * rho2_u * 4 * my2_u + 6 * _p1 * my_u + 2 * _p2 * mx_u;\n}\n\nvoid OmniCameraGeometry::updateTemporaries() {\n    // Inverse camera projection matrix parameters\n    _inv_K11 = 1.0 / _gamma1;\n    _inv_K13 = -_u0 / _gamma1;\n    _inv_K22 = 1.0 / _gamma2;\n    _inv_K23 = -_v0 / _gamma2;\n    _one_over_xixi_m_1 = 1.0 / (_xi * _xi - 1.0);\n}\n\nvoid OmniCameraGeometry::setIntrinsicsVectorImplementation(const Eigen::VectorXd& V) {\n    _xi = V[0];\n    _k1 = V[1];\n    _k2 = V[2];\n    _p1 = V[3];\n    _p2 = V[4];\n    _gamma1 = V[5];\n    _gamma2 = V[6];\n    _u0 = V[7];\n    _v0 = V[8];\n    updateTemporaries();\n}\n\nEigen::VectorXd OmniCameraGeometry::getIntrinsicsVectorImplementation() const {\n    Eigen::VectorXd V(9);\n    V[0] = _xi;\n    V[1] = _k1;\n    V[2] = _k2;\n    V[3] = _p1;\n    V[4] = _p2;\n    V[5] = _gamma1;\n    V[6] = _gamma2;\n    V[7] = _u0;\n    V[8] = _v0;\n    return V;\n}\n\nEigen::Matrix3d OmniCameraGeometry::getCameraMatrix() const {\n    Eigen::Matrix3d K;\n    K << _gamma1, 0, _u0, 0, _gamma2, _v0, 0, 0, 1;\n    return K;\n}\n\nEigen::VectorXd OmniCameraGeometry::createRandomKeypoint() const {\n    // This is tricky...The camera model defines a circle on the normalized image\n    // plane and the projection equations don't work outside of it.\n    // With some manipulation, we can see that, on the normalized image plane,\n    // the edge of this circle is at u^2 + v^2 = 1/(xi^2 - 1)\n    // So: this function creates keypoints inside this boundary.\n\n    // Create a point on the normalized image plane inside the boundary.\n    // This is not efficient, but it should be correct.\n\n    Eigen::Vector2d u(width() + 1, height() + 1);\n\n    while (u[0] < 0 || u[0] > width() - 1 || u[1] < 0 || u[1] > height() - 1) {\n        u.setRandom();\n        u = u - Eigen::Vector2d(0.5, 0.5);\n        u /= u.norm();\n        u *= ((double)rand() / (double)RAND_MAX) * _one_over_xixi_m_1;\n\n        // Now we run the point through distortion and projection.\n        // Apply distortion\n        double dx_u, dy_u;\n        distortion(u[0], u[1], &dx_u, &dy_u);\n        double mx_d = u[0] + dx_u;\n        double my_d = u[1] + dy_u;\n\n        // Apply generalised projection matrix\n        // Matlab points start at 1\n        u[0] = _gamma1 * mx_d + _u0;\n        u[1] = _gamma2 * my_d + _v0;\n    }\n\n    // I would like to do this below but it is way, way worse than above.\n    // // The output\n    // Eigen::Vector2d u;\n    // // The output projected to the normalized image plane.\n    // Eigen::Vector2d u_norm;\n\n    // // The singularity radius minus an epsilon\n    // double nRadius = 1.0/_one_over_xixi_m_1;\n\n    // do\n    // \t{\n    // \t  // Create a random keypoint in the image.\n    // \t  //u.setRandom();\n    // \t  u[0] = ( (double)rand() / (double)RAND_MAX)*_width;\n    // \t  u[1] = ( (double)rand() / (double)RAND_MAX)*_height;\n\n    // \t  // Lift points to normalised plane\n    // \t  // Matlab points start at 1 (calibration)\n    // \t  double u0_d = _inv_K11*(u[0])+_inv_K13;\n    // \t  double u1_d = _inv_K22*(u[1])+_inv_K23;\n    // \t  undistortGN(u0_d, u1_d, &u_norm[0], &u_norm[1]);\n\n    // \t}\n    // while( u_norm.dot(u_norm) >= nRadius );\n\n    return u;\n}\n\n// Use Gauss-Newton to undistort.\nvoid OmniCameraGeometry::undistortGN(double u_d, double v_d, double* u, double* v) const {\n    *u = u_d;\n    *v = v_d;\n\n    double ubar = u_d;\n    double vbar = v_d;\n    const int n = 5;\n    Eigen::Matrix2d F;\n\n    double hat_u_d;\n    double hat_v_d;\n\n    // void OmniCameraGeometry::distortion(double mx_u, double my_u,\n    // \t\t\t\t\t  double *dx_u, double *dy_u,\n    // \t\t\t\t\t  double *dxdmx, double *dydmx,\n    // \t\t\t\t\t  double *dxdmy, double *dydmy) const\n    for (int i = 0; i < n; i++) {\n        distortion(ubar, vbar, &hat_u_d, &hat_v_d, &F(0, 0), &F(1, 0), &F(0, 1), &F(1, 1));\n\n        Eigen::Vector2d e(u_d - ubar - hat_u_d, v_d - vbar - hat_v_d);\n        Eigen::Vector2d du = (F.transpose() * F).inverse() * F.transpose() * e;\n\n        ubar += du[0];\n        vbar += du[1];\n\n        if (e.dot(e) < 1e-15) break;\n    }\n    *u = ubar;\n    *v = vbar;\n}\n\n/// \\brief initialize the intrinsics based on one view of a gridded calibration target\n/// \\return true on success\n///\n/// These functions were developed with the help of Lionel Heng and the excellent camodocal\n/// https://github.com/hengli/camodocal\nbool OmniProjection::initializeIntrinsics(const GridCalibrationTargetObservation& obs) {\n    if (!obs.target()) {\n        return false;\n    }\n\n    double square(double x) { return x * x; }\n    float square(float x) { return x * x; }\n    double hypot(double a, double b) { return sqrt(square(a) + square(b)); }\n\n    // First, initialize the image center at the center of the image.\n    _xi = 1.0;\n    _cu = obs.imCols() / 2.0;\n    _cv = obs.imRows() / 2.0;\n    _ru = obs.imCols();\n    _rv = obs.imRows();\n\n    _distortion.clear();\n\n    // Grab a reference to the target for easy access.\n    const GridCalibrationTarget& target = *obs.target();\n\n    /// Initialize some temporaries needed.\n    double gamma0 = 0.0;\n    double minReprojErr = std::numeric_limits<double>::max();\n\n    // Now we try to find a non-radial line to initialize the focal length\n    bool success = false;\n    for (size_t r = 0; r < target.rows(); ++r) {\n        // Grab all the valid corner points for this checkerboard observation\n        cv::Mat P(target.cols(); 4, CV_64F);\n        size_t count = 0;\n        for (size_t c = 0; c < target.cols(); ++c) {\n            Eigen::Vector2d imagePoint;\n            Eigen::Vector3d gridPoint;\n            if (obs.imageGridPoint(r, c, imagePoint)) {\n                double u = imagePoint[0] - _cu;\n                double v = imagePoint[1] - _cv;\n                P.at<double>(count, 0) = u;\n                P.at<double>(count, 1) = v;\n                P.at<double>(count, 2) = 0.5;\n                P.at<double>(count, 3) = -0.5 * (square(u) + square(v));\n                ++count;\n            }\n        }\n\n        const int MIN_CORNERS = 8;\n        // MIN_CORNERS is an arbitrary threshold for the number of corners\n        if (count > MIN_CORNERS) {\n            // Resize P to fit with the count of valid points.\n            cv::Mat C;\n            cv::SVD::solveZ(P.colRange(0, count), C);\n\n            double t = square(C.at<double>(0)) + square(C.at<double>(1)) + C.at<double>(2) * C.at<double>(3);\n            if (t < 0) {\n                continue;\n            }\n\n            // check that line image is not radial\n            double d = sqrt(1.0 / t);\n            double nx = C.at<double>(0) * d;\n            double ny = C.at<double>(1) * d;\n            if (hypot(nx, ny) > 0.95) {\n                continue;\n            }\n\n            double nz = sqrt(1.0 - square(nx) - square(ny));\n            double gamma = fabs(C.at<double>(2) * d / nz);\n\n            _fu = gamma;\n            _fv = gamma;\n            sm::kinematics::Transformation T_target_camera;\n            if (!estimateTransformation(obs, T_target_camera)) {\n                continue;\n            }\n\n            double reprojErr = 0.0;\n            size_t numReprojected = computeReprojectionError(obs, T_target_camera, reprojErr);\n\n            if (numReprojected > MIN_CORNERS) {\n                double avgReprojErr = reprojErr / numReprojected;\n\n                if (avgReprojErr < minReprojErr) {\n                    minReprojErr = avgReprojErr;\n                    gamma0 = gamma;\n                    success = true;\n                }\n            }\n\n        }  // If this observation has enough valid corners\n    }      // For each row in the image.\n\n    _fu = gamma0;\n    _fv = gamma0;\n\n    return success;\n\n}  // initializeIntrinsics()\n\nbool OmniProjection::computeReprojectionError(const GridCalibrationTargetObservation& obs,\n                                              const sm::kinematics::Transformation& T_target_camera,\n                                              double& outErr) const {\n    outErr = 0.0;\n    size_t count = 0;\n    sm::kinematics::Transformation T_camera_target = T_target_camera.inverse();\n\n    for (size_t i = 0; i < obs.size(); ++i) {\n        Eigen::Vector2d y, yhat;\n        if (obs.imagePoint(i, y) && euclideanToKeypoint(T_camera_target * obs.target()->point(i), yhat)) {\n            outErr += (y - yhat).norm();\n            ++count;\n        }\n    }\n\n    return count;\n}\n\n/// \\brief estimate the transformation of the camera with respect to the calibration target\n///        On success out_T_t_c is filled in with the transformation that takes points from\n///        the camera frame to the target frame\n/// \\return true on success\n///\n/// These functions were developed with the help of Lionel Heng and the excellent camodocal\n/// https://github.com/hengli/camodocal\nbool OmniProjection::estimateTransformation(const GridCalibrationTargetObservation& obs,\n                                            sm::kinematics::Transformation& out_T_t_c) const {\n    // Convert all chessboard corners to a fakey pinhole view.\n    // Call the OpenCV pnp function.\n}\n\n}  // namespace cameras\n\n}  // namespace aslam\n", "meta": {"hexsha": "eb44b7718f16297ab9c8197a19824a6efd5a3f2e", "size": 19508, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_cv/aslam_cameras/src/OmniCameraGeometry.cpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aslam_cv/aslam_cameras/src/OmniCameraGeometry.cpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aslam_cv/aslam_cameras/src/OmniCameraGeometry.cpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9269565217, "max_line_length": 119, "alphanum_fraction": 0.5960118926, "num_tokens": 6195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4409083410629143}}
{"text": "/*\n * patSpeedDistributions.cc\n *\n *  Created on: Mar 26, 2012\n *      Author: jchen\n */\n\n#include \"patSpeedDistributions.h\"\n#include \"patDisplay.h\"\n#include \"patNBParameters.h\"\n#include \"patErrMiscError.h\"\n\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/lognormal.hpp> // for normal_distribution\n#include <boost/math/distributions/exponential.hpp> // for exponential distribution\n#include \"patDisplay.h\"\n#include \"patError.h\"\n#include <sstream>\n#include <vector>\n#include <cstdlib>\nusing boost::math::normal;\nusing boost::math::lognormal;\nusing boost::math::exponential_distribution;\n map<TransportMode, TrafficModelParam> patSpeedDistributions::tm_params;\npatSpeedDistributions::patSpeedDistributions() {\n\n}\n\npatSpeedDistributions::~patSpeedDistributions() {\n}\n\npatSpeedDistributions* patSpeedDistributions::ins = NULL;\n\npatSpeedDistributions* patSpeedDistributions::the() {\n\tif (patSpeedDistributions::ins == NULL) {\n\t\tpatSpeedDistributions::ins = new patSpeedDistributions;\n\t}\n\treturn patSpeedDistributions::ins;\n}\ndouble patSpeedDistributions::pdf(double v, TransportMode mode) {\n\tTrafficModelParam tm_param = patSpeedDistributions::tm_params[mode];\n\tdouble rtn = 0.0;\n\tif (v < 0.0) {\n//\t\tWARNING(\"wrong speed\" << v);\n\t\trtn = 0.0;\n\t} else if (v == 0.0) {\n\t\trtn = tm_param.w * tm_param.lambda;\n\t} else {\n\n\t\tif (tm_param.mode == TransportMode(WALK)) {\n\t\t\tboost::math::exponential e(tm_param.lambda);\t\n\t\t\tboost::math::normal n(tm_param.mu,tm_param.sigma);\n\t \t\t\n\t\t\trtn = tm_param.w * boost::math::pdf(e,v )  + (1.0-tm_param.w) *boost::math::pdf(n,v ) ;\n\t\t\t// rtn = tm_param.w * tm_param.lambda * exp(-tm_param.lambda * v)\n\t\t\t// \t\t+ (1.0 - tm_param.w)\n\t\t\t// \t\t\t\t* exp(-(v - tm_param.mu) * (v - tm_param.mu) /(2.0 * tm_param.sigma * tm_param.sigma))\n\t\t\t// \t\t\t\t/ (tm_param.sigma * sqrt(2.0 * \tM_PI) );\n\t\t} else {\n\t\t\tboost::math::exponential e(tm_param.lambda );\n\t\t\tboost::math::lognormal n(tm_param.mu,tm_param.sigma);\n\t\t\t rtn = tm_param.w * boost::math::pdf(e,v )  + (1.0-tm_param.w) *boost::math::pdf(n,v ) ;\n\t\t\t// rtn = tm_param.w * tm_param.lambda * exp(-tm_param.lambda * v)\n\t\t\t// \t\t+ (1.0 - tm_param.w)\n\t\t\t// \t\t\t\t* exp( -(log(v) - tm_param.mu) * (log(v) - tm_param.mu) /(2.0 * tm_param.sigma * tm_param.sigma))\n\t\t\t// \t\t\t\t/ (v * tm_param.sigma * sqrt(2.0 * M_PI));\n\t\t}\n\t}\n\tif (rtn >= 1.0 || rtn < 0.0) {\n\t\tWARNING(\"WRONG\");\n\t}\n\treturn rtn;\n}\nvoid patSpeedDistributions::readParams(patError*& err) {\n\n\tvector<TransportMode> modes;\n\tmodes.push_back(TransportMode(CAR));\n\tmodes.push_back(TransportMode(BUS));\n\tmodes.push_back(TransportMode(METRO));\n\tmodes.push_back(TransportMode(TRAIN));\n\tmodes.push_back(TransportMode(WALK));\n\tmodes.push_back(TransportMode(BIKE));\n\tfor (int i = 0; i < modes.size(); ++i) {\n\t\tTrafficModelParam params;\n\t\tparams.mode = modes[i];\n\t\tstring file_name = patNBParameters::the()->paramFolder + \"speed/\"\n\t\t\t\t+ getTransportModeString(modes[i]);\n\t\t//patAccelMeasurementModel::m_params[modes[i]];\n\t\tifstream file_stream_handler;\n\t\tfile_stream_handler.open(file_name.c_str(), ios::in);\n\t\tif (!file_stream_handler) {\n\t\t\tstringstream str;\n\t\t\tstr << \"Error while parsing \" << file_name;\n\t\t\terr = new patErrMiscError(str.str());\n\t\t\tWARNING(err->describe());\n\t\t\treturn;\n\t\t}\n//\t\tDEBUG_MESSAGE(\"Read file:\" << file_name);\n\t\tint components = 0;\n\t\tstring line;\n\t\tif (getline(file_stream_handler, line)) {\n\n\t\t\tistringstream linestream(line);\n\t\t\tstring item;\n\n\t\t\tgetline(linestream, item, ',');\n\t\t\t//\tDEBUG_MESSAGE(item);\n\t\t\tparams.w = atof(item.c_str());\n\n\t\t\tgetline(linestream, item, ',');\n\t\t\t//DEBUG_MESSAGE(item);\n\t\t\tparams.lambda = atof(item.c_str());\n\t\t\t//\t\tDEBUG_MESSAGE(item);\n\n\t\t\tgetline(linestream, item, ',');\n\t\t\tparams.mu = atof(item.c_str());\n//\t\t\tDEBUG_MESSAGE(item);\n\n\t\t\tgetline(linestream, item, ',');\n\t\t\tparams.sigma = atof(item.c_str());\n\n//\t\t\tDEBUG_MESSAGE(\n//\t\t\t\t\tparams.w << \",\" << params.lambda << \",\" << params.mu << \",\"\n//\t\t\t\t\t\t\t<< params.sigma)\n\t\t\tpatSpeedDistributions::tm_params[modes[i]] = params;\n\t\t} else {\n\t\t\tstringstream str;\n\t\t\tstr << \"Speed distribution for  \" << modes[i] << \"is wrong\";\n\t\t\terr = new patErrMiscError(str.str());\n\t\t\tWARNING(err->describe());\n\t\t\treturn;\n\n\t\t}\n\n\t}\n}\n", "meta": {"hexsha": "4031c730de228507caa3e5c8b4ea1200aff681ca", "size": 4161, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/MapMatching/patSpeedDistributions.cc", "max_stars_repo_name": "godosou/smaroute", "max_stars_repo_head_hexsha": "e2ccc9492dff54c8ef5c74d5309d2b06758ba342", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-02-23T16:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T17:58:53.000Z", "max_issues_repo_path": "src/MapMatching/patSpeedDistributions.cc", "max_issues_repo_name": "godosou/smaroute", "max_issues_repo_head_hexsha": "e2ccc9492dff54c8ef5c74d5309d2b06758ba342", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MapMatching/patSpeedDistributions.cc", "max_forks_repo_name": "godosou/smaroute", "max_forks_repo_head_hexsha": "e2ccc9492dff54c8ef5c74d5309d2b06758ba342", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-02-23T16:05:59.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-04T16:13:16.000Z", "avg_line_length": 30.3722627737, "max_line_length": 107, "alphanum_fraction": 0.6678683009, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4409083410629143}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n    @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_COT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_COT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-trigonometric\n    This function object returns the cotangent of the input in radian: \\f$\\cos(x)/\\sin(x)\\f$.\n\n\n    @par Header <boost/simd/function/cot.hpp>\n\n    @par Note\n\n      As most other trigonometric function cot can be called\n      with a second optional parameter  which is a tag on speed and accuracy\n      (see @ref cos for further details)\n\n    @see cos, sin, tan, cotd, cotpi\n\n\n    @par Example:\n\n      @snippet cot.cpp cot\n\n    @par Possible output:\n\n      @snippet cot.txt cot\n\n  **/\n  IEEEValue cot(IEEEValue const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/cot.hpp>\n#include <boost/simd/function/simd/cot.hpp>\n\n#endif\n", "meta": {"hexsha": "ac87e5ca27ee172a4931f1cb39afc85d6e8a5cbf", "size": 1217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/cot.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/cot.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/cot.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.862745098, "max_line_length": 100, "alphanum_fraction": 0.5875102712, "num_tokens": 270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.44090833484722414}}
{"text": "/// @file model.hpp Various log-PDF evaluators for parts of the Bayesian model\n\n#ifndef BIGGLES_MODEL_HPP__\n#define BIGGLES_MODEL_HPP__\n\n#include <vector>\n#include <boost/tuple/tuple.hpp>\n#include <Eigen/Dense>\n\n#include \"partition.hpp\"\n#include \"types.hpp\"\n\nnamespace biggles\n{\n\n/// @brief Functions and types defining the Biggles dynamic model\nnamespace model\n{\n\n/// @name Access to the tracking control parameters\n/// @{\ninline const float& birth_rate(const parameters& p) { return p.birth_rate; }\ninline float& birth_rate(parameters& p) { return p.birth_rate; }\n\ninline const float& clutter_rate(const parameters& p) { return p.clutter_rate; }\ninline float& clutter_rate(parameters& p) { return p.clutter_rate; }\n\ninline const float& survival_probability(const parameters& p) { return p.survival_probability; }\ninline float& survival_probability(parameters& p) { return p.survival_probability; }\n\ninline const float& observation_probability(const parameters& p) { return p.observation_probability; }\ninline float& observation_probability(parameters& p) { return p.observation_probability; }\n\ninline const matrix4f& process_noise_covariance(const parameters& p) { return p.process_noise_covariance; }\ninline matrix4f& process_noise_covariance(parameters& p) { return p.process_noise_covariance; }\n/// @}\n\n\n/// @brief Access the mean number of tracks per-frame parameter from a biggles::parameters tuple.\n///\n/// @param p\ninline const float& mean_new_tracks_per_frame(const parameters& p) { return p.birth_rate; }\n\n/// @brief Access the mean number of tracks per-frame parameter from a biggles::parameters tuple.\n///\n/// @param p\ninline float& mean_new_tracks_per_frame(parameters& p) { return p.birth_rate; }\n\n/// @brief Access the mean number of spurious observations per-frame parameter from a biggles::parameters tuple.\n///\n/// @param p\ninline const float& mean_false_observations_per_frame(const parameters& p) { return p.clutter_rate; }\n\n/// @brief Access the mean number of spurious observations per-frame parameter from a biggles::parameters tuple.\n///\n/// @param p\ninline float& mean_false_observations_per_frame(parameters& p) { return p.clutter_rate; }\n\n/// @brief Access the frame-to-frame survival probability parameter from a biggles::parameters tuple.\n///\n/// @param p\ninline const float& frame_to_frame_survival_probability(const parameters& p) { return p.survival_probability; }\n\n/// @brief Access the frame-to-frame survival probability parameter from a biggles::parameters tuple.\n///\n/// @param p\ninline float& frame_to_frame_survival_probability(parameters& p) { return p.survival_probability; }\n\n/// @brief Access the probability that a track will generate an observation from a biggles::parameters tuple.\n///\n/// @param p\ninline const float& generate_observation_probability(const parameters& p) { return p.observation_probability; }\n\n/// @brief Access the probability that a track will generate an observation from a biggles::parameters tuple.\n///\n/// @param p\ninline float& generate_observation_probability(parameters& p) { return p.observation_probability; }\n\n/// @brief Access the covariance matrix of the observation error from a biggles::parameters tuple.\n///\n/// @param p\ninline const Eigen::Matrix2f& observation_error_covariance(const parameters& p) { return p.observation_error_covariance; }\n\n/// @brief Access the covariance matrix of the observation error from a biggles::parameters tuple.\n///\n/// @param p\ninline Eigen::Matrix2f& observation_error_covariance(parameters& p) { return p.observation_error_covariance; }\n\n/// @brief Access the constraint radius from a biggles::parameters tuple.\n///\n/// @param p\ninline const float& constraint_radius(const parameters& p) { return p.constraint_radius; }\n\n/// @brief Access the constraint radius from a biggles::parameters tuple.\n///\n/// @param p\ninline float& constraint_radius(parameters& p) { return p.constraint_radius; }\n\n/// @brief Calculate the log-pdf of a partition given a set of model parameters, independent of observed data.\n///\n/// **The following needs to be reviewed. Binomial coefficients need to be included**\n///\n/// Calculate the value of \\f$ \\ell(T | \\theta) \\f$ from the partition and model parameters given. Since the model\n/// parameters are independent of one another, we may factorise the pdf as follows:\n///\n/// \\f[\n/// P(T | \\theta) = P(T | p_s) P(T | p_d) P(T | \\lambda_b) P(T | \\lambda_f).\n/// \\f]\n///\n/// Note that \\f$ R \\f$ does not appear here because it depends on data; these terms are all the data-independent parts\n/// of the posterior on \\f$ T \\f$. Each of these terms may defined in terms of the following values:\n///\n/// - \\f$ N_t^s \\f$: the number of tracks which survive from \\f$ t-1 \\f$ to \\f$ t \\f$;\n/// - \\f$ N_t^d \\f$: the number of tracks which <em>did not</em> survive from \\f$ t-1 \\f$ to \\f$ t \\f$;\n/// - \\f$ N_t^b \\f$: the number of tracks which newly appeared at \\f$ t \\f$;\n/// - \\f$ N_t^o \\f$: the number of observations assigned to a track at \\f$ t \\f$;\n/// - \\f$ N_t^f \\f$: the number of observations deemed spurious at \\f$ t \\f$,\n///\n/// where \\f$ N_0^s = N_o^b = 0 \\f$ by convention. Each of the individual parameter pdf terms can be written down based\n/// on the definition of the corresponding parameters:\n///\n/// - \\f$ P(T | p_s) = \\prod_{t=1}^K p_s^{N_t^s} (1-p_s)^{N_t^d}; \\f$\n/// - \\f$ P(T | p_d) = \\prod_{t=1}^K p_d^{N_t^o} (1-p_d)^{N_t^s + N_t^b - N_t^o}; \\f$\n/// - \\f$ P(T | \\lambda_b) = \\prod_{t=1}^K \\mathcal{P}(N_t^b ; \\lambda_b); \\f$\n/// - \\f$ P(T | \\lambda_f) = \\prod_{t=1}^K \\mathcal{P}(N_t^f ; \\lambda_f), \\f$\n///\n/// where \\f$ \\mathcal{P}(x ; \\lambda) \\f$ is the Poisson pmf with mean \\f$ \\lambda \\f$ evaluated at \\f$ x \\f$. The\n/// corresponding log terms become:\n///\n/// - \\f$ \\ell(T | p_s) = \\sum_{t=1}^K N_t^s \\log(p_s) + N_t^d \\log(1-p_s); \\f$\n/// - \\f$ \\ell(T | p_d) = \\sum_{t=1}^K N_t^o \\log(p_d) + (N_t^s + N_t^b - N_t^o) \\log(1-p_d); \\f$\n/// - \\f$ \\ell(T | \\lambda_b) = \\sum_{t=1}^K N_t^b \\log(\\lambda_b) - \\lambda_b - \\log(\\Gamma(1 + N_t^b)); \\f$\n/// - \\f$ \\ell(T | \\lambda_f) = \\sum_{t=1}^K N_t^f \\log(\\lambda_f) - \\lambda_f - \\log(\\Gamma(1 + N_t^f)); \\f$\n///\n/// @sa biggles::parameters\n///\n/// @param part A reference to the partition to consider.\n/// @param parameters A reference to the model parameters.\n///\n/// @return The value of \\f$ \\ell(T | \\theta) \\f$.\nfloat log_partition_given_parameters_density(const partition& part, const parameters& parameters);\n\nfloat log_partition_given_observation_prob_density(const partition& part, const parameters& parameters);\nfloat log_partition_given_survival_prob_density(const partition& part, const parameters& parameters);\nfloat log_partition_given_birth_rate_density(const partition& part, const parameters& parameters);\nfloat log_partition_given_clutter_rate_density(const partition& part, const parameters& parameters);\n\n/// @brief Calculate the log-pdf for the track <em>observations</em> given the parameters.\n///\n/// This function works by using a biggles::kalman_filter to sample missing states for a track and then to calculate\n/// the likelihood of the observations we've seen given the parameters.\n///\n/// Specifically, suppose we have an observation \\f$ y \\f$, a predicted state, \\f$ \\hat{x} \\f$ and state estimation\n/// error estimate, \\f$ \\hat{P} \\f$. Then the total error in the predicted observation, \\f$ \\hat{y} = B \\hat{x} \\f$ is\n/// given by \\f$ \\hat{\\Sigma} = B \\hat{P} B^T + R \\f$. We therefore calculate the likelihood of \\f$ y \\f$ assuming a\n/// Gaussian model:\n///\n/// \\f[\n/// P(y | \\hat{x}, \\hat{P}) = \\mathcal{N}(y ; \\hat{y}, \\hat{\\Sigma}).\n/// \\f]\n///\n/// We combine all these likelihoods for each observation in the track.\n///\n/// @sa biggles::kalman_filter\n///\n/// @param track_p\n/// @param parameters\n///\n/// @return The value of \\f$ \\ell(d_i|t_i, \\theta) \\f$.\nfloat log_track_given_parameters_density(const boost::shared_ptr<const track>& track_p,\n                                         const parameters& parameters);\n\n/// @brief Compute the log-prior on the model parameters.\n///\n/// The prior on the model parameters is as follows:\n///\n/// - \\f$ \\lambda_b \\f$ and \\f$ \\lambda_s \\f$ have improper uninformative priors on them being positive.\n/// - \\f$ p_s \\f$ and \\f$ p_d \\f$ have uniform priors over [0, 1].\n/// - \\f$ R \\f$ has an inverse Wishart prior with parameters \\f$ \\Phi = 2I \\f$ and \\f$ s = 5 \\f$. These are the same\n/// parameters as in sample_parameters_given_partition().\n///\n/// @sa sample_parameters_given_partition()\n///\n/// @param parameters The model parameters whose prior should be calculated.\n///\n/// @return The value of \\f$ \\ell(\\theta) \\f$.\nfloat log_parameters_prior_density(const parameters& parameters);\n\n/// @brief Calculate the log pdf of the clutter observations given the model parameters.\n///\n/// The clutter observations themselves are independent of the model parameter \\f$ R \\f$ and so their distribution is\n/// very simple:\n///\n/// \\f[\n/// P(d_0 | t_0, \\theta) = \\prod_{t=1}^K \\left( \\frac{1}{V} \\right)^{N_t^f}\n/// \\f]\n///\n/// where \\f$ V \\f$ is the total number of pixels in the image.\n///\n/// @note Currently it is assumed that \\f$ V = 256^2 \\f$. This is really a bug but for the moment, this is the only\n/// place where the absolute image size matters.\n///\n/// @param clutter\n/// @param parameters\n///\n/// @return The value of \\f$ \\ell(d_0 | t_0, \\theta) \\f$.\nfloat log_clutter_given_parameters_density(const partition& part, const parameters& parameters);\n\n/// @brief Calculate the log pdf of the track observations given the model parameters.\n///\n/// This uses the Kalman filter. track likelihood depends on the model parameter \\f$ R \\f$ only.\nfloat log_tracks_given_parameters_density(const partition& part, const model::parameters& parameters);\n\n/** \\brief returns log( p(data| partition, parameters) )\n *\n *\n */\nfloat log_likelihood(const partition& part_sample, const model::parameters& para_sample);\n\n/// @brief Evaluate the full log pdf for a particular partition\n///\n/// In the documentation for biggles::partition_sampler, it was shown that\n///\n/// \\f[\n/// \\ell(T | \\theta, D) = \\kappa + \\ell(d_0|t_0, \\theta) + \\sum_{i=1}^K \\ell(d_i|t_i, \\theta) + \\ell(T|\\theta) +\n/// \\ell(\\theta).\n/// \\f]\n///\n/// This function computes this value by calling other log density calculation functions.\n///\n/// @sa biggles::partition_sampler\n/// @sa log_clutter_given_parameters_density()\n/// @sa log_track_given_parameters_density()\n/// @sa log_partition_given_parameters_density()\n/// @sa log_parameters_prior_density()\n///\n/// @param part\n/// @param parameters\n///\n/// @return The value of \\f$ \\ell(T | \\theta, D) + \\kappa \\f$ where \\f$ \\kappa \\f$ is some constant offset.\nfloat log_partition_given_parameters_and_data_density(const partition& part, const parameters& parameters);\n\n\nclass log_factorial {\n    typedef float VALUE_TYPE;\n    std::deque< VALUE_TYPE > factorial_;\n    log_factorial() {\n        factorial_.push_back(0.f);\n        factorial_.push_back(0.f);\n    }\n    log_factorial& operator=(log_factorial&);\n    log_factorial(const log_factorial&);\npublic:\n    /// \\brief the call operator (non-const)\n    VALUE_TYPE operator() (size_t n) {\n        while (n >= factorial_.size()) {\n            factorial_.push_back(factorial_.back() + logf(factorial_.size()));\n        }\n        return factorial_.at(n);\n    }\n    /// \\brief calculate without creating a reference\n    static VALUE_TYPE calc (size_t n) {\n        static log_factorial fact;\n        return fact(n);\n    }\n    /// \\brief return an instance of the binomial coefficent\n    static log_factorial& get() {\n        static log_factorial fact;\n        return fact;\n    }\n};\n\n/// \\brief calculates the binomial coefficent\n///\n/// Each value is calculated once and is stored in Pascal's triangle.\n/// The calculation includes an overflow control.\n/// It is a recursive procedure.\n/// This is implemented as a singleton\nclass binomial_coefficient {\n    typedef float VALUE_TYPE;\n    /// \\brief the row type; the size of each vector is fixed\n    typedef std::vector<VALUE_TYPE> row_t;\n    std::deque< row_t > triangle_; /// \\brief Pascal's triangle\n    size_t num_rows_; /// \\brief the current number of rows of Pascal's triangle\n    /// \\brief The calculation routine\n    void build_row(size_t n) {\n        row_t row(n+1, VALUE_TYPE(1));\n        for (size_t k = 1; k < n; ++k) {\n            VALUE_TYPE s1 = operator()(n-1, k - 1);\n            VALUE_TYPE s2 = operator()(n-1, k);\n            if (s1 + s2 < s1) {\n                std::stringstream errmsg;\n                errmsg << \"maximum reached n = \" << n << \", k = \" << k;\n                throw std::overflow_error(errmsg.str());\n            }\n            row[k] = s1 + s2;\n        }\n        triangle_.push_back(row);\n        num_rows_ = triangle_.size();\n    }\n    /// \\brief The constructor initalises the Pascal's triangle with (0 choose 0)\n    binomial_coefficient() {\n        triangle_.push_back(row_t(1,VALUE_TYPE(1)));\n        num_rows_ = triangle_.size();\n    }\n    binomial_coefficient& operator=(binomial_coefficient&);\n    binomial_coefficient(const binomial_coefficient&);\npublic:\n    /// \\brief the call operator (non-const)\n    VALUE_TYPE operator() (size_t n, size_t k) {\n        if (num_rows_ <= n) build_row(n);\n        return triangle_[n][k];\n    }\n    /// \\brief return an instance of the binomial coefficent\n    static binomial_coefficient& get() {\n        static binomial_coefficient bc;\n        return bc;\n    }\n};\n\n}\n\n}\n\n#endif // BIGGLES_MODEL_HPP__\n", "meta": {"hexsha": "f0be6fe2971a43cbd2928f99e490a988ac8860f7", "size": 13472, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/biggles/model.hpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "include/biggles/model.hpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/biggles/model.hpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3251533742, "max_line_length": 122, "alphanum_fraction": 0.6866092637, "num_tokens": 3550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4409083348472241}}
{"text": "#ifndef PARMCB_SVA_TREES_HPP_\n#define PARMCB_SVA_TREES_HPP_\n\n//    Copyright (C) Dimitrios Michail 2019 - 2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/tuple/detail/tuple_basic.hpp>\n#include <boost/timer/timer.hpp>\n\n#include <cstddef>\n#include <functional>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <set>\n#include <vector>\n\n#include <parmcb/forestindex.hpp>\n#include <parmcb/spvecgf2.hpp>\n#include <parmcb/util.hpp>\n#include <parmcb/sptrees.hpp>\n#include <parmcb/detail/cycles.hpp>\n\nnamespace parmcb {\n\n    template<class Graph, class WeightMap, class CycleOutputIterator, class CyclesBuilder, bool ParallelUsingTBB>\n    typename boost::property_traits<WeightMap>::value_type _mcb_sva_trees(const Graph &g, WeightMap weight_map,\n            CycleOutputIterator out) {\n        typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n        typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n        /*\n         * Index the graph\n         */\n        ForestIndex<Graph> forest_index(g);\n        auto csd = forest_index.cycle_space_dimension();\n        std::cout << \"Cycle space dimension: \" << csd << std::endl;\n\n        /*\n         * Initialize support vectors\n         */\n        std::vector<SpVecGF2<std::size_t>> support;\n        for (std::size_t k = 0; k < csd; k++) {\n            support.emplace_back(k);\n        }\n\n        boost::timer::cpu_timer cycle_timer;\n        cycle_timer.stop();\n        boost::timer::cpu_timer support_timer;\n        support_timer.stop();\n        boost::timer::cpu_timer trees_timer;\n        trees_timer.stop();\n\n        /*\n         * Initialize all shortest path trees\n         */\n        trees_timer.resume();\n        std::vector<parmcb::SPTree<Graph, WeightMap>> trees;\n        std::vector<parmcb::CandidateCycle<Graph, WeightMap>> cycles;\n        CyclesBuilder cycles_builder;\n        cycles_builder(g, weight_map, trees, cycles);\n        std::cout << \"Total candidate cycles: \" << cycles.size() << std::endl;\n        const bool sorted_cycles = true;\n        if (sorted_cycles) {\n            // sort\n            std::cout << \"Sorting cycles\" << std::endl;\n            std::sort(cycles.begin(), cycles.end(), [](const auto &a, const auto &b) {\n                return a.weight() < b.weight();\n            });\n        }\n        ShortestOddCycleLookup<Graph, WeightMap, ParallelUsingTBB> cycle_lookup(g, weight_map, trees, cycles,\n                sorted_cycles);\n        trees_timer.stop();\n\n        /*\n         * Main loop\n         */\n        WeightType mcb_weight = WeightType();\n        for (std::size_t k = 0; k < csd; k++) {\n            if (k % 250 == 0) {\n                std::cout << k << std::endl;\n            }\n\n            /*\n             * Compute shortest odd cycle\n             */\n            std::set<Edge> signed_edges;\n            convert_edges(support[k], std::inserter(signed_edges, signed_edges.end()), forest_index);\n            cycle_timer.resume();\n            std::tuple<std::set<Edge>, WeightType, bool> best = cycle_lookup(signed_edges);\n            cycle_timer.stop();\n\n            /*\n             * Update support vectors\n             */\n            support_timer.resume();\n            std::set<std::size_t> cyclek;\n            convert_edges(std::get<0>(best), std::inserter(cyclek, cyclek.end()), forest_index);\n            for (std::size_t l = k + 1; l < csd; l++) {\n                if (support[l] * cyclek == 1) {\n                    support[l] += support[k];\n                }\n            }\n            support_timer.stop();\n\n            /*\n             * Output new cycle\n             */\n            std::list<Edge> cyclek_edgelist;\n            std::copy(std::get<0>(best).begin(), std::get<0>(best).end(), std::back_inserter(cyclek_edgelist));\n            *out++ = cyclek_edgelist;\n            mcb_weight += std::get<1>(best);\n        }\n\n        std::cout << \"trees   timer\" << trees_timer.format();\n        std::cout << \"cycle   timer\" << cycle_timer.format();\n        std::cout << \"support timer\" << support_timer.format();\n\n        return mcb_weight;\n    }\n\n    template<class Graph, class WeightMap, class CycleOutputIterator>\n    typename boost::property_traits<WeightMap>::value_type mcb_sva_fvs_trees(const Graph &g, WeightMap weight_map,\n            CycleOutputIterator out) {\n        return _mcb_sva_trees<Graph, WeightMap, CycleOutputIterator, parmcb::detail::FVSCyclesBuilder<Graph, WeightMap>,\n                false>(g, weight_map, out);\n    }\n\n    template<class Graph, class WeightMap, class CycleOutputIterator>\n    typename boost::property_traits<WeightMap>::value_type mcb_sva_fvs_trees_tbb(const Graph &g, WeightMap weight_map,\n            CycleOutputIterator out) {\n        return _mcb_sva_trees<Graph, WeightMap, CycleOutputIterator, parmcb::detail::FVSCyclesBuilder<Graph, WeightMap>,\n                true>(g, weight_map, out);\n    }\n\n    template<class Graph, class WeightMap, class CycleOutputIterator>\n    typename boost::property_traits<WeightMap>::value_type mcb_sva_iso_trees(const Graph &g, WeightMap weight_map,\n            CycleOutputIterator out) {\n        return _mcb_sva_trees<Graph, WeightMap, CycleOutputIterator, parmcb::detail::ISOCyclesBuilder<Graph, WeightMap>,\n                false>(g, weight_map, out);\n    }\n\n    template<class Graph, class WeightMap, class CycleOutputIterator>\n    typename boost::property_traits<WeightMap>::value_type mcb_sva_iso_trees_tbb(const Graph &g, WeightMap weight_map,\n            CycleOutputIterator out) {\n        return _mcb_sva_trees<Graph, WeightMap, CycleOutputIterator, parmcb::detail::ISOCyclesBuilder<Graph, WeightMap>,\n                true>(g, weight_map, out);\n    }\n\n} // namespace parmcb\n\n#endif\n", "meta": {"hexsha": "249d1c65527a89edfe363f70d496e927c40cd687", "size": 5940, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/parmcb/parmcb_sva_trees.hpp", "max_stars_repo_name": "d-michail/parmcb", "max_stars_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/parmcb/parmcb_sva_trees.hpp", "max_issues_repo_name": "d-michail/parmcb", "max_issues_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/parmcb/parmcb_sva_trees.hpp", "max_forks_repo_name": "d-michail/parmcb", "max_forks_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8343949045, "max_line_length": 120, "alphanum_fraction": 0.6175084175, "num_tokens": 1410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.44090832863153356}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n/*\n  Copyright (C) 2014, 2016 Peter Caspers\n\n  This file is part of QuantLib, a free-software/open-source library\n  for financial quantitative analysts and developers - http://quantlib.org/\n\n  QuantLib is free software: you can redistribute it and/or modify it\n  under the terms of the QuantLib license.  You should have received a\n  copy of the license along with this program; if not, please email\n  <quantlib-dev@lists.sf.net>. The license is also available online at\n  <http://quantlib.org/license.shtml>.\n\n\n  This program is distributed in the hope that it will be useful, but\n  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n  or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file lineartsrpricer.cpp\n*/\n\n#include <ql/cashflows/lineartsrpricer.hpp>\n#include <ql/cashflows/fixedratecoupon.hpp>\n#include <ql/cashflows/iborcoupon.hpp>\n#include <ql/cashflows/cmscoupon.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/indexes/iborindex.hpp>\n#include <ql/time/schedule.hpp>\n#include <ql/instruments/vanillaswap.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n#include <ql/math/integrals/kronrodintegral.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/termstructures/volatility/atmsmilesection.hpp>\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\n   const Real LinearTsrPricer::defaultLowerBound = 0.0001,\r\n             LinearTsrPricer::defaultUpperBound = 2.0000;\n\n    LinearTsrPricer::LinearTsrPricer(\n        const Handle<SwaptionVolatilityStructure> &swaptionVol,\n        const Handle<Quote> &meanReversion,\n        const Handle<YieldTermStructure> &couponDiscountCurve,\n        const Settings &settings,\n        const boost::shared_ptr<Integrator> &integrator)\n        : CmsCouponPricer(swaptionVol), meanReversion_(meanReversion),\n          couponDiscountCurve_(couponDiscountCurve), settings_(settings),\n          volDayCounter_(swaptionVol->dayCounter()), integrator_(integrator) {\n\n        if (!couponDiscountCurve_.empty())\n            registerWith(couponDiscountCurve_);\n\n        if (integrator_ == NULL)\n            integrator_ =\n                boost::make_shared<GaussKronrodNonAdaptive>(1E-10, 5000, 1E-10);\n    }\n\n    Real LinearTsrPricer::GsrG(const Date &d) const {\n\n        Real yf = volDayCounter_.yearFraction(fixingDate_, d);\n        if (std::fabs(meanReversion_->value()) < 1.0E-4)\n            return yf;\n        else\n            return (1.0 - std::exp(-meanReversion_->value() * yf)) /\n                   meanReversion_->value();\n    }\n\n    Real LinearTsrPricer::singularTerms(const Option::Type type,\n                                        const Real strike) const {\n\n        Real omega = (type == Option::Call ? 1.0 : -1.0);\n        Real s1 = std::max(omega * (swapRateValue_ - strike), 0.0) *\n                  (a_ * swapRateValue_ + b_);\n        Real s2 = (a_ * strike + b_) *\n                  smileSection_->optionPrice(strike, strike < swapRateValue_\n                                                         ? Option::Put\n                                                         : Option::Call);\n        return s1 + s2;\n    }\n\n    Real LinearTsrPricer::integrand(const Real strike) const {\n        return 2.0 * a_ * smileSection_->optionPrice(\n                              strike, strike < swapRateValue_ ? Option::Put\n                                                              : Option::Call);\n    }\n\n    void LinearTsrPricer::initialize(const FloatingRateCoupon &coupon) {\n\n        coupon_ = dynamic_cast<const CmsCoupon *>(&coupon);\n        QL_REQUIRE(coupon_, \"CMS coupon needed\");\n        gearing_ = coupon_->gearing();\n        spread_ = coupon_->spread();\n\n        fixingDate_ = coupon_->fixingDate();\n        paymentDate_ = coupon_->date();\n        swapIndex_ = coupon_->swapIndex();\n\n        forwardCurve_ = swapIndex_->forwardingTermStructure();\n        if (swapIndex_->exogenousDiscount())\n            discountCurve_ = swapIndex_->discountingTermStructure();\n        else\n            discountCurve_ = forwardCurve_;\n\n        // if no coupon discount curve is given just use the discounting curve\n        // from the swap index. for rate calculation this curve cancels out in\n        // the computation, so e.g. the discounting swap engine will produce\n        // correct results, even if the couponDiscountCurve is not set here.\n        // only the price member function in this class will be dependent on the\n        // coupon discount curve.\n\n        today_ = QuantLib::Settings::instance().evaluationDate();\n\n        if (paymentDate_ > today_ && !couponDiscountCurve_.empty())\n            couponDiscountRatio_ =\n                couponDiscountCurve_->discount(paymentDate_) /\n                discountCurve_->discount(paymentDate_);\n        else\n            couponDiscountRatio_ = 1.;\n\n        spreadLegValue_ = spread_ * coupon_->accrualPeriod() *\n                          discountCurve_->discount(paymentDate_) *\n                          couponDiscountRatio_;\n\n        if (fixingDate_ > today_) {\n\n            swapTenor_ = swapIndex_->tenor();\n            swap_ = swapIndex_->underlyingSwap(fixingDate_);\n\n            swapRateValue_ = swap_->fairRate();\n            annuity_ = 1.0E4 * std::fabs(swap_->fixedLegBPS());\n\n            boost::shared_ptr<SmileSection> sectionTmp =\n                swaptionVolatility()->smileSection(fixingDate_, swapTenor_);\n\n            adjustedLowerBound_ = settings_.lowerRateBound_;\n            adjustedUpperBound_ = settings_.upperRateBound_;\n\n            if(sectionTmp->volatilityType() == Normal) {\n                // adjust lower bound if it was not set explicitly\n                if(settings_.defaultBounds_)\n                    adjustedLowerBound_ = std::min(adjustedLowerBound_, -adjustedUpperBound_);\n            } else {\n                // adjust bounds by section's shift\n                adjustedLowerBound_ -= sectionTmp->shift();\n                adjustedUpperBound_ -= sectionTmp->shift();\n            }\n\n            // if the section does not provide an atm level, we enhance it to\n            // have one, no need to exit with an exception ...\n\n            if (sectionTmp->atmLevel() == Null<Real>())\n                smileSection_ = boost::make_shared<AtmSmileSection>(\n                    sectionTmp, swapRateValue_);\n            else\n                smileSection_ = sectionTmp;\n\n            // compute linear model's parameters\n\n            Real gx = 0.0, gy = 0.0;\n            for (Size i = 0; i < swap_->fixedLeg().size(); i++) {\n                boost::shared_ptr<Coupon> c =\n                    boost::dynamic_pointer_cast<Coupon>(swap_->fixedLeg()[i]);\n                Real yf = c->accrualPeriod();\n                Date d = c->date();\n                Real pv = yf * discountCurve_->discount(d);\n                gx += pv * GsrG(d);\n                gy += pv;\n            }\n\n            Real gamma = gx / gy;\n            Date lastd = swap_->fixedLeg().back()->date();\n\n            a_ = discountCurve_->discount(paymentDate_) *\n                 (gamma - GsrG(paymentDate_)) /\n                 (discountCurve_->discount(lastd) * GsrG(lastd) +\n                  swapRateValue_ * gy * gamma);\n\n            b_ = discountCurve_->discount(paymentDate_) / gy -\n                 a_ * swapRateValue_;\n        }\n    }\n\n    Real LinearTsrPricer::strikeFromVegaRatio(Real ratio,\n                                              Option::Type optionType,\n                                              Real referenceStrike) const {\n\n        Real a, b, min, max, k;\n        if (optionType == Option::Call) {\n            a = swapRateValue_;\n            min = referenceStrike;\n            b = max = k =\n                std::min(smileSection_->maxStrike(), adjustedUpperBound_);\n        } else {\n            a = min = k =\n                std::max(smileSection_->minStrike(), adjustedLowerBound_);\n            b = swapRateValue_;\n            max = referenceStrike;\n        }\n\n        VegaRatioHelper h(&*smileSection_,\n                          smileSection_->vega(swapRateValue_) * ratio);\n        Brent solver;\n\n        try {\n            k = solver.solve(h, 1.0E-5, (a + b) / 2.0, a, b);\n        }\n        catch (...) {\n            // use default value set above\n        }\n\n        return std::min(std::max(k, min), max);\n    }\n\n    Real LinearTsrPricer::strikeFromPrice(Real price, Option::Type optionType,\n                                          Real referenceStrike) const {\n\n        Real a, b, min, max, k;\n        if (optionType == Option::Call) {\n            a = swapRateValue_;\n            min = referenceStrike;\n            b = max = k =\n                std::min(smileSection_->maxStrike(), adjustedUpperBound_);\n        } else {\n            a = min = k =\n                std::max(smileSection_->minStrike(), adjustedLowerBound_);\n            b = swapRateValue_;\n            max = referenceStrike;\n        }\n\n        PriceHelper h(&*smileSection_, optionType, price);\n        Brent solver;\n\n        try {\n            k = solver.solve(h, 1.0E-5, swapRateValue_, a, b);\n        }\n        catch (...) {\n            // use default value set above\n        }\n\n        return std::min(std::max(k, min), max);\n    }\n\n    Real LinearTsrPricer::optionletPrice(Option::Type optionType,\n                                         Real strike) const {\n\n        if (optionType == Option::Call && strike >= adjustedUpperBound_)\n            return 0.0;\n        if (optionType == Option::Put && strike <= adjustedLowerBound_)\n            return 0.0;\n\n        // determine lower or upper integration bound (depending on option type)\n\n        Real lower = strike, upper = strike;\n\n        switch (settings_.strategy_) {\n\n        case Settings::RateBound: {\n            if (optionType == Option::Call)\n                upper = adjustedUpperBound_;\n            else\n                lower = adjustedLowerBound_;\n            break;\n        }\n\n        case Settings::VegaRatio: {\n            // strikeFromVegaRatio ensures that returned strike is on the\n            // expected side of strike\n            Real bound =\n                strikeFromVegaRatio(settings_.vegaRatio_, optionType, strike);\n            if (optionType == Option::Call)\n                upper = std::min(bound, adjustedUpperBound_);\n            else\n                lower = std::max(bound, adjustedLowerBound_);\n            break;\n        }\n\n        case Settings::PriceThreshold: {\n            // strikeFromPrice ensures that returned strike is on the expected\n            // side of strike\n            Real bound =\n                strikeFromPrice(settings_.vegaRatio_, optionType, strike);\n            if (optionType == Option::Call)\n                upper = std::min(bound, adjustedUpperBound_);\n            else\n                lower = std::max(bound, adjustedLowerBound_);\n            break;\n        }\n\n        case Settings::BSStdDevs : {\n            Real atm = smileSection_->atmLevel();\n            Real atmVol = smileSection_->volatility(atm);\n            Real shift = smileSection_->shift();\n            Real lowerTmp, upperTmp;\n            if (smileSection_->volatilityType() == ShiftedLognormal) {\n                upperTmp = (atm + shift) *\n                               std::exp(settings_.stdDevs_ * atmVol -\n                                        0.5 * atmVol * atmVol *\n                                            smileSection_->exerciseTime()) -\n                           shift;\n                lowerTmp = (atm + shift) *\n                               std::exp(-settings_.stdDevs_ * atmVol -\n                                        0.5 * atmVol * atmVol *\n                                            smileSection_->exerciseTime()) -\n                           shift;\n            } else {\n                Real tmp = settings_.stdDevs_ * atmVol *\n                           std::sqrt(smileSection_->exerciseTime());\n                upperTmp = atm + tmp;\n                lowerTmp = atm - tmp;\n            }\n            upper = std::min(upperTmp - shift, adjustedUpperBound_);\n            lower = std::max(lowerTmp - shift, adjustedLowerBound_);\n            break;\n        }\n\n        default:\n            QL_FAIL(\"Unknown strategy (\" << settings_.strategy_ << \")\");\n        }\n\n        // compute the relevant integral\n\n        Real result = 0.0;\n        Real tmpBound;\n        if (upper > lower) {\n            tmpBound = std::min(upper, swapRateValue_);\n            if (tmpBound > lower) {\n                result += integrator_->operator()(\n                    std::bind1st(std::mem_fun(&LinearTsrPricer::integrand),\n                                 this),\n                    lower, tmpBound);\n            }\n            tmpBound = std::max(lower, swapRateValue_);\n            if (upper > tmpBound) {\n                result += integrator_->operator()(\n                    std::bind1st(std::mem_fun(&LinearTsrPricer::integrand),\n                                 this),\n                    tmpBound, upper);\n            }\n            result *= (optionType == Option::Call ? 1.0 : -1.0);\n        }\n\n        result += singularTerms(optionType, strike);\n\n        return annuity_ * result * couponDiscountRatio_ *\n               coupon_->accrualPeriod();\n    }\n\n    Real LinearTsrPricer::meanReversion() const { return meanReversion_->value(); }\n\n    Rate LinearTsrPricer::swapletRate() const {\n        return swapletPrice() /\n               (coupon_->accrualPeriod() *\n                discountCurve_->discount(paymentDate_) * couponDiscountRatio_);\n    }\n\n    Real LinearTsrPricer::capletPrice(Rate effectiveCap) const {\n        // caplet is equivalent to call option on fixing\n        if (fixingDate_ <= today_) {\n            // the fixing is determined\n            const Rate Rs = std::max(\n                coupon_->swapIndex()->fixing(fixingDate_) - effectiveCap, 0.);\n            Rate price =\n                (gearing_ * Rs) *\n                (coupon_->accrualPeriod() *\n                 discountCurve_->discount(paymentDate_) * couponDiscountRatio_);\n            return price;\n        } else {\n            Real capletPrice = optionletPrice(Option::Call, effectiveCap);\n            return gearing_ * capletPrice;\n        }\n    }\n\n    Rate LinearTsrPricer::capletRate(Rate effectiveCap) const {\n        return capletPrice(effectiveCap) /\n               (coupon_->accrualPeriod() *\n                discountCurve_->discount(paymentDate_) * couponDiscountRatio_);\n    }\n\n    Real LinearTsrPricer::floorletPrice(Rate effectiveFloor) const {\n        // floorlet is equivalent to put option on fixing\n        if (fixingDate_ <= today_) {\n            // the fixing is determined\n            const Rate Rs = std::max(\n                effectiveFloor - coupon_->swapIndex()->fixing(fixingDate_), 0.);\n            Rate price =\n                (gearing_ * Rs) *\n                (coupon_->accrualPeriod() *\n                 discountCurve_->discount(paymentDate_) * couponDiscountRatio_);\n            return price;\n        } else {\n            Real floorletPrice = optionletPrice(Option::Put, effectiveFloor);\n            return gearing_ * floorletPrice;\n        }\n    }\n\n    Rate LinearTsrPricer::floorletRate(Rate effectiveFloor) const {\n        return floorletPrice(effectiveFloor) /\n               (coupon_->accrualPeriod() *\n                discountCurve_->discount(paymentDate_) * couponDiscountRatio_);\n    }\n\n    Real LinearTsrPricer::swapletPrice() const {\n        if (fixingDate_ <= today_) {\n            // the fixing is determined\n            const Rate Rs = coupon_->swapIndex()->fixing(fixingDate_);\n            Rate price =\n                (gearing_ * Rs + spread_) *\n                (coupon_->accrualPeriod() *\n                 discountCurve_->discount(paymentDate_) * couponDiscountRatio_);\n            return price;\n        } else {\n            Real atmCapletPrice = optionletPrice(Option::Call, swapRateValue_);\n            Real atmFloorletPrice = optionletPrice(Option::Put, swapRateValue_);\n            return gearing_ * (coupon_->accrualPeriod() *\n                                   discountCurve_->discount(paymentDate_) *\n                                   swapRateValue_ * couponDiscountRatio_ +\n                               atmCapletPrice - atmFloorletPrice) +\n                   spreadLegValue_;\n        }\n    }\n}\n", "meta": {"hexsha": "c8678bda7ba0c76307cbdc3507ee421ceeb90a1d", "size": 16390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/cashflows/lineartsrpricer.cpp", "max_stars_repo_name": "sfondi/QuantLib", "max_stars_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-19T11:17:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-19T11:17:48.000Z", "max_issues_repo_path": "ql/cashflows/lineartsrpricer.cpp", "max_issues_repo_name": "sfondi/QuantLib", "max_issues_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T18:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-17T18:49:22.000Z", "max_forks_repo_path": "ql/cashflows/lineartsrpricer.cpp", "max_forks_repo_name": "sfondi/QuantLib", "max_forks_repo_head_hexsha": "8a2449d2fb470a7d47a55d3e99c5dace749709c9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5647058824, "max_line_length": 94, "alphanum_fraction": 0.553752288, "num_tokens": 3635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.4408669138791905}}
{"text": "/*\n        Olalekan Ogunmolu.\n        June 01, 2017\n\n        See: A Model for Registration of 3D shapes,\n             Paul Besl and Neil D. McKay\n\n             Eqs 23 - 27\n*/\n\n#include \"ros/ros.h\"\n#include <ros/spinner.h>\n#include \"std_msgs/String.h\"\n#include \"tf_conversions/tf_eigen.h\"\n#include <tf/transform_broadcaster.h>\n#include <tf/transform_datatypes.h>  //for bt Quaternion\n#include <geometry_msgs/Transform.h>\n\n#include <mutex>\n#include <vector>\n#include <thread>\n#include <typeinfo>\n\n#include <vicon_bridge/Markers.h>\n#include <geometry_msgs/Point.h>\n\n#include <Eigen/Eigenvalues>\n// for sender to RIO\n#include <ensenso/boost_sender.h>\n\nusing namespace Eigen;\n#define OUT(__o__) std::cout<< __o__ << std::endl;\n\n//used to retrieve value from the ros param server\ndouble get(\n    const ros::NodeHandle& n,\n    const std::string& name) {\n    double value;\n    n.getParam(name, value);\n    return value;\n}\n\nclass Receiver\n{\nprivate:\n    int count, num_points; //iterator and number of markers on object\n    std::vector<geometry_msgs::Point> headMarkersVector,\n                                    firstHeadMarkersVector;\n    std::vector<Vector3d> face_vec, first_face_vec;\n    // identity matrix involved in Q matrix\n    Matrix3d I3;\n\n    // covariance matrix\n    Matrix<double, 3, 3> sigma_px, temp, rotation_matrix;\n    Matrix<double, 3, 3> A_Mat;\n\n    // Form Q from which we compute the rotation quaternion\n    Matrix4d Q;\n    // Delta\n    Vector3d Delta;\n    // will contain rotationand translation of the head\n    geometry_msgs::Pose pose_info;\n\n    ros::NodeHandle nm_;\n    std::mutex mutex;\n    bool updatePose, running, print_;\n    ros::AsyncSpinner spinner;\n    unsigned long const hardware_threads;\n\n    // pose vector\n    ros::Subscriber sub_markers;\n    ros::Publisher pose_pub; //publisher for translation and euler angles\n\n    std::thread rotoTransThread;\n    double roll, pitch, yaw;\n    Vector3d mu_p, mu_x;  // average of points\n    geometry_msgs::Point translation_vec_optim; // optimal translation vector\n    double x, y, z;\n    double q1, q2, q3, q4;\n\n    // sender objects \n    boost::asio::io_service io_service;\n    const std::string multicast_address;\n\npublic:\n    Receiver(const bool& print)\n    :  hardware_threads(std::thread::hardware_concurrency()),\n       spinner(2), count(0), num_points(4), updatePose(false), print_(print),\n       multicast_address(\"235.255.0.1\")\n    {\n       I3.setIdentity(3, 3);\n    }\n\n    ~Receiver()\n    {\n        // rotoTransThread.detach();\n    }\n\n    Receiver(Receiver const&) =delete;\n    Receiver& operator=(Receiver const&) = delete;\n\n    void run()\n    {\n      spawn();\n      unspawn();\n    }\nprivate:\n    void spawn()\n    {\n        if(spinner.canStart())\n            spinner.start();\n        running = true;\n        pose_pub = nm_.advertise<geometry_msgs::Pose>(\"/mannequine_head/pose\", 1000);\n\n        sub_markers = nm_.subscribe(\"/vicon/markers\", 10, &Receiver::callback, this);\n        while(!updatePose) {\n            if(!ros::ok()) {\n              return;\n            }\n            std::this_thread::sleep_for(std::chrono::milliseconds(1));\n        }\n        // spawn the threads\n        rotoTransThread = std::thread(&Receiver::processRotoTrans, this);\n        if(rotoTransThread.joinable())\n            rotoTransThread.join();\n    }\n\n    void unspawn()\n    {\n        spinner.stop();\n        rotoTransThread.detach();\n        running = false;\n    }\n\n    void callback(const vicon_bridge::MarkersConstPtr& markers_msg)\n    {\n        // solve all vicon markers here\n        std::vector<geometry_msgs::Point> headMarkersVector;\n        headMarkersVector.resize(num_points);\n        for(auto i=0; i < num_points; ++i){\n            headMarkersVector[i] = markers_msg -> markers[i].translation;   // fore\n        }\n\n        std::lock_guard<std::mutex> lock(mutex);\n        this->headMarkersVector = headMarkersVector;\n        updatePose          = true;\n        ++count;\n    }\n\n    void remove_mean(std::vector<geometry_msgs::Point> && vec, Vector3d&& mu)    {\n        double mu_x = 0, mu_y = 0, mu_z = 0;\n        // std::cout << \"mu_x: \" << mu_x << \" mu_y: \" << mu_y << \" mu_z: \" << mu_z << std::endl;\n        for(auto i = 0; i < num_points; ++i)        {\n            mu_x += vec[i].x;\n            mu_y += vec[i].y;\n            mu_z += vec[i].z;\n        }\n\n        mu_x /= num_points;\n        mu_y /= num_points;\n        mu_z /= num_points;\n\n        mu << mu_x, mu_y, mu_z;\n\n        for(auto i = 0; i < num_points; ++i)        {\n            vec[i].x -= mu_x;\n            vec[i].y -= mu_y;\n            vec[i].z -= mu_z;\n            // ROS_INFO(\"vec[%d].z: %.3f\", i, headMarkersVector[i].z);\n        }\n    }\n\n    void point_to_eigen(std::vector<geometry_msgs::Point>&& pt, std::vector<Vector3d>&& face_vec)    {\n        for(auto i=0; i < num_points; ++i){\n            face_vec[i] << pt[i].x, pt[i].y, pt[i].z;\n        }\n    }\n\n\n    // this closely follows pg 243 of the ICP paper by Besl and McKay\n    void processRotoTrans()    {\n        std::vector<geometry_msgs::Point> headMarkersVector;\n        headMarkersVector.resize(num_points);\n        firstHeadMarkersVector.resize(num_points);\n        first_face_vec.resize(num_points);\n        bool use_hard_coded = get(nm_, \"/vicon_icp/Utils/use_hard_coded\");\n\n        if(use_hard_coded){            \n            // seems better we hardcode these values in a yaml file for now\n            firstHeadMarkersVector[0].x = get(nm_, \"/vicon_icp/BasePose/Marker_Fore/x\");\n            firstHeadMarkersVector[0].y = get(nm_, \"/vicon_icp/BasePose/Marker_Fore/y\");\n            firstHeadMarkersVector[0].z = get(nm_, \"/vicon_icp/BasePose/Marker_Fore/z\");\n\n            firstHeadMarkersVector[1].x = get(nm_, \"/vicon_icp/BasePose/Marker_Left/x\");\n            firstHeadMarkersVector[1].y = get(nm_, \"/vicon_icp/BasePose/Marker_Left/y\");\n            firstHeadMarkersVector[1].z = get(nm_, \"/vicon_icp/BasePose/Marker_Left/z\");\n\n            firstHeadMarkersVector[2].x = get(nm_, \"/vicon_icp/BasePose/Marker_Right/x\");\n            firstHeadMarkersVector[2].y = get(nm_, \"/vicon_icp/BasePose/Marker_Right/y\");\n            firstHeadMarkersVector[2].z = get(nm_, \"/vicon_icp/BasePose/Marker_Right/z\");\n\n            firstHeadMarkersVector[3].x = get(nm_, \"/vicon_icp/BasePose/Marker_Chin/x\");\n            firstHeadMarkersVector[3].y = get(nm_, \"/vicon_icp/BasePose/Marker_Chin/y\");\n            firstHeadMarkersVector[3].z = get(nm_, \"/vicon_icp/BasePose/Marker_Chin/z\");\n        }\n        else{\n            if(count==7){\n                firstHeadMarkersVector = this->headMarkersVector;\n            }\n        }\n\n        this->mu_p.resize(3); \n        this->mu_x.resize(3);\n        remove_mean(std::move(firstHeadMarkersVector), std::move(this->mu_x));  // mu_x is the model point set\n        //convert from geometry points to eigen\n        point_to_eigen(std::move(firstHeadMarkersVector), std::move(first_face_vec));\n\n        for(; running && ros::ok() ;)\n        {    \n       \n            if(updatePose)\n            {\n\n                // ROS_INFO_STREAM(\"model point set: \" << this->mu_x(0) << \" | \" <<  this->mu_x(1) << \" | \" << this->mu_x(2));\n                // ROS_INFO_STREAM(\"measured point set: \" << this->mu_p(0) << \" | \" <<  this->mu_p(1) << \" | \" << this->mu_p(2));\n                {\n                    std::lock_guard<std::mutex> lock(mutex);\n                    headMarkersVector = this->headMarkersVector;\n                    updatePose = false;                    \n                }\n\n                //compute center of mass of model and measured point set\n                remove_mean(std::move(headMarkersVector), std::move(this->mu_p));  // mu_p is the measured point set\n                //convert from geometry points to eigen\n                face_vec.resize(num_points);\n                point_to_eigen(std::move(headMarkersVector), std::move(face_vec));\n\n                // for(auto elem: face_vec)\n                //     ROS_INFO_STREAM(\"face_vec: \" << elem.transpose());\n                // for(auto elem: first_face_vec)\n                //     ROS_INFO_STREAM(\"first_face_vec: \" << elem.transpose());\n                //compute the cross covariance matrix of the points sets P and X\n                sigma_px.resize(3, 3); // sigma_px will be 3x3 after the multiplication below\n\n                sigma_px =  first_face_vec[0] * face_vec[0].transpose() +\n                            first_face_vec[1] * face_vec[1].transpose() +\n                            first_face_vec[2] * face_vec[2].transpose() +\n                            first_face_vec[3] * face_vec[3].transpose() ;\n                sigma_px /= num_points;\n                // ROS_INFO_STREAM(\"\\nsigma_px: \\n\" << sigma_px);\n                \n                // A will be 3x3 skew symmetric\n                A_Mat.resize(3, 3);\n                A_Mat = sigma_px - sigma_px.transpose(); \n                // ROS_INFO_STREAM(\"\\nA_Mat: \\n\" << A_Mat);\n\n                //collect cyclic components of skew symmetric matrix\n                Delta << A_Mat(1,2), A_Mat(2, 0), A_Mat(0, 1); // will be of size 3x1\n                // ROS_INFO_STREAM(\"\\nDelta: \\n\" << Delta.transpose());\n\n                temp.resize(3, 3);  // will be 3x3\n                temp = sigma_px + sigma_px.transpose() - (sigma_px.trace() * I3);\n                // ROS_INFO_STREAM(\"\\ntemp: \\n\" << temp);\n\n                // Form the symmetric 4x4 Q matrix\n                Q(0, 0) =  sigma_px.trace();                  Q.block<1, 3>(0, 1) = Delta.transpose().eval(); //top row, last three entries\n                Q.block<3, 1>(1, 0) = Delta;                  Q.bottomRightCorner<3, 3>() = temp;\n                // ROS_INFO_STREAM(\"\\nQ: \\n\" << Q);\n\n                // we now find the maximum eigen value of the matrix Q\n                EigenSolver<Matrix4d> eig(Q);\n\n                // Note that eigVal and eigVec are std::complex types. To access their\n                // real or imaginary parts, call real or imag\n                EigenSolver< Matrix4d >::EigenvalueType eigVals = eig.eigenvalues();\n                EigenSolver< Matrix4d >::EigenvectorsType eigVecs = eig.eigenvectors();\n\n                // ROS_INFO_STREAM(\"eigVals: \" << eigVals[0].real() << \", \" << eigVals[1].real() << \", \" << eigVals[2].real() << \", \" << eigVals[3].real());\n                findQuaternion(std::move(eigVals), std::move(eigVecs));\n            }\n        }\n    }\n\n    inline void rad2deg(double&& rad) {\n        rad = (rad * 180.0)/M_PI;\n    }\n\n    void findQuaternion(EigenSolver< Matrix4d >::EigenvalueType&& eigVals, EigenSolver< Matrix4d >::EigenvectorsType && eigVecs)\n    {\n        //create a look-up table of eig vectors and values\n        std::vector<double> valueVectors {eigVals[0].real(), eigVals[1].real(), eigVals[2].real(), eigVals[3].real()};\n\n        auto max = valueVectors[0];\n        int magicIdx = 0;\n        for(int i = 0; i < valueVectors.size(); ++i)        {\n            if(valueVectors[i] > max) {\n              max = valueVectors[i];\n              magicIdx = i;\n            }\n        }\n        // find the eigen vector with the largest eigen value, This would be the optimal rotation quaternion\n        auto optimalEigVec = eigVecs.col(magicIdx);\n        // ROS_INFO_STREAM(\"\\neigVec: \\n\" << eigVecs);\n        // ROS_INFO(\"optimEigVec: %.4f, %.4f, %.4f, %.4f \", optimalEigVec[0].real(), optimalEigVec[1].real(), optimalEigVec[2].real(), optimalEigVec[3].real());\n        // Form optimal rotation quaternion components\n        double q0 = optimalEigVec[0].real();\n        double q1 = optimalEigVec[1].real();\n        double q2 = optimalEigVec[2].real();\n        double q3 = optimalEigVec[3].real();\n\n        // tf::Quaternion quart(q0, q1, q2, q3);\n        // tf::Matrix3x3 Rot(quart);\n        // Rot.getRPY(roll, pitch, yaw);\n        // tf::matrixTFToEigen (Rot, rotation_matrix);\n\n        // calculate rotation matrix\n        rotation_matrix.resize(3, 3);\n        rotation_matrix(0, 0) = std::pow(q0, 2) + std::pow(q1, 2) - std::pow(q2, 2) - std::pow(q3, 2);\n        rotation_matrix(0, 1) = 2 * (q1*q2 - q0*q3);\n        rotation_matrix(0, 2) = 2 * (q1*q3 + q0*q2);\n        rotation_matrix(1, 0) = 2 * (q1*q2 + q0*q3);\n        rotation_matrix(1, 1) = std::pow(q0, 2) + std::pow(q2, 2) - std::pow(q1, 2) - std::pow(q3, 2);\n        rotation_matrix(1, 2) = 2 * (q2*q3 - q0*q1);\n        rotation_matrix(2, 0) = 2 * (q1*q3 - q0*q2);\n        rotation_matrix(2, 1) = 2 * (q2*q3 + q0*q1);\n        rotation_matrix(2, 2) = std::pow(q0, 2) + std::pow(q3, 2) - std::pow(q1, 2) - std::pow(q2, 2);\n\n        // from https://eigen.tuxfamily.org/dox/group__Geometry__Module.html#gac3d90b12b21e1aaa2a9de9b0e45e6b7c\n        // in Vector3f ea = mat.eulerAngles(2, 0, 2), for instance\n        // \"2\" represents the z axis and \"0\" the x axis, etc\n        // This corresponds to the right-multiply conventions (with right hand side frames).\n        // The returned angles are in the ranges [0:pi]x[-pi:pi]x[-pi:pi].\n        Eigen::Vector3d rpy = rotation_matrix.eulerAngles(0, 1, 2);\n        roll    = rpy(0);   // roll is about axis x\n        pitch   = rpy(1);   // pitch is about axis z\n        yaw     = rpy(1);   // yaw about axis y\n\n        // see this: http://www.staff.city.ac.uk/~sbbh653/publications/euler.pdf\n        // theta =rot about x== roll\n        // psi = rot about y == pitch\n        // phi = rot about z == yaw\n        // double roll2, pitch2, yaw2;\n        // if (rotation_matrix(2,0) != 1.0 || rotation_matrix(2,0) != -1.0){\n        //     roll = -std::asin( rotation_matrix(2,0) );\n        //     pitch = std::atan2( rotation_matrix(2,1)/std::cos(roll), rotation_matrix(2,2)/std::cos(roll) );\n        //     yaw   = std::atan2( rotation_matrix(1,0)/std::cos(roll), rotation_matrix(0,0)/std::cos(roll) );\n\n        //     roll2  = M_PI - roll;\n        //     pitch2 = std::atan2( rotation_matrix(2,1)/std::cos(roll2), rotation_matrix(2,2)/std::cos(roll2) );\n        //     yaw2   = std::atan2( rotation_matrix(1,0)/std::cos(roll2), rotation_matrix(0,0)/std::cos(roll2) );\n        // }\n        // else{\n        //     yaw = 0;\n        //     if (rotation_matrix(2,0) == -1.0){                \n        //         roll = M_PI/2.0;\n        //         pitch = yaw + std::atan2(rotation_matrix(0,1), rotation_matrix(0,2));\n        //     }\n        //     else{\n        //         roll = -M_PI/2.0;\n        //         pitch = -yaw + std::atan2(-rotation_matrix(0,1), -rotation_matrix(0,2));\n        //     }\n        // }\n        // convert rads to degrees\n        rad2deg(std::move(roll));\n        rad2deg(std::move(pitch));\n        rad2deg(std::move(yaw));\n        // ROS_INFO(\"[(roll, roll2), (pitch, pitch2): , (yaw, yaw2)]: [(%.4f, %.4f), (%.4f, %.4f), (%.4f, %.4f)]\", roll, roll2, pitch,pitch2, yaw, yaw2);\n\n        Vector3d optimal_trans = (this->mu_p - /*rotation_matrix **/ this->mu_x);\n        pose_info.position.x = optimal_trans(0); \n        pose_info.position.y = optimal_trans(1);\n        pose_info.position.z = this->mu_p(2)-942; \n        // ROS_INFO_STREAM(\"optimal trans check: \" << this->mu_x - rotation_matrix * this->mu_p);\n\n        pose_info.orientation.x = roll;\n        pose_info.orientation.y = pitch;\n        pose_info.orientation.z = yaw;\n        pose_info.orientation.w = 1;\n\n        // publish the head pose\n        pose_pub.publish(pose_info);\n        if(print_){            \n            ROS_INFO(\"z: %.3f | roll: %.3f | pitch: %.3f | yaw: %.3f \\n\", pose_info.position.z, \\\n                                                            pose_info.orientation.x, pose_info.orientation.y, pose_info.orientation.z);\n        }\n        ros::Rate looper(30);\n        looper.sleep();\n\n        // ROS_INFO_STREAM(\"\\nrotation matrix\\n\" << rotation_matrix);\n\n        // define tf matrix to hold xalculated eigen matrix\n        // if(std::fabs(rotation_matrix(0,0)) < 0.001 & std::fabs(rotation_matrix(1, 0)) < .001){\n        //     //singularity\n        //     roll  = 0 ;\n        //     pitch = std::atan2(-rotation_matrix(2,0), rotation_matrix(0,0));\n        //     yaw   = std::atan2(-rotation_matrix(1,2), rotation_matrix(1,1));\n        // }\n        // else{\n        //     roll = std::atan2(rotation_matrix(1,0), rotation_matrix(0,0));\n        //     pitch = std::atan2(-rotation_matrix(2,0), \n        //                         std::cos(roll) * rotation_matrix(0,0) + std::sin(roll) * rotation_matrix(1,0));\n        //     yaw = std::atan2(std::sin(roll) * rotation_matrix(0,2) - std::cos(roll) * rotation_matrix(1,2), \n        //                     std::cos(roll)*rotation_matrix(1,1) - std::sin(roll)*rotation_matrix(0,1));            \n        // }        \n\n        // form quaternion from euler angles\n        // tf::Quaternion quat = tf::createQuaternionFromRPY(roll, pitch, yaw);\n    }\n};\n\nint main(int argc, char** argv)\n{\n    ros::init(argc, argv, \"vicon_icp_node\");\n\n    if(!ros::ok())   \n      return EXIT_SUCCESS;\n\n    ROS_INFO_STREAM(\"Started node \" << ros::this_node::getName().c_str());\n\n    bool print;\n    if(!ros::param::get(\"/vicon_icp/Utils/print\", print))\n        ROS_DEBUG(\"could not retrieve print param value from ros parameter server\");\n\n    Receiver rcvr(print);\n    rcvr.run();\n\n    ros::shutdown();\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "d0e5221075723843c3b596586c7a7b54f4f37acb", "size": 17208, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vicon_icp/src/vicon_icp.cpp", "max_stars_repo_name": "lakehanne/RAL2017", "max_stars_repo_head_hexsha": "49f9eddc5a1120b4a116f101d49a74af90462f4a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-07-03T15:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T14:02:56.000Z", "max_issues_repo_path": "vicon_icp/src/vicon_icp.cpp", "max_issues_repo_name": "lakehanne/soft-neuro-adapt", "max_issues_repo_head_hexsha": "49f9eddc5a1120b4a116f101d49a74af90462f4a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vicon_icp/src/vicon_icp.cpp", "max_forks_repo_name": "lakehanne/soft-neuro-adapt", "max_forks_repo_head_hexsha": "49f9eddc5a1120b4a116f101d49a74af90462f4a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0186046512, "max_line_length": 160, "alphanum_fraction": 0.5609600186, "num_tokens": 4745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6187804478040617, "lm_q1q2_score": 0.4407153574631217}}
{"text": "/* Copyright (C) 2017 IBM Corp.\n * Licensed under the Apache License, Version 2.0 (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific\n * language governing permissions and limitations under the License.\n */\n/* makeRandomBP.cpp - generate random read-once BPs\n */\n#include <fstream>\n#include <iostream>\n#include <string>\n\n#include <NTL/ZZ.h>\n#include <NTL/matrix.h>\n\n#include \"../utils/tools.h\"\n#include \"../utils/argmap.h\"\n\nNTL_CLIENT\n\n/** Usage example:\n *\n * % ./makeRandomBP_x name=myProgram dim=5 L=4 sig=4\n *\n * This will generate a length-5 BP over 4-symbol alphabet\n * with 5x5 transition matrices\n **/\nint main(int argc, char *argv[])\n{\n    extern bool bGGH15threading;\n\n    ArgMapping amap;\n\n    std::string dirName = \"test\";\n     amap.arg(\"testDir\", dirName, \"where to write the obfuscated program\");\n\n    std::string name = \"P\";\n    amap.arg(\"name\", name, \"Name of BP\");\n    long dim=2;\n    amap.arg(\"dim\", dim, \"dimension of transition matrices\");\n    long L=3;\n    amap.arg(\"L\", L, \"langth of BP\");\n    long sig= 2;\n    amap.arg(\"sig\", sig, \"alphabet size\");\n\n\n    amap.parse(argc, argv); // parses and overrides initail values\n\n    bGGH15threading = 0; //off\n\n    // For each step i=0,1,...,L-1 and each symbol sigma=0,1,...,nSym-1,\n    // choose a zero-matrix with probability 1/L, random 0/1 matrix otherwise\n\n    Mat< Mat<long> > trans(INIT_SIZE, L, sig);\n    for (long i=0; i<L; i++) for (long iSig=0; iSig<sig; iSig++) {\n        Mat<long>& M = trans[i][iSig];\n        M.SetDims(dim,dim);\n        if (NTL::RandomBnd(L)==0) clear(M);\n        else\n\t  for (long row=0; row<dim; row++) for (long col=0; col<dim; col++) {\n              M[row][col] = NTL::RandomBnd(2);\n\t  }\n      }\n\n    // Write the transitions matrices to file\n\n    std::string filename = dirName + \"/\" + name + \"_dim\" + ToString(dim)\n                                + \"_sig\" + ToString(sig)\n                                + \"_L\" + ToString(L)\n                                + \".txt\";\n\n    std::fstream fs;\n    fs.open(filename.c_str(), std::ios::out); // E.g., \"BPs/P_dim2_sig2_L3.txt\"\n    if (!fs.is_open())\n    {\n      std::cout << \"Cannot open input file \"<< filename << endl;\n      exit(0);\n    }\n    fs << trans << endl;\n    fs.close();\n\n#ifdef CodeBlocks\n    cin.get();\n#endif\n}\n", "meta": {"hexsha": "1850f629d90300a1bd401208dbbb2689fb3dc0c3", "size": 2650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "programs/makeRandomBP.cpp", "max_stars_repo_name": "shaih/BPobfus", "max_stars_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-25T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T03:19:43.000Z", "max_issues_repo_path": "programs/makeRandomBP.cpp", "max_issues_repo_name": "shaih/BPobfus", "max_issues_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "programs/makeRandomBP.cpp", "max_forks_repo_name": "shaih/BPobfus", "max_forks_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-12-23T04:03:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-12T07:42:29.000Z", "avg_line_length": 29.1208791209, "max_line_length": 79, "alphanum_fraction": 0.6056603774, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4407153474489862}}
{"text": "#include <cstdlib>\n#include <iostream>\n#include <set>\n#include <climits>\n#include <algorithm>\n\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/graph/graphviz.hpp>\n\n#include <vector>\n#include <utility>\n#include <queue>\n#include <ctime>\n\n#include \"naive.hh\"\n\n//using namespace std;\n\n//Treewidth is always positive, so we can use this in place of -Inf\nconst int NO_WIDTH = -1;\n\n\n\nint naiveTW(std::set<Vertex> S, Graph G)\n{\n    if (S.empty())\n    {\n        return NO_WIDTH;\n    }\n    else\n    {\n        int minSoFar = INT_MAX;\n        \n        for (auto iter = S.begin(); iter != S.end(); iter++)\n        {\n            Vertex v = *iter;\n            std::set<Vertex> S2(S);\n            \n            S2.erase(v);\n            \n            int subTW = naiveTW(S2, G);\n            int qVal = sizeQ(S2, v, G);\n            \n            \n            \n            //std::cout << \"S2 is \" << showSet(S2) << std::endl;\n            //std::cout << \"subTW \" << subTW << std::endl;\n            //std::cout << \"qVal \" << qVal << std::endl;\n            \n            minSoFar = std::min(minSoFar, std::max(subTW, qVal ) );\n        }\n        return minSoFar;\n        \n    }\n}\n\n\n\nint naiveMain()\n{\n    \n    Graph g;\n    boost::mt19937 rng(time (NULL));\n    boost::generate_random_graph(g, 8, 20, rng, true, true);\n    \n    boost::write_graphviz(std::cout, g);\n    \n    \n    auto iterInfo = boost::vertices(g);\n    std::set<Vertex> S;\n    for (auto iter = iterInfo.first; iter != iterInfo.second; iter++ )\n    {\n        S.insert(*iter);\n    }\n    \n    \n    std::cout << \"Treewidth: \" << naiveTW(S, g) << std::endl;\n\n    \n    return EXIT_SUCCESS;\n    \n}\n", "meta": {"hexsha": "644dd73dcae14d34a9e5eac7f6e1658f992e7884", "size": 1764, "ext": "cc", "lang": "C++", "max_stars_repo_path": "naive.cc", "max_stars_repo_name": "JoeyEremondi/treewidth-memoization", "max_stars_repo_head_hexsha": "5cd6be9e05bba189d14409f28c37805948ef11b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-07-25T15:09:11.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-25T15:09:11.000Z", "max_issues_repo_path": "naive.cc", "max_issues_repo_name": "JoeyEremondi/treewidth-memoization", "max_issues_repo_head_hexsha": "5cd6be9e05bba189d14409f28c37805948ef11b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-09-19T00:44:24.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-21T16:47:12.000Z", "max_forks_repo_path": "naive.cc", "max_forks_repo_name": "JoeyEremondi/treewidth-memoization", "max_forks_repo_head_hexsha": "5cd6be9e05bba189d14409f28c37805948ef11b3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.511627907, "max_line_length": 70, "alphanum_fraction": 0.5283446712, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6187804407739559, "lm_q1q2_score": 0.4407153448967729}}
{"text": "/*\n   ____    _ __           ____               __    ____\n  / __/___(_) /  ___ ____/ __ \\__ _____ ___ / /_  /  _/__  ____\n _\\ \\/ __/ / _ \\/ -_) __/ /_/ / // / -_|_-</ __/ _/ // _ \\/ __/\n/___/\\__/_/_.__/\\__/_/  \\___\\_\\_,_/\\__/___/\\__/ /___/_//_/\\__(_)\n\nCopyright 2012 SciberQuest Inc.\n*/\n#include \"vtkSQFTLE.h\"\n\n#include \"vtkCell.h\"\n#include \"vtkCellData.h\"\n#include \"vtkDataSet.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkGenericCell.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkTensor.h\"\n#include \"vtkPVXMLElement.h\"\n#include \"XMLUtils.h\"\n#include \"vtkSQLog.h\"\n\n#include <cmath>\n#include <string>\nusing std::string;\n#include <algorithm>\nusing std::max;\n\n#include \"SQEigenWarningSupression.h\"\n#include <Eigen/Eigenvalues>\nusing namespace Eigen;\n\n// ****************************************************************************\nstatic\nvoid ComputeVectorGradient(\n      vtkAlgorithm *alg,\n      double prog0,\n      double prog1,\n      vtkDataSet *input,\n      vtkIdType nCells,\n      vtkDataArray *V,\n      vtkDoubleArray *gradV)\n{\n  const vtkIdType nProgSteps=10;\n  const vtkIdType progInt=max(nCells/nProgSteps,vtkIdType(1));\n  const double progInc=(prog1-prog0)/nProgSteps;\n  double prog=prog0;\n\n  gradV->SetNumberOfComponents(9);\n  gradV->SetNumberOfTuples(nCells);\n  string name=\"grad-\";\n  name+=V->GetName();\n  gradV->SetName(name.c_str());\n  double *pGradV=gradV->GetPointer(0);\n\n  vtkDoubleArray *cellV=vtkDoubleArray::New();\n  cellV->SetNumberOfComponents(3);\n  cellV->Allocate(3*VTK_CELL_SIZE);\n\n  vtkGenericCell *cell=vtkGenericCell::New();\n\n  // for each cell\n  for (vtkIdType cellId=0; cellId<nCells; ++cellId)\n    {\n    if (!(cellId%progInt))\n      {\n      alg->UpdateProgress(prog);\n      prog+=progInc;\n      }\n\n    input->GetCell(cellId,cell);\n\n    double coords[3];\n    cell->GetParametricCenter(coords);\n\n    V->GetTuples(cell->PointIds,cellV);\n\n    double *pCellV=cellV->GetPointer(0);\n\n    double grad[9];\n    cell->Derivatives(0,coords,pCellV,3,grad);\n\n    for (int i=0; i<9; ++i)\n      {\n      pGradV[i]=grad[i];\n      }\n    pGradV+=9;\n    }\n\n  cell->Delete();\n  cellV->Delete();\n}\n\n// ****************************************************************************\nstatic\nvoid ComputeFTLE(\n      vtkAlgorithm *alg,\n      double prog0,\n      double prog1,\n      vtkIdType nCells,\n      vtkDoubleArray *gradV,\n      double timeInterval,\n      vtkDoubleArray *ftleV)\n{\n  const vtkIdType nProgSteps=10;\n  const vtkIdType progInt=max(nCells/nProgSteps,vtkIdType(1));\n  const double progInc=(prog1-prog0)/nProgSteps;\n  double prog=prog0;\n\n  double *pGradV=gradV->GetPointer(0);\n\n  ftleV->SetNumberOfComponents(1);\n  ftleV->SetNumberOfTuples(nCells);\n  double *pFtleV=ftleV->GetPointer(0);\n\n  // for each cell\n  for (vtkIdType cellId=0; cellId<nCells; ++cellId)\n    {\n    if (!(cellId%progInt))\n      {\n      alg->UpdateProgress(prog);\n      prog+=progInc;\n      }\n\n    Matrix<double,3,3> J;\n    J <<\n      pGradV[0], pGradV[1], pGradV[2],\n      pGradV[3], pGradV[4], pGradV[5],\n      pGradV[6], pGradV[7], pGradV[8];\n\n    Matrix<double,3,3> JJT;\n    JJT=J*J.transpose();\n\n    // compute eigen values\n    Matrix<double,3,1> e;\n    SelfAdjointEigenSolver<Matrix<double,3,3> >solver(JJT,false);\n    e=solver.eigenvalues();\n\n    double lam;\n    lam=max(e(0,0),e(1,0));\n    lam=max(lam,e(2,0));\n    lam=max(lam,1.0);\n\n    pFtleV[0]=log(sqrt(lam))/timeInterval;\n\n    pFtleV+=1;\n    pGradV+=9;\n    }\n}\n\n//-----------------------------------------------------------------------------\nvtkStandardNewMacro(vtkSQFTLE);\n\n//-----------------------------------------------------------------------------\nvtkSQFTLE::vtkSQFTLE()\n      :\n  PassInput(0),\n  TimeInterval(1.0),\n  LogLevel(0)\n{\n  #ifdef SQTK_DEBUG\n  pCerr() << \"=====vtkSQFTLE::vtkSQFTLE\" << endl;\n  #endif\n\n  this->SetNumberOfInputPorts(1);\n  this->SetNumberOfOutputPorts(1);\n}\n\n//-----------------------------------------------------------------------------\nint vtkSQFTLE::Initialize(vtkPVXMLElement *root)\n{\n  #ifdef SQTK_DEBUG\n  pCerr() << \"=====vtkSQFTLE::Initialize\" << endl;\n  #endif\n\n  vtkPVXMLElement *elem=0;\n  elem=GetOptionalElement(root,\"vtkSQFTLE\");\n  if (elem==0)\n    {\n    return -1;\n    }\n\n  // input arrays, optional but must be set somewhwere\n  vtkPVXMLElement *nelem;\n  nelem=GetOptionalElement(elem,\"input_arrays\");\n  if (nelem)\n    {\n    ExtractValues(nelem->GetCharacterData(),this->InputArrays);\n    }\n\n  int passInput=0;\n  GetOptionalAttribute<int,1>(elem,\"pass_input\",&passInput);\n  if (passInput>0)\n    {\n    this->SetPassInput(passInput);\n    }\n\n  double timeInterval=0.0;\n  GetOptionalAttribute<double,1>(elem,\"time_interval\",&timeInterval);\n  if (timeInterval>0.0)\n    {\n    this->SetTimeInterval(timeInterval);\n    }\n\n  vtkSQLog *log=vtkSQLog::GetGlobalInstance();\n  int globalLogLevel=log->GetGlobalLevel();\n  if (this->LogLevel || globalLogLevel)\n    {\n    log->GetHeader()\n      << \"# ::vtkSQFTLE\" << \"\\n\"\n      << \"#   pass_input=\" << this->PassInput << \"\\n\"\n      << \"#   time_interval=\" << this->TimeInterval << \"\\n\"\n      << \"#   input_arrays=\";\n\n    set<string>::iterator it=this->InputArrays.begin();\n    set<string>::iterator end=this->InputArrays.end();\n    for (; it!=end; ++it)\n      {\n      log->GetHeader() << *it << \" \";\n      }\n    log->GetHeader() << \"\\n\";\n    }\n\n  return 0;\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSQFTLE::AddInputArray(const char *name)\n{\n  #ifdef SQTK_DEBUG\n  pCerr()\n    << \"=====vtkSQFTLE::AddInputArray\"\n    << \"name=\" << name << endl;\n  #endif\n\n  if (this->InputArrays.insert(name).second)\n    {\n    this->Modified();\n    }\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSQFTLE::ClearInputArrays()\n{\n  #ifdef SQTK_DEBUG\n  pCerr()\n    << \"=====vtkSQFTLE::ClearInputArrays\" << endl;\n  #endif\n\n  if (this->InputArrays.size())\n    {\n    this->InputArrays.clear();\n    this->Modified();\n    }\n}\n\n//-----------------------------------------------------------------------------\nint vtkSQFTLE::RequestData(\n      vtkInformation *vtkNotUsed(request),\n      vtkInformationVector **inInfos,\n      vtkInformationVector *outInfos)\n{\n  #ifdef SQTK_DEBUG\n  pCerr() << \"=====vtkSQFTLE::RequestData\" << endl;\n  #endif\n\n  vtkSQLog *log=vtkSQLog::GetGlobalInstance();\n  int globalLogLevel=log->GetGlobalLevel();\n  if (this->LogLevel || globalLogLevel)\n    {\n    log->StartEvent(\"vtkSQFTLE::RequestData\");\n    }\n\n  vtkInformation *inInfo = inInfos[0]->GetInformationObject(0);\n  vtkInformation *outInfo = outInfos->GetInformationObject(0);\n\n  vtkDataSet *input\n     = vtkDataSet::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT()));\n  if (!input)\n    {\n    vtkErrorMacro(\"Null input.\");\n    return 1;\n    }\n\n  vtkDataSet *output\n     = vtkDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT()));\n  if (!output)\n    {\n    vtkErrorMacro(\"Null output.\");\n    return 1;\n    }\n\n  output->CopyStructure(input);\n  if (this->PassInput)\n    {\n    output->CopyAttributes(input);\n    }\n\n  vtkIdType nCells=input->GetNumberOfCells();\n  if (nCells>0)\n    {\n    set<string>::iterator it;\n    set<string>::iterator begin=this->InputArrays.begin();\n    set<string>::iterator end=this->InputArrays.end();\n    for (it=begin; it!=end; ++it)\n      {\n      vtkDataArray *V=input->GetPointData()->GetArray((*it).c_str());\n      if (V==0)\n        {\n        vtkErrorMacro(\n          << \"Array \" << (*it).c_str()\n          << \" was requested but is not present\");\n        continue;\n        }\n\n      if (V->GetNumberOfComponents()!=3)\n        {\n        vtkErrorMacro(\n          << \"Array \" << (*it).c_str() << \" is not a vector.\");\n        continue;\n        }\n\n      // Gradient.\n      vtkDoubleArray *gradV=vtkDoubleArray::New();\n      ComputeVectorGradient(this,0.0,0.4,input,nCells,V,gradV);\n\n      // FTLE\n      string name;\n      name+=\"ftle-\";\n      name+=V->GetName();\n\n      vtkDoubleArray *ftleV=vtkDoubleArray::New();\n      ftleV->SetName(name.c_str());\n\n      ComputeFTLE(this,0.5,1.0,nCells,gradV,this->TimeInterval,ftleV);\n\n      output->GetCellData()->AddArray(ftleV);\n\n      ftleV->Delete();\n      gradV->Delete();\n      }\n    }\n\n  if (this->LogLevel || globalLogLevel)\n    {\n    log->EndEvent(\"vtkSQFTLE::RequestData\");\n    }\n\n  return 1;\n}\n\n//-----------------------------------------------------------------------------\nvoid vtkSQFTLE::PrintSelf(ostream& os, vtkIndent indent)\n{\n  this->Superclass::PrintSelf(os,indent);\n}\n\n/*\nvtk code for eigen values.\n\n  double ux=pV[0];\n  double uy=pV[1];\n  double uz=pV[2];\n  double vx=pV[3];\n  double vy=pV[4];\n  double vz=pV[5];\n  double wx=pV[6];\n  double wy=pV[7];\n  double wz=pV[8];\n\n  double JJT0[3], JJT1[3], JJT2[3];\n  double *JJT[3]={JJT0, JJT1, JJT2};\n\n  JJT[0][0] = ux*ux+vx*vx+wx*wx;\n  JJT[0][1] = ux*uy+vx*vy+wx*wy;\n  JJT[0][2] = ux*uz+vx*vz+wx*wz;\n  JJT[1][0] = JJT[0][1];\n  JJT[1][1] = uy*uy+vy*vy+uz*wz;\n  JJT[1][2] = uy*uz+vy*vz+wy*wz;\n  JJT[2][0] = JJT[0][2];\n  JJT[2][1] = JJT[1][2];\n  JJT[2][2] = uz*uz+vz*vz+wz*wz;\n*/\n", "meta": {"hexsha": "3350c0ccaf3b686092934f36420de8f6b0800ef4", "size": 9078, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Plugins/SciberQuestToolKit/vtkSQFTLE.cxx", "max_stars_repo_name": "UV-CDAT/ParaView", "max_stars_repo_head_hexsha": "095ac28404a85fd86676491b8952884805842223", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Plugins/SciberQuestToolKit/vtkSQFTLE.cxx", "max_issues_repo_name": "UV-CDAT/ParaView", "max_issues_repo_head_hexsha": "095ac28404a85fd86676491b8952884805842223", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Plugins/SciberQuestToolKit/vtkSQFTLE.cxx", "max_forks_repo_name": "UV-CDAT/ParaView", "max_forks_repo_head_hexsha": "095ac28404a85fd86676491b8952884805842223", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.518134715, "max_line_length": 79, "alphanum_fraction": 0.5682969817, "num_tokens": 2663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.44071533988970535}}
{"text": "/*\r\n *  (C) Copyright Nick Thompson 2018.\r\n *  Use, modification and distribution are subject to the\r\n *  Boost Software License, Version 1.0. (See accompanying file\r\n *  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n#ifndef BOOST_INTEGER_EXTENDED_EUCLIDEAN_HPP\r\n#define BOOST_INTEGER_EXTENDED_EUCLIDEAN_HPP\r\n#include <limits>\r\n#include <stdexcept>\r\n#include <boost/throw_exception.hpp>\r\n#include <boost/core/swap.hpp>\r\n#include <boost/core/enable_if.hpp>\r\n\r\nnamespace boost { namespace integer {\r\n\r\n// From \"The Joy of Factoring\", Algorithm 2.7, with a small optimization to remove tmps from Wikipedia.\r\n// Solves mx + ny = gcd(m,n). Returns tuple with (gcd(m,n), x, y).\r\n\r\ntemplate<class Z>\r\nstruct euclidean_result_t\r\n{\r\n    Z gcd;\r\n    Z x;\r\n    Z y;\r\n};\r\n\r\ntemplate<class Z>\r\ntypename boost::enable_if_c< std::numeric_limits< Z >::is_signed, euclidean_result_t< Z > >::type\r\nextended_euclidean(Z m, Z n)\r\n{\r\n    if (m < 1 || n < 1)\r\n    {\r\n        BOOST_THROW_EXCEPTION(std::domain_error(\"extended_euclidean: arguments must be strictly positive\"));\r\n    }\r\n\r\n    bool swapped = false;\r\n    if (m < n)\r\n    {\r\n        swapped = true;\r\n        boost::swap(m, n);\r\n    }\r\n    Z u0 = m;\r\n    Z u1 = 1;\r\n    Z u2 = 0;\r\n    Z v0 = n;\r\n    Z v1 = 0;\r\n    Z v2 = 1;\r\n    Z w0;\r\n    Z w1;\r\n    Z w2;\r\n    while(v0 > 0)\r\n    {\r\n        Z q = u0/v0;\r\n        w0 = u0 - q*v0;\r\n        w1 = u1 - q*v1;\r\n        w2 = u2 - q*v2;\r\n        u0 = v0;\r\n        u1 = v1;\r\n        u2 = v2;\r\n        v0 = w0;\r\n        v1 = w1;\r\n        v2 = w2;\r\n    }\r\n\r\n    euclidean_result_t< Z > result;\r\n    result.gcd = u0;\r\n    if (!swapped)\r\n    {\r\n        result.x = u1;\r\n        result.y = u2;\r\n    }\r\n    else\r\n    {\r\n        result.x = u2;\r\n        result.y = u1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\n}}\r\n#endif\r\n", "meta": {"hexsha": "182d813fc6e0a0a222d7b9e2c287eea7c15285a3", "size": 1813, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/integer/extended_euclidean.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "deps/boost/include/boost/integer/extended_euclidean.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "deps/boost/include/boost/integer/extended_euclidean.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 21.5833333333, "max_line_length": 109, "alphanum_fraction": 0.5482625483, "num_tokens": 539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.44071533988970524}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef CBR_CONTROL__MPC__DLTV_OCP_SOLVER_HPP_\n#define CBR_CONTROL__MPC__DLTV_OCP_SOLVER_HPP_\n\n#include <Eigen/Dense>\n\n#include <cbr_utils/utils.hpp>\n\n#include <utility>\n#include <array>\n\n#include \"cbr_control/osqp-cpp.hpp\"\n#include \"ocp_common.hpp\"\n\nnamespace cbr\n{\n\nnamespace ocp_detail\n{\ntemplate<std::size_t nx, std::size_t nu, std::size_t nPts>\nconstexpr auto DltvOcpSolverCostSparsity()  // objective\n{\n  constexpr std::size_t nz = (nx + nu) * (nPts - 1);\n  std::array<std::size_t, nz> out{};\n\n  std::array<std::size_t, nx> etaX{};\n  std::array<std::size_t, nx> etaU{};\n\n  // Generate original vectors\n  for (std::size_t i = 0; i < nx; i++) {\n    etaX[i] = i + 1;\n  }\n  for (std::size_t i = 0; i < nu; i++) {\n    etaU[i] = i + 1;\n  }\n\n  // populate LHS values\n  for (std::size_t j = 0; j < nPts - 1; j++) {\n    for (std::size_t i = 0; i < nx; i++) {\n      out[(j * nx) + i] = etaX[i];\n    }\n  }\n\n  std::size_t oft = nx * (nPts - 1);\n  // populate RHS values\n  for (std::size_t j = 0; j < nPts - 1; j++) {\n    for (std::size_t i = 0; i < nu; i++) {\n      out[oft + (j * nu) + i] = etaU[i];\n    }\n  }\n\n  return out;\n}\n\ntemplate<std::size_t nx, std::size_t nu, std::size_t nPts>\nconstexpr auto DltvOcpSolverCstrSparsity()  // constraint\n{\n  constexpr std::size_t nz = (nx + nu) * (nPts - 1);\n  std::array<std::size_t, nz> out{};\n\n  std::array<std::size_t, nx> etaX{};\n  std::array<std::size_t, nx> etaU{};\n\n  // Generate original vectors\n  for (std::size_t i = 0; i < nx; i++) {\n    etaX[i] = nx + 2;\n  }\n\n  for (std::size_t i = 0; i < nu; i++) {\n    etaU[i] = nx + 1;\n  }\n\n  // populate LHS values\n  for (std::size_t j = 0; j < nPts - 1; j++) {\n    for (std::size_t i = 0; i < nx; i++) {\n      if (j == nPts - 2) {\n        out[(j * nx) + i] = 2;\n      } else {\n        out[(j * nx) + i] = etaX[i];\n      }\n    }\n  }\n\n  std::size_t oft = nx * (nPts - 1);\n  // populate RHS values\n  for (std::size_t j = 0; j < nPts - 1; j++) {\n    for (std::size_t i = 0; i < nu; i++) {\n      out[oft + (j * nu) + i] = etaU[i];\n    }\n  }\n\n  return out;\n}\n\n}  // namespace ocp_detail\n\n/* ---------------------------------------------------------------------------------------------- */\n/*                Discrete Time Linear Time Varying Optimal Control Problem Solver                */\n/* ---------------------------------------------------------------------------------------------- */\n\nstruct DltvOcpSolverParams\n{\n  osqp::OsqpSettings osqp_settings{};\n};\n\n// return code\nenum class DltvOcpSolverCode\n{\n  no_run,\n  success,\n  failure,\n};\n\n/**\n * @brief Solve a linear optimal control problem of type\n *\n *   min_{x, u}   \\sum_{k=0}^{K-1} [(1/2) x_k' Q x_k + q' x+k  + (1/2) u_k' R u_k + r' u_k ]  +  (1/2) x_K' QT Q_K\n *\n *    s.t.        x_{k+1} = A_k x_k + B_k u_k + E_k\n *\n * The optimal control problem is defined by implementing get_xxx methods as seen below\n *\n * The variable vector is\n *\n *  [x_1, x_2, \\ldots, x_K, u_0, u_1, \\ldots, u_{K-1}]\n *\n * @tparam dltv_pb_t\n */\ntemplate<typename dltv_pb_t>\nclass DltvOcpSolver\n{\npublic:\n  // Must be defined in dtlv_pb problem\n  constexpr static std::size_t nx = dltv_pb_t::nx;\n  constexpr static std::size_t nu = dltv_pb_t::nu;\n  constexpr static std::size_t nPts = dltv_pb_t::nPts;\n\n  using problem_t = dltv_pb_t;\n\n  // Variable sizes\n  constexpr static std::size_t nX = (nPts - 1) * nx;\n  constexpr static std::size_t nU = (nPts - 1) * nu;\n  constexpr static std::size_t nZ = nX + nU;\n\n  // Constraint matrix sizes\n  constexpr static std::size_t nIneqCstr = nZ;\n  constexpr static std::size_t nEqCstr = nX;\n  constexpr static std::size_t nCstr = nIneqCstr + nEqCstr;\n\n  // QP sparsity\n  constexpr static std::array<std::size_t, nZ> costSparsity =\n    ocp_detail::DltvOcpSolverCostSparsity<nx, nu, nPts>();\n  constexpr static std::array<std::size_t, nZ> cstrSparsity =\n    ocp_detail::DltvOcpSolverCstrSparsity<nx, nu, nPts>();\n\n  // Create some useful aliases\n  using state_t = Eigen::Matrix<double, nx, 1>;\n  using input_t = Eigen::Matrix<double, nu, 1>;\n  using A_t = Eigen::Matrix<double, nx, nx>;\n  using B_t = Eigen::Matrix<double, nx, nu>;\n  using Q_t = Eigen::Matrix<double, nx, nx>;\n  using R_t = Eigen::Matrix<double, nu, nu>;\n  using state_traj_t = Eigen::Matrix<double, nx, nPts>;\n  using input_traj_t = Eigen::Matrix<double, nu, nPts>;\n  using z_t = Eigen::Matrix<double, nZ, 1>;\n\n  // Get return type of problem functions\n  using Ar_t = std::result_of_t<decltype(&dltv_pb_t::get_A)(dltv_pb_t, std::size_t)>;\n  using Br_t = std::result_of_t<decltype(&dltv_pb_t::get_B)(dltv_pb_t, std::size_t)>;\n  using Qr_t = std::result_of_t<decltype(&dltv_pb_t::get_Q)(dltv_pb_t, std::size_t)>;\n  using QTr_t = std::result_of_t<decltype(&dltv_pb_t::get_QT)(dltv_pb_t)>;\n  using Rr_t = std::result_of_t<decltype(&dltv_pb_t::get_R)(dltv_pb_t, std::size_t)>;\n\n  /* -------------------------------------------------------------------------- */\n  /*                                  Optionals                                 */\n  /* -------------------------------------------------------------------------- */\n\n  // Check existance of get_E function\n  constexpr static bool has_E_approx = std::experimental::is_detected_v<ocp_detail::has_E_discrete,\n      dltv_pb_t>;\n  constexpr static bool has_E = std::experimental::is_detected_exact_v<state_t,\n      ocp_detail::has_E_discrete, dltv_pb_t>||\n    std::experimental::is_detected_exact_v<const state_t &, ocp_detail::has_E_discrete, dltv_pb_t>;\n  using Er_t = std::experimental::detected_or_t<state_t, ocp_detail::has_E_discrete, dltv_pb_t>;\n  static_assert(\n    !(has_E_approx && !has_E),\n    \"Detected get_E function doesn't have a correct return type. \"\n    \"It must be an nx*1 Eigen::Matrix (or a const reference to one)\");\n\n  // Check existance of get_q function\n  constexpr static bool has_q_approx = std::experimental::is_detected_v<ocp_detail::has_q_discrete,\n      dltv_pb_t>;\n  constexpr static bool has_q = std::experimental::is_detected_exact_v<state_t,\n      ocp_detail::has_q_discrete, dltv_pb_t>||\n    std::experimental::is_detected_exact_v<const state_t &, ocp_detail::has_q_discrete, dltv_pb_t>;\n  using qr_t = std::experimental::detected_or_t<state_t, ocp_detail::has_q_discrete, dltv_pb_t>;\n  static_assert(\n    !(has_q_approx && !has_q),\n    \"Detected get_q function doesn't have a correct return type. \"\n    \"It must be an nx*1 Eigen::Matrix (or a const reference to one)\");\n\n  // Check existance of get_qT function\n  constexpr static bool has_qT_approx = std::experimental::is_detected_v<\n    ocp_detail::has_qT_discrete, dltv_pb_t>;\n  constexpr static bool has_qT = std::experimental::is_detected_exact_v<state_t,\n      ocp_detail::has_qT_discrete, dltv_pb_t>||\n    std::experimental::is_detected_exact_v<const state_t &, ocp_detail::has_qT_discrete, dltv_pb_t>;\n  using qTr_t = std::experimental::detected_or_t<state_t, ocp_detail::has_qT_discrete, dltv_pb_t>;\n  static_assert(\n    !(has_qT_approx && !has_qT),\n    \"Detected get_qT function doesn't have a correct return type. \"\n    \"It must be an nx*1 Eigen::Matrix (or a const reference to one)\");\n\n  // Check existance of get_r function\n  constexpr static bool has_r_approx = std::experimental::is_detected_v<ocp_detail::has_r_discrete,\n      dltv_pb_t>;\n  constexpr static bool has_r = std::experimental::is_detected_exact_v<input_t,\n      ocp_detail::has_r_discrete, dltv_pb_t>||\n    std::experimental::is_detected_exact_v<const input_t &, ocp_detail::has_r_discrete, dltv_pb_t>;\n  using rr_t = std::experimental::detected_or_t<input_t, ocp_detail::has_r_discrete, dltv_pb_t>;\n  static_assert(\n    !(has_r_approx && !has_r),\n    \"Detected get_r function doesn't have a correct return type. \"\n    \"It must be an nu*1 Eigen::Matrix (or a const reference to one)\");\n\n  // Check problem dimensions\n  static_assert(nx > 0, \"Number of states must be > 0.\");\n  static_assert(nu > 0, \"Number of inputs must be > 0.\");\n  static_assert(nPts > 1, \"Number of trajectory points must be > 1.\");\n\n  // Check return type of problem functions\n  static_assert(\n    std::is_same_v<std::decay_t<Ar_t>, A_t>,\n    \"The get_A method of the problem must return an nx*nx Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<Br_t>, B_t>,\n    \"The get_B method of the problem must return an nx*nu Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<Qr_t>, Q_t>,\n    \"The get_Q method of the problem must return an nx*nx Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<qr_t>, state_t>,\n    \"The get_q method of the problem must return an nx*1 Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<QTr_t>, Q_t>,\n    \"The get_QT method of the problem must return an nx*nx Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<qTr_t>, state_t>,\n    \"The get_qT method of the problem must return an nx*1 Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<Rr_t>, R_t>,\n    \"The get_R method of the problem must return an nu*nu Eigen::Matrix (or a reference to one).\");\n  static_assert(\n    std::is_same_v<std::decay_t<rr_t>, input_t>,\n    \"The get_r method of the problem must return an nu*1 Eigen::Matrix (or a reference to one).\");\n\npublic:\n  // define structure SOLUTION for the output of the SOLVER\n  struct Solution\n  {\n    DltvOcpSolverCode rc = DltvOcpSolverCode::no_run;\n    state_traj_t x = state_traj_t::Zero();\n    input_traj_t u = input_traj_t::Zero();\n    z_t z = z_t::Zero();\n  };\n\npublic:\n  DltvOcpSolver() = delete;\n  DltvOcpSolver(const DltvOcpSolver &) = default;\n  DltvOcpSolver(DltvOcpSolver &&) = default;\n  DltvOcpSolver & operator=(const DltvOcpSolver &) = default;\n  DltvOcpSolver & operator=(DltvOcpSolver &&) = default;\n\n  explicit DltvOcpSolver(const dltv_pb_t & pb)\n  : dltv_pb_(pb) {}\n\n  explicit DltvOcpSolver(dltv_pb_t && pb)\n  : dltv_pb_(std::move(pb)) {}\n\n  template<typename T1, typename T2>\n  DltvOcpSolver(T1 && pb, T2 && prm)\n  : dltv_pb_(std::forward<T1>(pb)),\n    prm_(std::forward<T2>(prm)) {}\n\npublic:\n  /**\n   * @brief Read problem information and build constraint matrices\n   */\n  void init()\n  {\n    osqp::OsqpInstance osqp_instance;\n\n    // Resize osqp_instance matrices\n    osqp_instance.objective_matrix.resize(nZ, nZ);\n    osqp_instance.objective_vector.resize(nZ);\n    osqp_instance.constraint_matrix.resize(nCstr, nZ);\n    osqp_instance.lower_bounds.resize(nCstr);\n    osqp_instance.upper_bounds.resize(nCstr);\n\n    // Set sparsity structure\n    const Eigen::Map<const Eigen::Matrix<std::size_t, nZ, 1>> costSparsityVec(costSparsity.data());\n    const Eigen::Map<const Eigen::Matrix<std::size_t, nZ, 1>> cstrSparsityVec(cstrSparsity.data());\n    osqp_instance.objective_matrix.reserve(costSparsityVec);\n    osqp_instance.constraint_matrix.reserve(cstrSparsityVec);\n\n    // Get inital state\n    dltv_pb_.get_x0(sol_.x.col(0));\n\n\n    /* -------------------------------------------------------------------------- */\n    /*                         Set state and input bounds                         */\n    /* -------------------------------------------------------------------------- */\n\n    for (std::size_t i = 0; i < nPts - 1; i++) {\n      // state bounds\n      dltv_pb_.get_state_lb(i + 1, osqp_instance.lower_bounds.segment<nx>(i * nx));\n      dltv_pb_.get_state_ub(i + 1, osqp_instance.upper_bounds.segment<nx>(i * nx));\n      // input bounds\n      dltv_pb_.get_input_ub(i, osqp_instance.upper_bounds.segment<nu>(nX + i * nu));\n      dltv_pb_.get_input_lb(i, osqp_instance.lower_bounds.segment<nu>(nX + i * nu));\n    }\n\n    // Set equality constraints bounds A(0)*x(0)\n    osqp_instance.lower_bounds.segment<nx>(nZ) = dltv_pb_.get_A(0) * sol_.x.col(0);\n\n    if constexpr (has_E) {\n      osqp_instance.lower_bounds.segment<nx>(nZ) += dltv_pb_.get_E(0);\n\n      for (std::size_t i = 1; i < nPts - 1; i++) {\n        osqp_instance.lower_bounds.segment<nx>(nZ + (i * nx)) = dltv_pb_.get_E(i);\n      }\n    } else {\n      osqp_instance.lower_bounds.segment<nx * (nPts - 2)>(nZ + nx) =\n        Eigen::Matrix<double, nx *(nPts - 2), 1>::Zero();\n    }\n\n    // Duplicate lower bound constraints onto upper bounds to make equalities.\n    osqp_instance.upper_bounds.segment<nEqCstr>(nZ) =\n      osqp_instance.lower_bounds.segment<nEqCstr>(nZ);\n\n\n    /* -------------------------------------------------------------------------- */\n    /*                            Set contraint matrix A                          */\n    /* -------------------------------------------------------------------------- */\n\n    // Set bound constraints matrix\n    for (std::size_t i = 0; i < nZ; i++) {\n      osqp_instance.constraint_matrix.insert(i, i) = 1.;\n    }\n\n    // Fill up Go_eq Bottom upper half: I_(nx+nu*nx+nu)\n    for (std::size_t i = nZ; i < nCstr; i++) {\n      osqp_instance.constraint_matrix.insert(i, i - nZ) = 1.;\n    }\n\n    // Fill up Go_eq Bottom Left subDiagonal: -A (note i = 1 starting point)\n    for (std::size_t i = 1; i < nPts - 1; i++) {\n      const std::size_t i_col = (i - 1) * nx;\n      const std::size_t i_row = nZ + i * nx;\n      const Ar_t A = dltv_pb_.get_A(i);\n      for (std::size_t c = 0; c < nx; ++c) {\n        for (std::size_t r = 0; r < nx; ++r) {\n          osqp_instance.constraint_matrix.insert(i_row + r, i_col + c) = -A(r, c);\n        }\n      }\n    }\n\n    // Fill up Go_eq Bottom Right Block Diagonal: -B\n    for (std::size_t i = 0; i < nPts - 1; i++) {\n      const std::size_t i_col = nX + i * nu;\n      const std::size_t i_row = nZ + i * nx;\n      const Br_t B = dltv_pb_.get_B(i);\n      for (std::size_t c = 0; c < nu; ++c) {\n        for (std::size_t r = 0; r < nx; ++r) {\n          osqp_instance.constraint_matrix.insert(i_row + r, i_col + c) = -B(r, c);\n        }\n      }\n    }\n\n\n    /* -------------------------------------------------------------------------- */\n    /*                   Set objective Vector q' = [qx qu]'                       */\n    /* -------------------------------------------------------------------------- */\n\n    //  fill in q\n    if constexpr (has_q) {\n      for (std::size_t i = 0; i < (nPts - 2); i++) {\n        osqp_instance.objective_vector.segment<nx>(i * nx) = dltv_pb_.get_q(i + 1);\n      }\n    } else {\n      osqp_instance.objective_vector.segment<nx * (nPts - 2)>(0).setZero();\n    }\n    //  fill in qT\n    if constexpr (has_qT) {\n      osqp_instance.objective_vector.segment<nx>((nPts - 2) * nx) = dltv_pb_.get_qT();\n    } else {\n      osqp_instance.objective_vector.segment<nx>((nPts - 2) * nx).setZero();\n    }\n\n    //  fill in r\n    if constexpr (has_r) {\n      for (std::size_t i = 0; i < (nPts - 1); i++) {\n        osqp_instance.objective_vector.segment<nu>(nX + (i * nu)) = dltv_pb_.get_r(i);\n      }\n    } else {\n      osqp_instance.objective_vector.segment<nu * (nPts - 1)>(nX).setZero();\n    }\n\n\n    /* -------------------------------------------------------------------------- */\n    /*                     Set Objective Matrix P = [Q/QT/R]                      */\n    /* -------------------------------------------------------------------------- */\n\n    // Fill up Diagonal: Q\n    for (std::size_t i = 0; i < nPts - 2; i++) {\n      const std::size_t i_col = i * nx;\n      const std::size_t i_row = i * nx;\n      const Qr_t Q = dltv_pb_.get_Q(i + 1);\n      for (std::size_t c = 0; c < nx; ++c) {\n        for (std::size_t r = 0; r < c; ++r) {\n          osqp_instance.objective_matrix.insert(i_row + r, i_col + c) = (Q(r, c) + Q(c, r)) / 2;\n        }\n        osqp_instance.objective_matrix.insert(i_row + c, i_col + c) = Q(c, c);\n      }\n    }\n\n    // Fill up Diagonal: QT\n    const std::size_t i_col = (nPts - 2) * nx;\n    const std::size_t i_row = (nPts - 2) * nx;\n    const QTr_t QT = dltv_pb_.get_QT();\n    for (std::size_t c = 0; c < nx; ++c) {\n      for (std::size_t r = 0; r < c; ++r) {\n        osqp_instance.objective_matrix.insert(i_row + r, i_col + c) = (QT(r, c) + QT(c, r)) / 2;\n      }\n      osqp_instance.objective_matrix.insert(i_row + c, i_col + c) = QT(c, c);\n    }\n\n    // Fill up Diagonal: R\n    for (std::size_t i = 0; i < nPts - 1; i++) {\n      const std::size_t i_col = nX + i * nu;\n      const std::size_t i_row = nX + i * nu;\n      const Rr_t R = dltv_pb_.get_R(i);\n      for (std::size_t c = 0; c < nu; ++c) {\n        for (std::size_t r = 0; r < c; ++r) {\n          osqp_instance.objective_matrix.insert(i_row + r, i_col + c) = (R(r, c) + R(c, r)) / 2;\n        }\n        osqp_instance.objective_matrix.insert(i_row + c, i_col + c) = R(c, c);\n      }\n    }\n\n    /* ------------------------ compress Sparse Matrices ------------------------ */\n    osqp_instance.objective_matrix.makeCompressed();\n    osqp_instance.constraint_matrix.makeCompressed();\n\n    const auto status = osqp_solver_.Init(osqp_instance, prm_.osqp_settings, true);\n\n    if (!status.ok()) {\n      throw std::runtime_error(\"Osqp initialization failed.\");\n    }\n\n    osqp_instance_ = std::move(osqp_instance);\n  }\n\n  /**\n   * @brief Set initial guess for problem solution\n   *\n   * @param x nx x nPts matrix of state values\n   * @param u nu x nPts matrix of input values\n   */\n  template<typename Derived1, typename Derived2>\n  void set_ic(const Eigen::MatrixBase<Derived1> & x, const Eigen::MatrixBase<Derived2> & u)\n  {\n    static_assert(\n      Derived1::RowsAtCompileTime == nx,\n      \"Number of states inconsistant with the problem.\");\n    static_assert(\n      Derived2::RowsAtCompileTime == nu,\n      \"Number of inputs inconsistant with the problem.\");\n    static_assert(\n      Derived1::ColsAtCompileTime == nPts,\n      \"Number of state initial conditions inconsistent with the problem.\");\n    static_assert(\n      Derived2::ColsAtCompileTime == nPts,\n      \"Number of input initial conditions inconsistent with the problem.\");\n\n    Eigen::Map<Eigen::Matrix<double, nx, nPts - 1>> varX(sol_.z.data());\n    varX = x.template rightCols<nPts - 1>();\n\n    Eigen::Map<Eigen::Matrix<double, nu, nPts - 1>> varU(sol_.z.data() + nX);\n    varU = u.template leftCols<nPts - 1>();\n\n    osqp_solver_.SetPrimalWarmStart(sol_.z);\n  }\n\n  /**\n   * @brief Update solver parameters\n   */\n  template<typename T>\n  void update_params(T && p)\n  {\n    prm_ = std::forward<T>(p);\n\n    const auto status = osqp_solver_.Init(osqp_instance_, prm_.osqp_settings, true);\n\n    if (!status.ok()) {\n      throw std::runtime_error(\"Osqp initialization failed.\");\n    }\n  }\n\n  /**\n   * @brief Solve the problem and return solution\n   *\n   * Note that init() must have been called prior to this function\n   */\n  Solution solve()\n  {\n    osqp::OsqpExitCode exit_code = osqp_solver_.Solve();\n\n    if (exit_code == osqp::OsqpExitCode::kOptimal) {\n      sol_.rc = DltvOcpSolverCode::success;\n    } else {\n      sol_.rc = DltvOcpSolverCode::failure;\n    }\n\n    sol_.z = osqp_solver_.primal_solution();\n\n    // Create X\n    const Eigen::Map<const Eigen::Matrix<double, nx, nPts - 1>> mX(sol_.z.data());\n    sol_.x.template rightCols<nPts - 1>() = mX;\n\n    // Create U\n    const Eigen::Map<const Eigen::Matrix<double, nu, nPts - 1>> mU(sol_.z.data() + nX);\n\n    sol_.u.col(nPts - 1) = mU.template rightCols<1>();\n    sol_.u.template leftCols<nPts - 1>() = mU;\n\n    return sol_;\n  }\n\n  Solution solution() const\n  {\n    return sol_;\n  }\n\n  dltv_pb_t & problem()\n  {\n    return dltv_pb_;\n  }\n\nprotected:\n  dltv_pb_t dltv_pb_{};\n  DltvOcpSolverParams prm_{};\n  Solution sol_{};\n  osqp::OsqpInstance osqp_instance_{};\n  osqp::OsqpSolver osqp_solver_{};\n};\n\n// Class template argument deduction guides\ntemplate<typename T>\nDltvOcpSolver(T)->DltvOcpSolver<T>;\n\ntemplate<typename T1, typename T2>\nDltvOcpSolver(T1, T2)->DltvOcpSolver<T1>;\n\n}  // namespace cbr\n\n#endif  // CBR_CONTROL__MPC__DLTV_OCP_SOLVER_HPP_\n", "meta": {"hexsha": "fcfac5ec18059550079fcaf4c86ea82f6b4fa93e", "size": 19843, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cbr_control/mpc/dltv_ocp_solver.hpp", "max_stars_repo_name": "yamaha-bps/cbr_control", "max_stars_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/cbr_control/mpc/dltv_ocp_solver.hpp", "max_issues_repo_name": "yamaha-bps/cbr_control", "max_issues_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cbr_control/mpc/dltv_ocp_solver.hpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7513134851, "max_line_length": 114, "alphanum_fraction": 0.5995061231, "num_tokens": 6000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6187804196836383, "lm_q1q2_score": 0.44071532987557}}
{"text": "#include \"sharp_edges.h\"\n#include <igl/unique_edge_map.h>\n#include <igl/per_face_normals.h>\n#include <igl/PI.h>\n#include <Eigen/Geometry>\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedSE,\n  typename DerivedE,\n  typename DeriveduE,\n  typename DerivedEMAP,\n  typename uE2Etype,\n  typename sharptype>\nIGL_INLINE void igl::sharp_edges(\n  const Eigen::MatrixBase<DerivedV> & V,\n  const Eigen::MatrixBase<DerivedF> & F,\n  const typename DerivedV::Scalar angle,\n  Eigen::PlainObjectBase<DerivedSE> & SE,\n  Eigen::PlainObjectBase<DerivedE> & E,\n  Eigen::PlainObjectBase<DeriveduE> & uE,\n  Eigen::PlainObjectBase<DerivedEMAP> & EMAP,\n  std::vector<std::vector<uE2Etype> > & uE2E,\n  std::vector< sharptype > & sharp)\n{\n  typedef typename DerivedSE::Scalar Index;\n  typedef typename DerivedV::Scalar Scalar;\n  typedef Eigen::Matrix<Index,Eigen::Dynamic,2> MatrixX2I;\n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,3> MatrixX3S;\n  typedef Eigen::Matrix<Scalar,1,3> RowVector3S;\n  typedef Eigen::Matrix<Index,Eigen::Dynamic,1> VectorXI;\n\n  unique_edge_map(F,E,uE,EMAP,uE2E);\n  MatrixX3S N;\n  per_face_normals(V,F,N);\n  // number of faces\n  const Index m = F.rows();\n  // Dihedral angles\n  //std::vector<Eigen::Triplet<Scalar,int> > DIJV;\n  sharp.clear();\n  // Loop over each unique edge\n  for(int u = 0;u<uE2E.size();u++)\n  {\n    bool u_is_sharp = false;\n    // Consider every pair of incident faces\n    //\n    // if there are 3 faces (non-manifold) it appears to follow that the edge\n    // must be sharp if angle<60. Could skip those (they're likely small number\n    // anyway).\n    for(int i = 0;i<uE2E[u].size();i++)\n    for(int j = i+1;j<uE2E[u].size();j++)\n    {\n      const int ei = uE2E[u][i];\n      const int fi = ei%m;\n      const int ej = uE2E[u][j];\n      const int fj = ej%m;\n      const RowVector3S ni = N.row(fi);\n      const RowVector3S nj = N.row(fj);\n      // Edge vector\n      // normalization might not be necessary\n      const RowVector3S ev = (V.row(E(ei,1)) - V.row(E(ei,0))).normalized();\n      const Scalar dij = \n        igl::PI - atan2((ni.cross(nj)).dot(ev),ni.dot(nj));\n      //DIJV.emplace_back(fi,fj,dij);\n      if(std::abs(dij-igl::PI) > angle)\n      {\n        u_is_sharp = true;\n      }\n    }\n    if(u_is_sharp)\n    {\n      sharp.push_back(u);\n    }\n  }\n  SE.resize(sharp.size(),2);\n  for(int i = 0;i<SE.rows();i++)\n  {\n    SE(i,0) = uE(sharp[i],0);\n    SE(i,1) = uE(sharp[i],1);\n  }\n}\n\ntemplate <\n  typename DerivedV,\n  typename DerivedF,\n  typename DerivedSE>\nIGL_INLINE void igl::sharp_edges(\n  const Eigen::MatrixBase<DerivedV> & V,\n  const Eigen::MatrixBase<DerivedF> & F,\n  const typename DerivedV::Scalar angle,\n  Eigen::PlainObjectBase<DerivedSE> & SE\n  )\n{\n  typedef typename DerivedSE::Scalar Index;\n  typedef typename DerivedV::Scalar Scalar;\n  typedef Eigen::Matrix<Index,Eigen::Dynamic,2> MatrixX2I;\n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,3> MatrixX3S;\n  typedef Eigen::Matrix<Scalar,1,3> RowVector3S;\n  typedef Eigen::Matrix<Index,Eigen::Dynamic,1> VectorXI;\n  MatrixX2I E,uE;\n  VectorXI EMAP;\n  std::vector<std::vector<Index> > uE2E;\n  std::vector<int>  sharp;\n  return sharp_edges(V,F,angle,SE,E,uE,EMAP,uE2E,sharp);\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate void igl::sharp_edges<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);\ntemplate void igl::sharp_edges<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, int, int>(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >&, std::vector<int, std::allocator<int> >&);\n#endif\n", "meta": {"hexsha": "8f1c053f752d4a52742beb12c972622a53ca62f2", "size": 4532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/libigl/include/igl/sharp_edges.cpp", "max_stars_repo_name": "chefmramos85/monster-mash", "max_stars_repo_head_hexsha": "239a41f6f178ca83c4be638331e32f23606b0381", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1125.0, "max_stars_repo_stars_event_min_datetime": "2021-02-01T09:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:50:40.000Z", "max_issues_repo_path": "third_party/libigl/include/igl/sharp_edges.cpp", "max_issues_repo_name": "ryan-cranfill/monster-mash", "max_issues_repo_head_hexsha": "c1b906d996885f8a4011bdf7558e62e968e1e914", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T12:36:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T14:02:50.000Z", "max_forks_repo_path": "third_party/libigl/include/igl/sharp_edges.cpp", "max_forks_repo_name": "ryan-cranfill/monster-mash", "max_forks_repo_head_hexsha": "c1b906d996885f8a4011bdf7558e62e968e1e914", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2021-02-13T10:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T11:55:20.000Z", "avg_line_length": 40.1061946903, "max_line_length": 872, "alphanum_fraction": 0.6451897617, "num_tokens": 1551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4406100013337586}}
{"text": "#include <Eigen/Eigenvalues>\n#include \"ndt_mcl/particle_filter.hpp\"\n#include \"ros/ros.h\"\n\nbool myfunction (double i,double j) { return (i>j); }\n\nperception_oru::particle_filter::particle_filter(perception_oru::NDTMap *ndtMap_, int particleCount_ /*, init_type initializationType_*/, bool be2D_, bool forceSIR_, double varLimit_, int sirCount_){\n\tbe2D = be2D_;\n\tndtMap = ndtMap_;\n\t// initializationType=initializationType_;\n\tparticleCount = particleCount_;\n\tforceSIR = forceSIR_;\n\tvarLimit = varLimit_;\n\tsirCount = sirCount_;\n\tweights.resize(particleCount_,0);\n}\n\nvoid perception_oru::particle_filter::Reset(){\n\ttmp.clear();\n\tdelete ndt_ISSMap;\n\tparticleCloud.clear();\n}\n\nvoid perception_oru::particle_filter::InitializeNormal(double x, double y, double th, double var){\n\n\tif(particleCloud.size() > 0){\n\t\tparticleCloud.clear();\n\t\ttmp.clear();\n\t}\n\tm_pose<<x,y,th;\n\ttmp.resize(particleCount);\n\tstd::default_random_engine generator;\n\n\tfor(int parNo = 0; parNo < particleCount; parNo++){\n\t\tstd::normal_distribution<double> distribution_x(x, var);\n\t\tstd::normal_distribution<double> distribution_y(y, var);\n\t\tstd::normal_distribution<double> distribution_t(th, th * var);\n\t\tparticleCloud.emplace_back(0.0, 0.0, distribution_t(generator), distribution_x(generator), distribution_y(generator), 0.0);\n\t}\n}\n\nvoid perception_oru::particle_filter::InitializeNormal(double x, double y, double var){\n\n\tif(particleCloud.size() > 0){\n\t\tparticleCloud.clear();\n\t\ttmp.clear();\n\t}\n\t\tm_pose<<x,y,0;\n\ttmp.resize(particleCount);\n\tstd::default_random_engine generator;\n\tfor(int parNo = 0; parNo < particleCount; parNo++){\n\t\tstd::normal_distribution<double> distribution_x(x, var);\n\t\tstd::normal_distribution<double> distribution_y(y, var);\n\t\tstd::uniform_real_distribution<double> distribution_t(0, 2 * 3.1415);\n\t\tparticleCloud.emplace_back(0.0, 0.0, distribution_t(generator), distribution_x(generator), distribution_y(generator), 0.0);\n\t}\n}\n\n\nEigen::Vector3d perception_oru::particle_filter::GetMeanPose2D(){\n\tdouble sumX = 0, sumY = 0;\n\tEigen::Vector3d pos;\n\tdouble sumW = 0;\n\tdouble ax = 0, ay = 0;\n\n\tfor(int i = 0; i < particleCloud.size(); i++){\n\t\tdouble x, y, z, r, p, t;\n\t\tparticleCloud[i].GetXYZ(x, y, z);\n\t\tparticleCloud[i].GetRPY(r, p, t);\n\t\tsumX += particleCloud[i].GetProbability() * x;\n\t\tsumY += particleCloud[i].GetProbability() * y;\n\t\tax += particleCloud[i].GetProbability() * cos(t);\n\t\tay += particleCloud[i].GetProbability() * sin(t);\n\t\tsumW += particleCloud[i].GetProbability();\n\t}\n\tpos << sumX, sumY, atan2(ay, ax);\n\treturn pos;\n}\n\n\nvoid perception_oru::particle_filter::GetPoseMeanAndVariance2D(Eigen::Vector3d &mean, Eigen::Matrix3d &cov){\n\tdouble sumX = 0, sumY = 0;\n\tdouble sumW = 0;\n\tdouble ax = 0, ay = 0;\n\n\tfor(int i = 0; i < particleCloud.size(); i++){\n\t\tdouble x, y, z, r, p, t;\n\t\tparticleCloud[i].GetXYZ(x, y, z);\n\t\tparticleCloud[i].GetRPY(r, p, t);\n\t\tsumX += particleCloud[i].GetProbability() * x;\n\t\tsumY += particleCloud[i].GetProbability() * y;\n\t\tax += particleCloud[i].GetProbability() * cos(t);\n\t\tay += particleCloud[i].GetProbability() * sin(t);\n\t\tsumW += particleCloud[i].GetProbability();\n\t}\n\tmean << sumX, sumY, atan2(ay, ax);\n\n\tdouble xx = 0, yy = 0, xy = 0, aax = 0, aay = 0;\n\tdouble cax = cos(atan2(ay, ax));\n\tdouble say = sin(atan2(ay, ax));\n\tdouble w2 = 0;\n\n\n\tfor(int i = 0; i < particleCloud.size(); i++){\n\t\tdouble x, y, z, r, p, t;\n\t\tparticleCloud[i].GetXYZ(x, y, z);\n\t\tparticleCloud[i].GetRPY(r, p, t);\n\t\txx += particleCloud[i].GetProbability() * (x - sumX) * (x - sumX);\n\t\tyy += particleCloud[i].GetProbability() * (y - sumY) * (y - sumY);\n\t\txy += particleCloud[i].GetProbability() * (x - sumX) * (y - sumY);\n\t\taax += particleCloud[i].GetProbability() * (cos(t) - cax) * (cos(t) - cax);\n\t\taay += particleCloud[i].GetProbability() * (sin(t) - say) * (sin(t) - say);\n\t\tw2 += particleCloud[i].GetProbability() * particleCloud[i].GetProbability();\n\t}\n\n\tif(w2 == 1.0){\n\t\tfprintf(stderr, \"CParticleFilter::getDistributionVariances -- w2=%lf Should not happen!\\n\", w2);\n\t\tw2 = 0.99;\n\t}\n\tdouble wc = 1.0 / (1.0 - w2);\n\tcov << wc * xx, wc * xy, 0,\n\twc * xy, wc * yy, 0,\n\t0, 0, atan2(wc * aay, wc * aax);\n}\n\nvoid perception_oru::particle_filter::InitializeUniformMap(){\n\tint pCount_ = particleCount;\n\n\tstd::vector<perception_oru::NDTCell*> allCells = ndtMap->getAllInitializedCells();\n\tstd::vector<perception_oru::NDTCell*> cells;\n\tfor(int cInd = 0; cInd < allCells.size(); cInd++)\n\t\tif(allCells[cInd]->getOccupancy() < 0.0)\n\t\t\tcells.push_back(allCells[cInd]);\n\n\tstd::default_random_engine generator;\n\tstd::uniform_int_distribution<int> distribution_c(0, cells.size() - 1);\n\ttmp.resize(pCount_);\n\tfor(int parNo = 0; parNo < pCount_; parNo++){\n\t\tint cellId = distribution_c(generator);\n\t\tdouble cx, cy, cz, sx, sy, sz;\n\t\tif(be2D){\n\t\t\tcells[cellId]->getCenter(cx, cy, cz);\n\t\t\tcells[cellId]->getDimensions(sx, sy, sz);\n\t\t\tstd::uniform_real_distribution<double> distribution_x(cx - sx / 2.0, cx + sx / 2.0);\n\t\t\tstd::uniform_real_distribution<double> distribution_y(cy - sy / 2.0, cy + sy / 2.0);\n\t\t\tstd::uniform_real_distribution<double> distribution_t(0.0, 2 * M_PI);\n\t\t\tparticleCloud.emplace_back(0.0, 0.0, distribution_t(generator), distribution_x(generator), distribution_y(generator), 0.0);\n\t\t}\n\t\t//here will go 3d distibution\n\t}\n}\n\nvoid perception_oru::particle_filter::InitializeFilter(){\n\t// switch(initializationType){\n\t//case uniform_map:\n\tInitializeUniformMap();\n\t// break;\n\t//  default:3\n\t//}\n}\n\nvoid perception_oru::particle_filter::UpdateAndPredict(Eigen::Affine3d tMotion, perception_oru::NDTMap ndtLocalMap_){\n\tEigen::Vector3d tr = tMotion.translation();\n\tEigen::Vector3d rot = tMotion.rotation().eulerAngles(0, 1, 2);\n\n\tif(tr[0] != 0.0 && tr[1] != 0.0 && rot[2] != 0){\n\t\tPredict2D(tr[0], tr[1], rot[2], tr[0] * 0.03 + 0.005, tr[1] * 0.03 + 0.005, rot[2] * 0.08 + 0.01);\n\t\t\t\t#pragma omp parallel for\n\t\tfor(int i = 0; i < particleCloud.size(); i++){\n\t\t\tEigen::Affine3d T = particleCloud[i].GetAsAffine();\n\t\t\tstd::vector<perception_oru::NDTCell*> ndts;\n\t\t\tndts = ndtLocalMap_.pseudoTransformNDT(T);\n\t\t\tdouble score = 1;\n\t\t\tif(ndts.size() == 0) fprintf(stderr, \"ERROR no gaussians in measurement!!!\\n\");\n\t\t\tfor(int n = 0; n < ndts.size(); n++){\n\t\t\t\tEigen::Vector3d m = ndts[n]->getMean();\n\t\t\t\tperception_oru::NDTCell *cell;\n\t\t\t\tpcl::PointXYZ p;\n\t\t\t\tp.x = m[0]; p.y = m[1]; p.z = m[2];\n\t\t\t\tif(ndtMap->getCellForPoint(p, cell)){\n\t\t\t\t\tif(cell == NULL) continue;\n\t\t\t\t\tif(cell->hasGaussian_){\n\t\t\t\t\t\tEigen::Matrix3d covCombined = cell->getCov() + ndts[n]->getCov();\n\t\t\t\t\t\tEigen::Matrix3d icov;\n\t\t\t\t\t\tbool exists;\n\t\t\t\t\t\tdouble det = 0;\n\t\t\t\t\t\tcovCombined.computeInverseAndDetWithCheck(icov, det, exists);\n\t\t\t\t\t\tif(!exists) continue;\n\t\t\t\t\t\tdouble l = (cell->getMean() - m).dot(icov * (cell->getMean() - m));\n\t\t\t\t\t\tif(l * 0 != 0) continue;\n\t\t\t\t\t\tscore += 0.1 + 0.9 * exp(-0.05 * l / 2.0);\n\t\t\t\t\t}else {\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tparticleCloud[i].SetLikelihood(score);\n\t\t\tfor(unsigned int j = 0; j < ndts.size(); j++)\n\t\t\t\tdelete ndts[j];\n\t\t}\n\t\tNormalize();\n\t\tif(forceSIR)\n\t\t\tSIRUpdate();\n\t\telse{\n\t\t\tdouble varP = 0;\n\t\t\tfor(int i = 0; i < particleCloud.size(); i++)\n\t\t\t\tvarP += (particleCloud[i].GetProbability() - 1.0 / double(particleCloud.size()))\n\t\t\t\t        * (particleCloud[i].GetProbability() - 1.0 / double(particleCloud.size()));\n\t\t\tvarP /= double(particleCloud.size());\n\t\t\tvarP = sqrt(varP);\n\t\t\tif(varP > varLimit || sinceSIR > sirCount){\n\t\t\t\t//fprintf(stderr,\"-SIR- \");\n\t\t\t\tsinceSIR = 0;\n\t\t\t\tSIRUpdate();\n\t\t\t}else\n\t\t\t\tsinceSIR++;\n\t\t}\n\t}\n}\nvoid perception_oru::particle_filter::UpdateAndPredict(Eigen::Affine3d tMotion, perception_oru::NDTMap* ndtLocalMap_){\n\tEigen::Vector3d tr = tMotion.translation();\n\tEigen::Vector3d rot = tMotion.rotation().eulerAngles(0, 1, 2);\n\n\tif(tr[0] != 0.0 && tr[1] != 0.0 && rot[2] != 0){\n\t\tPredict2D(tr[0], tr[1], rot[2], tr[0] * 0.1 + 0.005, tr[1] * 0.1 + 0.005, rot[2] * 0.1 + 0.001);\n\t\t\t\t#pragma omp parallel for\n\t\tfor(int i = 0; i < particleCloud.size(); i++){\n\t\t\tEigen::Affine3d T = particleCloud[i].GetAsAffine();\n\t\t\tstd::vector<perception_oru::NDTCell*> ndts;\n\t\t\tndts = ndtLocalMap_->pseudoTransformNDT(T);\n\t\t\tdouble score = 1;\n\t\t\tif(ndts.size() == 0) fprintf(stderr, \"ERROR no gaussians in measurement!!!\\n\");\n\t\t\tfor(int n = 0; n < ndts.size(); n++){\n\t\t\t\tEigen::Vector3d m = ndts[n]->getMean();\n\t\t\t\tperception_oru::NDTCell *cell;\n\t\t\t\t//pcl::PointXYZ p;\n\t\t\t\t//p.x = m[0];p.y=m[1];p.z=m[2];\n\t\t\t\tpcl::PointXYZ p(m[0], m[1], m[2]);\n\t\t\t\tif(ndtMap->getCellForPoint(p, cell)){\n\t\t\t\t\tif(cell == NULL) continue;\n\t\t\t\t\tif(cell->hasGaussian_){\n\t\t\t\t\t\tEigen::Matrix3d covCombined = cell->getCov() + ndts[n]->getCov();\n\t\t\t\t\t\tEigen::Matrix3d icov;\n\t\t\t\t\t\tbool exists;\n\t\t\t\t\t\tdouble det = 0;\n\t\t\t\t\t\tcovCombined.computeInverseAndDetWithCheck(icov, det, exists);\n\t\t\t\t\t\tif(!exists) continue;\n\t\t\t\t\t\tdouble l = (cell->getMean() - m).dot(icov * (cell->getMean() - m));\n\t\t\t\t\t\tif(l * 0 != 0) continue;\n\t\t\t\t\t\tscore += 0.1 + 0.9 * exp(-0.05 * l / 2.0);\n\t\t\t\t\t}else {\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tparticleCloud[i].SetLikelihood(score);\n\t\t\tfor(unsigned int j = 0; j < ndts.size(); j++)\n\t\t\t\tdelete ndts[j];\n\t\t}\n\t\tNormalize();\n\t\tif(forceSIR)\n\t\t\tSIRUpdate();\n\t\telse{\n\t\t\tdouble varP = 0;\n\t\t\tfor(int i = 0; i < particleCloud.size(); i++)\n\t\t\t\tvarP += (particleCloud[i].GetProbability() - 1.0 / double(particleCloud.size()))\n\t\t\t\t        * (particleCloud[i].GetProbability() - 1.0 / double(particleCloud.size()));\n\t\t\tvarP /= double(particleCloud.size());\n\t\t\tvarP = sqrt(varP);\n\t\t\tif(varP > varLimit || sinceSIR > sirCount){\n\t\t\t\t//fprintf(stderr,\"-SIR- \");\n\t\t\t\tsinceSIR = 0;\n\t\t\t\tSIRUpdate();\n\t\t\t}else\n\t\t\t\tsinceSIR++;\n\t\t}\n\t}\n}\n\n\nvoid perception_oru::particle_filter::UpdateAndPredictEff(Eigen::Affine3d tMotion, perception_oru::NDTMap* ndtLocalMap_, double subsample_level, double z_cut){ //you may add z cut here if necessarry\n\tif(subsample_level < 0 || subsample_level > 1) subsample_level = 1;\n\n\tEigen::Vector3d tr = tMotion.translation();\n\tEigen::Vector3d rot = tMotion.rotation().eulerAngles(0, 1, 2);\n\tif(tr[0] != 0.0 && tr[1] != 0.0 && rot[2] != 0){\n\t  int all_cells;\n\t  int subsample_cells;\n\t  int used_cells=0;\n\t  Predict2D(tr[0], tr[1], rot[2], fabs(tr[0]) * 0.50 + 0.001, fabs(tr[1]) * 0.70 + 0.001, fabs(rot[2]) * 0.15 + 0.001); //this line!!!!!!!!!!!!!!!!!!!!!!!!!\n\t  //Predict2D(tr[0], tr[1], rot[2], fabs(tr[0]) * 0.25 + 0.001, fabs(tr[1]) * 0.25 + 0.001, fabs(rot[2]) * 0.15 + 0.001); //this line!!!!!!!!!!!!!!!!!!!!!!!!!\n\t\tstd::vector<perception_oru::NDTCell*> ndts0 = ndtLocalMap_->getAllCells();\n\t\tstd::vector<perception_oru::NDTCell*> ndts;\n\t\tif(subsample_level != 1){\n\t\t\tsrand(time(NULL));\n\t\t\tfor(int i = 0; i < ndts0.size(); ++i){\n\t\t\t\tdouble p = ((double)rand()) / RAND_MAX;\n\n\t\t\t\tif(p < subsample_level && ndts0[i]->getMean()[2]>z_cut && ndts0[i]->getClass()!=perception_oru::NDTCell::HORIZONTAL)\n\t\t\t\t\tndts.push_back(ndts0[i]);\n\t\t\t\telse\n\t\t\t\t\tdelete ndts0[i];\n\t\t\t}\n\t\t} else\n\t\t\tndts = ndts0;\n//#pragma omp parallel for\n\t\tfor(int i = 0; i < particleCloud.size(); i++){\n\t\t\tEigen::Affine3d T = particleCloud[i].GetAsAffine();\n\t\t\t// std::vector<lslgeneric::NDTCell*> ndts;\n\t\t\t// ndts = ndtLocalMap_->pseudoTransformNDT(T);\n\t\t\tdouble score = 1;\n\t\t\tif(ndts.size() == 0) fprintf(stderr, \"ERROR no gaussians in measurement!!!\\n\");\n\t\t\tfor(int n = 0; n < ndts.size(); n++){\n\t\t\t\tEigen::Vector3d m = T * ndts[n]->getMean();\n\t\t\t\t//if(m[2] < zfilt_min) continue;\n\t\t\t\tperception_oru::NDTCell *cell;\n\t\t\t\tpcl::PointXYZ p;\n\t\t\t\tp.x = m[0]; p.y = m[1]; p.z = m[2];\n\t\t\t\tif(ndtMap->getCellAtPoint(p, cell)){\n\t\t\t\t\tif(cell == NULL) continue;\n\t\t\t\t\tif(cell->getClass()==perception_oru::NDTCell::HORIZONTAL) continue;\n\t\t\t\t\tif(cell->hasGaussian_){\n\t\t\t\t\t  \tEigen::Matrix3d map_cov =\n\t\t\t\t\t\t  cell->getCov();\n\t\t\t\t\t\t//cell->blurCov( 10 );\n\n\t\t\t\t\t\t//Eigen::Matrix3d covCombined = cell->getCov() + T.rotation() * ndts[n]->getCov() * T.rotation().transpose();\n\t\t\t\t\t\tEigen::Matrix3d covCombined = map_cov + T.rotation() * ndts[n]->getCov() * T.rotation().transpose();\n\t\t\t\t\t\tEigen::Matrix3d icov;\n\t\t\t\t\t\tbool exists;\n\t\t\t\t\t\tdouble det = 0;\n\t\t\t\t\t\tcovCombined.computeInverseAndDetWithCheck(icov, det, exists);\n\t\t\t\t\t\tif(!exists) continue;\n\t\t\t\t\t\tdouble l = (cell->getMean() - m).dot(icov * (cell->getMean() - m));\n\t\t\t\t\t\tif(l * 0 != 0) continue;\n\t\t\t\t\t\tscore += 0.1 + 0.9 * exp(-0.005 * l / 2.0);\n\t\t\t\t\t}else{\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tparticleCloud[i].SetLikelihood(score);\n\t\t}\n\t\tfor(unsigned int j = 0; j < ndts.size(); j++)\n\t\t\tdelete ndts[j];\n\n\t\tNormalize();\n\t\tif(forceSIR)\n\t\t\tSIRUpdate();\n\t\telse{\n\t\t\tdouble varP = 0;\n\t\t\tfor(int i = 0; i < particleCloud.size(); i++)\n\t\t\t\tvarP += (particleCloud[i].GetProbability() - 1.0 / double(particleCloud.size()))\n\t\t\t\t        * (particleCloud[i].GetProbability() - 1.0 / double(particleCloud.size()));\n\t\t\tvarP /= double(particleCloud.size());\n\t\t\tvarP = sqrt(varP);\n\t\t\tif(varP > varLimit || sinceSIR > sirCount){\n\t\t\t\t//fprintf(stderr,\"-SIR- \");\n\t\t\t\tsinceSIR = 0;\n\t\t\t\tSIRUpdate();\n\t\t\t}else\n\t\t\t\tsinceSIR++;\n\t\t}\n\t}\n}\n\n\n\nvoid perception_oru::particle_filter::UpdateAndPredictEffRe(Eigen::Affine3d tMotion, perception_oru::NDTMap* ndtLocalMap_, double subsample_level, double z_cut, double x_var, double y_var, double th_var, double r_x_var, double r_y_var, double r_th_var, int tres){\n\tif(subsample_level < 0 || subsample_level > 1) subsample_level = 1;\n\tdouble tre=weights[tres];\n\tEigen::Vector3d tr = tMotion.translation();\n\tEigen::Vector3d rot = tMotion.rotation().eulerAngles(0, 1, 2);\n\tif(tr[0] != 0.0 || tr[1] != 0.0 || rot[2] != 0){\n\t  int all_cells;\n\t  int subsample_cells;\n\t  int used_cells=0;\n\t  Predict2D(tr[0], tr[1], rot[2], fabs(tr[0]) * x_var, fabs(tr[1]) * y_var, fabs(rot[2]) * th_var); //this line!!!!!!!!!!!!!!!!!!!!!!!!!\n\t\tstd::vector<perception_oru::NDTCell*> ndts0 = ndtLocalMap_->getAllCells();\n\t\tstd::vector<perception_oru::NDTCell*> ndts;\n\t\tif(subsample_level != 1){\n\t\t\tsrand(time(NULL));\n\t\t\tfor(int i = 0; i < ndts0.size(); ++i){\n\t\t\t\tdouble p = ((double)rand()) / RAND_MAX;\n\n\t\t\t\tif(p < subsample_level && ndts0[i]->getMean()[2]>z_cut && ndts0[i]->getClass()!=perception_oru::NDTCell::HORIZONTAL)\n\t\t\t\t\tndts.push_back(ndts0[i]);\n\t\t\t\telse\n\t\t\t\t\tdelete ndts0[i];\n\t\t\t}\n\t\t} else\n\t\t\tndts = ndts0;\n\n//#pragma omp parallel for\n\t\tfor(int i = 0; i < particleCloud.size(); i++){\n\t\t\tEigen::Affine3d T;\n\t\t\tif(particleCloud[i].GetProbability()>tre){\n\t\t\t\tT = particleCloud[i].GetAsAffine();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tstd::default_random_engine generator;\n\t\t\t\tstd::normal_distribution<double> distribution_x(m_pose[0], r_x_var);\n\t\t\t\tstd::normal_distribution<double> distribution_y(m_pose[1], r_y_var);\n\t\t\t\tstd::normal_distribution<double> distribution_t(m_pose[2], r_th_var);\n\t\t\t\tparticleCloud[i].Set(0.0, 0.0, distribution_t(generator), distribution_x(generator), distribution_y(generator), 0.0);\n\n\t\t\t\tT = particleCloud[i].GetAsAffine();\n\t\t\t}\n\t\t\t\t// std::vector<lslgeneric::NDTCell*> ndts;\n\t\t\t\t// ndts = ndtLocalMap_->pseudoTransformNDT(T);\n\t\t\t\tdouble score = 1;\n\t\t\t\tif(ndts.size() == 0) fprintf(stderr, \"ERROR no gaussians in measurement!!!\\n\");\n\t\t\t\tfor(int n = 0; n < ndts.size(); n++){\n\t\t\t\t\tEigen::Vector3d m = T * ndts[n]->getMean();\n\t\t\t\t\t//if(m[2] < zfilt_min) continue;\n\t\t\t\t\tperception_oru::NDTCell *cell;\n\t\t\t\t\tpcl::PointXYZ p;\n\t\t\t\t\tp.x = m[0]; p.y = m[1]; p.z = m[2];\n\t\t\t\t\tif(ndtMap->getCellAtPoint(p, cell)){\n\t\t\t\t\t\tif(cell == NULL) continue;\n\t\t\t\t\t\tif(cell->hasGaussian_){\n\t\t\t\t\t\t\tEigen::Matrix3d covCombined = cell->getCov() + T.rotation() * ndts[n]->getCov() * T.rotation().transpose();\n\t\t\t\t\t\t\tEigen::Matrix3d icov;\n\t\t\t\t\t\t\tbool exists;\n\t\t\t\t\t\t\tdouble det = 0;\n\t\t\t\t\t\t\tcovCombined.computeInverseAndDetWithCheck(icov, det, exists);\n\t\t\t\t\t\t\tif(!exists) continue;\n\t\t\t\t\t\t\tdouble l = (cell->getMean() - m).dot(icov * (cell->getMean() - m));\n\t\t\t\t\t\t\tif(l * 0 != 0) continue;\n\t\t\t\t\t\t\tscore += 0.1 + 0.9 * exp(-0.5*l / 2.0);\n\t\t\t\t\t\t}else{\n\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tparticleCloud[i].SetLikelihood(score);\n\t\t}\n\t\tfor(unsigned int j = 0; j < ndts.size(); j++)\n\t\t\tdelete ndts[j];\n\n\t\tNormalize();\n\t\tif(forceSIR)\n\t\t\tSIRUpdate();\n\t\telse{\n\t\t\tdouble varP = 0;\n\t\t\tfor(int i = 0; i < particleCloud.size(); i++)\n\t\t\t\tvarP += (particleCloud[i].GetProbability() - 1.0 / double(particleCloud.size()))\n\t\t\t\t        * (particleCloud[i].GetProbability() - 1.0 / double(particleCloud.size()));\n\t\t\tvarP /= double(particleCloud.size());\n\t\t\tvarP = sqrt(varP);\n\t\t\tif(varP > varLimit || sinceSIR > sirCount){\n\t\t\t\t//fprintf(stderr,\"-SIR- \");\n\t\t\t\tsinceSIR = 0;\n\t\t\t\tSIRUpdate();\n\t\t\t}else\n\t\t\t\tsinceSIR++;\n\t\t}\n\t}\n}\n\n\nvoid perception_oru::particle_filter::Predict2D(double x, double y, double th, double sx, double sy, double sth){\n\tfloat dx = 0.0, dy = 0.0, dl = 0.0;\n\tfloat t = 0.0;\n\tfloat dxe, dye; ///<estimates\n\tstd::default_random_engine generator;\n\tfloat eps=0.000001;\n\tfor(int i = 0; i < particleCloud.size(); i++){\n\t\tdouble px, py, pz, pr, pp, pt;\n\t\tparticleCloud[i].GetXYZ(px, py, pz);\n\t\tparticleCloud[i].GetRPY(pr, pp, pt);\n\n\t\tstd::normal_distribution<double> distribution_x(0, sx);\n\t\tstd::normal_distribution<double> distribution_y(0, sy);\n\t\tstd::normal_distribution<double> distribution_th(0, sth);\n\t\t///Generate noise from normal distribution\n\t\tdxe = x + distribution_x(generator);\n\t\tdye = y + distribution_y(generator);\n\n\t\t//if(fabs(x)<eps && fabs(y)<eps){\n\t\t//\tdxe = x*0;\n\t\t//\tdye = y*0;\n\t\t//\n\t\t//}\n\n\n\t\tdl = sqrt(dxe * dxe + dye * dye);\n\n\t\t//if(fabs(dxe)<eps && fabs(dye)<eps)\n\t\t//t = 0;\n\t\t//else\n\t\tt = atan2(dye, dxe);\n\n\t\tdx = dl * cos(pt + t);\n\t\tdy = dl * sin(pt + t);\n\t\t//ROS_INFO_STREAM(\"th\"<<th);\n\t\tpx += dx;\n\t\tpy += dy;\n\t\tpt = pt + th + distribution_th(generator);\n\t\ttoPI(pt);\n\t\tparticleCloud[i].Set(pr, pp, pt, px, py, pz);\n\t}\n\t//    isAvgSet = false;\n}\nvoid perception_oru::particle_filter::to2PI(double &a){\n\ta = (double)fmod((double)(a), (double)( 2 * M_PI));\n\tif(a < 0) a += 2 * (double)M_PI;\n}\nvoid perception_oru::particle_filter::toPI(double &a){\n\tif(a > M_PI)\n\t\twhile(a > M_PI) a -= 2.0 * M_PI;\n\telse\n\tif(a < -M_PI)\n\t\twhile(a < -M_PI) a += 2.0 * M_PI;\n}\n\nvoid perception_oru::particle_filter::Normalize(){\n\tint i;\n\tdouble summ = 0;\n\tdouble sumX = 0, sumY = 0;\n\tdouble sumW = 0;\n\tdouble ax = 0, ay = 0;\n\n\t//isAvgSet = false;\n\tfor(i = 0; i < particleCloud.size(); i++){\n\t\tparticleCloud[i].SetProbability(particleCloud[i].GetProbability() * particleCloud[i].GetLikelihood());\n\t\tsumm += particleCloud[i].GetProbability();\n\t}\n\tif(summ != 0){\n\t\tfor(i = 0; i < particleCloud.size(); i++){\n\t\t\tparticleCloud[i].SetProbability(particleCloud[i].GetProbability() / summ);\n\t\t\tweights[i]=particleCloud[i].GetProbability();\n\t\t\tdouble x, y, z, r, p, t;\n\t\t\tparticleCloud[i].GetXYZ(x, y, z);\n\t\t\tparticleCloud[i].GetRPY(r, p, t);\n\t\t\tsumX += particleCloud[i].GetProbability() * x;\n\t\t\tsumY += particleCloud[i].GetProbability() * y;\n\t\t\tax += particleCloud[i].GetProbability() * cos(t);\n\t\t\tay += particleCloud[i].GetProbability() * sin(t);\n\t\t\tsumW += particleCloud[i].GetProbability();\n\t\t}\n\t}\n\telse{\n\t\tfor(i = 0; i < particleCloud.size(); i++){\n\t\t\tparticleCloud[i].SetProbability(1.0 / particleCloud.size());\n\t\t\tweights[i]=particleCloud[i].GetProbability();\n\t\t\tdouble x, y, z, r, p, t;\n\t\t\tparticleCloud[i].GetXYZ(x, y, z);\n\t\t\tparticleCloud[i].GetRPY(r, p, t);\n\t\t\tsumX += particleCloud[i].GetProbability() * x;\n\t\t\tsumY += particleCloud[i].GetProbability() * y;\n\t\t\tax += particleCloud[i].GetProbability() * cos(t);\n\t\t\tay += particleCloud[i].GetProbability() * sin(t);\n\t\t\tsumW += particleCloud[i].GetProbability();\n\t\t}\n\t}\n\t\tm_pose << sumX, sumY, atan2(ay, ax);\n\t\tstd::sort (weights.begin(), weights.end(),myfunction);\n\t\t//ROS_INFO_STREAM(weights.front()<<\" \"<< weights.back());\n}\nvoid perception_oru::particle_filter::SIRUpdate(){\n\tstd::vector<particle> tmp2;\n\tstd::default_random_engine generator;\n\tstd::uniform_real_distribution<double> dist(0, 1);\n\tdouble U = 0, Q = 0;\n\tint i = 0, j = 0, k = 0;\n\tU = dist(generator) / (double)particleCloud.size();\n\t//fprintf(stderr,\"SIRUpdate()::U=%.6f\\n\",U);\n\twhile(U < 1.0){\n\t\tif(Q > U){\n\t\t\tU += 1.0 / (double)particleCloud.size();\n\t\t\tif(k >= particleCloud.size() || i >= particleCloud.size()){\n\t\t\t\twhile(i < particleCloud.size()){\n\t\t\t\t\ttmp[i] = particleCloud[particleCloud.size() - 1];\n\t\t\t\t\ttmp[i].probability = 1.0 / (double)particleCloud.size();\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\t//fprintf(stderr,\"ERROR: SIRupdate:: Invalid index k='%d' or i='%d'\\n\",k,i);\n\t\t\t\ttmp2 = particleCloud;\n\t\t\t\tparticleCloud = tmp;\n\t\t\t\ttmp = tmp2;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttmp[i] = particleCloud[k];\n\t\t\ttmp[i].probability = 1.0 / (double)particleCloud.size();\n\t\t\ti++;\n\t\t}else {\n\t\t\tj++;\n\t\t\tk = j;\n\t\t\tif(j >= particleCloud.size()){\n\t\t\t\twhile(i < particleCloud.size()){\n\t\t\t\t\ttmp[i] = particleCloud[particleCloud.size() - 1];\n\t\t\t\t\ttmp[i].probability = 1.0 / (double)particleCloud.size();\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\t//fprintf(stderr,\"ERROR: SIRupdate:: Invalid index j='%d' \\n\",j);\n\t\t\t\ttmp2 = particleCloud;\n\t\t\t\tparticleCloud = tmp;\n\t\t\t\ttmp = tmp2;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tQ += particleCloud[j].probability;\n\t\t\t///j++; ///WAS HERE until 30.7.2008\n\n\t\t\tif(j == particleCloud.size()){\n\t\t\t\twhile(i < particleCloud.size()){\n\t\t\t\t\ttmp[i] = particleCloud[k - 1];\n\t\t\t\t\ttmp[i].probability = 1.0 / (double)particleCloud.size();\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\ttmp2 = particleCloud;\n\t\t\t\tparticleCloud = tmp;\n\t\t\t\ttmp = tmp2;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t} //While\n\twhile(i < particleCloud.size()){\n\t\tif(k >= particleCloud.size()) k = particleCloud.size() - 1;\n\t\ttmp[i] = particleCloud[k];\n\t\ttmp[i].probability = 1.0 / (double)particleCloud.size();\n\t\ti++;\n\t}\n\t//  isAvgSet = false;\n\ttmp2 = particleCloud;\n\tparticleCloud = tmp;\n\ttmp = tmp2;\n}\n\nvoid perception_oru::particle_filter::GetRandomPoint(perception_oru::NDTCell* cell, double &x, double &y, double &th){\n\tEigen::Vector3d mean = cell->getMean();\n\tEigen::Matrix3d cov = cell->getCov();\n\tdouble mX = mean[0], mY = mean[1], mTh = mean[2];\n\tdouble varX = cov(0, 0), varY = cov(1, 1), varTh = cov(2, 2);\n\tstd::default_random_engine generator;\n\n\tstd::normal_distribution<double> distribution_x(mX, varX);\n\tstd::normal_distribution<double> distribution_y(mY, varY);\n\tstd::normal_distribution<double> distribution_th(mTh, varTh);\n\tx = distribution_x(generator);\n\ty = distribution_y(generator);\n\tth = distribution_th(generator);\n}\n\nvoid perception_oru::particle_filter::EigenSort( Eigen::Vector3d &eigenvalues, Eigen::Matrix3d &eigenvectors ){\n\tint k, j, i;\n\tdouble p;\n\n\tfor(i = 0; i < 2; i++){\n\t\tp = eigenvalues(k = i);\n\t\tfor(j = i + 1; j < 3; j++)\n\t\t\tif(fabs(eigenvalues(j)) >= fabs(p))\n\t\t\t\tp = eigenvalues(k = j);\n\t\tif(k != i){\n\t\t\teigenvalues.row(k).swap(eigenvalues.row(i));\n\t\t\teigenvectors.col(k).swap(eigenvectors.col(i));\n\t\t}\n\t}\n}\n\nEigen::Affine3d perception_oru::particle_filter::getAsAffine(float x, float y, float yaw ){\n\tEigen::Matrix3d m;\n\n\tm = Eigen::AngleAxisd(0, Eigen::Vector3d::UnitX())\n\t    * Eigen::AngleAxisd(0, Eigen::Vector3d::UnitY())\n\t    * Eigen::AngleAxisd(yaw, Eigen::Vector3d::UnitZ());\n\tEigen::Translation3d v(x, y, 0);\n\tEigen::Affine3d T = Eigen::Affine3d::Identity();\n\tT.rotate(Eigen::AngleAxisd(yaw, Eigen::Vector3d::UnitZ()));\n\tT.translation()<<x,y,0;\n\treturn T;\n}\n", "meta": {"hexsha": "2d07becccf2ca2b22cb86ad862bace9eabcc4d6c", "size": 22769, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception_oru-port-kinetic/ndt_localization/src/ndt_localization/particle_filter.cpp", "max_stars_repo_name": "lllray/ndt-loam", "max_stars_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-14T08:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-14T08:21:13.000Z", "max_issues_repo_path": "perception_oru-port-kinetic/ndt_localization/src/ndt_localization/particle_filter.cpp", "max_issues_repo_name": "lllray/ndt-loam", "max_issues_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-28T04:47:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-28T04:47:56.000Z", "max_forks_repo_path": "perception_oru-port-kinetic/ndt_localization/src/ndt_localization/particle_filter.cpp", "max_forks_repo_name": "lllray/ndt-loam", "max_forks_repo_head_hexsha": "331867941e0764b40e1a980dd85d2174f861e9c8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-18T11:25:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T12:59:59.000Z", "avg_line_length": 33.9329359165, "max_line_length": 263, "alphanum_fraction": 0.6317800518, "num_tokens": 7444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4406099943510988}}
{"text": "/*\n *            Copyright 2009-2018 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <votca/xtp/bfgs-trm.h>\n#include <boost/format.hpp>\n\nnamespace votca {\n    namespace xtp {\n\n        void BFGSTRM::Optimize(const Eigen::VectorXd& initialparameters) {\n           _parameters=initialparameters;\n\n            Eigen::VectorXd gradient=Eigen::VectorXd::Zero(_parameters.size());\n            Eigen::VectorXd delta_p_trial=Eigen::VectorXd::Zero(_parameters.size());\n            \n            double lastcost=_costfunction.EvaluateCost(_parameters);\n            Eigen::VectorXd last_gradient=Eigen::VectorXd::Zero(_parameters.size());\n            double delta_cost=0;\n            \n            for(_iteration=0;_iteration<_max_iteration;_iteration++){\n               gradient=_costfunction.EvaluateGradient(_parameters);\n                bool step_accepted = false;\n                for (int i=0;i<100;i++){\n                    delta_p_trial=CalculateInitialStep(gradient);\n                    if (delta_p_trial.norm()>_trust_radius){\n                       delta_p_trial=CalculateRegularizedStep(delta_p_trial,gradient);\n                    }\n                    double trialcost=_costfunction.EvaluateCost(_parameters+delta_p_trial);\n                    delta_cost=trialcost-lastcost;\n                    step_accepted=AcceptRejectStep(delta_p_trial,gradient,delta_cost);\n                    if(step_accepted){\n                      _cost=trialcost;\n                      _parameters+=delta_p_trial;\n                      break;\n                    }\n                    \n                } \n                if(_iteration>0){\n                  UpdateHessian(delta_p_trial,gradient-last_gradient);\n                }\n                lastcost=_cost;\n                last_gradient=gradient;\n                for(auto& func:_callbacks){\n                 func();\n                }\n                if(_costfunction.Converged(delta_p_trial,delta_cost,gradient)){\n                  break;\n                } else if(_iteration == _max_iteration-1) {\n                  _success=false;\n                  if(_logging){\n                    CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"BFGS-TRM @iteration %1$d: not converged after %2$d iterations \")\n                            % _iteration % _max_iteration).str() << std::flush;\n                  }\n                }\n\n            }\n            return;\n        }\n\n        /* Accept/reject the new geometry and adjust trust radius, if required */\n        bool BFGSTRM::AcceptRejectStep(const Eigen::VectorXd& delta_p,const Eigen::VectorXd& gradient,double cost_delta) {\n            bool step_accepted = false;\n            if (cost_delta > 0.0) {\n                // total energy has unexpectedly increased, half the trust radius\n                _trust_radius = 0.25 * _trust_radius;\n                if(_logging){\n                  CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"BFGS-TRM @iteration %1$d: step rejected \")\n                          % _iteration).str() << std::flush;\n                  CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"BFGS-TRM @iteration %1$d: new trust radius %2$8.6f\") \n                          % _iteration % _trust_radius).str() << std::flush;\n                }\n            } else {\n                // total energy has decreased, we accept the step but might update the trust radius\n                step_accepted = true;\n                // adjust trust radius, if required\n                double tr_check = cost_delta / QuadraticEnergy(gradient,delta_p);\n                double norm_delta_p=delta_p.squaredNorm();\n                if (tr_check > 0.75 && 1.25 * norm_delta_p > _trust_radius*_trust_radius) {\n                    _trust_radius = 2.0 * _trust_radius;\n                } else if (tr_check < 0.25) {\n                    _trust_radius = 0.25 * _trust_radius;\n                }\n                if(_logging){\n                  CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"BFGS-TRM @iteration %1$d: step accepted \")\n                          % _iteration).str() << std::flush;\n                  CTP_LOG(ctp::logINFO, *_pLog) << (boost::format(\"BFGS-TRM @iteration %1$d: new trust radius %2$8.6f\")\n                          % _iteration % _trust_radius).str() << std::flush;\n                }\n            }\n            return step_accepted;\n        }\n\n        void BFGSTRM::UpdateHessian(const Eigen::VectorXd& delta_pos,const Eigen::VectorXd& delta_gradient) {\n                // second term in BFGS update (needs current Hessian)\n               _hessian -= _hessian*delta_pos*delta_pos.transpose()*_hessian.transpose() / (delta_pos.transpose()*_hessian*delta_pos).value();\n                // first term in BFGS update\n                _hessian += (delta_gradient* delta_gradient.transpose()) / (delta_gradient.transpose()*delta_pos);\n                // symmetrize Hessian (since d2E/dxidxj should be symmetric)\n               _hessian=0.5*(_hessian+_hessian.transpose());\n            return;\n        }\n\n        /* Predict displacement of atom coordinates */\n        Eigen::VectorXd BFGSTRM::CalculateInitialStep(const Eigen::MatrixXd& gradient)const{\n            return _hessian.colPivHouseholderQr().solve(-gradient);\n        }\n\n        /* Regularize step in case of prediction outside of Trust Region */\n        Eigen::VectorXd BFGSTRM::CalculateRegularizedStep(const Eigen::VectorXd& delta_pos,const Eigen::VectorXd& gradient) const{\n            Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(_hessian);\n            // start value for lambda  a bit lower than lowest eigenvalue of Hessian\n            double lambda= 1.05 * es.eigenvalues()(0);\n            if (es.eigenvalues()(0) > 0.0) {\n              lambda = -0.05 * std::abs(es.eigenvalues()(0));\n            } \n            // for constrained step, we expect\n            double max_step_squared =delta_pos.squaredNorm();\n            while (max_step_squared>(_trust_radius * _trust_radius)) {\n              lambda -= 0.05 * std::abs(es.eigenvalues()(0));\n              Eigen::VectorXd quotient=(es.eigenvalues().array()-lambda).cwiseAbs2();\n              auto factor=(es.eigenvectors().transpose()*gradient).cwiseAbs2();\n              max_step_squared = (factor.cwiseQuotient(quotient)).sum();\n            }\n                \n            Eigen::VectorXd new_delta_pos = Eigen::VectorXd::Zero(delta_pos.size());\n            for (unsigned i = 0; i < delta_pos.size(); i++) {\n                new_delta_pos -= es.eigenvectors().col(i) * (es.eigenvectors().col(i).transpose()*gradient) / (es.eigenvalues()(i) - lambda);\n            }\n            return new_delta_pos;\n        }\n\n        /* Estimate energy change based on quadratic approximation */\n        double BFGSTRM::QuadraticEnergy(const Eigen::VectorXd& gradient, const Eigen::VectorXd& delta_pos) const{\n            return (gradient.transpose()* delta_pos).value() + 0.5*(delta_pos.transpose()*_hessian*delta_pos).value();\n        }\n        \n        \n\n        \n\n    }\n}\n", "meta": {"hexsha": "71170df2c7f38aefb27eec7ce120e2577effffe1", "size": 7573, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/bfgs-trm.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/bfgs-trm.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/bfgs-trm.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6289308176, "max_line_length": 142, "alphanum_fraction": 0.5671464413, "num_tokens": 1658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4406099943510988}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 1999 - 2019 by the deal.II authors\n *\n * This file is part of the deal.II library.\n *\n * The deal.II library is free software; you can use it, redistribute\n * it, and/or modify it under the terms of the GNU Lesser General\n * Public License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * The full text of the license can be found in the file LICENSE.md at\n * the top level of the deal.II distribution.\n *\n * ---------------------------------------------------------------------\n *\n * based on deal.II step-1\n */\n\n\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/manifold_lib.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <tuple>\n\nusing namespace dealii;\n\n\nstd::tuple<unsigned int, unsigned int, unsigned int>\nget_info_triangulation(const Triangulation<2> &tria)\n{\n  return std::make_tuple<unsigned int, unsigned int>(tria.n_active_cells(),\n                                                     tria.n_cells(),\n                                                     tria.n_levels());\n}\n\n\n\nvoid\nfirst_grid()\n{\n  Triangulation<2> triangulation;\n\n  GridGenerator::hyper_cube(triangulation);\n  triangulation.refine_global(4);\n\n  std::ofstream out(\"grid-1.vtk\");\n  GridOut       grid_out;\n  grid_out.write_svg(triangulation, out);\n\n  std::cout << \"Grid written to grid-1.vtk\" << std::endl;\n\n  auto info_tria = get_info_triangulation(triangulation);\n  std::cout << std::get<0>(info_tria) << \"\\t\" << std::get<1>(info_tria) << \"\\t\"\n            << std::get<2>(info_tria) << \"\\n\";\n}\n\n\n\nvoid\nsecond_grid()\n{\n  Triangulation<2> triangulation;\n\n  const Point<2> center(1, 0);\n  const double   inner_radius = 0.5, outer_radius = 1.0;\n  GridGenerator::hyper_shell(\n    triangulation, center, inner_radius, outer_radius, 10);\n  for (unsigned int step = 0; step < 5; ++step)\n    {\n      for (auto &cell : triangulation.active_cell_iterators())\n        {\n          for (const auto v : cell->vertex_indices())\n            {\n              const double distance_from_center =\n                center.distance(cell->vertex(v));\n\n              if (std::fabs(distance_from_center - inner_radius) <=\n                  1e-6 * inner_radius)\n                {\n                  cell->set_refine_flag();\n                  break;\n                }\n            }\n        }\n      triangulation.reset_manifold(\n        0); // Reset all parts of the triangulation, regardless of their\n            // manifold_id, to use a FlatManifold object.\n      triangulation.execute_coarsening_and_refinement();\n    }\n\n\n  std::ofstream out(\"grid-2.svg\");\n  GridOut       grid_out;\n  grid_out.write_svg(triangulation, out);\n  auto info_tria = get_info_triangulation(triangulation);\n\n  std::cout << \"Grid written to grid-2.svg\" << std::endl;\n  std::cout << std::get<0>(info_tria) << \"\\t\" << std::get<1>(info_tria) << \"\\t\"\n            << std::get<2>(info_tria) << \"\\n\";\n}\n\n\n\nvoid\nthird_grid()\n{\n  Triangulation<2> triangulation;\n  const double     left  = -1.0;\n  const double     right = +1.0;\n  GridGenerator::hyper_L(triangulation, left, right, true);\n  std::ofstream out(\"grid-3.svg\");\n  GridOut       grid_out;\n\n  grid_out.write_svg(triangulation, out);\n  std::cout << \"Grid written to grid-3.svg\" << std::endl;\n  auto info_tria = get_info_triangulation(triangulation);\n  std::cout << std::get<0>(info_tria) << \"\\t\" << std::get<1>(info_tria) << \"\\t\"\n            << std::get<2>(info_tria) << \"\\n\";\n\n  std::cout << \"Now refine the grid globally\" << std::endl;\n  const unsigned int initial_global_refinement = 2;\n\n  triangulation.refine_global(initial_global_refinement);\n  std::ofstream out_refined(\"grid-4.svg\");\n\n  grid_out.write_svg(triangulation, out_refined);\n  std::cout << \"Grid written to grid-4.svg\" << std::endl;\n\n\n  std::cout << \"Refine adaptively around the re-entrant corner\"\n            << \"\\n\";\n  const Point<2>     corner(0.0, 0.0);\n  const unsigned int no_refinements{4};\n  for (unsigned int step = 0; step < no_refinements; ++step)\n    {\n      for (auto &cell : triangulation.active_cell_iterators())\n        {\n          for (const auto v : cell->vertex_indices())\n            {\n              const double distance_from_corner =\n                corner.distance(cell->center(v));\n              // std::cout << cell->center(v) << cell->center() << \"\\n\"; //check\n              // about syntax\n              if (std::fabs(distance_from_corner) <= (1.0) / (3.0))\n                {\n                  cell->set_refine_flag();\n                  break;\n                }\n            }\n        }\n      triangulation.execute_coarsening_and_refinement();\n    }\n\n\n  std::ofstream out_refined_locally(\"grid-5.svg\");\n\n  grid_out.write_svg(triangulation, out_refined_locally);\n  std::cout << \"Grid written to grid-5.svg\" << std::endl;\n\n\n  auto info_tria_L = get_info_triangulation(triangulation);\n  std::cout << std::get<0>(info_tria_L) << \"\\t\" << std::get<1>(info_tria_L)\n            << \"\\t\" << std::get<2>(info_tria_L) << \"\\n\";\n}\n\n\n\nvoid\nfourth_grid()\n{\n  Triangulation<2> triangulation;\n  const double     radius = 1.0;\n  const Point<2>   center(0.0, 0.0); // center of the ball\n\n\n  const SphericalManifold<2> manifold(center);\n  GridGenerator::hyper_ball(\n    triangulation,\n    center,\n    radius,\n    true); // spherical manifold set to true on the bdary\n  std::ofstream out(\"grid-Spherical_Manifold_bdary.svg\");\n  GridOut       grid_out;\n\n  std::cout << \"Using Spherical Manifold on the boundary \"\n            << \"\\n\";\n  triangulation.reset_all_manifolds();\n  triangulation.set_all_manifold_ids_on_boundary(0);\n  triangulation.set_manifold(0, manifold);\n  triangulation.refine_global(4);\n\n  grid_out.write_svg(triangulation, out);\n\n\n  //////////////EVERYWHERE\n  Triangulation<2> triangulation_e;\n  GridGenerator::hyper_ball(triangulation_e,\n                            center,\n                            radius,\n                            true); // spherical manifold set to true\n\n  std::ofstream out_e(\"grid-Spherical_Manifold_everywhere.svg\");\n  GridOut       grid_out_e;\n\n  std::cout << \"Using Spherical Manifold everywhere \"\n            << \"\\n\";\n  triangulation_e.reset_all_manifolds();\n  // reenable the manifold:\n  triangulation_e.set_all_manifold_ids(0);\n  triangulation_e.set_manifold(0, manifold);\n  triangulation_e.refine_global(2);\n\n  grid_out_e.write_svg(triangulation_e, out_e);\n\n\n\n  //////////EXCEPT THE CENTER\n  Triangulation<2> triangulation_c;\n  GridGenerator::hyper_ball(triangulation_c, center, radius, true);\n\n  std::ofstream  out_c(\"grid-Spherical_Manifold_everywhere_but_center.svg\");\n  GridOut        grid_out_c;\n  const Point<2> mesh_center;\n  for (const auto &cell : triangulation_c.active_cell_iterators())\n    {\n      if (mesh_center.distance(cell->center()) > cell->diameter() / 10)\n        {\n          cell->set_all_manifold_ids(0);\n        }\n    }\n  std::cout << \"Using Spherical Manifold everywhere but the center\"\n            << \"\\n\";\n  triangulation_c.refine_global(4);\n\n  grid_out_c.write_svg(triangulation_c, out_c);\n}\n\n\n\nint\nmain()\n{\n  first_grid();\n  second_grid();\n  third_grid();\n  fourth_grid();\n}\n", "meta": {"hexsha": "f1b9b202e3f8b56438d3ac5caf05270310d62a68", "size": 7354, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/step-1.cc", "max_stars_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-fdrmrc", "max_stars_repo_head_hexsha": "62ce89931f91be19b4824b9c7064029cd9729311", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/step-1.cc", "max_issues_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-fdrmrc", "max_issues_repo_head_hexsha": "62ce89931f91be19b4824b9c7064029cd9729311", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/step-1.cc", "max_forks_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-fdrmrc", "max_forks_repo_head_hexsha": "62ce89931f91be19b4824b9c7064029cd9729311", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8392156863, "max_line_length": 80, "alphanum_fraction": 0.6150394343, "num_tokens": 1894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.44050822108825927}}
{"text": "#include <cmath>\n#include <exception>\n#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/program_options.hpp>\n\n#include <frovedis.hpp>\n#include <frovedis/core/dvector.hpp>\n#include <frovedis/core/zipped_dvectors.hpp>\n#include <frovedis/matrix/rowmajor_matrix.hpp>\n#include <frovedis/ml/tree/tree_model.hpp>\n\nnamespace po = boost::program_options;\nusing namespace frovedis;\n\ntemplate <typename T>\nvoid show_classification_error_rate(\n  zipped_dvectors<T, T>& zipped, const T num_records\n) {\n  std::cout << \"Error rate: \" << zipped.map(\n    +[] (const T predict, const T label) -> T {\n      return static_cast<T>(label != predict);\n    }\n  ).reduce(add<T>) / num_records * 100 << \"%\" << std::endl;\n}\n\ntemplate <typename T>\nvoid show_regression_errors(\n  zipped_dvectors<T, T>& zipped, const T num_records\n) {\n  const T mae = zipped.map(\n    +[] (const T predict, const T label) -> T {\n      return std::abs(label - predict);\n    }\n  ).reduce(add<T>) / num_records;\n\n  const T mse = zipped.map(\n    +[] (const T predict, const T label) -> T {\n      const T error = label - predict;\n      return error * error;\n    }\n  ).reduce(add<T>) / num_records;\n\n  std::cout << \"MAE:  \" << mae << std::endl;\n  std::cout << \"MSE:  \" << mse << std::endl;\n  std::cout << \"RMSE: \" << std::sqrt(mse) << std::endl;\n}\n\ntemplate <typename T>\nvoid do_validate(\n  const std::vector<T>& predicts, dvector<T>& labels,\n  const tree::algorithm algo\n) {\n  const T num_records = static_cast<T>(predicts.size());\n  auto dpredicts = make_dvector_scatter(predicts);\n  auto zipped = zip(dpredicts, labels);\n\n  switch (algo) {\n  case tree::algorithm::Classification:\n    show_classification_error_rate(zipped, num_records);\n    return;\n  case tree::algorithm::Regression:\n    show_regression_errors(zipped, num_records);\n    return;\n  default:\n    throw std::logic_error(\"invalid tree algorithm\");\n  }\n}\n\ntemplate <typename T>\nvoid do_predict(\n  const std::string& data_path,\n  const std::string& model_path,\n  const std::string& output_path,\n  const std::string& label_path,\n  const bool binary_mode\n) {\n  time_spent timer(DEBUG);\n  decision_tree_model<T> model;\n\n  if (binary_mode) {\n    timer.reset();\n    auto dataset = make_rowmajor_matrix_local_loadbinary<T>(data_path);\n    timer.show(\"load matrix: \");\n    model.loadbinary(model_path);\n    timer.show(\"load model:  \");\n    auto results = model.predict(dataset);\n    timer.show(\"predict:     \");\n    make_dvector_scatter(results).savebinary(output_path);\n    timer.show(\"save result: \");\n\n    if (!label_path.empty()) {\n      timer.reset();\n      auto labels = make_dvector_loadbinary<T>(label_path);\n      timer.show(\"load labels: \");\n      do_validate(results, labels, model.get_algo());\n      timer.show(\"validate:    \");\n    }\n  } else {\n    timer.reset();\n    auto dataset = make_rowmajor_matrix_local_load<T>(data_path);\n    timer.show(\"load matrix: \");\n    model.load(model_path);\n    timer.show(\"load model:  \");\n    auto results = model.predict(dataset);\n    timer.show(\"predict:     \");\n    make_dvector_scatter(results).saveline(output_path);\n    timer.show(\"save result: \");\n\n    if (!label_path.empty()) {\n      timer.reset();\n      auto labels = make_dvector_loadline(label_path).map(\n        +[] (const std::string& line) -> T {\n          return boost::lexical_cast<T>(line);\n        }\n      );\n      timer.show(\"load labels: \");\n      do_validate(results, labels, model.get_algo());\n      timer.show(\"validate:    \");\n    }\n  }\n}\n\ntemplate <typename T>\nvoid do_predict(const po::variables_map& argmap) {\n  do_predict<T>(\n    argmap[\"input\"].as<std::string>(),\n    argmap[\"model\"].as<std::string>(),\n    argmap[\"output\"].as<std::string>(),\n    argmap[\"label\"].as<std::string>(),\n    argmap.count(\"binary\")\n  );\n}\n\npo::variables_map parse(int argc, char** argv) {\n  po::options_description opt_desc(\"\");\n  opt_desc.add_options()\n    (\"help,h\", \"show this help message and exit\");\n\n  po::options_description reqarg_desc(\"required arguments\");\n  reqarg_desc.add_options()\n    (\"input,i\", po::value<std::string>(), \"an input matrix\")\n    (\"model,m\", po::value<std::string>(), \"an input model\")\n    (\"output,o\", po::value<std::string>(), \"an output prediction result\");\n\n  po::options_description optarg_desc(\"optional arguments\");\n  optarg_desc.add_options()\n    (\"label,l\", po::value<std::string>()->default_value(\"\"),\n     \"a correct label for validation\")\n    (\"binary\", \"use binary input/output\")\n    (\"double\", \"use double precision\")\n    (\"verbose\", \"set log-level to DEBUG\")\n    (\"trace\", \"set log-level to TRACE\");\n\n  opt_desc.add(reqarg_desc).add(optarg_desc);\n  po::variables_map argmap;\n  try {\n    po::store(po::command_line_parser(argc, argv)\n                .options(opt_desc)\n//              .allow_unregistered()\n                .run(),\n              argmap);\n    po::notify(argmap);\n  } catch (const po::error_with_option_name& e) {\n    std::cerr << e.what() << std::endl;\n    finalizefrovedis(1);\n  }\n\n  // help message\n  if (argmap.count(\"help\")) {\n    std::cerr << opt_desc;\n    finalizefrovedis(0);\n  }\n\n  // check required arguments\n  bool missing = false;\n  for (const auto opt: reqarg_desc.options()) {\n    const std::string& name = opt->long_name();\n    if (!argmap.count(name)) {\n      std::cerr << \"option '--\" << name << \"' is required\" << std::endl;\n      missing = true;\n    }\n  }\n  if (missing) { finalizefrovedis(1); }\n\n  return argmap;\n}\n\nint main(int argc, char** argv) {\n  use_frovedis use(argc, argv);\n\n  const auto argmap = parse(argc, argv);\n  if (argmap.count(\"verbose\")) { set_loglevel(DEBUG); }\n  if (argmap.count(\"trace\")) { set_loglevel(TRACE); }\n\n  try {\n    if (argmap.count(\"double\")) {\n      do_predict<double>(argmap);\n    } else {\n      do_predict<float>(argmap);\n    }\n  } catch (const std::exception& e) {\n    std::cerr << e.what() << std::endl;\n    finalizefrovedis(1);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "d366ccf80a866a5af6c3912f87aa327975ef2232", "size": 5950, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/tree/predict.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "samples/tree/predict.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "samples/tree/predict.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 27.9342723005, "max_line_length": 74, "alphanum_fraction": 0.6376470588, "num_tokens": 1560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4405082164542449}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2021 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n//#define DEBUG_NOCOLOR\n//#define DEBUG_BEGIN_END_ONLY\n// #define DEBUG_STDOUT\n// #define DEBUG_MESSAGES\n#include \"RotationQuaternion.hpp\"\n\n#include \"siconos_debug.h\"\n#include \"SiconosVector.hpp\"\n#include \"SimpleMatrix.hpp\"\n#include <boost/math/quaternion.hpp>\n\n\nvoid computeRotationMatrix(double q0, double q1, double q2, double q3,\n                           SP::SimpleMatrix rotationMatrix)\n{\n\n  /* Brute force version by multiplication of quaternion\n   */\n  // ::boost::math::quaternion<double>    quatQ(q0, q1, q2, q3);\n  // ::boost::math::quaternion<double>    quatcQ(q0, -q1, -q2, -q3);\n  // ::boost::math::quaternion<double>    quatx(0, 1, 0, 0);\n  // ::boost::math::quaternion<double>    quaty(0, 0, 1, 0);\n  // ::boost::math::quaternion<double>    quatz(0, 0, 0, 1);\n  // ::boost::math::quaternion<double>    quatBuff;\n  // quatBuff = quatQ * quatx * quatcQ;\n  // rotationMatrix->setValue(0, 0, quatBuff.R_component_2());\n  // rotationMatrix->setValue(1, 0, quatBuff.R_component_3());\n  // rotationMatrix->setValue(2, 0, quatBuff.R_component_4());\n  // quatBuff = quatQ * quaty * quatcQ;\n  // rotationMatrix->setValue(0, 1, quatBuff.R_component_2());\n  // rotationMatrix->setValue(1, 1, quatBuff.R_component_3());\n  // rotationMatrix->setValue(2, 1, quatBuff.R_component_4());\n  // quatBuff = quatQ * quatz * quatcQ;\n  // rotationMatrix->setValue(0, 2, quatBuff.R_component_2());\n  // rotationMatrix->setValue(1, 2, quatBuff.R_component_3());\n  // rotationMatrix->setValue(2, 2, quatBuff.R_component_4());\n\n  /* direct computation https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation */\n  rotationMatrix->setValue(0, 0,     q0*q0 +q1*q1 -q2*q2 -q3*q3);\n  rotationMatrix->setValue(0, 1, 2.0*(q1*q2        - q0*q3));\n  rotationMatrix->setValue(0, 2, 2.0*(q1*q3        + q0*q2));\n\n  rotationMatrix->setValue(1, 0, 2.0*(q1*q2        + q0*q3));\n  rotationMatrix->setValue(1, 1,     q0*q0 -q1*q1 +q2*q2 -q3*q3);\n  rotationMatrix->setValue(1, 2, 2.0*(q2*q3        - q0*q1));\n\n  rotationMatrix->setValue(2, 0, 2.0*(q1*q3        - q0*q2));\n  rotationMatrix->setValue(2, 1, 2.0*(q2*q3         + q0*q1));\n  rotationMatrix->setValue(2, 2,     q0*q0 -q1*q1 -q2*q2 +q3*q3);\n}\n\n\n\nvoid quaternionRotate(double q0, double q1, double q2, double q3, SiconosVector& v)\n{\n  DEBUG_BEGIN(\"::quaternionRotate(double q0, double q1, double q2, double q3, SiconosVector& v )\\n\");\n  DEBUG_EXPR(v.display(););\n  DEBUG_PRINTF(\"( q0 = %16.12e,  q1 = %16.12e,  q2= %16.12e,  q3= %16.12e )\\n\", q0,q1,q2,q3);\n  assert(v.size()==3);\n\n  // First way. Using the rotation matrix\n  // SP::SimpleMatrix rotationMatrix(new SimpleMatrix(3,3));\n  // SiconosVector tmp(3);\n  // ::computeRotationMatrix(q0,q1,q2,q3, rotationMatrix);\n  // prod(*rotationMatrix, v, tmp);\n  // v = tmp;\n  // return;\n\n  // Second way. Using the transpose of the rotation matrix\n  // SP::SimpleMatrix rotationMatrix(new SimpleMatrix(3,3));\n  // SiconosVector tmp(3);\n  // ::computeRotationMatrix(q0,-q1,-q2,-q3, rotationMatrix);\n  // prod(v, *rotationMatrix, tmp);\n  // v = tmp;\n\n  // Third way. cross product and axis angle\n  // see http://www.geometrictools.com/Documentation/RotationIssues.pdf\n  // SP::SiconosVector axis(new SiconosVector(3));\n  // double angle = ::axisAngleFromQuaternion(q0,q1,q2,q3, axis);\n  // SiconosVector t(3), tmp(3);\n  // cross_product(*axis,v,t);\n  // cross_product(*axis,t,tmp);\n  // v += sin(angle)*t + (1.0-cos(angle))*tmp;\n\n  // Direct computation with cross product\n  // Works only with unit quaternion\n  SiconosVector t(3), tmp(3);\n  SiconosVector qvect(3);\n  qvect(0)=q1;\n  qvect(1)=q2;\n  qvect(2)=q3;\n  cross_product(qvect,v,t);\n  t *= 2.0;\n  cross_product(qvect,t,tmp);\n  v += tmp;\n  v += q0*t;\n  DEBUG_EXPR(v.display(););\n  DEBUG_END(\"::quaternionRotate(double q0, double q1, double q2, double q3, SP::SiconosVector v )\\n\");\n}\n\nvoid quaternionRotate(double q0, double q1, double q2, double q3, SP::SiconosVector v)\n{\n  ::quaternionRotate(q0, q1, q2, q3, *v);\n}\n\nvoid quaternionRotate(double q0, double q1, double q2, double q3, SP::SimpleMatrix m)\n{\n  DEBUG_BEGIN(\"::quaternionRotate(double q0, double q1, double q2, double q3, SP::SimpleMatrix m )\\n\");\n  DEBUG_EXPR(m->display(););\n  DEBUG_PRINTF(\"( q0 = %16.12e,  q1 = %16.12e,  q2= %16.12e,  q3= %16.12e )\\n\", q0,q1,q2,q3);\n\n  // Direct computation with cross product for each column\n  assert(m->size(0) == 3 && \"::quaternionRotate(double q0, double q1, double q2, double q3, SP::SimpleMatrix m ) m must have 3 rows\");\n  SiconosVector v(3);\n  SiconosVector t(3), tmp(3);\n  SiconosVector qvect(3);\n  qvect(0)=q1;\n  qvect(1)=q2;\n  qvect(2)=q3;\n  for(unsigned int j = 0; j < m->size(1); j++)\n  {\n    v(0) = m->getValue(0,j);\n    v(1) = m->getValue(1,j);\n    v(2) = m->getValue(2,j);\n    cross_product(qvect,v,t);\n    t *= 2.0;\n    cross_product(qvect,t,tmp);\n    v += tmp;\n    v += q0*t;\n    m->setValue(0,j,v(0));\n    m->setValue(1,j,v(1));\n    m->setValue(2,j,v(2));\n  }\n  DEBUG_EXPR(m->display(););\n  DEBUG_END(\"::quaternionRotate(double q0, double q1, double q2, double q3, SP::SimpleMatrix m )\\n\");\n}\n\n\nvoid quaternionRotate(SP::SiconosVector q, SP::SiconosVector v)\n{\n  DEBUG_BEGIN(\"::quaternionRotate(SP::SiconosVector q, SP::SiconosVector v )\\n\");\n  ::quaternionRotate(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6), v);\n  DEBUG_END(\"::quaternionRotate(SP::SiconosVector q, SP::SiconosVector v )\\n\");\n}\n\nvoid quaternionRotate(SP::SiconosVector q, SP::SimpleMatrix m)\n{\n  DEBUG_BEGIN(\"::quaternionRotate(SP::SiconosVector q, SP::SimpleMatrix m )\\n\");\n  ::quaternionRotate(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6),m);\n  DEBUG_END(\"::quaternionRotate(SP::SiconosVector q, SP::SimpleMatrix m)\\n\");\n}\n\nvoid changeFrameAbsToBody(const SiconosVector& q, SiconosVector& v)\n{\n  DEBUG_BEGIN(\"::changeFrameAbsToBody(const SiconosVector& q, SiconosVector& v )\\n\");\n  ::quaternionRotate(q.getValue(3),-q.getValue(4),-q.getValue(5),-q.getValue(6), v);\n  DEBUG_END(\"::changeFrameAbsToBody(const SiconosVector& q, SiconosVector& v )\\n\");\n}\nvoid changeFrameAbsToBody(SP::SiconosVector q, SP::SiconosVector v)\n{\n  DEBUG_BEGIN(\"::changeFrameAbsToBody(SP::SiconosVector q, SP::SiconosVector v )\\n\");\n  ::quaternionRotate(q->getValue(3),-q->getValue(4),-q->getValue(5),-q->getValue(6), v);\n  DEBUG_END(\"::changeFrameAbsToBody(SP::SiconosVector q, SP::SiconosVector v )\\n\");\n}\nvoid changeFrameAbsToBody(SP::SiconosVector q, SP::SimpleMatrix m)\n{\n  DEBUG_BEGIN(\"::changeFrameAbsToBody(SP::SiconosVector q, SP::SimpleMatrix m )\\n\");\n  ::quaternionRotate(q->getValue(3),-q->getValue(4),-q->getValue(5),-q->getValue(6), m);\n  DEBUG_END(\"::changeFrameAbsToBody(SP::SiconosVector q, SP::SimpleMatrix m )\\n\");\n}\n\nvoid changeFrameBodyToAbs(const SiconosVector& q, SiconosVector& v)\n{\n  DEBUG_BEGIN(\"::changeFrameBodyToAbs(const SiconosVector& q, SiconosVector& v )\\n\");\n  ::quaternionRotate(q.getValue(3),q.getValue(4),q.getValue(5),q.getValue(6), v);\n  DEBUG_END(\"::changeFrameBodyToAbs(const SiconosVector& q, SiconosVector& v )\\n\");\n}\nvoid changeFrameBodyToAbs(SP::SiconosVector q, SP::SiconosVector v)\n{\n  DEBUG_BEGIN(\"::changeFrameBodyToAbs(SP::SiconosVector q, SP::SiconosVector v )\\n\");\n  ::quaternionRotate(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6), *v);\n  DEBUG_END(\"::changeFrameBodyToAbs(SP::SiconosVector q, SP::SiconosVector v )\\n\");\n}\nvoid changeFrameBodyToAbs(SP::SiconosVector q, SP::SimpleMatrix m)\n{\n  DEBUG_BEGIN(\"::changeFrameBodyToAbs(SP::SiconosVector q, SP::SimpleMatrix m )\\n\");\n  ::quaternionRotate(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6), m);\n  DEBUG_END(\"::changeFrameBodyToAbs(SP::SiconosVector q, SP::SimpleMatrix m )\\n\");\n}\n\n\n\nvoid computeRotationMatrix(SP::SiconosVector q, SP::SimpleMatrix rotationMatrix)\n{\n  ::computeRotationMatrix(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6),\n                          rotationMatrix);\n}\nvoid computeRotationMatrixTransposed(SP::SiconosVector q, SP::SimpleMatrix rotationMatrix)\n{\n  ::computeRotationMatrix(q->getValue(3),-q->getValue(4),-q->getValue(5),-q->getValue(6),\n                          rotationMatrix);\n}\n\ndouble axisAngleFromQuaternion(double q0, double q1, double q2, double q3, SP::SiconosVector axis)\n{\n  DEBUG_BEGIN(\"axisAngleFromQuaternion(double q0, double q1, double q2, double q3, SP::SiconosVector axis )\\n\");\n  double angle = acos(q0) *2.0;\n  //double f = sin( angle *0.5);\n  double f = sqrt(1-q0*q0); // cheaper than sin ?\n  if(f !=0.0)\n  {\n    axis->setValue(0, q1/f);\n    axis->setValue(1, q2/f);\n    axis->setValue(2, q3/f);\n  }\n  else\n  {\n    axis->zero();\n  }\n  DEBUG_PRINTF(\"angle= %12.8e\\n\", angle);\n  DEBUG_EXPR(axis->display(););\n  DEBUG_END(\"axisAngleFromQuaternion(double q0, double q1, double q2, double q3, SP::SiconosVector axis )\\n\");\n  return angle;\n}\n\ndouble axisAngleFromConfiguration(SP::SiconosVector q, SP::SiconosVector axis)\n{\n  double angle = ::axisAngleFromQuaternion(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6),axis);\n  return angle;\n}\n\nvoid rotationVectorFromQuaternion(double q0, double q1, double q2, double q3, SP::SiconosVector rotationVector)\n{\n  DEBUG_BEGIN(\"rotationVectorFromQuaternion(double q0, double q1, double q2, double q3, SP::SiconosVector rotationVector )\\n\");\n\n  rotationVector->setValue(0, q1);\n  rotationVector->setValue(1, q2);\n  rotationVector->setValue(2, q3);\n\n  double norm_v = sqrt(q1*q1+q2*q2+q3*q3);\n  assert(norm_v <= M_PI);  /* it should be called for a unit quaternion */\n  if(norm_v < 1e-12)\n  {\n    rotationVector->setValue(0, 0.0);\n    rotationVector->setValue(1, 0.0);\n    rotationVector->setValue(2, 0.0);\n  }\n  else\n  {\n    *rotationVector *=  2.0 * asin(norm_v)/norm_v;\n  }\n  DEBUG_EXPR(rotationVector->display(););\n  DEBUG_END(\"rotationVectorFromQuaternion(double q0, double q1, double q2, double q3, SP::SiconosVector rotationVector )\\n\");\n}\n\nvoid rotationVectorFromConfiguration(SP::SiconosVector q, SP::SiconosVector rotationVector)\n{\n  ::rotationVectorFromQuaternion(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6), rotationVector);\n}\n\n\nvoid quaternionFromAxisAngle(SP::SiconosVector axis, double angle, SP::SiconosVector q)\n{\n  q->setValue(3,cos(angle/2.0));\n  q->setValue(4,axis->getValue(0)* sin(angle *0.5));\n  q->setValue(5,axis->getValue(1)* sin(angle *0.5));\n  q->setValue(6,axis->getValue(2)* sin(angle *0.5));\n}\n\nstatic\ndouble sin_x(double x)\n{\n  if(std::abs(x) <= 1e-3)\n  {\n    return 1.0 + x*x / 3.0 + pow(x,4) * 2.0 / 15.0 + pow(x,6) * 17.0 / 315.0 + pow(x,8) * 62.0 / 2835.0;\n  }\n  else\n  {\n    return sin(x)/x;\n  }\n}\n\nvoid quaternionFromRotationVector(SP::SiconosVector rotationVector, SP::SiconosVector q)\n{\n  double angle = sqrt(rotationVector->getValue(0)*rotationVector->getValue(0)+\n                      rotationVector->getValue(1)*rotationVector->getValue(1)+\n                      rotationVector->getValue(2)*rotationVector->getValue(2));\n\n  double f = 0.5 * sin_x(angle *0.5);\n\n  q->setValue(3,cos(angle/2.0));\n  q->setValue(4,rotationVector->getValue(0)* f);\n  q->setValue(5,rotationVector->getValue(1)* f);\n  q->setValue(6,rotationVector->getValue(2)* f);\n}\n\n\ndouble quaternionNorm(const SiconosVector &q)\n{\n  double normq = sqrt(q.getValue(3) * q.getValue(3) +\n                      q.getValue(4) * q.getValue(4) +\n                      q.getValue(5) * q.getValue(5) +\n                      q.getValue(6) * q.getValue(6));\n  return normq;\n}\n\n\n\nvoid normalizeq(SP::SiconosVector q)\n{\n  double normq = sqrt(q->getValue(3) * q->getValue(3) +\n                      q->getValue(4) * q->getValue(4) +\n                      q->getValue(5) * q->getValue(5) +\n                      q->getValue(6) * q->getValue(6));\n  assert(normq > 0);\n  normq = 1.0 / normq;\n  q->setValue(3, q->getValue(3) * normq);\n  q->setValue(4, q->getValue(4) * normq);\n  q->setValue(5, q->getValue(5) * normq);\n  q->setValue(6, q->getValue(6) * normq);\n}\n\nvoid  normalizeq(SiconosVector &q)\n{\n  double normq = sqrt(q.getValue(3) * q.getValue(3) +\n                      q.getValue(4) * q.getValue(4) +\n                      q.getValue(5) * q.getValue(5) +\n                      q.getValue(6) * q.getValue(6));\n  assert(normq > 0);\n  normq = 1.0 / normq;\n  q.setValue(3, q.getValue(3) * normq);\n  q.setValue(4, q.getValue(4) * normq);\n  q.setValue(5, q.getValue(5) * normq);\n  q.setValue(6, q.getValue(6) * normq);\n}\n\nvoid quaternionFromTwistVector(SiconosVector& twist, SiconosVector& q)\n {\n   assert(twist.size() == 6);\n   assert(q.size() == 7);\n   double angle = sqrt(twist.getValue(3)*twist.getValue(3)+\n                       twist.getValue(4)*twist.getValue(4)+\n                       twist.getValue(5)*twist.getValue(5));\n\n   double f = 0.5 * sin_x(angle *0.5);\n\n   q.setValue(3,cos(angle/2.0));\n   q.setValue(4,twist.getValue(3)* f);\n   q.setValue(5,twist.getValue(4)* f);\n   q.setValue(6,twist.getValue(5)* f);\n\n }\nvoid compositionLawLieGroup(const SiconosVector& a, SiconosVector& b, SiconosVector& ab)\n{\n\n  assert(a.size() == 7);\n  assert(b.size() == 7);\n  assert(ab.size()== 7);\n\n  // For the translational component, the composition law is the addition\n  ab.setValue(0,a.getValue(0)+b.getValue(0));\n  ab.setValue(1,a.getValue(1)+b.getValue(1));\n  ab.setValue(2,a.getValue(2)+b.getValue(2));\n\n  // For the quaternion that encodes rotation, the composition law is the quaternion product.\n  ::boost::math::quaternion<double>    quat_a(a.getValue(3), a.getValue(4), a.getValue(5), a.getValue(6));\n  ::boost::math::quaternion<double>    quat_b(b.getValue(3), b.getValue(4), b.getValue(5), b.getValue(6));\n  ::boost::math::quaternion<double>    quat_ab = quat_a * quat_b;\n  ab.setValue(3,quat_ab.R_component_1());\n  ab.setValue(4,quat_ab.R_component_2());\n  ab.setValue(5,quat_ab.R_component_3());\n  ab.setValue(6,quat_ab.R_component_4());\n}\n\nvoid compositionLawLieGroup(const SiconosVector& a, SiconosVector& b)\n{\n\n  assert(a.size() == 7);\n  assert(b.size() == 7);\n\n  // For the translational component, the composition law is the addition\n  b.setValue(0,a.getValue(0)+b.getValue(0));\n  b.setValue(1,a.getValue(1)+b.getValue(1));\n  b.setValue(2,a.getValue(2)+b.getValue(2));\n\n  // For the quaternion that encodes rotation, the composition law is the quaternion product.\n  ::boost::math::quaternion<double>    quat_a(a.getValue(3), a.getValue(4), a.getValue(5), a.getValue(6));\n  ::boost::math::quaternion<double>    quat_b(b.getValue(3), b.getValue(4), b.getValue(5), b.getValue(6));\n  ::boost::math::quaternion<double>    quat_ab = quat_a * quat_b;\n  b.setValue(3,quat_ab.R_component_1());\n  b.setValue(4,quat_ab.R_component_2());\n  b.setValue(5,quat_ab.R_component_3());\n  b.setValue(6,quat_ab.R_component_4());\n  //normalizeq(b);\n}\n", "meta": {"hexsha": "bfd508808cc86907e52cf1e6e64f16e12b3aa3e4", "size": 15321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosTools/RotationQuaternion.cpp", "max_stars_repo_name": "BuildJet/siconos", "max_stars_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "kernel/src/utils/SiconosTools/RotationQuaternion.cpp", "max_issues_repo_name": "BuildJet/siconos", "max_issues_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "kernel/src/utils/SiconosTools/RotationQuaternion.cpp", "max_forks_repo_name": "BuildJet/siconos", "max_forks_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 37.0968523002, "max_line_length": 134, "alphanum_fraction": 0.6656223484, "num_tokens": 4930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.44050821009481284}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_AITOFF_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_AITOFF_HPP\n\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\n// This file is automatically generated. DO NOT EDIT.\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 4.9.1\n\n// Original copyright notice:\n\n// Purpose:  Implementation of the aitoff (Aitoff) and wintri (Winkel Tripel)\n// projections.\n// Author:   Gerald Evenden\n// Copyright (c) 1995, Gerald Evenden\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/extensions/gis/projections/impl/base_static.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace aitoff\n    {\n\n            struct par_aitoff\n            {\n                double    cosphi1;\n                int        mode;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_aitoff_spheroid : public base_t_fi<base_aitoff_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_aitoff m_proj_parm;\n\n                inline base_aitoff_spheroid(const Parameters& par)\n                    : base_t_fi<base_aitoff_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    double c, d;\n\n                    if((d = acos(cos(lp_lat) * cos(c = 0.5 * lp_lon)))) {/* basic Aitoff */\n                        xy_x = 2. * d * cos(lp_lat) * sin(c) * (xy_y = 1. / sin(d));\n                        xy_y *= d * sin(lp_lat);\n                    } else\n                        xy_x = xy_y = 0.;\n                    if (this->m_proj_parm.mode) { /* Winkel Tripel */\n                        xy_x = (xy_x + lp_lon * this->m_proj_parm.cosphi1) * 0.5;\n                        xy_y = (xy_y + lp_lat) * 0.5;\n                    }\n                }\n                /***********************************************************************************\n                *\n                * Inverse functions added by Drazen Tutic and Lovro Gradiser based on paper:\n                *\n                * I.Özbug Biklirici and Cengizhan Ipbüker. A General Algorithm for the Inverse\n                * Transformation of Map Projections Using Jacobian Matrices. In Proceedings of the\n                * Third International Symposium Mathematical & Computational Applications,\n                * pages 175{182, Turkey, September 2002.\n                *\n                * Expected accuracy is defined by EPSILON = 1e-12. Should be appropriate for\n                * most applications of Aitoff and Winkel Tripel projections.\n                *\n                * Longitudes of 180W and 180E can be mixed in solution obtained.\n                *\n                * Inverse for Aitoff projection in poles is undefined, longitude value of 0 is assumed.\n                *\n                * Contact : dtutic@geof.hr\n                * Date: 2015-02-16\n                *\n                ************************************************************************************/\n\n                // INVERSE(s_inverse)  sphere\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\n                {\n                        int iter, MAXITER = 10, round = 0, MAXROUND = 20;\n                    double EPSILON = 1e-12, D, C, f1, f2, f1p, f1l, f2p, f2l, dp, dl, sl, sp, cp, cl, x, y;\n\n                    if ((fabs(xy_x) < EPSILON) && (fabs(xy_y) < EPSILON )) { lp_lat = 0.; lp_lon = 0.; return; }\n\n                    /* intial values for Newton-Raphson method */\n                    lp_lat = xy_y; lp_lon = xy_x;\n                    do {\n                        iter = 0;\n                        do {\n                            sl = sin(lp_lon * 0.5); cl = cos(lp_lon * 0.5);\n                            sp = sin(lp_lat); cp = cos(lp_lat);\n                            D = cp * cl;\n                                   C = 1. - D * D;\n                            D = acos(D) / pow(C, 1.5);\n                                   f1 = 2. * D * C * cp * sl;\n                                   f2 = D * C * sp;\n                                   f1p = 2.* (sl * cl * sp * cp / C - D * sp * sl);\n                                   f1l = cp * cp * sl * sl / C + D * cp * cl * sp * sp;\n                                f2p = sp * sp * cl / C + D * sl * sl * cp;\n                                  f2l = 0.5 * (sp * cp * sl / C - D * sp * cp * cp * sl * cl);\n                                  if (this->m_proj_parm.mode) { /* Winkel Tripel */\n                                f1 = 0.5 * (f1 + lp_lon * this->m_proj_parm.cosphi1);\n                                f2 = 0.5 * (f2 + lp_lat);\n                                f1p *= 0.5;\n                                f1l = 0.5 * (f1l + this->m_proj_parm.cosphi1);\n                                f2p = 0.5 * (f2p + 1.);\n                                f2l *= 0.5;\n                            }\n                            f1 -= xy_x; f2 -= xy_y;\n                            dl = (f2 * f1p - f1 * f2p) / (dp = f1p * f2l - f2p * f1l);\n                            dp = (f1 * f2l - f2 * f1l) / dp;\n                            while (dl > geometry::math::pi<double>()) dl -= geometry::math::pi<double>(); /* set to interval [-geometry::math::pi<double>(), geometry::math::pi<double>()]  */\n                            while (dl < -geometry::math::pi<double>()) dl += geometry::math::pi<double>(); /* set to interval [-geometry::math::pi<double>(), geometry::math::pi<double>()]  */\n                            lp_lat -= dp;    lp_lon -= dl;\n                        } while ((fabs(dp) > EPSILON || fabs(dl) > EPSILON) && (iter++ < MAXITER));\n                        if (lp_lat > geometry::math::two_pi<double>()) lp_lat -= 2.*(lp_lat-geometry::math::two_pi<double>()); /* correct if symmetrical solution for Aitoff */\n                        if (lp_lat < -geometry::math::two_pi<double>()) lp_lat -= 2.*(lp_lat+geometry::math::two_pi<double>()); /* correct if symmetrical solution for Aitoff */\n                        if ((fabs(fabs(lp_lat) - geometry::math::two_pi<double>()) < EPSILON) && (!this->m_proj_parm.mode)) lp_lon = 0.; /* if pole in Aitoff, return longitude of 0 */\n\n                        /* calculate x,y coordinates with solution obtained */\n                        if((D = acos(cos(lp_lat) * cos(C = 0.5 * lp_lon)))) {/* Aitoff */\n                            x = 2. * D * cos(lp_lat) * sin(C) * (y = 1. / sin(D));\n                            y *= D * sin(lp_lat);\n                        } else\n                            x = y = 0.;\n                        if (this->m_proj_parm.mode) { /* Winkel Tripel */\n                            x = (x + lp_lon * this->m_proj_parm.cosphi1) * 0.5;\n                            y = (y + lp_lat) * 0.5;\n                        }\n                    /* if too far from given values of x,y, repeat with better approximation of phi,lam */\n                    } while (((fabs(xy_x-x) > EPSILON) || (fabs(xy_y-y) > EPSILON)) && (round++ < MAXROUND));\n\n                    if (iter == MAXITER && round == MAXROUND) fprintf(stderr, \"Warning: Accuracy of 1e-12 not reached. Last increments: dlat=%e and dlon=%e\\n\", dp, dl);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"aitoff_spheroid\";\n                }\n\n            };\n\n            template <typename Parameters>\n            void setup(Parameters& par, par_aitoff& proj_parm) \n            {\n                boost::ignore_unused(proj_parm);\n                par.es = 0.;\n            }\n\n\n            // Aitoff\n            template <typename Parameters>\n            void setup_aitoff(Parameters& par, par_aitoff& proj_parm)\n            {\n                proj_parm.mode = 0;\n                setup(par, proj_parm);\n            }\n\n            // Winkel Tripel\n            template <typename Parameters>\n            void setup_wintri(Parameters& par, par_aitoff& proj_parm)\n            {\n                proj_parm.mode = 1;\n                if (pj_param(par.params, \"tlat_1\").i)\n                    {\n                    if ((proj_parm.cosphi1 = cos(pj_param(par.params, \"rlat_1\").f)) == 0.)\n                        throw proj_exception(-22);\n                    }\n                else /* 50d28' or acos(2/pi) */\n                    proj_parm.cosphi1 = 0.636619772367581343;\n                setup(par, proj_parm);\n            }\n\n        }} // namespace detail::aitoff\n    #endif // doxygen\n\n    /*!\n        \\brief Aitoff projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Miscellaneous\n         - Spheroid\n        \\par Example\n        \\image html ex_aitoff.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct aitoff_spheroid : public detail::aitoff::base_aitoff_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline aitoff_spheroid(const Parameters& par) : detail::aitoff::base_aitoff_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::aitoff::setup_aitoff(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Winkel Tripel projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Miscellaneous\n         - Spheroid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel (degrees)\n        \\par Example\n        \\image html ex_wintri.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct wintri_spheroid : public detail::aitoff::base_aitoff_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline wintri_spheroid(const Parameters& par) : detail::aitoff::base_aitoff_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::aitoff::setup_wintri(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Factory entry(s)\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class aitoff_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<aitoff_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class wintri_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<wintri_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void aitoff_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"aitoff\", new aitoff_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"wintri\", new wintri_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_AITOFF_HPP\n\n", "meta": {"hexsha": "f784f49db760a65052c35d35ba91d73101cbac2c", "size": 14251, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/aitoff.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T05:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T05:02:05.000Z", "max_issues_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/aitoff.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/aitoff.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-04T10:55:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T18:52:06.000Z", "avg_line_length": 47.3455149502, "max_line_length": 191, "alphanum_fraction": 0.5427689285, "num_tokens": 3240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4405082100948128}}
{"text": "//\n// Created by Standard on 17/04/2021.\n//\n#include \"MTTensor.h\"\n#include \"gnuplot-iostream.h\"\n#include <iostream>\n#include <boost/tuple/tuple.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/program_options.hpp>\n#include \"Parser.h\"\n#include <fstream>\n#include <strstream>\n#include <algorithm>\n#include <cmath>\n#include <boost/filesystem.hpp>\n\nstruct measure{\n    double val{nan(\"\")};\n    double error{0};\n};\n\nconstexpr double mu0 = M_PI*4e-7;\n\nmeasure get_rho(double z_real, double z_imag, double z_var, double freq);\nmeasure get_phi(double z_real, double z_imag, double z_var);\n\nboost::program_options::options_description parse_cmdline(int argc, char *argv[], boost::program_options::variables_map& p_vm);\nstd::string getFileContents(std::ifstream&);\n\nint main(int argc, char* argv[]){\n    try {\n        // program configuration\n        boost::program_options::variables_map vm;\n        auto desc = parse_cmdline(argc, argv, vm);\n        if (vm.count(\"help\")) {\n            std::cout << desc << std::endl;\n            return 0;\n        }\n        auto fileName = vm[\"in-path\"].as<std::string>();\n        auto pathObject = boost::filesystem::path(fileName);\n        std::cout << \"handling file: \" << pathObject.filename().string() << \"\\n\";\n        std::ifstream is;\n        is.open(fileName);\n        if(!is.is_open())throw std::runtime_error(\"Cannot open file \" + fileName+ \"\\n\");\n        std::string fileContents = getFileContents(is);\n        is.close();\n        MTparser::Parser p;\n        p.parse(fileContents);\n        auto skip_string = p.get_option_list_for(\">HEAD\")[\"EMPTY\"];\n        std::cout << \"skip_string: \" << skip_string << \"\\n\";\n        auto edi_contents = p.get();\n        MTparser::Option_list ol;\n        MTparser::Data_set ds;\n//        for (auto it=edi_contents.begin();it!=edi_contents.end();it++) {\n//            std::cout << it->first << \":\\n\\toption list:\\n\";\n//            ol = p.get_option_list_for(it->first);\n//            for (auto oit = ol.begin(); oit != ol.end(); oit++) {\n//                std::cout << \"\\t\\t\" << oit->first << \"==\" << oit->second << std::endl;\n//            }\n//        }\n\n        Gnuplot gp;\n        auto freq = MTparser::dataset2double(p.get_data_set_for(\">FREQ\"), skip_string);\n        // OFF-DIAG\n        auto zxyr = MTparser::dataset2double(p.get_data_set_for(\">ZXYR\"), skip_string);\n        auto zyxr = MTparser::dataset2double(p.get_data_set_for(\">ZYXR\"), skip_string);\n        auto zxyi = MTparser::dataset2double(p.get_data_set_for(\">ZXYI\"), skip_string);\n        auto zyxi = MTparser::dataset2double(p.get_data_set_for(\">ZYXI\"), skip_string);\n        // MAIN-DIAG\n        auto zxxr = MTparser::dataset2double(p.get_data_set_for(\">ZXXR\"), skip_string);\n        auto zyyr = MTparser::dataset2double(p.get_data_set_for(\">ZYYR\"), skip_string);\n        auto zxxi = MTparser::dataset2double(p.get_data_set_for(\">ZXXI\"), skip_string);\n        auto zyyi = MTparser::dataset2double(p.get_data_set_for(\">ZYYI\"), skip_string);\n\n        auto zxyv = MTparser::dataset2double(p.get_data_set_for(\">ZXY.VAR\"), skip_string);\n        auto zyxv = MTparser::dataset2double(p.get_data_set_for(\">ZYX.VAR\"), skip_string);\n        auto zxxv = MTparser::dataset2double(p.get_data_set_for(\">ZXX.VAR\"), skip_string);\n        auto zyyv = MTparser::dataset2double(p.get_data_set_for(\">ZYY.VAR\"), skip_string);\n\n        std::vector<double> zxys,zyxs,zxxs,zyys;\n        for (auto v : zxyv) zxys.push_back(std::sqrt(v));\n        for (auto v : zyxv) zyxs.push_back(std::sqrt(v));\n        for (auto v : zxxv) zxxs.push_back(std::sqrt(v));\n        for (auto v : zyyv) zyys.push_back(std::sqrt(v));\n\n\n        auto title = pathObject.filename().string();\n\n        auto pos = title.find('_');\n        if(pos!=std::string::npos)title.insert(pos,\"\\\\\");\n        gp << \"set term qt enhanced 'Times-Roman, 9'\\n\";\n        gp << \"set title '\" + title +\"'\\n\";\n        gp << \"unset key\\n\";\n        gp << \"set multiplot layout 2,2\\n\";\n        gp << \"set logscale x\\n\";\n//        gp << \"set logscale y\\n\";\n        if (false) {\n            gp << \"set xlabel 'Frequency (Hz)'\\n\";\n            gp << \"set ylabel 'Impedance (Ohm)'\\n\";\n\n            // XX\n            gp << \"set title '\" + title + \"-XX'\\n\";\n            gp << \"plot \"\n               << \"'-' with errorbars pt 3 lc rgb '#F0BC42' title 're(z_{xx})', \"\n               << \"'-' with errorbars pt 4 lc rgb '#8E1F2F' title 'im(z_{xx})'\"\n               << \"\\n\";\n            gp.send1d(std::make_tuple(freq, zxxr, zxxs));\n            gp.send1d(std::make_tuple(freq, zxxi, zxxs));\n            // XY\n            gp << \"set title '\" + title + \"-XY'\\n\";\n            gp << \"plot \"\n               << \"'-' with errorbars pt 3 lc rgb '#F0BC42' title 're(z_{xy})', \"\n               << \"'-' with errorbars pt 4 lc rgb '#8E1F2F' title 'im(z_{xy})'\"\n               << \"\\n\";\n            gp.send1d(std::make_tuple(freq, zxyr, zxys));\n            gp.send1d(std::make_tuple(freq, zxyi, zxys));\n            // YX\n            gp << \"set title '\" + title + \"-YX'\\n\";\n            gp << \"plot \"\n               << \"'-' with errorbars pt 3 lc rgb '#F0BC42' title 're(z_{yx})', \"\n               << \"'-' with errorbars pt 4 lc rgb '#8E1F2F' title 'im(z_{yx})'\"\n               << \"\\n\";\n            gp.send1d(std::make_tuple(freq, zyxr, zyxs));\n            gp.send1d(std::make_tuple(freq, zyxi, zyxs));\n            // YY\n            gp << \"set title '\" + title + \"-YY'\\n\";\n            gp << \"plot \"\n               << \"'-' with errorbars pt 3 lc rgb '#F0BC42' title 're(z_{yy})', \"\n               << \"'-' with errorbars pt 4 lc rgb '#8E1F2F' title 'im(z_{yy})'\"\n               << \"\\n\";\n            gp.send1d(std::make_tuple(freq, zyyr, zyys));\n            gp.send1d(std::make_tuple(freq, zyyi, zyys));\n        } else {\n            std::vector<double> rhoxx, srhoxx,phixx, sphixx;\n            for(int i=0;i<zxxr.size();++i){\n                auto this_rho = get_rho(zxxr[i],zxxi[i],zxxv[i],freq[i]);\n                rhoxx.push_back(this_rho.val);\n                srhoxx.push_back(this_rho.error);\n                auto this_phi = get_phi(zxxr[i],zxxi[i],zxxv[i]);\n                phixx.push_back(this_phi.val);\n                sphixx.push_back(this_phi.error);\n            }\n\n            std::vector<double> rhoxy, srhoxy,phixy, sphixy;\n            for(int i=0;i<zxyr.size();++i){\n                auto this_rho = get_rho(zxyr[i],zxyi[i],zxyv[i],freq[i]);\n                rhoxy.push_back(this_rho.val);\n                srhoxy.push_back(this_rho.error);\n                auto this_phi = get_phi(zxyr[i],zxyi[i],zxyv[i]);\n                phixy.push_back(this_phi.val);\n                sphixy.push_back(this_phi.error);\n            }\n\n            std::vector<double> rhoyx, srhoyx,phiyx, sphiyx;\n            for(int i=0;i<zyxr.size();++i){\n                auto this_rho = get_rho(zyxr[i],zyxi[i],zyxv[i],freq[i]);\n                rhoyx.push_back(this_rho.val);\n                srhoyx.push_back(this_rho.error);\n                auto this_phi = get_phi(zyxr[i],zyxi[i],zyxv[i]);\n                phiyx.push_back(this_phi.val);\n                sphiyx.push_back(this_phi.error);\n            }\n\n            std::vector<double> rhoyy, srhoyy,phiyy, sphiyy;\n            for(int i=0;i<zyyr.size();++i){\n                auto this_rho = get_rho(zyyr[i],zyyi[i],zyyv[i],freq[i]);\n                rhoyy.push_back(this_rho.val);\n                srhoyy.push_back(this_rho.error);\n                auto this_phi = get_phi(zyyr[i],zyyi[i],zyyv[i]);\n                phiyy.push_back(this_phi.val);\n                sphiyy.push_back(this_phi.error);\n            }\n            \n            gp << \"set xlabel 'Frequency (Hz)'\\n\";\n            gp << \"set y2tics -180, 60\\n\";\n            gp << \"set y2range [-180:180]\\n\";\n            gp << \"set ytics nomirror\\n\";\n            gp << \"set logscale y\\n\";\n            gp << \"set ylabel '{/Symbol r}_{app} ({/Symbol W}m)'\\n\";\n            gp << \"set y2label '{/Symbol F} ({^0})'\\n\";\n\n            gp << \"plot \"\n               <<\"'-' with errorbars pt 4 lc rgb '#8E1F2F' axis x1y1,\"\n               <<\"'-' with errorbars pt 3 lc rgb '#F0BC42' axis x1y2\\n\";\n            gp.send1d(std::make_tuple(freq,rhoxx,srhoxx));\n            gp.send1d(std::make_tuple(freq,phixx,sphixx));\n\n            gp << \"plot \"\n               <<\"'-' with errorbars pt 4 lc rgb '#8E1F2F' axis x1y1,\"\n               <<\"'-' with errorbars pt 3 lc rgb '#F0BC42' axis x1y2\\n\";\n            gp.send1d(std::make_tuple(freq,rhoxy,srhoxy));\n            gp.send1d(std::make_tuple(freq,phixy,sphixy));\n\n            gp << \"plot \"\n               <<\"'-' with errorbars pt 4 lc rgb '#8E1F2F' axis x1y1,\"\n               <<\"'-' with errorbars pt 3 lc rgb '#F0BC42' axis x1y2\\n\";\n            gp.send1d(std::make_tuple(freq,rhoyx,srhoyx));\n            gp.send1d(std::make_tuple(freq,phiyx,sphiyx));\n\n            gp << \"plot \"\n               <<\"'-' with errorbars pt 4 lc rgb '#8E1F2F' axis x1y1,\"\n               <<\"'-' with errorbars pt 3 lc rgb '#F0BC42' axis x1y2\\n\";\n            gp.send1d(std::make_tuple(freq,rhoyy,srhoyy));\n            gp.send1d(std::make_tuple(freq,phiyy,sphiyy));\n        }\n\n        return 0;\n    }\n    catch (std::exception &e){\n        std::cout << \"Error: \" << e.what() <<\"\\n\";\n        return 1;\n    }\n    catch(...){\n        std::cerr << \"Unhandled exception. Quit.\\n\";\n        return 2;\n    }\n    return 0;\n}\n\n\n\n\n\n\nboost::program_options::options_description parse_cmdline(int argc, char *argv[], boost::program_options::variables_map& p_vm){\n    namespace po = boost::program_options;\n    po::options_description generic(\"Generic options\");\n    generic.add_options()\n            (\"help,h\", \"display this message and exit.\")\n            (\"in-path,i\", po::value<std::string>(), \"PATH to the input .edi file.\")\n            (\"out-path, o\", po::value<std::string>()->default_value(\"./\"), \"Where I save plots.\");\n    po::store(po::parse_command_line(argc, argv, generic), p_vm);\n    po::notify(p_vm);\n    return generic;\n}\n\nstd::string getFileContents(std::ifstream& input){\n    std::ostrstream sstr;\n    sstr << input.rdbuf();\n    return sstr.str();\n}\n\n\nmeasure get_rho(double z_real, double z_imag, double z_var, double freq){\n    auto omega = 2*M_PI*freq;\n    double rho = (z_real*z_real + z_imag*z_imag)/(mu0*omega);\n    double sigma_z = sqrt(z_var);\n    double sigma_rho = 2*sigma_z*sqrt(pow(z_real+z_imag,2))/(mu0*omega);\n//            double sigma_phi = sqrt(\n//            pow((z_imag/(z_real*z_real + z_imag*z_imag))*sigma_z,2) +\n//            pow((-z_real/(z_real*z_real + z_imag*z_imag))*sigma_z,2)\n//    );\n    return {rho,sigma_rho};\n}\nmeasure get_phi(double z_real, double z_imag, double z_var){\n    double phi = atan2(z_imag,z_real);\n    double sigma_z = sqrt(z_var);\n    double sigma_phi = sqrt(\n            pow((z_imag/(z_real*z_real + z_imag*z_imag))*sigma_z,2) +\n            pow((-z_real/(z_real*z_real + z_imag*z_imag))*sigma_z,2)\n    );\n    return {phi*180/M_PI, sigma_phi*180/M_PI};\n}", "meta": {"hexsha": "cbed0b37ae4cdd5489c3a6174874960e8b5e6104", "size": 10943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ediNaivePlot.cpp", "max_stars_repo_name": "oLazy/MTParser", "max_stars_repo_head_hexsha": "ced71f29f5a9643520f29e1f18210ae6fe422b31", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ediNaivePlot.cpp", "max_issues_repo_name": "oLazy/MTParser", "max_issues_repo_head_hexsha": "ced71f29f5a9643520f29e1f18210ae6fe422b31", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ediNaivePlot.cpp", "max_forks_repo_name": "oLazy/MTParser", "max_forks_repo_head_hexsha": "ced71f29f5a9643520f29e1f18210ae6fe422b31", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.608365019, "max_line_length": 127, "alphanum_fraction": 0.5500319839, "num_tokens": 3092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4405082037353805}}
{"text": "#ifndef CEGO_H\n#define CEGO_H\n\n#include <memory>\n#include <random>\n#include <algorithm>\n#include <numeric>\n#include <vector>\n#include <cassert>\n#include <iostream>\n#include <iterator>\n#include <functional>\n#include <tuple>\n#include <map>\n#include <string>\n#include <sstream>\n#include <stdexcept>\n#include <cassert>\n#include <future>       // std::packaged_task, std::future\n#include <thread>       // std::thread, std::this_thread::sleep_for\n\n#include <Eigen/Dense>\n#include \"CEGO/datatypes.hpp\"\n#include \"CEGO/utilities.hpp\"\n#include \"CEGO/lhs.hpp\"\n\n#include \"CEGO/evolvers/evolvers.hpp\"\n\n#include \"CEGO/concurrentqueue.h\"\n#include \"ThreadPool.h\"\n\n#include \"nlohmann/json.hpp\"\n\nnamespace CEGO{\n\n    struct Result {\n        Eigen::ArrayXd c;\n        double ssq;\n        Result() {};\n        Result(Eigen::ArrayXd &&c, double &&ssq) : c(c), ssq(ssq) {};\n    };\n\n    /// Return Mersenne twister generator\n    inline std::mt19937 get_gen(){\n        std::random_device rd;\n        return std::mt19937(rd());\n    };\n\n    template<class T>\n    inline std::string vec2string(const std::vector<T> &v, const std::string &sep = \", \") {\n        using std::to_string;\n        std::stringstream ss;\n        for (auto &&el : v)\n            ss << to_string(el) << sep;\n        return ss.str();\n    }\n\n    inline std::string vec2string(const std::vector<std::vector<double> > &v, const std::string &sep = \", \") {\n        std::stringstream ss;\n        for (auto &el : v)\n            ss << to_string(el) << sep;\n        return ss.str();\n    }\n\n    /// Generate a random population of individuals\n    template<typename T>\n    Population random_population(const std::vector<CEGO::Bound> bounds, std::size_t count, const CostFunction &cost_function) \n    {\n        auto length_ind = bounds.size();\n        auto gen = get_gen();\n        Population out; out.reserve(count);\n        for (std::size_t i = 0; i < count; ++i) {\n            std::vector<T> c; c.reserve(length_ind);\n            for (std::size_t j = 0; j < length_ind; ++j) {\n                auto &&bound = bounds[j];\n                double d = 0; int integer = 0;\n                bound.gen_uniform(gen, d, integer);\n\n                switch (bound.m_lower.type) {\n                case CEGO::numberish::types::DOUBLE:\n                    c.emplace_back(d); break;\n                case CEGO::numberish::types::INT:\n                    c.emplace_back(integer); break;\n                }\n            }\n            assert(c.size() == length_ind);\n            out.emplace_back(pIndividual(new NumericalIndividual<T>(std::move(c), cost_function)));\n        }\n        return out;\n    }\n\n    /// Generate a population of individuals with the use of Latin-Hypercube sampling\n    template<typename T>\n    Population LHS_population(const std::vector<CEGO::Bound> bounds, std::size_t count, const CostFunction &cost_function)\n    {\n        // Generate the set of floating parameters in [0,1]\n        Eigen::ArrayXXd population = LHS_samples(count, bounds.size());\n\n        auto length_ind = bounds.size();\n        auto gen = get_gen();\n        Population out; out.reserve(count);\n        for (std::size_t i = 0; i < count; ++i) {\n            std::vector<T> c; c.reserve(length_ind);\n            for (std::size_t j = 0; j < length_ind; ++j) {\n                auto &&bound = bounds[j];\n\n                switch (bound.m_lower.type) {\n                case CEGO::numberish::types::DOUBLE:\n                {\n                    double w = population(i,j);\n                    c.emplace_back(bound.m_lower.as_double()*w + bound.m_upper.as_double()*(1-w)); break;\n                }\n                case CEGO::numberish::types::INT:{\n                    double w = population(i, j);\n                    c.emplace_back(int(round(bound.m_lower.as_int()*w + bound.m_upper.as_int()*(1 - w)))); break;\n                }\n                }\n            }\n            assert(c.size() == length_ind);\n            out.emplace_back(pIndividual(new NumericalIndividual<T>(std::move(c), cost_function)));\n        }\n        return out;\n    }\n    \n    enum class LoggingScheme { none = 0, all, custom };\n    enum class FilterOptions { accept, reject };\n    enum class GenerationOptions { LHS, random };\n\n    template<typename T>\n    class Layers {\n        \n    private:\n        std::vector<Population> m_layers;\n        std::size_t m_generation = 0;\n        moodycamel::ConcurrentQueue<Result> result_queue;\n        \n        void initialize_layers() {\n\n            // Generate all the individuals serially(!)\n            MutantVector mutants;\n            for (auto i = 0; i < Nlayers; ++i) {\n                auto generator = (m_generation_flag == GenerationOptions::LHS) ? LHS_population<T> : random_population<T>;\n                for (auto && ind : generator(m_bounds, Npop_size, m_cost_function)) {\n                    mutants.emplace_back(std::make_pair(i, std::move(ind)));\n                }\n            }\n\n            // Evaluate all of the layers and individuals (in parallel, if desired)\n            evaluate_mutants(mutants);\n\n            // Recollect the individuals into layers, again in serial\n            m_layers.resize(Nlayers);\n            for (auto &&mut : mutants) {\n                auto i = std::get<0>(mut);\n                m_layers[i].emplace_back(std::move(std::get<1>(mut)));\n            }\n\n            // Sort all of the layers\n            sort_all_layers();\n        };\n        std::unique_ptr<ThreadPool> m_pool;\n        LoggingScheme m_log_scheme = LoggingScheme::none;\n        std::function<FilterOptions(const Result &)> m_filter_function; \n        std::unique_ptr<AbstractEvolver<T> > m_evolver; ///< The functor that is to be used to evolve a layer\n        std::vector<Bound> m_bounds;\n        GenerationOptions m_generation_flag = GenerationOptions::random;\n        CostFunction m_cost_function;\n        std::size_t m_Nelite = 2;\n    public:\n        \n        bool parallel = false;\n        bool print_chunk_times = false;\n        std::size_t parallel_threads = 6;\n        std::size_t Nind_size, Npop_size, Nlayers, age_gap;\n\n        Layers(const std::function<double(const std::vector<T>&)> &function, std::size_t Nind_size, std::size_t Npop_size, std::size_t Nlayers, std::size_t age_gap = 5)\n            : Nind_size(Nind_size), Npop_size(Npop_size), Nlayers(Nlayers), age_gap(age_gap){\n\n            m_cost_function = [function](const CEGO::AbstractIndividual *pind) {\n                const std::vector<T> &c = static_cast<const CEGO::NumericalIndividual<T>*>(pind)->get_coefficients();\n                return function(c);\n            };\n        };\n\n        /// Constructor into which is passed a CostFunction and information about the layers\n        Layers(CostFunction &function, std::size_t Nind_size, std::size_t Npop_size, std::size_t Nlayers, std::size_t age_gap = 5) \n            : Nind_size(Nind_size), Npop_size(Npop_size), Nlayers(Nlayers), age_gap(age_gap), m_cost_function(function){ };\n\n        /// Specify the logging scheme that is to be employed\n        void set_logging_scheme(LoggingScheme scheme){ m_log_scheme = scheme; }\n\n        /// Get the logging scheme in use\n        LoggingScheme get_logging_scheme() { return m_log_scheme; }\n\n        /// Set the filtering function that should be used\n        void set_filtering_function(const std::function<FilterOptions(const Result &)> &f){ m_filter_function = f; }\n    \n        /// Set the bounds on each element in the individual.  If a one-element vector, the same bounds are used for each parameter\n        void set_bounds(const std::vector<Bound> &bounds){ m_bounds = bounds; };\n\n        /// Get the bounds applied to each element in the individual\n        const std::vector<Bound > & get_bounds (){ return m_bounds; };\n\n        /// Get the flags for the evolver in JSON format\n        const nlohmann::json get_evolver_flags() const {\n            if (m_evolver == nullptr) {\n                throw std::invalid_argument(\"Evolver has not been selected yet!\");\n            }\n            return m_evolver->get_flags();\n        }\n\n        /// Set the flags for the evolver in JSON format\n        const void set_evolver_flags(const nlohmann::json &flags) const {\n            m_evolver->set_flags(flags);\n        }\n\n        /// Pick one of the builtin evolvers\n        void set_builtin_evolver(BuiltinEvolvers e) {\n            switch (e) {\n            case BuiltinEvolvers::differential_evolution:\n                m_evolver.reset(new DE1BinEvolver<T>); break;\n            default:\n                throw std::invalid_argument(\"Invalid builtin evolver\");\n            }\n        }\n\n        /// Get the cost function that is being used currently\n        const CostFunction &get_cost_function() {\n            return m_cost_function;\n        }\n\n        /// Set the flag to determine whether LHS or random (or other) is to be used to generate the population\n        void set_generation_mode(GenerationOptions flag) {\n            m_generation_flag = flag;\n        }\n\n        /// Get the flag to determine whether LHS or random is to be used to generate the population\n        GenerationOptions get_generation_mode() {\n            return m_generation_flag;\n        }\n    \n        /** Iterate over the layers and find individuals that are too old for the given layer\n         * \n         * First try to see if the elderly individual dominates any individual in a layer with a higher age limit\n         * If it does, replace the individual in the higher age limit layer\n         */\n        void graduate_elderly_individuals() {\n\n            // Iterate backwards through the layers, starting at the N-1 layer, since the \n            // last layer has an infinite age limit, and you cannot age out of the \n            // highest age limit layer\n            for (int ilayer = static_cast<int>(m_layers.size())-2; ilayer >= 0; --ilayer) {\n\n                double age_threshold = static_cast<double>(age_gap*pow(2, ilayer));\n                auto &this_layer = m_layers[ilayer];\n\n                // Iterate backwards through the individuals in the layer\n                for (int iind = static_cast<int>(this_layer.size())-1; iind >= static_cast<int>(m_Nelite); --iind) {\n                    auto &ind = this_layer[iind];\n                    if (ind->age() > age_threshold) {\n                        // If higher age limit layer has an empty slot, use it directly\n                        if (m_layers[ilayer+1].size() < Npop_size) {\n                            m_layers[ilayer+1].push_back(std::move(ind));\n                        }\n                        // Or if it dominates the worst individual in the higher age limit layer, replace that one\n                        // and sort the higher age limit layer\n                        else if (ind->get_cost() < m_layers[ilayer + 1].back()->get_cost()) {\n                            std::swap(m_layers[ilayer +1].back(), ind);\n                            sort_layer(m_layers[ilayer + 1]);\n                        }\n                        // Say goodbye to this individual\n                        this_layer.erase(this_layer.begin() + iind);\n                    }\n                }\n            }\n        }\n        /// Repopulate the layer to replace removed old individuals\n        void repopulate_layers() {\n\n            // Generate the new individuals serially\n            MutantVector mutants;\n            for (auto i = 0; i < m_layers.size(); ++i) {\n                auto &layer = m_layers[i];\n                if (layer.size() < Npop_size) {\n                    // How many individuals are missing?\n                    auto missing_individuals_count = Npop_size - layer.size();\n                    // Get the generator function\n                    auto generator = (m_generation_flag == GenerationOptions::LHS) ? LHS_population<T> : random_population<T>;\n                    // Then we pad out the population with new random individuals as needed (they start with an age of zero)\n                    for (auto && ind : generator(m_bounds, missing_individuals_count, m_cost_function)) {\n                        mutants.emplace_back(std::make_pair(i, std::move(ind)));\n                    }\n                }\n            }\n\n            // Evaluate the individuals we just generated\n            evaluate_mutants(mutants);\n\n            // Recollect the individuals into layers, again in serial\n            for (auto &&mut : mutants) {\n                auto i = std::get<0>(mut);\n                m_layers[i].emplace_back(std::move(std::get<1>(mut)));\n            }\n\n            // Sort all of the layers\n            sort_all_layers();\n        }\n\n        /// Evaluate a single individual, and store the values if needed\n        void evaluate_ind(pIndividual &ind) {\n            if (ind->needs_evaluation()){\n                ind->evaluate();\n                switch (m_log_scheme) {\n                    case LoggingScheme::none:\n                        break;\n                    case LoggingScheme::custom:{\n                        if (!m_filter_function) {\n                            throw std::invalid_argument(\"filtering function has not been provided, logging options are inconsistent!\");\n                        }\n                        Result r(ind->get_coeffs_ArrayXd(), ind->get_cost());\n                        // If the filter function returns the flag \"accept\", then store the result\n                        switch (m_filter_function(r)) {\n                        case FilterOptions::accept:\n                            result_queue.enqueue(std::move(r)); break;\n                        case FilterOptions::reject: break;\n                        }\n                        break;\n                    }\n                    case LoggingScheme::all:{\n                        result_queue.enqueue(std::move(Result(ind->get_coeffs_ArrayXd(), ind->get_cost())));\n                        break;\n                    }\n                    default: {\n                        throw std::invalid_argument(\"logging flag is not set; this is an error\");\n                    }\n                }\n            }\n        }\n    \n        /// Evaluate all of the layers\n        void evaluate_layers() {\n            for (auto &layer : m_layers) {\n                for (auto &ind : layer) {\n                    evaluate_ind(ind); // A no-op if the individual does not need to be evaluated\n                }\n            }\n        };\n\n        /// Sort all of the layers\n        void sort_all_layers() {\n            for (auto &layer : m_layers) {\n                sort_layer(layer);\n            }\n        };\n\n        /// Increase the age of all individuals\n        void increase_all_ages() {\n            for (auto &layer : m_layers) {\n                for (auto &ind : layer) {\n                    ind->increase_age();\n                }\n            }\n        }\n\n        /// Calculate statistics of the costs of individuals in each layer\n        std::vector<std::map<std::string, double> > cost_stats_each_layer() {\n            std::vector<std::map<std::string, double> > out;\n            for (auto &layer : m_layers) {\n                Eigen::ArrayXd cost_layer(layer.size());\n                for (auto i = 0; i < layer.size(); ++i) {\n                    cost_layer(i) = layer[i]->get_cost();\n                }\n                std::map<std::string, double> this_layer_map;\n                this_layer_map[\"max\"] = cost_layer.maxCoeff();\n                this_layer_map[\"min\"] = cost_layer.minCoeff();\n                // See https://en.wikipedia.org/wiki/Standard_deviation#Discrete_random_variable\n                this_layer_map[\"stddev\"] = sqrt((cost_layer - cost_layer.mean()).square().sum()/cost_layer.size());\n                out.push_back(this_layer_map);\n            }\n            return out;\n        }\n\n        /// Sort a given layer\n        void sort_layer(Population &pop) {\n            auto sort_fcn = [](pIndividual &i1, pIndividual &i2) {\n                return i1->get_cost() < i2->get_cost();\n            };\n            std::sort(pop.begin(), pop.end(), sort_fcn);\n        }\n\n        typedef std::vector<std::tuple<std::size_t, pIndividual> > MutantVector;\n\n        void parallel_evaluator(MutantVector::iterator itstart, MutantVector::iterator itend, double &elap_sec) {\n            \n            std::chrono::time_point<std::chrono::high_resolution_clock> start, end;\n            start = std::chrono::high_resolution_clock::now();\n            for (auto it = itstart; it != itend; ++it) {\n                auto &ind = std::get<1>(*it);\n                evaluate_ind(ind);\n            }\n            end = std::chrono::high_resolution_clock::now();\n            elap_sec = std::chrono::duration<double>(end - start).count();\n            return;\n        };\n        \n        void init_thread_pool(short Nthreads){\n            if (!m_pool || m_pool->GetThreads().size() != Nthreads){\n                // Make a thread pool for the workers\n                m_pool = std::unique_ptr<ThreadPool>(new ThreadPool(Nthreads));\n            }\n        }\n\n        void evaluate_mutants(MutantVector &mutants) {\n            if (!parallel || parallel_threads == 0) {\n                MutantVector::iterator itstart = mutants.begin();\n                MutantVector::iterator itend = mutants.end();\n                double time = 0;\n                parallel_evaluator(itstart, itend, time);\n            }\n            else {\n                // Initialize the thread pool, no-op if already initialized and is the right size\n                init_thread_pool(static_cast<short>(parallel_threads));\n                std::vector< std::future<void> > futures;\n                std::vector<std::thread> threads;\n                std::size_t Lchunk = mutants.size() / parallel_threads; // Note this is an integer division, so a floor()!\n                std::vector<double> times(parallel_threads);\n                \n                std::vector<std::size_t> chunksizes(parallel_threads, Lchunk);\n                auto Nmax = mutants.size();\n                std::size_t remainder = Nmax-Lchunk*parallel_threads;\n                // Increase the first remainder chunk sizes\n                for (auto i = 0; i < remainder; ++i){\n                    chunksizes[i]++;\n                }\n                // Double-check we get the right sizes\n                assert(std::accumulate(chunksizes.begin(), chunksizes.end(), static_cast<std::size_t>(0)) == mutants.size());\n                std::size_t isum = 0;\n                for (auto j = 0; j < parallel_threads; ++j)\n                {\n                    std::size_t cs = chunksizes[j];\n                    auto itstart = mutants.begin() + isum;\n                    auto itend = itstart + cs;\n                    isum += cs;\n                    double &time = times[j];\n                    \n                    std::function<void(void)> f = [this, itstart, itend, &time]() {\n                        auto startTime = std::chrono::high_resolution_clock::now();\n                        parallel_evaluator(itstart, itend, time);\n                        auto endTime = std::chrono::high_resolution_clock::now();\n                        time = std::chrono::duration<double>(endTime - startTime).count();\n                    };\n                    m_pool->AddJob(f);\n                }\n                // Wait until all the threads finish...\n                m_pool->WaitAll();\n                // Uncomment these lines to print out the times for each chunk; ideally they are all very close \n                // to each other.  Similar times means the work per thread is well divided\n                if (print_chunk_times){\n                    for (auto j = 0; j < parallel_threads; ++j) { \n                        std::cout << j << \" \" << times[j] << std::endl;\n                    }\n                }\n            }\n        }\n\n        void evolve_parallel() {\n            MutantVector mutants;\n            // In serial, generate the mutants; generation of the mutants \n            // is very fast.  Store all mutants in a flat vector with the index of the layer\n            for (auto i = 0; i < m_layers.size(); ++i) {\n                for (auto &&el : m_evolver->evolve_layer(m_layers, i, get_bounds(), get_cost_function())) {\n                    mutants.emplace_back(std::make_tuple(i, std::move(el)));\n                }\n            }\n\n            // Evaluate all the mutants, either in parallel or serial\n            evaluate_mutants(mutants);\n            \n            // Recollect the mutants into layers, again in serial\n            std::vector<Population> new_layers(m_layers.size());\n            for (auto &&mut : mutants) {\n                auto i = std::get<0>(mut);\n                new_layers[i].emplace_back(std::move(std::get<1>(mut)));\n            }\n            // Then determine which ones should be kept based on cost, greedily keeping\n            // the one with the lower cost\n            for (auto i = 0; i < m_layers.size(); ++i) {\n                assert(new_layers[i].size() == m_layers[i].size());\n                for (auto j = 0; j < m_layers[i].size(); ++j) {\n                    if (new_layers[i][j]->get_cost() < m_layers[i][j]->get_cost()) {\n                        std::swap(m_layers[i][j], new_layers[i][j]); // the other one will get thrown away\n                    }\n                    assert(new_layers[i][j]->get_cost() >= m_layers[i][j]->get_cost());\n                }\n            }\n        }\n\n        /// Evolve a given layer serially\n        void evolve_layer(std::size_t i) {\n\n            // Evolve the layer (elements are unevaluated)\n            auto new_layer = m_evolver->evolve_layer(m_layers, i, get_bounds(), get_cost_function());\n\n            for (auto j = 0; j < new_layer.size(); ++j) {\n                evaluate_ind(new_layer[j]);\n                double newcost = new_layer[j]->get_cost(), oldcost = m_layers[i][j]->get_cost();\n                // Keep the one with the lower cost (new_layer is going to be the one that is \n                // going to be used)\n                if (new_layer[j]->get_cost() > m_layers[i][j]->get_cost()) {\n                    // Swap because the older one is better, we are collecting values in new_layer\n                    std::swap(new_layer[j], m_layers[i][j]);\n                }\n                assert(new_layer[j]->get_cost() <= m_layers[i][j]->get_cost());\n            }\n\n            // How many individuals are missing?\n            auto missing_individuals_count = Npop_size - new_layer.size();\n\n            // Then we pad out the population with new random individuals as needed (they start with an age of zero)\n            if (missing_individuals_count > 0) {\n                auto generator = (m_generation_flag == GenerationOptions::LHS) ? LHS_population<T> : random_population<T>;\n                Population random_inds = generator(m_bounds, missing_individuals_count, m_cost_function);\n                std::move(random_inds.begin(), random_inds.end(), std::back_inserter(new_layer));\n            }\n\n            // And move back to the layer\n            std::swap(m_layers[i], new_layer);\n\n            assert(m_layers[i].size() == Npop_size);\n        }\n\n        /// Carry out the steps for one generation\n        void do_generation() {\n            if (m_evolver == nullptr) {\n                throw std::invalid_argument(\"Evolver has not been selected\");\n            }\n            if (m_layers.size() == 0) {\n                initialize_layers();\n            }\n            else if (m_generation % age_gap == 0 && m_layers.size() > 1) {\n\n                // ========\n                // Layer #1\n                // ========\n\n                // push into the next-from-bottom layer any individuals that dominate an individual in the higher layer\n                // --\n                // Join them all together into one population\n                Population pop;\n                // Move them into the population\n                std::move(m_layers[1].begin(), m_layers[1].end(), std::back_inserter(pop));\n                std::move(m_layers[0].begin(), m_layers[0].end(), std::back_inserter(pop));\n                // Sort them in terms of increasing cost\n                sort_layer(pop);\n                // Remove the ones that are no longer needed;\n                // Keep indices [0,Npop_size-1] inclusive\n                for (auto i = pop.size()-1; i >= Npop_size; --i){\n                    pop.erase(pop.begin()+i);\n                }\n                // Keep the best ones\n                m_layers[1] = std::move(pop);\n\n                // ========\n                // Layer #0\n                // ========\n\n                // Generate new individuals in serial (fast)\n                MutantVector mutants;\n                auto generator = (m_generation_flag == GenerationOptions::LHS) ? LHS_population<T> : random_population<T>;\n                for (auto && ind : generator(m_bounds, Npop_size, m_cost_function)) {\n                    mutants.emplace_back(std::make_pair(0,std::move(ind)));\n                }\n                // Evaluate the individuals in parallel\n                evaluate_mutants(mutants);\n\n                // Put them back into the 0-th layer\n                m_layers[0].clear();\n                for (auto &&mut : mutants) {\n                    auto i = std::get<0>(mut);\n                    m_layers[i].emplace_back(std::move(std::get<1>(mut)));\n                }\n            }\n            graduate_elderly_individuals();\n            repopulate_layers();\n            evaluate_layers();\n            if (parallel){\n                evolve_parallel();\n            }\n            else{\n                for (int i = static_cast<int>(m_layers.size()) - 1; i >= 0; i--) {\n                    evolve_layer(i);\n                }\n            }\n            evaluate_layers();\n            increase_all_ages();\n            sort_all_layers();\n            m_generation++;\n        }\n        // Get the best individuals from each layer, starting with layer 0\n        std::vector<std::tuple<double, const std::vector<T> > > get_best_per_layer(){\n            std::vector<std::tuple<double, const std::vector<T> > > out;\n            for (const auto &layer : m_layers) {\n                const auto c = static_cast<const NumericalIndividual<T>*>(layer[0].get())->get_coefficients();\n                out.emplace_back(std::make_tuple(layer[0]->get_cost(), c));\n            }\n            return out;\n        };\n        // Get the layer with the individual with the lowest (best) cost\n        std::tuple<double, const std::vector<T> > get_best() {\n            auto B = get_best_per_layer();\n            // The best individual might not be in the highest layer, let's find the best one\n            return *std::min_element(B.begin(), B.end(), [](decltype(B.back()) &b1, decltype(B.back()) &b2) { return std::get<0>(b1) < std::get<0>(b2); });\n        };\n        /** Return a string with some diagnostic information for the best individual in the population\n         * \\sa get_best\n         * \\sa get_best_per_layer\n         */\n        std::string print_diagnostics() {\n            auto best = get_best(); \n            double best_cost; std::vector<T> c;\n            std::tie(best_cost, c) = best;\n            std::stringstream ss;\n            ss << \"i: \" << static_cast<int>(m_generation - 1) << \" best: \" << best_cost << \" c: \" << vec2string(c) << \" queue: \" << result_queue.size_approx();\n            return ss.str();\n        }\n\n        /// Get the results that have been logged during the course of this optimization\n        std::vector<Result> get_results() {\n            std::vector<Result> results(result_queue.size_approx());\n            auto Nels = result_queue.try_dequeue_bulk(results.begin(), results.size());\n            return results;\n        }\n    };\n    struct ALPSInputValues {\n        std::vector<Bound> bounds; ///< The vector of bounds on the variables\n        double VTR; ///< Value to reach (terminates on reaching this cost value)\n        CostFunction f; ///< The cost function to be minimized\n        bool parallel = false; ///< If true, evaluate each layer in a separate thread\n        std::size_t max_gen = 1000; ///< Maximum number of generations that are allowed\n        std::size_t NP = 40; ///< The number of individuals in a population (per layer)\n        std::size_t Nlayer = 1; ///< The number of layers\n        std::size_t age_gap = 5; ///< The number of generations between restarting the bottom layer\n        bool disp = false; ///< If true, display diagnostics as you go to standard out\n    };\n    struct ALPSReturnValues {\n        double fval; ///< The function value at termination\n        double elapsed_sec; ///< The number of seconds to conduct the entire optimization\n        std::string termination_reason; ///< Why the optimization stopped\n    };\n\n    template<typename T>\n    ALPSReturnValues ALPS(ALPSInputValues &in) {\n        if (in.bounds.empty()){ throw std::invalid_argument(\"bounds variable must be provided\"); }\n        //if (in.VTR) { throw std::invalid_argument(\"VTR variable must be provided\"); }\n        if (!in.f) { throw std::invalid_argument(\"Cost function f must be provided\"); }\n        ALPSReturnValues out;\n        auto D = in.bounds.size();\n        auto layers = Layers<T>(in.f, D, in.NP, in.Nlayer, in.age_gap);\n        layers.set_bounds(in.bounds);\n        layers.parallel = in.parallel;\n        layers.set_builtin_evolver(BuiltinEvolvers::differential_evolution);\n        auto startTime = std::chrono::system_clock::now();\n        for (auto i = 0; i < in.max_gen; ++i) {\n            layers.do_generation();\n            if (in.disp){ auto diag = layers.print_diagnostics(); std::cout << diag << std::endl; }\n            auto best_layer = layers.get_best(); \n            if (std::get<0>(best_layer) < in.VTR) {\n                out.termination_reason = \"Reached VTR\"; \n                break;\n            }\n            if (i == in.max_gen-1) { out.termination_reason = \"Reached max # of generations\"; }\n        }\n        \n        auto endTime = std::chrono::system_clock::now();\n        out.elapsed_sec = std::chrono::duration<double>(endTime - startTime).count();\n        out.fval = std::get<0>(layers.get_best());\n        return out;\n    }\n\n} /* namespace CEGO */\n#endif\n", "meta": {"hexsha": "6da0897c701a7a2213ea2ee1aec12fb516d14117", "size": 30106, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/CEGO/CEGO.hpp", "max_stars_repo_name": "jedbrown/CEGO", "max_stars_repo_head_hexsha": "60e39319e577cf63e844d0818387aa9e486878f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/CEGO/CEGO.hpp", "max_issues_repo_name": "jedbrown/CEGO", "max_issues_repo_head_hexsha": "60e39319e577cf63e844d0818387aa9e486878f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/CEGO/CEGO.hpp", "max_forks_repo_name": "jedbrown/CEGO", "max_forks_repo_head_hexsha": "60e39319e577cf63e844d0818387aa9e486878f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1436950147, "max_line_length": 168, "alphanum_fraction": 0.5423503621, "num_tokens": 6490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4404769769626388}}
{"text": "/**\n * @file QuadraticConstraint.cpp\n * @author Giulio Romualdi\n * @copyright Released under the terms of the MIT License.\n * @date 2021\n */\n\n#include <cmath>\n#include <limits>\n#include <string>\n\n#include <Eigen/Dense>\n\n#include <ScsEigen/Logger.h>\n#include <ScsEigen/Math.h>\n#include <ScsEigen/QuadraticConstraint.h>\n\nusing namespace ScsEigen;\n\nQuadraticConstraint::QuadraticConstraint()\n{\n    this->m_lowerBound = ScsEigen::Vector1d::Constant(\n        -std::numeric_limits<ScsEigen::Vector1d::Scalar>::infinity());\n}\n\nQuadraticConstraint::QuadraticConstraint(const Eigen::Ref<const Eigen::MatrixXd>& Q,\n                                         const Eigen::Ref<const Eigen::MatrixXd>& b,\n                                         double upperBound)\n    : Constraint((Q.rows() == Q.cols() && Q.rows() == b.rows()) ? Q.rows() : 0,\n                 \"Quadratic constraint\")\n{\n    if (Q.rows() != Q.cols() || Q.rows() != b.rows())\n    {\n\n        log()->error(\"[QuadraticConstraint::QuadraticConstraint] Q matrix must be square and the \"\n                     \"size of b \"\n                     \"should be coherent with Q\");\n        assert(false);\n    } else\n    {\n        m_Q = (Q + Q.transpose()) / 2;\n        m_b = b;\n    }\n\n    // the only admissible lower bound is\n    // -std::numeric_limits<ScsEigen::Vector1d::Scalar>::infinity()\n    this->m_lowerBound = ScsEigen::Vector1d::Constant(\n        -std::numeric_limits<ScsEigen::Vector1d::Scalar>::infinity());\n\n    // set the upperbound\n    this->setUpperBound(ScsEigen::Vector1d::Constant(upperBound));\n}\n\nbool QuadraticConstraint::setQ(const Eigen::Ref<const Eigen::MatrixXd>& Q)\n{\n    if (m_Q.size() != 0)\n    {\n        if (Q.size() != m_Q.size())\n        {\n            log()->error(\"[QuadraticConstraint::setQ] The size of the matrix 'Q' cannot change.\");\n            return false;\n        }\n    } else if (Q.rows() != Q.cols())\n    {\n        log()->error(\"[QuadraticConstraint::QuadraticConstraint] Q matrix must be square.\");\n        return false;\n    } else if (!this->setNumberOfVariables(Q.rows()))\n    {\n        log()->error(\"[QuadraticConstraint::setQ] Unable to set the number of variables.\");\n        return false;\n    }\n\n    m_Q = (Q + Q.transpose()) / 2;\n    return true;\n}\n\nbool QuadraticConstraint::setB(const Eigen::Ref<const Eigen::VectorXd>& b)\n{\n    if (m_b.size() != 0)\n    {\n        if (b.size() != m_b.size())\n        {\n            log()->error(\"[QuadraticConstraint::setB] The size of the vector 'b' cannot change.\");\n            return false;\n        }\n    } else if (!this->setNumberOfVariables(b.size()))\n    {\n        log()->error(\"[QuadraticConstraint::setB] Unable to set the number of variables.\");\n        return false;\n    }\n\n    m_b = b;\n    return true;\n}\n\nbool QuadraticConstraint::setLowerBound(const Eigen::Ref<const Eigen::VectorXd>& lowerBound)\n{\n    if (lowerBound.size() != 1)\n    {\n        log()->error(\"[QuadraticConstraint::setLowerBound] The lower bound should be a scalar.\");\n        return false;\n    }\n\n    if (lowerBound[0] > 0 || !std::isinf(lowerBound[0]))\n    {\n        log()->error(\"[QuadraticConstraint::setLowerBound] The only admissible lowerBound is \"\n                     \"-std::numeric_limits<ScsEigen::Vector1d::Scalar>::infinity()\");\n        return false;\n    }\n\n    // the only admissible lowerBound is\n    // -std::numeric_limits<ScsEigen::Vector1d::Scalar>::infinity() and it has been already set in\n    // the constructor\n    return true;\n}\n\nEigen::Ref<const Eigen::VectorXd> QuadraticConstraint::getB() const\n{\n    return m_b;\n}\n\nEigen::Ref<const Eigen::MatrixXd> QuadraticConstraint::getQ() const\n{\n    return m_Q;\n}\n", "meta": {"hexsha": "3000703d003b6156201bbb194a5345d77549780e", "size": 3633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ScsEigen/src/QuadraticConstraint.cpp", "max_stars_repo_name": "GiulioRomualdi/scs-eigen", "max_stars_repo_head_hexsha": "b315dbee88f2a0bdcfe5b538607b858209880086", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-29T07:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-12T16:36:54.000Z", "max_issues_repo_path": "src/ScsEigen/src/QuadraticConstraint.cpp", "max_issues_repo_name": "GiulioRomualdi/scs-eigen", "max_issues_repo_head_hexsha": "b315dbee88f2a0bdcfe5b538607b858209880086", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-03T20:21:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-04T21:12:24.000Z", "max_forks_repo_path": "src/ScsEigen/src/QuadraticConstraint.cpp", "max_forks_repo_name": "GiulioRomualdi/scs-eigen", "max_forks_repo_head_hexsha": "b315dbee88f2a0bdcfe5b538607b858209880086", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-12T16:35:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-12T16:35:06.000Z", "avg_line_length": 28.8333333333, "max_line_length": 98, "alphanum_fraction": 0.5995045417, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4404769697392529}}
{"text": "//==============================================================================\n//         Copyright 2009 - 2013 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2014 MetaScale SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n\n#include <nt2/table.hpp>\n#include <nt2/include/functions/any.hpp>\n#include <nt2/include/functions/seladd.hpp>\n#include <nt2/include/functions/plus.hpp>\n#include <nt2/include/functions/minus.hpp>\n#include <nt2/include/functions/times.hpp>\n#include <nt2/include/functions/is_less.hpp>\n#include <nt2/include/functions/linspace.hpp>\n#include <nt2/include/functions/expand_to.hpp>\n#include <nt2/include/functions/colvect.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/functions/arrayfun.hpp>\n#include <boost/fusion/include/at.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/dispatch/meta/strip.hpp>\n#include <vector>\n#include <iostream>\n\n#include <nt2/sdk/bench/benchmark.hpp>\n#include <nt2/sdk/bench/metric/cycles_per_element.hpp>\n#include <nt2/sdk/bench/protocol/max_duration.hpp>\n#include <nt2/sdk/bench/setup/geometric.hpp>\n#include <nt2/sdk/bench/setup/combination.hpp>\n#include <nt2/sdk/bench/setup/constant.hpp>\n#include <nt2/sdk/bench/stats/median.hpp>\n\nusing namespace nt2::bench;\nusing namespace nt2;\n\nnamespace mandelbrot\n{\n\n  struct step\n  {\n    template<class Sig> struct result;\n    template<class This, class A0, class A1>\n    struct result<This(A0,A1)>\n    {\n      typedef typename boost::dispatch::meta::\n              as_integer<typename boost::dispatch::meta::strip<A0>::type\n                        >::type type;\n    };\n\n    step(std::size_t const& n) : max_iter_(n) {}\n\n    template<class T>\n    typename result<step(T,T)>::type operator()(T const& a, T const& b) const\n    {\n      typedef typename result<step(T const&, T const&)>::type iter_type;\n      typedef typename boost::simd::meta::scalar_of<T>::type s_type;\n      iter_type iter = nt2::Zero<iter_type>();\n      iter_type const o = nt2::One<iter_type>();\n      T x = nt2::Zero<T>();\n      T y = nt2::Zero<T>();\n      T x2,y2,xy,m2;\n      typename boost::simd::meta::as_logical<T>::type mask;\n      std::size_t i = 0;\n      bool flag;\n      do\n      {\n        x2 = x*x;\n        y2 = y*y;\n        xy = s_type(2)  *x*y;\n        x = x2 - y2 + a;\n        y = xy + b;\n        m2 = x2 + y2;\n        mask= m2<s_type(4);\n        iter = nt2::seladd(mask, iter, o);\n        flag = nt2::any(mask);\n        i++;\n      }while(flag && i < 256);\n\n      return iter;\n    }\n\n    std::size_t max_iter_;\n  };\n}\n\ntemplate<typename T> struct mandelbrot_nt2\n{\n  typedef T value_type;\n  template<typename Setup>\n  mandelbrot_nt2(Setup const& s)\n                    :  h_(boost::fusion::at_c<0>(s))\n                    ,  w_(boost::fusion::at_c<1>(s))\n                    ,  a0_(boost::fusion::at_c<2>(s))\n                    ,  a1_(boost::fusion::at_c<3>(s))\n                    ,  b0_(boost::fusion::at_c<4>(s))\n                    ,  b1_(boost::fusion::at_c<5>(s))\n                    ,  max_iter_(boost::fusion::at_c<6>(s))\n                    ,  size_(h_*w_)\n                    ,  julia(max_iter_)\n  {\n    A.resize(nt2::of_size(h_,w_));\n    B.resize(nt2::of_size(h_,w_));\n    C.resize(nt2::of_size(h_,w_));\n\n    A=nt2::expand_to(nt2::linspace(a0_,a1_,h_),h_,w_);\n    B=nt2::expand_to(nt2::colvect(nt2::linspace(b0_,b1_,w_)),h_,w_);\n  }\n\n  void operator()()\n  {\n    C = arrayfun(julia, A, B);\n  }\n\n  friend std::ostream& operator<<(std::ostream& os, mandelbrot_nt2<T> const& p)\n  {\n    return os << \"(\" << p.h_ << \" x \" << p.w_ << \")\";\n  }\n\n  std::size_t size() const { return size_; }\n\n  private:\n    std::size_t h_, w_;\n    value_type a0_, a1_, b0_, b1_;\n    std::size_t max_iter_, size_, step_size_, aligned_sz, it;\n    mandelbrot::step julia;\n    nt2::table<value_type> A, B;\n    nt2::table<int> C;\n};\n\nNT2_REGISTER_BENCHMARK_TPL( mandelbrot_nt2, (float) )\n{\n\n  std::size_t hmin = args(\"hmin\", 100);\n  std::size_t hmax = args(\"hmax\", 1600);\n  std::size_t hstep = args(\"hstep\", 2);\n  std::size_t wmin = args(\"wmin\", 100);\n  std::size_t wmax = args(\"wmax\",1600);\n  std::size_t wstep = args(\"wstep\", 2);\n  T xmin = args(\"xmin\", -1.5);\n  T xmax = args(\"xmax\", 1.5);\n  T ymin = args(\"ymin\", -1.5);\n  T ymax = args(\"ymax\", 1.5);\n  T max_iter = args(\"max_iter\", 256);\n\n  run_during_with< mandelbrot_nt2<float> > ( 1.\n                                          , and_( geometric(hmin,hmax,hstep)\n                                                , geometric(wmin,wmax,wstep)\n                                                , constant(xmin)\n                                                , constant(xmax)\n                                                , constant(ymin)\n                                                , constant(ymax)\n                                                , constant(max_iter)\n                                                )\n                                          , cycles_per_element<stats::median_>()\n                                          );\n}\n", "meta": {"hexsha": "a7a1c094bf3202634c70d60fd50c5dee931cc60f", "size": 5292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demo/mandelbrot/nt2/mandelbrot_nt2.cpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "demo/mandelbrot/nt2/mandelbrot_nt2.cpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demo/mandelbrot/nt2/mandelbrot_nt2.cpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 32.8695652174, "max_line_length": 80, "alphanum_fraction": 0.5359032502, "num_tokens": 1422, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478256, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4404698490799886}}
{"text": "//---------------------------------------------------------------------------------------------------------------------\n//  Vertical Engineering Solutions\n//---------------------------------------------------------------------------------------------------------------------\n// \n//  Copyright 2020 Vertical Engineering Solutions  - All Rights Reserved\n// \n//  Unauthorized copying of this file, via any medium is strictly prohibited Proprietary and confidential.\n// \n//  All information contained herein is, and remains the property of Vertical Engineering Solutions.  The \n//  intellectual and technical concepts contained herein are proprietary to Vertical Engineering Solutions \n//  and its suppliers and may be covered by UE and Foreign Patents, patents in process, and are protected \n//  by trade secret or copyright law. Dissemination of this information or reproduction of this material is \n//  strictly forbidden unless prior written permission is obtained from Adobe Systems Incorporated.\n//\n//---------------------------------------------------------------------------------------------------------------------\n//\n//  Maintainer: pramon@vengineerings.com\n//\n//---------------------------------------------------------------------------------------------------------------------\n\n#include <QApplication>\n#include <QVector>\n#include \"qcustomplot.h\"\n\n#include <pidpp/PID.h>\n\n#include<iostream>\n\n#include <boost/numeric/odeint.hpp>\nusing namespace boost::numeric::odeint;\n\ntypedef std::vector<double> state_type;\n/* The rhs of x' = f(x) */\nclass FirstOrderSystem {\n    public:\n        FirstOrderSystem( double _c ) : c_(_c) { }\n\n        void operator() ( const state_type &x , state_type &dxdt, const double _t ) {\n            dxdt[0] = -1/c_ * x[0] + x[1];\n        }\n\n    private:\n        double c_;\n};\n\nclass SecondOrderSystem {\n    public:\n        SecondOrderSystem( double _a, double _b ) : a_(_a), b_(_b) { }\n\n        void setU(double _u){\n            u_ = _u;\n        }\n\n        void operator() ( const state_type &x , state_type &dxdt, const double _t ) {\n            dxdt[0] = x[1];\n            dxdt[1] = u_ - b_*x[0] -a_* x[1];\n        }\n\n    private:\n        double a_, b_;\n        double u_;\n};\n\n\nint main(int _argc, char** _argv){\n    QApplication a(_argc, _argv);\n\n    //-----------------------------------------------------------------------------------------------------------------\n    // Simulation\n    //-----------------------------------------------------------------------------------------------------------------\n    \n    \n    float kp = 4.0;\n    float ki = 5.0;\n    float kd = 0.0;\n\n    //-----------------------------------------------------------------------------------------------------------------\n    // Free run\n    //-----------------------------------------------------------------------------------------------------------------\n    std::vector<double> stateFree = {0, 0};\n    std::vector<double> valuesFree;\n    std::vector<double> stepFree;\n    std::vector<double> timeFree;\n    \n    {\n        SecondOrderSystem system(1,1);\n        runge_kutta4< state_type > stepper;\n        system.setU(0);\n        integrate_const( stepper ,  system, stateFree , 0.0 , 10.0 , 0.01 );\n\n        const double dt = 0.01;\n        for( double t=0.0 ; t<10.0 ; t+= dt ){\n            if(t >1){\n                system.setU(1);\n                stepFree.push_back(1);\n            }else{\n                stepFree.push_back(0);\n            }\n\n            stepper.do_step( system , stateFree , t , dt );\n            timeFree.push_back(t);\n            valuesFree.push_back(stateFree[0]);\n        }\n    }\n\n    //-----------------------------------------------------------------------------------------------------------------\n    // PID no windup\n    //-----------------------------------------------------------------------------------------------------------------\n    std::vector<double> stateNoWindup = {0, 0};\n    std::vector<double> valuesNoWindup;\n    std::vector<double> stepNoWindup;\n    std::vector<double> timeNoWindup;\n    \n    {\n        SecondOrderSystem system(1,1);\n        runge_kutta4< state_type > stepper;\n        system.setU(0);\n        integrate_const( stepper ,  system, stateNoWindup , 0.0 , 10.0 , 0.01 );\n        pidpp::PID pid(kp, ki, kd,-2,2);\n        pid.reference(1);\n\n        const double dt = 0.01;\n        for( double t=0.0 ; t<10.0 ; t+= dt ){\n            if(t >1){\n                stepNoWindup.push_back(1);\n                system.setU(pid.update(stateNoWindup[0], dt));\n            }else{\n                stepNoWindup.push_back(0);\n            }\n\n            stepper.do_step( system , stateNoWindup , t , dt );\n            timeNoWindup.push_back(t);\n            valuesNoWindup.push_back(stateNoWindup[0]);\n        }\n    }\n\n    //-----------------------------------------------------------------------------------------------------------------\n    // PID windup sat\n    //-----------------------------------------------------------------------------------------------------------------\n    std::vector<double> stateWindupSat = {0, 0};\n    std::vector<double> valuesWindupSat;\n    std::vector<double> stepWindupSat;\n    std::vector<double> timeWindupSat;\n    \n    {\n        SecondOrderSystem system(1,1);\n        runge_kutta4< state_type > stepper;\n        system.setU(0);\n        integrate_const( stepper ,  system, stateWindupSat , 0.0 , 10.0 , 0.01 );\n        pidpp::PID pid(kp, ki, kd,-2,2);\n        pid.reference(1);\n        pid.setAntiWindup(pidpp::PID::AntiWindupMethod::Saturation, {-0.2, 0.2});\n\n        const double dt = 0.01;\n        for( double t=0.0 ; t<10.0 ; t+= dt ){\n            if(t >1){\n                stepWindupSat.push_back(1);\n                system.setU(pid.update(stateWindupSat[0], dt));\n            }else{\n                stepWindupSat.push_back(0);\n            }\n\n            stepper.do_step( system , stateWindupSat , t , dt );\n            timeWindupSat.push_back(t);\n            valuesWindupSat.push_back(stateWindupSat[0]);\n        }\n    }\n    \n    //-----------------------------------------------------------------------------------------------------------------\n    // PID windup Back calculation\n    //-----------------------------------------------------------------------------------------------------------------\n    std::vector<double> stateBackCalc = {0, 0};\n    std::vector<double> valuesBackCalc;\n    std::vector<double> stepBackCalc;\n    std::vector<double> timeBackCalc;\n    \n    {\n        SecondOrderSystem system(1,1);\n        runge_kutta4< state_type > stepper;\n        system.setU(0);\n        integrate_const( stepper ,  system, stateBackCalc , 0.0 , 10.0 , 0.01 );\n        pidpp::PID pid(kp, ki, kd,-2,2);\n        pid.reference(1);\n        pid.setAntiWindup(pidpp::PID::AntiWindupMethod::BackCalculation, {1.2});\n\n        const double dt = 0.01;\n        for( double t=0.0 ; t<10.0 ; t+= dt ){\n            if(t >1){\n                stepBackCalc.push_back(1);\n                system.setU(pid.update(stateBackCalc[0], dt));\n            }else{\n                stepBackCalc.push_back(0);\n            }\n\n            stepper.do_step( system , stateBackCalc , t , dt );\n            timeBackCalc.push_back(t);\n            valuesBackCalc.push_back(stateBackCalc[0]);\n        }\n    }\n\n    //-----------------------------------------------------------------------------------------------------------------\n    // PID windup clamp\n    //-----------------------------------------------------------------------------------------------------------------\n    std::vector<double> stateClamp = {0, 0};\n    std::vector<double> valuesClamp;\n    std::vector<double> stepClamp;\n    std::vector<double> timeClamp;\n    \n    {\n        SecondOrderSystem system(1,1);\n        runge_kutta4< state_type > stepper;\n        system.setU(0);\n        integrate_const( stepper ,  system, stateClamp , 0.0 , 10.0 , 0.01 );\n        pidpp::PID pid(kp, ki, kd,-2,2);\n        pid.reference(1);\n        pid.setAntiWindup(pidpp::PID::AntiWindupMethod::Clamping, {1});\n\n        const double dt = 0.01;\n        for( double t=0.0 ; t<10.0 ; t+= dt ){\n            if(t >1){\n                stepClamp.push_back(1);\n                system.setU(pid.update(stateClamp[0], dt));\n            }else{\n                stepClamp.push_back(0);\n            }\n\n            stepper.do_step( system , stateClamp , t , dt );\n            timeClamp.push_back(t);\n            valuesClamp.push_back(stateClamp[0]);\n        }\n    }\n\n    //-----------------------------------------------------------------------------------------------------------------\n    // PLOT\n    //-----------------------------------------------------------------------------------------------------------------\n    QCustomPlot plot;\n    plot.setInteraction(QCP::iSelectPlottables, true);\n    plot.legend->setVisible(true);\n    plot.legend->setBrush(QBrush(QColor(255,255,255,230)));\n    plot.setMinimumWidth(800);\n    plot.setMinimumHeight(500);\n    // Step\n    QPen graphPen;\n    graphPen.setColor(QColor(255,0,0));\n    graphPen.setWidthF(4);\n    plot.addGraph()->setPen(graphPen);\n    plot.graph(0)->setData(QVector<double>::fromStdVector(timeFree), QVector<double>::fromStdVector(stepFree));\n    plot.graph(0)->setName(\"Target Step\");\n    // Open step response\n    graphPen.setColor(QColor(0,255,0));\n    graphPen.setWidthF(2);\n    plot.addGraph()->setPen(graphPen);\n    plot.graph(1)->setData(QVector<double>::fromStdVector(timeFree), QVector<double>::fromStdVector(valuesFree));\n    plot.graph(1)->setName(\"Free form\");\n    // No wind up PID\n    graphPen.setColor(QColor(0,0,255));\n    graphPen.setWidthF(2);\n    plot.addGraph()->setPen(graphPen);\n    plot.graph(2)->setData(QVector<double>::fromStdVector(timeNoWindup), QVector<double>::fromStdVector(valuesNoWindup));\n    plot.graph(2)->setName(\"PID no antiwindup\");\n    \n    // wind up sat PID\n    graphPen.setColor(QColor(0,255,255));\n    graphPen.setWidthF(2);\n    plot.addGraph()->setPen(graphPen);\n    plot.graph(3)->setData(QVector<double>::fromStdVector(timeWindupSat), QVector<double>::fromStdVector(valuesWindupSat));\n    plot.graph(3)->setName(\"with saturation\");\n\n    // wind up back calculation\n    graphPen.setColor(QColor(255,0,255));\n    graphPen.setWidthF(2);\n    plot.addGraph()->setPen(graphPen);\n    plot.graph(4)->setData(QVector<double>::fromStdVector(timeBackCalc), QVector<double>::fromStdVector(valuesBackCalc));\n    plot.graph(4)->setName(\"Back Calculation\");\n\n    // wind up Clamp\n    graphPen.setColor(QColor(255,255,0));\n    graphPen.setWidthF(2);\n    plot.addGraph()->setPen(graphPen);\n    plot.graph(5)->setData(QVector<double>::fromStdVector(timeClamp), QVector<double>::fromStdVector(valuesClamp));\n    plot.graph(5)->setName(\"Clamping\");\n\n    // give the axes some labels:\n    plot.xAxis->setLabel(\"t (s)\");\n    plot.yAxis->setLabel(\"value (u)\");\n    // set axes ranges, so we see all data:\n    plot.xAxis->setRange(0, 10);\n    plot.yAxis->setRange(   -0.5, 2);\n    plot.replot();\n    plot.show();\n\n\n\n\n    return a.exec();\n\n}", "meta": {"hexsha": "eb0877098180f46e9a95f1399bb08e7ad6834895", "size": 11015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/PID_test.cpp", "max_stars_repo_name": "Bardo91/pidpp", "max_stars_repo_head_hexsha": "2f50f220460c209095f07d299bacef03c505d6db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/PID_test.cpp", "max_issues_repo_name": "Bardo91/pidpp", "max_issues_repo_head_hexsha": "2f50f220460c209095f07d299bacef03c505d6db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-04-25T16:19:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-25T16:20:18.000Z", "max_forks_repo_path": "example/PID_test.cpp", "max_forks_repo_name": "Bardo91/pidpp", "max_forks_repo_head_hexsha": "2f50f220460c209095f07d299bacef03c505d6db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0875420875, "max_line_length": 123, "alphanum_fraction": 0.4798002724, "num_tokens": 2471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.44045085685899604}}
{"text": "// Copyright (C) 2013 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/pose/util.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <glog/logging.h>\n\n#include <vector>\n\n#include \"theia/matching/feature_correspondence.h\"\n#include \"theia/util/random.h\"\n\nnamespace theia {\n\nusing Eigen::Map;\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::Vector2d;\nusing Eigen::Vector3d;\nusing Eigen::Vector4d;\n\n// For an E or F that is defined such that y^t * E * x = 0\ndouble SquaredSampsonDistance(const Matrix3d& F,\n                              const Vector2d& x,\n                              const Vector2d& y) {\n  const Vector3d epiline_x = F * x.homogeneous();\n  const double numerator_sqrt = y.homogeneous().dot(epiline_x);\n  const Vector4d denominator(y.homogeneous().dot(F.col(0)),\n                             y.homogeneous().dot(F.col(1)),\n                             epiline_x[0],\n                             epiline_x[1]);\n\n  // Finally, return the complete Sampson distance.\n  return numerator_sqrt * numerator_sqrt / denominator.squaredNorm();\n}\n\nEigen::Matrix3d CrossProductMatrix(const Vector3d& cross_vec) {\n  Matrix3d cross;\n  cross << 0.0, -cross_vec.z(), cross_vec.y(), cross_vec.z(), 0.0,\n      -cross_vec.x(), -cross_vec.y(), cross_vec.x(), 0.0;\n  return cross;\n}\n\n// Computes the normalization matrix transformation that centers image points\n// around the origin with an average distance of sqrt(2) to the centroid.\n// Returns the transformation matrix and the transformed points. This assumes\n// that no points are at infinity.\nbool NormalizeImagePoints(const std::vector<Vector2d>& image_points,\n                          std::vector<Vector2d>* normalized_image_points,\n                          Matrix3d* normalization_matrix) {\n  Eigen::Map<const Matrix<double, 2, Eigen::Dynamic> > image_points_mat(\n      image_points[0].data(), 2, image_points.size());\n\n  // Allocate the output vector and map an Eigen object to the underlying data\n  // for efficient calculations.\n  normalized_image_points->resize(image_points.size());\n  Eigen::Map<Matrix<double, 2, Eigen::Dynamic> > normalized_image_points_mat(\n      (*normalized_image_points)[0].data(), 2, image_points.size());\n\n  // Compute centroid.\n  const Vector2d centroid(image_points_mat.rowwise().mean());\n\n  // Calculate average RMS distance to centroid.\n  const double rms_mean_dist =\n      sqrt((image_points_mat.colwise() - centroid).squaredNorm() /\n           image_points.size());\n\n  // Create normalization matrix.\n  const double norm_factor = sqrt(2.0) / rms_mean_dist;\n  *normalization_matrix << norm_factor, 0, -1.0 * norm_factor * centroid.x(), 0,\n      norm_factor, -1.0 * norm_factor * centroid.y(), 0, 0, 1;\n\n  // Normalize image points.\n  const Matrix<double, 3, Eigen::Dynamic> normalized_homog_points =\n      (*normalization_matrix) * image_points_mat.colwise().homogeneous();\n  normalized_image_points_mat = normalized_homog_points.colwise().hnormalized();\n\n  return true;\n}\n\n// Projects a 3x3 matrix to the rotation matrix in SO3 space with the closest\n// Frobenius norm. For a matrix with an SVD decomposition M = USV, the nearest\n// rotation matrix is R = UV'.\nMatrix3d ProjectToRotationMatrix(const Matrix3d& matrix) {\n  Eigen::JacobiSVD<Matrix3d> svd(matrix,\n                                 Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Matrix3d rotation_mat = svd.matrixU() * (svd.matrixV().transpose());\n\n  // The above projection will give a matrix with a determinant +1 or -1. Valid\n  // rotation matrices have a determinant of +1.\n  if (rotation_mat.determinant() < 0) {\n    rotation_mat *= -1.0;\n  }\n\n  return rotation_mat;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "8d193f37d6e2c85900e9a7459e634ca566ebe521", "size": 5410, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/util.cc", "max_stars_repo_name": "urbste/TheiaSfM", "max_stars_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T03:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:08:45.000Z", "max_issues_repo_path": "src/theia/sfm/pose/util.cc", "max_issues_repo_name": "urbste/TheiaSfM", "max_issues_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/pose/util.cc", "max_forks_repo_name": "urbste/TheiaSfM", "max_forks_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-20T03:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T08:08:52.000Z", "avg_line_length": 40.9848484848, "max_line_length": 80, "alphanum_fraction": 0.704805915, "num_tokens": 1244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.4404504795421454}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2009 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Author: Guido Kanschat, Texas A&M University, 2009 \n */ \n\n\n\n// 前面几个文件已经在前面的例子中讲过了，因此不再做进一步的评论。\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/sparse_matrix.h> \n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_out.h> \n#include <deal.II/grid/grid_refinement.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/fe/mapping_q1.h> \n\n// 这里定义了不连续的有限元。它们的使用方式与所有其他有限元相同，不过--正如你在以前的教程程序中所看到的--用户与有限元类的交互并不多：它们被传递给 <code>DoFHandler</code> 和 <code>FEValues</code> 对象，就这样了。\n\n#include <deal.II/fe/fe_dgq.h> \n\n// 我们将使用最简单的求解器，称为Richardson迭代，它代表了一个简单的缺陷修正。这与一个块状SSOR预处理器（定义在precondition_block.h中）相结合，该预处理器使用DG离散化产生的系统矩阵的特殊块状结构。\n\n#include <deal.II/lac/solver_richardson.h> \n#include <deal.II/lac/precondition_block.h> \n\n// 我们将使用梯度作为细化指标。\n\n#include <deal.II/numerics/derivative_approximation.h> \n\n// 这里是使用MeshWorker框架的新的包含文件。第一个文件包含了 MeshWorker::DoFInfo, 类，它为局部积分器提供了局部与全局自由度之间的映射。在第二个文件中，我们发现一个类型为 MeshWorker::IntegrationInfo, 的对象，它主要是对一组FEValues对象的封装。文件<tt>meshworker/simple.h</tt>包含了将局部集成数据组装成只包含一个矩阵的全局系统的类。最后，我们将需要在所有的网格单元和面中运行循环的文件。\n\n#include <deal.II/meshworker/dof_info.h> \n#include <deal.II/meshworker/integration_info.h> \n#include <deal.II/meshworker/simple.h> \n#include <deal.II/meshworker/loop.h> \n\n// 像所有的程序一样，我们在完成这一部分时要包括所需的C++头文件，并声明我们要使用dealii命名空间中的对象，不加前缀。\n\n#include <iostream> \n#include <fstream> \n\nnamespace Step12 \n{ \n  using namespace dealii; \n// @sect3{Equation data}  \n\n// 首先，我们定义一个描述不均匀边界数据的类。由于只使用它的值，我们实现value_list()，但不定义Function的所有其他函数。\n\n  template <int dim> \n  class BoundaryValues : public Function<dim> \n  { \n  public: \n    BoundaryValues() = default; \n    virtual void value_list(const std::vector<Point<dim>> &points, \n                            std::vector<double> &          values, \n                            const unsigned int component = 0) const override; \n  }; \n\n// 考虑到流动方向，单位方块 $[0,1]^2$ 的流入边界为右边界和下边界。我们在x轴上规定了不连续的边界值1和0，在右边界上规定了值0。该函数在流出边界上的值将不会在DG方案中使用。\n\n  template <int dim> \n  void BoundaryValues<dim>::value_list(const std::vector<Point<dim>> &points, \n                                       std::vector<double> &          values, \n                                       const unsigned int component) const \n  { \n    (void)component; \n    AssertIndexRange(component, 1); \n    Assert(values.size() == points.size(), \n           ExcDimensionMismatch(values.size(), points.size())); \n\n    for (unsigned int i = 0; i < values.size(); ++i) \n      { \n        if (points[i](0) < 0.5) \n          values[i] = 1.; \n        else \n          values[i] = 0.; \n      } \n  } \n\n// 最后，一个计算并返回风场的函数  $\\beta=\\beta(\\mathbf x)$  。正如在介绍中所解释的，在2D中我们将使用一个围绕原点的旋转场。在3D中，我们只需不设置 $z$ 分量（即为零），而这个函数在目前的实现中不能用于1D。\n\n  template <int dim> \n  Tensor<1, dim> beta(const Point<dim> &p) \n  { \n    Assert(dim >= 2, ExcNotImplemented()); \n\n    Tensor<1, dim> wind_field; \n    wind_field[0] = -p[1]; \n    wind_field[1] = p[0]; \n    wind_field /= wind_field.norm(); \n\n    return wind_field; \n  } \n// @sect3{The AdvectionProblem class}  \n\n// 在这个准备工作之后，我们继续进行这个程序的主类，叫做AdvectionProblem。它基本上是  step-6  的主类。我们没有AffineConstraints对象，因为在DG离散中没有悬挂节点约束。\n\n// 主要的区别只出现在集合函数的实现上，因为在这里，我们不仅需要覆盖面上的通量积分，我们还使用MeshWorker接口来简化涉及的循环。\n\n  template <int dim> \n  class AdvectionProblem \n  { \n  public: \n    AdvectionProblem(); \n    void run(); \n\n  private: \n    void setup_system(); \n    void assemble_system(); \n    void solve(Vector<double> &solution); \n    void refine_grid(); \n    void output_results(const unsigned int cycle) const; \n\n    Triangulation<dim>   triangulation; \n    const MappingQ1<dim> mapping; \n\n// 此外，我们想使用程度为1的DG元素（但这只在构造函数中指定）。如果你想使用不同度数的DG方法，整个程序保持不变，只需在构造函数中用所需的多项式度数替换1。\n\n    FE_DGQ<dim>     fe; \n    DoFHandler<dim> dof_handler; \n\n// 接下来的四个成员代表要解决的线性系统。  <code>system_matrix</code> and <code>right_hand_side</code> 是由 <code>assemble_system()</code>, the <code>solution</code> 产生的， <code>solve()</code>. The <code>sparsity_pattern</code> 是用来确定 <code>system_matrix</code> 中非零元素的位置。\n\n    SparsityPattern      sparsity_pattern; \n    SparseMatrix<double> system_matrix; \n\n    Vector<double> solution; \n    Vector<double> right_hand_side; \n\n// 最后，我们必须提供集合单元、边界和内表面条款的函数。在MeshWorker框架中，所有单元的循环和大部分操作的设置都将在这个类之外完成，所以我们所要提供的只是这三个操作。他们将在中间对象上工作，首先，我们在这里定义了交给本地集成函数的信息对象的别名，以使我们的生活更轻松。\n\n    using DoFInfo  = MeshWorker::DoFInfo<dim>; \n    using CellInfo = MeshWorker::IntegrationInfo<dim>; \n\n// 下面的三个函数是在所有单元和面的通用循环中被调用的。它们是进行实际整合的函数。\n\n// 在我们下面的代码中，这些函数并不访问当前类的成员变量，所以我们可以将它们标记为 <code>static</code> ，并简单地将这些函数的指针传递给MeshWorker框架。然而，如果这些函数想要访问成员变量（或者需要额外的参数，而不是下面指定的参数），我们可以使用lambda函数的设施来为MeshWorker框架提供对象，这些对象就像它们拥有所需的参数数量和类型一样，但实际上已经绑定了其他参数。\n\n    static void integrate_cell_term(DoFInfo &dinfo, CellInfo &info); \n    static void integrate_boundary_term(DoFInfo &dinfo, CellInfo &info); \n    static void integrate_face_term(DoFInfo & dinfo1, \n                                    DoFInfo & dinfo2, \n                                    CellInfo &info1, \n                                    CellInfo &info2); \n  }; \n\n// 我们从构造函数开始。 <code>fe</code> 的构造器调用中的1是多项式的度数。\n\n  template <int dim> \n  AdvectionProblem<dim>::AdvectionProblem() \n    : mapping() \n    , fe(1) \n    , dof_handler(triangulation) \n  {} \n\n  template <int dim> \n  void AdvectionProblem<dim>::setup_system() \n  { \n\n// 在设置通常的有限元数据结构的函数中，我们首先需要分配DoF。\n\n    dof_handler.distribute_dofs(fe); \n\n// 我们从生成稀疏模式开始。为此，我们首先用系统中出现的耦合物填充一个动态稀疏模式（DynamicSparsityPattern）类型的中间对象。在建立模式之后，这个对象被复制到 <code>sparsity_pattern</code> 并可以被丢弃。\n\n// 为了建立DG离散的稀疏模式，我们可以调用类似于 DoFTools::make_sparsity_pattern, 的函数，它被称为 DoFTools::make_flux_sparsity_pattern:  \n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_flux_sparsity_pattern(dof_handler, dsp); \n    sparsity_pattern.copy_from(dsp); \n\n// 最后，我们设置了线性系统的所有组成部分的结构。\n\n    system_matrix.reinit(sparsity_pattern); \n    solution.reinit(dof_handler.n_dofs()); \n    right_hand_side.reinit(dof_handler.n_dofs()); \n  } \n// @sect4{The assemble_system function}  \n\n// 这里我们看到了与手工组装的主要区别。我们不需要在单元格和面上写循环，而是将这一切交给MeshWorker框架。为了做到这一点，我们只需要定义局部的集成函数，并使用命名空间 MeshWorker::Assembler 中的一个类来构建全局系统。\n\n  template <int dim> \n  void AdvectionProblem<dim>::assemble_system() \n  { \n\n// 这是一个神奇的对象，它知道关于数据结构和局部集成的一切。 这是在函数 MeshWorker::loop(), 中做工作的对象，它被下面的 MeshWorker::integration_loop() 隐式调用。在我们提供指针的函数完成局部积分后， MeshWorker::Assembler::SystemSimple 对象将这些数据分配到全局稀疏矩阵和右手边的向量。\n\n    MeshWorker::IntegrationInfoBox<dim> info_box; \n\n// 首先，我们在工作者基类中初始化正交公式和更新标志。对于正交，我们采取安全措施，使用QGauss公式，其点数比使用的多项式度数高一个。由于单元格、边界和内部面的正交率可以独立选择，我们必须把这个值交给三次。\n\n    const unsigned int n_gauss_points = dof_handler.get_fe().degree + 1; \n    info_box.initialize_gauss_quadrature(n_gauss_points, \n                                         n_gauss_points, \n                                         n_gauss_points); \n\n// 这些是我们整合系统时需要的数值类型。它们被添加到单元格、边界和内部面以及内部邻居面所使用的标志中，这是由四个 @p true 值强制执行的。\n\n    info_box.initialize_update_flags(); \n    UpdateFlags update_flags = \n      update_quadrature_points | update_values | update_gradients; \n    info_box.add_update_flags(update_flags, true, true, true, true); \n\n// 在准备好<tt>info_box</tt>中的所有数据后，我们初始化其中的FEValues对象。\n\n    info_box.initialize(fe, mapping); \n\n// 到目前为止创建的对象帮助我们在每个单元和面进行局部积分。现在，我们需要一个对象来接收整合后的（本地）数据，并将它们转发给装配程序。\n\n    MeshWorker::DoFInfo<dim> dof_info(dof_handler); \n\n// 现在，我们必须创建装配器对象，并告诉它将本地数据放在哪里。这些将是我们的系统矩阵和右手边的数据。\n\n    MeshWorker::Assembler::SystemSimple<SparseMatrix<double>, Vector<double>> \n      assembler; \n    assembler.initialize(system_matrix, right_hand_side); \n\n// 最后，在所有活动单元上进行积分循环（由第一个参数决定，它是一个活动迭代器）。\n\n// 正如在类声明中声明局部积分函数时的讨论中所指出的，装配积分器类所期望的参数实际上不是函数指针。相反，它们是可以像函数一样被调用的对象，有一定数量的参数。因此，我们也可以在这里传递具有适当的operator()实现的对象，或者如果本地集成器是，例如，非静态成员函数，则可以传递lambda函数。\n\n    MeshWorker::loop<dim, \n                     dim, \n                     MeshWorker::DoFInfo<dim>, \n                     MeshWorker::IntegrationInfoBox<dim>>( \n      dof_handler.begin_active(), \n      dof_handler.end(), \n      dof_info, \n      info_box, \n      &AdvectionProblem<dim>::integrate_cell_term, \n      &AdvectionProblem<dim>::integrate_boundary_term, \n      &AdvectionProblem<dim>::integrate_face_term, \n      assembler); \n  } \n// @sect4{The local integrators}  \n\n// 这些是给上面调用的 MeshWorker::integration_loop() 的函数。它们计算单元格和面中对系统矩阵和右手边的局部贡献。\n\n  template <int dim> \n  void AdvectionProblem<dim>::integrate_cell_term(DoFInfo & dinfo, \n                                                  CellInfo &info) \n  { \n\n// 首先，让我们从 @p info. 中检索这里使用的一些对象。注意，这些对象可以处理更复杂的结构，因此这里的访问看起来比看起来更复杂。\n\n    const FEValuesBase<dim> &  fe_values    = info.fe_values(); \n    FullMatrix<double> &       local_matrix = dinfo.matrix(0).matrix; \n    const std::vector<double> &JxW          = fe_values.get_JxW_values(); \n\n// 有了这些对象，我们像往常一样继续进行局部积分。首先，我们在正交点上循环，计算当前点的平流矢量。\n\n    for (unsigned int point = 0; point < fe_values.n_quadrature_points; ++point) \n      { \n        const Tensor<1, dim> beta_at_q_point = \n          beta(fe_values.quadrature_point(point)); \n\n// 我们求解的是一个同质方程，因此在单元项中没有显示出右手。 剩下的就是对矩阵项的积分。\n\n        for (unsigned int i = 0; i < fe_values.dofs_per_cell; ++i) \n          for (unsigned int j = 0; j < fe_values.dofs_per_cell; ++j) \n            local_matrix(i, j) += -beta_at_q_point *                // \n                                  fe_values.shape_grad(i, point) *  // \n                                  fe_values.shape_value(j, point) * // \n                                  JxW[point]; \n      } \n  } \n\n// 现在对边界条款也是如此。注意，现在我们使用FEValuesBase，即FEFaceValues和FESubfaceValues的基类，以便获得法向量。\n\n  template <int dim> \n  void AdvectionProblem<dim>::integrate_boundary_term(DoFInfo & dinfo, \n                                                      CellInfo &info) \n  { \n    const FEValuesBase<dim> &fe_face_values = info.fe_values(); \n    FullMatrix<double> &     local_matrix   = dinfo.matrix(0).matrix; \n    Vector<double> &         local_vector   = dinfo.vector(0).block(0); \n\n    const std::vector<double> &        JxW = fe_face_values.get_JxW_values(); \n    const std::vector<Tensor<1, dim>> &normals = \n      fe_face_values.get_normal_vectors(); \n\n    std::vector<double> g(fe_face_values.n_quadrature_points); \n\n    static BoundaryValues<dim> boundary_function; \n    boundary_function.value_list(fe_face_values.get_quadrature_points(), g); \n\n    for (unsigned int point = 0; point < fe_face_values.n_quadrature_points; \n         ++point) \n      { \n        const double beta_dot_n = \n          beta(fe_face_values.quadrature_point(point)) * normals[point]; \n        if (beta_dot_n > 0) \n          for (unsigned int i = 0; i < fe_face_values.dofs_per_cell; ++i) \n            for (unsigned int j = 0; j < fe_face_values.dofs_per_cell; ++j) \n              local_matrix(i, j) += beta_dot_n *                           // \n                                    fe_face_values.shape_value(j, point) * // \n                                    fe_face_values.shape_value(i, point) * // \n                                    JxW[point]; \n        else \n          for (unsigned int i = 0; i < fe_face_values.dofs_per_cell; ++i) \n            local_vector(i) += -beta_dot_n *                          // \n                               g[point] *                             // \n                               fe_face_values.shape_value(i, point) * // \n                               JxW[point]; \n      } \n  } \n\n// 最后是内部面的条款。这里的区别是，我们收到了两个信息对象，相邻面的每个单元都有一个，我们组装了四个矩阵，每个单元一个，两个用于来回耦合。\n\n  template <int dim> \n  void AdvectionProblem<dim>::integrate_face_term(DoFInfo & dinfo1, \n                                                  DoFInfo & dinfo2, \n                                                  CellInfo &info1, \n                                                  CellInfo &info2) \n  { \n\n// 对于正交点、权重等，我们使用第一个参数的FEValuesBase对象。\n\n    const FEValuesBase<dim> &fe_face_values = info1.fe_values(); \n    const unsigned int       dofs_per_cell  = fe_face_values.dofs_per_cell; \n\n// 对于额外的形状函数，我们必须询问邻居的FEValuesBase。\n\n    const FEValuesBase<dim> &fe_face_values_neighbor = info2.fe_values(); \n    const unsigned int       neighbor_dofs_per_cell = \n      fe_face_values_neighbor.dofs_per_cell; \n\n// 然后我们得到对四个局部矩阵的引用。字母u和v分别指的是试验和测试函数。%的数字表示由info1和info2提供的单元。按照惯例，每个信息对象中的两个矩阵指的是各自单元上的试验函数。第一个矩阵包含该单元的内部耦合，而第二个矩阵包含单元之间的耦合。\n\n    FullMatrix<double> &u1_v1_matrix = dinfo1.matrix(0, false).matrix; \n    FullMatrix<double> &u2_v1_matrix = dinfo1.matrix(0, true).matrix; \n    FullMatrix<double> &u1_v2_matrix = dinfo2.matrix(0, true).matrix; \n    FullMatrix<double> &u2_v2_matrix = dinfo2.matrix(0, false).matrix; \n\n// 在这里，按照前面的函数，我们会有本地的右手边向量。幸运的是，界面条款只涉及到解决方案，右手边没有收到任何贡献。\n\n    const std::vector<double> &        JxW = fe_face_values.get_JxW_values(); \n    const std::vector<Tensor<1, dim>> &normals = \n      fe_face_values.get_normal_vectors(); \n\n    for (unsigned int point = 0; point < fe_face_values.n_quadrature_points; \n         ++point) \n      { \n        const double beta_dot_n = \n          beta(fe_face_values.quadrature_point(point)) * normals[point]; \n        if (beta_dot_n > 0) \n          { \n\n// 这个词我们已经看过了。\n\n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                u1_v1_matrix(i, j) += beta_dot_n *                           // \n                                      fe_face_values.shape_value(j, point) * // \n                                      fe_face_values.shape_value(i, point) * // \n                                      JxW[point]; \n\n// 我们另外组装术语  $(\\beta\\cdot n u,\\hat v)_{\\partial \\kappa_+}$  。\n\n            for (unsigned int k = 0; k < neighbor_dofs_per_cell; ++k) \n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                u1_v2_matrix(k, j) += \n                  -beta_dot_n *                                   // \n                  fe_face_values.shape_value(j, point) *          // \n                  fe_face_values_neighbor.shape_value(k, point) * // \n                  JxW[point]; \n          } \n        else \n          { \n\n// 这个我们也已经看过了。\n\n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              for (unsigned int l = 0; l < neighbor_dofs_per_cell; ++l) \n                u2_v1_matrix(i, l) += \n                  beta_dot_n *                                    // \n                  fe_face_values_neighbor.shape_value(l, point) * // \n                  fe_face_values.shape_value(i, point) *          // \n                  JxW[point]; \n\n// 而这是另一个新的。 $(\\beta\\cdot n \\hat u,\\hat v)_{\\partial \\kappa_-}$  :\n\n            for (unsigned int k = 0; k < neighbor_dofs_per_cell; ++k) \n              for (unsigned int l = 0; l < neighbor_dofs_per_cell; ++l) \n                u2_v2_matrix(k, l) += \n                  -beta_dot_n *                                   // \n                  fe_face_values_neighbor.shape_value(l, point) * // \n                  fe_face_values_neighbor.shape_value(k, point) * // \n                  JxW[point]; \n          } \n      } \n  } \n// @sect3{All the rest}  \n\n// 对于这个简单的问题，我们使用了最简单的求解器，称为Richardson迭代，它代表了简单的缺陷修正。这与一个块状SSOR预处理相结合，该预处理使用DG离散化产生的系统矩阵的特殊块状结构。这些块的大小是每个单元的DoF数量。在这里，我们使用SSOR预处理，因为我们没有根据流场对DoFs进行重新编号。如果在流的下游方向对DoFs进行重新编号，那么块状的Gauss-Seidel预处理（见PreconditionBlockSOR类，放松=1）会做得更好。\n\n  template <int dim> \n  void AdvectionProblem<dim>::solve(Vector<double> &solution) \n  { \n    SolverControl                    solver_control(1000, 1e-12); \n    SolverRichardson<Vector<double>> solver(solver_control); \n\n// 这里我们创建了预处理程序。\n\n    PreconditionBlockSSOR<SparseMatrix<double>> preconditioner; \n\n// 然后将矩阵分配给它，并设置正确的块大小。\n\n    preconditioner.initialize(system_matrix, fe.n_dofs_per_cell()); \n\n// 做完这些准备工作后，我们就可以启动线性求解器了。\n\n    solver.solve(system_matrix, solution, right_hand_side, preconditioner); \n  } \n\n// 我们根据一个非常简单的细化标准来细化网格，即对解的梯度的近似。由于这里我们考虑的是DG(1)方法（即我们使用片状双线性形状函数），我们可以简单地计算每个单元的梯度。但是我们并不希望我们的细化指标只建立在每个单元的梯度上，而是希望同时建立在相邻单元之间的不连续解函数的跳跃上。最简单的方法是通过差分商计算近似梯度，包括考虑中的单元和其相邻的单元。这是由 <code>DerivativeApproximation</code> 类完成的，它计算近似梯度的方式类似于本教程 step-9 中描述的 <code>GradientEstimation</code> 。事实上， <code>DerivativeApproximation</code> 类是在 step-9 的 <code>GradientEstimation</code> 类之后开发的。与  step-9  中的讨论相关，这里我们考虑  $h^{1+d/2}|\\nabla_h u_h|$  。此外，我们注意到，我们不考虑近似的二次导数，因为线性平流方程的解一般不在 $H^2$ 中，而只在 $H^1$ 中（或者，更准确地说：在 $H^1_\\beta$ 中，即在方向 $\\beta$ 中的导数是可平方整除的函数空间）。\n\n  template <int dim> \n  void AdvectionProblem<dim>::refine_grid() \n  { \n\n//  <code>DerivativeApproximation</code> 类将梯度计算为浮点精度。这已经足够了，因为它们是近似的，只作为细化指标。\n\n    Vector<float> gradient_indicator(triangulation.n_active_cells()); \n\n// 现在，近似梯度被计算出来了\n\n    DerivativeApproximation::approximate_gradient(mapping, \n                                                  dof_handler, \n                                                  solution, \n                                                  gradient_indicator); \n\n//并且它们被单元格按比例放大，系数为 $h^{1+d/2}$  。\n    unsigned int cell_no = 0; \n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      gradient_indicator(cell_no++) *= \n        std::pow(cell->diameter(), 1 + 1.0 * dim / 2); \n\n// 最后它们作为细化指标。\n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    gradient_indicator, \n                                                    0.3, \n                                                    0.1); \n\n    triangulation.execute_coarsening_and_refinement(); \n  } \n\n// 这个程序的输出包括自适应细化网格的eps文件和gnuplot格式的数值解。\n\n  template <int dim> \n  void AdvectionProblem<dim>::output_results(const unsigned int cycle) const \n  { \n\n// 首先将网格写成eps格式。\n\n    { \n      const std::string filename = \"grid-\" + std::to_string(cycle) + \".eps\"; \n      deallog << \"Writing grid to <\" << filename << \">\" << std::endl; \n      std::ofstream eps_output(filename); \n\n      GridOut grid_out; \n      grid_out.write_eps(triangulation, eps_output); \n    } \n\n// 然后以gnuplot格式输出解决方案。\n\n    { \n      const std::string filename = \"sol-\" + std::to_string(cycle) + \".gnuplot\"; \n      deallog << \"Writing solution to <\" << filename << \">\" << std::endl; \n      std::ofstream gnuplot_output(filename); \n\n      DataOut<dim> data_out; \n      data_out.attach_dof_handler(dof_handler); \n      data_out.add_data_vector(solution, \"u\"); \n\n      data_out.build_patches(); \n\n      data_out.write_gnuplot(gnuplot_output); \n    } \n  } \n\n// 下面的 <code>run</code> 函数与前面的例子类似。\n\n  template <int dim> \n  void AdvectionProblem<dim>::run() \n  { \n    for (unsigned int cycle = 0; cycle < 6; ++cycle) \n      { \n        deallog << \"Cycle \" << cycle << std::endl; \n\n        if (cycle == 0) \n          { \n            GridGenerator::hyper_cube(triangulation); \n\n            triangulation.refine_global(3); \n          } \n        else \n          refine_grid(); \n\n        deallog << \"Number of active cells:       \" \n                << triangulation.n_active_cells() << std::endl; \n\n        setup_system(); \n\n        deallog << \"Number of degrees of freedom: \" << dof_handler.n_dofs() \n                << std::endl; \n\n        assemble_system(); \n        solve(solution); \n\n        output_results(cycle); \n      } \n  } \n} // namespace Step12 \n\n// 下面的 <code>main</code> 函数与前面的例子也类似，不需要注释。\n\nint main() \n{ \n  try \n    { \n      dealii::deallog.depth_console(5); \n\n      Step12::AdvectionProblem<2> dgmethod; \n      dgmethod.run(); \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "86e1be4a7d6de1a08306ae5ac91109fbf798c97f", "size": 20891, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-12b/step-12b.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-12b/step-12b.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-12b/step-12b.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0189655172, "max_line_length": 543, "alphanum_fraction": 0.6081566225, "num_tokens": 7711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.4404504617911398}}
{"text": "// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2018 www.open3d.org\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n// ----------------------------------------------------------------------------\n\n#include <Eigen/Eigenvalues>\n#include <queue>\n#include <tuple>\n\n#include \"open3d/geometry/KDTreeFlann.h\"\n#include \"open3d/geometry/PointCloud.h\"\n#include \"open3d/geometry/TetraMesh.h\"\n#include \"open3d/utility/Console.h\"\n#include \"open3d/utility/Eigen.h\"\n\nnamespace open3d {\n\nnamespace {\nusing namespace geometry;\n\nEigen::Vector3d ComputeEigenvector0(const Eigen::Matrix3d &A, double eval0) {\n    Eigen::Vector3d row0(A(0, 0) - eval0, A(0, 1), A(0, 2));\n    Eigen::Vector3d row1(A(0, 1), A(1, 1) - eval0, A(1, 2));\n    Eigen::Vector3d row2(A(0, 2), A(1, 2), A(2, 2) - eval0);\n    Eigen::Vector3d r0xr1 = row0.cross(row1);\n    Eigen::Vector3d r0xr2 = row0.cross(row2);\n    Eigen::Vector3d r1xr2 = row1.cross(row2);\n    double d0 = r0xr1.dot(r0xr1);\n    double d1 = r0xr2.dot(r0xr2);\n    double d2 = r1xr2.dot(r1xr2);\n\n    double dmax = d0;\n    int imax = 0;\n    if (d1 > dmax) {\n        dmax = d1;\n        imax = 1;\n    }\n    if (d2 > dmax) {\n        imax = 2;\n    }\n\n    if (imax == 0) {\n        return r0xr1 / std::sqrt(d0);\n    } else if (imax == 1) {\n        return r0xr2 / std::sqrt(d1);\n    } else {\n        return r1xr2 / std::sqrt(d2);\n    }\n}\n\nEigen::Vector3d ComputeEigenvector1(const Eigen::Matrix3d &A,\n                                    const Eigen::Vector3d &evec0,\n                                    double eval1) {\n    Eigen::Vector3d U, V;\n    if (std::abs(evec0(0)) > std::abs(evec0(1))) {\n        double inv_length =\n                1 / std::sqrt(evec0(0) * evec0(0) + evec0(2) * evec0(2));\n        U << -evec0(2) * inv_length, 0, evec0(0) * inv_length;\n    } else {\n        double inv_length =\n                1 / std::sqrt(evec0(1) * evec0(1) + evec0(2) * evec0(2));\n        U << 0, evec0(2) * inv_length, -evec0(1) * inv_length;\n    }\n    V = evec0.cross(U);\n\n    Eigen::Vector3d AU(A(0, 0) * U(0) + A(0, 1) * U(1) + A(0, 2) * U(2),\n                       A(0, 1) * U(0) + A(1, 1) * U(1) + A(1, 2) * U(2),\n                       A(0, 2) * U(0) + A(1, 2) * U(1) + A(2, 2) * U(2));\n\n    Eigen::Vector3d AV = {A(0, 0) * V(0) + A(0, 1) * V(1) + A(0, 2) * V(2),\n                          A(0, 1) * V(0) + A(1, 1) * V(1) + A(1, 2) * V(2),\n                          A(0, 2) * V(0) + A(1, 2) * V(1) + A(2, 2) * V(2)};\n\n    double m00 = U(0) * AU(0) + U(1) * AU(1) + U(2) * AU(2) - eval1;\n    double m01 = U(0) * AV(0) + U(1) * AV(1) + U(2) * AV(2);\n    double m11 = V(0) * AV(0) + V(1) * AV(1) + V(2) * AV(2) - eval1;\n\n    double absM00 = std::abs(m00);\n    double absM01 = std::abs(m01);\n    double absM11 = std::abs(m11);\n    double max_abs_comp;\n    if (absM00 >= absM11) {\n        max_abs_comp = std::max(absM00, absM01);\n        if (max_abs_comp > 0) {\n            if (absM00 >= absM01) {\n                m01 /= m00;\n                m00 = 1 / std::sqrt(1 + m01 * m01);\n                m01 *= m00;\n            } else {\n                m00 /= m01;\n                m01 = 1 / std::sqrt(1 + m00 * m00);\n                m00 *= m01;\n            }\n            return m01 * U - m00 * V;\n        } else {\n            return U;\n        }\n    } else {\n        max_abs_comp = std::max(absM11, absM01);\n        if (max_abs_comp > 0) {\n            if (absM11 >= absM01) {\n                m01 /= m11;\n                m11 = 1 / std::sqrt(1 + m01 * m01);\n                m01 *= m11;\n            } else {\n                m11 /= m01;\n                m01 = 1 / std::sqrt(1 + m11 * m11);\n                m11 *= m01;\n            }\n            return m11 * U - m01 * V;\n        } else {\n            return U;\n        }\n    }\n}\n\nEigen::Vector3d FastEigen3x3(Eigen::Matrix3d &A) {\n    // Previous version based on:\n    // https://en.wikipedia.org/wiki/Eigenvalue_algorithm#3.C3.973_matrices\n    // Current version based on\n    // https://www.geometrictools.com/Documentation/RobustEigenSymmetric3x3.pdf\n    // which handles edge cases like points on a plane\n\n    double max_coeff = A.maxCoeff();\n    if (max_coeff == 0) {\n        return Eigen::Vector3d::Zero();\n    }\n    A /= max_coeff;\n\n    double norm = A(0, 1) * A(0, 1) + A(0, 2) * A(0, 2) + A(1, 2) * A(1, 2);\n    if (norm > 0) {\n        Eigen::Vector3d eval;\n        Eigen::Vector3d evec0;\n        Eigen::Vector3d evec1;\n        Eigen::Vector3d evec2;\n\n        double q = (A(0, 0) + A(1, 1) + A(2, 2)) / 3;\n\n        double b00 = A(0, 0) - q;\n        double b11 = A(1, 1) - q;\n        double b22 = A(2, 2) - q;\n\n        double p =\n                std::sqrt((b00 * b00 + b11 * b11 + b22 * b22 + norm * 2) / 6);\n\n        double c00 = b11 * b22 - A(1, 2) * A(1, 2);\n        double c01 = A(0, 1) * b22 - A(1, 2) * A(0, 2);\n        double c02 = A(0, 1) * A(1, 2) - b11 * A(0, 2);\n        double det = (b00 * c00 - A(0, 1) * c01 + A(0, 2) * c02) / (p * p * p);\n\n        double half_det = det * 0.5;\n        half_det = std::min(std::max(half_det, -1.0), 1.0);\n\n        double angle = std::acos(half_det) / (double)3;\n        double const two_thirds_pi = 2.09439510239319549;\n        double beta2 = std::cos(angle) * 2;\n        double beta0 = std::cos(angle + two_thirds_pi) * 2;\n        double beta1 = -(beta0 + beta2);\n\n        eval(0) = q + p * beta0;\n        eval(1) = q + p * beta1;\n        eval(2) = q + p * beta2;\n\n        if (half_det >= 0) {\n            evec2 = ComputeEigenvector0(A, eval(2));\n            if (eval(2) < eval(0) && eval(2) < eval(1)) {\n                A *= max_coeff;\n                return evec2;\n            }\n            evec1 = ComputeEigenvector1(A, evec2, eval(1));\n            A *= max_coeff;\n            if (eval(1) < eval(0) && eval(1) < eval(2)) {\n                return evec1;\n            }\n            evec0 = evec1.cross(evec2);\n            return evec0;\n        } else {\n            evec0 = ComputeEigenvector0(A, eval(0));\n            if (eval(0) < eval(1) && eval(0) < eval(2)) {\n                A *= max_coeff;\n                return evec0;\n            }\n            evec1 = ComputeEigenvector1(A, evec0, eval(1));\n            A *= max_coeff;\n            if (eval(1) < eval(0) && eval(1) < eval(2)) {\n                return evec1;\n            }\n            evec2 = evec0.cross(evec1);\n            return evec2;\n        }\n    } else {\n        A *= max_coeff;\n        if (A(0, 0) < A(1, 1) && A(0, 0) < A(2, 2)) {\n            return Eigen::Vector3d(1, 0, 0);\n        } else if (A(1, 1) < A(0, 0) && A(1, 1) < A(2, 2)) {\n            return Eigen::Vector3d(0, 1, 0);\n        } else {\n            return Eigen::Vector3d(0, 0, 1);\n        }\n    }\n}\n\nEigen::Vector3d ComputeNormal(const PointCloud &cloud,\n                              const std::vector<int> &indices,\n                              bool fast_normal_computation) {\n    if (indices.size() == 0) {\n        return Eigen::Vector3d::Zero();\n    }\n    Eigen::Matrix3d covariance =\n            utility::ComputeCovariance(cloud.points_, indices);\n\n    if (fast_normal_computation) {\n        return FastEigen3x3(covariance);\n    } else {\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> solver;\n        solver.compute(covariance, Eigen::ComputeEigenvectors);\n        return solver.eigenvectors().col(0);\n    }\n}\n\n// Disjoint set data structure to find cycles in graphs\nclass DisjointSet {\npublic:\n    DisjointSet(size_t size) : parent_(size), size_(size) {\n        for (size_t idx = 0; idx < size; idx++) {\n            parent_[idx] = idx;\n            size_[idx] = 0;\n        }\n    }\n\n    // find representative element for given x\n    // using path compression\n    size_t Find(size_t x) {\n        if (x != parent_[x]) {\n            parent_[x] = Find(parent_[x]);\n        }\n        return parent_[x];\n    }\n\n    // combine two sets using size of sets\n    void Union(size_t x, size_t y) {\n        x = Find(x);\n        y = Find(y);\n        if (x != y) {\n            if (size_[x] < size_[y]) {\n                size_[y] += size_[x];\n                parent_[x] = y;\n            } else {\n                size_[x] += size_[y];\n                parent_[y] = x;\n            }\n        }\n    }\n\nprivate:\n    std::vector<size_t> parent_;\n    std::vector<size_t> size_;\n};\n\nstruct WeightedEdge {\n    WeightedEdge(size_t v0, size_t v1, double weight)\n        : v0_(v0), v1_(v1), weight_(weight) {}\n    size_t v0_;\n    size_t v1_;\n    double weight_;\n};\n\n// Minimum Spanning Tree algorithm (Kruskal's algorithm)\nstd::vector<WeightedEdge> Kruskal(std::vector<WeightedEdge> &edges,\n                                  size_t n_vertices) {\n    std::sort(edges.begin(), edges.end(),\n              [](WeightedEdge &e0, WeightedEdge &e1) {\n                  return e0.weight_ < e1.weight_;\n              });\n    DisjointSet disjoint_set(n_vertices);\n    std::vector<WeightedEdge> mst;\n    for (size_t eidx = 0; eidx < edges.size(); ++eidx) {\n        size_t set0 = disjoint_set.Find(edges[eidx].v0_);\n        size_t set1 = disjoint_set.Find(edges[eidx].v1_);\n        if (set0 != set1) {\n            mst.push_back(edges[eidx]);\n            disjoint_set.Union(set0, set1);\n        }\n    }\n    return mst;\n}\n\n}  // unnamed namespace\n\nnamespace geometry {\n\nvoid PointCloud::EstimateNormals(\n        const KDTreeSearchParam &search_param /* = KDTreeSearchParamKNN()*/,\n        bool fast_normal_computation /* = true */) {\n    bool has_normal = HasNormals();\n    if (!has_normal) {\n        normals_.resize(points_.size());\n    }\n    KDTreeFlann kdtree;\n    kdtree.SetGeometry(*this);\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n    for (int i = 0; i < (int)points_.size(); i++) {\n        std::vector<int> indices;\n        std::vector<double> distance2;\n        Eigen::Vector3d normal;\n        if (kdtree.Search(points_[i], search_param, indices, distance2) >= 3) {\n            normal = ComputeNormal(*this, indices, fast_normal_computation);\n            if (normal.norm() == 0.0) {\n                if (has_normal) {\n                    normal = normals_[i];\n                } else {\n                    normal = Eigen::Vector3d(0.0, 0.0, 1.0);\n                }\n            }\n            if (has_normal && normal.dot(normals_[i]) < 0.0) {\n                normal *= -1.0;\n            }\n            normals_[i] = normal;\n        } else {\n            normals_[i] = Eigen::Vector3d(0.0, 0.0, 1.0);\n        }\n    }\n}\n\nvoid PointCloud::OrientNormalsToAlignWithDirection(\n        const Eigen::Vector3d &orientation_reference\n        /* = Eigen::Vector3d(0.0, 0.0, 1.0)*/) {\n    if (!HasNormals()) {\n        utility::LogError(\n                \"[OrientNormalsToAlignWithDirection] No normals in the \"\n                \"PointCloud. Call EstimateNormals() first.\");\n    }\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n    for (int i = 0; i < (int)points_.size(); i++) {\n        auto &normal = normals_[i];\n        if (normal.norm() == 0.0) {\n            normal = orientation_reference;\n        } else if (normal.dot(orientation_reference) < 0.0) {\n            normal *= -1.0;\n        }\n    }\n}\n\nvoid PointCloud::OrientNormalsTowardsCameraLocation(\n        const Eigen::Vector3d &camera_location /* = Eigen::Vector3d::Zero()*/) {\n    if (!HasNormals()) {\n        utility::LogError(\n                \"[OrientNormalsTowardsCameraLocation] No normals in the \"\n                \"PointCloud. Call EstimateNormals() first.\");\n    }\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n    for (int i = 0; i < (int)points_.size(); i++) {\n        Eigen::Vector3d orientation_reference = camera_location - points_[i];\n        auto &normal = normals_[i];\n        if (normal.norm() == 0.0) {\n            normal = orientation_reference;\n            if (normal.norm() == 0.0) {\n                normal = Eigen::Vector3d(0.0, 0.0, 1.0);\n            } else {\n                normal.normalize();\n            }\n        } else if (normal.dot(orientation_reference) < 0.0) {\n            normal *= -1.0;\n        }\n    }\n}\n\nvoid PointCloud::OrientNormalsConsistentTangentPlane(size_t k) {\n    if (!HasNormals()) {\n        utility::LogError(\n                \"[OrientNormalsConsistentTangentPlane] No normals in the \"\n                \"PointCloud. Call EstimateNormals() first.\");\n    }\n\n    // Create Riemannian graph (Euclidian MST + kNN)\n    // Euclidian MST is subgraph of Delaunay triangulation\n    std::shared_ptr<TetraMesh> delaunay_mesh;\n    std::vector<size_t> pt_map;\n    std::tie(delaunay_mesh, pt_map) = TetraMesh::CreateFromPointCloud(*this);\n    std::vector<WeightedEdge> delaunay_graph;\n    std::unordered_set<size_t> graph_edges;\n    auto EdgeIndex = [&](size_t v0, size_t v1) -> size_t {\n        return std::min(v0, v1) * points_.size() + std::max(v0, v1);\n    };\n    auto AddEdgeToDelaunayGraph = [&](size_t v0, size_t v1) {\n        v0 = pt_map[v0];\n        v1 = pt_map[v1];\n        size_t edge = EdgeIndex(v0, v1);\n        if (graph_edges.count(edge) == 0) {\n            double dist = (points_[v0] - points_[v1]).squaredNorm();\n            delaunay_graph.push_back(WeightedEdge(v0, v1, dist));\n            graph_edges.insert(edge);\n        }\n    };\n    for (const Eigen::Vector4i &tetra : delaunay_mesh->tetras_) {\n        AddEdgeToDelaunayGraph(tetra[0], tetra[1]);\n        AddEdgeToDelaunayGraph(tetra[0], tetra[2]);\n        AddEdgeToDelaunayGraph(tetra[0], tetra[3]);\n        AddEdgeToDelaunayGraph(tetra[1], tetra[2]);\n        AddEdgeToDelaunayGraph(tetra[1], tetra[3]);\n        AddEdgeToDelaunayGraph(tetra[2], tetra[3]);\n    }\n\n    std::vector<WeightedEdge> mst = Kruskal(delaunay_graph, points_.size());\n\n    auto NormalWeight = [&](size_t v0, size_t v1) -> double {\n        return 1.0 - std::abs(normals_[v0].dot(normals_[v1]));\n    };\n    for (auto &edge : mst) {\n        edge.weight_ = NormalWeight(edge.v0_, edge.v1_);\n    }\n\n    // Add k nearest neighbors to Riemannian graph\n    KDTreeFlann kdtree(*this);\n    for (size_t v0 = 0; v0 < points_.size(); ++v0) {\n        std::vector<int> neighbors;\n        std::vector<double> dists2;\n        kdtree.SearchKNN(points_[v0], int(k), neighbors, dists2);\n        for (size_t vidx1 = 0; vidx1 < neighbors.size(); ++vidx1) {\n            size_t v1 = size_t(neighbors[vidx1]);\n            if (v0 == v1) {\n                continue;\n            }\n            size_t edge = EdgeIndex(v0, v1);\n            if (graph_edges.count(edge) == 0) {\n                double weight = NormalWeight(v0, v1);\n                mst.push_back(WeightedEdge(v0, v1, weight));\n                graph_edges.insert(edge);\n            }\n        }\n    }\n\n    // extract MST from Riemannian graph\n    mst = Kruskal(mst, points_.size());\n\n    // convert list of edges to graph\n    std::vector<std::unordered_set<size_t>> mst_graph(points_.size());\n    for (const auto &edge : mst) {\n        size_t v0 = edge.v0_;\n        size_t v1 = edge.v1_;\n        mst_graph[v0].insert(v1);\n        mst_graph[v1].insert(v0);\n    }\n\n    // find start node for tree traversal\n    // init with node that maximizes z\n    double max_z = std::numeric_limits<double>::lowest();\n    size_t v0;\n    for (size_t vidx = 0; vidx < points_.size(); ++vidx) {\n        const Eigen::Vector3d &v = points_[vidx];\n        if (v(2) > max_z) {\n            max_z = v(2);\n            v0 = vidx;\n        }\n    }\n\n    // traverse MST and orient normals consistently\n    std::queue<size_t> traversal_queue;\n    std::vector<bool> visited(points_.size(), false);\n    traversal_queue.push(v0);\n    auto TestAndOrientNormal = [&](const Eigen::Vector3d &n0,\n                                   Eigen::Vector3d &n1) {\n        if (n0.dot(n1) < 0) {\n            n1 *= -1;\n        }\n    };\n    TestAndOrientNormal(Eigen::Vector3d(0, 0, 1), normals_[v0]);\n    while (!traversal_queue.empty()) {\n        v0 = traversal_queue.front();\n        traversal_queue.pop();\n        visited[v0] = true;\n        for (size_t v1 : mst_graph[v0]) {\n            if (!visited[v1]) {\n                traversal_queue.push(v1);\n                TestAndOrientNormal(normals_[v0], normals_[v1]);\n            }\n        }\n    }\n}\n\n}  // namespace geometry\n}  // namespace open3d\n", "meta": {"hexsha": "819220256b9149dfa7ff212fe5eac0584576d9ad", "size": 17320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/open3d/geometry/EstimateNormals.cpp", "max_stars_repo_name": "jt-l/Open3D", "max_stars_repo_head_hexsha": "e2c5043e3bb1f23b16fa1718a8f2551d65d78526", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-24T10:09:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-24T10:09:22.000Z", "max_issues_repo_path": "cpp/open3d/geometry/EstimateNormals.cpp", "max_issues_repo_name": "LinkonBSMRSTU/Open3D", "max_issues_repo_head_hexsha": "7f02137cef52b6ad0f67fe72ae5bc0a795d77117", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/open3d/geometry/EstimateNormals.cpp", "max_forks_repo_name": "LinkonBSMRSTU/Open3D", "max_forks_repo_head_hexsha": "7f02137cef52b6ad0f67fe72ae5bc0a795d77117", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-25T20:23:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T20:23:11.000Z", "avg_line_length": 33.9607843137, "max_line_length": 80, "alphanum_fraction": 0.5246535797, "num_tokens": 5233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6584175139669998, "lm_q1q2_score": 0.440402478175079}}
{"text": "//  (C) Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_TOOLS_POLYNOMIAL_HPP\r\n#define BOOST_MATH_TOOLS_POLYNOMIAL_HPP\r\n\r\n#include <boost/assert.hpp>\r\n#include <boost/math/tools/rational.hpp>\r\n#include <boost/math/tools/real_cast.hpp>\r\n\r\n#include <vector>\r\n\r\nnamespace boost{ namespace math{ namespace tools{\r\n\r\ntemplate <class T>\r\nclass polynomial\r\n{\r\npublic:\r\n   // typedefs:\r\n   typedef typename std::vector<T>::value_type value_type;\r\n   typedef typename std::vector<T>::size_type size_type;\r\n\r\n   // construct:\r\n   polynomial(){}\r\n   template <class U>\r\n   polynomial(const U* data, unsigned order)\r\n      : m_data(data, data + order + 1)\r\n   {\r\n   }\r\n   template <class U>\r\n   polynomial(const U& point)\r\n   {\r\n      m_data.push_back(point);\r\n   }\r\n\r\n   // copy:\r\n   polynomial(const polynomial& p)\r\n      : m_data(p.m_data) { }\r\n\r\n   template <class U>\r\n   polynomial(const polynomial<U>& p)\r\n   {\r\n      for(unsigned i = 0; i < p.size(); ++i)\r\n      {\r\n         m_data.push_back(boost::math::tools::real_cast<T>(p[i]));\r\n      }\r\n   }\r\n\r\n   // access:\r\n   size_type size()const { return m_data.size(); }\r\n   size_type degree()const { return m_data.size() - 1; }\r\n   value_type& operator[](size_type i)\r\n   {\r\n      return m_data[i];\r\n   }\r\n   const value_type& operator[](size_type i)const\r\n   {\r\n      return m_data[i];\r\n   }\r\n   T evaluate(T z)const\r\n   {\r\n      return boost::math::tools::evaluate_polynomial(&m_data[0], z, m_data.size());;\r\n   }\r\n\r\n   // operators:\r\n   template <class U>\r\n   polynomial& operator +=(const U& value)\r\n   {\r\n      if(m_data.size() == 0)\r\n         m_data.push_back(value);\r\n      else\r\n      {\r\n         m_data[0] += value;\r\n      }\r\n      return *this;\r\n   }\r\n   template <class U>\r\n   polynomial& operator -=(const U& value)\r\n   {\r\n      if(m_data.size() == 0)\r\n         m_data.push_back(-value);\r\n      else\r\n      {\r\n         m_data[0] -= value;\r\n      }\r\n      return *this;\r\n   }\r\n   template <class U>\r\n   polynomial& operator *=(const U& value)\r\n   {\r\n      for(size_type i = 0; i < m_data.size(); ++i)\r\n         m_data[i] *= value;\r\n      return *this;\r\n   }\r\n   template <class U>\r\n   polynomial& operator +=(const polynomial<U>& value)\r\n   {\r\n      size_type s1 = (std::min)(m_data.size(), value.size());\r\n      for(size_type i = 0; i < s1; ++i)\r\n         m_data[i] += value[i];\r\n      for(size_type i = s1; i < value.size(); ++i)\r\n         m_data.push_back(value[i]);\r\n      return *this;\r\n   }\r\n   template <class U>\r\n   polynomial& operator -=(const polynomial<U>& value)\r\n   {\r\n      size_type s1 = (std::min)(m_data.size(), value.size());\r\n      for(size_type i = 0; i < s1; ++i)\r\n         m_data[i] -= value[i];\r\n      for(size_type i = s1; i < value.size(); ++i)\r\n         m_data.push_back(-value[i]);\r\n      return *this;\r\n   }\r\n   template <class U>\r\n   polynomial& operator *=(const polynomial<U>& value)\r\n   {\r\n      // TODO: FIXME: use O(N log(N)) algorithm!!!\r\n      BOOST_ASSERT(value.size());\r\n      polynomial base(*this);\r\n      *this *= value[0];\r\n      for(size_type i = 1; i < value.size(); ++i)\r\n      {\r\n         polynomial t(base);\r\n         t *= value[i];\r\n         size_type s = size() - i;\r\n         for(size_type j = 0; j < s; ++j)\r\n         {\r\n            m_data[i+j] += t[j];\r\n         }\r\n         for(size_type j = s; j < t.size(); ++j)\r\n            m_data.push_back(t[j]);\r\n      }\r\n      return *this;\r\n   }\r\n\r\nprivate:\r\n   std::vector<T> m_data;\r\n};\r\n\r\ntemplate <class T>\r\ninline polynomial<T> operator + (const polynomial<T>& a, const polynomial<T>& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result += b;\r\n   return result;\r\n}\r\n\r\ntemplate <class T>\r\ninline polynomial<T> operator - (const polynomial<T>& a, const polynomial<T>& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result -= b;\r\n   return result;\r\n}\r\n\r\ntemplate <class T>\r\ninline polynomial<T> operator * (const polynomial<T>& a, const polynomial<T>& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result *= b;\r\n   return result;\r\n}\r\n\r\ntemplate <class T, class U>\r\ninline polynomial<T> operator + (const polynomial<T>& a, const U& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result += b;\r\n   return result;\r\n}\r\n\r\ntemplate <class T, class U>\r\ninline polynomial<T> operator - (const polynomial<T>& a, const U& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result -= b;\r\n   return result;\r\n}\r\n\r\ntemplate <class T, class U>\r\ninline polynomial<T> operator * (const polynomial<T>& a, const U& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result *= b;\r\n   return result;\r\n}\r\n\r\ntemplate <class U, class T>\r\ninline polynomial<T> operator + (const U& a, const polynomial<T>& b)\r\n{\r\n   polynomial<T> result(b);\r\n   result += a;\r\n   return result;\r\n}\r\n\r\ntemplate <class U, class T>\r\ninline polynomial<T> operator - (const U& a, const polynomial<T>& b)\r\n{\r\n   polynomial<T> result(a);\r\n   result -= b;\r\n   return result;\r\n}\r\n\r\ntemplate <class U, class T>\r\ninline polynomial<T> operator * (const U& a, const polynomial<T>& b)\r\n{\r\n   polynomial<T> result(b);\r\n   result *= a;\r\n   return result;\r\n}\r\n\r\ntemplate <class charT, class traits, class T>\r\ninline std::basic_ostream<charT, traits>& operator << (std::basic_ostream<charT, traits>& os, const polynomial<T>& poly)\r\n{\r\n   os << \"{ \";\r\n   for(unsigned i = 0; i < poly.size(); ++i)\r\n   {\r\n      if(i) os << \", \";\r\n      os << poly[i];\r\n   }\r\n   os << \" }\";\r\n   return os;\r\n}\r\n\r\n} // namespace tools\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#endif // BOOST_MATH_TOOLS_POLYNOMIAL_HPP\r\n\r\n\r\n", "meta": {"hexsha": "3eeb65682b225d86dab534dc8da439c031c3d20d", "size": 5636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/windows/boost/include/boost/math/tools/polynomial.hpp", "max_stars_repo_name": "foxostro/CheeseTesseract", "max_stars_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-05-17T03:36:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-17T03:36:52.000Z", "max_issues_repo_path": "external/windows/boost/include/boost/math/tools/polynomial.hpp", "max_issues_repo_name": "foxostro/CheeseTesseract", "max_issues_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/windows/boost/include/boost/math/tools/polynomial.hpp", "max_forks_repo_name": "foxostro/CheeseTesseract", "max_forks_repo_head_hexsha": "737ebbd19cee8f5a196bf39a11ca793c561e56cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9829787234, "max_line_length": 121, "alphanum_fraction": 0.5684882896, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.4404024692085272}}
{"text": "#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <Eigen/Dense>\n#include <cmath>\n\nnamespace py = pybind11;\n\nvoid line(double fx1, double fy1, double fx2, double fy2, const Eigen::MatrixXd& global_map,\n          Eigen::MatrixXd& op_map) {\n  int x1 = static_cast<int>(round(fx1));\n  int y1 = static_cast<int>(round(fy1));\n  int x2 = static_cast<int>(round(fx2));\n  int y2 = static_cast<int>(round(fy2));\n\n  int dx = abs(x2 - x1);\n  int dy = abs(y2 - y1);\n  int x = x1, y = y1;\n  int error = dx - dy;\n  int x_inc = x2 > x1 ? 1 : -1;\n  int y_inc = y2 > y1 ? 1 : -1;\n  dx *= 2;\n  dy *= 2;\n\n  int coll_flag = 0;\n  int coll_size = 10;\n\n  int rows = global_map.rows();\n  int cols = global_map.cols();\n\n  while (x >= 0 && x < cols && y >= 0 && y < rows) {\n    if (x == x2 && y == y2) break;\n\n    int k = global_map(y, x);\n    if (k != 1 && coll_flag > 0) break;\n    if (k == 1 && coll_flag < coll_size) coll_flag += 1;\n\n    op_map(y, x) = k;\n\n    if (k == 1 && coll_flag == coll_size) break;\n\n    if (error > 0) {\n      x += x_inc;\n      error -= dy;\n    } else {\n      y += y_inc;\n      error += dx;\n    }\n  }\n}\n\nEigen::MatrixXd inverse_sensor_model(int x0, int y0, int sensor_range,\n                            Eigen::MatrixXd op_map, Eigen::MatrixXd global_map) {\n  Eigen::MatrixXd op_map_mod(op_map);\n  double sensor_angle_inc = 0.5 / 180.0 * M_PI;\n  for (double angle = 0.0; angle < M_PI * 2.0; angle += sensor_angle_inc) {\n    double x1 = double(x0) + double(sensor_range) * cos(angle);\n    double y1 = double (y0) + double(sensor_range) * sin(angle);\n    line(x0, y0, x1, y1, global_map, op_map_mod);\n  }\n  return op_map_mod;\n}\n\nPYBIND11_PLUGIN(inverse_sensor_model) {\n  py::module m(\"inverse_sensor_model\", \"inverse_sensor_model\");\n  m.def(\"inverse_sensor_model\", &inverse_sensor_model, \"inverse_sensor_model\");\n  return m.ptr();\n}\n", "meta": {"hexsha": "4809b280e336d235d3fba41190a4999e78447976", "size": 1849, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/inverse_sensor_model.cpp", "max_stars_repo_name": "oiqbal95/RL-Self-Exploration-Mapping", "max_stars_repo_head_hexsha": "71350bdcf9d4429e23de5e62cf5e1a6e655026d3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2020-07-25T11:33:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:17:43.000Z", "max_issues_repo_path": "src/inverse_sensor_model.cpp", "max_issues_repo_name": "oiqbal95/RL-Self-Exploration-Mapping", "max_issues_repo_head_hexsha": "71350bdcf9d4429e23de5e62cf5e1a6e655026d3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-08T02:05:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T13:15:57.000Z", "max_forks_repo_path": "src/inverse_sensor_model.cpp", "max_forks_repo_name": "oiqbal95/RL-Self-Exploration-Mapping", "max_forks_repo_head_hexsha": "71350bdcf9d4429e23de5e62cf5e1a6e655026d3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-09-07T03:32:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T11:17:29.000Z", "avg_line_length": 27.1911764706, "max_line_length": 92, "alphanum_fraction": 0.6014061655, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.44037267849808}}
{"text": "/*\n * This is part of the fl library, a C++ Bayesian filtering library\n * (https://github.com/filtering-library)\n *\n * Copyright (c) 2015 Max Planck Society,\n * \t\t\t\t Autonomous Motion Department,\n * \t\t\t     Institute for Intelligent Systems\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n */\n\n/**\n * \\file joint_sensor_iid.hpp\n * \\date Febuary 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n\n#include <Eigen/Dense>\n\n#include <memory>\n#include <type_traits>\n\n#include <fl/util/types.hpp>\n#include <fl/util/traits.hpp>\n#include <fl/util/descriptor.hpp>\n#include <fl/util/meta.hpp>\n#include <fl/distribution/gaussian.hpp>\n\n#include <fl/model/adaptive_model.hpp>\n#include <fl/model/sensor/interface/sensor_function.hpp>\n\nnamespace fl\n{\n\n// Forward declarations\ntemplate <typename...Models> class JointSensor;\n\n/**\n * Traits of JointSensor<MultipleOf<Sensor, Count>>\n */\ntemplate <\n    typename Sensor,\n    int Count\n>\nstruct Traits<JointSensor<MultipleOf<Sensor, Count>>>\n{\n    enum : signed int { ModelCount = Count };\n\n    typedef Sensor LocalSensor;\n    typedef typename Sensor::State State;\n    typedef typename Sensor::Obsrv::Scalar Scalar;\n    typedef typename Sensor::Obsrv LocalObsrv;\n    typedef typename Sensor::Noise LocalNoise;\n\n    enum : signed int\n    {\n        StateDim = SizeOf<State>::Value,\n        ObsrvDim = ExpandSizes<SizeOf<LocalObsrv>::Value, Count>::Value,\n        NoiseDim = ExpandSizes<SizeOf<LocalNoise>::Value, Count>::Value\n    };\n\n    typedef Eigen::Matrix<Scalar, ObsrvDim, 1> Obsrv;\n    typedef Eigen::Matrix<Scalar, NoiseDim, 1> Noise;\n\n    typedef SensorFunction<Obsrv, State, Noise> SensorFunctionBase;\n};\n\n/**\n * \\ingroup sensors\n *\n * \\brief JointSensor itself is an observation model which contains\n * internally multiple models all of the \\em same type. The joint model can be\n * simply summarized as \\f$ h(x, \\theta, w) = [ h_{local}(x, \\theta_1, w_1),\n * h_{local}(x, \\theta_2, w_2), \\ldots, h_{local}(x, \\theta_n, w_n) ]^T \\f$\n *\n * where \\f$x\\f$ is the state variate, \\f$\\theta = [ \\theta_1, \\theta_2, \\ldots,\n * \\theta_n ]^T\\f$ and \\f$w = [ w_1, w_2, \\ldots, w_n ]^T\\f$  are the the\n * parameters and noise terms of each of the \\f$n\\f$ models.\n *\n * JointSensor implements the SensorInterface and the\n * AdaptiveModel interface. That being said, the JointSensor can be\n * used as a regular observation model or even as an adaptive observation model\n * which provides a set of parameters that can be changed at any time. This\n * implies that all sub-models must implement the the AdaptiveModel\n * interface. However, if the sub-model is not adaptive, JointSensor\n * applies a decorator call the NotAdaptive operator on the sub-model. This\n * operator enables any model to be treated as if it is adaptive without\n * effecting the model behaviour.\n */\ntemplate <\n    typename LocalSensor,\n    int Count\n>\nclass JointSensor<MultipleOf<LocalSensor, Count>>\n    : public Traits<\n                 JointSensor<MultipleOf<LocalSensor, Count>>\n             >::SensorFunctionBase,\n      public Descriptor,\n      private internal::JointSensorIidType\n{\nprivate:\n    typedef JointSensor<MultipleOf<LocalSensor,Count>> This;\n\npublic:\n    enum : signed int { ModelCount = Count };\n\n    typedef LocalSensor LocalModel;\n    typedef typename Traits<This>::LocalObsrv LocalObsrv;\n    typedef typename Traits<This>::LocalNoise LocalNoise;\n\n    typedef typename Traits<This>::Obsrv Obsrv;\n    typedef typename Traits<This>::Noise Noise;\n    typedef typename Traits<This>::State State;\n\npublic:\n    JointSensor(\n            const LocalSensor& local_sensor,\n            int count = ToDimension<Count>::Value)\n        : local_sensor_(local_sensor),\n          count_(count)\n    {\n        assert(count_ > 0);\n    }\n\n    template <typename Model>\n    JointSensor(const MultipleOf<Model, Count>& mof)\n        : local_sensor_(mof.instance),\n          count_(mof.count)\n    {\n        assert(count_ > 0);\n    }\n\n    /**\n     * \\brief Overridable default destructor\n     */\n    virtual ~JointSensor() noexcept { }\n\n    Obsrv observation(const State& state, const Noise& noise) const override\n    {\n        Obsrv y = Obsrv::Zero(obsrv_dimension(), 1);\n\n        const int obsrv_dim = local_sensor_.obsrv_dimension();\n        const int noise_dim = local_sensor_.noise_dimension();\n\n        for (int i = 0; i < count_; ++i)\n        {\n            local_sensor_.id(i);\n\n            y.middleRows(i * obsrv_dim, obsrv_dim) =\n                local_sensor_.observation(\n                    state,\n                    noise.middleRows(i * noise_dim, noise_dim));\n        }\n\n        return y;\n    }\n\n    int obsrv_dimension() const override\n    {\n        return local_sensor_.obsrv_dimension() * count_;\n    }\n\n    int noise_dimension() const override\n    {\n        return local_sensor_.noise_dimension() * count_;\n    }\n\n    int state_dimension() const override\n    {\n        return local_sensor_.state_dimension();\n    }\n\n    LocalSensor& local_sensor()\n    {\n        return local_sensor_;\n    }\n\n    const LocalSensor& local_sensor() const\n    {\n        return local_sensor_;\n    }\n\n    virtual std::string name() const\n    {\n        return \"JointSensor<MultipleOf<\"\n                    + this->list_arguments(local_sensor_.name()) +\n               \", Count>>\";\n    }\n\n    virtual std::string description() const\n    {\n        return \"Joint observation model of multiple local observation models \"\n                \" with non-additive noise.\";\n    }\n\n    /**\n     *\n     * \\brief Returns the number of local models within this joint model\n     */\n    virtual int count_local_models() const\n    {\n        return count_;\n    }\n\nprotected:\n    mutable LocalSensor local_sensor_;\n    int count_;\n};\n\n///**\n// * Traits of JointSensor<MultipleOf<Sensor, Count>>\n// */\n//template <\n//    typename Sensor,\n//    int Count\n//>\n//struct Traits<\n//           JointSensor<MultipleOf<Sensor, Count>>\n//        >\n//    : public Traits<\n//                JointSensor<\n//                    MultipleOf<\n//                        typename ForwardAdaptive<Sensor>::Type, Count\n//                    >,\n//                    Adaptive<>>>\n//{ };\n\n///**\n// * \\internal\n// * \\ingroup sensors\n// *\n// * Forwards an adaptive LocalSensor type to the JointSensor\n// * implementation. \\sa ForwardAdaptive for more details.\n// */\n//template <\n//    typename Sensor,\n//    int Count\n//>\n//class JointSensor<MultipleOf<Sensor, Count>>\n//    : public JointSensor<\n//                MultipleOf<typename ForwardAdaptive<Sensor>::Type, Count>,\n//                Adaptive<>>\n//{\n//public:\n//    typedef JointSensor<\n//                MultipleOf<typename ForwardAdaptive<Sensor>::Type, Count>,\n//                Adaptive<>\n//            > Base;\n\n//    typedef typename ForwardAdaptive<Sensor>::Type ForwardedType;\n\n//    JointSensor(\n//            const Sensor& local_sensor,\n//            int count = ToDimension<Count>::Value)\n//        : Base(ForwardedType(local_sensor), count)\n//    { }\n\n//    JointSensor(const MultipleOf<Sensor, Count>& mof)\n//        : Base(mof)\n//    { }\n//};\n\n\n}\n\n\n", "meta": {"hexsha": "3c850f8e2373f78f759e4070cac2bb8eaba657e6", "size": 7202, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/model/sensor/joint_sensor_iid.hpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "include/fl/model/sensor/joint_sensor_iid.hpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "include/fl/model/sensor/joint_sensor_iid.hpp", "max_forks_repo_name": "aeolusbot-tommyliu/fl", "max_forks_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T20:55:13.000Z", "avg_line_length": 26.4779411765, "max_line_length": 80, "alphanum_fraction": 0.6349625104, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4403726687803086}}
{"text": "﻿#include <cstdio>\n#include <memory>\n#include <iostream>\n#include <vector>\nusing namespace std;\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\nusing namespace boost::accumulators;\n\n// 2 + (3+4)\nstruct Expression\n{\n  virtual double eval() = 0;\n  virtual void collect(vector<double>& v) = 0;\n};\n\nstruct Literal : Expression\n{\n  double value;\n\n  explicit Literal(const double value)\n    : value{value}\n  {\n  }\n\n  double eval() override\n  {\n    return value;\n  }\n\n  void collect(vector<double>& v) override\n  {\n    v.push_back(value);\n  }\n};\n\nstruct AdditionExpression : Expression\n{\n  shared_ptr<Expression> left, right;\n\n  AdditionExpression(const shared_ptr<Expression>& expression, const shared_ptr<Expression>& expression1)\n    : left{expression},\n      right{expression1}\n  {\n  }\n\n  double eval() override\n  {\n    return left->eval() + right->eval();\n  }\n\n  void collect(vector<double>& v) override\n  {\n    left->collect(v);\n    right->collect(v);\n  }\n};\n\nint main__3(int ac, char* av)\n{\n  AdditionExpression sum{\n    make_shared<Literal>(2),\n    make_shared<AdditionExpression>(\n      make_shared<Literal>(3),\n      make_shared<Literal>(4)\n      )\n  };\n  cout << \"2+(3+4) = \" << sum.eval() << endl;\n\n  vector<double> v;\n  sum.collect(v);\n  for (auto x : v)\n    cout << x << \"\\t\";\n  cout << endl;\n\n  vector<double> values{ 1,2,3,4 };\n  double s = 0;\n  for (auto x : values) s += x;\n  cout << \"average is \" << (s / values.size()) << endl;\n\n  accumulator_set<double, stats<tag::mean>> acc;\n  for (auto x : values) acc(x);\n  cout << \"average is \" << mean(acc) << endl;\n\n  getchar();\n  return 0;\n}\n", "meta": {"hexsha": "dec0b3f2b5b847620042d0de800351bb419d1b1d", "size": 1641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DesignPattern/cpp/Structural/Composite/composite.cpp", "max_stars_repo_name": "lacie-life/ProgrammingLanguageCollection", "max_stars_repo_head_hexsha": "bc8487b494e8af42838e30e1ca3e40f2112477cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DesignPattern/cpp/Structural/Composite/composite.cpp", "max_issues_repo_name": "lacie-life/ProgrammingLanguageCollection", "max_issues_repo_head_hexsha": "bc8487b494e8af42838e30e1ca3e40f2112477cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DesignPattern/cpp/Structural/Composite/composite.cpp", "max_forks_repo_name": "lacie-life/ProgrammingLanguageCollection", "max_forks_repo_head_hexsha": "bc8487b494e8af42838e30e1ca3e40f2112477cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6477272727, "max_line_length": 105, "alphanum_fraction": 0.6319317489, "num_tokens": 446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.4403726687803086}}
{"text": "/// MIT License\n/// \n/// Copyright (c) 2017 Bjoern Barz\n/// \n/// Permission is hereby granted, free of charge, to any person obtaining a copy\n/// of this software and associated documentation files (the \"Software\"), to deal\n/// in the Software without restriction, including without limitation the rights\n/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n/// copies of the Software, and to permit persons to whom the Software is\n/// furnished to do so, subject to the following conditions:\n/// \n/// The above copyright notice and this permission notice shall be included in all\n/// copies or substantial portions of the Software.\n/// \n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n/// SOFTWARE.\n\n#include <math.h>\n#include <limits>\n#include <iostream>\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <Eigen/Jacobi>     // required for LLT::rankUpdate()\n\n\n#define ITML_ERR_A0 -1\n#define ITML_ERR_NO_CONSTRAINTS -2\n#define ITML_ERR_INVALID_CONSTRAINTS -3\n#define ITML_ERR_CHOL -4\n\n\n/**\n* Stores the indices of two similar or dissimilar samples.\n*/\ntypedef struct {\n    int i; /**< Index of first sample. */\n    int j; /**< Index of second sample. */\n} itml_pair;\n\n\n/**\n* Learns a Mahalanobis distance metric `(x-y)^T * A * (x-y)` from given data and constraints using\n* Information Theoretic Metric Learning (ITML).\n*\n* ITML minimizes the differential relative entropy between two multivariate Gaussians under constraints\n* on the distance function, which can be formulated into a Bregman optimization problem by minimizing the\n* LogDet divergence subject to linear constraints.\n* Unlike some other methods, ITML does not rely on an eigenvalue computation or semi-definite programming.\n*\n* The constraints enforced by ITML have the following form:\n* \n* - `(x-y)^T * A * (x-y) < th_pos` for two similar samples `x` and `y`\n* - `(x-y)^T * A * (x-y) > th_neg` for two dissimilar samples `x` and `y`\n* \n* In theory, individual thresholds could be specified for all pairs, but this implementation only supports\n* constant `th_pos` and `th_neg` at the moment.\n*\n* Reference:  \n* Jason V. Davis, Brian Kulis, Prateek Jain, Suvrit Sra, Inderjit S. Dhillon.  \n* \"Information-Theoretic Metric Learning.\"\n* International Conference on Machine Learning (ITML), 2007.\n* \n* @param[in] n The number of samples.\n* \n* @param[in] d The number of dimensions of the data.\n* \n* @param[in] pX Pointer to an n-by-d matrix `X` containing one sample per row, stored in row-major order.\n* \n* @param[in,out] pA Pointer to a row-major d-by-d matrix `A` which initially contains the prior metric serving\n* as a regularizer (usually the identity matrix or inverse covariance). The algorithm will update this matrix\n* in-place, so that it will finally contain the learned metric or its Cholesky decomposition, depending on the\n* value of `return_metric`.\n* \n* @param[in] nb_pos Number of similarity constraints.\n* \n* @param[in] pos Pointer to an array of `nb_pos` similarity constraints, given as pairs of indices of similar\n* samples in `X`.\n* \n* @param[in] nb_neg Number of dissimilarity constraints.\n* \n* @param[in] neg Pointer to an array of `nb_neg` dissimilarity constraints, given as pairs of indices of\n* dissimilar samples in `X`.\n* \n* @param[in] th_pos Threshold for distances of similar samples. ITML enforces the given pairs of similar samples\n* to have a distance less than this threshold.\n* \n* @param[in] th_neg Threshold for distances of dissimilar samples. ITML enforces the given pairs of dissimilar\n* samples to have a distance greater than this threshold.\n* \n* @param[in] return_metric The algorithm actually learns the Cholesky decomposition `U` of the metric `A` with\n* `A = U^T * U`, which can be used to transform the data into a space where the Euclidean distance corresponds to\n* the learned metric. This matrix `U` will be stored in the matrix pointed to by `pA`. If, however, the actual\n* metric `A` is desired, this parameter can be set to `true` to obtain `A` in the matrix pointed to by `pA`.\n* \n* @param[in] gamma Controls the trade-off between satisyfing the given constraints and minimizing the divergence\n* from the prior metric.\n* Higher `gamma` puts more weight on the constraints, while lower `gamma` enforces stronger regularization.\n* \n* @param[in] max_iter Maximum number of iterations.\n* \n* @param[in] conv_th Convergence threshold.\n* \n* @param[in] verbose If set to `true`, information about convergence will be written to `stderr` during learning.\n* \n* @return On success, returns the number of iterations needed until convergence.\n* If this is equal to `max_iter`, the algorithm terminated prematurely without reaching convergence.\n* In the case of error, one of the following error codes is returned:\n*   - `ITML_ERR_A0` (not used anymore): The given prior metric is not positive-semidefinite.\n*   - `ITML_ERR_NO_CONSTRAINTS`: No non-trivial constraints have been given.\n*   - `ITML_ERR_INVALID_CONSTRAINTS`: Some of the given indices of similar or dissimilar pairs are out of bounds.\n*   - `ITML_ERR_CHOL`: Cholesky decomposition of learned metric failed.\n*/\ntemplate<typename F>\nint itml(int n, int d, const F * pX, F * pA,\n         int nb_pos, const itml_pair * pos, int nb_neg, const itml_pair * neg, F th_pos, F th_neg,\n         bool return_metric = false, F gamma = 1.0, int max_iter = 1000, F conv_th = 0.001, bool verbose = false)\n{\n    // General local variables\n    int i;\n    int num_pos, num_neg, num_constraints; // effective number of positive/negative constraints\n    const itml_pair * pair;\n    const F eps = std::numeric_limits<F>::epsilon();\n    \n    // Wrapper around array pointers\n    typedef Eigen::Matrix<F, Eigen::Dynamic, 1> Vector;\n    typedef Eigen::Matrix<F, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Matrix;\n    Eigen::Map<const Matrix> X(pX, n, d);\n    Eigen::Map<Matrix> A(pA, d, d);\n    Eigen::SelfAdjointView<Eigen::Map<Matrix>, Eigen::Upper> As = A.template selfadjointView<Eigen::Upper>();\n    \n    // Slice rows from X according to constraints\n    Matrix vv(nb_pos + nb_neg, d);\n    num_pos = num_neg = num_constraints = 0;\n    for (i = 0, pair = pos; i < nb_pos; ++i, ++pair)\n    {\n        if (pair->i < 0 || pair->i >= n || pair->j < 0 || pair->j >= n)\n            return ITML_ERR_INVALID_CONSTRAINTS;\n        vv.row(num_constraints) = X.row(pair->i) - X.row(pair->j);\n        if (vv.row(num_constraints).squaredNorm() > eps)\n        {\n            ++num_pos;\n            ++num_constraints;\n        }\n    }\n    for (i = 0, pair = neg; i < nb_neg; ++i, ++pair)\n    {\n        if (pair->i < 0 || pair->i >= n || pair->j < 0 || pair->j >= n)\n            return ITML_ERR_INVALID_CONSTRAINTS;\n        vv.row(num_constraints) = X.row(pair->i) - X.row(pair->j);\n        if (vv.row(num_constraints).squaredNorm() > eps)\n        {\n            ++num_neg;\n            ++num_constraints;\n        }\n    }\n    if (num_constraints == 0)\n        return ITML_ERR_NO_CONSTRAINTS;\n    \n    // Initialize ITML-specific variables\n    int sign;\n    F dist, alpha, beta, normsum, conv;\n    F gamma_proj = std::isinf(gamma) ? 1 : gamma/(gamma+1);\n    Vector Av(d);\n    Vector lambda = Vector::Zero(num_constraints);\n    Vector lambda_old = Vector::Zero(num_constraints);\n    Vector bhat(num_constraints);\n    bhat.head(num_pos).setConstant(th_pos);\n    bhat.tail(num_neg).setConstant(th_neg);\n    \n    // Iterative optimization algorithm\n    int it;\n    for (it = 0; it < max_iter; ++it)\n    {\n        // Perform update for all constraints\n        for (i = 0; i < num_constraints; ++i)\n        {\n            sign = (i < num_pos) ? 1 : -1;\n            Av.noalias() = As * vv.row(i).transpose();\n            dist = vv.row(i).dot(Av);\n            alpha = std::min(lambda(i), sign * gamma_proj * (1/dist - 1/bhat(i)));\n            lambda(i) -= alpha;\n            beta = sign * alpha / (1 - sign * alpha * dist);\n            bhat(i) = 1 / ((1 / bhat(i)) + sign * (alpha / gamma));\n            As.rankUpdate(Av, beta);\n        }\n        \n        // Check for convergence\n        normsum = lambda.norm() + lambda_old.norm();\n        if (normsum < eps)\n        {\n            conv = std::numeric_limits<F>::infinity();\n            break;\n        }\n        conv = (lambda_old - lambda).cwiseAbs().sum();\n        conv /= normsum;\n        if (conv < conv_th)\n            break;\n        lambda_old = lambda;\n        if (verbose)\n            std::cerr << \"itml iter: \" << it << \", conv = \" << conv << std::endl;\n    }\n    \n    if (verbose)\n    {\n        if (it < max_iter)\n            std::cerr << \"itml converged at iter: \" << it << \", conv = \" << conv << std::endl;\n        else\n            std::cerr << \"itml did not converge after \" << it << \" iterations, conv = \" << conv << std::endl;\n    }\n    \n    // Store computed metric or its Cholesky decomposition in pA\n    A = As;\n    if (!return_metric)\n    {\n        Eigen::LLT<Matrix, Eigen::Upper> llt(A);\n        if (llt.info() != Eigen::Success)\n            return ITML_ERR_CHOL;\n        A = llt.matrixU().toDenseMatrix();\n    }\n    \n    return it;\n}\n\n\nextern \"C\"\n{\n\nint itml_float(int n, int d, float * pX, float * pA,\n               int nb_pos, const itml_pair * pos, int nb_neg, const itml_pair * neg, float th_pos, float th_neg,\n               bool return_metric = false, float gamma = 1.0, int max_iter = 1000, float conv_th = 0.001, bool verbose = false)\n{\n    return itml(n, d, pX, pA, nb_pos, pos, nb_neg, neg, th_pos, th_neg, return_metric, gamma, max_iter, conv_th, verbose);\n}\n\nint itml_double(int n, int d, double * pX, double * pA,\n                int nb_pos, const itml_pair * pos, int nb_neg, const itml_pair * neg, double th_pos, double th_neg,\n                bool return_metric = false, double gamma = 1.0, int max_iter = 1000, double conv_th = 0.001, bool verbose = false)\n{\n    return itml(n, d, pX, pA, nb_pos, pos, nb_neg, neg, th_pos, th_neg, return_metric, gamma, max_iter, conv_th, verbose);\n}\n\n}", "meta": {"hexsha": "bb3ab013b0ed90dcd2b76ae5d8aab569447a2fbe", "size": 10358, "ext": "cc", "lang": "C++", "max_stars_repo_path": "libitml.cc", "max_stars_repo_name": "Callidior/libitml", "max_stars_repo_head_hexsha": "3de1cb47599855a8473907cc2c129880502a94ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-03T12:14:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T12:14:49.000Z", "max_issues_repo_path": "libitml.cc", "max_issues_repo_name": "Callidior/libitml", "max_issues_repo_head_hexsha": "3de1cb47599855a8473907cc2c129880502a94ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libitml.cc", "max_forks_repo_name": "Callidior/libitml", "max_forks_repo_head_hexsha": "3de1cb47599855a8473907cc2c129880502a94ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9352226721, "max_line_length": 130, "alphanum_fraction": 0.6605522302, "num_tokens": 2713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4403064818895477}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \r\n// unit/quantity manipulation and conversion\r\n//\r\n// Copyright (C) 2003-2008 Matthias Christian Schabel\r\n// Copyright (C) 2008 Steven Watanabe\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n/**\r\n\\file tutorial.cpp\r\n    \r\n\\brief Basic tutorial using SI units.\r\n\r\n\\details\r\nTutorial \r\nDefines a function that computes the work, in joules,\r\ndone by exerting a force in newtons over a specified distance \r\nin meters and outputs the result to std::cout. \r\n\r\nAlso code for computing the complex impedance\r\nusing std::complex<double> as the value type.\r\n\r\nOutput:\r\n@verbatim\r\n//[tutorial_output\r\nF  = 2 N\r\ndx = 2 m\r\nE  = 4 J\r\n\r\nV   = (12.5,0) V\r\nI   = (3,4) A\r\nZ   = (1.5,-2) Ohm\r\nI*Z = (12.5,0) V\r\nI*Z == V? true\r\n//]\r\n@endverbatim\r\n*/\r\n\r\n//[tutorial_code\r\n#include <complex>\r\n#include <iostream>\r\n\r\n#include <boost/typeof/std/complex.hpp>\r\n\r\n#include <boost/units/systems/si/energy.hpp>\r\n#include <boost/units/systems/si/force.hpp>\r\n#include <boost/units/systems/si/length.hpp>\r\n#include <boost/units/systems/si/electric_potential.hpp>\r\n#include <boost/units/systems/si/current.hpp>\r\n#include <boost/units/systems/si/resistance.hpp>\r\n#include <boost/units/systems/si/io.hpp>\r\n\r\nusing namespace boost::units;\r\nusing namespace boost::units::si;\r\n\r\nquantity<energy> \r\nwork(const quantity<force>& F, const quantity<length>& dx)\r\n{\r\n    return F * dx; // Defines the relation: work = force * distance.\r\n}\r\n\r\nint main()\r\n{   \r\n    /// Test calculation of work.\r\n    quantity<force>     F(2.0 * newton); // Define a quantity of force.\r\n    quantity<length>    dx(2.0 * meter); // and a distance,\r\n    quantity<energy>    E(work(F,dx));  // and calculate the work done.\r\n    \r\n    std::cout << \"F  = \" << F << std::endl\r\n              << \"dx = \" << dx << std::endl\r\n              << \"E  = \" << E << std::endl\r\n              << std::endl;\r\n\r\n    /// Test and check complex quantities.\r\n    typedef std::complex<double> complex_type; // double real and imaginary parts.\r\n    \r\n    // Define some complex electrical quantities.\r\n    quantity<electric_potential, complex_type> v = complex_type(12.5, 0.0) * volts;\r\n    quantity<current, complex_type>            i = complex_type(3.0, 4.0) * amperes;\r\n    quantity<resistance, complex_type>         z = complex_type(1.5, -2.0) * ohms;\r\n    \r\n    std::cout << \"V   = \" << v << std::endl\r\n              << \"I   = \" << i << std::endl\r\n              << \"Z   = \" << z << std::endl \r\n              // Calculate from Ohm's law voltage = current * resistance.\r\n              << \"I * Z = \" << i * z << std::endl\r\n              // Check defined V is equal to calculated.\r\n              << \"I * Z == V? \" << std::boolalpha << (i * z == v) << std::endl\r\n              << std::endl;\r\n    return 0;\r\n}\r\n//]\r\n", "meta": {"hexsha": "33e52e61a77e4e7e09fa945b9c7fc6592eb864e7", "size": 2921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/units/example/tutorial.cpp", "max_stars_repo_name": "lijgame/boost", "max_stars_repo_head_hexsha": "ec2214a19cdddd1048058321a8105dd0231dac47", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/units/example/tutorial.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/units/example/tutorial.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 30.7473684211, "max_line_length": 85, "alphanum_fraction": 0.6004792879, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.651354857898194, "lm_q1q2_score": 0.4401625641759447}}
{"text": "#include <iostream>\n#include <unistd>\n\n#include <boost/numeric/mtl/mtl.hpp>\n#include <boost/timer.hpp>\n\n/*\n  First run: 87ns + 74ns dynamic types \n             67ns + 42ns static types (r6809) (CET needs 52ns if run alone???)\n             71ns + 46ns static types with unrolled by hand (r6810)\n*/\n\n#define STATIC_TYPES\n\n#ifdef STATIC_TYPES\n   typedef mtl::dense_vector<double, mtl::parameters<mtl::tag::col_major, mtl::fixed::dimension<3>, true> > vec;\n#else\n   typedef mtl::dense_vector<double> vec;\n#endif\n\n\n\nusing namespace std;\n\nint main()\n{\n    \n    vec u(3), v(3), w(3), x(3);\n\n    u= 3., 4, 6; v= 7, 9, 3; w= 7, 2, 4;\n\n    const int rep= 10000000;\n    boost::timer time;\n    for(int i= 0; i < rep; i++) {\n\tx= dot(v, u) * w + 4.0 * v + 2 * w;\n    }\n    std::cout << \"Compute time (CET) = \" << 1000000000.*time.elapsed() / rep << \"ns\" << std::endl;\n\n    time.restart();\n    for(int i= 0; i < rep; i++) {\n\tx= dot(v, u) * (w+= 4.0 * v + 2 * w);\n    }\n    std::cout << \"Compute time (RET) = \" << 1000000000.*time.elapsed() / rep << \"ns\" << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "1b61eba2e0c69afe8b8903c07615b5fc34e5287a", "size": 1070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/timing/vector_expr_timing.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/timing/vector_expr_timing.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/timing/vector_expr_timing.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 22.7659574468, "max_line_length": 112, "alphanum_fraction": 0.5644859813, "num_tokens": 385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4401625602428718}}
{"text": "#include \"eigentypes.h\"\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/external/eigen/eigen_algebra.hpp>\n\n#ifndef RUNDOWN\n#define RUNDOWN\n\ntemplate < typename Stepper, typename Model, typename Observer >\nstruct rundown{\n  rundown(Model & state, double start, double end, double error = 1e-10 , double firststep = 0.01){\n    using namespace boost::numeric::odeint;\n\n    // define stepper with error control works only with C++11 standard!\n    auto cstepper = make_controlled( error , error , Stepper() );\n\n  // check whether input scale is lower then output scale:\n  if (end>start)\n    integrate_adaptive(cstepper, Model(), state, start, end, abs(firststep), Observer());\n\n  else{ // start integration across thresholds\n\n  // get thresholds from state type\n  Eigen::VectorXd scales= state.logthresholds();\n\n  double here = start; // helping variable\n\n  // integrate to next threshold\n  for (int i=scales.size()-1; i>=0; i--){\n    if (scales[i] > end){\n      integrate_adaptive(cstepper, Model(), state, here, scales[i], -abs(firststep), Observer());\n      state.integrate_out(i);\n      here = scales[i];\n    }\n    else integrate_adaptive(cstepper, Model(), state, here, end, -abs(firststep), Observer());\n  }\n  \n  // integrate to end\n  if (scales[0] > end)\n    integrate_adaptive(cstepper, Model(), state, scales[0], end, -abs(firststep), Observer());\n  } // else\n  } // contructor\n};\n\n\n// specialisation without observer\ntemplate < typename Stepper, typename Model >\nstruct rundown <Stepper, Model, void>{\n  rundown(Model & state, double start, double end, double error = 1e-10 , double firststep = 0.01){\n      // define stepper with error control works only with C++11 standard!\n    auto cstepper = make_controlled( error , error , Stepper() );\n  using namespace boost::numeric::odeint;\n\n  // check whether input scale is lower then output scale:\n  if (end>start)\n    integrate_adaptive(cstepper, Model(), state, start, end, abs(firststep));\n\n  else{ // start integration across thresholds\n\n  // get thresholds from state type\n    Eigen::VectorXd scales= state.logthresholds();\n\n  double here = start; // helping vairable\n\n  // integrate to next threshold\n  for (int i=scales.size()-1; i>=0; i--){\n    if (scales[i] > end){\n      integrate_adaptive(cstepper, Model(), state, here, scales[i], -abs(firststep));\n      state.integrate_out(i);\n      here = scales[i];\n    }\n    else integrate_adaptive(cstepper, Model(), state, here, end, -abs(firststep));\n  }\n  \n  // integrate to end\n  if (scales[0] > end)\n    integrate_adaptive(cstepper, Model(), state, scales[0], end, -abs(firststep));\n  } // else\n  } // contructor\n};\n\n\n#endif\n", "meta": {"hexsha": "495f626cbe39e22a33eb8cc4ab7e1ce01583cbe7", "size": 2652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/rundown.cpp", "max_stars_repo_name": "Herren/RGEpp", "max_stars_repo_head_hexsha": "65b23c877b94be71fb5ba8eb0b061c4fcbc844ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-20T11:39:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T04:39:54.000Z", "max_issues_repo_path": "examples/rundown.cpp", "max_issues_repo_name": "Herren/RGEpp", "max_issues_repo_head_hexsha": "65b23c877b94be71fb5ba8eb0b061c4fcbc844ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/rundown.cpp", "max_forks_repo_name": "Herren/RGEpp", "max_forks_repo_head_hexsha": "65b23c877b94be71fb5ba8eb0b061c4fcbc844ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-20T11:40:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-01T00:11:54.000Z", "avg_line_length": 31.9518072289, "max_line_length": 99, "alphanum_fraction": 0.6802413273, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.44004861881531915}}
{"text": "// File: element_matrix.cpp\n\n#include <iostream>\n#include <vector>\n#include <boost/numeric/mtl/mtl.hpp>\n\nusing namespace mtl;\n\ntemplate <typename Matrix>\nvoid fill(Matrix& m)\n{\n    // Matrices are not initialized by default\n    m= 0.0;\n\n    // Type of m's elements\n    typedef typename Collection<Matrix>::value_type value_type;\n\n    // Create inserter for matrix m\n    // Existing values are not overwritten but inserted\n    mat::inserter<Matrix, update_plus<value_type> > ins(m, 3);\n    \n    // Define element matrix (array)\n    double m1[2][2]= {{1.0, -.4}, {-0.5, 2.0}}; \n\n    // Corresponding indices of the elements\n    std::vector<int> v1(2);\n    v1[0]= 1; v1[1]= 3;\n\n    // Insert element matrix\n    ins << element_array(m1, v1);\n\n    // Insert same array with different indices\n    v1[0]= 0; v1[1]= 2;\n    ins << element_array(m1, v1);\n\n    // Use element matrix type with dynamic size\n    dense2D<double> m2(2, 3);\n    m2[0][0]= 1; m2[0][1]= 0.2; m2[0][2]= 0.1; \n    m2[1][0]= 2; m2[1][1]= 1.2; m2[1][2]= 1.1;\n\n    // Vector for column indices \n    dense_vector<int> v2(3);\n    // Indices can be out of order\n    v2[0]= 4; v2[1]= 1; v2[2]= 3;\n\n    // Use element_matrix and separate vectors for row and column indices\n    ins << element_matrix(m2, v1, v2);\n}\n\nint main(int, char**)\n{\n    // Matrices of different types\n    compressed2D<double>              A(5, 5);\n    dense2D<double>                   B(5, 5);\n    morton_dense<float, morton_mask>  C(5, 5);\n\n    // Fill the matrices generically\n    fill(A); fill(B); fill(C);\n    std::cout << \"A is \\n\" << with_format(A, 4, 3) \n\t      << \"\\nB is \\n\" << with_format(B, 4, 3)\n\t      << \"\\nC is \\n\" << with_format(C, 4, 3);\n\n    return 0;\n}\n\n", "meta": {"hexsha": "a00148326e0d0f59a2630917b2f97a32b66d8f6f", "size": 1702, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/element_matrix.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/element_matrix.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/element_matrix.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 25.7878787879, "max_line_length": 73, "alphanum_fraction": 0.5875440658, "num_tokens": 576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.44004861135119194}}
{"text": "\n#include <NTL/xdouble.h>\n#include <NTL/RR.h>\n\n\n\nNTL_START_IMPL\n\n\n\nNTL_CHEAP_THREAD_LOCAL\nlong xdouble::oprec = 10;\n\nvoid xdouble::SetOutputPrecision(long p)\n{\n   if (p < 1) p = 1;\n\n   if (NTL_OVERFLOW(p, 1, 0)) \n      ResourceError(\"xdouble: output precision too big\");\n\n   oprec = p;\n}\n\nvoid xdouble::normalize() \n{\n   if (x == 0) \n      e = 0;\n   else if (x > 0) {\n      while (x < NTL_XD_HBOUND_INV) { x *= NTL_XD_BOUND; e--; }\n      while (x > NTL_XD_HBOUND) { x *= NTL_XD_BOUND_INV; e++; }\n   }\n   else {\n      while (x > -NTL_XD_HBOUND_INV) { x *= NTL_XD_BOUND; e--; }\n      while (x < -NTL_XD_HBOUND) { x *= NTL_XD_BOUND_INV; e++; }\n   }\n\n   if (e >= NTL_OVFBND)\n      ResourceError(\"xdouble: overflow\");\n\n   if (e <= -NTL_OVFBND)\n      ResourceError(\"xdouble: underflow\");\n}\n   \n\n\nxdouble to_xdouble(double a)\n{\n   if (a == 0 || a == 1 || (a > 0 && a >= NTL_XD_HBOUND_INV && a <= NTL_XD_HBOUND)\n       || (a < 0 && a <= -NTL_XD_HBOUND_INV && a >= -NTL_XD_HBOUND)) {\n      \n      return xdouble(a, 0); \n\n   }\n\n   if (!IsFinite(&a))\n      ArithmeticError(\"double to xdouble conversion: non finite value\");\n\n   xdouble z = xdouble(a, 0);\n   z.normalize();\n   return z;\n}\n\n\nvoid conv(double& xx, const xdouble& a)\n{\n   double x;\n   long e;\n\n   x = a.x;\n   e = a.e;\n\n   while (e > 0) { x *= NTL_XD_BOUND; e--; }\n   while (e < 0) { x *= NTL_XD_BOUND_INV; e++; }\n\n   xx = x;\n}\n\n\n\n\nxdouble operator+(const xdouble& a, const xdouble& b)\n{\n   xdouble z;\n\n   if (a.x == 0) \n      return b;\n\n   if (b.x == 0)\n     return a;\n      \n\n   if (a.e == b.e) {\n      z.x = a.x + b.x;\n      z.e = a.e;\n      z.normalize();\n      return z;\n   }\n   else if (a.e > b.e) {\n      if (a.e > b.e+1)\n         return a;\n\n      z.x = a.x + b.x*NTL_XD_BOUND_INV;\n      z.e = a.e;\n      z.normalize();\n      return z;\n   }\n   else {\n      if (b.e > a.e+1)\n         return b;\n\n      z.x = a.x*NTL_XD_BOUND_INV + b.x;\n      z.e = b.e;\n      z.normalize();\n      return z;\n   }\n}\n\n\nxdouble operator-(const xdouble& a, const xdouble& b)\n{\n   xdouble z;\n\n   if (a.x == 0)\n      return -b;\n\n   if (b.x == 0)\n      return a;\n\n   if (a.e == b.e) {\n      z.x = a.x - b.x;\n      z.e = a.e;\n      z.normalize();\n      return z;\n   }\n   else if (a.e > b.e) {\n      if (a.e > b.e+1)\n         return a;\n\n      z.x = a.x - b.x*NTL_XD_BOUND_INV;\n      z.e = a.e;\n      z.normalize();\n      return z;\n   }\n   else {\n      if (b.e > a.e+1)\n         return -b;\n\n      z.x = a.x*NTL_XD_BOUND_INV - b.x;\n      z.e = b.e;\n      z.normalize();\n      return z;\n   }\n}\n\nxdouble operator-(const xdouble& a)\n{\n   xdouble z;\n   z.x = -a.x;\n   z.e = a.e;\n   return z;\n}\n\nxdouble operator*(const xdouble& a, const xdouble& b)\n{\n   xdouble z;\n\n   z.e = a.e + b.e;\n   z.x = a.x * b.x;\n   z.normalize();\n   return z;\n}\n\nxdouble operator/(const xdouble& a, const xdouble& b)\n{\n   xdouble z;\n\n   if (b.x == 0) ArithmeticError(\"xdouble division by 0\");\n\n   z.e = a.e - b.e;\n   z.x = a.x / b.x;\n   z.normalize();\n   return z;\n}\n\n\n\nlong compare(const xdouble& a, const xdouble& b)\n{\n   xdouble z = a - b;\n\n   if (z.x < 0)\n      return -1;\n   else if (z.x == 0)\n      return 0;\n   else\n      return 1;\n}\n\nlong sign(const xdouble& z)\n{\n   if (z.x < 0)\n      return -1;\n   else if (z.x == 0)\n      return 0;\n   else\n      return 1;\n}\n   \n\n\nxdouble trunc(const xdouble& a)\n{\n   if (a.x >= 0)\n      return floor(a);\n   else\n      return ceil(a);\n}\n\n\nxdouble floor(const xdouble& aa)\n{\n   xdouble z;\n\n   xdouble a = aa;\n   ForceToMem(&a.x);\n\n   if (a.e == 0) {\n      z.x = floor(a.x);\n      z.e = 0;\n      z.normalize();\n      return z;\n   }\n   else if (a.e > 0) {\n      return a;\n   }\n   else {\n      if (a.x < 0)\n         return to_xdouble(-1);\n      else\n         return to_xdouble(0);\n   }\n}\n\nxdouble ceil(const xdouble& aa)\n{\n   xdouble z;\n\n   xdouble a = aa;\n   ForceToMem(&a.x);\n\n   if (a.e == 0) {\n      z.x = ceil(a.x);\n      z.e = 0;\n      z.normalize();\n      return z;\n   }\n   else if (a.e > 0) {\n      return a;\n   }\n   else {\n      if (a.x < 0)\n         return to_xdouble(0);\n      else\n         return to_xdouble(1);\n   }\n}\n\nxdouble to_xdouble(const ZZ& a)\n{\n   RRPush push;\n   RR::SetPrecision(NTL_DOUBLE_PRECISION);\n   \n   NTL_TLS_LOCAL(RR, t);\n   conv(t, a);\n\n   double x;\n   conv(x, t.mantissa());\n\n   xdouble y, z, res;\n\n   conv(y, x);\n   power2(z, t.exponent());\n\n   res = y*z;\n\n   return res;\n}\n\nvoid conv(ZZ& x, const xdouble& a)\n{\n   xdouble b = floor(a);\n\n   RRPush push;\n   RR::SetPrecision(NTL_DOUBLE_PRECISION);\n\n   NTL_TLS_LOCAL(RR, t);\n   conv(t, b);\n   conv(x, t);\n}\n\n\nxdouble fabs(const xdouble& a)\n{\n   xdouble z;\n\n   z.e = a.e;\n   z.x = fabs(a.x);\n   return z;\n}\n\nxdouble sqrt(const xdouble& a)\n{\n   if (a == 0)\n      return to_xdouble(0);\n\n   if (a < 0)\n      ArithmeticError(\"xdouble: sqrt of negative number\");\n\n   xdouble t;\n\n   if (a.e & 1) {\n      t.e = (a.e - 1)/2;\n      t.x = sqrt(a.x * NTL_XD_BOUND);\n   }\n   else {\n      t.e = a.e/2;\n      t.x = sqrt(a.x);\n   }\n\n   t.normalize();\n\n   return t;\n}\n      \n\nvoid power(xdouble& z, const xdouble& a, const ZZ& e)\n{\n   xdouble b, res;\n\n   b = a;\n\n   res = 1;\n   long n = NumBits(e);\n   long i;\n\n   for (i = n-1; i >= 0; i--) {\n      res = res * res;\n      if (bit(e, i))\n         res = res * b;\n   }\n\n   if (sign(e) < 0) \n      z = 1/res;\n   else\n      z = res;\n}\n\n\n\n\nvoid power(xdouble& z, const xdouble& a, long e)\n{\n   NTL_ZZRegister(E);\n   E = e;\n   power(z, a, E);\n}\n   \n\n   \n\n\nvoid power2(xdouble& z, long e)\n{\n   long hb = NTL_XD_HBOUND_LOG;\n   long b = 2*hb;\n\n   long q, r;\n\n   q = e/b;\n   r = e%b;\n\n   while (r >= hb) {\n      r -= b;\n      q++;\n   }\n\n   while (r < -hb) {\n      r += b;\n      q--;\n   }\n\n   if (q >= NTL_OVFBND)\n      ResourceError(\"xdouble: overflow\");\n\n   if (q <= -NTL_OVFBND)\n      ResourceError(\"xdouble: underflow\");\n\n   double x = _ntl_ldexp(1.0, r);\n\n   z.x = x;\n   z.e = q;\n}\n\n\nvoid MulAdd(xdouble& z, const xdouble& a, const xdouble& b, const xdouble& c)\n// z = a + b*c\n{\n   double x;\n   long e;\n\n   e = b.e + c.e;\n   x = b.x * c.x;\n\n   if (x == 0) { \n      z = a;\n      return;\n   }\n\n   if (a.x == 0) {\n      z.e = e;\n      z.x = x;\n      z.normalize();\n      return;\n   }\n      \n\n   if (a.e == e) {\n      z.x = a.x + x;\n      z.e = e;\n      z.normalize();\n      return;\n   }\n   else if (a.e > e) {\n      if (a.e > e+1) {\n         z = a;\n         return;\n      }\n\n      z.x = a.x + x*NTL_XD_BOUND_INV;\n      z.e = a.e;\n      z.normalize();\n      return;\n   }\n   else {\n      if (e > a.e+1) {\n         z.x = x;\n         z.e = e;\n         z.normalize();\n         return;\n      }\n\n      z.x = a.x*NTL_XD_BOUND_INV + x;\n      z.e = e;\n      z.normalize();\n      return;\n   }\n}\n\nvoid MulSub(xdouble& z, const xdouble& a, const xdouble& b, const xdouble& c)\n// z = a - b*c\n{\n   double x;\n   long e;\n\n   e = b.e + c.e;\n   x = b.x * c.x;\n\n   if (x == 0) { \n      z = a;\n      return;\n   }\n\n   if (a.x == 0) {\n      z.e = e;\n      z.x = -x;\n      z.normalize();\n      return;\n   }\n      \n\n   if (a.e == e) {\n      z.x = a.x - x;\n      z.e = e;\n      z.normalize();\n      return;\n   }\n   else if (a.e > e) {\n      if (a.e > e+1) {\n         z = a;\n         return;\n      }\n\n      z.x = a.x - x*NTL_XD_BOUND_INV;\n      z.e = a.e;\n      z.normalize();\n      return;\n   }\n   else {\n      if (e > a.e+1) {\n         z.x = -x;\n         z.e = e;\n         z.normalize();\n         return;\n      }\n\n      z.x = a.x*NTL_XD_BOUND_INV - x;\n      z.e = e;\n      z.normalize();\n      return;\n   }\n}\n\ndouble log(const xdouble& a)\n{\n   static const double LogBound = log(NTL_XD_BOUND); // GLOBAL (assumes C++11 thread-safe init)\n   if (a.x <= 0) {\n      ArithmeticError(\"log(xdouble): argument must be positive\");\n   }\n\n   return log(a.x) + a.e*LogBound;\n}\n\nxdouble xexp(double x)\n{\n   const double LogBound = log(NTL_XD_BOUND);\n\n   double y = x/LogBound;\n   double iy = floor(y+0.5);\n\n   if (iy >= NTL_OVFBND)\n      ResourceError(\"xdouble: overflow\");\n\n   if (iy <= -NTL_OVFBND)\n      ResourceError(\"xdouble: underflow\");\n\n\n   double fy = y - iy;\n\n   xdouble res;\n   res.e = long(iy);\n   res.x = exp(fy*LogBound);\n   res.normalize();\n   return res;\n}\n\n/**************  input / output routines **************/\n\n\nvoid ComputeLn2(RR&);\nvoid ComputeLn10(RR&);\n\nlong ComputeMax10Power()\n{\n   RRPush push;\n   RR::SetPrecision(NTL_BITS_PER_LONG);\n\n   RR ln2, ln10;\n   ComputeLn2(ln2);\n   ComputeLn10(ln10);\n\n   long k = to_long( to_RR(NTL_OVFBND/2) * ln2 / ln10 );\n   return k;\n}\n\n\nxdouble PowerOf10(const ZZ& e)\n{\n   static NTL_CHEAP_THREAD_LOCAL long init = 0;\n   static NTL_CHEAP_THREAD_LOCAL long k = 0;\n\n   NTL_TLS_LOCAL(xdouble, v10k);\n\n   if (!init) {\n      k = ComputeMax10Power();\n      RRPush push;\n      RR::SetPrecision(NTL_DOUBLE_PRECISION);\n      v10k = to_xdouble(power(to_RR(10), k)); \n      init = 1;\n   }\n\n   ZZ e1;\n   long neg;\n\n   if (e < 0) {\n      e1 = -e;\n      neg = 1;\n   }\n   else {\n      e1 = e;\n      neg = 0;\n   }\n\n   long r;\n   ZZ q;\n\n   r = DivRem(q, e1, k);\n\n   RRPush push;\n   RR::SetPrecision(NTL_DOUBLE_PRECISION);\n   xdouble x1 = to_xdouble(power(to_RR(10), r));\n\n   xdouble x2 = power(v10k, q);\n   xdouble x3 = x1*x2;\n\n   if (neg) x3 = 1/x3;\n\n   return x3;\n}\n\n\n\n\nostream& operator<<(ostream& s, const xdouble& a)\n{\n   if (a == 0) {\n      s << \"0\";\n      return s;\n   }\n\n   RRPush push;\n   long temp_p = long(log(fabs(log(fabs(a))) + 1.0)/log(2.0)) + 10; \n   RR::SetPrecision(temp_p);\n\n   RR ln2, ln10, log_2_10;\n   ComputeLn2(ln2);\n   ComputeLn10(ln10);\n   log_2_10 = ln10/ln2;\n   ZZ log_10_a = to_ZZ(\n  (to_RR(a.e)*to_RR(2*NTL_XD_HBOUND_LOG) + log(fabs(a.x))/log(2.0))/log_2_10);\n\n\n   xdouble b;\n   long neg;\n\n   if (a < 0) {\n      b = -a;\n      neg = 1;\n   }\n   else {\n      b = a;\n      neg = 0;\n   }\n\n   ZZ k = xdouble::OutputPrecision() - log_10_a;\n\n   xdouble c, d;\n\n   c = PowerOf10(to_ZZ(xdouble::OutputPrecision()));\n   d = PowerOf10(log_10_a);\n\n   b = b / d;\n   b = b * c;\n\n   while (b < c) {\n      b = b * 10.0;\n      k++;\n   }\n\n   while (b >= c) {\n      b = b / 10.0;\n      k--;\n   }\n\n   b = b + 0.5;\n   k = -k;\n\n   ZZ B;\n   conv(B, b);\n\n   long bp_len = xdouble::OutputPrecision()+10;\n\n   UniqueArray<char> bp_store;\n   bp_store.SetLength(bp_len);\n   char *bp = bp_store.get();\n\n   long len, i;\n\n   len = 0;\n   do {\n      if (len >= bp_len) LogicError(\"xdouble output: buffer overflow\");\n      bp[len] = IntValToChar(DivRem(B, B, 10));\n      len++;\n   } while (B > 0);\n\n   for (i = 0; i < len/2; i++) {\n      char tmp;\n      tmp = bp[i];\n      bp[i] = bp[len-1-i];\n      bp[len-1-i] = tmp;\n   }\n\n   i = len-1;\n   while (bp[i] == '0') i--;\n\n   k += (len-1-i);\n   len = i+1;\n\n   bp[len] = '\\0';\n\n   if (k > 3 || k < -len - 3) {\n      // use scientific notation\n\n      if (neg) s << \"-\";\n      s << \"0.\" << bp << \"e\" << (k + len);\n   }\n   else {\n      long kk = to_long(k);\n\n      if (kk >= 0) {\n         if (neg) s << \"-\";\n         s << bp;\n         for (i = 0; i < kk; i++) \n            s << \"0\";\n      }\n      else if (kk <= -len) {\n         if (neg) s << \"-\";\n         s << \"0.\";\n         for (i = 0; i < -len-kk; i++)\n            s << \"0\";\n         s << bp;\n      }\n      else {\n         if (neg) s << \"-\";\n         for (i = 0; i < len+kk; i++)\n            s << bp[i];\n   \n         s << \".\";\n   \n         for (i = len+kk; i < len; i++)\n            s << bp[i];\n      }\n   }\n\n   return s;\n}\n\nistream& operator>>(istream& s, xdouble& x)\n{\n   long c;\n   long cval;\n   long sign;\n   ZZ a, b;\n\n   if (!s) NTL_INPUT_ERROR(s, \"bad xdouble input\");\n\n   c = s.peek();\n   while (IsWhiteSpace(c)) {\n      s.get();\n      c = s.peek();\n   }\n\n   if (c == '-') {\n      sign = -1;\n      s.get();\n      c = s.peek();\n   }\n   else\n      sign = 1;\n\n   long got1 = 0;\n   long got_dot = 0;\n   long got2 = 0;\n\n   a = 0;\n   b = 1;\n\n   cval = CharToIntVal(c);\n\n   if (cval >= 0 && cval <= 9) {\n      got1 = 1;\n\n      while (cval >= 0 && cval <= 9) {\n         mul(a, a, 10);\n         add(a, a, cval);\n         s.get();\n         c = s.peek();\n         cval = CharToIntVal(c);\n      }\n   }\n\n   if (c == '.') {\n      got_dot = 1;\n\n      s.get();\n      c = s.peek();\n      cval = CharToIntVal(c);\n\n      if (cval >= 0 && cval <= 9) {\n         got2 = 1;\n   \n         while (cval >= 0 && cval <= 9) {\n            mul(a, a, 10);\n            add(a, a, cval);\n            mul(b, b, 10);\n            s.get();\n            c = s.peek();\n            cval = CharToIntVal(c);\n         }\n      }\n   }\n\n   if (got_dot && !got1 && !got2)  NTL_INPUT_ERROR(s, \"bad xdouble input\");\n\n   ZZ e;\n\n   long got_e = 0;\n   long e_sign;\n\n   if (c == 'e' || c == 'E') {\n      got_e = 1;\n\n      s.get();\n      c = s.peek();\n\n      if (c == '-') {\n         e_sign = -1;\n         s.get();\n         c = s.peek();\n      }\n      else if (c == '+') {\n         e_sign = 1;\n         s.get();\n         c = s.peek();\n      }\n      else\n         e_sign = 1;\n\n      cval = CharToIntVal(c);\n\n      if (cval < 0 || cval > 9) NTL_INPUT_ERROR(s, \"bad xdouble input\");\n\n      e = 0;\n      while (cval >= 0 && cval <= 9) {\n         mul(e, e, 10);\n         add(e, e, cval);\n         s.get();\n         c = s.peek();\n         cval = CharToIntVal(c);\n      }\n   }\n\n   if (!got1 && !got2 && !got_e) NTL_INPUT_ERROR(s, \"bad xdouble input\");\n\n   xdouble t1, t2, v;\n\n   if (got1 || got2) {\n      conv(t1, a);\n      conv(t2, b);\n      v = t1/t2;\n   }\n   else\n      v = 1;\n\n   if (sign < 0)\n      v = -v;\n\n   if (got_e) {\n      if (e_sign < 0) negate(e, e);\n      t1 = PowerOf10(e);\n      v = v * t1;\n   }\n\n   x = v;\n   return s;\n}\n\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "335a73524cb1c86378ab68bacbe31a9532258332", "size": 13438, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/xdouble.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 160.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T09:32:19.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/xdouble.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2016-12-26T07:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T16:34:31.000Z", "max_forks_repo_path": "LibSource/ExtendedNTL/src/xdouble.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2016-10-10T17:56:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:56:39.000Z", "avg_line_length": 15.4459770115, "max_line_length": 95, "alphanum_fraction": 0.4554249144, "num_tokens": 4707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4400034248821999}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EXPONENTIAL_FUNCTIONS_SIMD_COMMON_IMPL_LOGS_F_LOG_HPP_INCLUDED\n#define NT2_EXPONENTIAL_FUNCTIONS_SIMD_COMMON_IMPL_LOGS_F_LOG_HPP_INCLUDED\n\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/plus.hpp>\n#include <nt2/include/functions/simd/fma.hpp>\n#include <nt2/include/functions/simd/is_eqz.hpp>\n#include <nt2/include/functions/simd/if_allbits_else.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/if_else_zero.hpp>\n#include <nt2/include/functions/simd/is_ltz.hpp>\n#include <nt2/exponential/functions/scalar/impl/logs/f_kernel.hpp>\n#include <nt2/include/constants/mhalf.hpp>\n#include <nt2/include/constants/minf.hpp>\n#include <nt2/include/constants/log_2hi.hpp>\n#include <nt2/include/constants/log_2lo.hpp>\n#include <nt2/include/constants/log2_em1.hpp>\n#include <nt2/include/constants/log10_ehi.hpp>\n#include <nt2/include/constants/log10_elo.hpp>\n#include <nt2/include/constants/log10_2hi.hpp>\n#include <nt2/include/constants/log10_2lo.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n#include <boost/simd/sdk/config.hpp>\n#include <boost/simd/sdk/meta/as_logical.hpp>\n\n#ifndef BOOST_SIMD_NO_NANS\n#include <nt2/include/functions/simd/is_nan.hpp>\n#include <nt2/include/functions/simd/logical_or.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/functions/simd/is_equal.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_DENORMALS\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/is_less.hpp>\n#include <nt2/include/constants/smallestposval.hpp>\n#include <nt2/include/constants/twotonmb.hpp>\n#include <nt2/include/constants/mlogtwo2nmb.hpp>\n#include <nt2/include/constants/mlog2two2nmb.hpp>\n#include <nt2/include/constants/mlog10two2nmb.hpp>\n#endif\n\n  //////////////////////////////////////////////////////////////////////////////\n  // how to compute the various logarithms\n  //////////////////////////////////////////////////////////////////////////////\n  // The method is mainly taken from the cephes library:\n  // first reduce the the data\n  // a0 is supposed > 0\n  // the input a0 is split into a mantissa and an exponent\n  // the mantissa m is between sqrt(0.5) and sqrt(2) and the correspondint exponent is e\n  // a0 = m*2^e\n  // then the log? calculus is split in two parts (? being nothing: natural logarithm,  2: base 2 logarithm,  10 base ten logarithm)\n  // as log?(a) = log?(2^e)+log?(m)\n  // 1) computing log?(m)\n  //   first put x = m-1 (so -0.29 <  x < 0.414)\n  //   write log(m)   = log(1+x)   = x + x*x/2 + x*x*x*g(x)\n  //   write log2(m)  = log2(1+x)  = C2*log(x)   C2 =  log(2)  the multiplication have to be taken seriously as C2 is not exact\n  //   write log10(m) = log10(1+x) = C10*log(x)  C10=  log(10) the multiplication have to be taken seriously as C10 is not exact\n  // then g(x) has to be approximated\n  // g is ((log(1+x)/x-1)/x-1/2)/x\n  // It is not a good idea to approximate directly log(1+x) instead of g,  because this will lead to bad precision around 1.\n  //\n  // in this approximation one can choose a best approximation rational function given by remez algorithm.\n  // there exist a classical solution which is a polynomial p8 one of degree 8 that gives 0.5ulps everywhere\n  // this is what is done in the kernel_t::log impl;\n  // Now,  it is possible to choose a rational fraction or a polynomial of lesser degree to approximate g\n  // providing faster but less accurate logs.\n  // 2) computing log?(2^e)\n  // see the explanations relative to each case\n  // 3) finalize\n  // This is simply treating invalid entries\n  // 4) For denormal we use the fact that log(x) =  log?(x*y)-log?(y) and that if y is\n  // the constant two2nmb if x is denormal x*y and y are not.\n  //////////////////////////////////////////////////////////////////////////////\n\nnamespace nt2 { namespace details\n{\n  //////////////////////////////////////////////////////////////////////////////\n  // math log functions\n  //////////////////////////////////////////////////////////////////////////////\n\n  template < class A0 >\n  struct logarithm< A0, tag::simd_type, float>\n  {\n    typedef typename meta::as_logical<A0>::type                 lA0;\n    typedef typename meta::as_integer<A0, signed>::type    int_type;\n    typedef typename meta::scalar_of<A0>::type                  sA0;\n    typedef kernel<A0, tag::simd_type, float>              kernel_t;\n\n    static inline A0 log(const A0& a0)\n    {\n      A0 z = a0;\n#ifndef BOOST_SIMD_NO_DENORMALS\n      A0 t = Zero<A0>();\n      lA0 denormal = lt(nt2::abs(z), Smallestposval<A0>());\n      z = if_else(denormal, z*Twotonmb<A0>(), z);\n      t = if_else_zero(denormal, Mlogtwo2nmb<A0>());\n#endif\n      //log(2.0) in double is 6.931471805599453e-01\n      //double(0.693359375f)+double(-0.00021219444f)  is  6.931471805600000e-01 at 1.0e-14 of log(2.0)\n      // let us call Log_2hi 0.693359375f anf Log_2lo -0.00021219444f\n      // We use thi to correct the sum where this could matter a lot\n      // log(a0) = fe*Log_2hi+ (0.5f*x*x +(fe*Log_2lo+y))\n      // These operations are order dependent: the parentheses do matter\n      A0 x, fe, x2, y;\n      kernel_t::log(z, fe, x, x2, y);\n      y = nt2::fma(fe, Log_2lo<A0>(), y);\n      y = nt2::fma(Mhalf<A0>(), x2, y);\n#ifdef BOOST_SIMD_NO_DENORMALS\n      return finalize(a0, nt2::fma(Log_2hi<A0>(), fe, x+y));\n#else\n      return finalize(a0, nt2::fma(Log_2hi<A0>(), fe, x+y+t));\n#endif\n    }\n\n    static inline A0 log2(const A0& a0)\n    {\n      A0 z =  a0;\n#ifndef BOOST_SIMD_NO_DENORMALS\n      lA0 denormal = lt(nt2::abs(z), Smallestposval<A0>());\n      z = if_else(denormal, z*Twotonmb<A0>(), z);\n      A0 t = if_else_zero(denormal, Mlog2two2nmb<A0>());\n#endif\n      //here let l2em1 = log2(e)-1, the computation is done as:\n      //log2(a0) = ((l2em1*x+(l2em1*(y+x*x/2)))+(y+x*x/2)))+x+fe for best results\n      // once again the order is very important.\n      A0 x, fe, x2, y;\n      kernel_t::log(z, fe, x, x2, y);\n      y =  nt2::fma(Mhalf<A0>(),x2, y);\n      z = nt2::fma(x,Log2_em1<A0>(),y*Log2_em1<A0>());\n#ifdef BOOST_SIMD_NO_DENORMALS\n      return finalize(a0, ((z+y)+x)+fe);\n#else\n      return finalize(a0, ((z+y)+x)+fe+t);\n#endif\n    }\n\n    static inline A0 log10(const A0& a0)\n    {\n      A0 z = a0;\n#ifndef BOOST_SIMD_NO_DENORMALS\n      lA0 denormal = lt(nt2::abs(z), Smallestposval<A0>());\n      z = if_else(denormal, z*Twotonmb<A0>(), z);\n      A0 t = if_else_zero(denormal, Mlog10two2nmb<A0>());\n#endif\n      // here there are two multiplication:  log of fraction by log10(e) and base 2 exponent by log10(2)\n      // and we have to split log10(e) and log10(2) in two parts to get extra precision when needed\n      A0 x, fe, x2, y;\n      kernel_t::log(z, fe, x, x2, y);\n      y = nt2::amul(y, Mhalf<A0>(), x2);\n      z = mul(x+y, Log10_elo<A0>());\n      z = nt2::amul(z, y, Log10_ehi<A0>());\n      z = nt2::amul(z, x, Log10_ehi<A0>());\n      z = nt2::amul(z, fe, Log10_2hi<A0>());\n#ifdef BOOST_SIMD_NO_DENORMALS\n      return finalize(a0, nt2::amul(z, fe, Log10_2lo<A0>()));\n#else\n      return finalize(a0, nt2::amul(z+t, fe, Log10_2lo<A0>()));\n#endif\n    }\n  private:\n    static inline A0 finalize(const A0& a0, const A0& y)\n    {\n      typedef typename meta::as_logical<A0>::type              lA0;\n    #ifdef BOOST_SIMD_NO_NANS\n      lA0 test = nt2::is_ltz(a0);\n    #else\n      lA0 test = nt2::logical_or(nt2::is_ltz(a0), nt2::is_nan(a0));\n    #endif\n      A0 y1 = nt2::if_nan_else(test, y);\n    #ifndef BOOST_SIMD_NO_INFINITIES\n      y1 = if_else(nt2::is_equal(a0, nt2::Inf<A0>()), a0, y1);\n    #endif\n      return if_else(is_eqz(a0), nt2::Minf<A0>(), y1);\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "1f2ed80ebff2ab84328b799e6ccaffcfce8ff141", "size": 8237, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/simd/common/impl/logs/f_log.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/exponential/include/nt2/exponential/functions/simd/common/impl/logs/f_log.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/exponential/include/nt2/exponential/functions/simd/common/impl/logs/f_log.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 43.1256544503, "max_line_length": 132, "alphanum_fraction": 0.6214641253, "num_tokens": 2466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4400034248821999}}
{"text": "/* Copyright 2020 Oinam Romesh Meitei\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n */\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/eigen.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <vector>\n#include \"fmath.hpp\"\n#include \"pulsec.h\"\n#include \"agradc.h\"\n#include \"grad_ana.h\"\n#include \"pulsehelper.h\"\n\n#include <iostream>\n#include <iomanip>\n#include <chrono>\n\nnamespace py = pybind11;\n\ngausgrad gaus_getnamp(int nqubit, int &ngaus, double duration,\t\t\t\t\t     \n\t\t\t\t\t\t std::vector< std::vector<double > > &amp,\n\t\t\t\t\t\t std::vector< std::vector<double > > &sigma,\n\t\t\t\t\t\t std::vector< std::vector<double > > &mean,\n\t\t\t\t\t\t std::vector<double > freq,\n\t\t\t\t\t\t std::vector<double> &tlist,\n\t\t\t\t\t\t std::vector<std::complex<double> > &ini_vec,\n\t\t\t\t\t\t std::vector< std::vector< Eigen::SparseMatrix\n\t\t\t\t\t\t\t\t\t   <double,0,ptrdiff_t> > > hdrive,\n\t\t\t\t\t\t std::vector< std::complex<double> > dsham,\n\t\t\t\t\t\t std::vector< int> &states,\n\t\t\t\t\t\t Eigen::MatrixXcd &cham){\n\t\t\t       \n\n  double tmpamp;\n  int tlen = tlist.size();\n  \n  std::vector< std::vector< std::vector<double > > >\n    expterm(nqubit, std::vector<std::vector<double> > (ngaus, std::vector< double> (tlen)));\n  \n  std::vector<std::vector<double > > tseq;\n  int nwindow = 0;\n  double gamp, gsig, gmean, esigmean;\n  std::vector<double > agradient;\n  \n  std::vector<std::vector<double > > tamp(nqubit, std::vector<double> (tlen));\n  int i,j,k;\n  for (i=0; i<nqubit; i++){\n    for (j=0;j<ngaus; j++){\n      for (k=0;k<tlen; k++){\n\texpterm[i][j][k] = fmath::expd(-sigma[i][j] * sigma[i][j] *\n\t\t\t\t       (tlist[k] - mean[i][j]) *\n\t\t\t\t       (tlist[k] - mean[i][j]));\n\ttamp[i][k] += amp[i][j] * expterm[i][j][k];\n      }\n    }\n  }\n\n  pulsec pobj(tamp, tseq, freq, duration, nqubit, nwindow);\n\n  gradc aobj = grad_ana(tlist, ini_vec, pobj, hdrive, dsham, states, cham);\n\n  for(int i=0; i< nqubit; i++){\n    for(int j=0; j< ngaus; j++){\n      gamp = 0.0;\n      gsig = 0.0;\n      gmean = 0.0;\n      for(int k=0; k< tlen;k++){\n\tesigmean = aobj.gradient[i][k] * expterm[i][j][k];\n\t\n\tgamp += esigmean;\n\tgsig += esigmean * amp[i][j] * -2.0 * sigma[i][j] *\n\t  (tlist[k] - mean[i][j])*(tlist[k] - mean[i][j]);\n\tgmean += esigmean * amp[i][j] * 2.0 * sigma[i][j] * sigma[i][j] *\n\t  (tlist[k] - mean[i][j]);\n\n      }\n      agradient.push_back(gamp);\n      agradient.push_back(gsig);\n      agradient.push_back(gmean);\n    }\n  }\n  gausgrad gausobj(aobj.energy, aobj.norm, agradient, tamp);\n\n  return gausobj;\n}\n\nstd::vector<double> gaus_gettamp(int &nqubit, int &ngaus,\n\t\t\t\tstd::vector<double> &tlist,\n\t\t\t\tstd::vector< std::vector<double > > &amp,\n\t\t\t\tstd::vector< std::vector<double > > &sigma,\n\t\t\t\tstd::vector< std::vector<double > > &mean,\n\t\t\t\tstd::vector< std::vector<double > > &gradient_){\n\n  double gamp, gsig, gmean, esigmean;\n  std::vector<double > agradient;\n  int tlen = tlist.size();\n\n  for(int i=0; i< nqubit; i++){\n    for(int j=0; j< ngaus; j++){\n      gamp = 0.0;\n      gsig = 0.0;\n      gmean = 0.0;\n      for(int k=0; k< tlen;k++){\n\tesigmean = gradient_[i][k] * fmath::expd(-sigma[i][j]*sigma[i][j] *\n\t\t\t\t\t\t(tlist[k] - mean[i][j]) *\n\t\t\t\t\t\t(tlist[k] - mean[i][j]));\n\tgamp += esigmean;\n\tgsig += esigmean * amp[i][j] * -2.0 * sigma[i][j] *\n\t  (tlist[k] - mean[i][j])*(tlist[k] - mean[i][j]);\n\tgmean += esigmean * amp[i][j] * 2.0 * sigma[i][j] * sigma[i][j] *\n\t  (tlist[k] - mean[i][j]);\n\n      }\n      agradient.push_back(gamp);\n      agradient.push_back(gsig);\n      agradient.push_back(gmean);\n    }\n  }\n  return agradient;\n}\n\t\n\t\nPYBIND11_MODULE(pulse_helper,m){\n  m.def(\"gaus_getnamp\", &gaus_getnamp, \"gaus_getnamp\");\n  m.def(\"gaus_gettamp\", &gaus_gettamp, \"gaus_gettamp\");\n  py::class_<gausgrad>(m,\"gausgrad\")\n    .def(py::init<\n\t double &, double &,\n\t std::vector<double> &,\n\t std::vector<std::vector< double > > & > ())\n    .def_readonly(\"energy\", &gausgrad::energy)\n    .def_readonly(\"norm\", &gausgrad::norm)\n    .def_readonly(\"gradient\",&gausgrad::gradient)\n    .def_readonly(\"amp\",&gausgrad::amp);\n}\n", "meta": {"hexsha": "110d7f01e4f941d4afa4db572c7af725c36e5b14", "size": 4562, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ctrlq/lib/pulse_helper.cc", "max_stars_repo_name": "asthanaa/ctrlq", "max_stars_repo_head_hexsha": "4af7721ed679a1ac2d4147a9406fa794f2af64d8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-09-25T14:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T17:36:53.000Z", "max_issues_repo_path": "ctrlq/lib/pulse_helper.cc", "max_issues_repo_name": "asthanaa/ctrlq", "max_issues_repo_head_hexsha": "4af7721ed679a1ac2d4147a9406fa794f2af64d8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-21T18:54:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T18:54:38.000Z", "max_forks_repo_path": "ctrlq/lib/pulse_helper.cc", "max_forks_repo_name": "asthanaa/ctrlq", "max_forks_repo_head_hexsha": "4af7721ed679a1ac2d4147a9406fa794f2af64d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-18T18:19:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-26T13:48:44.000Z", "avg_line_length": 30.0131578947, "max_line_length": 92, "alphanum_fraction": 0.6082858395, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4400034183784201}}
{"text": "#include <igl/writeDMAT.h>\n#include <igl/readDMAT.h>\n#include <igl/readMESH.h>\n#include <igl/get_seconds.h>\n\n#include <GaussIncludes.h>\n#include <ForceSpring.h>\n#include <FEMIncludes.h>\n#include <PhysicalSystemParticles.h>\n#include <ConstraintFixedPoint.h>\n\n#include <boost/filesystem.hpp>\n#include <nlohmann/json.hpp>\n\n#include <omp.h>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <memory>\n#include <algorithm>\n\n#include \"GreedyCubop.h\"\n\nusing json = nlohmann::json;\nnamespace fs = boost::filesystem;\nusing namespace std;\nusing namespace Gauss;\nusing namespace FEM;\nusing namespace ParticleSystem; \n\ntypedef PhysicalSystemFEM<double, NeohookeanTet> NeohookeanTets;\n\ntypedef World<double,\n    std::tuple<PhysicalSystemParticleSingle<double> *, NeohookeanTets *>,\n    std::tuple<ForceSpringFEMParticle<double> *>, std::tuple<ConstraintFixedPoint<double> *> > MyWorld;\n\n\n// Globals\nEigen::MatrixXd V; // Verts\nEigen::MatrixXi T; // Tet indices\nEigen::MatrixXi F; // Face indices\nfs::path model_root;\nint goal_tet_count = 0;\ndouble starting_time;\n\nvoid eig_to_VEC(const Eigen::VectorXd &eig_vec, VECTOR &vec_vec) {\n    vec_vec.resizeAndWipe(eig_vec.size());\n    std::memcpy(&vec_vec(0), eig_vec.data(), eig_vec.size() * sizeof(double));\n}\n\nEigen::VectorXd VEC_to_eig(VECTOR &vec) {\n    Eigen::VectorXd eig(vec.size());\n    std::memcpy(eig.data(), &vec(0), vec.size() * sizeof(double));   \n    return eig;\n}\n\nstd::string ZeroPadNumber(int num)\n{\n    std::ostringstream ss;\n    ss << std::setw( 7 ) << std::setfill( '0' ) << num;\n    return ss.str();\n}\n\ntemplate<typename T>\nT get_json_value(const json &j, const std::string &key, T def) {\n    try {\n        return j.at(key);\n    }\n    catch (nlohmann::detail::out_of_range& e){\n        return def;\n    }\n}\n\n\nclass MyGreedyCubop : public GreedyCubop {\npublic:\n    MyGreedyCubop(const Eigen::MatrixXd &V, const Eigen::MatrixXi &T, const Eigen::MatrixXd &U, double YM, double poisson, double density, const std::vector<Eigen::VectorXd> &reduced_forces, const std::vector<Eigen::VectorXd> &red_displacements) : GreedyCubop(), m_reduced_forces(reduced_forces), m_red_displacements(red_displacements) {\n        m_tets = make_unique<NeohookeanTets>(V,T);\n        for(auto element: m_tets->getImpl().getElements()) {\n            element->setDensity(density);\n            element->setParameters(YM, poisson);\n        }\n        // m_world.addSystem(m_tets.get());\n        // m_world.finalize();\n\n        m_U = U;\n    }\n\nprotected:\n    /**\n     * Return the total number of points we have to choose from.\n     * For example, for FEM piecewise-linear tetrahedra elements, this is just the number of tets.\n     */\n    int numTotalPoints() {\n        return m_tets->getImpl().getNumElements();\n    }\n\n\n\n    /**\n     * The main method that subclasses must implement. This should evaluate the reduced force density (or just the force, since\n     * the volume/area is constant anyway) at the given point.\n     *\n     *  pointId - an index in [0, getNumTotalPoints()). Implementations must map this index deterministically to a cubature point.\n     */\n    void evalPointForceDensity( int pointId, VECTOR& q, VECTOR& gOut ) {\n        // THIS ISN'T THREAD SAFE WITHOUT COPYING THE WORLD\n        // Make a copy of the world every time... Not the most efficient, but still faster than being single threaded\n        // double start = igl::get_seconds();\n\n        MyWorld m_world;\n        m_world.addSystem(m_tets.get());\n        m_world.finalize();\n\n        // update position of only the tet pointId\n        Eigen::VectorXd eig_q = VEC_to_eig(q);\n        auto gauss_map_q = mapDOFEigen(m_tets->getQ(), m_world);\n        const int n_verts = 4;\n        std::vector<int> verts(n_verts);\n        for(int i = 0; i < n_verts; i++) {\n            const int tet_vert = m_tets->getImpl().getElement(pointId)->getQDOFList()[i]->getGlobalId();\n            verts[i] = tet_vert;\n\n            for(int j = 0; j < 3; j++) {\n                gauss_map_q[tet_vert + j] = m_U.transpose().row(tet_vert + j) * eig_q;\n            }\n        }\n        // gauss_map_q = m_U.transpose() * eig_q;\n\n        // Get the element force\n        Eigen::VectorXd sampled_force(12);\n        m_tets->getImpl().getElement(pointId)->getInternalForce(sampled_force, m_world.getState());\n\n        // Assemble and project the full force\n        Eigen::SparseVector<double> full_force(m_U.cols());\n        for(int i = 0; i < n_verts; i++) {\n            int vert_index = verts[i];//m_tets->getImpl().getElement(pointId)->getQDOFList()[i]->getGlobalId();\n            for(int j = 0; j < 3; j++) {    \n                full_force.coeffRef(vert_index + j) = sampled_force[i * 3 + j];\n            }\n        }\n        \n        eig_to_VEC(m_U * full_force, gOut);\n        // std::cout << \"evalPointForceDensity: \" << igl::get_seconds() - start << \"s\" << std::endl;\n    }\n\n    /**\n     * At the end of each iteration (_not_ a sub-train iteration), when some cubature has been optimized, this will be called.\n     * Implementations should probably overwrite this and write the cubature out to file or something.\n     */\n    void handleCubature( std::vector<int>& selectedPoints, VECTOR& weights, Real relErr ) {\n        stringstream my_out;\n\n        my_out << \"n_tets: \" << selectedPoints.size() << endl;\n        my_out << \"relErr: \" << relErr << endl;\n        my_out << \"Selected tets: \";\n        for (std::vector<int>::iterator i = selectedPoints.begin(); i != selectedPoints.end(); ++i)\n        {\n            my_out << *i << \", \";\n        }\n        my_out << endl;\n\n        std::vector<int> nonzero_indices;\n        std::vector<double> nonzero_weights;\n        int n_nonzero = 0;\n        my_out << \"Weights: \";\n        for (int i = 0; i < weights.size(); ++i)\n        {\n            if(weights(i) > 0.00001) {\n                n_nonzero++;\n                nonzero_indices.push_back(selectedPoints[i]);\n                nonzero_weights.push_back(weights(i));\n            }\n\n            my_out << weights(i) << \", \";\n        }\n        my_out << endl << \"n_nonzero: \" << n_nonzero << endl;\n        my_out << endl;\n        my_out << \"Running time so far: \" << igl::get_seconds() - starting_time << \"s\" << std::endl;\n        my_out << endl;\n\n        Eigen::VectorXi Is = Eigen::Map<Eigen::VectorXi>(&nonzero_indices[0], nonzero_indices.size());\n        Eigen::VectorXd Ws = Eigen::Map<Eigen::VectorXd>(&nonzero_weights[0], nonzero_weights.size());\n\n        fs::path energy_model_dir = model_root / (\"energy_model/an08/pca_dim_\" + std::to_string(m_U.rows()) + \"/\");\n        fs::path this_iteration_output_dir = energy_model_dir / (ZeroPadNumber(n_nonzero) + \"_samples/\");\n        fs::create_directories(this_iteration_output_dir);\n\n        fs::path indices_path = this_iteration_output_dir / \"indices.dmat\";\n        fs::path weights_path = this_iteration_output_dir / \"weights.dmat\";\n        igl::writeDMAT(indices_path.string(), Is);\n        igl::writeDMAT(weights_path.string(), Ws);\n\n        fs::path details_path = this_iteration_output_dir / \"details.txt\";\n        ofstream fout(details_path.string());\n        fout << my_out.str();\n        fout.close();\n\n        cout << my_out.str();\n        cout << \"Saved weights and indices to \" << this_iteration_output_dir.string() << endl << endl;\n\n        const bool DEBUG = false;\n        if(DEBUG) {\n            int example_id = 500 % m_reduced_forces.size();//250;\n            Eigen::VectorXd actual_g = m_reduced_forces[example_id];\n            Eigen::VectorXd pred_g = get_predicted_force(example_id, nonzero_indices, nonzero_weights);\n\n            std::cout << actual_g.transpose() << std::endl;\n            std::cout << pred_g.transpose() << std::endl;\n\n            std::cout << (actual_g - pred_g).transpose().cwiseAbs() << std::endl;\n\n            std::cout << (actual_g - pred_g).squaredNorm() << std::endl;\n        }\n\n\n        // output everything every frame\n        {\n            fs::path indices_path = energy_model_dir / \"indices.dmat\";\n            fs::path weights_path = energy_model_dir / \"weights.dmat\";\n            igl::writeDMAT(indices_path.string(), Is);\n            igl::writeDMAT(weights_path.string(), Ws);\n\n            fs::path details_path = energy_model_dir / \"details.txt\";\n            ofstream fout(details_path.string());\n            fout << my_out.str();\n            fout.close();\n        }\n        if(n_nonzero >= goal_tet_count) {\n            cout << \"Reached goal number of tets. Exiting.\" << endl;\n            exit(0);\n        }\n    }\n\n    Eigen::VectorXd get_predicted_force(int example_id, const std::vector<int> &nonzero_indices, const std::vector<double> &nonzero_weights) {\n        Eigen::VectorXd pred_g = Eigen::VectorXd::Zero(m_U.rows());\n\n        MyWorld world;\n        world.addSystem(m_tets.get());\n        world.finalize();\n        auto gauss_map_q = mapDOFEigen(m_tets->getQ(), world);\n        gauss_map_q =  m_U.transpose() * m_red_displacements[example_id]; // Update the mesh\n\n\n        int n_sample_tets = nonzero_indices.size();\n        Eigen::SparseMatrix<double> neg_energy_sample_jac(m_U.cols(), T.rows());// m_cubature_indices.size());\n        neg_energy_sample_jac.reserve(Eigen::VectorXi::Constant(m_U.cols(), T.cols() * 3));\n        \n            \n        Eigen::VectorXd cubature_weights = Eigen::Map<const Eigen::VectorXd>(&nonzero_weights[0], nonzero_weights.size());\n        \n        int n_force_per_element = T.cols() * 3;\n        Eigen::MatrixXd element_forces(n_sample_tets, n_force_per_element);\n        Eigen::VectorXd energy_samp(n_sample_tets);\n\n\n        for(int i = 0; i < n_sample_tets; i++) { // TODO parallel\n            int tet_index = nonzero_indices[i];\n            energy_samp[i] = m_tets->getImpl().getElement(tet_index)->getStrainEnergy(world.getState());\n            // std::cout << energy_samp[i] << std::endl;\n            //Forces\n            Eigen::VectorXd sampled_force(n_force_per_element);\n            m_tets->getImpl().getElement(tet_index)->getInternalForce(sampled_force, world.getState());\n            element_forces.row(i) = sampled_force;\n        }\n\n        // std::cout << element_forces << std::endl;\n\n        for(int i = 0; i < n_sample_tets; i++) {\n            int tet_index = nonzero_indices[i];\n            for(int j = 0; j < 4; j++) {\n                int vert_index = m_tets->getImpl().getElement(tet_index)->getQDOFList()[j]->getGlobalId();\n                for(int k = 0; k < 3; k++) {\n                    neg_energy_sample_jac.insert(vert_index + k, i) = element_forces(i, j*3 + k);\n                }\n            }\n        }\n        pred_g = m_U * (neg_energy_sample_jac * cubature_weights);\n\n\n\n        return pred_g;\n    }\n\nprivate:\n    // MyWorld m_world;\n    unique_ptr<NeohookeanTets> m_tets;\n    Eigen::MatrixXd m_U;\n    const std::vector<Eigen::VectorXd> &m_reduced_forces;\n    const std::vector<Eigen::VectorXd> &m_red_displacements;\n};\n\n\nstd::vector<int> get_file_numbers_for_prefix(std::string prefix, fs::path dir) {\n    std::vector<int> nums;\n    for (auto i = fs::directory_iterator(dir); i != fs::directory_iterator(); i++)\n    {\n        fs::path cand_path = i->path();\n\n        std::string name = cand_path.filename().string(); \n        if(strncmp(name.c_str(), prefix.c_str(), prefix.size()) == 0) { // Is forces\n            std::string num_str = name.substr(prefix.size());\n            nums.push_back(std::stoi(num_str, nullptr));\n        }\n    }\n    std::sort(nums.begin(), nums.end());\n    return nums;\n}\n\nstd::vector<Eigen::VectorXd> load_forces(fs::path training_data_root, fs::path reduced_basis_path) {\n    std::cout << \"Loading reduced internal forces...\" << std::endl;\n    Eigen::MatrixXd U;\n    igl::readDMAT(reduced_basis_path.string(), U);\n    U.transposeInPlace();\n\n    std::string prefix = \"internalForces_\";\n    std::vector<int> forces_nums = get_file_numbers_for_prefix(prefix, training_data_root);\n    std::vector<Eigen::VectorXd> recorded_forces(forces_nums.size());\n    \n    std::cout << \"num threads: \" << omp_get_num_threads() << std::endl;\n    #pragma omp parallel for\n    for (int i = 0; i < forces_nums.size(); i++)\n    {//   std::vector<int>::iterator i = forces_nums.begin(); i != forces_nums.end(); ++i\n        fs::path dis_path = training_data_root / (prefix + std::to_string(forces_nums[i]) + \".dmat\");\n        Eigen::VectorXd F;\n        igl::readDMAT(dis_path.string(), F);\n        recorded_forces[i] = U * F;\n    }\n\n    std::cout << \"Done.\" << std::endl;\n\n    return recorded_forces;\n}\n\nstd::vector<Eigen::VectorXd> load_displacements(fs::path training_data_root, fs::path reduced_basis_path) {\n    std::cout << \"Loading displacements...\" << std::endl;\n    Eigen::MatrixXd U;\n    igl::readDMAT(reduced_basis_path.string(), U);\n    U.transposeInPlace();\n\n\n    std::string prefix = \"displacements_\";\n    std::vector<int> displacements_nums = get_file_numbers_for_prefix(prefix, training_data_root);\n    std::vector<Eigen::VectorXd> recorded_displacements(displacements_nums.size());\n\n    #pragma omp parallel for\n    for (int i = 0; i < displacements_nums.size(); i++)\n    {   \n        fs::path dis_path = training_data_root / (prefix + std::to_string(displacements_nums[i]) + \".dmat\");\n        Eigen::MatrixXd Q;\n        igl::readDMAT(dis_path.string(), Q);\n        Eigen::VectorXd q = Eigen::Map<Eigen::VectorXd>(Q.transpose().data(), Q.rows() * Q.cols());\n        recorded_displacements[i]=(U*q);\n    }\n    std::cout << \"Done.\" << std::endl;\n\n    return recorded_displacements;\n}\n\nvoid progress_bar(double progress, int barWidth = 70) {\n    std::cout << \"[\";\n    int pos = barWidth * progress;\n    for (int i = 0; i < barWidth; ++i) {\n        if (i < pos) std::cout << \"=\";\n        else if (i == pos) std::cout << \">\";\n        else std::cout << \" \";\n    }\n    std::cout << \"] \" << int(progress * 100.0) << \" %\\r\";\n    std::cout.flush();\n}\n\nstd::vector<Eigen::VectorXd> get_forces_from_reduced_displacements(const std::vector<Eigen::VectorXd> &red_displacements, const Eigen::MatrixXd &V, const Eigen::MatrixXi &T, const Eigen::MatrixXd &U, double YM, double poisson, double density) {\n    std::cout << \"Generating forces for reduced poses...\" << std::endl;\n    unique_ptr<NeohookeanTets> tets = make_unique<NeohookeanTets>(V,T);\n    \n    for(auto element: tets->getImpl().getElements()) {\n        element->setDensity(density);//1000.0);\n        element->setParameters(YM, poisson);\n    }\n    std::vector<Eigen::VectorXd> forces(red_displacements.size());\n    int n_done = 0;\n    double start = igl::get_seconds();\n    #pragma omp parallel\n    {\n        MyWorld world;\n        world.addSystem(tets.get());\n        world.finalize();\n\n\n        #pragma omp for\n        for(int i = 0; i < red_displacements.size(); i++) {\n            Eigen::Map<Eigen::VectorXd> gauss_map_q = mapDOFEigen(tets->getQ(), world);\n            gauss_map_q = U.transpose() * red_displacements[i];\n\n            AssemblerEigenVector<double> internal_force;\n            getInternalForceVector(internal_force, *tets, world);\n            forces[i] = (U * (*internal_force));\n            // std::cout << forces.back() << std::endl;\n            #pragma omp atomic\n            n_done++;\n\n            if(i % 20 == 0) progress_bar(n_done / (double) red_displacements.size());            \n        }\n    }\n    std::cout << \"Generating forces: \" << igl::get_seconds() - start << \"s\" << std::endl; \n    std::cout << std::endl;\n    return forces;\n}\n\nint main(int argc, char **argv) {\n    starting_time = igl::get_seconds();\n\n    if(argc < 3) {\n        cout << \"Need to pass in a path to model root and a goal number of tets.\" << endl;\n        exit(1);\n    }\n\n \n    // ---- Set Up\n    model_root = fs::path(argv[1]);\n    goal_tet_count = std::stoi(argv[2]);\n\n    fs::path reduced_basis_path = model_root / \"pca_results\" / \"ae_pca_components.dmat\";\n\n    int pca_dim;\n    if(argc == 4) {\n        pca_dim = std::stoi(argv[3]);\n        reduced_basis_path = model_root / \"pca_results\" / (\"pca_components_\" + std::to_string(pca_dim) + \".dmat\");\n    }\n\n\n    fs::path model_config_path = model_root / \"model_config.json\";\n    std::ifstream fin_model(model_config_path.string());\n    json model_config;\n    fin_model >> model_config;\n\n    std::string tdr = model_config[\"training_dataset\"];\n    fs::path training_data_root = tdr;\n    std::cout << training_data_root << std::endl;\n    fs::path mesh_path = model_root / \"tets.mesh\";\n    fs::path sim_config_path = model_root / \"sim_config.json\";\n\n    // Load sim config\n    std::ifstream fin(sim_config_path.string());\n    json sim_config;\n    fin >> sim_config;\n    double YM = sim_config[\"material_config\"][\"youngs_modulus\"];\n    double poisson = sim_config[\"material_config\"][\"poissons_ratio\"];\n    double density = sim_config[\"material_config\"][\"density\"];\n\n    // Load data\n    igl::readMESH(mesh_path.string(), V, T, F);\n\n    Eigen::MatrixXd U;\n    igl::readDMAT(reduced_basis_path.string(), U);\n    U.transposeInPlace();\n    std::cout << U.rows() << \" \" << U.cols() << std::endl;\n\n    // std::vector<Eigen::VectorXd> reduced_forces = load_forces(training_data_root, reduced_basis_path); // TODO maybe subsample?\n    std::vector<Eigen::VectorXd> red_displacements = load_displacements(training_data_root, reduced_basis_path);\n    // std::random_shuffle(red_displacements.begin(), red_displacements.end());\n    // std::vector<Eigen::VectorXd> less_displacements(red_displacements.begin(), red_displacements.begin() + 100);\n    std::vector<Eigen::VectorXd> reduced_forces = get_forces_from_reduced_displacements(red_displacements, V, T, U, YM, poisson, density);\n\n    // *** TODO ***\n    // I should test this by summing up the reduced forces at each tet and making sure they are equal to the full reduced force\n    // It's also possible that I should be generating the full reduced forces after projecting into, and out of, the reduced space\n    // for each training example...\n\n    // ---- Convert it all to the cubacode format\n    int n_poses = reduced_forces.size();\n    int r = reduced_forces[0].size();\n    cout << \"T: \" << n_poses << endl;\n    cout << \"r: \" << r << endl;\n    cout << \"r*T: \" << (n_poses*r) << endl;\n    cout << \"Tets: \" << T.rows() << endl;\n\n    // I have to construct the *reduced* forces evaluated at each of the total T tets.\n    VECTOR trainingForces(r * n_poses);\n    for(int i = 0; i < n_poses; i++) {\n        for(int j = 0; j < r; j++) {\n            trainingForces(i*r + j) = reduced_forces[i][j];\n        }\n    }\n\n    //What's this? -> It's all the configurations for each training pose\n    std::vector<VECTOR> training_poses(red_displacements.size());\n    TrainingSet trainingSet;\n    for(int i = 0; i < n_poses; i++) {\n        eig_to_VEC(red_displacements[i], training_poses[i]);\n        trainingSet.push_back(&training_poses[i]);\n    }\n\n    // Set up the optimization\n    MyGreedyCubop cubop(V, T, U, YM, poisson, density, reduced_forces, red_displacements);\n\n    // Params \n    Real relErrTol = get_json_value(model_config[\"learning_config\"][\"energy_model_config\"], \"rel_error_tol\", 0.05);//0.05; // What's a good val?\n    int maxNumPoints = goal_tet_count * 5; // some sane limit, for overnight runs\n    int numCandsPerIter = 200;//100;//T.rows() / 100;  //100;// default 100;  // |C|\n    int itersPerFullNNLS = r/2; // r/2 in the paper\n    int numSamplesPerSubtrain = 50; //training_poses.size() / 4; // default 50;   // T_s\n    \n    std::cout << \"relErrTol: \" << relErrTol << std::endl;    \n    std::cout << \"maxNumPoints: \" << maxNumPoints << std::endl;\n    std::cout << \"numCandsPerIter: \" << numCandsPerIter << std::endl;    \n    std::cout << \"itersPerFullNNLS: \" << itersPerFullNNLS << std::endl;\n    std::cout << \"numSamplesPerSubtrain: \" << numSamplesPerSubtrain << std::endl;\n\n    cout << \"Working\" << endl;\n\n    cubop.run(\n        trainingSet,\n        trainingForces,\n        relErrTol,\n        maxNumPoints,\n        numCandsPerIter,\n        itersPerFullNNLS,\n        numSamplesPerSubtrain\n    );\n\n    cout << \"Didn't reach goal number of tets.\" << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "92538a4ed8676270898868f42d4200cd0ea42435", "size": 19999, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cubacode/src/main.cpp", "max_stars_repo_name": "ericchen321/AutoDef", "max_stars_repo_head_hexsha": "aad03066d55422592e02281e5c1ea276ab0002d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T03:48:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T11:51:50.000Z", "max_issues_repo_path": "src/cubacode/src/main.cpp", "max_issues_repo_name": "ericchen321/AutoDef", "max_issues_repo_head_hexsha": "aad03066d55422592e02281e5c1ea276ab0002d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-04T12:16:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:02:41.000Z", "max_forks_repo_path": "src/cubacode/src/main.cpp", "max_forks_repo_name": "ericchen321/AutoDef", "max_forks_repo_head_hexsha": "aad03066d55422592e02281e5c1ea276ab0002d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-02T11:02:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T11:53:23.000Z", "avg_line_length": 37.9487666034, "max_line_length": 337, "alphanum_fraction": 0.6218810941, "num_tokens": 5181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.44000341837842005}}
{"text": "/**\n * Beck Pang 20180424, depreciated\n * Practice Extended Kalman Filter for eight states\n * Fusing an high precision gyroscope and a MPU6500 IMU as the process model,\n *   with an UWB and a magnetometer as the observation model.\n */\n#include <iostream>\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/Range.h>\n#include <std_msgs/String.h>\n#include <nav_msgs/Odometry.h>\n#include <uwb_msgs/uwb.h>\n#include <Eigen/Eigen>\n#include <queue>\n#include <vector>\n#include <cmath>\n\n#define INIT_Q_R_BY_MEASURE\n\nusing namespace std;\nusing namespace Eigen;\nros::Publisher odom_pub;\n\n/**\n * Define states:\n *      x = [pos_x, pos_y, angle_yaw, vel_x, vel_y, bias_gyro, bias_accel_x, bias_accel_y]\n * Define inputs:\n *      u = [angular_vel, accel_x, accel_y], all measurement\n * Define noises:\n *      n = [n_gyro, n_acc_x, n_acc_y, n_bias_gyro, n_bias_acc_x, n_bias_acc_y]\n */\nVectorXd x(8);                          // state\nMatrixXd P = MatrixXd::Identity(8, 8);  // covariance\nMatrixXd Q = MatrixXd::Identity(6, 6);  // prediction noise covariance\nMatrixXd R = MatrixXd::Identity(3, 3);  // observation noise covariance\n\n// Buffers to save imu reading and the uwb reading\n// for time synchronization\nqueue<sensor_msgs::Imu::ConstPtr> imu_buf;\nqueue<nav_msgs::Odometry::ConstPtr> odom_buf;\nqueue<Matrix<double, 8, 1>>     x_history;\nqueue<Matrix<double, 8, 8>>     P_history;\n\ndouble t;       //  previous propagated time\n\n// For initialization\nint imu_count = 0;\nconst int IMU_INIT_COUNT = 30;\nVector3d imu_mean_buf[IMU_INIT_COUNT]; // gyro, accel_x, accel_y\nqueue<double> odom_mean_buf_x;\nqueue<double> odom_mean_buf_y;\nqueue<double> odom_mean_buf_w;\ndouble theta_bias = 0;\nbool imu_initialized = false;\nbool odom_initialized= false;\n\n// Rotation from the IMU frame to the global frame\nEigen::Matrix3d Rimu;\n\n/**\n * non-linear propagate for EKF\n * with linearization around the current state\n * imu propagate in the world frame\n * @param imu_msg\n */\nvoid propagate(const sensor_msgs::ImuConstPtr &imu_msg)\n{\n    double cur_t = imu_msg->header.stamp.toSec();\n    double w     = imu_msg->angular_velocity.z;\n    double ax_raw   = imu_msg->linear_acceleration.x;\n    double ay_raw   = imu_msg->linear_acceleration.y;\n    Vector3d a_rotate = Vector3d(ax_raw, ay_raw, 0);\n    double ax = a_rotate(0);\n    double ay = a_rotate(1);\n\n    double dt   = cur_t - t;\n//    if (dt <= 0) {  ROS_BREAK; }\n\n    /**\n     * f(x, u, n) =\n     *      x4,\n     *      x5,\n     *      w_m - x6 - ng,\n     *      cos(x3) (a_mx - x7 - n_ax) + sin(x3) (a_my - x8 - n_ay),\n     *      -sin(x3) (a_mx - x7 - n_ax) + cos(x3) (a_my - x8 - n_ay),\n     *      n_bg,\n     *      n_bax,\n     *      n_bay.\n     * u_t_hat = u_t-1 + dt * f(u_t-1, u_t, 0)\n     */\n    x(0) += dt * x(3);\n    x(1) += dt * x(4);\n    x(2) += dt * (w - x(5));\n    x(3) += dt * ( cos(x(2)) * (ax - x(6)) + sin(x(2)) * (ay - x(7)) );\n    x(4) += dt * (-sin(x(2)) * (ax - x(6)) + cos(x(2)) * (ay - x(7)) );\n//    x(5) += dt * 0;\n//    x(6) += dt * 0;\n//    x(7) += dt * 0;\n\n    MatrixXd A = MatrixXd::Zero(8, 8);\n    A(0, 3) =  1;\n    A(1, 4) =  1;\n    A(2, 5) = -1;\n    // df4 / dx3\n    A(3, 2) = -sin(x(2)) * (ax - x(6)) + cos(x(2)) * (ay - x(7));\n    // df5 / dx3\n    A(4, 2) = -cos(x(2)) * (ax - x(6)) - sin(x(2)) * (ay - x(7));\n    A(3, 6) = -cos(x(2));\n    A(4, 6) =  sin(x(2));\n    A(3, 7) = -sin(x(2));\n    A(4, 7) = -cos(x(2));\n\n    MatrixXd U = MatrixXd::Zero(8, 6);\n    U(2, 0) = -1;\n    U(3, 1) = -cos(x(2));\n    U(4, 1) = -sin(x(2));\n    U(3, 2) =  sin(x(2));\n    U(4, 2) = -cos(x(2));\n    U.block<3,3>(5, 3) = MatrixXd::Identity(3, 3);\n\n    MatrixXd F, V;\n    F = dt * A + MatrixXd::Identity(8, 8);\n    V = dt * U;\n    /**\n     * P_t_hat = F * P_t * F' + V * Q * V'\n     */\n    P = F * P * F.transpose() + V * Q * V.transpose();\n\n    t = cur_t;\n}\n\n/**\n * linear update for EKF\n * @param msg\n */\nvoid update(const uwb_msgs::uwb &msg)\n{\n    MatrixXd C = MatrixXd::Zero(3, 8);\n    C.block<3, 3>(0, 0) = Matrix3d::Identity();\n\n    double pos_x = msg.pos_x;\n    double pos_y = msg.pos_y;\n    double angle_yaw = msg.pos_theta;\n    Vector3d y(pos_x, pos_y, angle_yaw);\n\n    MatrixXd K(8, 3);\n    K = P * C.transpose() * (C * P * C.transpose() + R).inverse();\n    x = x + K * (y - C * x);\n    P = P - K * C * P;\n}\n\nvoid pub_odom(std_msgs::Header header)\n{\n    nav_msgs::Odometry odom;\n    odom.header.stamp = header.stamp;\n    odom.header.frame_id = \"world\";\n    odom.pose.pose.position.x   = x(0);\n    odom.pose.pose.position.y   = x(1);\n    odom.pose.pose.orientation.z= x(2);\n    odom.twist.twist.linear.x   = x(3);\n    odom.twist.twist.linear.y   = x(4);\n    odom.pose.covariance[0]     = P(0, 0);\n    odom.pose.covariance[7]     = P(1, 1);\n    odom.pose.covariance[35]    = P(2, 2);\n    odom.twist.covariance[0]    = P(3, 3);\n    odom.twist.covariance[7]    = P(4, 4);\n\n    odom_pub.publish(odom);\n}\n\nvoid imu_callback(const sensor_msgs::Imu::ConstPtr &imu_msg)\n{\n//    ROS_INFO(\"IMU callback, time: %f\", imu_msg->header.stamp.toSec());\n\n    if (!imu_initialized && imu_count < IMU_INIT_COUNT)\n    {\n        // calculate the imu covariance and mean, and initialize the gravity\n        imu_mean_buf[imu_count](0) = imu_msg->angular_velocity.z;\n        imu_mean_buf[imu_count](1) = imu_msg->linear_acceleration.x;\n        imu_mean_buf[imu_count](2) = imu_msg->linear_acceleration.y;\n        imu_count++;\n    }\n    else if (!imu_initialized && imu_count == IMU_INIT_COUNT)\n    {\n#ifdef INIT_Q_R_BY_MEASURE\n        double imu_mean[3] = {0};\n        double imu_cova[3]= {0};\n        for (int i = 0; i < imu_count; ++i) {\n            imu_mean[0] += imu_mean_buf[i](0);\n            imu_mean[1] += imu_mean_buf[i](1);\n            imu_mean[2] += imu_mean_buf[i](2);\n            imu_cova[0] += pow( imu_mean_buf[i](0), 2 );\n            imu_cova[1] += pow( imu_mean_buf[i](1), 2 );\n            imu_cova[2] += pow( imu_mean_buf[i](2), 2 );\n        }\n        imu_mean[0] /= imu_count;\n        imu_mean[1] /= imu_count;\n        imu_mean[2] /= imu_count;\n        imu_cova[0] /= imu_count;\n        imu_cova[1] /= imu_count;\n        imu_cova[2] /= imu_count;\n        Q(0, 0) = imu_cova[0] - pow( imu_mean[0], 2 );\n        Q(1, 1) = imu_cova[1] - pow( imu_mean[1], 2 );\n        Q(2, 2) = imu_cova[2] - pow( imu_mean[2], 2 );\n#endif\n        imu_initialized = true;\n    }\n    else {\n        imu_buf.push(imu_msg);\n        propagate(imu_msg);\n        x_history.push(x);\n        P_history.push(P);\n        pub_odom(imu_msg->header);\n    }\n}\n\n/**\n * initialize, handle and save uwb messages\n * Also doing time synchronization\n * @param uwb msg\n */\nvoid odom_callback(const uwb_msgs::uwb &msg)\n{\n//    ROS_INFO(\"UWB callback, time: %f\", msg->header.stamp.toSec());\n\n    if (!imu_initialized && !odom_initialized)\n    {\n        // calculate the uwb covariance and mean\n        odom_mean_buf_x.push(msg.pos_x);\n        odom_mean_buf_y.push(msg.pos_y);\n        odom_mean_buf_w.push(msg.pos_theta);\n    }\n    else if (imu_initialized && !odom_initialized)\n    {\n#ifdef INIT_Q_R_BY_MEASURE\n        double odom_mean[3] = {0};\n        double odom_cova[3] = {0};\n        int odom_count = (int)odom_mean_buf_x.size();\n        for (int i = 0; i < odom_count; ++i) {\n            double temp_x = odom_mean_buf_x.front();\n            double temp_y = odom_mean_buf_y.front();\n            double temp_w = odom_mean_buf_w.front();\n            odom_mean[0] += temp_x;\n            odom_mean[1] += temp_y;\n            odom_mean[2] += temp_w;\n            odom_cova[0] += pow( temp_x, 2 );\n            odom_cova[1] += pow( temp_y, 2 );\n            odom_cova[2] += pow( temp_w, 2 );\n            odom_mean_buf_x.pop();\n            odom_mean_buf_y.pop();\n            odom_mean_buf_w.pop();\n        }\n        odom_mean[0] /= odom_count;\n        odom_mean[1] /= odom_count;\n        odom_mean[2] /= odom_count;\n        odom_cova[0] /= odom_count;\n        odom_cova[1] /= odom_count;\n        odom_cova[2] /= odom_count;\n\n\t\t// Initialize the position and bias\n\t\tx(0) = odom_mean[0];\n\t\tx(1) = odom_mean[1];\n\t\tx(2) = 0;\n\t\ttheta_bias = odom_mean[2];\n\n        // Initialize the covariance R\n\t\tR(0, 0) = odom_cova[0] - pow( odom_mean[0], 2 );\n        R(1, 1) = odom_cova[1] - pow( odom_mean[1], 2 );\n        R(2, 2) = odom_cova[2] - pow( odom_mean[2], 2 );\n#else\n\t\tx(0) = msg.pos_x;\n\t\tx(1) = msg.pos_y;\n\t\tx(2) = 0;\n\t\ttheta_bias = msg.pos_theta;\n#endif\n\t\tt = msg.header.stamp.toSec();\n        odom_initialized = true;\n    }\n    else {\n        while (!imu_buf.empty() && imu_buf.front()->header.stamp < msg.header.stamp)\n        {\n            ROS_INFO(\"throw state with time: %f\", imu_buf.front()->header.stamp.toSec());\n            // trace the time backwards to imu time\n            t = imu_buf.front()->header.stamp.toSec();\n            imu_buf.pop();\n            x_history.pop();\n            P_history.pop();\n        }\n        if (!x_history.empty())\n        {\n            // if x_history is empty then the odom is the same time as the imu\n            x = x_history.front();\n            P = P_history.front();\n            // trace the time backwards to imu time\n            t = imu_buf.front()->header.stamp.toSec();\n            imu_buf.pop();\n            x_history.pop();\n            P_history.pop();\n        }\n        ROS_INFO(\"update state with time: %f\", msg.header.stamp.toSec());\n        update(msg);\n\n        // clean the x and P history before new propagate\n        while(!x_history.empty()) x_history.pop();\n        while(!P_history.empty()) P_history.pop();\n\n        queue<sensor_msgs::Imu::ConstPtr> temp_imu_buf;\n        while (!imu_buf.empty())\n        {\n            ROS_INFO(\"propagate state with time: %f\", imu_buf.front()->header.stamp.toSec());\n            propagate(imu_buf.front());\n            temp_imu_buf.push(imu_buf.front());\n            x_history.push(x);\n            P_history.push(P);\n            imu_buf.pop();\n        }\n        std::swap(imu_buf, temp_imu_buf);\n    }\n}\n\nstring imu_topic, uwb_topic, publiser_topic;\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"ekf_8states\");\n    ros::NodeHandle n(\"~\");\n\n    ros::Duration(10).sleep(); // sleep for 10 seconds in order to launch both topics\n\n\n    n.param(\"imu_topic\", imu_topic, string(\"/dji_sdk/imu\"));\n    n.param(\"uwb_topic\", uwb_topic, string(\"/uwb_info\"));\n    n.param(\"publiser_topic\", publiser_topic, string(\"/ekf_odom\"));\n    ros::Subscriber s1 = n.subscribe(imu_topic, 100, imu_callback);\n    ros::Subscriber s2 = n.subscribe(uwb_topic, 10, odom_callback);\n    odom_pub = n.advertise<nav_msgs::Odometry>(publiser_topic, 100);\n    ros::Rate r(100);\n\n    // Rimu = Quaterniond( 0.7071, 0, 0, -0.7071 ).toRotationMatrix( );\n    Rimu << 1, 0, 0,\n\t\t\t0, 1, 0,\n\t\t\t0, 0, 1;\n\tcout << \"R_cam\" << endl << Rimu << endl;\n\n    odom_initialized = true;\n\n    // gyroscope noise n_g\n    Q(0, 0) = 0.0001 * Q(0, 0);\n    // accelerometer noise n_ax, n_ay\n    Q(1, 1) = 0.01 * Q(1, 1);\n    Q(2, 2) = 0.01 * Q(2, 2);\n    // gyroscope bias noise n_bg\n    Q(3, 3) = 0.000001 * Q(3, 3);\n    // accelerometer bias noise n_ba\n    Q(4, 4) = 0.0001 * Q(4, 4);\n    Q(5, 5) = 0.0001 * Q(5, 5);\n\n    // uwb noise n_x, n_y\n    R(0, 0) = 0.001 * R(0, 0);\n    R(1, 1) = 0.001 * R(1, 1);\n    // magnetometer noise n_theta\n    R(2, 2) = 0.01 * R(2, 2);\n\n    ros::spin();\n}\n", "meta": {"hexsha": "6e504f266f1f272b041be7c09b7a89ba5af41edd", "size": 11280, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3_estimator/history/ekf_uwb/src/ekf_uwb_node_2D.cpp", "max_stars_repo_name": "huying163/ros_environment", "max_stars_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-01-30T11:40:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T05:52:47.000Z", "max_issues_repo_path": "3_estimator/history/ekf_uwb/src/ekf_uwb_node_2D.cpp", "max_issues_repo_name": "huying163/ros_environment", "max_issues_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3_estimator/history/ekf_uwb/src/ekf_uwb_node_2D.cpp", "max_forks_repo_name": "huying163/ros_environment", "max_forks_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-23T08:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T08:14:57.000Z", "avg_line_length": 30.652173913, "max_line_length": 93, "alphanum_fraction": 0.5654255319, "num_tokens": 3647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.43999445379236696}}
{"text": "#include <iostream>\n#include <vector>\n#include <list>\n#include <cmath>\n\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/index/rtree.hpp>\n#include <boost/mpl/range_c.hpp>\n#include <boost/mpl/for_each.hpp>\n\n#include \"fof.hpp\"\n#include \"fof_brute.hpp\"\n\n\nnamespace bg = boost::geometry;\nnamespace bmpl = boost::mpl;\nnamespace bgi = bg::index;\n\n// Create a D dimensional point from an array of coordinates\ntemplate <size_t D>\nstruct point_setter {\n    typedef bg::model::point<double, D, bg::cs::cartesian> point_t;\n\n    point_t& point;\n    double *loc;\n\n    point_setter(point_t& point, double *loc) : point(point), loc(loc)\n    {}\n\n    template< typename U > void operator()(U i)\n    {\n        bg::set<i>(point, loc[i]);\n    }\n\n};\n\n// Calculate the square of the euclidian distance between two points\ntemplate <size_t D>\nstruct d2_calc {\n    typedef bg::model::point<double, D, bg::cs::cartesian> point_t;\n\n    const point_t &p1;\n    const point_t &p2;\n    double &d2;\n\n    d2_calc(const point_t &p1, const point_t &p2, double &d2) : p1(p1), p2(p2), d2(d2)\n    {}\n\n    template< typename U > void operator()(U i)\n    {\n        d2 += pow( bg::get<i>(p1) - bg::get<i>(p2), 2);\n    }\n};\n\n// Add a scaler to all the coordinates of a point\ntemplate <size_t D>\nstruct add_scalar_to_point {\n    typedef bg::model::point<double, D, bg::cs::cartesian> point_t;\n\n    point_t &p;\n    double c;\n\n    add_scalar_to_point(point_t &p, double c) : p(p), c(c)\n    {}\n\n    template< typename U > void operator()(U i)\n    {\n        double new_coord = bg::get<i>(p) + c;\n        bg::set<i>(p, new_coord);\n    }\n\n};\n\ntemplate <size_t D>\nstd::vector< std::vector<size_t> >\nfriends_of_friends_rtree(double *data, size_t npts, double linking_length)\n{\n    typedef bg::model::point<double, D, bg::cs::cartesian> point_t;\n    typedef std::pair<point_t, size_t> value_t;\n    using tree_t =  bgi::rtree< value_t, bgi::linear<16> >;\n    typedef bmpl::range_c<size_t, 0, D> dim_range;\n\n    std::vector< std::pair<point_t, size_t> > points;\n    points.reserve(npts);\n\n    for(size_t i = 0 ; i<npts ; ++i) {\n        point_t point;\n        bmpl::for_each< dim_range >( point_setter<D>(point, data + i*D) );\n        points.push_back(std::make_pair(point, i));\n    }\n\n    tree_t tree(points.begin(), points.end());\n\n    std::vector< std::vector< size_t > > groups;\n\n    while( !tree.empty() ) {\n        std::vector< value_t > to_add;\n\n        // Grab a point from the tree.\n        to_add.push_back( *tree.qbegin( bgi::satisfies([](value_t const &){return true;})) );\n        tree.remove( to_add.begin(), to_add.end() );\n\n\n        for( auto to_add_i = size_t(0) ; to_add_i < to_add.size() ; ++to_add_i ) {\n            std::vector< value_t >  added;\n\n            auto it = to_add.begin() + to_add_i;\n\n            // Build box to query\n            point_t lower = it->first;\n            bmpl::for_each< dim_range >( add_scalar_to_point<D>(lower, -linking_length) );\n            point_t upper = it->first;\n            bmpl::for_each< dim_range >( add_scalar_to_point<D>(upper, +linking_length));\n\n            bg::model::box< point_t > box( lower, upper );\n\n            auto within_ball = [&it, linking_length](value_t const &v) {\n                double d2 = 0.;\n                bmpl::for_each< dim_range >( d2_calc<D>(it->first, v.first, d2) );\n                return sqrt(d2) < linking_length;\n            };\n\n            // Find all points within a linking length of the current point.\n            tree.query( bgi::within(box) && bgi::satisfies(within_ball), std::back_inserter(added) );\n\n            // Add the found points to the list so we can find their \"friends\" as well\n            for (auto p: added) {\n                to_add.push_back(p);\n            }\n\n            // Remove any points we find from the tree as they have been assigned.\n            tree.remove( added.begin(), added.end() );\n\n            // Early exit when we have assigned all particles to a group\n            if (tree.empty()) {\n                break;\n            }\n        }\n\n        std::vector< size_t > group;\n        for( auto p : to_add ) {\n            group.push_back(p.second);\n        }\n        groups.push_back(group);\n    }\n\n    return groups;\n}\n\n\nstd::vector< std::vector<size_t> >\nfriends_of_friends(double *data, size_t npts, size_t ndim, double linking_length)\n{\n    switch(ndim) {\n        case 1:\n            return friends_of_friends_rtree<1>(data, npts, linking_length);\n            break;\n        case 2:\n            return friends_of_friends_rtree<2>(data, npts, linking_length);\n            break;\n        case 3:\n            return friends_of_friends_rtree<3>(data, npts, linking_length);\n            break;\n        case 4:\n            return friends_of_friends_rtree<4>(data, npts, linking_length);\n            break;\n        default:\n            return friends_of_friends_brute(data, npts, ndim, linking_length);\n            break;\n    }\n}\n\n", "meta": {"hexsha": "45e2a94a46c0be6efdd24d2915e5848eaad4b75a", "size": 4919, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pyfof/fof.cc", "max_stars_repo_name": "guotsuan/pyfof", "max_stars_repo_head_hexsha": "b15ffdd4ebb4aca46021942a342f664e8e4ab806", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2015-12-31T18:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T08:05:07.000Z", "max_issues_repo_path": "pyfof/fof.cc", "max_issues_repo_name": "guotsuan/pyfof", "max_issues_repo_head_hexsha": "b15ffdd4ebb4aca46021942a342f664e8e4ab806", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-03-27T16:59:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:48:48.000Z", "max_forks_repo_path": "pyfof/fof.cc", "max_forks_repo_name": "guotsuan/pyfof", "max_forks_repo_head_hexsha": "b15ffdd4ebb4aca46021942a342f664e8e4ab806", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-09-18T11:53:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T16:57:17.000Z", "avg_line_length": 28.4335260116, "max_line_length": 101, "alphanum_fraction": 0.593210002, "num_tokens": 1317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.43999445379236696}}
{"text": "#include \"adaptive.h\"\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <cmath>\n#include \"control/util.h\"\n\nnamespace sailbot {\nnamespace control {\n\nconstexpr float AdaptiveControl::dt;\n\nControlPhysics::ControlPhysics() {\n  constexpr double rhoair = 1.225; // Density of air, kg / m^3\n  constexpr double rhowater = 1000.0; // Density of water, kg / m^3\n  consts_ = {.sail = {.A = 2.0,\n                      .rho = rhoair,\n                      .C = 1.4,\n                      .K = 1.5,\n                      .drageps = 0.0,\n                      .maxalpha = M_PI_2},\n             .keel = {.A = 0.3,\n                      .rho = rhowater,\n                      .C = 1.4,\n                      .K = 8.0,\n                      .drageps = 0.1,\n                      .maxalpha = 0.25},\n             .rudder = {.A = 0.04,\n                        .rho = rhowater,\n                        .C = 1.7,\n                        .K = 5.0,\n                        .drageps = 0.05,\n                        .maxalpha = 0.25},\n             .hs = 1.5,\n             .hk = -0.7,\n             .hr = 0.0,\n             .rs = 0.1,\n             .rk = 0.0,\n             .rr = -0.9,\n             .ls = 0.35,\n             .lr = 0.0,\n             .hb = -0.7,\n             .m = 25.0,\n             .g = 9.8,\n             .J = 10.0,\n             .Blon = 15.0,\n             .Blat = 25.0,\n             .Bomega = 500.0,\n             .taubias = 0.0};\n  // beta = Blon, Bomega, Ar, rs, taubias, 1.0\n  betamin_ << 0.0, 0.0, 0.01, -1.0, -10.0, 1.0;\n  betamax_ << 1000.0, 10000.0, 1.0, 1.0, 10.0, 1.0;\n}\n\nvoid ControlPhysics::IncrementBeta(const MatrixBeta &diff) {\n  MatrixBeta b = beta();\n  b += diff;\n  // For sundry reasons, Eigen only provides the max/min operators for arrays...\n  b = b.array().max(betamin_).min(betamax_).matrix();\n  set_beta(b);\n}\n\ndouble ControlPhysics::RudderForTorque(double taus, double tauk, double taugoal,\n                                       double heel, double thetac,\n                                       double vc) const {\n  double cthetac = std::max(std::cos(thetac), 0.5);\n  double denom = 0.5 * consts_.rudder.rho * consts_.rudder.A * vc * vc *\n                 consts_.rudder.K * std::cos(thetac) * std::cos(heel) *\n                 consts_.rr;\n  return (taugoal - taus - tauk - consts_.taubias) / denom - thetac;\n}\n\nvoid ControlPhysics::SailAirfoil(double alpha, double v, double *force,\n                                 double *ang) const {\n  const double absalpha = std::abs(alpha);\n  const double signalpha = util::Sign(alpha);\n  if (force != nullptr) {\n    double trimalpha = std::max(absalpha - 0.05, 0.0);\n    const double mag =\n        consts_.sail.C * (1.0 - std::exp(-consts_.sail.K * trimalpha));\n    *force = 0.5 * consts_.sail.rho * consts_.sail.A * v * v * mag;\n  }\n  if (ang != nullptr) {\n    *ang = (M_PI_2 - std::abs(alpha)) * signalpha;\n  }\n}\n\nvoid ControlPhysics::KeelAirfoil(double alpha, double v, double *force,\n                                 double *ang) const {\n  const double absalpha = std::abs(alpha);\n  const double signalpha = util::Sign(alpha);\n  if (force != nullptr) {\n    const double mag = consts_.keel.K * std::min(absalpha, consts_.keel.maxalpha);\n    *force = 0.5 * consts_.keel.rho * consts_.keel.A * v * v * mag;\n  }\n  if (ang != nullptr) {\n    *ang = (M_PI_2 - consts_.keel.drageps) * signalpha;\n  }\n}\n\nvoid ControlPhysics::RudderAirfoil(double alpha, double v, double *force,\n                                   double *ang) const {\n  const double absalpha = std::abs(alpha);\n  const double signalpha = util::Sign(alpha);\n  if (force != nullptr) {\n    const double mag =\n        consts_.rudder.K * std::min(absalpha, consts_.rudder.maxalpha);\n    *force = 0.5 * consts_.rudder.rho * consts_.rudder.A * v * v * mag;\n  }\n  if (ang != nullptr) {\n    *ang = (M_PI_2 - consts_.rudder.drageps) * signalpha;\n  }\n}\n\nvoid ControlPhysics::SailForce(double thetaw, double vw, double deltas,\n                               double *Fs, double *gammas) const {\n  double alpha = -util::norm_angle(thetaw + deltas + M_PI);\n  double ang;\n  SailAirfoil(alpha, vw, Fs, &ang);\n  if (gammas != nullptr) {\n    *gammas = util::norm_angle(ang - thetaw);\n  }\n}\n\nvoid ControlPhysics::KeelForce(double thetac, double vc, double *Fk,\n                               double *gammak) const {\n  double alpha = -util::norm_angle(thetac);\n  double ang;\n  KeelAirfoil(alpha, vc, Fk, &ang);\n  if (gammak != nullptr) {\n    *gammak = util::norm_angle(ang - thetac + M_PI);\n  }\n}\n\nvoid ControlPhysics::RudderForce(double thetac, double vc, double deltar,\n                                 double *Fr, double *gammar) const {\n  double alpha = -util::norm_angle(thetac + deltar);\n  double ang;\n  RudderAirfoil(alpha, vc, Fr, &ang);\n  if (gammar != nullptr) {\n    *gammar = util::norm_angle(ang - thetac + M_PI);\n  }\n}\n\ndouble ControlPhysics::SailTorque(double Fs, double gammas, double deltas,\n                                  double heel) const {\n  return Fs * ((consts_.rs - consts_.ls * std::cos(deltas)) * std::sin(gammas) *\n                   std::cos(heel) +\n               consts_.hk * std::cos(gammas) * std::sin(heel));\n}\n\ndouble ControlPhysics::KeelTorque(double Fk, double gammak, double heel) const {\n  return Fk * (consts_.rk * std::sin(gammak) * std::cos(heel) +\n               consts_.hk * std::cos(gammak) * std::sin(heel));\n}\n\ndouble ControlPhysics::RudderTorque(double Fr, double gammar, double heel) const {\n  return Fr * consts_.rr * std::sin(gammar) * std::cos(heel);\n}\n\ndouble ControlPhysics::CalcHeel(double Fs, double gammas, double Fk,\n                                double gammak) const {\n  double tanheel =\n      (Fs * consts_.hs * std::sin(gammas) + Fk * consts_.hk * std::sin(gammak)) /\n      (consts_.hb * consts_.m * consts_.g);\n  return std::atan(tanheel);\n}\n\nvoid ControlPhysics::NetForce(double thetaw, double vw, double thetac,\n                              double vc, double deltas, double deltar,\n                              double omega, double *Flon, double *Flat,\n                              double *taunet, double *newheel,\n                              MatrixY *Y) const {\n  double Fs, gammas, Fk, gammak, Fr, gammar;\n  SailForce(thetaw, vw, deltas, &Fs, &gammas);\n  KeelForce(thetac, vc, &Fk, &gammak);\n  RudderForce(thetac, vc, deltar, &Fr, &gammar);\n  double heel = CalcHeel(Fs, gammas, Fk, gammak);\n  if (newheel != nullptr) *newheel = heel;\n  double taus = SailTorque(Fs, gammas, deltas, heel);\n  double tauk = KeelTorque(Fk, gammak, heel);\n  double taur = RudderTorque(Fr, gammar, heel);\n\n  double YFlonBlon = -vc * std::abs(vc) * std::cos(thetac);\n  double YFlonAr = Fr * std::cos(gammar) / consts_.rudder.A;\n  double YFlonconst = Fs * std::cos(gammas) + Fk * std::cos(gammak);\n  Eigen::Matrix<double, 1, 6> YFlon;\n  YFlon << YFlonBlon, 0.0, YFlonAr, 0.0, 0.0, YFlonconst;\n\n  if (Flon != nullptr) *Flon = YFlon * beta();\n  if (Flat != nullptr) {\n    double FBlat = consts_.Blat * vc * std::sin(thetac);\n    *Flat =\n        (Fs * std::sin(gammas) + Fk * std::sin(gammak) + Fr * std::sin(gammar)) *\n        std::cos(heel) + FBlat;\n  }\n\n  double YtauBomega = -omega * std::abs(omega);\n  double YtauAr = taur / consts_.rudder.A;\n  double Ytaurs = Fs * std::sin(gammas) * std::cos(heel);\n  double Ytauconst = tauk + (taus - Ytaurs * consts_.rs);\n  Eigen::Matrix<double, 1, 6> Ytau;\n  Ytau << 0.0, YtauBomega, YtauAr, Ytaurs, 1.0, Ytauconst;\n\n  if (taunet != nullptr) *taunet = Ytau * beta();\n\n  if (Y != nullptr) {\n    Y->row(0) = YFlon;\n    Y->row(1) = Ytau;\n  }\n}\n\nbool ControlPhysics::GlobalMaxForceForTorque(double thetaw, double vw,\n                                             double thetac, double vc,\n                                             double taug, Constraint constraint,\n                                             int nsteps, double *deltas,\n                                             double *deltar) const {\n  CHECK_NOTNULL(deltas);\n  CHECK_NOTNULL(deltar);\n  double minds, maxds;\n  {\n    double maxsail = std::abs(util::norm_angle(M_PI - thetaw));\n    double minsail = std::max(maxsail - M_PI_2, 0.0);\n    maxsail = std::min(maxsail, M_PI_2);\n    minds = thetaw > 0.0 ? minsail : -maxsail;\n    maxds = thetaw < 0.0 ? -minsail : maxsail;\n  }\n  double mindr = util::Clip(-consts().rudder.maxalpha - thetac, -0.5, 0.);\n  double maxdr = util::Clip(consts().rudder.maxalpha - thetac, 0., 0.5);\n\n  double mincost = std::numeric_limits<double>::infinity();\n  bool success = false;\n  double deltadeltas = (maxds - minds) / std::max(1, nsteps - 1);\n\n  double taus, tauk, taur, taue, heel;\n  for (int ii = 0; ii < nsteps; ++ii) {\n    double trialds = minds + (double)ii * deltadeltas;\n    double Fs, gammas, Fk, gammak, Fr, gammar;\n    SailForce(thetaw, vw, trialds, &Fs, &gammas);\n    KeelForce(thetac, vc, &Fk, &gammak);\n    heel = CalcHeel(Fs, gammas, Fk, gammak);\n    taus = SailTorque(Fs, gammas, trialds, heel);\n    tauk = KeelTorque(Fk, gammak, heel);\n    double trialdr = RudderForTorque(taus, tauk, taug, heel, thetac, vc);\n    switch (constraint) {\n      case kQuadratic:\n        trialdr = ClipRudder(trialdr, thetac);\n        break;\n      // For kStarboard and kPort, trialdr may end up outside of the allowable\n      // bounds, in which case this particular iteration of the for loop has\n      // produced an invalid result.\n      case kStarboard:\n        trialdr = std::max(trialdr, maxdr);\n        break;\n      case kPort:\n        trialdr = std::min(trialdr, mindr);\n        break;\n    }\n\n    if (ClipRudder(trialdr, thetac) != trialdr) {\n      // Invalid rudder result.\n      continue;\n    }\n\n    success = true;\n\n    RudderForce(thetac, vc, trialdr, &Fr, &gammar);\n    taur = RudderTorque(Fr, gammar, heel);\n    double Flon =\n        Fs * std::cos(gammas) + Fk * std::cos(gammak) + Fr * std::cos(gammar);\n\n    taue = taus + tauk + taur + consts_.taubias;\n\n    double cost = -Qf * Flon;\n    switch (constraint) {\n      case kQuadratic:\n        cost += Qtaueq * (taue - taug) * (taue - taug);\n        break;\n      case kStarboard:\n        cost += Qtaumax * taue;\n        break;\n      case kPort:\n        cost += -Qtaumax * taue;\n        break;\n    }\n\n    if (cost < mincost) {\n      mincost = cost;\n      *deltas = trialds;\n      *deltar = trialdr;\n    }\n  }\n\n  return success;\n}\n\nAdaptiveControl::AdaptiveControl()\n    : Node(dt),\n      sail_msg_(AllocateMessage<msg::SailCmd>()),\n      rudder_msg_(AllocateMessage<msg::RudderCmd>()),\n      boat_state_(AllocateMessage<msg::BoatState>()),\n      consts_msg_(AllocateMessage<msg::ControllerConstants>()),\n      heading_(2.0 * M_PI / 4.0),\n      sail_cmd_(\"sail_cmd\", true),\n      rudder_cmd_(\"rudder_cmd\", true),\n      consts_queue_(\"control_consts\", true) {\n\n    consts_msg_->set_winch_kp(13);\n    consts_msg_->set_rudder_kp(25.0);\n    consts_msg_->set_qf(1.0);\n    {\n      std::unique_lock<std::mutex> l(consts_mutex_);\n      consts_queue_.send(consts_msg_);\n    }\n\n  Kbeta.diagonal() << 0.0, 0.0, 0.0, 0.004, 0.0, 0.;\n  Lambda << 1.0, 0.0,\n            0.0, 1.0;\n  Kref = 0.99;\n  Kmax_exp_vel = 0.2;\n  Kmax_exp_acc = 0.2;\n\n  RegisterHandler<msg::BoatState>(\"boat_state\", [this](const msg::BoatState &msg) {\n    std::unique_lock<std::mutex> l(boat_state_mutex_);\n    *boat_state_ = msg;\n    double vx = boat_state_->vel().x();\n    double vy = boat_state_->vel().y();\n    yaw_ = boat_state_->euler().yaw();\n    omega_ = boat_state_->omega().z();\n   // double heel = boat_state_->euler().roll();\n    thetac_ = -util::norm_angle(std::atan2(vy, vx) - yaw_);\n    thetac_ = 0.0;\n    vc_ = std::sqrt(vx * vx + vy * vy);\n  });\n  RegisterHandler<msg::Vector3f>(\"wind\", [this](const msg::Vector3f &msg) {\n    double wx = msg.x();\n    double wy = msg.y();\n    thetaw_ = util::norm_angle(std::atan2(-wy, wx));\n    // TODO(james): Account for wind gradient properly, rather than by multiplying\n    // by a hard-coded constant.\n    vw_ = std::sqrt(wy * wy + wx * wx) * 1.6;\n  });\n  RegisterHandler<msg::HeadingCmd>(\"heading_cmd\", [this](const msg::HeadingCmd &msg) {\n    if (msg.has_heading()) {\n      heading_ = msg.heading();\n    }\n  });\n  RegisterHandler<msg::ControllerConstants>(\n      \"control_consts\", [this](const msg::ControllerConstants &msg) {\n    std::unique_lock<std::mutex> l(consts_mutex_);\n    if (msg.has_qf()) {\n      *consts_msg_ = msg;\n      physics_.Qf = msg.qf();\n    }\n  });\n  RegisterHandler<msg::SBUS>(\"sbus_value\", [this](const msg::SBUS &sbus) {\n    std::unique_lock<std::mutex> l(boat_state_mutex_);\n  });\n}\n\n/**\n * Computes the betadot given a particular deltas/deltar, using a method\n * described in section 8.5.4 Adaptive Control of \"Robotics: Modelling, Planning\n * and Control\", in which we presume that the dynamics are linear in some\n * parameters, such that under a given set of conditions the dynamics\n * are described by u = Y * beta, where Y is a (potentially nonlinear) function\n * of the current state.\n * For our purposes, u shall notionally comprise of the forwards (longitudinal)\n * force and the net yaw torque.\n * In order to update our estimate of the current beta, we look at the\n * error in the states that most closely correspond with u (in this case,\n * current velocity and current yaw) and update beta based on a PD-like\n * system, scaling by the current values of Y (so that the parameter\n * that most affect the current error are the most updated).\n * Currently, I assume there is always zero velocity error, as I do not\n * actually *care* much about the velocity. However, ignoring it is not\n * necessarily ideal. TODO(james): Investigate\n */\nControlPhysics::MatrixBeta AdaptiveControl::Adaptor(double deltas,\n                                                    double deltar) const {\n  ControlPhysics::MatrixY Y;\n  physics_.NetForce(thetaw_, vw_, thetac_, vc_, deltas, deltar, /*omega=*/0.0,\n                    nullptr, nullptr, nullptr, nullptr, &Y);\n  // See above; 0s should be accel/velocity errors.\n  Eigen::Vector2d sigma =\n      Eigen::Vector2d(0.0, omega_ref_ - omega_) +\n      Lambda * Eigen::Vector2d(0.0, util::norm_angle(yaw_ref_ - yaw_));\n  ControlPhysics::MatrixBeta betadot = -Kbeta * Y.transpose() * sigma;\n  return betadot;\n}\n\nvoid AdaptiveControl::UpdateYawRef() {\n  // Perform weighted averages\n  yaw_ref_ = util::norm_angle(Kref * util::norm_angle(yaw_ref_ - yaw_) + yaw_);\n  omega_ref_ = Kref * omega_ref_ + (1.0 - Kref) * omega_;\n\n  // Calculate expected velocity\n  double exp_vel = util::Clip(util::norm_angle(heading_ - yaw_ref_),\n                              -Kmax_exp_vel, Kmax_exp_vel);\n  // Calculate expected accel\n  double exp_acc = util::Clip(util::norm_angle(exp_vel - omega_ref_),\n                              -Kmax_exp_acc, Kmax_exp_acc);\n  // Perform integration, nothing fancy:\n  if (Kmax_exp_vel < 0.0) {\n    yaw_ref_ = heading_.load();\n  } else if (Kmax_exp_acc < 0.0) {\n    yaw_ref_ = yaw_ref_ + exp_vel * dt;\n  } else {\n    yaw_ref_ = yaw_ref_ + omega_ref_ * dt + 0.5 * exp_acc * dt * dt;\n    omega_ref_ = omega_ref_ + exp_acc * dt;\n  }\n  yaw_ref_ = util::norm_angle(yaw_ref_);\n}\n\nbool AdaptiveControl::Controller(double *deltas, double *deltar) {\n  CHECK_NOTNULL(deltas);\n  CHECK_NOTNULL(deltar);\n  double taue = consts_msg_->rudder_kp() * util::norm_angle(heading_ - yaw_) -\n                15.0 * omega_;\n  ControlPhysics::Constraint constraint = ControlPhysics::kQuadratic;\n//  constraint = ControlPhysics::kPort;\n//  taue = -100.0;\n  if (!physics_.GlobalMaxForceForTorque(thetaw_, vw_, thetac_, vc_, taue,\n                                        constraint,\n                                        /*nsteps=*/20, deltas, deltar)) {\n    return false;\n  }\n  ControlPhysics::MatrixBeta betadot = Adaptor(*deltas, *deltar);\n  physics_.IncrementBeta(betadot * dt);\n  UpdateYawRef();\n  return true;\n}\n\nvoid AdaptiveControl::Iterate() {\n  std::unique_lock<std::mutex> l(boat_state_mutex_);\n  std::unique_lock<std::mutex> lc(consts_mutex_);\n\n  double deltas, deltar;\n  if (!Controller(&deltas, &deltar)) {\n    deltas = 0.0;\n    deltar = 0.0;\n  }\n  // We can't control sign of deltas ;(\n  deltas = std::abs(deltas);\n\n  double cursail = boat_state_->internal().sail();\n  double sail_err = util::norm_angle(deltas - cursail);\n  sail_msg_->set_voltage(consts_msg_->winch_kp() * sail_err /\n                         std::sqrt(std::abs(sail_err)));\n  sail_msg_->set_pos(deltas);\n\n  rudder_msg_->set_pos(util::Clip(deltar, -0.5, 0.5));\n\n  sail_cmd_.send(sail_msg_);\n  rudder_cmd_.send(rudder_msg_);\n  consts_queue_.send(consts_msg_);\n}\n\n}  // control\n}  // sailbot\n", "meta": {"hexsha": "eb844a7dae155fa3ff430b7a26e0b2431d919b1b", "size": 16478, "ext": "cc", "lang": "C++", "max_stars_repo_path": "control/adaptive.cc", "max_stars_repo_name": "wpisailbot/boat", "max_stars_repo_head_hexsha": "7c053d67422d21af95e350c4c9d31425e5760df8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T19:33:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-29T07:44:52.000Z", "max_issues_repo_path": "control/adaptive.cc", "max_issues_repo_name": "wpisailbot/boat", "max_issues_repo_head_hexsha": "7c053d67422d21af95e350c4c9d31425e5760df8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2017-12-05T01:43:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-01T00:48:11.000Z", "max_forks_repo_path": "control/adaptive.cc", "max_forks_repo_name": "wpisailbot/boat", "max_forks_repo_head_hexsha": "7c053d67422d21af95e350c4c9d31425e5760df8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-02-19T22:40:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-07T11:14:24.000Z", "avg_line_length": 35.8217391304, "max_line_length": 86, "alphanum_fraction": 0.5904842821, "num_tokens": 4997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4399792413028403}}
{"text": "\n// BLAS level 3\n// symmetric matrices, syr2k \n\n#include <stddef.h>\n#include <iostream>\n#include <complex>\n#include <boost/numeric/bindings/blas/level3.hpp>\n#include <boost/numeric/bindings/trans.hpp>\n#include <boost/numeric/bindings/upper.hpp>\n#include <boost/numeric/bindings/lower.hpp>\n#include <boost/numeric/bindings/ublas/symmetric.hpp>\n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace blas = boost::numeric::bindings::blas;\nnamespace bindings = boost::numeric::bindings;\n\nusing std::cout;\nusing std::cin;\nusing std::endl; \n\ntypedef double real_t; \ntypedef std::complex<real_t> cmplx_t; \n\ntypedef ublas::matrix<real_t, ublas::column_major> cm_t;\ntypedef ublas::matrix<real_t, ublas::row_major> rm_t;\ntypedef ublas::symmetric_adaptor<cm_t, ublas::upper> ucsa_t; \ntypedef ublas::symmetric_adaptor<cm_t, ublas::lower> lcsa_t; \ntypedef ublas::symmetric_adaptor<rm_t, ublas::upper> ursa_t; \ntypedef ublas::symmetric_adaptor<rm_t, ublas::lower> lrsa_t; \n\ntypedef ublas::matrix<cmplx_t, ublas::column_major> ccm_t;\ntypedef ublas::matrix<cmplx_t, ublas::row_major> crm_t;\ntypedef ublas::symmetric_adaptor<ccm_t, ublas::upper> cucsa_t; \ntypedef ublas::symmetric_adaptor<ccm_t, ublas::lower> clcsa_t; \ntypedef ublas::symmetric_adaptor<crm_t, ublas::upper> cursa_t; \ntypedef ublas::symmetric_adaptor<crm_t, ublas::lower> clrsa_t; \n\nint main (int argc, char **argv) {\n  int n = 0, k = 0;\n  if (argc > 1) {\n    n = atoi(argv [1]);\n  }\n  if (argc > 2) {\n    k = atoi(argv [2]);\n  }\n\n  if (n <= 0) {\n    cout << \"n -> \";\n    cin >> n;\n  }\n  if (k <= 0) {\n    cout << \"k -> \";\n    cin >> k;\n  }\n\n  cm_t ac (n, k); \n  rm_t ar (n, k); \n  init_m (ac, rws1()); \n  init_m (ar, rws1());\n  print_m (ac, \"ac\"); \n  cout << endl; \n  print_m (ar, \"ar\"); \n  cout << endl << endl;\n\n  cm_t bc (n, k); \n  rm_t br (n, k); \n  init_m (bc, const_val<real_t> (1)); \n  init_m (br, const_val<real_t> (1));\n  print_m (bc, \"bc\"); \n  cout << endl; \n  print_m (br, \"br\"); \n  cout << endl << endl;\n\n  cm_t cmu (n, n); \n  cm_t cml (n, n); \n  rm_t rmu (n, n); \n  rm_t rml (n, n); \n  ucsa_t ucsa (cmu); \n  lcsa_t lcsa (cml); \n  ursa_t ursa (rmu); \n  lrsa_t lrsa (rml); \n\n  blas::syr2k (1.0, ac, bc, 0.0, ucsa); \n  blas::syr2k (1.0, ac, bc, 0.0, lcsa); \n  blas::syr2k (1.0, ar, br, 0.0, ursa); \n  blas::syr2k (1.0, ar, br, 0.0, lrsa); \n\n  print_m (ucsa, \"ucsa\");\n  cout << endl; \n  print_m (lcsa, \"lcsa\");\n  cout << endl; \n  print_m (ursa, \"ursa\");\n  cout << endl; \n  print_m (lrsa, \"lrsa\");\n  cout << endl << endl; \n\n  // part 2\n\n  cm_t act (k, n); \n  rm_t art (k, n); \n  init_m (act, cls1()); \n  init_m (art, cls1());\n  print_m (act, \"act\"); \n  cout << endl; \n  print_m (art, \"art\"); \n  cout << endl << endl;\n\n  cm_t bct (k, n); \n  rm_t brt (k, n); \n  init_m (bct, rws1()); \n  init_m (brt, rws1());\n  print_m (bct, \"bct\"); \n  cout << endl; \n  print_m (brt, \"brt\"); \n  cout << endl << endl;\n\n  init_m (cmu, const_val<real_t> (0));\n  init_m (cml, const_val<real_t> (0));\n  init_m (rmu, const_val<real_t> (0));\n  init_m (rml, const_val<real_t> (0));\n\n  blas::syr2k (1.0, bindings::trans(act), bct, 0.0, bindings::upper(cmu)); \n  blas::syr2k (1.0, bindings::trans(act), bct, 0.0, bindings::lower(cml)); \n  blas::syr2k (1.0, bindings::trans(art), brt, 0.0, bindings::upper(rmu)); \n  blas::syr2k (1.0, bindings::trans(art), brt, 0.0, bindings::lower(rml)); \n\n  print_m (cmu, \"cmu\");\n  cout << endl; \n  print_m (cml, \"cml\");\n  cout << endl; \n  print_m (rmu, \"rmu\");\n  cout << endl; \n  print_m (rml, \"rml\");\n  cout << endl; \n\n  // complex \n\n  const int n1 = 3;\n  const int k1 = 2; \n\n  ccm_t cac (n1, k1); \n  crm_t car (n1, k1); \n  cac(0,0) = car(0,0) = cmplx_t (1., 1.);\n  cac(1,0) = car(1,0) = cmplx_t (2., 1.);\n  cac(2,0) = car(2,0) = cmplx_t (3., 1.);\n  cac(0,1) = car(0,1) = cmplx_t (1., 1.);\n  cac(1,1) = car(1,1) = cmplx_t (2., 1.);\n  cac(2,1) = car(2,1) = cmplx_t (3., 1.);\n  print_m (cac, \"cac\"); \n  cout << endl; \n  print_m (car, \"car\"); \n  cout << endl << endl;\n\n  ccm_t cbc (n1, k1); \n  crm_t cbr (n1, k1); \n  cbc(0,0) = cbr(0,0) = cmplx_t (0., -1.);\n  cbc(1,0) = cbr(1,0) = cmplx_t (0., -1.);\n  cbc(2,0) = cbr(2,0) = cmplx_t (0., -1.);\n  cbc(0,1) = cbr(0,1) = cmplx_t (0., -1.);\n  cbc(1,1) = cbr(1,1) = cmplx_t (0., -1.);\n  cbc(2,1) = cbr(2,1) = cmplx_t (0., -1.);\n  print_m (cbc, \"cbc\"); \n  cout << endl; \n  print_m (cbr, \"cbr\"); \n  cout << endl << endl;\n\n  ccm_t ccmu (n1, n1); \n  ccm_t ccml (n1, n1); \n  crm_t crmu (n1, n1); \n  crm_t crml (n1, n1); \n  cucsa_t cucsa (ccmu); \n  clcsa_t clcsa (ccml); \n  cursa_t cursa (crmu); \n  clrsa_t clrsa (crml); \n\n  blas::syr2k ( 1.0, cac, cbc, 0.0, cucsa); \n  blas::syr2k (cmplx_t(1,0), cac, cbc, cmplx_t(0,0), clcsa); \n  blas::syr2k (cmplx_t(1,0), car, cbr, cmplx_t(0,0), cursa); \n  blas::syr2k (1.0, car, cbr, 0.0, clrsa); \n\n  print_m (cucsa, \"cucsa\");\n  cout << endl; \n  print_m (clcsa, \"clcsa\");\n  cout << endl; \n  print_m (cursa, \"cursa\");\n  cout << endl; \n  print_m (clrsa, \"clrsa\");\n  cout << endl << endl; \n\n}\n\n", "meta": {"hexsha": "06a5881cf61c37405852850e8008c0e95526bc2d", "size": 4947, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_symm3s2k.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_symm3s2k.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/atlas/ublas_symm3s2k.cc", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 25.5, "max_line_length": 75, "alphanum_fraction": 0.5843945826, "num_tokens": 2120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.4399707501739205}}
{"text": "#ifndef _jsc_util_interval_hpp_included_\n#define _jsc_util_interval_hpp_included_\n\n#include <boost/config.hpp>\n\n#include <math.h>\n\n#include <iostream>\n#include <map>\n#include <set>\n#include <sstream>\n#include <vector>\n\n#include <boost/lambda/bind.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/tokenizer.hpp>\n\n#include <jsc/util/log.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::lambda;\n\nnamespace jsc\n{\nnamespace util\n{\n\n//! A function which checks whether two intervals overlap.\n/*!\n * \\return whether [a, b) and [c, d) overlap.\n */\ntemplate<class T, class Compare>\nbool interval_overlap(T const & a, T const & b, T const & c, T const & d, Compare comp = Compare())\n{\n\treturn (!(comp(b, c) || comp(d, a)));\n}\n\n//! A function which computes the overlapping length of two intervals.\n/*!\n * \\return the overlapping length of [a, b) and [c, d).\n */\ntemplate<class T, class Compare>\ndouble compute_interval_overlap(T const & a, T const & b, T const & c, T const & d, Compare comp = Compare())\n{\n\tdouble length = 0;\n\tif (!(comp(b, c) || comp(d, a)))\n\t{\n\t\tif (comp(a, c))\n\t\t{\n\t\t\tif (comp(b, d))\n\t\t\t{\n\t\t\t\tlength = b - c;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlength = d - c;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (comp(b, d))\n\t\t\t{\n\t\t\t\tlength = b - a;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlength = d - a;\n\t\t\t}\n\t\t}\n\t}\n\treturn length;\n}\n\n//! A class representing a list of intervals.\n/*!\n * The intervals in the list are sorted according to their start positions and do not overlap with each other.\n */\ntemplate <class T, class Compare = less<T> >\nclass interval_list\n{\nprivate:\n\t//! The comparator.\n\tCompare comp;\n\t//! The internal representation of the list of intervals: [starts[0], end[0]), [starts[1], end[1]), ...\n\tvector<T> starts;\n\t//! The internal representation of the list of intervals: [starts[0], end[0]), [starts[1], end[1]), ...\n\tvector<T> ends;\n\npublic:\n\t//! A constructor.\n\tinterval_list()\n\t\t: comp(Compare())\n\t{\n\t}\n\n\t//! A constructor taking an explicit comparator.\n\texplicit\n\tinterval_list(Compare const & c)\n\t\t: comp(c)\n\t{\n\t}\n\n\t//! Copy constructor.\n\tinterval_list(interval_list<T, Compare> const & il)\n\t\t: comp(il.comp), starts(il.starts), ends(il.ends)\n\t{\n\t}\n\n\t//! Gets the number of intervals.\n\tunsigned long get_num_intervals() const\n\t{\n\t\treturn starts.size();\n\t}\n\n\t//! Gets the starts vector.\n\tvector<T> const & get_starts() const\n\t{\n\t\treturn starts;\n\t}\n\n\t//! Gets the ends vector.\n\tvector<T> const & get_ends() const\n\t{\n\t\treturn ends;\n\t}\n\n\t//! Counts the number of intervals in the list that overlap with the given interval.\n\t/*!\n\t * \\sa count_overlap_il().\n\t */\n\tlong count_overlap(T const & start, T const & end) const\n\t{\n\t\tif (!comp(start, end))\t/* [start, end) == nil */\n\t\t{\n\t\t\treturn 0;\t// always return 0 in this case\n\t\t}\n\n\t\ttypename vector<T>::const_iterator s_starts_itr, e_ends_itr;\n\t\ts_starts_itr = lower_bound(starts.begin(), starts.end(), start);\n\t\te_ends_itr = lower_bound(ends.begin(), ends.end(), end);\n\n\t\tlong s_starts_idx, e_ends_idx;\n\t\ts_starts_idx = distance(starts.begin(), s_starts_itr);\n\t\te_ends_idx = distance(ends.begin(), e_ends_itr);\n\t\tlong i;\n\t\tlong total_count = 0;\n\t\tfor (i = max((long)0, s_starts_idx - 1); i <= min((long)starts.size() - 1, e_ends_idx); ++i)\n\t\t{\n\t\t\tif (interval_overlap<T, Compare>(starts[i], ends[i], start, end, comp))\n\t\t\t{\n\t\t\t\ttotal_count++;\n\t\t\t}\n\t\t}\n\n\t\treturn total_count;\n\t}\n\n\t//! Counts the number of intervals in the list that overlap with the given interval list.\n\t/*!\n\t * \\sa count_overlap().\n\t */\n\tlong count_overlap_il(interval_list<T, Compare> const & il) const\n\t{\n\t\tlong total_count = 0;\n\t\tint n = starts.size();\n\n\t\tfor (int i = 0; i < n; ++i)\n\t\t{\n\t\t\tif (il.check_overlap(starts[i], ends[i]))\n\t\t\t{\n\t\t\t\ttotal_count++;\n\t\t\t}\n\t\t}\n\t\treturn total_count;\n\t}\n\n\t//! Checks whether the interval list overlaps with the interval [start, end).\n\tbool check_overlap(T const & start, T const & end) const\n\t{\n\t\tif (!comp(start, end))\t/* [start, end) == nil */\n\t\t{\n\t\t\treturn false;\t// always return false in this case\n\t\t}\n\n\t\ttypename vector<T>::const_iterator s_starts_itr, e_ends_itr;\n\t\ts_starts_itr = lower_bound(starts.begin(), starts.end(), start);\n\t\te_ends_itr = lower_bound(ends.begin(), ends.end(), end);\n\n\t\tlong s_starts_idx, e_ends_idx;\n\t\ts_starts_idx = distance(starts.begin(), s_starts_itr);\n\t\te_ends_idx = distance(ends.begin(), e_ends_itr);\n\t\tlong i;\n\t\tfor (i = max((long)0, s_starts_idx - 1); i <= min((long)starts.size() - 1, e_ends_idx); ++i)\n\t\t{\n\t\t\tif (interval_overlap<T, Compare>(starts[i], ends[i], start, end, comp))\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tstatic interval_list<T> get_interval_overlap(T const & a, T const & b, T const & c, T const & d, Compare comp = Compare())\n\t{\n\t\tinterval_list<T> il;\n\t\tif (!(comp(b, c) || comp(d, a)))\n\t\t{\n\t\t\tif (comp(a, c))\n\t\t\t{\n\t\t\t\tif (comp(b, d))\n\t\t\t\t{\n\t\t\t\t\til.add_interval(c, b);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\til.add_interval(c, d);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (comp(b, d))\n\t\t\t\t{\n\t\t\t\t\til.add_interval(a, b);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\til.add_interval(a, d);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn il;\n\t}\n\n\t//! Gets the overlap of the interval list with the interval [start, end).\n\tinterval_list<T> get_overlap_il(T const & start, T const & end) const\n\t{\n\t\tinterval_list<T> il;\n\t\tif (!comp(start, end))\t/* [start, end) == nil */\n\t\t{\n\t\t\treturn il;\t// always return 0 in this case\n\t\t}\n\n\t\ttypename vector<T>::const_iterator s_starts_itr, e_ends_itr;\n\t\ts_starts_itr = lower_bound(starts.begin(), starts.end(), start);\n\t\te_ends_itr = lower_bound(ends.begin(), ends.end(), end);\n\n\t\tlong s_starts_idx, e_ends_idx;\n\t\ts_starts_idx = distance(starts.begin(), s_starts_itr);\n\t\te_ends_idx = distance(ends.begin(), e_ends_itr);\n\t\tlong i;\n\t\tfor (i = max((long)0, s_starts_idx - 1); i <= min((long)starts.size() - 1, e_ends_idx); ++i)\n\t\t{\n\t\t\til.add_interval_list(\n\t\t\t\t\tget_interval_overlap(starts[i], ends[i], start, end, comp));\n\t\t}\n\n\t\treturn il;\n\t}\n\n\t//! Get the overlap of the interval list with another interval list.\n\tinterval_list<T> get_overlap_il(interval_list<T, Compare> const & il) const\n\t{\n\t\tinterval_list<T> rst_il;\n\t\tint n = il.starts.size();\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\trst_il.add_interval_list(get_overlap_il(il.starts[i], il.ends[i]));\n\t\t}\n\t\treturn rst_il;\n\t}\n\n\t//! Computes the overlap of the interval list with the interval [start, end).\n\t/*!\n\t * \\sa compute_overlap_il().\n\t */\n\tdouble compute_overlap(T const & start, T const & end) const\n\t{\n\t\tif (!comp(start, end))\t/* [start, end) == nil */\n\t\t{\n\t\t\treturn 0;\t// always return 0 in this case\n\t\t}\n\n\t\ttypename vector<T>::const_iterator s_starts_itr, e_ends_itr;\n\t\ts_starts_itr = lower_bound(starts.begin(), starts.end(), start);\n\t\te_ends_itr = lower_bound(ends.begin(), ends.end(), end);\n\n\t\tlong s_starts_idx, e_ends_idx;\n\t\ts_starts_idx = distance(starts.begin(), s_starts_itr);\n\t\te_ends_idx = distance(ends.begin(), e_ends_itr);\n\t\tlong i;\n\t\tdouble total_length = 0;\n\t\tfor (i = max((long)0, s_starts_idx - 1); i <= min((long)starts.size() - 1, e_ends_idx); ++i)\n\t\t{\n\t\t\ttotal_length += compute_interval_overlap<T, Compare>(starts[i], ends[i], start, end, comp);\n\t\t}\n\n\t\treturn total_length;\n\t}\n\n\tbool check_single_overlap(T const & start, T const & end, double const & threshold) const\n\t{\n\t\tbool found = false;\n\t\tif (!comp(start, end))\t/* [start, end) == nil */\n\t\t{\n\t\t\treturn false;\t// always return false in this case\n\t\t}\n\n\t\ttypename vector<T>::const_iterator s_starts_itr, e_ends_itr;\n\t\ts_starts_itr = lower_bound(starts.begin(), starts.end(), start);\n\t\te_ends_itr = lower_bound(ends.begin(), ends.end(), end);\n\n\t\tlong s_starts_idx, e_ends_idx;\n\t\ts_starts_idx = distance(starts.begin(), s_starts_itr);\n\t\te_ends_idx = distance(ends.begin(), e_ends_itr);\n\t\tlong i;\n\t\tfor (i = max((long)0, s_starts_idx - 1); i <= min((long)starts.size() - 1, e_ends_idx); ++i)\n\t\t{\n\t\t\tif (threshold <= compute_interval_overlap<T, Compare>(starts[i], ends[i], start, end, comp)) {\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn found;\n\t}\n\n\n\t//! Computes the overlap of the interval list with another interval list.\n\t/*!\n\t * \\sa compute_overlap().\n\t */\n\tdouble compute_overlap_il(interval_list<T, Compare> const & il) const\n\t{\n\t\tdouble total_length = 0;\n\t\tint n = il.starts.size();\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\ttotal_length += compute_overlap(il.starts[i], il.ends[i]);\n\t\t}\n\t\treturn total_length;\n\t}\n\n\t//! Computes the total length of the intervals in this interval list.\n\tdouble compute_total_length() const\n\t{\n\t\tdouble total_length = 0;\n\t\tint n = starts.size();\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\ttotal_length += ends[i] - starts[i];\n\t\t}\n\t\treturn total_length;\n\t}\n\n\t//! Finds in the interval list the index of the interval which contains the given interval [start, end).\n\t/*!\n\t * \\return the index of the interval containing [start, end); otherwise starts.size().\n\t * \\sa contains_interval(T const & start, T const & end)\n\t */\n\tlong idx_containing_interval(T const & start, T const & end) const\n\t{\n\t\tif (!comp(start, end))\t/* [start, end) == nil */\n\t\t{\n\t\t\treturn 0;\t// always return 0 in this case\n\t\t}\n\n\t\ttypename vector<T>::const_iterator s_starts_itr;\n\t\ts_starts_itr = lower_bound(starts.begin(), starts.end(), start);\n\n\t\tlong s_starts_idx;\n\t\ts_starts_idx = distance(starts.begin(), s_starts_itr);\n\t\tif (s_starts_idx >= 0 && s_starts_idx < (long)starts.size() &&\n\t\t\t\t!comp(start, starts[s_starts_idx]) &&\n\t\t\t\t!comp(ends[s_starts_idx], end))\n\t\t{\n\t\t\treturn s_starts_idx;\n\t\t}\n\t\tif (s_starts_idx - 1 >= 0 && s_starts_idx - 1 < (long)starts.size() &&\n\t\t\t\t!comp(start, starts[s_starts_idx - 1]) &&\n\t\t\t\t!comp(ends[s_starts_idx - 1], end))\n\t\t{\n\t\t\treturn s_starts_idx - 1;\n\t\t}\n\n\t\treturn starts.size();\n\t}\n\n\t//! Checks whether the interval list contains [start, end).\n\t/*!\n\t * \\sa idx_containing_interval()\n\t */\n\tbool contains_interval(T const & start, T const & end) const\n\t{\n\t\tif (!comp(start, end))\t/* [start, end) == nil */\n\t\t{\n\t\t\treturn true;\n\t\t}\n\n\t\ttypename vector<T>::const_iterator s_starts_itr;\n\t\ts_starts_itr = lower_bound(starts.begin(), starts.end(), start);\n\n\t\tlong s_starts_idx;\n\t\ts_starts_idx = distance(starts.begin(), s_starts_itr);\n\t\tif (s_starts_idx >= 0 && s_starts_idx < (long)starts.size() &&\n\t\t\t\t!comp(start, starts[s_starts_idx]) &&\n\t\t\t\t!comp(ends[s_starts_idx], end))\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\tif (s_starts_idx - 1 >= 0 && s_starts_idx - 1 < (long)starts.size() &&\n\t\t\t\t!comp(start, starts[s_starts_idx - 1]) &&\n\t\t\t\t!comp(ends[s_starts_idx - 1], end))\n\t\t{\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t//! Fill in gaps if their length is less than the given threshold\n\tvoid fill_in_gaps(double const & threshold)\n\t{\n\t\tint n = starts.size();\n\t\tif (n == 0)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tvector<T> new_starts, new_ends;\n\t\tT last_end;\n\t\tnew_starts.push_back(starts[0]);\n\t\tlast_end = ends[0];\n\t\tfor (int i = 1; i < n; ++i)\n\t\t{\n\t\t\tif (starts[i] - last_end < threshold)\n\t\t\t{\n\t\t\t\t// fill in the gap\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// copy the last end and current start\n\t\t\t\tnew_ends.push_back(last_end);\n\t\t\t\tnew_starts.push_back(starts[i]);\n\t\t\t}\n\t\t\t// update last end\n\t\t\tlast_end = ends[i];\n\t\t}\n\t\tnew_ends.push_back(last_end);\n\t\tstarts = new_starts;\n\t\tends = new_ends;\n\t}\n\n\t//! Add [start, end) to the interval list.\n\t/*!\n\t * Overlapping intervals in the list will be merged.\n\t * \\sa add_starts_sizes() and add_interval_list()\n\t */\n\tinterval_list<T> & add_interval(T const & start, T const & end)\n\t{\n\t\tif (!comp(start, end))\t/* [start, end) == nil */\n\t\t{\n\t\t\treturn *this;\n\t\t}\n\n\t\ttypename vector<T>::iterator s_starts_itr, s_ends_itr, e_starts_itr, e_ends_itr;\n\t\ts_starts_itr = lower_bound(starts.begin(), starts.end(), start);\n\t\ts_ends_itr = lower_bound(ends.begin(), ends.end(), start);\n\t\te_starts_itr = lower_bound(starts.begin(), starts.end(), end);\n\t\te_ends_itr = lower_bound(ends.begin(), ends.end(), end);\n\n\t\tint s_starts_idx, s_ends_idx, e_starts_idx, e_ends_idx;\n\t\ts_starts_idx = distance(starts.begin(), s_starts_itr);\n\t\ts_ends_idx = distance(ends.begin(), s_ends_itr);\n\t\te_starts_idx = distance(starts.begin(), e_starts_itr);\n\t\te_ends_idx = distance(ends.begin(), e_ends_itr);\n\t\tbool s_on_interval = (s_starts_idx - s_ends_idx == 1);\n\t\tbool e_on_interval = (e_starts_idx - e_ends_idx == 1);\n\n\t\ttypename vector<T>::iterator starts_itr = starts.erase(s_starts_itr, e_starts_itr);\n\t\ttypename vector<T>::iterator ends_itr = ends.erase(s_ends_itr, e_ends_itr);\n\t\tif (s_on_interval && e_on_interval)\n\t\t{\n\t\t}\n\t\telse if (!s_on_interval && !e_on_interval)\n\t\t{\n\t\t\tstarts.insert(starts_itr, start);\n\t\t\tends.insert(ends_itr, end);\n\t\t}\n\t\telse if (s_on_interval && !e_on_interval)\n\t\t{\n\t\t\tends.insert(ends_itr, end);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstarts.insert(starts_itr, start);\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\t//! Add another interval list to the interval list.\n\t/*!\n\t * \\sa add_starts_sizes() and add_interval()\n\t */\n\tvoid add_interval_list(interval_list<T, Compare> const & il)\n\t{\n\t\tint n = il.starts.size();\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tadd_interval(il.starts[i], il.ends[i]);\n\t\t}\n\t}\n\n\t//! Add another interval list to the interval list.\n\t/*!\n\t * \\param starts the starts vector of the interval list to be added.\n\t * \\param sizes  the sizes vector of the interval list to be added.\n\t * \\sa add_interval_list() and add_interval()\n\t */\n\tvoid add_starts_sizes(vector<T> const & starts, vector<T> const & sizes)\n\t{\n\t\tint n = starts.size();\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tadd_interval(starts[i], starts[i] + sizes[i]);\n\t\t}\n\t}\n\n\t//! Add another interval list to the interval list.\n\t/*!\n\t * \\param starts the starts vector of the interval list to be added.\n\t * \\param ends the ends vector of the interval list to be added.\n\t * \\sa add_interval_list() and add_interval()\n\t */\n\tvoid add_starts_ends(vector<T> const & starts, vector<T> const & ends)\n\t{\n\t\tint n = starts.size();\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tadd_interval(starts[i], ends[i]);\n\t\t}\n\t}\n\n\t//! Checks whether the total coverage of the interval list overlaps with that of another interval list.\n\t/*!\n\t * coverage = [min(starts), (max(ends))\n\t */\n\tbool coverage_overlap(interval_list<T, Compare> const & il2)\n\t{\n\t\tint n1 = starts.size();\n\t\tint n2 = il2.starts.size();\n\t\tif (n1 == 0 || n2 == 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\treturn interval_overlap<T, Compare>(starts[0], ends[n1 - 1], il2.starts[0], il2.ends[n2 - 1], comp);\n\t}\n\n\tT find_min_uncovered(T start_from) const {\n\t\tif (get_num_intervals() == 0) {\n\t\t\treturn start_from;\n\t\t} else {\n\t\t\ttypename vector<T>::const_iterator s_starts_itr;\n\t\t\ts_starts_itr = lower_bound(starts.begin(), starts.end(), start_from);\n\n\t\t\tlong s_starts_idx;\n\t\t\ts_starts_idx = distance(starts.begin(), s_starts_itr);\n\t\t\tlong i;\n\t\t\tfor (i = max((long)0, (long)s_starts_idx - 1);\n\t\t\t\t\ti < (long)get_num_intervals(); ++i)\n\t\t\t{\n\t\t\t\tif (starts[i] > start_from) {\n\t\t\t\t\treturn start_from;\n\t\t\t\t} else if (ends[i] > start_from) {\n\t\t\t\t\tstart_from = ends[i];\n\t\t\t\t} else {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn start_from;\n\t\t}\n\t}\n};\n\n//! Default printing of an interval_list.\ntemplate<class T, class Compare>\nostream & operator << (ostream& os, interval_list<T, Compare> const & il)\n{\n\tint n = il.get_starts().size();\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tos << \"[\" << il.get_starts()[i] << \",\" << il.get_ends()[i] << \"), \";\n\t}\n\treturn os;\n}\n\n\n} /* end of util */\n\n} /* end of jsc */\n\n#endif\n", "meta": {"hexsha": "2e3c1a66c41b2ae82cb41706f3604a63027c9f6f", "size": 15169, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "jdu_source_collection/jsc/util/interval_list.hpp", "max_stars_repo_name": "gersteinlab/LESSeq", "max_stars_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-06-19T21:14:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-15T03:04:41.000Z", "max_issues_repo_path": "jdu_source_collection/jsc/util/interval_list.hpp", "max_issues_repo_name": "gersteinlab/LESSeq", "max_issues_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-12T21:17:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-20T13:50:38.000Z", "max_forks_repo_path": "jdu_source_collection/jsc/util/interval_list.hpp", "max_forks_repo_name": "gersteinlab/LESSeq", "max_forks_repo_head_hexsha": "bfc0a9aae081682a176e26d9804b980999595f16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9901153213, "max_line_length": 123, "alphanum_fraction": 0.6443404311, "num_tokens": 4452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.43997074637872935}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>, Olga Diamanti <olga.diam@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"comb_cross_field.h\"\n\n#include <vector>\n#include <deque>\n#include <Eigen/Geometry>\n#include \"per_face_normals.h\"\n#include \"is_border_vertex.h\"\n#include \"rotation_matrix_from_directions.h\"\n\n#include \"triangle_triangle_adjacency.h\"\n\nnamespace igl {\n  template <typename DerivedV, typename DerivedF>\n  class Comb\n  {\n  public:\n\n    const Eigen::PlainObjectBase<DerivedV> &V;\n    const Eigen::PlainObjectBase<DerivedF> &F;\n    const Eigen::PlainObjectBase<DerivedV> &PD1;\n    const Eigen::PlainObjectBase<DerivedV> &PD2;\n    Eigen::PlainObjectBase<DerivedV> N;\n\n  private:\n    // internal\n    Eigen::PlainObjectBase<DerivedF> TT;\n    Eigen::PlainObjectBase<DerivedF> TTi;\n\n\n  private:\n\n\n    static inline double Sign(double a){return (double)((a>0)?+1:-1);}\n\n\n  private:\n\n    // returns the 90 deg rotation of a (around n) most similar to target b\n    /// a and b should be in the same plane orthogonal to N\n    static inline Eigen::Matrix<typename DerivedV::Scalar, 3, 1> K_PI_new(const Eigen::Matrix<typename DerivedV::Scalar, 3, 1>& a,\n                                                                   const Eigen::Matrix<typename DerivedV::Scalar, 3, 1>& b,\n                                                                   const Eigen::Matrix<typename DerivedV::Scalar, 3, 1>& n)\n    {\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 1> c = (a.cross(n)).normalized();\n      typename DerivedV::Scalar scorea = a.dot(b);\n      typename DerivedV::Scalar scorec = c.dot(b);\n      if (fabs(scorea)>=fabs(scorec))\n        return a*Sign(scorea);\n      else\n        return c*Sign(scorec);\n    }\n\n\n\n  public:\n    inline Comb(const Eigen::PlainObjectBase<DerivedV> &_V,\n         const Eigen::PlainObjectBase<DerivedF> &_F,\n         const Eigen::PlainObjectBase<DerivedV> &_PD1,\n         const Eigen::PlainObjectBase<DerivedV> &_PD2\n         ):\n    V(_V),\n    F(_F),\n    PD1(_PD1),\n    PD2(_PD2)\n    {\n      igl::per_face_normals(V,F,N);\n      igl::triangle_triangle_adjacency(V,F,TT,TTi);\n    }\n    inline void comb(Eigen::PlainObjectBase<DerivedV> &PD1out,\n              Eigen::PlainObjectBase<DerivedV> &PD2out)\n    {\n//      PD1out = PD1;\n//      PD2out = PD2;\n      PD1out.setZero(F.rows(),3);PD1out<<PD1;\n      PD2out.setZero(F.rows(),3);PD2out<<PD2;\n\n      Eigen::VectorXi mark = Eigen::VectorXi::Constant(F.rows(),false);\n\n      std::deque<int> d;\n\n      d.push_back(0);\n      mark(0) = true;\n\n      while (!d.empty())\n      {\n        int f0 = d.at(0);\n        d.pop_front();\n        for (int k=0; k<3; k++)\n        {\n          int f1 = TT(f0,k);\n          if (f1==-1) continue;\n          if (mark(f1)) continue;\n\n          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> dir0    = PD1out.row(f0);\n          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> dir1    = PD1out.row(f1);\n          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> n0    = N.row(f0);\n          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> n1    = N.row(f1);\n\n\n          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> dir0Rot = igl::rotation_matrix_from_directions(n0, n1)*dir0;\n          dir0Rot.normalize();\n          Eigen::Matrix<typename DerivedV::Scalar, 3, 1> targD   = K_PI_new(dir1,dir0Rot,n1);\n\n          PD1out.row(f1)  = targD;\n          PD2out.row(f1)  = n1.cross(targD).normalized();\n\n          mark(f1) = true;\n          d.push_back(f1);\n\n        }\n      }\n\n      // everything should be marked\n      for (int i=0; i<F.rows(); i++)\n      {\n        assert(mark(i));\n      }\n    }\n\n\n\n  };\n}\ntemplate <typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::comb_cross_field(const Eigen::PlainObjectBase<DerivedV> &V,\n                                      const Eigen::PlainObjectBase<DerivedF> &F,\n                                      const Eigen::PlainObjectBase<DerivedV> &PD1,\n                                      const Eigen::PlainObjectBase<DerivedV> &PD2,\n                                      Eigen::PlainObjectBase<DerivedV> &PD1out,\n                                      Eigen::PlainObjectBase<DerivedV> &PD2out)\n{\n  igl::Comb<DerivedV, DerivedF> cmb(V, F, PD1, PD2);\n  cmb.comb(PD1out, PD2out);\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template specialization\ntemplate void igl::comb_cross_field<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::comb_cross_field<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\n#endif\n", "meta": {"hexsha": "3e9f942402a86a8f51d286056ef4b040582a212d", "size": 5644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/include/igl/comb_cross_field.cpp", "max_stars_repo_name": "FabianRepository/SinusProject", "max_stars_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/include/igl/comb_cross_field.cpp", "max_issues_repo_name": "FabianRepository/SinusProject", "max_issues_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/include/igl/comb_cross_field.cpp", "max_forks_repo_name": "FabianRepository/SinusProject", "max_forks_repo_head_hexsha": "48d68902ccd83f08c4d208ba8e0739a8a1252338", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8791946309, "max_line_length": 547, "alphanum_fraction": 0.6001063076, "num_tokens": 1699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4399661346703256}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <boost/random.hpp>\n#include <boost/lexical_cast.hpp>\n#include <alps/accumulators.hpp>\n\nint main(int argc, char* argv[]){\n  alps::accumulators::accumulator_set measurements;\n  measurements << alps::accumulators::LogBinningAccumulator<double>(\"log\");\n  measurements << alps::accumulators::LogBinningAccumulator<double>(\"ran\");\n  boost::mt19937 eng(49135);\n  boost::variate_generator<boost::mt19937&, boost::uniform_real<>> random_uniform(eng, boost::uniform_real<>());\n  std::vector<double> log_data, ran_data;\n  int N = 500;\n  if(argc == 2){\n    N = boost::lexical_cast<double>(argv[1]);\n  }else{\n    std::cerr << \"usege: ./main number, N = 500 (Default)\" << std::endl;\n  }\n  double x = 0;\n  for(int i = 0; i < N; ++i){\n    double next = x + random_uniform() - 0.5;\n    if(abs(x) < abs(next)){\n      double probability = exp((x*x - next*next) * 0.125);\n      double dice = random_uniform();\n      if(probability > dice){\n\tx = next;\n      }\n    }else{\n      x = next;\n    }\n    measurements[\"log\"] << x;\n    double ran_cash = random_uniform();\n    measurements[\"ran\"] << ran_cash;\n\n    log_data.push_back(x);\n    ran_data.push_back(ran_cash);\n  }\n  alps::accumulators::result_set result(measurements);\n  std::cout << \"log \" << std::setprecision(20) << result[\"log\"] << std::endl;\n  std::cout << \"ran \" <<  result[\"ran\"] << std::endl;\n  auto log = result[\"log\"];\n  auto ran = result[\"ran\"];\n\n  double vari_log = 0.0;\n  double mean_log = 0.0;\n  double vari_ran = 0.0;\n  double mean_ran = 0.0;\n  for(int i = 0; i < ran_data.size(); ++i){\n    mean_log += log_data[i];\n    mean_ran += ran_data[i];\n  }\n  mean_log /= log_data.size();\n  mean_ran /= ran_data.size();\n  for(int i = 0; i < ran_data.size(); i = i+pow(2,floor(log2(N))-7)){\n    double bin_log = 0.0;\n    double bin_ran = 0.0;\n    for(int j = 0; j < pow(2,floor(log2(N))-7); ++j){\n      bin_log += log_data[i+j];\n      bin_ran += ran_data[i+j];\n    }\n    bin_log /= pow(2,floor(log2(N))-7);\n    bin_ran /= pow(2,floor(log2(N))-7);\n\n    vari_log += (bin_log - mean_log)*(bin_log - mean_log);\n    vari_ran += (bin_ran - mean_ran)*(bin_ran - mean_ran);\n  }\n  double vari_naive = 0.0;\n  for(int i = 0; i < ran_data.size(); ++i){\n    vari_naive += (log_data[i] - mean_log)*(log_data[i]-mean_log);\n  }\n  vari_naive /= log_data.size()*(log_data.size()-1);\n  \n  vari_log /= log_data.size()/(pow(2,floor(log2(N))-7))*(log_data.size()/(pow(2,floor(log2(N))-7)) - 1);\n  vari_ran /= log_data.size()/(pow(2,floor(log2(N))-7))*(log_data.size()/(pow(2,floor(log2(N))-7)) - 1);\n  std::cout << \"log error: \" << sqrt(vari_log) << std::setprecision(20) << \", log tau: \" << (vari_log/vari_naive - 1.0)*0.5 << std::endl;\n  std::cout << \"ran error: \" << sqrt(vari_ran) << std::endl;\n  std::cout << \"naive_error: \" << sqrt(vari_naive) << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "6cf3b2112d35abf10bdbbcd42bbdc1e5b316991a", "size": 2858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "suzumoto/binning-analysis", "max_stars_repo_head_hexsha": "b4ccd49821a692d23f30a69f0609a1fccbc14790", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "suzumoto/binning-analysis", "max_issues_repo_head_hexsha": "b4ccd49821a692d23f30a69f0609a1fccbc14790", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "suzumoto/binning-analysis", "max_forks_repo_head_hexsha": "b4ccd49821a692d23f30a69f0609a1fccbc14790", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8536585366, "max_line_length": 137, "alphanum_fraction": 0.6067179846, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.43996612883023173}}
{"text": "// (C) 2014 Arek Olek\n\n#pragma once\n\n#include <algorithm>\n#include <functional>\n#include <utility>\n#include <vector>\n\n#include <boost/iterator/function_input_iterator.hpp>\n#include <boost/function_output_iterator.hpp>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n#include <boost/graph/planar_canonical_ordering.hpp>\n#include <boost/graph/chrobak_payne_drawing.hpp>\n#include <boost/graph/make_connected.hpp>\n#include <boost/graph/make_biconnected_planar.hpp>\n#include <boost/graph/make_maximal_planar.hpp>\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Point_set_2.h>\n#include <CGAL/squared_distance_2.h>\n\n#include \"range.hpp\"\n\ntemplate<class Graph>\nunsigned num_internal(Graph const & G) {\n  unsigned internal = 0;\n  for (auto v : range(vertices(G)))\n    internal += out_degree(v, G) > 1;\n  return internal;\n}\n\ntemplate<class Graph>\nunsigned upper_bound(Graph const & G) {\n  return std::min(num_internal(G), (unsigned) num_vertices(G) - 2);\n}\n\ntemplate<class Graph>\nbool is_connected(Graph const & G) {\n  std::vector<int> component(num_vertices(G));\n  return connected_components(G, &component[0]) == 1;\n}\n\ntemplate<class Tree, class Graph>\nbool is_subgraph(Tree const & T, Graph const & G) {\n  for (auto e : range(edges(T)))\n    if(!edge(source(e, T), target(e, T), G).second)\n      return false;\n  return true;\n}\n\ntemplate<class G>\nvoid add_edge_no_dup(typename boost::graph_traits<G>::vertex_descriptor v,\n                     typename boost::graph_traits<G>::vertex_descriptor u,\n                     G& g) {\n  if (!edge(v, u, g).second) add_edge(v, u, g);\n}\n\ntemplate<class Input, class Output>\nvoid copy_edges(const Input& in, Output& out) {\n  for (auto e : range(edges(in)))\n    add_edge(source(e, in), target(e, in), out);\n}\n\ntemplate<class Input, class Output, class Generator>\nvoid copy_edges_shuffled(const Input& in, Output& out, Generator& generator) {\n  auto p = shuffled(range_iterator(0, num_vertices(in)), generator);\n  for (auto e : shuffled(edges(in), generator))\n    add_edge(p[source(e, in)], p[target(e, in)], out);\n}\n\ntemplate<class Graph>\nvoid add_spider(Graph& G, unsigned legs) {\n  unsigned n = num_vertices(G);\n  unsigned cutoff = ceil((double)n / legs);\n  for (unsigned i = 0; i < n - 1; ++i)\n    add_edge_no_dup(i % cutoff == 0 ? 0 : i, i + 1, G);\n}\n\ntemplate<class Graph, class Generator>\nvoid add_edges_uniform(Graph& G, double p, Generator& generator, bool mst) {\n  unsigned n = num_vertices(G);\n  double connectedness = 20.0 / n;\n  if (mst && p < connectedness) {\n    typedef boost::property<boost::edge_weight_t, double> Weight;\n    typedef boost::adjacency_list<boost::hash_setS, boost::vecS, boost::undirectedS, boost::no_property, Weight> WeightedGraph;\n    typedef boost::graph_traits<WeightedGraph>::edge_descriptor WeightedEdge;\n    std::uniform_real_distribution<> distribution(0, 1);\n    auto trial = std::bind(distribution, std::ref(generator));\n    WeightedGraph g;\n    for (unsigned i = 0; i < n; ++i) {\n      for (unsigned j = i + 1; j < n; ++j) {\n        auto w = trial();\n        if (w < connectedness) add_edge(i, j, w, g);\n        if (w < p) add_edge_no_dup(i, j, G);\n      }\n    }\n    std::vector<WeightedEdge> t;\n    kruskal_minimum_spanning_tree(g, std::back_inserter(t));\n    for (auto e : t)\n      add_edge_no_dup(source(e, g), target(e, g), G);\n  } else {\n    std::bernoulli_distribution distribution(p);\n    auto trial = std::bind(distribution, std::ref(generator));\n    for (unsigned i = 0; i < n; ++i) {\n      for (unsigned j = i + 1; j < n; ++j) {\n        if (trial()) add_edge_no_dup(i, j, G);\n      }\n    }\n  }\n}\n\nclass Geometric {\n  CGAL::Exact_predicates_inexact_constructions_kernel typedef Kernel;\n  CGAL::Triangulation_vertex_base_with_info_2<unsigned, Kernel> typedef Vertex_struct;\n  CGAL::Triangulation_data_structure_2<Vertex_struct> typedef Triangulation_struct;\n  CGAL::Point_set_2<Kernel, Triangulation_struct> typedef Delaunay;\n  Delaunay::Point typedef Point;\n\n  Delaunay D;\n\n public:\n  template<class Generator>\n  Geometric(int n, Generator& generator) {\n    // Choose random points in square [0, 1) x [0, 1)\n    std::uniform_real_distribution<> distribution(0, 1);\n    auto r = std::bind(distribution, std::ref(generator));\n    // Generate index for every point\n    int counter = 0;\n    std::function<std::pair<Point, int>()> f = [&]() {return std::make_pair(Point(r(), r()), counter++);};\n    // Initialize triangulation with n points\n    D = Delaunay(boost::make_function_input_iterator(f, 0), boost::make_function_input_iterator(f, n));\n  }\n\n  template<class Graph>\n  void add_random_geometric(Graph& G, double d) {\n    CGAL::Circle_2<Kernel> typedef Circle;\n    Delaunay::Vertex_handle typedef Vertex_handle;\n    // Query each point for other points lying in the circle\n    for (auto v : range(D.finite_vertices_begin(), D.finite_vertices_end()))\n      D.range_search(Circle(v.point(), d * d), boost::make_function_output_iterator([&](Vertex_handle u) {\n        if (v.info() < u->info()) add_edge_no_dup(v.info(), u->info(), G);\n      }));\n  }\n\n  template<class Graph>\n  void add_mst(Graph& G) {\n    typedef boost::property<boost::edge_weight_t, Kernel::FT> Weight;\n    typedef boost::adjacency_list<boost::hash_setS, boost::vecS, boost::undirectedS, boost::no_property, Weight> WeightedGraph;\n    typedef boost::graph_traits<WeightedGraph>::edge_descriptor WeightedEdge;\n\n    Delaunay::Finite_vertices_iterator vit;\n    Delaunay::Vertex_circulator vc, done;\n\n    WeightedGraph g;\n\n    for (vit = D.finite_vertices_begin(); vit != D.finite_vertices_end(); ++vit) {\n      unsigned s = vit->info();\n      done = vc = vit->incident_vertices();\n      if (vc != 0) do {\n        if (D.is_infinite(vc)) continue;\n        unsigned d = vc->info();\n        add_edge(s, d, CGAL::squared_distance(vit->point(), vc->point()), g);\n      } while (++vc != done);\n    }\n\n    std::vector<WeightedEdge> mst;\n    kruskal_minimum_spanning_tree(g, std::back_inserter(mst));\n    for (auto e : mst)\n      add_edge_no_dup(source(e, g), target(e, g), G);\n  }\n};\n\ntemplate<class G>\nbool is_planar(G const & gIn) {\n  return boyer_myrvold_planarity_test(gIn);\n}\n\n//a class to hold the coordinates of the straight line embedding\nstruct coord_t {\n  std::size_t x;\n  std::size_t y;\n};\n\ntemplate<class G>\nstd::vector<coord_t> straight_line_drawing(G const & gIn) {\n  using namespace boost;\n\n  typedef adjacency_list<vecS, vecS, undirectedS, property<vertex_index_t, int>, property<edge_index_t, int> > Graph;\n\n  Graph g;\n  copy_edges(gIn, g);\n\n  //Define the storage type for the planar embedding\n  typedef std::vector<std::vector<graph_traits<Graph>::edge_descriptor>> embedding_storage_t;\n  typedef iterator_property_map<embedding_storage_t::iterator, property_map<Graph, vertex_index_t>::type> embedding_t;\n\n  make_connected(g);\n\n  // Create the planar embedding\n  embedding_storage_t embedding_storage(num_vertices(g));\n  embedding_t embedding(embedding_storage.begin(), get(vertex_index, g));\n\n  boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g, boyer_myrvold_params::embedding = embedding);\n\n  //Initialize the interior edge index\n  property_map<Graph, edge_index_t>::type e_index = get(edge_index, g);\n  graph_traits<Graph>::edges_size_type edge_count = 0;\n  graph_traits<Graph>::edge_iterator ei, ei_end;\n  for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n    put(e_index, *ei, edge_count++);\n\n  make_biconnected_planar(g, embedding);\n\n  // Re-initialize the edge index, since we just added a few edges\n  edge_count = 0;\n  for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\n    put(e_index, *ei, edge_count++);\n\n  //Test for planarity again; compute the planar embedding as a side-effect\n  boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g, boyer_myrvold_params::embedding = embedding);\n\n  make_maximal_planar(g, embedding);\n\n  //Test for planarity again; compute the planar embedding as a side-effect\n  boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g, boyer_myrvold_params::embedding = embedding);\n\n  // Find a canonical ordering\n  std::vector<typename graph_traits<Graph>::vertex_descriptor> ordering;\n  planar_canonical_ordering(g, embedding, std::back_inserter(ordering));\n\n  //Set up a property map to hold the mapping from vertices to coord_t's\n  typedef std::vector<coord_t> drawing_storage_t;\n  typedef boost::iterator_property_map<drawing_storage_t::iterator, property_map<Graph, vertex_index_t>::type> drawing_t;\n\n  drawing_storage_t drawing_storage(num_vertices(g));\n  drawing_t drawing(drawing_storage.begin(), get(vertex_index, g));\n\n  // Compute the straight line drawing\n  chrobak_payne_straight_line_drawing(g, embedding, ordering.begin(), ordering.end(), drawing);\n\n  return drawing_storage;\n}\n", "meta": {"hexsha": "d24a49fad23438f5bbc830df895388b6d320981d", "size": 8965, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "util/graph.hpp", "max_stars_repo_name": "arekolek/MaxIST", "max_stars_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/graph.hpp", "max_issues_repo_name": "arekolek/MaxIST", "max_issues_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/graph.hpp", "max_forks_repo_name": "arekolek/MaxIST", "max_forks_repo_head_hexsha": "6a8b49152cfbf34c1c2728f64b1457a23824fe0d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0040160643, "max_line_length": 127, "alphanum_fraction": 0.7099832683, "num_tokens": 2397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568417, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.43996612299013765}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\n *    All rights reserved.\n *\n *    Redistribution and use in source and binary forms, with or without modification, are\n *    permitted provided that the following conditions are met:\n *      - Redistributions of source code must retain the above copyright notice, this list of\n *        conditions and the following disclaimer.\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\n *        conditions and the following disclaimer in the documentation and/or other materials\n *        provided with the distribution.\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\n *        may be used to endorse or promote products derived from this software without specific\n *        prior written permission.\n *\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *    Changelog\n *      YYMMDD    Author            Comment\n *      120210    T. Secretin       File created.\n *\n *    References\n *      Battin, R.H. An Introduction to the Mathematics and Methods of Astrodynamics,\n *          AIAA Education Series, 1999.\n *      Izzo, D. lambert_problem.h, keptoolbox.\n *\n *    Notes\n *      This code is an implementation of the method developed by Dario Izzo from ESA/ACT and\n *      publicly available at: http://keptoolbox.sourceforge.net/.\n *      After verification and validation, it was proven that this algorithm is faster and more\n *      robust than the implemented Lancaster & Blanchard and Gooding method. Notably, this method\n *      does not suffer from the near-pi singularity (pi-transfers are by nature singular).\n *\n */\n\n#include \"Tudat/Astrodynamics/MissionSegments/lambertTargeterIzzo.h\"\n#include \"Tudat/Astrodynamics/MissionSegments/lambertRoutines.h\"\n\n#include <Eigen/Geometry>\n\nnamespace tudat\n{\nnamespace mission_segments\n{\n\n//! Execute Lambert targeting solver.\nvoid LambertTargeterIzzo::execute( )\n{\n    // Call Izzo's Lambert targeting routine.\n    solveLambertProblemIzzo( cartesianPositionAtDeparture, cartesianPositionAtArrival,\n                             timeOfFlight, gravitationalParameter, cartesianVelocityAtDeparture,\n                             cartesianVelocityAtArrival, isRetrograde_, convergenceTolerance_,\n                             maximumNumberOfIterations_ );\n}\n\n//! Get radial velocity at departure.\ndouble LambertTargeterIzzo::getRadialVelocityAtDeparture( )\n{\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtDeparture\n            = cartesianPositionAtDeparture.normalized( );\n\n    // Compute radial velocity at departure.\n    return cartesianVelocityAtDeparture.dot( radialUnitVectorAtDeparture );\n}\n\n//! Get radial velocity at arrival.\ndouble LambertTargeterIzzo::getRadialVelocityAtArrival( )\n{\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtArrival = cartesianPositionAtArrival.normalized( );\n\n    // Compute radial velocity at arrival.\n    return cartesianVelocityAtArrival.dot( radialUnitVectorAtArrival );\n}\n\n//! Get transverse velocity at departure.\ndouble LambertTargeterIzzo::getTransverseVelocityAtDeparture( )\n{\n    // Compute angular momemtum vector.\n    const Eigen::Vector3d angularMomentumVector =\n            cartesianPositionAtDeparture.cross( cartesianVelocityAtDeparture );\n\n    // Compute normalized angular momentum vector.\n    const Eigen::Vector3d angularMomentumUnitVector = angularMomentumVector.normalized( );\n\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtDeparture\n            = cartesianPositionAtDeparture.normalized( );\n\n    // Compute tangential unit vector.\n    Eigen::Vector3d tangentialUnitVectorAtDeparture =\n                angularMomentumUnitVector.cross( radialUnitVectorAtDeparture );\n\n    // Compute tangential velocity at departure.\n    return cartesianVelocityAtDeparture.dot( tangentialUnitVectorAtDeparture );\n}\n\n//! Get transverse velocity at arrival.\ndouble LambertTargeterIzzo::getTransverseVelocityAtArrival( )\n{\n    // Compute angular momemtum vector.\n    const Eigen::Vector3d angularMomentumVector =\n            cartesianPositionAtArrival.cross( cartesianVelocityAtArrival );\n\n    // Compute normalized angular momentum vector.\n    const Eigen::Vector3d angularMomentumUnitVector = angularMomentumVector.normalized( );\n\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtArrival = cartesianPositionAtArrival.normalized( );\n\n    // Compute tangential unit vector.\n    Eigen::Vector3d tangentialUnitVectorAtArrival\n            = angularMomentumUnitVector.cross( radialUnitVectorAtArrival );\n\n    // Compute tangential velocity at departure.\n    return cartesianVelocityAtArrival.dot( tangentialUnitVectorAtArrival );\n}\n\n//! Get semi-major axis.\ndouble LambertTargeterIzzo::getSemiMajorAxis( )\n{\n    // Compute specific orbital energy: eps = v^2/ - mu/r.\n    const double specificOrbitalEnergy = cartesianVelocityAtDeparture.squaredNorm( ) / 2.0\n            - gravitationalParameter / cartesianPositionAtDeparture.norm( );\n\n    // Compute semi-major axis: a = -mu / 2*eps.\n    return -gravitationalParameter / ( 2.0 * specificOrbitalEnergy );\n}\n\n} // namespace mission_segments\n} // namespace tudat\n", "meta": {"hexsha": "e3f7385b946ed5140c30558d3077116df02eedd5", "size": 6043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/MissionSegments/lambertTargeterIzzo.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/MissionSegments/lambertTargeterIzzo.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/MissionSegments/lambertTargeterIzzo.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 43.1642857143, "max_line_length": 99, "alphanum_fraction": 0.7382094986, "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4399661229901376}}
{"text": "/********************************************************************************\n*  This file is part of CinoLib                                                 *\n*  Copyright(C) 2016: Marco Livesu                                              *\n*                                                                               *\n*  The MIT License                                                              *\n*                                                                               *\n*  Permission is hereby granted, free of charge, to any person obtaining a      *\n*  copy of this software and associated documentation files (the \"Software\"),   *\n*  to deal in the Software without restriction, including without limitation    *\n*  the rights to use, copy, modify, merge, publish, distribute, sublicense,     *\n*  and/or sell copies of the Software, and to permit persons to whom the        *\n*  Software is furnished to do so, subject to the following conditions:         *\n*                                                                               *\n*  The above copyright notice and this permission notice shall be included in   *\n*  all copies or substantial portions of the Software.                          *\n*                                                                               *\n*  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR   *\n*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,     *\n*  FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE *\n*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER       *\n*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      *\n*  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS *\n*  IN THE SOFTWARE.                                                             *\n*                                                                               *\n*  Author(s):                                                                   *\n*                                                                               *\n*     Marco Livesu (marco.livesu@gmail.com)                                     *\n*     http://pers.ge.imati.cnr.it/livesu/                                       *\n*                                                                               *\n*     Italian National Research Council (CNR)                                   *\n*     Institute for Applied Mathematics and Information Technologies (IMATI)    *\n*     Via de Marini, 6                                                          *\n*     16149 Genoa,                                                              *\n*     Italy                                                                     *\n*********************************************************************************/\n#include <cinolib/heat_flow.h>\n#include <cinolib/laplacian.h>\n#include <cinolib/vertex_mass.h>\n#include <cinolib/linear_solvers.h>\n#include <Eigen/Sparse>\n\nnamespace cinolib\n{\n\ntemplate<class M, class V, class E, class P>\nCINO_INLINE\nScalarField heat_flow(const AbstractMesh<M,V,E,P> & m,\n                      const std::vector<uint>     & heat_charges,\n                      const double                  time,\n                      const int                     laplacian_mode,\n                      const bool                    hard_contraint_bcs)\n{\n    assert(heat_charges.size() > 0);\n\n    ScalarField heat(m.num_verts());\n\n    Eigen::SparseMatrix<double> L   = laplacian(m, laplacian_mode);\n    Eigen::SparseMatrix<double> MM  = mass_matrix(m);\n    Eigen::VectorXd             rhs = Eigen::VectorXd::Zero(m.num_verts());\n\n    if (hard_contraint_bcs) // heat flow as a boundary problem (charges do not lose heat)\n    {\n        std::map<uint,double> bcs;\n        for(uint vid: heat_charges) bcs[vid] = 1.0;\n        solve_square_system_with_bc(MM - time * L, rhs, heat, bcs);\n    }\n    else // heat flow as a diffusion problem (charges lose heat)\n    {\n        for(uint vid : heat_charges) rhs[vid] = 1.0;\n        solve_square_system(MM - time * L, rhs, heat);\n    }\n\n\n    return heat;\n}\n\n}\n", "meta": {"hexsha": "111e410489bd6a7437396750b68397fcb77243be", "size": 4167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/cinolib/heat_flow.cpp", "max_stars_repo_name": "Deiv99/cinolib", "max_stars_repo_head_hexsha": "fbb6e951703764e5b97f074aede87752c3165d17", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 532.0, "max_stars_repo_stars_event_min_datetime": "2018-05-11T14:28:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:42:07.000Z", "max_issues_repo_path": "include/cinolib/heat_flow.cpp", "max_issues_repo_name": "Deiv99/cinolib", "max_issues_repo_head_hexsha": "fbb6e951703764e5b97f074aede87752c3165d17", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T16:47:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-29T14:36:12.000Z", "max_forks_repo_path": "include/cinolib/heat_flow.cpp", "max_forks_repo_name": "Deiv99/cinolib", "max_forks_repo_head_hexsha": "fbb6e951703764e5b97f074aede87752c3165d17", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 64.0, "max_forks_repo_forks_event_min_datetime": "2018-09-07T13:02:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T18:17:29.000Z", "avg_line_length": 53.4230769231, "max_line_length": 89, "alphanum_fraction": 0.4418046556, "num_tokens": 729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891261650248, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.43995210944479163}}
{"text": "// This file is part of snark, a generic and flexible library for robotics research\n// Copyright (c) 2014 The University of Sydney\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n// 1. Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the University of Sydney nor the\n//    names of its contributors may be used to endorse or promote products\n//    derived from this software without specific prior written permission.\n//\n// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE\n// GRANTED BY THIS LICENSE.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT\n// HOLDERS AND CONTRIBUTORS \\\"AS IS\\\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n// IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n/// @author vsevolod vlaskine\n\n#include <Eigen/Geometry>\n#include <comma/base/exception.h>\n#include <comma/math/compare.h>\n#include \"polygon.h\"\n\nnamespace snark {\n\ntemplate < typename C > static Eigen::Vector3d normal_impl( const C& corners )\n{\n    const Eigen::Vector3d& cross = ( corners[1] - corners[0] ).cross( corners[0] - corners[2] );\n    return cross / cross.norm();\n}\n\ntemplate < typename C > static Eigen::Vector3d projection_impl( const C& corners, const Eigen::Vector3d& rhs )\n{\n    const Eigen::Vector3d& n = normal_impl( corners );\n    return rhs - n * ( rhs - corners[0] ).dot( n );\n}\n\n// See https://blogs.msdn.microsoft.com/rezanour/2011/08/07/barycentric-coordinates-and-point-in-triangle-tests\nstatic inline bool is_inside( const Eigen::Vector3d& a, const Eigen::Vector3d& b, const Eigen::Vector3d& c, const Eigen::Vector3d& p )\n{\n    const Eigen::Vector3d& u = b - a;\n    const Eigen::Vector3d& v = c - a;\n    const Eigen::Vector3d& w = p - a;\n\n    const Eigen::Vector3d& v_cross_w = v.cross( w );\n    const Eigen::Vector3d& v_cross_u = v.cross( u );\n\n    if( v_cross_w.dot( v_cross_u ) < 0 ) { return false; }\n\n    const Eigen::Vector3d& u_cross_w = u.cross( w );\n    const Eigen::Vector3d& u_cross_v = -v_cross_u;\n\n    if( u_cross_w.dot( u_cross_v ) < 0 ) { return false; }\n\n    double denom = u_cross_v.norm();\n    double r = v_cross_w.norm();\n    double t = u_cross_w.norm();\n\n    return( r + t <= denom );\n}\n\ntemplate < typename C > static bool includes_impl( const C& corners, const Eigen::Vector3d& rhs )\n{\n    for( std::size_t i = 2; i < corners.size(); ++i )\n    {\n        if( is_inside( corners[0], corners[i-1], corners[i], rhs ) ) { return true; }\n    }\n    return false;\n}\n\nstatic inline double distance_to_line( const Eigen::Vector3d from, const Eigen::Vector3d& to, const Eigen::Vector3d& point )\n{\n    typedef Eigen::ParametrizedLine< double, 3 > line_t;\n    line_t line( from, ( to - from ).normalized() );\n    Eigen::Vector3d projection = line.projection( point );\n    bool is_between = ( ( projection - from ).squaredNorm() + ( projection - to ).squaredNorm() ) <= ( to - from ).squaredNorm();\n    return is_between ? ( projection - point ).norm() : std::min( ( from - point ).norm(), ( to - point ).norm() );\n}\n\ndouble convex_polygon::distance_from_border_to( const Eigen::Vector3d& rhs ) const\n{\n    double distance = distance_to_line( corners.front(), corners.back(), rhs );\n    for( unsigned int i = 1; i < corners.size(); ++i )\n    {\n        double d = distance_to_line( corners[ i - 1 ], corners[i], rhs );\n        if( d < distance ) { distance = d; }\n    }\n    return distance;\n}\n\nEigen::Vector3d convex_polygon::normal() const { return normal_impl( corners ); }\n\nbool convex_polygon::is_valid() const\n{\n    if( corners.size() < 3 ) { return false; }\n    COMMA_THROW( comma::exception, \"todo\" );\n    for( std::size_t i = 1; i < corners.size(); ++i )\n    {\n        // todo\n    }\n    return true;\n}\n    \nEigen::Vector3d convex_polygon::projection_of( const Eigen::Vector3d& rhs ) const { return projection_impl( corners, rhs ); }\n\nbool convex_polygon::includes( const Eigen::Vector3d& rhs ) const { return includes_impl( corners, rhs ); }\n\nEigen::Vector3d triangle::normal() const { return normal_impl( corners ); }\n\nbool triangle::is_valid() const\n{\n    if( corners.size() != 3 ) { return false; }\n    const Eigen::Vector3d& cross = ( corners[1] - corners[0] ).cross( corners[0] - corners[2] );\n    return !comma::math::equal( cross.norm(), 0 );\n}\n\nEigen::Vector3d triangle::projection_of( const Eigen::Vector3d& rhs ) const { return projection_impl( corners, rhs ); }\n\nbool triangle::includes( const Eigen::Vector3d& rhs ) const { return includes_impl( corners, rhs ); }\n\ndouble triangle::circumscribing_radius() const\n{\n    COMMA_THROW( comma::exception, \"todo\" );\n    const Eigen::Vector3d& a = corners[1] - corners[0];\n    const Eigen::Vector3d& b = corners[2] - corners[1];\n    const Eigen::Vector3d& c = corners[0] - corners[2];\n    return a.norm() / ( std::sqrt( 1 - b.dot( c ) / ( b.squaredNorm() * c.squaredNorm() ) ) * 2 );\n}\n\n} // namespace snark {\n", "meta": {"hexsha": "4fc7dee9a4184c10703110496ef3689db974feea", "size": 5870, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/geometry/polygon.cpp", "max_stars_repo_name": "nightfox0909/snark", "max_stars_repo_head_hexsha": "6a6ddc79af9086f13ba0c1287a555c2740fe4e70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2015-01-14T14:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T09:56:03.000Z", "max_issues_repo_path": "math/geometry/polygon.cpp", "max_issues_repo_name": "nightfox0909/snark", "max_issues_repo_head_hexsha": "6a6ddc79af9086f13ba0c1287a555c2740fe4e70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-01-21T00:57:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T04:22:35.000Z", "max_forks_repo_path": "math/geometry/polygon.cpp", "max_forks_repo_name": "nightfox0909/snark", "max_forks_repo_head_hexsha": "6a6ddc79af9086f13ba0c1287a555c2740fe4e70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T17:13:35.000Z", "avg_line_length": 40.7638888889, "max_line_length": 134, "alphanum_fraction": 0.6851788756, "num_tokens": 1539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4399232562063752}}
{"text": "#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include <QDebug>\n#include <QPrinter>\n\n#include <cmath>\n#include <iostream>\n\n#include \"MotionModes/crab.h\"\n#include \"MotionModes/motion_mode.h\"\n#include \"MotionModes/tangent_aligned.h\"\n#include \"wheel.h\"\n\n#include <dlib/global_optimization.h>\n\nMainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow), scene(new CustomScene)\n{\n  ui->setupUi(this);\n\n  ui->graphicsView->setScene(scene);\n  new QGraphicsViewZoom(ui->graphicsView);\n\n  Eigen::MatrixX2d cp1, cp2;\n  cp1.resize(4, 2);\n  cp2.resize(4, 2);\n\n  cp1 << -1, 0, -1, -4. / 3, 1, -4. / 3, 1.5, -0.5;\n  cp1 *= 300;\n  cp2 << 1.5, -0.5, 1, 2, 2, 1, 3, 1;\n  cp2 *= 150;\n  cp2.col(0) *= 2;\n\n  curve_1 = new qCurve(Bezier::Curve(cp1).splitCurve(0.5).second, ui, 1);\n  curve_2 = new qCurve(cp2, ui, 2);\n\n  curve_2->applyContinuity(*curve_1, {1.4});\n\n  curve_1->elevateOrder();\n  curve_1->elevateOrder();\n  curve_1->elevateOrder();\n\n  curve_2->elevateOrder();\n  curve_2->elevateOrder();\n  curve_2->elevateOrder();\n\n  scene->addItem(curve_1);\n  scene->addItem(curve_2);\n\n  curve_1->setDraw_control_points(true);\n  curve_2->setDraw_control_points(true);\n\n  ui->graphicsView->centerOn(scene->itemsBoundingRect().center());\n\n  // plots\n  ui->plot2->yAxis2->setVisible(true);\n\n  // add title layout element:\n  //  ui->plot1->plotLayout()->insertRow(0);\n  //  ui->plot2->plotLayout()->insertRow(0);\n  //  ui->plot3->plotLayout()->insertRow(0);\n  //  ui->plot1->setFont(QFont(\"Times\", 12));\n  //  ui->plot2->setFont(QFont(\"Times\", 12));\n  //  ui->plot3->setFont(QFont(\"Times\", 12));\n  //  ui->plot1->plotLayout()->addElement(0, 0, new QCPTextElement(ui->plot1, \"Speed limit and speed profiles\"));\n  //  ui->plot2->plotLayout()->addElement(0, 0, new QCPTextElement(ui->plot2, \"Angular velocities\"));\n  //  ui->plot3->plotLayout()->addElement(0, 0, new QCPTextElement(ui->plot3, \"Vehicle orientation and steering\n  //  angles\"));\n\n  // set labels:\n  ui->plot1->xAxis->setLabelFont(QFont(\"Times\", 10));\n  ui->plot2->xAxis->setLabelFont(QFont(\"Times\", 10));\n  ui->plot1->xAxis->setLabel(\"Distance along path [m]\");\n  ui->plot2->xAxis->setLabel(\"Distance along path [m]\");\n\n  ui->plot1->yAxis->setLabelFont(QFont(\"Times\", 10));\n  ui->plot2->yAxis->setLabelFont(QFont(\"Times\", 10));\n  ui->plot2->yAxis2->setLabelFont(QFont(\"Times\", 10));\n  ui->plot1->yAxis->setLabel(\"Speed [m/s]\");\n  ui->plot2->yAxis->setLabel(\"Vehicle orientation and wheel steering angle [°]\");\n  ui->plot2->yAxis2->setLabel(\"Angular velocity [°/s]\");\n\n  // set ticks:\n  ui->plot1->xAxis->setTickLabelFont(QFont(\"Times\", 10));\n  ui->plot2->xAxis->setTickLabelFont(QFont(\"Times\", 10));\n  ui->plot1->yAxis->setTickLabelFont(QFont(\"Times\", 10));\n  ui->plot2->yAxis->setTickLabelFont(QFont(\"Times\", 10));\n  ui->plot2->yAxis2->setTickLabelFont(QFont(\"Times\", 10));\n\n  // show legend\n  ui->plot1->legend->setVisible(true);\n  ui->plot2->legend->setVisible(true);\n  ui->plot1->legend->setFont(QFont(\"Times\", 10));\n  ui->plot2->legend->setFont(QFont(\"Times\", 10));\n  ui->plot1->legend->setRowSpacing(-5);\n  ui->plot2->legend->setRowSpacing(-5);\n  ui->plot1->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignBottom | Qt::AlignRight);\n  ui->plot2->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignRight);\n\n  // open in new window\n  //  ui->plot1->setParent(nullptr);\n  //  ui->plot2->setParent(nullptr);\n  ui->plot1->setMinimumSize(400, 300);\n  ui->plot2->setMinimumSize(400, 300);\n  ui->plot1->show();\n  ui->plot2->show();\n\n  auto saveAs = []() {\n    QFileDialog dialog(nullptr, \"Export PDF\");\n    dialog.setNameFilter(\"PDF (*.pdf)\");\n    dialog.setFileMode(QFileDialog::AnyFile);\n    dialog.setAcceptMode(QFileDialog::AcceptSave);\n    dialog.setDefaultSuffix(\"pdf\");\n    if (dialog.exec())\n      return dialog.selectedFiles().first();\n    return QString();\n  };\n\n  connect(ui->plot1, &QCustomPlot::mouseRelease, this, [&](QMouseEvent* e) {\n    if (e->button() == Qt::RightButton)\n    {\n      auto file_path = saveAs();\n      if (file_path == QString())\n        return;\n      ui->plot1->savePdf(file_path, 0, 0, QCP::epNoCosmetic);\n    }\n  });\n  connect(ui->plot2, &QCustomPlot::mouseRelease, this, [&](QMouseEvent* e) {\n    if (e->button() == Qt::RightButton)\n    {\n      auto file_path = saveAs();\n      if (file_path == QString())\n        return;\n      ui->plot2->savePdf(file_path, 0, 0, QCP::epNoCosmetic);\n    }\n  });\n\n  //    QPrinter printer(QPrinter::HighResolution);\n  //    printer.setPageSize(\n  //        QPageSize(scene->itemsBoundingRect().size().scaled(90, 90, Qt::AspectRatioMode::KeepAspectRatio),\n  //                  QPageSize::Unit::Point));\n  //    printer.setOrientation(QPrinter::Portrait);\n  //    printer.setOutputFormat(QPrinter::PdfFormat);\n  //    printer.setFullPage(true);\n  //    auto file_path = saveAs();\n  //    if (file_path == QString())\n  //      return;\n  //    printer.setOutputFileName(file_path);\n\n  //    QPainter p;\n\n  //    if (!p.begin(&printer))\n  //    {\n  //      qDebug() << \"Error!\";\n  //      return;\n  //    }\n\n  //    this->scene->render(&p);\n  //    p.end();\n\n  //    int sl = file_path.lastIndexOf('/') + 1;\n  //    QString file_path2 = file_path.left(sl) + \"angle\" + file_path.right(6);\n  //    ui->plot2->savePdf(file_path2, 0, 0, QCP::epNoCosmetic);\n  //    QString file_path3 = file_path.left(sl) + \"speed\" + file_path.right(6);\n  //    ui->plot1->savePdf(file_path3, 0, 0, QCP::epNoCosmetic);\n  //    // ovdje dodati export i ostalih\n\n  ui->plot1->setInteraction(QCP::iRangeDrag, true);\n  ui->plot2->setInteraction(QCP::iRangeDrag, true);\n\n  ui->plot1->axisRect()->setRangeDrag(Qt::Horizontal);\n  ui->plot2->axisRect()->setRangeDrag(Qt::Horizontal);\n\n  ui->plot1->setInteraction(QCP::iRangeZoom, true);\n  ui->plot2->setInteraction(QCP::iRangeZoom, true);\n\n  ui->plot1->axisRect()->setRangeZoom(Qt::Horizontal);\n  ui->plot2->axisRect()->setRangeZoom(Qt::Horizontal);\n\n  // curves\n  connect(ui->optimize, &QPushButton::pressed, this, &MainWindow::applyContinuity);\n  //  connect(ui->alpha1, qOverload<double>(&QDoubleSpinBox::valueChanged), this, &MainWindow::applyContinuity);\n  //  connect(ui->alpha2, qOverload<double>(&QDoubleSpinBox::valueChanged), this, &MainWindow::applyContinuity);\n  //  connect(ui->n1, qOverload<double>(&QDoubleSpinBox::valueChanged), this, &MainWindow::applyContinuity);\n  //  connect(ui->n2, qOverload<double>(&QDoubleSpinBox::valueChanged), this, &MainWindow::applyContinuity);\n  //  connect(ui->mm1, qOverload<int>(&QComboBox::currentIndexChanged), this, &MainWindow::applyContinuity);\n  //  connect(ui->mm2, qOverload<int>(&QComboBox::currentIndexChanged), this, &MainWindow::applyContinuity);\n\n  // vehicle tab\n  ui->vehicle->header()->resizeSection(0, 150);\n  ui->vehicle->header()->setSectionResizeMode(1, QHeaderView::Stretch);\n  ui->vehicle->header()->setStretchLastSection(false);\n\n  static auto addWheel = [&]() {\n    Wheel* temp = new Wheel(ui->vehicle->topLevelItemCount(), ui->vehicle);\n    ui->vehicle->addTopLevelItem(temp);\n    temp->expand();\n    connect(temp, &Wheel::wheelChanged, this, &MainWindow::updatePlot);\n  };\n\n  static auto removeWheel = [&]() { delete ui->vehicle->takeTopLevelItem(ui->vehicle->topLevelItemCount() - 1); };\n\n  for (uint k = 0; k < ui->wheel_num->value(); k++)\n    addWheel();\n  connect(scene, &QGraphicsScene::changed, this, &MainWindow::updatePlot);\n\n  connect(ui->wheel_num, qOverload<int>(&QSpinBox::valueChanged), this, [&](int n) {\n    while (n > ui->vehicle->topLevelItemCount())\n      addWheel();\n    while (n < ui->vehicle->topLevelItemCount())\n      removeWheel();\n    updatePlot();\n  });\n\n  //  curve_1->setVisible(false);\n  //  curve_2->setVisible(false);\n\n  //  ui->wheel_num->setValue(6);\n\n  //  static const QVector<QColor> matlab_colors(\n  //      {{0, 114, 189}, {217, 83, 25}, {237, 177, 32}, {126, 47, 142}, {119, 172, 48}, {77, 190, 238}, {162, 20,\n  //      47}});\n  //  QPainterPath vehicle_frame;\n\n  //  vehicle_frame = QPainterPath();\n  //  vehicle_frame.moveTo(50, 0);\n  //  vehicle_frame.lineTo(0, 0);\n  //  vehicle_frame.lineTo(0, -50);\n  //  vehicle_frame.lineTo(-3,-47);\n  //  vehicle_frame.lineTo(0, -50);\n  //  vehicle_frame.lineTo(3,-47);\n\n  //  QVector<QString> w;\n  //  w.push_back(u8\"w\\u2081\");\n  //  w.push_back(u8\"w\\u2082\");\n  //  w.push_back(u8\"w\\u2083\");\n  //  w.push_back(u8\"w\\u2084\");\n  //  w.push_back(u8\"w\\u2085\");\n  //  w.push_back(u8\"w\\u2086\");\n\n  //    scene->addPath(vehicle_frame, QPen(matlab_colors[0], 3));\n  //    for(int k = 0; k < ui->wheel_num->value(); k++)\n  //    {\n  //      auto wheel = static_cast<Wheel*>(ui->vehicle->topLevelItem(k));\n  //      auto R = wheel->getR();\n  //      scene->addRect(QRect(R.x()*10-100, -(R.y()*10-50), 200, -100), QPen(matlab_colors[k+1], 1));\n  //      scene->addLine(0,0,R.x()*10, -R.y()*10);\n  //      auto x = scene->addText(w[k], QFont(\"Times\", 24));\n  //      x->setPos(R.x()*10, -R.y()*10);\n  //    }\n\n  //  scene->update();\n\n  //  {\n  //      QPrinter printer( QPrinter::HighResolution );\n  //      printer.setPageSize(QPageSize(qCurve(cp2*5).boundingRect().size(), QPageSize::Unit::Point));\n  //      printer.setOrientation( QPrinter::Portrait );\n  //      printer.setOutputFormat( QPrinter::PdfFormat );\n  //      printer.setFullPage(true);\n  //      printer.setOutputFileName( \"/home/mirko/Pictures/motion_modes/\" + qCurve::getName());\n\n  //      QPainter p;\n\n  //      if( !p.begin( &printer ) )\n  //      {\n  //          qDebug() << \"Error!\";\n  //          return;\n  //      }\n  //      this->scene->render( &p );\n  //      p.end();\n  //  }\n\n  //  auto dC = curve_1->derivativeAt(1);\n  //  ui->alpha2->setValue(std::atan2(dC.y(), dC.x()) * 180 / M_PI);\n  //  ui->mm2->setCurrentIndex(2);\n}\n\nMainWindow::~MainWindow() { delete ui; }\n\nvoid MainWindow::applyContinuity()\n{\n  Romb::MotionModes::MotionMode *mm_1, *mm_2;\n  double alpha_1 = ui->alpha1->value() * M_PI / 180;\n  double alpha_2 = ui->alpha2->value() * M_PI / 180;\n  double n_1 = ui->n1->value();\n  double n_2 = ui->n2->value();\n\n  switch (ui->mm1->currentIndex())\n  {\n  case 0:\n    mm_1 = new Romb::MotionModes::TangentAligned(alpha_1);\n    break;\n  case 1:\n    mm_1 = new Romb::MotionModes::Crab(alpha_1);\n    break;\n  case 2:\n    mm_1 = new Romb::MotionModes::Exponential(alpha_1, n_1);\n    break;\n  default:\n    mm_1 = new Romb::MotionModes::Exponential(alpha_1, -n_1);\n    break;\n  }\n\n  switch (ui->mm2->currentIndex())\n  {\n  case 0:\n    mm_2 = new Romb::MotionModes::TangentAligned(alpha_2);\n    break;\n  case 1:\n    mm_2 = new Romb::MotionModes::Crab(alpha_2);\n    break;\n  case 2:\n    mm_2 = new Romb::MotionModes::Exponential(alpha_1, n_2);\n    break;\n  default:\n    mm_2 = new Romb::MotionModes::Exponential(alpha_1, -n_2);\n    break;\n  }\n\n  dlib::thread_pool tp(std::thread::hardware_concurrency());\n  std::function<void(std::vector<double>, Bezier::Curve&, Bezier::Curve&)> applyParams;\n  std::function<double(std::vector<double>)> evaluate = [&](std::vector<double> params) {\n    Bezier::Curve temp1 = *curve_1;\n    Bezier::Curve temp2 = *curve_2;\n    applyParams(params, temp1, temp2);\n\n    Data sim = calculateData(temp1, temp2, true);\n\n    auto time = [](QVector<double> v, QVector<double> s) {\n      double res{0.0};\n      for (int k = 1; k < s.size(); k++)\n        res += 2 * (s[k] - s[k - 1]) / (v[k] + v[k - 1]);\n      return res;\n    };\n\n    return time(sim.v_sim1, sim.s1) + time(sim.v_sim2, sim.s2);\n  };\n\n  constexpr std::chrono::seconds opt_max_duration(15);\n\n  if (mm_1->type == \"aligned\" && mm_2->type == \"aligned\")\n  {\n    ui->alpha2->setValue(alpha_1);\n    applyParams = [](std::vector<double> params, Bezier::Curve& curve_1, Bezier::Curve& curve_2) {\n      curve_2.applyContinuity(curve_1, {params[0], params[1], params[2]});\n    };\n    auto result = dlib::find_min_global(\n        tp,\n        [&](double x0, double x1, double x2) {\n          return evaluate({x0, x1, x2});\n        },\n        {0.01, 0, 0}, {5, 5, 5}, opt_max_duration);\n\n    applyParams(std::vector<double>(result.x.begin(), result.x.end()), *curve_1, *curve_2);\n  }\n  if ((mm_1->type == \"aligned\" || mm_1->type == \"exponential_1\") && mm_2->type == \"crab\")\n  {\n    auto dc = curve_1->derivativeAt(1);\n    ui->alpha2->setValue((std::atan2(dc.y(), dc.x()) + alpha_1) * 180 / M_PI);\n    applyParams = [](std::vector<double> params, Bezier::Curve& curve_1, Bezier::Curve& curve_2) {\n      auto dc = curve_1.derivativeAt(1);\n      curve_1.manipulateControlPoint(curve_1.order() - 1, curve_1.endPoints().second - params[0] * dc);\n      curve_1.manipulateControlPoint(curve_1.order() - 2, curve_1.endPoints().second - params[1] * dc);\n      curve_1.manipulateControlPoint(curve_1.order() - 3, curve_1.endPoints().second - params[2] * dc);\n\n      curve_2.manipulateControlPoint(0, curve_1.endPoints().second);\n      curve_2.manipulateControlPoint(1, curve_1.endPoints().second + params[3] * dc);\n      curve_2.manipulateControlPoint(2, curve_1.endPoints().second + params[4] * dc);\n    };\n\n    auto result = dlib::find_min_global(\n        tp,\n        [&](double x0, double x1, double x2, double x3, double x4) {\n          return evaluate({x0, x1, x2, x3, x4});\n        },\n        {0.1, 0, 0, 0.1, 0}, {5, 5, 5, 5, 5}, opt_max_duration);\n    applyParams({result.x(0), result.x(1), result.x(2), result.x(3), result.x(4)}, *curve_1, *curve_2);\n  }\n  if ((mm_2->type == \"aligned\" || mm_2->type == \"exponential_2\") && mm_1->type == \"crab\")\n  {\n    auto dc = curve_1->derivativeAt(1);\n    ui->alpha2->setValue((std::atan2(dc.y(), dc.x()) + alpha_1) * 180 / M_PI);\n    applyParams = [](std::vector<double> params, Bezier::Curve& curve_2, Bezier::Curve& curve_1) {\n      auto dc = curve_1.derivativeAt(0);\n      curve_1.manipulateControlPoint(curve_1.order() - 1, curve_1.endPoints().second - params[0] * dc);\n      curve_1.manipulateControlPoint(curve_1.order() - 2, curve_1.endPoints().second - params[1] * dc);\n      curve_1.manipulateControlPoint(curve_1.order() - 3, curve_1.endPoints().second - params[2] * dc);\n\n      curve_2.manipulateControlPoint(0, curve_1.endPoints().second);\n      curve_2.manipulateControlPoint(1, curve_1.endPoints().second + params[3] * dc);\n      curve_2.manipulateControlPoint(2, curve_1.endPoints().second + params[4] * dc);\n    };\n\n    auto result = dlib::find_min_global(\n        tp,\n        [&](double x0, double x1, double x2, double x3, double x4) {\n          return evaluate({x0, x1, x2, x3, x4});\n        },\n        {0.1, 0, 0, 0.1, 0}, {5, 5, 5, 5, 5}, opt_max_duration);\n    applyParams({result.x(0), result.x(1), result.x(2), result.x(3), result.x(4)}, *curve_1, *curve_2);\n  }\n\n  if (mm_1->type == \"aligned\" && mm_2->type == \"exponential_2\")\n  {\n    ui->alpha2->setValue(ui->alpha1->value());\n    applyParams = [&](std::vector<double> params, Bezier::Curve& curve_1, Bezier::Curve& curve_2) {\n      auto dc = curve_1.derivativeAt(1);\n      curve_1.manipulateControlPoint(curve_1.order() - 1, curve_1.endPoints().second - params[0] * dc);\n      curve_1.manipulateControlPoint(curve_1.order() - 2, curve_1.endPoints().second - params[1] * dc);\n\n      curve_2.manipulateControlPoint(0, curve_1.endPoints().second);\n      curve_2.manipulateControlPoint(1, curve_1.endPoints().second + params[2] * dc);\n      curve_2.manipulateControlPoint(2, curve_1.endPoints().second + params[3] * dc);\n\n      double beta_1 = curve_1.derivativeAt(1).norm() / curve_2.derivativeAt(0).norm();\n      double beta_2 = curve_1.derivativeAt(1).norm() / curve_2.derivativeAt(0).norm();\n\n      double dC3_scale = n_2 * n_2 * (beta_1 * beta_1 * beta_1);\n\n      double beta_3 = (curve_2.derivativeAt(3, 0).norm() * dC3_scale -\n                       beta_1 * beta_1 * beta_1 * curve_2.derivativeAt(2, 0).norm() -\n                       2 * beta_1 * beta_2 * curve_2.derivativeAt(2, 0).norm()) /\n                      curve_2.derivativeAt(0).norm();\n\n      curve_2.applyContinuity(curve_1, {beta_1, beta_2, beta_3});\n    };\n\n    auto result = dlib::find_min_global(\n        tp,\n        [&](double x0, double x1, double x2, double x3) {\n          return evaluate({x0, x1, x2, x3});\n        },\n        {0.0, 0, 0.0, 0.0}, {3, 3, 3, 3}, opt_max_duration);\n    applyParams({result.x(0), result.x(1), result.x(2), result.x(3)}, *curve_1, *curve_2);\n  }\n\n  scene->update();\n  updatePlot();\n}\n\nvoid MainWindow::updatePlot()\n{\n  const QString _max(u8\"\\u2098\\u2090\\u2093\");\n  const QString _sim(u8\"\\u209b\\u1d62\\u2098\");\n\n  Data data = calculateData(*curve_1, *curve_2);\n  int N = ui->vehicle->topLevelItemCount();\n  static const QVector<QColor> matlab_colors(\n      {{0, 114, 189}, {217, 83, 25}, {237, 177, 32}, {126, 47, 142}, {119, 172, 48}, {77, 190, 238}, {162, 20, 47}});\n\n  ////// PLOTANJE\n  QPen pen;\n  pen.setStyle(Qt::DashLine);\n  static QCPItemStraightLine* infLine1 = new QCPItemStraightLine(ui->plot1);\n  static QCPItemStraightLine* infLine2 = new QCPItemStraightLine(ui->plot2);\n  infLine1->setPen(pen);\n  infLine2->setPen(pen);\n  infLine1->point1->setCoords(data.s1.back(), 0); // location of point 1 in plot coordinate\n  infLine1->point2->setCoords(data.s1.back(), 1); // location of point 2 in plot coordinate\n  infLine2->point1->setCoords(data.s1.back(), 0); // location of point 1 in plot coordinate\n  infLine2->point2->setCoords(data.s1.back(), 1); // location of point 2 in plot coordinate\n\n  /// plot brzina\n  {\n    constexpr int n_v = 4;\n    while (ui->plot1->graphCount() < 4 * N + n_v)\n      ui->plot1->addGraph();\n    while (ui->plot1->graphCount() > 4 * N + n_v)\n      ui->plot1->removeGraph(ui->plot1->graphCount() - 1);\n\n    auto g_v1 = ui->plot1->graph(0);\n    auto g_v2 = ui->plot1->graph(1);\n    auto g_v_sim1 = ui->plot1->graph(2);\n    auto g_v_sim2 = ui->plot1->graph(3);\n\n    g_v1->setData(data.s1, data.v1, true);\n    g_v2->setData(data.s2, data.v2, true);\n    g_v_sim1->setData(data.s1, data.v_sim1, true);\n    g_v_sim2->setData(data.s2, data.v_sim2, true);\n\n    g_v1->setName(\"v\" + _max);\n    g_v2->removeFromLegend();\n    g_v_sim1->setName(\"v\" + _sim);\n    g_v_sim2->removeFromLegend();\n\n    pen.setStyle(Qt::SolidLine);\n    pen.setColor(matlab_colors[0]);\n    pen.setWidth(3);\n    g_v1->setPen(pen);\n    g_v2->setPen(pen);\n    pen.setStyle(Qt::DashLine);\n    g_v_sim1->setPen(pen);\n    g_v_sim2->setPen(pen);\n\n    for (int k = 0; k < N; k++)\n    {\n      auto g_w_v1 = ui->plot1->graph(n_v + 4 * k);\n      auto g_w_v2 = ui->plot1->graph(n_v + 4 * k + 1);\n      auto g_w_v_sim1 = ui->plot1->graph(n_v + 4 * k + 2);\n      auto g_w_v_sim2 = ui->plot1->graph(n_v + 4 * k + 3);\n\n      g_w_v1->setName(\"w\" + QString::number(k + 1) + _max);\n      g_w_v2->removeFromLegend();\n      g_w_v_sim1->setName(\"w\" + QString::number(k + 1) + _sim);\n      g_w_v_sim2->removeFromLegend();\n\n      g_w_v1->setData(data.s1, data.v_w1[k], true);\n      g_w_v2->setData(data.s2, data.v_w2[k], true);\n      g_w_v_sim1->setData(data.s1, data.v_w_sim1[k], true);\n      g_w_v_sim2->setData(data.s2, data.v_w_sim2[k], true);\n\n      pen.setWidth(1);\n      pen.setColor(matlab_colors[k + 1]);\n      pen.setStyle(Qt::SolidLine);\n      g_w_v1->setPen(pen);\n      g_w_v2->setPen(pen);\n      pen.setStyle(Qt::DashLine);\n      g_w_v_sim1->setPen(pen);\n      g_w_v_sim2->setPen(pen);\n    }\n\n    ui->plot1->rescaleAxes();\n    ui->plot1->yAxis->scaleRange(1.05);\n    ui->plot1->replot();\n  }\n\n  /// plot kutnih brzina\n  {\n    constexpr int n_w = 4;\n    while (ui->plot2->graphCount() < 4 * N + n_w)\n    {\n      ui->plot2->addGraph();\n      ui->plot2->addGraph(ui->plot2->xAxis, ui->plot2->yAxis2);\n    }\n    while (ui->plot2->graphCount() > 4 * N + n_w)\n      ui->plot2->removeGraph(ui->plot2->graphCount() - 1);\n\n    auto g_theta1 = ui->plot2->graph(0);\n    auto g_theta2 = ui->plot2->graph(2);\n    auto g_w_sim1 = ui->plot2->graph(1);\n    auto g_w_sim2 = ui->plot2->graph(3);\n\n    g_theta1->setName(u8\"\\u03b8\");\n    g_theta2->removeFromLegend();\n    g_w_sim1->setName(u8\"\\u03c9\" + _sim);\n    g_w_sim2->removeFromLegend();\n\n    g_theta1->setData(data.s1, data.theta1, true);\n    g_theta2->setData(data.s2, data.theta2, true);\n    g_w_sim1->setData(data.s1, data.w_sim1, true);\n    g_w_sim2->setData(data.s2, data.w_sim2, true);\n\n    pen.setStyle(Qt::SolidLine);\n    pen.setColor(matlab_colors[0]);\n    pen.setWidth(3);\n    g_theta1->setPen(pen);\n    g_theta2->setPen(pen);\n    pen.setStyle(Qt::DashLine);\n    g_w_sim1->setPen(pen);\n    g_w_sim2->setPen(pen);\n\n    for (int k = 0; k < N; k++)\n    {\n      auto g_delta1 = ui->plot2->graph(n_w + 4 * k + 0);\n      auto g_delta2 = ui->plot2->graph(n_w + 4 * k + 2);\n      auto g_w_w_sim1 = ui->plot2->graph(n_w + 4 * k + 1);\n      auto g_w_w_sim2 = ui->plot2->graph(n_w + 4 * k + 3);\n\n      g_delta1->setName(u8\"\\u03b4\" + QString::number(k + 1));\n      g_delta2->removeFromLegend();\n      g_w_w_sim1->setName(u8\"\\u03c9w\" + QString::number(k + 1) + _sim);\n      g_w_w_sim2->removeFromLegend();\n\n      g_delta1->setData(data.s1, data.delta1[k], true);\n      g_delta2->setData(data.s2, data.delta2[k], true);\n      g_w_w_sim1->setData(data.s1, data.w_w_sim1[k], true);\n      g_w_w_sim2->setData(data.s2, data.w_w_sim2[k], true);\n\n      pen.setStyle(Qt::SolidLine);\n      pen.setWidth(1);\n      pen.setColor(matlab_colors[k + 1]);\n      g_delta1->setPen(pen);\n      g_delta2->setPen(pen);\n      pen.setStyle(Qt::DashLine);\n      g_w_w_sim1->setPen(pen);\n      g_w_w_sim2->setPen(pen);\n    }\n\n    ui->plot2->rescaleAxes();\n    ui->plot2->yAxis->scaleRange(1.05);\n    ui->plot2->yAxis2->scaleRange(1.05);\n    ui->plot2->replot();\n  }\n\n  auto print = [](double x) {\n    std::ostringstream res;\n    res.precision(3);\n\n    if (x < 0)\n      res << \"{\" << std::fixed << x << \"}\";\n    else\n      res << \"  \" << std::fixed << x << \" \";\n    return res;\n  };\n\n  std::stringstream bezier1, bezier2;\n  auto cp1 = curve_1->controlPoints();\n  auto cp2 = curve_1->controlPoints();\n  for (auto& p : cp1)\n  {\n    p = {std::round(p.x() * 10) / 1000., std::round(p.y() * 10) / 1000.};\n    bezier1 << \"( \" << print(p.x()).str() << \",&\\\\ \" << print(p.y()).str() << \" ) \\\\\\\\\\n\";\n  }\n  for (auto& p : cp1)\n  {\n    p = {std::round(p.x() * 10) / 1000., std::round(p.y() * 10) / 1000.};\n    bezier2 << \"( \" << print(p.x()).str() << \",&\\\\ \" << print(p.y()).str() << \" ) \\\\\\\\\\n\";\n  }\n  cp1.back() = {std::round(cp1.back().x() * 10) / 1000., std::round(cp1.back().y() * 10) / 1000.};\n  bezier1 << \"( \" << print(cp1.back().x()).str() << \",&\\\\ \" << print(cp1.back().y()).str() << \" )\";\n  cp2.back() = {std::round(cp2.back().x() * 10) / 1000., std::round(cp2.back().y() * 10) / 1000.};\n  bezier2 << \"( \" << print(cp2.back().x()).str() << \",&\\\\ \" << print(cp2.back().y()).str() << \" )\";\n\n  ui->bezier1->setText(QString::fromStdString(bezier1.str()));\n  ui->bezier2->setText(QString::fromStdString(bezier2.str()));\n}\n\nMainWindow::Data MainWindow::calculateData(const Bezier::Curve& curve_1, const Bezier::Curve& curve_2, bool partial)\n{\n  ///////// DATA\n  ///\n  ///\n  ///\n  ///\n  constexpr double step = 0.005;\n  constexpr int samples = static_cast<int>(1. / step + 1);\n  constexpr double a = 0.5;\n  int N = ui->vehicle->topLevelItemCount();\n  Romb::MotionModes::MotionMode *mm_1, *mm_2;\n  double alpha_1 = ui->alpha1->value() * M_PI / 180;\n  double alpha_2 = ui->alpha2->value() * M_PI / 180;\n  double n_1 = ui->n1->value();\n  double n_2 = ui->n2->value();\n  double v_max_1 = ui->vmax1->value() * 100;\n  double v_max_2 = ui->vmax2->value() * 100;\n  switch (ui->mm1->currentIndex())\n  {\n  case 0:\n    mm_1 = new Romb::MotionModes::TangentAligned(alpha_1);\n    break;\n  case 1:\n    mm_1 = new Romb::MotionModes::Crab(alpha_1);\n    break;\n  case 2:\n    mm_1 = new Romb::MotionModes::Exponential(alpha_1, n_1);\n    break;\n  default:\n    mm_1 = new Romb::MotionModes::Exponential(alpha_1, -n_1);\n    break;\n  }\n  switch (ui->mm2->currentIndex())\n  {\n  case 0:\n    mm_2 = new Romb::MotionModes::TangentAligned(alpha_2);\n    break;\n  case 1:\n    mm_2 = new Romb::MotionModes::Crab(alpha_2);\n    break;\n  case 2:\n    mm_2 = new Romb::MotionModes::Exponential(alpha_1, n_2);\n    break;\n  default:\n    mm_2 = new Romb::MotionModes::Exponential(alpha_1, -n_2);\n    break;\n  }\n\n  Data results(N, samples, partial);\n\n  auto& t = results.t;\n  auto& s1 = results.s1;\n  auto& s2 = results.s2;\n  auto& v1 = results.v1;\n  auto& v2 = results.v2;\n  auto& v_sim1 = results.v_sim1;\n  auto& v_sim2 = results.v_sim2;\n  auto& w_sim1 = results.w_sim1;\n  auto& w_sim2 = results.w_sim2;\n  auto& theta1 = results.theta1;\n  auto& theta2 = results.theta2;\n  auto& delta1 = results.delta1;\n  auto& delta2 = results.delta2;\n  auto& v_w1 = results.v_w1;\n  auto& v_w2 = results.v_w2;\n  auto& v_w_sim1 = results.v_w_sim1;\n  auto& v_w_sim2 = results.v_w_sim2;\n  auto& w_w_sim1 = results.w_w_sim1;\n  auto& w_w_sim2 = results.w_w_sim2;\n\n  double S = curve_1.length() / 100;\n\n  /////////// izracun limita brzine\n  ///\n  ///\n  ///\n  ///\n  for (int idx = 0; idx < samples; idx++)\n  {\n    t[idx] = idx * step;\n    s1[idx] = curve_1.length(t[idx]) / 100;\n    s2[idx] = S + curve_2.length(t[idx]) / 100;\n    v1[idx] = v_max_1;\n    v2[idx] = v_max_2;\n\n    for (int k = 0; k < N; k++)\n    {\n      auto wheel = static_cast<Wheel*>(ui->vehicle->topLevelItem(k));\n\n      // single wheel limit #1\n      v_w1[k][idx] = wheel->vMax(curve_1, mm_1, t[idx]);\n      if (v_w1[k][idx] < v1[idx])\n        v1[idx] = v_w1[k][idx];\n\n      // single wheel limit #2\n      v_w2[k][idx] = wheel->vMax(curve_2, mm_2, t[idx]);\n      if (v_w2[k][idx] < v2[idx])\n        v2[idx] = v_w2[k][idx];\n    }\n    v1[idx] /= 100;\n    v2[idx] /= 100;\n\n    // combined speed limit\n    for (int k = 0; k < N; k++)\n    {\n      v_w1[k][idx] = static_cast<Wheel*>(ui->vehicle->topLevelItem(k))->Rv(curve_1, mm_1, t[idx]) * v1[idx];\n      v_w2[k][idx] = static_cast<Wheel*>(ui->vehicle->topLevelItem(k))->Rv(curve_2, mm_2, t[idx]) * v2[idx];\n    }\n  }\n\n  //////// simulacija brzine\n  ///\n  ///\n  ///\n  ///\n  QVector<double> v_full = v1;\n  QVector<double> s_full = s1;\n\n  v_full.append(v2);\n  s_full.append(s2);\n\n  int last_idx = std::numeric_limits<int>::infinity();\n\n  auto fill_sim = [&](double v, int idx) {\n    auto fill_all = [&](double v, int idx) {\n      auto& v_w_sim = idx < samples ? v_w_sim1 : v_w_sim2;\n      auto& curve = idx < samples ? curve_1 : curve_2;\n      auto& mm = idx < samples ? mm_1 : mm_2;\n      idx = idx < samples ? idx : idx - samples;\n\n      for (int k = 0; k < N; k++)\n      {\n        auto wheel = static_cast<Wheel*>(ui->vehicle->topLevelItem(k));\n        v_w_sim[k][idx] = wheel->Rv(curve, mm, t[idx]) * v;\n      }\n    };\n\n    for (int k = last_idx + 1; k <= idx; k++)\n    {\n      if (k == samples)\n      {\n        v_sim2[0] = v_sim1[k - 1];\n        fill_all(v_sim2[0], k);\n      }\n      else\n      {\n        double dS = s_full[k] - s_full[k - 1];\n        auto& v_sim = k < samples ? v_sim1 : v_sim2;\n        int temp_idx = k < samples ? k : k - samples;\n        if (v > v_sim[temp_idx - 1])\n          v_sim[temp_idx] = std::min(v, std::sqrt(v_sim[temp_idx - 1] * v_sim[temp_idx - 1] + 2 * a * dS));\n        else\n          v_sim[temp_idx] = std::max(v, std::sqrt(v_sim[temp_idx - 1] * v_sim[temp_idx - 1] - 2 * a * dS));\n        fill_all(v_sim[temp_idx], k);\n      }\n    }\n\n    last_idx = idx;\n  };\n\n  std::function<void(int, double, int, double)> d_and_c = [&](int idx1, double v_1, int idx3, double v_3) {\n    if (idx1 + 1 == idx3)\n    {\n      fill_sim(v_1, idx1);\n      return;\n    }\n\n    int idx2 =\n        static_cast<int>(std::min_element(v_full.begin() + idx1 + 1, v_full.begin() + idx3 - 1) - v_full.begin());\n\n    double v_reachable_1 = std::sqrt(v_1 * v_1 + 2 * a * (s_full[idx2] - s_full[idx1]));\n    double v_reachable_2 = std::sqrt(v_3 * v_3 + 2 * a * (s_full[idx3] - s_full[idx2]));\n\n    if (v_reachable_1 > std::min(v_reachable_2, v_full[idx2]))\n      d_and_c(idx1, v_1, idx2, std::min({v_reachable_1, v_reachable_2, v_full[idx2]}));\n    else\n      fill_sim(v_1, idx1);\n\n    if (v_reachable_2 > std::min(v_reachable_1, v_full[idx2]))\n      d_and_c(idx2, std::min({v_reachable_1, v_reachable_2, v_full[idx2]}), idx3, v_3);\n    else\n      fill_sim(std::min({v_reachable_1, v_reachable_2, v_full[idx2]}), idx2);\n  };\n\n  d_and_c(0, 0.0, 2 * samples - 1, 0.0);\n  fill_sim(0.0, 2 * samples - 1);\n\n  // return if only speed sim is wanted\n  if (partial)\n    return results;\n\n  /////////// angular velocity and orientation sim\n  ///\n  ///\n  ///\n  ///\n  ///\n\n  for (int idx = 0; idx < samples; idx++)\n  {\n    theta1[idx] = mm_1->phi(curve_1, t[idx]) * 180 / M_PI;\n    theta2[idx] = mm_2->phi(curve_2, t[idx]) * 180 / M_PI;\n    w_sim1[idx] =\n        v_sim1[idx] * mm_1->phiDerived(curve_1, t[idx]) / curve_1.derivativeAt(t[idx]).norm() * 100 * 180 / M_PI;\n    w_sim2[idx] =\n        v_sim2[idx] * mm_2->phiDerived(curve_2, t[idx]) / curve_2.derivativeAt(t[idx]).norm() * 100 * 180 / M_PI;\n\n    for (int k = 0; k < N; k++)\n    {\n      auto wheel = static_cast<Wheel*>(ui->vehicle->topLevelItem(k));\n      delta1[k][idx] = wheel->delta(curve_1, mm_1, t[idx]) * 180 / M_PI;\n      delta2[k][idx] = wheel->delta(curve_2, mm_2, t[idx]) * 180 / M_PI;\n      w_w_sim1[k][idx] = v_sim1[idx] * wheel->Rw(curve_1, mm_1, t[idx]) * 100 * 180 / M_PI;\n      w_w_sim2[k][idx] = v_sim2[idx] * wheel->Rw(curve_2, mm_2, t[idx]) * 100 * 180 / M_PI;\n    }\n  }\n\n  return results;\n}\n\nMainWindow::Data::Data(int N, int samples, bool partial)\n{\n  t.resize(samples);\n  s1.resize(samples);\n  s2.resize(samples);\n  v1.resize(samples);\n  v2.resize(samples);\n\n  v_sim1.resize(samples);\n  v_sim2.resize(samples);\n  v_w1.resize(N);\n  v_w2.resize(N);\n  v_w_sim1.resize(N);\n  v_w_sim2.resize(N);\n  if (!partial)\n  {\n    theta1.resize(samples);\n    theta2.resize(samples);\n    w_sim1.resize(samples);\n    w_sim2.resize(samples);\n    delta1.resize(N);\n    delta2.resize(N);\n    w_w_sim1.resize(N);\n    w_w_sim2.resize(N);\n  }\n\n  for (int k = 0; k < N; k++)\n  {\n    v_w1[k].resize(samples);\n    v_w2[k].resize(samples);\n    v_w_sim1[k].resize(samples);\n    v_w_sim2[k].resize(samples);\n    if (!partial)\n    {\n      delta1[k].resize(samples);\n      delta2[k].resize(samples);\n      w_w_sim1[k].resize(samples);\n      w_w_sim2[k].resize(samples);\n    }\n  }\n}\n", "meta": {"hexsha": "d4a3145f7fb5b8c996f9e9435d1aeb510d5a8f6a", "size": 30062, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mainwindow.cpp", "max_stars_repo_name": "romb-technologies/path_continuity", "max_stars_repo_head_hexsha": "b0300df60d3fc7bc08f7f77d48a555b05ef030c1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mainwindow.cpp", "max_issues_repo_name": "romb-technologies/path_continuity", "max_issues_repo_head_hexsha": "b0300df60d3fc7bc08f7f77d48a555b05ef030c1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-09T21:22:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-09T21:23:13.000Z", "max_forks_repo_path": "src/mainwindow.cpp", "max_forks_repo_name": "romb-technologies/path_continuity", "max_forks_repo_head_hexsha": "b0300df60d3fc7bc08f7f77d48a555b05ef030c1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7775280899, "max_line_length": 117, "alphanum_fraction": 0.6061805602, "num_tokens": 10119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4398710717663093}}
{"text": "/*\n * 根据2D图像和深度图生成点云\n * Author: YangQun\n * Date: 2018/5/9\n * Last Update:2018/5/9\n */\n// C++ 标准库\n#include <iostream>\n#include <string>\n#include <vector>\n\n// 第三方库头文件\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <Eigen/Eigen>\n#include <Eigen/Geometry>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n#include <pcl/common/transforms.h>\n#include <pcl/visualization/cloud_viewer.h>\n\n// 工程头文件\n#include \"generate_point_cloud.h\"\n#include \"param_reader.h\"\n\nusing namespace std;\n\n\nPointCloudGenerator::PointCloudGenerator(PinHoleCamera::Ptr cam, ParameterReader::Ptr param_reader)\n// viewer_(\"viewer\")\t// 初始化点云显示窗口的名字\n{\n\tcam_ = cam;\n\tis_show_ = param_reader->getParam<bool>(\"is_show_point_cloud\");\n\tis_save_ = param_reader->getParam<bool>(\"is_save_point_cloud\");\n\tgrid_size_ = param_reader->getParam<double>(\"voxel_grid\");\n\tis_filter_ = param_reader->getParam<bool>(\"is_filter\");\n\t\n\tif (is_filter_) {\n\t\tvoxel_.setLeafSize(grid_size_, grid_size_, grid_size_);\n\t}\n\t\n\tcloud_out_.reset(new PointCloud);\n\t\n\tif (is_show_) {\n\t\tviewer_ = new pcl::visualization::CloudViewer(\"viewer\");\n\t}\n\telse {\n\t\tviewer_ = nullptr;\n\t}\n}\n\nPointCloudGenerator::~PointCloudGenerator()\n{\n\tif (nullptr != viewer_) \n\t\tdelete viewer_;\n}\n\n\nPointCloud::Ptr PointCloudGenerator::generatePointCloud(Frame::Ptr frame)\n{\n    // 点云变量\n    // 使用智能指针，创建一个空点云。这种指针用完会自动释放。\n    PointCloud::Ptr cloud ( new PointCloud );\n    // 遍历深度图\n    for (int m = 0; m <  frame->depth_img_.rows; m++)\n        for (int n=0; n < frame->depth_img_.cols; n++)\n        {\n            // 获取深度图中(m,n)处的值\n            ushort d = frame->depth_img_.ptr<ushort>(m)[n];\n            // d 可能没有值，若如此，跳过此点\n            if (d == 0)\n\t\tcontinue;\n            // d 存在值，则向点云增加一个点\n            PointT p;\n\n            // 计算这个点的空间坐标\n            p.z = double(d) / cam_->factor();\n            p.x = (n - cam_->cx()) * p.z / cam_->fx();\n            p.y = (m - cam_->cy()) * p.z / cam_->fy();\n            \n            // 从rgb图像中获取它的颜色\n            // rgb是三通道的BGR格式图，所以按下面的顺序获取颜色\n            p.b = frame->rgb_img_.ptr<uchar>(m)[n*3];\n            p.g = frame->rgb_img_.ptr<uchar>(m)[n*3+1];\n            p.r = frame->rgb_img_.ptr<uchar>(m)[n*3+2];\n\n            // 把p加入到点云中\n            cloud->points.push_back( p );\n        }\n        \n\t// 设置点云\n\tcloud->height = 1;\n\tcloud->width = cloud->points.size();\n\t// cout<<\"point cloud size = \"<<cloud->points.size()<<endl;\n\tcloud->is_dense = false;\n\t\n// \tif (is_save_) {\n// \t\tpcl::io::savePCDFile( \"../data/pointcloud.pcd\", *cloud );\n// \t\tcout<<\"Point cloud saved.\"<<endl;\n// \t}\n\t\n// \tif (is_show_) {\n// \t\tviewer_->showCloud(cloud);\n// \t\t// while ( ! viewer_->wasStopped()) { }\n// \t}\n\t\n\t// 清除数据并退出\n\t// cloud->points.clear();\n\t\n\treturn cloud;\n}\n\nint PointCloudGenerator::joinPointCloud(Frame::Ptr frame)\n{\n\t// 转换成点云\n\tPointCloud::Ptr curr_cloud = generatePointCloud(frame);\n\t\n\t// 合并点云\n\tPointCloud::Ptr cloud_temp(new PointCloud);\n\tEigen::Matrix3d rotation_matrix = frame->T_c2w_.rotation_matrix();\n\tEigen::Vector3d translation_vector = frame->T_c2w_.translation();\n\tEigen::Isometry3d T = Eigen::Isometry3d::Identity();\n\tT.rotate(rotation_matrix);\n\tT.pretranslate(translation_vector);\n\tpcl::transformPointCloud(*curr_cloud, *cloud_temp, T.matrix());\t\t// 将当前点云变换到世界坐标系下\n\t*cloud_temp += *cloud_out_;\t\t\t\t\t\t\t\t\t// 在世界坐标系下将已有点云和当前帧点云进行拼接\n\tcloud_out_->clear();\t\t\t\t\t\t\t\t\t\t\t// 清空旧的世界点云数据\n\t\n\tif (is_filter_) {\n\t\t// 拼接之后的点云进行体素滤波降采样\n\t\tvoxel_.setInputCloud(cloud_temp);\n\t\tvoxel_.filter(*cloud_out_);\n\t}\n\telse {\n\t\tcloud_out_ = cloud_temp;\n\t}\n\t\n\t\n\t// 可视化\n\tif (is_show_) {\n\t\tviewer_->showCloud(cloud_out_);\n\t\t// while ( ! viewer.wasStopped()) { }\n\t}\n\t\n\treturn 0;\n}\n\nint PointCloudGenerator::savePointCloud()\n{\n\t// 保存成pcd文件\n\tif (is_save_) {\n\t\tpcl::io::savePCDFile(\"../data/joinPointCloud.pcd\", *cloud_out_);\n\t}\n\t\n\treturn 0;\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "fa5504f6909f7e0c62b1c9a7f0d797b5f193c792", "size": 3792, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/generate_point_cloud.cpp", "max_stars_repo_name": "YangQun1/Slamkit", "max_stars_repo_head_hexsha": "6ac967bd04b569a6645bbaba5ae67483ab2ae64b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-05-18T08:46:36.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-18T16:32:06.000Z", "max_issues_repo_path": "src/generate_point_cloud.cpp", "max_issues_repo_name": "YangQun1/Slamkit", "max_issues_repo_head_hexsha": "6ac967bd04b569a6645bbaba5ae67483ab2ae64b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/generate_point_cloud.cpp", "max_forks_repo_name": "YangQun1/Slamkit", "max_forks_repo_head_hexsha": "6ac967bd04b569a6645bbaba5ae67483ab2ae64b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.263803681, "max_line_length": 99, "alphanum_fraction": 0.6310654008, "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4398710541647257}}
{"text": "/* Copyright (C) 2017 IBM Corp.\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific\n * language governing permissions and limitations under the License. \n */\n/*********************************************************************\nvec_l: A module for handling vectors of type long\n**********************************************************************/\n#include <NTL/matrix.h>\n#include \"mat_l.h\"\n#include \"vec_l.h\"\n\n#include <NTL/new.h>\n#include <NTL/vec_long.h>\n\nNTL_CLIENT\n\n//x = a-b\nvoid sub(vec_l& x, const vec_l& a, const vec_l& b)\n{\n    long n = a.length();\n    if (b.length() != n) LogicError(\"vector sub: dimension mismatch\");\n    x.SetLength(n);\n\n    for (long i = 0; i < n; i++)\n        x[i] = a[i] - b[i];\n\n}\n\n//res = x*a, naive implementation\n\nvoid mul(long& res, const vec_l& x, const vec_l& a)\n{\n    long val;\n    long n = a.length();\n    long i;\n    val = 0;\n    for (i = 0; i < n; i++)\n    {\n        val += a.at(i)*x.at(i);\n    }\n    res = val;\n}\n\n//res = a-b\nvec_l operator-(const vec_l& a, const vec_l& b)\n{\n    vec_l res;\n    sub(res, a, b);\n    return res;\n    //NTL_OPT_RETURN(vec_l, res);\n}\n\n//res = a-b\nvec_l operator-(const vec_l& a, const long& b)\n{\n    vec_l res;\n\n    int n = a.length();\n    int i;\n    res.SetLength(n);\n    for (i = 0; i< n; i++)\n        //res.put(i,(a.get(i) - b));\n        res[i] = a[i] - b;\n    return res;\n    //NTL_OPT_RETURN(vec_l, res);\n}\n\n", "meta": {"hexsha": "b9a803df14890e878814536ac16897c35f6a9d7d", "size": 1822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vec_l.cpp", "max_stars_repo_name": "shaih/BPobfus", "max_stars_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-25T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T03:19:43.000Z", "max_issues_repo_path": "vec_l.cpp", "max_issues_repo_name": "shaih/BPobfus", "max_issues_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vec_l.cpp", "max_forks_repo_name": "shaih/BPobfus", "max_forks_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-12-23T04:03:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-12T07:42:29.000Z", "avg_line_length": 24.2933333333, "max_line_length": 71, "alphanum_fraction": 0.5609220637, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.43987105026513895}}
{"text": "// standard includes and external libraries\n#include <iostream>\n#include <random>\n#include <Eigen/Dense>\n#include <cmath>\n#include <fstream>\n#include <nlohmann/json.hpp>\n#include <ctime>\n// project includes\n#include \"abstractclasses.h\"\n#include \"bandit.h\"\n#include \"oful.h\"\n#include \"finitelinrep.h\"\n#include \"utils.h\"\n#include \"gzip.h\"\n\nusing json = nlohmann::json;\nusing namespace std;\nusing namespace Eigen;\n\nsize_t PREC = 4;   // for saving numbers are rounded to PREC decimals\nsize_t EVERY = 1;  // save EVERY round\n\nint main()\n{\n\n    int n_derank = 0;\n    int low_rank = 15;\n\n    const char *files[7] = { \"../../problem_data/jester/33/1/jester_post_d33_span33.npz\", \"../../problem_data/jester/33/1/jester_post_d26_span26.npz\", \"../../problem_data/jester/33/1/jester_post_d24_span24.npz\", \"../../problem_data/jester/33/1/jester_post_d23_span23.npz\", \"../../problem_data/jester/33/1/jester_post_d20_span20.npz\", \"../../problem_data/jester/33/1/jester_post_d17_span17.npz\", \"../../problem_data/jester/33/1/jester_post_d16_span16.npz\" };\n\n    const char *names[9] = {\"d=33\", \"d=26\", \"d=24\", \"d=23\", \"d=20\", \"d=17\", \"d=16\", \"d=16 (derank)\", \"d=17 (derank)\"};\n\n    std::time_t t = std::time(nullptr);\n    char MY_TIME[100];\n    std::strftime(MY_TIME, sizeof(MY_TIME), \"%Y%m%d%H%M%S\", std::localtime(&t));\n    std::cout << MY_TIME << '\\n';\n\n    typedef std::vector<std::vector<double>> vec2double;\n\n    int seed = time(NULL);\n    srand (seed);\n    cout << \"seed: \" << seed << endl;\n    int n_runs = 50, T = 1000000;\n    double delta = 0.01;\n    double reg_val = 1.;\n    double noise_std = 1.0;\n    double bonus_scale = 1.;\n    bool adaptive_ci = true;\n\n    std::vector<long> seeds(n_runs);\n    std::generate(seeds.begin(), seeds.end(), [] ()\n    {\n        return rand();\n    });\n\n    for (int j = 0; j < 7 + n_derank; j++) {\n\n    // load reference representation\n\n    auto start = TIC();\n    // FiniteLinearRepresentation reference_rep=flr_loadjson(\"jester_post_d33_span33.json\", noise_std, seed);\n    FiniteLinearRepresentation reference_rep=flr_loadnpz(\"../../problem_data/jester/33/1/jester_post_d33_span33.npz\", noise_std, seed,\"features\", \"theta\");\n    auto tottime = TOC(start);\n    int reference_rep_dim = reference_rep.features_dim();\n    cout << \"Loaded in \" << tottime << endl;\n    cout << \"Ref_rep.dim: \" << reference_rep_dim << endl;\n\n    // load representation for OFUL\n    start = TIC();\n    // FiniteLinearRepresentation oful_rep = flr_loadjson(\"A.json\", noise_std, seed);\n\n    int l = j;\n    if(j >= 7) {\n\tl = 7 + 6 - j;\n    }\n    FiniteLinearRepresentation oful_rep = flr_loadnpz(files[l], noise_std, seed, \"features\", \"theta\");\n\n    if(j >= 7) {\n        oful_rep = derank_hls(oful_rep, low_rank, false, true, true);\n    }\n    //oful_rep.normalize_features(10);\n\n    tottime = TOC(start);\n    int oful_rep_dim = oful_rep.features_dim();\n    cout << \"Loaded in \" << tottime << endl;\n    cout << \"OFUL_rep.dim: \" << oful_rep_dim << endl;\n\n\n    cout << \"Equal? \" << reference_rep.is_equal(oful_rep, 1e-3) << endl;\n\n    //just OFUL\n    vec2double regrets, pseudo_regrets;\n\n    #pragma omp parallel for\n    for (int i = 0; i < n_runs; ++i)\n    {\n        OFUL<int> localg(oful_rep, reg_val, noise_std, bonus_scale, delta, adaptive_ci);\n        // create same representation but with different seed\n        FiniteLinearRepresentation lrep = reference_rep.copy(seeds[i]);\n        ContBanditProblem<int> prb(lrep, localg);\n        prb.reset();\n        auto start = TIC();\n        prb.run(T);\n        auto tottime = TOC(start);\n        cout << \"time(\" << i << \"): \" << tottime << endl;\n\n        // store regret and pseudo regret\n        regrets.push_back(prb.instant_regret);\n        pseudo_regrets.push_back(prb.exp_instant_regret);\n\n        // save in compressed json\n        save_vector_csv_gzip(regrets, \"OFUL-\"+std::string(names[j])+\"_regrets.csv.gz\", EVERY, PREC);\n        save_vector_csv_gzip(pseudo_regrets, \"OFUL-\"+std::string(names[j])+\"_pseudoregrets.csv.gz\", EVERY, PREC);\n    }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "28abe2821c0c8d09848a999dc745a491bbb212ad", "size": 4020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/oful_jester.cpp", "max_stars_repo_name": "T3p/hidden-features", "max_stars_repo_head_hexsha": "7d3c27ab513e5a4c6a10c7550dc6363bd7735266", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/oful_jester.cpp", "max_issues_repo_name": "T3p/hidden-features", "max_issues_repo_head_hexsha": "7d3c27ab513e5a4c6a10c7550dc6363bd7735266", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/oful_jester.cpp", "max_forks_repo_name": "T3p/hidden-features", "max_forks_repo_head_hexsha": "7d3c27ab513e5a4c6a10c7550dc6363bd7735266", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5, "max_line_length": 457, "alphanum_fraction": 0.6407960199, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.43983706372037396}}
{"text": "/*\n * odeint_rk4_phase_lattice.cpp\n *\n * Copyright 2011 Mario Mulansky\n * Copyright 2012 Karsten Ahnert\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n#include <cmath>\n\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint/stepper/runge_kutta4_classic.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\n#include <boost/numeric/odeint/algebra/array_algebra.hpp>\n\n#include \"rk_performance_test_case.hpp\"\n\n#include \"phase_lattice.hpp\"\n\nconst size_t N = 1024;\n\ntypedef boost::array< double , N > state_type;\ntypedef boost::numeric::odeint::runge_kutta4_classic< state_type , double , state_type , double , boost::numeric::odeint::array_algebra> rk4_odeint_type;\n\nclass odeint_wrapper\n{\npublic:\n    void reset_init_cond()\n    {\n        for( size_t i = 0 ; i<N ; ++i )\n            m_x[i] = 2.0*3.1415927*rand() / RAND_MAX;\n        m_t = 0.0;\n    }\n\n    inline void do_step( const double dt )\n    {\n        m_stepper.do_step( phase_lattice<N>() , m_x , m_t , dt );\n        //m_t += dt;\n    }\n\n    double state( const size_t i ) const\n    { return m_x[i]; }\n    \nprivate:\n    state_type m_x;\n    double m_t;\n    rk4_odeint_type m_stepper;\n};\n\n\n\nint main()\n{\n    srand( 12312354 );\n\n    odeint_wrapper stepper;\n\n    run( stepper , 10000 , 1E-6 );\n}\n", "meta": {"hexsha": "1703b5c8aedf1763b61db9bab52ce584dacc660e", "size": 1374, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/performance/odeint_rk4_phase_lattice.cpp", "max_stars_repo_name": "cooparation/caffe-android", "max_stars_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/performance/odeint_rk4_phase_lattice.cpp", "max_issues_repo_name": "cooparation/caffe-android", "max_issues_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/performance/odeint_rk4_phase_lattice.cpp", "max_forks_repo_name": "cooparation/caffe-android", "max_forks_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 21.1384615385, "max_line_length": 153, "alphanum_fraction": 0.6703056769, "num_tokens": 408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.43975382551593645}}
{"text": "#ifndef OITK_CHESSBOARDSAMPLECONSENSUS_H\n#define OITK_CHESSBOARDSAMPLECONSENSUS_H\n\n#include <cmath>\n#include <Eigen/Core>\n#include <pcl/sample_consensus/sac_model.h>\n\nnamespace oitk\n{\n    inline void compressChessboardModel(Eigen::VectorXf &model,\n        const Eigen::Vector3f &plane, const Eigen::Vector3f &origin, const Eigen::Vector3f &xdirection)\n    {\n        model.resize(6);\n        model.head(3) = origin;\n        // model.data()[3] = plane.data()[0] / plane.data()[2];\n        model[3] = plane[0] / plane[2];\n        model[4] = plane[1] / plane[2];\n\n        Eigen::Vector3f absolute;\n        absolute << 1, 0, 0;\n        Eigen::Vector3f globalxdir = plane.cross(absolute);\n        Eigen::Vector3f globalydir = plane.cross(globalxdir);\n        \n        model[5] = atan2f(xdirection.dot(globalydir) / globalydir.norm(),\n                          xdirection.dot(globalxdir) / globalxdir.norm());\n    }\n\n    inline void decompressChessboardModel(const Eigen::VectorXf &model,\n        Eigen::Vector3f &plane, Eigen::Vector3f &origin, Eigen::Vector3f &xdirection)\n    {\n        origin = model.head(3);\n        plane[0] = model[3];\n        plane[1] = model[4];\n        plane[2] = 1;\n        plane /= plane.norm();\n\n        Eigen::Vector3f absolute;\n        absolute << 1, 0, 0;\n        Eigen::Vector3f globalxdir = plane.cross(absolute);\n        Eigen::Vector3f globalydir = plane.cross(globalxdir);\n        xdirection = globalxdir * cos(model[5]) + globalydir * sin(model[5]);\n        xdirection /= xdirection.norm();\n    }\n\n    template <typename PointT>\n    class SampleConsensusChessboard : public pcl::SampleConsensusModel<PointT>\n    {\n    public:\n        typedef typename pcl::SampleConsensusModel<PointT>::PointCloud PointCloud;\n        typedef typename pcl::SampleConsensusModel<PointT>::PointCloudPtr PointCloudPtr;\n        typedef typename pcl::SampleConsensusModel<PointT>::PointCloudConstPtr PointCloudConstPtr;\n        typedef boost::shared_ptr<SampleConsensusChessboard> Ptr;\n\n    private:\n        int _pattern_size;\n        float _board_size, _edge_size, _rand_rate, _hole_size;\n        Eigen::Vector3f _plane_coefficients;\n\n        virtual bool isSampleGood(const std::vector<int> &samples) const override\n        {\n            if (samples.size() < 2)\n                return false;\n\n            // Get the values at the two points\n            const Eigen::Map<const Eigen::Vector3f> p0 = input_->points[samples[0]].getVector3fMap();\n            const Eigen::Map<const Eigen::Vector3f> p1 = input_->points[samples[1]].getVector3fMap();\n            Eigen::Vector3f segment = (p1 - p0);\n\n            constexpr float sq2 = 1.5; // a bit larger than sqrt(2)\n            if (segment.norm() > _board_size * sq2)\n                return false;\n\n            return true;\n        }\n\n        inline float rndHalf()\n        {\n            constexpr int mod = 1024;\n            return (rnd() % mod - (mod >> 1)) / (float)mod;\n        }\n\n        inline float distanceToHoleEdge(const float &relative_coord)\n        {\n            // XXX: Assert relative_coord is positive\n            float times = relative_coord / (_hole_size * 2)\n                + ((_pattern_size / 2 + 1) % 2 == 0 ? 0.25 : -0.25);\n            times = times - (int)times;\n            if (times < 0.25)\n                return times * _hole_size * 2;\n            else if (times < 0.5)\n                return (0.5 - times) * _hole_size * 2;\n            else return 0;\n        }\n\n        inline float distanceToBoard(const float &board_x, const float &board_y)\n        {\n            // XXX: Assert board_x and board_y is positive\n            float outer_edge = _board_size / 2;\n            float dx = board_x - outer_edge;\n            float dy = board_y - outer_edge;\n            if (dx > 0)\n            {\n                if (dy > 0)\n                    return sqrt(dx * dx + dy * dy);\n                else\n                    return dx;\n            }\n            else if (board_y > outer_edge)\n                return dy;\n            else\n                return std::min(distanceToHoleEdge(board_x),\n                           distanceToHoleEdge(board_y));\n        }\n\n    protected:\n        using pcl::SampleConsensusModel<PointT>::model_name_;\n        using pcl::SampleConsensusModel<PointT>::input_;\n        using pcl::SampleConsensusModel<PointT>::indices_;\n        using pcl::SampleConsensusModel<PointT>::error_sqr_dists_;\n        using pcl::SampleConsensusModel<PointT>::sample_size_;\n        using pcl::SampleConsensusModel<PointT>::model_size_;\n        using pcl::SampleConsensusModel<PointT>::rnd;\n\n    private:\n        /** \\brief Functor for the optimization function */\n        struct OptimizationFunctor : pcl::Functor<float>\n        {\n            OptimizationFunctor(int n_data_points, SampleConsensusChessboard<PointT> *model) :\n                pcl::Functor<float>(n_data_points), model_(model) {}\n\n            int operator() (const Eigen::VectorXf &x, Eigen::VectorXf &fvec) const\n            {\n                // TODO: Implement\n            }\n\n            SampleConsensusChessboard<PointT> *model_;\n        };\n\n    public:\n        SampleConsensusChessboard(const PointCloudConstPtr &cloud,\n            int pattern_size, float board_size, float edge_size,\n            Eigen::VectorXf plane_coeffs, bool random = false)\n            : pcl::SampleConsensusModel<PointT>(cloud, random),\n            _pattern_size(pattern_size), _board_size(board_size), _edge_size(edge_size),\n            _hole_size((board_size - 2 * edge_size) / (pattern_size - 1)), _rand_rate(1)\n        {\n            model_name_ = \"SampleConsensusChessboard\";\n            sample_size_ = 2;\n            model_size_ = 6;\n\n            if (plane_coeffs.size() < 3)\n                cerr << \"Wrong plane coefficients input. Please estimate the plane before finding the board!\" << endl;\n            for (int i = 0; i < 3; i++)\n                _plane_coefficients[i] = plane_coeffs[i];\n            _plane_coefficients /= _plane_coefficients.norm();\n        }\n\n        SampleConsensusChessboard(const PointCloudConstPtr &cloud, const std::vector<int> &indices,\n            int pattern_size, float board_size, float edge_size,\n            Eigen::VectorXf plane_coeffs, bool random = false)\n            : pcl::SampleConsensusModel<PointT>(cloud, indices, random),\n            _pattern_size(pattern_size), _board_size(board_size), _edge_size(edge_size),\n            _hole_size((board_size - 2 * edge_size) / (pattern_size - 1)), _rand_rate(1)\n        {\n            model_name_ = \"SampleConsensusChessboard\";\n            sample_size_ = 2;\n            model_size_ = 6;\n\n            if (plane_coeffs.size() < 3)\n                cerr << \"Wrong plane coefficients input. Please estimate the plane before finding the board!\" << endl;\n            for (int i = 0; i < 3; i++)\n                _plane_coefficients[i] = plane_coeffs[i];\n            _plane_coefficients /= _plane_coefficients.norm();\n        }\n\n        virtual bool computeModelCoefficients(const std::vector<int> &samples,\n            Eigen::VectorXf &model_coefficients) override\n        {\n            pcl::Array3fMapConst p0 = input_->points[samples[0]].getArray3fMap();\n            pcl::Array3fMapConst p1 = input_->points[samples[1]].getArray3fMap();\n\n            Eigen::Array3f origin = (p0 + p1) / 2;\n            origin += (p0 - origin) * rndHalf() * _rand_rate;\n            Eigen::Vector3f diameter = p1 - p0;\n            Eigen::Vector3f adiameter = _plane_coefficients.cross(diameter);\n\n            Eigen::Vector3f xdirection = diameter / diameter.norm() * rndHalf() * _rand_rate\n                                       + adiameter / adiameter.norm() * rndHalf() * _rand_rate;\n            xdirection /= xdirection.norm();\n\n            compressChessboardModel(model_coefficients, _plane_coefficients, origin, xdirection);\n            return true;\n        }\n\n        virtual void optimizeModelCoefficients(const std::vector<int> &inliers,\n            const Eigen::VectorXf &model_coefficients,\n            Eigen::VectorXf &optimized_coefficients) override\n        {\n            // TODO: Implement\n            cerr << \"Not Implemented yet\" << endl;\n        }\n\n        virtual void getDistancesToModel(const Eigen::VectorXf &model_coefficients,\n            std::vector<double> &distances) override\n        {\n            distances.resize(indices_->size());\n\n            Eigen::Vector3f plane_normal, origin, xdirection, ydirection;\n            decompressChessboardModel(model_coefficients, plane_normal, origin, xdirection);\n            ydirection = plane_normal.cross(xdirection);\n\n            for (int idx = 0; idx < indices_->size(); idx++)\n            {\n                // Project to plane\n                Eigen::Vector3f direct_dist = \n                    input_->points[(*indices_)[idx]].getArray3fMap() - origin.array();\n                float zdist = direct_dist.dot(plane_normal);\n                direct_dist -= zdist * plane_normal;\n                float board_x = abs(direct_dist.dot(xdirection));\n                float board_y = abs(direct_dist.dot(ydirection));\n\n                // Calculate distance\n                float bdist = distanceToBoard(board_x, board_y);\n                // distances[idx] = sqrt(bdist * bdist + zdist * zdist);\n                distances[idx] = bdist; // Just consider the distance in board\n            }\n        }\n\n        virtual void selectWithinDistance(const Eigen::VectorXf &model_coefficients,\n            const double threshold, std::vector<int> &inliers) override\n        {\n            std::vector<double> distances;\n            getDistancesToModel(model_coefficients, distances);\n\n            int counter = 0;\n            inliers.resize(indices_->size());\n            error_sqr_dists_.resize(indices_->size());\n            for (int idx = 0;idx < distances.size(); idx++)\n            {\n                if (distances[idx] >= threshold) continue;\n                inliers[counter] = (*indices_)[idx];\n                error_sqr_dists_[counter] = distances[idx];\n                counter++;\n            }\n            inliers.resize(counter);\n            error_sqr_dists_.resize(counter);\n        }\n\n        virtual int countWithinDistance(const Eigen::VectorXf &model_coefficients,\n            const double threshold) override\n        {\n            std::vector<double> distances;\n            getDistancesToModel(model_coefficients, distances);\n\n            int counter = 0;\n            for (double distance : distances)\n                if (distance < threshold) counter++;\n            return counter;\n        }\n\n        virtual void projectPoints(const std::vector<int> &inliers,\n            const Eigen::VectorXf &model_coefficients,\n            PointCloud &projected_points,\n            bool copy_data_fields = true) override\n        {\n            // TODO: Implement\n            cerr << \"Not Implemented yet\" << endl;\n        }\n\n        virtual bool doSamplesVerifyModel(const std::set<int> &indices,\n            const Eigen::VectorXf &model_coefficients,\n            const double threshold) override\n        {\n            // TODO: Implement\n            cerr << \"Not Implemented yet\" << endl;\n            return false;\n        }\n\n        virtual pcl::SacModel getModelType() const override\n        {\n            cerr << \"SampleConsensusChessboard is not a sample consensus type built in pcl!\" << endl;\n            return pcl::SACMODEL_PLANE;\n        }\n\n        /** \\brief Set the randomization range of the board location\n          * \\param[in] rate the randomization range (0~1)\n          */\n        inline void setRandomRate(const float &rate)\n        {\n            _rand_rate = rate;\n        }\n\n        /** \\brief Get the randomization range of the board location\n          * \\param[out] rate the randomization range (0~1)\n          */\n        inline void getRandomRate(float &rate)\n        {\n            rate = _rand_rate;\n        }\n    };\n}\n\n\n#endif // OITK_CHESSBOARDSAMPLECONSENSUS_H", "meta": {"hexsha": "cba58a057c5b596931e12fbe23fef3449c802a49", "size": 11929, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "source/calibration/SampleConsensusChessBoard.hxx", "max_stars_repo_name": "cmpute/LRansacCalibrator", "max_stars_repo_head_hexsha": "afabfef98df397326ae02d5920b1c513961a9965", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T06:40:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T17:26:22.000Z", "max_issues_repo_path": "source/calibration/SampleConsensusChessBoard.hxx", "max_issues_repo_name": "cmpute/LRansacCalibrator", "max_issues_repo_head_hexsha": "afabfef98df397326ae02d5920b1c513961a9965", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/calibration/SampleConsensusChessBoard.hxx", "max_forks_repo_name": "cmpute/LRansacCalibrator", "max_forks_repo_head_hexsha": "afabfef98df397326ae02d5920b1c513961a9965", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2401315789, "max_line_length": 118, "alphanum_fraction": 0.5817755051, "num_tokens": 2754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105941403651, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.43975382009295977}}
{"text": "//  (C) Copyright John Maddock 2008.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_TR1_CMATH_HPP_INCLUDED\r\n#  define BOOST_TR1_CMATH_HPP_INCLUDED\r\n#  include <boost/tr1/detail/config.hpp>\r\n\r\n#ifdef BOOST_HAS_TR1_CMATH\r\n\r\n#  if defined(BOOST_HAS_INCLUDE_NEXT) && !defined(BOOST_TR1_DISABLE_INCLUDE_NEXT)\r\n#     include_next BOOST_TR1_HEADER(cmath)\r\n#  else\r\n#     include <boost/tr1/detail/config_all.hpp>\r\n#     include BOOST_TR1_HEADER(cmath)\r\n#  endif\r\n\r\n#else\r\n\r\n#include <boost/math/tr1.hpp>\r\n\r\nnamespace std{ namespace tr1{\r\n\r\nusing boost::math::tr1::assoc_laguerre;\r\nusing boost::math::tr1::assoc_laguerref;\r\nusing boost::math::tr1::assoc_laguerrel;\r\n// [5.2.1.2] associated Legendre functions:\r\nusing boost::math::tr1::assoc_legendre;\r\nusing boost::math::tr1::assoc_legendref;\r\nusing boost::math::tr1::assoc_legendrel;\r\n// [5.2.1.3] beta function:\r\nusing boost::math::tr1::beta;\r\nusing boost::math::tr1::betaf;\r\nusing boost::math::tr1::betal;\r\n// [5.2.1.4] (complete) elliptic integral of the first kind:\r\nusing boost::math::tr1::comp_ellint_1;\r\nusing boost::math::tr1::comp_ellint_1f;\r\nusing boost::math::tr1::comp_ellint_1l;\r\n// [5.2.1.5] (complete) elliptic integral of the second kind:\r\nusing boost::math::tr1::comp_ellint_2;\r\nusing boost::math::tr1::comp_ellint_2f;\r\nusing boost::math::tr1::comp_ellint_2l;\r\n// [5.2.1.6] (complete) elliptic integral of the third kind:\r\nusing boost::math::tr1::comp_ellint_3;\r\nusing boost::math::tr1::comp_ellint_3f;\r\nusing boost::math::tr1::comp_ellint_3l;\r\n#if 0\r\n// [5.2.1.7] confluent hypergeometric functions:\r\nusing boost::math::tr1::conf_hyperg;\r\nusing boost::math::tr1::conf_hypergf;\r\nusing boost::math::tr1::conf_hypergl;\r\n#endif\r\n// [5.2.1.8] regular modified cylindrical Bessel functions:\r\nusing boost::math::tr1::cyl_bessel_i;\r\nusing boost::math::tr1::cyl_bessel_if;\r\nusing boost::math::tr1::cyl_bessel_il;\r\n// [5.2.1.9] cylindrical Bessel functions (of the first kind):\r\nusing boost::math::tr1::cyl_bessel_j;\r\nusing boost::math::tr1::cyl_bessel_jf;\r\nusing boost::math::tr1::cyl_bessel_jl;\r\n// [5.2.1.10] irregular modified cylindrical Bessel functions:\r\nusing boost::math::tr1::cyl_bessel_k;\r\nusing boost::math::tr1::cyl_bessel_kf;\r\nusing boost::math::tr1::cyl_bessel_kl;\r\n// [5.2.1.11] cylindrical Neumann functions;\r\n// cylindrical Bessel functions (of the second kind):\r\nusing boost::math::tr1::cyl_neumann;\r\nusing boost::math::tr1::cyl_neumannf;\r\nusing boost::math::tr1::cyl_neumannl;\r\n// [5.2.1.12] (incomplete) elliptic integral of the first kind:\r\nusing boost::math::tr1::ellint_1;\r\nusing boost::math::tr1::ellint_1f;\r\nusing boost::math::tr1::ellint_1l;\r\n// [5.2.1.13] (incomplete) elliptic integral of the second kind:\r\nusing boost::math::tr1::ellint_2;\r\nusing boost::math::tr1::ellint_2f;\r\nusing boost::math::tr1::ellint_2l;\r\n// [5.2.1.14] (incomplete) elliptic integral of the third kind:\r\nusing boost::math::tr1::ellint_3;\r\nusing boost::math::tr1::ellint_3f;\r\nusing boost::math::tr1::ellint_3l;\r\n// [5.2.1.15] exponential integral:\r\nusing boost::math::tr1::expint;\r\nusing boost::math::tr1::expintf;\r\nusing boost::math::tr1::expintl;\r\n// [5.2.1.16] Hermite polynomials:\r\nusing boost::math::tr1::hermite;\r\nusing boost::math::tr1::hermitef;\r\nusing boost::math::tr1::hermitel;\r\n#if 0\r\n// [5.2.1.17] hypergeometric functions:\r\nusing boost::math::tr1::hyperg;\r\nusing boost::math::tr1::hypergf;\r\nusing boost::math::tr1::hypergl;\r\n#endif\r\n// [5.2.1.18] Laguerre polynomials:\r\nusing boost::math::tr1::laguerre;\r\nusing boost::math::tr1::laguerref;\r\nusing boost::math::tr1::laguerrel;\r\n// [5.2.1.19] Legendre polynomials:\r\nusing boost::math::tr1::legendre;\r\nusing boost::math::tr1::legendref;\r\nusing boost::math::tr1::legendrel;\r\n// [5.2.1.20] Riemann zeta function:\r\nusing boost::math::tr1::riemann_zeta;\r\nusing boost::math::tr1::riemann_zetaf;\r\nusing boost::math::tr1::riemann_zetal;\r\n// [5.2.1.21] spherical Bessel functions (of the first kind):\r\nusing boost::math::tr1::sph_bessel;\r\nusing boost::math::tr1::sph_besself;\r\nusing boost::math::tr1::sph_bessell;\r\n// [5.2.1.22] spherical associated Legendre functions:\r\nusing boost::math::tr1::sph_legendre;\r\nusing boost::math::tr1::sph_legendref;\r\nusing boost::math::tr1::sph_legendrel;\r\n// [5.2.1.23] spherical Neumann functions;\r\n// spherical Bessel functions (of the second kind):\r\nusing boost::math::tr1::sph_neumann;\r\nusing boost::math::tr1::sph_neumannf;\r\nusing boost::math::tr1::sph_neumannl;\r\n\r\n// types\r\nusing boost::math::tr1::double_t;\r\nusing boost::math::tr1::float_t;\r\n// functions\r\nusing boost::math::tr1::acosh;\r\nusing boost::math::tr1::acoshf;\r\nusing boost::math::tr1::acoshl;\r\nusing boost::math::tr1::asinh;\r\nusing boost::math::tr1::asinhf;\r\nusing boost::math::tr1::asinhl;\r\nusing boost::math::tr1::atanh;\r\nusing boost::math::tr1::atanhf;\r\nusing boost::math::tr1::atanhl;\r\nusing boost::math::tr1::cbrt;\r\nusing boost::math::tr1::cbrtf;\r\nusing boost::math::tr1::cbrtl;\r\nusing boost::math::tr1::copysign;\r\nusing boost::math::tr1::copysignf;\r\nusing boost::math::tr1::copysignl;\r\nusing boost::math::tr1::erf;\r\nusing boost::math::tr1::erff;\r\nusing boost::math::tr1::erfl;\r\nusing boost::math::tr1::erfc;\r\nusing boost::math::tr1::erfcf;\r\nusing boost::math::tr1::erfcl;\r\n#if 0\r\nusing boost::math::tr1::exp2;\r\nusing boost::math::tr1::exp2f;\r\nusing boost::math::tr1::exp2l;\r\n#endif\r\nusing boost::math::tr1::expm1;\r\nusing boost::math::tr1::expm1f;\r\nusing boost::math::tr1::expm1l;\r\n#if 0\r\nusing boost::math::tr1::fdim;\r\nusing boost::math::tr1::fdimf;\r\nusing boost::math::tr1::fdiml;\r\nusing boost::math::tr1::fma;\r\nusing boost::math::tr1::fmaf;\r\nusing boost::math::tr1::fmal;\r\n#endif\r\nusing boost::math::tr1::fmax;\r\nusing boost::math::tr1::fmaxf;\r\nusing boost::math::tr1::fmaxl;\r\nusing boost::math::tr1::fmin;\r\nusing boost::math::tr1::fminf;\r\nusing boost::math::tr1::fminl;\r\nusing boost::math::tr1::hypot;\r\nusing boost::math::tr1::hypotf;\r\nusing boost::math::tr1::hypotl;\r\n#if 0\r\nusing boost::math::tr1::ilogb;\r\nusing boost::math::tr1::ilogbf;\r\nusing boost::math::tr1::ilogbl;\r\n#endif\r\nusing boost::math::tr1::lgamma;\r\nusing boost::math::tr1::lgammaf;\r\nusing boost::math::tr1::lgammal;\r\n#if 0\r\nusing boost::math::tr1::llrint;\r\nusing boost::math::tr1::llrintf;\r\nusing boost::math::tr1::llrintl;\r\n#endif\r\nusing boost::math::tr1::llround;\r\nusing boost::math::tr1::llroundf;\r\nusing boost::math::tr1::llroundl;\r\nusing boost::math::tr1::log1p;\r\nusing boost::math::tr1::log1pf;\r\nusing boost::math::tr1::log1pl;\r\n#if 0\r\nusing boost::math::tr1::log2;\r\nusing boost::math::tr1::log2f;\r\nusing boost::math::tr1::log2l;\r\nusing boost::math::tr1::logb;\r\nusing boost::math::tr1::logbf;\r\nusing boost::math::tr1::logbl;\r\nusing boost::math::tr1::lrint;\r\nusing boost::math::tr1::lrintf;\r\nusing boost::math::tr1::lrintl;\r\n#endif\r\nusing boost::math::tr1::lround;\r\nusing boost::math::tr1::lroundf;\r\nusing boost::math::tr1::lroundl;\r\n#if 0\r\nusing boost::math::tr1::nan;\r\nusing boost::math::tr1::nanf;\r\nusing boost::math::tr1::nanl;\r\nusing boost::math::tr1::nearbyint;\r\nusing boost::math::tr1::nearbyintf;\r\nusing boost::math::tr1::nearbyintl;\r\n#endif\r\nusing boost::math::tr1::nextafter;\r\nusing boost::math::tr1::nextafterf;\r\nusing boost::math::tr1::nextafterl;\r\nusing boost::math::tr1::nexttoward;\r\nusing boost::math::tr1::nexttowardf;\r\nusing boost::math::tr1::nexttowardl;\r\n#if 0\r\nusing boost::math::tr1::remainder;\r\nusing boost::math::tr1::remainderf;\r\nusing boost::math::tr1::remainderl;\r\nusing boost::math::tr1::remquo;\r\nusing boost::math::tr1::remquof;\r\nusing boost::math::tr1::remquol;\r\nusing boost::math::tr1::rint;\r\nusing boost::math::tr1::rintf;\r\nusing boost::math::tr1::rintl;\r\n#endif\r\nusing boost::math::tr1::round;\r\nusing boost::math::tr1::roundf;\r\nusing boost::math::tr1::roundl;\r\n#if 0\r\nusing boost::math::tr1::scalbln;\r\nusing boost::math::tr1::scalblnf;\r\nusing boost::math::tr1::scalblnl;\r\nusing boost::math::tr1::scalbn;\r\nusing boost::math::tr1::scalbnf;\r\nusing boost::math::tr1::scalbnl;\r\n#endif\r\nusing boost::math::tr1::tgamma;\r\nusing boost::math::tr1::tgammaf;\r\nusing boost::math::tr1::tgammal;\r\nusing boost::math::tr1::trunc;\r\nusing boost::math::tr1::truncf;\r\nusing boost::math::tr1::truncl;\r\n// C99 macros defined as C++ templates\r\nusing boost::math::tr1::signbit;\r\nusing boost::math::tr1::fpclassify;\r\nusing boost::math::tr1::isfinite;\r\nusing boost::math::tr1::isinf;\r\nusing boost::math::tr1::isnan;\r\nusing boost::math::tr1::isnormal;\r\n#if 0\r\nusing boost::math::tr1::isgreater;\r\nusing boost::math::tr1::isgreaterequal;\r\nusing boost::math::tr1::isless;\r\nusing boost::math::tr1::islessequal;\r\nusing boost::math::tr1::islessgreater;\r\nusing boost::math::tr1::isunordered;\r\n#endif\r\n} } // namespaces\r\n\r\n#endif // BOOST_HAS_TR1_CMATH\r\n\r\n#endif // BOOST_TR1_CMATH_HPP_INCLUDED\r\n", "meta": {"hexsha": "414da2abb5b8a7dbc0e91f3b0d99d869e268c84e", "size": 8844, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/tr1/cmath.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/tr1/cmath.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/tr1/cmath.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 33.0, "max_line_length": 82, "alphanum_fraction": 0.7088421529, "num_tokens": 2983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.6825737279551494, "lm_q1q2_score": 0.43973113257670443}}
{"text": "#pragma once\n\n#include \"ArithmeticProgression.hpp\"\n#include \"Misc.hpp\"\n#include \"Reversed.hpp\"\n#include \"Sequences.hpp\"\n#include \"VectorHelpers.hpp\"\n#include \"detail/PartitionsDetail.hpp\"\n#include <boost/iterator/iterator_facade.hpp>\n\nnamespace discreture\n{\n\n////////////////////////////////////////////////////////////\n/// \\brief class of partitions of the number n.\n/// \\param IntType should be an integral type with enough space to store n and\n/// k. It can be signed or unsigned. # Example:\n///\n///\t partitions X(6);\n///\t\tfor (auto&& x : X)\n///\t\t\tcout << x << ' ';\n///\n/// Prints out:\n///\n/// \t[ 1 1 1 1 1 1 ] [ 2 1 1 1 1 ] [ 3 1 1 1 ] [ 2 2 1 1 ] [ 4 1 1 ] [ 3 2 1\n/// ] [ 2 2 2 ] [ 5 1 ] [ 4 2 ] [ 3 3 ] [ 6 ]\n////////////////////////////////////////////////////////////\ntemplate <class IntType = int, class RAContainerInt = std::vector<IntType>>\nclass Partitions\n{\npublic:\n    static_assert(std::is_integral<IntType>::value,\n                  \"Template parameter IntType must be integral\");\n    static_assert(std::is_signed<IntType>::value,\n                  \"Template parameter IntType must be signed\");\n    using value_type = RAContainerInt;\n    using partition = value_type;\n    using difference_type = std::ptrdiff_t;\n    using size_type = difference_type;\n    class iterator;\n    using const_iterator = iterator;\n    class reverse_iterator;\n    using const_reverse_iterator = reverse_iterator;\n\n    ////////////////////////////////////////////////////////////\n    /// \\brief Constructor\n    ///\n    /// \\param n is an integer >= 0\n    ///\n    ////////////////////////////////////////////////////////////\n    explicit Partitions(IntType n)\n        : n_(n), min_num_parts_(1), max_num_parts_(n), size_(calc_size(n))\n    {}\n\n    ////////////////////////////////////////////////////////////\n    /// \\brief Constructor\n    ///\n    /// \\param n is an integer >= 0\n    /// \\param numparts is an integer >= 1 and <= n\n    ///\n    ////////////////////////////////////////////////////////////\n    Partitions(IntType n, IntType numparts)\n        : n_(n)\n        , min_num_parts_(numparts)\n        , max_num_parts_(numparts)\n        , size_(calc_size(n, numparts))\n    {}\n\n    ////////////////////////////////////////////////////////////\n    /// \\brief Constructor\n    ///\n    /// \\param n is an integer >= 0\n    /// \\param minnumparts is an integer >= 1 and <= n\n    /// \\param maxnumparts is an integer >= minnumparts and <= n\n    ///\n    ////////////////////////////////////////////////////////////\n    Partitions(IntType n, IntType minnumparts, IntType maxnumparts)\n        : n_(n)\n        , min_num_parts_(minnumparts)\n        , max_num_parts_(maxnumparts)\n        , size_(calc_size(n, minnumparts, maxnumparts))\n    {}\n\n    ////////////////////////////////////////////////////////////\n    /// \\brief The total number of partitions\n    ///\n    /// \\return p_n\n    ///\n    ////////////////////////////////////////////////////////////\n    size_type size() const { return size_; }\n\n    IntType get_n() const { return n_; }\n\n    iterator begin() const { return iterator(n_, max_num_parts_); }\n\n    const iterator end() const\n    {\n        return iterator::make_invalid_with_id(size());\n    }\n\n    reverse_iterator rbegin() const\n    {\n        return reverse_iterator(n_, min_num_parts_);\n    }\n\n    const reverse_iterator rend() const\n    {\n        return reverse_iterator::make_invalid_with_id(size());\n    }\n\n    template <class Func>\n    void for_each(Func f) const\n    {\n        for (auto k : reversed(II(min_num_parts_, max_num_parts_ + 1)))\n        {\n            for_each(f, k);\n        }\n    }\n\n    ////////////////////////////////////////////////////////////\n    /// \\brief Bidirectional iterator class.\n    ////////////////////////////////////////////////////////////\n    class iterator\n        : public boost::iterator_facade<iterator, const partition&, boost::bidirectional_traversal_tag>\n    {\n    public:\n        iterator() : n_(0), data_() {}\n\n        explicit iterator(IntType n, IntType numparts)\n            : n_(n), data_(numparts, 1)\n        {\n            if (numparts > 0)\n                data_[0] = n - numparts + 1;\n        }\n\n        inline size_type ID() const { return ID_; }\n\n        // boost::iterator_facade provides all the public interface you need,\n        // like ++, etc.\n\n        static const iterator make_invalid_with_id(size_type id)\n        {\n            iterator it;\n            it.ID_ = id;\n            return it;\n        }\n\n    private:\n        void increment()\n        {\n            ++ID_;\n\n            next_partition(data_, n_);\n        }\n\n        void decrement()\n        {\n            --ID_;\n\n            prev_partition(data_, n_);\n        }\n\n        const partition& dereference() const { return data_; }\n\n        bool equal(const iterator& it) const { return it.ID() == ID(); }\n\n        difference_type distance_to(const iterator& lhs) const\n        {\n            return static_cast<difference_type>(lhs.ID()) - ID();\n        }\n\n    private:\n        size_type ID_{0};\n        IntType n_;\n        partition data_;\n\n        friend class boost::iterator_core_access;\n    }; // end class iterator\n\n    ////////////////////////////////////////////////////////////\n    /// \\brief Bidirectional iterator class.\n    ////////////////////////////////////////////////////////////\n    class reverse_iterator\n        : public boost::iterator_facade<reverse_iterator,\n                                        const partition&,\n                                        boost::bidirectional_traversal_tag>\n    {\n    public:\n        reverse_iterator() : n_(0), data_() {}\n\n        explicit reverse_iterator(IntType n, IntType numparts) : n_(n), data_()\n        {\n            last_with_given_number_of_parts(data_, n, numparts);\n        }\n\n        inline size_type ID() const { return ID_; }\n\n        // boost::iterator_facade provides all the public interface you need,\n        // like ++, etc.\n\n        static const reverse_iterator make_invalid_with_id(size_type id)\n        {\n            reverse_iterator it;\n            it.ID_ = id;\n            return it;\n        }\n\n    private:\n        void increment()\n        {\n            ++ID_;\n\n            prev_partition(data_, n_);\n        }\n\n        void decrement()\n        {\n            --ID_;\n\n            next_partition(data_, n_);\n        }\n\n        const partition& dereference() const { return data_; }\n\n        bool equal(const reverse_iterator& it) const { return it.ID() == ID(); }\n\n        difference_type distance_to(const reverse_iterator& lhs) const\n        {\n            return static_cast<difference_type>(lhs.ID()) - ID();\n        }\n\n    private:\n        size_type ID_{0};\n        IntType n_;\n        partition data_;\n\n        friend class boost::iterator_core_access;\n    }; // end class reverse_iterator\n\n    // **************** Begin static functions\n    static void next_partition(partition& data, IntType n)\n    {\n        size_t t = data.size();\n\n        if (t < 2)\n        {\n            return;\n        }\n\n        if (data.front() - data.back() < 2) // We must change size!\n        {\n            first_with_given_number_of_parts(data, n, t - 1);\n            return;\n        }\n\n        // If no size change is necessary\n\n        // Starting from the end, we look at the first whose difference is at\n        // least 2 in order to transfer one unit from that one and then divide\n        // unevenly among the other ones.\n        IntType smallest = data.back();\n        difference_type suffixSum = smallest;\n\n        for (difference_type i = t - 2; i >= 0; --i)\n        {\n            if (data[i] - smallest > 1)\n            {\n                --data[i];\n                distribute_unevenly(data.begin() + i + 1,\n                                    data.end(),\n                                    suffixSum + 1,\n                                    data[i]);\n                return;\n            }\n            suffixSum += data[i];\n        }\n    }\n\n    static void prev_partition(partition& data, IntType n)\n    {\n        size_type t = data.size();\n        if (t == 0)\n            return;\n        if (t == 1 || data[1] == 1)\n        {\n            last_with_given_number_of_parts(data, n, t + 1);\n            return;\n        }\n\n        difference_type suffixSum = data.back();\n\n        for (IntType i = t - 2; i >= 0; --i)\n        {\n\n            if (can_increase(data, i))\n            {\n                ++data[i];\n                distribute_evenly(data.begin() + i + 1, data.end(), suffixSum - 1);\n                return;\n            }\n            suffixSum += data[i];\n        }\n    }\n\n    static void first_with_given_number_of_parts(partition& data,\n                                                 IntType n,\n                                                 IntType k)\n    {\n        if (n == 0)\n        {\n            data.clear();\n            return;\n        }\n\n        data.resize(k);\n\n        std::fill(data.begin(), data.end(), 1);\n\n        data[0] = n - k + 1;\n    }\n\n    static void last_with_given_number_of_parts(partition& data,\n                                                IntType n,\n                                                IntType k)\n    {\n        if (n == 0)\n        {\n            data.clear();\n            return;\n        }\n        data.resize(k);\n\n        distribute_evenly(data.begin(), data.end(), n);\n    }\n\n    static partition conjugate(const partition& P)\n    {\n        assert(!P.empty());\n        partition result(P[0], 1);\n        auto n = P.size();\n\n        result[0] = n;\n\n        for (size_t i = 1; i < n; ++i)\n        {\n            auto t =\n              std::lower_bound(P.begin(), P.end(), i, std::greater<IntType>());\n\n            int r = t - P.begin();\n\n            if (r > 0)\n                result[i] = r;\n        }\n\n        return result;\n    }\n\n    // **************** End static functions\n\nprivate:\n    IntType n_;\n    IntType min_num_parts_;\n    IntType max_num_parts_;\n    size_type size_;\n\n    static size_type calc_size(IntType n) { return partition_number(n); }\n\n    static size_type calc_size(IntType n, IntType numparts)\n    {\n        return partition_number(n, numparts);\n    }\n\n    static size_type calc_size(IntType n, IntType minnumparts, IntType maxnumparts)\n    {\n        size_type toReturn = 0;\n        for (size_type k = minnumparts; k <= maxnumparts; ++k)\n            toReturn += partition_number(n, k);\n        return toReturn;\n    }\n\n    static bool can_increase(const partition& data, size_type i)\n    {\n        if (i == 0)\n            return true;\n\n        if (data[i] == 1 || data[i + 1] == 1)\n            return false;\n\n        if (data[i - 1] == data[i])\n            return false;\n\n        return true;\n    }\n\n    template <class Iter>\n    static void distribute_evenly(const Iter& first, const Iter& last, IntType n)\n    {\n        if (first == last)\n            return;\n        IntType k = last - first;\n\n        auto quot_rem = std::div(n, k);\n\n        //         IntType lower = n/k;\n        //         IntType residue = n - lower*k;\n\n        auto mid = first + quot_rem.rem;\n        std::fill(first, mid, quot_rem.quot + 1);\n        std::fill(mid, last, quot_rem.quot);\n    }\n\n    template <class Iter>\n    static void distribute_unevenly(Iter first,\n                                    const Iter& last,\n                                    IntType n,\n                                    IntType maximum)\n    {\n        auto k = last - first;\n        IntType excess = n - k;\n        for (; first != last; ++first)\n        {\n            *first = std::min<IntType>(maximum, excess + 1);\n            excess += (1 - *first);\n        }\n    }\n\n    template <class Func>\n    void for_each(Func f, IntType k) const\n    {\n        // I'm really sorry about this. I don't know how to improve it. If you\n        // do, by all means, tell me about it.\n        switch (k)\n        {\n            // clang-format off\n        using part = partition;\n        case 0: detail::for_each_partition<part, 0>::apply(n_, f); break;\n        case 1: detail::for_each_partition<part, 1>::apply(n_, f); break;\n        case 2: detail::for_each_partition<part, 2>::apply(n_, f); break;\n        case 3: detail::for_each_partition<part, 3>::apply(n_, f); break;\n        case 4: detail::for_each_partition<part, 4>::apply(n_, f); break;\n        case 5: detail::for_each_partition<part, 5>::apply(n_, f); break;\n        case 6: detail::for_each_partition<part, 6>::apply(n_, f); break;\n        case 7: detail::for_each_partition<part, 7>::apply(n_, f); break;\n        case 8: detail::for_each_partition<part, 8>::apply(n_, f); break;\n        case 9: detail::for_each_partition<part, 9>::apply(n_, f); break;\n        case 10: detail::for_each_partition<part, 10>::apply(n_, f); break;\n        case 11: detail::for_each_partition<part, 11>::apply(n_, f); break;\n        case 12: detail::for_each_partition<part, 12>::apply(n_, f); break;\n        case 13: detail::for_each_partition<part, 13>::apply(n_, f); break;\n        case 14: detail::for_each_partition<part, 14>::apply(n_, f); break;\n        case 15: detail::for_each_partition<part, 15>::apply(n_, f); break;\n        case 16: detail::for_each_partition<part, 16>::apply(n_, f); break;\n\n            // clang-format on\n\n        default:\n        {\n            for (auto&& x : Partitions<IntType, RAContainerInt>(n_, k))\n            {\n                f(x);\n            }\n\n            break;\n        }\n        } // end switch(k)\n    }\n\n}; // end class Partitions\n\nusing boost::container::static_vector;\n\nusing partitions = Partitions<int>;\nusing partitions_stack = Partitions<int, static_vector<int, 128>>;\n\n} // namespace discreture\n", "meta": {"hexsha": "e58c8553cfd66d49225c07889fa44481e471d6bb", "size": 13614, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Discreture/Partitions.hpp", "max_stars_repo_name": "remz1337/discreture", "max_stars_repo_head_hexsha": "f15227a3e5c4faf04621bc9b2adad937aee06898", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T07:40:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T09:27:31.000Z", "max_issues_repo_path": "include/Discreture/Partitions.hpp", "max_issues_repo_name": "remz1337/discreture", "max_issues_repo_head_hexsha": "f15227a3e5c4faf04621bc9b2adad937aee06898", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2020-06-06T18:32:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-02T22:16:49.000Z", "max_forks_repo_path": "sources/include/external/Discreture/Partitions.hpp", "max_forks_repo_name": "greati/logicantsy", "max_forks_repo_head_hexsha": "11d1f33f57df6fc77c3c18b506fc98f9b9a88794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-03-12T05:42:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:18:32.000Z", "avg_line_length": 28.6008403361, "max_line_length": 103, "alphanum_fraction": 0.4941236962, "num_tokens": 3149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.4397311190919639}}
{"text": "/*\n * Copyright 2013 Matthew Harvey\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"frequency.hpp\"\n#include \"interval_type.hpp\"\n#include \"dcm_exceptions.hpp\"\n#include \"string_conv.hpp\"\n#include <boost/lexical_cast.hpp>\n#include <jewel/decimal.hpp>\n#include <jewel/decimal_exceptions.hpp>\n#include <jewel/exception.hpp>\n#include <wx/string.h>\n#include <string>\n\nusing boost::lexical_cast;\nusing jewel::Decimal;\nusing jewel::DecimalMultiplicationException;\nusing std::string;\n\nnamespace dcm\n{\n\n\nnamespace\n{\n    Decimal const& days_per_year()\n    {\n        static Decimal const ret(\"365.25\");\n        return ret;\n    }\n    Decimal const& days_per_week()\n    {\n        static Decimal const ret(\"7\");\n        return ret;\n    }\n    Decimal const& months_per_year()\n    {\n        static Decimal const ret(\"12\");\n        return ret;\n    }\n    Decimal const& days_per_canonical_interval()\n    {\n        // A number with that's wholly divisible\n        // by various commonly used Frequencies expressed\n        // in numbers of days.\n        static Decimal const ret(654528, 0);\n        return ret;\n    }\n    Decimal const& weeks_per_canonical_interval()\n    {\n        static Decimal const ret =\n            days_per_canonical_interval() / days_per_week();\n        JEWEL_ASSERT (round(ret, 0) == ret);\n        return ret;\n    }\n    Decimal const& years_per_canonical_interval()\n    {\n        static Decimal const ret =\n            days_per_canonical_interval() / days_per_year();\n        JEWEL_ASSERT (round(ret, 0) == ret);\n        return ret;\n    }\n    Decimal const& months_per_canonical_interval()\n    {\n        static Decimal const ret =\n            years_per_canonical_interval() * months_per_year();\n        JEWEL_ASSERT (round(ret, 0) == ret);\n        return ret;\n    }\n\n}  // end anonymous namespace\n\nFrequency::Frequency\n(   int p_num_steps,\n    IntervalType p_step_type\n):\n    m_num_steps(p_num_steps),\n    m_step_type(p_step_type)\n{\n    if (p_num_steps < 1)\n    {\n        JEWEL_THROW\n        (   InvalidFrequencyException,\n            \"In Frequency constructor, p_num_steps passed a value less than 1.\"\n        );\n    }\n    JEWEL_ASSERT (p_num_steps > 0);\n}\n\nint\nFrequency::num_steps() const\n{\n    return m_num_steps;\n}\n\nIntervalType\nFrequency::step_type() const\n{\n    return m_step_type;\n}\n\nstring\nfrequency_description(Frequency const& frequency, string const& first_word)\n{\n    string ret = first_word + \" \";\n    int const num_steps = frequency.num_steps();\n    if (num_steps > 1)\n    {\n        ret += lexical_cast<string>(num_steps);\n        ret += \" \";\n        ret += wx_to_std8(phrase(frequency.step_type(), true));\n    }\n    else\n    {\n        ret += wx_to_std8(phrase(frequency.step_type(), false));\n    }\n    return ret;\n}\n\nFrequency const&\ncanonical_frequency()\n{\n    JEWEL_ASSERT\n    (   round(days_per_canonical_interval(), 0) ==\n        days_per_canonical_interval()\n    );\n    static Frequency const ret\n    (   round(days_per_canonical_interval(), 0).intval(),\n        IntervalType::days\n    );\n    return ret;\n}\n\nDecimal\nconvert_to_canonical(Frequency const& p_frequency, Decimal const& p_amount)\n{\n    auto const num_steps = p_frequency.num_steps();\n    static_assert\n    (   sizeof(Decimal::int_type) >= sizeof(num_steps),\n        \"Potentially unsafe integral conversion.\"\n    );\n    Decimal const steps(num_steps, 0);  // will not throw\n\n    // The next part could throw DecimalMultiplicationException or\n    // DecimalDivisionException.\n    switch (p_frequency.step_type())\n    {\n    case IntervalType::days:\n        return p_amount * days_per_canonical_interval() / steps;\n    case IntervalType::weeks:\n        return p_amount * weeks_per_canonical_interval() / steps;\n    case IntervalType::months:  // fall through\n    case IntervalType::month_ends:\n        return p_amount * months_per_canonical_interval() / steps;\n    default:\n        JEWEL_HARD_ASSERT (false);\n    }\n}\n\nDecimal\nconvert_from_canonical(Frequency const& p_frequency, Decimal const& p_amount)\n{\n    auto const num_steps = p_frequency.num_steps();\n    static_assert\n    (   sizeof(Decimal::int_type) >= sizeof(num_steps),\n        \"Potentially unsafe integral conversion.\"\n    );\n    Decimal const steps(num_steps, 0);  // will not throw\n\n    // Might throw DecimalMultiplicationException.\n    Decimal const intermediate = p_amount * steps;\n\n    // The next part will throw jewel::DecimalDivisionException if and only if\n    // the number of significant digits in intermediate is\n    // equal to jewel::Decimal::maximum_precision().\n    switch (p_frequency.step_type())\n    {\n    case IntervalType::days:\n        return intermediate / days_per_canonical_interval();\n    case IntervalType::weeks:\n        return intermediate / weeks_per_canonical_interval();\n    case IntervalType::months:  // fall through\n    case IntervalType::month_ends:\n        return intermediate / months_per_canonical_interval();\n    default:\n        JEWEL_HARD_ASSERT (false);\n    }\n}\n\nbool\noperator==(Frequency const& lhs, Frequency const& rhs)\n{\n    return\n        (lhs.num_steps() == rhs.num_steps()) &&\n        (lhs.step_type() == rhs.step_type());\n}\n\nbool\noperator!=(Frequency const& lhs, Frequency const& rhs)\n{\n    return !(lhs == rhs);\n}\n\n}  // namespace dcm\n", "meta": {"hexsha": "c371fd27acb01bc01413b4725f96da27bd00a3dc", "size": 5758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/frequency.cpp", "max_stars_repo_name": "skybaboon/dailycashmanager", "max_stars_repo_head_hexsha": "0b022cc230a8738d5d27a799728da187e22f17f8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-07-05T07:42:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-15T15:27:22.000Z", "max_issues_repo_path": "src/frequency.cpp", "max_issues_repo_name": "skybaboon/dailycashmanager", "max_issues_repo_head_hexsha": "0b022cc230a8738d5d27a799728da187e22f17f8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-07T20:58:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-07T20:58:21.000Z", "max_forks_repo_path": "src/frequency.cpp", "max_forks_repo_name": "skybaboon/dailycashmanager", "max_forks_repo_head_hexsha": "0b022cc230a8738d5d27a799728da187e22f17f8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4128440367, "max_line_length": 79, "alphanum_fraction": 0.6675929142, "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.43966556223127606}}
{"text": "#pragma once\n\n// deal.II includes --------------------\n#include <deal.II/base/function.h>\n\n// my own includes\n#include \"var_form/polar_var_form.hpp\"\n\nnamespace boltzmann {\n\n/**\n * @brief spatial integrals for weighted least squares formulation\n *\n *\n * \\f$ \\operatorname{L} := v \\cdot \\nabla_x + \\sigma(x)\\f$\n *\n */\ntemplate <int dimX, typename APP>\nclass LeastSquaresVarForm : public PolarXVarForm<dimX>\n{\n public:\n  /**\n   * @param fe : fe space\n   */\n  template <typename FE>\n  LeastSquaresVarForm(const FE& fe)\n      : PolarXVarForm<dimX>(fe)\n  { /* empty */\n  }\n\n public:\n  /**\n   * @brief transport matrix \\f$ \\left ( \\operatorname{R} b_i , \\epsilon(x) \\operatorname{L} b_j\n   * \\right)_{L^2} \\f$\n   * where \\f$ \\operatorname{R} = \\operatorname{L} \\f$\n   * @param cell\n   *\n   *\n   * Query results with members: PolarXVarForm::S0(), PolarXVarForm::S1(), PolarXVarForm::T1(),\n   * PolarXVarForm::T2()\n   *\n   * Note that for thea bsorption free case, i.e. \\f$\\sigma(x) = 0\\f$, only T2() has nonzero\n   * contribution.\n   *\n   */\n  template <typename cell_iterator>\n  void calc_transport_cell(const cell_iterator& cell);\n\n  /**\n   * @brief Stabilized identity \\f$ \\left ( \\operatorname{R} b_i,\n   *        \\epsilon(x) b_j \\right )_{L^2} \\f$\n   *        where \\f$ \\operatorname{R} = v \\cdot \\nabla_x + \\sigma(x)\\f$\n   *\n   *\n   * @param cell\n   *\n   *\n   * Query results with members: PolarXVarForm::S0(), PolarXVarForm::S1()\n   *\n   *\n   */\n  template <typename cell_iterator>\n  void calc_identity(const cell_iterator& cell);\n\n  /**\n   * @brief Stabilized identity\n   *        \\f$\n   *        \\left ( \\operatorname{R} b_i, b_j \\right )_{L_2(\\Omega)} +\n   *        \\left ( b_i, \\operatorname{R} b_j \\right )_{L_2(\\Omega)}\n   *        \\f$\n   *        where \\f$ \\operatorname{R} = v \\cdot \\nabla_x \\f$\n   * DEPRECATED\n   *\n   * @param cell\n   *\n   *\n   */\n  template <typename cell_iterator>\n  void calc_identity_sym(const cell_iterator& cell) __attribute__((deprecated));\n\n  /**\n   * @brief just overlap (without stabilization term)\n   *        hint: this uses the weighted l2 scalar product\n   *        \\f$ \\left(b_i, b_j\\right )_L^2 \\f$\n   *\n   * Query results with members: PolarXVarForm::S0()\n   *\n   */\n  template <typename cell_iterator>\n  void calc_raw_identity(const cell_iterator& cell);\n\n  template <typename cell_iterator>\n  void calc_boundary(const cell_iterator& cell);\n\n  static const std::string info;\n};\n\ntemplate <int dimX, typename APP>\nconst std::string LeastSquaresVarForm<dimX, APP>::info = \"Weighted least squares\";\n\n// --------------------------------------------------------------------------------\ntemplate <int dimX, typename APP>\ntemplate <typename cell_iterator>\ninline void\nLeastSquaresVarForm<dimX, APP>::calc_transport_cell(const cell_iterator& cell)\n{\n  // update fevalues\n  this->init_cell(cell);\n  // clear S0_mat, S1_mat, T1_mat, T2_mat\n  PolarXVarForm<dimX>::clear_storage();\n\n  const int n_qpoints = this->quad.size();\n  // make sure the arrays have the right size\n  const int dofs_per_cell = this->fe_values.dofs_per_cell;\n\n  for (int ix1 = 0; ix1 < dofs_per_cell; ++ix1) {\n    for (int ix2 = 0; ix2 < dofs_per_cell; ++ix2) {\n      for (int q = 0; q < n_qpoints; ++q) {\n        auto shape_ix1 = this->fe_values.shape_value(ix1, q);\n        auto shape_ix2 = this->fe_values.shape_value(ix2, q);\n        auto grad_ix1 = this->fe_values.shape_grad(ix1, q);\n        auto grad_ix2 = this->fe_values.shape_grad(ix2, q);\n        double weight = this->fe_values.JxW(q);\n\n#if DEAL_II_VERSION_MAJOR >= 8 && DEAL_II_VERSION_MINOR <= 3\n        typename PolarXVarForm<dimX>::T2_t T2tmp;\n        outer_product(T2tmp, grad_ix1, grad_ix2 * weight);\n        this->T2_mat[ix1][ix2] += T2tmp;\n#else\n        this->T2_mat[ix1][ix2] += outer_product(grad_ix1, grad_ix2 * weight);\n#endif  // DEAL_II_VERSION_MAJOR >= 8 && DEAL_II_VERSION_MINOR <= 3\n        // mass contributions\n      }\n    }\n  }\n}\n\n// --------------------------------------------------------------------------------\ntemplate <int dimX, typename APP>\ntemplate <typename cell_iterator>\ninline void\nLeastSquaresVarForm<dimX, APP>::calc_identity(const cell_iterator& cell)\n{\n  // update fevalues\n  this->init_cell(cell);\n  // clear S0_mat, S1_mat, T1_mat, T2_mat\n  PolarXVarForm<dimX>::clear_storage();\n\n  const int n_qpoints = this->quad.size();\n\n  const int dofs_per_cell = this->fe_values.dofs_per_cell;\n  for (int ix1 = 0; ix1 < dofs_per_cell; ++ix1) {\n    // test\n    for (int ix2 = 0; ix2 < dofs_per_cell; ++ix2) {\n      // trial\n      for (int q = 0; q < n_qpoints; ++q) {\n        auto shape_ix1 = this->fe_values.shape_value(ix1, q);\n        auto shape_ix2 = this->fe_values.shape_value(ix2, q);\n        auto grad_ix1 = this->fe_values.shape_grad(ix1, q);\n        double weight = this->fe_values.JxW(q);\n        // mass contributions\n        this->S1_mat[ix1][ix2] += grad_ix1 * (shape_ix2 * weight);\n      }\n    }\n  }\n}\n\n// --------------------------------------------------------------------------------\ntemplate <int dimX, typename APP>\ntemplate <typename cell_iterator>\ninline void\nLeastSquaresVarForm<dimX, APP>::calc_identity_sym(const cell_iterator& cell)\n{\n  // update fevalues\n  this->init_cell(cell);\n  // clear S0_mat, S1_mat, T1_mat, T2_mat\n  PolarXVarForm<dimX>::clear_storage();\n\n  const int n_qpoints = this->quad.size();\n  const int dofs_per_cell = this->fe_values.dofs_per_cell;\n\n  for (int ix1 = 0; ix1 < dofs_per_cell; ++ix1) {\n    // test\n    for (int ix2 = 0; ix2 < dofs_per_cell; ++ix2) {\n      // trial\n      for (int q = 0; q < n_qpoints; ++q) {\n        auto shape_ix1 = this->fe_values.shape_value(ix1, q);\n        auto shape_ix2 = this->fe_values.shape_value(ix2, q);\n        auto& grad_ix1 = this->fe_values.shape_grad(ix1, q);\n        auto& grad_ix2 = this->fe_values.shape_grad(ix2, q);\n        // auto grad_ix2 = this->fe_values.shape_grad(ix2,q);\n        double weight = this->fe_values.JxW(q);\n        // mass contributions\n        this->S1_mat[ix1][ix2] += grad_ix1 * (shape_ix2 * weight) + grad_ix2 * (shape_ix1 * weight);\n      }\n    }\n  }\n}\n\n// --------------------------------------------------------------------------------\ntemplate <int dimX, typename APP>\ntemplate <typename cell_iterator>\ninline void\nLeastSquaresVarForm<dimX, APP>::calc_raw_identity(const cell_iterator& cell)\n{\n  // update fevalues\n  this->init_cell(cell);\n  // clear S0_mat, S1_mat, T1_mat, T2_mat\n  PolarXVarForm<dimX>::clear_storage();\n\n  const int n_qpoints = this->quad.size();\n  // make sure the arrays have the right size\n\n  const int dofs_per_cell = this->fe_values.dofs_per_cell;\n  for (int ix1 = 0; ix1 < dofs_per_cell; ++ix1) {\n    // test\n    for (int ix2 = 0; ix2 < dofs_per_cell; ++ix2) {\n      // trial\n      for (int q = 0; q < n_qpoints; ++q) {\n        auto shape_ix1 = this->fe_values.shape_value(ix1, q);\n        auto shape_ix2 = this->fe_values.shape_value(ix2, q);\n        double weight = this->fe_values.JxW(q);\n        // mass contributions\n        this->S0_mat[ix1][ix2] += shape_ix1 * shape_ix2 * weight;\n      }\n    }\n  }\n}\n\n// -------------------------------------------------------------------------------\ntemplate <int dimX, typename APP>\ntemplate <typename cell_iterator>\ninline void\nLeastSquaresVarForm<dimX, APP>::calc_boundary(const cell_iterator& cell)\n{\n  // update fevalues\n  // clear S0_mat, S1_mat, T1_mat, T2_mat\n  PolarXVarForm<dimX>::clear_storage();\n\n  if (cell->at_boundary()) return;\n\n  const int faces_per_cell = dealii::GeometryInfo<dimX>::faces_per_cell;\n  const int n_qpoints = this->face_quad.size();\n  const int dofs_per_cell = this->fe_values.dofs_per_cell;\n\n  for (int face_idx = 0; face_idx < faces_per_cell; ++face_idx) {\n    this->init_face(cell, face_idx);\n    for (int ix1 = 0; ix1 < dofs_per_cell; ++ix1) {\n      // test\n      for (int ix2 = 0; ix2 < dofs_per_cell; ++ix2) {\n        // trial\n        for (int q = 0; q < n_qpoints; ++q) {\n          auto shape_ix1 = this->fe_face_values.shape_value(ix1, q);\n          auto shape_ix2 = this->fe_face_values.shape_value(ix2, q);\n          double weight = this->fe_values.JxW(q);\n          // mass contributions\n          this->S1_mat[ix1][ix2] +=\n              (this->fe_face_values.normal_vector(q) * shape_ix1 * shape_ix2 * weight);\n        }\n      }\n    }\n  }\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "4ccc740a439d5541fce18c7ccd08b2aeb8a3c93a", "size": 8300, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/var_form/least_squares/least_squares.hpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/var_form/least_squares/least_squares.hpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/var_form/least_squares/least_squares.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2030075188, "max_line_length": 100, "alphanum_fraction": 0.6077108434, "num_tokens": 2411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.43966555534321394}}
{"text": "#include <iostream>\n#include <fstream>\n//#include <cstdlib>\n#include <stdlib.h>\n#include <time.h>\n#include <iterator>\n#include <vector>\n#include <cmath>\n\n#include <boost/program_options.hpp>\n\n#define STRINGIFY(a) #a\n\nnamespace po = boost::program_options;\n\n\nusing namespace std;\n\n// Build and parameters for populating the grid\nint l;// = 49;\nint h;// = 49;\nvector< vector<int> > grid;//(l, vector<int>(h));\n\nstring grid_load_filename;\n\nfloat grid_density;// = 0.50;\nfloat init_coop_level;// = 0.50;\nint cooperators,defectors,empty;\n\n// Set up neighborhood\nint numNeighbors;// = 4;\nvector<int> nghb_h;//(numNeighbors);\nvector<int> nghb_l;//(numNeighbors);\n\n\n// Players\nint focal_player_l,focal_player_h;\nint player2_l,player2_h;\n\n// Prisoner's Dilemma Constants and Variables\nfloat T;// = 1.3;\nfloat R;// = 1.0;\nfloat P;// = 0.1;\nfloat S;// = 0.0;\n\nint strategy_focal_player;\nfloat payoff_focal_player;\n\n// Strategy update parameters\nstring update_style = \"Dirk\"; // warning : I've commented out the Fermi update function\n\nfloat noise;// = 0.000;\nfloat imitation_likelihood;\n//float imitation_r;// = 1- imitation_likelihood;\nfloat reset_strategy_likelihood;// = noise;\n\nfloat fermi_temperature;// = 0.1;\n\n// Migration parameters\nint migration_range;// = 5;\nfloat random_migration;// = 0;\nfloat expell_likelihood;// = 0.01;\n\nint n_migration_sites;// = (2*migration_range + 1)*(2*migration_range + 1) - 1;\nvector<int> migration_array_l;//(n_migration_sites);\nvector<int> migration_array_h;//(n_migration_sites);\n\n// Simulation Parameters;\n\nint verbose;// = 1;\nint iterations;\nint save_grids;\n\nint MCS;// = l*h*iterations;//static_cast<const int>(l)*static_cast<const int>(h)*static_cast<const int>(iterations);\n\nvector<int> rand_steps_l;//(MCS);\nvector<int> rand_steps_h;//(MCS);\nint current_step;\nint count_changes = 1;\n\nint chosen_migration_site;\n\nofstream output_all_mv;\nofstream output_summary;\nofstream output_grid_states;\nstring summary;\n\nbool fileExists(string fileName)\n{\n    ifstream infile(fileName);\n    return infile.good();\n}\n\n\nvoid prepare_parameters() {\n    MCS = l*h*iterations;\n    grid.resize(l, vector<int>(h));\n    rand_steps_l.resize(MCS);\n    rand_steps_h.resize(MCS);\n    nghb_h.resize(numNeighbors);\n    nghb_l.resize(numNeighbors);\n    n_migration_sites = (2*migration_range + 1)*(2*migration_range + 1) - 1;\n    migration_array_l.resize(n_migration_sites);\n    migration_array_h.resize(n_migration_sites);\n    }\n\n// Output;\n\nvoid open_output_files(){\n    char Buffer[500];\n    string str;\n    int length = 0;\n    length += sprintf(Buffer+length, \"iter_%d\",iterations);\n    length += sprintf(Buffer+length, \"_l_%d\",l);\n    length += sprintf(Buffer+length, \"_h_%d\",h);\n    length += sprintf(Buffer+length, \"_d_%0.3f\", grid_density);\n    length += sprintf(Buffer+length, \"_cl_%0.3f\",init_coop_level);\n    length += sprintf(Buffer+length, \"_ns_%d\",numNeighbors);\n    length += sprintf(Buffer+length, \"_il_%0.3f\",imitation_likelihood);\n    length += sprintf(Buffer+length, \"_q_%0.3f\",reset_strategy_likelihood);\n    length += sprintf(Buffer+length, \"_M_%d\",migration_range);\n    length += sprintf(Buffer+length, \"_m_%0.3f\",random_migration);\n    length += sprintf(Buffer+length, \"_s_%0.4f\",expell_likelihood);\n    \n\n    str.assign(Buffer, Buffer + length);\n\n    int k = 0;\n    string filename_output_all_mv = \"results/allmoves/\" + str + \"_\" + to_string(k) + \".csv\";\n    string filename_output_summary = \"results/summary/\" + str + \"_\" + to_string(k) + \".csv\";\n    string filename_configurations = \"results/grids/\" + str + \"_\" + to_string(k) + \".csv\";\n    \n    while (fileExists(filename_output_summary)){\n        k++;\n        filename_output_all_mv = \"results/allmoves/\" + str + \"_\" + to_string(k) + \".csv\";\n        filename_output_summary = \"results/summary/\" + str + \"_\" + to_string(k) + \".csv\";\n        filename_configurations = \"results/grids/\" + str + \"_\" + to_string(k) + \".csv\";\n        }\n    \n    output_all_mv.open(filename_output_all_mv, ios::trunc); // open all moves output file;\n    output_summary.open(filename_output_summary, ios::trunc); // open summary output file;\n    output_summary << \"simul_step,completion,coop_level,cooperators,defectors,empty\\n\";\n    output_grid_states.open(filename_configurations, ios::trunc); // open configuration output file;\n    }\n\nstring format_summary(){\n\n    char Buffer[500];\n    string str;\n    int length = 0;\n    \n    length += sprintf(Buffer+length, \"%d,\",current_step);\n    length += sprintf(Buffer+length, \"%0.3f,\",current_step/static_cast<float>(MCS));\n    length += sprintf(Buffer+length, \"%0.3f,\",static_cast<float>(cooperators)/(cooperators + defectors));\n    length += sprintf(Buffer+length, \"%d,\",cooperators);\n    length += sprintf(Buffer+length, \"%d,\",defectors);\n    length += sprintf(Buffer+length, \"%d\\n\",empty);\n    \n    str.assign(Buffer, Buffer + length);\n    \n    return str;\n    }\n\n\n\nfloat rand01() {\n\treturn (float)arc4random_uniform(100000)/100000;\n\t}\n\n\nvoid makeGrid() {\n\t/* Makes a grid of size l with equal number\n\t of cooperators (value 1) and defectors (value 0). If grid_density is\n\t less than 100%, then the some sites are emptied randmonly (value -1)\n\t */\n    \n\tfor (int i = 0; i < l; i++) {\n\t\tfor (int j = 0; j < h; j++) {\n            if (rand01() < init_coop_level) grid[i][j] = 1;\n            else grid[i][j] = 0;\n            \n\t\t\tif (rand01() > grid_density) { // remove player from grid as a function of grid_density\n\t\t\t\tgrid[i][j] = -1;\n            }\n        }\n    }\n}\n\n\nvoid countCDE(){\n\t/* Performs a count of cooperators, defectors and empty sites.\n\t If update = 1, cooperators, defectors, and empty variables are updated\n\t If update = 0, assuming that if there is no update, then the then the only reason\n\t for invoking this function is to print out the current state of cooperation and defection.\n\t Regardless of the value of update, if verbose >=2, then the current state of cooperation and defection is printed out.\n\t */\n\t\n\t//int c,d,e = 0; // initialize count variables;\n    \n\tcooperators = 0;\n\tdefectors = 0;\n\tempty = 0;\n\t\n\tfor (int i = 0; i < l; i++){\n\t\tfor (int j = 0; j < h; j++){\n\t\t\tif (grid[i][j] == 1) {\n\t\t\t\tcooperators++;\n            }\n\t\t\t\n\t\t\telse if (grid[i][j] == 0) {\n\t\t\t\tdefectors++;\n            }\n\t\t\t\n\t\t\telse {\n\t\t\t\tempty++;\n            }\n        }\n    }\n\t\n    \n\tif (verbose >= 2){\n\t\tcout << \"cooperators:\" << cooperators << \", defectors:\" << defectors << \", empty sites:\" << empty << endl;\n    }\n    \n}\n\n\nvoid load_grid(){\n    \n    std::ifstream testFile(grid_load_filename, std::ios::binary);\n    \n    string cell;\n    int cellInt;\n    \n    grid.resize(l, vector<int>(h));\n    \n    int i=0;\n    \n    while(getline(testFile,cell,',')){\n        stringstream str(cell);\n        str >> cellInt;\n        //cout << i/h << \" \" << i%h << \" \" << cellInt << endl;\n        //grid[i/h][i%h] = cellInt;\n        grid[i%h][i/h] = cellInt;\n        i++;\n    }\n    countCDE(); // update values for cooperators, defectors, and empty\n}\n\nvoid showGrid(int subset = 20) {\n\t/* Displays the grid on the command line\n\t Note that the grid is large, the display won't be nice.\n\t */\n    \n    int height;\n    int length;\n    \n    if (subset == 0){\n        height = h;\n        length = l;\n        }\n    else {\n        height = length = subset;\n        }\n    \n    string character;\n    \n\tfor (int j = 0; j < height; j++){\n\t\tfor (int i=0; i < length; i++) {\n            if (grid[i][j] == -1) character = \" \";\n            else character = to_string(grid[i][j]);\n            \n            \n            if (i+1==length){\n                \n\t\t\t\tif (grid[0][j+1] < 0){\n\t\t\t\t\tcout << character << \"\\n\";\n\t\t\t\t\t//cout << grid[i][j] << \"\\n\";\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcout << character << \"\\n \";\n\t\t\t\t}\n            }\n\t\t\telse {\n\t\t\t\tif (grid[i+1][j] < 0){\n\t\t\t\t\tcout << character << \"\\t\";\n                }\n\t\t\t\telse {\n\t\t\t\t\tcout << character << \"\\t \";\n                }\n            }\n        }\n    }\n\tcout << endl;\n}\n\n\nvoid save_grid_state(){\n    \n    output_grid_states << current_step << \":[\";\n    \n    for (int j = 0; j < h; j++){\n\t\tfor (int i=0; i < l; i++) {\n            //output_grid_states << \"(\" << i << \",\" << j << \",\" << grid[i][j] << \"),\";\n            output_grid_states << grid[i][j] << \",\";\n            }\n        }\n    output_grid_states << \"]\\n\";\n    }\n\nvoid findNeighbors(int player_l, int player_h) {\n\t/*Find neighbors of a focal site:\n\t If numNeighbors = 4, the 4 sites in direct contact are selected.\n\t If numNeighbors = 8, the 8 sites around the focal site are selected.\n\t This function is useful to compare payoffs between the focal player and her neighbors.\n\t */\n\t\n\t//cout << \"focal site: \" << player_l << \" \" << player_h << \" \" << grid[player_l][player_h] << endl;\n\t//cout << player_l  << \",\" << player_h  << \"\\n\" << endl;\n    \n\t\n\tif ((numNeighbors != 4) && (numNeighbors != 8)){\n\t\tcout << \"wrong neighborhood number\" << endl;\n    }\n\t\n\tif (numNeighbors==4){\n\t\tnghb_l[0] = player_l;\n\t\tnghb_h[0] = (player_h - 1 + h)%h;\n        \n\t\tnghb_l[1] = (player_l - 1 + l)%l;\n\t\tnghb_h[1] = player_h;\n\t\t\n\t\tnghb_l[2] = (player_l + 1 + l)%l;\n\t\tnghb_h[2] = player_h;\n\t\t\n\t\tnghb_l[3] = player_l;\n\t\tnghb_h[3] = (player_h + 1 + h)%h;\n        \n    }\n    \n\t\n\t/*\n     cout << (player_h - 1 + h)%h  << \",\" << player_l << endl;\n     cout << player_h << \",\" << (player_l - 1 + l)%l << endl;\n     cout << player_h << \",\" << (player_l + 1 + l)%l << endl;\n     cout << (player_h + 1 + h)%h << \",\" << player_l << endl;\n     */\n    \n    /*\n     cout << nghb_h[0]  << \",\" << nghb_l[0] << endl;\n     cout << nghb_h[1] << \",\" << nghb_l[1] << endl;\n     cout << nghb_h[2]<< \",\" << nghb_l[2] << endl;\n     cout << nghb_h[3] << \",\" << nghb_l[3] << endl;\n     */\n    \n\telse if (numNeighbors==8){\n\t\t\n\t\tnghb_l[0] = (player_l - 1 + l)%l;\n\t\tnghb_h[0] = (player_h - 1 + h)%h;\n\t\t\n        \n\t\tnghb_l[1] = player_l;\n\t\tnghb_h[1] = (player_h - 1 + h)%h;\n        \n\t\tnghb_l[2] = (player_l + 1 + l)%l;\n\t\tnghb_h[2] = (player_h - 1 + h)%h;\n\t\t\n\t\tnghb_l[3] = (player_l - 1 + l)%l;\n\t\tnghb_h[3] = player_h;\n        \n\t\tnghb_l[4] = (player_l + 1 + l)%l;\n\t\tnghb_h[4] = player_h;\n\t\t\n\t\tnghb_l[5] = (player_l - 1 + l)%l;\n\t\tnghb_h[5] = (player_h + 1 + h)%h;\n\t\t\n\t\tnghb_l[6] = player_l;\n\t\tnghb_h[6] = (player_h + 1 + h)%h;\n        \n\t\tnghb_l[7] = (player_l + 1 + l)%l;\n\t\tnghb_h[7] = (player_h + 1 + h)%h;\n        \n\t\t\n    }\n\t\n\tif (verbose >= 2){\n\t\tfor (int i=0; i < numNeighbors; i++) {\n\t\t\tcout << nghb_l[i]  << \",\" << nghb_h[i] << endl;\n        }\n    }\n    \n}\n\n\nvoid explore_m_range(int player_l, int player_h){\n\t/* Explore migration range to find best sites. */\n\t\n\tint l_index;\n\tint h_index;\n    \n\tint k = 0;\n\tfor (int j= player_h - migration_range ; j < player_h + migration_range +1 ; j++) {\n\t\tfor (int i = player_l - migration_range ; i < player_l + migration_range +1 ; i++){\n\t\t\t\n\t\t\tl_index = (i + l)%l;\n\t\t\th_index = (j + h)%h;\n\t\t\t\n\t\t\t\n\t\t\tif ((l_index == player_l)&&(h_index == player_h)){\n\t\t\t\tcontinue;\n            }\n\t\t\t\n\t\t\tmigration_array_l[k] = l_index;\n\t\t\tmigration_array_h[k] = h_index;\n\t\t\tk++;\n\t\t}\n\t}\n    \n\t\n\tif (verbose >= 2){\n\t\t\n\t\tcout << \"focal player: \"\n\t\t<< player_l\n\t\t<< \",\"\n\t\t<< player_h\n\t\t<< \" strategy: \"\n\t\t<< grid[player_l][player_h]\n\t\t<< endl;\n\t\t\n\t\tk=0;\n\t\tfor (int i = 0; i < n_migration_sites ; i++) {\n\t\t\t//cout << i << \" (\" << migration_array_l[i] << \",\" << migration_array_h[i] << \")\" << endl;\n\t\t\t\n\t\t\tif ( (i-1) == (n_migration_sites-1)/2){\n\t\t\t\tcout << \"X\" << \",\" << \"X\" << \"  \";\n\t\t\t\tk=1;\n\t\t\t}\n\t\t\t\n\t\t\tif ( (i + 1 + k)  % (2*migration_range +1) == 0){\n\t\t\t\tcout << migration_array_l[i] << \",\" << migration_array_h[i] << \"(\" << grid[ migration_array_l[i]][ migration_array_h[i]] << \")\\n\";\n\t\t\t}\n\t\t\t\n\t\t\telse {\n\t\t\t\tcout << migration_array_l[i] << \",\" << migration_array_h[i]  << \"(\" << grid[ migration_array_l[i]][ migration_array_h[i]] << \") \";\n            }\n\t\t\t\n            \n\t\t\t\n        }\n\t\tcout << endl;\n    }\n\t\n}\n\n\nfloat compute_migration_distance(float site_l, float site_h, float migration_site_l, float migration_site_h){\n    // computes a simple distance between 2 sites\n    \n    return sqrt(pow(min(abs(site_l-migration_site_l), l-1-abs(site_l-migration_site_l)),2)+  pow(min(abs(site_h - migration_site_h), h-1-abs(site_h-migration_site_h)),2));\n    }\n\nfloat pDilemma(int strategy, int stragegy_nghb) {\n\t/* Implements the prisoners dilemma game between */\n\t\n\tfloat pd_payoff = 0;\n\t\n\tif ((strategy == 1) && (stragegy_nghb == 1)) {\n\t\tpd_payoff = R;\n    }\n\t\n\telse if ((strategy == 0) && (stragegy_nghb == 1)) {\n\t\tpd_payoff = T;\n    }\n\t\n\telse if ((strategy == 1) && (stragegy_nghb == 0)) {\n\t\tpd_payoff = S;\n    }\n\t\n\telse if ((strategy == 0) && (stragegy_nghb == 0)) {\n\t\tpd_payoff = P;\n    }\n\t\n\telse {\n\t\tcout << \"error with input strategies\" << endl;\n\t\treturn -1;\n    }\n    \n\treturn pd_payoff;\n}\n\n\nfloat payoff(int player_l, int player_h, int strategy){\n\t// Compute payoff from playing with neighbors\n\t\n\t//int strategy = grid[player_l][player_h];\n\tfloat sum_payoff = 0;\n    \n\tfindNeighbors(player_l,player_h); // Search for neighbors\n\t\n\tint strategy_nghb;\n\t\n\tfor (int i=0; i < numNeighbors; i++) {\n\t\t\n\t\tstrategy_nghb = grid[nghb_l[i]][nghb_h[i]];\n\t\t\n\t\tif (strategy_nghb != -1){\n\t\t\t\n\t\t\tsum_payoff += pDilemma(strategy, strategy_nghb);\n\t\t\t\n\t\t\t/*\n             cout << nghb_l[i]\n             << \",\"\n             << nghb_h[i]\n             << \"  strategy :\"\n             << strategy_nghb\n             << \" payoff: \"\n             << payoff\n             << endl;\n             */\n        }\n    }\n\t\n\t//cout << \"sum payoff: \" << sum_payoff << endl;\n\treturn sum_payoff;\n}\n\n\nint strategy_update_Fermi(float o_pay_off, float best_pay_off) {\n\t/*update strategy of focal player by trying to reproduce\n\t the strategy of the best performing neighbor, using\n\t Fermi Temperature*/\n    \n\tif ((o_pay_off - best_pay_off) >= 0){\n\t\t/* If initial strategy has better payoff or\n\t\t both strategies have same payoff, do nothing */\n\t\t//cout << \" higher original payoff or same payoff: \" << o_pay_off;\n\t\treturn 0;\n\t\t\n    }\n\t\n\telse {\n\t\tfloat f_temperature = 1./(1 + exp(o_pay_off - best_pay_off)/fermi_temperature);\n\t\t\t\t\n\t\tif (rand01() < f_temperature) {\n\t\t\t//cout << \"update strategy\" << endl;\n\t\t\treturn 1;\n        }\n\t\telse {\n\t\t\t//cout << \"no update \" << endl;\n\t\t\treturn 0;\n\t\t}\n        \n    }\n\t\n}\n\n\nint strategy_update_Dirk(float o_pay_off, float best_pay_off){\n\t\n\tif ((o_pay_off < best_pay_off) and (rand01() <  imitation_likelihood)){\n        //cout << o_pay_off << \" \" << best_pay_off << \" \" << rand01() << endl;\n        return 2; // copy strategy\n    }\n\telse if ((rand01() > imitation_likelihood) and (rand01() < reset_strategy_likelihood)){\n\t\treturn 1; // cooperate\n    }\n    else if ((rand01() > imitation_likelihood ) and (rand01() > reset_strategy_likelihood) and (reset_strategy_likelihood > 0)){\n\t\treturn 0; // defect\n    }\n    else {\n        return -1; // do nothing\n    }\n}\n\n\n\nvoid compare_payoff_with_nghbs(int player_l, int player_h, int update_strategies = 1){\n\t\n\t\n    strategy_focal_player = grid[player_l][player_h];\n\tpayoff_focal_player = payoff(player_l,player_h, strategy_focal_player);\n\t\n\tfindNeighbors(player_l,player_h);\n\t\n\t//copy(begin(nghb_l), end(nghb_l), begin(nghbl));\n\t//int nghbh = nghb_h;\n\t\n\t\n\tfloat payoff_nghb;\n\tfloat strategy_nghb;\n\tfloat highest_payoff = payoff_focal_player;\n\tint win_strategy = strategy_focal_player;\n\tint win_nghb_l = player_l;\n\tint win_nghb_h = player_h;\n\t\n\t//vector<int> nghbl(numNeighbors];\n\t//vector<int> nghbh(numNeighbors];\n\t\n    \n    vector<int> nghbl(nghb_l);\n\tvector<int> nghbh(nghb_h);\n\t\n    //copy(nghb_l, nghb_l + numNeighbors, nghbl);\n\t//copy(nghb_h, nghb_h + numNeighbors, nghbh);\n\t\n\tfor (int i=0; i < numNeighbors; i++) {\n\t\t/* Parkour all neighbors to find the strategy with highest payoff */\n\t\t\n\t\t//cout << nghb_l[i] << \",\" << nghb_h[i] << \" \" << nghbl[i] << \",\" << nghbh[i] << endl;\n\t\tstrategy_nghb = grid[nghbl[i]][nghbh[i]];\n\t\t\n\t\tif (strategy_nghb == -1) {\n\t\t\t//cout << \"empty site\" << endl;\n\t\t\tpayoff_nghb = -1000; // assign an arbitrary small payoff\n\t\t}\n\t\telse {\n\t\t\tpayoff_nghb = payoff(nghbl[i],nghbh[i],strategy_nghb);\n\t\t}\n\t\t\n\t\tif (payoff_nghb > highest_payoff){\n\t\t\thighest_payoff = payoff_nghb;\n\t\t\twin_nghb_l = nghbl[i];\n\t\t\twin_nghb_h = nghbh[i];\n\t\t\twin_strategy = strategy_nghb;\n\t\t\t//cout << highest_payoff << \" \" << win_strategy << \" (\" << win_nghb_l << \",\" << win_nghb_h << \") \" << grid[win_nghb_l][win_nghb_h] << endl;\n\t\t}\n\t}\n    \n\t\n\tif (update_strategies == 1){\n\t\t/* Attempt strategy update:\n\t\t provides a binary value to determine if an update actually ocurred\n\t\t (1 => update, 0 => no update) */\n\t\tint update_s;\n\t\t\n\t\t\n\t\t/* Choose update method */\n\t\t//if (update_style == \"Fermi\"){\n\t\t//\tupdate_s = strategy_update_Fermi(payoff_focal_player, highest_payoff);\n        //}\n\t\t//else if (update_style == \"Dirk\"){\n        update_s = strategy_update_Dirk(payoff_focal_player, highest_payoff);\n\t\t\t//cout << \"Dirk update \" << update_s << endl;\n        //}\n        \n        \n\t\t\n\t\tif ((update_s == 2) and (win_strategy != strategy_focal_player)){ //\n\t\t\tgrid[player_l][player_h] = grid[win_nghb_l][win_nghb_h]; // update strategy\n\t\t\t\n\t\t\t//cout << grid[player_l][player_h] << endl;\n\t\t\t\n\t\t\t\n            countCDE(); //recount current number of cooperators, defectors and empty sites.\n\t\t\t\n\t\t\t// write update to output_all_mv file\n\t\t\toutput_all_mv  << current_step <<\",\"\n            << cooperators << \",\"\n            << defectors << \",\"\n            << empty << \",\"\n            << \"U\" << \",\"\n            << player_l << \",\"\n            << player_h << \",\"\n            << strategy_focal_player << \",\"\n            << grid[win_nghb_l][win_nghb_h] << \",\"\n            << payoff_focal_player << \",\"\n            << highest_payoff\n            << \"\\n\";\n            \n            count_changes +=1;\n            \n\t\t\t\n\t\t\tif (verbose >= 2){\n\t\t\t\tcout << \"strategy updated for (\"\n\t\t\t\t<< player_l\n\t\t\t\t<< \",\"\n\t\t\t\t<< player_h\n\t\t\t\t<< \")\"\n\t\t\t\t<< \" from \"\n\t\t\t\t<< strategy_focal_player\n\t\t\t\t<< \" to \"\n\t\t\t\t<< win_strategy\n\t\t\t\t<< endl;\n            }\n        }\n\t\t\n\t\telse if ((update_s == 0) or (update_s == 1)){\n\t\t\tint old_strategy = grid[player_l][player_h];\n\t\t\tgrid[player_l][player_h] = update_s;\n            \n            countCDE();\n            \n            output_all_mv  << current_step <<\",\"\n            << cooperators << \",\"\n            << defectors << \",\"\n            << empty << \",\"\n            << \"R\" << \",\"\n            << player_l << \",\"\n            << player_h << \",\"\n            << old_strategy << \",\"\n            << grid[player_l][player_h]\n            << \"\\n\";\n        \n            count_changes +=1;\n        }\n        \n        else {\n            return;\n        }\n    }\n    \n}\n\n\n\nvoid compare_payoff_m_range(int player_l, int player_h, float random_migration_likelihood, float expell, int force_migrate){\n\t\n    \n    strategy_focal_player = grid[player_l][player_h];\n    int sfp = grid[player_l][player_h];\n    payoff_focal_player = payoff(player_l,player_h, strategy_focal_player);\n\texplore_m_range(player_l,player_h);\n\t\n    float pf;\n\tfloat best_pay_off;\n\t\n    float migration_payoff[n_migration_sites];\n    float migration_distance[n_migration_sites];\n    float distance; //migration distance\n\tfloat shortest_distance = 1000; // shortest migration distance\n    \n    \n\tint index;\n    \n    int mv_destination_l;\n    int mv_destination_h;\n    \n    string migration_type;\n\t\n    \n    vector<int> sites_empty;\n\tvector<int>::iterator it_e;\n\t\n\tvector<int> sites_occupied;\n\tvector<int>::iterator it_o;\n\n\tvector<int> best_sites_empty;\n\tvector<int>::iterator it_bse;\n\t\n\tvector<int> better_sites_empty;\n\tvector<int>::iterator it_rse;\n    \n    vector<int> better_sites_empty_payoff;\n\tvector<int>::iterator it_rsep;\n\t\n\tvector<int> best_sites_occupied;\n\tvector<int>::iterator it_bso;\n\n    vector<int> worse_sites_empty;\n\tvector<int>::iterator it_wse;\n    \n    vector<int> worse_sites_empty_payoff;\n\tvector<int>::iterator it_wsep;\n    \n    \n\tif (verbose >=2) cout << \"(\" << player_l << \",\" << player_h << \") \" << \"orig. strategy : \" << strategy_focal_player << \"  orig. payoff : \" << payoff_focal_player << endl;\n\n\t\n\tif (force_migrate == 1) best_pay_off = -10;// assign an arbitrary small value to force migration to make sure a \"better\" spot can be found\n\telse best_pay_off = payoff_focal_player + 0.0001; // added a small value to ensure that only sites with higher payoff are selected\n\n    \n\tfor (int q=0; q < n_migration_sites; q++){\n        /* compute payoff on all possible migration sites */\n        \n        grid[player_l][player_h] = -1; //nasty hack to compute payoff assuming that the player has already left the site\n        \n\t\tmigration_payoff[q] = payoff(migration_array_l[q], migration_array_h[q],strategy_focal_player);\n        migration_distance[q] = compute_migration_distance(player_l, player_h,migration_array_l[q] ,migration_array_h[q]);\n\t\t\n        grid[player_l][player_h] = strategy_focal_player; // follow up nasty hack: restore original strategy because at this point is unclear whether the player will move\n        \n        if (migration_payoff[q] > best_pay_off) {\n            // find the highest possible payoff among all sites\n            best_pay_off = migration_payoff[q];\n            }\n    }\n    \n    \n\t//cout << \"\\n\";\n    \n\tfor (int j=0; j < n_migration_sites; j++) {\n        \n        //cout << \"(\"<< migration_array_l[j] << \",\" << migration_array_h[j] << \")\" << strategy_focal_player << \" \" << payoff(migration_array_l[j], migration_array_h[j],strategy_focal_player) << endl;\n\n        if (grid[migration_array_l[j]][migration_array_h[j]] == -1){\n            //find all EMPTY sites\n            it_e = sites_empty.end();\n            sites_empty.insert(it_e,j); // add site index to sites_empty vector\n\n            }\n        \n        \n        if (grid[migration_array_l[j]][migration_array_h[j]] > -1){\n            //find all OCCUPIED sites\n            it_o = sites_occupied.end();\n            sites_occupied.insert(it_o,j); // add site index to sites_occupied vector\n            \n        }\n        \n        \n\t\tif (migration_payoff[j] == best_pay_off) {\n            //find all EMPTY sites with HIGHEST payoff (there might be multiple ones)\n\t\t\tif (grid[migration_array_l[j]][migration_array_h[j]] == -1){\n\t\t\t\tit_bse = best_sites_empty.end();\n\t\t\t\tbest_sites_empty.insert(it_bse,j); // add site index to best_sites_empty vector\n            }\n\t\t\telse {\n                // find all OCCUPIED sites with highest payoff (there might be multiple ones)\n\t\t\t\tit_bso = best_sites_occupied.end();\n\t\t\t\tbest_sites_occupied.insert(it_bso,j); // add site index to best_sites_occupied vector\n            }\n        }\n\t\telse if ((grid[migration_array_l[j]][migration_array_h[j]] == -1) and (migration_payoff[j] < best_pay_off) and (migration_payoff[j] > payoff_focal_player)){\n            // find all EMPTY sites with HIGHER payoff\n\t\t\tit_rse = better_sites_empty.end();\n\t\t\tbetter_sites_empty.insert (it_rse,j); // add site index to better_sites_empty vector\n            \n            it_rsep = better_sites_empty_payoff.end();\n\t\t\tbetter_sites_empty_payoff.insert(it_rsep,j); // add site index to better_sites_empty vector\n        }\n\n        else if ((grid[migration_array_l[j]][migration_array_h[j]] == -1) and (migration_payoff[j] <= payoff_focal_player) and (force_migrate == 1)){\n            // find all EMPTY sites with LOWER payoff\n\t\t\tit_wse = worse_sites_empty.end();\n\t\t\tworse_sites_empty.insert(it_wse,j); // add site index to better_sites_empty vector\n            \n            it_wsep = worse_sites_empty_payoff.end();\n\t\t\tworse_sites_empty_payoff.insert(it_wsep,j); // add site index to better_sites_empty vecto\n        }\n\n        \n        \n\t\tif (verbose >= 2){\n\t\t\tcout << j\n\t\t\t<< \" (\"\n\t\t\t<< migration_array_l[j]\n\t\t\t<< \",\"\n\t\t\t<< migration_array_h[j]\n\t\t\t<< \") \"\n\t\t\t<< grid[migration_array_l[j]][migration_array_h[j]]\n\t\t\t<< \"  payoff: \" << pf << endl;\n\t\t}\n        \n\t}\n    \n    float rand_migration = rand01(); // draw a uniform random variable for random migration likelihood\n    float rand_expell = rand01();\n    \n    if (rand_migration < random_migration_likelihood) {  // random relocation\n    \n        if ((sites_occupied.size() > 0) and (rand_expell < expell)) {  // with property violation\n            //int size = sites_occupied.size();\n            //int r_site = arc4random_uniform(static_cast<int>(sites_occupied.size()));\n            index = sites_occupied[arc4random_uniform(static_cast<int>(sites_occupied.size()))];\n\n            \n            migration_type = \"RE\";\n            \n            mv_destination_l = migration_array_l[index];\n            mv_destination_h = migration_array_h[index];\n\n            shortest_distance = compute_migration_distance(player_l, player_h,mv_destination_l,mv_destination_h);\n            \n            \n            //cout << \"RE \"<< index << \" (\"<< mv_destination_l<< \",\" << mv_destination_h << \") \"<< endl;\n            \n            //cout << \"E \"<< size << \" \" << r_site << \" \"<< index << \" (\"<< mv_destination_l<< \",\" << mv_destination_h << \") \"<< endl;\n            \n            grid[player_l][player_h] = -1; // clear old site first to allow relocation of the expelled player to this site\n            //cout << \"expell: cleared site: (\" << player_l << \",\" << player_h << \") \" << grid[player_l][player_h] << \"\\n\";\n            compare_payoff_m_range(mv_destination_l,mv_destination_h,0,0,1); // force migration (recursive function)\n            grid[mv_destination_l][mv_destination_h] = sfp; // move agent (i.e., copy strategy from old to new site)\n            countCDE(); // count cooperators, defectors and empty sites\n            \n            \n        }\n        else if ((sites_empty.size() > 0) and (rand_expell > expell)){ // without property violation\n            //int size = sites_empty.size();\n            //int r_site = arc4random_uniform(static_cast<int>(sites_empty.size()));\n            index = sites_empty[arc4random_uniform(static_cast<int>(sites_empty.size()))];\n            \n    \n            migration_type = \"RM\";\n            \n            mv_destination_l = migration_array_l[index];\n            mv_destination_h = migration_array_h[index];\n            \n            shortest_distance = compute_migration_distance(player_l, player_h,mv_destination_l,mv_destination_h);\n            \n            //cout << \"M \"<< size << \" \" << r_site << \" \"<< index << \" (\"<< mv_destination_l<< \",\" << mv_destination_h << \") \"<< endl;\n            \n            \n            if (verbose >= 2) cout << \"best empty site: \"<< \"(\" << mv_destination_l << \",\" << mv_destination_h << \") \" << shortest_distance << \"\\n\"<< endl;\n            \n            grid[mv_destination_l][mv_destination_h] = strategy_focal_player;\n            grid[player_l][player_h] = -1;\n            countCDE(); // count cooperators, defectors and empty sites\n\n            \n        }\n        \n        else return;\n    }\n\n    else if ((best_sites_empty.size() > 0) and (rand_migration < (1 - random_migration_likelihood))){\n            /* find closest EMPTY site with highest payoff AND shortest dist*/\n        //shortest_distance = 1000;\n        for (int i=0; i < best_sites_empty.size(); i++) {\n            distance = compute_migration_distance(player_l, player_h,migration_array_l[best_sites_empty[i]], migration_array_h[best_sites_empty[i]]);\n            \n            if (distance < shortest_distance){\n                shortest_distance = distance;\n                chosen_migration_site = i;\n                }\n        }\n    \n        index = best_sites_empty[chosen_migration_site];\n        \n        if (force_migrate == 1) migration_type = \"FM\";\n        else migration_type = \"M\";\n    \n        mv_destination_l = migration_array_l[index];\n        mv_destination_h = migration_array_h[index];\n        \n        \n        if (verbose >= 2) cout << \"best empty site: \"<< \"(\" << mv_destination_l << \",\" << mv_destination_h << \") \" << shortest_distance << \"\\n\"<< endl;\n        \n        grid[mv_destination_l][mv_destination_h] = strategy_focal_player;\n        grid[player_l][player_h] = -1;\n        countCDE(); // count cooperators, defectors and empty sites\n    }\n    \n    \n    else if ((best_sites_empty.size() == 0) and (best_sites_occupied.size() > 0) and (rand_expell < expell)){\n        /* find closest OCCUPIED site with highest payoff (if no empty site with similar payoff is available */\n        //shortest_distance = 1000;\n        for (int i=0; i < best_sites_occupied.size(); i++) {\n            distance = compute_migration_distance(\n                player_l, player_h,\n                migration_array_l[best_sites_occupied[i]], migration_array_h[best_sites_occupied[i]]\n                );\n        \n            if (distance < shortest_distance){\n                shortest_distance = distance;\n                chosen_migration_site = i;\n            }\n        }\n    \n        index = best_sites_occupied[chosen_migration_site];\n        migration_type = \"E\";\n    \n        mv_destination_l = migration_array_l[index];\n        mv_destination_h = migration_array_h[index];\n    \n        grid[player_l][player_h] = -1; // clear old site first to allow relocation of the expelled player to this site\n        //cout << \"expell: cleared site: (\" << player_l << \",\" << player_h << \") \" << grid[player_l][player_h] << \"\\n\";\n        compare_payoff_m_range(mv_destination_l,mv_destination_h,0,0,1); // force migration (recursive function)\n        grid[mv_destination_l][mv_destination_h] = sfp; // move agent (i.e., copy strategy from old to new site)\n        countCDE(); // count cooperators, defectors and empty sites\n    }\n    \n    else if ((better_sites_empty.size() > 0) and (rand_migration < (1 - random_migration_likelihood))) {\n        /* Find the best available site with higher payoff, if all sites with highest payoff are occupied and the property violation step has not occurred (resp. if the player is forced to move)*/\n        best_pay_off = payoff_focal_player;\n        \n        for (int i=0; i < better_sites_empty.size(); i++) {\n            distance = compute_migration_distance(player_l, player_h,migration_array_l[better_sites_empty[i]], migration_array_h[better_sites_empty[i]]);\n    \n            if (distance < shortest_distance){\n                shortest_distance = distance;\n                chosen_migration_site = i;\n            }\n        }\n        \n        index = better_sites_empty[chosen_migration_site];\n        \n        \n        if (force_migrate == 1) migration_type = \"FM\";\n        else migration_type = \"M\";\n        \n        mv_destination_l = migration_array_l[index];\n        mv_destination_h = migration_array_h[index];\n        \n        shortest_distance = compute_migration_distance(player_l, player_h,mv_destination_l, mv_destination_h);\n        \n        if (verbose >= 2 and force_migrate==1) cout << \"better empty site: \"<< \"(\" << mv_destination_l << \",\" << mv_destination_h << \") \" << shortest_distance << \"\\n\"<< endl;\n        \n        \n        grid[mv_destination_l][mv_destination_h] = strategy_focal_player;\n        grid[player_l][player_h] = -1;\n        countCDE(); // count cooperators, defectors and empty sites\n    }\n    \n    else if ((worse_sites_empty.size() > 0) and (rand_migration < (1 - random_migration_likelihood))) {\n        \n        for (int i=0; i < worse_sites_empty.size(); i++) {\n            distance = compute_migration_distance(player_l, player_h,migration_array_l[worse_sites_empty[i]], migration_array_h[worse_sites_empty[i]]);\n            \n            if (distance < shortest_distance){\n                shortest_distance = distance;\n                chosen_migration_site = i;\n            }\n        }\n        \n        index = worse_sites_empty[chosen_migration_site];\n        \n        \n        if (force_migrate == 1) migration_type = \"FM\";\n        else migration_type = \"M\";\n        \n        mv_destination_l = migration_array_l[index];\n        mv_destination_h = migration_array_h[index];\n        \n        shortest_distance = compute_migration_distance(player_l, player_h,mv_destination_l, mv_destination_h);\n        \n        if (verbose >= 2 and force_migrate==1) cout << \"worse empty site: \"<< \"(\" << mv_destination_l << \",\" << mv_destination_h << \") \" << shortest_distance << \"\\n\"<< endl;\n        \n        \n        grid[mv_destination_l][mv_destination_h] = strategy_focal_player;\n        grid[player_l][player_h] = -1;\n        countCDE(); // count cooperators, defectors and empty sites\n    }\n\n    \n    else {\n        /*\n        if (force_migrate==1) {\n            cout << current_step << \"  blah\" << endl;\n            cout << worse_sites_empty.size() << \" \" << rand_migration <<endl;\n            verbose = 2;\n            explore_m_range(player_l, player_h);\n            verbose = 1;\n            \n        }\n        */\n        return;\n    }\n\n\n    // write update to output_all_mv file\n    output_all_mv  << current_step <<\",\"\n    << cooperators << \",\"\n    << defectors << \",\"\n    << empty << \",\"\n    << migration_type << \",\"\n    << player_l << \",\"\n    << player_h << \",\"\n    << mv_destination_l << \",\"\n    << mv_destination_h << \",\"\n    << grid[mv_destination_l][mv_destination_h] << \",\"\n    << payoff(mv_destination_l, mv_destination_h,grid[mv_destination_l][mv_destination_h]) - payoff(player_l, player_h, grid[mv_destination_l][mv_destination_h]) << \",\"\n    << shortest_distance\n    << \"\\n\";\n    \n    count_changes +=1;\n    \n    focal_player_l = mv_destination_l;\n    focal_player_h = mv_destination_h;\n\n    }\n\n\nvoid oneStep(){\n\t/*Performs one step of the simulation:\n\t a: compare payoffs with those of neighbors\n\t b: update strategy (not implemented yet)\n\t c: explore migration range M\n     */\n    \n\tfocal_player_l = rand_steps_l[current_step];\n\tfocal_player_h = rand_steps_h[current_step];\n\tstrategy_focal_player = grid[focal_player_l][focal_player_h];\n\t\n\tif ((strategy_focal_player != -1) and migration_range > 0){\n        compare_payoff_m_range(focal_player_l, focal_player_h,random_migration,expell_likelihood,0);\n        compare_payoff_with_nghbs(focal_player_l,focal_player_h,1);\n    }\n    else if ((strategy_focal_player != -1) and migration_range == 0){\n        compare_payoff_with_nghbs(focal_player_l,focal_player_h,1);\n    }\n    \n\tif (verbose >= 2){\n\t\tcout << \"( \" << focal_player_l << \",\" << focal_player_h << \") \" << strategy_focal_player << endl;\n    }\n}\n\n\nvoid randomSteps(){\n\t// Generate random grids (randSteps_l and randSteps_h) of size MCS\n\t//srand ( time(NULL) ); //initialize the random seed\n\tfor(int i=0; i < MCS; i++){\n\t\trand_steps_l[i] = arc4random_uniform(l);\n\t\trand_steps_h[i] = arc4random_uniform(h);\n\t}\n}\n\nvoid simulate(){\n\t\n\trandomSteps();\n\tcountCDE();\n    summary = format_summary();\n    output_summary << summary;\n    save_grid_state();\n    //showGrid();\n    \n    int coop_count;\n    \n    if (verbose > 0) cout << \"(start) \" << 0/static_cast<float>(MCS)*100 << \"% \" << static_cast<float>(cooperators)/(cooperators + defectors)*100 << \"%\\tcooperators: \" << cooperators << \", defectors:\" << defectors << \", empty sites:\" << empty << endl;\n\tif (verbose >= 2) showGrid();\n\t\n\tfor (int i=0; i<MCS; i++) {\n\t\t\n\t\tif ((count_changes)%100 == 0) {\n\t\t\tcountCDE();\n            coop_count = cooperators;\n            \n            summary = format_summary();\n            output_summary << summary;\n            if (save_grids > 0) {\n                save_grid_state();\n                }\n            \n\t\t\tif (verbose > 0) cout << summary;\n\t\t\telse if (verbose >= 2) showGrid();\n            \n            count_changes += 1; // just to make sure the same grid does not show up again if no change occurs\n\t\t\t\n        }\n\t\tif ((cooperators == 0) or (defectors == 0)){\n            countCDE();\n            \n            summary = format_summary();\n            output_summary << summary;\n            save_grid_state();\n            \n            if (verbose > 0) cout << summary;\n            \n\t\t\tif (verbose >= 2) showGrid();\n            break;\n        }\n\t\t\n\t\tif (i+1 == MCS){\n            countCDE();\n             summary = format_summary();\n            output_summary << summary;\n            save_grid_state();\n\t\t\tif (verbose > 0) cout << summary;\n            if (verbose >= 2) showGrid();\n\t\t\tbreak;\n        }\n        \n\t\tcurrent_step = i;\n\t\toneStep();\n    }\n\toutput_all_mv.close(); // close output_all_mv file;\n    output_summary.close(); // close output summary file;\n    output_grid_states.close(); // close grid state file;\n};\n\n\nvoid testing(){\n    /*\n\tcout << \"1. Test Make Grid\\n\" << endl;\n\tmakeGrid();\n\tshowGrid();\n\tcountCDE();\n\tcout << \"cooperators:\t\" << cooperators << \", defectors:\" << defectors << \", empty sites:\" << empty << endl;\n    \n     cout << \"\\n2. Test Find Neighbors\" << endl;\n     int player_l = 4;\n     int player_h = 9;\n     cout << \"focal player: \" << player_l << \",\" << player_h << endl;\n     findNeighbors(player_l,player_h);\n     \n     \n     cout << \"\\n3. Test Prisoners' Dilemma\" << endl;\n     \n     pDilemma(0,0);\n     cout << payoff_focal_player << endl;\n     \n     cout << \"\\n4. Test One Step Simmulation\" << endl;\n     randomSteps();\n     current_step = 10;\n     oneStep();\n     \n     \n     cout << \"\\n5. Test explore Migration Range\" << endl;\n     current_step = 10;\n     randomSteps();\n     focal_player_l = rand_steps_l[current_step];\n     focal_player_h = rand_steps_h[current_step];\n     \n     explore_m_range(focal_player_l,focal_player_h);\n     cout << endl;\n     \n     cout << \"\\n6. Test compare payoffs migration range\" << endl;\n     compare_payoff_m_range(focal_player_l,focal_player_h);\n     */\n    \n    /*\n     cout << \"\\n7. Test Fermi Update\" << endl;\n     strategy_update_Fermi(4, 6.);\n     */\n\n    /*\n    cout << \"\\n8. Test Migration distance\" << endl;\n    cout << compute_migration_distance(12, 17, 47, 3) << endl;\n    */\n    \n    cout << \"\\n5. Test Whole Simulation\" << endl;\n    simulate();\n    cout << MCS << \" done\" << endl;\n\n    /*\n     \n     char str[10];\n     \n     //Creates an instance of ofstream, and opens example.txt\n     ofstream a_file ( \"example.txt\" , ios::trunc);\n     // Outputs to example.txt through a_file\n     \n     for (int i=0; i < 100000; i++) {\n     a_file << \"This text will now be inside of example.txt\\n\";\n     }\n     // Close the file stream explicitly\n     \n     a_file.close();\n     //Opens for reading the file\n     \n     \n     string line;\n     ifstream b_file ( \"example.txt\" );\n     while (std::getline(b_file, line)){\n     cout << line;\n     }\n     //Reads one string from the file\n     b_file >> str;\n     //Should output 'this'\n     cout<< str <<\"\\n\";\n     //cin.get();    // wait for a keypress\n     // b_file is closed implicitly here\n     */\n    }\n\n\n\nint main(int ac, char* av[])\n    {\n        try {\n            string config_file;\n            \n            \n            // Declare a group of options that will be\n            // allowed only on command line\n            po::options_description generic(\"Generic options\");\n            generic.add_options()\n            (\"version,v\", \"print version string\")\n            (\"help\", \"produce help message\")\n            (\"config,c\", po::value<string>(&config_file)->default_value(\"pgame.cfg\"),\n             \"name of a file with configuration.\")\n            ;\n            \n            // Declare a group of options that will be\n            // allowed both on command line and in\n            // config file\n            po::options_description config(\"Configuration\");\n            config.add_options()\n            (\"verbose\", po::value<int>(&verbose)->default_value(0),\"verbose 0 to 3 (default 0)\")\n            (\"iterations,i\", po::value<int>(&iterations)-> default_value(200),\"number of iterations\")\n            (\"grid_length,l\",po::value<int>(&l)-> default_value(50),\"grid length\")\n            (\"grid_height,h\",po::value<int>(&h)-> default_value(50),\"grid heigth\")\n            (\"grid_density,d\",po::value<float>(&grid_density) -> default_value(0.5),\"grid density (between 0 and 1)\")\n            (\"load_grid,g\", po::value<string>(&grid_load_filename),\n             \"name of a file with initial grid configuration.\")\n            (\"save_grids\", po::value<int>(&save_grids),\n             \"save intermediary grids.\")\n            (\"init_coop_level\",po::value<float>(&init_coop_level) -> default_value(0.5),\"cooperation level at initialization (between 0 and 1)\")\n            (\"neighbors,n\",po::value<int>(&numNeighbors)-> default_value(4),\"set 4 or 8 neighbors to play with\")\n            (\"migration_range,M\",po::value<int>(&migration_range) -> default_value(5),\"migration range (M >= 1)\")\n            (\"imitation_likelihood,r\",po::value<float>(&imitation_likelihood)-> default_value(0),\"probability r to imitate best neighbor (between 0 and 1)\")\n            (\"reset_strategy_likelihood,q\",po::value<float>(&reset_strategy_likelihood)-> default_value(0),\"probability q to reset strategy (between 0 and 1). Cooperate with probability q and to defect with probability 1-q\")\n            (\"random_migration,m\",po::value<float>(&random_migration)-> default_value(1),\"random migration (m between 0 and 1)\")\n            (\"expell_likelihood,s\",po::value<float>(&expell_likelihood)-> default_value(0),\"expell_likelihood (between 0 and 1)\")\n            (\"temptation,T\",po::value<float>(&T)-> default_value(1.3),\"temptation payoff (c.f., game theory to tune this parameter)\")\n            (\"reward,R\",po::value<float>(&R)->default_value(1.0),\"cooperation reward payoff(c.f., game theory to tune this parameter)\")\n            (\"punishment,P\",po::value<float>(&P)->default_value(0.1),\"reciprocator payoff (c.f., game theory to tune this parameter)\")\n            (\"sucker,S\",po::value<float>(&S)->default_value(0.0),\"sucker payoff (c.f., game theory to tune this parameter)\")\n            ;\n            \n            // Hidden options, will be allowed both on command line and\n            // in config file, but will not be shown to the user.\n            \n            po::options_description hidden(\"Hidden options\");\n            hidden.add_options()\n            ;\n            \n            po::options_description cmdline_options;\n            cmdline_options.add(generic).add(config).add(hidden);\n            \n            po::options_description config_file_options;\n            config_file_options.add(config).add(hidden);\n            \n            po::options_description visible(\"Allowed options\");\n            visible.add(generic).add(config);\n            \n            po::positional_options_description p;\n            //p.add(\"input-file\", -1);\n            \n            po::variables_map vm;\n            store(po::command_line_parser(ac, av).\n                  options(cmdline_options).positional(p).run(), vm);\n            notify(vm);\n            \n            ifstream ifs(config_file.c_str());\n            if (!ifs)\n            {\n                cout << \"can not open config file: \" << config_file << \"\\n\";\n                return 0;\n            }\n            else\n            {\n                store(parse_config_file(ifs, config_file_options), vm);\n                notify(vm);\n            }\n            \n            if (vm.count(\"help\")) {\n                cout << visible << \"\\n\";\n                return 0;\n            }\n            \n            if (vm.count(\"version\")) {\n                cout << \"Property Game, version 1.0\\n\";\n                return 0;\n            }\n            \n        }\n        catch(exception& e)\n        {\n            cout << e.what() << \"\\n\";\n            return 1;\n        }\n        \n        prepare_parameters();\n\n        \n        if (fileExists(grid_load_filename)) {\n            cout << \"loading grid from \" << grid_load_filename << endl;\n            load_grid();\n            //showGrid();\n            //cout << format_summary()<< endl;\n        }\n        else {\n            cout << \"generating new grid\" << endl;\n            makeGrid();\n        }\n        \n        open_output_files();\n        //testing();\n        \n        simulate();\n        return 0;\n    }\n\n\n\n\n\n\n\n", "meta": {"hexsha": "d3e944cac209c2cf08180311f53daa8eca72052e", "size": 43553, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xcode/source/main.cpp", "max_stars_repo_name": "wazaahhh/pgames", "max_stars_repo_head_hexsha": "acf6fbb86d689ee307b6b2f807bc29fb6a818535", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xcode/source/main.cpp", "max_issues_repo_name": "wazaahhh/pgames", "max_issues_repo_head_hexsha": "acf6fbb86d689ee307b6b2f807bc29fb6a818535", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-11-06T18:21:13.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-06T20:28:50.000Z", "max_forks_repo_path": "xcode/source/main.cpp", "max_forks_repo_name": "wazaahhh/pgames", "max_forks_repo_head_hexsha": "acf6fbb86d689ee307b6b2f807bc29fb6a818535", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-01T15:55:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T15:55:10.000Z", "avg_line_length": 31.5372918175, "max_line_length": 251, "alphanum_fraction": 0.5829908387, "num_tokens": 11167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4396655553432139}}
{"text": "\r\n///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright 2013 Nikhar Agrawal\r\n//  Copyright 2013 Christopher Kormanyos\r\n//  Copyright 2013 John Maddock\r\n//  Copyright 2013 Paul Bristow\r\n//  Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef _BOOST_POLYGAMMA_2013_07_30_HPP_\r\n  #define _BOOST_POLYGAMMA_2013_07_30_HPP_\r\n\r\n  #include <boost/array.hpp>\r\n  #include <boost/cstdint.hpp>\r\n  #include <boost/math/special_functions/factorials.hpp>\r\n  #include \"detail/polygamma.hpp\"\r\n\r\n  namespace boost { namespace math {\r\n\r\n  template<class T>\t  \r\n  struct promoteftod\r\n  {\r\n\t  typedef T type;\r\n  };  \r\n\r\n  template<>\r\n  struct promoteftod<float>\r\n  {\r\n\t  typedef double type;\r\n  };\r\n\r\n  template<class T, class Policy>\r\n  inline T polygamma(const int n, T x, const Policy &pol)\r\n  {\r\n\ttypedef typename promoteftod<T>::type result_type;\r\n//\tstd::cout<<\"~:\"<<typeid(T).name()<<std::endl;\r\n//\tstd::cout<<\"~:\"<<typeid(result_type).name()<<std::endl;\r\n\tresult_type xx=result_type(x);\r\n        result_type result= boost::math::detail::polygamma_imp(n,xx,pol);\r\n\treturn T(result);\r\n  }\r\n\r\n  template<class T>\r\n  inline T polygamma(const int n, T x)\r\n  {\r\n      return boost::math::polygamma(n,x,policies::policy<>());\r\n  }\r\n\r\n/*  template<class T, class Policy>\r\n  inline T digamma(T x, const Policy &pol)\r\n  {\r\n      return boost::math::polygamma(0,x,pol);\r\n  }\r\n\r\n  template<class T>\r\n  inline T digamma(T x)\r\n  {\r\n      return boost::math::digamma(x,policies::policy<>());\r\n  }\r\n*/\r\n  template<class T, class Policy>\r\n  inline T trigamma(T x, const Policy &pol)\r\n  {\r\n      return boost::math::polygamma(1,x,pol);\r\n  }\r\n\r\n  template<class T>\r\n  inline T trigamma(T x)\r\n  {\r\n      return boost::math::trigamma(x,policies::policy<>());\r\n  }\r\n\r\n\r\n} } // namespace boost::math\r\n\r\n#endif // _BOOST_BERNOULLI_2013_05_30_HPP_\r\n", "meta": {"hexsha": "5b82448b4473a4cb48e664bb86a1ad4f22c239fb", "size": 1968, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SigTM/external/boost_sub/math/special_functions/polygamma.hpp", "max_stars_repo_name": "regenschauer490/TopicModel", "max_stars_repo_head_hexsha": "d9a2be5801d7e4da7429bca828039accf1b30033", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SigTM/external/boost_sub/math/special_functions/polygamma.hpp", "max_issues_repo_name": "regenschauer490/TopicModel", "max_issues_repo_head_hexsha": "d9a2be5801d7e4da7429bca828039accf1b30033", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SigTM/external/boost_sub/math/special_functions/polygamma.hpp", "max_forks_repo_name": "regenschauer490/TopicModel", "max_forks_repo_head_hexsha": "d9a2be5801d7e4da7429bca828039accf1b30033", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2307692308, "max_line_length": 80, "alphanum_fraction": 0.6244918699, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4396475548936777}}
{"text": "﻿//\n// Copyright © 2017 Arm Ltd. All rights reserved.\n// See LICENSE file in the project root for full license information.\n//\n\n#include \"ConvImpl.hpp\"\n\n#include <boost/assert.hpp>\n\n#include <cmath>\n#include <limits>\n\nnamespace armnn\n{\n\nQuantizedMultiplierSmallerThanOne::QuantizedMultiplierSmallerThanOne(float multiplier)\n{\n    BOOST_ASSERT(multiplier >= 0.0f && multiplier < 1.0f);\n    if (multiplier == 0.0f)\n    {\n        m_Multiplier = 0;\n        m_RightShift = 0;\n    }\n    else\n    {\n        const double q = std::frexp(multiplier, &m_RightShift);\n        m_RightShift = -m_RightShift;\n        int64_t qFixed = static_cast<int64_t>(std::round(q * (1ll << 31)));\n        BOOST_ASSERT(qFixed <= (1ll << 31));\n        if (qFixed == (1ll << 31))\n        {\n            qFixed /= 2;\n            --m_RightShift;\n        }\n        BOOST_ASSERT(m_RightShift >= 0);\n        BOOST_ASSERT(qFixed <= std::numeric_limits<int32_t>::max());\n        m_Multiplier = static_cast<int32_t>(qFixed);\n    }\n}\n\nint32_t QuantizedMultiplierSmallerThanOne::operator*(int32_t rhs) const\n{\n    int32_t x = SaturatingRoundingDoublingHighMul(rhs, m_Multiplier);\n    return RoundingDivideByPOT(x, m_RightShift);\n}\n\nint32_t QuantizedMultiplierSmallerThanOne::SaturatingRoundingDoublingHighMul(int32_t a, int32_t b)\n{\n    // Check for overflow.\n    if (a == b && a == std::numeric_limits<int32_t>::min())\n    {\n        return std::numeric_limits<int32_t>::max();\n    }\n    int64_t a_64(a);\n    int64_t b_64(b);\n    int64_t ab_64 = a_64 * b_64;\n    int32_t nudge = ab_64 >= 0 ? (1 << 30) : (1 - (1 << 30));\n    int32_t ab_x2_high32 = static_cast<std::int32_t>((ab_64 + nudge) / (1ll << 31));\n    return ab_x2_high32;\n}\n\nint32_t QuantizedMultiplierSmallerThanOne::RoundingDivideByPOT(int32_t x, int exponent)\n{\n    BOOST_ASSERT(exponent >= 0 && exponent <= 31);\n    int32_t mask = (1 << exponent) - 1;\n    int32_t remainder = x & mask;\n    int32_t threshold = (mask >> 1) + (x < 0 ? 1 : 0);\n    return (x >> exponent) + (remainder > threshold ? 1 : 0);\n}\n\n} //namespace armnn\n", "meta": {"hexsha": "3dcd3441011942a6fd93b09e1c05ab814d6204b6", "size": 2048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/armnn/backends/RefWorkloads/ConvImpl.cpp", "max_stars_repo_name": "KevinRodrigues05/armnn_caffe2_parser", "max_stars_repo_head_hexsha": "c577f2c6a3b4ddb6ba87a882723c53a248afbeba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/armnn/backends/RefWorkloads/ConvImpl.cpp", "max_issues_repo_name": "KevinRodrigues05/armnn_caffe2_parser", "max_issues_repo_head_hexsha": "c577f2c6a3b4ddb6ba87a882723c53a248afbeba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/armnn/backends/RefWorkloads/ConvImpl.cpp", "max_forks_repo_name": "KevinRodrigues05/armnn_caffe2_parser", "max_forks_repo_head_hexsha": "c577f2c6a3b4ddb6ba87a882723c53a248afbeba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4444444444, "max_line_length": 98, "alphanum_fraction": 0.6342773438, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4396475477652647}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/random_spanning_tree.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <iostream>\n#include <boost/array.hpp>\n#include <string>\n#include <boost/foreach.hpp>\n#include <vector>\n#include <boost/unordered_map.hpp>\n#include <boost/tuple/tuple.hpp> \n#include <boost/tuple/tuple_io.hpp> \n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/property_map/shared_array_property_map.hpp>\n#include <boost/property_map/dynamic_property_map.hpp>\n#include <boost/graph/property_maps/constant_property_map.hpp>\n\n#ifdef DEBUG\n#define DEBUG_MSG(str) do { std::cout << str << std::endl; } while( false )\n#else\n#define DEBUG_MSG(str) do { } while ( false )\n#endif\n\n//Defining types\ntypedef boost::property<boost::edge_weight_t, double> EdgeWeightProperty;\ntypedef boost::adjacency_list < \n    boost::vecS, boost::vecS, boost::directedS,\n    boost::no_property,EdgeWeightProperty > digraph_t;\n\n// typedef boost::property<boost::edge_index_t, int> EdgeWeightProperty;\n// typedef boost::adjacency_list < boost::vecS, boost::vecS, boost::directedS,\n// boost::no_property,boost::property< boost::edge_index_t, std::size_t > > digraph_t;\n\n\ntypedef boost::unordered_map<std::string,double> unordered_map;\nboost::random::mt19937 rng;\n\n#ifdef DEBUG_L2\nint MAXIT = 10;\n#else\nint MAXIT = 10000;\n#endif\n\n/*\nMacro to return \"v1->v2\"\n(Used to avoid implementing a hash function for tuples)\n*/\n#define getKey(v1,v2) std::to_string((long long unsigned int)v1)+\"->\"+std::to_string((long long unsigned int)v2)\n\n/*\nInitialize a graph using the edge list \n*/\nvoid initializeGraph(std::vector<boost::tuple<int,int,double> > edgeList, \n                    digraph_t* g,\n                    unordered_map* map) \n{   \n    int v1,v2;\n    double wt;\n    boost::tuple<int,int,double> t;\n    BOOST_FOREACH ( t, edgeList)\n    {\n        v1 = boost::get<0>(t);\n        v2 = boost::get<1>(t);\n        wt = boost::get<2>(t);\n        DEBUG_MSG(\"Loading: \"<<v1<<\"->\"<<v2<<\" : \"<<wt);\n        add_edge(v1,v2,wt,*g);\n        map->insert(unordered_map::value_type(getKey(v1,v2),0));\n    }\n}\n\n\n/*\nGiven an edgeList, run the test case\n*/\nvoid runTest(int n_vertices,std::vector<boost::tuple<int,int,double> > edgeList)\n{\n    digraph_t g;\n\n    unordered_map edgeProb;\n    initializeGraph(edgeList,&g,&edgeProb);\n    for (unordered_map::iterator it = edgeProb.begin(); it != edgeProb.end(); ++it) \n        DEBUG_MSG(it->first << \", \" << it->second);\n    \n    // boost::shared_array_property_map\n    // < \n    // double, boost::property_map<digraph_t, boost::edge_weight_t> \n    // > weight(num_edges(g), get(edge_weight, g));\n\n    //BGL_FORALL_EDGES(e, g, digraph_t) {put(weight, e, (1. + get(edge_index, g, e)) / num_edges(g));}\n  \n    BGL_FORALL_EDGES(e, g, digraph_t) \n    {\n        std::cout<<e<<std::endl;\n        //put(weight, e, (1. + get(edge_index, g, e)) / num_edges(g));\n    }\n\n    std::vector<int> predecessors (n_vertices);\n    std::vector<double> root_prob (n_vertices);\n    for(int i=0;i<n_vertices;i++)\n    {\n        predecessors[i]=0;\n        root_prob[i] = 0;\n    }\n    int root;\n    boost::random::uniform_int_distribution<> dist(0, n_vertices-1);\n    for(int i=1;i<=MAXIT;i++)\n    {\n        //Sample root uniformly \n        root = dist(rng);\n        #ifdef DEBUG_L2 //Since the DEBUG_MSG macro prints newline\n            std::cout<<i<<\"|\"<<root<<\"|,\"<<std::flush;\n        #endif\n        boost::random_spanning_tree(g,rng,\n            boost::predecessor_map(\n                boost::make_iterator_property_map(\n                    predecessors.begin(), get(boost::vertex_index, g))).\n            root_vertex(root));\n\n        // boost::random_spanning_tree(g,rng,(boost::graph_traits<digraph_t>::vertex_descriptor)root,\n        //     boost::predecessor_map(\n        //         boost::make_iterator_property_map(\n        //             predecessors.begin(), get(boost::vertex_index, g))));\n        \n        //Update counts\n        root_prob[root]+=1;\n        #ifdef DEBUG_L2 \n        std::cout<<\"Tree Found\"<<std::endl;\n        #endif\n\n        for(int i=0;i<n_vertices;i++)\n        {\n            if(predecessors[i]!=-1)\n            {\n                edgeProb.at(getKey(predecessors[i],i)) +=1;\n                #ifdef DEBUG_L2\n                std::cout<<predecessors[i]<<\"->\"<<i<<std::endl;\n                #endif\n            }\n            else\n            {\n            \t#ifdef DEBUG_L2\n            \tstd::cout<<\"r<\"<<i<<\">\"std::endl;;\n            \t#endif\n                if(root!=i)\n                {\n                    std::cout<<\"Error. root=\"<<root<<\" i=\"<<i<<std::endl;\n                    exit(1);\n                }\n\n            }\n            \n        }\n\n    }\n    DEBUG_MSG(\"\");\n\n    std::cout<<\"---RESULT---\"<<std::endl;\n    //Normalize root and edge probabilities\n    for (int i=0;i<n_vertices;i++)\n    {\n        root_prob[i]/=MAXIT;\n        std::cout<<\"Node \"<<i<<\" : \" << root_prob[i] << std::endl;\n    }\n    for (unordered_map::iterator it = edgeProb.begin(); it != edgeProb.end(); ++it) \n    {\n        std::cout << it->first << \": \" << (it->second/MAXIT) << std::endl; \n    } \n}\n\n/*\n4 node grid\n\nExpected Result (Uniform) : The edges in grid should all have 1/4 probabilities, the edge\nmoving outside should have \n*/\nvoid tc1()\n{\n    int n_vertices = 4;\n    std::cout<<\"----------- 4 Node Grid (Uniform) ------------\"<<std::endl;\n    std::vector<boost::tuple<int,int,double> > edgeList = \n    {\n        boost::make_tuple(0,1,1), \n        boost::make_tuple(1,0,1),\n        boost::make_tuple(3,1,100), \n        boost::make_tuple(1,3,1),\n        boost::make_tuple(2,3,100), \n        boost::make_tuple(3,2,1),\n        boost::make_tuple(0,2,100), \n        boost::make_tuple(2,0,1)\n    };\n    runTest(n_vertices,edgeList);\n    std::cout<<\"----------- Done (Check Results Visually) ------------\"<<std::endl;\n}\n\n\nvoid tc2()\n{\n    int n_vertices = 4;\n    std::cout<<\"----------- 4 Node Grid (Non Uniform) ------------\"<<std::endl;\n    std::cout<<\"----------- 0-2-3-1 has highest probability ------------\"<<std::endl;\n    std::cout<<\"----------- 2-0-1-3 has second highest probability ------------\"<<std::endl;\n    std::vector<boost::tuple<int,int,double> > edgeList = \n    {\n        boost::make_tuple(0,1,50), \n        boost::make_tuple(1,0,10),\n        boost::make_tuple(3,1,100), \n        boost::make_tuple(1,3,50),\n        boost::make_tuple(2,3,100), \n        boost::make_tuple(3,2,10),\n        boost::make_tuple(0,2,100), \n        boost::make_tuple(2,0,50)\n    };\n    runTest(n_vertices,edgeList);\n    std::cout<<\"----------- Done (Check Results Visually) ------------\"<<std::endl;\n}\n\n\n\n/*\n4 node fully connected graph\n\nExpected Result (Uniform) : The edges in grid should all have 1/12 probabilities, the edge\nmoving outside should have \n\n*/\nvoid tc3()\n{\n    int n_vertices = 4;\n    std::cout<<\"----------- 4 Node Fully Connected (Uniform) ------------\"<<std::endl;\n    std::vector<boost::tuple<int,int,double> > edgeList = \n    {\n        boost::make_tuple(0,1,10), \n        boost::make_tuple(1,0,10),\n        boost::make_tuple(3,1,10), \n        boost::make_tuple(1,3,10),\n        boost::make_tuple(2,3,10), \n        boost::make_tuple(3,2,10),\n        boost::make_tuple(0,2,10), \n        boost::make_tuple(2,0,10),\n        boost::make_tuple(0,3,10), \n        boost::make_tuple(3,0,10),\n        boost::make_tuple(1,2,10), \n        boost::make_tuple(2,1,10)\n    };\n    runTest(n_vertices,edgeList);\n    std::cout<<\"----------- Done (Check Results Visually) ------------\"<<std::endl;\n\n}\n\n\n/*\nGraph with a single edge that appears in all \nundirected spanning trees. (2x2 grid graph + 1 extra outgrid edge)\n\nExpected Result (Uniform) : The edges in grid should all have equal probabilities, \nthe edges moving outside should have probability 0.5 for either direction\n*/\nvoid tc4()\n{\n    int n_vertices = 5;\n    std::cout<<\"----------- 4 Node Grid (Uniform) +1 ------------\"<<std::endl;\n    std::vector<boost::tuple<int,int,double> > edgeList = \n    {\n        boost::make_tuple(0,1,10), \n        boost::make_tuple(1,0,10),\n        boost::make_tuple(3,1,10), \n        boost::make_tuple(1,3,10),\n        boost::make_tuple(2,3,10), \n        boost::make_tuple(3,2,10),\n        boost::make_tuple(0,2,10), \n        boost::make_tuple(2,0,10),\n        boost::make_tuple(0,4,10), \n        boost::make_tuple(4,0,10)\n    };\n    runTest(n_vertices,edgeList);\n    std::cout<<\"----------- Done (Check Results Visually) ------------\"<<std::endl;\n\n}\n\nint main()\n{\n    tc1();\n    tc2();\n    tc3();\n    tc4();\n    return EXIT_SUCCESS;\n}\n\n/*\n\n    digraph_t g;\n    add_edge(0, 1,10, g);\n    add_edge(0, 2,10, g);\n    add_edge(1, 3,10, g);\n    add_edge(0, 4,10, g);\n    boost::array<int, 5> predecessors;\n\n    add_edge(1, 0,10, g);\n    add_edge(2, 0,10, g);\n    add_edge(3, 1,10, g);\n    add_edge(4, 0,10, g);\n\n    boost::random_spanning_tree(g,rng,\n    boost::predecessor_map(predecessors.begin()).root_vertex(0));\n    std::cout<<\"Spanning Tree\"<<std::endl;\n    int p = 0;\n    while (p != 5)\n    {\n    std::cout << predecessors[p++] << '\\n';\n    //p = predecessors[p];\n    }\n    // You should expect to see 0 1 3 2 4\n    return EXIT_SUCCESS;\n*/\n\n", "meta": {"hexsha": "ea2767f84591191231a04d1e6964e1c990c43438", "size": 9265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "random_spanning_tree_test.cpp", "max_stars_repo_name": "rahulk90/mcmc_directed_spanning_tree", "max_stars_repo_head_hexsha": "c6622e82107ca8377118893ce01571a2d0f9561b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "random_spanning_tree_test.cpp", "max_issues_repo_name": "rahulk90/mcmc_directed_spanning_tree", "max_issues_repo_head_hexsha": "c6622e82107ca8377118893ce01571a2d0f9561b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "random_spanning_tree_test.cpp", "max_forks_repo_name": "rahulk90/mcmc_directed_spanning_tree", "max_forks_repo_head_hexsha": "c6622e82107ca8377118893ce01571a2d0f9561b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2271293375, "max_line_length": 112, "alphanum_fraction": 0.5765785213, "num_tokens": 2604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4396475477652646}}
{"text": "#ifdef _MSC_VER\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n\n#define _USE_MATH_DEFINES\n#include \"gate_factory.hpp\"\n\n#include <Eigen/QR>\n#include <cmath>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n\n#include \"exception.hpp\"\n#include \"gate.hpp\"\n#include \"gate_matrix.hpp\"\n#include \"gate_matrix_diagonal.hpp\"\n#include \"gate_matrix_sparse.hpp\"\n#include \"gate_merge.hpp\"\n#include \"gate_named_one.hpp\"\n#include \"gate_named_pauli.hpp\"\n#include \"gate_named_two.hpp\"\n#include \"gate_noisy_evolution.hpp\"\n#include \"gate_reflect.hpp\"\n#include \"gate_reversible.hpp\"\n#include \"type.hpp\"\n\nnamespace gate {\nComplexMatrix get_IBMQ_matrix(double theta, double phi, double lambda);\n\nQuantumGateBase* Identity(UINT qubit_index) {\n    return new ClsIGate(qubit_index);\n}\nQuantumGateBase* X(UINT qubit_index) { return new ClsXGate(qubit_index); }\nQuantumGateBase* Y(UINT qubit_index) { return new ClsYGate(qubit_index); }\nQuantumGateBase* Z(UINT qubit_index) { return new ClsZGate(qubit_index); }\nQuantumGateBase* H(UINT qubit_index) { return new ClsHGate(qubit_index); }\nQuantumGateBase* S(UINT qubit_index) { return new ClsSGate(qubit_index); }\nQuantumGateBase* Sdag(UINT qubit_index) { return new ClsSdagGate(qubit_index); }\nQuantumGateBase* T(UINT qubit_index) { return new ClsTGate(qubit_index); }\nQuantumGateBase* Tdag(UINT qubit_index) { return new ClsTdagGate(qubit_index); }\nQuantumGateBase* sqrtX(UINT qubit_index) {\n    return new ClsSqrtXGate(qubit_index);\n}\nQuantumGateBase* sqrtXdag(UINT qubit_index) {\n    return new ClsSqrtXdagGate(qubit_index);\n}\nQuantumGateBase* sqrtY(UINT qubit_index) {\n    return new ClsSqrtYGate(qubit_index);\n}\nQuantumGateBase* sqrtYdag(UINT qubit_index) {\n    return new ClsSqrtYdagGate(qubit_index);\n}\nQuantumGateBase* P0(UINT qubit_index) { return new ClsP0Gate(qubit_index); }\nQuantumGateBase* P1(UINT qubit_index) { return new ClsP1Gate(qubit_index); }\nQuantumGateBase* RX(UINT qubit_index, double angle) {\n    return new ClsRXGate(qubit_index, angle);\n}\nQuantumGateBase* RY(UINT qubit_index, double angle) {\n    return new ClsRYGate(qubit_index, angle);\n}\nQuantumGateBase* RZ(UINT qubit_index, double angle) {\n    return new ClsRZGate(qubit_index, angle);\n}\n\nComplexMatrix get_IBMQ_matrix(double theta, double phi, double lambda) {\n    CPPCTYPE im(0, 1);\n    CPPCTYPE exp_val1 = exp(im * phi);\n    CPPCTYPE exp_val2 = exp(im * lambda);\n    CPPCTYPE cos_val = cos(theta / 2);\n    CPPCTYPE sin_val = sin(theta / 2);\n\n    ComplexMatrix matrix(2, 2);\n    matrix(0, 0) = cos_val;\n    matrix(0, 1) = -exp_val2 * sin_val;\n    matrix(1, 0) = exp_val1 * sin_val;\n    matrix(1, 1) = exp_val1 * exp_val2 * cos_val;\n    return matrix;\n}\nQuantumGateBase* U1(UINT qubit_index, double lambda) {\n    ComplexMatrix matrix = get_IBMQ_matrix(0, 0, lambda);\n    std::vector<UINT> vec;\n    vec.push_back(qubit_index);\n    return new QuantumGateMatrix(vec, matrix);\n}\nQuantumGateBase* U2(UINT qubit_index, double phi, double lambda) {\n    ComplexMatrix matrix = get_IBMQ_matrix(M_PI / 2, phi, lambda);\n    std::vector<UINT> vec;\n    vec.push_back(qubit_index);\n    return new QuantumGateMatrix(vec, matrix);\n}\nQuantumGateBase* U3(UINT qubit_index, double theta, double phi, double lambda) {\n    ComplexMatrix matrix = get_IBMQ_matrix(theta, phi, lambda);\n    std::vector<UINT> vec;\n    vec.push_back(qubit_index);\n    return new QuantumGateMatrix(vec, matrix);\n}\n\nQuantumGateBase* CNOT(UINT control_qubit_index, UINT target_qubit_index) {\n    if (control_qubit_index == target_qubit_index) {\n        throw InvalidControlQubitException(\n            \"Error: gate::CNOT(UINT, UINT): control_qubit_index and \"\n            \"target_qubit_index has the same value.\"\n            \"\\nInfo: NULL used to be returned, \"\n            \"but it changed to throw exception.\");\n    }\n    return new ClsCNOTGate(control_qubit_index, target_qubit_index);\n}\nQuantumGateBase* CZ(UINT control_qubit_index, UINT target_qubit_index) {\n    if (control_qubit_index == target_qubit_index) {\n        throw InvalidControlQubitException(\n            \"Error: gate::CZ(UINT, UINT): control_qubit_index and \"\n            \"target_qubit_index has the same value.\"\n            \"\\nInfo: NULL used to be returned, \"\n            \"but it changed to throw exception.\");\n    }\n    return new ClsCZGate(control_qubit_index, target_qubit_index);\n}\nQuantumGateBase* SWAP(UINT qubit_index1, UINT qubit_index2) {\n    if (qubit_index1 == qubit_index2) {\n        throw DuplicatedQubitIndexException(\n            \"Error: gate::SWAP(UINT, UINT): two indices have the same value.\"\n            \"\\nInfo: NULL used to be returned, \"\n            \"but it changed to throw exception.\");\n    }\n    return new ClsSWAPGate(qubit_index1, qubit_index2);\n}\n\nQuantumGateBase* Pauli(std::vector<UINT> target, std::vector<UINT> pauli_id) {\n    if (!check_is_unique_index_list(target)) {\n        throw DuplicatedQubitIndexException(\n            \"Error: gate::Pauli(std::vector<UINT> target, \"\n            \"std::vector<UINT>pauli_id): target list contains \"\n            \"duplicated values.\"\n            \"\\nInfo: NULL used to be returned, \"\n            \"but it changed to throw exception.\");\n    }\n    auto pauli = new PauliOperator(target, pauli_id);\n    return new ClsPauliGate(pauli);\n}\nQuantumGateBase* PauliRotation(\n    std::vector<UINT> target, std::vector<UINT> pauli_id, double angle) {\n    if (!check_is_unique_index_list(target)) {\n        throw DuplicatedQubitIndexException(\n            \"Error: gate::PauliRotation(std::vector<UINT> target, \"\n            \"std::vector<UINT>pauli_id, double angle): target list \"\n            \"contains duplicated values.\"\n            \"\\nInfo: NULL used to be returned, \"\n            \"but it changed to throw exception.\");\n    }\n    auto pauli = new PauliOperator(target, pauli_id, angle);\n    return new ClsPauliRotationGate(angle, pauli);\n}\n\nQuantumGateMatrix* DenseMatrix(UINT target_index, ComplexMatrix matrix) {\n    std::vector<UINT> target_list(1, target_index);\n    return new QuantumGateMatrix(target_list, matrix);\n}\nQuantumGateMatrix* DenseMatrix(\n    std::vector<UINT> target_list, ComplexMatrix matrix) {\n    if (!check_is_unique_index_list(target_list)) {\n        throw DuplicatedQubitIndexException(\n            \"Error: gate::DenseMatrix(std::vector<UINT> target_list, \"\n            \"ComplexMatrix matrix): target list contains duplicated values.\"\n            \"\\nInfo: NULL used to be returned, \"\n            \"but it changed to throw exception.\");\n    }\n    return new QuantumGateMatrix(target_list, matrix);\n}\n\nQuantumGateBase* SparseMatrix(\n    std::vector<UINT> target_list, SparseComplexMatrix matrix) {\n    if (!check_is_unique_index_list(target_list)) {\n        throw DuplicatedQubitIndexException(\n            \"Error: gate::SparseMatrix(std::vector<UINT> target_list, \"\n            \"SparseComplexMatrix matrix): target list contains duplicated \"\n            \"values.\"\n            \"\\nInfo: NULL used to be returned, \"\n            \"but it changed to throw exception.\");\n    }\n    return new QuantumGateSparseMatrix(target_list, matrix);\n}\nQuantumGateBase* DiagonalMatrix(\n    std::vector<UINT> target_list, ComplexVector diagonal_element) {\n    if (!check_is_unique_index_list(target_list)) {\n        throw DuplicatedQubitIndexException(\n            \"Error: gate::DiagonalMatrix(std::vector<UINT> target_list, \"\n            \"ComplexVector diagonal_element): target list contains \"\n            \"duplicated values.\"\n            \"\\nInfo: NULL used to be returned, \"\n            \"but it changed to throw exception.\");\n    }\n    return new QuantumGateDiagonalMatrix(target_list, diagonal_element);\n}\n\nQuantumGateMatrix* RandomUnitary(std::vector<UINT> target_list) {\n    if (!check_is_unique_index_list(target_list)) {\n        throw DuplicatedQubitIndexException(\n            \"Error: gate::RandomUnitary(std::vector<UINT> target_list): \"\n            \"target list contains duplicated values.\"\n            \"\\nInfo: NULL used to be returned, \"\n            \"but it changed to throw exception.\");\n    }\n    Random random;\n    UINT qubit_count = (UINT)target_list.size();\n    ITYPE dim = 1ULL << qubit_count;\n    ComplexMatrix matrix(dim, dim);\n    for (ITYPE i = 0; i < dim; ++i) {\n        for (ITYPE j = 0; j < dim; ++j) {\n            matrix(i, j) = (random.normal() + 1.i * random.normal()) / sqrt(2.);\n        }\n    }\n    Eigen::HouseholderQR<ComplexMatrix> qr_solver(matrix);\n    ComplexMatrix Q = qr_solver.householderQ();\n    // actual R matrix is upper-right triangle of matrixQR\n    auto R = qr_solver.matrixQR();\n    for (ITYPE i = 0; i < dim; ++i) {\n        CPPCTYPE phase = R(i, i) / abs(R(i, i));\n        for (ITYPE j = 0; j < dim; ++j) {\n            Q(j, i) *= phase;\n        }\n    }\n    return new QuantumGateMatrix(target_list, Q);\n}\nQuantumGateMatrix* RandomUnitary(std::vector<UINT> target_list, UINT seed) {\n    if (!check_is_unique_index_list(target_list)) {\n        throw DuplicatedQubitIndexException(\n            \"Error: gate::RandomUnitary(std::vector<UINT> target_list): \"\n            \"target list contains duplicated values.\"\n            \"\\nInfo: NULL used to be returned, \"\n            \"but it changed to throw exception.\");\n    }\n    Random random;\n    random.set_seed(seed);\n    UINT qubit_count = (UINT)target_list.size();\n    ITYPE dim = 1ULL << qubit_count;\n    ComplexMatrix matrix(dim, dim);\n    for (ITYPE i = 0; i < dim; ++i) {\n        for (ITYPE j = 0; j < dim; ++j) {\n            matrix(i, j) = (random.normal() + 1.i * random.normal()) / sqrt(2.);\n        }\n    }\n    Eigen::HouseholderQR<ComplexMatrix> qr_solver(matrix);\n    ComplexMatrix Q = qr_solver.householderQ();\n    // actual R matrix is upper-right triangle of matrixQR\n    auto R = qr_solver.matrixQR();\n    for (ITYPE i = 0; i < dim; ++i) {\n        CPPCTYPE phase = R(i, i) / abs(R(i, i));\n        for (ITYPE j = 0; j < dim; ++j) {\n            Q(j, i) *= phase;\n        }\n    }\n    return new QuantumGateMatrix(target_list, Q);\n}\nQuantumGateBase* ReversibleBoolean(std::vector<UINT> target_qubit_index_list,\n    std::function<ITYPE(ITYPE, ITYPE)> function_ptr) {\n    if (!check_is_unique_index_list(target_qubit_index_list)) {\n        throw DuplicatedQubitIndexException(\n            \"Error: gate::ReversibleBoolean(std::vector<UINT> \"\n            \"target_qubit_index_list, std::function<ITYPE(ITYPE,ITYPE)> \"\n            \"function_ptr): target list contains duplicated values.\"\n            \"\\nInfo: NULL used to be returned, \"\n            \"but it changed to throw exception.\");\n    }\n    return new ClsReversibleBooleanGate(target_qubit_index_list, function_ptr);\n}\nQuantumGateBase* StateReflection(const QuantumStateBase* reflection_state) {\n    return new ClsStateReflectionGate(reflection_state);\n}\n\nQuantumGateBase* BitFlipNoise(UINT target_index, double prob) {\n    auto gate0 = X(target_index);\n    auto gate1 = Identity(target_index);\n    auto new_gate =\n        new QuantumGate_Probabilistic({prob, 1 - prob}, {gate0, gate1});\n    delete gate0;\n    delete gate1;\n    return new_gate;\n}\nQuantumGateBase* DephasingNoise(UINT target_index, double prob) {\n    auto gate0 = Z(target_index);\n    auto gate1 = Identity(target_index);\n    auto new_gate =\n        new QuantumGate_Probabilistic({prob, 1 - prob}, {gate0, gate1});\n    delete gate0;\n    delete gate1;\n    return new_gate;\n}\nQuantumGateBase* IndependentXZNoise(UINT target_index, double prob) {\n    auto gate0 = X(target_index);\n    auto gate1 = Z(target_index);\n    auto gate2 = Y(target_index);\n    auto gate3 = Identity(target_index);\n    double p1 = prob * (1 - prob);\n    double p2 = prob * prob;\n    auto new_gate = new QuantumGate_Probabilistic(\n        {p1, p1, p2, 1 - 2 * p1 - p2}, {gate0, gate1, gate2, gate3});\n    delete gate0;\n    delete gate1;\n    delete gate2;\n    return new_gate;\n}\nQuantumGateBase* DepolarizingNoise(UINT target_index, double prob) {\n    auto gate0 = X(target_index);\n    auto gate1 = Z(target_index);\n    auto gate2 = Y(target_index);\n    auto gate3 = Identity(target_index);\n    auto new_gate = new QuantumGate_Probabilistic(\n        {prob / 3, prob / 3, prob / 3, 1 - prob}, {gate0, gate1, gate2, gate3});\n    delete gate0;\n    delete gate1;\n    delete gate2;\n    delete gate3;\n    return new_gate;\n}\nQuantumGateBase* TwoQubitDepolarizingNoise(\n    UINT target_index1, UINT target_index2, double prob) {\n    if (target_index1 == target_index2) {\n        throw DuplicatedQubitIndexException(\n            \"Error: gate::TwoQubitDepolarizingNoise(UINT, UINT, double): \"\n            \"target list contains duplicated values.\"\n            \"\\nInfo: NULL used to be returned, \"\n            \"but it changed to throw exception.\");\n    }\n    std::vector<QuantumGateBase*> gate_list;\n    for (int i = 0; i < 16; ++i) {\n        if (i != 0) {\n            UINT pauli_qubit1 = i % 4;\n            UINT pauli_qubit2 = i / 4;\n            auto gate_pauli = Pauli(\n                {target_index1, target_index2}, {pauli_qubit1, pauli_qubit2});\n            auto gate_dense = gate::to_matrix_gate(gate_pauli);\n            gate_list.push_back(gate_dense);\n        } else {\n            gate_list.push_back(Identity(target_index1));\n        }\n    }\n    std::vector<double> probabilities(16, prob / 15);\n    probabilities[0] = 1 - prob;\n    auto new_gate = new QuantumGate_Probabilistic(probabilities, gate_list);\n    for (UINT gate_index = 0; gate_index < 15; ++gate_index) {\n        delete gate_list[gate_index];\n    }\n    return new_gate;\n}\nQuantumGateBase* AmplitudeDampingNoise(UINT target_index, double prob) {\n    ComplexMatrix damping_matrix_0(2, 2), damping_matrix_1(2, 2);\n    damping_matrix_0 << 1, 0, 0, sqrt(1 - prob);\n    damping_matrix_1 << 0, sqrt(prob), 0, 0;\n    auto gate0 = DenseMatrix({target_index}, damping_matrix_0);\n    auto gate1 = DenseMatrix({target_index}, damping_matrix_1);\n    auto new_gate = new QuantumGate_CPTP({gate0, gate1});\n    delete gate0;\n    delete gate1;\n    return new_gate;\n}\nQuantumGateBase* Measurement(\n    UINT target_index, UINT classical_register_address) {\n    auto gate0 = P0(target_index);\n    auto gate1 = P1(target_index);\n    auto new_gate =\n        new QuantumGate_Instrument({gate0, gate1}, classical_register_address);\n    delete gate0;\n    delete gate1;\n    return new_gate;\n}\n\nQuantumGateBase* NoisyEvolution(Observable* hamiltonian,\n    std::vector<GeneralQuantumOperator*> c_ops, double time, double dt) {\n    return new ClsNoisyEvolution(hamiltonian, c_ops, time, dt);\n}\n\nQuantumGateBase* create_quantum_gate_from_string(std::string gate_string) {\n    const char* gateString = gate_string.c_str();\n    char* sbuf;\n    const char delim[] = \" \";\n    std::vector<UINT> targets;\n    QuantumGateBase* gate = NULL;\n    char* buf = (char*)calloc(strlen(gateString) + 1, sizeof(char));\n    strcpy(buf, gateString);\n    sbuf = strtok(buf, delim);\n\n    if (strcasecmp(sbuf, \"I\") == 0)\n        gate = gate::Identity(atoi(strtok(NULL, delim)));\n    else if (strcasecmp(sbuf, \"X\") == 0)\n        gate = gate::X(atoi(strtok(NULL, delim)));\n    else if (strcasecmp(sbuf, \"Y\") == 0)\n        gate = gate::Y(atoi(strtok(NULL, delim)));\n    else if (strcasecmp(sbuf, \"Z\") == 0)\n        gate = gate::Z(atoi(strtok(NULL, delim)));\n    else if (strcasecmp(sbuf, \"H\") == 0)\n        gate = gate::H(atoi(strtok(NULL, delim)));\n    else if (strcasecmp(sbuf, \"S\") == 0)\n        gate = gate::S(atoi(strtok(NULL, delim)));\n    else if (strcasecmp(sbuf, \"Sdag\") == 0)\n        gate = gate::Sdag(atoi(strtok(NULL, delim)));\n    else if (strcasecmp(sbuf, \"T\") == 0)\n        gate = gate::T(atoi(strtok(NULL, delim)));\n    else if (strcasecmp(sbuf, \"Tdag\") == 0)\n        gate = gate::Tdag(atoi(strtok(NULL, delim)));\n    else if (strcasecmp(sbuf, \"CNOT\") == 0 || strcasecmp(sbuf, \"CX\") == 0) {\n        unsigned int control = atoi(strtok(NULL, delim));\n        unsigned int target = atoi(strtok(NULL, delim));\n        gate = gate::CNOT(control, target);\n    } else if (strcasecmp(sbuf, \"CZ\") == 0) {\n        unsigned int control = atoi(strtok(NULL, delim));\n        unsigned int target = atoi(strtok(NULL, delim));\n        gate = gate::CZ(control, target);\n    } else if (strcasecmp(sbuf, \"SWAP\") == 0) {\n        unsigned int target1 = atoi(strtok(NULL, delim));\n        unsigned int target2 = atoi(strtok(NULL, delim));\n        gate = gate::SWAP(target1, target2);\n    } else if (strcasecmp(sbuf, \"U1\") == 0) {\n        unsigned int target = atoi(strtok(NULL, delim));\n        double theta1 = atof(strtok(NULL, delim));\n        gate = gate::U1(target, theta1);\n    } else if (strcasecmp(sbuf, \"U2\") == 0) {\n        unsigned int target = atoi(strtok(NULL, delim));\n        double theta1 = atof(strtok(NULL, delim));\n        double theta2 = atof(strtok(NULL, delim));\n        gate = gate::U2(target, theta1, theta2);\n    } else if (strcasecmp(sbuf, \"U3\") == 0) {\n        unsigned int target = atoi(strtok(NULL, delim));\n        double theta1 = atof(strtok(NULL, delim));\n        double theta2 = atof(strtok(NULL, delim));\n        double theta3 = atof(strtok(NULL, delim));\n        gate = gate::U3(target, theta1, theta2, theta3);\n    } else if (strcasecmp(sbuf, \"RX\") == 0) {\n        unsigned int target = atoi(strtok(NULL, delim));\n        double theta = atof(strtok(NULL, delim));\n        gate = gate::RX(target, theta);\n    } else if (strcasecmp(sbuf, \"RY\") == 0) {\n        unsigned int target = atoi(strtok(NULL, delim));\n        double theta = atof(strtok(NULL, delim));\n        gate = gate::RY(target, theta);\n    } else if (strcasecmp(sbuf, \"RZ\") == 0) {\n        unsigned int target = atoi(strtok(NULL, delim));\n        double theta = atof(strtok(NULL, delim));\n        gate = gate::RZ(target, theta);\n    } else if (strcasecmp(sbuf, \"RM\") == 0) {\n        char* pauliStr = strtok(NULL, delim);\n        unsigned int targetCount = (UINT)strlen(pauliStr);\n\n        std::vector<UINT> pauli(targetCount, 0);\n        for (unsigned int i = 0; i < targetCount; i++) {\n            if (pauliStr[i] == 'x' || pauliStr[i] == 'X')\n                pauli[i] = 1;\n            else if (pauliStr[i] == 'y' || pauliStr[i] == 'Y')\n                pauli[i] = 2;\n            else if (pauliStr[i] == 'z' || pauliStr[i] == 'Z')\n                pauli[i] = 3;\n        }\n\n        targets = std::vector<UINT>(targetCount, 0);\n        for (unsigned int i = 0; i < targetCount; i++) {\n            targets[i] = atoi(strtok(NULL, delim));\n        }\n\n        double theta = atof(strtok(NULL, delim));\n        gate = gate::PauliRotation(targets, pauli, theta);\n    } else if (strcasecmp(sbuf, \"U\") == 0) {\n        unsigned int targetCount = atoi(strtok(NULL, delim));\n\n        targets = std::vector<UINT>(targetCount, 0);\n        for (unsigned int i = 0; i < targetCount; i++) {\n            targets[i] = atoi(strtok(NULL, delim));\n        }\n        ITYPE dim = 1ULL << targetCount;\n        ComplexMatrix matrix(dim, dim);\n\n        for (ITYPE i = 0; i < dim * dim; i++) {\n            char* token;\n            token = strtok(NULL, delim);\n            matrix(i / dim, i % dim) = atof(token);\n            token = strtok(NULL, delim);\n            matrix(i / dim, i % dim) += CPPCTYPE(0, 1) * atof(token);\n        }\n        gate = gate::DenseMatrix(targets, matrix);\n    } else {\n        throw InvalidGateIdentifierException(\n            \"Error: \"\n            \"gate::create_quantum_gate_from_string(string): invalid gate \"\n            \"name \" +\n            std::string(sbuf));\n    }\n    free(buf);\n    return gate;\n}\n\n}  // namespace gate\n", "meta": {"hexsha": "cdbaa078abc38a5b7a27e70eccba362298bac779", "size": 19399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cppsim/gate_factory.cpp", "max_stars_repo_name": "Qulacs-Osaka/qulacs-osaka", "max_stars_repo_head_hexsha": "9ec1044c8214a64dbd1e1de7ad077e5cf779b3b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-26T06:56:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T02:07:24.000Z", "max_issues_repo_path": "src/cppsim/gate_factory.cpp", "max_issues_repo_name": "Qulacs-Osaka/qulacs-osaka", "max_issues_repo_head_hexsha": "9ec1044c8214a64dbd1e1de7ad077e5cf779b3b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 104.0, "max_issues_repo_issues_event_min_datetime": "2021-11-12T04:15:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T05:12:20.000Z", "max_forks_repo_path": "src/cppsim/gate_factory.cpp", "max_forks_repo_name": "Qulacs-Osaka/qulacs-osaka", "max_forks_repo_head_hexsha": "9ec1044c8214a64dbd1e1de7ad077e5cf779b3b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-12-19T11:52:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T04:20:17.000Z", "avg_line_length": 39.5091649695, "max_line_length": 80, "alphanum_fraction": 0.644930151, "num_tokens": 5215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4396061229302414}}
{"text": "/**\n * \\file\n * \\author Thomas Fischer\n * \\date   2010-03-17\n * \\brief  Implementation of analytical geometry functions.\n *\n * \\copyright\n * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include \"AnalyticalGeometry.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n\n\n#include <Eigen/Dense>\n\n#include \"BaseLib/StringTools.h\"\n\n#include \"Polyline.h\"\n#include \"PointVec.h\"\n\n#include \"MathLib/GeometricBasics.h\"\n\nextern double orient2d(double *, double *, double *);\nextern double orient2dfast(double*, double*, double*);\n\nnamespace ExactPredicates\n{\ndouble getOrientation2d(MathLib::Point3d const& a,\n    MathLib::Point3d const& b, MathLib::Point3d const& c)\n{\n    return orient2d(const_cast<double*>(a.getCoords()),\n        const_cast<double*>(b.getCoords()),\n        const_cast<double*>(c.getCoords()));\n}\n\ndouble getOrientation2dFast(MathLib::Point3d const& a,\n                            MathLib::Point3d const& b,\n                            MathLib::Point3d const& c)\n{\n    return orient2dfast(const_cast<double*>(a.getCoords()),\n                        const_cast<double*>(b.getCoords()),\n                        const_cast<double*>(c.getCoords()));\n}\n}  // namespace ExactPredicates\n\nnamespace GeoLib\n{\nOrientation getOrientation(MathLib::Point3d const& p0,\n                           MathLib::Point3d const& p1,\n                           MathLib::Point3d const& p2)\n{\n    double const orientation = ExactPredicates::getOrientation2d(p0, p1, p2);\n    if (orientation > 0)\n    {\n        return CCW;\n    }\n    if (orientation < 0)\n    {\n        return CW;\n    }\n    return COLLINEAR;\n}\n\nOrientation getOrientationFast(MathLib::Point3d const& p0,\n                               MathLib::Point3d const& p1,\n                               MathLib::Point3d const& p2)\n{\n    double const orientation =\n        ExactPredicates::getOrientation2dFast(p0, p1, p2);\n    if (orientation > 0)\n    {\n        return CCW;\n    }\n    if (orientation < 0)\n    {\n        return CW;\n    }\n    return COLLINEAR;\n}\n\nbool parallel(MathLib::Vector3 v, MathLib::Vector3 w)\n{\n    const double eps(std::numeric_limits<double>::epsilon());\n\n    // check degenerated cases\n    if (v.getLength() < eps)\n    {\n        return false;\n    }\n\n    if (w.getLength() < eps)\n    {\n        return false;\n    }\n\n    v.normalize();\n    w.normalize();\n\n    bool parallel(true);\n    if (std::abs(v[0] - w[0]) > eps)\n    {\n        parallel = false;\n    }\n    if (std::abs(v[1] - w[1]) > eps)\n    {\n        parallel = false;\n    }\n    if (std::abs(v[2] - w[2]) > eps)\n    {\n        parallel = false;\n    }\n\n    if (! parallel) {\n        parallel = true;\n        // change sense of direction of v_normalised\n        v *= -1.0;\n        // check again\n        if (std::abs(v[0] - w[0]) > eps)\n        {\n            parallel = false;\n        }\n        if (std::abs(v[1] - w[1]) > eps)\n        {\n            parallel = false;\n        }\n        if (std::abs(v[2] - w[2]) > eps)\n        {\n            parallel = false;\n        }\n    }\n\n    return parallel;\n}\n\nbool lineSegmentIntersect(GeoLib::LineSegment const& s0,\n                          GeoLib::LineSegment const& s1,\n                          GeoLib::Point& s)\n{\n    GeoLib::Point const& a{s0.getBeginPoint()};\n    GeoLib::Point const& b{s0.getEndPoint()};\n    GeoLib::Point const& c{s1.getBeginPoint()};\n    GeoLib::Point const& d{s1.getEndPoint()};\n\n    if (!isCoplanar(a, b, c, d))\n    {\n        return false;\n    }\n\n    // handle special cases here to avoid computing intersection numerical\n    if (MathLib::sqrDist(a, c) < std::numeric_limits<double>::epsilon() ||\n        MathLib::sqrDist(a, d) < std::numeric_limits<double>::epsilon()) {\n        s = a;\n        return true;\n    }\n    if (MathLib::sqrDist(b, c) < std::numeric_limits<double>::epsilon() ||\n        MathLib::sqrDist(b, d) < std::numeric_limits<double>::epsilon()) {\n        s = b;\n        return true;\n    }\n\n    MathLib::Vector3 const v(a, b);\n    MathLib::Vector3 const w(c, d);\n    MathLib::Vector3 const qp(a, c);\n    MathLib::Vector3 const pq(c, a);\n\n    auto isLineSegmentIntersectingAB = [&v](MathLib::Vector3 const& ap,\n                                            std::size_t i)\n    {\n        // check if p is located at v=(a,b): (ap = t*v, t in [0,1])\n        return 0.0 <= ap[i] / v[i] && ap[i] / v[i] <= 1.0;\n    };\n\n    if (parallel(v,w)) { // original line segments (a,b) and (c,d) are parallel\n        if (parallel(pq,v)) { // line segment (a,b) and (a,c) are also parallel\n            // Here it is already checked that the line segments (a,b) and (c,d)\n            // are parallel. At this point it is also known that the line\n            // segment (a,c) is also parallel to (a,b). In that case it is\n            // possible to express c as c(t) = a + t * (b-a) (analog for the\n            // point d). Since the evaluation of all three coordinate equations\n            // (x,y,z) have to lead to the same solution for the parameter t it\n            // is sufficient to evaluate t only once.\n\n            // Search id of coordinate with largest absolute value which is will\n            // be used in the subsequent computations. This prevents division by\n            // zero in case the line segments are parallel to one of the\n            // coordinate axis.\n            std::size_t i_max(std::abs(v[0]) <= std::abs(v[1]) ? 1 : 0);\n            i_max = std::abs(v[i_max]) <= std::abs(v[2]) ? 2 : i_max;\n            if (isLineSegmentIntersectingAB(qp, i_max)) {\n                s = c;\n                return true;\n            }\n            MathLib::Vector3 const ad(a, d);\n            if (isLineSegmentIntersectingAB(ad, i_max)) {\n                s = d;\n                return true;\n            }\n            return false;\n        }\n        return false;\n    }\n\n    // general case\n    const double sqr_len_v(v.getSqrLength());\n    const double sqr_len_w(w.getSqrLength());\n\n    Eigen::Matrix2d mat;\n    mat(0,0) = sqr_len_v;\n    mat(0,1) = -1.0 * MathLib::scalarProduct(v,w);\n    mat(1,1) = sqr_len_w;\n    mat(1,0) = mat(0,1);\n\n    Eigen::Vector2d rhs;\n    rhs << MathLib::scalarProduct(v, qp), MathLib::scalarProduct(w, pq);\n\n    rhs = mat.partialPivLu().solve(rhs);\n\n    // no theory for the following tolerances, determined by testing\n    // lower tolerance: little bit smaller than zero\n    const double l(-1.0*std::numeric_limits<float>::epsilon());\n    // upper tolerance a little bit greater than one\n    const double u(1.0+std::numeric_limits<float>::epsilon());\n    if (rhs[0] < l || u < rhs[0] || rhs[1] < l || u < rhs[1]) {\n        return false;\n    }\n\n    // compute points along line segments with minimal distance\n    GeoLib::Point const p0(a[0]+rhs[0]*v[0], a[1]+rhs[0]*v[1], a[2]+rhs[0]*v[2]);\n    GeoLib::Point const p1(c[0]+rhs[1]*w[0], c[1]+rhs[1]*w[1], c[2]+rhs[1]*w[2]);\n\n    double const min_dist(sqrt(MathLib::sqrDist(p0, p1)));\n    double const min_seg_len(std::min(sqrt(sqr_len_v), sqrt(sqr_len_w)));\n    if (min_dist < min_seg_len * 1e-6) {\n        s[0] = 0.5 * (p0[0] + p1[0]);\n        s[1] = 0.5 * (p0[1] + p1[1]);\n        s[2] = 0.5 * (p0[2] + p1[2]);\n        return true;\n    }\n\n    return false;\n}\n\nbool lineSegmentsIntersect(const GeoLib::Polyline* ply,\n                           GeoLib::Polyline::SegmentIterator &seg_it0,\n                           GeoLib::Polyline::SegmentIterator &seg_it1,\n                           GeoLib::Point& intersection_pnt)\n{\n    std::size_t const n_segs(ply->getNumberOfSegments());\n    // Neighbouring segments always intersects at a common vertex. The algorithm\n    // checks for intersections of non-neighbouring segments.\n    for (seg_it0 = ply->begin(); seg_it0 != ply->end() - 2; ++seg_it0)\n    {\n        seg_it1 = seg_it0+2;\n        std::size_t const seg_num_0 = seg_it0.getSegmentNumber();\n        for ( ; seg_it1 != ply->end(); ++seg_it1) {\n            // Do not check first and last segment, because they are\n            // neighboured.\n            if (!(seg_num_0 == 0 && seg_it1.getSegmentNumber() == n_segs - 1)) {\n                if (lineSegmentIntersect(*seg_it0, *seg_it1, intersection_pnt)) {\n                    return true;\n                }\n            }\n        }\n    }\n    return false;\n}\n\nvoid rotatePoints(MathLib::DenseMatrix<double> const& rot_mat, std::vector<GeoLib::Point*> &pnts)\n{\n    rotatePoints(rot_mat, pnts.begin(), pnts.end());\n}\n\nMathLib::DenseMatrix<double> rotatePointsToXY(std::vector<GeoLib::Point*>& pnts)\n{\n    return rotatePointsToXY(pnts.begin(), pnts.end(), pnts.begin(), pnts.end());\n}\n\nstd::unique_ptr<GeoLib::Point> triangleLineIntersection(\n    MathLib::Point3d const& a, MathLib::Point3d const& b,\n    MathLib::Point3d const& c, MathLib::Point3d const& p,\n    MathLib::Point3d const& q)\n{\n    const MathLib::Vector3 pq(p, q);\n    const MathLib::Vector3 pa(p, a);\n    const MathLib::Vector3 pb(p, b);\n    const MathLib::Vector3 pc(p, c);\n\n    double u (MathLib::scalarTriple(pq, pc, pb));\n    if (u < 0)\n    {\n        return nullptr;\n    }\n    double v (MathLib::scalarTriple(pq, pa, pc));\n    if (v < 0)\n    {\n        return nullptr;\n    }\n    double w (MathLib::scalarTriple(pq, pb, pa));\n    if (w < 0)\n    {\n        return nullptr;\n    }\n\n    const double denom (1.0/(u+v+w));\n    u*=denom;\n    v*=denom;\n    w*=denom;\n    return std::make_unique<GeoLib::Point>(u * a[0] + v * b[0] + w * c[0],\n                                           u * a[1] + v * b[1] + w * c[1],\n                                           u * a[2] + v * b[2] + w * c[2]);\n}\n\nvoid computeAndInsertAllIntersectionPoints(GeoLib::PointVec &pnt_vec,\n    std::vector<GeoLib::Polyline*> & plys)\n{\n    auto computeSegmentIntersections = [&pnt_vec](GeoLib::Polyline& poly0,\n                                                  GeoLib::Polyline& poly1)\n    {\n        for (auto seg0_it(poly0.begin()); seg0_it != poly0.end(); ++seg0_it)\n        {\n            for (auto seg1_it(poly1.begin()); seg1_it != poly1.end(); ++seg1_it)\n            {\n                GeoLib::Point s(0.0, 0.0, 0.0, pnt_vec.size());\n                if (lineSegmentIntersect(*seg0_it, *seg1_it, s))\n                {\n                    std::size_t const id(\n                        pnt_vec.push_back(new GeoLib::Point(s)));\n                    poly0.insertPoint(seg0_it.getSegmentNumber() + 1, id);\n                    poly1.insertPoint(seg1_it.getSegmentNumber() + 1, id);\n                }\n            }\n        }\n    };\n\n    for (auto it0(plys.begin()); it0 != plys.end(); ++it0) {\n        auto it1(it0);\n        ++it1;\n        for (; it1 != plys.end(); ++it1) {\n            computeSegmentIntersections(*(*it0), *(*it1));\n        }\n    }\n}\n\nGeoLib::Polygon rotatePolygonToXY(GeoLib::Polygon const& polygon_in,\n    MathLib::Vector3 & plane_normal)\n{\n    // 1 copy all points\n    auto* polygon_pnts(new std::vector<GeoLib::Point*>);\n    for (std::size_t k(0); k < polygon_in.getNumberOfPoints(); k++)\n    {\n        polygon_pnts->push_back(new GeoLib::Point(*(polygon_in.getPoint(k))));\n    }\n\n    // 2 rotate points\n    double d_polygon (0.0);\n    GeoLib::getNewellPlane (*polygon_pnts, plane_normal, d_polygon);\n    MathLib::DenseMatrix<double> rot_mat(3,3);\n    GeoLib::computeRotationMatrixToXY(plane_normal, rot_mat);\n    GeoLib::rotatePoints(rot_mat, *polygon_pnts);\n\n    // 3 set z coord to zero\n    std::for_each(polygon_pnts->begin(), polygon_pnts->end(),\n        [] (GeoLib::Point* p) { (*p)[2] = 0.0; }\n    );\n\n    // 4 create new polygon\n    GeoLib::Polyline rot_polyline(*polygon_pnts);\n    for (std::size_t k(0); k < polygon_in.getNumberOfPoints(); k++)\n    {\n        rot_polyline.addPoint(k);\n    }\n    rot_polyline.addPoint(0);\n    return GeoLib::Polygon(rot_polyline);\n}\n\nstd::vector<MathLib::Point3d> lineSegmentIntersect2d(\n    GeoLib::LineSegment const& ab, GeoLib::LineSegment const& cd)\n{\n    GeoLib::Point const& a{ab.getBeginPoint()};\n    GeoLib::Point const& b{ab.getEndPoint()};\n    GeoLib::Point const& c{cd.getBeginPoint()};\n    GeoLib::Point const& d{cd.getEndPoint()};\n\n    double const orient_abc(getOrientation(a, b, c));\n    double const orient_abd(getOrientation(a, b, d));\n\n    // check if the segment (cd) lies on the left or on the right of (ab)\n    if ((orient_abc > 0 && orient_abd > 0) || (orient_abc < 0 && orient_abd < 0)) {\n        return std::vector<MathLib::Point3d>();\n    }\n\n    // check: (cd) and (ab) are on the same line\n    if (orient_abc == 0.0 && orient_abd == 0.0) {\n        double const eps(std::numeric_limits<double>::epsilon());\n        if (MathLib::sqrDist2d(a, c) < eps && MathLib::sqrDist2d(b, d) < eps)\n        {\n            return {{a, b}};\n        }\n        if (MathLib::sqrDist2d(a, d) < eps && MathLib::sqrDist2d(b, c) < eps)\n        {\n            return {{a, b}};\n        }\n\n        // Since orient_ab and orient_abd vanish, a, b, c, d are on the same\n        // line and for this reason it is enough to check the x-component.\n        auto isPointOnSegment = [](double q, double p0, double p1)\n        {\n            double const t((q - p0) / (p1 - p0));\n            return 0 <= t && t <= 1;\n        };\n\n        // check if c in (ab)\n        if (isPointOnSegment(c[0], a[0], b[0])) {\n            // check if a in (cd)\n            if (isPointOnSegment(a[0], c[0], d[0])) {\n                return {{a, c}};\n            }\n            // check b == c\n            if (MathLib::sqrDist2d(b,c) < eps) {\n                return {{b}};\n            }\n            // check if b in (cd)\n            if (isPointOnSegment(b[0], c[0], d[0])) {\n                return {{b, c}};\n            }\n            // check d in (ab)\n            if (isPointOnSegment(d[0], a[0], b[0])) {\n                return {{c, d}};\n            }\n            std::stringstream err;\n            err.precision(std::numeric_limits<double>::digits10);\n            err << ab << \" x \" << cd;\n            OGS_FATAL(\n                \"The case of parallel line segments ({:s}) is not handled yet. \"\n                \"Aborting.\",\n                err.str());\n        }\n\n        // check if d in (ab)\n        if (isPointOnSegment(d[0], a[0], b[0])) {\n            // check if a in (cd)\n            if (isPointOnSegment(a[0], c[0], d[0])) {\n                return {{a, d}};\n            }\n            // check if b==d\n            if (MathLib::sqrDist2d(b, d) < eps) {\n                return {{b}};\n            }\n            // check if b in (cd)\n            if (isPointOnSegment(b[0], c[0], d[0])) {\n                return {{b, d}};\n            }\n            // d in (ab), b not in (cd): check c in (ab)\n            if (isPointOnSegment(c[0], a[0], b[0])) {\n                return {{c, d}};\n            }\n\n            std::stringstream err;\n            err.precision(std::numeric_limits<double>::digits10);\n            err << ab << \" x \" << cd;\n            OGS_FATAL(\n                \"The case of parallel line segments ({:s}) \"\n                \"is not handled yet. Aborting.\",\n                err.str());\n        }\n        return std::vector<MathLib::Point3d>();\n    }\n\n    // precondition: points a, b, c are collinear\n    // the function checks if the point c is onto the line segment (a,b)\n    auto isCollinearPointOntoLineSegment = [](MathLib::Point3d const& a,\n                                              MathLib::Point3d const& b,\n                                              MathLib::Point3d const& c) {\n        if (b[0] - a[0] != 0)\n        {\n            double const t = (c[0] - a[0]) / (b[0] - a[0]);\n            return 0.0 <= t && t <= 1.0;\n        }\n        if (b[1] - a[1] != 0)\n        {\n            double const t = (c[1] - a[1]) / (b[1] - a[1]);\n            return 0.0 <= t && t <= 1.0;\n        }\n        if (b[2] - a[2] != 0)\n        {\n            double const t = (c[2] - a[2]) / (b[2] - a[2]);\n            return 0.0 <= t && t <= 1.0;\n        }\n        return false;\n    };\n\n    if (orient_abc == 0.0) {\n        if (isCollinearPointOntoLineSegment(a, b, c))\n        {\n            return {{c}};\n        }\n        return std::vector<MathLib::Point3d>();\n    }\n\n    if (orient_abd == 0.0) {\n        if (isCollinearPointOntoLineSegment(a, b, d))\n        {\n            return {{d}};\n        }\n        return std::vector<MathLib::Point3d>();\n    }\n\n    // check if the segment (ab) lies on the left or on the right of (cd)\n    double const orient_cda(getOrientation(c, d, a));\n    double const orient_cdb(getOrientation(c, d, b));\n    if ((orient_cda > 0 && orient_cdb > 0) || (orient_cda < 0 && orient_cdb < 0)) {\n        return std::vector<MathLib::Point3d>();\n    }\n\n    // at this point it is sure that there is an intersection and the system of\n    // linear equations will be invertible\n    // solve the two linear equations (b-a, c-d) (t, s)^T = (c-a) simultaneously\n    Eigen::Matrix2d mat;\n    mat(0,0) = b[0]-a[0];\n    mat(0,1) = c[0]-d[0];\n    mat(1,0) = b[1]-a[1];\n    mat(1,1) = c[1]-d[1];\n    Eigen::Vector2d rhs{c[0] - a[0], c[1] - a[1]};\n\n    rhs = mat.partialPivLu().solve(rhs);\n    if (0 <= rhs[1] && rhs[1] <= 1.0) {\n        return { MathLib::Point3d{std::array<double,3>{{\n                c[0]+rhs[1]*(d[0]-c[0]), c[1]+rhs[1]*(d[1]-c[1]),\n                c[2]+rhs[1]*(d[2]-c[2])}} } };\n    }\n    return std::vector<MathLib::Point3d>();  // parameter s not in the valid\n                                             // range\n}\n\nvoid sortSegments(\n    MathLib::Point3d const& seg_beg_pnt,\n    std::vector<GeoLib::LineSegment>& sub_segments)\n{\n    double const eps(std::numeric_limits<double>::epsilon());\n\n    auto findNextSegment = [&eps](\n                               MathLib::Point3d const& seg_beg_pnt,\n                               std::vector<GeoLib::LineSegment>& sub_segments,\n                               std::vector<GeoLib::LineSegment>::iterator&\n                                   sub_seg_it) {\n        if (sub_seg_it == sub_segments.end())\n        {\n            return;\n        }\n        // find appropriate segment for the given segment begin point\n        auto act_beg_seg_it = std::find_if(\n            sub_seg_it, sub_segments.end(),\n            [&seg_beg_pnt, &eps](GeoLib::LineSegment const& seg)\n            {\n                return MathLib::sqrDist(seg_beg_pnt, seg.getBeginPoint()) < eps ||\n                       MathLib::sqrDist(seg_beg_pnt, seg.getEndPoint()) < eps;\n            });\n        if (act_beg_seg_it == sub_segments.end())\n        {\n            return;\n        }\n        // if necessary correct orientation of segment, i.e. swap beg and end\n        if (MathLib::sqrDist(seg_beg_pnt, act_beg_seg_it->getEndPoint()) <\n            MathLib::sqrDist(seg_beg_pnt, act_beg_seg_it->getBeginPoint()))\n        {\n            std::swap(act_beg_seg_it->getBeginPoint(),\n                      act_beg_seg_it->getEndPoint());\n        }\n        assert(sub_seg_it != sub_segments.end());\n        // exchange segments within the container\n        if (sub_seg_it != act_beg_seg_it)\n        {\n            std::swap(*sub_seg_it, *act_beg_seg_it);\n        }\n    };\n\n    // find start segment\n    auto seg_it = sub_segments.begin();\n    findNextSegment(seg_beg_pnt, sub_segments, seg_it);\n\n    while (seg_it != sub_segments.end())\n    {\n        MathLib::Point3d & new_seg_beg_pnt(seg_it->getEndPoint());\n        seg_it++;\n        if (seg_it != sub_segments.end())\n        {\n            findNextSegment(new_seg_beg_pnt, sub_segments, seg_it);\n        }\n    }\n}\n\n} // end namespace GeoLib\n", "meta": {"hexsha": "0f01711e2e15a477909d14e6f639f140c6241f4c", "size": 19510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GeoLib/AnalyticalGeometry.cpp", "max_stars_repo_name": "fwitte/ogs", "max_stars_repo_head_hexsha": "0b367872fc58ecd4e1dbfe1dcebbc847da6639d7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-09-02T11:49:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-02T11:49:52.000Z", "max_issues_repo_path": "GeoLib/AnalyticalGeometry.cpp", "max_issues_repo_name": "fwitte/ogs", "max_issues_repo_head_hexsha": "0b367872fc58ecd4e1dbfe1dcebbc847da6639d7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T13:08:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-25T12:56:17.000Z", "max_forks_repo_path": "GeoLib/AnalyticalGeometry.cpp", "max_forks_repo_name": "fwitte/ogs", "max_forks_repo_head_hexsha": "0b367872fc58ecd4e1dbfe1dcebbc847da6639d7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T13:37:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-01T10:19:03.000Z", "avg_line_length": 32.462562396, "max_line_length": 97, "alphanum_fraction": 0.5296258329, "num_tokens": 5470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4396061168065352}}
{"text": "#include <state_estimation/filters/ukf_vs.h>\n#include <state_estimation/utilities/data_subset_utilities.h>\n#include <state_estimation/utilities/logging.h>\n#include <Eigen/Dense>\n\nnamespace state_estimation {\n\nUKFVS::UKFVS(system_models::NonlinearSystemModel* system_model)\n    : FilterBase::FilterBase(system_model) {\n    initializeSigmaPointParameters();\n}\n\nUKFVS::UKFVS(system_models::NonlinearSystemModel* system_model, const Eigen::VectorXd& x,\n             const Eigen::MatrixXd& cov, double timestamp)\n    : FilterBase::FilterBase(system_model, x, cov, timestamp) {\n    initializeSigmaPointParameters();\n}\n\nvoid UKFVS::setSigmaPointParameters(double alpha, double kappa, double beta) {\n    uint32_t n = system_model_->activeStateSize();\n    num_sigma_pts_ = 2 * n + 1;\n\n    // Compute our lambda value\n    lambda_ = pow(alpha, 2) * (n + kappa) - n;\n\n    // Compute our weight vectors\n    w_mean_.resize(num_sigma_pts_);\n    w_cov_.resize(num_sigma_pts_);\n\n    const double init_w = 0.5 / (n + lambda_);\n    w_mean_ = Eigen::VectorXd::Constant(num_sigma_pts_, init_w);\n    w_cov_ = Eigen::VectorXd::Constant(num_sigma_pts_, init_w);\n\n    w_mean_(0) = lambda_ / (n + lambda_);\n    w_cov_(0) = w_mean_(0) + 1 - pow(alpha, 2) + beta;\n\n#ifdef DEBUG_STATE_ESTIMATION\n    std::cout << \"UKF sigma point initialization\" << std::endl\n              << \"alpha=\" << alpha << std::endl\n              << \"kappa=\" << kappa << std::endl\n              << \"lambda=\" << lambda_ << std::endl\n              << \"Initialized mean weights to [\" << w_mean_.transpose() << \"]\" << std::endl\n              << \"Initialized covariance weights to [\" << w_cov_.transpose() << \"]\" << std::endl;\n#endif\n}\n\nvoid UKFVS::initializeSigmaPointParameters() {\n    setSigmaPointParameters(0.001, 0, 2);\n}\n\nvoid UKFVS::myPredict(const Eigen::VectorXd& u, double dt) {\n    // We will only be updating a subset of the state. All the computationally expensive linear\n    // algebra operations will happen on the subset of the state for efficiency. Since the models\n    // still operate on the full state vector the sigma points vectors will be of the full\n    // dimensionality, but the number of sigma points will still be determined by the number of\n    // active states. This only adds a slight additional memory cost.\n\n    // Generate the sigma offsets only using the subset of the covariance matrix we are inerested\n    // for efficiency\n    const Eigen::MatrixXd cov_subset = getSubset(\n        filter_state_.covariance, system_model_->activeStates(), system_model_->activeStates());\n    const Eigen::MatrixXd sigma_offset_subset =\n        ((system_model_->activeStateSize() + lambda_) * cov_subset).llt().matrixL();\n\n    Eigen::MatrixXd sigma_pts(system_model_->stateSize(), num_sigma_pts_);\n\n    // Run all the sigma points through the model\n    system_model_->update(filter_state_.x, u, dt);\n    sigma_pts.col(0) = system_model_->g();\n\n    Eigen::VectorXd offset = Eigen::VectorXd::Zero(system_model_->stateSize());\n    for (uint32_t i = 0; i < system_model_->activeStateSize(); ++i) {\n        const uint32_t i_high = i + 1;\n        const uint32_t i_low = i + 1 + system_model_->activeStateSize();\n        convertSubsetToFull(sigma_offset_subset.col(i), &offset, system_model_->activeStates());\n\n        const Eigen::VectorXd x_high = system_model_->addVectors(filter_state_.x, offset);\n        system_model_->update(x_high, u, dt);\n        sigma_pts.col(i_high) = system_model_->g();\n\n        const Eigen::VectorXd x_low = system_model_->subtractVectors(filter_state_.x, offset);\n        system_model_->update(x_low, u, dt);\n        sigma_pts.col(i_low) = system_model_->g();\n    }\n\n    // Compute the weighted mean\n    filter_state_.x = system_model_->weightedSum(w_mean_, sigma_pts);\n\n    // Initialze the covariance with the process and control noise\n    const Eigen::MatrixXd Rc_subset =\n        getSubset(system_model_->Rc(), system_model_->activeControls());\n    const Eigen::MatrixXd P_subset =\n        getSubset(system_model_->P(), system_model_->activeStates(), {});\n    const Eigen::MatrixXd V_subset = getSubset(system_model_->V(), system_model_->activeStates(),\n                                               system_model_->activeControls());\n\n    Eigen::MatrixXd cov_prime_subset = P_subset * system_model_->Rp() * P_subset.transpose() +\n                                       V_subset * Rc_subset * V_subset.transpose();\n\n    // Add the weighted sample covariance\n    for (uint32_t i = 0; i < num_sigma_pts_; ++i) {\n        const Eigen::VectorXd dx_full =\n            system_model_->subtractVectors(sigma_pts.col(i), filter_state_.x);\n        const Eigen::VectorXd dx_subset = getSubset(dx_full, system_model_->activeStates());\n\n        cov_prime_subset += w_cov_(i) * dx_subset * dx_subset.transpose();\n    }\n\n    // Update the full covariance matrix with the subset we calculated\n    convertSubsetToFull(cov_prime_subset, &filter_state_.covariance, system_model_->activeStates());\n\n#ifdef DEBUG_STATE_ESTIMATION\n    Eigen::MatrixXd sigma_offset =\n        Eigen::MatrixXd::Zero(system_model_->stateSize(), system_model_->stateSize());\n    convertSubsetToFull(sigma_offset_subset, &sigma_offset, system_model_->activeStates());\n\n    std::cout << \"UKF predicition update:\" << std::endl\n              << \"Sigma offsets=\" << std::endl\n              << printMatrix(sigma_offset) << std::endl\n              << \"Sigma points=\" << std::endl\n              << printMatrix(sigma_pts) << std::endl\n              << \"P=\" << std::endl\n              << printMatrix(system_model_->P()) << std::endl\n              << \"V=\" << std::endl\n              << printMatrix(system_model_->V()) << std::endl\n              << \"x=\" << printMatrix(filter_state_.x) << std::endl\n              << \"Covariance=\" << std::endl\n              << printMatrix(filter_state_.covariance) << std::endl;\n#endif\n}\n\nvoid UKFVS::myCorrect(const Eigen::VectorXd& z,\n                      measurement_models::NonlinearMeasurementModel* model, double dt) {\n    // We will only be updating a subset of the state. All the computationally expensive linear\n    // algebra operations will happen on the subset of the state for efficiency. Since the models\n    // still operate on the full state vector the sigma points vectors will be of the full\n    // dimensionality, but the number of sigma points will still be determined by the number of\n    // active states. This only adds a slight additional memory cost.\n\n    // Generate the sigma offsets only using the subset of the covariance matrix we are inerested\n    // for efficiency\n    const Eigen::MatrixXd cov_subset =\n        getSubset(filter_state_.covariance, system_model_->activeStates());\n    const Eigen::MatrixXd sigma_offset_subset =\n        ((system_model_->activeStateSize() + lambda_) * cov_subset).llt().matrixL();\n\n    Eigen::MatrixXd state_sigma_pts(system_model_->stateSize(), num_sigma_pts_);\n    Eigen::MatrixXd meas_sigma_pts(model->measurementSize(), num_sigma_pts_);\n\n    // Run all the sigma points through the model\n    state_sigma_pts.col(0) = filter_state_.x;\n    model->update(filter_state_.x, dt);\n    meas_sigma_pts.col(0) = model->h();\n\n    Eigen::VectorXd offset = Eigen::VectorXd::Zero(system_model_->stateSize());\n    for (uint32_t i = 0; i < system_model_->activeStateSize(); ++i) {\n        const uint32_t i_high = i + 1;\n        const uint32_t i_low = i + 1 + system_model_->activeStateSize();\n        convertSubsetToFull(sigma_offset_subset.col(i), &offset, system_model_->activeStates());\n\n        state_sigma_pts.col(i_high) = system_model_->addVectors(filter_state_.x, offset);\n        model->update(state_sigma_pts.col(i_high), dt);\n        meas_sigma_pts.col(i_high) = model->h();\n\n        state_sigma_pts.col(i_low) = system_model_->subtractVectors(filter_state_.x, offset);\n        model->update(state_sigma_pts.col(i_low), dt);\n        meas_sigma_pts.col(i_low) = model->h();\n    }\n\n    // Compute the weighted mean for the predicted measurement\n    Eigen::VectorXd z_pred = model->weightedSum(w_mean_, meas_sigma_pts);\n\n    // Compute the gain (only using the subset of the states)\n    Eigen::MatrixXd S = getSubset(model->covariance(), model->activeMeasurements());\n    for (uint32_t i = 0; i < num_sigma_pts_; ++i) {\n        const Eigen::VectorXd dz_full = model->subtractVectors(meas_sigma_pts.col(i), z_pred);\n        const Eigen::VectorXd dz_subset = getSubset(dz_full, model->activeMeasurements());\n        S += w_cov_(i) * dz_subset * dz_subset.transpose();\n    }\n\n    Eigen::MatrixXd cross_covariance =\n        Eigen::MatrixXd::Zero(system_model_->activeStateSize(), model->activeMeasurementSize());\n    for (uint32_t i = 0; i < num_sigma_pts_; ++i) {\n        const Eigen::VectorXd dx_full =\n            system_model_->subtractVectors(state_sigma_pts.col(i), state_sigma_pts.col(0));\n        const Eigen::VectorXd dx_subset = getSubset(dx_full, system_model_->activeStates());\n\n        const Eigen::VectorXd dz_full = model->subtractVectors(meas_sigma_pts.col(i), z_pred);\n        const Eigen::VectorXd dz_subset = getSubset(dz_full, model->activeMeasurements());\n\n        cross_covariance += w_cov_(i) * dx_subset * dz_subset.transpose();\n    }\n\n    const Eigen::MatrixXd K = cross_covariance * S.inverse();\n\n    // Perform the mean update\n    const Eigen::VectorXd dz_full = model->subtractVectors(z, z_pred);\n    const Eigen::VectorXd dz_subset = getSubset(dz_full, model->activeMeasurements());\n    const Eigen::VectorXd dx_subset = K * dz_subset;\n    const Eigen::VectorXd dx_full = convertSubsetToFullZeroed(\n        dx_subset, system_model_->activeStates(), system_model_->stateSize());\n    filter_state_.x = system_model_->addVectors(filter_state_.x, dx_full);\n\n    // Perform the covariance update\n    const Eigen::MatrixXd cov_prime_subset = cov_subset - K * S * K.transpose();\n    convertSubsetToFull(cov_prime_subset, &filter_state_.covariance, system_model_->activeStates());\n\n#ifdef DEBUG_STATE_ESTIMATION\n    const Eigen::MatrixXd sigma_offset = convertSubsetToFullZeroed(\n        sigma_offset_subset, system_model_->activeStates(), system_model_->stateSize());\n\n    const Eigen::MatrixXd S_full =\n        convertSubsetToFullZeroed(S, model->activeMeasurements(), model->measurementSize());\n\n    const Eigen::MatrixXd cross_full = convertSubsetToFullZeroed(\n        cross_covariance, system_model_->activeStates(), model->activeMeasurements(),\n        system_model_->stateSize(), model->measurementSize());\n\n    const Eigen::MatrixXd K_full =\n        convertSubsetToFullZeroed(K, system_model_->activeStates(), model->activeMeasurements(),\n                                  system_model_->stateSize(), model->measurementSize());\n\n    std::cout << \"UKF measurement update:\" << std::endl\n              << \"Sigma offsets=\" << std::endl\n              << printMatrix(sigma_offset) << std::endl\n              << \"State sigma points=\" << std::endl\n              << printMatrix(state_sigma_pts) << std::endl\n              << \"Measurement sigma points=\" << std::endl\n              << printMatrix(meas_sigma_pts) << std::endl\n              << \"z_pred=\" << printMatrix(z_pred) << std::endl\n              << \"Q=\" << std::endl\n              << printMatrix(model->covariance()) << std::endl\n              << \"S=\" << std::endl\n              << printMatrix(S_full) << std::endl\n              << \"Cross Covariance=\" << std::endl\n              << printMatrix(cross_full) << std::endl\n              << \"K=\" << std::endl\n              << printMatrix(K_full) << std::endl\n              << \"x=\" << printMatrix(filter_state_.x) << std::endl\n              << \"Covariance=\" << std::endl\n              << printMatrix(filter_state_.covariance) << std::endl;\n#endif\n}\n\n}  // namespace state_estimation\n", "meta": {"hexsha": "b3154566e2742aae83dc9018041dbd8b4da48a06", "size": 11724, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/filters/ukf_vs.cpp", "max_stars_repo_name": "MarbleInc/state_estimation", "max_stars_repo_head_hexsha": "05b3f0bbceda695b4420594ac9ff3cd22001a577", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-05T06:19:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T06:19:45.000Z", "max_issues_repo_path": "src/filters/ukf_vs.cpp", "max_issues_repo_name": "stevendaniluk/state_estimation", "max_issues_repo_head_hexsha": "05b3f0bbceda695b4420594ac9ff3cd22001a577", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/filters/ukf_vs.cpp", "max_forks_repo_name": "stevendaniluk/state_estimation", "max_forks_repo_head_hexsha": "05b3f0bbceda695b4420594ac9ff3cd22001a577", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6585365854, "max_line_length": 100, "alphanum_fraction": 0.6659843057, "num_tokens": 2728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115012, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.43960611068282884}}
{"text": "#include <ros/ros.h>\n#include <std_msgs/String.h>\n#include <model_based_shared_control/State.h>\n#include <model_based_shared_control/Control.h>\n#include \"robotlib/dynamicalSystems/koopman/koopman_operator.hpp\"\n#include \"robotlib/dynamicalSystems/koopman/basis_functions/linear_basis.hpp\"\n#include \"robotlib/dynamicalSystems/koopman/basis_functions/nonlinear_basis.hpp\"\n#include <armadillo>\n\nclass HumanRobot {\n\npublic:\n\n  // publishers and subscribers\n  ros::Subscriber state_sub;\n  ros::Subscriber shutdown_sub;\n  bool has_initialized = false;\n\n  // messages\n  model_based_shared_control::State state;\n  model_based_shared_control::Control control;\n\n  // data vectors\n  arma::vec current_state;\n  arma::vec dataIn;\n  arma::vec dataOut;\n  arma::vec cdataIn;\n  arma::vec hdataIn;\n  arma::vec hdataOut;\n\n  // Koopman models\n  KoopmanOperator* linear_koopman_operator;\n  KoopmanOperator* nonlinear_koopman_operator;\n\n  HumanRobot(ros::Rate* loop_rate) {\n\n    ros::NodeHandle nh;\n\n    // set up subscribers\n    state_sub = nh.subscribe(\"/state\", 1, &HumanRobot::get_state, this);\n    shutdown_sub = nh.subscribe(\"/shutdown\", 1, &HumanRobot::get_shutdown, this);\n\n    // set up data vectors\n    dataIn = arma::zeros<arma::vec>(6);\n    dataOut = arma::zeros<arma::vec>(6);\n    cdataIn = arma::zeros<arma::vec>(2);\n    hdataIn = arma::zeros<arma::vec>(2);\n    hdataOut = arma::zeros<arma::vec>(2);\n    current_state = arma::zeros<arma::vec>(6);\n\n    // set up Linear Koopman\n    linear_koopman_operator = new KoopmanOperator(new LinearBasisFunction());\n\n    // set up Non Linear Koopman\n    nonlinear_koopman_operator = new KoopmanOperator(new NonLinearBasisFunction());\n\n  }\n\n  void get_state(const model_based_shared_control::State::ConstPtr& msg) {\n    if (has_initialized == false) {\n      dataOut[0] = msg->x;\n      dataOut[1] = msg->y;\n      dataOut[2] = msg->theta;\n      dataOut[3] = msg->x_dot;\n      dataOut[4] = msg->y_dot;\n      dataOut[5] = msg->theta_dot;\n      hdataOut[0] = msg->u_1;\n      hdataOut[1] = msg->u_2;\n      has_initialized = true;\n    } else {\n       if (std::abs(dataOut[0] - msg->x) + std::abs(dataOut[1] - msg->y) < 0.3){\n        dataIn = dataOut;\n        hdataIn = hdataOut;\n        dataOut[0] = msg->x;\n        dataOut[1] = msg->y;\n        dataOut[2] = msg->theta;\n        dataOut[3] = msg->x_dot;\n        dataOut[4] = msg->y_dot;\n        dataOut[5] = msg->theta_dot;\n        hdataOut[0] = msg->u_1;\n        hdataOut[1] = msg->u_2;\n        linear_koopman_operator->gradStep(dataIn, hdataIn, dataOut, hdataOut);\n        nonlinear_koopman_operator->gradStep(dataIn, hdataIn, dataOut, hdataOut);\n        current_state = dataOut;\n      } else {\n        has_initialized = false;\n      }\n\t\t}\n\t}\n\n  void get_shutdown(const std_msgs::String::ConstPtr& msg) {\n    std::string filePath = msg->data;\n    std::string linearFilePath = filePath + \"-koopman-linear\";\n    std::string nonlinearFilePath = filePath + \"-koopman-nonlinear\";\n    linear_koopman_operator->saveOperator(linearFilePath);\n    nonlinear_koopman_operator->saveOperator(nonlinearFilePath);\n  }\n\n};\n\nint main(int argc, char** argv) {\n  ros::init(argc, argv,\"human_robot\");\n  ros::NodeHandle nh;\n  ros::Rate loop_rate(10);\n  HumanRobot sys(&loop_rate);\n\n  while (ros::ok()) {\n    loop_rate.sleep();\n    ros::spinOnce();\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "33d40dbab8a11f67228ff54c88aecee2fdd08d58", "size": 3319, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/model_based_shared_control/src/collect_data.cpp", "max_stars_repo_name": "argallab/model_based_shared_control", "max_stars_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T19:47:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:43:31.000Z", "max_issues_repo_path": "src/model_based_shared_control/src/collect_data.cpp", "max_issues_repo_name": "argallab/model_based_shared_control", "max_issues_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/model_based_shared_control/src/collect_data.cpp", "max_forks_repo_name": "argallab/model_based_shared_control", "max_forks_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-08T19:47:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T10:10:17.000Z", "avg_line_length": 29.1140350877, "max_line_length": 83, "alphanum_fraction": 0.6679722808, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4394875188962753}}
{"text": "/**\n * @file calc-characteristic.cpp\n *\n * @brief calculate characteristic polynomial.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (The University of Tokyo)\n *\n * Copyright (C) 2012 Mutsuo Saito, Makoto Matsumoto,\n * Hiroshima University and The University of Tokyo.\n * All rights reserved.\n *\n * The 3-clause BSD License is applied to this software, see\n * LICENSE.txt\n */\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <string>\n#include <inttypes.h>\n#include <stdint.h>\n#include \"SFMText.hpp\"\n#include \"SFMT-calc-jump.hpp\"\n#include <NTL/GF2X.h>\n#include <NTL/vec_GF2.h>\n#include <NTL/GF2XFactoring.h>\n\nnamespace sfmt {\n    using namespace NTL;\n    using namespace std;\n    static void calc_minimal(GF2X& minimal, SFMText& sfmt, int bitpos)\n    {\n\tuint32_t mask[4];\n\tfor (int i = 0; i < 4; i++) {\n\t    mask[i] = 0;\n\t}\n\tint pos = bitpos / 32;\n\tuint32_t m = 1 << (bitpos % 32);\n\tmask[pos] = m;\n\tint maxdegree = sfmt.get_maxdegree();\n\tvec_GF2 seq;\n\tseq.SetLength(2 * maxdegree);\n\tfor (int i = 0; i < 2 * maxdegree; i++) {\n\t    seq[i] = sfmt.next(mask);\n\t}\n\tMinPolySeq(minimal, seq, maxdegree);\n#ifdef DEBUG\n\tif (deg(minimal) == 0) {\n\t    cout << \"deg minimal:\" << dec << deg(minimal) << endl;\n\t    cout << \"minimal:\" << minimal << endl;\n\t    cout << \"seq:\" << seq << endl;\n\t}\n#endif\n    }\n\n    static void LCM(GF2X& lcm, const GF2X& x, const GF2X& y) {\n\tGF2X gcd;\n\tmul(lcm, x, y);\n\tGCD(gcd, x, y);\n\tlcm /= gcd;\n    }\n\n    void get_characteristic(GF2X& lcmpoly, SFMText& sfmt) {\n\tGF2X minimal;\n\tGF2X tmp;\n\tint maxdegree = sfmt.get_maxdegree();\n\tsfmt.seeding(1234);\n\tfor (int bitpos = 0; bitpos < 128; bitpos++) {\n\t    calc_minimal(minimal, sfmt, bitpos);\n\t    LCM(tmp, lcmpoly, minimal);\n\t    lcmpoly = tmp;\n\t    if (deg(lcmpoly) == maxdegree) {\n\t\treturn;\n\t    }\n\t}\n\tfor (int i = 0; i < maxdegree; i++) {\n\t    sfmt.init_basis();\n\t    for (int bitpos = 0; bitpos < 128; bitpos++) {\n\t\tcalc_minimal(minimal, sfmt, bitpos);\n\t\tLCM(tmp, lcmpoly, minimal);\n\t\tlcmpoly = tmp;\n\t\tif (deg(lcmpoly) == maxdegree) {\n\t\t    return;\n\t\t}\n\t    }\n\t}\n\tcerr << \"deg:\" << deg(lcmpoly) << endl;\n\tthrow new logic_error(\"can't find lcm\");\n    }\n\n    static void check(SFMText& sfmt) {\n\tsfmt.seeding(1234);\n\n\tfor (int i = 0; i < 10; i++) {\n\t    w128_t x = sfmt.next();\n\t    for (int j = 0; j < 4; j++) {\n\t\tcout << dec << x.u[j] << endl;\n\t    }\n\t}\n    }\n\n    static int has_large_irreducible(GF2X& fpoly, int degree) {\n\tstatic const GF2X t2(2, 1);\n\tstatic const GF2X t1(1, 1);\n\tGF2X t2m;\n\tGF2X t;\n\tGF2X alpha;\n\tint m;\n\n\tt2m = t2;\n\tif (deg(fpoly) < degree) {\n\t    return 0;\n\t}\n\tt = t1;\n\tt += t2m;\n\n\tfor (m = 1; deg(fpoly) > degree; m++) {\n\t    for(;;) {\n\t\tGCD(alpha, fpoly, t);\n\t\tif (IsOne(alpha)) {\n\t\t    break;\n\t\t}\n\t\tfpoly /= alpha;\n\t\tif (deg(fpoly) < degree) {\n\t\t    return 0;\n\t\t}\n\t    }\n\t    t2m *= t2m;\n\t    t2m %= fpoly;\n\t    add(t, t2m, t1);\n\t}\n\tif (deg(fpoly) != degree) {\n\t    return 0;\n\t}\n\treturn IterIrredTest(fpoly);\n    }\n}\n#if defined(MAIN)\nusing namespace sfmt;\nusing namespace NTL;\nusing namespace std;\n\nint main(int argc, char *argv[]) {\n    if (argc < 11) {\n\tcout << argv[0]\n\t     << \" mexp sl1 sl2 sr1 sr2 pos1 mask1 mask2 mask3 mask4\"\n\t     << \" parity1 parity2 parity3 parity4\"\n\t     << endl;\n\treturn -1;\n    }\n    int mexp = strtol(argv[1], NULL, 10);\n    int pos1 = strtol(argv[2], NULL, 10);\n    int sl1 = strtol(argv[3], NULL, 10);\n    int sl2 = strtol(argv[4], NULL, 10);\n    int sr1 = strtol(argv[5], NULL, 10);\n    int sr2 = strtol(argv[6], NULL, 10);\n    uint32_t mask[4];\n    mask[0] = strtoull(argv[7], NULL, 16);\n    mask[1] = strtoull(argv[8], NULL, 16);\n    mask[2] = strtoull(argv[9], NULL, 16);\n    mask[3] = strtoull(argv[10], NULL, 16);\n    uint32_t parity[4];\n    parity[0] = strtoull(argv[11], NULL, 16);\n    parity[1] = strtoull(argv[12], NULL, 16);\n    parity[2] = strtoull(argv[13], NULL, 16);\n    parity[3] = strtoull(argv[14], NULL, 16);\n#if defined(DEBUG)\n    cout << \"mexp:\" << dec << mexp << endl;\n    cout << \"pos1:\" << dec << pos1 << endl;\n    cout << \"sl1:\" << dec << sl1 << endl;\n    cout << \"sl2:\" << dec << sl2 << endl;\n    cout << \"sr1:\" << dec << sr1 << endl;\n    cout << \"sr2:\" << dec << sr2 << endl;\n    cout << \"mask1:\" << hex<< mask[0] << endl;\n    cout << \"mask2:\" << hex << mask[1] << endl;\n    cout << \"mask3:\" << hex << mask[2] << endl;\n    cout << \"mask4:\" << hex << mask[3] << endl;\n    cout << \"parity1:\" << hex<< parity[0] << endl;\n    cout << \"parity2:\" << hex << parity[1] << endl;\n    cout << \"parity3:\" << hex << parity[2] << endl;\n    cout << \"parity4:\" << hex << parity[3] << endl;\n#endif\n    SFMText sfmt(mexp, sl1, sl2, sr1, sr2, pos1,\n\t\t mask, parity);\n    GF2X characteristic(0, 1);\n#if defined(DEBUG)\n    check(sfmt);\n#endif\n    get_characteristic(characteristic, sfmt);\n    GF2X work;\n    work = characteristic;\n#if defined(DEBUG)\n    cout << \"degree:\" << deg(characteristic) << endl;\n    cout << characteristic << endl;\n#endif\n    if (!has_large_irreducible(characteristic, mexp)) {\n\tcout << \"error?\" << endl;\n\treturn -1;\n    }\n    string x;\n    polytostring(x, work);\n#if defined(DEBUG)\n    cout << \"characteristic:\" << x << endl;\n#endif\n    cout << \"#\" << dec << mexp;\n    cout << \",\" << dec << pos1;\n    cout << \",\" << dec << sl1;\n    cout << \",\" << dec << sl2;\n    cout << \",\" << dec << sr1;\n    cout << \",\" << dec << sr2;\n    cout << \",\" << hex << mask[0];\n    cout << \",\" << hex << mask[1];\n    cout << \",\" << hex << mask[2];\n    cout << \",\" << hex << mask[3];\n    cout << \",\" << hex << parity[0];\n    cout << \",\" << hex << parity[1];\n    cout << \",\" << hex << parity[2];\n    cout << \",\" << hex << parity[3];\n    cout << endl;\n    cout << x << endl;\n    cout << dec << flush;\n    return 0;\n}\n#endif\n", "meta": {"hexsha": "e0b19db9a10467a348df1900fe2b0908018a538a", "size": 5708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SFMT/jump/calc-characteristic.cpp", "max_stars_repo_name": "sukhoy/liblinear", "max_stars_repo_head_hexsha": "58659575b3393d0cfc5a022e4266842b400556d6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T06:39:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T00:19:09.000Z", "max_issues_repo_path": "SFMT/jump/calc-characteristic.cpp", "max_issues_repo_name": "sukhoy/liblinear", "max_issues_repo_head_hexsha": "58659575b3393d0cfc5a022e4266842b400556d6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2016-03-11T01:02:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-18T00:15:11.000Z", "max_forks_repo_path": "SFMT/jump/calc-characteristic.cpp", "max_forks_repo_name": "sukhoy/liblinear", "max_forks_repo_head_hexsha": "58659575b3393d0cfc5a022e4266842b400556d6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2016-01-26T02:39:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T12:58:20.000Z", "avg_line_length": 25.3688888889, "max_line_length": 70, "alphanum_fraction": 0.5558864751, "num_tokens": 1938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4394875188962752}}
{"text": "//[ LazyVector\n///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2008 Eric Niebler. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// This example constructs a mini-library for linear algebra, using\n// expression templates to eliminate the need for temporaries when\n// adding vectors of numbers.\n//\n// This example uses a domain with a grammar to prune the set\n// of overloaded operators. Only those operators that produce\n// valid lazy vector expressions are allowed.\n\n#include <vector>\n#include <iostream>\n#include <boost/mpl/int.hpp>\n#include <boost/proto/core.hpp>\n#include <boost/proto/context.hpp>\nnamespace mpl = boost::mpl;\nnamespace proto = boost::proto;\nusing proto::_;\n\n// This grammar describes which lazy vector expressions\n// are allowed; namely, vector terminals and addition\n// and subtraction of lazy vector expressions.\nstruct LazyVectorGrammar\n  : proto::or_<\n        proto::terminal< std::vector<_> >\n      , proto::plus< LazyVectorGrammar, LazyVectorGrammar >\n      , proto::minus< LazyVectorGrammar, LazyVectorGrammar >\n    >\n{};\n\n// Expressions in the lazy vector domain must conform\n// to the lazy vector grammar\nstruct lazy_vector_domain;\n\n// Here is an evaluation context that indexes into a lazy vector\n// expression, and combines the result.\ntemplate<typename Size = std::size_t>\nstruct lazy_subscript_context\n{\n    lazy_subscript_context(Size subscript)\n      : subscript_(subscript)\n    {}\n\n    // Use default_eval for all the operations ...\n    template<typename Expr, typename Tag = typename Expr::proto_tag>\n    struct eval\n      : proto::default_eval<Expr, lazy_subscript_context>\n    {};\n\n    // ... except for terminals, which we index with our subscript\n    template<typename Expr>\n    struct eval<Expr, proto::tag::terminal>\n    {\n        typedef typename proto::result_of::value<Expr>::type::value_type result_type;\n\n        result_type operator ()( Expr const & expr, lazy_subscript_context & ctx ) const\n        {\n            return proto::value( expr )[ ctx.subscript_ ];\n        }\n    };\n\n    Size subscript_;\n};\n\n// Here is the domain-specific expression wrapper, which overrides\n// operator [] to evaluate the expression using the lazy_subscript_context.\ntemplate<typename Expr>\nstruct lazy_vector_expr\n  : proto::extends<Expr, lazy_vector_expr<Expr>, lazy_vector_domain>\n{\n    typedef proto::extends<Expr, lazy_vector_expr<Expr>, lazy_vector_domain> base_type;\n\n    lazy_vector_expr( Expr const & expr = Expr() )\n      : base_type( expr )\n    {}\n\n    // Use the lazy_subscript_context<> to implement subscripting\n    // of a lazy vector expression tree.\n    template< typename Size >\n    typename proto::result_of::eval< Expr, lazy_subscript_context<Size> >::type\n    operator []( Size subscript ) const\n    {\n        lazy_subscript_context<Size> ctx(subscript);\n        return proto::eval(*this, ctx);\n    }\n};\n\n// Here is our lazy_vector terminal, implemented in terms of lazy_vector_expr\ntemplate< typename T >\nstruct lazy_vector\n  : lazy_vector_expr< typename proto::terminal< std::vector<T> >::type >\n{\n    typedef typename proto::terminal< std::vector<T> >::type expr_type;\n\n    lazy_vector( std::size_t size = 0, T const & value = T() )\n      : lazy_vector_expr<expr_type>( expr_type::make( std::vector<T>( size, value ) ) )\n    {}\n\n    // Here we define a += operator for lazy vector terminals that\n    // takes a lazy vector expression and indexes it. expr[i] here\n    // uses lazy_subscript_context<> under the covers.\n    template< typename Expr >\n    lazy_vector &operator += (Expr const & expr)\n    {\n        std::size_t size = proto::value(*this).size();\n        for(std::size_t i = 0; i < size; ++i)\n        {\n            proto::value(*this)[i] += expr[i];\n        }\n        return *this;\n    }\n};\n\n// Tell proto that in the lazy_vector_domain, all\n// expressions should be wrapped in laxy_vector_expr<>\nstruct lazy_vector_domain\n  : proto::domain<proto::generator<lazy_vector_expr>, LazyVectorGrammar>\n{};\n\nint main()\n{\n    // lazy_vectors with 4 elements each.\n    lazy_vector< double > v1( 4, 1.0 ), v2( 4, 2.0 ), v3( 4, 3.0 );\n\n    // Add two vectors lazily and get the 2nd element.\n    double d1 = ( v2 + v3 )[ 2 ];   // Look ma, no temporaries!\n    std::cout << d1 << std::endl;\n\n    // Subtract two vectors and add the result to a third vector.\n    v1 += v2 - v3;                  // Still no temporaries!\n    std::cout << '{' << v1[0] << ',' << v1[1]\n              << ',' << v1[2] << ',' << v1[3] << '}' << std::endl;\n\n    // This expression is disallowed because it does not conform\n    // to the LazyVectorGrammar\n    //(v2 + v3) += v1;\n\n    return 0;\n}\n//]\n", "meta": {"hexsha": "3ac33acc487f78468128d2e653a2d7e82384a049", "size": 4784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/proto/example/lazy_vector.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/proto/example/lazy_vector.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/proto/example/lazy_vector.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 32.9931034483, "max_line_length": 88, "alphanum_fraction": 0.6599080268, "num_tokens": 1155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.43944382371202767}}
{"text": "#include \"libsnark/gadgetlib1/gadgets/basic_gadgets.hpp\"\n#include \"libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp\"\n#include \"libsnark/common/default_types/r1cs_ppzksnark_pp.hpp\"\n#include \"libff/common/utils.hpp\"\n#include <boost/optional.hpp>\n\nusing namespace libsnark;\nusing namespace std;\n\n#include \"payment_in_out_gadget.hpp\"\n#include \"payment_multi_gadget.hpp\"\n\ntemplate<typename ppzksnark_ppT>\nr1cs_ppzksnark_keypair<ppzksnark_ppT> generate_keypair()\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n\n    protoboard<FieldT> pb;\n    payment_in_out_gadget<FieldT> g(pb);\n    g.generate_payment_in_out_constraints();\n    const r1cs_constraint_system<FieldT> constraint_system = pb.get_constraint_system();\n\n    cout << \"Number of R1CS constraints: \" << constraint_system.num_constraints() << endl;\n\n    return r1cs_ppzksnark_generator<ppzksnark_ppT>(constraint_system);\n}\n\ntemplate<typename ppzksnark_ppT>\nr1cs_ppzksnark_keypair<ppzksnark_ppT> generate_keypair_multi()\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n\n    protoboard<FieldT> pb;\n    payment_multi_gadget<FieldT> g(pb);\n    g.generate_payment_multi_constraints();\n    const r1cs_constraint_system<FieldT> constraint_system = pb.get_constraint_system();\n\n    cout << \"Number of R1CS constraints: \" << constraint_system.num_constraints() << endl;\n\n    return r1cs_ppzksnark_generator<ppzksnark_ppT>(constraint_system);\n}\n\ntemplate<typename ppzksnark_ppT>\nboost::optional<r1cs_ppzksnark_proof<ppzksnark_ppT>> generate_payment_in_out_proof(r1cs_ppzksnark_proving_key<ppzksnark_ppT> proving_key,\n                                                                   const bit_vector &h_startbalance,\n                                                                   const bit_vector &h_endbalance,\n                                                                   const bit_vector &h_incoming,\n                                                                   const bit_vector &h_outgoing,\n                                                                   const bit_vector &r_startbalance,\n                                                                   const bit_vector &r_endbalance,\n                                                                   const bit_vector &r_incoming,\n                                                                   const bit_vector &r_outgoing\n                                                                   )\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n\n    protoboard<FieldT> pb;\n    payment_in_out_gadget<FieldT> g(pb);\n    g.generate_payment_in_out_constraints();\n    g.generate_payment_in_out_witness(h_startbalance, h_endbalance, h_incoming, h_outgoing, r_startbalance, r_endbalance, r_incoming, r_outgoing);\n\n    if (!pb.is_satisfied()) {\n      std::cout << \"System not satisfied!\" << std::endl;\n        return boost::none;\n    }\n\n    return r1cs_ppzksnark_prover<ppzksnark_ppT>(proving_key, pb.primary_input(), pb.auxiliary_input());\n}\n\n\ntemplate<typename ppzksnark_ppT>\nboost::optional<r1cs_ppzksnark_proof<ppzksnark_ppT>> generate_payment_multi_proof(r1cs_ppzksnark_proving_key<ppzksnark_ppT> proving_key,\n                                                            const bit_vector &h_startbalance,\n                                                            const bit_vector &h_endbalance,\n                                                            const bit_vector *h_incoming,\n                                                            const bit_vector *h_outgoing,\n                                                            const bit_vector &r_startbalance,\n                                                            const bit_vector &r_endbalance,\n                                                            const bit_vector *r_incoming,\n                                                            const bit_vector *r_outgoing\n                                                            )\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n\n    protoboard<FieldT> pb;\n    payment_multi_gadget<FieldT> g(pb);\n    g.generate_payment_multi_constraints();\n    g.generate_payment_multi_witness(h_startbalance, h_endbalance, h_incoming, h_outgoing, r_startbalance, r_endbalance, r_incoming, r_outgoing);\n\n    if (!pb.is_satisfied()) {\n      std::cout << \"System not satisfied!\" << std::endl;\n        return boost::none;\n    }\n\n    return r1cs_ppzksnark_prover<ppzksnark_ppT>(proving_key, pb.primary_input(), pb.auxiliary_input());\n}\n\ntemplate<typename ppzksnark_ppT>\nbool verify_payment_in_out_proof(r1cs_ppzksnark_verification_key<ppzksnark_ppT> verification_key,\n                  r1cs_ppzksnark_proof<ppzksnark_ppT> proof,\n                  const bit_vector &h_startbalance,\n                  const bit_vector &h_endbalance,\n                  const bit_vector &h_incoming,\n                  const bit_vector &h_outgoing\n                 )\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n\n    const r1cs_primary_input<FieldT> input = l_input_map<FieldT>(h_startbalance, h_endbalance, h_incoming, h_outgoing);\n\n    std::cout << \"**** After l_input_map *****\" << std::endl;\n\n    return r1cs_ppzksnark_verifier_strong_IC<ppzksnark_ppT>(verification_key, input, proof);\n\n}\n\ntemplate<typename ppzksnark_ppT>\nbool verify_payment_multi_proof(r1cs_ppzksnark_verification_key<ppzksnark_ppT> verification_key,\n                  r1cs_ppzksnark_proof<ppzksnark_ppT> proof,\n                  const bit_vector &h_startbalance,\n                  const bit_vector &h_endbalance,\n                  const bit_vector *h_incoming,\n                  const bit_vector *h_outgoing\n                 )\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n    const r1cs_primary_input<FieldT> input = l_input_map_multi<FieldT>(h_startbalance, h_endbalance, h_incoming, h_outgoing);\n\n    std::cout << \"**** After l_input_map_multi *****\" << std::endl;\n\n    return r1cs_ppzksnark_verifier_strong_IC<ppzksnark_ppT>(verification_key, input, proof);\n\n}\n", "meta": {"hexsha": "5ff397723416b0ee7d3bbfa9814f74f477e22f32", "size": 5911, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/snark.hpp", "max_stars_repo_name": "agiletechvn/ZKP", "max_stars_repo_head_hexsha": "d1294da076585e2a906aa64560a71fc68114c75c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 118.0, "max_stars_repo_stars_event_min_datetime": "2017-08-29T05:25:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:59:39.000Z", "max_issues_repo_path": "src/snark.hpp", "max_issues_repo_name": "technologiespro/zero-knowledge-proofs", "max_issues_repo_head_hexsha": "6fdfb0c25ae24e33b6325baa2b261860e89ae087", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-08-29T03:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-10T23:39:26.000Z", "max_forks_repo_path": "src/snark.hpp", "max_forks_repo_name": "technologiespro/zero-knowledge-proofs", "max_forks_repo_head_hexsha": "6fdfb0c25ae24e33b6325baa2b261860e89ae087", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T01:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T13:38:35.000Z", "avg_line_length": 44.1119402985, "max_line_length": 146, "alphanum_fraction": 0.6088648283, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.439425832812153}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_SINHCOSH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_SINHCOSH_HPP_INCLUDED\n\n#include <boost/simd/arch/common/detail/generic/sinh_kernel.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/constant/maxlog.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/scalar/average.hpp>\n#include <boost/simd/function/scalar/bitofsign.hpp>\n#include <boost/simd/function/scalar/bitwise_xor.hpp>\n#include <boost/simd/function/scalar/exp.hpp>\n#include <boost/simd/function/scalar/if_else.hpp>\n#include <boost/simd/function/scalar/rec.hpp>\n#include <boost/simd/function/scalar/sqr.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( sinhcosh_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_<bd::floating_<A0> >\n                          , bd::scalar_<bd::floating_<A0> >\n                          , bd::scalar_<bd::floating_<A0> >\n                          )\n  {\n    //////////////////////////////////////////////////////////////////////////////\n    // if x = abs(a0) is less than 1 sinh is computed using a polynomial(float)\n    // respectively rational(double) approx from cephes.\n    // else according x < Threshold e =  exp(x) or exp(x/2) is respectively\n    // computed\n    // * in the first case sinh is (e-rec(e))/2 and cosh (e+rec(e))/2\n    // * in the second     sinh and cosh are (e/2)*e (avoiding undue overflow)\n    // Threshold is Maxlog - Log_2\n    //////////////////////////////////////////////////////////////////////////////\n    BOOST_FORCEINLINE void operator() ( A0 a0,A0 & a1,A0 & a2) const BOOST_NOEXCEPT\n    {\n      A0 x = bs::abs(a0);\n      auto test1 = (x >  Maxlog<A0>()-Log_2<A0>());\n      A0 fac = if_else(test1, Half<A0>(), One<A0>());\n      A0 tmp = exp(x*fac);\n      A0 tmp1 = Half<A0>()*tmp;\n      A0 rtmp = rec(tmp);\n      A0 r =  test1 ? tmp1*tmp : tmp1-Half<A0>()*rtmp;\n      a1 = bitwise_xor(((x < One<A0>())\n                  ? detail::sinh_kernel<A0>::compute(x, sqr(x))\n                  : r),\n                 bitofsign(a0));\n      a2 = test1 ? r : bs::average(tmp, rtmp);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "a7c5daba8a2b64040bed0b176f92543293935f4e", "size": 2876, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/sinhcosh.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/scalar/function/sinhcosh.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/sinhcosh.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9444444444, "max_line_length": 100, "alphanum_fraction": 0.5507649513, "num_tokens": 701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120234, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4394258284466209}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <Eigen/Dense>\n#include \"bicycle/bicycle.h\"\n#include \"control_design_functions.h\"\n#include \"firmware_generator.h\"\n#include \"robot_bicycle_parameters.h\"\n\nint main(int argc, char ** argv)\n{\n  bicycle::Bicycle rb = bicycle::robot_bicycle();\n\n  design_parameters params;\n  params.N = 101;\n  params.Ts = 0.005;\n  params.lowest_speed = 0.5;\n  params.highest_speed = 10.0;\n  // LQR design parameters\n  constexpr double pi = M_PI;\n  constexpr double max_lean = 2.0*pi/180.0;    // rad\n  constexpr double max_steer = 5.0*pi/180.0;   // rad\n  constexpr double max_lean_frequency = 1*pi;  // rad / s\n  constexpr double max_steer_frequency = 20*pi;// rad / s\n  constexpr double max_steer_torque = 0.5;     // N * m\n  params.Q = Eigen::MatrixXd::Zero(4, 4);\n  params.Q(0, 0) = std::pow(max_lean, -2.0);\n  params.Q(1, 1) = std::pow(max_steer, -2.0);\n  params.Q(2, 2) = std::pow(max_lean_frequency * max_lean, -2.0);\n  params.Q(3, 3) = std::pow(max_steer_frequency * max_steer, -2.0);\n  params.R.resize(1, 1);\n  params.R << std::pow(max_steer_torque, -2.0);\n  // Observer pole placement factor\n  params.pole_placement_factor = 3.0;\n  // Kalman design\n  constexpr double lean_acc_std = 1e-3;          // rad / s / s\n  constexpr double steer_acc_std = 1e-2;         // rad / s / s\n  constexpr double lean_vel_std = .6827 * lean_acc_std;      // rad / s\n  constexpr double steer_vel_std = .6827 * steer_acc_std;     // rad / s\n  params.W.resize(4, 4);          // Process noise covariance\n  params.W << std::pow(lean_vel_std, 2.0), 0.0, 0.0, 0.0,\n              0.0, std::pow(steer_vel_std, 2.0), 0.0, 0.0,\n              0.0, 0.0, std::pow(lean_acc_std, 2.0), 0.0,\n              0.0, 0.0, 0.0, std::pow(steer_acc_std, 2.0);\n\n  params.V.resize(2, 2);          // Measurement noise covariance\n  params.V << std::pow(2*pi/20000, 2.0), 0,\n              0, std::pow(0.00227631723111, 2.0);\n\n  std::vector<model_data> md = design_controller(params, rb);\n  std::sort(md.begin(), md.end());\n  firmware_generator(md);\n}\n\n", "meta": {"hexsha": "d7af2e83d32bb256125b3b9d8296f7ad551bcb49", "size": 2057, "ext": "cc", "lang": "C++", "max_stars_repo_path": "design/full_order_observer.cc", "max_stars_repo_name": "hazelnusse/robot.bicycle", "max_stars_repo_head_hexsha": "b8d7c67290497577c96167dac123765efc4e08f8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T14:58:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-23T16:45:17.000Z", "max_issues_repo_path": "design/full_order_observer.cc", "max_issues_repo_name": "hazelnusse/robot.bicycle", "max_issues_repo_head_hexsha": "b8d7c67290497577c96167dac123765efc4e08f8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "design/full_order_observer.cc", "max_forks_repo_name": "hazelnusse/robot.bicycle", "max_forks_repo_head_hexsha": "b8d7c67290497577c96167dac123765efc4e08f8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-28T15:28:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-28T15:28:46.000Z", "avg_line_length": 37.4, "max_line_length": 72, "alphanum_fraction": 0.6373359261, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.43939662788110306}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2008 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Author: Wolfgang Bangerth, Texas A&M University, 2008 \n */ \n\n\n// @sect3{Include files}  \n\n// 像往常一样，我们从包括一些著名的文件开始。\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/utilities.h> \n\n#include <deal.II/lac/block_vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/block_sparse_matrix.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/precondition.h> \n#include <deal.II/lac/affine_constraints.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_tools.h> \n#include <deal.II/grid/grid_refinement.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_renumbering.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/fe_values.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n\n// 然后我们需要包括稀疏直接求解器UMFPACK的头文件。\n\n#include <deal.II/lac/sparse_direct.h> \n\n// 这包括不完全LU因子化的库，它将被用作3D的预处理程序。\n\n#include <deal.II/lac/sparse_ilu.h> \n\n// 这是C++语言。\n\n#include <iostream> \n#include <fstream> \n#include <memory> \n\n// 和所有的程序一样，名字空间dealii被包括在内。\n\nnamespace Step22 \n{ \n  using namespace dealii; \n// @sect3{Defining the inner preconditioner type}  \n\n// 正如介绍中所解释的，我们将分别对两个和三个空间维度使用不同的预处理程序。我们通过使用空间维度作为模板参数来区分它们。关于模板的细节，请参见 step-4 。我们不打算在这里创建任何预处理对象，我们所做的只是创建一个持有确定预处理类的本地别名的类，这样我们就可以以独立于维度的方式编写我们的程序。\n\n  template <int dim> \n  struct InnerPreconditioner; \n\n// 在二维中，我们将使用一个稀疏的直接求解器作为预处理程序。\n\n  template <> \n  struct InnerPreconditioner<2> \n  { \n    using type = SparseDirectUMFPACK; \n  }; \n\n// 还有三维的ILU预处理，由SparseILU调用。\n\n  template <> \n  struct InnerPreconditioner<3> \n  { \n    using type = SparseILU<double>; \n  }; \n// @sect3{The <code>StokesProblem</code> class template}  \n\n// 这是对 step-20 的改编，所以主类和数据类型与那里使用的几乎相同。唯一不同的是，我们有一个额外的成员  <code>preconditioner_matrix</code>  ，用于预处理Schur补码，以及一个相应的稀疏模式  <code>preconditioner_sparsity_pattern</code>  。此外，我们没有依赖LinearOperator，而是实现了我们自己的InverseMatrix类。\n\n// 在这个例子中，我们还使用了自适应网格细化，其处理方式与  step-6  类似。根据介绍中的讨论，我们也将使用AffineConstraints对象来实现Dirichlet边界条件。因此，我们改变名称  <code>hanging_node_constraints</code> into <code>constraints</code>  。\n\n  template <int dim> \n  class StokesProblem \n  { \n  public: \n    StokesProblem(const unsigned int degree); \n    void run(); \n\n  private: \n    void setup_dofs(); \n    void assemble_system(); \n    void solve(); \n    void output_results(const unsigned int refinement_cycle) const; \n    void refine_mesh(); \n\n    const unsigned int degree; \n\n    Triangulation<dim> triangulation; \n    FESystem<dim>      fe; \n    DoFHandler<dim>    dof_handler; \n\n    AffineConstraints<double> constraints; \n\n    BlockSparsityPattern      sparsity_pattern; \n    BlockSparseMatrix<double> system_matrix; \n\n    BlockSparsityPattern      preconditioner_sparsity_pattern; \n    BlockSparseMatrix<double> preconditioner_matrix; \n\n    BlockVector<double> solution; \n    BlockVector<double> system_rhs; \n\n// 这一条是新的：我们将使用一个所谓的共享指针结构来访问预处理程序。共享指针本质上只是指针的一种方便形式。几个共享指针可以指向同一个对象（就像普通的指针一样），但是当最后一个指向前提器对象的共享指针对象被删除时（例如共享指针对象超出了范围，它所在的类被销毁，或者指针被分配给了不同的前提器对象），那么指向的前提器对象也被销毁。这确保了我们不必手动跟踪有多少地方仍在引用一个前置条件器对象，它永远不会产生内存泄漏，也不会产生一个指向已被销毁对象的悬空指针。\n\n    std::shared_ptr<typename InnerPreconditioner<dim>::type> A_preconditioner; \n  }; \n// @sect3{Boundary values and right hand side}  \n\n// 与 step-20 和其他大多数例子程序一样，下一个任务是定义PDE的数据：对于斯托克斯问题，我们将在部分边界上使用自然边界值（即同质诺伊曼型），对于这些边界，我们不必做任何特殊处理（同质性意味着弱形式中的相应项只是零），而在边界的其余部分使用速度的边界条件（迪里希勒型），如介绍中所述。\n\n// 为了强制执行速度上的Dirichlet边界值，我们将像往常一样使用 VectorTools::interpolate_boundary_values 函数，这要求我们写一个具有与有限元一样多分量的函数对象。换句话说，我们必须在 $(u,p)$ -空间上定义函数，但在插值边界值时，我们要过滤掉压力分量。\n\n// 下面的函数对象是介绍中描述的边界值的表示。\n\n  template <int dim> \n  class BoundaryValues : public Function<dim> \n  { \n  public: \n    BoundaryValues() \n      : Function<dim>(dim + 1) \n    {} \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n    virtual void vector_value(const Point<dim> &p, \n                              Vector<double> &  value) const override; \n  }; \n\n  template <int dim> \n  double BoundaryValues<dim>::value(const Point<dim> & p, \n                                    const unsigned int component) const \n  { \n    Assert(component < this->n_components, \n           ExcIndexRange(component, 0, this->n_components)); \n\n    if (component == 0) \n      return (p[0] < 0 ? -1 : (p[0] > 0 ? 1 : 0)); \n    return 0; \n  } \n\n  template <int dim> \n  void BoundaryValues<dim>::vector_value(const Point<dim> &p, \n                                         Vector<double> &  values) const \n  { \n    for (unsigned int c = 0; c < this->n_components; ++c) \n      values(c) = BoundaryValues<dim>::value(p, c); \n  } \n\n// 我们为右手边实现类似的函数，在目前的例子中，右手边只是零。\n\n  template <int dim> \n  class RightHandSide : public Function<dim> \n  { \n  public: \n    RightHandSide() \n      : Function<dim>(dim + 1) \n    {} \n\n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override; \n\n    virtual void vector_value(const Point<dim> &p, \n                              Vector<double> &  value) const override; \n  }; \n\n  template <int dim> \n  double RightHandSide<dim>::value(const Point<dim> & /*p*/, \n                                   const unsigned int /*component*/) const \n  { \n    return 0; \n  } \n\n  template <int dim> \n  void RightHandSide<dim>::vector_value(const Point<dim> &p, \n                                        Vector<double> &  values) const \n  { \n    for (unsigned int c = 0; c < this->n_components; ++c) \n      values(c) = RightHandSide<dim>::value(p, c); \n  } \n// @sect3{Linear solvers and preconditioners}  \n\n// 在介绍中广泛讨论了线性求解器和预处理器。在这里，我们创建将被使用的各自对象。\n\n//  @sect4{The <code>InverseMatrix</code> class template}   <code>InverseMatrix</code> 类表示逆矩阵的数据结构。与 step-20 不同，我们用一个类来实现，而不是用辅助函数inverse_linear_operator()，我们将把这个类应用于不同种类的矩阵，这些矩阵需要不同的预处理程序（在 step-20 中，我们只对质量矩阵使用非同一性预处理程序）。矩阵和预处理器的类型通过模板参数传递给这个类，当创建 <code>InverseMatrix</code> 对象时，这些类型的矩阵和预处理器对象将被传递给构造器。成员函数 <code>vmult</code> 是通过解决一个线性系统得到的。\n\n  template <class MatrixType, class PreconditionerType> \n  class InverseMatrix : public Subscriptor \n  { \n  public: \n    InverseMatrix(const MatrixType &        m, \n                  const PreconditionerType &preconditioner); \n\n    void vmult(Vector<double> &dst, const Vector<double> &src) const; \n\n  private: \n    const SmartPointer<const MatrixType>         matrix; \n    const SmartPointer<const PreconditionerType> preconditioner; \n  }; \n\n  template <class MatrixType, class PreconditionerType> \n  InverseMatrix<MatrixType, PreconditionerType>::InverseMatrix( \n    const MatrixType &        m, \n    const PreconditionerType &preconditioner) \n    : matrix(&m) \n    , preconditioner(&preconditioner) \n  {} \n\n// 这就是 <code>vmult</code> 函数的实现。\n\n// 在这个类中，我们对解算器控制使用了一个相当大的容忍度。这样做的原因是，该函数被频繁使用，因此，任何使CG求解中的残差变小的额外努力都会使求解更加昂贵。请注意，我们不仅将该类作为Schur补码的预处理程序，而且在形成拉普拉斯矩阵的逆时也使用该类；因此，该类直接对解本身的精度负责，所以我们也不能选择太大的公差。\n\n  template <class MatrixType, class PreconditionerType> \n  void InverseMatrix<MatrixType, PreconditionerType>::vmult( \n    Vector<double> &      dst, \n    const Vector<double> &src) const \n  { \n    SolverControl            solver_control(src.size(), 1e-6 * src.l2_norm()); \n    SolverCG<Vector<double>> cg(solver_control); \n\n    dst = 0; \n\n    cg.solve(*matrix, dst, src, *preconditioner); \n  } \n// @sect4{The <code>SchurComplement</code> class template}  \n\n// 这个类实现了介绍中讨论的Schur补码。它与  step-20  相类似。 不过，我们现在用一个模板参数 <code>PreconditionerType</code> 来调用它，以便在指定逆矩阵类的各自类型时访问它。作为上述定义的结果，声明  <code>InverseMatrix</code>  现在包含了上述预处理类的第二个模板参数，这也影响到  <code>SmartPointer</code> object <code>m_inverse</code>  。\n\n  template <class PreconditionerType> \n  class SchurComplement : public Subscriptor \n  { \n  public: \n    SchurComplement( \n      const BlockSparseMatrix<double> &system_matrix, \n      const InverseMatrix<SparseMatrix<double>, PreconditionerType> &A_inverse); \n\n    void vmult(Vector<double> &dst, const Vector<double> &src) const; \n\n  private: \n    const SmartPointer<const BlockSparseMatrix<double>> system_matrix; \n    const SmartPointer< \n      const InverseMatrix<SparseMatrix<double>, PreconditionerType>> \n      A_inverse; \n\n    mutable Vector<double> tmp1, tmp2; \n  }; \n\n  template <class PreconditionerType> \n  SchurComplement<PreconditionerType>::SchurComplement( \n    const BlockSparseMatrix<double> &system_matrix, \n    const InverseMatrix<SparseMatrix<double>, PreconditionerType> &A_inverse) \n    : system_matrix(&system_matrix) \n    , A_inverse(&A_inverse) \n    , tmp1(system_matrix.block(0, 0).m()) \n    , tmp2(system_matrix.block(0, 0).m()) \n  {} \n\n  template <class PreconditionerType> \n  void \n  SchurComplement<PreconditionerType>::vmult(Vector<double> &      dst, \n                                             const Vector<double> &src) const \n  { \n    system_matrix->block(0, 1).vmult(tmp1, src); \n    A_inverse->vmult(tmp2, tmp1); \n    system_matrix->block(1, 0).vmult(dst, tmp2); \n  } \n// @sect3{StokesProblem class implementation}  \n// @sect4{StokesProblem::StokesProblem}  \n\n// 这个类的构造函数看起来与  step-20  的构造函数非常相似。构造函数初始化了多项式程度、三角形、有限元系统和dof处理器的变量。矢量速度分量的基础多项式函数的阶数为 <code>degree+1</code> ，压力的阶数为 <code>degree</code> 。 这就得到了LBB稳定元对 $Q_{degree+1}^d\\times Q_{degree}$ ，通常被称为泰勒-霍德元。\n\n// 请注意，我们用MeshSmoothing参数初始化三角形，这可以确保单元的细化是以PDE解的近似保持良好的方式进行的（如果网格过于非结构化就会出现问题），详情请参见 <code>Triangulation::MeshSmoothing</code> 的文档。\n\n  template <int dim> \n  StokesProblem<dim>::StokesProblem(const unsigned int degree) \n    : degree(degree) \n    , triangulation(Triangulation<dim>::maximum_smoothing) \n    , fe(FE_Q<dim>(degree + 1), dim, FE_Q<dim>(degree), 1) \n    , dof_handler(triangulation) \n  {} \n// @sect4{StokesProblem::setup_dofs}  \n\n// 给定一个网格，该函数将自由度与之关联，并创建相应的矩阵和向量。在开始的时候，它还释放了指向预处理对象的指针（如果共享指针在此时指向任何东西的话），因为在这之后肯定不会再需要它了，在组装矩阵后必须重新计算，并将稀疏矩阵从其稀疏模式对象中解开。\n\n// 然后，我们继续分配自由度并重新编号。为了使ILU预处理程序（在3D中）有效地工作，重要的是以这样的方式列举自由度，以减少矩阵的带宽，或者也许更重要的是：以这样的方式使ILU尽可能地接近于真正的LU分解。另一方面，我们需要保留在  step-20  和  step-21  中已经看到的速度和压力的块状结构。这将分两步完成。首先，对所有的道次进行重新编号，以改善ILU，然后我们再一次按组件重新编号。由于 <code>DoFRenumbering::component_wise</code> 没有触及单个块内的重新编号，所以第一步的基本重新编号仍然存在。至于如何对自由度进行重新编号以提高ILU：deal.II有许多算法试图找到排序以提高ILU，或减少矩阵的带宽，或优化其他方面。DoFRenumbering命名空间显示了我们在本教程程序中基于这里讨论的测试案例而获得的几种算法的结果比较。在这里，我们将使用传统的Cuthill-McKee算法，该算法已经在之前的一些教程程序中使用。 在<a href=\"#improved-ilu\">section on improved ILU</a>中我们将更详细地讨论这个问题。\n//与以前的教程程序相比，\n//还有一个变化。没有理由对 <code>dim</code> 的速度成分进行单独排序。事实上，与其先列举所有 $x$ -velocities，再列举所有 $y$ -velocities，等等，我们希望将所有速度放在一起，只在速度（所有分量）和压力之间分开。默认情况下， DoFRenumbering::component_wise 函数不是这样做的：它把每个矢量分量分开处理；我们要做的是把几个分量分成 \"块\"，并把这个块结构传递给该函数。因此，我们分配一个矢量 <code>block_component</code> ，有多少个元素就有多少个分量，描述所有的速度分量对应于块0，而压力分量将形成块1。\n\n  template <int dim> \n  void StokesProblem<dim>::setup_dofs() \n  { \n    A_preconditioner.reset(); \n    system_matrix.clear(); \n    preconditioner_matrix.clear(); \n\n    dof_handler.distribute_dofs(fe); \n    DoFRenumbering::Cuthill_McKee(dof_handler); \n\n    std::vector<unsigned int> block_component(dim + 1, 0); \n    block_component[dim] = 1; \n    DoFRenumbering::component_wise(dof_handler, block_component); \n\n// 现在是对Dirichlet边界条件的实现，在介绍中的讨论之后，这应该是很明显的。所有的变化是，这个函数已经出现在设置函数中，而我们习惯于在一些汇编例程中看到它。在我们设置网格的下面，我们将把施加Dirichlet边界条件的顶部边界与边界指标1联系起来。 我们必须将这个边界指标作为第二个参数传递给下面的插值函数。 不过，还有一件事。 描述Dirichlet条件的函数是为所有分量定义的，包括速度和压力。然而，Dirichlet条件只为速度而设置。 为此，我们使用一个只选择速度分量的ComponentMask。通过指定我们想要的特定分量，从有限元中获得该分量掩码。由于我们使用自适应细化网格，仿生约束对象需要首先填充由DoF处理程序生成的悬挂节点约束。注意这两个函数的顺序；我们首先计算悬挂节点约束，然后将边界值插入约束对象。这确保了我们在有悬挂节点的边界上尊重H<sup>1</sup>一致性（在三个空间维度上），悬挂节点需要支配Dirichlet边界值。\n\n    { \n      constraints.clear(); \n\n      FEValuesExtractors::Vector velocities(0); \n      DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n      VectorTools::interpolate_boundary_values(dof_handler, \n                                               1, \n                                               BoundaryValues<dim>(), \n                                               constraints, \n                                               fe.component_mask(velocities)); \n    } \n\n    constraints.close(); \n\n// 与 step-20 相类似，我们计算各个组件中的道夫。我们可以用与那里相同的方式来做，但我们想在我们已经用于重新编号的块结构上进行操作。函数  <code>DoFTools::count_dofs_per_fe_block</code>  的作用与  <code>DoFTools::count_dofs_per_fe_component</code>  相同，但现在通过  <code>block_component</code>  将速度和压力块分组。\n\n    const std::vector<types::global_dof_index> dofs_per_block = \n      DoFTools::count_dofs_per_fe_block(dof_handler, block_component); \n    const unsigned int n_u = dofs_per_block[0]; \n    const unsigned int n_p = dofs_per_block[1]; \n\n    std::cout << \"   Number of active cells: \" << triangulation.n_active_cells() \n              << std::endl \n              << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << \" (\" << n_u << '+' << n_p << ')' << std::endl; \n\n// 下一个任务是为我们将创建的系统矩阵分配一个稀疏模式，为预处理矩阵分配一个稀疏模式。我们可以用与 step-20 相同的方式来做这件事，即通过 DoFTools::make_sparsity_pattern. 直接建立一个SparsityPattern类型的对象，但是，有一个重要的理由不这样做。在3D中，函数 DoFTools::max_couplings_between_dofs 对各个道夫之间的耦合产生了一个保守但相当大的数字，因此，最初为创建矩阵的稀疏模式提供的内存太多--实际上，对于中等大小的3D问题，初始稀疏模式甚至无法放入大多数系统的物理内存中，也请参见 step-18  中的讨论。相反，我们首先建立临时对象，使用不同的数据结构，不需要分配更多的内存，但不适合作为SparseMatrix或BlockSparseMatrix对象的基础；在第二步，我们将这些对象复制到BlockSparsityPattern类型的对象中。这完全类似于我们在  step-11  和  step-18  中已经做过的事情。特别是，我们利用了这样一个事实，即我们永远不会写入系统矩阵的 $(1,1)$ 块中，而且这是唯一需要填充的预处理矩阵块。\n\n// 所有这些都是在新范围内完成的，这意味着一旦信息被复制到  <code>sparsity_pattern</code>  ，  <code>dsp</code>  的内存将被释放。\n\n    { \n      BlockDynamicSparsityPattern dsp(2, 2); \n\n      dsp.block(0, 0).reinit(n_u, n_u); \n      dsp.block(1, 0).reinit(n_p, n_u); \n      dsp.block(0, 1).reinit(n_u, n_p); \n      dsp.block(1, 1).reinit(n_p, n_p); \n\n      dsp.collect_sizes(); \n\n      Table<2, DoFTools::Coupling> coupling(dim + 1, dim + 1); \n\n      for (unsigned int c = 0; c < dim + 1; ++c) \n        for (unsigned int d = 0; d < dim + 1; ++d) \n          if (!((c == dim) && (d == dim))) \n            coupling[c][d] = DoFTools::always; \n          else \n            coupling[c][d] = DoFTools::none; \n\n      DoFTools::make_sparsity_pattern( \n        dof_handler, coupling, dsp, constraints, false); \n\n \n    } \n\n    { \n      BlockDynamicSparsityPattern preconditioner_dsp(2, 2); \n\n      preconditioner_dsp.block(0, 0).reinit(n_u, n_u); \n      preconditioner_dsp.block(1, 0).reinit(n_p, n_u); \n      preconditioner_dsp.block(0, 1).reinit(n_u, n_p); \n      preconditioner_dsp.block(1, 1).reinit(n_p, n_p); \n\n      preconditioner_dsp.collect_sizes(); \n\n      Table<2, DoFTools::Coupling> preconditioner_coupling(dim + 1, dim + 1); \n\n      for (unsigned int c = 0; c < dim + 1; ++c) \n        for (unsigned int d = 0; d < dim + 1; ++d) \n          if (((c == dim) && (d == dim))) \n            preconditioner_coupling[c][d] = DoFTools::always; \n          else \n            preconditioner_coupling[c][d] = DoFTools::none; \n\n      DoFTools::make_sparsity_pattern(dof_handler, \n                                      preconditioner_coupling, \n                                      preconditioner_dsp, \n                                      constraints, \n                                      false); \n\n      preconditioner_sparsity_pattern.copy_from(preconditioner_dsp); \n    } \n\n// 最后，与  step-20  中的方法类似，从块状结构中创建系统矩阵、前导矩阵、解决方案和右侧向量。\n\n    system_matrix.reinit(sparsity_pattern); \n    preconditioner_matrix.reinit(preconditioner_sparsity_pattern); \n\n    solution.reinit(2); \n    solution.block(0).reinit(n_u); \n    solution.block(1).reinit(n_p); \n    solution.collect_sizes(); \n\n    system_rhs.reinit(2); \n    system_rhs.block(0).reinit(n_u); \n    system_rhs.block(1).reinit(n_p); \n    system_rhs.collect_sizes(); \n  } \n// @sect4{StokesProblem::assemble_system}  \n\n// 汇编过程遵循 step-20 和介绍中的讨论。我们使用众所周知的缩写来表示保存本单元自由度的局部矩阵、右手边和全局编号的数据结构。\n\n  template <int dim> \n  void StokesProblem<dim>::assemble_system() \n  { \n    system_matrix         = 0; \n    system_rhs            = 0; \n    preconditioner_matrix = 0; \n\n    QGauss<dim> quadrature_formula(degree + 2); \n\n    FEValues<dim> fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_quadrature_points | \n                              update_JxW_values | update_gradients); \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n\n    const unsigned int n_q_points = quadrature_formula.size(); \n\n    FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell); \n    FullMatrix<double> local_preconditioner_matrix(dofs_per_cell, \n                                                   dofs_per_cell); \n    Vector<double>     local_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    const RightHandSide<dim>    right_hand_side; \n    std::vector<Vector<double>> rhs_values(n_q_points, Vector<double>(dim + 1)); \n\n// 接下来，我们需要两个对象，作为FEValues对象的提取器。它们的用途在  @ref  vector_valued 的报告中详细解释。\n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure(dim); \n\n// 作为对 step-20 和 step-21 的扩展，我们包括了一些优化，使这个特定问题的装配速度大大加快。这些改进是基于这样的观察：当我们像 step-20 那样做时，我们做了太多次的计算：对称梯度实际上在每个正交点有 <code>dofs_per_cell</code> 个不同的值，但是我们从FEValues对象中提取了 <code>dofs_per_cell*dofs_per_cell</code> 次。\n\n// - 在 <code>i</code> 的循环和 <code>j</code> 的内循环中。在3D中，这意味着评估它 $89^2=7921$ 次而不是 $89$ 次，这是一个不小的差别。\n\n// 所以我们在这里要做的是，在开始对单元上的道夫进行循环之前，在正交点得到一个秩-2张量的向量（类似的还有压力上的发散和基函数值）来避免这种重复计算。首先，我们创建各自的对象来保存这些值。然后，我们开始在所有单元上进行循环，并在正交点上进行循环，在那里我们首先提取这些值。我们在这里还实现了一个优化：本地矩阵（以及全局矩阵）将是对称的，因为所有涉及的操作都是相对于 $i$ 和 $j$ 对称的。这可以通过简单地运行内循环而不是 <code>dofs_per_cell</code>, but only up to <code>i</code> 来实现，即外循环的索引。\n\n    std::vector<SymmetricTensor<2, dim>> symgrad_phi_u(dofs_per_cell); \n    std::vector<double>                  div_phi_u(dofs_per_cell); \n    std::vector<double>                  phi_p(dofs_per_cell); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        fe_values.reinit(cell); \n        local_matrix                = 0; \n        local_preconditioner_matrix = 0; \n        local_rhs                   = 0; \n\n        right_hand_side.vector_value_list(fe_values.get_quadrature_points(), \n                                          rhs_values); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            for (unsigned int k = 0; k < dofs_per_cell; ++k) \n              { \n                symgrad_phi_u[k] = \n                  fe_values[velocities].symmetric_gradient(k, q); \n                div_phi_u[k] = fe_values[velocities].divergence(k, q); \n                phi_p[k]     = fe_values[pressure].value(k, q); \n              } \n\n// 最后是系统矩阵和我们用于预处理程序的矩阵的双线性形式。回顾一下，这两个的公式分别是\n  //  @f{align*}{\n  //    A_{ij} &= a(\\varphi_i,\\varphi_j)\n  //    \\\\     &= \\underbrace{2(\\varepsilon(\\varphi_{i,\\textbf{u}}),\n  //                            \\varepsilon(\\varphi_{j,\\textbf{u}}))_{\\Omega}}\n  //                         _{(1)}\n  //            \\;\n  //              \\underbrace{- (\\textrm{div}\\; \\varphi_{i,\\textbf{u}},\n  //                             \\varphi_{j,p})_{\\Omega}}\n  //                         _{(2)}\n  //            \\;\n  //              \\underbrace{- (\\varphi_{i,p},\n  //                             \\textrm{div}\\;\n  //                             \\varphi_{j,\\textbf{u}})_{\\Omega}}\n  //                         _{(3)}\n  //  @f}\n  //  和\n  //  @f{align*}{\n  //    M_{ij} &= \\underbrace{(\\varphi_{i,p},\n  //                           \\varphi_{j,p})_{\\Omega}}\n  //                         _{(4)},\n  //  @f} ， \n  //  其中 $\\varphi_{i,\\textbf{u}}$ 和 $\\varphi_{i,p}$ 是 $i$ th形状函数的速度和压力成分。然后，上述各种术语在下面的实现中很容易识别。\n\n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              { \n                for (unsigned int j = 0; j <= i; ++j) \n                  { \n                    local_matrix(i, j) += \n                      (2 * (symgrad_phi_u[i] * symgrad_phi_u[j]) // (1) \n                       - div_phi_u[i] * phi_p[j]                 // (2) \n                       - phi_p[i] * div_phi_u[j])                // (3) \n                      * fe_values.JxW(q);                        // * dx \n\n                    local_preconditioner_matrix(i, j) += \n                      (phi_p[i] * phi_p[j]) // (4) \n                      * fe_values.JxW(q);   // * dx \n                  } \n\n// 注意在上述（1）的实现中，`operator*`被重载用于对称张量，产生两个张量之间的标量乘积。            对于右手边，我们利用形状函数只在一个分量中不为零的事实（因为我们的元素是原始的）。 我们不是将代表形状函数i的dim+1值的张量与整个右手边的向量相乘，而是只看唯一的非零分量。函数 FiniteElement::system_to_component_index 将返回这个形状函数所处的分量（0=x速度，1=y速度，2=2d中的压力），我们用它来挑选出右手边向量的正确分量来相乘。\n\n                const unsigned int component_i = \n                  fe.system_to_component_index(i).first; \n                local_rhs(i) += (fe_values.shape_value(i, q)   // (phi_u_i(x_q) \n                                 * rhs_values[q](component_i)) // * f(x_q)) \n                                * fe_values.JxW(q);            // * dx \n              } \n          } \n\n// 在我们将局部数据写入全局矩阵之前（同时使用AffineConstraints对象来应用Dirichlet边界条件并消除悬挂的节点约束，正如我们在介绍中讨论的那样），我们必须注意一件事。由于对称性，我们只建立了一半的局部矩阵，但我们要保存完整的矩阵，以便使用标准函数进行解算。这是通过翻转指数来实现的，以防我们指向本地矩阵的空部分。\n\n        for (unsigned int i = 0; i < dofs_per_cell; ++i) \n          for (unsigned int j = i + 1; j < dofs_per_cell; ++j) \n            { \n              local_matrix(i, j) = local_matrix(j, i); \n              local_preconditioner_matrix(i, j) = \n                local_preconditioner_matrix(j, i); \n            } \n\n        cell->get_dof_indices(local_dof_indices); \n        constraints.distribute_local_to_global(local_matrix, \n                                               local_rhs, \n                                               local_dof_indices, \n                                               system_matrix, \n                                               system_rhs); \n        constraints.distribute_local_to_global(local_preconditioner_matrix, \n                                               local_dof_indices, \n                                               preconditioner_matrix); \n      } \n\n// 在我们要解决这个线性系统之前，我们为速度-速度矩阵生成一个预处理程序，即系统矩阵中的 <code>block(0,0)</code> 。如上所述，这取决于空间维度。由于 <code>InnerPreconditioner::type</code> 别名所描述的两个类具有相同的接口，因此无论我们想使用稀疏直接求解器还是ILU，都不需要做任何不同的事情。\n\n    std::cout << \"   Computing preconditioner...\" << std::endl << std::flush; \n\n    A_preconditioner = \n      std::make_shared<typename InnerPreconditioner<dim>::type>(); \n    A_preconditioner->initialize( \n      system_matrix.block(0, 0), \n      typename InnerPreconditioner<dim>::type::AdditionalData()); \n  } \n\n//  @sect4{StokesProblem::solve}  \n\n// 经过前面介绍中的讨论和各自类的定义， <code>solve</code> 函数的实现是相当直接的，其方式与 step-20 类似。首先，我们需要一个 <code>InverseMatrix</code> 类的对象，代表矩阵A的逆。正如在介绍中所描述的，在  <code>InnerPreconditioner::type</code>  类型的内部预处理器的帮助下，生成了逆。\n\n  template <int dim> \n  void StokesProblem<dim>::solve() \n  { \n    const InverseMatrix<SparseMatrix<double>, \n                        typename InnerPreconditioner<dim>::type> \n                   A_inverse(system_matrix.block(0, 0), *A_preconditioner); \n    Vector<double> tmp(solution.block(0).size()); \n\n// 这与  step-20  中的情况一样。我们生成 Schur 补数的右手边  $B A^{-1} F - G$  和一个代表各自线性运算的对象  $B A^{-1} B^T$  ，现在有一个模板参数表示预处理器\n\n// - 按照类的定义。\n\n    { \n      Vector<double> schur_rhs(solution.block(1).size()); \n      A_inverse.vmult(tmp, system_rhs.block(0)); \n      system_matrix.block(1, 0).vmult(schur_rhs, tmp); \n      schur_rhs -= system_rhs.block(1); \n\n      SchurComplement<typename InnerPreconditioner<dim>::type> schur_complement( \n        system_matrix, A_inverse); \n\n// 解算器调用的常规控制结构被创建...\n\n      SolverControl            solver_control(solution.block(1).size(), \n                                   1e-6 * schur_rhs.l2_norm()); \n      SolverCG<Vector<double>> cg(solver_control); \n\n// 现在是对舒尔补码的预处理。正如介绍中所解释的，预处理是由压力变量的质量矩阵来完成的。\n\n// 实际上，求解器需要有 $P^{-1}$ 形式的预处理，所以我们需要创建一个逆运算。我们再次使用一个 <code>InverseMatrix</code> 类的对象，它实现了求解器需要的 <code>vmult</code> 操作。 在这种情况下，我们必须对压力质量矩阵进行反转。正如在早期的教程程序中已经证明的那样，质量矩阵的反转是一个相当便宜和简单的操作（与拉普拉斯矩阵等相比）。带有ILU预处理的CG方法在5-10步内收敛，与网格大小无关。 这正是我们在这里所做的。我们选择另一个ILU预处理，并通过相应的模板参数将其带入InverseMatrix对象。 然后在逆矩阵的vmult操作中调用一个CG求解器。\n\n// 另一种方法是选择因子为1.2的SSOR预处理器，这种方法构建成本较低，但之后需要更多的迭代。它需要大约两倍的迭代次数，但其生成的成本几乎可以忽略不计。\n\n      SparseILU<double> preconditioner; \n      preconditioner.initialize(preconditioner_matrix.block(1, 1), \n                                SparseILU<double>::AdditionalData()); \n\n      InverseMatrix<SparseMatrix<double>, SparseILU<double>> m_inverse( \n        preconditioner_matrix.block(1, 1), preconditioner); \n\n// 有了舒尔补码和高效的预处理程序，我们可以用通常的方法解决压力的相关方程（即解向量中的0块）。\n\n      cg.solve(schur_complement, solution.block(1), schur_rhs, m_inverse); \n\n// 在这第一个求解步骤之后，必须将悬挂的节点约束分布到求解中，以实现一致的压力场。\n\n      constraints.distribute(solution); \n\n      std::cout << \"  \" << solver_control.last_step() \n                << \" outer CG Schur complement iterations for pressure\" \n                << std::endl; \n    } \n\n// 和 step-20 一样，我们最后需要解速度方程，在这里我们插入压力方程的解。这只涉及我们已经知道的对象\n\n// 所以我们只需用 $p$ 乘以 $B^T$ ，减去右边的部分，再乘以 $A$ 的逆数。最后，我们需要分配悬挂节点的约束，以获得一个一致的流场。\n\n    { \n      system_matrix.block(0, 1).vmult(tmp, solution.block(1)); \n      tmp *= -1; \n      tmp += system_rhs.block(0); \n\n      A_inverse.vmult(solution.block(0), tmp); \n\n      constraints.distribute(solution); \n    } \n  } \n// @sect4{StokesProblem::output_results}  \n\n// 下一个函数生成图形输出。在这个例子中，我们将使用VTK文件格式。 我们给问题中的各个变量附上名字： <code>velocity</code> to the <code>dim</code> 速度的组成部分和 <code>pressure</code> 压力的组成部分。\n\n// 并非所有的可视化程序都有能力将各个矢量分量组合成一个矢量来提供矢量图；特别是对于一些基于VTK的可视化程序来说，这一点是成立的。在这种情况下，在包含数据的文件中应该已经描述了组件的逻辑分组为矢量的情况。换句话说，我们需要做的是为我们的输出编写者提供一种方法，让他们知道有限元的哪些分量在逻辑上形成一个矢量（在 $d$ 空间维度上有 $d$ 分量），而不是让他们假设我们只是有一堆标量场。 这是用 <code>DataComponentInterpretation</code> 命名空间的成员实现的：和文件名一样，我们创建一个矢量，其中第一个 <code>dim</code> 分量指的是速度，并被赋予 DataComponentInterpretation::component_is_part_of_vector; 标签，我们最后推一个标签 DataComponentInterpretation::component_is_scalar 来描述压力变量的分组。\n\n// 然后函数的其余部分与  step-20  中的相同。\n\n  template <int dim> \n  void \n  StokesProblem<dim>::output_results(const unsigned int refinement_cycle) const \n  { \n    std::vector<std::string> solution_names(dim, \"velocity\"); \n    solution_names.emplace_back(\"pressure\"); \n\n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      data_component_interpretation( \n        dim, DataComponentInterpretation::component_is_part_of_vector); \n    data_component_interpretation.push_back( \n      DataComponentInterpretation::component_is_scalar); \n\n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \n                             solution_names, \n                             DataOut<dim>::type_dof_data, \n                             data_component_interpretation); \n    data_out.build_patches(); \n\n    std::ofstream output( \n      \"solution-\" + Utilities::int_to_string(refinement_cycle, 2) + \".vtk\"); \n    data_out.write_vtk(output); \n  } \n// @sect4{StokesProblem::refine_mesh}  \n\n// 这是 <code>StokesProblem</code> 类中最后一个有趣的函数。 正如它的名字所示，它获取问题的解决方案，并在需要时细化网格。其过程与 step-6 中的相应步骤相同，不同的是我们只根据压力的变化进行细化，也就是说，我们用ComponentMask类型的掩码对象调用Kelly误差估计器，选择我们感兴趣的压力的单一标量分量（我们通过指定我们想要的分量从有限元类中得到这样一个掩码）。此外，我们没有再次粗化网格。\n\n  template <int dim> \n  void StokesProblem<dim>::refine_mesh() \n  { \n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n\n    FEValuesExtractors::Scalar pressure(dim); \n    KellyErrorEstimator<dim>::estimate( \n      dof_handler, \n      QGauss<dim - 1>(degree + 1), \n      std::map<types::boundary_id, const Function<dim> *>(), \n      solution, \n      estimated_error_per_cell, \n      fe.component_mask(pressure)); \n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    estimated_error_per_cell, \n                                                    0.3, \n                                                    0.0); \n    triangulation.execute_coarsening_and_refinement(); \n  } \n// @sect4{StokesProblem::run}  \n\n// 在斯托克斯类中的最后一步，像往常一样，是生成初始网格的函数，并按各自的顺序调用其他函数。\n\n// 我们从一个大小为 $4 \\times 1$ （2D）或 $4 \\times 1 \\times 1$ （3D）的矩形开始，在 $R^2/R^3$ 中分别放置为 $(-2,2)\\times(-1,0)$ 或 $(-2,2)\\times(0,1)\\times(-1,0)$  。在每个方向上以相等的网格大小开始是很自然的，所以我们在第一个坐标方向上将初始矩形细分四次。为了将创建网格所涉及的变量的范围限制在我们实际需要的范围内，我们将整个块放在一对大括号之间。\n\n  template <int dim> \n  void StokesProblem<dim>::run() \n  { \n    { \n      std::vector<unsigned int> subdivisions(dim, 1); \n      subdivisions[0] = 4; \n\n      const Point<dim> bottom_left = (dim == 2 ?                // \n                                        Point<dim>(-2, -1) :    // 2d case \n                                        Point<dim>(-2, 0, -1)); // 3d case \n\n      const Point<dim> top_right = (dim == 2 ?              // \n                                      Point<dim>(2, 0) :    // 2d case \n                                      Point<dim>(2, 1, 0)); // 3d case \n\n      GridGenerator::subdivided_hyper_rectangle(triangulation, \n                                                subdivisions, \n                                                bottom_left, \n                                                top_right); \n    } \n\n// 边界指标1被设置为所有受Dirichlet边界条件约束的边界，即位于最后一个坐标方向上的0的面。详见上面的例子描述。\n\n    for (const auto &cell : triangulation.active_cell_iterators()) \n      for (const auto &face : cell->face_iterators()) \n        if (face->center()[dim - 1] == 0) \n          face->set_all_boundary_ids(1); \n\n// 然后，在第一次求解之前，我们应用一个初始细化。在3D中，会有更多的自由度，所以我们在那里细化得更少。\n\n    triangulation.refine_global(4 - dim); \n\n// 正如在 step-6 中第一次看到的那样，我们在不同的细化级别上循环细化（除了第一个循环），设置自由度和矩阵，组装，求解和创建输出。\n\n    for (unsigned int refinement_cycle = 0; refinement_cycle < 6; \n         ++refinement_cycle) \n      { \n        std::cout << \"Refinement cycle \" << refinement_cycle << std::endl; \n\n        if (refinement_cycle > 0) \n          refine_mesh(); \n\n        setup_dofs(); \n\n        std::cout << \"   Assembling...\" << std::endl << std::flush; \n        assemble_system(); \n\n        std::cout << \"   Solving...\" << std::flush; \n        solve(); \n\n        output_results(refinement_cycle); \n\n        std::cout << std::endl; \n      } \n  } \n} // namespace Step22 \n// @sect3{The <code>main</code> function}  \n\n// 主函数与  step-20  中的相同。我们将元素度数作为参数传递，并在众所周知的模板槽中选择空间尺寸。\n\nint main() \n{ \n  try \n    { \n      using namespace Step22; \n\n      StokesProblem<2> flow_problem(1); \n      flow_problem.run(); \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n\n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "ffde580e49ea7500b4e9e726177d3fb7c02b509c", "size": 31755, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-22/step-22.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-22/step-22.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-22/step-22.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9154411765, "max_line_length": 523, "alphanum_fraction": 0.6277751535, "num_tokens": 12633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.4393931430378644}}
{"text": "\r\n\r\n#include <NTL/GF2EX.h>\r\n#include <NTL/vec_vec_GF2.h>\r\n#include <NTL/ZZX.h>\r\n\r\n#include <NTL/new.h>\r\n\r\nNTL_START_IMPL\r\n\r\n\r\n\r\nconst GF2EX& GF2EX::zero()\r\n{\r\n   NTL_THREAD_LOCAL static GF2EX z;\r\n   return z;\r\n}\r\n\r\n\r\n\r\nistream& operator>>(istream& s, GF2EX& x)\r\n{\r\n   NTL_INPUT_CHECK_RET(s, s >> x.rep);\r\n   x.normalize();\r\n   return s;\r\n}\r\n\r\nostream& operator<<(ostream& s, const GF2EX& a)\r\n{\r\n   return s << a.rep;\r\n}\r\n\r\n\r\nvoid GF2EX::normalize()\r\n{\r\n   long n;\r\n   const GF2E* p;\r\n\r\n   n = rep.length();\r\n   if (n == 0) return;\r\n   p = rep.elts() + n;\r\n   while (n > 0 && IsZero(*--p)) {\r\n      n--;\r\n   }\r\n   rep.SetLength(n);\r\n}\r\n\r\n\r\nlong IsZero(const GF2EX& a)\r\n{\r\n   return a.rep.length() == 0;\r\n}\r\n\r\n\r\nlong IsOne(const GF2EX& a)\r\n{\r\n    return a.rep.length() == 1 && IsOne(a.rep[0]);\r\n}\r\n\r\nvoid GetCoeff(GF2E& x, const GF2EX& a, long i)\r\n{\r\n   if (i < 0 || i > deg(a))\r\n      clear(x);\r\n   else\r\n      x = a.rep[i];\r\n}\r\n\r\nvoid SetCoeff(GF2EX& x, long i, const GF2E& a)\r\n{\r\n   long j, m;\r\n\r\n   if (i < 0) \r\n      LogicError(\"SetCoeff: negative index\");\r\n\r\n   if (NTL_OVERFLOW(i, 1, 0))\r\n      LogicError(\"overflow in SetCoeff\");\r\n\r\n   m = deg(x);\r\n\r\n   if (i > m && IsZero(a)) return; \r\n\r\n   if (i > m) {\r\n      /* careful: a may alias a coefficient of x */\r\n\r\n      long alloc = x.rep.allocated();\r\n\r\n      if (alloc > 0 && i >= alloc) {\r\n         GF2E aa = a;\r\n         x.rep.SetLength(i+1);\r\n         x.rep[i] = aa;\r\n      }\r\n      else {\r\n         x.rep.SetLength(i+1);\r\n         x.rep[i] = a;\r\n      }\r\n\r\n      for (j = m+1; j < i; j++)\r\n         clear(x.rep[j]);\r\n   }\r\n   else\r\n      x.rep[i] = a;\r\n\r\n   x.normalize();\r\n}\r\n\r\nvoid SetCoeff(GF2EX& x, long i, GF2 a)\r\n{\r\n   if (i < 0)\r\n      LogicError(\"SetCoeff: negative index\");\r\n\r\n   if (a == 1)\r\n      SetCoeff(x, i);\r\n   else\r\n      SetCoeff(x, i, GF2E::zero());\r\n}\r\n\r\nvoid SetCoeff(GF2EX& x, long i, long a)\r\n{\r\n   if (i < 0)\r\n      LogicError(\"SetCoeff: negative index\");\r\n\r\n   if ((a & 1) == 1)\r\n      SetCoeff(x, i);\r\n   else\r\n      SetCoeff(x, i, GF2E::zero());\r\n}\r\n\r\nvoid SetCoeff(GF2EX& x, long i)\r\n{\r\n   long j, m;\r\n\r\n   if (i < 0) \r\n      LogicError(\"coefficient index out of range\");\r\n\r\n   if (NTL_OVERFLOW(i, 1, 0))\r\n      ResourceError(\"overflow in SetCoeff\");\r\n\r\n   m = deg(x);\r\n\r\n   if (i > m) {\r\n      x.rep.SetLength(i+1);\r\n      for (j = m+1; j < i; j++)\r\n         clear(x.rep[j]);\r\n   }\r\n   set(x.rep[i]);\r\n   x.normalize();\r\n}\r\n\r\n\r\nvoid SetX(GF2EX& x)\r\n{\r\n   clear(x);\r\n   SetCoeff(x, 1);\r\n}\r\n\r\n\r\nlong IsX(const GF2EX& a)\r\n{\r\n   return deg(a) == 1 && IsOne(LeadCoeff(a)) && IsZero(ConstTerm(a));\r\n}\r\n      \r\n      \r\n\r\nconst GF2E& coeff(const GF2EX& a, long i)\r\n{\r\n   if (i < 0 || i > deg(a))\r\n      return GF2E::zero();\r\n   else\r\n      return a.rep[i];\r\n}\r\n\r\n\r\nconst GF2E& LeadCoeff(const GF2EX& a)\r\n{\r\n   if (IsZero(a))\r\n      return GF2E::zero();\r\n   else\r\n      return a.rep[deg(a)];\r\n}\r\n\r\nconst GF2E& ConstTerm(const GF2EX& a)\r\n{\r\n   if (IsZero(a))\r\n      return GF2E::zero();\r\n   else\r\n      return a.rep[0];\r\n}\r\n\r\n\r\n\r\nvoid conv(GF2EX& x, const GF2E& a)\r\n{\r\n   if (IsZero(a))\r\n      x.rep.SetLength(0);\r\n   else {\r\n      x.rep.SetLength(1);\r\n      x.rep[0] = a;\r\n   }\r\n}\r\n\r\nvoid conv(GF2EX& x, long a)\r\n{\r\n   if (a & 1)\r\n      set(x);\r\n   else\r\n      clear(x);\r\n}\r\n\r\nvoid conv(GF2EX& x, GF2 a)\r\n{\r\n   if (a == 1)\r\n      set(x);\r\n   else\r\n      clear(x);\r\n}\r\n\r\nvoid conv(GF2EX& x, const ZZ& a)\r\n{\r\n   if (IsOdd(a))\r\n      set(x);\r\n   else\r\n      clear(x);\r\n}\r\n\r\nvoid conv(GF2EX& x, const GF2X& aa)\r\n{\r\n   GF2X a = aa; // in case a aliases the rep of a coefficient of x\r\n   \r\n   long n = deg(a)+1;\r\n   long i;\r\n\r\n   x.rep.SetLength(n);\r\n   for (i = 0; i < n; i++)\r\n      conv(x.rep[i], coeff(a, i));\r\n}\r\n\r\nvoid conv(GF2EX& x, const vec_GF2E& a)\r\n{\r\n   x.rep = a;\r\n   x.normalize();\r\n}\r\n\r\n\r\n\r\n/* additional legacy conversions for v6 conversion regime */\r\n\r\nvoid conv(GF2EX& x, const ZZX& a)\r\n{\r\n   long n = a.rep.length();\r\n   long i;\r\n\r\n   x.rep.SetLength(n);\r\n   for (i = 0; i < n; i++)\r\n      conv(x.rep[i], a.rep[i]);\r\n\r\n   x.normalize();\r\n}\r\n\r\n\r\n/* ------------------------------------- */\r\n\r\n\r\n\r\n\r\nvoid add(GF2EX& x, const GF2EX& a, const GF2EX& b)\r\n{\r\n   long da = deg(a);\r\n   long db = deg(b);\r\n   long minab = min(da, db);\r\n   long maxab = max(da, db);\r\n   x.rep.SetLength(maxab+1);\r\n\r\n   long i;\r\n   const GF2E *ap, *bp; \r\n   GF2E* xp;\r\n\r\n   for (i = minab+1, ap = a.rep.elts(), bp = b.rep.elts(), xp = x.rep.elts();\r\n        i; i--, ap++, bp++, xp++)\r\n      add(*xp, (*ap), (*bp));\r\n\r\n   if (da > minab && &x != &a)\r\n      for (i = da-minab; i; i--, xp++, ap++)\r\n         *xp = *ap;\r\n   else if (db > minab && &x != &b)\r\n      for (i = db-minab; i; i--, xp++, bp++)\r\n         *xp = *bp;\r\n   else\r\n      x.normalize();\r\n}\r\n\r\nvoid add(GF2EX& x, const GF2EX& a, const GF2E& b)\r\n{\r\n   long n = a.rep.length();\r\n   if (n == 0) {\r\n      conv(x, b);\r\n   }\r\n   else if (&x == &a) {\r\n      add(x.rep[0], a.rep[0], b);\r\n      x.normalize();\r\n   }\r\n   else if (x.rep.MaxLength() == 0) {\r\n      x = a;\r\n      add(x.rep[0], a.rep[0], b);\r\n      x.normalize();\r\n   }\r\n   else {\r\n      // ugly...b could alias a coeff of x\r\n\r\n      GF2E *xp = x.rep.elts();\r\n      add(xp[0], a.rep[0], b);\r\n      x.rep.SetLength(n);\r\n      xp = x.rep.elts();\r\n      const GF2E *ap = a.rep.elts();\r\n      long i;\r\n      for (i = 1; i < n; i++)\r\n         xp[i] = ap[i];\r\n      x.normalize();\r\n   }\r\n}\r\n\r\nvoid add(GF2EX& x, const GF2EX& a, GF2 b)\r\n{\r\n   if (a.rep.length() == 0) {\r\n      conv(x, b);\r\n   }\r\n   else {\r\n      if (&x != &a) x = a;\r\n      add(x.rep[0], x.rep[0], b);\r\n      x.normalize();\r\n   }\r\n}\r\n\r\nvoid add(GF2EX& x, const GF2EX& a, long b)\r\n{\r\n   if (a.rep.length() == 0) {\r\n      conv(x, b);\r\n   }\r\n   else {\r\n      if (&x != &a) x = a;\r\n      add(x.rep[0], x.rep[0], b);\r\n      x.normalize();\r\n   }\r\n}\r\n\r\n\r\nvoid PlainMul(GF2EX& x, const GF2EX& a, const GF2EX& b)\r\n{\r\n   long da = deg(a);\r\n   long db = deg(b);\r\n\r\n   if (da < 0 || db < 0) {\r\n      clear(x);\r\n      return;\r\n   }\r\n\r\n   if (&a == &b) {\r\n      sqr(x, a);\r\n      return;\r\n   }\r\n\r\n   long d = da+db;\r\n\r\n   const GF2E *ap, *bp;\r\n   GF2E *xp;\r\n   \r\n   GF2EX la, lb;\r\n\r\n   if (&x == &a) {\r\n      la = a;\r\n      ap = la.rep.elts();\r\n   }\r\n   else\r\n      ap = a.rep.elts();\r\n\r\n   if (&x == &b) {\r\n      lb = b;\r\n      bp = lb.rep.elts();\r\n   }\r\n   else\r\n      bp = b.rep.elts();\r\n\r\n   x.rep.SetLength(d+1);\r\n\r\n   xp = x.rep.elts();\r\n\r\n   long i, j, jmin, jmax;\r\n   GF2X t, accum;\r\n\r\n   for (i = 0; i <= d; i++) {\r\n      jmin = max(0, i-db);\r\n      jmax = min(da, i);\r\n      clear(accum);\r\n      for (j = jmin; j <= jmax; j++) {\r\n\t mul(t, rep(ap[j]), rep(bp[i-j]));\r\n\t add(accum, accum, t);\r\n      }\r\n      conv(xp[i], accum);\r\n   }\r\n   x.normalize();\r\n}\r\n\r\n\r\nvoid sqr(GF2EX& x, const GF2EX& a)\r\n{\r\n   long da = deg(a);\r\n\r\n   if (da < 0) {\r\n      clear(x);\r\n      return;\r\n   }\r\n\r\n   x.rep.SetLength(2*da+1);\r\n   long i;\r\n\r\n   for (i = da; i > 0; i--) {\r\n      sqr(x.rep[2*i], a.rep[i]);\r\n      clear(x.rep[2*i-1]);\r\n   }\r\n\r\n   sqr(x.rep[0], a.rep[0]);\r\n\r\n   x.normalize();\r\n}\r\n\r\n\r\n\r\nstatic \r\nvoid PlainMul1(GF2X *xp, const GF2X *ap, long sa, const GF2X& b)\r\n{\r\n   long i;\r\n\r\n   for (i = 0; i < sa; i++)\r\n      mul(xp[i], ap[i], b);\r\n}\r\n\r\n\r\n\r\n\r\nstatic inline\r\nvoid q_add(GF2X& x, const GF2X& a, const GF2X& b)\r\n\r\n// This is a quick-and-dirty add routine used by the karatsuba routine.\r\n// It assumes that the output already has enough space allocated,\r\n// thus avoiding any procedure calls.\r\n// WARNING: it also accesses the underlying WordVector representation\r\n// directly...that is dirty!.\r\n// It shaves a few percent off the running time.\r\n\r\n{\r\n   _ntl_ulong *xp = x.xrep.elts();\r\n   const _ntl_ulong *ap = a.xrep.elts();\r\n   const _ntl_ulong *bp = b.xrep.elts();\r\n\r\n   long sa = ap[-1];\r\n   long sb = bp[-1];\r\n\r\n   long i;\r\n\r\n   if (sa == sb) {\r\n      for (i = 0; i < sa; i++)\r\n         xp[i] = ap[i] ^ bp[i];\r\n\r\n      i = sa-1;\r\n      while (i >= 0 && !xp[i]) i--;\r\n      xp[-1] = i+1;\r\n   }\r\n   else if (sa < sb) {\r\n      for (i = 0; i < sa; i++)\r\n         xp[i] = ap[i] ^ bp[i];\r\n\r\n      for (; i < sb; i++)\r\n         xp[i] = bp[i];\r\n\r\n      xp[-1] = sb;\r\n   }\r\n   else { // sa > sb\r\n      for (i = 0; i < sb; i++)\r\n         xp[i] = ap[i] ^ bp[i];\r\n\r\n      for (; i < sa; i++)\r\n         xp[i] = ap[i];\r\n\r\n      xp[-1] = sa;\r\n   }\r\n}\r\n\r\n\r\nstatic inline\r\nvoid q_copy(GF2X& x, const GF2X& a)\r\n// see comments for q_add above\r\n\r\n{\r\n   _ntl_ulong *xp = x.xrep.elts();\r\n   const _ntl_ulong *ap = a.xrep.elts();\r\n\r\n   long sa = ap[-1];\r\n   long i;\r\n\r\n   for (i = 0; i < sa; i++)\r\n      xp[i] = ap[i];\r\n\r\n   xp[-1] = sa;\r\n}\r\n\r\n\r\n\r\nstatic\r\nvoid KarFold(GF2X *T, const GF2X *b, long sb, long hsa)\r\n{\r\n   long m = sb - hsa;\r\n   long i;\r\n\r\n   for (i = 0; i < m; i++)\r\n      q_add(T[i], b[i], b[hsa+i]);\r\n\r\n   for (i = m; i < hsa; i++)\r\n      q_copy(T[i], b[i]);\r\n}\r\n\r\n\r\nstatic\r\nvoid KarAdd(GF2X *T, const GF2X *b, long sb)\r\n{\r\n   long i;\r\n\r\n   for (i = 0; i < sb; i++)\r\n      q_add(T[i], T[i], b[i]);\r\n}\r\n\r\nstatic\r\nvoid KarFix(GF2X *c, const GF2X *b, long sb, long hsa)\r\n{\r\n   long i;\r\n\r\n   for (i = 0; i < hsa; i++)\r\n      q_copy(c[i], b[i]);\r\n\r\n   for (i = hsa; i < sb; i++)\r\n      q_add(c[i], c[i], b[i]);\r\n}\r\n\r\n\r\n\r\nstatic\r\nvoid KarMul(GF2X *c, const GF2X *a, \r\n            long sa, const GF2X *b, long sb, GF2X *stk)\r\n{\r\n   if (sa < sb) {\r\n      { long t = sa; sa = sb; sb = t; }\r\n      { const GF2X *t = a; a = b; b = t; }\r\n   }\r\n\r\n   if (sb == 1) {  \r\n      if (sa == 1) \r\n         mul(*c, *a, *b);\r\n      else\r\n         PlainMul1(c, a, sa, *b);\r\n\r\n      return;\r\n   }\r\n\r\n   if (sb == 2 && sa == 2) {\r\n      mul(c[0], a[0], b[0]);\r\n      mul(c[2], a[1], b[1]);\r\n      q_add(stk[0], a[0], a[1]);\r\n      q_add(stk[1], b[0], b[1]);\r\n      mul(c[1], stk[0], stk[1]);\r\n      q_add(c[1], c[1], c[0]);\r\n      q_add(c[1], c[1], c[2]);\r\n      \r\n      return;\r\n   }\r\n\r\n   long hsa = (sa + 1) >> 1;\r\n\r\n   if (hsa < sb) {\r\n      /* normal case */\r\n\r\n      long hsa2 = hsa << 1;\r\n\r\n      GF2X *T1, *T2, *T3;\r\n\r\n      T1 = stk; stk += hsa;\r\n      T2 = stk; stk += hsa;\r\n      T3 = stk; stk += hsa2 - 1;\r\n\r\n      /* compute T1 = a_lo + a_hi */\r\n\r\n      KarFold(T1, a, sa, hsa);\r\n\r\n      /* compute T2 = b_lo + b_hi */\r\n\r\n      KarFold(T2, b, sb, hsa);\r\n\r\n      /* recursively compute T3 = T1 * T2 */\r\n\r\n      KarMul(T3, T1, hsa, T2, hsa, stk);\r\n\r\n      /* recursively compute a_hi * b_hi into high part of c */\r\n      /* and subtract from T3 */\r\n\r\n      KarMul(c + hsa2, a+hsa, sa-hsa, b+hsa, sb-hsa, stk);\r\n      KarAdd(T3, c + hsa2, sa + sb - hsa2 - 1);\r\n\r\n\r\n      /* recursively compute a_lo*b_lo into low part of c */\r\n      /* and subtract from T3 */\r\n\r\n      KarMul(c, a, hsa, b, hsa, stk);\r\n      KarAdd(T3, c, hsa2 - 1);\r\n\r\n      clear(c[hsa2 - 1]);\r\n\r\n      /* finally, add T3 * X^{hsa} to c */\r\n\r\n      KarAdd(c+hsa, T3, hsa2-1);\r\n   }\r\n   else {\r\n      /* degenerate case */\r\n\r\n      GF2X *T;\r\n\r\n      T = stk; stk += hsa + sb - 1;\r\n\r\n      /* recursively compute b*a_hi into high part of c */\r\n\r\n      KarMul(c + hsa, a + hsa, sa - hsa, b, sb, stk);\r\n\r\n      /* recursively compute b*a_lo into T */\r\n\r\n      KarMul(T, a, hsa, b, sb, stk);\r\n\r\n      KarFix(c, T, hsa + sb - 1, hsa);\r\n   }\r\n}\r\n\r\nvoid ExtractBits(_ntl_ulong *cp, const _ntl_ulong *ap, long k, long n)\r\n\r\n// extract k bits from a at position n\r\n\r\n{\r\n   long sc = (k + NTL_BITS_PER_LONG-1)/NTL_BITS_PER_LONG;\r\n\r\n   long wn = n/NTL_BITS_PER_LONG;\r\n   long bn = n - wn*NTL_BITS_PER_LONG;\r\n\r\n   long i;\r\n\r\n   if (bn == 0) {\r\n      for (i = 0; i < sc; i++)\r\n         cp[i] = ap[i+wn];\r\n   }\r\n   else {\r\n      for (i = 0; i < sc-1; i++)\r\n         cp[i] = (ap[i+wn] >> bn) | (ap[i+wn+1] << (NTL_BITS_PER_LONG - bn));\r\n\r\n      if (k > sc*NTL_BITS_PER_LONG - bn) \r\n         cp[sc-1] = (ap[sc+wn-1] >> bn)|(ap[sc+wn] << (NTL_BITS_PER_LONG - bn));\r\n      else\r\n         cp[sc-1] = ap[sc+wn-1] >> bn;\r\n   }\r\n\r\n   long p = k % NTL_BITS_PER_LONG;\r\n   if (p != 0) \r\n      cp[sc-1] &= ((1UL << p) - 1UL);\r\n\r\n}\r\n\r\n\r\nvoid KronSubst(GF2X& aa, const GF2EX& a)\r\n{\r\n   long sa = a.rep.length();\r\n   long blocksz = 2*GF2E::degree() - 1;\r\n\r\n   long saa = sa*blocksz;\r\n\r\n   long wsaa = (saa + NTL_BITS_PER_LONG-1)/NTL_BITS_PER_LONG;\r\n\r\n   aa.xrep.SetLength(wsaa+1);\r\n\r\n   _ntl_ulong *paa = aa.xrep.elts();\r\n\r\n\r\n   long i;\r\n   for (i = 0; i < wsaa+1; i++)\r\n      paa[i] = 0;\r\n\r\n   for (i = 0; i < sa; i++) \r\n      ShiftAdd(paa, rep(a.rep[i]).xrep.elts(), rep(a.rep[i]).xrep.length(),\r\n               blocksz*i);\r\n\r\n   aa.normalize(); \r\n}\r\n\r\nvoid KronMul(GF2EX& x, const GF2EX& a, const GF2EX& b)\r\n{\r\n   if (a == 0 || b == 0) {\r\n      clear(x);\r\n      return;\r\n   }\r\n\r\n   GF2X aa, bb, xx;\r\n\r\n   long sx = deg(a) + deg(b) + 1;\r\n   long blocksz = 2*GF2E::degree() - 1;\r\n\r\n   if (NTL_OVERFLOW(blocksz, sx, 0))\r\n      ResourceError(\"overflow in GF2EX KronMul\");\r\n\r\n   KronSubst(aa, a);\r\n   KronSubst(bb, b);\r\n   mul(xx, aa, bb);\r\n\r\n   GF2X c;\r\n\r\n   long wc = (blocksz + NTL_BITS_PER_LONG-1)/NTL_BITS_PER_LONG;\r\n\r\n   x.rep.SetLength(sx);\r\n\r\n   long i;\r\n   for (i = 0; i < sx-1; i++) {\r\n      c.xrep.SetLength(wc);\r\n      ExtractBits(c.xrep.elts(), xx.xrep.elts(), blocksz, i*blocksz);\r\n      c.normalize();\r\n      conv(x.rep[i], c);\r\n   }\r\n\r\n   long last_blocksz = deg(xx) - (sx-1)*blocksz + 1;\r\n   wc = (last_blocksz + NTL_BITS_PER_LONG-1)/NTL_BITS_PER_LONG;\r\n   c.xrep.SetLength(wc);\r\n\r\n   ExtractBits(c.xrep.elts(), xx.xrep.elts(), last_blocksz, (sx-1)*blocksz);\r\n   c.normalize();\r\n   conv(x.rep[sx-1], c);\r\n\r\n   x.normalize();\r\n}\r\n\r\n\r\n\r\nvoid mul(GF2EX& c, const GF2EX& a, const GF2EX& b)\r\n{\r\n   if (IsZero(a) || IsZero(b)) {\r\n      clear(c);\r\n      return;\r\n   }\r\n\r\n   if (&a == &b) {\r\n      sqr(c, a);\r\n      return;\r\n   }\r\n\r\n   long sa = a.rep.length();\r\n   long sb = b.rep.length();\r\n\r\n   if (sa == 1) {\r\n      mul(c, b, a.rep[0]);\r\n      return;\r\n   }\r\n\r\n   if (sb == 1) {\r\n      mul(c, a, b.rep[0]);\r\n      return;\r\n   }\r\n\r\n   if (sa < GF2E::KarCross() || sb < GF2E::KarCross()) {\r\n      PlainMul(c, a, b);\r\n      return;\r\n   }\r\n\r\n   if (GF2E::WordLength() <= 1) {\r\n      KronMul(c, a, b);\r\n      return;\r\n   }\r\n   \r\n\r\n   /* karatsuba */\r\n\r\n   long n, hn, sp;\r\n\r\n   n = max(sa, sb);\r\n   sp = 0;\r\n   do {\r\n      hn = (n+1) >> 1;\r\n      sp += (hn << 2) - 1;\r\n      n = hn;\r\n   } while (n > 1);\r\n\r\n   GF2XVec stk;\r\n   stk.SetSize(sp + 2*(sa+sb)-1, 2*GF2E::WordLength()); \r\n\r\n   long i;\r\n\r\n   for (i = 0; i < sa; i++)\r\n      stk[i+sa+sb-1] = rep(a.rep[i]);\r\n\r\n   for (i = 0; i < sb; i++)\r\n      stk[i+2*sa+sb-1] = rep(b.rep[i]);\r\n\r\n   KarMul(&stk[0], &stk[sa+sb-1], sa, &stk[2*sa+sb-1], sb, \r\n          &stk[2*(sa+sb)-1]);\r\n\r\n   c.rep.SetLength(sa+sb-1);\r\n\r\n   for (i = 0; i < sa+sb-1; i++)\r\n      conv(c.rep[i], stk[i]);\r\n\r\n   c.normalize();\r\n}\r\n\r\n\r\nvoid MulTrunc(GF2EX& x, const GF2EX& a, const GF2EX& b, long n)\r\n{\r\n   GF2EX t;\r\n   mul(t, a, b);\r\n   trunc(x, t, n);\r\n}\r\n\r\nvoid SqrTrunc(GF2EX& x, const GF2EX& a, long n)\r\n{\r\n   GF2EX t;\r\n   sqr(t, a);\r\n   trunc(x, t, n);\r\n}\r\n\r\n\r\n\r\nvoid PlainDivRem(GF2EX& q, GF2EX& r, const GF2EX& a, const GF2EX& b)\r\n{\r\n   long da, db, dq, i, j, LCIsOne;\r\n   const GF2E *bp;\r\n   GF2E *qp;\r\n   GF2X *xp;\r\n\r\n\r\n   GF2E LCInv, t;\r\n   GF2X s;\r\n\r\n   da = deg(a);\r\n   db = deg(b);\r\n\r\n   if (db < 0) ArithmeticError(\"GF2EX: division by zero\");\r\n\r\n   if (da < db) {\r\n      r = a;\r\n      clear(q);\r\n      return;\r\n   }\r\n\r\n   GF2EX lb;\r\n\r\n   if (&q == &b) {\r\n      lb = b;\r\n      bp = lb.rep.elts();\r\n   }\r\n   else\r\n      bp = b.rep.elts();\r\n\r\n   if (IsOne(bp[db]))\r\n      LCIsOne = 1;\r\n   else {\r\n      LCIsOne = 0;\r\n      inv(LCInv, bp[db]);\r\n   }\r\n\r\n   GF2XVec x(da + 1, 2*GF2E::WordLength());\r\n\r\n   for (i = 0; i <= da; i++)\r\n      x[i] = rep(a.rep[i]);\r\n\r\n   xp = x.elts();\r\n\r\n   dq = da - db;\r\n   q.rep.SetLength(dq+1);\r\n   qp = q.rep.elts();\r\n\r\n   for (i = dq; i >= 0; i--) {\r\n      conv(t, xp[i+db]);\r\n      if (!LCIsOne)\r\n\t mul(t, t, LCInv);\r\n      qp[i] = t;\r\n\r\n      for (j = db-1; j >= 0; j--) {\r\n\t mul(s, rep(t), rep(bp[j]));\r\n\t add(xp[i+j], xp[i+j], s);\r\n      }\r\n   }\r\n\r\n   r.rep.SetLength(db);\r\n   for (i = 0; i < db; i++)\r\n      conv(r.rep[i], xp[i]);\r\n   r.normalize();\r\n}\r\n\r\n\r\nvoid PlainRem(GF2EX& r, const GF2EX& a, const GF2EX& b, GF2XVec& x)\r\n{\r\n   long da, db, dq, i, j, LCIsOne;\r\n   const GF2E *bp;\r\n   GF2X *xp;\r\n\r\n\r\n   GF2E LCInv, t;\r\n   GF2X s;\r\n\r\n   da = deg(a);\r\n   db = deg(b);\r\n\r\n   if (db < 0) ArithmeticError(\"GF2EX: division by zero\");\r\n\r\n   if (da < db) {\r\n      r = a;\r\n      return;\r\n   }\r\n\r\n   bp = b.rep.elts();\r\n\r\n   if (IsOne(bp[db]))\r\n      LCIsOne = 1;\r\n   else {\r\n      LCIsOne = 0;\r\n      inv(LCInv, bp[db]);\r\n   }\r\n\r\n   for (i = 0; i <= da; i++)\r\n      x[i] = rep(a.rep[i]);\r\n\r\n   xp = x.elts();\r\n\r\n   dq = da - db;\r\n\r\n   for (i = dq; i >= 0; i--) {\r\n      conv(t, xp[i+db]);\r\n      if (!LCIsOne)\r\n\t mul(t, t, LCInv);\r\n\r\n      for (j = db-1; j >= 0; j--) {\r\n\t mul(s, rep(t), rep(bp[j]));\r\n\t add(xp[i+j], xp[i+j], s);\r\n      }\r\n   }\r\n\r\n   r.rep.SetLength(db);\r\n   for (i = 0; i < db; i++)\r\n      conv(r.rep[i], xp[i]);\r\n   r.normalize();\r\n}\r\n\r\n\r\nvoid PlainDivRem(GF2EX& q, GF2EX& r, const GF2EX& a, const GF2EX& b, GF2XVec& x)\r\n{\r\n   long da, db, dq, i, j, LCIsOne;\r\n   const GF2E *bp;\r\n   GF2E *qp;\r\n   GF2X *xp;\r\n\r\n\r\n   GF2E LCInv, t;\r\n   GF2X s;\r\n\r\n   da = deg(a);\r\n   db = deg(b);\r\n\r\n   if (db < 0) ArithmeticError(\"GF2EX: division by zero\");\r\n\r\n   if (da < db) {\r\n      r = a;\r\n      clear(q);\r\n      return;\r\n   }\r\n\r\n   GF2EX lb;\r\n\r\n   if (&q == &b) {\r\n      lb = b;\r\n      bp = lb.rep.elts();\r\n   }\r\n   else\r\n      bp = b.rep.elts();\r\n\r\n   if (IsOne(bp[db]))\r\n      LCIsOne = 1;\r\n   else {\r\n      LCIsOne = 0;\r\n      inv(LCInv, bp[db]);\r\n   }\r\n\r\n   for (i = 0; i <= da; i++)\r\n      x[i] = rep(a.rep[i]);\r\n\r\n   xp = x.elts();\r\n\r\n   dq = da - db;\r\n   q.rep.SetLength(dq+1);\r\n   qp = q.rep.elts();\r\n\r\n   for (i = dq; i >= 0; i--) {\r\n      conv(t, xp[i+db]);\r\n      if (!LCIsOne)\r\n\t mul(t, t, LCInv);\r\n      qp[i] = t;\r\n\r\n      for (j = db-1; j >= 0; j--) {\r\n\t mul(s, rep(t), rep(bp[j]));\r\n\t add(xp[i+j], xp[i+j], s);\r\n      }\r\n   }\r\n\r\n   r.rep.SetLength(db);\r\n   for (i = 0; i < db; i++)\r\n      conv(r.rep[i], xp[i]);\r\n   r.normalize();\r\n}\r\n\r\n\r\nvoid PlainDiv(GF2EX& q, const GF2EX& a, const GF2EX& b)\r\n{\r\n   long da, db, dq, i, j, LCIsOne;\r\n   const GF2E *bp;\r\n   GF2E *qp;\r\n   GF2X *xp;\r\n\r\n\r\n   GF2E LCInv, t;\r\n   GF2X s;\r\n\r\n   da = deg(a);\r\n   db = deg(b);\r\n\r\n   if (db < 0) ArithmeticError(\"GF2EX: division by zero\");\r\n\r\n   if (da < db) {\r\n      clear(q);\r\n      return;\r\n   }\r\n\r\n   GF2EX lb;\r\n\r\n   if (&q == &b) {\r\n      lb = b;\r\n      bp = lb.rep.elts();\r\n   }\r\n   else\r\n      bp = b.rep.elts();\r\n\r\n   if (IsOne(bp[db]))\r\n      LCIsOne = 1;\r\n   else {\r\n      LCIsOne = 0;\r\n      inv(LCInv, bp[db]);\r\n   }\r\n\r\n   GF2XVec x(da + 1 - db, 2*GF2E::WordLength());\r\n\r\n   for (i = db; i <= da; i++)\r\n      x[i-db] = rep(a.rep[i]);\r\n\r\n   xp = x.elts();\r\n\r\n   dq = da - db;\r\n   q.rep.SetLength(dq+1);\r\n   qp = q.rep.elts();\r\n\r\n   for (i = dq; i >= 0; i--) {\r\n      conv(t, xp[i]);\r\n      if (!LCIsOne)\r\n\t mul(t, t, LCInv);\r\n      qp[i] = t;\r\n\r\n      long lastj = max(0, db-i);\r\n\r\n      for (j = db-1; j >= lastj; j--) {\r\n\t mul(s, rep(t), rep(bp[j]));\r\n\t add(xp[i+j-db], xp[i+j-db], s);\r\n      }\r\n   }\r\n}\r\n\r\nvoid PlainRem(GF2EX& r, const GF2EX& a, const GF2EX& b)\r\n{\r\n   long da, db, dq, i, j, LCIsOne;\r\n   const GF2E *bp;\r\n   GF2X *xp;\r\n\r\n\r\n   GF2E LCInv, t;\r\n   GF2X s;\r\n\r\n   da = deg(a);\r\n   db = deg(b);\r\n\r\n   if (db < 0) ArithmeticError(\"GF2EX: division by zero\");\r\n\r\n   if (da < db) {\r\n      r = a;\r\n      return;\r\n   }\r\n\r\n   bp = b.rep.elts();\r\n\r\n   if (IsOne(bp[db]))\r\n      LCIsOne = 1;\r\n   else {\r\n      LCIsOne = 0;\r\n      inv(LCInv, bp[db]);\r\n   }\r\n\r\n   GF2XVec x(da + 1, 2*GF2E::WordLength());\r\n\r\n   for (i = 0; i <= da; i++)\r\n      x[i] = rep(a.rep[i]);\r\n\r\n   xp = x.elts();\r\n\r\n   dq = da - db;\r\n\r\n   for (i = dq; i >= 0; i--) {\r\n      conv(t, xp[i+db]);\r\n      if (!LCIsOne)\r\n\t mul(t, t, LCInv);\r\n\r\n      for (j = db-1; j >= 0; j--) {\r\n\t mul(s, rep(t), rep(bp[j]));\r\n\t add(xp[i+j], xp[i+j], s);\r\n      }\r\n   }\r\n\r\n   r.rep.SetLength(db);\r\n   for (i = 0; i < db; i++)\r\n      conv(r.rep[i], xp[i]);\r\n   r.normalize();\r\n}\r\n\r\nvoid mul(GF2EX& x, const GF2EX& a, const GF2E& b)\r\n{\r\n   if (IsZero(a) || IsZero(b)) {\r\n      clear(x);\r\n      return;\r\n   }\r\n\r\n   GF2X bb, t;\r\n   long i, da;\r\n\r\n   const GF2E *ap;\r\n   GF2E* xp;\r\n\r\n   bb = rep(b);\r\n   da = deg(a);\r\n   x.rep.SetLength(da+1);\r\n   ap = a.rep.elts();\r\n   xp = x.rep.elts();\r\n\r\n   for (i = 0; i <= da; i++) {\r\n      mul(t, rep(ap[i]), bb);\r\n      conv(xp[i], t);\r\n   }\r\n\r\n   x.normalize();\r\n}\r\n\r\nvoid mul(GF2EX& x, const GF2EX& a, GF2 b)\r\n{\r\n   if (b == 0)\r\n      clear(x);\r\n   else\r\n      x = a;\r\n}\r\n\r\nvoid mul(GF2EX& x, const GF2EX& a, long b)\r\n{\r\n   if ((b & 1) == 0)\r\n      clear(x);\r\n   else\r\n      x = a;\r\n}\r\n\r\n\r\nvoid GCD(GF2EX& x, const GF2EX& a, const GF2EX& b)\r\n{\r\n   GF2E t;\r\n\r\n   if (IsZero(b))\r\n      x = a;\r\n   else if (IsZero(a))\r\n      x = b;\r\n   else {\r\n      long n = max(deg(a),deg(b)) + 1;\r\n      GF2EX u(INIT_SIZE, n), v(INIT_SIZE, n);\r\n      GF2XVec tmp(n, 2*GF2E::WordLength());\r\n\r\n      u = a;\r\n      v = b;\r\n      do {\r\n         PlainRem(u, u, v, tmp);\r\n         swap(u, v);\r\n      } while (!IsZero(v));\r\n\r\n      x = u;\r\n   }\r\n\r\n   if (IsZero(x)) return;\r\n   if (IsOne(LeadCoeff(x))) return;\r\n\r\n   /* make gcd monic */\r\n\r\n\r\n   inv(t, LeadCoeff(x)); \r\n   mul(x, x, t); \r\n}\r\n\r\n\r\n\r\n         \r\n\r\nvoid XGCD(GF2EX& d, GF2EX& s, GF2EX& t, const GF2EX& a, const GF2EX& b)\r\n{\r\n   GF2E z;\r\n\r\n\r\n   if (IsZero(b)) {\r\n      set(s);\r\n      clear(t);\r\n      d = a;\r\n   }\r\n   else if (IsZero(a)) {\r\n      clear(s);\r\n      set(t);\r\n      d = b;\r\n   }\r\n   else {\r\n      long e = max(deg(a), deg(b)) + 1;\r\n\r\n      GF2EX temp(INIT_SIZE, e), u(INIT_SIZE, e), v(INIT_SIZE, e), \r\n            u0(INIT_SIZE, e), v0(INIT_SIZE, e), \r\n            u1(INIT_SIZE, e), v1(INIT_SIZE, e), \r\n            u2(INIT_SIZE, e), v2(INIT_SIZE, e), q(INIT_SIZE, e);\r\n\r\n\r\n      set(u1); clear(v1);\r\n      clear(u2); set(v2);\r\n      u = a; v = b;\r\n\r\n      do {\r\n         DivRem(q, u, u, v);\r\n         swap(u, v);\r\n         u0 = u2;\r\n         v0 = v2;\r\n         mul(temp, q, u2);\r\n         add(u2, u1, temp);\r\n         mul(temp, q, v2);\r\n         add(v2, v1, temp);\r\n         u1 = u0;\r\n         v1 = v0;\r\n      } while (!IsZero(v));\r\n\r\n      d = u;\r\n      s = u1;\r\n      t = v1;\r\n   }\r\n\r\n   if (IsZero(d)) return;\r\n   if (IsOne(LeadCoeff(d))) return;\r\n\r\n   /* make gcd monic */\r\n\r\n   inv(z, LeadCoeff(d));\r\n   mul(d, d, z);\r\n   mul(s, s, z);\r\n   mul(t, t, z);\r\n}\r\n\r\n\r\nvoid MulMod(GF2EX& x, const GF2EX& a, const GF2EX& b, const GF2EX& f)\r\n{\r\n   if (deg(a) >= deg(f) || deg(b) >= deg(f) || deg(f) == 0) \r\n      LogicError(\"MulMod: bad args\");\r\n\r\n   GF2EX t;\r\n\r\n   mul(t, a, b);\r\n   rem(x, t, f);\r\n}\r\n\r\nvoid SqrMod(GF2EX& x, const GF2EX& a, const GF2EX& f)\r\n{\r\n   if (deg(a) >= deg(f) || deg(f) == 0) LogicError(\"SqrMod: bad args\");\r\n\r\n   GF2EX t;\r\n\r\n   sqr(t, a);\r\n   rem(x, t, f);\r\n}\r\n\r\n\r\nvoid InvMod(GF2EX& x, const GF2EX& a, const GF2EX& f)\r\n{\r\n   if (deg(a) >= deg(f) || deg(f) == 0) LogicError(\"InvMod: bad args\");\r\n\r\n   GF2EX d, xx, t;\r\n\r\n   XGCD(d, xx, t, a, f);\r\n   if (!IsOne(d))\r\n      InvModError(\"GF2EX InvMod: can't compute multiplicative inverse\");\r\n\r\n   x = xx;\r\n}\r\n\r\nlong InvModStatus(GF2EX& x, const GF2EX& a, const GF2EX& f)\r\n{\r\n   if (deg(a) >= deg(f) || deg(f) == 0) LogicError(\"InvModStatus: bad args\");\r\n\r\n   GF2EX d, t;\r\n\r\n   XGCD(d, x, t, a, f);\r\n   if (!IsOne(d)) {\r\n      x = d;\r\n      return 1;\r\n   }\r\n   else\r\n      return 0;\r\n}\r\n\r\n\r\n\r\n\r\nstatic\r\nvoid MulByXModAux(GF2EX& h, const GF2EX& a, const GF2EX& f)\r\n{\r\n   long i, n, m;\r\n   GF2E* hh;\r\n   const GF2E *aa, *ff;\r\n\r\n   GF2E t, z;\r\n\r\n   n = deg(f);\r\n   m = deg(a);\r\n\r\n   if (m >= n || n == 0) LogicError(\"MulByXMod: bad args\");\r\n\r\n   if (m < 0) {\r\n      clear(h);\r\n      return;\r\n   }\r\n\r\n   if (m < n-1) {\r\n      h.rep.SetLength(m+2);\r\n      hh = h.rep.elts();\r\n      aa = a.rep.elts();\r\n      for (i = m+1; i >= 1; i--)\r\n         hh[i] = aa[i-1];\r\n      clear(hh[0]);\r\n   }\r\n   else {\r\n      h.rep.SetLength(n);\r\n      hh = h.rep.elts();\r\n      aa = a.rep.elts();\r\n      ff = f.rep.elts();\r\n      z = aa[n-1];\r\n      if (!IsOne(ff[n]))\r\n         div(z, z, ff[n]);\r\n      for (i = n-1; i >= 1; i--) {\r\n         mul(t, z, ff[i]);\r\n         add(hh[i], aa[i-1], t);\r\n      }\r\n      mul(hh[0], z, ff[0]);\r\n      h.normalize();\r\n   }\r\n}\r\n\r\nvoid MulByXMod(GF2EX& h, const GF2EX& a, const GF2EX& f)\r\n{\r\n   if (&h == &f) {\r\n      GF2EX hh;\r\n      MulByXModAux(hh, a, f);\r\n      h = hh;\r\n   }\r\n   else\r\n      MulByXModAux(h, a, f);\r\n}\r\n\r\n\r\n\r\n\r\nvoid random(GF2EX& x, long n)\r\n{\r\n   long i;\r\n\r\n   x.rep.SetLength(n);\r\n\r\n   for (i = 0; i < n; i++)\r\n      random(x.rep[i]); \r\n\r\n   x.normalize();\r\n}\r\n\r\n\r\nvoid CopyReverse(GF2EX& x, const GF2EX& a, long hi)\r\n\r\n   // x[0..hi] = reverse(a[0..hi]), with zero fill\r\n   // input may not alias output\r\n\r\n{\r\n   long i, j, n, m;\r\n\r\n   n = hi+1;\r\n   m = a.rep.length();\r\n\r\n   x.rep.SetLength(n);\r\n\r\n   const GF2E* ap = a.rep.elts();\r\n   GF2E* xp = x.rep.elts();\r\n\r\n   for (i = 0; i < n; i++) {\r\n      j = hi-i;\r\n      if (j < 0 || j >= m)\r\n         clear(xp[i]);\r\n      else\r\n         xp[i] = ap[j];\r\n   }\r\n\r\n   x.normalize();\r\n} \r\n\r\n\r\n\r\nvoid trunc(GF2EX& x, const GF2EX& a, long m)\r\n\r\n// x = a % X^m, output may alias input \r\n\r\n{\r\n   if (m < 0) LogicError(\"trunc: bad args\");\r\n\r\n   if (&x == &a) {\r\n      if (x.rep.length() > m) {\r\n         x.rep.SetLength(m);\r\n         x.normalize();\r\n      }\r\n   }\r\n   else {\r\n      long n;\r\n      long i;\r\n      GF2E* xp;\r\n      const GF2E* ap;\r\n\r\n      n = min(a.rep.length(), m);\r\n      x.rep.SetLength(n);\r\n\r\n      xp = x.rep.elts();\r\n      ap = a.rep.elts();\r\n\r\n      for (i = 0; i < n; i++) xp[i] = ap[i];\r\n\r\n      x.normalize();\r\n   }\r\n}\r\n\r\nvoid NewtonInvTrunc(GF2EX& c, const GF2EX& a, long e)\r\n{\r\n   GF2E x;\r\n\r\n   inv(x, ConstTerm(a));\r\n\r\n   if (e == 1) {\r\n      conv(c, x);\r\n      return;\r\n   }\r\n\r\n   vec_long E;\r\n   E.SetLength(0);\r\n   append(E, e);\r\n   while (e > 1) {\r\n      e = (e+1)/2;\r\n      append(E, e);\r\n   }\r\n\r\n   long L = E.length();\r\n\r\n   GF2EX g, g0, g1, g2;\r\n\r\n\r\n   g.rep.SetMaxLength(E[0]);\r\n   g0.rep.SetMaxLength(E[0]);\r\n   g1.rep.SetMaxLength((3*E[0]+1)/2);\r\n   g2.rep.SetMaxLength(E[0]);\r\n\r\n   conv(g, x);\r\n\r\n   long i;\r\n\r\n   for (i = L-1; i > 0; i--) {\r\n      // lift from E[i] to E[i-1]\r\n\r\n      long k = E[i];\r\n      long l = E[i-1]-E[i];\r\n\r\n      trunc(g0, a, k+l);\r\n\r\n      mul(g1, g0, g);\r\n      RightShift(g1, g1, k);\r\n      trunc(g1, g1, l);\r\n\r\n      mul(g2, g1, g);\r\n      trunc(g2, g2, l);\r\n      LeftShift(g2, g2, k);\r\n\r\n      add(g, g, g2);\r\n   }\r\n\r\n   c = g;\r\n}\r\n\r\n\r\nvoid InvTrunc(GF2EX& c, const GF2EX& a, long e)\r\n{\r\n   if (e < 0) LogicError(\"InvTrunc: bad args\");\r\n   if (e == 0) {\r\n      clear(c);\r\n      return;\r\n   }\r\n\r\n   if (NTL_OVERFLOW(e, 1, 0))\r\n      ResourceError(\"overflow in InvTrunc\");\r\n\r\n   NewtonInvTrunc(c, a, e);\r\n}\r\n\r\n\r\n\r\nconst long GF2EX_MOD_PLAIN = 0;\r\nconst long GF2EX_MOD_MUL = 1;\r\n\r\nvoid build(GF2EXModulus& F, const GF2EX& f)\r\n{\r\n   long n = deg(f);\r\n\r\n   if (n <= 0) LogicError(\"build(GF2EXModulus,GF2EX): deg(f) <= 0\");\r\n\r\n   if (NTL_OVERFLOW(n, GF2E::degree(), 0))\r\n      ResourceError(\"build(GF2EXModulus,GF2EX): overflow\");\r\n\r\n   F.tracevec.make();\r\n\r\n   F.f = f;\r\n   F.n = n;\r\n\r\n   if (F.n < GF2E::ModCross()) {\r\n      F.method = GF2EX_MOD_PLAIN;\r\n   }\r\n   else {\r\n      F.method = GF2EX_MOD_MUL;\r\n      GF2EX P1;\r\n      GF2EX P2;\r\n\r\n      CopyReverse(P1, f, n);\r\n      InvTrunc(P2, P1, n-1);\r\n      CopyReverse(P1, P2, n-2);\r\n      trunc(F.h0, P1, n-2);\r\n      trunc(F.f0, f, n);\r\n      F.hlc = ConstTerm(P2);\r\n   }\r\n}\r\n\r\nGF2EXModulus::GF2EXModulus()\r\n{\r\n   n = -1;\r\n   method = GF2EX_MOD_PLAIN;\r\n}\r\n\r\n\r\n\r\nGF2EXModulus::GF2EXModulus(const GF2EX& ff)\r\n{\r\n   n = -1;\r\n   method = GF2EX_MOD_PLAIN;\r\n\r\n   build(*this, ff);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid UseMulRem21(GF2EX& r, const GF2EX& a, const GF2EXModulus& F)\r\n{\r\n   GF2EX P1;\r\n   GF2EX P2;\r\n\r\n   RightShift(P1, a, F.n);\r\n   mul(P2, P1, F.h0);\r\n   RightShift(P2, P2, F.n-2);\r\n   if (!IsOne(F.hlc)) mul(P1, P1, F.hlc);\r\n   add(P2, P2, P1);\r\n   mul(P1, P2, F.f0);\r\n   trunc(P1, P1, F.n);\r\n   trunc(r, a, F.n);\r\n   add(r, r, P1);\r\n}\r\n\r\nvoid UseMulDivRem21(GF2EX& q, GF2EX& r, const GF2EX& a, const GF2EXModulus& F)\r\n{\r\n   GF2EX P1;\r\n   GF2EX P2;\r\n\r\n   RightShift(P1, a, F.n);\r\n   mul(P2, P1, F.h0);\r\n   RightShift(P2, P2, F.n-2);\r\n   if (!IsOne(F.hlc)) mul(P1, P1, F.hlc);\r\n   add(P2, P2, P1);\r\n   mul(P1, P2, F.f0);\r\n   trunc(P1, P1, F.n);\r\n   trunc(r, a, F.n);\r\n   add(r, r, P1);\r\n   q = P2;\r\n}\r\n\r\nvoid UseMulDiv21(GF2EX& q, const GF2EX& a, const GF2EXModulus& F)\r\n{\r\n   GF2EX P1;\r\n   GF2EX P2;\r\n\r\n   RightShift(P1, a, F.n);\r\n   mul(P2, P1, F.h0);\r\n   RightShift(P2, P2, F.n-2);\r\n   if (!IsOne(F.hlc)) mul(P1, P1, F.hlc);\r\n   add(P2, P2, P1);\r\n   q = P2;\r\n\r\n}\r\n\r\nvoid rem(GF2EX& x, const GF2EX& a, const GF2EXModulus& F)\r\n{\r\n   if (F.method == GF2EX_MOD_PLAIN) {\r\n      PlainRem(x, a, F.f);\r\n      return;\r\n   }\r\n\r\n   long da = deg(a);\r\n   long n = F.n;\r\n\r\n   if (da <= 2*n-2) {\r\n      UseMulRem21(x, a, F);\r\n      return;\r\n   }\r\n\r\n   GF2EX buf(INIT_SIZE, 2*n-1);\r\n\r\n   long a_len = da+1;\r\n\r\n   while (a_len > 0) {\r\n      long old_buf_len = buf.rep.length();\r\n      long amt = min(2*n-1-old_buf_len, a_len);\r\n\r\n      buf.rep.SetLength(old_buf_len+amt);\r\n\r\n      long i;\r\n\r\n      for (i = old_buf_len+amt-1; i >= amt; i--)\r\n         buf.rep[i] = buf.rep[i-amt];\r\n\r\n      for (i = amt-1; i >= 0; i--)\r\n         buf.rep[i] = a.rep[a_len-amt+i];\r\n\r\n      buf.normalize();\r\n\r\n      UseMulRem21(buf, buf, F);\r\n\r\n      a_len -= amt;\r\n   }\r\n\r\n   x = buf;\r\n}\r\n\r\nvoid DivRem(GF2EX& q, GF2EX& r, const GF2EX& a, const GF2EXModulus& F)\r\n{\r\n   if (F.method == GF2EX_MOD_PLAIN) {\r\n      PlainDivRem(q, r, a, F.f);\r\n      return;\r\n   }\r\n\r\n   long da = deg(a);\r\n   long n = F.n;\r\n\r\n   if (da <= 2*n-2) {\r\n      UseMulDivRem21(q, r, a, F);\r\n      return;\r\n   }\r\n\r\n   GF2EX buf(INIT_SIZE, 2*n-1);\r\n   GF2EX qbuf(INIT_SIZE, n-1);\r\n\r\n   GF2EX qq;\r\n   qq.rep.SetLength(da-n+1);\r\n\r\n   long a_len = da+1;\r\n   long q_hi = da-n+1;\r\n\r\n   while (a_len > 0) {\r\n      long old_buf_len = buf.rep.length();\r\n      long amt = min(2*n-1-old_buf_len, a_len);\r\n\r\n      buf.rep.SetLength(old_buf_len+amt);\r\n\r\n      long i;\r\n\r\n      for (i = old_buf_len+amt-1; i >= amt; i--)\r\n         buf.rep[i] = buf.rep[i-amt];\r\n\r\n      for (i = amt-1; i >= 0; i--)\r\n         buf.rep[i] = a.rep[a_len-amt+i];\r\n\r\n      buf.normalize();\r\n\r\n      UseMulDivRem21(qbuf, buf, buf, F);\r\n      long dl = qbuf.rep.length();\r\n      a_len = a_len - amt;\r\n      for(i = 0; i < dl; i++)\r\n         qq.rep[a_len+i] = qbuf.rep[i];\r\n      for(i = dl+a_len; i < q_hi; i++)\r\n         clear(qq.rep[i]);\r\n      q_hi = a_len;\r\n   }\r\n\r\n   r = buf;\r\n\r\n   qq.normalize();\r\n   q = qq;\r\n}\r\n\r\nvoid div(GF2EX& q, const GF2EX& a, const GF2EXModulus& F)\r\n{\r\n   if (F.method == GF2EX_MOD_PLAIN) {\r\n      PlainDiv(q, a, F.f);\r\n      return;\r\n   }\r\n\r\n   long da = deg(a);\r\n   long n = F.n;\r\n\r\n   if (da <= 2*n-2) {\r\n      UseMulDiv21(q, a, F);\r\n      return;\r\n   }\r\n\r\n   GF2EX buf(INIT_SIZE, 2*n-1);\r\n   GF2EX qbuf(INIT_SIZE, n-1);\r\n\r\n   GF2EX qq;\r\n   qq.rep.SetLength(da-n+1);\r\n\r\n   long a_len = da+1;\r\n   long q_hi = da-n+1;\r\n\r\n   while (a_len > 0) {\r\n      long old_buf_len = buf.rep.length();\r\n      long amt = min(2*n-1-old_buf_len, a_len);\r\n\r\n      buf.rep.SetLength(old_buf_len+amt);\r\n\r\n      long i;\r\n\r\n      for (i = old_buf_len+amt-1; i >= amt; i--)\r\n         buf.rep[i] = buf.rep[i-amt];\r\n\r\n      for (i = amt-1; i >= 0; i--)\r\n         buf.rep[i] = a.rep[a_len-amt+i];\r\n\r\n      buf.normalize();\r\n\r\n      a_len = a_len - amt;\r\n      if (a_len > 0)\r\n         UseMulDivRem21(qbuf, buf, buf, F);\r\n      else\r\n         UseMulDiv21(qbuf, buf, F);\r\n\r\n      long dl = qbuf.rep.length();\r\n      for(i = 0; i < dl; i++)\r\n         qq.rep[a_len+i] = qbuf.rep[i];\r\n      for(i = dl+a_len; i < q_hi; i++)\r\n         clear(qq.rep[i]);\r\n      q_hi = a_len;\r\n   }\r\n\r\n   qq.normalize();\r\n   q = qq;\r\n}\r\n\r\n\r\n\r\n\r\nvoid MulMod(GF2EX& c, const GF2EX& a, const GF2EX& b, const GF2EXModulus& F)\r\n{\r\n   if (deg(a) >= F.n || deg(b) >= F.n) LogicError(\"MulMod: bad args\");\r\n\r\n   GF2EX t;\r\n   mul(t, a, b);\r\n   rem(c, t, F);\r\n}\r\n\r\n\r\nvoid SqrMod(GF2EX& c, const GF2EX& a, const GF2EXModulus& F)\r\n{\r\n   if (deg(a) >= F.n) LogicError(\"MulMod: bad args\");\r\n\r\n   GF2EX t;\r\n   sqr(t, a);\r\n   rem(c, t, F);\r\n}\r\n\r\n\r\n\r\nstatic\r\nlong OptWinSize(long n)\r\n// finds k that minimizes n/(k+1) + 2^{k-1}\r\n\r\n{\r\n   long k;\r\n   double v, v_new;\r\n\r\n\r\n   v = n/2.0 + 1.0;\r\n   k = 1;\r\n\r\n   for (;;) {\r\n      v_new = n/(double(k+2)) + double(1L << k);\r\n      if (v_new >= v) break;\r\n      v = v_new;\r\n      k++;\r\n   }\r\n\r\n   return k;\r\n}\r\n      \r\n\r\n\r\nvoid PowerMod(GF2EX& h, const GF2EX& g, const ZZ& e, const GF2EXModulus& F)\r\n// h = g^e mod f using \"sliding window\" algorithm\r\n{\r\n   if (deg(g) >= F.n) LogicError(\"PowerMod: bad args\");\r\n\r\n   if (e == 0) {\r\n      set(h);\r\n      return;\r\n   }\r\n\r\n   if (e == 1) {\r\n      h = g;\r\n      return;\r\n   }\r\n\r\n   if (e == -1) {\r\n      InvMod(h, g, F);\r\n      return;\r\n   }\r\n\r\n   if (e == 2) {\r\n      SqrMod(h, g, F);\r\n      return;\r\n   }\r\n\r\n   if (e == -2) {\r\n      SqrMod(h, g, F);\r\n      InvMod(h, h, F);\r\n      return;\r\n   }\r\n\r\n\r\n   long n = NumBits(e);\r\n\r\n   GF2EX res;\r\n   res.SetMaxLength(F.n);\r\n   set(res);\r\n\r\n   long i;\r\n\r\n   if (n < 16) {\r\n      // plain square-and-multiply algorithm\r\n\r\n      for (i = n - 1; i >= 0; i--) {\r\n         SqrMod(res, res, F);\r\n         if (bit(e, i))\r\n            MulMod(res, res, g, F);\r\n      }\r\n\r\n      if (e < 0) InvMod(res, res, F);\r\n\r\n      h = res;\r\n      return;\r\n   }\r\n\r\n   long k = OptWinSize(n);\r\n   k = min(k, 5);\r\n\r\n   vec_GF2EX v;\r\n\r\n   v.SetLength(1L << (k-1));\r\n\r\n   v[0] = g;\r\n \r\n   if (k > 1) {\r\n      GF2EX t;\r\n      SqrMod(t, g, F);\r\n\r\n      for (i = 1; i < (1L << (k-1)); i++)\r\n         MulMod(v[i], v[i-1], t, F);\r\n   }\r\n\r\n\r\n   long val;\r\n   long cnt;\r\n   long m;\r\n\r\n   val = 0;\r\n   for (i = n-1; i >= 0; i--) {\r\n      val = (val << 1) | bit(e, i); \r\n      if (val == 0)\r\n         SqrMod(res, res, F);\r\n      else if (val >= (1L << (k-1)) || i == 0) {\r\n         cnt = 0;\r\n         while ((val & 1) == 0) {\r\n            val = val >> 1;\r\n            cnt++;\r\n         }\r\n\r\n         m = val;\r\n         while (m > 0) {\r\n            SqrMod(res, res, F);\r\n            m = m >> 1;\r\n         }\r\n\r\n         MulMod(res, res, v[val >> 1], F);\r\n\r\n         while (cnt > 0) {\r\n            SqrMod(res, res, F);\r\n            cnt--;\r\n         }\r\n\r\n         val = 0;\r\n      }\r\n   }\r\n\r\n   if (e < 0) InvMod(res, res, F);\r\n\r\n   h = res;\r\n}\r\n\r\n   \r\n\r\n\r\nvoid PowerXMod(GF2EX& hh, const ZZ& e, const GF2EXModulus& F)\r\n{\r\n   if (F.n < 0) LogicError(\"PowerXMod: uninitialized modulus\");\r\n\r\n   if (IsZero(e)) {\r\n      set(hh);\r\n      return;\r\n   }\r\n\r\n   long n = NumBits(e);\r\n   long i;\r\n\r\n   GF2EX h;\r\n\r\n   h.SetMaxLength(F.n+1);\r\n   set(h);\r\n\r\n   for (i = n - 1; i >= 0; i--) {\r\n      SqrMod(h, h, F);\r\n      if (bit(e, i)) {\r\n         MulByXMod(h, h, F.f);\r\n      }\r\n   }\r\n\r\n   if (e < 0) InvMod(h, h, F);\r\n\r\n   hh = h;\r\n}\r\n\r\n\r\n      \r\n\r\n\r\nvoid UseMulRem(GF2EX& r, const GF2EX& a, const GF2EX& b)\r\n{\r\n   GF2EX P1;\r\n   GF2EX P2;\r\n\r\n   long da = deg(a);\r\n   long db = deg(b);\r\n\r\n   CopyReverse(P1, b, db);\r\n   InvTrunc(P2, P1, da-db+1);\r\n   CopyReverse(P1, P2, da-db);\r\n\r\n   RightShift(P2, a, db);\r\n   mul(P2, P1, P2);\r\n   RightShift(P2, P2, da-db);\r\n   mul(P1, P2, b);\r\n   add(P1, P1, a);\r\n   \r\n   r = P1;\r\n}\r\n\r\nvoid UseMulDivRem(GF2EX& q, GF2EX& r, const GF2EX& a, const GF2EX& b)\r\n{\r\n   GF2EX P1;\r\n   GF2EX P2;\r\n\r\n   long da = deg(a);\r\n   long db = deg(b);\r\n\r\n   CopyReverse(P1, b, db);\r\n   InvTrunc(P2, P1, da-db+1);\r\n   CopyReverse(P1, P2, da-db);\r\n\r\n   RightShift(P2, a, db);\r\n   mul(P2, P1, P2);\r\n   RightShift(P2, P2, da-db);\r\n   mul(P1, P2, b);\r\n   add(P1, P1, a);\r\n   \r\n   r = P1;\r\n   q = P2;\r\n}\r\n\r\nvoid UseMulDiv(GF2EX& q, const GF2EX& a, const GF2EX& b)\r\n{\r\n   GF2EX P1;\r\n   GF2EX P2;\r\n\r\n   long da = deg(a);\r\n   long db = deg(b);\r\n\r\n   CopyReverse(P1, b, db);\r\n   InvTrunc(P2, P1, da-db+1);\r\n   CopyReverse(P1, P2, da-db);\r\n\r\n   RightShift(P2, a, db);\r\n   mul(P2, P1, P2);\r\n   RightShift(P2, P2, da-db);\r\n   \r\n   q = P2;\r\n}\r\n\r\n\r\n\r\nvoid DivRem(GF2EX& q, GF2EX& r, const GF2EX& a, const GF2EX& b)\r\n{\r\n   long sa = a.rep.length();\r\n   long sb = b.rep.length();\r\n\r\n   if (sb < GF2E::DivCross() || sa-sb < GF2E::DivCross())\r\n      PlainDivRem(q, r, a, b);\r\n   else if (sa < 4*sb)\r\n      UseMulDivRem(q, r, a, b);\r\n   else {\r\n      GF2EXModulus B;\r\n      build(B, b);\r\n      DivRem(q, r, a, B);\r\n   }\r\n}\r\n\r\nvoid div(GF2EX& q, const GF2EX& a, const GF2EX& b)\r\n{\r\n   long sa = a.rep.length();\r\n   long sb = b.rep.length();\r\n\r\n   if (sb < GF2E::DivCross() || sa-sb < GF2E::DivCross())\r\n      PlainDiv(q, a, b);\r\n   else if (sa < 4*sb)\r\n      UseMulDiv(q, a, b);\r\n   else {\r\n      GF2EXModulus B;\r\n      build(B, b);\r\n      div(q, a, B);\r\n   }\r\n}\r\n\r\nvoid div(GF2EX& q, const GF2EX& a, const GF2E& b)\r\n{\r\n   GF2E t;\r\n   inv(t, b);\r\n   mul(q, a, t);\r\n}\r\n\r\nvoid div(GF2EX& q, const GF2EX& a, GF2 b)\r\n{\r\n   if (b == 0)\r\n      ArithmeticError(\"div: division by zero\");\r\n\r\n   q = a;\r\n}\r\n\r\nvoid div(GF2EX& q, const GF2EX& a, long b)\r\n{\r\n   if ((b & 1) == 0)\r\n      ArithmeticError(\"div: division by zero\");\r\n\r\n   q = a;\r\n}\r\n   \r\n\r\n\r\nvoid rem(GF2EX& r, const GF2EX& a, const GF2EX& b)\r\n{\r\n   long sa = a.rep.length();\r\n   long sb = b.rep.length();\r\n\r\n   if (sb < GF2E::DivCross() || sa-sb < GF2E::DivCross())\r\n      PlainRem(r, a, b);\r\n   else if (sa < 4*sb)\r\n      UseMulRem(r, a, b);\r\n   else {\r\n      GF2EXModulus B;\r\n      build(B, b);\r\n      rem(r, a, B);\r\n   }\r\n}\r\n\r\n\r\nvoid diff(GF2EX& x, const GF2EX& a)\r\n{\r\n   long n = deg(a);\r\n   long i;\r\n\r\n   if (n <= 0) {\r\n      clear(x);\r\n      return;\r\n   }\r\n\r\n   if (&x != &a)\r\n      x.rep.SetLength(n);\r\n\r\n   for (i = 0; i <= n-1; i++) {\r\n      if ((i+1)&1)\r\n         x.rep[i] = a.rep[i+1];\r\n      else\r\n         clear(x.rep[i]);\r\n   }\r\n\r\n   if (&x == &a)\r\n      x.rep.SetLength(n);\r\n\r\n   x.normalize();\r\n}\r\n\r\n\r\nvoid RightShift(GF2EX& x, const GF2EX& a, long n)\r\n{\r\n   if (IsZero(a)) {\r\n      clear(x);\r\n      return;\r\n   }\r\n\r\n   if (n < 0) {\r\n      if (n < -NTL_MAX_LONG) ResourceError(\"overflow in RightShift\");\r\n      LeftShift(x, a, -n);\r\n      return;\r\n   }\r\n\r\n   long da = deg(a);\r\n   long i;\r\n \r\n   if (da < n) {\r\n      clear(x);\r\n      return;\r\n   }\r\n\r\n   if (&x != &a)\r\n      x.rep.SetLength(da-n+1);\r\n\r\n   for (i = 0; i <= da-n; i++)\r\n      x.rep[i] = a.rep[i+n];\r\n\r\n   if (&x == &a)\r\n      x.rep.SetLength(da-n+1);\r\n\r\n   x.normalize();\r\n}\r\n\r\nvoid LeftShift(GF2EX& x, const GF2EX& a, long n)\r\n{\r\n   if (IsZero(a)) {\r\n      clear(x);\r\n      return;\r\n   }\r\n\r\n   if (n < 0) {\r\n      if (n < -NTL_MAX_LONG) \r\n         clear(x);\r\n      else\r\n         RightShift(x, a, -n);\r\n      return;\r\n   }\r\n\r\n   if (NTL_OVERFLOW(n, 1, 0))\r\n      ResourceError(\"overflow in LeftShift\");\r\n\r\n   long m = a.rep.length();\r\n\r\n   x.rep.SetLength(m+n);\r\n\r\n   long i;\r\n   for (i = m-1; i >= 0; i--)\r\n      x.rep[i+n] = a.rep[i];\r\n\r\n   for (i = 0; i < n; i++)\r\n      clear(x.rep[i]);\r\n}\r\n\r\n\r\nvoid ShiftAdd(GF2EX& U, const GF2EX& V, long n)\r\n// assumes input does not alias output\r\n{\r\n   if (IsZero(V))\r\n      return;\r\n\r\n   long du = deg(U);\r\n   long dv = deg(V);\r\n\r\n   long d = max(du, n+dv);\r\n\r\n   U.rep.SetLength(d+1);\r\n   long i;\r\n\r\n   for (i = du+1; i <= d; i++)\r\n      clear(U.rep[i]);\r\n\r\n   for (i = 0; i <= dv; i++)\r\n      add(U.rep[i+n], U.rep[i+n], V.rep[i]);\r\n\r\n   U.normalize();\r\n}\r\n\r\n\r\nvoid IterBuild(GF2E* a, long n)\r\n{\r\n   long i, k;\r\n   GF2E b, t;\r\n\r\n   if (n <= 0) return;\r\n\r\n   for (k = 1; k <= n-1; k++) {\r\n      b = a[k];\r\n      add(a[k], b, a[k-1]);\r\n      for (i = k-1; i >= 1; i--) {\r\n         mul(t, a[i], b);\r\n         add(a[i], t, a[i-1]);\r\n      }\r\n      mul(a[0], a[0], b);\r\n   }\r\n} \r\n\r\n\r\n\r\nvoid BuildFromRoots(GF2EX& x, const vec_GF2E& a)\r\n{\r\n   long n = a.length();\r\n\r\n   if (n == 0) {\r\n      set(x);\r\n      return;\r\n   }\r\n\r\n   x.rep.SetMaxLength(n+1);\r\n   x.rep = a;\r\n   IterBuild(&x.rep[0], n);\r\n   x.rep.SetLength(n+1);\r\n   SetCoeff(x, n);\r\n}\r\n\r\n\r\n\r\nvoid eval(GF2E& b, const GF2EX& f, const GF2E& a)\r\n// does a Horner evaluation\r\n{\r\n   GF2E acc;\r\n   long i;\r\n\r\n   clear(acc);\r\n   for (i = deg(f); i >= 0; i--) {\r\n      mul(acc, acc, a);\r\n      add(acc, acc, f.rep[i]);\r\n   }\r\n\r\n   b = acc;\r\n}\r\n\r\n\r\n\r\nvoid eval(vec_GF2E& b, const GF2EX& f, const vec_GF2E& a)\r\n// naive algorithm:  repeats Horner\r\n{\r\n   if (&b == &f.rep) {\r\n      vec_GF2E bb;\r\n      eval(bb, f, a);\r\n      b = bb;\r\n      return;\r\n   }\r\n\r\n   long m = a.length();\r\n   b.SetLength(m);\r\n   long i;\r\n   for (i = 0; i < m; i++) \r\n      eval(b[i], f, a[i]);\r\n}\r\n\r\n\r\n\r\n\r\nvoid interpolate(GF2EX& f, const vec_GF2E& a, const vec_GF2E& b)\r\n{\r\n   long m = a.length();\r\n   if (b.length() != m) LogicError(\"interpolate: vector length mismatch\");\r\n\r\n   if (m == 0) {\r\n      clear(f);\r\n      return;\r\n   }\r\n\r\n   vec_GF2E prod;\r\n   prod = a;\r\n\r\n   GF2E t1, t2;\r\n\r\n   long k, i;\r\n\r\n   vec_GF2E res;\r\n   res.SetLength(m);\r\n\r\n   for (k = 0; k < m; k++) {\r\n\r\n      const GF2E& aa = a[k];\r\n\r\n      set(t1);\r\n      for (i = k-1; i >= 0; i--) {\r\n         mul(t1, t1, aa);\r\n         add(t1, t1, prod[i]);\r\n      }\r\n\r\n      clear(t2);\r\n      for (i = k-1; i >= 0; i--) {\r\n         mul(t2, t2, aa);\r\n         add(t2, t2, res[i]);\r\n      }\r\n\r\n\r\n      inv(t1, t1);\r\n      sub(t2, b[k], t2);\r\n      mul(t1, t1, t2);\r\n\r\n      for (i = 0; i < k; i++) {\r\n         mul(t2, prod[i], t1);\r\n         add(res[i], res[i], t2);\r\n      }\r\n\r\n      res[k] = t1;\r\n\r\n      if (k < m-1) {\r\n         if (k == 0)\r\n            negate(prod[0], prod[0]);\r\n         else {\r\n            negate(t1, a[k]);\r\n            add(prod[k], t1, prod[k-1]);\r\n            for (i = k-1; i >= 1; i--) {\r\n               mul(t2, prod[i], t1);\r\n               add(prod[i], t2, prod[i-1]);\r\n            }\r\n            mul(prod[0], prod[0], t1);\r\n         }\r\n      }\r\n   }\r\n\r\n   while (m > 0 && IsZero(res[m-1])) m--;\r\n   res.SetLength(m);\r\n   f.rep = res;\r\n}\r\n\r\n   \r\nvoid InnerProduct(GF2EX& x, const vec_GF2E& v, long low, long high, \r\n                   const vec_GF2EX& H, long n, GF2XVec& t)\r\n{\r\n   GF2X s;\r\n   long i, j;\r\n\r\n   for (j = 0; j < n; j++)\r\n      clear(t[j]);\r\n\r\n   high = min(high, v.length()-1);\r\n   for (i = low; i <= high; i++) {\r\n      const vec_GF2E& h = H[i-low].rep;\r\n      long m = h.length();\r\n      const GF2X& w = rep(v[i]);\r\n\r\n      for (j = 0; j < m; j++) {\r\n         mul(s, w, rep(h[j]));\r\n         add(t[j], t[j], s);\r\n      }\r\n   }\r\n\r\n   x.rep.SetLength(n);\r\n   for (j = 0; j < n; j++)\r\n      conv(x.rep[j], t[j]);\r\n   x.normalize();\r\n}\r\n\r\n\r\nvoid CompMod(GF2EX& x, const GF2EX& g, const GF2EXArgument& A, \r\n             const GF2EXModulus& F)\r\n{\r\n   if (deg(g) <= 0) {\r\n      x = g;\r\n      return;\r\n   }\r\n\r\n\r\n   GF2EX s, t;\r\n   GF2XVec scratch(F.n, 2*GF2E::WordLength());\r\n\r\n   long m = A.H.length() - 1;\r\n   long l = ((g.rep.length()+m-1)/m) - 1;\r\n\r\n   const GF2EX& M = A.H[m];\r\n\r\n   InnerProduct(t, g.rep, l*m, l*m + m - 1, A.H, F.n, scratch);\r\n   for (long i = l-1; i >= 0; i--) {\r\n      InnerProduct(s, g.rep, i*m, i*m + m - 1, A.H, F.n, scratch);\r\n      MulMod(t, t, M, F);\r\n      add(t, t, s);\r\n   }\r\n\r\n   x = t;\r\n}\r\n\r\n\r\nvoid build(GF2EXArgument& A, const GF2EX& h, const GF2EXModulus& F, long m)\r\n{\r\n   long i;\r\n\r\n   if (m <= 0 || deg(h) >= F.n)\r\n      LogicError(\"build GF2EXArgument: bad args\");\r\n\r\n   if (m > F.n) m = F.n;\r\n\r\n   if (GF2EXArgBound > 0) {\r\n      double sz = GF2E::storage();\r\n      sz = sz*F.n;\r\n      sz = sz + NTL_VECTOR_HEADER_SIZE + sizeof(vec_GF2E);\r\n      sz = sz/1024;\r\n      m = min(m, long(GF2EXArgBound/sz));\r\n      m = max(m, 1);\r\n   }\r\n\r\n   A.H.SetLength(m+1);\r\n\r\n   set(A.H[0]);\r\n   A.H[1] = h;\r\n   for (i = 2; i <= m; i++) \r\n      MulMod(A.H[i], A.H[i-1], h, F);\r\n}\r\n\r\n\r\n\r\n\r\nNTL_THREAD_LOCAL\r\nlong GF2EXArgBound = 0;\r\n\r\n\r\nvoid CompMod(GF2EX& x, const GF2EX& g, const GF2EX& h, const GF2EXModulus& F)\r\n   // x = g(h) mod f\r\n{\r\n   long m = SqrRoot(g.rep.length());\r\n\r\n   if (m == 0) {\r\n      clear(x);\r\n      return;\r\n   }\r\n\r\n   GF2EXArgument A;\r\n\r\n   build(A, h, F, m);\r\n\r\n   CompMod(x, g, A, F);\r\n}\r\n\r\n\r\n\r\n\r\nvoid Comp2Mod(GF2EX& x1, GF2EX& x2, const GF2EX& g1, const GF2EX& g2,\r\n              const GF2EX& h, const GF2EXModulus& F)\r\n\r\n{\r\n   long m = SqrRoot(g1.rep.length() + g2.rep.length());\r\n\r\n   if (m == 0) {\r\n      clear(x1);\r\n      clear(x2);\r\n      return;\r\n   }\r\n\r\n   GF2EXArgument A;\r\n\r\n   build(A, h, F, m);\r\n\r\n   GF2EX xx1, xx2;\r\n\r\n   CompMod(xx1, g1, A, F);\r\n   CompMod(xx2, g2, A, F);\r\n\r\n   x1 = xx1;\r\n   x2 = xx2;\r\n}\r\n\r\nvoid Comp3Mod(GF2EX& x1, GF2EX& x2, GF2EX& x3, \r\n              const GF2EX& g1, const GF2EX& g2, const GF2EX& g3,\r\n              const GF2EX& h, const GF2EXModulus& F)\r\n\r\n{\r\n   long m = SqrRoot(g1.rep.length() + g2.rep.length() + g3.rep.length());\r\n\r\n   if (m == 0) {\r\n      clear(x1);\r\n      clear(x2);\r\n      clear(x3);\r\n      return;\r\n   }\r\n\r\n   GF2EXArgument A;\r\n\r\n   build(A, h, F, m);\r\n\r\n   GF2EX xx1, xx2, xx3;\r\n\r\n   CompMod(xx1, g1, A, F);\r\n   CompMod(xx2, g2, A, F);\r\n   CompMod(xx3, g3, A, F);\r\n\r\n   x1 = xx1;\r\n   x2 = xx2;\r\n   x3 = xx3;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid build(GF2EXTransMultiplier& B, const GF2EX& b, const GF2EXModulus& F)\r\n{\r\n   long db = deg(b);\r\n\r\n   if (db >= F.n) LogicError(\"build TransMultiplier: bad args\");\r\n\r\n   GF2EX t;\r\n\r\n   LeftShift(t, b, F.n-1);\r\n   div(t, t, F);\r\n\r\n   // we optimize for low degree b\r\n\r\n   long d;\r\n\r\n   d = deg(t);\r\n   if (d < 0)\r\n      B.shamt_fbi = 0;\r\n   else\r\n      B.shamt_fbi = F.n-2 - d; \r\n\r\n   CopyReverse(B.fbi, t, d);\r\n\r\n   // The following code optimizes the case when \r\n   // f = X^n + low degree poly\r\n\r\n   trunc(t, F.f, F.n);\r\n   d = deg(t);\r\n   if (d < 0)\r\n      B.shamt = 0;\r\n   else\r\n      B.shamt = d;\r\n\r\n   CopyReverse(B.f0, t, d);\r\n\r\n   if (db < 0)\r\n      B.shamt_b = 0;\r\n   else\r\n      B.shamt_b = db;\r\n\r\n   CopyReverse(B.b, b, db);\r\n}\r\n\r\nvoid TransMulMod(GF2EX& x, const GF2EX& a, const GF2EXTransMultiplier& B,\r\n               const GF2EXModulus& F)\r\n{\r\n   if (deg(a) >= F.n) LogicError(\"TransMulMod: bad args\");\r\n\r\n   GF2EX t1, t2;\r\n\r\n   mul(t1, a, B.b);\r\n   RightShift(t1, t1, B.shamt_b);\r\n\r\n   mul(t2, a, B.f0);\r\n   RightShift(t2, t2, B.shamt);\r\n   trunc(t2, t2, F.n-1);\r\n\r\n   mul(t2, t2, B.fbi);\r\n   if (B.shamt_fbi > 0) LeftShift(t2, t2, B.shamt_fbi);\r\n   trunc(t2, t2, F.n-1);\r\n   LeftShift(t2, t2, 1);\r\n\r\n   add(x, t1, t2);\r\n}\r\n\r\n\r\nvoid UpdateMap(vec_GF2E& x, const vec_GF2E& a, \r\n         const GF2EXTransMultiplier& B, const GF2EXModulus& F)\r\n{\r\n   GF2EX xx;\r\n   TransMulMod(xx, to_GF2EX(a), B, F);\r\n   x = xx.rep;\r\n}\r\n   \r\n\r\n\r\nstatic\r\nvoid ProjectPowers(vec_GF2E& x, const GF2EX& a, long k, \r\n                   const GF2EXArgument& H, const GF2EXModulus& F)\r\n{\r\n   if (k < 0 || deg(a) >= F.n) \r\n      LogicError(\"ProjectPowers: bad args\");\r\n\r\n   if (NTL_OVERFLOW(k, 1, 0)) \r\n      ResourceError(\"ProjectPowers: excessive args\");\r\n\r\n   long m = H.H.length()-1;\r\n   long l = (k+m-1)/m - 1;\r\n\r\n   GF2EXTransMultiplier M;\r\n   build(M, H.H[m], F);\r\n\r\n   GF2EX s;\r\n   s = a;\r\n\r\n   x.SetLength(k);\r\n\r\n   long i;\r\n\r\n   for (i = 0; i <= l; i++) {\r\n      long m1 = min(m, k-i*m);\r\n      for (long j = 0; j < m1; j++)\r\n         InnerProduct(x[i*m+j], H.H[j].rep, s.rep);\r\n      if (i < l)\r\n         TransMulMod(s, s, M, F);\r\n   }\r\n}\r\n\r\nstatic\r\nvoid ProjectPowers(vec_GF2E& x, const GF2EX& a, long k, const GF2EX& h, \r\n                   const GF2EXModulus& F)\r\n{\r\n   if (k < 0 || deg(a) >= F.n || deg(h) >= F.n)\r\n      LogicError(\"ProjectPowers: bad args\");\r\n\r\n   if (k == 0) {\r\n      x.SetLength(0);;\r\n      return;\r\n   }\r\n\r\n   long m = SqrRoot(k);\r\n\r\n   GF2EXArgument H;\r\n   build(H, h, F, m);\r\n\r\n   ProjectPowers(x, a, k, H, F);\r\n}\r\n\r\nvoid ProjectPowers(vec_GF2E& x, const vec_GF2E& a, long k,\r\n                   const GF2EXArgument& H, const GF2EXModulus& F)\r\n{\r\n   ProjectPowers(x, to_GF2EX(a), k, H, F);\r\n}\r\n\r\nvoid ProjectPowers(vec_GF2E& x, const vec_GF2E& a, long k, \r\n                   const GF2EX& h, const GF2EXModulus& F)\r\n{\r\n   ProjectPowers(x, to_GF2EX(a), k, h, F);\r\n}\r\n\r\n\r\n\r\n\r\nvoid BerlekampMassey(GF2EX& h, const vec_GF2E& a, long m)\r\n{\r\n   GF2EX Lambda, Sigma, Temp;\r\n   long L;\r\n   GF2E Delta, Delta1, t1;\r\n   long shamt;\r\n   GF2X tt1, tt2;\r\n\r\n   // cerr << \"*** \" << m << \"\\n\";\r\n\r\n   Lambda.SetMaxLength(m+1);\r\n   Sigma.SetMaxLength(m+1);\r\n   Temp.SetMaxLength(m+1);\r\n\r\n   L = 0;\r\n   set(Lambda);\r\n   clear(Sigma);\r\n   set(Delta);\r\n   shamt = 0;\r\n\r\n   long i, r, dl;\r\n\r\n   for (r = 1; r <= 2*m; r++) {\r\n      // cerr << r << \"--\";\r\n      clear(tt1);\r\n      dl = deg(Lambda);\r\n      for (i = 0; i <= dl; i++) {\r\n         mul(tt2, rep(Lambda.rep[i]), rep(a[r-i-1]));\r\n         add(tt1, tt1, tt2);\r\n      }\r\n\r\n      conv(Delta1, tt1);\r\n\r\n      if (IsZero(Delta1)) {\r\n         shamt++;\r\n         // cerr << \"case 1: \" << deg(Lambda) << \" \" << deg(Sigma) << \" \" << shamt << \"\\n\";\r\n      }\r\n      else if (2*L < r) {\r\n         div(t1, Delta1, Delta);\r\n         mul(Temp, Sigma, t1);\r\n         Sigma = Lambda;\r\n         ShiftAdd(Lambda, Temp, shamt+1);\r\n         shamt = 0;\r\n         L = r-L;\r\n         Delta = Delta1;\r\n         // cerr << \"case 2: \" << deg(Lambda) << \" \" << deg(Sigma) << \" \" << shamt << \"\\n\";\r\n      }\r\n      else {\r\n         shamt++;\r\n         div(t1, Delta1, Delta);\r\n         mul(Temp, Sigma, t1);\r\n         ShiftAdd(Lambda, Temp, shamt);\r\n         // cerr << \"case 3: \" << deg(Lambda) << \" \" << deg(Sigma) << \" \" << shamt << \"\\n\";\r\n      }\r\n   }\r\n\r\n   // cerr << \"finished: \" << L << \" \" << deg(Lambda) << \"\\n\"; \r\n\r\n   dl = deg(Lambda);\r\n   h.rep.SetLength(L + 1);\r\n\r\n   for (i = 0; i < L - dl; i++)\r\n      clear(h.rep[i]);\r\n\r\n   for (i = L - dl; i <= L; i++)\r\n      h.rep[i] = Lambda.rep[L - i];\r\n}\r\n\r\n\r\nvoid MinPolySeq(GF2EX& h, const vec_GF2E& a, long m)\r\n{\r\n   if (m < 0 || NTL_OVERFLOW(m, 1, 0)) LogicError(\"MinPoly: bad args\");\r\n   if (a.length() < 2*m) LogicError(\"MinPoly: sequence too short\");\r\n\r\n   BerlekampMassey(h, a, m);\r\n}\r\n\r\n\r\nvoid DoMinPolyMod(GF2EX& h, const GF2EX& g, const GF2EXModulus& F, long m, \r\n               const GF2EX& R)\r\n{\r\n   vec_GF2E x;\r\n\r\n   ProjectPowers(x, R, 2*m, g, F);\r\n   MinPolySeq(h, x, m);\r\n}\r\n\r\nvoid ProbMinPolyMod(GF2EX& h, const GF2EX& g, const GF2EXModulus& F, long m)\r\n{\r\n   long n = F.n;\r\n   if (m < 1 || m > n) LogicError(\"ProbMinPoly: bad args\");\r\n\r\n   GF2EX R;\r\n   random(R, n);\r\n\r\n   DoMinPolyMod(h, g, F, m, R);\r\n}\r\n\r\nvoid ProbMinPolyMod(GF2EX& h, const GF2EX& g, const GF2EXModulus& F)\r\n{\r\n   ProbMinPolyMod(h, g, F, F.n);\r\n}\r\n\r\nvoid MinPolyMod(GF2EX& hh, const GF2EX& g, const GF2EXModulus& F, long m)\r\n{\r\n   GF2EX h, h1;\r\n   long n = F.n;\r\n   if (m < 1 || m > n) LogicError(\"MinPoly: bad args\");\r\n\r\n   /* probabilistically compute min-poly */\r\n\r\n   ProbMinPolyMod(h, g, F, m);\r\n   if (deg(h) == m) { hh = h; return; }\r\n   CompMod(h1, h, g, F);\r\n   if (IsZero(h1)) { hh = h; return; }\r\n\r\n   /* not completely successful...must iterate */\r\n\r\n\r\n   GF2EX h2, h3;\r\n   GF2EX R;\r\n   GF2EXTransMultiplier H1;\r\n   \r\n\r\n   for (;;) {\r\n      random(R, n);\r\n      build(H1, h1, F);\r\n      TransMulMod(R, R, H1, F);\r\n      DoMinPolyMod(h2, g, F, m-deg(h), R);\r\n\r\n      mul(h, h, h2);\r\n      if (deg(h) == m) { hh = h; return; }\r\n      CompMod(h3, h2, g, F);\r\n      MulMod(h1, h3, h1, F);\r\n      if (IsZero(h1)) { hh = h; return; }\r\n   }\r\n}\r\n\r\nvoid IrredPolyMod(GF2EX& h, const GF2EX& g, const GF2EXModulus& F, long m)\r\n{\r\n   if (m < 1 || m > F.n) LogicError(\"IrredPoly: bad args\");\r\n\r\n   GF2EX R;\r\n   set(R);\r\n\r\n   DoMinPolyMod(h, g, F, m, R);\r\n}\r\n\r\n\r\n\r\nvoid IrredPolyMod(GF2EX& h, const GF2EX& g, const GF2EXModulus& F)\r\n{\r\n   IrredPolyMod(h, g, F, F.n);\r\n}\r\n\r\n\r\n\r\nvoid MinPolyMod(GF2EX& hh, const GF2EX& g, const GF2EXModulus& F)\r\n{\r\n   MinPolyMod(hh, g, F, F.n);\r\n}\r\n\r\n\r\nvoid MakeMonic(GF2EX& x)\r\n{\r\n   if (IsZero(x))\r\n      return;\r\n\r\n   if (IsOne(LeadCoeff(x)))\r\n      return;\r\n\r\n   GF2E t;\r\n\r\n   inv(t, LeadCoeff(x));\r\n   mul(x, x, t);\r\n}\r\n\r\n\r\nlong divide(GF2EX& q, const GF2EX& a, const GF2EX& b)\r\n{\r\n   if (IsZero(b)) {\r\n      if (IsZero(a)) {\r\n         clear(q);\r\n         return 1;\r\n      }\r\n      else\r\n         return 0;\r\n   }\r\n\r\n   GF2EX lq, r;\r\n   DivRem(lq, r, a, b);\r\n   if (!IsZero(r)) return 0; \r\n   q = lq;\r\n   return 1;\r\n}\r\n\r\nlong divide(const GF2EX& a, const GF2EX& b)\r\n{\r\n   if (IsZero(b)) return IsZero(a);\r\n   GF2EX lq, r;\r\n   DivRem(lq, r, a, b);\r\n   if (!IsZero(r)) return 0; \r\n   return 1;\r\n}\r\n\r\n\r\nlong operator==(const GF2EX& a, long b)\r\n{\r\n   if (b & 1)\r\n      return IsOne(a);\r\n   else\r\n      return IsZero(a);\r\n}\r\n\r\n\r\nlong operator==(const GF2EX& a, GF2 b)\r\n{\r\n   if (b == 1)\r\n      return IsOne(a);\r\n   else\r\n      return IsZero(a);\r\n}\r\n\r\nlong operator==(const GF2EX& a, const GF2E& b)\r\n{\r\n   if (IsZero(b))\r\n      return IsZero(a);\r\n\r\n   if (deg(a) != 0)\r\n      return 0;\r\n\r\n   return a.rep[0] == b;\r\n}\r\n\r\n\r\n\r\nvoid power(GF2EX& x, const GF2EX& a, long e)\r\n{\r\n   if (e < 0) {\r\n      ArithmeticError(\"power: negative exponent\");\r\n   }\r\n\r\n   if (e == 0) {\r\n      x = 1;\r\n      return;\r\n   }\r\n\r\n   if (a == 0 || a == 1) {\r\n      x = a;\r\n      return;\r\n   }\r\n\r\n   long da = deg(a);\r\n\r\n   if (da == 0) {\r\n      x = power(ConstTerm(a), e);\r\n      return;\r\n   }\r\n\r\n\r\n   if (da > (NTL_MAX_LONG-1)/e)\r\n      ResourceError(\"overflow in power\");\r\n\r\n   GF2EX res;\r\n   res.SetMaxLength(da*e + 1);\r\n   res = 1;\r\n   \r\n   long k = NumBits(e);\r\n   long i;\r\n\r\n   for (i = k - 1; i >= 0; i--) {\r\n      sqr(res, res);\r\n      if (bit(e, i))\r\n         mul(res, res, a);\r\n   }\r\n\r\n   x = res;\r\n}\r\n\r\nvoid reverse(GF2EX& x, const GF2EX& a, long hi)\r\n{\r\n   if (hi < 0) { clear(x); return; }\r\n   if (NTL_OVERFLOW(hi, 1, 0)) ResourceError(\"overflow in reverse\");\r\n\r\n   if (&x == &a) {\r\n      GF2EX tmp;\r\n      CopyReverse(tmp, a, hi);\r\n      x = tmp;\r\n   }\r\n   else\r\n      CopyReverse(x, a, hi);\r\n}\r\n\r\n\r\nstatic\r\nvoid FastTraceVec(vec_GF2E& S, const GF2EXModulus& f)\r\n{\r\n   long n = deg(f);\r\n\r\n   GF2EX x = reverse(-LeftShift(reverse(diff(reverse(f)), n-1), n-1)/f, n-1);\r\n\r\n   S.SetLength(n);\r\n   S[0] = n;\r\n\r\n   long i;\r\n   for (i = 1; i < n; i++)\r\n      S[i] = coeff(x, i);\r\n}\r\n\r\n\r\nvoid PlainTraceVec(vec_GF2E& S, const GF2EX& ff)\r\n{\r\n   if (deg(ff) <= 0)\r\n      LogicError(\"TraceVec: bad args\");\r\n\r\n   GF2EX f;\r\n   f = ff;\r\n\r\n   MakeMonic(f);\r\n\r\n   long n = deg(f);\r\n\r\n   S.SetLength(n);\r\n\r\n   if (n == 0)\r\n      return;\r\n\r\n   long k, i;\r\n   GF2X acc, t;\r\n   GF2E t1;\r\n\r\n   S[0] = n;\r\n\r\n   for (k = 1; k < n; k++) {\r\n      mul(acc, rep(f.rep[n-k]), k);\r\n\r\n      for (i = 1; i < k; i++) {\r\n         mul(t, rep(f.rep[n-i]), rep(S[k-i]));\r\n         add(acc, acc, t);\r\n      }\r\n\r\n      conv(t1, acc);\r\n      negate(S[k], t1);\r\n   }\r\n}\r\n\r\nvoid TraceVec(vec_GF2E& S, const GF2EX& f)\r\n{\r\n   if (deg(f) < GF2E::DivCross())\r\n      PlainTraceVec(S, f);\r\n   else\r\n      FastTraceVec(S, f);\r\n}\r\n\r\nstatic\r\nvoid ComputeTraceVec(vec_GF2E& S, const GF2EXModulus& F)\r\n{\r\n   if (F.method == GF2EX_MOD_PLAIN) {\r\n      PlainTraceVec(S, F.f);\r\n   }\r\n   else {\r\n      FastTraceVec(S, F);\r\n   }\r\n}\r\n\r\nvoid TraceMod(GF2E& x, const GF2EX& a, const GF2EXModulus& F)\r\n{\r\n   long n = F.n;\r\n\r\n   if (deg(a) >= n)\r\n      LogicError(\"trace: bad args\");\r\n\r\n   do { // NOTE: thread safe lazy init\r\n      Lazy<vec_GF2E>::Builder builder(F.tracevec.val());\r\n      if (!builder()) break;\r\n      UniquePtr<vec_GF2E> p;\r\n      p.make();\r\n      ComputeTraceVec(*p, F);\r\n      builder.move(p);\r\n   } while (0);\r\n\r\n   InnerProduct(x, a.rep, *F.tracevec.val());\r\n}\r\n\r\nvoid TraceMod(GF2E& x, const GF2EX& a, const GF2EX& f)\r\n{\r\n   if (deg(a) >= deg(f) || deg(f) <= 0)\r\n      LogicError(\"trace: bad args\");\r\n\r\n   project(x, TraceVec(f), a);\r\n}\r\n\r\n\r\nvoid PlainResultant(GF2E& rres, const GF2EX& a, const GF2EX& b)\r\n{\r\n   GF2E res;\r\n \r\n   if (IsZero(a) || IsZero(b))\r\n      clear(res);\r\n   else if (deg(a) == 0 && deg(b) == 0) \r\n      set(res);\r\n   else {\r\n      long d0, d1, d2;\r\n      GF2E lc;\r\n      set(res);\r\n\r\n      long n = max(deg(a),deg(b)) + 1;\r\n      GF2EX u(INIT_SIZE, n), v(INIT_SIZE, n);\r\n      GF2XVec tmp(n, 2*GF2E::WordLength());\r\n\r\n      u = a;\r\n      v = b;\r\n\r\n      for (;;) {\r\n         d0 = deg(u);\r\n         d1 = deg(v);\r\n         lc = LeadCoeff(v);\r\n\r\n         PlainRem(u, u, v, tmp);\r\n         swap(u, v);\r\n\r\n         d2 = deg(v);\r\n         if (d2 >= 0) {\r\n            power(lc, lc, d0-d2);\r\n            mul(res, res, lc);\r\n            if (d0 & d1 & 1) negate(res, res);\r\n         }\r\n         else {\r\n            if (d1 == 0) {\r\n               power(lc, lc, d0);\r\n               mul(res, res, lc);\r\n            }\r\n            else\r\n               clear(res);\r\n        \r\n            break;\r\n         }\r\n      }\r\n\r\n      rres = res;\r\n   }\r\n}\r\n\r\nvoid resultant(GF2E& rres, const GF2EX& a, const GF2EX& b)\r\n{\r\n   PlainResultant(rres, a, b); \r\n}\r\n\r\n\r\nvoid NormMod(GF2E& x, const GF2EX& a, const GF2EX& f)\r\n{\r\n   if (deg(f) <= 0 || deg(a) >= deg(f)) \r\n      LogicError(\"norm: bad args\");\r\n\r\n   if (IsZero(a)) {\r\n      clear(x);\r\n      return;\r\n   }\r\n\r\n   GF2E t;\r\n   resultant(t, f, a);\r\n   if (!IsOne(LeadCoeff(f))) {\r\n      GF2E t1;\r\n      power(t1, LeadCoeff(f), deg(a));\r\n      inv(t1, t1);\r\n      mul(t, t, t1);\r\n   }\r\n\r\n   x = t;\r\n}\r\n\r\n\r\n\r\n// tower stuff...\r\n\r\nvoid InnerProduct(GF2EX& x, const GF2X& v, long low, long high,\r\n                   const vec_GF2EX& H, long n, vec_GF2E& t)\r\n{\r\n   long i, j;\r\n\r\n   for (j = 0; j < n; j++)\r\n      clear(t[j]);\r\n\r\n   high = min(high, deg(v));\r\n   for (i = low; i <= high; i++) {\r\n      const vec_GF2E& h = H[i-low].rep;\r\n      long m = h.length();\r\n\r\n      if (coeff(v, i) != 0) {\r\n         for (j = 0; j < m; j++) {\r\n            add(t[j], t[j], h[j]);\r\n         }\r\n      }\r\n   }\r\n\r\n   x.rep.SetLength(n);\r\n   for (j = 0; j < n; j++)\r\n      x.rep[j] = t[j];\r\n\r\n   x.normalize();\r\n}\r\n\r\n\r\n\r\nvoid CompTower(GF2EX& x, const GF2X& g, const GF2EXArgument& A,\r\n             const GF2EXModulus& F)\r\n{\r\n   if (deg(g) <= 0) {\r\n      conv(x, g);\r\n      return;\r\n   }\r\n\r\n\r\n   GF2EX s, t;\r\n   vec_GF2E scratch;\r\n   scratch.SetLength(deg(F));\r\n\r\n   long m = A.H.length() - 1;\r\n   long l = (((deg(g)+1)+m-1)/m) - 1;\r\n\r\n   const GF2EX& M = A.H[m];\r\n\r\n   InnerProduct(t, g, l*m, l*m + m - 1, A.H, F.n, scratch);\r\n   for (long i = l-1; i >= 0; i--) {\r\n      InnerProduct(s, g, i*m, i*m + m - 1, A.H, F.n, scratch);\r\n      MulMod(t, t, M, F);\r\n      add(t, t, s);\r\n   }\r\n   x = t;\r\n}\r\n\r\n\r\nvoid CompTower(GF2EX& x, const GF2X& g, const GF2EX& h, \r\n             const GF2EXModulus& F)\r\n   // x = g(h) mod f\r\n{\r\n   long m = SqrRoot(deg(g)+1);\r\n\r\n   if (m == 0) {\r\n      clear(x);\r\n      return;\r\n   }\r\n\r\n\r\n   GF2EXArgument A;\r\n\r\n   build(A, h, F, m);\r\n\r\n   CompTower(x, g, A, F);\r\n}\r\n\r\nvoid PrepareProjection(vec_vec_GF2& tt, const vec_GF2E& s,\r\n                       const vec_GF2& proj)\r\n{\r\n   long l = s.length();\r\n   tt.SetLength(l);\r\n\r\n   GF2XTransMultiplier M;\r\n   long i;\r\n\r\n   for (i = 0; i < l; i++) {\r\n      build(M, rep(s[i]), GF2E::modulus());\r\n      UpdateMap(tt[i], proj, M, GF2E::modulus());\r\n   }\r\n}\r\n\r\nvoid ProjectedInnerProduct(ref_GF2 x, const vec_GF2E& a, \r\n                           const vec_vec_GF2& b)\r\n{\r\n   long n = min(a.length(), b.length());\r\n\r\n   GF2 t, res;\r\n\r\n   res = 0;\r\n\r\n   long i;\r\n   for (i = 0; i < n; i++) {\r\n      project(t, b[i], rep(a[i]));\r\n      res += t;\r\n   }\r\n\r\n   x = res;\r\n}\r\n\r\n\r\n\r\nvoid PrecomputeProj(vec_GF2& proj, const GF2X& f)\r\n{\r\n   long n = deg(f);\r\n\r\n   if (n <= 0) LogicError(\"PrecomputeProj: bad args\");\r\n\r\n   if (ConstTerm(f) != 0) {\r\n      proj.SetLength(1);\r\n      proj[0] = 1;\r\n   }\r\n   else {\r\n      proj.SetLength(n);\r\n      clear(proj);\r\n      proj[n-1] = 1;\r\n   }\r\n}\r\n\r\nvoid ProjectPowersTower(vec_GF2& x, const vec_GF2E& a, long k,\r\n                   const GF2EXArgument& H, const GF2EXModulus& F,\r\n                   const vec_GF2& proj)\r\n\r\n{\r\n   long n = F.n;\r\n\r\n   if (a.length() > n || k < 0) LogicError(\"ProjectPowers: bad args\");\r\n\r\n   long m = H.H.length()-1;\r\n   long l = (k+m-1)/m - 1;\r\n\r\n   GF2EXTransMultiplier M;\r\n   build(M, H.H[m], F);\r\n\r\n   vec_GF2E s(INIT_SIZE, n);\r\n   s = a;\r\n\r\n   x.SetLength(k);\r\n\r\n   vec_vec_GF2 tt;\r\n\r\n   for (long i = 0; i <= l; i++) {\r\n      long m1 = min(m, k-i*m);\r\n\r\n      PrepareProjection(tt, s, proj);\r\n\r\n      for (long j = 0; j < m1; j++) {\r\n         GF2 r;\r\n         ProjectedInnerProduct(r, H.H[j].rep, tt);\r\n         x.put(i*m + j, r);\r\n      }\r\n      if (i < l)\r\n         UpdateMap(s, s, M, F);\r\n   }\r\n}\r\n\r\n\r\n\r\n\r\nvoid ProjectPowersTower(vec_GF2& x, const vec_GF2E& a, long k,\r\n                   const GF2EX& h, const GF2EXModulus& F,\r\n                   const vec_GF2& proj)\r\n\r\n{\r\n   if (a.length() > F.n || k < 0) LogicError(\"ProjectPowers: bad args\");\r\n\r\n   if (k == 0) {\r\n      x.SetLength(0);\r\n      return;\r\n   }\r\n\r\n   long m = SqrRoot(k);\r\n\r\n   GF2EXArgument H;\r\n\r\n   build(H, h, F, m);\r\n   ProjectPowersTower(x, a, k, H, F, proj);\r\n}\r\n\r\n\r\nvoid DoMinPolyTower(GF2X& h, const GF2EX& g, const GF2EXModulus& F, long m,\r\n               const vec_GF2E& R, const vec_GF2& proj)\r\n{\r\n   vec_GF2 x;\r\n\r\n   ProjectPowersTower(x, R, 2*m, g, F, proj);\r\n   \r\n   MinPolySeq(h, x, m);\r\n}\r\n\r\n\r\nvoid ProbMinPolyTower(GF2X& h, const GF2EX& g, const GF2EXModulus& F, \r\n                      long m)\r\n{\r\n   long n = F.n;\r\n   if (m < 1 || m > n*GF2E::degree()) LogicError(\"ProbMinPoly: bad args\");\r\n\r\n   vec_GF2E R;\r\n   R.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++) random(R[i]);\r\n\r\n   vec_GF2 proj;\r\n   PrecomputeProj(proj, GF2E::modulus());\r\n\r\n   DoMinPolyTower(h, g, F, m, R, proj);\r\n}\r\n\r\nvoid ProbMinPolyTower(GF2X& h, const GF2EX& g, const GF2EXModulus& F, \r\n                      long m, const vec_GF2& proj)\r\n{\r\n   long n = F.n;\r\n   if (m < 1 || m > n*GF2E::degree()) LogicError(\"ProbMinPoly: bad args\");\r\n\r\n   vec_GF2E R;\r\n   R.SetLength(n);\r\n   long i;\r\n   for (i = 0; i < n; i++) random(R[i]);\r\n\r\n   DoMinPolyTower(h, g, F, m, R, proj);\r\n}\r\n\r\nvoid MinPolyTower(GF2X& hh, const GF2EX& g, const GF2EXModulus& F, long m)\r\n{\r\n   GF2X h;\r\n   GF2EX h1;\r\n   long n = F.n;\r\n   if (m < 1 || m > n*GF2E::degree()) {\r\n      LogicError(\"MinPoly: bad args\");\r\n   }\r\n\r\n   vec_GF2 proj;\r\n   PrecomputeProj(proj, GF2E::modulus());\r\n\r\n   /* probabilistically compute min-poly */\r\n\r\n   ProbMinPolyTower(h, g, F, m, proj);\r\n   if (deg(h) == m) { hh = h; return; }\r\n   CompTower(h1, h, g, F);\r\n   if (IsZero(h1)) { hh = h; return; }\r\n\r\n   /* not completely successful...must iterate */\r\n\r\n   long i;\r\n\r\n   GF2X h2;\r\n   GF2EX h3;\r\n   vec_GF2E R;\r\n   GF2EXTransMultiplier H1;\r\n   \r\n\r\n   for (;;) {\r\n      R.SetLength(n);\r\n      for (i = 0; i < n; i++) random(R[i]);\r\n      build(H1, h1, F);\r\n      UpdateMap(R, R, H1, F);\r\n      DoMinPolyTower(h2, g, F, m-deg(h), R, proj);\r\n\r\n      mul(h, h, h2);\r\n      if (deg(h) == m) { hh = h; return; }\r\n      CompTower(h3, h2, g, F);\r\n      MulMod(h1, h3, h1, F);\r\n      if (IsZero(h1)) { \r\n         hh = h; \r\n         return; \r\n      }\r\n   }\r\n}\r\n\r\nvoid IrredPolyTower(GF2X& h, const GF2EX& g, const GF2EXModulus& F, long m)\r\n{\r\n   if (m < 1 || m > deg(F)*GF2E::degree()) LogicError(\"IrredPoly: bad args\");\r\n\r\n   vec_GF2E R;\r\n   R.SetLength(1);\r\n   R[0] = 1;\r\n\r\n   vec_GF2 proj;\r\n   proj.SetLength(1);\r\n   proj.put(0, 1);\r\n\r\n   DoMinPolyTower(h, g, F, m, R, proj);\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "4d88285876cdde66ce3c75ee4f6defe18ed37044", "size": 62740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/GF2EX.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WinNTL-8_1_2/src/GF2EX.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WinNTL-8_1_2/src/GF2EX.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1434355119, "max_line_length": 92, "alphanum_fraction": 0.4538412496, "num_tokens": 22201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.7057850154599562, "lm_q1q2_score": 0.4393224785816463}}
{"text": "﻿/*! \\file diffsolver.cpp\n    \\brief 微分方程式を解くクラスの実装\n\n    Copyright ©  2015 @dc1394 All Rights Reserved.\n    This software is released under the BSD 2-Clause License.\n*/\n\n#include \"diffsolver.h\"\n#include <algorithm>                    // for std::copy\n#include <stdexcept>                    // for std::runtime_error\n#include <boost/numeric/odeint.hpp>     // for boost::numeric::odeint\n#include <tbb/parallel_invoke.h>        // for tbb::parallel_invoke\n\nnamespace schrac {\n    using namespace boost::numeric::odeint;\n\n    // #region 型エイリアス\n\n    using error_stepper_type = runge_kutta_dopri5< myarray >;\n\n    // #endregion 型エイリアス\n\n    // #region コンストラクタ\n\n    DiffSolver::DiffSolver(std::shared_ptr<Data> const & pdata, std::shared_ptr<DiffData> const & pdiffdata) :\n        DiffSolver(pdata, pdiffdata, nullptr, nullptr)\n    {\n    }\n\n    DiffSolver::DiffSolver(std::shared_ptr<Data> const & pdata, std::shared_ptr<DiffData> const & pdiffdata, std::shared_ptr<Rho> const & prho, std::shared_ptr<Vhartree> const & pvh) :\n        PDiffData([this]() { return std::cref(pdiffdata_); }, nullptr),\n        pdata_(pdata),\n        pdiffdata_(pdiffdata),\n        prho_(prho),\n        pvh_(pvh),\n        pvh2_(pvh ? std::make_shared<Vhartree>(*pvh_) : nullptr)\n    {\n        if (pdata_->chemical_symbol_ == Data::Chemical_Symbol[0]) {\n            V_ = [this](double r)\n            {\n                return -pdiffdata_->Z_ / r;\n            };\n                        \n            V2_ = V_;\n\n            dV_dr_ = [this](double r)\n            {\n                return pdiffdata_->Z_ / (r * r);\n            };\n\n            dV_dr2_ = dV_dr_;\n        } else {\n            V_ = [this](double r)\n            {\n                return -pdiffdata_->Z_ / r + pvh_->vhartree(r);\n            };\n\n            V2_ = [this](double r)\n            {\n                return -pdiffdata_->Z_ / r + pvh2_->vhartree(r);\n            };\n\n            dV_dr_ = [this](double r)\n            {\n                return pdiffdata_->Z_ / (r * r) + pvh_->dvhartree_dr(r);\n            };\n\n            dV_dr2_ = [this](double r)\n            {\n                return pdiffdata_->Z_ / (r * r) + pvh2_->dvhartree_dr(r);\n            };\n        };\n    }\n\n    // #endregion コンストラクタ\n\n    // #region publicメンバ関数\n\n    DiffSolver::mypair DiffSolver::getMPval() const\n    {\n        myarray L, M;\n\n        L[0] = pdiffdata_->lo_[pdiffdata_->mp_o_];\n        L[1] = pdiffdata_->li_[pdiffdata_->mp_i_];\n        M[0] = pdiffdata_->mo_[pdiffdata_->mp_o_];\n        M[1] = pdiffdata_->mi_[pdiffdata_->mp_i_];\n\n        return std::make_pair(L, M);\n    }\n\n    void DiffSolver::initialize(double E)\n    {\n        pdiffdata_->E_ = E;         // エネルギーを代入\n        pdiffdata_->thisnode_ = 0;  // ノード数初期化\n        am_evaluate();              // am_を求める\n        bm_evaluate();              // bm_を求める\n\n        pdiffdata_->li_.clear();\n        pdiffdata_->mi_.clear();\n        pdiffdata_->lo_.clear();\n        pdiffdata_->mo_.clear();\n    }\n\n    void DiffSolver::solve_diff_equ()\n    {\n        if (pdata_->usetbb_) {\n            switch (pdata_->solver_type_) {\n            case Data::Solver_type::ADAMS_BASHFORTH_MOULTON:\n                tbb::parallel_invoke(\n                    [this]{ solve_diff_equ_o(adams_bashforth_moulton< 2, myarray >(), V_, dV_dr_); },\n                    [this]{ solve_diff_equ_i(adams_bashforth_moulton< 2, myarray >(), V2_, dV_dr2_); });\n                break;\n\n            case Data::Solver_type::BULIRSCH_STOER:\n                tbb::parallel_invoke(\n                    [this]{ solve_diff_equ_o(bulirsch_stoer < myarray >(pdata_->eps_, pdata_->eps_), V_, dV_dr_); },\n                    [this]{ solve_diff_equ_i(bulirsch_stoer < myarray >(pdata_->eps_, pdata_->eps_), V2_, dV_dr2_); });\n                break;\n\n            case Data::Solver_type::CONTROLLED_RUNGE_KUTTA:\n                tbb::parallel_invoke(\n                    [this]{ solve_diff_equ_o(make_controlled(pdata_->eps_, pdata_->eps_, error_stepper_type()), V_, dV_dr_); },\n                    [this]{ solve_diff_equ_i(make_controlled(pdata_->eps_, pdata_->eps_, error_stepper_type()), V2_, dV_dr2_); });\n                break;\n\n            default:\n                BOOST_ASSERT(!\"何かがおかしい！\");\n                break;\n            }\n        }\n        else {\n            switch (pdata_->solver_type_) {\n            case Data::Solver_type::ADAMS_BASHFORTH_MOULTON:\n                solve_diff_equ_o(adams_bashforth_moulton< 2, myarray >(), V_, dV_dr_);\n                solve_diff_equ_i(adams_bashforth_moulton< 2, myarray >(), V_, dV_dr_);\n                break;\n\n            case Data::Solver_type::BULIRSCH_STOER:\n                solve_diff_equ_o(bulirsch_stoer < myarray >(pdata_->eps_, pdata_->eps_), V_, dV_dr_);\n                solve_diff_equ_i(bulirsch_stoer < myarray >(pdata_->eps_, pdata_->eps_), V_, dV_dr_);\n                break;\n\n            case Data::Solver_type::CONTROLLED_RUNGE_KUTTA:\n                solve_diff_equ_o(make_controlled(pdata_->eps_, pdata_->eps_, error_stepper_type()), V_, dV_dr_);\n                solve_diff_equ_i(make_controlled(pdata_->eps_, pdata_->eps_, error_stepper_type()), V_, dV_dr_);\n                break;\n\n            default:\n                BOOST_ASSERT(!\"何かがおかしい！\");\n                break;\n            }\n        }\n    }\n\n    void DiffSolver::solve_poisson()\n    {\n        switch (pdata_->solver_type_) {\n        case Data::Solver_type::ADAMS_BASHFORTH_MOULTON:\n            solve_poisson_run(adams_bashforth_moulton< 2, myarray >()); \n            break;\n\n        case Data::Solver_type::BULIRSCH_STOER:\n            solve_poisson_run(bulirsch_stoer < myarray >(pdata_->eps_, pdata_->eps_));\n            break;\n\n        case Data::Solver_type::CONTROLLED_RUNGE_KUTTA:\n            solve_poisson_run(make_controlled(pdata_->eps_, pdata_->eps_, error_stepper_type()));\n            break;\n\n        default:\n            BOOST_ASSERT(!\"何かがおかしい！\");\n            break;\n        }\n    }\n\n    // #endregion publicメンバ関数\n\n    // #region privateメンバ関数\n\n    void DiffSolver::am_evaluate()\n    {\n        std::array<double, AMMAX * AMMAX> a;\n        myvector b;\n\n        for (auto i = 0U; i < AMMAX; i++) {\n            auto rtmp = 1.0;\n\n            for (auto j = 0U; j < AMMAX; j++) {\n                a[AMMAX * i + j] = rtmp;\n                rtmp *= pdiffdata_->r_mesh_[i];\n            }\n\n            b[i] = V_(std::exp(pdata_->xmin_ + static_cast<double>(i) * pdiffdata_->dx_));    \n        }\n            \n        am_ = solve_linear_equ(a, b);\n    }\n\n    void DiffSolver::bm_evaluate()\n    {\n        bm_[0] = 1.0;\n        bm_[1] = 0.0;\n        bm_[2] = (am_[0] - pdiffdata_->E_) / static_cast<double>(2 * pdata_->l_ + 3) * bm_[0];\n        bm_[3] = am_[1] / static_cast<double>(3 * pdata_->l_ + 6) * bm_[0];\n        bm_[4] = (am_[0] * bm_[2] + am_[2] * bm_[0] - pdiffdata_->E_ * bm_[2]) / static_cast<double>(4 * pdata_->l_ + 10);\n    }\n\n    void DiffSolver::derivs(myarray const & f, myarray & dfdx, double x, std::function<double(double)> const & V, std::function<double(double)> const & dV_dr) const\n    {\n        auto const dL_dx = [](double M) { return M; };\n\n        // dL / dx = M\n        dfdx[0] = dL_dx(f[1]);\n                \n        switch (pdata_->eq_type_) {\n        case Data::Eq_type::DIRAC:\n            // dM / dx \n            dfdx[1] = dM_dx_dirac(f[0], f[1], x, V, dV_dr);\n            break;\n\n        case Data::Eq_type::SCH:\n            // dM / dx \n            dfdx[1] = dM_dx_sch(f[0], f[1], x, V);\n            break;\n\n        case Data::Eq_type::SDIRAC:\n            // dM / dx \n            dfdx[1] = dM_dx_sdirac(f[0], f[1], x, V, dV_dr);\n            break;\n\n        default:\n            BOOST_ASSERT(!\"何かがおかしい！！\");\n            break;\n        }\n    }\n\n    double DiffSolver::dM_dx_dirac(double L, double M, double x, std::function<double(double)> const & V, std::function<double(double)> const & dV_dr) const\n    {\n        auto const r = std::exp(x);\n\n        auto const mass = 1.0 + Data::al2half * (pdiffdata_->E_ - V(r));\n        auto const d = Data::al2half * r / mass * dV_dr(r);\n        auto const l = static_cast<double>(pdata_->l_);\n\n        // dependence on all angular momentum\n        auto const d1 = -(2.0 * l + 1.0 + d) * M;\n        auto const d2 = (2.0 * sqr(r) * mass * (V(r) - pdiffdata_->E_) -\n            d * (l + 1.0 + pdata_->kappa_)) * L;\n\n        return d1 + d2;\n    }\n\n    double DiffSolver::dM_dx_sch(double L, double M, double x, std::function<double(double)> const & V) const\n    {\n        auto const r = std::exp(x);\n\n        return -(2.0 * static_cast<double>(pdata_->l_) + 1.0) * M +\n               2.0 * sqr(r) * (V(r) - pdiffdata_->E_) * L;\n    }\n\n    double DiffSolver::dM_dx_sdirac(double L, double M, double x, std::function<double(double)> const & V, std::function<double(double)> const & dV_dr) const\n    {\n        auto const r = std::exp(x);\n\n        auto const mass = 1.0 + Data::al2half * (pdiffdata_->E_ - V(r));\n        auto const d = Data::al2half * r / mass * dV_dr(r);\n        auto const l = static_cast<double>(pdata_->l_);\n\n        // scaler treatment\n        auto const d1 = -(2.0 * l + 1.0 + d) * M;\n        auto const d2 = (2.0 * sqr(r) * mass * (V(r) - pdiffdata_->E_) - d * l) * L;\n        \n        return d1 + d2;\n    }\n    \n    void DiffSolver::node_count(dvector const & L)\n    {\n        if (L.size() > 1 && (L.back() * *(++L.rbegin()) < 0.0)) {\n            pdiffdata_->thisnode_++;\n        }\n    }\n\n    myarray DiffSolver::req_lm_i_init_val()\n    {\n        auto const rmax = pdiffdata_->r_mesh_i_[0];\n        auto const a = std::sqrt(-2.0 * pdiffdata_->E_);\n        auto const d = std::exp(-a * rmax);\n\n        myarray state;\n        state[0] = d / std::pow(rmax, pdata_->l_ + 1);\n\n        if (state[0] < DiffSolver::MINVALUE) {\n            state[0] = DiffSolver::MINVALUE;\n        }\n\n        state[1] = -state[0] * (a + static_cast<double>(pdata_->l_ + 1) / rmax);\n\n        if (std::fabs(state[1]) < DiffSolver::MINVALUE) {\n            state[1] = -DiffSolver::MINVALUE;\n        }\n\n        return state;\n    }\n\n    myarray DiffSolver::req_lm_o_init_val()\n    {\n        myarray state;\n        state[0] = bm_[DiffSolver::BMMAX - 1];\n        state[1] = 4.0 * bm_[DiffSolver::BMMAX - 1];\n\n        auto const cnt = static_cast<std::int32_t>(DiffSolver::BMMAX - 2);\n        for (auto i = cnt; i >= 0; i--) {\n            state[0] *= pdiffdata_->r_mesh_[0];\n            state[0] += bm_[i];\n        }\n\n        for (auto i = cnt; i > 0; i--) {\n            state[1] *= pdiffdata_->r_mesh_[0];\n            state[1] += static_cast<double>(i) * bm_[i];\n        }\n        state[1] *= pdiffdata_->r_mesh_[0];\n\n        return state;\n    }\n    \n    myarray DiffSolver::req_poisson_init_val()\n    {\n        std::array<double, AMMAX * AMMAX> a;\n        myvector b;\n\n        for (auto i = 0U; i < AMMAX; i++) {\n            auto rtmp = pdiffdata_->r_mesh_[i];\n\n            for (auto j = 0U; j < AMMAX; j++) {\n                a[AMMAX * i + j] = rtmp;\n                rtmp *= pdiffdata_->r_mesh_[i];\n            }\n\n            b[i] = - pdiffdata_->r_mesh_[i] * (*prho_)(pdiffdata_->r_mesh_[i]);\n        }\n\n        auto const bn = solve_linear_equ(a, b);\n        \n        myarray state{};\n        auto const r0 = pdiffdata_->r_mesh_[0];\n\n        state[0] = ((bn[2] / 6.0 * r0 + bn[1] / 3.0) * r0 + bn[0]) * 0.5 * r0;\n        state[1] = ((0.25 * bn[2] * r0 + bn[1] / 3.0) * r0 + 0.5 * bn[0]);\n\n        return state;\n    }\n\n    template <typename Stepper>\n    void DiffSolver::solve_poisson_run(Stepper const & stepper)\n    {\n        auto state = req_poisson_init_val();\n        auto const loop = pdiffdata_->r_mesh_.size() - 1;\n\n        std::vector<double> vhart;\n        vhart.reserve(pdiffdata_->r_mesh_.size());\n        for (auto i = 0U; i < loop; i++) {\n            integrate_adaptive(\n                stepper,\n                [this](myarray const & f, myarray & dfdx, double r) {\n                dfdx[0] = f[1];\n                dfdx[1] = -r * (*prho_)(r);\n            },\n            state,\n            pdiffdata_->r_mesh_[i],\n            pdiffdata_->r_mesh_[i + 1],\n            pdiffdata_->r_mesh_[i + 1] - pdiffdata_->r_mesh_[i]);\n\n            vhart.push_back(state[0] / pdiffdata_->r_mesh_[i]);\n         \n        }\n\n        vhart.push_back(state[0] / pdiffdata_->r_mesh_.back());\n        pvh_->Vhart(vhart);\n    }\n\n    template <typename Stepper>\n    void DiffSolver::solve_diff_equ_i(Stepper const & stepper, std::function<double(double)> const & V, std::function<double(double)> const & dV_dr)\n    {\n        myarray state = req_lm_i_init_val();\n\n        integrate_const(\n            stepper,\n            [this, &V, &dV_dr](myarray const & f, myarray & dfdx, double x) { return derivs(f, dfdx, x, V, dV_dr); },\n            state,\n            pdiffdata_->x_i_[0],\n            pdiffdata_->x_i_[pdiffdata_->mp_i_] - pdiffdata_->dx_,\n            - pdiffdata_->dx_,\n            [this](myarray const & f, double const)\n        {\n            pdiffdata_->li_.push_back(f[0]);\n            pdiffdata_->mi_.push_back(f[1]);\n            node_count(pdiffdata_->li_);\n        });\n    }\n\n    template <typename Stepper>\n    void DiffSolver::solve_diff_equ_o(Stepper const & stepper, std::function<double(double)> const & V, std::function<double(double)> const & dV_dr)\n    {\n        auto state = req_lm_o_init_val();\n\n        integrate_const(\n            stepper,\n            [this, &V, &dV_dr](myarray const & f, myarray & dfdx, double x) { return derivs(f, dfdx, x, V, dV_dr); },\n            state,\n            pdiffdata_->x_o_[0],\n            pdiffdata_->x_o_[pdiffdata_->mp_o_],\n            pdiffdata_->dx_,\n            [this](myarray const & f, double const)\n        {\n            pdiffdata_->lo_.push_back(f[0]);\n            pdiffdata_->mo_.push_back(f[1]);\n            node_count(pdiffdata_->lo_);\n        });\n\n        if (pdiffdata_->lo_.size() != static_cast<std::vector<double>::size_type>(pdiffdata_->mp_o_ + 1)) {\n            pdiffdata_->lo_.pop_back();\n            pdiffdata_->mo_.pop_back();\n\n            integrate_const(\n                stepper,\n                [this, &V, &dV_dr](myarray const & f, myarray & dfdx, double x) { return derivs(f, dfdx, x, V, dV_dr); },\n                state,\n                pdiffdata_->x_o_[pdiffdata_->mp_o_],\n                pdiffdata_->x_o_[pdiffdata_->mp_o_] + pdiffdata_->dx_,\n                pdiffdata_->dx_,\n                [this](myarray const & f, double const)\n            {\n                pdiffdata_->lo_.push_back(f[0]);\n                pdiffdata_->mo_.push_back(f[1]);\n                node_count(pdiffdata_->lo_);\n            });\n        }\n    }\n\n    // #endregion privateメンバ関数\n\n    // #region templateメンバ関数の実体化\n\n    template void DiffSolver::solve_poisson_run<adams_bashforth_moulton< 2, myarray > >(adams_bashforth_moulton< 2, myarray > const & stepper);\n    template void DiffSolver::solve_poisson_run<bulirsch_stoer < myarray > >(bulirsch_stoer < myarray > const & stepper);\n    template void DiffSolver::solve_poisson_run<error_stepper_type>(error_stepper_type const & stepper);\n    template void DiffSolver::solve_diff_equ_i<adams_bashforth_moulton< 2, myarray > >(adams_bashforth_moulton< 2, myarray > const & stepper, std::function<double(double)> const & V, std::function<double(double)> const & dV_dr);\n    template void DiffSolver::solve_diff_equ_i<bulirsch_stoer < myarray > >(bulirsch_stoer < myarray > const & stepper, std::function<double(double)> const & V, std::function<double(double)> const & dV_dr);\n    template void DiffSolver::solve_diff_equ_i<error_stepper_type>(error_stepper_type const & stepper, std::function<double(double)> const & V, std::function<double(double)> const & dV_dr);\n    template void DiffSolver::solve_diff_equ_o<adams_bashforth_moulton< 2, myarray > >(adams_bashforth_moulton< 2, myarray > const & stepper, std::function<double(double)> const & V, std::function<double(double)> const & dV_dr);\n    template void DiffSolver::solve_diff_equ_o<bulirsch_stoer < myarray > >(bulirsch_stoer < myarray > const & stepper, std::function<double(double)> const & V, std::function<double(double)> const & dV_dr);\n    template void DiffSolver::solve_diff_equ_o<error_stepper_type>(error_stepper_type const & stepper, std::function<double(double)> const & V, std::function<double(double)> const & dV_dr);\n\n    // #endregion templateメンバ関数の実体化\n}\n", "meta": {"hexsha": "813023fe2b39571507a80d13b2fb1a61cd7e72d4", "size": 16321, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/diffsolver.cpp", "max_stars_repo_name": "dc1394/Schrac", "max_stars_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-31T23:35:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T07:10:30.000Z", "max_issues_repo_path": "src/diffsolver.cpp", "max_issues_repo_name": "dc1394/schrac", "max_issues_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/diffsolver.cpp", "max_forks_repo_name": "dc1394/schrac", "max_forks_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7916666667, "max_line_length": 228, "alphanum_fraction": 0.5454935359, "num_tokens": 4809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.43932247639970834}}
{"text": "// Copyright  (C)  2007  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n\n// Version: 1.0\n// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// URL: http://www.orocos.org/kdl\n\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// Lesser General Public License for more details.\n\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n#include \"rigidbodyinertia.hpp\"\n\n#include <Eigen/Core>\n\nnamespace KDL{\n    \n    const static bool mhi=true;\n\n    RigidBodyInertia::RigidBodyInertia(double m_,const Vector& h_,const RotationalInertia& I_,bool mhi):\n        m(m_),h(h_),I(I_)\n    {\n    }\n    \n    RigidBodyInertia::RigidBodyInertia(double m_, const Vector& c_, const RotationalInertia& Ic):\n        m(m_),h(m*c_){\n        //I=Ic-c x c x\n        Eigen::Vector3d c_eig=Eigen::Map<const Eigen::Vector3d>(c_.data);\n        Eigen::Map<Eigen::Matrix3d>(I.data)=Eigen::Map<const Eigen::Matrix3d>(Ic.data)-m_*(c_eig*c_eig.transpose()-c_eig.dot(c_eig)*Eigen::Matrix3d::Identity());\n    }\n    \n    RigidBodyInertia operator*(double a,const RigidBodyInertia& I){\n        return RigidBodyInertia(a*I.m,a*I.h,a*I.I,mhi);\n    }\n    \n    RigidBodyInertia operator+(const RigidBodyInertia& Ia, const RigidBodyInertia& Ib){\n        return RigidBodyInertia(Ia.m+Ib.m,Ia.h+Ib.h,Ia.I+Ib.I,mhi);\n    }\n    \n    Wrench operator*(const RigidBodyInertia& I,const Twist& t){\n        return Wrench(I.m*t.vel-I.h*t.rot,I.I*t.rot+I.h*t.vel);\n    }\n\n    RigidBodyInertia operator*(const Frame& T,const RigidBodyInertia& I){\n        Frame X=T.Inverse();\n        //mb=ma\n        //hb=R*(h-m*r)\n        //Ib = R(Ia+r x h x + (h-m*r) x r x)R'\n        Vector hmr = (I.h-I.m*X.p);\n        Eigen::Vector3d r_eig = Eigen::Map<Eigen::Vector3d>(X.p.data);\n        Eigen::Vector3d h_eig = Eigen::Map<const Eigen::Vector3d>(I.h.data);\n        Eigen::Vector3d hmr_eig = Eigen::Map<Eigen::Vector3d>(hmr.data);\n        Eigen::Matrix3d rcrosshcross = h_eig *r_eig.transpose()-r_eig.dot(h_eig)*Eigen::Matrix3d::Identity();\n        Eigen::Matrix3d hmrcrossrcross = r_eig*hmr_eig.transpose()-hmr_eig.dot(r_eig)*Eigen::Matrix3d::Identity();\n        Eigen::Matrix3d R = Eigen::Map<Eigen::Matrix3d>(X.M.data);\n        RotationalInertia Ib;\n        Eigen::Map<Eigen::Matrix3d>(Ib.data) = R*((Eigen::Map<const Eigen::Matrix3d>(I.I.data)+rcrosshcross+hmrcrossrcross)*R.transpose());\n        \n        return RigidBodyInertia(I.m,T.M*hmr,Ib,mhi);\n    }\n\n    RigidBodyInertia operator*(const Rotation& M,const RigidBodyInertia& I){\n        //mb=ma\n        //hb=R*h\n        //Ib = R(Ia)R' with r=0\n        Eigen::Matrix3d R = Eigen::Map<const Eigen::Matrix3d>(M.data);\n        RotationalInertia Ib;\n        Eigen::Map<Eigen::Matrix3d>(Ib.data) = R.transpose()*(Eigen::Map<const Eigen::Matrix3d>(I.I.data)*R);\n        \n        return RigidBodyInertia(I.m,M*I.h,Ib,mhi);\n    }\n\n    RigidBodyInertia RigidBodyInertia::RefPoint(const Vector& p){\n        //mb=ma\n        //hb=(h-m*r)\n        //Ib = (Ia+r x h x + (h-m*r) x r x)\n        Vector hmr = (this->h-this->m*p);\n        Eigen::Vector3d r_eig = Eigen::Map<const Eigen::Vector3d>(p.data);\n        Eigen::Vector3d h_eig = Eigen::Map<Eigen::Vector3d>(this->h.data);\n        Eigen::Vector3d hmr_eig = Eigen::Map<Eigen::Vector3d>(hmr.data);\n        Eigen::Matrix3d rcrosshcross = h_eig * r_eig.transpose()-r_eig.dot(h_eig)*Eigen::Matrix3d::Identity();\n        Eigen::Matrix3d hmrcrossrcross = r_eig*hmr_eig.transpose()-hmr_eig.dot(r_eig)*Eigen::Matrix3d::Identity();\n        RotationalInertia Ib;\n        Eigen::Map<Eigen::Matrix3d>(Ib.data) = Eigen::Map<Eigen::Matrix3d>(this->I.data)+rcrosshcross+hmrcrossrcross;\n        \n        return RigidBodyInertia(this->m,hmr,Ib,mhi);\n    }\n}//namespace\n", "meta": {"hexsha": "3bfd938d03742066e9905a8059161ce64d988430", "size": 4360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/kdl/src/rigidbodyinertia.cpp", "max_stars_repo_name": "rocos-sia/rocos-app", "max_stars_repo_head_hexsha": "83aa8aa31dd303d77693cfc5ad48055d051fa4bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-06T15:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:21:40.000Z", "max_issues_repo_path": "3rdparty/kdl/src/rigidbodyinertia.cpp", "max_issues_repo_name": "thinkexist1989/rocos-app", "max_issues_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/kdl/src/rigidbodyinertia.cpp", "max_forks_repo_name": "thinkexist1989/rocos-app", "max_forks_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0404040404, "max_line_length": 161, "alphanum_fraction": 0.6561926606, "num_tokens": 1335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.439322468695495}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020 Mikhail Komarov <nemo@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------//\n\n#ifndef BOOST_MULTIPRECISION_INVERSE_HPP\n#define BOOST_MULTIPRECISION_INVERSE_HPP\n\n#include <boost/container/vector.hpp>\n\n#include <boost/type_traits/is_integral.hpp>\n\n#include <nil/crypto3/multiprecision/cpp_int.hpp>\n#include <nil/crypto3/multiprecision/cpp_int/cpp_int_config.hpp>\n#include <nil/crypto3/multiprecision/modular/modular_adaptor.hpp>\n#include <nil/crypto3/multiprecision/modular/inverse.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace multiprecision {\n\n            template<typename Backend, expression_template_option ExpressionTemplates>\n            constexpr number<Backend, ExpressionTemplates>\n                inverse_extended_euclidean_algorithm(const number<Backend, ExpressionTemplates>& n,\n                                                     const number<Backend, ExpressionTemplates>& mod) {\n                return number<Backend, ExpressionTemplates>(\n                    backends::eval_inverse_extended_euclidean_algorithm(n.backend(), mod.backend()));\n            }\n\n            template<typename Backend, expression_template_option ExpressionTemplates>\n            constexpr number<modular_adaptor<Backend>, ExpressionTemplates> inverse_extended_euclidean_algorithm(\n                const number<modular_adaptor<Backend>, ExpressionTemplates>& modular) {\n                number<Backend, ExpressionTemplates> new_base, res;\n                number<modular_adaptor<Backend>, ExpressionTemplates> res_mod;\n\n                modular.backend().mod_data().adjust_regular(new_base.backend(), modular.backend().base_data());\n                res = backends::eval_inverse_extended_euclidean_algorithm(\n                    new_base.backend(), modular.backend().mod_data().get_mod().backend());\n                assign_components(res_mod.backend(), res.backend(), modular.backend().mod_data().get_mod().backend());\n\n                return res_mod;\n            }\n\n            template<typename Backend, expression_template_option ExpressionTemplates>\n            constexpr number<Backend, ExpressionTemplates>\n                monty_inverse(const number<Backend, ExpressionTemplates>& a,\n                              const number<Backend, ExpressionTemplates>& p,\n                              const number<Backend, ExpressionTemplates>& k) {\n                number<Backend, ExpressionTemplates> res;\n                backends::eval_monty_inverse(res.backend(), a.backend(), p.backend(), k.backend());\n                return res;\n            }\n\n            /*\n            template <typename IntegerType, typename = typename boost::enable_if<typename\n            is_trivial_cpp_int<IntegerType>::value>::type> IntegerType monty_inverse(const IntegerType& a)\n            {\n               return eval_monty_inverse(a);\n            }\n             */\n\n            /*\n            template <typename IntegerType, typename = typename boost::enable_if<!typename\n            is_trivial_cpp_int<IntegerType>::value>::type> IntegerType monty_inverse(const IntegerType& a)\n            {\n               IntegerType res;\n               eval_monty_inverse(res.backend(), a.backend());\n               return res;\n            }\n             */\n\n        }    // namespace multiprecision\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "e7b0fe09dfd425ea2937cad20cb644aac89a510a", "size": 3638, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/multiprecision/include/nil/crypto3/multiprecision/inverse.hpp", "max_stars_repo_name": "idealatom/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "snark-logic/libs-source/multiprecision/include/nil/crypto3/multiprecision/inverse.hpp", "max_issues_repo_name": "idealatom/podlodkin-freeton-year-control", "max_issues_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snark-logic/libs-source/multiprecision/include/nil/crypto3/multiprecision/inverse.hpp", "max_forks_repo_name": "idealatom/podlodkin-freeton-year-control", "max_forks_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T20:27:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T20:27:27.000Z", "avg_line_length": 45.475, "max_line_length": 118, "alphanum_fraction": 0.6146234195, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.43928382807451466}}
{"text": "//\n// Copyright 2013 Christian Henning\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#ifndef BOOST_GIL_TEST_EXTENSION_IO_MANDEL_VIEW_HPP\n#define BOOST_GIL_TEST_EXTENSION_IO_MANDEL_VIEW_HPP\n\n#include <boost/gil.hpp>\n\n#include <cmath>\n#include <cstdint>\n\nnamespace gil = boost::gil;\n\n// Models a Unary Function\ntemplate <typename P> // Models PixelValueConcept\nstruct mandelbrot_fn {\n  using point_t = gil::point_t;\n  using const_t = mandelbrot_fn;\n  using value_type = P;\n  using reference = value_type;\n  using const_reference = value_type;\n  using argument_type = point_t;\n  using result_type = reference;\n  static constexpr bool is_mutable = false;\n\n  value_type in_color_;\n  value_type out_color_;\n  point_t img_size_;\n  static const int MAX_ITER = 100; // max number of iterations\n\n  mandelbrot_fn() = default;\n  mandelbrot_fn(gil::point_t const &sz, value_type const &in_color,\n                value_type const &out_color)\n      : in_color_(in_color), out_color_(out_color), img_size_(sz) {}\n\n  std::ptrdiff_t width() { return img_size_.x; }\n  std::ptrdiff_t height() { return img_size_.y; }\n\n  result_type operator()(gil::point_t const &p) const {\n    // normalize the coords to (-2..1, -1.5..1.5)\n    // (actually make y -1.0..2 so it is asymmetric, so we can verify some view\n    // factory methods)\n    gil::point<double> const n{\n        static_cast<double>(p.x) / static_cast<double>(img_size_.x) * 3 - 2,\n        static_cast<double>(p.y) / static_cast<double>(img_size_.y) * 3 -\n            1.0f}; // 1.5f}\n    double t = get_num_iter(n);\n    t = std::pow(t, 0.2);\n\n    value_type ret;\n    for (std::size_t k = 0; k < gil::num_channels<P>::value; ++k)\n      ret[k] = (typename gil::channel_type<P>::type)(in_color_[k] * t +\n                                                     out_color_[k] * (1 - t));\n    return ret;\n  }\n\nprivate:\n  double get_num_iter(boost::gil::point<double> const &p) const {\n    gil::point<double> z(0, 0);\n    for (int i = 0; i < MAX_ITER; ++i) {\n      z = gil::point<double>(z.x * z.x - z.y * z.y + p.x, 2 * z.x * z.y + p.y);\n      if (z.x * z.x + z.y * z.y > 4)\n        return i / (double)MAX_ITER;\n    }\n    return 0;\n  }\n};\n\ntemplate <typename Pixel> struct mandel_view {\n  using deref_t = mandelbrot_fn<Pixel>;\n  using locator_t = gil::virtual_2d_locator<deref_t, false>;\n  using my_virt_view_t = gil::image_view<locator_t>;\n  using type = my_virt_view_t;\n};\n\ntemplate <typename Pixel>\nauto create_mandel_view(unsigned int width, unsigned int height,\n                        Pixel const &in, Pixel const &out) ->\n    typename mandel_view<Pixel>::type {\n  using view_t = typename mandel_view<Pixel>::type;\n  using deref_t = typename mandel_view<Pixel>::deref_t;\n  using locator_t = typename mandel_view<Pixel>::locator_t;\n\n  gil::point_t dims(width, height);\n  return view_t(dims, locator_t(gil::point_t(0, 0), gil::point_t(1, 1),\n                                deref_t(dims, in, out)));\n}\n\n#endif // BOOST_GIL_TEST_EXTENSION_IO_MANDEL_VIEW_HPP\n", "meta": {"hexsha": "b792bc49d8515b7ea7173332e6af1e4ba7fd5ec9", "size": 3100, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/extension/io/mandel_view.hpp", "max_stars_repo_name": "sdebionne/gil-reformated", "max_stars_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/extension/io/mandel_view.hpp", "max_issues_repo_name": "sdebionne/gil-reformated", "max_issues_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/extension/io/mandel_view.hpp", "max_forks_repo_name": "sdebionne/gil-reformated", "max_forks_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9787234043, "max_line_length": 79, "alphanum_fraction": 0.6567741935, "num_tokens": 897, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4392722327135004}}
{"text": "//==============================================================================\n//          Copyright 2015 J.T. Lapreste\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EULER_FUNCTIONS_SCALAR_ERFCX_HPP_INCLUDED\n#define NT2_EULER_FUNCTIONS_SCALAR_ERFCX_HPP_INCLUDED\n\n#include <nt2/euler/functions/erfcx.hpp>\n#include <nt2/euler/functions/details/erf_kernel.hpp>\n#include <nt2/include/functions/scalar/erfc.hpp>\n#include <nt2/include/functions/scalar/expx2.hpp>\n#include <nt2/include/functions/scalar/sqr.hpp>\n#include <nt2/include/functions/scalar/sqrt.hpp>\n#include <nt2/include/functions/scalar/oneplus.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/include/constants/six.hpp>\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/constants/inf.hpp>\n#endif\n\n#include <boost/simd/sdk/config.hpp>\n#include <iostream>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( erfcx_, tag::cpu_\n                            , (A0)\n                            , (scalar_< double_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n#ifndef BOOST_SIMD_NO_INFINITIES\n      if(a0 == Inf<A0>()) return Zero<A0>();\n      if(nt2::is_nan(a0)) return a0;\n#endif\n      if(a0 < 0.65)\n      {\n        return expx2(a0)*erfc(a0);\n      }\n      else if (a0 < 2.2)\n      {\n        return details::erf_kernel<A0>::erfc2(a0);\n      }\n      else if(a0< A0(6))\n      {\n        return details::erf_kernel<A0>::erfc3(a0);\n      }\n      else\n      {\n        return details::erf_kernel<A0>::erfc4(rec(a0));\n      }\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( erfcx_, tag::cpu_\n                            , (A0)\n                            , (scalar_< single_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n#ifndef BOOST_SIMD_NO_INFINITIES\n      if(a0 == Inf<A0>()) return Zero<A0>();\n      if(nt2::is_nan(a0)) return a0;\n#endif\n      if(a0 < Twothird<A0>())\n      {\n        return expx2(a0)*erfc(a0);\n      }\n      else\n      {\n        A0 z =  a0/oneplus(a0)- 0.4f;\n        return details::erf_kernel<A0>::erfc2(z);\n      }\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "af23d0cbe0a3f0e42adedaf19dfa13424c404d26", "size": 2381, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/include/nt2/euler/functions/scalar/erfcx.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/euler/include/nt2/euler/functions/scalar/erfcx.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/euler/include/nt2/euler/functions/scalar/erfcx.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6860465116, "max_line_length": 80, "alphanum_fraction": 0.5417891642, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.43927222644669667}}
{"text": "\r\n//\r\n// Copyright 2010 Scott McMurray.\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt or copy at\r\n//  http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n\r\n#ifndef BOOST_HASH_DETAIL_PRIMES_HPP\r\n#define BOOST_HASH_DETAIL_PRIMES_HPP\r\n\r\n#include <boost/integer.hpp>\r\n\r\nnamespace boost {\r\nnamespace hashes {\r\nnamespace detail {\r\n\r\ntemplate <int Bits>\r\nstruct all_ones {\r\n    typedef typename uint_t<Bits>::least type;\r\n    static type const value = (type(all_ones<Bits-1>::value) << 1) | 1;\r\n};\r\ntemplate <>\r\nstruct all_ones<0> {\r\n    typedef uint_t<0>::least type;\r\n    static type const value = 0;\r\n};\r\n\r\ntemplate <int Bits>\r\nstruct largest_prime;\r\n\r\n#define BOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(B, D) \\\r\n    template <> \\\r\n    struct largest_prime<B> { \\\r\n        static uint_t<B>::least const value = all_ones<B>::value - D; \\\r\n    }\r\n\r\n// http://primes.utm.edu/lists/2small/0bit.html or\r\n// http://www.research.att.com/~njas/sequences/A013603\r\n// Though those offets are from 2**b; This code is offsets from 2**b-1\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET( 2, 0);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET( 3, 0);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET( 4, 2);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET( 5, 0);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET( 6, 2);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET( 7, 0);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET( 8, 4);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET( 9, 2);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(10, 2);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(11, 8);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(12, 2);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(13, 0);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(14, 2);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(15, 18);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(16, 14);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(17, 0);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(18, 4);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(19, 0);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(20, 2);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(21, 8);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(22, 2);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(23, 14);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(24, 2);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(25, 38);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(26, 4);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(27, 38);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(28, 56);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(29, 2);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(30, 34);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(31, 0);\r\nBOOST_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(32, 4);\r\n\r\n} // namespace detail\r\n} // namespace hashes\r\n} // namespace boost\r\n\r\n#endif // BOOST_HASH_DETAIL_PRIMES_HPP\r\n", "meta": {"hexsha": "f015d7baed42755e965c554ae37f738cec979af8", "size": 2773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/hash/detail/primes.hpp", "max_stars_repo_name": "dillonl/boost-cmake", "max_stars_repo_head_hexsha": "7204d4c68345a0b26e24f51fa46a04b1d2bda3e7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/hash/detail/primes.hpp", "max_issues_repo_name": "dillonl/boost-cmake", "max_issues_repo_head_hexsha": "7204d4c68345a0b26e24f51fa46a04b1d2bda3e7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/hash/detail/primes.hpp", "max_forks_repo_name": "dillonl/boost-cmake", "max_forks_repo_head_hexsha": "7204d4c68345a0b26e24f51fa46a04b1d2bda3e7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5512820513, "max_line_length": 72, "alphanum_fraction": 0.7839884602, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267118026095991, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.43915705862493365}}
{"text": "#include <layer/layer.h>\n#include <layer/math.h>\n#include <layer/hg.h>\n#include <layer/microfacet.h>\n#include <layer/fresnel.h>\n#include <layer/spline.h>\n#include <layer/log.h>\n#include <filesystem/path.h>\n#include <Eigen/SparseLU>\n#include <Eigen/Geometry>\n#include <tbb/tbb.h>\n\n#if defined(HAVE_FFTW)\n    #include <fftw3.h>\n#endif\n\nNAMESPACE_BEGIN(layer)\n\nnamespace {\n    template <typename VectorType> MatrixS sparseDiagonal(const VectorType &vec) {\n        MatrixS result(vec.size(), vec.size());\n        for (MatrixS::Index i = 0; i < vec.size(); ++i)\n            result.insert(i, i) = vec[i];\n        result.makeCompressed();\n        return result;\n    }\n\n    void sparsify(const MatrixX &dense, MatrixS &sparse) {\n        sparse.setZero();\n\n        for (MatrixX::Index j = 0; j < dense.cols(); ++j) {\n            for (MatrixX::Index i = 0; i < dense.rows(); ++i) {\n                Float value = dense.coeff(i, j);\n                if (value != 0)\n                    sparse.insert(i, j) = value;\n            }\n        }\n        sparse.makeCompressed();\n    }\n\n    void scaleColumns(LayerMode &mode, const VectorX &d) {\n        if ((size_t) d.size() != mode.resolution())\n            throw std::runtime_error(\"scaleColumns(): size mismatch!\");\n        MatrixS scale = sparseDiagonal(d.head(d.size()/2));\n        mode.transmissionBottomTop = mode.transmissionBottomTop * scale;\n        mode.reflectionBottom = mode.reflectionBottom * scale;\n        scale = sparseDiagonal(d.tail(d.size()/2));\n        mode.transmissionTopBottom = mode.transmissionTopBottom * scale;\n        mode.reflectionTop = mode.reflectionTop * scale;\n    }\n\n    void applySurfaceIntegrationWeights(Layer &layer) {\n        for (size_t l=0; l<layer.fourierOrders(); ++l)\n            scaleColumns(layer[l], layer.weights().cwiseProduct(\n                                       layer.nodes().cwiseAbs()) *\n                                       math::Pi * (l == 0 ? 2 : 1));\n    }\n\n    void applyMediumIntegrationWeights(Layer &layer) {\n        for (size_t l=0; l<layer.fourierOrders(); ++l)\n            scaleColumns(layer[l], layer.weights() * math::Pi * (l == 0 ? 2 : 1));\n    }\n};\n\nLayer::Layer(const VectorX &nodes, const VectorX &weights, size_t nFourierOrders)\n    : m_modes(nFourierOrders, LayerMode(nodes.size())), m_nodes(nodes), m_weights(weights) {\n    if (nodes.size() < 2)\n        throw std::runtime_error(\"Need at least 2 integration nodes!\");\n    else if (nodes.size() % 2 == 1)\n        throw std::runtime_error(\"The number of integration nodes must be even!\");\n    for (int i=0; i<nodes.size(); ++i)\n        if (nodes[i] == 0)\n            throw std::runtime_error(\"The set of integrations includes mu=0 -- this is not allowed.\");\n\n    if (nodes[0] < nodes[1]) {\n        size_t n = (size_t) nodes.size();\n        /* Order integration weights so that they are usable for adding-doubling */\n        m_weights.head(n/2).reverseInPlace();\n        m_nodes.head(n/2).reverseInPlace();\n    }\n}\n\nvoid Layer::setQuartets(const std::vector<Quartet> &quartets) {\n    std::vector<std::vector<Eigen::Triplet<Float>>>\n        tripletsTbt(fourierOrders()),\n        tripletsTtb(fourierOrders()),\n        tripletsRb(fourierOrders()),\n        tripletsRt(fourierOrders());\n\n    size_t approxSize = quartets.size() / (4 * fourierOrders());\n\n    for (size_t i=0; i<fourierOrders(); ++i) {\n        tripletsTbt[i].reserve(approxSize);\n        tripletsTtb[i].reserve(approxSize);\n        tripletsRb[i].reserve(approxSize);\n        tripletsRt[i].reserve(approxSize);\n    }\n\n    size_t n = resolution() / 2;\n    for (auto const &quartet: quartets) {\n        typedef MatrixS::Index Index;\n        if (quartet.o < n && quartet.i < n)\n            tripletsTbt[quartet.l].emplace_back(Index(quartet.o), Index(quartet.i), quartet.value);\n        else if (quartet.o >= n && quartet.i >= n)\n            tripletsTtb[quartet.l].emplace_back(Index(quartet.o-n), Index(quartet.i-n), quartet.value);\n        else if (quartet.o <n && quartet.i >= n)\n            tripletsRt[quartet.l].emplace_back(Index(quartet.o), Index(quartet.i-n), quartet.value);\n        else if (quartet.o >=n && quartet.i < n)\n            tripletsRb[quartet.l].emplace_back(Index(quartet.o-n), Index(quartet.i), quartet.value);\n        else\n            throw std::runtime_error(\"Layer::setFromQuartets(): internal error!\");\n    }\n\n    tbb::parallel_for(\n        tbb::blocked_range<size_t>(0, fourierOrders(), 1),\n        [&](const tbb::blocked_range<size_t> &range) {\n            for (size_t l = range.begin(); l < range.end(); ++l) {\n                m_modes[l].reflectionTop        .setFromTriplets(tripletsRt [l].begin(), tripletsRt [l].end());\n                m_modes[l].reflectionBottom     .setFromTriplets(tripletsRb [l].begin(), tripletsRb [l].end());\n                m_modes[l].transmissionTopBottom.setFromTriplets(tripletsTtb[l].begin(), tripletsTtb[l].end());\n                m_modes[l].transmissionBottomTop.setFromTriplets(tripletsTbt[l].begin(), tripletsTbt[l].end());\n            }\n        }\n    );\n}\n\nvoid Layer::setHenyeyGreenstein(Float albedo, Float g) {\n    std::vector<Quartet> quartets;\n    tbb::spin_mutex mutex;\n\n    tbb::parallel_for(\n        tbb::blocked_range<size_t>(0, resolution()),\n        [&](const tbb::blocked_range<size_t> &range) {\n            std::vector<Quartet> quartetsLocal;\n            quartetsLocal.reserve(fourierOrders() * resolution());\n            std::vector<Float> result;\n            for (size_t i = range.begin(); i < range.end(); ++i) {\n                for (size_t o = 0; o <= i; ++o) {\n                    hgFourierSeries(m_nodes[o], m_nodes[i], g, (int) fourierOrders(),\n                                    ERROR_GOAL, result);\n                    for (size_t l=0; l<std::min(fourierOrders(), result.size()); ++l) {\n                        quartetsLocal.emplace_back(l, o, i, result[l] * albedo);\n                        if (i != o)\n                            quartetsLocal.emplace_back(l, i, o, result[l] * albedo);\n                    }\n                }\n                tbb::spin_mutex::scoped_lock lock(mutex);\n                quartets.insert(quartets.end(), quartetsLocal.begin(), quartetsLocal.end());\n            }\n        }\n    );\n    setQuartets(quartets);\n    applyMediumIntegrationWeights(*this);\n}\n\nvoid Layer::setVonMisesFisher(Float albedo, Float kappa) {\n    std::vector<Quartet> quartets;\n    tbb::spin_mutex mutex;\n\n    Float scale;\n    if (kappa == 0)\n        scale = albedo / (4 * math::Pi);\n    else\n        scale = albedo * kappa / (4 * math::Pi * std::sinh(kappa));\n\n    tbb::parallel_for(\n        tbb::blocked_range<size_t>(0, resolution()),\n        [&](const tbb::blocked_range<size_t> &range) {\n            std::vector<Quartet> quartetsLocal;\n            quartetsLocal.reserve(fourierOrders() * resolution());\n            std::vector<Float> result;\n            for (size_t i = range.begin(); i < range.end(); ++i) {\n                Float mu_i = m_nodes[i];\n                for (size_t o = 0; o <= i; ++o) {\n                    Float mu_o = m_nodes[o];\n                    Float A = kappa * mu_i * mu_o;\n                    Float B = kappa * math::safe_sqrt((1 - mu_i * mu_i) *\n                                                      (1 - mu_o * mu_o));\n                    expCosFourierSeries(A, B, ERROR_GOAL, result);\n\n                    for (size_t l=0; l<std::min(fourierOrders(), result.size()); ++l) {\n                        quartetsLocal.emplace_back(l, o, i, result[l] * scale);\n                        if (i != o)\n                            quartetsLocal.emplace_back(l, i, o, result[l] * scale);\n                    }\n                }\n                tbb::spin_mutex::scoped_lock lock(mutex);\n                quartets.insert(quartets.end(), quartetsLocal.begin(), quartetsLocal.end());\n            }\n        }\n    );\n\n    setQuartets(quartets);\n    applyMediumIntegrationWeights(*this);\n}\n\nvoid Layer::setDiffuse(Float albedo) {\n    std::vector<Quartet> quartets;\n    quartets.reserve(resolution() * resolution() / 2);\n\n    size_t n = resolution(), h = n/2;\n    for (size_t i=0; i<n; ++i) {\n        for (size_t o=0; o<n; ++o) {\n            if ((i < h && o >= h) || (o < h && i >= h))\n                quartets.emplace_back(0, o, i, albedo * math::InvPi);\n        }\n    }\n\n    setQuartets(quartets);\n    applySurfaceIntegrationWeights(*this);\n}\n\nvoid Layer::setIsotropic(Float albedo) {\n    std::vector<Quartet> quartets;\n    quartets.reserve(resolution() * resolution());\n\n    size_t n = resolution();\n    for (size_t i=0; i<n; ++i)\n        for (size_t o=0; o<n; ++o)\n            quartets.emplace_back(0, o, i, albedo * math::InvFourPi);\n\n    setQuartets(quartets);\n    applyMediumIntegrationWeights(*this);\n}\n\nvoid Layer::setMicrofacet(std::complex<Float> eta, Float alpha, bool conserveEnergy,\n                          size_t fourierOrdersTarget) {\n    size_t n = resolution(), h = n/2;\n    std::vector<Quartet> quartets;\n    tbb::spin_mutex mutex;\n\n    fourierOrdersTarget = std::max(fourierOrdersTarget, fourierOrders());\n\n    tbb::parallel_for(\n        tbb::blocked_range<size_t>(0, resolution()),\n        [&](const tbb::blocked_range<size_t> &range) {\n            std::vector<Quartet> quartetsLocal;\n            quartetsLocal.reserve(fourierOrdersTarget * resolution());\n            std::vector<Float> result;\n            for (size_t i = range.begin(); i < range.end(); ++i) {\n                for (size_t o=0; o<n; ++o) {\n                    /* Sign flip due to different convention (depth values\n                     * increase opposite to the normal direction) */\n                    microfacetFourierSeries(-m_nodes[o], -m_nodes[i], eta,\n                                            alpha, fourierOrdersTarget,\n                                            ERROR_GOAL, result);\n\n                    for (size_t l=0; l<std::min(fourierOrders(), result.size()); ++l)\n                        quartetsLocal.emplace_back(l, o, i, result[l]);\n                }\n            }\n            tbb::spin_mutex::scoped_lock lock(mutex);\n            quartets.insert(quartets.end(), quartetsLocal.begin(), quartetsLocal.end());\n        }\n    );\n\n    setQuartets(quartets);\n\n    /* Add a pseudo-diffuse term to capture lost energy */\n    if (conserveEnergy && eta.imag() == 0) {\n        /* Case 1: Dielectrics */\n        VectorX W = m_weights.tail(h).cwiseProduct(m_nodes.tail(h)) * 2 * math::Pi;\n        LayerMode &l = m_modes[0];\n\n        VectorX Mb  = (W.asDiagonal() * MatrixX(l.reflectionBottom)).colwise().sum();\n        VectorX Mt  = (W.asDiagonal() * MatrixX(l.reflectionTop)).colwise().sum();\n        VectorX Mtb = (W.asDiagonal() * MatrixX(l.transmissionTopBottom)).colwise().sum();\n        VectorX Mbt = (W.asDiagonal() * MatrixX(l.transmissionBottomTop)).colwise().sum();\n\n        /* Determine how much energy we'd like to put into the transmission component\n           (proportional to the current reflection/reflaction split) */\n        VectorX Atb = (VectorX::Ones(h) - Mt - Mtb).cwiseProduct(Mtb.cwiseQuotient(Mt + Mtb));\n        VectorX Abt = (VectorX::Ones(h) - Mb - Mbt).cwiseProduct(Mbt.cwiseQuotient(Mb + Mbt));\n        Atb = Atb.cwiseMax(VectorX::Zero(h));\n        Abt = Abt.cwiseMax(VectorX::Zero(h));\n\n        /* Create a correction matrix which contains as much of the desired\n           energy as possible, while maintaining symmetry and energy conservation */\n        MatrixX Ctb = Abt*Atb.transpose() / std::max(W.dot(Abt), W.dot(Atb) / (eta.real()*eta.real()));\n        MatrixX Cbt = Ctb.transpose() / (eta.real()*eta.real());\n\n        sparsify(MatrixX(l.transmissionTopBottom) + Ctb, l.transmissionTopBottom);\n        sparsify(MatrixX(l.transmissionBottomTop) + Cbt, l.transmissionBottomTop);\n\n        /* Update missing energy terms */\n        Mtb = (W.asDiagonal() * MatrixX(l.transmissionTopBottom)).colwise().sum();\n        Mbt = (W.asDiagonal() * MatrixX(l.transmissionBottomTop)).colwise().sum();\n\n        /* Put the rest of the missing energy into the reflection component */\n        VectorX At = VectorX::Ones(h) - Mt - Mtb;\n        VectorX Ab = VectorX::Ones(h) - Mb - Mbt;\n        At = At.cwiseMax(VectorX::Zero(h));\n        Ab = Ab.cwiseMax(VectorX::Zero(h));\n\n        sparsify(MatrixX(l.reflectionTop)    + At*At.transpose() / W.dot(At), l.reflectionTop);\n        sparsify(MatrixX(l.reflectionBottom) + Ab*Ab.transpose() / W.dot(Ab), l.reflectionBottom);\n    } else if (conserveEnergy && eta.imag() != 0) {\n        /* Case 2: Conductors */\n        VectorX W = m_weights.tail(h).cwiseProduct(m_nodes.tail(h)) * 2 * math::Pi;\n\n        /* Compute a reference matrix for a material *without* Fresnel effects */\n        MatrixX refMatrix(n, n);\n\n        tbb::parallel_for(\n            tbb::blocked_range<size_t>(0, resolution()),\n            [&](const tbb::blocked_range<size_t> &range) {\n                std::vector<Float> result;\n                for (size_t i = range.begin(); i < range.end(); ++i) {\n                    /* Parallel loop over 'i' */\n                    for (size_t o = 0; o < n; ++o) {\n                        microfacetFourierSeries(\n                            -m_nodes[o], -m_nodes[i], std::complex<Float>(0.0f, 1.0f), alpha,\n                            fourierOrdersTarget, ERROR_GOAL, result);\n                        refMatrix(o, i) = result.size() > 0 ? result[0] : 0.0f;\n                    }\n                }\n            }\n        );\n\n        MatrixX reflectionTopRef = MatrixX(refMatrix).block(0, h, h, h);\n\n        VectorX Mt = VectorX::Ones(h) - (W.asDiagonal() * reflectionTopRef).colwise().sum().transpose();\n        Mt = Mt.cwiseMax(VectorX::Zero(h));\n\n        Float F = fresnelConductorIntegral(eta);\n        Float E = 1 - W.dot(Mt) * math::InvPi;\n\n        Float factor = F*E / (1-F*(1-E));\n\n        MatrixX C = Mt * Mt.transpose() * (factor/ W.dot(Mt));\n\n        sparsify(MatrixX(m_modes[0].reflectionTop) + C, m_modes[0].reflectionTop);\n        sparsify(MatrixX(m_modes[0].reflectionBottom) + C, m_modes[0].reflectionBottom);\n    }\n\n    applySurfaceIntegrationWeights(*this);\n}\n\nvoid Layer::add(const Layer &layer1, const Layer &layer2, Layer &output, bool homogeneous) {\n    if (output.resolution() != layer1.resolution() &&\n        output.resolution() != layer2.resolution() &&\n        output.fourierOrders() != layer1.fourierOrders() &&\n        output.fourierOrders() != layer2.fourierOrders())\n        throw std::runtime_error(\"Layer::addLayer(): incompatible sizes!\");\n\n    size_t n = output.resolution() / 2;\n    MatrixS I((int) n, (int) n);\n    I.setIdentity();\n\n    /* Special case: it is possible to save quite a bit of computation when we\n       know that both layers are homogeneous and of the same type */\n    if (homogeneous) {\n        tbb::parallel_for(\n            tbb::blocked_range<size_t>(0, layer1.fourierOrders(), 1),\n            [&](const tbb::blocked_range<size_t> &range) {\n                MatrixS Rb, Ttb;\n                for (size_t i = range.begin(); i < range.end(); ++i) {\n                    const LayerMode &l1 = layer1[i], &l2 = layer2[i];\n                    LayerMode &lo = output[i];\n\n                    /* Gain for downward radiation */\n                    Eigen::SparseLU<MatrixS, Eigen::AMDOrdering<int>> G_tb;\n                    G_tb.compute(I - l1.reflectionBottom * l2.reflectionTop);\n\n                    /* Transmission at the bottom due to illumination at the top */\n                    MatrixS result = G_tb.solve(l1.transmissionTopBottom);\n                    Ttb = l2.transmissionTopBottom * result;\n\n                    /* Reflection at the bottom */\n                    MatrixS temp = l1.reflectionBottom * l2.transmissionBottomTop;\n                    result = G_tb.solve(temp);\n                    Rb = l2.reflectionBottom + l2.transmissionTopBottom * result;\n\n                    #if defined(DROP_THRESHOLD)\n                        Ttb.prune((Float) 1, (Float) DROP_THRESHOLD);\n                        Rb.prune((Float) 1, (Float) DROP_THRESHOLD);\n                    #endif\n\n                    lo.transmissionTopBottom = Ttb;\n                    lo.transmissionBottomTop = Ttb;\n                    lo.reflectionTop = Rb;\n                    lo.reflectionBottom = Rb;\n                }\n            }\n        );\n    } else {\n        tbb::parallel_for(\n            tbb::blocked_range<size_t>(0, layer1.fourierOrders(), 1),\n            [&](const tbb::blocked_range<size_t> &range) {\n                for (size_t i = range.begin(); i < range.end(); ++i) {\n                    const LayerMode &l1 = layer1[i], &l2 = layer2[i];\n                    LayerMode &lo = output[i];\n\n                    /* Gain for downward radiation */\n                    Eigen::SparseLU<MatrixS, Eigen::AMDOrdering<int>> G_tb;\n                    G_tb.compute(I - l1.reflectionBottom * l2.reflectionTop);\n\n                    /* Gain for upward radiation */\n                    Eigen::SparseLU<MatrixS, Eigen::AMDOrdering<int>> G_bt;\n                    G_bt.compute(I - l2.reflectionTop * l1.reflectionBottom);\n\n                    /* Transmission at the bottom due to illumination at the top */\n                    MatrixS result = G_tb.solve(l1.transmissionTopBottom);\n                    MatrixS Ttb = l2.transmissionTopBottom * result;\n\n                    /* Reflection at the bottom */\n                    MatrixS temp = l1.reflectionBottom * l2.transmissionBottomTop;\n                    result = G_tb.solve(temp);\n                    MatrixS Rb = l2.reflectionBottom + l2.transmissionTopBottom * result;\n\n                    /* Transmission at the top due to illumination at the bottom */\n                    result = G_bt.solve(l2.transmissionBottomTop);\n                    MatrixS Tbt = l1.transmissionBottomTop * result;\n\n                    /* Reflection at the top */\n                    temp = l2.reflectionTop * l1.transmissionTopBottom;\n                    result = G_bt.solve(temp);\n                    MatrixS Rt = l1.reflectionTop + l1.transmissionBottomTop * result;\n\n                    #if defined(DROP_THRESHOLD)\n                        Ttb.prune((Float) 1, (Float) DROP_THRESHOLD);\n                        Tbt.prune((Float) 1, (Float) DROP_THRESHOLD);\n                        Rb.prune((Float) 1, (Float) DROP_THRESHOLD);\n                        Rt.prune((Float) 1, (Float) DROP_THRESHOLD);\n                    #endif\n\n                    lo.transmissionTopBottom = Ttb;\n                    lo.transmissionBottomTop = Tbt;\n                    lo.reflectionTop = Rt;\n                    lo.reflectionBottom = Rb;\n                }\n            }\n        );\n    }\n}\n\n#if !defined(HAVE_FFTW)\nvoid Layer::setMatusik(const fs::path &, int, int) {\n    throw std::runtime_error(\"setMatusik(): You need to recompile with support for FFTW!\");\n}\n#else\nvoid Layer::setMatusik(const fs::path &path, int ch, int order) {\n    if (ch < 0 || ch >= 3)\n        throw std::runtime_error(\"Channel must be between 1 and 3\");\n    double scale[3] = { 1.0/1500.0, 1.15/1500.0, 1.66/1500.0 };\n\n    FILE *f = fopen(path.str().c_str(), \"rb\");\n    if (f == nullptr)\n        throw std::runtime_error(\"I/O error: could not open file \" + path.str());\n\n    struct {\n        int res_theta_h;\n        int res_theta_d;\n        int res_phi_d;\n    } header;\n\n    if (fread(&header, sizeof(int), 3, f) != 3)\n        throw std::runtime_error(\"I/O error while loading header\");\n\n    Log(\"Loading Matusik-style BRDF data file \\\"%s\\\" (%ix%ix%i)\",\n        path.str(), header.res_theta_h, header.res_theta_d, header.res_phi_d);\n\n    size_t nValues = 3 * header.res_theta_h * header.res_theta_d * header.res_phi_d;\n\n    double *storage = new double[nValues];\n    if (fread(storage, sizeof(double), nValues, f) != nValues)\n        throw std::runtime_error(\"I/O error while loading file contents\");\n\n    fftw_plan_with_nthreads(1);\n\n    order = std::max(order, (int) fourierOrders());\n    int fftSize = order * 4;\n    fftw_plan plan = fftw_plan_r2r_1d(fftSize, NULL, NULL, FFTW_REDFT00, FFTW_ESTIMATE);\n\n    size_t n = resolution(), nEntries = n*n;\n    tbb::spin_mutex mutex;\n    std::vector<Quartet> quartets;\n\n    tbb::parallel_for(\n        tbb::blocked_range<size_t>(0, nEntries, 1),\n        [&](const tbb::blocked_range<size_t> &range) {\n            for (size_t entry = range.begin(); entry < range.end(); ++entry) {\n                int i = entry / n, o = entry % n;\n\n                Float cosThetaI = m_nodes[i],\n                      sinThetaI = std::sqrt(1-cosThetaI*cosThetaI),\n                      cosThetaO = m_nodes[o],\n                      sinThetaO = std::sqrt(1-cosThetaO*cosThetaO);\n\n                Vector wi(sinThetaI, 0, cosThetaI);\n\n                if (cosThetaI * cosThetaO > 0 || cosThetaI < 0)\n                    continue;\n\n                double *data = (double *) fftw_malloc(fftSize * sizeof(double));\n\n                for (int j=0; j<fftSize; ++j) {\n                    Float phi_d = M_PI * j/(Float) (fftSize-1),\n                          cosPhi = std::cos(phi_d),\n                          sinPhi = std::sin(phi_d);\n                    Vector wo(-sinThetaO*cosPhi, -sinThetaO*sinPhi, -cosThetaO);\n\n                    Vector half = (wi + wo).normalized();\n\n                    Float theta_half = std::acos(half.z());\n                    Float phi_half = std::atan2(half.y(), half.x());\n\n                    Vector diff =\n                          Eigen::AngleAxis<Float>(-theta_half, Vector(0, 1, 0)) *\n                         (Eigen::AngleAxis<Float>(-phi_half, Vector(0, 0, 1)) * wi);\n\n                    int theta_half_idx = std::min(std::max(0, (int) std::sqrt(\n                        ((theta_half / (M_PI/2.0))*header.res_theta_h) * header.res_theta_h)), header.res_theta_h-1);\n\n                    Float theta_diff = std::acos(diff.z());\n                    Float phi_diff = std::atan2(diff.y(), diff.x());\n\n                    if (phi_diff < 0)\n                        phi_diff += M_PI;\n\n                    int phi_diff_idx = std::min(std::max(0, int(phi_diff / M_PI * header.res_phi_d)), header.res_phi_d - 1);\n\n                    int theta_diff_idx = std::min(std::max(0, int(theta_diff / (M_PI * 0.5) * header.res_theta_d)),\n                        header.res_theta_d - 1);\n\n                    int ind = phi_diff_idx +\n                        theta_diff_idx * header.res_phi_d +\n                        theta_half_idx * header.res_phi_d * header.res_theta_d;\n\n                    data[j] = storage[ind+ch*header.res_theta_h*header.res_theta_d*header.res_phi_d] * scale[ch] * 2; /// XXX too dark?\n                }\n                double *spectrum = (double *) fftw_malloc(fftSize * sizeof(double));\n                fftw_execute_r2r(plan, data, spectrum);\n\n                for (int j=0; j<fftSize; ++j)\n                    spectrum[j] /= (double) (fftSize-1);\n                spectrum[0] /= 2;\n                spectrum[fftSize-1] /= 2;\n\n                double ref = std::abs(spectrum[0]);\n                size_t sparseSize = 0;\n                double partialSum = 0;\n                if (ref != 0) {\n                    sparseSize = fourierOrders();\n                    for (size_t j= fourierOrders()-1; j>=1; --j) {\n                        double value = (float) spectrum[j];\n                        partialSum += std::abs(value);\n                        if (partialSum <= ref * ERROR_GOAL)\n                            sparseSize = j;\n                    }\n                }\n\n                tbb::spin_mutex::scoped_lock lock(mutex);\n                for (size_t l=0; l<sparseSize; ++l)\n                    quartets.push_back(Quartet(l, o, i, (Float) spectrum[l]));\n                fftw_free(spectrum);\n                fftw_free(data);\n            }\n        }\n    );\n\n    fftw_destroy_plan(plan);\n    delete[] storage;\n\n    setQuartets(quartets);\n    applySurfaceIntegrationWeights(*this);\n}\n#endif\n\nvoid Layer::reverse() {\n    for (auto &m: m_modes)\n        m.reverse();\n}\n\nvoid Layer::clear() {\n    for (auto &m: m_modes)\n        m.clear();\n}\n\nvoid Layer::expand(Float target_tau) {\n    /* Heuristic for choosing the initial width of a layer based on\n       \"Discrete Space Theory of Radiative Transfer\" by Grant and Hunt\n       Proc. R. Soc. London 1969 */\n    Float tau = std::min(m_nodes.cwiseAbs().minCoeff() * 2, (Float) std::pow(2.0, -15.0));\n\n    size_t doublings = (size_t) std::ceil(std::log(target_tau / tau) / std::log(2.0));\n    tau = target_tau * std::pow((Float) 2.0f, -(Float) doublings);\n\n    size_t n = resolution() / 2;\n\n    MatrixS I((int) n, (int) n);\n    I.setIdentity();\n\n    MatrixS rowScale = sparseDiagonal(m_nodes.tail(n).cwiseInverse() * tau);\n\n    tbb::parallel_for(\n        tbb::blocked_range<size_t>(0, fourierOrders(), 1),\n        [&](const tbb::blocked_range<size_t> &range) {\n            for (size_t i = range.begin(); i < range.end(); ++i) {\n                LayerMode &mode = m_modes[i];\n                MatrixS Rt = rowScale * mode.reflectionTop;\n                MatrixS Ttb = I + rowScale * (mode.transmissionTopBottom - I);\n\n                mode.reflectionTop = Rt;\n                mode.reflectionBottom = Rt;\n                mode.transmissionTopBottom = Ttb;\n                mode.transmissionBottomTop = Ttb;\n            }\n        }\n    );\n\n    for (size_t i = 0; i < (size_t) doublings; ++i)\n        addToTop(*this, true);\n}\n\nstd::string Layer::toString() const {\n    size_t nz = 0, nz_max = resolution() * resolution() * fourierOrders();\n    for (auto const &mode: m_modes)\n        nz += mode.nonZeros();\n    std::ostringstream oss;\n    oss.precision(2);\n    oss << \"Layer[resolution=\" << resolution() << \"x\" << resolution()\n        << \", fourierOrders=\" << fourierOrders() << \", nonZeros=\" << nz << \"/\"\n        << nz_max << \" (\" << ((Float) nz / (Float) nz_max * 100) << \"%)]\";\n    return oss.str();\n}\n\nMatrixX Layer::matrix(size_t l) const {\n    if (l >= m_modes.size())\n        throw std::runtime_error(\"Layer::matrix(): out of bounds!\");\n    size_t n = resolution(), h = n / 2;\n    MatrixX M(n, n);\n\n    M.topLeftCorner(h, h)     = m_modes[l].transmissionBottomTop;\n    M.bottomRightCorner(h, h) = m_modes[l].transmissionTopBottom;\n    M.topRightCorner(h, h)    = m_modes[l].reflectionTop;\n    M.bottomLeftCorner(h, h)  = m_modes[l].reflectionBottom;\n\n    for (size_t i = 0; i < n; ++i)\n        M.col(i) /= m_weights[i] * std::abs(m_nodes[i]) * (l == 0 ? 2.f : 1.f) * math::Pi;\n\n    M.block(0, 0, h, n) = M.block(0, 0, h, n).colwise().reverse().eval();\n    M.block(0, 0, h, n) = M.block(0, 0, n, h).rowwise().reverse().eval();\n\n    return M;\n}\n\nFloat Layer::eval(Float mu_o, Float mu_i, Float phi_d) const {\n    int n = m_nodes.size(), h = n / 2;\n    ssize_t offset_o, offset_i;\n    Float weights_o[4], weights_i[4];\n\n    if (mu_o < 0 || (mu_o == 0 && mu_i > 0)) {\n        spline::evalSplineWeights(m_nodes.data() + h, h, -mu_o, offset_o, weights_o, true);\n    } else {\n        spline::evalSplineWeights(m_nodes.data() + h, h, mu_o, offset_o, weights_o, true);\n        offset_o += h;\n    }\n\n    if (mu_i < 0 || (mu_i == 0 && mu_o > 0)) {\n        spline::evalSplineWeights(m_nodes.data() + h, h, -mu_i, offset_i, weights_i, true);\n    } else {\n        spline::evalSplineWeights(m_nodes.data() + h, h, mu_i, offset_i, weights_i, true);\n        offset_i += h;\n    }\n\n    Float result = 0;\n    for (size_t l=0; l<fourierOrders(); ++l) {\n        Float sum = 0;\n        for (int o = 0; o < 4; ++o) {\n            for (int i = 0; i < 4; ++i) {\n                Float weight = weights_o[o] * weights_i[i];\n                if (weight == 0)\n                    continue;\n                weight /= \n                    std::abs(m_nodes[offset_i + i]) *\n                    m_weights[offset_i + i] *\n                    (l == 0 ? 2 : 1);\n\n                sum += m_modes[l].coeff(offset_o + o, offset_i + i) * weight;\n            }\n        }\n        result += sum * std::cos(phi_d * l);\n    }\n\n    return std::max((Float) 0.f, result / math::Pi);\n}\n\nstd::string LayerMode::toString() const {\n    size_t nz = nonZeros(), nz_max = resolution() * resolution();\n    std::ostringstream oss;\n    oss.precision(2);\n    oss << \"LayerMode[resolution=\" << resolution() << \"x\" << resolution()\n        << \", nonZeros=\" << nz << \"/\" << nz_max << \" (\"\n        << ((Float) nz / (Float) nz_max * 100) << \"%)]\";\n    return oss.str();\n}\n\nstd::pair<int, int> parameterHeuristicMicrofacet(Float alpha, std::complex<Float> &eta) {\n    alpha = std::min(alpha, (Float) 1);\n    if (eta.real() < 1 && eta.imag() == 0)\n        eta = std::complex<Float>(1.f) / eta;\n\n    static const Float c[][9] = {\n        /* IOR    A_n      B_n     C_n       D_n      A_m      B_m      C_m      D_m                                 */\n        {  0.0, 35.275,  14.136,  29.287,  1.8765,   39.814,  88.992, -98.998,  39.261  },  /* Generic conductor     */\n        {  1.1, 256.47, -73.180,  99.807,  37.383,  110.782,  57.576,  94.725,  14.001  },  /* Dielectric, eta = 1.1 */\n        {  1.3, 100.264, 28.187,  64.425,  14.850,   45.809,  17.785, -7.8543,  12.892  },  /* Dielectric, eta = 1.3 */\n        {  1.5, 74.176,  27.470,  42.454,  9.6437,   31.700,  44.896, -45.016,  19.643  },  /* Dielectric, eta = 1.5 */\n        {  1.7, 80.098,  17.016,  50.656,  7.2798,   46.549,  58.592, -73.585,  25.473  },  /* Dielectric, eta = 1.7 */\n    };\n\n    int i0 = 0, i1 = 0;\n\n    if (eta.imag() == 0) { /* Dielectric case */\n        for (int i=1; i<4; ++i) {\n            if (eta.real() >= c[i][0] && eta.real() <= c[i+1][0]) {\n                if (std::abs(eta.real()-c[i][0]) < 0.05f) {\n                    i1 = i0 = i;\n                } else if (std::abs(eta-c[i+1][0]) < 0.05f) {\n                    i0 = i1 = i+1;\n                } else {\n                    i0 = i; i1 = i+1;\n                }\n            }\n        }\n\n        if (!i0)\n            throw std::runtime_error(\"Index of refraction is out of bounds (must be between 1.1 and 1.7)!\");\n    }\n\n    Float n0 = std::max(c[i0][1] + c[i0][2]*std::pow(std::log(alpha), (Float) 4)*alpha, c[i0][3]+c[i0][4]*std::pow(alpha, (Float) -1.2f));\n    Float n1 = std::max(c[i1][1] + c[i1][2]*std::pow(std::log(alpha), (Float) 4)*alpha, c[i1][3]+c[i1][4]*std::pow(alpha, (Float) -1.2f));\n    Float m0 = std::max(c[i0][5] + c[i0][6]*std::pow(std::log(alpha), (Float) 4)*alpha, c[i0][7]+c[i0][8]*std::pow(alpha, (Float) -1.2f));\n    Float m1 = std::max(c[i1][5] + c[i1][6]*std::pow(std::log(alpha), (Float) 4)*alpha, c[i1][7]+c[i1][8]*std::pow(alpha, (Float) -1.2f));\n\n    int n_i = (int) std::ceil(std::max(n0, n1));\n    int m_i = (int) std::ceil(std::max(m0, m1));\n\n    if (n_i % 2 == 1)\n        n_i += 1;\n\n    return std::make_pair(n_i, m_i);\n}\n\nstd::pair<int, int> parameterHeuristicHG(Float g) {\n    g = std::abs(g);\n    Float m = 5.4f/(1.0f - g) - 1.3f;\n    Float n = 8.6f/(1.0f - g) - 0.2f;\n    int n_i = (int) std::ceil(n), m_i = (int) std::ceil(m);\n    if (n_i % 2 == 1)\n        n_i += 1;\n    return std::make_pair(n_i, m_i);\n}\n\nNAMESPACE_END(layer)\n", "meta": {"hexsha": "e11ebfc354ce58be15bc4110d21cc3571f67d262", "size": 30906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/layer.cpp", "max_stars_repo_name": "wjakob/layerlab", "max_stars_repo_head_hexsha": "3e5257e3076a7287d1da9bbd4ee3f05fe37d3ee3", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2015-07-31T05:20:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-05T13:21:33.000Z", "max_issues_repo_path": "src/layer.cpp", "max_issues_repo_name": "wjakob/layerlab", "max_issues_repo_head_hexsha": "3e5257e3076a7287d1da9bbd4ee3f05fe37d3ee3", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-08-17T20:50:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-07T11:27:04.000Z", "max_forks_repo_path": "src/layer.cpp", "max_forks_repo_name": "wjakob/layerlab", "max_forks_repo_head_hexsha": "3e5257e3076a7287d1da9bbd4ee3f05fe37d3ee3", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2015-08-03T01:09:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-25T15:45:42.000Z", "avg_line_length": 40.8269484808, "max_line_length": 138, "alphanum_fraction": 0.5385362066, "num_tokens": 8445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.43915704955301865}}
{"text": "/*\n\nPICCANTE\nThe hottest HDR imaging library!\nhttp://vcg.isti.cnr.it/piccante\n\nCopyright (C) 2014\nVisual Computing Laboratory - ISTI CNR\nhttp://vcg.isti.cnr.it\nFirst author: Francesco Banterle\n\nThis Source Code Form is subject to the terms of the Mozilla Public\nLicense, v. 2.0. If a copy of the MPL was not distributed with this\nfile, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n*/\n\n#ifndef PIC_FILTERING_FILTER_WLS_HPP\n#define PIC_FILTERING_FILTER_WLS_HPP\n\n#include \"../filtering/filter.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n#ifndef PIC_EIGEN_NOT_BUNDLED\n    #include \"../externals/Eigen/Sparse\"\n    #include \"../externals/Eigen/src/SparseCore/SparseMatrix.h\"\n#else\n    #include <Eigen/Sparse>\n    #include <Eigen/src/SparseCore/SparseMatrix.h>\n#endif\n\n#endif\n\nnamespace pic {\n\n#ifndef PIC_DISABLE_EIGEN\n\nclass FilterWLS: public Filter\n{\nprotected:\n    /**\n     * @brief singleChannel applies WLS smoothing filter for gray-scale images.\n     * @param imgIn\n     * @param imgOut\n     * @return\n     */\n    Image *singleChannel(ImageVec imgIn, Image *imgOut)\n    {\n        Image *L = imgIn[0];\n\n        int width  = L->width;\n        int height = L->height;\n        int tot    = height * width;\n\n        Eigen::VectorXd b, x;\n        b = Eigen::VectorXd::Zero(tot);\n\n        #ifdef PIC_DEBUG\n            printf(\"Init matrix...\");\n        #endif\n\n        std::vector< Eigen::Triplet< double > > tL;\n\n        for(int i = 0; i < height; i++) {\n            int tmpInd = i * width;\n\n            for(int j = 0; j < width; j++) {\n\n                float Ltmp, tmp;\n                int indJ;\n                int indI = tmpInd + j;\n                float Lref = L->data[indI];\n\n                b[indI] = Lref;\n\n                float sum = 0.0f;\n\n                if((i - 1) >= 0) {\n                    indJ = indI - width;\n                    Ltmp = L->data[indJ];\n                    tmp  = -lambda / (powf(fabsf(Ltmp - Lref), alpha) + epsilon);\n                    tL.push_back(Eigen::Triplet< double > (indI, indJ, tmp));\n                    sum += tmp;\n                }\n\n                if((i + 1) < height) {\n                    indJ = indI + width;\n                    Ltmp = L->data[indJ];\n                    tmp  = -lambda / (powf(fabsf(Ltmp - Lref), alpha) + epsilon);\n                    tL.push_back(Eigen::Triplet< double > (indI, indJ, tmp));\n                    sum += tmp;\n                }\n\n                if((j - 1) >= 0) {\n                    indJ = indI - 1;\n                    Ltmp = L->data[indJ];\n                    tmp  = -lambda / (powf(fabsf(Ltmp - Lref), alpha) + epsilon);\n                    tL.push_back(Eigen::Triplet< double > (indI, indJ, tmp));\n                    sum += tmp;\n                }\n\n                if((j + 1) < width) {\n                    indJ = indI + 1;\n                    Ltmp = L->data[indJ];\n                    tmp  = -lambda / (powf(fabsf(Ltmp - Lref), alpha) + epsilon);\n                    tL.push_back(Eigen::Triplet< double > (indI, indJ, tmp));\n                    sum += tmp;\n                }\n\n                tL.push_back(Eigen::Triplet< double > (indI, indI, 1.0f - sum));\n            }\n        }\n\n        #ifdef PIC_DEBUG\n            printf(\"Ok\\n\");\n        #endif\n\n        Eigen::SparseMatrix<double> A = Eigen::SparseMatrix<double>(tot, tot);\n        A.setFromTriplets(tL.begin(), tL.end());\n\n        Eigen::SimplicialCholesky<Eigen::SparseMatrix<double> > solver(A);\n        x = solver.solve(b);\n\n        if(solver.info() != Eigen::Success) {\n            #ifdef PIC_DEBUG\n                printf(\"SOLVER FAILED!\\n\");\n            #endif\n            return NULL;\n        }\n\n        #ifdef PIC_DEBUG\n            printf(\"SOLVER SUCCESS!\\n\");\n        #endif\n\n        #pragma omp parallel for\n\n        for(int i = 0; i < tot; i++) {\n            imgOut->data[i] = float(x(i));\n        }\n\n        return imgOut;\n    }\n\n    /**\n     * @brief multiChannel applies WLS filter for color images.\n     * @param imgIn\n     * @param imgOut\n     * @return\n     */\n    Image *multiChannel(ImageVec imgIn, Image *imgOut)\n    {\n        Image *img = imgIn[0];\n\n        int width  = img->width;\n        int height = img->height;\n        int tot    = height * width;\n\n        alpha /= 2.0f;\n\n        int stridex = width * img->channels;\n\n        #ifdef PIC_DEBUG\n            printf(\"Init matrix...\");\n        #endif\n\n        std::vector< Eigen::Triplet< double > > tL;\n\n        for(int i = 0; i < height; i++) {\n            int tmpInd = i * width;\n\n            for(int j = 0; j < width; j++) {\n\n                float sum = 0.0f;\n                float tmp;\n                int indJ;\n                int indI = tmpInd + j;\n                int indImg = indI * img->channels;\n\n                if((i - 1) >= 0) {\n                    indJ = indImg - stridex;\n                    float diff = 0.0f;\n\n                    for(int p = 0; p < img->channels; p++) {\n                        float tmpDiff = img->data[indJ + p] - img->data[indImg + p];\n                        diff += tmpDiff * tmpDiff;\n                    }\n\n                    tmp  = -lambda / (powf(diff, alpha) + epsilon);\n\n                    tL.push_back(Eigen::Triplet< double > (indI, indI - width , tmp));\n\n                    sum += tmp;\n                }\n\n                if((i + 1) < height) {\n                    indJ = indImg + stridex;\n                    float diff = 0.0f;\n\n                    for(int p = 0; p < img->channels; p++) {\n                        float tmpDiff = img->data[indJ + p] - img->data[indImg + p];\n                        diff += tmpDiff * tmpDiff;\n                    }\n\n                    tmp  = -lambda / (powf(diff, alpha) + epsilon);\n                    tL.push_back(Eigen::Triplet< double > (indI, indI + width , tmp));\n                    sum += tmp;\n                }\n\n                if((j - 1) >= 0) {\n                    indJ = indImg - img->channels;\n                    float diff = 0.0f;\n\n                    for(int p = 0; p < img->channels; p++) {\n                        float tmpDiff = img->data[indJ + p] - img->data[indImg + p];\n                        diff += tmpDiff * tmpDiff;\n                    }\n\n                    tmp  = -lambda / (powf(diff, alpha) + epsilon);\n                    tL.push_back(Eigen::Triplet< double > (indI, indI - 1 , tmp));\n                    sum += tmp;\n                }\n\n                if((j + 1) < width) {\n                    indJ = indImg + img->channels;\n                    float diff = 0.0f;\n\n                    for(int p = 0; p < img->channels; p++) {\n                        float tmpDiff = img->data[indJ + p] - img->data[indImg + p];\n                        diff += tmpDiff * tmpDiff;\n                    }\n\n                    tmp  = -lambda / (powf(diff, alpha) + epsilon);\n\n                    tL.push_back(Eigen::Triplet< double > (indI, indI + 1 , tmp));\n                    sum += tmp;\n                }\n\n                tL.push_back(Eigen::Triplet< double > (indI, indI, 1.0f - sum));\n            }\n        }\n\n        #ifdef PIC_DEBUG\n            printf(\"Ok\\n\");\n        #endif\n\n        Eigen::SparseMatrix<double> A = Eigen::SparseMatrix<double>(tot, tot);\n\n        A.setFromTriplets(tL.begin(), tL.end());\n\n        Eigen::SimplicialCholesky< Eigen::SparseMatrix< double > > solver(A);\n\n        for(int i = 0; i < imgOut->channels; i++) {\n            Eigen::VectorXd b, x;\n\n            b = Eigen::VectorXd::Zero(tot);\n            #pragma omp parallel for\n\n            for(int j = 0; j < tot; j++) {\n                b[j] = img->data[j * img->channels + i];\n            }\n\n            x = solver.solve(b);\n\n            if(solver.info() == Eigen::Success) {\n\n                #ifdef PIC_DEBUG\n                    printf(\"SOLVER SUCCESS!\\n\");\n                #endif\n\n                #pragma omp parallel for\n\n                for(int j = 0; j < tot; j++) {\n                    imgOut->data[j * imgOut->channels + i] = float(x(j));\n                }\n            } else {\n                #ifdef PIC_DEBUG\n                    printf(\"SOLVER FAILED!\\n\");\n                #endif\n            }\n\n        }\n\n        return imgOut;\n    }\n\n    float alpha, lambda, epsilon;\n\npublic:\n\n    /**\n     * @brief FilterWLS\n     */\n    FilterWLS() : Filter()\n    {\n        update(1.2f, 1.0f);\n    }\n\n    /**\n     * @brief FilterWLS\n     * @param alpha\n     * @param lambda\n     */\n    FilterWLS(float alpha, float lambda) : Filter()\n    {\n        update(alpha, lambda);\n    }\n\n    /**\n     * @brief update\n     * @param alpha\n     * @param lambda\n     */\n    void update(float alpha, float lambda)\n    {\n        epsilon = 0.0001f;\n\n        if(alpha <= 0.0f) {\n            alpha = 1.2f;\n        }\n\n        if(lambda <= 0.0f) {\n            lambda = 1.0f;\n        }\n\n        this->alpha = alpha;\n        this->lambda = lambda;\n    }\n\n    /**\n     * @brief Process\n     * @param imgIn\n     * @param imgOut\n     * @return\n     */\n    Image *Process(ImageVec imgIn, Image *imgOut)\n    {\n        if(imgIn.empty()){\n            return imgOut;\n        }\n\n        if(imgIn[0] == NULL) {\n            return imgOut;\n        }\n\n        imgOut = setupAux(imgIn, imgOut);\n\n        if(imgOut == NULL) {\n            return imgOut;\n        }\n\n        //convolution\n        if(imgIn[0]->channels == 1) {\n            return singleChannel(imgIn, imgOut);\n        } else {\n            return multiChannel(imgIn, imgOut);\n        }\n    }\n\n    /**\n     * @brief main\n     * @param argc\n     * @param argv\n     * @return\n     */\n    static int main(int argc, char* argv[])\n    {\n        if(argc < 4) {\n            printf(\"Usage: name_input alpha lambad\\n\");\n            return 0;\n        }\n\n        std::string nameIn = argv[1];\n        std::string name = removeExtension(nameIn);\n        std::string ext = getExtension(nameIn);\n\n        float alpha = float(atof(argv[2]));\n        float lambda = float(atof(argv[3]));\n\n        std::string nameOut = name + \"_wls.\" + ext; \n\n        Image img(nameIn);\n\n        FilterWLS *filter = new FilterWLS(alpha, lambda);\n\n        filter->Process(Single(&img), NULL)->Write(nameOut);\n\n        return 0;\n    }\n};\n#endif\n\n} // end namespace pic\n\n#endif /* PIC_FILTERING_FILTER_WLS_HPP */\n\n", "meta": {"hexsha": "48a989180c559615625ed5490ae87be3ca60c412", "size": 10185, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/filtering/filter_wls.hpp", "max_stars_repo_name": "ecarpita93/HPC_projet_1", "max_stars_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/filtering/filter_wls.hpp", "max_issues_repo_name": "ecarpita93/HPC_projet_1", "max_issues_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/filtering/filter_wls.hpp", "max_forks_repo_name": "ecarpita93/HPC_projet_1", "max_forks_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6549118388, "max_line_length": 86, "alphanum_fraction": 0.4486990673, "num_tokens": 2607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4391257571426389}}
{"text": "//\n//  Copyright (C) 2020 Brian P. Kelley\n//\n//   @@ All Rights Reserved @@\n//  This file is part of the RDKit.\n//  The contents are covered by the terms of the BSD license\n//  which is included in the file license.txt, found at the root\n//  of the RDKit source tree.\n//\n#ifdef RDK_HAS_EIGEN3\n#include \"BCUT.h\"\n#include \"Crippen.h\"\n#include <Eigen/Dense>\n#include <GraphMol/RDKitBase.h>\n#include \"GraphMol/PartialCharges/GasteigerCharges.h\"\n#include \"GraphMol/PartialCharges/GasteigerParams.h\"\n#include <RDGeneral/types.h>\n\nnamespace RDKit {\nnamespace Descriptors {\n  // diagonal elements are a property (atomic num, charge, etc)\n  // off diagonal are 1/sqrt(bond_order)\n  //  Original burden matrix was .1, .2, .3, .15 for single,double,triple or aromatic\n  //  all other elements are .001\nnamespace {\nstd::unique_ptr<Eigen::MatrixXd>  make_burden(const ROMol &m) {\n  auto num_atoms = m.getNumAtoms();\n  std::unique_ptr<Eigen::MatrixXd> burden(\n\t new Eigen::MatrixXd(num_atoms, num_atoms));\n    \n  for(unsigned int i=0;i<num_atoms; ++i) {\n    for(unsigned int j=0;j<num_atoms; ++j) {\n      (*burden)(i,j) = (*burden)(j,i) = 0.001;\n    }\n  }\n  \n  for(auto &bond : m.bonds()) {\n    unsigned int i = bond->getBeginAtomIdx();\n    unsigned int j = bond->getEndAtomIdx();\n    double score = 0.0;\n    switch(bond->getBondType()) {\n    case Bond::AROMATIC:\n      // score = 0.15; orig burden\n      score = 0.8164965809277261; // 1/sqrt(1.5)\n      break;\n    case Bond::SINGLE:\n      // score = 0.1;\n      score = 1.0; // 1/sqrt(1.0)\n      break;\n    case Bond::DOUBLE:\n      // score = 0.2;\n      score = 0.7071067811865475; // 1/sqrt(2.0)\n      break;\n    case Bond::TRIPLE:\n      // score = 0.3;\t\n      score = 0.5773502691896258; // 1/sqrt(3);\n      break;\n    default:\n      CHECK_INVARIANT(0, \"Bond order must be Single, Double, Triple or Aromatic\");\n    }\n    (*burden)(i,j) = (*burden)(j,i) = score;\n  }    \n  return burden;\n}\n  \nstd::pair<double,double> BCUT2D(std::unique_ptr<Eigen::MatrixXd> &burden,\n\t\t\t\tconst std::vector<double> &atom_props) {\n  for(unsigned int i=0; i<atom_props.size(); ++i) {\n    (*burden)(i,i) = atom_props[i];\n  }\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(*burden);\n  auto eivals = es.eigenvalues();\n  double lowest = eivals(0);\n  double highest = eivals(atom_props.size()-1);\n  return std::pair<double,double>(highest,lowest);\n}\n}\n    \nstd::pair<double,double> BCUT2D(const ROMol &m, const std::vector<double> &atom_props) {\n  unsigned int num_atoms = m.getNumAtoms();\n  PRECONDITION(atom_props.size() == num_atoms, \"Number of atom props not equal to number of atoms\");\n  \n  if (num_atoms == 0) {\n    return std::pair<double,double>(0,0);\n  }\n  auto burden = make_burden(m);\n  return BCUT2D(burden, atom_props);\n}\n  \nstd::pair<double,double> BCUT2D(const ROMol &m, const std::string &atom_double_prop) {\n  std::vector<double> props;\n  props.reserve(m.getNumAtoms());\n  for(auto &atom : m.atoms()) {\n    props.push_back(atom->getProp<double>(atom_double_prop));\n  }\n  return BCUT2D(m, props);\n}\n\nstd::vector<double> BCUT2D(const ROMol &m) {\n  std::unique_ptr<ROMol> mol(MolOps::removeHs(m));\n  std::vector<double> masses;\n  std::vector<double> charges;\n  unsigned int num_atoms = mol->getNumAtoms();\n  masses.reserve(num_atoms);\n  charges.reserve(num_atoms);\n\n  RDKit::computeGasteigerCharges(*mol, 12, true);\n  for(auto &atom: mol->atoms()) {\n    masses.push_back(atom->getMass());\n    charges.push_back(atom->getProp<double>(common_properties::_GasteigerCharge));\n  }\n  \n  std::vector<double> slogp(num_atoms, 0.0);\n  std::vector<double> cmr(num_atoms, 0.0);\n  getCrippenAtomContribs(*mol, slogp, cmr);\n  \n  // polarizability? - need model\n  // slogp?  sasa?\n  auto burden = make_burden(m);\n  auto atom_bcut = BCUT2D(burden, masses);\n  auto gasteiger = BCUT2D(burden, charges);\n  auto logp = BCUT2D(burden, slogp);\n  auto mr = BCUT2D(burden, cmr);\n  std::vector<double> res = {atom_bcut.first, atom_bcut.second,\n\t\t\t     gasteiger.first, gasteiger.second,\n\t\t\t     logp.first, logp.second,\n\t\t\t     mr.first, mr.second\n  };\n  return res;\n}\n}\n}\n\n#endif\n", "meta": {"hexsha": "a0b23a5d749bee8a338b724ce17bbe76237ceea6", "size": 4088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Descriptors/BCUT.cpp", "max_stars_repo_name": "jungb-basf/rdkit", "max_stars_repo_head_hexsha": "5d0eb77c655b6ba91f0891e7dc51e658aced3d00", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T14:52:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T08:12:45.000Z", "max_issues_repo_path": "Code/GraphMol/Descriptors/BCUT.cpp", "max_issues_repo_name": "jungb-basf/rdkit", "max_issues_repo_head_hexsha": "5d0eb77c655b6ba91f0891e7dc51e658aced3d00", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-08-08T13:53:40.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-08T05:52:07.000Z", "max_forks_repo_path": "Code/GraphMol/Descriptors/BCUT.cpp", "max_forks_repo_name": "bp-kelley/rdkit", "max_forks_repo_head_hexsha": "e0de7c9622ce73894b1e7d9568532f6d5638058a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-15T15:48:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T15:48:44.000Z", "avg_line_length": 30.2814814815, "max_line_length": 100, "alphanum_fraction": 0.6587573386, "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4391257519909226}}
{"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_FACESFROMTETS_HPP\n#define MCL_FACESFROMTETS_HPP 1\n\n#include <Eigen/Dense>\n#include <set>\n\nnamespace mcl\n{\n\n// Given a tet mesh T, compute surface triangles F.\n// True on success\ntemplate <typename DerivedT, typename DerivedF>\nstatic inline bool faces_from_tets(\n\tconst Eigen::MatrixBase<DerivedT> &T,\n\tEigen::PlainObjectBase<DerivedF> &F)\n{\n\tusing namespace Eigen;\n\tstruct FaceKey\n\t{\n\t\tFaceKey() : f(Vector3i::Zero()), f_sorted(Vector3i::Zero()) {}\n\t\tFaceKey(int f0, int f1, int f2)\n\t\t{\n\t\t\tf = Vector3i(f0, f1, f2);\n\t\t\tf_sorted = f;\n\t\t\tmcl::sort3(f_sorted[0], f_sorted[1], f_sorted[2]);\n\t\t}\n\t\tVector3i f;\n\t\tVector3i f_sorted;\n\t\tbool operator<(const FaceKey& other) const\n\t\t{\n\t\t\tfor (int i=0; i<3; ++i)\n\t\t\t{\n\t\t\t\tif (f_sorted[i] < other.f_sorted[i]) { return true; }\n\t\t\t\tif (f_sorted[i] > other.f_sorted[i]) { return false; }\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tif (T.rows()==0 || T.cols()!=4) {\n\t\treturn false;\n\t}\n\n\tstd::set<FaceKey> faces;\n\tstd::set<FaceKey> faces_seen_twice;\n\tint n_tets = T.rows();\n\tint total_faces = 0;\n\tfor (int t=0; t<n_tets; ++t)\n\t{\n\t\ttotal_faces += 4;\n\t\tint p0 = T(t,0);\n\t\tint p1 = T(t,1);\n\t\tint p2 = T(t,2);\n\t\tint p3 = T(t,3);\n\t\tFaceKey curr_faces[4] = {\n\t\t\tFaceKey(p0, p1, p3),\n\t\t\tFaceKey(p0, p2, p1),\n\t\t\tFaceKey(p0, p3, p2),\n\t\t\tFaceKey(p1, p2, p3) };\n\n\t\tfor (int f=0; f<4; ++f)\n\t\t{\n\t\t\tconst FaceKey &curr_face = curr_faces[f];\n\t\t\t// We've already seen the face at least twice.\n\t\t\tif (faces_seen_twice.count(curr_face)>0) { continue; }\n\t\t\t// Check that we don't already have the face\n\t\t\ttypename std::set<FaceKey>::iterator it = faces.find(curr_face);\n\t\t\tif (it != faces.end())\n\t\t\t{\n\t\t\t\tfaces.erase(it);\n\t\t\t\tfaces_seen_twice.insert(curr_face);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// Otherwise, add it to faces\n\t\t\tfaces.insert(curr_face);\n\t\t} // end loop faces\n\n\t} // end loop tets\n\n\tint nf = faces.size();\n\tF.resize(nf, 3);\n\ttypename std::set<FaceKey>::const_iterator fit = faces.begin();\n\tfor (int f_idx=0; fit != faces.end(); ++fit, ++f_idx) {\n\t\tF.row(f_idx) = fit->f;\n\t}\n\n\treturn true;\n}\n\n} // ns mcl\n\n#endif\n", "meta": {"hexsha": "b194dc7488e8ec3d67f9e6434800e25ae4cd5089", "size": 2102, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/FacesFromTets.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/MCL/FacesFromTets.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/FacesFromTets.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8958333333, "max_line_length": 67, "alphanum_fraction": 0.6303520457, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.43910891283240555}}
{"text": "#include <iostream>\n\n#include <cstdlib>\n#include <cmath>\n\n#include <armadillo>\n\n#include \"Conv2D/Mesh.hpp\"\n#include \"Conv2D/EulerDefaultBase.hpp\"\n\ndouble uniform(double a, double b)\n{\n    return a + ((b - a) * std::rand() / RAND_MAX);\n}\n\ndouble consistencyTestError(double gamma, const EulerDefaultBase &problem)\n{\n    // construct random unit normal\n    const double nx = uniform(-1.0, 1.0);\n    const double ny = uniform(-1.0, 1.0);\n    const double nl = std::hypot(nx, ny);\n    const arma::rowvec n {nx / nl, ny / nl};\n\n    // construct a state\n    const double rho = uniform( 0.0, 1.0);\n    const double u = uniform(-1.0, 1.0);\n    const double v = uniform(-1.0, 1.0);\n    const double e = uniform( 0.0, 1.0);\n    const double E = e + 0.5 * (u * u + v * v);\n    const arma::vec U {rho, rho * u, rho * v, rho * E};\n\n    // compute analytical flux\n    const double p = (gamma - 1.0) * rho * e;\n    const double H = E + p / rho;\n    const arma::vec F {\n            n[0] * (rho * u)         + n[1] * (rho * v),\n            n[0] * (rho * u * u + p) + n[1] * (rho * u * v),\n            n[0] * (rho * u * v)     + n[1] * (rho * v * v + p),\n            n[0] * (rho * u * H)     + n[1] * (rho * v * H)};\n\n    // compute Roe flux\n    arma::vec FHat(4);\n    double s;\n    problem.computeRoeFlux(U, U, n, FHat, s);\n\n    // return error\n    return arma::norm(F - FHat);\n}\n\ndouble flipTestError(const EulerDefaultBase &problem)\n{\n    // construct random oppsing unit normals\n    const double nx = uniform(-1.0, 1.0);\n    const double ny = uniform(-1.0, 1.0);\n    const double nl = std::hypot(nx, ny);\n    const arma::rowvec nLR { nx / nl,  ny / nl};\n    const arma::rowvec nRL {-nx / nl, -ny / nl};\n\n    // construct left state\n    const double rhoL = uniform( 0.0, 1.0);\n    const double uL = uniform(-1.0, 1.0);\n    const double vL = uniform(-1.0, 1.0);\n    const double EL = uniform( 0.0, 1.0) + 0.5 * (uL * uL + vL * vL);\n    const arma::vec UL {rhoL, rhoL * uL, rhoL * vL, rhoL * EL};\n\n    // construct right state\n    const double rhoR = uniform( 0.0, 1.0);\n    const double uR   = uniform(-1.0, 1.0);\n    const double vR   = uniform(-1.0, 1.0);\n    const double ER   = uniform( 0.0, 1.0) + 0.5 * (uR * uR + vR * vR);\n    const arma::vec UR {rhoR, rhoR * uR, rhoR * vR, rhoR * ER};\n\n    // temporary variable to store wave speed, not used here!\n    double s;\n\n    // compute Roe flux from left to right\n    arma::vec FHatLR(4);\n    problem.computeRoeFlux(UL, UR, nLR, FHatLR, s);\n\n    // compute Roe flux from right to left\n    arma::vec FHatRL(4);\n    problem.computeRoeFlux(UR, UL, nRL, FHatRL, s);\n\n    // return error\n    return arma::norm(FHatLR + FHatRL);\n}\n\ndouble supersonicTestError(double gamma, const EulerDefaultBase &problem)\n{\n    // construct normal that points north-east\n    const double nx = uniform(0.0, 1.0);\n    const double ny = uniform(0.0, 1.0);\n    const double nl = std::hypot(nx, ny);\n    const arma::rowvec n {nx / nl, ny / nl};\n\n    // construct supersonic state on the left\n    const double rhoL = uniform(0.0, 1.0);\n    const double uL   = uniform(0.8, 1.0);\n    const double vL   = uniform(0.8, 1.0);\n    const double eL   = uniform(0.0, 1.0);\n    const double EL   = eL + 0.5 * (uL * uL + vL * vL);\n\n    const arma::vec UL {rhoL, rhoL * uL, rhoL * vL, rhoL * EL};\n\n    // construct supersonic state on the right\n    const double rhoR = uniform(0.0, 1.0);\n    const double uR   = uniform(0.8, 1.0);\n    const double vR   = uniform(0.8, 1.0);\n    const double eR   = uniform(0.0, 1.0);\n    const double ER   = eR + 0.5 * (uR * uR + vR * vR);\n\n    const arma::vec UR {rhoR, rhoR * uR, rhoR * vR, rhoR * ER};\n\n    // compute Roe flux\n    arma::vec FHat(4);\n    double s;\n    problem.computeRoeFlux(UL, UR, n, FHat, s);\n\n    // compute analytical flux on the left\n    const double pL = (gamma - 1.0) * rhoL * eL;\n    const double HL = EL + pL / rhoL;\n\n    const arma::vec FL {\n            n[0] * (rhoL * uL)           + n[1] * (rhoL * vL),\n            n[0] * (rhoL * uL * uL + pL) + n[1] * (rhoL * uL * vL),\n            n[0] * (rhoL * uL * vL)      + n[1] * (rhoL * vL * vL + pL),\n            n[0] * (rhoL * uL * HL)      + n[1] * (rhoL * vL * HL)};\n\n    // return error\n    return arma::norm(FHat - FL);\n}\n\nint main()\n{\n    // random seed\n    std::srand(1279);\n\n    // this choice is gamma is very important for supersonic test!\n    const double gamma = 1.4;\n\n    // set up problem\n    EulerDefaultBase problem;\n    problem.setSpecificHeatRatio(gamma);\n\n    // report errors\n    std::cout << \"L2 errors in\" << std::endl\n              << \"  Consistency test: \" << std::scientific\n              << consistencyTestError(gamma, problem) << std::endl\n              << \"  Flip test       : \" << std::scientific\n              << flipTestError(problem) << std::endl\n              << \"  Supersonic test : \" << std::scientific\n              << supersonicTestError(gamma, problem) << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "26de33722b54ddac601d0e87c09861f53c060d93", "size": 4926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/RoeFlux.cpp", "max_stars_repo_name": "saibalde/Aerosp623Project2", "max_stars_repo_head_hexsha": "cfa1c725f370404b2a2cee463d51826b9592d066", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/RoeFlux.cpp", "max_issues_repo_name": "saibalde/Aerosp623Project2", "max_issues_repo_head_hexsha": "cfa1c725f370404b2a2cee463d51826b9592d066", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/RoeFlux.cpp", "max_forks_repo_name": "saibalde/Aerosp623Project2", "max_forks_repo_head_hexsha": "cfa1c725f370404b2a2cee463d51826b9592d066", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5769230769, "max_line_length": 74, "alphanum_fraction": 0.5544051969, "num_tokens": 1696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.43883442145044654}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n/// Copyright 2018-present Xinyan DAI<xinyan.dai@outlook.com>\n///\n/// permission is hereby granted, free of charge, to any person obtaining a copy\n/// of this software and associated documentation files (the \"Software\"), to\n/// deal in the Software without restriction, including without limitation the\n/// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n/// sell copies of the Software, and to permit persons to whom the Software is\n/// furnished to do so, subject to the following conditions:\n///\n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions ofthe Software.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n/// IN THE SOFTWARE.\n\n/// @version 0.1\n/// @author  Xinyan DAI\n/// @contact xinyan.dai@outlook.com\n//////////////////////////////////////////////////////////////////////////////\n\n\n\n#pragma once\n\n#include <utility>\n#include <vector>\n#include <random>\n#include <unordered_map>\n#include <boost/progress.hpp>\n\n#include \"../index.hpp\"\n\nnamespace ss {\n\n    using std::vector;\n\n    template<class DataType>\n    class KMeansIndex : public Index<DataType> {\n    protected:\n        /// _center[i] means the i'th center's coordinate\n        vector<vector<DataType > >     _centers;\n        /// _points[i] means all points' indexes belong to i'th center\n        /// _points[i][j] means the j'th point's index belongs to i'th center\n        vector<vector<int > >          _points;\n    public:\n        explicit KMeansIndex(const parameter& para) :\n                Index<DataType >(para),\n                _centers(para.kmeans_centers),\n                _points(para.kmeans_centers) {}\n\n        const vector<vector<DataType > > & get_centers() const { return _centers; }\n        const vector<vector<int > >      & get_points()  const { return _points; }\n\n        void reset(int num_centers) {\n            this->_centers = vector<vector<DataType > >(num_centers);\n            this->_points = vector<vector<int > >(num_centers);\n        }\n\n        void set_centers(const vector<vector<DataType > >& centers) {\n            _centers = centers;\n        }\n\n        void Train(const Matrix<DataType > & data) override {\n            Iterate(Visitor<DataType >(data, 0, data.getDim()));\n        }\n\n\n        void Add(const Matrix<DataType > & data) override {\n            Assign(Visitor<DataType >(data, 0, data.getDim()));\n        }\n\n        void Search(const DataType *query, const std::function<void (int)>& prober) override {\n            const vector<int>& idx = _points[NearestCenter(query, _centers[0].size())];\n            for (int id : idx) {\n                prober(id);\n            }\n        }\n\n        const vector<int>& Search(const DataType *query)  {\n            return  _points[NearestCenter(query, _centers[0].size())];\n        }\n\n        /***\n         * iteratively update centers and re-assign points\n         * @param data\n         */\n        void Iterate(const Visitor<DataType> & data) {\n\n            /// initialize centers\n            /// TODO(Xinyan): should initialized randomly\n            for(int i=0; i<_centers.size(); i++) {\n                _centers[i] = vector<DataType >(data[i], data[i]+data.getDim());\n            }\n\n            boost::progress_display progress(this->_para.iteration);\n            for (int iter = 0; iter < this->_para.iteration; ++iter, ++progress) {\n\n                /// Assignment\n                Assign(data);\n                /// UpdateCenter\n                Update(data);\n                /// clear points in each centers\n                for (int c = 0; c<_points.size(); c++) {\n                    _points[c].clear();\n                }\n            }\n        }\n\n        /**\n         * re-calculate center by averaging points' coordinate\n         */\n        void Update(const Visitor<DataType> & data) {\n            for (int c = 0; c < _centers.size(); ++c) {\n\n                vector<DataType > sum(data.getDim(), 0.0f);\n                for (int p = 0; p < _points[c].size(); ++p) {\n\n                    for (int d = 0; d < data.getDim(); ++d) {\n                        sum[d] += data[_points[c][p]][d];        /// add up\n                    }\n                }\n\n                for (int d = 0; d < data.getDim(); ++d) {\n                    _centers[c][d] = sum[d] / _points[c].size(); /// average\n                }\n            }\n        }\n\n        /**\n         * assign each point in {@link data} to nearest center\n         */\n        void Assign(const Visitor<DataType> & data) {\n            vector<int > codes(data.getSize());\n#pragma omp parallel for\n            for (int i = 0; i < data.getSize(); ++i) {\n                codes[i] = NearestCenter(data[i], data.getDim());\n            }\n            for (int i=0; i<data.getSize(); ++i) {\n                _points[codes[i]].push_back(i);\n            }\n        }\n\n\n        int NearestCenter(const DataType * vector, int dimension) {\n            DataType min_distance = ss::EuclidDistance(vector, _centers[0].data(), dimension);\n            int nearest_center = 0;\n            for (int c = 1; c < _centers.size(); c++) {\n                DataType distance = Distance(vector, dimension, c);\n                if (distance < min_distance) {\n                    min_distance = distance;\n                    nearest_center = c;\n                }\n            }\n            return nearest_center;\n        }\n\n\n        /**\n         * calculate distances from {@link vector} to each center\n         * @return distances within a vector of pair<distance, center>\n         */\n        std::vector<std::pair<float, int > > ClusterDistance(const DataType *vector, int dimension) {\n            std::vector<std::pair<float, int>> dist_centers(this->_centers.size());\n            for (int center = 0; center < (this->_centers.size()); ++center) {\n                DataType distance = Distance(vector, dimension, center);\n                dist_centers[center] = std::make_pair(distance, center);\n            }\n\n            return dist_centers;\n        }\n\n        inline DataType Distance(const DataType * vector, int dimension, int center) {\n            return ss::EuclidDistance(vector, _centers[center].data(), dimension);\n        }\n\n    };\n\n} // namespace ss\n", "meta": {"hexsha": "0826719ee4014a46f1db0a7b379920f8fb320ed2", "size": 6726, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/index/kmeans.hpp", "max_stars_repo_name": "xinyandai/similarity-search", "max_stars_repo_head_hexsha": "75dc71abdd7f79094475db734fe55d04358363fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-11-17T00:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T22:51:56.000Z", "max_issues_repo_path": "src/include/index/kmeans.hpp", "max_issues_repo_name": "xinyandai/similarity-search", "max_issues_repo_head_hexsha": "75dc71abdd7f79094475db734fe55d04358363fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/index/kmeans.hpp", "max_forks_repo_name": "xinyandai/similarity-search", "max_forks_repo_head_hexsha": "75dc71abdd7f79094475db734fe55d04358363fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-11-14T08:08:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-08T02:42:58.000Z", "avg_line_length": 36.3567567568, "max_line_length": 101, "alphanum_fraction": 0.545941124, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.43883441503986353}}
{"text": "// Copyright Louis Dionne 2013-2017\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n\n#include <boost/hana/equal.hpp>\n#include <boost/hana/minus.hpp>\n#include <boost/hana/plus.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/zip_with.hpp>\n\n#include <functional>\nnamespace hana = boost::hana;\n\n\n//\n// Example of implementing basic dimensional analysis using Hana\n//\n\n\n// base dimensions                              M  L  T  I  K  J  N\nusing mass        = decltype(hana::tuple_c<int, 1, 0, 0, 0, 0, 0, 0>);\nusing length      = decltype(hana::tuple_c<int, 0, 1, 0, 0, 0, 0, 0>);\nusing time_       = decltype(hana::tuple_c<int, 0, 0, 1, 0, 0, 0, 0>);\nusing charge      = decltype(hana::tuple_c<int, 0, 0, 0, 1, 0, 0, 0>);\nusing temperature = decltype(hana::tuple_c<int, 0, 0, 0, 0, 1, 0, 0>);\nusing intensity   = decltype(hana::tuple_c<int, 0, 0, 0, 0, 0, 1, 0>);\nusing amount      = decltype(hana::tuple_c<int, 0, 0, 0, 0, 0, 0, 1>);\n\n// composite dimensions\nusing velocity     = decltype(hana::tuple_c<int, 0, 1, -1, 0, 0, 0, 0>); // M/T\nusing acceleration = decltype(hana::tuple_c<int, 0, 1, -2, 0, 0, 0, 0>); // M/T^2\nusing force        = decltype(hana::tuple_c<int, 1, 1, -2, 0, 0, 0, 0>); // ML/T^2\n\n\ntemplate <typename Dimensions>\nstruct quantity {\n    double value_;\n\n    explicit quantity(double v) : value_(v) { }\n\n    template <typename OtherDimensions>\n    explicit quantity(quantity<OtherDimensions> other)\n      : value_(other.value_)\n    {\n      static_assert(Dimensions{} == OtherDimensions{},\n        \"Constructing quantities with incompatible dimensions!\");\n    }\n\n    explicit operator double() const { return value_; }\n};\n\ntemplate <typename D1, typename D2>\nauto operator*(quantity<D1> a, quantity<D2> b) {\n    using D = decltype(hana::zip_with(std::plus<>{}, D1{}, D2{}));\n    return quantity<D>{static_cast<double>(a) * static_cast<double>(b)};\n}\n\ntemplate <typename D1, typename D2>\nauto operator/(quantity<D1> a, quantity<D2> b) {\n    using D = decltype(hana::zip_with(std::minus<>{}, D1{}, D2{}));\n    return quantity<D>{static_cast<double>(a) / static_cast<double>(b)};\n}\n\nint main() {\n    quantity<mass>         m{10.3};\n    quantity<length>       d{3.6};\n    quantity<time_>        t{2.4};\n    quantity<velocity>     v{d / t};\n    quantity<acceleration> a{3.9};\n    quantity<force>        f{m * a};\n}\n", "meta": {"hexsha": "40872df9fae4a4f381f73d20f9181a1b2b78b4e3", "size": 2431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/hana/example/misc/dimensional_analysis.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/hana/example/misc/dimensional_analysis.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/hana/example/misc/dimensional_analysis.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 33.7638888889, "max_line_length": 82, "alphanum_fraction": 0.6285479227, "num_tokens": 787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4388344150398635}}
{"text": "/*\n * SphereInitializer.hpp\n *\n *  Created on: Nov 8, 2012\n *      Author: petr\n */\n#pragma once\n#ifndef SPHEREINITIALIZER_HPP_\n#define SPHEREINITIALIZER_HPP_\n\n#include <petscdmadda.h>\n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/StdVector>\n\n#include \"Interface.hpp\"\n\n\nclass SphereInitializer{\n\n    // where the sphere is located\n    Eigen::Vector3d center;\n\n    // how big is the sphere\n    PetscReal              radius;\n\n    size_t                 d;\n\n    // geometry is stores here\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > geometry;\n \n    // select which boundaries need to be initialized\n    int selectBoundaries(const Box<double, 3>& procAABB);\n\n    // defines the distance to the sphere\n    PetscReal sphereEquation(const Eigen::Vector3d& point);\n\n    // initialize the geometry (in this case creates the sphere)\n    void initializeGeometry();\n\n\npublic:\n\n    SphereInitializer(const Eigen::Vector3d& center, PetscReal radius);\n\n\n    // This is where the magic happens and the initializator puts the data in\n    template <typename type, int dim>\n    void operator() (Interface<type, dim>& interface, bool initAll);\n\n\n\n};\n\n\n///===========================================\n///              Implementation\n///===========================================\n\nSphereInitializer::SphereInitializer(const Eigen::Vector3d& center, PetscReal radius) {\n\n    this->center = center;\n    this->radius = radius;\n    this->d = center.size();\n    initializeGeometry();\n\n}\n\ntemplate <typename type, int dim>\nvoid SphereInitializer::operator ()(Interface<type, dim>& interface, bool initAll) {\n\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > boundaryCells;    // xyz coordinated to compute the distance to\n\n    int                        myBoundaries;     // local boundaries to init\n\n    MPI_Group worldGroup;\n    MPI_Comm_group(MPI_COMM_WORLD, &worldGroup);\n    // perpendicular distance computed towards the triangle, it is used when we are no longer sure, which normal shall we use\n\n    // initialize the data\n\n    Vec           localData = interface.getLocalData();\n    double***     data_ptr;\n    int           x, y, z, m, n, p;\n    int           vecSize;\n    DM            cda;\n    Vec           gc;\n    DMDACoor3d*** coors;\n\n    VecSet(localData, std::numeric_limits<double>::max());\n//    VecSet(localData, -0.5);\n    VecGetLocalSize(localData, &vecSize);\n    assert( vecSize > 0 );\n\n    int myWorldRank;\n    int nProcsInWorld;\n\n    MPI_Comm_rank(MPI_COMM_WORLD, &myWorldRank);\n    MPI_Comm_size(MPI_COMM_WORLD, &nProcsInWorld);\n\n\n    const Grid<type, dim>& gr = interface.getGrid();\n\n    DMDAVecGetArray(gr.getDA(), localData, &data_ptr);\n    \n    DMDAGetGhostCorners(gr.getDA(), &x, &y, &z, &m, &n, &p);\n\n    DMGetCoordinatesLocal(gr.getDA() ,&gc);\n    DMGetCoordinateDM(gr.getDA(), &cda);\n    DMDAVecGetArray(cda, gc, &coors);\n\n\n    if (initAll) {\n        // initialize the whole domain\n        \n        for (int i = x; i < x+m; ++i) {\n            for (int j = y; j < y+n; ++j) {\n                for (int k = z; k < z+p; ++k) {\n                    data_ptr[k][j][i] = \n                        sphereEquation(\n                            Eigen::Vector3d(coors[k][j][i].x,\n                                            coors[k][j][i].y,\n                                            coors[k][j][i].z)                            \n                        );\n\n                }\n            }\n        }\n\n    } else {\n        // insert sphere boundaries\n    \tdouble    narrowBand = gr.getDx(0) * 3;\n        for (int i = x; i < x+m; ++i) {\n            for (int j = y; j < y+n; ++j) {\n                for (int k = z; k < z+p; ++k) {\n                    double dist = \n                        sphereEquation(\n                            Eigen::Vector3d(coors[k][j][i].x,\n                                            coors[k][j][i].y,\n                                            coors[k][j][i].z)                            \n                        );\n                    if (fabs(dist) > narrowBand) {\n                        continue;\n                    }\n                    data_ptr[k][j][i] = dist;\n                }\n            }\n        }\n\n        // boundaries\n        int gh = 1;\n        int boundaries = 63;//selectBoundaries( gr.getNodeSpan(myWorldRank) );\n\n        if ( boundaries & 1 ) {\n            // this means lets initialize left side\n            for (int i = x; i < x+gh; ++i) {\n                for (int j = y; j < y+n; ++j) {\n                    for (int k = z; k < z+p; ++k) {\n                        data_ptr[k][j][i+1] = sphereEquation(\n                                                Eigen::Vector3d(coors[k][j][i+1].x,\n                                                                coors[k][j][i+1].y,\n                                                                coors[k][j][i+1].z)\n                                                );\n                    }\n                }\n            }\n        }\n\n        if ( boundaries & 2 ) {\n            // this means lets initialize right side\n            for (int i = x+m-1; i > x+m-1-gh; --i) {\n                for (int j = y; j < y+n; ++j) {\n                    for (int k = z; k < z+p; ++k) {\n                        data_ptr[k][j][i-1] = sphereEquation(\n                                                Eigen::Vector3d(coors[k][j][i-1].x,\n                                                                coors[k][j][i-1].y,\n                                                                coors[k][j][i-1].z)\n                                                );\n                    }\n                }\n            }\n        }\n\n        if ( boundaries & 4 ) {\n            // this means initialize the bottom side\n            for (int j = y; j < y+gh; ++j) {\n                for (int i = x; i < x+m; ++i) {\n                    for (int k = z; k < z+p; ++k) {\n                        data_ptr[k][j+1][i] = sphereEquation(\n                                                Eigen::Vector3d(coors[k][j+1][i].x,\n                                                                coors[k][j+1][i].y,\n                                                                coors[k][j+1][i].z)\n                                                );\n                    }\n                }\n            }\n        }\n\n        if ( boundaries & 8 ) {\n            // this means initialize the top side\n            for (int j = y+n-1; j > y+n-1-gh; --j) {\n                for (int i = x; i < x+m; ++i) {\n                    for (int k = z; k < z+p; ++k) {\n                        data_ptr[k][j-1][i] = sphereEquation(\n                                                Eigen::Vector3d(coors[k][j-1][i].x,\n                                                                coors[k][j-1][i].y,\n                                                                coors[k][j-1][i].z)\n                                                );\n                    }\n                }\n            }\n        }\n\n        if ( boundaries & 16 ) {\n            // this means initialize the front side\n            for (int k = z; k < z+gh; ++k) {\n                for (int i = x; i < x+m; ++i) {\n                    for (int j = y; j < y+n; ++j) {\n                        data_ptr[k+1][j][i] = sphereEquation(\n                                                Eigen::Vector3d(coors[k+1][j][i].x,\n                                                                coors[k+1][j][i].y,\n                                                                coors[k+1][j][i].z)\n                                                );\n                    }\n                }\n            }\n        }\n\n        if ( boundaries & 32 ) {\n            // this means initialize the far side\n            for (int k = z+p-1; k > z+p-1-gh; --k) {\n                for (int i = x; i < x+m; ++i) {\n                    for (int j = y; j < y+n; ++j) {\n                        data_ptr[k-1][j][i] = sphereEquation(\n                                                Eigen::Vector3d(coors[k-1][j][i].x,\n                                                                coors[k-1][j][i].y,\n                                                                coors[k-1][j][i].z)\n                                                );\n                    }\n                }\n            }\n        }\n\n    }\n\n    DMDAVecRestoreArray(cda, gc, &coors);\n    DMDAVecRestoreArray(gr.getDA(), localData, &data_ptr);\n\n}\n\nPetscReal SphereInitializer::sphereEquation(const Eigen::Vector3d& point) {\n    // this function really speaks for itself. It is just sphere equation\n\n    PetscReal dist = 0;\n\n    \n    dist = sqrt( (point[0] - center[0])*(point[0] - center[0]) +\n                 (point[1] - center[1])*(point[1] - center[1]) +\n                 (point[2] - center[2])*(point[2] - center[2])) - radius;\n        \n\n    return dist;\n\n}\n\n\nint SphereInitializer::selectBoundaries(const Box<double, 3>& procAABB) {\n    // chooses which boundaries of the domain have to be initialized\n    // ordering : [left, right, bottom, top, front, back]\n\n    int selectedBoundaries_int = 0;\n\n    for (int i = 0; i < 3; ++i) {\n        //gr->getLocalGhostedMax(i) <= dataProvider->getMaxX(i)\n        if ( procAABB.maxX(i) <= (center[i]+radius) ) {\n            selectedBoundaries_int |= ( 1 << (i*2 + 1) );\n        }\n        // gr->getLocalGhostedMin(i) >= dataProvider->getMinX(i)\n        if ( procAABB.minX(i) >= (center[i]-radius) ) {\n            selectedBoundaries_int |= ( 1 << (i*2) );\n        }\n    }\n\n    return selectedBoundaries_int;\n\n}\n\n\nvoid SphereInitializer::initializeGeometry() {\n    // creates the sphere points in Nd\n\n    int    numberOfPoints = 300;\n\n\n    // x(t) = center(1) - radius*cos(angle_step_1 * t)*sin(angle_step_2 * t);\n    // y(t) = center(2) - radius*sin(angle_step_1 * t)*cos(angle_step_2 * t);\n    // z(t) =             radius*                      cos(angle_step_2 * t);\n\n    double angle_step_1 = (2*3.1415926535897) / numberOfPoints;\n    double angle_step_2 = (  3.1415926535897) / numberOfPoints;\n\n    geometry.reserve(numberOfPoints*numberOfPoints);\n\n    for (int i = 0; i < numberOfPoints; ++i) {\n\n        for (int j = 0; j < numberOfPoints; ++j) {\n                \n            double x = center[0] + radius*cos(angle_step_1 * i)*sin(angle_step_2*j);\n            double y = center[1] + radius*sin(angle_step_1 * i)*sin(angle_step_2*j);\n            double z = center[2] + radius*cos(angle_step_2*j);\n\n\n            geometry.push_back( Eigen::Vector3d(x, y, z) );\n            \n        }\n\n    }\n    \n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n#endif /* SPHEREINITIALIZER_HPP_ */\n", "meta": {"hexsha": "c2bccb8e1bd08d457aab4097f1c78b78e5a161b6", "size": 10565, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/SphereInitializer.hpp", "max_stars_repo_name": "petrkotas/libLS", "max_stars_repo_head_hexsha": "eb57365bfb0be486a4e8c564ff831ad358993268", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SphereInitializer.hpp", "max_issues_repo_name": "petrkotas/libLS", "max_issues_repo_head_hexsha": "eb57365bfb0be486a4e8c564ff831ad358993268", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SphereInitializer.hpp", "max_forks_repo_name": "petrkotas/libLS", "max_forks_repo_head_hexsha": "eb57365bfb0be486a4e8c564ff831ad358993268", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5373134328, "max_line_length": 140, "alphanum_fraction": 0.4220539517, "num_tokens": 2553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4387728558646381}}
{"text": "// The MIT License \n// (c) 2019 Daniel Williams\n\n#include <cmath>\n#include <cstdio>\n#include <string>\n#include <memory>\n#include <iostream>\n#include <iomanip>\n\nusing std::string;\nusing std::cerr;\nusing std::endl;\n\n#include <Eigen/Geometry>\nusing Eigen::Vector2d;\n\n#include <nlohmann/json/json.hpp>\nusing nlohmann::json;\n\n#include \"geometry/layout.hpp\"\n#include \"quadtree/tree.hpp\"\n\nusing namespace terrain;\nusing geometry::Layout;\nusing quadtree::Tree;\nusing quadtree::Node;\n\n// main method for descending through a tree and returning the appropriate location / node / value \n// note: weakly optimized; intended to be a hot path.\nvoid descend( const Vector2d& target, double& x_c, double& y_c, const double start_width, Node* & current_node){\n    double current_width = start_width;\n    double next_width = start_width*0.5;\n\n    while( ! current_node->is_leaf() )\n    {\n        current_width = next_width;\n        next_width *= 0.5;\n\n        if(target[0] > x_c){\n            if( target[1] > y_c){\n                x_c += next_width;\n                y_c += next_width;\n                current_node = current_node->get_northeast();\n            }else{\n                x_c += next_width;\n                y_c -= next_width;\n                current_node = current_node->get_southeast();\n            }\n        }else{\n            if( target[1] > y_c){\n                x_c -= next_width;\n                y_c += next_width;\n                current_node = current_node->get_northwest();\n            }else{\n                x_c -= next_width;\n                y_c -= next_width;\n                current_node = current_node->get_southwest();\n            }\n        }\n    }\n}\n\nTree::Tree(): Tree(Layout()) {}\n\nTree::Tree(const Layout& _layout)\n    : layout(_layout) \n{ \n    reset();\n}\n\nTree::~Tree(){\n    root.release();\n}\n\nbool Tree::contains(const Eigen::Vector2d& p) const {\n    return layout.contains(p);\n}\n\ncell_value_t Tree::classify(const Eigen::Vector2d& p) const {\n    // create a R/W copy, initialized at the tree's center.\n    Eigen::Vector2d located( layout.get_center() );\n\n    auto current_node = root.get();\n    \n    descend( p, located[0], located[1], layout.get_width(), current_node );\n\n    return current_node->get_value();\n}\n\nvoid Tree::debug_tree(const bool show_pointers) const {\n    cerr << \"====== Quad Tree: ======\\n\";\n    cerr << \"##  bounds:     \" << layout.to_string() << endl;\n    cerr << \"##  height:     \" << get_height() << endl;\n    cerr << \"##  precision:  \" << layout.get_precision() << endl;\n\n    root->draw(cerr, \"    \", \"RT\", show_pointers);\n    cerr << endl;\n}\n\nsize_t Tree::calculate_complete_tree(const size_t height){\n    // see: https://en.wikipedia.org/wiki/M-ary_tree\n    //      # properties of M-ary trees\n    //\n    //    m == branching_factor == 4  ///< for a quadtree, this is trivially 4\n    //\n    //       (h+1)\n    //     m        - 1\n    // N = ---------------\n    //        m - 1\n    // \n    return ( pow(4,height+1) - 1 )/3;\n}\n\ndouble Tree::get_load_factor() const {\n    const size_t height = root->get_height();\n    const size_t count = root->get_count();\n    const size_t complete = calculate_complete_tree(height);\n    return static_cast<double>(count) / static_cast<double>(complete);\n}\n\nsize_t Tree::get_memory_usage() const {\n    return size() * sizeof(Node);\n}\n\ncell_value_t Tree::interp(const Eigen::Vector2d& at) const {\n\n    // cout << \"@@\" << at << \"    near: \" << near.get_bounds() << \" = \" << near.get_value() << endl;\n\n    // if Eigen::Vector2d is outside the tree, entirely\n    if( ! contains(at)){\n        return cell_default_value;\n    }\n\n    // const Node& near = root->search(at, get_bounds());\n//     const Eigen::Vector2d& cn = near.get_center();\n//     const double dx = std::copysign(1.0, (at.x() - cn.x())) * 2 * near.get_bounds().half_width;\n//     const double dy = std::copysign(1.0, (at.y() - cn.y())) * 2 * near.get_bounds().half_width;\n//     const Node& n2 = root->search({cn.x() + dx, cn.y()     }, get_bounds());\n//     const Node& n3 = root->search({cn.x() + dx, cn.y() + dy}, get_bounds());\n//     const Node& n4 = root->search({cn.x()     , cn.y() + dy}, get_bounds());\n\n//     const auto& interp = near.interpolate_bilinear(at, n2, n3, n4);\n    // return interp;\n\n    return NAN;\n}\n\nvoid Tree::fill(const cell_value_t fill_value){\n    root->fill(fill_value);\n}\n\nsize_t Tree::get_height() const {\n    return root->get_height() - 1;\n}\n\n\nbool Tree::load_tree(const nlohmann::json& doc){\n    if(! doc.is_object()){\n        cerr << \"?? attempted to load unexpected format: no-object json document!\\n\";\n        return false;\n    }\n    return root->load(doc);\n}\n\nvoid Tree::prune(){\n    root->prune();\n}\n\nvoid Tree::reset(){\n    root = std::make_unique<Node>(0);\n}\n\nvoid Tree::reset(const Layout& new_layout){\n    layout = new_layout;\n\n    root = std::make_unique<Node>(0);\n    root->split(layout.get_precision(), layout.get_width());\n}\n\nSample Tree::sample(const Eigen::Vector2d& p) const {\n    Vector2d located( layout.get_center() );\n    auto current_node = root.get();\n\n    descend( p, located[0], located[1], layout.get_width(), current_node );\n\n    return {located, current_node->get_value()};\n}\n\nbool Tree::store(const Vector2d& p, const cell_value_t new_value) {\n    Vector2d located( layout.get_center() );\n    auto current_node = root.get();\n\n    descend( p, located[0], located[1], layout.get_width(), current_node );\n\n    current_node->set_value(new_value);\n    return true;\n}\n\nsize_t Tree::size() const {\n    return root->get_count();\n}\n\njson Tree::to_json_tree() const {\n    return root->to_json();\n}\n\n", "meta": {"hexsha": "2754d9f5f53f59f61ea58234d2b50f6ac7ad8a12", "size": 5585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/quadtree/tree.cpp", "max_stars_repo_name": "teyrana/quadtree", "max_stars_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/quadtree/tree.cpp", "max_issues_repo_name": "teyrana/quadtree", "max_issues_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-24T17:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-24T17:31:50.000Z", "max_forks_repo_path": "src/quadtree/tree.cpp", "max_forks_repo_name": "teyrana/quadtree", "max_forks_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8509615385, "max_line_length": 112, "alphanum_fraction": 0.5985675918, "num_tokens": 1449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4387728488310402}}
{"text": "//  Copyright John Maddock 2006.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_SP_FACTORIALS_HPP\r\n#define BOOST_MATH_SP_FACTORIALS_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include <boost/math/special_functions/gamma.hpp>\r\n#include <boost/math/special_functions/math_fwd.hpp>\r\n#include <boost/math/special_functions/detail/unchecked_factorial.hpp>\r\n#include <boost/array.hpp>\r\n#ifdef BOOST_MSVC\r\n#pragma warning(push) // Temporary until lexical cast fixed.\r\n#pragma warning(disable: 4127 4701)\r\n#endif\r\n#include <boost/lexical_cast.hpp>\r\n#ifdef BOOST_MSVC\r\n#pragma warning(pop)\r\n#endif\r\n#include <boost/config/no_tr1/cmath.hpp>\r\n\r\nnamespace boost { namespace math\r\n{\r\n\r\ntemplate <class T, class Policy>\r\ninline T factorial(unsigned i, const Policy& pol)\r\n{\r\n   BOOST_STATIC_ASSERT(!boost::is_integral<T>::value);\r\n   BOOST_MATH_STD_USING // Aid ADL for floor.\r\n\r\n   if(i <= max_factorial<T>::value)\r\n      return unchecked_factorial<T>(i);\r\n   T result = boost::math::tgamma(static_cast<T>(i+1), pol);\r\n   if(result > tools::max_value<T>())\r\n      return result; // Overflowed value! (But tgamma will have signalled the error already).\r\n   return floor(result + 0.5f);\r\n}\r\n\r\ntemplate <class T>\r\ninline T factorial(unsigned i)\r\n{\r\n   return factorial<T>(i, policies::policy<>());\r\n}\r\n/*\r\n// Can't have these in a policy enabled world?\r\ntemplate<>\r\ninline float factorial<float>(unsigned i)\r\n{\r\n   if(i <= max_factorial<float>::value)\r\n      return unchecked_factorial<float>(i);\r\n   return tools::overflow_error<float>(BOOST_CURRENT_FUNCTION);\r\n}\r\n\r\ntemplate<>\r\ninline double factorial<double>(unsigned i)\r\n{\r\n   if(i <= max_factorial<double>::value)\r\n      return unchecked_factorial<double>(i);\r\n   return tools::overflow_error<double>(BOOST_CURRENT_FUNCTION);\r\n}\r\n*/\r\ntemplate <class T, class Policy>\r\nT double_factorial(unsigned i, const Policy& pol)\r\n{\r\n   BOOST_STATIC_ASSERT(!boost::is_integral<T>::value);\r\n   BOOST_MATH_STD_USING  // ADL lookup of std names\r\n   if(i & 1)\r\n   {\r\n      // odd i:\r\n      if(i < max_factorial<T>::value)\r\n      {\r\n         unsigned n = (i - 1) / 2;\r\n         return ceil(unchecked_factorial<T>(i) / (ldexp(T(1), (int)n) * unchecked_factorial<T>(n)) - 0.5f);\r\n      }\r\n      //\r\n      // Fallthrough: i is too large to use table lookup, try the \r\n      // gamma function instead.\r\n      //\r\n      T result = boost::math::tgamma(static_cast<T>(i) / 2 + 1, pol) / sqrt(constants::pi<T>());\r\n      if(ldexp(tools::max_value<T>(), -static_cast<int>(i+1) / 2) > result)\r\n         return ceil(result * ldexp(T(1), (i+1) / 2) - 0.5f);\r\n   }\r\n   else\r\n   {\r\n      // even i:\r\n      unsigned n = i / 2;\r\n      T result = factorial<T>(n, pol);\r\n      if(ldexp(tools::max_value<T>(), -(int)n) > result)\r\n         return result * ldexp(T(1), (int)n);\r\n   }\r\n   //\r\n   // If we fall through to here then the result is infinite:\r\n   //\r\n   return policies::raise_overflow_error<T>(\"boost::math::double_factorial<%1%>(unsigned)\", 0, pol);\r\n}\r\n\r\ntemplate <class T>\r\ninline T double_factorial(unsigned i)\r\n{\r\n   return double_factorial<T>(i, policies::policy<>());\r\n}\r\n\r\nnamespace detail{\r\n\r\ntemplate <class T, class Policy>\r\nT rising_factorial_imp(T x, int n, const Policy& pol)\r\n{\r\n   BOOST_STATIC_ASSERT(!boost::is_integral<T>::value);\r\n   if(x < 0)\r\n   {\r\n      //\r\n      // For x less than zero, we really have a falling\r\n      // factorial, modulo a possible change of sign.\r\n      //\r\n      // Note that the falling factorial isn't defined\r\n      // for negative n, so we'll get rid of that case\r\n      // first:\r\n      //\r\n      bool inv = false;\r\n      if(n < 0)\r\n      {\r\n         x += n;\r\n         n = -n;\r\n         inv = true;\r\n      }\r\n      T result = ((n&1) ? -1 : 1) * falling_factorial(-x, n, pol);\r\n      if(inv)\r\n         result = 1 / result;\r\n      return result;\r\n   }\r\n   if(n == 0)\r\n      return 1;\r\n   //\r\n   // We don't optimise this for small n, because\r\n   // tgamma_delta_ratio is alreay optimised for that\r\n   // use case:\r\n   //\r\n   return 1 / boost::math::tgamma_delta_ratio(x, static_cast<T>(n), pol);\r\n}\r\n\r\ntemplate <class T, class Policy>\r\ninline T falling_factorial_imp(T x, unsigned n, const Policy& pol)\r\n{\r\n   BOOST_STATIC_ASSERT(!boost::is_integral<T>::value);\r\n   BOOST_MATH_STD_USING // ADL of std names\r\n   if(x == 0)\r\n      return 0;\r\n   if(x < 0)\r\n   {\r\n      //\r\n      // For x < 0 we really have a rising factorial\r\n      // modulo a possible change of sign:\r\n      //\r\n      return (n&1 ? -1 : 1) * rising_factorial(-x, n, pol);\r\n   }\r\n   if(n == 0)\r\n      return 1;\r\n   if(x < n-1)\r\n   {\r\n      //\r\n      // x+1-n will be negative and tgamma_delta_ratio won't\r\n      // handle it, split the product up into three parts:\r\n      //\r\n      T xp1 = x + 1;\r\n      unsigned n2 = itrunc((T)floor(xp1), pol);\r\n      if(n2 == xp1)\r\n         return 0;\r\n      T result = boost::math::tgamma_delta_ratio(xp1, -static_cast<T>(n2), pol);\r\n      x -= n2;\r\n      result *= x;\r\n      ++n2;\r\n      if(n2 < n)\r\n         result *= falling_factorial(x - 1, n - n2, pol);\r\n      return result;\r\n   }\r\n   //\r\n   // Simple case: just the ratio of two\r\n   // (positive argument) gamma functions.\r\n   // Note that we don't optimise this for small n, \r\n   // because tgamma_delta_ratio is alreay optimised\r\n   // for that use case:\r\n   //\r\n   return boost::math::tgamma_delta_ratio(x + 1, -static_cast<T>(n), pol);\r\n}\r\n\r\n} // namespace detail\r\n\r\ntemplate <class RT>\r\ninline typename tools::promote_args<RT>::type \r\n   falling_factorial(RT x, unsigned n)\r\n{\r\n   typedef typename tools::promote_args<RT>::type result_type;\r\n   return detail::falling_factorial_imp(\r\n      static_cast<result_type>(x), n, policies::policy<>());\r\n}\r\n\r\ntemplate <class RT, class Policy>\r\ninline typename tools::promote_args<RT>::type \r\n   falling_factorial(RT x, unsigned n, const Policy& pol)\r\n{\r\n   typedef typename tools::promote_args<RT>::type result_type;\r\n   return detail::falling_factorial_imp(\r\n      static_cast<result_type>(x), n, pol);\r\n}\r\n\r\ntemplate <class RT>\r\ninline typename tools::promote_args<RT>::type \r\n   rising_factorial(RT x, int n)\r\n{\r\n   typedef typename tools::promote_args<RT>::type result_type;\r\n   return detail::rising_factorial_imp(\r\n      static_cast<result_type>(x), n, policies::policy<>());\r\n}\r\n\r\ntemplate <class RT, class Policy>\r\ninline typename tools::promote_args<RT>::type \r\n   rising_factorial(RT x, int n, const Policy& pol)\r\n{\r\n   typedef typename tools::promote_args<RT>::type result_type;\r\n   return detail::rising_factorial_imp(\r\n      static_cast<result_type>(x), n, pol);\r\n}\r\n\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#endif // BOOST_MATH_SP_FACTORIALS_HPP\r\n\r\n", "meta": {"hexsha": "c81493d75efc5a95d8d9374a11d983388b693531", "size": 6809, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/math/special_functions/factorials.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-04-22T04:22:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T16:28:47.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/math/special_functions/factorials.hpp", "max_issues_repo_name": "benkaraban/anima-games-engine", "max_issues_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-05T01:56:28.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T01:56:28.000Z", "max_forks_repo_path": "LibsExternes/Includes/boost/math/special_functions/factorials.hpp", "max_forks_repo_name": "benkaraban/anima-games-engine", "max_forks_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-27T21:22:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-24T00:15:26.000Z", "avg_line_length": 29.0982905983, "max_line_length": 108, "alphanum_fraction": 0.6254956675, "num_tokens": 1803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.43872716713622895}}
{"text": "\n#ifndef SMOOTH__FEEDBACK__UTILS__SPARSE_HPP_\n#define SMOOTH__FEEDBACK__UTILS__SPARSE_HPP_\n\n#include <Eigen/Sparse>\n\n#include <numeric>\n#include <optional>\n\nnamespace smooth::feedback {\n\n/**\n * @brief Block sparse matrix construction.\n *\n * @param blocks list of lists {{b00, b01}, {b10, b11 ...}} of (optional) sparse matrix blocks\n * @return the blocks as a single sparse matrix\n *\n * Non-present (std::nullopt-valued) blocks are considered zeros.\n *\n * @warning The block sizes must be consistent, i.e. all blocks in the same block-column must have\n * the same number of columns, and similarly for row-columns and rows.\n */\ninline Eigen::SparseMatrix<double> sparse_block_matrix(\n  const std::initializer_list<std::initializer_list<std::optional<Eigen::SparseMatrix<double>>>> &\n    l)\n{\n  const auto n_rows = l.size();\n  const auto n_cols = std::begin(l)->size();\n\n  Eigen::VectorXi dims_rows = Eigen::VectorXi::Constant(n_rows, -1);\n  Eigen::VectorXi dims_cols = Eigen::VectorXi::Constant(n_cols, -1);\n\n  // figure block row and col dimensions\n  for (auto krow = 0u; const auto & row : l) {\n    for (auto kcol = 0u; const auto & item : row) {\n      if (item.has_value()) {\n        if (dims_cols(kcol) == -1) {\n          dims_cols(kcol) = item->cols();\n        } else {\n          assert(dims_cols(kcol) == item->cols());\n        }\n        if (dims_rows(krow) == -1) {\n          dims_rows(krow) = item->rows();\n        } else {\n          assert(dims_rows(krow) == item->rows());\n        }\n      }\n      ++kcol;\n    }\n    ++krow;\n  }\n\n  // check that all dimensions are defined by input args\n  assert(dims_rows.minCoeff() > -1);\n  assert(dims_cols.minCoeff() > -1);\n\n  // figure starting indices\n  const auto n_row = std::accumulate(std::cbegin(dims_rows), std::cend(dims_rows), 0u);\n  const auto n_col = std::accumulate(std::cbegin(dims_cols), std::cend(dims_cols), 0u);\n\n  Eigen::SparseMatrix<double> ret(n_row, n_col);\n\n  // allocate pattern\n  Eigen::Matrix<decltype(ret)::StorageIndex, -1, 1> pattern(n_col);\n  pattern.setZero();\n  for (const auto & row : l) {\n    for (auto kcol = 0u, col0 = 0u; const auto &item : row) {\n      if (item.has_value()) {\n        for (auto col = 0; col < dims_cols(kcol); ++col) {\n          pattern(col0 + col) += item->outerIndexPtr()[col + 1] - item->outerIndexPtr()[col];\n        }\n      }\n      col0 += dims_cols(kcol++);\n    }\n  }\n\n  ret.reserve(pattern);\n\n  // insert values\n  for (auto krow = 0u, row0 = 0u; const auto &row : l) {\n    for (auto kcol = 0u, col0 = 0u; const auto &item : row) {\n      if (item.has_value()) {\n        for (auto col = 0; col < dims_cols(kcol); ++col) {\n          for (typename std::decay_t<decltype(*item)>::InnerIterator it(*item, col); it; ++it) {\n            ret.insert(row0 + it.index(), col0 + col) = it.value();\n          }\n        }\n      }\n      col0 += dims_cols(kcol++);\n    }\n    row0 += dims_rows(krow++);\n  }\n\n  ret.makeCompressed();\n\n  return ret;\n}\n\n/**\n * @brief nxn sparse identity matrix\n *\n * @param n matrix square dimension\n */\ninline Eigen::SparseMatrix<double> sparse_identity(std::size_t n)\n{\n  Eigen::SparseMatrix<double> ret(n, n);\n  ret.reserve(Eigen::Matrix<int, -1, 1>::Ones(n));\n  for (auto i = 0u; i < n; ++i) { ret.insert(i, i) = 1; }\n  return ret;\n}\n\n/**\n * @brief Compute X ⊗ In where X is sparse.\n *\n * @param X sparse matrix in compressed format\n * @param n identity matrix dimension\n *\n * The result has the same storage order as X.\n */\ntemplate<typename Derived>\ninline auto kron_identity(const Eigen::SparseCompressedBase<Derived> & X, std::size_t n)\n{\n  Eigen::\n    SparseMatrix<typename Derived::Scalar, Derived::IsRowMajor ? Eigen::RowMajor : Eigen::ColMajor>\n      ret(X.rows() * n, X.cols() * n);\n\n  Eigen::Matrix<int, -1, 1> pattern(X.outerSize() * n);\n\n  for (auto i0 = 0u, i = 0u; i < X.outerSize(); ++i) {\n    auto nnz_i = X.outerIndexPtr()[i + 1] - X.outerIndexPtr()[i];\n    pattern.segment(i0, n).setConstant(nnz_i);\n    i0 += n;\n  }\n\n  ret.reserve(pattern);\n\n  for (auto i0 = 0u; i0 < X.outerSize(); ++i0) {\n    for (typename std::decay_t<decltype(X)>::InnerIterator it(X, i0); it; ++it) {\n      for (auto diag = 0u; diag < n; ++diag) {\n        ret.insert(n * it.row() + diag, n * it.col() + diag) = it.value();\n      }\n    }\n  }\n\n  ret.makeCompressed();\n\n  return ret;\n}\n\n/**\n * @brief Compute X ⊗ In where X is dense.\n *\n * @param X sparse matrix in compressed format\n * @param n identity matrix dimension\n *\n * The result is column-major.\n */\ntemplate<typename Derived>\ninline auto kron_identity(const Eigen::MatrixBase<Derived> & X, std::size_t n)\n{\n  Eigen::SparseMatrix<typename Derived::Scalar> ret(X.rows() * n, X.cols() * n);\n\n  ret.reserve(Eigen::Matrix<int, -1, 1>::Constant(ret.cols(), n * X.rows()));\n\n  for (auto row = 0u; row < X.rows(); ++row) {\n    for (auto col = 0u; col < X.cols(); ++col) {\n      for (auto diag = 0u; diag < n; ++diag) {\n        ret.insert(n * row + diag, n * col + diag) = X(row, col);\n      }\n    }\n  }\n\n  ret.makeCompressed();\n\n  return ret;\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__UTILS__SPARSE_HPP_\n", "meta": {"hexsha": "3523bd10c293cfea3de927df585b453b58f9424d", "size": 5091, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/utils/sparse.hpp", "max_stars_repo_name": "pettni/smooth_feedback", "max_stars_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T16:18:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T06:13:55.000Z", "max_issues_repo_path": "include/smooth/feedback/utils/sparse.hpp", "max_issues_repo_name": "pettni/smooth_feedback", "max_issues_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T16:39:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T03:51:41.000Z", "max_forks_repo_path": "include/smooth/feedback/utils/sparse.hpp", "max_forks_repo_name": "pettni/smooth_feedback", "max_forks_repo_head_hexsha": "5f967a6b513a7eeea7c70406416440e7c9a5d2e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T15:56:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:23:18.000Z", "avg_line_length": 28.1270718232, "max_line_length": 99, "alphanum_fraction": 0.6126497741, "num_tokens": 1497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.6926419831347361, "lm_q1q2_score": 0.43872654117171533}}
{"text": "// Copyright 2006. Peter Gottschling, Matthias Troyer, Rolf Bonderer\n// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef LA_VECTOR_CONCEPTS_INCLUDE\n#define LA_VECTOR_CONCEPTS_INCLUDE\n\n\n#include <boost/numeric/linear_algebra/concepts.hpp>\n#include <boost/numeric/linear_algebra/ets_concepts.hpp>\n\n#ifdef __GXX_CONCEPTS__\n#  include <concepts>\n#else \n#  include <boost/numeric/linear_algebra/pseudo_concept.hpp>\n#endif\n\n\nnamespace math {  \n  \n/** @addtogroup Concepts\n *  @{\n */\n\n#ifdef __GXX_CONCEPTS__\nconcept VectorSpace<typename Vector, typename Scalar = typename Vector::value_type>\n: AdditiveAbelianGroup<Vector>\n{\n    requires Field<Scalar>;\n    requires Multiplicable<Scalar, Vector>;\n    requires MultiplicableWithAssign<Vector, Scalar>;\n    requires DivisibleWithAssign<Vector, Scalar>;\n  \n    requires std::Assignable<Vector, Multiplicable<Scalar, Vector>::result_type>;\n    requires std::Assignable<Vector, Multiplicable<Vector, Scalar>::result_type>;\n    requires std::Assignable<Vector, Divisible<Vector, Scalar>::result_type>;\n    \n    // Associated types of Field<Scalar> and AdditiveAbelianGroup<Vector> collide\n    // typename result_type = AdditiveAbelianGroup<Vector>::result_type;\n    // typename assign_result_type = AdditiveAbelianGroup<Vector>::assign_result_type;\n\n    axiom Distributivity(Vector v, Vector w, Scalar a, Scalar b)\n    {\n\ta * (v + w) == a * v + a * w;\n\t(a + b) * v == a * v + b * v;\n\t// The following properties are implied by the above, Field and Abelian group\n\t// Can we be sure that compilers can deduce/interfere it?\n\t(v + w) * a == v * a + w * a;\n\tv * (a + b) == v * a + v * b;\n    }\n}\n#else\n    //! Concept VectorSpace\n    /*!\n\t\\param Vector   The the type of a vector or a collection \n        \\param Scalar   The scalar over which the vector field is defined\n        \n\t\\par Requires:\n\t- Field < Scalar >;\n\t- Multiplicable <Scalar, Vector>;\n\t- MultiplicableWithAssign <Vector, Scalar>;\n\t- DivisibleWithAssign <Vector, Scalar>;\n\t- std::Assignable <Vector, Multiplicable<Scalar, Vector>::result_type>;\n\t- std::Assignable <Vector, Multiplicable<Vector, Scalar>::result_type>;\n\t- std::Assignable <Vector, Divisible<Vector, Scalar>::result_type>;\n\n    */\n    template <typename Vector, typename Scalar = typename Vector::value_type>\n    struct VectorSpace\n      : AdditiveAbelianGroup<Vector>\n    {\n\t/// Invariant: Distributivity of scalars and vectors from left and from right\n\taxiom Distributivity(Vector v, Vector w, Scalar a, Scalar b)\n\t{\n\t    /// a * (v + w) == a * v + a * w;       // Scalar from left\n\n\t    /// Vector from right: (a + b) * v == a * v + b * v; \n\n\t    /// Scalar from right: (v + w) * a == v * a + w * a; \n\n\t    /// Vector from left:  v * (a + b) == v * a + v * b;\n\t}\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\nconcept Norm<typename N, typename Vector, \n\t     typename Scalar = typename Vector::value_type>\n  : std::Callable1<N, Vector>\n{\n    requires VectorSpace<Vector, Scalar>;\n    requires RealMagnitude<Scalar>;\n    typename magnitude_type = MagnitudeType<Scalar>::type;\n    requires std::Convertible<magnitude_type, Scalar>;\n\n    typename result_type_norm = std::Callable1<N, Vector>::result_type;\n    requires std::Convertible<result_type_norm, RealMagnitude<Scalar>::magnitude_type>;\n    requires std::Convertible<result_type_norm, Scalar>;\n\n    // Version with function instead functor, as used by Rolf and Matthias\n    // Axioms there defined without norm functor and concept has only 2 types\n#if 0       \n    typename result_type_norm; \n    result_type_norm norm(const Vector&);\n    requires std::Convertible<result_type_norm, magnitude_type>;\n    requires std::Convertible<result_type_norm, Scalar>;\n#endif\n\n    axiom Positivity(N norm, Vector v, magnitude_type ref)\n    {\n\tnorm(v) >= zero(ref);\n    }\n\n    // The following is covered by RealMagnitude\n    // requires AbsApplicable<Scalar>;\n    // requires std::Convertible<AbsApplicable<Scalar>::result_type, magnitude_type>;\n    // requires Multiplicable<magnitude_type>;\n\n    axiom PositiveHomogeneity(N norm, Vector v, Scalar a)\n    {\n\tnorm(a * v) == abs(a) * norm(v);\n    }\n\n    axiom TriangleInequality(N norm, Vector u, Vector v)\n    {\n\tnorm(u + v) <= norm(u) + norm(v);\n    }\n}\n#else\n    //! Concept Norm\n    /*!\n        Semantic requirements of a norm\n\n\t\\param N        Norm functor\n\t\\param Vector   The the type of a vector or a collection \n        \\param Scalar   The scalar over which the vector field is defined\n        \n\t\\par Refinement of:\n\t- std::Callable1 <N, Vector>\n\n\t\\par Associated types:\n\t- magnitude_type\n\t- result_type_norm\n\n\t\\par Requires:\n\t- VectorSpace <Vector, Scalar>;\n\t- RealMagnitude < Scalar >;\n\t- std::Convertible <magnitude_type, Scalar>;\n\t- std::Convertible <result_type_norm, RealMagnitude<Scalar>::magnitude_type>;\n\t- std::Convertible <result_type_norm, Scalar>;\n\n    */\ntemplate <typename N, typename Vector, \n\t  typename Scalar = typename Vector::value_type>\nstruct Norm\n  : std::Callable1<N, Vector>\n{\n    /// Associated type to represent real values in teh Field of scalar (with default)\n    /** By default MagnitudeType<Scalar>::type */\n    typedef associated_type magnitude_type;\n\n    /// Associated type for result of norm functor\n    /** Automatically detected */\n    typedef associated_type result_type_norm;\n\n    /// Invariant: norm of vector is larger than zero \n    axiom Positivity(N norm, Vector v, magnitude_type ref)\n    {\n\t/// norm(v) >= zero(ref);\n    }\n\n    /// Invariant: positive homogeneity with scalar\n    axiom PositiveHomogeneity(N norm, Vector v, Scalar a)\n    {\n\t/// norm(a * v) == abs(a) * norm(v);\n    }\n\n    /// Invariant: triangle inequality\n    axiom TriangleInequality(N norm, Vector u, Vector v)\n    {\n\t/// norm(u + v) <= norm(u) + norm(v);\n    }\n};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\nconcept SemiNorm<typename N, typename Vector, \n\t\t typename Scalar = typename Vector::value_type>\n  : Norm<N, Vector, Scalar>\n{\n    axiom PositiveDefiniteness(N norm, Vector v, magnitude_type ref)\n    {\n\tif (norm(v) == zero(ref))\n\t    v == zero(v);\n\tif (v == zero(v))\n\t    norm(v) == zero(ref);\n    }\n}\n#else\n    //! Concept SemiNorm\n    /*!\n        Semantic requirements of a semi-norm\n\n\t\\param N        Norm functor\n\t\\param Vector   The the type of a vector or a collection \n        \\param Scalar   The scalar over which the vector field is defined\n        \n\t\\par Refinement of:\n\t- Norm <N, Vector, Scalar>\n    */\ntemplate <typename N, typename Vector, \n\t  typename Scalar = typename Vector::value_type>\nstruct SemiNorm\n  : Norm<N, Vector, Scalar>\n{\n    /// The norm of a vector is zero if and only if the vector is the zero vector\n    axiom PositiveDefiniteness(N norm, Vector v, magnitude_type ref)\n    {\n\t/// if (norm(v) == zero(ref)) v == zero(v);\n\n\t/// if (v == zero(v)) norm(v) == zero(ref);\n    }\n};\n#endif\n\n#ifdef __GXX_CONCEPTS__\nconcept BanachSpace<typename N, typename Vector, \n\t\t    typename Scalar = typename Vector::value_type>\n  : Norm<N, Vector, Scalar>,\n    VectorSpace<Vector, Scalar>\n{};\n#else\n    //! Concept BanachSpace\n    /*!\n        A Banach space is a vector space with a norm\n\n\t\\param N        Norm functor\n\t\\param Vector   The the type of a vector or a collection \n        \\param Scalar   The scalar over which the vector field is defined\n        \n\t\\par Refinement of:\n\t- Norm <N, Vector, Scalar>\n\t- VectorSpace <Vector, Scalar>\n\n\t\\note\n\t- The (expressible) requirements of Banach Space are already given in Norm.\n\t- The difference between the requirements is the completeness of the \n\t  Banach space, i.e. that every Cauchy sequence w.r.t. norm(v-w) has a limit\n\t  in the space. Unfortunately, completeness is never satisfied for\n\t  finite precision arithmetic types.\n\t- Another subtle difference is that Norm is not a refinement of Vectorspace\n    */\ntemplate <typename N, typename Vector, \n\t  typename Scalar = typename Vector::value_type>\nstruct BanachSpace\n  : Norm<N, Vector, Scalar>,\n    VectorSpace<Vector, Scalar>\n{};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\nconcept InnerProduct<typename I, typename Vector, \n\t\t     typename Scalar = typename Vector::value_type>\n  : std::Callable2<I, Vector, Vector>\n{\n    // Result of the inner product must be convertible to Scalar\n    requires std::Convertible<std::Callable2<I, Vector, Vector>::result_type, Scalar>;\n\n    // Let's try without this\n    // requires ets::InnerProduct<I, Vector, Scalar>;\n\n    requires HasConjugate<Scalar>;\n\n    axiom ConjugateSymmetry(I inner, Vector v, Vector w)\n    {\n\tinner(v, w) == conj(inner(w, v));\n    }\n\n    axiom SequiLinearity(I inner, Scalar a, Scalar b, Vector u, Vector v, Vector w)\n    {\n\tinner(v, b * w) == b * inner(v, w);\n\tinner(u, v + w) == inner(u, v) + inner(u, w);\n\t// This implies the following (will compilers infere/deduce?)\n\tinner(a * v, w) == conj(a) * inner(v, w);\n\tinner(u + v, w) == inner(u, w) + inner(v, w);\n    }\n\n    requires RealMagnitude<Scalar>;\n    typename magnitude_type = RealMagnitude<Scalar>::type;\n    // requires FullLessThanComparable<magnitude_type>;\n\n    axiom NonNegativity(I inner, Vector v, MagnitudeType<Scalar>::type magnitude)\n    {\n\t// inner(v, v) == conj(inner(v, v)) implies inner(v, v) is real\n\t// ergo representable as magnitude type\n\tmagnitude_type(inner(v, v)) >= zero(magnitude)\n    }\n\n    axiom NonDegeneracy(I inner, Vector v, Vector w, Scalar s)\n    {\n\tif (v == zero(v))\n\t    inner(v, w) == zero(s);\n\tif (inner(v, w) == zero(s))\n\t    v == zero(v);\n    }\n};\n#else\n    //! Concept InnerProduct\n    /*!\n        Semantic requirements of a inner product\n\n\t\\param I        The inner product functor\n\t\\param Vector   The the type of a vector or a collection \n        \\param Scalar   The scalar over which the vector field is defined\n        \n\t\\par Refinement of:\n\t- std::Callable2 <I, Vector, Vector>\n\n\t\\par Associated types:\n\t- magnitude_type\n\n\t\\par Requires:\n\t- std::Convertible<std::Callable2 <I, Vector, Vector>::result_type, Scalar> ;\n\t  result of inner product convertible to scalar to be used in expressions\n\t- HasConjugate < Scalar >\n\t- RealMagnitude < Scalar > ; the scalar value needs a real magnitude type\n    */\ntemplate <typename I, typename Vector, \n          typename Scalar = typename Vector::value_type>\nstruct InnerProduct\n  : std::Callable2<I, Vector, Vector>\n{\n    /// Associated type: the  real magnitude type of the scalar\n    /** By default RealMagnitude<Scalar>::type */\n    typename associated_type magnitude_type;\n    // requires FullLessThanComparable<magnitude_type>;\n\n    /// The arguments can be changed and the result is then the complex conjugate\n    axiom ConjugateSymmetry(I inner, Vector v, Vector w)\n    {\n\t/// inner(v, w) == conj(inner(w, v));\n    }\n\n    /// The inner product is linear in the second argument and conjugate linear in the first one\n    /** The equalities are partly redundant with ConjugateSymmetry */\n    axiom SequiLinearity(I inner, Scalar a, Scalar b, Vector u, Vector v, Vector w)\n    {\n\t/// inner(v, b * w) == b * inner(v, w);\n\n\t/// inner(u, v + w) == inner(u, v) + inner(u, w);\n\n\t/// inner(a * v, w) == conj(a) * inner(v, w);\n\n\t/// inner(u + v, w) == inner(u, w) + inner(v, w);\n    }\n\n    /// The inner product of a vector with itself is not negative\n    /** inner(v, v) == conj(inner(v, v)) implies inner(v, v) is representable as real */\n    axiom NonNegativity(I inner, Vector v, MagnitudeType<Scalar>::type magnitude)\n    {\n\t/// magnitude_type(inner(v, v)) >= zero(magnitude);\n    }\n\n    /// Non-degeneracy not representable with axiom\n    axiom NonDegeneracy(I inner, Vector v, Vector w, Scalar s)\n    {\n\t/// \\f$\\langle v, w\\rangle = 0 \\forall w \\Leftrightarrow v = \\vec{0}\\f$\n    }\n};\n#endif\n\n\n\n\n#ifdef __GXX_CONCEPTS_\n// A dot product is only a semantically special case of an inner product\n// Questionable if we want such a concept\nconcept DotProduct<typename I, typename Vector, \n\t\t   typename Scalar = typename Vector::value_type>\n  : InnerProduct<I, Vector, Scalar>\n{};\n#else\n    //! Concept DotProduct\n    /*!\n        Semantic requirements of dot product. The dot product is a specific inner product.\n\n\t\\param I        Norm functor\n\t\\param Vector   The the type of a vector or a collection \n        \\param Scalar   The scalar over which the vector field is defined\n        \n\t\\par Refinement of:\n\t- InnerProduct <I, Vector, Scalar>\n    */\ntemplate <typename I, typename Vector, \n\t  typename Scalar = typename Vector::value_type>\nstruct DotProduct\n  : InnerProduct<I, Vector, Scalar>\n{};\n#endif\n\n\n\n\n// Norm induced by inner product\n// Might be moved to another place later\n// Definition as class and function\n// Conversion from scalar to magnitude_type is covered by norm concept\ntemplate <typename I, typename Vector,\n\t  typename Scalar = typename Vector::value_type>\n  _GLIBCXX_WHERE(InnerProduct<I, Vector, Scalar> \n\t\t && RealMagnitude<Scalar>)\nstruct induced_norm_t\n{\n    // Return type evtl. with macro to use concept definition\n    typename magnitude_type_trait<Scalar>::type\n    operator() (const I& inner, const Vector& v)\n    {\n\t// Check whether inner product is positive real\n\t// assert(Scalar(abs(inner(v, v))) == inner(v, v));\n\t\n\t// Similar check while accepting small imaginary values\n\t// assert( (abs(inner(v, v)) - inner(v, v)) / abs(inner(v, v)) < 1e-6; )\n\t\n\t// Could also be defined with abs but that might introduce extra ops\n\t// typedef RealMagnitude<Scalar>::type magnitude_type;\n\n\ttypedef typename magnitude_type_trait<Scalar>::type magnitude_type;\n\treturn sqrt(static_cast<magnitude_type> (inner(v, v)));\n    }\n};\n\n\n#if 0\ntemplate <typename I, typename Vector,\n\t  typename Scalar = typename Vector::value_type>\n  LA_WHERE( InnerProduct<I, Vector, Scalar> \n\t    && RealMagnitude<Scalar> )\nmagnitude_type_trait<Scalar>::type\ninduced_norm(const I& inner, const Vector& v)\n{\n    return induced_norm_t<I, Vector, Scalar>() (inner, v);\n}\n#endif\n\n#ifdef __GXX_CONCEPTS__\n\n\nconcept HilbertSpace<typename I, typename Vector,\n\t\t     typename Scalar = typename Vector::value_type, \n\t\t     typename N = induced_norm_t<I, Vector, Scalar> >\n  : InnerProduct<I, Vector, Scalar>,\n    BanachSpace<N, Vector, Scalar>\n{\n    axiom Consistency(Vector v)\n    {\n\tmath::induced_norm_t<I, Vector, Scalar>()(v) == N()(v);                    \n    }   \n};\n#else\n    //! Concept HilbertSpace\n    /*!\n        A Hilbert space is a vector space with an inner product that induces a norm\n\n\t\\param I        Inner product functor\n\t\\param Vector   The the type of a vector or a collection \n        \\param Scalar   The scalar over which the vector field is defined\n\t\\param N        Norm functor\n        \n\t\\par Refinement of:\n\t- InnerProduct <I, Vector, Scalar>\n\t- BanachSpace <N, Vector, Scalar>\n\n\t\\note\n\t- The (expressible) requirements of Banach Space are already given in InnerProduct\n\t  (besides consistency of the functors).\n\t- A difference is that InnerProduct is not a refinement of Vectorspace\n    */\ntemplate <typename I, typename Vector,\n          typename Scalar = typename Vector::value_type, \n\t  typename N = induced_norm_t<I, Vector, Scalar> >\nstruct HilbertSpace\n  : InnerProduct<I, Vector, Scalar>,\n    BanachSpace<N, Vector, Scalar>\n{\n    /// Consistency between norm and induced norm\n    axiom Consistency(Vector v)\n    {\n\t/// math::induced_norm_t<I, Vector, Scalar>()(v) == N()(v);                    \n    }   \n};\n#endif // __GXX_CONCEPTS__\n\n/*@}*/ // end of group Concepts\n\n} // namespace math\n\n#endif // LA_VECTOR_CONCEPTS_INCLUDE\n", "meta": {"hexsha": "0f37105c7705023ea689c7398339e9c2bbba7724", "size": 15737, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/linear_algebra/vector_concepts.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/linear_algebra/vector_concepts.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "lib/mtl4/boost/numeric/linear_algebra/vector_concepts.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 30.9174852652, "max_line_length": 96, "alphanum_fraction": 0.6765584292, "num_tokens": 3948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.43872653560406993}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <type_traits>\n#include \"ear/helpers/assert.hpp\"\n#include \"ear/helpers/output_gains.hpp\"\n\nnamespace ear {\n\n  /** @brief Check if two containers have intersecting elements\n   */\n  template <class InputIterator1, class InputIterator2>\n  bool doIntersect(InputIterator1 first1, InputIterator1 last1,\n                   InputIterator2 first2, InputIterator2 last2) {\n    while (first1 != last1 && first2 != last2) {\n      if (*first1 < *first2)\n        ++first1;\n      else if (*first2 < *first1)\n        ++first2;\n      else {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  template <int N, int M>\n  double interp(double x, const Eigen::Matrix<double, N, 1> &xp,\n                const Eigen::Matrix<double, M, 1> &yp) {\n    ear_assert(std::is_sorted(xp.begin(), xp.end()),\n               \"in interp: unsorted x values\");\n    ear_assert(xp.size() == yp.size(),\n               \"in interp: must have same number of x and y points\");\n    ear_assert(xp.size() >= 2, \"in interp: must have at least 2 points\");\n\n    if (x <= xp(0)) {\n      return yp(0);\n    }\n    for (int i = 0; i < xp.size() - 1; ++i) {\n      if (xp(i + 1) > x) {\n        double x0 = xp(i);\n        double x1 = xp(i + 1);\n        double y0 = yp(i);\n        double y1 = yp(i + 1);\n        return y0 + (y1 - y0) / (x1 - x0) * (x - x0);\n      }\n    }\n    return yp(yp.size() - 1);\n  }\n\n  // write to a vector in a way which is compatible with OutputGains\n  template <typename VecT, typename ValueT>\n  void vec_write(VecT &vec, size_t i, ValueT value) {\n    vec[i] = value;\n  }\n  template <typename ValueT>\n  void vec_write(OutputGains &vec, size_t i, ValueT value) {\n    vec.write(i, value);\n  }\n\n  /// `mask_write(out, mask, values)` is equivalent to numpy\n  /// `out[mask] = values` for boolean masks\n  template <typename OutT, typename MaskT, typename ValuesT>\n  void mask_write(OutT &&out, const MaskT &mask, const ValuesT &values) {\n    Eigen::Index out_size = out.size();\n    Eigen::Index mask_size = mask.size();\n    Eigen::Index values_size = values.size();\n\n    ear_assert(\n        out_size == mask_size,\n        \"in mask_write: out_size and mask_write must be the same length\");\n\n    Eigen::Index j = 0;\n    for (Eigen::Index i = 0; i < mask_size; i++)\n      if (mask[i]) vec_write(out, i, values[j++]);\n\n    ear_assert(j == values_size,\n               \"in mask_size: length of values must equal the number of \"\n               \"entries in mask\");\n  }\n\n  /// make an eigen copy of a std::vector (or other type with size() and\n  /// operator[]), for use when Eigen::Map can't be used, e.g. with\n  /// std::vector<bool>\n  template <typename EigenT, typename ParamT,\n            typename std::enable_if<EigenT::RowsAtCompileTime == Eigen::Dynamic,\n                                    int>::type = 0>\n  inline EigenT copy_vector(const ParamT &x) {\n    Eigen::Index size = x.size();\n    EigenT rv(size);\n\n    for (Eigen::Index i = 0; i < size; i++) rv[i] = x[i];\n\n    return rv;\n  }\n\n  template <typename EigenT, typename ParamT,\n            typename std::enable_if<EigenT::RowsAtCompileTime != Eigen::Dynamic,\n                                    int>::type = 0>\n  inline EigenT copy_vector(const ParamT &x) {\n    Eigen::Index size = x.size();\n    EigenT rv;\n    ear_assert(rv.rows() == size,\n               \"in copy_vector: incorrect size vector for Eigen type used\");\n\n    for (Eigen::Index i = 0; i < size; i++) rv[i] = x[i];\n\n    return rv;\n  }\n}  // namespace ear\n", "meta": {"hexsha": "cf59335b7822c36768ea6cd7edda8e0f5ae9f5f7", "size": 3485, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/helpers/eigen_helpers.hpp", "max_stars_repo_name": "rsjtaylor/libear", "max_stars_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-07-30T17:58:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T15:33:36.000Z", "max_issues_repo_path": "src/common/helpers/eigen_helpers.hpp", "max_issues_repo_name": "rsjtaylor/libear", "max_issues_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T18:01:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T10:24:52.000Z", "max_forks_repo_path": "src/common/helpers/eigen_helpers.hpp", "max_forks_repo_name": "rsjtaylor/libear", "max_forks_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-07-30T15:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T16:22:43.000Z", "avg_line_length": 31.6818181818, "max_line_length": 80, "alphanum_fraction": 0.5850789096, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.6926419831347362, "lm_q1q2_score": 0.4387265315853425}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_CBRT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_CBRT_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/real_splat.hpp>\n#include <boost/simd/constant/third.hpp>\n#include <boost/simd/constant/three.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/constant.hpp>\n#include <boost/simd/function/simd/abs.hpp>\n#include <boost/simd/function/simd/bitofsign.hpp>\n#include <boost/simd/function/simd/bitwise_or.hpp>\n#include <boost/simd/function/simd/divides.hpp>\n#include <boost/simd/function/simd/fast_frexp.hpp>\n#include <boost/simd/function/simd/fast_ldexp.hpp>\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/function/simd/if_else.hpp>\n#include <boost/simd/function/simd/is_equal.hpp>\n#include <boost/simd/function/simd/is_eqz.hpp>\n#include <boost/simd/function/simd/is_gez.hpp>\n#include <boost/simd/function/simd/minus.hpp>\n#include <boost/simd/function/simd/multiplies.hpp>\n#include <boost/simd/function/simd/negate.hpp>\n#include <boost/simd/function/simd/sqr.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/dispatch/meta/scalar_of.hpp>\n\n#ifndef BOOST_SIMD_NO_DENORMALS\n#include <boost/simd/constant/smallestposval.hpp>\n#include <boost/simd/constant/twotomnmbo_3.hpp>\n#include <boost/simd/constant/twotonmb.hpp>\n#include <boost/simd/function/simd/is_less.hpp>\n#endif\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/function/simd/is_inf.hpp>\n#include <boost/simd/function/simd/logical_or.hpp>\n#endif\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD(cbrt_\n                          , (typename A0,typename A1,typename X)\n                          , bd::cpu_\n                          , bs::pack_<bd::single_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( ) const BOOST_NOEXCEPT\n      {\n        A0 z =  nt2::abs(a0);\n        using int_type =  bs::as_integer_t<A0, signed>;\n        using stype =  bd::scalar_of_t<A0>;\n  #ifndef BOOST_SIMD_NO_DENORMALS\n        auto denormal = is_less(z, Smallestposval<A0>());\n        z = if_else(denormal, z*Twotonmb<A0>(), z);\n        A0 f = if_else(denormal, Twotomnmbo_3<A0>(), One<A0>());\n  #endif\n        const A0 CBRT2  = Constant< A0, 0x3fa14518> ();\n        const A0 CBRT4  = Constant< A0, 0x3fcb2ff5> ();\n        const A0 CBRT2I = Constant< A0, 0x3f4b2ff5> ();\n        const A0 CBRT4I = Constant< A0, 0x3f214518> ();\n        int_type e;\n        A0 x = fast_frexp(z, e);\n        x = horn <stype, 0xbe09e49a,\n                         0x3f0bf0fe,\n                         0xbf745265,\n                         0x3f91eb77,\n                         0x3ece0609)\n                 > (x);\n        auto flag = is_gez(e);\n        int_type e1 =  nt2::abs(e);\n        int_type rem = e1;\n        e1 /= Three<int_type>();\n        rem -= e1*Three<int_type>();\n        e = negate(e1, e);\n        const A0 cbrt2 = if_else(flag, CBRT2, CBRT2I);\n        const A0 cbrt4 = if_else(flag, CBRT4, CBRT4I);\n        A0 fact = if_else(is_equal(rem, One<int_type>()), cbrt2, One<A0>());\n        fact = if_else(is_equal(rem, Two<int_type>()), cbrt4, fact);\n        x = fast_ldexp(x*fact, e);\n        x -= (x-z/sqr(x))*Third<A0>();\n  #ifndef BOOST_SIMD_NO_DENORMALS\n        x = bitwise_or(x, bitofsign(a0))*f;\n  #else\n        x = bitwise_or(x, bitofsign(a0));\n  #endif\n  #ifndef BOOST_SIMD_NO_INFINITIES\n        return if_else(logical_or(is_eqz(a0),is_inf(a0)), a0, x);\n  #else\n        return if_else(is_eqz(a0), a0, x);\n  #endif\n      }\n   };\n\n} }\n\n#endif\n", "meta": {"hexsha": "8da58874e80500352a776bdbc67f0473f0caa05c", "size": 4157, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/function/cbrt.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/simd/function/cbrt.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/simd/function/cbrt.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7876106195, "max_line_length": 100, "alphanum_fraction": 0.621842675, "num_tokens": 1164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.819893353516963, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4387236451083298}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2018 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n */\n\n#include <ql/math/ode/adaptiverungekutta.hpp>\n#include <ql/methods/finitedifferences/schemes/methodoflinesscheme.hpp>\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n#include <boost/bind.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\nnamespace QuantLib {\n\n    MethodOfLinesScheme::MethodOfLinesScheme(\n        const Real eps,\n        const Real relInitStepSize,\n        const ext::shared_ptr<FdmLinearOpComposite> & map,\n        const bc_set& bcSet)\n    : dt_(Null<Real>()),\n      eps_(eps),\n      relInitStepSize_(relInitStepSize),\n      map_(map),\n      bcSet_(bcSet) {\n    }\n\n\n    Disposable<std::vector<Real> >\n    MethodOfLinesScheme::apply(Time t, const std::vector<Real>& u) const {\n        map_->setTime(t, t + 0.0001);\n        bcSet_.applyBeforeApplying(*map_);\n\n        const Array dxdt = -map_->apply(Array(u.begin(), u.end()));\n\n        std::vector<Real> retVal(dxdt.begin(), dxdt.end());\n        return retVal;\n    }\n\n    void MethodOfLinesScheme::step(array_type& a, Time t) {\n        QL_REQUIRE(t-dt_ > -1e-8, \"a step towards negative time given\");\n\n        const std::vector<Real> v =\n           AdaptiveRungeKutta<Real>(eps_, relInitStepSize_*dt_)(\n               boost::bind(&MethodOfLinesScheme::apply, this, _1, _2),\n               std::vector<Real>(a.begin(), a.end()),\n               t, std::max(0.0, t-dt_));\n\n        Array y(v.begin(), v.end());\n\n        bcSet_.applyAfterSolving(y);\n\n        a = y;\n    }\n\n    void MethodOfLinesScheme::setStep(Time dt) {\n        dt_ = dt;\n    }\n}\n", "meta": {"hexsha": "3be8f87c9b28281f48ccbae2728b4556887d5c4c", "size": 2523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/methods/finitedifferences/schemes/methodoflinesscheme.cpp", "max_stars_repo_name": "tlapfai/My-Quantlib", "max_stars_repo_head_hexsha": "9e24dafd8c849659d3a9b4b432abf854441ab825", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/methods/finitedifferences/schemes/methodoflinesscheme.cpp", "max_issues_repo_name": "tlapfai/My-Quantlib", "max_issues_repo_head_hexsha": "9e24dafd8c849659d3a9b4b432abf854441ab825", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/methods/finitedifferences/schemes/methodoflinesscheme.cpp", "max_forks_repo_name": "tlapfai/My-Quantlib", "max_forks_repo_head_hexsha": "9e24dafd8c849659d3a9b4b432abf854441ab825", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T02:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T02:04:10.000Z", "avg_line_length": 32.3461538462, "max_line_length": 87, "alphanum_fraction": 0.6575505351, "num_tokens": 653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390164, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.43867662252283657}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2009 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <complex>\n#include <iostream>\n#include <iomanip>\n#include <cstdlib>\n#include <cmath>\n\n#include <boost/timer.hpp>\n\n#include \"dune/common/stdstreams.hh\"\n#include \"dune/grid/sgrid.hh\"\n#include \"dune/grid/uggrid.hh\"\n#include \"dune/grid/geometrygrid.hh\"\n#include \"dune/grid/common/gridinfo.hh\"\n#include \"dune/istl/solvers.hh\"\n\n#include \"fem/assemble.hh\"\n#include \"fem/embedded_errorest.hh\"\n#include \"fem/istlinterface.hh\"\n#include \"fem/functional_aux.hh\"\n#include \"fem/hierarchicspace.hh\"\n#include \"fem/lagrangespace.hh\"\n#include \"linalg/trivialpreconditioner.hh\"\n#include \"linalg/direct.hh\"\n#include \"linalg/triplet.hh\"\n#include \"linalg/iluprecond.hh\"\n#include \"linalg/additiveschwarz.hh\"\n#include \"linalg/hyprecond.hh\"\n#include \"io/vtk.hh\"\n#include \"io/amira.hh\"\n\n#include \"utilities/kaskopt.hh\"\n\n#include \"ht.hh\"\n\n namespace Dune\n  {\n\n    namespace Capabilities\n    {\n\n      template< class Grid >\n      struct hasHierarchicIndexSet\n      {\n        static const bool v = false;\n      };\n\n      template< class Grid >\n      struct hasHierarchicIndexSet< const Grid >\n      {\n        static const bool v = hasHierarchicIndexSet< Grid >::v;\n      };\n\n    }\n\n  }\n\n\nclass SquareToCircle\n  : public Dune::AnalyticalCoordFunction< double, 2, 2, SquareToCircle >\n  {\n    typedef SquareToCircle This;\n    typedef Dune::AnalyticalCoordFunction< double, 2, 2, This > Base;\n\n  public:\n    typedef Base::DomainVector DomainVector;\n    typedef Base::RangeVector RangeVector;\n\n    void evaluate ( const DomainVector &x, RangeVector &y ) const\n    {\n      double enorm = sqrt(x[0]*x[0]+x[1]*x[1]);\n\n      if(enorm > 0.00001)\n      {\n\n        double radius = sqrt(2.0)*std::max(std::fabs(x[0]),std::fabs(x[1]));\n\n      \n\n      double scaling = radius/enorm;\n\n\n      y[ 0 ] = x[ 0 ]*scaling;\n      y[ 1 ] = x[ 1 ]*scaling;\n      } else\n      {\n      y[ 0 ] = x[ 0 ];\n      y[ 1 ] = x[ 1 ];\n      }\n        \n    }\n  };\n\n\nint main(int argc, char *argv[])\n  {\n\n\t//   two-dimensional space: dim=2\n\tint const dim=2; \t\t\n\ttypedef Dune::UGGrid<dim> Grid;\n\n        typedef Dune::GeometryGrid<Grid,SquareToCircle> GGrid;\n\n\tDune::GridFactory<Grid> factory;\n\n\t// vertex coordinates v[0], v[1]\n\tDune::FieldVector<double,dim> v; \t\n\tv[0]=-1; v[1]=-1; factory.insertVertex(v);\n\tv[0]=1; v[1]=-1; factory.insertVertex(v);\n\tv[0]=1; v[1]=1; factory.insertVertex(v);\n\tv[0]=-1; v[1]=1; factory.insertVertex(v);\n\tv[0]=0; v[1]=0; factory.insertVertex(v);\n\t// triangle defined by 3 vertex indices\n\tstd::vector<unsigned int> vid(3);\n\tDune::GeometryType gt(Dune::GeometryType::simplex,2);\n\tvid[0]=0; vid[1]=1; vid[2]=4; factory.insertElement(gt,vid);\n\tvid[0]=1; vid[1]=2; vid[2]=4; factory.insertElement(gt,vid);\n\tvid[0]=2; vid[1]=3; vid[2]=4; factory.insertElement(gt,vid);\n\tvid[0]=3; vid[1]=0; vid[2]=4; factory.insertElement(gt,vid);\n\tstd::auto_ptr<Grid> grid( factory.createGrid() ) ;\n\n        \n\n\t// the coarse grid will be refined three times\n\t// some information on the refined mesh\n\tstd::cout << \"Grid: \" << grid->size(0) << \" triangles, \" << std::endl;\n\tstd::cout << \"      \" << grid->size(1) << \" edges, \" << std::endl;\n\tstd::cout << \"      \" << grid->size(2) << \" points\" << std::endl;\n\t// a gridmanager is constructed \n\t// as connector between geometric and algebraic information\n        \n        SquareToCircle def;\n\n        std::auto_ptr<GGrid> ggrid(new GGrid(*grid,def));\n\n\tggrid->globalRefine(6);\n\n\tGridManager<GGrid> gridManager(ggrid);    \n\n\n//StartSnippet2\n\t// construction of finite element space for the scalar solution T\n\ttypedef GGrid::LeafGridView GridView;\n\ttypedef FEFunctionSpace<ContinuousLagrangeMapper<double,GridView> > H1Space;\n\tH1Space temperatureSpace(gridManager,gridManager.grid().leafView(),\n\t\t\t\t\t\t\t 1);\n\ttypedef boost::fusion::vector<H1Space const*> Spaces;\n\tSpaces spaces(&temperatureSpace);\n\t// VariableDescription<int spaceId, int components, int Id>\n\t// spaceId: number of associated FEFunctionSpace\n\t// components: number of components in this variable\n\t// Id: number of this variable\n\ttypedef boost::fusion::vector<VariableDescription<0,1,0> >\n\t\t\tVariableDescriptions;\n\tstd::string varNames[1] = { \"T\" };\n\ttypedef VariableSetDescription<Spaces,VariableDescriptions> VariableSet;\n\tVariableSet variableSet(spaces,varNames);\n//StopSnippet2\n\n//StartSnippet3\n\ttypedef HeatFunctional<double,VariableSet> Functional;\n\tFunctional F;\n\ttypedef VariationalFunctionalAssembler<LinearizationAt<Functional> > GOP;\n\ttypedef GOP::TestVariableRepresentation<>::type Rhs;\n\tGOP gop(gridManager.signals,spaces);\n\tVariableSet::VariableSet x(variableSet);\n//StopSnippet3\n\n//StartSnippet4\n\n\ttypedef GOP::AnsatzVariableRepresentation<>::type Sol;\n\tSol solution(GOP::AnsatzVariableRepresentation<>::init(gop));\n\tsolution = 0;\n\tgop.assemble(linearization(F,x));\n\n\n\tRhs rhs(GOP::TestVariableRepresentation<>::rhs(gop));\n\tAssembledGalerkinOperator<GOP,0,1,0,1> A(gop, false);\n\tAssembledGalerkinOperator<GOP,0,1,0,1>::matrix_type tri(A.getmat());\n//\tA.getmat().print();\n\n\n//StartSnippet5\n    boost::timer directTimer;\n    directInverseOperator(A,DirectType::UMFPACK,MatrixProperties::GENERAL).applyscaleadd(-1.0,rhs,solution);\n    std::cout << \"direct solve: \" << directTimer.elapsed() << \"s\\n\";\n    x.data = solution.data;\n//StopSnippet5\n\n//StartSnippet6\n\t// output of solution in VTK format for visualization,\n\t// the data are written as ascii stream into file temperature.vtu,\n\t// possible is also binary\n \tIoOptions options;\n \toptions.outputType = IoOptions::ascii;\n \n    typedef GGrid::LeafGridView LeafGridView;\n    LeafGridView leafView = gridManager.grid().leafView();\n    writeVTKFile(leafView,variableSet,x,\"temperature\",options);\n\n  }\n", "meta": {"hexsha": "165884e291c16cd8cee948248ddda749e7b03df0", "size": 6504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/geomgrid/geomgrid.cpp", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/tutorial/geomgrid/geomgrid.cpp", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/tutorial/geomgrid/geomgrid.cpp", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 30.5352112676, "max_line_length": 108, "alphanum_fraction": 0.6248462485, "num_tokens": 1770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.43867662252283646}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include <isce3/antenna/EdgeMethodCostFunc.h>\n#include <isce3/except/Error.h>\n#include <isce3/math/RootFind1dNewton.h>\n#include <isce3/math/polyfunc.h>\n\nnamespace isce3 { namespace antenna {\n\nstd::tuple<double, double, bool, int> rollAngleOffsetFromEdge(\n        const poly1d_t& polyfit_echo, const poly1d_t& polyfit_ant,\n        const isce3::core::Linspace<double>& look_ang,\n        std::optional<poly1d_t> polyfit_weight)\n{\n    // check the input arguments\n    if (polyfit_echo.order != 3 || polyfit_ant.order != 3)\n        throw isce3::except::InvalidArgument(ISCE_SRCINFO(),\n                \"Requires 3rd-order poly-fit object for both \"\n                \"Echo and Antenna!\");\n    constexpr double a_tol {1e-5};\n    if (std::abs(polyfit_echo.mean - polyfit_ant.mean) > a_tol ||\n            std::abs(polyfit_echo.norm - polyfit_ant.norm) > a_tol)\n        throw isce3::except::InvalidArgument(ISCE_SRCINFO(),\n                \"Requires same (mean, std) for Echo and Antenna Poly1d obj!\");\n\n    if (!(polyfit_echo.norm > 0.0))\n        throw isce3::except::InvalidArgument(ISCE_SRCINFO(),\n                \"Requires positive std of Echo and Antenna Poly1d obj!\");\n\n    if (polyfit_weight) {\n        if (polyfit_weight->order < 0)\n            throw isce3::except::InvalidArgument(ISCE_SRCINFO(),\n                    \"The order of polyfit for weights must be \"\n                    \"at least 0 (constant weights)!\");\n        if (!(polyfit_weight->norm > 0.0))\n            throw isce3::except::InvalidArgument(ISCE_SRCINFO(),\n                    \"Requires positive std of weight Poly1d obj!\");\n    }\n\n    // create a copy polyfit objects \"echo\" and \"ant\" with zero mean and unit\n    // std\n    auto pf_echo_cp = polyfit_echo;\n    pf_echo_cp.mean = 0.0;\n    pf_echo_cp.norm = 1.0;\n    auto pf_ant_cp = polyfit_ant;\n    pf_ant_cp.mean = 0.0;\n    pf_ant_cp.norm = 1.0;\n\n    // declare and initialize a look angle vector\n    Eigen::ArrayXd lka_vec(look_ang.size());\n    for (int idx = 0; idx < look_ang.size(); ++idx)\n        lka_vec(idx) = look_ang[idx];\n\n    // create a weighting vector from look vector and weighting Poly1d\n    Eigen::ArrayXd wgt_vec;\n    if (polyfit_weight) {\n        Eigen::Map<Eigen::ArrayXd> wgt_coef(\n                polyfit_weight->coeffs.data(), polyfit_weight->coeffs.size());\n        wgt_vec = isce3::math::polyval(\n                wgt_coef, lka_vec, polyfit_weight->mean, polyfit_weight->norm);\n        // normalize power in dB\n        wgt_vec -= wgt_vec.maxCoeff();\n        // convert from dB to linear power scale\n        wgt_vec = Eigen::pow(10, 0.1 * wgt_vec);\n    }\n    // centralized and scaled the look vector based on mean/std of the echo\n    // Poly1d to be used for both antenna and echo in the cost function.\n    lka_vec -= polyfit_echo.mean;\n    const auto std_inv = 1.0 / polyfit_echo.norm;\n    lka_vec *= std_inv;\n\n    // form some derivatives used in the cost function\n    auto pf_echo_der = pf_echo_cp.derivative();\n    auto pf_ant_der = pf_ant_cp.derivative();\n    auto pf_ant_der2 = pf_ant_der.derivative();\n    // create a memmap of the coeff for the first and second derivatives\n    Eigen::Map<Eigen::ArrayXd> coef_ant_der(\n            pf_ant_der.coeffs.data(), pf_ant_der.coeffs.size());\n    Eigen::Map<Eigen::ArrayXd> coef_ant_der2(\n            pf_ant_der2.coeffs.data(), pf_ant_der2.coeffs.size());\n    Eigen::Map<Eigen::ArrayXd> coef_echo_der(\n            pf_echo_der.coeffs.data(), pf_echo_der.coeffs.size());\n    // form some arrays over scaled look angles for diff of first derivatives\n    // and for second derivative\n    auto ant_echo_der_dif_vec =\n            isce3::math::polyval(coef_ant_der - coef_echo_der, lka_vec);\n    auto ant_der2_vec = isce3::math::polyval(coef_ant_der2, lka_vec);\n\n    // build cost function in the form of Poly1d object (3th order polynimal!)\n    auto cf_pf = isce3::core::Poly1d(3, 0.0, 1.0);\n    // fill up the coeff for the derivative of the WMSE cost function:\n    // cost(ofs) = pf_wgt*(pf_echo_der(el) - pf_ant_der(el + ofs))**2\n    // See section 1.1 of the cited reference.\n    if (polyfit_weight) {\n        auto tmp1 = wgt_vec * ant_echo_der_dif_vec;\n        auto tmp2 = wgt_vec * ant_der2_vec;\n        cf_pf.coeffs[0] = (tmp1 * ant_der2_vec).sum();\n        cf_pf.coeffs[1] = (tmp2 * ant_der2_vec).sum() +\n                          6 * pf_ant_cp.coeffs[3] * tmp1.sum();\n        cf_pf.coeffs[2] = 9 * pf_ant_cp.coeffs[3] * tmp2.sum();\n        cf_pf.coeffs[3] =\n                18 * pf_ant_cp.coeffs[3] * pf_ant_cp.coeffs[3] * wgt_vec.sum();\n    } else // no weighting\n    {\n        cf_pf.coeffs[0] = (ant_echo_der_dif_vec * ant_der2_vec).sum();\n        cf_pf.coeffs[1] = ant_der2_vec.square().sum() +\n                          6 * pf_ant_cp.coeffs[3] * ant_echo_der_dif_vec.sum();\n        cf_pf.coeffs[2] = 9 * pf_ant_cp.coeffs[3] * ant_der2_vec.sum();\n        cf_pf.coeffs[3] = 18 * pf_ant_cp.coeffs[3] * pf_ant_cp.coeffs[3] *\n                          look_ang.size();\n    }\n    // form Root finding object\n    auto rf_obj =\n            isce3::math::RootFind1dNewton(1e-4, 20, look_ang.spacing() / 10.);\n    // solve for the root/roll offset via Newton\n    auto [roll, f_val, flag, n_iter] = rf_obj.root(cf_pf);\n    // scale back the roll angle by std of original poly1d object\n    roll *= polyfit_echo.norm;\n\n    return {roll, f_val, flag, n_iter};\n}\n\nstd::tuple<double, double, bool, int> rollAngleOffsetFromEdge(\n        const poly1d_t& polyfit_echo, const poly1d_t& polyfit_ant,\n        double look_ang_near, double look_ang_far, double look_ang_prec,\n        std::optional<poly1d_t> polyfit_weight)\n{\n    if (!(look_ang_near > 0.0 && look_ang_far > 0.0 && look_ang_prec > 0.0))\n        throw isce3::except::InvalidArgument(ISCE_SRCINFO(),\n                \"All look angles values must be positive numbers!\");\n    if (look_ang_near >= (look_ang_far - look_ang_prec))\n        throw isce3::except::InvalidArgument(ISCE_SRCINFO(),\n                \"Near-range look angle shall be smaller than \"\n                \"far one by at least one prec!\");\n\n    const auto ang_size = static_cast<int>(\n            std::round((look_ang_far - look_ang_near) / look_ang_prec) + 1);\n    auto look_ang = isce3::core::Linspace<double>::from_interval(\n            look_ang_near, look_ang_far, ang_size);\n\n    return rollAngleOffsetFromEdge(\n            polyfit_echo, polyfit_ant, look_ang, polyfit_weight);\n}\n\n}} // namespace isce3::antenna\n", "meta": {"hexsha": "2111ab831706d7c64ebfdb28caaf5d8c694aa9dc", "size": 6491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cxx/isce3/antenna/EdgeMethodCostFunc.cpp", "max_stars_repo_name": "isce3-testing/isce3-circleci-poc", "max_stars_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cxx/isce3/antenna/EdgeMethodCostFunc.cpp", "max_issues_repo_name": "isce3-testing/isce3-circleci-poc", "max_issues_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T00:00:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T00:00:31.000Z", "max_forks_repo_path": "cxx/isce3/antenna/EdgeMethodCostFunc.cpp", "max_forks_repo_name": "isce3-testing/isce3-circleci-poc", "max_forks_repo_head_hexsha": "ec1dfb6019bcdc7afb7beee7be0fa0ce3f3b87b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T21:10:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T21:10:11.000Z", "avg_line_length": 43.2733333333, "max_line_length": 79, "alphanum_fraction": 0.6396549068, "num_tokens": 1799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.43867002559173346}}
{"text": "//============================================================================\n// Name        : test2.cpp\n// Author      : \n// Version     :\n// Copyright   : Your copyright notice\n// Description : Hello World in C++, Ansi-style\n//============================================================================\n\n#include <iostream>\n#include <Eigen/Dense>\n//#include <unsupported/Eigen/AutoDiff>\n#include <unsupported/Eigen/AdolcForward>\n//#include <unsupported/Eigen/AdolcSupport>\n\n//#include <chrono>\n//#include <iomanip>\n#include <adolc.h>\n#include <adolc/adouble.h>\n#include <vector>\n#include <time.h>\n#include <math.h>\n#include <fstream>\n#include <thread>\n#include <future>\n#include <algorithm>\n#include <iterator>\n#include \"cost.h\"\n#include \"dynamics.h\"\n#include \"iLQR.h\"\n#include \"utils.h\"\n#include<unistd.h>\n#include \"DataStreamClient.h\"\n\n\n\nint main()\n{\n\n\n\n//\n//\tEigen::VectorXd X0(4,1),inputs(2,1);\n//\tX0<<0,0,0,0;\n//\tinputs<<0,0;\n//\n//\tconstexpr size_t state_size=4;\n//\tconstexpr size_t input_size=2;\n\tconstexpr size_t horizon=5;\n\tconstexpr int total_steps=300;\n\tsrand((unsigned int) time(0));\n////\tint horizon=1000;\n\tunsigned int tag1(1),tag2(2),tag3(3),tag4(4),tag5(5),tag6(6)\n\t,tag7(7),tag8(8),tag9(9);\n\n//\tdouble time_step=0.2;\n\tdouble time_step=0.1;\n\n//\n\n//\t/* This part is unicycle simulation*/\n//\n//\tcost<4,2> running_cost_uni(Unicycle_Cost::running_cost,tag1);\n//\tcost<4,2> terminal_cost_uni(Unicycle_Cost::terminal_cost,tag2);\n//\tdynamics<4,2> dynamics_uni(Unicycle_Dynamics::dynamics,tag3,time_step);\n//\n//\tiLQR<4,2,horizon> uni_solver(running_cost_uni,terminal_cost_uni,dynamics_uni);\n//\tEigen::Matrix<double,2,1> u_uni=Eigen::Matrix<double,2,1>::Zero();\n//\tEigen::Matrix<double,4,1> x0_uni=Eigen::Matrix<double,4,1>::Zero();\n//\tx0_uni<<-5,-5,0,0;\n//////\tX0_drone<<0,-50,10, M_PI/20,0,0, 0,0,0, 0,0,0;\n//\tEigen::Matrix<double,4,1> x_goal_uni;\n//\n//\n////\n//\tiLQR<4,2,horizon>::input_trajectory u_init_uni;\n//\tstd::fill(std::begin(u_init_uni), std::end(u_init_uni), u_uni);\n//\tiLQR<4,2,horizon>::state_input_trajectory soln_uni;\n//\tiLQR<4,2,total_steps>::state_input_trajectory soln_uni_rhc;\n//\n//\n//\n//\tclock_t t_start, t_end;\n//\n////\n//\tdouble seconds;\n//\tuni_solver.set_MPC(u_init_uni);\n//\tint execution_steps=1;\n//\tsoln_uni_rhc.first[0]=x0_uni;\n//\tstd::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n//\tstd::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n//\n//\tx_goal_uni<<5,5,0,0;\n//\tt_start = clock();\n//\tfor(int i=0;i<total_steps;++i)\n//\t{\n////\t\tX_goal_drone<<10,0,0, 0,0,0, 0,0,0, 0,0,0;\n////\t\tif (i>total_steps/3)\n////\t\t\tX_goal_drone<<0,0,0, 0,0,0, 0,0,0, 0,0,0;\n//\t\tstd::cout<<\"iteration \"<<i<<std::endl;\n//////\n//\t\tsoln_uni=uni_solver.run_MPC(soln_uni_rhc.first[i], x_goal_uni, 100, execution_steps);\n////\n////////\t\tunsigned int microsecond = 1000000;\n////////\t\tusleep(2 * microsecond);\n////\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n////\t\tstd::cout<<soln_uni.first[39]<<std::endl;\n//\t\tsoln_uni_rhc.first[i+1]=soln_uni.first[1];\n//\t\tsoln_uni_rhc.second[i]=soln_uni.second[0];\n//\t}\n//\tt_end = clock();\n//////\n//////\n////////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n////////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\twrite_file<4,2,total_steps>(state_path,input_path, soln_uni_rhc);\n////\n//\tstd::cout<<\"finished\"<<std::endl;\n//\tseconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n//\tprintf(\"Time: %f s\\n\", seconds);\n//\n//\n//\t/* End of unicycle simulation*/\n\n/* This part is 2-unicycle simulation*/\n\n//\tcost<8,4> running_cost_uni2(Unicycle_Cost::running_cost2,tag1);\n//\tcost<8,4> terminal_cost_uni2(Unicycle_Cost::terminal_cost2,tag2);\n//\tdynamics<8,4> dynamics_uni2(Unicycle_Dynamics::dynamics_2,tag3,time_step);\n//\n//\tiLQR<8,4,horizon> uni2_solver(running_cost_uni2,terminal_cost_uni2,dynamics_uni2);\n//\tEigen::Matrix<double,4,1> u_uni2=Eigen::Matrix<double,4,1>::Random()*0.1;\n//\tEigen::Matrix<double,8,1> x0_uni2=Eigen::Matrix<double,8,1>::Zero();\n//\tx0_uni2<<0,0.1,0,0, 10,0,M_PI,0;\n//\n//\tEigen::Matrix<double,8,1> x_goal_uni2;\n//\n//\n////\n//\tiLQR<8,4,horizon>::input_trajectory u_init_uni2;\n//\tfor(auto &item : u_init_uni2)\n//\t\titem=Eigen::Matrix<double,4,1>::Random()*0.1;\n//\tstd::fill(std::begin(u_init_uni2), std::end(u_init_uni2), u_uni2);\n//\tiLQR<8,4,horizon>::state_input_trajectory soln_uni2;\n//\tiLQR<8,4,total_steps>::state_input_trajectory soln_uni2_rhc;\n//\n//\n//\n//\tclock_t t_start, t_end;\n//\n////\n//\tdouble seconds;\n//\tuni2_solver.set_MPC(u_init_uni2);\n//\tint execution_steps=1;\n//\tsoln_uni2_rhc.first[0]=x0_uni2;\n//\tstd::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n//\tstd::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n//\n//\tx_goal_uni2<<10,0,0,0, 0,0,M_PI,0;\n//\tt_start = clock();\n//\tfor(int i=0;i<total_steps;++i)\n//\t{\n////\t\tX_goal_drone<<10,0,0, 0,0,0, 0,0,0, 0,0,0;\n////\t\tif (i>total_steps/3)\n////\t\t\tX_goal_drone<<0,0,0, 0,0,0, 0,0,0, 0,0,0;\n//\t\tstd::cout<<\"iteration \"<<i<<std::endl;\n//////\n//\t\tsoln_uni2=uni2_solver.run_MPC(soln_uni2_rhc.first[i], x_goal_uni2, 5, execution_steps);\n////\n////////\t\tunsigned int microsecond = 1000000;\n////////\t\tusleep(2 * microsecond);\n////\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n////\t\tstd::cout<<soln_uni.first[39]<<std::endl;\n//\t\tsoln_uni2_rhc.first[i+1]=soln_uni2.first[1];\n//\t\tsoln_uni2_rhc.second[i]=soln_uni2.second[0];\n//\t}\n//\tt_end = clock();\n////\n////\n//////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n//////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\twrite_file<8,4,total_steps>(state_path,input_path, soln_uni2_rhc);\n////\n//\tstd::cout<<\"finished\"<<std::endl;\n//\tseconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n//\tprintf(\"Time: %f s\\n\", seconds);\n\n\n/* End of 2-unicycle simulation*/\n\n\n\n\n\n\n\n\n/* This part is single drone simulation*/\n\n//\tcost<12,4> running_cost_dr(Drone_Cost::running_cost,tag1);\n//\tcost<12,4> terminal_cost_dr(Drone_Cost::terminal_cost,tag2);\n//\tdynamics<12,4> dynamics_dr(Drone_Dynamics::dynamics,tag3,time_step);\n//\n//\tiLQR<12,4,horizon> drone_solver(running_cost_dr,terminal_cost_dr,dynamics_dr);\n//\tEigen::Matrix<double,4,1> u_drone=Eigen::Matrix<double,4,1>::Ones();\n//\tEigen::Matrix<double,12,1> X0_drone=Eigen::Matrix<double,12,1>::Zero();\n//////\tX0_drone<<0,-50,10, M_PI/20,0,0, 0,0,0, 0,0,0;\n//\tEigen::Matrix<double,12,1> X_goal_drone;\n//\n//\tu_drone=u_drone*sqrt(Drone_Dynamics::mass*Drone_Dynamics::g/(4*Drone_Dynamics::C_T));\n////\n//\tiLQR<12,4,horizon>::input_trajectory u_init_drone;\n//\tstd::fill(std::begin(u_init_drone), std::end(u_init_drone), u_drone);\n//\tiLQR<12,4,horizon>::state_input_trajectory soln_drone;\n//\tiLQR<12,4,total_steps>::state_input_trajectory soln_drone_rhc;\n//\n//\n//\n//\tclock_t t_start, t_end;\n//\n////\n//\tdouble seconds;\n//\tdrone_solver.set_MPC(u_init_drone);\n//\tint execution_steps=1;\n//\tsoln_drone_rhc.first[0]=X0_drone;\n//\tstd::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n//\tstd::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n//\tX_goal_drone<<1,1,1.5, 0,0,0, 0,0,0, 0,0,0;\n//\tt_start = clock();\n//\tfor(int i=0;i<total_steps;++i)\n//\t{\n////\t\tX_goal_drone<<10,0,0, 0,0,0, 0,0,0, 0,0,0;\n////\t\tif (i>total_steps/3)\n////\t\t\tX_goal_drone<<0,0,0, 0,0,0, 0,0,0, 0,0,0;\n//\t\tstd::cout<<\"iteration \"<<i<<std::endl;\n//////\n//\t\tsoln_drone=drone_solver.run_MPC(soln_drone_rhc.first[i], X_goal_drone, 100, execution_steps);\n////\n////////\t\tunsigned int microsecond = 1000000;\n////////\t\tusleep(2 * microsecond);\n////\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\t\tstd::cout<<soln_drone.first[39]<<std::endl;\n//\t\tsoln_drone_rhc.first[i+1]=soln_drone.first[1];\n//\t\tsoln_drone_rhc.second[i]=soln_drone.second[0];\n//\t}\n//\tt_end = clock();\n//////\n//////\n////////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n////////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\twrite_file<12,4,total_steps>(state_path,input_path, soln_drone_rhc);\n////\n//\tstd::cout<<\"finished\"<<std::endl;\n//\tseconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n//\tprintf(\"Time: %f s\\n\", seconds);\n\n\n/* End of single drone simulation*/\n\n\n\n\n\n\n\n\n\n\n/* This part is 2-drone simulation*/\n\n\n//\tcost<12*2,4*2> running_cost_dr2(Drone_Cost::running_cost2,tag4);\n//\tcost<12*2,4*2> terminal_cost_dr2(Drone_Cost::terminal_cost2,tag5);\n//\tdynamics<12*2,4*2> dynamics_dr2(Drone_Dynamics::dynamics_2,tag6,time_step);\n//\tiLQR<12*2,4*2,horizon>::input_trajectory u_init_drone2;\n//\n//\tiLQR<12*2,4*2,horizon> drone2_solver(running_cost_dr2,terminal_cost_dr2,dynamics_dr2);\n//\tEigen::Matrix<double,4*2,1> u_drone2=Eigen::Matrix<double,4*2,1>::Ones();\n//\tEigen::Matrix<double,12*2,1> X0_drone2=Eigen::Matrix<double,12*2,1>::Zero();\n////\tX0_drone2<<-2.5,-2.5,-2.5, 0,0,0, 0,0,0, 0,0,0,\n////\t\t\t2.5,-2.5,-2.5, 0,0,0, 0,0,0, 0,0,0;\n//\tX0_drone2<<-1,0,2, 0,0,0, 0,0,0, 0,0,0,\n//\t\t\t1,0,2, 0,0,0, 0,0,0, 0,0,0;\n//\tEigen::Matrix<double,12*2,1> X_goal_drone2;\n//\tu_drone2=u_drone2*sqrt(Drone_Dynamics::mass*Drone_Dynamics::g/(4*Drone_Dynamics::C_T));\n//\tstd::fill(std::begin(u_init_drone2), std::end(u_init_drone2), u_drone2);\n//\tiLQR<12*2,4*2,horizon>::state_input_trajectory soln_drone2;\n//\tiLQR<12*2,4*2,total_steps>::state_input_trajectory soln_drone2_rhc;\n//\n//\tclock_t t_start, t_end;\n//\n////\n//\tdouble seconds;\n//\tdrone2_solver.set_MPC(u_init_drone2);\n//\tint execution_steps=1;\n//\tsoln_drone2_rhc.first[0]=X0_drone2;\n//\tstd::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n//\tstd::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n////\tX_goal_drone2<<2.5,2.5,2.5, 0,0,0, 0,0,0, 0,0,0,\n////\t\t\t-2.5,2.5,2.5, 0,0,0, 0,0,0, 0,0,0;\n//\tX_goal_drone2<<1,0,2, 0,0,0, 0,0,0, 0,0,0,\n//\t\t\t-1,0,2, 0,0,0, 0,0,0, 0,0,0;\n//\tt_start = clock();\n//\tfor(int i=0;i<total_steps;++i)\n//\t{\n//\n////\t\tif (i>total_steps/3)\n////\t\t\tX_goal_drone<<0,0,0, 0,0,0, 0,0,0, 0,0,0;\n//\t\tstd::cout<<\"iteration \"<<i<<std::endl;\n//////\n//\t\tsoln_drone2=drone2_solver.run_MPC(soln_drone2_rhc.first[i], X_goal_drone2, 20, execution_steps);\n////\n////////\t\tunsigned int microsecond = 1000000;\n////////\t\tusleep(2 * microsecond);\n////\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\t\tsoln_drone2_rhc.first[i+1]=soln_drone2.first[1];\n//\t\tsoln_drone2_rhc.second[i]=soln_drone2.second[0];\n//\t}\n//\tt_end = clock();\n//////\n//////\n////////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n////////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\twrite_file<12*2,4*2,total_steps>(state_path,input_path, soln_drone2_rhc);\n////\n//\tstd::cout<<\"finished\"<<std::endl;\n//\tseconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n//\tprintf(\"Time: %f s\\n\", seconds);\n//\n/* End of 2-drone simulation*/\n\n\n//\n//\n\n//\n////\tdiff = difftime( stop, start );\n////\tstd::cout << \"Time: \" << diff << \" seconds\";\n////\tseconds = (double)(t_end - t_start) / CLOCKS_PER_SEC;\n////\tprintf(\"Time: %f s\\n\", seconds);\n//\t\tdrone_solver.set_MPC(u_init_drone);\n////\t\tt_start = clock();\n//\t\tstd::string state_write_path=\"/Users/talhakavuncu/Desktop/cflib_stream.txt\";\n//\t\tstd::string state_read_path=\"/Users/talhakavuncu/Desktop/stream.txt\";\n//\t\tstd::ifstream state_read_file(state_read_path);\n//\t\tstd::ofstream state_write_file(state_write_path);\n//\t\tEigen::IOFormat CommaInitFmt(Eigen::FullPrecision, Eigen::DontAlignCols, \",\", \", \", \"\", \"\", \"\", \"\");\n//\t\tdouble dt,x,y,z,roll,pitch,yaw;\n//\t\tstate_read_file>>dt>>x>>y >> z>>roll >> pitch>>yaw;\n//\t\tX0_drone<<x,y,z,roll,pitch,yaw,x/dt,y/dt,z/dt,roll/dt,pitch/dt,yaw/dt;\n//\t\tX_goal_drone<<0,0,1, 0,0,0, 0,0,0, 0,0,0;\n//\t\twhile(true)\n//\t\t{\n////\t\t\tX_goal_drone<<10,0,0, 0,0,0, 0,0,0, 0,0,0;\n////\t\t\tif (i>total_steps/3)\n////\t\t\t\tX_goal_drone<<0,0,0, 0,0,0, 0,0,0, 0,0,0;\n////\t\t\tstd::cout<<\"iteration \"<<i<<std::endl;\n//\t//\n//\n//\t\t\tsoln_drone=drone_solver.run_MPC(X0_drone, X_goal_drone, 50, 1);\n//\t\t\tstate_write_file.open(state_write_path,std::ios::out | std::ios::trunc);\n//\t\t\tstate_write_file<<soln_drone.first[1].transpose().format(CommaInitFmt);\n////\t\t\ti.transpose().format(CommaInitFmt)\n//\t\t\tstate_write_file.close();\n//\t\t\tstate_read_file>>dt>>x>>y >> z>>roll >> pitch>>yaw;\n//\t\t\tX0_drone<<x,y,z,roll,pitch,yaw,x/dt,y/dt,z/dt,roll/dt,pitch/dt,yaw/dt;\n//\t////\t\tunsigned int microsecond = 1000000;\n//\t////\t\tusleep(2 * microsecond);\n//\t////\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n////\t\t\tsoln_drone_rhc.first[i+1]=soln_drone.first[1];\n//\n////\t\t\tsoln_drone_rhc.second[i]=soln_drone.second[0];\n//\t\t}\n////\t\tt_end = clock();\n\n\n/* This part is integrator simulation */\n\n//\n//cost<3,3> integrator_running_cost(Single_Integrator_Cost::running_cost,tag7);\n//cost<3,3> integrator_terminal_cost(Single_Integrator_Cost::terminal_cost,tag8);\n//dynamics<3,3> integrator_dynamics(Single_Integrator_3D::dynamics,tag9,time_step);\n//iLQR<3,3,horizon>::input_trajectory u_init_integrator;\n//iLQR<3,3,horizon> integrator_solver(integrator_running_cost,integrator_terminal_cost,integrator_dynamics);\n//Eigen::Matrix<double,3,1> u_integrator=Eigen::Matrix<double,3,1>::Zero();\n//Eigen::Matrix<double,3,1> x0_integrator=Eigen::Matrix<double,3,1>::Zero();\n//Eigen::Matrix<double,3,1> x_goal_integrator;\n//iLQR<3,3,horizon>::state_input_trajectory soln_integrator;\n//iLQR<3,3,total_steps>::state_input_trajectory soln_integrator_rhc;\n//\n////\tu_drone2=u_drone2*sqrt(Drone_Dynamics::mass*Drone_Dynamics::g/(4*Drone_Dynamics::C_T));\n//\tstd::fill(std::begin(u_init_integrator), std::end(u_init_integrator), u_integrator);\n////\tiLQR<12*2,4*2,horizon>::state_input_trajectory soln_drone2;\n////\tiLQR<12*2,4*2,total_steps>::state_input_trajectory soln_drone2_rhc;\n//\n//\n//\n//\n//\n//\tclock_t t_start, t_end;\n////\n//////\n//\tx0_integrator<<0,0,0.5;\n////\tx0_integrator+=0.1*Eigen::Matrix<double,3,1>::Random();\n//\tdouble seconds;\n//\tintegrator_solver.set_MPC(u_init_integrator);\n//\tint execution_steps=1;\n//\tsoln_integrator_rhc.first[0]=x0_integrator;\n//\tstd::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n//\tstd::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n//\tt_start = clock();\n//\tfor(int i=0;i<total_steps;++i)\n//\t{\n//\t\tx_goal_integrator<<2,2,2;\n////\t\tif (i>total_steps/3)\n////\t\t\tx_goal_integrator<<0,0,0;\n//\t\tstd::cout<<\"iteration \"<<i<<std::endl;\n////////\n////\t\tauto term1=soln_integrator_rhc.first[i]+0.2*Eigen::Matrix<double,3,1>::Random();\n////\t\tauto term2=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n////\t\tauto term3=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n////\t\tauto term4=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n////\t\tauto term5=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n////\t\tauto term6=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n////\t\tauto term7=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n////\t\tauto term8=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n////\t\tauto term9=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n////\t\tauto term10=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n////\t\tauto term=(term1+term2+term3+term4+term5+term6+term7+term8+term9+term10)/10;\n//\t\tsoln_integrator=integrator_solver.run_MPC(soln_integrator_rhc.first[i],\n//\t\t\t\tx_goal_integrator, 100, execution_steps);\n//////\n//////////\t\tunsigned int microsecond = 1000000;\n//////////\t\tusleep(2 * microsecond);\n//////\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\t\tsoln_integrator_rhc.first[i+1]=soln_integrator.first[1];\n//\t\tsoln_integrator_rhc.second[i]=soln_integrator.second[0];\n//\t}\n//\tt_end = clock();\n//////\n////////\n//////////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n//////////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\twrite_file<3,3,total_steps>(state_path,input_path, soln_integrator_rhc);\n//////\n//\tstd::cout<<\"finished\"<<std::endl;\n//\tseconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n//\tprintf(\"Time: %f s\\n\", seconds);\n\n\n/*single integrator simulation ends */\n\n\n/*Single integrator 2 agent simulation */\n\n//\tcost<6,6> integrator2_running_cost(Single_Integrator_Cost::running_cost2,tag7);\n//\tcost<6,6> integrator2_terminal_cost(Single_Integrator_Cost::terminal_cost2,tag8);\n//\tdynamics<6,6> integrator2_dynamics(Single_Integrator_3D::dynamics2,tag9,time_step);\n//\tiLQR<6,6,horizon>::input_trajectory u_init_integrator2;\n//\tiLQR<6,6,horizon> integrator2_solver(integrator2_running_cost,integrator2_terminal_cost,integrator2_dynamics);\n//\tEigen::Matrix<double,6,1> u_integrator2=Eigen::Matrix<double,6,1>::Zero();\n//\tEigen::Matrix<double,6,1> x0_integrator2=Eigen::Matrix<double,6,1>::Zero();\n//\tx0_integrator2<<-1,0,2.001, 1,0,2;\n////\tstd::cout<<x0_integrator2<<std::endl;\n//\tEigen::Matrix<double,6,1> x_goal_integrator2;\n//\tx_goal_integrator2<<1,0,2, -1,0,2;\n//\tiLQR<6,6,horizon>::state_input_trajectory soln_integrator2;\n//\tiLQR<6,6,total_steps>::state_input_trajectory soln_integrator2_rhc;\n//\n//\t//\tu_drone2=u_drone2*sqrt(Drone_Dynamics::mass*Drone_Dynamics::g/(4*Drone_Dynamics::C_T));\n//\t//\tstd::fill(std::begin(u_init_drone2), std::end(u_init_drone2), u_drone2);\n//\t//\tiLQR<12*2,4*2,horizon>::state_input_trajectory soln_drone2;\n//\t//\tiLQR<12*2,4*2,total_steps>::state_input_trajectory soln_drone2_rhc;\n//\n//\n//\n//\n//\n//\t\tclock_t t_start, t_end;\n//\t//\n//\t////\n//\t\tdouble seconds;\n//\t\tintegrator2_solver.set_MPC(u_init_integrator2);\n//\t\tint execution_steps=1;\n//\t\tsoln_integrator2_rhc.first[0]=x0_integrator2;\n//\t\tstd::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n//\t\tstd::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n//\t\tt_start = clock();\n//\t\tfor(int i=0;i<total_steps;++i)\n//\t\t{\n////\t\t\tx_goal_integrator2<<2,2,2;\n//\t//\t\tif (i>total_steps/3)\n//\t//\t\t\tx_goal_integrator<<0,0,0;\n//\t\t\tstd::cout<<\"iteration \"<<i<<std::endl;\n//\t//////\n//\t\t\tsoln_integrator2=integrator2_solver.run_MPC(soln_integrator2_rhc.first[i],\n//\t\t\t\t\tx_goal_integrator2, 5, execution_steps);\n//\t////\n//\t////////\t\tunsigned int microsecond = 1000000;\n//\t////////\t\tusleep(2 * microsecond);\n//\t////\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\t\t\tsoln_integrator2_rhc.first[i+1]=soln_integrator2.first[1];\n//\t\t\tsoln_integrator2_rhc.second[i]=soln_integrator2.second[0];\n//\t\t}\n//\t\tt_end = clock();\n//\t////\n//\t//////\n//\t////////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n//\t////////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\t\twrite_file<6,6,total_steps>(state_path,input_path, soln_integrator2_rhc);\n//\t////\n//\t\tstd::cout<<\"finished\"<<std::endl;\n//\t\tseconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n//\t\tprintf(\"Time: %f s\\n\", seconds);\n\n/*Single integrator 2 agent simulation ends*/\n\n\n\n/*Double Integrator Simulation*/\n\n//\n//\n//\tcost<6,3> integrator_running_cost(Double_Integrator_Cost::running_cost,tag7);\n//\tcost<6,3> integrator_terminal_cost(Double_Integrator_Cost::terminal_cost,tag8);\n//\tdynamics<6,3> integrator_dynamics(Double_Integrator_3D::dynamics,tag9,time_step);\n//\tiLQR<6,3,horizon>::input_trajectory u_init_integrator;\n//\tiLQR<6,3,horizon> integrator_solver(integrator_running_cost,integrator_terminal_cost,integrator_dynamics);\n//\tEigen::Matrix<double,3,1> u_integrator=Eigen::Matrix<double,3,1>::Zero();\n//\tEigen::Matrix<double,6,1> x0_integrator=Eigen::Matrix<double,6,1>::Zero();\n//\tEigen::Matrix<double,6,1> x_goal_integrator;\n//\tiLQR<6,3,horizon>::state_input_trajectory soln_integrator;\n//\tiLQR<6,3,total_steps>::state_input_trajectory soln_integrator_rhc;\n//\n//\t//\tu_drone2=u_drone2*sqrt(Drone_Dynamics::mass*Drone_Dynamics::g/(4*Drone_Dynamics::C_T));\n//\t\tstd::fill(std::begin(u_init_integrator), std::end(u_init_integrator), u_integrator);\n//\t//\tiLQR<12*2,4*2,horizon>::state_input_trajectory soln_drone2;\n//\t//\tiLQR<12*2,4*2,total_steps>::state_input_trajectory soln_drone2_rhc;\n//\n//\n//\n//\n//\n//\t\tclock_t t_start, t_end;\n//\t//\n//\t////\n//\t\tx0_integrator<<0,0,0.5, 0,0,0;\n//\t//\tx0_integrator+=0.1*Eigen::Matrix<double,3,1>::Random();\n//\t\tdouble seconds;\n//\t\tintegrator_solver.set_MPC(u_init_integrator);\n//\t\tint execution_steps=1;\n//\t\tsoln_integrator_rhc.first[0]=x0_integrator;\n//\t\tstd::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n//\t\tstd::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n//\t\tt_start = clock();\n//\t\tfor(int i=0;i<total_steps;++i)\n//\t\t{\n//\t\t\tx_goal_integrator<<2,2,2, 0,0,0;\n//\t//\t\tif (i>total_steps/3)\n//\t//\t\t\tx_goal_integrator<<0,0,0;\n//\t\t\tstd::cout<<\"iteration \"<<i<<std::endl;\n//\t//////\n//\t//\t\tauto term1=soln_integrator_rhc.first[i]+0.2*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term2=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term3=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term4=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term5=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term6=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term7=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term8=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term9=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term10=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term=(term1+term2+term3+term4+term5+term6+term7+term8+term9+term10)/10;\n//\t\t\tsoln_integrator=integrator_solver.run_MPC(soln_integrator_rhc.first[i],\n//\t\t\t\t\tx_goal_integrator, 5, execution_steps);\n//\t////\n//\t////////\t\tunsigned int microsecond = 1000000;\n//\t////////\t\tusleep(2 * microsecond);\n//\t////\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\t\t\tsoln_integrator_rhc.first[i+1]=soln_integrator.first[1];\n//\t\t\tsoln_integrator_rhc.second[i]=soln_integrator.second[0];\n//\t\t}\n//\t\tt_end = clock();\n//\t////\n//\t//////\n//\t////////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n//\t////////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\t\twrite_file<6,3,total_steps>(state_path,input_path, soln_integrator_rhc);\n//\t////\n//\t\tstd::cout<<\"finished\"<<std::endl;\n//\t\tseconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n//\t\tprintf(\"Time: %f s\\n\", seconds);\n\n\n\n\n/*Double Integrator Simulation Ends*/\n\n\n/*First Order Drone Simulation */\n\n\n\n\tcost<6,6> drone_running_cost(Drone_First_Order_Cost::running_cost,tag7);\n\tcost<6,6> drone_terminal_cost(Drone_First_Order_Cost::terminal_cost,tag8);\n\tdynamics<6,6> drone_dynamics(Drone_First_Order_Dynamics::dynamics,tag9,time_step);\n\tiLQR<6,6,horizon>::input_trajectory u_init_drone;\n\tiLQR<6,6,horizon> drone_solver(drone_running_cost,drone_terminal_cost,drone_dynamics);\n\tEigen::Matrix<double,6,1> u_drone=Eigen::Matrix<double,6,1>::Zero();\n\tEigen::Matrix<double,6,1> x0_drone=Eigen::Matrix<double,6,1>::Zero();\n\tEigen::Matrix<double,6,1> x_goal_drone;\n\tiLQR<6,6,horizon>::state_input_trajectory soln_drone;\n\tiLQR<6,6,total_steps>::state_input_trajectory soln_drone_rhc;\n\n\t//\tu_drone2=u_drone2*sqrt(Drone_Dynamics::mass*Drone_Dynamics::g/(4*Drone_Dynamics::C_T));\n\t\tstd::fill(std::begin(u_init_drone), std::end(u_init_drone), u_drone);\n\t//\tiLQR<12*2,4*2,horizon>::state_input_trajectory soln_drone2;\n\t//\tiLQR<12*2,4*2,total_steps>::state_input_trajectory soln_drone2_rhc;\n\n\n\n\n\n\t\tclock_t t_start, t_end;\n\t//\n\t////\n\t\tx0_drone<<0,0,0.5, 0,0,0;\n\t//\tx0_integrator+=0.1*Eigen::Matrix<double,3,1>::Random();\n\t\tdouble seconds;\n\t\tdrone_solver.set_MPC(u_init_drone);\n\t\tint execution_steps=1;\n\t\tsoln_drone_rhc.first[0]=x0_drone;\n\t\tstd::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n\t\tstd::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n\t\tt_start = clock();\n\t\tfor(int i=0;i<total_steps;++i)\n\t\t{\n\t\t\tx_goal_drone<<2,2,2, 0,0,0;\n\t//\t\tif (i>total_steps/3)\n\t//\t\t\tx_goal_integrator<<0,0,0;\n\t\t\tstd::cout<<\"iteration \"<<i<<std::endl;\n\t\t\tdouble scale=0.01;\n\t\t\tauto term1=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n//\t\t\tauto term2=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n//\t\t\tauto term3=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n//\t\t\tauto term4=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n//\t\t\tauto term5=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n//\t\t\tauto term6=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n//\t\t\tauto term7=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n//\t\t\tauto term8=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n//\t\t\tauto term9=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n//\t\t\tauto term10=soln_drone_rhc.first[i]+scale*Eigen::Matrix<double,6,1>::Random();\n//\t\t\tauto term=(term1+term2+term3+term4+term5+term6+term7+term8+term9+term10)/10;\n\t\t\tsoln_drone=drone_solver.run_MPC(term1,\n\t\t\t\t\tx_goal_drone, 5, execution_steps);\n\t////\n\t////////\t\tunsigned int microsecond = 1000000;\n\t////////\t\tusleep(2 * microsecond);\n\t////\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n\t\t\tsoln_drone_rhc.first[i+1]=soln_drone.first[1];\n\t\t\tsoln_drone_rhc.second[i]=soln_drone.second[0];\n\t\t}\n\t\tt_end = clock();\n\t////\n\t//////\n\t////////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n\t////////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n\t\twrite_file<6,6,total_steps>(state_path,input_path, soln_drone_rhc);\n\t////\n\t\tstd::cout<<\"finished\"<<std::endl;\n\t\tseconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n\t\tprintf(\"Time: %f s\\n\", seconds);\n\n\n\n\n/*First Order Drone Simulation Ends*/\n\n/*First Order 2 Drone Simulation*/\n\n//\tcost<12,12> drone2_running_cost(Drone_First_Order_Cost::running_cost2,tag7);\n//\tcost<12,12> drone2_terminal_cost(Drone_First_Order_Cost::terminal_cost2,tag8);\n//\tdynamics<12,12> drone2_dynamics(Drone_First_Order_Dynamics::dynamics_2,tag9,time_step);\n//\tiLQR<12,12,horizon>::input_trajectory u_init_drone2;\n//\tiLQR<12,12,horizon> drone2_solver(drone2_running_cost,drone2_terminal_cost,drone2_dynamics);\n//\tEigen::Matrix<double,12,1> u_drone2=Eigen::Matrix<double,12,1>::Zero();\n//\tEigen::Matrix<double,12,1> x0_drone2=Eigen::Matrix<double,12,1>::Zero();\n//\tEigen::Matrix<double,12,1> x_goal_drone2;\n//\tiLQR<12,12,horizon>::state_input_trajectory soln_drone2;\n//\tiLQR<12,12,total_steps>::state_input_trajectory soln_drone2_rhc;\n//\n//\t//\tu_drone2=u_drone2*sqrt(Drone_Dynamics::mass*Drone_Dynamics::g/(4*Drone_Dynamics::C_T));\n//\t\tstd::fill(std::begin(u_init_drone2), std::end(u_init_drone2), u_drone2);\n//\t//\tiLQR<12*2,4*2,horizon>::state_input_trajectory soln_drone2;\n//\t//\tiLQR<12*2,4*2,total_steps>::state_input_trajectory soln_drone2_rhc;\n//\n//\n//\n//\n//\n//\t\tclock_t t_start, t_end;\n//\t//\n//\t////\n////\t\tx0_drone2<<0,0,0.5, 0,0,1;\n//\t\tx0_drone2<<-3,0,2.1, 0,0,0, 3,0,2, 0,0,0;\n//\t\tx_goal_drone2<<3,0,2, 0,0,0, -3,0,2, 0,0,0;\n//\n//\t//\tx0_integrator+=0.1*Eigen::Matrix<double,3,1>::Random();\n//\t\tdouble seconds;\n//\t\tdrone2_solver.set_MPC(u_init_drone2);\n//\t\tint execution_steps=1;\n//\t\tsoln_drone2_rhc.first[0]=x0_drone2;\n//\t\tstd::string state_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/states.txt\";\n//\t\tstd::string input_path=\"/Users/talhakavuncu/Desktop/research/cpp_code/inputs.txt\";\n//\t\tt_start = clock();\n//\t\tfor(int i=0;i<total_steps;++i)\n//\t\t{\n////\t\t\tx_goal_drone2<<2,2,2, 0,0,0;\n//\t//\t\tif (i>total_steps/3)\n//\t//\t\t\tx_goal_integrator<<0,0,0;\n//\t\t\tstd::cout<<\"iteration \"<<i<<std::endl;\n//\t//////\n//\t//\t\tauto term1=soln_integrator_rhc.first[i]+0.2*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term2=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term3=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term4=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term5=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term6=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term7=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term8=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term9=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term10=soln_integrator_rhc.first[i]+0.02*Eigen::Matrix<double,3,1>::Random();\n//\t//\t\tauto term=(term1+term2+term3+term4+term5+term6+term7+term8+term9+term10)/10;\n//\t\t\tsoln_drone2=drone2_solver.run_MPC(soln_drone2_rhc.first[i],\n//\t\t\t\t\tx_goal_drone2, 5, execution_steps);\n//\t////\n//\t////////\t\tunsigned int microsecond = 1000000;\n//\t////////\t\tusleep(2 * microsecond);\n//\t////\t\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\t\t\tsoln_drone2_rhc.first[i+1]=soln_drone2.first[1];\n//\t\t\tsoln_drone2_rhc.second[i]=soln_drone2.second[0];\n//\t\t}\n//\t\tt_end = clock();\n//\t////\n//\t//////\n//\t////////\tsoln_drone=drone_solver.solve_open_loop(X0_drone, X0_drone, 200, u_init_drone, horizon);\n//\t////////\twrite_file<12,4,horizon>(state_path,input_path, soln_drone);\n//\t\twrite_file<12,12,total_steps>(state_path,input_path, soln_drone2_rhc);\n//\t////\n//\t\tstd::cout<<\"finished\"<<std::endl;\n//\t\tseconds = 1/((double)(t_end - t_start) / CLOCKS_PER_SEC/total_steps);\n//\t\tprintf(\"Time: %f s\\n\", seconds);\n\n\n\n\n\n\n\n/*First Order 2 Drone Simulation Ends*/\n};\n", "meta": {"hexsha": "301252b132306304d36c2d3efa81fdfdb773d960", "size": 29866, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros_ws/src/iconlab/src/iLQR_node/main.cpp", "max_stars_repo_name": "labicon/crazyswarm-labicon", "max_stars_repo_head_hexsha": "32a1cd553093a31ed86058c5a9868b5a6a59dfe6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ros_ws/src/iconlab/src/iLQR_node/main.cpp", "max_issues_repo_name": "labicon/crazyswarm-labicon", "max_issues_repo_head_hexsha": "32a1cd553093a31ed86058c5a9868b5a6a59dfe6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ros_ws/src/iconlab/src/iLQR_node/main.cpp", "max_forks_repo_name": "labicon/crazyswarm-labicon", "max_forks_repo_head_hexsha": "32a1cd553093a31ed86058c5a9868b5a6a59dfe6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2457293035, "max_line_length": 113, "alphanum_fraction": 0.6895466417, "num_tokens": 10594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.43857676454415295}}
{"text": "#pragma once\n\n#include <scomplex/simplicial_complex.hpp>\n#include <scomplex/types.hpp>\n\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/Sparse>\n#include <cmath>\n#include <exception>\n#include <tuple>\n#include <vector>\n\n#include <memory>\n#include <fstream>\n\nnamespace gsimp {\n\nclass non_zero_chain : public std::exception {};\n\nclass bounding_chain {\n    std::shared_ptr<simplicial_complex> s_comp;\n    std::vector<std::unique_ptr<matrix_t>> boundary_matrices;\n    void populate_matrices();\n\n   public:\n    bounding_chain(simplicial_complex& sc);\n    bounding_chain(std::shared_ptr<simplicial_complex> sc);\n    bounding_chain(std::vector<point_t>& points, std::vector<cell_t>& tris);\n    ~bounding_chain();\n    chain_t get_bounding_chain(chain_t&);\n};\n\n//---------------------------------------\n// implementation\n\nbounding_chain::~bounding_chain() {}\n\nbounding_chain::bounding_chain(std::shared_ptr<simplicial_complex> sc) {\n    s_comp = sc;\n    populate_matrices();\n}\n\nbounding_chain::bounding_chain(simplicial_complex& sc) {\n    s_comp = std::make_shared<simplicial_complex>(sc);\n    populate_matrices();\n}\n\nbounding_chain::bounding_chain(std::vector<point_t>& points,\n                               std::vector<cell_t>& tris) {\n    s_comp = std::make_shared<simplicial_complex>(points,tris);\n    populate_matrices();\n}\n\nvoid bounding_chain::populate_matrices() {\n    for (int d = 0; d < s_comp->dimension(); ++d) {\n        auto level_matrix = s_comp->get_boundary_matrix(d);\n        boundary_matrices.push_back(\n            std::unique_ptr<matrix_t>(new matrix_t(level_matrix)));\n    }\n}\n\n// round vectors for comparison\nvector_t round_vec(vector_t vec) {\n    vector_t rounded_vec(vec.rows());\n    for (int i = 0; i < vec.rows(); ++i) {\n        int coef = round(vec.coeffRef(i));\n        if (coef != 0) rounded_vec.coeffRef(i) = coef;\n    }\n    return rounded_vec;\n}\n\nbool equals(vector_t vec1, vector_t vec2) {\n    for (int i = 0; i < vec1.rows(); ++i) {\n        if (vec1.coeffRef(i) != vec2.coeffRef(i)) {\n            std::cout << i << \": \" << vec1.coeffRef(i) << \" \"\n                      << vec2.coeffRef(i) << '\\n';\n            return false;\n        }\n    }\n    return true;\n}\n\nchain_t bounding_chain::get_bounding_chain(chain_t& chain) {\n    int chain_d;\n    vector_t chain_v;\n    std::tie<int, vector_t>(chain_d, chain_v) = chain;\n\n    if (chain_d >= s_comp->dimension()) throw non_zero_chain();\n\n    Eigen::LeastSquaresConjugateGradient<matrix_t> lscg;\n    lscg.compute(*(boundary_matrices.at(chain_d)));\n\n    vector_t bound_chain(round_vec(lscg.solve(chain_v)));\n    vector_t result(round_vec(*(boundary_matrices.at(chain_d)) * bound_chain));\n\n    if (equals(result, chain_v))\n        return chain_t(chain_d + 1, bound_chain);\n    else\n        throw non_zero_chain();\n}\n\n};\n", "meta": {"hexsha": "32ceb69d28a0d1ed3181b3eea6b8dc663fe8a63b", "size": 2791, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/scomplex/chain_calc.hpp", "max_stars_repo_name": "crvs/coeff-flow", "max_stars_repo_head_hexsha": "24a2bbae4f2d11d29332cb00c453e4d9a8ed6f57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-10-03T12:32:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-25T19:24:27.000Z", "max_issues_repo_path": "lib/scomplex/chain_calc.hpp", "max_issues_repo_name": "crvs/coeff-flow", "max_issues_repo_head_hexsha": "24a2bbae4f2d11d29332cb00c453e4d9a8ed6f57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T22:50:35.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-28T14:05:52.000Z", "max_forks_repo_path": "lib/scomplex/chain_calc.hpp", "max_forks_repo_name": "crvs/coeff-flow", "max_forks_repo_head_hexsha": "24a2bbae4f2d11d29332cb00c453e4d9a8ed6f57", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0970873786, "max_line_length": 79, "alphanum_fraction": 0.6538874955, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.43857676454415295}}
{"text": "#include <boost/config.hpp>\n#include <iostream>\n#include <fstream> //file output\n#include <cfloat>\n#include <omp.h>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/rmat_graph_generator.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/graph/graph_traits.hpp>\n \nvoid printUsageAndExit()\n{\n  printf(\"%s\", \"Usage:./rmatg x y\\n\");\n  printf(\"%s\", \"x is the size of the graph, x>32 (Boost generator hang if x<32)\\n\");\n  printf(\"%s\", \"y is the source of sssp\\n\");\n  exit(0);\n}\n\nint main(int argc, char *argv[])\n{\n  // read size\n  if (argc < 3) printUsageAndExit();\n  int size = atoi (argv[1]);\n  if (size<32) printUsageAndExit();\n  int source_sssp =atoi (argv[2]);\n  assert (size > 1 && size < INT_MAX);\n  assert (source_sssp >= 0 && source_sssp < size);\n  const unsigned num_edges = 15 * size;\n  \n  // Some boost types\n  typedef boost::no_property VertexProperty;\n  typedef boost::property<boost::edge_weight_t, float> EdgeProperty;\n  typedef boost::adjacency_list<boost::mapS, boost::vecS, boost::directedS, VertexProperty, EdgeProperty> Graph;\n  typedef boost::unique_rmat_iterator<boost::minstd_rand, Graph> RMATGen;\n  typedef boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n  boost::minstd_rand gen;\n  boost::graph_traits<Graph>::edge_iterator edge, edge_end;\n\n  /************************\n   * Random weights\n   ************************/\n  // !!! WARNING !!!\n  // watch the stack\n  float* weight = new float[num_edges]; \n  int count = 0;\n  for( int i = 0; i < num_edges;  ++i)\n    weight[i] = (rand()%10)+(rand()%100)*(1.2e-2f);\n\n  /************************\n   * RMAT Gen\n   ************************/\n  Graph g(RMATGen(gen, size, num_edges, 0.57, 0.19, 0.19, 0.05,true),RMATGen(),weight, size);\n  std::cout << \"Generator : done. Edges = \"<<boost::num_edges(g)<<std::endl; \n  assert (num_edges == boost::num_edges(g));\n  // debug print after gen\n  //for( boost::tie(edge, edge_end) = boost::edges(g); edge != edge_end; ++edge)\n  //  std::cout << boost::source(*edge, g) << ' ' << boost::target(*edge, g)<< ' '<<  boost::get(boost::get(boost::edge_weight, g),*edge) << '\\n';\n  \n  /************************\n   * Dijkstra\n   ************************/\n  std::vector<vertex_descriptor> p(num_vertices(g));\n  std::vector<float> d(num_vertices(g));\n  vertex_descriptor s = vertex(source_sssp, g); //define soruce node\n  \n  double start = omp_get_wtime();\n  dijkstra_shortest_paths(g, s,\n                          predecessor_map(boost::make_iterator_property_map(p.begin(), get(boost::vertex_index, g))).\n                          distance_map(boost::make_iterator_property_map(d.begin(), get(boost::vertex_index, g))));\n\n  double stop = omp_get_wtime();\n  std::cout << \"Time = \" << stop-start << \"s\"<< std::endl;\n\n  /************************\n   * Print\n   ************************/\n  /*\n  boost::graph_traits<Graph>::vertex_iterator vi, vend;\n  std::cout << \"SOURCE = \"<< source_sssp << std::endl; \n  for (boost::tie(vi, vend) = vertices(g); vi != vend; ++vi) \n  {\n    if (d[*vi] != FLT_MAX) \n    {\n      std::cout << \"d(\" << *vi << \") = \" << d[*vi] << \", \";\n      std::cout << \"parent = \" << p[*vi] << std::endl; \n    }\n    else\n      std::cout << \"d(\" << *vi << \") = INF\"<< std::endl;\n  }\n  */\n  return 0;\n                \n}\n\n", "meta": {"hexsha": "4e3c81fb82e178bd51c1b7111d35bdff5c528189", "size": 3451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/nvgraph/test/ref/ref_sssp_BGL.cpp", "max_stars_repo_name": "seunghwak/cugraph", "max_stars_repo_head_hexsha": "f2f6f9147ce8c2f46b7b6dbc335f885c11b69004", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2019-09-13T11:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T10:11:59.000Z", "max_issues_repo_path": "cpp/nvgraph/test/ref/ref_sssp_BGL.cpp", "max_issues_repo_name": "seunghwak/cugraph", "max_issues_repo_head_hexsha": "f2f6f9147ce8c2f46b7b6dbc335f885c11b69004", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-02-12T14:55:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T17:55:12.000Z", "max_forks_repo_path": "cpp/nvgraph/test/ref/ref_sssp_BGL.cpp", "max_forks_repo_name": "seunghwak/cugraph", "max_forks_repo_head_hexsha": "f2f6f9147ce8c2f46b7b6dbc335f885c11b69004", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-04-06T01:34:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-21T17:13:24.000Z", "avg_line_length": 34.8585858586, "max_line_length": 146, "alphanum_fraction": 0.5960591133, "num_tokens": 970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.43857675727018297}}
{"text": "/* \n * Open Source Movement Analysis Library\n * Copyright (C) 2016, Moveck Solution Inc., all rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n *     * Redistributions of source code must retain the above\n *       copyright notice, this list of conditions and the following\n *       disclaimer.\n *     * Redistributions in binary form must reproduce the above\n *       copyright notice, this list of conditions and the following\n *       disclaimer in the documentation and/or other materials\n *       provided with the distribution.\n *     * Neither the name(s) of the copyright holders nor the names\n *       of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written\n *       permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include \"openma/body/unitquaternionposeestimator.h\"\n\n#include \"openma/body/landmarksregistrar.h\"\n#include \"openma/body/landmarkstranslator.h\"\n#include \"openma/body/model.h\"\n#include \"openma/body/point.h\"\n#include \"openma/body/referenceframe.h\"\n#include \"openma/body/segment.h\"\n#include \"openma/body/skeletonhelper.h\"\n#include \"openma/body/utils.h\"\n#include \"openma/base/trial.h\"\n#include \"openma/base/logger.h\"\n#include \"openma/math.h\"\n\n#include <Eigen/Eigenvalues> // Eigen::SelfAdjointEigenSolver\n\n#include <iostream>\n\n// -------------------------------------------------------------------------- //\n//                                 PUBLIC API                                 //\n// -------------------------------------------------------------------------- //\n\nOPENMA_INSTANCE_STATIC_TYPEID(ma::body::UnitQuaternionPoseEstimator);\n\nnamespace ma\n{\nnamespace body\n{\n  /**\n   * @class UnitQuaternionPoseEstimator openma/body/unitquaternionposeestimator.h\n   * @brief Least square pose estimator based on unit quaternions\n   *\n   * This estimator is based on the paper of Horn [1] that use unit quaternions to find the rigid body transformation betwen two group of markers.\n   *\n   * @par References\n   *  1. Horn B.K.P., <em>Closed-form solution of absolute orientation using unit quaternions</em>, Journal of the Optical Society of America, 1987, 4\n   *\n   * @ingroup openma_body\n   */\n  \n  /**\n   * Constructor\n   */\n  UnitQuaternionPoseEstimator::UnitQuaternionPoseEstimator(const std::string& name, Node* parent)\n  : PoseEstimator(name,parent)\n  {};\n  \n  /**\n   * Destructor (default)\n   */\n  UnitQuaternionPoseEstimator::~UnitQuaternionPoseEstimator() _OPENMA_NOEXCEPT = default;\n  \n  /**\n   * Internaly call the method UnitQuaternion::reconstruct().\n   */\n  bool UnitQuaternionPoseEstimator::run(Model* output, SkeletonHelper* helper, Trial* trial)\n  {\n    // 0. Check\n    if (output == nullptr)\n    {\n      error(\"UnitQuaternionPoseEstimator - Null output passed. Pose estimator aborted.\");\n      return false;\n    }\n    if (helper == nullptr)\n    {\n      error(\"UnitQuaternionPoseEstimator - Null helper passed. Pose estimator aborted.\");\n      return false;\n    }\n    if (trial == nullptr)\n    {\n      error(\"UnitQuaternionPoseEstimator - Null trial passed. Pose estimator aborted.\");\n      return false;\n    }\n    // 1. Look for the child node MarkerClusterRegistration\n    auto mcr = helper->findChild(\"MarkerClusterRegistration\",{},false);\n    if (mcr == nullptr)\n    {\n      error(\"UnitQuaternionPoseEstimator - No marker cluster registration found. Pose estimator aborted.\");\n      return false;\n    }\n    const auto& lt = helper->findChild<LandmarksTranslator*>({},{},false);\n    const auto& segments = output->segments()->findChildren<Segment*>({},{},false);\n    double startTime = 0.0, sampleRate = 0.0;\n    bool ok = false;\n    for (auto segment : segments)\n    {\n      const auto& lr = segment->findChild<LandmarksRegistrar*>({},{},false);\n      if (lr == nullptr)\n        continue;\n      // Look for the markers in the trial and the marker cluster registration\n      auto globalMarkers = extract_landmark_positions(nullptr, lr->retrieveLandmarks(lt, trial->timeSequences()), &sampleRate, &startTime, &ok);\n      if (!ok)\n      {\n        error(\"UnitQuaternionPoseEstimator - The sampling information is not consistent between required landmarks (sampling rates or start times are not the same). Calibration aborted.\");\n        return false;\n      }\n      std::vector<std::pair<Eigen::Map<Eigen::Matrix<double,3,1>>,const math::Map<math::Position>&>> mappedMarkers;\n      mappedMarkers.reserve(globalMarkers.size());\n      auto it = globalMarkers.begin();\n      while (it != globalMarkers.end())\n      {\n        Point* localMarker = nullptr;\n        if (!it->second.isValid() || ((localMarker = mcr->findChild<Point*>(segment->name()+\".\"+it->first,{},false)) == nullptr))\n          it = globalMarkers.erase(it);\n        else\n        {\n          mappedMarkers.push_back({localMarker->data(),it->second});\n          ++it;\n        }\n      }\n      assert(globalMarkers.size() == mappedMarkers.size());\n      if (mappedMarkers.size() < 3)\n      {\n        error(\"Less than 3 valid markers was found for the segment '%s'. Impossible to compute the TCS. Pose estimator aborted.\", segment->name().c_str());\n        return false;\n      }\n      // Reconstruct for each sample\n      unsigned numSamples = std::numeric_limits<unsigned>::max();\n      for (const auto& marker : globalMarkers)\n      {\n        numSamples = std::min<unsigned>(numSamples, marker.second.rows());\n        if (marker.second.rows() != numSamples)\n        {\n          error(\"The number of samples for the markers used by the cluster '%s.Cluster' is not the same. Impossible to compute the TCS. Pose estimator aborted.\", segment->name().c_str());\n          return false;\n        }\n      }\n      ma::math::Pose tcs(numSamples);\n      Eigen::Matrix<double,3,3> M;\n      Eigen::Matrix<double,4,4> N;\n      Eigen::Matrix<double,3,Eigen::Dynamic> ps1, ps2;\n      for (unsigned i = 0 ; i < numSamples ; ++i)\n      {\n        int inc = 0;\n        ps1.setZero(3,static_cast<int>(globalMarkers.size()));\n        ps2.setZero(3,static_cast<int>(globalMarkers.size()));\n        for (const auto& m : mappedMarkers)\n        {\n          if (m.second.residuals().coeff(i) >= 0.0)\n          {\n            ps1.col(inc) = m.first; // Local\n            ps2.col(inc) = m.second.values().row(i); // Global\n            ++inc;\n          }\n        }\n        if (inc < 3) // Not enough landmark to create the least square fitting.\n        {\n          tcs.residuals().coeffRef(i) = -1.0;\n          continue;\n        }\n        ps1.resize(Eigen::NoChange,inc);\n        ps2.resize(Eigen::NoChange,inc);\n        // Express the point sets regarding to their respective center\n        Eigen::Matrix<double,3,1> p1 = (ps1.rowwise().sum() / static_cast<double>(inc));\n        ps1 -= p1.replicate(1,inc);\n        // ps1.row(0).array() -= p1.x();\n        // ps1.row(1).array() -= p1.y();\n        // ps1.row(2).array() -= p1.z();\n        Eigen::Matrix<double,3,1> p2 = ps2.rowwise().sum() / static_cast<double>(inc);\n        ps2 -= p2.replicate(1,inc);\n        // ps2.row(0).array() -= p2.x();\n        // ps2.row(1).array() -= p2.y();\n        // ps2.row(2).array() -= p2.z();\n        // Build the matrice N\n        M.setZero();\n        for (int j = 0 ; j < inc ; ++j)\n          M += ps1.col(j) * ps2.col(j).transpose();\n        N.setZero();\n        N.coeffRef(0,1) = N.coeffRef(1,0) = M.coeff(1,2) - M.coeff(2,1);\n        N.coeffRef(0,2) = N.coeffRef(2,0) = M.coeff(2,0) - M.coeff(0,2);\n        N.coeffRef(0,3) = N.coeffRef(3,0) = M.coeff(0,1) - M.coeff(1,0);\n        N.coeffRef(1,2) = N.coeffRef(2,1) = M.coeff(0,1) + M.coeff(1,0);\n        N.coeffRef(1,3) = N.coeffRef(3,1) = M.coeff(2,0) + M.coeff(0,2);\n        N.coeffRef(2,3) = N.coeffRef(3,2) = M.coeff(1,2) + M.coeff(2,1);\n        N.coeffRef(0,0) =  M.coeff(0,0) + M.coeff(1,1) + M.coeff(2,2);\n        N.coeffRef(1,1) =  M.coeff(0,0) - M.coeff(1,1) - M.coeff(2,2);\n        N.coeffRef(2,2) = -M.coeff(0,0) + M.coeff(1,1) - M.coeff(2,2);\n        N.coeffRef(3,3) = -M.coeff(0,0) - M.coeff(1,1) + M.coeff(2,2);\n        // Extract the eigen vector associated with the most positive eigen value and compute the rotation matrix (the extracted eigen vector is a quaternion)\n        Eigen::SelfAdjointEigenSolver< Eigen::Matrix<double,4,4> > eig(N);\n        int idx; eig.eigenvalues().maxCoeff(&idx);\n        // Q2R need to be done in 2 steps as the eigen vector is formatted as WXYZ and the internal storage in Eigen is XYZW\n        Eigen::Matrix<double,4,1> q = eig.eigenvectors().col(idx);\n        Eigen::Matrix<double,3,3> R = Eigen::Quaternion<double>(q.coeff(0),q.coeff(1),q.coeff(2),q.coeff(3)).toRotationMatrix();\n        // Set the pose\n        auto row = tcs.values().row(i);\n        row.segment<3>(0) = R.col(0);    // u\n        row.segment<3>(3) = R.col(1);    // v\n        row.segment<3>(6) = R.col(2);    // w\n        row.segment<3>(9) = p2 - R * p1; // o\n        tcs.residuals().coeffRef(i) = 0.0;\n      }\n      // Reconstruction of the SCS\n      // Look for Reference frame in the node MarkerClusterRegistration\n      auto relframe = mcr->findChild<ReferenceFrame*>(segment->name() + \".SCS\", {}, false);\n      if (relframe != nullptr)\n      {\n        relframe->addParent(segment);\n        math::to_timesequence(transform_relative_frame(relframe, segment, tcs), segment->name() + \".SCS\", sampleRate, startTime, TimeSequence::Pose, \"\", segment);\n      }\n      math::to_timesequence(tcs, segment->name() + \".TCS\", sampleRate, startTime, TimeSequence::Pose, \"\", segment);\n    }\n    return true;\n  }\n};\n};", "meta": {"hexsha": "751c76500b54e97528c7df8a0ff720af77e8474d", "size": 10394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/body/src/unitquaternionposeestimator.cpp", "max_stars_repo_name": "OpenMA/openma", "max_stars_repo_head_hexsha": "6f3b55292fd0a862b3444f11d71d0562cfe81ac1", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-06-28T13:51:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T16:33:00.000Z", "max_issues_repo_path": "modules/body/src/unitquaternionposeestimator.cpp", "max_issues_repo_name": "bmswgnp/openma", "max_issues_repo_head_hexsha": "6f3b55292fd0a862b3444f11d71d0562cfe81ac1", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 82.0, "max_issues_repo_issues_event_min_datetime": "2016-04-09T15:19:31.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-15T18:56:12.000Z", "max_forks_repo_path": "modules/body/src/unitquaternionposeestimator.cpp", "max_forks_repo_name": "bmswgnp/openma", "max_forks_repo_head_hexsha": "6f3b55292fd0a862b3444f11d71d0562cfe81ac1", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-03-29T14:28:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-29T07:39:19.000Z", "avg_line_length": 43.3083333333, "max_line_length": 188, "alphanum_fraction": 0.621223783, "num_tokens": 2692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.43845898520362686}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_LGAMMA_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_LGAMMA_HPP\n\n#include <stan/math/prim/scal/fun/boost_policy.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the natural logarithm of the gamma function applied to\n * the specified argument.\n *\n   \\f[\n   \\mbox{lgamma}(x) =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x\\in \\{\\dots, -3, -2, -1, 0\\}\\\\\n     \\ln\\Gamma(x) & \\mbox{if } x\\not\\in \\{\\dots, -3, -2, -1, 0\\}\\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{lgamma}(x)}{\\partial x} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x\\in \\{\\dots, -3, -2, -1, 0\\}\\\\\n     \\Psi(x) & \\mbox{if } x\\not\\in \\{\\dots, -3, -2, -1, 0\\}\\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN}\n   \\end{cases}\n\\f]\n*\n* @param x argument\n* @return natural logarithm of the gamma function applied to\n* argument\n*/\ninline double lgamma(double x) {\n  return boost::math::lgamma(x, boost_policy_t());\n}\n\n/**\n * Return the natural logarithm of the gamma function applied\n * to the specified argument.\n *\n * @param x argument\n * @return natural logarithm of the gamma function applied to\n * argument\n */\ninline double lgamma(int x) { return boost::math::lgamma(x, boost_policy_t()); }\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "1d93b622dd32a1c34f825fbf1f821ea3ac4fbf94", "size": 1366, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/lgamma.hpp", "max_stars_repo_name": "nolta/math", "max_stars_repo_head_hexsha": "fb2cc51188b0171d70d63d5ef8be44998f5b3814", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/scal/fun/lgamma.hpp", "max_issues_repo_name": "nolta/math", "max_issues_repo_head_hexsha": "fb2cc51188b0171d70d63d5ef8be44998f5b3814", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/scal/fun/lgamma.hpp", "max_forks_repo_name": "nolta/math", "max_forks_repo_head_hexsha": "fb2cc51188b0171d70d63d5ef8be44998f5b3814", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7735849057, "max_line_length": 80, "alphanum_fraction": 0.6361639824, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.43845897959284025}}
{"text": "#include <NTL/ZZ_p.h>\n#include <NTL/xdouble.h>\n#include <sstream>\n#include <vector>\n#include <tuple>\n#include <complex>\n#include <parallel/algorithm>\n#include <fftw3.h> \n#include \"bleichenbacher.h\"\n\nusing namespace std;\nusing namespace NTL;\n\nxdouble average, stdDev_accum;\n\nstruct {\n\n\tbool operator()(tuple<ZZ_p, ZZ_p> a, \n\t\ttuple<ZZ_p, ZZ_p> b) const\n\t{\n\t\tZZ a_ZZ, b_ZZ;\n\n\t\ta_ZZ = rep(get<1>(a));\n\t\tb_ZZ = rep(get<1>(b));\n\t\n\t\treturn a_ZZ < b_ZZ;\n\t}\n\n} compareHCtuple;\n\ntemplate<class To, class From>\nTo NTLtoOther(From *x)\n{\n\tstringstream ss;\n\tss << *x;\n\treturn atof(ss.str().c_str());\n}\n\ndouble Z_exp(ZZ_p h);\nvector<tuple<int, double>> internal_maxM(vector<tuple<ZZ_p, ZZ_p>> *hcPairs,\n\tint Z_index_divisor,\n\tint l);\nvoid internal_hcFromRs(vector<tuple<ZZ_p, ZZ_p, ZZ_p>> *rsmTuples, \n\tvector<tuple<ZZ_p, ZZ_p>> *hcPairs,\n\tint numBits,\n\tZZ knownBits,\n\tbool specialH);\n\nvoid hcFromRs(vector<tuple<ZZ_p, ZZ_p, ZZ_p>> *rsmTuples, \n\tvector<tuple<ZZ_p, ZZ_p>> *hcPairs,\n\tint numBits,\n\tZZ knownBits)\n{\n\tinternal_hcFromRs(rsmTuples,\n\t\thcPairs,\n\t\tnumBits,\n\t\tknownBits,\n\t\ttrue);\n}\n\nvoid hcFromRs(vector<tuple<ZZ_p, ZZ_p, ZZ_p>> *rsmTuples, \n\tvector<tuple<ZZ_p, ZZ_p>> *hcPairs)\n{\n\tZZ zero;\n\tzero = 0;\n\tinternal_hcFromRs(rsmTuples,\n\t\thcPairs,\n\t\t0,\n\t\tzero,\n\t\tfalse);\n}\n\nvoid internal_hcFromRs(vector<tuple<ZZ_p, ZZ_p, ZZ_p>> *rsmTuples, \n\tvector<tuple<ZZ_p, ZZ_p>> *hcPairs,\n\tint numBits,\n\tZZ knownBits,\n\tbool specialH)\n{\n\tfor(vector<tuple<ZZ_p, ZZ_p, ZZ_p>>::iterator it = rsmTuples->begin(); \n\t\tit != rsmTuples->end(); ++it)\n\t{\n\t\tZZ_p h, c, r, s, m, sInverse;\n\n\t\tr = get<0>(*it);\n\t\ts = get<1>(*it);\n\t\tm = get<2>(*it);\n\n\t\tif(s == 0) continue;\n\n\t\tpower(sInverse, s, -1);\n\n\t\tc = r * sInverse;\n\n\t\tif(specialH)\n\t\t{\n\t\t\tZZ modulus, keyBits;\n\n\t\t\t/* Place known key bits in MSBs of modulus */\n\t\t\tkeyBits = knownBits;\n\t\t\tkeyBits >>= (NumBits(keyBits) - numBits); \n\t\t\tkeyBits <<= (NumBits(r.modulus()) - numBits);\t\t\n\n\t\t\th = m * sInverse + c * to_ZZ_p(keyBits);\n\n\t\t} else {\n\t\t\th = m * sInverse;\n\t\t}\n\n\t\thcPairs->push_back(make_tuple(h, c));\n\t}\n}\n\nvoid sortAndDiff(vector<tuple<ZZ_p, ZZ_p>> *hcPairs, \n\tint l,\n\tint t)\n{\t\n\tZZ comp; \n\tZZ_p zero;\n\tint S;\n\n\tS = hcPairs->size();\n\tomp_set_nested(1);\n\tomp_set_num_threads(NUM_CPUs * THREADS_PER_CPU);\n\n\tfor(int i = 0; i < t; i++)\n\t{\n\t\tZZ_p hFirst, cFirst;\n\n\t\t__gnu_parallel::sort(hcPairs->begin(), hcPairs->end(), \n\t\t\tcompareHCtuple);\n\t\t\n\t\tfor(int j = 0; j <= S-t; j++)\n\t\t{\n\t\t\tZZ_p new_h, new_c;\n\n\t\t\tsub(new_h, get<0>((*hcPairs)[j+1]), \n\t\t\t\tget<0>((*hcPairs)[j]));\n\t\t\tsub(new_c, get<1>((*hcPairs)[j+1]), \n\t\t\t\tget<1>((*hcPairs)[j]));\n\n\t\t\thcPairs->at(j) = make_tuple(new_h, new_c);\n\t\t}\n\t}\n\n\t/* Remove (h,c) pairs with c < 2^l */\n\t\n\tcomp = 2;\n\tzero = 0;\n\tpower(comp, comp, l);\n\n\tfor(int i = 0; i < S; i++)\n\t{\n\t\tif(rep(get<1>((*hcPairs)[i])) >= comp)\t\t\n\t\t\thcPairs->at(i) = make_tuple(zero, zero);\n\t}\n\n\t__gnu_parallel::sort(hcPairs->begin(), hcPairs->end(), \n\t\t\tcompareHCtuple);\n\t\n\tif(rep(get<1>((*hcPairs)[S-1])) == rep(zero))\n\t{\n\t\thcPairs->clear();\n\t\treturn;\n\t}\n\n\tfor(int i = 0; i < S; i++)\n\t{\n\t\tif(rep(get<1>((*hcPairs)[i])) != rep(zero)) \n\t\t{\n\t\t\thcPairs->erase(hcPairs->begin(), \n\t\t\t\t(hcPairs->begin()) + i);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvector<tuple<int, double>> maxM(vector<tuple<ZZ_p, ZZ_p>> *hcPairs,\n\tint l)\n{\n\treturn internal_maxM(hcPairs, 1, l);\n}\n\nvector<tuple<int, double>> maxM(vector<tuple<ZZ_p, ZZ_p>> *hcPairs,\n\tint bits,\n\tint l)\n{\n\treturn internal_maxM(hcPairs, bits, l);\n}\n\nvector<tuple<int, double>> internal_maxM(vector<tuple<ZZ_p, ZZ_p>> *hcPairs,\n\tint Z_index_divisor,\n\tint l)\n{\n\tint size;\n\tfftw_complex *in, *out;\n    \tfftw_plan p;\n\tvector<tuple<int, double>> indexValuePairs;\n\n\tsize = pow(2,l)/Z_index_divisor;\n\n\tin = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * size);\n    \tout = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * size);\n\tp = fftw_plan_dft_1d(size, in, out, FFTW_BACKWARD, FFTW_ESTIMATE);\n\n\t/* Compute and store Z values using Euler's Formula */\n\tfor(vector<tuple<ZZ_p, ZZ_p>>::iterator it = hcPairs->begin(); \n\t\tit != hcPairs->end(); ++it)\n\t{\n\t\tint c;\n\t\tdouble z_exp;\n\t\tZZ zz_c;\n\t\t\n\t\tzz_c = rep(get<1>(*it));\n\t\tc = NTLtoOther<int, ZZ>(&zz_c);\n\t\tz_exp = Z_exp(get<0>(*it));\t\n\n\t\tin[c/Z_index_divisor][0] += cos(z_exp); // Re\n\t\tin[c/Z_index_divisor][1] += sin(z_exp); // Im\n\t}\n\n\t/* Do FFT */\n\tfftw_execute(p);\n\n\t/* Get max |Z_m| */\n\taverage = 0;\n\tfor(int i = 0; i < size; i++)\n\t{\n\t\tdouble magnitude;\n\n\t\tmagnitude = abs(complex<double>((out[i])[0], (out[i])[1]));\n\t\taverage += magnitude;\t\t\n\n\t\tif(indexValuePairs.size() < 10)\n\t\t{\n\t\t\tindexValuePairs.push_back(make_tuple(i, magnitude));\n\t\t} else {\n\t\t\tfor(int j = 0; j < 10; j++)\n\t\t\t{\n\t\t\t\tif(magnitude > get<1>(indexValuePairs[j]))\n\t\t\t\t{\n\t\t\t\t\tindexValuePairs.at(j) = \n\t\t\t\t\t\tmake_tuple(i, magnitude);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\taverage /= size;\n\n\t/* Multiply the 1/L back in */\n\taverage /= hcPairs->size();\n\tfor(int i = 0; i < 10; i++)\n\t{\n\t\tint index;\n\t\tdouble B;\n\n\t\tindex = get<0>(indexValuePairs[i]);\n\t\tB = get<1>(indexValuePairs[i]) / hcPairs->size();\n\n\t\tindexValuePairs.at(i) = make_tuple(index, B);\n\t}\n\n\t/* Compute square of standard deviation */\n\tstdDev_accum = 0;\t\n\tfor(int i = 0; i < size; i++)\n\t{\n\t\txdouble term;\n\t\tterm = abs(complex<double>((out[i])[0], (out[i])[1])) \n\t\t\t/ hcPairs->size();\n\t\tterm -= average;\n\t\tpower(term, term, 2);\n\t\tstdDev_accum += term;\n\t}\n\tstdDev_accum /= size;\n\n\tfftw_destroy_plan(p);\n\tfftw_free(in); \n\tfftw_free(out);\n\t\n\treturn indexValuePairs;\n}\n\ndouble avgBias()\n{\n\tdouble ret;\n\tconv(ret, average);\n\treturn ret;\n}\n\ndouble stdDevBias()\n{\n\tdouble ret;\n\tconv(ret, stdDev_accum);\n\tret = sqrt(ret);\n\treturn ret;\n}\n\ndouble Z_exp(ZZ_p h)\n{\n\tZZ n;\n\txdouble h_doub, n_doub, x, pi2;\n\n\tpi2 = 2 * M_PI;\n\n\tn = h.modulus();\n\tn_doub = to_xdouble(n);\n\th_doub = to_xdouble(rep(h));\n\tx = pi2 * h_doub / n_doub;\n\n\treturn NTLtoOther<double, xdouble>(&x);\n}\n", "meta": {"hexsha": "fdbee0ba21a3c08b17b50d3f4b1c938af9a54975", "size": 5780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bleichenbacher.cpp", "max_stars_repo_name": "wcharysz/Bleichenbacher-ECDSA-Nonce-Attack", "max_stars_repo_head_hexsha": "b2a97397edbd51d79b67472e559b2222a5c0526a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-21T22:25:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-21T22:25:06.000Z", "max_issues_repo_path": "bleichenbacher.cpp", "max_issues_repo_name": "wcharysz/Bleichenbacher-ECDSA-Nonce-Attack", "max_issues_repo_head_hexsha": "b2a97397edbd51d79b67472e559b2222a5c0526a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bleichenbacher.cpp", "max_forks_repo_name": "wcharysz/Bleichenbacher-ECDSA-Nonce-Attack", "max_forks_repo_head_hexsha": "b2a97397edbd51d79b67472e559b2222a5c0526a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-17T02:07:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T02:07:29.000Z", "avg_line_length": 18.5256410256, "max_line_length": 76, "alphanum_fraction": 0.6193771626, "num_tokens": 2037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4384273249972114}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_FALLING_FACTORIAL_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_FALLING_FACTORIAL_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n#include <stan/math/prim/scal/fun/boost_policy.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the falling factorial function evaluated\n * at the inputs.\n * Will throw for NaN x and for negative n\n *\n * @tparam T Type of x argument.\n * @param x Argument.\n * @param n Argument\n * @return Result of falling factorial function.\n * @throw std::domain_error if x is NaN\n * @throw std::domain_error if n is negative\n *\n   \\f[\n   \\mbox{falling\\_factorial}(x, n) =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x \\leq 0\\\\\n     (x)_n & \\mbox{if } x > 0 \\textrm{ and } -\\infty \\leq n \\leq \\infty \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } n = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{falling\\_factorial}(x, n)}{\\partial x} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x \\leq 0\\\\\n     \\frac{\\partial\\, (x)_n}{\\partial x} & \\mbox{if } x > 0 \\textrm{ and }\n -\\infty \\leq n \\leq \\infty \\\\[6pt] \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or\n } n = \\textrm{NaN} \\end{cases} \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{falling\\_factorial}(x, n)}{\\partial n} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } x \\leq 0\\\\\n     \\frac{\\partial\\, (x)_n}{\\partial n} & \\mbox{if } x > 0 \\textrm{ and }\n -\\infty \\leq n \\leq \\infty \\\\[6pt] \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or\n } n = \\textrm{NaN} \\end{cases} \\f]\n\n   \\f[\n   (x)_n=\\frac{\\Gamma(x+1)}{\\Gamma(x-n+1)}\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, (x)_n}{\\partial x} = (x)_n\\Psi(x+1)\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, (x)_n}{\\partial n} = -(x)_n\\Psi(n+1)\n   \\f]\n *\n */\ntemplate <typename T>\ninline return_type_t<T> falling_factorial(const T& x, int n) {\n  static const char* function = \"falling_factorial\";\n  check_not_nan(function, \"first argument\", x);\n  check_nonnegative(function, \"second argument\", n);\n  return boost::math::falling_factorial(x, n, boost_policy_t());\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "dc46ef010f52075bd8a6c25344b2c5ff01406529", "size": 2246, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/falling_factorial.hpp", "max_stars_repo_name": "peterwicksstringfield/math", "max_stars_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "stan/math/prim/scal/fun/falling_factorial.hpp", "max_issues_repo_name": "peterwicksstringfield/math", "max_issues_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "stan/math/prim/scal/fun/falling_factorial.hpp", "max_forks_repo_name": "peterwicksstringfield/math", "max_forks_repo_head_hexsha": "5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5526315789, "max_line_length": 80, "alphanum_fraction": 0.6340160285, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4383257133580893}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2007 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Author: David Neckels, Boulder, Colorado, 2007, 2008 \n */ \n\n\n// @sect3{Include files}  \n\n// 首先是一套标准的deal.II包括。这里没有什么特别需要评论的。\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/parameter_handler.h> \n#include <deal.II/base/function_parser.h> \n#include <deal.II/base/utilities.h> \n#include <deal.II/base/conditional_ostream.h> \n\n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_out.h> \n#include <deal.II/grid/grid_refinement.h> \n#include <deal.II/grid/grid_in.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n\n \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/mapping_q1.h> \n#include <deal.II/fe/fe_q.h> \n\n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/solution_transfer.h> \n\n// 然后，正如介绍中提到的，我们使用各种Trilinos软件包作为线性求解器以及自动微分。这些都在以下的包含文件中。\n\n// 由于deal.II提供了基本的Trilinos矩阵、预处理程序和求解器的接口，我们把它们作为deal.II线性代数结构类似地包括在内。\n\n#include <deal.II/lac/trilinos_sparse_matrix.h> \n#include <deal.II/lac/trilinos_precondition.h> \n#include <deal.II/lac/trilinos_solver.h> \n\n// Sacado是Trilinos中的自动微分包，用于寻找全隐式牛顿迭代的雅各布系数。\n\n#include <Sacado.hpp> \n\n// 这又是C++语言。\n\n#include <iostream> \n#include <fstream> \n#include <vector> \n#include <memory> \n#include <array> \n\n// 在本节结束时，将dealii库中的所有内容引入本程序内容将进入的命名空间。\n\nnamespace Step33 \n{ \n  using namespace dealii; \n// @sect3{Euler equation specifics}  \n\n// 这里我们定义了这个特定的守恒定律系统的通量函数，以及几乎所有其他的气体动力学欧拉方程所特有的东西，原因在介绍中讨论过。我们将所有这些归入一个结构，该结构定义了所有与通量有关的东西。这个结构的所有成员都是静态的，也就是说，这个结构没有由实例成员变量指定的实际状态。更好的方法是使用命名空间，而不是一个拥有所有静态成员的结构--但是命名空间不能被模板化，而且我们希望结构中的一些成员变量取决于空间维度，我们以通常的方式用模板参数来引入。\n\n  template <int dim> \n  struct EulerEquations \n  { \n// @sect4{Component description}  \n\n// 首先是几个变量，它们以一种通用的方式描述了我们的解向量的各个组成部分。这包括系统中分量的数量（欧拉方程中每个空间方向的动量都有一个条目，加上能量和密度分量，总共有 <code>dim+2</code> 个分量），以及描述第一个动量分量、密度分量和能量密度分量在解向量中的索引的函数。请注意，所有这些%数都取决于空间维度；以通用的方式定义它们（而不是以隐含的惯例）使我们的代码更加灵活，并使以后的扩展更加容易，例如，在方程中加入更多的分量。\n\n    static const unsigned int n_components             = dim + 2; \n    static const unsigned int first_momentum_component = 0; \n    static const unsigned int density_component        = dim; \n    static const unsigned int energy_component         = dim + 1; \n\n// 在这个程序中一路生成图形输出时，我们需要指定解变量的名称，以及各种成分如何分组为矢量和标量场。我们可以在这里进行描述，但是为了使与欧拉方程有关的事情在这里得到解决，并使程序的其他部分尽可能地通用，我们在以下两个函数中提供了这类信息。\n\n    static std::vector<std::string> component_names() \n    { \n      std::vector<std::string> names(dim, \"momentum\"); \n      names.emplace_back(\"density\"); \n      names.emplace_back(\"energy_density\"); \n\n      return names; \n    } \n\n    static std::vector<DataComponentInterpretation::DataComponentInterpretation> \n    component_interpretation() \n    { \n      std::vector<DataComponentInterpretation::DataComponentInterpretation> \n        data_component_interpretation( \n          dim, DataComponentInterpretation::component_is_part_of_vector); \n      data_component_interpretation.push_back( \n        DataComponentInterpretation::component_is_scalar); \n      data_component_interpretation.push_back( \n        DataComponentInterpretation::component_is_scalar); \n\n      return data_component_interpretation; \n    } \n// @sect4{Transformations between variables}  \n\n// 接下来，我们定义气体常数。我们将在紧接着这个类的声明之后的定义中把它设置为1.4（与整数变量不同，比如上面的变量，静态常量浮点成员变量不能在C++的类声明中被初始化）。这个1.4的值代表了由两个原子组成的分子的气体，比如空气，它几乎完全由 $N_2$ 和 $O_2$ 组成，痕迹很小。\n\n    static const double gas_gamma; \n\n// 在下文中，我们将需要从保守变量的矢量中计算动能和压力。我们可以根据能量密度和动能 $\\frac 12 \\rho |\\mathbf v|^2= \\frac{|\\rho \\mathbf v|^2}{2\\rho}$ 来做这件事（注意，独立变量包含动量分量 $\\rho v_i$ ，而不是速度 $v_i$ ）。\n\n    template <typename InputVector> \n    static typename InputVector::value_type \n    compute_kinetic_energy(const InputVector &W) \n    { \n      typename InputVector::value_type kinetic_energy = 0; \n      for (unsigned int d = 0; d < dim; ++d) \n        kinetic_energy += \n          W[first_momentum_component + d] * W[first_momentum_component + d]; \n      kinetic_energy *= 1. / (2 * W[density_component]); \n\n      return kinetic_energy; \n    } \n\n    template <typename InputVector> \n    static typename InputVector::value_type \n    compute_pressure(const InputVector &W) \n    { \n      return ((gas_gamma - 1.0) * \n              (W[energy_component] - compute_kinetic_energy(W))); \n    } \n// @sect4{EulerEquations::compute_flux_matrix}  \n\n// 我们将通量函数 $F(W)$ 定义为一个大矩阵。 这个矩阵的每一行都代表了该行成分的标量守恒定律。 这个矩阵的确切形式在介绍中给出。请注意，我们知道这个矩阵的大小：它的行数与系统的分量一样多， <code>dim</code> 列数一样多；我们没有为这样的矩阵使用FullMatrix对象（它的行数和列数是可变的，因此每次创建这样的矩阵时必须在堆上分配内存），而是马上使用一个矩形的数字阵列。\n\n// 我们将通量函数的数值类型模板化，这样我们就可以在这里使用自动微分类型。 同样地，我们将用不同的输入矢量数据类型来调用该函数，所以我们也对其进行模板化。\n\n    template <typename InputVector> \n    static void compute_flux_matrix(const InputVector &W, \n                                    ndarray<typename InputVector::value_type, \n                                            EulerEquations<dim>::n_components, \n                                            dim> &     flux) \n    { \n\n// 首先计算出现在通量矩阵中的压力，然后计算矩阵中对应于动量项的前 <code>dim</code> 列。\n\n      const typename InputVector::value_type pressure = compute_pressure(W); \n\n      for (unsigned int d = 0; d < dim; ++d) \n        { \n          for (unsigned int e = 0; e < dim; ++e) \n            flux[first_momentum_component + d][e] = \n              W[first_momentum_component + d] * \n              W[first_momentum_component + e] / W[density_component]; \n\n          flux[first_momentum_component + d][d] += pressure; \n        } \n\n// 然后是密度（即质量守恒）的条款，最后是能量守恒。\n\n      for (unsigned int d = 0; d < dim; ++d) \n        flux[density_component][d] = W[first_momentum_component + d]; \n\n      for (unsigned int d = 0; d < dim; ++d) \n        flux[energy_component][d] = W[first_momentum_component + d] / \n                                    W[density_component] * \n                                    (W[energy_component] + pressure); \n    } \n// @sect4{EulerEquations::compute_normal_flux}  \n\n// 在域的边界和跨挂节点上，我们使用一个数值通量函数来强制执行边界条件。 这个程序是基本的Lax-Friedrich的通量，有一个稳定的参数  $\\alpha$  。它的形式也已经在介绍中给出。\n\n    template <typename InputVector> \n    static void numerical_normal_flux( \n      const Tensor<1, dim> &                                      normal, \n      const InputVector &                                         Wplus, \n      const InputVector &                                         Wminus, \n      const double                                                alpha, \n      std::array<typename InputVector::value_type, n_components> &normal_flux) \n    { \n      ndarray<typename InputVector::value_type, \n              EulerEquations<dim>::n_components, \n              dim> \n        iflux, oflux; \n\n      compute_flux_matrix(Wplus, iflux); \n      compute_flux_matrix(Wminus, oflux); \n\n      for (unsigned int di = 0; di < n_components; ++di) \n        { \n          normal_flux[di] = 0; \n          for (unsigned int d = 0; d < dim; ++d) \n            normal_flux[di] += 0.5 * (iflux[di][d] + oflux[di][d]) * normal[d]; \n\n          normal_flux[di] += 0.5 * alpha * (Wplus[di] - Wminus[di]); \n        } \n    } \n// @sect4{EulerEquations::compute_forcing_vector}  \n\n// 与描述通量函数 $\\mathbf F(\\mathbf w)$ 的方式相同，我们也需要有一种方法来描述右侧的强迫项。正如介绍中提到的，我们在这里只考虑重力，这导致了具体的形式 $\\mathbf G(\\mathbf w) = \\left( g_1\\rho, g_2\\rho, g_3\\rho, 0, \\rho \\mathbf g \\cdot \\mathbf v \\right)^T$ ，这里显示的是三维情况。更具体地说，我们将只考虑三维的 $\\mathbf g=(0,0,-1)^T$ ，或二维的 $\\mathbf g=(0,-1)^T$ 。这自然导致了以下函数。\n\n    template <typename InputVector> \n    static void compute_forcing_vector( \n      const InputVector &                                         W, \n      std::array<typename InputVector::value_type, n_components> &forcing) \n    { \n      const double gravity = -1.0; \n\n      for (unsigned int c = 0; c < n_components; ++c) \n        switch (c) \n          { \n            case first_momentum_component + dim - 1: \n              forcing[c] = gravity * W[density_component]; \n              break; \n            case energy_component: \n              forcing[c] = gravity * W[first_momentum_component + dim - 1]; \n              break; \n            default: \n              forcing[c] = 0; \n          } \n    } \n// @sect4{Dealing with boundary conditions}  \n\n// 我们必须处理的另一件事是边界条件。为此，让我们首先定义一下我们目前知道如何处理的各种边界条件。\n\n    enum BoundaryKind \n    { \n      inflow_boundary, \n      outflow_boundary, \n      no_penetration_boundary, \n      pressure_boundary \n    }; \n\n// 接下来的部分是实际决定在每一种边界上做什么。为此，请记住，从介绍中可以看出，边界条件是通过在给定的不均匀性 $\\mathbf j$ 的边界外侧选择一个值 $\\mathbf w^-$ ，以及可能在内部选择解的值 $\\mathbf w^+$ 来指定的。然后，两者都被传递给数值通量 $\\mathbf H(\\mathbf{w}^+, \\mathbf{w}^-, \\mathbf{n})$ ，以定义边界对双线性形式的贡献。\n\n// 边界条件在某些情况下可以为解矢量的每个分量独立指定。例如，如果分量 $c$ 被标记为流入，那么 $w^-_c = j_c$  。如果是流出，那么 $w^-_c = w^+_c$  。这两种简单的情况在下面的函数中首先得到处理。\n\n// 有一个小插曲，从C++语言的角度来看，这个函数是不愉快的。输出向量  <code>Wminus</code>  当然会被修改，所以它不应该是  <code>const</code>  的参数。然而，在下面的实现中，它却成为了参数，而且为了使代码能够编译，它必须成为参数。原因是我们在 <code>Wminus</code> 类型为 <code>Table@<2,Sacado::Fad::DFad@<double@> @></code> 的地方调用这个函数，这是一个2d表，其指数分别代表正交点和向量分量。我们用 <code>Wminus[q]</code> 作为最后一个参数来调用这个函数；对2d表进行下标会产生一个代表1d向量的临时访问器对象，这正是我们在这里想要的。问题是，根据C++ 1998和2003标准，临时访问器对象不能被绑定到一个函数的非静态引用参数上，就像我们在这里希望的那样（这个问题将在下一个标准中以rvalue引用的形式得到解决）。 我们在这里把输出参数变成常量，是因为<i>accessor</i>对象是常量，而不是它所指向的表：那个表仍然可以被写到。然而，这个黑客是不愉快的，因为它限制了可以作为这个函数的模板参数的数据类型：一个普通的向量是不行的，因为当标记为  <code>const</code>  时，不能被写入。由于目前没有好的解决方案，我们将采用这里显示的务实的，甚至是不漂亮的解决方案。\n\n    template <typename DataVector> \n    static void \n    compute_Wminus(const std::array<BoundaryKind, n_components> &boundary_kind, \n                   const Tensor<1, dim> &                        normal_vector, \n                   const DataVector &                            Wplus, \n                   const Vector<double> &boundary_values, \n                   const DataVector &    Wminus) \n    { \n      for (unsigned int c = 0; c < n_components; c++) \n        switch (boundary_kind[c]) \n          { \n            case inflow_boundary: \n              { \n                Wminus[c] = boundary_values(c); \n                break; \n              } \n\n            case outflow_boundary: \n              { \n                Wminus[c] = Wplus[c]; \n                break; \n              } \n\n// 规定的压力边界条件有点复杂，因为即使压力是规定的，我们在这里真正设定的是能量分量，它将取决于速度和压力。因此，尽管这似乎是一个Dirichlet类型的边界条件，但我们得到了能量对速度和密度的敏感性（除非这些也被规定了）。\n\n            case pressure_boundary: \n              { \n                const typename DataVector::value_type density = \n                  (boundary_kind[density_component] == inflow_boundary ? \n                     boundary_values(density_component) : \n                     Wplus[density_component]); \n\n                typename DataVector::value_type kinetic_energy = 0; \n                for (unsigned int d = 0; d < dim; ++d) \n                  if (boundary_kind[d] == inflow_boundary) \n                    kinetic_energy += boundary_values(d) * boundary_values(d); \n                  else \n                    kinetic_energy += Wplus[d] * Wplus[d]; \n                kinetic_energy *= 1. / 2. / density; \n\n                Wminus[c] = \n                  boundary_values(c) / (gas_gamma - 1.0) + kinetic_energy; \n\n                break; \n              } \n\n            case no_penetration_boundary: \n              { \n\n// 我们规定了速度（我们在这里处理的是一个特定的分量，所以速度的平均值是与表面法线正交的。 这就形成了整个速度分量的敏感度。\n\n                typename DataVector::value_type vdotn = 0; \n                for (unsigned int d = 0; d < dim; d++) \n                  { \n                    vdotn += Wplus[d] * normal_vector[d]; \n                  } \n\n                Wminus[c] = Wplus[c] - 2.0 * vdotn * normal_vector[c]; \n                break; \n              } \n\n            default: \n              Assert(false, ExcNotImplemented()); \n          } \n    } \n// @sect4{EulerEquations::compute_refinement_indicators}  \n\n// 在这个类中，我们也要指定如何细化网格。这个类 <code>ConservationLaw</code> 将使用我们在 <code>EulerEquation</code> 类中提供的所有信息，对于它所求解的特定守恒定律是不可知的：它甚至不关心一个求解向量有多少个分量。因此，它不可能知道合理的细化指标是什么。另一方面，在这里我们知道，或者至少我们可以想出一个合理的选择：我们简单地看一下密度的梯度，然后计算  $\\eta_K=\\log\\left(1+|\\nabla\\rho(x_K)|\\right)$  ，其中  $x_K$  是单元格  $K$  的中心。\n\n// 当然也有很多同样合理的细化指标，但这个指标确实如此，而且很容易计算。\n\n    static void \n    compute_refinement_indicators(const DoFHandler<dim> &dof_handler, \n                                  const Mapping<dim> &   mapping, \n                                  const Vector<double> & solution, \n                                  Vector<double> &       refinement_indicators) \n    { \n      const unsigned int dofs_per_cell = dof_handler.get_fe().n_dofs_per_cell(); \n      std::vector<unsigned int> dofs(dofs_per_cell); \n\n      const QMidpoint<dim> quadrature_formula; \n      const UpdateFlags    update_flags = update_gradients; \n      FEValues<dim>        fe_v(mapping, \n                         dof_handler.get_fe(), \n                         quadrature_formula, \n                         update_flags); \n\n      std::vector<std::vector<Tensor<1, dim>>> dU( \n        1, std::vector<Tensor<1, dim>>(n_components)); \n\n      for (const auto &cell : dof_handler.active_cell_iterators()) \n        { \n          const unsigned int cell_no = cell->active_cell_index(); \n          fe_v.reinit(cell); \n          fe_v.get_function_gradients(solution, dU); \n\n          refinement_indicators(cell_no) = std::log( \n            1 + std::sqrt(dU[0][density_component] * dU[0][density_component])); \n        } \n    } \n\n//  @sect4{EulerEquations::Postprocessor}  \n\n// 最后，我们声明一个实现数据组件后处理的类。这个类解决的问题是，我们使用的欧拉方程的表述中的变量是保守的而不是物理形式的：它们是动量密度  $\\mathbf m=\\rho\\mathbf v$  ，密度  $\\rho$  ，和能量密度  $E$  。我们还想把速度  $\\mathbf v=\\frac{\\mathbf m}{\\rho}$  和压力  $p=(\\gamma-1)(E-\\frac{1}{2} \\rho |\\mathbf v|^2)$  放入我们的输出文件中。\n\n// 此外，我们还想增加生成Schlieren图的可能性。Schlieren图是一种将冲击和其他尖锐界面可视化的方法。Schlieren \"这个词是一个德语单词，可以翻译成 \"条纹\"--不过，用一个例子来解释可能更简单：比如说，当你把高浓度的酒精或透明的盐水倒入水中时，你会看到schlieren；这两种物质的颜色相同，但它们的折射率不同，所以在它们完全混合之前，光线会沿着弯曲的光线穿过混合物，如果你看它，会导致亮度变化。这就是 \"分光\"。类似的效果发生在可压缩流中，因为折射率取决于气体的压力（以及因此的密度）。\n\n// 这个词的起源是指三维体积的二维投影（我们看到的是三维流体的二维图片）。在计算流体力学中，我们可以通过考虑其原因来了解这种效应：密度变化。因此，Schlieren图是通过绘制 $s=|\\nabla \\rho|^2$ 产生的；显然， $s$ 在冲击和其他高度动态的地方很大。如果用户需要（通过在输入文件中指定），我们希望除了上面列出的其他派生量之外，还能生成这些希里伦图。\n\n// 从解决我们问题的数量中计算出派生数量，并将其输出到数据文件中的算法的实现依赖于DataPostprocessor类。它有大量的文档，该类的其他用途也可以在  step-29  中找到。因此，我们避免了大量的评论。\n\n    class Postprocessor : public DataPostprocessor<dim> \n    { \n    public: \n      Postprocessor(const bool do_schlieren_plot); \n\n      virtual void evaluate_vector_field( \n        const DataPostprocessorInputs::Vector<dim> &inputs, \n        std::vector<Vector<double>> &computed_quantities) const override; \n\n      virtual std::vector<std::string> get_names() const override; \n\n      virtual std::vector< \n        DataComponentInterpretation::DataComponentInterpretation> \n      get_data_component_interpretation() const override; \n\n      virtual UpdateFlags get_needed_update_flags() const override; \n\n    private: \n      const bool do_schlieren_plot; \n    }; \n  }; \n\n  template <int dim> \n  const double EulerEquations<dim>::gas_gamma = 1.4; \n\n  template <int dim> \n  EulerEquations<dim>::Postprocessor::Postprocessor( \n    const bool do_schlieren_plot) \n    : do_schlieren_plot(do_schlieren_plot) \n  {} \n\n// 这是唯一值得评论的函数。在生成图形输出时，DataOut和相关的类将在每个单元格上调用这个函数，以获取每个正交点的值、梯度、Hessians和法向量（如果我们在处理面）。请注意，每个正交点的数据本身就是矢量值，即保守变量。我们在这里要做的是计算每个正交点上我们感兴趣的量。注意，为此我们可以忽略Hessians（\"inputs.solution_hessians\"）和法向量（\"inputs.normals\"）。\n\n  template <int dim> \n  void EulerEquations<dim>::Postprocessor::evaluate_vector_field( \n    const DataPostprocessorInputs::Vector<dim> &inputs, \n    std::vector<Vector<double>> &               computed_quantities) const \n  { \n\n// 在函数的开始，让我们确保所有的变量都有正确的大小，这样我们就可以访问各个向量元素，而不必怀疑我们是否可能读或写无效的元素；我们还检查 <code>solution_gradients</code> 向量只包含我们真正需要的数据（系统知道这个，因为我们在下面的 <code>get_needed_update_flags()</code> 函数中这样说）。对于内向量，我们检查至少外向量的第一个元素有正确的内部大小。\n\n    const unsigned int n_quadrature_points = inputs.solution_values.size(); \n\n    if (do_schlieren_plot == true) \n      Assert(inputs.solution_gradients.size() == n_quadrature_points, \n             ExcInternalError()); \n\n    Assert(computed_quantities.size() == n_quadrature_points, \n           ExcInternalError()); \n\n    Assert(inputs.solution_values[0].size() == n_components, \n           ExcInternalError()); \n\n    if (do_schlieren_plot == true) \n      { \n        Assert(computed_quantities[0].size() == dim + 2, ExcInternalError()); \n      } \n    else \n      { \n        Assert(computed_quantities[0].size() == dim + 1, ExcInternalError()); \n      } \n\n// 然后在所有的正交点上循环，在那里做我们的工作。这段代码应该是不言自明的。输出变量的顺序首先是 <code>dim</code> 速度，然后是压力，如果需要的话，还可以是SCHLIEREN图。请注意，我们尝试使用 <code>first_momentum_component</code> 和 <code>density_component</code> 的信息，对输入向量中的变量顺序进行通用处理。\n\n    for (unsigned int q = 0; q < n_quadrature_points; ++q) \n      { \n        const double density = inputs.solution_values[q](density_component); \n\n        for (unsigned int d = 0; d < dim; ++d) \n          computed_quantities[q](d) = \n            inputs.solution_values[q](first_momentum_component + d) / density; \n\n        computed_quantities[q](dim) = \n          compute_pressure(inputs.solution_values[q]); \n\n        if (do_schlieren_plot == true) \n          computed_quantities[q](dim + 1) = \n            inputs.solution_gradients[q][density_component] * \n            inputs.solution_gradients[q][density_component]; \n      } \n  } \n\n  template <int dim> \n  std::vector<std::string> EulerEquations<dim>::Postprocessor::get_names() const \n  { \n    std::vector<std::string> names; \n    for (unsigned int d = 0; d < dim; ++d) \n      names.emplace_back(\"velocity\"); \n    names.emplace_back(\"pressure\"); \n\n    if (do_schlieren_plot == true) \n      names.emplace_back(\"schlieren_plot\"); \n\n    return names; \n  } \n\n  template <int dim> \n  std::vector<DataComponentInterpretation::DataComponentInterpretation> \n  EulerEquations<dim>::Postprocessor::get_data_component_interpretation() const \n  { \n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      interpretation(dim, \n                     DataComponentInterpretation::component_is_part_of_vector); \n\n    interpretation.push_back(DataComponentInterpretation::component_is_scalar); \n\n    if (do_schlieren_plot == true) \n      interpretation.push_back( \n        DataComponentInterpretation::component_is_scalar); \n\n    return interpretation; \n  } \n\n  template <int dim> \n  UpdateFlags \n  EulerEquations<dim>::Postprocessor::get_needed_update_flags() const \n  { \n    if (do_schlieren_plot == true) \n      return update_values | update_gradients; \n    else \n      return update_values; \n  } \n// @sect3{Run time parameter handling}  \n\n// 我们接下来的工作是定义一些包含运行时参数的类（例如求解器的公差、迭代次数、稳定参数等等）。我们可以在主类中完成这项工作，但我们将其与主类分开，以使程序更加模块化和易于阅读。所有与运行时参数有关的东西都在以下命名空间中，而程序逻辑则在主类中。\n\n// 我们将把运行时参数分成几个独立的结构，我们将把这些结构全部放在一个命名空间  <code>Parameters</code>  中。在这些类中，有几个类将参数分组，用于单独的组，比如用于求解器、网格细化或输出。这些类中的每一个都有函数  <code>declare_parameters()</code>  和  <code>parse_parameters()</code>  ，分别在ParameterHandler对象中声明参数子段和条目，并从这样的对象中检索实际参数值。这些类在ParameterHandler的子段中声明它们的所有参数。\n\n// 以下命名空间的最后一个类结合了前面所有的类，从它们派生出来，并负责处理输入文件顶层的一些条目，以及其他一些奇特的条目，这些条目在子段中太短了，不值得本身有一个结构。\n\n// 这里值得指出的是一件事。下面这些类中没有一个构造函数可以初始化各种成员变量。不过这不是问题，因为我们将从输入文件中读取这些类中声明的所有变量（或者间接地：一个ParameterHandler对象将从那里读取，我们将从这个对象中获取数值），它们将以这种方式被初始化。如果输入文件中根本没有指定某个变量，这也不是问题。在这种情况下，ParameterHandler类将简单地采取默认值，这个默认值是在声明下面这些类的 <code>declare_parameters()</code> 函数中的一个条目时指定的。\n\n  namespace Parameters \n  { \n// @sect4{Parameters::Solver}  \n\n// 这些类中的第一个是关于线性内部求解器的参数。它提供的参数表明使用哪种求解器（GMRES作为一般非对称不定式系统的求解器，或稀疏直接求解器），要产生的输出量，以及各种调整阈值不完全LU分解（ILUT）的参数，我们使用它作为GMRES的预处理器。\n\n// 特别是，ILUT需要以下参数。\n\n// - ilut_fill：形成ILU分解时要增加的额外条目数\n\n// - ilut_atol, ilut_rtol: 在形成预处理程序时，对于某些问题，不好的条件（或者只是运气不好）会导致预处理程序的条件很差。 因此，将对角线扰动添加到原始矩阵中，并为这个稍好的矩阵形成预处理程序会有帮助。 ATOL是一个绝对扰动，在形成预处理之前加到对角线上，RTOL是一个比例因子  $rtol \\geq 1$  。\n\n// - ilut_drop: ILUT将放弃任何幅度小于此值的数值。 这是一种管理该预处理程序所使用的内存量的方法。\n\n// 每个参数的含义在  ParameterHandler::declare_entry  调用的第三个参数中也有简要说明  <code>declare_parameters()</code>  。\n\n    struct Solver \n    { \n      enum SolverType \n      { \n        gmres, \n        direct \n      }; \n      SolverType solver; \n\n      enum OutputType \n      { \n        quiet, \n        verbose \n      }; \n      OutputType output; \n\n      double linear_residual; \n      int    max_iterations; \n\n      double ilut_fill; \n      double ilut_atol; \n      double ilut_rtol; \n      double ilut_drop; \n\n      static void declare_parameters(ParameterHandler &prm); \n      void        parse_parameters(ParameterHandler &prm); \n    }; \n\n    void Solver::declare_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"linear solver\"); \n      { \n        prm.declare_entry( \n          \"output\", \n          \"quiet\", \n          Patterns::Selection(\"quiet|verbose\"), \n          \"State whether output from solver runs should be printed. \" \n          \"Choices are <quiet|verbose>.\"); \n        prm.declare_entry(\"method\", \n                          \"gmres\", \n                          Patterns::Selection(\"gmres|direct\"), \n                          \"The kind of solver for the linear system. \" \n                          \"Choices are <gmres|direct>.\"); \n        prm.declare_entry(\"residual\", \n                          \"1e-10\", \n                          Patterns::Double(), \n                          \"Linear solver residual\"); \n        prm.declare_entry(\"max iters\", \n                          \"300\", \n                          Patterns::Integer(), \n                          \"Maximum solver iterations\"); \n        prm.declare_entry(\"ilut fill\", \n                          \"2\", \n                          Patterns::Double(), \n                          \"Ilut preconditioner fill\"); \n        prm.declare_entry(\"ilut absolute tolerance\", \n                          \"1e-9\", \n                          Patterns::Double(), \n                          \"Ilut preconditioner tolerance\"); \n        prm.declare_entry(\"ilut relative tolerance\", \n                          \"1.1\", \n                          Patterns::Double(), \n                          \"Ilut relative tolerance\"); \n        prm.declare_entry(\"ilut drop tolerance\", \n                          \"1e-10\", \n                          Patterns::Double(), \n                          \"Ilut drop tolerance\"); \n      } \n      prm.leave_subsection(); \n    } \n\n    void Solver::parse_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"linear solver\"); \n      { \n        const std::string op = prm.get(\"output\"); \n        if (op == \"verbose\") \n          output = verbose; \n        if (op == \"quiet\") \n          output = quiet; \n\n        const std::string sv = prm.get(\"method\"); \n        if (sv == \"direct\") \n          solver = direct; \n        else if (sv == \"gmres\") \n          solver = gmres; \n\n        linear_residual = prm.get_double(\"residual\"); \n        max_iterations  = prm.get_integer(\"max iters\"); \n        ilut_fill       = prm.get_double(\"ilut fill\"); \n        ilut_atol       = prm.get_double(\"ilut absolute tolerance\"); \n        ilut_rtol       = prm.get_double(\"ilut relative tolerance\"); \n        ilut_drop       = prm.get_double(\"ilut drop tolerance\"); \n      } \n      prm.leave_subsection(); \n    } \n\n//  @sect4{Parameters::Refinement}  \n\n// 同样的，这里有几个参数决定了网格如何被细化（以及是否要被细化）。关于冲击参数的具体作用，请看下面的网格细化函数。\n\n    struct Refinement \n    { \n      bool   do_refine; \n      double shock_val; \n      double shock_levels; \n\n      static void declare_parameters(ParameterHandler &prm); \n      void        parse_parameters(ParameterHandler &prm); \n    }; \n\n    void Refinement::declare_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"refinement\"); \n      { \n        prm.declare_entry(\"refinement\", \n                          \"true\", \n                          Patterns::Bool(), \n                          \"Whether to perform mesh refinement or not\"); \n        prm.declare_entry(\"refinement fraction\", \n                          \"0.1\", \n                          Patterns::Double(), \n                          \"Fraction of high refinement\"); \n        prm.declare_entry(\"unrefinement fraction\", \n                          \"0.1\", \n                          Patterns::Double(), \n                          \"Fraction of low unrefinement\"); \n        prm.declare_entry(\"max elements\", \n                          \"1000000\", \n                          Patterns::Double(), \n                          \"maximum number of elements\"); \n        prm.declare_entry(\"shock value\", \n                          \"4.0\", \n                          Patterns::Double(), \n                          \"value for shock indicator\"); \n        prm.declare_entry(\"shock levels\", \n                          \"3.0\", \n                          Patterns::Double(), \n                          \"number of shock refinement levels\"); \n      } \n      prm.leave_subsection(); \n    } \n\n    void Refinement::parse_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"refinement\"); \n      { \n        do_refine    = prm.get_bool(\"refinement\"); \n        shock_val    = prm.get_double(\"shock value\"); \n        shock_levels = prm.get_double(\"shock levels\"); \n      } \n      prm.leave_subsection(); \n    } \n\n//  @sect4{Parameters::Flux}  \n\n// 接下来是关于通量修改的部分，使其更加稳定。特别是提供了两个选项来稳定Lax-Friedrichs通量：要么选择 $\\mathbf{H}(\\mathbf{a},\\mathbf{b},\\mathbf{n}) = \\frac{1}{2}(\\mathbf{F}(\\mathbf{a})\\cdot \\mathbf{n} + \\mathbf{F}(\\mathbf{b})\\cdot \\mathbf{n} + \\alpha (\\mathbf{a} - \\mathbf{b}))$ ，其中 $\\alpha$ 是在输入文件中指定的一个固定数字，要么 $\\alpha$ 是一个与网格有关的值。在后一种情况下，它被选择为 $\\frac{h}{2\\delta T}$ ，其中 $h$ 是施加流量的面的直径， $\\delta T$ 是当前的时间步长。\n\n    struct Flux \n    { \n      enum StabilizationKind \n      { \n        constant, \n        mesh_dependent \n      }; \n      StabilizationKind stabilization_kind; \n\n      double stabilization_value; \n\n      static void declare_parameters(ParameterHandler &prm); \n      void        parse_parameters(ParameterHandler &prm); \n    }; \n\n    void Flux::declare_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"flux\"); \n      { \n        prm.declare_entry( \n          \"stab\", \n          \"mesh\", \n          Patterns::Selection(\"constant|mesh\"), \n          \"Whether to use a constant stabilization parameter or \" \n          \"a mesh-dependent one\"); \n        prm.declare_entry(\"stab value\", \n                          \"1\", \n                          Patterns::Double(), \n                          \"alpha stabilization\"); \n      } \n      prm.leave_subsection(); \n    } \n\n    void Flux::parse_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"flux\"); \n      { \n        const std::string stab = prm.get(\"stab\"); \n        if (stab == \"constant\") \n          stabilization_kind = constant; \n        else if (stab == \"mesh\") \n          stabilization_kind = mesh_dependent; \n        else \n          AssertThrow(false, ExcNotImplemented()); \n\n        stabilization_value = prm.get_double(\"stab value\"); \n      } \n      prm.leave_subsection(); \n    } \n\n//  @sect4{Parameters::Output}  \n\n// 然后是关于输出参数的部分。我们提供产生Schlieren图（密度的平方梯度，一种可视化冲击前沿的工具），以及图形输出的时间间隔，以防我们不希望每个时间步骤都有输出文件。\n\n    struct Output \n    { \n      bool   schlieren_plot; \n      double output_step; \n\n      static void declare_parameters(ParameterHandler &prm); \n      void        parse_parameters(ParameterHandler &prm); \n    }; \n\n    void Output::declare_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"output\"); \n      { \n        prm.declare_entry(\"schlieren plot\", \n                          \"true\", \n                          Patterns::Bool(), \n                          \"Whether or not to produce schlieren plots\"); \n        prm.declare_entry(\"step\", \n                          \"-1\", \n                          Patterns::Double(), \n                          \"Output once per this period\"); \n      } \n      prm.leave_subsection(); \n    } \n\n    void Output::parse_parameters(ParameterHandler &prm) \n    { \n      prm.enter_subsection(\"output\"); \n      { \n        schlieren_plot = prm.get_bool(\"schlieren plot\"); \n        output_step    = prm.get_double(\"step\"); \n      } \n      prm.leave_subsection(); \n    } \n\n//  @sect4{Parameters::AllParameters}  \n\n// 最后是将这一切结合起来的类。它自己声明了一些参数，主要是参数文件顶层的参数，以及一些太小的部分，以至于不值得有自己的类。它还包含了所有实际上与空间维度有关的东西，比如初始或边界条件。\n\n// 因为这个类是由上面所有的类派生出来的，所以 <code>declare_parameters()</code> and <code>parse_parameters()</code> 函数也会调用基类的相应函数。\n\n// 注意这个类也处理输入文件中指定的初始和边界条件的声明。为此，在这两种情况下，都有像 \"w_0值 \"这样的条目，它代表了 $x,y,z$ 方面的表达式，将初始或边界条件描述为一个公式，随后将由FunctionParser类来解析。类似的表达方式还有 \"w_1\"、\"w_2 \"等，表示欧拉系统的 <code>dim+2</code> 守恒变量。同样，我们允许在输入文件中最多使用 <code>max_n_boundaries</code> 个边界指标，这些边界指标中的每一个都可以与流入、流出或压力边界条件相关联，同质的边界条件要分别为每个组件和每个边界指标指定。\n\n// 用来存储边界指标的数据结构有点复杂。它是一个 <code>max_n_boundaries</code> 元素的数组，表示将被接受的边界指标的范围。对于这个数组中的每个条目，我们在 <code>BoundaryCondition</code> 结构中存储一对数据：首先是一个大小为 <code>n_components</code> 的数组，对于解向量的每个分量，它表明它是流入、流出还是其他类型的边界，其次是一个FunctionParser对象，它一次描述了这个边界ID的解向量的所有分量。\n\n//  <code>BoundaryCondition</code> 结构需要一个构造器，因为我们需要在构造时告诉函数解析器对象它要描述多少个向量分量。因此，这个初始化不能等到我们在后面的 <code>AllParameters::parse_parameters()</code> 中实际设置FunctionParser对象所代表的公式。\n\n// 由于必须在构造时告诉Function对象其向量大小的同样原因，我们必须有一个 <code>AllParameters</code> 类的构造函数，至少要初始化另一个FunctionParser对象，即描述初始条件的对象。\n\n    template <int dim> \n    struct AllParameters : public Solver, \n                           public Refinement, \n                           public Flux, \n                           public Output \n    { \n      static const unsigned int max_n_boundaries = 10; \n\n      struct BoundaryConditions \n      { \n        std::array<typename EulerEquations<dim>::BoundaryKind, \n                   EulerEquations<dim>::n_components> \n          kind; \n\n        FunctionParser<dim> values; \n\n        BoundaryConditions(); \n      }; \n\n      AllParameters(); \n\n      double diffusion_power; \n\n      double time_step, final_time; \n      double theta; \n      bool   is_stationary; \n\n      std::string mesh_filename; \n\n \n      BoundaryConditions  boundary_conditions[max_n_boundaries]; \n\n      static void declare_parameters(ParameterHandler &prm); \n      void        parse_parameters(ParameterHandler &prm); \n    }; \n\n    template <int dim> \n    AllParameters<dim>::BoundaryConditions::BoundaryConditions() \n      : values(EulerEquations<dim>::n_components) \n    { \n      std::fill(kind.begin(), \n                kind.end(), \n                EulerEquations<dim>::no_penetration_boundary); \n    } \n\n    template <int dim> \n    AllParameters<dim>::AllParameters() \n      : diffusion_power(0.) \n      , time_step(1.) \n      , final_time(1.) \n      , theta(.5) \n      , is_stationary(true) \n      , initial_conditions(EulerEquations<dim>::n_components) \n    {} \n\n    template <int dim> \n    void AllParameters<dim>::declare_parameters(ParameterHandler &prm) \n    { \n      prm.declare_entry(\"mesh\", \n                        \"grid.inp\", \n                        Patterns::Anything(), \n                        \"input file name\"); \n\n      prm.declare_entry(\"diffusion power\", \n                        \"2.0\", \n                        Patterns::Double(), \n                        \"power of mesh size for diffusion\"); \n\n      prm.enter_subsection(\"time stepping\"); \n      { \n        prm.declare_entry(\"time step\", \n                          \"0.1\", \n                          Patterns::Double(0), \n                          \"simulation time step\"); \n        prm.declare_entry(\"final time\", \n                          \"10.0\", \n                          Patterns::Double(0), \n                          \"simulation end time\"); \n        prm.declare_entry(\"theta scheme value\", \n                          \"0.5\", \n                          Patterns::Double(0, 1), \n                          \"value for theta that interpolated between explicit \" \n                          \"Euler (theta=0), Crank-Nicolson (theta=0.5), and \" \n                          \"implicit Euler (theta=1).\"); \n      } \n      prm.leave_subsection(); \n\n      for (unsigned int b = 0; b < max_n_boundaries; ++b) \n        { \n          prm.enter_subsection(\"boundary_\" + Utilities::int_to_string(b)); \n          { \n            prm.declare_entry(\"no penetration\", \n                              \"false\", \n                              Patterns::Bool(), \n                              \"whether the named boundary allows gas to \" \n                              \"penetrate or is a rigid wall\"); \n\n            for (unsigned int di = 0; di < EulerEquations<dim>::n_components; \n                 ++di) \n              { \n                prm.declare_entry(\"w_\" + Utilities::int_to_string(di), \n                                  \"outflow\", \n                                  Patterns::Selection( \n                                    \"inflow|outflow|pressure\"), \n                                  \"<inflow|outflow|pressure>\"); \n\n                prm.declare_entry(\"w_\" + Utilities::int_to_string(di) + \n                                    \" value\", \n                                  \"0.0\", \n                                  Patterns::Anything(), \n                                  \"expression in x,y,z\"); \n              } \n          } \n          prm.leave_subsection(); \n        } \n\n      prm.enter_subsection(\"initial condition\"); \n      { \n        for (unsigned int di = 0; di < EulerEquations<dim>::n_components; ++di) \n          prm.declare_entry(\"w_\" + Utilities::int_to_string(di) + \" value\", \n                            \"0.0\", \n                            Patterns::Anything(), \n                            \"expression in x,y,z\"); \n      } \n      prm.leave_subsection(); \n\n      Parameters::Solver::declare_parameters(prm); \n      Parameters::Refinement::declare_parameters(prm); \n      Parameters::Flux::declare_parameters(prm); \n      Parameters::Output::declare_parameters(prm); \n    } \n\n    template <int dim> \n    void AllParameters<dim>::parse_parameters(ParameterHandler &prm) \n    { \n      mesh_filename   = prm.get(\"mesh\"); \n      diffusion_power = prm.get_double(\"diffusion power\"); \n\n      prm.enter_subsection(\"time stepping\"); \n      { \n        time_step = prm.get_double(\"time step\"); \n        if (time_step == 0) \n          { \n            is_stationary = true; \n            time_step     = 1.0; \n            final_time    = 1.0; \n          } \n        else \n          is_stationary = false; \n\n        final_time = prm.get_double(\"final time\"); \n        theta      = prm.get_double(\"theta scheme value\"); \n      } \n      prm.leave_subsection(); \n\n      for (unsigned int boundary_id = 0; boundary_id < max_n_boundaries; \n           ++boundary_id) \n        { \n          prm.enter_subsection(\"boundary_\" + \n                               Utilities::int_to_string(boundary_id)); \n          { \n            std::vector<std::string> expressions( \n              EulerEquations<dim>::n_components, \"0.0\"); \n\n            const bool no_penetration = prm.get_bool(\"no penetration\"); \n\n            for (unsigned int di = 0; di < EulerEquations<dim>::n_components; \n                 ++di) \n              { \n                const std::string boundary_type = \n                  prm.get(\"w_\" + Utilities::int_to_string(di)); \n\n                if ((di < dim) && (no_penetration == true)) \n                  boundary_conditions[boundary_id].kind[di] = \n                    EulerEquations<dim>::no_penetration_boundary; \n                else if (boundary_type == \"inflow\") \n                  boundary_conditions[boundary_id].kind[di] = \n                    EulerEquations<dim>::inflow_boundary; \n                else if (boundary_type == \"pressure\") \n                  boundary_conditions[boundary_id].kind[di] = \n                    EulerEquations<dim>::pressure_boundary; \n                else if (boundary_type == \"outflow\") \n                  boundary_conditions[boundary_id].kind[di] = \n                    EulerEquations<dim>::outflow_boundary; \n                else \n                  AssertThrow(false, ExcNotImplemented()); \n\n                expressions[di] = \n                  prm.get(\"w_\" + Utilities::int_to_string(di) + \" value\"); \n              } \n\n            boundary_conditions[boundary_id].values.initialize( \n              FunctionParser<dim>::default_variable_names(), \n              expressions, \n              std::map<std::string, double>()); \n          } \n          prm.leave_subsection(); \n        } \n\n      prm.enter_subsection(\"initial condition\"); \n      { \n        std::vector<std::string> expressions(EulerEquations<dim>::n_components, \n                                             \"0.0\"); \n        for (unsigned int di = 0; di < EulerEquations<dim>::n_components; di++) \n          expressions[di] = \n            prm.get(\"w_\" + Utilities::int_to_string(di) + \" value\"); \n        initial_conditions.initialize( \n          FunctionParser<dim>::default_variable_names(), \n          expressions, \n          std::map<std::string, double>()); \n      } \n      prm.leave_subsection(); \n\n      Parameters::Solver::parse_parameters(prm); \n      Parameters::Refinement::parse_parameters(prm); \n      Parameters::Flux::parse_parameters(prm); \n      Parameters::Output::parse_parameters(prm); \n    } \n  } // namespace Parameters \n\n//  @sect3{Conservation law class}  \n\n// 这里终于出现了一个类，它实际上是对我们上面定义的所有欧拉方程和参数的具体内容做了一些事情。公共接口与以往基本相同（构造函数现在需要一个文件名来读取参数，这个文件名在命令行中传递）。私有函数接口也与通常的安排非常相似， <code>assemble_system</code> 函数被分成三个部分：一个包含所有单元的主循环，然后分别调用另外两个单元和面的积分。\n\n  template <int dim> \n  class ConservationLaw \n  { \n  public: \n    ConservationLaw(const char *input_filename); \n    void run(); \n\n  private: \n    void setup_system(); \n\n    void assemble_system(); \n    void assemble_cell_term(const FEValues<dim> &                       fe_v, \n                            const std::vector<types::global_dof_index> &dofs); \n    void assemble_face_term( \n      const unsigned int                          face_no, \n      const FEFaceValuesBase<dim> &               fe_v, \n      const FEFaceValuesBase<dim> &               fe_v_neighbor, \n      const std::vector<types::global_dof_index> &dofs, \n      const std::vector<types::global_dof_index> &dofs_neighbor, \n      const bool                                  external_face, \n      const unsigned int                          boundary_id, \n      const double                                face_diameter); \n\n    std::pair<unsigned int, double> solve(Vector<double> &solution); \n\n    void compute_refinement_indicators(Vector<double> &indicator) const; \n    void refine_grid(const Vector<double> &indicator); \n\n    void output_results() const; \n\n// 前面的几个成员变量也相当标准。请注意，我们定义了一个映射对象，在整个程序中组装术语时使用（我们将把它交给每个FEValues和FEFaceValues对象）；我们使用的映射只是标准的 $Q_1$ 映射--换句话说，没有什么花哨的东西--但是在这里声明一个映射并在整个程序中使用它将使以后在有必要时改变它更加简单。事实上，这一点相当重要：众所周知，对于欧拉方程的跨音速模拟，如果边界近似没有足够高的阶数，计算就不会收敛，即使像 $h\\rightarrow 0$ 那样。\n\n    Triangulation<dim>   triangulation; \n    const MappingQ1<dim> mapping; \n\n    const FESystem<dim> fe; \n    DoFHandler<dim>     dof_handler; \n\n    const QGauss<dim>     quadrature; \n    const QGauss<dim - 1> face_quadrature; \n\n// 接下来是一些数据向量，对应于前一个时间步骤的解决方案（ <code>old_solution</code> ），当前解决方案的最佳猜测（ <code>current_solution</code> ；我们说<i>guess</i>是因为计算它的牛顿迭代可能还没有收敛，而 <code>old_solution</code> 是指前一个时间步骤的完全收敛的最终结果），以及下一个时间步骤的解决方案的预测器，通过将当前和之前的解决方案推算到未来一个时间步骤计算。\n\n    Vector<double> old_solution; \n    Vector<double> current_solution; \n    Vector<double> predictor; \n\n    Vector<double> right_hand_side; \n\n// 这一组最后的成员变量（除了最下面的保存所有运行时参数的对象和一个屏幕输出流，它只在要求verbose输出的情况下打印一些东西）处理我们在这个程序中与Trilinos库的接口，该库为我们提供了线性求解器。与在 step-17 和 step-18 中包括PETSc矩阵类似，我们需要做的是创建一个Trilinos稀疏矩阵而不是标准的deal.II类。该系统矩阵在每个牛顿步骤中被用于雅各布系数。由于我们不打算并行运行这个程序（不过用Trilinos数据结构也不难），所以我们不必考虑其他的事情，比如分配自由度。\n\n    TrilinosWrappers::SparseMatrix system_matrix; \n\n    Parameters::AllParameters<dim> parameters; \n    ConditionalOStream             verbose_cout; \n  }; \n// @sect4{ConservationLaw::ConservationLaw}  \n\n// 关于构造函数没有什么可说的。基本上，它读取输入文件并将解析后的值填充到参数对象中。\n\n  template <int dim> \n  ConservationLaw<dim>::ConservationLaw(const char *input_filename) \n    : mapping() \n    , fe(FE_Q<dim>(1), EulerEquations<dim>::n_components) \n    , dof_handler(triangulation) \n    , quadrature(fe.degree + 1) \n    , face_quadrature(fe.degree + 1) \n    , verbose_cout(std::cout, false) \n  { \n    ParameterHandler prm; \n    Parameters::AllParameters<dim>::declare_parameters(prm); \n\n    prm.parse_input(input_filename); \n    parameters.parse_parameters(prm); \n\n    verbose_cout.set_condition(parameters.output == \n                               Parameters::Solver::verbose); \n  } \n\n//  @sect4{ConservationLaw::setup_system}  \n\n// 每次改变网格时都会调用下面这个（简单的）函数。它所做的就是根据我们在之前所有的教程程序中生成的稀疏模式来调整特里诺斯矩阵的大小。\n\n  template <int dim> \n  void ConservationLaw<dim>::setup_system() \n  { \n    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp); \n\n    system_matrix.reinit(dsp); \n  } \n// @sect4{ConservationLaw::assemble_system}  \n\n// 这个和下面两个函数是这个程序的核心。它们将牛顿方法应用于非线性守恒方程组所产生的线性系统组合起来。\n\n// 第一个函数将所有的装配部件放在一个例行程序中，为每个单元格/面分配正确的部件。 对这些对象的装配的实际实现是在以下函数中完成的。\n\n// 在函数的顶部，我们做了常规的内务处理：分配FEValues、FEFaceValues和FESubfaceValues对象，这些对象对单元、面和子面（在不同细化级别的相邻单元的情况下）进行积分。请注意，我们并不需要所有这些对象的所有信息（如值、梯度或正交点的实际位置），所以我们只让FEValues类通过指定最小的UpdateFlags集来获得实际需要的信息。例如，当使用邻接单元的FEFaceValues对象时，我们只需要形状值。给定一个特定的面，正交点和 <code>JxW</code> 值与当前单元格相同，法向量已知为当前单元格的法向量的负值。\n\n  template <int dim> \n  void ConservationLaw<dim>::assemble_system() \n  { \n    const unsigned int dofs_per_cell = dof_handler.get_fe().n_dofs_per_cell(); \n\n    std::vector<types::global_dof_index> dof_indices(dofs_per_cell); \n    std::vector<types::global_dof_index> dof_indices_neighbor(dofs_per_cell); \n\n    const UpdateFlags update_flags = update_values | update_gradients | \n                                     update_quadrature_points | \n                                     update_JxW_values, \n                      face_update_flags = \n                        update_values | update_quadrature_points | \n                        update_JxW_values | update_normal_vectors, \n                      neighbor_face_update_flags = update_values; \n\n    FEValues<dim>        fe_v(mapping, fe, quadrature, update_flags); \n    FEFaceValues<dim>    fe_v_face(mapping, \n                                fe, \n                                face_quadrature, \n                                face_update_flags); \n    FESubfaceValues<dim> fe_v_subface(mapping, \n                                      fe, \n                                      face_quadrature, \n                                      face_update_flags); \n    FEFaceValues<dim>    fe_v_face_neighbor(mapping, \n                                         fe, \n                                         face_quadrature, \n                                         neighbor_face_update_flags); \n    FESubfaceValues<dim> fe_v_subface_neighbor(mapping, \n                                               fe, \n                                               face_quadrature, \n                                               neighbor_face_update_flags); \n\n// 然后循环所有单元，初始化当前单元的FEValues对象，并调用在此单元上组装问题的函数。\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        fe_v.reinit(cell); \n        cell->get_dof_indices(dof_indices); \n\n        assemble_cell_term(fe_v, dof_indices); \n\n// 然后在这个单元的所有面上循环。 如果一个面是外部边界的一部分，那么就在那里集合边界条件（ <code>assemble_face_terms</code> 的第五个参数表示我们是在外部面还是内部面工作；如果是外部面，表示邻居自由度指数的第四个参数被忽略，所以我们传递一个空向量）。\n\n        for (const auto face_no : cell->face_indices()) \n          if (cell->at_boundary(face_no)) \n            { \n              fe_v_face.reinit(cell, face_no); \n              assemble_face_term(face_no, \n                                 fe_v_face, \n                                 fe_v_face, \n                                 dof_indices, \n                                 std::vector<types::global_dof_index>(), \n                                 true, \n                                 cell->face(face_no)->boundary_id(), \n                                 cell->face(face_no)->diameter()); \n            } \n\n// 另一种情况是，我们正在处理一个内部面。我们需要区分两种情况：这是在同一细化水平的两个单元之间的正常面，和在不同细化水平的两个单元之间的面。\n\n// 在第一种情况下，我们不需要做什么：我们使用的是连续有限元，在这种情况下，面条款不会出现在双线性表格中。第二种情况通常也不会导致面条款，如果我们强烈地执行悬挂节点约束的话（就像到目前为止，只要我们使用连续有限元的所有教程程序一样--这种执行是由AffineConstraints类和 DoFTools::make_hanging_node_constraints). 一起完成的）。 然而，在当前程序中，我们选择在不同细化水平的单元之间的面弱地执行连续性，原因有二。(i)因为我们可以，更重要的是(ii)因为我们必须通过AffineConstraints类的操作，将我们用来计算牛顿矩阵元素的自动微分穿起来。这是有可能的，但不是微不足道的，所以我们选择了这种替代方法。\n\n// 需要决定的是我们坐在两个不同细化水平的单元之间的接口的哪一边。\n\n// 让我们先来看看邻居更精细的情况。然后，我们必须在当前单元格的面的子代上循环，并在每个子代上进行整合。我们在代码中加入了几个断言，以确保我们试图找出邻居的哪个子面与当前单元格的某个子面重合的推理是正确的--有点防御性的编程永远不会有坏处。\n\n// 然后我们调用对面进行整合的函数；由于这是一个内部面，第五个参数是假的，第六个参数被忽略了，所以我们再次传递一个无效的值。\n\n          else \n            { \n              if (cell->neighbor(face_no)->has_children()) \n                { \n                  const unsigned int neighbor2 = \n                    cell->neighbor_of_neighbor(face_no); \n\n                  for (unsigned int subface_no = 0; \n                       subface_no < cell->face(face_no)->n_children(); \n                       ++subface_no) \n                    { \n                      const typename DoFHandler<dim>::active_cell_iterator \n                        neighbor_child = \n                          cell->neighbor_child_on_subface(face_no, subface_no); \n\n                      Assert(neighbor_child->face(neighbor2) == \n                               cell->face(face_no)->child(subface_no), \n                             ExcInternalError()); \n                      Assert(neighbor_child->is_active(), ExcInternalError()); \n\n                      fe_v_subface.reinit(cell, face_no, subface_no); \n                      fe_v_face_neighbor.reinit(neighbor_child, neighbor2); \n\n                      neighbor_child->get_dof_indices(dof_indices_neighbor); \n\n                      assemble_face_term( \n                        face_no, \n                        fe_v_subface, \n                        fe_v_face_neighbor, \n                        dof_indices, \n                        dof_indices_neighbor, \n                        false, \n                        numbers::invalid_unsigned_int, \n                        neighbor_child->face(neighbor2)->diameter()); \n                    } \n                } \n\n// 我们必须关注的另一种可能性是邻居是否比当前单元更粗（特别是，由于每个面只有一个悬挂节点的通常限制，邻居必须正好比当前单元更粗一级，这是我们用断言检查的）。同样，我们在这个接口上进行整合。\n\n              else if (cell->neighbor(face_no)->level() != cell->level()) \n                { \n                  const typename DoFHandler<dim>::cell_iterator neighbor = \n                    cell->neighbor(face_no); \n                  Assert(neighbor->level() == cell->level() - 1, \n                         ExcInternalError()); \n\n                  neighbor->get_dof_indices(dof_indices_neighbor); \n\n                  const std::pair<unsigned int, unsigned int> faceno_subfaceno = \n                    cell->neighbor_of_coarser_neighbor(face_no); \n                  const unsigned int neighbor_face_no = faceno_subfaceno.first, \n                                     neighbor_subface_no = \n                                       faceno_subfaceno.second; \n\n                  Assert(neighbor->neighbor_child_on_subface( \n                           neighbor_face_no, neighbor_subface_no) == cell, \n                         ExcInternalError()); \n\n                  fe_v_face.reinit(cell, face_no); \n                  fe_v_subface_neighbor.reinit(neighbor, \n                                               neighbor_face_no, \n                                               neighbor_subface_no); \n\n                  assemble_face_term(face_no, \n                                     fe_v_face, \n                                     fe_v_subface_neighbor, \n                                     dof_indices, \n                                     dof_indices_neighbor, \n                                     false, \n                                     numbers::invalid_unsigned_int, \n                                     cell->face(face_no)->diameter()); \n                } \n            } \n      } \n  } \n// @sect4{ConservationLaw::assemble_cell_term}  \n\n// 这个函数通过计算残差的单元部分来组装单元项，将其负数加到右手边的向量上，并将其相对于局部变量的导数加到雅各布系数（即牛顿矩阵）上。回顾一下，单元格对残差的贡献为 $R_i = \\left(\\frac{\\mathbf{w}^{k}_{n+1} - \\mathbf{w}_n}{\\delta t} , \\mathbf{z}_i \\right)_K $ 。\n// $ + \\theta \\mathbf{B}(\\mathbf{w}^{k}_{n+1})(\\mathbf{z}_i)_K $  \n// $ + (1-\\theta) \\mathbf{B}(\\mathbf{w}_{n}) (\\mathbf{z}_i)_K $ ，其中 $\\mathbf{B}(\\mathbf{w})(\\mathbf{z}_i)_K = - \\left(\\mathbf{F}(\\mathbf{w}),\\nabla\\mathbf{z}_i\\right)_K $  。\n// $ + h^{\\eta}(\\nabla \\mathbf{w} , \\nabla \\mathbf{z}_i)_K $  \n// $ - (\\mathbf{G}(\\mathbf {w}), \\mathbf{z}_i)_K $ 为 $\\mathbf{w} = \\mathbf{w}^k_{n+1}$ 和 $\\mathbf{w} = \\mathbf{w}_{n}$  ， $\\mathbf{z}_i$ 为 $i$ 的第1个向量值测试函数。  此外，标量积 $\\left(\\mathbf{F}(\\mathbf{w}), \\nabla\\mathbf{z}_i\\right)_K$ 可以理解为 $\\int_K \\sum_{c=1}^{\\text{n\\_components}}  \\sum_{d=1}^{\\text{dim}} \\mathbf{F}(\\mathbf{w})_{cd} \\frac{\\partial z^c_i}{x_d}$ ，其中 $z^c_i$ 是 $i$ 第1个测试函数的 $c$ 分量。\n\n// 在这个函数的顶部，我们做了一些常规的内务工作，即分配一些我们以后需要的局部变量。特别是，我们将分配一些变量来保存 $k$ 次牛顿迭代后的当前解 $W_{n+1}^k$ （变量 <code>W</code> ）和上一时间步长的解 $W_{n}$ （变量 <code>W_old</code> ）的值。\n\n// 除此以外，我们还需要当前变量的梯度。 我们必须计算这些是有点遗憾的，我们几乎不需要。 一个简单的守恒定律的好处是，通量一般不涉及任何梯度。 然而，我们确实需要这些梯度，用于扩散稳定化。\n\n// 我们存储这些变量的实际格式需要一些解释。首先，我们需要解向量的 <code>EulerEquations::n_components</code> 分量在每个正交点的数值。这就构成了一个二维表，我们使用deal.II的表类（这比 <code>std::vector@<std::vector@<T@> @></code> 更有效，因为它只需要分配一次内存，而不是为外向量的每个元素分配一次）。同样地，梯度是一个三维表，Table类也支持。\n\n// 其次，我们想使用自动微分。为此，我们使用 Sacado::Fad::DFad 模板来计算所有我们想计算导数的变量。这包括当前解和正交点的梯度（是自由度的线性组合），以及由它们计算出来的所有东西，如残差，但不包括前一个时间步长的解。这些变量都可以在函数的第一部分找到，同时还有一个变量，我们将用它来存储残差的一个分量的导数。\n\n  template <int dim> \n  void ConservationLaw<dim>::assemble_cell_term( \n    const FEValues<dim> &                       fe_v, \n    const std::vector<types::global_dof_index> &dof_indices) \n  { \n    const unsigned int dofs_per_cell = fe_v.dofs_per_cell; \n    const unsigned int n_q_points    = fe_v.n_quadrature_points; \n\n    Table<2, Sacado::Fad::DFad<double>> W(n_q_points, \n                                          EulerEquations<dim>::n_components); \n\n    Table<2, double> W_old(n_q_points, EulerEquations<dim>::n_components); \n\n    Table<3, Sacado::Fad::DFad<double>> grad_W( \n      n_q_points, EulerEquations<dim>::n_components, dim); \n\n    Table<3, double> grad_W_old(n_q_points, \n                                EulerEquations<dim>::n_components, \n                                dim); \n\n    std::vector<double> residual_derivatives(dofs_per_cell); \n\n// 接下来，我们必须定义自变量，我们将尝试通过解决一个牛顿步骤来确定自变量。这些自变量是局部自由度的值，我们在这里提取。\n\n    std::vector<Sacado::Fad::DFad<double>> independent_local_dof_values( \n      dofs_per_cell); \n    for (unsigned int i = 0; i < dofs_per_cell; ++i) \n      independent_local_dof_values[i] = current_solution(dof_indices[i]); \n\n// 下一步包含了所有的魔法：我们宣布自分变量的一个子集为独立自由度，而所有其他的变量仍然是依存函数。这些正是刚刚提取的局部自由度。所有引用它们的计算（无论是直接还是间接）都将积累与这些变量有关的敏感度。\n\n// 为了将这些变量标记为独立变量，下面的方法可以起到作用，将 <code>independent_local_dof_values[i]</code> 标记为总共 <code>dofs_per_cell</code> 中的 $i$ 个独立变量。\n\n    for (unsigned int i = 0; i < dofs_per_cell; ++i) \n      independent_local_dof_values[i].diff(i, dofs_per_cell); \n\n// 在所有这些声明之后，让我们实际计算一些东西。首先， <code>W</code>, <code>W_old</code>, <code>grad_W</code> 和 <code>grad_W_old</code> 的值，我们可以通过使用公式 $W(x_q)=\\sum_i \\mathbf W_i \\Phi_i(x_q)$ 从局部DoF值计算出来，其中 $\\mathbf W_i$ 是解向量（局部部分）的第 $i$ 项，而 $\\Phi_i(x_q)$ 是在正交点 $x_q$ 评估的第 $i$ 个矢量值的形状函数的值。梯度可以用类似的方法来计算。\n\n// 理想情况下，我们可以通过调用类似 FEValues::get_function_values 和 FEValues::get_function_gradients, 的东西来计算这些信息，但是由于（i）我们必须为此扩展FEValues类，以及（ii）我们不想让整个 <code>old_solution</code> 矢量fad类型，只有局部单元变量，我们明确编码上面的循环。在这之前，我们增加一个循环，将所有的fad变量初始化为零。\n\n    for (unsigned int q = 0; q < n_q_points; ++q) \n      for (unsigned int c = 0; c < EulerEquations<dim>::n_components; ++c) \n        { \n          W[q][c]     = 0; \n          W_old[q][c] = 0; \n          for (unsigned int d = 0; d < dim; ++d) \n            { \n              grad_W[q][c][d]     = 0; \n              grad_W_old[q][c][d] = 0; \n            } \n        } \n\n    for (unsigned int q = 0; q < n_q_points; ++q) \n      for (unsigned int i = 0; i < dofs_per_cell; ++i) \n        { \n          const unsigned int c = \n            fe_v.get_fe().system_to_component_index(i).first; \n\n          W[q][c] += independent_local_dof_values[i] * \n                     fe_v.shape_value_component(i, q, c); \n          W_old[q][c] += \n            old_solution(dof_indices[i]) * fe_v.shape_value_component(i, q, c); \n\n          for (unsigned int d = 0; d < dim; d++) \n            { \n              grad_W[q][c][d] += independent_local_dof_values[i] * \n                                 fe_v.shape_grad_component(i, q, c)[d]; \n              grad_W_old[q][c][d] += old_solution(dof_indices[i]) * \n                                     fe_v.shape_grad_component(i, q, c)[d]; \n            } \n        } \n\n// 接下来，为了计算单元贡献，我们需要在所有正交点评估 $\\mathbf{F}({\\mathbf w}^k_{n+1})$  ,  $\\mathbf{G}({\\mathbf w}^k_{n+1})$  和  $\\mathbf{F}({\\mathbf w}_n)$  ,  $\\mathbf{G}({\\mathbf w}_n)$  。为了存储这些，我们还需要分配一点内存。请注意，我们以自分变量的方式计算通量矩阵和右手边，这样以后就可以很容易地从中计算出雅各布贡献。\n\n    std::vector<ndarray<Sacado::Fad::DFad<double>, \n                        EulerEquations<dim>::n_components, \n                        dim>> \n      flux(n_q_points); \n\n    std::vector<ndarray<double, EulerEquations<dim>::n_components, dim>> \n      flux_old(n_q_points); \n\n \n      std::array<Sacado::Fad::DFad<double>, EulerEquations<dim>::n_components>> \n      forcing(n_q_points); \n\n    std::vector<std::array<double, EulerEquations<dim>::n_components>> \n      forcing_old(n_q_points); \n\n    for (unsigned int q = 0; q < n_q_points; ++q) \n      { \n        EulerEquations<dim>::compute_flux_matrix(W_old[q], flux_old[q]); \n        EulerEquations<dim>::compute_forcing_vector(W_old[q], forcing_old[q]); \n        EulerEquations<dim>::compute_flux_matrix(W[q], flux[q]); \n        EulerEquations<dim>::compute_forcing_vector(W[q], forcing[q]); \n      } \n\n// 我们现在已经有了所有的部件，所以进行组装。 我们有一个通过系统组件的外循环，和一个通过正交点的内循环，在那里我们积累了对 $i$ 的残差 $R_i$ 的贡献。这个残差的一般公式在引言和本函数的顶部给出。然而，考虑到  $i$  第三个（矢量值）测试函数  $\\mathbf{z}_i$  实际上只有一个非零分量（关于这个主题的更多信息可以在  @ref  矢量值模块中找到），我们可以把它简化一下。它将由下面的变量 <code>component_i</code> 表示。有了这个，残差项可以重新写成\n// @f{eqnarray*}\n//  R_i &=&\n//  \\left(\\frac{(\\mathbf{w}_{n+1} -\n//  \\mathbf{w}_n)_{\\text{component\\_i}}}{\\delta\n//  t},(\\mathbf{z}_i)_{\\text{component\\_i}}\\right)_K\n//  \\\\ &-& \\sum_{d=1}^{\\text{dim}} \\left(  \\theta \\mathbf{F}\n//  ({\\mathbf{w}^k_{n+1}})_{\\text{component\\_i},d} + (1-\\theta)\n//  \\mathbf{F} ({\\mathbf{w}_{n}})_{\\text{component\\_i},d}  ,\n//  \\frac{\\partial(\\mathbf{z}_i)_{\\text{component\\_i}}} {\\partial\n//  x_d}\\right)_K\n//  \\\\ &+& \\sum_{d=1}^{\\text{dim}} h^{\\eta} \\left( \\theta \\frac{\\partial\n//  (\\mathbf{w}^k_{n+1})_{\\text{component\\_i}}}{\\partial x_d} + (1-\\theta)\n//  \\frac{\\partial (\\mathbf{w}_n)_{\\text{component\\_i}}}{\\partial x_d} ,\n//  \\frac{\\partial (\\mathbf{z}_i)_{\\text{component\\_i}}}{\\partial x_d}\n//  \\right)_K\n//  \\\\ &-& \\left( \\theta\\mathbf{G}({\\mathbf{w}^k_n+1} )_{\\text{component\\_i}}\n//  + (1-\\theta)\\mathbf{G}({\\mathbf{w}_n})_{\\text{component\\_i}} ,\n//  (\\mathbf{z}_i)_{\\text{component\\_i}} \\right)_K ,\n//  @f}\n//  ，其中积分可以理解为通过对正交点求和来评估。\n\n// 我们最初对残差的所有贡献进行正向求和，这样我们就不需要对雅各布项进行负数。 然后，当我们对 <code>right_hand_side</code> 矢量进行求和时，我们就否定了这个残差。\n\n    for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i) \n      { \n        Sacado::Fad::DFad<double> R_i = 0; \n\n        const unsigned int component_i = \n          fe_v.get_fe().system_to_component_index(i).first; \n\n// 每一行（i）的残差将被累积到这个fad变量中。 在这一行的装配结束时，我们将查询这个变量的敏感度，并将其加入到雅各布系数中。\n\n        for (unsigned int point = 0; point < fe_v.n_quadrature_points; ++point) \n          { \n            if (parameters.is_stationary == false) \n              R_i += 1.0 / parameters.time_step * \n                     (W[point][component_i] - W_old[point][component_i]) * \n                     fe_v.shape_value_component(i, point, component_i) * \n                     fe_v.JxW(point); \n\n            for (unsigned int d = 0; d < dim; d++) \n              R_i -= \n                (parameters.theta * flux[point][component_i][d] + \n                 (1.0 - parameters.theta) * flux_old[point][component_i][d]) * \n                fe_v.shape_grad_component(i, point, component_i)[d] * \n                fe_v.JxW(point); \n\n            for (unsigned int d = 0; d < dim; d++) \n              R_i += \n                1.0 * \n                std::pow(fe_v.get_cell()->diameter(), \n                         parameters.diffusion_power) * \n                (parameters.theta * grad_W[point][component_i][d] + \n                 (1.0 - parameters.theta) * grad_W_old[point][component_i][d]) * \n                fe_v.shape_grad_component(i, point, component_i)[d] * \n                fe_v.JxW(point); \n\n            R_i -= \n              (parameters.theta * forcing[point][component_i] + \n               (1.0 - parameters.theta) * forcing_old[point][component_i]) * \n              fe_v.shape_value_component(i, point, component_i) * \n              fe_v.JxW(point); \n          } \n\n// 在循环结束时，我们必须将敏感度加到矩阵上，并从右手边减去残差。Trilinos FAD数据类型让我们可以使用  <code>R_i.fastAccessDx(k)</code>  访问导数，所以我们将数据存储在一个临时数组中。然后，这些关于整行本地道夫的信息被一次性添加到特里诺斯矩阵中（支持我们选择的数据类型）。\n\n        for (unsigned int k = 0; k < dofs_per_cell; ++k) \n          residual_derivatives[k] = R_i.fastAccessDx(k); \n        system_matrix.add(dof_indices[i], dof_indices, residual_derivatives); \n        right_hand_side(dof_indices[i]) -= R_i.val(); \n      } \n  } \n// @sect4{ConservationLaw::assemble_face_term}  \n\n// 在这里，我们做的事情与前面的函数基本相同。在顶部，我们引入自变量。因为如果我们在两个单元格之间的内部面上工作，也会使用当前的函数，所以自变量不仅是当前单元格上的自由度，而且在内部面上的情况下，也是邻近单元格上的自由度。\n\n  template <int dim> \n  void ConservationLaw<dim>::assemble_face_term( \n    const unsigned int                          face_no, \n    const FEFaceValuesBase<dim> &               fe_v, \n    const FEFaceValuesBase<dim> &               fe_v_neighbor, \n    const std::vector<types::global_dof_index> &dof_indices, \n    const std::vector<types::global_dof_index> &dof_indices_neighbor, \n    const bool                                  external_face, \n    const unsigned int                          boundary_id, \n    const double                                face_diameter) \n  { \n    const unsigned int n_q_points    = fe_v.n_quadrature_points; \n    const unsigned int dofs_per_cell = fe_v.dofs_per_cell; \n\n    std::vector<Sacado::Fad::DFad<double>> independent_local_dof_values( \n      dofs_per_cell), \n      independent_neighbor_dof_values(external_face == false ? dofs_per_cell : \n                                                               0); \n\n    const unsigned int n_independent_variables = \n      (external_face == false ? 2 * dofs_per_cell : dofs_per_cell); \n\n    for (unsigned int i = 0; i < dofs_per_cell; i++) \n      { \n        independent_local_dof_values[i] = current_solution(dof_indices[i]); \n        independent_local_dof_values[i].diff(i, n_independent_variables); \n      } \n\n    if (external_face == false) \n      for (unsigned int i = 0; i < dofs_per_cell; i++) \n        { \n          independent_neighbor_dof_values[i] = \n            current_solution(dof_indices_neighbor[i]); \n          independent_neighbor_dof_values[i].diff(i + dofs_per_cell, \n                                                  n_independent_variables); \n        } \n\n// 接下来，我们需要定义保守变量  ${\\mathbf W}$  在面的这一侧（  $ {\\mathbf W}^+$  ）和另一侧（  ${\\mathbf W}^-$  ）的值，对于  ${\\mathbf W} = {\\mathbf W}^k_{n+1}$  和  ${\\mathbf W} = {\\mathbf W}_n$  。\"这一边 \"的值可以用与前一个函数完全相同的方式计算，但注意 <code>fe_v</code> 变量现在是FEFaceValues或FESubfaceValues的类型。\n\n    Table<2, Sacado::Fad::DFad<double>> Wplus( \n      n_q_points, EulerEquations<dim>::n_components), \n      Wminus(n_q_points, EulerEquations<dim>::n_components); \n    Table<2, double> Wplus_old(n_q_points, EulerEquations<dim>::n_components), \n      Wminus_old(n_q_points, EulerEquations<dim>::n_components); \n\n    for (unsigned int q = 0; q < n_q_points; ++q) \n      for (unsigned int i = 0; i < dofs_per_cell; ++i) \n        { \n          const unsigned int component_i = \n            fe_v.get_fe().system_to_component_index(i).first; \n          Wplus[q][component_i] += \n            independent_local_dof_values[i] * \n            fe_v.shape_value_component(i, q, component_i); \n          Wplus_old[q][component_i] += \n            old_solution(dof_indices[i]) * \n            fe_v.shape_value_component(i, q, component_i); \n        } \n\n// 计算 \"对立面 \"就比较复杂了。如果这是一个内部面，我们可以像上面那样，简单地使用邻居的独立变量来计算它。\n\n    if (external_face == false) \n      { \n        for (unsigned int q = 0; q < n_q_points; ++q) \n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            { \n              const unsigned int component_i = \n                fe_v_neighbor.get_fe().system_to_component_index(i).first; \n              Wminus[q][component_i] += \n                independent_neighbor_dof_values[i] * \n                fe_v_neighbor.shape_value_component(i, q, component_i); \n              Wminus_old[q][component_i] += \n                old_solution(dof_indices_neighbor[i]) * \n                fe_v_neighbor.shape_value_component(i, q, component_i); \n            } \n      } \n\n// 另一方面，如果这是一个外部边界面，那么 $\\mathbf{W}^-$ 的值将是 $\\mathbf{W}^+$ 的函数，或者它们将是规定的，这取决于这里施加的边界条件的种类。\n\n// 为了开始评估，让我们确保为这个边界指定的边界ID是我们在参数对象中实际有数据的一个。接下来，我们对不均匀性的函数对象进行评估。 这有点棘手：一个给定的边界可能同时有规定的和隐含的值。 如果一个特定的成分没有被规定，那么这些值就会被评估为零，并在下面被忽略。\n\n// 剩下的部分由一个实际了解欧拉方程边界条件具体内容的函数完成。请注意，由于我们在这里使用的是fad变量，敏感度将被适当地更新，否则这个过程将是非常复杂的。\n\n    else \n      { \n        Assert(boundary_id < Parameters::AllParameters<dim>::max_n_boundaries, \n               ExcIndexRange(boundary_id, \n                             0, \n                             Parameters::AllParameters<dim>::max_n_boundaries)); \n\n        std::vector<Vector<double>> boundary_values( \n          n_q_points, Vector<double>(EulerEquations<dim>::n_components)); \n        parameters.boundary_conditions[boundary_id].values.vector_value_list( \n          fe_v.get_quadrature_points(), boundary_values); \n\n        for (unsigned int q = 0; q < n_q_points; q++) \n          { \n            EulerEquations<dim>::compute_Wminus( \n              parameters.boundary_conditions[boundary_id].kind, \n              fe_v.normal_vector(q), \n              Wplus[q], \n              boundary_values[q], \n              Wminus[q]); \n\n// 这里我们假设边界类型、边界法向量和边界数据值在时间推进中保持不变。\n\n            EulerEquations<dim>::compute_Wminus( \n              parameters.boundary_conditions[boundary_id].kind, \n              fe_v.normal_vector(q), \n              Wplus_old[q], \n              boundary_values[q], \n              Wminus_old[q]); \n          } \n      } \n\n// 现在我们有了 $\\mathbf w^+$ 和 $\\mathbf w^-$ ，我们可以去计算每个正交点的数值通量函数 $\\mathbf H(\\mathbf w^+,\\mathbf w^-, \\mathbf n)$ 。在调用这个函数之前，我们还需要确定Lax-Friedrich的稳定性参数。\n\n    std::vector< \n      std::array<Sacado::Fad::DFad<double>, EulerEquations<dim>::n_components>> \n      normal_fluxes(n_q_points); \n    std::vector<std::array<double, EulerEquations<dim>::n_components>> \n      normal_fluxes_old(n_q_points); \n\n    double alpha; \n\n \n      { \n        case Parameters::Flux::constant: \n          alpha = parameters.stabilization_value; \n          break; \n        case Parameters::Flux::mesh_dependent: \n          alpha = face_diameter / (2.0 * parameters.time_step); \n          break; \n        default: \n          Assert(false, ExcNotImplemented()); \n          alpha = 1; \n      } \n\n    for (unsigned int q = 0; q < n_q_points; ++q) \n      { \n        EulerEquations<dim>::numerical_normal_flux( \n          fe_v.normal_vector(q), Wplus[q], Wminus[q], alpha, normal_fluxes[q]); \n        EulerEquations<dim>::numerical_normal_flux(fe_v.normal_vector(q), \n                                                   Wplus_old[q], \n                                                   Wminus_old[q], \n                                                   alpha, \n                                                   normal_fluxes_old[q]); \n      } \n\n// 现在以与前面函数中的单元格贡献完全相同的方式组装面项。唯一不同的是，如果这是一个内部面，我们还必须考虑到剩余贡献对相邻单元自由度的敏感性。\n\n    std::vector<double> residual_derivatives(dofs_per_cell); \n    for (unsigned int i = 0; i < fe_v.dofs_per_cell; ++i) \n      if (fe_v.get_fe().has_support_on_face(i, face_no) == true) \n        { \n          Sacado::Fad::DFad<double> R_i = 0; \n\n          for (unsigned int point = 0; point < n_q_points; ++point) \n            { \n              const unsigned int component_i = \n                fe_v.get_fe().system_to_component_index(i).first; \n\n              R_i += (parameters.theta * normal_fluxes[point][component_i] + \n                      (1.0 - parameters.theta) * \n                        normal_fluxes_old[point][component_i]) * \n                     fe_v.shape_value_component(i, point, component_i) * \n                     fe_v.JxW(point); \n            } \n\n          for (unsigned int k = 0; k < dofs_per_cell; ++k) \n            residual_derivatives[k] = R_i.fastAccessDx(k); \n          system_matrix.add(dof_indices[i], dof_indices, residual_derivatives); \n\n          if (external_face == false) \n            { \n              for (unsigned int k = 0; k < dofs_per_cell; ++k) \n                residual_derivatives[k] = R_i.fastAccessDx(dofs_per_cell + k); \n              system_matrix.add(dof_indices[i], \n                                dof_indices_neighbor, \n                                residual_derivatives); \n            } \n\n          right_hand_side(dof_indices[i]) -= R_i.val(); \n        } \n  } \n// @sect4{ConservationLaw::solve}  \n\n// 在这里，我们实际解决线性系统，使用Trilinos的Aztec或Amesos线性求解器。计算的结果将被写入传递给这个函数的参数向量中。其结果是一对迭代次数和最终的线性残差。\n\n  template <int dim> \n  std::pair<unsigned int, double> \n  ConservationLaw<dim>::solve(Vector<double> &newton_update) \n  { \n    switch (parameters.solver) \n      { \n\n// 如果参数文件指定要使用直接求解器，那么我们就到这里。这个过程很简单，因为deal.II在Trilinos中为Amesos直接求解器提供了一个封装类。我们所要做的就是创建一个求解器控制对象（这里只是一个虚拟对象，因为我们不会进行任何迭代），然后创建直接求解器对象。在实际进行求解时，注意我们没有传递一个预处理程序。无论如何，这对直接求解器来说没有什么意义。 最后我们返回求解器的控制统计信息&mdash;它将告诉我们没有进行任何迭代，并且最终的线性残差为零，这里没有任何可能提供的更好的信息。\n\n        case Parameters::Solver::direct: \n          { \n            SolverControl                                  solver_control(1, 0); \n            TrilinosWrappers::SolverDirect::AdditionalData data( \n              parameters.output == Parameters::Solver::verbose); \n            TrilinosWrappers::SolverDirect direct(solver_control, data); \n\n            direct.solve(system_matrix, newton_update, right_hand_side); \n\n            return {solver_control.last_step(), solver_control.last_value()}; \n          } \n\n// 同样地，如果我们要使用一个迭代求解器，我们使用Aztec的GMRES求解器。我们也可以在这里使用Trilinos的迭代求解器和预处理类，但是我们选择直接使用Aztec的求解器。对于给定的问题，Aztec的内部预处理实现优于deal.II的包装类，所以我们在AztecOO求解器中使用ILU-T预处理，并设置了一堆可以从参数文件中修改的选项。\n\n// 还有两个实际问题。由于我们将右手边和求解向量建立为deal.II向量对象（而不是矩阵，它是一个Trilinos对象），我们必须将Trilinos Epetra向量交给求解器。 幸运的是，他们支持 \"视图 \"的概念，所以我们只需发送一个指向deal.II向量的指针。我们必须为设置平行分布的向量提供一个Epetra_Map，这只是一个串行的假对象。最简单的方法是要求矩阵提供它的地图，我们要用它为矩阵-向量乘积做好准备。\n\n// 其次，Aztec求解器希望我们传入一个Trilinos Epetra_CrsMatrix，而不是 deal.II包装类本身。所以我们通过trilinos_matrix()命令来访问Trilinos包装类中的实际Trilinos矩阵。Trilinos希望矩阵是非常量的，所以我们必须使用const_cast手动删除常量。\n\n        case Parameters::Solver::gmres: \n          { \n            Epetra_Vector x(View, \n                            system_matrix.trilinos_matrix().DomainMap(), \n                            newton_update.begin()); \n            Epetra_Vector b(View, \n                            system_matrix.trilinos_matrix().RangeMap(), \n                            right_hand_side.begin()); \n\n            AztecOO solver; \n            solver.SetAztecOption( \n              AZ_output, \n              (parameters.output == Parameters::Solver::quiet ? AZ_none : \n                                                                AZ_all)); \n            solver.SetAztecOption(AZ_solver, AZ_gmres); \n            solver.SetRHS(&b); \n            solver.SetLHS(&x); \n\n            solver.SetAztecOption(AZ_precond, AZ_dom_decomp); \n            solver.SetAztecOption(AZ_subdomain_solve, AZ_ilut); \n            solver.SetAztecOption(AZ_overlap, 0); \n            solver.SetAztecOption(AZ_reorder, 0); \n\n            solver.SetAztecParam(AZ_drop, parameters.ilut_drop); \n            solver.SetAztecParam(AZ_ilut_fill, parameters.ilut_fill); \n            solver.SetAztecParam(AZ_athresh, parameters.ilut_atol); \n            solver.SetAztecParam(AZ_rthresh, parameters.ilut_rtol); \n\n            solver.SetUserMatrix( \n              const_cast<Epetra_CrsMatrix *>(&system_matrix.trilinos_matrix())); \n\n            solver.Iterate(parameters.max_iterations, \n                           parameters.linear_residual); \n\n            return {solver.NumIters(), solver.TrueResidual()}; \n          } \n      } \n\n    Assert(false, ExcNotImplemented()); \n    return {0, 0}; \n  } \n// @sect4{ConservationLaw::compute_refinement_indicators}  \n\n// 这个函数是真正的简单。我们在这里并不假装知道一个好的细化指标会是什么。相反，我们认为 <code>EulerEquation</code> 类会知道这个问题，所以我们只是简单地服从于我们在那里实现的相应函数。\n\n  template <int dim> \n  void ConservationLaw<dim>::compute_refinement_indicators( \n    Vector<double> &refinement_indicators) const \n  { \n    EulerEquations<dim>::compute_refinement_indicators(dof_handler, \n                                                       mapping, \n                                                       predictor, \n                                                       refinement_indicators); \n  } \n\n//  @sect4{ConservationLaw::refine_grid}  \n\n// 在这里，我们使用之前计算的细化指标来细化网格。在开始的时候，我们在所有的单元格上循环，并标记那些我们认为应该被细化的单元格。\n\n  template <int dim> \n  void \n  ConservationLaw<dim>::refine_grid(const Vector<double> &refinement_indicators) \n  { \n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        const unsigned int cell_no = cell->active_cell_index(); \n        cell->clear_coarsen_flag(); \n        cell->clear_refine_flag(); \n\n        if ((cell->level() < parameters.shock_levels) && \n            (std::fabs(refinement_indicators(cell_no)) > parameters.shock_val)) \n          cell->set_refine_flag(); \n        else if ((cell->level() > 0) && \n                 (std::fabs(refinement_indicators(cell_no)) < \n                  0.75 * parameters.shock_val)) \n          cell->set_coarsen_flag(); \n      } \n\n// 然后，我们需要在进行细化的同时，将各种解决方案向量从旧网格转移到新网格。SolutionTransfer类是我们的朋友；它有相当丰富的文档，包括例子，所以我们不会对下面的代码做太多评论。最后三行只是把其他一些向量的大小重新设置为现在的正确大小。\n\n    std::vector<Vector<double>> transfer_in; \n    std::vector<Vector<double>> transfer_out; \n\n    transfer_in.push_back(old_solution); \n    transfer_in.push_back(predictor); \n\n    triangulation.prepare_coarsening_and_refinement(); \n\n    SolutionTransfer<dim> soltrans(dof_handler); \n    soltrans.prepare_for_coarsening_and_refinement(transfer_in); \n\n    triangulation.execute_coarsening_and_refinement(); \n\n    dof_handler.clear(); \n    dof_handler.distribute_dofs(fe); \n\n    { \n      Vector<double> new_old_solution(1); \n      Vector<double> new_predictor(1); \n\n      transfer_out.push_back(new_old_solution); \n      transfer_out.push_back(new_predictor); \n      transfer_out[0].reinit(dof_handler.n_dofs()); \n      transfer_out[1].reinit(dof_handler.n_dofs()); \n    } \n\n    soltrans.interpolate(transfer_in, transfer_out); \n\n \n    old_solution = transfer_out[0]; \n\n    predictor.reinit(transfer_out[1].size()); \n    predictor = transfer_out[1]; \n\n    current_solution.reinit(dof_handler.n_dofs()); \n    current_solution = old_solution; \n    right_hand_side.reinit(dof_handler.n_dofs()); \n  } \n// @sect4{ConservationLaw::output_results}  \n\n// 现在的这个函数是相当直接的。所有的魔法，包括将数据从保守变量转化为物理变量，都已经被抽象化，并被移到EulerEquations类中，这样在我们想要解决其他双曲守恒定律时就可以被替换。\n\n// 请注意，输出文件的数量是通过保持一个静态变量形式的计数器来确定的，这个计数器在我们第一次来到这个函数时被设置为零，并在每次调用结束时被增加一。\n\n  template <int dim> \n  void ConservationLaw<dim>::output_results() const \n  { \n    typename EulerEquations<dim>::Postprocessor postprocessor( \n      parameters.schlieren_plot); \n\n    DataOut<dim> data_out; \n    data_out.attach_dof_handler(dof_handler); \n\n    data_out.add_data_vector(current_solution, \n                             EulerEquations<dim>::component_names(), \n                             DataOut<dim>::type_dof_data, \n                             EulerEquations<dim>::component_interpretation()); \n\n    data_out.add_data_vector(current_solution, postprocessor); \n\n    data_out.build_patches(); \n\n    static unsigned int output_file_number = 0; \n    std::string         filename = \n      \"solution-\" + Utilities::int_to_string(output_file_number, 3) + \".vtk\"; \n    std::ofstream output(filename); \n    data_out.write_vtk(output); \n\n    ++output_file_number; \n  } \n\n//  @sect4{ConservationLaw::run}  \n\n// 这个函数包含了这个程序的顶层逻辑：初始化，时间循环，以及牛顿内部迭代。\n\n// 在开始时，我们读取参数文件指定的网格文件，设置DoFHandler和各种向量，然后在这个网格上插值给定的初始条件。然后我们在初始条件的基础上进行一系列的网格细化，以获得一个已经很适应起始解的网格。在这个过程结束时，我们输出初始解。\n\n  template <int dim> \n  void ConservationLaw<dim>::run() \n  { \n    { \n      GridIn<dim> grid_in; \n      grid_in.attach_triangulation(triangulation); \n\n      std::ifstream input_file(parameters.mesh_filename); \n      Assert(input_file, ExcFileNotOpen(parameters.mesh_filename.c_str())); \n\n      grid_in.read_ucd(input_file); \n    } \n\n    dof_handler.clear(); \n    dof_handler.distribute_dofs(fe); \n\n// 所有字段的大小。\n\n    old_solution.reinit(dof_handler.n_dofs()); \n    current_solution.reinit(dof_handler.n_dofs()); \n    predictor.reinit(dof_handler.n_dofs()); \n    right_hand_side.reinit(dof_handler.n_dofs()); \n\n    setup_system(); \n\n    VectorTools::interpolate(dof_handler, \n                             parameters.initial_conditions, \n                             old_solution); \n    current_solution = old_solution; \n    predictor        = old_solution; \n\n    if (parameters.do_refine == true) \n      for (unsigned int i = 0; i < parameters.shock_levels; ++i) \n        { \n          Vector<double> refinement_indicators(triangulation.n_active_cells()); \n\n          compute_refinement_indicators(refinement_indicators); \n          refine_grid(refinement_indicators); \n\n          setup_system(); \n\n          VectorTools::interpolate(dof_handler, \n                                   parameters.initial_conditions, \n                                   old_solution); \n          current_solution = old_solution; \n          predictor        = old_solution; \n        } \n\n    output_results(); \n\n// 然后我们进入主时间步进循环。在顶部，我们简单地输出一些状态信息，这样就可以跟踪计算的位置，以及显示非线性内部迭代进展的表格的标题。\n\n    Vector<double> newton_update(dof_handler.n_dofs()); \n\n    double time        = 0; \n    double next_output = time + parameters.output_step; \n\n    predictor = old_solution; \n    while (time < parameters.final_time) \n      { \n        std::cout << \"T=\" << time << std::endl \n                  << \"   Number of active cells:       \" \n                  << triangulation.n_active_cells() << std::endl \n                  << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n                  << std::endl \n                  << std::endl; \n\n        std::cout << \"   NonLin Res     Lin Iter       Lin Res\" << std::endl \n                  << \"   _____________________________________\" << std::endl; \n\n// 然后是内牛顿迭代，解决每个时间步长的非线性问题。它的工作方式是将矩阵和右手边重置为零，然后组装线性系统。如果右手边的规范足够小，那么我们就宣布牛顿迭代已经收敛了。否则，我们求解线性系统，用牛顿增量更新当前解，并输出收敛信息。最后，我们检查牛顿迭代的次数是否超过了10次的限制--如果超过了，就说明迭代有可能出现了发散，继续迭代也没有什么好处。如果发生这种情况，我们就抛出一个异常，这个异常将在 <code>main()</code> 中被捕获，并在程序终止前显示状态信息。\n\n// 注意，我们写AssertThrow宏的方式基本上等同于写<code>if (!(nonlin_iter  @<=  10)) throw ExcMessage (\"No convergence in nonlinear solver\");</code>这样的话。唯一显著的区别是，AssertThrow还确保被抛出的异常带有它产生的位置（文件名和行号）的信息。这在这里不是太关键，因为只有一个地方可能发生这种异常；然而，当人们想找出错误发生的地方时，它通常是一个非常有用的工具。\n\n        unsigned int nonlin_iter = 0; \n        current_solution         = predictor; \n        while (true) \n          { \n            system_matrix = 0; \n\n            right_hand_side = 0; \n            assemble_system(); \n\n            const double res_norm = right_hand_side.l2_norm(); \n            if (std::fabs(res_norm) < 1e-10) \n              { \n                std::printf(\"   %-16.3e (converged)\\n\\n\", res_norm); \n                break; \n              } \n            else \n              { \n                newton_update = 0; \n\n                std::pair<unsigned int, double> convergence = \n                  solve(newton_update); \n\n                current_solution += newton_update; \n\n                std::printf(\"   %-16.3e %04d        %-5.2e\\n\", \n                            res_norm, \n                            convergence.first, \n                            convergence.second); \n              } \n\n            ++nonlin_iter; \n            AssertThrow(nonlin_iter <= 10, \n                        ExcMessage(\"No convergence in nonlinear solver\")); \n          } \n\n// 只有在牛顿迭代已经收敛的情况下，我们才会到达这一点，所以在这里做各种收敛后的任务。\n\n// 首先，我们更新时间，如果需要的话，产生图形输出。然后，我们通过近似 $\\mathbf w^{n+1}\\approx \\mathbf w^n + \\delta t \\frac{\\partial \\mathbf w}{\\partial t} \\approx \\mathbf w^n + \\delta t \\; \\frac{\\mathbf w^n-\\mathbf w^{n-1}}{\\delta t} = 2 \\mathbf w^n - \\mathbf w^{n-1}$ 来更新下一个时间步长的解决方案的预测器，以尝试使适应性更好地工作。 我们的想法是尝试在前面进行细化，而不是步入一个粗略的元素集并抹去旧的解决方案。 这个简单的时间推断器可以完成这个工作。有了这个，如果用户需要的话，我们就可以对网格进行细化，最后继续进行下一个时间步骤。\n\n        time += parameters.time_step; \n\n        if (parameters.output_step < 0) \n          output_results(); \n        else if (time >= next_output) \n          { \n            output_results(); \n            next_output += parameters.output_step; \n          } \n\n        predictor = current_solution; \n        predictor.sadd(2.0, -1.0, old_solution); \n\n        old_solution = current_solution; \n\n        if (parameters.do_refine == true) \n          { \n            Vector<double> refinement_indicators( \n              triangulation.n_active_cells()); \n            compute_refinement_indicators(refinement_indicators); \n\n            refine_grid(refinement_indicators); \n            setup_system(); \n\n            newton_update.reinit(dof_handler.n_dofs()); \n          } \n      } \n  } \n} // namespace Step33 \n// @sect3{main()}  \n\n// 下面的``main''函数与前面的例子类似，不需要进行注释。请注意，如果在命令行上没有给出输入文件名，程序就会中止。\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace dealii; \n      using namespace Step33; \n\n      if (argc != 2) \n        { \n          std::cout << \"Usage:\" << argv[0] << \" input_file\" << std::endl; \n          std::exit(1); \n        } \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization( \n        argc, argv, dealii::numbers::invalid_unsigned_int); \n\n      ConservationLaw<2> cons(argv[1]); \n      cons.run(); \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    }; \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "926f5af66df1029affb8acd950f2373a8620fed4", "size": 79016, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-33/step-33.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-33/step-33.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-33/step-33.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5277638819, "max_line_length": 617, "alphanum_fraction": 0.5933608383, "num_tokens": 27501, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.43829689456121296}}
{"text": "#pragma once\n\n// system includes ---------------------------------------------------------\n#include <Eigen/Dense>\n#include <cmath>\n\n// own includes ------------------------------------------------------------\n#include \"ridgelet_frame.hpp\"\n\n\ntemplate <typename STORAGE = Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>\nclass RidgeletCellArray\n{\n public:\n  typedef STORAGE value_t;\n  typedef RidgeletCellArray<STORAGE> own_type;\n  typedef typename STORAGE::Scalar numeric_t;\n\n public:\n  RidgeletCellArray(const RidgeletFrame &rf);\n  RidgeletCellArray() {}\n\n  template <class S>\n  void resize(const RidgeletCellArray<S> &other);\n\n  const value_t &operator[](int i) const;\n  value_t &operator[](int i);\n  const std::vector<value_t> &coeffs() const { return data_; }\n  std::vector<value_t> &coeffs() { return data_; }\n\n  template <typename S>\n  own_type &operator=(const RidgeletCellArray<S> &other);\n\n  template <typename S>\n  own_type &operator+=(const RidgeletCellArray<S> &other);\n\n  template <typename S>\n  own_type &operator-=(const RidgeletCellArray<S> &other);\n\n  template <typename S>\n  own_type &operator*=(const RidgeletCellArray<S> &other);\n\n  template <typename NUMERIC_T>\n  own_type &operator*=(NUMERIC_T f);\n\n  template <typename S, typename NUMERIC_T>\n  own_type &sadd(const RidgeletCellArray<S> &other, NUMERIC_T a);\n  /**\n   * this += a*this + b*other\n   */\n  template <typename S, typename NUMERIC1_T, typename NUMERIC2_T>\n  own_type &sadd(NUMERIC1_T a, const RidgeletCellArray<S> &other, NUMERIC2_T b);\n\n  template <typename S, typename NUMERIC_T>\n  own_type &sadd(NUMERIC_T a,\n                 const RidgeletCellArray<S> &r1,\n                 NUMERIC_T a1,\n                 const RidgeletCellArray<S> &r2,\n                 NUMERIC_T a2);\n\n  double norm() const;\n  numeric_t dot(const RidgeletCellArray<STORAGE> &other) const;\n  const RidgeletFrame &rf() const { return rf_; }\n  unsigned int size() const { return data_.size(); }\n\n private:\n  RidgeletFrame rf_;\n  std::vector<value_t> data_;\n  Eigen::VectorXd Tx_;\n  Eigen::VectorXd Ty_;\n  bool T_initialized_ = false;\n};\n\ntemplate <typename STORAGE>\nRidgeletCellArray<STORAGE>::RidgeletCellArray(const RidgeletFrame &rf)\n    : rf_(rf)\n{\n  data_.resize(rf.size());\n\n  const auto &lambdas = rf_.lambdas();\n\n  std::function<int(int)> pow2p = [](int j) {\n    assert(j >= 0);\n    if (j == 0)\n      return 1;\n    else\n      return 2 << (j - 1);\n  };\n\n  unsigned int N = lambdas.size();\n  Tx_.resize(N);\n  Ty_.resize(N);\n  unsigned int rho_x = rf_.rho_x();\n  unsigned int rho_y = rf_.rho_y();\n  for (unsigned int i = 0; i < N; ++i) {\n    if (lambdas[i].t == rt_type::S) {\n      Tx_[i] = 4 * rho_x;\n      Ty_[i] = 4 * rho_y;\n    } else if (lambdas[i].t == rt_type::D) {\n      Tx_[i] = pow2p(lambdas[i].j + 2) * rho_x;\n      Ty_[i] = 8 * rho_y;\n    } else if (lambdas[i].t == rt_type::X) {\n      Tx_[i] = pow2p(lambdas[i].j + 2) * rho_x;\n      Ty_[i] = 8 * rho_y;\n    } else if (lambdas[i].t == rt_type::Y) {\n      Tx_[i] = 8 * rho_x;\n      Ty_[i] = pow2p(lambdas[i].j + 2) * rho_y;\n    }\n    data_[i].resize(Ty_[i], Tx_[i]);\n  }\n  T_initialized_ = true;\n}\n\ntemplate <typename STORAGE>\ntemplate <typename S>\nvoid\nRidgeletCellArray<STORAGE>::resize(const RidgeletCellArray<S> &other)\n{\n  data_.resize(other.data_.size());\n\n  for (unsigned int i = 0; i < other.data_.size(); ++i) {\n    data_[i].resize(other.data_[i].rows(), other.data_[i].cols());\n  }\n}\n\ntemplate <typename STORAGE>\ntypename RidgeletCellArray<STORAGE>::numeric_t\nRidgeletCellArray<STORAGE>::dot(const RidgeletCellArray<STORAGE> &other) const\n{\n  assert(T_initialized_);\n  numeric_t sum = 0;\n  for (unsigned int i = 0; i < data_.size(); ++i) {\n    sum += Tx_[i] * Ty_[i] * (data_[i] * other.data_[i].conjugate()).sum();\n  }\n\n  return sum;\n}\n\ntemplate <typename STORAGE>\ndouble\nRidgeletCellArray<STORAGE>::norm() const\n{\n  numeric_t v = this->dot(*this);\n  return std::sqrt(std::real(v));\n}\n\ntemplate <typename STORAGE>\ninline const typename RidgeletCellArray<STORAGE>::value_t &RidgeletCellArray<STORAGE>::operator[](\n    int i) const\n{\n  return data_[i];\n}\n\ntemplate <typename STORAGE>\ninline typename RidgeletCellArray<STORAGE>::value_t &RidgeletCellArray<STORAGE>::operator[](int i)\n{\n  return data_[i];\n}\n\ntemplate <typename STORAGE>\ntemplate <typename S>\ninline typename RidgeletCellArray<STORAGE>::own_type &\nRidgeletCellArray<STORAGE>::operator=(const RidgeletCellArray<S> &other)\n{\n  data_ = other.data_;\n  rf_ = other.rf_;\n  Tx_ = other.Tx_;\n  Ty_ = other.Ty_;\n  T_initialized_ = true;\n  return *this;\n}\n\ntemplate <typename STORAGE>\ntemplate <typename S>\ninline typename RidgeletCellArray<STORAGE>::own_type &\nRidgeletCellArray<STORAGE>::operator+=(const RidgeletCellArray<S> &other)\n{\n  for (unsigned int i = 0; i < data_.size(); ++i) {\n    data_[i] += other.data_[i];\n  }\n  return *this;\n}\n\ntemplate <typename STORAGE>\ntemplate <typename S>\ninline typename RidgeletCellArray<STORAGE>::own_type &\nRidgeletCellArray<STORAGE>::operator-=(const RidgeletCellArray<S> &other)\n{\n  for (unsigned int i = 0; i < data_.size(); ++i) {\n    data_[i] -= other.data_[i];\n  }\n  return *this;\n}\n\ntemplate <typename STORAGE>\ntemplate <typename S>\ninline typename RidgeletCellArray<STORAGE>::own_type &\nRidgeletCellArray<STORAGE>::operator*=(const RidgeletCellArray<S> &other)\n{\n  for (unsigned int i = 0; i < data_.size(); ++i) {\n    data_[i] *= other.data_[i];\n  }\n  return *this;\n}\n\ntemplate <typename STORAGE>\ntemplate <typename NUMERIC_T>\ninline typename RidgeletCellArray<STORAGE>::own_type &\nRidgeletCellArray<STORAGE>::operator*=(NUMERIC_T f)\n{\n  for (unsigned int i = 0; i < data_.size(); ++i) {\n    data_[i] *= f;\n  }\n  return *this;\n}\n\ntemplate <typename STORAGE>\ntemplate <typename S, typename NUMERIC_T>\ninline typename RidgeletCellArray<STORAGE>::own_type &\nRidgeletCellArray<STORAGE>::sadd(const RidgeletCellArray<S> &other, NUMERIC_T f)\n{\n  for (unsigned int i = 0; i < data_.size(); ++i) {\n    data_[i] += f * other.data_[i];\n  }\n  return *this;\n}\n\ntemplate <typename STORAGE>\ntemplate <typename S, typename NUMERIC1_T, typename NUMERIC2_T>\ninline typename RidgeletCellArray<STORAGE>::own_type &\nRidgeletCellArray<STORAGE>::sadd(NUMERIC1_T a, const RidgeletCellArray<S> &other, NUMERIC2_T b)\n{\n  for (unsigned int i = 0; i < data_.size(); ++i) {\n    data_[i] *= a;\n    data_[i] += b * other.data_[i];\n  }\n}\n\ntemplate <typename STORAGE>\ntemplate <typename S, typename NUMERIC_T>\ninline typename RidgeletCellArray<STORAGE>::own_type &\nRidgeletCellArray<STORAGE>::sadd(NUMERIC_T a,\n                                 const RidgeletCellArray<S> &r1,\n                                 NUMERIC_T a1,\n                                 const RidgeletCellArray<S> &r2,\n                                 NUMERIC_T a2)\n{\n  for (unsigned int i = 0; i < data_.size(); ++i) {\n    data_[i] *= a;\n    data_[i] += a1 * r1.data_[i] + a2 * r2.data_[i];\n  }\n}\n", "meta": {"hexsha": "74e0083839c7ef48f33d228ed1ea4d9b62956331", "size": 6889, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ridgelet/ridgelet_cell_array.hpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "ridgelet/ridgelet_cell_array.hpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ridgelet/ridgelet_cell_array.hpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 27.2292490119, "max_line_length": 99, "alphanum_fraction": 0.6504572507, "num_tokens": 2028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.4382968809177757}}
{"text": "#include <valarray>\n#include <iterator>\n\n#include <symengine/prime_sieve.h>\n#include <symengine/ntheory.h>\n#include <symengine/rational.h>\n#include <symengine/add.h>\n#include <symengine/mul.h>\n#include <symengine/pow.h>\n#ifdef HAVE_SYMENGINE_ECM\n#include <ecm.h>\n#endif // HAVE_SYMENGINE_ECM\n#ifdef HAVE_SYMENGINE_PRIMESIEVE\n#include <primesieve.hpp>\n#endif // HAVE_SYMENGINE_PRIMESIEVE\n#ifdef HAVE_SYMENGINE_ARB\n#include \"arb.h\"\n#include \"bernoulli.h\"\n#include \"rational.h\"\n#endif // HAVE_SYMENGINE_ARB\n#ifndef HAVE_SYMENGINE_GMP\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random.hpp>\n#endif // !HAVE_SYMENGINE_GMP\n\nnamespace SymEngine\n{\n\n// Basic number theoretic functions\nRCP<const Integer> gcd(const Integer &a, const Integer &b)\n{\n    integer_class g;\n    mp_gcd(g, a.as_integer_class(), b.as_integer_class());\n    return integer(std::move(g));\n}\n\nvoid gcd_ext(const Ptr<RCP<const Integer>> &g, const Ptr<RCP<const Integer>> &s,\n             const Ptr<RCP<const Integer>> &t, const Integer &a,\n             const Integer &b)\n{\n    integer_class g_, s_, t_;\n    mp_gcdext(g_, s_, t_, a.as_integer_class(), b.as_integer_class());\n    *g = integer(std::move(g_));\n    *s = integer(std::move(s_));\n    *t = integer(std::move(t_));\n}\n\nRCP<const Integer> lcm(const Integer &a, const Integer &b)\n{\n    integer_class c;\n    mp_lcm(c, a.as_integer_class(), b.as_integer_class());\n    return integer(std::move(c));\n}\n\nint mod_inverse(const Ptr<RCP<const Integer>> &b, const Integer &a,\n                const Integer &m)\n{\n    int ret_val;\n    integer_class inv_t;\n    ret_val = mp_invert(inv_t, a.as_integer_class(), m.as_integer_class());\n    *b = integer(std::move(inv_t));\n    return ret_val;\n}\n\nRCP<const Integer> mod(const Integer &n, const Integer &d)\n{\n    return integer(n.as_integer_class() % d.as_integer_class());\n}\n\nRCP<const Integer> quotient(const Integer &n, const Integer &d)\n{\n    return integer(n.as_integer_class() / d.as_integer_class());\n}\n\nvoid quotient_mod(const Ptr<RCP<const Integer>> &q,\n                  const Ptr<RCP<const Integer>> &r, const Integer &n,\n                  const Integer &d)\n{\n    integer_class _q, _r;\n    mp_tdiv_qr(_q, _r, n.as_integer_class(), d.as_integer_class());\n    *q = integer(std::move(_q));\n    *r = integer(std::move(_r));\n}\n\nRCP<const Integer> mod_f(const Integer &n, const Integer &d)\n{\n    integer_class q;\n    mp_fdiv_r(q, n.as_integer_class(), d.as_integer_class());\n    return integer(std::move(q));\n}\n\nRCP<const Integer> quotient_f(const Integer &n, const Integer &d)\n{\n    integer_class q;\n    mp_fdiv_q(q, n.as_integer_class(), d.as_integer_class());\n    return integer(std::move(q));\n}\n\nvoid quotient_mod_f(const Ptr<RCP<const Integer>> &q,\n                    const Ptr<RCP<const Integer>> &r, const Integer &n,\n                    const Integer &d)\n{\n    integer_class _q, _r;\n    mp_fdiv_qr(_q, _r, n.as_integer_class(), d.as_integer_class());\n    *q = integer(std::move(_q));\n    *r = integer(std::move(_r));\n}\n\nRCP<const Integer> fibonacci(unsigned long n)\n{\n    integer_class f;\n    mp_fib_ui(f, n);\n    return integer(std::move(f));\n}\n\nvoid fibonacci2(const Ptr<RCP<const Integer>> &g,\n                const Ptr<RCP<const Integer>> &s, unsigned long n)\n{\n    integer_class g_t;\n    integer_class s_t;\n    mp_fib2_ui(g_t, s_t, n);\n    *g = integer(std::move(g_t));\n    *s = integer(std::move(s_t));\n}\n\nRCP<const Integer> lucas(unsigned long n)\n{\n    integer_class f;\n    mp_lucnum_ui(f, n);\n    return integer(std::move(f));\n}\n\nvoid lucas2(const Ptr<RCP<const Integer>> &g, const Ptr<RCP<const Integer>> &s,\n            unsigned long n)\n{\n    integer_class g_t;\n    integer_class s_t;\n    mp_lucnum2_ui(g_t, s_t, n);\n    *g = integer(std::move(g_t));\n    *s = integer(std::move(s_t));\n}\n\n// Binomial Coefficient\nRCP<const Integer> binomial(const Integer &n, unsigned long k)\n{\n    integer_class f;\n    mp_bin_ui(f, n.as_integer_class(), k);\n    return integer(std::move(f));\n}\n\n// Factorial\nRCP<const Integer> factorial(unsigned long n)\n{\n    integer_class f;\n    mp_fac_ui(f, n);\n    return integer(std::move(f));\n}\n\n// Returns true if `b` divides `a` without reminder\nbool divides(const Integer &a, const Integer &b)\n{\n    return mp_divisible_p(a.as_integer_class(), b.as_integer_class()) != 0;\n}\n\n// Prime functions\nint probab_prime_p(const Integer &a, unsigned reps)\n{\n    return mp_probab_prime_p(a.as_integer_class(), reps);\n}\n\nRCP<const Integer> nextprime(const Integer &a)\n{\n    integer_class c;\n    mp_nextprime(c, a.as_integer_class());\n    return integer(std::move(c));\n}\n\nnamespace\n{\n// Factoring by Trial division using primes only\nint _factor_trial_division_sieve(integer_class &factor, const integer_class &N)\n{\n    integer_class sqrtN = mp_sqrt(N);\n    unsigned long limit = mp_get_ui(sqrtN);\n    if (limit > std::numeric_limits<unsigned>::max())\n        throw SymEngineException(\"N too large to factor\");\n    Sieve::iterator pi(numeric_cast<unsigned>(limit));\n    unsigned p;\n    while ((p = pi.next_prime()) <= limit) {\n        if (N % p == 0) {\n            factor = p;\n            return 1;\n        }\n    }\n    return 0;\n}\n// Factor using lehman method.\nint _factor_lehman_method(integer_class &rop, const integer_class &n)\n{\n    if (n < 21)\n        throw SymEngineException(\"Require n >= 21 to use lehman method\");\n\n    int ret_val = 0;\n    integer_class u_bound;\n\n    mp_root(u_bound, n, 3);\n    u_bound = u_bound + 1;\n\n    Sieve::iterator pi(numeric_cast<unsigned>(mp_get_ui(u_bound)));\n    unsigned p;\n    while ((p = pi.next_prime()) <= mp_get_ui(u_bound)) {\n        if (n % p == 0) {\n            rop = n / p;\n            ret_val = 1;\n            break;\n        }\n    }\n\n    if (not ret_val) {\n\n        integer_class k, a, b, l;\n\n        k = 1;\n\n        while (k <= u_bound) {\n            a = mp_sqrt(4 * k * n);\n            mp_root(b, n, 6);\n            mp_root(l, k, 2);\n            b = b / (4 * l);\n            b = b + a;\n\n            while (a <= b) {\n                l = a * a - 4 * k * n;\n                if (mp_perfect_square_p(l)) {\n                    b = a + mp_sqrt(l);\n                    mp_gcd(rop, n, b);\n                    ret_val = 1;\n                    break;\n                }\n                a = a + 1;\n            }\n            if (ret_val)\n                break;\n            k = k + 1;\n        }\n    }\n\n    return ret_val;\n}\n} // anonymous namespace\n\nint factor_lehman_method(const Ptr<RCP<const Integer>> &f, const Integer &n)\n{\n    int ret_val;\n    integer_class rop;\n\n    ret_val = _factor_lehman_method(rop, n.as_integer_class());\n    *f = integer(std::move(rop));\n    return ret_val;\n}\n\nnamespace\n{\n// Factor using Pollard's p-1 method\nint _factor_pollard_pm1_method(integer_class &rop, const integer_class &n,\n                               const integer_class &c, unsigned B)\n{\n    if (n < 4 or B < 3)\n        throw SymEngineException(\n            \"Require n > 3 and B > 2 to use Pollard's p-1 method\");\n\n    integer_class m, _c;\n    _c = c;\n\n    Sieve::iterator pi(B);\n    unsigned p;\n    while ((p = pi.next_prime()) <= B) {\n        m = 1;\n        // calculate log(p, B), this can be improved\n        while (m <= B / p) {\n            m = m * p;\n        }\n        mp_powm(_c, _c, m, n);\n    }\n    _c = _c - 1;\n    mp_gcd(rop, _c, n);\n\n    if (rop == 1 or rop == n)\n        return 0;\n    else\n        return 1;\n}\n} // anonymous namespace\n\nint factor_pollard_pm1_method(const Ptr<RCP<const Integer>> &f,\n                              const Integer &n, unsigned B, unsigned retries)\n{\n    int ret_val = 0;\n    integer_class rop, nm4, c;\n\n    mp_randstate state;\n    nm4 = n.as_integer_class() - 4;\n\n    for (unsigned i = 0; i < retries and ret_val == 0; ++i) {\n        state.urandomint(c, nm4);\n        c += 2;\n        ret_val = _factor_pollard_pm1_method(rop, n.as_integer_class(), c, B);\n    }\n\n    if (ret_val != 0)\n        *f = integer(std::move(rop));\n    return ret_val;\n}\n\nnamespace\n{\n// Factor using Pollard's rho method\nint _factor_pollard_rho_method(integer_class &rop, const integer_class &n,\n                               const integer_class &a, const integer_class &s,\n                               unsigned steps = 10000)\n{\n    if (n < 5)\n        throw SymEngineException(\"Require n > 4 to use pollard's-rho method\");\n\n    integer_class u, v, g, m;\n    u = s;\n    v = s;\n\n    for (unsigned i = 0; i < steps; ++i) {\n        u = (u * u + a) % n;\n        v = (v * v + a) % n;\n        v = (v * v + a) % n;\n        m = u - v;\n        mp_gcd(g, m, n);\n\n        if (g == n)\n            return 0;\n        if (g == 1)\n            continue;\n        rop = g;\n        return 1;\n    }\n    return 0;\n}\n} // namespace\n\nint factor_pollard_rho_method(const Ptr<RCP<const Integer>> &f,\n                              const Integer &n, unsigned retries)\n{\n    int ret_val = 0;\n    integer_class rop, nm1, nm4, a, s;\n    mp_randstate state;\n    nm1 = n.as_integer_class() - 1;\n    nm4 = n.as_integer_class() - 4;\n\n    for (unsigned i = 0; i < retries and ret_val == 0; ++i) {\n        state.urandomint(a, nm1);\n        state.urandomint(s, nm4);\n        s += 1;\n        ret_val = _factor_pollard_rho_method(rop, n.as_integer_class(), a, s);\n    }\n\n    if (ret_val != 0)\n        *f = integer(std::move(rop));\n    return ret_val;\n}\n\n// Factorization\nint factor(const Ptr<RCP<const Integer>> &f, const Integer &n, double B1)\n{\n    int ret_val = 0;\n    integer_class _n, _f;\n\n    _n = n.as_integer_class();\n\n#ifdef HAVE_SYMENGINE_ECM\n    if (mp_perfect_power_p(_n)) {\n\n        unsigned long int i = 1;\n        integer_class m, rem;\n        rem = 1; // Any non zero number\n        m = 2;   // set `m` to 2**i, i = 1 at the begining\n\n        // calculate log2n, this can be improved\n        for (; m < _n; ++i)\n            m = m * 2;\n\n        // eventually `rem` = 0 zero as `n` is a perfect power. `f_t` will\n        // be set to a factor of `n` when that happens\n        while (i > 1 and rem != 0) {\n            mp_rootrem(_f, rem, _n, i);\n            --i;\n        }\n\n        ret_val = 1;\n    } else {\n\n        if (mp_probab_prime_p(_n, 25) > 0) { // most probably, n is a prime\n            ret_val = 0;\n            _f = _n;\n        } else {\n\n            for (int i = 0; i < 10 and not ret_val; ++i)\n                ret_val = ecm_factor(get_mpz_t(_f), get_mpz_t(_n), B1, nullptr);\n            mp_demote(_f);\n            if (not ret_val)\n                throw SymEngineException(\n                    \"ECM failed to factor the given number\");\n        }\n    }\n#else\n    // B1 is discarded if gmp-ecm is not installed\n    ret_val = _factor_trial_division_sieve(_f, _n);\n#endif // HAVE_SYMENGINE_ECM\n    *f = integer(std::move(_f));\n\n    return ret_val;\n}\n\nint factor_trial_division(const Ptr<RCP<const Integer>> &f, const Integer &n)\n{\n    int ret_val;\n    integer_class factor;\n    ret_val = _factor_trial_division_sieve(factor, n.as_integer_class());\n    if (ret_val == 1)\n        *f = integer(std::move(factor));\n    return ret_val;\n}\n\nvoid prime_factors(std::vector<RCP<const Integer>> &prime_list,\n                   const Integer &n)\n{\n    integer_class sqrtN;\n    integer_class _n = n.as_integer_class();\n    if (_n == 0)\n        return;\n    if (_n < 0)\n        _n *= -1;\n\n    sqrtN = mp_sqrt(_n);\n    auto limit = mp_get_ui(sqrtN);\n    if (not mp_fits_ulong_p(sqrtN)\n        or limit > std::numeric_limits<unsigned>::max())\n        throw SymEngineException(\"N too large to factor\");\n    Sieve::iterator pi(numeric_cast<unsigned>(limit));\n    unsigned p;\n\n    while ((p = pi.next_prime()) <= limit) {\n        while (_n % p == 0) {\n            prime_list.push_back(integer(p));\n            _n = _n / p;\n        }\n        if (_n == 1)\n            break;\n    }\n    if (not(_n == 1))\n        prime_list.push_back(integer(std::move(_n)));\n}\n\nvoid prime_factor_multiplicities(map_integer_uint &primes_mul, const Integer &n)\n{\n    integer_class sqrtN;\n    integer_class _n = n.as_integer_class();\n    unsigned count;\n    if (_n == 0)\n        return;\n    if (_n < 0)\n        _n *= -1;\n\n    sqrtN = mp_sqrt(_n);\n    auto limit = mp_get_ui(sqrtN);\n    if (not mp_fits_ulong_p(sqrtN)\n        or limit > std::numeric_limits<unsigned>::max())\n        throw SymEngineException(\"N too large to factor\");\n    Sieve::iterator pi(numeric_cast<unsigned>(limit));\n\n    unsigned p;\n    while ((p = pi.next_prime()) <= limit) {\n        count = 0;\n        while (_n % p == 0) { // when a prime factor is found, we divide\n            ++count;          // _n by that prime as much as we can\n            _n = _n / p;\n        }\n        if (count > 0) {\n            insert(primes_mul, integer(p), count);\n            if (_n == 1)\n                break;\n        }\n    }\n    if (not(_n == 1))\n        insert(primes_mul, integer(std::move(_n)), 1);\n}\n\nRCP<const Number> bernoulli(unsigned long n)\n{\n#ifdef HAVE_SYMENGINE_ARB\n    fmpq_t res;\n    fmpq_init(res);\n    bernoulli_fmpq_ui(res, n);\n    mpq_t a;\n    mpq_init(a);\n    fmpq_get_mpq(a, res);\n    rational_class b(a);\n    fmpq_clear(res);\n    mpq_clear(a);\n    return Rational::from_mpq(std::move(b));\n#else\n    // TODO: implement a faster algorithm\n    std::vector<rational_class> v(n + 1);\n    for (unsigned m = 0; m <= n; ++m) {\n        v[m] = rational_class(1u, m + 1);\n\n        for (unsigned j = m; j >= 1; --j) {\n            v[j - 1] = j * (v[j - 1] - v[j]);\n        }\n    }\n    return Rational::from_mpq(v[0]);\n#endif\n}\n\nRCP<const Number> harmonic(unsigned long n, long m)\n{\n    rational_class res(0);\n    if (m == 1) {\n        for (unsigned i = 1; i <= n; ++i) {\n            res += rational_class(1u, i);\n        }\n        return Rational::from_mpq(res);\n    } else {\n        for (unsigned i = 1; i <= n; ++i) {\n            if (m > 0) {\n                rational_class t(1u, i);\n#if SYMENGINE_INTEGER_CLASS != SYMENGINE_BOOSTMP\n                mp_pow_ui(get_den(t), get_den(t), m);\n#else\n                mp_pow_ui(t, t, m);\n#endif\n                res += t;\n            } else {\n                integer_class t(i);\n                mp_pow_ui(t, t, static_cast<unsigned long>(-m));\n                res += t;\n            }\n        }\n        return Rational::from_mpq(res);\n    }\n}\n\n// References : Cohen H., A course in computational algebraic number theory\n// (1996), page 21.\nbool crt(const Ptr<RCP<const Integer>> &R,\n         const std::vector<RCP<const Integer>> &rem,\n         const std::vector<RCP<const Integer>> &mod)\n{\n    if (mod.size() > rem.size())\n        throw SymEngineException(\"Too few remainders\");\n    if (mod.size() == 0)\n        throw SymEngineException(\"Moduli vector cannot be empty\");\n\n    integer_class m, r, g, s, t;\n    m = mod[0]->as_integer_class();\n    r = rem[0]->as_integer_class();\n\n    for (unsigned i = 1; i < mod.size(); ++i) {\n        mp_gcdext(g, s, t, m, mod[i]->as_integer_class());\n        // g = s * m + t * mod[i]\n        t = rem[i]->as_integer_class() - r;\n        if (not mp_divisible_p(t, g))\n            return false;\n        r += m * s * (t / g); // r += m * (m**-1 mod[i]/g)* (rem[i] - r) / g\n        m *= mod[i]->as_integer_class() / g;\n        mp_fdiv_r(r, r, m);\n    }\n    *R = integer(std::move(r));\n    return true;\n}\n\nnamespace\n{\n// Crt over a cartesian product of vectors (Assuming that moduli are pairwise\n// relatively prime).\nvoid _crt_cartesian(std::vector<RCP<const Integer>> &R,\n                    const std::vector<std::vector<RCP<const Integer>>> &rem,\n                    const std::vector<RCP<const Integer>> &mod)\n{\n    if (mod.size() > rem.size())\n        throw SymEngineException(\"Too few remainders\");\n    if (mod.size() == 0)\n        throw SymEngineException(\"Moduli vector cannot be empty\");\n    integer_class m, _m, r, s, t;\n    m = mod[0]->as_integer_class();\n    R = rem[0];\n\n    for (unsigned i = 1; i < mod.size(); ++i) {\n        std::vector<RCP<const Integer>> rem2;\n        mp_invert(s, m, mod[i]->as_integer_class());\n        _m = m;\n        m *= mod[i]->as_integer_class();\n        for (auto &elem : R) {\n            for (auto &_k : rem[i]) {\n                r = elem->as_integer_class();\n                r += _m * s * (_k->as_integer_class() - r);\n                mp_fdiv_r(r, r, m);\n                rem2.push_back(integer(r));\n            }\n        }\n        R = rem2;\n    }\n}\n\n// Tests whether n is a prime power and finds a prime p and e such that n =\n// p**e.\nbool _prime_power(integer_class &p, integer_class &e, const integer_class &n)\n{\n    if (n < 2)\n        return false;\n    integer_class _n = n, temp;\n    e = 1;\n    unsigned i = 2;\n    while (mp_perfect_power_p(_n) and _n >= 2) {\n        if (mp_root(temp, _n, i)) {\n            e *= i;\n            _n = temp;\n        } else {\n            ++i;\n        }\n    }\n    if (mp_probab_prime_p(_n, 25)) {\n        p = _n;\n        return true;\n    }\n    return false;\n}\n\n// Computes a primitive root modulo p**e or 2*p**e where p is an odd prime.\n// References : Cohen H., A course in computational algebraic number theory\n// (2009), pages 25-27.\nvoid _primitive_root(integer_class &g, const integer_class &p,\n                     const integer_class &e, bool even = false)\n{\n    std::vector<RCP<const Integer>> primes;\n    prime_factors(primes, *integer(p - 1));\n\n    integer_class t;\n    g = 2;\n    while (g < p) {\n        bool root = true;\n        for (const auto &it : primes) {\n            t = it->as_integer_class();\n            t = (p - 1) / t;\n            mp_powm(t, g, t, p);\n            if (t == 1) { // If g**(p-1)/q is 1 then g is not a primitive root.\n                root = false;\n                break;\n            }\n        }\n        if (root)\n            break;\n        ++g;\n    }\n\n    if (e > 1) {\n        t = p * p;\n        integer_class pm1 = p - 1;\n        mp_powm(t, g, pm1, t);\n        if (t == 1) { // If g**(p-1) mod (p**2) == 1 then g + p is a primitive\n                      // root.\n            g += p;\n        }\n    }\n    if (even and g % 2 == 0) {\n        mp_pow_ui(t, p, mp_get_ui(e));\n        g += t; // If g is even then root of 2*p**e is g + p**e.\n    }\n}\n\n} // anonymous namespace\n\nbool primitive_root(const Ptr<RCP<const Integer>> &g, const Integer &n)\n{\n    integer_class _n = n.as_integer_class();\n    if (_n < 0)\n        _n = -_n;\n    if (_n <= 1)\n        return false;\n    if (_n < 5) {\n        *g = integer(_n - 1);\n        return true;\n    }\n    bool even = false;\n    if (_n % 2 == 0) {\n        if (_n % 4 == 0) {\n            return false; // If n mod 4 == 0 and n > 4, then no primitive roots.\n        }\n        _n /= 2;\n        even = true;\n    }\n    integer_class p, e;\n    if (not _prime_power(p, e, _n))\n        return false;\n    _primitive_root(_n, p, e, even);\n    *g = integer(std::move(_n));\n    return true;\n}\n\nnamespace\n{\n// Computes primitive roots modulo p**e or 2*p**e where p is an odd prime.\n// References :\n// [1] Cohen H., A course in computational algebraic number theory (1996), pages\n// 25-27.\n// [2] Hackman P., Elementary number theory (2009), page 28.\nvoid _primitive_root_list(std::vector<RCP<const Integer>> &roots,\n                          const integer_class &p, const integer_class &e,\n                          bool even = false)\n{\n    integer_class g, h, d, t, pe2, n, pm1;\n    _primitive_root(g, p, integer_class(1),\n                    false); // Find one primitive root for p.\n    h = 1;\n    pm1 = p - 1;\n    // Generate other primitive roots for p. h = g**i and gcd(i, p-1) = 1.\n    // Ref[2]\n    mp_pow_ui(n, p, mp_get_ui(e));\n    for (unsigned long i = 1; i < p; ++i) {\n        h *= g;\n        h %= p;\n        mp_gcd(d, pm1, integer_class(i));\n        if (d == 1) {\n            if (e == 1) {\n                if (even and h % 2 == 0)\n                    roots.push_back(integer(h + n));\n                else\n                    roots.push_back(integer(h));\n            } else {\n                integer_class pp = p * p;\n                // Find d such that (h + d*p)**(p-1) mod (p**2) == 1. Ref[1]\n                // h**(p-1) - 1 = d*p*h**(p-2)\n                // d = (h - h**(2-p)) / p\n                t = 2 - p;\n                mp_powm(d, h, t, pp);\n                d = ((h - d) / p + p) % p;\n                t = h;\n                // t = h + i * p + j * p * p and i != d\n                mp_pow_ui(pe2, p, mp_get_ui(e) - 2);\n                for (unsigned long j = 0; j < pe2; ++j) {\n                    for (unsigned long i = 0; i < p; ++i) {\n                        if (i != d) {\n                            if (even and t % 2 == 0)\n                                roots.push_back(integer(t + n));\n                            else\n                                roots.push_back(integer(t));\n                        }\n                        t += p;\n                    }\n                }\n            }\n        }\n    }\n} //_primitive_root_list\n} // anonymous namespace\n\nvoid primitive_root_list(std::vector<RCP<const Integer>> &roots,\n                         const Integer &n)\n{\n    integer_class _n = n.as_integer_class();\n    if (_n < 0)\n        _n = -_n;\n    if (_n <= 1)\n        return;\n    if (_n < 5) {\n        roots.push_back(integer(_n - 1));\n        return;\n    }\n    bool even = false;\n    if (_n % 2 == 0) {\n        if (_n % 4 == 0) {\n            return; // If n%4 == 0 and n > 4, then no primitive roots.\n        }\n        _n /= 2;\n        even = true;\n    }\n    integer_class p, e;\n    if (not _prime_power(p, e, _n))\n        return;\n    _primitive_root_list(roots, p, e, even);\n    std::sort(roots.begin(), roots.end(), SymEngine::RCPIntegerKeyLess());\n    return;\n}\n\nRCP<const Integer> totient(const RCP<const Integer> &n)\n{\n    if (n->is_zero())\n        return integer(1);\n\n    integer_class phi = n->as_integer_class(), p;\n    if (phi < 0)\n        phi = -phi;\n    map_integer_uint prime_mul;\n    prime_factor_multiplicities(prime_mul, *n);\n\n    for (const auto &it : prime_mul) {\n        p = it.first->as_integer_class();\n        mp_divexact(phi, phi, p);\n        // phi is exactly divisible by p.\n        phi *= p - 1;\n    }\n    return integer(std::move(phi));\n}\n\nRCP<const Integer> carmichael(const RCP<const Integer> &n)\n{\n    if (n->is_zero())\n        return integer(1);\n\n    map_integer_uint prime_mul;\n    integer_class lambda, t, p;\n    unsigned multiplicity;\n\n    prime_factor_multiplicities(prime_mul, *n);\n    lambda = 1;\n    for (const auto &it : prime_mul) {\n        p = it.first->as_integer_class();\n        multiplicity = it.second;\n        if (p == 2\n            and multiplicity\n                    > 2) { // For powers of 2 greater than 4 divide by 2.\n            multiplicity--;\n        }\n        t = p - 1;\n        mp_lcm(lambda, lambda, t);\n        mp_pow_ui(t, p, multiplicity - 1);\n        // lambda and p are relatively prime.\n        lambda = lambda * t;\n    }\n    return integer(std::move(lambda));\n}\n\n// References : Cohen H., A course in computational algebraic number theory\n// (1996), page 25.\nbool multiplicative_order(const Ptr<RCP<const Integer>> &o,\n                          const RCP<const Integer> &a,\n                          const RCP<const Integer> &n)\n{\n    integer_class order, p, t;\n    integer_class _a = a->as_integer_class(),\n                  _n = mp_abs(n->as_integer_class());\n    mp_gcd(t, _a, _n);\n    if (t != 1)\n        return false;\n\n    RCP<const Integer> lambda = carmichael(n);\n    map_integer_uint prime_mul;\n    prime_factor_multiplicities(prime_mul, *lambda);\n    _a %= _n;\n    order = lambda->as_integer_class();\n\n    for (const auto &it : prime_mul) {\n        p = it.first->as_integer_class();\n        mp_pow_ui(t, p, it.second);\n        mp_divexact(order, order, t);\n        mp_powm(t, _a, order, _n);\n        while (t != 1) {\n            mp_powm(t, t, p, _n);\n            order *= p;\n        }\n    }\n    *o = integer(std::move(order));\n    return true;\n}\nint legendre(const Integer &a, const Integer &n)\n{\n    return mp_legendre(a.as_integer_class(), n.as_integer_class());\n}\n\nint jacobi(const Integer &a, const Integer &n)\n{\n    return mp_jacobi(a.as_integer_class(), n.as_integer_class());\n}\n\nint kronecker(const Integer &a, const Integer &n)\n{\n    return mp_kronecker(a.as_integer_class(), n.as_integer_class());\n}\n\nnamespace\n{\nbool _sqrt_mod_tonelli_shanks(integer_class &rop, const integer_class &a,\n                              const integer_class &p)\n{\n    mp_randstate state;\n    integer_class n, y, b, q, pm1, t(1);\n    pm1 = p - 1;\n    unsigned e, m;\n    e = numeric_cast<unsigned>(mp_scan1(pm1));\n    q = pm1 >> e; // p - 1 = 2**e*q\n\n    while (t != -1) {\n        state.urandomint(n, p);\n        t = mp_legendre(n, p);\n    }\n    mp_powm(y, n, q, p); // y = n**q mod p\n    mp_powm(b, a, q, p); // b = a**q mod p\n    t = (q + 1) / 2;\n    mp_powm(rop, a, t, p); // rop = a**((q + 1) / 2) mod p\n\n    while (b != 1) {\n        m = 0;\n        t = b;\n        while (t != 1) {\n            mp_powm(t, t, integer_class(2), p);\n            ++m; // t = t**2 = b**2**(m)\n        }\n        if (m == e)\n            return false;\n        mp_pow_ui(q, integer_class(2), e - m - 1); // q = 2**(e - m - 1)\n        mp_powm(t, y, q, p);                       // t = y**(2**(e - m - 1))\n        mp_powm(y, t, integer_class(2), p);        // y = t**2\n        e = m;\n        rop = (rop * t) % p;\n        b = (b * y) % p;\n    }\n    return true;\n}\n\nbool _sqrt_mod_prime(integer_class &rop, const integer_class &a,\n                     const integer_class &p)\n{\n    if (p == 2) {\n        rop = a % p;\n        return true;\n    }\n    int l = mp_legendre(a, p);\n    integer_class t;\n    if (l == -1) {\n        return false;\n    } else if (l == 0) {\n        rop = 0;\n    } else if (p % 4 == 3) {\n        t = (p + 1) / 4;\n        mp_powm(rop, a, t, p);\n    } else if (p % 8 == 5) {\n        t = (p - 1) / 4;\n        mp_powm(t, a, t, p);\n        if (t == 1) {\n            t = (p + 3) / 8;\n            mp_powm(rop, a, t, p);\n        } else {\n            t = (p - 5) / 8;\n            integer_class t1 = 4 * a;\n            mp_powm(t, t1, t, p);\n            rop = (2 * a * t) % p;\n        }\n    } else {\n        if (p < 10000) { // If p < 10000, brute force is faster.\n            integer_class sq = integer_class(1), _a;\n            mp_fdiv_r(_a, a, p);\n            for (unsigned i = 1; i < p; ++i) {\n                if (sq == _a) {\n                    rop = i;\n                    return true;\n                }\n                sq += 2 * i + 1;\n                mp_fdiv_r(sq, sq, p);\n            }\n            return false;\n        } else {\n            return _sqrt_mod_tonelli_shanks(rop, a, p);\n        }\n    }\n    return true;\n}\n\n// References : Menezes, Alfred J., Paul C. Van Oorschot, and Scott A. Vanstone.\n// Handbook of applied cryptography. CRC press, 2010. pages 104 - 108\n// Calculates log = x mod q**k where g**x == a mod p and order(g, p) = n.\nvoid _discrete_log(integer_class &log, const integer_class &a,\n                   const integer_class &g, const integer_class &n,\n                   const integer_class &q, const unsigned &k,\n                   const integer_class &p)\n{\n    log = 0;\n    integer_class gamma = a, alpha, _n, t, beta, qj(1), m, l;\n    _n = n / q;\n    mp_powm(alpha, g, _n, p);\n    mp_sqrtrem(m, t, q);\n    if (t != 0)\n        ++m; // m = ceiling(sqrt(q)).\n    map_integer_uint\n        table; // Table for lookup in baby-step giant-step algorithm\n    integer_class alpha_j(1), d, s;\n    s = -m;\n    mp_powm(s, alpha, s, p);\n\n    for (unsigned j = 0; j < m; ++j) {\n        insert(table, integer(alpha_j), j);\n        alpha_j = (alpha_j * alpha) % p;\n    }\n\n    for (unsigned long j = 0; j < k; ++j) { // Pohlig-Hellman\n        mp_powm(beta, gamma, _n, p);\n        // Baby-step giant-step algorithm for l = log_alpha(beta)\n        d = beta;\n        bool found = false;\n        for (unsigned i = 0; not found && i < m; ++i) {\n            if (table.find(integer(d)) != table.end()) {\n                l = i * m + table[integer(d)];\n                found = true;\n                break;\n            }\n            d = (d * s) % p;\n        }\n        _n /= q;\n        t = -l * qj;\n\n        log -= t;\n        mp_powm(t, g, t, p);\n        gamma *= t; // gamma *= g ** (-l * (q ** j))\n        qj *= q;\n    }\n}\n\n// References : Johnston A., A generalised qth root algorithm.\n// Solution for x**n == a mod p**k where a != 0 mod p and p is an odd prime.\nbool _nthroot_mod1(std::vector<RCP<const Integer>> &roots,\n                   const integer_class &a, const integer_class &n,\n                   const integer_class &p, const unsigned k,\n                   bool all_roots = false)\n{\n    integer_class _n, r, root, s, t, g(0), pk, m, phi;\n    mp_pow_ui(pk, p, k);\n    phi = pk * (p - 1) / p;\n    mp_gcd(m, phi, n);\n    t = phi / m;\n    mp_powm(t, a, t, pk);\n    // Check whether a**(phi / gcd(phi, n)) == 1 mod p**k.\n    if (t != 1) {\n        return false;\n    }\n    // Solve x**n == a mod p first.\n    t = p - 1;\n    mp_gcdext(_n, r, s, n, t);\n    if (r < 0) {\n        mp_fdiv_r(r, r, t / _n);\n    }\n    mp_powm(s, a, r, p);\n\n    // Solve x**(_n) == s mod p where _n | p - 1.\n    if (_n == 1) {\n        root = s;\n    } else if (_n == 2) {\n        _sqrt_mod_prime(root, s, p);\n    } else { // Ref[1]\n        map_integer_uint prime_mul;\n        prime_factor_multiplicities(prime_mul, *integer(_n));\n        integer_class h, q, qt, z, v, x, s1 = s;\n        _primitive_root(g, p, integer_class(2));\n        unsigned c;\n        for (const auto &it : prime_mul) {\n            q = it.first->as_integer_class();\n            mp_pow_ui(qt, q, it.second);\n            h = (p - 1) / q;\n            c = 1;\n            while (h % q == 0) {\n                ++c;\n                h /= q;\n            }\n            mp_invert(t, h, qt);\n            z = t * -h;\n            x = (1 + z) / qt;\n            mp_powm(v, s1, x, p);\n\n            if (c == it.second) {\n                s1 = v;\n            } else {\n                mp_powm(x, s1, h, p);\n                t = h * qt;\n                mp_powm(r, g, t, p);\n                mp_pow_ui(qt, q, c - it.second);\n                _discrete_log(t, x, r, qt, q, c - it.second, p);\n                t = -z * t;\n                mp_powm(r, g, t, p);\n                v *= r;\n                mp_fdiv_r(v, v, p);\n                s1 = v;\n            }\n        }\n        root = s1;\n    }\n    r = n;\n    unsigned c = 0;\n    while (r % p == 0) {\n        mp_divexact(r, r, p);\n        ++c;\n    }\n\n    // Solve s == x**r mod p**k where (x**r)**(p**c)) == a mod p**k\n    integer_class pc = n / r, pd = pc * p;\n    if (c >= 1) {\n        mp_powm(s, root, r, p);\n        // s == root**r mod p. Since s**(p**c) == 1 == a mod p**(c + 1), lift\n        // until p**k.\n        for (unsigned d = c + 2; d <= k; ++d) {\n            t = 1 - pc;\n            pd *= p;\n            mp_powm(t, s, t, pd);\n            t = (a * t - s) / pc;\n            s += t;\n        }\n    } else {\n        s = a;\n    }\n\n    // Solve x**r == s mod p**k given that root**r == s mod p and r % p != 0.\n    integer_class u;\n    pd = p;\n    for (unsigned d = 2; d < 2 * k; d *= 2) { // Hensel lifting\n        t = r - 1;\n        pd *= pd;\n        if (d > k)\n            pd = pk;\n        mp_powm(u, root, t, pd);\n        t = r * u;\n        mp_invert(t, t, pd);\n        root += (s - u * root) * t;\n        mp_fdiv_r(root, root, pd);\n    }\n    if (m != 1 and all_roots) {\n        // All roots are generated by root*(g**(phi / gcd(phi , n)))**j\n        if (n == 2) {\n            t = -1;\n        } else {\n            if (g == 0)\n                _primitive_root(g, p, integer_class(2));\n            t = phi / m;\n            mp_powm(t, g, t, pk);\n        }\n        for (unsigned j = 0; j < m; ++j) {\n            roots.push_back(integer(root));\n            root *= t;\n            mp_fdiv_r(root, root, pk);\n        }\n    } else {\n        roots.push_back(integer(root));\n    }\n    return true;\n}\n\n// Checks if Solution for x**n == a mod p**k exists where a != 0 mod p and p is\n// an odd prime.\nbool _is_nthroot_mod1(const integer_class &a, const integer_class &n,\n                      const integer_class &p, const unsigned k)\n{\n    integer_class t, pk, m, phi;\n    mp_pow_ui(pk, p, k);\n    phi = pk * (p - 1) / p;\n    mp_gcd(m, phi, n);\n    t = phi / m;\n    mp_powm(t, a, t, pk);\n    // Check whether a**(phi / gcd(phi, n)) == 1 mod p**k.\n    if (t != 1) {\n        return false;\n    }\n    return true;\n}\n\n// Solution for x**n == a mod p**k.\nbool _nthroot_mod_prime_power(std::vector<RCP<const Integer>> &roots,\n                              const integer_class &a, const integer_class &n,\n                              const integer_class &p, const unsigned k,\n                              bool all_roots = false)\n{\n    integer_class pk, root;\n    std::vector<RCP<const Integer>> _roots;\n    if (a % p != 0) {\n        if (p == 2) {\n            integer_class r = n, t, s, pc, pj;\n            pk = integer_class(1) << k;\n            unsigned c = numeric_cast<unsigned>(mp_scan1(n));\n            r = n >> c; // n = 2**c * r where r is odd.\n\n            // Handle special cases of k = 1 and k = 2.\n            if (k == 1) {\n                roots.push_back(integer(1));\n                return true;\n            }\n            if (k == 2) {\n                if (c > 0 and a % 4 == 3) {\n                    return false;\n                }\n                roots.push_back(integer(a % 4));\n                if (all_roots and c > 0)\n                    roots.push_back(integer(3));\n                return true;\n            }\n            if (c >= k - 2) {\n                c = k - 2; // Since x**(2**c) == x**(2**(k - 2)) mod 2**k, let c\n                           // = k - 2.\n            }\n            t = integer_class(1) << (k - 2);\n            pc = integer_class(1) << c;\n\n            mp_invert(s, r, t);\n            if (c == 0) {\n                // x**r == a mod 2**k and x**2**(k - 2) == 1 mod 2**k, implies\n                // x**(r * s) == x == a**s mod 2**k.\n                mp_powm(root, a, s, pk);\n                roots.push_back(integer(root));\n                return true;\n            }\n\n            // First, solve for y**2**c == a mod 2**k where y == x**r\n            t = integer_class(1) << (c + 2);\n            mp_fdiv_r(t, a, t);\n            // Check for a == y**2**c == 1 mod 2**(c + 2).\n            if (t != 1)\n                return false;\n            root = 1;\n            pj = pc * 4;\n            // 1 is a root of x**2**c == 1 mod 2**(c + 2). Lift till 2**k.\n            for (unsigned j = c + 2; j < k; ++j) {\n                pj *= 2;\n                mp_powm(t, root, pc, pj);\n                t -= a;\n                if (t % pj != 0)\n                    // Add 2**(j - c).\n                    root += integer_class(1) << (j - c);\n            }\n            // Solve x**r == root mod 2**k.\n            mp_powm(root, root, s, pk);\n\n            if (all_roots) {\n                // All roots are generated by, root * (j * (2**(k - c) +/- 1)).\n                t = pk / pc * root;\n                for (unsigned i = 0; i < 2; ++i) {\n                    for (unsigned long j = 0; j < pc; ++j) {\n                        roots.push_back(integer(root));\n                        root += t;\n                    }\n                    root = t - root;\n                }\n            } else {\n                roots.push_back(integer(root));\n            }\n            return true;\n        } else {\n            return _nthroot_mod1(roots, a, n, p, k, all_roots);\n        }\n    } else {\n        integer_class _a;\n        mp_pow_ui(pk, p, k);\n        _a = a % pk;\n        unsigned m;\n        integer_class pm;\n        if (_a == 0) {\n            if (not all_roots) {\n                roots.push_back(integer(0));\n                return true;\n            }\n            _roots.push_back(integer(0));\n            if (n >= k)\n                m = k - 1;\n            else\n                m = numeric_cast<unsigned>(k - 1 - (k - 1) / mp_get_ui(n));\n            mp_pow_ui(pm, p, m);\n        } else {\n            unsigned r = 1;\n            mp_divexact(_a, _a, p);\n            while (_a % p == 0) {\n                mp_divexact(_a, _a, p);\n                ++r;\n            }\n            if (r < n or r % n != 0\n                or not _nthroot_mod_prime_power(_roots, _a, n, p, k - r,\n                                                all_roots)) {\n                return false;\n            }\n            m = numeric_cast<unsigned>(r / mp_get_ui(n));\n            mp_pow_ui(pm, p, m);\n            if (not all_roots) {\n                roots.push_back(\n                    integer(_roots.back()->as_integer_class() * pm));\n                return true;\n            }\n            for (auto &it : _roots) {\n                it = integer(it->as_integer_class() * pm);\n            }\n            m = numeric_cast<unsigned>(r - r / mp_get_ui(n));\n            mp_pow_ui(pm, p, m);\n        }\n        integer_class pkm;\n        mp_pow_ui(pkm, p, k - m);\n\n        for (const auto &it : _roots) {\n            root = it->as_integer_class();\n            for (unsigned long i = 0; i < pm; ++i) {\n                roots.push_back(integer(root));\n                root += pkm;\n            }\n        }\n    }\n    return true;\n}\n} // anonymous namespace\n\n// Returns whether Solution for x**n == a mod p**k exists or not\nbool _is_nthroot_mod_prime_power(const integer_class &a, const integer_class &n,\n                                 const integer_class &p, const unsigned k)\n{\n    integer_class pk;\n    if (a % p != 0) {\n        if (p == 2) {\n            integer_class t;\n            unsigned c = numeric_cast<unsigned>(mp_scan1(n));\n\n            // Handle special cases of k = 1 and k = 2.\n            if (k == 1) {\n                return true;\n            }\n            if (k == 2) {\n                if (c > 0 and a % 4 == 3) {\n                    return false;\n                }\n                return true;\n            }\n            if (c >= k - 2) {\n                c = k - 2; // Since x**(2**c) == x**(2**(k - 2)) mod 2**k, let c\n                           // = k - 2.\n            }\n            if (c == 0) {\n                // x**r == a mod 2**k and x**2**(k - 2) == 1 mod 2**k, implies\n                // x**(r * s) == x == a**s mod 2**k.\n                return true;\n            }\n\n            // First, solve for y**2**c == a mod 2**k where y == x**r\n            t = integer_class(1) << (c + 2);\n            mp_fdiv_r(t, a, t);\n            // Check for a == y**2**c == 1 mod 2**(c + 2).\n            if (t != 1)\n                return false;\n            return true;\n        } else {\n            return _is_nthroot_mod1(a, n, p, k);\n        }\n    } else {\n        integer_class _a;\n        mp_pow_ui(pk, p, k);\n        _a = a % pk;\n        integer_class pm;\n        if (_a == 0) {\n            return true;\n        } else {\n            unsigned r = 1;\n            mp_divexact(_a, _a, p);\n            while (_a % p == 0) {\n                mp_divexact(_a, _a, p);\n                ++r;\n            }\n            if (r < n or r % n != 0\n                or not _is_nthroot_mod_prime_power(_a, n, p, k - r)) {\n                return false;\n            }\n            return true;\n        }\n    }\n    return true;\n}\n\nbool nthroot_mod(const Ptr<RCP<const Integer>> &root,\n                 const RCP<const Integer> &a, const RCP<const Integer> &n,\n                 const RCP<const Integer> &mod)\n{\n    if (mod->as_integer_class() <= 0) {\n        return false;\n    } else if (mod->as_integer_class() == 1) {\n        *root = integer(0);\n        return true;\n    }\n    map_integer_uint prime_mul;\n    prime_factor_multiplicities(prime_mul, *mod);\n    std::vector<RCP<const Integer>> moduli;\n    bool ret_val;\n\n    std::vector<RCP<const Integer>> rem;\n    for (const auto &it : prime_mul) {\n        integer_class _mod;\n        mp_pow_ui(_mod, it.first->as_integer_class(), it.second);\n        moduli.push_back(integer(std::move(_mod)));\n        ret_val = _nthroot_mod_prime_power(\n            rem, a->as_integer_class(), n->as_integer_class(),\n            it.first->as_integer_class(), it.second, false);\n        if (not ret_val)\n            return false;\n    }\n    crt(root, rem, moduli);\n    return true;\n}\n\nvoid nthroot_mod_list(std::vector<RCP<const Integer>> &roots,\n                      const RCP<const Integer> &a, const RCP<const Integer> &n,\n                      const RCP<const Integer> &m)\n{\n    if (m->as_integer_class() <= 0) {\n        return;\n    } else if (m->as_integer_class() == 1) {\n        roots.push_back(integer(0));\n        return;\n    }\n    map_integer_uint prime_mul;\n    prime_factor_multiplicities(prime_mul, *m);\n    std::vector<RCP<const Integer>> moduli;\n    bool ret_val;\n\n    std::vector<std::vector<RCP<const Integer>>> rem;\n    for (const auto &it : prime_mul) {\n        integer_class _mod;\n        mp_pow_ui(_mod, it.first->as_integer_class(), it.second);\n        moduli.push_back(integer(std::move(_mod)));\n        std::vector<RCP<const Integer>> rem1;\n        ret_val = _nthroot_mod_prime_power(\n            rem1, a->as_integer_class(), n->as_integer_class(),\n            it.first->as_integer_class(), it.second, true);\n        if (not ret_val)\n            return;\n        rem.push_back(rem1);\n    }\n    _crt_cartesian(roots, rem, moduli);\n    std::sort(roots.begin(), roots.end(), SymEngine::RCPIntegerKeyLess());\n}\n\nbool powermod(const Ptr<RCP<const Integer>> &powm, const RCP<const Integer> &a,\n              const RCP<const Number> &b, const RCP<const Integer> &m)\n{\n    if (is_a<Integer>(*b)) {\n        integer_class t = down_cast<const Integer &>(*b).as_integer_class();\n        if (b->is_negative())\n            t *= -1;\n        mp_powm(t, a->as_integer_class(), t, m->as_integer_class());\n        if (b->is_negative()) {\n            bool ret_val = mp_invert(t, t, m->as_integer_class());\n            if (not ret_val)\n                return false;\n        }\n        *powm = integer(std::move(t));\n        return true;\n    } else if (is_a<Rational>(*b)) {\n        RCP<const Integer> num, den, r;\n        get_num_den(down_cast<const Rational &>(*b), outArg(num), outArg(den));\n        if (den->is_negative()) {\n            den = den->mulint(*minus_one);\n            num = num->mulint(*minus_one);\n        }\n        integer_class t = mp_abs(num->as_integer_class());\n        mp_powm(t, a->as_integer_class(), t, m->as_integer_class());\n        if (num->is_negative()) {\n            bool ret_val = mp_invert(t, t, m->as_integer_class());\n            if (not ret_val)\n                return false;\n        }\n        r = integer(std::move(t));\n        return nthroot_mod(powm, r, den, m);\n    }\n    return false;\n}\n\nvoid powermod_list(std::vector<RCP<const Integer>> &pows,\n                   const RCP<const Integer> &a, const RCP<const Number> &b,\n                   const RCP<const Integer> &m)\n{\n    if (is_a<Integer>(*b)) {\n        integer_class t\n            = mp_abs(down_cast<const Integer &>(*b).as_integer_class());\n        mp_powm(t, a->as_integer_class(), t, m->as_integer_class());\n        if (b->is_negative()) {\n            bool ret_val = mp_invert(t, t, m->as_integer_class());\n            if (not ret_val)\n                return;\n        }\n        pows.push_back(integer(std::move(t)));\n    } else if (is_a<Rational>(*b)) {\n        RCP<const Integer> num, den, r;\n        get_num_den(down_cast<const Rational &>(*b), outArg(num), outArg(den));\n        if (den->is_negative()) {\n            den = den->mulint(*integer(-1));\n            num = num->mulint(*integer(-1));\n        }\n        integer_class t = num->as_integer_class();\n        if (num->is_negative())\n            t *= -1;\n        mp_powm(t, a->as_integer_class(), t, m->as_integer_class());\n        if (num->is_negative()) {\n            bool ret_val = mp_invert(t, t, m->as_integer_class());\n            if (not ret_val)\n                return;\n        }\n        r = integer(t);\n        nthroot_mod_list(pows, r, den, m);\n    }\n}\n\nvec_integer_class quadratic_residues(const Integer &a)\n{\n    /*\n        Returns the list of quadratic residues.\n        Example\n        ========\n        >>> quadratic_residues(7)\n        [0, 1, 2, 4]\n    */\n\n    if (a.as_integer_class() < 1) {\n        throw SymEngineException(\"quadratic_residues: Input must be > 0\");\n    }\n\n    vec_integer_class residue;\n    for (integer_class i = integer_class(0); i <= a.as_int() / 2; i++) {\n        residue.push_back((i * i) % a.as_int());\n    }\n\n    sort(residue.begin(), residue.end());\n    residue.erase(unique(residue.begin(), residue.end()), residue.end());\n\n    return residue;\n}\n\nbool is_quad_residue(const Integer &a, const Integer &p)\n{\n    /*\n    Returns true if ``a`` (mod ``p``) is in the set of squares mod ``p``,\n    i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd but\n    not prime, an iterative method is used to make the determination.\n    */\n\n    integer_class p2 = p.as_integer_class();\n    if (p2 == 0)\n        throw SymEngineException(\n            \"is_quad_residue: Second parameter must be non-zero\");\n    if (p2 < 0)\n        p2 = -p2;\n    integer_class a_final = a.as_integer_class();\n    if (a.as_integer_class() >= p2 || a.as_integer_class() < 0)\n        mp_fdiv_r(a_final, a.as_integer_class(), p2);\n    if (a_final < 2)\n        return true;\n\n    if (!probab_prime_p(*integer(p2))) {\n        if ((p2 % 2 == 1) && jacobi(*integer(a_final), p) == -1)\n            return false;\n\n        const RCP<const Integer> a1 = integer(a_final);\n        const RCP<const Integer> p1 = integer(p2);\n\n        map_integer_uint prime_mul;\n        prime_factor_multiplicities(prime_mul, *p1);\n        bool ret_val;\n\n        for (const auto &it : prime_mul) {\n            ret_val = _is_nthroot_mod_prime_power(\n                a1->as_integer_class(), integer(2)->as_integer_class(),\n                it.first->as_integer_class(), it.second);\n            if (not ret_val)\n                return false;\n        }\n        return true;\n    }\n\n    return mp_legendre(a_final, p2) == 1;\n}\n\nbool is_nth_residue(const Integer &a, const Integer &n, const Integer &mod)\n/*\nReturns true if ``a`` (mod ``mod``) is in the set of nth powers mod ``mod``,\ni.e a % mod in set([i**n % mod for i in range(mod)]).\n*/\n{\n    integer_class _mod = mod.as_integer_class();\n\n    if (_mod == 0) {\n        return false;\n    } else if (_mod == 1) {\n        return true;\n    }\n\n    if (_mod < 0)\n        _mod = -(_mod);\n\n    RCP<const Integer> mod2 = integer(_mod);\n    map_integer_uint prime_mul;\n    prime_factor_multiplicities(prime_mul, *mod2);\n    bool ret_val;\n\n    for (const auto &it : prime_mul) {\n        ret_val = _is_nthroot_mod_prime_power(\n            a.as_integer_class(), n.as_integer_class(),\n            it.first->as_integer_class(), it.second);\n        if (not ret_val)\n            return false;\n    }\n    return true;\n}\n\nint mobius(const Integer &a)\n{\n    if (a.as_int() <= 0) {\n        throw SymEngineException(\"mobius: Integer <= 0\");\n    }\n    map_integer_uint prime_mul;\n    bool is_square_free = true;\n    prime_factor_multiplicities(prime_mul, a);\n    auto num_prime_factors = prime_mul.size();\n    for (const auto &it : prime_mul) {\n        int p_freq = it.second;\n        if (p_freq > 1) {\n            is_square_free = false;\n            break;\n        }\n    }\n    if (!is_square_free) {\n        return 0;\n    } else if (num_prime_factors % 2 == 0) {\n        return 1;\n    } else {\n        return -1;\n    }\n}\n\nlong mertens(const unsigned long a)\n{\n    long mertens = 0;\n    for (unsigned long i = 1; i <= a; ++i) {\n        mertens += mobius(*(integer(i)));\n    }\n    return mertens;\n}\n\n/**\n * @brief Numeric calculation of the n:th s-gonal number\n * @param s Number of sides of the polygon. Must be greater than 2.\n * @param n Must be greater than 0\n * @returns The n:th s-gonal number\n *\n * A fast pure numeric calculation of the n:th s-gonal number. No bounds\n * checking of the input is performed.\n * See https://en.wikipedia.org/wiki/Polygonal_number for source of formula.\n */\ninteger_class mp_polygonal_number(const integer_class &s,\n                                  const integer_class &n)\n{\n    auto res = ((s - 2) * n * n - (s - 4) * n) / 2;\n    return res;\n}\n\n/**\n * @brief Numeric calculation of the principal s-gonal root of x\n * @param s Number of sides of the polygon. Must be greater than 2.\n * @param x An integer greater than 0\n * @returns The root\n *\n * A fast pure numeric calculation of the principal (i.e. positive) s-gonal root\n * of x. No bounds checking of the input is performed.\n * See https://en.wikipedia.org/wiki/Polygonal_number for source of formula.\n */\ninteger_class mp_principal_polygonal_root(const integer_class &s,\n                                          const integer_class &x)\n{\n    integer_class tmp;\n    mp_pow_ui(tmp, s - 4, 2);\n    integer_class root = mp_sqrt(8 * x * (s - 2) + tmp);\n    integer_class n = (root + s - 4) / (2 * (s - 2));\n    return n;\n}\n\nstd::pair<integer_class, integer_class>\nmp_perfect_power_decomposition(const integer_class &n, bool lowest_exponent)\n{\n    // From\n    // https://codegolf.stackexchange.com/questions/1935/fastest-algorithm-for-decomposing-a-perfect-power\n    unsigned long p = 2;\n    integer_class intone, i, j, m, res;\n    intone = 1;\n    std::pair<integer_class, integer_class> respair;\n    respair = std::make_pair(n, intone);\n\n    while ((intone << p) <= n) {\n        i = 2;\n        j = n;\n        while (j > i + 1) {\n            m = (i + j) / 2;\n            mp_pow_ui(res, m, p);\n            if (res > n)\n                j = m;\n            else\n                i = m;\n        }\n        mp_pow_ui(res, i, p);\n        if (res == n) {\n            respair = std::make_pair(i, p);\n            if (lowest_exponent) {\n                return respair;\n            }\n        }\n        p++;\n    }\n    return respair;\n}\n\n} // namespace SymEngine\n", "meta": {"hexsha": "6108bf2c94ede311fe76b81fbb91b3f86ec0b79d", "size": 49634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "symengine/ntheory.cpp", "max_stars_repo_name": "stjordanis/symengine", "max_stars_repo_head_hexsha": "8be879dd6b4586ea2be94712d8e9edf37c0f2c0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "symengine/ntheory.cpp", "max_issues_repo_name": "stjordanis/symengine", "max_issues_repo_head_hexsha": "8be879dd6b4586ea2be94712d8e9edf37c0f2c0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "symengine/ntheory.cpp", "max_forks_repo_name": "stjordanis/symengine", "max_forks_repo_head_hexsha": "8be879dd6b4586ea2be94712d8e9edf37c0f2c0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0257309942, "max_line_length": 106, "alphanum_fraction": 0.5036869888, "num_tokens": 14092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.4382968778108119}}
{"text": "// Deal.ii\n#include <deal.II/base/tensor_function.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.h>\n\n// STL\n#include <iostream>\n#include <fstream>\n#include <cmath>\n\n\n//#include \"reconstruction_mesh.hpp\"\n\n#include <deal.II/base/logstream.h>\n\nusing namespace dealii;\n\n\ntemplate <int dim> class AdvectionField : public TensorFunction<1, dim> {\npublic:\n  AdvectionField() : TensorFunction<1, dim>() {}\n\n  virtual Tensor<1, dim> value(const Point<dim> &point) const override;\n  virtual void value_list(const std::vector<Point<dim>> &points,\n                          std::vector<Tensor<1, dim>> &values) const override;\n\nprivate:\n  const double pi = numbers::PI;\n};\n\ntemplate <int dim>\nTensor<1, dim> AdvectionField<dim>::value(const Point<dim> &p) const\n{\n  const double t = this->get_time();\n\n  Tensor<1, dim> value;\n  value.clear();\n\n  double t0 = 0;\n\n    const double tn = 1;\n\n    const double n=10;\n\n    const double dt = (tn-t0)/n;\n\n    const double c=3;\n\n  // Here velocity is consider to be constant let it be 1 m/s.\n\n  for (unsigned int d = 0; d < dim; ++d)\n\n    {\n\n\n      value[d] =0.8 * std::sin( 3.14* p[1]);\n\n     // value[d] =1; //0.8 * std::sin( numbers::PI * p[1]);\n\n    }\n\n  return value;\n}\n\ntemplate <int dim>\nvoid AdvectionField<dim>::value_list(\n    const std::vector<Point<dim>> &points,\n    std::vector<Tensor<1, dim>> &values) const {\n  Assert(points.size() == values.size(),\n         ExcDimensionMismatch(points.size(), values.size()));\n\n  for (unsigned int p = 0; p < points.size(); ++p) {\n    values[p].clear();\n    values[p] = value(points[p]);\n  }\n}\n\n///////////////////////////////////////////////////////////////\n\ntemplate <int dim> class RK4 : public Tensor<1, dim> {\npublic:\n  RK4() : Tensor<1, dim>() {}\n  virtual Tensor<1, dim> value(const Point<dim> &p) const;\n\nprivate:\n  AdvectionField<dim> advection_field;\n};\n\ntemplate <int dim> Tensor<1, dim> RK4<dim>::value(const Point<dim> &p) const {\n\n  Tensor<1, dim> yn;\n\n  double t0 = 0;\n\n  const double tn = 1;\n\n  const double n=10;\n\n  const double dt = (tn-t0)/n;\n\n  /* Here the equation is dy/dt =c; where c is velocity y is the vertex of mesh and t is the time\n   *\n   */\n\n  yn = advection_field.value(p);\n\n  for (double t0 = 0; t0 <= tn; t0++) {\n    auto k1 = dt * advection_field.value(p),\n         k2 = dt * (advection_field.value(p) + k1 / 2),\n         k3 = dt * (advection_field.value(p) + k2 / 2),\n         k4 = dt * (advection_field.value(p) + k3);\n    return yn += (1 / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4);\n    t0 = t0 + dt;\n  }\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////\n\ntemplate <int dim> class MeshDeformer {\npublic:\n  MeshDeformer();\n\n  void run();\n\nprivate:\n  void make_grid();\n\n  Triangulation<dim> triangulation;\n\n  GridOut grid_out;\n  AdvectionField<dim> advection_field;\n  Vector<double> solution;\n  RK4<dim> rk4;\n\n  double time;\n  double time_step;\n  /*!\n   * Final simulation time.\n   */\n  double T_max;\n};\n\ntemplate <int dim>\nMeshDeformer<dim>::MeshDeformer()\n    : triangulation(), time(1.0), time_step(1), T_max(1.0) {}\n\ntemplate <int dim> void MeshDeformer<dim>::make_grid()\n{\n  GridGenerator::hyper_cube(triangulation, 0, 1, /* colorize faces */\n                            false);\n  triangulation.refine_global(4);\n\n  std::vector<Tensor<1, dim>> vetices_on_cell;\n   \t\t while (T_max>=0.09) {\n  for (const auto &cell : triangulation.active_cell_iterators()) {\n\n    for (unsigned int i = 0; i < GeometryInfo<dim>::vertices_per_cell; i++) {\n      Point<2> &v = cell->vertex(i); // initial vertex\n\n      rk4.value(v);\n\n      std::cout << \"----------------------------------\" << std::endl;\n\n      std::cout << rk4.value(v) << \"  rk4    \" << std::endl;\n      std::cout << \"----------------------------------\" << std::endl;\n\n      GridOut       grid_out;\n       \t\t\t\t\t\t\t\t\t\t\tstd::ofstream output(\"mesh-\" + std::to_string(T_max) + \".vtu\");\n       \t\t\t\t\t\t\t\t\t\t\tgrid_out.write_vtu( triangulation, output);\n       \t\t\t\t\t\t\t\t\t\t T_max=T_max-time_step;\n    }\n  }\n  }\n\n}\n\ntemplate <int dim> void MeshDeformer<dim>::run()\n{\n\tmake_grid();\n}\n\nint main()\n{\n\n  MeshDeformer<2> rk4_problem_2d;\n  rk4_problem_2d.run();\n\n  return 0;\n}\n", "meta": {"hexsha": "f2798ed9b73cdc0ac08190a0bdcdb3cc9078928e", "size": 4225, "ext": "cc", "lang": "C++", "max_stars_repo_path": "runge_kutta.cc", "max_stars_repo_name": "heena008/Runge_Kutta_fourth_order", "max_stars_repo_head_hexsha": "fc685c491b5fbf554046b89b95ff2f67073e12a8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "runge_kutta.cc", "max_issues_repo_name": "heena008/Runge_Kutta_fourth_order", "max_issues_repo_head_hexsha": "fc685c491b5fbf554046b89b95ff2f67073e12a8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "runge_kutta.cc", "max_forks_repo_name": "heena008/Runge_Kutta_fourth_order", "max_forks_repo_head_hexsha": "fc685c491b5fbf554046b89b95ff2f67073e12a8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1204188482, "max_line_length": 97, "alphanum_fraction": 0.5760946746, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430353105599, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4382754558111052}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2014 by Synge Todo <wistaria@comp-phys.org>\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n// C++ version of TITPACK Ver.2 by H. Nishimori\n\n/************ Sample main program #11 *****************\n* 1d Heisenberg antiferromagnet with 8 spins\n* Eigenvalues and an eigenvector by diag\n******************************************************/\n\n#include <mpi.h>\n#include <iostream>\n#include <rokko/rokko.hpp>\n#include <boost/timer.hpp>\n#include \"titpack.hpp\"\n#include \"options.hpp\"\n\ntypedef rokko::parallel_dense_solver solver_type;\ntypedef rokko::distributed_matrix<rokko::matrix_col_major> matrix_type;\n\nint main(int argc, char** argv) {\n  int provided;\n  MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);\n  rokko::grid g;\n\n  std::cout.precision(10);\n  options opt(argc, argv, 8, solver_type::default_solver(), g.get_myrank() == 0);\n  if (!opt.valid) MPI_Abort(MPI_COMM_WORLD, 1);\n  boost::timer tm;\n  MPI_Barrier(g.get_comm());\n  double t1 = tm.elapsed();\n\n  // lattice structure\n  int n = opt.N;\n  int ibond = n;\n  std::vector<int> ipair;\n  for (int i = 0; i < ibond; ++i) {\n    ipair.push_back(i);\n    ipair.push_back((i + 1) % n);\n  }\n\n  // Hamiltonian parameters\n  std::vector<double> bondwt(ibond, -1);\n  std::vector<double> zrtio(ibond, 1);\n\n  // table of configurations and Hamiltonian operator\n  subspace ss(n, 0);\n  hamiltonian hop(ss, ipair, bondwt, zrtio);\n  solver_type solver(opt.solver);\n  solver.initialize(argc, argv);\n\n  // Hamiltonian matrix\n  matrix_type elemnt(hop.dimension(), hop.dimension(), g, solver);\n  elm3(hop, elemnt);\n  MPI_Barrier(g.get_comm());\n  double t2 = tm.elapsed();\n  \n  rokko::localized_vector E(hop.dimension());\n  matrix_type v(hop.dimension(), hop.dimension(), g, solver);\n  solver.diagonalize(elemnt, E, v);\n  double t3 = tm.elapsed();\n\n  if (g.get_myrank() == 0) {\n    int ne = 4;\n    std::cout << \"[Eigenvalues]\\n\";\n    for (int i = 0; i < ne; ++i) std::cout << '\\t' << E[i];\n    std::cout << std::endl << std::flush;\n  }\n  MPI_Barrier(g.get_comm());\n\n  // Do not forget to call elm3 again before calling check3\n  elm3(hop, elemnt);\n  matrix_type w(hop.dimension(), 1, g, solver);\n  check3_mpi(elemnt, v, 0, w);\n  std::cout << std::flush;\n  MPI_Barrier(g.get_comm());\n  double t4 = tm.elapsed();\n  \n  std::vector<int> npair;\n  npair.push_back(1);\n  npair.push_back(2);\n  std::vector<double> sxx(1);\n  matrix_type sxmat(hop.dimension(), hop.dimension(), g, solver);\n  xcorr3_mpi(ss, npair, v, 0, sxx, sxmat, w);\n  if (v.is_gindex(0, 0)) std::cout << \"sxx: \" << sxx[0] << std::endl;\n  std::cout << std::flush;\n  MPI_Barrier(g.get_comm());\n  std::vector<double> szz(1);\n  zcorr_mpi(ss, npair, v, 0, szz);\n  if (g.get_myrank() == 0) std::cout << \"szz: \" << szz[0] << std::endl;\n  std::cout << std::flush;\n  MPI_Barrier(g.get_comm());\n  double t5 = tm.elapsed();\n\n  if (g.get_myrank() == 0) {\n    std::cerr << \"initialize      \" << (t2-t1) << \" sec\\n\"\n              << \"diagonalization \" << (t3-t2) << \" sec\\n\"\n              << \"check           \" << (t4-t3) << \" sec\\n\"\n              << \"correlation     \" << (t5-t4) << \" sec\\n\";\n  }\n  MPI_Finalize();\n}\n", "meta": {"hexsha": "da0017a4793128a82c330a4be602ec517c485d6d", "size": 3464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tutorial/titpack/03_rokko_cxx/sample-11_mpi.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorial/titpack/03_rokko_cxx/sample-11_mpi.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial/titpack/03_rokko_cxx/sample-11_mpi.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2072072072, "max_line_length": 81, "alphanum_fraction": 0.5920900693, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.43826241827717877}}
{"text": "#ifndef BIGGLES_PARTITION_SAMPLER_HPP__\n#define BIGGLES_PARTITION_SAMPLER_HPP__\n\n#include <boost/tuple/tuple.hpp>\n\n#include \"model.hpp\"\n#include \"partition.hpp\"\n#include \"mh_moves/mh_moves.hpp\"\n#include \"sampling/metropolis_hastings.hpp\"\n#include \"sampling/simple.hpp\"\n\nnamespace biggles {\n\n/// @brief A class which can sample a set of tracks and clutter given a set of model parameters.\n///\n/// Internally this class is implemented via the Metropolis-Hastings algorithm. See the documentation for sample() for\n/// more information.\n///\n/// This samples from the posterior distribution \\f$ P(T | \\theta, D) \\f$ where \\f$ T \\f$ is a set of tracks and\n/// clutter which encompass all observations, \\f$ \\theta \\f$ is a set of model parameters and \\f$ D \\f$ are the\n/// observations.\n///\n/// We can re-arrange this posterior using the law of conditional probability which states \\f$ P(T | \\theta, D) =\n/// P(T, \\theta | D) / P(\\theta | D) \\f$ combined with Bayes' theorem:\n///\n/// \\f[\n/// P(T, \\theta | D)\n///     = \\frac{P(D|T, \\theta) P(T, \\theta)}{P(D)}\n///     = \\frac{P(D|T, \\theta) P(T | \\theta) P(\\theta)}{P(D)}\n/// \\f]\n///\n/// and hence\n///\n/// \\f[\n/// P(T | \\theta, D)\n///     = \\frac{P(D|T, \\theta) P(T | \\theta) P(\\theta)}{P(\\theta | D)P(D)}\n///     = \\frac{P(D|T, \\theta) P(T | \\theta) P(\\theta)}{P(\\theta, D)}.\n/// \\f]\n///\n/// Internally we use the Metropolis-Hastings algorithm which requires only a value proportional to this density.\n/// Removing terms independent of \\f$ T \\f$ we obtain:\n///\n/// \\f[\n/// P(T | \\theta, D) \\propto P(D|T, \\theta) P(T | \\theta) P(\\theta).\n/// \\f]\n///\n/// The \\f$ P(\\theta) \\f$ term is simply the prior on the model parameters. The \\f$ P(T | \\theta) \\f$ term is a\n/// little more subtle; it is the likelihood of the tracks independent of the observations within them. This is\n/// a function of the model parameters and birth and death times for the tracks only. Since the data is partitioned\n/// between tracks and the clutter with no overlap, we may factorise the data likelihood term as follows:\n///\n/// \\f[\n/// P(D | T, \\theta) = P(d_0 | \\theta) \\prod_{i = 1}^K P(d_i | t_i, \\theta)\n/// \\f]\n///\n/// where \\f$ d_0 \\f$ is used to represent the clutter observations and \\f$ d_1, ..., d_K \\f$ are the \\f$ K \\f$\n/// sets of observations corresponding to the \\f$ K \\f$ tracks in the partition. \\f$ P(d_0 | \\theta) \\f$ is the\n/// likelihood of having seen the clutter observations we have given the parameters. \\f$ P(d_i | t_i, \\theta) \\f$ is\n/// the likelihood of track \\f$ i \\f$ having generated the data we saw.\n///\n/// Taking logarithms, we obtain the final log density function used within the Metropolis-Hastings sampler:\n///\n/// \\f[\n/// \\ell(T | \\theta, D) = \\kappa + \\ell(d_0 | t_0, \\theta) + \\sum_{i = 1}^K \\ell(d_i | t_i, \\theta) + \\ell(T | \\theta) + \\ell(\\theta)\n/// \\f]\n///\n/// where \\f$ \\ell(\\cdot) \\f$ is used to denote the log-PDF and \\f$ \\kappa \\f$ is some arbitrary normalising offset.\n/// Without loss of generality, we set it to zero.\n///\n/// Each log-PDF term in the expansion above is calculated by one of the log-PDF functions in biggles/model.hpp.\nclass partition_sampler : public sampling::metropolis_hastings_sampler\n{\nprivate:\n    typedef sampling::metropolis_hastings_sampler base_type;\npublic:\n    /// @brief Construct a sampler from an initial partition and set of model parameters.\n    ///\n    /// @param initial_partition\n    /// @param initial_parameters\n    partition_sampler(const partition_ptr_t& initial_partition_ptr,\n                      const model::parameters& initial_parameters = model::parameters())\n        : base_type(partition_distribution(initial_parameters),\n                    partition_proposal(),\n                    partition_sampler_sample(initial_partition_ptr, mh_moves::NONE, mh_moves::NONE))\n    {\n        // Merge partition sampler and MH sampler?\n    }\n\n    /// @brief The model parameters associated with this sampler.\n    const model::parameters& parameters() const { return target_.params; }\n\n    /// @brief Return a reference to the partition of the last sample drawn so far.\n    const partition_ptr_t last_partition() const { return last_sample().partition_sample_ptr; }\n\n    /// @brief Return a reference to the move type of the last sample drawn so far.\n    const mh_moves::move_type& last_move() const { return last_sample().executed_move; }\n\n    /// @brief Modify the parameters associated with this sampler.\n    ///\n    /// @param params A new set of parameters for the sampler.\n    void set_parameters(const model::parameters& params) { target_.params = params; }\n\n    /// @brief set the partition_is_valid value\n    void set_partition_is_valid(bool v) { propose_.partition_is_valid = v; }\n};\n\n\n} // namespace biggles\n\n#endif //BIGGLES_PARTITION_SAMPLER_HPP__\n", "meta": {"hexsha": "a0856da326967602a2e14a4417e9de3a880d0b6e", "size": 4770, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/biggles/partition_sampler.hpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "include/biggles/partition_sampler.hpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/biggles/partition_sampler.hpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.972972973, "max_line_length": 133, "alphanum_fraction": 0.6716981132, "num_tokens": 1274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.769080247656264, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.43826241827717866}}
{"text": "/* \n// Copyright 2018 University of Liege\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n//     http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Authors:\n// - Adrien Crovato\n*/\n\n//// Field mapping\n// Identify each cell as an interior or exterior (FLAG 0, 1). Also create vector of indexes associated to\n// field mapping type.\n// Crossing number method is used as point in polygon algorithm.\n//\n// References: http://geomalgorithms.com/a03-_inclusion.html\n//\n// I/O:\n// - sGrid: temporary dynamic array containing body panel vertices\n// - numC: list of numerical parameters (structure)\n// - bPan: body panels (structure)\n// - fPan: field panels (structure)\n\n#include <iostream>\n#include <Eigen/Dense>\n#include \"map_field.h\"\n\n#define NDIM 3\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid map_field(MatrixX3d &sGrid, Numerical_CST &numC, Network &bPan, Field &fPan) {\n\n    //// Begin\n    // Temporary variables\n    double minX, maxX, minY, maxY, minZ, maxZ; // minimal bounding box holding the geometry\n    int iE = 0, iI = 0; // indexes\n    MatrixX2d panVert;\n    panVert.resize(bPan.nC,2);\n\n    // Display check\n    cout << \"Mapping field cells... \" << flush;\n\n    // Resize matrices\n    fPan.fMap.resize(fPan.nF);\n\n    // Compute minimum size box including full geometry\n    minX = sGrid.col(0).minCoeff() - numC.TOLB;\n    maxX = sGrid.col(0).maxCoeff() + numC.TOLB;\n    minY = sGrid.col(1).minCoeff();\n    maxY = sGrid.col(1).maxCoeff();\n    minZ = sGrid.col(2).minCoeff() - numC.TOLB;\n    maxZ = sGrid.col(2).maxCoeff() + numC.TOLB;\n\n    //// Map field cells\n    for (int f = 0; f < fPan.nF; f++) {\n        lbl_loop0:\n        // Bounding box\n        if (fPan.CG(f,0) < minX || fPan.CG(f,0) > maxX\n            || fPan.CG(f,1) < minY || fPan.CG(f,1) > maxY\n            || fPan.CG(f,2) < minZ || fPan.CG(f,2) > maxZ) {\n            fPan.fMap(f) = 1;\n            fPan.nE++;\n        }\n        // 2D PIP algorithm\n        else {\n            // Find spanwise station corresponding to y-coordinate of field cell\n            for (int s = 0; s < bPan.nS_; s++) {\n                if (fPan.CG(f,1) <= sGrid((s+1)*bPan.nC,1)) {\n                    // Interpolate\n                    double a = (sGrid((s+1)*bPan.nC,1) - fPan.CG(f,1)) / (sGrid((s+1)*bPan.nC,1) - sGrid(s*bPan.nC,1));\n                    double b = (fPan.CG(f,1) - sGrid(s*bPan.nC,1)) / (sGrid((s+1)*bPan.nC,1) - sGrid(s*bPan.nC,1));\n                    // Store interpolated airfoil panel vertices\n                    for (int i = 0; i < bPan.nC; i++) {\n                        panVert(i,0) = a*sGrid(s*bPan.nC+i,0) + b*sGrid((s+1)*bPan.nC+i,0);\n                        panVert(i,1) = a*sGrid(s*bPan.nC+i,2) + b*sGrid((s+1)*bPan.nC+i,2);\n                    }\n                    // Crossing number method\n                    int nInter = 0;\n                    for (int i = 0; i < bPan.nC_; i++) {\n                        // Check if point is not on a vertex\n                        if (fPan.CG(f,0) == panVert(i,0) && fPan.CG(f,2) == panVert(i,1)) {\n                            fPan.fMap(f) = 0;\n                            fPan.nI++;\n                            f++;\n                            goto lbl_loop0; // *might wanna use goto here!!\n                        }\n                        // Exclude top endpoint of segment to avoid double crossings and horizontal edges\n                        if ((fPan.CG(f,2) >= panVert(i,1) && fPan.CG(f,2) < panVert(i+1,1))\n                            || (fPan.CG(f,2) < panVert(i,1) && fPan.CG(f,2) >= panVert(i+1,1))) {\n                            double sI = (fPan.CG(f,2) - panVert(i,1)) / (panVert(i+1,1) - panVert(i,1)); // Compute y-intersection\n                            if (fPan.CG(f,0) <  panVert(i,0) + sI * (panVert(i+1,0) - panVert(i,0))) { // If point is left of x-intersect\n                                nInter++; // Then intersection is valid\n                            }\n                        }\n                    }\n                    // Even number of intersections, external point\n                    if (nInter%2 == 0) {\n                        fPan.fMap(f) = 1;\n                        fPan.nE++;\n                        break;\n                    }\n                    // Odd number of intersections, internal point\n                    else {\n                        fPan.fMap(f) = 0;\n                        fPan.nI++;\n                        break;\n                    }\n                }\n                else\n                    continue;\n            }\n        }\n    }\n    // Find cell indices according to mapping type\n    fPan.eIdx.resize(fPan.nE);\n    fPan.iIdx.resize(fPan.nI);\n    for (int f = 0; f < fPan.nF; ++f) {\n        if (fPan.fMap(f)) {\n            fPan.eIdx(iE) = f;\n            iE++;\n        }\n        else {\n            fPan.iIdx(iI) = f;\n            iI++;\n        }\n    }\n\n    //// Control display\n    cout << \"Done!\" << endl;\n    cout << \"Field map: \" << fPan.fMap.size() << endl;\n    #ifdef VERBOSE\n        for (int j = 0; j < fPan.nY; ++j) {\n            cout << endl;\n            for (int k = 0; k < fPan.nZ; ++k) {\n                cout << endl;\n                for (int i = 0; i < fPan.nX; ++i)\n                    cout << fPan.fMap(i + k * fPan.nX + j * fPan.nX * fPan.nZ) << ' ';\n            }\n        }\n        cout << endl;\n    #endif\n    cout << \"Exterior cells: \" << fPan.eIdx.rows() << endl;\n    cout << \"Interior cells: \" << fPan.iIdx.rows() << endl;\n    cout << endl;\n}", "meta": {"hexsha": "45150086436a4f0f2224eac52880521af129852f", "size": 5901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/map_field.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/map_field.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/map_field.cpp", "max_forks_repo_name": "acrovato/aero", "max_forks_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8269230769, "max_line_length": 137, "alphanum_fraction": 0.4880528724, "num_tokens": 1636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.438262412244983}}
{"text": "// Copyright (c) 2015-2020 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#include \"coalescent_model.hpp\"\n\n#include <memory>\n#include <cmath>\n#include <complex>\n#include <numeric>\n#include <stdexcept>\n\n#include <boost/math/special_functions/binomial.hpp>\n\n#include \"utils/maths.hpp\"\n\nnamespace octopus {\n\nCoalescentModel::CoalescentModel(Haplotype reference, Parameters params,\n                                 std::size_t num_haplotyes_hint, CachingStrategy caching)\n: reference_ {std::move(reference)}\n, indel_heterozygosity_model_ {make_indel_model(reference_, {params.indel_heterozygosity})}\n, params_ {params}\n, haplotypes_ {}\n, caching_ {caching}\n, index_cache_ {}\n, index_flag_buffer_ {}\n, k_indel_zero_result_cache_ {2 * num_haplotyes_hint, std::vector<boost::optional<LogProbability>> {}}\n{\n    if (params_.snp_heterozygosity <= 0 || params_.indel_heterozygosity <= 0) {\n        throw std::domain_error {\"CoalescentModel: snp and indel heterozygosity must be > 0\"};\n    }\n    site_buffer1_.reserve(128);\n    site_buffer2_.reserve(128);\n    if (caching == CachingStrategy::address) {\n        difference_address_cache_.reserve(num_haplotyes_hint);\n    } else if (caching_ == CachingStrategy::value) {\n        difference_value_cache_.reserve(num_haplotyes_hint);\n        difference_value_cache_.emplace(std::piecewise_construct,\n                                        std::forward_as_tuple(reference_),\n                                        std::forward_as_tuple());\n    }\n    k_indel_pos_result_cache_.reserve(2 * num_haplotyes_hint);\n}\n\nvoid CoalescentModel::set_reference(Haplotype reference)\n{\n    reference_ = std::move(reference);\n    if (caching_ == CachingStrategy::address) {\n        difference_address_cache_.clear();\n    } else if (caching_ == CachingStrategy::value) {\n        difference_value_cache_.clear();\n        difference_value_cache_.emplace(std::piecewise_construct,\n                                        std::forward_as_tuple(reference_),\n                                        std::forward_as_tuple());\n    }\n}\n\nvoid CoalescentModel::prime(MappableBlock<Haplotype> haplotypes)\n{\n    haplotypes_ = std::move(haplotypes);\n    index_cache_.assign(haplotypes_.size(), boost::none);\n    index_flag_buffer_.assign(haplotypes_.size(), false);\n}\n\nvoid CoalescentModel::unprime() noexcept\n{\n    haplotypes_.clear();\n    haplotypes_.shrink_to_fit();\n    index_cache_.clear();\n    index_cache_.shrink_to_fit();\n    index_flag_buffer_.clear();\n    index_flag_buffer_.shrink_to_fit();\n}\n\nbool CoalescentModel::is_primed() const noexcept\n{\n    return !index_cache_.empty();\n}\n\nCoalescentModel::LogProbability CoalescentModel::evaluate(const Haplotype& haplotype) const\n{\n    return evaluate(count_segregating_sites(haplotype));\n}\n\nCoalescentModel::LogProbability CoalescentModel::evaluate(const std::vector<unsigned>& haplotype_indices) const\n{\n    return evaluate(count_segregating_sites(haplotype_indices));\n}\n\nnamespace {\n\nauto powm1(const unsigned i) noexcept // std::pow(-1, i)\n{\n    return (i % 2 == 0) ? 1 : -1;\n}\n\nauto binom(const unsigned n, const unsigned k)\n{\n    return boost::math::binomial_coefficient<CoalescentModel::LogProbability>(n, k);\n}\n\nauto log_binom(const unsigned n, const unsigned k)\n{\n    using T = CoalescentModel::LogProbability;\n    using maths::log_factorial;\n    return log_factorial<T>(n) - (log_factorial<T>(k) + log_factorial<T>(n - k));\n}\n\ntemplate <typename T>\nauto coalescent_real_space(const unsigned n, const unsigned k, const T theta)\n{\n    T result {0};\n    for (unsigned i {2}; i <= n; ++i) {\n        result += powm1(i) * binom(n - 1, i - 1) * ((i - 1) / (theta + i - 1)) * std::pow(theta / (theta + i - 1), k);\n    }\n    return std::log(result);\n}\n\ntemplate <typename ForwardIt>\nauto complex_log_sum_exp(ForwardIt first, ForwardIt last)\n{\n    using ComplexType = typename std::iterator_traits<ForwardIt>::value_type;\n    const auto l = [] (const auto& lhs, const auto& rhs) { return lhs.real() < rhs.real(); };\n    const auto max = *std::max_element(first, last, l);\n    return max + std::log(std::accumulate(first, last, ComplexType {},\n                                          [max] (const auto curr, const auto x) { return curr + std::exp(x - max); }));\n}\n\ntemplate <typename Container>\nauto complex_log_sum_exp(const Container& logs)\n{\n    return complex_log_sum_exp(std::cbegin(logs), std::cend(logs));\n}\n\ntemplate <typename T>\nauto coalescent_log_space(const unsigned n, const unsigned k, const T theta)\n{\n    std::vector<std::complex<T>> tmp(n - 1, std::log(std::complex<T> {-1}));\n    for (unsigned i {2}; i <= n; ++i) {\n        auto& cur = tmp[i - 2];\n        cur *= i;\n        cur += log_binom(n - 1, i - 1);\n        cur += std::log((i - 1) / (theta + i - 1));\n        cur += k * std::log(theta / (theta + i - 1));\n    }\n    return complex_log_sum_exp(tmp).real();\n}\n\ntemplate <typename T>\nauto coalescent(const unsigned n, const unsigned k, const T theta)\n{\n    if (n < 30 && k <= 80) {\n        auto result = coalescent_real_space(n, k, theta);\n        if (std::isnan(result)) {\n            result = coalescent_log_space(n, k, theta);\n        }\n        return result;\n    } else {\n        return coalescent_log_space(n, k, theta);\n    }\n}\n\ntemplate <typename T>\nauto coalescent(const unsigned n, const unsigned k_snp, const unsigned k_indel,\n                const T theta_snp, const T theta_indel)\n{\n    const auto theta = theta_snp + theta_indel;\n    const auto k_tot = k_snp + k_indel;\n    auto result = coalescent(n, k_tot, theta);\n    result += k_snp * std::log(theta_snp / theta);\n    result += k_indel * std::log(theta_indel / theta);\n    result += log_binom(k_tot, k_snp);\n    return result;\n}\n\n} // namespace\n\nCoalescentModel::LogProbability CoalescentModel::evaluate(const SiteCountTuple& t) const\n{\n    unsigned k_snp, k_indel, n;\n    std::tie(k_snp, k_indel, n) = t;\n    if (k_indel == 0) {\n        return evaluate(k_snp, n);\n    } else {\n        return evaluate(k_snp, k_indel, n);\n    }\n}\n\nCoalescentModel::LogProbability CoalescentModel::evaluate(const unsigned k_snp, const unsigned n) const\n{\n    if (k_indel_zero_result_cache_.size() > n) {\n        if (k_indel_zero_result_cache_[n].size() > k_snp) {\n            auto& result = k_indel_zero_result_cache_[n][k_snp];\n            if (!result) {\n                result = coalescent(n, k_snp, 0, params_.snp_heterozygosity, params_.indel_heterozygosity);\n            }\n            return *result;\n        } else {\n            k_indel_zero_result_cache_[n].resize(k_snp + 1, boost::none);\n        }\n    } else {\n        k_indel_zero_result_cache_.resize(n + 1);\n        k_indel_zero_result_cache_[n].assign(k_snp + 1, boost::none);\n    }\n    const auto result = coalescent(n, k_snp, 0, params_.snp_heterozygosity, params_.indel_heterozygosity);\n    k_indel_zero_result_cache_[n][k_snp] = result;\n    return result;\n}\n\nCoalescentModel::LogProbability CoalescentModel::evaluate(const unsigned k_snp, const unsigned k_indel, const unsigned n) const\n{\n    const auto indel_heterozygosity = calculate_buffered_indel_heterozygosity();\n    const auto t = std::make_tuple(k_snp, k_indel, n, maths::round_sf(indel_heterozygosity, 6));\n    auto itr = k_indel_pos_result_cache_.find(t);\n    if (itr != std::cend(k_indel_pos_result_cache_)) {\n        return itr->second;\n    }\n    const auto result = coalescent(n, k_snp, k_indel, params_.snp_heterozygosity, indel_heterozygosity);\n    k_indel_pos_result_cache_.emplace(t, result);\n    return result;\n}\n\nvoid CoalescentModel::fill_site_buffer(const Haplotype& haplotype) const\n{\n    assert(site_buffer2_.empty());\n    site_buffer1_.clear();\n    if (caching_ == CachingStrategy::address) {\n        fill_site_buffer_from_address_cache(haplotype);\n    } else {\n        fill_site_buffer_from_value_cache(haplotype);\n    }\n    site_buffer1_ = std::move(site_buffer2_);\n    site_buffer2_.clear();\n}\n\nvoid CoalescentModel::fill_site_buffer_uncached(const Haplotype& haplotype) const\n{\n    // Although we won't retrieve from the cache, we need to make sure all the variants\n    // stay in existence as we populate the buffers by reference.\n    auto itr = difference_value_cache_.find(reference_);\n    if (itr == std::cend(difference_value_cache_)) {\n        itr = difference_value_cache_.emplace(reference_, haplotype.difference(reference_)).first;\n    } else {\n        itr->second = haplotype.difference(reference_);\n    }\n    std::set_union(std::begin(site_buffer1_), std::end(site_buffer1_),\n                   std::cbegin(itr->second), std::cend(itr->second),\n                   std::back_inserter(site_buffer2_));\n}\n\nvoid CoalescentModel::fill_site_buffer_from_value_cache(const Haplotype& haplotype) const\n{\n    auto itr = difference_value_cache_.find(haplotype);\n    if (itr == std::cend(difference_value_cache_)) {\n        itr = difference_value_cache_.emplace(haplotype, haplotype.difference(reference_)).first;\n    }\n    std::set_union(std::begin(site_buffer1_), std::end(site_buffer1_),\n                   std::cbegin(itr->second), std::cend(itr->second),\n                   std::back_inserter(site_buffer2_));\n}\n\nvoid CoalescentModel::fill_site_buffer_from_address_cache(const Haplotype& haplotype) const\n{\n    auto itr = difference_address_cache_.find(std::addressof(haplotype));\n    if (itr == std::cend(difference_address_cache_)) {\n        itr = difference_address_cache_.emplace(std::addressof(haplotype), haplotype.difference(reference_)).first;\n    }\n    std::set_union(std::begin(site_buffer1_), std::end(site_buffer1_),\n                   std::cbegin(itr->second), std::cend(itr->second),\n                   std::back_inserter(site_buffer2_));\n}\n\nCoalescentModel::SiteCountTuple CoalescentModel::count_segregating_sites(const Haplotype& haplotype) const\n{\n    fill_site_buffer(haplotype);\n    return count_segregating_sites_in_buffer(1);\n}\n\nCoalescentModel::SiteCountTuple CoalescentModel::count_segregating_sites_in_buffer(const unsigned num_haplotypes) const\n{\n    const auto num_indels = std::count_if(std::cbegin(site_buffer1_), std::cend(site_buffer1_),\n                                          [] (const auto& v) noexcept { return is_indel(v); });\n    return std::make_tuple(site_buffer1_.size() - num_indels, num_indels, num_haplotypes + 1);\n}\n\ndouble CoalescentModel::calculate_buffered_indel_heterozygosity() const\n{\n    boost::optional<double> max_heterozygosity {};\n    for (const auto& site : site_buffer1_) {\n        if (is_indel(site)) {\n            auto site_heterozygosity = calculate_heterozygosity(site);\n            if (max_heterozygosity) {\n                max_heterozygosity = std::max(*max_heterozygosity, site_heterozygosity);\n            } else {\n                max_heterozygosity = site_heterozygosity;\n            }\n        }\n    }\n    return max_heterozygosity ? *max_heterozygosity : params_.indel_heterozygosity;\n}\n\ndouble CoalescentModel::calculate_heterozygosity(const Variant& indel) const\n{\n    assert(is_indel(indel));\n    const auto offset = static_cast<std::size_t>(begin_distance(reference_, indel));\n    return calculate_indel_probability(indel_heterozygosity_model_, offset, indel_size(indel));\n}\n\nCoalescentProbabilityGreater::CoalescentProbabilityGreater(CoalescentModel model)\n: model_ {std::move(model)}\n, buffer_ {}\n, cache_ {}\n{\n    buffer_.reserve(1);\n    cache_.reserve(100);\n}\n\nbool CoalescentProbabilityGreater::operator()(const Haplotype& lhs, const Haplotype& rhs) const\n{\n    if (have_same_alleles(lhs, rhs)) return true;\n    auto cache_itr = cache_.find(lhs);\n    if (cache_itr == std::cend(cache_)) {\n        buffer_.assign({lhs});\n        cache_itr = cache_.emplace(lhs, model_.evaluate(buffer_)).first;\n    }\n    const auto lhs_probability = cache_itr->second;\n    cache_itr = cache_.find(rhs);\n    if (cache_itr == std::cend(cache_)) {\n        buffer_.assign({rhs});\n        cache_itr = cache_.emplace(rhs, model_.evaluate(buffer_)).first;\n    }\n    const auto rhs_probability = cache_itr->second;\n    return lhs_probability > rhs_probability;\n}\n\n} // namespace octopus\n", "meta": {"hexsha": "e562a79885aa5297a93aaceb30c509e9d5ca32cd", "size": 12083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/models/mutation/coalescent_model.cpp", "max_stars_repo_name": "roryk/octopus", "max_stars_repo_head_hexsha": "0ec2839c33b846107278696ee04ce6d7d0f69a54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/models/mutation/coalescent_model.cpp", "max_issues_repo_name": "roryk/octopus", "max_issues_repo_head_hexsha": "0ec2839c33b846107278696ee04ce6d7d0f69a54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/models/mutation/coalescent_model.cpp", "max_forks_repo_name": "roryk/octopus", "max_forks_repo_head_hexsha": "0ec2839c33b846107278696ee04ce6d7d0f69a54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8545994065, "max_line_length": 127, "alphanum_fraction": 0.6788049325, "num_tokens": 3194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709795, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.43812185473345633}}
{"text": "#include <iostream>\n#include <fstream>\n#include <Eigen/Eigen>\n//include the bie header files\n#include \"material.hh\"\n#include \"precomputed_kernel.hh\"\n#include \"bimat_interface.hh\"\n#include \"infinite_boundary.hh\"\n//include the fem header files\n//#include \"mesh_Generated.hpp\"\n#include \"mesh_Generated_multi_faults.hpp\"\n\n#include \"bcdof.hpp\"\n#include \"bcdof_ptr.hpp\"\n#include \"cal_ke.hpp\"\n#include \"cal_fe_global_const_ke.hpp\"\n#include \"mapglobal.hpp\"\n#include \"Slip_Weakening.hpp\"\n#include \"Rate_and_State_Aging.hpp\"\n#include \"cal_slip_sliprate.hpp\"\n#include \"update_disp_velocity.hpp\"\n#include \"time_advance.hpp\"\n#include \"BIE_correct.hpp\"\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main() {\n    // Domain Size\n    double x_min = -20e3;\n    double x_max = 20e3;\n    double y_min = -1.0e3;\n    double y_max = 1.0e3;\n    int dim = 2.0;\n    double dx = 50;\n    double dy = 50;\n    int nx_el = (x_max-x_min)/dx;\n    int ny = (y_max-y_min)/dy;\n    MatrixXd Node = MatrixXd::Zero((nx_el+1)*(ny+1),2);\n    MatrixXi_rm Element(nx_el*ny,4); Element.setZero();\n    ArrayXi BIE_top_surf_nodes = ArrayXi::Zero((nx_el+1),1);\n    ArrayXi BIE_bot_surf_nodes = ArrayXi::Zero((nx_el+1),1);\n    int num_faults = 1;\n    // Mesh\n    // Position of the fault : y_pos, x_left, x_right\n    MatrixXd fault_pos(num_faults,3);\n    fault_pos << 0.0,  x_min ,x_max;\n    \n    //    MatrixXd fault_pos;\n    //    read_matrix(\"fault_pos.txt\", fault_pos);\n    //    int num_faults = fault_pos.rows();\n    cout<<\"test_mat=\"<<\"\\n\"<<fault_pos<<\"\\n\"<<\"rows=\"<<fault_pos.rows()<<\"\\n\";\n    std::vector<std::vector<int>> fault_nodes(num_faults*2);\n    mesh_Generated_multi_faults(x_min,x_max,y_min,y_max,dx,dy,nx_el,ny,Node, Element,BIE_top_surf_nodes, BIE_bot_surf_nodes,fault_pos, fault_nodes);\n    \n     double Vw_width = 5e3;\n    // Finding Nodes on the diagonal\n    ArrayXi left_diag_nodes =ArrayXi::Zero((ny+1),1);\n    ArrayXi right_diag_nodes =ArrayXi::Zero((ny+1),1); ;\n    double TOL = 1e-6;\n    int m = 0;\n    int n = 0;\n    for(int i=0; i<Node.rows(); i++)\n    {\n        if ((std::abs(Node(i,0) +Vw_width/2.0)<TOL)&&(std::abs(Node(i,1))>=dx))\n        {\n            left_diag_nodes(m) = i ;\n            m+=1;\n        };\n        if ((std::abs(Node(i,0) - Vw_width/2.0)<TOL)&&(std::abs(Node(i,1))>=dx))\n        {\n            right_diag_nodes(n) = i ;\n            n+=1;\n        };\n    }\n    VectorXi left_diag_index = VectorXi::Zero(2*(left_diag_nodes.size()),1);\n    VectorXi right_diag_index = VectorXi::Zero(2*(right_diag_nodes.size()),1);\n\n    bcdof(left_diag_nodes,dim,left_diag_index);\n    bcdof(right_diag_nodes,dim,right_diag_index);\n    \n//    std::cout<<left_diag_nodes<<std::endl;\n//    std::cout<<\"********\"<<std::endl;\n//    std::cout<<right_diag_nodes<<std::endl;\n\n    std::ofstream Element_output(\"results/Element.txt\");\n    std::ofstream Node_output(\"results/Node.txt\");\n    Node_output<<Node;\n    Element_output<<Element;\n    \n    Element_output.close();\n    Node_output.close();\n    // Vector containing number of elements on each faults (nx)\n    std::vector<int> nx_faults(num_faults);\n    for (int i=0;i<num_faults;i++)\n    {\n        nx_faults[i] =fault_nodes[2*i].size();\n    }\n    \n    // Write the x coordiantes for each fault\n    std::vector<double> fault_angle(num_faults);\n    double x1 = 0.0;\n    double x2 = 0.0;\n    double y1 = 0.0;\n    double y2 = 0.0;\n    for (int j=0;j<num_faults; j++)\n    {\n        VectorXd x = VectorXd::Zero(nx_faults[j], 1);\n        VectorXd y = VectorXd::Zero(nx_faults[j], 1);\n        \n        for (int i=0; i<x.size(); i++)\n        {\n            x(i) = Node(fault_nodes[2*j][i],0);\n            y(i) = Node(fault_nodes[2*j][i],1);\n        }\n        \n        //std::ofstream x_output(\"results/fault_x_coord.txt\");\n        std::string  x_fault= \"results/x_fault_\"+std::to_string(j)+\".txt\";\n        std::ofstream x_output(x_fault);\n        x_output<<x;\n        \n        x1 = Node(fault_nodes[2*j][0],0);\n        x2 = Node(fault_nodes[2*j][nx_faults[j]-1],0);\n        y1 = Node(fault_nodes[2*j][0],1);\n        y2 = Node(fault_nodes[2*j][nx_faults[j]-1],1);\n        fault_angle[j]=std::atan2(y2-y1,x2-x1);\n    }\n    int n_nodes = Node.rows();\n    int n_el = Element.rows();\n    int Ndofn = 2;\n    int Nnel = Element.cols();\n   // nx_el = fault_nodes.size()-1;\n    // Material\n    double density = 2670.0;\n    double v_s =3.464e3;\n    double v_p = 6.0e3;\n    double G= pow(v_s,2)*density;\n    double Lambda = pow(v_p,2)*density-2.0*G;\n    double E  = G*(3.0*Lambda+2.0*G)/(Lambda+G);\n    double nu = Lambda/(2.0*(Lambda+G));\n    // Time\n    double alpha = 0.1;\n    double dt = alpha*dx/v_p;\n    // Reyleigh Damping\n    double beta =0.2;\n    double q = beta*dt;\n    double time_run = 9.0;\n    int numt = time_run/dt;\n    //numt =1;\n    \n    \n    std::ofstream time_output(\"results/time.txt\");\n    time_output<<time_run<<\"\\n\";\n    time_output<<dt<<\"\\n\";\n    time_output<<numt<<std::endl;\n    //numt = 3;\n    VectorXd time = dt*VectorXd::LinSpaced(numt,1,numt);\n    // Rate and state friction parameters\n    \n    double a = 0.008;\n    double b = 0.012;\n    \n    VectorXd a_array = a*VectorXd::Zero(nx_el+1,1);\n    VectorXd b_array = b*VectorXd::Zero(nx_el+1,1);\n\n    double V_0 = 1e-6;\n    double f_0 = 0.6;\n    double L = 0.02;\n    double tau_ini = 75e6;\n    double sigma_ini = 120e6;\n    double V_ini  = 1e-12;\n    // Intialization\n    // disp velocity current and next time step (new)\n    VectorXd u_n = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd v_n = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd u_new = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd v_new = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd a_n = VectorXd::Zero(n_nodes*Ndofn,1);\n    // slip and slip-rate\n    VectorXd delt_u_n = VectorXd::Zero(Ndofn*(nx_el+1),1);\n    VectorXd delt_v_n = VectorXd::Zero(Ndofn*(nx_el+1),1);\n    std::cout<<delt_u_n.size()<<std::endl;\n    std::cout<<nx_el<<std::endl;\n    // Stress on the fault T_0 = intial stress , T = sticking force, T_c= stress critical goes into F_global\n    VectorXd T_0 = VectorXd::Zero(Ndofn*(nx_el+1),1);\n    VectorXd T = VectorXd::Zero(Ndofn*(nx_el+1),1);\n    VectorXd T_c = VectorXd::Zero(Ndofn*(nx_el+1),1);\n    VectorXd tau_s = VectorXd::Zero(nx_el+1,1);\n    VectorXd F_ext_global = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd theta_n =VectorXd::Zero(nx_el+1, 1);\n    VectorXd theta_dot_n = VectorXd::Zero(nx_el+1, 1);\n    VectorXd theta_ini =VectorXd::Zero(nx_el+1, 1);\n\n    // Setting intial stress on the fault\n    for (int i=0; i<T_0.size()/2; i++)\n    {\n        T_0(2*i) = tau_ini;\n        T_0(2*i+1) = -sigma_ini;\n    }\n    VectorXd x = VectorXd::LinSpaced(nx_el+1,x_min,x_max);\n    double d_tau_0 = 25e6;\n    double R = 2.5e3;\n    VectorXd F_r = VectorXd::Zero(nx_el+1,1);\n    for (int i=0; i<nx_el+1; i++)\n    {\n        if (fabs(x(i))<R)\n        {\n            F_r(i) = exp(pow(x(i),2)/( pow(x(i),2)-pow(R,2)));\n        }\n        else\n        {\n            F_r(i) = 0.0;\n        }\n    }\n    VectorXd G_t = VectorXd::Zero(numt,1);\n    double T_ramp = 1.0;\n    for (int i=0; i<numt;i++)\n    {\n        if(time(i)<T_ramp)\n        {\n            G_t(i) = exp(pow((time(i)-T_ramp),2)/(time(i)*(time(i)-2*T_ramp)));\n        }\n        else\n        {\n            G_t(i) = 1.0;\n        }\n    }\n   \n    for (int i =0; i<nx_el+1; i++){\n        if (abs(x(i))<Vw_width/2.0)\n        {\n            a_array(i) = 0.008;\n            b_array(i) = 0.012;\n            theta_ini(i) = L/V_0*exp((a_array(i)*log(2*sinh(tau_ini/(a_array(i)*sigma_ini)))-f_0-a_array(i)*log(V_ini/V_0))/b_array(i));\n        }\n        else\n        {\n            b_array(i) = 0.08;\n            a_array(i) = 0.12;\n            theta_ini(i) = L/V_0*exp((a_array(i)*log(2*sinh(tau_ini/(a_array(i)*sigma_ini)))-f_0-a_array(i)*log(V_ini/V_0))/b_array(i));\n        }\n    }\n    \n    theta_n = theta_ini;\n    MatrixXd d_tau = MatrixXd::Zero(nx_el+1,numt);\n    for (int i=0;i<numt;i++)\n    {\n        d_tau.col(i)=75e6*VectorXd::Ones(nx_el+1,1)+d_tau_0*F_r*(G_t(i));\n       // d_tau.col(i)=75e6*VectorXd::Ones(nx_el+1,1)+3.75e6*F_r+dt*0.3125e7*i*VectorXd::Ones(nx_el+1,1);\n    }\n    // Get the index degree of freedome for each element\n    VectorXi index_el = VectorXi::Zero(Ndofn*Nnel,1);\n    MatrixXi index_store = MatrixXi::Zero(Nnel*Ndofn,n_el);\n    for (int i=0;i<n_el;i++)\n    {\n        bcdof(Element.row(i),dim,index_el);\n        index_store.col(i) = index_el;\n    }\n    VectorXi BIE_top_surf_index = VectorXi::Zero(Ndofn*(BIE_top_surf_nodes.size()),1);\n    VectorXi BIE_bot_surf_index = VectorXi::Zero(Ndofn*(BIE_bot_surf_nodes.size()),1);\n    \n    std::vector<Eigen::ArrayXi> Fault_surf_index(num_faults*2);\n    for (int i=0; i <num_faults*2; i++)\n    {\n        Fault_surf_index[i] = ArrayXi::Zero(Ndofn*(fault_nodes[i].size()),1);\n    }\n    \n    // Getting the faults DOF index\n    for (int i=0; i<num_faults*2;i++)\n    {\n        bcdof_ptr(fault_nodes[i], dim, Fault_surf_index[i].data());\n    }\n    bcdof(BIE_top_surf_nodes,dim,BIE_top_surf_index);\n    bcdof(BIE_bot_surf_nodes,dim,BIE_bot_surf_index);\n    \n    // Rate and state initlaized v_n delt_v_n\n    for (int i=0;i<nx_el+1;i++)\n    {\n        delt_v_n(2*i)= V_ini;\n  //      v_n(top_surf_index(2*i))= V_ini/2.0;\n        \n  //      v_n(bot_surf_index(2*i))= -V_ini/2.0;\n        \n        v_n(Fault_surf_index[0](2*i))= V_ini/2.0;\n        \n        v_n(Fault_surf_index[1](2*i))= -V_ini/2.0;\n    }\n    \n    // Calculating the Global Mass Vector (lumped mass)\n    // Element mass\n    double M=density*dx*dy*1.0;\n    VectorXd M_el_vec = M/4*VectorXd::Ones(Nnel*Ndofn,1);\n    VectorXd M_global_vec=VectorXd::Zero(n_nodes*Ndofn,1);\n    for (int i=0 ; i<n_el;i++)\n    {\n        index_el = index_store.col(i);\n        mapglobal(index_el,M_global_vec,M_el_vec);\n    }\n    // Element matrix\n    MatrixXd ke = MatrixXd::Zero(8,8);\n    MatrixXd coord = MatrixXd::Zero(4,2);\n    VectorXi Element_0= Element.row(0);\n    coord.row(0) = Node.row(Element_0(0));\n    coord.row(1) = Node.row(Element_0(1));\n    coord.row(2) = Node.row(Element_0(2));\n    coord.row(3) = Node.row(Element_0(3));\n    \n    std::cout<<coord<<std::endl;\n    \n    cal_ke (coord,E,nu,ke);\n    // BIE part initiation\n    // Setting up the material property for the BIE code\n    Material BIE_top_mat = Material(E,nu,density);\n    Material BIE_bot_mat = Material(E,nu,density);\n    double length = x_max-x_min;\n    // infinte bc BIE call infinite_boundary.cc\n    PrecomputedKernel h11(\"kernels/nu_.25_h11.dat\");\n    PrecomputedKernel h12(\"kernels/nu_.25_k12.dat\");\n    PrecomputedKernel h22(\"kernels/nu_.25_h22.dat\");\n    InfiniteBoundary BIE_inf_top(length,nx_el+1,1.0,&BIE_top_mat,&h11,&h12,&h22);\n    InfiniteBoundary BIE_inf_bot(length,nx_el+1,-1.0,&BIE_bot_mat,&h11,&h12,&h22);\n    // BIE setting time step\n    BIE_inf_top.setTimeStep(dt);\n    BIE_inf_bot.setTimeStep(dt);\n    // BIE initialization\n    BIE_inf_top.init();\n    BIE_inf_bot.init();\n\n    //BIE_initiation(E, nu, density, x_max, x_min, nx_el, dt);\n    printf(\"ready to start\\n\");\n    // Output\n    ofstream file;\n    file.open(\"results/num_nodes_fault.bin\",ios::binary);\n    file.write((char*)(nx_faults.data()),nx_faults.size()*sizeof(int));\n    file.close();\n    //\n    file.open(\"results/u_n.bin\",ios::binary);\n    file.close();\n    file.open(\"results/v_n.bin\",ios::binary);\n    file.close();\n    file.open(\"results/eq_ep_n.bin\",ios::binary);\n    file.close();\n    \n    \n    for (int i=0;i<num_faults;i++)\n    {\n        std::string slip = \"results/slip_\"+std::to_string(i)+\".bin\";\n        file.open(slip);\n        file.close();\n        std::string slip_rate = \"results/slip_rate_\"+std::to_string(i)+\".bin\";\n        file.open(slip_rate);\n        file.close();\n        std::string shear = \"results/shear_\"+std::to_string(i)+\".bin\";\n        file.open(shear);\n        file.close();\n    }\n\n    // Main time loop\n    for (int j=0;j<numt;j++)\n    {\n        // Compute the global internal force\n        VectorXd fe_global= VectorXd::Zero(n_nodes*Ndofn,1);\n        cal_fe_global_const_ke(n_nodes, n_el, index_store, q, u_n, v_n, Ndofn, ke, fe_global);\n        // Friction subroutine\n        VectorXd F_fault = VectorXd::Zero(Ndofn*(nx_el+1),1);\n      //  Slip_Weakening(M_global_vec, top_surf_index, bot_surf_index, fe_global, dt, dx, dy, nx_el, delt_v_n, delt_u_n, T_0, tau_s, mu_s, mu_d, Dc, Ndofn, M, F_fault, T_c);\n        for (int i=0;i<nx_el+1;i++)\n        {\n            T_0(2*i) = d_tau(i,j);\n        }\n        Rate_and_State_Aging(M_global_vec, Fault_surf_index[0], Fault_surf_index[1], fe_global, dt, dx, dy, nx_el, delt_u_n, delt_v_n, T_0, tau_s, a_array, b_array , L, V_0, f_0, Ndofn, M, F_fault, T_c, theta_n, theta_dot_n);\n\n        \n        // Calculate the global force vector\n        // Adding contribution of the fault force to the global force vector F_total\n        VectorXd F_total = F_ext_global-fe_global;\n        mapglobal(Fault_surf_index[0],F_total,-F_fault);\n        mapglobal(Fault_surf_index[1],F_total,F_fault);\n        // Central Difference Time integration\n        time_advance(u_n, v_n, F_total, M_global_vec, dt);\n        \n//        for (int i=0 ; i<left_diag_index.size();i++)\n//        {\n//            u_n(left_diag_index(i)) = 0.0;\n//            v_n(left_diag_index(i)) = 0.0;\n//            u_n(right_diag_index(i)) = 0.0;\n//            v_n(right_diag_index(i)) = 0.0;\n//        }\n//        \n        \n        // Get the slip and slip rate\n        //cal_slip_slip_rate(u_n, v_n, top_surf_index, bot_surf_index, Ndofn, nx_el, delt_u_n, delt_v_n);\n        update_disp_velocity(u_n, v_n, Fault_surf_index[0], Fault_surf_index[1], Ndofn, nx_el, delt_u_n, delt_v_n);\n\n        // Correct the BIE surf nodes solutions from FEM with the BIE solution\n        BIE_correct(BIE_top_surf_index, BIE_bot_surf_index, fe_global, Ndofn, nx_el, dx, BIE_inf_top, BIE_inf_bot, u_n, v_n);\n        \n        // Set the diagonal to be fixed\n        \n \n        //ofstream file;\n        for (int i=0;i<1;i++)\n        {\n            std::string slip = \"results/slip_\"+std::to_string(i)+\".bin\";\n            file.open(slip,ios::binary | ios::app);\n            file.write((char*)(delt_u_n.data()),delt_u_n.size()*sizeof(double));\n            file.close();\n            \n            std::string slip_rate = \"results/slip_rate_\"+std::to_string(i)+\".bin\";\n            file.open(slip_rate,ios::binary | ios::app);\n            file.write((char*)(delt_v_n.data()),delt_v_n.size()*sizeof(double));\n            file.close();\n            \n            std::string shear = \"results/shear_\"+std::to_string(i)+\".bin\";\n            file.open(shear,ios::binary | ios::app);\n            file.write((char*)(T_c.data()),T_c.size()*sizeof(double));\n            file.close();\n        }\n        \n        if (j%100==1)\n        {\n            file.open(\"results/u_n.bin\",ios::binary | ios::app);\n            file.write((char*)(u_n.data()),u_n.size()*sizeof(double));\n            file.close();\n            file.open(\"results/v_n.bin\",ios::binary | ios::app);\n            file.write((char*)(v_n.data()),v_n.size()*sizeof(double));\n            file.close();\n        }\n        \n        printf(\"Simulation time = %f\\n\",time(j));\n\n    }\n    return 0;\n}\n", "meta": {"hexsha": "c9302e7791e217d2c198fa1933e038cc30b64083", "size": 15111, "ext": "cc", "lang": "C++", "max_stars_repo_path": "simulations/rate_and_state_generated/input_Rate_and_State_Aging_Generated.cc", "max_stars_repo_name": "XiaoMaResearch/hybrid_FEM_SBI", "max_stars_repo_head_hexsha": "32fcf1e21a7f78907e01585d892777c11ff1c21e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "simulations/rate_and_state_generated/input_Rate_and_State_Aging_Generated.cc", "max_issues_repo_name": "XiaoMaResearch/hybrid_FEM_SBI", "max_issues_repo_head_hexsha": "32fcf1e21a7f78907e01585d892777c11ff1c21e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulations/rate_and_state_generated/input_Rate_and_State_Aging_Generated.cc", "max_forks_repo_name": "XiaoMaResearch/hybrid_FEM_SBI", "max_forks_repo_head_hexsha": "32fcf1e21a7f78907e01585d892777c11ff1c21e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 34.6582568807, "max_line_length": 225, "alphanum_fraction": 0.5952617299, "num_tokens": 4738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4381218400730536}}
{"text": "/*\r\n [auto_generated]\r\n boost/numeric/odeint/stepper/adams_bashforth.hpp\r\n\r\n [begin_description]\r\n Implementaton of the Adam-Bashforth method a multistep method used for the predictor step in the\r\n Adams-Bashforth-Moulton method.\r\n [end_description]\r\n\r\n Copyright 2009-2011 Karsten Ahnert\r\n Copyright 2009-2011 Mario Mulansky\r\n\r\n Distributed under the Boost Software License, Version 1.0.\r\n (See accompanying file LICENSE_1_0.txt or\r\n copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n\r\n#ifndef BOOST_NUMERIC_ODEINT_STEPPER_ADAMS_BASHFORTH_HPP_INCLUDED\r\n#define BOOST_NUMERIC_ODEINT_STEPPER_ADAMS_BASHFORTH_HPP_INCLUDED\r\n\r\n#include <boost/static_assert.hpp>\r\n\r\n#include <boost/numeric/odeint/util/bind.hpp>\r\n#include <boost/numeric/odeint/util/unwrap_reference.hpp>\r\n\r\n#include <boost/numeric/odeint/algebra/range_algebra.hpp>\r\n#include <boost/numeric/odeint/algebra/default_operations.hpp>\r\n\r\n#include <boost/numeric/odeint/util/state_wrapper.hpp>\r\n#include <boost/numeric/odeint/util/is_resizeable.hpp>\r\n#include <boost/numeric/odeint/util/resizer.hpp>\r\n\r\n#include <boost/numeric/odeint/stepper/stepper_categories.hpp>\r\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\r\n\r\n#include <boost/numeric/odeint/stepper/base/algebra_stepper_base.hpp>\r\n\r\n#include <boost/numeric/odeint/stepper/detail/adams_bashforth_coefficients.hpp>\r\n#include <boost/numeric/odeint/stepper/detail/adams_bashforth_call_algebra.hpp>\r\n#include <boost/numeric/odeint/stepper/detail/rotating_buffer.hpp>\r\n\r\n\r\n\r\nnamespace boost {\r\nnamespace numeric {\r\nnamespace odeint {\r\n\r\n\r\ntemplate<\r\nsize_t Steps ,\r\nclass State ,\r\nclass Value = double ,\r\nclass Deriv = State ,\r\nclass Time = Value ,\r\nclass Algebra = range_algebra ,\r\nclass Operations = default_operations ,\r\nclass Resizer = initially_resizer ,\r\nclass InitializingStepper = runge_kutta4< State , Value , Deriv , Time , Algebra , Operations, Resizer >\r\n>\r\nclass adams_bashforth : public algebra_stepper_base< Algebra , Operations >\r\n{\r\n\r\n#ifndef DOXYGEN_SKIP\r\n    BOOST_STATIC_ASSERT(( Steps > 0 ));\r\n    BOOST_STATIC_ASSERT(( Steps < 9 ));\r\n#endif\r\n\r\npublic :\r\n\r\n    typedef State state_type;\r\n    typedef state_wrapper< state_type > wrapped_state_type;\r\n    typedef Value value_type;\r\n    typedef Deriv deriv_type;\r\n    typedef state_wrapper< deriv_type > wrapped_deriv_type;\r\n    typedef Time time_type;\r\n    typedef Resizer resizer_type;\r\n    typedef stepper_tag stepper_category;\r\n\r\n    typedef InitializingStepper initializing_stepper_type;\r\n\r\n    typedef typename algebra_stepper_base< Algebra , Operations >::algebra_type algebra_type;\r\n    typedef typename algebra_stepper_base< Algebra , Operations >::operations_type operations_type;\r\n#ifndef DOXYGEN_SKIP\r\n    typedef adams_bashforth< Steps , State , Value , Deriv , Time , Algebra , Operations , Resizer , InitializingStepper > stepper_type;\r\n#endif\r\n    static const size_t steps = Steps;\r\n\r\n\r\n\r\n    typedef unsigned short order_type;\r\n    static const order_type order_value = steps;\r\n\r\n    typedef detail::rotating_buffer< wrapped_deriv_type , steps > step_storage_type;\r\n\r\n\r\n    \r\n    order_type order( void ) const { return order_value; }\r\n\r\n    adams_bashforth( const algebra_type &algebra = algebra_type() )\r\n    : m_step_storage() , m_resizer() , m_coefficients() ,\r\n      m_steps_initialized( 0 ) , m_initializing_stepper() ,\r\n      m_algebra( algebra )\r\n    { }\r\n\r\n    adams_bashforth( const adams_bashforth &stepper )\r\n    : m_step_storage( stepper.m_step_storage ) , m_resizer( stepper.m_resizer ) , m_coefficients() ,\r\n      m_steps_initialized( stepper.m_steps_initialized ) , m_initializing_stepper( stepper.m_initializing_stepper ) ,\r\n      m_algebra( stepper.m_algebra )\r\n    { }\r\n\r\n    adams_bashforth& operator=( const adams_bashforth &stepper )\r\n    {\r\n        m_resizer = stepper.m_resizer;\r\n        m_step_storage = stepper.m_step_storage;\r\n        m_algebra = stepper.m_algebra;\r\n        return *this;\r\n    }\r\n\r\n\r\n    /*\r\n     * Version 1 : do_step( system , x , t , dt );\r\n     *\r\n     * solves the forwarding problem\r\n     */\r\n    template< class System , class StateInOut >\r\n    void do_step( System system , StateInOut &x , time_type t , time_type dt )\r\n    {\r\n        do_step( system , x , t , x , dt );\r\n    }\r\n\r\n    /**\r\n     * \\brief Second version to solve the forwarding problem, can be called with Boost.Range as StateInOut.\r\n     */\r\n    template< class System , class StateInOut >\r\n    void do_step( System system , const StateInOut &x , time_type t , time_type dt )\r\n    {\r\n        do_step( system , x , t , x , dt );\r\n    }\r\n\r\n\r\n\r\n    /*\r\n     * Version 2 : do_step( system , in , t , out , dt );\r\n     *\r\n     * solves the forwarding problem\r\n     */\r\n\r\n    template< class System , class StateIn , class StateOut >\r\n    void do_step( System system , const StateIn &in , time_type t , StateOut &out , time_type dt )\r\n    {\r\n        do_step_impl( system , in , t , out , dt );\r\n    }\r\n\r\n    /**\r\n     * \\brief Second version to solve the forwarding problem, can be called with Boost.Range as StateOut.\r\n     */\r\n    template< class System , class StateIn , class StateOut >\r\n    void do_step( System system , const StateIn &in , time_type t , const StateOut &out , time_type dt )\r\n    {\r\n        do_step_impl( system , in , t , out , dt );\r\n    }\r\n\r\n\r\n    template< class StateType >\r\n    void adjust_size( const StateType &x )\r\n    {\r\n        resize_impl( x );\r\n    }\r\n\r\n    const step_storage_type& step_storage( void ) const\r\n    {\r\n        return m_step_storage;\r\n    }\r\n\r\n    step_storage_type& step_storage( void )\r\n    {\r\n        return m_step_storage;\r\n    }\r\n\r\n    template< class ExplicitStepper , class System , class StateIn >\r\n    void initialize( ExplicitStepper explicit_stepper , System system , StateIn &x , time_type &t , time_type dt )\r\n    {\r\n        typename odeint::unwrap_reference< ExplicitStepper >::type &stepper = explicit_stepper;\r\n        typename odeint::unwrap_reference< System >::type &sys = system;\r\n\r\n        m_resizer.adjust_size( x , detail::bind( &stepper_type::template resize_impl<StateIn> , detail::ref( *this ) , detail::_1 ) );\r\n\r\n        for( size_t i=0 ; i<steps-1 ; ++i )\r\n        {\r\n            if( i != 0 ) m_step_storage.rotate();\r\n            sys( x , m_step_storage[0].m_v , t );\r\n            stepper.do_step( system , x , m_step_storage[0].m_v , t , dt );\r\n            t += dt;\r\n        }\r\n        m_steps_initialized = steps;\r\n    }\r\n\r\n    template< class System , class StateIn >\r\n    void initialize( System system , StateIn &x , time_type &t , time_type dt )\r\n    {\r\n        initialize( detail::ref( m_initializing_stepper ) , system , x , t , dt );\r\n    }\r\n\r\n    void reset( void )\r\n    {\r\n        m_steps_initialized = 0;\r\n    }\r\n\r\n    bool is_initialized( void ) const\r\n    {\r\n        return m_steps_initialized >= steps;\r\n    }\r\n\r\n    const initializing_stepper_type& initializing_stepper( void ) const { return m_initializing_stepper; }\r\n\r\n    initializing_stepper_type& initializing_stepper( void ) { return m_initializing_stepper; }\r\n\r\nprivate:\r\n\r\n    template< class System , class StateIn , class StateOut >\r\n    void do_step_impl( System system , const StateIn &in , time_type t , StateOut &out , time_type dt )\r\n    {\r\n        typename odeint::unwrap_reference< System >::type &sys = system;\r\n        if( m_resizer.adjust_size( in , detail::bind( &stepper_type::template resize_impl<StateIn> , detail::ref( *this ) , detail::_1 ) ) )\r\n        {\r\n            m_steps_initialized = 0;\r\n        }\r\n\r\n        if( m_steps_initialized < steps - 1 )\r\n        {\r\n            if( m_steps_initialized != 0 ) m_step_storage.rotate();\r\n            sys( in , m_step_storage[0].m_v , t );\r\n            m_initializing_stepper.do_step( system , in , m_step_storage[0].m_v , t , out , dt );\r\n            m_steps_initialized++;\r\n        }\r\n        else\r\n        {\r\n            m_step_storage.rotate();\r\n            sys( in , m_step_storage[0].m_v , t );\r\n            detail::adams_bashforth_call_algebra< steps , algebra_type , operations_type >()( m_algebra , in , out , m_step_storage , m_coefficients , dt );\r\n        }\r\n    }\r\n\r\n\r\n    template< class StateIn >\r\n    bool resize_impl( const StateIn &x )\r\n    {\r\n        bool resized( false );\r\n        for( size_t i=0 ; i<steps ; ++i )\r\n        {\r\n            resized |= adjust_size_by_resizeability( m_step_storage[i] , x , typename is_resizeable<deriv_type>::type() );\r\n        }\r\n        return resized;\r\n    }\r\n\r\n    step_storage_type m_step_storage;\r\n    resizer_type m_resizer;\r\n    const detail::adams_bashforth_coefficients< value_type , steps > m_coefficients;\r\n    size_t m_steps_initialized;\r\n    initializing_stepper_type m_initializing_stepper;\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nprotected:\r\n\r\n    algebra_type m_algebra;\r\n};\r\n\r\n\r\n/***** DOXYGEN *****/\r\n\r\n/**\r\n * \\class adams_bashforth\r\n * \\brief The Adams-Bashforth multistep algorithm.\r\n *\r\n * The Adams-Bashforth method is a multi-step algorithm with configurable step\r\n * number. The step number is specified as template parameter Steps and it \r\n * then uses the result from the previous Steps steps. See also\r\n * <a href=\"http://en.wikipedia.org/wiki/Linear_multistep_method\">en.wikipedia.org/wiki/Linear_multistep_method</a>.\r\n * Currently, a maximum of Steps=8 is supported.\r\n * The method is explicit and fulfills the Stepper concept. Step size control\r\n * or continuous output are not provided.\r\n * \r\n * This class derives from algebra_base and inherits its interface via\r\n * CRTP (current recurring template pattern). For more details see\r\n * algebra_stepper_base.\r\n *\r\n * \\tparam Steps The number of steps (maximal 8).\r\n * \\tparam State The state type.\r\n * \\tparam Value The value type.\r\n * \\tparam Deriv The type representing the time derivative of the state.\r\n * \\tparam Time The time representing the independent variable - the time.\r\n * \\tparam Algebra The algebra type.\r\n * \\tparam Operations The operations type.\r\n * \\tparam Resizer The resizer policy type.\r\n * \\tparam InitializingStepper The stepper for the first two steps.\r\n */\r\n\r\n    /**\r\n     * \\fn adams_bashforth::adams_bashforth( const algebra_type &algebra )\r\n     * \\brief Constructs the adams_bashforth class. This constructor can be used as a default\r\n     * constructor if the algebra has a default constructor. \r\n     * \\param algebra A copy of algebra is made and stored.\r\n     */\r\n\r\n    /**\r\n     * \\fn order_type adams_bashforth::order( void ) const\r\n     * \\brief Returns the order of the algorithm, which is equal to the number of steps.\r\n     * \\return order of the method.\r\n     */\r\n\r\n    /**\r\n     * \\fn void adams_bashforth::do_step( System system , StateInOut &x , time_type t , time_type dt )\r\n     * \\brief This method performs one step. It transforms the result in-place.\r\n     *\r\n     * \\param system The system function to solve, hence the r.h.s. of the ordinary differential equation. It must fulfill the\r\n     *               Simple System concept.\r\n     * \\param x The state of the ODE which should be solved. After calling do_step the result is updated in x.\r\n     * \\param t The value of the time, at which the step should be performed.\r\n     * \\param dt The step size.\r\n     */\r\n\r\n    /**\r\n     * \\fn void adams_bashforth::do_step( System system , const StateIn &in , time_type t , StateOut &out , time_type dt )\r\n     * \\brief The method performs one step with the stepper passed by Stepper. The state of the ODE is updated out-of-place.\r\n     *\r\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\r\n     *               Simple System concept.\r\n     * \\param in The state of the ODE which should be solved. in is not modified in this method\r\n     * \\param t The value of the time, at which the step should be performed.\r\n     * \\param out The result of the step is written in out.\r\n     * \\param dt The step size.\r\n     */\r\n\r\n    /**\r\n     * \\fn void adams_bashforth::adjust_size( const StateType &x )\r\n     * \\brief Adjust the size of all temporaries in the stepper manually.\r\n     * \\param x A state from which the size of the temporaries to be resized is deduced.\r\n     */\r\n\r\n\r\n    /**\r\n     * \\fn const step_storage_type& adams_bashforth::step_storage( void ) const\r\n     * \\brief Returns the storage of intermediate results.\r\n     * \\return The storage of intermediate results.\r\n     */\r\n\r\n    /**\r\n     * \\fn step_storage_type& adams_bashforth::step_storage( void )\r\n     * \\brief Returns the storage of intermediate results.\r\n     * \\return The storage of intermediate results.\r\n     */\r\n\r\n    /**\r\n     * \\fn void adams_bashforth::initialize( ExplicitStepper explicit_stepper , System system , StateIn &x , time_type &t , time_type dt )\r\n     * \\brief Initialized the stepper. Does Steps-1 steps with the explicit_stepper to fill the buffer.\r\n     * \\param explicit_stepper the stepper used to fill the buffer of previous step results\r\n     * \\param system The system function to solve, hence the r.h.s. of the ordinary differential equation. It must fulfill the\r\n     *               Simple System concept.\r\n     * \\param x The state of the ODE which should be solved. After calling do_step the result is updated in x.\r\n     * \\param t The value of the time, at which the step should be performed.\r\n     * \\param dt The step size.\r\n     */\r\n\r\n    /**\r\n     * \\fn void adams_bashforth::initialize( System system , StateIn &x , time_type &t , time_type dt )\r\n     * \\brief Initialized the stepper. Does Steps-1 steps with an internal instance of InitializingStepper to fill the buffer.\r\n     * \\note The state x and time t are updated to the values after Steps-1 initial steps.\r\n     * \\param system The system function to solve, hence the r.h.s. of the ordinary differential equation. It must fulfill the\r\n     *               Simple System concept.\r\n     * \\param x The initial state of the ODE which should be solved, updated in this method.\r\n     * \\param t The initial value of the time, updated in this method.\r\n     * \\param dt The step size.\r\n     */\r\n\r\n    /**\r\n     * \\fn void adams_bashforth::reset( void )\r\n     * \\brief Resets the internal buffer of the stepper.\r\n     */\r\n\r\n    /**\r\n     * \\fn bool adams_bashforth::is_initialized( void ) const\r\n     * \\brief Returns true if the stepper has been initialized.\r\n     * \\return bool true if stepper is initialized, false otherwise\r\n     */\r\n\r\n    /**\r\n     * \\fn const initializing_stepper_type& adams_bashforth::initializing_stepper( void ) const\r\n     * \\brief Returns the internal initializing stepper instance.\r\n     * \\return initializing_stepper\r\n     */\r\n\r\n    /**\r\n     * \\fn const initializing_stepper_type& adams_bashforth::initializing_stepper( void ) const\r\n     * \\brief Returns the internal initializing stepper instance.\r\n     * \\return initializing_stepper\r\n     */\r\n\r\n    /**\r\n     * \\fn initializing_stepper_type& adams_bashforth::initializing_stepper( void )\r\n     * \\brief Returns the internal initializing stepper instance.\r\n     * \\return initializing_stepper\r\n     */\r\n\r\n} // odeint\r\n} // numeric\r\n} // boost\r\n\r\n\r\n\r\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_ADAMS_BASHFORTH_HPP_INCLUDED\r\n", "meta": {"hexsha": "2bd8ff63dd66df5706ab8075c280196d6c8c83fc", "size": 15110, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/numeric/odeint/stepper/adams_bashforth.hpp", "max_stars_repo_name": "PXLVision/opengv", "max_stars_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-22T03:43:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-11T18:20:27.000Z", "max_issues_repo_path": "third_party/boost/numeric/odeint/stepper/adams_bashforth.hpp", "max_issues_repo_name": "PXLVision/opengv", "max_issues_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T16:34:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-06T17:29:22.000Z", "max_forks_repo_path": "third_party/boost/numeric/odeint/stepper/adams_bashforth.hpp", "max_forks_repo_name": "PXLVision/opengv", "max_forks_repo_head_hexsha": "e48f77da4db7b8cee36ec677ed4ff5c5354571bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 71.0, "max_forks_repo_forks_event_min_datetime": "2015-03-26T10:28:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-07T10:09:12.000Z", "avg_line_length": 36.2350119904, "max_line_length": 157, "alphanum_fraction": 0.6664460622, "num_tokens": 3555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669998, "lm_q2_score": 0.665410572017153, "lm_q1q2_score": 0.43811797459489316}}
{"text": "/* Author: Wolfgang Bangerth, University of Heidelberg, 2001 */\n\n/*    $Id: step-11.cc 27657 2012-11-21 13:19:08Z bangerth $       */\n/*                                                                */\n/*    Copyright (C) 2001-2004, 2006, 2009, 2011-2012 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n// As usual, the program starts with a rather long list of include files which\n// you are probably already used to by now:\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/table_handler.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/mapping_q.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n\n// Just this one is new: it declares a class\n// <code>CompressedSparsityPattern</code>, which we will use and explain\n// further down below.\n#include <deal.II/lac/compressed_sparsity_pattern.h>\n\n// We will make use of the std::find algorithm of the C++ standard library, so\n// we have to include the following file for its declaration:\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n\n// The last step is as in all previous programs:\nnamespace Step11\n{\n  using namespace dealii;\n\n  // Then we declare a class which represents the solution of a Laplace\n  // problem. As this example program is based on step-5, the class looks\n  // rather the same, with the sole structural difference that the functions\n  // <code>assemble_system</code> now calls <code>solve</code> itself, and is\n  // thus called <code>assemble_and_solve</code>, and that the output function\n  // was dropped since the solution function is so boring that it is not worth\n  // being viewed.\n  //\n  // The only other noteworthy change is that the constructor takes a value\n  // representing the polynomial degree of the mapping to be used later on,\n  // and that it has another member variable representing exactly this\n  // mapping. In general, this variable will occur in real applications at the\n  // same places where the finite element is declared or used.\n  template <int dim>\n  class LaplaceProblem\n  {\n  public:\n    LaplaceProblem (const unsigned int mapping_degree);\n    void run ();\n\n  private:\n    void setup_system ();\n    void assemble_and_solve ();\n    void solve ();\n\n    Triangulation<dim>   triangulation;\n    FE_Q<dim>            fe;\n    DoFHandler<dim>      dof_handler;\n    MappingQ<dim>        mapping;\n\n    SparsityPattern      sparsity_pattern;\n    SparseMatrix<double> system_matrix;\n    ConstraintMatrix     mean_value_constraints;\n\n    Vector<double>       solution;\n    Vector<double>       system_rhs;\n\n    TableHandler         output_table;\n  };\n\n\n\n  // Construct such an object, by initializing the variables. Here, we use\n  // linear finite elements (the argument to the <code>fe</code> variable\n  // denotes the polynomial degree), and mappings of given order. Print to\n  // screen what we are about to do.\n  template <int dim>\n  LaplaceProblem<dim>::LaplaceProblem (const unsigned int mapping_degree) :\n    fe (1),\n    dof_handler (triangulation),\n    mapping (mapping_degree)\n  {\n    std::cout << \"Using mapping with degree \" << mapping_degree << \":\"\n              << std::endl\n              << \"============================\"\n              << std::endl;\n  }\n\n\n\n  // The first task is to set up the variables for this problem. This includes\n  // generating a valid <code>DoFHandler</code> object, as well as the\n  // sparsity patterns for the matrix, and the object representing the\n  // constraints that the mean value of the degrees of freedom on the boundary\n  // be zero.\n  template <int dim>\n  void LaplaceProblem<dim>::setup_system ()\n  {\n    // The first task is trivial: generate an enumeration of the degrees of\n    // freedom, and initialize solution and right hand side vector to their\n    // correct sizes:\n    dof_handler.distribute_dofs (fe);\n    solution.reinit (dof_handler.n_dofs());\n    system_rhs.reinit (dof_handler.n_dofs());\n\n    // Next task is to construct the object representing the constraint that\n    // the mean value of the degrees of freedom on the boundary shall be\n    // zero. For this, we first want a list of those nodes which are actually\n    // at the boundary. The <code>DoFTools</code> class has a function that\n    // returns an array of boolean values where <code>true</code> indicates\n    // that the node is at the boundary. The second argument denotes a mask\n    // selecting which components of vector valued finite elements we want to\n    // be considered. This sort of information is encoded using the\n    // ComponentMask class (see also @ref GlossComponentMask). Since we have a\n    // scalar finite element anyway, this mask in reality should have only one\n    // entry with a <code>true</code> value. However, the ComponentMask class\n    // has semantics that allow it to represents a mask of indefinite size\n    // whose every element equals <code>true</code> when one just default\n    // constructs such an object, so this is what we'll do here.\n    std::vector<bool> boundary_dofs (dof_handler.n_dofs(), false);\n    DoFTools::extract_boundary_dofs (dof_handler,\n                                     ComponentMask(),\n                                     boundary_dofs);\n\n    // Now first for the generation of the constraints: as mentioned in the\n    // introduction, we constrain one of the nodes on the boundary by the\n    // values of all other DoFs on the boundary. So, let us first pick out the\n    // first boundary node from this list. We do that by searching for the\n    // first <code>true</code> value in the array (note that\n    // <code>std::find</code> returns an iterator to this element), and\n    // computing its distance to the overall first element in the array to get\n    // its index:\n    const unsigned int first_boundary_dof\n      = std::distance (boundary_dofs.begin(),\n                       std::find (boundary_dofs.begin(),\n                                  boundary_dofs.end(),\n                                  true));\n\n    // Then generate a constraints object with just this one constraint. First\n    // clear all previous content (which might reside there from the previous\n    // computation on a once coarser grid), then add this one line\n    // constraining the <code>first_boundary_dof</code> to the sum of other\n    // boundary DoFs each with weight -1. Finally, close the constraints\n    // object, i.e. do some internal bookkeeping on it for faster processing\n    // of what is to come later:\n    mean_value_constraints.clear ();\n    mean_value_constraints.add_line (first_boundary_dof);\n    for (unsigned int i=first_boundary_dof+1; i<dof_handler.n_dofs(); ++i)\n      if (boundary_dofs[i] == true)\n        mean_value_constraints.add_entry (first_boundary_dof,\n                                          i, -1);\n    mean_value_constraints.close ();\n\n    // Next task is to generate a sparsity pattern. This is indeed a tricky\n    // task here. Usually, we just call\n    // <code>DoFTools::make_sparsity_pattern</code> and condense the result\n    // using the hanging node constraints. We have no hanging node constraints\n    // here (since we only refine globally in this example), but we have this\n    // global constraint on the boundary. This poses one severe problem in\n    // this context: the <code>SparsityPattern</code> class wants us to state\n    // beforehand the maximal number of entries per row, either for all rows\n    // or for each row separately. There are functions in the library which\n    // can tell you this number in case you just have hanging node constraints\n    // (namely <code>DoFHandler::max_coupling_between_dofs</code>), but how is\n    // this for the present case? The difficulty arises because the\n    // elimination of the constrained degree of freedom requires a number of\n    // additional entries in the matrix at places that are not so simple to\n    // determine. We would therefore have a problem had we to give a maximal\n    // number of entries per row here.\n    //\n    // Since this can be so difficult that no reasonable answer can be given\n    // that allows allocation of only a reasonable amount of memory, there is\n    // a class <code>CompressedSparsityPattern</code>, that can help us out\n    // here. It does not require that we know in advance how many entries rows\n    // could have, but allows just about any length. It is thus significantly\n    // more flexible in case you do not have good estimates of row lengths,\n    // however at the price that building up such a pattern is also\n    // significantly more expensive than building up a pattern for which you\n    // had information in advance. Nevertheless, as we have no other choice\n    // here, we'll just build such an object by initializing it with the\n    // dimensions of the matrix and calling another function\n    // <code>DoFTools::make_sparsity_pattern</code> to get the sparsity\n    // pattern due to the differential operator, then condense it with the\n    // constraints object which adds those positions in the sparsity pattern\n    // that are required for the elimination of the constraint.\n    CompressedSparsityPattern csp (dof_handler.n_dofs(),\n                                   dof_handler.n_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler, csp);\n    mean_value_constraints.condense (csp);\n\n    // Finally, once we have the full pattern, we can initialize an object of\n    // type <code>SparsityPattern</code> from it and in turn initialize the\n    // matrix with it. Note that this is actually necessary, since the\n    // <code>CompressedSparsityPattern</code> is so inefficient compared to\n    // the <code>SparsityPattern</code> class due to the more flexible data\n    // structures it has to use, that we can impossibly base the sparse matrix\n    // class on it, but rather need an object of type\n    // <code>SparsityPattern</code>, which we generate by copying from the\n    // intermediate object.\n    //\n    // As a further sidenote, you will notice that we do not explicitly have\n    // to <code>compress</code> the sparsity pattern here. This, of course, is\n    // due to the fact that the <code>copy_from</code> function generates a\n    // compressed object right from the start, to which you cannot add new\n    // entries anymore. The <code>compress</code> call is therefore implicit\n    // in the <code>copy_from</code> call.\n    sparsity_pattern.copy_from (csp);\n    system_matrix.reinit (sparsity_pattern);\n  }\n\n\n\n  // The next function then assembles the linear system of equations, solves\n  // it, and evaluates the solution. This then makes three actions, and we\n  // will put them into eight true statements (excluding declaration of\n  // variables, and handling of temporary vectors). Thus, this function is\n  // something for the very lazy. Nevertheless, the functions called are\n  // rather powerful, and through them this function uses a good deal of the\n  // whole library. But let's look at each of the steps.\n  template <int dim>\n  void LaplaceProblem<dim>::assemble_and_solve ()\n  {\n\n    // First, we have to assemble the matrix and the right hand side. In all\n    // previous examples, we have investigated various ways how to do this\n    // manually. However, since the Laplace matrix and simple right hand sides\n    // appear so frequently in applications, the library provides functions\n    // for actually doing this for you, i.e. they perform the loop over all\n    // cells, setting up the local matrices and vectors, and putting them\n    // together for the end result.\n    //\n    // The following are the two most commonly used ones: creation of the\n    // Laplace matrix and creation of a right hand side vector from body or\n    // boundary forces. They take the mapping object, the\n    // <code>DoFHandler</code> object representing the degrees of freedom and\n    // the finite element in use, a quadrature formula to be used, and the\n    // output object. The function that creates a right hand side vector also\n    // has to take a function object describing the (continuous) right hand\n    // side function.\n    //\n    // Let us look at the way the matrix and body forces are integrated:\n    const unsigned int gauss_degree\n      = std::max (static_cast<unsigned int>(std::ceil(1.*(mapping.get_degree()+1)/2)),\n                  2U);\n    MatrixTools::create_laplace_matrix (mapping, dof_handler,\n                                        QGauss<dim>(gauss_degree),\n                                        system_matrix);\n    VectorTools::create_right_hand_side (mapping, dof_handler,\n                                         QGauss<dim>(gauss_degree),\n                                         ConstantFunction<dim>(-2),\n                                         system_rhs);\n    // That's quite simple, right?\n    //\n    // Two remarks are in order, though: First, these functions are used in a\n    // lot of contexts. Maybe you want to create a Laplace or mass matrix for\n    // a vector values finite element; or you want to use the default Q1\n    // mapping; or you want to assembled the matrix with a coefficient in the\n    // Laplace operator. For this reason, there are quite a large number of\n    // variants of these functions in the <code>MatrixCreator</code> and\n    // <code>MatrixTools</code> classes. Whenever you need a slightly\n    // different version of these functions than the ones called above, it is\n    // certainly worthwhile to take a look at the documentation and to check\n    // whether something fits your needs.\n    //\n    // The second remark concerns the quadrature formula we use: we want to\n    // integrate over bilinear shape functions, so we know that we have to use\n    // at least a Gauss2 quadrature formula. On the other hand, we want to\n    // have the quadrature rule to have at least the order of the boundary\n    // approximation. Since the order of Gauss-r is 2r, and the order of the\n    // boundary approximation using polynomials of degree p is p+1, we know\n    // that 2r@>=p+1. Since r has to be an integer and (as mentioned above)\n    // has to be at least 2, this makes up for the formula above computing\n    // <code>gauss_degree</code>.\n    //\n    // Since the generation of the body force contributions to the right hand\n    // side vector was so simple, we do that all over again for the boundary\n    // forces as well: allocate a vector of the right size and call the right\n    // function. The boundary function has constant values, so we can generate\n    // an object from the library on the fly, and we use the same quadrature\n    // formula as above, but this time of lower dimension since we integrate\n    // over faces now instead of cells:\n    Vector<double> tmp (system_rhs.size());\n    VectorTools::create_boundary_right_hand_side (mapping, dof_handler,\n                                                  QGauss<dim-1>(gauss_degree),\n                                                  ConstantFunction<dim>(1),\n                                                  tmp);\n    // Then add the contributions from the boundary to those from the interior\n    // of the domain:\n    system_rhs += tmp;\n    // For assembling the right hand side, we had to use two different vector\n    // objects, and later add them together. The reason we had to do so is\n    // that the <code>VectorTools::create_right_hand_side</code> and\n    // <code>VectorTools::create_boundary_right_hand_side</code> functions\n    // first clear the output vector, rather than adding up their results to\n    // previous contents. This can reasonably be called a design flaw in the\n    // library made in its infancy, but unfortunately things are as they are\n    // for some time now and it is difficult to change such things that\n    // silently break existing code, so we have to live with that.\n\n    // Now, the linear system is set up, so we can eliminate the one degree of\n    // freedom which we constrained to the other DoFs on the boundary for the\n    // mean value constraint from matrix and right hand side vector, and solve\n    // the system. After that, distribute the constraints again, which in this\n    // case means setting the constrained degree of freedom to its proper\n    // value\n    mean_value_constraints.condense (system_matrix);\n    mean_value_constraints.condense (system_rhs);\n\n    solve ();\n    mean_value_constraints.distribute (solution);\n\n    // Finally, evaluate what we got as solution. As stated in the\n    // introduction, we are interested in the H1 semi-norm of the\n    // solution. Here, as well, we have a function in the library that does\n    // this, although in a slightly non-obvious way: the\n    // <code>VectorTools::integrate_difference</code> function integrates the\n    // norm of the difference between a finite element function and a\n    // continuous function. If we therefore want the norm of a finite element\n    // field, we just put the continuous function to zero. Note that this\n    // function, just as so many other ones in the library as well, has at\n    // least two versions, one which takes a mapping as argument (which we\n    // make us of here), and the one which we have used in previous examples\n    // which implicitly uses <code>MappingQ1</code>.  Also note that we take a\n    // quadrature formula of one degree higher, in order to avoid\n    // superconvergence effects where the solution happens to be especially\n    // close to the exact solution at certain points (we don't know whether\n    // this might be the case here, but there are cases known of this, and we\n    // just want to make sure):\n    Vector<float> norm_per_cell (triangulation.n_active_cells());\n    VectorTools::integrate_difference (mapping, dof_handler,\n                                       solution,\n                                       ZeroFunction<dim>(),\n                                       norm_per_cell,\n                                       QGauss<dim>(gauss_degree+1),\n                                       VectorTools::H1_seminorm);\n    // Then, the function just called returns its results as a vector of\n    // values each of which denotes the norm on one cell. To get the global\n    // norm, a simple computation shows that we have to take the l2 norm of\n    // the vector:\n    const double norm = norm_per_cell.l2_norm();\n\n    // Last task -- generate output:\n    output_table.add_value (\"cells\", triangulation.n_active_cells());\n    output_table.add_value (\"|u|_1\", norm);\n    output_table.add_value (\"error\", std::fabs(norm-std::sqrt(3.14159265358/2)));\n  }\n\n\n\n  // The following function solving the linear system of equations is copied\n  // from step-5 and is explained there in some detail:\n  template <int dim>\n  void LaplaceProblem<dim>::solve ()\n  {\n    SolverControl           solver_control (1000, 1e-12);\n    SolverCG<>              cg (solver_control);\n\n    PreconditionSSOR<> preconditioner;\n    preconditioner.initialize(system_matrix, 1.2);\n\n    cg.solve (system_matrix, solution, system_rhs,\n              preconditioner);\n  }\n\n\n\n  // Finally the main function controlling the different steps to be\n  // performed. Its content is rather straightforward, generating a\n  // triangulation of a circle, associating a boundary to it, and then doing\n  // several cycles on subsequently finer grids. Note again that we have put\n  // mesh refinement into the loop header; this may be something for a test\n  // program, but for real applications you should consider that this implies\n  // that the mesh is refined after the loop is executed the last time since\n  // the increment clause (the last part of the three-parted loop header) is\n  // executed before the comparison part (the second one), which may be rather\n  // costly if the mesh is already quite refined. In that case, you should\n  // arrange code such that the mesh is not further refined after the last\n  // loop run (or you should do it at the beginning of each run except for the\n  // first one).\n  template <int dim>\n  void LaplaceProblem<dim>::run ()\n  {\n    GridGenerator::hyper_ball (triangulation);\n    static const HyperBallBoundary<dim> boundary;\n    triangulation.set_boundary (0, boundary);\n\n    for (unsigned int cycle=0; cycle<6; ++cycle, triangulation.refine_global(1))\n      {\n        setup_system ();\n        assemble_and_solve ();\n      };\n\n    // After all the data is generated, write a table of results to the\n    // screen:\n    output_table.set_precision(\"|u|_1\", 6);\n    output_table.set_precision(\"error\", 6);\n    output_table.write_text (std::cout);\n    std::cout << std::endl;\n  }\n}\n\n\n\n// Finally the main function. It's structure is the same as that used in\n// several of the previous examples, so probably needs no more explanation.\nint main ()\n{\n  try\n    {\n      dealii::deallog.depth_console (0);\n      std::cout.precision(5);\n\n      // This is the main loop, doing the computations with mappings of linear\n      // through cubic mappings. Note that since we need the object of type\n      // <code>LaplaceProblem@<2@></code> only once, we do not even name it,\n      // but create an unnamed such object and call the <code>run</code>\n      // function of it, subsequent to which it is immediately destroyed\n      // again.\n      for (unsigned int mapping_degree=1; mapping_degree<=3; ++mapping_degree)\n        Step11::LaplaceProblem<2>(mapping_degree).run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    };\n\n  return 0;\n}\n", "meta": {"hexsha": "b4a33d4fd0c85666dcf7d9a6f87bd7b4933052bf", "size": 23090, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-11/step-11.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/step-11/step-11.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/step-11/step-11.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 49.0233545648, "max_line_length": 86, "alphanum_fraction": 0.6669553919, "num_tokens": 5243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105720171531, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.43811797013487347}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//\n// THIS SOFTWARE IS PROVIDED \"AS-IS\". THERE IS NO WARRANTY OF ANY KIND.\n// NEITHER THE AUTHORS NOR THE OHIO STATE UNIVERSITY WILL BE LIABLE\n// FOR ANY DAMAGES OF ANY KIND, EVEN IF ADVISED OF SUCH POSSIBILITY.\n//\n// Copyright (c) 2010 Jyamiti Research Group.\n// CS&E Department of the Ohio State University, Columbus, OH.\n// All rights reserved.\n//\n// Author: Sayan Mandal\n//\n///////////////////////////////////////////////////////////////////////////////\n\n\n#include <iostream>\n#include <fstream>\n#include <cstdlib>\n#include <ctime>\n#include <map>\n#include <list>\n#include <vector>\n#include <cmath>\n#include <sstream>\n#include <unordered_set>\n#include <string>\n#include <sys/stat.h>\n#include <cstddef>\n\n#ifndef INFINITY\n#define INFINITY std::numeric_limits< double >::infinity()\n#endif // INFINITY\n\n#include <boost/config.hpp>\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/timer.hpp>\n#include <boost/progress.hpp>\n#include <boost/geometry.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/edmonds_karp_max_flow.hpp>\n//#include <boost/graph/read_dimacs.hpp>\n#include <boost/graph/graph_utility.hpp>\n\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/reader_utils.h>\n#include <gudhi/Bitmap_cubical_complex.h>\n#include <gudhi/Persistent_cohomology.h>\n// standard stuff\n\n#include<ParseCommand.h>\n#include <Legal.h>\n#include \"Graph.h\"\n\nusing namespace boost;\nusing namespace std;\nnamespace bg = boost::geometry;\n\n//extern vector<int> complexSizes;\n//extern vector<int> accumulativeSizes;\n//extern int accumulativeSize;\n//extern double fThreshold;\n//extern vector<double> vecFiltrationScale;\n//extern SimplicialTree<bool> domain_complex;\n\n\ntypedef Gudhi::cubical_complex::Bitmap_cubical_complex_base<double> Bitmap_cubical_complex_base;\ntypedef Gudhi::cubical_complex::Bitmap_cubical_complex<Bitmap_cubical_complex_base> Bitmap_cubical_complex;\ntypedef Gudhi::persistent_cohomology::Field_Zp Field_Zp;\ntypedef Gudhi::persistent_cohomology::Persistent_cohomology<Bitmap_cubical_complex, Field_Zp> Persistent_cohomology;\n\nextern map <int,int> threesimplex_to_node; // maps index of tetrahedrons from simplex->first to dual-graph-nodes->second\nextern map <int,int> twosimplex_to_tri; // maps index of traingles from simplex->first to dual-graph-edges->second\nextern map <int,int> threesimplex_to_node_rev; // maps index of tetrahedrons from dual-graph-nodes->first to simplex->second\nextern map <int,int> twosimplex_to_tri_rev; // maps index of traingles from dual-graph-edges->first to simplex->second\nextern map<size_t, vector<int>>  sizescale;//0- edge, 1- vertex, for each deathindex, count of vertex and edges\nextern vector<double> x;\nextern vector<double> y;\nextern vector<double> z;\nextern map<unsigned long,unsigned long> vertind; // vertex index in cubical complex(first) to actual index in x,y,z, filter\n\n\nstruct cmp_intervals_by_dim_then_length {\n    explicit cmp_intervals_by_dim_then_length(Bitmap_cubical_complex * sc)\n    : sc_(sc) { }\n    template<typename Persistent_interval>\n    bool operator()(const Persistent_interval & p1, const Persistent_interval & p2) {\n        if (sc_->dimension(get < 0 > (p1)) == sc_->dimension(get < 0 > (p2)))\n            return (sc_->filtration(get < 1 > (p1)) - sc_->filtration(get < 0 > (p1))\n                    > sc_->filtration(get < 1 > (p2)) - sc_->filtration(get < 0 > (p2)));\n        else\n            return (sc_->dimension(get < 0 > (p1)) > sc_->dimension(get < 0 > (p2)));\n    }\n    Bitmap_cubical_complex* sc_;\n};\n\nBitmap_cubical_complex buildComplex(const char* file) {\n    \n    bool dbg = false;\n    std::ifstream inFiltration;\n    inFiltration.open(file);\n    \n    unsigned dimensionOfData;\n    inFiltration >> dimensionOfData;\n    \n    if (dbg) {\n        std::cerr << \"dimensionOfData : \" << dimensionOfData << std::endl;\n    }\n    \n    std::vector<unsigned> sizes;\n    sizes.reserve(dimensionOfData);\n    // all dimensions multiplied\n    std::size_t dimensions = 1;\n    size_t top_dim = 1;\n    for (std::size_t i = 0; i != dimensionOfData; ++i) {\n        unsigned size_in_this_dimension;\n        inFiltration >> size_in_this_dimension;\n        sizes.push_back(size_in_this_dimension - 1);\n        dimensions *= (size_in_this_dimension);\n        top_dim *= (size_in_this_dimension - 1);\n        if (dbg) {\n            std::cerr << \"size_in_this_dimension : \" << size_in_this_dimension << std::endl;\n        }\n    }\n    if (dbg) {\n        std::cerr << \"Top dimension names : \" << top_dim << std::endl;\n    }\n    \n    //Create a blank Cubical Complex\n    vector<double> top_dim_cells(top_dim, 0);\n    Bitmap_cubical_complex b(sizes, top_dim_cells);\n    double filtrationLevel;\n    \n    vector<size_t> indices_to_consider;\n    \n    //Assign values to vertices\n    //Bitmap_cubical_complex::Skeleton_simplex_iterator it(&b, 0);\n    for (Bitmap_cubical_complex::Skeleton_simplex_iterator it = b.skeleton_simplex_range(0).begin();\n         it != b.skeleton_simplex_range(0).end(); it++) {\n        if (!(inFiltration >> filtrationLevel) || (inFiltration.eof())) {\n            throw std::ios_base::failure(\"Bad Perseus file format.\");\n        }\n        if (dbg) {\n            std::cerr << \"Cell of an index : \" << (*it)\n            << \" and dimension: \" << b.get_dimension_of_a_cell(*it)\n            << \" get the value : \" << filtrationLevel << std::endl;\n        }\n        b.get_cell_data(*it) = filtrationLevel;\n        size_t s = (*it);\n        indices_to_consider.push_back(s);\n        \n    }\n    vector<bool> is_this_cell_considered(b.num_simplices(), false);\n    while (indices_to_consider.size()) {\n        if (dbg) {\n            std::cerr << \"indices_to_consider in this iteration \\n\";\n            for (std::size_t i = 0; i != indices_to_consider.size(); ++i) {\n                std::cout << indices_to_consider[i] << \"  \";\n            }\n        }\n        std::vector<std::size_t> new_indices_to_consider;\n        for (std::size_t i = 0; i != indices_to_consider.size(); ++i) {\n            std::vector<std::size_t> bd = b.get_coboundary_of_a_cell(indices_to_consider[i]);\n            for (std::size_t boundaryIt = 0; boundaryIt != bd.size(); ++boundaryIt) {\n                if (dbg) {\n                    std::cerr << \"filtration of a cell : \" << bd[boundaryIt] << \" is : \" << b.filtration(bd[boundaryIt])\n                    << \" while of a cell: \" << indices_to_consider[i] << \" is: \" << b.filtration(indices_to_consider[i])\n                    << std::endl;\n                }\n                if (b.filtration(bd[boundaryIt]) < b.filtration(indices_to_consider[i])) {\n                    b.get_cell_data(bd[boundaryIt]) = b.filtration(indices_to_consider[i]);\n                    if (dbg) {\n                        std::cerr << \"Setting the value of a cell : \" << bd[boundaryIt]\n                        << \" to : \" << b.filtration(indices_to_consider[i]) << std::endl;\n                    }\n                }\n                if (is_this_cell_considered[bd[boundaryIt]] == false) {\n                    new_indices_to_consider.push_back(bd[boundaryIt]);\n//                    if (b.get_dimension_of_a_cell(bd[boundaryIt]) == dimensionOfData - 1) {\n//                        edges->push_back(bd[boundaryIt]);\n//                    }\n                    is_this_cell_considered[bd[boundaryIt]] = true;\n                }\n            }\n        }\n        indices_to_consider.swap(new_indices_to_consider);\n    }\n    \n    \n    \n    b.initialize_simplex_associated_to_key();\n//cub = b;\n    return b;\n}\n\n\nint main(int argc, char *argv[] )\n{\n    int dimensions, noPoints, currentEdgeSize = 0, barcode_count = 0, scalecount = 0;\n    int filtration = 0, totinsCount = 0, numbars = 0, index = 0, gap = 0;\n  \n  string point_file, tr_file, to_file;\n  std::vector<bg::model::point<double, 3, bg::cs::cartesian>> vPoint;\n  bool verbose;\n    ParseCommand(argc, argv,  point_file, numbars, verbose, index, gap);\n//  Simplex_tree simplexTree;\n  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n    cout<<\"Point_file: \"<<point_file; //getchar();\n    // THIS LINE GENERATES THE CUBICAL COMPLEX\n    Bitmap_cubical_complex cub(point_file.c_str());//buildComplex(point_file.c_str());//(//\n//    c = ;\n    // Compute the persistence diagram of the complex\n    Persistent_cohomology pcoh(cub);\n    \n    int p = 2;\n    double min_persistence = 0;\n    vector<size_t> birthiv, deathiv;\n    pcoh.init_coefficients(p);  // initializes the coefficient field for homology\n    pcoh.compute_persistent_cohomology(min_persistence);\n  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n    ofstream spers(point_file+\"_pers\");\n    ofstream fpers(point_file+\"_filtpers\");\n    \n    \n    cmp_intervals_by_dim_then_length cmp(&cub);\n    auto persistent_pairs = pcoh.get_persistent_pairs();\n    cout<<\" persistent_pairs: \"<<persistent_pairs.size()<<\"\\n\";\n    if(verbose)\n        getchar();\n    sort(std::rbegin(persistent_pairs), std::rend(persistent_pairs), cmp);\n\n    for (auto pair : persistent_pairs) {\n        if(cub.dimension(get<0>(pair))!=2)\n            continue;\n        \n        birthiv.push_back(get<0>(pair));\n        deathiv.push_back(get<1>(pair));\n    }\n    \n    if(birthiv.size()<numbars)\n    {\n        cout<<\"Not enough 2-cycles: \"<<birthiv.size()<<\" \"<<numbars<<endl;\n        getchar();\n        exit(0);\n    }\n//        birthiv.erase(birthiv.begin(),birthiv.end()-numbars);\n//        deathiv.erase(deathiv.begin(),deathiv.end()-numbars);\n    if(verbose){\n        cout<<\"birth size: \"<<birthiv.size()<<\" \"<<deathiv.size()<<\" numbers: \"<<numbars<<\" gaps: \"<<gap;\n    getchar();\n    }\n    birthiv.erase(birthiv.begin(),birthiv.end()-numbars-gap);\n    deathiv.erase(deathiv.begin(),deathiv.end()-numbars-gap);\n    birthiv.erase(birthiv.end()-gap,birthiv.end());\n    deathiv.erase(deathiv.end()-gap,deathiv.end());\n    buildFullCubicSetting(cub, point_file, deathiv);        // GRAPH BUILDING\n    cout<<\"Sizes: \"<<birthiv.size()<<\" \"<<deathiv.size()<<\" \"<<numbars<<\" \"<<(birthiv.size()-numbars);\n    if(verbose)\n     getchar();\n\n    for(int gotonumbars=birthiv.size()-1; gotonumbars >= 0; gotonumbars--){\n\n        size_t birthi = birthiv[gotonumbars];\n        size_t deathi = deathiv[gotonumbars];\n//        cout<<\"birthi: \"<<birthi<<\" deathi:\"<<deathi<<endl;\n//        cout.setf(ios::fixed);\n        \n        spers<<\"2 \"<<to_string(int(birthi))<<\" \"<<to_string(int(deathi))<<\"\\n\";\n        fpers<<\"2 \"<<to_string(float(cub.filtration(birthi)))<<\" \"<<to_string(float(cub.filtration(deathi)))<<\"\\n\";\n        if(verbose){\n            cout<<\"birthi: \"<<birthi<<\" deathi:\"<<deathi<<endl;\n            getchar();\n            \n        }\n        \n        \n        \n        vector<vector<int>> rGraph;\n        vector<vector<int>> vectri\n        = boostCut( cub, birthi, deathi, verbose);\n//        = minCut(adjMatrix, threesimplex_to_node[death], adjMatrix.size()-1, rGraph );\n        cout<<\" Found Boykov Komolov cut.\\n\"; //getchar();\n        string ind = point_file;\n\n        string dir_path = ind+\"loops/\";\n\n        boost::filesystem::path dir(dir_path.c_str());\n        boost::filesystem::create_directory(dir_path.c_str());\n        string ff = ind+\"loops/\"+to_string(int(birthi))+\"_\"+to_string(int(deathi))+\".off\";\n        tr_file = ind+\"loops/\"+to_string(int(birthi))+\"_\"+to_string(int(deathi))+\".txt\";\n        to_file = ind+\"loops/\"+to_string(int(birthi))+\"_\"+to_string(int(deathi))+\".off\";\n        string cu_file = ind+\"loops/\"+to_string(int(birthi))+\"_\"+to_string(int(deathi))+\"cub.txt\";\n        cout<<\"tr_file:\"<<tr_file<<endl;\n//        writeToFile( cub, vectri, birthi, deathi, tr_file);//\n        writeToFileOFF( cub, vectri, birthi, deathi, to_file);\n        cout<<\"Written to TEXT: \"<<gotonumbars<<\" vec: \"<<birthiv.size()<<\" current index:\"<<gotonumbars<<endl; //getchar();\n\n    }\n  \n    threesimplex_to_node.clear();\n    twosimplex_to_tri.clear();\n    threesimplex_to_node_rev.clear();\n    twosimplex_to_tri_rev.clear();\n    sizescale.clear();\n    x.clear();\n    y.clear();\n    z.clear();\n    vertind.clear();\n\n\n\n  return EXIT_SUCCESS;\n}//end of main\n \n", "meta": {"hexsha": "672feb18bd76c37f877c6132b0088b52245f8af2", "size": 12380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pers2cyc_fin/src/twocyc.cpp", "max_stars_repo_name": "Sayan-m90/Minimum-Persistent-Cycles", "max_stars_repo_head_hexsha": "071f2a9f4d31f2ecbcd7e6e963ec9db3cc30b120", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pers2cyc_fin/src/twocyc.cpp", "max_issues_repo_name": "Sayan-m90/Minimum-Persistent-Cycles", "max_issues_repo_head_hexsha": "071f2a9f4d31f2ecbcd7e6e963ec9db3cc30b120", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-11-07T14:35:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T14:18:00.000Z", "max_forks_repo_path": "pers2cyc_fin/src/twocyc.cpp", "max_forks_repo_name": "Sayan-m90/Minimum-Persistent-Cycles", "max_forks_repo_head_hexsha": "071f2a9f4d31f2ecbcd7e6e963ec9db3cc30b120", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9308176101, "max_line_length": 137, "alphanum_fraction": 0.6124394184, "num_tokens": 3116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.6584175072643413, "lm_q1q2_score": 0.4381179526600261}}
{"text": "#include \"alpha_shapes.hpp\"\n#include <boost/lexical_cast.hpp>\n#include <iostream>\n\nint main(int argc, char* argv[]){\n\tif(argc != 2){\n\t\tstd::cout << \"usage: \" << argv[0] << \" <alpha>\" << std::endl;\n\t\treturn 1;\n\t}\n\tdouble alpha = boost::lexical_cast<double>(argv[1]);\n\n\tunsigned int num_edges, num_triangles, num_tetrahedra;\n\tdouble points[] = {\n\t\t.2,.2,.2,\n\t\t1,0,0,\n\t\t0,1,0,\n\t\t0,0,1,\n\t\t.7,.7,.7\n\t};\n\tdouble weights[] = {\n\t\t1, 1, 1, 1, 1\n\t};\n\tunsigned int* edges;\n\tunsigned int* triangles;\n\tunsigned int* tetrahedra;\n\n\talpha_shapes(\n\t\t5, alpha, points, weights,\n\t\t&num_edges, &edges, \n\t\t&num_triangles, &triangles, \n\t\t&num_tetrahedra, &tetrahedra\n\t);\n\t\n\tstd::cout << \"Tetra \" << num_tetrahedra << std::endl;\n\tfor(unsigned int i = 0; i < num_tetrahedra*4; i+=4){\n\t\tfor(unsigned int j = 0; j < 4; ++j){\n\t\t\tstd::cout << \"\\t\" << tetrahedra[i+j];\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\tstd::cout << \"Tri \" << num_triangles << std::endl;\n\tfor(unsigned int i = 0; i < num_triangles*3; i+=3){\n\t\tfor(unsigned int j = 0; j < 3; ++j){\n\t\t\tstd::cout << \"\\t\" << triangles[i+j];\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\tstd::cout << \"Edge \" << num_edges << std::endl;\n\tfor(unsigned int i = 0; i < num_edges*2; i+=2){\n\t\tfor(unsigned int j = 0; j < 2; ++j){\n\t\t\tstd::cout << \"\\t\" << edges[i+j];\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "26baac2809271117f7ac32fd7fbab7d58d956b89", "size": 1313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/alpha_shapes/inex_unfinished/test.cpp", "max_stars_repo_name": "academicRobot/mmstructlib", "max_stars_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/alpha_shapes/inex_unfinished/test.cpp", "max_issues_repo_name": "academicRobot/mmstructlib", "max_issues_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/alpha_shapes/inex_unfinished/test.cpp", "max_forks_repo_name": "academicRobot/mmstructlib", "max_forks_repo_head_hexsha": "76949620c9e9ca26faf10ff1a21c6fda1a564f5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5245901639, "max_line_length": 63, "alphanum_fraction": 0.5742574257, "num_tokens": 491, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4380853668330579}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <stdexcept>\n#include <functional>\n#include <arc_utilities/arc_helpers.hpp>\n#include <Eigen/Geometry>\n\n#ifdef ENABLE_PARALLEL_COMPLETE_LINK_CLUSTERING\n    #include <omp.h>\n#endif\n\n#ifndef SIMPLE_HIERARCHICAL_CLUSTERING_HPP\n#define SIMPLE_HIERARCHICAL_CLUSTERING_HPP\n\nnamespace simple_hierarchical_clustering\n{\n    enum CLUSTER_STRATEGY { SINGLE_LINK, COMPLETE_LINK };\n\n    class SimpleHierarchicalClustering\n    {\n    private:\n\n        SimpleHierarchicalClustering() {}\n\n        static inline size_t GetNumOMPThreads()\n        {\n#ifdef ENABLE_PARALLEL_COMPLETE_LINK_CLUSTERING\n            size_t num_threads = 0;\n            #pragma omp parallel\n            {\n                num_threads = (size_t)omp_get_num_threads();\n            }\n            return num_threads;\n#else\n            return 1;\n#endif\n        }\n\n        static std::pair<std::pair<std::pair<bool, int64_t>, std::pair<bool, int64_t>>, double> GetClosestPair(const std::vector<uint8_t>& datapoint_mask, const Eigen::MatrixXd& distance_matrix, const std::vector<std::vector<int64_t>>& clusters, const CLUSTER_STRATEGY strategy)\n        {\n            // Compute distances between unclustered points <-> unclustered points, unclustered_points <-> clusters, and clusters <-> clusters\n            // Compute the minimum unclustered point <-> unclustered point / unclustered_point <-> cluster distance\n#ifdef ENABLE_PARALLEL_COMPLETE_LINK_CLUSTERING\n            const size_t num_threads = GetNumOMPThreads();\n            std::vector<double> per_thread_min_distances(num_threads, INFINITY);\n            std::vector<std::pair<int64_t, std::pair<bool, int64_t>>> per_thread_min_element_pairs(num_threads, std::make_pair(-1, std::make_pair(false, -1)));\n            #pragma omp parallel for\n#else\n            double min_distance = INFINITY;\n            std::pair<int64_t, std::pair<bool, int64_t>> min_element_pair(-1, std::pair<bool, int64_t>(false, -1));\n#endif\n            for (size_t idx = 0; idx < datapoint_mask.size(); idx++)\n            {\n                // Make sure we aren't in a cluster already\n                if (datapoint_mask[idx] == 0)\n                {\n                    // Compute the minimum unclustered point <-> unclustered point distance\n                    double min_point_point_distance = INFINITY;\n                    int64_t min_point_index = -1;\n                    for (size_t jdx = 0; jdx < datapoint_mask.size(); jdx++)\n                    {\n                        // Make sure the other point isn't us, and isn't already in a cluster\n                        if ((idx != jdx) && (datapoint_mask[jdx] == 0))\n                        {\n                            const double& current_distance = distance_matrix((ssize_t)idx, (ssize_t)jdx);\n                            // Update the closest point\n                            if (current_distance < min_point_point_distance)\n                            {\n                                min_point_point_distance = current_distance;\n                                min_point_index = (int64_t)jdx;\n                            }\n                        }\n                    }\n                    // Compute the minimum unclustered point <-> cluster distance\n                    double min_point_cluster_distance = INFINITY;\n                    int64_t min_cluster_index = -1;\n                    for (size_t cdx = 0; cdx < clusters.size(); cdx++)\n                    {\n                        // We only work with clusters that aren't empty\n                        if (clusters[cdx].size() > 0)\n                        {\n                            // Compute the distance to the current cluster\n                            double complete_link_distance = 0.0;\n                            double single_link_distance = INFINITY;\n                            for (size_t cpdx = 0; cpdx < clusters[cdx].size(); cpdx++)\n                            {\n                                const int64_t& current_cluster_point_index = clusters[cdx][cpdx];\n                                const double& new_distance = distance_matrix((ssize_t)idx, (ssize_t)current_cluster_point_index);\n                                complete_link_distance = std::max(complete_link_distance, new_distance);\n                                single_link_distance = std::min(single_link_distance, new_distance);\n                            }\n                            const double current_distance = (strategy == COMPLETE_LINK) ? complete_link_distance : single_link_distance;\n                            // Update the closest cluster\n                            if (current_distance < min_point_cluster_distance)\n                            {\n                                min_point_cluster_distance = current_distance;\n                                min_cluster_index = (int64_t)cdx;\n                            }\n                        }\n                    }\n#ifdef ENABLE_PARALLEL_COMPLETE_LINK_CLUSTERING\n                    const size_t thread_num = (size_t)omp_get_thread_num();\n                    double& per_thread_min_distance = per_thread_min_distances[thread_num];\n                    std::pair<int64_t, std::pair<bool, int64_t>>& per_thread_min_element_pair = per_thread_min_element_pairs[thread_num];\n                    // Update the closest index\n                    if (min_point_point_distance < per_thread_min_distance)\n                    {\n                        per_thread_min_distance = min_point_point_distance;\n                        per_thread_min_element_pair.first = idx;\n                        per_thread_min_element_pair.second.first = false;\n                        per_thread_min_element_pair.second.second = min_point_index;\n                    }\n                    if (min_point_cluster_distance < per_thread_min_distance)\n                    {\n                        per_thread_min_distance = min_point_cluster_distance;\n                        per_thread_min_element_pair.first = idx;\n                        per_thread_min_element_pair.second.first = true;\n                        per_thread_min_element_pair.second.second = min_cluster_index;\n                    }\n#else\n                    // Update the closest index\n                    if (min_point_point_distance < min_distance)\n                    {\n                        min_distance = min_point_point_distance;\n                        min_element_pair.first = (int64_t)idx;\n                        min_element_pair.second.first = false;\n                        min_element_pair.second.second = min_point_index;\n                    }\n                    if (min_point_cluster_distance < min_distance)\n                    {\n                        min_distance = min_point_cluster_distance;\n                        min_element_pair.first = (int64_t)idx;\n                        min_element_pair.second.first = true;\n                        min_element_pair.second.second = min_cluster_index;\n                    }\n#endif\n                }\n            }\n#ifdef ENABLE_PARALLEL_COMPLETE_LINK_CLUSTERING\n            double min_distance = INFINITY;\n            std::pair<int64_t, std::pair<bool, int64_t>> min_element_pair(-1, std::pair<bool, int64_t>(false, -1));\n            for (size_t idx = 0; idx < num_threads; idx++)\n            {\n                const double& current_min_distance = per_thread_min_distances[idx];\n                const std::pair<int64_t, std::pair<bool, int64_t>>& current_min_element_pair = per_thread_min_element_pairs[idx];\n                if (current_min_distance < min_distance)\n                {\n                    min_distance = current_min_distance;\n                    min_element_pair = current_min_element_pair;\n                }\n            }\n#endif\n            // Compute the minimum cluster <-> cluster distance\n#ifdef ENABLE_PARALLEL_COMPLETE_LINK_CLUSTERING\n            std::vector<double> per_thread_min_cluster_cluster_distances(num_threads, INFINITY);\n            std::vector<std::pair<int64_t, int64_t>> per_thread_min_cluster_pairs(num_threads, std::make_pair(-1, -1));\n            #pragma omp parallel for\n#else\n            double min_cluster_cluster_distance = INFINITY;\n            std::pair<int64_t, int64_t> min_cluster_pair(-1, -1);\n#endif\n            for (size_t fcdx = 0; fcdx < clusters.size(); fcdx++)\n            {\n                const std::vector<int64_t>& first_cluster = clusters[fcdx];\n                // Don't evaluate empty clusters\n                if (first_cluster.size() > 0)\n                {\n                    for (size_t scdx = 0; scdx < clusters.size(); scdx++)\n                    {\n                        // Don't compare against ourself\n                        if (fcdx != scdx)\n                        {\n                            const std::vector<int64_t>& second_cluster = clusters[scdx];\n                            // Don't evaluate empty clusters\n                            if (second_cluster.size() > 0)\n                            {\n                                // Compute the cluster <-> cluster distance\n                                double complete_link_distance = 0.0;\n                                double single_link_distance = INFINITY;\n                                // Find the maximum-pointwise distance between clusters\n                                for (size_t fcpx = 0; fcpx < first_cluster.size(); fcpx++)\n                                {\n                                    const int64_t& fcp_index = first_cluster[fcpx];\n                                    for (size_t scpx = 0; scpx < second_cluster.size(); scpx++)\n                                    {\n                                        const int64_t& scp_index = second_cluster[scpx];\n                                        const double& new_distance = distance_matrix(fcp_index, scp_index);\n                                        complete_link_distance = std::max(complete_link_distance, new_distance);\n                                        single_link_distance = std::min(single_link_distance, new_distance);\n                                    }\n                                }\n                                const double cluster_cluster_distance = (strategy == COMPLETE_LINK) ? complete_link_distance : single_link_distance;\n#ifdef ENABLE_PARALLEL_COMPLETE_LINK_CLUSTERING\n                                const size_t thread_num = (size_t)omp_get_thread_num();\n                                double& per_thread_min_cluster_cluster_distance = per_thread_min_cluster_cluster_distances[thread_num];\n                                std::pair<int64_t, int64_t>& per_thread_min_cluster_pair = per_thread_min_cluster_pairs[thread_num];\n                                if (cluster_cluster_distance < per_thread_min_cluster_cluster_distance)\n                                {\n                                    per_thread_min_cluster_cluster_distance = cluster_cluster_distance;\n                                    per_thread_min_cluster_pair.first = fcdx;\n                                    per_thread_min_cluster_pair.second = scdx;\n                                }\n#else\n                                if (cluster_cluster_distance < min_cluster_cluster_distance)\n                                {\n                                    min_cluster_cluster_distance = cluster_cluster_distance;\n                                    min_cluster_pair.first = (int64_t)fcdx;\n                                    min_cluster_pair.second = (int64_t)scdx;\n                                }\n#endif\n                            }\n                        }\n                    }\n                }\n            }\n#ifdef ENABLE_PARALLEL_COMPLETE_LINK_CLUSTERING\n            double min_cluster_cluster_distance = INFINITY;\n            std::pair<int64_t, int64_t> min_cluster_pair(-1, -1);\n            for (size_t idx = 0; idx < num_threads; idx++)\n            {\n                const double& current_min_cluster_cluster_distance = per_thread_min_cluster_cluster_distances[idx];\n                const std::pair<int64_t, int64_t>& current_min_cluster_pair = per_thread_min_cluster_pairs[idx];\n                if (current_min_cluster_cluster_distance < min_cluster_cluster_distance)\n                {\n                    min_cluster_cluster_distance = current_min_cluster_cluster_distance;\n                    min_cluster_pair = current_min_cluster_pair;\n                }\n            }\n#endif\n            // Return the minimum-distance pair\n            if (min_distance < min_cluster_cluster_distance)\n            {\n                // Set the indices\n                const std::pair<bool, int64_t> first_index(false, min_element_pair.first);\n                const std::pair<bool, int64_t> second_index = min_element_pair.second;\n                const std::pair<std::pair<bool, int64_t>, std::pair<bool, int64_t>> indices(first_index, second_index);\n                const std::pair<std::pair<std::pair<bool, int64_t>, std::pair<bool, int64_t>>, double> minimum_pair(indices, min_distance);\n                return minimum_pair;\n            }\n            // A cluster <-> cluster pair is closest\n            else\n            {\n                // Set the indices\n                const std::pair<bool, int64_t> first_index(true, min_cluster_pair.first);\n                const std::pair<bool, int64_t> second_index(true, min_cluster_pair.second);\n                const std::pair<std::pair<bool, int64_t>, std::pair<bool, int64_t>> indices(first_index, second_index);\n                const std::pair<std::pair<std::pair<bool, int64_t>, std::pair<bool, int64_t>>, double> minimum_pair(indices, min_cluster_cluster_distance);\n                return minimum_pair;\n            }\n        }\n\n    public:\n\n        template<typename Datatype, typename Allocator=std::allocator<Datatype>>\n        static std::pair<std::vector<std::vector<Datatype, Allocator>>, double> Cluster(const std::vector<Datatype, Allocator>& data, const std::function<double(const Datatype&, const Datatype&)>& distance_fn, const double max_cluster_distance, const CLUSTER_STRATEGY strategy)\n        {\n#ifdef ENABLE_PARALLEL_COMPLETE_LINK_CLUSTERING\n            const Eigen::MatrixXd distance_matrix = arc_helpers::BuildDistanceMatrixParallel(data, distance_fn);\n#else\n            const Eigen::MatrixXd distance_matrix = arc_helpers::BuildDistanceMatrixSerial(data, distance_fn);\n#endif\n            return Cluster(data, distance_matrix, max_cluster_distance, strategy);\n        }\n\n        template<typename Datatype, typename Allocator=std::allocator<Datatype>>\n        static std::pair<std::vector<std::vector<Datatype, Allocator>>, double> Cluster(const std::vector<Datatype, Allocator>& data, const Eigen::MatrixXd& distance_matrix, const double max_cluster_distance, const CLUSTER_STRATEGY strategy)\n        {\n            assert((size_t)distance_matrix.rows() == data.size());\n            assert((size_t)distance_matrix.cols() == data.size());\n            std::vector<uint8_t> datapoint_mask(data.size(), 0u);\n            std::vector<std::vector<int64_t>> cluster_indices;\n            double closest_distance = 0.0;\n            bool complete = false;\n            while (!complete)\n            {\n                // Get closest pair of elements (an element can be a cluster or single data value!)\n                const std::pair<std::pair<std::pair<bool, int64_t>, std::pair<bool, int64_t>>, double> closest_element_pair = GetClosestPair(datapoint_mask, distance_matrix, cluster_indices, strategy);\n                const std::pair<std::pair<bool, int64_t>, std::pair<bool, int64_t>>& closest_elements = closest_element_pair.first;\n                closest_distance = closest_element_pair.second;\n                //std::cout << \"Element pair: \" << PrettyPrint::PrettyPrint(closest_element_pair, true) << std::endl;\n                if (closest_distance <= max_cluster_distance)\n                {\n                    const std::pair<bool, int64_t>& first_element = closest_elements.first;\n                    const std::pair<bool, int64_t>& second_element = closest_elements.second;\n                    // If both elements are points, create a new cluster\n                    if ((first_element.first == false) && (second_element.first == false))\n                    {\n                        //std::cout << \"New point-point cluster\" << std::endl;\n                        const int64_t first_element_index = first_element.second;\n                        assert(first_element_index >= 0);\n                        const int64_t second_element_index = second_element.second;\n                        assert(second_element_index >= 0);\n                        // Add a cluster\n                        cluster_indices.push_back(std::vector<int64_t>{first_element_index, second_element_index});\n                        // Mask out the indices\n                        datapoint_mask[(size_t)first_element_index] = 1u;\n                        datapoint_mask[(size_t)second_element_index] = 1u;\n                    }\n                    // If both elements are clusters, merge the clusters\n                    else if ((first_element.first == true) && (second_element.first == true))\n                    {\n                        //std::cout << \"Combining clusters\" << std::endl;\n                        // Get the cluster indices\n                        const int64_t first_cluster_index = first_element.second;\n                        assert(first_cluster_index >= 0);\n                        const int64_t second_cluster_index = second_element.second;\n                        assert(second_cluster_index >= 0);\n                        // Merge the second cluster into the first\n                        std::vector<int64_t>& first_cluster = cluster_indices[(size_t)first_cluster_index];\n                        std::vector<int64_t>& second_cluster = cluster_indices[(size_t)second_cluster_index];\n                        first_cluster.insert(first_cluster.end(), second_cluster.begin(), second_cluster.end());\n                        // Empty the second cluster (we don't remove, because this triggers move)\n                        second_cluster.clear();\n                    }\n                    // If one of the elements is a cluster and the other is a point, add the point to the existing cluster\n                    else\n                    {\n                        //std::cout << \"Adding to an existing cluster\" << std::endl;\n                        int64_t cluster_index = -1;\n                        int64_t element_index = -1;\n                        if (first_element.first)\n                        {\n                            cluster_index = first_element.second;\n                            element_index = second_element.second;\n                        }\n                        else if (second_element.first)\n                        {\n                            cluster_index = second_element.second;\n                            element_index = first_element.second;\n                        }\n                        else\n                        {\n                            assert(false);\n                        }\n                        assert(cluster_index >= 0);\n                        assert(element_index >= 0);\n                        // Add the element to the cluster\n                        std::vector<int64_t>& cluster = cluster_indices[(size_t)cluster_index];\n                        cluster.push_back(element_index);\n                        // Mask out the element index\n                        datapoint_mask[(size_t)element_index] = 1u;\n                    }\n                }\n                else\n                {\n                    complete = true;\n                }\n            }\n            // Extract the actual cluster data\n            std::vector<std::vector<Datatype, Allocator>> clusters;\n            for (size_t idx = 0; idx < cluster_indices.size(); idx++)\n            {\n                const std::vector<int64_t>& current_cluster = cluster_indices[idx];\n                // Ignore empty clusters\n                if (current_cluster.size() > 0)\n                {\n                    std::vector<Datatype, Allocator> new_cluster;\n                    for (size_t cdx = 0; cdx < current_cluster.size(); cdx++)\n                    {\n                        const int64_t index = current_cluster[cdx];\n                        new_cluster.push_back(data[(size_t)index]);\n                    }\n                    clusters.push_back(new_cluster);\n                }\n            }\n            // Add any points that we haven't clustered into their own clusters\n            for (size_t idx = 0; idx < datapoint_mask.size(); idx++)\n            {\n                // If an element hasn't been clustered at all\n                if (datapoint_mask[idx] == 0)\n                {\n                    clusters.push_back(std::vector<Datatype, Allocator>{data[idx]});\n                }\n            }\n            return std::pair<std::vector<std::vector<Datatype, Allocator>>, double>(clusters, closest_distance);\n        }\n    };\n}\n#endif // SIMPLE_HIERARCHICAL_CLUSTERING_HPP\n", "meta": {"hexsha": "ce47e0f87234ef4f0a28ec2edb798c3e9749a8b6", "size": 21143, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arc_utilities/simple_hierarchical_clustering.hpp", "max_stars_repo_name": "ToyotaResearchInstitute/arc_utilities", "max_stars_repo_head_hexsha": "f15a1dfd9fba5ca83296354bae8b97628895c1c2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/arc_utilities/simple_hierarchical_clustering.hpp", "max_issues_repo_name": "ToyotaResearchInstitute/arc_utilities", "max_issues_repo_head_hexsha": "f15a1dfd9fba5ca83296354bae8b97628895c1c2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/arc_utilities/simple_hierarchical_clustering.hpp", "max_forks_repo_name": "ToyotaResearchInstitute/arc_utilities", "max_forks_repo_head_hexsha": "f15a1dfd9fba5ca83296354bae8b97628895c1c2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-11-06T21:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-06T21:38:23.000Z", "avg_line_length": 55.0598958333, "max_line_length": 278, "alphanum_fraction": 0.5379085276, "num_tokens": 3839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4379941434170671}}
{"text": "\n\n#include\"main.hpp\"\n#include\"Option.hpp\"\n#include\"Pre.hpp\"\n#include\"Post.hpp\"\n\n#include <boost/math/distributions/hypergeometric.hpp>\n\n\nvoid Post::fdr(vector<map<double,fdrs,greater<double> > >& fdr,const int up)\n{\n    fdr.resize(1?1:d_pr.nl());\n    for (unsigned l=0;l<d_pr.nl();l++) {\n        map<double,fdrs,greater<double> >& fdr_l(fdr.at(fdr.size()==1?0:l));\n        for (unsigned p=0;p<d_pr.np();p++) {\n            fdr_l[up==-1 or d_up.at(l).at(p)==up?pr().cp().at(p).at(l):0].t++;\n        }\n    }\n    for (unsigned l=0;l<fdr.size();l++) {\n        map<double,fdrs,greater<double> >& fdr_l(fdr.at(l));\n        int denom=fdr_l.begin()->second.t;\n        double numer=(1-fdr_l.begin()->first)*denom;\n        map<double,fdrs>::iterator it=fdr_l.begin();\n        for (it++;it!=fdr_l.end();it++) {\n            it->second.fdr=numer/denom;\n            numer += (1-it->first)*it->second.t;\n            denom += it->second.t;\n        }\n    }\n}\n\n\nvoid Post::selection(vector<vector<int> >& sel,const vector<map<double,fdrs,greater<double> > >& fdr,const int up)\n{\n    double minCPS=1;\n    for (unsigned l=0;l<d_pr.nl();l++) {\n        const map<double,fdrs,greater<double> >& fdr_l(fdr.at(fdr.size()==1?0:l));\n        sel.at(l).assign(d_pr.np(),0);\n        for (unsigned p=0;p<d_pr.np();p++) {\n            if (fdr_l.at(up==-1 or d_up.at(l).at(p)==up?pr().cp().at(p).at(l):0).fdr<d_op.FDRcut()) {\n                sel.at(l).at(p)=1;\n                if (pr().cp().at(p).at(l)<minCPS) minCPS=pr().cp().at(p).at(l);\n            }\n        }\n    }\n}\n\n\nvoid Post::test(const vector<vector<int> >& sel,vector<vector<double> >& pval,const int up)\n{\n    for (unsigned l=0;l<d_pr.nl();l++) {\n        const int r=accumulate(sel.at(l).begin(),sel.at(l).end(),0);\n        for (unsigned g=0;g<d_pr.ng();g++) {\n            int sum=0;\n            for (unsigned m=0;m<d_pr.mem().at(g).size();m++) {\n                sum+=sel.at(l).at(d_pr.mem().at(g).at(m));\n            }\n            boost::math::hypergeometric a(r, d_pr.mem().at(g).size(), d_pr.np());\n            pval.at(l).at(g)=cdf(complement(a,sum))+pdf(a,sum);\n        }\n    }\n}\n\n\nPost::Post(const Pre& pr) :\n    d_op(pr.op()),d_pr(pr),d_up(pr.nl()),d_selup(pr.nl()),d_seldown(pr.nl()),d_selsig(pr.nl()),d_pvup(pr.nl(),vector<double>(pr.ng())),d_pvdown(pr.nl(),vector<double>(pr.ng())),d_pvsig(pr.nl(),vector<double>(pr.ng()))\n{\n    if (op().selbool()) {\n        d_selup=pr.selup();\n    } else {\n        for (unsigned l=0;l<d_pr.nl();l++) {\n            d_up.at(l).assign(d_pr.np(),0);\n            for (unsigned p=0;p<d_pr.np();p++) {\n                if (d_pr.R().at(p).at(l)<d_pr.R().at(p).at(l+1)) d_up.at(l).at(p)=1;\n            }\n        }\n        fdr(d_fdrup,1);\n        selection(d_selup,d_fdrup,1);\n    }\n    test(d_selup,d_pvup,1);\n\n    if (op().selbool()) {\n        d_seldown=pr.seldown();\n    } else {\n        fdr(d_fdrdown,0);\n        selection(d_seldown,d_fdrdown,0);\n    }\n    test(d_seldown,d_pvdown,0);\n\n    if (op().selbool()) {\n        d_selsig=pr.selsig();\n    } else {\n        fdr(d_fdrsig,-1);\n        selection(d_selsig,d_fdrsig,-1);\n    }\n    test(d_selsig,d_pvsig,-1);\n}\n", "meta": {"hexsha": "4caa509dfd7a1036c5ffc58c253f041f14c062a0", "size": 3126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "peca_gsa/src/Post.cpp", "max_stars_repo_name": "PECAplus/PECAplus_cmd_line", "max_stars_repo_head_hexsha": "3e84ef1c6e59925bf5a9552beb86c022392b94d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-08T05:45:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-08T05:45:08.000Z", "max_issues_repo_path": "peca_gsa/src/Post.cpp", "max_issues_repo_name": "PECAplus/PECAplus_cmd_line", "max_issues_repo_head_hexsha": "3e84ef1c6e59925bf5a9552beb86c022392b94d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-07-09T13:20:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-15T17:22:23.000Z", "max_forks_repo_path": "peca_gsa/src/Post.cpp", "max_forks_repo_name": "PECAplus/PECAplus_cmd_line", "max_forks_repo_head_hexsha": "3e84ef1c6e59925bf5a9552beb86c022392b94d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-02-01T09:03:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-09T13:00:40.000Z", "avg_line_length": 31.5757575758, "max_line_length": 217, "alphanum_fraction": 0.5230326296, "num_tokens": 1002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619263765706, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.43796190328101803}}
{"text": "#include \"newton_solver.h\"\n\n#include \"store.h\"\n#include \"acap_solve_energy_gradient.h\"\n#include \"muscle_energy_gradient.h\"\n#include \"stablenh_energy_gradient.h\"\n#include <igl/polar_dec.h>\n#include <Eigen/LU>\n#include <Eigen/Cholesky>\n#include <igl/Timer.h>\n\nusing Store = famu::Store;\nusing namespace Eigen;\nusing namespace std;\n\ndouble famu::Energy(Store& store, VectorXd& dFvec){\n\tdouble EM = famu::muscle::energy(store, dFvec);\n\tdouble ENH = famu::stablenh::energy(store, dFvec);\n\tdouble EACAP = famu::acap::fastEnergy(store, dFvec);\n\n\treturn EM + ENH + EACAP;\n}\n\nvoid famu::polar_dec(Store& store, VectorXd& dFvec){\n\tif(store.jinput[\"polar_dec\"]){\n\t\t//project bones dF back to rotations\n\t\tif(store.jinput[\"reduced\"]){\n\t\t\tfor(int b =0; b < store.bone_tets.size(); b++){\n\t\t\t\tEigen::Matrix3d _r, _t;\n\t\t\t\tMatrix3d dFb = Map<Matrix3d>(dFvec.segment<9>(9*b).data()).transpose();\n\t\t\t\tigl::polar_dec(dFb, _r, _t);\n\n\t\t\t\tdFvec[9*b+0] = _r(0,0);\n\t      \t\tdFvec[9*b+1] = _r(0,1);\n\t      \t\tdFvec[9*b+2] = _r(0,2);\n\t      \t\tdFvec[9*b+3] = _r(1,0);\n\t      \t\tdFvec[9*b+4] = _r(1,1);\n\t      \t\tdFvec[9*b+5] = _r(1,2);\n\t      \t\tdFvec[9*b+6] = _r(2,0);\n\t      \t\tdFvec[9*b+7] = _r(2,1);\n\t      \t\tdFvec[9*b+8] = _r(2,2);\n\t\t\t\n\t\t\t}\n\n\t\t}else{\n\t\t\tfor(int t = 0; t < store.bone_tets.size(); t++){\n\t\t\t\tfor(int i=0; i<store.bone_tets[t].size(); i++){\n\t\t\t\t\tint b =store.bone_tets[t][i];\n\n\t\t\t\t\tEigen::Matrix3d _r, _t;\n\t\t\t\t\tMatrix3d dFb = Map<Matrix3d>(dFvec.segment<9>(9*b).data()).transpose();\n\t\t\t\t\tigl::polar_dec(dFb, _r, _t);\n\n\t\t\t\t\tdFvec[9*b+0] = _r(0,0);\n\t\t      \t\tdFvec[9*b+1] = _r(0,1);\n\t\t      \t\tdFvec[9*b+2] = _r(0,2);\n\t\t      \t\tdFvec[9*b+3] = _r(1,0);\n\t\t      \t\tdFvec[9*b+4] = _r(1,1);\n\t\t      \t\tdFvec[9*b+5] = _r(1,2);\n\t\t      \t\tdFvec[9*b+6] = _r(2,0);\n\t\t      \t\tdFvec[9*b+7] = _r(2,1);\n\t\t      \t\tdFvec[9*b+8] = _r(2,2);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\ndouble famu::line_search(int& tot_ls_its, Store& store, VectorXd& grad, VectorXd& drt){\n\t// Decreasing and increasing factors\n\tVectorXd x = store.dFvec;\n\tVectorXd xp = x;\n\tdouble step = 50;\n    const double dec = 0.5;\n    const double inc = 2.1;\n    int pmax_linesearch = 100;\n    int plinesearch = 1;//1 for armijo, 2 for wolfe\n    double pftol = 1e-4;\n    double pwolfe = 0.9;\n    double pmax_step = 1e8;\n    double pmin_step = 1e-20;\n\n\n    // Check the value of step\n    if(step <= double(0))\n        std::invalid_argument(\"'step' must be positive\");\n\n    polar_dec(store, x);\n    famu::acap::solve(store, x);\n   \tdouble fx = Energy(store, x);\n    // Save the function value at the current x\n    const double fx_init = fx;\n    // Projection of gradient on the search direction\n    const double dg_init = grad.dot(drt);\n    // Make sure d points to a descent direction\n    if(dg_init > 0)\n        std::logic_error(\"the moving direction increases the objective function value\");\n\n    const double dg_test = pftol * dg_init;\n    double width;\n\n\n    int iter;\n    for(iter = 0; iter < pmax_linesearch; iter++)\n    {\n        // x_{k+1} = x_k + step * d_k\n        x.noalias() = xp + step * drt;\n        polar_dec(store, x);\n\n        // Evaluate this candidate\n        famu::acap::solve(store, x);\n       \tfx = Energy(store, x);\n\n        if(fx > fx_init + step * dg_test)\n        {\n            width = dec;\n        } else {\n            // Armijo condition is met\n            if(plinesearch == 1)\n                break;\n\n            const double dg = grad.dot(drt);\n            if(dg < pwolfe * dg_init)\n            {\n                width = inc;\n            } else {\n                // Regular Wolfe condition is met\n                if(plinesearch == 2)\n                    break;\n\n                if(dg > -pwolfe * dg_init)\n                {\n                    width = dec;\n                } else {\n                    // Strong Wolfe condition is met\n                    break;\n                }\n            }\n        }\n\n        if(iter >= pmax_linesearch)\n            throw std::runtime_error(\"the line search routine reached the maximum number of iterations\");\n\n        if(step < pmin_step)\n            throw std::runtime_error(\"the line search step became smaller than the minimum value allowed\");\n\n        if(step > pmax_step)\n            throw std::runtime_error(\"the line search step became larger than the maximum value allowed\");\n\n        step *= width;\n    }\n    // cout<<\"\t\t\tls iters: \"<<iter<<endl;\n    // cout<<\"\t\t\tstep: \"<<step<<endl;\n    tot_ls_its += iter;\n    return step;\n}\n\nvoid famu::sparse_to_dense(const Store& store, SparseMatrix<double, Eigen::RowMajor>& H, MatrixXd& denseHess){\n\t//Fill denseHess with 9x9 block diags from H\n\t//TODO: this should be done in the hessians code. coeffRef is expensive\n\t//FIX AFTER THE DEADLINE\n\n\t#pragma omp parallel for\n\tfor(int i=0; i<store.dFvec.size()/9; i++){\n\t\t//loop through 9x9 block and fill denseH\n\t\tMatrix9d A;\n\t\t#pragma omp parallel for collapse(2)\n\t\tfor(int j =0; j<9; j++){\n\t\t\tfor(int k=0; k<9; k++){\n\t\t\t\tA(j, k) = H.coeffRef(9*i + j, 9*i +k);\n\t\t\t}\n\t\t}\n\t\tdenseHess.block<9,9>(9*i, 0) = A;\n\t}\n}\n\nvoid famu::fastWoodbury(Store& store, const VectorXd& g, MatrixModesxModes X, VectorXd& BInvXDy, MatrixXd& denseHess, VectorXd& drt){\n\t//Woodbury parallel approach 1 (with reduction)\n\n\tMatrix<double, NUM_MODES, 1> DAg = Matrix<double, NUM_MODES, 1>::Zero(); \n\tMatrix<double, NUM_MODES, 1> InvXDAg;\n\tFullPivLU<MatrixModesxModes> WoodburyDenseSolve;\n\n\tdouble aa = store.jinput[\"alpha_arap\"];\n\tX = store.InvC*aa;\n\t#pragma omp parallel\n\t{\n\t\tMatrixModesxModes Xpriv = MatrixModesxModes::Zero();\n\t\tMatrix<double, NUM_MODES, 1> DAgpriv = Matrix<double, NUM_MODES, 1>::Zero(); \n\n\t\t#pragma omp for\n\t\tfor(int i=0; i<store.dFvec.size()/9; i++){\n\t\t\tMatrix9d A = denseHess.block<9,9>(9*i, 0);\n\t\t\tLDLT<Matrix9d> InvA;\n\t\t\tInvA.compute(A);\n\t\t\tstore.vecInvA[i] = InvA;\n\n\t\t\tVector9d invAg = InvA.solve(g.segment<9>(9*i));\n\t\t\tdrt.segment<9>(9*i) = invAg;\n\n\t\t\tMatrix9xModes B = store.WoodB.block<9, NUM_MODES>(9*i, 0);\n\t\t\tXpriv = Xpriv + -B.transpose()*InvA.solve(B);\n\n\t\t\tDAgpriv  = DAgpriv + -B.transpose()*invAg;\n\t\t}\n\t\t#pragma omp critical\n\t\t{\n\t\t\tX += Xpriv;\n\t\t\tDAg += DAgpriv;\n\t\t}\n\t}\n\n\t#pragma omp single\n\t{\n\n\t\tWoodburyDenseSolve.compute(X);\n\t\tInvXDAg = WoodburyDenseSolve.solve(DAg);\n\n\t}\n\n\t#pragma omp parallel for\n\tfor(int i=0; i<store.dFvec.size()/9; i++){\n\t\tMatrix9xModes B = store.WoodB.block<9, NUM_MODES>(9*i, 0);\n\n\t\tVector9d InvAtemp1 = store.vecInvA[i].solve(B*InvXDAg);\n\t\tdrt.segment<9>(9*i) -=  InvAtemp1;\n\t}\n\n\tdrt *= -1;\n}\n\nint famu::newton_static_solve(Store& store){\n\tint MAX_ITERS = store.jinput[\"NM_MAX_ITERS\"];\n\tVectorXd muscle_grad, neo_grad, acap_grad;\n\tmuscle_grad.resize(store.dFvec.size());\n\tneo_grad.resize(store.dFvec.size());\n\tacap_grad.resize(store.dFvec.size());\n\t\n\tSparseMatrix<double, Eigen::RowMajor> constHess(store.dFvec.size(), store.dFvec.size());\n\tconstHess.setZero();\n\n\n\n\tconstHess = store.neoHess + store.muscleHess + store.acapHess;// + store.ContactHess;\n\tconstHess -= store.neoHess;\n\n\tMatrixXd denseHess = MatrixXd::Zero(store.dFvec.size(),  9);\n\tMatrixXd constDenseHess = MatrixXd::Zero(store.dFvec.size(),  9);\n\tsparse_to_dense(store, constHess, constDenseHess);\n\n\tVectorXd delta_dFvec = VectorXd::Zero(store.dFvec.size());\n\tVectorXd test_drt = delta_dFvec;\n\tVectorXd grad_dofs = VectorXd::Zero(store.dFvec.size());\n\t\n\tVectorXd BInvXDy = VectorXd::Zero(store.dFvec.size());\n\tMatrixModesxModes X;\n\t\t\n\tigl::Timer timer, timer1;\n\tdouble woodtimes =0;\n\tdouble linetimes =0;\n\tint tot_ls_its = 0;\n\tint iter =1;\n\ttimer1.start();\n\tfor(iter=1; iter<MAX_ITERS; iter++){\n\t\tgrad_dofs.setZero();\n\t\tdouble prevfx = Energy(store, store.dFvec);\n\n\t\tfamu::acap::solve(store, store.dFvec);\n\t\tfamu::muscle::gradient(store, muscle_grad);\n\t\tfamu::stablenh::gradient(store, neo_grad);\n\t\tfamu::acap::fastGradient(store, acap_grad);\n\t\tgrad_dofs = muscle_grad + neo_grad + acap_grad;\n\n\t\t// cout<<\"\t\tmuscle grad: \"<<muscle_grad.norm()<<endl;\n\t\t// cout<<\"\t\tneo grad: \"<<neo_grad.norm()<<endl;\n\t\t// cout<<\"\t\tacap grad: \"<<acap_grad.norm()<<endl;\n\t\t// cout<<\"\t\ttotal grad: \"<<grad_dofs.norm()<<endl;\n\t\t\n\t\tif(grad_dofs != grad_dofs){\n\t\t\tcout<<\"Error: nans in grad\"<<endl;\n\t\t\texit(0);\n\t\t}\n\n\t\t\n\t\tfamu::stablenh::hessian(store, store.neoHess, store.denseNeoHess, store.jinput[\"woodbury\"]);\n\n\t\t// if(!store.jinput[\"woodbury\"]){\n\t\t\t\n\t\t// SparseMatrix<double, Eigen::RowMajor> hessFvec = store.neoHess + constHess;\n\t\t// store.NM_SPLU.factorize(hessFvec);\n\t\t// if(store.NM_SPLU.info()!=Success){\n\t\t// \tcout<<\"SOLVER FAILED\"<<endl;\n\t\t// \tcout<<store.NM_SPLU.info()<<endl;\n\t\t// }\n\t\t// delta_dFvec = -1*store.NM_SPLU.solve(grad_dofs);\n\t\t\n\t\t// }else{\n\n\t\t\t// //Sparse Woodbury code\n\t\t\t// hessFvec.setZero();\n\t\t\t// hessFvec = store.neoHess + constHess;\n\t\t\t// store.NM_SPLU.factorize(hessFvec);\n\t\t\t// if(store.NM_SPLU.info()!=Success){\n\t\t\t// \tcout<<\"SOLVER FAILED\"<<endl;\n\t\t\t// \tcout<<store.NM_SPLU.info()<<endl;\n\t\t\t// }\n\t\t\t// VectorXd InvAg = store.NM_SPLU.solve(grad_dofs);\n\t\t\t// MatrixXd CDAB = store.InvC + store.WoodD*store.NM_SPLU.solve(store.WoodB);\n\t\t\t// FullPivLU<MatrixXd>  WoodburyDenseSolve;\n\t\t\t// WoodburyDenseSolve.compute(CDAB);\n\t\t\t// VectorXd temp1 = store.WoodB*WoodburyDenseSolve.solve(store.WoodD*InvAg);;\n\n\t\t\t// VectorXd InvAtemp1 = store.NM_SPLU.solve(temp1);\n\t\t\t// test_drt =  -InvAg + InvAtemp1;\n\n\t\t\t//Dense Woodbury code\n\t\t\tdenseHess = constDenseHess + store.denseNeoHess;\n\t\t\ttimer.start();\n\t\t\tfastWoodbury(store, grad_dofs, X, BInvXDy, denseHess, delta_dFvec);\n\t\t\ttimer.stop();\n\t\t\twoodtimes += timer.getElapsedTimeInMicroSec();\n\t\t\t// cout<<\"\t\twoodbury diff: \"<<(delta_dFvec - test_drt).norm()<<endl;\n\n\t\t// }\n\n\t\tif(delta_dFvec != delta_dFvec){\n\t\t\tcout<<\"Error: nans\"<<endl;\n\t\t\texit(0);\n\t\t}\n\t\t\n\t\t//line search\n\t\tdouble alpha = 0.1;\n\t\ttimer.start();\n\t\talpha = line_search(tot_ls_its, store, grad_dofs, delta_dFvec);\n\t\ttimer.stop();\n\t\tlinetimes += timer.getElapsedTimeInMicroSec();\n\n\t\tif(fabs(alpha)<1e-9 ){\n\t\t\tbreak;\n\t\t}\n\n\t\tstore.dFvec += alpha*delta_dFvec;\n\t\tpolar_dec(store, store.dFvec);\n\t\tdouble fx = Energy(store, store.dFvec);\n\n\t\t\n\n\t\tif(grad_dofs.squaredNorm()/grad_dofs.size()<1e-4 || fabs(fx - prevfx)<1e-3){\n\t\t\tbreak;\n\t\t}\n\t}\n\ttimer1.stop();\n\tdouble nmtime = timer1.getElapsedTimeInMicroSec();\n\n\t// timer1.start();\n\t// double acap_energy = famu::acap::fastEnergy(store, store.dFvec);\n\t// timer1.stop();\n\t// double energy_time = timer1.getElapsedTimeInMicroSec();\n\n\t// timer1.start();\n\t// famu::acap::solve(store, store.dFvec);\n\t// timer1.stop();\n\n\tcout<<\"-----------QS STEP INFO----------\"<<endl;\n\tcout<<\"V, T:\"<<store.V.rows()<<\", \"<<store.T.rows()<<endl;\n\tcout<<\"Threads: \"<<Eigen::nbThreads()<<endl;\n\tcout<<\"NM Iters: \"<<iter<<endl;\n\tcout<<\"Total NM time: \"<<nmtime<<endl;\n\t// cout<<\"Total Hess time: \"<<woodtimes<<endl;\n\t// cout<<\"Total LS time: \"<<linetimes<<endl;\n\t// cout<<\"LS iters: \"<<tot_ls_its<<endl;\n\t// cout<<\"Energy: \"<<acap_energy<<endl;\n\t// cout<<\"Energy Time: \"<<energy_time<<endl;\n\t// cout<<\"ACAP time: \"<<timer1.getElapsedTimeInMicroSec()<<endl;\n\t// cout<<\"dFvec: \"<<store.dFvec.transpose()<<endl;\n\tcout<<\"--------------------------------\"<<endl;\n    return iter;\n}", "meta": {"hexsha": "e38af205231e301a9a534683a03d701747bd6689", "size": 10981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "famu/newton_solver.cpp", "max_stars_repo_name": "itsvismay/fast_muscles", "max_stars_repo_head_hexsha": "86c9d93bd14da92ce2140bf47857810b579e7b2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T22:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-02T01:38:52.000Z", "max_issues_repo_path": "famu/newton_solver.cpp", "max_issues_repo_name": "itsvismay/fast_muscles", "max_issues_repo_head_hexsha": "86c9d93bd14da92ce2140bf47857810b579e7b2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-08T21:10:36.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-08T21:10:36.000Z", "max_forks_repo_path": "famu/newton_solver.cpp", "max_forks_repo_name": "itsvismay/fast_muscles", "max_forks_repo_head_hexsha": "86c9d93bd14da92ce2140bf47857810b579e7b2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-08T21:11:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-08T21:11:10.000Z", "avg_line_length": 29.0502645503, "max_line_length": 133, "alphanum_fraction": 0.6163373099, "num_tokens": 3619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4378532191633746}}
{"text": "/*====================================================================\n   Simple pendulum example\n   Copyright (c) 2017 Matthew Millard <matthew.millard@iwr.uni-heidelberg.de>\n   Licensed under the zlib license. See LICENSE for more details.\n *///=================================================================\n\n\n#include <string>\n#include <iostream>\n#include <stdio.h> \n#include <rbdl/rbdl.h>\n#include \"csvtools.h\"\n\n#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp>\n#include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n#include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>\n#include <boost/numeric/odeint/stepper/generation/make_controlled.hpp>\n//using namespace std;\nusing namespace boost::numeric::odeint;\n\n\n#ifndef RBDL_BUILD_ADDON_LUAMODEL\n    #error \"Error: RBDL addon LuaModel not enabled.\"\n#endif\n\n#include <rbdl/addons/luamodel/luamodel.h>\n\nusing namespace RigidBodyDynamics;\nusing namespace RigidBodyDynamics::Math;\n\n\n\n//====================================================================\n// Boost stuff\n//====================================================================\n\ntypedef std::vector< double > state_type;\n\ntypedef runge_kutta_cash_karp54< state_type > error_stepper_type;\ntypedef controlled_runge_kutta< error_stepper_type > controlled_stepper_type;\n\n\nclass rbdlToBoost {\n\n    public:\n        rbdlToBoost(Model* model) : model(model) {\n            q = VectorNd::Zero(model->dof_count);\n            qd = VectorNd::Zero(model->dof_count);\n            qdd = VectorNd::Zero(model->dof_count);\n            tau = VectorNd::Zero(model->dof_count);\n\n        }\n\n        //3c. Boost uses this 'operator()' function to evaluate the state\n        //    derivative of the pendulum.\n        void operator() (const state_type &x, \n                         state_type &dxdt, \n                         const double t){\n\n            //3d. Here we split out q (generalized positions) and qd \n            //    (generalized velocities) from the x (state vector)\n            //q\n            int j = 0;            \n            for(int i=0; i<model->dof_count; i++){                \n                q[i] = (double)x[j];\n                j++;\n            }\n\n            //qd\n            for(int i=0; i<model->dof_count; i++){                \n                qd[i] = (double)x[j];\n                j++;\n            }\n\n            //3e. Here we set the applied generalized forces to zero\n            for(int i=0; i<model->dof_count; i++){                \n                tau[i] = 0;\n            }\n\n            //3f. RBDL's ForwardDynamics function is used to evaluate\n            //    qdd (generalized accelerations)\n            ForwardDynamics (*model,q,qd,tau,qdd);\n\n            //3g. Here qd, and qdd are used to populate dxdt \n            //(the state derivative)\n            j = 0;\n            for(int i = 0; i < model->dof_count; i++){\n                dxdt[j] = (double)qd[i];\n                j++;\n            }            \n            for(int i = 0; i < model->dof_count; i++){\n                dxdt[j] = (double)qdd[i];\n                j++;\n            }\n\n\n        }\n\n    private:\n        Model* model;\n        VectorNd q, qd, qdd, tau;\n};\n\nstruct pushBackStateAndTime\n{\n    std::vector< state_type >& states;\n    std::vector< double >& times;\n\n    pushBackStateAndTime( std::vector< state_type > &states , \n                              std::vector< double > &times )\n    : states( states ) , times( times ) { }\n\n    void operator()( const state_type &x , double t )\n    {\n        states.push_back( x );\n        times.push_back( t );\n    }\n};\n\nvoid f(const state_type &x, state_type &dxdt, const double t);\n\n/* Problem Constants */\nint main (int argc, char* argv[]) {\n    rbdl_check_api_version (RBDL_API_VERSION);\n\n\n    //problem specific constants\n    int     nPts    = 100;\n    double  t0      = 0;\n    double  t1      = 3;\n\n\n    //Integration settings\n    double absTolVal   = 1e-10;\n    double relTolVal   = 1e-6;\n\n    VectorNd q, qd;\n\n    Model* model  = NULL;\n    model         = new Model();\n\n    //3a. The Lua model is read in here, and turned into a series of \n    //    vectors and matricies in model which RBDL uses to evaluate \n    //    dynamics quantities\n    if (!Addons::LuaModelReadFromFile (\"./../model/pendulum.lua\", \n                                       model, false)             ){        \n        std::cerr     << \"Error loading model ./model/pendulum.lua\" \n                    << std::endl;\n        abort();\n    }\n\n    q       = VectorNd::Zero (model->dof_count);\n    qd      = VectorNd::Zero (model->dof_count);\n\n    double t        = 0;             //time\n    double ts       = 0;            //scaled time\n    double dtsdt    = M_PI/(t1-t0);    //dertivative scaled time \n                                    //w.r.t. time\n\n    printf(\"DoF: %i\\n\",model->dof_count);\n\n\n    printf(\"Forward Dynamics \\n\");\n\n    //3b. Here we instantiate a wrapper class which is needed so that \n    //    Boost can evaluate the state derivative of the model.\n    rbdlToBoost rbdlModel(model);\n    state_type xState(2);\n    int steps = 0;\n    xState[0] = -M_PI/4.0;\n    xState[1] = 0;\n\n\n    double dt   = (t1-t0)/((double)nPts);    \n\n\n    double ke, pe = 0;\n\n\n\n    std::vector<std::vector< double > > matrixData;\n    std::vector<std::vector< double > > matrixErrorData;\n    std::vector< double > rowData(model->dof_count+1);\n    std::vector< double > rowErrorData(2);\n\n    double a_x = 1.0 , a_dxdt = 1.0;\n    controlled_stepper_type  \n    controlled_stepper(\n        default_error_checker< double , \n                               range_algebra , \n                               default_operations >\n        ( absTolVal , relTolVal , a_x , a_dxdt ) );\n    \n\n    double tp = 0;\n    rowData[0] = 0;\n    for(int z=0; z < model->dof_count; z++){\n        rowData[z+1] = xState[model->dof_count + z];\n    }\n    matrixData.push_back(rowData);\n\n    double kepe0 = 0;\n\n    printf(\"Columns\\n\");\n    printf(\"      t,         q,       qd,       ke,        pe,   ke+pe-(kepe0)\\n\");\n    for(int i = 0; i <= nPts; i++){\n\n        t = t0 + dt*i;\n\n        //3h. Here we integrate forward in time between a series of nPts from\n        //    t0 to t1\n        integrate_adaptive( \n            controlled_stepper ,\n            rbdlModel , xState , tp , t , (t-tp)/10 );\n        tp = t;\n\n        //3i. At each point the state, kinetic (ke), and potential energy (pe) \n        //    is evaluated. In this conservative system the sum of kinetic and\n        //    potential energy should be constant. Any error that accumulates\n        //    is due to the cumulation of integration error.\n\n        q[0]  = xState[0];\n        qd[0] = xState[1];\n\n        pe = Utils::CalcPotentialEnergy(*model, q, true);\n        ke = Utils::CalcKineticEnergy(*model, q, qd, true);\n\n\n        printf(\"%f, %f, %f, %f, %f, %f\\n\",\n                    t, q[0],qd[0],ke,\n                    pe,(ke+pe-kepe0)); \n\n        rowData[0] = t;\n        for(int z=0; z < model->dof_count; z++){\n            rowData[z+1] = xState[z];\n        }\n        matrixData.push_back(rowData);\n\n        if(i==0) kepe0 = (ke+pe);\n\n        rowErrorData[0] = t;\n        rowErrorData[1] = (ke + pe) - kepe0;\n        matrixErrorData.push_back(rowErrorData);\n    }\n    printf(\"Columns\\n\");\n    printf(\"      t,         q,       qd,       ke,        pe,      ke+pe-(kepe0)\\n\");\n\n    //3j. Now the data we have accumulated is written to file\n    std::string header = \"\";\n    std::string fname   = \"../output/meshup.csv\";    \n    printMatrixToFile(matrixData, header, fname);\n    printf(\"Wrote: ../output/meshup.csv (meshup animation file)\\n\");\n\n    fname               = \"../output/kepe.csv\";\n    header = \"time,systemEnergy,\";\n    printMatrixToFile(matrixErrorData,header,fname);\n    printf(\"Wrote: ../output/kepe.csv (simulation data)\\n\");\n    delete model;\n\n    return 0;\n        \n}\n\n", "meta": {"hexsha": "70cb23bf18e0769ea1a33ab42e9bd66b33b263c2", "size": 7862, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/pendulum/src/pendulumForwardDynamics.cc", "max_stars_repo_name": "ju6ge/rbdl-orb", "max_stars_repo_head_hexsha": "321e20e80e2859a3a2ab43629c7c26c1020cb6f6", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-04-30T19:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T11:30:23.000Z", "max_issues_repo_path": "examples/pendulum/src/pendulumForwardDynamics.cc", "max_issues_repo_name": "ju6ge/rbdl-orb", "max_issues_repo_head_hexsha": "321e20e80e2859a3a2ab43629c7c26c1020cb6f6", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-04T23:16:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T23:37:28.000Z", "max_forks_repo_path": "examples/pendulum/src/pendulumForwardDynamics.cc", "max_forks_repo_name": "ju6ge/rbdl-orb", "max_forks_repo_head_hexsha": "321e20e80e2859a3a2ab43629c7c26c1020cb6f6", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-02-01T20:38:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T22:28:24.000Z", "avg_line_length": 29.7803030303, "max_line_length": 86, "alphanum_fraction": 0.5236581023, "num_tokens": 2055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.43782010690695883}}
{"text": "#include \"gdrawer.hpp\"\n\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/phoenix_object.hpp>\n#include <boost/spirit/include/phoenix_fusion.hpp>\n#if BOOST_VERSION >= 106000\n#include <boost/phoenix/object/new.hpp>\n#else\n#include <boost/spirit/home/phoenix/object/new.hpp>\n#endif\n#include <stdexcept>\n#include <QDebug>\n\nusing namespace boost;\nusing namespace spirit;\nusing namespace ascii;\nusing namespace phoenix;\n\ntemplate<class Iterator>\nstruct ExprGrammar : qi::grammar<Iterator, expr_t*(), ascii::space_type>\n{\n\tExprGrammar(): ExprGrammar::base_type(expr, \"Expression\")\n\t{\n\t\tprimitive.name(\"Primitive\");\n\t\tfactor.name(\"Factor\");\n\t\tterm.name(\"Term\");\n\t\texpr.name(\"Expression\");\n\n\t\tprimitive \n\t\t\t= ('(' >> expr >> ')')[_val = _1]\n\t\t\t| ('|' >> expr >> '|')[_val = new_<unop_t>('|', _1)]\n\t\t\t| (char_('a', 'z') | char_('A', 'Z'))[_val = new_<var_t>(_1)]\n\t\t\t| real[_val = new_<const_t>(_1)];\n\t\t\n\t\tprimitive2\n\t\t\t= primitive[_val = _1]\n\t\t\t| ('-' >> primitive)[_val = new_<unop_t>('-', _1)];\n\n\t\tfactor\n\t\t\t= (primitive2 >> '^' >> factor)[_val = new_<binop_t>('^', _1, _2)]\n\t\t\t| primitive2[_val = _1];\n\t\t\n\t\tterm\n\t\t\t= factor[_val = _1] >> \n\t\t\t\t*( (char_(\"/*\") >> factor)[_val = new_<binop_t>(_1, _val, _2)] \n\t\t\t\t| !char_(\"-+\") >> factor[_val = new_<binop_t>('*', _val, _1)] );\n\t\t\n\t\texpr\n\t\t\t= term[_val = _1] >> *(char_(\"+-\") >> term)[_val = new_<binop_t>(_1, _val, _2)];\n\n\t\tqi::on_error<qi::fail>\n\t\t(\n\t\t\texpr,\n\t\t\tstd::cout\n                << val(\"Error! Expecting \")\n                << _4                               // what failed?\n                << val(\" here: \\\"\")\n                << construct<std::string>(_3, _2)   // iterators to error-pos, end\n                << val(\"\\\"\")\n                << std::endl\n\t\t);\n\t\t/* qi::debug(expr); qi::debug(term); qi::debug(factor); qi::debug(primitive); qi::debug(primitive2); */\n\t}\n\t\n\tqi::rule<Iterator, expr_t*(), ascii::space_type> primitive, primitive2, factor, term, expr;\n\tqi::real_parser<real_t> real;\n};\n\nVm *MathVm::get(const QString& expr)\n{\n\texpr_t* tree = NULL;\n\tstd::string s = expr.toStdString();\n\tExprGrammar<std::string::const_iterator> g;\n\tstd::string::const_iterator begin = s.begin(), end = s.end();\n\tbool r = phrase_parse(begin, end, g, space, tree);\n\tif (!r || begin != end || !tree)\n\t{\n//\t\tqDebug() << \"end - begin = \" << int(end - begin) << \" tree \" << (long long)tree << std::endl; \n\t\tif (tree) delete tree;\n\t\tthrow Exception(\"Syntax error\");\n\t}\n\n\tMathVm *ret = new MathVm;\n\ttree->addInstr(ret);\n\tret->requiredStackSize = tree->getDepth();\n\tdelete tree;\n\treturn ret;\n}\n", "meta": {"hexsha": "fc824c15aef3f4df8ecd553bc38c3c7f192e8553", "size": 2649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/parse.cpp", "max_stars_repo_name": "bdolgov/gdrawer", "max_stars_repo_head_hexsha": "10b3a686638a1a3c8d2a189e7e6e4fe81edd408c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parse.cpp", "max_issues_repo_name": "bdolgov/gdrawer", "max_issues_repo_head_hexsha": "10b3a686638a1a3c8d2a189e7e6e4fe81edd408c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parse.cpp", "max_forks_repo_name": "bdolgov/gdrawer", "max_forks_repo_head_hexsha": "10b3a686638a1a3c8d2a189e7e6e4fe81edd408c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1098901099, "max_line_length": 105, "alphanum_fraction": 0.5960739902, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.43777224228394257}}
{"text": "//Eigen\n#include <Eigen/Core>\n\n//OpenCV\n#include <opencv2/core/core.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/calib3d.hpp>\n#include <opencv2/imgproc.hpp>\n\n//PCL\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/visualization/common/common.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/filters/statistical_outlier_removal.h>\n\n#include <chrono>\n#include <iostream>\n\n#include \"estimate_motion.h\"\n\nusing namespace p3dv;\n\nbool MotionEstimator::estimate2D2D_E5P_RANSAC(frame_t &cur_frame_1, frame_t &cur_frame_2,\n                                              std::vector<cv::DMatch> &matches, std::vector<cv::DMatch> &inlier_matches,\n                                              Eigen::Matrix4f &T, double ransac_thre, double ransac_prob, bool show)\n{\n    std::chrono::steady_clock::time_point tic = std::chrono::steady_clock::now();\n\n    std::vector<cv::Point2f> pointset1;\n    std::vector<cv::Point2f> pointset2;\n\n    for (int i = 0; i < (int)matches.size(); i++)\n    {\n        pointset1.push_back(cur_frame_1.keypoints[matches[i].queryIdx].pt);\n        pointset2.push_back(cur_frame_2.keypoints[matches[i].trainIdx].pt);\n    }\n\n    cv::Mat camera_mat;\n    cv::eigen2cv(cur_frame_1.K_cam, camera_mat);\n\n    cv::Mat essential_matrix;\n\n    cv::Mat inlier_matches_indicator;\n\n    essential_matrix = cv::findEssentialMat(pointset1, pointset2, camera_mat,\n                                            CV_RANSAC, ransac_prob, ransac_thre, inlier_matches_indicator);\n\n    std::cout << \"essential_matrix is \" << std::endl\n              << essential_matrix << std::endl;\n\n    for (int i = 0; i < (int)matches.size(); i++)\n    {\n        if (inlier_matches_indicator.at<bool>(0, i) == 1)\n        {\n            inlier_matches.push_back(matches[i]);\n        }\n    }\n\n    cv::Mat R;\n    cv::Mat t;\n\n    cv::recoverPose(essential_matrix, pointset1, pointset2, camera_mat, R, t, inlier_matches_indicator);\n\n    std::chrono::steady_clock::time_point toc = std::chrono::steady_clock::now();\n    std::chrono::duration<double> time_used = std::chrono::duration_cast<std::chrono::duration<double>>(toc - tic);\n    std::cout << \"Estimate Motion [2D-2D] cost = \" << time_used.count() << \" seconds. \" << std::endl;\n    std::cout << \"Find [\" << inlier_matches.size() << \"] inlier matches from [\" << matches.size() << \"] total matches.\" << std::endl;\n\n    Eigen::Matrix3f R_eigen;\n    Eigen::Vector3f t_eigen;\n    cv::cv2eigen(R, R_eigen);\n    cv::cv2eigen(t, t_eigen);\n    T.block(0, 0, 3, 3) = R_eigen;\n    T.block(0, 3, 3, 1) = t_eigen;\n    T(3, 0) = 0;\n    T(3, 1) = 0;\n    T(3, 2) = 0;\n    T(3, 3) = 1;\n\n    std::cout << \"Transform is \" << std::endl\n              << T << std::endl;\n\n    if (show)\n    {\n        cv::Mat ransac_match_image;\n        cv::namedWindow(\"RANSAC inlier matches\", 0);\n        cv::drawMatches(cur_frame_1.rgb_image, cur_frame_1.keypoints, cur_frame_2.rgb_image, cur_frame_2.keypoints, inlier_matches, ransac_match_image);\n        cv::imshow(\"RANSAC inlier matches\", ransac_match_image);\n        cv::waitKey(0);\n    }\n\n    return 1;\n}\n\nbool MotionEstimator::estimate2D3D_P3P_RANSAC(frame_t &cur_frame, pointcloud_sparse_t &cur_map_3d, double ransac_thre,\n                                              int iterationsCount, double ransac_prob, bool show)\n{\n    std::chrono::steady_clock::time_point tic = std::chrono::steady_clock::now();\n\n    cv::Mat camera_mat;\n    cv::eigen2cv(cur_frame.K_cam, camera_mat);\n\n    //std::cout<< \"K Mat:\" <<std::endl<< camera_mat<<std::endl;\n\n    std::vector<cv::Point2f> pointset2d;\n    std::vector<cv::Point3f> pointset3d;\n    std::vector<int> pointset3d_index;\n\n    int count = 0;\n    float dist_thre = 300;\n\n    std::cout << \"2D points: \" << cur_frame.unique_pixel_ids.size() << std::endl\n              << \"3D points: \" << cur_map_3d.unique_point_ids.size() << std::endl;\n\n    // Construct the 2d-3d initial matchings\n    for (int i = 0; i < cur_frame.unique_pixel_ids.size(); i++)\n    {\n        for (int j = 0; j < cur_map_3d.unique_point_ids.size(); j++)\n        {\n            if (cur_frame.unique_pixel_ids[i] == cur_map_3d.unique_point_ids[j])\n            {\n\n                float x_3d = cur_map_3d.rgb_pointcloud->points[j].x;\n                float y_3d = cur_map_3d.rgb_pointcloud->points[j].y;\n                float z_3d = cur_map_3d.rgb_pointcloud->points[j].z;\n                float x_2d = cur_frame.keypoints[i].pt.x;\n                float y_2d = cur_frame.keypoints[i].pt.y;\n\n                if (std::abs(x_3d) < dist_thre && std::abs(y_3d) < dist_thre && std::abs(z_3d) < dist_thre)\n                {\n                    // Assign value for pointset2d and pointset3d\n                    pointset2d.push_back(cv::Point2f(x_2d, y_2d));\n                    //pointset2d.push_back(pixel2cam(cur_frame.keypoints[i].pt, camera_mat));\n\n                    pointset3d.push_back(cv::Point3f(x_3d, y_3d, z_3d));\n                    pointset3d_index.push_back(j);\n\n                    count++;\n                }\n                //std::cout << \"2D: \" << cur_frame.unique_pixel_ids[i] << \" \" << cur_frame.keypoints[i].pt << std::endl;\n                //std::cout << \"3D: \" << cur_map_3d.unique_point_ids[j] << \" \" << cv::Point3f(x_3d, y_3d, z_3d) << std::endl;\n            }\n        }\n    }\n\n    std::cout << count << \" initial correspondences are used.\" << std::endl;\n\n    // Use RANSAC P3P to estiamte the optimal transformation\n\n    cv::Mat distort_para = cv::Mat::zeros(1, 4, CV_64FC1); // Assuming no lens distortion\n    cv::Mat r_vec;\n    cv::Mat t_vec;\n    cv::Mat inliers;\n\n    cv::solvePnPRansac(pointset3d, pointset2d, camera_mat, distort_para, r_vec, t_vec,\n                       false, iterationsCount, ransac_thre, ransac_prob, inliers, cv::SOLVEPNP_EPNP);\n\n    //cv::solvePnP(pointset3d, pointset2d, camera_mat, distort_para, r_vec, t_vec, false, cv::SOLVEPNP_EPNP);\n\n    std::cout << \"Inlier count: \" << inliers.rows << std::endl;\n\n    std::vector<int> outlier;\n    for (int i = 0; i < inliers.rows; i++)\n    {\n        pointset3d_index[inliers.at<float>(i, 0)] = -1; // inlier 's index\n    }\n\n    for (int i = 0; i < pointset3d_index.size(); i++)\n    {\n        if (pointset3d_index[i] >= 0)\n            outlier.push_back(pointset3d_index[i]);\n    }\n    for (int i = 0; i < outlier.size(); i++)\n    {\n        cur_map_3d.is_inlier[outlier[i]] = 0;\n    }\n\n    cv::Mat R_mat;\n    cv::Rodrigues(r_vec, R_mat);\n\n    Eigen::Matrix3f R_eigen;\n    Eigen::Vector3f t_eigen;\n    Eigen::Matrix4f T_mat;\n\n    cv::cv2eigen(R_mat, R_eigen);\n    cv::cv2eigen(t_vec, t_eigen);\n\n    T_mat.block(0, 0, 3, 3) = R_eigen;\n    T_mat.block(0, 3, 3, 1) = t_eigen;\n    T_mat(3, 0) = 0;\n    T_mat(3, 1) = 0;\n    T_mat(3, 2) = 0;\n    T_mat(3, 3) = 1;\n\n    // std::cout << \"Transform is: \" << std::endl\n    //           << T_mat << std::endl;\n\n    cur_frame.pose_cam = T_mat;\n\n    // Calculate the reprojection error\n    std::vector<cv::Point2f> proj_points;\n    cv::projectPoints(pointset3d, R_mat, t_vec, camera_mat, distort_para, proj_points);\n\n    float reproj_err = 0.0;\n    for (int i = 0; i < proj_points.size(); i++)\n    {\n        float cur_repro_error = norm(proj_points[i] - pointset2d[i]);\n        reproj_err += cur_repro_error;\n\n        //std::cout << cur_repro_error << std::endl;\n    }\n\n    reproj_err /= proj_points.size();\n    double inlier_ratio = 1.0 * inliers.rows / count;\n    std::cout << \"Mean reprojection error: \" << reproj_err << std::endl;\n\n    std::chrono::steady_clock::time_point toc = std::chrono::steady_clock::now();\n    std::chrono::duration<double> time_used = std::chrono::duration_cast<std::chrono::duration<double>>(toc - tic);\n    std::cout << \"Estimate Motion [3D-2D] cost = \" << time_used.count() << \" seconds. \" << std::endl;\n\n    if (reproj_err > 10 && inlier_ratio < 0.5) // mean reprojection error is too big (may be some problem)\n    {\n        std::cout << \"[Warning] pnp may encounter some problem, the inlier ratio is [ \" << inlier_ratio * 100 << \" % ], the mean reprojection error is [ \" << reproj_err << \" ].\" << std::endl;\n        return 0;\n    }\n    else\n        return 1;\n}\n\nbool MotionEstimator::getDepthFast(frame_t &cur_frame_1, frame_t &cur_frame_2, Eigen::Matrix4f &T_21,\n                                   const std::vector<cv::DMatch> &matches, double &appro_depth, int random_rate)\n{\n    cv::Mat T1_mat;\n    cv::Mat T2_mat;\n    cv::Mat camera_mat;\n\n    Eigen::Matrix4f Teye = Eigen::Matrix4f::Identity();\n    Eigen::Matrix<float, 3, 4> T1 = Teye.block<3, 4>(0, 0);\n    Eigen::Matrix<float, 3, 4> T2 = (T_21 * Teye).block<3, 4>(0, 0);\n\n    cv::eigen2cv(cur_frame_1.K_cam, camera_mat);\n    cv::eigen2cv(T1, T1_mat);\n    cv::eigen2cv(T2, T2_mat);\n\n    std::vector<cv::Point2f> pointset1;\n    std::vector<cv::Point2f> pointset2;\n\n    for (int i = 0; i < matches.size(); i++)\n    {\n        if (i % random_rate == 0)\n        {\n            pointset1.push_back(pixel2cam(cur_frame_1.keypoints[matches[i].queryIdx].pt, camera_mat));\n            pointset2.push_back(pixel2cam(cur_frame_2.keypoints[matches[i].trainIdx].pt, camera_mat));\n        }\n    }\n\n    cv::Mat pts_3d_homo;\n    if (pointset1.size() > 0)\n        cv::triangulatePoints(T1_mat, T2_mat, pointset1, pointset2, pts_3d_homo);\n\n    // De-homo and calculate mean depth\n    double depth_sum = 0;\n    for (int i = 0; i < pts_3d_homo.cols; i++)\n    {\n        cv::Mat pts_3d = pts_3d_homo.col(i);\n\n        pts_3d /= pts_3d.at<float>(3, 0);\n\n        Eigen::Vector3f pt_temp;\n        pt_temp(0) = pts_3d.at<float>(0, 0);\n        pt_temp(1) = pts_3d.at<float>(1, 0);\n        pt_temp(2) = pts_3d.at<float>(2, 0);\n\n        depth_sum = depth_sum + pt_temp.norm();\n    }\n    appro_depth = depth_sum / pts_3d_homo.cols;\n\n    std::cout << \"Mean relative depth is about \" << appro_depth << \" * baseline length. \" << std::endl;\n}\n\nbool MotionEstimator::doTriangulation(frame_t &cur_frame_1, frame_t &cur_frame_2,\n                                      const std::vector<cv::DMatch> &matches,\n                                      pointcloud_sparse_t &sparse_pointcloud, bool show)\n{\n    std::chrono::steady_clock::time_point tic = std::chrono::steady_clock::now();\n\n    cv::Mat T1_mat;\n    cv::Mat T2_mat;\n    cv::Mat camera_mat;\n\n    Eigen::Matrix<float, 3, 4> T1 = cur_frame_1.pose_cam.block(0, 0, 3, 4);\n    Eigen::Matrix<float, 3, 4> T2 = cur_frame_2.pose_cam.block(0, 0, 3, 4);\n\n    cv::eigen2cv(cur_frame_1.K_cam, camera_mat);\n    cv::eigen2cv(T1, T1_mat);\n    cv::eigen2cv(T2, T2_mat);\n\n    // std::cout<<camera_mat<<std::endl;\n    // std::cout<<T1_mat<<std::endl;\n    // std::cout<<T2_mat<<std::endl;\n\n    std::vector<cv::Point2f> pointset1;\n    std::vector<cv::Point2f> pointset2;\n\n    int count_newly_triangu = 0;\n    for (int i = 0; i < matches.size(); i++)\n    {\n        bool already_in_world = 0;\n        for (int k = 0; k < sparse_pointcloud.unique_point_ids.size(); k++)\n        {\n            if (sparse_pointcloud.unique_point_ids[k] == cur_frame_1.unique_pixel_ids[matches[i].queryIdx])\n            {\n                already_in_world = 1;\n                break;\n            }\n        }\n        if (!already_in_world)\n        {\n            sparse_pointcloud.unique_point_ids.push_back(cur_frame_1.unique_pixel_ids[matches[i].queryIdx]);\n            sparse_pointcloud.is_inlier.push_back(1);\n\n            pointset1.push_back(pixel2cam(cur_frame_1.keypoints[matches[i].queryIdx].pt, camera_mat));\n            pointset2.push_back(pixel2cam(cur_frame_2.keypoints[matches[i].trainIdx].pt, camera_mat));\n\n            count_newly_triangu++;\n        }\n    }\n\n    cv::Mat pts_3d_homo;\n    if (pointset1.size() > 0)\n        cv::triangulatePoints(T1_mat, T2_mat, pointset1, pointset2, pts_3d_homo);\n\n    // De-homo and assign color\n    for (int i = 0; i < pts_3d_homo.cols; i++)\n    {\n        cv::Mat pts_3d = pts_3d_homo.col(i);\n\n        pts_3d /= pts_3d.at<float>(3, 0);\n\n        pcl::PointXYZRGB pt_temp;\n        pt_temp.x = pts_3d.at<float>(0, 0);\n        pt_temp.y = pts_3d.at<float>(1, 0);\n        pt_temp.z = pts_3d.at<float>(2, 0);\n\n        // check here if(pt_temp.x> )\n\n        cv::Point2f cur_key_pixel = cur_frame_1.keypoints[matches[i].queryIdx].pt;\n\n        uchar blue = cur_frame_1.rgb_image.at<cv::Vec3b>(cur_key_pixel.y, cur_key_pixel.x)[0];\n        uchar green = cur_frame_1.rgb_image.at<cv::Vec3b>(cur_key_pixel.y, cur_key_pixel.x)[1];\n        uchar red = cur_frame_1.rgb_image.at<cv::Vec3b>(cur_key_pixel.y, cur_key_pixel.x)[2];\n\n        pt_temp.r = 1.0 * red;\n        pt_temp.g = 1.0 * green;\n        pt_temp.b = 1.0 * blue;\n        sparse_pointcloud.rgb_pointcloud->points.push_back(pt_temp);\n    }\n\n    std::cout << \"Triangulate [ \" << count_newly_triangu << \" ] new points, [ \" << sparse_pointcloud.rgb_pointcloud->points.size() << \" ] points in total.\" << std::endl;\n\n    std::chrono::steady_clock::time_point toc = std::chrono::steady_clock::now();\n    std::chrono::duration<double> time_used = std::chrono::duration_cast<std::chrono::duration<double>>(toc - tic);\n    std::cout << \"Triangularization done in \" << time_used.count() << \" seconds. \" << std::endl;\n\n    if (show)\n    {\n        // Show 2D image pair and correspondences\n        cv::Mat match_image_pair;\n        cv::drawMatches(cur_frame_1.rgb_image, cur_frame_1.keypoints, cur_frame_2.rgb_image, cur_frame_2.keypoints, matches, match_image_pair);\n        cv::imshow(\"Triangularization matches\", match_image_pair);\n        cv::waitKey(0);\n\n        boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer(new pcl::visualization::PCLVisualizer(\"Sfm Viewer\"));\n        viewer->setBackgroundColor(0, 0, 0);\n\n        // Draw camera\n        char t[256];\n        std::string s;\n        int n = 0;\n        float frame_color_r, frame_color_g, frame_color_b;\n        float sphere_size = 0.2;\n        float line_size_cam = 0.4;\n\n        pcl::PointXYZ pt_cam1(cur_frame_1.pose_cam(0, 3), cur_frame_1.pose_cam(1, 3), cur_frame_1.pose_cam(2, 3));\n        pcl::PointXYZ pt_cam2(cur_frame_2.pose_cam(0, 3), cur_frame_2.pose_cam(1, 3), cur_frame_2.pose_cam(2, 3));\n\n        sprintf(t, \"%d\", n);\n        s = t;\n        viewer->addSphere(pt_cam1, sphere_size, 1.0, 0.0, 0.0, s);\n        n++;\n\n        sprintf(t, \"%d\", n);\n        s = t;\n        viewer->addSphere(pt_cam2, sphere_size, 0.0, 0.0, 1.0, s);\n        n++;\n\n        sprintf(t, \"%d\", n);\n        s = t;\n        viewer->addLine(pt_cam1, pt_cam2, 0.0, 1.0, 0.0, s);\n        n++;\n\n        // for (int i = 0; i < sparse_pointcloud->points.size(); i++)\n        // {\n        //     char sparse_point[256];\n        //     pcl::PointXYZ ptc_temp;\n        //     ptc_temp.x = sparse_pointcloud->points[i].x;\n        //     ptc_temp.y = sparse_pointcloud->points[i].y;\n        //     ptc_temp.z = sparse_pointcloud->points[i].z;\n        //     sprintf(sparse_point, \"SP_%03u\", i);\n        //     viewer->addSphere(ptc_temp, 0.2, 1.0, 0.0, 0.0, sparse_point);\n        // }\n\n        viewer->addPointCloud(sparse_pointcloud.rgb_pointcloud, \"sparsepointcloud\");\n\n        std::cout << \"Click X(close) to continue...\" << std::endl;\n        while (!viewer->wasStopped())\n        {\n            viewer->spinOnce(100);\n            boost::this_thread::sleep(boost::posix_time::microseconds(100000));\n        }\n    }\n\n    std::cout << \"Generate new sparse point cloud done.\" << std::endl;\n    return true;\n}\n\nbool MotionEstimator::doUnDistort(frame_t &cur_frame, cv::Mat distort_coeff)\n{\n    cv::Mat camera_mat;\n    cv::eigen2cv(cur_frame.K_cam, camera_mat);\n    cv::Mat undistorted_img;\n    cv::undistort(cur_frame.rgb_image, undistorted_img, camera_mat, distort_coeff);\n    cur_frame.rgb_image = undistorted_img;\n\n    std::cout << \"Undistort the image done.\" << std::endl;\n    return true;\n}\n\n/**\n* \\brief Transform a Point Cloud using a given transformation matrix\n* \\param[in]  cloud_in : A pointer of the Point Cloud before transformation\n* \\param[out] cloud_out : A pointer of the Point Cloud after transformation\n* \\param[in]  trans : A 4*4 transformation matrix\n*/\nbool MotionEstimator::transformCloud(pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud_in,\n                                     pcl::PointCloud<pcl::PointXYZ>::Ptr &cloud_out,\n                                     Eigen::Matrix4f &trans)\n{\n    Eigen::Matrix4Xf PC;\n    Eigen::Matrix4Xf TPC;\n    PC.resize(4, cloud_in->size());\n    TPC.resize(4, cloud_in->size());\n    for (int i = 0; i < cloud_in->size(); i++)\n    {\n        PC(0, i) = cloud_in->points[i].x;\n        PC(1, i) = cloud_in->points[i].y;\n        PC(2, i) = cloud_in->points[i].z;\n        PC(3, i) = 1;\n    }\n    TPC = trans * PC;\n    for (int i = 0; i < cloud_in->size(); i++)\n    {\n        pcl::PointXYZ pt;\n        pt.x = TPC(0, i);\n        pt.y = TPC(1, i);\n        pt.z = TPC(2, i);\n        cloud_out->points.push_back(pt);\n    }\n    //cout << \"Transform done ...\" << endl;\n}\n\nbool MotionEstimator::outlierFilter(pointcloud_sparse_t &sparse_pointcloud, int MeanK, double std)\n{\n    // Create the filtering object\n    pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor;\n\n    std::vector<int> filtered_indice;\n\n    sor.setInputCloud(sparse_pointcloud.rgb_pointcloud);\n    sor.setMeanK(MeanK);         //50\n    sor.setStddevMulThresh(std); //1.0\n    sor.filter(filtered_indice);\n\n    pcl::PointCloud<pcl::PointXYZRGB>::Ptr output_pointcloud(new pcl::PointCloud<pcl::PointXYZRGB>);\n    std::vector<int> output_unique_points_id;\n    std::vector<int> output_is_inlier;\n    for (int i = 0; i < filtered_indice.size(); i++)\n    {\n        output_pointcloud->points.push_back(sparse_pointcloud.rgb_pointcloud->points[filtered_indice[i]]);\n        output_unique_points_id.push_back(sparse_pointcloud.unique_point_ids[filtered_indice[i]]);\n        output_is_inlier.push_back(sparse_pointcloud.is_inlier[filtered_indice[i]]);\n    }\n\n    std::cout << \"apply outlier filter: [ \" << sparse_pointcloud.unique_point_ids.size() << \" ] points before filtering, [ \" << filtered_indice.size() << \" ] points after filtering.\" << std::endl;\n\n    sparse_pointcloud.rgb_pointcloud->points.swap(output_pointcloud->points);\n    sparse_pointcloud.unique_point_ids.swap(output_unique_points_id);\n    sparse_pointcloud.is_inlier.swap(output_is_inlier);\n\n    return 1;\n}\n\nbool MotionEstimator::estimateE8Points(std::vector<cv::KeyPoint> &keypoints1,\n                                       std::vector<cv::KeyPoint> &keypoints2,\n                                       std::vector<cv::DMatch> &matches,\n                                       Eigen::Matrix3f &K,\n                                       Eigen::Matrix4f &T)\n{\n#if 0\n    std::vector<cv::Point2f> pointset1;\n    std::vector<cv::Point2f> pointset2;\n\n    for (int i = 0; i < (int)matches.size(); i++)\n    {\n        pointset1.push_back(keypoints1[matches[i].queryIdx].pt);\n        pointset2.push_back(keypoints2[matches[i].trainIdx].pt);\n    }\n\n    cv::Point2d principal_point(K(0, 2), K(1, 2));\n    double focal_length = (K(0, 0) + K(1, 1)) * 0.5;\n    cv::Mat essential_matrix;\n    essential_matrix = cv::findEssentialMat(pointset1, pointset2, focal_length, principal_point);\n    std::cout << \"essential_matrix is \" << std::endl\n              << essential_matrix << std::endl;\n\n    cv::Mat R;\n    cv::Mat t;\n\n    cv::recoverPose(essential_matrix, pointset1, pointset2, R, t, focal_length, principal_point);\n\n    Eigen::Matrix3f R_eigen;\n    Eigen::Vector3f t_eigen;\n    cv::cv2eigen(R, R_eigen);\n    cv::cv2eigen(t, t_eigen);\n    T.block(0, 0, 3, 3) = R_eigen;\n    T.block(0, 3, 3, 1) = t_eigen;\n    T(3, 0) = 0;\n    T(3, 1) = 0;\n    T(3, 2) = 0;\n    T(3, 3) = 1;\n\n    std::cout << \"Transform is \" << std::endl\n              << T << std::endl;\n#endif\n}", "meta": {"hexsha": "baaa70f25135ca9dfd3a1af07137ebf9154600fc", "size": 19723, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp_code/src/estimate_motion.cpp", "max_stars_repo_name": "YuePanEdward/EasySFM", "max_stars_repo_head_hexsha": "4fe0ec70cc93126904168c3305db893c8e0dbe10", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2019-12-13T02:12:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T14:16:11.000Z", "max_issues_repo_path": "cpp_code/src/estimate_motion.cpp", "max_issues_repo_name": "YuePanEdward/P3DV", "max_issues_repo_head_hexsha": "4fe0ec70cc93126904168c3305db893c8e0dbe10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-03T16:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-21T22:33:11.000Z", "max_forks_repo_path": "cpp_code/src/estimate_motion.cpp", "max_forks_repo_name": "YuePanEdward/P3DV", "max_forks_repo_head_hexsha": "4fe0ec70cc93126904168c3305db893c8e0dbe10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-02-24T04:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-09T09:01:39.000Z", "avg_line_length": 35.9253187614, "max_line_length": 196, "alphanum_fraction": 0.6055873853, "num_tokens": 5918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.43776886033424744}}
{"text": "\n\n// #pragma GCC optimize (\"O0\")\n\n#include <boost/numeric/odeint.hpp>       // odeint function definitions \n\nusing namespace boost::numeric::odeint;\n\n\n#include \"eigenIncluder.hpp\"\n#include \"forceModels.hpp\"\n#include \"streamTrace.hpp\"\n#include \"instrument.hpp\"\n#include \"navigation.hpp\"\n#include \"satRefSys.hpp\"\n#include \"constants.hpp\"\n#include \"acsConfig.hpp\"\n#include \"gravity.hpp\"\n#include \"common.hpp\"\n#include \"jplEph.hpp\"\n#include \"tides.hpp\"\n#include \"enums.h\"\n\ntypedef Eigen::Vector<double, 48> VectorXSTMS;\t\t\t//todo aaron, delete this\n\nmap<int, OrbitPropagator>\torbitPropagatorMap;\n\nGravityModel OrbitPropagator::gravityModel;\n\n/* Frac: Gives the fractional part of a number\n*/\ndouble Frac (double x)\n{\n\treturn x - floor(x);\n}\n\n/* Computes the Sun's geocentric position using a low precision analytical series\n*/\nVector3d SunPos(\n\tdouble mjdTT)\t\t///< Terrestrial time: modified Julian date\n{\n\t/* Constants\n\t*/\n\tconst double eps\t= 23.43929111 * D2R;\t\t\t\t// Obliquity of J2000 ecliptic\n\tconst double T\t\t= (mjdTT - mjdJ2000) / 36525.0;\t\t// Julian cent. since J2000\n\n\t/* Mean anomaly, ecliptic longitude and radius\n\t*/\n\tdouble M = PI2 * Frac ( 0.9931267 + 99.9973583 * T);\t\t\t\t\t\t\t\t\t\t// [rad]\n\tdouble L = PI2 * Frac ( 0.7859444 + M/PI2 + ( 6892 * sin(M) + 72 * sin(2 * M) ) / 1296e3 );\t// [rad]\n\tdouble R = 149.619e9 - 2.499e9 * cos(M) - 0.021e9 * cos(2 * M);\t\t\t\t\t\t\t\t// [m]\n\n\t/* Solar position vector [m] with respect to the mean equator and equinox of J2000 (EME2000, ICRF)\n\t*/\n\treturn R_x(-eps) * R * Vector3d(cos(L), sin(L), 0);\n}\n\n/* Computes the fractional illumination of a spacecraft in the vicinity of the Earth assuming a cylindrical shadow model\n*\n*/\ndouble Illumination(\n\tconst Vector3d& \t\trSat,\t\t\t///< Spacecraft position vector [m]\n\tconst Vector3d& \t\trSun )\t\t\t///< Sun position vector [m]\n{                      \n\tVector3d eSun = rSun / rSun.norm();    // Sun direction unit vector\n\tdouble s     \t= rSat.dot(eSun);      // Projection of s/c position \n\n\t/* Illumination factor:\n\t*  1: Spacecraft fully illuminated by the Sun\n\t*  0: Spacecraft in Earth shadow\n\t*/\n\treturn ( ( s > 0 || (rSat - s * eSun).norm() > RE_WGS84 ) ?  1 : 0 );\n}\n\n/* Class type: The class of solar radiation pressure\n*\n*/\nSolarRadPressure::SolarRadPressure(\n\tSRPPara \t\t\t\tparaSRP)\n{\n\tmSRPPara\t\t= paraSRP;\n}\n\nVector3d SolarRadPressure::directSolarRadiationAcc(\n\tTrace&\t\t\t\ttrace,\t\t \t\t\t\t///< Trace to output to\n\tdouble \t\t\t\tmjdTT,\t\t \t\t\t\t///< Terrestrial time (modified Julian date)\t\n\tconst Vector3d& \trSat)        \t\t\t\t///< Satellite position vector, unit: m, m/s\n{\n\n\t/* Relative position vector of spacecraft w.r.t. Sun\n\t*/\n\tVector3d rSun;\n\tjplEphPos(nav.jplEph_ptr, mjdTT + JD2MJD, E_ThirdBody::SUN, rSun);\n\n\t// trace << \"Calculated sun position: \" << std::setw(14) << mjdTT << std::setw(14) << rSun.transpose() << std::endl;\n\n\tVector3d rDis = rSat - rSun;\n\tdouble illumination = Illumination(rSat, rSun);\n\t\n\tswitch (mSRPPara.srpMdlName)\n\t{\n\t\tcase E_SRPModels::CANNONBALL:\t\treturn illumination * mSRPPara.srpCoef * (mSRPPara.srpArea / mSRPPara.satMass) * PSOL * (AU * AU) * rDis / pow(rDis.norm(), 3);\t\n\t\tcase E_SRPModels::BOXWING:\t\t\treturn Vector3d::Zero();\t\t\t\n\t\tcase E_SRPModels::ECOM:\t\t\t\treturn Vector3d::Zero();\t\t\t\t\t\n\t\tcase E_SRPModels::ECOM2:\t\t\treturn Vector3d::Zero();\t\t\t\t\t\n\t\tdefault:\t\t\t\t\t\t\treturn Vector3d::Zero();\n\t}\n}\n\nVector3d SolarRadPressure::indirectSolarRadiationAcc(\n\tTrace&\t\t\t\ttrace,\t\t \t\t\t\t\t///< Trace to output to (similar to cout)\n\tdouble \t\t\t\tmjdTT,\t\t \t\t\t\t\t///< Terrestrial time (modified Julian date)\t\n\tconst Vector3d& \trSat)        \t\t\t\t\t///< Satellite position vector, unit: m, m/s\n{\n\treturn Vector3d::Zero();\n}\n\nVector3d antennarThrustAcc()\n{\n\treturn Vector3d::Zero();\n}\n\nVector3d empiricalAcc()\n{\n\treturn Vector3d::Zero();\n}\n\nVector3d manoeuvreAcc()\n{\n\treturn Vector3d::Zero();\n}\n\n\n/* Set options for force models in the propagator\n*\n*/\nvoid OrbitPropagator::setPropOption(\n\tForceModels\t\t\t\tforceMdl)\t\t\t\n{\n\t/* Options from yaml file */\n\tpropOpt.optEarthGravMdl.earthGravMdl\t\t= E_GravMdl::GGM03S;\n\t\n\t/* Parameters from yaml file */\n\tpropOpt.optEarthGravMdl.earthGravAccDeg.mMax = forceMdl.egmAccDeg;\n\tpropOpt.optEarthGravMdl.earthGravAccDeg.nMax = forceMdl.egmAccOrd;\n\tpropOpt.optEarthGravMdl.earthGravSTMDeg.mMax = forceMdl.egmSTMDeg;\n\tpropOpt.optEarthGravMdl.earthGravSTMDeg.nMax = forceMdl.egmSTMOrd;\n\n\tpropOpt.paraSRP.srpMdlName\t= forceMdl.srp_model;\n\tpropOpt.paraSRP.satMass\t\t= forceMdl.sat_mass;\n\tpropOpt.paraSRP.srpArea\t\t= forceMdl.srp_area;\n\tpropOpt.paraSRP.srpCoef\t\t= forceMdl.srp_coef;\n}\t\n\n/* initialise the propagator with time, state and necessary parameters\n*\n*/\nvoid OrbitPropagator::init(\n\tVector6d\t\t\t\trvSatECI,\t\n\tdouble \t\t\t\t\tmjdUTC,\n\tdouble\t\t\t\t\tleapSec,\n\tERP*\t\t\t\t\terpSrc,\n\tEGMCoef\t\t\t\t\tegmCoef)\n{\n\tinertialState \t\t= rvSatECI;\n\tmMJDUTC \t\t\t= mjdUTC;\n\terp \t\t\t\t= erpSrc;\n\t\n\tgeterp(*erp, mMJDUTC, erpv);\n\n\tgravityModel = GravityModel(propOpt.optEarthGravMdl, egmCoef);\n\n\tif\t(acsConfig.forceModels.solar_radiation_pressure)\n\t{\n\t\tsolarRadPressure = SolarRadPressure(propOpt.paraSRP);\n\t}\n}\n\nvoid OrbitPropagator::update(\n\tdouble\t\t\t\tmjdUTC)\n{\n\t// update time\n\tmMJDUTC = mjdUTC;\n\t\n\t// update erp\n\tgeterp(*erp, mMJDUTC, erpv);\n\tdouble dUTC_TAI\t= -(19 + erpv.leaps);\n\tdouble xp\t\t= erpv.xp;\n\tdouble yp\t\t= erpv.yp;\n\tdouble dUT1_UTC\t= erpv.ut1_utc;\n\tdouble lod\t\t= erpv.lod;\n\t\n\t// update iers\n\tiers = IERS(dUT1_UTC, dUTC_TAI, xp, yp, lod);\n\t\n\t//update srp parameters\n\tsolarRadPressure.mSRPPara = propOpt.paraSRP;\n\t\n\t//update third body positions\n\tdouble mjdTT = mMJDUTC + iers.TT_UTC() / 86400.0;\n\tfor (int i = 0; i < E_ThirdBody::_size(); i++)\n\t{\n\t\tE_ThirdBody\tbody \t\t= E_ThirdBody::_values()[i];\n\t\tstring\t\tbodyName\t= E_ThirdBody::_names()[i];\n\t\t\n\t\tif (acsConfig.forceModels.process_third_body[body] == false)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t// Relative position vector of satellite w.r.t. point mass\n\t\tVector3d thirdBodyPos;\n\t\tjplEphPos(nav.jplEph_ptr, mjdTT + JD2MJD, body, thirdBodyPos);\n\n\t\tthirdBodyPositionMap[body] = thirdBodyPos;\n\t}\n\t\n\t//update reference frame matrices\n\teci2ecef_sofa(mjdUTC, iers, mECI2ECEF, mdECI2ECEF);\n\t\n\t//update egm coefficients for tides\n\tgravityModel.correctEgmCoefficients(std::cout, mjdUTC, erpv, mECI2ECEF);\n}\n\t\nVector3d  OrbitVEQPropagator::calculateAccelNGradient(\n\tTrace&    \t\t\t\ttrace,\t \t\t\t///< Trace to output to (similar to cout)\n\tconst Vector3d& \t\trSat,\t\t \t\t///< Inertial position of satellite (m)\n\tconst Vector3d& \t\tvSat,\t\t \t\t///< Inertial velocity of satellite (m/s)\n\tMatrix3d&\t\t\t\tmGradient,\t\t\t///< Gradient (G=da/dr) in the ICRF/J2000 system\n\tVector3d&\t\t\t\tdadCr,       \t\t///< Partials of acceleration w.r.t. to the solar radiation coefficient\n\tconst Matrix3d& \t\tmECI2ECEF)\t \t\t///< Transformation matrix from ECI coordinate to ECEF\t\t\t\n{\n// \tbool bVarEq = true;\n// \tVector3d earthGravityAcc = gravityModel.centralBodyGravityAcc(trace, mMJDUTC, mERPv, rSat, mECI2ECEF, bVarEq);\n// \tVector3d drSat;\n// \tconst double dinc = 1;   // Position increment [m]\n// \tVector3d daSat;\n// \n// \t/* Gradient\n// \t*/\n//   \tfor (int i = 0; i < 3; i++)\n// \t{\n//     \tdrSat = Vector3d::Zero();\t\n// \t\tdrSat(i) = dinc;\t// Set offset in i-th component of the position vector\n//     \tdaSat = gravityModel.centralBodyGravityAcc (trace, mMJDUTC, mERPv, rSat + drSat, mECI2ECEF, bVarEq) -  earthGravityAcc;\t// Acceleration difference\n//     \tmGradient.col(i) = daSat / dinc;\t// Derivative with respect to i-th component\n//   \t}\n// \n//   \t/* Radiation pressure coefficient partials\n// \t*/  \n// \tdouble mjdTT = mIERS.TT_UTC(mMJDUTC) / 86400.0 + mMJDUTC;\n// \tsolarRadPressure.mSRPPara.srpCoef = 1;\t\n// \tdadCr = solarRadPressure.directSolarRadiationAcc(trace, mjdTT, rSat);\n\tVector3d acc;\n\treturn acc;\n}\t\n/** Propagate orbits by ODE functor.\n * Used by RK - input is a 6 element inertial state and time, and output is the derivative of the state at the provided time.\n * This function requires the update function to be called first to set planetary ephemerides, erp values, etc.\n */\nvoid OrbitPropagator::operator ()(\n\tVector6d&\t\t inertialState,\t\t\t\t ///< Inertial position and velocity of satellite (m, m/s)\n\tVector6d&\t\tdInertialState,  \t\t\n\tconst double\tmjdUTCinSec)\n{\n\tInstrument instrument(__FUNCTION__);\n\t\n\t//Get sub vectors from the state\n\tVector3d rSat = inertialState.head(3);\n\tVector3d vSat = inertialState.tail(3);\n\n\tauto& trace = std::cout;\n\t\n\tdouble mjdUTC = mjdUTCinSec / 86400;\n\n\t// double erpv[4] = {};\n\t// geterp_from_utc(&nav.erp, mjdUTC, erpv);\n\t// double leapSec\t= nav.leaps;\n\t// double dUT1_UTC = erpv[2];\n\t// double dUTC_TAI\t= -(19 + leapSec);\n\t// double xp = erpv[0];\n\t// double yp = erpv[1];\n\t// double lod = erpv[3];\n\t// clIERS iersInstance;\n\t// iersInstance.Set(dUT1_UTC, dUTC_TAI, xp, yp, lod);\n\t// double mjdTT = mjdUTC + iersInstance.TT_UTC(mjdUTC) / 86400;\n\n\n\t// Matrix3d mECI2ECEF = Matrix3d::Identity();\n\t// Matrix3d mdECI2ECEF = Matrix3d::Identity();\n\t// eci2ecef_sofa(mjdUTC, iersInstance, mECI2ECEF, mdECI2ECEF);\n\t// std::cout << \"mECI2ECEF: \" << mjdUTC << \"  \" << std::setw(14) << mECI2ECEF << std::endl;\n\t// Vector3d aSat = calculateAcceleration(std::cout, mjdTT, rSat, vSat, mECI2ECEF, egm.cmn, egm.smn, 12, 12);\n\t// std::cout << \"Accelerations: \" << mjdUTC << \"  \" << std::setw(14) << aSat.transpose() << std::endl;\n\t\n\t\n\t// std::cout << \"mECI2ECEF: \" << orbitProp.mMJDUTC << \"  \" << std::setw(14) << mECI2ECEF << std::endl;\n\n\t\n\t//calculate acceleration components\n\tVector3d aSat = Vector3d::Zero();\n\t\n\t\n\tbool bVarEq = false;\n\tif (acsConfig.forceModels.earth_gravity)\n\t{\n\t\tInstrument instrument(\"Grav\");\n\t\t\n\t\tVector3d earthgravityAcc = -GM_Earth * rSat.normalized() / rSat.squaredNorm();// = gravityModel.centralBodyGravityAcc(trace, mMJDUTC, erpv, rSat, mECI2ECEF, bVarEq);\n\t\t\n// \t\ttrace << \"Calculated accleration due to the Earth's central body gravity: \" << std::setw(14) << mMJDUTC << std::setw(14) << earthgravityAcc.transpose() << std::endl;\n\n\t\taSat += earthgravityAcc;\t\t\n\t}\n\n\t\n\tdouble mjdTT = iers.TT_UTC() / 86400.0 + mMJDUTC;\n\tfor (int i = 0; i < E_ThirdBody::_size(); i++)\n\t{\n\t\tE_ThirdBody\tbody \t\t= E_ThirdBody::_values()[i];\n\t\tstring\t\tbodyName\t= E_ThirdBody::_names()[i];\n\t\t\n\t\tif (acsConfig.forceModels.process_third_body[body] == false)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tVector3d& bodyPos = thirdBodyPositionMap[body];\n\t\t\n\t\t\n\t\tVector3d thirdbodyAcc = accelPointMassGravity(trace, mjdTT, rSat, body, bodyPos);\n\t\t\n// \t\ttrace << \"Calculated acceleration due to \" << bodyName << \"'s attraction: \" << std::setw(14) << mMJDUTC << std::setw(14) << thirdbodyAcc.transpose() << std::endl;\n\t\t\n\t\taSat += thirdbodyAcc;\n\t}\n\t\n\tif (acsConfig.forceModels.relativity_effect)\n\t{\n\t\tInstrument instrument(\"Rel\");\n\t\t\n\t\tVector3d relativityAcc = gravityModel.relativityEffectsAcc(trace, rSat, vSat);\n\n// \t\ttrace << \"Calculated acceleration due to the relativity effect: \" << std::setw(14) << mMJDUTC << std::setw(14) << relativityAcc.transpose() << std::endl;\n\t\t\n\t\taSat += relativityAcc;\n\t}\t\n\n\tif (acsConfig.forceModels.solar_radiation_pressure)\n\t{\n\t\tInstrument instrument(\"SRP\");\n\t\t\n\t\tVector3d directSRPAcc = solarRadPressure.directSolarRadiationAcc(trace, mMJDUTC, rSat);\n\n// \t\ttrace << \"Calculated acceleration due to the direct solar radiation: \" << std::setw(14) << mMJDUTC << std::setw(14) << directSRPAcc.transpose() << std::endl;\n\t\t\n\t\taSat += directSRPAcc;\n\t}\t\t\n\t\n\t// std::cout << \"Total accelerations: \" << mjdUTC << \"  \" << std::setw(14) << aSat.transpose() << std::endl;\n\n\t//set ODE output from sub vectors\n\tdInertialState.head(3) = vSat;\n\tdInertialState.tail(3) = aSat;\n\t\n\t\n\tstd::cout << \"\\n\" << (aSat.dot(rSat.normalized()));\n}\n\n/** Observer, prints time and state when called (during integration)\n*\n*/\nvoid obsvrSatMotion( \n\tconst Vector6d& x, \n\tconst double mjdUTC)\n{\n\t// std::cout << std::endl;\n\t// std::cout << std::setw(8) << mjdUTC << std::setw(14) << x[0] << std::setw(14) << x[1] << std::setw(14) << x[2]\n\t// \t\t  << std::setw(14) << x[3] << std::setw(14) << x[4] << std::setw(14) << x[5] << std::setw(14) <<  std::endl;\n}\n\n/** ODE of variational equation to be solved, i.e. the derivative of the state vector and the state transition matrix\n*\n*/\n// struct VarEqPropagator\n// {\n// \tvoid operator()( \n// \t\tconst\tVectorXSTMS&\trvPhiS, \n// \t\t\t\tVectorXSTMS&\tdrvPhiSdt, \n// \t\tconst\tdouble\t\t\tmjdUTCinSec)\n// \t{\n// \t\tdouble mjdUTC = mjdUTCinSec / 86400;\t// Time\n// \n// \t\tVector3d rSat = rvPhiS.segment(0, 3);\t// Position components\n// \t\tVector3d vSat = rvPhiS.segment(3, 3);\t// Velocity components\n// \n// \t\tMatrixXd Phi = MatrixXd::Identity(6, 6);\t// State transition matrix\n// \t\t// for (int j = 0; j < 6; j++)\n// \t\t// {\n// \t\t// \tPhi.col(j) = rvPhiS.segment(6 * (j + 1), 6);\n// \t\t// }\n// \n// \t\tMatrixXd S = MatrixXd::Zero(6, 1);\t// Sensitivity matrix\n// \t\t// for (int j = 0; j < 1; j++)\n// \t\t// {\n// \t\t// \tS.col(j) = rvPhiS.segment(6 * (j + 7), 6);\n// \t\t// }\n// \n// \t\tMatrix3d mECI2ECEF\t= Matrix3d::Identity();\n// \t\tMatrix3d mdECI2ECEF\t= Matrix3d::Identity();\n// \t\tupdPropagator(mjdUTC); //time epoch inside the integrator\n// \t\teci2ecef_sofa(mjdUTC, mIERS, mECI2ECEF, mdECI2ECEF);\n// \n// \t\tMatrix3d mGradient;\n// \t\tVector3d dadCr;\n// \t\tVector3d aSat = calculateAccelNGradient(std::cout, rSat, vSat, mGradient, dadCr, mECI2ECEF);\n// \n// \t\t/* Time derivative of state transition matrix\n// \t\t*\n// \t\t*/\n// \t\tMatrixXd dfdy = MatrixXd::Zero(6, 6);\n// \t\tfor (int i = 0; i < 3; i++)\n// \t\tfor (int j = 0; j < 3; j++)\n// \t\t{\n// \t\t\tdfdy(i, \tj\t ) = 0;\t\t\t\t\t\t// dv/dr(i, j)\n// \t\t\tdfdy(i + 3, j\t ) = mGradient(i, j);\t\t// da/dr(i, j)\n// \t\t\tdfdy(i,     j + 3) = ( i == j ? 1 : 0 );\t// dv/dv(i, j)\n// \t\t\tdfdy(i + 3, j + 3) = 0;\t\t\t\t\t\t// da/dv(i, j)\n// \t\t}\n// \t\tMatrixXd dPhi = dfdy * Phi;\t// Time derivative of state transition matrix\n// \n// \n// \t\t/* Time derivative of sensitivity matrix\n// \t\t*\n// \t\t*/\n// \t\tMatrixXd dfdp(6, 1);\n// \t\tfor (int i = 0; i < 3; i++)\n// \t\t{\n// \t\t\tdfdp(i    ) = 0;\t\t\t\t\t\t\t// dv/dCr(i)\n// \t\t\tdfdp(i + 3) = dadCr(i);\t\t\t\t\t\t// da/dCr(i)\n// \t\t}\n// \n// \t\tMatrixXd dS = MatrixXd::Zero(6, 1);\n// \t\tdS = dfdy * S + dfdp;\n// \n// \t\t/* Derivative of combined state vector and state transition matrix\n// \t\t*\n// \t\t*/\n// \t\tfor (int i = 0; i < 3; i++)\n// \t\t{\n// \t\t\tdrvPhiSdt(i    ) = vSat(i);                    // dr/dt(i)\n// \t\t\tdrvPhiSdt(i + 3) = aSat(i);                    // dv/dt(i)\n// \t\t}\n// \t\t\n// \t\tfor (int i = 0; i < 6; i++)\n// \t\tfor (int j = 0; j < 6; j++)\n// \t\t{\n// \t\t\tdrvPhiSdt(6 * (j + 1) + i  ) = dPhi(i, j);     // dPhi/dt(i,j)\n// \t\t}\n// \n// \t\tfor (int i = 0; i < 6; i++)\n// \t\tfor (int j = 6; j < 7; j++)\n// \t\t{\n// \t\t\tdrvPhiSdt(6 * (j + 1) + i) = dS(i, j - 6);     // dS/dt(i,j)\n// \t\t}\n// \t}\n// };\n\nvoid updateOrbits(\n\tTrace&\t\t\ttrace,\n\tKFState&\t\tkfState,\n\tGTime           time)\n{\n\t{\n\t\t//get current inertial states from the kfState\n\t\tfor (auto& [kfKey, index] : kfState.kfIndexMap)\n\t\t{\n\t\t\tif\t( kfKey.type\t!= KF::SAT_POS\n\t\t\t\t||kfKey.num\t\t!= 0)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tauto& orbitPropagator = orbitPropagatorMap[kfKey.Sat];\n\t\t\t\n\t\t\tVector6d rvECI;\n\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t{\n\t\t\t\tKFKey posKey = kfKey;\n\t\t\t\t\n\t\t\t\tposKey.num = i;\n\t\t\t\tkfState.getKFValue(posKey, rvECI(0 + i));\t\t\t\t\n\t\t\t\t\n\t\t\t\tposKey.type = KF::SAT_POS_RATE;\n\t\t\t\tkfState.getKFValue(posKey, rvECI(3 + i));\t\t\n\t\t\t}\n\t\t\t\n\t\t\tdouble mjdUTC\t= gpst2mjd(tsync);\n\t\t\tdouble leapSec\t= nav.leaps;\n\t\t\torbitPropagator.setPropOption(acsConfig.forceModels);\n\t\t\torbitPropagator.init(rvECI, mjdUTC, leapSec, &nav.erp, nav.egm);\n\t\t}\n\t}\n\t\n\tfor (auto& [satId, orbitPropagator] : orbitPropagatorMap)\n\t{\n\t\tSatSys Sat;\n\t\tSat.fromHash(satId);\n\t\t\n\t\tdouble dt = time - kfState.time;\t\t\t//time indicates the current epoch, kfState.time indicates the last epoch\n\t\t\n\t\tdouble t0 = gpst2mjd(kfState.time)\t* 86400;\n\t\tdouble t1 = gpst2mjd(time)\t\t\t* 86400;\n\t\t\n\t\tif (dt == 0)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t\n// \t\torbitPropagator.stateTime = time;\n\t\t\n\t\tVectorXd oldState = orbitPropagator.inertialState;\n\t\t\n\t\tdouble t_mid = (t0 + t1) / 2 / 86400;\n\t\t\n\t// \torbitPropagator.updPropagator(t0);//time epoch before the orbital propagation\n\n\t\tstd::cout << std::setprecision(2) << std::fixed;\n\t\tstd::cout\n\t\t<< \"ICRF coordinates before the orbital propagation step: \" \n\t\t<< std::setprecision(14) << orbitPropagator.inertialState.transpose() <<  std::endl;\n\t\t\n\t\torbitPropagator.update(t_mid); //time epoch inside the integrator\n\t\t\n\t\t\t\n\t\t\n\t\t//Run the propagator using the functor\n\t\t\n\t\tif (acsConfig.forceModels.ode_integrator == +E_Integrator::RKF78)\n\t\t{\n\t\t\ttypedef runge_kutta_fehlberg78<Vector6d>\trkf78;\t\t\t// Error stepper, used to create the controlled stepper\n// \t\t\ttypedef controlled_runge_kutta<rkf78>\t\tctrl_rkf78;\t\t// Controlled stepper: it's built on an error stepper and allows us to have the output at each internally defined (refined) timestep, via integrate_adaptive call\n\n\t\t\tdouble errAbs = 1.0e-16; // Error bounds\n\t\t\tdouble errRel = 1.0e-13;\n\t\t\t\n\t\t\t//integrate_adaptive(ctrl_rkf78(), OrbitPropagator(), rvECI, t0, t1, dt);\n\t\t\tauto controller = make_controlled(errAbs, errRel, rkf78());\n\t\t\tintegrate_adaptive(controller, orbitPropagator, orbitPropagator.inertialState, t0, t1, dt);\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tstd::cout \n\t\t<< \"ICRF coordinates after the orbital propagation step:  \" \n\t\t<< std::setprecision(14) << orbitPropagator.inertialState.transpose() <<  std::endl;\n\t// \tVectorXSTMS\trvPhiS\t= kfState.xSTMSM;\n\n\t// \tif (0)\n\t// \t{\n\t// \t\t// typedef runge_kutta4<VectorXSTMS> rk4;\n\t// \t\t// integrate_const(rk4(), odeVarEquation, rvPhiS, t0, t1, dt);\n\t// \t\tintegrate(VarEqPropagator(), rvPhiS, t0, t1, dt);\n\t// \t\t// typedef runge_kutta_dopri5<Vector6d> rk5;\n\t// \t\t// typedef controlled_runge_kutta<rk5> ctrl_rk5;\n\t// \t\t// double errAbs = 1.0e-10; // Error bounds\n\t// \t\t// double errRel = 1.0e-8;\n\t// \t\t// integrate_adaptive(ctrl_rk5(), odeVarEquation, rvPhiS, t0, t1, dt);\n\t// \t\t\n\t// \t\tstd::cout << \"ICRF coordinates before the variatioanal equation propagation: \" << std::setprecision(14) << rvPhiS.head(3).transpose() <<  std::endl;\n\t// \t\tkfState.xSTMSM = rvPhiS;\n\t// \t}\n\n\t// \tkfState.x\t\t= rvECI;\n\t// \tkfState.time\t= time;\n\n\n\t\t// ECI to ECEF transformation\n\n\t\t// double erpv[4] = {};\n\t\t// geterp(&nav.erp, time + dt, erpv);\n\t\t// double mjdUTC = gpst2mjd(time + dt);\n\t\t// double leapSec\t= nav.leaps;\n\t\t// double dUT1_UTC = erpv[2];\n\t\t// double dUTC_TAI\t= -(19 + orbitProp.mLeapSec);\n\t\t// double xp = erpv[0];\n\t\t// double yp = erpv[1];\n\t\t// double lod = erpv[3];\n\t\t// clIERS iersInstance;\n\t\t// iersInstance.Set(dUT1_UTC, dUTC_TAI, xp, yp, lod);\n\t\t// double mjdTT = mjdUTC + iersInstance.TT_UTC(mjdUTC) / 86400;\n\t\t// Matrix3d mECI2ECEF = Matrix3d::Identity();\n\t\t// Matrix3d mdECI2ECEF = Matrix3d::Identity();\n\t\t// Vector6d rvECEF;\n\t\t// eci2ecefVec_sofa(mjdUTC, iersInstance, rvECI, rvECEF);\n\t\t// std::cout << \"ITRF coordinates: \" << std::endl << std::setprecision(14) << rvECEF.transpose() <<  std::endl;\n\n\n\t// \tMatrix3d mECI2ECEF\t= Matrix3d::Identity();\n\t// \tMatrix3d mdECI2ECEF\t= Matrix3d::Identity();\n\t\torbitPropagator.update(gpst2mjd(time));//time epoch after the orbital propagation;\n\t\t\n\t\tVector3d rECI = orbitPropagator.inertialState.head(3);\n\t\tVector3d vECI = orbitPropagator.inertialState.tail(3);\n// \t\tstd::cout \n// \t\t<< \"ICRF coordinates after the orbital propagation step:  \" \n// \t\t<< std::setprecision(14) << rECI.transpose() << \" \" << vECI.transpose() <<  std::endl;\n\t\t\n\t\tVector3d rECEF2;\n\t\tVector3d vECEF2;\n\t\teci2ecef_sofa(orbitPropagator.mMJDUTC, orbitPropagator.iers, rECI, vECI, rECEF2, vECEF2);\n// \t\tstd::cout \n// \t\t<< \"ITRF coordinates after the orbital propagation step:  \" \n// \t\t<< std::setprecision(14) << rECEF2.transpose() << \" \" << vECEF2.transpose() <<  std::endl;\n\n// \t\tstd::ofstream fileOPResults(\"./ex01/OPResults.txt\", std::ios_base::app | std::ios_base::in);\n// \t\tif (!fileOPResults)\n// \t\t{\n// \t\t\tstd::cout << \"Error openinng results file!\\n\";\n// \t\t\treturn;\n// \t\t}\n\t\t\n// \t\tfileOPResults << std::setprecision(6) << std::fixed;\n\t\t\n\t\t\n\t\t// fileOPResults << setw(16) << orbitProp.mMJDUTC << setw(16) << rvECI.transpose() << setw(16) << rvECEF2.transpose() << endl;\n// \t\tfileOPResults << std::setw(16) << orbitPropagator.mMJDUTC << \" \" << rECEF2.transpose() << vECEF2.transpose() << std::endl;\n\t\t\n\t\t//get the change in state ready for use in the kalman filter's state transition\n// \t\torbitPropagator.stateDelta\t\t= orbitPropagator.inertialState - oldState;\n\t\t\n\t\t//get the noise in the state delta according to uncertainty in the inputs, and propagation uncertainty for use in the filters' covariance transition\n// \t\torbitPropagator.stateDeltaNoise\t= Matrix6d::Zero();\n\t\t\n\t\tMatrix6d stateTransition = Matrix6d::Identity();\n\t\tstateTransition.topRightCorner(3,3) = Matrix3d::Identity() * dt;\n\t\t\n\t\tVector6d transitionedState = stateTransition * oldState;\n\t\t\n\t\tVector6d missingDynamics = orbitPropagator.inertialState - transitionedState;\n\t\t\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tKFKey oneKey = {.type = KF::ONE};\n\t\t\t\n\t\t\tKFKey kfKey;\n\t\t\tkfKey.Sat = Sat;\n\t\t\tkfKey.num = i;\n\t\t\t\n\t\t\tkfKey.type = KF::SAT_POS;\n\t\t\t\n\t\t\tkfState.setKFTrans(kfKey, oneKey, missingDynamics(0 + i));\n\t\t\t\n\t\t\tkfKey.type = KF::SAT_POS_RATE;\n\t\t\t\n\t\t\tkfState.setKFTrans(kfKey, oneKey, missingDynamics(3 + i));\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "041cef9b9d46a75cb0bfb7b6ac31e2d9821f3181", "size": 20857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/orbprop/forceModels.cpp", "max_stars_repo_name": "HiTMonitor/ginan", "max_stars_repo_head_hexsha": "f348e2683507cfeca65bb58880b3abc2f9c36bcf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-31T15:16:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:16:19.000Z", "max_issues_repo_path": "src/cpp/orbprop/forceModels.cpp", "max_issues_repo_name": "hqy123-cmyk/ginan", "max_issues_repo_head_hexsha": "b69593b584f75e03238c1c667796e2030391fbed", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/orbprop/forceModels.cpp", "max_forks_repo_name": "hqy123-cmyk/ginan", "max_forks_repo_head_hexsha": "b69593b584f75e03238c1c667796e2030391fbed", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6015151515, "max_line_length": 219, "alphanum_fraction": 0.6477921082, "num_tokens": 7226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.43776701950126173}}
{"text": "#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <set>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <Eigen/Core>\n\n#include \"igl/AABB.h\"\n#include \"igl/adjacency_list.h\"\n#include \"igl/adjacency_matrix.h\"\n#include \"igl/ambient_occlusion.h\"\n#include \"igl/components.h\"\n#include \"igl/cotmatrix.h\"\n#include \"igl/decimate.h\"\n#include \"igl/dijkstra.h\"\n#include \"igl/embree/ambient_occlusion.h\"\n#include \"igl/embree/EmbreeIntersector.h\"\n#include \"igl/embree/unproject_onto_mesh.h\"\n#include \"igl/gaussian_curvature.h\"\n#include \"igl/invert_diag.h\"\n#include \"igl/jet.h\"\n#include \"igl/per_vertex_attribute_smoothing.h\"\n#include \"igl/per_vertex_normals.h\"\n#include \"igl/point_mesh_squared_distance.h\"\n#include \"igl/polygon_mesh_to_triangle_mesh.h\"\n#include \"igl/principal_curvature.h\"\n#include \"igl/ray_mesh_intersect.h\"\n#include \"igl/readOFF.h\"\n#include \"igl/unproject_onto_mesh.h\"\n#include \"igl/viewer/Viewer.h\"\n#include \"igl/writeOFF.h\"\n\n#include \"GLFW/glfw3.h\"\n\n#include \"dijkstra.hxx\"\n\nconst double mOCC_MAX_RAY_DIST = 10.0;\nconst int mOCC_NUM_RAYS = 20;\nconst double mDECIMATE_PERC = 0.6;\n\nvoid getMeanCurvature(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F,\n                      Eigen::VectorXd &VCs) {\n  Eigen::MatrixXd PD1,PD2;\n  Eigen::VectorXd PV1,PV2;\n  //igl::principal_curvature(V,F,PD1,PD2,PV1,PV2, 5);\n  igl::principal_curvature(V,F,PD1,PD2,PV1,PV2, 8);\n  //mean_curve = 0.5 * (PV1 + PV2);\n  VCs = PV1.cwiseProduct(PV1) + PV2.cwiseProduct(PV2);\n  VCs = VCs.cwiseMin(0.1);\n  VCs /= VCs.maxCoeff();\n\n  Eigen::VectorXd ones = Eigen::VectorXd::Constant(VCs.rows(), 1, 1);\n  VCs = ones - VCs;\n\n\n  /*\n  // Get the laplacian\n  Eigen::SparseMatrix<double> L,M,Minv;\n  //   from the cotangent matrix\n  igl::cotmatrix(V,F, L);\n  //   and the mass matrix\n  igl::massmatrix(V,F, igl::MASSMATRIX_TYPE_VORONOI, M);\n  igl::invert_diag(M, Minv);\n\n  Eigen::MatrixXd HN = -Minv*(L * V);\n  // Mean curviture is this value.\n  Eigen::VectorXd VC = HN.rowwise().norm();\n\n  // Smooth this out a bit.\n  igl::per_vertex_attribute_smoothing(VC,F, VCs);\n  // Cutoff at 1 (to avoid overpowering by high curvature)\n  VCs = VCs.cwiseMin(1.0);\n\n  // Normalize\n  VCs /= VCs.maxCoeff();\n  // Invert so high curvature has low weight.\n  Eigen::VectorXd ones = Eigen::VectorXd::Constant(VCs.rows(), 1, 1);\n  // Sqrt before switching\n  VCs = VCs.cwiseSqrt();\n  VCs = ones - VCs;\n  //std::cout << VCs;\n  */\n  \n}\n\nvoid printHelp() {\n  printf(\"Press 'U' to undo last point\\n\");\n  printf(\"Press 'C' to show colors from curvature\\n\");\n  printf(\"Press 'D' to show colors from ambient occlusion\\n\");\n}\n\nbool file_exists(const char* fn) {\n  FILE* ifs = fopen(fn, \"r\");\n  if (ifs) {\n    fclose(ifs);\n    return true;\n  }\n  return false;\n}\n\nint main(int argc, char* argv[]) {\n  if (argc < 3) {\n    fprintf(stderr, \"Used for selecting points on the surface of a mesh. Will write the\\n\"\n                    \"corresponding vertices to output.off\\n\");\n    fprintf(stderr, \"usage: %s <input.off> <output.off> [nowrite]\\n\",\n            argv[0]);\n    return -1;\n  }\n\n  bool writeable = true;\n  if (argc == 4) {\n    writeable = false;\n  }\n\n  Eigen::MatrixXd V,V2;\n  Eigen::MatrixXi F,F2;\n  igl::embree::EmbreeIntersector ei;\n\n  printf(\"Reading in mesh...\\n\");\n  // Read in the input file.\n  igl::readOFF(argv[1], V, F);\n  \n  // Colors are all white to start.\n  Eigen::MatrixXd VC = Eigen::MatrixXd::Constant(V.rows(),3,1);\n  // Initialize this thing so we can get the vertices.\n  ei.init(V.cast<float>(), F);\n\n  // Ambient occlusion\n  Eigen::VectorXd AO;\n  Eigen::MatrixXd N;\n  igl::per_vertex_normals(V,F,N);\n  // Compute ambient occlusion factor using embree\n  printf(\"Building AABB tree...\\n\");\n  igl::AABB<Eigen::MatrixXd, 3> aabb;\n  aabb.init(V, F);\n  const auto & shoot_ray = [&aabb,&V,&F](\n      const Eigen::Vector3f& _s,\n      const Eigen::Vector3f& dir)->bool\n  {\n    Eigen::Vector3f s = _s+1e-4*dir;\n    igl::Hit hit;\n    if (aabb.intersect_ray(V,F, s.cast<double>().eval(),dir.cast<double>().eval(), hit)) {\n      return hit.t < mOCC_MAX_RAY_DIST;\n    } \n    return false;\n  };\n\n  printf(\"Now setting ambient occlusion vertices to improve contrast (patience)...\\n\");\n  //igl::embree::ambient_occlusion(V,F,V,N,300,AO);\n  igl::ambient_occlusion(shoot_ray, V,N, mOCC_NUM_RAYS,AO);\n  AO = 1.0 - AO.array();\n  for (int i = 0; i < V.rows(); ++i) {\n    VC.row(i) *= AO(i);\n  }\n  \n  printf(\"Constructing adjacency list...\\n\");\n  // Need the adjacency list\n  std::vector<std::vector<int> > VV;\n  igl::adjacency_list(F, VV);\n\n  std::vector<std::vector<double> > darkWeight;\n  darkWeight.resize(VV.size());\n  //std::vector<std::vector<double> > curveWeight;\n  //curveWeight.resize(VV.size());\n  for (int i = 0; i < VV.size(); ++i) {\n    for (int j = 0; j < VV[i].size(); ++j) {\n      // Just use the value of the ambient occlusion.\n      darkWeight[i].push_back(AO(VV[i][j]));\n      //curveWeight[i].push_back(1.0 - AO(VV[i][j]));\n    }\n  }\n\n  // Also caluculate the curvature values.\n  printf(\"Calculating mean curvature...\\n\");\n  Eigen::VectorXd mean_curve;\n  getMeanCurvature(V,F, mean_curve);\n  std::vector<std::vector<double> > curveWeight;\n  curveWeight.resize(VV.size());\n  double maxCurve = 0;\n  double minCurve = 0;\n  for (int i = 0; i < VV.size(); ++i) {\n    for (int j = 0; j < VV[i].size(); ++j) {\n      // Difference in gausssian curvature\n      //double diff = std::abs(VCs(i) - VCs(j));\n      double diff = mean_curve(VV[i][j]);\n      curveWeight[i].push_back(diff);\n      maxCurve = std::max(diff, maxCurve);\n      minCurve = std::min(diff, minCurve);\n    }\n  }\n\n  // Create the colors for mean curviture to use\n  Eigen::MatrixXd curve_colors;\n  igl::jet(mean_curve, true, curve_colors);\n  \n\n  std::vector<int> all_points;  // will contain all selected points.\n  \n  igl::viewer::Viewer viewer;\n  viewer.data.set_mesh(V, F);\n  viewer.data.set_colors(curve_colors);\n  viewer.core.show_lines = false;\n\n  if (file_exists(argv[2])) {\n    printf(\"File exists! Adding points from previous run!\\n\");\n    Eigen::MatrixXd sp;\n    Eigen::MatrixXd spf;\n    igl::readOFF(argv[2], sp, spf);\n\n    // Create indices.\n    Eigen::VectorXi ids(V.rows());\n    for (int i = 0; i < V.rows(); ++i) {\n      ids(i) = i;\n    }\n\n    Eigen::VectorXd D;\n    Eigen::VectorXi I;\n    Eigen::MatrixXd CP;\n    igl::point_mesh_squared_distance(sp, V,ids, D,I,CP);\n\n    // Add them to the viewer.\n    for (int i = 0; i < sp.rows(); ++i) {\n      all_points.push_back(I(i));\n      VC.row(I(i)) << 1,0,0;\n\n      std::stringstream label;\n      label << all_points.size();\n      viewer.data.add_label(sp.row(i), label.str());\n    }\n  }\n\n  viewer.callback_key_down = [&](igl::viewer::Viewer& viewer, unsigned char key, int modifier)->bool {\n    switch(key) {\n      case 'U':\n      {\n        printf(\"Undoing last point...\\n\");\n        // Undo the last choice\n        int last = all_points.back();\n        printf(\"Undoing last choice... %d\\n\", last);\n        all_points.pop_back();\n        VC.row(last) << 1,1,1;\n        VC.row(last) *= AO(last);\n        \n        // Set the colors back to what they were.\n        viewer.data.set_colors(VC);\n        viewer.data.labels_positions.conservativeResize(all_points.size(), 3);\n        viewer.data.labels_strings.pop_back();\n        break;\n      }\n      case 'C':\n        printf(\"Setting curvature colors...\\n\");\n        viewer.data.set_colors(curve_colors);\n        break;\n      case 'D':\n        printf(\"Setting colors to highlight darkness...\\n\");\n        viewer.data.set_colors(VC);\n        break;\n      case 'W':\n      {\n        if (!writeable) {\n          return false;\n        }\n        printf(\"Writing output to %s\\n\", argv[2]);\n        // Write to output file\n        FILE* ofs = fopen(argv[2], \"w\");\n        fprintf(ofs, \"OFF\\n\");\n        fprintf(ofs, \"%d 0 0\\n\", all_points.size());\n        for (int idx : all_points) {\n          fprintf(ofs, \"%f %f %f\\n\", V(idx, 0), V(idx, 1), V(idx, 2));\n        }\n        fclose(ofs);\n        // You can quit now.\n        printf(\"Finished! Please close the program.\\n\");\n        break;\n      }\n      default:\n        // Question mark ('?')\n        if (key == '/' && modifier == GLFW_MOD_SHIFT) {\n          printHelp();\n        }\n    }\n\n    // Make sure this stays the same.\n    viewer.core.lighting_factor = \n        std::min(std::max(viewer.core.lighting_factor,0.f),1.f);\n    return false;\n  };\n  viewer.callback_mouse_down = \n      [&](igl::viewer::Viewer &viewer, int, int)->bool\n      {\n        if (!writeable) {\n          return false;\n        }\n        // fid will be the face ID. Need to get the vertex ID\n        int fid, vid;\n        // Cast a ray in the view direction starting from the mouse position\n        double x = viewer.current_mouse_x;\n        double y = viewer.core.viewport(3) - viewer.current_mouse_y;\n        if(igl::embree::unproject_onto_mesh(Eigen::Vector2f(x,y), F, \n                                            viewer.core.view * viewer.core.model,\n                                            viewer.core.proj,\n                                            viewer.core.viewport,\n                                            ei,\n                                            fid, vid)) {\n          // If it already exists, ignore it.\n          for (int i : all_points) {\n            if (vid == i) return false;\n          }\n\n          all_points.push_back(vid);\n          VC.row(vid) << 1,0,0;\n          viewer.data.set_colors(VC);\n          std::stringstream label;\n          label << all_points.size();\n          viewer.data.add_label(V.row(vid), label.str());\n\n          return true;\n        }\n        return false;\n      };\n\n  printHelp();\n  viewer.launch();\n}\n\n", "meta": {"hexsha": "1aa38bab5ead4c22b5d099624e86c4689b2cae78", "size": 9713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cgal_mesh_generation/point_selector_raw.cpp", "max_stars_repo_name": "chipbuster/skull-atlas", "max_stars_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cgal_mesh_generation/point_selector_raw.cpp", "max_issues_repo_name": "chipbuster/skull-atlas", "max_issues_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cgal_mesh_generation/point_selector_raw.cpp", "max_forks_repo_name": "chipbuster/skull-atlas", "max_forks_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1681681682, "max_line_length": 102, "alphanum_fraction": 0.5985792237, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.4377590997003496}}
{"text": "/******************************\r\n      Author: Joel Veness\r\n        Date: 2013\r\n******************************/\r\n\r\n#include \"skipcts.hpp\"\r\n#include \"fastmath.hpp\"\r\n\r\n#include <boost/random.hpp>\r\n\r\n\r\n// adaptive KT estimator parameters\r\nstatic const bool UseDiscounting = true;\r\nstatic const count_t Gamma       = 0.02f;\r\nstatic const count_t Discount    = 1.0f - Gamma;\r\nstatic const count_t KT_Alpha = 0.0625f;\r\nstatic const count_t KT_Alpha2 = KT_Alpha + KT_Alpha;\r\n\r\n\r\n// initialise weights for switching model\r\nstatic const double SplitPrior        = 0.925;\r\nstatic const double LogSplitPrior   = std::log(SplitPrior);\r\nstatic const double LogStopPrior    = std::log(1.0 - SplitPrior);\r\n\r\nstatic const double LogOneHalf = std::log(0.5);\r\n\r\nstruct prior_t {\r\n    double stop;\r\n    double split;\r\n    double skip;\r\n};\r\n\r\n\r\n// prior weights for either splitting, stopping or skipping\r\nstatic const prior_t SplitSkipPrior[] = { \r\n    { LogStopPrior,    LogSplitPrior,   std::log(0.0)   },\r\n    { std::log(0.075), std::log(0.85),  std::log(0.075) },\r\n    { std::log(0.075), std::log(0.85),  std::log(0.075) },\r\n    { std::log(0.075), std::log(0.85),  std::log(0.075) },\r\n    { std::log(0.075), std::log(0.85),  std::log(0.075) },\r\n    { std::log(0.075), std::log(0.85),  std::log(0.075) },\r\n};\r\n\r\n\r\n// zobrist key generation for context hashing\r\ntypedef boost::mt19937 randsrc_t;\r\ntypedef boost::variate_generator<randsrc_t &, boost::uniform_int<uint64_t> > zobrng_t;\r\nstatic randsrc_t randsrc(666);\r\nstatic boost::uniform_int<uint64_t> uint64_random_range(0, std::numeric_limits<uint64_t>::max());\r\nstatic zobrng_t zobrng(randsrc, uint64_random_range);\r\n\r\n\r\n// precomputed static tables\r\nzobhash_t SkipCTS::s_zobtbl[MaxDepth][2];\r\nweight_t SkipCTS::s_log_tbl[LogTblSize];\r\n\r\n\r\n/* adds two numbers represented in the logarithmic domain */\r\ninline static double fast_logadd(double log_x, double log_y) {\r\n\r\n    if (log_x < log_y) {\r\n        return fast_jacoblog(log_y - log_x) + log_x;\r\n    } else {\r\n        return fast_jacoblog(log_x - log_y) + log_y;\r\n    }\r\n}\r\n\r\n\r\n/* skip nodes */\r\nSkipNode::SkipNode() :\r\n    m_log_prob_est(LogStopPrior),\r\n    m_log_prob_split(LogSplitPrior),\r\n    m_log_prob_weighted(0.0),\r\n    m_log_skip_lik(NULL),\r\n    m_depth(-1),\r\n    m_buf(0.0)\r\n{\r\n    m_count[0] = 0.0f;\r\n    m_count[1] = 0.0f;\r\n}\r\n\r\n\r\nSkipNode::~SkipNode() {\r\n    delete [] m_log_skip_lik;\r\n}\r\n\r\n\r\n/* compute the logarithm of the KT-estimator update multiplier */\r\ninline double SkipNode::logKTMul(bit_t b) const {\r\n\r\n    return fast_log(ktMul(b));\r\n}\r\n\r\n\r\n/* compute the logarithm of the KT-estimator update multiplier */\r\ninline double SkipNode::ktMul(bit_t b) const {\r\n\r\n    count_t kt_mul_numer = m_count[b] + KT_Alpha;\r\n    count_t kt_mul_denom = m_count[0] + m_count[1] + KT_Alpha2;\r\n\r\n    return kt_mul_numer / kt_mul_denom;\r\n}\r\n\r\n\r\n/* update the KT estimates */\r\ninline void SkipNode::updateKT(bit_t b, double log_est_mul) {\r\n\r\n    if (UseDiscounting) {\r\n        m_count[0] *= Discount;\r\n        m_count[1] *= Discount;\r\n    }\r\n    m_count[b]++;\r\n}\r\n\r\n       \r\n/* precompute the zobrist hash keys used for context hashing. */\r\nvoid SkipCTS::initZobrist() {\r\n\r\n    static bool init = false;\r\n\r\n    if (!init) {\r\n        for (int i=0; i < SkipCTS::MaxDepth; i++) {\r\n            s_zobtbl[i][0] = zobrng();\r\n            s_zobtbl[i][1] = zobrng();\r\n        }\r\n        init = true;\r\n    }\r\n}\r\n\r\n\r\n/* initialise a table of precomputed logarithms */\r\nvoid SkipCTS::initLogTbl() {\r\n\r\n    static bool init = false;\r\n\r\n    if (!init) {\r\n        for (int i=0; i < SkipCTS::LogTblSize; i++) {\r\n            s_log_tbl[i] = std::log(static_cast<double>(i));\r\n        }\r\n        init = true;\r\n    }\r\n}\r\n\r\n\r\n/* initialise the hash deltas to save having to recompompute each \r\n   zobrist hash key from scratch. */\r\nvoid SkipCTS::initHashDeltas() {\r\n    \r\n    // compute the hash deltas\r\n    indices_t delta;\r\n\r\n    for (int i=m_depth; i >= 0; i--) {\r\n        \r\n        indices_list_t &il = m_indices[i];\r\n        \r\n        for (int j=0; j < il.size(); j++) {\r\n\r\n            indices_t &idxs = il[j];                \r\n            indices_t diff(m_depth);\r\n\r\n            indices_t::iterator it = std::set_symmetric_difference(\r\n                delta.begin(), delta.end(), idxs.begin(),\r\n                idxs.end(), diff.begin()\r\n            );\r\n            diff.resize(it - diff.begin());\r\n            delta = idxs;\r\n            idxs = diff;\r\n        }\r\n    }\r\n}\r\n\r\n\r\n/* initialise auxilary information such as number of remaining skips,\r\n   and the depth of the context. */\r\nvoid SkipCTS::initAuxInfo() {\r\n    \r\n    // initialise the auxilary information\r\n    for (int i=0; i <= m_depth; i++) {\r\n        \r\n        m_auxinfo.push_back(aux_info_list_t());\r\n        indices_list_t &il = m_indices[i];\r\n        \r\n        for (int j=0; j < il.size(); j++) {\r\n            \r\n            m_auxinfo.back().push_back(aux_info_t());\r\n            \r\n            // precompute last index\r\n            m_auxinfo.back().back().last_idx   = -1;\r\n            if (!il[j].empty()) \r\n                m_auxinfo.back().back().last_idx = static_cast<int>(il[j].back());\r\n            \r\n            // precompute number of skips remaining\r\n            m_auxinfo.back().back().skips_left = m_skips;\r\n            for (size_t k=0; k < il[j].size(); k++) {\r\n                if ((k == 0 &&  il[j][k] > 0) || (k > 0 &&  il[j][k] >  il[j][k-1]+1)) \r\n                    m_auxinfo.back().back().skips_left--;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n\r\n/* compute the indices for the zobrist hashes, on a per depth basis */\r\nvoid SkipCTS::initIndices() {\r\n    \r\n    for (size_t i=0; i <= m_depth; i++)\r\n        m_indices.push_back(indices_list_t());\r\n\r\n    skip_contexts_t::const_iterator it = m_skip_contexts.begin();\r\n    for ( ; it != m_skip_contexts.end(); ++it) {\r\n  \r\n        const std::string &s = *it;\r\n        int depth = static_cast<int>(std::count(s.begin(), s.end(), 'b'));\r\n        m_indices[depth].push_back(indices_t());\r\n        \r\n        for (size_t j=0; j < s.length(); j++) {\r\n            if (s[j] == 'b') m_indices[depth].back().push_back(j);\r\n        }\r\n    }\r\n}\r\n\r\n\r\n/* precomputes the context indices */\r\nvoid SkipCTS::initContexts() {\r\n\r\n    // generate contexts\r\n    m_skip_contexts.clear();\r\n    genBoundedSkipContexts(\"\", m_depth, m_skips);\r\n\r\n    initIndices();\r\n\r\n    m_skip_contexts.clear();\r\n}\r\n\r\n\r\n/* create the skip context tree */\r\nSkipCTS::SkipCTS(history_t &history, int depth, int max_skips, size_t log2_slots) :\r\n    m_history(history),\r\n    m_depth(depth),\r\n    m_skips(max_skips),\r\n    m_log_skip_preds(MaxDepth),\r\n    m_nodes(new SkipNode[size_t(1) << log2_slots]),\r\n    m_mask((size_t(1) << log2_slots)-1)\r\n{\r\n    initZobrist();\r\n    initContexts();\r\n    initAuxInfo();\r\n    initHashDeltas();\r\n    initLogTbl();\r\n}\r\n\r\n\r\nSkipCTS::~SkipCTS() {\r\n    delete [] m_nodes;\r\n}\r\n\r\n\r\n/* the logarithm of the probability of all processed experience */\r\ndouble SkipCTS::logBlockProbability() const {\r\n\r\n    return getNode(0, 0, numSubmodels(-1, m_skips)).logProbWeighted();\r\n}\r\n\r\n\r\n/* compute the switching rate for a given time t */\r\ndouble SkipCTS::switchRate(size_t t) const {\r\n\r\n    return 1.0 / double(t - m_depth + 3);\r\n}\r\n\r\n\r\nint SkipCTS::numSubmodels(int position, int skips) const {\r\n\r\n    int n = m_depth - position;\r\n    return (skips == 0) ? std::min(n, 2) : n;\r\n}\r\n\r\n\r\n/* the probability of seeing a particular symbol next */\r\ndouble SkipCTS::prob(bit_t b) {\r\n\r\n    // We proceed as with update(), except that we keep track of the symbol probability at\r\n    // each node instead of actually updating parameters\r\n    getContext();\r\n\r\n    zobhash_t hash = 0;\r\n    int skips_left, last_idx;\r\n    double symbolLogProb = LogOneHalf; \r\n\r\n    // propagate the symbol probability from leaves to root \r\n    for (int i=m_depth; i >= 0; i--) {\r\n        \r\n        // update the KT statistics, then the weighted \r\n        // probability for every node on this level\r\n        const indices_list_t &il = m_indices[i];\r\n        \r\n        for (int j=0; j < il.size(); j++) {\r\n\r\n            getContextInfo(hash, il[j]);\r\n            skips_left = m_auxinfo[i][j].skips_left;\r\n            last_idx   = m_auxinfo[i][j].last_idx;\r\n\r\n            // update the node\r\n            int n_submodels = numSubmodels(last_idx, skips_left);\r\n\r\n            SkipNode &n = getNode(hash, i, n_submodels);\r\n\r\n            // handle the stop case\r\n            double log_est_mul = n.logKTMul(b);\r\n            if (n_submodels == 1) {\r\n                n.m_buf = symbolLogProb = log_est_mul;\r\n                continue;\r\n            }\r\n                 \r\n            // Here we rely on the property that log_prob_est and the like are unnormalized\r\n            // posteriors. we accumulate the symbol log probability under 'symbolLogProb' \r\n            symbolLogProb = n.m_log_prob_est + log_est_mul;\r\n \r\n            // handle the split case\r\n            zobhash_t delta = s_zobtbl[last_idx+1][m_context[last_idx+1]];\r\n            const SkipNode &nn = getNode(hash ^ delta, i+1, numSubmodels(last_idx+1, skips_left));\r\n            // recall that m_buf contains the symbol probability at the child node\r\n            double log_split_pred = nn.m_buf;\r\n            symbolLogProb = fast_logadd(symbolLogProb, n.m_log_prob_split + log_split_pred);\r\n\r\n            // handle the skipping case\r\n            if (n_submodels > 2) {\r\n                \r\n                // if we did not yet allocate these models, this node must never have been\r\n                // updated. We assume (perhaps incorrectly) that none of this node's children\r\n                // exist and pretend they return a symbol probability of 0.5 \r\n                if (n.m_log_skip_lik == NULL) {\r\n\r\n                    const prior_t &p = SplitSkipPrior[skips_left];\r\n                    symbolLogProb = fast_logadd(symbolLogProb, p.skip + LogOneHalf); \r\n                }\r\n                \r\n                // mix in the symbol probability from the skipping models\r\n                else for (int k=last_idx+2; k < m_depth; k++) { \r\n                    \r\n                    zobhash_t h = hash ^ s_zobtbl[k][m_context[k]];\r\n                    SkipNode &sn = getNode(h, i+1, numSubmodels(k, skips_left - 1));\r\n                    \r\n                    double log_skip_pred = sn.m_buf;\r\n                    int z = k - last_idx - 2;\r\n                    symbolLogProb = fast_logadd(symbolLogProb, n.m_log_skip_lik[z] + log_skip_pred);\r\n                }\r\n            }\r\n\r\n            // Finally we normalize by the mixture probability at this node\r\n            symbolLogProb -= n.m_log_prob_weighted;\r\n            n.m_buf = symbolLogProb;\r\n\r\n            assert(n.m_buf < 0.0);\r\n        }\r\n    }\r\n   \r\n    // our scheme assumes that the last node processed is the root; the variable 'symbolLogProb'\r\n    // contains its symbol probability \r\n    return fast_exp(symbolLogProb);\r\n}\r\n\r\n\r\n/* gets the node's index into the hash table */\r\ninline SkipNode &SkipCTS::getNode(zobhash_t hash, int depth, int submodels) const {\r\n\r\n    size_t key = static_cast<size_t>(hash & m_mask);\r\n\r\n    // do a linear scan till we find either an empty slot, or\r\n    // a populated slot with matching depth\r\n    do {\r\n        if (m_nodes[key].m_depth == -1) break;\r\n        if (m_nodes[key].m_depth == depth && m_nodes[key].m_submodels == submodels) break;\r\n        key = (key + 1) & m_mask;\r\n    } while (true);\r\n\r\n    // mark the slot as used\r\n    m_nodes[key].m_depth = depth;\r\n    m_nodes[key].m_submodels = submodels;\r\n\r\n    return m_nodes[key];\r\n}\r\n\r\n\r\n/* performs the update operation to maintain a switching posterior. */\r\nvoid SkipCTS::posteriorUpdate(\r\n    SkipNode &n, double log_scale, double log_alpha, \r\n    double log_K, double log_mul, double &log_post\r\n) const {\r\n\r\n    log_post = log_scale + \r\n        fast_logadd(\r\n            log_alpha + n.m_log_prob_weighted,\r\n            log_K + log_post + log_mul\r\n        );\r\n}\r\n\r\n\r\n/* lazy allocation of skipping posterior weights. */\r\nvoid SkipCTS::lazyAllocate(SkipNode &n, int n_submodels, int skips_left) const {\r\n\r\n    n.m_log_skip_lik = new weight_t[n_submodels-2];\r\n\r\n    const prior_t &p = SplitSkipPrior[skips_left];\r\n    n.m_log_prob_est    = p.stop;\r\n    n.m_log_prob_split  = p.split;\r\n    for (int k=0; k < n_submodels-2; k++) {\r\n        n.m_log_skip_lik[k] = p.skip - s_log_tbl[n_submodels-2];  \r\n    }\r\n}\r\n\r\n\r\n/* compute the information needed to update the current context stats. */\r\nvoid SkipCTS::getContextInfo(zobhash_t &hash, const indices_t &idxs) const {\r\n\r\n    // compute the hash\r\n    for (int k=0; k < idxs.size(); k++) {\r\n        size_t x = idxs[k];\r\n        hash ^= s_zobtbl[x][m_context[x]];\r\n    }\r\n}\r\n\r\n\r\n/* process a new piece of sensory experience */\r\nvoid SkipCTS::update(bit_t b) {\r\n\r\n    getContext();\r\n\r\n    double alpha = switchRate(m_history.size());\r\n    double log_alpha = fast_log(alpha);\r\n    \r\n    zobhash_t hash = 0;\r\n    int skips_left, last_idx;\r\n\r\n    // update nodes from deepest to shallowest\r\n    for (int i=m_depth; i >= 0; i--) {\r\n        \r\n        // update the KT statistics, then the weighted \r\n        // probability for every node on this level\r\n        const indices_list_t &il = m_indices[i];\r\n        \r\n        for (int j=0; j < il.size(); j++) {\r\n\r\n            m_log_skip_preds.clear();\r\n\r\n            getContextInfo(hash, il[j]);\r\n            skips_left = m_auxinfo[i][j].skips_left;\r\n            last_idx   = m_auxinfo[i][j].last_idx;\r\n\r\n            // update the node\r\n            int n_submodels = numSubmodels(last_idx, skips_left);\r\n\r\n            SkipNode &n = getNode(hash, i, n_submodels);\r\n            n.m_buf = n.m_log_prob_weighted;\r\n\r\n            // lazy allocation of skipping prior weights\r\n            if (n_submodels > 2 && n.m_log_skip_lik == NULL)\r\n                lazyAllocate(n, n_submodels, skips_left);\r\n    \r\n            // handle the stop case\r\n            double log_est_mul = n.logKTMul(b);\r\n            if (n_submodels == 1) {\r\n                n.updateKT(b, log_est_mul);\r\n                n.m_log_prob_weighted += log_est_mul;\r\n                n.m_buf = log_est_mul;\r\n                continue;\r\n            }\r\n                 \r\n            double log_acc = n.m_log_prob_est + log_est_mul;\r\n            n.updateKT(b, log_est_mul);\r\n                \r\n            // handle the split case\r\n            zobhash_t delta = s_zobtbl[last_idx+1][m_context[last_idx+1]];\r\n            const SkipNode &nn = getNode(hash ^ delta, i+1, numSubmodels(last_idx+1, skips_left));\r\n            double log_split_pred = nn.m_buf;\r\n            log_acc = fast_logadd(log_acc, n.m_log_prob_split + log_split_pred);\r\n\r\n            // handle the skipping case\r\n            if (n_submodels > 2) {\r\n                \r\n                // update the skipping models\r\n                for (int k=last_idx+2; k < m_depth; k++) { \r\n                    \r\n                    zobhash_t h = hash ^ s_zobtbl[k][m_context[k]];\r\n                    SkipNode &sn = getNode(h, i+1, numSubmodels(k, skips_left - 1));\r\n                    \r\n                    double log_skip_pred = sn.m_buf;\r\n                    m_log_skip_preds.push_back(log_skip_pred);\r\n                    int z = k - last_idx - 2;\r\n                    log_acc = fast_logadd(log_acc, n.m_log_skip_lik[z] + log_skip_pred);\r\n                }\r\n            }\r\n\r\n            // store the weighted probability\r\n            n.m_log_prob_weighted = log_acc;\r\n\r\n            assert(n.m_log_prob_weighted < n.m_buf);\r\n            // Store the *difference* in log probability in m_buf\r\n            n.m_buf = n.m_log_prob_weighted - n.m_buf;\r\n\r\n            updatePosteriors(n, n_submodels, alpha, log_alpha, log_est_mul, log_split_pred);\r\n        }\r\n    }\r\n\r\n    m_history.push_back(b != 0);\r\n}\r\n\r\n\r\n/* update the switching posterior weights */\r\nvoid SkipCTS::updatePosteriors(SkipNode &n, int n_submodels, double alpha, \r\n    double log_alpha, double log_stop_mul, double log_split_mul) {\r\n\r\n    // update switching log-posteriors\r\n    double dn        =  static_cast<double>(n_submodels);\r\n    double K         =  (1.0 - alpha) * dn - 1.0;\r\n    double log_K     =  fast_log(K);\r\n    double log_scale = -s_log_tbl[n_submodels-1];\r\n\r\n    posteriorUpdate(n, log_scale, log_alpha, log_K, log_stop_mul, n.m_log_prob_est);\r\n    posteriorUpdate(n, log_scale, log_alpha, log_K, log_split_mul, n.m_log_prob_split);\r\n    for (int k=0; k < m_log_skip_preds.size(); k++) {\r\n        posteriorUpdate(n, log_scale, log_alpha, log_K, m_log_skip_preds[k], n.m_log_skip_lik[k]);\r\n    }\r\n}\r\n\r\n\r\n/* generate possible context strings with bounded # of skips */\r\nvoid SkipCTS::genBoundedSkipContexts(std::string buf, int depth, int skips) {\r\n\r\n    m_skip_contexts.push_back(buf);\r\n\r\n    if (depth == 0) return;\r\n\r\n    if (skips > 0) {\r\n        std::string skipstr = \"*\";\r\n        for (int i=0; i < depth-1; i++) {\r\n            genBoundedSkipContexts(buf + skipstr + \"b\", depth - (i+1) - 1, skips-1);\r\n            skipstr.append(\"*\");\r\n        }\r\n    }\r\n\r\n    genBoundedSkipContexts(buf + \"b\", depth - 1, skips);\r\n}\r\n\r\n\r\n/* prints a set of skips contexts */\r\nvoid SkipCTS::printContexts(skip_contexts_t &l) const {\r\n\r\n    skip_contexts_t::const_iterator it = l.begin();\r\n    for (; it != l.end(); ++it) {\r\n        std::cout << *it << std::endl;\r\n    }\r\n}\r\n\r\n\r\n/* compute the current binary context */\r\ninline void SkipCTS::getContext() {\r\n\r\n    size_t offset = m_history.size();\r\n    m_context.clear();\r\n\r\n    for (size_t i=0; i < m_depth; ++i) {\r\n        m_context.push_back(m_history[offset-i-1]);\r\n    }\r\n}\r\n\r\n", "meta": {"hexsha": "5c745bca33480d2bf13439fc8fb1cd73edea8fa2", "size": 17535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/skipcts.cpp", "max_stars_repo_name": "mgbellemare/SkipCTS", "max_stars_repo_head_hexsha": "ff142fa87bc16b1e2e381cf4f9e4959e754b9028", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2015-01-27T10:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T07:49:56.000Z", "max_issues_repo_path": "src/skipcts.cpp", "max_issues_repo_name": "GitHubBeinner/SkipCTS", "max_issues_repo_head_hexsha": "48af5c74ed43f724c61cdcf2e1a022f48c460ed7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-02-12T21:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-27T01:44:10.000Z", "max_forks_repo_path": "src/skipcts.cpp", "max_forks_repo_name": "GitHubBeinner/SkipCTS", "max_forks_repo_head_hexsha": "48af5c74ed43f724c61cdcf2e1a022f48c460ed7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-06-15T07:06:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-10T12:04:21.000Z", "avg_line_length": 30.9259259259, "max_line_length": 101, "alphanum_fraction": 0.570116909, "num_tokens": 4435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680199891789, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4376435693058784}}
{"text": "/*\r\n * EigenProxy.hpp\r\n *\r\n *  Created on: 12 Apr 2018\r\n *      Author: Viktor Csomor\r\n */\r\n\r\n#ifndef C_ATTL3_CORE_EIGENPROXY_H_\r\n#define C_ATTL3_CORE_EIGENPROXY_H_\r\n\r\n#define EIGEN_USE_THREADS\r\n\r\n#include <algorithm>\r\n#include <cassert>\r\n#include <cstddef>\r\n#include <Eigen/Dense>\r\n#include <iostream>\r\n#include <string>\r\n#include <thread>\r\n#include <unsupported/Eigen/CXX11/Tensor>\r\n\r\n/**\r\n * The namespace containing all classes and typedefs of the C-ATTL3 library.\r\n */\r\nnamespace cattle {\r\n\r\n/**\r\n * An alias for a single row matrix of an arbitrary scalar type.\r\n */\r\ntemplate<typename Scalar>\r\nusing RowVector = Eigen::Matrix<Scalar,1,Eigen::Dynamic,Eigen::RowMajor, 1,Eigen::Dynamic>;\r\n\r\n/**\r\n * An alias for a single column matrix of an arbitrary scalar type.\r\n */\r\ntemplate <typename Scalar>\r\nusing ColVector = Eigen::Matrix<Scalar,Eigen::Dynamic,1,Eigen::ColMajor,Eigen::Dynamic,1>;\r\n\r\n/**\r\n * An alias for a dynamically sized matrix of an arbitrary scalar type.\r\n */\r\ntemplate<typename Scalar>\r\nusing Matrix = Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor,\r\n\t\tEigen::Dynamic,Eigen::Dynamic>;\r\n\r\n/**\r\n * An alias for a class that can be used to map raw pointer data to a dynamically\r\n * sized Matrix of an arbitrary scalar type.\r\n */\r\ntemplate<typename Scalar>\r\nusing MatrixMap = Eigen::Map<Matrix<Scalar>>;\r\n\r\n/**\r\n * An alias for a tensor of arbitrary rank and scalar type with dynamic dimensionality.\r\n */\r\ntemplate<typename Scalar, std::size_t Rank>\r\nusing Tensor = Eigen::Tensor<Scalar,Rank,Eigen::ColMajor,std::size_t>;\r\n\r\n/**\r\n * An for a class that can be used to map raw pointer data to a tensor of arbitrary\r\n * rank and scalar type with dynamic dimensionality.\r\n */\r\ntemplate<typename Scalar, std::size_t Rank>\r\nusing TensorMap = Eigen::TensorMap<Tensor<Scalar,Rank>>;\r\n\r\n/**\r\n * An alias for permutation matrices.\r\n */\r\nusing PermMatrix = Eigen::PermutationMatrix<Eigen::Dynamic,Eigen::Dynamic>;\r\n\r\n/**\r\n * An alias for self-adjoint eigen solvers.\r\n */\r\ntemplate<typename Scalar>\r\nusing EigenSolver = Eigen::SelfAdjointEigenSolver<Matrix<Scalar>>;\r\n\r\n/**\r\n * An alias for Eigen's bi-diagonal divide and conquer singular-value decomposition.\r\n */\r\ntemplate<typename Scalar>\r\nusing SVD = Eigen::BDCSVD<Matrix<Scalar>>;\r\n\r\n/**\r\n * An alias for Eigen's singular-value decomposition options.\r\n */\r\nusing SVDOptions = Eigen::DecompositionOptions;\r\n\r\n/**\r\n * @return The number of threads used by Eigen to accelerate operations\r\n * supporting multithreading.\r\n */\r\ninline int num_of_eval_threads() {\r\n\treturn Eigen::nbThreads();\r\n}\r\n\r\n/**\r\n * @param num_of_threads The number of threads Eigen should use to accelerate\r\n * operations supporting multithreading. The lower bound of the actual value\r\n * applied is 1 while the upper bound is the maximum of 1 and the level of\r\n * hardware concurrency detected.\r\n */\r\ninline void set_num_of_eval_threads(int num_of_threads) {\r\n\tint max = std::max(1, (int) std::thread::hardware_concurrency());\r\n\tEigen::setNbThreads(std::max(1, std::min(num_of_threads, max)));\r\n}\r\n\r\n/**\r\n * It serializes the matrix in a format such that the first two numbers denote the\r\n * matrix's number of rows and columns respectively and the remaining numbers represent\r\n * the coefficients of the matrix in column-major order.\r\n *\r\n * @param matrix The matrix to serialize.\r\n * @param out_stream The non-binary stream to serialize the matrix to.\r\n */\r\ntemplate<typename Scalar>\r\ninline void serialize(const Matrix<Scalar>& matrix, std::ostream& out_stream) {\r\n\tout_stream << sizeof(Scalar);\r\n\tout_stream << \" \" << matrix.rows();\r\n\tout_stream << \" \" << matrix.cols();\r\n\tfor (std::size_t i = 0; i < matrix.size(); ++i)\r\n\t\tout_stream << \" \" << *(matrix.data() + i);\r\n\tout_stream << std::flush;\r\n}\r\n\r\n/**\r\n * It serializes the matrix into a file at the specified file path.\r\n *\r\n * @param matrix The matrix to serialize.\r\n * @param file_path The path to the file to which the matrix is to be serialized.\r\n */\r\ntemplate<typename Scalar>\r\ninline void serialize(const Matrix<Scalar>& matrix, const std::string& file_path) {\r\n\tstd::ofstream out_stream(file_path);\r\n\tassert(out_stream.is_open());\r\n\tserialize<Scalar>(matrix, out_stream);\r\n}\r\n\r\n/**\r\n * It serializes the matrix in a format such that the first 2 bytes denote the size of\r\n * a single coefficient of the matrix in bytes, the second and third 4 bytes denote the\r\n * matrix's number of rows and columns respectively, and the remaining bytes contain\r\n * the coefficients of the matrix in column-major order.\r\n *\r\n * @param matrix The matrix to serialize.\r\n * @param out_stream The binary stream to serialize the matrix to.\r\n */\r\ntemplate<typename Scalar>\r\ninline void serialize_binary(const Matrix<Scalar>& matrix, std::ostream& out_stream) {\r\n\tunsigned short scalar_size = static_cast<unsigned short>(sizeof(Scalar));\r\n\tout_stream.write(reinterpret_cast<const char*>(&scalar_size),\r\n\t\t\tstd::streamsize(sizeof(unsigned short)));\r\n\tunsigned rows = static_cast<unsigned>(matrix.rows());\r\n\tunsigned cols = static_cast<unsigned>(matrix.cols());\r\n\tout_stream.write(reinterpret_cast<const char*>(&rows), std::streamsize(sizeof(unsigned)));\r\n\tout_stream.write(reinterpret_cast<const char*>(&cols), std::streamsize(sizeof(unsigned)));\r\n\tout_stream.write(reinterpret_cast<const char*>(matrix.data()),\r\n\t\t\tstd::streamsize(matrix.size() * sizeof(Scalar)));\r\n\tout_stream << std::flush;\r\n}\r\n\r\n/**\r\n * It serializes the matrix into a binary file at the specified file path.\r\n *\r\n * @param matrix The matrix to serialize.\r\n * @param file_path The path to the binary file to which the matrix is to be serialized.\r\n */\r\ntemplate<typename Scalar>\r\ninline void serialize_binary(const Matrix<Scalar>& matrix, const std::string& file_path) {\r\n\tstd::ofstream out_stream(file_path, std::ios::binary);\r\n\tassert(out_stream.is_open());\r\n\tserialize_binary<Scalar>(matrix, out_stream);\r\n}\r\n\r\n/**\r\n * It deserializes a matrix assuming the serialized format matches that used by the\r\n * serialize() method.\r\n *\r\n * @param in_stream The stream to the serialized matrix.\r\n * @return The unserialized matrix.\r\n */\r\ntemplate<typename Scalar>\r\ninline Matrix<Scalar> deserialize(std::istream& in_stream) {\r\n\tunsigned rows, cols;\r\n\tin_stream >> rows;\r\n\tin_stream >> cols;\r\n\tMatrix<Scalar> matrix(rows, cols);\r\n\tfor (std::size_t i = 0; i < matrix.size(); ++i)\r\n\t\tin_stream >> *(matrix.data() + i);\r\n\treturn matrix;\r\n}\r\n\r\n/**\r\n * It deserializes a matrix from the file at the provided file path.\r\n *\r\n * @param file_path The path to the file containing the serialized matrix.\r\n * @return The deserialized matrix.\r\n */\r\ntemplate<typename Scalar>\r\ninline Matrix<Scalar> deserialize(const std::string& file_path) {\r\n\tstd::ifstream in_stream(file_path);\r\n\tassert(in_stream.is_open());\r\n\treturn deserialize<Scalar>(in_stream);\r\n}\r\n\r\n/**\r\n * It deserializes a matrix assuming the serialized format matches that used by the\r\n * serialize_binary() method.\r\n *\r\n * @param in_stream The binary stream to the serialized matrix.\r\n * @return The unserialized matrix.\r\n */\r\ntemplate<typename Scalar>\r\ninline Matrix<Scalar> deserialize_binary(std::istream& in_stream) {\r\n\tunsigned short scalar_size;\r\n\tin_stream.read(reinterpret_cast<char*>(&scalar_size), std::streamsize(sizeof(unsigned short)));\r\n\tassert(scalar_size == sizeof(Scalar));\r\n\tunsigned rows, cols;\r\n\tin_stream.read(reinterpret_cast<char*>(&rows), std::streamsize(sizeof(unsigned)));\r\n\tin_stream.read(reinterpret_cast<char*>(&cols), std::streamsize(sizeof(unsigned)));\r\n\tMatrix<Scalar> matrix(rows, cols);\r\n\tin_stream.read(reinterpret_cast<char*>(matrix.data()),\r\n\t\t\tstd::streamsize(matrix.size() * sizeof(Scalar)));\r\n\treturn matrix;\r\n}\r\n\r\n/**\r\n * It deserializes a matrix from the binary file at the provided file path.\r\n *\r\n * @param file_path The path to the binary file containing the serialized matrix.\r\n * @return The deserialized matrix.\r\n */\r\ntemplate<typename Scalar>\r\ninline Matrix<Scalar> deserialize_binary(const std::string& file_path) {\r\n\tstd::ifstream in_stream(file_path, std::ios::binary);\r\n\tassert(in_stream.is_open());\r\n\treturn deserialize_binary<Scalar>(in_stream);\r\n}\r\n\r\n}\r\n\r\n#endif /* C_ATTL3_CORE_EIGENPROXY_H_ */\r\n", "meta": {"hexsha": "9a57b5ad6eccf0d9dcb5dfaf268ab407d28c966d", "size": 8155, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "C-ATTL3/core/EigenProxy.hpp", "max_stars_repo_name": "ViktorC/CppNN", "max_stars_repo_head_hexsha": "daf7207fdc047412957761ef412fa805b2656d65", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2018-07-03T09:39:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T07:53:09.000Z", "max_issues_repo_path": "C-ATTL3/core/EigenProxy.hpp", "max_issues_repo_name": "Merlin1A/C-ATTL3", "max_issues_repo_head_hexsha": "daf7207fdc047412957761ef412fa805b2656d65", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C-ATTL3/core/EigenProxy.hpp", "max_forks_repo_name": "Merlin1A/C-ATTL3", "max_forks_repo_head_hexsha": "daf7207fdc047412957761ef412fa805b2656d65", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-11-01T09:38:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T00:41:05.000Z", "avg_line_length": 33.6983471074, "max_line_length": 97, "alphanum_fraction": 0.719558553, "num_tokens": 1769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4376435559066508}}
{"text": "/*\n * GridMapMath.hpp\n *\n *  Created on: Dec 2, 2013\n *      Author: Péter Fankhauser\n *\t Institute: ETH Zurich, Autonomous Systems Lab\n */\n\n#pragma once\n\n#include \"grid_map_core/TypeDefs.hpp\"\n#include \"grid_map_core/BufferRegion.hpp\"\n\n#include <Eigen/Core>\n#include <vector>\n#include <map>\n\nnamespace grid_map {\n\n/*!\n * Gets the position of a cell specified by its index in the map frame.\n * @param[out] position the position of the center of the cell in the map frame.\n * @param[in] index of the cell.\n * @param[in] mapLength the lengths in x and y direction.\n * @param[in] mapPosition the position of the map.\n * @param[in] resolution the resolution of the map.\n * @param[in] bufferSize the size of the buffer (optional).\n * @param[in] bufferStartIndex the index of the starting point of the circular buffer (optional).\n * @return true if successful, false if index not within range of buffer.\n */\nbool getPositionFromIndex(Eigen::Vector2d& position,\n                          const Eigen::Array2i& index,\n                          const Eigen::Array2d& mapLength,\n                          const Eigen::Vector2d& mapPosition,\n                          const double& resolution,\n                          const Eigen::Array2i& bufferSize,\n                          const Eigen::Array2i& bufferStartIndex = Eigen::Array2i::Zero());\n\n/*!\n * Gets the index of the cell which contains a position in the map frame.\n * @param[out] index of the cell.\n * @param[in] position the position in the map frame.\n * @param[in] mapLength the lengths in x and y direction.\n * @param[in] mapPosition the position of the map.\n * @param[in] resolution the resolution of the map.\n * @param[in] bufferSize the size of the buffer (optional).\n * @param[in] bufferStartIndex the index of the starting point of the circular buffer (optional).\n * @return true if successful, false if position outside of map.\n */\nbool getIndexFromPosition(Eigen::Array2i& index,\n                          const Eigen::Vector2d& position,\n                          const Eigen::Array2d& mapLength,\n                          const Eigen::Vector2d& mapPosition,\n                          const double& resolution,\n                          const Eigen::Array2i& bufferSize,\n                          const Eigen::Array2i& bufferStartIndex = Eigen::Array2i::Zero());\n\n/*!\n * Checks if position is within the map boundaries.\n * @param[in] position the position which is to be checked.\n * @param[in] mapLength the length of the map.\n * @param[in] mapPosition the position of the map.\n * @return true if position is within map, false otherwise.\n */\nbool checkIfPositionWithinMap(const Eigen::Vector2d& position,\n                              const Eigen::Array2d& mapLength,\n                              const Eigen::Vector2d& mapPosition);\n\n/*!\n * Gets the position of the data structure origin.\n * @param[in] position the position of the map.\n * @param[in] mapLength the map length.\n * @param[out] positionOfOrigin the position of the data structure origin.\n */\nvoid getPositionOfDataStructureOrigin(const Eigen::Vector2d& position,\n                                      const Eigen::Array2d& mapLength,\n                                      Eigen::Vector2d& positionOfOrigin);\n\n/*!\n * Computes how many cells/indeces the map is moved based on a position shift in\n * the grid map frame. Use this function if you are moving the grid map\n * and want to ensure that the cells match before and after.\n * @param[out] indexShift the corresponding shift of the indices.\n * @param[in] positionShift the desired position shift.\n * @param[in] resolution the resolution of the map.\n * @return true if successful.\n */\nbool getIndexShiftFromPositionShift(Eigen::Array2i& indexShift,\n                                    const Eigen::Vector2d& positionShift,\n                                    const double& resolution);\n\n/*!\n * Computes the corresponding position shift from a index shift. Use this function\n * if you are moving the grid map and want to ensure that the cells match\n * before and after.\n * @param[out] positionShift the corresponding shift in position in the grid map frame.\n * @param[in] indexShift the desired shift of the indeces.\n * @param[in] resolution the resolution of the map.\n * @return true if successful.\n */\nbool getPositionShiftFromIndexShift(Eigen::Vector2d& positionShift,\n                                    const Eigen::Array2i& indexShift,\n                                    const double& resolution);\n\n/*!\n * Checks if index is within range of the buffer.\n * @param[in] index to check.\n * @param[in] bufferSize the size of the buffer.\n * @return true if index is within, and false if index is outside of the buffer.\n */\nbool checkIfIndexWithinRange(const Eigen::Array2i& index, const Eigen::Array2i& bufferSize);\n\n/*!\n * Maps an index that runs out of the range of the circular buffer back into allowed the region.\n * This is the 2d version of mapIndexWithinRange(int&, const int&).\n * @param[in/out] index the indeces that will be mapped into the valid region of the buffer.\n * @param[in] bufferSize the size of the buffer.\n */\nvoid mapIndexWithinRange(Eigen::Array2i& index,\n                         const Eigen::Array2i& bufferSize);\n\n/*!\n * Maps an index that runs out of the range of the circular buffer back into allowed the region.\n * @param[in/out] index the index that will be mapped into the valid region of the buffer.\n * @param[in] bufferSize the size of the buffer.\n */\nvoid mapIndexWithinRange(int& index, const int& bufferSize);\n\n/*!\n * Limits (cuts off) the position to lie inside the map.\n * @param[in/out] position the position to be limited.\n * @param[in] mapLength the lengths in x and y direction.\n * @param[in] mapPosition the position of the map.\n */\nvoid limitPositionToRange(Eigen::Vector2d& position,\n                          const Eigen::Array2d& mapLength,\n                          const Eigen::Vector2d& mapPosition);\n\n/*!\n * Provides the alignment transformation from the buffer order (outer/inner storage)\n * and the map frame (x/y-coordinate).\n * @return the alignment transformation.\n */\nconst Eigen::Matrix2i getBufferOrderToMapFrameAlignment();\n\n/*!\n * Given a map and a desired submap (defined by position and size), this function computes\n * various information about the submap. The returned submap might be smaller than the requested\n * size as it respects the boundaries of the map.\n * @param[out] submapTopLeftIndex the top left index of the returned submap.\n * @param[out] submapBufferSize the buffer size of the returned submap.\n * @param[out] submapPosition the position of the submap (center) in the map frame.\n * @param[out] submapLength the length of the submap.\n * @param[out] requestedIndexInSubmap the index in the submap that corresponds to the requested\n *             position of the submap.\n * @param[in] requestedSubmapPosition the requested submap position (center) in the map frame.\n * @param[in] requestedSubmapLength the requested submap length.\n * @param[in] mapLength the lengths in x and y direction.\n * @param[in] mapPosition the position of the map.\n * @param[in] resolution the resolution of the map.\n * @param[in] bufferSize the buffer size of the map.\n * @param[in] bufferStartIndex the index of the starting point of the circular buffer (optional).\n * @return true if successful.\n */\nbool getSubmapInformation(Eigen::Array2i& submapTopLeftIndex,\n                          Eigen::Array2i& submapBufferSize,\n                          Eigen::Vector2d& submapPosition,\n                          Eigen::Array2d& submapLength,\n                          Eigen::Array2i& requestedIndexInSubmap,\n                          const Eigen::Vector2d& requestedSubmapPosition,\n                          const Eigen::Vector2d& requestedSubmapLength,\n                          const Eigen::Array2d& mapLength,\n                          const Eigen::Vector2d& mapPosition,\n                          const double& resolution,\n                          const Eigen::Array2i& bufferSize,\n                          const Eigen::Array2i& bufferStartIndex = Eigen::Array2i::Zero());\n\n/*!\n * Computes the regions in the circular buffer that make up the data for\n * a requested submap.\n * @param[out] submapBufferRegions the list of buffer regions that make up the submap.\n * @param[in] submapIndex the index (top-left) for the requested submap.\n * @param[in] submapBufferSize the size of the requested submap.\n * @param[in] bufferSize the buffer size of the map.\n * @param[in] bufferStartIndex the index of the starting point of the circular buffer (optional).\n * @return true if successful, false if requested submap is not fully contained in the map.\n */\nbool getBufferRegionsForSubmap(std::vector<BufferRegion>& submapBufferRegions,\n                               const Index& submapIndex,\n                               const Size& submapBufferSize,\n                               const Size& bufferSize,\n                               const Index& bufferStartIndex = Index::Zero());\n\n/*!\n * Increases the index by one to iterate through the map.\n * Increments either to the neighboring index to the right or to\n * the start of the lower row. Returns false if end of iterations are reached.\n * @param[in/out] index the index in the map that is incremented (corrected for the circular buffer).\n * @param[in] bufferSize the map buffer size.\n * @param[in] bufferStartIndex the map buffer start index.\n * @return true if successfully incremented indeces, false if end of iteration limits are reached.\n */\nbool incrementIndex(Eigen::Array2i& index, const Eigen::Array2i& bufferSize,\n                    const Eigen::Array2i& bufferStartIndex = Eigen::Array2i::Zero());\n\n/*!\n * Increases the index by one to iterate through the cells of a submap.\n * Increments either to the neighboring index to the right or to\n * the start of the lower row. Returns false if end of iterations are reached.\n *\n * Note: This function does not check if submap actually fits to the map. This needs\n * to be checked before separately.\n *\n * @param[in/out] submapIndex the index in the submap that is incremented.\n * @param[out] index the index in the map that is incremented (corrected for the circular buffer).\n * @param[in] submapTopLefIndex the top left index of the submap.\n * @param[in] submapBufferSize the submap buffer size.\n * @param[in] bufferSize the map buffer size.\n * @param[in] bufferStartIndex the map buffer start index.\n * @return true if successfully incremented indeces, false if end of iteration limits are reached.\n */\nbool incrementIndexForSubmap(Eigen::Array2i& submapIndex, Eigen::Array2i& index,\n                             const Eigen::Array2i& submapTopLeftIndex,\n                             const Eigen::Array2i& submapBufferSize,\n                             const Eigen::Array2i& bufferSize,\n                             const Eigen::Array2i& bufferStartIndex = Eigen::Array2i::Zero());\n\n/*!\n * Retrieve the index as unwrapped index, i.e., as the corresponding index of a\n * grid map with no circular buffer offset.\n * @param bufferIndex the index in the circular buffer.\n * @param bufferSize the map buffer size.\n * @param bufferStartIndex the map buffer start index.\n * @return the unwrapped index.\n */\nIndex getIndexFromBufferIndex(const Index& bufferIndex, const Size& bufferSize,\n                              const Index& bufferStartIndex);\n\n/*!\n * Returns the 1d index corresponding to the 2d index for either row- or column-major format.\n * Note: Eigen is defaulting to column-major format.\n * @param[in] index the 2d index.\n * @param[in] bufferSize the map buffer size.\n * @param[in] (optional) rowMajor if the 1d index is generated for row-major format.\n * @return the 1d index.\n */\nunsigned int get1dIndexFrom2dIndex(const Index& index, const Size& bufferSize,\n                                   const bool rowMajor);\n\n/*!\n * Generates a list of indices for a region in the map.\n * @param regionIndex the region top-left index.\n * @param regionSize the region size.\n * @param indices the list of indices of the region.\n */\nvoid getIndicesForRegion(const Index& regionIndex, const Size& regionSize,\n                         std::vector<Index> indices);\n\n/*!\n * Generates a list of indices for multiple regions in the map.\n * This method makes sure every index is only once contained in the list.\n * @param regionIndeces the regions' top-left index.\n * @param regionSizes the regions' sizes.\n * @param indices the list of indices of the regions.\n */\nvoid getIndicesForRegions(const std::vector<Index>& regionIndeces, const Size& regionSizes,\n                          std::vector<Index> indices);\n\n} // namespace\n", "meta": {"hexsha": "10862a6e08b7795a78df8bc7ed6595936888500d", "size": 12656, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "grid_map_core/include/grid_map_core/GridMapMath.hpp", "max_stars_repo_name": "Yvaine/grid_map_avoidance", "max_stars_repo_head_hexsha": "bf37623abce89074ba71ee65a3e06400f0a50744", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-29T01:29:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T08:29:27.000Z", "max_issues_repo_path": "grid_map_core/include/grid_map_core/GridMapMath.hpp", "max_issues_repo_name": "ycb88/grid_map", "max_issues_repo_head_hexsha": "93ca546f48012b7b0c500c730bd7d878c9a4e47e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grid_map_core/include/grid_map_core/GridMapMath.hpp", "max_forks_repo_name": "ycb88/grid_map", "max_forks_repo_head_hexsha": "93ca546f48012b7b0c500c730bd7d878c9a4e47e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-17T08:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-17T08:29:30.000Z", "avg_line_length": 46.8740740741, "max_line_length": 101, "alphanum_fraction": 0.6751738306, "num_tokens": 2771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4376227434927769}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file    Rot3.cpp\n * @brief   Rotation, common code between Rotation matrix and Quaternion\n * @author  Alireza Fathi\n * @author  Christian Potthast\n * @author  Frank Dellaert\n * @author  Richard Roberts\n * @author  Varun Agrawal\n */\n\n#include <gtsam/geometry/Rot3.h>\n#include <gtsam/geometry/SO3.h>\n#include <boost/math/constants/constants.hpp>\n\n#include <cmath>\n#include <random>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/* ************************************************************************* */\nvoid Rot3::print(const std::string& s) const {\n  cout << (s.empty() ? \"R: \" : s + \" \");\n  gtsam::print(static_cast<Matrix>(matrix()));\n}\n\n/* ************************************************************************* */\nRot3 Rot3::Random(std::mt19937& rng) {\n  Unit3 axis = Unit3::Random(rng);\n  uniform_real_distribution<double> randomAngle(-M_PI, M_PI);\n  double angle = randomAngle(rng);\n  return AxisAngle(axis, angle);\n}\n\n\n\n/* ************************************************************************* */\nRot3 Rot3::AlignPair(const Unit3& axis, const Unit3& a_p, const Unit3& b_p) {\n  // if a_p is already aligned with b_p, return the identity rotation\n  if (std::abs(a_p.dot(b_p)) > 0.999999999) {\n    return Rot3();\n  }\n\n  // Check axis was not degenerate cross product\n  const Vector3 z = axis.unitVector();\n  if (z.hasNaN())\n    throw std::runtime_error(\"AlignSinglePair: axis has Nans\");\n\n  // Now, calculate rotation that takes b_p to a_p\n  const Matrix3 P = I_3x3 - z * z.transpose();  // orthogonal projector\n  const Vector3 a_po = P * a_p.unitVector();    // point in a orthogonal to axis\n  const Vector3 b_po = P * b_p.unitVector();    // point in b orthogonal to axis\n  const Vector3 x = a_po.normalized();          // x-axis in axis-orthogonal plane, along a_p vector\n  const Vector3 y = z.cross(x);                 // y-axis in axis-orthogonal plane\n  const double u = x.dot(b_po);                 // x-coordinate for b_po\n  const double v = y.dot(b_po);                 // y-coordinate for b_po\n  double angle = std::atan2(v, u);\n  return Rot3::AxisAngle(z, -angle);\n}\n\n/* ************************************************************************* */\nRot3 Rot3::AlignTwoPairs(const Unit3& a_p, const Unit3& b_p,  //\n                         const Unit3& a_q, const Unit3& b_q) {\n  // there are three frames in play:\n  // a: the first frame in which p and q are measured\n  // b: the second frame in which p and q are measured\n  // i: intermediate, after aligning first pair\n\n  // First, find rotation around that aligns a_p and b_p\n  Rot3 i_R_b = AlignPair(a_p.cross(b_p), a_p, b_p);\n\n  // Rotate points in frame b to the intermediate frame,\n  // in which we expect the point p to be aligned now\n  Unit3 i_q = i_R_b * b_q;\n  assert(assert_equal(a_p, i_R_b * b_p, 1e-6));\n\n  // Now align second pair: we need to align i_q to a_q\n  Rot3 a_R_i = AlignPair(a_p, a_q, i_q);\n  assert(assert_equal(a_p, a_R_i * a_p, 1e-6));\n  assert(assert_equal(a_q, a_R_i * i_q, 1e-6));\n\n  // The desired rotation is the product of both\n  Rot3 a_R_b = a_R_i * i_R_b;\n  return a_R_b;\n}\n\n/* ************************************************************************* */\nbool Rot3::equals(const Rot3 & R, double tol) const {\n  return equal_with_abs_tol(matrix(), R.matrix(), tol);\n}\n\n/* ************************************************************************* */\nPoint3 Rot3::operator*(const Point3& p) const {\n  return rotate(p);\n}\n\n/* ************************************************************************* */\nUnit3 Rot3::rotate(const Unit3& p,\n    OptionalJacobian<2,3> HR, OptionalJacobian<2,2> Hp) const {\n  Matrix32 Dp;\n  Unit3 q = Unit3(rotate(p.point3(Hp ? &Dp : 0)));\n  if (Hp) *Hp = q.basis().transpose() * matrix() * Dp;\n  if (HR) *HR = -q.basis().transpose() * matrix() * p.skew();\n  return q;\n}\n\n/* ************************************************************************* */\nUnit3 Rot3::unrotate(const Unit3& p,\n    OptionalJacobian<2,3> HR, OptionalJacobian<2,2> Hp) const {\n  Matrix32 Dp;\n  Unit3 q = Unit3(unrotate(p.point3(Dp)));\n  if (Hp) *Hp = q.basis().transpose() * matrix().transpose () * Dp;\n  if (HR) *HR = q.basis().transpose() * q.skew();\n  return q;\n}\n\n/* ************************************************************************* */\nUnit3 Rot3::operator*(const Unit3& p) const {\n  return rotate(p);\n}\n\n/* ************************************************************************* */\n// see doc/math.lyx, SO(3) section\nPoint3 Rot3::unrotate(const Point3& p, OptionalJacobian<3,3> H1,\n    OptionalJacobian<3,3> H2) const {\n  const Matrix3& Rt = transpose();\n  Point3 q(Rt * p); // q = Rt*p\n  const double wx = q.x(), wy = q.y(), wz = q.z();\n  if (H1)\n    *H1 << 0.0, -wz, +wy, +wz, 0.0, -wx, -wy, +wx, 0.0;\n  if (H2)\n    *H2 = Rt;\n  return q;\n}\n\n/* ************************************************************************* */\nPoint3 Rot3::column(int index) const{\n  if(index == 3)\n    return r3();\n  else if(index == 2)\n    return r2();\n  else if(index == 1)\n    return r1(); // default returns r1\n  else\n    throw invalid_argument(\"Argument to Rot3::column must be 1, 2, or 3\");\n}\n\n/* ************************************************************************* */\nVector3 Rot3::xyz(OptionalJacobian<3, 3> H) const {\n  Matrix3 I;Vector3 q;\n  if (H) {\n    Matrix93 mH;\n    const auto m = matrix();\n#ifdef GTSAM_USE_QUATERNIONS\n    SO3{m}.vec(mH);\n#else\n    rot_.vec(mH);\n#endif\n\n    Matrix39 qHm;\n    boost::tie(I, q) = RQ(m, qHm);\n\n    // TODO : Explore whether this expression can be optimized as both\n    // qHm and mH are super-sparse\n    *H = qHm * mH;\n  } else\n    boost::tie(I, q) = RQ(matrix());\n  return q;\n}\n\n/* ************************************************************************* */\nVector3 Rot3::ypr(OptionalJacobian<3, 3> H) const {\n  Vector3 q = xyz(H);\n  if (H) H->row(0).swap(H->row(2));\n\n  return Vector3(q(2),q(1),q(0));\n}\n\n/* ************************************************************************* */\nVector3 Rot3::rpy(OptionalJacobian<3, 3> H) const { return xyz(H); }\n\n/* ************************************************************************* */\ndouble Rot3::roll(OptionalJacobian<1, 3> H) const {\n  double r;\n  if (H) {\n    Matrix3 xyzH;\n    r = xyz(xyzH)(0);\n    *H = xyzH.row(0);\n  } else\n    r = xyz()(0);\n  return r;\n}\n\n/* ************************************************************************* */\ndouble Rot3::pitch(OptionalJacobian<1, 3> H) const {\n  double p;\n  if (H) {\n    Matrix3 xyzH;\n    p = xyz(xyzH)(1);\n    *H = xyzH.row(1);\n  } else\n    p = xyz()(1);\n  return p;\n}\n\n/* ************************************************************************* */\ndouble Rot3::yaw(OptionalJacobian<1, 3> H) const {\n  double y;\n  if (H) {\n    Matrix3 xyzH;\n    y = xyz(xyzH)(2);\n    *H = xyzH.row(2);\n  } else\n    y = xyz()(2);\n  return y;\n}\n\n/* ************************************************************************* */\n#ifdef GTSAM_ALLOW_DEPRECATED_SINCE_V42\nVector Rot3::quaternion() const {\n  gtsam::Quaternion q = toQuaternion();\n  Vector v(4);\n  v(0) = q.w();\n  v(1) = q.x();\n  v(2) = q.y();\n  v(3) = q.z();\n  return v;\n}\n#endif\n\n/* ************************************************************************* */\npair<Unit3, double> Rot3::axisAngle() const {\n  const Vector3 omega = Rot3::Logmap(*this);\n  return std::pair<Unit3, double>(Unit3(omega), omega.norm());\n}\n\n/* ************************************************************************* */\nMatrix3 Rot3::ExpmapDerivative(const Vector3& x) {\n  return SO3::ExpmapDerivative(x);\n}\n\n/* ************************************************************************* */\nMatrix3 Rot3::LogmapDerivative(const Vector3& x)    {\n  return SO3::LogmapDerivative(x);\n}\n\n/* ************************************************************************* */\npair<Matrix3, Vector3> RQ(const Matrix3& A, OptionalJacobian<3, 9> H) {\n  const double x = -atan2(-A(2, 1), A(2, 2));\n  const auto Qx = Rot3::Rx(-x).matrix();\n  const Matrix3 B = A * Qx;\n\n  const double y = -atan2(B(2, 0), B(2, 2));\n  const auto Qy = Rot3::Ry(-y).matrix();\n  const Matrix3 C = B * Qy;\n\n  const double z = -atan2(-C(1, 0), C(1, 1));\n  const auto Qz = Rot3::Rz(-z).matrix();\n  const Matrix3 R = C * Qz;\n\n  if (H) {\n    if (std::abs(y - M_PI / 2) < 1e-2)\n      throw std::runtime_error(\n          \"Rot3::RQ : Derivative undefined at singularity (gimbal lock)\");\n\n    auto atan_d1 = [](double y, double x) { return x / (x * x + y * y); };\n    auto atan_d2 = [](double y, double x) { return -y / (x * x + y * y); };\n\n    const auto sx = -Qx(2, 1), cx = Qx(1, 1);\n    const auto sy = -Qy(0, 2), cy = Qy(0, 0);\n\n    *H = Matrix39::Zero();\n    // First, calculate the derivate of x\n    (*H)(0, 5) = atan_d1(A(2, 1), A(2, 2));\n    (*H)(0, 8) = atan_d2(A(2, 1), A(2, 2));\n\n    // Next, calculate the derivate of y. We have\n    // b20 = a20 and b22 = a21 * sx + a22 * cx\n    (*H)(1, 2) = -atan_d1(B(2, 0), B(2, 2));\n    const auto yHb22 = -atan_d2(B(2, 0), B(2, 2));\n    (*H)(1, 5) = yHb22 * sx;\n    (*H)(1, 8) = yHb22 * cx;\n\n    // Next, calculate the derivate of z. We have\n    // c10 = a10 * cy + a11 * sx * sy + a12 * cx * sy\n    // c11 = a11 * cx - a12 * sx\n    const auto c10Hx = (A(1, 1) * cx - A(1, 2) * sx) * sy;\n    const auto c10Hy = A(1, 2) * cx * cy + A(1, 1) * cy * sx - A(1, 0) * sy;\n    Vector9 c10HA = c10Hx * H->row(0) + c10Hy * H->row(1);\n    c10HA[1] = cy;\n    c10HA[4] = sx * sy;\n    c10HA[7] = cx * sy;\n\n    const auto c11Hx = -A(1, 2) * cx - A(1, 1) * sx;\n    Vector9 c11HA = c11Hx * H->row(0);\n    c11HA[4] = cx;\n    c11HA[7] = -sx;\n\n    H->block<1, 9>(2, 0) =\n        atan_d1(C(1, 0), C(1, 1)) * c10HA + atan_d2(C(1, 0), C(1, 1)) * c11HA;\n  }\n\n  const auto xyz = Vector3(x, y, z);\n  return make_pair(R, xyz);\n}\n\n/* ************************************************************************* */\nostream &operator<<(ostream &os, const Rot3& R) {\n  os << R.matrix().format(matlabFormat());\n  return os;\n}\n\n/* ************************************************************************* */\nRot3 Rot3::slerp(double t, const Rot3& other) const {\n  return interpolate(*this, other, t);\n}\n\n/* ************************************************************************* */\n\n} // namespace gtsam\n\n", "meta": {"hexsha": "6db5e1919595cfabf379f03fdf91e54146e32ce7", "size": 10555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Rot3.cpp", "max_stars_repo_name": "mcx/gtsam", "max_stars_repo_head_hexsha": "784f16fe750b350c9faa67b6656cac52d0dd8624", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gtsam/geometry/Rot3.cpp", "max_issues_repo_name": "mcx/gtsam", "max_issues_repo_head_hexsha": "784f16fe750b350c9faa67b6656cac52d0dd8624", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/geometry/Rot3.cpp", "max_forks_repo_name": "mcx/gtsam", "max_forks_repo_head_hexsha": "784f16fe750b350c9faa67b6656cac52d0dd8624", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6017964072, "max_line_length": 100, "alphanum_fraction": 0.4803410706, "num_tokens": 3101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4376227371750012}}
{"text": "/**\n *  Moore-Greitzer engine DBA control with the specification-guided engine.\n *  \n *  Created by Yinan Li on July 3, 2020.\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstdlib>\n#include <sys/stat.h>\n\n#include <string>\n#include <cmath>\n#include <boost/numeric/odeint.hpp>\n\n#include \"src/DBAparser.h\"\n#include \"src/abstraction.hpp\"\n#include \"src/bsolver.hpp\"\n#include \"src/hdf5io.h\"\n\n\nconst double a = 1./3.5;\nconst double B = 2.0;\nconst double H = 0.18;\nconst double W = 0.25;\nconst double lc = 8.0;\nconst double cx = 1.0/lc;\nconst double cy = 1.0/(4*lc*B*B);\nconst double aH = a+H;\nconst double H2 = H/(2.0*W*W*W);\nconst double W2 = 3*W*W;\n\n/* user defined dynamics */\nstruct mgode2 {\n\n    static const int n = 2;  // system dimension\n    static const int nu = 2;  // control dimension\n    \n    /* template constructor\n     * @param[out] dx\n     * @param[in] x\n     * @param u\n     */\n    template<typename S>\n    mgode2(S *dx, const S *x, rocs::Rn u) {\n\tdx[0] = cx * (aH+H2*(x[0]-W)*(W2-(x[0]-W)*(x[0]-W)) - x[1]) + u[0];\n\tdx[1] = cy * (x[0] - u[1]*sqrt(x[1]));\n    }\n};\n\n\nint main(int argc, char *argv[])\n{\n    /**\n     * Input arguments: \n     * engine2dAbstII dbafile \n     */\n    if (argc != 2) {\n\tstd::cout << \"Improper number of arguments.\\n\";\n\tstd::exit(1);\n    }\n\n    \n    clock_t tb, te;\n    /* set the state space */\n    double xlb[]{0.44, 0.6};\n    double xub[]{0.54, 0.7};\n    \n    /* set the control values */\n    // double Lmu = 0.01;\n    double Lu = 0.05;\n    double ulb[]{-Lu, 0.5};\n    double uub[]{Lu, 0.8};\n    double mu[]{Lu/5, 0.01};\n\n    /* set the sampling time and disturbance */\n    double delta = 0.01;\n    /* parameters for computing the flow */\n    int kmax = 10;\n    double tol = 0.01;\n    double alpha = 0.5;\n    double beta = 2;\n    rocs::params controlparams(kmax, tol, alpha, beta);\n    \n    /* define the control system */\n    double t= 0.1;\n    rocs::CTCntlSys<mgode2> engine(\"Moore-Greitzer\", t, mgode2::n, mgode2::nu,\n\t\t\t\t  delta, &controlparams);\n    engine.init_workspace(xlb, xub);\n    engine.init_inputset(mu, ulb, uub);\n    engine.allocate_flows();\n\n\n    /**\n     * Abstraction \n     */\n    rocs::abstraction< rocs::CTCntlSys<mgode2> > abst(&engine);\n    const double eta[]{0.00018, 0.00018};\n    abst.init_state(eta, xlb, xub);\n    std::cout << \"The number of abstraction states: \" << abst._x._nv << '\\n';\n    double obs[][2]{{0.497, 0.503}, {0.650, 0.656}};\n    auto avoid = [&obs, abst, eta](size_t& id) {\n\t\t     std::vector<double> x(abst._x._dim);\n    \t\t     abst._x.id_to_val(x, id);\n    \t\t     double c1 = eta[0]/2.0; //+1e-10;\n    \t\t     double c2 = eta[1]/2.0; //+1e-10;\n\t\t     if ((obs[0][0]-c1) <= x[0] && x[0] <= (obs[0][1]+c1) &&\n\t\t\t (obs[1][0]-c2) <= x[1] && x[1] <= (obs[1][1]+c2))\n\t\t\t return -1;\n\t\t     return 0;\n\t\t };\n    abst.assign_labels(avoid);\n    abst.assign_label_outofdomain(0);\n    std::vector<size_t> obstacles;\n    for (size_t i = 0; i < abst._x._nv; ++i) {\n    \tif (abst._labels[i] < 0)\n    \t    obstacles.push_back(i);\n    }\n\n    std::string transfile = \"abstII_0.00018.h5\";\n    struct stat buffer;\n    float tabst;\n    if(stat(transfile.c_str(), &buffer) == 0) {\n\t/* Read from a file */\n\tstd::cout << \"Transitions have been computed. Reading transitions...\\n\";\n\trocs::h5FileHandler transRdr(transfile, H5F_ACC_RDONLY);\n\ttb = clock();\n\ttransRdr.read_transitions(abst._ts);\n\tte = clock();\n\ttabst = (float)(te - tb)/CLOCKS_PER_SEC;\n\tstd::cout << \"Time of reading abstraction: \" << tabst << '\\n';\n    } else {\n\tstd::cout << \"Transitions haven't been computed. Computing transitions...\\n\";\n\t/* Robustness margins */\n\tdouble e1[] = {0.0, 0.0};\n\tdouble e2[] = {0.0, 0.0};\n\ttb = clock();\n\tabst.assign_transitions(e1, e2);\n\tte = clock();\n\ttabst = (float)(te - tb)/CLOCKS_PER_SEC;\n\tstd::cout << \"Time of computing abstraction: \" << tabst << '\\n';\n\t/* Write abstraction to file */\n\trocs::h5FileHandler transWtr(transfile, H5F_ACC_TRUNC);\n\ttransWtr.write_transitions(abst._ts);\n    }\n    std::cout << \"# of transitions: \" << abst._ts._ntrans << '\\n';\n\n\n    /**\n     * Read DBA from spec*.txt file\n     */\n    std::cout << \"Reading the specification...\\n\";\n    rocs::UintSmall nAP = 0, nNodes = 0, q0 = 0;\n    std::vector<rocs::UintSmall> acc;\n    std::vector<std::vector<rocs::UintSmall>> arrayM;\n    std::string specfile = std::string(argv[1]);\n    if (!rocs::read_spec(specfile, nNodes, nAP, q0, arrayM, acc)) \n\tstd::exit(1);\n    \n\n    /* \n     * Assign labels to states: has to be consistent with the dba file.\n     */\n    double e = 0.003;\n    double goal[][2]{{0.4519-e, 0.4519+e}, {0.6513-e, 0.6513+e}};\n    \n    auto label_target = [&goal, &abst, &eta](size_t i) {\n\t\t\t    std::vector<double> x(abst._x._dim);\n\t\t\t    abst._x.id_to_val(x, i);\n\t\t\t    double c1= eta[0]/2.0; //+1e-10;\n\t\t\t    double c2= eta[1]/2.0; //+1e-10;\n\t\t\t    \n\t\t\t    return (goal[0][0] <= (x[0]-c1) && (x[0]+c1) <= goal[0][1] && \n\t\t\t\t    goal[1][0] <= (x[1]-c2) && (x[1]+c2) <= goal[1][1]) ?\n\t\t\t\t1: abst._labels[i];\n\t\t\t};\n    abst.assign_labels(label_target);\n    std::cout << \"Specification assignment is done.\\n\";\n    std::vector<size_t> targetIDs;\n    std::vector<rocs::Rn> targetPts;   //initial invariant set\n    rocs::Rn x(abst._x._dim);\n    for(size_t i = 0; i < abst._labels.size(); ++i) {\n    \tif(abst._labels[i] > 0) {\n    \t    targetIDs.push_back(i);\n    \t    abst._x.id_to_val(x, i);\n    \t    targetPts.push_back(x);\n    \t}\n    }\n\n\n    /**\n     * Solve a Buchi game on the product of NTS and DBA.\n     */\n    std::cout << \"Start solving a Buchi game on the product of the abstraction and DBA...\\n\";\n    rocs::BSolver solver; // memories will be allocated for psolver\n    solver.construct_dba((int)nAP, (int)nNodes, (int)q0, acc, arrayM);\n    tb = clock();\n    solver.load_abstraction(abst);\n    solver.generate_product(abst);\n    solver.solve_buchigame_on_product();\n    te = clock();\n    float tsyn = (float)(te - tb)/CLOCKS_PER_SEC;\n    std::cout << \"Time of synthesizing controller: \" << tsyn << '\\n';\n\n    /**\n     * Display and save memoryless controllers.\n     */\n    std::cout << \"Writing the controller...\\n\";\n    // std::string datafile = \"controller_abstII.txt\";\n    // solver.write_controller_to_txt(const_cast<char*>(datafile.c_str()));\n    std::string datafile = \"controller_abstII_0.00018.h5\";\n    rocs::h5FileHandler ctlrWtr(datafile, H5F_ACC_TRUNC);\n    ctlrWtr.write_problem_setting< rocs::CTCntlSys<mgode2> >(engine);\n    ctlrWtr.write_2d_array<double>(targetPts, \"G\");\n    ctlrWtr.write_array<double>(eta, mgode2::n, \"eta\");\n    ctlrWtr.write_2d_array<double>(abst._x._data, \"xgrid\");\n    ctlrWtr.write_discrete_controller(&(solver._sol));\n    std::cout << \"Controller writing is done.\\n\";\n\n    std::cout << \"Total time of used (abstraction+synthesis): \" << tabst+tsyn << '\\n';\n    \n\n    engine.release_flows();\n    return 0;\n}\n", "meta": {"hexsha": "104f818b937b710d32faabe913192376fc69b9b6", "size": 6879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Moore-Greitzer/engine2dAbstII.cpp", "max_stars_repo_name": "yinanl/rocs", "max_stars_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Moore-Greitzer/engine2dAbstII.cpp", "max_issues_repo_name": "yinanl/rocs", "max_issues_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Moore-Greitzer/engine2dAbstII.cpp", "max_forks_repo_name": "yinanl/rocs", "max_forks_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.03930131, "max_line_length": 93, "alphanum_fraction": 0.5935455735, "num_tokens": 2284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.43762273717500116}}
{"text": "/*\n * This file is modified from the sources of Gazebo 7.0\n *\n * Copyright (C) 2012-2016 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*/\n#ifndef _GAZEBO_MATH_FUNCTIONS_HH_\n#define _GAZEBO_MATH_FUNCTIONS_HH_\n\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <string>\n#include <iostream>\n#include <vector>\n\n/// \\brief Double maximum value\n#define GZ_DBL_MAX std::numeric_limits<double>::max()\n\n/// \\brief Double min value\n#define GZ_DBL_MIN std::numeric_limits<double>::min()\n\n/// \\brief Double positive infinite value\n#define GZ_DBL_INF std::numeric_limits<double>::infinity()\n\n/// \\brief Float maximum value\n#define GZ_FLT_MAX std::numeric_limits<float>::max()\n\n/// \\brief Float minimum value\n#define GZ_FLT_MIN std::numeric_limits<float>::min()\n\n/// \\brief 32bit unsigned integer maximum value\n#define GZ_UINT32_MAX std::numeric_limits<uint32_t>::max()\n\n/// \\brief 32bit unsigned integer minimum value\n#define GZ_UINT32_MIN std::numeric_limits<uint32_t>::min()\n\n/// \\brief 32bit integer maximum value\n#define GZ_INT32_MAX std::numeric_limits<int32_t>::max()\n\n/// \\brief 32bit integer minimum value\n#define GZ_INT32_MIN std::numeric_limits<int32_t>::min()\n\n\nnamespace gazebo\n{\n  namespace math\n  {\n    /// \\addtogroup gazebo_math\n    /// \\brief A set of classes that encapsulate math related properties and\n    ///        functions.\n    /// \\{\n\n    /// \\brief Returns the representation of a quiet not a number (NAN)\n    static const double NAN_D = std::numeric_limits<double>::quiet_NaN();\n\n    /// \\brief Returns the representation of a quiet not a number (NAN)\n    static const int NAN_I = std::numeric_limits<int>::quiet_NaN();\n\n    /// \\brief Simple clamping function\n    /// \\param[in] _v value\n    /// \\param[in] _min minimum\n    /// \\param[in] _max maximum\n    template<typename T>\n    inline T clamp(T _v, T _min, T _max)\n    {\n      return std::max(std::min(_v, _max), _min);\n    }\n\n    /// \\brief check if a float is NaN\n    /// \\param[in] _v the value\n    /// \\return true if _v is not a number, false otherwise\n    inline bool isnan(float _v)\n    {\n      return (boost::math::isnan)(_v);\n    }\n\n    /// \\brief check if a double is NaN\n    /// \\param[in] _v the value\n    /// \\return true if _v is not a number, false otherwise\n    inline bool isnan(double _v)\n    {\n      return (boost::math::isnan)(_v);\n    }\n\n    /// \\brief Fix a nan value.\n    /// \\param[in] _v Value to correct.\n    /// \\return 0 if _v is NaN, _v otherwise.\n    inline float fixnan(float _v)\n    {\n      return isnan(_v) || std::isinf(_v) ? 0.0f : _v;\n    }\n\n    /// \\brief Fix a nan value.\n    /// \\param[in] _v Value to correct.\n    /// \\return 0 if _v is NaN, _v otherwise.\n    inline double fixnan(double _v)\n    {\n      return isnan(_v) || std::isinf(_v) ? 0.0 : _v;\n    }\n\n    /// \\brief get mean of vector of values\n    /// \\param[in] _values the vector of values\n    /// \\return the mean\n    template<typename T>\n    inline T mean(const std::vector<T> &_values)\n    {\n      T sum = 0;\n      for (unsigned int i = 0; i < _values.size(); ++i)\n        sum += _values[i];\n      return sum / _values.size();\n    }\n\n    /// \\brief get variance of vector of values\n    /// \\param[in] _values the vector of values\n    /// \\return the squared deviation\n    template<typename T>\n    inline T variance(const std::vector<T> &_values)\n    {\n      T avg = mean<T>(_values);\n\n      T sum = 0;\n      for (unsigned int i = 0; i < _values.size(); ++i)\n        sum += (_values[i] - avg) * (_values[i] - avg);\n      return sum / _values.size();\n    }\n\n    /// \\brief get the maximum value of vector of values\n    /// \\param[in] _values the vector of values\n    /// \\return maximum\n    template<typename T>\n    inline T max(const std::vector<T> &_values)\n    {\n      T max = std::numeric_limits<T>::min();\n      for (unsigned int i = 0; i < _values.size(); ++i)\n        if (_values[i] > max)\n          max = _values[i];\n      return max;\n    }\n\n    /// \\brief get the minimum value of vector of values\n    /// \\param[in] _values the vector of values\n    /// \\return minimum\n    template<typename T>\n    inline T min(const std::vector<T> &_values)\n    {\n      T min = std::numeric_limits<T>::max();\n      for (unsigned int i = 0; i < _values.size(); ++i)\n        if (_values[i] < min)\n          min = _values[i];\n      return min;\n    }\n\n    /// \\brief check if two values are equal, within a tolerance\n    /// \\param[in] _a the first value\n    /// \\param[in] _b the second value\n    /// \\param[in] _epsilon the tolerance\n    template<typename T>\n    inline bool equal(const T &_a, const T &_b,\n                      const T &_epsilon = 1e-6)\n    {\n      return std::fabs(_a - _b) <= _epsilon;\n    }\n\n    /// \\brief get value at a specified precision\n    /// \\param[in] _a the number\n    /// \\param[in] _precision the precision\n    /// \\return the value for the specified precision\n    template<typename T>\n    inline T precision(const T &_a, const unsigned int &_precision)\n    {\n      if (!std::isinf(_a))\n      {\n        return boost::math::round(\n          _a * pow(10, _precision)) / pow(10, _precision);\n      }\n      else\n      {\n        return _a;\n      }\n    }\n\n    /// \\brief is this a power of 2?\n    /// \\param[in] _x the number\n    /// \\return true if _x is a power of 2, false otherwise\n    inline bool isPowerOfTwo(unsigned int _x)\n    {\n      return ((_x != 0) && ((_x & (~_x + 1)) == _x));\n    }\n\n    /// \\brief Get the smallest power of two that is greater or equal to a given\n    /// value\n    /// \\param[in] _x the number\n    /// \\return the same value if _x is already a power of two. Otherwise,\n    /// it returns the smallest power of two that is greater than _x\n    inline unsigned int roundUpPowerOfTwo(unsigned int _x)\n    {\n      if (_x == 0)\n        return 1;\n\n      if (isPowerOfTwo(_x))\n        return _x;\n\n      while (_x & (_x - 1))\n        _x = _x & (_x - 1);\n\n      _x = _x << 1;\n\n      return _x;\n    }\n\n    /// \\brief parse string into an integer\n    /// \\param[in] _input the string\n    /// \\return an integer, 0 or 0 and a message in the error stream\n    inline int parseInt(const std::string& _input)\n    {\n      const char *p = _input.c_str();\n      if (!*p || *p == '?')\n        return NAN_I;\n\n      int s = 1;\n      while (*p == ' ')\n        p++;\n\n      if (*p == '-')\n      {\n        s = -1;\n        p++;\n      }\n\n      double acc = 0;\n      while (*p >= '0' && *p <= '9')\n        acc = acc * 10 + *p++ - '0';\n\n      if (*p)\n      {\n        std::cerr << \"Invalid int numeric format[\" << _input << \"]\\n\";\n        return 0.0;\n      }\n\n      return s * acc;\n    }\n\n    /// \\brief parse string into float\n    /// \\param _input the string\n    /// \\return a floating point number (can be NaN) or 0 with a message in the\n    /// error stream\n    inline double parseFloat(const std::string& _input)\n    {\n      const char *p = _input.c_str();\n      if (!*p || *p == '?')\n        return NAN_D;\n      int s = 1;\n      while (*p == ' ')\n        p++;\n\n      if (*p == '-')\n      {\n        s = -1;\n        p++;\n      }\n\n      double acc = 0;\n      while (*p >= '0' && *p <= '9')\n        acc = acc * 10 + *p++ - '0';\n\n      if (*p == '.')\n      {\n        double k = 0.1;\n        p++;\n        while (*p >= '0' && *p <= '9')\n        {\n          acc += (*p++ - '0') * k;\n          k *= 0.1;\n        }\n      }\n      if (*p == 'e')\n      {\n        int es = 1;\n        int f = 0;\n        p++;\n        if (*p == '-')\n        {\n          es = -1;\n          p++;\n        }\n        else if (*p == '+')\n        {\n          es = 1;\n          p++;\n        }\n        while (*p >= '0' && *p <= '9')\n          f = f * 10 + *p++ - '0';\n\n        acc *= pow(10, f*es);\n      }\n\n      if (*p)\n      {\n        std::cerr << \"Invalid double numeric format[\" << _input << \"]\\n\";\n        return 0.0;\n      }\n      return s * acc;\n    }\n    /// \\}\n  }\n}\n#endif\n", "meta": {"hexsha": "4ade0a4c327f04e585803ba3e88c563c531113b3", "size": 8504, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/auto_referee/src/Helpers.hh", "max_stars_repo_name": "SaligiaR/simatch", "max_stars_repo_head_hexsha": "a295a39500518ec220fa511ebfb2b50daab84b4e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 60.0, "max_stars_repo_stars_event_min_datetime": "2016-09-17T13:18:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-20T01:19:49.000Z", "max_issues_repo_path": "src/auto_referee/src/Helpers.hh", "max_issues_repo_name": "SaligiaR/simatch", "max_issues_repo_head_hexsha": "a295a39500518ec220fa511ebfb2b50daab84b4e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2016-09-09T14:40:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T08:10:44.000Z", "max_forks_repo_path": "src/auto_referee/src/Helpers.hh", "max_forks_repo_name": "SaligiaR/simatch", "max_forks_repo_head_hexsha": "a295a39500518ec220fa511ebfb2b50daab84b4e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2016-09-09T14:49:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T15:02:54.000Z", "avg_line_length": 26.3281733746, "max_line_length": 80, "alphanum_fraction": 0.5592662277, "num_tokens": 2358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4376227371750011}}
{"text": "#include <iostream>\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nvec addTwo_parallel(vec x, vec y){\n    vec z(x.n_elem);\n    int i;\n#pragma omp parallel for schedule(static) \\\nprivate(i) shared(x,y,z)\n    for(i=0; i < x.n_elem; i++)\n        z(i) = x(i) + 2 * y(i);\n    return z;\n}\n\nint main()\n{\n\n    vec a = ones<vec>(10);\n    vec b = ones<vec>(10);\n    vec c = addTwo_parallel(a, b);\n    c.print();\n    return 0;\n}\n", "meta": {"hexsha": "e76ff22e1d977fd04ecda429fe6765285f6efdfb", "size": 437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "yhwhu/DSA_CPP_Deng", "max_stars_repo_head_hexsha": "e47ac149241034341d53cb41343008efadaed08c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "yhwhu/DSA_CPP_Deng", "max_issues_repo_head_hexsha": "e47ac149241034341d53cb41343008efadaed08c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "yhwhu/DSA_CPP_Deng", "max_forks_repo_head_hexsha": "e47ac149241034341d53cb41343008efadaed08c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.8076923077, "max_line_length": 43, "alphanum_fraction": 0.5789473684, "num_tokens": 134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4375439874449355}}
{"text": "#include \"powerlawCommon.h\"\n//#include <boost/program_options.hpp>\n#include \"tkdCmdParser.h\"\n\n/**\n * @author: W.M. Otte (wim@invivonmr.uu.nl); Image Sciences Institute, UMC Utrecht, NL.\n * @date: 19-11-2009\n *\n * Estimate powerlaw scaling parameter from input distribution.\n *\n * ***************************************************************************\n * Method: \"Power-law distributions in empirical data\", Clauset et al, 2009\n * http://www.santafe.edu/~aaronc/powerlaws/\n * ***************************************************************************\n */\nclass PowerLawFit\n{\n\npublic:\n\n\ttypedef double ValueType;\n\ttypedef std::vector< ValueType > VectorType;\n\n\t/**\n\t * Power law fit.\n\t */\n\tvoid run( const std::string& inputFileName, bool nosmall, bool finite,\n\t\t\t\t\tdouble startXmin, double incrementXmin, double endXmin,\n\t\t\t\t\t\tbool bootstrap, unsigned int bootstrapIterations, bool verbose )\n\t{\n\t\t// [ 1 ] read input from text file ...\n\t\tVectorType values = getInput( inputFileName );\n\n\t\t// [ 2 ] bootstrap or single fit ...\n\t\tVectorType results;\n\n\t\tif ( bootstrap )\n\t\t{\n\t\t\tgraph::Powerlaw< ValueType >::BootstrapFit( values, results, nosmall, finite, startXmin, incrementXmin, endXmin, bootstrapIterations, verbose );\n\n\t\t\tif ( ! results.empty() )\n\t\t\t{\n\t\t\t\tstd::cout << \"Alpha,\" << results.at( 0 ) <<  std::endl;\n\t\t\t\tstd::cout << \"Xmin,\" << results.at( 1 ) << std::endl;\n\t\t\t\tstd::cout << \"Log-likelihood,\" << results.at( 2 ) << std::endl;\n\t\t\t\tstd::cout << \"Alpha_sd,\" << results.at( 3 ) <<  std::endl;\n\t\t\t\tstd::cout << \"Xmin_sd,\" << results.at( 4 ) << std::endl;\n\t\t\t\tstd::cout << \"Log-likelihood_sd,\" << results.at( 5 ) << std::endl;\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: maximum likelihood \"\n\t\t\t\t\t\"bootstrap estimation failed! -> check input ...\" << std::endl;\n\t\t\t}\n\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgraph::Powerlaw< ValueType >::SingleFit( values, results, nosmall, finite,\n\t\t\t\t\tstartXmin, incrementXmin, endXmin );\n\n\t\t\tif ( ! results.empty() )\n\t\t\t{\n\t\t\t\tstd::cout << \"Alpha,\" << results.at( 0 ) << std::endl;\n\t\t\t\tstd::cout << \"Xmin,\" << results.at( 1 ) << std::endl;\n\t\t\t\tstd::cout << \"Log-likelihood,\" << results.at( 2 ) << std::endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: maximum likelihood \"\n\t\t\t\t\t\"single estimation failed! -> check input ...\" << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\nprotected:\n\n\t/**\n\t * Return input from given text file as vector.\n\t */\n\tVectorType getInput( const std::string& input )\n\t{\n\t\tstd::ifstream inFile;\n\n\t\tinFile.open( input.c_str() );\n\t\tif ( !inFile )\n\t\t{\n\t\t\tstd::cout << \"*** ERROR ***: Unable to open: \" << input << \".\" << std::endl;\n\t\t\texit( EXIT_FAILURE );\n\t\t}\n\n\t\tdouble x;\n\t\tVectorType output;\n\n\t\twhile ( inFile >> x )\n\t\t{\n\t\t\toutput.push_back( x );\n\t\t}\n\t\tinFile.close();\n\n\t\t/**\n\t\t * Negative values will be converted to complex numbers in matlab,\n\t\t * but not with the stl ...\n\t\t *\n\t\t * No support is given (yet) for complex number mle.\n\t\t */\n\t\tif ( *( std::min_element( output.begin(), output.end() ) ) < 0 )\n\t\t{\n\t\t\tstd::cerr << \"*** ERROR ***: Negative input not supported!\" << std::endl;\n\t\t\texit (EXIT_FAILURE );\n\t\t}\n\n\t\treturn output;\n\t}\n};\n\n// ************************************************************************************\n\n\n/**\n * Option list.\n */\nstruct parameters\n{\n\tstd::string input;\n\tbool nosmall;\n\tbool finite;\n\tbool bootstrap;\n\tbool verbose;\n\tdouble startXmin;\n\tdouble incrementXmin;\n\tdouble endXmin;\n\tint bootstrapIterations;\n\n};\n\n/**\n * Fit powerlaw to list of numbers.\n */\nint main(int argc, char* argv[])\n{\n\ttkd::CmdParser p( argv[0], \"Fits a power-law distributional model to data.\" );\n\n\t\tparameters list;\n\n\t\tlist.nosmall = false;\n\t\tlist.finite = false;\n\t\tlist.bootstrap = false;\n\t\tlist.verbose = false;\n\t\tlist.startXmin = 1.5;\n\t\tlist.incrementXmin = 0.01;\n\t\tlist.endXmin = 3.5;\n\t\tlist.bootstrapIterations = 1000;\n\n\t\tp.AddArgument( list.input, \"input\" )\n\t\t\t\t->AddAlias( \"i\" )\n\t\t\t\t->SetDescription( \"Input file with distribution values in column format\" )\n\t\t\t\t->SetRequired( true );\n\n\t\tp.AddArgument( list.nosmall, \"nosmall\" )\n\t\t\t\t->SetDescription( \"Truncate the search over xmin values before the finite-size bias becomes significant (default: false)\" );\n\n\t\tp.AddArgument( list.finite, \"finite\" )\n\t\t\t\t->SetDescription( \"Use an experimental finite-size correction (default: false)\" );\n\n\t\tp.AddArgument( list.bootstrap, \"bootstrap\" )\n\t\t\t\t->SetDescription( \"Run non-parametric bootstrap instead of single estimation (default: false)\" );\n\n\t\tp.AddArgument( list.verbose, \"verbose\" )\n\t\t\t\t->SetDescription( \"Print boostrap status (default: false)\" );\n\n\t\tp.AddArgument( list.startXmin, \"start-x-min\" )\n\t\t\t\t->SetDescription( \"Start value for discrete xmin estimation (default: 1.5)\" );\n\n\t\tp.AddArgument( list.incrementXmin, \"increment-x-min\" )\n\t\t\t\t->SetDescription( \"Increment value for discrete xmin estimation (default: 0.01)\" );\n\n\t\tp.AddArgument( list.endXmin, \"end-x-min\" )\n\t\t\t\t->SetDescription( \"End value for discrete xmin estimation (default: 3.5)\" );\n\n\t\tp.AddArgument( list.bootstrapIterations, \"iterations\" )\n\t\t\t\t->SetDescription( \"Bootstrap iterations (default: 1000)\" );\n\n\n\t\tif ( !p.Parse( argc, argv ) )\n\t\t{\n\t\t\tp.PrintUsage( std::cout );\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\n        // run application ...\n        PowerLawFit powerlawFit;\n\n    \tpowerlawFit.run( list.input, list.nosmall, list.finite,\n\t\t\t\t\t\t\tlist.startXmin, list.incrementXmin, list.endXmin,\n\t\t\t\t\t\t\t\t\t\t\tlist.bootstrap, list.bootstrapIterations, list.verbose );\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "7745863db694b35fc307a77b9f03593200637e09", "size": 5415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graphs/powerlawFit.cpp", "max_stars_repo_name": "wmotte/toolkid", "max_stars_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/graphs/powerlawFit.cpp", "max_issues_repo_name": "wmotte/toolkid", "max_issues_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graphs/powerlawFit.cpp", "max_forks_repo_name": "wmotte/toolkid", "max_forks_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9402985075, "max_line_length": 147, "alphanum_fraction": 0.6103416436, "num_tokens": 1448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863698, "lm_q2_score": 0.6791787056691698, "lm_q1q2_score": 0.4375439739829957}}
{"text": "#ifndef HOPS_AUTOCORRELATION_HPP\n#define HOPS_AUTOCORRELATION_HPP\n\n#include <Eigen/Core>\n#include <unsupported/Eigen/FFT>\n#include <memory>\n        \nnamespace hops {\n    inline size_t nextGoodSizeFFT(size_t N) {\n        if (N <= 2) {\n            return 2;\n        }\n        while (true) {\n            size_t m = N;\n            while ((m % 2) == 0) {\n            m /= 2;\n            }\n            while ((m % 3) == 0) {\n            m /= 3;\n            }\n            while ((m % 5) == 0) {\n            m /= 5;\n            }\n            if (m <= 1) {\n            return N;\n            }\n            N++;\n        }\n    }\n       \n    template <typename StateType>\n    void computeAutocorrelations (const std::vector<StateType>& draws, \n                                  Eigen::VectorXd& autocorrelations, \n                                  unsigned long dimension) {\n        computeAutocorrelations(&draws, autocorrelations, dimension);\n    }\n    \n    template <typename StateType>\n    void computeAutocorrelations (const std::vector<StateType>* draws, \n                                  Eigen::VectorXd& autocorrelations, \n                                  unsigned long dimension) {\n        size_t N = draws->size();\n        Eigen::VectorXd X = Eigen::VectorXd::Zero(N);\n        for (size_t n = 0; n < N; ++n) {\n            X(n) = (*draws)[n](dimension);\n        }\n\n        Eigen::FFT<typename StateType::Scalar> fft;\n        size_t M = nextGoodSizeFFT(N);\n        size_t Mt2 = 2 * M;\n\n        // center and pad X\n        Eigen::VectorXd centeredX(Mt2);\n        centeredX.setZero();\n        centeredX.head(N) = X.array() - X.mean();\n\n        // See https://en.wikipedia.org/wiki/Autocorrelation#Efficient_computation for a quick\n        // explanation on what follows\n        Eigen::VectorXcd frequency(Mt2);\n        fft.fwd(frequency, centeredX);\n        \n        frequency = frequency.cwiseAbs2();\n\n        Eigen::VectorXcd autocorrelationsTmp(Mt2);\n        fft.inv(autocorrelationsTmp, frequency);\n\n        // use \"biased\" estimate as recommended by Geyer (1992)\n        autocorrelations = autocorrelationsTmp.head(N).real().array() / (N * N * 2);\n        autocorrelations /= autocorrelations(0);\n    }\n}\n\n#endif // HOPS_AUTOCORRELATION_HPP\n", "meta": {"hexsha": "4229f7032e22c7280fd68d7f0661d490ea5826ae", "size": 2241, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hops/Statistics/Autocorrelation.hpp", "max_stars_repo_name": "modsim/hops", "max_stars_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T05:13:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T02:08:40.000Z", "max_issues_repo_path": "include/hops/Statistics/Autocorrelation.hpp", "max_issues_repo_name": "modsim/hops", "max_issues_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-20T23:16:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-20T23:16:34.000Z", "max_forks_repo_path": "include/hops/Statistics/Autocorrelation.hpp", "max_forks_repo_name": "modsim/hops", "max_forks_repo_head_hexsha": "4285dd75a07dd844295440a0756b3ba25f5819ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2837837838, "max_line_length": 94, "alphanum_fraction": 0.5211958947, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4373973342840862}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_FLOOR_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FLOOR_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing floor capabilities\n\n    Computes the floor of its parameter.\n\n    @par semantic:\n    For any given value @c x of type @c T:\n\n    @code\n    T r = floor(x);\n    @endcode\n\n    is the greatest integral value of type @c T less or equal to @c x.\n\n    @see  ceil, round, nearbyint, trunc, ifloor\n\n  **/\n  Value floor(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/floor.hpp>\n#include <boost/simd/function/simd/floor.hpp>\n\n#endif\n", "meta": {"hexsha": "998d218da828e392bcbe7961c08508039ed682dd", "size": 1061, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/floor.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/function/floor.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/floor.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 23.5777777778, "max_line_length": 100, "alphanum_fraction": 0.5768143261, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4373973342840862}}
{"text": "/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */\n\n#include <boost/tokenizer.hpp>\n#include <spotfinder/core_toolbox/distl.h>\n#include <scitbx/vec3.h>\n\n\nnamespace af = scitbx::af;\nnamespace di = spotfinder::distltbx;\n//this function was developed but never used; deprecate soon\nDistl::spot::spot(af::flex_int::const_iterator intptr) :\n  peakintensity(0.0),\n  nmaxima(0),\n  p_gotaxes(false)\n{\n  peak = Distl::point(*intptr,*(intptr+1));\n  intptr+=2;\n  int bodylen = *intptr; intptr++;\n  bodypixels.reserve(bodylen);\n  for (int i=0; i<bodylen; ++i, intptr+=2){\n    bodypixels.push_back(Distl::point(*intptr,*(intptr+1)));}\n}\n\nvoid\ndi::w_spot::p_getaxes() {\n//DEPRECATE SOON---DEPRECATE SOON\n  if (p_gotaxes) return;\n  if (bodypixels.size() < 2) {\n    p_majoraxis = 1.0;\n    p_minoraxis = 1.0;\n    p_gotaxes = true;\n    return;\n  }\n  // iteration to find average position\n  af::tiny<double, 2> average_pixel_position = af::tiny<double, 2>(0.,0.);\n  for (int i = 0; i < bodypixels.size() ; ++i) {\n    average_pixel_position[0]+=bodypixels[i].x;\n    average_pixel_position[1]+=bodypixels[i].y;\n  }\n  average_pixel_position[0]/=bodypixels.size();\n  average_pixel_position[1]/=bodypixels.size();\n\n  //iteration to find major axis\n  std::vector<double> sq_distance;\n  for (int i = 0; i < bodypixels.size() ; ++i) {\n    sq_distance.push_back(\n     (bodypixels[i].x - average_pixel_position[0]) *\n     (bodypixels[i].x - average_pixel_position[0]) +\n     (bodypixels[i].y - average_pixel_position[1]) *\n     (bodypixels[i].y - average_pixel_position[1]));\n  }\n  std::vector<double>::const_iterator ptrmajor =\n    std::max_element(sq_distance.begin(),sq_distance.end());\n  double c_majoraxis = 2.0*std::sqrt(*ptrmajor);\n  size_t posmajor = ptrmajor - sq_distance.begin();\n  //printf(\"posmajor %7d\\n\",posmajor);\n\n  //double check to verify the major axis vector:\n  double dx = bodypixels[posmajor].x - average_pixel_position[0];\n  double dy = bodypixels[posmajor].y - average_pixel_position[1];\n  //double d_majoraxis = 2.0*std::sqrt( dx*dx + dy*dy );\n  //printf(\"C_major %7.1f   D_major %7.1f\\n\",c_majoraxis,d_majoraxis);\n\n  //iteration to find minor axis\n  std::vector<double> abs_cross_product;\n  for (int i = 0; i < bodypixels.size() ; ++i) {\n    abs_cross_product.push_back( std::fabs(\n       dx * (bodypixels[i].y - average_pixel_position[1]) -\n       (bodypixels[i].x - average_pixel_position[0]) * dy\n    ) );\n  }\n  std::vector<double>::const_iterator ptrminor =\n    std::max_element(abs_cross_product.begin(),abs_cross_product.end());\n  double c_minoraxis = 4.0*(*ptrminor)/c_majoraxis;\n  //printf(\"C_major %7.1f   C_minor %7.1f\\n\",c_majoraxis,c_minoraxis);\n\n  if (c_majoraxis >= c_minoraxis) {\n    p_majoraxis = c_majoraxis;\n    p_minoraxis = c_minoraxis;\n  } else {\n    p_majoraxis = c_minoraxis;\n    p_minoraxis = c_majoraxis;\n  }\n\n  p_gotaxes=true;\n}\n\n// major and minor axes given in units of pixels\ndouble\ndi::w_spot::get_majoraxis() {\n  p_getaxes();\n  return p_majoraxis;\n}\n\ndouble\ndi::w_spot::get_minoraxis() {\n  p_getaxes();\n  return p_minoraxis;\n}\n\nvoid di::w_spot::setstate(Distl::point const& pk){\n  nmaxima=0;\n  p_gotaxes=false;\n  peak=pk;\n}\n\n\n/*\n * Does not take any charge sharing into account.  beam_center_x and\n * beam_center_y must be given in pixel units.\n */\nscitbx::vec2<double>\ndi::w_spot::get_radial_and_azimuthal_size(\n  double beam_center_x, double beam_center_y)\n{\n  if (bodypixels.size() == 0)\n    return (scitbx::vec2<double>(0, 0));\n\n  /*\n   * Calculate unit-length radial and azimuthal (tangential) direction\n   * vectors, r and a, respectively.  The azimuthal direction vector\n   * is the radial vector rotated by 90 degrees counter-clockwise.\n   */\n  const scitbx::vec2<double> center(model_center());\n  scitbx::vec2<double> r(center[0] - beam_center_x,\n                         center[1] - beam_center_y);\n  double h(r.length());\n  if (h <= 0)\n    return (scitbx::vec2<double>(0, 0));\n  r /= h;\n  scitbx::vec2<double> a(-r[1], +r[0]);\n\n  /*\n   * Determine the extent of the spot along the radial and azimuthal\n   * directions from its center.\n   */\n  double a_max(-std::numeric_limits<double>::infinity());\n  double a_min(+std::numeric_limits<double>::infinity());\n  double r_max(-std::numeric_limits<double>::infinity());\n  double r_min(+std::numeric_limits<double>::infinity());\n  for (point_list_t::const_iterator q = bodypixels.begin();\n       q != bodypixels.end();\n       q++) {\n    const scitbx::vec2<double> p(q->x - center[0], q->y - center[1]);\n    const double pa(p * a);\n    const double pr(p * r);\n\n    if (pa > a_max)\n      a_max = pa;\n    if (pa < a_min)\n      a_min = pa;\n    if (pr > r_max)\n      r_max = pr;\n    if (pr < r_min)\n      r_min = pr;\n  }\n\n  return (scitbx::vec2<double>(r_max - r_min, a_max - a_min));\n}\n\n\n/*\nCommentary on DISTL, relevant to the use of DISTL for virus images.\n\n1) the function pxlclassify considers background boxes in sequence across\n   the detector face, but then when it comes to the final edge, it\n   calculates the final box boundaries differently.  This makes for clumsy\n   code, in particular the pxlclassify_scanbox() is called in 4 places.\n   Duplicated code, harder to maintain.  Better to change the function so\n   it establishes a single loop with an adjusted-size box so it only\n   needs to call scanbox once.\n\n2) consecutively scanned boxes overlap in 2 pixels.  This was probably\n   intentional to avoid edge-related discontinuties; but it also has an\n   unwanted consequence.  The pixelintensity[x][y] value is both used and\n   modified by pxlclassify_scanbox().  Therefore, for the two pixels that\n   overlap with the previous box, we are using\n   pixelintensity[x][y] values modified in this cycle, while all other pixels\n   have values from the last cycle.  It would be cleaner to implement boxes\n   without overlaps.\n\n3) on the same topic, it would help avoid discontinuties to determine a\n   background plane using International Tables, volume F, p. 213.\n\n4) the as-published gamma-I values don't really make sense:\n   a) in cycle 1, all initial pixelintensity[x][y] values are supposed to\n      be zero (but see 2 above) so it doesn't mean anything to have a\n      bgupperint for this cycle.\n   b) in cycle 2, we remove some box pixels from the background calculation.\n      Then in cycle 3, the published procedure increases the bgupperint\n      cutoff and recalculates the mask, having the effect of adding some\n      pixels back to the background.  But this seems wrong; once a pixel\n      is removed from background (because it may have signal in it) it\n      probably shouldn't be added back.  So the bgupperint cutoff should\n      remain constant across cycles.\n\n5) regarding #3, for the HK97 image (with many spots) we are spending an\n   enormous amount of time increasing the background-box size and retesting\n   it to attain 2/3 of spots in background.  It is possible that by\n   applying the background plane correction, we will attain the 2/3 threshhold\n   much sooner.  No--just a modest improvement when the plane correction is\n   applied to the pixelvalue[x][y].  Second try: the plane correction must\n   also be applied when calculating the boxstd(); otherwise the estimate\n   of standard deviation will be generally too high.  No:  no improvement in\n   the occurrence of background-box increases (even though the sd is lower).\n   There are dramatically more spots chosen around the water ring.\n\n   Actions:\n   -add a DetectorImageBase.debug_write() command to the iotbx.\n   -add a w_Distl.mod_data() function to get a custom-written modified dataarray\n\n6) Conclusions:\n   - the get_underload() function is at fault; it is choosing a lower cutoff\n   of 4035, which is much too high for reasonable interpretation of the\n   virus diffraction.  Most true background is masked out.\n   Change the code so it does a sanity check, and never masks out more than\n   10% of the pixels as underloads (and thus ~90% of pixels are potential\n   background pixels).\n\n7) tackle some performance issues.  the function spotlist_to_flexint() takes\n   as much CPU as the libdistl calls.  Solution: alleviate by coding in C++.\n\n8) In tnear, there are numerous boost.python function calls for each spot,\n   allowing for spot filtering.  This becomes prohibitive for large unit\n   cells.  Solution: recode spot filtering tests in C++ code.\n   Also: implement the SpotManager to give a more general way of subsetting\n   the spot list.\n\n   Tuesday goals:\n     tweak parameters for this image--bg cutoff to 1.5, d1 to 2.5\n       & see where I am.\n     still don't understand why the spots bleed into each other when bg\n       cutoff is at 1.5.  I thought the criteria for growing spots had to\n       do with d1, not bg2.\n*/\n\ndi::w_Distl::w_Distl(std::string optionstring, bool report_overloads){\n/*\n\"       -s2     Smallest acceptible spot area. Spots with area smaller than this value are ignored.\\n\\n\"\n\"               Recommended values: [3,5]\\n\\n\"\n\"       -s3     Spot base area.\\n\\n\"\n\"               Summary of spot shape, strength, etc. are based on spots no smaller than this size.\\n\\n\"\n\"       -s7     Spot area upper bound factor. If area exceeds\\n\"\n\"                   median + (95th prctile - 5th prctile) * factor,\\n\"\n\"               the spot is eliminated.\\n\\n\"\n\"               Recommended value: [2, 5]\\n\\n\"\n\"       -s8     Spot peak intensity upper bound factor. If peak intensity exceeds \\n\"\n\"                   median + (95th prctile - 5th prctile) * factor,\\n\"\n\"               the spot is eliminated.\\n\\n\"\n\"               Recommended value: [2, 10]\\n\\n\"\n\"   Ice-Ring Detection Parameters:\\n\\n\"\n\"       -i3     Intensity percentile as a measure of ice-ring strength.\\n\\n\"\n\"                               Recommended value: [0.1, 0.3]\\n\\n\"\n        -d1     Diffraction lower intensity; a lower bound for finding maxima, default 3.5\n    More parameters added Feb. 2006 for virus work\n        -bx0,1,2 Scanboxsize integer values for cycles 1,2,and 3.\n        -bg0,1,2 Bgupperint cutoff values for cycles 1,2,and 3.\n*/\n    finder.spotbasesize = 10; // distl initializes it as 16, but the LABELIT default is 10.\n    finder.bgupperint[0] = 1.5; //See note 4a above; value shouldn't be used\n    finder.bgupperint[1] = 1.5; //See note 4b above\n    finder.bgupperint[2] = 1.5; //See note 4b above\n    if (report_overloads) {finder.report_overloads = true;}\n    typedef boost::tokenizer<boost::char_separator<char> > tokenizer;\n    boost::char_separator<char> sep(\" \");\n    tokenizer tok(optionstring,sep);\n    for (tokenizer::iterator tok_iter = tok.begin();\n         tok_iter!=tok.end(); ++tok_iter){\n      if        (*tok_iter == \"-s2\") {\n        finder.spotarealowcut = atoi((*(++tok_iter)).c_str());\n      } else if (*tok_iter == \"-s3\") {\n        finder.spotbasesize = atoi((*(++tok_iter)).c_str());\n      } else if (*tok_iter == \"-s7\") {\n        finder.spotareamaxfactor = atof((*(++tok_iter)).c_str());\n      } else if (*tok_iter == \"-s8\") {\n        finder.spotpeakintmaxfactor = atof((*(++tok_iter)).c_str());\n      } else if (*tok_iter == \"-i3\") {\n        finder.icering_strengthprctile = atof((*(++tok_iter)).c_str());\n      } else if (*tok_iter == \"-d1\") {\n        finder.difflowerint = atof((*(++tok_iter)).c_str());\n      } else if (*tok_iter == \"-bx0\") {\n        finder.scanboxsize[0] = atoi((*(++tok_iter)).c_str());\n      } else if (*tok_iter == \"-bx1\") {\n        finder.scanboxsize[1] = atoi((*(++tok_iter)).c_str());\n      } else if (*tok_iter == \"-bx2\") {\n        finder.scanboxsize[2] = atoi((*(++tok_iter)).c_str());\n      } else if (*tok_iter == \"-bg0\") {\n        finder.bgupperint[0] = atof((*(++tok_iter)).c_str());\n      } else if (*tok_iter == \"-bg1\") {\n        finder.bgupperint[1] = atof((*(++tok_iter)).c_str());\n      } else if (*tok_iter == \"-bg2\") {\n        finder.bgupperint[2] = atof((*(++tok_iter)).c_str());\n      } else if (*tok_iter == \"-ro\") {\n        set_resolution_outer( atof((*(++tok_iter)).c_str()) );\n      }\n    }\n}\n\nvoid\ndi::w_Distl::set_resolution_outer(const double& newvalue)\n{\n  // only meaningful if the resolution value is a positive number.\n  SCITBX_ASSERT(newvalue>0.0);\n  finder.resolution_outer = newvalue;\n  //SCITBX_EXAMINE(finder.resolution_outer);\n}\n\nvoid\ndi::w_Distl::setspotimg(const double& pixel_size,\n                        const double& distance,\n                        const double& wavelength,\n                        const double& beamx,\n                        const double& beamy,\n                        af::flex_int const& intdata,\n                        const int& peripheral_margin,\n                        const double& saturation )\n{\n  finder.overloadvalue = saturation;\n  //Take default angle settings because we don't use them anyway.\n  finder.set_imageheader(pixel_size, distance, wavelength, 0., 0.,\n                         beamx, beamy);\n\n  int ncols = intdata.accessor().all()[0];\n  int nrows = intdata.accessor().all()[1];\n\n  finder.imgmargin = peripheral_margin;\n  finder.set_imagedata(intdata.begin(),ncols,nrows);\n}\n\nvoid\ndi::w_Distl::set_tiling(const string& vendortype)\n{\n  if (vendortype==\"Pilatus-6M\") {\n    finder.tiling = Distl::ptr_tiling(new Distl::scanbox_tiling_pilatus6M(\n      finder.firstx, finder.lastx, finder.firsty, finder.lasty));\n  } else if (vendortype==\"Pilatus-2M\") {\n    finder.tiling = Distl::ptr_tiling(new Distl::scanbox_tiling_pilatus2M(\n      finder.firstx, finder.lastx, finder.firsty, finder.lasty));\n  } else if (vendortype==\"Pilatus-300K\") {\n    finder.tiling = Distl::ptr_tiling(new Distl::scanbox_tiling_pilatus300K(\n      finder.firstx, finder.lastx, finder.firsty, finder.lasty));\n  } else if (vendortype.substr(0,5)==\"Eiger\") {\n    finder.tiling = Distl::ptr_tiling(new Distl::scanbox_tiling_eiger(\n      finder.firstx, finder.lastx, finder.firsty, finder.lasty,\n      finder.pixelvalue.nx, finder.pixelvalue.ny));\n  } else {\n    finder.tiling = Distl::ptr_tiling(new Distl::scanbox_tiling(\n      finder.firstx, finder.lastx, finder.firsty, finder.lasty));\n  }\n}\n\nvoid\ndi::w_Distl::set_tiling(af::flex_int const& explicit_tiling,int const& peripheral_margin)\n{\n  finder.tiling = Distl::ptr_tiling(new Distl::scanbox_tiling_explicit(\n      explicit_tiling, peripheral_margin));\n}\n\naf::flex_double\ndi::w_Distl::Z_data()\n{\n  int nrows=finder.pixelvalue.ny;\n  af::flex_double z(af::flex_grid<>(finder.pixelvalue.nx,nrows));\n\n  double* begin = z.begin();\n\n  for (int x=0; x<finder.pixelvalue.nx; x++) {\n    for (int y=0; y<nrows; y++){\n        //capture DISTL's Z-function;\n        *begin++ = finder.pixelintensity[x][y];\n    }\n  }\n  return z;\n}\n\naf::flex_int\ndi::w_Distl::mod_data()\n{\n  int nrows=finder.pixelvalue.ny;\n  af::flex_int z(af::flex_grid<>(finder.pixelvalue.nx,nrows));\n\n  int* begin = z.begin();\n\n  for (int x=0; x<finder.pixelvalue.nx; x++) {\n    for (int y=0; y<nrows; y++){\n        //example mod_data function; pixel value conditional on some property\n        if (finder.pixelintensity[x][y]<1.5 &&\n        finder.pixelvalue[x][y]>finder.underloadvalue &&\n        finder.pixelvalue[x][y]<finder.overloadvalue\n        ){\n            *begin = 10;\n        }else{\n            *begin = finder.pixelvalue[x][y];\n        }\n        begin++;\n    }\n  }\n  return z;\n}\n\nvoid\ndi::w_Distl::finish_analysis(){\n\n  // Now done as python calls to individual methods-->finder.process();\n\n  //get the spots out of std::list and in to af::shared\n\n  spots.reserve(finder.spots.size());\n  list<Distl::spot>::const_iterator position = finder.spots.begin();\n  list<Distl::spot>::const_iterator end = finder.spots.end();\n  for (; position!=end;++position ) {\n\n    //It turns out that minimum spot area is an extremely important\n    //  filter without which all sorts of junk are reported.\n    /* 12oct2011-->the following line has a bug; should be >=\n     * However, can't fix the bug without changing all previous results\n     * For now simply work around it by decrementing distl.minimum_spot_area by 1\n     */\n    if ((*position).area() > finder.spotbasesize) {\n      spots.push_back(*position);\n    }\n  }\n\n  icerings.reserve(finder.icerings.size());\n  vector<Distl::icering>::const_iterator iposition = finder.icerings.begin();\n  vector<Distl::icering>::const_iterator iend = finder.icerings.end();\n\n  for (; iposition!=iend;++iposition ) {\n    icerings.push_back(*iposition);\n  }\n\n}\n\nbool\ndi::w_Distl::isIsolated(const w_spot& spot, const double& mmradius) const {\n  //Future:  1) find cases that use this algorithm\n  //         2) change the algorithm so it relies on elliptical modelling\n  //            rather than on the borderpixels data structure\n  double pixelradius = mmradius / finder.pixel_size;\n  typedef scitbx::vec2<double>                 vpoint;\n  af::shared<Distl::point>::const_iterator sptr;\n  af::shared<Distl::point>::const_iterator send;\n\n  //vpoint focusspot(spot.ctr_mass_x(),spot.ctr_mass_y());\n  vpoint focusspot(spot.max_pxl_x(),spot.max_pxl_y());\n\n  spot_list_t::const_iterator p = spots.begin();\n  spot_list_t::const_iterator e = spots.end();\n  for (; p!=e; ++p) {\n      //vpoint target((*p).ctr_mass_x(),(*p).ctr_mass_y());\n      vpoint target((*p).max_pxl_x(),(*p).max_pxl_y());\n      vpoint diff = target - focusspot;\n      double dist = std::sqrt(diff*diff);\n      if ( dist > pixelradius ) {continue;}\n\n      // Consider border pixels of the focus spot\n      vpoint bisector = 0.45*diff;\n      double bisectorsq = bisector*bisector;\n      sptr = spot.borderpixels.begin();\n      send = spot.borderpixels.end();\n      for (;sptr!=send; ++sptr) {\n        vpoint borderpt((*sptr).x,(*sptr).y);\n        vpoint bordervec = borderpt - focusspot;\n        if ( bordervec*bisector > bisectorsq ) {return false;}\n      }\n\n      // Consider border pixels of the target spot\n      bisector = 0.55*diff;\n      bisectorsq = bisector*bisector;\n      sptr = (*p).borderpixels.begin();\n      send = (*p).borderpixels.end();\n      for (;sptr!=send; ++sptr) {\n        vpoint borderpt((*sptr).x,(*sptr).y);\n        vpoint bordervec = borderpt - focusspot;\n        if ( bordervec*bisector < bisectorsq ) {return false;}\n      }\n  }\n  return true;\n}\n", "meta": {"hexsha": "b42930cd4ed32d45a9a31f4b74f07097cdfaf986", "size": 18104, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spotfinder/core_toolbox/distl.cpp", "max_stars_repo_name": "rimmartin/cctbx_project", "max_stars_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "spotfinder/core_toolbox/distl.cpp", "max_issues_repo_name": "rimmartin/cctbx_project", "max_issues_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "spotfinder/core_toolbox/distl.cpp", "max_forks_repo_name": "rimmartin/cctbx_project", "max_forks_repo_head_hexsha": "644090f9432d9afc22cfb542fc3ab78ca8e15e5d", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 37.7166666667, "max_line_length": 104, "alphanum_fraction": 0.6600751215, "num_tokens": 5026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4373090845212351}}
{"text": "#include \"pose.hpp\"\n\n#include <typeinfo> // operator typeid\n\n#include <Eigen/Geometry>\n#include <tbb/parallel_for.h>\n\n#include <autodiff/autodiff.h>\n#include <logger.hpp>\n#include <profiler.hpp>\n#include <utils/is_zero.hpp>\n#include <utils/not_implemented_error.hpp>\n#include <utils/sinc.hpp>\n#include <utils/type_name.hpp>\n\nnamespace ipc::rigid {\n\ntemplate <typename T>\nPose<T>::Pose()\n    : position()\n    , rotation()\n{\n}\n\ntemplate <typename T>\nPose<T>::Pose(const VectorMax3<T>& position, const VectorMax3<T>& rotation)\n    : position(position)\n    , rotation(rotation)\n{\n}\n\ntemplate <typename T> Pose<T>::Pose(const VectorMax6<T>& dof)\n{\n    if (dof.size() == dim_to_ndof(2)) {\n        position = dof.head(dim_to_pos_ndof(2));\n        rotation = dof.tail(dim_to_rot_ndof(2));\n    } else if (dof.size() == dim_to_ndof(3)) {\n        position = dof.head(dim_to_pos_ndof(3));\n        rotation = dof.tail(dim_to_rot_ndof(3));\n    } else {\n        throw NotImplementedError(\"Unknown pose convertion for given ndof\");\n    }\n}\n\ntemplate <typename T>\nPose<T>::Pose(const T& x, const T& y, const T& theta)\n    : Pose(Vector2<T>(x, y), Vector1<T>())\n{\n    rotation << theta;\n}\n\ntemplate <typename T>\nPose<T>::Pose(\n    const T& x,\n    const T& y,\n    const T& z,\n    const T& theta_x,\n    const T& theta_y,\n    const T& theta_z)\n    : Pose(Vector3<T>(x, y, z), Vector3<T>(theta_x, theta_y, theta_z))\n{\n}\n\ntemplate <typename T> Pose<T> Pose<T>::Zero(int dim)\n{\n    assert(dim == 2 || dim == 3);\n    return Pose(\n        VectorX<T>::Zero(Pose<T>::dim_to_pos_ndof(dim)),\n        VectorX<T>::Zero(Pose<T>::dim_to_rot_ndof(dim)));\n}\n\ntemplate <typename T>\nPoses<T> Pose<T>::dofs_to_poses(const VectorX<T>& dofs, int dim)\n{\n    int ndof = dim_to_ndof(dim);\n    int num_poses = dofs.size() / ndof;\n    assert(dofs.size() % ndof == 0);\n    Poses<T> poses;\n    poses.reserve(num_poses);\n    for (int i = 0; i < num_poses; i++) {\n        poses.emplace_back(dofs.segment(i * ndof, ndof));\n    }\n    return poses;\n}\n\ntemplate <typename T> VectorX<T> Pose<T>::poses_to_dofs(const Poses<T>& poses)\n{\n    const int ndof = poses.size() ? poses[0].ndof() : 0;\n    VectorX<T> dofs(poses.size() * ndof);\n    for (size_t i = 0; i < poses.size(); i++) {\n        assert(poses[i].ndof() == ndof);\n        dofs.segment(i * ndof, ndof) = poses[i].dof();\n    }\n    return dofs;\n}\n\ntemplate <typename T> VectorMax6<T> Pose<T>::dof() const\n{\n    VectorMax6<T> pose_dof(ndof());\n    pose_dof.head(pos_ndof()) = position;\n    pose_dof.tail(rot_ndof()) = rotation;\n    return pose_dof;\n}\n\n// Replace a selected dof with the dof in other.\ntemplate <typename T>\nvoid Pose<T>::select_dof(\n    const VectorMax6b& is_dof_selected,\n    const Pose<T>& other,\n    const MatrixMax3d& R)\n{\n    assert(is_dof_selected.size() == this->ndof());\n    assert(other.dim() == this->dim());\n    // R should be a rotation\n    assert(R.isUnitary(1e-9));\n    assert(fabs(R.determinant() - 1.0) < 1.0e-6);\n    position =\n        is_dof_selected.head(pos_ndof()).select(other.position, position);\n    rotation = R.transpose()\n        * is_dof_selected.tail(rot_ndof())\n              .select(R * other.rotation, R * rotation);\n}\n\n// Zero out the i-th dof if is_dof_zero(i) == true.\ntemplate <typename T>\nvoid Pose<T>::zero_dof(const VectorMax6b& is_dof_zero, const MatrixMax3d& R)\n{\n    select_dof(is_dof_zero, Pose<T>::Zero(dim()), R);\n}\n\ntemplate <typename T> MatrixMax3<T> Pose<T>::construct_rotation_matrix() const\n{\n    return ipc::rigid::construct_rotation_matrix(rotation);\n}\n\ntemplate <typename T> Eigen::Quaternion<T> Pose<T>::construct_quaternion() const\n{\n    return ipc::rigid::construct_quaternion(rotation);\n}\n\ntemplate <typename T>\nPose<T> Pose<T>::interpolate(const Pose<T>& pose0, const Pose<T>& pose1, T t)\n{\n    assert(pose0.dim() == pose1.dim());\n    return Pose<T>(\n        (pose1.position - pose0.position) * t + pose0.position,\n        (pose1.rotation - pose0.rotation) * t + pose0.rotation);\n}\n\ntemplate <typename T> bool Pose<T>::operator==(const Pose<T>& other) const\n{\n    return this->position == other.position && this->rotation == other.rotation;\n}\n\ntemplate <typename T> Pose<T>& Pose<T>::operator*=(const T& x)\n{\n    this->position *= x;\n    this->rotation *= x;\n    return *this;\n}\n\ntemplate <typename T> Pose<T> Pose<T>::operator/(const T& x) const\n{\n    return Pose<T>(this->position / x, this->rotation / x);\n}\n\n///////////////////////////////////////////////////////////////////////////\n// Operations on vector of Poses\n\ntemplate <typename T>\nPoses<T> interpolate(const Poses<T>& poses0, const Poses<T>& poses1, T t)\n{\n    PROFILE_POINT(fmt::format(\"Poses<{}>::interpolate\", get_type_name<T>()));\n    PROFILE_START();\n    Poses<T> poses(poses0.size());\n    for (size_t i = 0; i < poses.size(); i++) {\n        poses[i] = Pose<T>::interpolate(poses0[i], poses1[i], t);\n    }\n    PROFILE_END();\n    return poses;\n}\n\ntemplate <typename T> Poses<T> operator*(const Poses<T>& poses, const T& x)\n{\n    Poses<T> product = poses;\n    for (size_t i = 0; i < product.size(); i++) {\n        product[i] *= x;\n    }\n    return product;\n}\n\ntemplate <typename T, typename U> Poses<T> cast(const Poses<U>& poses)\n{\n    Poses<T> poses_T;\n    poses_T.reserve(poses_T.size());\n    for (int i = 0; i < poses.size(); i++) {\n        poses_T.push_back(poses[i].template cast<T>());\n    }\n    return poses_T;\n}\n\ntemplate <typename T>\nMatrixMax3<T> construct_rotation_matrix(const VectorMax3<T>& r)\n{\n    if (r.size() == 1) {\n        return Eigen::Rotation2D<T>(r(0)).toRotationMatrix();\n    } else {\n        assert(r.size() == 3);\n        T sinc_angle = sinc_normx(r);\n        T sinc_half_angle = sinc_normx((r / T(2.0)).eval());\n        Matrix3<T> K = Hat(r);\n        Matrix3<T> K2 = K * K;\n        Matrix3<T> R =\n            sinc_angle * K + 0.5 * sinc_half_angle * sinc_half_angle * K2;\n        R.diagonal().array() += T(1.0);\n        return R;\n    }\n}\n\ntemplate <typename Derived, typename T>\nEigen::Quaternion<T> construct_quaternion(const Eigen::MatrixBase<Derived>& r)\n{\n    assert(r.size() == 3 && (r.rows() == 3 || r.cols() == 3));\n    T angle = r.norm();\n    if (angle == 0) {\n        return Eigen::Quaternion<T>::Identity();\n    }\n    return Eigen::Quaternion<T>(Eigen::AngleAxis<T>(angle, r / angle));\n}\n\ntemplate <typename T> Matrix3<T> rotate_to_z(Vector3<T> n)\n{\n    if (n.norm() == T(0)) {\n        return Matrix3<T>::Identity();\n    }\n    return Eigen::Quaternion<T>::FromTwoVectors(n, Vector3<T>::UnitZ())\n        .toRotationMatrix();\n}\n\ntemplate <typename T> Matrix3<T> rotate_around_z(const T& theta)\n{\n    Matrix3<T> R;\n    R.row(0) << cos(theta), -sin(theta), T(0);\n    R.row(1) << sin(theta), cos(theta), T(0);\n    R.row(2) << T(0), T(0), T(1);\n    return R;\n}\n\ntemplate <typename T>\nvoid decompose_to_z_screwing(\n    const Pose<T>& pose_t0,\n    const Pose<T>& pose_t1,\n    Matrix3<T>& R0,\n    Matrix3<T>& P,\n    T& omega)\n{\n    // Decompose the inbetween rotation as a rotation around the z-axis:\n    //     R = Pᵀ R_z P\n    // Where R = R₁R₀ᵀ, P is a rotation from n̂ to ẑ, and R_z is a rotation\n    // of ω around the z-axis.\n    R0 = pose_t0.construct_rotation_matrix();\n    Matrix3<T> R1 = pose_t1.construct_rotation_matrix();\n    Eigen::AngleAxis<T> r(R1 * R0.transpose());\n    omega = r.angle();\n    P = rotate_to_z(r.axis());\n}\n\n} // namespace ipc::rigid\n", "meta": {"hexsha": "3c187d9c01462fe77cf653d6ad3994bc24dcc76e", "size": 7336, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/physics/pose.tpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "src/physics/pose.tpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "src/physics/pose.tpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 27.2713754647, "max_line_length": 80, "alphanum_fraction": 0.6119138495, "num_tokens": 2132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.4372963995159782}}
{"text": "/*\nAuthor: Rohan Chetan Thanki\nDate created: 16-Oct-2021\n*/\n\n// This file contains functions which are used in the main file. This ensures that the main file is not cluttered\n\n#include \"Hedging_Portfolio.hpp\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n\n#include <boost/random.hpp>\n#include <boost/math/distributions.hpp>\n#include <boost/date_time.hpp>\n\nusing namespace std;\n\n/**************************************** GENERIC UTIL FUNCTIONS ****************************************************/\n\n// split a string into substrings based on a delimiter\ninline vector<string> string_splitter(const string& str, char delimiter)\n{\n    vector<string> str_vec;\n    stringstream ss(str);\n    string token;\n    while (getline(ss, token, delimiter))\n    {\n        str_vec.push_back(token);\n    }\n    return str_vec;\n}\n\n// Writing a 2D Vector to a CSV file\ninline void write2DVectorToCSV(const vector<vector<double>>& vect, const string& filepath)\n{\n    std::ofstream out(filepath);\n    for (int i = 0; i <= vect.size() - 1; i++)\n    {\n        for (int j = 0; j <= vect[0].size() - 1; j++)\n        {\n            out << vect[i][j] << \",\";\n        }\n        out << \"\\n\";\n    }\n}\n\n// Get CDF of Standard Normal\ninline double N(const double& x)\n{\n    boost::math::normal_distribution<> stdNormal(0.0, 1.0);\n    return(cdf(stdNormal, x));\n}\n\n// print a 2D vector to console\ntemplate <typename T>\ninline void printVect(vector<vector<T>> vect)\n{\n    for (int i = 0; i <= vect[0].size() - 1; i++)\n    {\n        for (int j = 0; j <= vect.size() - 1; j++)\n        {\n            cout << vect[j][i] << \"\\t\";\n        }\n        cout << \"\\n\";\n    }\n}\n\n// convert vector of string to vector of double\ninline vector<double> stringToDoubleVect(const vector<string>& inVect)\n{\n    vector<double> outVect;\n    for (int i = 0; i <= inVect.size() - 1; i++)\n    {\n        outVect.push_back(stod(inVect[i]));\n    }\n    return(outVect);\n}\n\n// convert vector of string to vector of dates\ninline vector<boost::gregorian::date> stringtoDateVect(const vector<string>& inVect)\n{\n    vector<boost::gregorian::date> outVect;\n    for (int i = 0; i <= inVect.size() - 1; i++)\n    {\n        outVect.push_back(boost::gregorian::from_simple_string(inVect[i]));\n    }\n    return(outVect);\n}\n\n// function to read a CSV where each column is returned as a vector\ninline vector<vector<string>> readCSV(const string& filepath, const unsigned int& ignoreLines, const int& numCols)\n{\n    ifstream infile(filepath);\n    string line;\n\n    // ignore the first few lines of the file\n    for (int lineCount = 1; lineCount <= ignoreLines && infile.good(); lineCount++)\n        getline(infile, line);\n\n    // initialising vectors which will be populated when the file is read\n    vector<vector<string>> csvData;\n    for (int i = 0; i <= numCols - 1; i++)\n    {\n        vector<string> temp;\n        csvData.push_back(temp);\n    }\n\n    // Read the data line by line\n    while (getline(infile, line))\n    {\n        vector<string> rowData = string_splitter(line, ',');\n        for (int i = 0; i <= numCols - 1; i++)\n        {\n            csvData[i].push_back(rowData[i]);\n        }\n    }\n\n    infile.close();\n    return(csvData);\n}\n\n/************************************ FUNCTIONS SPECIFIC TO PART 1 ****************************************************/\n\n// Simulate stock prices\ninline vector<vector<double>> simulateStockPrices(unsigned int numPaths, unsigned int N, double S0, double T, double u, double sigma)\n{\n    double dt = T / N;          // time step\n    vector < vector<double> > stockPrices;          // creating a vector to store stock prices for all paths\n\n    boost::random::mt19937 rng;     // creating a random number generator\n    //rng.seed(static_cast<unsigned int> (std::time(0)));     // setting the seed of the random number generator\n    rng.seed(123);\n    boost::random::normal_distribution<double> stdNormal(0, 1);     // creating the distribution object\n\n    for (int i = 0; i <= numPaths - 1; i++)\n    {\n        vector<double> pathStockPrices;             // creating a vector to store stock prices of the current path\n        double S = S0;\n        pathStockPrices.push_back(S);\n\n        // add simulated stock prices of the current path to the  current path vector\n        for (int j = 1; j <= N; j++)\n        {\n            S = (S)+(S * u * dt) + (S * sigma * sqrt(dt) * stdNormal(rng));\n            pathStockPrices.push_back(S);\n        }\n\n        // add the stock prices of the current path to the overall stock price vector\n        stockPrices.push_back(pathStockPrices);\n    }\n\n    return(stockPrices);\n}\n\n// Computing Hedging Error of Hedged Portfolio\ninline vector<vector<Hedging_Portfolio>> computeHedgingErrors(const vector<vector<double>>& stockPrices, const double& K, const double& r, const double& T, const double& sigma, const char& optionFlag)\n{\n    unsigned int numPaths = stockPrices.size(); // number of paths\n    unsigned int pathLength = stockPrices[0].size() - 1;\n    double dt = T / pathLength;     // time step\n\n    vector<vector<Hedging_Portfolio>> allHedgingPortfolio;     // creating a vector to store the details of the hedging error\n\n    for (int i = 0; i <= numPaths - 1; i++)\n    {\n        vector<Hedging_Portfolio> pathHedgingPortfolio;\n        for (int j = 0; j <= pathLength; j++)\n        {\n            // creating variables\n            double S = stockPrices[i][j];\n            double TMat = T - (j * dt);\n            double deltaPrev, BPrev, rPrev;\n            double delta, V, B, HE;\n\n            // computing d1 and d2 for Black Scholes model\n            double d1 = (log(S / K) + ((r + (pow(sigma, 2) / 2)) * TMat)) / (sigma * sqrt(TMat));\n            double d2 = d1 - (sigma * sqrt(TMat));\n\n            // creating an object of the hedged portfolio at the current state\n            Hedging_Portfolio portfolio(K, S, r, TMat, sigma, optionFlag);\n\n            // setting delta\n            delta = N(d1);\n            portfolio.setDelta(delta);\n\n            // setting option Price\n            if (optionFlag == 'c' || optionFlag == 'C')\n                V = (S * N(d1)) - (K * exp(-r * TMat) * N(d2));\n            else if (optionFlag == 'p' || optionFlag == 'P')\n                V = (K * exp(-r * TMat) * N(-d2)) - (S * N(-d1));\n            else\n            {\n                cout << \"Flag \" << optionFlag << \"is incorrect. Flag must be either 'c', 'C', 'p' or 'P'\" << endl;\n                throw(10);\n            }\n            portfolio.setOptionPrice(V);\n\n            // setting B\n            if (j == 0)\n            {\n                B = V - delta * S;\n            }\n            else\n            {\n                rPrev = pathHedgingPortfolio[j - 1].getRiskFreeRate();\n                deltaPrev = pathHedgingPortfolio[j - 1].getDelta();\n                BPrev = pathHedgingPortfolio[j - 1].getB();\n                B = ((deltaPrev - delta) * S) + BPrev * exp(rPrev * dt);\n            }\n            portfolio.setB(B);\n\n            // setting Hedging Error\n            if (j == 0)\n            {\n                HE = 0;\n            }\n            else\n            {\n                HE = deltaPrev * S + BPrev * exp(rPrev * dt) - V;\n            }\n            portfolio.setHedgingError(HE);\n\n            // adding current state of the portfolio to the vector of states of the portfolio for current path\n            pathHedgingPortfolio.push_back(portfolio);\n        }\n\n        // adding the path of portfolio to the vector containinf portfolio states of all paths\n        allHedgingPortfolio.push_back(pathHedgingPortfolio);\n    }\n    return(allHedgingPortfolio);\n}\n\n// function to create a 2D Vector of a specific attribute from the hedged portfolio state vector\ninline vector<vector<double>> getHedgedPortfolioParam(const vector<vector<Hedging_Portfolio>>& allPortfolioStates, const string param)\n{\n    vector<vector<double>> allVect;\n    int numPaths = allPortfolioStates.size();\n    int pathSize = allPortfolioStates[0].size() - 1;\n\n\n    for (int i = 0; i <= numPaths - 1; i++)\n    {\n        vector<double> pathVect;\n        for (int j = 0; j <= pathSize; j++)\n        {\n            double val;\n\n            if (param == \"S\")\n                val = allPortfolioStates[i][j].getSpotPrice();\n            else if (param == \"DELTA\")\n                val = allPortfolioStates[i][j].getDelta();\n            else if (param == \"V\")\n                val = allPortfolioStates[i][j].getOptionPrice();\n            else if (param == \"B\")\n                val = allPortfolioStates[i][j].getB();\n            else if (param == \"HE\")\n                val = allPortfolioStates[i][j].getHedgingError();\n            else\n                val = 0;\n\n            pathVect.push_back(val);\n        }\n        allVect.push_back(pathVect);\n    }\n\n    return(allVect);\n}\n\n/************************************** FUNCTIONS SPECIFIC TO PART 2 ****************************************************/\n\n// Count the number of weekdays between 2 days\ninline long countWeekDays(string d0str, string d1str)\n{\n    boost::gregorian::date d0(boost::gregorian::from_simple_string(d0str));\n    boost::gregorian::date d1(boost::gregorian::from_simple_string(d1str));\n    long ndays = (d1 - d0).days() + 1; // +1 for inclusive\n    long nwkends = 2 * ((ndays + d0.day_of_week()) / 7); // 2*Saturdays\n    if (d0.day_of_week() == boost::date_time::Sunday) ++nwkends;\n    if (d1.day_of_week() == boost::date_time::Saturday) --nwkends;\n    return ndays - nwkends;\n}\n\n// finding corresponding value from a vector given the date\ninline double findVal(vector<string> dateVec, vector<double> valVec, string date)\n{\n    auto it = find(dateVec.begin(), dateVec.end(), date);\n    return valVec.at(it - dateVec.begin());  // this will throw an exception if array is out of bounds\n}\n", "meta": {"hexsha": "05417b8d70126ef4c7439edf2274f63a11c783e3", "size": 9726, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sys_Comp_Midterm_Project/Sys_Comp_Midterm_Project/Utilities.cpp", "max_stars_repo_name": "rohanthanki/delta_hedging", "max_stars_repo_head_hexsha": "f1c2b8e9965ccea594466e6a32e1c8f82036763e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sys_Comp_Midterm_Project/Sys_Comp_Midterm_Project/Utilities.cpp", "max_issues_repo_name": "rohanthanki/delta_hedging", "max_issues_repo_head_hexsha": "f1c2b8e9965ccea594466e6a32e1c8f82036763e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sys_Comp_Midterm_Project/Sys_Comp_Midterm_Project/Utilities.cpp", "max_forks_repo_name": "rohanthanki/delta_hedging", "max_forks_repo_head_hexsha": "f1c2b8e9965ccea594466e6a32e1c8f82036763e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5379310345, "max_line_length": 200, "alphanum_fraction": 0.5687847008, "num_tokens": 2431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.4372963819218968}}
{"text": "/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n *****************************************************************************/\n\n#ifndef MAPNIK_WELL_KNOWN_SRS_HPP\n#define MAPNIK_WELL_KNOWN_SRS_HPP\n\n// mapnik\n#include <mapnik/global.hpp> // for M_PI on windows\n#include <mapnik/enumeration.hpp>\n#include <mapnik/geometry.hpp>\n\n#pragma GCC diagnostic push\n#include <mapnik/warning_ignore.hpp>\n#include <boost/optional.hpp>\n#pragma GCC diagnostic pop\n\n// stl\n#include <cmath>\n\nnamespace mapnik {\n\nenum well_known_srs_enum : std::uint8_t {\n    WGS_84,\n    G_MERC,\n    well_known_srs_enum_MAX\n};\n\nDEFINE_ENUM( well_known_srs_e, well_known_srs_enum );\n\nstatic const double EARTH_RADIUS = 6378137.0;\nstatic const double EARTH_DIAMETER = EARTH_RADIUS * 2.0;\nstatic const double EARTH_CIRCUMFERENCE = EARTH_DIAMETER * M_PI;\nstatic const double MAXEXTENT = EARTH_CIRCUMFERENCE / 2.0;\nstatic const double M_PI_by2 = M_PI / 2;\nstatic const double D2R = M_PI / 180;\nstatic const double R2D = 180 / M_PI;\nstatic const double M_PIby360 = M_PI / 360;\nstatic const double MAXEXTENTby180 = MAXEXTENT / 180;\nstatic const double MAX_LATITUDE = R2D * (2 * std::atan(std::exp(180 * D2R)) - M_PI_by2);\nstatic const std::string MAPNIK_LONGLAT_PROJ = \"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\";\nstatic const std::string MAPNIK_GMERC_PROJ = \"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over\";\n\nboost::optional<well_known_srs_e> is_well_known_srs(std::string const& srs);\n\nboost::optional<bool> is_known_geographic(std::string const& srs);\n\nstatic inline bool lonlat2merc(double * x, double * y , int point_count)\n{\n    for(int i=0; i<point_count; ++i)\n    {\n        if (x[i] > 180) x[i] = 180;\n        else if (x[i] < -180) x[i] = -180;\n        if (y[i] > MAX_LATITUDE) y[i] = MAX_LATITUDE;\n        else if (y[i] < -MAX_LATITUDE) y[i] = -MAX_LATITUDE;\n        x[i] = x[i] * MAXEXTENTby180;\n        y[i] = std::log(std::tan((90 + y[i]) * M_PIby360)) * R2D;\n        y[i] = y[i] * MAXEXTENTby180;\n    }\n    return true;\n}\n\nstatic inline bool merc2lonlat(double * x, double * y , int point_count)\n{\n    for(int i=0; i<point_count; i++)\n    {\n        if (x[i] > MAXEXTENT) x[i] = MAXEXTENT;\n        else if (x[i] < -MAXEXTENT) x[i] = -MAXEXTENT;\n        if (y[i] > MAXEXTENT) y[i] = MAXEXTENT;\n        else if (y[i] < -MAXEXTENT) y[i] = -MAXEXTENT;\n        x[i] = (x[i] / MAXEXTENT) * 180;\n        y[i] = (y[i] / MAXEXTENT) * 180;\n        y[i] = R2D * (2 * std::atan(std::exp(y[i] * D2R)) - M_PI_by2);\n    }\n    return true;\n}\n\nstatic inline bool lonlat2merc(geometry::line_string<double> & ls)\n{\n    for(auto & p : ls)\n    {\n        if (p.x > 180) p.x = 180;\n        else if (p.x < -180) p.x = -180;\n        if (p.y > MAX_LATITUDE) p.y = MAX_LATITUDE;\n        else if (p.y < -MAX_LATITUDE) p.y = -MAX_LATITUDE;\n        p.x = p.x * MAXEXTENTby180;\n        p.y = std::log(std::tan((90 + p.y) * M_PIby360)) * R2D;\n        p.y = p.y * MAXEXTENTby180;\n    }\n    return true;\n}\n\nstatic inline bool merc2lonlat(geometry::line_string<double> & ls)\n{\n    for (auto & p : ls)\n    {\n        if (p.x > MAXEXTENT) p.x = MAXEXTENT;\n        else if (p.x < -MAXEXTENT) p.x = -MAXEXTENT;\n        if (p.y > MAXEXTENT) p.y = MAXEXTENT;\n        else if (p.y < -MAXEXTENT) p.y = -MAXEXTENT;\n        p.x = (p.x / MAXEXTENT) * 180;\n        p.y = (p.y / MAXEXTENT) * 180;\n        p.y = R2D * (2 * std::atan(std::exp(p.y * D2R)) - M_PI_by2);\n    }\n    return true;\n}\n\n}\n\n#endif // MAPNIK_WELL_KNOWN_SRS_HPP\n", "meta": {"hexsha": "e8349e709efec76b37ac38db828dbd0bbab096e0", "size": 4410, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/mapnik/include/mapnik/well_known_srs.hpp", "max_stars_repo_name": "baiyicanggou/mapnik_mvt", "max_stars_repo_head_hexsha": "9bde52fa9958d81361c015c816858534ec0931bb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "external/mapnik/include/mapnik/well_known_srs.hpp", "max_issues_repo_name": "baiyicanggou/mapnik_mvt", "max_issues_repo_head_hexsha": "9bde52fa9958d81361c015c816858534ec0931bb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/mapnik/include/mapnik/well_known_srs.hpp", "max_forks_repo_name": "baiyicanggou/mapnik_mvt", "max_forks_repo_head_hexsha": "9bde52fa9958d81361c015c816858534ec0931bb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1860465116, "max_line_length": 176, "alphanum_fraction": 0.6219954649, "num_tokens": 1395, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.43714723979151643}}
{"text": "/* ------------------------------------------------------\n *\n * @file logistic.cpp\n *\n * @brief Logistic-Regression functions\n *\n * We implement the conjugate-gradient method and the iteratively-reweighted-\n * least-squares method.\n *\n *//* ----------------------------------------------------------------------- */\n#include <limits>\n#include <dbconnector/dbconnector.hpp>\n#include <modules/shared/HandleTraits.hpp>\n#include <modules/prob/boost.hpp>\n#include <boost/math/distributions.hpp>\n#include <modules/prob/student.hpp>\n#include \"logistic.hpp\"\n\nnamespace madlib {\n\n// Use Eigen\nusing namespace dbal::eigen_integration;\n\nnamespace modules {\n\n// Import names from other MADlib modules\nusing dbal::NoSolutionFoundException;\n\nnamespace regress {\n\n// FIXME this enum should be accessed by all modules that may need grouping\n// valid status values\nenum { IN_PROCESS, COMPLETED, TERMINATED, NULL_EMPTY };\n\n// Internal functions\nAnyType stateToResult(const Allocator &inAllocator,\n                      const HandleMap<const ColumnVector, TransparentHandle<double> >& inCoef,\n                      const Matrix & hessian,\n                      const double &logLikelihood,\n                      int status,\n                      const uint64_t &numRows);\n\n\n// ---------------------------------------------------------------------------\n//              Logistic Regression States\n// ---------------------------------------------------------------------------\n\n/**\n * @brief Inter- and intra-iteration state for conjugate-gradient method for\n *        logistic regression\n *\n * TransitionState encapsualtes the transition state during the\n * logistic-regression aggregate function. To the database, the state is\n * exposed as a single DOUBLE PRECISION array, to the C++ code it is a proper\n * object containing scalars and vectors.\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length at least 5, and all elemenets are 0.\n *\n */\ntemplate <class Handle>\nclass LogRegrCGTransitionState {\n    template <class OtherHandle>\n    friend class LogRegrCGTransitionState;\n\n  public:\n    LogRegrCGTransitionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n\n        rebind(static_cast<uint16_t>(mStorage[1]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the conjugate-gradient state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(const Allocator &inAllocator, uint16_t inWidthOfX) {\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n                                             dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(inWidthOfX));\n        rebind(inWidthOfX);\n        widthOfX = inWidthOfX;\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle>\n    LogRegrCGTransitionState &operator=(\n        const LogRegrCGTransitionState<OtherHandle> &inOtherState) {\n\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object by copying the intra-iteration\n     *     fields\n     */\n    template <class OtherHandle>\n    LogRegrCGTransitionState &operator+=(\n        const LogRegrCGTransitionState<OtherHandle> &inOtherState) {\n\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            widthOfX != inOtherState.widthOfX)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                                   \"states\");\n\n        numRows += inOtherState.numRows;\n        gradNew += inOtherState.gradNew;\n        X_transp_AX += inOtherState.X_transp_AX;\n        logLikelihood += inOtherState.logLikelihood;\n        // merged state should have the higher status\n        // (see top of file for more on 'status' )\n        status = (inOtherState.status > status) ? inOtherState.status : status;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        numRows = 0;\n        X_transp_AX.fill(0);\n        gradNew.fill(0);\n        logLikelihood = 0;\n        status = IN_PROCESS;\n    }\n\n  private:\n    static inline size_t arraySize(const uint16_t inWidthOfX) {\n        return 6 + inWidthOfX * inWidthOfX + 4 * inWidthOfX;\n    }\n\n    /**\n     * @brief Rebind to a new storage array\n     *\n     * @param inWidthOfX The number of independent variables.\n     *\n     * Array layout (iteration refers to one aggregate-function call):\n     * Inter-iteration components (updated in final function):\n     * - 0: iteration (current iteration)\n     * - 1: widthOfX (number of coefficients)\n     * - 2: coef (vector of coefficients)\n     * - 2 + widthOfX: dir (direction)\n     * - 2 + 2 * widthOfX: grad (gradient)\n     * - 2 + 3 * widthOfX: beta (scale factor)\n     *\n     * Intra-iteration components (updated in transition step):\n     * - 3 + 3 * widthOfX: numRows (number of rows already processed in this iteration)\n     * - 4 + 3 * widthOfX: gradNew (intermediate value for gradient)\n     * - 4 + 4 * widthOfX: X_transp_AX (X^T A X)\n     * - 4 + widthOfX * widthOfX + 4 * widthOfX: logLikelihood ( ln(l(c)) )\n     */\n    void rebind(uint16_t inWidthOfX) {\n        iteration.rebind(&mStorage[0]);\n        widthOfX.rebind(&mStorage[1]);\n        coef.rebind(&mStorage[2], inWidthOfX);\n        dir.rebind(&mStorage[2 + inWidthOfX], inWidthOfX);\n        grad.rebind(&mStorage[2 + 2 * inWidthOfX], inWidthOfX);\n        beta.rebind(&mStorage[2 + 3 * inWidthOfX]);\n        numRows.rebind(&mStorage[3 + 3 * inWidthOfX]);\n        gradNew.rebind(&mStorage[4 + 3 * inWidthOfX], inWidthOfX);\n        X_transp_AX.rebind(&mStorage[4 + 4 * inWidthOfX], inWidthOfX, inWidthOfX);\n        logLikelihood.rebind(&mStorage[4 + inWidthOfX * inWidthOfX + 4 * inWidthOfX]);\n        status.rebind(&mStorage[5 + inWidthOfX * inWidthOfX + 4 * inWidthOfX]);\n    }\n\n    Handle mStorage;\n\n  public:\n    typename HandleTraits<Handle>::ReferenceToUInt32 iteration;\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap coef;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap dir;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap grad;\n    typename HandleTraits<Handle>::ReferenceToDouble beta;\n\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap gradNew;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap X_transp_AX;\n    typename HandleTraits<Handle>::ReferenceToDouble logLikelihood;\n    typename HandleTraits<Handle>::ReferenceToUInt16 status;\n};\n\n\n\n\n/**\n * @brief Logistic function\n */\ninline double sigma(double x) {\n    return 1. / (1. + std::exp(-x));\n}\n\n/**\n * @brief Perform the logistic-regression transition step\n */\nAnyType\nlogregr_cg_step_transition::run(AnyType &args) {\n    LogRegrCGTransitionState<MutableArrayHandle<double> > state = args[0];\n    if (args[1].isNull() || args[2].isNull()) { return args[0]; }\n    double y = args[1].getAs<bool>() ? 1. : -1.;\n    MappedColumnVector x;\n    try {\n        // an exception is raised in the backend if args[2] contains nulls\n        MappedColumnVector xx = args[2].getAs<MappedColumnVector>();\n        // x is a const reference, we can only rebind to change its pointer\n        x.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    // The following check was added with MADLIB-138.\n    if (!dbal::eigen_integration::isfinite(x)) {\n        //throw std::domain_error(\"Design matrix is not finite.\");\n        warning(\"Design matrix is not finite.\");\n        state.status = TERMINATED;\n        return state;\n    }\n\n    if (state.numRows == 0) {\n        if (x.size() > std::numeric_limits<uint16_t>::max()){\n            //throw std::domain_error(\n            //    \"Number of independent variables cannot be \"\n            //    \"larger than 65535.\");\n            warning(\"Number of independent variables cannot be larger than 65535.\");\n            state.status = TERMINATED;\n            return state;\n        }\n\n\n        state.initialize(*this, static_cast<uint16_t>(x.size()));\n        if (!args[3].isNull()) {\n            LogRegrCGTransitionState<ArrayHandle<double> > previousState = args[3];\n\n            state = previousState;\n            state.reset();\n        }\n    }\n    // Now do the transition step\n    state.numRows++;\n    double xc = dot(x, state.coef);\n    state.gradNew.noalias() += sigma(-y * xc) * y * trans(x);\n\n    // Note: sigma(-x) = 1 - sigma(x).\n    // a_i = sigma(x_i c) sigma(-x_i c)\n    double a = sigma(xc) * sigma(-xc);\n    //triangularView<Lower>(state.X_transp_AX) += x * trans(x) * a;\n    state.X_transp_AX += x * trans(x) * a;\n\n    //          n\n    //         --\n    // l(c) = -\\  log(1 + exp(-y_i * c^T x_i))\n    //         /_\n    //         i=1\n    state.logLikelihood -= std::log( 1. + std::exp(-y * xc) );\n\n    return state;\n}\n\n\n/**\n * @brief Perform the perliminary aggregation function: Merge transition states\n */\nAnyType\nlogregr_cg_step_merge_states::run(AnyType &args) {\n    LogRegrCGTransitionState<MutableArrayHandle<double> > stateLeft = args[0];\n    LogRegrCGTransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    // We first handle the trivial case where this function is called with one\n    // of the states being the initial state\n    if (stateLeft.numRows == 0)\n        return stateRight;\n    else if (stateRight.numRows == 0)\n        return stateLeft;\n\n    // Merge states together and return\n    stateLeft += stateRight;\n    return stateLeft;\n}\n\n\n\n/**\n * @brief Perform the logistic-regression final step\n */\nAnyType\nlogregr_cg_step_final::run(AnyType &args) {\n    // We request a mutable object. Depending on the backend, this might perform\n    // a deep copy.\n    LogRegrCGTransitionState<MutableArrayHandle<double> > state = args[0];\n\n    // Aggregates that haven't seen any data just return Null.\n    if (state.numRows == 0){\n        state.status = NULL_EMPTY;\n        return state;\n    }\n\n    // Note: k = state.iteration\n    if (state.iteration == 0) {\n        // Iteration computes the gradient\n\n        state.dir = state.gradNew;\n        state.grad = state.gradNew;\n    } else {\n        // We use the Hestenes-Stiefel update formula:\n        //\n        //            g_k^T (g_k - g_{k-1})\n        // beta_k = -------------------------\n        //          d_{k-1}^T (g_k - g_{k-1})\n        ColumnVector gradNewMinusGrad = state.gradNew - state.grad;\n        state.beta\n            = dot(state.gradNew, gradNewMinusGrad)\n            / dot(state.dir, gradNewMinusGrad);\n\n        // Alternatively, we could use Polak-Ribière\n        // state.beta\n        //     = dot(state.gradNew, gradNewMinusGrad)\n        //     / dot(state.grad, state.grad);\n\n        // Or Fletcher–Reeves\n        // state.beta\n        //     = dot(state.gradNew, state.gradNew)\n        //     / dot(state.grad, state.grad);\n\n        // Do a direction restart (Powell restart)\n        // Note: This is testing whether state.beta < 0 if state.beta were\n        // assigned according to Polak-Ribière\n        if (dot(state.gradNew, gradNewMinusGrad)\n            / dot(state.grad, state.grad) <= std::numeric_limits<double>::denorm_min()) state.beta = 0;\n\n        // d_k = g_k - beta_k * d_{k-1}\n        state.dir = state.gradNew - state.beta * state.dir;\n        state.grad = state.gradNew;\n    }\n\n    // H_k = - X^T A_k X\n    // where A_k = diag(a_1, ..., a_n) and a_i = sigma(x_i c_{k-1}) sigma(-x_i c_{k-1})\n    //\n    //             g_k^T d_k\n    // alpha_k = -------------\n    //           d_k^T H_k d_k\n    //\n    // c_k = c_{k-1} - alpha_k * d_k\n    state.coef += dot(state.grad, state.dir) /\n        as_scalar(trans(state.dir) * state.X_transp_AX * state.dir)\n        * state.dir;\n\n    if(!state.coef.is_finite()){\n        //throw NoSolutionFoundException(\n        //    \"Over- or underflow in conjugate-gradient step, while updating \"\n        //    \"coefficients. Input data is likely of poor numerical condition.\");\n        warning(\"Over- or underflow in conjugate-gradient step, while updating \"\n              \"coefficients. Input data is likely of poor numerical condition.\");\n        state.status = TERMINATED;\n        return state;\n    }\n\n    state.iteration++;\n    return state;\n}\n\n/**\n * @brief Return the difference in log-likelihood between two states\n */\nAnyType\ninternal_logregr_cg_step_distance::run(AnyType &args) {\n    LogRegrCGTransitionState<ArrayHandle<double> > stateLeft = args[0];\n    LogRegrCGTransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    if(stateLeft.status == NULL_EMPTY || stateRight.status == NULL_EMPTY){\n        return 0.0;\n    }\n\n    return std::abs(stateLeft.logLikelihood - stateRight.logLikelihood);\n}\n\n/**\n * @brief Return the coefficients and diagnostic statistics of the state\n */\nAnyType\ninternal_logregr_cg_result::run(AnyType &args) {\n    LogRegrCGTransitionState<ArrayHandle<double> > state = args[0];\n    if (state.status == NULL_EMPTY)\n        return Null();\n\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        state.X_transp_AX, EigenvaluesOnly, ComputePseudoInverse);\n\n    return stateToResult(*this, state.coef,\n                         state.X_transp_AX, state.logLikelihood,\n                         state.status, state.numRows);\n}\n\n\n\n/**\n * @brief Inter- and intra-iteration state for iteratively-reweighted-least-\n *        squares method for logistic regression\n *\n * TransitionState encapsualtes the transition state during the\n * logistic-regression aggregate function. To the database, the state is\n * exposed as a single DOUBLE PRECISION array, to the C++ code it is a proper\n * object containing scalars, a vector, and a matrix.\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length at least 4, and all elemenets are 0.\n */\ntemplate <class Handle>\nclass LogRegrIRLSTransitionState {\n    template <class OtherHandle>\n    friend class LogRegrIRLSTransitionState;\n\n  public:\n    LogRegrIRLSTransitionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n\n        rebind(static_cast<uint16_t>(mStorage[0]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the iteratively-reweighted-least-squares state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(const Allocator &inAllocator, uint16_t inWidthOfX) {\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n                                             dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(inWidthOfX));\n        rebind(inWidthOfX);\n        widthOfX = inWidthOfX;\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle>\n    LogRegrIRLSTransitionState &operator=(\n        const LogRegrIRLSTransitionState<OtherHandle> &inOtherState) {\n\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object by copying the intra-iteration\n     *     fields\n     */\n    template <class OtherHandle>\n    LogRegrIRLSTransitionState &operator+=(\n        const LogRegrIRLSTransitionState<OtherHandle> &inOtherState) {\n\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            widthOfX != inOtherState.widthOfX)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                                   \"states\");\n\n        numRows += inOtherState.numRows;\n        X_transp_Az += inOtherState.X_transp_Az;\n        X_transp_AX += inOtherState.X_transp_AX;\n        logLikelihood += inOtherState.logLikelihood;\n        // merged state should have the higher status\n        // (see top of file for more on 'status' )\n        status = (inOtherState.status > status) ? inOtherState.status : status;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        numRows         = 0;\n        X_transp_Az.fill(0);\n        X_transp_AX.fill(0);\n        logLikelihood   = 0;\n        status          = IN_PROCESS;\n    }\n\n  private:\n    static inline uint32_t arraySize(const uint16_t inWidthOfX) {\n        return 4 + inWidthOfX * inWidthOfX + 2 * inWidthOfX;\n    }\n\n    /**\n     * @brief Rebind to a new storage array\n     *\n     * @param inWidthOfX The number of independent variables.\n     *\n     * Array layout (iteration refers to one aggregate-function call):\n     * Inter-iteration components (updated in final function):\n     * - 0: widthOfX (number of coefficients)\n     * - 1: coef (vector of coefficients)\n     *\n     * Intra-iteration components (updated in transition step):\n     * - 1 + widthOfX: numRows (number of rows already processed in this iteration)\n     * - 2 + widthOfX: X_transp_Az (X^T A z)\n     * - 2 + 2 * widthOfX: X_transp_AX (X^T A X)\n     * - 2 + widthOfX^2 + 2 * widthOfX: logLikelihood ( ln(l(c)) )\n     */\n    void rebind(uint16_t inWidthOfX = 0) {\n        widthOfX.rebind(&mStorage[0]);\n        coef.rebind(&mStorage[1], inWidthOfX);\n        numRows.rebind(&mStorage[1 + inWidthOfX]);\n        X_transp_Az.rebind(&mStorage[2 + inWidthOfX], inWidthOfX);\n        X_transp_AX.rebind(&mStorage[2 + 2 * inWidthOfX], inWidthOfX, inWidthOfX);\n        logLikelihood.rebind(&mStorage[2 + inWidthOfX * inWidthOfX + 2 * inWidthOfX]);\n        status.rebind(&mStorage[3 + inWidthOfX * inWidthOfX + 2 * inWidthOfX]);\n    }\n\n    Handle mStorage;\n\n  public:\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap coef;\n\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap X_transp_Az;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap X_transp_AX;\n    typename HandleTraits<Handle>::ReferenceToDouble logLikelihood;\n    typename HandleTraits<Handle>::ReferenceToUInt16 status;\n\n};\n\n\nAnyType logregr_irls_step_transition::run(AnyType &args) {\n    LogRegrIRLSTransitionState<MutableArrayHandle<double> > state = args[0];\n    if (args[1].isNull() || args[2].isNull()) { return args[0]; }\n    double y = args[1].getAs<bool>() ? 1. : -1.;\n    MappedColumnVector x;\n    try {\n        // an exception is raised in the backend if args[2] contains nulls\n        MappedColumnVector xx = args[2].getAs<MappedColumnVector>();\n        // x is a const reference, we can only rebind to change its pointer\n        x.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    // The following check was added with MADLIB-138.\n    if (!x.is_finite()){\n        //throw std::domain_error(\"Design matrix is not finite.\");\n        warning(\"Design matrix is not finite.\");\n        state.status = TERMINATED;\n        return state;\n    }\n\n    if (state.numRows == 0) {\n        if (x.size() > std::numeric_limits<uint16_t>::max()){\n            //throw std::domain_error(\n            //    \"Number of independent variables cannot be larger than 65535.\");\n            warning(\"Number of independent variables cannot be larger than 65535.\");\n            state.status = TERMINATED;\n            return state;\n        }\n\n        state.initialize(*this, static_cast<uint16_t>(x.size()));\n        if (!args[3].isNull()) {\n            LogRegrIRLSTransitionState<ArrayHandle<double> > previousState = args[3];\n\n            state = previousState;\n            state.reset();\n        }\n    }\n\n    // Now do the transition step\n    state.numRows++;\n\n    // xc = x^T_i c\n    double xc = dot(x, state.coef);\n\n    // a_i = sigma(x_i c) sigma(-x_i c)\n    double a = sigma(xc) * sigma(-xc);\n\n    // Note: sigma(-x) = 1 - sigma(x).\n    //\n    //             sigma(-y_i x_i c) y_i\n    // z = x_i c + ---------------------\n    //                     a_i\n    //\n    // To avoid overflows if a_i is close to 0, we do not compute z directly,\n    // but instead compute a * z.\n    double az = xc * a + sigma(-y * xc) * y;\n\n    state.X_transp_Az.noalias() += x * az;\n    //triangularView<Lower>(state.X_transp_AX) += x * trans(x) * a;\n    state.X_transp_AX += x * trans(x) * a;\n\n    //          n\n    //         --\n    // l(c) = -\\  ln(1 + exp(-y_i * c^T x_i))\n    //         /_\n    //         i=1\n    state.logLikelihood -= std::log( 1. + std::exp(-y * xc) );\n    return state;\n}\n\n\n/**\n * @brief Perform the perliminary aggregation function: Merge transition states\n */\nAnyType logregr_irls_step_merge_states::run(AnyType &args) {\n    LogRegrIRLSTransitionState<MutableArrayHandle<double> > stateLeft = args[0];\n    LogRegrIRLSTransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    // We first handle the trivial case where this function is called with one\n    // of the states being the initial state\n    if (stateLeft.numRows == 0)\n        return stateRight;\n    else if (stateRight.numRows == 0)\n        return stateLeft;\n\n    // Merge states together and return\n    stateLeft += stateRight;\n    return stateLeft;\n}\n\n/**\n * @brief Perform the logistic-regression final step\n */\nAnyType logregr_irls_step_final::run(AnyType &args) {\n    // We request a mutable object. Depending on the backend, this might perform\n    // a deep copy.\n    LogRegrIRLSTransitionState<MutableArrayHandle<double> > state = args[0];\n\n    // Aggregates that haven't seen any data just return Null.\n    if (state.numRows == 0){\n        state.status = NULL_EMPTY;\n        return state;\n    }\n\n    // See MADLIB-138. At least on certain platforms and with certain versions,\n    // LAPACK will run into an infinite loop if pinv() is called for non-finite\n    // matrices. We extend the check also to the dependent variables.\n    if (!state.X_transp_AX.is_finite() || !state.X_transp_Az.is_finite()){\n        //throw NoSolutionFoundException(\n        //    \"Over- or underflow in intermediate calulation. Input data is \"\n        //    \"likely of poor numerical condition.\");\n        warning(\"Over- or underflow in intermediate calulation. Input data is \"\n              \"likely of poor numerical condition.\");\n        state.status = TERMINATED;\n        return state;\n    }\n\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        state.X_transp_AX, EigenvaluesOnly, ComputePseudoInverse);\n\n    // Precompute (X^T * A * X)^+\n    Matrix inverse_of_X_transp_AX = decomposition.pseudoInverse();\n\n    state.coef.noalias() = inverse_of_X_transp_AX * state.X_transp_Az;\n    if(!state.coef.is_finite()){\n        //throw NoSolutionFoundException(\n        //    \"Over- or underflow in Newton step, while updating coefficients. \"\n        //    \"Input data is likely of poor numerical condition.\");\n        warning(\"Over- or underflow in Newton step, while updating coefficients.\"\n              \"Input data is likely of poor numerical condition.\");\n        state.status = TERMINATED;\n        return state;\n    }\n\n    // We use the intra-iteration field X_transp_Az for storing the diagonal\n    // of X^T A X, so that we don't have to recompute it in the result function.\n    // Likewise, we store the condition number.\n    // FIXME: This feels a bit like a hack.\n    // state.X_transp_Az = inverse_of_X_transp_AX.diagonal();\n    // state.X_transp_AX(0,0) = decomposition.conditionNo();\n    // state.X_transp_Az(0) = decomposition.conditionNo();\n    return state;\n}\n\n\n/**\n * @brief Return the difference in log-likelihood between two states\n */\nAnyType internal_logregr_irls_step_distance::run(AnyType &args) {\n    LogRegrIRLSTransitionState<ArrayHandle<double> > stateLeft = args[0];\n    LogRegrIRLSTransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    if(stateLeft.status == NULL_EMPTY || stateRight.status == NULL_EMPTY){\n        return 0.0;\n    }\n\n    return std::abs(stateLeft.logLikelihood - stateRight.logLikelihood);\n}\n\n\n/**\n * @brief Return the coefficients and diagnostic statistics of the state\n */\nAnyType internal_logregr_irls_result::run(AnyType &args) {\n    LogRegrIRLSTransitionState<ArrayHandle<double> > state = args[0];\n\n    if (state.status == NULL_EMPTY)\n        return Null();\n\n    return stateToResult(*this, state.coef, state.X_transp_AX,\n                         state.logLikelihood,\n                         state.status, state.numRows);\n}\n\n/**\n * @brief Inter- and intra-iteration state for incremental gradient\n *        method for logistic regression\n *\n * TransitionState encapsualtes the transition state during the\n * logistic-regression aggregate function. To the database, the state is\n * exposed as a single DOUBLE PRECISION array, to the C++ code it is a proper\n * object containing scalars, a vector, and a matrix.\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length at least 4, and all elemenets are 0.\n */\ntemplate <class Handle>\nclass LogRegrIGDTransitionState {\n    template <class OtherHandle>\n    friend class LogRegrIGDTransitionState;\n\n  public:\n    LogRegrIGDTransitionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n\n        rebind(static_cast<uint16_t>(mStorage[0]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the conjugate-gradient state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(const Allocator &inAllocator, uint16_t inWidthOfX) {\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n                                             dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(inWidthOfX));\n        rebind(inWidthOfX);\n        widthOfX = inWidthOfX;\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle>\n    LogRegrIGDTransitionState &operator=(\n        const LogRegrIGDTransitionState<OtherHandle> &inOtherState) {\n\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object by copying the intra-iteration\n     *     fields\n     */\n    template <class OtherHandle>\n    LogRegrIGDTransitionState &operator+=(\n        const LogRegrIGDTransitionState<OtherHandle> &inOtherState) {\n\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            widthOfX != inOtherState.widthOfX)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                                   \"states\");\n\n        // Compute the average of the models. Note: The following remains an\n        // invariant, also after more than one merge:\n        // The model is a linear combination of the per-segment models\n        // where the coefficient (weight) for each per-segment model is the\n        // ratio \"# rows in segment / total # rows of all segments merged so\n        // far\".\n        double totalNumRows = static_cast<double>(numRows)\n            + static_cast<double>(inOtherState.numRows);\n        coef = double(numRows) / totalNumRows * coef\n            + double(inOtherState.numRows) / totalNumRows * inOtherState.coef;\n\n        numRows += inOtherState.numRows;\n        X_transp_AX += inOtherState.X_transp_AX;\n        logLikelihood += inOtherState.logLikelihood;\n        // merged state should have the higher status\n        // (see top of file for more on 'status' )\n        status = (inOtherState.status == TERMINATED) ? inOtherState.status : status;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        // FIXME: HAYING: stepsize is hard-coded here now\n        stepsize = .01;\n        numRows = 0;\n        X_transp_AX.fill(0);\n        logLikelihood = 0;\n        status = IN_PROCESS;\n    }\n\n  private:\n    static inline uint32_t arraySize(const uint16_t inWidthOfX) {\n        return 5 + inWidthOfX * inWidthOfX + inWidthOfX;\n    }\n    /**\n     * @brief Rebind to a new storage array\n     *\n     * @param inWidthOfX The number of independent variables.\n     *\n     * Array layout (iteration refers to one aggregate-function call):\n     * Inter-iteration components (updated in final function):\n     * - 0: widthOfX (number of coefficients)\n     * - 1: stepsize (step size of gradient steps)\n     * - 2: coef (vector of coefficients)\n     *\n     * Intra-iteration components (updated in transition step):\n     * - 2 + widthOfX: numRows (number of rows already processed in this iteration)\n     * - 3 + widthOfX: X_transp_AX (X^T A X)\n     * - 3 + widthOfX * widthOfX + widthOfX: logLikelihood ( ln(l(c)) )\n     */\n    void rebind(uint16_t inWidthOfX) {\n        widthOfX.rebind(&mStorage[0]);\n        stepsize.rebind(&mStorage[1]);\n        coef.rebind(&mStorage[2], inWidthOfX);\n        numRows.rebind(&mStorage[2 + inWidthOfX]);\n        X_transp_AX.rebind(&mStorage[3 + inWidthOfX], inWidthOfX, inWidthOfX);\n        logLikelihood.rebind(&mStorage[3 + inWidthOfX * inWidthOfX + inWidthOfX]);\n        status.rebind(&mStorage[4 + inWidthOfX * inWidthOfX + inWidthOfX]);\n    }\n\n    Handle mStorage;\n\n  public:\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;\n    typename HandleTraits<Handle>::ReferenceToDouble stepsize;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap coef;\n\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap X_transp_AX;\n    typename HandleTraits<Handle>::ReferenceToDouble logLikelihood;\n    typename HandleTraits<Handle>::ReferenceToUInt16 status;\n};\n\nAnyType\nlogregr_igd_step_transition::run(AnyType &args) {\n    LogRegrIGDTransitionState<MutableArrayHandle<double> > state = args[0];\n    if (args[1].isNull() || args[2].isNull()) { return args[0]; }\n    double y = args[1].getAs<bool>() ? 1. : -1.;\n    MappedColumnVector x;\n    try {\n        // an exception is raised in the backend if args[2] contains nulls\n        MappedColumnVector xx = args[2].getAs<MappedColumnVector>();\n        // x is a const reference, we can only rebind to change its pointer\n        x.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    // The following check was added with MADLIB-138.\n    if (!x.is_finite()){\n        //throw std::domain_error(\"Design matrix is not finite.\");\n        warning(\"Design matrix is not finite.\");\n        state.status = TERMINATED;\n        return state;\n    }\n\n    // We only know the number of independent variables after seeing the first\n    // row.\n    if (state.numRows == 0) {\n        if (x.size() > std::numeric_limits<uint16_t>::max()){\n            //throw std::domain_error(\n            //    \"Number of independent variables cannot be larger than 65535.\");\n            warning(\"Number of independent variables cannot be larger than 65535.\");\n            state.status = TERMINATED;\n            return state;\n        }\n\n        state.initialize(*this, static_cast<uint16_t>(x.size()));\n\n        // For the first iteration, the previous state is NULL\n        if (!args[3].isNull()) {\n            LogRegrIGDTransitionState<ArrayHandle<double> > previousState = args[3];\n            state = previousState;\n            state.reset();\n        }\n    }\n\n    // Now do the transition step\n    state.numRows++;\n\n    // xc = x^T_i c\n    double xc = dot(x, state.coef);\n    double scale = state.stepsize * sigma(-xc * y) * y;\n    state.coef += scale * x;\n\n    // Note: previous coefficients are used for Hessian and log likelihood\n    if (!args[3].isNull()) {\n        LogRegrIGDTransitionState<ArrayHandle<double> > previousState = args[3];\n\n        double previous_xc = dot(x, previousState.coef);\n\n        // a_i = sigma(x_i c) sigma(-x_i c)\n        double a = sigma(previous_xc) * sigma(-previous_xc);\n        //triangularView<Lower>(state.X_transp_AX) += x * trans(x) * a;\n        state.X_transp_AX += x * trans(x) * a;\n\n        // l_i(c) = - ln(1 + exp(-y_i * c^T x_i))\n        state.logLikelihood -= std::log( 1. + std::exp(-y * previous_xc) );\n    }\n\n    return state;\n}\n\n/**\n * @brief Perform the perliminary aggregation function: Merge transition states\n */\nAnyType\nlogregr_igd_step_merge_states::run(AnyType &args) {\n    LogRegrIGDTransitionState<MutableArrayHandle<double> > stateLeft = args[0];\n    LogRegrIGDTransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    // We first handle the trivial case where this function is called with one\n    // of the states being the initial state\n    if (stateLeft.numRows == 0)\n        return stateRight;\n    else if (stateRight.numRows == 0)\n        return stateLeft;\n\n    // Merge states together and return\n    stateLeft += stateRight;\n    return stateLeft;\n}\n\n/**\n * @brief Perform the logistic-regression final step\n *\n * All that we do here is to test whether we have seen any data. If not, we\n * return NULL. Otherwise, we return the transition state unaltered.\n */\nAnyType\nlogregr_igd_step_final::run(AnyType &args) {\n    LogRegrIGDTransitionState<MutableArrayHandle<double> > state = args[0];\n\n    if(!state.coef.is_finite()){\n        //throw NoSolutionFoundException(\n        //    \"Overflow or underflow in incremental-gradient iteration. Input \"\n        //    \"data is likely of poor numerical condition.\");\n        warning(\"Overflow or underflow in incremental-gradient iteration. Input\"\n              \"data is likely of poor numerical condition.\");\n        state.status = TERMINATED;\n        return state;\n    }\n\n    // Aggregates that haven't seen any data just return Null.\n    if (state.numRows == 0){\n        state.status = NULL_EMPTY;\n        return state;\n    }\n\n    return state;\n}\n\n/**\n * @brief Return the difference in log-likelihood between two states\n */\nAnyType\ninternal_logregr_igd_step_distance::run(AnyType &args) {\n    LogRegrIGDTransitionState<ArrayHandle<double> > stateLeft = args[0];\n    LogRegrIGDTransitionState<ArrayHandle<double> > stateRight = args[1];\n\n    if(stateLeft.status == NULL_EMPTY || stateRight.status == NULL_EMPTY){\n        return 0.0;\n    }\n\n    return std::abs(stateLeft.logLikelihood - stateRight.logLikelihood);\n}\n\n/**\n * @brief Return the coefficients and diagnostic statistics of the state\n */\nAnyType\ninternal_logregr_igd_result::run(AnyType &args) {\n    LogRegrIGDTransitionState<ArrayHandle<double> > state = args[0];\n\n    if (state.status == NULL_EMPTY)\n        return Null();\n\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        state.X_transp_AX, EigenvaluesOnly, ComputePseudoInverse);\n\n    return stateToResult(*this, state.coef,\n                         state.X_transp_AX,\n                         state.logLikelihood,\n                         state.status, state.numRows);\n}\n\n/**\n * @brief Compute the diagnostic statistics\n *\n * This function wraps the common parts of computing the results for both the\n * CG and the IRLS method.\n */\nAnyType stateToResult(\n    const Allocator &inAllocator,\n    const HandleMap<const ColumnVector, TransparentHandle<double> > &inCoef,\n    const Matrix & hessian,\n    const double &logLikelihood,\n    int status,\n    const uint64_t &numRows) {\n\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        hessian, EigenvaluesOnly, ComputePseudoInverse);\n\n    const Matrix &inverse_of_X_transp_AX = decomposition.pseudoInverse();\n    const ColumnVector &diagonal_of_X_transp_AX = inverse_of_X_transp_AX.diagonal();\n\n    MutableNativeColumnVector stdErr(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector waldZStats(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector waldPValues(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector oddsRatios(\n        inAllocator.allocateArray<double>(inCoef.size()));\n\n    for (Index i = 0; i < inCoef.size(); ++i) {\n        stdErr(i) = std::sqrt(diagonal_of_X_transp_AX(i));\n        waldZStats(i) = inCoef(i) / stdErr(i);\n        waldPValues(i) = 2. * prob::cdf( prob::normal(),\n                                         -std::abs(waldZStats(i)));\n        oddsRatios(i) = std::exp( inCoef(i) );\n    }\n\n    // Return all coefficients, standard errors, etc. in a tuple\n    AnyType tuple;\n    tuple << inCoef << logLikelihood << stdErr << waldZStats << waldPValues\n          << oddsRatios << inverse_of_X_transp_AX\n          << sqrt(decomposition.conditionNo()) << status << numRows;\n    return tuple;\n}\n\n// ---------------------------------------------------------------------------\n//             Robust Logistic Regression States\n// ---------------------------------------------------------------------------\n/**\n * @brief Inter-and intra-iteration state for robust variance calculation for\n *        logistic regression\n *\n * TransitionState encapsualtes the transition state during the\n * logistic-regression aggregate function. To the database, the state is\n * exposed as a single DOUBLE PRECISION array, to the C++ code it is a proper\n * object containing scalars and vectors.\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length at least 5, and all elemenets are 0.\n *\n */\ntemplate <class Handle>\nclass RobustLogRegrTransitionState {\n    template <class OtherHandle>\n    friend class RobustLogRegrTransitionState;\n\n  public:\n    RobustLogRegrTransitionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n\n        rebind(static_cast<uint16_t>(mStorage[1]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the robust variance calculation state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(const Allocator &inAllocator, uint16_t inWidthOfX) {\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n                                             dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(inWidthOfX));\n        rebind(inWidthOfX);\n        widthOfX = inWidthOfX;\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle>\n    RobustLogRegrTransitionState &operator=(\n        const RobustLogRegrTransitionState<OtherHandle> &inOtherState) {\n\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object by copying the intra-iteration\n     *     fields\n     */\n    template <class OtherHandle>\n    RobustLogRegrTransitionState &operator+=(\n        const RobustLogRegrTransitionState<OtherHandle> &inOtherState) {\n\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            widthOfX != inOtherState.widthOfX)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                                   \"states\");\n\n        numRows += inOtherState.numRows;\n        X_transp_AX += inOtherState.X_transp_AX;\n        meat += inOtherState.meat;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        numRows = 0;\n        X_transp_AX.fill(0);\n        meat.fill(0);\n\n    }\n\n  private:\n    static inline size_t arraySize(const uint16_t inWidthOfX) {\n        return 4 + 2 * inWidthOfX * inWidthOfX + inWidthOfX;\n    }\n\n    /**\n     * @brief Rebind to a new storage array\n     *\n     * @param inWidthOfX The number of independent variables.\n     *\n     * Array layout (variables that are constant throughout function call):\n     * Inter-iteration components\n     * - 0: Iteration (What iteration is this)\n     * - 1: widthOfX (number of coefficients)\n     * - 2: coef (vector of coefficients)\n     *\n     * Intra-iteration components (variables that updated in transition step):\n     * - 2 + widthOfX: numRows (number of rows already processed in this iteration)\n     * - 3 + widthOfX: X_transp_AX (X^T A X)\n     * - 3 + widthOfX * widthOfX + widthOfX: meat (the meat matrix)\n     * - 3 + 2 * widthOfX * widthOfX + widthOfX: grad (intermediate value for gradient)\n     */\n    void rebind(uint16_t inWidthOfX) {\n        iteration.rebind(&mStorage[0]);\n        widthOfX.rebind(&mStorage[1]);\n        coef.rebind(&mStorage[2], inWidthOfX);\n        numRows.rebind(&mStorage[2 + inWidthOfX]);\n        X_transp_AX.rebind(&mStorage[3 + inWidthOfX], inWidthOfX, inWidthOfX);\n        meat.rebind(&mStorage[3 + inWidthOfX * inWidthOfX + inWidthOfX], inWidthOfX, inWidthOfX);\n    }\n\n    Handle mStorage;\n\n  public:\n    typename HandleTraits<Handle>::ReferenceToUInt32 iteration;\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap coef;\n\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap X_transp_AX;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap meat;\n};\n\n\n\n/**\n * @brief Helper function that computes the final statistics for the robust variance\n */\n\nAnyType robuststateToResult(\n    const Allocator &inAllocator,\n    const ColumnVector &inCoef,\n    const ColumnVector &diagonal_of_varianceMat) {\n\n    MutableNativeColumnVector variance(\n        inAllocator.allocateArray<double>(inCoef.size()));\n\n    MutableNativeColumnVector coef(\n        inAllocator.allocateArray<double>(inCoef.size()));\n\n    MutableNativeColumnVector stdErr(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector waldZStats(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector waldPValues(\n        inAllocator.allocateArray<double>(inCoef.size()));\n\n    for (Index i = 0; i < inCoef.size(); ++i) {\n        //variance(i) = diagonal_of_varianceMat(i);\n        coef(i) = inCoef(i);\n\n        stdErr(i) = std::sqrt(diagonal_of_varianceMat(i));\n        waldZStats(i) = inCoef(i) / stdErr(i);\n        waldPValues(i) = 2. * prob::cdf(\n            prob::normal(), -std::abs(waldZStats(i)));\n    }\n\n    // Return all coefficients, standard errors, etc. in a tuple\n    AnyType tuple;\n    //tuple <<  variance<<stdErr << waldZStats << waldPValues;\n    tuple <<  coef<<stdErr << waldZStats << waldPValues;\n    return tuple;\n}\n\n/**\n * @brief Perform the logistic-regression transition step\n */\nAnyType\nrobust_logregr_step_transition::run(AnyType &args) {\n    // Early return because of an exception has been \"thrown\"\n    // (actually \"warning\") in the previous invocations\n    if(args[0].isNull())\n        return Null();\n    RobustLogRegrTransitionState<MutableArrayHandle<double> > state = args[0];\n    if (args[1].isNull() || args[2].isNull()) { return args[0]; }\n    double y = args[1].getAs<bool>() ? 1. : -1.;\n    MappedColumnVector x;\n    try {\n        // an exception is raised in the backend if args[2] contains nulls\n        MappedColumnVector xx = args[2].getAs<MappedColumnVector>();\n        // x is a const reference, we can only rebind to change its pointer\n        x.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n    MappedColumnVector coef = args[3].getAs<MappedColumnVector>();\n\n    // The following check was added with MADLIB-138.\n    if (!dbal::eigen_integration::isfinite(x)) {\n        //throw std::domain_error(\"Design matrix is not finite.\");\n        warning(\"Design matrix is not finite.\");\n        return Null();\n    }\n\n    if (state.numRows == 0) {\n        if (x.size() > std::numeric_limits<uint16_t>::max()) {\n            //throw std::domain_error(\"Number of independent variables cannot be \"\n            //                        \"larger than 65535.\");\n            warning(\"Number of independent variables cannot be larger than 65535.\");\n            return Null();\n        }\n\n        state.initialize(*this, static_cast<uint16_t>(x.size()));\n        state.coef = coef; //Copy this into the state for later\n    }\n\n    // Now do the transition step\n    state.numRows++;\n    double xc = dot(x, coef);\n    ColumnVector Grad;\n    Grad = sigma(-y * xc) * y * trans(x);\n\n    Matrix GradGradTranspose;\n    GradGradTranspose = Grad*Grad.transpose();\n    state.meat += GradGradTranspose;\n\n    // Note: sigma(-x) = 1 - sigma(x).\n    // a_i = sigma(x_i c) sigma(-x_i c)\n    double a = sigma(xc) * sigma(-xc);\n    triangularView<Lower>(state.X_transp_AX) += x * trans(x) * a;\n    return state;\n}\n\n\n/**\n * @brief Perform the perliminary aggregation function: Merge transition states\n */\nAnyType\nrobust_logregr_step_merge_states::run(AnyType &args) {\n    // In case the aggregator should be terminated because\n    // an exception has been \"thrown\" in the transition function\n    if(args[0].isNull() || args[1].isNull())\n        return Null();\n\n    RobustLogRegrTransitionState<MutableArrayHandle<double> > stateLeft = args[0];\n    RobustLogRegrTransitionState<ArrayHandle<double> > stateRight = args[1];\n    // We first handle the trivial case where this function is called with one\n    // of the states being the initial state\n    if (stateLeft.numRows == 0)\n        return stateRight;\n    else if (stateRight.numRows == 0)\n        return stateLeft;\n\n    // Merge states together and return\n    stateLeft += stateRight;\n    return stateLeft;\n}\n\n/**\n * @brief Perform the robust variance calculation for logistic-regression final step\n */\nAnyType\nrobust_logregr_step_final::run(AnyType &args) {\n    // In case the aggregator should be terminated because\n    // an exception has been \"thrown\" in the transition function\n    if (args[0].isNull())\n        return Null();\n    // We request a mutable object. Depending on the backend, this might perform\n    // a deep copy.\n    RobustLogRegrTransitionState<MutableArrayHandle<double> > state = args[0];\n    // Aggregates that haven't seen any data just return Null.\n    if (state.numRows == 0)\n        return Null();\n\n    //Compute the robust variance with the White sandwich estimator\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        state.X_transp_AX, EigenvaluesOnly, ComputePseudoInverse);\n\n    Matrix bread = decomposition.pseudoInverse();\n\n    /*\n      This is written a little strangely because it prevents Eigen warnings.\n      The following two lines are equivalent to:\n      Matrix variance = bread*state.meat*bread;\n      but eigen throws a warning on that.\n    */\n    Matrix varianceMat;// = meat;\n    varianceMat = bread*state.meat*bread;\n\n    /*\n     * Computing the results for robust variance\n     */\n\n    return robuststateToResult(*this, state.coef,\n                               varianceMat.diagonal());\n}\n\n// ------------------------ End of Robust ------------------------------------\n\n\n\n\n// ---------------------------------------------------------------------------\n//             Marginal Effects Logistic Regression States\n// ---------------------------------------------------------------------------\n/**\n * @brief State for marginal effects calculation for logistic regression\n *\n * TransitionState encapsualtes the transition state during the\n * marginal effects calculation for the logistic-regression aggregate function.\n * To the database, the state is exposed as a single DOUBLE PRECISION array,\n * to the C++ code it is a proper object containing scalars and vectors.\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length at least 5, and all elemenets are 0.\n *\n */\ntemplate <class Handle>\nclass MarginalLogRegrTransitionState {\n    template <class OtherHandle>\n    friend class MarginalLogRegrTransitionState;\n\n  public:\n    MarginalLogRegrTransitionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n\n        rebind(static_cast<uint16_t>(mStorage[1]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the marginal variance calculation state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(const Allocator &inAllocator, uint16_t inWidthOfX) {\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n                                             dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(inWidthOfX));\n        rebind(inWidthOfX);\n        widthOfX = inWidthOfX;\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle>\n    MarginalLogRegrTransitionState &operator=(\n        const MarginalLogRegrTransitionState<OtherHandle> &inOtherState) {\n\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object by copying the intra-iteration\n     *     fields\n     */\n    template <class OtherHandle>\n    MarginalLogRegrTransitionState &operator+=(\n        const MarginalLogRegrTransitionState<OtherHandle> &inOtherState) {\n\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            widthOfX != inOtherState.widthOfX)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                                   \"states\");\n\n        numRows += inOtherState.numRows;\n        marginal_effects_per_observation += inOtherState.marginal_effects_per_observation;\n        X_bar += inOtherState.X_bar;\n        X_transp_AX += inOtherState.X_transp_AX;\n        delta += inOtherState.delta;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        numRows = 0;\n        marginal_effects_per_observation = 0;\n        X_bar.fill(0);\n        X_transp_AX.fill(0);\n        delta.fill(0);\n    }\n\n  private:\n    static inline size_t arraySize(const uint16_t inWidthOfX) {\n        return 4 + 2 * inWidthOfX * inWidthOfX + 2 * inWidthOfX;\n    }\n\n    /**\n     * @brief Rebind to a new storage array\n     *\n     * @param inWidthOfX The number of independent variables.\n     *\n     * Array layout (variables that are constant throughout function call):\n     * Inter-iteration components\n     * - 0: Iteration (What iteration is this)\n     * - 1: widthOfX (number of coefficients)\n     * - 2: coef (vector of coefficients)\n     *\n     * Intra-iteration components (variables that updated in transition step):\n     * - 2 + widthOfX: numRows (number of rows already processed in this iteration)\n     * - 3 + widthOfX: X_transp_AX (X^T A X)\n     */\n    void rebind(uint16_t inWidthOfX) {\n        iteration.rebind(&mStorage[0]);\n        widthOfX.rebind(&mStorage[1]);\n        coef.rebind(&mStorage[2], inWidthOfX);\n        numRows.rebind(&mStorage[2 + inWidthOfX]);\n        marginal_effects_per_observation.rebind(&mStorage[3 + inWidthOfX]);\n        X_bar.rebind(&mStorage[4 + inWidthOfX], inWidthOfX);\n        X_transp_AX.rebind(&mStorage[4 + 2*inWidthOfX], inWidthOfX, inWidthOfX);\n        delta.rebind(&mStorage[4+inWidthOfX*inWidthOfX+2*inWidthOfX], inWidthOfX, inWidthOfX);\n    }\n    Handle mStorage;\n\n  public:\n\n    typename HandleTraits<Handle>::ReferenceToUInt32 iteration;\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap coef;\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::ReferenceToDouble marginal_effects_per_observation;\n\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap X_bar;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap X_transp_AX;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap delta;\n};\n\n// ----------------------------------------------------------------------\n\n/**\n * @brief Helper function that computes the final statistics for the marginal variance\n */\n\nAnyType marginalstateToResult(\n    const Allocator &inAllocator,\n    const ColumnVector &inCoef,\n    const ColumnVector &diagonal_of_variance_matrix,\n    const double inmarginal_effects_per_observation,\n    const Index numRows) {\n\n    MutableNativeColumnVector marginal_effects(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector coef(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector stdErr(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector tStats(\n        inAllocator.allocateArray<double>(inCoef.size()));\n    MutableNativeColumnVector pValues(\n        inAllocator.allocateArray<double>(inCoef.size()));\n\n    for (Index i = 0; i < inCoef.size(); ++i) {\n        coef(i) = inCoef(i);\n        marginal_effects(i) = inCoef(i) * inmarginal_effects_per_observation / static_cast<double>(numRows);\n        stdErr(i) = std::sqrt(diagonal_of_variance_matrix(i));\n        tStats(i) = marginal_effects(i) / stdErr(i);\n\n        // P-values only make sense if numRows > coef.size()\n        if (numRows > inCoef.size())\n            pValues(i) = 2. * prob::cdf(\n                prob::normal(), -std::abs(tStats(i)));\n    }\n\n    // Return all coefficients, standard errors, etc. in a tuple\n    // Note: PValues will return NULL if numRows <= coef.size\n    AnyType tuple;\n    tuple << marginal_effects\n          << coef\n          << stdErr\n          << tStats\n          << (numRows > inCoef.size()? pValues: Null());\n    return tuple;\n}\n\n\n/**\n * @brief Perform the marginal effects transition step\n */\nAnyType\nmarginal_logregr_step_transition::run(AnyType &args) {\n    // Early return because of an exception has been \"thrown\"\n    // (actually \"warning\") in the previous invocations\n    if (args[0].isNull())\n        return Null();\n    MarginalLogRegrTransitionState<MutableArrayHandle<double> > state = args[0];\n    if (args[1].isNull() || args[2].isNull()) { return args[0]; }\n    MappedColumnVector x;\n    try {\n        // an exception is raised in the backend if args[2] contains nulls\n        MappedColumnVector xx = args[2].getAs<MappedColumnVector>();\n        // x is a const reference, we can only rebind to change its pointer\n        x.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    MappedColumnVector coef = args[3].getAs<MappedColumnVector>();\n\n    // The following check was added with MADLIB-138.\n    if (!dbal::eigen_integration::isfinite(x)) {\n        //throw std::domain_error(\"Design matrix is not finite.\");\n        warning(\"Design matrix is not finite.\");\n        return Null();\n    }\n\n    if (state.numRows == 0) {\n        if (x.size() > std::numeric_limits<uint16_t>::max()) {\n            //throw std::domain_error(\"Number of independent variables cannot be \"\n            //                        \"larger than 65535.\");\n            warning(\"Number of independent variables cannot be larger than 65535.\");\n            return Null();\n        }\n        state.initialize(*this, static_cast<uint16_t>(x.size()));\n        state.coef = coef; //Copy this into the state for later\n    }\n\n    // Now do the transition step\n    state.numRows++;\n    double xc = dot(x, coef);\n    double p = std::exp(xc)/ (1 + std::exp(xc));\n    double a = sigma(xc) * sigma(-xc);\n\n    // TODO: Change the average code so it won't overflow\n    state.marginal_effects_per_observation += p * (1 - p);\n    state.X_bar += x;\n    state.X_transp_AX += x * trans(x) * a;\n\n    Matrix delta;\n    delta = (1 - 2*p) * state.coef * trans(x);\n    // This should be faster than adding an identity\n    for (int i=0; i < state.widthOfX; i++){\n        delta(i,i) += 1;\n    }\n\n    // Standard error according to the delta method\n    state.delta += p * (1 - p) * delta;\n\n    return state;\n}\n\n\n/**\n * @brief Marginal effects: Merge transition states\n */\nAnyType\nmarginal_logregr_step_merge_states::run(AnyType &args) {\n    // In case the aggregator should be terminated because\n    // an exception has been \"thrown\" in the transition function\n    if(args[0].isNull() || args[1].isNull())\n        return Null();\n\n    MarginalLogRegrTransitionState<MutableArrayHandle<double> > stateLeft = args[0];\n    MarginalLogRegrTransitionState<ArrayHandle<double> > stateRight = args[1];\n    // We first handle the trivial case where this function is called with one\n    // of the states being the initial state\n    if (stateLeft.numRows == 0)\n        return stateRight;\n    else if (stateRight.numRows == 0)\n        return stateLeft;\n\n    // Merge states together and return\n    stateLeft += stateRight;\n    return stateLeft;\n}\n\n/**\n * @brief Marginal effects: Final step\n */\nAnyType\nmarginal_logregr_step_final::run(AnyType &args) {\n    // In case the aggregator should be terminated because\n    // an exception has been \"thrown\" in the transition function\n    if (args[0].isNull())\n        return Null();\n\n    // We request a mutable object.\n    // Depending on the backend, this might perform a deep copy.\n    MarginalLogRegrTransitionState<MutableArrayHandle<double> > state = args[0];\n    // Aggregates that haven't seen any data just return Null.\n    if (state.numRows == 0)\n        return Null();\n\n    // Compute variance matrix of logistic regression\n    SymmetricPositiveDefiniteEigenDecomposition<Matrix> decomposition(\n        state.X_transp_AX, EigenvaluesOnly, ComputePseudoInverse);\n    Matrix variance = decomposition.pseudoInverse();\n    // Standard error according to the delta method\n    Matrix std_err;\n    std_err = state.delta * variance * trans(state.delta) / static_cast<double>(state.numRows*state.numRows);\n\n    // Computing the marginal effects\n    return marginalstateToResult(*this,\n                                 state.coef,\n                                 std_err.diagonal(),\n                                 state.marginal_effects_per_observation,\n                                 state.numRows);\n}\n\n// ------------------------ End of Marginal ------------------------------------\n\nAnyType logregr_predict::run(AnyType &args) {\n    try {\n        args[0].getAs<MappedColumnVector>();\n    } catch (const ArrayWithNullException &e) {\n        throw std::runtime_error(\n            \"Logregr error: the coefficients contain NULL values\");\n    }\n\n    // returns NULL if args[1] (features) contains NULL values\n    try {\n        args[1].getAs<MappedColumnVector>();\n    } catch (const ArrayWithNullException &e) {\n        return Null();\n    }\n\n    MappedColumnVector vec1 = args[0].getAs<MappedColumnVector>();\n    MappedColumnVector vec2 = args[1].getAs<MappedColumnVector>();\n\n    if (vec1.size() != vec2.size())\n        throw std::runtime_error(\n            \"Coefficients and independent variables are of incompatible length\");\n\n    return vec1.dot(vec2) > 0 ? true : false;\n}\n\nAnyType logregr_predict_prob::run(AnyType &args) {\n    try {\n        args[0].getAs<MappedColumnVector>();\n    } catch (const ArrayWithNullException &e) {\n        throw std::runtime_error(\n            \"Logregr error: the coefficients contain NULL values\");\n    }\n\n    // returns NULL if args[1] (features) contains NULL values\n    try {\n        args[1].getAs<MappedColumnVector>();\n    } catch (const ArrayWithNullException &e) {\n        return Null();\n    }\n\n    MappedColumnVector vec1 = args[0].getAs<MappedColumnVector>();\n    MappedColumnVector vec2 = args[1].getAs<MappedColumnVector>();\n\n    if (vec1.size() != vec2.size())\n        throw std::runtime_error(\n            \"Coefficients and independent variables are of incompatible length\");\n\n    double dot = vec1.dot(vec2);\n    double logit = 0.0;\n    // Underflow/overfolow handling\n    try {\n        logit = 1.0 / (1 + exp(-dot));\n    } catch (...) {\n        logit = (dot > 0) ? 1.0 : 0.0;\n    }\n    return logit;\n}\n\n} // namespace regress\n} // namespace modules\n} // namespace madlib\n", "meta": {"hexsha": "31007ef566a6c5bc0e7efbe9c08e1bb92617523d", "size": 60953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/regress/logistic.cpp", "max_stars_repo_name": "iyerr3/madlib", "max_stars_repo_head_hexsha": "ab7166ff4fc55311ec29bb8b54d17becd9bb1750", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/modules/regress/logistic.cpp", "max_issues_repo_name": "iyerr3/madlib", "max_issues_repo_head_hexsha": "ab7166ff4fc55311ec29bb8b54d17becd9bb1750", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/modules/regress/logistic.cpp", "max_forks_repo_name": "iyerr3/madlib", "max_forks_repo_head_hexsha": "ab7166ff4fc55311ec29bb8b54d17becd9bb1750", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9902411022, "max_line_length": 109, "alphanum_fraction": 0.6387708562, "num_tokens": 14958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.43714723332995475}}
{"text": "/*\n * (C) Copyright 1996- ECMWF.\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n * In applying this licence, ECMWF does not waive the privileges and immunities\n * granted to it by virtue of its status as an intergovernmental organisation\n * nor does it submit to any jurisdiction.\n */\n\n//----------------------------------------------------------------------------------------------------------------------\n\n#include \"eckit/eckit.h\"\n\n#ifdef eckit_HAVE_ARMADILLO\n\n#include \"eckit/linalg/LinearAlgebraArmadillo.h\"\n\n#include <armadillo>\n\n#include \"eckit/exception/Exceptions.h\"\n#include \"eckit/linalg/Matrix.h\"\n#include \"eckit/linalg/Vector.h\"\n\n//----------------------------------------------------------------------------------------------------------------------\n\nnamespace eckit {\nnamespace linalg {\n\n//----------------------------------------------------------------------------------------------------------------------\n\nLinearAlgebraArmadillo::LinearAlgebraArmadillo() :\n    LinearAlgebra(\"armadillo\") {}\n\n//----------------------------------------------------------------------------------------------------------------------\n\nvoid LinearAlgebraArmadillo::print(std::ostream& out) const {\n    out << \"LinearAlgebraArmadillo[]\";\n}\n\n//----------------------------------------------------------------------------------------------------------------------\n\nScalar LinearAlgebraArmadillo::dot(const Vector& x, const Vector& y) const {\n    ASSERT(x.size() == y.size());\n    // Armadillo requires non-const pointers to the data for views without copy\n    arma::vec xi(const_cast<Scalar*>(x.data()), x.size(), /* copy_aux_mem= */ false);\n    arma::vec yi(const_cast<Scalar*>(y.data()), y.size(), /* copy_aux_mem= */ false);\n    return arma::dot(xi, yi);\n}\n\n//----------------------------------------------------------------------------------------------------------------------\n\nvoid LinearAlgebraArmadillo::gemv(const Matrix& A, const Vector& x, Vector& y) const {\n    ASSERT(x.size() == A.cols() && y.size() == A.rows());\n    // Armadillo requires non-const pointers to the data for views without copy\n    arma::mat Ai(const_cast<Scalar*>(A.data()), A.rows(), A.cols(), /* copy_aux_mem= */ false);\n    arma::vec xi(const_cast<Scalar*>(x.data()), x.size(), /* copy_aux_mem= */ false);\n    arma::vec yi(y.data(), y.size(), /* copy_aux_mem= */ false);\n    yi = Ai * xi;\n}\n\n//----------------------------------------------------------------------------------------------------------------------\n\nvoid LinearAlgebraArmadillo::gemm(const Matrix& A, const Matrix& B, Matrix& C) const {\n    ASSERT(A.cols() == B.rows() && A.rows() == C.rows() && B.cols() == C.cols());\n    // Armadillo requires non-const pointers to the data for views without copy\n    arma::mat Ai(const_cast<Scalar*>(A.data()), A.rows(), A.cols(), /* copy_aux_mem= */ false);\n    arma::mat Bi(const_cast<Scalar*>(B.data()), B.rows(), B.cols(), /* copy_aux_mem= */ false);\n    arma::mat Ci(C.data(), C.rows(), C.cols(), /* copy_aux_mem= */ false);\n    Ci = Ai * Bi;\n}\n\n//----------------------------------------------------------------------------------------------------------------------\n\nvoid LinearAlgebraArmadillo::spmv(const SparseMatrix& A, const Vector& x, Vector& y) const {\n    // FIXME: Armadillo stores matrices in CSC format and does not provide\n    // constructors from existing storage. A sparse matrix would have to be\n    // copied from CSR to CSC format, which is probably not worth the cost\n    LinearAlgebra::getBackend(\"generic\").spmv(A, x, y);\n}\n\n//----------------------------------------------------------------------------------------------------------------------\n\nvoid LinearAlgebraArmadillo::spmm(const SparseMatrix& A, const Matrix& B, Matrix& C) const {\n    // FIXME: Armadillo stores matrices in CSC format and does not provide\n    // constructors from existing storage. A sparse matrix would have to be\n    // copied from CSR to CSC format, which is probably not worth the cost\n    LinearAlgebra::getBackend(\"generic\").spmm(A, B, C);\n}\n\n//----------------------------------------------------------------------------------------------------------------------\n\nvoid LinearAlgebraArmadillo::dsptd(const Vector& x, const SparseMatrix& A, const Vector& y, SparseMatrix& B) const {\n    LinearAlgebra::getBackend(\"generic\").dsptd(x, A, y, B);\n}\n\n//----------------------------------------------------------------------------------------------------------------------\n\nstatic LinearAlgebraArmadillo LinearAlgebraArmadillo;\n\n//----------------------------------------------------------------------------------------------------------------------\n\n}  // namespace linalg\n}  // namespace eckit\n\n#endif  // eckit_HAVE_ARMDILLO\n", "meta": {"hexsha": "449b909ef7a96cc17089cc9231424af9f236a6f0", "size": 4813, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/eckit/linalg/LinearAlgebraArmadillo.cc", "max_stars_repo_name": "dvuckovic/eckit", "max_stars_repo_head_hexsha": "58a918e7be8fe073f37683abf639374ab1ad3e4f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-01T22:11:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T14:13:58.000Z", "max_issues_repo_path": "src/eckit/linalg/LinearAlgebraArmadillo.cc", "max_issues_repo_name": "dvuckovic/eckit", "max_issues_repo_head_hexsha": "58a918e7be8fe073f37683abf639374ab1ad3e4f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2018-04-11T11:13:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:28:03.000Z", "max_forks_repo_path": "src/eckit/linalg/LinearAlgebraArmadillo.cc", "max_forks_repo_name": "dvuckovic/eckit", "max_forks_repo_head_hexsha": "58a918e7be8fe073f37683abf639374ab1ad3e4f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-03-07T21:36:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T13:25:25.000Z", "avg_line_length": 44.9813084112, "max_line_length": 120, "alphanum_fraction": 0.4809889882, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4369815894528669}}
{"text": "#include <boost/math/special_functions/next.hpp>\n#include <boost/random.hpp>\n\n#include <limits>\n\n#include \"caffe/common.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/rng.hpp\"\n\nnamespace caffe {\n\n\nvoid caffe_cpu_gemm(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,\n    const float alpha, const float* A, const float* B, const float beta,\n    float* C) {\n  int lda = (TransA == CblasNoTrans) ? K : M;\n  int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_sgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B,\n      ldb, beta, C, N);\n}\n\n\n\nvoid caffe_cpu_gemv(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const float alpha, const float* A, const float* x,\n    const float beta, float* y) {\n  cblas_sgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\n\nvoid caffe_axpy(const int N, const float alpha, const float* X,\n    float* Y) { cblas_saxpy(N, alpha, X, 1, Y, 1); }\n\n\n\nvoid caffe_set(const int N, const float alpha, float* Y) {\n  if (alpha == 0) {\n    memset(Y, 0, sizeof(float) * N);  // NOLINT(caffe/alt_fn)\n    return;\n  }\n  for (int i = 0; i < N; ++i) {\n    Y[i] = alpha;\n  }\n}\n\nvoid caffe_add_scalar(const int N, const float alpha, float* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\nvoid caffe_copy(const int N, const float* X, float* Y) {\n\tif (X != Y)\n\t{\n\t\t//CUDA_CHECK(cudaMemcpy(Y, X, sizeof(float) * N, cudaMemcpyDefault));\n\t\tcaffe_gpu_memcpy(sizeof(float) * N,X,Y);\n  }\n}\n\nvoid caffe_scal(const int N, const float alpha, float *X) {\n  cblas_sscal(N, alpha, X, 1);\n}\n\nvoid caffe_cpu_axpby(const int N, const float alpha, const float* X,\n                            const float beta, float* Y) {\n  cblas_saxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\n\nvoid caffe_add(const int n, const float* a, const float* b,\n    float* y) {\n  vsAdd(n, a, b, y);\n}\n\nvoid caffe_sub(const int n, const float* a, const float* b,\n    float* y) {\n  vsSub(n, a, b, y);\n}\n\nvoid caffe_mul(const int n, const float* a, const float* b,\n    float* y) {\n  vsMul(n, a, b, y);\n}\n\nvoid caffe_div(const int n, const float* a, const float* b,\n    float* y) {\n  vsDiv(n, a, b, y);\n}\n\nvoid caffe_powx(const int n, const float* a, const float b,\n    float* y) {\n  vsPowx(n, a, b, y);\n}\n\nvoid caffe_sqr(const int n, const float* a, float* y) {\n  vsSqr(n, a, y);\n}\n\n\nvoid caffe_exp(const int n, const float* a, float* y) {\n  vsExp(n, a, y);\n}\n\nvoid caffe_log(const int n, const float* a, float* y) {\n  vsLn(n, a, y);\n}\n\nvoid caffe_abs(const int n, const float* a, float* y) {\n    vsAbs(n, a, y);\n}\n\nint caffe_rng_rand() {\n  int rand_num = (*Caffe::rng())();\n  return int(abs(rand_num));\n}\n\n\nfloat caffe_nextafter(const float b) {\n  return boost::math::nextafter<float>(\n      b, std::numeric_limits<float>::max());\n}\n\n\n\n\nvoid caffe_rng_uniform(const int n, const float a, const float b, float* r) {\n\tCHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_LE(a, b);\n  boost::uniform_real<float > random_distribution(a, caffe_nextafter(b));\n  boost::variate_generator<caffe::rng_t*, boost::uniform_real<float > >\n      variate_generator(Caffe::rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\n\n\nvoid caffe_rng_gaussian(const int n, const float a, const float sigma, float* r) \n{\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GT(sigma, 0);\n  boost::normal_distribution<float > random_distribution(a, sigma);\n  boost::variate_generator<caffe::rng_t*, boost::normal_distribution<float > >\n      variate_generator(Caffe::rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\n\n\n\nvoid caffe_rng_bernoulli(const int n, const float p, int* r) \n{\n\tCHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n  boost::bernoulli_distribution<float > random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<float > >\n      variate_generator(Caffe::rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = static_cast<unsigned int>(variate_generator());\n  }\n}\n\n\nvoid caffe_rng_bernoulli(const int n, const float p, unsigned int* r) {\n//TODO\nNOT_IMPLEMENTED;\n}\n\n\n\n\nfloat caffe_cpu_strided_dot(const int n, const float* x, const int incx,\n    const float* y, const int incy) {\n  return cblas_sdot(n, x, incx, y, incy);\n}\n\n\nfloat caffe_cpu_dot(const int n, const float* x, const float* y) {\n  return caffe_cpu_strided_dot(n, x, 1, y, 1);\n}\n\n\n\n\n\nfloat caffe_cpu_asum(const int n, const float* x) {\n  return cblas_sasum(n, x, 1);\n}\n\n\nvoid caffe_cpu_scale(const int n, const float alpha, const float *x,\n                            float* y) {\n  cblas_scopy(n, x, 1, y, 1);\n  cblas_sscal(n, alpha, y, 1);\n}\n\n\n\n}  // namespace caffe\n", "meta": {"hexsha": "ed549a44a0705c4c6cef519b50753fea01ef34d3", "size": 4740, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_functions.cpp", "max_stars_repo_name": "JEF1056/MetaLearning-Neural-Style", "max_stars_repo_head_hexsha": "94ac33cb6a62c4de8ff2aeac3572afd61f1bda5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 126.0, "max_stars_repo_stars_event_min_datetime": "2017-09-14T01:53:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-24T08:57:41.000Z", "max_issues_repo_path": "src/caffe/util/math_functions.cpp", "max_issues_repo_name": "hli1221/styletransfer", "max_issues_repo_head_hexsha": "5101f2c024638d3e111644c64398b3290fdeaec6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2017-09-14T09:11:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-27T08:56:52.000Z", "max_forks_repo_path": "src/caffe/util/math_functions.cpp", "max_forks_repo_name": "hli1221/styletransfer", "max_forks_repo_head_hexsha": "5101f2c024638d3e111644c64398b3290fdeaec6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2017-09-14T09:14:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-16T09:49:40.000Z", "avg_line_length": 22.7884615385, "max_line_length": 81, "alphanum_fraction": 0.6417721519, "num_tokens": 1493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.43698158945286686}}
{"text": "#include \"SDOT/SemiDiscreteOT.h\"\n\n\n#include \"SDOT/Assert.h\"\n#include \"SDOT/Distances/Distances.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SparseCholesky>\n#include <Eigen/Dense>\n\n#include <CGAL/Kernel/global_functions.h>\n\n#include <algorithm>\n#include <chrono>\n\nusing namespace sdot;\n\ntemplate<typename ConjugateFunctionType>\nSemidiscreteOT<ConjugateFunctionType>::SemidiscreteOT(std::shared_ptr<Distribution2d> const& distIn,\n                               Eigen::Matrix2Xd                const& discrPtsIn,\n                               Eigen::VectorXd                 const& discrProbsIn,\n                               double                                 unbalancedPenaltyIn) : dist(distIn),\n                                                                                      grid(distIn->Grid()),\n                                                                                      discrPts(discrPtsIn),\n                                                                                      discrProbs(discrProbsIn),\n                                                                                      unbalancedPenalty(unbalancedPenaltyIn)\n{\n  if(discrPtsIn.cols()!=discrProbsIn.size())\n  SDOT_ASSERT(discrPtsIn.cols()==discrProbsIn.size());\n\n  SDOT_ASSERT(unbalancedPenalty>0);\n\n  CheckNormalization();\n\n  // Check to make sure all the points are inside the grid domain\n  for(unsigned int i=0; i<discrPts.cols(); ++i){\n    SDOT_ASSERT(discrPts(0,i)>=grid->xMin);\n    SDOT_ASSERT(discrPts(0,i)<=grid->xMax);\n    SDOT_ASSERT(discrPts(1,i)>=grid->yMin);\n    SDOT_ASSERT(discrPts(1,i)<=grid->yMax);\n  }\n}\n\n\ntemplate<>\nvoid SemidiscreteOT<sdot::distances::Wasserstein2>::CheckNormalization()\n{\n  double discrSum = discrProbs.sum();\n  double contSum= dist->TotalMass();\n  SDOT_ASSERT(std::abs(discrSum-contSum)<1e-5);\n}\n\ntemplate<typename ConjugateFunctionType>\nvoid SemidiscreteOT<ConjugateFunctionType>::SetPoints(Eigen::Matrix2Xd const& newPts){\n  SDOT_ASSERT(newPts.cols()==discrProbs.size());\n\n  // Check to make sure all the points are inside the grid domain\n  for(unsigned int i=0; i<newPts.cols(); ++i){\n    SDOT_ASSERT(newPts(0,i)>=grid->xMin);\n    SDOT_ASSERT(newPts(0,i)<=grid->xMax);\n    SDOT_ASSERT(newPts(1,i)>=grid->yMin);\n    SDOT_ASSERT(newPts(1,i)<=grid->yMax);\n  }\n\n  discrPts = newPts;\n}\n\ntemplate<typename ConjugateFunctionType>\nstd::tuple<double,Eigen::VectorXd, Eigen::SparseMatrix<double>> SemidiscreteOT<ConjugateFunctionType>::Objective(Eigen::VectorXd const& prices) const\n{\n    // Notes:\n    //   - The cost c(x,y) is the squared distance between x and y\n    //   - See (17) of https://arxiv.org/pdf/1710.02634.pdf\n\n    const int numCells = discrPts.cols();\n    SDOT_ASSERT(numCells==prices.size());\n\n    // Construct the Laguerre diagram\n    LaguerreDiagram lagDiag(grid->xMin, grid->xMax, grid->yMin, grid->yMax, discrPts, prices);\n\n    double obj;\n    Eigen::VectorXd grad;\n    Eigen::SparseMatrix<double> hess;\n\n    std::tie(obj,grad) = ComputeGradient(prices, lagDiag);\n    hess = ComputeHessian(prices, lagDiag);\n\n    return std::make_tuple(obj,grad,hess);\n}\n\ntemplate<typename ConjugateFunctionType>\nEigen::Matrix2Xd SemidiscreteOT<ConjugateFunctionType>::PointGradient() const\n{\n  return PointGradient(optPrices, *lagDiag);\n}\n\ntemplate<typename ConjugateFunctionType>\nEigen::Matrix2Xd SemidiscreteOT<ConjugateFunctionType>::PointGradient(Eigen::VectorXd const& prices,\n                                                                      LaguerreDiagram const& lagDiag) const\n{\n  int numCells =  lagDiag.NumCells();\n  Eigen::Matrix2Xd grad(2,numCells);\n\n  // Loop over all ofthe cells\n  for(int i=0; i<numCells; ++i){\n\n    auto triFunc = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2, Eigen::Vector2d const& pt3)\n      {\n        return ConjugateFunctionType::TriangularIntegralPointGrad(prices(i), discrPts.col(i), pt1,pt2,pt3,unbalancedPenalty);\n      };\n    auto rectFunc = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2)\n      {\n        return ConjugateFunctionType::RectangularIntegralPointGrad(prices(i), discrPts.col(i), pt1,pt2,unbalancedPenalty);\n      };\n\n    grad.col(i) = lagDiag.IntegrateOverCell(i, triFunc, rectFunc, dist);\n  }\n\n  return grad;\n}\n\ntemplate<typename ConjugateFunctionType>\nEigen::Matrix2Xd SemidiscreteOT<ConjugateFunctionType>::LloydPointHessian() const\n{\n  return LloydPointHessian(optPrices, *lagDiag);\n}\n\ntemplate<typename ConjugateFunctionType>\nEigen::Matrix2Xd SemidiscreteOT<ConjugateFunctionType>::LloydPointHessian(Eigen::VectorXd const& prices,\n                                                                         LaguerreDiagram const& lagDiag) const\n{\n  const unsigned int numCells = discrPts.cols();\n  Eigen::Matrix2Xd hessVals(2,numCells);\n  Eigen::Matrix2d intVal(2,2);\n\n  // For unbalanced transport, the Diagonal of the hessian has an additional term\n  for(unsigned int cellInd=0; cellInd<numCells; ++cellInd) {\n\n    auto triFunc = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2, Eigen::Vector2d const& pt3)\n      {\n        return ConjugateFunctionType::TriangularIntegralPointHessDiag(prices(cellInd), discrPts.col(cellInd), pt1,pt2,pt3, unbalancedPenalty);\n      };\n    auto rectFunc = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2)\n      {\n        return ConjugateFunctionType::RectangularIntegralPointHessDiag(prices(cellInd), discrPts.col(cellInd), pt1,pt2, unbalancedPenalty);\n      };\n\n    intVal = -1.0*lagDiag.IntegrateOverCell(cellInd, triFunc, rectFunc, dist);\n    hessVals(0,cellInd)   =  intVal(0,0);\n    hessVals(1,cellInd)   =  intVal(1,1);\n  }\n\n  return hessVals;\n}\n\n\ntemplate<typename ConjugateFunctionType>\nEigen::SparseMatrix<double> SemidiscreteOT<ConjugateFunctionType>::PointHessian(Eigen::VectorXd const& prices,\n                                                                                LaguerreDiagram const& lagDiag) const\n{\n  const unsigned int numCells = discrPts.cols();\n  typedef Eigen::Triplet<double> T;\n  std::vector<T> hessVals;\n\n  Eigen::VectorXd diagVals = Eigen::VectorXd::Zero(2*numCells);\n  Eigen::Matrix2d intVal;\n\n  // For unbalanced transport, the Diagonal of the hessian has an additional term\n  for(unsigned int cellInd=0; cellInd<numCells; ++cellInd) {\n\n    auto triFunc = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2, Eigen::Vector2d const& pt3)\n      {\n        return ConjugateFunctionType::TriangularIntegralPointHessDiag(prices(cellInd), discrPts.col(cellInd), pt1,pt2,pt3, unbalancedPenalty);\n      };\n    auto rectFunc = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2)\n      {\n        return ConjugateFunctionType::RectangularIntegralPointHessDiag(prices(cellInd), discrPts.col(cellInd), pt1,pt2, unbalancedPenalty);\n      };\n\n    intVal = -1.0*lagDiag.IntegrateOverCell(cellInd, triFunc, rectFunc, dist);\n    hessVals.push_back(T(2*cellInd,2*cellInd,intVal(0,0)));\n    hessVals.push_back(T(2*cellInd,2*cellInd+1,intVal(0,1)));\n    hessVals.push_back(T(2*cellInd+1,2*cellInd,intVal(1,0)));\n    hessVals.push_back(T(2*cellInd+1,2*cellInd+1,intVal(1,1)));\n  }\n\n\n  ///////\n  // Off-diagonal parts\n\n  unsigned int cellInd2;\n  LaguerreDiagram::Point_2 srcPt, tgtPt;\n\n  for(unsigned int cellInd1=0; cellInd1<numCells; ++cellInd1){\n\n    for(auto edgeTuple : lagDiag.InternalEdges(cellInd1)){\n      std::tie(cellInd2, srcPt, tgtPt) = edgeTuple;\n\n      // Compute the integral of the target density along the edge\n      auto func = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2)\n      {\n        return ConjugateFunctionType::LineIntegralPointHess(prices(cellInd1), discrPts.col(cellInd1), discrPts.col(cellInd2), pt1, pt2, unbalancedPenalty);\n      };\n      intVal = LineIntegral(func, srcPt, tgtPt)/(discrPts.col(cellInd1)-discrPts.col(cellInd2)).norm();\n\n      hessVals.push_back(T(2*cellInd1,2*cellInd1,-intVal(0,0)));\n      hessVals.push_back(T(2*cellInd1+1,2*cellInd1,-intVal(0,1)));\n      hessVals.push_back(T(2*cellInd1,2*cellInd1+1,-intVal(1,0)));\n      hessVals.push_back(T(2*cellInd1+1,2*cellInd1+1,-intVal(1,1)));\n\n      hessVals.push_back(T(2*cellInd1,2*cellInd2,intVal(0,0)));\n      hessVals.push_back(T(2*cellInd1+1,2*cellInd2,intVal(0,1)));\n      hessVals.push_back(T(2*cellInd1,2*cellInd2+1,intVal(1,0)));\n      hessVals.push_back(T(2*cellInd1+1,2*cellInd2+1,intVal(1,1)));\n\n    }\n  }\n\n  Eigen::SparseMatrix<double> hess(2*numCells,2*numCells);\n  hess.setFromTriplets(hessVals.begin(), hessVals.end());\n\n  return hess;\n\n}\n\ntemplate<typename ConjugateFunctionType>\nEigen::SparseMatrix<double> SemidiscreteOT<ConjugateFunctionType>::PointHessian() const\n{\n  return PointHessian(optPrices, *lagDiag);\n}\n\ntemplate<typename ConjugateFunctionType>\nstd::pair<double,Eigen::VectorXd> SemidiscreteOT<ConjugateFunctionType>::ComputeGradient(Eigen::VectorXd const& prices,\n                                                                                         LaguerreDiagram const& lagDiag) const\n{\n  const int numCells = prices.size();\n\n  // Holds the part of the objective for each cell in the Laguerre diagram\n  Eigen::VectorXd objParts = Eigen::VectorXd::Zero(numCells);\n  Eigen::VectorXd gradient = Eigen::VectorXd::Zero(numCells);\n\n  Eigen::VectorXd probs(numCells);\n\n  //Eigen::MatrixXd cellAreas = Eigen::MatrixXd::Zero(grid->Nx, grid->Ny);\n#if defined(_OPENMP)\n  #pragma omp parallel for\n#endif\n  for(int cellInd=0; cellInd<numCells; ++cellInd){\n\n    // auto area_integrand = std::make_shared<ConstantIntegrand>();\n    //\n    // auto trans_integrand = std::make_shared<TransportIntegrand>(discrPts.col(cellInd));\n\n    // auto triArea = [](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2, Eigen::Vector2d const& pt3)\n    //   {\n    //     return 0.5*std::abs((pt2[0]*pt1[1]-pt1[0]*pt2[1])+(pt3[0]*pt2[1]-pt2[0]*pt3[1])+(pt1[0]*pt3[1]-pt3[0]*pt1[1]));\n    //   };\n    //\n    // auto rectArea = [](Eigen::Vector2d const& bottomLeft, Eigen::Vector2d const& topRight)\n    //   {\n    //     return std::abs((topRight[0]-bottomLeft[0])*(topRight[1]-bottomLeft[1]));\n    //   };\n    //\n    //\n    // double weightedArea  = lagDiag.IntegrateOverCell(cellInd, triArea, rectArea, dist);\n\n    objParts(cellInd) = -ConjugateFunctionType::Evaluate(-prices(cellInd), unbalancedPenalty)*discrProbs(cellInd);// - prices(cellInd)*weightedArea;\n\n    gradient(cellInd) = ConjugateFunctionType::Derivative(-prices(cellInd), unbalancedPenalty)*discrProbs(cellInd);\n\n    // if(weightedArea>0){\n\n      auto triFunc = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2, Eigen::Vector2d const& pt3)\n        {\n          return ConjugateFunctionType::TriangularIntegral(prices(cellInd), discrPts.col(cellInd), pt1,pt2,pt3,unbalancedPenalty);\n        };\n      auto rectFunc = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2)\n        {\n          return ConjugateFunctionType::RectangularIntegral(prices(cellInd), discrPts.col(cellInd), pt1,pt2,unbalancedPenalty);\n        };\n\n      objParts(cellInd) += -lagDiag.IntegrateOverCell(cellInd, triFunc, rectFunc, dist);\n\n      auto triFuncDeriv = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2, Eigen::Vector2d const& pt3)\n        {\n          return ConjugateFunctionType::TriangularIntegralDeriv(prices(cellInd), discrPts.col(cellInd), pt1,pt2,pt3,unbalancedPenalty);\n        };\n      auto rectFuncDeriv = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2)\n        {\n          return ConjugateFunctionType::RectangularIntegralDeriv(prices(cellInd), discrPts.col(cellInd), pt1,pt2,unbalancedPenalty);\n        };\n\n      gradient(cellInd) += -lagDiag.IntegrateOverCell(cellInd, triFuncDeriv, rectFuncDeriv, dist); //-weightedArea;\n    }\n\n  //   probs(cellInd) = weightedArea;\n  // }\n  //\n  // double totalProb = probs.sum();\n  // if(std::abs(totalProb-1.0)>1e-10){\n  //\n  //   std::cout << \"Warning:  Total probability has an error of \" << totalProb-1.0 << std::endl;\n  //   // std::cout << \"Prices = \" << prices.transpose() << std::endl;\n  //   // for(unsigned int cellInd=0; cellInd<lagDiag.NumCells(); ++cellInd){\n  //   //   std::cout << \"Cell \" << cellInd << \" has points \" << std::endl;\n  //   //   Eigen::MatrixXd pts = lagDiag.GetCellVertices(cellInd);\n  //   //   for(unsigned int ptInd=0; ptInd<pts.cols(); ++ptInd){\n  //   //      std::cout << \"[\" << pts(0,ptInd) << \",\" << pts(1,ptInd) << \"], \";\n  //   //   }\n  //   //   std::cout << std::endl;\n  //   // }\n  //   throw std::runtime_error(\"Error in total probability.\");\n  //\n  //\n  //\n  //  //SDOT_ASSERT(std::abs(weightedArea-1.0)<1e-10);\n  // }\n\n  return std::make_pair(objParts.sum(), gradient);\n}\n\n\ntemplate<typename ConjugateFunctionType>\nEigen::SparseMatrix<double> SemidiscreteOT<ConjugateFunctionType>::ComputeHessian(Eigen::VectorXd const& prices,\n                                                                                  LaguerreDiagram const& lagDiag) const\n{\n  const unsigned int numCells = discrPts.cols();\n  typedef Eigen::Triplet<double> T;\n\n  /* The diagonal entries of the Hessian are the negative sum of the off diagonals\n     See equation 27 of https://arxiv.org/pdf/1710.02634.pdf\n     This vector is used to keep track of this sum for each cell.\n  */\n  Eigen::VectorXd diagVals = Eigen::VectorXd::Zero(numCells);\n\n  // For unbalanced transport, the Diagonal of the hessian has an additional term\n  for(unsigned int cellInd=0; cellInd<numCells; ++cellInd) {\n\n    diagVals(cellInd) -= ConjugateFunctionType::Derivative2(-prices(cellInd), unbalancedPenalty)*discrProbs(cellInd);\n\n    auto triFunc = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2, Eigen::Vector2d const& pt3)\n      {\n        return ConjugateFunctionType::TriangularIntegralDeriv2(prices(cellInd), discrPts.col(cellInd), pt1,pt2,pt3, unbalancedPenalty);\n      };\n    auto rectFunc = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2)\n      {\n        return ConjugateFunctionType::RectangularIntegralDeriv2(prices(cellInd), discrPts.col(cellInd), pt1,pt2, unbalancedPenalty);\n      };\n\n    diagVals(cellInd) -= lagDiag.IntegrateOverCell(cellInd, triFunc, rectFunc, dist);\n  }\n\n  // Hold the i,j,val triplets defining the sparse Hessian\n  std::vector<T> hessVals;\n\n  double intVal;\n  unsigned int cellInd2;\n  LaguerreDiagram::Point_2 srcPt, tgtPt;\n\n  for(unsigned int cellInd1=0; cellInd1<numCells; ++cellInd1){\n\n    for(auto edgeTuple : lagDiag.InternalEdges(cellInd1)){\n      std::tie(cellInd2, srcPt, tgtPt) = edgeTuple;\n\n      // Compute the integral of the target density along the edge\n      auto func = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2)\n      {\n        return ConjugateFunctionType::LineIntegralDeriv(prices(cellInd1), discrPts.col(cellInd1), pt1, pt2, unbalancedPenalty);\n      };\n      intVal = 0.5*LineIntegral(func, srcPt, tgtPt)/(discrPts.col(cellInd1)-discrPts.col(cellInd2)).norm();\n\n      diagVals(cellInd1) -= intVal;\n      hessVals.push_back(T(cellInd1,cellInd2,intVal));\n    }\n  }\n\n  for(int i=0; i<numCells; ++i){\n    hessVals.push_back(T(i,i, diagVals(i)));\n  }\n\n  Eigen::SparseMatrix<double> hess(numCells,numCells);\n  hess.setFromTriplets(hessVals.begin(), hessVals.end());\n\n  return hess;\n}\n\n// double SemidiscreteOT::SquareIntegral(double xmin, double xmax,\n//                                       double ymin, double ymax,\n//                                       double px,   double py)\n// {\n//  double rectInt = (0.5/3.0)*(ymax-ymin)*(std::pow(xmax-px,3.0)-std::pow(xmin-px,3.0))\n//                 + (0.5/3.0)*(xmax-xmin)*(std::pow(ymax-py,3.0)-std::pow(ymin-py,3.0));\n//\n//  return rectInt;\n// }\n\n// double SemidiscreteOT::TriangleIntegral(double x1, double y1,\n//                                        double x2, double y2,\n//                                        double x3, double y3,\n//                                        double px, double py)\n// {\n//  double triInt = (1.0/2.0)*std::pow(px, 2) - 1.0/3.0*px*x1 - 1.0/3.0*px*x2 - 1.0/3.0*px*x3 + (1.0/2.0)*std::pow(py, 2) - 1.0/3.0*py*y1 - 1.0/3.0*py*y2 - 1.0/3.0*py*y3 + (1.0/12.0)*std::pow(x1, 2) + (1.0/12.0)*x1*x2 + (1.0/12.0)*x1*x3 + (1.0/12.0)*std::pow(x2, 2) + (1.0/12.0)*x2*x3 + (1.0/12.0)*std::pow(x3, 2) + (1.0/12.0)*std::pow(y1, 2) + (1.0/12.0)*y1*y2 + (1.0/12.0)*y1*y3 + (1.0/12.0)*std::pow(y2, 2) + (1.0/12.0)*y2*y3 + (1.0/12.0)*std::pow(y3, 2);\n//  triInt *= 0.5*((x2-x1)*(y3-y1) - (x3-x1)*(y2-y1));\n//\n//  return triInt;\n// }\n\n\n// template<typename ConjugateFunctionType>\n// Eigen::VectorXd SemidiscreteOT<ConjugateFunctionType>::GetValidPrices(Eigen::VectorXd const& x0)\n// {\n//\n// }\n\ntemplate<typename ConjugateFunctionType>\nstd::pair<Eigen::VectorXd, double> SemidiscreteOT<ConjugateFunctionType>::Solve(Eigen::VectorXd                  const& prices0,\n                                                         OptionList                              options)\n{\n  SDOT_ASSERT(prices0.size()==discrPts.cols());\n  const unsigned int dim = prices0.size();\n\n  unsigned int printLevel = GetOpt(\"Print Level\", options, 3);\n\n  // Trust region approach with a double dogleg step\n  double trustRadius = GetOpt(\"Trust Radius\", options, 1.0);\n  const unsigned int maxEvals = GetOpt(\"Max Steps\", options, 100.0);\n\n  const double xtol_abs = GetOpt(\"XTol Abs\", options, 1e-13*std::sqrt(double(dim)));\n  const double gtol_abs = GetOpt(\"GTol Abs\", options, 2e-4*std::sqrt(double(dim)));\n  const double ftol_abs = GetOpt(\"FTol Abs\", options, 1e-11);\n\n  const double acceptRatio = GetOpt(\"Accept Ratio\", options, 0.1);//0.1;\n  const double shrinkRatio = GetOpt(\"Shrink Ratio\", options, 0.25);//0.1;\n  const double growRatio = GetOpt(\"Grow Ratio\", options, 0.75);\n  const double growRate = GetOpt(\"Grow Rate\", options, 2.0);\n  const double shrinkRate = GetOpt(\"Shrink Rate\", options, 0.25);\n  const double maxRadius = GetOpt(\"Max Radius\", options, 10);\n\n  SDOT_ASSERT(shrinkRatio>=acceptRatio);\n\n  double fval, newF, gradNorm, newGradNorm;\n  Eigen::VectorXd grad, newGrad;\n  Eigen::SparseMatrix<double> hess;\n\n  Eigen::VectorXd x = prices0;\n  Eigen::VectorXd newX(x);\n  Eigen::VectorXd step = Eigen::VectorXd::Zero(dim);\n\n  std::shared_ptr<LaguerreDiagram> newLagDiag;\n\n  // Compute an initial gradient and Hessian\n  lagDiag  = std::make_shared<LaguerreDiagram>(grid->xMin, grid->xMax, grid->yMin, grid->yMax, discrPts, x);\n  SDOT_ASSERT(lagDiag!=nullptr);\n\n  std::tie(fval, grad) = ComputeGradient(x, *lagDiag);\n  hess = ComputeHessian(x, *lagDiag);\n\n  fval *= -1.0;\n  grad *= -1.0;\n  hess *= -1.0;\n  gradNorm = grad.norm();\n\n  if(printLevel>0){\n    std::cout << \"Using NewtonTrust optimizer...\" << std::endl;\n    std::cout << \"  Iteration, TrustRadius, Empty Cells,           rho, Dual Objective,        ||g||,   ||g||/sqrt(dim)\" << std::endl;\n  }\n\n  // count the non-empty Cells\n  int numEmpty = 0;\n  for(int i=0; i<x.size(); ++i){\n    if(lagDiag->GetCellVertices(i).cols()<3)\n      ++numEmpty;\n  }\n\n\n  for(int it=0; it<maxEvals; ++it) {\n\n    if((gradNorm < gtol_abs)&&(numEmpty==0)){\n      if(printLevel>0){\n        std::printf(\"Terminating because gradient norm (%4.2e) is smaller than gtol_abs (%4.2e).\\n\", gradNorm, gtol_abs);\n      }\n      optPrices = x;\n      return std::make_pair(x,fval);\n    }\n\n    step = SolveSubProblem(fval, grad,  hess, trustRadius);\n\n    newX = x+step;\n\n    // Try constructing the new Laguerre diagram.\n    newLagDiag  = std::make_shared<LaguerreDiagram>(grid->xMin, grid->xMax, grid->yMin, grid->yMax, discrPts, newX);\n\n    std::tie(newF, newGrad) = ComputeGradient(newX, *newLagDiag);\n    newF *= -1.0;\n    newGrad *= -1.0;\n    newGradNorm = newGrad.norm();\n\n    // Use the quadratic submodel to predict the change in the objective\n    double trueDelta = newF-fval;\n    double modDelta = grad.dot(step) + 0.5*step.dot(hess.selfadjointView<Eigen::Lower>()*step);\n\n    double rho = trueDelta/modDelta;\n    //std::cout << \"Model, Truth = \" << modDelta << \", \" << trueDelta << std::endl;\n    //std::cout << \"          step.dot(grad) = \" << step.dot(grad) << std::endl;\n    // std::cout << \"          delta f = \" << trueDelta << std::endl;\n    // std::cout << \"          modDelta = \" << modDelta << std::endl;\n    // std::cout << \"          New prices = \" << newX.transpose() << std::endl;\n    //std::cout << \"          rho = \" << rho << std::endl;\n\n    if(printLevel>0){\n      std::printf(\"  %9d, %11.2e,  %10d,    % 5.3e, % 14.3e,    %5.3e,  %15.3e\\n\", it, trustRadius, numEmpty, rho, -1.0*fval, gradNorm, gradNorm/std::sqrt(double(dim)));\n    }\n\n    double stepNorm = step.norm();\n    if((stepNorm < xtol_abs)&&(numEmpty==0)){\n      if(printLevel>0){\n        std::printf(\"Terminating because stepsize (%4.2e) is smaller than xtol_abs (%4.2e).\\n\", stepNorm, xtol_abs);\n      }\n      optPrices = newX;\n      return std::make_pair(newX,newF);\n    }\n\n    // Update the position.  If the model is really bad, we'll just stay put\n    if(rho>acceptRatio){\n\n      if(((std::abs(fval-newF)<ftol_abs))&&(numEmpty==0)){\n        if(printLevel>0){\n          std::printf(\"Terminating because change in objective (%4.2e) is smaller than ftol_abs (%4.2e).\\n\", fval-newF, ftol_abs);\n        }\n        optPrices = newX;\n        return std::make_pair(newX,newF);\n      }\n\n      x = newX;\n      fval = newF;\n      lagDiag = newLagDiag;\n      grad = newGrad;\n      gradNorm = newGradNorm;\n\n      // Recompute the Hessian at the new point\n      hess = ComputeHessian(x, *lagDiag);\n      hess *= -1.0;\n\n      // Update the number of empty cells in the diagram\n      numEmpty = 0;\n      for(int i=0; i<x.size(); ++i){\n        if(lagDiag->GetCellVertices(i).cols()<3)\n          ++numEmpty;\n      }\n    }\n\n    // Update the trust region size\n    if(rho<shrinkRatio){\n      trustRadius = shrinkRate*trustRadius; // shrink trust region\n\n      if(printLevel>1)\n        std::cout << \"            Shrinking trust region because of submodel accuracy.\" << std::endl;\n\n    }else if((rho>growRatio)&&(std::abs(step.norm()-trustRadius)<1e-10)) {\n      trustRadius = std::min(growRate*trustRadius, maxRadius);\n\n      if(printLevel>1)\n        std::cout << \"            Growing trust region.\" << std::endl;\n\n    }\n  }\n\n  if(printLevel>0){\n    std::printf(\"Terminating because maximum number of iterations (%d) was reached.\", maxEvals);\n  }\n\n  optPrices = x;\n  return std::make_pair(x,fval);\n}\n\ntemplate<typename ConjugateFunctionType>\nEigen::VectorXd SemidiscreteOT<ConjugateFunctionType>::SolveSubProblem(double obj,\n                                                Eigen::Ref<const Eigen::VectorXd> const& grad,\n                                                Eigen::Ref<const Eigen::SparseMatrix<double>> const& hess,\n                                                double trustRadius) const\n{\n  const double trustTol = 1e-12;\n  const unsigned int dim = grad.size();\n\n  // Current estimate of the subproblem minimum\n  Eigen::VectorXd z = Eigen::VectorXd::Zero(dim);\n\n  // Related to the step direction\n  Eigen::VectorXd r = grad;\n  Eigen::VectorXd d = -r;\n\n  // If the gradient is small enough where we're starting, then we're done\n  if(r.norm()<trustTol){\n    return z;\n  }\n\n  Eigen::VectorXd Bd; // the Hessian (B) applied to a vector d\n\n  double alpha, beta, gradd, dBd, rr;\n\n  for(int i=0; i<dim; ++i){\n    Bd = hess.selfadjointView<Eigen::Lower>()*d;\n    gradd = grad.dot(d);\n    dBd = d.dot(Bd);\n    rr = r.squaredNorm();\n\n    // If the Hessian isn't positive definite in this direction, we can go all\n    // the way to the trust region boundary\n    if(dBd<=0){\n      // do something\n\n      double dz = d.dot(z);\n      double dd = d.squaredNorm();\n      double zz = z.squaredNorm();\n      double r2 = trustRadius*trustRadius;\n\n      double tau1 = (-dz + sqrt(dz*dz - dd*(zz-r2)))/dd;\n      double tau2 = (-dz - sqrt(dz*dz - dd*(zz-r2)))/dd;\n\n      double zBd = z.dot(Bd);\n      double mval1 = tau1*gradd + tau1*zBd + tau1*tau1*dBd;\n      double mval2 = tau2*gradd + tau2*zBd + tau2*tau2*dBd;\n\n      return (mval1<mval2) ? (z+tau1*d) : (z+tau2*d);\n    }\n\n    alpha = rr / dBd;\n    Eigen::VectorXd newZ = z + alpha * d;\n\n    if(newZ.norm()>trustRadius){\n\n      double dz = d.dot(z);\n      double dd = d.squaredNorm();\n      double zz = z.squaredNorm();\n      double r2 = trustRadius*trustRadius;\n\n      double tau = (-dz + sqrt(dz*dz - dd*(zz-r2)))/dd;\n      return z + tau*d;\n    }\n\n    z = newZ;\n\n    r += alpha*Bd;\n\n    if(r.norm()<trustTol){\n      return z;\n    }\n\n    beta = r.squaredNorm() / rr;\n    d = (-r + beta*d).eval();\n  }\n\n  return z;\n}\n\ntemplate<typename ConjugateFunctionType>\nstd::shared_ptr<LaguerreDiagram> SemidiscreteOT<ConjugateFunctionType>::BuildCentroidal(std::shared_ptr<Distribution2d> const& dist,\n                                                                 Eigen::Matrix2Xd                const& initialPoints,\n                                                                 Eigen::VectorXd                 const& pointProbs,\n                                                                 OptionList                             opts)\n{\n\n  unsigned int maxIts =  GetOpt(\"Lloyd Steps\", opts, 100);\n  double xtol = GetOpt(\"Lloyd Tol\", opts, 1e-8);\n  double gtol = xtol;\n\n  auto optIt = opts.find(\"Print Level\");\n  if(optIt == opts.end())\n    opts[\"Print Level\"] = 0;\n\n  const unsigned int numPts = pointProbs.size();\n  SDOT_ASSERT(numPts==initialPoints.cols());\n\n  double resid = xtol + 1.0;\n\n  Eigen::MatrixXd newPts;\n  Eigen::VectorXd prices = Eigen::VectorXd::Ones(numPts);\n  double dualObj;\n  Eigen::MatrixXd pts = initialPoints;\n  std::shared_ptr<SemidiscreteOT> ot = std::make_shared<SemidiscreteOT>(dist, initialPoints, pointProbs, GetOpt(\"Penalty\", opts, 1.0));\n\n  std::cout << \"Computing constrained centroidal diagram...\" << std::endl;\n  std::cout << \"  Iteration,  ||g||,   max(dx)\" << std::endl;\n\n  for(unsigned int i=0; i<maxIts; ++i){\n    SDOT_ASSERT(ot);\n\n    std::tie(prices, dualObj) = ot->Solve(prices, opts);\n\n    Eigen::MatrixXd pointGrad = ot->PointGradient();\n    Eigen::Map<Eigen::VectorXd> pointGradVec(pointGrad.data(),2*pointGrad.cols());\n\n    double stepSize = 1.0;\n    Eigen::Matrix2Xd dir = -pointGrad.array()*(ot->LloydPointHessian()+1e-12*Eigen::MatrixXd::Ones(2,numPts)).array().inverse();\n\n    newPts = pts + stepSize*dir;\n\n    // Backtrack until all the points are  in the domain\n    while((newPts.row(0).minCoeff()<ot->grid->xMin)||(newPts.row(0).maxCoeff()>ot->grid->xMax)||(newPts.row(1).minCoeff()<ot->grid->yMin)||(newPts.row(1).maxCoeff()>ot->grid->yMax)){\n      stepSize *= 0.75;\n      newPts = pts + stepSize*dir;\n    }\n\n    resid = (newPts - pts).cwiseAbs().maxCoeff();;\n    std::printf(\"  %9d, %5.3e, %5.3e\\n\", i, pointGrad.norm(), resid);\n\n    if(resid<xtol){\n      std::cout << \"Converged due to small stepsize.\" << std::endl;\n      return ot->Diagram();\n    }\n\n    if((pointGradVec.norm()/(2*numPts))<gtol){\n      std::cout << \"Converged due to small gradient.\" << std::endl;\n      return ot->Diagram();\n    }\n\n    pts = newPts;\n    ot->SetPoints(pts);\n  }\n\n  std::cout << \"WARNING: Did not converge to constrained centroidal diagram.\" << std::endl;\n  return ot->Diagram();\n}\n\ntemplate<typename ConjugateFunctionType>\nstd::shared_ptr<LaguerreDiagram> SemidiscreteOT<ConjugateFunctionType>::BuildCentroidal(std::shared_ptr<Distribution2d> const& dist,\n                                                                 Eigen::VectorXd                 const& probs,\n                                                                 OptionList                             opts)\n{\n  BoundingBox bbox(dist->Grid()->xMin, dist->Grid()->xMax, dist->Grid()->yMin, dist->Grid()->yMax);\n  Eigen::Matrix2Xd initialPts = LaguerreDiagram::LatinHypercubeSample(bbox, probs.size());\n  return BuildCentroidal(dist, initialPts, probs, opts);\n}\n\ntemplate<typename ConjugateFunctionType>\nstd::shared_ptr<LaguerreDiagram> SemidiscreteOT<ConjugateFunctionType>::BuildCentroidal(std::shared_ptr<Distribution2d> const& dist,\n                                                                 unsigned int                           numPts,\n                                                                 OptionList                             opts)\n{\n  Eigen::VectorXd probs = (1.0/numPts)*Eigen::VectorXd::Ones(numPts);\n  return BuildCentroidal(dist, probs, opts);\n}\n\ntemplate<typename ConjugateFunctionType>\nEigen::Matrix2Xd SemidiscreteOT<ConjugateFunctionType>::MarginalCentroids(Eigen::VectorXd const& prices,\n                                                                          LaguerreDiagram const& lagDiag) const\n{\n  int numCells =  lagDiag.NumCells();\n  Eigen::Matrix2Xd centroids(2,numCells);\n\n  // Loop over all ofthe cells\n  for(int i=0; i<numCells; ++i){\n\n    auto triFunc = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2, Eigen::Vector2d const& pt3)\n      {\n        return ConjugateFunctionType::TriangularIntegralMarginalCentroid(prices(i), discrPts.col(i), pt1,pt2,pt3,unbalancedPenalty);\n      };\n    auto rectFunc = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2)\n      {\n        return ConjugateFunctionType::RectangularIntegralMarginalCentroid(prices(i), discrPts.col(i), pt1,pt2,unbalancedPenalty);\n      };\n\n\n    centroids.col(i) = lagDiag.IntegrateOverCell(i, triFunc, rectFunc, dist);\n\n\n    auto triFunc2 = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2, Eigen::Vector2d const& pt3)\n      {\n        return ConjugateFunctionType::TriangularIntegralMarginalMass(prices(i), discrPts.col(i), pt1,pt2,pt3,unbalancedPenalty);\n      };\n    auto rectFunc2 = [&](Eigen::Vector2d const& pt1, Eigen::Vector2d const& pt2)\n      {\n        return ConjugateFunctionType::RectangularIntegralMarginalMass(prices(i), discrPts.col(i), pt1,pt2,unbalancedPenalty);\n      };\n\n    centroids.col(i) /= lagDiag.IntegrateOverCell(i, triFunc2, rectFunc2, dist);\n  }\n\n  return centroids;\n}\n\ntemplate<>\nEigen::Matrix2Xd SemidiscreteOT<sdot::distances::Wasserstein2>::MarginalCentroids(Eigen::VectorXd const& prices,\n                                                                                  LaguerreDiagram const& lagDiag) const\n{\n  return lagDiag.Centroids(dist);\n}\n\n\n\n\nnamespace sdot{\n  template class SemidiscreteOT<sdot::distances::Wasserstein2>;\n  template class SemidiscreteOT<sdot::distances::QuadraticRegularization>;\n  template class SemidiscreteOT<sdot::distances::GHK>;\n}\n", "meta": {"hexsha": "8d5f6f5cf8b994eddbe2f6512e90837f46632abc", "size": 30175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SemiDiscreteOT.cpp", "max_stars_repo_name": "mparno/sdot2d", "max_stars_repo_head_hexsha": "f632824fc4f0285eab6de911cca8932f69ece705", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SemiDiscreteOT.cpp", "max_issues_repo_name": "mparno/sdot2d", "max_issues_repo_head_hexsha": "f632824fc4f0285eab6de911cca8932f69ece705", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SemiDiscreteOT.cpp", "max_forks_repo_name": "mparno/sdot2d", "max_forks_repo_head_hexsha": "f632824fc4f0285eab6de911cca8932f69ece705", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.860727729, "max_line_length": 458, "alphanum_fraction": 0.6263131732, "num_tokens": 8744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.43697972189465684}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/experimental/models/lgm1.hpp>\n#include <ql/quotes/simplequote.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\nLgm1::Lgm1(const Handle<YieldTermStructure> &yts,\n           const std::vector<Date> &volstepdates,\n           const std::vector<Real> &alpha, const Real &kappa)\n    : Lgm(yts), CalibratedModel(2), volstepdates_(volstepdates),\n      volsteptimes_(volstepdates_.size()),\n      volsteptimesArray_(volstepdates_.size()), alpha_(arguments_[0]),\n      kappa_(arguments_[1]) {\n    alphaQuotes_.resize(alpha.size());\n    for (Size i = 0; i < alpha.size(); ++i) {\n        alphaQuotes_[i] =\n            Handle<Quote>(boost::make_shared<SimpleQuote>(alpha[i]));\n    }\n\n    kappaQuote_ = Handle<Quote>(boost::make_shared<SimpleQuote>(kappa));\n\n    initialize();\n}\n\nLgm1::Lgm1(const Handle<YieldTermStructure> &yts,\n           const std::vector<Date> &volstepdates,\n           const std::vector<Handle<Quote> > &alpha, const Handle<Quote> &kappa)\n    : Lgm(yts), CalibratedModel(2), volstepdates_(volstepdates),\n      volsteptimes_(volstepdates_.size()),\n      volsteptimesArray_(volstepdates_.size()), alphaQuotes_(alpha),\n      kappaQuote_(kappa), alpha_(arguments_[0]), kappa_(arguments_[1]) {\n\n    initialize();\n}\n\nvoid Lgm1::updateTimes() const {\n    volsteptimes_.clear();\n    int j = 0;\n    for (std::vector<Date>::const_iterator i = volstepdates_.begin();\n         i != volstepdates_.end(); ++i, ++j) {\n        volsteptimes_.push_back(termStructure()->timeFromReference(*i));\n        volsteptimesArray_[j] = volsteptimes_[j];\n        if (j == 0)\n            QL_REQUIRE(volsteptimes_[0] > 0.0, \"volsteptimes must be positive (\"\n                                                   << volsteptimes_[0] << \")\");\n        else\n            QL_REQUIRE(volsteptimes_[j] > volsteptimes_[j - 1],\n                       \"volsteptimes must be strictly increasing (\"\n                           << volsteptimes_[j - 1] << \"@\" << (j - 1) << \", \"\n                           << volsteptimes_[j] << \"@\" << j << \")\");\n    }\n}\n\nvoid Lgm1::updateAlpha() {\n    for (Size i = 0; i < alpha_.size(); ++i) {\n        alpha_.setParam(i, alphaQuotes_[i]->value());\n    }\n    update();\n}\n\nvoid Lgm1::updateKappa() {\n    kappa_.setParam(0, kappaQuote_->value());\n    update();\n}\n\nvoid Lgm1::initialize() {\n    QL_REQUIRE(volstepdates_.size() + 1 == alphaQuotes_.size(),\n               \"alphas (\" << alphaQuotes_.size() << \") and step dates (\"\n                          << volstepdates_.size() << \") inconsistent.\");\n    updateTimes();\n    alpha_ = PiecewiseConstantParameter(volsteptimes_, NoConstraint());\n    kappa_ = ConstantParameter(kappaQuote_->value(), NoConstraint());\n    updateAlpha();\n    alphaObserver_ = boost::make_shared<AlphaObserver>(this);\n    kappaObserver_ = boost::make_shared<KappaObserver>(this);\n    for (Size i = 0; i < alpha_.size(); ++i)\n        alphaObserver_->registerWith(alphaQuotes_[i]);\n    kappaObserver_->registerWith(kappaQuote_);\n    setParametrization(\n        boost::make_shared<detail::LgmPiecewiseAlphaConstantKappa>(\n            volsteptimesArray_, alpha_.params(), kappa_.params()));\n    stateProcess_ = boost::make_shared<\n        LgmStateProcess<detail::LgmPiecewiseAlphaConstantKappa> >(\n        parametrization());\n    registerWith(stateProcess_);\n    parametrization()->update();\n}\n\n} // namespace QuantLib\n", "meta": {"hexsha": "28eb3162cd5448fc693925a7aba8567fe33d1a17", "size": 4155, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/lgm1.cpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/experimental/models/lgm1.cpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/experimental/models/lgm1.cpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 37.7727272727, "max_line_length": 80, "alphanum_fraction": 0.6430806258, "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925402, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4369797218946568}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_GAMMA_Q_HPP\n#define STAN_MATH_PRIM_FUN_GAMMA_Q_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/functor/apply_scalar_binary.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n *\n   \\f[\n   \\mbox{gamma\\_q}(a, z) =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } a\\leq 0 \\textrm{ or } z < 0\\\\\n     Q(a, z) & \\mbox{if } a > 0, z \\geq 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } a = \\textrm{NaN or } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{gamma\\_q}(a, z)}{\\partial a} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } a\\leq 0 \\textrm{ or } z < 0\\\\\n     \\frac{\\partial\\, Q(a, z)}{\\partial a} & \\mbox{if } a > 0, z \\geq 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } a = \\textrm{NaN or } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{gamma\\_q}(a, z)}{\\partial z} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } a\\leq 0 \\textrm{ or } z < 0\\\\\n     \\frac{\\partial\\, Q(a, z)}{\\partial z} & \\mbox{if } a > 0, z \\geq 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } a = \\textrm{NaN or } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   Q(a, z)=\\frac{1}{\\Gamma(a)}\\int_z^\\infty t^{a-1}e^{-t}dt\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, Q(a, z)}{\\partial a} =\n -\\frac{\\Psi(a)}{\\Gamma^2(a)}\\int_z^\\infty t^{a-1}e^{-t}dt\n   + \\frac{1}{\\Gamma(a)}\\int_z^\\infty (a-1)t^{a-2}e^{-t}dt\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, Q(a, z)}{\\partial z} = -\\frac{z^{a-1}e^{-z}}{\\Gamma(a)}\n   \\f]\n   * @throws domain_error if x is at pole\n */\ninline double gamma_q(double x, double a) { return boost::math::gamma_q(x, a); }\n\n/**\n * Enables the vectorised application of the gamma_q function,\n * when the first and/or second arguments are containers.\n *\n * @tparam T1 type of first input\n * @tparam T2 type of second input\n * @param a First input\n * @param b Second input\n * @return gamma_q function applied to the two inputs.\n */\ntemplate <typename T1, typename T2, require_any_container_t<T1, T2>* = nullptr>\ninline auto gamma_q(const T1& a, const T2& b) {\n  return apply_scalar_binary(\n      a, b, [&](const auto& c, const auto& d) { return gamma_q(c, d); });\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "1387b3abe60138ed93ee8465ac5c846ff0b34688", "size": 2213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/gamma_q.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T14:33:37.000Z", "max_issues_repo_path": "stan/math/prim/fun/gamma_q.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/fun/gamma_q.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-10T12:55:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-10T12:55:07.000Z", "avg_line_length": 29.1184210526, "max_line_length": 80, "alphanum_fraction": 0.5892453683, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4369797160942045}}
{"text": "\n#include <NTL/ZZ_pX.h>\n#include <NTL/FFT.h>\n\n#include <cstdio>\n\nNTL_CLIENT\n\n\ndouble clean_data(double *t)\n{\n   double x, y, z;\n   long i, ix, iy, n;\n\n   x = t[0]; ix = 0;\n   y = t[0]; iy = 0;\n\n   for (i = 1; i < 5; i++) {\n      if (t[i] < x) {\n         x = t[i];\n         ix = i;\n      }\n      if (t[i] > y) {\n         y = t[i];\n         iy = i;\n      }\n   }\n\n   z = 0; n = 0;\n   for (i = 0; i < 5; i++) {\n      if (i != ix && i != iy) z+= t[i], n++;\n   }\n\n   z = z/n;  \n\n   return z;\n}\n\n\nvoid print_flag()\n{\n\n#if defined(NTL_FFT_LAZYMUL)\nprintf(\"FFT_LAZYMUL \");\n#endif\n\n#if defined(NTL_SPMM_ULL)\nprintf(\"SPMM_ULL \");\n#endif\n\n#if defined(NTL_AVOID_BRANCHING)\nprintf(\"AVOID_BRANCHING \");\n#endif\n\n#if defined(NTL_FFT_BIGTAB)\nprintf(\"FFT_BIGTAB \");\n#endif\n\nprintf(\"\\n\");\n\n}\n\n\nint main()\n{\n\n   SetSeed(ZZ(0));\n\n\n   long n, k;\n\n   n = 200;\n   k = 10*NTL_ZZ_NBITS;\n\n   ZZ p;\n\n   RandomLen(p, k);\n   if (!IsOdd(p)) p++;\n\n\n   ZZ_p::init(p);         // initialization\n\n   ZZ_pX f, g, h, r1, r2, r3;\n\n   random(g, n);    // g = random polynomial of degree < n\n   random(h, n);    // h =             \"   \"\n   random(f, n);    // f =             \"   \"\n\n   SetCoeff(f, n);  // Sets coefficient of X^n to 1\n   \n\n   // For doing arithmetic mod f quickly, one must pre-compute\n   // some information.\n\n   ZZ_pXModulus F;\n   build(F, f);\n\n   PlainMul(r1, g, h);  // this uses classical arithmetic\n   PlainRem(r1, r1, f);\n\n   MulMod(r2, g, h, F);  // this uses the FFT\n\n   MulMod(r3, g, h, f);  // uses FFT, but slower\n\n   // compare the results...\n\n   if (r1 != r2) {\n      printf(\"999999999999999 \");\n      print_flag();\n      return 0;\n   }\n   else if (r1 != r3) {\n      printf(\"999999999999999 \");\n      print_flag();\n      return 0;\n   }\n\n   double t;\n   long i, j;\n   long iter;\n\n   const int nprimes = 30;\n   const long L = 12; \n   const long N = 1L << L;\n   long r;\n   \n\n   for (r = 0; r < nprimes; r++) UseFFTPrime(r);\n\n   vec_long A1[nprimes], A2[nprimes];\n   vec_long B1[nprimes], B2[nprimes];\n\n   for (r = 0; r < nprimes; r++) {\n      A1[r].SetLength(N);\n      A2[r].SetLength(N);\n      B1[r].SetLength(N);\n      B2[r].SetLength(N);\n\n      for (i = 0; i < N; i++) {\n         A1[r][i] = RandomBnd(GetFFTPrime(r));\n         A2[r][i] = RandomBnd(GetFFTPrime(r));\n      }\n   }\n\n   for (r = 0; r < nprimes; r++) {\n      long *A1p = A1[r].elts();\n      long *A2p = A2[r].elts();\n      long *B1p = B1[r].elts();\n      long *B2p = B2[r].elts();\n      long q = GetFFTPrime(r);\n      mulmod_t qinv = GetFFTPrimeInv(r);\n \n      FFTFwd(B1p, A1p, L, r);\n      FFTFwd(B2p, A2p, L, r);\n      for (i = 0; i < N; i++) B1p[i] = NormalizedMulMod(B1p[i], B2p[i], q, qinv);\n      FFTRev1(B1p, B1p, L, r);\n   }\n\n   iter = 1;\n\n   do {\n     t = GetTime();\n     for (j = 0; j < iter; j++) {\n        for (r = 0; r < nprimes; r++) {\n           long *A1p = A1[r].elts();\n           long *A2p = A2[r].elts();\n           long *B1p = B1[r].elts();\n           long *B2p = B2[r].elts();\n           long q = GetFFTPrime(r);\n           mulmod_t qinv = GetFFTPrimeInv(r);\n\n           FFTFwd(B1p, A1p, L, r);\n           FFTFwd(B2p, A2p, L, r);\n           for (i = 0; i < N; i++) B1p[i] = NormalizedMulMod(B1p[i], B2p[i], q, qinv);\n           FFTRev1(B1p, B1p, L, r);\n        }\n     }\n     t = GetTime() - t;\n     iter = 2*iter;\n   } while(t < 1);\n\n   iter = iter/2;\n\n   iter = long((3/t)*iter) + 1;\n\n\n   double tvec[5];\n   long w;\n\n   for (w = 0; w < 5; w++) {\n     t = GetTime();\n     for (j = 0; j < iter; j++) {\n        for (r = 0; r < nprimes; r++) {\n           long *A1p = A1[r].elts();\n           long *A2p = A2[r].elts();\n           long *B1p = B1[r].elts();\n           long *B2p = B2[r].elts();\n           long q = GetFFTPrime(r);\n           mulmod_t qinv = GetFFTPrimeInv(r);\n\n           FFTFwd(B1p, A1p, L, r);\n           FFTFwd(B2p, A2p, L, r);\n           for (i = 0; i < N; i++) B1p[i] = NormalizedMulMod(B1p[i], B2p[i], q, qinv);\n           FFTRev1(B1p, B1p, L, r);\n        }\n     }\n     t = GetTime() - t;\n     tvec[w] = t;\n   }\n\n   t = clean_data(tvec);\n\n   t = floor((t/iter)*1e13);\n\n   if (t < 0 || t >= 1e15)\n      printf(\"999999999999999 \");\n   else\n      printf(\"%015.0f \", t);\n\n   printf(\" [%ld] \", iter);\n\n   print_flag();\n\n   return 0;\n}\n", "meta": {"hexsha": "ee2912f1e10a62fcdb95d3a6e19e4a28ad7de734", "size": 4219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/Poly1TimeTest.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 160.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T09:32:19.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/Poly1TimeTest.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2016-12-26T07:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T16:34:31.000Z", "max_forks_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/Poly1TimeTest.cpp", "max_forks_repo_name": "dklee0501/Lobster", "max_forks_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2016-10-10T17:56:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:56:39.000Z", "avg_line_length": 18.6681415929, "max_line_length": 86, "alphanum_fraction": 0.4640910168, "num_tokens": 1577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4369797160942045}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Maciej Andrejczuk\n//               2014 Piotr Wygocki\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file steiner_component.hpp\n * @brief\n * @author Maciej Andrejczuk, Piotr Wygocki\n * @version 1.0\n * @date 2013-08-01\n */\n#ifndef PAAL_STEINER_COMPONENT_HPP\n#define PAAL_STEINER_COMPONENT_HPP\n\n#include \"paal/data_structures/metric/basic_metrics.hpp\"\n#include \"paal/steiner_tree/dreyfus_wagner.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/range/algorithm/transform.hpp>\n#include <boost/range/join.hpp>\n\n#include <iosfwd>\n#include <set>\n\nnamespace paal {\nnamespace ir {\n\n/**\n * @class steiner_component\n * @brief Class represents k-components of Steiner Tree.\n * Component is a subtree whose terminals coincide with leaves.\n */\ntemplate <typename Vertex, typename Dist>\nclass steiner_component {\npublic:\n    using Edge = typename std::pair<Vertex, Vertex>;\n    using Vertices = typename std::vector<Vertex>;\n\n    ///constructor\n    template<typename Metric, typename Terminals>\n    steiner_component(const Metric & cost_map, Vertices terminals, const Terminals& steiner_vertices) :\n        m_terminals(std::move(terminals)), m_size(m_terminals.size()) {\n\n        auto all_elements = boost::join(m_terminals, steiner_vertices);\n        data_structures::array_metric<typename data_structures::metric_traits<Metric>::DistanceType>\n            fast_metric(cost_map, all_elements);\n        auto term_nr = boost::distance(m_terminals);\n        auto all_elements_nr = boost::distance(all_elements);\n        auto dw = paal::make_dreyfus_wagner(fast_metric,\n                    irange(term_nr),\n                    irange(int(term_nr), int(all_elements_nr)));\n        dw.solve();\n        m_cost = dw.get_cost();\n        auto &steiner = dw.get_steiner_elements();\n        m_steiner_elements.resize(steiner.size());\n        auto id_to_elem = [&](int i){\n                if(i < term_nr) {\n                    return m_terminals[i];\n                } else {\n                    return steiner_vertices[i - term_nr];\n                }\n        };\n        boost::transform(steiner, m_steiner_elements.begin(), id_to_elem);\n        m_edges.resize(dw.get_edges().size());\n        boost::transform(dw.get_edges(), m_edges.begin(), [=](std::pair<int, int> e) {\n            return std::make_pair(id_to_elem(e.first), id_to_elem(e.second));\n        });\n    }\n\n    /**\n     * @brief Each component has versions, where sink is chosen from its\n     * terminals\n     */\n    Vertex get_sink(int version) const {\n        assert(version < count_terminals());\n        return m_terminals[version];\n    }\n\n    /**\n     * Returns vector composed of component's terminals.\n     */\n    const Vertices &get_terminals() const { return m_terminals; }\n\n    /**\n     * Returns vector composed of component's nonterminals, i.e. Steiner\n     * elements.\n     */\n    const Vertices &get_steiner_elements() const {\n        return m_steiner_elements;\n    }\n\n    /**\n     * Returns edges spanning the component.\n     */\n    const std::vector<Edge> &get_edges() const { return m_edges; }\n\n    /**\n     * Returns degree of component, i.e. number of terminals.\n     */\n    int count_terminals() const { return m_size; }\n\n    /**\n     * Returns minimal cost of spanning a component.\n     */\n    Dist get_cost() const { return m_cost; }\n\n    /**\n     * Prints the component.\n     */\n    friend std::ostream &operator<<(std::ostream &stream,\n                                    const steiner_component &component) {\n        for (int i = 0; i < component.m_size; i++) {\n            stream << component.m_terminals[i] << \" \";\n        }\n        stream << \": \";\n        for (auto edge : component.m_edges) {\n            stream << \"(\" << edge.first << \",\" << edge.second << \") \";\n        }\n        stream << component.m_cost;\n        return stream;\n    }\n\n  private:\n    const Vertices m_terminals; // terminals of the component\n    int m_size;                           // m_terminals.size()\n    Dist m_cost; // minimal cost of spanning the component\n    Vertices m_steiner_elements; // non-terminals selected for\n                                            // spanning tree\n    std::vector<Edge> m_edges;              // edges spanning the component\n};\n\n} // ir\n} // paal\n\n#endif // PAAL_STEINER_COMPONENT_HPP\n", "meta": {"hexsha": "0528398b3f1e6d1a34a9632d7c7c83e84c047755", "size": 4553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/iterative_rounding/steiner_tree/steiner_component.hpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/paal/iterative_rounding/steiner_tree/steiner_component.hpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/paal/iterative_rounding/steiner_tree/steiner_component.hpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 32.5214285714, "max_line_length": 103, "alphanum_fraction": 0.5987261146, "num_tokens": 1030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.43697093447685714}}
{"text": "/**\n * @author pkambadu\n */\n\n#include <iostream>\n#include <fstream>\n#include <functional>\n#include <cstring>\n#include <cstdlib>\n#include <vector>\n#include <utility>\n#include <cstdio>\n#include <map>\n\n#if defined(_OPENMP)\n#include <omp.h>\n#endif\n\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/filesystem.hpp>\n\n#include \"dyck_options.hpp\"\n#include \"generate_Galton_Watson.hpp\"\n#include \"dyck_path.hpp\"\n\ntypedef generate_Galton_Watson_t::graph_type graph_type;\ntypedef generate_Galton_Watson_t::vertex_index_map_t vertex_index_map_t;\ntypedef generate_Galton_Watson_t::vertex_name_map_t vertex_name_map_t;\ntypedef generate_Galton_Watson_t::edge_weight_map_t edge_weight_map_t;\ntypedef generate_Galton_Watson_t::vertex_distance_map_t vertex_weight_map_t;\ntypedef boost::graph_traits<graph_type>::vertex_iterator vertex_iter_t;\n\nstatic const double PI = \n    3.1415926535897932384626433832795028841971693993751058209749445923078164;\n\n/**\n * Thin wrapper around boost::uniform<> so that it conforms to random_shuffle.\n */\ntemplate <typename EngineType>\nstruct random_functor_t : std::unary_function<int, int> {\n  typedef EngineType engine_type;\n  typedef boost::uniform_int<int> uni_int_type;\n  engine_type engine;\n  \n  random_functor_t (engine_type engine) : engine(engine) {}\n\n  int operator()(const int& ULIMIT) {\n    uni_int_type dist (0, ULIMIT-1);\n    return dist(engine);\n  }\n};\n\n/**\n * Print the tree as a DOT file \n */ \ntemplate <typename Graph>\nvoid print_tree (Graph& G, const dyck_options_t& options) {\n#pragma omp critical\n  if (options.print_tree) {\n    /** Set the properties that you need to extract from the graph */\n    boost::dynamic_properties dp;\n    vertex_index_map_t index_map = boost::get(boost::vertex_index, G);\n    vertex_name_map_t name_map = boost::get(boost::vertex_name, G);\n    vertex_weight_map_t weight_map = boost::get(boost::vertex_distance, G);\n\n    dp.property(\"index\", index_map);\n    dp.property(\"name\", name_map);\n    dp.property(\"weight\", weight_map);\n\n    /** Create the output */\n    std::ostream* output; \n    if (0==strcmp(\"stdout\", options.dot_out.c_str())) output = &(std::cout);\n    else output = new std::ofstream(options.dot_out.c_str());\n\n    boost::write_graphviz_dp(*output, G, dp, \"index\");\n\n    if (0!=strcmp(\"stdout\", options.dot_out.c_str())) delete output;\n  }\n}\n\n/**\n * A function that lists all the DOT files in a directory.\n */\nstd::vector<std::string> get_dot_files (const std::string& dir_name) {\n  std::vector<std::string> dot_file_list;\n\n  if (boost::filesystem::exists(dir_name) && \n      boost::filesystem::is_directory(dir_name)) {\n    boost::filesystem::directory_iterator end_iter;\n    for(boost::filesystem::directory_iterator dir_iter(dir_name); \n        dir_iter != end_iter; \n        ++dir_iter) {\n      if (boost::filesystem::is_regular_file(dir_iter->status())) {\n        const boost::filesystem::path current_file = dir_iter->path();\n        const boost::filesystem::path current_file_ext = \n                                             current_file.extension();\n        if (current_file_ext.native() == \".dot\") {\n          dot_file_list.push_back(current_file.native());\n        }\n      }\n    }\n  }\n\n  return dot_file_list;\n}\n\n/**\n * The one annoying problem is that OutputIterator's do not define\n * a value type, so it may not always work! Hrmp!\n */ \nint generate_seed () {\n  int r_int;\n#pragma omp critical\n  {\n    std::ifstream rf(\"/dev/random\", std::ios::binary);\n    if(rf.is_open())rf.read(reinterpret_cast<char*>(&r_int),sizeof(r_int));\n    else r_int = std::time(NULL);\n  }\n\n  return r_int;\n}\n\ngraph_type generate_one_graph (const dyck_options_t& options,\n                               int& gen_seed) {\n  graph_type G;\n\n  gen_seed = (0>options.seed)?generate_seed():options.seed;\n  if (0 == strcmp(\"Poisson\", options.gen_method.c_str())) {\n    G = generate_Galton_Watson_t::generate_Poisson(options.n,\n                                                   gen_seed,\n                                                   options.lambda,\n                                                   options.use_random_weights,\n                                                   options.verbosity,\n                                                   options.use_stupid_tree_gen);\n  } else if (0 == strcmp(\"Binomial\", options.gen_method.c_str())) {\n    G = generate_Galton_Watson_t::generate_Binomial (options.n,\n                                                     gen_seed,\n                                                     options.k,\n                                                     options.p,\n                                                     options.use_random_weights,\n                                                     options.verbosity,\n                                                 options.use_stupid_tree_gen);\n  } else if (0 == strcmp(\"Geometric\", options.gen_method.c_str())) {\n    G = generate_Galton_Watson_t::generate_Geometric(options.n,\n                                                     gen_seed,\n                                                     options.p,\n                                                     options.use_random_weights,\n                                                     options.verbosity,\n                                                 options.use_stupid_tree_gen);\n  } else if (0 == strcmp(\"Binary-0-2\", options.gen_method.c_str())) {\n    if (false == (options.n & 0x1)) {\n      std::cerr << \"Binary-0-2 can only generate odd number of nodes\\\n due to a shortcoming of Devroye's algorithm. Sorry\" << std::endl;\n      exit(-1);\n    }\n    G = generate_Galton_Watson_t::generate_Binary_0_2\n                                              (options.n,\n                                               gen_seed,\n                                               options.p,\n                                               options.use_random_weights,\n                                               options.verbosity,\n                                               options.use_stupid_tree_gen);\n  } else if (0 == strcmp(\"Binary-0-1-2\", options.gen_method.c_str())) {\n    G = generate_Galton_Watson_t::generate_Binary_0_1_2\n                                              (options.n,\n                                               gen_seed,\n                                               options.use_random_weights,\n                                               options.verbosity,\n                                               options.use_stupid_tree_gen);\n  } else if (0 == strcmp(\"Graphviz\", options.gen_method.c_str())) {\n    /** Get the input file */\n    std::ifstream input_dot_file(options.dot_in.c_str());\n\n    /** Set the properties that you need to extract from the graph */\n    boost::dynamic_properties dp;\n    vertex_index_map_t index_map = boost::get(boost::vertex_index, G);\n    vertex_name_map_t name_map = boost::get(boost::vertex_name, G);\n    vertex_weight_map_t weight_map = boost::get(boost::vertex_distance, G);\n\n    dp.property(\"index\", index_map);\n    dp.property(\"name\", name_map);\n    dp.property(\"weight\", weight_map);\n\n    /** Read the graph --- note that indices are relabeled, which is fine */\n    boost::read_graphviz(input_dot_file, G, dp, \"name\");\n\n    /** Label it */\n    bfs_label(G);\n\n  } else {\n    std::cout << \"Chosen method of graph generation not supported\" \n              << std::endl;\n  }\n  return G;\n}\n\ntemplate <typename NameToIndexMap, \n          typename WeightMap>\ndouble path_length (const std::string& parent, \n                    const std::string& child,\n                    const NameToIndexMap& name_map,\n                    const WeightMap& weight_map,\n                    const dyck_options_t& options) {\n\n  double total_path_length = 0.0;\n\n  if (0<options.verbosity) {\n    std::cout << \"Path length \" << name_map.find(parent)->second << \" ---> \" \n              << name_map.find(child)->second << std::endl;\n  }\n\n  /** Get the first place where things mismatch */\n  std::string::const_iterator position = \n    std::mismatch (parent.begin(), parent.end(), child.begin()).second;\n\n  /** If they don't, we get to go one by one */\n  while (position != child.end()) {\n    const std::string current_vertex(child.begin(), position+1);\n    const int current_vertex_index = name_map.find(current_vertex)->second;\n    const double weight = boost::get(weight_map, current_vertex_index);\n    if (0<options.verbosity) {\n      std::cout << \"Adding \" << current_vertex_index << \" (code:\"\n              << current_vertex << \") \" \n              << \" of weight \" << weight << std::endl;\n    }\n    total_path_length += weight;\n    ++position;\n  }\n\n  return total_path_length;\n}\n\n/** total path length and generate trees by cutting things off */\n\nstd::pair<int,double>\nrun_one_lca_experiment(dyck_options_t& options,\n                       int& gen_seed,\n                       int& lca_seed,\n                       int& num_nodes_in_G) {\n  graph_type G;\n  vertex_name_map_t name_map;\n  vertex_weight_map_t weight_map;\n\n  /** Generate the seeds if needed */\n  lca_seed = (0>options.lca_seed)?generate_seed():options.lca_seed;\n  gen_seed = (0>options.seed)?generate_seed():options.seed;\n\n  if (options.verbosity) std::cout << \"Generating graph .... \" << std::flush;\n\n  do {\n    /** Generate a graph */\n    G = generate_one_graph (options, gen_seed);\n\n    /** Get the number of nodes in the graph */\n    vertex_iter_t v_begin, v_end;\n    boost::tie(v_begin, v_end) = boost::vertices(G);\n    num_nodes_in_G = std::distance(v_begin, v_end);\n\n    if (false==options.dot_in.empty()) {\n      options.n = num_nodes_in_G;\n    }\n  } while (num_nodes_in_G<options.n);\n  if (options.verbosity) std::cout << \"DONE\" << std::endl;\n\n  name_map = boost::get(boost::vertex_name, G);\n  weight_map = boost::get(boost::vertex_distance, G);\n\n  int num_lca_samples = num_nodes_in_G*options.percent_lca_samples;\n  std::vector<int> lca_vertices(num_lca_samples);\n  const std::string file_name = \n           boost::filesystem::path(options.dot_in).filename().string();\n\n  /** \n   * We want to generate some vertices from the given set of vertices \n   * randomly and form the LCA tree. The thing wrong here is that my\n   * compiler doesn't implement std::random_sample and std::iota. Hence\n   * that long stupid way to sample elements from the vertex.\n   *\n   */\n  std::vector<int> all_vertices(num_nodes_in_G-1);\n  for (size_t i=0; i<all_vertices.size(); ++i) all_vertices[i]=(i+1);\n  boost::mt19937 engine(lca_seed);\n  random_functor_t<boost::mt19937> shuffle_prng (engine);\n  std::random_shuffle (all_vertices.begin(), all_vertices.end(), shuffle_prng);\n\n  if (options.sample_leaves) {\n    /**\n     * We want to only sample leaf nodes. The logic behind this is that we want\n     * to only sample \"original\" data points. In case of Arvind's data, the \n     * intermediate nodes are formed by hierarchical clustering and hence are \n     * not original. There are two things to do:\n     *\n     * (1) Iterate through the shuffled vertices and \n     *    -- copy those vertices that are leaves (up to num_lca_samples)\n     *    -- count the number of leaves\n     * (2) If num_leaves>num_lca_samples, we are golden. However, if this is \n     *     not the case (num_lca_samples>=num_leaves), then we want to cut \n     *     down on the number of samples.\n     */\n    int num_leaves = 0;\n    std::vector<int>::iterator lca_vertices_iter = lca_vertices.begin();\n    for (size_t i=0; i<all_vertices.size(); ++i) {\n      const int vertex_id = all_vertices[i];\n      if (0 == boost::out_degree(vertex_id, G)) {\n        if (num_leaves<num_lca_samples) { \n          *lca_vertices_iter = vertex_id;\n          ++lca_vertices_iter; \n        }\n        ++num_leaves;\n      }\n    }\n\n    if (num_lca_samples>=num_leaves) {\n      std::cerr << file_name << \": Sampling \" << num_lca_samples \n                << \" from \" << num_leaves;\n      num_lca_samples = 0.5*num_leaves;\n      std::cerr << \". Changing to sample \" << num_lca_samples << std::endl;\n      if (0==num_lca_samples) {\n        std::cerr << \"Error: sampling \" << num_lca_samples << std::endl;\n        exit(-3);\n      }\n      lca_vertices.resize(num_lca_samples);\n    }\n  } else {\n    /**\n     * Approach 1:\n     * We don't care whether we are sampling leaf or non-leaf nodes. As long as\n     * it's a non-root node, we are golden.  All we are doing here is creating\n     * an array of elements 1...(n-1), randomly shuffling it and then picking\n     * the top num_lca_samples.\n     */\n    std::copy (all_vertices.begin(), \n               all_vertices.begin() + num_lca_samples,\n               lca_vertices.begin());\n  }\n\n  /**\n   * Now, build the new tree with intermediate vertices and figure out the \n   * number of edges in the new tree using the LCA algorithm to create \n   * intermediate nodes.\n   */\n  if (0<options.verbosity) {\n    std::cout << \"Sampled LCA vertices are: \" << std::endl;\n    for (size_t i=0; i<lca_vertices.size(); ++i) \n      std::cout << lca_vertices[i] << \" (code:\" \n              << boost::get(name_map, lca_vertices[i]) << \")\" << std::endl;\n  }\n\n  std::map<std::string, int> all_vertices_name_map;\n\n  /** Create a name map */\n  for (size_t i=0; i<num_nodes_in_G; ++i)\n    all_vertices_name_map[boost::get(name_map, i)] = i;\n\n  /** 2. Join the vertices one by one to get the LCA tree */\n  std::map<std::string,int> new_lca_vertices;\n  typedef std::map<std::string, int>::const_iterator MapIterator;\n  new_lca_vertices[boost::get(name_map, 0)] = 0;\n\n  std::set<std::pair<int,int> > added_edges_set;\n  double total_path_length = 0.0;\n  int total_num_edges = 0; \n\n  for (size_t i=0; i<(lca_vertices.size()-1); ++i) {\n    for (size_t j=(i+1); j<lca_vertices.size(); ++j) {\n      /** Figure out the vertices we are dealing with */\n      const int me = lca_vertices[i];\n      const std::string my_name = boost::get(name_map, me);\n      const int you = lca_vertices[j];\n      const std::string your_name = boost::get(name_map, you);\n      \n      /** Push these two vertices into new LCA tree --- duplicate elim by map */\n      new_lca_vertices[my_name] = me;\n      new_lca_vertices[your_name] = you;\n      \n      /** Find the LCA, which also happens to be the common prefix */\n      const std::string our_common_prefix = \n        std::string(my_name.begin(),\n        std::mismatch(my_name.begin(), my_name.end(), your_name.begin()).first);\n      \n      /** Search for the common ancestor */\n      const bool found_ancestor = (new_lca_vertices.end() != \n                            new_lca_vertices.find(our_common_prefix));\n      \n      if (false == found_ancestor) {\n      const int our_common_ancestor = all_vertices_name_map[our_common_prefix];\n        new_lca_vertices[our_common_prefix] = our_common_ancestor;\n      }\n      \n      /** If the common prefix is not found, then insert it in */\n      if (0<options.verbosity) {\n        std::cout << \"Ancestor of \" << me << \" (code:\" << my_name << \") and \" \n                  << you << \" (code:\" << your_name << \") is \"\n                  << new_lca_vertices[our_common_prefix] << \" (code:\" \n            << our_common_prefix << \")\" << (found_ancestor?\" (already present)\": \n                                                    \" (had to be added)\")\n            << std::endl;\n      }\n    }\n  }\n\n  if (options.sample_leaves) {\n    std::cerr << file_name << \": \" << num_lca_samples \n              << \" lca-tree (|V|=\" << new_lca_vertices.size() \n              << \", |E|=\" << 2*num_lca_samples-1 << \")\" << std::endl;\n  }\n\n  if (0<options.verbosity) {\n    std::cout << \"Sampled (and built) LCA tree has \" << new_lca_vertices.size()\n              << \" nodes and these vertices: \" << std::endl;\n    for (MapIterator iter = new_lca_vertices.begin(); \n         iter != new_lca_vertices.end(); \n         ++iter) {\n      std::cout << iter->second << \" (code:\" << iter->first << \")\" << std::endl;\n    }\n  }\n\n  const MapIterator range_first = new_lca_vertices.begin();\n  MapIterator range_last = range_first; \n  ++range_last;\n  MapIterator iter = range_last;\n  while (iter != new_lca_vertices.end()) {\n    /** find parent of *iter */\n    MapIterator lowest_parent = range_first;\n    MapIterator first = range_first;\n    while (first != range_last) {\n      if (0<options.verbosity) {\n        std::cout << \"Testing \" << first->second << \" for \" \n                    << iter->second << std::endl;\n      }\n      if (first->first.end()==\n          std::mismatch(first->first.begin(), \n                        first->first.end(),\n                        iter->first.begin()).first) {\n        if (0<options.verbosity) {\n          std::cout << first->second << \" is an ancestor of \" \n                    << iter->second << std::endl;\n        }\n        lowest_parent = first;\n      }\n      ++first;\n    }\n\n    if (0<options.verbosity) {\n      std::cout << lowest_parent->second << \" is the LCA of \" \n                << iter->second << std::endl;\n    }\n\n    /** compute distance from parent to *iter */\n    total_path_length += path_length(lowest_parent->first, iter->first, \n                                    all_vertices_name_map, weight_map, options);\n    ++total_num_edges;\n\n    /** increment range_last */\n    ++range_last;\n    ++iter;\n  }\n\n  print_tree(G, options);\n\n  return std::pair<int,double>(total_num_edges, total_path_length);\n}\n\nvoid run_one_experiment (const dyck_options_t& options,\n                         int& gen_seed,\n                         int& mle_seed,\n                         int& num_nodes_in_G,\n                         int& vertex_to_find,\n                         double& vertex_height,\n                         double& mean_height) {\n  graph_type G;\n  vertex_name_map_t name_map;\n  vertex_weight_map_t weight_map;\n\n  do {\n    /** Generate a graph */\n    G = generate_one_graph (options, gen_seed);\n\n    /** Get the number of nodes in the graph */\n    vertex_iter_t v_begin, v_end;\n    boost::tie(v_begin, v_end) = boost::vertices(G);\n    num_nodes_in_G = std::distance(v_begin, v_end);\n  } while (num_nodes_in_G < (options.n));\n\n  name_map = boost::get(boost::vertex_name, G);\n  weight_map = boost::get(boost::vertex_distance, G);\n\n  /** \n   * If we want to identify the height of a random (non-root) vertex in the\n   * tree, then we want generate a random number between [1,n), where n is \n   * the number of nodes in the generated tree.\n   */\n  vertex_to_find = -1;\n  mle_seed = (0>options.mle_seed)?generate_seed():options.mle_seed;\n  boost::mt19937 engine (mle_seed);\n  boost::uniform_int<int> dist (1, num_nodes_in_G-1);\n  vertex_to_find = dist(engine);\n\n  /** Now, compute the Dyck path using depth-first search */\n  std::vector<double> y_axis;\n  vertex_height = dyck_path (G, name_map, weight_map, \n                             std::back_inserter(y_axis), \n                             vertex_to_find, \n                             options.verbosity);\n\n  /** Compute the mean height of the tree */\n  assert (y_axis.size() == 2*num_nodes_in_G);\n  mean_height = 0.0;\n  for (size_t i=0; i<y_axis.size(); ++i) mean_height += y_axis[i];\n  mean_height /= (2*pow(num_nodes_in_G,1.5));\n\n  print_tree (G, options);\n\n#pragma omp critical\n  if (options.print_path) {\n    /** Write stuff out where needed */\n    /** We need to ensure that the x-axis is such that the slope is always 45*/\n    std::vector<double> x_axis(y_axis.size());\n    x_axis[0] = 0;\n    for (size_t i=1; i<x_axis.size(); ++i)\n      x_axis[i] = x_axis[i-1] + std::abs(y_axis[i] - y_axis[i-1]);\n\n    /** Remember, DO NOT PRINT THE LAST INDEX -- this is an artifact of DFS */\n    std::ostream* output; \n    if (0==strcmp(\"stdout\", options.dyck_out.c_str())) output = &(std::cout);\n    else output = new std::ofstream(options.dyck_out.c_str());\n    for (size_t i=0; i<(x_axis.size()-1); ++i) {\n      *output << x_axis[i] << \"  \" << y_axis[i] << std::endl;\n    }\n    if (0!=strcmp(\"stdout\", options.dyck_out.c_str())) delete output;\n  }\n\n}\n\nint main (int argc, char** argv) {\n  dyck_options_t options (argc, argv);\n  if (options.exit_on_return) { return -1; }\n\n  if (1<options.verbosity) options.pretty_print();\n\n  std::vector<std::string> dot_file_names;\n  if (options.dot_in_dir != \"\") {\n    dot_file_names = get_dot_files(options.dot_in_dir);\n    options.num_trials = dot_file_names.size();\n    options.gen_method = \"Graphviz\";\n  } \n\n  std::vector<int> gen_seed_vec(options.num_trials);\n  std::vector<int> mle_seed_vec(options.num_trials);\n  std::vector<int> lca_seed_vec(options.num_trials);\n  std::vector<int> num_nodes_vec(options.num_trials);\n  std::vector<int> vertex_to_find_vec(options.num_trials);\n  std::vector<double> vertex_height_vec(options.num_trials);\n  std::vector<double> mean_height_vec(options.num_trials);\n\n  if (options.measure_lca) {\n\n    char header_string[1024];\n    int h_count = sprintf (header_string, \n            \"%9s %9s %2s %10s %2s %7s %7s %7s %5s %12s %12s\",\n                \"dist-type\", \"f-name\", \"k\", \"p\", \"lm\", \"n\",\n                \"n-tru\", \"n-smpl\", \"lca-edges\", \"lca-path-ln\");\n    std::cout << header_string << std::endl;\n\n#pragma omp parallel for num_threads(options.num_threads)\n    for (int i=0; i<options.num_trials; ++i) {\n      /**\n       * TODO: This is a hack. What we are doing is that we are checking if \n       * the input method is a DOT file. If so, we are checking if the input\n       * mentioned is actually a directory listing of files. In this case, \n       * we will populate options.dot_in to be a different file name every \n       * single time.\n       */\n      if (false==options.dot_in_dir.empty()) {\n        options.dot_in = dot_file_names[i];\n      }\n      std::pair<int,double> lca_result = \n        run_one_lca_experiment (options, gen_seed_vec[i], \n                                lca_seed_vec[i], num_nodes_vec[i]); \n\n      char value_string[1024];\n      const std::string file_name = \n              boost::filesystem::path(options.dot_in).filename().string();\n      int v_count = sprintf (value_string, \n               \"%9s %9s %2d %.4e %2d %7d %7d %6.2f %12d %.6e\",\n                               options.gen_method.c_str(),\n                               file_name.c_str(),\n                               options.k,\n                               options.p,\n                               options.lambda,\n                               options.n,\n                               num_nodes_vec[i],\n                               options.percent_lca_samples,\n                               lca_result.first,\n                               lca_result.second);\n      std::cout << value_string << std::endl;\n    }\n\n    goto END;\n  }\n\n#pragma omp parallel for num_threads(options.num_threads)\n  for (int i=0; i<options.num_trials; ++i) {\n    /**\n     * TODO: This is a hack. What we are doing is that we are checking if \n     * the input method is a DOT file. If so, we are checking if the input\n     * mentioned is actually a directory listing of files. In this case, \n     * we will populate options.dot_in to be a different file name every \n     * single time.\n     */\n    if (false==options.dot_in_dir.empty()) {\n      options.dot_in = dot_file_names[i];\n    }\n    run_one_experiment (options, gen_seed_vec[i], mle_seed_vec[i], \n                        num_nodes_vec[i], vertex_to_find_vec[i], \n                        vertex_height_vec[i], mean_height_vec[i]);\n  }\n\n  double true_var;\n  if (0 == strcmp(\"Poisson\", options.gen_method.c_str())) \n    true_var=options.lambda;\n  else if (0 == strcmp(\"Binomial\", options.gen_method.c_str())) \n    true_var=options.k*options.p*(1-options.p);\n  else if (0 == strcmp(\"Geometric\", options.gen_method.c_str()))\n    true_var=(1-options.p)/(options.p*options.p);\n  else if (0 == strcmp(\"Binary-0-2\", options.gen_method.c_str()))\n    true_var=1;\n  else if (0 == strcmp(\"Binary-0-1-2\", options.gen_method.c_str()))\n    true_var=2./3.;\n\n  if (options.dump_numbers) {\n    for (int i=0; i<options.num_trials; ++i) {\n      double x_i = (1.0/(sqrt((double)num_nodes_vec[i])))*vertex_height_vec[i];\n      printf (\" %-8.3f\", x_i);\n    }\n    printf (\"\\n\");\n    for (int i=0;i<options.num_trials;++i) {\n      printf(\" %-8.3f\", mean_height_vec[i]);\n    }\n    printf (\"\\n\");\n  }\n\n  if (options.measure_mle) {\n    if (options.verbosity) {\n      char header_string[1024];\n      int h_count = sprintf (header_string, \n            \"%9s %9s %2s %10s %2s %7s %7s %7s %7s %12s %12s %12s\", \n                \"dist-type\", \"filename\", \"k\", \"p\", \"lm\", \"n\",\n                \"n-tru\", \"node-#\",\"height-raw\",\"height-nrmzd\",\"height-mean\");\n      if (1<options.verbosity)\n   sprintf (&(header_string[h_count]), \" %10s %10s\", \"gen-seed\", \"MLE-seed\");\n      std::cout << header_string << std::endl;\n    }\n\n    double sum_of_x_i_sqr = 0.0;\n    double mean_of_x_i_sqr = 0.0;\n    for (int i=0; i<options.num_trials; ++i) {\n      double x_i = (1.0/(sqrt((double)num_nodes_vec[i])))*vertex_height_vec[i];\n      sum_of_x_i_sqr += x_i*x_i;\n      mean_of_x_i_sqr += x_i;\n\n      if (options.verbosity) {\n        char value_string[1024];\n        const std::string file_name = \n              boost::filesystem::path(dot_file_names[i]).filename().string();\n        int v_count = sprintf (value_string, \n               \"%9s %9s %2d %.4e %2d %7d %7d %7d %.6e %.6e %.6e\",\n                               options.gen_method.c_str(),\n                               file_name.c_str(),\n                               options.k,\n                               options.p,\n                               options.lambda,\n                               options.n,\n                               num_nodes_vec[i],\n                               vertex_to_find_vec[i],\n                               vertex_height_vec[i],\n                               x_i,\n                               mean_height_vec[i]);\n        if (1<options.verbosity)\n          sprintf (&(value_string[v_count]), \" %10u %10u\", \n                          gen_seed_vec[i], mle_seed_vec[i]);\n        std::cout << value_string << std::endl;\n      }\n    }\n    mean_of_x_i_sqr /= options.num_trials;\n    mean_of_x_i_sqr *= mean_of_x_i_sqr;\n\n    double mle_estimate_var = (2*options.num_trials)/sum_of_x_i_sqr;\n    double ano_estimate_var = PI/(2*mean_of_x_i_sqr);\n\n    std::cout << \"True variance = \" << true_var\n              << \" MLE = \" << mle_estimate_var \n              << \" Another = \" << ano_estimate_var << std::endl;\n    std::cout << \" Mean of x_i^2 =  \" << mean_of_x_i_sqr << std::endl;\n  }\n\n  if (options.test_confidence) {\n    int num_batches = options.num_trials / options.batch_size;\n    int num_contained = 0;\n\n    int num_nodes = num_nodes_vec[0];\n    bool experimental_error = false;\n    for (int i=1; i<options.num_trials; ++i) {\n      if (num_nodes != num_nodes_vec[i]) {\n        experimental_error = true;\n        break;\n      }\n    }\n\n    if (experimental_error) {\n      std::cout << \"Run this experiment again, please\" << std::endl;\n      goto END;\n    }\n\n    std::vector<double> other_variances;\n    if (0 == strcmp(\"Poisson\", options.gen_method.c_str())) {\n      other_variances.push_back(1 - 1./2.);\n      other_variances.push_back(1 - 1./3.);\n      other_variances.push_back(1 - 1./4.);\n      other_variances.push_back(1 - 1./5.);\n      other_variances.push_back(2);\n    } else if (0 == strcmp(\"Binomial\", options.gen_method.c_str())) {\n      other_variances.push_back(1);\n      other_variances.push_back(2);\n      other_variances.push_back(2.0/3.0);\n    } else if (0 == strcmp(\"Geometric\", options.gen_method.c_str())) {\n      other_variances.push_back(1);\n      other_variances.push_back(1 - 1./2.);\n      other_variances.push_back(1 - 1./3.);\n      other_variances.push_back(1 - 1./4.);\n      other_variances.push_back(1 - 1./5.);\n    } else if (0 == strcmp(\"Binary-0-2\", options.gen_method.c_str())) {\n      other_variances.push_back(1 - 1./2.);\n      other_variances.push_back(1 - 1./4.);\n      other_variances.push_back(1 - 1./5.);\n      other_variances.push_back(2);\n      other_variances.push_back(2.0/3.0);\n    } else if (0 == strcmp(\"Binary-0-1-2\", options.gen_method.c_str())) {\n      other_variances.push_back(1 - 1./2.);\n      other_variances.push_back(1 - 1./3.);\n      other_variances.push_back(1 - 1./4.);\n      other_variances.push_back(1 - 1./5.);\n      other_variances.push_back(1);\n      other_variances.push_back(2);\n    }\n    std::vector<double> power_against_others (other_variances.size(), 0.0);\n\n    boost::math::chi_squared chi_dist (2*options.batch_size);\n    const double a = boost::math::quantile(chi_dist, 0.025);\n    const double b = boost::math::quantile(chi_dist, 0.975);\n    \n    for (int i=0; i<options.num_trials; i+=options.batch_size) {\n      double sum_of_x_j_sqr = 0.0;\n      for (int j=0; j<options.batch_size; ++j) {\n        double x_j = (1.0/(sqrt((double)num_nodes_vec[i+j])))*\n                                        vertex_height_vec[i+j];\n        sum_of_x_j_sqr += x_j*x_j;\n      }\n      \n      const double A = a/sum_of_x_j_sqr;\n      const double B = b/sum_of_x_j_sqr;\n      if (A <= true_var && B >= true_var) ++num_contained;\n      for (int l=0; l<other_variances.size(); ++l)\n        if (A <= other_variances[l] && B >= other_variances[l]) \n          power_against_others[l]+=1;\n\n      if (1<options.verbosity) {\n        std::cout << \"Lower = \" << A << \" Upper = \" << B  \n                  << \" sum_of_x_j_sqr = \" << sum_of_x_j_sqr << std::endl;\n      }\n    }\n    const double contained = \n       100*static_cast<double>(num_contained)/static_cast<double>(num_batches);\n\n    printf (\"%12s %5d %3d %7.3f%%(tru-var=%4.3f) \", options.gen_method.c_str(),\n                                                    num_batches,\n                                                    options.batch_size,\n                                                    contained,\n                                                    true_var);\n    for (int l=0; l<other_variances.size(); ++l) \n      printf (\" %7.3f%%(var=%4.3f)\", 100*(power_against_others[l]/num_batches),\n                                     other_variances[l]);\n    printf (\"\\n\");\n  }\n\nEND:\n\n  return 0;\n}\n", "meta": {"hexsha": "8d4488804ebdb9002b596eeb040745799b2f8712", "size": 29962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "harness.cpp", "max_stars_repo_name": "karthikbharath/Trees_DyckPaths", "max_stars_repo_head_hexsha": "6fc9b5e603aa8bb89cb68964a06d3992f32085a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "harness.cpp", "max_issues_repo_name": "karthikbharath/Trees_DyckPaths", "max_issues_repo_head_hexsha": "6fc9b5e603aa8bb89cb68964a06d3992f32085a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "harness.cpp", "max_forks_repo_name": "karthikbharath/Trees_DyckPaths", "max_forks_repo_head_hexsha": "6fc9b5e603aa8bb89cb68964a06d3992f32085a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9265822785, "max_line_length": 81, "alphanum_fraction": 0.5810026033, "num_tokens": 7464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.43692239734481725}}
{"text": "\n\n//\n// Created by mknoe on 04.04.2021.\n//\n#include <windows.h>        // Must have for Windows platform builds\n\n#include <cmath>\n#include <cstdio>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <chrono>\n#include <cstdlib>\n#include <utility>\n#include <vector>\n#include <algorithm>\n\n#include <iterator>\n#include \"../exercise01/drawLine.h\"\n#include \"../basics.h\"\n#include \"../bench.h\"\n#include \"../exercise02/drawCircle.h\"\n#include \"bezier.h\"\n#include <boost/math/interpolators/cardinal_cubic_b_spline.hpp>\n#include <boost/random.hpp>\n#include <boost/math/statistics/bivariate_statistics.hpp>\n#include <random>\n#include <boost/math/tools/roots.hpp>\n#include \"splines.cpp\"\n#include \"splines.h\"\n#include \"vec3.hpp\"\n#include <boost/config.hpp>\n#include <cstddef>\n#include <iosfwd>\n#include <GL/glu.h>\n\n//https://chi3x10.wordpress.com/2009/10/18/de-boor-algorithm-in-c/\nclass Point {\npublic:\n    Point() {\n        x = 0.;\n        y = 0.;\n        z = 0.;\n    };\n\n    // copy operator\n    Point operator=(const Point &pt);\n\n    Point operator+(const Point &pt) const;\n\n    //Point operator-(const Point &pt) const;\n    Point operator*(double m) const;\n\n    Point operator/(double m) const;\n\n    double x, y, z;\n};\n\nPoint Point::operator=(const Point &pt) {\n    x = pt.x;\n    y = pt.y;\n    z = pt.z;\n    return *this;\n}\n\nPoint Point::operator+(const Point &pt) const {\n    Point temp;\n    temp.x = x + pt.x;\n    temp.y = y + pt.y;\n    temp.z = z + pt.z;\n    return temp;\n}\n\nPoint Point::operator*(double m) const {\n    Point temp;\n    temp.x = x * m;\n    temp.y = y * m;\n    temp.z = z * m;\n    return temp;\n}\n\nPoint Point::operator/(double m) const {\n    Point temp;\n    temp.x = x / m;\n    temp.y = y / m;\n    temp.z = z / m;\n    return temp;\n}\n\nCordinate deBoorRecursiv(int k, int degree, int i, double x, vector<double> knots, vector<Cordinate> ctrlPoints) {\n    // Please see wikipedia page for detail\n    // note that the algorithm here kind of traverses in reverse order\n    // comapred to that in the wikipedia page\n    if (k == 0)\n        return ctrlPoints[i];\n    else {\n        double alpha = (x - knots[i]) / (knots[i + degree + 1 - k] - knots[i]);\n        return (deBoorRecursiv(k - 1, degree, i - 1, x, knots, ctrlPoints) * (1 - alpha) +\n                deBoorRecursiv(k - 1, degree, i, x, knots, ctrlPoints) * alpha);\n    }\n}\n\nCordinate deBoor(int k, double x, vector<double> t, vector<Cordinate> c, int p) {\n/*\nk: Index of knot interval that contains x.\nx: Position.\nt: Array of knot positions, needs to be padded as described above.\nc: Array of control points.\np: Degree of B-spline.\n */\n    vector<Cordinate> d{};\n    for (int j = 0; j < p + 1; ++j) {\n        d.push_back(c[j + k - p]);\n    }\n    for (int r = 1; r < p + 1; ++r) {\n        for (int j = p; j > r - 1; --j) {\n            int alpha = (x - t[j + k - p]) / (t[j + 1 + k - r] - t[j + k - p]);\n            d[j] = (1.0 - alpha) * d[j - 1] + alpha * d[j];\n        }\n    }\n    return d[p];\n}\n\nint WhichInterval(double x, vector<double> knot, int ti) {\n    for (int i = 1; i < ti - 1; i++) {\n        if (x < knot[i])\n            return (i - 1);\n        else if (x == knot[ti - 1])\n            return (ti - 1);\n    }\n    return -1;\n}\n\n\nCordinate bSpline(vector<Cordinate> d, int n, vector<double> t, int i) {\n    auto m = d.size() - 1;\n    int ts;\n    if (t[i + 1] - 1 >= t[i])\n        ts = t[i + 1] - 1;\n    else\n        ts = t[i];\n\n    // if (0 < i <= m) throw new exception();\n\n    vector<vector<Cordinate>> d0{};\n    for (int j = 0; j < n; ++j) {\n        d0.emplace_back();\n        for (int l = i - n + j; l < i; l++) {\n            if (j == 0) {\n                d0[0].push_back(d[l]);\n            } else {\n                double tl = (ts - t[l]) / t[l + n - j] - t[l];\n                d0[j][l] = (1 - tl) * d0[j - 1][l - 1] + tl * d0[j - 1][l];\n            }\n        }\n    }\n    return d0[n][i];\n}\n\nCordinate closeBSpline(vector<Cordinate> d, int n, vector<double> t, int i) {\n    auto m = d.size() - 1;\n    int ts;\n    if (t[i + 1] - 1 >= t[i])\n        ts = t[i + 1] - 1;\n    else\n        ts = t[i];\n\n    //  if (0 < i <= m) throw new exception();\n\n    vector<vector<Cordinate>> d0{};\n\n    for (int j = 0; j < n; ++j) {\n        int l = i - n + j - 1;\n        do {\n            l++;\n            if (l < 0) {\n                l = l + m + 1;\n                ts = ts - t[0] + t[m + 1];\n            } else {\n                if (l >= m + 1) {\n                    l = l - m - 1;\n                    ts = ts - t[m + 1] + t[0];\n                }\n            }\n            if (j == 0) {\n                d0[0].push_back(d[l]);\n            } else {\n                double tl = (ts - t[l]) / t[l + n - j] - t[l];\n                d0[j][l] = (1 - tl) * d0[j - 1][l - 1] + tl * d0[j - 1][l];\n            }\n        } while (l != i);\n    }\n    return d0[n][i];\n}\n\n\nint main(int argc, char *argv[]) {\n\n    RGBPixel color = RGBPixel(40, 40, 40);\n    RGBPixel color2 = RGBPixel(0, 255, 255);\n    RGBPixel color3 = RGBPixel(0, 0, 255);\n\n    Display::init(argc, argv, 256, 256);\n    auto display = Display::getInstance();\n    ////////// put your framebuffer drawing code here /////////////\n\n\n\n    const Cordinate P1 = Cordinate(30, 45);\n    const Cordinate P2 = Cordinate(35, 100);\n    const Cordinate P3 = Cordinate(70, 95);\n    const Cordinate P4 = Cordinate(80, 35);\n\n    std::vector<std::vector<double>> vList = {};\n    const vector<Cordinate> list = {P1, P2, P3, P4};\n\n\n    int k{3};\n    vector<double> t{0, 0, 0, 0.5, 0.5, 0.5, 1, 1, 1};\n    vector<Cordinate> c{P1, P2, P3, P4};\n    auto degree = 2;\n    int n = 2;\n    vector<Cordinate> points;\n//    for (int i = 0; i < list.size() - 1; i++) {\n//        auto point = bSpline(list, n, t, i);\n//\n//        points.push_back(point);\n//        display->setPixel(point, color);\n//\n//    }\n\n    for (int x = 0; x < display->RESOLUTION; x++) {\n        Cordinate b = deBoor(k, x, t, c, degree);\n        Cordinate b2 = deBoorRecursiv(k, degree, WhichInterval(x, t, t.size()), x, t, c);\n        display->setPixel(b, color3);\n        display->setPixel(b2, color2);\n        cout << \"b= \" << b << \"\\n\";\n        cout << \"b2= \" << b2 << \"\\n\";\n    }\n    drawList(list, color);\n\n\n\n\n\n    /////////////////////////////////\n    glutMainLoop();\n    return 0;\n}", "meta": {"hexsha": "e21be0820da01462f5d1586159ecbc15a2f6417c", "size": 6258, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exercise03/exercise03.cpp", "max_stars_repo_name": "knoeferl/vertiefung_mi_computergrafik", "max_stars_repo_head_hexsha": "e48f42d48a6d7ad8744b47c6dfebb01228adac6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exercise03/exercise03.cpp", "max_issues_repo_name": "knoeferl/vertiefung_mi_computergrafik", "max_issues_repo_head_hexsha": "e48f42d48a6d7ad8744b47c6dfebb01228adac6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exercise03/exercise03.cpp", "max_forks_repo_name": "knoeferl/vertiefung_mi_computergrafik", "max_forks_repo_head_hexsha": "e48f42d48a6d7ad8744b47c6dfebb01228adac6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.032, "max_line_length": 114, "alphanum_fraction": 0.5028763183, "num_tokens": 1998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4369223902605898}}
{"text": "// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n// Copyright (c) 2014 cDc and Pierre MOULON.\n\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this\n// file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"openMVG/multiview/rotation_averaging_l1.hpp\"\n#include \"openMVG/numeric/l1_solver_admm.hpp\"\n\n#ifdef HAVE_BOOST\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/foreach.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\nusing namespace boost;\n#else\n#include \"lemon/adaptors.h\"\n#include \"lemon/dfs.h\"\n#include \"lemon/kruskal.h\"\n#include \"lemon/list_graph.h\"\n#include \"lemon/path.h\"\nusing namespace lemon;\n#endif\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n\n#include <Eigen/Cholesky>\n#include <Eigen/SparseCholesky>\n\n#include <queue>\n\nnamespace openMVG   {\nnamespace rotation_averaging  {\nnamespace l1  {\n\n/////////////////////////\n\n// given an array of values, compute the X84 threshold as in:\n// Hampel FR, Rousseeuw PJ, Ronchetti EM, Stahel WA\n// \"Robust Statistics: the Approach Based on Influence Functions\"\n// Wiley Series in Probability and Mathematical Statistics, John Wiley & Sons, 1986\n// returns the pair(median,trust_region)\n// upper-bound threshold = median+trust_region\n// lower-bound threshold = median-trust_region\ntemplate<typename TYPE>\ninline std::pair<TYPE, TYPE>\nComputeX84Threshold(const TYPE* const values, uint32_t size, TYPE mul=TYPE(5.2))\n{\n  assert(size > 0);\n  typename std::vector<TYPE> data(values, values+size);\n  typename std::vector<TYPE>::iterator mid = data.begin() + size / 2;\n  std::nth_element(data.begin(), mid, data.end());\n  const TYPE median = *mid;\n  // threshold = 5.2 * MEDIAN(ABS(values-median));\n  for (size_t i=0; i<size; ++i)\n    data[i] = std::abs(values[i]-median);\n  std::nth_element(data.begin(), mid, data.end());\n  return {median, mul*(*mid)};\n} // ComputeX84Threshold\n\n\n/////////////////////////\n\nusing Matrix3x3 = openMVG::Mat3;\nusing IndexArr = std::vector<uint32_t>;\n\n// find the shortest cycle for the given graph and starting vertex\nstruct Node {\n  using InternalType = IndexArr;\n  InternalType edges; // array of vertex indices\n};\nusing NodeArr = std::vector<Node>;\n\nstruct Link {\n  uint32_t ID; // node index\n  uint32_t parentID;// parent link\n  inline Link(uint32_t ID_=0, uint32_t parentID_=0) : ID(ID_), parentID(parentID_) {}\n};\nusing LinkQue = std::queue<Link>;\n\n#ifdef HAVE_BOOST\nusing edge_property_t = boost::property<boost::edge_weight_t, float>;\nusing graph_t = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, uint32_t, edge_property_t>;\nusing vertex_t = graph_t::vertex_descriptor;\nusing edge_t = graph_t::edge_descriptor;\nusing edge_iter = boost::graph_traits<graph_t>::edge_iterator;\n#else\nusing graph_t = lemon::ListGraph;\nusing map_EdgeMap = graph_t::EdgeMap<double>;\n#endif\nusing MapEdgeIJ2R = std::map<std::pair<uint32_t,uint32_t>, Matrix3x3>;\n\n// Look for the maximum spanning tree along the graph of relative rotations\n// since we look for the maximum spanning tree using a minimum spanning tree algorithm\n// weight are negated.\nuint32_t FindMaximumSpanningTree(const RelativeRotations& RelRs, graph_t& g, MapEdgeIJ2R& mapIJ2R, NodeArr& minGraph)\n{\n  assert(!RelRs.empty());\n#ifdef HAVE_BOOST\n  for (size_t p = 0; p < RelRs.size(); ++p) {\n    const RelativeRotation& relR = RelRs[p];\n    boost::add_edge(relR.i, relR.j, - relR.weight, g);\n    mapIJ2R[{relR.i, relR.j}] = relR.Rij;\n    mapIJ2R[{relR.j, relR.i}] = relR.Rij.transpose();\n  }\n  // find the minimum spanning tree\n  const size_t nViews = boost::num_vertices(g);\n  minGraph.resize(nViews);\n  std::vector<edge_t> spanningTree;\n  boost::kruskal_minimum_spanning_tree(g, std::back_inserter(spanningTree));\n  for (std::vector<edge_t>::const_iterator ei=spanningTree.begin(); ei!=spanningTree.end(); ++ei) {\n    const edge_t& edge = *ei;\n    minGraph[edge.m_source].edges.push_back(edge.m_target);\n    minGraph[edge.m_target].edges.push_back(edge.m_source);\n  }\n  const size_t nEdges = spanningTree.size();\n  return nEdges;\n#else\n\n  //A-- Compute the number of node we need\n  std::set<uint32_t> setNodes;\n  for (size_t p = 0; p < RelRs.size(); ++p) {\n    const RelativeRotation& relR = RelRs[p];\n    setNodes.insert(relR.i);\n    setNodes.insert(relR.j);\n  }\n\n  //B-- Create a node graph for each element of the set\n  using map_NodeT = std::map<uint32_t, graph_t::Node>;\n  map_NodeT map_index_to_node;\n  for (const auto & iter : setNodes)\n  {\n    map_index_to_node[iter] = g.addNode();\n  }\n\n  //C-- Create a graph from RelRs with weighted edges\n  map_EdgeMap map_edgeMap(g);\n  for (size_t p = 0; p < RelRs.size(); ++p) {\n    const RelativeRotation& relR = RelRs[p];\n    mapIJ2R[{relR.i, relR.j}] = relR.Rij;\n    mapIJ2R[{relR.j, relR.i}] = relR.Rij.transpose();\n\n    // add edge to the graph\n    graph_t::Edge edge =  g.addEdge(map_index_to_node[relR.i], map_index_to_node[relR.j]);\n    map_edgeMap[ edge ] = - relR.weight;\n  }\n\n  //D-- Compute the MST of the graph\n  std::vector<graph_t::Edge> tree_edge_vec;\n  lemon::kruskal(g, map_edgeMap, std::back_inserter(tree_edge_vec));\n\n  const size_t nViews = lemon::countNodes(g);\n  minGraph.resize(nViews);\n\n  //E-- Export compute MST\n  for (size_t i= 0; i < tree_edge_vec.size(); i++)\n  {\n    minGraph[g.id(g.u(tree_edge_vec[i]))].edges.push_back(g.id(g.v(tree_edge_vec[i])));\n    minGraph[g.id(g.v(tree_edge_vec[i]))].edges.push_back(g.id(g.u(tree_edge_vec[i])));\n  }\n  return tree_edge_vec.size();\n#endif\n}\n//----------------------------------------------------------------\n\n\n// Filter the given relative rotations using the known global rotations\n// returns the number of inliers\nunsigned int FilterRelativeRotations(\n  const RelativeRotations& RelRs,\n  const Matrix3x3Arr& Rs,\n  float threshold,\n  std::vector<bool> * vec_inliers)\n{\n  assert(!RelRs.empty() && !Rs.empty());\n  assert(threshold >= 0);\n  // compute errors for each relative rotation\n  std::vector<float> errors(RelRs.size());\n  for (size_t r= 0; r<RelRs.size(); ++r) {\n    const RelativeRotation& relR = RelRs[r];\n    const Matrix3x3& Ri = Rs[relR.i];\n    const Matrix3x3& Rj = Rs[relR.j];\n    const Matrix3x3& Rij = relR.Rij;\n    const Mat3 eRij(Rj.transpose()*Rij*Ri);\n    const openMVG::Vec3 erij;\n    ceres::RotationMatrixToAngleAxis((const double*)eRij.data(), (double*)erij.data());\n    errors[r] = (float)erij.norm();\n  }\n  if (threshold == 0) {\n    // estimate threshold\n    const std::pair<float,float> res = ComputeX84Threshold(&errors[0], errors.size());\n    threshold = res.first+res.second;\n  }\n  if (vec_inliers)  {\n    vec_inliers->resize(RelRs.size());\n  }\n  // mark outliers\n  unsigned int nInliers = 0;\n  for (size_t r=0; r<errors.size(); ++r) {\n    const bool bInlier = errors[r] < threshold;\n    if (vec_inliers)\n      (*vec_inliers)[r] = bInlier;\n    if (bInlier)\n      ++nInliers;\n  }\n  return nInliers;\n} // FilterRelativeRotations\n//----------------------------------------------------------------\n\n\ndouble RelRotationAvgError\n(\n  const RelativeRotations& RelRs,\n  const Matrix3x3Arr& Rs,\n  double* pMin=nullptr,\n  double* pMax=nullptr\n)\n{\n#ifdef HAVE_BOOST\n  boost::accumulators::accumulator_set<double,\n    boost::accumulators::stats<\n      boost::accumulators::tag::min,\n      boost::accumulators::tag::mean,\n      boost::accumulators::tag::max>> acc;\n\n  for (int i=0; i < RelRs.size(); ++i) {\n    const RelativeRotation& relR = RelRs[i];\n    acc(openMVG::FrobeniusNorm(relR.Rij  - (Rs[relR.j]*Rs[relR.i].transpose())));\n  }\n  if (pMin)\n    *pMin = boost::accumulators::min(acc);\n  if (pMax)\n    *pMax = boost::accumulators::max(acc);\n  return boost::accumulators::mean(acc);\n#else\n  std::vector<double> vec_err(RelRs.size(), 0.0);\n  for (size_t i=0; i < RelRs.size(); ++i) {\n    const RelativeRotation& relR = RelRs[i];\n    vec_err[i] = openMVG::FrobeniusNorm(relR.Rij  - (Rs[relR.j]*Rs[relR.i].transpose()));\n  }\n  float min, max, mean, median;\n  minMaxMeanMedian(vec_err.begin(), vec_err.end(), min, max, mean, median);\n  if (pMin)\n    *pMin = min;\n  if (pMax)\n    *pMax = max;\n  return mean;\n#endif\n}\n//----------------------------------------------------------------\n\nvoid InitRotationsMST\n(\n  const RelativeRotations& RelRs,\n  Matrix3x3Arr& Rs,\n  const uint32_t nMainViewID\n)\n{\n  assert(!Rs.empty());\n\n  // -- Compute coarse global rotation estimates:\n  //   - by finding the maximum spanning tree and linking the relative rotations\n  //   - Initial solution is driven by relative rotations data confidence.\n  graph_t g;\n  MapEdgeIJ2R mapIJ2R;\n  NodeArr minGraph;\n  // find the Maximum Spanning Tree\n  FindMaximumSpanningTree(RelRs, g, mapIJ2R, minGraph);\n  g.clear();\n\n  // start from the main view and link all views using the relative rotation estimates\n  LinkQue stack;\n  stack.push(Link(nMainViewID, uint32_t(0)));\n  Rs[nMainViewID] = Matrix3x3::Identity();\n  do {\n    const Link& link = stack.front();\n    const Node& node = minGraph[link.ID];\n\n    for (Node::InternalType::const_iterator pEdge = node.edges.begin();\n      pEdge != node.edges.end(); ++pEdge) {\n        const size_t edge = *pEdge;\n        if (edge == link.parentID) {\n          // compute the global rotation for the current node\n          assert(mapIJ2R.find({link.parentID, link.ID}) != mapIJ2R.end());\n          const Matrix3x3& Rij = mapIJ2R[{link.parentID, link.ID}];\n          Rs[link.ID] = Rij * Rs[link.parentID];\n        } else {\n          // add edge to the processing queue\n          stack.push(Link(edge, link.ID));\n        }\n    }\n    stack.pop();\n  } while (!stack.empty());\n}\n\n// Robustly estimate global rotations from relative rotations as in:\n// \"Efficient and Robust Large-Scale Rotation Averaging\", Chatterjee and Govindu, 2013\n// and detect outliers relative rotations and return them with 0 in arrInliers\nbool GlobalRotationsRobust(\n  const RelativeRotations& RelRs,\n  Matrix3x3Arr& Rs,\n  const uint32_t nMainViewID,\n  float threshold,\n  std::vector<bool> * vec_Inliers)\n{\n  assert(!Rs.empty());\n\n  // -- Compute coarse global rotation estimates:\n  InitRotationsMST(RelRs, Rs, nMainViewID);\n\n  // refine global rotations based on the relative rotations\n  const bool bOk = RefineRotationsAvgL1IRLS(RelRs, Rs, nMainViewID);\n\n  // find outlier relative rotations\n  if (threshold>=0 && vec_Inliers)  {\n    FilterRelativeRotations(RelRs, Rs, threshold, vec_Inliers);\n  }\n\n  return bOk;\n} // GlobalRotationsRobust\n//----------------------------------------------------------------\n\nnamespace internal\n{\n\n// build A in Ax=b\ninline void FillMappingMatrix(\n  const RelativeRotations& RelRs,\n  const uint32_t nMainViewID,\n  sMat& A)\n{\n  A.reserve(A.rows()*2); // estimate of the number of non-zeros (optional)\n  sMat::Index i = 0, j = 0;\n  for (size_t r=0; r<RelRs.size(); ++r) {\n    const RelativeRotation& relR = RelRs[r];\n    if (relR.i != nMainViewID) {\n      j = 3*(relR.i<nMainViewID ? relR.i : relR.i-1);\n      A.insert(i+0,j+0) = -1.0;\n      A.insert(i+1,j+1) = -1.0;\n      A.insert(i+2,j+2) = -1.0;\n    }\n    if (relR.j != nMainViewID) {\n      j = 3*(relR.j<nMainViewID ? relR.j : relR.j-1);\n      A.insert(i+0,j+0) = 1.0;\n      A.insert(i+1,j+1) = 1.0;\n      A.insert(i+2,j+2) = 1.0;\n    }\n    i+=3;\n  }\n  A.makeCompressed();\n}\n\n// compute errors for each relative rotation\ninline void FillErrorMatrix(\n  const RelativeRotations& RelRs,\n  const Matrix3x3Arr& Rs,\n  Vec & b)\n{\n  for (size_t r = 0; r < RelRs.size(); ++r) {\n    const RelativeRotation& relR = RelRs[r];\n    const Matrix3x3& Ri = Rs[relR.i];\n    const Matrix3x3& Rj = Rs[relR.j];\n    const Matrix3x3& Rij = relR.Rij;\n    const Mat3 eRij(Rj.transpose()*Rij*Ri);\n    const openMVG::Vec3 erij;\n    ceres::RotationMatrixToAngleAxis((const double*)eRij.data(), (double*)erij.data());\n    b.block<3,1>(3*r,0) = erij;\n  }\n}\n\n// apply correction to global rotations\ninline void CorrectMatrix(\n  const Mat& x,\n  const uint32_t nMainViewID,\n  Matrix3x3Arr& Rs)\n{\n  for (size_t r = 0; r < Rs.size(); ++r) {\n    if (r == nMainViewID)\n      continue;\n    Matrix3x3& Ri = Rs[r];\n    const uint32_t i = (r<nMainViewID ? r : r-1);\n    const openMVG::Vec3 eRid = openMVG::Vec3(x.block<3,1>(3*i,0));\n    const Mat3 eRi;\n    ceres::AngleAxisToRotationMatrix((const double*)eRid.data(), (double*)eRi.data());\n    Ri = Ri*eRi;\n  }\n}\n\n// L1RA -> L1 Rotation Averaging implementation\nbool SolveL1RA\n(\n  const RelativeRotations& RelRs,\n  Matrix3x3Arr& Rs,\n  const sMat & A,\n  const unsigned int nMainViewID\n)\n{\n  const unsigned nObss = (unsigned)RelRs.size();\n  const unsigned nVars = (unsigned)Rs.size()-1; // one view is kept constant\n  const unsigned m = nObss*3;\n  const unsigned n = nVars*3;\n\n  // init x with 0 that corresponds to trusting completely the initial Ri guess\n  Vec x(Vec::Zero(n)), b(m);\n\n  // Current error and the previous one\n  double e = std::numeric_limits<double>::max(), ep;\n  unsigned iter = 0;\n  // L1RA iterate optimization till the desired precision is reached\n  do {\n    // compute errors for each relative rotation\n    FillErrorMatrix(RelRs, Rs, b);\n\n    // solve the linear system using l1 norm\n    L1Solver<sMat >::Options options;\n    L1Solver<sMat > l1_solver(options, A);\n    l1_solver.Solve(b, &x);\n\n    ep = e; e = x.norm();\n    if (ep < e)\n      break;\n    // apply correction to global rotations\n    CorrectMatrix(x, nMainViewID, Rs);\n  } while (++iter < 32 && e > 1e-5 && (ep-e)/e > 1e-2);\n\n  std::cout << \"L1RA Converged in \" << iter << \" iterations.\" << std::endl;\n\n  return true;\n}\n\n// Iteratively Reweighted Least Squares (IRLS) implementation\nbool SolveIRLS\n(\n  const RelativeRotations& RelRs,\n  Matrix3x3Arr& Rs,\n  const sMat & A,\n  const unsigned int nMainViewID,\n  const double sigma\n)\n{\n  const unsigned nObss = (unsigned)RelRs.size();\n  const unsigned nVars = (unsigned)Rs.size()-1; // one view is kept constant\n  const unsigned m = nObss*3;\n  const unsigned n = nVars*3;\n\n  // init x with 0 that corresponds to trusting completely the initial Ri guess\n  Vec x(Vec::Zero(n)), b(m);\n\n  // Since the sparsity pattern will not change with each linear solve\n  //  compute it once to speed up the solution time.\n  using Linear_Solver_T = Eigen::SimplicialLDLT<sMat >;\n\n  Linear_Solver_T linear_solver;\n  linear_solver.analyzePattern(A.transpose() * A);\n  if (linear_solver.info() != Eigen::Success) {\n    std::cerr << \"Cholesky decomposition failed.\" << std::endl;\n    return false;\n  }\n\n  const double sigmaSq(Square(sigma));\n\n  Eigen::ArrayXd errors, weights;\n  Vec xp(n);\n  // current error and the previous one\n  double e = std::numeric_limits<double>::max(), ep;\n  unsigned int iter = 0;\n  do\n  {\n    xp = x;\n    // compute errors for each relative rotation\n    FillErrorMatrix(RelRs, Rs, b);\n\n    // Compute the weights for each error term\n    errors = (A * x - b).array();\n\n    // compute robust errors using the Huber-like loss function\n    weights = sigmaSq / (errors.square() + sigmaSq).square();\n\n    // Update the factorization for the weighted values\n    const sMat at_weight = A.transpose() * weights.matrix().asDiagonal();\n    linear_solver.factorize(at_weight * A);\n    if (linear_solver.info() != Eigen::Success) {\n      std::cerr << \"Failed to factorize the least squares system.\" << std::endl;\n      return false;\n    }\n\n    // Solve the least squares problem\n    x = linear_solver.solve(at_weight * b);\n    if (linear_solver.info() != Eigen::Success) {\n      std::cerr << \"Failed to solve the least squares system.\" << std::endl;\n      return false;\n    }\n\n    // apply correction to global rotations\n    CorrectMatrix(x, nMainViewID, Rs);\n\n    ep = e; e = (xp-x).norm();\n\n  } while (++iter < 32 && e > 1e-5 && (ep-e)/e > 1e-2);\n\n  std::cout << \"IRLS Converged in \" << iter << \" iterations.\" << std::endl;\n\n  return true;\n}\n\n} // namespace internal\n\n// Refine the global rotations using to the given relative rotations, similar to:\n// \"Efficient and Robust Large-Scale Rotation Averaging\", Chatterjee and Govindu, 2013\n// L1 Rotation Averaging (L1RA) and Iteratively Reweighted Least Squares (IRLS) implementations combined\nbool RefineRotationsAvgL1IRLS(\n  const RelativeRotations& RelRs,\n  Matrix3x3Arr& Rs,\n  const uint32_t nMainViewID,\n  const double sigma)\n{\n  assert(!RelRs.empty() && !Rs.empty());\n  assert(Rs[nMainViewID] == Matrix3x3::Identity());\n\n  double fMinBefore, fMaxBefore;\n  const double fMeanBefore = RelRotationAvgError(RelRs, Rs, &fMinBefore, &fMaxBefore);\n\n  const unsigned nObss = (unsigned)RelRs.size();\n  const unsigned nVars = (unsigned)Rs.size()-1; // main view is kept constant\n  const unsigned m = nObss*3;\n  const unsigned n = nVars*3;\n\n  // build mapping matrix A in Ax=b\n  sMat A(m, n);\n  internal::FillMappingMatrix(RelRs, nMainViewID, A);\n\n  if (!internal::SolveL1RA(RelRs, Rs, A, nMainViewID))\n  {\n    std::cerr << \"Could not solve the L1 regression step.\" << std::endl;\n    return false;\n  }\n\n  if (!internal::SolveIRLS(RelRs, Rs, A, nMainViewID, sigma))\n  {\n    std::cerr << \"Could not solve the ILRS step.\" << std::endl;\n    return false;\n  }\n\n  double fMinAfter, fMaxAfter;\n  const double fMeanAfter = RelRotationAvgError(RelRs, Rs, &fMinAfter, &fMaxAfter);\n\n  std::cout << \"Refine global rotations using L1RA-IRLS and \" << nObss << \" relative rotations:\\n\"\n    << \" error reduced from \" << fMeanBefore << \"(\" <<fMinBefore << \" min, \" << fMaxBefore << \" max)\\n\"\n    << \" to \" << fMeanAfter << \"(\" << fMinAfter << \"min,\"<< fMaxAfter<< \"max)\" << std::endl;\n\n  return true;\n} // RefineRotationsAvgL1IRLS\n\n} // namespace l1\n} // namespace rotation_averaging\n} // namespace openMVG\n", "meta": {"hexsha": "7cda44ead62538d4a0a7afa91cbe2359169a5870", "size": 17879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/multiview/rotation_averaging_l1.cpp", "max_stars_repo_name": "Aurelio93/satellite-pose-estimation", "max_stars_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2019-05-19T03:48:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:20:49.000Z", "max_issues_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/multiview/rotation_averaging_l1.cpp", "max_issues_repo_name": "Aurelio93/satellite-pose-estimation", "max_issues_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-05-22T07:45:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T01:48:26.000Z", "max_forks_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/multiview/rotation_averaging_l1.cpp", "max_forks_repo_name": "Aurelio93/satellite-pose-estimation", "max_forks_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-05-19T03:48:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-29T18:19:16.000Z", "avg_line_length": 31.6442477876, "max_line_length": 117, "alphanum_fraction": 0.6671514067, "num_tokens": 5219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.43692239026058977}}
{"text": "#include \"functions.hpp\"\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\nnamespace gd {\n\nusing namespace boost::numeric::ublas;\n\nvoid py_export_functions() {\n\tusing namespace boost::python;\n\tdef(\"matmul_2d_3d\", matmul_2d_3d);\n\tdef(\"matmul_3d_3d\", matmul_3d_3d);\n\tdef(\"velocity_cartesian_to_spherical\", velocity_cartesian_to_spherical);\n\tdef(\"add_to_matrix_indexed\", add_to_matrix_indexed);\n}\n\nvoid add_to_matrix_indexed(double_matrix M, int_vector _i, int_vector _j, double_vector weight) {\n\tdouble* Mp = M.data().begin();\n\tdouble* wp = weight.data().begin();\n\tint* ip = _i.data().begin();\n\tint* jp = _j.data().begin();\n\tint size1 = M.size1();\n\tint size2 = M.size2();\n\tint length = min(min(_i.size(), _j.size()), weight.size());\n\tfor(int k = 0; k < length; k++) {\n\t\tint i = *ip++;\n\t\tint j = *jp++;\n\t\tdouble w = *wp++;\n\t\tif((i < size1) && (j < size2) && (i >= 0) && (j >= 0)) {\n\t\t\tint index = j + i * size2;\n\t\t\tMp[index] += w;\n\t\t}\n\t}\n}\n\nvoid matmul_2d_3d(double_matrix M, double_vector x, double_vector y, double_vector xt, double_vector yt, double_vector zt) {\n\tdouble* Mp = M.data().begin();\n\tint Mstride = M.size2();\n\tdouble* xp = x.data().begin();\n\tdouble* yp = y.data().begin();\n\tdouble* xtp = xt.data().begin();\n\tdouble* ytp = yt.data().begin();\n\tdouble* ztp = zt.data().begin();\n\tint size = x.size();\n\tfor(int i = 0; i < size; i++) {\n\t\t//for(int j = 0; j < 3; j++) {\n\t\t*xtp++ = (*xp) * Mp[0+Mstride*0] + (*yp) * Mp[0+Mstride*1];\n\t\t*ytp++ = (*xp) * Mp[1+Mstride*0] + (*yp) * Mp[1+Mstride*1];\n\t\t*ztp++ = (*xp) * Mp[2+Mstride*0] + (*yp) * Mp[2+Mstride*1];\n\t\txp++; yp++;\n\t\t//}\n\t}\n} \nvoid matmul_3d_3d(double_matrix M, double_vector x, double_vector y, double_vector z, double_vector xt, double_vector yt, double_vector zt) {\n\tdouble* Mp = M.data().begin();\n\tint Mstride = M.size2();\n\tdouble* xp = x.data().begin();\n\tdouble* yp = y.data().begin();\n\tdouble* zp = z.data().begin();\n\tdouble* xtp = xt.data().begin();\n\tdouble* ytp = yt.data().begin();\n\tdouble* ztp = zt.data().begin();\n\tint size = x.size();\n\tfor(int i = 0; i < size; i++) {\n\t\t*xtp++ = (*xp) * Mp[0+Mstride*0] + (*yp) * Mp[0+Mstride*1] + (*zp) * Mp[0+Mstride*2];\n\t\t*ytp++ = (*xp) * Mp[1+Mstride*0] + (*yp) * Mp[1+Mstride*1] + (*zp) * Mp[1+Mstride*2];\n\t\t*ztp++ = (*xp) * Mp[2+Mstride*0] + (*yp) * Mp[2+Mstride*1] + (*zp) * Mp[2+Mstride*2];\n\t\txp++; yp++; zp++;\n\t}\n} \n\nvoid velocity_cartesian_to_spherical(double_vector xv, double_vector yv, double_vector zv, double_vector vxv, double_vector vyv, double_vector vzv, double_vector vrv, double_vector vphiv, double_vector vthetav) {\n\tdouble *xp = xv.data().begin();\n\tdouble *yp = yv.data().begin();\n\tdouble *zp = zv.data().begin();\n\tdouble *vxp = vxv.data().begin();\n\tdouble *vyp = vyv.data().begin();\n\tdouble *vzp = vzv.data().begin();\n\tdouble *vrp = vrv.data().begin();\n\tdouble *vphip = vphiv.data().begin();\n\tdouble *vthetap = vthetav.data().begin();\n\tdouble *xpend = xv.data().end();\n\twhile(xp != xpend) {\n\t\tdouble x = *xp++;\n\t\tdouble y = *yp++;\n\t\tdouble z = *zp++;\n\t\tdouble vx = *vxp++;\n\t\tdouble vy = *vyp++;\n\t\tdouble vz = *vzp++;\n\t\tdouble r = sqrt(x*x+y*y+z*z);\n\t\tdouble rhosq = (x*x+y*y);\n\t\tdouble rho = sqrt(rhosq);\n\t\t//double cosatan2xy = x / rho;\n\t\t//double sinatan2xy = y / rho;\n\t\t*vrp++ = (vx*x + vy*y + vz*z)/r;\n\t\t*vphip++ = (vy*x - vx*y)/rho;\n\t\t*vthetap++ = (vx*z*x/rho + vy*z*y/rho - vz*rho)/r;\n\t\t\n\t}\n}\n\n\n}\n", "meta": {"hexsha": "6973333093d5a9b67e56918efc65ae4890baac11", "size": 3416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/functions.cpp", "max_stars_repo_name": "maartenbreddels/mab", "max_stars_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T04:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T04:10:34.000Z", "max_issues_repo_path": "gdfast/src/functions.cpp", "max_issues_repo_name": "maartenbreddels/mab", "max_issues_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdfast/src/functions.cpp", "max_forks_repo_name": "maartenbreddels/mab", "max_forks_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5333333333, "max_line_length": 212, "alphanum_fraction": 0.6068501171, "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.43692238317636206}}
{"text": "#include <iostream>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/timer.hpp>\n\n\n#include <vector>\n#include <math.h>\n\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\n#include \"TwoChQSz.hpp\"\n\nvoid TwoChQSz_UpdateQm1fQ(CNRGbasisarray* pSingleSite,CNRGarray* pAeig, \n\t\t\t  CNRGbasisarray* pAbasis,CNRGmatrix* Qm1fNQ){\n\n  // Boost matrices\n  boost::numeric::ublas::matrix<double> Zibl;\n  boost::numeric::ublas::matrix<double> Zjbl;\n  boost::numeric::ublas::matrix<double> fnbasis;\n\n\n  boost::numeric::ublas::matrix<double> fnw;\n  // Check time\n  boost::timer t;\n  double time_elapsed;\n\n\n\n  //Clear all\n  for (int ich=1;ich<=2;ich++)\n    {\n      Qm1fNQ[ich-1].ClearAll();\n      Qm1fNQ[ich-1].SyncNRGarray(*pAeig);\n    }\n\n  // Note: assumes  Abasis and Aeig have \n  // EXACTLY the same block structure... should check.\n\n  double Qi[2];\n  double Qj[2];\n  double Szi,Szj;\n\n  // Loop over blocks (icount counts for each matrix)\n  int icount[2]={0,0};\n  for (int ibl=0;ibl<pAeig->NumBlocks();ibl++)\n    {\n      Qi[0]=pAeig->GetQNumber(ibl,0);\n      Qi[1]=pAeig->GetQNumber(ibl,1);\n      Szi=pAeig->GetQNumber(ibl,2);\n      int Nstibl=pAeig->GetBlockSize(ibl);\n\n      for (int jbl=ibl+1;jbl<pAeig->NumBlocks();jbl++)\n\t{\n\t  Qj[0]=pAeig->GetQNumber(jbl,0);\n\t  Qj[1]=pAeig->GetQNumber(jbl,1);\n\t  Szj=pAeig->GetQNumber(jbl,2);\n\t  int Nstjbl=pAeig->GetBlockSize(jbl);\n\n\t  //Loop over channels: check if the matrix elements are non-zero\n\t  for (int ich=1;ich<=2;ich++)\n\t    {\n\t      if (  dEqual(Qi[ich-1]+1.0,Qj[ich-1])&&\n\t\t   ( dEqual(Szi+0.5,Szj)||dEqual(Szi-0.5,Szj) )  )\n\t\t{\n\t\t  // Set Zi,Zj\n\t\t  cout << \" BC: Nshell = \" << pAeig->Nshell << endl;\n\t\t  cout << \"Matrix in channel: \" << ich << endl;\n\t\t  cout << \"  Setting up Block i : \" << ibl \n\t\t       << \" (size \" <<  Nstibl \n\t\t       << \") x Block j \" << jbl\n\t\t       << \" (size \" << Nstjbl << \") of \" << pAeig->NumBlocks() << endl;\n\t\t  Qm1fNQ[ich-1].MatBlockMap.push_back(ibl);\n\t\t  Qm1fNQ[ich-1].MatBlockMap.push_back(jbl);\n\t\t  Qm1fNQ[ich-1].MatBlockBegEnd.push_back(icount[ich-1]);\n\t\t  icount[ich-1]+=Nstibl*Nstjbl;\n\t\t  Qm1fNQ[ich-1].MatBlockBegEnd.push_back(icount[ich-1]-1);\n\n\t\t  cout << \"    Setting up BLAS matrices...\" << endl;\n\t\t  //boost::numeric::ublas::matrix<double> Zibl(Nstibl,Nstibl);\n\t\t  //boost::numeric::ublas::matrix<double> Zjbl(Nstjbl,Nstjbl);\n\t\t  Zibl.resize(Nstibl,Nstibl);\n\t\t  Zjbl.resize(Nstjbl,Nstjbl);\n\n\t\t  Zibl=pAeig->EigVec2BLAS(ibl);\n\t\t  Zjbl=pAeig->EigVec2BLAS(jbl);\n\t\t  cout << \"    ...Zs done ...\" << endl;\n\n\t\t  //boost::numeric::ublas::matrix<double> fnbasis (Nstibl,Nstjbl);\n\t\t  fnbasis.resize(Nstibl,Nstjbl);\n\t\t  // Set-up fn basis: Loop in the basis states\n\t\t  int istbl=0;\n\t\t  for (int ist=pAbasis->GetBlockLimit(ibl,0);\n\t\t       ist<=pAbasis->GetBlockLimit(ibl,1);ist++)\n\t\t    {\n\t\t      int typei=pAbasis->iType[ist];\n\t\t      int stcfi=pAbasis->StCameFrom[ist];\n\n\t\t      int jstbl=0;\n\t\t      for (int jst=pAbasis->GetBlockLimit(jbl,0);\n\t\t\t   jst<=pAbasis->GetBlockLimit(jbl,1);jst++)\n\t\t\t{\n\t\t\t  int typej=pAbasis->iType[jst];\n\t\t\t  int stcfj=pAbasis->StCameFrom[jst];\n\t\t\t  \n\t\t\t  fnbasis(istbl,jstbl)=0.0;\n\n\t\t\t  if (stcfi==stcfj)\n\t\t\t    {\n\t\t\t    fnbasis(istbl,jstbl)=fd_table(ich,-1,typej,typei)+\n\t\t\t      fd_table(ich,1,typej,typei);\n\t\t\t    }\n\t\t\t  jstbl++;\n\t\t\t}\n\t\t      // end jst loop\n\t\t      istbl++;\n\t\t    }\n\t\t  // end ist loop\n\t\t  cout << \"    ...fnbasis done.\" << endl;\n\n\t\t  cout << \"    Multiplying BLAS matrices... \" << endl;\n\t\t  \n\t\t  fnw.resize(Nstibl,Nstjbl);\n\t\t  t.restart();\n\t\t  noalias(fnw)=prod (Zibl, \n\t\t\t\t     boost::numeric::ublas::matrix<double>(prod(fnbasis,trans(Zjbl))) );\n\t\t  time_elapsed=t.elapsed();\n\t\t  cout << \"    ...done. Elapsed time:\" << time_elapsed << endl;\n\n// \t\t  cout << \"Z(i=\"<<ibl<<\")  : \" <<  Zibl << endl;\n// \t\t  cout << \"Z(j=\"<<jbl<<\")  : \" <<  Zjbl << endl;\n// \t\t  cout << \"fbasis   :\" <<  fnbasis << endl;\n// \t\t  cout << \"Zi.fbasis.ZjT : \" <<  fnw << endl;\n\n\n\t\t  // Add to Qm1fNQ[ich-1]\n\t\t  for (int ii=0;ii<fnw.size1();ii++)\n\t\t    for (int jj=0;jj<fnw.size2();jj++)\n\t\t      Qm1fNQ[ich-1].MatEl.push_back(fnw(ii,jj));\n\t\t\t\n\n\t\t}\n\t      //end if Q=Q'+1 etc\n\n\t    }\n\t  // end channel loop\n\n\n\n\t}\n      // end jbl loop\n\n    }\n  // end ibl loop\n\n}\n// END subroutine\n\n//////////////////////////////////\n//////////////////////////////////\n//////////////////////////////////\n//////////////////////////////////\n\nvoid TwoChQSz_UpdateMatrixAfterCutting(CNRGbasisarray* pSingleSite,\n\t\t\t\t       CNRGbasisarray* pAeigCut, \n\t\t\t\t       CNRGbasisarray* pAbasis,\n\t\t\t\t       CNRGmatrix* Qm1fNQ, \n\t\t\t\t       CNRGmatrix* pMQQp1){\n\n  // Boost matrices\n  boost::numeric::ublas::matrix<double> Zibl;\n  boost::numeric::ublas::matrix<double> Zjbl;\n  boost::numeric::ublas::matrix<double> fnbasis;\n\n\n  boost::numeric::ublas::matrix<double> fnw;\n  // Check time\n  boost::timer t;\n  double time_elapsed;\n\n  //Clear all\n  for (int ich=1;ich<=2;ich++)\n    {\n      Qm1fNQ[ich-1].ClearAll();\n      Qm1fNQ[ich-1].SyncNRGarray(*pAeigCut);\n    }\n\n  // Note: assumes  Abasis and Aeig have \n  // EXACTLY the same block structure... should check.\n\n  double Qi[2];\n  double Qj[2];\n  double Szi,Szj;\n\n  double qnums[3];\n\n\n  // Loop over blocks (icount counts for each matrix)\n  int icount[2]={0,0};\n  for (int ibl=0;ibl<pAeigCut->NumBlocks();ibl++)\n    {\n      Qi[0]=pAeigCut->GetQNumber(ibl,0);\n      Qi[1]=pAeigCut->GetQNumber(ibl,1);\n      Szi=pAeigCut->GetQNumber(ibl,2);\n      int Nstibl=pAeigCut->GetBlockSize(ibl);\n\n      // Get the corresponding block in pAbasis!\n      qnums[0]=Qi[0];\n      qnums[1]=Qi[1];\n      qnums[2]=Szi;\n      int ii_corr=pAbasis->GetBlockFromQNumbers(qnums);\n      int NstiblBC=pAbasis->GetBlockSize(ii_corr);\n\n      for (int jbl=ibl+1;jbl<pAeigCut->NumBlocks();jbl++)\n\t{\n\t  Qj[0]=pAeigCut->GetQNumber(jbl,0);\n\t  Qj[1]=pAeigCut->GetQNumber(jbl,1);\n\t  Szj=pAeigCut->GetQNumber(jbl,2);\n\t  int Nstjbl=pAeigCut->GetBlockSize(jbl);\n\n\t  // Get the corresponding block in pAbasis!\n\t  qnums[0]=Qj[0];\n\t  qnums[1]=Qj[1];\n\t  qnums[2]=Szj;\n\t  int jj_corr=pAbasis->GetBlockFromQNumbers(qnums);\n\t  int NstjblBC=pAbasis->GetBlockSize(jj_corr);\n\n\t  if ( (!dEqual(Qj[0],pAbasis->GetQNumber(jj_corr,0)))||\n\t       (!dEqual(Qj[1],pAbasis->GetQNumber(jj_corr,1)))||\n\t       (!dEqual(Szj,pAbasis->GetQNumber(jj_corr,2))) )\n\t    {\n\t      cout << \"Ops, problems with GetBlockFromQNumbers\" << endl;\n\t      pAbasis->PrintQNumbers();\n\t      cout << qnums[0] << \" \" << qnums[1] << \" \" << qnums[2] << endl;\n\t      cout << pAbasis->GetBlockFromQNumbers(qnums) << endl;\n\t    }\n\n\n\n\t  //Loop over channels: check if the matrix elements are non-zero\n\t  for (int ich=1;ich<=2;ich++)\n\t    {\n\t      if (  dEqual(Qi[ich-1]+1.0,Qj[ich-1])&&\n\t\t   ( dEqual(Szi+0.5,Szj)||dEqual(Szi-0.5,Szj) )  )\n\t\t{\n\t\t  // Set Zi,Zj\n\t\t  cout << \" AC : Nshell = \" << pAeigCut->Nshell << endl;\n\t\t  cout << \"Matrix in channel: \" << ich << endl;\n\t\t  cout << \"  Setting up Block i : \" << ibl \n\t\t       << \" (size \" <<  Nstibl << \" was \" << NstiblBC\n\t\t       << \") x Block j \" << jbl\n\t\t       << \" (size \" << Nstjbl << \" was \" << NstjblBC\n\t\t       << \") of \" << pAeigCut->NumBlocks() << endl;\n\t\t  Qm1fNQ[ich-1].MatBlockMap.push_back(ibl);\n\t\t  Qm1fNQ[ich-1].MatBlockMap.push_back(jbl);\n\t\t  Qm1fNQ[ich-1].MatBlockBegEnd.push_back(icount[ich-1]);\n\t\t  icount[ich-1]+=Nstibl*Nstjbl;\n\t\t  Qm1fNQ[ich-1].MatBlockBegEnd.push_back(icount[ich-1]-1);\n\n\t\t  cout << \"    Setting up BLAS matrices...\" << endl;\n\t\t  //boost::numeric::ublas::matrix<double> Zibl(Nstibl,Nstibl);\n\t\t  //boost::numeric::ublas::matrix<double> Zjbl(Nstjbl,Nstjbl);\n\t\t  Zibl.resize(Nstibl,NstiblBC);\n\t\t  Zjbl.resize(Nstjbl,NstjblBC);\n\n\t\t  //Zibl=pAeigCut->EigVec2BLAS(ibl);\n\t\t  //Zjbl=pAeigCut->EigVec2BLAS(jbl);\n\t\t  Zibl=pAeigCut->EigVecCut2BLAS(ibl);\n\t\t  Zjbl=pAeigCut->EigVecCut2BLAS(jbl);\n\t\t  cout << \"    ...Zs done ...\" << endl;\n\n\t\t  fnbasis.resize(NstiblBC,NstjblBC);\n\t\t  // Set-up fn basis: Loop in the basis states\n\t\t  // Watch out here... ii_corr, not ibl\n\t\t  int istbl=0;\n\t\t  for (int ist=pAbasis->GetBlockLimit(ii_corr,0);\n\t\t       ist<=pAbasis->GetBlockLimit(ii_corr,1);ist++)\n\t\t    {\n\t\t      int typei=pAbasis->iType[ist];\n\t\t      int stcfi=pAbasis->StCameFrom[ist];\n\n\t\t      int jstbl=0;\n\t\t      for (int jst=pAbasis->GetBlockLimit(jj_corr,0);\n\t\t\t   jst<=pAbasis->GetBlockLimit(jj_corr,1);jst++)\n\t\t\t{\n\t\t\t  int typej=pAbasis->iType[jst];\n\t\t\t  int stcfj=pAbasis->StCameFrom[jst];\n\t\t\t  \n\t\t\t  fnbasis(istbl,jstbl)=0.0;\n\n\t\t\t  if (stcfi==stcfj)\n\t\t\t    {\n\t\t\t    fnbasis(istbl,jstbl)=fd_table(ich,-1,typej,typei)+\n\t\t\t      fd_table(ich,1,typej,typei);\n\t\t\t    }\n\t\t\t  jstbl++;\n\t\t\t}\n\t\t      // end jst loop\n\t\t      istbl++;\n\t\t    }\n\t\t  // end ist loop\n\t\t  cout << \"    ...fnbasis done.\" << endl;\n\n\t\t  cout << \"    Multiplying BLAS matrices... \" << endl;\n\t\t  \n\t\t  fnw.resize(Nstibl,Nstjbl);\n\t\t  t.restart();\n\t\t  noalias(fnw)=prod (Zibl, \n\t\t\t\t     boost::numeric::ublas::matrix<double>(prod(fnbasis,trans(Zjbl))) );\n\t\t  time_elapsed=t.elapsed();\n\t\t  cout << \"    ...done. Elapsed time:\" << time_elapsed << endl;\n\n// \t\t  cout << \"Z(i=\"<<ibl<<\")  : \" <<  Zibl << endl;\n// \t\t  cout << \"Z(j=\"<<jbl<<\")  : \" <<  Zjbl << endl;\n// \t\t  cout << \"fbasis   :\" <<  fnbasis << endl;\n// \t\t  cout << \"Zi.fbasis.ZjT : \" <<  fnw << endl;\n\n\n\t\t  // Add to Qm1fNQ[ich-1]\n\t\t  for (int ii=0;ii<fnw.size1();ii++)\n\t\t    for (int jj=0;jj<fnw.size2();jj++)\n\t\t      Qm1fNQ[ich-1].MatEl.push_back(fnw(ii,jj));\n\t\t\t\n\n\t\t}\n\t      //end if Q=Q'+1 etc\n\n\t    }\n\t  // end channel loop\n\n\n\n\t}\n      // end jbl loop\n\n    }\n  // end ibl loop\n\n\n\n\n}\n//////////////////////////////////\n//////////////////////////////////\n//////////////////////////////////\n//////////////////////////////////\n", "meta": {"hexsha": "5e5e36c74bfdb848330020422ef0f67dee10096f", "size": 9652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TwoChQ1Q2Sz/TwoChQ1Q2Sz_UpdateMatrices.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/TwoChQ1Q2Sz/TwoChQ1Q2Sz_UpdateMatrices.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TwoChQ1Q2Sz/TwoChQ1Q2Sz_UpdateMatrices.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6561604585, "max_line_length": 76, "alphanum_fraction": 0.5685868214, "num_tokens": 3461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021706, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.43690466943368345}}
{"text": "// =========================================================================\n// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co)\n// =========================================================================\n\n#include \"NeuralNetwork.h\"\n\n#include <cassert>\n#include <map>\n#include <regex>\n#include <sstream>\n#include <boost/algorithm/string.hpp>\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nNeuralNetwork< _TScl >::\nNeuralNetwork( )\n{\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nNeuralNetwork< _TScl >::\nNeuralNetwork( const Self& o )\n{\n  this->m_L.clear( );\n  this->m_L.insert( this->m_L.begin( ), o.m_L.begin( ), o.m_L.end( ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename NeuralNetwork< _TScl >::\nSelf& NeuralNetwork< _TScl >::\noperator=( const Self& o )\n{\n  this->m_L.clear( );\n  this->m_L.insert( this->m_L.begin( ), o.m_L.begin( ), o.m_L.end( ) );\n  return( *this );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid NeuralNetwork< _TScl >::\nadd( unsigned int i, unsigned int o, const std::string& f )\n{\n  this->add( TLayer( i, o, f ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid NeuralNetwork< _TScl >::\nadd( unsigned int o, const std::string& f )\n{\n  assert( this->m_L.size( ) > 0 && \"At least one layer is needed\" );\n\n  this->add( this->m_L.back( ).output_size( ), o, f );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid NeuralNetwork< _TScl >::\nadd( const TMatrix& w, const TColVector& b, const std::string& f )\n{\n  this->add( TLayer( w, b, f ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid NeuralNetwork< _TScl >::\nadd( const TLayer& l )\n{\n  if( this->m_L.size( ) > 0 )\n    assert(\n      l.input_size( ) == this->m_L.back( ).output_size( ) && \"Invalid sizes\"\n      );\n  this->m_L.push_back( l );\n\n  // Normalization transforms\n  if( this->m_L.size( ) == 1 )\n  {\n    unsigned int n = this->m_L[ 0 ].input_size( );\n    this->m_NormalizationOffset = TColVector::Zero( n );\n    this->m_NormalizationScale = TMatrix::Identity( n, n );\n  } // end if\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid NeuralNetwork< _TScl >::\nload_topology( std::istream& is )\n{\n  unsigned int L;\n  std::map< unsigned int, unsigned long > K;\n  std::map< unsigned int, std::string > F;\n\n  // Read parameters\n  std::regex r( \"\\\\s+\" );\n  std::string line;\n  while( std::getline( is, line ) )\n  {\n    line = std::regex_replace( line, r, \"\" );\n    std::vector< std::string > tokens;\n    boost::algorithm::split( tokens, line, boost::is_any_of( \"=\" ) );\n    if( tokens.size( ) == 2 )\n    {\n      if( tokens[ 0 ] == \"L\" )\n      {\n        std::istringstream data( tokens[ 1 ] );\n        data >> L;\n      }\n      else\n      {\n        if( tokens[ 0 ][ 0 ] == 'k' )\n        {\n          std::istringstream i_str( tokens[ 0 ].substr( 1 ) );\n          std::istringstream k_str( tokens[ 1 ] );\n          unsigned int i;\n          unsigned long k;\n          i_str >> i;\n          k_str >> k;\n          K[ i ] = k;\n        }\n        else if( tokens[ 0 ][ 0 ] == 'f' )\n        {\n          std::istringstream i_str( tokens[ 0 ].substr( 1 ) );\n          unsigned int i;\n          i_str >> i;\n          F[ i ] = tokens[ 1 ];\n        } // end if\n      } // end if\n    } // end if\n  } // end while\n\n  // Real build\n  if( F.size( ) == L && K.size( ) == L + 1 )\n    for( unsigned int l = 0; l < L; ++l )\n      this->add( K[ l ], K[ l + 1 ], F[ l ] );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid NeuralNetwork< _TScl >::\nset( unsigned int l, const TMatrix& w, const TColVector& b )\n{\n  if( l < this->m_L.size( ) )\n  {\n    this->m_L[ l ].weights( ) = w;\n    this->m_L[ l ].biases( ) = b;\n  } // end if\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nunsigned int NeuralNetwork< _TScl >::\nnumber_of_layers( ) const\n{\n  return( this->m_L.size( ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename NeuralNetwork< _TScl >::\nTMatrix& NeuralNetwork< _TScl >::\nweights( unsigned int l )\n{\n  static TMatrix w( 1, 1 );\n  if( l < this->m_L.size( ) )\n    return( this->m_L[ l ].weights( ) );\n  else\n    return( w );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nconst typename NeuralNetwork< _TScl >::\nTMatrix& NeuralNetwork< _TScl >::\nweights( unsigned int l ) const\n{\n  static const TMatrix w( 1, 1 );\n  if( l < this->m_L.size( ) )\n    return( this->m_L[ l ].weights( ) );\n  else\n    return( w );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename NeuralNetwork< _TScl >::\nTColVector& NeuralNetwork< _TScl >::\nbiases( unsigned int l )\n{\n  static TColVector b( 1 );\n  if( l < this->m_L.size( ) )\n    return( this->m_L[ l ].biases( ) );\n  else\n    return( b );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nconst typename NeuralNetwork< _TScl >::\nTColVector& NeuralNetwork< _TScl >::\nbiases( unsigned int l ) const\n{\n  static const TColVector b( 1 );\n  if( l < this->m_L.size( ) )\n    return( this->m_L[ l ].biases( ) );\n  else\n    return( b );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename NeuralNetwork< _TScl >::\nTActivation* NeuralNetwork< _TScl >::\nsigma( unsigned int l )\n{\n  if( l < this->m_L.size( ) )\n    return( this->m_L[ l ].sigma( ) );\n  else\n    return( nullptr );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nconst typename NeuralNetwork< _TScl >::\nTActivation* NeuralNetwork< _TScl >::\nsigma( unsigned int l ) const\n{\n  if( l < this->m_L.size( ) )\n    return( this->m_L[ l ].sigma( ) );\n  else\n    return( nullptr );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid NeuralNetwork< _TScl >::\nsetNormalizationOffset( const TColVector& o )\n{\n  this->m_NormalizationOffset = o;\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid NeuralNetwork< _TScl >::\nsetNormalizationScale( const TMatrix& s )\n{\n  this->m_NormalizationScale = s;\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid NeuralNetwork< _TScl >::\ninit( )\n{\n  // Weights\n  for( TLayer& l: this->m_L )\n    l.init( );\n\n  // Normalization transforms\n  unsigned int n = this->m_L[ 0 ].input_size( );\n  this->m_NormalizationOffset = TColVector::Zero( n );\n  this->m_NormalizationScale = TMatrix::Identity( n, n );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename NeuralNetwork< _TScl >::\nTMatrix NeuralNetwork< _TScl >::\nf( const TMatrix& x ) const\n{\n  typename TLayers::const_iterator lIt = this->m_L.begin( );\n  TMatrix z = lIt->f(\n    this->m_NormalizationScale *\n    ( x.colwise( ) + this->m_NormalizationOffset )\n    );\n  for( lIt++; lIt != this->m_L.end( ); ++lIt )\n    z = lIt->f( z );\n  return( z );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid NeuralNetwork< _TScl >::\nf( std::vector< TMatrix >& a, std::vector< TMatrix >& z ) const\n{\n  typename TLayers::const_iterator lIt = this->m_L.begin( );\n  typename std::vector< TMatrix >::iterator aIt, bIt, zIt;\n  aIt = bIt = a.begin( );\n  zIt = z.begin( );\n\n  for( bIt++; lIt != this->m_L.end( ); ++lIt, ++aIt, ++bIt, ++zIt )\n    *bIt = lIt->f( *aIt, *zIt );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename NeuralNetwork< _TScl >::\nTMatrix NeuralNetwork< _TScl >::\nt( const TMatrix& x ) const\n{\n  return( this->m_L.back( ).sigma( )->t( this->f( x ) ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\ntypename NeuralNetwork< _TScl >::\nTMatrix NeuralNetwork< _TScl >::\n_d( const unsigned int& l, const TMatrix& z ) const\n{\n  assert( l < this->m_L.size( ) && \"Layer does not exist\" );\n\n  return( this->m_L[ l ].sigma( )->d( z ) );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid NeuralNetwork< _TScl >::\n_read_from( std::istream& i )\n{\n  unsigned int L;\n  i >> L;\n  for( unsigned int n = 0; n < L; ++n )\n  {\n    TLayer l;\n    i >> l;\n    this->add( l );\n  } // end for\n\n  // Read normalization parameters\n  unsigned int N = this->m_L[ 0 ].input_size( );\n  this->m_NormalizationOffset = TColVector::Zero( N );\n  this->m_NormalizationScale = TMatrix::Identity( N, N );\n  for( unsigned int n = 0; n < N; ++n )\n    i >> this->m_NormalizationOffset( n, 0 );\n  for( unsigned int x = 0; x < N; ++x )\n    for( unsigned int y = 0; y < N; ++y )\n      i >> this->m_NormalizationScale( x, y );\n}\n\n// -------------------------------------------------------------------------\ntemplate< class _TScl >\nvoid NeuralNetwork< _TScl >::\n_copy_to( std::ostream& o ) const\n{\n  o << this->m_L.size( ) << std::endl;\n  for( const TLayer& l: this->m_L )\n    o << l << std::endl;\n  o << this->m_NormalizationOffset << std::endl;\n  o << this->m_NormalizationScale << std::endl;\n}\n\n// -------------------------------------------------------------------------\ntemplate class NeuralNetwork< float >;\ntemplate class NeuralNetwork< double >;\ntemplate class NeuralNetwork< long double >;\n\n// eof - $RCSfile$\n", "meta": {"hexsha": "5933cc3af6d2bf0caf589f8480c06f71f398109b", "size": 9924, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "examples/neural_network/NeuralNetwork.cxx", "max_stars_repo_name": "DanteCely/PUJ_ML", "max_stars_repo_head_hexsha": "7cb592bb51a9c7b5a5d330754d410377cc34911b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-01T09:20:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:16:37.000Z", "max_issues_repo_path": "examples/neural_network/NeuralNetwork.cxx", "max_issues_repo_name": "DanteCely/PUJ_ML", "max_issues_repo_head_hexsha": "7cb592bb51a9c7b5a5d330754d410377cc34911b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/neural_network/NeuralNetwork.cxx", "max_forks_repo_name": "DanteCely/PUJ_ML", "max_forks_repo_head_hexsha": "7cb592bb51a9c7b5a5d330754d410377cc34911b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:38:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T23:17:44.000Z", "avg_line_length": 27.643454039, "max_line_length": 76, "alphanum_fraction": 0.4695687223, "num_tokens": 2562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.436889028718094}}
{"text": "#include \"tkdCmdParser.h\"\n\n#include \"vnl/vnl_matrix.h\"\n#include \"vnl/vnl_vector.h\"\n#include \"vnl/algo/vnl_determinant.h\"\n#include \"vnl/algo/vnl_svd.h\"\n\n#include <stdlib.h>\n#include <math.h>\n#include <fstream>\n\n#include <boost/tokenizer.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random.hpp>\n#include <boost/utility.hpp>\n#include <boost/accumulators/numeric/functional/vector.hpp>\n#include <boost/accumulators/numeric/functional/complex.hpp>\n#include <boost/accumulators/numeric/functional/valarray.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n\n#include <boost/math/distributions/normal.hpp>\n\n/* Indexer problem... */\n\n/**\n * Option list.\n */\nstruct parameters\n{\n\tstd::string inputFileName;\n\tstd::string link;\n\tstd::string separation;\n\tint iterations;\n\tdouble percentage;\n\tbool verbose;\n\tbool printPValues;\n\tbool printZValues;\n};\n\n/**\n * Generalized Linear Model (GLM) is a flexible generalization of ordinary least squares regression.\n *\n * http://en.wikipedia.org/wiki/Generalized_linear_model\n *\n * wim@invivonmr.uu.nl, 02-03-2010.\n *\n */\nnamespace generalized_linear_model\n{\n\ttypedef double PixelType;\n\ttypedef vnl_matrix< PixelType > MatrixType;\n\ttypedef vnl_vector< PixelType > VectorType;\n\ttypedef boost::tokenizer< boost::char_separator< char > > TokType;\n\ttypedef boost::mt19937 random_number_type;\n\ttypedef boost::uniform_int< long > int_distribution_type;\n\ttypedef boost::variate_generator< random_number_type&, int_distribution_type > int_generator_type;\n\n\tclass GLM\n\t{\n\tpublic:\n\n\t\t/**\n\t\t * Run glm.\n\t\t */\n\t\tvoid Run( parameters& list )\n\t\t{\n\t\t\t// read covariates and response-function (latter as last column).\n\t\t\tMatrixType covariates;\n\t\t\tVectorType binaryResponse;\n\n\t\t\tif( list.verbose )\n\t\t\t\tstd::cout << \"Reading input data...\" << std::endl;\n\n\t\t\tReadData( list.separation, list.inputFileName, covariates, binaryResponse, list.percentage );\n\t\t\tcovariates = AddIntercept( covariates );\n\n\t\t\tif( list.verbose )\n\t\t\t\tstd::cout << \"Finished reading input data...\" << std::endl;\n\n\t\t\tif ( list.link == \"logistic\" )\n\t\t\t{\n\t\t\t\t// Calculate coefficients...\n\t\t\t\tVectorType coefficients = IRLS( binaryResponse, covariates, list.iterations, list.verbose );\n\t\t\t\tstd::cout << \"Coefficients: \" << coefficients << std::endl;\n\n\t\t\t\tif( list.printZValues )\n\t\t\t\t\tstd::cout << \"Z-values: \" << ZStatistic( coefficients, binaryResponse, covariates ) << std::endl;\n\n\t\t\t\tif( list.printPValues )\n\t\t\t\t\tstd::cout << \"P-values: \" << PValue( ZStatistic( coefficients, binaryResponse, covariates ) ) << std::endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: Link function not supported!\" << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\t\t}\n\n\tprotected:\n\n\t\t/**\n\t\t * The P values for individual coefficients, given the z values.\n\t\t */\n\t\tVectorType PValue( const VectorType& zValues )\n\t\t{\n\t\t\tVectorType pValues( zValues.size(), 0.0 );\n\n\t\t\tfor ( unsigned int i = 0; i < zValues.size(); i++ )\n\t\t\t{\n\t\t\t\t// two-sided\n\t\t\t\tboost::math::normal s;\n\t\t\t\tPixelType alpha = boost::math::pdf( s, zValues( i ) ) * 2.;\n\t\t\t\tpValues( i ) = alpha;\n\t\t\t}\n\t\t\treturn pValues;\n\t\t}\n\n\t\t/**\n\t\t * The z statistics for individual coefficients.\n\t\t */\n\t\tVectorType ZStatistic( const VectorType& coefficients, const VectorType& response,\n\t\t\t\tconst MatrixType& covariates )\n\t\t{\n\t\t\tVectorType means = Means( coefficients, covariates );\n\t\t\tMatrixType weights = Weights( means, coefficients, covariates );\n\n\t\t\tMatrixType xwx = covariates * weights * covariates.transpose();\n\n\t\t\tvnl_svd< double > svd( xwx );\n\n\t\t\tMatrixType variance = svd.inverse();\n\n\t\t\tVectorType coefficientSE( variance.rows(), 0.0 );\n\n\t\t\tfor( unsigned int i = 0; i < variance.rows(); i++ )\n\t\t\t\tcoefficientSE( i ) = std::sqrt( variance( i, i ) );\n\n\t\t\tMatrixType correlation( variance.rows(), variance.rows(), 0.0 );\n\n\t\t\tfor( unsigned int i = 0; i < variance.rows(); i++)\n\t\t\t{\n\t\t\t\tfor ( unsigned int j = i; j < variance.rows(); j++ )\n\t\t\t\t{\n\t\t\t\t\tcorrelation( i, j ) = variance( i, j ) /\n\t\t\t\t\t\t\t\t\t\t\tstd::sqrt(variance( i, i ) * variance( j, j ) );\n\n\t\t\t\t\tcorrelation( j, i ) = correlation( i, j );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tVectorType zValues( coefficients.size(), 0.0 );\n\n\t\t\tfor( unsigned int i = 0; i < zValues.size(); i++ )\n\t\t\t\tzValues( i ) = coefficients( i ) / coefficientSE( i );\n\n\t\t\treturn zValues;\n\t\t}\n\n\t\t/**\n\t\t * Return number of training dimensions.\n\t\t */\n\t\tunsigned int GetNumberOfTrainingDims( const std::string& trainingData )\n\t\t{\n\t\t\tstd::string sep = \"\\t\";\n\t\t\tstd::ifstream in( trainingData.c_str() );\n\n\t\t\tif ( in.fail() )\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: could not read labels from: \" << trainingData << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\n\t\t\tstd::string line;\n\t\t\tgetline( in, line );\n\n\t\t\tTokType tok( line, boost::char_separator< char >( sep.c_str() ) );\n\n\t\t\tunsigned int results = 0;\n\t\t\ttry\n\t\t\t{\n\t\t\t\tfor ( TokType::iterator id = tok.begin(); id != tok.end(); ++id )\n\t\t\t\t\tresults++;\n\t\t\t}\n\t\t\tcatch ( boost::bad_lexical_cast& e )\n\t\t\t{\n\t\t\t\tstd::cout << \"*** WARNING ***: bad lexical cast during training data parsing!\" << std::endl;\n\t\t\t}\n\t\t\tin.close();\n\t\t\treturn results;\n\t\t}\n\n\t\t/**\n\t\t * Return number of training data points.\n\t\t */\n\t\tunsigned int GetNumberOfTrainingPoints( const std::string& trainingData )\n\t\t{\n\t\t\tstd::ifstream in( trainingData.c_str() );\n\n\t\t\tif ( in.fail() )\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: could not read labels from: \" << trainingData << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\t\t\tstd::string line;\n\t\t\tunsigned int result = 0;\n\n\t\t\twhile ( getline( in, line ) )\n\t\t\t{\n\t\t\t\tresult++;\n\t\t\t}\n\n\t\t\tin.close();\n\t\t\treturn result;\n\t\t}\n\n\t\t/**\n\t\t * Add column with initial intercept values (1.0).\n\t\t */\n\t\tMatrixType AddIntercept( const MatrixType& M )\n\t\t{\n\t\t\tMatrixType result( M.rows() + 1, M.cols() );\n\n\t\t\tfor( unsigned int i = 0; i < result.rows(); i++ )\n\t\t\t{\n\t\t\t\tfor( unsigned int j = 0; j < result.cols(); j++ )\n\t\t\t\t{\n\t\t\t\t\tif( i == 0 )\n\t\t\t\t\t\tresult( i, j ) = 1.0;\n\t\t\t\t\telse\n\t\t\t\t\t\tresult( i, j ) = M( i - 1, j );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\n\t\t/**\n\t\t * Read data from text file.\n\t\t */\n\t\tvoid ReadData( const std::string& sep, const std::string& inputFileName, MatrixType& covariates, VectorType& binaryResponse, PixelType percentage )\n\t\t{\n\t\t\tunsigned int dims = GetNumberOfTrainingDims( inputFileName );\n\t\t\tunsigned int points = GetNumberOfTrainingPoints( inputFileName );\n\n\t\t\tcovariates = MatrixType( dims - 1, points, 0.0 );\n\t\t\tbinaryResponse = VectorType( points, 0.0 );\n\n\t\t\t// open training data ...\n\t\t\tstd::ifstream in( inputFileName.c_str() );\n\t\t\tif ( in.fail() )\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: could not read data from: \" << inputFileName << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\n\t\t\t// insert all values into matrix, except the last one (responses) which is inserted in\n\t\t\t// the respose vector ...\n\t\t\tstd::string line;\n\t\t\tunsigned int rowIndex = 0;\n\t\t\twhile ( getline( in, line ) )\n\t\t\t{\n\t\t\t\tTokType tok( line, boost::char_separator< char >( sep.c_str() ) );\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tunsigned int colIndex = 0;\n\t\t\t\t\tfor ( TokType::iterator id = tok.begin(); id != tok.end(); ++id )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( colIndex == dims - 1 ) // last column ...\n\t\t\t\t\t\t\tbinaryResponse( rowIndex ) = boost::lexical_cast< PixelType >( *id );\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tcovariates( colIndex, rowIndex ) = boost::lexical_cast< PixelType >( *id );\n\n\t\t\t\t\t\tcolIndex++;\n\t\t\t\t\t}\n\t\t\t\t\trowIndex++;\n\t\t\t\t} catch ( boost::bad_lexical_cast& e )\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"*** WARNING ***: could not parse data! (is it in column format?)\" << std::endl;\n\t\t\t\t\te.what();\n\t\t\t\t\texit( EXIT_FAILURE );\n\t\t\t\t}\n\t\t\t}\n\t\t\tin.close();\n\n\t\t\tif ( ( percentage > 0 ) && ( percentage < 100 ) )\n\t\t\t{\n\t\t\t\tResizeTrainingData( covariates, binaryResponse, percentage );\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Reduce number of training-points to given percentage.\n\t\t */\n\n\t\tvoid ResizeTrainingData( MatrixType& trainingData, VectorType& trainingClasses,\n\t\t\t\tPixelType percentage )\n\t\t{\n\t\t\tunsigned int pointsToKeep = ( trainingClasses.size() * percentage ) / 100.0;\n\n\t\t\t// initialize vector ...\n\t\t\tVectorType subClasses( pointsToKeep, 0.0 );\n\n\t\t\t// initialize matrix ...\n\t\t\tMatrixType subData( trainingData.rows(), pointsToKeep, 0.0 );\n\n\t\t\t// create generator ...\n\t\t\trandom_number_type generator( time( 0 ) );\n\n\t\t\tVectorType indices = GetRandomValues( trainingClasses, generator, pointsToKeep );\n\n\t\t\t// insert random samples ...\n\t\t\tfor ( unsigned int i = 0; i < indices.size(); i++ )\n\t\t\t{\n\t\t\t\tsubClasses( i ) = trainingClasses( indices( i ) );\n\n\t\t\t\tfor ( unsigned int j = 0; j < subData.rows(); j++ )\n\t\t\t\t\tsubData( j, i ) = trainingData( j, indices( i ) );\n\t\t\t}\n\n\t\t\ttrainingData = subData;\n\t\t\ttrainingClasses = subClasses;\n\t\t}\n\n\t\t/**\n\t\t * Return uniform random values vector from inputs, with similar size.\n\t\t */\n\t\tVectorType GetRandomValues( const VectorType& inputs, random_number_type& generator, unsigned int total )\n\t\t{\n\t\t\t// uniform distribution: 0 -> largest index ...\n\t\t\tint_distribution_type int_uni_dist( 0, inputs.size() - 1 );\n\n\t\t\t// generator ...\n\t\t\tint_generator_type int_distribution( generator, int_uni_dist );\n\n\t\t\tVectorType results( total, 0.0 );\n\n\t\t\tfor ( unsigned int i = 0; i < total; i++ )\n\t\t\t\tresults( int_distribution() );\n\n\t\t\treturn results;\n\t\t}\n\n\n\t\t/**\n\t\t * Return weight matrix.\n\t\t */\n\t\tMatrixType Weights( const VectorType& means, const VectorType& coefficients, const MatrixType& covariate )\n\t\t{\n\t\t\tMatrixType weights( means.size(), means.size(), 0 );\n\n\t\t\tfor ( unsigned int i = 0; i < means.size(); i++ )\n\t\t\t\tweights( i, i ) = means( i ) * ( 1. - ( means( i ) ) );\n\n\t\t\treturn weights;\n\t\t}\n\n\t\t/**\n\t\t * Return means vector.\n\t\t */\n\t\tVectorType Means( const VectorType& coefficients, const MatrixType& covariate )\n\t\t{\n\t\t\tVectorType linearPredictors = GetColumnPackedCopy( covariate.transpose() * Vector2Matrix( coefficients ) );\n\n\t\t\tVectorType means( linearPredictors.size() );\n\n\t\t\tfor ( unsigned int i = 0; i < means.size(); i++ )\n\t\t\t\tmeans( i) = std::exp( linearPredictors( i ) ) / ( static_cast< PixelType > ( 1.0 ) + std::exp( linearPredictors( i ) ) );\n\n\t\t\treturn means;\n\t\t}\n\n\t\t/**\n\t\t * Construct matrix from vector.\n\t\t */\n\t\tMatrixType Vector2Matrix( const VectorType& V )\n\t\t{\n\t\t\tMatrixType A( V.size(), 1 );\n\t\t\tA.set_column( 0, V );\n\n\t\t\treturn A;\n\t\t}\n\n\t\t/**\n\t\t * Convert all matrix columns to vector.\n\t\t */\n\t\tVectorType GetColumnPackedCopy( const MatrixType& M )\n\t\t{\n\t\t\tVectorType V( M.rows() * M.cols() );\n\n\t\t\tfor ( unsigned int i = 0; i < M.rows(); i++ )\n\t\t\t\tfor ( unsigned int j = 0; j < M.cols(); j++ )\n\t\t\t\t\tV( i + j * M.rows() ) = M( i, j );\n\n\t\t\treturn V;\n\t\t}\n\n\t\t/**\n\t\t * Set initial values for IRLS estimation.\n\t\t */\n\t\tVectorType SetInit( const MatrixType& covariate )\n\t\t{\n\t\t\tVectorType V( covariate.rows() );\n\n\t\t\tPixelType a = 0;\n\n\t\t\tfor ( unsigned int i = 0; i < V.size(); i++ )\n\t\t\t{\n\t\t\t\ta = 0;\n\t\t\t\tfor ( unsigned int j = 0; j < covariate.get_row( i ).size(); j++ )\n\t\t\t\t{\n\t\t\t\t\ta += covariate( i, j );\n\t\t\t\t}\n\n\t\t\t\tV( i) = covariate.get_row( i ).size() / ( static_cast< PixelType > ( 100 ) * a );\n\t\t\t}\n\t\t\treturn V;\n\t\t}\n\n\t\t/**\n\t\t * Reweighted Least Squares ( IRLS ) estimation, by finding the\n\t\t * maximum likelihood estimates of a generalized linear model( GLM ).\n\t\t */\n\t\tVectorType IRLS( const VectorType& response, const MatrixType& covariate, unsigned int max_iter, bool verbose )\n\t\t{\n\t\t\tif ( response.size() != covariate.cols() )\n\t\t\t{\n\t\t\t\tstd::cerr << \"*** ERROR ***: The response vector and rows of the \"\n\t\t\t\t\t\"covariate matrix must have the same length.\" << std::endl;\n\t\t\t\texit( EXIT_FAILURE );\n\t\t\t}\n\n\t\t\tVectorType coefficients = SetInit( covariate );\n\n\t\t\tMatrixType responseMatrix = Vector2Matrix( response );\n\n\t\t\tPixelType error = 1.0;\n\n\t\t\tMatrixType covariateMatrix( covariate );\n\n\t\t\tif( verbose )\n\t\t\t\tstd::cout << \"Starting iterative solving...\" << std::endl;\n\n\t\t\tunsigned int iter = 0;\n\t\t\twhile ( error > 0.000001 )\n\t\t\t{\n\t\t\t\tif( iter > max_iter )\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"*** ERROR ***: maximum iteration reached. No convergence.\"<< std::endl;\n\t\t\t\t\texit( EXIT_FAILURE );\n\t\t\t\t}\n\n\t\t\t\tif( verbose )\n\t\t\t\t\tstd::cout << \"Iteration: \" << iter << std::endl;\n\n\t\t\t\tMatrixType coefficientMatrix = Vector2Matrix( coefficients );\n\n\t\t\t\tVectorType means = Means( coefficients, covariate );\n\t\t\t\tMatrixType weights = Weights( means, coefficients, covariate );\n\n\t\t\t\tMatrixType inversedWeights( weights.rows(), weights.cols() );\n\t\t\t\tMatrixType weight = MatrixType( weights );\n\n\t\t\t\tfor ( unsigned int i = 0; i < weights.rows(); i++ )\n\t\t\t\t{\n\t\t\t\t\tif ( weights( i, i ) == 0. )\n\t\t\t\t\t\tinversedWeights( i, i ) = 0.;\n\t\t\t\t\telse\n\t\t\t\t\t\tinversedWeights( i, i ) = static_cast< PixelType > ( 1. ) / weights( i, i );\n\t\t\t\t}\n\n\t\t\t\tMatrixType linearPredictor = covariateMatrix.transpose() * coefficientMatrix;\n\t\t\t\tMatrixType z = linearPredictor + ( inversedWeights ) * ( responseMatrix - ( Vector2Matrix( means ) ) );\n\t\t\t\tMatrixType xwx = covariateMatrix * ( weight * covariateMatrix.transpose() );\n\n\t\t\t\t// Correct for rows with all values close to zero, by adding 0.1 to diagonal ...\n\t\t\t\tif ( std::abs( vnl_determinant< PixelType > ( xwx ) ) <= 1e-8 )\n\t\t\t\t\tfor ( unsigned int i = 0; i < xwx.rows(); i++ )\n\t\t\t\t\t\txwx( i, i ) = xwx( i, i ) + 0.1;\n\n\t\t\t\t// inverse...\n\t\t\t\tvnl_svd< PixelType > svd( xwx );\n\n\t\t\t\tMatrixType updatedCoefficient = svd.inverse() * ( ( covariateMatrix * weight ) * z );\n\n\t\t\t\tcoefficients = GetColumnPackedCopy( updatedCoefficient );\n\t\t\t\terror = std::pow( ( updatedCoefficient - coefficientMatrix ).frobenius_norm(), 2.0 );\n\n\t\t\t\titer++;\n\t\t\t}\n\n\t\t\treturn coefficients;\n\t\t}\n\n\t};\n} // end namespace generalized_linear_model\n\n\n\n/**\n * Main.\n */\nint main( int argc, char ** argv )\n{\n\ttkd::CmdParser p( argv[0], \"Generalized linear model\" );\n\n\tparameters list;\n\n\tlist.iterations = 100000;\n\tlist.link = \"logistic\";\n\tlist.separation = \"\\t\";\n\tlist.percentage = 100.0;\n\tlist.verbose = false;\n\tlist.printPValues = false;\n\tlist.printZValues = false;\n\n\tp.AddArgument( list.inputFileName, \"input\" ) ->AddAlias( \"i\" ) ->SetInput( \"filename\" ) ->SetDescription(\n\t\t\t\"Input file: list of covariate(s) and response function (column format)\" ) ->SetRequired( true );\n\n\tp.AddArgument( list.link, \"link\" ) ->AddAlias( \"l\" ) ->SetInput( \"string\" ) ->SetDescription( \"Link function (default: \\\"logistic\\\")\" );\n\n\tp.AddArgument( list.separation, \"separation\" ) ->AddAlias( \"s\" ) ->SetInput( \"string\" ) ->SetDescription( \"Data separator string (default: \\\\t\" );\n\n\tp.AddArgument( list.printZValues, \"print-z-values\" ) ->AddAlias( \"pz\" ) ->SetInput( \"bool\" ) ->SetDescription( \"Print Z-values for coefficients (default: false\" );\n\n\tp.AddArgument( list.printPValues, \"print-p-values\" ) ->AddAlias( \"pp\" ) ->SetInput( \"bool\" ) ->SetDescription( \"Print P-values for coefficients (default: false\" );\n\n\tp.AddArgument( list.percentage, \"percentage\" ) ->AddAlias( \"p\" ) ->SetInput( \"float\" ) ->SetDescription(\n\t\t\t\"Percentage of covariates to select randomly (default: 100)\" );\n\n\tp.AddArgument( list.verbose, \"verbose\" ) ->AddAlias( \"v\" ) ->SetInput( \"bool\" ) ->SetDescription( \"Verbose (default: false\" );\n\n\tif ( !p.Parse( argc, argv ) )\n\t{\n\t\tp.PrintUsage( std::cout );\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tgeneralized_linear_model::GLM glm;\n\n\tglm.Run( list );\n\n\treturn EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "6a564350d08171ab0997eb56f4ad52c510d8680c", "size": 15234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/glm/glm.cpp", "max_stars_repo_name": "wmotte/toolkid", "max_stars_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/glm/glm.cpp", "max_issues_repo_name": "wmotte/toolkid", "max_issues_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/glm/glm.cpp", "max_forks_repo_name": "wmotte/toolkid", "max_forks_repo_head_hexsha": "2a8f82e1492c9efccde9a4935ce3019df1c68cde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6981818182, "max_line_length": 164, "alphanum_fraction": 0.6337797033, "num_tokens": 4257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581684030623, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4368890252958125}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Utilities/Rational.hpp\"\n\n#include <boost/functional/hash.hpp>\n#include <boost/integer/common_factor_rt.hpp>\n#include <ostream>\n#include <pup.h>\n#include <tuple>\n\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n\n// IWYU pragma: no_include <boost/cstdint.hpp>\n\nnamespace {\n// This is needed a lot, so define a shorter name.\nstd::int64_t to64(const std::int32_t n) { return static_cast<std::int64_t>(n); }\n\ntemplate <typename IntType>\nstd::tuple<std::int32_t, std::int32_t> reduce(IntType numerator,\n                                              IntType denominator) {\n  const IntType common_factor = boost::integer::gcd(numerator, denominator);\n  numerator /= common_factor;\n  denominator /= common_factor;\n  if (denominator < 0) {\n    numerator = -numerator;\n    denominator = -denominator;\n  }\n  ASSERT(static_cast<std::int32_t>(numerator) == numerator and\n         static_cast<std::int32_t>(denominator) == denominator,\n         \"Rational overflow: \" << numerator << \"/\" << denominator);\n  return std::make_tuple(numerator, denominator);\n}\n}  // namespace\n\nRational::Rational(const std::int32_t numerator,\n                   const std::int32_t denominator) {\n  ASSERT(denominator != 0, \"Division by zero\");\n  std::tie(numerator_, denominator_) = reduce(numerator, denominator);\n}\n\ndouble Rational::value() const {\n  return static_cast<double>(numerator_) / static_cast<double>(denominator_);\n}\n\nRational Rational::inverse() const {\n  // Default construct to avoid the reduce() call.\n  ASSERT(*this != 0, \"Division by zero\");\n  Rational ret;\n  ret.numerator_ = denominator_;\n  ret.denominator_ = numerator_;\n  if (ret.denominator_ < 0) {\n    ret.numerator_ = -ret.numerator_;\n    ret.denominator_ = -ret.denominator_;\n  }\n  return ret;\n}\n\nRational& Rational::operator+=(const Rational& other) {\n  std::tie(numerator_, denominator_) =\n      reduce(to64(numerator_) * to64(other.denominator_) +\n             to64(denominator_) * to64(other.numerator_),\n             to64(denominator_) * to64(other.denominator_));\n  return *this;\n}\nRational& Rational::operator-=(const Rational& other) {\n  return *this += -other;\n}\nRational& Rational::operator*=(const Rational& other) {\n  std::tie(numerator_, denominator_) =\n      reduce(to64(numerator_) * to64(other.numerator()),\n             to64(denominator_) * to64(other.denominator()));\n  return *this;\n}\nRational& Rational::operator/=(const Rational& other) {\n  return *this *= other.inverse();\n}\n\nvoid Rational::pup(PUP::er& p) {\n  p | numerator_;\n  p | denominator_;\n}\n\nRational operator-(Rational r) {\n  // No reduced-form check needed\n  r.numerator_ = -r.numerator_;\n  return r;\n}\n\nRational operator+(const Rational& a, const Rational& b) {\n  Rational ret = a;\n  ret += b;\n  return ret;\n}\nRational operator-(const Rational& a, const Rational& b) {\n  Rational ret = a;\n  ret -= b;\n  return ret;\n}\nRational operator*(const Rational& a, const Rational& b) {\n  Rational ret = a;\n  ret *= b;\n  return ret;\n}\nRational operator/(const Rational& a, const Rational& b) {\n  Rational ret = a;\n  ret /= b;\n  return ret;\n}\n\nbool operator==(const Rational& a, const Rational& b) {\n  return a.numerator() == b.numerator() and a.denominator() == b.denominator();\n}\nbool operator!=(const Rational& a, const Rational& b) { return not(a == b); }\nbool operator<(const Rational& a, const Rational& b) {\n  return to64(a.numerator()) * to64(b.denominator()) <\n         to64(b.numerator()) * to64(a.denominator());\n}\nbool operator>(const Rational& a, const Rational& b) { return b < a; }\nbool operator<=(const Rational& a, const Rational& b) { return not(b < a); }\nbool operator>=(const Rational& a, const Rational& b) { return not(a < b); }\n\nstd::ostream& operator<<(std::ostream& os, const Rational& r) {\n  return os << r.numerator() << '/' << r.denominator();\n}\n\nsize_t hash_value(const Rational& r) {\n  size_t h = 0;\n  boost::hash_combine(h, r.numerator());\n  boost::hash_combine(h, r.denominator());\n  return h;\n}\n\n// clang-tidy: do not modify std namespace (okay for hash)\nnamespace std {  // NOLINT\nsize_t hash<Rational>::operator()(const Rational& r) const {\n  return boost::hash<Rational>{}(r);\n}\n}  // namespace std\n", "meta": {"hexsha": "acdd1777197dd98d18312fb0dfce4f56f468745c", "size": 4227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utilities/Rational.cpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 117.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T22:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:23:36.000Z", "max_issues_repo_path": "src/Utilities/Rational.cpp", "max_issues_repo_name": "GitHimanshuc/spectre", "max_issues_repo_head_hexsha": "4de4033ba36547113293fe4dbdd77591485a4aee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3177.0, "max_issues_repo_issues_event_min_datetime": "2017-04-07T21:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:59.000Z", "max_forks_repo_path": "src/Utilities/Rational.cpp", "max_forks_repo_name": "geoffrey4444/spectre", "max_forks_repo_head_hexsha": "9350d61830b360e2d5b273fdd176dcc841dbefb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2017-04-07T19:36:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T10:21:00.000Z", "avg_line_length": 29.9787234043, "max_line_length": 80, "alphanum_fraction": 0.6723444523, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.436889021873531}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2014, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/*\n*\n*   Tutorial: Using ViennaCL with multiple threads for a conjugate gradient solver, one thread per GPU\n*\n*/\n\n#ifndef VIENNACL_WITH_OPENCL\n  #define VIENNACL_WITH_OPENCL\n#endif\n\n// include necessary system headers\n#include <iostream>\n\n//\n// ublas includes\n//\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/operation_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n// Must be set if you want to use ViennaCL algorithms on ublas objects\n#define VIENNACL_WITH_UBLAS 1\n\n\n//include basic scalar and vector types of ViennaCL\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n\n#include \"viennacl/ocl/device.hpp\"\n#include \"viennacl/ocl/platform.hpp\"\n#include \"viennacl/ocl/backend.hpp\"\n\n//include the generic inner product functions of ViennaCL\n#include \"viennacl/linalg/norm_2.hpp\"\n#include \"viennacl/linalg/cg.hpp\"\n\n// Some helper functions for this tutorial:\n#include \"Random.hpp\"\n#include \"vector-io.hpp\"\n\nusing namespace boost::numeric;\n\n#include <boost/thread.hpp>\n\ntemplate<typename NumericT>\nclass worker\n{\npublic:\n  worker(std::size_t tid) : thread_id_(tid) {}\n\n  void operator()()\n  {\n    //\n    // Set up some ublas objects\n    //\n    ublas::vector<NumericT> rhs;\n    ublas::vector<NumericT> ref_result;\n    ublas::compressed_matrix<NumericT> ublas_matrix;\n\n    //\n    // Read system from file\n    //\n    if (!viennacl::io::read_matrix_market_file(ublas_matrix, \"../examples/testdata/mat65k.mtx\"))\n    {\n      std::cout << \"Error reading Matrix file\" << std::endl;\n      return;\n    }\n\n    if (!readVectorFromFile(\"../examples/testdata/rhs65025.txt\", rhs))\n    {\n      std::cout << \"Error reading RHS file\" << std::endl;\n      return;\n    }\n\n    if (!readVectorFromFile(\"../examples/testdata/result65025.txt\", ref_result))\n    {\n      std::cout << \"Error reading Result file\" << std::endl;\n      return;\n    }\n\n    //\n    // Set up some ViennaCL objects in the respective context\n    //\n    viennacl::context ctx(viennacl::ocl::get_context(static_cast<long>(thread_id_)));\n\n    std::size_t vcl_size = rhs.size();\n    viennacl::compressed_matrix<NumericT> vcl_compressed_matrix(ctx);\n    viennacl::vector<NumericT> vcl_rhs(vcl_size, ctx);\n    viennacl::vector<NumericT> vcl_ref_result(vcl_size, ctx);\n\n    viennacl::copy(rhs.begin(), rhs.end(), vcl_rhs.begin());\n    viennacl::copy(ref_result.begin(), ref_result.end(), vcl_ref_result.begin());\n\n\n    //\n    // Transfer ublas-matrix to GPU:\n    //\n    viennacl::copy(ublas_matrix, vcl_compressed_matrix);\n\n    viennacl::vector<NumericT> vcl_result = viennacl::linalg::solve(vcl_compressed_matrix, vcl_rhs, viennacl::linalg::cg_tag());\n\n    std::stringstream ss;\n    ss << \"Result of thread \" << thread_id_ << \" on device \" << viennacl::ocl::get_context(static_cast<long>(thread_id_)).devices()[0].name() << \": \" << vcl_result[0] << \", should: \" << ref_result[0] << std::endl;\n    message_ = ss.str();\n  }\n\n  std::string message() const { return message_; }\n\nprivate:\n  std::string message_;\n  std::size_t thread_id_;\n};\n\n\nint main()\n{\n  //Change this type definition to double if your gpu supports that\n  typedef float       ScalarType;\n\n  if (viennacl::ocl::get_platforms().size() == 0)\n  {\n    std::cerr << \"Error: No platform found!\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  //\n  // Part 1: Setup first device for first context, second device for second context:\n  //\n  viennacl::ocl::platform pf = viennacl::ocl::get_platforms()[0];\n  std::vector<viennacl::ocl::device> const & devices = pf.devices();\n\n  // Set first device to first context:\n  viennacl::ocl::setup_context(0, devices[0]);\n\n  // Set second device for second context (use the same device for the second context if only one device available):\n  if (devices.size() > 1)\n    viennacl::ocl::setup_context(1, devices[1]);\n  else\n    viennacl::ocl::setup_context(1, devices[0]);\n\n  //\n  // Part 2: Now let two threads operate on two GPUs in parallel\n  //\n\n  worker<ScalarType> work_functor0(0);\n  worker<ScalarType> work_functor1(1);\n  boost::thread worker_thread_0(boost::ref(work_functor0));\n  boost::thread worker_thread_1(boost::ref(work_functor1));\n\n  worker_thread_0.join();\n  worker_thread_1.join();\n\n  std::cout << work_functor0.message() << std::endl;\n  std::cout << work_functor1.message() << std::endl;\n\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "a04b210fca70a64fdd88767a9c97c7fc87b8db1b", "size": 5494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/multithreaded_cg.cpp", "max_stars_repo_name": "denis14/ViennaCL-1.5.2", "max_stars_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/tutorial/multithreaded_cg.cpp", "max_issues_repo_name": "denis14/ViennaCL-1.5.2", "max_issues_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tutorial/multithreaded_cg.cpp", "max_forks_repo_name": "denis14/ViennaCL-1.5.2", "max_forks_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5376344086, "max_line_length": 213, "alphanum_fraction": 0.6541681835, "num_tokens": 1400, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.436889021873531}}
{"text": "// clang-format off\n// MUST BE at the beginning before any other <cmath> include (e.g. in armadillo's headers)\n#define _USE_MATH_DEFINES // required for Visual Studio\n#include <cmath>\n// clang-format on\n\n#include \"libKriging/Bench.hpp\"\n#include \"libKriging/OrdinaryKriging.hpp\"\n\n#include <armadillo>\n#include <optim.hpp>\n#include <tuple>\n\n// #include \"libKriging/covariance.h\"\n\nLIBKRIGING_EXPORT Bench::Bench(int _n) {\n  n = _n;\n}\n\n////////////////// LogLik /////////////////////\n//' @ref https://github.com/cran/DiceKriging/blob/master/R/logLikFun.R\n//  model@covariance <- vect2covparam(model@covariance, param)\n//  model@covariance@sd2 <- 1\t\t# to get the correlation matrix\n//\n//  aux <- covMatrix(model@covariance, model@X)\n//\n//  R <- aux[[1]]\n//  T <- chol(R)\n//\n//  x <- backsolve(t(T), model@y, upper.tri = FALSE)\n//  M <- backsolve(t(T), model@F, upper.tri = FALSE)\n//  z <- compute.z(x=x, M=M, beta=beta)\n//  sigma2.hat <- compute.sigma2.hat(z)\n//  logLik <- -0.5*(model@n * log(2*pi*sigma2.hat) + 2*sum(log(diag(T))) + model@n)\n\n////////////////// LogLikGrad /////////////////////\n//' @ref https://github.com/cran/DiceKriging/blob/master/R/logLikGrad.R\n//  logLik.derivative <- matrix(0,nparam,1)\n//  x <- backsolve(T,z)\t\t\t# compute x := T^(-1)*z\n//  Rinv <- chol2inv(T)\t\t\t# compute inv(R) by inverting T\n//\n//  Rinv.upper <- Rinv[upper.tri(Rinv)]\n//  xx <- x%*%t(x)\n//  xx.upper <- xx[upper.tri(xx)]\n//\n//  for (k in 1:nparam) {\n//    gradR.k <- CovMatrixDerivative(model@covariance, X=model@X, C0=R, k=k)\n//    gradR.k.upper <- gradR.k[upper.tri(gradR.k)]\n//\n//    terme1 <- sum(xx.upper*gradR.k.upper)   / sigma2.hat\n//    # quick computation of t(x)%*%gradR.k%*%x /  ...\n//    terme2 <- - sum(Rinv.upper*gradR.k.upper)\n//    # quick computation of trace(Rinv%*%gradR.k)\n//    logLik.derivative[k] <- terme1 + terme2\n//  }\n\nLIBKRIGING_EXPORT\narma::mat Bench::SolveTri(const arma::mat& Xtri, const arma::vec& y) {\n  arma::mat s;\n  for (int i = 0; i < n; i++) {\n    s = arma::solve(arma::trimatu(Xtri), y, arma::solve_opts::fast);\n  }\n  return s;\n}\n\nLIBKRIGING_EXPORT\narma::mat Bench::CholSym(const arma::mat& Rsym) {\n  arma::mat s;\n  for (int i = 0; i < n; i++) {\n    s = arma::chol(Rsym);\n  }\n  return s;\n}\n\nLIBKRIGING_EXPORT\nstd::tuple<arma::mat, arma::mat> Bench::QR(const arma::mat& M) {\n  arma::mat Q;\n  arma::mat R;\n  for (int i = 0; i < n; i++) {\n    arma::qr_econ(Q, R, M);\n  }\n  return std::make_tuple(std::move(Q), std::move(R));\n}\n\nLIBKRIGING_EXPORT\narma::mat Bench::InvSymPD(const arma::mat& Rsympd) {\n  arma::mat s;\n  for (int i = 0; i < n; i++) {\n    s = arma::inv_sympd(Rsympd);\n  }\n  return s;\n}\n\nLIBKRIGING_EXPORT\ndouble Bench::LogLik(OrdinaryKriging& ok, const arma::vec& theta) {\n  // arma::vec theta = 0.5*ones(ok->X().n_cols)\n  double s = 0;\n  for (int i = 0; i < n; i++) {\n    s += ok.logLikelihood(theta);\n  }\n  return s / n;\n}\n\nLIBKRIGING_EXPORT\narma::vec Bench::LogLikGrad(OrdinaryKriging& ok, const arma::vec& theta) {\n  // arma::vec theta = 0.5*ones(ok->X().n_cols)\n  arma::vec s = arma::zeros(theta.n_elem);\n  for (int i = 0; i < n; i++) {\n    s += ok.logLikelihoodGrad(theta);\n  }\n  return s / n;\n  }\n\n\ndouble a = .5;\ndouble b = 50;\ninline double rosenbrock_fun(arma::vec X) noexcept {\n  return (a-X(0))*(a-X(0))+b*(X(1)-X(0)*X(0))*(X(1)-X(0)*X(0));\n};\ninline arma::vec rosenbrock_grad(arma::vec X) noexcept {\n  arma::vec g = arma::zeros(2);\n  g(0) = -2*(a-X(0)) + 4*b*(X(0)*X(0)*X(0) - X(1)*X(0));\n  g(1) = 2*b*(X(1) - X(0)*X(0));\n  return g;\n};\n\n  double ofn_rosenbrock(const arma::vec& x,arma::vec* grad_out,void* ofn_data) {\n    if (ofn_data) {\n    Bench::OFNData* fd = reinterpret_cast<Bench::OFNData*>(ofn_data);\n    if (fd->histx.n_cols != x.n_elem)\n      fd->histx = arma::reshape(x,1,x.n_elem);\n    else\n      fd->histx.insert_rows(fd->histx.n_rows,trans(arma::mat(x)));\n    }\n    arma::cout << \"x \"<< x << arma::endl;\n    if (grad_out) {\n      arma::cout << \"g\";\n      *grad_out = rosenbrock_grad(x);\n    } else     arma::cout << \"o\";\n    \n    return rosenbrock_fun(x);\n  }\n  \n  LIBKRIGING_EXPORT\n    double Bench::Rosenbrock(arma::vec& x) {\n      return rosenbrock_fun(x);\n    } \n  \n  LIBKRIGING_EXPORT\n    arma::vec Bench::RosenbrockGrad(arma::vec& x) { \n      return rosenbrock_grad(x);\n    } \n  \n  LIBKRIGING_EXPORT\n    arma::mat Bench::OptimRosenbrock(arma::vec& x0) {\n      \n      optim::algo_settings_t algo_settings;\n      algo_settings.vals_bound = true;\n      algo_settings.lower_bounds = arma::zeros<arma::vec>(2);\n      algo_settings.upper_bounds = arma::ones<arma::vec>(2);\n      \n      algo_settings.iter_max = 10;  // TODO change by default?\n      algo_settings.err_tol = 1e-9;\n      \n      algo_settings.gd_method = 2;\n      algo_settings.gd_settings.step_size=0.01;\n      algo_settings.gd_settings.norm_term=1E-7;\n      algo_settings.gd_settings.ada_rho=0.9;\n      \n      algo_settings.cg_method = 2; \n      \n      Bench::OFNData ofn_data; // FIXME AFTER\n      arma::cout << \"> bfgs 2 \";\n      ofn_data.histx = arma::zeros(1,2);\n      bool bfgs_ok = optim::cg(\n        x0,\n        ofn_rosenbrock,\n        (void*)(&ofn_data),\n        algo_settings);\n      arma::cout << \" <\" << arma::endl;\n      \n      return ofn_data.histx;\n    }\n", "meta": {"hexsha": "72f95b5d3d6d5694e104600bc139ae627aa5e39d", "size": 5200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/Bench.cpp", "max_stars_repo_name": "yannrichet/libKriging", "max_stars_repo_head_hexsha": "25475d1de02d518401183e93f6a0fa5c12b3c96b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lib/Bench.cpp", "max_issues_repo_name": "yannrichet/libKriging", "max_issues_repo_head_hexsha": "25475d1de02d518401183e93f6a0fa5c12b3c96b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/Bench.cpp", "max_forks_repo_name": "yannrichet/libKriging", "max_forks_repo_head_hexsha": "25475d1de02d518401183e93f6a0fa5c12b3c96b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2608695652, "max_line_length": 90, "alphanum_fraction": 0.5971153846, "num_tokens": 1787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.43688902187353096}}
{"text": "#include \"utils.h\"\n#include <NTL/GF2X.h>\n#include <openssl/evp.h>\n#include <openssl/sha.h>\n#include <vector>\n#include <rank/rank_params.h>\n#include <random>\n\nstatic int is_element_in_vector(const NTL::GF2E &element, const NTL::vec_GF2E &vector) {\n    for (int i = 0; i < vector.length(); i++) {\n        if (element == vector[i]) {\n            return 1;\n        }\n    }\n    return 0;\n}\n\nstatic void gf2_from_gf2e_element(NTL::vec_GF2 &res, const NTL::GF2E &v) {\n\n\n    if (NTL::IsZero(v)) {\n        for (int i = 0; i < v.degree(); i++) {\n            res.append(NTL::GF2(0));\n            return;\n        }\n    }\n\n    for (int i = 0; i < v.degree(); i++) {\n        res.append(v._GF2E__rep[i]);\n    }\n}\n\nNTL::GF2X utils::gf2x_from_gf2(const NTL::Vec<NTL::GF2> &in) {\n\n    NTL::GF2X v;\n    v.SetLength(in.length());\n\n    for (int i = 0; i < in.length(); i++) {\n        NTL::SetCoeff(v, i, in[i]);\n    }\n\n    return v;\n}\n\nNTL::Vec<NTL::GF2> utils::gf2_from_gf2x(const NTL::GF2X &in, int len) {\n    NTL::Vec<NTL::GF2> v;\n    NTL::VectorCopy(v, in, len);\n\n    return v;\n}\n\nNTL::GF2X utils::gf2x_from_matgf2(const NTL::mat_GF2 &in) {\n    NTL::GF2X v;\n    v.SetLength(in.NumRows() * in.NumCols());\n\n    for (int i = 0; i < in.NumRows(); i++) {\n        for (int j = 0; j < in.NumCols(); j++) {\n            v[(i * in.NumCols()) + j] = in[i][j];\n        }\n    }\n    return v;\n}\n\nNTL::GF2X utils::gf2x_from_gf2e(const NTL::vec_GF2E &in) {\n    NTL::GF2X v;\n    v.SetLength(in.length() * in[0].degree());\n\n    for (int i = 0; i < in.length(); i++) {\n        for (int j = 0; j < in[i].degree(); j++) {\n            NTL::SetCoeff(v, (i * in[i].degree()) + j, in[i]._GF2E__rep[j]);\n        }\n    }\n\n    return v;\n}\n\nNTL::vec_GF2 utils::gf2_from_gf2e(const NTL::vec_GF2E &in) {\n    NTL::vec_GF2 v;\n    v.SetLength(in.length() * in[0].degree());\n\n    for (int i = 0; i < in.length(); i++) {\n        for (int j = 0; j < in[i].degree(); j++) {\n            v[(i * in[i].degree()) + j] = in[i]._GF2E__rep[j];\n        }\n    }\n\n    return v;\n}\n\nNTL::vec_GF2E utils::gf2e_from_gf2x(const NTL::GF2X &in, int length) {\n    NTL::vec_GF2E v;\n    auto v_size = std::ceil((float) length / (float) v[0].degree());\n    v.SetLength(v_size);\n\n    for (int i = 0; i < v.length(); i++) {\n        for (int j = 0; j < v[i].degree(); j++) {\n            NTL::SetCoeff(v[i]._GF2E__rep, j, in[(i * v[i].degree()) + j]);\n        }\n    }\n    return v;\n}\n\nNTL::vec_GF2 utils::encode(const NTL::mat_GF2 &P, const NTL::mat_GF2 &Q, const NTL::vec_GF2E &V,\n                           int size) {\n\n    uint digest_length = SHA512_DIGEST_LENGTH;\n\n    const EVP_MD* algorithm = EVP_sha3_512();\n    EVP_MD_CTX* context = EVP_MD_CTX_new();\n    EVP_DigestInit_ex(context, algorithm, nullptr);\n\n    NTL::vec_GF2 out;\n    std::vector<uint8_t> hash(digest_length);\n\n    auto P_gf2x = gf2x_from_matgf2(P);\n    std::vector<uint8_t> P_bytes(NTL::NumBytes(P_gf2x));\n    NTL::BytesFromGF2X(P_bytes.data(), P_gf2x, P_bytes.size());\n    EVP_DigestUpdate(context, P_bytes.data(), P_bytes.size());\n\n    auto Q_gf2x = gf2x_from_matgf2(Q);\n    std::vector<uint8_t> Q_bytes(NTL::NumBytes(Q_gf2x));\n    NTL::BytesFromGF2X(Q_bytes.data(), Q_gf2x, Q_bytes.size());\n    EVP_DigestUpdate(context, Q_bytes.data(), Q_bytes.size());\n\n    auto V_gf2x = gf2x_from_gf2e(V);\n    std::vector<uint8_t> V_bytes(NTL::NumBytes(V_gf2x));\n    NTL::BytesFromGF2X(V_bytes.data(), V_gf2x, V_bytes.size());\n    EVP_DigestUpdate(context, V_bytes.data(), V_bytes.size());\n\n    EVP_DigestFinal_ex(context, hash.data(), &digest_length);\n\n    auto hash_gf2x = NTL::GF2XFromBytes(hash.data(), hash.size());\n\n    out = gf2_from_gf2x(hash_gf2x, size);\n\n    EVP_MD_CTX_destroy(context);\n\n    return out;\n}\n\nNTL::vec_GF2 utils::encode_2(const NTL::vec_GF2E &V, int size) {\n\n    uint digest_length = SHA512_DIGEST_LENGTH;\n    const EVP_MD* algorithm = EVP_sha3_512();\n    EVP_MD_CTX* context = EVP_MD_CTX_new();\n    EVP_DigestInit_ex(context, algorithm, nullptr);\n\n    NTL::vec_GF2 out;\n    std::vector<uint8_t> hash(digest_length);\n\n    auto V_gf2x = gf2x_from_gf2e(V);\n    std::vector<uint8_t> V_bytes(NTL::NumBytes(V_gf2x));\n    NTL::BytesFromGF2X(V_bytes.data(), V_gf2x, V_bytes.size());\n    EVP_DigestUpdate(context, V_bytes.data(), V_bytes.size());\n\n    EVP_DigestFinal_ex(context, hash.data(), &digest_length);\n\n    auto hash_gf2x = NTL::GF2XFromBytes(hash.data(), hash.size());\n\n    out = gf2_from_gf2x(hash_gf2x, size);\n\n    EVP_MD_CTX_destroy(context);\n\n    return out;\n}\n\nNTL::vec_GF2E utils::gf2e_from_two_gf2(const NTL::vec_GF2 &first, const NTL::vec_GF2 &second) {\n    NTL::vec_GF2E out;\n    auto out_size = std::ceil((float) (first.length() + second.length()) / (float) out[0].degree());\n    out.SetLength(out_size);\n\n    NTL::vec_GF2 first_second = first;\n    first_second.append(second);\n\n    for (int i = 0; i < out.length(); i++) {\n        for (int j = 0; j < out[i].degree(); j++) {\n            NTL::SetCoeff(out[i]._GF2E__rep, j, first_second[(i * out[i].degree()) + j]);\n        }\n    }\n\n    return out;\n}\n\nNTL::vec_GF2E utils::gf2e_from_vec_gf2(const NTL::vec_GF2 &in) {\n    NTL::vec_GF2E out;\n    auto out_size = std::ceil((float) in.length() / (float) out[0].degree());\n    out.SetLength(out_size);\n\n    for (int i = 0; i < out.length(); i++) {\n        for (int j = 0; j < out[i].degree(); j++) {\n            NTL::SetCoeff(out[i]._GF2E__rep, j, in[(i * out[i].degree()) + j]);\n        }\n    }\n\n    return out;\n}\n\nNTL::Vec<NTL::GF2> utils::encode_binary_vector(const NTL::Vec<NTL::GF2> &in, int size) {\n\n    uint digest_length = SHA512_DIGEST_LENGTH;\n    const EVP_MD* algorithm = EVP_sha3_512();\n    EVP_MD_CTX* context = EVP_MD_CTX_new();\n    EVP_DigestInit_ex(context, algorithm, nullptr);\n\n    auto in_to_gf2x = utils::gf2x_from_gf2(in);\n    std::vector<uint8_t> in_to_bytes(NTL::NumBytes(in_to_gf2x));\n    NTL::BytesFromGF2X(in_to_bytes.data(), in_to_gf2x, in_to_bytes.size());\n\n    std::vector<uint8_t> hash(NTL::NumBytes(in_to_gf2x));\n\n    EVP_DigestUpdate(context, in_to_bytes.data(), in_to_bytes.size());\n    EVP_DigestFinal_ex(context, hash.data(), &digest_length);\n\n    NTL::GF2X hash_to_gf2x;\n    NTL::GF2XFromBytes(hash_to_gf2x, hash.data(), hash.size());\n\n    auto hash_gf2 = utils::gf2_from_gf2x(hash_to_gf2x, size);\n\n    EVP_MD_CTX_destroy(context);\n\n    return hash_gf2;\n}\n\nvoid utils::sample_messages(\n        NTL::vec_GF2 &m_1,\n        NTL::vec_GF2 &m_2,\n        NTL::vec_GF2 &m_3,\n        int size) {\n\n    NTL::vec_GF2 _m_1, _m_2, _m_3;\n    {\n        _m_1.SetLength(4);\n        _m_2.SetLength(4);\n        _m_3.SetLength(4);\n\n        _m_1[2] = 1;\n        _m_1[3] = 1;\n\n        _m_2[1] = 1;\n        _m_2[3] = 1;\n\n        _m_3[3] = 1;\n    }\n\n    m_1.append(_m_1);\n    m_2.append(_m_2);\n    m_3.append(_m_3);\n\n    for (int i = 0; i < size - 1; i++) {\n\n        std::vector<uint> permutation;\n        {\n            permutation.resize(4);\n        }\n\n        create_random_permutation(\n                permutation,\n                4);\n\n        NTL::mat_GF2 permutation_matrix;\n        {\n            permutation_matrix.SetDims(4, 4);\n        }\n\n        for (uint j = 0; j < permutation.size(); j++) {\n            permutation_matrix[j][permutation[j]] = NTL::GF2(1);\n        }\n\n        m_1.append(permutation_matrix * _m_1);\n        m_2.append(permutation_matrix * _m_2);\n        m_3.append(permutation_matrix * _m_3);\n\n\n    }\n}\n\nvoid utils::create_random_permutation(\n        std::vector<uint> &permutation,\n        int size) {\n\n    permutation.resize(size);\n\n    for (uint i = 0; i < permutation.size(); i++) {\n        permutation[i] = i;\n    }\n\n    auto shuffled_vector = shuffle(\n            permutation,\n            permutation.size());\n\n    permutation = shuffled_vector;\n\n}\n\nvoid utils::create_permutation_matrix(\n        NTL::mat_GF2 &P,\n        const std::vector<uint> &permutation) {\n\n    for (uint i = 0; i < permutation.size(); i++) {\n        P[i][permutation[i]] = NTL::GF2(1);\n    }\n}\n\nvoid utils::create_permutation_matrix(\n        NTL::mat_GF2 &P,\n        int size) {\n\n    P.kill();\n    P.SetDims(size, size);\n\n    std::vector<uint> permutation(size);\n\n    create_random_permutation(\n            permutation,\n            size);\n\n    for (uint i = 0; i < permutation.size(); i++) {\n        P[i][permutation[i]] = NTL::GF2(1);\n    }\n}\n\nNTL::mat_GF2 utils::mat_gf2_from_vec_gf2e(const NTL::vec_GF2E &v) {\n    NTL::mat_GF2 M;\n    M.SetDims(v.length(), v[0].degree());\n\n    for (int j = 0; j < v.length(); j++) {\n        for (int z = 0; z < v[0].degree(); z++) {\n            if (NTL::IsZero(v[j]._GF2E__rep[z])) {\n                M[j][z] = NTL::GF2(0);\n            } else {\n                M[j][z] = NTL::GF2(1);\n            }\n        }\n    }\n    return M;\n}\n\nvoid utils::generate_relation_matrix(\n        NTL::mat_GF2 &_R,\n        NTL::Vec<NTL::mat_GF2> &R,\n        const NTL::Vec<NTL::vec_GF2> &m_tilde,\n        const NTL::Vec<NTL::vec_GF2> &m,\n        int size) {\n\n    _R.SetDims(size, 4 * size);\n\n    NTL::vec_GF2 tmp;\n    tmp.SetLength(_R.NumCols());\n\n    for (int i = 0; i < _R.NumRows(); i++) {\n        for (int j = 0; j < _R.NumCols(); j++) {\n            _R[i][j] = NTL::GF2(1);\n        }\n    }\n\n    for (int i = 0; i < m[0].length(); i++) {\n        for (int j = 0; j < m.length() - 1; j++) {\n            for (int q = 0; q < m_tilde[j].length(); q++) {\n                if (NTL::IsZero(m[j][i]) && (NTL::IsZero(m_tilde[j][q]))) {\n                    tmp[q] = NTL::GF2(1);\n                }\n                if (NTL::IsZero(m[j][i]) && (!NTL::IsZero(m_tilde[j][q]))) {\n                    tmp[q] = NTL::GF2(0);\n                }\n                if (!NTL::IsZero(m[j][i]) && (NTL::IsZero(m_tilde[j][q]))) {\n                    tmp[q] = NTL::GF2(0);\n                }\n                if (!NTL::IsZero(m[j][i]) && (!NTL::IsZero(m_tilde[j][q]))) {\n                    tmp[q] = NTL::GF2(1);\n                }\n            }\n            for (int c = 0; c < tmp.length(); c++) {\n                _R[i][c] *= tmp[c];\n            }\n        }\n    }\n\n    NTL::mat_GF2 R_tmp;\n    R_tmp.SetDims(_R.NumRows(), _R.NumCols());\n\n    std::vector<uint> v;\n    v.resize(size);\n\n    std::vector<std::vector<uint>> indexes;\n    indexes.resize(size);\n\n    for (int i = 0; i < _R.NumRows(); i++) {\n        for (int j = 0; j < _R.NumCols(); j++) {\n            if (NTL::IsOne(_R[i][j])) {\n                indexes[i].push_back(j);\n            }\n        }\n    }\n\n    auto rnd_element = indexes[0][NTL::RandomBnd(indexes[0].size() - 1)];\n    v[0] = rnd_element;\n    R_tmp[0][rnd_element] = NTL::GF2(1);\n\n    for (int i = 1; i < _R.NumRows(); i++) {\n        do {\n            rnd_element = indexes[i][NTL::RandomBnd(indexes[i].size() - 1)];\n        } while (std::find(v.begin(), v.end(), rnd_element) != v.end());\n        v[i] = rnd_element;\n        R_tmp[i][rnd_element] = NTL::GF2(1);\n    }\n\n    _R = R_tmp;\n\n    // Generate R\n    R.SetLength(J);\n\n    for (int i = 0; i < J; i++) {\n        R[i].SetDims(size, size);\n        for (int j = 0; j < size; j++) {\n            for (int z = 0; z < size; z++) {\n                R[i][j][z] = _R[j][z + (i * size)];\n            }\n        }\n    }\n}\n\nint utils::gauss_row_reduced_echelon_form(NTL::mat_GF2 &M) {\n    long row;\n    long max_i = (int) floor((M.NumRows() + (M.NumCols() - 1)) / M.NumCols());\n    for (long i = 0; i < max_i; i++) {\n        for (long j = 0; j < M.NumCols(); j++) {\n\n            row = i * M.NumCols() + j;\n\n            if (row >= M.NumRows()) {\n                return 1;\n            }\n            for (long k = row + 1; k < M.NumRows(); k++) {\n                if (!NTL::IsZero(M[row][j] + M[k][j])) {\n                    M[row] += M[k];\n                }\n            }\n\n            for (long k = 0; k < M.NumRows(); k++) {\n                if (k != row) {\n                    if (!NTL::IsZero(M[k][j])) {\n                        M[k] += M[row];\n                    }\n                }\n            }\n        }\n    }\n    return 0;\n}\n\nint utils::gauss_row_reduced_echelon_form_gf2e(\n        NTL::mat_GF2E &M) {\n    int i = 0;\n    int j = 0;\n    int found = 0;\n\n    for (;;) {\n        if (!NTL::IsZero(M[i][j])) {\n            auto element = M[i][j];\n            for (int c = 0; c < M.NumCols(); ++c) {\n                M[i][c] = M[i][c] / element;\n            }\n        }\n\n        if (!NTL::IsZero(M[i][j])) {\n            for (int k = 0; k < M.NumRows(); k++) {\n                if (k != i) {\n                    auto t = M[k][j] / M[i][j];\n                    for (int h = 0; h < M.NumCols(); h++) {\n                        M[k][h] = M[k][h] - M[i][h] * t;\n                    }\n                }\n            }\n            i++;\n            j++;\n        } else {\n            found = 0;\n            for (int k = i; k < M.NumRows(); k++) {\n                if (!NTL::IsZero(M[k][j])) {\n                    for (int h = 0; h < M.NumCols(); h++) {\n                        M[i][h] = M[i][h] + M[k][h];\n                    }\n                    found = 1;\n                    break;\n                }\n            }\n            if (found == 0) {\n                j++;\n            }\n        }\n        if (i > (M.NumRows() - 1) || j > (M.NumCols() - 1)) {\n            break;\n        }\n    }\n\n    return 0;\n}\n\nint utils::convert_matrix_to_rref_and_check_solutions(NTL::mat_GF2 &M) {\n\n    utils::gauss_row_reduced_echelon_form(M);\n\n    for (int i = 0; i < M.NumRows(); i++) {\n        if (NTL::weight(NTL::IsZero(M[i]))) {\n            break;\n        }\n        if (NTL::IsOne(M[i][M.NumCols() - 1]) && (NTL::weight(M[i]) == 1)) {\n            return 1;\n        }\n    }\n    return 0;\n}\n\nint utils::convert_matrix_to_rref_and_check_solutions(NTL::mat_GF2E &M) {\n\n    utils::gauss_row_reduced_echelon_form_gf2e(M);\n\n    for (int i = 0; i < K; i++) {\n        for (int j = 0; j < K; j++) {\n            if (i == j) {\n                if (M[i][j]._GF2E__rep != NTL::GF2(1)) {\n                    return 1;\n                }\n            } else {\n                if (M[i][j]._GF2E__rep != NTL::GF2(0)) {\n                    return 1;\n                }\n            }\n        }\n    }\n\n    return 0;\n}\n\nvoid utils::generate_random_matrix_gf2e(\n        NTL::mat_GF2E &g,\n        int num_of_rows,\n        int num_of_cols) {\n\n    g.kill();\n    g = NTL::random_mat_GF2E(num_of_rows, num_of_cols);\n}\n\nvoid utils::generate_random_square_invertible_matrix(\n        NTL::mat_GF2 &M,\n        int size) {\n\n    do {\n        M = NTL::random_mat_GF2(size, size);\n    } while (NTL::determinant(M) == 0);\n}\n\nvoid utils::generate_random_binary_matrix(\n        NTL::mat_GF2 &A,\n        int num_of_rows,\n        int num_of_cols) {\n\n    A.kill();\n    A = NTL::random_mat_GF2(num_of_rows, num_of_cols);\n}\n\nvoid utils::generate_random_binary_vector_gf2e(\n        NTL::vec_GF2E &v,\n        int length) {\n\n    v.SetLength(length);\n    v = NTL::random_vec_GF2E(length);\n}\n\nvoid utils::generate_vector_of_specific_rank(\n        NTL::vec_GF2E &e,\n        int length,\n        int rank) {\n\n    e.SetLength(length);\n    auto degree = e[0].degree();\n\n    NTL::mat_GF2 _e;\n    _e.SetDims(degree, length);\n\n    NTL::vec_GF2E F;\n    F.append(NTL::GF2E());\n\n    int dim = 0;\n\n    while (dim < rank) {\n        auto n = NTL::random_GF2E();\n        if (!is_element_in_vector(n, F)) {\n            NTL::GF2E tmp;\n            auto size_of_F = F.length();\n            for (int i = 0; i < size_of_F; i++) {\n                tmp = n + F[i];\n                F.append(tmp);\n            }\n            dim++;\n        }\n    }\n\n    NTL::mat_GF2 tmp_e;\n    uint _rank = 0;\n    do {\n        for (int i = 0; i < length; i++) {\n            auto rnd_element = F[NTL::RandomBnd(F.length() - 1)];\n            NTL::vec_GF2 v;\n            gf2_from_gf2e_element(v, rnd_element);\n\n            for (int c = 0; c < v.length(); c++) {\n                _e[c][i] = v[c];\n            }\n        }\n\n        for (int i = 0; i < length; i++) {\n            for (int j = 0; j < degree; j++) {\n                NTL::SetCoeff(e[i].LoopHole(), j, _e[j][i]);\n            }\n        }\n\n        tmp_e = utils::mat_gf2_from_vec_gf2e(e);\n        _rank = NTL::gauss(tmp_e);\n    } while (_rank != rank);\n\n}\n\nvoid utils::generate_random_binary_vector(\n        NTL::vec_GF2 &v,\n        int length) {\n\n    v.SetLength(length);\n    v = NTL::random_vec_GF2(length);\n}\n\nvoid utils::generate_vector_of_weight_w(\n        NTL::vec_GF2 &e,\n        int length,\n        int weight) {\n\n    e.SetLength(length);\n\n    std::vector<uint> pos;\n    for (long i = 0; i < e.length(); i++) {\n        pos.push_back(i);\n    }\n\n    auto shuffled_vector = shuffle(\n            pos,\n            pos.size());\n\n    for (long i = 0; i < weight; i++) {\n        e[shuffled_vector[i]] = NTL::GF2(1);\n    }\n}\n\nint utils::solve_equation(\n        NTL::vec_GF2 &res,\n        const NTL::mat_GF2 &M,\n        const NTL::vec_GF2 &v) {\n\n    auto A_T = NTL::transpose(M);\n\n    A_T._mat__rep.append(v);\n    A_T = NTL::transpose(A_T);\n\n    if (utils::convert_matrix_to_rref_and_check_solutions(A_T) != 0) {\n        return 1;\n    }\n\n    A_T = NTL::transpose(A_T);\n    res = A_T[A_T.NumRows() - 1];\n\n    return 0;\n}\n\nint utils::solve_equation(\n        NTL::vec_GF2E &res,\n        const NTL::mat_GF2E &M,\n        const NTL::vec_GF2E &v) {\n\n    auto A_T = M;\n\n    A_T._mat__rep.append(v);\n    A_T = NTL::transpose(A_T);\n\n    if (utils::convert_matrix_to_rref_and_check_solutions(A_T) != 0) {\n        return 1;\n    }\n\n    A_T = NTL::transpose(A_T);\n    res = A_T[A_T.NumRows() - 1];\n\n    return 0;\n}\n\nint utils::rank_of_vector(\n        NTL::vec_GF2E &v) {\n\n    NTL::mat_GF2 M;\n    M.SetDims(v.length(), v[0].degree());\n\n    for (int z = 0; z < EN; z++) {\n        for (int j = 0; j < EM; j++) {\n            if (NTL::IsZero(v[z]._GF2E__rep[j])) {\n                M[z][j] = NTL::GF2(0);\n            } else {\n                M[z][j] = NTL::GF2(1);\n            }\n        }\n    }\n\n    auto _M = NTL::transpose(M);\n    return NTL::gauss(_M);\n}\n\nstd::vector<uint> utils::shuffle(\n        const std::vector<uint> &input,\n        int array_size) {\n\n    std::vector<uint> index_array(input.size());\n    std::vector<uint> output(input.size());\n\n    int index;\n    for (int i = 0; i < array_size; i++) {\n        do {\n            index = rand() % array_size;\n        } while (index_array[index] != 0);\n        index_array[index] = 1;\n        output[i] = input[index];\n    }\n\n    return output;\n}", "meta": {"hexsha": "e041219c9031a2963e0b2579e4df11a80609267d", "size": 18281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/utils.cpp", "max_stars_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_stars_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils/utils.cpp", "max_issues_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_issues_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/utils.cpp", "max_forks_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_forks_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-16T07:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-16T07:21:24.000Z", "avg_line_length": 25.0424657534, "max_line_length": 100, "alphanum_fraction": 0.5023795197, "num_tokens": 5858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.43688457088259525}}
{"text": "#pragma once\n\n#include <iostream>\n#include <unistd.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/Cholesky>\n#include <Eigen/StdVector>\n\n#include <opencv2/opencv.hpp>\n\n/**\n * @file   types.h\n * @Author Giorgio Grisetti\n * @date   December 2014\n * @brief  This file contains some useful defines about \n * Eigen types, common Mat opencv specializations, and transforms mappings\n */\n\nnamespace srrg_core {\n\n  //!a vector of Vector2f with alignment\n  typedef std::vector<Eigen::Vector2i, Eigen::aligned_allocator<Eigen::Vector2i> > Vector2iVector;\n\n  //!a vector of Vector3f with alignment\n  typedef std::vector<Eigen::Vector3f, Eigen::aligned_allocator<Eigen::Vector3f> > Vector3fVector;\n\n  //!a vector of Vector2f with alignment\n  typedef std::vector<Eigen::Vector2f, Eigen::aligned_allocator<Eigen::Vector2f> > Vector2fVector;\n\n  //!a vector of Matrix3f with alignment\n  typedef std::vector<Eigen::Matrix3f, Eigen::aligned_allocator<Eigen::Matrix3f> > Matrix3fVector;\n\n  //!a vector of Matrix2f with alignment\n  typedef std::vector<Eigen::Matrix2f, Eigen::aligned_allocator<Eigen::Matrix2f> > Matrix2fVector;\n\n  //!a 4x3 float matrix\n  typedef Eigen::Matrix<float, 4, 3> Matrix4_3f;\n\n  //!a 4x6 float matrix\n  typedef Eigen::Matrix<float, 4, 6> Matrix4_6f;\n\n  //!a 2x6 float matrix\n  typedef Eigen::Matrix<float, 2, 6> Matrix2_6f;\n\n  //!a 3x6 float matrix\n  typedef Eigen::Matrix<float, 3, 6> Matrix3_6f;\n\n\n  //!a 5x5 float matrix\n  typedef Eigen::Matrix<float, 5, 5> Matrix5f;\n\n  //!a 6x6 float matrix\n  typedef Eigen::Matrix<float, 6, 6> Matrix6f;\n\n  //!a 6   float vector\n  typedef Eigen::Matrix<float, 6, 1> Vector6f;\n  \n  //!a 9x6 float matrix \n  typedef Eigen::Matrix<float, 9, 6> Matrix9_6f;\n\n  //!a 9x9 float matrix \n  typedef Eigen::Matrix<float, 9, 9> Matrix9f;\n\n  //!a 9 float vector\n  typedef Eigen::Matrix<float, 9, 1> Vector9f;\n\n  //!a 6x3 float matrix\n  typedef Eigen::Matrix<float, 6, 3> Matrix6_3f;\n\n  //!a 5 float cv vector\n  typedef cv::Vec<float, 5> Vec5f;\n\n  //!a 7 float cv vector\n  typedef cv::Vec<float, 7> Vec7f;\n  \n  //!check if an Eigen type contains a nan element\n  //!@returns true if at least one element of\n  //!the argument is null\n  template <class T> \n  bool isNan(const T& m){\n    for (int i=0; i< m.rows(); i++) {\n      for (int j=0; j< m.cols(); j++) {\n\tfloat v = m(i,j);\n\tif ( std::isnan( v ) )\n\t  return true;\n      }\n    }\n    return false;\n  }\n\n  //!converts from 6 vector to isometry\n  //!@param t: a vector (tx, ty, tz, qx, qy, qz) reptesenting the transform.\n  //!(qx, qy, qz) are the imaginary part of a normalized queternion, with qw>0.\n  //!@returns the isometry corresponding to the transform described by t\n  inline Eigen::Isometry3f v2t(const Vector6f& t){\n    Eigen::Isometry3f T;\n    T.setIdentity();\n    T.translation()=t.head<3>();\n    float w=t.block<3,1>(3,0).squaredNorm();\n    if (w<1) {\n      w=sqrt(1-w);\n      T.linear()=Eigen::Quaternionf(w, t(3), t(4), t(5)).toRotationMatrix();\n    } else {\n      Eigen::Vector3f q=t.block<3,1>(3,0);\n      q.normalize();\n      T.linear()=Eigen::Quaternionf(0, q(0), q(1), q(2)).toRotationMatrix();\n    }\n    return T;\n  }\n  inline Eigen::Isometry3d v2t(const Eigen::Matrix<double, 6, 1>& t){\n    Eigen::Isometry3d T;\n    T.setIdentity();\n    T.translation()=t.head<3>();\n    float w=t.block<3,1>(3,0).squaredNorm();\n    if (w<1) {\n      w=sqrt(1-w);\n      T.linear()=Eigen::Quaterniond(w, t(3), t(4), t(5)).toRotationMatrix();\n    } else {\n      Eigen::Vector3d q=t.block<3,1>(3,0);\n      q.normalize();\n      T.linear()=Eigen::Quaterniond(0, q(0), q(1), q(2)).toRotationMatrix();\n    }\n    return T;\n  }\n\n  //!converts from isometry to 6 vector                                                                   \n  //!@param t: an isometry\n  //!@returns a vector (tx, ty, tz, qx, qy, qz) reptesenting the transform.\n  //!(qx, qy, qz) are the imaginary part of a normalized queternion, with qw>0.\n  inline Vector6f t2v(const Eigen::Isometry3f& t){\n    Vector6f v;\n    v.head<3>()=t.translation();\n    Eigen::Quaternionf q(t.linear());\n    v(3) = q.x();\n    v(4) = q.y();\n    v(5) = q.z();\n    if (q.w()<0)\n      v.block<3,1>(3,0) *= -1.0f;\n    return v;\n  }\n\n  //!converts from isometry2f to isometry3f                                                                   \n  //!@param t: an isometry2f\n  //!@returns an isometry3f\n  inline Eigen::Isometry3f toIsometry3f(const Eigen::Isometry2f& isometry2f){\n    Eigen::Isometry3f isometry3f;\n    isometry3f.linear().block<2,2>(0,0) = isometry2f.linear();\n    isometry3f.translation().head<2>() = isometry2f.translation();\n    return isometry3f;\n  }\n\n  //!computes the cross product matrix of the vector argument\n  //!@param p: the vector\n  //!@returns a 3x3 matrix \n  inline Eigen::Matrix3f skew(const Eigen::Vector3f& p){\n    Eigen::Matrix3f s;\n    s << \n      0,  -p.z(), p.y(),\n      p.z(), 0,  -p.x(), \n      -p.y(), p.x(), 0;\n    return s;\n  }\n  inline Eigen::Matrix3d skew(const Eigen::Vector3d& p){\n    Eigen::Matrix3d s;\n    s <<\n      0,  -p.z(), p.y(),\n      p.z(), 0,  -p.x(),\n      -p.y(), p.x(), 0;\n    return s;\n  }\n\n  inline Eigen::Isometry2f v2t(const Eigen::Vector3f& t){\n    Eigen::Isometry2f T;\n    T.setIdentity();\n    T.translation()=t.head<2>();\n    float c = cos(t(2));\n    float s = sin(t(2));\n    T.linear() << c, -s, s, c;\n    return T;\n  }\n\n  inline Eigen::Vector3f t2v(const Eigen::Isometry2f& t){\n    Eigen::Vector3f v;\n    v.head<2>()=t.translation();\n    v(2) = atan2(t.linear()(1,0), t.linear()(0,0));\n    return v;\n  }\n\n\n  inline Eigen::Matrix3f Rx(float rot_x){\n    float c=cos(rot_x);\n    float s=sin(rot_x);\n    Eigen::Matrix3f R;\n    R << 1,  0, 0,\n      0,  c,  -s,\n      0,  s,  c;\n    return R;\n  }\n  inline Eigen::Matrix3d Rx(const double& rot_x){\n    const double c=cos(rot_x);\n    const double s=sin(rot_x);\n    Eigen::Matrix3d R;\n    R << 1,  0, 0,\n      0,  c,  -s,\n      0,  s,  c;\n    return R;\n  }\n  \n  inline Eigen::Matrix3f Ry(float rot_y){\n    float c=cos(rot_y);\n    float s=sin(rot_y);\n    Eigen::Matrix3f R;\n    R << c,  0,  s,\n      0 , 1,  0,\n      -s,  0, c;\n    return R;\n  }\n  inline Eigen::Matrix3d Ry(const double& rot_y){\n    const double c=cos(rot_y);\n    const double s=sin(rot_y);\n    Eigen::Matrix3d R;\n    R << c,  0,  s,\n      0 , 1,  0,\n      -s,  0, c;\n    return R;\n  }\n\n  inline Eigen::Matrix3f Rz(float rot_z){\n    float c=cos(rot_z);\n    float s=sin(rot_z);\n    Eigen::Matrix3f R;\n    R << c,  -s,  0,\n      s,  c,  0,\n      0,  0,  1;\n    return R;\n  }\n  inline Eigen::Matrix3d Rz(const double& rot_z){\n    const double c=cos(rot_z);\n    const double s=sin(rot_z);\n    Eigen::Matrix3d R;\n    R << c,  -s,  0,\n      s,  c,  0,\n      0,  0,  1;\n    return R;\n  }\n\n  \n  inline Eigen::Isometry3f v2tEuler(const Vector6f& v){\n    Eigen::Isometry3f T;\n    T.linear()=Rx(v[3])*Ry(v[4])*Rz(v[5]);\n    T.translation()=v.head<3>();\n    return T;\n  }\n  inline Eigen::Isometry3d v2tEuler(const Eigen::Matrix<double, 6, 1>& v){\n    Eigen::Isometry3d T;\n    T.linear()=Rx(v[3])*Ry(v[4])*Rz(v[5]);\n    T.translation()=v.head<3>();\n    return T;\n  }\n\n\n  inline Eigen::Matrix2f skew(const Eigen::Vector2f& p){\n    Eigen::Matrix2f s;\n    s << \n      0,  -p.y(),\n      p.x(), 0;\n    return s;\n  }\n\n  /** \\typedef UnsignedCharImage\n   * \\brief An unsigned char cv::Mat.\n   */\n  typedef cv::Mat_<unsigned char> UnsignedCharImage;\n  \n  /** \\typedef CharImage\n   * \\brief A char cv::Mat.\n   */\n  typedef cv::Mat_<char> CharImage;\n\n  /** \\typedef UnsignedShortImage\n   * \\brief An unsigned short cv::Mat.\n   */\n  typedef cv::Mat_<unsigned short> UnsignedShortImage;\n  \n  /** \\typedef UnsignedIntImage\n   * \\brief An unsigned int cv::Mat.\n   */\n  typedef cv::Mat_<unsigned int> UnsignedIntImage;\n  \n  /** \\typedef IntImage\n   * \\brief An int cv::Mat.\n   */\n  typedef cv::Mat_<int> IntImage;\n\n  /** \\typedef Int4Image\n   * \\brief A 4D int cv::Mat.\n   */\n  typedef cv::Mat_<cv::Vec4i> Int4Image;\n\n  /** \\typedef IntervalImage\n   * \\brief A 4D int cv::Mat used to store intervals.\n   */\n  typedef Int4Image IntervalImage;\n\n  /** \\typedef FloatImage\n   * \\brief A float cv::Mat.\n   */\n  typedef cv::Mat_<float> FloatImage;\n\n  /** \\typedef Float3Image\n   * \\brief A 3D float cv::Mat.\n   */\n  typedef cv::Mat_<cv::Vec3f> Float3Image;\n\n  /** \\typedef Float5Image\n   * \\brief A 5D float cv::Mat.\n   */\n  typedef cv::Mat_<Vec5f> Float5Image;\n\n  /** \\typedef Float5Image\n   * \\brief A 7D float cv::Mat.\n   */\n  typedef cv::Mat_<Vec7f> Float7Image;\n  \n  /** \\typedef DoubleImage\n   * \\brief A double cv::Mat.\n   */\n  typedef cv::Mat_<double> DoubleImage;\n  \n  /** \\typedef RawDepthImage\n   * \\brief An unsigned char cv::Mat used to for depth images with depth values expressed in millimeters.\n   */\n  typedef UnsignedShortImage RawDepthImage;\n  \n  /** \\typedef IndexImage\n   * \\brief An int cv::Mat used to save the indeces of the points of a depth image inside a vector of points.\n   */\n  typedef IntImage IndexImage;\n  \n  /** \\typedef DepthImage\n   * \\brief A float cv::Mat used to for depth images with depth values expressed in meters.\n   */\n  typedef cv::Mat_<cv::Vec3b> RGBImage;\n\n  /** used to represent rgb values\n   */\n  typedef std::vector<cv::Vec3b> RGBVector;\n\n  \n  typedef std::vector<int> IntVector;\n  \n  typedef std::vector<float> FloatVector;\n\n  typedef std::vector<std::pair<int, int> > IntPairVector;\n\n  //ds overloaded opencv/eigen converters: double\n  inline cv::Mat_<double> toCv(const Eigen::Matrix<double, 3, 3>& matrix_eigen_) {\n    cv::Mat_<double> matrix_opencv(3, 3);\n    for(uint32_t u = 0; u < 3; ++u) {\n      for(uint32_t v = 0; v < 3; ++v) {\n        matrix_opencv.at<double>(u, v) = matrix_eigen_(u, v);\n      }\n    }\n    return matrix_opencv;\n  }\n  inline cv::Mat_<double> toCv(const Eigen::Matrix<double, 3, 4>& matrix_eigen_) {\n    cv::Mat_<double> matrix_opencv(3, 4);\n    for(uint32_t u = 0; u < 3; ++u) {\n      for(uint32_t v = 0; v < 4; ++v) {\n        matrix_opencv.at<double>(u, v) = matrix_eigen_(u, v);\n      }\n    }\n    return matrix_opencv;\n  }\n  inline cv::Mat_<double> toCv(const Eigen::Matrix<double, 5, 1>& vector_eigen_) {\n    cv::Mat_<double> vector_opencv(5,1);\n    for(uint32_t u = 0; u < 5; ++u) {\n      vector_opencv.at<double>(u) = vector_eigen_(u);\n    }\n    return vector_opencv;\n  }\n  inline Eigen::Matrix<double, 3, 1> fromCv(const cv::Vec<double, 3>& vector_opencv_) {\n    Eigen::Matrix<double, 3, 1> vector_eigen;\n    for(uint32_t u = 0; u < 3; ++u) {\n      vector_eigen(u) = vector_opencv_(u);\n    }\n    return vector_eigen;\n  }\n\n  //ds overloaded opencv/eigen converters: float\n  inline cv::Mat_<float> toCv(const Eigen::Matrix<float, 3, 3>& matrix_eigen_) {\n    cv::Mat_<float> matrix_opencv(3, 3);\n    for(uint32_t u = 0; u < 3; ++u) {\n      for(uint32_t v = 0; v < 3; ++v) {\n        matrix_opencv.at<float>(u, v) = matrix_eigen_(u, v);\n      }\n    }\n    return matrix_opencv;\n  }\n  inline cv::Mat_<float> toCv(const Eigen::Matrix<float, 3, 4>& matrix_eigen_) {\n    cv::Mat_<float> matrix_opencv(3, 4);\n    for(uint32_t u = 0; u < 3; ++u) {\n      for(uint32_t v = 0; v < 4; ++v) {\n        matrix_opencv.at<float>(u, v) = matrix_eigen_(u, v);\n      }\n    }\n    return matrix_opencv;\n  }\n  inline cv::Mat_<float> toCv(const Eigen::Matrix<float, 5, 1>& vector_eigen_) {\n    cv::Mat_<float> vector_opencv(5,1);\n    for(uint32_t u = 0; u < 5; ++u) {\n      vector_opencv.at<float>(u) = vector_eigen_(u);\n    }\n    return vector_opencv;\n  }\n  inline Eigen::Matrix<float, 3, 1> fromCv(const cv::Vec<float, 3>& vector_opencv_) {\n    Eigen::Matrix<float, 3, 1> vector_eigen;\n    for(uint32_t u = 0; u < 3; ++u) {\n      vector_eigen(u) = vector_opencv_(u);\n    }\n    return vector_eigen;\n  }\n\n  //ml std vector to Eigen converters\n  inline Eigen::Matrix<float, 3, 1> fromFloatVector3f(const FloatVector& float_vector_){\n    Eigen::Matrix<float, 3, 1> vector_eigen;\n    assert(float_vector_.size() == 3);\n    for (size_t i=0; i<3; i++)\n      vector_eigen[i] = float_vector_[i];\n    \n    return vector_eigen;\n  }\n  inline FloatVector toFloatVector3f(const Eigen::Matrix<float, 3, 1>& vector_eigen_){\n    FloatVector float_vector;\n    float_vector.resize(3);\n    for (size_t i=0; i<3; i++)\n      float_vector[i] = vector_eigen_[i];\n    return float_vector;\n  }\n}\n", "meta": {"hexsha": "a76d3bf9a16b28890a883c65a52d7b5510726509", "size": 12215, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/srrg_types/types.hpp", "max_stars_repo_name": "pet1330/spqrel_navigation", "max_stars_repo_head_hexsha": "af0c0797404770c8c97825e081d41069d9c40cc9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-06-27T07:45:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T03:34:18.000Z", "max_issues_repo_path": "src/srrg_types/types.hpp", "max_issues_repo_name": "pet1330/spqrel_navigation", "max_issues_repo_head_hexsha": "af0c0797404770c8c97825e081d41069d9c40cc9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2017-07-22T22:09:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T10:20:45.000Z", "max_forks_repo_path": "src/srrg_types/types.hpp", "max_forks_repo_name": "pet1330/spqrel_navigation", "max_forks_repo_head_hexsha": "af0c0797404770c8c97825e081d41069d9c40cc9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2017-07-09T12:12:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T22:37:42.000Z", "avg_line_length": 27.5733634312, "max_line_length": 110, "alphanum_fraction": 0.606467458, "num_tokens": 4098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355188, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4368777319886903}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2013, 2015 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file gsr.hpp\n    \\brief GSR 1 factor model\n*/\n\n#ifndef quantlib_gsr_hpp\n#define quantlib_gsr_hpp\n\n#include <ql/time/schedule.hpp>\n#include <ql/math/integrals/simpsonintegral.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n\n#include <ql/models/shortrate/onefactormodels/gaussian1dmodel.hpp>\n#include <ql/processes/gsrprocess.hpp>\n\n#include <boost/math/special_functions.hpp>\n\nnamespace QuantLib {\n\n//! One factor gsr model, formulation is in forward measure\n\nclass Gsr : public Gaussian1dModel, public CalibratedModel {\n\n  public:\n    // constant mean reversion\n    Gsr(const Handle<YieldTermStructure> &termStructure,\n        const std::vector<Date> &volstepdates,\n        const std::vector<Real> &volatilities, const Real reversion,\n        const Real T = 60.0);\n    // piecewise mean reversion (with same step dates as volatilities)\n    Gsr(const Handle<YieldTermStructure> &termStructure,\n        const std::vector<Date> &volstepdates,\n        const std::vector<Real> &volatilities,\n        const std::vector<Real> &reversions, const Real T = 60.0);\n    // constant mean reversion with floating model data\n    Gsr(const Handle<YieldTermStructure> &termStructure,\n        const std::vector<Date> &volstepdates,\n        const std::vector<Handle<Quote> > &volatilities,\n        const Handle<Quote> reversion, const Real T = 60.0);\n    // piecewise mean reversion with floating model data\n    Gsr(const Handle<YieldTermStructure> &termStructure,\n        const std::vector<Date> &volstepdates,\n        const std::vector<Handle<Quote> > &volatilities,\n        const std::vector<Handle<Quote> > &reversions, const Real T = 60.0);\n\n    const Real numeraireTime() const;\n    const void numeraireTime(const Real T);\n\n    const Array &reversion() const { return reversion_.params(); }\n    const Array &volatility() const { return sigma_.params(); }\n\n    // calibration constraints\n\n    Disposable<std::vector<bool> > FixedReversions() {\n        std::vector<bool> res(reversions_.size(), true);\n        std::vector<bool> vol(volatilities_.size(), false);\n        res.insert(res.end(), vol.begin(), vol.end());\n        return res;\n    }\n\n    Disposable<std::vector<bool> > FixedVolatilities() {\n        std::vector<bool> res(reversions_.size(), false);\n        std::vector<bool> vol(volatilities_.size(), true);\n        res.insert(res.end(), vol.begin(), vol.end());\n        return res;\n    }\n\n    Disposable<std::vector<bool> > MoveVolatility(Size i) {\n        QL_REQUIRE(i < volatilities_.size(),\n                   \"volatility with index \" << i << \" does not exist (0...\"\n                                            << volatilities_.size() - 1 << \")\");\n        std::vector<bool> res(reversions_.size() + volatilities_.size(),\n                              true);\n        res[reversions_.size() + i] = false;\n        return res;\n    }\n\n    Disposable<std::vector<bool> > MoveReversion(Size i) {\n        QL_REQUIRE(i < reversions_.size(),\n                   \"reversion with index \" << i << \" does not exist (0...\"\n                                           << reversions_.size() - 1 << \")\");\n        std::vector<bool> res(reversions_.size() + volatilities_.size(),\n                              true);\n        res[i] = false;\n        return res;\n    }\n\n    // With fixed reversion calibrate the volatilities one by one\n    // to the given helpers. It is assumed that that volatility step\n    // dates are suitable for this, i.e. they should be identical to\n    // the fixing dates of the helpers (except for the last one where\n    // we do not need a step). Also note that the endcritera reflect\n    // only the status of the last calibration when using this method.\n    void calibrateVolatilitiesIterative(\n        const std::vector<boost::shared_ptr<CalibrationHelper> > &helpers,\n        OptimizationMethod &method, const EndCriteria &endCriteria,\n        const Constraint &constraint = Constraint(),\n        const std::vector<Real> &weights = std::vector<Real>()) {\n\n        for (Size i = 0; i < helpers.size(); i++) {\n            std::vector<boost::shared_ptr<CalibrationHelper> > h(1, helpers[i]);\n            calibrate(h, method, endCriteria, constraint, weights,\n                      MoveVolatility(i));\n        }\n    }\n\n    // With fixed volatility calibrate the reversions one by one\n    // to the given helpers. In this case the step dates must be chosen\n    // according to the maturities of the calibration instruments.\n    void calibrateReversionsIterative(\n        const std::vector<boost::shared_ptr<CalibrationHelper> > &helpers,\n        OptimizationMethod &method, const EndCriteria &endCriteria,\n        const Constraint &constraint = Constraint(),\n        const std::vector<Real> &weights = std::vector<Real>()) {\n\n        for (Size i = 0; i < helpers.size(); i++) {\n            std::vector<boost::shared_ptr<CalibrationHelper> > h(1, helpers[i]);\n            calibrate(h, method, endCriteria, constraint, weights,\n                      MoveReversion(i));\n        }\n    }\n\n  protected:\n    const Real numeraireImpl(const Time t, const Real y,\n                             const Handle<YieldTermStructure> &yts) const;\n\n    const Real zerobondImpl(const Time T, const Time t, const Real y,\n                            const Handle<YieldTermStructure> &yts) const;\n\n    void generateArguments() {\n        boost::static_pointer_cast<GsrProcess>(stateProcess_)->flushCache();\n        notifyObservers();\n    }\n\n    void update() { LazyObject::update(); }\n\n    void performCalculations() const {\n        Gaussian1dModel::performCalculations();\n        updateTimes();\n        updateState();\n    }\n\n  private:\n    void updateTimes() const;\n    void updateState() const;\n    void initialize(Real);\n\n    Parameter &reversion_, &sigma_;\n\n    std::vector<Handle<Quote> > volatilities_;\n    std::vector<Handle<Quote> > reversions_;\n    std::vector<Date> volstepdates_; // this is shared between vols and reversions\n                                     // in case of piecewise reversions\n    mutable std::vector<Time> volsteptimes_;\n    mutable Array volsteptimesArray_; // FIXME this is redundant (just a copy of\n                                      // volsteptimes_)\n};\n\ninline const Real Gsr::numeraireTime() const {\n    return boost::dynamic_pointer_cast<GsrProcess>(stateProcess_)\n        ->getForwardMeasureTime();\n}\n\ninline const void Gsr::numeraireTime(const Real T) {\n    boost::dynamic_pointer_cast<GsrProcess>(stateProcess_)\n        ->setForwardMeasureTime(T);\n}\n}\n\n#endif\n", "meta": {"hexsha": "4b281aa04fa8c922c12dc0ecaee152277b00972d", "size": 7361, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantLib/ql/models/shortrate/onefactormodels/gsr.hpp", "max_stars_repo_name": "txu2014/quantlib", "max_stars_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantLib/ql/models/shortrate/onefactormodels/gsr.hpp", "max_issues_repo_name": "txu2014/quantlib", "max_issues_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/ql/models/shortrate/onefactormodels/gsr.hpp", "max_forks_repo_name": "txu2014/quantlib", "max_forks_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7421052632, "max_line_length": 82, "alphanum_fraction": 0.6492324412, "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.43687772604750835}}
{"text": "/**\n* Copyright 2019, ftdlyc <yclu.cn@gmail.com>\n* Licensed under the MIT license.\n*/\n\n#include <algorithm>\n#include <functional>\n#include <vector>\n\n#include <ceres/ceres.h>\n#include <ceres/loss_function.h>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/opencv.hpp>\n\n#include \"libcalib/calibration.h\"\n#include \"libcalib/ceres_type.h\"\n\nnamespace calib {\n\nvoid init_camera_params(const std::vector<std::vector<cv::Point2d>>& world_points,\n                        const std::vector<std::vector<cv::Point2d>>& image_points,\n                        std::vector<double>& K,\n                        std::vector<double>& D,\n                        std::vector<std::vector<double>>& Rwc,\n                        std::vector<std::vector<double>>& Twc) {\n  int num_images = world_points.size();\n  int num_points = 0;\n  for(int i = 0; i < num_images; ++i) {\n    num_points += world_points[i].size();\n  }\n\n  std::vector<cv::Mat> homo_vec;\n  Eigen::MatrixXd mat_v = Eigen::MatrixXd::Zero(2 * num_images, 6);\n  for(int i = 0; i < num_images; ++i) {\n    cv::Mat homo = cv::findHomography(world_points[i], image_points[i], cv::RANSAC);\n    auto homo_at = [&homo](int x, int y) { return homo.at<double>(y - 1, x - 1); };\n    mat_v.block(2 * i, 0, 1, 6) << homo_at(1, 1) * homo_at(2, 1),\n        homo_at(1, 1) * homo_at(2, 2) + homo_at(1, 2) * homo_at(2, 1),\n        homo_at(1, 2) * homo_at(2, 2),\n        homo_at(1, 3) * homo_at(2, 1) + homo_at(1, 1) * homo_at(2, 3),\n        homo_at(1, 3) * homo_at(2, 2) + homo_at(1, 2) * homo_at(2, 3),\n        homo_at(1, 3) * homo_at(2, 3);\n    mat_v.block(2 * i + 1, 0, 1, 6) << homo_at(1, 1) * homo_at(1, 1) - homo_at(2, 1) * homo_at(2, 1),\n        homo_at(1, 1) * homo_at(1, 2) + homo_at(1, 2) * homo_at(1, 1) -\n            homo_at(2, 1) * homo_at(2, 2) - homo_at(2, 2) * homo_at(2, 1),\n        homo_at(1, 2) * homo_at(1, 2) - homo_at(2, 2) * homo_at(2, 2),\n        homo_at(1, 3) * homo_at(1, 1) + homo_at(1, 1) * homo_at(1, 3) -\n            homo_at(2, 3) * homo_at(2, 1) - homo_at(2, 1) * homo_at(2, 3),\n        homo_at(1, 3) * homo_at(1, 2) + homo_at(1, 2) * homo_at(1, 3) -\n            homo_at(2, 3) * homo_at(2, 2) - homo_at(2, 2) * homo_at(2, 3),\n        homo_at(1, 3) * homo_at(1, 3) - homo_at(2, 3) * homo_at(2, 3);\n    homo_vec.emplace_back(homo);\n  }\n\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(mat_v.transpose() * mat_v, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Eigen::Matrix<double, 6, 6> mat_b = svd.matrixV().cast<double>();\n  double b11                        = mat_b(0, 5);\n  double b12                        = mat_b(1, 5);\n  double b22                        = mat_b(2, 5);\n  double b13                        = mat_b(3, 5);\n  double b23                        = mat_b(4, 5);\n  double b33                        = mat_b(5, 5);\n  double cy                         = (b12 * b13 - b11 * b23) / (b11 * b22 - b12 * b12);\n  double lambda                     = b33 - (b13 * b13 + cy * (b12 * b13 - b11 * b23)) / b11;\n  double fx                         = sqrt(lambda / b11);\n  double fy                         = sqrt(lambda * b11 / (b11 * b22 - b12 * b12));\n  double radio                      = -b12 * fx * fx * fy / lambda;\n  double cx                         = radio * cy / fx - b13 * fx * fx / lambda;\n  K[0]                              = fx;\n  K[1]                              = fy;\n  K[2]                              = 0.;\n  K[3]                              = cx;\n  K[4]                              = cy;\n  Eigen::Matrix3d K_eigen;\n  K_eigen << K[0], K[2], K[3],\n      0, K[1], K[4],\n      0, 0, 1;\n\n  for(int i = 0; i < num_images; ++i) {\n    Eigen::Matrix3d rotation_eigen;\n    Eigen::Matrix<double, 3, 1> translation_eigen;\n    Eigen::Matrix3d homo_eigen;\n    cv::cv2eigen(homo_vec[i], homo_eigen);\n    double s              = (K_eigen.inverse() * homo_eigen.col(0)).norm();\n    rotation_eigen.col(0) = K_eigen.inverse() * homo_eigen.col(0) / s;\n    rotation_eigen.col(1) = K_eigen.inverse() * homo_eigen.col(1) / s;\n    rotation_eigen.col(2) = rotation_eigen.col(0).cross(rotation_eigen.col(1));\n    translation_eigen     = K_eigen.inverse() * homo_eigen.col(2) / s;\n\n    cv::Mat rotation;\n    cv::Mat angle_axis;\n    cv::eigen2cv(rotation_eigen, rotation);\n    cv::Rodrigues(rotation, angle_axis);\n\n    Rwc[i][0] = angle_axis.at<double>(0);\n    Rwc[i][1] = angle_axis.at<double>(1);\n    Rwc[i][2] = angle_axis.at<double>(2);\n    Twc[i][0] = translation_eigen(0, 0);\n    Twc[i][1] = translation_eigen(1, 0);\n    Twc[i][2] = translation_eigen(2, 0);\n  }\n\n  D[0] = 0.;\n  D[1] = 0.;\n  D[2] = 0.;\n  D[3] = 0.;\n  D[4] = 0.;\n}\n\ndouble optimize_params(const std::vector<std::vector<cv::Point2d>>& world_points,\n                       const std::vector<std::vector<cv::Point2d>>& image_points,\n                       std::vector<double>& K,\n                       std::vector<double>& D,\n                       std::vector<std::vector<double>>& Rwc,\n                       std::vector<std::vector<double>>& Twc) {\n  std::vector<double> intrinsics = {K[0], K[1], K[3], K[4], D[0], D[1], D[2], D[3], D[4]};\n  std::vector<std::vector<double>> se3(world_points.size(), std::vector<double>(6));\n  for(int i = 0; i < world_points.size(); ++i) {\n    se3[i][0] = Twc[i][0];\n    se3[i][1] = Twc[i][1];\n    se3[i][2] = Twc[i][2];\n    se3[i][3] = Rwc[i][0];\n    se3[i][4] = Rwc[i][1];\n    se3[i][5] = Rwc[i][2];\n  }\n\n  ceres::Problem problem;\n  ceres::HuberLoss* loss_fuction = new ceres::HuberLoss(4.5);\n  for(int i = 0; i < world_points.size(); ++i) {\n    for(int j = 0; j < world_points[i].size(); ++j) {\n      problem.AddResidualBlock(new ProjectCostFunction(world_points[i][j], image_points[i][j]), nullptr, intrinsics.data(), se3[i].data());\n    }\n    problem.SetParameterization(se3[i].data(), new SE3Parameterization());\n  }\n\n  ceres::Solver::Options options;\n  options.linear_solver_type           = ceres::DENSE_QR;\n  options.minimizer_progress_to_stdout = false;\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n\n  K = {intrinsics[0], intrinsics[1], 0., intrinsics[2], intrinsics[3]};\n  D = {intrinsics[4], intrinsics[5], intrinsics[6], intrinsics[7], intrinsics[8]};\n  for(int i = 0; i < world_points.size(); ++i) {\n    Twc[i][0] = se3[i][0];\n    Twc[i][1] = se3[i][1];\n    Twc[i][2] = se3[i][2];\n    Rwc[i][0] = se3[i][3];\n    Rwc[i][1] = se3[i][4];\n    Rwc[i][2] = se3[i][5];\n  }\n\n  double err = sqrt(2 * summary.final_cost / summary.num_residual_blocks);\n  return err;\n}\n\ndouble calibrate_camera(const std::vector<std::vector<cv::Point2d>>& world_points,\n                        const std::vector<std::vector<cv::Point2d>>& image_points,\n                        std::vector<double>& K,\n                        std::vector<double>& D,\n                        std::vector<std::vector<double>>& Rwc,\n                        std::vector<std::vector<double>>& Twc) {\n  init_camera_params(world_points, image_points, K, D, Rwc, Twc);\n  double err = optimize_params(world_points, image_points, K, D, Rwc, Twc);\n  return err;\n}\n\nvoid init_stereo_params(std::vector<std::vector<double>>& Rwc1,\n                        std::vector<std::vector<double>>& Rwc2,\n                        std::vector<std::vector<double>>& Twc1,\n                        std::vector<std::vector<double>>& Twc2,\n                        std::vector<double>& R,\n                        std::vector<double>& T) {\n  auto num_images       = static_cast<int>(Rwc1.size());\n  Eigen::MatrixXd mat_a = Eigen::MatrixXd::Zero(9 * num_images, 9);\n  Eigen::MatrixXd mat_b = Eigen::MatrixXd::Zero(9 * num_images, 1);\n  for(int i = 0; i < num_images; ++i) {\n    Eigen::Matrix3d r1_t, r2;\n    ceres::AngleAxisToRotationMatrix(Rwc1[i].data(), r1_t.data());\n    ceres::AngleAxisToRotationMatrix(Rwc2[i].data(), r2.data());\n    r1_t.transposeInPlace();\n    mat_a.block(9 * i, 0, 3, 3)     = r1_t;\n    mat_a.block(9 * i + 3, 3, 3, 3) = r1_t;\n    mat_a.block(9 * i + 6, 6, 3, 3) = r1_t;\n    mat_b.block(9 * i, 0, 9, 1) << r2(0, 0), r2(0, 1), r2(0, 2),\n        r2(1, 0), r2(1, 1), r2(1, 2),\n        r2(2, 0), r2(2, 1), r2(2, 2);\n  }\n  Eigen::MatrixXd r = (mat_a.transpose() * mat_a).inverse() * mat_a.transpose() * mat_b;\n  r.resize(3, 3);\n  r.transposeInPlace();\n\n  T[0] = T[1] = T[2] = 0.;\n  for(int i = 0; i < num_images; ++i) {\n    Eigen::Matrix<double, 3, 1> t, t1(Twc1[i].data()), t2(Twc2[i].data());\n    t = t2 - r * t1;\n    T[0] += t(0, 0);\n    T[1] += t(1, 0);\n    T[2] += t(2, 0);\n  }\n  T[0] /= num_images;\n  T[1] /= num_images;\n  T[2] /= num_images;\n  ceres::RotationMatrixToAngleAxis(r.data(), R.data());\n}\n\ndouble optimize_stereo_params(const std::vector<std::vector<cv::Point2d>>& world_points,\n                              const std::vector<std::vector<cv::Point2d>>& image_points_1,\n                              const std::vector<std::vector<cv::Point2d>>& image_points_2,\n                              std::vector<double>& K1,\n                              std::vector<double>& K2,\n                              std::vector<double>& D1,\n                              std::vector<double>& D2,\n                              std::vector<std::vector<double>>& Rwc1,\n                              std::vector<std::vector<double>>& Rwc2,\n                              std::vector<std::vector<double>>& Twc1,\n                              std::vector<std::vector<double>>& Twc2,\n                              std::vector<double>& R,\n                              std::vector<double>& T) {\n  std::vector<double> intrinsics_1 = {K1[0], K1[1], K1[3], K1[4], D1[0], D1[1], D1[2], D1[3], D1[4]};\n  std::vector<double> intrinsics_2 = {K2[0], K2[1], K2[3], K2[4], D2[0], D2[1], D2[2], D2[3], D2[4]};\n  std::vector<std::vector<double>> se3_1(world_points.size(), std::vector<double>(6));\n  std::vector<double> se3 = {T[0], T[1], T[2], R[0], R[1], R[2]};\n  for(int i = 0; i < world_points.size(); ++i) {\n    se3_1[i][0] = Twc1[i][0];\n    se3_1[i][1] = Twc1[i][1];\n    se3_1[i][2] = Twc1[i][2];\n    se3_1[i][3] = Rwc1[i][0];\n    se3_1[i][4] = Rwc1[i][1];\n    se3_1[i][5] = Rwc1[i][2];\n  }\n\n  ceres::Problem problem;\n  ceres::HuberLoss* loss_fuction = new ceres::HuberLoss(4.5);\n  for(int i = 0; i < world_points.size(); ++i) {\n    for(int j = 0; j < world_points[i].size(); ++j) {\n      problem.AddResidualBlock(new StereoCostFunction(world_points[i][j], image_points_1[i][j], image_points_2[i][j]), nullptr,\n                               intrinsics_1.data(), intrinsics_2.data(), se3_1[i].data(), se3.data());\n    }\n    problem.SetParameterization(se3_1[i].data(), new SE3Parameterization());\n  }\n  problem.SetParameterization(se3.data(), new SE3Parameterization());\n\n  ceres::Solver::Options options;\n  options.linear_solver_type           = ceres::DENSE_QR;\n  options.trust_region_strategy_type   = ceres::DOGLEG;\n  options.minimizer_progress_to_stdout = false;\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n\n  K1 = {intrinsics_1[0], intrinsics_1[1], 0., intrinsics_1[2], intrinsics_1[3]};\n  D1 = {intrinsics_1[4], intrinsics_1[5], intrinsics_1[6], intrinsics_1[7], intrinsics_1[8]};\n  K2 = {intrinsics_2[0], intrinsics_2[1], 0., intrinsics_2[2], intrinsics_2[3]};\n  D2 = {intrinsics_2[4], intrinsics_2[5], intrinsics_2[6], intrinsics_2[7], intrinsics_2[8]};\n  R  = {se3[3], se3[4], se3[5]};\n  T  = {se3[0], se3[1], se3[2]};\n\n  double q[4], q1[4], q2[4];\n  ceres::AngleAxisToQuaternion(R.data(), q);\n  for(int i = 0; i < world_points.size(); ++i) {\n    Twc1[i][0] = se3_1[i][0];\n    Twc1[i][1] = se3_1[i][1];\n    Twc1[i][2] = se3_1[i][2];\n    Rwc1[i][0] = se3_1[i][3];\n    Rwc1[i][1] = se3_1[i][4];\n    Rwc1[i][2] = se3_1[i][5];\n\n    ceres::AngleAxisToQuaternion(Rwc1[i].data(), q1);\n    ceres::QuaternionProduct(q, q1, q2);\n    ceres::QuaternionToAngleAxis(q2, Rwc2[i].data());\n    ceres::AngleAxisRotatePoint(R.data(), Twc1[i].data(), Twc2[i].data());\n    Twc2[i][0] += T[0];\n    Twc2[i][1] += T[1];\n    Twc2[i][2] += T[2];\n  }\n\n  double err = sqrt(2 * summary.final_cost / summary.num_residual_blocks / 2);\n  return err;\n}\n\ndouble calibrate_stereo_camera(const std::vector<std::vector<cv::Point2d>>& world_points,\n                               const std::vector<std::vector<cv::Point2d>>& image_points_1,\n                               const std::vector<std::vector<cv::Point2d>>& image_points_2,\n                               std::vector<double>& K1,\n                               std::vector<double>& K2,\n                               std::vector<double>& D1,\n                               std::vector<double>& D2,\n                               std::vector<std::vector<double>>& Rwc1,\n                               std::vector<std::vector<double>>& Rwc2,\n                               std::vector<std::vector<double>>& Twc1,\n                               std::vector<std::vector<double>>& Twc2,\n                               std::vector<double>& R,\n                               std::vector<double>& T) {\n  init_stereo_params(Rwc1, Rwc2, Twc1, Twc2, R, T);\n  double err = optimize_stereo_params(world_points, image_points_1, image_points_2, K1, K2, D1, D2, Rwc1, Rwc2, Twc1, Twc2, R, T);\n  return err;\n}\n\n} // namespace calib\n", "meta": {"hexsha": "f0c09966d0a984d1e8477dce4467f659f58013ba", "size": 13176, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/calibration.cc", "max_stars_repo_name": "ftdlyc/libcalib", "max_stars_repo_head_hexsha": "116a5561d446016e9b463d704c191dc3e5c703c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-06-04T07:10:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:36:26.000Z", "max_issues_repo_path": "src/calibration.cc", "max_issues_repo_name": "sxtiann/libcalib", "max_issues_repo_head_hexsha": "1c2ea09d031fbd97c2c4fa0d2b68cebcbb693853", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-07-19T02:09:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T07:06:07.000Z", "max_forks_repo_path": "src/calibration.cc", "max_forks_repo_name": "sxtiann/libcalib", "max_forks_repo_head_hexsha": "1c2ea09d031fbd97c2c4fa0d2b68cebcbb693853", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T01:19:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-29T04:19:17.000Z", "avg_line_length": 43.2, "max_line_length": 139, "alphanum_fraction": 0.5358986035, "num_tokens": 4375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426303, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4368777201063263}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      lambertTargeterIzzo.h/.cpp source files, tudat revision 455/466.\n *      PyKEP kepler toolbox, Dario Izzo, ESA Advanced Concepts Team.\n *\n *    Notes\n *      This is a new implementation of the lambertTargeterIzzo class, for better adaptability and\n *      extension towards subclasses and future improvements/additions. Therefore, it replaces the\n *      lambertTargeterIzzo class while still providing the same functionality.\n *\n */\n\n#include <cmath>\n\n#include <boost/math/special_functions.hpp> // For asinh and acosh\n#include <boost/exception/all.hpp> // For exceptions in sanity checks\n#include <Eigen/Dense> // for cross product issues (can someone explain why, exactly?)\n\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/Astrodynamics/MissionSegments/zeroRevolutionLambertTargeterIzzo.h\"\n#include \"Tudat/Mathematics/BasicMathematics/convergenceException.h\"\n\nnamespace tudat\n{\nnamespace mission_segments\n{\n\n//! Get radial velocity at departure.\ndouble ZeroRevolutionLambertTargeterIzzo::getRadialVelocityAtDeparture( )\n// Based on lambertTargeterIzzo class.\n{\n    // If execute has not been called yet, execute.\n    if ( !solved ) execute( );\n\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtDeparture = cartesianPositionAtDeparture.normalized( );\n\n    // Compute radial velocity at departure.\n    return cartesianVelocityAtDeparture.dot( radialUnitVectorAtDeparture );\n}\n\n//! Get transverse velocity at departure.\ndouble ZeroRevolutionLambertTargeterIzzo::getTransverseVelocityAtDeparture( )\n// Based on lambertTargeterIzzo class.\n{\n    // If execute has not been called yet, execute.\n    if ( !solved ) execute( );\n\n    // Compute angular momemtum vector.\n    const Eigen::Vector3d angularMomentumVector =\n            cartesianPositionAtDeparture.cross( cartesianVelocityAtDeparture );\n\n    // Compute normalized angular momentum vector.\n    const Eigen::Vector3d angularMomentumUnitVector = angularMomentumVector.normalized( );\n\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtDeparture = cartesianPositionAtDeparture.normalized( );\n\n    // Compute tangential unit vector.\n    Eigen::Vector3d tangentialUnitVectorAtDeparture =\n            angularMomentumUnitVector.cross( radialUnitVectorAtDeparture );\n\n    // Compute tangential velocity at departure.\n    return cartesianVelocityAtDeparture.dot( tangentialUnitVectorAtDeparture );\n}\n\n//! Get radial velocity at arrival.\ndouble ZeroRevolutionLambertTargeterIzzo::getRadialVelocityAtArrival( )\n// Based on lambertTargeterIzzo class.\n{\n    // If execute has not been called yet, execute.\n    if ( !solved ) execute( );\n\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtArrival = cartesianPositionAtArrival.normalized( );\n\n    // Compute radial velocity at arrival.\n    return cartesianVelocityAtArrival.dot( radialUnitVectorAtArrival );\n}\n\n//! Get transverse velocity at arrival.\ndouble ZeroRevolutionLambertTargeterIzzo::getTransverseVelocityAtArrival( )\n// Based on lambertTargeterIzzo class.\n{\n    // If execute has not been called yet, execute.\n    if ( !solved ) execute( );\n\n    // Compute angular momemtum vector.\n    const Eigen::Vector3d angularMomentumVector =\n            cartesianPositionAtArrival.cross( cartesianVelocityAtArrival );\n\n    // Compute normalized angular momentum vector.\n    const Eigen::Vector3d angularMomentumUnitVector = angularMomentumVector.normalized( );\n\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtArrival = cartesianPositionAtArrival.normalized( );\n\n    // Compute tangential unit vector.\n    Eigen::Vector3d tangentialUnitVectorAtArrival\n            = angularMomentumUnitVector.cross( radialUnitVectorAtArrival );\n\n    // Compute tangential velocity at departure.\n    return cartesianVelocityAtArrival.dot( tangentialUnitVectorAtArrival );\n}\n\n//! Get semi-major axis.\ndouble ZeroRevolutionLambertTargeterIzzo::getSemiMajorAxis( )\n// Based on lambertTargeterIzzo class.\n{\n    // If execute has not been called yet, execute.\n    if ( !solved ) execute( );\n\n    // Compute specific orbital energy: eps = v^2/ - mu/r.\n    const double specificOrbitalEnergy = cartesianVelocityAtDeparture.squaredNorm( ) / 2.0\n            - gravitationalParameter / cartesianPositionAtDeparture.norm( );\n\n    // Compute semi-major axis: a = -mu / 2*eps.\n    return -gravitationalParameter / ( 2.0 * specificOrbitalEnergy );\n}\n\n// What about get retrograde flag, tolerance and max number of iterations? Might be useful to check.\n\n//! Execute the solving procedure.\nvoid ZeroRevolutionLambertTargeterIzzo::execute( )\n{\n    // Sanity checks\n    sanityCheckTimeOfFlight( );\n    sanityCheckGravitationalParameter( );\n\n    // Transform dimensional parameters to dimensionless parameters if not done already (e.g. in\n    // multirevolution case\n    if( !transformed ) transformDimensions( );\n\n    // Solve root (single rev)\n    double xResult = ZeroRevolutionLambertTargeterIzzo::computeRootTimeOfFlight( );\n\n    // Reconstruct Vs\n    computeVelocities( xResult );\n\n    solved = true;\n}\n\n//! Sanity check time of flight.\nvoid ZeroRevolutionLambertTargeterIzzo::sanityCheckTimeOfFlight( )\n{\n    // If time of flight is negative, throw an exception\n    if ( timeOfFlight < 0 )\n    {\n        // Throw exception.\n        throw std::runtime_error(\n                    \"Time-of-flight specified in Lambert problem must be strictly positive. Specified time-of-flight in days.\" +\n                                         std::to_string( timeOfFlight ) );\n    }\n    // Else, do nothing and continue.\n}\n\n//! Sanity check gravitational parameter.\nvoid ZeroRevolutionLambertTargeterIzzo::sanityCheckGravitationalParameter( )\n{\n    // If gravitational parameter is negative, throw an exception\n    if ( gravitationalParameter < 0 )\n    {\n        // Throw exception.\n        throw std::runtime_error(\n                    \"Gravitational parameter specified in Lambert problem must be strictly positive. Specified gravitational parameter: \" +\n                    std::to_string( gravitationalParameter ) );\n    }\n    // Else, do nothing and continue.\n}\n\n//! Transform input to sub results in adimensional units.\nvoid ZeroRevolutionLambertTargeterIzzo::transformDimensions( )\n// Created using theory from PyKEP toolbox and LambertTargeterIzzo class\n{\n    // Compute normalizing values.\n    const double distanceNormalizingValue = cartesianPositionAtDeparture.norm( );\n    velocityNormalizingValue = std::sqrt( gravitationalParameter /\n                                          distanceNormalizingValue );\n    const double timeNormalizingValue = distanceNormalizingValue / velocityNormalizingValue;\n\n    // Compute transfer geometry parameters in adimensional units.\n    // Time of Flight.\n    normalizedTimeOfFlight = timeOfFlight / timeNormalizingValue;\n\n    // Cosine of transfer angle.\n    const double cosineOfTransferAngle =\n            cartesianPositionAtDeparture.dot( cartesianPositionAtArrival )\n            / (distanceNormalizingValue * cartesianPositionAtArrival.norm( ) );\n\n    // Normalized Cartesian position at arrival.\n    normalizedRadiusAtArrival = cartesianPositionAtArrival.norm( ) / distanceNormalizingValue;\n\n    // Chord.\n    normalizedChord = std::sqrt( 1.0 + normalizedRadiusAtArrival\n                                 * ( normalizedRadiusAtArrival\n                                     - 2.0 * cosineOfTransferAngle ) );\n\n    // Semi-perimeter.\n    normalizedSemiPerimeter = ( 1.0 + normalizedRadiusAtArrival + normalizedChord ) / 2.0;\n\n    // Assuming a prograde motion, determine whether the transfer corresponds to the long- or the\n    // short-way solution: longway if x1*y2 - x2*y1 < 0.\n    isLongway = false;\n    if ( cartesianPositionAtDeparture.x( ) * cartesianPositionAtArrival.y( )\n         - cartesianPositionAtDeparture.y( ) * cartesianPositionAtArrival.x( ) < 0.0 )\n    {\n        isLongway = true;\n    }\n\n    // If retrograde is true, switch longway flag.\n    if ( isRetrograde )\n    {\n        isLongway = !isLongway;\n    }\n\n    // Semi-major axis of the minimum energy ellipse.\n    normalizedMinimumEnergySemiMajorAxis = normalizedSemiPerimeter / 2.0;\n\n    // Transfer angle.\n    transferAngle = std::acos( cosineOfTransferAngle );\n    if ( isLongway )\n    {\n        transferAngle = 2.0 * mathematical_constants::PI - transferAngle;\n    }\n\n    // Lambda parameter.\n    lambdaParameter = std::sqrt( normalizedRadiusAtArrival )\n            * std::cos( transferAngle / 2.0 ) / normalizedSemiPerimeter;\n\n    // Set transformed flag to true, as the dimension transformation has been performed\n    transformed = true;\n}\n\n//! Compute time-of-flight using Lagrange's equation.\ndouble ZeroRevolutionLambertTargeterIzzo::computeTimeOfFlight( const double xParameter )\n// Created using theory from PyKEP toolbox and LambertTargeterIzzo class\n{\n    // Determine semi-major axis.\n    const double semiMajorAxis = normalizedMinimumEnergySemiMajorAxis\n            / ( 1.0 - xParameter * xParameter );\n\n    // If x < 1, the solution is an ellipse.\n    if ( xParameter < 1.0 )\n    {\n        // Alpha parameter in Lagrange's equation (no explanation available).\n        const double alphaParameter = 2.0 * std::acos( xParameter );\n\n        // Beta parameter in Lagrange's equation (no explanation available).\n        double betaParameter;\n        // If long transfer arc\n        if ( isLongway )\n        {\n            betaParameter = -2.0 * std::asin(\n                        std::sqrt( ( normalizedSemiPerimeter - normalizedChord )\n                                   / ( 2.0 * semiMajorAxis ) ) );\n        }\n        // Otherwise short transfer arc\n        else\n        {\n            betaParameter = 2.0 * std::asin(\n                        std::sqrt( ( normalizedSemiPerimeter - normalizedChord )\n                                   / ( 2.0 * semiMajorAxis ) ) );\n        }\n\n        // Time-of-flight according to Lagrange including multiple revolutions.\n        const double timeOfFlight = semiMajorAxis * std::sqrt( semiMajorAxis ) *\n                ( ( alphaParameter - std::sin( alphaParameter ) )\n                  - ( betaParameter - std::sin( betaParameter ) ) );\n\n        return timeOfFlight;\n    }\n    // Otherwise it is a hyperbola.\n    else\n    {\n        // Alpha parameter in Lagrange's equation (no explanation available).\n        const double alphaParameter = 2.0 * boost::math::acosh( xParameter );\n\n        // Beta parameter in Lagrange's equation (no explanation available).\n        double betaParameter;\n        // If long transfer arc\n        if ( isLongway )\n        {\n            betaParameter = -2.0 * boost::math::asinh ( std::sqrt( ( normalizedSemiPerimeter\n                                                                     - normalizedChord )\n                                                                   / ( -2.0 * semiMajorAxis ) ) );\n        }\n        // Otherwise short transfer arc\n        else\n        {\n            betaParameter = 2.0 * boost::math::asinh ( std::sqrt( ( normalizedSemiPerimeter\n                                                                    - normalizedChord )\n                                                                  / ( -2.0 * semiMajorAxis ) ) );\n        }\n\n        // Time-of-flight according to Lagrange.\n        const double timeOfFlightLagrange = -semiMajorAxis * std::sqrt( -semiMajorAxis ) *\n                ( ( std::sinh( alphaParameter ) - alphaParameter )\n                  - ( std::sinh( betaParameter ) - betaParameter ) );\n\n        return timeOfFlightLagrange;\n    }\n}\n\n//! Solve the time of flight equation for x.\ndouble ZeroRevolutionLambertTargeterIzzo::computeRootTimeOfFlight( )\n// Created using theory from PyKEP toolbox and LambertTargeterIzzo class\n{\n    // Find root (secant method, currently hard coded)\n    // Optimize log(t_spec).\n    const double logarithmOfTheSpecifiedTimeOfFlight = std::log( normalizedTimeOfFlight );\n\n    // Define initial guesses for abcissae (x) and ordinates (y).\n    double x1 = std::log( 0.5 ), x2 = std::log( 1.5 );\n\n    double y1 = std::log( computeTimeOfFlight( -0.5 ) ) - logarithmOfTheSpecifiedTimeOfFlight;\n\n    double y2 = std::log( computeTimeOfFlight( 0.5 ) ) - logarithmOfTheSpecifiedTimeOfFlight;\n\n    // Declare and initialize root-finding parameters.\n    double rootFindingError = 1.0, xNew = 0.0, yNew = 0.0;\n    int iterator = 0;\n\n    // Root-finding loop.\n    while ( ( rootFindingError > convergenceTolerance ) && (y1 != y2)\n            && ( iterator < maximumNumberOfIterations ) )\n    {\n        // Update iterator.\n        iterator++;\n\n        // Compute new x-value.\n        xNew = ( x1 * y2 - y1 * x2 ) / ( y2 - y1 );\n\n        // Compute corresponding y-value.\n        yNew = std::log( computeTimeOfFlight( std::exp( xNew ) - 1.0 ) )\n                - logarithmOfTheSpecifiedTimeOfFlight;\n\n        // Update abcissae and ordinates.\n        x1 = x2;\n        y1 = y2;\n        x2 = xNew;\n        y2 = yNew;\n\n        // Compute root-finding error.\n        rootFindingError = std::fabs( x1 - xNew );\n    }\n\n    // Verify that root-finder has converged.\n    if ( iterator == maximumNumberOfIterations )\n    {\n        throw std::runtime_error(\n                    \"Multi-Revolution Lambert targeter failed to converge to a solution. Reached the maximum number of iterations: \" +\n                    std::to_string( maximumNumberOfIterations ) );\n    }\n\n    // Recovering x parameter and returning it.\n    double xParameter = std::exp( xNew ) - 1.0;\n    return xParameter;\n}\n\n//! Compute velocities at departure and arrival.\nvoid ZeroRevolutionLambertTargeterIzzo::computeVelocities( const double xParameter )\n// Created using theory from PyKEP toolbox and LambertTargeterIzzo class\n{\n    // Then it is possible to retrieve a sensible value from the x-parameter computed)\n    // Determine semi-major axis of the conic.\n    const double semiMajorAxis = normalizedMinimumEnergySemiMajorAxis\n            / ( 1.0 - xParameter * xParameter );\n\n    // Declare variables.\n    double etaParameter, etaParameterSquared, psiParameter;\n\n    // If x < 1, the solution is an ellipse.\n    if ( xParameter < 1.0 )\n    {\n        // Alpha parameter in Lagrange's equation (no explanation available).\n        const double alphaParameter = 2.0 * std::acos( xParameter );\n\n        // Beta parameter in Lagrange's equation (no explanation available).\n        double betaParameter = 2.0 * std::asin( std::sqrt( ( normalizedSemiPerimeter\n                                                             - normalizedChord )\n                                                           / ( 2.0 * semiMajorAxis ) ) );\n\n        if ( isLongway )\n        {\n            betaParameter = -betaParameter;\n        }\n\n        // Psi parameter in Izzo's approach (no explanation available).\n        psiParameter = ( alphaParameter - betaParameter ) / 2.0;\n\n        // Eta parameter in Izzo's approach (no explanation available).\n        etaParameterSquared = 2.0 * semiMajorAxis * std::sin( psiParameter )\n                * std::sin( psiParameter ) / normalizedSemiPerimeter;\n        etaParameter = std::sqrt( etaParameterSquared );\n    }\n\n    // Otherwise it is a hyperbola.\n    else\n    {\n        // Alpha parameter in Lagrange's equation (no explanation available).\n        const double alphaParameter = 2.0 * boost::math::acosh( xParameter );\n\n        // Beta parameter in Lagrange's equation (no explanation available).\n        double betaParameter = 2.0 * boost::math::asinh (\n                    std::sqrt( ( normalizedSemiPerimeter - normalizedChord )\n                               / ( -2.0 * semiMajorAxis ) ) );\n\n        if ( isLongway )\n        {\n            betaParameter = -betaParameter;\n        }\n\n        // Psi parameter in Izzo's approach (no explanation available).\n        psiParameter = (alphaParameter - betaParameter ) / 2.0;\n\n        // Eta parameter in Izzo's approach (no explanation available).\n        etaParameterSquared = -2.0 * semiMajorAxis * std::sinh( psiParameter )\n                * std::sinh( psiParameter ) / normalizedSemiPerimeter;\n        etaParameter = std::sqrt( etaParameterSquared );\n    }\n\n    // Determine semi-latus rectum, p.\n    const double semiLatusRectum = ( normalizedRadiusAtArrival\n                                     / ( normalizedMinimumEnergySemiMajorAxis\n                                         * etaParameterSquared ) )\n            * std::sin( transferAngle / 2.0 )\n            * std::sin( transferAngle / 2.0 );\n\n    // Velocity components at departure.\n    const double radialVelocityAtDeparture =\n            ( 1.0 / ( etaParameter * std::sqrt( normalizedMinimumEnergySemiMajorAxis ) ) )\n            * ( 2.0 * lambdaParameter * normalizedMinimumEnergySemiMajorAxis\n                - ( lambdaParameter + xParameter * etaParameter ) );\n\n    const double transverseVelocityAtDeparture = std::sqrt( semiLatusRectum );\n\n    // Velocity components at arrival.\n    const double transverseVelocityAtArrival = transverseVelocityAtDeparture\n            / normalizedRadiusAtArrival;\n    const double radialVelocityAtArrival = ( transverseVelocityAtDeparture\n                                             - transverseVelocityAtArrival )\n            / std::tan( transferAngle / 2.0 )\n            - radialVelocityAtDeparture;\n\n    // Determining inertial vectors\n    // Determine radial unit vectors.\n    const Eigen::Vector3d radialUnitVectorAtDeparture = cartesianPositionAtDeparture.normalized( );\n    const Eigen::Vector3d radialUnitVectorAtArrival = cartesianPositionAtArrival.normalized( );\n\n    // Determine plane of motion.\n    Eigen::Vector3d angularMomentumVector;\n\n    if ( isLongway )\n    {\n        angularMomentumVector = radialUnitVectorAtArrival.cross( radialUnitVectorAtDeparture );\n    }\n    else\n    {\n        angularMomentumVector = radialUnitVectorAtDeparture.cross( radialUnitVectorAtArrival );\n    }\n\n    // Compute normalized angular momentum vector.\n    const Eigen::Vector3d angularMomentumUnitVector = angularMomentumVector.normalized( );\n\n    // Compute transverse unit vectors.\n    const Eigen::Vector3d transverseUnitVectorAtDeparture =\n            radialUnitVectorAtDeparture.cross( angularMomentumUnitVector );\n    const Eigen::Vector3d transverseUnitVectorAtArrival =\n            radialUnitVectorAtArrival.cross( angularMomentumUnitVector );\n\n    // Reconstruct non-dimensional velocity vectors.\n    cartesianVelocityAtDeparture << radialVelocityAtDeparture * radialUnitVectorAtDeparture\n                                    - transverseVelocityAtDeparture * transverseUnitVectorAtDeparture;\n\n    cartesianVelocityAtArrival << radialVelocityAtArrival * radialUnitVectorAtArrival\n                                  - transverseVelocityAtArrival * transverseUnitVectorAtArrival;\n\n    // Return to dimensions of initial problem definition.\n    cartesianVelocityAtDeparture *= velocityNormalizingValue;\n    cartesianVelocityAtArrival *= velocityNormalizingValue;\n}\n\n} // namespace mission_segments\n} // namespace tudat\n", "meta": {"hexsha": "285f4ef90b494225bc0447ef024760b719e7b1de", "size": 19491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/MissionSegments/zeroRevolutionLambertTargeterIzzo.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/MissionSegments/zeroRevolutionLambertTargeterIzzo.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/MissionSegments/zeroRevolutionLambertTargeterIzzo.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.455465587, "max_line_length": 139, "alphanum_fraction": 0.6632804884, "num_tokens": 4457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257655, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.4368345374291999}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_GIS_GEOGRAPHIC_STRATEGIES_VINCENTY_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_GIS_GEOGRAPHIC_STRATEGIES_VINCENTY_HPP\n\n#include <boost/math/constants/constants.hpp>\n\n\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/extensions/gis/geographic/detail/ellipsoid.hpp>\n\n\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n/*!\n\\brief Distance calculation formulae on latlong coordinates, after Vincenty, 1975\n\\ingroup distance\n\\tparam Point1 \\tparam_first_point\n\\tparam Point2 \\tparam_second_point\n\\tparam CalculationType \\tparam_calculation\n\\author See http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf\n\\author Adapted from various implementations to get it close to the original document\n    - http://www.movable-type.co.uk/scripts/LatLongVincenty.html\n    - http://exogen.case.edu/projects/geopy/source/geopy.distance.html\n    - http://futureboy.homeip.net/fsp/colorize.fsp?fileName=navigation.frink\n\n*/\ntemplate\n<\n    typename Point1,\n    typename Point2 = Point1,\n    typename CalculationType = void\n>\nclass vincenty\n{\npublic :\n    typedef typename promote_floating_point\n        <\n            typename select_most_precise\n                <\n                    typename select_calculation_type\n                        <\n                            Point1,\n                            Point2,\n                            CalculationType\n                        >::type,\n                    double // to avoid bad results in float\n                >::type\n        >::type calculation_type;\n\n    inline vincenty()\n    {}\n\n    explicit inline vincenty(geometry::detail::ellipsoid<calculation_type> const& e)\n        : m_ellipsoid(e)\n    {}\n\n    inline calculation_type apply(Point1 const& p1, Point2 const& p2) const\n    {\n        return calculate(get_as_radian<0>(p1), get_as_radian<1>(p1),\n                        get_as_radian<0>(p2), get_as_radian<1>(p2));\n    }\n\n    inline geometry::detail::ellipsoid<calculation_type> ellipsoid() const\n    {\n        return m_ellipsoid;\n    }\n\n\nprivate :\n    geometry::detail::ellipsoid<calculation_type> m_ellipsoid;\n\n    inline calculation_type calculate(calculation_type const& lon1,\n                calculation_type const& lat1,\n                calculation_type const& lon2,\n                calculation_type const& lat2) const\n    {\n        calculation_type const c2 = 2;\n        calculation_type const pi = geometry::math::pi<calculation_type>();\n        calculation_type const two_pi = c2 * pi;\n\n        // lambda: difference in longitude on an auxiliary sphere\n        calculation_type L = lon2 - lon1;\n        calculation_type lambda = L;\n\n        if (L < -pi) L += two_pi;\n        if (L > pi) L -= two_pi;\n\n        if (math::equals(lat1, lat2) && math::equals(lon1, lon2))\n        {\n            return calculation_type(0);\n        }\n\n        // U: reduced latitude, defined by tan U = (1-f) tan phi\n        calculation_type const c1 = 1;\n        calculation_type const one_min_f = c1 - m_ellipsoid.f();\n\n        calculation_type const U1 = atan(one_min_f * tan(lat1)); // above (1)\n        calculation_type const U2 = atan(one_min_f * tan(lat2)); // above (1)\n\n        calculation_type const cos_U1 = cos(U1);\n        calculation_type const cos_U2 = cos(U2);\n        calculation_type const sin_U1 = sin(U1);\n        calculation_type const sin_U2 = sin(U2);\n\n        // alpha: azimuth of the geodesic at the equator\n        calculation_type cos2_alpha;\n        calculation_type sin_alpha;\n\n        // sigma: angular distance p1,p2 on the sphere\n        // sigma1: angular distance on the sphere from the equator to p1\n        // sigma_m: angular distance on the sphere from the equator to the midpoint of the line\n        calculation_type sigma;\n        calculation_type sin_sigma;\n        calculation_type cos2_sigma_m;\n\n        calculation_type previous_lambda;\n\n        calculation_type const c3 = 3;\n        calculation_type const c4 = 4;\n        calculation_type const c6 = 6;\n        calculation_type const c16 = 16;\n\n        calculation_type const c_e_12 = 1e-12;\n\n        do\n        {\n            previous_lambda = lambda; // (13)\n            calculation_type sin_lambda = sin(lambda);\n            calculation_type cos_lambda = cos(lambda);\n            sin_sigma = sqrt(math::sqr(cos_U2 * sin_lambda) + math::sqr(cos_U1 * sin_U2 - sin_U1 * cos_U2 * cos_lambda)); // (14)\n            calculation_type cos_sigma = sin_U1 * sin_U2 + cos_U1 * cos_U2 * cos_lambda; // (15)\n            sin_alpha = cos_U1 * cos_U2 * sin_lambda / sin_sigma; // (17)\n            cos2_alpha = c1 - math::sqr(sin_alpha);\n            cos2_sigma_m = math::equals(cos2_alpha, 0) ? 0 : cos_sigma - c2 * sin_U1 * sin_U2 / cos2_alpha; // (18)\n\n            calculation_type C = m_ellipsoid.f()/c16 * cos2_alpha * (c4 + m_ellipsoid.f() * (c4 - c3 * cos2_alpha)); // (10)\n            sigma = atan2(sin_sigma, cos_sigma); // (16)\n            lambda = L + (c1 - C) * m_ellipsoid.f() * sin_alpha *\n                (sigma + C * sin_sigma * ( cos2_sigma_m + C * cos_sigma * (-c1 + c2 * math::sqr(cos2_sigma_m)))); // (11)\n\n        } while (geometry::math::abs(previous_lambda - lambda) > c_e_12\n                && geometry::math::abs(lambda) < pi);\n\n        calculation_type sqr_u = cos2_alpha * (math::sqr(m_ellipsoid.a()) - math::sqr(m_ellipsoid.b())) / math::sqr(m_ellipsoid.b()); // above (1)\n\n        // Oops getting hard here\n        // (again, problem is that ttmath cannot divide by doubles, which is OK)\n        calculation_type const c47 = 47;\n        calculation_type const c74 = 74;\n        calculation_type const c128 = 128;\n        calculation_type const c256 = 256;\n        calculation_type const c175 = 175;\n        calculation_type const c320 = 320;\n        calculation_type const c768 = 768;\n        calculation_type const c1024 = 1024;\n        calculation_type const c4096 = 4096;\n        calculation_type const c16384 = 16384;\n\n        calculation_type A = c1 + sqr_u/c16384 * (c4096 + sqr_u * (-c768 + sqr_u * (c320 - c175 * sqr_u))); // (3)\n        calculation_type B = sqr_u/c1024 * (c256 + sqr_u * ( -c128 + sqr_u * (c74 - c47 * sqr_u))); // (4)\n        calculation_type delta_sigma = B * sin_sigma * ( cos2_sigma_m + (B/c4) * (cos(sigma)* (-c1 + c2 * cos2_sigma_m)\n                - (B/c6) * cos2_sigma_m * (-c3 + c4 * math::sqr(sin_sigma)) * (-c3 + c4 * cos2_sigma_m))); // (6)\n\n        return m_ellipsoid.b() * A * (sigma - delta_sigma); // (19)\n    }\n};\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename Point1, typename Point2>\nstruct tag<strategy::distance::vincenty<Point1, Point2> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename Point1, typename Point2>\nstruct return_type<strategy::distance::vincenty<Point1, Point2> >\n{\n    typedef typename strategy::distance::vincenty<Point1, Point2>::calculation_type type;\n};\n\n\ntemplate <typename Point1, typename Point2, typename P1, typename P2>\nstruct similar_type<vincenty<Point1, Point2>, P1, P2>\n{\n    typedef vincenty<P1, P2> type;\n};\n\n\ntemplate <typename Point1, typename Point2, typename P1, typename P2>\nstruct get_similar<vincenty<Point1, Point2>, P1, P2>\n{\n    static inline vincenty<P1, P2> apply(vincenty<Point1, Point2> const& input)\n    {\n        return vincenty<P1, P2>(input.ellipsoid());\n    }\n};\n\ntemplate <typename Point1, typename Point2>\nstruct comparable_type<vincenty<Point1, Point2> >\n{\n    typedef vincenty<Point1, Point2> type;\n};\n\n\ntemplate <typename Point1, typename Point2>\nstruct get_comparable<vincenty<Point1, Point2> >\n{\n    static inline vincenty<Point1, Point2> apply(vincenty<Point1, Point2> const& input)\n    {\n        return input;\n    }\n};\n\ntemplate <typename Point1, typename Point2>\nstruct result_from_distance<vincenty<Point1, Point2> >\n{\n    template <typename T>\n    static inline typename return_type<vincenty<Point1, Point2> >::type apply(vincenty<Point1, Point2> const& , T const& value)\n    {\n        return value;\n    }\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n// We might add a vincenty-like strategy also for point-segment distance, but to calculate the projected point is not trivial\n\n\n\n}} // namespace strategy::distance\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_GIS_GEOGRAPHIC_STRATEGIES_VINCENTY_HPP\n", "meta": {"hexsha": "9b9b887ea82ecddcd734a78150b9a4158b8598c4", "size": 8927, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/gis/geographic/strategies/vincenty.hpp", "max_stars_repo_name": "juslee/boost-svn", "max_stars_repo_head_hexsha": "6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-07-03T22:12:18.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-03T22:12:18.000Z", "max_issues_repo_path": "boost/geometry/extensions/gis/geographic/strategies/vincenty.hpp", "max_issues_repo_name": "graehl/boost", "max_issues_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/geometry/extensions/gis/geographic/strategies/vincenty.hpp", "max_forks_repo_name": "graehl/boost", "max_forks_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9429657795, "max_line_length": 146, "alphanum_fraction": 0.6591240058, "num_tokens": 2297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.43675457744815815}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_SINHC_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_SCALAR_SINHC_HPP_INCLUDED\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/constant/inf.hpp>\n#endif\n#include <boost/simd/arch/common/detail/generic/sinhc_kernel.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/constant/maxlog.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/scalar/abs.hpp>\n#include <boost/simd/function/scalar/average.hpp>\n#include <boost/simd/function/scalar/exp.hpp>\n#include <boost/simd/function/scalar/if_else.hpp>\n#include <boost/simd/function/scalar/rec.hpp>\n#include <boost/simd/function/scalar/sqr.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( sinhc_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      //////////////////////////////////////////////////////////////////////////////\n      // if x = abs(a0) is less than 1 sinhc is computed using a polynomial(float)\n      // respectively rational(double) approx inspired from cephes sinh approx.\n      // else according x < Threshold e =  exp(x) or exp(x/2) is respectively\n      // computed\n      // * in the first case sinh is ((e-rec(e))/2)/x\n      // * in the second     sinh is (e/2/x)*e (avoiding undue overflow)\n      // Threshold is Maxlog - Log_2 defined in Maxshlog\n      //////////////////////////////////////////////////////////////////////////////\n      A0 x = bs::abs(a0);\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if (x == Inf<A0>()) return x;\n      #endif\n      if( x < One<A0>())\n      {\n        return detail::sinhc_kernel<A0>::compute(sqr(x));\n      }\n      else\n      {\n        auto test1 = (x >  Maxlog<A0>()-Log_2<A0>());\n        A0 fac = if_else(test1, Half<A0>(), One<A0>());\n        A0 tmp = exp(x*fac);\n        A0 tmp1 = (Half<A0>()*tmp)/x;\n        return if_else(test1, tmp1*tmp, average(tmp, -rec(tmp))/x);\n      }\n     }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "86dff9d3b8fa65962115a95d4836c49f3f87e615", "size": 2744, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/sinhc.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/scalar/function/sinhc.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/sinhc.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1052631579, "max_line_length": 100, "alphanum_fraction": 0.5586734694, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.43675456819039926}}
{"text": "//\n// Created by Hamza El-Kebir on 5/8/21.\n//\n\n#ifndef LODESTAR_ORDINARYDIFFERENTIALEQUATION_HPP\n#define LODESTAR_ORDINARYDIFFERENTIALEQUATION_HPP\n\n#ifdef LS_USE_GINAC\n\n#include <Eigen/Dense>\n#include \"ginac/ginac.h\"\n\n#include \"Lodestar/systems/StateSpace.hpp\"\n\n#include <string>\n#include <deque>\n\nnamespace ls {\n    namespace symbolic {\n        class OrdinaryDifferentialEquation {\n        public:\n            OrdinaryDifferentialEquation() :\n                    functions_(GiNaC::lst{GiNaC::ex(0)}),\n                    states_(GiNaC::lst{GiNaC::symbol(\"x\")}),\n                    inputs_(GiNaC::lst{GiNaC::symbol(\"u\")}),\n                    time_(GiNaC::symbol(\"t\"))\n            {\n                makeSymbolMap();\n            }\n\n            OrdinaryDifferentialEquation(const GiNaC::lst &functions,\n                                         const GiNaC::lst &states,\n                                         const GiNaC::lst &inputs) :\n                    functions_(functions),\n                    states_(states),\n                    inputs_(inputs),\n                    time_(GiNaC::symbol(\"t\"))\n            {\n                makeSymbolMap();\n            }\n\n            OrdinaryDifferentialEquation(const GiNaC::lst &functions,\n                                         const GiNaC::lst &states,\n                                         const GiNaC::lst &inputs,\n                                         const GiNaC::symbol &time) :\n                    functions_(functions),\n                    states_(states),\n                    inputs_(inputs),\n                    time_(time)\n            {\n                makeSymbolMap();\n            }\n\n            GiNaC::exmap generateExpressionMap() const;\n\n            GiNaC::exmap generateExpressionMap(\n                    const std::vector<GiNaC::relational> &relationals) const;\n\n            GiNaC::exmap\n            generateExpressionMap(const std::vector<double> &states,\n                                  const std::vector<double> &inputs) const;\n\n            GiNaC::exmap generateExpressionMap(double t,\n                                               const std::vector<double> &states,\n                                               const std::vector<double> &inputs) const;\n\n            GiNaC::symbol getSymbol(const std::string &symbolName) const;\n\n            GiNaC::symbol getStateSymbol(unsigned int i) const;\n\n            GiNaC::symbol getInputSymbol(unsigned int i) const;\n\n            GiNaC::symbol getTimeSymbol() const;\n\n            const GiNaC::lst &getFunctions() const;\n\n            void setFunctions(const GiNaC::lst &functions);\n\n            const GiNaC::lst &getStates() const;\n\n            void setStates(const GiNaC::lst &states);\n\n            const GiNaC::lst &getInputs() const;\n\n            void setInputs(const GiNaC::lst &inputs);\n\n            Eigen::MatrixXd evalf(const GiNaC::exmap &m) const;\n\n            Eigen::MatrixXd evalf(const std::vector<double> &states,\n                                  const std::vector<double> &inputs) const;\n\n            Eigen::MatrixXd\n            evalf(double t, const std::vector<double> &states,\n                  const std::vector<double> &inputs) const;\n\n            GiNaC::matrix generateJacobian(const GiNaC::lst &variables) const;\n\n            GiNaC::matrix generateJacobianStates() const;\n\n            std::string generateJacobianStatesCppFunc(const std::string &functionName, const bool dynamicType = false) const;\n\n            std::string generateJacobianStatesArrayInputCppFunc(const std::string &functionName, const bool dynamicType = false) const;\n\n            GiNaC::matrix generateJacobianInputs() const;\n\n            std::string generateJacobianInputsCppFunc(const std::string &functionName, const bool dynamicType = false) const;\n\n            std::string generateJacobianInputsArrayInputCppFunc(const std::string &functionName, const bool dynamicType = false) const;\n\n            Eigen::MatrixXd generateJacobianMatrix(const GiNaC::lst &variables,\n                                                   const GiNaC::exmap &exmap) const;\n\n            Eigen::MatrixXd\n            generateJacobianMatrix(const GiNaC::matrix &jacobian,\n                                   const GiNaC::exmap &exmap) const;\n\n            Eigen::MatrixXd\n            generateJacobianMatrixStates(const GiNaC::exmap &exmap) const;\n\n            Eigen::MatrixXd\n            generateJacobianMatrixInputs(const GiNaC::exmap &exmap) const;\n\n            std::string generateMatrixCppFunc(const GiNaC::matrix &ginacMatrix, const std::string &functionName, const bool dynamicType = false) const;\n\n            std::string generateMatrixArrayInputCppFunc(const GiNaC::matrix &ginacMatrix, const std::string &functionName, const bool dynamicType = false) const;\n\n            systems::StateSpace<> linearize(const GiNaC::exmap &exmap) const;\n\n            systems::StateSpace<> linearize(const std::vector<double> &states,\n                                          const std::vector<double> &inputs) const;\n\n            systems::StateSpace<> linearize(double t,\n                                          const std::vector<double> &states,\n                                          const std::vector<double> &inputs) const;\n\n            systems::StateSpace<> linearize(const GiNaC::matrix &jacobianStates,\n                                          const GiNaC::matrix &jacobianInputs,\n                                          const GiNaC::exmap &exmap) const;\n\n            systems::StateSpace<> linearize(const GiNaC::matrix &jacobianStates,\n                                          const GiNaC::matrix &jacobianInputs,\n                                          const std::vector<double> &states,\n                                          const std::vector<double> &inputs) const;\n\n            systems::StateSpace<> linearize(const GiNaC::matrix &jacobianStates,\n                                          const GiNaC::matrix &jacobianInputs,\n                                          double t,\n                                          const std::vector<double> &states,\n                                          const std::vector<double> &inputs) const;\n\n            static Eigen::MatrixXd matrixToMatrixXd(const GiNaC::matrix &mat);\n\n            static Eigen::MatrixXd matrixToMatrixXd(const GiNaC::ex &ex);\n\n        protected:\n            GiNaC::lst functions_;\n            GiNaC::symbol time_;\n            GiNaC::lst states_;\n            GiNaC::lst inputs_;\n\n            std::map<std::string, GiNaC::symbol> symbolMap_;\n\n            void makeSymbolMap();\n\n            static void replaceString(std::string &str, const std::string &source, const std::string &dest);\n            static void replaceStringAll(std::string &str, const std::string &source, const std::string &dest);\n            static std::string stripWhiteSpace(std::string &str);\n        };\n    }\n}\n\n#endif\n\n#endif //LODESTAR_ORDINARYDIFFERENTIALEQUATION_HPP\n", "meta": {"hexsha": "8b4520a185ba000261308d0981d36d96e4bc0ccb", "size": 6916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/symbolic/OrdinaryDifferentialEquation.hpp", "max_stars_repo_name": "helkebir/Lodestar", "max_stars_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T14:08:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T22:15:31.000Z", "max_issues_repo_path": "Lodestar/symbolic/OrdinaryDifferentialEquation.hpp", "max_issues_repo_name": "helkebir/Lodestar", "max_issues_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T15:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T17:43:20.000Z", "max_forks_repo_path": "Lodestar/symbolic/OrdinaryDifferentialEquation.hpp", "max_forks_repo_name": "helkebir/Lodestar", "max_forks_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T03:15:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T03:15:23.000Z", "avg_line_length": 39.52, "max_line_length": 161, "alphanum_fraction": 0.545691151, "num_tokens": 1421, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4366899783718048}}
{"text": "/**\n * \\copyright\n * Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include \"MohrCoulomb.h\"\n\n#include \"BaseLib/Error.h\"\n#include \"MathLib/MathTools.h\"\n\n#ifndef Q_MOC_RUN // to avoid Qt4 bug, https://bugreports.qt.io/browse/QTBUG-22829\n#include <boost/math/special_functions/sign.hpp>\n#endif\n\nnamespace MaterialLib\n{\nnamespace Fracture\n{\n\nnamespace\n{\n\nstruct MaterialPropertyValues\n{\n    double Kn = 0.0;\n    double Ks = 0.0;\n    double phi = 0.0; // friction angle\n    double psi = 0.0; // dilation angle\n    double c = 0.0;\n\n    template <typename MaterialProperties>\n    MaterialPropertyValues(\n            MaterialProperties const& mp,\n            double const t,\n            ProcessLib::SpatialPosition const& x)\n    {\n        Kn = mp.normal_stiffness(t,x)[0];\n        Ks = mp.shear_stiffness(t,x)[0];\n        phi = MathLib::to_radians(mp.friction_angle(t,x)[0]);\n        psi = MathLib::to_radians(mp.dilatancy_angle(t,x)[0]);\n        c = mp.cohesion(t,x)[0];\n    }\n};\n\n} // no namespace\n\ntemplate <int DisplacementDim>\nvoid MohrCoulomb<DisplacementDim>::computeConstitutiveRelation(\n        double const t,\n        ProcessLib::SpatialPosition const& x,\n        Eigen::Ref<Eigen::VectorXd const> w_prev,\n        Eigen::Ref<Eigen::VectorXd const> w,\n        Eigen::Ref<Eigen::VectorXd const> sigma_prev,\n        Eigen::Ref<Eigen::VectorXd> sigma,\n        Eigen::Ref<Eigen::MatrixXd> Kep,\n        typename FractureModelBase<DisplacementDim>::MaterialStateVariables&\n        material_state_variables)\n{\n    if (DisplacementDim == 3)\n    {\n        OGS_FATAL(\"MohrCoulomb fracture model does not support 3D case.\");\n        return;\n    }\n    material_state_variables.reset();\n\n    MaterialPropertyValues const mat(_mp, t, x);\n    Eigen::VectorXd const dw = w - w_prev;\n\n    Eigen::MatrixXd Ke(2,2);\n    Ke.setZero();\n    Ke(0,0) = mat.Ks;\n    Ke(1,1) = mat.Kn;\n\n    sigma.noalias() = sigma_prev + Ke * dw;\n\n    // if opening\n    if (sigma[1] > 0)\n    {\n        Kep.setZero();\n        sigma.setZero();\n        material_state_variables.setTensileStress(true);\n        return;\n    }\n\n    // check shear yield function (Fs)\n    double const Fs = std::abs(sigma[0]) + sigma[1] * std::tan(mat.phi) - mat.c;\n    material_state_variables.setShearYieldFunctionValue(Fs);\n    if (Fs < .0)\n    {\n        Kep = Ke;\n        return;\n    }\n\n    Eigen::VectorXd dFs_dS(2);\n    dFs_dS[0] = boost::math::sign(sigma[0]);\n    dFs_dS[1] = std::tan(mat.phi);\n\n    // plastic potential function: Qs = |tau| + Sn * tan da\n    Eigen::VectorXd dQs_dS(2);\n    dQs_dS[0] = boost::math::sign(sigma[0]);\n    dQs_dS[1] = std::tan(mat.psi);\n\n    // plastic multiplier\n    Eigen::RowVectorXd const A = dFs_dS.transpose() * Ke / (dFs_dS.transpose() * Ke * dQs_dS);\n    double const d_eta = A * dw;\n\n    // plastic part of the dispalcement\n    Eigen::VectorXd const dwp = dQs_dS * d_eta;\n\n    // correct stress\n    sigma.noalias() = sigma_prev + Ke * (dw - dwp);\n\n    // Kep\n    Kep = Ke - Ke * dQs_dS * A;\n}\n\ntemplate class MohrCoulomb<2>;\ntemplate class MohrCoulomb<3>;\n\n}   // namespace Fracture\n}  // namespace MaterialLib\n", "meta": {"hexsha": "6b84617593ce6641efd40d1a72a4c2ce8d44b0f2", "size": 3294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MaterialLib/FractureModels/MohrCoulomb.cpp", "max_stars_repo_name": "HaibingShao/ogs6_ufz", "max_stars_repo_head_hexsha": "d4acfe7132eaa2010157122da67c7a4579b2ebae", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MaterialLib/FractureModels/MohrCoulomb.cpp", "max_issues_repo_name": "HaibingShao/ogs6_ufz", "max_issues_repo_head_hexsha": "d4acfe7132eaa2010157122da67c7a4579b2ebae", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MaterialLib/FractureModels/MohrCoulomb.cpp", "max_forks_repo_name": "HaibingShao/ogs6_ufz", "max_forks_repo_head_hexsha": "d4acfe7132eaa2010157122da67c7a4579b2ebae", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1428571429, "max_line_length": 94, "alphanum_fraction": 0.6241651488, "num_tokens": 945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8872045907347108, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.4366715735166487}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_REM_PIO2_MEDIUM_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REM_PIO2_MEDIUM_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing rem_pio2_medium capabilities\n\n    Computes the remainder modulo \\f$\\pi/2\\f$ with medium algorithm,\n    and the angle quadrant between 0 and 3.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r, rc;\n    as_integer<T> n;\n    rem_pio2_cephes(x, n, r);\n    @endcode\n\n    is similar to:\n\n    @code\n    as_integer<T> n = idivround2even(x, Pio_2<T>());\n    T r =  remainder(x, Pio_2<T>());\n    @endcode\n\n    @par Note:\n\n    @c rem_pio2_medium compute the remainder modulo \\f$\\pi/2\\f$ with medium algorithm,\n    and the angle quadrant between 0 and 3.\n    This is a medium_ version version accurate if the input is in:\n     \\f$[-2^6\\pi,2^6\\pi]\\f$ for float,\n     \\f$[-2^{18}\\pi,2^{18}\\pi]\\f$ for double.\n    \\par\n    The reduction of the argument modulo \\f$\\pi/2\\f$ is generally\n    the most difficult part of trigonometric evaluations.\n    The accurate algorithm is over costly and implies the knowledge\n    of a few hundred \\f$pi\\f$ decimals\n    some simpler algorithms as this one\n    can be used, but the precision is only insured on smaller intervals.\n\n    @see rem_pio2, rem_pio2_straight,rem_2pi,  rem_pio2_cephes,\n\n  **/\n  const boost::dispatch::functor<tag::rem_pio2_medium_> rem_pio2_medium = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/rem_pio2_medium.hpp>\n#include <boost/simd/function/simd/rem_pio2_medium.hpp>\n\n#endif\n", "meta": {"hexsha": "7abfbc1b589dd97c8226bb2a4cbd0e10921fb4b2", "size": 2039, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/rem_pio2_medium.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/function/rem_pio2_medium.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/rem_pio2_medium.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1285714286, "max_line_length": 100, "alphanum_fraction": 0.638548308, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4366633537379374}}
{"text": "//\n//  multivector.hpp\n//\n//  Created by r. on 09/05/14\n//\n\n#ifndef round1_multivector_hpp\n#define round1_multivector_hpp\n\n// Standard libraries\n#include <algorithm>    // std::random_shuffle\n#include <numeric> // std::iota\n#include <iostream>\n#include <vector>\n#include <queue>\n#include <string>\n#include <sstream>\n#include <list>\n#include <set>\n#include <limits>\n\n// Boost MPI\n#include <boost/mpi.hpp>\n#include <boost/serialization/vector.hpp>\n\n// Boost ublas\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/vector_sparse.hpp>\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n//\n#include \"../include/stopwatch.hpp\"\n\nnamespace mypara\n{\n    \n\tnamespace ublas = boost::numeric::ublas;\n    namespace mpi = boost::mpi;\n\t\n\tclass multivector : public ublas::matrix<double, ublas::column_major>\n\t{\n\tpublic:\n\t\ttypedef ublas::matrix<double, ublas::column_major> parent_type;\n\t\ttypedef parent_type::value_type value_type;\n\t\ttypedef parent_type::size_type size_type;\n\t\t\n\t\ttypedef ublas::matrix_column<parent_type> matrix_column;\n\t\ttypedef ublas::matrix_column<const parent_type> const_matrix_column;\n\t\t\n\t\ttypedef ublas::matrix<value_type, ublas::column_major> dense_matrix;\n\tprivate:\n\t\t// MPI\n\t\tmpi::communicator world;\n\tprivate:\n\t\t// Total number of verticals to distribute (horizontal size)\n\t\tunsigned int total;\n\t\t// For each process, begin and end of its portion\n\t\tstd::vector<unsigned int> p2gja;\n\t\tstd::vector<unsigned int> p2gjb;\n\tpublic:\n\t\tconst mpi::communicator& getcm() const { return world; }\n\tpublic:\n        // Width of the whole multivector\n\t\tunsigned int getot() const { return total; }\n        // Rank in the communicator\n\t\tunsigned int getrk() const { return world.rank(); }\n        // Begin of portion (global)\n\t\tunsigned int getja() const { return p2gja[getrk()]; }\n        // End of portion (global)\n\t\tunsigned int getjb() const { return p2gjb[getrk()]; }\n        // Size of portion\n\t\tunsigned int getsz() const { return (getjb() - getja()); }\n\tpublic:\n\t\tunsigned int gj2pr(unsigned int j) const\n        // Finds the owner process of global column j\n\t\t{\n\t\t\tfor (auto p = 0; p < world.size(); ++p)\n\t\t\t\tif ((p2gja[p] <= j) && (j < p2gjb[p]))\n\t\t\t\t\treturn p;\n\t\t\treturn world.size();\n\t\t}\n\t\t\n\t\tbool ismyj(unsigned int j) const { return ((getja() <= j) && (j < getjb())); }\n\tpublic:\n\t\tmultivector(const mpi::communicator& comm)\n\t\t: world(comm), total(0), parent_type(0,0)\n\t\t{\n\t\t}\n\t\t\n\t\tmultivector(size_type size1, unsigned int total, const mpi::communicator& comm)\n\t\t: world(comm), total(total), parent_type(0,0)\n\t\t// Pre: the operation is requested by all processes in the communicator comm\n\t\t{\n\t\t\tstopwatch::Time time(stopwatch::watches, \"multivector::multivector\");\n\t\t\t\n//\t\t\tworld.barrier();\n\t\t\t\n\t\t\t//cout << \"ID: \" << world.rank() << \": new multivector\" << endl;\n\t\t\t\n\t\t\tunsigned int wsize = world.size();\n\t\t\t\n\t\t\t// Compute everybody's portion\n\t\t\t{\n\t\t\t\tunsigned int share = total; // Number of vectors still to be distributed\n\t\t\t\tunsigned int pleft = wsize; // Number of processes still unemployed\n\t\t\t\twhile (pleft)\n\t\t\t\t{\n\t\t\t\t\tp2gjb.push_back(share);\n\t\t\t\t\tshare -= (share / pleft);\n\t\t\t\t\tp2gja.push_back(share);\n\t\t\t\t\tpleft--;\n\t\t\t\t}\n\t\t\t\tassert(share == 0);\n\t\t\t\tassert(pleft == 0);\n\t\t\t}\n\t\t\t\n\t\t\tassert(p2gja.size() == wsize);\n\t\t\tassert(p2gjb.size() == wsize);\n\t\t\t\n\t\t\tparent_type& mymat = *this;\n\t\t\tmymat.resize(size1, getsz());\n\t\t\tmymat.clear();\n\t\t}\n\tpublic:\n\t\tmultivector& operator=(const multivector&) = default;\n\tpublic:\n\t\tmatrix_column\n\t\tcolio_local(unsigned int j)\n\t\t// Provides access to global column #j\n\t\t// Pre: the column is owned by the local process\n\t\t{\n\t\t\tassert(ismyj(j));\n\t\t\tunsigned int loclj = (j - getja());\n\t\t\tparent_type& x = *this;\n\t\t\tublas::matrix_column< parent_type > mc(x, loclj);\n\t\t\treturn mc;\n\t\t}\n\t\t\n\t\tvoid\n\t\tsetcolumn(unsigned int j, const ublas::vector<value_type>& colmn)\n\t\t// Replaces global column #j\n\t\t// Pre: the column is owned by the local process\n\t\t{\n\t\t\tmatrix_column mc = this->colio_local(j);\n\t\t\tmc = colmn;\n\t\t}\n        \n        ublas::vector<value_type>\n        getcolumn(unsigned int j) const\n\t\t// Gets a copy of global column #j\n\t\t// Pre: the column is owned by the local process\n        {\n\t\t\tassert(ismyj(j));\n\t\t\tunsigned int loclj = (j - getja());\n\t\t\tconst parent_type& x = *this;\n            ublas::vector<value_type> v = column(x, loclj);\n\t\t\treturn v;\n        }\n\t\t\n\t\tdense_matrix\n\t\tgetwhole() const\n        // Combines all portions to one dense matrix available locally\n\t\t// Pre: requested by all processes in the communicator of u\n\t\t{\n\t\t\tgetcm().barrier();\n\t\t\t\n\t\t\tstd::vector<parent_type> parts;\n\t\t\tmpi::all_gather(getcm(), (parent_type&)(*this), parts);\n\t\t\tdense_matrix whole(size1(), getot());\n\t\t\tfor (auto p = 0; p < parts.size(); ++p)\n\t\t\t{\n\t\t\t\tublas::range vrang(0, parts[p].size1());\n\t\t\t\tublas::range hrang(p2gja[p], p2gjb[p]);\n\t\t\t\tublas::matrix_range<dense_matrix> subma(whole, vrang, hrang);\n\t\t\t\tsubma = parts[p];\n\t\t\t}\n\t\t\treturn whole;\n\t\t}\n\tpublic:\n\t\tbool\n\t\tshrink_communicator()\n\t\t// If the local has no capacity, it is removed from the communicator\n\t\t// Returns true iff the local has any capacity\n\t\t{\n\t\t\tmultivector& me = *this;\n\t\t\t\n\t\t\tunsigned int isfat = ((me.size2() == 0) ? 0 : 1);\n\t\t\tmpi::communicator small = me.getcm().split(isfat);\n\t\t\t\n\t\t\tembrace_communicator(small);\n\t\t\t\n\t\t\treturn (isfat != 0);\n\t\t}\n\t\t\n\t\tvoid\n\t\tembrace_communicator(const mpi::communicator& newcm)\n\t\t{\n\t\t\tmultivector& me = *this;\n\t\t\t\n\t\t\tunsigned int newja = me.getja();\n\t\t\tunsigned int newjb = me.getjb();\n\t\t\t\n\t\t\tassert(me.size2() == (newjb - newja));\n\t\t\t\n\t\t\tme.world = newcm;\n\t\t\t\n\t\t\tme.p2gja.resize(0);\n\t\t\tme.p2gjb.resize(0);\n\t\t\tmpi::all_gather(me.world, newja, me.p2gja);\n\t\t\tmpi::all_gather(me.world, newjb, me.p2gjb);\n\t\t}\n\t\t\n\tprivate:\n\t\tvoid\n\t\tkeepj(unsigned int ja, unsigned int jb)\n\t\t{\n            stopwatch::Time time(stopwatch::watches, \"mypara::multivector::keepj()\");\n\n\t\t\tmultivector& me = *this;\n            assert((0 <= ja) && (ja <= jb) && (jb <= me.getot()));\n\n            unsigned int np = me.getcm().size();\n            assert((np == me.p2gja.size()) && (np == me.p2gjb.size()));\n\n            for (unsigned int p = 0; p != np; ++p)\n            {\n                // Old range of process p\n                unsigned int oldja = me.p2gja[p];\n                unsigned int oldjb = me.p2gjb[p];\n\n                // New range of process p\n                unsigned int newja, newjb;\n                {\n                    newja = std::min(std::max(oldja, ja), oldjb);\n                    newjb = std::max(std::min(oldjb, jb), oldja);\n                    assert(newja <= newjb);\n                    assert((oldja <= newja) && (newjb <= oldjb));\n                }\n\n                // If I am process p, then cut my data to the new range\n                if (p == me.getcm().rank()) {\n                    ublas::range hrang(newja - oldja, newjb - oldja);\n                    ublas::range vrang(0, me.size1());\n                    ((parent_type)me) = ublas::matrix_range<parent_type>(me, vrang, hrang);\n                }\n\n                // Compute p2gja and p2gjb of process p\n                {\n                    assert(newja <= newjb);\n                    if (newja != newjb) {\n                        assert((ja <= newja) && (newja <= newjb) && (newjb <= jb));\n                        newja -= ja;\n                        newjb -= ja;\n                    } else {\n                        newja = newjb = 0;\n                    }\n\n                    me.p2gja[p] = newja;\n                    me.p2gjb[p] = newjb;\n                }\n            }\n\n            me.total = (jb - ja);\n\t\t}\n\t\t\n\tpublic:\n\t\tvoid\n\t\tsplit(multivector& A, multivector& B, unsigned int j0) const\n\t\t// First j0 columns of *this go to a, the others to b\n\t\t// Pre: *this, a and b all have the same communicator\n\t\t{\n            stopwatch::Time time(stopwatch::watches, \"mypara::multivector::split()\");\n\t\t\t\n\t\t\tconst multivector& me = *this;\n\t\t\tassert(j0 <= me.getot());\n\t\t\t\n\t\t\t//\n\t\t\tB.p2gja = A.p2gja = me.p2gja;\n\t\t\tB.p2gjb = A.p2gjb = me.p2gjb;\n            B.total = A.total = me.total;\n\t\t\t\n            // Clean data of a and b, but make consistent\n\t\t\tA.resize(0, A.getjb() - A.getja());\n\t\t\tB.resize(0, B.getjb() - B.getja());\n\t\t\t\n            //\n\t\t\tA.keepj(0, j0);\n\t\t\tB.keepj(j0, me.getot());\n\t\t\t\n\t\t\t// Copy data\n\t\t\tA.resize(me.size1(), A.getjb() - A.getja());\n\t\t\tB.resize(me.size1(), B.getjb() - B.getja());\n\t\t\t\n\t\t\t// This could be done more efficiently:\n\t\t\t\n\t\t\tfor (unsigned int j = A.getja(); j != A.getjb(); ++j) {\n\t\t\t\tA.setcolumn(j, me.getcolumn(j));\n\t\t\t}\n\t\t\t\n\t\t\tfor (unsigned int j = B.getja(); j != B.getjb(); ++j) {\n\t\t\t\tB.setcolumn(j, me.getcolumn(j0 + j));\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid\n\t\tmerge(multivector& a, multivector& b)\n\t\t// Pre: a and b are the (possibly modified) result of split\n\t\t// Note: a, b, and this need not share the communicator\n\t\t{\n\t\t\tstopwatch::Time time(stopwatch::watches, \"mypara::multivector::merge()\");\n\t\t\t\n\t\t\tmultivector& me = *this;\n\t\t\tassert(me.getot() == (a.getot() + b.getot()));\n\t\t\tassert((me.size1() == a.size1()) && (me.size1() == b.size1()));\n\t\t\t\n\t\t\tfor (unsigned int j = a.getja(); j != a.getjb(); ++j)\n\t\t\t{\n\t\t\t\tme.setcolumn(j, a.getcolumn(j));\n\t\t\t}\n\t\t\t\n\t\t\tunsigned int j0 = a.getot();\n\t\t\tfor (unsigned int j = b.getja(); j != b.getjb(); ++j)\n\t\t\t{\n\t\t\t\tme.setcolumn(j0 + j, b.getcolumn(j));\n\t\t\t}\n\t\t}\n\t\t\n\t};\n\t\n\t// Operators\n\t\n\tdouble\n\tinner_prod_max(const multivector& a, const multivector& b)\n\t// Pre: a and b share the mpi communicator\n\t// Pre: the operation is requested by all processes in the communicator of a / b\n\t{\n\t\tstopwatch::Time time(stopwatch::watches, \"multivector::inner_prod\");\n\t\t\n\t\tstd::vector<double> local_vec;\n\t\t{\n\t\t\tassert(a.getja() == b.getja());\n\t\t\tassert(a.getjb() == b.getjb());\n\t\t\t\n\t\t\tfor (unsigned int k = 0; k != a.getsz(); ++k)\n\t\t\t\tlocal_vec.push_back(ublas::inner_prod(ublas::column(a, k), ublas::column(b, k)));\n\t\t}\n\t\t\n\t\t// negative infinity\n\t\tdouble local = std::numeric_limits<double>::lowest();\n\t\t\n\t\tif (local_vec.size())\n\t\t\tlocal = *std::max_element(local_vec.begin(), local_vec.end());\n\t\t\n\t\tdouble global = 0;\n\t\t{\n\t\t\tmpi::all_reduce(a.getcm(), local, global, mpi::maximum<double>());\n\t\t}\n\t\t\n\t\treturn global;\n\t}\n\t\n\tdouble\n\tinner_prod(const multivector& a, const multivector& b)\n\t// Pre: a and b share the mpi communicator\n\t// Pre: the operation is requested by all processes in the communicator of a / b\n\t{\n        stopwatch::Time time(stopwatch::watches, \"multivector::inner_prod\");\n        \n\t\tdouble local = 0;\n\t\t{\n\t\t\tassert(a.getja() == b.getja());\n\t\t\tassert(a.getjb() == b.getjb());\n            \n\t\t\tfor (unsigned int k = 0; k != a.getsz(); ++k)\n\t\t\t{\n\t\t\t\tlocal += ublas::inner_prod(ublas::column(a, k), ublas::column(b, k));\n\t\t\t}\n\t\t}\n        \n\t\tdouble global = 0;\n\t\t{\n\t\t\tmpi::all_reduce(a.getcm(), local, global, std::plus<double>());\n\t\t}\n        \n\t\treturn global;\n\t}\n\t\n    // RIGHT MULTIPLY\n\n    void\n    prod_ref(const multivector& u, const multivector::dense_matrix& m, multivector& v)\n    // This is the reference implementation for the following:\n    // Right matrix multiply u * m, assumes no structure in m\n    // Compare with function prod(u, m, jplan, v)\n    // Pre: the operation is requested by all processes in the communicator of u and v\n    // Pre: u and v have the same communicator\n    {\n        stopwatch::Time time(stopwatch::watches, \"multivector::prod(ref)\");\n\n        typedef multivector::value_type value_type;\n        typedef multivector::const_matrix_column const_matrix_column;\n        typedef ublas::vector<value_type> vector;\n\n        for (unsigned int j = 0; j != v.getot(); ++j)\n        {\n            namespace ublas = boost::numeric::ublas;\n            typedef ublas::vector<value_type> Vec;\n\n            // From the j-th column of the right matrix m, get local subvector\n            ublas::vector<value_type> submv(u.getsz());\n            {\n                ublas::range verrg(u.getja(), u.getjb());\n                const_matrix_column colmj(m, j);\n                submv = ublas::vector_range<const_matrix_column>(colmj, verrg);\n            }\n\n            // Am I receiving data and/or sending data?\n            bool itodo = (v.ismyj(j) || (0 != ublas::norm_inf(submv)));\n\n            // A. Who has something to contribute?\n            // Note: cannot interchange order with B\n            mpi::communicator activ = u.getcm().split(itodo ? 1 : 0);\n\n            // B. Do I have something to contribute? If not, skip.\n            // Note: cannot interchange order with A\n            if (!itodo) continue;\n\n            // Find the rank of the process in the activ communicator\n            // that holds the j-th column of the result\n            unsigned int trank;\n            {\n                unsigned int local = (v.ismyj(j) ? activ.rank() : 0);\n                mpi::all_reduce(activ, local, trank, std::plus<unsigned int>());\n            }\n\n            // Local contribution to j-th column of the result\n            Vec myvec(u.size1());\n            myvec = ublas::prod(u, submv);\n\n            // Am I to receive the product vector?\n            if (activ.rank() == trank) {\n                Vec resul(myvec.size());\n                mpi::reduce(activ, myvec, resul, std::plus<Vec>(), trank);\n                v.setcolumn(j, resul);\n            } else {\n                mpi::reduce(activ, myvec, std::plus<Vec>(), trank);\n            }\n        }\n\n        v.getcm().barrier();\n    }\n\n\t\n\tstruct Jplan\n\t{\n\tpublic:\n\t\tenum Strategy { nnz = 1, jforward = 2, jreverse = 4 };\n\tprivate:\n\t\tStrategy strategy;\n\tpublic:\n\t\ttypedef double value_type;\n\t\ttypedef ublas::compressed_vector<value_type> sparse_vector;\n\t\ttypedef ublas::compressed_matrix<value_type, ublas::column_major> sparse_matrix;\n\tpublic:\n\t\tstd::vector<sparse_vector> M_local;\n\tpublic:\n\t\ttypedef ublas::vector<unsigned int> GROUP;\n\t\ttypedef ublas::vector<unsigned int> TARGT;\n\tpublic:\n\t\tstd::vector<GROUP> group_plan;\n\t\tstd::vector<TARGT> targt_plan;\n\tprivate:\n\t\tbool ready;\n\tpublic:\n\t\tbool is_ready() const { return ready; }\n\tpublic:\n\t\tJplan() : ready(false), strategy(Strategy::nnz) { }\n\t\t\n\t\tJplan& operator()(const Strategy& s)\n\t\t{\n\t\t\tstrategy = s;\n\t\t\treturn (*this);\n\t\t}\n\t\t\n\t\tvoid\n\t\tcompute(const multivector& u, const sparse_matrix& m, const multivector& v)\n\t\t// Pre: u and v have the same communicator\n\t\t{\n\t\t\tstopwatch::Time time(stopwatch::watches, \"Jplan::compute\");\n\t\t\t\n\t\t\tassert(u.getot() == m.size1());\n\t\t\tassert(v.getot() == m.size2());\n\t\t\t\n\t\t\t// Horizontal size of the result multivector v\n\t\t\tunsigned int width = (unsigned int)(m.size2());\n\t\t\t\n\t\t\t// Clear\n\t\t\t{\n\t\t\t\tM_local.clear();\n\t\t\t\tgroup_plan.clear();\n\t\t\t\ttargt_plan.clear();\n\t\t\t}\n\t\t\t\n\t\t\tstd::vector<sparse_vector> M;\n\t\t\t\n\t\t\t// Step 1.\n\t\t\t// Convert the right multiplication matrix to a vector of vectors\n\t\t\tfor (unsigned int j = 0; j != width; ++j)\n\t\t\t{\n\t\t\t\tsparse_vector v(ublas::column(m, j));\n\t\t\t\tM.push_back(v);\n\t\t\t\t\n\t\t\t\t// From the j-th column of the right matrix m, get local subvector\n\t\t\t\tsparse_vector submv(u.getsz());\n\t\t\t\t{\n\t\t\t\t\tublas::range range(u.getja(), u.getjb());\n\t\t\t\t\tsubmv = ublas::vector_range<sparse_vector>(v, range);\n\t\t\t\t}\n\t\t\t\tassert(submv.size() == u.getsz());\n\t\t\t\tM_local.push_back(submv);\n\t\t\t}\n\t\t\t\n\t\t\t// Step 2.\n\t\t\t// Create sets of disjoint communication groups\n\t\t\t{\n\t\t\t\tstd::list<unsigned int> jleft;\n\t\t\t\t{\n\t\t\t\t\tstd::vector<unsigned int> order(M.size());\n\t\t\t\t\t\n\t\t\t\t\t// Default strategy: Strategy::jforward\n\t\t\t\t\tstd::iota(order.begin(), order.end(), 0.);\n\t\t\t\t\t\n\t\t\t\t\tif (strategy == Strategy::nnz)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Sort with decreasing nnz value\n\t\t\t\t\t\tstruct R {\n\t\t\t\t\t\t\ttypedef std::vector<sparse_vector> VOV;\n\t\t\t\t\t\t\tconst VOV& M;\n\t\t\t\t\t\t\tR(const VOV& M) : M(M) { }\n\t\t\t\t\t\t\tbool operator()(unsigned int i, unsigned int j) const {\n\t\t\t\t\t\t\t\treturn (M[i].nnz() > M[j].nnz());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t\tstd::sort(order.begin(), order.end(), R(M));\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (strategy == Strategy::jreverse) {\n\t\t\t\t\t\tstd::sort(order.rbegin(), order.rend());\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tfor (unsigned int j = 0; j != width; ++j)\n\t\t\t\t\t\tjleft.push_back(order[j]);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// While there are target columns to process\n\t\t\t\twhile (jleft.size())\n\t\t\t\t{\n\t\t\t\t\tGROUP group(u.getcm().size());\n\t\t\t\t\t// group[p] is the number of the communication group\n\t\t\t\t\t// where process p is involved\n\t\t\t\t\t// It is zero if the process has nothing to communicate\n\t\t\t\t\t\n\t\t\t\t\tTARGT targt(u.getcm().size());\n\t\t\t\t\t// targt[p] is the target column in the result\n\t\t\t\t\t// for the communication group masks[p]\n\t\t\t\t\t\n\t\t\t\t\tgroup.clear();\n\t\t\t\t\ttargt.clear();\n\t\t\t\t\t\n\t\t\t\t\tunsigned int grpno = 0;\n\t\t\t\t\tauto pj = jleft.begin();\n\t\t\t\t\twhile (pj != jleft.end())\n\t\t\t\t\t{\n\t\t\t\t\t\t// jmask[p] is one if process p is involved, and zero else\n\t\t\t\t\t\tublas::vector<unsigned int> jmask(group.size());\n\t\t\t\t\t\tjmask.clear();\n\t\t\t\t\t\t\n\t\t\t\t\t\tunsigned int j = *pj;\n\t\t\t\t\t\t\n\t\t\t\t\t\t// conflict iff jmask has nontrivial overlap with group\n\t\t\t\t\t\tbool conflict = false;\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Target index\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tunsigned int p = v.gj2pr(j);\n\t\t\t\t\t\t\tconflict = conflict || (group[p] != 0);\n\t\t\t\t\t\t\tjmask[p] = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Source indices\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttypedef ublas::compressed_vector<double> sparse_vector;\n\t\t\t\t\t\t\tconst sparse_vector& vj = M[j];\n\t\t\t\t\t\t\t// (Does a non-const iterator work here?)\n\t\t\t\t\t\t\tfor (sparse_vector::const_iterator i = vj.begin(); i != vj.end(); ++i)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tunsigned int p = u.gj2pr((unsigned int)i.index());\n\t\t\t\t\t\t\t\tconflict = conflict || (group[p] != 0);\n\t\t\t\t\t\t\t\tjmask[p] = 1;\n\t\t\t\t\t\t\t\tif (conflict) break;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (conflict) {\n\t\t\t\t\t\t\t// Bad luck, try another column j\n\t\t\t\t\t\t\tpj++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tgrpno++;\n\t\t\t\t\t\t\tgroup += (grpno * jmask);\n\t\t\t\t\t\t\ttargt += (j * jmask);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// The target column j has been scheduled for processing\n\t\t\t\t\t\t\t// Remove from queue and proceed to next column\n\t\t\t\t\t\t\tpj = jleft.erase(pj);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tgroup_plan.push_back(group);\n\t\t\t\t\ttargt_plan.push_back(targt);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tthis->ready = true;\n\t\t}\n\t}; // class Jplan\n\t\n\t\n\tvoid\n\tprod(const multivector& u, const Jplan::sparse_matrix& m, Jplan& jplan, multivector& v)\n    // Right matrix multiply, u * m\n\t// Good for matrices m where each row is sparse\n\t// Pre: the operation is requested by all processes in the communicator of u and v\n\t// Pre: u and v have the same communicator\n\t// TODO: implement using MPI groups\n\t{\n        stopwatch::Time time(stopwatch::watches, \"multivector::prod(jplan)\");\n\t\t\n\t\ttypedef multivector::value_type value_type;\n\t\t//\t\ttypedef multivector::dense_matrix dense_matrix;\n\t\ttypedef multivector::const_matrix_column const_matrix_column;\n        typedef ublas::vector<value_type> vector;\n\t\t\n\t\tif (!jplan.is_ready()) jplan.compute(u, m, v);\n\t\tassert(jplan.is_ready());\n\t\t\n\t\tfor (unsigned int k = 0; k != jplan.group_plan.size(); ++k)\n\t\t{\n\t\t\tauto& group = jplan.group_plan[k];\n\t\t\tauto& targt = jplan.targt_plan[k];\n\t\t\t\n\t\t\t//std::cout << \"group: \" << group << std::endl;\n\t\t\t//std::cout << \"targt: \" << targt << std::endl;\n\t\t\t\n\t\t\t// Partition the MPI communicator into disjoint groups\n\t\t\t\n\t\t\tunsigned int r = u.getcm().rank();\n\t\t\tunsigned int color = group[r];\n\t\t\t//std::cout << masks << std::endl;\n\t\t\tmpi::communicator activ = u.getcm().split(color);\n\t\t\t\n\t\t\t//std::cout << \"Proc: \" << r << \"; color: \" << color << \"; targt: \" << targt[r] << std::endl;\n\t\t\t\n\t\t\t// Am I in one of the communicating groups?\n\t\t\tif (!color) continue;\n\t\t\t\n\t\t\t// The truly parallel part:\n\t\t\t// Compute the partial matrix matrix product\n\t\t\t\n\t\t\tunsigned int j = targt[r];\n\t\t\t\n\t\t\t// From the j-th column of the right matrix m, get local subvector\n\t\t\tconst Jplan::sparse_vector& submv = jplan.M_local[j];\n\t\t\t\n\t\t\t// Find the rank of the process in the activ communicator\n\t\t\t// that holds the j-th column of the result\n\t\t\tunsigned int jdest;\n\t\t\t{\n\t\t\t\tunsigned int local = (v.ismyj(j) ? activ.rank() : 0);\n\t\t\t\tmpi::all_reduce(activ, local, jdest, std::plus<unsigned int>());\n\t\t\t}\n\t\t\t\n\t\t\t//std::cout << \"j: \" << j << \"; trank: \" << trank << std::endl;\n\t\t\t\n\t\t\t// Local contribution to j-th column of the result\n\t\t\ttypedef ublas::vector<value_type> Vec;\n\t\t\tVec myvec(u.size1()); myvec.clear();\n\t\t\tmyvec = ublas::prod(u, submv);\n\t\t\t\n\t\t\t// Am I to receive the product vector?\n\t\t\tif (activ.rank() == jdest) {\n\t\t\t\tVec resul(myvec.size());\n\t\t\t\tmpi::reduce(activ, myvec, resul, std::plus<Vec>(), jdest);\n\t\t\t\tv.setcolumn(j, resul);\n\t\t\t} else {\n\t\t\t\tmpi::reduce(activ, myvec, std::plus<Vec>(), jdest);\n\t\t\t}\n\t\t}\n\n        #ifndef NDEBUG\n        /// Check correctness\n        {\n            multivector v_ref = v;\n            mypara::prod_ref(u, m, v_ref);\n            assert(v.size1() == v_ref.size1());\n            assert(v.size2() == v_ref.size2());\n            assert(ublas::norm_inf(v - v_ref) <= 1e-6);\n        }//*/\n        #endif\n\t}\n\t\n\tmultivector\n\tprod(const multivector& u, const multivector::dense_matrix& m, Jplan& jplan)\n    // Right matrix multiply. See void prod(u, m, jplan, v)\n\t{\n\t\tassert(u.getot() == m.size1());\n\t\t\n\t\tmultivector v(u.size1(), (unsigned int)(m.size2()), u.getcm());\n\t\tmypara::prod(u, m, jplan, v);\n\t\t\n\t\treturn v;\n\t}\n\t\n\n\tvoid\n\tprod(const multivector& u, const ublas::compressed_matrix<double, ublas::column_major>& m, multivector& v)\n\t// Asynchronous implementation of:\n    // Right matrix multiply u * m\n\t// Compare with function prod(u, m, jplan, v)\n    // Pre: m is sparse (send buffers created)\n\t// Pre: the operation is requested by all processes in the communicator of u and v\n\t// Pre: u and v have the same communicator\n\t{\n        stopwatch::Time time(stopwatch::watches, \"multivector::prod(asynch)\");\n\n        v.clear();\n\t\t\n\t\t// Type of m\n\t\ttypedef ublas::compressed_matrix<double, ublas::column_major> matrix;\n\t\t// Column of m\n\t\ttypedef ublas::matrix_column<const matrix> cmc;\n\t\t// Vector type of column of m\n\t\ttypedef ublas::compressed_vector<matrix::value_type> sparse_vector;\n\t\t\t\n\t\t// Step 1.\n\t\t// Convert the right multiplication matrix to a vector of vectors\n\t\tstd::vector<sparse_vector> M, M_local;\n\t\t{\n\t\t\tstopwatch::Time time(stopwatch::watches, \"multivector::prod(asynch).Mlocal\");\n\t\t\t\n\t\t\tfor (unsigned int j = 0; j != m.size2(); ++j)\n\t\t\t{\n\t\t\t\tsparse_vector vcolj(ublas::column(m, j));\n\t\t\t\t\n\t\t\t\t// From the j-th column of the right matrix m, get local subvector\n\t\t\t\tsparse_vector submv(u.getsz());\n\t\t\t\t{\n\t\t\t\t\tublas::range range(u.getja(), u.getjb());\n\t\t\t\t\tsubmv = ublas::vector_range<sparse_vector>(vcolj, range);\n\t\t\t\t\tassert(submv.size() == u.getsz());\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tM.push_back(vcolj);\n\t\t\t\tM_local.push_back(submv);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Vector for a column of u or v\n\t\ttypedef ublas::vector<multivector::value_type> Vec;\n\n        //\n        struct Packet {\n            int dest, src, tag;\n            Vec myvec;\n            //\n            Packet(int dest, int tag, const Vec& myvec, int src) : dest(dest), tag(tag), myvec(myvec), src(src)\n            { }\n\t\t\t//\n\t\t\tstd::string str() const {\n                std::stringstream s;\n                s << \"dest: \" << dest << \", \"\n                  << \"tag: \" << tag << \", \"\n                  << \"vecsize: \" << myvec.size() << \", \"\n                  << \"src: \" << src;\n                return s.str();\n\t\t\t}\n        };\n\n        // Queue in everything that has to be sent\n        std::list<Packet> sendbuf;\n        std::vector<mpi::request> sendreq;\n\t\t{\n\t\t\tstopwatch::Time time(stopwatch::watches, \"multivector::prod(asynch).sendbuf\");\n\t\t\t\n\t\t\t// Prepare for send: iterate over target columns\n\t\t\tfor (unsigned int j = 0; j != v.getot(); ++j)\n\t\t\t{\n\t\t\t\t// Is the target local?\n\t\t\t\tif (v.ismyj(j)) continue;\n\t\t\t\t\n\t\t\t\t// Local subvector from the j-th column of the right matrix m\n\t\t\t\tconst sparse_vector& submv = M_local[j];\n\t\t\t\t\n\t\t\t\t// Do I have data to send?\n\t\t\t\tif (0 == submv.nnz()) continue;\n\t\t\t\t\n\t\t\t\t// Local contribution to j-th column of the result\n\t\t\t\tVec myvec = ublas::prod(u, submv);\n\t\t\t\tassert(myvec.size() == v.size1());\n\t\t\t\t\n\t\t\t\t// Destination rank\n\t\t\t\tconst unsigned int trank = v.gj2pr(j);\n\t\t\t\t// Source rank\n\t\t\t\tconst unsigned int srank = u.getcm().rank();\n\t\t\t\t\n\t\t\t\tassert(trank != srank);\n\t\t\t\tconst int tag = j;\n\t\t\t\t// Put data into send buffer\n\t\t\t\tsendbuf.push_back(Packet(trank, tag, myvec, srank));\n\t\t\t\t\n\t\t\t\t// Submit MPI send request\n\t\t\t\tconst Packet& packet = sendbuf.back();\n\t\t\t\t//std::cout << \"Sending packet \" << packet.str() << std::endl;\n\t\t\t\tsendreq.push_back(u.getcm().isend(packet.dest, packet.tag, packet.myvec));\n\t\t\t}\n\t\t}\n\t\t\n        // Queue in everything that has to be received\n        std::list<Packet> recvbuf;\n        std::vector<mpi::request> recvreq;\n\t\t{\n\t\t\tstopwatch::Time time(stopwatch::watches, \"multivector::prod(asynch).recvbuf\");\n\t\t\t\n\t\t\tfor (unsigned int j = v.getja(); j != v.getjb(); ++j)\n\t\t\t{\n\t\t\t\t// j-th column of m\n\t\t\t\tsparse_vector vcolj = M[j];\n\t\t\t\t\n\t\t\t\t// Identify senders\n\t\t\t\tstd::set<unsigned int> ranks;\n\t\t\t\tfor (sparse_vector::const_iterator i = vcolj.begin(); i != vcolj.end(); ++i)\n\t\t\t\t{\n\t\t\t\t\t// Is the source local?\n\t\t\t\t\tif (u.ismyj((unsigned int)i.index())) continue;\n\t\t\t\t\t\n\t\t\t\t\tunsigned int srank = u.gj2pr((unsigned int)i.index());\n\t\t\t\t\tranks.insert(srank);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfor (auto i = ranks.begin(); i != ranks.end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tconst unsigned int srank = (*i);\n\t\t\t\t\tconst int tag = j;\n\t\t\t\t\t\n\t\t\t\t\t// Receive buffer\n                    // The target vector will be automatically resized by boost::mpi\n\t\t\t\t\trecvbuf.push_back(Packet(v.getcm().rank(), tag, Vec(0), srank));\n\t\t\t\t\t\n\t\t\t\t\t// Submit MPI receive request\n\t\t\t\t\tPacket& packet = recvbuf.back();\n\t\t\t\t\t//std::cout << \"Recving packet \" << packet.str() << std::endl;\n\t\t\t\t\trecvreq.push_back(u.getcm().irecv(packet.src, packet.tag, packet.myvec));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n        // Do what is entirely local\n\t\t{\n\t\t\tstopwatch::Time time(stopwatch::watches, \"multivector::prod(asynch).local\");\n\t\t\t\n\t\t\tfor (unsigned int j = v.getja(); j != v.getjb(); ++j)\n\t\t\t{\n\t\t\t\t// Local contribution to j-th column of the result\n\t\t\t\tv.setcolumn(j, ublas::prod(u, M_local[j]));\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Receive all data\n\t\t{\n\t\t\tstopwatch::Time time(stopwatch::watches, \"multivector::prod(asynch).recvall\");\n\t\t\t\n\t\t\tmpi::wait_all(recvreq.begin(), recvreq.end());\n\t\t\t//std::cout << \"#\" << v.getcm().rank() << \": recieved\" << std::endl;\n\t\t\t\n\t\t\tfor (std::list<Packet>::const_iterator i = recvbuf.begin(); i != recvbuf.end(); ++i)\n\t\t\t{\n\t\t\t\tunsigned int j = i->tag;\n\t\t\t\tassert(v.ismyj(j));\n\t\t\t\tassert(i->myvec.size() == v.size1());\n\t\t\t\tv.colio_local(j) += i->myvec;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Wait for all sent data to be received (before destroying the send buffer)\n\t\t{\n\t\t\tstopwatch::Time time(stopwatch::watches, \"multivector::prod(asynch).sendall\");\n\t\t\t\n\t\t\tmpi::wait_all(sendreq.begin(), sendreq.end());\n\t\t\t//std::cout << \"#\" << v.getcm().rank() << \": sent\" << std::endl;\n\t\t}\n//\t\tv.getcm().barrier();\n\n        #ifndef NDEBUG\n        /// Check correctness\n        {\n            multivector v_ref = v;\n            mypara::prod_ref(u, m, v_ref);\n            assert(v.size1() == v_ref.size1());\n            assert(v.size2() == v_ref.size2());\n            assert(ublas::norm_inf(v - v_ref) <= 1e-6);\n\t\t\tstd::cout << \"Prod check ok (use -DNDEBUG to disable)\" << std::endl;\n        }//*/\n        #endif\n\t}\n\t\n\tmultivector\n    prod(const multivector& u, const ublas::compressed_matrix<double, ublas::column_major>& m)\n    // Right matrix multiply. See void prod(u, m, v)\n\t{\n\t\tassert(u.getot() == m.size1());\n\t\t\n\t\tmultivector v(u.size1(), (unsigned int)(m.size2()), u.getcm());\n\t\tmypara::prod(u, m, v);\n\t\t\n\t\treturn v;\n\t}\n\n\n    // LEFT MULTIPLY\n\t\n\t\n\tmultivector\n\tprod(const ublas::compressed_matrix<double, ublas::row_major>& m, const multivector& u)\n    // Left matrix multiply\n\t{\n        stopwatch::Time time(stopwatch::watches, \"multivector::prod(left)\");\n\t\t\n//\t\tu.getcm().barrier();\n\t\t\n\t\tassert(m.size2() == u.size1());\n\t\t\n\t\t\n\t\tmultivector v(m.size1(), u.getot(), u.getcm());\n\t\t{\n\t\t\t//ublas::compressed_matrix<multivector::value_type, ublas::column_major> m1(m);\n\t\t\t//ublas::matrix<multivector::value_type, ublas::row_major> u1(u);\n\t\t\tstopwatch::Time time(stopwatch::watches, \"multivector::prod(left)/ublas::prod\");\n\t\t\t((multivector::parent_type&)v) = boost::numeric::ublas::prod(m, u);\n\t\t}\n\t\t\n\t\treturn v;\n\t}\n}\n\n\n\n#endif\n", "meta": {"hexsha": "39198e49ab7c5ee5ce0c19c0f3c84c9e45bd0d11", "size": 28089, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "parawt/c++/include/multivector.hpp", "max_stars_repo_name": "numpde/parabolic", "max_stars_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "parawt/c++/include/multivector.hpp", "max_issues_repo_name": "numpde/parabolic", "max_issues_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parawt/c++/include/multivector.hpp", "max_forks_repo_name": "numpde/parabolic", "max_forks_repo_head_hexsha": "7d102f19c0991d720779f4b5d456571794651b17", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2289281998, "max_line_length": 111, "alphanum_fraction": 0.5848552814, "num_tokens": 8061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.43666334641374777}}
{"text": "//  (C) Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_TOOLS_SOLVE_HPP\n#define BOOST_MATH_TOOLS_SOLVE_HPP\n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\n#include <boost/config.hpp>\n#include <boost/math/tools/assert.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable:4996 4267 4244)\n#endif\n\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\nnamespace boost{ namespace math{ namespace tools{\n\n//\n// Find x such that Ax = b\n//\n// Caution: this uses undocumented, and untested ublas code,\n// however short of writing our own LU-decomposition code\n// it's the only game in town.\n//\ntemplate <class T>\nboost::numeric::ublas::vector<T> solve(\n          const boost::numeric::ublas::matrix<T>& A_,\n          const boost::numeric::ublas::vector<T>& b_)\n{\n   //BOOST_MATH_ASSERT(A_.size() == b_.size());\n\n   boost::numeric::ublas::matrix<T> A(A_);\n   boost::numeric::ublas::vector<T> b(b_);\n   boost::numeric::ublas::permutation_matrix<> piv(b.size());\n   lu_factorize(A, piv);\n   lu_substitute(A, piv, b);\n   //\n   // iterate to reduce error:\n   //\n   boost::numeric::ublas::vector<T> delta(b.size());\n   for(unsigned k = 0; k < 1; ++k)\n   {\n      noalias(delta) = prod(A_, b);\n      delta -= b_;\n      lu_substitute(A, piv, delta);\n      b -= delta;\n\n      T max_error = 0;\n\n      for(unsigned i = 0; i < delta.size(); ++i)\n      {\n         T err = fabs(delta[i] / b[i]);\n         if(err > max_error)\n            max_error = err;\n      }\n      //std::cout << \"Max change in LU error correction: \" << max_error << std::endl;\n   }\n\n   return b;\n}\n\n}}} // namespaces\n\n#endif // BOOST_MATH_TOOLS_SOLVE_HPP\n\n\n", "meta": {"hexsha": "f524414a8919ad5817c816f1919b5e054b7d0249", "size": 1915, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include_private/boost/math/tools/solve.hpp", "max_stars_repo_name": "jwuttke/math", "max_stars_repo_head_hexsha": "45a2cbe789e1b81d310024d58c9616cc434a63d3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-10T12:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-10T13:59:44.000Z", "max_issues_repo_path": "include_private/boost/math/tools/solve.hpp", "max_issues_repo_name": "jwuttke/math", "max_issues_repo_head_hexsha": "45a2cbe789e1b81d310024d58c9616cc434a63d3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "include_private/boost/math/tools/solve.hpp", "max_forks_repo_name": "jwuttke/math", "max_forks_repo_head_hexsha": "45a2cbe789e1b81d310024d58c9616cc434a63d3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 23.9375, "max_line_length": 85, "alphanum_fraction": 0.6490861619, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.43666333908955784}}
{"text": "\n//=======================================================================\n// Copyright 2008\n// Author: Matyas W Egyhazy\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#ifndef BOOST_GRAPH_METRIC_TSP_APPROX_HPP\n#define BOOST_GRAPH_METRIC_TSP_APPROX_HPP\n\n// metric_tsp_approx\n// Generates an approximate tour solution for the traveling salesperson\n// problem in polynomial time. The current algorithm guarantees a tour with a\n// length at most as long as 2x optimal solution. The graph should have\n// 'natural' (metric) weights such that the triangle inequality is maintained.\n// Graphs must be fully interconnected.\n\n// TODO:\n// There are a couple of improvements that could be made.\n// 1) Change implementation to lower uppper bound Christofides heuristic\n// 2) Implement a less restrictive TSP heuristic (one that does not rely on\n//    triangle inequality).\n// 3) Determine if the algorithm can be implemented without creating a new\n//    graph.\n\n#include <vector>\n\n#include <boost/shared_ptr.hpp>\n#include <boost/concept_check.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_as_tree.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <boost/graph/lookup_edge.hpp>\n#include <boost/throw_exception.hpp>\n\nnamespace boost\n{\n    // Define a concept for the concept-checking library.\n    template <typename Visitor, typename Graph>\n    struct TSPVertexVisitorConcept\n    {\n    private:\n        Visitor vis_;\n    public:\n        typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n\n        BOOST_CONCEPT_USAGE(TSPVertexVisitorConcept)\n        {\n            Visitor vis(vis_);  // require copy construction\n            Graph g(1);\n            Vertex v(*vertices(g).first);\n            vis_.visit_vertex(v, g); // require visit_vertex\n        }\n    };\n\n    // Tree visitor that keeps track of a preorder traversal of a tree\n    // TODO: Consider migrating this to the graph_as_tree header.\n    // TODO: Parameterize the underlying stores o it doesn't have to be a vector.\n    template<typename Node, typename Tree> class PreorderTraverser\n    {\n    private:\n        std::vector<Node>& path_;\n    public:\n        typedef typename std::vector<Node>::const_iterator const_iterator;\n\n        PreorderTraverser(std::vector<Node>& p) : path_(p) {}\n\n        void preorder(Node n, const Tree&)\n        { path_.push_back(n); }\n\n        void inorder(Node, const Tree&) const {}\n        void postorder(Node, const Tree&) const {}\n\n        const_iterator begin() const { return path_.begin(); }\n        const_iterator end() const { return path_.end(); }\n    };\n\n    // Forward declarations\n    template <typename> class tsp_tour_visitor;\n    template <typename, typename, typename, typename> class tsp_tour_len_visitor;\n\n    template<typename VertexListGraph, typename OutputIterator>\n    void metric_tsp_approx_tour(VertexListGraph& g, OutputIterator o)\n    {\n        metric_tsp_approx_from_vertex(g, *vertices(g).first,\n            get(edge_weight, g), get(vertex_index, g),\n            tsp_tour_visitor<OutputIterator>(o));\n    }\n\n    template<typename VertexListGraph, typename WeightMap, typename OutputIterator>\n    void metric_tsp_approx_tour(VertexListGraph& g, WeightMap w, OutputIterator o)\n    {\n        metric_tsp_approx_from_vertex(g, *vertices(g).first,\n            w, tsp_tour_visitor<OutputIterator>(o));\n    }\n\n    template<typename VertexListGraph, typename OutputIterator>\n    void metric_tsp_approx_tour_from_vertex(VertexListGraph& g,\n        typename graph_traits<VertexListGraph>::vertex_descriptor start,\n        OutputIterator o)\n    {\n        metric_tsp_approx_from_vertex(g, start, get(edge_weight, g),\n            get(vertex_index, g), tsp_tour_visitor<OutputIterator>(o));\n    }\n\n    template<typename VertexListGraph, typename WeightMap,\n        typename OutputIterator>\n    void metric_tsp_approx_tour_from_vertex(VertexListGraph& g,\n    typename graph_traits<VertexListGraph>::vertex_descriptor start,\n        WeightMap w, OutputIterator o)\n    {\n        metric_tsp_approx_from_vertex(g, start, w, get(vertex_index, g),\n            tsp_tour_visitor<OutputIterator>(o));\n    }\n\n    template<typename VertexListGraph, typename TSPVertexVisitor>\n    void metric_tsp_approx(VertexListGraph& g, TSPVertexVisitor vis)\n    {\n        metric_tsp_approx_from_vertex(g, *vertices(g).first,\n            get(edge_weight, g), get(vertex_index, g), vis);\n    }\n\n    template<typename VertexListGraph, typename Weightmap,\n        typename VertexIndexMap, typename TSPVertexVisitor>\n    void metric_tsp_approx(VertexListGraph& g, Weightmap w,\n        TSPVertexVisitor vis)\n    {\n        metric_tsp_approx_from_vertex(g, *vertices(g).first, w,\n            get(vertex_index, g), vis);\n    }\n\n    template<typename VertexListGraph, typename WeightMap,\n        typename VertexIndexMap, typename TSPVertexVisitor>\n    void metric_tsp_approx(VertexListGraph& g, WeightMap w, VertexIndexMap id,\n        TSPVertexVisitor vis)\n    {\n        metric_tsp_approx_from_vertex(g, *vertices(g).first, w, id, vis);\n    }\n\n    template<typename VertexListGraph, typename WeightMap,\n        typename TSPVertexVisitor>\n    void metric_tsp_approx_from_vertex(VertexListGraph& g,\n    typename graph_traits<VertexListGraph>::vertex_descriptor start,\n        WeightMap w, TSPVertexVisitor vis)\n    {\n        metric_tsp_approx_from_vertex(g, start, w, get(vertex_index, g), vis);\n    }\n\n    template <\n        typename VertexListGraph,\n        typename WeightMap,\n        typename VertexIndexMap,\n        typename TSPVertexVisitor>\n    void metric_tsp_approx_from_vertex(const VertexListGraph& g,\n                                       typename graph_traits<VertexListGraph>::vertex_descriptor start,\n                                       WeightMap weightmap,\n                                       VertexIndexMap indexmap,\n                                       TSPVertexVisitor vis)\n    {\n        using namespace boost;\n        using namespace std;\n\n        BOOST_CONCEPT_ASSERT((VertexListGraphConcept<VertexListGraph>));\n        BOOST_CONCEPT_ASSERT((TSPVertexVisitorConcept<TSPVertexVisitor, VertexListGraph>));\n\n        // Types related to the input graph (GVertex is a template parameter).\n        typedef typename graph_traits<VertexListGraph>::vertex_descriptor GVertex;\n        typedef typename graph_traits<VertexListGraph>::vertex_iterator GVItr;\n\n        // We build a custom graph in this algorithm.\n        typedef adjacency_list <vecS, vecS, directedS, no_property, no_property > MSTImpl;\n        typedef graph_traits<MSTImpl>::vertex_descriptor Vertex;\n        typedef graph_traits<MSTImpl>::vertex_iterator VItr;\n\n        // And then re-cast it as a tree.\n        typedef iterator_property_map<vector<Vertex>::iterator, property_map<MSTImpl, vertex_index_t>::type> ParentMap;\n        typedef graph_as_tree<MSTImpl, ParentMap> Tree;\n        typedef tree_traits<Tree>::node_descriptor Node;\n\n        // A predecessor map.\n        typedef vector<GVertex> PredMap;\n        typedef iterator_property_map<typename PredMap::iterator, VertexIndexMap> PredPMap;\n\n        PredMap preds(num_vertices(g));\n        PredPMap pred_pmap(preds.begin(), indexmap);\n\n        // Compute a spanning tree over the in put g.\n        prim_minimum_spanning_tree(g, pred_pmap,\n             root_vertex(start)\n            .vertex_index_map(indexmap)\n            .weight_map(weightmap));\n\n        // Build a MST using the predecessor map from prim mst\n        MSTImpl mst(num_vertices(g));\n        std::size_t cnt = 0;\n        pair<VItr, VItr> mst_verts(vertices(mst));\n        for(typename PredMap::iterator vi(preds.begin()); vi != preds.end(); ++vi, ++cnt)\n        {\n            if(indexmap[*vi] != cnt) {\n                add_edge(*next(mst_verts.first, indexmap[*vi]),\n                         *next(mst_verts.first, cnt), mst);\n            }\n        }\n\n        // Build a tree abstraction over the MST.\n        vector<Vertex> parent(num_vertices(mst));\n        Tree t(mst, *vertices(mst).first,\n            make_iterator_property_map(parent.begin(),\n            get(vertex_index, mst)));\n\n        // Create tour using a preorder traversal of the mst\n        vector<Node> tour;\n        PreorderTraverser<Node, Tree> tvis(tour);\n        traverse_tree(indexmap[start], t, tvis);\n\n        pair<GVItr, GVItr> g_verts(vertices(g));\n        for(PreorderTraverser<Node, Tree>::const_iterator curr(tvis.begin());\n            curr != tvis.end(); ++curr)\n        {\n            // TODO: This is will be O(n^2) if vertex storage of g != vecS.\n            GVertex v = *next(g_verts.first, get(vertex_index, mst)[*curr]);\n            vis.visit_vertex(v, g);\n        }\n\n        // Connect back to the start of the tour\n        vis.visit_vertex(start, g);\n    }\n\n    // Default tsp tour visitor that puts the tour in an OutputIterator\n    template <typename OutItr>\n    class tsp_tour_visitor\n    {\n        OutItr itr_;\n    public:\n        tsp_tour_visitor(OutItr itr)\n            : itr_(itr)\n        { }\n\n        template <typename Vertex, typename Graph>\n        void visit_vertex(Vertex v, const Graph&)\n        {\n            BOOST_CONCEPT_ASSERT((OutputIterator<OutItr, Vertex>));\n            *itr_++ = v;\n        }\n\n    };\n\n    // Tsp tour visitor that adds the total tour length.\n    template<typename Graph, typename WeightMap, typename OutIter, typename Length>\n    class tsp_tour_len_visitor\n    {\n        typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n        BOOST_CONCEPT_ASSERT((OutputIterator<OutIter, Vertex>));\n\n        OutIter iter_;\n        Length& tourlen_;\n        WeightMap& wmap_;\n        Vertex previous_;\n\n        // Helper function for getting the null vertex.\n        Vertex null()\n        { return graph_traits<Graph>::null_vertex(); }\n\n    public:\n        tsp_tour_len_visitor(Graph const&, OutIter iter, Length& l, WeightMap map)\n            : iter_(iter), tourlen_(l), wmap_(map), previous_(null())\n        { }\n\n        void visit_vertex(Vertex v, const Graph& g)\n        {\n            typedef typename graph_traits<Graph>::edge_descriptor Edge;\n\n            // If it is not the start, then there is a\n            // previous vertex\n            if(previous_ != null())\n            {\n                // NOTE: For non-adjacency matrix graphs g, this bit of code\n                // will be linear in the degree of previous_ or v. A better\n                // solution would be to visit edges of the graph, but that\n                // would require revisiting the core algorithm.\n                Edge e;\n                bool found;\n                boost::tie(e, found) = lookup_edge(previous_, v, g);\n                if(!found) {\n                    BOOST_THROW_EXCEPTION(not_complete());\n                }\n\n                tourlen_ += wmap_[e];\n            }\n\n            previous_ = v;\n            *iter_++ = v;\n        }\n    };\n\n    // Object generator(s)\n    template <typename OutIter>\n    inline tsp_tour_visitor<OutIter>\n    make_tsp_tour_visitor(OutIter iter)\n    { return tsp_tour_visitor<OutIter>(iter); }\n\n    template <typename Graph, typename WeightMap, typename OutIter, typename Length>\n    inline tsp_tour_len_visitor<Graph, WeightMap, OutIter, Length>\n    make_tsp_tour_len_visitor(Graph const& g, OutIter iter, Length& l, WeightMap map)\n    { return tsp_tour_len_visitor<Graph, WeightMap, OutIter, Length>(g, iter, l, map); }\n\n} //boost\n\n#endif // BOOST_GRAPH_METRIC_TSP_APPROX_HPP\n", "meta": {"hexsha": "c8e7dba5955573f7577e47f777ded708558b5e8d", "size": 11676, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/graph/metric_tsp_approx.hpp", "max_stars_repo_name": "multi-os-engine/cinder-natj-binding", "max_stars_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "deps/cinder/include/boost/graph/metric_tsp_approx.hpp", "max_issues_repo_name": "multi-os-engine/cinder-natj-binding", "max_issues_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1074.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T15:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-22T20:28:39.000Z", "max_forks_repo_path": "deps/cinder/include/boost/graph/metric_tsp_approx.hpp", "max_forks_repo_name": "multi-os-engine/cinder-natj-binding", "max_forks_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 412.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T07:31:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:41:41.000Z", "avg_line_length": 37.1847133758, "max_line_length": 119, "alphanum_fraction": 0.6483384721, "num_tokens": 2577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.43661325393731587}}
{"text": "/**\n * Copyright (c) 2015\n * Jakob van Santen <jvansanten@icecube.wisc.edu>\n * and the IceCube Collaboration <http://www.icecube.wisc.edu>\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\n * $Id$\n *\n * @file Axis.cxx\n * @version $LastChangedRevision$\n * @date $Date$\n * @author Jakob van Santen\n */\n\n#include \"clsim/tabulator/Axis.h\"\n#include \"clsim/I3CLSimHelperToFloatString.h\"\n\n#include <boost/foreach.hpp>\n\n#include <cmath>\n\nnamespace clsim {\n\nnamespace tabulator {\n\nAxis::Axis(double min, double max, unsigned n_bins)\n    : min_(min), max_(max), n_bins_(n_bins)\n{}\n\nAxis::~Axis()\n{}\n\nstd::string\nAxis::GetIndexCode(const std::string &var) const {\n\t\n\tstd::ostringstream ss;\n\tdouble scale = n_bins_/(InverseTransform(max_)-InverseTransform(min_));\n\tdouble offset = scale*InverseTransform(min_);\n\n\tusing I3CLSimHelper::ToFloatString;\n\tss << \"(clamp(convert_int_sat_rtn(\"\n\t    <<ToFloatString(scale)<<\"*\"<<GetInverseTransformCode(var)\n\t    <<\" - \"<<ToFloatString(offset)\n\t    <<\"), -1, \"<<(n_bins_)<<\")+1)\";\n\t\n\treturn ss.str();\n}\n\nstd::vector<double>\nAxis::GetBinEdges() const\n{\n\tstd::vector<double> edges(GetNBins()+1);\n\n\tdouble imin = InverseTransform(GetMin());\n\tdouble imax = InverseTransform(GetMax());\n\tdouble istep = (imax-imin)/GetNBins();\n\tfor (unsigned i = 0; i <= GetNBins(); i++)\n\t\tedges[i] = Transform(imin + i*istep);\n\n\treturn edges;\n}\n\ndouble\nAxis::GetBinEdge(unsigned i) const\n{\n\tdouble imin = InverseTransform(GetMin());\n\tdouble imax = InverseTransform(GetMax());\n\tdouble istep = (imax-imin)/GetNBins();\n\treturn Transform(imin + i*istep);\n}\n\nLinearAxis::LinearAxis(double min, double max, unsigned n_bins)\n    : Axis(min, max, n_bins)\n{}\n\nLinearAxis::~LinearAxis()\n{}\n\ndouble\nLinearAxis::Transform(double value) const\n{\n\treturn value;\n}\n\ndouble\nLinearAxis::InverseTransform(double value) const\n{\n\treturn value;\n}\n\nstd::string\nLinearAxis::GetTransformCode(const std::string &var) const\n{\n\treturn var;\n}\n\nstd::string\nLinearAxis::GetInverseTransformCode(const std::string &var) const\n{\n\treturn var;\n}\n\nPowerAxis::PowerAxis(double min, double max, unsigned n_bins, unsigned power)\n    : Axis(min, max, n_bins), power_(power)\n{}\n\nPowerAxis::~PowerAxis()\n{}\n\ndouble\nPowerAxis::Transform(double value) const\n{\n\treturn std::pow(value, power_);\n}\n\ndouble\nPowerAxis::InverseTransform(double value) const\n{\n\treturn std::pow(value, 1./power_);\n}\n\nstd::string\nPowerAxis::GetTransformCode(const std::string &var) const\n{\n\tstd::ostringstream ss;\n\tif (power_ == 0) {\n\t\tss << 1;\n\t} else if (power_ < 5) {\n\t\tss << var;\n\t\tfor (unsigned i = 0; i+1 < power_; i++)\n\t\t\tss << \"*\" << var;\n\t} else {\n\t\tss << \"pow(\"<<var<<\", \"<<power_<< \")\";\n\t}\n\treturn ss.str();\n}\n\nstd::string\nPowerAxis::GetInverseTransformCode(const std::string &var) const\n{\n\tstd::ostringstream ss;\n\tswitch (power_) {\n\t\tcase 0:\n\t\t\tss << 1;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tss << var;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tss << \"sqrt(\" << var << \")\";\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tss << \"cbrt(\" << var << \")\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tss << \"pow(\" << var << \",\" << I3CLSimHelper::ToFloatString(1./power_) << \")\";\n\t}\n\treturn ss.str();\n}\n\n}\n\n}\n", "meta": {"hexsha": "c4be2d7ce74abce24bfeb25259f60276fcd45e9a", "size": 3759, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "private/clsim/tabulator/Axis.cxx", "max_stars_repo_name": "claudiok/clsim", "max_stars_repo_head_hexsha": "e1d3f4a2de21bd1bedd0b8e604b122a784f7151d", "max_stars_repo_licenses": ["ISC", "BSD-2-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-09-29T12:01:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-30T02:16:37.000Z", "max_issues_repo_path": "private/clsim/tabulator/Axis.cxx", "max_issues_repo_name": "claudiok/clsim", "max_issues_repo_head_hexsha": "e1d3f4a2de21bd1bedd0b8e604b122a784f7151d", "max_issues_repo_licenses": ["ISC", "BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2015-03-17T18:57:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-08T00:09:02.000Z", "max_forks_repo_path": "private/clsim/tabulator/Axis.cxx", "max_forks_repo_name": "claudiok/clsim", "max_forks_repo_head_hexsha": "e1d3f4a2de21bd1bedd0b8e604b122a784f7151d", "max_forks_repo_licenses": ["ISC", "BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-12-24T19:00:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T22:10:07.000Z", "avg_line_length": 21.3579545455, "max_line_length": 80, "alphanum_fraction": 0.6815642458, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4366132429424891}}
{"text": "//\n//  torus.cpp\n//\n//\n//  Created by Protoss Probe on 2017/04/09.\n//  Copyright © 2016-2017年 probe. All rights reserved.\n//\n\n#include \"poly_run.hpp\"\n#include \"poly_grav.hpp\"\n#include <boost/array.hpp>\n#include <cmath>\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass Particle {\n  public:\n    Particle() = default;\n    ~Particle() = default;\n    Particle(pos position) : r(position[0]), z(position[1]) {}\n    Particle(state_type5 state)\n        : r(state[0]), z(state[1]), r_dot(state[2]), z_dot(state[3]),\n          lam_dot(state[4]) {}\n    Particle(state_type5 state, double time)\n        : r(state[0]), z(state[1]), r_dot(state[2]), z_dot(state[3]),\n          lam_dot(state[4]), t(time) {}\n\n    double r = 0.0, z = 0.0, r_dot = 0.0, z_dot = 0.0, lam_dot = 0.0, t = 0.0;\n\n    state_type5 convert2state() const { return {r, z, r_dot, z_dot, lam_dot}; }\n    pos convert2pos() const { return {r, z}; }\n    vel convert2vel() const { return {r_dot, z_dot, lam_dot}; }\n};\n\nint main(int argc, char *argv[]) {\n    string filename(argv[1]);\n\n    PolyGrav poly(filename);\n\n    poly.init();\n    cout << poly.vert_n << '\\t' << poly.face_n << '\\t' << poly.edge_n << endl;\n    poly.principle_axes();\n    poly.export_3d_txt(\"assets/\" + filename + \"_prin.txt\", 'd');\n\n    vec3 pos;\n    double x = 1.1;\n    // double real = -1 / x;\n    // poly.co = -1 / (4. / 3. * M_PI) * 0.5;\n\n    const clock_t start = clock();\n    pos = {{x, 0, 0}};\n    // for (double i = 1.1; i < 3.0; i = i + 0.1) {\n    //     pos[0] = i;\n    //     cout << endl;\n    //     cout << setprecision(12) << -1 / i << endl;\n    //     cout << poly.potential(pos) << endl;\n    //     cout << (-1 / i - poly.potential(pos)) / (-1 / i) << endl;\n    // }\n    double value = poly.potential(pos);\n    cout << endl\n         << \"Cpu Time: \"\n         << static_cast<double>(clock() - start) / CLOCKS_PER_SEC << endl;\n    cout << endl << \"------------\" << endl;\n    // cout << \"Real : \" << real << endl;\n    cout << \"Poly Value : \" << value << endl;\n    // cout << \"Ratio : \" << real / value << endl;\n    cout << \"------------\" << endl;\n}\n", "meta": {"hexsha": "e0616558e6e06dc02d3729d89a3c5eaf55c4637b", "size": 2100, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/poly_run.cpp", "max_stars_repo_name": "ProtossProbe/poly_grav", "max_stars_repo_head_hexsha": "7d48acbfe134fb969a1f480817b5de362c9e290c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/poly_run.cpp", "max_issues_repo_name": "ProtossProbe/poly_grav", "max_issues_repo_head_hexsha": "7d48acbfe134fb969a1f480817b5de362c9e290c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-27T12:49:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-27T12:49:08.000Z", "max_forks_repo_path": "src/poly_run.cpp", "max_forks_repo_name": "ProtossProbe/poly_grav", "max_forks_repo_head_hexsha": "7d48acbfe134fb969a1f480817b5de362c9e290c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5774647887, "max_line_length": 79, "alphanum_fraction": 0.5314285714, "num_tokens": 666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.43656678601832916}}
{"text": "/* boost random/extreme_value_distribution.hpp header file\n *\n * Copyright Steven Watanabe 2010\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id: extreme_value_distribution.hpp 71018 2011-04-05 21:27:52Z steven_watanabe $\n */\n\n#ifndef BOOST_RANDOM_EXTREME_VALUE_DISTRIBUTION_HPP\n#define BOOST_RANDOM_EXTREME_VALUE_DISTRIBUTION_HPP\n\n#include <boost/config/no_tr1/cmath.hpp>\n#include <iosfwd>\n#include <istream>\n#include <boost/config.hpp>\n#include <boost/limits.hpp>\n#include <boost/random/detail/operators.hpp>\n#include <boost/random/uniform_01.hpp>\n\nnamespace boost {\nnamespace random {\n\n/**\n * The extreme value distribution is a real valued distribution with two\n * parameters a and b.\n *\n * It has \\f$\\displaystyle p(x) = \\frac{1}{b}e^{\\frac{a-x}{b} - e^\\frac{a-x}{b}}\\f$.\n */\ntemplate<class RealType = double>\nclass extreme_value_distribution {\npublic:\n    typedef RealType result_type;\n    typedef RealType input_type;\n\n    class param_type {\n    public:\n        typedef extreme_value_distribution distribution_type;\n\n        /**\n         * Constructs a @c param_type from the \"a\" and \"b\" parameters\n         * of the distribution.\n         *\n         * Requires: b > 0\n         */\n        explicit param_type(RealType a_arg = 1.0, RealType b_arg = 1.0)\n          : _a(a_arg), _b(b_arg)\n        {}\n\n        /** Returns the \"a\" parameter of the distribtuion. */\n        RealType a() const { return _a; }\n        /** Returns the \"b\" parameter of the distribution. */\n        RealType b() const { return _b; }\n\n        /** Writes a @c param_type to a @c std::ostream. */\n        BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, param_type, parm)\n        { os << parm._a << ' ' << parm._b; return os; }\n\n        /** Reads a @c param_type from a @c std::istream. */\n        BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, param_type, parm)\n        { is >> parm._a >> std::ws >> parm._b; return is; }\n\n        /** Returns true if the two sets of parameters are the same. */\n        BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(param_type, lhs, rhs)\n        { return lhs._a == rhs._a && lhs._b == rhs._b; }\n        \n        /** Returns true if the two sets of parameters are the different. */\n        BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(param_type)\n\n    private:\n        RealType _a;\n        RealType _b;\n    };\n\n    /**\n     * Constructs an @c extreme_value_distribution from its \"a\" and \"b\" parameters.\n     *\n     * Requires: b > 0\n     */\n    explicit extreme_value_distribution(RealType a_arg = 1.0, RealType b_arg = 1.0)\n      : _a(a_arg), _b(b_arg)\n    {}\n    /** Constructs an @c extreme_value_distribution from its parameters. */\n    explicit extreme_value_distribution(const param_type& parm)\n      : _a(parm.a()), _b(parm.b())\n    {}\n\n    /**\n     * Returns a random variate distributed according to the\n     * @c extreme_value_distribution.\n     */\n    template<class URNG>\n    RealType operator()(URNG& urng) const\n    {\n        using std::log;\n        return _a - log(-log(uniform_01<RealType>()(urng))) * _b;\n    }\n\n    /**\n     * Returns a random variate distributed accordint to the extreme\n     * value distribution with parameters specified by @c param.\n     */\n    template<class URNG>\n    RealType operator()(URNG& urng, const param_type& parm) const\n    {\n        return extreme_value_distribution(parm)(urng);\n    }\n\n    /** Returns the \"a\" parameter of the distribution. */\n    RealType a() const { return _a; }\n    /** Returns the \"b\" parameter of the distribution. */\n    RealType b() const { return _b; }\n\n    /** Returns the smallest value that the distribution can produce. */\n    RealType min BOOST_PREVENT_MACRO_SUBSTITUTION () const\n    { return -std::numeric_limits<RealType>::infinity(); }\n    /** Returns the largest value that the distribution can produce. */\n    RealType max BOOST_PREVENT_MACRO_SUBSTITUTION () const\n    { return std::numeric_limits<RealType>::infinity(); }\n\n    /** Returns the parameters of the distribution. */\n    param_type param() const { return param_type(_a, _b); }\n    /** Sets the parameters of the distribution. */\n    void param(const param_type& parm)\n    {\n        _a = parm.a();\n        _b = parm.b();\n    }\n\n    /**\n     * Effects: Subsequent uses of the distribution do not depend\n     * on values produced by any engine prior to invoking reset.\n     */\n    void reset() { }\n\n    /** Writes an @c extreme_value_distribution to a @c std::ostream. */\n    BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, extreme_value_distribution, wd)\n    {\n        os << wd.param();\n        return os;\n    }\n\n    /** Reads an @c extreme_value_distribution from a @c std::istream. */\n    BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, extreme_value_distribution, wd)\n    {\n        param_type parm;\n        if(is >> parm) {\n            wd.param(parm);\n        }\n        return is;\n    }\n\n    /**\n     * Returns true if the two instances of @c extreme_value_distribution will\n     * return identical sequences of values given equal generators.\n     */\n    BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(extreme_value_distribution, lhs, rhs)\n    { return lhs._a == rhs._a && lhs._b == rhs._b; }\n    \n    /**\n     * Returns true if the two instances of @c extreme_value_distribution will\n     * return different sequences of values given equal generators.\n     */\n    BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(extreme_value_distribution)\n\nprivate:\n    RealType _a;\n    RealType _b;\n};\n\n} // namespace random\n} // namespace boost\n\n#endif // BOOST_RANDOM_EXTREME_VALUE_DISTRIBUTION_HPP\n", "meta": {"hexsha": "61a65545469b03c2dd7418a7c9f40e4ff23ded65", "size": 5687, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost/boost/random/extreme_value_distribution.hpp", "max_stars_repo_name": "creatologist/openFrameworks0084", "max_stars_repo_head_hexsha": "aa74f188f105b62fbcecb7baf2b41d56d97cf7bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 130.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T23:34:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T19:22:35.000Z", "max_issues_repo_path": "Boost_1_49/boost/random/extreme_value_distribution.hpp", "max_issues_repo_name": "jjzhang166/WinUtil4", "max_issues_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2015-07-22T07:35:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T16:03:06.000Z", "max_forks_repo_path": "Boost_1_49/boost/random/extreme_value_distribution.hpp", "max_forks_repo_name": "jjzhang166/WinUtil4", "max_forks_repo_head_hexsha": "7c7b1e9bbe2fb6177bb066d74764d10711748ec5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 44.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T09:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:17.000Z", "avg_line_length": 31.9494382022, "max_line_length": 84, "alphanum_fraction": 0.6534200809, "num_tokens": 1383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4365667860183291}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n */\n\n#include <Eigen/Geometry>\n\n#include \"Tudat/Astrodynamics/Gravitation/directTidalDissipationAcceleration.h\"\n\nnamespace tudat\n{\n\nnamespace gravitation\n{\n\n//! Function to compute the acceleration acting on a satellite due to tidal deformation caused by this satellite on host planet.\nEigen::Vector3d computeDirectTidalAccelerationDueToTideOnPlanet(\n        const Eigen::Vector6d relativeStateOfBodyExertingTide, const Eigen::Vector3d planetAngularVelocityVector,\n        const double currentTidalAccelerationMultiplier, const double timeLag,\n        const bool includeDirectRadialComponent )\n{\n    Eigen::Vector3d relativePosition = relativeStateOfBodyExertingTide.segment( 0, 3 );\n    Eigen::Vector3d relativeVelocity = relativeStateOfBodyExertingTide.segment( 3, 3 );\n\n    double distance = relativePosition.norm( );\n    double distanceSquared = distance * distance;\n    double radialComponentMultiplier = ( includeDirectRadialComponent == true ) ? 1.0 : 0.0;\n\n    return currentTidalAccelerationMultiplier * (\n                 radialComponentMultiplier * relativePosition + timeLag * (\n                    2.0 * ( relativePosition.dot( relativeVelocity ) * relativePosition / distanceSquared ) +\n                    ( relativePosition.cross( planetAngularVelocityVector ) + relativeVelocity ) ) );\n\n}\n\n//! Function to compute the acceleration acting on a satellite due to tidal deformation caused in this satellite by host planet.\nEigen::Vector3d computeDirectTidalAccelerationDueToTideOnSatellite(\n        const Eigen::Vector6d relativeStateOfBodyExertingTide,\n        const double currentTidalAccelerationMultiplier,\n        const double timeLag,const bool includeDirectRadialComponent )\n{\n    Eigen::Vector3d relativePosition = relativeStateOfBodyExertingTide.segment( 0, 3 );\n    Eigen::Vector3d relativeVelocity = relativeStateOfBodyExertingTide.segment( 3, 3 );\n\n    double distance = relativePosition.norm( );\n    double distanceSquared = distance * distance;\n    double radialComponentMultiplier = ( includeDirectRadialComponent == true ) ? 1.0 : 0.0;\n\n    return currentTidalAccelerationMultiplier * (\n                 2.0 * radialComponentMultiplier * relativePosition + timeLag * (\n                   7.0 * relativePosition.dot( relativeVelocity ) * relativePosition / distanceSquared ) );\n\n}\n\n//! Function to retrieve all DirectTidalDissipationAcceleration from an AccelerationMap, for specific deformed/deforming bodies\nstd::vector< std::shared_ptr< DirectTidalDissipationAcceleration > > getTidalDissipationAccelerationModels(\n        const basic_astrodynamics::AccelerationMap accelerationModelList, const std::string bodyBeingDeformed,\n        const std::vector< std::string >& bodiesCausingDeformation )\n{\n    // Iterate over all bodies undergoing acceleration\n    std::vector< std::shared_ptr< DirectTidalDissipationAcceleration > > selectedDissipationModels;\n    for( basic_astrodynamics::AccelerationMap::const_iterator modelIterator1 = accelerationModelList.begin( );\n         modelIterator1 != accelerationModelList.end( ); modelIterator1++ )\n    {\n        std::string bodyUndergoingAcceleration = modelIterator1->first;\n\n        // Iterate over all bodies exerting acceleration\n        basic_astrodynamics::SingleBodyAccelerationMap singleBodyAccelerationList = modelIterator1->second;\n        for( basic_astrodynamics::SingleBodyAccelerationMap::const_iterator modelIterator2 = singleBodyAccelerationList.begin( );\n             modelIterator2 != singleBodyAccelerationList.end( ); modelIterator2++ )\n        {\n            std::string bodyExertingAcceleration = modelIterator2->first;\n\n            // Iterate over all accelerations being exerted by bodyExertingAcceleration on bodyUndergoingAcceleration\n            for( unsigned int i = 0; i < modelIterator2->second.size( ); i++ )\n            {\n                // Check if acceleration model is due to tidal dissipations\n                std::shared_ptr< DirectTidalDissipationAcceleration > currentDissipationAcceleration =\n                    std::dynamic_pointer_cast< DirectTidalDissipationAcceleration >( modelIterator2->second.at( i ) );\n                if( currentDissipationAcceleration != nullptr )\n                {\n                    // Check whether model correspionds to input requirements\n                    if( currentDissipationAcceleration->getModelTideOnPlanet( ) &&\n                            ( bodyExertingAcceleration == bodyBeingDeformed ) )\n                    {\n                        if( ( std::find( bodiesCausingDeformation.begin( ), bodiesCausingDeformation.end( ),\n                                       bodyUndergoingAcceleration ) != bodiesCausingDeformation.end( ) ) ||\n                                bodiesCausingDeformation.size( ) == 0 )\n                        {\n                            selectedDissipationModels.push_back( currentDissipationAcceleration );\n                        }\n                    }\n                    else if( !currentDissipationAcceleration->getModelTideOnPlanet( ) &&\n                             ( bodyUndergoingAcceleration == bodyBeingDeformed ) )\n                    {\n                        if( ( std::find( bodiesCausingDeformation.begin( ), bodiesCausingDeformation.end( ),\n                                       bodyExertingAcceleration ) != bodiesCausingDeformation.end( ) ) ||\n                                bodiesCausingDeformation.size( ) == 0 )\n                        {\n                            selectedDissipationModels.push_back( currentDissipationAcceleration );\n                        }\n                    }\n                }\n            }\n        }\n    }\n    return selectedDissipationModels;\n}\n\n\n} // namespace gravitation\n\n} // namespace tudat\n", "meta": {"hexsha": "6090bbdcd05c9f93490e1a57796e3fb89461db16", "size": 6152, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Gravitation/directTidalDissipationAcceleration.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Gravitation/directTidalDissipationAcceleration.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Gravitation/directTidalDissipationAcceleration.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.2666666667, "max_line_length": 129, "alphanum_fraction": 0.6736020806, "num_tokens": 1281, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.43639916904936205}}
{"text": "\n#include \"coord.h\"\n\n#include \"adler32.h\"\n#include \"composite-imp.h\"\n#include \"float.h\"\n\n#include <boost/static_assert.hpp>\n\nusing namespace std;\n\nclass Coords {\npublic:\n  typedef Coord T1;\n  typedef Coord2 T2;\n  typedef Coord4 T4;\n  \n  static Coord atan2(Coord a, Coord b) { return Coord(float(::atan2(a.toFloat(), b.toFloat()))); }\n  static Coord sin(Coord a) { return cfsin(a); };\n  static Coord cos(Coord a) { return cfcos(a); };\n  \n  static const Coord tPI;\n};\nconst Coord Coords::tPI = COORDPI;\n\nstring Coord::rawstr() const {\n  return StringPrintf(\"%08x%08x\", (unsigned int)(d >> 32), (unsigned int)d);\n}\n\nCoord coordFromRawstr(const string &lhs) {\n  if(lhs.size() != 16) {\n    dprintf(\"%s\\n\", lhs.c_str());\n    CHECK(lhs.size() == 16);\n  }\n  for(int i = 0; i < lhs.size(); i++)\n    CHECK(isdigit(lhs[i]) || (lhs[i] >= 'a' && lhs[i] <= 'f'));\n  long long dd = 0;\n  for(int i = 0; i < 16; i++) {\n    dd *= 16;\n    if(isdigit(lhs[i]))\n      dd += lhs[i] - '0';\n    else\n      dd += lhs[i] - 'a' + 10;\n  }\n  CHECK(coordExplicit(dd).rawstr() == lhs);\n  return coordExplicit(dd);\n}\n\nFloat2 Coord2::toFloat() const { return Float2(x.toFloat(), y.toFloat()); }\nCoord2::Coord2(const Float2 &rhs) : x(rhs.x), y(rhs.y) { };\nstring Coord2::rawstr() const {\n  return StringPrintf(\"%s %s\", x.rawstr().c_str(), y.rawstr().c_str());\n}\n\nFloat4 Coord4::toFloat() const { return Float4(sx.toFloat(), sy.toFloat(), ex.toFloat(), ey.toFloat()); }\nstring Coord4::rawstr() const {\n  return StringPrintf(\"%s %s %s %s\", sx.rawstr().c_str(), sy.rawstr().c_str(), ex.rawstr().c_str(), ey.rawstr().c_str());\n}\n\nCoord4::Coord4(const Float4 &rhs) : sx(rhs.sx), sy(rhs.sy), ex(rhs.ex), ey(rhs.ey) { }\n\n/*************\n * Computational geometry\n */\n\nCoord len(const Coord2 &in) { return Coord(len(in.toFloat())); };\nCoord2 normalize(const Coord2 &in) { return imp_normalize<Coords>(in); };\nCoord dot(const Coord2 &lhs, const Coord2 &rhs) { return lhs.x * rhs.x + lhs.y * rhs.y; };\n\nCoord getAngle(const Coord2 &in) { return imp_getAngle<Coords>(in); };\nCoord2 makeAngle(const Coord &in) { return imp_makeAngle<Coords>(in); };\n\nint whichSide(const Coord4 &f4, const Coord2 &pta) { return imp_whichSide<Coords>(f4, pta); };\n\nCoord distanceFromLine(const Coord4 &line, const Coord2 &pt) {\n  Coord u = ((pt.x - line.sx) * (line.ex - line.sx) + (pt.y - line.sy) * (line.ey - line.sy)) / ((line.ex - line.sx) * (line.ex - line.sx) + (line.ey - line.sy) * (line.ey - line.sy));\n  if(u < 0 || u > 1)\n    return min(len(pt - Coord2(line.sx, line.sy)), len(pt - Coord2(line.ex, line.ey)));\n  Coord2 ipt = Coord2(line.sx, line.sy) + Coord2(line.ex - line.sx, line.ey - line.sy) * u;\n  return len(ipt - pt);\n}\n\nint inPath(const Coord2 &point, const vector<Coord2> &path) {\n  return imp_inPath<Coords>(point, path);\n};\n\nbool roughInPath(const Coord2 &point, const vector<Coord2> &path, int goal) {\n  int dx[] = {0, 0, 0, 1, -1, 1, 1, -1, -1};\n  int dy[] = {0, 1, -1, 0, 0, 1, -1, 1, -1};\n  for(int i = 0; i < 9; i++)\n    if((bool)inPath(point + Coord2(dx[i], dy[i]) / 65536, path) == goal)\n      return true;\n  return false;\n}\n\nCoord2 getPointIn(const vector<Coord2> &path) {\n  // TODO: find a point inside the polygon in a better fashion\n  //GetDifferenceHandler CrashHandler(path, path);\n  Coord2 pt;\n  bool found = false;\n  for(int j = 0; j < path.size() && !found; j++) {\n    Coord2 pospt = (path[j] + path[(j + 1) % path.size()] + path[(j + 2) % path.size()]) / 3;\n    if(inPath(pospt, path)) {\n      pt = pospt;\n      found = true;\n    }\n  }\n  CHECK(found);\n  return pt;\n}\n\nbool pathReversed(const vector<Coord2> &path) {\n  return imp_pathReversed<Coords>(path);\n}\n\nint getPathRelation(const vector<Coord2> &lhs, const vector<Coord2> &rhs) {\n  for(int i = 0; i < lhs.size(); i++) {\n    int i2 = (i + 1) % lhs.size();\n    for(int j = 0; j < rhs.size(); j++) {\n      int j2 = (j + 1) % rhs.size();\n      if(linelineintersect(Coord4(lhs[i], lhs[i2]), Coord4(rhs[j], rhs[j2])))\n        return PR_INTERSECT;\n    }\n  }\n  bool lir = inPath(getPointIn(lhs), rhs);\n  bool ril = inPath(getPointIn(rhs), lhs);\n  if(!lir && !ril) {\n    return PR_SEPARATE;\n  } else if(lir && !ril) {\n    return PR_RHSENCLOSE;\n  } else if(!lir && ril) {\n    return PR_LHSENCLOSE;\n  } else if(lir && ril && abs(getArea(lhs)) < abs(getArea(rhs))) {\n    return PR_RHSENCLOSE;\n  } else if(lir && ril && abs(getArea(lhs)) > abs(getArea(rhs))) {\n    return PR_LHSENCLOSE;\n  } else {\n    // dammit, don't send the same two paths! we deny!\n    CHECK(0);\n  }\n}\n\nCoord getArea(const vector<Coord2> &are) { return imp_getArea<Coords>(are); }\nCoord2 getCentroid(const vector<Coord2> &are) { return imp_getCentroid<Coords>(are); }\nCoord getPerimeter(const vector<Coord2> &are) {\n  Coord totperi = 0;\n  for(int i = 0; i < are.size(); i++) {\n    int j = (i + 1) % are.size();\n    totperi += len(are[i] - are[j]);\n  }\n  return totperi;\n}\nCoord4 getBoundBox(const vector<Coord2> &are) {\n  Coord4 bbox = startCBoundBox();\n  for(int i = 0; i < are.size(); i++)\n    addToBoundBox(&bbox, are[i]);\n  CHECK(bbox.isNormalized());\n  return bbox;\n}\n\nbool colinear(const Coord4 &line, const Coord2 &pt) {\n  Coord koord = distanceFromLine(line, pt);\n  return koord < Coord(0.00001f);\n}\n\nCoord2 reflect(const Coord2 &incoming, Coord normal) {\n  return imp_reflect<Coords>(incoming, normal);\n}\nCoord reflect(Coord incoming, Coord normal) {\n  return imp_reflect<Coords>(incoming, normal);\n}\n\nCoord ang_dist(Coord lhs, Coord rhs) {\n  lhs = mod(lhs, COORDPI * 2);\n  rhs = mod(rhs, COORDPI * 2);\n  Coord v = abs(lhs - rhs);\n  if(v > COORDPI)\n    return COORDPI * 2 - v;\n  else\n    return v;\n}\nCoord ang_approach(const Coord &cur, const Coord &goal, const Coord &amount) {\n  Coord jcur = mod(cur, COORDPI * 2);\n  Coord jgoal = mod(goal, COORDPI * 2);\n  if(abs(jcur - jgoal) > abs(jcur - (jgoal - COORDPI * 2))) {\n    jgoal -= COORDPI * 2;\n  } else if(abs(jcur - jgoal) > abs(jcur - (jgoal + COORDPI * 2))) {\n    jgoal += COORDPI * 2;\n  }\n  CHECK(ang_dist(cur, goal) >= ang_dist(approach(jcur, jgoal, amount), goal));\n  return approach(jcur, jgoal, amount);\n}\n\n/*************\n * Bounding box\n */\n\nCoord4 startCBoundBox() { return imp_startBoundBox<Coords>(); };\n\nvoid addToBoundBox(Coord4 *bbox, const Coord4 &rect) { return imp_addToBoundBox<Coords>(bbox, rect); };\nvoid addToBoundBox(Coord4 *bbox, const vector<Coord2> &line) { return imp_addToBoundBox<Coords>(bbox, line); };\n\nvoid expandBoundBox(Coord4 *bbox, Coord factor) { return imp_expandBoundBox<Coords>(bbox, factor); };\n\n/*************\n * Math\n */\n\nbool linelineintersect(const Coord4 &lhs, const Coord4 &rhs) { return imp_linelineintersect<Coords>(lhs, rhs); };\nCoord linelineintersectpos(const Coord4 &lhs, const Coord4 &rhs) { return imp_linelineintersectpos<Coords>(lhs, rhs); };\n\nCoord approach(Coord start, Coord target, Coord delta, Coord drag) {\n  if(!(((start < 0) == (target < 0)) && start < target))\n    delta += drag;\n  return approach(start, target, delta);\n}\nCoord2 approach(Coord2 start, Coord2 target, Coord delta) {\n  CHECK(delta >= 0);\n  Coord2 diff = target - start;\n  if(len(diff) <= delta)\n    return target;\n  return start + diff / len(diff) * delta;\n}\nCoord2 approach(Coord2 start, Coord2 target, Coord delta, Coord drag) {\n  if(target == start)\n    return target;\n  if(len(start) == 0)\n    return approach(start, target, delta);\n  return approach(start, target, delta + drag * max(Coord(0), -dot(normalize(start), normalize(target - start))));\n}\n\nCoord2 rotate(const Coord2 &in, Coord ang) {\n  return imp_rotate<Coords>(in, ang);\n}\n\nCoord mod(const Coord &a, const Coord &b) {\n  if(a < Coord(0))\n    return b - mod(-a, b);\n  return coordExplicit(a.d % b.d);\n}\n\nCoord2 lerp(const Coord2 &lhs, const Coord2 &rhs, Coord dist) {\n  return lhs + (rhs - lhs) * dist;\n}\nCoord2 lerp(const Coord4 &movement, Coord dist) {\n  return lerp(movement.s(), movement.e(), dist);\n}\nCoord4 lerp(const Coord4 &lhs, const Coord4 &rhs, Coord dist) {\n  return lhs + (rhs - lhs) * dist;\n}\n\nBOOST_STATIC_ASSERT(sizeof(Coord) == 8);\nBOOST_STATIC_ASSERT(sizeof(Coord2) == 16);\nBOOST_STATIC_ASSERT(sizeof(Coord4) == 32);\n\nvoid adler(Adler32 *adl, const Coord &val) { adl->addBytes(&val, sizeof(val)); }\nvoid adler(Adler32 *adl, const Coord2 &val) { adl->addBytes(&val, sizeof(val)); }\nvoid adler(Adler32 *adl, const Coord4 &val) { adl->addBytes(&val, sizeof(val)); }\nvoid adler(Adler32 *adl, const CPosInfo &val) {\n  adler(adl, val.pos);\n  adler(adl, val.d);\n}\n", "meta": {"hexsha": "39db35004586d8ffade224410ba1f674c70e2174", "size": 8420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "coord.cpp", "max_stars_repo_name": "zorbathut/d-net", "max_stars_repo_head_hexsha": "61f610ca71270c6a95cf57dc3acaeab8559a234b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-02T06:47:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-02T06:47:52.000Z", "max_issues_repo_path": "coord.cpp", "max_issues_repo_name": "zorbathut/d-net", "max_issues_repo_head_hexsha": "61f610ca71270c6a95cf57dc3acaeab8559a234b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coord.cpp", "max_forks_repo_name": "zorbathut/d-net", "max_forks_repo_head_hexsha": "61f610ca71270c6a95cf57dc3acaeab8559a234b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0152091255, "max_line_length": 184, "alphanum_fraction": 0.6334916865, "num_tokens": 2683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4363991637999142}}
{"text": "//\n// Created by Hamza El-Kebir on 4/21/21.\n//\n\n#ifndef LODESTAR_DISCRETESYSTEM_HPP\n#define LODESTAR_DISCRETESYSTEM_HPP\n\n#include <Eigen/Dense>\n#include \"StateSpace.hpp\"\n#include \"SystemStateful.hpp\"\n#include \"Lodestar/aux/CompileTimeQualifiers.hpp\"\n\nnamespace ls {\n    namespace systems {\n        template<class SYS>\n        class DiscreteSystem : public SystemStateful {\n        public:\n            typedef SYS TDSystem;\n            DiscreteSystem() : system(new SYS), state(new Eigen::VectorXd),\n                               input(\n                                       nullptr), time(0)\n            {}\n\n            DiscreteSystem(SYS *sys) : system(sys), state(new Eigen::VectorXd),\n                                       input(nullptr), time(0)\n            {}\n\n            void advance();\n\n//            void advance(void *control);\n\n            void advanceFree();\n\n            void advanceForced();\n\n//            void advanceForced(void *control);\n\n            SYS *system;\n            void *state;\n            void *input;\n\n            double time;\n        };\n\n        template <template <typename, const int, const int, const int> class TSystem, typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\n        class DiscreteSystem<TSystem<TScalar, TStateDim, TInputDim, TOutputDim>>;\n\n        template <typename TScalar, const int TStateDim, const int TInputDim, const int TOutputDim>\n        class DiscreteSystem<StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>> {\n        public:\n            typedef StateSpace<TScalar, TStateDim, TInputDim, TOutputDim> TDSystem;\n            typedef Eigen::Matrix<TScalar, TStateDim, LS_STATIC_UNLESS_DYNAMIC_VAL(TStateDim, 1)> TDStateVector;\n            typedef Eigen::Matrix<TScalar, TInputDim, LS_STATIC_UNLESS_DYNAMIC_VAL(TInputDim, 1)> TDInputVector;\n\n            DiscreteSystem() : system(new TDSystem), state(new TDStateVector),\n                               input(nullptr), time(0)\n            {}\n\n            DiscreteSystem(TDSystem *sys) : system(sys), state(new TDStateVector),\n                                       input(nullptr), time(0)\n            {}\n\n            IF_DYNAMIC_RETURN(TStateDim, TInputDim, TOutputDim, void)\n            initialize() {\n                state->conservativeResize(system->getA().rows());\n\n                if (input == nullptr)\n                    input = new Eigen::VectorXd;\n\n                input->conservativeResize(system->getB().cols());\n            }\n\n            IF_STATIC_RETURN(TStateDim, TInputDim, TOutputDim, void)\n            initialize() {\n                // NOTE: No action since no memory may be allocated.\n                return;\n            }\n\n            void advance();\n\n            void advance(TDInputVector *control);\n\n            void advanceFree();\n\n            void advanceForced();\n\n            void advanceForced(TDInputVector *control);\n\n            TDSystem *system;\n            TDStateVector *state;\n            TDInputVector *input;\n\n            double time;\n        };\n    }\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::DiscreteSystem<ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>>::advance()\n{\n    if (input != nullptr) {\n        *state = (*system->getA()) * (*state) + (*system->getB()) * (*input);\n    } else {\n        *state = (*system->getA()) * (*state);\n    }\n\n    time += system->getSamplingPeriod();\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::DiscreteSystem<ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>>::advance(\n        Eigen::Matrix<TScalar, TInputDim, Kmax2(-1, TInputDim, 1)> *control)\n{\n    *state = (*system->getA()) * (*state) + (*system->getB()) * (*control);\n\n    time = system->getSamplingPeriod();\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::DiscreteSystem<ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>>::advanceFree()\n{\n    *state = (*system->getA()) * (*state);\n\n    time += system->getSamplingPeriod();\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::DiscreteSystem<ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>>::advanceForced()\n{\n    *state = (*system->getA()) * (*state) + (*system->getB()) * (*input);\n\n    time += system->getSamplingPeriod();\n}\n\ntemplate<typename TScalar, int TStateDim, int TInputDim, int TOutputDim>\nvoid ls::systems::DiscreteSystem<ls::systems::StateSpace<TScalar, TStateDim, TInputDim, TOutputDim>>::advanceForced(\n        Eigen::Matrix<TScalar, TInputDim, Kmax2(-1, TInputDim, 1)> *control)\n{\n    *state = (*system->getA()) * (*state) + (*system->getB()) * (*control);\n\n    time += system->getSamplingPeriod();\n}\n\n#endif //LODESTAR_DISCRETESYSTEM_HPP\n", "meta": {"hexsha": "c5e27593abdd9eff531a4616e0353fe0c3abb771", "size": 4840, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/systems/DiscreteSystem.hpp", "max_stars_repo_name": "helkebir/Lodestar", "max_stars_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T14:08:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T22:15:31.000Z", "max_issues_repo_path": "Lodestar/systems/DiscreteSystem.hpp", "max_issues_repo_name": "helkebir/Lodestar", "max_issues_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T15:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T17:43:20.000Z", "max_forks_repo_path": "Lodestar/systems/DiscreteSystem.hpp", "max_forks_repo_name": "helkebir/Lodestar", "max_forks_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T03:15:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T03:15:23.000Z", "avg_line_length": 33.3793103448, "max_line_length": 167, "alphanum_fraction": 0.6064049587, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.43636885505561884}}
{"text": "#include \"math-dsp.h\"\n#include <speex/speex_resampler.h>\n#include <boost/scope_exit.hpp>\n#include <algorithm>\n#include <stdexcept>\n#include <cmath>\n\ndouble tukey_window(double a, double x) {\n  if (x < a / 2) {\n    return (1.0 + std::cos(M_PI * (2.0 * x / a - 1.0))) / 2.0;\n  } else if (x > 1.0 - a / 2) {\n    return (1.0 + std::cos(M_PI * (2.0 * (x - 1.0) / a + 1.0))) / 2.0;\n  } else {\n    return 1.0;\n  }\n}\n\nvoid resample(const float *in_samples,\n              unsigned in_sample_count,\n              float *out_samples,\n              unsigned out_sample_count) {\n  if (in_sample_count == 0) {\n    std::fill(out_samples, out_samples + out_sample_count, 0.0f);\n    return;\n  }\n\n  int err {};\n\n  SpeexResamplerState *resampler = speex_resampler_init(\n    1, in_sample_count, out_sample_count, SPEEX_RESAMPLER_QUALITY_MAX, &err);\n\n  if (!resampler) {\n    const char *errmsg = speex_resampler_strerror(err);\n    throw std::runtime_error(std::string(\"speex_resampler_init: \") + errmsg);\n  }\n\n  BOOST_SCOPE_EXIT(resampler) {\n    speex_resampler_destroy(resampler);\n  } BOOST_SCOPE_EXIT_END;\n\n  speex_resampler_skip_zeros(resampler);\n\n  while (out_sample_count > 0) {\n    unsigned in_count = in_sample_count;\n    unsigned out_count = out_sample_count;\n    speex_resampler_process_float(\n      resampler, 0, in_samples, &in_count, out_samples, &out_count);\n    in_samples += in_count;\n    in_sample_count -= in_count;\n    out_samples += out_count;\n    out_sample_count -= out_count;\n    if (out_count == 0)\n      break;\n  }\n\n  static const unsigned nzeros = 32;\n  static const float zero[nzeros] {};\n\n  while (out_sample_count > 0) {\n    unsigned in_count = nzeros;\n    unsigned out_count = out_sample_count;\n    speex_resampler_process_float(\n      resampler, 0, zero, &in_count, out_samples, &out_count);\n    out_samples += out_count;\n    out_sample_count -= out_count;\n  }\n}\n", "meta": {"hexsha": "4c586ae52333b6baa8cd0eb02dda7144f15a14c4", "size": 1872, "ext": "cc", "lang": "C++", "max_stars_repo_path": "sources/math-dsp.cc", "max_stars_repo_name": "jpcima/dessiner-un-son", "max_stars_repo_head_hexsha": "eea2eb92d82c3356061d64335e2433da0f8c6a92", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-05-15T05:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-29T10:22:12.000Z", "max_issues_repo_path": "sources/math-dsp.cc", "max_issues_repo_name": "jpcima/dessiner-un-son", "max_issues_repo_head_hexsha": "eea2eb92d82c3356061d64335e2433da0f8c6a92", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-05-15T18:44:39.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-19T13:14:26.000Z", "max_forks_repo_path": "sources/math-dsp.cc", "max_forks_repo_name": "jpcima/dessiner-un-son", "max_forks_repo_head_hexsha": "eea2eb92d82c3356061d64335e2433da0f8c6a92", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5294117647, "max_line_length": 77, "alphanum_fraction": 0.6634615385, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.436229624017616}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl\n Copyright (C) 2006 François du Vignaud\n Copyright (C) 2006, 2008 Ferdinando Ametrano\n Copyright (C) 2015 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file swaptionvolmatrix.hpp\n    \\brief Swaption at-the-money volatility matrix\n*/\n\n#ifndef quantlib_swaption_volatility_matrix_hpp\n#define quantlib_swaption_volatility_matrix_hpp\n\n#include <ql/termstructures/volatility/swaption/swaptionvoldiscrete.hpp>\n#include <ql/math/interpolations/interpolation2d.hpp>\n#include <ql/math/matrix.hpp>\n#include <boost/noncopyable.hpp>\n#include <vector>\n\nnamespace QuantLib {\n\n    class Quote;\n\n    //! At-the-money swaption-volatility matrix\n    /*! This class provides the at-the-money volatility for a given\n        swaption by interpolating a volatility matrix whose elements\n        are the market volatilities of a set of swaption with given\n        option date and swapLength.\n\n        The volatility matrix <tt>M</tt> must be defined so that:\n        - the number of rows equals the number of option dates;\n        - the number of columns equals the number of swap tenors;\n        - <tt>M[i][j]</tt> contains the volatility corresponding\n          to the <tt>i</tt>-th option and <tt>j</tt>-th tenor.\n    */\n    class SwaptionVolatilityMatrix : public SwaptionVolatilityDiscrete,\n                                     private boost::noncopyable {\n      public:\n        //! floating reference date, floating market data\n        SwaptionVolatilityMatrix(\n                    const Calendar& calendar,\n                    BusinessDayConvention bdc,\n                    const std::vector<Period>& optionTenors,\n                    const std::vector<Period>& swapTenors,\n                    const std::vector<std::vector<Handle<Quote> > >& vols,\n                    const DayCounter& dayCounter,\n                    const bool flatExtrapolation = false,\n                    const VolatilityType type = ShiftedLognormal,\n                    const std::vector<std::vector<Real> >& shifts\n                    = std::vector<std::vector<Real> >());\n        //! fixed reference date, floating market data\n        SwaptionVolatilityMatrix(\n                    const Date& referenceDate,\n                    const Calendar& calendar,\n                    BusinessDayConvention bdc,\n                    const std::vector<Period>& optionTenors,\n                    const std::vector<Period>& swapTenors,\n                    const std::vector<std::vector<Handle<Quote> > >& vols,\n                    const DayCounter& dayCounter,\n                    const bool flatExtrapolation = false,\n                    const VolatilityType type = ShiftedLognormal,\n                    const std::vector<std::vector<Real> >& shifts\n                    = std::vector<std::vector<Real> >());\n        //! floating reference date, fixed market data\n        SwaptionVolatilityMatrix(\n                    const Calendar& calendar,\n                    BusinessDayConvention bdc,\n                    const std::vector<Period>& optionTenors,\n                    const std::vector<Period>& swapTenors,\n                    const Matrix& volatilities,\n                    const DayCounter& dayCounter,\n                    const bool flatExtrapolation = false,\n                    const VolatilityType type = ShiftedLognormal,\n                    const Matrix& shifts = Matrix());\n        //! fixed reference date, fixed market data\n        SwaptionVolatilityMatrix(\n                    const Date& referenceDate,\n                    const Calendar& calendar,\n                    BusinessDayConvention bdc,\n                    const std::vector<Period>& optionTenors,\n                    const std::vector<Period>& swapTenors,\n                    const Matrix& volatilities,\n                    const DayCounter& dayCounter,\n                    const bool flatExtrapolation = false,\n                    const VolatilityType type = ShiftedLognormal,\n                    const Matrix& shifts = Matrix());\n        // fixed reference date and fixed market data, option dates\n        SwaptionVolatilityMatrix(const Date& referenceDate,\n                                 const std::vector<Date>& optionDates,\n                                 const std::vector<Period>& swapTenors,\n                                 const Matrix& volatilities,\n                                 const DayCounter& dayCounter,\n                                 const bool flatExtrapolation = false,\n                                 const VolatilityType type = ShiftedLognormal,\n                                 const Matrix& shifts = Matrix());\n\n        //! \\name LazyObject interface\n        //@{\n        void performCalculations() const;\n        //@}\n        //! \\name TermStructure interface\n        //@{\n        Date maxDate() const;\n        //@}\n        //! \\name VolatilityTermStructure interface\n        //@{\n        Rate minStrike() const;\n        Rate maxStrike() const;\n        //@}\n        //! \\name SwaptionVolatilityStructure interface\n        //@{\n        const Period& maxSwapTenor() const;\n        //@}\n        //! \\name Other inspectors\n        //@{\n        //! returns the lower indexes of surrounding volatility matrix corners\n        std::pair<Size,Size> locate(const Date& optionDate,\n                                    const Period& swapTenor) const {\n            return locate(timeFromReference(optionDate),\n                          swapLength(swapTenor));\n        }\n        //! returns the lower indexes of surrounding volatility matrix corners\n        std::pair<Size,Size> locate(Time optionTime,\n                                    Time swapLength) const {\n            return std::make_pair(interpolation_.locateY(optionTime),\n                                  interpolation_.locateX(swapLength));\n        }\n        //@}\n        VolatilityType volatilityType() const;\n      protected:\n        // defining the following method would break CMS test suite\n        // to be further investigated\n        //ext::shared_ptr<SmileSection> smileSectionImpl(const Date&,\n        //                                                 const Period&) const;\n        ext::shared_ptr<SmileSection> smileSectionImpl(Time,\n                                                         Time) const;\n        Volatility volatilityImpl(Time optionTime,\n                                  Time swapLength,\n                                  Rate strike) const;\n        Real shiftImpl(Time optionTime, Time swapLength) const;\n      private:\n        void checkInputs(Size volRows,\n                         Size volsColumns,\n                         Size shiftRows,\n                         Size shiftsColumns) const;\n        void registerWithMarketData();\n        std::vector<std::vector<Handle<Quote> > > volHandles_;\n        std::vector<std::vector<Real> > shiftValues_;\n        mutable Matrix volatilities_, shifts_;\n        Interpolation2D interpolation_, interpolationShifts_;\n        VolatilityType volatilityType_;\n    };\n\n    // inline definitions\n\n    inline Date SwaptionVolatilityMatrix::maxDate() const {\n        return optionDates_.back();\n    }\n\n    inline Rate SwaptionVolatilityMatrix::minStrike() const {\n        return -QL_MAX_REAL;\n    }\n\n    inline Rate SwaptionVolatilityMatrix::maxStrike() const {\n        return QL_MAX_REAL;\n    }\n\n    inline const Period& SwaptionVolatilityMatrix::maxSwapTenor() const {\n        return swapTenors_.back();\n    }\n\n    inline Volatility SwaptionVolatilityMatrix::volatilityImpl(Time optionTime,\n                                                               Time swapLength,\n                                                               Rate) const {\n        calculate();\n        return interpolation_(swapLength, optionTime, true);\n    }\n\n    inline VolatilityType SwaptionVolatilityMatrix::volatilityType() const {\n        return volatilityType_;\n    }\n\n    inline Real SwaptionVolatilityMatrix::shiftImpl(Time optionTime,\n                                                    Time swapLength) const {\n        calculate();\n        Real tmp = interpolationShifts_(swapLength, optionTime, true);\n        return tmp;\n    }\n} // namespace QuantLib\n\n#endif\n", "meta": {"hexsha": "c823e0489b739c55129d216acf17fccd490807c7", "size": 8912, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/termstructures/volatility/swaption/swaptionvolmatrix.hpp", "max_stars_repo_name": "akshett/QuantLib", "max_stars_repo_head_hexsha": "eb02391a1c79009c0f1ba6ef235a424bed60c576", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-20T10:58:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T10:58:37.000Z", "max_issues_repo_path": "ql/termstructures/volatility/swaption/swaptionvolmatrix.hpp", "max_issues_repo_name": "akshett/QuantLib", "max_issues_repo_head_hexsha": "eb02391a1c79009c0f1ba6ef235a424bed60c576", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/termstructures/volatility/swaption/swaptionvolmatrix.hpp", "max_forks_repo_name": "akshett/QuantLib", "max_forks_repo_head_hexsha": "eb02391a1c79009c0f1ba6ef235a424bed60c576", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T02:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T02:04:10.000Z", "avg_line_length": 42.8461538462, "max_line_length": 80, "alphanum_fraction": 0.5805655296, "num_tokens": 1737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.436229624017616}}
{"text": "#include \"integrator.h\"\n#include \"biorbd.h\"\n\n#include <boost/numeric/odeint.hpp>\n#include \"dynamics.h\"\n\nAcadoIntegrator::AcadoIntegrator(biorbd::Model& m) :\n    biorbd::rigidbody::Integrator(m),\n    m_isKinematicsComputed(false),\n    m_nMus(m.nbMuscleTotal()),\n    m_nTorque(m.nbGeneralizedTorque())\n{\n    m_lhs = new double[m_model->nbQ() + m_model->nbQdot()\n            + m_nMus + m_nTorque];\n    m_rhs = new double[m_model->nbQ() + m_model->nbQdot()];\n}\n\n\nvoid AcadoIntegrator::operator()(\n        const state_type &x,\n        state_type &dxdt,\n        double)\n{\n    for (unsigned int i=0; i<*m_nQ + *m_nQdot; i++){\n        m_lhs[i] = x[i];\n    }\n    for (unsigned int i=0; i<m_nMus + m_nTorque; ++i){\n        m_lhs[i + *m_nQ + *m_nQdot] = (*m_u)(i);\n    }\n\n    // Équation différentielle : x/xdot => xdot/xddot\n    forwardDynamics_contact(m_lhs, m_rhs);\n\n    // Faire sortir xdot/xddot\n    for (unsigned int i=0; i<*m_nQ + *m_nQdot; i++){\n        dxdt[i] = m_rhs[i];\n    }\n\n}\n\nvoid AcadoIntegrator::integrateKinematics(\n        const biorbd::rigidbody::GeneralizedCoordinates &Q,\n        const biorbd::rigidbody::GeneralizedCoordinates &QDot,\n        const biorbd::utils::Vector &control,\n        double t0,\n        double tend,\n        double timeStep)\n{\n    biorbd::utils::Vector v(static_cast<unsigned int>(Q.rows()+QDot.rows()));\n    v << Q,QDot;\n    integrate(v, control, t0, tend, timeStep); // vecteur, t0, tend, pas, effecteurs\n    m_isKinematicsComputed = true;\n}\n\nvoid AcadoIntegrator::getIntegratedKinematics(\n        unsigned int step,\n        biorbd::rigidbody::GeneralizedCoordinates &Q,\n        biorbd::rigidbody::GeneralizedCoordinates &QDot)\n{\n    // Si la cinématique n'a pas été mise à jour\n    biorbd::utils::Error::check(\n                m_isKinematicsComputed,\n                \"ComputeKinematics must be call before calling updateKinematics\");\n    const biorbd::utils::Vector& tp(getX(step));\n    for (unsigned int i=0; i< static_cast<unsigned int>(tp.rows()/2); i++){\n        Q(i) = tp(i);\n        QDot(i) = tp(i+tp.rows()/2);\n    }\n}\nunsigned int AcadoIntegrator::nbInterationStep() const\n{\n    return steps();\n}\n\nvoid AcadoIntegrator::launchIntegrate(\n        state_type &x,\n        double t0,\n        double tend,\n        double timeStep)\n{\n    // Choix de l'algorithme et intégration\n    boost::numeric::odeint::runge_kutta4< state_type > stepper;\n    *m_steps = static_cast<unsigned int>(\n                boost::numeric::odeint::integrate_const(\n                    stepper, *this, x, t0, tend, timeStep,\n                    push_back_state_and_time( *m_x_vec , *m_times )));\n}\n", "meta": {"hexsha": "609f4c43e2722eb0ddea8ea089ce0c324a0c2eb6", "size": 2610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "optimal_control/includes/integrator.cpp", "max_stars_repo_name": "paulWegiel/ViolinOptimalControl", "max_stars_repo_head_hexsha": "0b9bc7b5ff3249abbf0f971da5c7d1efa8c03c75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-02T13:37:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:29:31.000Z", "max_issues_repo_path": "optimal_control/includes/integrator.cpp", "max_issues_repo_name": "paulWegiel/ViolinOptimalControl", "max_issues_repo_head_hexsha": "0b9bc7b5ff3249abbf0f971da5c7d1efa8c03c75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-16T02:21:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-16T02:21:49.000Z", "max_forks_repo_path": "optimal_control/includes/integrator.cpp", "max_forks_repo_name": "paulWegiel/ViolinOptimalControl", "max_forks_repo_head_hexsha": "0b9bc7b5ff3249abbf0f971da5c7d1efa8c03c75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-04-23T15:14:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-02T15:05:49.000Z", "avg_line_length": 29.6590909091, "max_line_length": 84, "alphanum_fraction": 0.6233716475, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232480373843, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4362296192134183}}
{"text": "/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.\n *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.\n *    Author(s):       Vincent Rouvreau\n *\n *    Copyright (C) 2014 Inria\n *\n *    Modification(s):\n *      - YYYY/MM Author: Description of the modification\n */\n\n#include <gudhi/reader_utils.h>\n#include <gudhi/graph_simplicial_complex.h>\n#include <gudhi/distance_functions.h>\n#include <gudhi/Simplex_tree.h>\n#include <gudhi/Persistent_cohomology.h>\n\n#include <boost/program_options.hpp>\n\n#include <string>\n\nusing namespace Gudhi;\nusing namespace Gudhi::persistent_cohomology;\n\ntypedef double Filtration_value;\n\nvoid program_options(int argc, char * argv[]\n                     , std::string & simplex_tree_file\n                     , std::string & output_file\n                     , int & p\n                     , Filtration_value & min_persistence);\n\nint main(int argc, char * argv[]) {\n  std::string simplex_tree_file;\n  std::string output_file;\n  int p;\n  Filtration_value min_persistence;\n\n  program_options(argc, argv, simplex_tree_file, output_file, p, min_persistence);\n\n  std::cout << \"Simplex_tree from file=\" << simplex_tree_file.c_str() << \" - output_file=\" << output_file.c_str()\n      << std::endl;\n  std::cout << \"     - p=\" << p << \" - min_persistence=\" << min_persistence << std::endl;\n\n  // Read the list of simplices from a file.\n  Simplex_tree<> simplex_tree;\n\n  std::ifstream simplex_tree_stream(simplex_tree_file);\n  simplex_tree_stream >> simplex_tree;\n\n  std::cout << \"The complex contains \" << simplex_tree.num_simplices() << \" simplices\" << std::endl;\n  std::cout << \"   - dimension \" << simplex_tree.dimension() << std::endl;\n\n  /*\n  std::cout << std::endl << std::endl << \"Iterator on Simplices in the filtration, with [filtration value]:\" << std::endl;\n  for( auto f_simplex : simplex_tree.filtration_simplex_range() )\n  { std::cout << \"   \" << \"[\" << simplex_tree.filtration(f_simplex) << \"] \";\n  for( auto vertex : simplex_tree.simplex_vertex_range(f_simplex) )\n  { std::cout << vertex << \" \"; }\n  std::cout << std::endl;\n  }*/\n\n  // Sort the simplices in the order of the filtration\n  simplex_tree.initialize_filtration();\n\n  // Compute the persistence diagram of the complex\n  Persistent_cohomology< Simplex_tree<>, Field_Zp > pcoh(simplex_tree);\n  // initializes the coefficient field for homology\n  pcoh.init_coefficients(p);\n\n  pcoh.compute_persistent_cohomology(min_persistence);\n\n  // Output the diagram in output_file\n  if (output_file.empty()) {\n    pcoh.output_diagram();\n  } else {\n    std::ofstream out(output_file);\n    pcoh.output_diagram(out);\n    out.close();\n  }\n\n  return 0;\n}\n\nvoid program_options(int argc, char * argv[]\n                     , std::string & simplex_tree_file\n                     , std::string & output_file\n                     , int & p\n                     , Filtration_value & min_persistence) {\n  namespace po = boost::program_options;\n  po::options_description hidden(\"Hidden options\");\n  hidden.add_options()\n      (\"input-file\", po::value<std::string>(&simplex_tree_file),\n       \"Name of file containing a simplex set. Format is one simplex per line (cf. reader_utils.h - read_simplex): Dim1 X11 X12 ... X1d Fil1  \");\n\n  po::options_description visible(\"Allowed options\", 100);\n  visible.add_options()\n      (\"help,h\", \"produce help message\")\n      (\"output-file,o\", po::value<std::string>(&output_file)->default_value(std::string()),\n       \"Name of file in which the persistence diagram is written. Default print in std::cout\")\n      (\"field-charac,p\", po::value<int>(&p)->default_value(11),\n       \"Characteristic p of the coefficient field Z/pZ for computing homology.\")\n      (\"min-persistence,m\", po::value<Filtration_value>(&min_persistence),\n       \"Minimal lifetime of homology feature to be recorded. Default is 0\");\n\n  po::positional_options_description pos;\n  pos.add(\"input-file\", 1);\n\n  po::options_description all;\n  all.add(visible).add(hidden);\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).\n            options(all).positional(pos).run(), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\") || !vm.count(\"input-file\")) {\n    std::cout << std::endl;\n    std::cout << \"Compute the persistent homology with coefficient field Z/pZ \\n\";\n    std::cout << \"of a Rips complex defined on a set of input points.\\n \\n\";\n    std::cout << \"The output diagram contains one bar per line, written with the convention: \\n\";\n    std::cout << \"   p   dim b d \\n\";\n    std::cout << \"where dim is the dimension of the homological feature,\\n\";\n    std::cout << \"b and d are respectively the birth and death of the feature and \\n\";\n    std::cout << \"p is the characteristic of the field Z/pZ used for homology coefficients.\" << std::endl << std::endl;\n\n    std::cout << \"Usage: \" << argv[0] << \" [options] input-file\" << std::endl << std::endl;\n    std::cout << visible << std::endl;\n    exit(-1);\n  }\n}\n", "meta": {"hexsha": "d169cc638939ed261e715a7b7d63941179f1130a", "size": 4992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Persistent_cohomology/example/persistence_from_file.cpp", "max_stars_repo_name": "jmarino/gudhi-devel", "max_stars_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-27T03:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T21:14:14.000Z", "max_issues_repo_path": "src/Persistent_cohomology/example/persistence_from_file.cpp", "max_issues_repo_name": "jmarino/gudhi-devel", "max_issues_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-25T16:03:23.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-28T07:36:21.000Z", "max_forks_repo_path": "src/Persistent_cohomology/example/persistence_from_file.cpp", "max_forks_repo_name": "jmarino/gudhi-devel", "max_forks_repo_head_hexsha": "b1824e4de6fd1d037af3c1341c3065731472ffc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-06T12:36:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-25T14:53:13.000Z", "avg_line_length": 38.106870229, "max_line_length": 145, "alphanum_fraction": 0.6584535256, "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239133, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.43620833136593806}}
{"text": "/********************************************************************************\n * Copyright 2017 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#include \"Delaunay.hpp\"\n\n#if defined(__cplusplus)\nextern \"C\"\n{\n#include <libqhull_r/libqhull_r.h>\n}\n#endif\n\n#include <boost/numeric/conversion/cast.hpp>\n\nusing rw::core::ownedPtr;\nusing namespace rw::math;\nusing namespace rw::geometry;\n\nnamespace {\nint build (int dim, double* coords, int nrCoords, std::vector< int >& vertIdxs,\n           std::vector< int >& faceIdxs)\n{\n    vertIdxs.clear ();\n    faceIdxs.clear ();\n\n    std::vector< int >& result = vertIdxs;\n\n    int curlong, totlong; /* used !qh_NOmem */\n    int exitcode;\n    boolT ismalloc = false;\n    qhT qh;\n    qhT* qhT_pointer = &qh;    // allocate memory for qhull\n\n    char flags[] = \"qhull d Qbb Qt Qz\";\n    // d Qbb: delaunay with scaling of last coordinate (eq. to qdelaunay)\n    // Qt: triangulated output\n    // Qz: add point-at-infinity (for cocircular points like in rectangles)\n\n    // According to doc. in libqhull_r/user_r.c, the qhull memory should be cleared:\n    qh_zero (qhT_pointer, stderr);\n\n    \n    // Then the object is constructed.\n    exitcode = qh_new_qhull (qhT_pointer, dim, nrCoords, coords, ismalloc, flags, NULL, stderr);\n    \n\n    // Loop through all vertices,\n    vertexT* vertex;    //, **vertexp;\n    for (vertex = qhT_pointer->vertex_list; vertex && vertex->next; vertex = vertex->next) {\n        int vertexIdx = qh_pointid (qhT_pointer, vertex->point);\n        result.push_back (vertexIdx);\n    }\n\n    if (!exitcode) {\n        // For all facets:\n        for (facetT* facet = qhT_pointer->facet_list; facet && facet->next; facet = facet->next) {\n            if (!facet->upperdelaunay) {\n                int vertex_n, vertex_i;\n                FOREACHvertex_i_ (qhT_pointer, facet->vertices)\n                {\n                    int vertexIdx = qh_pointid (qhT_pointer, vertex->point);\n                    faceIdxs.push_back (vertexIdx);\n                }\n            }\n        }\n    }\n    if (qhT_pointer->VERIFYoutput && !qhT_pointer->FORCEoutput && !qhT_pointer->STOPpoint &&\n        !qhT_pointer->STOPcone)\n        qh_check_points (qhT_pointer);\n\n    qh_freeqhull (qhT_pointer, False);\n    qh_memfreeshort (qhT_pointer, &curlong, &totlong);\n    if (curlong || totlong)\n        fprintf (\n            stderr,\n            \"qdelaunay internal warning (main): did not free %d bytes of long memory (%d pieces)\\n\",\n            totlong,\n            curlong);\n    return exitcode;\n}\n\ntemplate< typename S >\ntypename IndexedTriMeshN0< double, S >::Ptr makeMesh (const std::vector< Vector2D<> >& hullVertices,\n                                                      const std::vector< int >& faceIdxs,\n                                                      const std::vector< double >& values)\n{\n    typedef IndexedTriMeshN0< double, S > Mesh;\n    typedef typename Mesh::VertexArray VertexArray;\n    typedef typename Mesh::TriangleArray TriangleArray;\n\n    // Add vertices\n    const rw::core::Ptr< VertexArray > meshV = ownedPtr (new VertexArray (hullVertices.size ()));\n    for (size_t i = 0; i < hullVertices.size (); i++) {\n        (*meshV)[i] = Vector3D<> (hullVertices[i][0],\n                                  hullVertices[i][1],\n                                  (values.size () == hullVertices.size ()) ? values[i] : 0);\n    }\n\n    // Add triangles\n    const rw::core::Ptr< TriangleArray > meshTri =\n        ownedPtr (new TriangleArray (faceIdxs.size () / 3));\n    for (size_t i = 0; i < faceIdxs.size () / 3; i++) {\n        const typename Mesh::tri_type tempTri (\n            faceIdxs[i * 3 + 0], faceIdxs[i * 3 + 1], faceIdxs[i * 3 + 2]);\n        const Vector3D<>& v1 = (*meshV)[tempTri[0]];\n        const Vector3D<>& v2 = (*meshV)[tempTri[1]];\n        const Vector3D<>& v3 = (*meshV)[tempTri[2]];\n\n        // Make sure the vertices order is correct according to right-hand rule. Otherwise flip v2\n        // and v3.\n        const double dotProduct = dot (cross (v2 - v1, v3 - v2), Vector3D<>::z ());\n        if (dotProduct < 0.0) {\n            (*meshTri)[i] = typename Mesh::tri_type (tempTri[0], tempTri[2], tempTri[1]);\n        }\n        else {\n            (*meshTri)[i] = tempTri;\n        }\n    }\n\n    const typename Mesh::Ptr mesh = ownedPtr (new Mesh (meshV, meshTri));\n    return mesh;\n}\n}    // namespace\n\nDelaunay::Delaunay ()\n{}\n\nDelaunay::~Delaunay ()\n{}\n\nIndexedTriMesh<>::Ptr Delaunay::triangulate (const std::vector< Vector2D<> >& vertices,\n                                             const std::vector< double >& values)\n{\n    if (vertices.size () == 3) {\n        std::vector< int > faceIdxs (3);\n        faceIdxs[0] = 0;\n        faceIdxs[1] = 1;\n        faceIdxs[2] = 2;\n        return makeMesh< uint8_t > (vertices, faceIdxs, values);\n    }\n    const int nrInputVertices = boost::numeric_cast< int > (vertices.size ());\n\n    // convert the vertice array to an array of double\n    double* vertArray = new double[vertices.size () * 2];\n    // copy all data into the vertArray\n    for (size_t i = 0; i < vertices.size (); i++) {\n        const Vector2D<>& v  = vertices[i];\n        vertArray[i * 2 + 0] = v[0];\n        vertArray[i * 2 + 1] = v[1];\n    }\n    // Build delaunay triangulation\n    std::vector< Vector2D<> > triangVertices;\n    std::vector< int > vertiIdxs;\n    std::vector< int > faceIdxs;\n\n    \n    const int exitcode = build (2, vertArray, nrInputVertices, vertiIdxs, faceIdxs);\n    \n    delete[] vertArray;\n    if (exitcode)\n        RW_THROW (\"Delaunay triangulation returned with exit code \" << exitcode);\n\n    std::vector< int > vertIdxMap (vertices.size ());\n    triangVertices.resize (vertiIdxs.size () - 1);    // Qz gives extra vertex\n    int triangVerticesI = 0;\n    for (size_t i = 0; i < vertiIdxs.size (); i++) {\n        if (vertiIdxs[i] < nrInputVertices) {\n            triangVertices[triangVerticesI] = vertices[vertiIdxs[i]];\n            vertIdxMap[vertiIdxs[i]]        = triangVerticesI;\n            triangVerticesI++;\n        }\n    }\n    for (size_t i = 0; i < faceIdxs.size (); i++) {\n        const int tmp = faceIdxs[i];\n        faceIdxs[i]   = vertIdxMap[tmp];\n    }\n\n    // Create the mesh\n    if (vertices.size () <= 256) {\n        return makeMesh< uint8_t > (triangVertices, faceIdxs, values);\n    }\n    else if (vertices.size () <= 65536) {\n        return makeMesh< uint16_t > (triangVertices, faceIdxs, values);\n    }\n    else if (vertices.size () <= 4294967296) {\n        return makeMesh< uint32_t > (triangVertices, faceIdxs, values);\n    }\n    else {\n        return makeMesh< uint64_t > (triangVertices, faceIdxs, values);\n    }\n}\n", "meta": {"hexsha": "f3137d7bc7fdc8f73e8165a581faa6c149fc84a1", "size": 7341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/geometry/Delaunay.cpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/geometry/Delaunay.cpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/geometry/Delaunay.cpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6359223301, "max_line_length": 100, "alphanum_fraction": 0.5830268356, "num_tokens": 1968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.43620832818755473}}
{"text": "#include \"static_ic.h\"\n#include \"../../cosmo_includes.h\"\n#include \"../../cosmo_types.h\"\n#include \"../../cosmo_globals.h\"\n#include \"../../ICs/ICs.h\"\n#include \"../../utils/math.h\"\n\n#include <boost/math/special_functions/spherical_harmonic.hpp>\n\n#include <utility>\n#include <random>\n\nnamespace cosmo\n{\n\ntypedef std::pair<real_t, real_t> complex_t;\n#define m_idx(l, m) ((l)+(m))\n\n\n/**\n * @brief Gaussian random field ICs\n * \n * General steps:\n *  1) Generate the Newtonian gauge variables:\n *     phi = psi, \\dot{phi} = 0, \\delta_u\n *  2) Compute the synchronous gauge variables\n *  3) Fix \\phi, \\bar{gamma}_{ij}, K\n *  4) Solve for V, U in CTT decomposition -> obtain \\bar{A}_{ij}^{\\rm NL}\n *  5) Use the Hamiltonian constraint residual to solve for the density field\n */\nvoid static_ic_set_random(BSSN * bssn, Static * stat, Lambda * lambda,\n  Fourier * fourier, IOData * iodata)\n{\n  idx_t i, j, k;\n\n  // Background cosmology, a_FRW = 1\n  real_t rho_FRW = 3.0/PI/8.0;\n  real_t Omega_L = std::stod(_config(\"Omega_L\", \"1.0e-6\"));\n  real_t p0 = std::stod(_config(\"p0\", \"7.0\"));\n  real_t P = H_LEN_FRAC*H_LEN_FRAC*1.0e-15*std::stod(_config(\"P\", \"1.0\"));\n  real_t p_cut = std::stod(_config(\"p_cut\", \"1.0\"));\n  real_t rho_L = Omega_L * rho_FRW;\n  lambda->setLambda(rho_L);\n\n  // final metric fields\n  arr_t & DIFFphi_p = *bssn->fields[\"DIFFphi_p\"];\n  arr_t & DIFFK_p = *bssn->fields[\"DIFFK_p\"];\n  arr_t & A11_p = *bssn->fields[\"A11_p\"];\n  arr_t & A12_p = *bssn->fields[\"A12_p\"];\n  arr_t & A13_p = *bssn->fields[\"A13_p\"];\n  arr_t & A22_p = *bssn->fields[\"A22_p\"];\n  arr_t & A23_p = *bssn->fields[\"A23_p\"];\n  arr_t & A33_p = *bssn->fields[\"A33_p\"];\n  arr_t & DIFFD_a = *stat->fields[\"DIFFD_a\"];\n\n  // Extra / auxiliary fields for intermediate computations\n  // (re-use _c register, it gets overwritten later anyways)\n  arr_t & phi_N = *bssn->fields[\"DIFFphi_c\"];\n  arr_t & lap_phi_N = *bssn->fields[\"DIFFK_c\"];\n  arr_t & invlape6pd1K = *bssn->fields[\"DIFFgamma11_c\"];\n  arr_t & invlape6pd2K = *bssn->fields[\"DIFFgamma12_c\"];\n  arr_t & invlape6pd3K = *bssn->fields[\"DIFFgamma13_c\"];\n  arr_t & W1 = *bssn->fields[\"A22_c\"];\n  arr_t & W2 = *bssn->fields[\"A23_c\"];\n  arr_t & W3 = *bssn->fields[\"A33_c\"];\n\n  // 1.a) Synchronous-gauge Newtonian potential:\n  set_gaussian_random_Phi_N(phi_N, fourier, P, p0, p_cut);\n\n  // 1.b) Preliminary metric variables: phi, K\n# pragma omp parallel for default(shared) private(i,j,k)\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n    \n    lap_phi_N[idx] = laplacian(i, j, k, phi_N);\n\n    DIFFphi_p[idx] = log1p(-10.0/3.0*phi_N[idx])/4.0;\n    DIFFK_p[idx] = -3.0*(1.0 + 2.0*phi_N[idx]) + 2.0/3.0*lap_phi_N[idx];\n  }\n\n  // 1.c) Vector contribution to the extrinsic curvature, W^i\n  // compute invlapK\n# pragma omp parallel for default(shared) private(i,j,k)\n  LOOP3(i,j,k) {\n    idx_t idx = NP_INDEX(i,j,k);\n    real_t e6p = exp(6.0*DIFFphi_p[idx]);\n    invlape6pd1K[idx] = e6p*derivative(i,j,k,1,DIFFK_p);\n    invlape6pd2K[idx] = e6p*derivative(i,j,k,2,DIFFK_p);\n    invlape6pd3K[idx] = e6p*derivative(i,j,k,3,DIFFK_p);\n  }\n  fourier->inverseLaplacian <idx_t, real_t> (invlape6pd1K._array);\n  fourier->inverseLaplacian <idx_t, real_t> (invlape6pd2K._array);\n  fourier->inverseLaplacian <idx_t, real_t> (invlape6pd3K._array);\n  // compute W^i = W_i\n# pragma omp parallel for default(shared) private(i,j,k)\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n    W1[idx] = -derivative(i,j,k,1,phi_N)/3.0 + invlape6pd1K[idx]/2.0;\n    W2[idx] = -derivative(i,j,k,2,phi_N)/3.0 + invlape6pd2K[idx]/2.0;\n    W3[idx] = -derivative(i,j,k,3,phi_N)/3.0 + invlape6pd3K[idx]/2.0;\n  }\n\n  // 1.d) Aij components\n# pragma omp parallel for default(shared) private(i,j,k)\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n    // these are the CTT conformal Aij\n    real_t CTT2BSSNAij = exp(-6.0*DIFFphi_p[idx]);\n    real_t DkWk = derivative(i,j,k,1,W1) + derivative(i,j,k,2,W2) + derivative(i,j,k,3,W3);\n    A11_p[idx] = CTT2BSSNAij * ( derivative(i,j,k,1,W1) + derivative(i,j,k,1,W1) + 2.0/3.0*double_derivative(i,j,k,1,1,phi_N)\n      - 2.0/3.0*DkWk - 2.0/9.0*lap_phi_N[idx] );\n    A12_p[idx] = CTT2BSSNAij * ( derivative(i,j,k,1,W2) + derivative(i,j,k,2,W1) + 2.0/3.0*double_derivative(i,j,k,1,2,phi_N) );\n    A13_p[idx] = CTT2BSSNAij * ( derivative(i,j,k,1,W3) + derivative(i,j,k,3,W1) + 2.0/3.0*double_derivative(i,j,k,1,3,phi_N) );\n    A22_p[idx] = CTT2BSSNAij * ( derivative(i,j,k,2,W2) + derivative(i,j,k,2,W2) + 2.0/3.0*double_derivative(i,j,k,2,2,phi_N)\n      - 2.0/3.0*DkWk - 2.0/9.0*lap_phi_N[idx] );\n    A23_p[idx] = CTT2BSSNAij * ( derivative(i,j,k,2,W3) + derivative(i,j,k,3,W2) + 2.0/3.0*double_derivative(i,j,k,2,3,phi_N) );\n    A33_p[idx] = CTT2BSSNAij * ( derivative(i,j,k,3,W3) + derivative(i,j,k,3,W3) + 2.0/3.0*double_derivative(i,j,k,3,3,phi_N)\n      - 2.0/3.0*DkWk - 2.0/9.0*lap_phi_N[idx] );\n  }\n\n  // 1.e) Density field\n# pragma omp parallel for default(shared) private(i,j,k)\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n\n    real_t AijAij = A11_p[idx]*A11_p[idx] + A22_p[idx]*A22_p[idx] + A33_p[idx]*A33_p[idx]\n      + 2.0*(A12_p[idx]*A12_p[idx] + A13_p[idx]*A13_p[idx] + A23_p[idx]*A23_p[idx]);\n    real_t lap_e_p = exp(DIFFphi_p[idx]) * ( laplacian(i,j,k,DIFFphi_p)\n      + pw2(derivative(i,j,k,1,DIFFphi_p)) + pw2(derivative(i,j,k,2,DIFFphi_p)) + pw2(derivative(i,j,k,3,DIFFphi_p)) );\n    real_t rho_ADM = 1.0/2.0/PI * ( DIFFK_p[idx]*DIFFK_p[idx]/12.0 - AijAij/8.0 - exp(-5.0*DIFFphi_p[idx])*lap_e_p );\n    real_t rho_0 = rho_ADM - rho_L;\n\n    if(rho_0 < 0.0)\n    {\n      iodata->log(\"Error: negative density in some regions.\");\n      throw -1;\n    }\n\n    DIFFD_a[idx] = exp(6.0*DIFFphi_p[idx])*rho_0;\n  }\n\n  iodata->log( \"Average fluctuation density: \" + stringify(average(DIFFD_a)) );\n  iodata->log( \"Std.dev fluctuation density: \" + stringify(standard_deviation(DIFFD_a)) );\n}\n\n\nvoid static_ic_set_sinusoid_3d(BSSN * bssn, Static * stat, Lambda * lambda, Fourier * fourier,\n  IOData * iodata)\n{\n\n  idx_t i, j, k;\n\n  arr_t & DIFFr_a = *bssn->fields[\"DIFFr_a\"];\n  arr_t & DIFFphi_p = *bssn->fields[\"DIFFphi_p\"];\n  arr_t & DIFFD_a = *stat->fields[\"DIFFD_a\"];\n\n  real_t rho_FRW = 3.0/PI/8.0;\n\n  real_t Omega_L = std::stod(_config(\"Omega_L\", \"0.0\"));\n  real_t rho_m = (1.0 - Omega_L) * rho_FRW;\n  real_t rho_L = Omega_L * rho_FRW;\n  lambda->setLambda(rho_L);\n\n  real_t A = H_LEN_FRAC*H_LEN_FRAC*std::stod(_config(\"peak_amplitude_frac\", \"0.001\"));\n\n  // the conformal factor in front of metric is the solution to\n  // d^2 exp(\\phi) = -2*pi exp(5\\phi) * \\delta_rho\n  // generate random mode in \\phi\n  // delta_rho = -(lap e^\\phi)/e^(4\\phi)/2pi\n  real_t phix = std::stod(_config(\"phix\", \"0.0\"));\n  real_t phiy = phix, phiz = phix;\n\n  // grid values\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n\n    real_t x_frac = ((real_t) i / (real_t) NX),\n      y_frac = ((real_t) j / (real_t) NY), z_frac = ((real_t) k / (real_t) NZ);\n    \n    real_t phi = A*\n      (sin(2.0*PI*x_frac + phix) + sin(2.0*PI*y_frac + phiy) + sin(2.0*PI*z_frac + phiz));\n\n    real_t DIFFrho = -exp(-4.0*phi)/PI/2.0*(\n      pw2(A*2.0*PI / H_LEN_FRAC * cos(2.0*PI*x_frac + phix))\n      + pw2(A*2.0*PI / H_LEN_FRAC * cos(2.0*PI*y_frac + phiy))\n      + pw2(A*2.0*PI / H_LEN_FRAC * cos(2.0*PI*z_frac + phiz))\n      -  ( A * pw2(2.0*PI / H_LEN_FRAC) * sin(2.0*PI*x_frac + phix)\n           + A * pw2(2.0*PI / H_LEN_FRAC) * sin(2.0*PI*y_frac + phiy)\n           + A * pw2(2.0*PI / H_LEN_FRAC) * sin(2.0*PI*z_frac + phiz))\n    );\n\n    // These aren't difference vars\n    DIFFphi_p[NP_INDEX(i,j,k)] = phi;\n    DIFFr_a[idx] = DIFFrho;\n\n// // debugging: throw away field\n// DIFFD_a[idx] = phi;\n  }\n// std::cout << std::setprecision(17);\n// std::cout << \"field[0] = \" << DIFFD_a[0] << \"; \";\n// fourier->inverseLaplacian <idx_t, real_t> (DIFFD_a._array);\n// std::cout << \"lap/lap field = \" << laplacian(0,0,0,DIFFD_a) << \"\\n\";\n\n  // Make sure min density value > 0\n  // Set conserved density variable field\n  real_t min = rho_m;\n  real_t max = min;\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n    real_t DIFFr = DIFFr_a[idx];\n    real_t rho = rho_m + DIFFr;\n    // phi_FRW = 0\n    real_t DIFFphi = DIFFphi_p[idx];\n    // phi = DIFFphi\n    // DIFFK = 0\n\n    DIFFD_a[idx] =\n      rho_m*expm1(6.0*DIFFphi) + exp(6.0*DIFFphi)*DIFFr;\n\n    if(rho < min)\n    {\n      min = rho;\n    }\n    if(rho > max)\n    {\n      max = rho;\n    }\n    if(rho != rho)\n    {\n      iodata->log(\"Error: NaN energy density.\");\n      throw -1;\n    }\n  }\n\n  iodata->log( \"Minimum fluid density: \" + stringify(min) );\n  iodata->log( \"Maximum fluid density: \" + stringify(max) );\n  iodata->log( \"Average fluctuation density: \" + stringify(average(DIFFD_a)) );\n  iodata->log( \"Std.dev fluctuation density: \" + stringify(standard_deviation(DIFFD_a)) );\n  if(min < 0.0)\n  {\n    iodata->log(\"Error: negative density in some regions.\");\n    throw -1;\n  }\n\n# if USE_REFERENCE_FRW\n  // Set values in reference FRW integrator\n  auto & frw = bssn->frw;\n  real_t K_FRW = -sqrt(24.0*PI*rho_FRW);\n  frw->set_phi(0.0);\n  frw->set_K(K_FRW);\n  frw->addFluid(rho_m, 0.0 /* w=0 */);\n# else\n  arr_t & DIFFK_p = *bssn->fields[\"DIFFK_p\"];\n  arr_t & DIFFK_a = *bssn->fields[\"DIFFK_a\"];\n  // add in FRW pieces to ICs\n  // phi is unchanged\n  // rho (D) and K get contribs\n  // w=0 fluid only\n# pragma omp parallel for default(shared) private(i,j,k)\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n\n    real_t D_FRW = rho_m; // on initial slice\n\n    DIFFr_a[idx] += rho_m;\n\n    DIFFK_a[idx] = -sqrt(24.0*PI*rho_FRW);\n    DIFFK_p[idx] = -sqrt(24.0*PI*rho_FRW);\n\n    DIFFD_a[idx] += D_FRW;\n  }\n# endif\n\n}\n\n\n/**\n * @brief Sinusoidal mode ICs\n */\nvoid static_ic_set_sinusoid(BSSN * bssn, Static * stat, Lambda * lambda, Fourier * fourier,\n  IOData * iodata)\n{\n  idx_t i, j, k;\n\n  arr_t & DIFFr_a = *bssn->fields[\"DIFFr_a\"];\n  arr_t & DIFFphi_p = *bssn->fields[\"DIFFphi_p\"];\n  arr_t & DIFFD_a = *stat->fields[\"DIFFD_a\"];\n\n  real_t rho_FRW = 3.0/PI/8.0;\n\n  real_t Omega_L = std::stod(_config(\"Omega_L\", \"0.0\"));\n  real_t rho_m = (1.0 - Omega_L) * rho_FRW;\n  real_t rho_L = Omega_L * rho_FRW;\n  lambda->setLambda(rho_L);\n\n  real_t A = H_LEN_FRAC*H_LEN_FRAC*std::stod(_config(\"peak_amplitude_frac\", \"0.001\"));\n\n  // the conformal factor in front of metric is the solution to\n  // d^2 exp(\\phi) = -2*pi exp(5\\phi) * \\delta_rho\n  // generate random mode in \\phi\n  // delta_rho = -(lap e^\\phi)/e^(4\\phi)/2pi\n  real_t phix = std::stod(_config(\"phix\", \"0.0\"));\n  real_t twopi_L = 2.0*PI/H_LEN_FRAC;\n  real_t pw2_twopi_L = twopi_L*twopi_L;\n  // grid values\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n\n    real_t x = ((real_t) i / (real_t) NX);\n    real_t phi = A*sin(2.0*PI*x + phix);\n    real_t DIFFrho = -exp(-4.0*phi)/PI/2.0*(\n        pw2(twopi_L*A*cos(2.0*PI*x + phix))\n        - pw2_twopi_L*A*sin(2.0*PI*x + phix)\n      );\n\n    // These aren't difference vars\n    DIFFphi_p[NP_INDEX(i,j,k)] = phi;\n    DIFFr_a[idx] = DIFFrho;\n\n  }\n\n  // Make sure min density value > 0\n  // Set conserved density variable field\n  real_t min = rho_m;\n  real_t max = min;\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n    real_t DIFFr = DIFFr_a[idx];\n    real_t rho = rho_m + DIFFr;\n    // phi_FRW = 0\n    real_t DIFFphi = DIFFphi_p[idx];\n    // phi = DIFFphi\n    // DIFFK = 0\n\n    DIFFD_a[idx] =\n      rho_m*expm1(6.0*DIFFphi) + exp(6.0*DIFFphi)*DIFFr;\n\n    if(rho < min)\n    {\n      min = rho;\n    }\n    if(rho > max)\n    {\n      max = rho;\n    }\n    if(rho != rho)\n    {\n      iodata->log(\"Error: NaN energy density.\");\n      throw -1;\n    }\n  }\n\n  iodata->log( \"Minimum fluid density: \" + stringify(min) );\n  iodata->log( \"Maximum fluid density: \" + stringify(max) );\n  iodata->log( \"Average fluctuation density: \" + stringify(average(DIFFD_a)) );\n  iodata->log( \"Std.dev fluctuation density: \" + stringify(standard_deviation(DIFFD_a)) );\n  if(min < 0.0)\n  {\n    iodata->log(\"Error: negative density in some regions.\");\n    throw -1;\n  }\n\n# if USE_REFERENCE_FRW\n  // Set values in reference FRW integrator\n  auto & frw = bssn->frw;\n  real_t K_FRW = -sqrt(24.0*PI*rho_FRW);\n  frw->set_phi(0.0);\n  frw->set_K(K_FRW);\n  frw->addFluid(rho_m, 0.0 /* w=0 */);\n# else\n  arr_t & DIFFK_p = *bssn->fields[\"DIFFK_p\"];\n  arr_t & DIFFK_a = *bssn->fields[\"DIFFK_a\"];\n  // add in FRW pieces to ICs\n  // phi is unchanged\n  // rho (D) and K get contribs\n  // w=0 fluid only\n# pragma omp parallel for default(shared) private(i,j,k)\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n\n    real_t D_FRW = rho_m; // on initial slice\n\n    DIFFr_a[idx] += rho_m;\n\n    DIFFK_a[idx] = -sqrt(24.0*PI*rho_FRW);\n    DIFFK_p[idx] = -sqrt(24.0*PI*rho_FRW);\n\n    DIFFD_a[idx] += D_FRW;\n  }\n# endif\n}\n\n\nvoid static_ic_set_semianalytic(\n  BSSN * bssn, Static * stat, Lambda * lambda, Fourier * fourier,\n  IOData * iodata)\n{\n  idx_t i, j, k;\n\n  arr_t & DIFFr_a = *bssn->fields[\"DIFFr_a\"];\n  arr_t & DIFFphi_p = *bssn->fields[\"DIFFphi_p\"];\n  arr_t & DIFFD_a = *stat->fields[\"DIFFD_a\"];\n  arr_t & DIFFK_p = *bssn->fields[\"DIFFK_p\"];\n\n  real_t rho_FRW = 3.0/PI/8.0;\n  real_t K_FRW = -3.0;\n\n  real_t Omega_L = std::stod(_config(\"Omega_L\", \"0.0\"));\n  real_t rho_m = (1.0 - Omega_L) * rho_FRW;\n  real_t rho_L = Omega_L * rho_FRW;\n  lambda->setLambda(rho_L);\n  real_t L = H_LEN_FRAC;\n  real_t A = std::stod(_config(\"peak_amplitude\", \"0.001\"))*0.026699*L*L;\n  // grid values\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n    real_t x = ((real_t) i) * dx;\n    DIFFphi_p[idx] = std::log1p( A*std::sin(2.0*PI*x/L) );\n    DIFFr_a[idx] = rho_m + 2.0*A*PI*std::sin((2*PI*x)/L)\n      / ( L*L*std::pow(1 + A*std::sin((2*PI*x)/L), 5) );\n    DIFFK_p[idx] = K_FRW;\n    DIFFD_a[idx] = exp(6.0*DIFFphi_p[idx])*DIFFr_a[idx];\n  }\n\n  // Make sure min density value > 0\n  // Set conserved density variable field\n  real_t min = rho_m;\n  real_t max = min;\n  LOOP3(i,j,k)\n  {\n    real_t rho = DIFFr_a[NP_INDEX(i,j,k)];\n    if(rho < min)\n    {\n      min = rho;\n    }\n    if(rho > max)\n    {\n      max = rho;\n    }\n    if(rho != rho)\n    {\n      iodata->log(\"Error: NaN energy density.\");\n      throw -1;\n    }\n  }\n\n  iodata->log( \"Minimum fluid density: \" + stringify(min) );\n  iodata->log( \"Maximum fluid density: \" + stringify(max) );\n  iodata->log( \"Average fluctuation density: \" + stringify(average(DIFFD_a)) );\n  iodata->log( \"Std.dev fluctuation density: \" + stringify(standard_deviation(DIFFD_a)) );\n  if(min < 0.0)\n  {\n    iodata->log(\"Error: negative density in some regions.\");\n    throw -1;\n  }\n}\n\n\n\n/**\n * @brief Spherical \"shell\" of perturbations around an observer\n */\nvoid static_ic_set_sphere(BSSN * bssn, Static * stat, IOData * iodata)\n{\n  idx_t i, j, k;\n\n  arr_t & DIFFr_a = *bssn->fields[\"DIFFr_a\"];\n  arr_t & DIFFphi_p = *bssn->fields[\"DIFFphi_p\"];\n  arr_t & DIFFphi_a = *bssn->fields[\"DIFFphi_a\"];\n  arr_t & DIFFphi_f = *bssn->fields[\"DIFFphi_f\"];\n\n  arr_t & DIFFD_a = *stat->fields[\"DIFFD_a\"];\n\n  // shell amplitude\n  const real_t A = stod(_config(\"shell_amplitude\", \"1e-5\"));\n  // Shell described by only one fixed l:\n  const idx_t l = stoi(_config(\"shell_angular_scale_l\", \"1\"));\n  iodata->log( \"Generating ICs with shell angular scale of l = \" + stringify(l) );\n  iodata->log( \"Generating ICs with peak amp. = \" + stringify(A) );\n\n  // spherical shell of perturbations in phi0field\n\n  // place shell around center of box\n  real_t x0 = (NX-0.001)*dx/2.0;\n  real_t y0 = (NY-0.001)*dx/2.0;\n  real_t z0 = (NZ-0.001)*dx/2.0;\n\n  // place spherical \"shell\" of fluctuations at r = NX/4, 1/2-way between observer and boundary \n  real_t r_shell = NX*dx / 4.0;\n  // shell width\n  real_t shell_width = NX*dx / 40.0;\n\n  // Angular fluctuations in shell described by spherical harmonic coeffs, a_lm's,\n  complex_t * alms = new complex_t[m_idx(l,l)+1];\n  const real_t seed = stod(_config(\"mt19937_seed\", \"7\"));\n  std::mt19937 gen(seed);\n  std::normal_distribution<> normal_dist(0.0, 1.0);\n  std::uniform_real_distribution<> uniform_dist(0.0, 2.0*PI);\n\n  std::cout << \"normal_dist(gen) = \" << normal_dist(gen) << \", uniform_dist(gen) = \" << uniform_dist(gen) << \"\\n\";\n\n  // zero mode:\n  alms[m_idx(l, 0)].first = normal_dist(gen);\n  alms[m_idx(l, 0)].second = 0;\n  // positive modes:\n  for(int m = 1; m <= l; m++)\n  {\n    real_t phase = uniform_dist(gen);\n    real_t amp = normal_dist(gen);\n    alms[m_idx(l,m)].first = amp*std::cos(phase);\n    alms[m_idx(l,m)].second = amp*std::sin(phase);\n  }\n  // negative modes:\n  for(int m = -l; m <= -1; m++)\n  {\n    real_t Condon_Shortley_phase = std::abs(m) % 2 ? -1.0 : 1.0; // 0 (false) if m even, 1 (true) if odd\n    alms[m_idx(l,m)].first = Condon_Shortley_phase*alms[m_idx(l,std::abs(m))].first;\n    alms[m_idx(l,m)].second = -Condon_Shortley_phase*alms[m_idx(l,std::abs(m))].second;\n  }\n\n  for(int m = -l; m <= l; m++)\n  {\n    std::cout << \"Amp. of a_{\" << l << \",\" << m << \"} = \" << alms[m_idx(l,m)].first\n      << \" + \" << alms[m_idx(l,m)].second << \"i\\n\";\n  }\n\n  LOOP3(i,j,k) {\n    idx_t idx = NP_INDEX(i,j,k);\n\n    real_t x = i*dx;\n    real_t y = j*dx;\n    real_t z = k*dx;\n\n    real_t r = sqrt( pw2(x - x0) + pw2(y - y0) + pw2(z - z0) );\n    real_t theta = acos((z - z0) / r); // \"theta\" (polar angle)\n    real_t phi = atan2(y - y0, x - x0); // \"phi\" (azimuthal angle)\n\n    real_t DIFFphi_r = 0.0;\n    real_t DIFFphi_i = 0.0;\n    for(int m=-l; m<=l; m++)\n    {\n      real_t Y_r = boost::math::spherical_harmonic_r(l, m, theta, phi);\n      real_t Y_i = boost::math::spherical_harmonic_i(l, m, theta, phi);\n\n      DIFFphi_r += alms[m_idx(l,m)].first*Y_r - alms[m_idx(l,m)].second*Y_i;\n      DIFFphi_i += alms[m_idx(l,m)].first*Y_i + alms[m_idx(l,m)].second*Y_r;\n    }\n    if(std::abs(DIFFphi_i) > 1e-6)\n    {\n      iodata->log(\"Significant non-zero imaginary component of solution exists!\");\n      throw -1;\n    }\n\n    // gaussian profile shell of fluctuations\n    real_t U_r = A*std::exp( -pw2((r - r_shell)/2.0/shell_width) );\n    // cosine profile\n    // real_t U_r = (r < r_shell-shell_width || r > r_shell+shell_width ) ? 0 : A*(1+std::cos(PI*(r-r_shell)/shell_width));\n\n    DIFFphi_p[idx] = U_r*DIFFphi_r;\n\n\n    if(i==NX/2 && j==NY/2 && k==NZ/2)\n      std::cout << \"At a grid point close to the middle, r = \" << r\n                << \", r_shell = \" << r_shell\n                << \", shell_width = \" << shell_width\n                << \", U_r = \" << U_r\n                << \", DIFFphi_p = \" << DIFFphi_p[idx] << \"\\n\";\n  }\n  // cleanup\n  delete [] alms;\n\n  // delta_rho = -lap(phi)/(1+xi)^5/2pi\n# pragma omp parallel for default(shared) private(i,j,k)\n  LOOP3(i,j,k) {\n    DIFFr_a[NP_INDEX(i,j,k)] = -0.5/PI/(\n      pow(1.0 + DIFFphi_p[NP_INDEX(i,j,k)], 5.0)\n    )*(\n      double_derivative(i, j, k, 1, 1, DIFFphi_p)\n      + double_derivative(i, j, k, 2, 2, DIFFphi_p)\n      + double_derivative(i, j, k, 3, 3, DIFFphi_p)\n    );\n  }\n\n  // phi = ln(xi)\n# pragma omp parallel for default(shared) private(i,j,k)\n  LOOP3(i,j,k) {\n    idx_t idx = NP_INDEX(i,j,k);\n    DIFFphi_a[idx] = log1p(DIFFphi_p[idx]);\n    DIFFphi_f[idx] = log1p(DIFFphi_p[idx]);\n    DIFFphi_p[idx] = log1p(DIFFphi_p[idx]);\n  }\n\n  // Make sure min density value > 0\n  // Set conserved density variable field\n  real_t min = 3.0/PI/8.0;\n  real_t max = min;\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n    real_t rho_FRW = 3.0/PI/8.0;\n    real_t DIFFr = DIFFr_a[idx];\n    real_t rho = rho_FRW + DIFFr;\n    // phi_FRW = 0\n    real_t DIFFphi = DIFFphi_a[idx];\n    // phi = DIFFphi\n    // DIFFK = 0\n\n    DIFFD_a[idx] =\n      rho_FRW*expm1(6.0*DIFFphi) + exp(6.0*DIFFphi)*DIFFr;\n\n    if(rho < min)\n    {\n      min = rho;\n    }\n    if(rho > max)\n    {\n      max = rho;\n    }\n    if(rho != rho)\n    {\n      iodata->log(\"Error: NaN energy density.\");\n      throw -1;\n    }\n  }\n\n  iodata->log( \"Minimum fluid density: \" + stringify(min) );\n  iodata->log( \"Maximum fluid density: \" + stringify(max) );\n  iodata->log( \"Average fluctuation density: \" + stringify(average(DIFFD_a)) );\n  iodata->log( \"Std.dev fluctuation density: \" + stringify(standard_deviation(DIFFD_a)) );\n  if(min < 0.0)\n  {\n    iodata->log(\"Error: negative density in some regions.\");\n    throw -1;\n  }\n\n# if USE_REFERENCE_FRW\n  // Set values in reference FRW integrator\n  real_t rho_FRW = 3.0/PI/8.0;\n  real_t K_frw = -sqrt(24.0*PI*rho_FRW);\n\n  auto & frw = bssn->frw;\n  frw->set_phi(0.0);\n  frw->set_K(K_frw);\n  frw->addFluid(rho_FRW, 0.0 /* w=0 */);\n# else\n  arr_t & DIFFK_p = *bssn->fields[\"DIFFK_p\"];\n  arr_t & DIFFK_a = *bssn->fields[\"DIFFK_a\"];\n  // add in FRW pieces to ICs\n  // phi is unchanged\n  // rho (D) and K get contribs\n  // w=0 fluid only\n# pragma omp parallel for default(shared) private(i,j,k)\n  LOOP3(i,j,k)\n  {\n    idx_t idx = NP_INDEX(i,j,k);\n    real_t rho_FRW = 3.0/PI/8.0;\n    real_t D_FRW = rho_FRW; // on initial slice\n\n    DIFFr_a[idx] += rho_FRW;\n\n    DIFFK_a[idx] = -sqrt(24.0*PI*rho_FRW);\n    DIFFK_p[idx] = -sqrt(24.0*PI*rho_FRW);\n\n    DIFFD_a[idx] += D_FRW;\n  }\n# endif\n}\n\n}\n", "meta": {"hexsha": "0281f81cf10c53ca4b1eeee6ead5dcfa987ee8e5", "size": 20790, "ext": "cc", "lang": "C++", "max_stars_repo_path": "components/static/static_ic.cc", "max_stars_repo_name": "LBJ-Wade/cosmograph", "max_stars_repo_head_hexsha": "dbd0cb1014666ad47fbbb48831989a1b79923eb0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-02-04T18:06:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-23T12:06:07.000Z", "max_issues_repo_path": "components/static/static_ic.cc", "max_issues_repo_name": "LBJ-Wade/cosmograph", "max_issues_repo_head_hexsha": "dbd0cb1014666ad47fbbb48831989a1b79923eb0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "components/static/static_ic.cc", "max_forks_repo_name": "LBJ-Wade/cosmograph", "max_forks_repo_head_hexsha": "dbd0cb1014666ad47fbbb48831989a1b79923eb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-10-21T20:29:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T06:57:11.000Z", "avg_line_length": 30.5286343612, "max_line_length": 128, "alphanum_fraction": 0.6076479076, "num_tokens": 7705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.4361847682315388}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <NTL/GF2X.h>\n#include <stdint.h>\n#include \"xsadd.h\"\n#include \"xsadd.c\" // to check static functions\n\nusing namespace NTL;\nusing namespace std;\n\nstatic void uztostring16(char * str, uz * x)\n{\n    int p = 0;\n    int first = 1;\n    for (int i = UZ_ARRAY_SIZE - 1; i >= 0; i--) {\n\tif (first) {\n\t    if (x->ar[i] != 0) {\n\t\tfirst = 0;\n\t\tsprintf(str, \"%x\", x->ar[i]);\n\t\tp = strlen(str);\n\t    }\n\t} else {\n\t    sprintf(str + p, \"%04x\", x->ar[i]);\n\t    p = p + 4;\n\t}\n    }\n    if (first) {\n\tstrcpy(str, \"0\");\n    }\n}\n\n//static const char * const characteristic_polynomial\n//= \"100000000008101840085118000000001\";\n\nvoid xsadd_calculate_jump_polynomial_debug(char *jump_str,\n\t\t\t\t\t   uint32_t mul_step,\n\t\t\t\t\t   const char * base_step)\n{\n    f2_polynomial jump_poly;\n    f2_polynomial charcteristic;\n    f2_polynomial tee;\n    uz base;\n    uz mul;\n    uz step;\n    char buff[200];\n\n    strtopolynomial(&charcteristic, characteristic_polynomial);\n    clear(&tee);\n    tee.ar[0] = 2;\n    string16touz(&base, base_step);\n    uint32touz(&mul, mul_step);\n\n    uztostring16(buff, &mul);\n    cout << \"mul:\" << buff << endl;\n    uztostring16(buff, &base);\n    cout << \"base:\" << buff << endl;\n    uz_mul(&step, &mul, &base);\n    uztostring16(buff, &step);\n    cout << \"step:\" << buff << endl;\n    polynomial_power_mod(&jump_poly, &tee, &step, &charcteristic);\n    polynomialtostr(jump_str, &jump_poly);\n}\n\nvoid xsadd_jump_by_polynomial_debug(xsadd_t *xsadd, const char * jump_str)\n{\n    f2_polynomial jump_poly;\n    xsadd_t work_z;\n    xsadd_t * work = &work_z;\n    cout << \"xsadd_jump_by_polynomial_debug: step1\" << endl;\n    *work = *xsadd;\n    for (int i = 0; i < 4; i++) {\n        work->state[i] = 0;\n    }\n    strtopolynomial(&jump_poly, jump_str);\n    cout << \"xsadd_jump_by_polynomial_debug: step2\" << endl;\n    char buff[200];\n    polynomialtostr(buff, &jump_poly);\n    cout << \"jump_poly:\" << buff << endl;\n    for (int i = 0; i < POLYNOMIAL_ARRAY_SIZE; i++) {\n\tfor (int j = 0; j < 32; j++) {\n\t    //cout << \"(i,j) = (\" << dec << i << \",\" << j << \")\" << endl;\n\t    uint32_t mask = 1 << j;\n\t    if ((jump_poly.ar[i] & mask) != 0) {\n\t\txsadd_add(work, xsadd);\n\t    }\n\t    xsadd_uint32(xsadd);\n\t}\n    }\n    cout << \"xsadd_jump_by_polynomial_debug: step3\" << endl;\n    *xsadd = *work;\n}\n\nvoid xsadd_jump_debug(xsadd_t *xsadd,\n\t\t      uint32_t mul_step,\n\t\t      const char * base_step)\n{\n    char jump_str[200];\n    cout << \"step1\" << endl;\n    xsadd_calculate_jump_polynomial_debug(jump_str, mul_step, base_step);\n    cout << \"jump_str:\" << jump_str << endl;\n    cout << \"step2\" << endl;\n    xsadd_jump_by_polynomial_debug(xsadd, jump_str);\n    cout << \"step3\" << endl;\n}\n\nvoid test_xsadd_jump_debug()\n{\n    const char * base_step = \"0\";\n    uint32_t step = 139;\n    uint32_t seed = 1791095845;\n    xsadd_t xsadd;\n    xsadd_init(&xsadd, seed);\n    xsadd_jump_debug(&xsadd, step, base_step);\n    cout << \"debug end\" << endl;\n}\n\nint main() {\n    test_xsadd_jump_debug();\n}\n", "meta": {"hexsha": "3e37e506b846b7fcf830daa4c87cbb2cc8a318bb", "size": 3001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/debug_xsadd_jump.cpp", "max_stars_repo_name": "mkt-matsumoto-lab/XSadd", "max_stars_repo_head_hexsha": "da4b241cd7ee69511fe227bf5e83ec4a90eb4f4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T02:15:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-12T00:11:45.000Z", "max_issues_repo_path": "test/debug_xsadd_jump.cpp", "max_issues_repo_name": "mkt-matsumoto-lab/XSadd", "max_issues_repo_head_hexsha": "da4b241cd7ee69511fe227bf5e83ec4a90eb4f4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/debug_xsadd_jump.cpp", "max_forks_repo_name": "mkt-matsumoto-lab/XSadd", "max_forks_repo_head_hexsha": "da4b241cd7ee69511fe227bf5e83ec4a90eb4f4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-06-23T08:58:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T00:12:38.000Z", "avg_line_length": 25.0083333333, "max_line_length": 74, "alphanum_fraction": 0.604131956, "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.43610905851973214}}
{"text": "/*\n * main_optimize.cpp\n * Date: 2013-01-28\n * Author: Karsten Ahnert (karsten.ahnert@gmx.de)\n */\n\n#define FUSION_MAX_VECTOR_SIZE 20\n\n#include <gpcxx/tree/basic_tree.hpp>\n#include <gpcxx/generate/uniform_symbol.hpp>\n#include <gpcxx/generate/node_generator.hpp>\n#include <gpcxx/generate/ramp.hpp>\n#include <gpcxx/operator/mutation.hpp>\n#include <gpcxx/operator/simple_mutation_strategy.hpp>\n#include <gpcxx/operator/random_selector.hpp>\n#include <gpcxx/operator/tournament_selector.hpp>\n#include <gpcxx/operator/crossover.hpp>\n#include <gpcxx/operator/one_point_crossover_strategy.hpp>\n#include <gpcxx/operator/reproduce.hpp>\n#include <gpcxx/eval/static_eval.hpp>\n#include <gpcxx/eval/regression_fitness.hpp>\n#include <gpcxx/evolve/static_pipeline.hpp>\n#include <gpcxx/io/best_individuals.hpp>\n#include <gpcxx/stat/population_statistics.hpp>\n#include <gpcxx/app/timer.hpp>\n#include <gpcxx/app/normalize.hpp>\n#include <gpcxx/app/generate_evenly_spaced_test_data.hpp>\n\n#include <boost/fusion/include/make_vector.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <random>\n#include <vector>\n#include <functional>\n\nconst std::string tab = \"\\t\";\n\nnamespace fusion = boost::fusion;\n\ntypedef double value_type;\ntypedef gpcxx::regression_training_data< value_type , 3 > trainings_data_type;\ntypedef std::mt19937 rng_type ;\ntypedef char symbol_type;\ntypedef std::array< value_type , 3 > eval_context_type;\ntypedef std::vector< value_type > fitness_type;\n\n\n\n\n\n\nnamespace pl = std::placeholders;\n\n\nint main( int argc , char *argv[] )\n{\n    rng_type rng;\n\n    trainings_data_type c = gpcxx::generate_evenly_spaced_test_data< 3 >( -5.0 , 5.0 + 0.1 , 0.4 , []( double x1 , double x2 , double x3 ) {\n                        return  1.0 / ( 1.0 + pow( x1 , -4.0 ) ) + 1.0 / ( 1.0 + pow( x2 , -4.0 ) ) + 1.0 / ( 1.0 + pow( x3 , -4.0 ) ); } );\n    gpcxx::normalize( c.y );\n    \n\n    std::ofstream fout1( \"testdata.dat\" );\n    for( size_t i=0 ; i<c.x[0].size() ; ++i )\n        fout1 << c.y[i] << \" \" << c.x[0][i] << \" \" << c.x[1][i] << \" \" << c.x[2][i] << \"\\n\";\n    fout1.close();\n    \n    auto eval = gpcxx::make_static_eval< value_type , symbol_type , eval_context_type >(\n        fusion::make_vector(\n            fusion::make_vector( 'x' , []( eval_context_type const& t ) { return t[0]; } )\n          , fusion::make_vector( 'y' , []( eval_context_type const& t ) { return t[1]; } )\n          , fusion::make_vector( 'z' , []( eval_context_type const& t ) { return t[2]; } )          \n          ) ,\n        fusion::make_vector(\n            fusion::make_vector( 's' , []( double v ) -> double { return std::sin( v ); } )\n          , fusion::make_vector( 'c' , []( double v ) -> double { return std::cos( v ); } ) \n          , fusion::make_vector( 'e' , []( double v ) -> double { return std::exp( v ); } ) \n          , fusion::make_vector( 'l' , []( double v ) -> double { return ( std::abs( v ) < 1.0e-20 ) ? log( 1.0e-20 ) : std::log( std::abs( v ) ); } ) \n          ) ,\n        fusion::make_vector(\n            fusion::make_vector( '+' , std::plus< double >() )\n          , fusion::make_vector( '-' , std::minus< double >() )\n          , fusion::make_vector( '*' , std::multiplies< double >() ) \n          , fusion::make_vector( '/' , std::divides< double >() ) \n          ) );\n    typedef decltype( eval ) eval_type;\n    typedef eval_type::node_attribute_type node_attribute_type;\n    \n    typedef gpcxx::basic_tree< node_attribute_type > tree_type;\n    typedef std::vector< tree_type > population_type;\n    typedef gpcxx::static_pipeline< population_type , fitness_type , rng_type > evolver_type;\n\n    \n    size_t population_size = 1000;\n    size_t generation_size = 20;\n    double number_elite = 1;\n    double mutation_rate = 0.0;\n    double crossover_rate = 0.6;\n    double reproduction_rate = 0.3;\n    size_t min_tree_height = 8 , max_tree_height = 8;\n    size_t tournament_size = 15;\n\n\n    // generators< rng_type > gen( rng );\n    auto terminal_gen = eval.get_terminal_symbol_distribution();\n    auto unary_gen = eval.get_unary_symbol_distribution();\n    auto binary_gen = eval.get_binary_symbol_distribution();\n    gpcxx::node_generator< node_attribute_type , rng_type , 3 > node_generator {\n        { 2.0 * double( terminal_gen.num_symbols() ) , 0 , terminal_gen } ,\n        { double( unary_gen.num_symbols() ) , 1 , unary_gen } ,\n        { double( binary_gen.num_symbols() ) , 2 , binary_gen } };\n\n    auto tree_generator = gpcxx::make_ramp( rng , node_generator , min_tree_height , max_tree_height , 0.5 );\n    \n\n    evolver_type evolver( number_elite , mutation_rate , crossover_rate , reproduction_rate , rng );\n    std::vector< double > fitness( population_size , 0.0 );\n    std::vector< tree_type > population( population_size );\n\n\n    auto fitness_f = gpcxx::regression_fitness< eval_type >( eval );\n    evolver.mutation_function() = gpcxx::make_mutation(\n        gpcxx::make_simple_mutation_strategy( rng , node_generator ) ,\n        gpcxx::make_tournament_selector( rng , tournament_size ) );\n    evolver.crossover_function() = gpcxx::make_crossover( \n        gpcxx::make_one_point_crossover_strategy( rng , max_tree_height ) ,\n        gpcxx::make_tournament_selector( rng , tournament_size ) );\n    evolver.reproduction_function() = gpcxx::make_reproduce( gpcxx::make_tournament_selector( rng , tournament_size ) );\n    \n    gpcxx::timer timer;\n\n\n\n    // initialize population with random trees and evaluate fitness\n    timer.restart();\n    for( size_t i=0 ; i<population.size() ; ++i )\n    {\n        tree_generator( population[i] );\n        fitness[i] = fitness_f( population[i] , c );\n    }\n    std::cout << gpcxx::indent( 0 ) << \"Generation time \" << timer.seconds() << std::endl;\n    std::cout << gpcxx::indent( 1 ) << \"Best individuals\" << std::endl << gpcxx::best_individuals( population , fitness , 1 , 10 ) << std::endl;\n    std::cout << gpcxx::indent( 1 ) << \"Statistics : \" << gpcxx::calc_population_statistics( population ) << std::endl;\n    std::cout << gpcxx::indent( 1 ) << std::endl << std::endl;\n\n    timer.restart();\n    for( size_t generation=1 ; generation<=generation_size ; ++generation )\n    {\n        gpcxx::timer iteration_timer;\n        iteration_timer.restart();\n        evolver.next_generation( population , fitness );\n        double evolve_time = iteration_timer.seconds();\n        iteration_timer.restart();\n        std::transform( population.begin() , population.end() , fitness.begin() , [&]( tree_type const &t ) { return fitness_f( t , c ); } );\n        double eval_time = iteration_timer.seconds();\n        \n        std::cout << gpcxx::indent( 0 ) << \"Generation \" << generation << std::endl;\n        std::cout << gpcxx::indent( 1 ) << \"Evolve time \" << evolve_time << std::endl;\n        std::cout << gpcxx::indent( 1 ) << \"Eval time \" << eval_time << std::endl;\n        std::cout << gpcxx::indent( 1 ) << \"Best individuals\" << std::endl << gpcxx::best_individuals( population , fitness , 2 , 10 ) << std::endl;\n        std::cout << gpcxx::indent( 1 ) << \"Statistics : \" << gpcxx::calc_population_statistics( population ) << std::endl << std::endl;\n    }\n    std::cout << \"Overall time : \" << timer.seconds() << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "2cdb5ef377eecf2391072722204c87d91530b341", "size": 7180, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "performance/pagie2/pagie2.cpp", "max_stars_repo_name": "gchoinka/gpcxx", "max_stars_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T08:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-12T07:28:54.000Z", "max_issues_repo_path": "performance/pagie2/pagie2.cpp", "max_issues_repo_name": "gchoinka/gpcxx", "max_issues_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-03-26T23:48:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-02-29T14:16:37.000Z", "max_forks_repo_path": "performance/pagie2/pagie2.cpp", "max_forks_repo_name": "gchoinka/gpcxx", "max_forks_repo_head_hexsha": "143398d8a12cdc39735e6ef50c3f8a44a6e6360f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T21:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-01T05:14:08.000Z", "avg_line_length": 42.4852071006, "max_line_length": 151, "alphanum_fraction": 0.6388579387, "num_tokens": 1986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.43602756815603877}}
{"text": "#include <iostream>\n#include <vector>\n#include <cmath>\n\n#include <boost/timer/timer.hpp>\n\n#include <poplar/DeviceManager.hpp>\n#include <poplar/IPUModel.hpp>\n\n#include <poplar/Engine.hpp>\n#include <poplar/Program.hpp>\n#include <poplin/codelets.hpp>\n#include <popops/ElementWise.hpp>\n#include <popops/codelets.hpp>\n#include <popops/ExprOp.hpp>\n#include <popops/Pad.hpp>\n#include <poputil/TileMapping.hpp>\n\n#include \"KalmanFilter.h\"\n\nusing namespace poplar;\nusing namespace poplar::program;\nusing namespace popops;\n\nfloat d = 1.0;\nfloat sigma = 10E-2;\nint N = 5;\nfloat z = 0.1;\nfloat x0 = 0.01;\nfloat theta0 = 10E-3;\n\nint main(int argc, char const *argv[]) {\n\n  Device dev = KalmanFilter::connectToIPU();\n\n  // IPUModel ipuModel;\n  // ipuModel.compileIPUCode = true;\n\n  // Device dev = ipuModel.createDevice();\n\n  Graph graph(dev.getTarget());\n\n  popops::addCodelets(graph);\n  poplin::addCodelets(graph);\n  graph.addCodelets(\"matrixInverseVertex.cpp\");\n  graph.addCodelets(\"matrixProductVertex.cpp\");\n  graph.addCodelets(\"scaledAddVertex.cpp\");\n  graph.addCodelets(\"packHitsVertex.cpp\");\n\n  int n_inputs = 1;\n  int batch_size = 1;\n\n  std::vector<Tensor> inputs(n_inputs);\n  std::vector<Tensor> inputs_batch(n_inputs);\n\n  for (uint i = 0; i < inputs.size(); i++) {\n\n    std::string iStr = std::to_string(i);\n\n    inputs[i] = graph.addVariable(FLOAT, {5, 2}, \"x_in\" + iStr);\n    inputs_batch[i] = graph.addVariable(FLOAT, {uint(batch_size), 5 * 2}, \"x_in_batch\" + iStr); // Check dims!\n    graph.setTileMapping(inputs[i], i);\n    graph.setTileMapping(inputs_batch[i], i);\n  }\n\n  Sequence preProg;\n\n  std::vector<DataStream> inStreams(n_inputs);\n  std::vector<Tensor> covs(n_inputs);\n  std::vector<Tensor> qs(n_inputs);\n  std::vector<Tensor> hs(n_inputs);\n  std::vector<Tensor> gs(n_inputs);\n  std::vector<Tensor> fs(n_inputs);\n  std::vector<Tensor> d(n_inputs);\n  std::vector<Tensor> dInit(n_inputs);\n  std::vector<Tensor> dSkip(n_inputs);\n  std::vector<Tensor> scatterInto(n_inputs);\n  std::vector<Tensor> loop(n_inputs);\n  std::vector<Tensor> zero(n_inputs);\n  std::vector<Tensor> one(n_inputs);\n  std::vector<Tensor> loop_batch(n_inputs);\n  std::vector<Tensor> hitThisLoop(n_inputs);\n\n  std::vector<Tensor> p_proj_all(n_inputs);\n  std::vector<Tensor> C_proj_all(n_inputs);\n\n  std::vector<Tensor> p_filt_all(n_inputs);\n  std::vector<Tensor> C_filt_all(n_inputs);\n\n  std::vector<Tensor> p_smooth(n_inputs);\n  std::vector<Tensor> C_smooth(n_inputs);\n\n  for (uint i = 0; i < covs.size(); i++) {\n\n    std::string iStr = std::to_string(i);\n\n    inStreams[i] = graph.addHostToDeviceFIFO(\"inStream\" + iStr, FLOAT, 5 * 2 * batch_size);\n    preProg.add(Copy(inStreams[i], inputs_batch[i]));\n\n  }\n\n  Sequence prog;\n\n  std::vector<Tensor> covFlat(covs.size());\n\n  for (uint i = 0; i < covs.size(); i++) {\n\n    std::string iStr = std::to_string(i);\n\n    loop[i] = graph.addVariable(INT, {1}, \"loop\");\n    graph.setTileMapping(loop[i], i);\n\n    scatterInto[i] = graph.addConstant<int>(INT, {1}, {0});\n    graph.setTileMapping(scatterInto[i], i);\n\n    zero[i] = graph.addConstant<int>(INT, {1}, {0});\n    graph.setTileMapping(zero[i], i);\n\n    one[i] = graph.addConstant<int>(INT, {1}, {1});\n    graph.setTileMapping(one[i], i);\n\n    prog.add(Copy(inputs_batch[i].slice(0, 1, 0).reshape({5, 2}), inputs[i]));\n\n    covFlat[i] = graph.addConstant<float>(FLOAT, {16, 1}, {sigma * sigma, 0., 0., 0.,\n                                                          0., M_PI, 0., 0.,\n                                                          0., 0., sigma * sigma, 0.,\n                                                          0., 0., 0., M_PI\n                                                          });\n\n    Tensor qFlat = graph.addConstant<float>(FLOAT, {16, 1}, {0.});\n\n    Tensor hFlat = graph.addConstant<float>(FLOAT, {16, 1}, {1., 0., 0., 0.,\n                                                             0., 0., 0., 0.,\n                                                             0., 0., 1., 0.,\n                                                             0., 0., 0., 0.});\n    Tensor fFlat = graph.addConstant<float>(FLOAT, {16, 1}, {1., 1., 0., 0.,\n                                                             0., 1., 0., 0.,\n                                                             0., 0., 1., 1.,\n                                                             0., 0., 0., 1.});\n    Tensor gFlat = graph.addConstant<float>(FLOAT, {16, 1}, {float(1.0)/(sigma * sigma), 0., 0., 0.,\n                                                             0, 0., 0., 0.,\n                                                             0, 0., float(1.0)/(sigma * sigma), 0.,\n                                                             0, 0., 0., 0.,\n                                                             });\n\n    d[i] = graph.addVariable(FLOAT, {1, 1}, \"d\" + iStr);\n    dInit[i] = graph.addConstant<float>(FLOAT, {1, 1}, {1.});\n    dSkip[i] = graph.addConstant<float>(FLOAT, {1, 1}, {2.});\n\n    prog.add(Copy(dInit[i], d[i]));\n\n    covs[i] = graph.addVariable(FLOAT, {4, 4}, \"cov\" + iStr);\n    prog.add(Copy(covFlat[i].reshape({4, 4}), covs[i]));\n\n    p_proj_all[i] = graph.addVariable(FLOAT, {5, 4, 1}, \"p_proj_all\" + iStr);\n    C_proj_all[i] = graph.addVariable(FLOAT, {5, 4, 4}, \"C_proj_all\" + iStr);\n\n    p_filt_all[i] = graph.addVariable(FLOAT, {5, 4, 1}, \"p_filt_all\" + iStr);\n    C_filt_all[i] = graph.addVariable(FLOAT, {5, 4, 4}, \"C_filt_all\" + iStr);\n\n    p_smooth[i] = graph.addVariable(FLOAT, {4, 1}, \"p_smooth\" + iStr);\n    C_smooth[i] = graph.addVariable(FLOAT, {4, 4}, \"C_smooth\" + iStr);\n\n    graph.setTileMapping(p_proj_all[i], i);\n    graph.setTileMapping(C_proj_all[i], i);\n    graph.setTileMapping(p_filt_all[i], i);\n    graph.setTileMapping(C_filt_all[i], i);\n\n    graph.setTileMapping(p_smooth[i], i);\n    graph.setTileMapping(C_smooth[i], i);\n\n    qs[i] = qFlat.reshape({4, 4});\n\n    hs[i] = hFlat.reshape({4, 4});\n    gs[i] = gFlat.reshape({4, 4});\n    fs[i] = fFlat.reshape({4, 4});\n\n    graph.setTileMapping(covFlat[i], i);\n    graph.setTileMapping(qFlat, i);\n    graph.setTileMapping(d[i], i);\n    graph.setTileMapping(dInit[i], i);\n    graph.setTileMapping(dSkip[i], i);\n\n    graph.setTileMapping(covs[i], i);\n    graph.setTileMapping(qs[i], i);\n\n    graph.setTileMapping(gFlat, i);\n    graph.setTileMapping(hFlat, i);\n    graph.setTileMapping(fFlat, i);\n    graph.setTileMapping(hs[i], i);\n    graph.setTileMapping(gs[i], i);\n    graph.setTileMapping(fs[i], i);\n  }\n\n  // Init p with hits\n  auto [packIterationTensorsInit, ps] = KalmanFilter::packIterationTensors(graph, loop, scatterInto, inputs);\n\n  prog.add(packIterationTensorsInit);\n\n  // Prepare hits for each loop\n  auto [packIterationTensorsProg, hits] = KalmanFilter::packIterationTensors(graph, loop, scatterInto, inputs);\n\n  auto [projProg, p_proj, C_proj] = KalmanFilter::project(graph, ps, covs, fs, qs);\n\n  auto [filterSeq, outP, C] = KalmanFilter::filter(graph, hs, gs, hits, p_proj, C_proj);\n\n  std::vector<Tensor> p_proj_chi2(ps.size());\n  std::vector<Tensor> p_filt_chi2(ps.size());\n  std::vector<Tensor> C_proj_chi2(ps.size());\n\n  std::vector<Tensor> chiSqThreshold(ps.size());\n\n  // For chi2 calc, test\n  for (uint i = 0; i < ps.size(); i++) {\n\n    std::string iStr = std::to_string(i);\n\n    p_proj_chi2[i] = graph.addVariable(FLOAT, {4, 1}, \"p_proj_chi2\" + iStr);\n    graph.setTileMapping(p_proj_chi2[i], i);\n\n    p_filt_chi2[i] = graph.addVariable(FLOAT, {4, 1}, \"p_filt_chi2\" + iStr);\n    graph.setTileMapping(p_filt_chi2[i], i);\n\n    C_proj_chi2[i] = graph.addVariable(FLOAT, {4, 4}, \"C_proj_chi2\" + iStr);\n    graph.setTileMapping(C_proj_chi2[i], i);\n\n    chiSqThreshold[i] = graph.addConstant<float>(FLOAT, {1}, {0.4});\n    graph.setTileMapping(chiSqThreshold[i], i);\n\n  }\n\n  // ChiSq computation\n\n  auto [resSeq, res] = KalmanFilter::calcResidual(graph, hits, p_filt_chi2, hs);\n\n  auto [chiSqSeq, chiSq] = KalmanFilter::calcChiSq(graph, res, gs, C_proj_chi2, p_proj_chi2, p_filt_chi2);\n\n  auto [chiSqTestSeq, chiSqTestPred] = KalmanFilter::chiSqTest(graph, chiSq, chiSqThreshold);\n\n  // Update loop index\n  Sequence updateIterator;\n\n  for (uint i = 0; i < inputs.size(); i++) {\n\n    auto [computeIterate, itr] = KalmanFilter::iterate(graph, loop[i], i);\n    updateIterator.add(Execute(computeIterate));\n    updateIterator.add(Copy(itr, loop[i]));\n\n  }\n\n  Sequence planeLoop;\n\n  planeLoop.add(packIterationTensorsProg);\n\n  // For EKF\n  // planeLoop.add(stateProg);\n  // planeLoop.add(jacProg);\n\n  planeLoop.add(projProg);\n  planeLoop.add(filterSeq);\n\n  // Save proj and filt states for smoothing step\n\n  for (uint i = 0; i < ps.size(); i++) {\n\n    auto [append_p_proj_Seq, p_proj_new] = KalmanFilter::appendTo(graph, p_proj[i], loop[i], p_proj_all[i], i);\n    auto [append_C_proj_Seq, C_proj_new] = KalmanFilter::appendTo(graph, C_proj[i], loop[i], C_proj_all[i], i);\n    auto [append_p_filt_Seq, p_filt_new] = KalmanFilter::appendTo(graph, outP[i], loop[i], p_filt_all[i], i);\n    auto [append_C_filt_Seq, C_filt_new] = KalmanFilter::appendTo(graph, C[i], loop[i], C_filt_all[i], i);\n\n    planeLoop.add(Execute(append_p_proj_Seq));\n    planeLoop.add(Execute(append_C_proj_Seq));\n    planeLoop.add(Execute(append_p_filt_Seq));\n    planeLoop.add(Execute(append_C_filt_Seq));\n\n    planeLoop.add(Copy(p_proj_new, p_proj_all[i]));\n    planeLoop.add(Copy(C_proj_new, C_proj_all[i]));\n    planeLoop.add(Copy(p_filt_new, p_filt_all[i]));\n    planeLoop.add(Copy(C_filt_new, C_filt_all[i]));\n\n  }\n\n  // For chi2 calc, test\n  // for (uint i = 0; i < ps.size(); i++) {\n  //\n  //   planeLoop.add(Copy(p_proj[i], p_proj_chi2[i]));\n  //   planeLoop.add(Copy(outP[i], p_filt_chi2[i]));\n  //   planeLoop.add(Copy(C_proj[i], C_proj_chi2[i]));\n  //\n  // }\n\n  // planeLoop.add(resSeq);\n  // planeLoop.add(chiSqSeq);\n  // planeLoop.add(chiSqTestSeq);\n\n  planeLoop.add(updateIterator);\n\n  // Set up p for next projection, using p_filt\n  // Set up covs for next projection, using C(_filt)\n  for (uint i = 0; i < inputs.size(); i++) {\n    planeLoop.add(Copy(outP[i], ps[i]));\n    planeLoop.add(Copy(C[i], covs[i]));\n  }\n\n  // for (uint i = 0; i < inputs.size(); i++) {\n  //\n  //   auto [skipSwitchSeq, switchP, switchC, outD] = skipSwitch(graph, ps[i], covs[i],\n  //                                                     outP[i], C[i],\n  //                                                     chiSq[i],\n  //                                                     i);\n  //   planeLoop.add(Execute(skipSwitchSeq));\n  //   planeLoop.add(Copy(switchP, ps[i]));\n  //   planeLoop.add(Copy(switchC, covs[i]));\n  //   planeLoop.add(Copy(outD, d[i]));\n  // }\n\n  prog.add(poplar::program::Repeat(5, planeLoop));\n\n  for (uint i = 0; i < inputs.size(); i++) {\n    // Reset iterator for smoothing step\n    prog.add(Copy(zero[i], loop[i]));\n\n    // Copy last filtered state to initial smoothing state\n    prog.add(Copy(outP[i], p_smooth[i]));\n    prog.add(Copy(C[i], C_smooth[i]));\n  }\n\n  std::vector<Tensor> p_proj_smooth(inputs.size());\n  std::vector<Tensor> C_proj_smooth(inputs.size());\n  std::vector<Tensor> p_filt_smooth(inputs.size());\n  std::vector<Tensor> C_filt_smooth(inputs.size());\n\n  Sequence smoothLoop;\n\n  for (uint i = 0; i < inputs.size(); i++) {\n\n    // Offset iterator for filtered states (when starting from idx == 0)\n    auto [loopFiltSeq, loopFilt] = KalmanFilter::iterate(graph, loop[i], i);\n    smoothLoop.add(Execute(loopFiltSeq));\n\n    auto [sm_p_proj_seq, p_proj] = KalmanFilter::smoothingState(graph, p_proj_all[i], loop[i], i);\n    auto [sm_C_proj_seq, C_proj] = KalmanFilter::smoothingState(graph, C_proj_all[i], loop[i], i);\n    auto [sm_p_filt_seq, p_filt] = KalmanFilter::smoothingState(graph, p_filt_all[i], loopFilt, i);\n    auto [sm_C_filt_seq, C_filt] = KalmanFilter::smoothingState(graph, C_filt_all[i], loopFilt, i);\n\n    smoothLoop.add(Execute(sm_p_proj_seq));\n    smoothLoop.add(Execute(sm_C_proj_seq));\n    smoothLoop.add(Execute(sm_p_filt_seq));\n    smoothLoop.add(Execute(sm_C_filt_seq));\n\n    p_proj_smooth[i] = p_proj;\n    C_proj_smooth[i] = C_proj;\n    p_filt_smooth[i] = p_filt;\n    C_filt_smooth[i] = C_filt;\n\n  }\n\n  auto [smoothSeq, p_smooth_new, C_smooth_new] = KalmanFilter::smooth(graph, p_smooth, C_smooth, p_filt_smooth, C_filt_smooth, p_proj_smooth, C_proj_smooth, fs);\n\n  smoothLoop.add(smoothSeq);\n\n  smoothLoop.add(PrintTensor(\"p_smooth_new\", p_smooth_new[0]));\n\n  for (uint i = 0; i < inputs.size(); i++) {\n\n    // Propagate last smoothed state\n    smoothLoop.add(Copy(p_smooth_new[i], p_smooth[i]));\n    smoothLoop.add(Copy(C_smooth_new[i], C_smooth[i]));\n\n  }\n\n  smoothLoop.add(updateIterator);\n\n  prog.add(poplar::program::Repeat(4, smoothLoop));\n\n  // After loop over planes, for the next in the batch:\n\n  for (uint i = 0; i < inputs.size(); i++) {\n    // Reset plane iterator for next batch\n    prog.add(Copy(zero[i], loop[i]));\n  }\n\n  Sequence progRepeat;\n  progRepeat.add(poplar::program::Repeat(batch_size, prog));\n\n  Sequence progMain;\n  progMain.add(preProg);\n  progMain.add(progRepeat);\n\n  // Engine engine(graph, prog);\n  Engine engine(graph, progMain);\n  engine.load(dev);\n\n  // Test input\n  std::vector<float> v1 = {\n    -0.02062073, -0.12062073,\n    -0.02062073, -0.22062073,\n    -0.12062073, -0.42062073,\n    -0.12062073, -0.52062073,\n    -0.22062073, -0.62062073,\n  };\n\n  std::vector<std::vector<float>> vs;\n  for (uint i = 0; i < inputs.size(); i++) {\n    // Instead of 1 * 5 inputs, N * 5 inputs\n    std::vector<float> v10;\n    for (uint j = 0; j < batch_size; j++) {\n      v10.insert(std::end(v10), std::begin(v1), std::end(v1));\n    }\n    vs.push_back(v10);\n  }\n\n  for (uint i = 0; i < inputs.size(); i++) {\n    engine.connectStream(inStreams[i], &vs[i][0], &vs[i][5 * 2 * batch_size]);\n  }\n\n  {\n  boost::timer::auto_cpu_timer t;\n  engine.run(0);\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "334cf53f8be53255ae384a357f278aacc08489b2", "size": 13787, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kalman_filter_poplar/execute-kalman-filter.cpp", "max_stars_repo_name": "dpohanlon/IPU4HEP", "max_stars_repo_head_hexsha": "ab8897160edac5dba10c2d85dc425706e7156783", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T15:17:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-08T15:17:20.000Z", "max_issues_repo_path": "kalman_filter_poplar/execute-kalman-filter.cpp", "max_issues_repo_name": "dpohanlon/IPU4HEP", "max_issues_repo_head_hexsha": "ab8897160edac5dba10c2d85dc425706e7156783", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kalman_filter_poplar/execute-kalman-filter.cpp", "max_forks_repo_name": "dpohanlon/IPU4HEP", "max_forks_repo_head_hexsha": "ab8897160edac5dba10c2d85dc425706e7156783", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-08-11T15:30:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T14:58:43.000Z", "avg_line_length": 32.516509434, "max_line_length": 161, "alphanum_fraction": 0.6046275477, "num_tokens": 4074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.435959912393955}}
{"text": "/*\n * Copyright (c) 2019 Opticks Team. All Rights Reserved.\n *\n * This file is part of Opticks\n * (see https://bitbucket.org/simoncblyth/opticks).\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); \n * you may not use this file except in compliance with the License.  \n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software \n * distributed under the License is distributed on an \"AS IS\" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  \n * See the License for the specific language governing permissions and \n * limitations under the License.\n */\n\n#include <cmath>\n#include <cassert>\n#include <cmath>\n#include <cstring>\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"OpticksCSG.h\"\n\n#include \"NPrism.hpp\"\n#include \"NBBox.hpp\"\n#include \"NPlane.hpp\"\n#include \"NPart.hpp\"\n\n\nnprism::nprism(float apex_angle_degrees, float height_mm, float depth_mm, float fallback_mm)\n{\n    param.f.x = apex_angle_degrees  ;\n    param.f.y = height_mm  ;\n    param.f.z = depth_mm  ;\n    param.f.w = fallback_mm  ;\n}\n\nnprism::nprism(const nquad& param_)\n{\n    param = param_ ;\n}\n\nfloat nprism::height()\n{\n    return param.f.y > 0.f ? param.f.y : param.f.w ; \n}\nfloat nprism::depth()\n{\n    return param.f.z > 0.f ? param.f.z : param.f.w ; \n}\nfloat nprism::hwidth()\n{\n    float pi = boost::math::constants::pi<float>() ;\n    return height()*tan((pi/180.f)*param.f.x/2.0f) ;\n}\n\n\nvoid nprism::dump(const char* msg)\n{\n    param.dump(msg);\n}\n\nnbbox nprism::bbox()\n{\n    float h  = height();\n    float hw = hwidth();\n    float d  = depth();\n\n    nbbox bb ;\n    bb.min = {-hw,0.f,-d/2.f } ;\n    bb.max = { hw,  h, d/2.f } ;\n\n    return bb ; \n}\n\n\nnpart nprism::part()\n{\n    // hmm more dupe of hemi-pmt.cu/make_prism\n    // but if could somehow make vector types appear \n    // the same could use same code with CUDA ?\n\n    nbbox bb = bbox();\n\n    npart p ; \n    p.zero();            \n    p.setParam(param) ; \n    p.setTypeCode(CSG_PRISM); \n    p.setBBox(bb);\n\n    return p ; \n}\n\n\n", "meta": {"hexsha": "0b04d10b34169c61332e8a82f353efe8d1fc81b2", "size": 2127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "npy/NPrism.cpp", "max_stars_repo_name": "hanswenzel/opticks", "max_stars_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2020-07-05T02:39:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T18:52:44.000Z", "max_issues_repo_path": "npy/NPrism.cpp", "max_issues_repo_name": "hanswenzel/opticks", "max_issues_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "npy/NPrism.cpp", "max_forks_repo_name": "hanswenzel/opticks", "max_forks_repo_head_hexsha": "b75b5929b6cf36a5eedeffb3031af2920f75f9f0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-03T20:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T07:42:21.000Z", "avg_line_length": 21.27, "max_line_length": 92, "alphanum_fraction": 0.6426892337, "num_tokens": 601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4359599060253633}}
{"text": "\n#include \"matrix_product_dense.h\"\n#include <optional>\n#include <Eigen/Core>\n#include <Eigen/LU>\n\ntemplate<typename T> using MatrixType  = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;\ntemplate<typename T> using VectorType  = Eigen::Matrix<T, Eigen::Dynamic, 1, Eigen::ColMajor>;\ntemplate<typename T> using VectorTypeT = Eigen::Matrix<T, 1, Eigen::Dynamic, Eigen::RowMajor>;\n\nnamespace dense_lu {\n    std::optional<Eigen::PartialPivLU<MatrixType<double>>>               lu_real       = std::nullopt;\n    std::optional<Eigen::PartialPivLU<MatrixType<std::complex<double>>>> lu_cplx       = std::nullopt;\n\n    void reset(){\n        lu_real.reset();\n        lu_cplx.reset();\n    }\n    template<typename Scalar>\n    void init(){\n        if constexpr (std::is_same_v<Scalar,double>)\n            dense_lu::lu_real = Eigen::PartialPivLU<MatrixType<Scalar>>();\n        if constexpr (std::is_same_v<Scalar,std::complex<double>>)\n            dense_lu::lu_cplx = Eigen::PartialPivLU<MatrixType<Scalar>>();\n    }\n}\n\n\ntemplate<typename Scalar>\nDenseMatrixProduct<Scalar>::~DenseMatrixProduct(){\n    dense_lu::reset();\n}\n\n\n\n// Pointer to data constructor, copies the matrix into an internal Eigen matrix.\ntemplate<typename Scalar>\nDenseMatrixProduct<Scalar>::DenseMatrixProduct(const Scalar *const A_, const int L_,const bool copy_data, const eigutils::eigSetting::Form form_, const eigutils::eigSetting::Side side_)\n    : A_ptr(A_), L(L_), form(form_), side(side_) {\n    if (copy_data){\n        A_stl.resize(L*L);\n        std::copy(A_ptr,A_ptr + L*L, A_stl.begin());\n        A_ptr = A_stl.data();\n    }\n    dense_lu::init<Scalar>();\n    init_profiling();\n}\n\n\ntemplate<typename Scalar>\nvoid DenseMatrixProduct<Scalar>::print() const {\n    Eigen::Map<const MatrixType<Scalar>> A_matrix (A_ptr, L, L);\n    std::cout << \"A_matrix: \\n\" << A_matrix << std::endl;\n}\n\n// Function definitions\n\ntemplate<typename Scalar>\nvoid DenseMatrixProduct<Scalar>::FactorOP()\n\n/*  Partial pivot LU decomposition\n *  Factors P(A-sigma*I) = LU\n */\n{\n    if(readyFactorOp) { return; }\n    std::cout << \"Starting LU \\n\";\n    Eigen::Map<const MatrixType<Scalar>> A_matrix (A_ptr, L, L);\n\n    t_factorOp.tic();\n    assert(readyShift and \"Shift value sigma has not been set.\");\n\n    if constexpr(std::is_same_v<Scalar, double>) {\n        dense_lu::lu_real = Eigen::PartialPivLU<MatrixType<Scalar>>();\n        dense_lu::lu_real.value().compute(A_matrix - sigmaR * Eigen::MatrixXd::Identity(L, L));\n    }\n    if constexpr(std::is_same_v<Scalar, std::complex<double>>) {\n        Scalar sigma = std::complex<double>(sigmaR, sigmaI);\n        dense_lu::lu_cplx = Eigen::PartialPivLU<MatrixType<Scalar>>();\n        dense_lu::lu_cplx.value().compute(A_matrix - sigma * Eigen::MatrixXd::Identity(L, L));\n    }\n\n    readyFactorOp = true;\n    t_factorOp.toc();\n    std::cout << \"Finished LU \\n\";\n    std::cout << \"Time LU Op [ms]: \" << std::fixed << std::setprecision(3) << t_factorOp.get_last_time_interval() * 1000 << '\\n';\n}\n\ntemplate<typename Scalar>\nvoid DenseMatrixProduct<Scalar>::MultOPv(Scalar *x_in_ptr, Scalar *x_out_ptr) {\n    using namespace eigutils::eigSetting;\n    assert(readyFactorOp and \"FactorOp() has not been run yet.\");\n    switch(side) {\n        case Side::R: {\n            Eigen::Map<VectorType<Scalar>> x_in(x_in_ptr, L);\n            Eigen::Map<VectorType<Scalar>> x_out(x_out_ptr, L);\n            if constexpr(std::is_same_v<Scalar, double>)\n                x_out.noalias() = dense_lu::lu_real.value().solve(x_in);\n            if constexpr(std::is_same_v<Scalar, std::complex<double>>)\n                x_out.noalias() = dense_lu::lu_cplx.value().solve(x_in);\n            break;\n        }\n        case Side::L: {\n            Eigen::Map<VectorTypeT<Scalar>> x_in(x_in_ptr, L);\n            Eigen::Map<VectorTypeT<Scalar>> x_out(x_out_ptr, L);\n            if constexpr(std::is_same_v<Scalar, double>)\n                x_out.noalias() = x_in * dense_lu::lu_real.value().inverse();\n            if constexpr(std::is_same_v<Scalar, std::complex<double>>)\n                x_out.noalias() = x_in * dense_lu::lu_cplx.value().inverse();\n            break;\n        }\n    }\n    counter++;\n}\n\ntemplate<typename Scalar>\nvoid DenseMatrixProduct<Scalar>::MultAx(Scalar *x_in, Scalar *x_out) {\n    using namespace eigutils::eigSetting;\n    Eigen::Map<const MatrixType<Scalar>> A_matrix (A_ptr, L, L);\n    switch(form) {\n        case Form::NONSYMMETRIC:\n            switch(side) {\n                case Side::R: {\n                    Eigen::Map<VectorType<Scalar>> x_vec_in(x_in, L);\n                    Eigen::Map<VectorType<Scalar>> x_vec_out(x_out, L);\n                    x_vec_out.noalias() = A_matrix * x_vec_in;\n                    break;\n                }\n                case Side::L: {\n                    Eigen::Map<VectorTypeT<Scalar>> x_vec_in(x_in, L);\n                    Eigen::Map<VectorTypeT<Scalar>> x_vec_out(x_out, L);\n                    x_vec_out.noalias() = x_vec_in * A_matrix;\n                    break;\n                }\n            }\n            break;\n        case Form::SYMMETRIC: {\n            Eigen::Map<VectorType<Scalar>> x_vec_in(x_in, L);\n            Eigen::Map<VectorType<Scalar>> x_vec_out(x_out, L);\n            x_vec_out.noalias() = A_matrix.template selfadjointView<Eigen::Upper>() * x_vec_in;\n            break;\n        }\n    }\n    counter++;\n}\n\n// Explicit instantiations\ntemplate class DenseMatrixProduct<double>;\ntemplate class DenseMatrixProduct<std::complex<double>>;\n", "meta": {"hexsha": "211e6ecba7c44cafbdabdc8ccf6117389e227460", "size": 5489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unused/eigsolver_backup/arpack_extra/matrix_product_dense.cpp", "max_stars_repo_name": "DavidAce/DMRG", "max_stars_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-31T22:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:45:27.000Z", "max_issues_repo_path": "unused/eigsolver_backup/arpack_extra/matrix_product_dense.cpp", "max_issues_repo_name": "DavidAce/DMRG", "max_issues_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unused/eigsolver_backup/arpack_extra/matrix_product_dense.cpp", "max_forks_repo_name": "DavidAce/DMRG", "max_forks_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T00:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-16T00:27:56.000Z", "avg_line_length": 36.8389261745, "max_line_length": 185, "alphanum_fraction": 0.6199672071, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.43593878458351537}}
{"text": "/**\n * @file\n * @brief Implementation of linear Lagrangian finite elements for the Dirichlet\n *        problem for the Laplacian\n * @author Ralf Hiptmair\n * @date   October 2018\n * @copyright MIT License\n */\n\n#include <cmath>\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include <lf/assemble/assemble.h>\n#include <lf/geometry/geometry.h>\n#include <lf/io/io.h>\n#include <lf/mesh/hybrid2d/hybrid2d.h>\n#include <lf/refinement/refinement.h>\n#include \"lf/fe/fe.h\"\n#include \"lf/mesh/test_utils/test_meshes.h\"\n#include \"lf/mesh/utils/utils.h\"\n\nstatic unsigned int dbg_ctrl = 0;\nconst unsigned int dbg_dofh = 1;\nconst unsigned int dbg_mesh = 2;\nconst unsigned int dbg_mat = 4;\nconst unsigned int dbg_vec = 8;\nconst unsigned int dbg_bdf = 16;\nconst unsigned int dbg_elim = 32;\nconst unsigned int dbg_basic = 64;\nconst unsigned int dbg_trp = 128;\n\n/**\n * @brief Build a vector of boundary flags for degrees of freedom\n *\n * @param dofh Local-to-global mapper managing indexing for shape\n * functions\n * @return boolean vector of boundary flags, whose length agrees with the\n *         number of global shape functions managed by `dofh`.\n *\n * Every global shape functions belongs to a unique mesh entity. If that\n * entity is contained in the boundary of the mesh, then the flag array\n * entry with the index of the global shape function is set to `true`,\n * otherwise to `false`.\n */\nstd::vector<bool> flagBoundaryDOFs(const lf::assemble::DofHandler &dofh) {\n  const lf::base::size_type N{dofh.NoDofs()};\n  // Flag all entities on the boundary\n  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(dofh.Mesh())};\n  // Run through all global shape functions and check whether\n  // they are associated with an entity on the boundary. Store\n  // this information in a boolean vector\n  std::vector<bool> tmp_bd_flags(N, false);\n  for (lf::assemble::gdof_idx_t dofnum = 0; dofnum < N; ++dofnum) {\n    const lf::mesh::Entity &dof_entity{dofh.Entity(dofnum)};\n    tmp_bd_flags[dofnum] = bd_flags(dof_entity);\n    SWITCHEDSTATEMENT(\n        dbg_ctrl, dbg_bdf,\n        std::cout << \"FBD: dof \" << dofnum << \"@ \" << dof_entity << \" [\"\n                  << dofh.Mesh()->Index(dof_entity) << \"] \";\n        if (tmp_bd_flags[dofnum]) { std::cout << \"ON BOUNDARY\"; } std::cout\n        << std::endl);\n  }\n  return tmp_bd_flags;\n}\n\n/** @brief Eliminate degrees of freedom located on the boundary\n *\n * No longer in use. Replaced with lf::assemble::fix_flagged_solution_components\n */\nvoid eliminateBoundaryDofs(const std::vector<bool> &tmp_bd_flags,\n                           lf::assemble::COOMatrix<double> *A) {\n  const lf::base::size_type N = tmp_bd_flags.size();\n  LF_ASSERT_MSG((A->cols() == N) && (A->rows() == N),\n                \"Matrix dimension mismath\");\n\n  // Remove rows associated with dofs on the boundary\n  auto new_last = std::remove_if(\n      A->triplets().begin(), A->triplets().end(),\n      [&tmp_bd_flags](lf::assemble::COOMatrix<double>::Triplet &triplet) {\n        SWITCHEDSTATEMENT(dbg_ctrl, dbg_elim, if (tmp_bd_flags[triplet.row()]) {\n          std::cout << \"EBD: removing \" << triplet.row() << ',' << triplet.col()\n                    << \"[\" << triplet.value() << \"]\" << std::endl;\n        });\n        return tmp_bd_flags[triplet.row()];\n      });\n  A->triplets().erase(new_last, A->triplets().end());\n  // Add unit diagonal entries to rows belonging to dofs on the boundary\n  for (lf::assemble::gdof_idx_t dofnum = 0; dofnum < N; ++dofnum) {\n    if (tmp_bd_flags[dofnum]) {\n      A->AddToEntry(dofnum, dofnum, 1.0);\n    }\n  }\n}\n\n/** @brief Insert sampled values from Dirichlet data into right hand side\n * vector\n *\n */\nvoid insertDirichletDataRHS(const std::vector<bool> &tmp_bd_flags,\n                            Eigen::VectorXd *rhs,\n                            const Eigen::VectorXd &dirichlet_values) {\n  const lf::base::size_type N = tmp_bd_flags.size();\n  LF_VERIFY_MSG((rhs->size() == N), \"rhs vector size mismatch\");\n  LF_VERIFY_MSG((dirichlet_values.size() == N), \"data vector size mismatch\");\n\n  for (lf::assemble::gdof_idx_t dofnum = 0; dofnum < N; ++dofnum) {\n    if (tmp_bd_flags[dofnum]) {\n      // Shape function associated with the boundary\n      (*rhs)[dofnum] = dirichlet_values[dofnum];\n    }\n  }\n}\n\n/** @brief Solves Dirichlet problem for the Laplacian\n *\n * @tparam SOLFUNC functor providing boundary values/exact solution\n * @tparam RHSFUNC functor for right hand side source function\n * @param mesh reference to the mesh on which the FE solution is to be\n * computed\n * @param u functor object for solution, also used to sample Dirichlet\n * data\n * @param f object supplying right-hand-side source function\n *\n * @return L2 norm of the nodal error, which is just the L2 norm of the\n *         discretization error approximated by means of the the 2D\n * trapezoidal rule.\n */\ntemplate <typename SOLFUNC, typename RHSFUNC>\ndouble L2ErrorLinearFEDirichletLaplacian(\n    const std::shared_ptr<const lf::mesh::Mesh> &mesh_p, SOLFUNC &&u,\n    RHSFUNC &&f) {\n  LF_ASSERT_MSG(mesh_p != nullptr, \"Invalid mesh pointer\");\n  LF_ASSERT_MSG((mesh_p->DimMesh() == 2) && (mesh_p->DimWorld() == 2),\n                \"For 2D planar meshes only!\");\n  // Debugging output\n  SWITCHEDSTATEMENT(\n      dbg_ctrl, dbg_basic,\n      std::cout << \"Dirichlet Laplacian: Linear FE L2 error on mesh with \"\n                << mesh_p->Size(0) << \" cells, \" << mesh_p->Size(1)\n                << \" edges, \" << mesh_p->Size(2) << \" nodes\" << std::endl;)\n  SWITCHEDSTATEMENT(\n      dbg_ctrl, dbg_mesh,\n      const int tmp_mesh_ctrl = lf::mesh::hybrid2d::Mesh::output_ctrl_;\n      lf::mesh::hybrid2d::Mesh::output_ctrl_ = 100;\n      lf::mesh::utils::PrintInfo(*mesh_p, std::cout);\n      lf::mesh::hybrid2d::Mesh::output_ctrl_ = tmp_mesh_ctrl);\n  // Initialize objects for local computations\n  lf::fe::LinearFELaplaceElementMatrix loc_mat_laplace{};\n  lf::fe::LinearFELocalLoadVector<double, decltype(f)> loc_vec_sample(f);\n  // Initialization of index mapping for linear finite elements\n  lf::assemble::UniformFEDofHandler loc_glob_map(\n      mesh_p, {{lf::base::RefEl::kPoint(), 1}});\n  SWITCHEDSTATEMENT(dbg_ctrl, dbg_dofh,\n                    std::cout << loc_glob_map << std::endl;);\n  // Dimension of finite element space\n  const lf::assemble::size_type N_dofs(loc_glob_map.NoDofs());\n  // Matrix in triplet format holding Galerkin matrix\n  lf::assemble::COOMatrix<double> mat(N_dofs, N_dofs);\n  // Building the Galerkin matrix (trial space = test space)\n  // This Galerkin matrix is oblivious of Dirichlet boundary conditions\n  mat = lf::assemble::AssembleMatrixLocally<lf::assemble::COOMatrix<double>>(\n      0, loc_glob_map, loc_mat_laplace);\n  // Debugging output\n  SWITCHEDSTATEMENT(dbg_ctrl, dbg_trp, mat.PrintInfo(std::cout));\n  SWITCHEDSTATEMENT(dbg_ctrl, dbg_mat,\n                    std::cout << \"Full \" << mat.rows() << 'x' << mat.cols()\n                              << \" stiffness matrix, \" << mat.triplets().size()\n                              << \" tripets:\\n\"\n                              << mat.makeDense() << std::endl);\n\n  // Filling the right-hand-side vector\n  auto rhsvec = lf::assemble::AssembleVectorLocally<Eigen::VectorXd>(\n      0, loc_glob_map, loc_vec_sample);\n  // Sample Dirichlet date from the exact solution\n  Eigen::VectorXd dirichlet_data(loc_glob_map.NoDofs());\n  const Eigen::Matrix<double, 0, 1> ref_coord{\n      Eigen::Matrix<double, 0, 1>::Zero(0, 1)};\n  for (const lf::mesh::Entity &node : mesh_p->Entities(mesh_p->DimMesh())) {\n    LF_ASSERT_MSG(node.RefEl() == lf::base::RefEl::kPoint(),\n                  \"Wrong topological type for a node\");\n    const Eigen::Vector2d point = node.Geometry()->Global(ref_coord);\n    const lf::assemble::size_type num_int_dof =\n        loc_glob_map.NoInteriorDofs(node);\n    LF_ASSERT_MSG(num_int_dof == 1, \"Node with \" << num_int_dof << \" dof\");\n    const lf::base::RandomAccessRange<const lf::assemble::gdof_idx_t> gsf_idx(\n        loc_glob_map.InteriorGlobalDofIndices(node));\n    const lf::assemble::gdof_idx_t node_dof_idx = gsf_idx[0];\n    dirichlet_data[node_dof_idx] = u(point);\n  }\n\n  // modify linear system in order to take into account boundary data\n  std::vector<bool> tmp_bd_flags{flagBoundaryDOFs(loc_glob_map)};\n  // >> Old version\n  // eliminateBoundaryDofs(tmp_bd_flags, mat);\n  // insertDirichletDataRHS(tmp_bd_flags, rhsvec, dirichlet_data);\n  // Identify dof indices associated with the boundary\n  // >>\n  // >> Equivalent new versions\n  lf::assemble::fix_flagged_solution_comp_alt<double>(\n      [&tmp_bd_flags,\n       &dirichlet_data](lf::assemble::gdof_idx_t i) -> std::pair<bool, double> {\n        LF_ASSERT_MSG((i < tmp_bd_flags.size()) && (i < dirichlet_data.size()),\n                      \"Illegal index \" << i);\n        return std::make_pair(tmp_bd_flags[i], dirichlet_data[i]);\n      },\n      mat, rhsvec);\n  // lf::assemble::fix_flagged_solution_components<double>(\n  //   tmp_bd_flags, dirichlet_data, mat, rhsvec);\n  // >>\n  // Debugging output\n  SWITCHEDSTATEMENT(dbg_ctrl, dbg_mat,\n                    std::cout << \"Reduced \" << mat.rows() << 'x' << mat.cols()\n                              << \" stiffness matrix, \" << mat.triplets().size()\n                              << \" triplets:\\n\"\n                              << mat.makeDense() << std::endl);\n\n  // Initialize sparse matrix\n  Eigen::SparseMatrix<double> stiffness_matrix(mat.makeSparse());\n  // Solve linear system\n  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;\n  solver.compute(stiffness_matrix);\n  Eigen::VectorXd sol_vec = solver.solve(rhsvec);\n  if (solver.info() != Eigen::Success) {\n    std::cout << \"solver failed!\" << std::endl;\n  }\n\n  // Compute the norm of nodal error cell by cell\n  double nodal_err = 0.0;\n  for (const lf::mesh::Entity &cell : mesh_p->Entities(0)) {\n    const lf::base::RandomAccessRange<const lf::assemble::gdof_idx_t>\n        cell_dof_idx(loc_glob_map.GlobalDofIndices(cell));\n    LF_ASSERT_MSG(loc_glob_map.NoLocalDofs(cell) == cell.RefEl().NumNodes(),\n                  \"Inconsistent node number\");\n    const lf::base::size_type num_nodes = cell.RefEl().NumNodes();\n    double sum = 0.0;\n    for (int k = 0; k < num_nodes; ++k) {\n      sum += std::pow(\n          sol_vec[cell_dof_idx[k]] - dirichlet_data[cell_dof_idx[k]], 2);\n    }\n    nodal_err += lf::geometry::Volume(*cell.Geometry()) * (sum / num_nodes);\n  }\n  return std::sqrt(nodal_err);\n}\n\n/** @brief Solves Dirichlet problem for the Laplacian on a sequence of\n *         regularly refined meshes\n * @param coarse_mesh_p pointer to coarsest mesh\n * @param reflevels number of refinements\n * @param u exact solution of the boundary value problem\n * @param f right hand side source function\n * @return L2 norms of discretization errors on each refinement level\n *\n */\ntemplate <typename SOLFUNCTOR, typename RHSFUNCTOR>\nstd::vector<double> SolveDirLaplSeqMesh(\n    std::shared_ptr<lf::mesh::Mesh> coarse_mesh_p, unsigned int reflevels,\n    SOLFUNCTOR &&u, RHSFUNCTOR &&f) {\n  // Prepare for creating a hierarchy of meshes\n  std::shared_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory_ptr =\n      std::make_shared<lf::mesh::hybrid2d::MeshFactory>(2);\n  lf::refinement::MeshHierarchy multi_mesh(std::move(coarse_mesh_p),\n                                           mesh_factory_ptr);\n\n  // Perform several steps of regular refinement of the given mesh\n  for (int refstep = 0; refstep < reflevels; ++refstep) {\n    multi_mesh.RefineRegular(/*lf::refinement::RefPat::rp_barycentric*/);\n  }\n  // Solve Dirichlet boundary value problem on every level\n  lf::assemble::size_type L = multi_mesh.NumLevels();\n  std::vector<double> errors(L);\n  for (int level = 0; level < L; level++) {\n    errors.push_back(\n        L2ErrorLinearFEDirichletLaplacian(multi_mesh.getMesh(level), u, f));\n  }\n  return errors;\n}\n\nint main(int argc, const char **argv) {\n  // Pointer to the current mesh\n  std::shared_ptr<lf::mesh::Mesh> mesh_p;\n\n  // Processing command line arguments\n  bool verbose = false;\n  namespace po = boost::program_options;\n  po::options_description desc(\"Allowed options\");\n  // clang-format off\n  desc.add_options()\n  (\"help,h\", \"-h -v -f <filename> -s <selection>\")\n  (\"filename,f\", \"File to load coarse mesh from \")\n  (\"selector,s\", po::value<int>()->default_value(0), \"Selection of test mesh\")\n  (\"reflevels,r\", po::value<int>()->default_value(2), \"Number of refinement levels\")\n  (\"bvpsel,b\", po::value<int>()->default_value(0),\n   \"Selector for Dirichlet data and rhs function\")\n  (\"verbose,v\", po::bool_switch(&verbose),\"Enable verbose mode\");\n  // clang-format on\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  if (vm.count(\"help\") > 0) {\n    std::cout << desc << std::endl;\n    std::cout << \"Internal variables that can be set by name=value args\"\n              << std::endl;\n    lf::base::ListCtrlVars(std::cout);\n  } else {\n    lf::base::ReadCtrVarsCmdArgs(argc, argv);\n    std::cout << \"*** Solving Dirichlet problems for the Laplacian ***\"\n              << std::endl;\n    // Retrieve number of degrees of freedom for each entity type from\n    // command line arguments\n    if (vm.count(\"filename\") > 0) {\n      // A filename was specified\n      std::string filename{vm[\"filename\"].as<std::string>()};\n      if (filename.length() > 0) {\n        std::cout << \"Reading mesh from file \" << filename << std::endl;\n        boost::filesystem::path here = __FILE__;\n        auto mesh_file_path = here.parent_path() / filename.c_str();\n        auto mesh_factory =\n            std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);\n        lf::io::GmshReader reader(std::move(mesh_factory),\n                                  mesh_file_path.string());\n        mesh_p = reader.mesh();\n      }\n    } else {\n      std::cout << \"No mesh file supplied, using GenerateHybrid2DTestMesh()\"\n                << std::endl;\n      if (vm.count(\"selector\") > 0) {\n        const int selector = vm[\"selector\"].as<int>();\n        std::cout << \"Using test mesh no \" << selector << std::endl;\n        if ((selector >= 0) && (selector <= 4)) {\n          mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(selector);\n        }\n      }\n    }\n    // Set number of refinement levels\n    unsigned int reflevels = 2;\n    if (vm.count(\"reflevels\") > 0) {\n      reflevels = vm[\"reflevels\"].as<int>();\n    }\n    unsigned int bvpsel = 0;\n    if (vm.count(\"bvpsel\") > 0) {\n      bvpsel = vm[\"bvpsel\"].as<int>();\n    }\n    if (mesh_p == nullptr) {\n      // Default mesh\n      std::cout << \"Using default mesh; test mesh 0\" << std::endl;\n      mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(0);\n    }\n    // At this point a pointer to the mesh is stored in mesh_p\n    // Output summary information about the coarsest mesh\n    std::cout << \"Coarse mesh: \" << mesh_p->Size(0) << \" cells, \"\n              << mesh_p->Size(1) << \" edges, \" << mesh_p->Size(2) << \" vertices\"\n              << std::endl;\n    std::cout << reflevels << \" refinement levels requested\" << std::endl;\n\n    // Problem data provided by function pointers\n    std::function<double(const Eigen::Vector2d &)> u, f;\n\n    // Initialize the problem data\n    std::cout << \"Problem setting \" << bvpsel << \" selected\" << std::endl;\n    switch (bvpsel) {\n      case 0: {\n        // A linear solution, no error, if contained in FE space\n        f = [](const Eigen::Vector2d &) { return 0.0; };\n        u = [](const Eigen::Vector2d &x) { return (x[0] + 2.0 * x[1]); };\n        break;\n      }\n      case 1: {\n        // Quadratic polynomial solution\n        f = [](const Eigen::Vector2d &) { return -4.0; };\n        u = [](const Eigen::Vector2d &x) {\n          return (std::pow(x[0], 2) + std::pow(x[1], 2));\n        };\n        break;\n      }\n      default: {\n        LF_VERIFY_MSG(false, \"Illegal problem number\");\n        break;\n      }\n    }\n\n    // Set debugging switches\n    lf::fe::LinearFELaplaceElementMatrix::dbg_ctrl = 0;\n    // LinearFELaplaceElementMatrix::dbg_geo |\n    // LinearFELaplaceElementMatrix::dbg_locmat;\n    lf::fe::LinearFELocalLoadVector<double, decltype(f)>::dbg_ctrl = 0;\n    lf::assemble::DofHandler::output_ctrl_ = 6;\n    dbg_ctrl = dbg_basic;  // | dbg_mat | dbg_mesh | dbg_dofh | dbg_trp;\n    // lf::assemble::ass_mat_dbg_ctrl = 255;\n\n    // Compute finite element solution and error\n    auto L2errs = SolveDirLaplSeqMesh(mesh_p, reflevels, u, f);\n    int level = 0;\n    for (auto &err : L2errs) {\n      std::cout << \"L2 rrror on level \" << level << \" = \" << err << std::endl;\n      level++;\n    }\n  }\n  return 0;\n}\n", "meta": {"hexsha": "0685328f8e7914b5bc8a2e8efa9881e8fbce55e0", "size": 16513, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/assemble/Dirichlet_Laplacian_demo.cc", "max_stars_repo_name": "Cryoris/lehrfempp", "max_stars_repo_head_hexsha": "fe5b830c25b950be9be90dda0f4f693a6dcb054b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/assemble/Dirichlet_Laplacian_demo.cc", "max_issues_repo_name": "Cryoris/lehrfempp", "max_issues_repo_head_hexsha": "fe5b830c25b950be9be90dda0f4f693a6dcb054b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/assemble/Dirichlet_Laplacian_demo.cc", "max_forks_repo_name": "Cryoris/lehrfempp", "max_forks_repo_head_hexsha": "fe5b830c25b950be9be90dda0f4f693a6dcb054b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1795511222, "max_line_length": 84, "alphanum_fraction": 0.6403439714, "num_tokens": 4476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.4358837083486863}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/optional.hpp>\n#include <cstddef>\n#include <limits>\n\n#include \"DataStructures/Tensor/TypeAliases.hpp\"\n#include \"Utilities/TypeTraits.hpp\"\n\nnamespace PUP {\nclass er;\n}  // namespace PUP\n\nnamespace CoordinateMaps {\n\n/*!\n * \\ingroup CoordinateMapsGroup\n *\n * \\brief Redistributes gridpoints on the sphere.\n * \\image html EquatorialCompression.png \"A sphere with an `aspect_ratio` of 3.\"\n *\n * \\details A mapping from the sphere to itself which depends on a single\n * parameter, the `aspect_ratio` \\f$\\alpha\\f$, which is the ratio of the\n * horizontal length to the vertical height for a given point. This parameter\n * name was chosen because points with \\f$\\tan \\theta = 1\\f$ get mapped to\n * points with \\f$\\tan \\theta' = \\alpha\\f$. In general, gridpoints located\n * at an angle \\f$\\theta\\f$ from the pole are mapped to a new angle\n * \\f$\\theta'\\f$ satisfying \\f$\\tan \\theta' = \\alpha \\tan \\theta\\f$.\n *\n * For an `aspect_ratio` greater than one, the gridpoints are mapped towards\n * the equator, leading to an equatorially compressed grid. For an\n * `aspect_ratio` less than one, the gridpoints are mapped towards the poles.\n * Note that the aspect ratio must be positive.\n *\n * We define the auxiliary variables \\f$ r := \\sqrt{x^2 + y^2 +z^2}\\f$\n * and \\f$ \\rho := \\sqrt{x^2 + y^2 + \\alpha^{-2} z^2}\\f$.\n *\n * The map corresponding to this transformation in cartesian coordinates\n * is then given by:\n *\n * \\f[\\vec{x}'(x,y,z) =\n * \\frac{r}{\\rho}\\begin{bmatrix}\n * x\\\\\n * y\\\\\n * \\alpha^{-1} z\\\\\n * \\end{bmatrix}\\f]\n *\n */\nclass EquatorialCompression {\n public:\n  static constexpr size_t dim = 3;\n  explicit EquatorialCompression(double aspect_ratio) noexcept;\n  EquatorialCompression() = default;\n  ~EquatorialCompression() = default;\n  EquatorialCompression(EquatorialCompression&&) = default;\n  EquatorialCompression(const EquatorialCompression&) = default;\n  EquatorialCompression& operator=(const EquatorialCompression&) = default;\n  EquatorialCompression& operator=(EquatorialCompression&&) = default;\n\n  template <typename T>\n  std::array<tt::remove_cvref_wrap_t<T>, 3> operator()(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  boost::optional<std::array<double, 3>> inverse(\n      const std::array<double, 3>& target_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> jacobian(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> inv_jacobian(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  // clang-tidy: google runtime references\n  void pup(PUP::er& p) noexcept;  // NOLINT\n\n private:\n  template <typename T>\n  std::array<tt::remove_cvref_wrap_t<T>, 3> angular_distortion(\n      const std::array<T, 3>& coords, double inverse_alpha) const noexcept;\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame>\n  angular_distortion_jacobian(const std::array<T, 3>& coords,\n                              double inverse_alpha) const noexcept;\n  friend bool operator==(const EquatorialCompression& lhs,\n                         const EquatorialCompression& rhs) noexcept;\n\n  double aspect_ratio_{std::numeric_limits<double>::signaling_NaN()};\n  double inverse_aspect_ratio_{std::numeric_limits<double>::signaling_NaN()};\n};\nbool operator!=(const EquatorialCompression& lhs,\n                const EquatorialCompression& rhs) noexcept;\n}  // namespace CoordinateMaps\n", "meta": {"hexsha": "c8c12aa722e5ce30c41bb1bf33917bbce580a4e0", "size": 3590, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Domain/CoordinateMaps/EquatorialCompression.hpp", "max_stars_repo_name": "marissawalker/spectre", "max_stars_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Domain/CoordinateMaps/EquatorialCompression.hpp", "max_issues_repo_name": "marissawalker/spectre", "max_issues_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Domain/CoordinateMaps/EquatorialCompression.hpp", "max_forks_repo_name": "marissawalker/spectre", "max_forks_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2626262626, "max_line_length": 80, "alphanum_fraction": 0.7080779944, "num_tokens": 944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975978, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4358836980585609}}
{"text": "/* ScaFES\n * Copyright (c) 2011-2015, ZIH, TU Dresden, Federal Republic of Germany.\n * For details, see the files COPYING and LICENSE in the base directory\n * of the package.\n */\n\n#ifndef MODULATEDGAUSSIANSOURCE_HPP_\n#define    MODULATEDGAUSSIANSOURCE_HPP_\n\n#include <boost/property_tree/ptree.hpp>\n\ntemplate <typename T>\nclass ModulatedGaussianSource {\npublic:\n    ModulatedGaussianSource(const ModulatedGaussianSource&)=delete;\n\n    ~ModulatedGaussianSource() { };\n\n    ModulatedGaussianSource(const T& dt, const boost::property_tree::ptree& p)\n    : dt_(dt)\n    , f_mod_(p.get<T>(\"source.f_mod\"))\n    , t0_(p.get<T>(\"source.t0\"))\n    , spread_(p.get<T>(\"source.spread\")) { };\n\n    template <typename TT> TT operator()(const TT & n) const\n    {\n        TT v=(t0_-n)/spread_;\n        v*=v;\n        v*=-.5;\n        v=exp(v);\n        TT mod=cos(2.*M_PI*f_mod_*n*dt_);\n        TT ret=v*mod;\n        return ret;\n    }\n\nprivate:\n    const T dt_;\n    const T f_mod_;\n    const T t0_;\n    const T spread_;\n};\n\n#endif    /* MODULATEDGAUSSIANSOURCE_HPP_ */\n\n", "meta": {"hexsha": "216e94d7b26dc2827692263956632a808a8f1cea", "size": 1050, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/EMFDTD/sources/ModulatedGaussianSource.hpp", "max_stars_repo_name": "nih23/MRIDrivenHeatSimulation", "max_stars_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/EMFDTD/sources/ModulatedGaussianSource.hpp", "max_issues_repo_name": "nih23/MRIDrivenHeatSimulation", "max_issues_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_issues_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/EMFDTD/sources/ModulatedGaussianSource.hpp", "max_forks_repo_name": "nih23/MRIDrivenHeatSimulation", "max_forks_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3333333333, "max_line_length": 78, "alphanum_fraction": 0.6428571429, "num_tokens": 307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271998, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4358836908292565}}
{"text": "/* Copyright (c) 2018, Skolkovo Institute of Science and Technology (Skoltech)\n * All rights reserved.\n *\n * See LICENSE file in the root of the mrob library.\n *\n *\n * planeRegistration.cpp\n *\n *  Created on: Jan 28, 2019\n *      Author: Gonzalo Ferrer\n *              g.ferrer@skoltech.ru\n *              Mobile Robotics Lab, Skoltech\n */\n\n\n#include \"mrob/pc_registration.hpp\"\n#include \"mrob/plane_registration.hpp\"\n#include <Eigen/LU> // for inverse and determinant\n#include <Eigen/Eigenvalues>\n#include <iostream>\n\n\n#include <chrono>\n\nusing namespace mrob;\n\n\nPlaneRegistration::PlaneRegistration():\n        numberPlanes_(0), numberPoses_(0),isSolved_(0), trajectory_(new std::vector<SE3>(8,SE3())),\n        solveMode_(SolveMode::GRADIENT),\n        c1_(1e-4), c2_(0.9), alpha_(0.75), beta_(0.1)\n{\n    // Optmizer does not establish the size for this matrices and thus it is required\n    gradient_.resize(6);\n    hessian_.resize(6,6);\n}\n\n\nPlaneRegistration::~PlaneRegistration()\n{\n\n}\n\n\nvoid PlaneRegistration::set_number_planes_and_poses(uint_t numberPlanes, uint_t numberPoses)\n{\n    planes_.clear();\n    planes_.reserve(numberPlanes);\n    trajectory_->clear();\n    trajectory_->resize(numberPoses, SE3());\n    numberPlanes_ = numberPlanes;\n    numberPoses_ = numberPoses;\n\n    previousState_.clear();\n    previousState_.resize(numberPoses, Mat61::Zero());\n}\n\n\nvoid PlaneRegistration::reset_solution()\n{\n    // trajectory is reset\n    trajectory_->clear();\n    trajectory_->resize(numberPoses_, SE3());\n    previousState_.clear();\n    previousState_.resize(numberPoses_, Mat61::Zero());\n}\n\n\nuint_t PlaneRegistration::solve(SolveMode mode, bool singleIteration)\n{\n    // just in case some methods, such as gradient, has several modes\n    solveMode_ = mode;\n    switch(mode)\n    {\n        case SolveMode::INITIALIZE:\n            return solve_initialize();\n        case SolveMode::GRADIENT:\n        case SolveMode::GRADIENT_BENGIOS_NAG:\n            return solve_interpolate_gradient(singleIteration);\n        case SolveMode::GN_HESSIAN:\n            return optimize(NEWTON_RAPHSON);\n        case SolveMode::GN_CLAMPED_HESSIAN:\n            return solve_interpolate_hessian(singleIteration);\n        case SolveMode::LM_SPHER:\n            return optimize(LEVENBERG_MARQUARDT_SPHER);\n        case SolveMode::LM_ELLIP:\n            return optimize(LEVENBERG_MARQUARDT_ELLIP);\n        default:\n            return 0;\n    }\n}\n\nuint_t PlaneRegistration::solve_interpolate_gradient(bool singleIteration)\n{\n    // This function is from the first implementation, is just kept for comparisons (but should not be used to solve the problem)\n    // iterative process, on convergence basis | error_k - error_k-1| < tol\n    solveIters_ = 0;\n    double previousError = 1e20, diffError = 10;\n    do\n    {\n        // 1) calculate plane estimation given the current trajectory\n        double  initialError = 0.0;\n        for (auto it = planes_.cbegin();  it != planes_.cend(); ++it)\n        {\n            initialError += it->second->estimate_plane();\n        }\n        diffError = previousError - initialError;\n        previousError = initialError;\n\n        std::cout << \"current error iteration \" << solveIters_ << \" = \"<< initialError << std::endl;\n\n        // 2) calculate Gradient = Jacobian^T. We maintain the nomenclature Jacobian for coherence on the project,\n        //    but actually this Jacobian should be transposed.\n        Mat61 jacobian = Mat61::Zero(), accumulatedJacobian = Mat61::Zero();\n        double  numberPoints, tau = 1.0 / (double)(numberPoses_-1);\n        for (uint_t t = 1 ; t < numberPoses_; ++t)\n        {\n            numberPoints = 0.0;\n            jacobian.setZero();\n            for (auto it = planes_.cbegin();  it != planes_.cend(); ++it)\n            {\n                jacobian += it->second->calculate_gradient(t);\n                numberPoints += it->second->get_number_points(t);\n            }\n            // XXX this could be changed to time stamps later\n            accumulatedJacobian +=  (tau *  t  / numberPoints / numberPoses_) * jacobian;\n\n        }\n        // 3) update results Tf = exp(-dxi) * Tf (our convention, we expanded from the left)\n        // 3-1)\n        Mat61 dxi, xiFinal;\n        if (solveMode_ == SolveMode::GRADIENT)\n        {\n            double alpha = alpha_;\n            dxi = -alpha * accumulatedJacobian;\n            //std::cout << \"\\nINterpolate jacobian : = \" << accumulatedJacobian.transpose() << \", and increment update = \" << dxi << std::endl;\n        }\n        // 3.4-B) Bengio's NAG: a modification to NAG as proposed in Bengio-2013. Fixed parameters\n        //          1) momentum or velocity  v_k = beta_k-1 v _k-1 - alpha_k-1 Grad f (x_k-1)\n        //          2) x_k+1 = x_k + beta_k+1 beta_k * v_k - (1 + beta_k+1)*alpha_k * Grad f(x_k)\n        if (solveMode_ == SolveMode::GRADIENT_BENGIOS_NAG)\n        {\n            double alpha = alpha_;\n            double beta = beta_;\n            // x update\n            dxi = beta * beta * previousState_.back() - (1 + beta) * alpha * accumulatedJacobian;\n\n            // momentum\n            previousState_.back() = beta * previousState_.back() - alpha * accumulatedJacobian;\n        }\n        trajectory_->back().update_lhs(dxi);\n        xiFinal = trajectory_->back().ln_vee();\n        for (uint_t t = 1 ; t < numberPoses_-1; ++t)\n        {\n            dxi = tau * t * xiFinal;// SE3 does not like all derived classes TODO\n            trajectory_->at(t) = SE3(dxi);\n        }\n        ++solveIters_;\n    }while(fabs(diffError) > 1e-4 && !singleIteration && solveIters_ < 1e4);\n    return solveIters_;\n}\n\n// TO BE DEPRECATED. Only used for clamped Hessian, and that is shown NOT to work.\nuint_t PlaneRegistration::solve_interpolate_hessian(bool singleIteration)\n{\n    // iterative process, on convergence basis | error_k - error_k-1| < tol\n    // For now, only 1 iteration\n    solveIters_ = 0;\n    double previousError = 1e20, diffError = 10;\n\n    do\n    {\n\n        // 1) calculate plane estimation given the current trajectory. Same as solve_interpolate\n        double  initialError = get_current_error();\n\n        diffError = previousError - initialError;\n        previousError = initialError;\n\n        solveIters_++;\n        std::cout << \"current error iteration \" << solveIters_ << \" = \"<< initialError << std::endl;\n\n        // 2) calculate Gradient and Hessian\n        Mat61 gradient = Mat61::Zero();\n        Mat6 hessian = Mat6::Zero();\n        gradient__.setZero();\n        hessian__.setZero();\n        double  tau = 1.0 / (double)(numberPoses_-1);\n        for (uint_t t = 1 ; t < numberPoses_; ++t)\n        {\n            gradient.setZero();\n            hessian.setZero();\n            for (auto it = planes_.cbegin();  it != planes_.cend(); ++it)\n            {\n                gradient += it->second->calculate_gradient(t);\n                hessian += it->second->calculate_hessian(t);\n            }\n            // TODO this should be changed to time stamps later\n            gradient__ +=  (tau *  t)  * gradient;\n            hessian__ += (tau *  t) * hessian.selfadjointView<Eigen::Upper>();\n        }\n        // 3) calculate update Tf = exp(-dxi) * Tf (our convention, we expanded from the left)\n        Mat61 dxi;\n        if (solveMode_ == SolveMode::GN_CLAMPED_HESSIAN)\n        {\n            // we clamp the vector spaces corresponding to negative eigenvals\n            Mat6 pseudoInv = Mat6::Zero();\n            Eigen::SelfAdjointEigenSolver<Mat6> eigs(hessian__);\n            for (uint_t i = 0; i < 6 ; ++i)\n            {\n                if(eigs.eigenvalues()[i] > 1e-4 || true ) //TODO set tolerance\n                {\n                    std::cout << \"POSITIVE. cos distance to grad = \" << eigs.eigenvectors().col(i).dot(gradient)/gradient.norm()\n                              << \", eigs = \" << eigs.eigenvalues()[i] << std::endl;\n                    pseudoInv += (1.0/eigs.eigenvalues()(i)) * eigs.eigenvectors().col(i) * eigs.eigenvectors().col(i).transpose();\n                    // XXX why is this function not monotonically decreasing? this is annoying, but makes clamping a bad idea: LM!\n                }\n                else\n                {\n                    std::cout << \"NEGATIVE. cos distance to grad = \" << eigs.eigenvectors().col(i).dot(gradient)/gradient.norm()\n                              << \", eigs = \" << eigs.eigenvalues()[i] << std::endl;\n\n                }\n            }\n            dxi = - pseudoInv * gradient__;\n        }\n        else\n            dxi = - hessian__.inverse() * gradient__;\n        trajectory_->back().update_lhs(dxi);\n\n\n        // 4) update full trajectory. Here we assume a full rank matrix TODO check for degenerate cases\n        Mat61 xiFinal = trajectory_->back().ln_vee();\n        for (uint_t t = 1 ; t < numberPoses_-1; ++t)\n        {\n            dxi = tau * t * xiFinal;\n            trajectory_->at(t) = SE3(dxi);\n        }\n    }while(fabs(diffError) > 1e-4 && !singleIteration && solveIters_ < 1e4);\n    return solveIters_;\n}\n\n\nuint_t PlaneRegistration::solve_quaternion_plane()\n{\n    solveIters_ = 0;\n    double previousError = 1e20, diffError = 10;\n\n    // TODO create factor graph or call dense solver?\n\n\n    return solveIters_;\n}\n\nuint_t PlaneRegistration::solve_initialize()\n{\n    // TODO Maybe solve this as a plane-to-point alignment wrt T0\n    // Initialize matrices of points\n    MatX X(numberPlanes_,3), Y(numberPlanes_,3);\n\n    // create points Y (from frame t =0), minimum 3 planes per pose\n    uint_t t = 0;\n    for (auto it = planes_.cbegin();  it != planes_.cend(); ++it)\n    {\n        it->second->calculate_all_matrices_S();\n        Y.row(t) = it->second->get_mean_point(0);\n        ++t;\n    }\n\n    // create points X, for t = 1, ... T, minimum 3 planes per pose\n    for (t = 1; t < numberPoses_; ++t)\n    {\n        uint_t cont = 0;\n        X.setZero();\n        for (auto it = planes_.cbegin();  it != planes_.cend(); ++it)\n        {\n            X.row(cont) = it->second->get_mean_point(t);\n            ++cont;\n        }\n        // Arun solver\n        SE3 estimatedPose;\n        if (!PCRegistration::arun(X,Y,estimatedPose))\n            return 0;\n        trajectory_->at(t) = estimatedPose;\n    }\n\n\n    // update current trajectory\n    return 1;\n}\n\ndouble PlaneRegistration::get_current_error() const\n{\n    double  currentError = 0.0;\n    for (auto it = planes_.cbegin();  it != planes_.cend(); ++it)\n        currentError += it->second->estimate_plane();\n    return currentError;\n}\n\nvoid PlaneRegistration::add_plane(uint_t id, std::shared_ptr<Plane> &plane)\n{\n    plane->set_trajectory(trajectory_);\n    planes_.emplace(id, plane);\n}\n\ndouble PlaneRegistration::calculate_poses_rmse(std::vector<SE3> & groundTruth) const\n{\n    assert(groundTruth.size() >= numberPoses_ && \"PlaneRegistration::calculate_poses_rmse: number of poses from GT is incorrect\\n\");\n    double rmse= 0.0;\n    uint_t t = 0;\n    for (auto &pose: groundTruth)\n    {\n        Mat61 dxi = (trajectory_->at(t) * pose.inv()).ln_vee();\n        //std::cout << pose.ln_vee().transpose() << \" and solution inv first pose \\n\" << (invFirstPose * trajectory_->at(t) * pose.inv()).ln_vee().transpose() <<std::endl;\n        rmse += dxi.dot(dxi)/(double)numberPoses_;\n        ++t;\n    }\n    return std::sqrt(rmse);\n}\n\n//XXX this can be a reference, who does this interface with pybinds?\nstd::vector<Mat31> PlaneRegistration::get_point_cloud(uint_t time)\n{\n\tstd::vector<Mat31> aggregated_pc;\n\tfor (auto it = planes_.cbegin();  it != planes_.cend(); ++it)\n    {\n        std::vector<Mat31>& plane_pc = it->second->get_points(time);\n        // aggregating elements\n        aggregated_pc.insert(aggregated_pc.end(), plane_pc.begin(), plane_pc.end());\n\t}\n\treturn aggregated_pc;\n}\n\nMat4 PlaneRegistration::get_trajectory(uint_t time)\n{\n    assert(time < numberPoses_ && \"CreatePoints::getPointCloud: temporal index larger than number of calculated poses\\n\");\n    if (time < numberPoses_ )\n        return trajectory_->at(time).T();\n    return Mat4::Identity();\n}\n\nvoid PlaneRegistration::print(bool plotPlanes) const\n{\n    std::cout << \"Printing plane registration data :\"<< std::endl;\n    for (SE3 &transf : *trajectory_)\n        transf.print();\n    if (plotPlanes)\n    {\n        for (auto it = planes_.cbegin();  it != planes_.cend(); ++it)\n            it->second->print();\n    }\n}\n\n\n// resturns: [0]error, [1]iters, hessdet[2], conditioningNumber[3]\nstd::vector<double> PlaneRegistration::print_evaluate()\n{\n    std::vector<double> result(6,0.0);\n\n    result[0] = get_current_error();\n    result[1] = solveIters_;\n\n    MatX allPlanes(numberPlanes_,4);\n    MatX allNormals(numberPlanes_,3);\n    uint_t i = 0;\n\n\n    switch(solveMode_)\n    {\n        case SolveMode::GRADIENT:\n        case SolveMode::GRADIENT_BENGIOS_NAG:\n            hessian__.setZero();\n            break;\n        case SolveMode::GN_HESSIAN:\n        case SolveMode::LM_SPHER:\n        case SolveMode::LM_ELLIP:\n            gradient__ = gradient_;\n            hessian__ = hessian_;\n    }\n\n    // Normals on planes, check for rank\n    for (auto plane : planes_)\n    {\n        Mat41 pi = plane.second->get_plane();\n        //std::cout << \"plane : \\n\" << pi << std::endl;\n        allPlanes.row(i) = pi;\n        allNormals.row(i) = pi.head(3)/(pi.head(3).norm());\n        ++i;\n    }\n    // Orthogonality between planes (4 dim)\n    std::cout << \"current gradient \\n\" << gradient__ << std::endl;\n    // XXX : NO, Orthogonolaity was not an issue\n    //std::cout << \"solution\\n\" << allPlanes << \"\\nOrthogonality between planes: \\n\" << allPlanes * allPlanes.transpose() <<\n    //              \"\\n and det  = \\n\" << allPlanes.determinant() << std::endl;\n\n    // XXX No, Orthogonality between normals\n    //std::cout << \"Orthogonality between normals: \\n\" << allNormals * allNormals.transpose() <<\n    //             \"\\n and det = \\n\" << allNormals.determinant() << std::endl;\n\n    // Hessian rank and eigen, look for negative vaps. Lasta hessina calculateds\n    Eigen::EigenSolver<MatX> eigs(hessian__);\n    std::cout << \"eigen values are: \\n\" << eigs.eigenvalues() << std::endl;\n    // Determinant of stacked normals\n    std::cout << \"det(Hessian) = \\n\" << hessian__ << std::endl;\n    // Hessian conditioning number\n    Eigen::JacobiSVD<Mat6> svd(hessian__, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    // TODO remove\n    //std::cout << \"SVD decomposition : \\n\" << svd.singularValues() <<\n    //              \"\\n vectors :\\n\" << svd.matrixU() <<\n    //             \"\\n and conditioning number = \" << svd.singularValues()(0)/svd.singularValues()(5) << std::endl;\n\n    result[2] = hessian__.determinant();\n    //TODO count this and optimze\n    result[3] = svd.singularValues()(0)/svd.singularValues()(5);\n\n    return result;\n}\n\n// From parent class Optimizer:\n// TOOD for now replicated, later we will substitute\nmatData_t PlaneRegistration::calculate_error()\n{\n    return get_current_error();\n}\n\nvoid PlaneRegistration::calculate_gradient_hessian()\n{\n    Mat61 gradient = Mat61::Zero();\n    Mat6 hessian = Mat6::Zero();\n    gradient_.setZero();\n    hessian_.setZero();\n    double  tau = 1.0 / (double)(numberPoses_-1);\n    for (uint_t t = 1 ; t < numberPoses_; ++t)\n    {\n        gradient.setZero();\n        hessian.setZero();\n        for (auto it = planes_.cbegin();  it != planes_.cend(); ++it)\n        {\n            gradient += it->second->calculate_gradient(t);\n            hessian += it->second->calculate_hessian(t);\n        }\n        // TODO this should be changed to time stamps later\n        gradient_ +=  (tau *  t)  * gradient;\n        hessian_ += (tau *  t) * hessian.selfadjointView<Eigen::Upper>();\n    }\n}\n\nvoid PlaneRegistration::update_state(const MatX1 &dx)\n{\n    trajectory_->back().update_lhs(dx);\n    Mat61 xiFinal = trajectory_->back().ln_vee();\n    double  tau = 1.0 / (double)(numberPoses_-1);\n    Mat61 dxi;\n    for (uint_t t = 1 ; t < numberPoses_-1; ++t)\n    {\n        dxi = tau * t * xiFinal;\n        trajectory_->at(t) = SE3(dxi);\n    }\n}\n\nvoid PlaneRegistration::bookkeep_state()\n{\n    bookept_trajectory_ = trajectory_->back();\n}\n\nvoid PlaneRegistration::update_state_from_bookkeep()\n{\n    trajectory_->back() = bookept_trajectory_;\n    Mat61 xiFinal = bookept_trajectory_.ln_vee();\n    double  tau = 1.0 / (double)(numberPoses_-1);\n    Mat61 dxi;\n    for (uint_t t = 1 ; t < numberPoses_-1; ++t)\n    {\n        dxi = tau * t * xiFinal;\n        trajectory_->at(t) = SE3(dxi);\n    }\n    calculate_error();// planes get recalculated, which is a requisite for later\n    //(this class construction, in general grad should be self-contained...)\n}\n\n", "meta": {"hexsha": "867daafac7f53a2ab4ea8563ab23a123caf893b9", "size": 16557, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PCRegistration/plane_registration.cpp", "max_stars_repo_name": "anastasiia-kornilova/mrob", "max_stars_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-10T09:36:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-10T09:36:50.000Z", "max_issues_repo_path": "src/PCRegistration/plane_registration.cpp", "max_issues_repo_name": "anastasiia-kornilova/mrob", "max_issues_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PCRegistration/plane_registration.cpp", "max_forks_repo_name": "anastasiia-kornilova/mrob", "max_forks_repo_head_hexsha": "4238e01657911bfbc853a6633e5708d75a4fad99", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.422037422, "max_line_length": 171, "alphanum_fraction": 0.6037929577, "num_tokens": 4401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4358806366777909}}
{"text": "#include <anie/details/kernels.hpp>\n\n#include <boost/compute.hpp>\n\nnamespace anie::details\n{\n\tconst std::string kernel_matrix_add = BOOST_COMPUTE_STRINGIZE_SOURCE(\n\t\t__kernel void matrix_add(__global double* lhs, __global const double* rhs,\n\t\t\t\t\t\t\t\t const uint width)\n\t\t{\n\t\t\tconst uint y = get_global_id(0);\n\t\t\t\n\t\t\tfor (uint i = 0; i < width; ++i)\n\t\t\t{\n\t\t\t\tlhs[width * y + i] += rhs[width * y + i];\n\t\t\t}\n\t\t}\n\t);\n\tconst std::string kernel_matrix_sub = BOOST_COMPUTE_STRINGIZE_SOURCE(\n\t\t__kernel void matrix_sub(__global double* lhs, __global const double* rhs,\n\t\t\t\t\t\t\t\t const uint width)\n\t\t{\n\t\t\tconst uint y = get_global_id(0);\n\n\t\t\tfor (uint i = 0; i < width; ++i)\n\t\t\t{\n\t\t\t\tlhs[width * y + i] -= rhs[width * y + i];\n\t\t\t}\n\t\t}\n\t);\n\tconst std::string kernel_matrix_multiply = BOOST_COMPUTE_STRINGIZE_SOURCE(\n\t\t__kernel void matrix_multiply(__global double* dest, __global const double* src_lhs, __global const double* src_rhs,\n\t\t\t\t\t\t\t\t\t  const uint src_lhs_width, const uint src_rhs_width)\n\t\t{\n\t\t\tconst uint width = get_global_size(0);\n\t\t\tconst uint x = get_global_id(0);\n\t\t\tconst uint y = get_global_id(1);\n\t\t\tconst uint index = y * width + x;\n\t\t\t\n\t\t\tdouble sum = 0.;\n\n\t\t\tfor (uint i = 0; i < src_lhs_width; ++i)\n\t\t\t{\n\t\t\t\tsum += src_lhs[src_lhs_width * y + i] * src_rhs[src_rhs_width * i + x];\n\t\t\t}\n\n\t\t\tdest[index] = sum;\n\t\t}\n\t);\n\tconst std::string kernel_matrix_transpose = BOOST_COMPUTE_STRINGIZE_SOURCE(\n\t\t__kernel void matrix_transpose(__global double* dest, __global const double* src,\n\t\t\t\t\t\t\t\t const uint src_width, const uint src_height)\n\t\t{\n\t\t\tconst uint y = get_global_id(0);\n\n\t\t\tfor (uint i = 0; i < src_width; ++i)\n\t\t\t{\n\t\t\t\tdest[i * src_height + y] = src[y * src_width + i];\n\t\t\t}\n\t\t}\n\t);\n}", "meta": {"hexsha": "78114112d54e1321544dc9955c0e322416277874", "size": 1697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/details/kernels.cpp", "max_stars_repo_name": "kmc7468/ANIE", "max_stars_repo_head_hexsha": "ed140830712fa04372c01319b090ef5c1be17ecf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-11-21T12:30:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-26T07:15:30.000Z", "max_issues_repo_path": "src/details/kernels.cpp", "max_issues_repo_name": "kmc7468/ANIE", "max_issues_repo_head_hexsha": "ed140830712fa04372c01319b090ef5c1be17ecf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/details/kernels.cpp", "max_forks_repo_name": "kmc7468/ANIE", "max_forks_repo_head_hexsha": "ed140830712fa04372c01319b090ef5c1be17ecf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3709677419, "max_line_length": 118, "alphanum_fraction": 0.652327637, "num_tokens": 505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4357738632269278}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation, \n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file  Pose3.cpp\n * @brief 3D Pose\n */\n\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/geometry/Pose2.h>\n#include <gtsam/geometry/concepts.h>\n#include <gtsam/base/Lie-inl.h>\n#include <boost/foreach.hpp>\n#include <iostream>\n#include <cmath>\n\nusing namespace std;\n\nnamespace gtsam {\n\n  /** Explicit instantiation of base class to export members */\n  INSTANTIATE_LIE(Pose3);\n\n  /** instantiate concept checks */\n  GTSAM_CONCEPT_POSE_INST(Pose3);\n\n  static const Matrix3 I3 = eye(3), Z3 = zeros(3, 3), _I3=-I3;\n  static const Matrix6 I6 = eye(6);\n\n  /* ************************************************************************* */\n  Pose3::Pose3(const Pose2& pose2) :\n      R_(Rot3::rodriguez(0, 0, pose2.theta())),\n      t_(Point3(pose2.x(), pose2.y(), 0)) {\n  }\n\n  /* ************************************************************************* */\n  // Calculate Adjoint map\n  // Ad_pose is 6*6 matrix that when applied to twist xi, returns Ad_pose(xi)\n  // Experimental - unit tests of derivatives based on it do not check out yet\n  Matrix6 Pose3::AdjointMap() const {\n    const Matrix3 R = R_.matrix();\n    const Vector3 t = t_.vector();\n    Matrix3 A = skewSymmetric(t)*R;\n    Matrix6 adj;\n    adj << R, Z3, A, R;\n    return adj;\n  }\n\n  /* ************************************************************************* */\n  Matrix6 Pose3::adjointMap(const Vector& xi) {\n    Matrix3 w_hat = skewSymmetric(xi(0), xi(1), xi(2));\n    Matrix3 v_hat = skewSymmetric(xi(3), xi(4), xi(5));\n    Matrix6 adj;\n    adj << w_hat, Z3, v_hat, w_hat;\n\n    return adj;\n  }\n\n  /* ************************************************************************* */\n  Vector Pose3::adjoint(const Vector& xi, const Vector& y, boost::optional<Matrix&> H) {\n    if (H) {\n      *H = zeros(6,6);\n      for (int i = 0; i<6; ++i) {\n        Vector dxi = zero(6); dxi(i) = 1.0;\n        Matrix Gi = adjointMap(dxi);\n        (*H).col(i) = Gi*y;\n      }\n    }\n    return adjointMap(xi)*y;\n  }\n\n  /* ************************************************************************* */\n  Vector Pose3::adjointTranspose(const Vector& xi, const Vector& y, boost::optional<Matrix&> H) {\n    if (H) {\n      *H = zeros(6,6);\n      for (int i = 0; i<6; ++i) {\n        Vector dxi = zero(6); dxi(i) = 1.0;\n        Matrix GTi = adjointMap(dxi).transpose();\n        (*H).col(i) = GTi*y;\n      }\n    }\n    Matrix adjT = adjointMap(xi).transpose();\n    return adjointMap(xi).transpose() * y;\n  }\n\n  /* ************************************************************************* */\n  Matrix6 Pose3::dExpInv_exp(const Vector& xi) {\n    // Bernoulli numbers, from Wikipedia\n    static const Vector B = Vector_(9, 1.0, -1.0/2.0, 1./6., 0.0, -1.0/30.0, 0.0, 1.0/42.0, 0.0, -1.0/30);\n    static const int N = 5; // order of approximation\n    Matrix res = I6;\n    Matrix6 ad_i = I6;\n    Matrix6 ad_xi = adjointMap(xi);\n    double fac = 1.0;\n    for (int i = 1 ; i<N; ++i) {\n      ad_i = ad_xi * ad_i;\n      fac = fac*i;\n      res = res + B(i)/fac*ad_i;\n    }\n    return res;\n  }\n\n  /* ************************************************************************* */\n  void Pose3::print(const string& s) const {\n    cout << s;\n    R_.print(\"R:\\n\");\n    t_.print(\"t: \");\n  }\n\n  /* ************************************************************************* */\n  bool Pose3::equals(const Pose3& pose, double tol) const {\n    return R_.equals(pose.R_,tol) && t_.equals(pose.t_,tol);\n  }\n\n  /* ************************************************************************* */\n  /** Modified from Murray94book version (which assumes w and v normalized?) */\n  Pose3 Pose3::Expmap(const Vector& xi) {\n\n    // get angular velocity omega and translational velocity v from twist xi\n    Point3 w(xi(0),xi(1),xi(2)), v(xi(3),xi(4),xi(5));\n\n    double theta = w.norm();\n    if (theta < 1e-10) {\n      static const Rot3 I;\n      return Pose3(I, v);\n    }\n    else {\n      Point3 n(w/theta); // axis unit vector\n      Rot3 R = Rot3::rodriguez(n.vector(),theta);\n      double vn = n.dot(v); // translation parallel to n\n      Point3 n_cross_v = n.cross(v); // points towards axis\n      Point3 t = (n_cross_v - R*n_cross_v)/theta + vn*n;\n      return Pose3(R, t);\n    }\n  }\n\n  /* ************************************************************************* */\n  Vector6 Pose3::Logmap(const Pose3& p) {\n    Vector3 w = Rot3::Logmap(p.rotation()), T = p.translation().vector();\n    double t = w.norm();\n    if (t < 1e-10) {\n      Vector6 log;\n      log << w, T;\n      return log;\n    }\n    else {\n      Matrix3 W = skewSymmetric(w/t);\n      // Formula from Agrawal06iros, equation (14)\n      // simplified with Mathematica, and multiplying in T to avoid matrix math\n      double Tan = tan(0.5*t);\n      Vector3 WT = W*T;\n      Vector3 u = T - (0.5*t)*WT + (1 - t/(2.*Tan)) * (W * WT);\n      Vector6 log;\n      log << w, u;\n      return log;\n    }\n  }\n\n  /* ************************************************************************* */\n  Pose3 Pose3::retractFirstOrder(const Vector& xi) const {\n      Vector3 omega(sub(xi, 0, 3));\n      Point3 v(sub(xi, 3, 6));\n      Rot3 R = R_.retract(omega);  // R is done exactly\n      Point3 t = t_ + R_ * v; // First order t approximation\n      return Pose3(R, t);\n  }\n\n  /* ************************************************************************* */\n  // Different versions of retract\n  Pose3 Pose3::retract(const Vector& xi, Pose3::CoordinatesMode mode) const {\n    if(mode == Pose3::EXPMAP) {\n      // Lie group exponential map, traces out geodesic\n      return compose(Expmap(xi));\n    } else if(mode == Pose3::FIRST_ORDER) {\n      // First order\n      return retractFirstOrder(xi);\n    } else {\n      // Point3 t = t_.retract(v.vector()); // Incorrect version retracts t independently\n      // Point3 t = t_ + R_ * (v+Point3(omega).cross(v)/2); // Second order t approximation\n      assert(false);\n      exit(1);\n    }\n  }\n\n  /* ************************************************************************* */\n  // different versions of localCoordinates\n  Vector6 Pose3::localCoordinates(const Pose3& T, Pose3::CoordinatesMode mode) const {\n    if(mode == Pose3::EXPMAP) {\n      // Lie group logarithm map, exact inverse of exponential map\n      return Logmap(between(T));\n    } else if(mode == Pose3::FIRST_ORDER) {\n      // R is always done exactly in all three retract versions below\n      Vector3 omega = R_.localCoordinates(T.rotation());\n\n      // Incorrect version\n      // Independently computes the logmap of the translation and rotation\n      // Vector v = t_.localCoordinates(T.translation());\n\n      // Correct first order t inverse\n      Point3 d = R_.unrotate(T.translation() - t_);\n\n      // TODO: correct second order t inverse\n      Vector6 local;\n      local << omega(0),omega(1),omega(2),d.x(),d.y(),d.z();\n      return local;\n    } else {\n      assert(false);\n      exit(1);\n    }\n  }\n\n  /* ************************************************************************* */\n  Matrix4 Pose3::matrix() const {\n    const Matrix3 R = R_.matrix();\n    const Vector3 T = t_.vector();\n    Eigen::Matrix<double,1,4> A14;\n    A14 << 0.0, 0.0, 0.0, 1.0;\n    Matrix4 mat;\n    mat << R, T, A14;\n    return mat;\n  }\n\n  /* ************************************************************************* */\n  Pose3 Pose3::transform_to(const Pose3& pose) const {\n    Rot3 cRv = R_ * Rot3(pose.R_.inverse());\n    Point3 t = pose.transform_to(t_);\n    return Pose3(cRv, t);\n  }\n\n  /* ************************************************************************* */\n  Point3 Pose3::transform_from(const Point3& p,\n      boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n    if (H1) {\n      const Matrix R = R_.matrix();\n      Matrix DR = R*skewSymmetric(-p.x(), -p.y(), -p.z());\n      H1->resize(3,6);\n      (*H1) << DR, R;\n    }\n    if (H2) *H2 = R_.matrix();\n    return R_ * p + t_;\n  }\n\n  /* ************************************************************************* */\n  Point3 Pose3::transform_to(const Point3& p,\n            boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n    const Point3 result = R_.unrotate(p - t_);\n    if (H1) {\n      const Point3& q = result;\n      Matrix DR = skewSymmetric(q.x(), q.y(), q.z());\n      H1->resize(3,6);\n      (*H1) << DR, _I3;\n    }\n    if (H2) *H2 = R_.transpose();\n    return result;\n  }\n\n  /* ************************************************************************* */\n  Pose3 Pose3::compose(const Pose3& p2,\n        boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n    if (H1) *H1 = p2.inverse().AdjointMap();\n    if (H2) *H2 = I6;\n    return (*this) * p2;\n  }\n\n  /* ************************************************************************* */\n  Pose3 Pose3::inverse(boost::optional<Matrix&> H1) const {\n    if (H1) *H1 = -AdjointMap();\n    Rot3 Rt = R_.inverse();\n    return Pose3(Rt, Rt*(-t_));\n  }\n\n  /* ************************************************************************* */\n  // between = compose(p2,inverse(p1));\n  Pose3 Pose3::between(const Pose3& p2, boost::optional<Matrix&> H1,\n      boost::optional<Matrix&> H2) const {\n    Pose3 result = inverse()*p2;\n    if (H1) *H1 = -result.inverse().AdjointMap();\n    if (H2) *H2 = I6;\n    return result;\n  }\n\n  /* ************************************************************************* */\n  double Pose3::range(const Point3& point,\n      boost::optional<Matrix&> H1,\n      boost::optional<Matrix&> H2) const {\n    if (!H1 && !H2) return transform_to(point).norm();\n    Point3 d = transform_to(point, H1, H2);\n    double x = d.x(), y = d.y(), z = d.z(),\n       d2 = x * x + y * y + z * z, n = sqrt(d2);\n    Matrix D_result_d = Matrix_(1, 3, x / n, y / n, z / n);\n    if (H1) *H1 = D_result_d * (*H1);\n    if (H2) *H2 = D_result_d * (*H2);\n    return n;\n  }\n\n  /* ************************************************************************* */\n  double Pose3::range(const Pose3& point,\n        boost::optional<Matrix&> H1, boost::optional<Matrix&> H2) const {\n     double r = range(point.translation(), H1, H2);\n     if (H2) {\n       Matrix H2_ = *H2 * point.rotation().matrix();\n       *H2 = zeros(1, 6);\n       insertSub(*H2, H2_, 0, 3);\n     }\n     return r;\n  }\n\n  /* ************************************************************************* */\n  boost::optional<Pose3> align(const vector<Point3Pair>& pairs) {\n    const size_t n = pairs.size();\n    if (n<3) return boost::none; // we need at least three pairs\n\n    // calculate centroids\n    Vector cp = zero(3),cq = zero(3);\n    BOOST_FOREACH(const Point3Pair& pair, pairs) {\n      cp += pair.first.vector();\n      cq += pair.second.vector();\n    }\n    double f = 1.0/n;\n    cp *= f; cq *= f;\n\n    // Add to form H matrix\n    Matrix H = zeros(3,3);\n    BOOST_FOREACH(const Point3Pair& pair, pairs) {\n      Vector dp = pair.first.vector()  - cp;\n      Vector dq = pair.second.vector() - cq;\n      H += dp * dq.transpose();\n    }\n\n    // Compute SVD\n    Matrix U,V;\n    Vector S;\n    svd(H,U,S,V);\n\n    // Recover transform with correction from Eggert97machinevisionandapplications\n    Matrix UVtranspose = U * V.transpose();\n    Matrix detWeighting = eye(3,3);\n    detWeighting(2,2) = UVtranspose.determinant();\n    Rot3 R(Matrix(V * detWeighting * U.transpose()));\n    Point3 t = Point3(cq) - R * Point3(cp);\n    return Pose3(R, t);\n  }\n\n  /* ************************************************************************* */\n  std::ostream &operator<<(std::ostream &os, const Pose3& pose) {\n    os << pose.rotation() << \"\\n\" << pose.translation() << endl;\n    return os;\n  }\n\n} // namespace gtsam\n", "meta": {"hexsha": "faec92a6b8488dea2f93d4343dc5fb8d8ffe0624", "size": 11921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Pose3.cpp", "max_stars_repo_name": "malcolmreynolds/GTSAM", "max_stars_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-23T19:34:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-23T19:34:50.000Z", "max_issues_repo_path": "gtsam/geometry/Pose3.cpp", "max_issues_repo_name": "malcolmreynolds/GTSAM", "max_issues_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/geometry/Pose3.cpp", "max_forks_repo_name": "malcolmreynolds/GTSAM", "max_forks_repo_head_hexsha": "e911b4d39f8a8c8604663bd46f10e7f53c860ae8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2061281337, "max_line_length": 106, "alphanum_fraction": 0.4832648268, "num_tokens": 3240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.4357738586084505}}
{"text": "#ifndef GEOMETRY_UTILS_HPP\n#define GEOMETRY_UTILS_HPP\n/**\n * @file geometry_utils.hpp\n * @author Rafael Rey (rreyarc@upo.es)\n * @brief A set of geometry utilities functions\n * @version 0.1\n * @date 2021-06-29\n * \n * @copyright Copyright (c) 2021\n * \n */\n#include <iostream>\n#include <vector>\n#include <math.h>\n#include <Eigen/Dense>\n\n#include \"utils/utils.hpp\"\n#include \"utils/LineOfSight.hpp\"\n#include \"utils/world.hpp\"\n\n\nnamespace Planners\n{\n    namespace utils\n    {\n        namespace geometry\n        {\n            /**\n             * @brief Return the integrated distance alongside the _path object with the _resolution given\n             * \n             * @param _path CoordinateList object of points (discrete)\n             * @param _resolution \n             * @return float continous path length\n             */\n            float calculatePathLength(const CoordinateList &_path, const double &_resolution);\n\n            /**\n             * @brief Get the Adjacent Path object\n             * \n             * @param _path \n             * @param _algorithm \n             * @return utils::CoordinateList \n             */\n            utils::CoordinateList getAdjacentPath(const utils::CoordinateList &_path, const utils::DiscreteWorld &_world);\n            /**\n             * @brief Discrete distance multiplied by dist_scale_factor_\n             * \n             * @param n1 \n             * @param n2 \n             * @return unsigned int \n             */\n            unsigned int distanceBetween2Nodes(const Node &_n1, const Node &_n2);\n            /**\n             * @brief  Discrete distance multiplied by dist_scale_factor_\n             * \n             * @param n1 \n             * @param n2 \n             * @return unsigned int \n             */\n            unsigned int distanceBetween2Nodes(const Node *_n1, const Node *_n2);\n            \n            /**\n             * @brief \n             * \n             * @param _v1 \n             * @param _v2 \n             * @return unsigned int \n             */\n            unsigned int distanceBetween2Nodes(const Vec3i &_v1, const Vec3i &_v2);\n            /**\n             * @brief Discrete distance \n             * \n             * @param n1 \n             * @param n2 \n             * @return unsigned int \n             */\n            unsigned int NodesBetween2Nodes(const Node &_n1, const Node &_n2);\n            /**\n             * @brief  Discrete distance             * \n             * @param n1 \n             * @param n2 \n             * @return unsigned int \n             */\n            unsigned int NodesBetween2Nodes(const Node *_n1, const Node *_n2);\n            \n            /**\n             * @brief \n             * \n             * @param _v1 \n             * @param _v2 \n             * @return unsigned int \n             */\n            unsigned int NodesBetween2Nodes(const Vec3i &_v1, const Vec3i &_v2);\n\n            /**\n             * @brief Returns the absolute value vector \n             * \n             * @param _vec \n             * @return Vec3i \n             */\n            Vec3i abs(const Vec3i &_vec);\n\n\n            int dotProduct(const Vec3i &_v1, const Vec3i &_v2);\n\n            double moduleVector(const Vec3i &_v);\n\n            double angleBetweenThreePoints(const Vec3i &_v1, const Vec3i &_v2, const Vec3i &_v3);\n\n            double angleBetweenThreePoints(const Eigen::Vector3d &_v1, const Eigen::Vector3d &_v2, const Eigen::Vector3d &_v3);\n\n            double getCircunferenceRadius(const Vec3i &_v1, const Vec3i &_v2, const Vec3i &_v3);\n\n            double getCircunferenceRadius(const Eigen::Vector3d &_v1, const Eigen::Vector3d &_v2, const Eigen::Vector3d &_v3);\n            \n        }//namespace geometry\n    }//namespace utils\n}\n\n#endif", "meta": {"hexsha": "e891766c929578316b2839d76ff76cc6c00c5a92", "size": 3711, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/utils/geometry_utils.hpp", "max_stars_repo_name": "RafaelRey/3D_heuristic_path_planners", "max_stars_repo_head_hexsha": "e23a286a730485db4c87b0ae3168d008699f9df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-06-30T09:41:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T05:52:47.000Z", "max_issues_repo_path": "include/utils/geometry_utils.hpp", "max_issues_repo_name": "RafaelRey/3D_heuristic_path_planners", "max_issues_repo_head_hexsha": "e23a286a730485db4c87b0ae3168d008699f9df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-30T09:29:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-26T18:40:49.000Z", "max_forks_repo_path": "include/utils/geometry_utils.hpp", "max_forks_repo_name": "robotics-upo/3D_heuristic_path_planners", "max_forks_repo_head_hexsha": "e23a286a730485db4c87b0ae3168d008699f9df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-03-11T14:22:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T05:52:50.000Z", "avg_line_length": 30.6694214876, "max_line_length": 127, "alphanum_fraction": 0.5208838588, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.43575632393604385}}
{"text": "\n#include <NTL/vec_ZZ_pE.h>\n\n\nNTL_START_IMPL\n\nvoid InnerProduct(ZZ_pE& x, const vec_ZZ_pE& a, const vec_ZZ_pE& b)\n{\n   long n = min(a.length(), b.length());\n   long i;\n   ZZ_pX accum, t;\n\n   clear(accum);\n   for (i = 0; i < n; i++) {\n      mul(t, rep(a[i]), rep(b[i]));\n      add(accum, accum, t);\n   }\n\n   conv(x, accum);\n}\n\nvoid InnerProduct(ZZ_pE& x, const vec_ZZ_pE& a, const vec_ZZ_pE& b,\n                  long offset)\n{\n   if (offset < 0) LogicError(\"InnerProduct: negative offset\");\n   if (NTL_OVERFLOW(offset, 1, 0)) ResourceError(\"InnerProduct: offset too big\");\n\n   long n = min(a.length(), b.length()+offset);\n   long i;\n   ZZ_pX accum, t;\n\n   clear(accum);\n   for (i = offset; i < n; i++) {\n      mul(t, rep(a[i]), rep(b[i-offset]));\n      add(accum, accum, t);\n   }\n\n   conv(x, accum);\n}\n\nvoid mul(vec_ZZ_pE& x, const vec_ZZ_pE& a, const ZZ_pE& b_in)\n{\n   ZZ_pE b = b_in;\n   long n = a.length();\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      mul(x[i], a[i], b);\n}\n\nvoid mul(vec_ZZ_pE& x, const vec_ZZ_pE& a, const ZZ_p& b_in)\n{\n   NTL_ZZ_pRegister(b);\n   b = b_in;\n   long n = a.length();\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      mul(x[i], a[i], b);\n}\n\nvoid mul(vec_ZZ_pE& x, const vec_ZZ_pE& a, long b_in)\n{\n   NTL_ZZ_pRegister(b);\n   b = b_in;\n   long n = a.length();\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      mul(x[i], a[i], b);\n}\n\n\nvoid add(vec_ZZ_pE& x, const vec_ZZ_pE& a, const vec_ZZ_pE& b)\n{\n   long n = a.length();\n   if (b.length() != n) LogicError(\"vector add: dimension mismatch\");\n\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      add(x[i], a[i], b[i]);\n}\n\nvoid sub(vec_ZZ_pE& x, const vec_ZZ_pE& a, const vec_ZZ_pE& b)\n{\n   long n = a.length();\n   if (b.length() != n) LogicError(\"vector sub: dimension mismatch\");\n\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      sub(x[i], a[i], b[i]);\n}\n\nvoid negate(vec_ZZ_pE& x, const vec_ZZ_pE& a)\n{\n   long n = a.length();\n\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      negate(x[i], a[i]);\n}\n\n\nvoid clear(vec_ZZ_pE& x)\n{\n   long n = x.length();\n   long i;\n   for (i = 0; i < n; i++)\n      clear(x[i]);\n}\n\n\n\nlong IsZero(const vec_ZZ_pE& a)\n{\n   long n = a.length();\n   long i;\n\n   for (i = 0; i < n; i++)\n      if (!IsZero(a[i]))\n         return 0;\n\n   return 1;\n}\n\nvec_ZZ_pE operator+(const vec_ZZ_pE& a, const vec_ZZ_pE& b)\n{\n   vec_ZZ_pE res;\n   add(res, a, b);\n   NTL_OPT_RETURN(vec_ZZ_pE, res);\n}\n\nvec_ZZ_pE operator-(const vec_ZZ_pE& a, const vec_ZZ_pE& b)\n{\n   vec_ZZ_pE res;\n   sub(res, a, b);\n   NTL_OPT_RETURN(vec_ZZ_pE, res);\n}\n\n\nvec_ZZ_pE operator-(const vec_ZZ_pE& a)\n{\n   vec_ZZ_pE res;\n   negate(res, a);\n   NTL_OPT_RETURN(vec_ZZ_pE, res);\n}\n\n\nZZ_pE operator*(const vec_ZZ_pE& a, const vec_ZZ_pE& b)\n{\n   ZZ_pE res;\n   InnerProduct(res, a, b);\n   return res;\n}\n\nvoid VectorCopy(vec_ZZ_pE& x, const vec_ZZ_pE& a, long n)\n{\n   if (n < 0) LogicError(\"VectorCopy: negative length\");\n   if (NTL_OVERFLOW(n, 1, 0)) ResourceError(\"overflow in VectorCopy\");\n\n   long m = min(n, a.length());\n\n   x.SetLength(n);\n  \n   long i;\n\n   for (i = 0; i < m; i++)\n      x[i] = a[i];\n\n   for (i = m; i < n; i++)\n      clear(x[i]);\n}\n\nvoid random(vec_ZZ_pE& x, long n)\n{\n   x.SetLength(n);\n   for (long i = 0; i < n; i++) random(x[i]);\n}\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "f51a9fb9b6660576cddf0ffbf761cf42f4bb8688", "size": 3320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/vec_ZZ_pE.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 160.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T09:32:19.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/vec_ZZ_pE.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2016-12-26T07:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T16:34:31.000Z", "max_forks_repo_path": "LibSource/ExtendedNTL/src/vec_ZZ_pE.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2016-10-10T17:56:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:56:39.000Z", "avg_line_length": 17.9459459459, "max_line_length": 81, "alphanum_fraction": 0.5596385542, "num_tokens": 1223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6513548714339145, "lm_q1q2_score": 0.4356784159986415}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MTL_SFUNCTOR_INCLUDE\n#define MTL_SFUNCTOR_INCLUDE\n\n#include <cmath>\n#include <complex>\n\n#include <boost/numeric/mtl/concept/std_concept.hpp>\n#include <boost/numeric/mtl/concept/magnitude.hpp>\n#include <boost/numeric/mtl/concept/static_functor.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n#include <boost/type_traits.hpp>\n\nnamespace mtl { namespace sfunctor {\n\ntemplate <typename Value1, typename Value2>\nstruct plus\n{\n    typedef const Value1&                                 first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef typename Addable<Value1, Value2>::result_type result_type;\n\n    static inline result_type apply(const Value1& v1, const Value2& v2)\n    {\n  return v1 + v2;\n    }\n\n    result_type operator() (const Value1& v1, const Value2& v2) const\n    {\n  vampir_trace<23> tracer;\n  return v1 + v2;\n    }\n};\n    \ntemplate <typename Value1, typename Value2>\nstruct minus\n{\n    typedef const Value1&                                 first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef typename Subtractable<Value1, Value2>::result_type result_type;\n\n    static inline result_type apply(const Value1& v1, const Value2& v2)\n    {\n  return v1 - v2;\n    }\n\n    result_type operator() (const Value1& v1, const Value2& v2) const\n    {\n  vampir_trace<24> tracer;\n  return v1 - v2;\n    }\n};\n\ntemplate <typename Value1, typename Value2>\nstruct times\n{\n    typedef const Value1&                                 first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef typename Multiplicable<Value1, Value2>::result_type result_type;\n\n    static inline result_type apply(const Value1& v1, const Value2& v2)\n    {\n  return v1 * v2;\n    }\n\n    result_type operator() (const Value1& v1, const Value2& v2) const\n    {\n  vampir_trace<25> tracer;\n  return v1 * v2;\n    }\n};\n\ntemplate <typename Value1, typename Value2>\nstruct divide\n{\n    typedef const Value1&                                 first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef typename Divisible<Value1, Value2>::result_type result_type;\n\n    static inline result_type apply(const Value1& v1, const Value2& v2)\n    {\n  return v1 / v2;\n    }\n\n    result_type operator() (const Value1& v1, const Value2& v2) const\n    {\n  vampir_trace<26> tracer;\n  return v1 / v2;\n    }\n};\n\ntemplate <typename Value1, typename Value2>\nstruct assign\n{\n    typedef Value1&                                       first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef Value1&                                       result_type;\n\n    static inline result_type apply(Value1& v1, const Value2& v2)\n    {\n  return v1= Value1(v2);\n    }\n\n    result_type operator() (Value1& v1, const Value2& v2) const\n    {\n  vampir_trace<27> tracer;\n  return v1= v2;\n    }\n};\n    \ntemplate <typename Value1, typename Value2>\nstruct plus_assign\n{\n    typedef Value1&                                       first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef Value1&                                       result_type;\n\n    static inline result_type apply(Value1& v1, const Value2& v2)\n    {\n  return v1+= v2;\n    }\n\n    result_type operator() (Value1& v1, const Value2& v2) const\n    {\n  vampir_trace<28> tracer;\n  return v1+= v2;\n    }\n};\n    \ntemplate <typename Value1, typename Value2>\nstruct minus_assign\n{\n    typedef Value1&                                       first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef Value1&                                       result_type;\n\n    static inline result_type apply(Value1& v1, const Value2& v2)\n    {\n  return v1-= v2;\n    }\n\n    result_type operator() (Value1& v1, const Value2& v2) const\n    {\n  vampir_trace<29> tracer;\n  return v1-= v2;\n    }\n};\n\ntemplate <typename Value1, typename Value2>\nstruct times_assign\n{\n    typedef Value1&                                       first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef Value1&                                       result_type;\n\n    static inline result_type apply(Value1& v1, const Value2& v2)\n    {\n  return v1*= v2;\n    }\n\n    result_type operator() (Value1& v1, const Value2& v2) const\n    {\n  vampir_trace<30> tracer;\n  return v1*= v2;\n    }\n};\n\ntemplate <typename Value1, typename Value2>\nstruct divide_assign\n{\n    typedef Value1&                                       first_argument_type;\n    typedef const Value2&                                 second_argument_type;\n    typedef Value1&                                       result_type;\n\n    static inline result_type apply(Value1& v1, const Value2& v2)\n    {\n  return v1/= v2;\n    }\n\n    result_type operator() (Value1& v1, const Value2& v2) const\n    {\n  vampir_trace<31> tracer;\n  return v1/= v2;\n    }\n};\n\n\n// Might be helpful for surplus functor arguments\ntemplate <typename Value>\nstruct identity\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v)\n    {\n  return v;\n    }\n\n    result_type operator() (const Value& v) const\n    {\n  vampir_trace<32> tracer;\n  return v;\n    }\n};\n\n\ntemplate <typename Value>\nstruct abs\n{\n    typedef const Value&                                  argument_type;\n    typedef typename Magnitude<Value>::type               result_type;\n\n    static inline result_type apply(const Value& v)\n    {            \n  using std::abs;\n  return abs(v);\n    }\n\n    result_type operator() (const Value& v)  const\n    {\n  vampir_trace<33> tracer; \n  return apply(v); \n    }\n};\n\ntemplate <typename Value>\nstruct sqrt\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v)\n    {            \n  using std::sqrt;\n  return sqrt(v);\n    }\n\n    result_type operator() (const Value& v)  const\n    {\n  vampir_trace<34> tracer;\n  return apply(v); \n    }\n};\n\ntemplate <typename Value>\nstruct square\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v)\n    {            \n  return v * v;\n    }\n\n    result_type operator() (const Value& v) const\n    {\n  vampir_trace<35> tracer;\n  return apply(v);\n    }\n};\n\n\ntemplate <typename Value>\nstruct negate\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) { return -v;  }\n    result_type operator() (const Value& v) const \n    {\n  vampir_trace<36> tracer;\n  return -v;\n    }\n};\n\ntemplate <typename Value>\nstruct acos\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::acos;\n        return acos(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n\n# ifdef MTL_WITH_MATH_ELEVEN\ntemplate <typename Value>\nstruct acosh\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::acosh;\n        return acosh(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n# endif\n\ntemplate <typename Value>\nstruct asin\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::asin;\n        return asin(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n\n# ifdef MTL_WITH_MATH_ELEVEN\ntemplate <typename Value>\nstruct asinh\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::asinh;\n        return asinh(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n# endif\n\ntemplate <typename Value>\nstruct atan\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::atan;\n        return atan(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n\n# ifdef MTL_WITH_MATH_ELEVEN\ntemplate <typename Value>\nstruct atanh\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::atanh;\n        return atanh(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n# endif\n\n\ntemplate <typename Value>\nstruct cos\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::cos;\n        return cos(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n\ntemplate <typename Value>\nstruct cosh\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::cosh;\n        return cosh(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n\ntemplate <typename Value>\nstruct sin\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::sin;\n        return sin(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n\ntemplate <typename Value>\nstruct sinh\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::sinh;\n        return sinh(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n\ntemplate <typename Value>\nstruct tan\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::tan;\n        return tan(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n\ntemplate <typename Value>\nstruct tanh\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::tanh;\n        return tanh(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n\n// Rounding functions\n\ntemplate <typename Value>\nstruct ceil\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    {\n        return apply(v, boost::is_integral<Value>());\n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n\nprivate:\n    static inline result_type apply(const Value& v, boost::integral_constant<bool, false>)\n    {\n        using std::ceil;\n        return ceil(v);\n    }\n    \n    // return value directly for integer values\n    static inline result_type apply(const Value& v, boost::integral_constant<bool, true>)\n    {\n        return v;\n    };\n};\n\ntemplate <typename Value>\nstruct floor\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    {\n        return apply(v, boost::is_integral<Value>());\n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n\nprivate:\n    static inline result_type apply(const Value& v, boost::integral_constant<bool, false>)\n    {\n        using std::floor;\n        return floor(v);\n    }\n    \n    // return value directly for integer values\n    static inline result_type apply(const Value& v, boost::integral_constant<bool, true>)\n    {\n        return v;\n    };\n};\n\n# ifdef MTL_WITH_MATH_ELEVEN    \n\n    template <typename Value>\n    struct round\n    {\n        typedef const Value&                                  argument_type;\n        typedef Value                                         result_type;\n\n        static inline result_type apply(const Value& v) \n        {\n            return apply(v, boost::is_integral<Value>());\n        }\n        result_type operator() (const Value& v) const \n        {\n            return apply(v);\n        }\n\n    private:\n        static inline result_type apply(const Value& v, boost::integral_constant<bool, false>)\n        {\n            using std::round;\n            return round(v);\n        }\n        \n        // return value directly for integer values\n        static inline result_type apply(const Value& v, boost::integral_constant<bool, true>)\n        {\n            return v;\n        };\n    };\n\n    template <typename Value>\n    struct trunc\n    {\n        typedef const Value&                                  argument_type;\n        typedef Value                                         result_type;\n\n        static inline result_type apply(const Value& v) \n        {\n            return apply(v, boost::is_integral<Value>());\n        }\n        result_type operator() (const Value& v) const \n        {\n            return apply(v);\n        }\n\n    private:\n        static inline result_type apply(const Value& v, boost::integral_constant<bool, false>)\n        {\n            using std::trunc;\n            return trunc(v);\n        }\n        \n        // return value directly for integer values\n        static inline result_type apply(const Value& v, boost::integral_constant<bool, true>)\n        {\n            return v;\n        };\n    };\n\n# endif\n\n// Logarithmic functions\n\ntemplate <typename Value>\nstruct log\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::log;\n        return log(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n\n# ifdef MTL_WITH_MATH_ELEVEN    \ntemplate <typename Value>\nstruct log2\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::log2;\n        return log2(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n        return apply(v);\n    }\n};\n# endif\n\ntemplate <typename Value>\nstruct log10\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::log10;\n        return log10(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n        return apply(v);\n    }\n};\n\n// Exponential functions\n\ntemplate <typename Value>\nstruct exp\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::exp;\n        return exp(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n        return apply(v);\n    }\n};\n\n# ifdef MTL_WITH_MATH_ELEVEN    \ntemplate <typename Value>\nstruct exp2\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::exp2;\n        return exp2(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n        return apply(v);\n    }\n};\n#endif\n\ntemplate <typename Value>\nstruct exp10\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::exp;\n        return exp(v * 2.302585092994045684017991454684364207601101488628772976033);  \n    }\n    result_type operator() (const Value& v) const \n    {\n        return apply(v);\n    }\n};\n\n// Inverse square root functions\n\ntemplate <typename Value>\nstruct rsqrt\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::pow;\n        return pow(v, -0.5);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n\n// Error functions\n\n# ifdef MTL_WITH_MATH_ELEVEN    \ntemplate <typename Value>\nstruct erf\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::erf;\n        return erf(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n\ntemplate <typename Value>\nstruct erfc\n{\n    typedef const Value&                                  argument_type;\n    typedef Value                                         result_type;\n\n    static inline result_type apply(const Value& v) \n    { \n        using std::erfc;\n        return erfc(v);  \n    }\n    result_type operator() (const Value& v) const \n    {\n  return apply(v);\n    }\n};\n# endif\n\n/// Compose functors \\p F and \\p G, i.e. compute f(g(x)).\n/** Functors must be models of StaticUnaryFunctor,\n    StaticUnaryFunctor<G>::result_type must be convertible to\n    StaticUnaryFunctor<F>::argument_type.\n    Under these conditions compose<F, G> will be a model of StaticUnaryFunctor.\n**/\ntemplate <typename F, typename G>\nstruct compose\n{\n    typedef typename StaticUnaryFunctor<G>::argument_type argument_type;\n    typedef typename StaticUnaryFunctor<F>::result_type   result_type;\n    \n    static inline result_type apply(argument_type x)\n    {\n  return F::apply(G::apply(x));\n    }\n\n    result_type operator()(argument_type x) \n    {\n  vampir_trace<37> tracer;\n  return apply(x);\n    }\n};\n\n\n/// Compose functors \\p F and \\p G with G in F's first argument, i.e. compute f(g(x), y).\n/** F/G must be models of StaticBinaryFunctor/StaticUnaryFunctor,\n    StaticUnaryFunctor<G>::result_type must be convertible to\n    StaticBinaryFunctor<F>::first_argument_type.\n    Under these conditions compose_first<F, G> will be a model of StaticBinaryFunctor.\n**/\ntemplate <typename F, typename G>\nstruct compose_first\n{\n    typedef typename StaticUnaryFunctor<G>::argument_type         first_argument_type;\n    typedef typename StaticBinaryFunctor<F>::second_argument_type second_argument_type;\n    typedef typename StaticBinaryFunctor<F>::result_type          result_type;\n    \n    static inline result_type apply(first_argument_type x, second_argument_type y)\n    {\n  return F::apply(G::apply(x), y);\n    }\n\n    result_type operator()(first_argument_type x, second_argument_type y)\n    {\n  vampir_trace<38> tracer;\n  return apply(x, y);\n    }\n};\n\n\n/// Compose functors \\p F and \\p G with G in F's second argument, i.e. compute f(x, g(y)).\n/** F/G must be models of StaticBinaryFunctor/StaticUnaryFunctor,\n    StaticUnaryFunctor<G>::result_type must be convertible to\n    StaticBinaryFunctor<F>::second_argument_type.\n    Under these conditions compose_second<F, G> will be a model of StaticBinaryFunctor.\n**/\ntemplate <typename F, typename G>\nstruct compose_second\n{\n    typedef typename StaticBinaryFunctor<F>::first_argument_type  first_argument_type;\n    typedef typename StaticUnaryFunctor<G>::argument_type         second_argument_type;\n    typedef typename StaticBinaryFunctor<F>::result_type          result_type;\n    \n    static inline result_type apply(first_argument_type x, second_argument_type y)\n    {\n  return F::apply(x, G::apply(y));\n    }\n\n    result_type operator()(first_argument_type x, second_argument_type y)\n    {\n  vampir_trace<39> tracer;\n  return apply(x, y);\n    }\n};\n\n/// Compose functors \\p F, \\p G, and \\p H with G/H in F's first/second argument, i.e. compute f(g(x), h(y)).\n/** F/G must be models of StaticBinaryFunctor/StaticUnaryFunctor,\n    StaticUnaryFunctor<G>::result_type must be convertible to\n    StaticBinaryFunctor<F>::first_argument_type and\n    StaticUnaryFunctor<H>::result_type must be convertible to\n    StaticBinaryFunctor<F>::second_argument_type.\n    Under these conditions compose_both<F, G, H> will be a model of StaticBinaryFunctor.\n**/\ntemplate <typename F, typename G, typename H>\nstruct compose_both\n{\n    typedef typename StaticUnaryFunctor<G>::argument_type         first_argument_type;\n    typedef typename StaticUnaryFunctor<H>::argument_type         second_argument_type;\n    typedef typename StaticBinaryFunctor<F>::result_type          result_type;\n    \n    static inline result_type apply(first_argument_type x, second_argument_type y)\n    {\n  return F::apply(G::apply(x), H::apply(y));\n    }\n\n    result_type operator()(first_argument_type x, second_argument_type y)\n    {\n  vampir_trace<40> tracer;\n  return apply(x, y);\n    }\n};\n\n/// Compose unary functor \\p F with binary functor \\p G, i.e. compute f(g(x, y)).\n/** F/G must be models of StaticUnaryFunctor/StaticBinaryFunctor,\n    StaticBinaryFunctor<G>::result_type must be convertible to\n    StaticUnaryFunctor<F>::argument_type.\n    Under these conditions compose_binary<F, G> will be a model of StaticBinaryFunctor.\n**/\ntemplate <typename F, typename G>\nstruct compose_binary\n{\n    typedef typename StaticBinaryFunctor<G>::first_argument_type  first_argument_type;\n    typedef typename StaticBinaryFunctor<G>::second_argument_type second_argument_type;\n    typedef typename StaticUnaryFunctor<F>::result_type           result_type;\n    \n    static inline result_type apply(first_argument_type x, second_argument_type y)\n    {\n  return F::apply(G::apply(x, y));\n    }\n\n    result_type operator()(first_argument_type x, second_argument_type y)\n    {\n  vampir_trace<41> tracer;\n  return apply(x, y);\n    }\n};\n\n\n/// Templatized example of composition, computes l_2 norm in 2D, i.e. sqrt(abs(x*x + y*y))\ntemplate <typename T>\nstruct l_2_2D\n  : public compose_binary<sqrt<typename abs<T>::result_type>, \n        compose_binary<abs<T>, \n           compose_both<plus<T, T>, \n                  square<T>, \n                  square<T>  > \n                                        > \n                         >\n{};\n\n}} // namespace mtl::sfunctor\n\n#endif // MTL_SFUNCTOR_INCLUDE\n", "meta": {"hexsha": "05b5d49d2ec5983b01057fdb032855abee325fcf", "size": 24402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/sfunctor.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/mtl/operation/sfunctor.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/mtl/operation/sfunctor.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 26.1263383298, "max_line_length": 108, "alphanum_fraction": 0.5769199246, "num_tokens": 5342, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.4355352759641682}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_DETAIL_PRIMES_HPP\n#define CRYPTO3_DETAIL_PRIMES_HPP\n\n#include <boost/integer.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace detail {\n\n            template<int Bits>\n            struct all_ones {\n                typedef typename boost::uint_t<Bits>::least type;\n                static type const value = (all_ones<Bits - 1>::value << 1) | 1;\n            };\n            template<>\n            struct all_ones<0> {\n                typedef boost::uint_t<0>::least type;\n                static type const value = 0;\n            };\n\n            template<int Bits>\n            struct largest_prime;\n\n#define CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(B, D)                              \\\n    template<>                                                                         \\\n    struct largest_prime<B> {                                                          \\\n        constexpr static boost::uint_t<B>::least const value = all_ones<B>::value - D; \\\n    };                                                                                 \\\n    constexpr boost::uint_t<B>::least const largest_prime<B>::value;\n\n            // http://primes.utm.edu/lists/2small/0bit.html or\n            // http://www.research.att.com/~njas/sequences/A013603\n            // Though those offets are from 2**b; This code is offsets from 2**b-1\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(2, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(3, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(4, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(5, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(6, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(7, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(8, 4);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(9, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(10, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(11, 8);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(12, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(13, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(14, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(15, 18);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(16, 14);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(17, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(18, 4);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(19, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(20, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(21, 8);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(22, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(23, 14);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(24, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(25, 38);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(26, 4);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(27, 38);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(28, 56);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(29, 2);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(30, 34);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(31, 0);\n            CRYPTO3_HASH_DEFINE_LARGEST_PRIME_BY_OFFSET(32, 4);\n\n        }    // namespace detail\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_HASH_DETAIL_PRIMES_HPP\n", "meta": {"hexsha": "983019b24ccaae7b5e592b596f032a1c24064bec", "size": 3858, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/detail/primes.hpp", "max_stars_repo_name": "NilFoundation/boost-crypto", "max_stars_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-02T06:19:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T04:55:03.000Z", "max_issues_repo_path": "include/boost/crypto3/detail/primes.hpp", "max_issues_repo_name": "NilFoundation/boost-crypto", "max_issues_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-04-06T21:49:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-18T04:54:51.000Z", "max_forks_repo_path": "include/boost/crypto3/detail/primes.hpp", "max_forks_repo_name": "NilFoundation/boost-crypto", "max_forks_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:14:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:14:37.000Z", "avg_line_length": 48.835443038, "max_line_length": 88, "alphanum_fraction": 0.6036806636, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118222, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.43553502052839527}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file cclgmprocess.hpp\n    \\brief cross currency lgm model process\n           the fx processes are modeled in log spot here\n           (different from BlackScholesProcess where it is mixed\n           log spot / spot depending on the method)\n*/\n\n#ifndef quantlib_cclgm_process_hpp\n#define quantlib_cclgm_process_hpp\n\n#include <ql/math/matrixutilities/pseudosqrt.hpp>\n#include <ql/experimental/models/cclgmparametrization.hpp>\n\n#include <boost/unordered_map.hpp>\n\nnamespace QuantLib {\n\ntemplate <class Impl, class ImplFx, class ImplLgm>\nclass CcLgmProcess : public StochasticProcess {\n  public:\n    CcLgmProcess(const boost::shared_ptr<detail::CcLgmParametrization<\n                     Impl, ImplFx, ImplLgm> > &parametrization,\n                 const std::vector<Handle<Quote> > &fxSpots,\n                 const std::vector<Handle<YieldTermStructure> > &curves);\n\n    //! Stochastic process interface\n    Size size() const;\n    Size factors() const;\n    Disposable<Array> initialValues() const;\n    Disposable<Array> drift(Time t, const Array &x) const;      // not available\n    Disposable<Matrix> diffusion(Time t, const Array &x) const; // not available\n    Disposable<Array> expectation(Time t0, const Array &x0, Time dt) const;\n    Disposable<Matrix> stdDeviation(Time t0, const Array &x0, Time dt) const;\n    Disposable<Matrix> covariance(Time t0, const Array &x0, Time dt) const;\n\n    //! clear cache\n    void flushCache() const;\n\n    //! curves inspector\n    Handle<YieldTermStructure> termStructure(const Size i) const {\n        QL_REQUIRE(i <= n_, \"term structure index (\"\n                                << i << \") out of range 0...\" << n_);\n        return curves_[i];\n    }\n\n  private:\n    const boost::shared_ptr<\n        detail::CcLgmParametrization<Impl, ImplFx, ImplLgm> > p_;\n    const std::vector<Handle<Quote> > fxSpots_;\n    const std::vector<Handle<YieldTermStructure> > curves_;\n    const Size n_;\n\n    struct cache_key {\n        double t0;\n        double dt;\n        const bool operator==(const cache_key &o) const {\n            return (t0 == o.t0) && (dt == o.dt);\n        }\n    };\n\n    struct cache_hasher : std::unary_function<cache_key, std::size_t> {\n        std::size_t operator()(cache_key const &x) const {\n            std::size_t seed = 0;\n            boost::hash_combine(seed, x.t0);\n            boost::hash_combine(seed, x.dt);\n            return seed;\n        }\n    };\n\n    mutable boost::unordered_map<cache_key, Array, cache_hasher> cache_e_;\n    mutable boost::unordered_map<cache_key, Matrix, cache_hasher> cache_v_,\n        cache_s_;\n};\n\n// inline\n\ntemplate <class Impl, class ImplFx, class ImplLgm>\nvoid CcLgmProcess<Impl, ImplFx, ImplLgm>::flushCache() const {\n    cache_v_.clear();\n    cache_s_.clear();\n    cache_e_.clear();\n}\n\ntemplate <class Impl, class ImplFx, class ImplLgm>\ninline Size CcLgmProcess<Impl, ImplFx, ImplLgm>::size() const {\n    return 2 * n_ + 1;\n}\n\ntemplate <class Impl, class ImplFx, class ImplLgm>\ninline Size CcLgmProcess<Impl, ImplFx, ImplLgm>::factors() const {\n    return 2 * n_ + 1;\n}\n\ntemplate <class Impl, class ImplFx, class ImplLgm>\ninline Disposable<Array>\nCcLgmProcess<Impl, ImplFx, ImplLgm>::initialValues() const {\n    Array res(2 * n_ + 1);\n    for (Size i = 0; i < n_; ++i) {\n        res[i] = fxSpots_[i]->value();\n    }\n    for (Size i = n_; i < 2 * n_ + 1; ++i) {\n        res[i] = 0.0;\n    }\n    return res;\n}\n\ntemplate <class Impl, class ImplFx, class ImplLgm>\ninline Disposable<Array>\nCcLgmProcess<Impl, ImplFx, ImplLgm>::drift(Time t, const Array &x) const {\n    QL_FAIL(\"drift not implemented\");\n}\n\ntemplate <class Impl, class ImplFx, class ImplLgm>\ninline Disposable<Matrix>\nCcLgmProcess<Impl, ImplFx, ImplLgm>::diffusion(Time t, const Array &x) const {\n    QL_FAIL(\"diffusion not implemented\");\n}\n\ntemplate <class Impl, class ImplFx, class ImplLgm>\ninline Disposable<Array>\nCcLgmProcess<Impl, ImplFx, ImplLgm>::expectation(Time t0, const Array &x0,\n                                                 Time dt) const {\n    cache_key k = {t0, dt};\n    typename boost::unordered_map<cache_key, Array>::iterator it =\n        cache_e_.find(k);\n    Array res(2 * n_ + 1, 0.0);\n    if (it == cache_e_.end()) {\n        // fx\n        for (Size i = 0; i < n_; ++i) {\n            res[i] =\n                std::log(curves_[i + 1]->discount(t0 + dt) /\n                         curves_[i + 1]->discount(t0) *\n                         curves_[0]->discount(t0) /\n                         curves_[0]->discount(t0 + dt)) -\n                0.5 * p_->int_sigma_i_sigma_j(i, i, t0, t0 + dt) +\n                0.5 * (p_->H_i(0, t0 + dt) * p_->H_i(0, t0 + dt) *\n                           p_->zeta_i(0, t0 + dt) -\n                       p_->H_i(0, t0) * p_->H_i(0, t0) * p_->zeta_i(0, t0) -\n                       p_->int_H_i_H_j_alpha_i_alpha_j(0, 0, t0, t0 + dt)) -\n                0.5 * (p_->H_i(i + 1, t0 + dt) * p_->H_i(i + 1, t0 + dt) *\n                           p_->zeta_i(i + 1, t0 + dt) -\n                       p_->H_i(i + 1, t0) * p_->H_i(i + 1, t0) *\n                           p_->zeta_i(i + 1, t0) -\n                       p_->int_H_i_H_j_alpha_i_alpha_j(i + 1, i + 1, t0,\n                                                       t0 + dt)) +\n                p_->int_H_i_alpha_i_sigma_j(0, i, t0, t0 + dt) -\n                p_->H_i(i + 1, t0 + dt) *\n                    (-p_->int_H_i_alpha_i_alpha_j(i + 1, i + 1, t0, t0 + dt) +\n                     p_->int_H_i_alpha_i_alpha_j(0, i + 1, t0, t0 + dt) -\n                     p_->int_alpha_i_sigma_j(i + 1, i, t0, t0 + dt)) -\n                p_->int_H_i_H_j_alpha_i_alpha_j(i + 1, i + 1, t0, t0 + dt) +\n                p_->int_H_i_H_j_alpha_i_alpha_j(0, i + 1, t0, t0 + dt) -\n                p_->int_H_i_alpha_i_sigma_j(i + 1, i, t0, t0 + dt);\n        }\n        // lgm\n        for (Size i = 1; i < n_ + 1; ++i) {\n            res[n_ + i] = -p_->int_H_i_alpha_i_alpha_j(i, i, t0, t0 + dt) -\n                          p_->int_alpha_i_sigma_j(i, i - 1, t0, t0 + dt) +\n                          p_->int_H_i_alpha_i_alpha_j(0, i, t0, t0 + dt);\n        }\n        cache_e_.insert(std::make_pair(k, res));\n    } else {\n        res = it->second;\n    }\n    for (Size i = 0; i < n_; ++i) {\n        res[i] +=\n            x0[i] + (p_->H_i(0, t0 + dt) - p_->H_i(0, t0)) * x0[n_] -\n            (p_->H_i(i + 1, t0 + dt) - p_->H_i(i + 1, t0)) * x0[n_ + i + 1];\n    }\n    for (Size i = 0; i < n_ + 1; ++i) {\n        res[n_ + i] += x0[n_ + i];\n    }\n    return res;\n}\n\ntemplate <class Impl, class ImplFx, class ImplLgm>\ninline Disposable<Matrix>\nCcLgmProcess<Impl, ImplFx, ImplLgm>::covariance(Time t0, const Array &x0,\n                                                Time dt) const {\n    cache_key k = {t0, dt};\n    typename boost::unordered_map<cache_key, Matrix>::iterator i =\n        cache_v_.find(k);\n    if (i == cache_v_.end()) {\n        Matrix res(2 * n_ + 1, 2 * n_ + 1, 0.0);\n        // fx-fx\n        for (Size i = 0; i < n_; ++i) {\n            for (Size j = 0; j <= i; ++j) {\n                res[i][j] = res[j][i] =\n                    // row 1\n                    p_->H_i(0, t0 + dt) * p_->H_i(0, t0 + dt) *\n                        p_->int_alpha_i_alpha_j(0, 0, t0, t0 + dt) -\n                    2.0 * p_->H_i(0, t0 + dt) *\n                        p_->int_H_i_alpha_i_alpha_j(0, 0, t0, t0 + dt) +\n                    p_->int_H_i_H_j_alpha_i_alpha_j(0, 0, t0, t0 + dt) -\n                    // row 2\n                    p_->H_i(0, t0 + dt) * p_->H_i(j + 1, t0 + dt) *\n                        p_->int_alpha_i_alpha_j(0, j + 1, t0, t0 + dt) +\n                    p_->H_i(j + 1, t0 + dt) *\n                        p_->int_H_i_alpha_i_alpha_j(0, j + 1, t0, t0 + dt) +\n                    p_->H_i(0, t0 + dt) *\n                        p_->int_H_i_alpha_i_alpha_j(j + 1, 0, t0, t0 + dt) -\n                    p_->int_H_i_H_j_alpha_i_alpha_j(0, j + 1, t0, t0 + dt) -\n                    // row 3\n                    p_->H_i(0, t0 + dt) * p_->H_i(i + 1, t0 + dt) *\n                        p_->int_alpha_i_alpha_j(0, i + 1, t0, t0 + dt) +\n                    p_->H_i(i + 1, t0 + dt) *\n                        p_->int_H_i_alpha_i_alpha_j(0, i + 1, t0, t0 + dt) +\n                    p_->H_i(0, t0 + dt) *\n                        p_->int_H_i_alpha_i_alpha_j(i + 1, 0, t0, t0 + dt) -\n                    p_->int_H_i_H_j_alpha_i_alpha_j(0, i + 1, t0, t0 + dt) +\n                    // row 4\n                    p_->H_i(0, t0 + dt) *\n                        p_->int_alpha_i_sigma_j(0, j, t0, t0 + dt) -\n                    p_->int_H_i_alpha_i_sigma_j(0, j, t0, t0 + dt) +\n                    // row 5\n                    p_->H_i(0, t0 + dt) *\n                        p_->int_alpha_i_sigma_j(0, i, t0, t0 + dt) -\n                    p_->int_H_i_alpha_i_sigma_j(0, i, t0, t0 + dt) -\n                    // row 6\n                    p_->H_i(i + 1, t0 + dt) *\n                        p_->int_alpha_i_sigma_j(i + 1, j, t0, t0 + dt) +\n                    p_->int_H_i_alpha_i_sigma_j(i + 1, j, t0, t0 + dt) -\n                    // row 7\n                    p_->H_i(j + 1, t0 + dt) *\n                        p_->int_alpha_i_sigma_j(j + 1, i, t0, t0 + dt) +\n                    p_->int_H_i_alpha_i_sigma_j(j + 1, i, t0, t0 + dt) +\n                    // row 8\n                    p_->H_i(i + 1, t0 + dt) * p_->H_i(j + 1, t0 + dt) *\n                        p_->int_alpha_i_alpha_j(i + 1, j + 1, t0, t0 + dt) -\n                    p_->H_i(j + 1, t0 + dt) *\n                        p_->int_H_i_alpha_i_alpha_j(i + 1, j + 1, t0, t0 + dt) -\n                    p_->H_i(i + 1, t0 + dt) *\n                        p_->int_H_i_alpha_i_alpha_j(j + 1, i + 1, t0, t0 + dt) +\n                    p_->int_H_i_H_j_alpha_i_alpha_j(i + 1, j + 1, t0, t0 + dt) +\n                    // row 9\n                    p_->int_sigma_i_sigma_j(i, j, t0, t0 + dt);\n            }\n        }\n        // fx-lgm\n        for (Size i = 0; i < n_ + 1; ++i) {\n            for (Size j = 0; j < n_; ++j) {\n                res[j][i + n_] = res[i + n_][j] =\n                    p_->H_i(0, t0 + dt) *\n                        p_->int_alpha_i_alpha_j(0, i, t0, t0 + dt) -\n                    p_->int_H_i_alpha_i_alpha_j(0, i, t0, t0 + dt) -\n                    p_->H_i(j + 1, t0 + dt) *\n                        p_->int_alpha_i_alpha_j(j + 1, i, t0, t0 + dt) +\n                    p_->int_H_i_alpha_i_alpha_j(j + 1, i, t0, t0 + dt) +\n                    p_->int_alpha_i_sigma_j(i, j, t0, t0 + dt);\n            }\n        }\n        // lgm-lgm\n        for (Size i = 0; i < n_ + 1; ++i) {\n            for (Size j = 0; j <= i; ++j) {\n                res[i + n_][j + n_] = res[j + n_][i + n_] =\n                    p_->int_alpha_i_alpha_j(i, j, t0, t0 + dt);\n            }\n        }\n        cache_v_.insert(std::make_pair(k, res));\n        return res;\n    } else {\n        // we need to make a copy here since a disposable is returned\n        Matrix tmp = i->second;\n        return tmp;\n    }\n}\n\ntemplate <class Impl, class ImplFx, class ImplLgm>\ninline Disposable<Matrix>\nCcLgmProcess<Impl, ImplFx, ImplLgm>::stdDeviation(Time t0, const Array &x0,\n                                                  Time dt) const {\n    cache_key k = {t0, dt};\n    typename boost::unordered_map<cache_key, Matrix>::iterator i =\n        cache_s_.find(k);\n    if (i == cache_s_.end()) {\n        Matrix tmp =\n            pseudoSqrt(covariance(t0, x0, dt), SalvagingAlgorithm::Spectral);\n        cache_s_.insert(std::make_pair(k, tmp));\n        return tmp;\n    } else {\n        // we need to make a copy here since a disposable is returned\n        Matrix tmp = i->second;\n        return tmp;\n    }\n}\n\n// implementation\n\ntemplate <class Impl, class ImplFx, class ImplLgm>\nCcLgmProcess<Impl, ImplFx, ImplLgm>::CcLgmProcess(\n    const boost::shared_ptr<\n        detail::CcLgmParametrization<Impl, ImplFx, ImplLgm> > &parametrization,\n    const std::vector<Handle<Quote> > &fxSpots,\n    const std::vector<Handle<YieldTermStructure> > &curves)\n    : p_(parametrization), fxSpots_(fxSpots), curves_(curves), n_(p_->n()) {\n\n    QL_REQUIRE(fxSpots_.size() == n_,\n               fxSpots_.size()\n                   << \" fx spots given, while parametrization suggests \" << n_);\n    QL_REQUIRE(curves_.size() == n_ + 1,\n               curves_.size()\n                   << \" curves given, while parametrization suggests \"\n                   << (n_ + 1));\n\n    for (Size i = 0; i < n_; ++i)\n        registerWith(fxSpots_[i]);\n}\n\n} // namesapce QuantLib\n\n#endif\n", "meta": {"hexsha": "490eb9fa83ddef2f34f3ecd7e4d9ed3b3451561a", "size": 13272, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/cclgmprocess.hpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/experimental/models/cclgmprocess.hpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/experimental/models/cclgmprocess.hpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 40.0966767372, "max_line_length": 80, "alphanum_fraction": 0.5132610006, "num_tokens": 4062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933183101078, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4355350158528421}}
{"text": "#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>\n#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>\n#include \"ui_Mean_curvature_flow_skeleton_plugin.h\"\n#include \"Scene_polyhedron_item.h\"\n#include \"Scene_points_with_normal_item.h\"\n#include \"Scene_polylines_item.h\"\n#include \"Scene.h\"\n\n#include \"Polyhedron_type.h\"\n\n#include <QApplication>\n#include <QMainWindow>\n#include <QInputDialog>\n#include <QTime>\n#include <QMessageBox>\n\n#include <Eigen/Sparse>\n\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Eigen_solver_traits.h>\n#include <CGAL/extract_mean_curvature_flow_skeleton.h>\n#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>\n#include <CGAL/iterator.h>\n#include <CGAL/Polygon_mesh_processing/connected_components.h>\n#include <CGAL/boost/graph/split_graph_into_polylines.h>\n#include <CGAL/mesh_segmentation.h>\n#include <CGAL/Polyhedron_copy_3.h>\n#include <queue>\n\n\ntypedef boost::graph_traits<Polyhedron>::vertex_descriptor          vertex_descriptor;\ntypedef boost::graph_traits<Polyhedron>::vertex_iterator            vertex_iterator;\ntypedef boost::graph_traits<Polyhedron>::halfedge_descriptor        halfedge_descriptor;\ntypedef Polyhedron::Facet_iterator                                  Facet_iterator;\n\ntypedef CGAL::Mean_curvature_flow_skeletonization<Polyhedron>      Mean_curvature_skeleton;\ntypedef Mean_curvature_skeleton::Skeleton Skeleton;\n\ntypedef Polyhedron::Traits         Kernel;\ntypedef Kernel::Point_3            Point;\n\nstruct Polyline_visitor\n{\n  typedef std::vector<Point> Polyline;\n  typedef std::vector<std::size_t> Polyline_of_ids;\n\n  std::list<Polyline>& polylines;\n  Skeleton& skeleton;\n\n  Polyline_visitor(std::list<Polyline>& lines, Skeleton& skeleton)\n    : polylines(lines),\n      skeleton(skeleton)\n  {}\n\n  void start_new_polyline()\n  {\n    Polyline V;\n    polylines.push_back(V);\n  }\n\n  void add_node(boost::graph_traits<Skeleton>::vertex_descriptor vd)\n  {\n    Polyline& polyline = polylines.back();\n    polyline.push_back(skeleton[vd].point);\n  }\n\n  void end_polyline(){}\n};\n\ntemplate<class ValueType>\nstruct Facet_with_id_pmap\n    : public boost::put_get_helper<ValueType&,\n             Facet_with_id_pmap<ValueType> >\n{\n    typedef Polyhedron::Face_handle key_type;\n    typedef ValueType value_type;\n    typedef value_type& reference;\n    typedef boost::lvalue_property_map_tag category;\n\n    Facet_with_id_pmap(\n      std::vector<ValueType>& internal_vector\n    ) : internal_vector(internal_vector) { }\n\n    reference operator[](key_type key) const\n    { return internal_vector[key->id()]; }\nprivate:\n    std::vector<ValueType>& internal_vector;\n};\nusing namespace CGAL::Three;\nclass Polyhedron_demo_mean_curvature_flow_skeleton_plugin :\n  public QObject,\n  public Polyhedron_demo_plugin_helper\n{\n  Q_OBJECT\n  Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)\n  Q_PLUGIN_METADATA(IID \"com.geometryfactory.PolyhedronDemo.PluginInterface/1.0\")\n  QAction* actionMCFSkeleton;\n  QAction* actionConvert_to_medial_skeleton;\n\npublic:\n  // used by Polyhedron_demo_plugin_helper\n  QStringList actionsNames() const {\n    return QStringList() << \"actionMCFSkeleton\" << \"actionConvert_to_medial_skeleton\";\n  }\n\n  void init(QMainWindow* mainWindow, CGAL::Three::Scene_interface* scene_interface) {\n    mcs = NULL;\n    dockWidget = NULL;\n    ui = NULL;\n\n    actionMCFSkeleton = new QAction(tr(\"Mean Curvature Skeleton (Advanced)\"), mainWindow);\n    actionMCFSkeleton->setProperty(\"subMenuName\", \"Triangulated Surface Mesh Skeletonization\");\n    actionMCFSkeleton->setObjectName(\"actionMCFSkeleton\");\n\n    actionConvert_to_medial_skeleton = new QAction(tr(\"Extract Medial Skeleton\"), mainWindow);\n    actionConvert_to_medial_skeleton->setProperty(\"subMenuName\", \"Triangulated Surface Mesh Skeletonization\");\n    actionConvert_to_medial_skeleton->setObjectName(\"actionConvert_to_medial_skeleton\");\n\n    Polyhedron_demo_plugin_helper::init(mainWindow, scene_interface);\n\n    dockWidget = new QDockWidget(mw);\n    dockWidget->setVisible(false);\n    ui = new Ui::Mean_curvature_flow_skeleton_plugin();\n    ui->setupUi(dockWidget);\n    dockWidget->setFeatures(QDockWidget::DockWidgetMovable\n                          | QDockWidget::DockWidgetFloatable\n                          | QDockWidget::DockWidgetClosable);\n    dockWidget->setWindowTitle(\"Mean Curvature Flow Skeleton\");\n    add_dock_widget(dockWidget);\n\n    connect(ui->pushButton_contract, SIGNAL(clicked()),\n            this, SLOT(on_actionContract()));\n    connect(ui->pushButton_collapse, SIGNAL(clicked()),\n            this, SLOT(on_actionCollapse()));\n    connect(ui->pushButton_split, SIGNAL(clicked()),\n            this, SLOT(on_actionSplit()));\n    connect(ui->pushButton_degeneracy, SIGNAL(clicked()),\n            this, SLOT(on_actionDegeneracy()));\n    connect(ui->pushButton_run, SIGNAL(clicked()),\n            this, SLOT(on_actionRun()));\n    connect(ui->pushButton_skeletonize, SIGNAL(clicked()),\n            this, SLOT(on_actionSkeletonize()));\n    connect(ui->pushButton_converge, SIGNAL(clicked()),\n            this, SLOT(on_actionConverge()));\n    connect(dynamic_cast<Scene*>(scene), SIGNAL(updated_bbox()),\n            this, SLOT(on_actionUpdateBBox()));\n    connect(ui->pushButton_segment, SIGNAL(clicked()),\n            this, SLOT(on_actionSegment()));\n\n    QObject* scene_object = dynamic_cast<QObject*>(scene);\n    connect(scene_object, SIGNAL(itemAboutToBeDestroyed(CGAL::Three::Scene_item*)),\n            this, SLOT(on_actionItemAboutToBeDestroyed(CGAL::Three::Scene_item*)));\n  }\n\n  virtual void closure()\n  {\n    dockWidget->hide();\n  }\n\n  QList<QAction*> actions() const {\n    return QList<QAction*>() << actionMCFSkeleton << actionConvert_to_medial_skeleton;\n  }\n\n  bool applicable(QAction*) const {\n    return qobject_cast<Scene_polyhedron_item*>(scene->item(scene->mainSelectionIndex()));\n  }\n\n  void init_ui(double diag) {\n    ui->omega_H->setValue(0.1);\n    ui->omega_H->setSingleStep(0.1);\n    ui->omega_H->setDecimals(3);\n    ui->omega_P->setValue(0.2);\n    ui->omega_P->setSingleStep(0.1);\n    ui->omega_P->setDecimals(3);\n    ui->min_edge_length->setDecimals(7);\n    ui->min_edge_length->setValue(0.002 * diag);\n    ui->min_edge_length->setSingleStep(0.0000001);\n    ui->delta_area->setDecimals(7);\n    ui->delta_area->setValue(1e-4);\n    ui->delta_area->setSingleStep(1e-5);\n    ui->is_medially_centered->setChecked(false);\n\n    ui->label_omega_H->setToolTip(QString(\"omega_H controls the velocity of movement and approximation quality\"));\n    ui->label_omega_P->setToolTip(QString(\"omega_P controls the smoothness of the medial approximation\"));\n    ui->pushButton_contract->setToolTip(QString(\"contract mesh based on mean curvature flow\"));\n    ui->pushButton_collapse->setToolTip(QString(\"collapse short edges\"));\n    ui->pushButton_split->setToolTip(QString(\"split obtuse triangles\"));\n    ui->pushButton_degeneracy->setToolTip(QString(\"fix degenerate points\"));\n    ui->pushButton_skeletonize->setToolTip(QString(\"Turn mesh to a skeleton curve\"));\n    ui->pushButton_run->setToolTip(QString(\"run one iteration of contract, collapse, split, detect degeneracy\"));\n    ui->pushButton_converge->setToolTip(QString(\"iteratively contract the mesh until convergence\"));\n  }\n\n  bool check_item_index(int index) {\n    if (index < 0)\n    {\n      QMessageBox msgBox;\n      msgBox.setText(\"Please select an item first\");\n      msgBox.exec();\n      return false;\n    }\n    return true;\n  }\n\n  /// \\todo move this function into an include\n  bool is_mesh_valid(Polyhedron *pMesh) {\n    if (!pMesh->is_closed())\n    {\n      QMessageBox msgBox;\n      msgBox.setText(\"The mesh is not closed.\");\n      msgBox.exec();\n      return false;\n    }\n    if (!pMesh->is_pure_triangle())\n    {\n      QMessageBox msgBox;\n      msgBox.setText(\"The mesh is not a pure triangle mesh.\");\n      msgBox.exec();\n      return false;\n    }\n\n    // the algorithm is only applicable on a mesh\n    // that has only one connected component\n    std::size_t num_component;\n    CGAL::Counting_output_iterator output_it(&num_component);\n    CGAL::internal::corefinement::extract_connected_components(*pMesh, output_it);\n    ++output_it;\n    if (num_component != 1)\n    {\n      QMessageBox msgBox;\n      QString str = QString(\"The mesh is not a single closed mesh.\\n It has %1 components.\").arg(num_component);\n      msgBox.setText(str);\n      msgBox.exec();\n      return false;\n    }\n    return true;\n  }\n\n  /// \\todo remove duplicated code\n  // check if the Mean_curvature_skeleton exists\n  // or has the same polyheron item\n  // check if the mesh is a watertight triangle mesh\n  bool check_mesh(Scene_polyhedron_item* item) {\n    double omega_H = ui->omega_H->value();\n    double omega_P = ui->omega_P->value();\n    double min_edge_length = ui->min_edge_length->value();\n    double delta_area = ui->delta_area->value();\n    bool is_medially_centered = ui->is_medially_centered->isChecked();\n\n    Polyhedron *pMesh = item->polyhedron();\n\n    if (mcs == NULL)\n    {\n      if (!is_mesh_valid(pMesh))\n      {\n        return false;\n      }\n\n      mcs = new Mean_curvature_skeleton(*pMesh);\n      meso_skeleton = new Polyhedron(*pMesh);\n      input_triangle_mesh = pMesh;\n      //set algorithm parameters\n      mcs->set_quality_speed_tradeoff(omega_H);\n      mcs->set_medially_centered_speed_tradeoff(omega_P);\n      mcs->set_min_edge_length(min_edge_length);\n      mcs->set_is_medially_centered(is_medially_centered);\n      mcs->set_area_variation_factor(delta_area);\n\n      Scene_polyhedron_item* contracted_item = new Scene_polyhedron_item( meso_skeleton );\n      contracted_item->setName(QString(\"contracted mesh of %1\").arg(item->name()));\n\n      InputMeshItemIndex = scene->mainSelectionIndex();\n\n      contractedItemIndex = scene->addItem(contracted_item);\n\n      item->setVisible(false);\n\n      fixedPointsItemIndex = -1;\n      nonFixedPointsItemIndex = -1;\n      poleLinesItemIndex = -1;\n    }\n    else\n    {\n      if (input_triangle_mesh != pMesh)\n      {\n        if (!is_mesh_valid(pMesh))\n        {\n          return false;\n        }\n\n        delete mcs;\n\n        mcs = new Mean_curvature_skeleton(*pMesh);\n        meso_skeleton = new Polyhedron(*pMesh);\n        input_triangle_mesh = pMesh;\n        //set algorithm parameters\n        mcs->set_quality_speed_tradeoff(omega_H);\n        mcs->set_medially_centered_speed_tradeoff(omega_P);\n        mcs->set_min_edge_length(min_edge_length);\n        mcs->set_is_medially_centered(is_medially_centered);\n        mcs->set_area_variation_factor(delta_area);\n\n        Scene_polyhedron_item* contracted_item = new Scene_polyhedron_item(meso_skeleton);\n        contracted_item->setName(QString(\"contracted mesh of %1\").arg(item->name()));\n\n        InputMeshItemIndex = scene->mainSelectionIndex();\n\n        contractedItemIndex = scene->addItem(contracted_item);\n\n        item->setVisible(false);\n\n        fixedPointsItemIndex = -1;\n        nonFixedPointsItemIndex = -1;\n        poleLinesItemIndex = -1;\n      }\n      else\n      {\n        mcs->set_quality_speed_tradeoff(omega_H);\n        mcs->set_medially_centered_speed_tradeoff(omega_P);\n        mcs->set_min_edge_length(min_edge_length);\n        mcs->set_area_variation_factor(delta_area);\n        mcs->set_is_medially_centered(is_medially_centered);\n      }\n    }\n    return true;\n  }\n\n  void update_meso_skeleton()\n  {\n    CGAL::Polyhedron_copy_3<Mean_curvature_skeleton::Meso_skeleton, Polyhedron::HalfedgeDS> modifier(mcs->meso_skeleton());\n    meso_skeleton->delegate(modifier);\n    scene->item(contractedItemIndex)->invalidateOpenGLBuffers();\n    scene->itemChanged(contractedItemIndex);\n  }\n\n  void update_parameters(Mean_curvature_skeleton* mcs)\n  {\n    double omega_H = ui->omega_H->value();\n    double omega_P = ui->omega_P->value();\n    double min_edge_length = ui->min_edge_length->value();\n    double delta_area = ui->delta_area->value();\n    bool is_medially_centered = ui->is_medially_centered->isChecked();\n\n    mcs->set_quality_speed_tradeoff(omega_H);\n    mcs->set_medially_centered_speed_tradeoff(omega_P);\n    mcs->set_min_edge_length(min_edge_length);\n    mcs->set_area_variation_factor(delta_area);\n    mcs->set_is_medially_centered(is_medially_centered);\n  }\n\npublic Q_SLOTS:\n  void on_actionMCFSkeleton_triggered();\n  void on_actionConvert_to_medial_skeleton_triggered();\n  void on_actionContract();\n  void on_actionCollapse();\n  void on_actionSplit();\n  void on_actionDegeneracy();\n  void on_actionRun();\n  void on_actionSkeletonize();\n  void on_actionConverge();\n  void on_actionUpdateBBox();\n  void on_actionSegment();\n  void on_actionItemAboutToBeDestroyed(CGAL::Three::Scene_item*);\n\nprivate:\n  Mean_curvature_skeleton* mcs;\n  Polyhedron* meso_skeleton; // a copy of the meso_skeleton that is displayed\n  Polyhedron* input_triangle_mesh;\n  QDockWidget* dockWidget;\n  Ui::Mean_curvature_flow_skeleton_plugin* ui;\n\n  int fixedPointsItemIndex;\n  int nonFixedPointsItemIndex;\n  int poleLinesItemIndex;\n  int contractedItemIndex;\n  int InputMeshItemIndex;\n\n  Skeleton skeleton_curve;\n}; // end Polyhedron_demo_mean_curvature_flow_skeleton_plugin\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionMCFSkeleton_triggered()\n{\n  dockWidget->show();\n  dockWidget->raise();\n\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n\n  Scene_polyhedron_item* item =\n    qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n  if(item)\n  {\n    Polyhedron* pMesh = item->polyhedron();\n\n    if(!pMesh) return;\n\n    double diag = scene->len_diagonal();\n    init_ui(diag);\n\n    fixedPointsItemIndex = -1;\n    nonFixedPointsItemIndex = -1;\n    poleLinesItemIndex = -1;\n    contractedItemIndex = -1;\n    InputMeshItemIndex = -1;\n  }\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionUpdateBBox()\n{\n  double diag = scene->len_diagonal();\n  ui->min_edge_length->setValue(0.002 * diag);\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionSegment()\n{\n  if (num_vertices(skeleton_curve)==0 ) on_actionSkeletonize();\n  if (num_vertices(skeleton_curve)==0 ) return;\n\n  QTime time;\n  time.start();\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n    // init the polyhedron simplex indices\n  CGAL::set_halfedgeds_items_id(*input_triangle_mesh);\n\n  //for each input vertex compute its distance to the skeleton\n  std::vector<double> distances(num_vertices(*input_triangle_mesh));\n  BOOST_FOREACH(boost::graph_traits<Skeleton>::vertex_descriptor v, vertices(skeleton_curve) )\n  {\n    const Point& skel_pt = skeleton_curve[v].point;\n    BOOST_FOREACH(vertex_descriptor mesh_v, skeleton_curve[v].vertices)\n    {\n      const Point& mesh_pt = mesh_v->point();\n      distances[mesh_v->id()] = std::sqrt(CGAL::squared_distance(skel_pt, mesh_pt));\n    }\n  }\n\n  // create a property-map for sdf values\n  std::vector<double> sdf_values( num_faces(*input_triangle_mesh) );\n  Facet_with_id_pmap<double> sdf_property_map(sdf_values);\n\n  // compute sdf values with skeleton\n  BOOST_FOREACH(Polyhedron::Face_handle f, faces(*input_triangle_mesh))\n  {\n    double dist = 0;\n    BOOST_FOREACH(Polyhedron::Halfedge_handle hd, halfedges_around_face(halfedge(f, *input_triangle_mesh), *input_triangle_mesh))\n      dist+=distances[target(hd, *input_triangle_mesh)->id()];\n    sdf_property_map[f] = dist / 3.;\n  }\n\n  // post-process the sdf values\n  CGAL::sdf_values_postprocessing(*input_triangle_mesh, sdf_property_map);\n\n  // create a property-map for segment-ids (it is an adaptor for this case)\n  std::vector<std::size_t> segment_ids( num_faces(*input_triangle_mesh) );\n  Facet_with_id_pmap<std::size_t> segment_property_map(segment_ids);\n\n  // segment the mesh using default parameters\n  std::cout << \"Number of segments: \"\n            << CGAL::segmentation_from_sdf_values(*input_triangle_mesh, sdf_property_map, segment_property_map) <<\"\\n\";\n\n  Polyhedron* segmented_polyhedron = new Polyhedron(*input_triangle_mesh);\n\n  int i=0;\n  BOOST_FOREACH(Polyhedron::Face_handle fd, faces(*segmented_polyhedron))\n  {\n    fd->set_patch_id( static_cast<int>(segment_ids[i++] ));\n  }\n\n  scene->item(InputMeshItemIndex)->setVisible(false);\n  Scene_polyhedron_item* item_segmentation = new Scene_polyhedron_item(segmented_polyhedron);\n  item_segmentation->setItemIsMulticolor(true);\n  scene->addItem(item_segmentation);\n  item_segmentation->setName(QString(\"segmentation\"));\n\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionConvert_to_medial_skeleton_triggered()\n{\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n\n  Scene_polyhedron_item* item =\n    qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n  if(item)\n  {\n    Polyhedron* pMesh = item->polyhedron();\n\n    if ( !is_mesh_valid(pMesh) ) return;\n\n    QTime time;\n    time.start();\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n\n    Skeleton skeleton;\n    CGAL::extract_mean_curvature_flow_skeleton(*pMesh, skeleton);\n\n    std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n    //create the polylines representing the skeleton\n    Scene_polylines_item* skeleton_item = new Scene_polylines_item();\n    skeleton_item->setColor(QColor(175, 0, 255));\n\n    Polyline_visitor polyline_visitor(skeleton_item->polylines, skeleton);\n    CGAL::split_graph_into_polylines( skeleton,\n                                      polyline_visitor,\n                                      CGAL::internal::IsTerminalDefault() );\n\n    skeleton_item->setName(QString(\"Medial skeleton curve of %1\").arg(item->name()));\n    scene->addItem(skeleton_item);\n    skeleton_item->invalidateOpenGLBuffers();\n\n    item->setPointsMode();\n\n    QApplication::restoreOverrideCursor();\n  }\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionContract()\n{\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n  if (!check_item_index(index))\n  {\n    return;\n  }\n\n  Scene_polyhedron_item* item =\n    qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n  if (!check_mesh(item))\n  {\n    return;\n  }\n\n  QTime time;\n  time.start();\n  std::cout << \"Contract...\\n\";\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  update_parameters(mcs);\n  mcs->contract_geometry();\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  update_meso_skeleton();\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionCollapse()\n{\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n  if (!check_item_index(index))\n  {\n    return;\n  }\n\n  Scene_polyhedron_item* item =\n    qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n  if (!check_mesh(item))\n  {\n    return;\n  }\n\n  QTime time;\n  time.start();\n  std::cout << \"Collapse...\\n\";\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  update_parameters(mcs);\n  std::size_t num_collapses = mcs->collapse_edges();\n  std::cout << \"collapsed \" << num_collapses << \" edges.\\n\";\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  update_meso_skeleton();\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionSplit()\n{\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n  if (!check_item_index(index))\n  {\n    return;\n  }\n\n  Scene_polyhedron_item* item =\n    qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n  if (!check_mesh(item))\n  {\n    return;\n  }\n\n  QTime time;\n  time.start();\n  std::cout << \"Split...\\n\";\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  update_parameters(mcs);\n  std::size_t num_split = mcs->split_faces();\n  std::cout << \"split \" << num_split << \" triangles.\\n\";\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  update_meso_skeleton();\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionDegeneracy()\n{\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n  if (!check_item_index(index))\n  {\n    return;\n  }\n\n  Scene_polyhedron_item* item =\n    qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n  if (!check_mesh(item))\n  {\n    return;\n  }\n\n  QTime time;\n  time.start();\n  std::cout << \"Detect degeneracy...\\n\";\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  update_parameters(mcs);\n  mcs->detect_degeneracies();\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  Scene_points_with_normal_item* fixedPointsItem = new Scene_points_with_normal_item;\n  fixedPointsItem->setName(QString(\"fixed points of %1\").arg(item->name()));\n\n  std::vector<Point> fixedPoints;\n  mcs->fixed_points(fixedPoints);\n\n  Point_set *ps = fixedPointsItem->point_set();\n  for (size_t i = 0; i < fixedPoints.size(); ++i)\n  {\n    UI_point_3<Kernel> point(fixedPoints[i].x(), fixedPoints[i].y(), fixedPoints[i].z());\n    ps->push_back(point);\n  }\n  ps->select_all ();\n\n  if (fixedPointsItemIndex == -1)\n  {\n    fixedPointsItemIndex = scene->addItem(fixedPointsItem);\n  }\n  else\n  {\n    Scene_item* temp = scene->replaceItem(fixedPointsItemIndex, fixedPointsItem, false);\n    delete temp;\n  }\n  // update scene\n  update_meso_skeleton();\n  scene->item(fixedPointsItemIndex)->invalidateOpenGLBuffers();\n  scene->itemChanged(fixedPointsItemIndex);\n  scene->setSelectedItem(index);\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionRun()\n{\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n  if (!check_item_index(index))\n  {\n    return;\n  }\n\n  Scene_polyhedron_item* item =\n    qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n  if (!check_mesh(item))\n  {\n    return;\n  }\n\n  QTime time;\n  time.start();\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  std::cout << \"Run one iteration...\\n\";\n\n  update_parameters(mcs);\n  mcs->contract();\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  CGAL::Three::Scene_interface::Item_id contracted_item_index = scene->mainSelectionIndex();\n  Scene_polyhedron_item* contracted_item =\n    qobject_cast<Scene_polyhedron_item*>(scene->item(contracted_item_index));\n\n  // update scene\n  Scene_points_with_normal_item* fixedPointsItem = new Scene_points_with_normal_item;\n  fixedPointsItem->setName(QString(\"fixed points of %1\").arg(contracted_item->name()));\n\n  std::vector<Point> fixedPoints;\n  mcs->fixed_points(fixedPoints);\n\n  Point_set *ps = fixedPointsItem->point_set();\n  for (size_t i = 0; i < fixedPoints.size(); ++i)\n  {\n    UI_point_3<Kernel> point(fixedPoints[i].x(), fixedPoints[i].y(), fixedPoints[i].z());\n    ps->push_back(point);\n  }\n  ps->select_all();\n  \n  if (fixedPointsItemIndex == -1)\n  {\n    fixedPointsItemIndex = scene->addItem(fixedPointsItem);\n  }\n  else\n  {\n    Scene_item* temp = scene->replaceItem(fixedPointsItemIndex, fixedPointsItem, false);\n    delete temp;\n  }\n\n//#define DRAW_NON_FIXED_POINTS\n#ifdef DRAW_NON_FIXED_POINTS\n  // draw non-fixed points\n  Scene_points_with_normal_item* nonFixedPointsItem = new Scene_points_with_normal_item;\n  nonFixedPointsItem->setName(\"non-fixed points\");\n  nonFixedPointsItem->setColor(QColor(0, 255, 0));\n  std::vector<Point> nonFixedPoints;\n  mcs->non_fixed_points(nonFixedPoints);\n  ps = nonFixedPointsItem->point_set();\n  for (size_t i = 0; i < nonFixedPoints.size(); ++i)\n  {\n    UI_point_3<Kernel> point(nonFixedPoints[i].x(), nonFixedPoints[i].y(), nonFixedPoints[i].z());\n    ps->push_back(point);\n  }\n  if (nonFixedPointsItemIndex == -1)\n  {\n    nonFixedPointsItemIndex = scene->addItem(nonFixedPointsItem);\n  }\n  else\n  {\n    scene->replaceItem(nonFixedPointsItemIndex, nonFixedPointsItem, false);\n  }\n  scene->itemChanged(nonFixedPointsItemIndex);\n#endif\n\n//#define DRAW_POLE_LINE\n#ifdef DRAW_POLE_LINE\n  // draw lines connecting surface points and their correspondent poles\n  Scene_polylines_item* poleLinesItem = new Scene_polylines_item();\n\n  Polyhedron* pMesh = item->polyhedron();\n  std::vector<Point> pole_points;\n  mcs->poles(pole_points);\n  vertex_iterator vb, ve;\n  int id = 0;\n  for (boost::tie(vb, ve) = vertices(*pMesh); vb != ve; ++vb)\n  {\n    std::vector<Point> line;\n    line.clear();\n\n    vertex_descriptor v = *vb;\n    Point s = v->point();\n    Point t = pole_points[id++];\n\n    line.push_back(s);\n    line.push_back(t);\n    poleLinesItem->polylines.push_back(line);\n  }\n\n  if (poleLinesItemIndex == -1)\n  {\n    poleLinesItemIndex = scene->addItem(poleLinesItem);\n  }\n  else\n  {\n    scene->replaceItem(poleLinesItemIndex, poleLinesItem, false);\n  }\n#endif\n\n  update_meso_skeleton();\n  scene->setSelectedItem(index);\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionSkeletonize()\n{\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n  if (!check_item_index(index))\n  {\n    return;\n  }\n\n  Scene_polyhedron_item* item =\n    qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n  if (!check_mesh(item))\n  {\n    return;\n  }\n\n  QTime time;\n  time.start();\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  update_parameters(mcs);\n\n  mcs->convert_to_skeleton(skeleton_curve);\n\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  //create the polylines representing the skeleton\n  Scene_polylines_item* skeleton = new Scene_polylines_item();\n  skeleton->setColor(QColor(175, 0, 255));\n\n  Polyline_visitor polyline_visitor(skeleton->polylines, skeleton_curve);\n  CGAL::split_graph_into_polylines( skeleton_curve,\n                                    polyline_visitor,\n                                    CGAL::internal::IsTerminalDefault() );\n\n  skeleton->setName(QString(\"skeleton curve of %1\").arg(item->name()));\n  scene->addItem(skeleton);\n  skeleton->invalidateOpenGLBuffers();\n\n  // set the fixed points and contracted mesh as invisible\n  if (fixedPointsItemIndex >= 0)\n  {\n    scene->item(fixedPointsItemIndex)->setVisible(false);\n    scene->itemChanged(fixedPointsItemIndex);\n  }\n  scene->item(contractedItemIndex)->setVisible(false);\n  scene->itemChanged(contractedItemIndex);\n  // display the original mesh in transparent mode\n  item->setVisible(false);\n  if (InputMeshItemIndex >= 0)\n  {\n    scene->item(InputMeshItemIndex)->setVisible(true);\n    scene->item(InputMeshItemIndex)->setPointsMode();\n    scene->itemChanged(InputMeshItemIndex);\n  }\n\n  // update scene\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionConverge()\n{\n  const CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n  if (!check_item_index(index))\n  {\n    return;\n  }\n\n  Scene_polyhedron_item* item =\n    qobject_cast<Scene_polyhedron_item*>(scene->item(index));\n\n  if (!check_mesh(item))\n  {\n    return;\n  }\n\n  QTime time;\n  time.start();\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  mcs->contract_until_convergence();\n\n  std::cout << \"ok (\" << time.elapsed() << \" ms, \" << \")\" << std::endl;\n\n  // update scene\n  Scene_points_with_normal_item* fixedPointsItem = new Scene_points_with_normal_item;\n  fixedPointsItem->setName(QString(\"fixed points of %1\").arg(item->name()));\n\n  std::vector<Point> fixedPoints;\n  mcs->fixed_points(fixedPoints);\n\n  Point_set *ps = fixedPointsItem->point_set();\n  for (size_t i = 0; i < fixedPoints.size(); ++i)\n  {\n    UI_point_3<Kernel> point(fixedPoints[i].x(), fixedPoints[i].y(), fixedPoints[i].z());\n    ps->push_back(point);\n  }\n  ps->select_all();\n  \n  if (fixedPointsItemIndex == -1)\n  {\n    fixedPointsItemIndex = scene->addItem(fixedPointsItem);\n  }\n  else\n  {\n    Scene_item* temp = scene->replaceItem(fixedPointsItemIndex, fixedPointsItem, false);\n    delete temp;\n  }\n\n  scene->item(fixedPointsItemIndex)->invalidateOpenGLBuffers();\n  scene->itemChanged(fixedPointsItemIndex);\n  update_meso_skeleton();\n  scene->setSelectedItem(index);\n\n  QApplication::restoreOverrideCursor();\n}\n\nvoid Polyhedron_demo_mean_curvature_flow_skeleton_plugin::on_actionItemAboutToBeDestroyed(CGAL::Three::Scene_item* /* item */)\n{\n  if (mcs != NULL)\n  {\n    delete mcs;\n    mcs = NULL;\n  }\n}\n\n#include \"Mean_curvature_flow_skeleton_plugin.moc\"\n", "meta": {"hexsha": "57a7667b00cad25c276db24d202279b7dfac17f3", "size": 28340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/PMP/Mean_curvature_flow_skeleton_plugin.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/PMP/Mean_curvature_flow_skeleton_plugin.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Polyhedron/demo/Polyhedron/Plugins/PMP/Mean_curvature_flow_skeleton_plugin.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7709011944, "max_line_length": 129, "alphanum_fraction": 0.711644319, "num_tokens": 7136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.4355346692927909}}
{"text": "// -----------------------------------------------------------------------------\n// Copyright (c) 2022 Mohamed Aladem\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this softwareand associated documentation files(the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and /or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions :\n//\n// The above copyright noticeand this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n// -----------------------------------------------------------------------------\n\n#include \"micro_graph_optimizer.h\"\n\n#include <math.h>\n#include <map>\n#include <Eigen/Sparse>\n\nnamespace mgo\n{\n  namespace\n  {\n    struct VariableInfo\n    {\n    public:\n      inline VariableInfo& set_dim(int val) { m_dim = val; return *this; }\n      inline VariableInfo& set_idx(int val) { m_idx = val; return *this; }\n      inline int dim()const { return m_dim; }\n      inline int idx()const { return m_idx; }\n\n    private:\n      int m_dim;\n      int m_idx; // The index of this variable in the H matrix.\n    };\n\n    struct ScratchPad\n    {\n      int total_variables_dim = 0;\n      int total_factors_dim = 0;\n      std::map<Variable*, VariableInfo> variable_lookup_table;\n      inline const VariableInfo& variable_lookup(Variable* var) { MGO_ASSERT(variable_lookup_table.count(var) != 0); return variable_lookup_table[var]; }\n      typedef Eigen::Triplet<double> T;\n      std::vector<T> tripletList;\n      Eigen::SparseMatrix<double> H;\n      Eigen::VectorXd b;\n    };\n\n    // ===================================================================\n    void compute_graph_info(const FactorGraph& graph, ScratchPad* pad)\n    {\n      const std::vector<Variable*>& variables = graph.get_variables();\n      int total_variables_dim = 0;\n      std::map<Variable*, VariableInfo> variable_lookup_table;\n      for (int i = 0, var_idx = 0, count = variables.size(); i < count; ++i)\n      {\n        Variable* var = variables[i];\n        if (!var->fixed)\n        {\n          const int v_dim = var->dim();\n          total_variables_dim += v_dim;\n          variable_lookup_table[var] = VariableInfo().set_dim(v_dim).set_idx(var_idx);\n          var_idx += v_dim;\n        }\n      }\n      pad->total_variables_dim = total_variables_dim;\n      pad->variable_lookup_table.swap(variable_lookup_table);\n\n      const std::vector<Factor*>& factors = graph.get_factors();\n      int total_factors_dim = 0;\n      for (int i = 0, count = factors.size(); i < count; ++i)\n      {\n        const int f_dim = factors[i]->dim();\n        total_factors_dim += f_dim;\n      }\n      pad->total_factors_dim = total_factors_dim;\n\n      pad->H = Eigen::SparseMatrix<double>(total_variables_dim, total_variables_dim);\n      pad->b = Eigen::VectorXd::Zero(total_variables_dim);\n    }\n\n    // ===================================================================\n    double compute_error_norm_squared(const FactorGraph& graph)\n    {\n      const std::vector<Factor*>& factors = graph.get_factors();\n      double error = 0.0;\n      for (size_t i = 0, count = factors.size(); i < count; ++i)\n      {\n        error += factors[i]->error().squaredNorm();\n      }\n      return error;\n    }\n\n    // ===================================================================\n    void linearize_single_factor(Factor* factor, ScratchPad* pad)\n    {\n      // Our goal in this function is to add the contribution of a factor\n      // to the linearized system (H, b).\n\n      // First we need to calculate the jacobian of the factor wrt each of\n      // its variables then stack them horizontally in Js then compute Jt*J matrix.\n      const int n_rows = factor->dim();\n      const int num_variables = factor->num_variables();\n      std::vector<int> vars_cols(num_variables, -1);\n      std::vector<int> vars_dim(num_variables, -1);\n      int n_cols = 0;\n      for (int i = 0; i < num_variables; ++i)\n      {\n        Variable* var = factor->variable_at(i);\n        if (!var->fixed)\n        {\n          const int var_dim = pad->variable_lookup(var).dim();\n          vars_cols[i] = n_cols;\n          vars_dim[i] = var_dim;\n          n_cols += var_dim;\n        }\n      }\n\n      if (n_cols == 0)\n      {\n        MGO_LOG(\"All variables connected to this factor are fixed.\");\n        return;\n      }\n\n      Eigen::MatrixXd Js(n_rows, n_cols);\n      for (int i = 0, start_col = 0; i < num_variables; ++i)\n      {\n        if (!factor->variable_at(i)->fixed)\n        {\n          Eigen::MatrixXd J = factor->jacobian(i);\n          Js.block(0, start_col, J.rows(), J.cols()) = J;\n          start_col += J.cols();\n        }\n      }\n\n      Eigen::MatrixXd JtJ(Js.cols(), Js.cols());\n      JtJ.noalias() = Js.transpose() * Js;\n\n      // Now we need to add the contribution to H. Note that we are only filling the lower triangular part.\n      for (int i = 0; i < num_variables; ++i)\n      {\n        if (factor->variable_at(i)->fixed)\n        {\n          continue;\n        }\n        const int H_col = pad->variable_lookup(factor->variable_at(i)).idx();\n        const int JtJ_col = vars_cols[i];\n        for (int j = i; j < num_variables; ++j)\n        {\n          if (factor->variable_at(j)->fixed)\n          {\n            continue;\n          }\n          const int H_row = pad->variable_lookup(factor->variable_at(j)).idx();\n          const int JtJ_row = vars_cols[j];\n          for (int JtJ_i = JtJ_col, H_i = H_col; JtJ_i < (JtJ_col + vars_dim[i]); ++JtJ_i, ++H_i)\n          {\n            for (int JtJ_j = JtJ_row, H_j = H_row; JtJ_j < (JtJ_row + vars_dim[j]); ++JtJ_j, ++H_j)\n            {\n              pad->tripletList.push_back(ScratchPad::T(H_j, H_i, JtJ(JtJ_j, JtJ_i)));\n            }\n          }\n        }\n      }\n\n      // Handle the vector b.\n      const Eigen::VectorXd Jtb = Js.transpose() * factor->error();\n      for (int i = 0; i < num_variables; ++i)\n      {\n        Variable* var = factor->variable_at(i);\n        if (!var->fixed)\n        {\n          const int var_idx = pad->variable_lookup(var).idx();\n          const int var_dim = vars_dim[i];\n          pad->b.segment(var_idx, var_dim) -= Jtb.segment(vars_cols[i], var_dim);\n        }\n      }\n    }\n\n    // ===================================================================\n    bool iterate(FactorGraph* graph, ScratchPad* pad)\n    {\n      const std::vector<Factor*>& factors = graph->get_factors();\n      pad->b.setZero();\n      pad->tripletList.clear();\n      for (size_t i = 0, count = factors.size(); i < count; ++i)\n      {\n        linearize_single_factor(factors[i], pad);\n      }\n      MGO_ASSERT(!pad->tripletList.empty());\n      pad->H.setFromTriplets(pad->tripletList.begin(), pad->tripletList.end());\n\n      Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> chol(pad->H);\n      Eigen::VectorXd dx = chol.solve(pad->b);\n      if (chol.info() == Eigen::Success)\n      {\n        std::vector<Variable*>& variables = graph->get_variables();\n        for (int i = 0, d = 0, count = variables.size(); i < count; ++i)\n        {\n          Variable* var = variables[i];\n          if (!var->fixed)\n          {\n            const int vd = pad->variable_lookup_table[var].dim();\n            var->plus(dx.segment(d, vd));\n            d += vd;\n          }\n        }\n        return true;\n      }\n      else\n      {\n        MGO_LOG(\"Linear solver failed.\");\n        return false;\n      }\n    }\n\n    // ===================================================================\n    bool continue_iterating_check(int iter_num, double current_error, double new_error, const OptimizationParameters& params, bool* converged)\n    {\n      if (!std::isfinite(new_error))\n      {\n        return false;\n      }\n\n      if (iter_num == params.max_iterations)\n      {\n        MGO_LOG(\"Max iterations reached.\");\n        return false;\n      }\n\n      const double error_decrease = current_error - new_error;\n      if ((error_decrease <= params.absolute_error_th) ||\n        ((error_decrease / current_error) <= params.relative_error_th))\n      {\n        MGO_LOG(\"Converged.\");\n        *converged = true;\n        return false;\n      }\n\n      return true;\n    }\n\n    // ===================================================================\n  } // anonymous namespace\n\n  bool optimize_gn(FactorGraph* graph, const OptimizationParameters& params)\n  {\n    MGO_LOG(\"Started optimization with %i factors and %i variables.\", (int)graph->get_factors().size(), (int)graph->get_variables().size());\n    ScratchPad pad;\n    compute_graph_info(*graph, &pad);\n    double current_error = 0.5 * compute_error_norm_squared(*graph);\n    MGO_LOG(\"Initial error: %f\", current_error);\n    double new_error = current_error;\n    int iter_num = 0;\n    bool converged = false;\n    bool continue_iterating = true;\n    while (continue_iterating)\n    {\n      current_error = new_error;\n      if (!iterate(graph, &pad))\n      {\n        return false;\n      }\n      ++iter_num;\n      new_error = 0.5 * compute_error_norm_squared(*graph);\n      MGO_LOG(\"New error after iteration %i: %f\", iter_num, new_error);\n      continue_iterating = continue_iterating_check(iter_num, current_error, new_error, params, &converged);\n    }\n    return converged;\n  }\n\n  // ===================================================================\n  Eigen::MatrixXd Factor::jacobian(int idx)const\n  {\n    MGO_ASSERT(m_num_variables > 0 && idx < m_num_variables);\n    return compute_numerical_jacobian(m_variables[idx]);\n  }\n\n  // ===================================================================\n  Eigen::MatrixXd Factor::compute_numerical_jacobian(Variable* v)const\n  {\n    constexpr double h = 1e-5;\n    const int N = v->dim();\n    const int M = this->dim();\n    Eigen::MatrixXd J = Eigen::MatrixXd::Zero(M, N);\n    Eigen::VectorXd dx = Eigen::VectorXd::Zero(N);\n    Eigen::VectorXd dy0 = this->error();\n    constexpr double k = 1.0 / (2.0 * h);\n    for (int i = 0; i < N; ++i)\n    {\n      dx(i) = h;\n      v->plus(dx); // right\n      const Eigen::VectorXd dy1 = this->subtract_error(this->error(), dy0);\n      dx(i) = -2.0 * h;\n      v->plus(dx); // left\n      const Eigen::VectorXd dy2 = this->subtract_error(this->error(), dy0);\n      dx(i) = h;\n      v->plus(dx); // return to original state.\n      dx(i) = 0.0;\n      J.col(i) << (dy1 - dy2) * k;\n    }\n    return J;\n  }\n\n  // ===================================================================\n  FactorGraph::FactorGraph() = default;\n\n  FactorGraph::~FactorGraph()\n  {\n    for (Factor* f : m_factors)\n    {\n      delete f;\n    }\n    for (Variable* v : m_variables)\n    {\n      delete v;\n    }\n  }\n}\n", "meta": {"hexsha": "5c14b09d2617e134de59b8c185119a360dd35c39", "size": 11229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "micro_graph_optimizer.cpp", "max_stars_repo_name": "alademm/micro-graph-optimizer", "max_stars_repo_head_hexsha": "b5e2ea5676a52b66dc03fbcd30828b4e573805a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-14T16:06:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T16:06:28.000Z", "max_issues_repo_path": "micro_graph_optimizer.cpp", "max_issues_repo_name": "alademm/micro-graph-optimizer", "max_issues_repo_head_hexsha": "b5e2ea5676a52b66dc03fbcd30828b4e573805a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "micro_graph_optimizer.cpp", "max_forks_repo_name": "alademm/micro-graph-optimizer", "max_forks_repo_head_hexsha": "b5e2ea5676a52b66dc03fbcd30828b4e573805a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1306990881, "max_line_length": 153, "alphanum_fraction": 0.5576631935, "num_tokens": 2683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.435491091601807}}
{"text": "/*\n * Update.hpp\n *\n *  Created on: Feb 9, 2014\n *      Author: Bloeschm\n */\n\n#ifndef LWF_UPDATEMODEL_HPP_\n#define LWF_UPDATEMODEL_HPP_\n\n#include \"lightweight_filtering/common.hpp\"\n#include \"lightweight_filtering/ModelBase.hpp\"\n#include \"lightweight_filtering/PropertyHandler.hpp\"\n#include \"lightweight_filtering/SigmaPoints.hpp\"\n#include \"lightweight_filtering/OutlierDetection.hpp\"\n#include <Eigen/StdVector>\n\nnamespace LWF{\n\ntemplate<typename Innovation, typename FilterState, typename Meas, typename Noise, typename OutlierDetection = OutlierDetectionDefault, bool isCoupled = false>\nclass Update: public ModelBase<Update<Innovation,FilterState,Meas,Noise,OutlierDetection,isCoupled>,Innovation,typename FilterState::mtState,Noise>, public PropertyHandler{\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  static_assert(!isCoupled || Noise::D_ == FilterState::noiseExtensionDim_,\"Noise Size for coupled Update must match noise extension of prediction!\");\n  typedef ModelBase<Update<Innovation,FilterState,Meas,Noise,OutlierDetection,isCoupled>,Innovation,typename FilterState::mtState,Noise> mtModelBase;\n  typedef FilterState mtFilterState;\n  typedef typename mtFilterState::mtState mtState;\n  typedef typename mtModelBase::mtInputTuple mtInputTuple;\n  typedef typename mtFilterState::mtPredictionMeas mtPredictionMeas;\n  typedef typename mtFilterState::mtPredictionNoise mtPredictionNoise;\n  typedef Innovation mtInnovation;\n  typedef Meas mtMeas;\n  typedef Noise mtNoise;\n  typedef OutlierDetection mtOutlierDetection;\n  mtMeas meas_; // TODO change to pointer, or remove\n  static const bool coupledToPrediction_ = isCoupled;\n  bool useSpecialLinearizationPoint_;\n  bool useImprovedJacobian_;\n  bool hasConverged_;\n  bool successfulUpdate_;\n  mutable bool cancelIteration_;\n  mutable int candidateCounter_;\n  mutable Eigen::MatrixXd H_;\n  Eigen::MatrixXd Hlin_;\n  Eigen::MatrixXd boxMinusJac_;\n  Eigen::MatrixXd Hn_;\n  Eigen::MatrixXd updnoiP_;\n  Eigen::MatrixXd noiP_;\n  Eigen::MatrixXd preupdnoiP_;\n  Eigen::MatrixXd C_;\n  mtInnovation y_;\n  mutable Eigen::MatrixXd Py_;\n  Eigen::MatrixXd Pyinv_;\n  typename mtInnovation::mtDifVec innVector_;\n  mtInnovation yIdentity_;\n  typename mtState::mtDifVec updateVec_;\n  mtState linState_;\n  double updateVecNorm_;\n  Eigen::MatrixXd K_;\n  Eigen::MatrixXd Pyx_;\n  mutable typename mtState::mtDifVec difVecLinInv_;\n\n  SigmaPoints<mtState,2*mtState::D_+1,2*(mtState::D_+mtNoise::D_)+1,0> stateSigmaPoints_;\n  SigmaPoints<mtNoise,2*mtNoise::D_+1,2*(mtState::D_+mtNoise::D_)+1,2*mtState::D_> stateSigmaPointsNoi_;\n  SigmaPoints<mtInnovation,2*(mtState::D_+mtNoise::D_)+1,2*(mtState::D_+mtNoise::D_)+1,0> innSigmaPoints_;\n  SigmaPoints<mtNoise,2*(mtNoise::D_+mtPredictionNoise::D_)+1,2*(mtState::D_+mtNoise::D_+mtPredictionNoise::D_)+1,2*(mtState::D_)> coupledStateSigmaPointsNoi_;\n  SigmaPoints<mtInnovation,2*(mtState::D_+mtNoise::D_+mtPredictionNoise::D_)+1,2*(mtState::D_+mtNoise::D_+mtPredictionNoise::D_)+1,0> coupledInnSigmaPoints_;\n  SigmaPoints<LWF::VectorElement<mtState::D_>,2*mtState::D_+1,2*mtState::D_+1,0> updateVecSP_;\n  SigmaPoints<mtState,2*mtState::D_+1,2*mtState::D_+1,0> posterior_;\n  double alpha_;\n  double beta_;\n  double kappa_;\n  double updateVecNormTermination_;\n  int maxNumIteration_;\n  int iterationNum_;\n  mtOutlierDetection outlierDetection_;\n  unsigned int numSequences;\n  bool disablePreAndPostProcessingWarning_;\n  Update(): H_((int)(mtInnovation::D_),(int)(mtState::D_)),\n      Hlin_((int)(mtInnovation::D_),(int)(mtState::D_)),\n      boxMinusJac_((int)(mtState::D_),(int)(mtState::D_)),\n      Hn_((int)(mtInnovation::D_),(int)(mtNoise::D_)),\n      updnoiP_((int)(mtNoise::D_),(int)(mtNoise::D_)),\n      noiP_((int)(mtNoise::D_),(int)(mtNoise::D_)),\n      preupdnoiP_((int)(mtPredictionNoise::D_),(int)(mtNoise::D_)),\n      C_((int)(mtState::D_),(int)(mtInnovation::D_)),\n      Py_((int)(mtInnovation::D_),(int)(mtInnovation::D_)),\n      Pyinv_((int)(mtInnovation::D_),(int)(mtInnovation::D_)),\n      K_((int)(mtState::D_),(int)(mtInnovation::D_)),\n      Pyx_((int)(mtInnovation::D_),(int)(mtState::D_)){\n    alpha_ = 1e-3;\n    beta_ = 2.0;\n    kappa_ = 0.0;\n    updateVecNormTermination_ = 1e-6;\n    maxNumIteration_  = 10;\n    updnoiP_.setIdentity();\n    updnoiP_ *= 0.0001;\n    noiP_.setZero();\n    preupdnoiP_.setZero();\n    useSpecialLinearizationPoint_ = false;\n    useImprovedJacobian_ = false;\n    yIdentity_.setIdentity();\n    updateVec_.setIdentity();\n    refreshNoiseSigmaPoints();\n    // refreshUKFParameter();\n    mtNoise n;\n    n.setIdentity();\n    n.registerCovarianceToPropertyHandler_(updnoiP_,this,\"UpdateNoise.\");\n    doubleRegister_.registerScalar(\"alpha\",alpha_);\n    doubleRegister_.registerScalar(\"beta\",beta_);\n    doubleRegister_.registerScalar(\"kappa\",kappa_);\n    doubleRegister_.registerScalar(\"updateVecNormTermination\",updateVecNormTermination_);\n    intRegister_.registerScalar(\"maxNumIteration\",maxNumIteration_);\n    outlierDetection_.setEnabledAll(false);\n    numSequences = 1;\n    disablePreAndPostProcessingWarning_ = false;\n  };\n  virtual ~Update(){};\n  void refreshNoiseSigmaPoints(){\n    if(noiP_ != updnoiP_){\n      noiP_ = updnoiP_;\n      stateSigmaPointsNoi_.computeFromZeroMeanGaussian(noiP_);\n    }\n  }\n  void refreshUKFParameter(){\n    stateSigmaPoints_.computeParameter(alpha_,beta_,kappa_);\n    innSigmaPoints_.computeParameter(alpha_,beta_,kappa_);\n    coupledInnSigmaPoints_.computeParameter(alpha_,beta_,kappa_);\n    updateVecSP_.computeParameter(alpha_,beta_,kappa_);\n    posterior_.computeParameter(alpha_,beta_,kappa_);\n    stateSigmaPointsNoi_.computeParameter(alpha_,beta_,kappa_);\n    stateSigmaPointsNoi_.computeFromZeroMeanGaussian(noiP_);\n    coupledStateSigmaPointsNoi_.computeParameter(alpha_,beta_,kappa_);\n  }\n  void refreshProperties(){\n    refreshPropertiesCustom();\n    // refreshUKFParameter();\n  }\n  virtual void refreshPropertiesCustom(){}\n  void eval_(mtInnovation& x, const mtInputTuple& inputs, double dt) const{\n    evalInnovation(x,std::get<0>(inputs),std::get<1>(inputs));\n  }\n  template<int i,typename std::enable_if<i==0>::type* = nullptr>\n  void jacInput_(Eigen::MatrixXd& F, const mtInputTuple& inputs, double dt) const{\n    jacState(F,std::get<0>(inputs));\n  }\n  template<int i,typename std::enable_if<i==1>::type* = nullptr>\n  void jacInput_(Eigen::MatrixXd& F, const mtInputTuple& inputs, double dt) const{\n    jacNoise(F,std::get<0>(inputs));\n  }\n  virtual void evalInnovation(mtInnovation& y, const mtState& state, const mtNoise& noise) const = 0;\n  virtual void evalInnovationShort(mtInnovation& y, const mtState& state) const{\n    mtNoise n; // TODO get static for Identity()\n    n.setIdentity();\n    evalInnovation(y,state,n);\n  }\n  virtual void jacState(Eigen::MatrixXd& F, const mtState& state) const = 0;\n  virtual void jacNoise(Eigen::MatrixXd& F, const mtState& state) const = 0;\n  virtual void preProcess(mtFilterState& filterState, const mtMeas& meas, bool& isFinished){\n    isFinished = false;\n    if(!disablePreAndPostProcessingWarning_){\n      std::cout << \"Warning: update preProcessing is not implemented!\" << std::endl;\n    }\n  }\n  virtual bool extraOutlierCheck(const mtState& state) const{\n    return hasConverged_;\n  }\n  virtual bool generateCandidates(const mtFilterState& filterState, mtState& candidate) const{\n    candidate = filterState.state_;\n    candidateCounter_++;\n    if(candidateCounter_<=1)\n      return true;\n    else\n      return false;\n  }\n  virtual void postProcess(mtFilterState& filterState, const mtMeas& meas, const mtOutlierDetection& outlierDetection, bool& isFinished){\n    isFinished = true;\n    if(!disablePreAndPostProcessingWarning_){\n      std::cout << \"Warning: update postProcessing is not implemented!\" << std::endl;\n    }\n  }\n  int performUpdate(mtFilterState& filterState, const mtMeas& meas){\n    bool isFinished = true;\n    int r = 0;\n    do {\n      preProcess(filterState,meas,isFinished);\n      if(!isFinished){\n        switch(filterState.mode_){\n          case ModeEKF:\n            r = performUpdateEKF(filterState,meas);\n            break;\n          case ModeUKF:\n            r = performUpdateUKF(filterState,meas);\n            break;\n          case ModeIEKF:\n            r = performUpdateIEKF(filterState,meas);\n            break;\n          default:\n            r = performUpdateEKF(filterState,meas);\n            break;\n        }\n      }\n      postProcess(filterState,meas,outlierDetection_,isFinished);\n      filterState.state_.fix();\n      enforceSymmetry(filterState.cov_);\n    } while (!isFinished);\n    return r;\n  }\n  int performUpdateEKF(mtFilterState& filterState, const mtMeas& meas){\n    meas_ = meas;\n    if(!useSpecialLinearizationPoint_){\n      this->jacState(H_,filterState.state_);\n      Hlin_ = H_;\n      this->jacNoise(Hn_,filterState.state_);\n      this->evalInnovationShort(y_,filterState.state_);\n    } else {\n      filterState.state_.boxPlus(filterState.difVecLin_,linState_);\n      this->jacState(H_,linState_);\n      if(useImprovedJacobian_){\n        filterState.state_.boxMinusJac(linState_,boxMinusJac_);\n        Hlin_ = H_*boxMinusJac_;\n      } else {\n        Hlin_ = H_;\n      }\n      this->jacNoise(Hn_,linState_);\n      this->evalInnovationShort(y_,linState_);\n    }\n\n    if(isCoupled){\n      C_ = filterState.G_*preupdnoiP_*Hn_.transpose();\n      Py_ = Hlin_*filterState.cov_*Hlin_.transpose() + Hn_*updnoiP_*Hn_.transpose() + Hlin_*C_ + C_.transpose()*Hlin_.transpose();\n    } else {\n      Py_ = Hlin_*filterState.cov_*Hlin_.transpose() + Hn_*updnoiP_*Hn_.transpose();\n    }\n    y_.boxMinus(yIdentity_,innVector_);\n\n    // Outlier detection // TODO: adapt for special linearization point\n    outlierDetection_.doOutlierDetection(innVector_,Py_,Hlin_);\n    Pyinv_.setIdentity();\n    Py_.llt().solveInPlace(Pyinv_);\n\n    // Kalman Update\n    if(isCoupled){\n      K_ = (filterState.cov_*Hlin_.transpose()+C_)*Pyinv_;\n    } else {\n      K_ = filterState.cov_*Hlin_.transpose()*Pyinv_;\n    }\n    filterState.cov_ = filterState.cov_ - K_*Py_*K_.transpose();\n    if(!useSpecialLinearizationPoint_){\n      updateVec_ = -K_*innVector_;\n    } else {\n      filterState.state_.boxMinus(linState_,difVecLinInv_);\n      updateVec_ = -K_*(innVector_+H_*difVecLinInv_); // includes correction for offseted linearization point, dif must be recomputed (a-b != (-(b-a)))\n    }\n    filterState.state_.boxPlus(updateVec_,filterState.state_);\n    return 0;\n  }\n  int performUpdateIEKF(mtFilterState& filterState, const mtMeas& meas){\n    meas_ = meas;\n    successfulUpdate_ = false;\n    candidateCounter_ = 0;\n\n    std::vector<double> scores;\n    std::vector<mtState, Eigen::aligned_allocator<mtState>> states;\n    double bestScore = -1.0;\n    mtState bestState;\n    MXD bestCov;\n\n    while(generateCandidates(filterState,linState_)){\n      cancelIteration_ = false;\n      hasConverged_ = false;\n      for(iterationNum_=0;iterationNum_<maxNumIteration_ && !hasConverged_ && !cancelIteration_;iterationNum_++){\n        this->jacState(H_,linState_);\n        this->jacNoise(Hn_,linState_);\n        this->evalInnovationShort(y_,linState_);\n\n        if(isCoupled){\n          C_ = filterState.G_*preupdnoiP_*Hn_.transpose();\n          Py_ = H_*filterState.cov_*H_.transpose() + Hn_*updnoiP_*Hn_.transpose() + H_*C_ + C_.transpose()*H_.transpose();\n        } else {\n          Py_ = H_*filterState.cov_*H_.transpose() + Hn_*updnoiP_*Hn_.transpose();\n        }\n        y_.boxMinus(yIdentity_,innVector_);\n\n        // Outlier detection\n        outlierDetection_.doOutlierDetection(innVector_,Py_,H_);\n        Pyinv_.setIdentity();\n        Py_.llt().solveInPlace(Pyinv_);\n\n        // Kalman Update\n        if(isCoupled){\n          K_ = (filterState.cov_*H_.transpose()+C_)*Pyinv_;\n        } else {\n          K_ = filterState.cov_*H_.transpose()*Pyinv_;\n        }\n        filterState.state_.boxMinus(linState_,difVecLinInv_);\n        updateVec_ = -K_*(innVector_+H_*difVecLinInv_)+difVecLinInv_; // includes correction for offseted linearization point, dif must be recomputed (a-b != (-(b-a)))\n        linState_.boxPlus(updateVec_,linState_);\n        updateVecNorm_ = updateVec_.norm();\n        hasConverged_ = updateVecNorm_<=updateVecNormTermination_;\n      }\n      if(extraOutlierCheck(linState_)){\n        successfulUpdate_ = true;\n        double score = (innVector_.transpose()*Pyinv_*innVector_)(0);\n        scores.push_back(score);\n        states.push_back(linState_);\n        if(bestScore == -1.0 || score < bestScore){\n          bestScore = score;\n          bestState = linState_;\n          bestCov = filterState.cov_ - K_*Py_*K_.transpose();\n        }\n      }\n    }\n\n    if(successfulUpdate_){\n      if(scores.size() == 1){\n        filterState.state_ = bestState;\n        filterState.cov_ = bestCov;\n      } else {\n        bool foundOtherMin = false;\n        for(auto it = states.begin();it!=states.end();it++){\n          bestState.boxMinus(*it,difVecLinInv_);\n          if(difVecLinInv_.norm()>2*updateVecNormTermination_){\n            foundOtherMin = true;\n            break;\n          }\n        }\n        if(!foundOtherMin){\n          filterState.state_ = bestState;\n          filterState.cov_ = bestCov;\n        } else {\n          successfulUpdate_ = false;\n        }\n      }\n    }\n    return 0;\n  }\n  int performUpdateUKF(mtFilterState& filterState, const mtMeas& meas){\n    meas_ = meas;\n    handleUpdateSigmaPoints<isCoupled>(filterState);\n    y_.boxMinus(yIdentity_,innVector_);\n\n    outlierDetection_.doOutlierDetection(innVector_,Py_,Pyx_);\n    Pyinv_.setIdentity();\n    Py_.llt().solveInPlace(Pyinv_);\n\n    // Kalman Update\n    K_ = Pyx_.transpose()*Pyinv_;\n    filterState.cov_ = filterState.cov_ - K_*Py_*K_.transpose();\n    updateVec_ = -K_*innVector_;\n\n    // Adapt for proper linearization point\n    updateVecSP_.computeFromZeroMeanGaussian(filterState.cov_);\n    for(unsigned int i=0;i<2*mtState::D_+1;i++){\n      filterState.state_.boxPlus(updateVec_+updateVecSP_(i).v_,posterior_(i));\n    }\n    posterior_.getMean(filterState.state_);\n    posterior_.getCovarianceMatrix(filterState.state_,filterState.cov_);\n    return 0;\n  }\n  template<bool IC = isCoupled, typename std::enable_if<(IC)>::type* = nullptr>\n  void handleUpdateSigmaPoints(mtFilterState& filterState){\n    coupledStateSigmaPointsNoi_.extendZeroMeanGaussian(filterState.stateSigmaPointsNoi_,updnoiP_,preupdnoiP_);\n    for(unsigned int i=0;i<coupledInnSigmaPoints_.L_;i++){\n      this->evalInnovation(coupledInnSigmaPoints_(i),filterState.stateSigmaPointsPre_(i),coupledStateSigmaPointsNoi_(i));\n    }\n    coupledInnSigmaPoints_.getMean(y_);\n    coupledInnSigmaPoints_.getCovarianceMatrix(y_,Py_);\n    coupledInnSigmaPoints_.getCovarianceMatrix(filterState.stateSigmaPointsPre_,Pyx_);\n  }\n  template<bool IC = isCoupled, typename std::enable_if<(!IC)>::type* = nullptr>\n  void handleUpdateSigmaPoints(mtFilterState& filterState){\n    refreshNoiseSigmaPoints();\n    stateSigmaPoints_.computeFromGaussian(filterState.state_,filterState.cov_);\n    for(unsigned int i=0;i<innSigmaPoints_.L_;i++){\n      this->evalInnovation(innSigmaPoints_(i),stateSigmaPoints_(i),stateSigmaPointsNoi_(i));\n    }\n    innSigmaPoints_.getMean(y_);\n    innSigmaPoints_.getCovarianceMatrix(y_,Py_);\n    innSigmaPoints_.getCovarianceMatrix(stateSigmaPoints_,Pyx_);\n  }\n  bool testUpdateJacs(double d = 1e-6,double th = 1e-6){\n    mtState state;\n    mtMeas meas;\n    unsigned int s = 1;\n    state.setRandom(s);\n    meas.setRandom(s);\n    return testUpdateJacs(state,meas,d,th);\n  }\n  bool testUpdateJacs(const mtState& state, const mtMeas& meas, double d = 1e-6,double th = 1e-6){\n    mtInputTuple inputs;\n    const double dt = 1.0;\n    std::get<0>(inputs) = state;\n    std::get<1>(inputs).setIdentity(); // Noise is always set to zero for Jacobians\n    meas_ = meas;\n    return this->testJacs(inputs,d,th,dt);\n  }\n};\n\n}\n\n#endif /* LWF_UPDATEMODEL_HPP_ */\n", "meta": {"hexsha": "411925c06f63c26a826f89f7ec0366e9a360824c", "size": 15839, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lightweight_filtering/include/lightweight_filtering/Update.hpp", "max_stars_repo_name": "nicolov/rovio_fork", "max_stars_repo_head_hexsha": "8a6d0b1de95389868bc9a988a3adf04ae34d50bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T01:00:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-05T01:00:08.000Z", "max_issues_repo_path": "lightweight_filtering/include/lightweight_filtering/Update.hpp", "max_issues_repo_name": "nicolov/rovio_fork", "max_issues_repo_head_hexsha": "8a6d0b1de95389868bc9a988a3adf04ae34d50bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lightweight_filtering/include/lightweight_filtering/Update.hpp", "max_forks_repo_name": "nicolov/rovio_fork", "max_forks_repo_head_hexsha": "8a6d0b1de95389868bc9a988a3adf04ae34d50bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.3027295285, "max_line_length": 172, "alphanum_fraction": 0.7042111244, "num_tokens": 4451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745834049793372, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4354525882554908}}
{"text": "\n#include <Eigen/Core>\n\n#include <vector>\n#include <memory>\n\n#include <CGAL/Boolean_set_operations_2.h>\n\n// standard includes\n#include <iostream>\n\n#include \"SDOT/PolygonRasterize.h\"\n#include \"SDOT/RegularGrid.h\"\n#include \"SDOT/LaguerreDiagram.h\"\n\nusing namespace sdot;\n\nint main(int argc, char* argv[])\n{\n  int numPts = 4;\n  Eigen::VectorXd costs = Eigen::VectorXd::Ones(numPts);\n\n  Eigen::Matrix2Xd pts(2,numPts);\n  pts <<  0.680375,  0.566198,  0.823295,  0.329554,//  0.444451, 0.0452059,  0.270431,  0.904459,  0.271423,  0.716795,\n          0.211234,   0.59688,  0.604897,  0.536459;//,   0.10794,  0.257742, 0.0268018,   0.83239,  0.434594,  0.213938;\n\n\n  std::cout << \"Points = \\n\";\n  std::cout << \"[[\" << pts(0,0) << \",\" << pts(1,0) << \"]\";\n  for(int i=1; i<numPts; ++i){\n    std::cout << \", [\" << pts(0,i) << \",\" << pts(1,i) << \"]\";\n  }\n  std::cout << \"]\" << std::endl;\n\n  Eigen::Matrix2Xd domain(2,4);\n  domain << 0.0, 1.0, 1.0, 0.0,\n            0.0, 0.0, 1.0, 1.0;\n  // domain << 0.0, 1.0, 1.0, 0.0,\n  //           0.0, 0.0, 1.0, 1.0;\n\n  LaguerreDiagram diag(domain(0,0), domain(0,1), domain(1,0), domain(1,2), pts, costs);\n\n  auto grid = std::make_shared<RegularGrid>(domain(0,0),domain(1,0), domain(0,2), domain(1,2), 10, 10);\n\n  double area = 0.0;\n  Eigen::VectorXd localAreas = Eigen::VectorXd::Zero(numPts);\n  Eigen::MatrixXd cellAreas = Eigen::MatrixXd::Zero(grid->NumCells(0), grid->NumCells(1));\n\n  for(int polyInd=0; polyInd<numPts; ++polyInd){\n    std::cout << \"\\n\\n==================================\\n\";\n    std::cout << \"Polygon \" << polyInd << std::endl;\n    std::shared_ptr<PolygonRasterizeIter::Polygon_2> poly = diag.GetCell(polyInd)->ToCGAL();\n\n    auto vertIt = poly->vertices_begin();\n    std::cout << \"[[\" << vertIt->x() << \",\" << vertIt->y() << \"]\";\n    vertIt++;\n    for(;  vertIt != poly->vertices_end(); ++vertIt){\n      std::cout << \", [\" << vertIt->x() << \",\" << vertIt->y() << \"]\";\n    }\n    std::cout << \"]\" << std::endl;\n\n    PolygonRasterizeIter gridIter(grid,poly);\n\n    //\n    // unsigned int oldYInd = gridIter.Indices().second;\n    // std::cout << \"yind = \" << oldYInd << std::endl;\n    // std::cout << \"yval = \" << grid->yMin + oldYInd*grid->dy << std::endl;\n    // std::cout << \"    \";\n\n    while(gridIter.IsValid()){\n\n      // if(gridIter.Indices().second != oldYInd){\n      //   oldYInd = gridIter.Indices().second;\n      //   std::cout << \"\\nyind = \" << oldYInd << std::endl;\n      //   std::cout << \"yval = \" << grid->yMin + oldYInd*grid->dy << std::endl;\n      //   std::cout << \"    \";\n      // }\n\n      double cellArea;\n\n\n      if(gridIter.IsBoundary()){\n\n        cellArea = CGAL::to_double( gridIter.OverlapPoly()->area() );\n        //std::cout << \"  \" << gridIter.Indices().first << \", \" << gridIter.Indices().second << \" -> Overlap poly = \" << *gridIter.OverlapPoly() << std::endl;\n        // unsigned int indX = gridIter.Indices().first;\n        // unsigned int indY = gridIter.Indices().second;\n        //\n        // PolygonRasterizeIter::Polygon_2 tempPoly;\n        // tempPoly.push_back(PolygonRasterizeIter::Point_2(grid->xMin + indX*grid->dx, grid->yMin+indY*grid->dy));\n        // tempPoly.push_back(PolygonRasterizeIter::Point_2(grid->xMin + (indX+1)*grid->dx, grid->yMin+indY*grid->dy));\n        // tempPoly.push_back(PolygonRasterizeIter::Point_2(grid->xMin + (indX+1)*grid->dx, grid->yMin+(indY+1)*grid->dy));\n        // tempPoly.push_back(PolygonRasterizeIter::Point_2(grid->xMin + indX*grid->dx, grid->yMin+(indY+1)*grid->dy));\n        //\n        // // Compute the intersection of P and Q.\n        // std::list<PolygonRasterizeIter::Polygon_with_holes_2> interList;\n        // CGAL::intersection(*poly, tempPoly, std::back_inserter(interList));\n        //\n        // double trueArea = CGAL::to_double( interList.begin()->outer_boundary().area() );\n        //\n        // //std::cout << *gridIter.OverlapPoly() << std::endl;\n        // double error = cellArea-trueArea;\n        // if(std::abs(error)>std::numeric_limits<double>::epsilon()){\n        //   // std::cout << \"  Cell area = \" << cellArea << \" with error \" << error << std::endl;\n        // }\n      }else{\n        cellArea = grid->dx*grid->dy;\n      }\n\n      std::cout << \"    area(\" << gridIter.Indices().first << \",\" << gridIter.Indices().second << \")= \" << cellArea << std::endl;\n      cellAreas(gridIter.Indices().first, gridIter.Indices().second) += cellArea;\n      localAreas(polyInd) += std::abs(cellArea);\n      area += std::abs(cellArea);\n\n      gridIter.Increment();\n    }\n\n    std::cout << \"  Polygon area = \" << localAreas(polyInd) << std::endl;\n    std::cout << \"  Polygon area error = \" << localAreas(polyInd) - CGAL::to_double( poly->area() ) << std::endl;\n    // std::cout << \"\\n\\n\";\n  }\n\n  // Eigen::VectorXd trueAreas(3);\n  // trueAreas << 0.15*0.15, (domain(0,2)-0.15)*0.15 + 0.5*(domain(1,2)-0.15)*(domain(0,2)-0.15), 0.15*(domain(1,2)-0.15) + 0.5*(domain(1,2)-0.15)*(domain(0,2)-0.15);\n\n  // List all cells with errors\n  for(unsigned int yInd=0; yInd<grid->NumCells(1); ++yInd){\n    for(unsigned int xInd=0; xInd<grid->NumCells(0); ++xInd){\n      if(std::abs(cellAreas(xInd,yInd) - grid->dx*grid->dy)>1e-15){\n        std::cout << \"Cell \" << xInd << \",\" << yInd << \" error = \" << cellAreas(xInd,yInd) - grid->dx*grid->dy << std::endl;\n      }\n    }\n  }\n\n  std::cout << \"Local areas = \" << localAreas.transpose() << std::endl;\n\n  //std::cout << \"dx*dy = \" << grid->dx * grid->dy << std::endl;\n  std::cout << \"True total area = \" << grid->dx*grid->dy*grid->NumCells() << std::endl;\n  std::cout << \"Total Area = \" << area << std::endl;\n  std::cout << \"Error = \" << area - grid->dx*grid->dy*grid->NumCells() << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "af38268214f1185799b37a50a83088bff5d393ea", "size": 5680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/ConstructLaguerre.cpp", "max_stars_repo_name": "mparno/sdot2d", "max_stars_repo_head_hexsha": "f632824fc4f0285eab6de911cca8932f69ece705", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/ConstructLaguerre.cpp", "max_issues_repo_name": "mparno/sdot2d", "max_issues_repo_head_hexsha": "f632824fc4f0285eab6de911cca8932f69ece705", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/ConstructLaguerre.cpp", "max_forks_repo_name": "mparno/sdot2d", "max_forks_repo_head_hexsha": "f632824fc4f0285eab6de911cca8932f69ece705", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7202797203, "max_line_length": 166, "alphanum_fraction": 0.5621478873, "num_tokens": 1902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.43545258240480383}}
{"text": "#ifndef CALIBRATOR_PROCESSES_GENERAL_VASICEK_HPP\n#define CALIBRATOR_PROCESSES_GENERAL_VASICEK_HPP\n\n#include <boost/bind.hpp>\n\n#include <ql/math/randomnumbers/sobolrsg.hpp>\n#include <ql/models/shortrate/onefactormodel.hpp>\n#include <ql/math/integrals/kronrodintegral.hpp>\n\n#include <calibrator/global.hpp>\n#include <calibrator/processes/generalornsteinuhlenbeckprocess.hpp>\n\nnamespace HJCALIBRATOR\n{\n\t//! Time-dependent %Hull-White model class\n\t/*! This class implements the time-dependent Hull-White model defined by\n\t\\f[\n\tdr(t) = (\\theta(t) - a(t)r(t))dt + \\sigma(t) dW_t ,\n\t\\f]\n\ta risk premium \\f$ \\lambda \\f$ can also be specified.\n\n\t\\ingroup shortrate\n\t*/\n\tclass GeneralizedHullWhite : public OneFactorAffineModel, public TermStructureConsistentModel\n\t{\n\tpublic:\n\t\tGeneralizedHullWhite( const Handle<YieldTermStructure>& termStructure,\n\t\t\t\t\t\t\t  const IntegrableParameter& a,\n\t\t\t\t\t\t\t  const Parameter& sigma );\n\n\t\t// OnFactorModel virtual override\n\t\tboost::shared_ptr<Lattice> tree( const TimeGrid& grid ) const override \n\t\t{\n\t\t\treturn boost::shared_ptr<Lattice>();\n\t\t};\n\t\tvirtual boost::shared_ptr<ShortRateDynamics> dynamics() const override;\n\n\t\t\n\t\tvirtual Real discountBondOption( Option::Type type,\n\t\t\t\t\t\t\t\t\t\t Real strike,\n\t\t\t\t\t\t\t\t\t\t Time maturity,\n\t\t\t\t\t\t\t\t\t\t Time bondMaturity ) const override;\n\n\t\tvirtual Real discountBondOption( Option::Type type, Real strike,\n\t\t\t\t\t\t\t\t\t\t Time maturity, Time bondStart,\n\t\t\t\t\t\t\t\t\t\t Time bondMaturity ) const override;\n\n\t\tParameter a() const { return a_; }\n\t\tParameter sigma() const { return sigma_; }\n\n\t\tReal a( Time t ) const { return a_( t ); }\n\t\tReal sigma( Time t ) const { return sigma_( t ); }\n\n\t\t/*! Futures convexity bias (i.e., the difference between\n\t\tfutures implied rate and forward rate) calculated as in\n\t\tG. Kirikos, D. Novak, \"Convexity Conundrums\", Risk\n\t\tMagazine, March 1997.\n\t\thttp://www.powerfinance.com/convexity/\n\n\t\t\\note t and T should be expressed in yearfraction using\n\t\tdeposit day counter, F_quoted is futures' market price.\n\t\t*/\n\t\t// to be implemented with variable a & \\sigma\n\t\t/*\n\t\tstatic Rate convexityBias( Real futurePrice,\n\t\t\t\t\t\t\t\t   Time t,\n\t\t\t\t\t\t\t\t   Time T,\n\t\t\t\t\t\t\t\t   Real sigma,\n\t\t\t\t\t\t\t\t   Real a );\n\t\t*/\n\n\t\tstatic std::vector<bool> FixedReversion() {\n\t\t\tstd::vector<bool> c( 2 );\n\t\t\tc[0] = true; c[1] = false;\n\t\t\treturn c;\n\t\t}\n\n\tprotected:\n\t\tvoid generateArguments();\n\n\t\tvirtual Real A( Time t, Time T ) const;\n\t\tvirtual Real B( Time t, Time T ) const;\n\n\t\tParameter& a_;\n\t\tParameter& sigma_;\n\n\tprivate:\n\t\tclass Dynamics;\n\t\tclass FittingParameter;\n\n\t\tboost::shared_ptr<FittingParameter> alpha_;\n\t};\n\n\tclass GeneralizedHullWhite::FittingParameter : public TermStructureFittingParameter \n\t{\n\tprivate:\n\t\tclass Impl : public Parameter::Impl \n\t\t{\n\t\tpublic:\n\t\t\tImpl( const Handle<YieldTermStructure>& termStructure,\n\t\t\t\t  const IntegrableParameter& a,\n\t\t\t\t  const Parameter& sigma );\n\t\t\t~Impl()\n\t\t\t{\n\t\t\t\tgsl_integration_workspace_free( int_wrkspcs_ );\n\t\t\t}\n\n\t\t\tReal value( const Array&, Time t ) const override;\n\n\t\t\tReal B( Time t, Time T ) const;\n\t\t\tReal variance( Time s, Time t ) const;\n\n\t\tprivate:\n\t\t\tReal E( Time t0, Time t1, Real multiplier = 1. ) const;\n\t\t\tReal integrand( Time u, Time t ) const;\n\t\t\tReal integrandVr( Time t ) const;\n\t\t\tReal value_integral( Time t ) const;\n\n\t\t\tgsl_integration_workspace* int_wrkspcs_;\n\t\t\t//gsl_function integrand_Vr_;\n\t\t\t//gsl_function OneOverE_;\n\n\t\t\tGaussKronrodAdaptive integrator_;\n\t\t\t//SimpsonIntegral integrator_;\n\t\t\t//boost::function<Real( Real )> OneOverEintegrand_; // Eq. 31 integrand\n\t\t\t//boost::function<Real( Real )> Vrintegrand_; // Eq. 37 integrand\n\n\t\t\tHandle<YieldTermStructure> termStructure_;\n\t\t\tIntegrableParameter a_;\n\t\t\tParameter sigma_;\n\t\t};\n\tpublic:\n\t\tFittingParameter( const Handle<YieldTermStructure>& termStructure,\n\t\t\t\t\t\t  const IntegrableParameter& a,\n\t\t\t\t\t\t  const Parameter& sigma )\n\t\t\t: TermStructureFittingParameter( boost::shared_ptr<Parameter::Impl>( new FittingParameter::Impl( termStructure, a, sigma ) ) )\n\t\t{}\n\n\n\t\tReal B( Time t, Time T ) const\n\t\t{\n\t\t\treturn boost::static_pointer_cast<Impl>(implementation())->B( t, T );\n\t\t}\n\n\n\t\tReal variance( Time t, Time T ) const\n\t\t{\n\t\t\treturn boost::static_pointer_cast<Impl>(implementation())->variance( t, T );\n\t\t}\n\t};\n\n\t//! Short-rate dynamics in the time-dependent Hull-White model\n\t/*! The short-rate follows an time-dependent Hull-White process */\n\tclass GeneralizedHullWhite::Dynamics : public OneFactorModel::ShortRateDynamics {\n\tpublic:\n\t\tDynamics( const FittingParameter& fitting,\n\t\t\t\t  const IntegrableParameter& a,\n\t\t\t\t  const Parameter& sigma )\n\t\t\t: ShortRateDynamics( boost::shared_ptr<StochasticProcess1D>(\n\t\t\t\tnew GeneralizedOrnsteinUhlenbeckProcess( a, sigma ) ) )\n\t\t\t, fitting_( fitting )\n\t\t{}\n\n\t\tvirtual Real variable( Time t, Rate r ) const {\n\t\t\treturn r - fitting_( t );\n\t\t}\n\t\tvirtual Real shortRate( Time t, Real x ) const {\n\t\t\treturn x + fitting_( t );\n\t\t}\n\n\t\tFittingParameter fitting_;\n\t};\n\n\t// inline definitions\n\tinline boost::shared_ptr<OneFactorModel::ShortRateDynamics>\n\t\tGeneralizedHullWhite::dynamics() const \n\t{\n\t\treturn boost::shared_ptr<ShortRateDynamics>(\n\t\t\tnew Dynamics( *alpha_, static_cast<IntegrableParameter>(a()), sigma() ) );\n\t}\n\n\tinline Real GeneralizedHullWhite::FittingParameter::Impl::value( const Array&, Time t ) const\n\t{\n\t\t/*\n\t\tRate forwardRate = termStructure_->forwardRate( t, t, Continuous, NoFrequency );\n\t\tReal Et = E( 0, t );\n\t\t\n\t\tboost::function<Real( Real )> I_t;\n\t\tI_t = boost::bind( &GeneralizedHullWhite::FittingParameter::Impl::integrand, this, _1, t );\n\t\tgsl_function tmpf = convertToGslFunction( I_t );\n\n\t\tReal result, error;\n\t\tgsl_integration_qags( &tmpf, 0, t, 0, 1e-7, 1000, int_wrkspcs_, &result, &error );\n\t\t\n\t\treturn forwardRate;// +result;\n\t\t*/\n\n\t\tRate forwardRate = termStructure_->forwardRate( t, t, Continuous, NoFrequency );\n\n\t\tReal intsum = value_integral( t );\n\n\t\treturn forwardRate + intsum;\n\t}\n\n\tinline Real GeneralizedHullWhite::FittingParameter::Impl::integrand( Time u, Time t ) const\n\t{\n\t\t/* eq.36 */\n\t\tReal sigma_u = sigma_( u );\n\n\t\treturn E( 0, u ) * sigma_u * sigma_u * B( u, t );\n\t}\n\n\tinline Real GeneralizedHullWhite::FittingParameter::Impl::integrandVr( Time t ) const\n\t{\n\t\tReal sigma_t = sigma_( t );\n\t\tReal E_t = E( 0, t );\n\n\t\treturn E_t * E_t * sigma_t * sigma_t;\n\t}\n\n\n\tinline Real GeneralizedHullWhite::FittingParameter::Impl::E( Time t0, Time t1, Real multiplier ) const\n\t{\n\t\t/* eq. 30 */\n\t\treturn exp( multiplier * a_.integral( t0, t1 ) );\n\t}\n\n\tinline Real GeneralizedHullWhite::FittingParameter::Impl::B( Time t, Time T ) const\n\t{\n\t\t/* eq. 31 */\n\n\t\tauto lambda = [&, t]( Time u )\n\t\t{\n\t\t\treturn 1 / E( t, u );\n\t\t};\n\n\t\treturn integrator_( lambda, t, T );\n\t}\n\n\tinline Real GeneralizedHullWhite::FittingParameter::Impl::variance( Time s, Time t ) const\n\t{\n\t\t/* eq. 37 */\n\t\tconst Parameter& sigma_i = sigma_;\n\n\t\tauto integrand = [&, sigma_i,  t]( Time u )\n\t\t{\n\t\t\tReal sigma = sigma_i( u );\n\t\t\tReal Eut = E( u, t );\n\t\t\treturn sigma * sigma / Eut / Eut;\n\t\t};\n\n\t\treturn integrator_( integrand, s, t );\n\t}\n}\n\n#endif // !CALIBRATOR_PROCESSES_GENERAL_VASICEK_HPP\n", "meta": {"hexsha": "9862ed6b0641444dc613441cbbaf442b753051f6", "size": 7041, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "calibrator/obsolete/generalhullwhite.hpp", "max_stars_repo_name": "hanjin-kim/gaussian-n-factor", "max_stars_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-25T05:59:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T04:10:19.000Z", "max_issues_repo_path": "calibrator/obsolete/generalhullwhite.hpp", "max_issues_repo_name": "hanjin-kim/gaussian-n-factor", "max_issues_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calibrator/obsolete/generalhullwhite.hpp", "max_forks_repo_name": "hanjin-kim/gaussian-n-factor", "max_forks_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-27T04:10:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T04:10:42.000Z", "avg_line_length": 27.3968871595, "max_line_length": 129, "alphanum_fraction": 0.6879704587, "num_tokens": 2035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4354525765541165}}
{"text": "/**\n * @file expressions.hpp\n * \n */\n\n#pragma once\n\n#include \"parameter.hpp\"\n#include \"variable.hpp\"\n\n#include <Eigen/Sparse>\n\nnamespace Eigen\n{\n\n    template <>\n    struct NumTraits<cvx::Scalar>\n        : NumTraits<double>\n    {\n        using Real = cvx::Scalar;\n        using NonInteger = cvx::Scalar;\n        using Nested = cvx::Scalar;\n\n        enum\n        {\n            IsComplex = 0,\n            IsInteger = 0,\n            IsSigned = 1,\n            RequireInitialization = 1,\n            ReadCost = 10,\n            AddCost = 200,\n            MulCost = 200,\n        };\n    };\n\n} // namespace Eigen\n\nnamespace cvx\n{\n    class Constraint;\n    class OptimizationProblem;\n    class Scalar;\n\n    namespace internal\n    {\n        class Affine;\n        class SOCPWrapperBase;\n        class QPWrapperBase;\n\n        class Term\n        {\n        public:\n            Term();\n\n            Parameter parameter;\n            Variable variable;\n\n            bool operator==(const Term &other) const;\n            Term &operator*=(const Parameter &param);\n            Term &operator/=(const Parameter &param);\n\n            operator Affine() const;\n\n            friend std::ostream &operator<<(std::ostream &os, const Term &term);\n            double evaluate() const;\n        };\n\n        class Affine\n        {\n        public:\n            bool operator==(const Affine &other) const;\n\n            Parameter constant = Parameter(0.);\n            std::vector<Term> terms;\n\n            friend std::ostream &operator<<(std::ostream &os, const Affine &affine);\n            double evaluate() const;\n            Affine &operator+=(const Affine &other);\n            Affine &operator-=(const Affine &other);\n            Affine &operator*=(const Parameter &param);\n            Affine &operator/=(const Parameter &param);\n            // Affine operator+(const Affine &other) const;\n            Affine operator-(const Affine &other) const;\n            Affine operator-() const;\n\n            void cleanUp();\n\n            bool isZero() const;\n            bool isConstant() const;\n            bool isFirstOrder() const;\n        };\n\n        class Product\n        {\n        public:\n            explicit Product(const Affine &term);\n            Product(const Affine &lhs, const Affine &rhs);\n            Affine &firstTerm();\n            Affine &secondTerm();\n            const Affine &firstTerm() const;\n            const Affine &secondTerm() const;\n            void toSquaredTerm();\n            double evaluate() const;\n            bool isSquare() const;\n\n            bool operator==(const Product &other) const;\n\n            friend std::ostream &operator<<(std::ostream &os, const Product &product);\n\n        private:\n            std::vector<Affine> factors;\n        };\n\n    } // namespace internal\n\n    class Scalar\n    {\n    public:\n        Scalar() = default;\n        explicit Scalar(int x);\n        Scalar(double x);\n        explicit Scalar(double *x);\n\n        Scalar &operator+=(const Scalar &other);\n        Scalar &operator-=(const Scalar &other);\n        Scalar &operator*=(const Scalar &other);\n        Scalar &operator/=(const Scalar &other);\n        Scalar operator-() const;\n        friend Scalar operator+(const Scalar &lhs, const Scalar &rhs);\n        friend Scalar operator-(const Scalar &lhs, const Scalar &rhs);\n        friend Scalar operator*(const Scalar &lhs, const Scalar &rhs);\n        friend Scalar operator/(const Scalar &lhs, const Scalar &rhs);\n\n        bool operator==(const cvx::Scalar &other) const;\n\n        double evaluate() const;\n        size_t getOrder() const;\n        bool isNorm() const;\n\n        friend OptimizationProblem;\n        friend internal::SOCPWrapperBase;\n        friend internal::QPWrapperBase;\n\n        explicit operator double() const;\n\n        friend Scalar sqrt(const Scalar &scalar);\n        friend Scalar square(const Scalar &scalar);\n        friend Scalar abs2(const Scalar &scalar);\n\n        // friend internal::Parameter::operator Scalar() const;\n        friend internal::Variable::operator Scalar() const;\n\n        friend Constraint equalTo(const Scalar &lhs, const Scalar &rhs);\n        friend Constraint lessThan(const Scalar &lhs, const Scalar &rhs);\n        friend Constraint greaterThan(const Scalar &lhs, const Scalar &rhs);\n        friend Constraint box(const Scalar &lower, const Scalar &middle, const Scalar &upper);\n\n    private:\n        internal::Affine affine;\n        std::vector<internal::Product> products;\n        bool norm = false;\n\n        friend std::ostream &operator<<(std::ostream &os, const Scalar &scalar);\n    };\n\n    using MatrixX = Eigen::Matrix<cvx::Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using VectorX = Eigen::Matrix<cvx::Scalar, Eigen::Dynamic, 1>;\n\n    /**\n     * @brief Creates a constant parameter.\n     * \n     * @param p The value of the parameter\n     * @return Scalar The constant parameter\n     */\n    Scalar par(double p);\n\n    /**\n     * @brief Creates a dynamic parameter.\n     * \n     * @details Internally stores pointers to the original values.\n     * \n     * @warning Do not delete the source before the parameter is no longer required.\n     * \n     * @param p The value of the parameter\n     * @return Scalar The constant parameter\n     */\n    Scalar dynpar(double &p);\n\n    /**\n     * @brief Creates a constant parameter from a dense Eigen type.\n     * \n     * @tparam Derived \n     * @param m A dense Eigen type containing problem parameters\n     * @return auto A dense Eigen type with cvx::Scalar as scalar type\n     */\n    template <typename Derived>\n    inline auto par(const Eigen::MatrixBase<Derived> &m)\n    {\n        return m.template cast<Scalar>().eval();\n    }\n\n    /**\n     * @brief Creates a constant parameter from a sparse Eigen type.\n     * \n     * @tparam Derived \n     * @param m A sparse Eigen type containing problem parameters\n     * @return auto A sparse Eigen type with cvx::Scalar as scalar type\n     */\n    template <typename Derived>\n    inline auto par(const Eigen::SparseMatrixBase<Derived> &m)\n    {\n        return m.template cast<Scalar>().eval();\n    }\n\n    /**\n     * @brief Creates a dynamic parameter from a dense Eigen type.\n     * \n     * @details Internally stores pointers to the original values.\n     * \n     * @warning Do not delete the source before the parameter is no longer required.\n     * \n     * @tparam Derived \n     * @param m A dense Eigen type containing problem parameters\n     * @return auto A dense Eigen type with cvx::Scalar as scalar type\n     */\n    template <typename Derived>\n    auto dynpar(Eigen::MatrixBase<Derived> &m)\n    {\n        auto result = m.template cast<Scalar>().eval();\n\n        for (int row = 0; row < m.rows(); row++)\n        {\n            for (int col = 0; col < m.cols(); col++)\n            {\n                result.coeffRef(row, col) = dynpar(m.coeffRef(row, col));\n            }\n        }\n\n        return result;\n    }\n\n    /**\n     * @brief Creates a dynamic parameter from a sparse Eigen type.\n     * \n     * @details Internally stores pointers to the original values.\n     * \n     * @warning Do not delete the source before the parameter is no longer required.\n     * \n     * @tparam T \n     * @param m A sparse Eigen type containing problem parameters\n     * @return auto A sparse Eigen type with cvx::Scalar as scalar type\n     */\n    template <typename T>\n    auto dynpar(Eigen::SparseMatrix<T> &m)\n    {\n        auto result = m.template cast<Scalar>().eval();\n\n        for (int k = 0; k < result.nonZeros(); k++)\n        {\n            result.valuePtr()[k] = dynpar(m.valuePtr()[k]);\n        }\n\n        return result;\n    }\n\n    /**\n     * @brief Evaluates the scalar.\n     * \n     * @param s The scalar to be evaluated\n     * @return double The value of the scalar\n     */\n    double eval(const Scalar &s);\n\n    /**\n     * @brief Evaluates a dense Eigen type\n     * \n     * @tparam Derived Has to be cvx::Scalar\n     * @param m A dense Eigen type to be evaluated\n     * @return auto The evaluated dense Eigen type\n     */\n    template <typename Derived>\n    inline auto eval(const Eigen::MatrixBase<Derived> &m)\n    {\n        return m.template cast<double>();\n    }\n\n    /**\n     * @brief Evaluates a sparse Eigen type\n     * \n     * @tparam Derived Has to be cvx::Scalar\n     * @param m A sparse Eigen type to be evaluated\n     * @return auto The evaluated sparse Eigen type\n     */\n    template <typename Derived>\n    inline auto eval(const Eigen::SparseMatrixBase<Derived> &m)\n    {\n        return m.template cast<double>();\n    }\n\n    inline const Scalar &conj(const Scalar &x) { return x; }\n    inline const Scalar &real(const Scalar &x) { return x; }\n    inline Scalar imag(const Scalar &) { return Scalar(0.); }\n    inline Scalar square(const Scalar &x)\n    {\n        Scalar new_scalar;\n        new_scalar.products = {internal::Product(x.affine)};\n        return new_scalar;\n    }\n    inline Scalar abs2(const Scalar &x)\n    {\n        return square(x);\n    }\n\n} // namespace cvx\n", "meta": {"hexsha": "2500c92d8b50eee2889b34fa9ee7cbd6633dc929", "size": 8958, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expressions.hpp", "max_stars_repo_name": "BenjaminNavarro/Epigraph", "max_stars_repo_head_hexsha": "c76293fe437d68442598c080ab092e3806177b48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 116.0, "max_stars_repo_stars_event_min_datetime": "2020-06-29T23:36:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T04:19:14.000Z", "max_issues_repo_path": "include/expressions.hpp", "max_issues_repo_name": "BenjaminNavarro/Epigraph", "max_issues_repo_head_hexsha": "c76293fe437d68442598c080ab092e3806177b48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-08-17T14:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-16T07:31:36.000Z", "max_forks_repo_path": "include/expressions.hpp", "max_forks_repo_name": "BenjaminNavarro/Epigraph", "max_forks_repo_head_hexsha": "c76293fe437d68442598c080ab092e3806177b48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T03:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T08:27:05.000Z", "avg_line_length": 28.4380952381, "max_line_length": 94, "alphanum_fraction": 0.5860683188, "num_tokens": 1997, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4354467121457266}}
{"text": "//Copyright (c) 2014 - 2020, The Trustees of Indiana University.\n//\n//Licensed under the Apache License, Version 2.0 (the \"License\");\n//you may not use this file except in compliance with the License.\n//You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n//Unless required by applicable law or agreed to in writing, software\n//distributed under the License is distributed on an \"AS IS\" BASIS,\n//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//See the License for the specific language governing permissions and\n//limitations under the License.\n\n#include <cmath>\n\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/math/distributions/normal.hpp>\n\n#include \"common/util/logger.hpp\"\n#include \"ms/spec/peak.hpp\"\n#include \"ms/spec/env_peak.hpp\"\n#include \"ms/spec/raw_ms_util.hpp\"\n#include \"ms/feature/peak_cluster.hpp\"\n\nnamespace toppic {\n\nint PeakCluster::even_charge_idx_ = 0;\nint PeakCluster::odd_charge_idx_ = 1;\ndouble PeakCluster::win_size_ = 6.0;\n\ndouble getBcDistance(std::vector<double> &v1, std::vector<double> &v2) {\n  if (v1.size() != v2.size() || v1.size() == 0) {\n    LOG_ERROR(\"Two vectors have different sizes!\");\n    exit(EXIT_FAILURE);\n  }\n\n  double s1 = 0.0;\n  double s2 = 0.0;\n  for (size_t i = 0; i < v1.size(); i++) {\n    s1 += v1[i];\n    s2 += v2[i];\n  }\n\n  if (!(s1 > 0) || !(s2 > 0)) return 10.0;\n\n  double bc = 0.0;\n  for (size_t i = 0; i < v1.size(); i++) {\n    double p = v1[i]/ s1;\n    double q = v2[i]/ s2;\n    bc += std::sqrt(p * q); \n  }\n  if (bc > std::exp(-10)) {\n    return -std::log(bc);\n  }\n  else {\n    return 10;\n  }\n}\n\n\ndouble getPearsonCorr(std::vector<double> &v1, std::vector<double> &v2) {\n  if (v1.size() != v2.size() || v1.size() == 0) {\n    LOG_ERROR(\"Two vectors have different sizes or empty vector!\");\n    exit(EXIT_FAILURE);\n  }\n  if (v1.size() == 1) {\n    return 1.0;\n  }\n  // Compute means\n  double m1 = 0.0;\n  double m2 = 0.0;\n  for (size_t i = 0; i < v1.size(); i++) {\n    m1 += v1[i];\n    m2 += v2[i];\n  }\n  m1 /= v1.size();\n  m2 /= v2.size();\n\n  // compute Pearson correlation\n  double cov = 0.0;\n  double s1 = 0.0;\n  double s2 = 0.0;\n\n  for (size_t i = 0; i < v1.size(); i++) {\n    double d1 = v1[i] - m1;\n    double d2 = v2[i] - m2;\n    cov += d1 * d2;\n    s1 += d1 * d1;\n    s2 += d2 * d2;\n  }\n\n  if (s1 <= 0 || s2 <= 0) return 0;\n\n  return cov < 0 ? 0 : cov / std::sqrt(s1 * s2);\n}\n\ndouble getPoissonPValue(PeakPtrVec &win_peaks, double win_size, \n                        std::vector<double> &env_peak_intensities) {\n  double win_high_inte = raw_ms_util::getHighestPeakInte(win_peaks);\n  double inte_thresh = win_high_inte  * 0.1;\n  int match_peak_num = 0;\n  for (size_t i = 0; i < env_peak_intensities.size(); i++) {\n    if (env_peak_intensities[i] > inte_thresh) {\n      match_peak_num++;\n    }\n  }\n  int inte_peak_num = 0;\n  for (size_t i = 0; i < win_peaks.size(); i++) {\n    if (win_peaks[i]->getIntensity() > inte_thresh) {\n      inte_peak_num++;\n    }\n  }\n  int possible_peak_num = std::ceil(win_size * 100);\n\n  double n = possible_peak_num;\n  double k = env_peak_intensities.size();\n  double n1 = inte_peak_num;\n  double k1 = match_peak_num;\n  double lambda = n1 / n * k;\n\n  boost::math::poisson_distribution<> pd(lambda); \n\n  double pvalue = 1.0 - boost::math::cdf(pd, k1);\n  return pvalue;\n}\n\ndouble compRankSumPValue(double n1, double n2, double r1) {\n  double u1 = n1 * n2 + n1 * (n1 + 1) * 0.5 - r1;\n\n  double mean_u = 0.5 * (n1 * n2);\n  double log_sig_u = 0.5 * (std::log(n1) + std::log(n2) + std::log(n1 + n2 + 1) - std::log(12));\n  double sig_u = std::exp(log_sig_u);\n  LOG_DEBUG(\"log sig u \" << log_sig_u << \" sig u \" << sig_u << \" n1 \" << n1 << \" n2 \" << n2 << \" r1 \" << r1);\n  // all peaks are matched\n  if (sig_u == 0.0) {\n    return 0.0;\n  }\n  boost::math::normal_distribution<> nd(mean_u, sig_u);\n  double p_value = boost::math::cdf(nd, u1);\n  p_value = std::min(p_value, 1-p_value);\n  return std::abs(p_value);\n}\n\ndouble getRankSumPValue(PeakPtrVec win_peaks, std::vector<double> &env_peak_intensities) {\n  int rank_sum = 0;\n  int match_peak_num = 0;\n\n  std::sort(win_peaks.begin(), win_peaks.end(), Peak::cmpInteDec);\n\n  for (size_t i = 0; i < env_peak_intensities.size(); i++) {\n    double peak_inte = env_peak_intensities[i];\n    if (peak_inte > 0.0) {\n      int rank = win_peaks.size();\n      for (size_t j = 0; j < win_peaks.size(); j++) {\n        if (peak_inte >= win_peaks[j]->getIntensity()) {\n          rank = j+1;\n          break;\n        }\n      }\n      rank_sum += rank;\n      match_peak_num++; \n    }\n  }\n  int peak_num = win_peaks.size();\n  double pvalue = compRankSumPValue(peak_num, match_peak_num, rank_sum);\n  return pvalue;\n}\n\nPeakCluster::PeakCluster(EnvelopePtr theo_env) {\n  theo_env_ = theo_env;\n  rep_mass_ = theo_env_->getMonoNeutralMass();\n  rep_charge_ = theo_env_->getCharge();\n\n  int peak_num = theo_env_->getPeakNum();\n  rep_summed_intensities_.resize(peak_num, 0.0);\n\n  clearScores();\n\n  flag_ = 0;\n  init_score_ = false;\n  smoother_ = std::make_shared<SavitzkyGolay>(9, 2);\n}\n\nvoid PeakCluster::addEnvelopes(FracFeaturePtr feature_ptr, \n                               RealEnvPtrVec envs) {\n\n  int row_num = feature_ptr->getMaxCharge() - feature_ptr->getMinCharge() + 1;\n  int col_num = feature_ptr->getMaxMs1Id() - feature_ptr->getMinMs1Id() + 1;\n  \n  min_charge_ = feature_ptr->getMinCharge();\n  max_charge_ = feature_ptr->getMaxCharge();\n\n  min_ms1_id_ = feature_ptr->getMinMs1Id();\n  max_ms1_id_ = feature_ptr->getMaxMs1Id();\n\n  scan_begin_ = feature_ptr->getScanBegin();\n  scan_end_ = feature_ptr->getScanEnd();\n  LOG_DEBUG(\"add env row \" << row_num << \" col \" << col_num);\n\n  real_envs_.resize(row_num);\n\n  for (int i = 0; i < row_num; i++) {\n    real_envs_[i].resize(col_num);\n  }\n\n  for (size_t i = 0; i < envs.size(); i++) {\n    int row = envs[i]->getCharge() - min_charge_;\n    int col = envs[i]->getSpId() - min_ms1_id_;\n    if (row >= 0 && row < row_num && col >= 0 && col < col_num) {\n      real_envs_[row][col] = envs[i];\n    }\n  }\n}\n\nvoid PeakCluster::clearScores() {\n  inte_distr_.resize(2, 0.0);\n  best_corr_scores_.resize(2, 0.0);\n  best_inte_scores_.resize(2, 0.0);\n  best_dist_scores_.resize(2, 1.0);\n\n  best_charges_.resize(2, 0);\n  sum_dist_scores_.resize(2, 1.0);\n  sum_corr_scores_.resize(2, 0.0);\n  sum_inte_scores_.resize(2, 0.0);\n  xic_corr_between_best_charges_.resize(2, 0.0);\n}\n\nvoid PeakCluster::updateScore(PeakPtrVec2D &raw_peaks, bool check_pvalue) {\n  int row_num = max_charge_ - min_charge_ + 1;\n  int col_num = max_ms1_id_ - min_ms1_id_ + 1;\n  int ref_idx = theo_env_->getReferIdx(); \n\n  clearScores();\n\n  std::vector<double> best_charge_dists{10.0, 10.0};\n\n  // sum up peak intensities\n  int peak_num = theo_env_->getPeakNum();\n  std::vector<double> theo_intensities = theo_env_->getIntensities();\n  std::vector<double> summed_intensities(peak_num, 0);\n\n  int xic_len = col_num + 18;\n  int xic_start_idx = 9;\n\n  std::vector<std::vector<double>> xic2(2);\n  xic2[0].resize(xic_len, 0.0);\n  xic2[1].resize(xic_len, 0.0);\n\n  std::vector<std::vector<double>> charge_xic(row_num);\n\n  double tmp_best_bc_dist = 10.0;\n  double rep_env_bc_dist = 10.0;\n  RealEnvPtr rep_env(nullptr);\n\n  double rep_env_bc_dist_2 = 10.0;\n  RealEnvPtr rep_env_2(nullptr);\n\n  std::vector<double> tmp_best_dist_scores{10.0, 10.0};\n  std::vector<double> tmp_best_inte_scores(2, 0.0);\n  std::vector<double> tmp_best_corr_scores(2, 0.0);\n\n  for (int i = 0; i < row_num; i++) {\n    int charge = i + min_charge_;\n    double ref_neutral_mass = theo_env_->getRefNeutralMass();\n    double ref_mz = Peak::compMz(ref_neutral_mass, charge); \n    std::fill(summed_intensities.begin(), summed_intensities.end(), 0.0);\n\n    charge_xic[i].resize(xic_len, 0.0);\n\n    int charge_idx = (charge % 2 == 0) ? even_charge_idx_:odd_charge_idx_;\n    // summed_most_abu_isotope_intensity\n    double summed_iso_high_inte = 0.0;\n    //summed_referenc_intensity\n    double summed_win_high_inte = 0.0;\n\n    for (int j = 0; j < col_num; j++) {\n      RealEnvPtr env = real_envs_[i][j];\n      if (env == nullptr) continue;\n      \n      // sum peak inte\n      for (int k = 0; k < peak_num; k++) {\n        summed_intensities[k] += env->getIntensity(k);\n      }\n\n      int ms1_id = min_ms1_id_ + j;\n      PeakPtrVec all_peaks = raw_peaks[ms1_id];\n      PeakPtrVec win_peaks = raw_ms_util::getPeaksInWindow(all_peaks, ref_mz, win_size_);\n      double win_high_inte = raw_ms_util::getHighestPeakInte(win_peaks);\n      double win_median_inte = raw_ms_util::getMedianPeakInte(win_peaks);\n       \n      if (env->isExist(ref_idx)) {\n        summed_iso_high_inte += env->getIntensity(ref_idx);\n        summed_win_high_inte += win_high_inte;\n      }\n      double env_inte_sum = env->getIntensitySum();\n      inte_distr_[charge_idx] += env_inte_sum; \n\n      std::vector<double> real_intensities = env->getIntensities();\n\n      double new_bc_dist = getBcDistance(theo_intensities, real_intensities);\n      double new_corr = getPearsonCorr(theo_intensities, real_intensities);\n\n      bool good_env = (new_bc_dist < 0.07 || new_corr > 0.7);\n      if (good_env) {\n        xic2[charge_idx][xic_start_idx + j] += env_inte_sum;\n        charge_xic[i][xic_start_idx+j] = env_inte_sum;\n      }\n\n      bool level_one_env = true;\n      bool level_two_env = true;\n      if (check_pvalue) {\n        double poisson_pvalue = getPoissonPValue(win_peaks, win_size_, real_intensities);\n        double rank_sum_pvalue = getRankSumPValue(win_peaks, real_intensities);\n        level_one_env = (rank_sum_pvalue < 0.01 && poisson_pvalue < 0.01);\n        //levelTwoEnvelope = (rankSumPValue < 0.05 || poissonPValue < 0.05);\n      }\n      if (level_one_env ) {\n        if (new_bc_dist < best_dist_scores_[charge_idx]) {\n          best_dist_scores_[charge_idx] = new_bc_dist;\n          double new_inte_score = 1.0;\n          if (win_median_inte > 0.0) {\n            new_inte_score = env->getReferIntensity()/win_high_inte; \n          }\n          best_inte_scores_[charge_idx] = std::max(best_inte_scores_[charge_idx], new_inte_score);\n        }\n        best_corr_scores_[charge_idx] = std::max(best_corr_scores_[charge_idx], new_corr);\n\n        if (new_bc_dist < rep_env_bc_dist) {\n          rep_env_bc_dist = new_bc_dist;\n          rep_env = env;\n        }\n      }\n      if (level_two_env) {\n        if (new_bc_dist < tmp_best_dist_scores[charge_idx]) {\n          tmp_best_dist_scores[charge_idx] = new_bc_dist;\n          double new_inte_score = 1.0;\n          if (win_median_inte > 0.0) {\n            new_inte_score = env->getReferIntensity()/win_high_inte; \n          }\n          tmp_best_inte_scores[charge_idx] = std::max(tmp_best_inte_scores[charge_idx], new_inte_score);\n        }\n        tmp_best_corr_scores[charge_idx] = std::max(tmp_best_corr_scores[charge_idx], new_corr);\n\n        if (new_bc_dist < rep_env_bc_dist_2) {\n          rep_env_bc_dist_2 = new_bc_dist;\n          rep_env_2 = env;\n        }\n      }\n\n      double bc_dist = getBcDistance(theo_intensities, summed_intensities);\n      sum_dist_scores_[charge_idx] = std::min(sum_dist_scores_[charge_idx], bc_dist);\n      double pc = getPearsonCorr(theo_intensities, summed_intensities);\n      sum_corr_scores_[charge_idx] = std::max(sum_corr_scores_[charge_idx], pc);\n\n      if (best_charges_[charge_idx] < 1 || bc_dist < best_charge_dists[charge_idx]) {\n        best_charges_[charge_idx] = charge;\n        best_charge_dists[charge_idx] = bc_dist;\n        if (summed_win_high_inte > 0.0) {\n          sum_inte_scores_[charge_idx] = summed_iso_high_inte/summed_win_high_inte;\n        }\n      }\n\n      if (bc_dist < tmp_best_bc_dist) {\n        tmp_best_bc_dist = bc_dist;\n        rep_summed_intensities_ = summed_intensities;\n      }\n    }\n  }\n\n  // when good envelope is observed at only even charge...\n  if (best_corr_scores_[0] > 0.7 && best_corr_scores_[1] < 0.5) {\n    int idx = 1;\n    best_corr_scores_[idx] = tmp_best_corr_scores[idx];\n    best_inte_scores_[idx] = tmp_best_inte_scores[idx];\n    best_dist_scores_[idx] = tmp_best_dist_scores[idx];\n  }\n\n  // when good envelope is observed at only odd charge...\n  if (best_corr_scores_[1] > 0.7 && best_corr_scores_[0] < 0.5) {\n    int idx = 0;\n    best_corr_scores_[idx] = tmp_best_corr_scores[idx];\n    best_inte_scores_[idx] = tmp_best_inte_scores[idx];\n    best_dist_scores_[idx] = tmp_best_dist_scores[idx];\n  }\n\n\n  // normalize intensities\n  double s = inte_distr_[0] + inte_distr_[1];\n  if (s > 0) {\n    inte_distr_[0] = inte_distr_[0] / s;\n    inte_distr_[1] = inte_distr_[1] / s;\n  }\n\n  if (col_num > 1) {\n    int even_best_charge = best_charges_[even_charge_idx_] - min_charge_;\n    int odd_best_charge = best_charges_[odd_charge_idx_] - min_charge_;\n    if (even_best_charge >= 0 && odd_best_charge >= 0) {\n      std::vector<double> v1 = smoother_->smooth(charge_xic[even_best_charge]);\n      std::vector<double> v2 = smoother_->smooth(charge_xic[odd_best_charge]);\n      xic_corr_between_best_charges_[0] = getPearsonCorr(v1, v2); \n      v1 = smoother_->smooth(xic2[even_charge_idx_]);\n      v2 = smoother_->smooth(xic2[odd_charge_idx_]);\n      xic_corr_between_best_charges_[1] = getPearsonCorr(v1, v2);\n    }\n  }\n\n  if (rep_env == nullptr && rep_env_2 != nullptr) {\n    rep_env = rep_env_2;\n  }\n  if (rep_env != nullptr) {\n    rep_charge_ = rep_env->getCharge();\n    rep_mz_ = rep_env->getMonoMz();\n    rep_ms1_id_ = rep_env->getSpId();\n  }\n\n  init_score_ = true;\n}\n\n}\n\n", "meta": {"hexsha": "a5345c0f426c0466aed41c93d0a3588c0f93af4b", "size": 13435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ms/feature/peak_cluster.cpp", "max_stars_repo_name": "toppic-suite/toppic-suite", "max_stars_repo_head_hexsha": "b5f0851f437dde053ddc646f45f9f592c16503ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-05-23T14:37:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T23:48:38.000Z", "max_issues_repo_path": "src/ms/feature/peak_cluster.cpp", "max_issues_repo_name": "toppic-suite/toppic-suite", "max_issues_repo_head_hexsha": "b5f0851f437dde053ddc646f45f9f592c16503ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-08-31T08:17:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T20:58:06.000Z", "max_forks_repo_path": "src/ms/feature/peak_cluster.cpp", "max_forks_repo_name": "toppic-suite/toppic-suite", "max_forks_repo_head_hexsha": "b5f0851f437dde053ddc646f45f9f592c16503ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-25T01:39:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-20T19:25:07.000Z", "avg_line_length": 31.836492891, "max_line_length": 109, "alphanum_fraction": 0.6499441757, "num_tokens": 4239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.43544671214572644}}
{"text": "﻿//=======================================================================\n// Copyright 2015 Tsinghua University.\n// Authors: Fuan Pu (Pu.Fuan@gmail.com)\n// \n// Dung's abstract argumentation framework\n//=======================================================================\n\n#ifndef DUNG_REASONER_HPP\n#define DUNG_REASONER_HPP\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <utility>   \n#include <algorithm>   \n#include <iosfwd>\n\n//boost\n#include <boost/graph/graph_traits.hpp> \n#include <boost/graph/adjacency_list.hpp>\n\n#include \"config/config.hpp\"\n#include \"ArgumentProperty.hpp\"\n#include \"AttackProperty.hpp\"\n#include \"bitmatrix/bitvector.hpp\"\n#include \"bitmatrix/bitmatrix.hpp\"\n#include \"DungAF.hpp\"\n\n\nnamespace argumatrix{\n\nusing namespace std;\n\nclass Reasoner {\npublic:\n\tReasoner(const DungAF& daf, streambuf* osbuff = std::cout.rdbuf());\n\tvirtual ~Reasoner() {}\n\t/**\n\t * @brief Get the attacked arguments by arguments in _bv, \\f$R^+(S)\\f$ \n\t * \\f$R^+(S) = {x|x is attacked by S}\\f$.\n\t * \\f$R^+(S_bv) = D*S_bv\\f$\n\t * @param _bv the bitvector with respect to the set \\f$S\\f$.\n\t * @return a set of arguments in bitvector form.\n\t */\n\tbitvector getAttacked(const bitvector& _bv);\n\t//bitvector R_plus(const bitvector& _bv);\t\n\n\t/**\n\t * @brief The characteristic function of an abstract argumentation framework: \n\t * \\f$F_{AF}(S) = {A|A is acceptable wrt. S}\\f$.\n\t * F_AF(S_bv) = not{ R^+[ not( R^+(S_bv) ) ] }\n\t * @param extension an extension (a set of arguments), the default is empty set.\n\t * @return a set of arguments in bitvector form.\n\t */\n\tbitvector characteristic(const bitvector& _bv);\n\n\t/**\n\t * @brief The characteristic function of an abstract argumentation framework with\n\t * the initialization of empty set\n\t * @return a set of arguments in bitvector form.\n\t */\n\tbitvector characteristic();\n\n\t/**\n\t * @brief The neutrality function of an abstract argumentation framework: \n\t * N_AF(S) = {A| All arguments that not attacked by S}.\n\t * N_AF(S_bv) = not( R^+(S_bv) )\n\t * @param extension an extension (a set of arguments).\n\t * @return a set of arguments in bitvector form.\n\t */\n\tbitvector neutrality(const bitvector& _bv);\n\n\t/**\n\t * @brief Argument set S is conflict-free? \n\t * S is said to be conflict-free iff for any two arguments a,b in S such\n\t * that a does not attack b\n\t * @param extension an extension (a set of arguments).\n\t * @return true if S is conflict-free.\n\t */\n\tbool is_conflict_free(const bitvector& _bv);\n\tbool is_conflict_free(const set<string>& argset);\n\n\t/**\n\t * @brief Argument set A is acceptable w.r.t S? Alternately, S defends A? \n\t * A can be an argument or an argument set. \n\t * S defends argument (set) A iff for any argument x in X, if attacks A\n\t * (or a in A) then there is an argument y in S such that y attacks x.\n\t * @param S: a set of arguments.\n\t * @param A: an argument or an argument set\n\t * @return true if S defends A.\n\t */\n\tbool is_acceptable(const bitvector& S, const bitvector& A);\n\n\t/**\n\t * @brief Argument a is self-attacking iff it attacks itself.\n\t * @param idx: the index of the argument w.r.t the attack matrix\n\t * @return true if S defends A.\n\t */\n\tbool is_self_attacking(size_type idx);\n\n\t/**\n\t * @brief To decide whether a set of arguments (with the form of bitvector) is \n\t * an admissible extension.\n\t * $S$ is an admissible extension iff $S \\subseteq F(S) \\cap N(S)$.\n\t * @return true if _bv is admissible; otherwise returns false.\n\t */\n\tbool is_admissible(const bitvector& _bv);\n\n\n\t/**\n\t * @brief To decide whether a set of arguments (with the form of bitvector) is \n\t * a complete extension.\n\t * $S$ is a complete extension iff $S == F(S) \\cap N(S)$.\n\t * @return true if _bv is complete; otherwise returns false.\n\t */\n\tbool is_complete(const bitvector& _bv);\n\n\t/**\n\t * @brief To decide whether a set of arguments (with the form of bitvector) is \n\t * a stable extension.\n\t * $S$ is a stable extension iff $S == N(S)$.\n\t * @return true if _bv is stable; otherwise returns false.\n\t */\n\tbool is_stable(const bitvector& _bv);\n\n\t/**\n\t * @brief To decide whether a set of arguments (with the form of bitvector) is \n\t * a grounded extension. $S$ is a grounded extension iff it is the least\n\t * fixed point of the characteristic function F.\n\t * @return true if _bv is grounded; otherwise returns false.\n\t */\n\tbool is_grounded(const bitvector& _bv);\n\n\t/**\n\t * @brief Get all arguments which are self-attacking. Obviously, if an argument \n\t * i attacks itself, the entry[i][i] of the attack matrix must be 1 (true).\n\t * Therefore to get the set of self-attacking arguments is to get the diagonal\n\t * elements of the attack matrix.\n\t * @return a set of arguments in bitvector form, if bitvector[i] = true \n\t * representing the argument (with index) i is a self-attacking argument,\n\t * otherwise is not.\n\t */\n\tbitvector getSelfAttackingArguments();\n\n\t/**\n\t * @brief Get all extensions given a specific semantics in format of bitvector. \n\t * Each extension is a set of arguments which can \"survive the conflict\n\t * together\". Here, we use a bitvector to represent an extension. \n\t * Therefore, all extensions are formed an set of bit vectors, i.e., \n\t * set<bitvector>. Each bitvector in set is an extension w.r.t. \n\t * a given semantics. The computed extensions are stored in m_extensions, \n\t * therefore, to get all extensions, it must first invoke the function \n\t * computeExtension() \n\t * @return a set of bitvector, i.e., set<bitvector>. \n\t */\n\tconst set<bitvector>& getBvExtensions();\n\n\n\t/**\n\t * @brief Get a vector of integers {0, 1, 2}: 2 -- Unknown, 1 -- in grounded\n\t * extension, and 0 -- attacked by the grounded extension.\n\t * @return a vector of integers {0, 1, 2}.\n\t */\n\tvector<int> getGroundedIntVector();\n\n\t/**\n\t * @brief Redirect the output stream to streambuf* strbuf or ostream& os. If strbuf = cout.rdbuf(),\n\t * then the output is standard output. It can also redirect the output to \n\t * a file by the following codes:\n\t * ~~~~~{.cpp}\n\t *   ofstream ofile(\"output.txt\");\n\t *   streambuf* oldsb = xxx.setOutput(ofile.rdbuf()); \n\t * ~~~~~\n\t * or\n\t * ~~~~~{.cpp}\n\t *   streambuf* oldsb = xxx.setOutput(ofile); \n\t * ~~~~~\n\t * @param strbuf is a streambuf pointer.\n\t * @return return the old streambuf, which can be used to redirect the old\n\t * streambuf.\n\t */\n\tstreambuf* setOutput(streambuf* strbuf);\n\n\n\t/**\n\t * Method:    setOutput\n\t * FullName:  public  argumatrix::Reasoner::setOutput\n\t * @see       streambuf* setOutput(streambuf* strbuf = std::cout.rdbuf());\n\t * @param     ostream & os\n\t * @return    streambuf*\n\t */\n\tstreambuf* setOutput(ostream& os = std::cout);\n\n\t/**\n\t * @brief Print an extension with the form of bitvector. Assume the bitvector \n\t * is [0, 1, 0, 1], the arguments corresponding to entry 1 will\n\t * be print. The member *m_output* will determine where to print.\n\t * @param bitvector& bv_ext : The bv_ext is a bitvector, which represents\n\t * an extension.\n\t * @return no return. \n\t * @see [setOutput]\n\t */\n\tvoid printLabSet(const bitvector& bv_ext);\n\n\t/**\n\t * @brief Print a set of arguments. The member *m_output* will determine\n\t * where to print.\n\t * @param const std::set<string>& labset\n\t * @return no return. \n\t * @see setOutput(streambuf* strbuf = std::cout.rdbuf());\n\t */\n\tvoid printLabSet(const std::set<string>& labset);\n\n\t/**\n\t * @brief Output all extensions given a specific semantics with an ostream.  \n\t * Each extension is a set of arguments which can \"survive the conflict\n\t * together\". Here, we return a string to represent all\n\t * extensions. For example, if there are two extensions, \n\t * [a,b] and [b, d], for some problem w.r.t. a given semantics, then we \n\t * return string \"[[a,b],[d,c]]\". If extensions is not existing, the string\n\t * \"[]\" will return.\n\t * @param ostream& os = std::cout, output the resluts into the ostream os. \n\t * @return a set of bitvector, i.e., set<bitvector>. \n\t */\n\tvoid printBvExts();\n\n\t/**\n\t * @brief Get the grounded extension\n\t * @return a set of arguments in bitvector form.\n\t */\n\tbitvector getGroundedExtension();\n\n\t\n\t/**\n\t * @brief Print the grounded extension\n\t * @return no return. \n\t */\n\tvoid printGroundedExt();\n\n\t/**\n\t * @brief Convert a set of argument (string) labels to an integer vector of {0,1,2},\n\t * All arguments in these set, the indices is 1; otherwise 2 (representing unknown)\n\t * @return no return. \n\t */\n\tvector<int> labelSet2IntVector(const std::set<string>& label_set);\n\npublic:\n\t/**\n\t * @brief Problem [EE-$\\sigma$]\n\t * Print all extensions\n\t * @param no argument\n\t * @return no return.\n\t */\n\tvirtual void task_EE() { cerr << \"Unimplemented!\" << endl; }\n\tvirtual void task_EX() { cerr << \"Unimplemented!\" << endl; }\n\n\t/**\n\t * @brief Problem [EC-$\\sigma$]\n\t * Given an $\\textit{AF}=\\left< \\mathcal{X}, \\mathcal{R}\\right>$ and \n\t * an argument $s \\in \\mathcal{X}$ (respectively, a set of arguments \n\t * $S\\subseteq \\mathcal{X}$), enumerate all sets $E\\subseteq \\mathcal{X}$\n\t * such that $E \\in \\mathcal{E}_\\sigma(AF)$ and $s\\in E$ (respectively,\n\t * $S \\subseteq E$).\n\t * @param set<string>, or a Boolean vector: a set of argument\n\t * @return no return.\n\t */\n\tvirtual void task_EC(const std::set<string>& argset)\n\t{ cerr << \"Unimplemented!\" << endl; }\n\n\t/**\n\t * @brief Problem [SC-$\\sigma$]\n\t * Given an $\\textit{AF}=\\left< \\mathcal{X}, \\mathcal{R}\\right>$ and an \n\t * argument $s \\in \\mathcal{X}$ (respectively, a set of arguments \n\t * $S\\subseteq \\mathcal{X}$), enumerate some set $E\\subseteq \\mathcal{X}$\n\t * such that $E \\in \\mathcal{E}_\\sigma(AF)$ and $s\\in E$ (respectively, \n\t * $S \\subseteq E$).\n\t * @param a set of arguments.\n\t * @return no return.\n\t */\n\tvirtual void task_SC(const std::set<string>& argset) \n\t{ cerr << \"Unimplemented!\" << endl; }\n\n\t/**\n\t * @brief Problem [SE-$\\sigma$]\n\t * Given an $\\textit{AF}=\\left< \\mathcal{X}, \\mathcal{R}\\right>$, enumerate\n\t * some set $E\\subseteq \\mathcal{X}$ that are in $\\mathcal{E}_\\sigma(AF)$.\n\t * @param a set of arguments.\n\t * @return no return.\n\t */\n\tvirtual void task_SE() { cerr << \"Unimplemented!\" << endl; }\n\n\t/**\n\t * @brief Problem [DE-$\\sigma$]\n\t * Given an $AF = \\left<X,R\\right>$ and a set of arguments $S \\subseteq X$. Decide whether S is\n\t * a \\sigma-extension of AF, i.e., S \\in E_\\sigma(AF).\n\t * @param a set of arguments.\n\t * @return true if argset is a \\sigma-extension; otherwise return false.\n\t * @note For this task, the *set<string>& argset* can be empty, which means\n\t * to decide whether the empty set is a $\\sigma$-extension of AF. This indicates\n\t * that the option -a is not necessary, then the default *set<string>& argset* \n\t * is empty.\n\t */\n\tvirtual void task_DE(const std::set<string>& argset)\n\t{ cerr << \"Unimplemented!\" << endl; }\n\n\t/**\n\t * @brief Problem [DN-$\\sigma$]\n\t * Given an $AF = \\left<X,R\\right>$ and a set of arguments $S \\subseteq X$. Decide whether\n\t * there exist a non-empty \\sigma-extension for AF\n\t * @return true if there exist a non-empty \\sigma-extension; otherwise return false.\n\t */\n\n\tvirtual void task_DN() { cerr << \"Unimplemented!\" << endl; }\n\n\t/**\n\t * @brief Problem [DC-$\\sigma$]\n\t * Given an $AF = \\left<X,R\\right>$ and an argument s \\in X (respectively, a set of \n\t * arguments $S \\subseteq X$). Decide whether s contained (respectively, S included)\n\t * in some E \\in E_\\sigma(AF) (i.e., credulously justified).\n\t */\n\tvirtual void task_DC(const std::set<string>& argset) \n\t{ cerr << \"Unimplemented!\" << endl; }\n\n\t/**\n\t * @brief Problem [DS-$\\sigma$]\n\t * Given an $AF = \\left<X,R\\right>$ and an argument s \\in X (respectively, a set of \n\t * arguments $S \\subseteq X$). Decide whether s contained (respectively, S included)\n\t * in each E \\in E_\\sigma(AF) (i.e., skeptically justified).\n\t */\n\tvirtual void task_DS(const std::set<string>& argset) \n\t{ cerr << \"Unimplemented!\" << endl; }\n\nprotected:\n\tbitmatrix m_BmAtkMtx;  /**< The bitmatrix of the Dung Abstract argumentation framework. We can \n\t* access all attackers of an argument. The attackers of the argument \n\t* with index i is m_BmAtkMtx[i].\n\t*/\n\n\tsize_type m_argNum; /**< The number of arguments */\n\n\n\tconst DungAF&\t  m_daf;  /**< Dung's abstract argumentation framework */\n\n\tset< bitvector > m_extensions;\n\n\tvector< std::string > m_argLabels; /**< Dung's abstract argumentation framework */\n\n\tstd::ostream m_output; /**< Where to output */\n};\n\nReasoner::Reasoner(const DungAF& daf, streambuf* osbuff /*= std::cout.rdbuf()*/):\n\tm_daf(daf), m_output(osbuff)\n{ \n\tm_argNum = m_daf.getNumberOfArguments();\n\tm_BmAtkMtx = m_daf.getAttackMatrix();\n\tm_argLabels = m_daf.getArgumentLabels();\n}\n\n__inline\nargumatrix::bitvector Reasoner::getAttacked(const bitvector& _bv)\n{\n\t//assert( _bv.size() == m_argNum );\n\n\treturn m_BmAtkMtx * _bv;\n}\n\n__inline\nargumatrix::bitvector Reasoner::characteristic(const bitvector& _bv)\n{\n\t// return ~(m_BmAtkMtx * (~(m_BmAtkMtx * _bv)));\n\treturn neutrality(neutrality(_bv));\n}\n\n__inline\nargumatrix::bitvector Reasoner::characteristic()\n{\n\treturn characteristic(bitvector::EmptySet(m_argNum));\n}\n\n__inline\nbool Reasoner::is_conflict_free(const bitvector& _bv)\n{\n\t// S is conflict-free iff $S \\intersect R^+(S) = \\emptyset$.\n\treturn !_bv.intersects( getAttacked(_bv) );\n}\n\n__inline\nbool Reasoner::is_conflict_free(const set<string>& argset)\n{\n\treturn is_conflict_free(m_daf.labelSet2bv(argset));\n}\n\n__inline\nbool Reasoner::is_acceptable(const bitvector& S, const bitvector& A)\n{\n\treturn A.is_subset_of( characteristic(S) );\n}\n\n__inline\nconst set<bitvector>& Reasoner::getBvExtensions()\n{\n\treturn m_extensions;\n}\n\n__inline\nbool Reasoner::is_self_attacking(size_type idx)\n{\n\t// assert(idx < m_argNum);\n\n\treturn m_BmAtkMtx[idx][idx];\n}\n\n__inline\nargumatrix::bitvector Reasoner::getSelfAttackingArguments()\n{\n\t//bitvector _bv(m_argNum, false);\n\t//for (size_type i=0; i<m_argNum; i++)\n\t//{\n\t//\t_bv[i] = m_BmAtkMtx[i][i];\n\t//}\n\n\t//return _bv;\n\n\treturn m_BmAtkMtx.diag();\n}\n\n__inline\nvoid Reasoner::printBvExts()\n{\n\tm_daf.outputBvSet(m_extensions, m_output);\n}\n\nvoid Reasoner::printLabSet(const bitvector& bv_ext)\n{\n\tbool first = true;\n\n\tm_output << LEFT_LIMITER;\n\tfor ( size_type i = bv_ext.find_first(); \n\t\ti != bitvector::npos; \n\t\ti = bv_ext.find_next(i) )\n\t{\n\t\tif(first){\n\t\t\tfirst = false;\n\t\t}else{\n\t\t\tm_output << DELIMITER; // \",\"\n\t\t}\n\t\tm_output << m_argLabels[i];\n\t}\n\tm_output << RIGHT_LIMITER;\n\n\t// m_daf.outputBv(bv_ext, m_output);\n}\n\nvoid Reasoner::printLabSet(const std::set<string>& labset)\n{\n\tbool first = true;\n\n\tm_output << LEFT_LIMITER;\n\tset<string>::iterator itr = labset.begin();\n\tfor ( ; itr != labset.end(); ++itr )\n\t{\n\t\tif(first){\n\t\t\tfirst = false;\n\t\t}else{\n\t\t\tm_output << DELIMITER; // \",\"\n\t\t}\n\t\tm_output << *itr;\n\t}\n\tm_output << RIGHT_LIMITER;\n}\n\n__inline\nstreambuf* Reasoner::setOutput(streambuf* strbuf)\n{\n\treturn m_output.rdbuf(strbuf);\n}\n\n__inline\nstreambuf* Reasoner::setOutput(ostream& os /*= std::cout*/)\n{\n\treturn m_output.rdbuf(os.rdbuf());\n}\n\nargumatrix::bitvector Reasoner::getGroundedExtension()\n{\n\tbitvector _bv = bitvector::EmptySet(m_argNum);\n\tbitvector _bv_next = characteristic(_bv);\n\n\twhile (_bv != _bv_next)\n\t{\n\t\t_bv = _bv_next;\n\t\t_bv_next = characteristic(_bv);\n\t}\n\n\treturn _bv_next;\n}\n\n\nvector<int> Reasoner::getGroundedIntVector()\n{\n\t// create m_argNum length vector with initial value 2 -- Unknown\n\tvector<int> vecii(m_argNum, 2);\n\n\tbitvector gr_ext = bitvector::EmptySet(m_argNum);\n\tbitvector gr_out;\n\tbitvector _bv_last;\n\tdo {\n\t\t_bv_last = gr_ext;\n\t\t//gr_out = (m_BmAtkMtx * _bv_last); // S =  R^+(X)\n\t\t//gr_ext = ~(m_BmAtkMtx * (~gr_out)); // G = ~R^+(~S)\n\t\tgr_out = getAttacked( _bv_last ); // S =  R^+(X)\n\t\tgr_ext = neutrality( ~gr_out ); // G = ~R^+(~S)\n\t} while (gr_ext != _bv_last);\n\n\t// cout << \"gr_ext\" << gr_ext << endl;\n\n\tfor(size_type i=0; i<m_argNum; ++i)\n\t{\n\t\tif( gr_ext[i] ) { vecii[i] = 1; }\n\t\telse if ( gr_out[i] ) { vecii[i] = 0; }\n\t}\n\n\treturn vecii;\n}\n\nvector<int> Reasoner::labelSet2IntVector(const std::set<string>& label_set)\n{\n\tvector<int> vecI( m_argNum, 2 );\n\tset<string>::iterator _ls_itr;\n\tfor (_ls_itr = label_set.begin(); _ls_itr != label_set.end(); ++_ls_itr)\n\t{\n\t\tvecI[ m_daf.getArgumentIdx( *_ls_itr ) ] = 1;\n\t}\n\n\treturn vecI;\n}\n\n__inline\nvoid Reasoner::printGroundedExt()\n{\n\tm_output << LEFT_LIMITER;  // [\n\tprintLabSet( getGroundedExtension() );\n\tm_output << RIGHT_LIMITER; // ]\n}\n\n__inline\nargumatrix::bitvector Reasoner::neutrality(const bitvector& _bv)\n{\n\treturn ~getAttacked(_bv);\n}\n\n__inline\nbool Reasoner::is_admissible(const bitvector& _bv)\n{\n\t// $S$ is an admissible extension iff $S \\subseteq F(S) \\cap N(S)$.\n\tbitvector neu_s = neutrality(_bv);\n\tbitvector f_s = neutrality( neu_s );\n\tf_s &= neu_s;\n\n\treturn _bv.is_subset_of(f_s);\n}\n\n__inline\nbool Reasoner::is_complete(const bitvector& _bv)\n{\n\t// // $S$ is a complete extension iff $S$ is conflict-free and $S == F(S)$.\n\t// if ( !is_conflict_free(_bv) )\n\t//\t  return false;\t\n\t// bitvector neu_s = neutrality(_bv);\n\t// bitvector f_s = neutrality( neu_s );\n\t// return _bv == f_s;\n\t\n\t// This way may be more efficient.\n\treturn is_conflict_free(_bv) && (_bv == characteristic(_bv));\n\n\t//// $S$ is a complete extension iff $S == F(S) \\cap N(S)$.\n\t//bitvector neu_s = neutrality(_bv);\n\t//bitvector f_s = neutrality( neu_s );\n\t//f_s &= neu_s;\n\n\t//return _bv == f_s;\n}\n\n__inline\nbool Reasoner::is_stable(const bitvector& _bv)\n{\n\t// $S$ is a stable extension iff $S == N(S)$.\n\tbitvector neu_s = neutrality(_bv);\n\n\treturn _bv == neu_s;\n}\n\n__inline\nbool Reasoner::is_grounded(const bitvector& _bv)\n{\n\tbitvector gr_ext = getGroundedExtension();\n\n\treturn (_bv == gr_ext);\n}\n\n} // namespace argumatrix\n\n\n\n#endif  //DUNG_REASONER_HPP", "meta": {"hexsha": "d488cc6ac0c8e5ea50f45a15e30749cc959b297c", "size": 17442, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dung_theory/Reasoner.hpp", "max_stars_repo_name": "xixicat/argmat-clpb", "max_stars_repo_head_hexsha": "eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-01-09T21:48:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-28T05:52:14.000Z", "max_issues_repo_path": "dung_theory/Reasoner.hpp", "max_issues_repo_name": "xixicat/argmat-clpb", "max_issues_repo_head_hexsha": "eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dung_theory/Reasoner.hpp", "max_forks_repo_name": "xixicat/argmat-clpb", "max_forks_repo_head_hexsha": "eb76cb42ff7e9e2fd8d82a40778d1ac6343cea58", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8297520661, "max_line_length": 100, "alphanum_fraction": 0.6697626419, "num_tokens": 5117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.435445925712509}}
{"text": "#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n\n#include <arlib/esx.hpp>\n#include <arlib/graph_utils.hpp>\n#include <arlib/multi_predecessor_map.hpp>\n#include <arlib/onepass_plus.hpp>\n#include <arlib/path.hpp>\n#include <arlib/penalty.hpp>\n#include <arlib/routing_kernels/types.hpp>\n\n#include <iostream>\n#include <string>\n#include <string_view>\n#include <vector>\n\n// Create type-aliases for the Graph type\nusing Graph = boost::adjacency_list<boost::vecS, boost::vecS,\n                                    boost::bidirectionalS, boost::no_property,\n                                    boost::property<boost::edge_weight_t, int>>;\nusing Vertex = typename boost::graph_traits<Graph>::vertex_descriptor;\nusing Edge = typename boost::graph_traits<Graph>::edge_descriptor;\n\n/// Run the alternative routing algorithm named @p name.\ntemplate <typename WeightMap, typename MultiPredecessorMap>\nvoid run_alt_routing(std::string_view name, Graph const &G,\n                     WeightMap const &weight, MultiPredecessorMap &predecessors,\n                     Vertex s, Vertex t, int k, double theta) {\n  using arlib::routing_kernels;\n  if (name == \"onepass_plus\") {\n    arlib::onepass_plus(G, weight, predecessors, s, t, k, theta);\n  } else if (name == \"esx\") {\n    arlib::esx(G, weight, predecessors, s, t, k, theta,\n               routing_kernels::astar);\n  } else if (name == \"penalty\") {\n    double p = 0.1, r = 0.1;\n    int max_nb_updates = 10, max_nb_steps = 100000;\n    arlib::penalty(G, weight, predecessors, s, t, k, theta, p, r,\n                   max_nb_updates, max_nb_steps,\n                   routing_kernels::bidirectional_dijkstra);\n  } else {\n    std::cout << \"Unknown algorithm '\" << name << \"'. Exiting...\\n\";\n    std::exit(1);\n  }\n}\n\n/// Define a convenient function to compute the alternative routes and return\n/// them as a view.\nstd::vector<arlib::Path<Graph>> get_alternative_routes(std::string_view alg,\n                                                       Graph const &G, Vertex s,\n                                                       Vertex t) {\n  // Make output MultiPredecessorMap\n  auto predecessors = arlib::multi_predecessor_map<Vertex>{};\n\n  int k = 3;                                       // Nb alternative routes\n  double theta = 0.5;                              // Overlapping threshold\n  auto weight = boost::get(boost::edge_weight, G); // Get Edge WeightMap\n\n  run_alt_routing(alg, G, weight, predecessors, s, t, k, theta);\n  auto alt_routes = arlib::to_paths(G, predecessors, weight, s, t);\n  return alt_routes;\n}\n\nvoid print_path(arlib::Path<Graph> const &path,\n                std::vector<std::string> const &name) {\n  using namespace boost;\n\n  for (auto [v_it, v_end] = vertices(path); v_it != v_end; ++v_it) {\n    for (auto [e_it, e_end] = out_edges(*v_it, path); e_it != e_end; ++e_it) {\n      std::cout << name[source(*e_it, path)] << \" -- \"\n                << name[target(*e_it, path)] << \"\\n\";\n    }\n  }\n}\n\nint main() {\n  // Make convenient labels for the vertices\n  enum { S, N1, N2, N3, N4, N5, T };\n  const long unsigned num_vertices = T;\n  const auto name =\n      std::vector<std::string>{\"s\", \"n1\", \"n2\", \"n3\", \"n4\", \"n5\", \"t\"};\n\n  // Writing out the edges in the graph\n  const auto edges = std::vector<std::pair<int, int>>{\n      {S, N1},  {N1, S},  {S, N2},  {N2, S},  {S, N3},  {N3, S},\n      {N1, T},  {T, N1},  {N3, N1}, {N1, N3}, {N3, N5}, {N5, N3},\n      {N3, N2}, {N2, N3}, {N3, N4}, {N4, N3}, {N2, N4}, {N4, N2},\n      {N5, T},  {T, N5},  {N5, N4}, {N4, N5}, {N4, T},  {T, N4}};\n\n  const auto weights = std::vector<int>{6, 6, 4, 4, 3, 3, 6, 6, 2, 2, 3, 3,\n                                        3, 3, 5, 5, 5, 5, 2, 2, 1, 1, 2, 2};\n  auto G = Graph{edges.begin(), edges.end(), weights.begin(), num_vertices};\n\n  //=-------------------------------------------------------------------------=\n\n  // OnePass+\n  auto res_opplus = get_alternative_routes(\"onepass_plus\", G, S, T);\n  // ESX\n  auto res_esx = get_alternative_routes(\"esx\", G, S, T);\n  // Penalty\n  auto res_penalty = get_alternative_routes(\"penalty\", G, S, T);\n\n  std::cout << \"OnePass+ solutions...\\n\";\n  for (auto const &route : res_opplus) {\n    print_path(route, name);\n    std::cout << \"--------\\n\";\n  }\n\n  std::cout << \"ESX solutions...\\n\";\n  for (auto const &route : res_esx) {\n    print_path(route, name);\n    std::cout << \"--------\\n\";\n  }\n\n  std::cout << \"Penalty solutions...\\n\";\n  for (auto const &route : res_penalty) {\n    print_path(route, name);\n    std::cout << \"--------\\n\";\n  }\n\n  return 0;\n}", "meta": {"hexsha": "579149f8eaad12aef9206cf0e501b1e3759cd465", "size": 4556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/src/softwarex_example.cpp", "max_stars_repo_name": "ashishkashinath/arlib", "max_stars_repo_head_hexsha": "891aa8603a6e07a16aec5700e7129a0d14a40b84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-10-29T17:17:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-01T02:09:37.000Z", "max_issues_repo_path": "examples/src/softwarex_example.cpp", "max_issues_repo_name": "ashishkashinath/arlib", "max_issues_repo_head_hexsha": "891aa8603a6e07a16aec5700e7129a0d14a40b84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-05T07:27:35.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-05T07:27:35.000Z", "max_forks_repo_path": "examples/src/softwarex_example.cpp", "max_forks_repo_name": "ashishkashinath/arlib", "max_forks_repo_head_hexsha": "891aa8603a6e07a16aec5700e7129a0d14a40b84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-07-20T09:31:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T12:06:49.000Z", "avg_line_length": 37.3442622951, "max_line_length": 80, "alphanum_fraction": 0.571334504, "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370423, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.43543041955427986}}
{"text": "#pragma once\n#ifndef VECTORMATH_NEW_H\n#define VECTORMATH_NEW_H\n\n#include <vector>\n#include <memory>\n\n#include <Eigen/Core>\n\n#include <data/Spin_System.hpp>\n#include <engine/Vectormath_Defines.hpp>\n\nnamespace Engine\n{\n    namespace Vectormath\n    {\n        /////////////////////////////////////////////////////////////////\n        //////// Single Vector Math\n\n        // Rotate a vector around an axis by a certain degree (Implemented with Rodrigue's formula)\n        void rotate(const Vector3 & v, const Vector3 & axis, const scalar & angle, Vector3 & v_out);\n        void rotate( const vectorfield & v, const vectorfield & axis, const scalarfield & angle, \n                     vectorfield & v_out );\n        \n        // Decompose a vector into numbers of translations in a basis\n        Vector3 decompose(const Vector3 & v, const std::vector<Vector3> & basis);\n\n        /////////////////////////////////////////////////////////////////\n        //////// Translating across the lattice\n\n        inline int idx_from_translations(const intfield & n_cells, const int n_cell_atoms, const std::array<int, 3> & translations)\n        {\n            int Na = n_cells[0];\n            int Nb = n_cells[1];\n            int Nc = n_cells[2];\n            int N = n_cell_atoms;\n\n            int da = translations[0];\n            int db = translations[1];\n            int dc = translations[2];\n\n            return da*N + db*N*Na + dc*N*Na*Nb;\n        }\n\n        #ifndef USE_CUDA\n\n        inline int idx_from_translations(const intfield & n_cells, const int n_cell_atoms, const std::array<int, 3> & translations_i, const std::array<int, 3> translations)\n        {\n            int Na = n_cells[0];\n            int Nb = n_cells[1];\n            int Nc = n_cells[2];\n            int N = n_cell_atoms;\n\n            int da = translations_i[0] + translations[0];\n            int db = translations_i[1] + translations[1];\n            int dc = translations_i[2] + translations[2];\n\n            if (translations[0] < 0)\n                da += N*Na;\n            if (translations[1] < 0)\n                db += N*Na*Nb;\n            if (translations[2] < 0)\n                dc += N*Na*Nb*Nc;\n\n            int idx = (da%Na)*N + (db%Nb)*N*Na + (dc%Nc)*N*Na*Nb;\n\n            return idx;\n        }\n\n        inline bool boundary_conditions_fulfilled(const intfield & n_cells, const intfield & boundary_conditions, const std::array<int, 3> & translations_i, const std::array<int, 3> & translations_j)\n        {\n            int da = translations_i[0] + translations_j[0];\n            int db = translations_i[1] + translations_j[1];\n            int dc = translations_i[2] + translations_j[2];\n            return ((boundary_conditions[0] || (0 <= da && da < n_cells[0])) &&\n                    (boundary_conditions[1] || (0 <= db && db < n_cells[1])) &&\n                    (boundary_conditions[2] || (0 <= dc && dc < n_cells[2])));\n        }\n\n        #endif\n        #ifdef USE_CUDA\n    \n        inline int idx_from_translations(const intfield & n_cells, const int n_cell_atoms, const std::array<int, 3> & translations_i, const int translations[3])\n        {\n            int Na = n_cells[0];\n            int Nb = n_cells[1];\n            int Nc = n_cells[2];\n            int N = n_cell_atoms;\n    \n            int da = translations_i[0] + translations[0];\n            int db = translations_i[1] + translations[1];\n            int dc = translations_i[2] + translations[2];\n    \n            if (translations[0] < 0)\n                da += N*Na;\n            if (translations[1] < 0)\n                db += N*Na*Nb;\n            if (translations[2] < 0)\n                dc += N*Na*Nb*Nc;\n    \n            int idx = (da%Na)*N + (db%Nb)*N*Na + (dc%Nc)*N*Na*Nb;\n    \n            return idx;\n        }\n\n        inline bool boundary_conditions_fulfilled(const intfield & n_cells, const intfield & boundary_conditions, const std::array<int, 3> & translations_i, const int translations_j[3])\n        {\n            int da = translations_i[0] + translations_j[0];\n            int db = translations_i[1] + translations_j[1];\n            int dc = translations_i[2] + translations_j[2];\n            return ((boundary_conditions[0] || (0 <= da && da < n_cells[0])) &&\n                    (boundary_conditions[1] || (0 <= db && db < n_cells[1])) &&\n                    (boundary_conditions[2] || (0 <= dc && dc < n_cells[2])));\n        }\n\n        __inline__ __device__ bool cu_check_atom_type(int atom_type)\n        {\n            #ifdef SPIRIT_ENABLE_DEFECTS\n                // If defects are enabled we check for\n                //\t\tvacancies (type < 0)\n                if (atom_type >= 0) return true;\n                else return false;\n            #else\n                // Else we just return true\n                return true;\n            #endif\n        }\n\n        __inline__ __device__ bool cu_check_atom_type(int atom_type, int reference_type)\n        {\n            #ifdef SPIRIT_ENABLE_DEFECTS\n                // If defects are enabled we do a check if\n                //\t\tatom types match.\n                if (atom_type == reference_type) return true;\n                else return false;\n            #else\n                // Else we just return true\n                return true;\n            #endif\n        }\n\n        // Calculates, for a spin i, a pair spin's index j.\n        // This function takes into account boundary conditions and atom types and returns `-1` if any condition is not met.\n        __inline__ __device__ int cu_idx_from_pair(int ispin, const int * boundary_conditions, const int * n_cells, int N, const int * atom_types, const Pair & pair, bool invert=false)\n        {\n            // Invalid index if atom type of spin i is not correct\n            if ( pair.i != ispin%N || !cu_check_atom_type(atom_types[ispin]) )\n                return -1;\n\n            // Number of cells\n            auto& Na = n_cells[0];\n            auto& Nb = n_cells[1];\n            auto& Nc = n_cells[2];\n\n            // Invalid index if translations reach out over the lattice bounds\n            if (std::abs(pair.translations[0]) > Na ||\n                std::abs(pair.translations[1]) > Nb ||\n                std::abs(pair.translations[2]) > Nc )\n                return -1;\n\n            // Translations (cell) of spin i\n            int nic = ispin / (N*Na*Nb);\n            int nib = (ispin - nic*N*Na*Nb) / (N*Na);\n            int nia = ispin - nic*N*Na*Nb - nib*N*Na;\n\n            // Translations (cell) of spin j (possibly outside of non-periodical domain)\n            int pm = 1;\n            if (invert)\n                pm = -1;\n            int nja = nia + pm*pair.translations[0];\n            int njb = nib + pm*pair.translations[1];\n            int njc = nic + pm*pair.translations[2];\n\n            // Check boundary conditions: a\n            if ( boundary_conditions[0] || (0 <= nja && nja < Na) )\n            {\n                // Boundary conditions fulfilled\n                // Find the translations of spin j within the non-periodical domain\n                if (nja < 0)\n                    nja += Na;\n                // Calculate the correct index\n                if (nja >= Na)\n                    nja -= Na;\n            }\n            else\n            {\n                // Boundary conditions not fulfilled\n                return -1;\n            }\n\n            // Check boundary conditions: b\n            if ( boundary_conditions[1] || (0 <= njb && njb < Nb) )\n            {\n                // Boundary conditions fulfilled\n                // Find the translations of spin j within the non-periodical domain\n                if (njb < 0)\n                    njb += Nb;\n                // Calculate the correct index\n                if (njb >= Nb)\n                    njb -= Nb;\n            }\n            else\n            {\n                // Boundary conditions not fulfilled\n                return -1;\n            }\n\n            // Check boundary conditions: c\n            if ( boundary_conditions[2] || (0 <= njc && njc < Nc) )\n            {\n                // Boundary conditions fulfilled\n                // Find the translations of spin j within the non-periodical domain\n                if (njc < 0)\n                    njc += Nc;\n                // Calculate the correct index\n                if (njc >= Nc)\n                    njc -= Nc;\n            }\n            else\n            {\n                // Boundary conditions not fulfilled\n                return -1;\n            }\n\n            // Calculate the index of spin j according to it's translations\n            int jspin = pair.j + (nja)*N + (njb)*N*Na + (njc)*N*Na*Nb;\n\n            // Invalid index if atom type of spin j is not correct\n            if ( pair.j != jspin%N || !cu_check_atom_type(atom_types[jspin]) )\n                return -1;\n            \n            // Return a valid index\n            return jspin;\n        }\n\n        #endif\n\n        inline std::array<int, 3> translations_from_idx(const intfield & n_cells, const int n_cell_atoms, int idx)\n        {\n            std::array<int, 3> ret;\n            int Na = n_cells[0];\n            int Nb = n_cells[1];\n            int Nc = n_cells[2];\n            int N = n_cell_atoms;\n\n            ret[2] = idx / (N*Na*Nb);\n            ret[1] = (idx - ret[2] * N*Na*Nb) / (N*Na);\n            ret[0] = (idx - ret[2] * N*Na*Nb - ret[1] * N*Na) / N;\n            return ret;\n        }\n\n        // Check atom types\n        inline bool check_atom_type(int atom_type)\n        {\n            #ifdef SPIRIT_ENABLE_DEFECTS\n                // If defects are enabled we check for\n                //\t\tvacancies (type < 0)\n                if (atom_type >= 0) return true;\n                else return false;\n            #else\n                // Else we just return true\n                return true;\n            #endif\n        }\n        inline bool check_atom_type(int atom_type, int reference_type)\n        {\n            #ifdef SPIRIT_ENABLE_DEFECTS\n                // If defects are enabled we do a check if\n                //\t\tatom types match.\n                if (atom_type == reference_type) return true;\n                else return false;\n            #else\n                // Else we just return true\n                return true;\n            #endif\n        }\n\n        // Calculates, for a spin i, a pair spin's index j.\n        // This function takes into account boundary conditions and atom types and returns `-1` if any condition is not met.\n        inline int idx_from_pair(int ispin, const intfield & boundary_conditions, const intfield & n_cells, int N, const intfield & atom_types, const Pair & pair, bool invert=false)\n        {\n            // Invalid index if atom type of spin i is not correct\n            if ( pair.i != ispin%N || !check_atom_type(atom_types[ispin]) )\n                return -1;\n\n            // Number of cells\n            auto& Na = n_cells[0];\n            auto& Nb = n_cells[1];\n            auto& Nc = n_cells[2];\n\n            // Invalid index if translations reach out over the lattice bounds\n            if (std::abs(pair.translations[0]) > Na ||\n                std::abs(pair.translations[1]) > Nb ||\n                std::abs(pair.translations[2]) > Nc )\n                return -1;\n\n            // Translations (cell) of spin i\n            int nic = ispin / (N*Na*Nb);\n            int nib = (ispin - nic*N*Na*Nb) / (N*Na);\n            int nia = (ispin - nic*N*Na*Nb - nib*N*Na) / N;\n\n            int pm = 1;\n            if (invert)\n                pm = -1;\n            // Translations (cell) of spin j (possibly outside of non-periodical domain)\n            int nja = nia + pm*pair.translations[0];\n            int njb = nib + pm*pair.translations[1];\n            int njc = nic + pm*pair.translations[2];\n\n            // Check boundary conditions: a\n            if ( boundary_conditions[0] || (0 <= nja && nja < Na) )\n            {\n                // Boundary conditions fulfilled\n                // Find the translations of spin j within the non-periodical domain\n                if (nja < 0)\n                    nja += Na;\n                // Calculate the correct index\n                if (nja >= Na)\n                    nja -= Na;\n            }\n            else\n            {\n                // Boundary conditions not fulfilled\n                return -1;\n            }\n\n            // Check boundary conditions: b\n            if ( boundary_conditions[1] || (0 <= njb && njb < Nb) )\n            {\n                // Boundary conditions fulfilled\n                // Find the translations of spin j within the non-periodical domain\n                if (njb < 0)\n                    njb += Nb;\n                // Calculate the correct index\n                if (njb >= Nb)\n                    njb -= Nb;\n            }\n            else\n            {\n                // Boundary conditions not fulfilled\n                return -1;\n            }\n\n            // Check boundary conditions: c\n            if ( boundary_conditions[2] || (0 <= njc && njc < Nc) )\n            {\n                // Boundary conditions fulfilled\n                // Find the translations of spin j within the non-periodical domain\n                if (njc < 0)\n                    njc += Nc;\n                // Calculate the correct index\n                if (njc >= Nc)\n                    njc -= Nc;\n            }\n            else\n            {\n                // Boundary conditions not fulfilled\n                return -1;\n            }\n\n            // Calculate the index of spin j according to it's translations\n            int jspin = pair.j + (nja)*N + (njb)*N*Na + (njc)*N*Na*Nb;\n\n            // Invalid index if atom type of spin j is not correct\n            if ( !check_atom_type(atom_types[jspin]) )\n                return -1;\n            \n            // Return a valid index\n            return jspin;\n        }\n\n\n        /////////////////////////////////////////////////////////////////\n        //////// Vectorfield Math - special stuff\n\n        // Build an array of spin positions and atom types. TODO: find a better name for this function\n        void Build_Spins(vectorfield & positions, intfield & atom_types,\n                         const std::vector<Vector3> & cell_atoms, const intfield & cell_atom_types,\n                         const std::vector<Vector3> & translation_vectors, const intfield & n_cells);\n        // Calculate the mean of a vectorfield\n        std::array<scalar, 3> Magnetization(const vectorfield & vf);\n        // Calculate the topological charge inside a vectorfield\n        scalar TopologicalCharge(const vectorfield & vf, const vectorfield & vf_pos, const std::vector<std::array<int, 3>> & triangulation);\n\n        // Utility function for the SIB Solver - maybe create a MathUtil namespace?\n        void transform(const vectorfield & spins, const vectorfield & force, vectorfield & out);\n\n        void get_random_vector(std::uniform_real_distribution<scalar> & distribution, std::mt19937 & prng, Vector3 & vec);\n        void get_random_vectorfield(std::mt19937 & prng, vectorfield & xi);\n        void get_random_vector_unitsphere(std::uniform_real_distribution<scalar> & distribution, std::mt19937 & prng, Vector3 & vec);\n        void get_random_vectorfield_unitsphere(std::mt19937 & prng, vectorfield & xi);\n\n        // Calculate a gradient scalar distribution according to a starting value, direction and inclination\n        void get_gradient_distribution(const Data::Geometry & geometry, Vector3 gradient_direction, scalar gradient_start, scalar gradient_inclination, scalarfield & distribution, scalar range_min, scalar range_max);\n\n        // Calculate the spatial gradient of a vectorfield in a certain direction.\n        //      This requires to know the underlying geometry, as well as the boundary conditions.\n        void directional_gradient(const vectorfield & vf, const Data::Geometry & geometry, const intfield & boundary_conditions, const Vector3 & direction, vectorfield & gradient);\n\n        /////////////////////////////////////////////////////////////////\n        //////// Vectormath-like operations\n\n        // sets sf := s\n        // sf is a scalarfield\n        // s is a scalar\n        void fill(scalarfield & sf, scalar s);\n        \n        // TODO: Add the test\n        void fill(scalarfield & sf, scalar s, const intfield & mask);\n\n        // Scale a scalarfield by a given value\n        void scale(scalarfield & sf, scalar s);\n\n        // Add a scalar to all entries of a scalarfield\n        void add(scalarfield & sf, scalar s);\n\n        // Sum over a scalarfield\n        scalar sum(const scalarfield & sf);\n\n        // Calculate the mean of a scalarfield\n        scalar mean(const scalarfield & sf);\n\n        // Cut off all values to remain in a certain range\n        void set_range(scalarfield & sf, scalar sf_min, scalar sf_max);\n\n        // sets vf := v\n        // vf is a vectorfield\n        // v is a vector\n        void fill(vectorfield & vf, const Vector3 & v);\n        void fill(vectorfield & vf, const Vector3 & v, const intfield & mask);\n        \n        // Normalize the vectors of a vectorfield\n        void normalize_vectors(vectorfield & vf);\n        \n        // Get the norm of a vectorfield \n        void norm( const vectorfield & vf, scalarfield & norm );\n\n        // Pair of Minimum and Maximum of any component of any vector of a vectorfield\n        std::pair<scalar, scalar> minmax_component(const vectorfield & v1);\n\n        // Maximum absolute component of a vectorfield\n        scalar max_abs_component(const vectorfield & vf);\n\n        // Scale a vectorfield by a given value\n        void scale(vectorfield & vf, const scalar & sc);\n\n        // Sum over a vectorfield\n        Vector3 sum(const vectorfield & vf);\n\n        // Calculate the mean of a vectorfield\n        Vector3 mean(const vectorfield & vf);\n\n        // divide two scalarfields\n        void divide( const scalarfield & numerator, const scalarfield & denominator, scalarfield & out );\n\n        // TODO: move this function to manifold??\n        // computes the inner product of two vectorfields v1 and v2\n        scalar dot(const vectorfield & vf1, const vectorfield & vf2);\n\n        // computes the inner products of vectors in v1 and v2\n        // v1 and v2 are vectorfields\n        void dot(const vectorfield & vf1, const vectorfield & vf2, scalarfield & out);\n        \n        // TODO: find a more appropriate name\n        // computes the product of scalars in sf1 and sf2\n        // sf1 and sf2 are vectorfields\n        void dot(const scalarfield & sf1, const scalarfield & sf2, scalarfield & out);\n\n        // computes the vector (cross) products of vectors in v1 and v2\n        // v1 and v2 are vector fields\n        void cross(const vectorfield & vf1, const vectorfield & vf2, vectorfield & out);\n        \n        // out[i] += c*a\n        void add_c_a(const scalar & c, const Vector3 & a, vectorfield & out);\n        // out[i] += c*a[i]\n\t\tvoid add_c_a(const scalar & c, const vectorfield & vf, vectorfield & out);\n\t\tvoid add_c_a(const scalar & c, const vectorfield & vf, vectorfield & out, const intfield & mask);\n        // out[i] += c[i]*a[i]\n        void add_c_a( const scalarfield & c, const vectorfield & vf, vectorfield & out );\n\n        // out[i] = c*a\n        void set_c_a(const scalar & c, const Vector3 & a, vectorfield & out);\n        void set_c_a(const scalar & c, const Vector3 & a, vectorfield & out, const intfield & mask);\n        // out[i] = c*a[i]\n        void set_c_a(const scalar & c, const vectorfield & vf, vectorfield & out);\n        void set_c_a(const scalar & c, const vectorfield & vf, vectorfield & out, const intfield & mask);\n        // out[i] = c[i]*a[i]\n        void set_c_a( const scalarfield & sf, const vectorfield & vf, vectorfield & out );\n\n        // out[i] += c * a*b[i]\n        void add_c_dot(const scalar & c, const Vector3 & a, const vectorfield & b, scalarfield & out);\n        // out[i] += c * a[i]*b[i]\n        void add_c_dot(const scalar & c, const vectorfield & a, const vectorfield & b, scalarfield & out);\n        \n        // out[i] = c * a*b[i]\n        void set_c_dot(const scalar & c, const Vector3 & a, const vectorfield & b, scalarfield & out);\n        // out[i] = c * a[i]*b[i]\n        void set_c_dot(const scalar & c, const vectorfield & a, const vectorfield & b, scalarfield & out);\n\n        // out[i] += c * a x b[i]\n        void add_c_cross(const scalar & c, const Vector3 & a, const vectorfield & b, vectorfield & out);\n        // out[i] += c * a[i] x b[i]\n        void add_c_cross(const scalar & c, const vectorfield & a, const vectorfield & b, vectorfield & out);\n        // out[i] += c[i] * a[i] x b[i]\n        void add_c_cross(const scalarfield & c, const vectorfield & a, const vectorfield & b, vectorfield & out);\n        \n        // out[i] = c * a x b[i]\n        void set_c_cross(const scalar & c, const Vector3 & a, const vectorfield & b, vectorfield & out);\n        // out[i] = c * a[i] x b[i]\n        void set_c_cross(const scalar & c, const vectorfield & a, const vectorfield & b, vectorfield & out);\n\n    }\n}\n\n#endif", "meta": {"hexsha": "cb0c6f978c54b3175ddf6917145383c8266a94c2", "size": 21010, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/include/engine/Vectormath.hpp", "max_stars_repo_name": "SpiritSuperUser/spirit", "max_stars_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T13:54:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T09:10:27.000Z", "max_issues_repo_path": "core/include/engine/Vectormath.hpp", "max_issues_repo_name": "SpiritSuperUser/spirit", "max_issues_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/include/engine/Vectormath.hpp", "max_forks_repo_name": "SpiritSuperUser/spirit", "max_forks_repo_head_hexsha": "fbe69c2a9b7a73e8f47d302c619303aea2a22ace", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7961165049, "max_line_length": 216, "alphanum_fraction": 0.5325559257, "num_tokens": 4933, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4354304139822485}}
{"text": "#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <complex>\n#include <cmath>\n\nusing namespace boost::numeric::ublas ;\n\ntemplate<class E1, class E2>\nstruct component_prod{\n\ttypedef E1\t\t\targument_type1 ;\n\ttypedef E2\t\t\targument_type2 ;\n\ttypedef E1\t\t\tresult_type ;\n\t\n\tstatic\n\tresult_type apply(argument_type1 t1, argument_type2 t2) {\n\t\treturn element_prod( t1, t2 ) ;\n\t}\n};\n\ntemplate<class E1, class E2>\ntypename vector_binary_traits<E1, E2, component_prod<typename E1::value_type,\n\ttypename E2::value_type> >::result_type\nlayer_prod( const vector_expression<E1>& e1, const vector_expression<E2>& e2 ) {\n    typedef typename vector_binary_traits<E1, E2, component_prod<\n    \ttypename E1::value_type, typename E2::value_type> >::expression_type expression_type ;\n    return expression_type( e1(), e2() ) ;\n}\n\ntemplate<class E>\nstruct matrix_inverse {\n\ttypedef E\t\targument_type ;\n\ttypedef argument_type\tresult_type ;\n\ttypedef typename E::value_type\tvalue_type ;\n\t\n\tstatic\n\tresult_type apply(argument_type t) {\n\t\targument_type tmp(t) ;\n\t\tvalue_type d = t(0,0)*t(1,1) - t(0,1)*t(1,0) ;\n\t\ttmp(0,0) = t(1,1) / d ;\n\t\ttmp(1,0) = -t(1,0) / d ;\n\t\ttmp(0,1) = -t(0,1) / d ;\n\t\ttmp(1,1) = t(0,0) / d ;\n\t\treturn tmp ;\n\t}\n};\n\ntemplate<class E>\ntypename vector_unary_traits<E, matrix_inverse<typename E::value_type> >::result_type\ninverse( const vector_expression<E>& e ) {\n\ttypedef typename vector_unary_traits<E, matrix_inverse<typename E::value_type> >::expression_type\n\t\texpression_type ;\n\treturn expression_type( e() ) ;\n}\n\n/** ========== VECTOR UNARY SPECIAL ========== **/\ntemplate<class E, std::size_t I1, std::size_t I2>\nstruct nested_index {\n\ttypedef E\t\t\targument_type ;\n\ttypedef typename E::value_type\t\tresult_type ;\n\t\n\tstatic\n\tresult_type apply(argument_type t) {\n\t\treturn t(I1,I2) ;\n\t}\n};\n\ntemplate<class E1, class E2>\nstruct nested_plus_assign {\n\ttypedef E1\t\targument_type1 ;\n\ttypedef E2\t\targument_type2 ;\n\ttypedef argument_type1\tresult_type ;\n\ttypedef typename E1::size_type\tsize_type ;\n\n\tstatic\n\tresult_type apply(argument_type1 t1, argument_type2 t2) {\n\t\tsize_type size( t2.size() ) ;\n\t\tfor(size_type i=0; i<size; ++i)\n\t\t\tt1 += t2(i) ;\n\t\treturn t1 ;\n\t}\n\n};\n\ntemplate<class E>\nstruct component_determinant{\n\ttypedef E\t\t\targument_type ;\n\ttypedef typename E::value_type\t\t\tresult_type ;\n\t\n\tstatic\n\tresult_type apply(argument_type t) {\n\t\treturn t(0,0)*t(1,1) - t(0,1)*t(1,0) ;\n\t}\n};\n\ntemplate<class E, class F>\nclass vector_unary_special :\n\tpublic vector_expression<vector_unary_special<E,F> >\n{\t\n\tpublic:\n\t\ttypedef F\tfunctor_type ;\n\t\ttypedef E\texpression_type ;\n\t\ttypedef typename E::size_type\tsize_type ;\n\t\ttypedef typename E::value_type::value_type\tvalue_type ;\n\t\ttypedef value_type\tconst_reference ;\n\t\ttypedef typename E::iterator\t\titerator ;\n\t\ttypedef typename E::const_iterator\t\t\tconst_iterator ;\n\t\n\t\texplicit\n\t\tvector_unary_special( const expression_type& e ) : __e(e) {}\n\t\t\t\t\n\t\tconst expression_type& expression() const {\n\t\t\treturn __e ;\n\t\t}\n\t\t\n\t\tconst size_type size() const {\n\t\t\treturn expression().size() ;\n\t\t}\n\t\t\n\t\tconst_reference operator() (size_type i) const {\n\t\t\treturn functor_type::apply( __e(i) ) ;\n\t\t}\n\t\t\n\t\tconst_iterator begin() const {\n\t\t\treturn expression().begin() ;\n\t\t}\n\t\t\n\t\tconst_iterator end() const {\n\t\t\treturn expression().end() ;\n\t\t}\n\t\n\tprivate:\n\t\texpression_type\t__e ;\n};\n\ntemplate<class E, class F>\nstruct vector_unary_special_traits {\n\ttypedef vector_unary_special<E,F>\tresult_type ;\n\ttypedef result_type\t\texpression_type ;\n};\n\ntemplate<class E>\ntypename vector_unary_special_traits<E,\tcomponent_determinant<typename E::value_type> >::result_type\nlayer_determinant( const vector_expression<E>& e ) {\n    typedef typename vector_unary_special_traits<E, component_determinant<\n    \ttypename E::value_type> >::expression_type expression_type ;\n    return expression_type( e() ) ;\n}\n\ntemplate<template<class E1, class E2>class F, class V, class E>\nvoid nested_vector_assign( V& v, const vector_expression<E>& e) {\n\ttypedef F<V,E>\t\tfunctor_type ;\n    typedef typename V::size_type size_type ;\n    v = functor_type::apply( v, e () ) ;\n}\n\ntemplate<class E, std::size_t I1, std::size_t I2>\ntypename vector_unary_special_traits<E, nested_index<typename E::value_type, I1, I2> >::result_type\nnested_access( const vector_expression<E>& e ) {\n\ttypedef typename vector_unary_special_traits<E, nested_index<typename E::value_type,\n\t\tI1, I2> >::expression_type\texpression_type ;\n\treturn expression_type( e() ) ;\n}\n\ntemplate<class T>\nstruct scalar_abs:\n    public scalar_real_unary_functor<T> {\n    typedef typename scalar_real_unary_functor<T>::argument_type\n\t\t argument_type;\n    typedef typename scalar_real_unary_functor<T>::result_type\n\t\t result_type;\n\n    static inline result_type apply(argument_type t) {\n        return type_traits<result_type>::abs(t);\n    }\n};\n\n/**\n * Magnitude of a complex vector.\n */\ntemplate<class E> BOOST_UBLAS_INLINE\n    typename vector_unary_traits<E,\n    scalar_abs<typename E::value_type> >::result_type\nabs(const vector_expression<E> &e) {\n    typedef typename vector_unary_traits<E,\n    scalar_abs<typename E::value_type> >::expression_type\n        expression_type;\n    return expression_type( e() );\n}\n\nint main() {\n\n\ttypedef std::complex<double>\tcomplex_num ;\n\n\tbool full_test = false ;\n\n\tvector<complex_num> vc(3) ;\n\tvc(0) = complex_num(5, 10) ;\n\tvc(1) = complex_num(-3, 2) ;\n\tvc(2) = complex_num(1, -1) ;\n\n\tstd::cout << \"vc:\" << vc << std::endl ;\n//\tstd::cout << \"abs(vc):\" << abs(vc) << std::endl ;\n\n\tif( full_test ) {\n\t\tvector<double> v1(4) ;\n\t\tvector<double> v2(4) ;\n\t\tvector<double> v3(4) ;\n\t\tvector<double> v4(4) ;\n\t\tfor(unsigned i=0; i<v1.size(); ++i) {\n\t\t\tv1(i) = (i+1)*1 ;\n\t\t\tv2(i) = (i+1)*2 ;\n\t\t\tv3(i) = (i+1)*6 ;\n\t\t\tv4(i) = (i+1)*4 ;\n\t\t}\n\t\tvector<vector<double> > vv1(2) ;\n\t\tvv1(0) = v1 ;\n\t\tvv1(1) = v2 ;\n\t\tvector<vector<double> > vv2(2) ;\n\t\tvv2(0) = v3 ;\n\t\tvv2(1) = v4 ;\n\t\tvector<vector<double> > v_diff = layer_prod(vv2, vv1) ;\n\t\n\t\tstd::cout << \"vv1: \" << vv1 << std::endl ;\n\t\tstd::cout << \"vv2: \" << vv2 << std::endl ;\n\t\tstd::cout << \"v_diff: \" << v_diff << std::endl ;\n\t\tvector<double> vtest (4,0.0) ;\n\t\tnested_vector_assign<nested_plus_assign>(vtest, v_diff) ;\n\t\tstd::cout << \"vtest: \" << vtest << std::endl ;\n\t\t\n\t\tmatrix<double> m1(2,2) ;\n\t\tmatrix<double> m2(2,2) ;\n\t\tmatrix<double> m3(2,2) ;\n\t\tmatrix<double> m4(2,2) ;\n\t\tfor(unsigned i=0; i<m1.size1(); ++i) {\n\t\t\tfor(unsigned j=0; j<m1.size2(); ++j) {\n\t\t\t\tm1(i,j) = (i+1)*1 + j * 1 ;\n\t\t\t\tm2(i,j) = (i+1)*6 + j * 2 ;\n\t\t\t\tm3(i,j) = (i+1)*5 + j * 3 ;\n\t\t\t\tm4(i,j) = (i+1)*4 + j * 4 ;\n\t\t\t}\n\t\t}\t\n\t\tvector<matrix<double> > vm1(2) ;\n\t\tvm1(0) = m1 ;\n\t\tvm1(1) = m2 ;\n\t\tvector<matrix<double> > vm2(2) ;\n\t\tvm2(0) = m3 ;\n\t\tvm2(1) = m4 ;\n\t\tvector<matrix<double> > m_diff = vm1 - vm2 ;\n\t\n\t\tstd::cout << \"vm1: \" << vm1 << std::endl ;\n\t\tstd::cout << \"vm2: \" << vm2 << std::endl ;\n\t\tstd::cout << \"m_diff: \" << m_diff << std::endl ;\n\t\n\t\tvector<matrix<double> > test_inverse = inverse(m_diff) ;\n\t\tstd::cout << \"test_inverse:\" << test_inverse << std::endl ;\n\t\n\t\tvector<double> test_access = nested_access<vector<matrix<double> >,1,1>(m_diff) ;\n\t\tstd::cout << \"test_access:\" << test_access << std::endl ;\n\t\n\t\tvector<double> det = layer_determinant(m_diff) ;\n\t\tstd::cout << \"det: \" << det << std::endl ;\n\t\n\t\tdouble result = prod( m1, m2 )(0,0) ;\n\t\tstd::cout << \"result: \" << result << std::endl ;\n\t}\n}\n", "meta": {"hexsha": "b52585ea62b1c39505f72c48041abd4a994b94f1", "size": 7378, "ext": "cc", "lang": "C++", "max_stars_repo_path": "misc_test/boost_test.cc", "max_stars_repo_name": "Tibonium/genecis", "max_stars_repo_head_hexsha": "4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "misc_test/boost_test.cc", "max_issues_repo_name": "Tibonium/genecis", "max_issues_repo_head_hexsha": "4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc_test/boost_test.cc", "max_forks_repo_name": "Tibonium/genecis", "max_forks_repo_head_hexsha": "4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5298507463, "max_line_length": 100, "alphanum_fraction": 0.6675250745, "num_tokens": 2244, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4354304139822485}}
{"text": "#include \"MyModel.h\"\n#include \"RNG.h\"\n#include \"Utils.h\"\n#include \"Data.h\"\n//#include \"MultiSite2.h\"\n#include <cmath>\n#include <fstream>\n#include <chrono>\n#include <typeinfo>  //for 'typeid' to work  \n\n//#include \"HODLR_Tree.hpp\"\n// #include <Eigen/Core>\n#include \"celerite/celerite.h\"\n\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace DNest4;\n\n// get the instance for the full dataset\n//DataSet& full = DataSet::getRef(\"full\");\n\n#define DONEW false  \n#define DOCEL true\n\n#define trend true\n#define GP true\n\nMyModel::MyModel()\n:objects(5, 10, false, MyConditionalPrior())\n,mu(Data::get_instance().get_t().size())\n,C(Data::get_instance().get_t().size(), Data::get_instance().get_t().size())\n{\n    //setupHODLR();\n    // celerite::solver::BandSolver<double> solver;\n}\n\n\n/*void MyModel::setupHODLR()\n{\n    const vector<double>& t = full.get_t();\n    \n    kernel = new QPkernel(t);\n    kernel->set_hyperpars(1., 1., 1., 1.);  // not sure if this is needed\n\n    A = new HODLR_Tree<QPkernel>(kernel, full.N, 150);\n}*/\n\nvoid MyModel::from_prior(RNG& rng)\n{\n    objects.from_prior(rng);\n    objects.consolidate_diff();\n    \n    double ymin, ymax, tmin, tmax;\n    tmin = Data::get_instance().get_t_min();\n    tmax = Data::get_instance().get_t_max();\n    ymin = Data::get_instance().get_y_min();\n    ymax = Data::get_instance().get_y_max();\n\n    background = ymin + (ymax - ymin)*rng.rand();\n\n    #if trend\n        // double max_slope = Data::get_instance().get_max_slope();\n        // slope = -1E-4 + 2E-4*rng.rand();\n        // quad = -1E-4 + 2E-4*rng.rand();\n        double topslope = abs(ymax-ymin) / (tmax - tmin);\n        slope = -topslope + 2.*topslope*rng.rand();\n        double topquad = abs(ymax-ymin) / ((tmax - tmin)*(tmax - tmin));\n        quad = -topquad + 2.*topquad*rng.rand();\n    #endif\n\n\n\n    // centered at 1 (data in m/s)\n    /*extra_sigma = exp(tan(M_PI*(0.97*rng.rand() - 0.485)));*/\n    // centered at 0.001 (data in km/s)\n    extra_sigma = exp(-6.908 + tan(M_PI*(0.97*rng.rand() - 0.485)));\n\n    //eta5 = exp(tan(M_PI*(0.97*rng.rand() - 0.485)));\n\n    #if GP\n        // Log-uniform prior from 10^(-1) to 50 m/s\n        //eta1 = exp(log(1E-1) + log(5E2)*rng.rand());\n        // Log-uniform prior from 10^(-5) to 0.05 km/s\n        eta1 = exp(log(1E-5) + log(1E-1)*rng.rand());\n\n\n        // Log-uniform prior\n        eta2 = exp(log(1E-6) + log(1E6)*rng.rand());\n\n        // or uniform prior between 10 and 40 days\n        eta3 = 15. + 35.*rng.rand();\n\n        // Log-uniform prior from 10^(-1) to 10 (fraction of eta3)\n        // Log-uniform prior from 10^(-1) to 2 (fraction of eta3)\n        // eta4 = 1.; \n        exp(log(1E-5) + log(1E5)*rng.rand());\n        // eta4 = rng.rand();\n    #endif\n\n    calculate_mu();\n\n    #if GP\n        calculate_C();\n    #endif\n}\n\nvoid MyModel::calculate_C()\n{\n\n    // Get the data\n    const vector<double>& t = Data::get_instance().get_t();\n    const vector<double>& sig = Data::get_instance().get_sig();\n\n    #if DONEW\n        //auto begin = std::chrono::high_resolution_clock::now();  // start timing\n\n        kernel->set_hyperpars(eta1, eta2, eta3, eta4);\n        cout << eta1 << \"   \" << eta2 << \"   \" << eta3 << \"   \" << eta4 << \"   \";\n        VectorXd yvar(t.size());\n        for (int i = 0; i < t.size(); ++i)\n            yvar(i) = eta1*eta1 + sig[i] * sig[i] + extra_sigma * extra_sigma;\n\n        //auto begin = std::chrono::high_resolution_clock::now();  // start timing\n        A->assemble_Matrix(yvar, 1e-14, 's');\n        //auto end = std::chrono::high_resolution_clock::now();\n        //cout << \"assembling up took \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << \" ns\" << std::endl;\n        A->compute_Factor();\n\n        //auto end = std::chrono::high_resolution_clock::now();\n\n        //ofstream timerfile;\n        //timerfile.open(\"timings.txt\", std::ios_base::app);\n        //timerfile.setf(ios::fixed,ios::floatfield);\n        //timerfile << t.size() << '\\t' << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << \" ns\" << std::endl;\n\n    #elif DOCEL\n        // celerite!\n        // auto begin1 = std::chrono::high_resolution_clock::now();  // start timing\n\n        /*\n        This implements the kernel in Eq (61) of Foreman-Mackey et al. (2017)\n        The kernel has parameters a, b, c and P\n        corresponding to an amplitude, factor, decay timescale and period.\n        */\n\n        VectorXd alpha_real(1),\n                 beta_real(1),\n                 alpha_complex_real(1),\n                 alpha_complex_imag(1),\n                 beta_complex_real(1),\n                 beta_complex_imag(1);\n        \n        a = eta1;\n        b = eta4;\n        P = eta3;\n        c = eta2;\n\n        alpha_real << a*(1.+b)/(2.+b);\n        beta_real << c;\n        alpha_complex_real << a/(2.+b);\n        alpha_complex_imag << 0.;\n        beta_complex_real << c;\n        beta_complex_imag << 2.*M_PI / P;\n\n\n        VectorXd yvar(t.size()), tt(t.size());\n        for (int i = 0; i < t.size(); ++i){\n            yvar(i) = sig[i] * sig[i] + extra_sigma * extra_sigma;\n            tt(i) = t[i];\n        }\n\n        solver.compute(\n            alpha_real, beta_real,\n            alpha_complex_real, alpha_complex_imag,\n            beta_complex_real, beta_complex_imag,\n            tt, yvar  // Note: this is the measurement _variance_\n        );\n\n\n        // auto end1 = std::chrono::high_resolution_clock::now();\n        // cout << \"new GP: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end1-begin1).count() << \" ns\" << std::endl;\n        \n    #else\n\n        int N = Data::get_instance().get_t().size();\n        // auto begin = std::chrono::high_resolution_clock::now();  // start timing\n\n        for(size_t i=0; i<N; i++)\n        {\n            for(size_t j=i; j<N; j++)\n            {\n                //C(i, j) = eta1*eta1*exp(-0.5*pow((t[i] - t[j])/eta2, 2) );\n                C(i, j) = eta1*eta1*exp(-0.5*pow((t[i] - t[j])/eta2, 2) \n                           -2.0*pow(sin(M_PI*(t[i] - t[j])/eta3)/eta4, 2) );\n\n                if(i==j)\n                    C(i, j) += sig[i]*sig[i] + extra_sigma*extra_sigma; //+ eta5*t[i]*t[i];\n                else\n                    C(j, i) = C(i, j);\n            }\n        }\n\n        // auto end = std::chrono::high_resolution_clock::now();\n        // cout << \"old GP: \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << \" ns\" << \"\\t\"; // << std::endl;\n\n\n\n        //ofstream timerfile;\n        //timerfile.open(\"timings.txt\", std::ios_base::app);\n        //timerfile.setf(ios::fixed,ios::floatfield);\n        //timerfile << t.size() << '\\t' << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << \" ns\" << std::endl;\n\n    #endif\n}\n\nvoid MyModel::calculate_mu()\n{\n    // Get the times from the data\n    const vector<double>& t = Data::get_instance().get_t();\n\n    // Update or from scratch?\n    bool update = (objects.get_added().size() < objects.get_components().size()) &&\n            (staleness <= 10);\n\n    // Get the components\n    const vector< vector<double> >& components = (update)?(objects.get_added()):\n                (objects.get_components());\n    // at this point, components has:\n    //  if updating: only the added planets' parameters\n    //  if from scratch: all the planets' parameters\n\n    // Zero the signal\n    if(!update) // not updating, means recalculate everything\n    {\n        mu.assign(mu.size(), background);\n        staleness = 0;\n        #if trend\n            for(size_t i=0; i<t.size(); i++)\n                mu[i] += slope*(t[i] - t[0]) + quad*(t[i] - t[0])*(t[i] - t[0]);\n            \n            // cout << slope << \"\\t\" << quad << endl;\n        #endif\n    }\n    else // just updating (adding) planets\n        staleness++;\n\n    //auto begin = std::chrono::high_resolution_clock::now();  // start timing\n\n    double P, K, phi, ecc, viewing_angle, f, v, ti;\n    for(size_t j=0; j<components.size(); j++)\n    {\n        P = exp(components[j][0]);\n        K = components[j][1];\n        phi = components[j][2];\n        ecc = components[j][3];\n        viewing_angle = components[j][4];\n\n        for(size_t i=0; i<t.size(); i++)\n        {\n            ti = t[i];\n            f = true_anomaly(ti, P, ecc, t[0]-(P*phi)/(2.*M_PI));\n            v = K*(cos(f+viewing_angle) + ecc*cos(viewing_angle));\n            mu[i] += v;\n        }\n    }\n\n\n\n\n\n    // cout << background << endl;\n\n    //auto end = std::chrono::high_resolution_clock::now();\n    //ofstream timerfile;\n    //timerfile.open(\"timings.txt\", std::ios_base::app);\n    //timerfile.setf(ios::fixed,ios::floatfield);\n    //timerfile << components.size() << '\\t' << ecc << '\\t' << viewing_angle << '\\t' << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << \" ns\" << std::endl;\n    \n    //cout<<Ea<<endl;\n}\n\ndouble MyModel::perturb(RNG& rng)\n{\n    double logH = 0.;\n\n    if(rng.rand() <= 0.5)\n    {\n        logH += objects.perturb(rng);\n        objects.consolidate_diff();\n        calculate_mu();\n    }\n\n    #if GP\n    else if(rng.rand() <= 0.5)\n    {\n        if(rng.rand() <= 0.25)\n        {\n            eta1 = log(eta1);\n            eta1 += log(1E4)*rng.randh(); // range of prior support\n            wrap(eta1, log(1E-5), log(1E-1)); // wrap around inside prior\n            eta1 = exp(eta1);\n        }\n        else if(rng.rand() <= 0.33330)\n        {\n            eta2 = log(eta2);\n            eta2 += log(1E12)*rng.randh(); // range of prior support\n            wrap(eta2, log(1E-6), log(1E6)); // wrap around inside prior\n            eta2 = exp(eta2);\n        }\n        else if(rng.rand() <= 0.5)\n        {\n            eta3 += 35.*rng.randh(); // range of prior support\n            wrap(eta3, 15., 50.); // wrap around inside prior\n        }\n        else\n        {\n            // eta4 = 1.0;\n\n            eta4 = log(eta4);\n            eta4 += log(1E10)*rng.randh(); // range of prior support\n            wrap(eta4, log(1E-5), log(1E5)); // wrap around inside prior\n            eta4 = exp(eta4);\n\n            // eta4 += rng.randh();\n            // wrap(eta4, 0., 1.);\n        }\n\n        calculate_C();\n\n    }\n    #endif // GP\n\n    else if(rng.rand() <= 0.5)\n    {\n        // data in km/s\n        extra_sigma = log(extra_sigma);\n        extra_sigma = (atan(extra_sigma + 6.908)/M_PI + 0.485)/0.97;\n        extra_sigma += rng.randh();\n        wrap(extra_sigma, 0., 1.);\n        extra_sigma = -6.908 + tan(M_PI*(0.97*extra_sigma - 0.485));\n        extra_sigma = exp(extra_sigma);\n\n        #if GP\n            calculate_C();\n        #endif\n    }\n    else\n    {\n\n    #if trend\n\n        // Get the times from the data\n        const vector<double>& t = Data::get_instance().get_t();\n\n        for(size_t i=0; i<mu.size(); i++)\n            mu[i] = mu[i] - background - slope*(t[i]-t[0]) - quad*(t[i]-t[0])*(t[i]-t[0]);\n\n        double ymin, ymax, tmin, tmax;\n        tmin = Data::get_instance().get_t_min();\n        tmax = Data::get_instance().get_t_max();\n        ymin = Data::get_instance().get_y_min();\n        ymax = Data::get_instance().get_y_max();\n        double topslope = abs(ymax-ymin) / (tmax - tmin);\n        double topquad = abs(ymax-ymin) / ((tmax - tmin)*(tmax - tmin));\n\n        // propose new offset\n        background += (ymax - ymin)*rng.randh();\n        wrap(background, ymin, ymax);\n\n        // propose new slope and quad \n        slope += 2.*topslope*rng.randh();\n        wrap(slope, -topslope, topslope);\n        quad += 2.*topquad*rng.randh();\n        wrap(quad, -topquad, topquad);\n        // slope += 2E-6*rng.randh();\n        // wrap(slope, -3E-6, -1E-6);\n        // quad += 2E-9*rng.randh();\n        // wrap(quad, 8E-9, 1E-8);\n\n\n        // add it back again\n        for(size_t i=0; i<mu.size(); i++)\n            mu[i] = mu[i] + background + slope*(t[i]-t[0]) + quad*(t[i]-t[0])*(t[i]-t[0]);\n\n    #else\n        for(size_t i=0; i<mu.size(); i++)\n            mu[i] -= background;\n\n        double ymin, ymax;\n        ymin = Data::get_instance().get_y_min();\n        ymax = Data::get_instance().get_y_max();\n\n        background += (ymax - ymin)*rng.randh();\n        wrap(background, ymin, ymax);\n\n        for(size_t i=0; i<mu.size(); i++)\n            mu[i] += background;\n    #endif\n\n    }\n\n\n    return logH;\n}\n\n\ndouble MyModel::log_likelihood() const\n{\n    int N = Data::get_instance().get_y().size();\n\n    /** The following code calculates the log likelihood in the case of a GP model */\n\n    // Get the data\n    const vector<double>& y = Data::get_instance().get_y();\n\n    //auto begin = std::chrono::high_resolution_clock::now();  // start timing\n    #if GP\n\n    #if DONEW\n        // Set up the kernel.\n        //auto begin = std::chrono::high_resolution_clock::now();  // start timing\n        //QPkernel kernel;\n        //kernel->set_hyperpars(eta1, eta2, eta3, eta4);\n        //auto end = std::chrono::high_resolution_clock::now();\n        //cout << \"set kernel took \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << \" ns\" << std::endl;\n\n        // Setting things up\n        //auto begin = std::chrono::high_resolution_clock::now();  // start timing\n        \n        //auto end = std::chrono::high_resolution_clock::now();\n        //cout << \"setting up took \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << \" ns\" << std::endl;\n        \n        MatrixXd b(y.size(), 1), x;\n        //VectorXd yvar(t.size());\n        for (int i = 0; i < y.size(); ++i) {\n            //yvar(i) = eta1*eta1 + sig[i] * sig[i] + extra_sigma * extra_sigma;\n            b(i, 0) = y[i] - mu[i];\n        }\n\n        //auto begin = std::chrono::high_resolution_clock::now();  // start timing\n        A->solve(b, x);\n        double determinant;\n        A->compute_Determinant(determinant);\n        //auto end = std::chrono::high_resolution_clock::now();\n        //cout << \"solve and determinant took \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << \" ns\" << std::endl;\n\n        //cout << logDeterminant << \"   \" << determinant << endl;\n        //assert (logDeterminant == determinant);\n        double exponent2 = 0.;\n        for(int i = 0; i < y.size(); ++i)\n            exponent2 += b(i,0)*x(i);\n\n\n        double logL = -0.5*y.size()*log(2*M_PI)\n                        - 0.5*determinant - 0.5*exponent2;\n\n        //cout << logL << endl;\n        //cout << logL << \"   \" << logL2 << endl;    \n        //assert (logL == logL2);\n\n\n    #else\n        // residual vector (observed y minus model y)\n        VectorXd residual(y.size());\n        for(size_t i=0; i<y.size(); i++)\n            residual(i) = y[i] - mu[i];\n\n        #if DOCEL\n            // logDeterminant = solver.log_determinant();\n            // VectorXd solution = solver.solve(residual);\n\n            double logL = -0.5 * (solver.dot_solve(residual) +\n                                  solver.log_determinant() +\n                                  y.size()*log(2*M_PI)); \n        #else\n            // perform the cholesky decomposition of C\n            Eigen::LLT<Eigen::MatrixXd> cholesky = C.llt();\n            // get the lower triangular matrix L\n            MatrixXd L = cholesky.matrixL();\n\n            double logDeterminant = 0.;\n            for(size_t i=0; i<y.size(); i++)\n                logDeterminant += 2.*log(L(i,i));\n\n            VectorXd solution = cholesky.solve(residual);\n\n            // y*solution\n            double exponent = 0.;\n            for(size_t i=0; i<y.size(); i++)\n                exponent += residual(i)*solution(i);\n\n            double logL = -0.5*y.size()*log(2*M_PI)\n                            - 0.5*logDeterminant - 0.5*exponent;\n        #endif\n\n        // cout << \"old GP log_det: \" << logDeterminant << \"\\t\"; // << std::endl;\n        // cout << \"new GP log_det: \" << solver.log_determinant() << std::endl;\n\n        // calculate C^-1*(y-mu)\n        // auto begin = std::chrono::high_resolution_clock::now();  // start timing\n        // auto end = std::chrono::high_resolution_clock::now();\n        // cout << \"solve took \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << \" ns \\t\";// <<  std::endl;\n\n        // auto begin1 = std::chrono::high_resolution_clock::now();  // start timing\n        // auto end1 = std::chrono::high_resolution_clock::now();\n        // cout << \"solve took \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end1-begin1).count() << \" ns\" << std::endl;\n    #endif\n\n\n    //auto end = std::chrono::high_resolution_clock::now();\n    ////cout << \"Likelihood took \" << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << \" ns\" << std::endl;\n\n    //ofstream timerfile;\n    //timerfile.open(\"timings_logL.txt\", std::ios_base::app);\n    //timerfile.setf(ios::fixed,ios::floatfield);\n    //timerfile << y.size() << '\\t' << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << \" ns\" << std::endl;\n\n    // cout << \"finished log_likelihood!\" << endl;\n    // return logL;\n\n\n    #else\n\n    /** The following code calculates the log likelihood in the case of a t-Student model without correlated noise*/\n    //  for(size_t i=0; i<y.size(); i++)\n    //  {\n    //      var = sig[i]*sig[i] + extra_sigma*extra_sigma;\n    //      logL += gsl_sf_lngamma(0.5*(nu + 1.)) - gsl_sf_lngamma(0.5*nu)\n    //          - 0.5*log(M_PI*nu) - 0.5*log(var)\n    //          - 0.5*(nu + 1.)*log(1. + pow(y[i] - mu[i], 2)/var/nu);\n    //  }\n\n    /** The following code calculates the log likelihood in the case of a Gaussian likelihood*/\n    const vector<double>& sig = Data::get_instance().get_sig();\n\n    double halflog2pi = 0.5*log(2.*M_PI);\n    double logL = 0.;\n    double var;\n    for(size_t i=0; i<y.size(); i++)\n    {\n        var = sig[i]*sig[i] + extra_sigma*extra_sigma;\n        logL += - halflog2pi - 0.5*log(var)\n                - 0.5*(pow(y[i] - mu[i], 2)/var);\n    }\n\n    #endif // GP\n\n\n    if(std::isnan(logL) || std::isinf(logL))\n        logL = -1E300;\n    return logL;\n}\n\nvoid MyModel::print(std::ostream& out) const\n{\n    // output presision\n    out.setf(ios::fixed,ios::floatfield);\n    out.precision(8);\n\n    //out<<extra_sigma<<'\\t'<<eta1<<'\\t'<<eta2<<'\\t'<<eta3<<'\\t'<<eta4<<'\\t'<<eta5<<'\\t';\n    //out<<extra_sigma<<'\\t'<<eta1<<'\\t'<<eta2<<'\\t';\n    // out<<extra_sigma<<'\\t'<<eta1<<'\\t'<<eta2<<'\\t'<<eta3<<'\\t'<<eta4<<'\\t';\n\n    out<<extra_sigma<<'\\t';\n\n    #if GP\n        out<<eta1<<'\\t'<<eta2<<'\\t'<<eta3<<'\\t'<<eta4<<'\\t';\n    #endif\n    #if trend\n        out<<slope<<'\\t'<<quad*1E8<<'\\t';\n    #endif\n\n  \n    objects.print(out); out<<' '<<staleness<<' ';\n    out<<background<<' ';\n}\n\nstring MyModel::description() const\n{\n    #if #GP\n        #if trend\n            return string(\"extra_sigma   eta1   eta2   eta3   eta4  slope   quad   objects.print   staleness   background\");\n        #else\n            return string(\"extra_sigma   eta1   eta2   eta3   eta4  objects.print   staleness   background\");\n        #endif\n    #else\n        return string(\"extra_sigma   objects.print   staleness   background\");\n    #endif\n    //return string(\"extra_sigma  eta1    eta2    objects.print   staleness   background\");\n    //return string(\"extra_sigma  eta1    eta2    eta3    eta4    eta5    offsets    objects.print   staleness   background\");\n}\n\n\n/**\n    Calculates the eccentric anomaly at time t by solving Kepler's equation.\n    See \"A Practical Method for Solving the Kepler Equation\", Marc A. Murison, 2006\n\n    @param t the time at which to calculate the eccentric anomaly.\n    @param period the orbital period of the planet\n    @param ecc the eccentricity of the orbit\n    @param t_peri time of periastron passage\n    @return eccentric anomaly.\n*/\ndouble MyModel::ecc_anomaly(double t, double period, double ecc, double time_peri)\n{\n    double tol;\n    if (ecc < 0.8) tol = 1e-14;\n    else tol = 1e-13;\n\n    double n = 2.*M_PI/period;  // mean motion\n    double M = n*(t - time_peri);  // mean anomaly\n    double Mnorm = fmod(M, 2.*M_PI);\n    double E0 = keplerstart3(ecc, Mnorm);\n    double dE = tol + 1;\n    double E;\n    int count = 0;\n    while (dE > tol)\n    {\n        E = E0 - eps3(ecc, Mnorm, E0);\n        dE = abs(E-E0);\n        E0 = E;\n        count++;\n        // failed to converge, this only happens for nearly parabolic orbits\n        if (count == 100) break;\n    }\n    return E;\n}\n\n\n/**\n    Provides a starting value to solve Kepler's equation.\n    See \"A Practical Method for Solving the Kepler Equation\", Marc A. Murison, 2006\n\n    @param e the eccentricity of the orbit\n    @param M mean anomaly (in radians)\n    @return starting value for the eccentric anomaly.\n*/\ndouble MyModel::keplerstart3(double e, double M)\n{\n    double t34 = e*e;\n    double t35 = e*t34;\n    double t33 = cos(M);\n    return M + (-0.5*t35 + e + (t34 + 1.5*t33*t35)*t33)*sin(M);\n}\n\n\n/**\n    An iteration (correction) method to solve Kepler's equation.\n    See \"A Practical Method for Solving the Kepler Equation\", Marc A. Murison, 2006\n\n    @param e the eccentricity of the orbit\n    @param M mean anomaly (in radians)\n    @param x starting value for the eccentric anomaly\n    @return corrected value for the eccentric anomaly\n*/\ndouble MyModel::eps3(double e, double M, double x)\n{\n    double t1 = cos(x);\n    double t2 = -1 + e*t1;\n    double t3 = sin(x);\n    double t4 = e*t3;\n    double t5 = -x + t4 + M;\n    double t6 = t5/(0.5*t5*t4/t2+t2);\n\n    return t5/((0.5*t3 - 1/6*t1*t6)*e*t6+t2);\n}\n\n\n\n/**\n    Calculates the true anomaly at time t.\n    See Eq. 2.6 of The Exoplanet Handbook, Perryman 2010\n\n    @param t the time at which to calculate the true anomaly.\n    @param period the orbital period of the planet\n    @param ecc the eccentricity of the orbit\n    @param t_peri time of periastron passage\n    @return true anomaly.\n*/\ndouble MyModel::true_anomaly(double t, double period, double ecc, double t_peri)\n{\n    double E = ecc_anomaly(t, period, ecc, t_peri);\n    double f = acos( (cos(E)-ecc)/( 1-ecc*cos(E) ) );\n    //acos gives the principal values ie [0:PI]\n    //when E goes above PI we need another condition\n    if(E>M_PI)\n      f=2*M_PI-f;\n\n    return f;\n}\n", "meta": {"hexsha": "98794e8c819d5345bc8c6f847caaa4dd53dc38f8", "size": 22058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/MyModel.cpp", "max_stars_repo_name": "j-faria/bicerin", "max_stars_repo_head_hexsha": "1f06a71d17ab3f18f6ce2bf15773b6402519ecda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MyModel.cpp", "max_issues_repo_name": "j-faria/bicerin", "max_issues_repo_head_hexsha": "1f06a71d17ab3f18f6ce2bf15773b6402519ecda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-09-04T13:44:21.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-07T08:25:32.000Z", "max_forks_repo_path": "src/MyModel.cpp", "max_forks_repo_name": "j-faria/bicerin", "max_forks_repo_head_hexsha": "1f06a71d17ab3f18f6ce2bf15773b6402519ecda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8757225434, "max_line_length": 182, "alphanum_fraction": 0.5462870614, "num_tokens": 6397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4354304084102171}}
{"text": "#include \"problems/mga_transx.h\"\n\n#include <boost/array.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include <keplerian_toolbox/core_functions/fb_vel.h>\n#include <keplerian_toolbox/core_functions/array3D_operations.h>\n#include <keplerian_toolbox/lambert_problem.h>\n\n#include <cmath>\n#include <numeric>\n#include <string>\n#include <vector>\n\nnamespace pagmo { namespace problem {\n\nmga_transx::mga_transx(const std::vector<kep_toolbox::planet::planet_ptr> seq,\n    const double dep_altitude, const double arr_altitude, const bool circularize,\n    const kep_toolbox::epoch t0_l, const kep_toolbox::epoch t0_u,\n    const double tof_l, const double tof_u, \n    const double vinf_l, const double vinf_u, \n    const bool add_vinf_dep, const bool add_vinf_arr,\n    const bool multi_obj) : transx_problem(seq, dep_altitude, arr_altitude, circularize, seq.size() + 1, 1 + (int)multi_obj), m_add_vinf_dep(add_vinf_dep), m_add_vinf_arr(add_vinf_arr), m_multi_obj(multi_obj) {\n    \n        size_t dim(get_dimension());\n        decision_vector lb(dim), ub(dim);\n        lb[0] = t0_l.mjd2000(); ub[0] = t0_u.mjd2000();\n        lb[1] = tof_l * 365.25; ub[1] = tof_u * 365.25;\n\n        for (int i = 0; i < dim - 2; ++i) {\n          lb[2 + i] = 1e-5; ub[2 + i] = 1 - 1e-5; \n        }\n\n        set_bounds(lb, ub);\n}\n\nmga_transx::mga_transx(const mga_transx &p) : transx_problem(p.get_seq(), p.get_dep_altitude(), p.get_arr_altitude(), p.get_circularize(), p.get_dimension(), p.get_f_dimension()), m_add_vinf_dep(p.m_add_vinf_dep), m_add_vinf_arr(p.m_add_vinf_arr), m_multi_obj(p.m_multi_obj) {\n  set_bounds(p.get_lb(), p.get_ub());\n\n}\n\nbase_ptr mga_transx::clone() const {\n  return base_ptr(new mga_transx(*this));\n}\n\nvoid mga_transx::calc_objective(fitness_vector &f, const decision_vector &x, bool should_print, TransXSolution * solution) const {\n\n  int n = get_n_legs();\n\n  std::vector<double> T(n, 0.0);\n\n  double alpha_sum = 0.0;\n  for (int i = 0; i < get_n_legs(); ++i) {\n    double tmp = -log(x[2 + i]);\n    alpha_sum += tmp;\n    T[i] = x[1] * tmp;\n  }\n\n  for (int i = 0; i < T.size(); ++i) {\n    T[i] /= alpha_sum;\n  }\n\n  std::vector<kep_toolbox::epoch>   t_P(get_seq().size());\n  std::vector<kep_toolbox::array3D> r_P(get_seq().size());\n  std::vector<kep_toolbox::array3D> v_P(get_seq().size());\n  std::vector<double> DV(get_seq().size());\n  for (int i = 0; i < get_seq().size(); ++i) {\n    kep_toolbox::planet::planet_ptr planet = get_seq()[i];\n    t_P[i] = kep_toolbox::epoch(x[0] + std::accumulate(T.begin(), T.begin()+i, 0.0));\n    planet->eph(t_P[i], r_P[i], v_P[i]);\n  }\n\n  kep_toolbox::array3D r(r_P[0]), v(v_P[0]);\n  kep_toolbox::array3D v_end_l;\n  kep_toolbox::array3D v_beg_l;\n\n  if (should_print) {\n    transx_time_info(solution->mutable_times(), get_seq(), t_P);\n  }\n\n  kep_toolbox::array3D vout, vin;\n  for (int i = 0; i < get_n_legs(); ++i) {\n    r = r_P[i]; v = v_P[i];\n\n    double dt = (t_P[i + 1].mjd() - t_P[i].mjd()) * ASTRO_DAY2SEC;\n    kep_toolbox::lambert_problem l(r, r_P[i + 1], dt, get_common_mu(), false, false);\n    v_beg_l = l.get_v1()[0];\n    v_end_l = l.get_v2()[0];\n\n    vout = v_beg_l;\n\n    if (i == 0) {\n      kep_toolbox::array3D vout_rel(vout);\n      kep_toolbox::diff(vout_rel, vout, v_P[i]);\n      if (get_add_vinf_dep()) {\n        DV[0] = burn_cost(get_seq()[0], vout_rel, false, true);\n      }\n      if (should_print) {\n        transx_escape(solution->mutable_escape(), get_seq()[0], v_P[0], r_P[0], vout_rel, t_P[0].mjd());\n      }\n    } else {\n      kep_toolbox::array3D v_rel_in(vin), v_rel_out(vout);\n      kep_toolbox::diff(v_rel_in, vin, v_P[i]);\n      kep_toolbox::diff(v_rel_out, vout, v_P[i]);\n      kep_toolbox::planet::planet_ptr planet = get_seq()[i];\n      kep_toolbox::fb_vel(DV[i], v_rel_in, v_rel_out, *planet);\n\n      double ta  = acos(kep_toolbox::dot(v_rel_in, v_rel_out)/sqrt(kep_toolbox::dot(v_rel_in,v_rel_in))/sqrt(kep_toolbox::dot(v_rel_out,v_rel_out)));\n      double alt = (planet->get_mu_self() / kep_toolbox::dot(v_rel_in,v_rel_in)*(1/sin(ta/2)-1) - planet->get_radius())/1000;\n      if (alt > planet->get_safe_radius()) {\n        f[0] = DBL_MAX;\n        return;\n      }\n\n      if (should_print) {\n        transx_flyby(solution->add_flybyes(), planet, v_P[i], r_P[i], v_rel_in, v_rel_out, t_P[i].mjd());\n      }\n    }\n\n    vin = v_end_l;\n  }\n\n  kep_toolbox::array3D Vexc_arr;\n  kep_toolbox::diff(Vexc_arr, v_end_l, v_P[v_P.size() - 1]);\n  if (get_add_vinf_arr()) {\n    DV[DV.size() - 1] = burn_cost(get_seq()[get_seq().size() - 1], Vexc_arr, true, get_circularize());\n  }\n\n  if (should_print) {\n    transx_arrival(solution->mutable_arrival(), get_seq()[get_seq().size() - 1], Vexc_arr, t_P[t_P.size() - 1].mjd());\n  }\n\n  double fuelCost = std::accumulate(DV.begin(), DV.end(), 0.0);\n  double totalTime = std::accumulate(T.begin(), T.end(), 0.0);\n\n  if (should_print) {\n    solution->set_fuel_cost(fuelCost);\n  }\n\n  f[0] = fuelCost;\n  if (get_f_dimension() == 2) {\n    f[1] = totalTime;\n  }\n\n}\n\nstd::string mga_transx::get_name() const {\n  return \"MGA\";\n}\n\n}} // namespaces\n\n\nBOOST_CLASS_EXPORT_IMPLEMENT(pagmo::problem::mga_transx)\n", "meta": {"hexsha": "234d91fe3bc044c4879d7dcc60e51f6c404c832f", "size": 5094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "orbiterkep-lib/src/problems/mga_transx.cpp", "max_stars_repo_name": "tuzcsaba/orbiter-kep", "max_stars_repo_head_hexsha": "cf61ca82c1d171b8187ae505b3370ee9368de9f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-08-28T08:49:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-19T11:45:50.000Z", "max_issues_repo_path": "orbiterkep-lib/src/problems/mga_transx.cpp", "max_issues_repo_name": "tuzcsaba/orbiter-kep", "max_issues_repo_head_hexsha": "cf61ca82c1d171b8187ae505b3370ee9368de9f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "orbiterkep-lib/src/problems/mga_transx.cpp", "max_forks_repo_name": "tuzcsaba/orbiter-kep", "max_forks_repo_head_hexsha": "cf61ca82c1d171b8187ae505b3370ee9368de9f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-06-12T04:28:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T10:28:24.000Z", "avg_line_length": 32.864516129, "max_line_length": 276, "alphanum_fraction": 0.6438947782, "num_tokens": 1681, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.435313669235044}}
{"text": "#include <iostream>\n#include <cmath>\n#include <concepts>\n\n#include <boost/numeric/linear_algebra/operators.hpp>\n#include <boost/numeric/linear_algebra/inverse.hpp>\n#include <boost/numeric/linear_algebra/is_invertible.hpp>\n#include <boost/numeric/linear_algebra/new_concepts.hpp>\n#include <boost/numeric/linear_algebra/concept_maps.hpp>\n#include <boost/numeric/linear_algebra/power.hpp>\n\n\ntemplate <std::HasPlus T>\n    requires std::Convertible<std::HasPlus<T, T>::result_type, T>\n          && std::Semiregular<T>\nT f(const T& x, const T& y)\n{\n    std::cout << \"\\nAdditive magma.\\n\";\n    return x + y;\n}\n\ntemplate <math::AdditiveSemiGroup T>\n    requires std::Convertible<std::HasPlus<T, T>::result_type, T>\n          && std::Semiregular<T>\nT f(const T& x, const T& y)\n{\n    std::cout << \"\\nAdditive semi-group.\\n\";\n    return x + y;\n}\n\ntemplate <math::AdditiveMonoid T>\n    requires std::Convertible<std::HasPlus<T, T>::result_type, T>\n          && std::Semiregular<T>\nT f(const T& x, const T& y)\n{\n    std::cout << \"\\nAdditive monoid.\\n\";\n    return x + y;\n}\n\n#if 0\ntemplate <math::AdditivePIMonoid T>\n    requires std::Convertible<std::HasPlus<T, T>::result_type, T>\n          && std::Semiregular<T>\nT f(const T& x, const T& y)\n{\n    std::cout << \"\\nAdditive partially invertible monoid.\\n\";\n    return x + y;\n}\n\ntemplate <math::AdditiveGroup T>\n    requires std::Convertible<std::HasPlus<T, T>::result_type, T>\n          && std::Semiregular<T>\nT f(const T& x, const T& y)\n{\n    std::cout << \"\\nAdditive group.\\n\";\n    return x + y;\n}\n#endif\n\nint main(int, char* []) \n{\n    std::cout << \"f(3, 4) \" << f(3, 4) << '\\n';\n    std::cout << \"f(3l, 4l) \" << f(3l, 4l) << '\\n';\n    std::cout << \"f(3u, 4u) \" << f(3u, 4u) << '\\n';\n    std::cout << \"f(3.0f, 4.0f) \" << f(3.0f, 4.0f) << '\\n';\n    std::cout << \"f(3.0, 4.0) \" << f(3.0, 4.0) << '\\n';\n\n    return 0;\n}\n\n", "meta": {"hexsha": "d683146fc5ed05fac4eb098a54516ae79841feeb", "size": 1858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/linear_algebra/test/additive_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/linear_algebra/test/additive_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/linear_algebra/test/additive_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 26.1690140845, "max_line_length": 65, "alphanum_fraction": 0.6060279871, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.769080226485192, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.43531366324343435}}
{"text": "//\n// Created by dchansen on 9/4/18.\n//\n\n#include \"bounded_field_map.h\"\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/tools/minima.hpp>\n#include <numeric>\n#include <GadgetronTimer.h>\n\nconstexpr float PI = boost::math::constants::pi<float>();\n\n\nnamespace Gadgetron {\n    namespace FatWater {\n        namespace {\n            template<unsigned int N>\n            struct FieldMapModel {\n\n                FieldMapModel(const Parameters &parameters,\n                              const std::array<complext<float>, N> &data) : TEs_(parameters.echo_times_s) {\n\n                    std::transform(data.begin(), data.end(), angles.begin(), [](auto c) { return arg(c); });\n\n\n                    auto data_norm = std::accumulate(data.begin(), data.end(), 0.0,\n                                                     [](auto acc, auto c) { return acc + norm(c); });\n                    for (int i = 0; i < data.size(); i++) {\n                        for (int j = 0; j < data.size(); j++) {\n                            weights[j + i * N] = norm(data[i] * data[j]) / data_norm;\n                        }\n                    }\n                }\n\n\n                float operator()(float field_value) const {\n\n                    float result = 0;\n                    for (int i = 0; i < N; i++) {\n                        for (int j = 0; j < N; j++) {\n                            result += magnitude_internal(field_value, TEs_[i], TEs_[j], angles[i], angles[j],\n                                                         weights[j + i * N]);\n                        }\n                    }\n                    return result;\n                }\n\n                float magnitude_internal(float field_value, float time1, float time2, float angle1, float angle2,\n                                         float weight) const {\n                    assert(weight >= 0);\n                    return weight * (1.0f - std::cos(field_value * (time1 - time2) + angle1 - angle2));\n\n                }\n\n                const std::vector<float> TEs_;\n                std::array<float, N * N> weights;\n                std::array<float, N> angles;\n\n            };\n\n\n            template<unsigned int N>\n            void bounded_field_map_N(Gadgetron::hoNDArray<float> &field_map,\n                                     const Gadgetron::hoNDArray<std::complex<float>> &input_data,\n                                     const Gadgetron::FatWater::Parameters &parameters,\n                                     float delta_field) {\n\n\n                const size_t X = input_data.get_size(0);\n                const size_t Y = input_data.get_size(1);\n                const size_t Z = input_data.get_size(2);\n                const size_t S = input_data.get_size(5);\n\n#ifdef WIN32\n    #pragma omp parallel for\n#else\n    #pragma omp parallel for collapse(2)\n#endif\n                for (int ky = 0; ky < Y; ky++) {\n                    for (size_t kx = 0; kx < X; kx++) {\n\n                        std::array<complext<float>, N> signal;\n\n                        for (int k3 = 0; k3 < S; k3++) {\n                            signal[k3] = input_data(kx, ky, 0, 0, 0, k3, 0);\n                        }\n\n\n                        auto model = FieldMapModel<N>(parameters, signal);\n\n                        auto result_pair = boost::math::tools::brent_find_minima(model, field_map(kx,ky)-delta_field,field_map(kx,ky)+delta_field, 24);\n                        field_map(kx, ky) = result_pair.first;\n                    }\n                }\n\n\n\n            }\n        }\n\n        void bounded_field_map(Gadgetron::hoNDArray<float> &field_map,\n                                 const Gadgetron::hoNDArray<std::complex<float>> &input_data,\n                                 const Gadgetron::FatWater::Parameters &parameters,\n                                 float delta_field\n        ) {\n\n\n            if (input_data.get_size(4) > 1) throw std::runtime_error(\"Only single repetition supported\");\n\n            switch (input_data.get_size(5)) {\n                case 2:\n                    bounded_field_map_N<2>(field_map, input_data, parameters, delta_field);\n                    break;\n                case 3:\n                    bounded_field_map_N<3>(field_map, input_data, parameters, delta_field);\n                    break;\n                case 4:\n                    bounded_field_map_N<4>(field_map, input_data, parameters, delta_field);\n                    break;\n                case 5:\n                    bounded_field_map_N<5>(field_map, input_data, parameters, delta_field);\n                    break;\n                case 6:\n                    bounded_field_map_N<6>(field_map, input_data, parameters, delta_field);\n                    break;\n                case 7:\n                    bounded_field_map_N<7>(field_map, input_data, parameters, delta_field);\n                    break;\n                case 8:\n                    bounded_field_map_N<8>(field_map, input_data, parameters, delta_field);\n                    break;\n                default:\n                    throw std::runtime_error(\"Unsupported number of echoes\");\n\n            }\n        }\n\n    }\n}\n\n", "meta": {"hexsha": "4c9533595ba35cc7690a50b3de4af4e1dfd59a31", "size": 5126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/fatwater/bounded_field_map.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "toolboxes/fatwater/bounded_field_map.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolboxes/fatwater/bounded_field_map.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3546099291, "max_line_length": 151, "alphanum_fraction": 0.4648849005, "num_tokens": 1056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.5, "lm_q1q2_score": 0.4352986291679902}}
{"text": "#include \"linear_relations.h\"\n#include <vector>\n#include <hamming/knowledge_of_valid_opening/knowledge_of_valid_opening.h>\n#include <NTL/GF2X.h>\n#include <utils/utils.h>\n\nvoid hamming_metric::linear_relations::initialize_commitments_and_responses(\n        commitments_t *commitments,\n        responses_t *responses) {\n\n    for (int i = 0; i < I; i++) {\n        responses->t0.append(NTL::vec_GF2());\n        responses->t1.append(NTL::vec_GF2());\n        responses->t2.append(NTL::vec_GF2());\n        commitments->r0.append(NTL::vec_GF2());\n        commitments->r1.append(NTL::vec_GF2());\n        commitments->r2.append(NTL::vec_GF2());\n        commitments->c0.append(NTL::vec_GF2());\n        commitments->c1.append(NTL::vec_GF2());\n        commitments->c2.append(NTL::vec_GF2());\n    }\n}\n\nvoid hamming_metric::linear_relations::generate_private_key(\n        private_key_t *private_key,\n        const linear_relation_matrices_t *matrices) {\n\n    {\n        private_key->m.kill();\n        private_key->m.SetLength(I);\n\n        private_key->m[0] = NTL::random_vec_GF2(JAIN_V);\n        private_key->m[1] = NTL::random_vec_GF2(JAIN_V);\n        private_key->m[2] = (matrices->x_0 * private_key->m[0]) + (matrices->x_1 * private_key->m[1]);\n    }\n\n    {\n        private_key->e.kill();\n        private_key->e.SetLength(I);\n\n        for (int i = 0; i < I; i++) {\n            utils::generate_vector_of_weight_w(\n                    private_key->e[i],\n                    JAIN_K,\n                    W);\n        }\n    }\n}\n\nvoid hamming_metric::linear_relations::generate_random_values(\n        random_values_t *random_values,\n        const linear_relation_matrices_t *matrices) {\n\n    {\n        random_values->u.kill();\n        random_values->u.SetLength(I);\n        random_values->v.kill();\n        random_values->v.SetLength(I);\n        random_values->u_v.kill();\n        random_values->u_v.SetLength(I);\n        random_values->f.kill();\n        random_values->f.SetLength(I);\n    }\n    for (int i = 0; i < I; i++) {\n        utils::generate_random_binary_vector(\n                random_values->u[i],\n                JAIN_L);\n        utils::generate_random_binary_vector(\n                random_values->f[i],\n                JAIN_K);\n    }\n\n    for (int i = 0; i < I - 1; i++) {\n        utils::generate_random_binary_vector(\n                random_values->v[i],\n                JAIN_V);\n    }\n\n    random_values->v[2] = (matrices->x_0 * random_values->v[0]) + (matrices->x_1 * random_values->v[1]);\n\n    random_values->u_v = random_values->u;\n    for (int i = 0; i < I; i++) {\n        NTL::append(random_values->u_v[i], random_values->v[i]);\n    }\n}\n\nvoid hamming_metric::linear_relations::generate_public_key(\n        public_key_t *public_key,\n        const private_key_t *private_key) {\n\n    public_key->commitments.kill();\n    public_key->commitments.SetLength(I);\n\n    utils::generate_random_binary_matrix(\n            public_key->A,\n            JAIN_K,\n            JAIN_L + JAIN_V);\n\n    for (int i = 0; i < I; i++) {\n        NTL::vec_GF2 r;\n        utils::generate_random_binary_vector(\n                r,\n                JAIN_L);\n\n        hamming_metric::commitment::generate_commitment(\n                public_key->commitments[i],\n                public_key->A,\n                r,\n                private_key->m[i],\n                private_key->e[i]);\n    }\n}\n\nvoid hamming_metric::linear_relations::generate_revealed_values(\n        revealed_values_t *revealed_values) {\n\n    ::utils::generate_random_binary_matrix(\n            revealed_values->matrices.x_0,\n            JAIN_V,\n            JAIN_V);\n    ::utils::generate_random_binary_matrix(\n            revealed_values->matrices.x_1,\n            JAIN_V,\n            JAIN_V);\n\n    for(int i = 0; i < I; i++) {\n\n        revealed_values->P.append(NTL::mat_GF2());\n\n        utils::create_permutation_matrix(\n                revealed_values->P[i],\n                JAIN_K);\n    }\n\n}\n\nvoid hamming_metric::linear_relations::generate_commitments_and_responses(\n        responses_t *responses,\n        commitments_t *commitments,\n        const random_values_t *random_values,\n        const revealed_values_t *revealed_values,\n        const public_key_t *public_key,\n        const private_key_t *private_key) {\n\n    for (int i = 0; i < I; i++) {\n        hamming_metric::knowledge_of_valid_opening::generate_commitment_and_response_0(\n                commitments->c0[i],\n                commitments->r0[i],\n                responses->t0[i],\n                random_values->u_v[i],\n                public_key->A,\n                random_values->f[i]);\n\n        hamming_metric::knowledge_of_valid_opening::generate_commitment_and_response_1(\n                commitments->c1[i],\n                commitments->r1[i],\n                responses->t1[i],\n                public_key->A,\n                revealed_values->P[i],\n                random_values->f[i]);\n\n        hamming_metric::knowledge_of_valid_opening::generate_commitment_and_response_2(\n                commitments->c2[i],\n                commitments->r2[i],\n                responses->t2[i],\n                public_key->A,\n                revealed_values->P[i],\n                random_values->f[i],\n                private_key->e[i]);\n    }\n}\n\nint hamming_metric::linear_relations::verify_0(\n        const NTL::Vec<NTL::vec_GF2> &c0,\n        const NTL::Vec<NTL::vec_GF2> &r0,\n        const NTL::Vec<NTL::vec_GF2> &t0,\n        const NTL::Vec<NTL::vec_GF2> &c1,\n        const NTL::Vec<NTL::vec_GF2> &r1,\n        const NTL::Vec<NTL::vec_GF2> &t1,\n        const NTL::Vec<NTL::mat_GF2> &P,\n        const NTL::mat_GF2 &x_0,\n        const NTL::mat_GF2 &x_1,\n        const public_key_t *public_key) {\n\n    for(int i = 0; i < I; i++) {\n        auto _t0 = utils::encode_binary_vector(t0[i], JAIN_V);\n        auto _t1 = utils::encode_binary_vector(t1[i], JAIN_V);\n\n        if (hamming_metric::commitment::verify(\n                c0[i],\n                public_key->A,\n                r0[i],\n                _t0) != 0) {\n            std::cout << \"Linear Relations. Verification failed on ch = 0 and c0\" << std::endl;\n            return 1;\n        }\n\n        if (hamming_metric::commitment::verify(\n                c1[i],\n                public_key->A,\n                r1[i],\n                _t1) != 0) {\n            std::cout << \"Linear Relations. Verification failed on ch = 0 and c1\" << std::endl;\n            return 1;\n        }\n    }\n\n    NTL::Vec<NTL::vec_GF2> results;\n    for (int i = 0; i < I; i++) {\n        NTL::vec_GF2 result;\n\n        if (utils::solve_equation(\n                result,\n                public_key->A,\n                t0[i] + (NTL::inv(P[i]) * t1[i])) != 0) {\n            std::cout << \"No Solutions\" << std::endl;\n            return 1;\n        }\n        results.append(result);\n    }\n\n    NTL::Vec<NTL::vec_GF2> b;\n    for (int i = 0; i < I; i++) {\n        {\n            b.append(NTL::vec_GF2());\n            b[i].SetLength(JAIN_V);\n        }\n\n        for (int j = 0; j < JAIN_V; j++) {\n            b[i][j] = results[i].at(j + JAIN_L);\n        }\n    }\n\n    if (NTL::IsZero(b[2] + ((x_0 * b[0]) + (x_1 * b[1])))) {\n        return 0;\n    } else {\n        std::cout << b[2] << std::endl;\n        std::cout << ((b[0] * x_0) + (b[1] * x_1)) << std::endl;\n        return 1;\n    }\n\n}\n\nint hamming_metric::linear_relations::verify_1(\n        const NTL::Vec<NTL::vec_GF2> &c0,\n        const NTL::Vec<NTL::vec_GF2> &r0,\n        const NTL::Vec<NTL::vec_GF2> &t0,\n        const NTL::Vec<NTL::vec_GF2> &c2,\n        const NTL::Vec<NTL::vec_GF2> &r2,\n        const NTL::Vec<NTL::vec_GF2> &t2,\n        const NTL::Vec<NTL::mat_GF2> &P,\n        const NTL::mat_GF2 &x_0,\n        const NTL::mat_GF2 &x_1,\n        const public_key_t *public_key) {\n\n    for (int i = 0; i < I; i++) {\n        auto _t0 = utils::encode_binary_vector(t0[i], JAIN_V);\n        auto _t2 = utils::encode_binary_vector(t2[i], JAIN_V);\n\n        if (hamming_metric::commitment::verify(\n                c0[i],\n                public_key->A,\n                r0[i],\n                _t0) != 0) {\n            std::cout << \"Linear Relations. Verification failed on ch = 1 and c0\" << std::endl;\n            return 1;\n        }\n\n        if (hamming_metric::commitment::verify(\n                c2[i],\n                public_key->A,\n                r2[i],\n                _t2) != 0) {\n            std::cout << \"Linear Relations. Verification failed on ch = 1 and c2\" << std::endl;\n            return 1;\n        }\n    }\n\n    NTL::Vec<NTL::vec_GF2> results;\n    for (int i = 0; i < 3; i++) {\n        NTL::vec_GF2 result;\n\n        if (utils::solve_equation(\n                result,\n                public_key->A,\n                t0[i] + (NTL::inv(P[i]) * t2[i]) + public_key->commitments[i]) != 0) {\n            std::cout << \"No Solutions\" << std::endl;\n            return 1;\n        }\n        results.append(result);\n    }\n\n    NTL::Vec<NTL::vec_GF2> d;\n    for (int i = 0; i < 3; i++) {\n        {\n            d.append(NTL::vec_GF2());\n            d[i].SetLength(JAIN_V);\n        }\n\n        for (int j = 0; j < JAIN_V; j++) {\n            d[i][j] = results[i].at(j + JAIN_L);\n        }\n    }\n\n    if (NTL::IsZero(d[2] + ((x_0 * d[0]) + (x_1 * d[1])))) {\n        return 0;\n    } else {\n        std::cout << d[2] << std::endl;\n        std::cout << ((d[2] + ((x_0 * d[0]) + (x_1 * d[1])))) << std::endl;\n        return 1;\n    }\n}\n\nint hamming_metric::linear_relations::verify_2(\n        const NTL::Vec<NTL::vec_GF2> &c1,\n        const NTL::Vec<NTL::vec_GF2> &r1,\n        const NTL::Vec<NTL::vec_GF2> &t1,\n        const NTL::Vec<NTL::vec_GF2> &c2,\n        const NTL::Vec<NTL::vec_GF2> &r2,\n        const NTL::Vec<NTL::vec_GF2> &t2,\n        const public_key_t *public_key) {\n\n    for (int i = 0; i < I; i++) {\n        auto _t1 = utils::encode_binary_vector(t1[i], JAIN_V);\n        auto _t2 = utils::encode_binary_vector(t2[i], JAIN_V);\n\n        if (hamming_metric::commitment::verify(\n                c1[i],\n                public_key->A,\n                r1[i],\n                _t1) != 0) {\n            std::cout << \"Linear Relations. Verification failed on ch = 2 and c1\" << std::endl;\n            return 1;\n        }\n\n        if (hamming_metric::commitment::verify(\n                c2[i],\n                public_key->A,\n                r2[i],\n                _t2) != 0) {\n            std::cout << \"Linear Relations. Verification failed on ch = 2 and c2\" << std::endl;\n            return 1;\n        }\n\n        if(NTL::weight(t1[i] + t2[i]) != W) {\n            std::cout << \"Invalid weight\" << std::endl;\n            return 1;\n        }\n\n    }\n\n    return 0;\n}", "meta": {"hexsha": "ba50933c5f1d5a804b8a59afae57643850c748e6", "size": 10601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hamming/linear_relations/linear_relations.cpp", "max_stars_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_stars_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hamming/linear_relations/linear_relations.cpp", "max_issues_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_issues_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hamming/linear_relations/linear_relations.cpp", "max_forks_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_forks_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-16T07:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-16T07:21:24.000Z", "avg_line_length": 30.0311614731, "max_line_length": 104, "alphanum_fraction": 0.5144797661, "num_tokens": 2996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4352718161384436}}
{"text": "/*\n\nCandyPoker\nhttps://github.com/sweeterthancandy/CandyPoker\n\nMIT License\n\nCopyright (c) 2019 Gerry Candy\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*/\n#include \"ps/heads_up_solver.h\"\n#include \"ps/heads_up.h\"\n\n#include <numeric>\n#include <boost/timer/timer.hpp>\n#include <thread>\n#include <future>\n\nnamespace ps{\n\n\n/*\n                \n                                        <>\n                                 ______/  \\______\n                                /                \\\n                             <SB Push>         <SB Fold>\n                         ____/     \\_____\n                        /                \\\n                    <BB Call>          <BB Fold>\n\n\n                               +-----------+\n                               |Total Value|\n                               +-----------+\n                                \n                        <SB fold>           = -sb\n                        <SB push | BB fold> = bb\n                        <SB push | BB call> = 2 S Eq - S  \n                                            = S( 2 Eq - 1 )\n\n */\n\n// given hands\n//    {sb_id, bb_id}\ndouble calc_detail(calc_context& ctx)\n{\n        /*\n                                         <root>\n                                    ______/  \\______\n                                   /                \\\n                              <sb_push>          <sb_fold>\n                         ____/        \\_____\n                        /                   \\\n               <sb_push_bb_call>      <sb_push_bb_fold>\n               \n\n         */\n        struct sb_push{\n                struct sb_push__bb_call{\n                        double operator()(calc_context& ctx)const{\n                                auto equity = ctx.cec->visit_boards(std::vector<ps::holdem_class_id>{ ctx.sb_id,ctx.bb_id }).equity();\n                                return ctx.eff_stack * ( 2 * equity - 1 );\n                        }\n                };\n                struct sb_push__bb_fold{\n                        double operator()(calc_context& ctx)const{\n                                return +ctx.bb;\n                        }\n                };\n                double operator()(calc_context& ctx)const{\n                        if( ctx.bb_call_strat[ctx.bb_id] == 0.0 )\n                                return bb_fold_(ctx);\n                        return \n                                (  ctx.bb_call_strat[ctx.bb_id]) * bb_call_(ctx) +\n                                (1-ctx.bb_call_strat[ctx.bb_id]) * bb_fold_(ctx);\n                }\n                sb_push__bb_call bb_call_;\n                sb_push__bb_fold bb_fold_;\n        };\n        struct sb_fold{\n                double operator()(calc_context& ctx)const{\n                        return -ctx.sb;\n                }\n        };\n        struct root{\n                double operator()(calc_context& ctx)const{\n\n                        // short-circuit\n                        if( ctx.sb_push_strat[ctx.sb_id] == 0.0 )\n                                return sb_fold_(ctx);\n\n                        return \n                                (  ctx.sb_push_strat[ctx.sb_id]) * sb_push_(ctx) +\n                                (1-ctx.sb_push_strat[ctx.sb_id]) * sb_fold_(ctx);\n                }\n                sb_push sb_push_;\n                sb_fold sb_fold_;\n        };\n        static root root_;\n        return root_(ctx);\n}\ndouble calc( class_equity_cacher& cec,\n                   hu_strategy const& sb_push_strat,\n                   hu_strategy const& bb_call_strat,\n                   double eff_stack, double sb, double bb)\n{\n        calc_context ctx = {\n                &cec,\n                sb_push_strat,\n                bb_call_strat,\n                eff_stack,\n                sb,\n                bb,\n                0,\n                0\n        };\n        return calc(ctx);\n}\ndouble calc(calc_context& ctx){\n        double sigma{0.0};\n        for(ctx.sb_id = 0; ctx.sb_id != 169;++ctx.sb_id){\n                for(ctx.bb_id = 0; ctx.bb_id != 169;++ctx.bb_id){\n                        auto p =  holdem_class_decl::prob(ctx.sb_id, ctx.bb_id) ;\n                        sigma += calc_detail(ctx) * p;\n                }\n                        //PRINT(sigma);\n        }\n        return sigma;\n}\n\n\nhu_strategy solve_hu_push_fold_bb_maximal_exploitable(ps::class_equity_cacher& cec,\n                                               hu_strategy const& sb_push_strat,\n                                               double eff_stack, double sb, double bb)\n{\n        struct context{\n                class_equity_cacher* cec;\n                hu_strategy sb_push_strat;\n                hu_strategy bb_call_strat;\n                double eff_stack;\n                double sb;\n                double bb;\n                holdem_class_id bb_id;\n                \n                hu_strategy debug;\n        };\n        /*\n                                         <solver>\n                                    ______/  \\______\n                                   /                \\\n                              <call>              <fold>\n\n         */\n        struct fold{\n                double operator()(context& ctx)const{\n                        return 0;\n                        //return -ctx.bb;\n                }\n        };\n        struct call{\n                double operator()(context& ctx)const{\n                        hu_fresult_t res;\n                        for(holdem_class_id sb_id{0}; sb_id != 169;++sb_id){\n                                hu_fresult_t tmp{ctx.cec->visit_boards(std::vector<ps::holdem_class_id>{ ctx.bb_id, sb_id })};\n                                auto weight = ctx.sb_push_strat[sb_id];\n                                \n                                tmp.times(weight);\n                                res.append(tmp);\n                                \n\n                        }\n\n                        // edge case, can return anything here probably\n                        if( res.sigma() == 0 )\n                                return 0.0;\n                        \n                        //PRINT_SEQ((ctx.eff_stack)(ctx.sb)(ctx.bb));\n\n                        double ev{ ctx.eff_stack * 2 * res.equity() - ( ctx.eff_stack - ctx.bb ) };\n                        //         \\----equity of pot to win -----/   \\------cost of bet-------/\n\n                        ctx.debug[ctx.bb_id] = ev;\n                        return ev;\n                }\n        };\n        struct solver{\n                void operator()(context& ctx)const{\n                        //ctx.debug[ctx.bb_id] = ev_call;\n                        if( call_(ctx) > fold_(ctx) ){\n                                ctx.bb_call_strat[ctx.bb_id] = 1.0;\n                        }\n                }\n        private:\n                call call_;\n                fold fold_;\n        };\n\n        context ctx = {\n                &cec,\n                sb_push_strat,\n                hu_strategy{0.0},\n                eff_stack,\n                sb,\n                bb,\n                0\n        };\n        solver solver_;\n\n\n        for(holdem_class_id bb_id{0}; bb_id != 169;++bb_id){\n                ctx.bb_id = bb_id;\n                solver_(ctx);\n        }\n        //std::cout << \"HERE is BB Call diff\\n\";\n        //ctx.debug.display();\n        #if 0\n        std::cout << \"HERE is BB Strat\\n\";\n        ctx.bb_call_strat.display();\n        #endif\n        return std::move(ctx.bb_call_strat);\n} \nhu_strategy solve_hu_push_fold_sb_maximal_exploitable(ps::class_equity_cacher& cec,\n                                               hu_strategy const& bb_call_strat,\n                                               double eff_stack, double sb, double bb)\n{\n        struct context{\n                class_equity_cacher* cec;\n                hu_strategy sb_push_strat;\n                hu_strategy bb_call_strat;\n                double eff_stack;\n                double sb;\n                double bb;\n                holdem_class_id bb_id;\n                holdem_class_id sb_id;\n                hu_strategy debug;\n        };\n        struct sb_push__bb_call{\n                double operator()(context& ctx)const{\n                        auto equity = ctx.cec->visit_boards(std::vector<ps::holdem_class_id>{ ctx.sb_id, ctx.bb_id }).equity();\n                        return ctx.eff_stack * 2 *  equity - ( ctx.eff_stack -  ctx.sb );\n                        //     \\- reuity of pot to win  -/   \\--- cost of bet  --------/\n                }\n        };\n        struct sb_push__bb_fold{\n                double operator()(context& ctx)const{\n                        return ctx.sb + ctx.bb;\n                }\n        };\n        #if 0\n        struct sb_push{\n                double operator()(context& ctx)const{\n\n                        hu_fresult_t agg;\n                        for(ctx.bb_id = 0; ctx.bb_id != 169;++ctx.bb_id){\n                                agg.append(ctx.cec->visit_boards(std::vector<ps::holdem_class_id>{ ctx.sb_id, ctx.bb_id }));\n                        }\n                        auto ret =  ctx.eff_stack * 2 *  agg.equity() - ( ctx.eff_stack -  ctx.sb ) ;\n                        PRINT_SEQ((ctx.eff_stack)(agg.equity())(ctx.sb)( ctx.eff_stack * 2 *  agg.equity() - ( ctx.eff_stack -  ctx.sb ) ));\n                        ctx.debug[ctx.sb_id] = ret;\n                        return ret;\n                }\n        private:\n                sb_push__bb_call bb_call_;\n                sb_push__bb_fold bb_fold_;\n        };\n        #else\n        struct sb_push{\n                double operator()(context& ctx)const{\n                        double sigma{0.0};\n                        double factor{0.0};\n\n                        for(ctx.bb_id = 0; ctx.bb_id != 169;++ctx.bb_id){\n                                auto ev_bb_call =  bb_call_(ctx) ;\n                                auto ev_bb_fold =  bb_fold_(ctx) ;\n                                //PRINT_SEQ((ev_bb_call)(ev_bb_fold));\n                                double ev_bb{\n                                           ctx.bb_call_strat[ctx.bb_id]  * ev_bb_call +\n                                        (1-ctx.bb_call_strat[ctx.bb_id]) * ev_bb_fold};\n                                auto weight = holdem_class_decl::weight(ctx.sb_id, ctx.bb_id);\n                                sigma  += weight * ev_bb;\n                                factor += weight;\n                        }\n                        sigma /= factor;\n\n                        return sigma;\n                }\n        private:\n                sb_push__bb_call bb_call_;\n                sb_push__bb_fold bb_fold_;\n        };\n        #endif\n        struct sb_fold{\n               double operator()(context& ctx)const{\n                        //return ctx.sb;\n                        return 0;\n                }\n        };\n        struct solver{\n                void operator()(context& ctx)const{\n                        auto ev_push =  sb_push_(ctx) ;\n                        auto ev_fold =  sb_fold_(ctx) ;\n                        //PRINT_SEQ((ev_push)(ev_fold));\n                        if( ev_push > ev_fold )\n                                ctx.sb_push_strat[ctx.sb_id] = 1.0;\n                }\n        private:\n                sb_push sb_push_;\n                sb_fold sb_fold_;\n        };\n        context ctx = {\n                &cec,\n                hu_strategy{0.0},\n                bb_call_strat,\n                eff_stack,\n                sb,\n                bb,\n                0,\n                0\n        };\n        solver solver_;\n\n        for(ctx.sb_id = 0; ctx.sb_id != 169;++ctx.sb_id){\n                solver_(ctx);\n        }\n        \n        //std::cout << \"HERE is SB Push diff\\n\";\n        ctx.debug.display();\n        return std::move(ctx.sb_push_strat);\n} \n\nhu_strategy solve_hu_push_fold_sb(ps::class_equity_cacher& cec,\n                           double eff_stack, double sb, double bb){\n        double alpha{0.3};\n        hu_strategy sb_strat{1.0};\n\n        std::set< hu_strategy > circular_set;\n\n        for(size_t i=0;;++i){\n                boost::timer::auto_cpu_timer at;\n\n                auto bb_me = solve_hu_push_fold_bb_maximal_exploitable(cec,\n                                                                     sb_strat,\n                                                                     eff_stack,\n                                                                     sb,\n                                                                     bb);\n\n                double ev = calc(cec, sb_strat, bb_me, eff_stack, sb, bb);\n\n                auto sb_me = solve_hu_push_fold_sb_maximal_exploitable(cec,\n                                                                       bb_me,\n                                                                       eff_stack,\n                                                                       sb,\n                                                                       bb);\n                #if 0\n                auto sb_me{solve_hu_push_fold_sb_maximal_exploitable(cec,\n                                                                     bb_me,\n                                                                     eff_stack,\n                                                                     sb,\n                                                                     bb)};\n                auto sb_me_alt{solve_hu_push_fold_sb_maximal_exploitable__ev(cec,\n                                                                     bb_me,\n                                                                     eff_stack,\n                                                                     sb,\n                                                                     bb)};\n                PRINT( (sb_me - sb_me_alt).norm() );\n                (sb_me - sb_me_alt).display();\n                #endif\n                \n                double ev_{calc(cec, sb_me, bb_me, eff_stack, sb, bb)};\n\n                std::cout << \"BB COUNTER\\n\";\n                bb_me.display();\n                std::cout << \"SB COUNTER COUNTER\\n\";\n                sb_me.display();\n\n                auto sb_next =  sb_strat * ( 1 - alpha) + sb_me * alpha ;\n                auto sb_norm =  (sb_next - sb_strat).norm() ;\n                sb_strat = std::move(sb_next);\n                double ev_d{ std::fabs(ev - ev_) };\n                \n                PRINT_SEQ((sb_norm)(ev)(ev_)(ev_d));\n\n                if( circular_set.count(sb_strat) ){\n                        std::cerr << \"ok circular!\\n\";\n                        break;\n                }\n                circular_set.insert(sb_strat);\n\n                sb_strat.display();\n\n                #if 0\n                if( ( ev_d ) < 1e-3 ){\n                        std::cout << \"_ev_d_break_\\n\";\n                        break;\n                }\n                #endif\n                if( ( sb_norm ) < 1e-5 ){\n                        std::cout << \"_break_\\n\";\n                        break;\n                }\n                if( i == 50){\n                        std::cout << \"_i_break_\\n\";\n                        break;\n                }\n        }\n        return std::move(sb_strat);\n}\n\n\nvoid make_heads_up_table(){\n        using namespace ps;\n\n        equity_cacher ec;\n        ec.load(\"cache.bin\");\n        class_equity_cacher cec(ec);\n        cec.load(\"hc_cache.bin\");\n\n        double bb{1.0};\n        double sb{0.5};\n                \n        hu_strategy sb_table{0.0};\n        hu_strategy bb_table{0.0};\n\n        std::vector<\n                std::tuple<\n                        double, // stack\n                        std::future<hu_strategy>\n                >\n        > results;\n\n        for( double eff_stack{4.0};eff_stack < 10;eff_stack += 1){\n\n                auto work = [&cec, eff_stack,sb,bb]()->hu_strategy{\n                        auto sb_strat = solve_hu_push_fold_sb(cec, eff_stack, sb, bb);\n                        return std::move(sb_strat);\n                };\n                std::packaged_task<hu_strategy()> pt(work);\n                results.emplace_back( eff_stack, pt.get_future());\n                std::thread{std::move(pt)}.detach();\n\n\n\n        }\n        for(auto& r : results ){\n                std::get<1>(r).wait();\n                auto eff_stack =  std::get<0>(r) ;\n                auto sb_strat =  std::get<1>(r).get() ;\n                auto bb_strat = solve_hu_push_fold_bb_maximal_exploitable(cec,\n                                                                          sb_strat,\n                                                                          eff_stack,\n                                                                          sb,\n                                                                          bb);\n                for(size_t i{0};i!=169;++i){\n                        if( sb_strat[i] < 1e-3 )\n                                continue;\n                        if( std::fabs(1.0 - sb_strat[i]) < 1e-3 )\n                                sb_table[i] = eff_stack;\n                }\n                for(size_t i{0};i!=169;++i){\n                        if( bb_strat[i] < 1e-3 )\n                                continue;\n                        if( std::fabs(1.0 - bb_strat[i]) < 1e-3 )\n                                bb_table[i] = eff_stack;\n                }\n        }\n        std::cout << \"------------ sb push ----------------\\n\";\n        sb_table.display();\n        std::cout << \"------------ bb call ----------------\\n\";\n        bb_table.display();\n\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n} // ps\n", "meta": {"hexsha": "6b07e600391bdf84c8c35856a001688356b51357", "size": 18425, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Trash/heads_up_solver.cpp", "max_stars_repo_name": "sweeterthancandy/CandyPoker", "max_stars_repo_head_hexsha": "53dfcc92402492739a2300847aeb298d389d546a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T12:57:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T10:41:18.000Z", "max_issues_repo_path": "Trash/heads_up_solver.cpp", "max_issues_repo_name": "sweeterthancandy/CandyPoker", "max_issues_repo_head_hexsha": "53dfcc92402492739a2300847aeb298d389d546a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Trash/heads_up_solver.cpp", "max_forks_repo_name": "sweeterthancandy/CandyPoker", "max_forks_repo_head_hexsha": "53dfcc92402492739a2300847aeb298d389d546a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-01T06:05:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-01T06:05:52.000Z", "avg_line_length": 36.3412228797, "max_line_length": 140, "alphanum_fraction": 0.3880054274, "num_tokens": 3504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303087996143, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4352718107039157}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// This file was modified by Oracle on 2021.\n// Modifications copyright (c) 2021 Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ARITHMETIC_ARITHMETIC_HPP\n#define BOOST_GEOMETRY_ARITHMETIC_ARITHMETIC_HPP\n\n#include <functional>\n\n#include <boost/call_traits.hpp>\n#include <boost/concept/requires.hpp>\n\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/geometries/concepts/point_concept.hpp>\n#include <boost/geometry/util/algorithm.hpp>\n#include <boost/geometry/util/select_coordinate_type.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\n\ntemplate <typename Point>\nstruct param\n{\n    typedef typename boost::call_traits\n        <\n            typename coordinate_type<Point>::type\n        >::param_type type;\n};\n\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n/*!\n    \\brief Adds the same value to each coordinate of a point\n    \\ingroup arithmetic\n    \\details\n    \\tparam Point \\tparam_point\n    \\param p point\n    \\param value value to add\n */\ntemplate <typename Point>\ninline void add_value(Point& p, typename detail::param<Point>::type value)\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<Point>) );\n\n    detail::for_each_dimension<Point>([&](auto index)\n    {\n        set<index>(p, get<index>(p) + value);\n    });\n}\n\n/*!\n    \\brief Adds a point to another\n    \\ingroup arithmetic\n    \\details The coordinates of the second point will be added to those of the first point.\n             The second point is not modified.\n    \\tparam Point1 \\tparam_point\n    \\tparam Point2 \\tparam_point\n    \\param p1 first point\n    \\param p2 second point\n */\ntemplate <typename Point1, typename Point2>\ninline void add_point(Point1& p1, Point2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<Point1>) );\n    BOOST_CONCEPT_ASSERT( (concepts::ConstPoint<Point2>) );\n\n    detail::for_each_dimension<Point1>([&](auto index)\n    {\n        using calc_t = typename select_coordinate_type<Point1, Point2>::type;\n        set<index>(p1, calc_t(get<index>(p1)) + calc_t(get<index>(p2)));\n    });\n}\n\n/*!\n    \\brief Subtracts the same value to each coordinate of a point\n    \\ingroup arithmetic\n    \\details\n    \\tparam Point \\tparam_point\n    \\param p point\n    \\param value value to subtract\n */\ntemplate <typename Point>\ninline void subtract_value(Point& p, typename detail::param<Point>::type value)\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<Point>) );\n\n    detail::for_each_dimension<Point>([&](auto index)\n    {\n        set<index>(p, get<index>(p) - value);\n    });\n}\n\n/*!\n    \\brief Subtracts a point to another\n    \\ingroup arithmetic\n    \\details The coordinates of the second point will be subtracted to those of the first point.\n             The second point is not modified.\n    \\tparam Point1 \\tparam_point\n    \\tparam Point2 \\tparam_point\n    \\param p1 first point\n    \\param p2 second point\n */\ntemplate <typename Point1, typename Point2>\ninline void subtract_point(Point1& p1, Point2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<Point1>) );\n    BOOST_CONCEPT_ASSERT( (concepts::ConstPoint<Point2>) );\n\n    detail::for_each_dimension<Point1>([&](auto index)\n    {\n        using calc_t = typename select_coordinate_type<Point1, Point2>::type;\n        set<index>(p1, calc_t(get<index>(p1)) - calc_t(get<index>(p2)));\n    });\n}\n\n/*!\n    \\brief Multiplies each coordinate of a point by the same value\n    \\ingroup arithmetic\n    \\details\n    \\tparam Point \\tparam_point\n    \\param p point\n    \\param value value to multiply by\n */\ntemplate <typename Point>\ninline void multiply_value(Point& p, typename detail::param<Point>::type value)\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<Point>) );\n\n    detail::for_each_dimension<Point>([&](auto index)\n    {\n        set<index>(p, get<index>(p) * value);\n    });\n}\n\n/*!\n    \\brief Multiplies a point by another\n    \\ingroup arithmetic\n    \\details The coordinates of the first point will be multiplied by those of the second point.\n             The second point is not modified.\n    \\tparam Point1 \\tparam_point\n    \\tparam Point2 \\tparam_point\n    \\param p1 first point\n    \\param p2 second point\n    \\note This is *not* a dot, cross or wedge product. It is a mere field-by-field multiplication.\n */\ntemplate <typename Point1, typename Point2>\ninline void multiply_point(Point1& p1, Point2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<Point1>) );\n    BOOST_CONCEPT_ASSERT( (concepts::ConstPoint<Point2>) );\n\n    detail::for_each_dimension<Point1>([&](auto index)\n    {\n        using calc_t = typename select_coordinate_type<Point1, Point2>::type;\n        set<index>(p1, calc_t(get<index>(p1)) * calc_t(get<index>(p2)));\n    });\n}\n\n/*!\n    \\brief Divides each coordinate of the same point by a value\n    \\ingroup arithmetic\n    \\details\n    \\tparam Point \\tparam_point\n    \\param p point\n    \\param value value to divide by\n */\ntemplate <typename Point>\ninline void divide_value(Point& p, typename detail::param<Point>::type value)\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<Point>) );\n\n    detail::for_each_dimension<Point>([&](auto index)\n    {\n        set<index>(p, get<index>(p) / value);\n    });\n}\n\n/*!\n    \\brief Divides a point by another\n    \\ingroup arithmetic\n    \\details The coordinates of the first point will be divided by those of the second point.\n             The second point is not modified.\n    \\tparam Point1 \\tparam_point\n    \\tparam Point2 \\tparam_point\n    \\param p1 first point\n    \\param p2 second point\n */\ntemplate <typename Point1, typename Point2>\ninline void divide_point(Point1& p1, Point2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<Point1>) );\n    BOOST_CONCEPT_ASSERT( (concepts::ConstPoint<Point2>) );\n\n    detail::for_each_dimension<Point1>([&](auto index)\n    {\n        using calc_t = typename select_coordinate_type<Point1, Point2>::type;\n        set<index>(p1, calc_t(get<index>(p1)) / calc_t(get<index>(p2)));\n    });\n}\n\n/*!\n    \\brief Assign each coordinate of a point the same value\n    \\ingroup arithmetic\n    \\details\n    \\tparam Point \\tparam_point\n    \\param p point\n    \\param value value to assign\n */\ntemplate <typename Point>\ninline void assign_value(Point& p, typename detail::param<Point>::type value)\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<Point>) );\n\n    detail::for_each_dimension<Point>([&](auto index)\n    {\n        set<index>(p, value);\n    });\n}\n\n/*!\n    \\brief Assign a point with another\n    \\ingroup arithmetic\n    \\details The coordinates of the first point will be assigned those of the second point.\n             The second point is not modified.\n    \\tparam Point1 \\tparam_point\n    \\tparam Point2 \\tparam_point\n    \\param p1 first point\n    \\param p2 second point\n */\ntemplate <typename Point1, typename Point2>\ninline void assign_point(Point1& p1, Point2 const& p2)\n{\n    BOOST_CONCEPT_ASSERT( (concepts::Point<Point1>) );\n    BOOST_CONCEPT_ASSERT( (concepts::ConstPoint<Point2>) );\n\n    detail::for_each_dimension<Point1>([&](auto index)\n    {\n        set<index>(p1, get<index>(p2));\n    });\n}\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ARITHMETIC_ARITHMETIC_HPP\n", "meta": {"hexsha": "bf09e7a1cb03b31aab6af4775e6a01b1bb7b9ebe", "size": 7764, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/arithmetic/arithmetic.hpp", "max_stars_repo_name": "pranavgo/RRT", "max_stars_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "boost/geometry/arithmetic/arithmetic.hpp", "max_issues_repo_name": "pranavgo/RRT", "max_issues_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "boost/geometry/arithmetic/arithmetic.hpp", "max_forks_repo_name": "pranavgo/RRT", "max_forks_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 28.9701492537, "max_line_length": 98, "alphanum_fraction": 0.6926841834, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.43525744707452707}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2011 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Author: Katharina Kormann, Martin Kronbichler, Uppsala University, 2011-2012 \n */ \n\n\n\n// deal.II库中的必要文件。\n\n#include <deal.II/base/logstream.h> \n#include <deal.II/base/utilities.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/conditional_ostream.h> \n#include <deal.II/base/timer.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/dofs/dof_tools.h> \n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/distributed/tria.h> \n\n// 这包括用于有效实现无矩阵方法的数据结构。\n\n#include <deal.II/lac/la_parallel_vector.h> \n#include <deal.II/matrix_free/matrix_free.h> \n#include <deal.II/matrix_free/fe_evaluation.h> \n\n#include <fstream> \n#include <iostream> \n#include <iomanip> \n\nnamespace Step48 \n{ \n  using namespace dealii; \n\n// 我们首先定义了两个全局变量，以便在一个地方收集所有需要改变的参数。一个是尺寸，一个是有限元度。维度在主函数中是作为实际类的模板参数使用的（就像所有其他deal.II程序一样），而有限元的度数则更为关键，因为它是作为模板参数传递给Sine-Gordon算子的实现。因此，它需要成为一个编译时常数。\n\n  const unsigned int dimension = 2; \n  const unsigned int fe_degree = 4; \n// @sect3{SineGordonOperation}  \n\n//  <code>SineGordonOperation</code> 类实现了每个时间步骤中需要的基于单元的操作。这个非线性操作可以在 <code>MatrixFree</code> 类的基础上直接实现，与线性操作在这个实现的有限元算子应用中的处理方式相同。我们对该类应用了两个模板参数，一个是尺寸，一个是有限元的程度。这与deal.II中的其他函数不同，其中只有维度是模板参数。这对于为 @p FEEvaluation 中的内循环提供关于循环长度等的信息是必要的，这对于效率是至关重要的。另一方面，这使得将度数作为一个运行时参数来实现更具挑战性。\n\n  template <int dim, int fe_degree> \n  class SineGordonOperation \n  { \n  public: \n    SineGordonOperation(const MatrixFree<dim, double> &data_in, \n                        const double                   time_step); \n\n    void apply(LinearAlgebra::distributed::Vector<double> &dst, \n               const std::vector<LinearAlgebra::distributed::Vector<double> *> \n                 &src) const; \n\n  private: \n    const MatrixFree<dim, double> &            data; \n    const VectorizedArray<double>              delta_t_sqr; \n    LinearAlgebra::distributed::Vector<double> inv_mass_matrix; \n\n    void local_apply( \n      const MatrixFree<dim, double> &                                  data, \n      LinearAlgebra::distributed::Vector<double> &                     dst, \n      const std::vector<LinearAlgebra::distributed::Vector<double> *> &src, \n      const std::pair<unsigned int, unsigned int> &cell_range) const; \n  }; \n\n//  @sect4{SineGordonOperation::SineGordonOperation}  \n\n// 这是SineGordonOperation类的构造函数。它接收一个对MatrixFree的引用，该引用持有问题信息和时间步长作为输入参数。初始化程序设置了质量矩阵。由于我们使用Gauss-Lobatto元素，质量矩阵是一个对角矩阵，可以存储为一个矢量。利用FEEvaluation提供的数据结构，质量矩阵对角线的计算很容易实现。只要在所有的单元格批次上循环，即由于SIMD矢量化的单元格集合，并通过使用 <code>integrate</code> 函数与 @p true 参数在数值的槽上对所有正交点上常一的函数进行积分。最后，我们将对角线条目进行反转，以便在每个时间步长中直接获得反质量矩阵。\n\n  template <int dim, int fe_degree> \n  SineGordonOperation<dim, fe_degree>::SineGordonOperation( \n    const MatrixFree<dim, double> &data_in, \n    const double                   time_step) \n    : data(data_in) \n    , delta_t_sqr(make_vectorized_array(time_step * time_step)) \n  { \n    data.initialize_dof_vector(inv_mass_matrix); \n\n    FEEvaluation<dim, fe_degree> fe_eval(data); \n    const unsigned int           n_q_points = fe_eval.n_q_points; \n\n    for (unsigned int cell = 0; cell < data.n_cell_batches(); ++cell) \n      { \n        fe_eval.reinit(cell); \n        for (unsigned int q = 0; q < n_q_points; ++q) \n          fe_eval.submit_value(make_vectorized_array(1.), q); \n        fe_eval.integrate(EvaluationFlags::values); \n        fe_eval.distribute_local_to_global(inv_mass_matrix); \n      } \n\n    inv_mass_matrix.compress(VectorOperation::add); \n    for (unsigned int k = 0; k < inv_mass_matrix.locally_owned_size(); ++k) \n      if (inv_mass_matrix.local_element(k) > 1e-15) \n        inv_mass_matrix.local_element(k) = \n          1. / inv_mass_matrix.local_element(k); \n      else \n        inv_mass_matrix.local_element(k) = 1; \n  } \n\n//  @sect4{SineGordonOperation::local_apply}  \n\n// 这个算子实现了程序的核心操作，即对正弦-戈登问题的非线性算子进行单元范围的积分。其实现是基于  step-37  中的FEEvaluation类。由于Gauss-Lobatto元素的特殊结构，某些操作变得更加简单，特别是正交点上的形状函数值的评估，这只是单元自由度值的注入。MatrixFree类在初始化时检测了正交点上有限元的可能结构，然后由FEEvaluation自动用于选择最合适的数值核。\n\n// 我们要为时间步进例程评估的非线性函数包括当前时间的函数值 @p current 以及前一个时间步进的值 @p old. 这两个值都在源向量集合 @p src, 中传递给运算器，该集合只是一个指向实际解向量的 <tt>std::vector</tt> 指针。这种将多个源向量收集到一起的结构是必要的，因为 @p MatrixFree 中的单元格循环正好需要一个源向量和一个目的向量，即使我们碰巧使用了很多向量，比如本例中的两个。请注意，单元格循环接受任何有效的输入和输出类，这不仅包括向量，还包括一般的数据类型。 然而，只有在遇到收集这些向量的 LinearAlgebra::distributed::Vector<Number> 或 <tt>std::vector</tt> 时，它才会在循环的开始和结束时调用由于MPI而交换幽灵数据的函数。在单元格的循环中，我们首先要读入与本地值相关的向量中的值。 然后，我们评估当前求解向量的值和梯度以及正交点的旧向量的值。接下来，我们在正交点的循环中结合方案中的条款。最后，我们将结果与测试函数进行积分，并将结果累积到全局解向量 @p  dst。\n\n  template <int dim, int fe_degree> \n  void SineGordonOperation<dim, fe_degree>::local_apply( \n    const MatrixFree<dim> &                                          data, \n    LinearAlgebra::distributed::Vector<double> &                     dst, \n    const std::vector<LinearAlgebra::distributed::Vector<double> *> &src, \n    const std::pair<unsigned int, unsigned int> &cell_range) const \n  { \n    AssertDimension(src.size(), 2); \n    FEEvaluation<dim, fe_degree> current(data), old(data); \n    for (unsigned int cell = cell_range.first; cell < cell_range.second; ++cell) \n      { \n        current.reinit(cell); \n        old.reinit(cell); \n\n        current.read_dof_values(*src[0]); \n        old.read_dof_values(*src[1]); \n\n        current.evaluate(EvaluationFlags::values | EvaluationFlags::gradients); \n        old.evaluate(EvaluationFlags::values); \n\n        for (unsigned int q = 0; q < current.n_q_points; ++q) \n          { \n            const VectorizedArray<double> current_value = current.get_value(q); \n            const VectorizedArray<double> old_value     = old.get_value(q); \n\n            current.submit_value(2. * current_value - old_value - \n                                   delta_t_sqr * std::sin(current_value), \n                                 q); \n            current.submit_gradient(-delta_t_sqr * current.get_gradient(q), q); \n          } \n\n        current.integrate(EvaluationFlags::values | EvaluationFlags::gradients); \n        current.distribute_local_to_global(dst); \n      } \n  } \n\n//  @sect4{SineGordonOperation::apply}  \n\n// 该函数根据单元本地策略执行时间步进例程。请注意，在添加当前时间步长的积分贡献之前，我们需要将目标向量设置为零（通过 FEEvaluation::distribute_local_to_global() 调用）。在本教程中，我们通过传递给 MatrixFree::cell_loop. 的第五个`true`参数让单元格循环进行归零操作。 循环可以将归零操作安排在更接近对支持的向量项的操作，从而可能提高数据的定位性（首先被归零的向量项后来在`distribute_local_to_global()`调用中重新使用）。单元循环的结构是在单元有限元运算器类中实现的。在每个单元上，它应用定义为类 <code>local_apply()</code> 方法的例程  <code>SineGordonOperation</code>, i.e., <code>this</code>  。我们也可以提供一个具有相同签名的、不属于类的函数。最后，积分的结果要乘以质量矩阵的逆值。\n\n  template <int dim, int fe_degree> \n  void SineGordonOperation<dim, fe_degree>::apply( \n    LinearAlgebra::distributed::Vector<double> &                     dst, \n    const std::vector<LinearAlgebra::distributed::Vector<double> *> &src) const \n  { \n    data.cell_loop( \n      &SineGordonOperation<dim, fe_degree>::local_apply, this, dst, src, true); \n    dst.scale(inv_mass_matrix); \n  } \n\n//  @sect3{Equation data}  \n\n// 我们定义了一个随时间变化的函数，作为初始值使用。通过改变起始时间，可以得到不同的解决方案。这个函数取自 step-25 ，将代表一维中所有时间的分析解，但在这里只是用来设置一些感兴趣的起始解。在  step-25  中给出了可以测试该程序收敛性的更详细的选择。\n\n  template <int dim> \n  class InitialCondition : public Function<dim> \n  { \n  public: \n    InitialCondition(const unsigned int n_components = 1, \n                     const double       time         = 0.) \n      : Function<dim>(n_components, time) \n    {} \n    virtual double value(const Point<dim> &p, \n                         const unsigned int /*component*/) const override \n    { \n      double t = this->get_time(); \n\n      const double m  = 0.5; \n      const double c1 = 0.; \n      const double c2 = 0.; \n      const double factor = \n        (m / std::sqrt(1. - m * m) * std::sin(std::sqrt(1. - m * m) * t + c2)); \n      double result = 1.; \n      for (unsigned int d = 0; d < dim; ++d) \n        result *= -4. * std::atan(factor / std::cosh(m * p[d] + c1)); \n      return result; \n    } \n  }; \n\n//  @sect3{SineGordonProblem class}  \n\n// 这是在  step-25  中的类基础上的主类。 然而，我们用MatrixFree类代替了SparseMatrix<double>类来存储几何数据。另外，我们在这个例子中使用了一个分布式三角形。\n\n  template <int dim> \n  class SineGordonProblem \n  { \n  public: \n    SineGordonProblem(); \n    void run(); \n\n  private: \n    ConditionalOStream pcout; \n\n    void make_grid_and_dofs(); \n    void output_results(const unsigned int timestep_number); \n\n#ifdef DEAL_II_WITH_P4EST \n    parallel::distributed::Triangulation<dim> triangulation; \n#else \n    Triangulation<dim> triangulation; \n#endif \n    FE_Q<dim>       fe; \n    DoFHandler<dim> dof_handler; \n\n    MappingQ1<dim> mapping; \n\n    AffineConstraints<double> constraints; \n    IndexSet                  locally_relevant_dofs; \n\n    MatrixFree<dim, double> matrix_free_data; \n\n    LinearAlgebra::distributed::Vector<double> solution, old_solution, \n      old_old_solution; \n\n    const unsigned int n_global_refinements; \n    double             time, time_step; \n    const double       final_time; \n    const double       cfl_number; \n    const unsigned int output_timestep_skip; \n  }; \n// @sect4{SineGordonProblem::SineGordonProblem}  \n\n// 这是SineGordonProblem类的构造函数。时间间隔和时间步长在此定义。此外，我们使用在程序顶部定义的有限元的程度来初始化一个基于Gauss-Lobatto支持点的FE_Q有限元。这些点很方便，因为与同阶的QGauss-Lobatto正交规则相结合，它们可以得到一个对角线质量矩阵，而不会太影响精度（注意，虽然积分是不精确的），也可以参见介绍中的讨论。请注意，FE_Q默认选择Gauss-Lobatto结点，因为它们相对于等距结点有更好的条件。为了使事情更加明确，我们还是要说明节点的选择。\n\n  template <int dim> \n  SineGordonProblem<dim>::SineGordonProblem() \n    : pcout(std::cout, Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0) \n    , \n#ifdef DEAL_II_WITH_P4EST \n    triangulation(MPI_COMM_WORLD) \n    , \n#endif \n    fe(QGaussLobatto<1>(fe_degree + 1)) \n    , dof_handler(triangulation) \n    , n_global_refinements(10 - 2 * dim) \n    , time(-10) \n    , time_step(10.) \n    , final_time(10.) \n    , cfl_number(.1 / fe_degree) \n    , output_timestep_skip(200) \n  {} \n// @sect4{SineGordonProblem::make_grid_and_dofs}  \n\n// 和 step-25 一样，这个函数在 <code>dim</code> 维度上设置了一个范围为 $[-15,15]$ 的立方体网格。我们在域的中心更多的细化网格，因为解决方案都集中在那里。我们首先细化所有中心在半径为11的单元，然后再细化一次半径为6的单元。 这种简单的临时细化可以通过在时间步进过程中使用误差估计器来适应网格，并使用 parallel::distributed::SolutionTransfer 将解决方案转移到新的网格中来完成。\n\n  template <int dim> \n  void SineGordonProblem<dim>::make_grid_and_dofs() \n  { \n    GridGenerator::hyper_cube(triangulation, -15, 15); \n    triangulation.refine_global(n_global_refinements); \n    { \n      typename Triangulation<dim>::active_cell_iterator \n        cell     = triangulation.begin_active(), \n        end_cell = triangulation.end(); \n      for (; cell != end_cell; ++cell) \n        if (cell->is_locally_owned()) \n          if (cell->center().norm() < 11) \n            cell->set_refine_flag(); \n      triangulation.execute_coarsening_and_refinement(); \n\n      cell     = triangulation.begin_active(); \n      end_cell = triangulation.end(); \n      for (; cell != end_cell; ++cell) \n        if (cell->is_locally_owned()) \n          if (cell->center().norm() < 6) \n            cell->set_refine_flag(); \n      triangulation.execute_coarsening_and_refinement(); \n    } \n\n    pcout << \"   Number of global active cells: \" \n#ifdef DEAL_II_WITH_P4EST \n          << triangulation.n_global_active_cells() \n#else \n          << triangulation.n_active_cells() \n#endif \n          << std::endl; \n\n    dof_handler.distribute_dofs(fe); \n\n    pcout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n          << std::endl; \n\n// 我们生成悬挂节点约束，以确保解决方案的连续性。如同在 step-40 中，我们需要为约束矩阵配备本地相关自由度的IndexSet，以避免它在大问题中消耗过多的内存。接下来，问题的<code>MatrixFree</code>对象被设置。请注意，我们为共享内存并行化指定了一个特定的方案（因此，人们会使用多线程来实现节点内的并行化，而不是MPI；我们在这里选择了标准选项&mdash；如果我们想在程序中有一个以上的TBB线程的情况下禁用共享内存并行化，我们会选择 MatrixFree::AdditionalData::TasksParallelScheme::none).  另外请注意，我们没有使用默认的QGauss正交参数，而是提供一个QGaussLobatto正交公式来实现期望的行为。最后，三个求解向量被初始化。MatrixFree期望有一个特定的鬼魂索引布局（因为它在MPI本地数字中处理索引访问，需要在向量和MatrixFree之间匹配），所以我们只是要求它初始化向量，以确保鬼魂交换得到正确处理。\n\n    DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs); \n    constraints.clear(); \n    constraints.reinit(locally_relevant_dofs); \n    DoFTools::make_hanging_node_constraints(dof_handler, constraints); \n    constraints.close(); \n\n    typename MatrixFree<dim>::AdditionalData additional_data; \n    additional_data.tasks_parallel_scheme = \n      MatrixFree<dim>::AdditionalData::TasksParallelScheme::partition_partition; \n\n    matrix_free_data.reinit(mapping, \n                            dof_handler, \n                            constraints, \n                            QGaussLobatto<1>(fe_degree + 1), \n                            additional_data); \n\n    matrix_free_data.initialize_dof_vector(solution); \n    old_solution.reinit(solution); \n    old_old_solution.reinit(solution); \n  } \n\n//  @sect4{SineGordonProblem::output_results}  \n\n// 这个函数打印出解的规范，并将解的向量写到一个文件中。法线是标准的（除了我们需要累积所有处理器上的法线，用于并行网格，我们通过  VectorTools::compute_global_error()  函数来做），第二项类似于我们在  step-40  或  step-37  . 请注意，我们可以使用与计算过程中使用的相同的向量进行输出。无矩阵框架中的向量总是提供所有本地拥有的单元的全部信息（这也是本地评估中需要的），包括这些单元上的鬼向量条目。这是 VectorTools::integrate_difference() 函数以及DataOut中唯一需要的数据。这时唯一要做的就是确保在我们从矢量中读取数据之前更新其鬼魂值，并在完成后重置鬼魂值。这是一个只存在于 LinearAlgebra::distributed::Vector 类中的特性。另一方面，带有PETSc和Trilinos的分布式向量需要被复制到包括ghost值的特殊向量（见 step-40 中的相关章节 ）。如果我们还想访问幽灵单元上的所有自由度（例如，当计算使用单元边界上的解的跳跃的误差估计时），我们将需要更多的信息，并创建一个初始化了本地相关自由度的向量，就像在  step-40  中一样。还请注意，我们需要为输出分配约束条件\n\n// --它们在计算过程中不被填充（相反，它们在无矩阵的方法中被实时插值  FEEvaluation::read_dof_values()).  \n  template <int dim> \n  void \n  SineGordonProblem<dim>::output_results(const unsigned int timestep_number) \n  { \n    constraints.distribute(solution); \n\n    Vector<float> norm_per_cell(triangulation.n_active_cells()); \n    solution.update_ghost_values(); \n    VectorTools::integrate_difference(mapping, \n                                      dof_handler, \n                                      solution, \n                                      Functions::ZeroFunction<dim>(), \n                                      norm_per_cell, \n                                      QGauss<dim>(fe_degree + 1), \n                                      VectorTools::L2_norm); \n    const double solution_norm = \n      VectorTools::compute_global_error(triangulation, \n                                        norm_per_cell, \n                                        VectorTools::L2_norm); \n\n    pcout << \"   Time:\" << std::setw(8) << std::setprecision(3) << time \n          << \", solution norm: \" << std::setprecision(5) << std::setw(7) \n          << solution_norm << std::endl; \n\n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \"solution\"); \n    data_out.build_patches(mapping); \n\n    data_out.write_vtu_with_pvtu_record( \n      \"./\", \"solution\", timestep_number, MPI_COMM_WORLD, 3); \n\n    solution.zero_out_ghost_values(); \n  } \n// @sect4{SineGordonProblem::run}  \n\n// 这个函数被主函数调用，并步入类的子程序中。\n\n// 在打印了一些关于并行设置的信息后，第一个动作是设置网格和单元运算器。然后，根据构造函数中给出的CFL编号和最细的网格尺寸计算出时间步长。最细的网格尺寸计算为三角形中最后一个单元的直径，也就是网格中最细层次上的最后一个单元。这只适用于一个层次上的所有元素都具有相同尺寸的网格，否则就需要对所有单元进行循环。请注意，我们需要查询所有处理器的最细单元，因为不是所有的处理器都可能持有网格处于最细级别的区域。然后，我们重新调整一下时间步长，以准确地达到最后的时间。\n\n  template <int dim> \n  void SineGordonProblem<dim>::run() \n  { \n    { \n      pcout << \"Number of MPI ranks:            \" \n            << Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD) << std::endl; \n      pcout << \"Number of threads on each rank: \" \n            << MultithreadInfo::n_threads() << std::endl; \n      const unsigned int n_vect_doubles = VectorizedArray<double>::size(); \n      const unsigned int n_vect_bits    = 8 * sizeof(double) * n_vect_doubles; \n      pcout << \"Vectorization over \" << n_vect_doubles \n            << \" doubles = \" << n_vect_bits << \" bits (\" \n            << Utilities::System::get_current_vectorization_level() << \")\" \n            << std::endl \n            << std::endl; \n    } \n    make_grid_and_dofs(); \n\n    const double local_min_cell_diameter = \n      triangulation.last()->diameter() / std::sqrt(dim); \n    const double global_min_cell_diameter = \n      -Utilities::MPI::max(-local_min_cell_diameter, MPI_COMM_WORLD); \n    time_step = cfl_number * global_min_cell_diameter; \n    time_step = (final_time - time) / (int((final_time - time) / time_step)); \n    pcout << \"   Time step size: \" << time_step \n          << \", finest cell: \" << global_min_cell_diameter << std::endl \n          << std::endl; \n\n// 接下来是初始值的设置。由于我们有一个两步的时间步进方法，我们还需要一个在时间步进时的解的值。为了得到准确的结果，需要根据初始时间的解的时间导数来计算，但是在这里我们忽略了这个困难，只是将其设置为该人工时间的初始值函数。\n\n// 然后，我们继续将初始状态写入文件，并将两个初始解收集到 <tt>std::vector</tt> 的指针中，这些指针随后被 SineGordonOperation::apply() 函数消耗。接下来，根据文件顶部指定的有限元程度，建立一个 <code> SineGordonOperation class </code> 的实例。\n\n    VectorTools::interpolate(mapping, \n                             dof_handler, \n                             InitialCondition<dim>(1, time), \n                             solution); \n    VectorTools::interpolate(mapping, \n                             dof_handler, \n                             InitialCondition<dim>(1, time - time_step), \n                             old_solution); \n    output_results(0); \n\n    std::vector<LinearAlgebra::distributed::Vector<double> *> \n      previous_solutions({&old_solution, &old_old_solution}); \n\n    SineGordonOperation<dim, fe_degree> sine_gordon_op(matrix_free_data, \n                                                       time_step); \n\n// 现在在时间步骤上循环。在每个迭代中，我们将解的向量移动一个，并调用`正弦戈登运算器'类的`应用'函数。然后，我们将解决方案写到一个文件中。我们对所需的计算时间和创建输出所需的时间进行计时，并在时间步长结束后报告这些数字。\n\n// 注意这个交换是如何实现的。我们只是在两个向量上调用了交换方法，只交换了一些指针，而不需要复制数据，这在显式时间步进方法中是比较昂贵的操作。让我们来看看发生了什么。首先，我们交换 <code>old_solution</code> with <code>old_old_solution</code> ，这意味着 <code>old_old_solution</code> 得到 <code>old_solution</code> ，这就是我们所期望的。同样，在下一步中， <code>old_solution</code> gets the content from <code>solution</code> 也是如此。在这之后， <code>solution</code> 持有 <code>old_old_solution</code> ，但这将在这一步被覆盖。\n\n    unsigned int timestep_number = 1; \n\n    Timer  timer; \n    double wtime       = 0; \n    double output_time = 0; \n    for (time += time_step; time <= final_time; \n         time += time_step, ++timestep_number) \n      { \n        timer.restart(); \n        old_old_solution.swap(old_solution); \n        old_solution.swap(solution); \n        sine_gordon_op.apply(solution, previous_solutions); \n        wtime += timer.wall_time(); \n\n        timer.restart(); \n        if (timestep_number % output_timestep_skip == 0) \n          output_results(timestep_number / output_timestep_skip); \n\n        output_time += timer.wall_time(); \n      } \n    timer.restart(); \n    output_results(timestep_number / output_timestep_skip + 1); \n    output_time += timer.wall_time(); \n\n    pcout << std::endl \n          << \"   Performed \" << timestep_number << \" time steps.\" << std::endl; \n\n    pcout << \"   Average wallclock time per time step: \" \n          << wtime / timestep_number << \"s\" << std::endl; \n\n    pcout << \"   Spent \" << output_time << \"s on output and \" << wtime \n          << \"s on computations.\" << std::endl; \n  } \n} // namespace Step48 \n\n//  @sect3{The <code>main</code> function}  \n\n// 与 step-40 中一样，我们在程序开始时初始化MPI。由于我们一般会将MPI并行化与线程混合在一起，所以我们也将MPI_InitFinalize中控制线程数量的第三个参数设置为无效数字，这意味着TBB库会自动选择线程的数量，通常为系统中可用的内核数量。作为一种选择，如果你想设置一个特定的线程数（例如，当需要只使用MPI时），你也可以手动设置这个数字。\n\nint main(int argc, char **argv) \n{ \n  using namespace Step48; \n  using namespace dealii; \n\n  Utilities::MPI::MPI_InitFinalize mpi_initialization( \n    argc, argv, numbers::invalid_unsigned_int); \n\n  try \n    { \n      SineGordonProblem<dimension> sg_problem; \n      sg_problem.run(); \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n\n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n\n  return 0; \n} \n\n", "meta": {"hexsha": "41e07f3c491cd74f8af0c1f0aa2834f64a0bc192", "size": 21017, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-48/step-48.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-48/step-48.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-48/step-48.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.048828125, "max_line_length": 558, "alphanum_fraction": 0.6496169767, "num_tokens": 7772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.435257447074527}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG, www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also tools/license/license.mtl.txt in the distribution.\n\n#ifndef MTL_VEC_TRIGONOMETRIC_INCLUDE\n#define MTL_VEC_TRIGONOMETRIC_INCLUDE\n\n#include <boost/numeric/mtl/vector/map_view.hpp>\n\n// vector functions\n\nnamespace mtl { namespace vec {\n\n    /// Element-wise acos of \\a v\n    template <typename Vector>\n    acos_view<Vector> acos(const Vector& v)\n    {\n        return acos_view<Vector>(v);\n    }\n\n    /// Element-wise acosh of \\a v\n    template <typename Vector>\n    acosh_view<Vector> acosh(const Vector& v)\n    {\n        return acosh_view<Vector>(v);\n    }\n\n    /// Element-wise asin of \\a v\n    template <typename Vector>\n    asin_view<Vector> asin(const Vector& v)\n    {\n        return asin_view<Vector>(v);\n    }\n\n    /// Element-wise asinh of \\a v\n    template <typename Vector>\n    asinh_view<Vector> asinh(const Vector& v)\n    {\n        return asinh_view<Vector>(v);\n    }\n\n    /// Element-wise atan of \\a v\n    template <typename Vector>\n    atan_view<Vector> atan(const Vector& v)\n    {\n        return atan_view<Vector>(v);\n    }\n\n    /// Element-wise atanh of \\a v\n    template <typename Vector>\n    atanh_view<Vector> atanh(const Vector& v)\n    {\n        return atanh_view<Vector>(v);\n    }\n\n    // non-inverse\n    \n    /// Element-wise cos of \\a v\n    template <typename Vector>\n    cos_view<Vector> cos(const Vector& v)\n    {\n        return cos_view<Vector>(v);\n    }\n\n    /// Element-wise cosh of \\a v\n    template <typename Vector>\n    cosh_view<Vector> cosh(const Vector& v)\n    {\n        return cosh_view<Vector>(v);\n    }\n\n    /// Element-wise sin of \\a v\n    template <typename Vector>\n    sin_view<Vector> sin(const Vector& v)\n    {\n        return sin_view<Vector>(v);\n    }\n\n    /// Element-wise sinh of \\a v\n    template <typename Vector>\n    sinh_view<Vector> sinh(const Vector& v)\n    {\n        return sinh_view<Vector>(v);\n    }\n\n    /// Element-wise tan of \\a v\n    template <typename Vector>\n    tan_view<Vector> tan(const Vector& v)\n    {\n        return tan_view<Vector>(v);\n    }\n\n    /// Element-wise tanh of \\a v\n    template <typename Vector>\n    tanh_view<Vector> tanh(const Vector& v)\n    {\n        return tanh_view<Vector>(v);\n    }\n\n\n}} // namespace mtl::vec\n\n#endif // MTL_VEC_TRIGONOMETRIC_INCLUDE\n", "meta": {"hexsha": "0b930cebe569379283a1681c85615dac0d7f577b", "size": 2619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/trigonometric.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/mtl/operation/trigonometric.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/mtl/operation/trigonometric.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 23.3839285714, "max_line_length": 94, "alphanum_fraction": 0.6265750286, "num_tokens": 668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4352574392721748}}
{"text": "#ifndef GAUSSIAN_PROCESS_HPP\n#define GAISSIAN_PROCESS_HPP\n\n#include \"gplib/kernel.hpp\"\n#include <Eigen/Cholesky>\n#include <vector>\n\nnamespace librav{\n\n    class GaussianProcess{\n        public:\n            ~GaussianProcess() {};\n            // The keyword explicit avoid the implicit type conversion constructor\n            explicit GaussianProcess(const Kernel::Ptr& kernel, double noise, const std::shared_ptr<std::vector<Eigen::VectorXd>> points, const Eigen::VectorXd& targets, size_t max_points = 100);\n\n            // Evaluate mean and variance at a point\n            void Evaluate(const Eigen::VectorXd& x, double& mean, double& variance) const;\n            void EvaluateTrainingPoint(size_t ii, double& mean, double& variance) const;\n\n            // Add new point(s). Return whether or not points were added (points will\n            // only be added until 'max_points' is reached).\n            bool Add(const Eigen::VectorXd& x, double target);\n            bool Add(const std::vector<Eigen::VectorXd>& points, const Eigen::VectorXd& targets);\n\n            // Update the training targets in the direction of the gradient of the\n            // mean squared error at the given points. Returns the mean squared error.\n            // If 'finalize' is set, computes regressed targets - only set to false if\n            // you are doing repeated updates, and be sure to set true on final update.\n            double UpdateTargets(const std::vector<Eigen::VectorXd>& points,\n                                 const std::vector<double>& targets,\n                                 double step_size, bool finalize = true);\n\n            // Learn kernel hyperparameters by maximizing log-likelihood of the\n            // training data.\n            bool LearnHyperparams();\n\n            // Immutable accessors\n            const Eigen::MatrixXd& ImmutableCovariance() const { return covariance_; };\n            const Eigen::VectorXd& ImmutableRegressedTargets() const { return regressed_; };\n            const Eigen::VectorXd& ImmutableTargerts() const { return targets_; };\n            const std::shared_ptr<const std::vector<Eigen::VectorXd>> ImmutablePoints() const { return points_; };\n            const Eigen::LLT<Eigen::MatrixXd>& ImmutableCholesky() const { return llt_; };\n            size_t Dimension() const { return dimension_; };\n\n        private:\n            // Compute the covariance and cross covariance against the trainning points.\n            void Covariance();\n            void CrossCovariance(const Eigen::VectorXd& x, Eigen::VectorXd& cross) const;\n\n            // Kernel.\n            const Kernel::Ptr kernel_;\n\n            // Noise variance\n            double noise_;\n\n            // Trainning points, targets, and regressed targets (inv(cov) * targets).\n            const std::shared_ptr<std::vector<Eigen::VectorXd>> points_;\n            size_t dimension_;\n            Eigen::VectorXd targets_;\n            Eigen::VectorXd regressed_;\n\n            // Maximum number of points.\n            const size_t max_points_;\n\n            // Covariance matrix, with Cholesky decomposition.\n            Eigen::MatrixXd covariance_;\n            Eigen::LLT<Eigen::MatrixXd> llt_;\n    };\n}\n\n#endif /* GAUSSIAN_PROCESS_HPP */", "meta": {"hexsha": "1a4d641b79030f91c4a362b3598490736695e848", "size": 3224, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gplib/include/gplib/gaussian_process.hpp", "max_stars_repo_name": "jfangwpi/Interactive_planning_and_sensing", "max_stars_repo_head_hexsha": "00042c51c2fdc020b7b1c184286cf2b513ed9096", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gplib/include/gplib/gaussian_process.hpp", "max_issues_repo_name": "jfangwpi/Interactive_planning_and_sensing", "max_issues_repo_head_hexsha": "00042c51c2fdc020b7b1c184286cf2b513ed9096", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gplib/include/gplib/gaussian_process.hpp", "max_forks_repo_name": "jfangwpi/Interactive_planning_and_sensing", "max_forks_repo_head_hexsha": "00042c51c2fdc020b7b1c184286cf2b513ed9096", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4084507042, "max_line_length": 195, "alphanum_fraction": 0.6259305211, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4352574392721748}}
{"text": "\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Copyright Paul A. Bristow 2015 - 2016.\n// Copyright Christopher Kormanyos 2015 - 2016.\n\n// This program computes fixed-point negatable limits for various\n// precisions and stores them in partial format for a Quickbook table.\n\n#include <iomanip>\n#include <iostream>\n#include <limits>\n\n#include <boost/fixed_point/fixed_point.hpp>\n\ntemplate<typename fixed_point_type>\nvoid print_limits()\n{\n  std::cout << std::setprecision(4)\n            << \"[\"\n            << \"[<\" << fixed_point_type::range << \", \" << fixed_point_type::resolution << \">] \"\n            << \"[\"  << fixed_point_type::range << \"] \"\n            << \"[\"  << fixed_point_type::resolution << \"] \"\n            << \"[\"  << std::numeric_limits<fixed_point_type>::digits << \"] \"\n            << \"[\"  << std::numeric_limits<fixed_point_type>::digits +1 << \"] \"\n            << \"[\"  << std::numeric_limits<fixed_point_type>::epsilon() << \"] \"\n            << \"[\"  << std::numeric_limits<fixed_point_type>::lowest() << \"] \"\n            << \"[\"  << (std::numeric_limits<fixed_point_type>::min)() << \"] \"\n            << \"[\"  << (std::numeric_limits<fixed_point_type>::max)() << \"]\"\n            << \"]\"\n            << std::endl\n            ;\n}\n\nint main()\n{\n  print_limits<boost::fixed_point::negatable< 15,  -16>>();\n  print_limits<boost::fixed_point::negatable< 11,  -20>>();\n  print_limits<boost::fixed_point::negatable<  0,  -31>>();\n  print_limits<boost::fixed_point::negatable< 30,   -1>>();\n  print_limits<boost::fixed_point::negatable< 15, -240>>();\n  print_limits<boost::fixed_point::negatable<  0, -255>>();\n  print_limits<boost::fixed_point::negatable<200,  -55>>();\n  print_limits<boost::fixed_point::negatable<  7,   -8>>();\n  print_limits<boost::fixed_point::negatable<  0,   -7>>();\n  print_limits<boost::fixed_point::negatable<  2,   -5>>();\n  print_limits<boost::fixed_point::negatable<  4,  -11>>();\n  print_limits<boost::fixed_point::negatable<  7,  -24>>();\n  print_limits<boost::fixed_point::negatable< 10,  -53>>();\n  print_limits<boost::fixed_point::negatable< 14, -113>>();\n}\n", "meta": {"hexsha": "55b479e1a4e9a30438b2f0e761c0e4f3901be403", "size": 2237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/fixed_point_limits_table.cpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/fixed_point_limits_table.cpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/fixed_point_limits_table.cpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6727272727, "max_line_length": 95, "alphanum_fraction": 0.6146624944, "num_tokens": 599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.622459324198198, "lm_q1q2_score": 0.435257434374837}}
{"text": "#define CERES_FOUND \n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/features2d.hpp>\n#include <opencv2/core/cvstd.hpp>\n#include <opencv2/opencv.hpp>\n#include <unistd.h>\n#include <algorithm>\n\n//#include <opencv2/xfeatures2d.hpp>\n//#include <opencv2/xfeatures2d/nonfree.hpp>\n//#include <opencv2/sfm.hpp>\n\n#include <Eigen/Geometry>\n\n//https://docs.opencv.org/3.1.0/d0/d13/classcv_1_1Feature2D.html\nnamespace featuresdetectors {enum FEATURES_DETECTORS\n{\nAgastFeatureDetector,\nAKAZE,\nBRISK,\nFastFeatureDetector,\nGFTTDetector,\nKAZE,\nMSER,\nORB,\nSimpleBlobDetector,\nMSDDetector,\nSIFT,\nStarDetector,\nSURF\n};\n}\n\nnamespace featuresdescriptor {enum FEATURES_DESCRIPTOR\n{\nAKAZE,\nBRISK,\nKAZE,\nORB,\nSimpleBlobDetector,\nBriefDescriptorExtractor,\nDAISY,\nFREAK,\nLATCH,\nLUCID,\nMSDDetector,\nSIFT,\nStarDetector,\nSURF\n};\n}\n\n//void test()\n//{\n//    double max_dist = 0; double min_dist = 100;\n\n//    //-- Quick calculation of max and min distances between keypoints\n//    for( int i = 0; i < descriptors_object.rows; i++ )\n//    {   double dist = matches[i].distance;\n//        if( dist < min_dist ) min_dist = dist;\n//        if( dist > max_dist ) max_dist = dist;\n//    }\n\n//    printf(\"-- Max dist : %f \\n\", max_dist );\n//    printf(\"-- Min dist : %f \\n\", min_dist );\n\n//    //-- Draw only \"good\" matches (i.e. whose distance is less than 3*min_dist )\n//    std::vector< cv::DMatch > good_matches;\n\n//    for( int i = 0; i < descriptors_object.rows; i++ )\n//    { if( matches[i].distance < 1.5*min_dist )\n//        {\n//            good_matches.push_back( matches[i]);\n//        }\n//    }\n//}\n\nint dumb(int argc, char ** argv)\n{\n\n    /**/\n\n\n        unsigned int microseconds=1000000;\n        cv::VideoCapture webCam(0); // open the default camera\n        webCam.set(cv::CAP_PROP_FRAME_WIDTH,640);\n        webCam.set(cv::CAP_PROP_FRAME_HEIGHT,480);\n        webCam.set(cv::CAP_PROP_FPS, 1);\n        //webCam.set(cv::CAP_PROP_MODE, CV_CAP_MODE_YUYV);\n\n\n\n\n\n\n\n\n\n\n        if(!webCam.isOpened())  // check if we succeeded\n    //    return;\n\n        cv::namedWindow(\"camera\",1);\n        for(;;)\n        {\n    //        Mat frame;\n    //        webCam >> frame; // get a new frame from camera\n    //        imshow(\"camera\", frame);\n            if(cv::waitKey(200) >= 0) break;\n\n    //        Mat img_1 = imread( argv[1], IMREAD_GRAYSCALE );\n    //        Mat img_2 = imread( argv[2], IMREAD_GRAYSCALE );\n\n            cv::Mat img_1, img_2;\n            webCam >> img_1;\n\n\n\n            usleep(microseconds);\n\n\n            webCam >> img_2;\n\n\n\n\n\n\n\n\n\n            std::vector<cv::Mat> points2d;\n\n\n            if( !img_1.data || !img_2.data )\n            { std::cout<< \" --(!) Error reading images \" << std::endl; return -1; }\n            //-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors\n            int minHessian = 400;\n            cv::Ptr<cv::xfeatures2d::SURF> detector = cv::xfeatures2d::SURF::create();\n\n\n    //        cv::xfeatures2d::DAISY;\n\n\n    //SURF\n    //SIFT\n    //ORB\n    //BRISK\n    //MSER\n    //GFTT\n    //Harris\n    //Dense\n    //SimpleBlob\n\n    //FAST\n    //STAR\n\n\n\n    //        cv::xfeatures2d::\n\n            cv::Ptr<cv::xfeatures2d::SIFT> SIFT_detector = cv::xfeatures2d::SIFT::create();\n            SIFT_detector->defaultNorm();\n\n\n//            Ptr<ORB> ORB_detector = ORB::create();\n//            //ORB_detector->set\n\n//            Ptr<BRISK> BRISK_detector = BRISK::create();\n\n\n\n    //        SIFT::create();\n            detector->setHessianThreshold(minHessian);\n            std::vector<cv::KeyPoint> keypoints_1, keypoints_2;\n            cv::Mat descriptors_1, descriptors_2;\n//            detector->detectAndCompute( img_1, cv::Mat(), keypoints_1, descriptors_1 );\n//            detector->detectAndCompute( img_2, cv::Mat(), keypoints_2, descriptors_2 );\n\n\n\n            SIFT_detector->detectAndCompute( img_1, cv::Mat(), keypoints_1, descriptors_1 );\n            SIFT_detector->detectAndCompute( img_2, cv::Mat(), keypoints_2, descriptors_2 );\n\n\n            //-- Step 2: Matching descriptor vectors using FLANN matcher\n            cv::FlannBasedMatcher matcher;\n            std::vector< cv::DMatch > matches;\n            matcher.match( descriptors_1, descriptors_2, matches );\n            double max_dist = 0; double min_dist = 100;\n            //-- Quick calculation of max and min distances between keypoints\n            for( int i = 0; i < descriptors_1.rows; i++ )\n            { double dist = matches[i].distance;\n              if( dist < min_dist ) min_dist = dist;\n              if( dist > max_dist ) max_dist = dist;\n            }\n            printf(\"-- Max dist : %f \\n\", max_dist );\n            printf(\"-- Min dist : %f \\n\", min_dist );\n            //-- Draw only \"good\" matches (i.e. whose distance is less than 2*min_dist,\n            //-- or a small arbitary value ( 0.02 ) in the event that min_dist is very\n            //-- small)\n            //-- PS.- radiusMatch can also be used here.\n            std::vector< cv::DMatch > good_matches;\n            for( int i = 0; i < descriptors_1.rows; i++ )\n            { if( matches[i].distance <= std::max(2*min_dist, 0.02) )\n              {\n                    good_matches.push_back( matches[i]);\n                }\n            }\n\n            int number_of_frames=2;\n            int number_of_points=good_matches.size();\n            int number_of_rows=2;\n    //        std::cout <<\"good_matches:\"<<good_matches.size() <<std::endl;\n\n            cv::Mat_<double> frame1(number_of_rows, number_of_points),frame2(number_of_rows, number_of_points);\n            double  p_f1_x,\n                    p_f1_y,\n                    p_f2_x,\n                    p_f2_y;\n            for (std::size_t i=0;i<good_matches.size();i++)\n            {\n                p_f1_x=keypoints_1[good_matches.at(i).queryIdx].pt.x;\n                p_f1_y=keypoints_1[good_matches.at(i).queryIdx].pt.y;\n\n                frame1(0,i)=p_f1_x;\n                frame1(1,i)=p_f1_y;\n            }\n\n            for (std::size_t i=0;i<good_matches.size();i++)\n            {\n                p_f2_x=keypoints_2[good_matches.at(i).trainIdx].pt.x;\n                p_f2_y=keypoints_2[good_matches.at(i).trainIdx].pt.y;\n                frame2(0,i)=p_f2_x;\n                frame2(1,i)=p_f2_y;\n            }\n            points2d.clear();\n\n            points2d.push_back(cv::Mat(frame1));\n            points2d.push_back(cv::Mat(frame2));\n\n\n            const double f  = std::atof(argv[1]),\n                         cx = std::atof(argv[2]), cy = std::atof(argv[3]);\n            cv::Matx33d K = cv::Matx33d( f, 0, cx,\n                                 0, f, cy,\n                                 0, 0,  1);\n            bool is_projective = true;\n\n\n            std::cout <<\"points2d.size():\"<<        points2d.size()  <<std::endl;\n\n            std::vector<cv::Mat> Rs_est, ts_est, points3d_estimated;\n            //cv::::reconstruct(points2d, Rs_est, ts_est, K, points3d_estimated, is_projective);\n            std::cout<<\"Rotation:\" <<std::endl;\n            std::cout<<Rs_est.size() <<std::endl;\n\n            std::cout<<\"Translation:\" <<std::endl;\n            std::cout<<ts_est.size() <<std::endl;\n\n\n\n\n            //-- Draw only \"good\" matches\n            cv::Mat img_matches;\n            cv::drawMatches( img_1, keypoints_1, img_2, keypoints_2,\n                         good_matches, img_matches, cv::Scalar::all(-1), cv::Scalar::all(-1),\n                         std::vector<char>(), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );\n            //-- Show detected matches\n            cv::imshow( \"Good Matches\", img_matches );\n            cv::imshow( \"Diff\", img_1-img_2 );\n    //        for( int i = 0; i < (int)good_matches.size(); i++ )\n    //        {\n    //            printf( \"-- Good Match [%d] Keypoint 1: %d  -- Keypoint 2: %d  \\n\", i, good_matches[i].queryIdx, good_matches[i].trainIdx );\n    //        }\n            cv::waitKey(10);\n    //        return 0;\n\n\n\n\n\n\n        }\n\n\n\n}\n\n\nvoid featureDetection( cv::Mat &image_in, std::vector<cv::KeyPoint> &keypoints,cv::Mat &descriptors,featuresdetectors::FEATURES_DETECTORS featureDetector, featuresdescriptor::FEATURES_DESCRIPTOR featureDescriptor)\n{\n    cv::Ptr<cv::Feature2D> features_detector;\n    cv::Ptr<cv::Feature2D> features_descriptor;\n\n     switch(featureDetector)\n    {\n        case featuresdetectors::AgastFeatureDetector :\n             features_detector = cv::AgastFeatureDetector::create();\n            break;\n        case featuresdetectors::AKAZE :\n            features_detector = cv::AKAZE::create();\n            break;\n        case featuresdetectors::BRISK:\n            features_detector = cv::BRISK::create();\n            break;\n        case featuresdetectors::FastFeatureDetector:\n            features_detector = cv::FastFeatureDetector::create();\n            break;\n        case featuresdetectors::GFTTDetector:\n            features_detector = cv::GFTTDetector::create();\n            break;\n        case featuresdetectors::KAZE:\n            features_detector = cv::KAZE::create();\n            break;\n        case featuresdetectors::MSER:\n            features_detector = cv::MSER::create();\n            break;\n        case featuresdetectors::ORB:\n            features_detector = cv::ORB::create();\n            break;\n        case featuresdetectors::SimpleBlobDetector:\n            features_detector = cv::SimpleBlobDetector::create();\n            break;\n        case featuresdetectors::MSDDetector:\n            features_detector = cv::xfeatures2d::MSDDetector::create();\n            break;\n        case featuresdetectors::SIFT:\n            features_detector = cv::xfeatures2d::SIFT::create();\n            break;\n        case featuresdetectors::StarDetector:\n            features_detector = cv::xfeatures2d::StarDetector::create();\n            break;\n        case featuresdetectors::SURF:\n            features_detector = cv::xfeatures2d::SURF::create();\n            break;\n    }\n\n    switch(featureDescriptor)\n    {\n        case featuresdescriptor::AKAZE :\n            features_descriptor = cv::AKAZE::create();\n            break;\n        case featuresdescriptor::BRISK:\n            features_descriptor = cv::BRISK::create();\n            break;\n        case featuresdescriptor::KAZE:\n            features_descriptor = cv::KAZE::create();\n            break;\n        case featuresdescriptor::ORB:\n            features_descriptor = cv::ORB::create();\n            break;\n        case featuresdescriptor::BriefDescriptorExtractor:\n            features_descriptor = cv::xfeatures2d::BriefDescriptorExtractor::create();\n            break;\n        case featuresdescriptor::DAISY:\n            features_descriptor = cv::xfeatures2d::DAISY::create();\n            break;\n        case featuresdescriptor::FREAK:\n            features_descriptor = cv::xfeatures2d::FREAK::create();\n            break;\n        case featuresdescriptor::LATCH:\n            features_descriptor = cv::xfeatures2d::LATCH::create();\n            break;\n        case featuresdescriptor::LUCID:\n            features_descriptor = cv::xfeatures2d::LUCID::create();\n            break;\n        case featuresdescriptor::MSDDetector:\n            features_descriptor = cv::xfeatures2d::MSDDetector::create();\n            break;\n        case featuresdescriptor::SIFT:\n            features_descriptor = cv::xfeatures2d::SIFT::create();\n            break;\n        case featuresdescriptor::StarDetector:\n            features_descriptor = cv::xfeatures2d::StarDetector::create();\n            break;\n        case featuresdescriptor::SURF:\n            features_descriptor = cv::xfeatures2d::SURF::create();\n            break;\n    }\n\n    features_detector->detect(image_in,keypoints,cv::Mat());\n    features_descriptor->compute(image_in,keypoints,descriptors);\n}\n\nvoid featureDetection_test(int argc , char ** argv )\n{\n    cv::Mat image_in;\n    cv::Mat image_out;\n    std::vector<cv::KeyPoint> keypoints;\n    cv::Mat descriptors;\n    std::string file_path=argv[1];\n    image_in=cv::imread( file_path,cv::IMREAD_COLOR);\n    featureDetection(image_in,keypoints,descriptors,featuresdetectors::AgastFeatureDetector,featuresdescriptor::DAISY);\n    cv::drawKeypoints(image_in,keypoints,image_out);\n    std::string window_title=\"Feature\";\n    cv::imshow(window_title, image_out);\n    cv::waitKey(0);\n}\n\nvoid featureMatching( cv::Mat &descriptors_object, cv::Mat descriptors_scene, std::vector< cv::DMatch >& matches)\n{\n\n    cv::BFMatcher bruteForceMatching;\n    //bruteForceMatching.match();\n    //bruteForceMatching.knnMatch();\n    cv::FlannBasedMatcher matcher;\n\n    //matcher.radiusMatch();\n\n\n    matcher.match( descriptors_object, descriptors_scene, matches );\n\n\n}\n\nvoid refineMathes(std::vector< cv::DMatch > &matches,cv::Mat &object_descriptors ,std::vector< cv::DMatch > &good_matches)\n{\n\n    double max_dist = 0; double min_dist = 100;\n\n    std::vector<double> vec;\n\n\n\n    //-- Quick calculation of max and min distances between keypoints\n    for( int i = 0; i < object_descriptors.rows; i++ )\n    {   double dist = matches[i].distance;\n        if( dist < min_dist ) min_dist = dist;\n        if( dist > max_dist ) max_dist = dist;\n        vec.push_back(dist);\n    }\n\n//    size_t midIndex = vec.size()/9;\n    size_t midIndex = 40;\n    std::nth_element(vec.begin(), vec.begin() + midIndex, vec.end());\n\n\n//    printf(\"-- Max dist : %f \\n\", max_dist );\n//    printf(\"-- Min dist : %f \\n\", min_dist );\n//    std::cout<<\"the 5the element is: \"<<vec[midIndex] <<std::endl;\n\n    //-- Draw only \"good\" matches (i.e. whose distance is less than 3*min_dist )\n\n\n    for( int i = 0; i < object_descriptors.rows; i++ )\n    {\n        if( matches[i].distance < vec[midIndex] )\n        {\n            good_matches.push_back( matches[i]);\n        }\n    }\n}\n\nvoid featureMatching_Test(int argc, char ** argv)\n{\n    cv::Mat image_object,image_scene;\n    std::vector<cv::KeyPoint> object_keypoints,scene_keypoints;\n    cv::Mat object_descriptors, scene_descriptors;\n\n    image_scene=cv::imread( argv[1],cv::IMREAD_COLOR);\n    image_object=cv::imread( argv[2],cv::IMREAD_COLOR);\n\n    featureDetection(image_object,object_keypoints,object_descriptors,featuresdetectors::SIFT,featuresdescriptor::SURF);\n    featureDetection(image_scene,scene_keypoints,scene_descriptors,featuresdetectors::SIFT,featuresdescriptor::SURF);\n\n    std::vector< cv::DMatch > matches;\n    featureMatching(object_descriptors, scene_descriptors, matches);\n\n\n//    std::cout<<\"matches\"<<matches.size() <<std::endl;\n    std::vector< cv::DMatch > good_matches;\n\n    refineMathes(matches,object_descriptors ,good_matches);\n\n    cv::Mat img_matches;\n    cv::drawMatches( image_object, object_keypoints, image_scene, scene_keypoints,\n    good_matches, img_matches, cv::Scalar::all(-1), cv::Scalar::all(-1),\n    std::vector<char>(), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );\n\n    std::string window_title=\"matches\";\n    cv::imshow(window_title, img_matches);\n    cv::waitKey(0);\n    cv::imwrite(\"mathes.jpg\",img_matches);\n\n\n    std::vector<cv::Point2f> points1Raw; //Raw points from Keypoints\n    std::vector<cv::Point2f> points1; //Undistorted points\n    std::vector<cv::Point2f> points2Raw;\n    std::vector<cv::Point2f> points2;\n    for(int k=0; k<good_matches.size(); k++)\n    {\n        points1Raw.push_back(object_keypoints[good_matches[k].queryIdx].pt);\n        points2Raw.push_back(scene_keypoints[good_matches[k].trainIdx].pt);\n    }\n\n//    cv::undistortPoints(points1Raw, points1, cameraMatrixm, distCoeffsm);\n//    cv::undistortPoints(points2Raw, points2, cameraMatrixm, distCoeffsm);\n\n    points1=points1Raw;\n    points2=points2Raw;\n    std::vector<uchar> states;\n\n\n//https://stackoverflow.com/questions/25251676/opencv-findfundamentalmat-very-unstable-and-sensitive\n\n//    cv::Mat f = cv::findFundamentalMat(points1, points2, cv::FM_RANSAC, 3, 0.99, states);\n\n    cv::Mat f = cv::findFundamentalMat(points1, points2, cv::FM_LMEDS, 3, 0.99, states);\n\n//    cv::Mat f = cv::findFundamentalMat(points1, points2, cv::FM_7POINT, 3, 0.99, states);\n\n//    cv::Mat f = cv::findFundamentalMat(points1, points2, cv::FM_8POINT, 3, 0.99, states);\n\t\n\t\n\n    std::cout<<\"Fundamental Mat is: \" <<f <<std::endl;\n\n    double err=0;\n    for(int k=0; k<good_matches.size(); k++)\n    {\n        cv::Mat p1(3, 1, CV_64F);\n        p1.at<double>(0, 0) = points1[k].x;\n        p1.at<double>(1, 0) = points1[k].y;\n        p1.at<double>(2, 0) = 1;\n        cv::Mat p2(1, 3, CV_64F);\n        p2.at<double>(0, 0) = points2[k].x;\n        p2.at<double>(0, 1) = points2[k].y;\n        p2.at<double>(0, 2) = 1;\n\n        cv::Mat res = cv::abs(p2 * f * p1); // f computed matrix\n\n        if((bool)states[k]) //if match considered inlier (in my strange case all)\n            err = err + res.at<double>(0, 0); //accumulate errors\n\n    }\n\n    std::cout<<\"Total error is: \" <<err <<std::endl;\n\n\n    double focal=1.0;\n    cv::Point2d pp=cv::Point2d(10, 10);\n    double threshold=1;\n    double prob=0.999;\n    cv::LMEDS;\n    cv::Mat E,R,t,mask;\n\n    E= cv::findEssentialMat(points1, points2,focal,pp, cv::RANSAC,prob,threshold,mask);\n    std::cout<<\"E: \" <<E<<std::endl;\n    cv::recoverPose(E, points1, points2, R, t, focal, pp, mask);\n    std::cout<<\"R: \" <<R<<std::endl;\n    std::cout<<\"t: \" <<t<<std::endl;\n\n\n\n}\n\nvoid findFundamentalMatrix(cv::Mat &image1,cv::Mat &image2,cv::Mat &fundamentalMatrix,double &error)\n{\n    //1)featureDetection\n    std::vector<cv::KeyPoint> image1_keypoints,image2_keypoints;\n    cv::Mat image1_descriptors,image2_descriptors;\n\n    featureDetection(  image1, image1_keypoints,image1_descriptors,featuresdetectors::SIFT,featuresdescriptor::SURF);\n    featureDetection(  image2, image2_keypoints,image2_descriptors,featuresdetectors::SIFT,featuresdescriptor::SURF);\n\n    //2)featureMatching\n    std::vector< cv::DMatch > matches;\n\n    featureMatching( image1_descriptors, image2_descriptors,  matches);\n\n\n    //)refineMathes\n    std::vector< cv::DMatch > good_matches;\n    refineMathes(matches,image2_descriptors, good_matches);\n\n\n\n    std::vector<cv::Point2f> points1Raw; //Raw points from Keypoints\n    std::vector<cv::Point2f> points1; //Undistorted points\n    std::vector<cv::Point2f> points2Raw;\n    std::vector<cv::Point2f> points2;\n    for(int k=0; k<good_matches.size(); k++)\n    {\n        points1Raw.push_back(image1_keypoints[good_matches[k].queryIdx].pt);\n        points2Raw.push_back(image2_keypoints[good_matches[k].trainIdx].pt);\n    }\n\n    //4)undistortion\n//    cv::undistortPoints(points1Raw, points1, cameraMatrixm, distCoeffsm);\n//    cv::undistortPoints(points2Raw, points2, cameraMatrixm, distCoeffsm);\n\n    points1=points1Raw;\n    points2=points2Raw;\n    std::vector<uchar> states;\n\n    //5)findFundamentalMat\n//https://stackoverflow.com/questions/25251676/opencv-findfundamentalmat-very-unstable-and-sensitive\n//  cv::findFundamentalMat(points1, points2, cv::FM_RANSAC, 3, 0.99, states);\n//  cv::findFundamentalMat(points1, points2, cv::FM_7POINT, 3, 0.99, states);\n//  cv::findFundamentalMat(points1, points2, cv::FM_8POINT, 3, 0.99, states);\n    fundamentalMatrix = cv::findFundamentalMat(points1, points2, cv::FM_LMEDS, 3, 0.99, states);\n    for(int k=0; k<good_matches.size(); k++)\n    {\n        cv::Mat p1(3, 1, CV_64F);\n        p1.at<double>(0, 0) = points1[k].x;\n        p1.at<double>(1, 0) = points1[k].y;\n        p1.at<double>(2, 0) = 1;\n        cv::Mat p2(1, 3, CV_64F);\n        p2.at<double>(0, 0) = points2[k].x;\n        p2.at<double>(0, 1) = points2[k].y;\n        p2.at<double>(0, 2) = 1;\n        cv::Mat res = cv::abs(p2 * fundamentalMatrix * p1); // f computed matrix\n        if((bool)states[k]) //if match considered inlier (in my strange case all)\n            error = error + res.at<double>(0, 0); //accumulate errors\n    }\n\n}\n\nvoid findFundamentalMatrix_test(int argc, char ** argv)\n{\n    cv::Mat image1=cv::imread( argv[1],cv::IMREAD_COLOR);\n    cv::Mat image2=cv::imread( argv[2],cv::IMREAD_COLOR);\n    cv::Mat fundamentalMatrix;\n    double error;\n    findFundamentalMatrix(image1,image2,fundamentalMatrix,error);\n    std::cout<<\"Fundamental Matrix is: \" <<fundamentalMatrix <<std::endl;\n    std::cout<<\"error is: \" <<error <<std::endl;\n}\n\nvoid findEssentialMatrix(cv::Mat &image1,cv::Mat &image2, cv::Mat &cameraMatrix, cv::Mat &EssentialMatrix,cv::Mat &rotation,cv::Mat &translation)\n{\n    //1)featureDetection\n    std::vector<cv::KeyPoint> image1_keypoints,image2_keypoints;\n    cv::Mat image1_descriptors,image2_descriptors;\n\n    featureDetection(  image1, image1_keypoints,image1_descriptors,featuresdetectors::SIFT,featuresdescriptor::SURF);\n    featureDetection(  image2, image2_keypoints,image2_descriptors,featuresdetectors::SIFT,featuresdescriptor::SURF);\n\n    //2)featureMatching\n    std::vector< cv::DMatch > matches;\n\n    featureMatching( image1_descriptors, image2_descriptors,  matches);\n\n\n    //)refineMathes\n    std::vector< cv::DMatch > good_matches;\n    refineMathes(matches,image2_descriptors, good_matches);\n\n\n\n    std::vector<cv::Point2f> points1Raw; //Raw points from Keypoints\n    std::vector<cv::Point2f> points1; //Undistorted points\n    std::vector<cv::Point2f> points2Raw;\n    std::vector<cv::Point2f> points2;\n    for(int k=0; k<good_matches.size(); k++)\n    {\n        points1Raw.push_back(image1_keypoints[good_matches[k].queryIdx].pt);\n        points2Raw.push_back(image2_keypoints[good_matches[k].trainIdx].pt);\n    }\n\n    //4)undistortion\n//    cv::undistortPoints(points1Raw, points1, cameraMatrixm, distCoeffsm);\n//    cv::undistortPoints(points2Raw, points2, cameraMatrixm, distCoeffsm);\n\n    points1=points1Raw;\n    points2=points2Raw;\n    std::vector<uchar> states;\n\n\n    double focal=1.0;\n    cv::Point2d pp=cv::Point2d(10, 10);\n    double threshold=1;\n    double prob=0.999;\n    cv::LMEDS;\n    cv::Mat mask;\n\n    EssentialMatrix= cv::findEssentialMat(points1, points2,focal,pp, cv::RANSAC,prob,threshold,mask);\n    cv::recoverPose(EssentialMatrix, points1, points2, rotation, translation, focal, pp, mask);\n}\n\nvoid findEssentialMatrix_Test(int argc, char** argv)\n{\n    std::string camera_calibration_path=\"front_webcam.yml\";\n    cv::FileStorage fs(camera_calibration_path,cv::FileStorage::READ);\n    cv::Mat camera_matrix, distortion_coefficient;\n    fs[\"camera_matrix\"]>>camera_matrix;\n    fs[\"distortion_coefficients\"]>>distortion_coefficient;\n\n\n//    std::cout<<\"R: \" <<R<<std::endl;\n//    std::cout<<\"t: \" <<t<<std::endl;\n}\n\nvoid test()\n{\n//    unsigned int microseconds=1000000;\n    unsigned int microseconds=0;\n    cv::VideoCapture webCam(1); // open the default camera\n    webCam.set(CV_CAP_PROP_FRAME_WIDTH,640);\n    webCam.set(CV_CAP_PROP_FRAME_HEIGHT,480);\n    webCam.set(CV_CAP_PROP_FPS, 30);\n\n\n    if(!webCam.isOpened())  // check if we succeeded\n        return;\n//    cv::namedWindow(\"camera\",1);\n    for(;;)\n    {\n\n        try\n        {\n\n\n            if(cv::waitKey(200) >= 0) break;\n            cv::Mat image1, image2;\n            webCam >> image1;\n            usleep(microseconds);\n            webCam >> image2;\n\n            std::vector<cv::KeyPoint> image1_keypoints,image2_keypoints;\n            cv::Mat image1_descriptors, image2_descriptors;\n\n            featureDetection(image1,image1_keypoints,image1_descriptors,featuresdetectors::SIFT,featuresdescriptor::DAISY);\n            featureDetection(image2,image2_keypoints,image2_descriptors,featuresdetectors::SIFT,featuresdescriptor::DAISY);\n\n\n//            std::cout<<\"image1_keypoints.size()\"<<image1_keypoints.size() <<std::endl;\n//            std::cout<<\"image2_keypoints.size()\"<<image2_keypoints.size() <<std::endl;\n\n\n            std::vector< cv::DMatch > matches;\n            featureMatching(image1_descriptors, image2_descriptors, matches);\n\n\n            if(matches.size()<20)\n                continue;\n\n        //    std::cout<<\"matches\"<<matches.size() <<std::endl;\n            std::vector< cv::DMatch > good_matches;\n\n    //        std::cout<<\"matches.size()\"<<matches.size() <<std::endl;\n\n            refineMathes(matches,image1_descriptors ,good_matches);\n\n\n\n            if(good_matches.size()<9)\n                continue;\n    //        std::cout<<\"good_matches.size()\"<<good_matches.size() <<std::endl;\n    /**/\n            cv::Mat img_matches;\n            cv::drawMatches( image1, image1_keypoints, image2, image2_keypoints,\n            good_matches, img_matches, cv::Scalar::all(-1), cv::Scalar::all(-1),\n            std::vector<char>(), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );\n\n\n\n\n\n            std::vector<cv::Point2f> points1Raw; //Raw points from Keypoints\n            std::vector<cv::Point2f> points1; //Undistorted points\n            std::vector<cv::Point2f> points2Raw;\n            std::vector<cv::Point2f> points2;\n            for(int k=0; k<good_matches.size(); k++)\n            {\n                points1Raw.push_back(image1_keypoints[good_matches[k].queryIdx].pt);\n                points2Raw.push_back(image2_keypoints[good_matches[k].trainIdx].pt);\n            }\n\n            //4)undistortion\n        //    cv::undistortPoints(points1Raw, points1, cameraMatrixm, distCoeffsm);\n        //    cv::undistortPoints(points2Raw, points2, cameraMatrixm, distCoeffsm);\n\n            points1=points1Raw;\n            points2=points2Raw;\n            std::vector<uchar> states;\n\n            cv::Mat f = cv::findFundamentalMat(points1, points2, cv::FM_RANSAC, 1, 0.99, states);\n\n            double err=0;\n            for(int k=0; k<good_matches.size(); k++)\n            {\n                cv::Mat p1(3, 1, CV_64F);\n                p1.at<double>(0, 0) = points1[k].x;\n                p1.at<double>(1, 0) = points1[k].y;\n                p1.at<double>(2, 0) = 1;\n                cv::Mat p2(1, 3, CV_64F);\n                p2.at<double>(0, 0) = points2[k].x;\n                p2.at<double>(0, 1) = points2[k].y;\n                p2.at<double>(0, 2) = 1;\n\n                cv::Mat res = cv::abs(p2 * f * p1); // f computed matrix\n\n                if((bool)states[k]) //if match considered inlier (in my strange case all)\n                    err = err + res.at<double>(0, 0); //accumulate errors\n\n            }\n\n//            std::cout<<\"Total error is: \" <<err <<std::endl;\n\n\n    ////        std::string camera_calibration_path=\"/home/behnam/workspace/OpenCVProjects/build/front_webcam.yml\";\n    ////        cv::FileStorage fs(camera_calibration_path,cv::FileStorage::READ);\n    ////        cv::Mat camera_matrix, distortion_coefficient;\n    ////        fs[\"camera_matrix\"]>>camera_matrix;\n    ////        fs[\"distortion_coefficients\"]>>distortion_coefficient;\n\n\n    ///*\n    // camera_matrix:\n    //    |fx   0   cx|\n    //    |0   fy   cy|\n    //    |0    0    1|\n\n    //*/\n\n\n\n\n            double cx,cy,focal;\n            cv::Point2d pp;\n\n    //        focal=camera_matrix.at<double>(1,1);\n\n\n    //        cx=camera_matrix.at<double>(0,2);\n    //        cy=camera_matrix.at<double>(1,2);\n//            cv::Point2d pp=cv::Point2d(cx, cy);\n\n\n            //normalize coordinates\n\n            focal=1036.169926;\n            cx=308.412977;\n            cy=270.068003;\n            pp=cv::Point2d(cx,cy);\n\n            //(do not normalize coordinates)\n//            cx=320;\n//            cy=240;\n//            focal=1;\n            //http://answers.opencv.org/question/65788/undistortpoints-findessentialmat-recoverpose-what-is-the-relation-between-their-arguments/\n            //http://answers.opencv.org/question/179981/does-recoverpose-return-up-to-scale-or-correct-translation/\n            //https://docs.opencv.org/3.0-beta/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html#decomposeessentialmat\n            //https://stackoverflow.com/questions/23114047/opencv-camera-relative-pose-estimation\n            //https://github.com/PacktPublishing/OpenCV3-Computer-Vision-Application-Programming-Cookbook-Third-Edition\n\n\n            //By decomposing E, you can only get the direction of the translation, so the function returns unit\n\n            double threshold=1;\n            double prob=0.999;\n            cv::LMEDS;\n            cv::Mat mask,rotation,translation;\n\n            cv::Mat EssentialMatrix= cv::findEssentialMat(points1, points2,focal,pp, cv::LMEDS,prob,threshold,mask);\n\n\n\n//            cv::correctMatches(E, imgpts1, imgpts2, imgpts1, imgpts2)\n\n//  The R and t are the rotation and translation (in camera 2's coordinates) to get to camera 1.\n\n\n            cv::recoverPose(EssentialMatrix, points1, points2, rotation, translation, focal, pp, mask);\n\n\n\n\n\n\n    //        Eigen::Quaternion<double> q =  yawAngle*pitchAngle *rollAngle;\n\n            Eigen::Matrix3d rotationMatrix;\n            rotationMatrix(0,0)=rotation.at<double>(0,0);\n            rotationMatrix(0,1)=rotation.at<double>(0,1);\n            rotationMatrix(0,2)=rotation.at<double>(0,2);\n            rotationMatrix(1,0)=rotation.at<double>(1,0);\n            rotationMatrix(1,1)=rotation.at<double>(1,1);\n            rotationMatrix(1,2)=rotation.at<double>(1,2);\n            rotationMatrix(2,0)=rotation.at<double>(2,0);\n            rotationMatrix(2,1)=rotation.at<double>(2,1);\n            rotationMatrix(2,2)=rotation.at<double>(2,2);\n\n\n\n            std::cout.precision(3);\n            std::cout.setf(std::ios_base::fixed);\n\n\n//            std::cout<<rotationMatrix <<std::endl;\n\n//            Eigen::Quaterniond quaternion_mat(rotationMatrix);\n//            std::cout<<\"quaternion_mat.x(): \" <<quaternion_mat.x()<<std::endl;\n//            std::cout<<\"quaternion_mat.y(): \" <<quaternion_mat.y()<<std::endl;\n//            std::cout<<\"quaternion_mat.z(): \" <<quaternion_mat.z()<<std::endl;\n//            std::cout<<\"quaternion_mat.w(): \" <<quaternion_mat.w()<<std::endl;\n//            std::cout<<\"--------------------------\" <<std::endl;\n//            std::cout<<\"translation: \" <<std::endl;\n//            //cv::norm(translation, cv::NORM_L2, cv::Mat());\n\n            double minVal;\n            double maxVal=0;\n            cv::Point minLoc;\n            cv::Point maxLoc;\n            double scale=100;\n\n            cv::minMaxLoc(translation, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat());\n            translation=translation/(std::abs(maxVal)*scale);\n\n\n            std::cout.precision(3);\n            std::cout.setf(std::ios_base::fixed);\n\n            std::cout<<translation.at<double>(0,0)<<std::endl;\n//            std::cout<<translation.at<double>(1,0)<<std::endl;\n//            std::cout<<translation.at<double>(2,0)<<std::endl;\n\n\n\n\n//            std::cout<<\"roll is: \" <<atan2( rotationMatrix(2,1),rotationMatrix(2,2) ) <<std::endl;\n//            std::cout<<\"pitch: \" <<atan2( -rotationMatrix(2,0), std::pow( rotationMatrix(2,1)*rotationMatrix(2,1) +rotationMatrix(2,2)*rotationMatrix(2,2) ,0.5  )  ) <<std::endl;\n//            std::cout<<\"yaw is: \" <<atan2( rotationMatrix(1,0),rotationMatrix(0,0) ) <<std::endl;\n\n\n\n//            std::cout<<\"EssentialMatrix: \"<<std::endl;\n//            std::cout<<EssentialMatrix<<std::endl;\n////            std::cout<<\"f: \"<<std::endl;\n////            std::cout<<f<<std::endl;\n\n\n\n            std::string window_title=\"matches\";\n            cv::imshow(window_title, img_matches);\n\n        }\n               catch (const std::exception& e)\n               { /* */ }\n\n\n////        cv::waitKey(0);\n\n\n\n    }\n}\n\nint main(int argc , char ** argv)\n{\n    //dumb(argc, argv);\n//    featureDetection_test(argc, argv);\n//    featureMatching_Test(argc, argv);\n\n    test();\n}\n", "meta": {"hexsha": "8b8341633d046f2f0fde255f1ae23a966e26cf15", "size": 31246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/legecy/OpenCV3BasicOperations.cpp", "max_stars_repo_name": "behnamasadi/OpenCVProjects", "max_stars_repo_head_hexsha": "157c8d536c78c5660b64a23300a7aaf941584756", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/legecy/OpenCV3BasicOperations.cpp", "max_issues_repo_name": "behnamasadi/OpenCVProjects", "max_issues_repo_head_hexsha": "157c8d536c78c5660b64a23300a7aaf941584756", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/legecy/OpenCV3BasicOperations.cpp", "max_forks_repo_name": "behnamasadi/OpenCVProjects", "max_forks_repo_head_hexsha": "157c8d536c78c5660b64a23300a7aaf941584756", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5818561001, "max_line_length": 213, "alphanum_fraction": 0.6031812072, "num_tokens": 8439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4352574314698224}}
{"text": "/*\n * <one line to give the library's name and an idea of what it does.>\n * Copyright (C) 2016  <copyright holder> <email>\n * \n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n * \n */\n\n#include \"impact.h\"\n\n#include <boost/geometry/algorithms/intersection.hpp> \n#include <list>\n\nusing namespace mia;\n\nbool mia::impact(const Segment2 & s1, const Segment2 & s2)\n{\n  std::list<Float2> X;\n  return ( boost::geometry::intersection(s1, s2, X) && !X.empty() );\n}\n\nbool mia::impact(const Segment2 & s1, const Segment2 & s2, Float2 & point)\n{\n  std::list<Float2> X;\n  if( boost::geometry::intersection(s1, s2, X) && !X.empty() )\n  {\n    point= *(X.begin());\n    return true;\n  }\n  return false;\n}\n\nbool mia::impact(const Circle2 & c1, const Circle2 & c2)\n{\n    Float2 between= c2.center - c1.center;\n    float distMin= c1.radius + c2.radius;\n\n    return between.length2() < (distMin*distMin);\n}\n\nbool mia::impact(const Circle2 & c1, const Circle2 & c2, Float2 & point)\n{\n    Float2 between= c2.center - c1.center;\n    float distMin= c1.radius + c2.radius;\n    bool out(false);\n    \n    if( between.length2() < (distMin*distMin) )\n    {\n      point= c2.center + (between*0.5f);\n      out= true;\n    }\n    return out;\n}\n\nbool mia::impact(const Float2 & v, const Circle2 & c){\n  Float2 d(v - c.center);\n  return d.length2() < (c.radius*c.radius);\n}\n\nbool mia::impact(const Segment2 & s, const Circle2 & c){\n  Float2 out;\n  return impact(s, c, out);\n}\n\nbool mia::impact(const Segment2 & s, const Circle2 & c, Float2 & point){\n    \n    Float2 radius= s.b - s.a;\n    radius.orthonormalize(c.radius);\n    Segment2 diametre( c.center - radius, c.center + radius );\n    \n    if ( impact( s, diametre, point ) )\n    {\n        return true;\n    }\n\n    if( impact( s.a, c ) )\n    {\n        point= s.a;\n        return true;\n    }\n\n    if( impact( s.b, c ) )\n    {\n        point= s.b;\n        return true;\n    }\n\n    return false;\n}\n\nbool mia::impact(const Polygon2 & p1, const Polygon2 & p2)\n{\n  std::list<Polygon2> output;\n  return (boost::geometry::intersection(p1, p2, output) && !output.empty() );\n}\n\nbool mia::impact(const Polygon2 & p1, const Polygon2 & p2, std::list<Polygon2> & output)\n{\n  return (boost::geometry::intersection(p1, p2, output) && !output.empty() );\n}\n\n// bool mia::impact(const Polygon2 & p1, Polygon2 & p2, Float2 & point)\n// {\n//   std::list<Polygon2> output;\n//   boost::geometry::intersection(p1, p2, output);\n//   compute mean point of output;\n//   return output.empty();\n// }\n", "meta": {"hexsha": "a6843f72c2ccd172a105b6012b7434e7e734273b", "size": 3082, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "torob/src/impact.cpp", "max_stars_repo_name": "CARMinesDouai/MutiRobotExplorationPackages", "max_stars_repo_head_hexsha": "725f36eaa22adb33be7f5961db1a0f8e50fdadbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-12-10T15:44:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-27T17:40:11.000Z", "max_issues_repo_path": "torob/src/impact.cpp", "max_issues_repo_name": "CARMinesDouai/MutiRobotExplorationPackages", "max_issues_repo_head_hexsha": "725f36eaa22adb33be7f5961db1a0f8e50fdadbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-14T15:19:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-26T21:26:47.000Z", "max_forks_repo_path": "torob/src/impact.cpp", "max_forks_repo_name": "CARMinesDouai/MutiRobotExplorationPackages", "max_forks_repo_head_hexsha": "725f36eaa22adb33be7f5961db1a0f8e50fdadbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-01-29T03:01:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T14:59:10.000Z", "avg_line_length": 25.6833333333, "max_line_length": 88, "alphanum_fraction": 0.6408176509, "num_tokens": 872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4352574314698223}}
{"text": "#ifndef COMPOSITE_STEP_SOLVERS\n#define COMPOSITE_STEP_SOLVERS\n\n#include <memory> // std::unique_ptr\n#include <vector>\n\n#include <boost/timer/timer.hpp>\n\n#include \"algorithm/opt_interface.hh\"\n#include \"algorithm/newton_bridge.hh\"\n#include \"linalg/triplet.hh\"\n#include \"linalg/tcg.hh\"\n\nnamespace Kaskade\n{\n  namespace Bridge\n  {\n    template<class DirectSolver>\n    class DirectInnerSolver\n    {\n    public:\n      DirectInnerSolver(int numberOfBlocks_,bool stabilization_=true) : numberOfBlocks(numberOfBlocks_), stabilization(stabilization_) {}\n\n      // on exit: sol=(dx, p), where dx is normal step, p is least squares update of Lagrange multiplier\n      void solveAdjAndNormal(std::vector<double>& sol, SparseLinearSystem const& lin)\n      {\n        MatrixAsTriplet<double> mat;\n        lin.getMatrix(mat);\n        //      mat.print();\n        if(stabilization)\n        {\n          // stabilization: cf. Conn/Gould/Toint pg. 110, (5.4.7)\n          AT.flush();\n          lin.getMatrixBlocks(AT,0,numberOfBlocks,numberOfBlocks,lin.nColBlocks());\n          // shift c'(x)^* to block matrix (0 c'(x)^*)\n          AT.shiftIndices(0,lin.cols(0,numberOfBlocks));\n          // AT is (0 c'(x)^*)\n          ATx.resize(0);\n        }\n        solver.reset(new DirectSolver(mat.nrows(),\n            2,\n            mat.ridx,\n            mat.cidx,\n            mat.data,\n            MatrixProperties::GENERAL));\n        std::vector<double> r,s, soladj;\n        sz=lin.size();\n        lin.getRHSBlocks(r,0,numberOfBlocks);\n        lin.getRHSBlocks(s,numberOfBlocks,lin.nRowBlocks());\n\n        std::vector<double> rg(sz,0.0),rc(sz,0.0);\n        for(int i=0;i<r.size();++i) rg[i]=r[i];\n        for(int i=0;i<s.size();++i) rc[i+r.size()]=s[i];\n\n        solver->solve(rg,soladj);\n        solver->solve(rc,sol);\n        for(int i=r.size(); i<sol.size();++i) sol[i]=soladj[i];\n\n      }\n\n      // Application of \"preconditioner\"\n      // stabilization: cf. Conn/Gould/Toint pg. 110, (5.4.7)\n      void ax(std::vector<double>& sol, std::vector<double>const &r) const\n      {\n        std::vector<double> r1(sz,0.0),x;\n        if(stabilization && ATx.size()!=0)\n          for(int i=0;i<r.size();++i)\n            r1[i]=r[i]-ATx[i];\n        else\n          for(int i=0;i<r.size();++i)\n            r1[i]=r[i];\n        solver->solve(r1,x);\n        if(stabilization) AT.ax(ATx,x);\n        for(int i=0; i<sol.size(); ++i) sol[i]=x[i];\n      }\n\n      void resolveNormal(std::vector<double>& sol, SparseLinearSystem const& lin)\n      {\n        std::vector<double> s,r2(sz,0.0);\n        lin.getRHSBlocks(s,numberOfBlocks,lin.nRowBlocks());\n        for(int i=0;i<s.size();++i) r2[i+lin.rows(0,numberOfBlocks)]=s[i];\n        solver->solve(r2,sol);\n        for(int i=lin.rows(0,numberOfBlocks); i<sol.size();++i) sol[i]=0.0;\n\n      }\n    private:\n      MatrixAsTriplet<double> AT;\n      mutable std::vector<double> ATx;\n      std::unique_ptr<DirectSolver> solver;\n      int numberOfBlocks, sz;\n      bool stabilization;\n    };\n\n    template <class VectorImpl,class InnerSolver>\n    class ProjTCGSolver : public AbstractTangentialSpace\n    {\n    public:\n      virtual void setRelativeAccuracy(double accuracy) { acc=accuracy; };\n      virtual   double getRelativeAccuracy() { return acc; }\n      virtual   double getAbsoluteAccuracy() { return acc; }\n      virtual   bool improvementPossible() { return true; }\n      virtual   int nSolutionVectors() const { return 2; }\n      ProjTCGSolver(InnerSolver& solver_, int numberOfBlocks_) : solver(solver_), numberOfBlocks(numberOfBlocks_) {}\n      virtual ~ProjTCGSolver() {}\n    private:\n\n      double acc;\n\n      virtual int doSolve(std::vector<AbstractVector* >& correction,\n          AbstractLinearization& linT, AbstractLinearization& linN, int start, double nu0)\n      {\n        SparseLinearSystem const &lT = dynamic_cast<SparseLinearSystem const &>(linT);\n        SparseLinearSystem const &lN = dynamic_cast<SparseLinearSystem const &>(linN);\n\n        boost::timer::cpu_timer timer;\n\n        std::vector<double> r(lN.rows(0,numberOfBlocks),0.0);\n\n        // r=f'(x)\n        lN.getRHSBlocks(r,0,numberOfBlocks);\n\n\tdouble rsum(0.0);\n\tfor(int i=0; i<r.size(); ++i)\n\t  rsum += fabs(r[i]);\n\n\n\tstd::cout << \"r:\" << rsum << \" \" << r.size() << \" \" << numberOfBlocks << std::endl;\n\n        MatrixAsTriplet<double> m;\n        int dimx=lT.rows(0,numberOfBlocks);\n        std::vector<double> x,p,normalstep;\n        x.reserve(lT.size());\n        p.reserve(lT.size());\n\n        if(start >=1)\n          dynamic_cast<Bridge::Vector<VectorImpl>& >(*(correction[start-1])).write(normalstep);\n\n        dynamic_cast<Bridge::Vector<VectorImpl>const & >(linN.getOrigin()).write(x );\n\n        MatrixAsTriplet<double> H;\n        // H = c'(x)^*\n        lN.getMatrixBlocks(H,0,numberOfBlocks,numberOfBlocks,lN.nColBlocks());\n        H.shiftIndices(0,lN.cols(0,numberOfBlocks));\n        H.axpy(r,x);\n        H.flush();\n        // r = f'(x)+c'(x)^*p\n        lT.getMatrixBlocks(H,0,numberOfBlocks,0,numberOfBlocks);\n        // r = f'(x)+c'(x)^*p+nu_0 L_xx delta n\n        H.axpy(r,normalstep,nu0);\n\n        for(int i=0; i< r.size(); ++i)\n        {\n          r[i] *= -1.0;\n          x[i] = 0.0;\n        }\n\n        // min <Hx,x>+<r,x>\n        int exit=projectedtcg(x,p,H,solver,r,1e-6,100);\n\n        for(int i=0; i<dimx;++i) x[i] *= -1.0;\n        for(int i=dimx; i<lT.size();++i) x.push_back(0.0);\n        dynamic_cast<Bridge::Vector<VectorImpl>& >(*(correction[start])).read(x);\n\n        std::cout << \" ProjTCG:\" << (double)(timer.elapsed().user)/1e9 << std::endl;\n\n        if(exit==2)\n        {\n          for(int i=0; i<dimx;++i) p[i] *= -1.0;\n          for(int i=dimx; i<lT.size();++i) p.push_back(0.0);\n          dynamic_cast<Bridge::Vector<VectorImpl>& >(*(correction[start+1])).read(p);\n          return 2;\n        }\n        return 1;\n\n      }\n      InnerSolver& solver;\n      int numberOfBlocks;\n    };\n\n\n    template <class VectorImpl,class InnerSolver>\n    class TCGSolver : public AbstractTangentialSpace\n    {\n    public:\n      virtual   void setRelativeAccuracy(double accuracy) { acc=accuracy; };\n      virtual   double getRelativeAccuracy() { return acc; }\n      virtual   double getAbsoluteAccuracy() { return acc; }\n      virtual   bool improvementPossible() { return true; }\n      virtual   int nSolutionVectors() const { return 2; }\n      TCGSolver(InnerSolver& solver_, int numberOfBlocks_) : solver(solver_), numberOfBlocks(numberOfBlocks_) {}\n      virtual ~TCGSolver() {}\n    private:\n      double acc;\n\n      virtual int doSolve(std::vector<AbstractVector* >& correction,\n          AbstractLinearization& linT, AbstractLinearization& linN, int start, double d1, double d2, double d3, double d4, double nu0)\n      {\n        SparseLinearSystem const &lT = dynamic_cast<SparseLinearSystem const &>(linT);\n        SparseLinearSystem const &lN = dynamic_cast<SparseLinearSystem const &>(linN);\n        MatrixAsTriplet<double> m;\n        int dimx=lT.rows(0,numberOfBlocks);\n        std::vector<double> x,p,normalstep;\n        if(start >=1)\n          dynamic_cast<Bridge::Vector<VectorImpl>& >(*(correction[start-1])).write(normalstep);\n\n        solver.solveTCG(x,p,lT,lN,normalstep,nu0);\n\n        for(int i=0; i<dimx;++i) x[i] *= -1.0;\n        for(int i=dimx; i<x.size();++i) x[i] *= 0.0;\n        dynamic_cast<Bridge::Vector<VectorImpl>& >(*(correction[start])).read(x);\n        if(p.size() != 0)\n        {\n          for(int i=0; i<dimx;++i) p[i] *= -1.0;\n          for(int i=dimx; i<p.size();++i) p[i] *= 0.0;\n          dynamic_cast<Bridge::Vector<VectorImpl>& >(*(correction[start+1])).read(p);\n          return 2;\n        }\n        return 1;\n\n      }\n      InnerSolver& solver;\n      int numberOfBlocks;\n    };\n\n    template <class VectorImpl,class InnerSolver>\n    class PINVSolver : public AbstractNormalDirection\n    {\n    public:\n\n      virtual void setRelativeAccuracy(double accuracy) { acc=accuracy; };\n      virtual   double getRelativeAccuracy() { return acc; }\n      virtual   double getAbsoluteAccuracy() { return acc; }\n      virtual   bool improvementPossible() { return true; }\n      virtual ~PINVSolver() {}\n\n      PINVSolver(InnerSolver& solver_, int numberOfBlocks_) : solver(solver_), numberOfBlocks(numberOfBlocks_) {};\n\n      void computeCorrectionAndAdjointCorrection(Kaskade::AbstractVector&, Kaskade::AbstractVector&, Kaskade::AbstractLinearization&){assert(\"not implemented\");}\n      void computeSimplifiedCorrection(Kaskade::AbstractVector&, const Kaskade::AbstractLinearization&) const {assert(\"not implemented\");}\n\n    private:\n\n      double acc;\n      virtual void doSolve(AbstractVector& correction,\n          AbstractVector& iterate,\n          AbstractLinearization& lin)\n      {\n        SparseLinearSystem const &l = dynamic_cast<SparseLinearSystem const &>(lin);\n        int dimx=l.rows(0,numberOfBlocks);\n        if(dimx==l.size()) return;\n        std::vector<double> xcor(l.size(),0.0);\n        solver.solveAdjAndNormal(xcor,l);\n        for(int i=0; i< xcor.size(); ++i) xcor[i]*=-1.0;\n\n        std::vector<double> xiterate;\n        dynamic_cast<Bridge::Vector<VectorImpl>& >(iterate).write(xiterate);\n\n\n        // update dual variables of iterate\n        for(int i=dimx; i< xcor.size(); ++i)\n        {\n          xiterate[i]= xcor[i];\n          xcor[i]=0.0;\n        }\n\n        // read data into correction and iterate\n        dynamic_cast<Bridge::Vector<VectorImpl>& >(correction).read(xcor);\n        dynamic_cast<Bridge::Vector<VectorImpl>& >(iterate).read(xiterate);\n      }\n\n\n      virtual void doResolve(AbstractVector& correction,\n          AbstractLinearization const& lin) const\n      {\n        SparseLinearSystem const &l = dynamic_cast<SparseLinearSystem const &>(lin);\n        int dimx=l.rows(0,numberOfBlocks);\n        if(l.size()==dimx) return;\n        std::vector<double> x(l.size(),0.0);\n        solver.resolveNormal(x,l);\n        for(int i=0; i< dimx; ++i) x[i]*=-1.0;\n        for(int i=dimx; i< x.size(); ++i) x[i]=0.0;\n\n        dynamic_cast<Bridge::Vector<VectorImpl>& >(correction).read(x);\n      }\n\n      MatrixAsTriplet<double> m;\n      mutable MatrixAsTriplet<double> P;\n      InnerSolver& solver;\n      int numberOfBlocks;\n    };\n\n    //   template<class LinImpl, class VectorImpl,class Preconditioner>\n    //   class TCGWithPreconditioner : public AbstractTangentialSolver\n    //   {\n    //   public:\n    //     virtual void setRelativeAccuracy(double accuracy) { acc=accuracy; };\n    //     virtual   double getRelativeAccuracy() { return acc; }\n    //     virtual   double getAbsoluteAccuracy() { return acc; }\n    //     virtual   bool improvementPossible() { return true; }\n    //     virtual   bool localConvergenceLikely() { return lCl; }\n\n    //     virtual   int nSolutionVectors() const { return 2; }\n\n    //     TCGWithPreconditioner(int primalblocks_) :\n    //       Me(3), Ae(4), addreg(0.0), primalblocks(primalblocks_) , tcgfile(\"tcg.log\",std::ios::out)\n    //     {}\n\n    //     virtual ~TCGWithPreconditioner() {};\n\n    //     virtual bool getNormInfo(std::vector<double>& M,std::vector<double>& A) const\n    //     {\n    //       M=Me;\n    //       A=Ae;\n    //       return true;\n    //     }\n\n    //   private:\n\n    //     std::vector<double> Me, Ae;\n    //     double acc;\n    //     double addreg;\n    //     bool lCl;\n\n    //     virtual int doSolve(std::vector<AbstractVector* >& correction,\n    //                         AbstractLinearization& linT, AbstractLinearization& linN, int start,\n    //                         double ThetaAim, double omegaC, double omegaL, double omegaH, double nu0)\n    //     {\n    //       SparseLinearSystem &lT = dynamic_cast<SparseLinearSystem &>(linT);\n    //       SparseLinearSystem &lN = dynamic_cast<SparseLinearSystem &>(linN);\n\n    //       MatrixAsTriplet<double> NM;\n\n    //       lN.getMatrix(NM);\n\n\n    //       boost::timer timer;\n\n    //       std::vector<double> r(lN.rows(0,primalblocks),0.0);\n\n    //       // r = f'(x)\n\n    //       lN.getRHSBlocks(r,0,primalblocks);\n    //       int dimx=lT.rows(0,primalblocks);\n\n    //       if(primalblocks < lT.nColBlocks())\n    //       {\n    //         // if equality constraints are present, then r += C'(x)^T p\n    //         // this is for numerical stability\n    //         std::vector<double> x;\n    //         dynamic_cast<Bridge::Vector<VectorImpl>const & >(linN.getOrigin()).write(x);\n    //         MatrixAsTriplet<double> CPrimeTransposed;\n    //         lT.getMatrixBlocks(CPrimeTransposed,0,primalblocks,primalblocks,lT.nColBlocks());\n    //         CPrimeTransposed.shiftIndices(0,lN.cols(0,primalblocks));\n    //         CPrimeTransposed.axpy(r,x);\n    //       }\n\n    //       MatrixAsTriplet<double> Hessian;\n    //       lT.getMatrixBlocks(Hessian,0,primalblocks,0,primalblocks);\n\n    //       if(start >=1)\n    //       {\n    //         // if normal step was taken, then r += nu_0 H delta n\n    //         // this guarantees second order approximation\n\n    //         std::vector<double> normalstep;\n    //         dynamic_cast<Bridge::Vector<VectorImpl>& >(*(correction[start-1])).write(normalstep);\n    //         Hessian.axpy(r,normalstep,nu0);\n    //       }\n\n    //       std::vector<double> x(lT.size(),0.0),p(lT.size(),0.0);\n\n    // // Preconditioner is only created at the beginning of the whole algorithm\n\n    // //      if(!(prec_ptr.get()))\n    //         prec_ptr.reset(new Preconditioner(lN));\n\n\n    //       int maxiter=1000;\n\n    //       int exit(2);\n\n    //       double negm(1e300), posdefalpha(1.0);\n\n    // // for unregularized tcg:\n\n    //       addreg = 0.0;\n\n    //       int ntrial(0);\n\n    //       do\n    //       {\n    //         PrecWrapperForStdVector<Preconditioner> prec(*prec_ptr);\n    //         maxiter=1000;\n    //         std::cout << \"Regularization \" << addreg << std::endl;\n    //         exit=tcgRegForCubic(x,p,Hessian,prec,r,acc,omegaL,omegaH, addreg,maxiter, ntrial,Me,Ae,tcgfile);\n    //         if(exit==-1)\n    //           prec_ptr.reset(new Preconditioner(lN));\n\n    //         std::cout << \"Negative Curvature: \" << Ae[3] << std::endl;\n    //         negm=std::min(negm,Ae[3]);\n    //         if(addreg >0 ) posdefalpha=0.0;\n    //         ntrial++;\n    //         lCl = (addreg == 0.0);\n    //       } while(exit !=1);\n\n    //       addreg=std::max(0.0,-negm);\n\n    // //        if(posdefalpha>0.0)\n    // //              prec_ptr.reset(new Preconditioner(lT));\n    //                       //Preconditioner preconditioner(lN);\n\n    //       std::vector<double> Mx(x.size());\n\n    //       NM.ax(Mx,x);\n    //       double sum(0.0);\n    //       for(int i=0; i<x.size();++i)\n    //         sum += x[i]*Mx[i];\n\n    //       std::cout << \"xMx:\" << sum << \" \"  << Me[0] << \" \";\n\n    //       sum=0.0;\n\n    //       for(int i=0; i<x.size();++i)\n    //         sum += p[i]*Mx[i];\n\n    //       std::cout << \"pMx:\" << sum << \" \" << Me[2] << \" \";\n\n    //       NM.ax(Mx,p);\n    //       sum=0.0;\n    //       for(int i=0; i<x.size();++i)\n    //         sum += p[i]*Mx[i];\n\n    //       std::cout << \"pMp:\" << sum << \" \" << Me[1] << std::endl;\n\n\n    //       // no update of lagrangian multiplier\n    //       for(int i=dimx; i<lT.size();++i) x.push_back(0.0);\n    //       dynamic_cast<Bridge::Vector<VectorImpl>& >(*(correction[start])).read(x);\n\n    //       std::cout << \" ProjTCG: exit:\" << exit << \" t:\" << timer.elapsed() << \" it:\" << maxiter << std::endl;\n\n    //       if(exit==2)\n    //       {\n    //         for(int i=dimx; i<lT.size();++i) p.push_back(0.0);\n    //         dynamic_cast<Bridge::Vector<VectorImpl>& >(*(correction[start+1])).read(p);\n    //         return 2;\n    //       }\n    //       return 1;\n\n    //     }\n    //     int primalblocks;\n    //     std::ofstream tcgfile;\n    //     std::unique_ptr<Preconditioner> prec_ptr;\n    //   };\n\n\n  }\n} // namespace Kaskade\n#endif\n", "meta": {"hexsha": "00a4bf953a06678716962545c3e2be620c04ab4e", "size": 15840, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/linalg/composite_step_solvers.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/linalg/composite_step_solvers.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/linalg/composite_step_solvers.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 34.4347826087, "max_line_length": 161, "alphanum_fraction": 0.5670454545, "num_tokens": 4357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4350881308629726}}
{"text": "#ifndef YAC_CORE_HPP\n#define YAC_CORE_HPP\n\n/*****************************************************************************\n * This file is huge, it contains everything from parsing yaml files, linear\n * algebra functions to networking code used for robotics.\n *\n * Contents:\n * - Data Type\n * - Macros\n * - Data\n * - Filesystem\n * - Configuration\n * - Algebra\n * - Linear Algebra\n * - Geometry\n * - Differential Geometry\n * - Statistics\n * - Transform\n * - Time\n * - Networking\n * - Interpolation\n * - Control\n * - Measurements\n * - Models\n * - Vision\n * - Parameters\n * - Simulation\n * - Factor Graph\n *\n ****************************************************************************/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <sys/time.h>\n#include <inttypes.h>\n#include <dirent.h>\n#include <execinfo.h>\n#include <signal.h>\n#include <unistd.h>\n#include <errno.h>\n#include <pthread.h>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/poll.h>\n\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include <random>\n#include <set>\n#include <list>\n#include <deque>\n#include <vector>\n#include <unordered_map>\n#include <unordered_set>\n#include <type_traits>\n\n#include <yaml-cpp/yaml.h>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/Geometry>\n#include <unsupported/Eigen/Splines>\n\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/features2d/features2d.hpp>\n\n#define ENABLE_MACROS 1\n\nnamespace yac {\n\n/******************************************************************************\n *                                DATA TYPE\n *****************************************************************************/\n\n/* PRECISION TYPE */\n// #define PRECISION 1 // Single Precision\n#define PRECISION 2 // Double Precision\n\n#if PRECISION == 1\n  #define real_t float\n#elif PRECISION == 2\n  #define real_t double\n#else\n  #define real_t double\n#endif\n\n#define col_major_t Eigen::ColMajor\n#define row_major_t Eigen::RowMajor\n\ntypedef Eigen::Matrix<real_t, 2, 1> vec2_t;\ntypedef Eigen::Matrix<real_t, 3, 1> vec3_t;\ntypedef Eigen::Matrix<real_t, 4, 1> vec4_t;\ntypedef Eigen::Matrix<real_t, 5, 1> vec5_t;\ntypedef Eigen::Matrix<real_t, 6, 1> vec6_t;\ntypedef Eigen::Matrix<real_t, Eigen::Dynamic, 1> vecx_t;\ntypedef Eigen::Matrix<real_t, 2, 2> mat2_t;\ntypedef Eigen::Matrix<real_t, 3, 3> mat3_t;\ntypedef Eigen::Matrix<real_t, 4, 4> mat4_t;\ntypedef Eigen::Matrix<real_t, Eigen::Dynamic, Eigen::Dynamic> matx_t;\ntypedef Eigen::Matrix<real_t, 3, 4> mat34_t;\ntypedef Eigen::Quaternion<real_t> quat_t;\ntypedef Eigen::AngleAxis<real_t> angle_axis_t;\ntypedef Eigen::Matrix<real_t, 1, Eigen::Dynamic> row_vector_t;\ntypedef Eigen::Matrix<real_t, Eigen::Dynamic, 1> col_vector_t;\ntypedef Eigen::Array<real_t, Eigen::Dynamic, 1> arrayx_t;\n\ntypedef Eigen::SparseMatrix<real_t> sp_mat_t;\ntypedef Eigen::SparseVector<real_t> sp_vec_t;\n\ntypedef std::vector<vec2_t, Eigen::aligned_allocator<vec2_t>> vec2s_t;\ntypedef std::vector<vec3_t, Eigen::aligned_allocator<vec3_t>> vec3s_t;\ntypedef std::vector<vec4_t, Eigen::aligned_allocator<vec4_t>> vec4s_t;\ntypedef std::vector<vec5_t, Eigen::aligned_allocator<vec5_t>> vec5s_t;\ntypedef std::vector<vec6_t, Eigen::aligned_allocator<vec6_t>> vec6s_t;\ntypedef std::vector<vecx_t> vecxs_t;\ntypedef std::vector<mat2_t, Eigen::aligned_allocator<mat2_t>> mat2s_t;\ntypedef std::vector<mat3_t, Eigen::aligned_allocator<mat3_t>> mat3s_t;\ntypedef std::vector<mat4_t, Eigen::aligned_allocator<mat4_t>> mat4s_t;\ntypedef std::vector<matx_t, Eigen::aligned_allocator<matx_t>> matxs_t;\ntypedef std::vector<quat_t, Eigen::aligned_allocator<quat_t>> quats_t;\n\ntemplate <int LENGTH, Eigen::StorageOptions STRIDE_TYPE = Eigen::ColMajor>\nusing vec_t = Eigen::Matrix<real_t, LENGTH, 1, STRIDE_TYPE>;\n\ntemplate <int ROWS,\n          int COLS,\n          Eigen::StorageOptions STRIDE_TYPE = Eigen::ColMajor>\nusing mat_t = Eigen::Matrix<real_t, ROWS, COLS, STRIDE_TYPE>;\n\ntemplate <int ROWS,\n          int COLS,\n          Eigen::StorageOptions STRIDE_TYPE = Eigen::ColMajor>\nusing map_mat_t = Eigen::Map<Eigen::Matrix<real_t, ROWS, COLS, STRIDE_TYPE>>;\n\ntemplate <int ROWS>\nusing map_vec_t = Eigen::Map<Eigen::Matrix<real_t, ROWS, 1>>;\n\ntypedef std::unordered_map<long, std::unordered_map<long, real_t>> mat_hash_t;\ntypedef std::vector<std::pair<long int, long int>> mat_indicies_t;\n\ntypedef int64_t timestamp_t;\ntypedef std::vector<timestamp_t> timestamps_t;\n\n/******************************************************************************\n *                                MACROS\n *****************************************************************************/\n#ifdef ENABLE_MACROS\n\n#define __FILENAME__                                                           \\\n  (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)\n\n#define LOG_ERROR(M, ...)                                                      \\\n  fprintf(stderr,                                                              \\\n          \"\\033[31m[ERROR] [%s:%d] \" M \"\\033[0m\\n\",                            \\\n          __FILENAME__,                                                        \\\n          __LINE__,                                                            \\\n          ##__VA_ARGS__)\n\n#define LOG_INFO(M, ...) fprintf(stdout, \"[INFO] \" M \"\\n\", ##__VA_ARGS__)\n#define LOG_WARN(M, ...)                                                       \\\n  fprintf(stdout, \"\\033[33m[WARN] \" M \"\\033[0m\\n\", ##__VA_ARGS__)\n\n#define FATAL(M, ...)                                                          \\\n  fprintf(stdout,                                                              \\\n          \"\\033[31m[FATAL] [%s:%d] \" M \"\\033[0m\\n\",                            \\\n          __FILENAME__,                                                        \\\n          __LINE__,                                                            \\\n          ##__VA_ARGS__);                                                      \\\n  exit(-1)\n\n#ifdef NDEBUG\n#define DEBUG(M, ...)\n#else\n#define DEBUG(M, ...) fprintf(stdout, \"[DEBUG] \" M \"\\n\", ##__VA_ARGS__)\n#endif\n\n#define UNUSED(expr)                                                           \\\n  do {                                                                         \\\n    (void) (expr);                                                             \\\n  } while (0)\n\n#ifndef CHECK\n#define CHECK(A, M, ...)                                                       \\\n  if (!(A)) {                                                                  \\\n    LOG_ERROR(M, ##__VA_ARGS__);                                               \\\n    goto error;                                                                \\\n  }\n#endif\n\n#endif // ENABLE_MACROS ------------------------------------------------------\n\n/******************************************************************************\n *                                  DATA\n *****************************************************************************/\n\n/**\n * Convert bytes to signed 8bit number\n */\nint8_t int8(const uint8_t *data, const size_t offset);\n\n/**\n * Convert bytes to unsigned 8bit number\n */\nuint8_t uint8(const uint8_t *data, const size_t offset);\n\n/**\n * Convert bytes to signed 16bit number\n */\nint16_t int16(const uint8_t *data, const size_t offset);\n\n/**\n * Convert bytes to unsigned 16bit number\n */\nuint16_t uint16(const uint8_t *data, const size_t offset);\n\n/**\n * Convert bytes to signed 32bit number\n */\nint32_t int32(const uint8_t *data, const size_t offset);\n\n/**\n * Convert bytes to unsigned 32bit number\n */\nuint32_t uint32(const uint8_t *data, const size_t offset);\n\n/**\n * Allocate memory for a C-style string\n */\nchar *malloc_string(const char *s);\n\n/**\n * Get number of rows in CSV file.\n * @returns Number of rows in CSV file else -1 for failure.\n */\nint csv_rows(const char *fp);\n\n/**\n * Get number of cols in CSV file.\n * @returns Number of cols in CSV file else -1 for failure.\n */\nint csv_cols(const char *fp);\n\n/**\n * Return csv fields as strings and number of fields in csv file.\n */\nchar **csv_fields(const char *fp, int *nb_fields);\n\n/**\n * Load data in csv file `fp`. Assumming the data are real_ts. Also returns\n * number of rows and cols in `nb_rows` and `nb_cols` respectively.\n */\nreal_t **csv_data(const char *fp, int *nb_rows, int *nb_cols);\n\n/**\n * Load integer arrays in csv file located at `csv_path`. The number of arrays\n * is returned in `nb_arrays`.\n */\nint **load_iarrays(const char *csv_path, int *nb_arrays);\n\n/**\n * Load real_t arrays in csv file located at `csv_path`. The number of arrays\n * is returned in `nb_arrays`.\n */\nreal_t **load_darrays(const char *csv_path, int *nb_arrays);\n\n/**\n * Get number of rows in CSV file.\n * @returns Number of rows in CSV file else -1 for failure.\n */\nint csv_rows(const std::string &file_path);\n\n/**\n * Get number of columns in CSV file.\n * @returns Number of columns in CSV file else -1 for failure.\n */\nint csv_cols(const std::string &file_path);\n\n/**\n * Convert CSV file to matrix.\n * @returns 0 for success, -1 for failure\n */\nint csv2mat(const std::string &file_path, const bool header, matx_t &data);\n\n/**\n * Convert matrix to csv file.\n * @returns 0 for success, -1 for failure\n */\nint mat2csv(const std::string &file_path, const matx_t &data);\n\n/**\n * Convert vector to csv file.\n * @returns 0 for success, -1 for failure\n */\nint vec2csv(const std::string &file_path, const std::deque<vec3_t> &data);\n\n/**\n * Convert timestamps to csv file.\n * @returns 0 for success, -1 for failure\n */\nint ts2csv(const std::string &file_path, const std::deque<timestamp_t> &data);\n\n/**\n * Print progress to screen\n */\nvoid print_progress(const real_t percentage);\n\n/**\n * Check if vector `x` is all true.\n */\nbool all_true(const std::vector<bool> x);\n\n/**\n * Pop front of an `std::vector`.\n */\ntemplate <typename T>\nvoid pop_front(std::vector<T> &vec) {\n  assert(!vec.empty());\n  vec.front() = std::move(vec.back());\n  vec.pop_back();\n}\n\n/**\n * Pop front of an `std::vector`.\n */\ntemplate <typename T1, typename T2>\nvoid pop_front(std::vector<T1, T2> &vec) {\n  assert(!vec.empty());\n  vec.front() = std::move(vec.back());\n  vec.pop_back();\n}\n\n/**\n * Extend `std::vector`.\n */\ntemplate <typename T>\nvoid extend(std::vector<T> &x, std::vector<T> &add) {\n  x.reserve(x.size() + add.size());\n  x.insert(x.end(), add.begin(), add.end());\n}\n\n/**\n * Extend `std::vector`.\n */\ntemplate <typename T1, typename T2>\nvoid extend(std::vector<T1, T2> &x, std::vector<T1, T2> &add) {\n  x.reserve(x.size() + add.size());\n  x.insert(x.end(), add.begin(), add.end());\n}\n\n/**\n * Slice `std::vector`.\n */\ntemplate<typename T>\nstd::vector<T> slice(std::vector<T> const &v, int m, int n) {\n  auto first = v.cbegin() + m;\n  auto last = v.cbegin() + n + 1;\n\n  std::vector<T> vec(first, last);\n  return vec;\n}\n\n/**\n * Slice `std::vector`.\n */\ntemplate<typename T1, typename T2>\nstd::vector<T1, T2> slice(std::vector<T1, T2> const &v, int m, int n) {\n  auto first = v.cbegin() + m;\n  auto last = v.cbegin() + n + 1;\n\n  std::vector<T1, T2> vec(first, last);\n  return vec;\n}\n\n/**\n * Get raw pointer of a value in a `std::map`.\n */\ntemplate <typename K, typename V>\nconst V *lookup(const std::map<K, V> &map, K key) {\n  typename std::map<K, V>::const_iterator iter = map.find(key);\n  if (iter != map.end()) {\n    return &iter->second;\n  } else {\n    return nullptr;\n  }\n}\n\n/**\n * Get raw pointer of a value in a `std::map`.\n */\ntemplate <typename K, typename V>\nV *lookup(std::map<K, V> &map, K key) {\n  return const_cast<V *>(lookup(const_cast<const std::map<K, V> &>(map), key));\n}\n\n/**\n * Get raw pointer of a value in a `std::map`.\n */\ntemplate <typename K, typename V>\nconst V *lookup(const std::unordered_map<K, V> &map, K key) {\n  typename std::unordered_map<K, V>::const_iterator iter = map.find(key);\n  if (iter != map.end()) {\n    return &iter->second;\n  } else {\n    return nullptr;\n  }\n}\n\n/**\n * Get raw pointer of a value in a `std::map`.\n */\ntemplate <typename K, typename V>\nV *lookup(std::unordered_map<K, V> &map, K key) {\n  return const_cast<V *>(\n      lookup(const_cast<const std::unordered_map<K, V> &>(map), key));\n}\n\n/**\n * Union between set `a` and set `b`.\n */\ntemplate <typename T>\nT set_union(const T &s1, const T &s2) {\n  T result = s1;\n  result.insert(s2.begin(), s2.end());\n  return result;\n}\n\n/**\n * Difference between `a` and set `b`.\n */\ntemplate <typename T>\nT set_diff(const T &a, const T &b) {\n  T results;\n  std::set_difference(a.begin(),\n                      a.end(),\n                      b.begin(),\n                      b.end(),\n                      std::inserter(results, results.end()));\n  return results;\n}\n\n/**\n * Symmetric difference between `a` and `b`.\n */\ntemplate <typename T>\nT set_symmetric_diff(const T &a, const T &b) {\n  T results;\n  std::set_symmetric_difference(a.begin(),\n                                a.end(),\n                                b.begin(),\n                                b.end(),\n                                std::back_inserter(results));\n  return results;\n}\n\n/**\n * Intersection between std::vectors `vecs`.\n * @returns Number of common elements\n */\ntemplate <typename T>\nstd::set<T> intersection(const std::list<std::vector<T>> &vecs) {\n  // Obtain element count across all vectors\n  std::unordered_map<T, size_t> counter;\n  for (const auto &vec : vecs) { // Loop over all vectors\n    for (const auto &p : vec) {  // Loop over elements in vector\n      counter[p] += 1;\n    }\n  }\n\n  // Build intersection result\n  std::set<T> retval;\n  for (const auto &el : counter) {\n    if (el.second == vecs.size()) {\n      retval.insert(el.first);\n    }\n  }\n\n  return retval;\n}\n\n/**\n * Ordered Set\n */\ntemplate <class T>\nclass ordered_set_t {\npublic:\n  using iterator                     = typename std::vector<T>::iterator;\n  using const_iterator               = typename std::vector<T>::const_iterator;\n\n  iterator begin()                   { return vector.begin(); }\n  iterator end()                     { return vector.end(); }\n  const_iterator begin() const       { return vector.begin(); }\n  const_iterator end() const         { return vector.end(); }\n  const T& at(const size_t i) const  { return vector.at(i); }\n  const T& front() const             { return vector.front(); }\n  const T& back() const              { return vector.back(); }\n  void insert(const T& item)         { if (set.insert(item).second) vector.push_back(item); }\n  size_t count(const T& item) const  { return set.count(item); }\n  bool empty() const                 { return set.empty(); }\n  size_t size() const                { return set.size(); }\n  void clear()                       { vector.clear(); set.clear(); }\n\nprivate:\n  std::vector<T> vector;\n  std::set<T>    set;\n};\n\n/**\n * Save 3D features to csv file defined in `path`.\n */\nvoid save_features(const std::string &path, const vec3s_t &features);\n\n/**\n * Save pose to `csv_file` incrementally.\n */\nvoid save_pose(FILE *csv_file,\n               const timestamp_t &ts,\n               const quat_t &rot,\n               const vec3_t &pos);\n\n/**\n * Save pose to `csv_file` incrementally.\n */\nvoid save_pose(FILE *csv_file, const timestamp_t &ts, const vecx_t &pose);\n\n/**\n * Save poses to csv file in `path`.\n */\nvoid save_poses(const std::string &path,\n                const timestamps_t &timestamps,\n                const quats_t &orientations,\n                const vec3s_t &positions);\n\n/**\n * Save poses to csv file in `path`.\n */\nvoid save_poses(const std::string &path, const mat4s_t &poses);\n\n/** Load pose */\nmat4_t load_pose(const std::string &fpath);\n\n/** Load poses */\nvoid load_poses(const std::string &fpath,\n                timestamps_t &timestamps,\n                mat4s_t &poses);\n\n/**\n * Check jacobian\n */\nint check_jacobian(const std::string &jac_name,\n                   const matx_t &fdiff,\n                   const matx_t &jac,\n                   const real_t threshold,\n                   const bool print=false);\n\n/******************************************************************************\n *                                FILESYSTEM\n *****************************************************************************/\n\n/**\n * Open file in `path` with `mode` and set `nb_rows`.\n * @returns File pointer on success, nullptr on failure.\n */\nFILE *file_open(const std::string &path,\n                const std::string &mode,\n                int *nb_rows = nullptr);\n\n/**\n * Skip file line in file `fp`.\n */\nvoid skip_line(FILE *fp);\n\n/**\n * Get number of rows in file.\n * @returns Number of rows in file else -1 for failure.\n */\nint file_rows(const std::string &file_path);\n\n/**\n * Copy file from path `src` to path `dest.\n *\n * @returns 0 for success else -1 if `src` file could not be opend, or -2 if\n * `dest` file could not be opened.\n */\nint file_copy(const std::string &src, const std::string &dest);\n\n/**\n * Return file extension in `path`.\n */\nstd::string parse_fext(const std::string &path);\n\n/**\n * Return basename\n */\nstd::string parse_fname(const std::string &path);\n\n/**\n * Check if file exists\n *\n * @param path Path to file\n * @returns true or false\n */\nbool file_exists(const std::string &path);\n\n/**\n * Check if path exists\n *\n * @param path Path\n * @returns true or false\n */\nbool dir_exists(const std::string &path);\n\n/**\n * Create directory\n *\n * @param path Path\n * @returns 0 for success, -1 for failure\n */\nint dir_create(const std::string &path);\n\n/**\n * Return directory name\n *\n * @param path Path\n * @returns directory name\n */\nstd::string dir_name(const std::string &path);\n\n/**\n * Strips a target character from the start and end of a string\n *\n * @param s String to strip\n * @param target Target character to strip\n * @returns Stripped string\n */\nstd::string strip(const std::string &s, const std::string &target = \" \");\n\n/**\n * Strips a target character from the end of a string\n *\n * @param s String to strip\n * @param target Target character to strip\n * @returns Stripped string\n */\nstd::string strip_end(const std::string &s, const std::string &target = \" \");\n\n/**\n * Create directory\n *\n * @param path Path to directory\n * @returns 0 for success, -1 for failure\n */\nint create_dir(const std::string &path);\n\n/**\n * Remove directory\n *\n * @param path Path to directory\n * @returns 0 for success, -1 for failure\n */\nint remove_dir(const std::string &path);\n\n/**\n * Remove file extension\n *\n * @param path Path to directory\n * @returns File path without extension\n */\nstd::string remove_ext(const std::string &path);\n\n/**\n * List directory\n *\n * @param path Path to directory\n * @param results List of files and directories\n * @returns 0 for success, -1 for failure\n */\nint list_dir(const std::string &path, std::vector<std::string> &results);\n\n/**\n * Split path into a number of elements\n *\n * @param path Path\n * @returns List of path elements\n */\nstd::vector<std::string> path_split(const std::string path);\n\n/**\n * Combine `path1` and `path2`\n *\n * @param path1 Path 1\n * @param path2 Path 22\n * @returns Combined path\n */\nstd::string paths_join(const std::string path1, const std::string path2);\n\n\n/******************************************************************************\n *                              CONFIGURATION\n *****************************************************************************/\n\nstruct config_t {\n  std::string file_path;\n  YAML::Node root;\n  bool ok = false;\n\n  config_t();\n  config_t(const std::string &file_path_);\n  ~config_t();\n};\n\n/**\n * Load YAML file.\n * @returns 0 for success or -1 for failure.\n */\nint yaml_load_file(const std::string file_path, YAML::Node &root);\n\n/**\n * Get YAML node containing the parameter value.\n * @returns 0 for success or -1 for failure.\n */\nint yaml_get_node(const config_t &config,\n                  const std::string &key,\n                  const bool optional,\n                  YAML::Node &node);\n\n/**\n * Check if yaml file has `key`.\n * @returns 0 for success or -1 for failure.\n */\nint yaml_has_key(const config_t &config, const std::string &key);\n\n/**\n * Check if yaml file has `key`.\n * @returns 0 for success or -1 for failure.\n */\nint yaml_has_key(const std::string &file_path, const std::string &key);\n\n/**\n * Check size of vector in config file and returns the size.\n */\ntemplate <typename T>\nsize_t yaml_check_vector(const YAML::Node &node,\n                         const std::string &key,\n                         const bool optional);\n\n/**\n * Check matrix fields.\n */\nvoid yaml_check_matrix_fields(const YAML::Node &node,\n                              const std::string &key,\n                              size_t &rows,\n                              size_t &cols);\n\n/**\n * Check matrix to make sure that the parameter has the data field \"rows\",\n * \"cols\" and \"data\". It also checks to make sure the number of values is the\n * same size as the matrix.\n */\ntemplate <typename T>\nvoid yaml_check_matrix(const YAML::Node &node,\n                       const std::string &key,\n                       const bool optional,\n                       size_t &rows,\n                       size_t &cols);\n\ntemplate <typename T>\nvoid yaml_check_matrix(const YAML::Node &node,\n                       const std::string &key,\n                       const bool optional);\n\ntemplate <typename T>\nint parse(const config_t &config,\n          const std::string &key,\n          T &out,\n          const bool optional = false);\n\ntemplate <typename T>\nint parse(const config_t &config,\n          const std::string &key,\n          std::vector<T> &out,\n          const bool optional);\n\nint parse(const config_t &config,\n          const std::string &key,\n          vec2_t &vec,\n          const bool optional = false);\n\nint parse(const config_t &config,\n          const std::string &key,\n          vec3_t &vec,\n          const bool optional = false);\n\nint parse(const config_t &config,\n          const std::string &key,\n          vec4_t &vec,\n          const bool optional = false);\n\nint parse(const config_t &config,\n          const std::string &key,\n          vecx_t &vec,\n          const bool optional = false);\n\nint parse(const config_t &config,\n          const std::string &key,\n          mat2_t &mat,\n          const bool optional = false);\n\nint parse(const config_t &config,\n          const std::string &key,\n          mat3_t &mat,\n          const bool optional = false);\n\nint parse(const config_t &config,\n          const std::string &key,\n          mat4_t &mat,\n          const bool optional = false);\n\nint parse(const config_t &config,\n          const std::string &key,\n          matx_t &mat,\n          const bool optional = false);\n\nint parse(const config_t &config,\n          const std::string &key,\n          cv::Mat &mat,\n          const bool optional = false);\n\ntemplate <typename T>\nint parse(const config_t &config,\n          const std::string &key,\n          const int rows,\n          const int cols,\n          T &mat,\n          const bool optional = false);\n\n////////// CONFIG IMPLEMENTATION\n\ntemplate <typename T>\nsize_t yaml_check_vector(const YAML::Node &node,\n                         const std::string &key,\n                         const bool optional) {\n  UNUSED(optional);\n  assert(node);\n\n  // Get expected vector size\n  size_t vector_size = 0;\n  if (std::is_same<T, vec2_t>::value) {\n    vector_size = 2;\n  } else if (std::is_same<T, vec3_t>::value) {\n    vector_size = 3;\n  } else if (std::is_same<T, vec4_t>::value) {\n    vector_size = 4;\n  } else if (std::is_same<T, vec5_t>::value) {\n    vector_size = 5;\n  } else if (std::is_same<T, vecx_t>::value) {\n    vector_size = node.size();\n    return vector_size; // Don't bother, it could be anything\n  } else {\n    FATAL(\"Unsportted vector type!\");\n  }\n\n  // Check number of values in the param\n  if (node.size() == 0 && node.size() != vector_size) {\n    FATAL(\"Vector [%s] should have %d values but config has %d!\",\n          key.c_str(),\n          static_cast<int>(vector_size),\n          static_cast<int>(node.size()));\n  }\n\n  return vector_size;\n}\n\ntemplate <typename T>\nvoid yaml_check_matrix(const YAML::Node &node,\n                       const std::string &key,\n                       const bool optional,\n                       size_t &rows,\n                       size_t &cols) {\n  UNUSED(optional);\n  assert(node);\n  yaml_check_matrix_fields(node, key, rows, cols);\n\n  // Check number of elements\n  size_t nb_elements = 0;\n  if (std::is_same<T, mat2_t>::value) {\n    nb_elements = 4;\n  } else if (std::is_same<T, mat3_t>::value) {\n    nb_elements = 9;\n  } else if (std::is_same<T, mat4_t>::value) {\n    nb_elements = 16;\n  } else if (std::is_same<T, matx_t>::value) {\n    nb_elements = node[\"data\"].size();\n\n  } else if (std::is_same<T, cv::Mat>::value) {\n    nb_elements = node[\"data\"].size();\n  } else {\n    FATAL(\"Unsportted matrix type!\");\n  }\n  if (node[\"data\"].size() != nb_elements) {\n    FATAL(\"Matrix [%s] rows and cols do not match number of values!\",\n          key.c_str());\n  }\n}\n\ntemplate <typename T>\nvoid yaml_check_matrix(const YAML::Node &node,\n                       const std::string &key,\n                       const bool optional) {\n  size_t rows;\n  size_t cols;\n  yaml_check_matrix<T>(node, key, optional, rows, cols);\n}\n\ntemplate <typename T>\nint parse(const config_t &config,\n          const std::string &key,\n          T &out,\n          const bool optional) {\n  // Get node\n  YAML::Node node;\n  if (yaml_get_node(config, key, optional, node) != 0) {\n    return -1;\n  }\n\n  // Parse\n  out = node.as<T>();\n  return 0;\n}\n\ntemplate <typename T>\nint parse(const config_t &config,\n          const std::string &key,\n          std::vector<T> &out,\n          const bool optional) {\n  // Get node\n  YAML::Node node;\n  if (yaml_get_node(config, key, optional, node) != 0) {\n    return -1;\n  }\n\n  // Parse\n  std::vector<T> array;\n  for (auto n : node) {\n    out.push_back(n.as<T>());\n  }\n\n  return 0;\n}\n\n/******************************************************************************\n *                                  ALGEBRA\n *****************************************************************************/\n\n/**\n * Sign of number\n *\n * @param[in] x Number to check sign\n * @return\n *    - 0: Number is zero\n *    - 1: Positive number\n *    - -1: Negative number\n */\nint sign(const real_t x);\n\n/**\n * Floating point comparator\n *\n * @param[in] f1 First value\n * @param[in] f2 Second value\n * @return\n *    - 0: if equal\n *    - 1: if f1 > f2\n *    - -1: if f1 < f2\n */\nint fltcmp(const real_t f1, const real_t f2);\n\n/**\n * Calculate binomial coefficient\n *\n * @param[in] n\n * @param[in] k\n * @returns Binomial coefficient\n */\nreal_t binomial(const real_t n, const real_t k);\n\n/**\n * Return evenly spaced numbers over a specified interval.\n */\ntemplate <typename T>\nstd::vector<T> linspace(const T start, const T end, const int num) {\n  std::vector<T> linspaced;\n\n  if (num == 0) {\n    return linspaced;\n  }\n  if (num == 1) {\n    linspaced.push_back(start);\n    return linspaced;\n  }\n\n  const real_t diff = static_cast<real_t>(end - start);\n  const real_t delta = diff / static_cast<real_t>(num - 1);\n  for (int i = 0; i < num - 1; ++i) {\n    linspaced.push_back(start + delta * i);\n  }\n  linspaced.push_back(end);\n  return linspaced;\n}\n\n/******************************************************************************\n *                              LINEAR ALGEBRA\n *****************************************************************************/\n\n/**\n * Print shape of a matrix\n *\n * @param[in] name Name of matrix\n * @param[in] A Matrix\n */\nvoid print_shape(const std::string &name, const matx_t &A);\n\n/**\n * Print shape of a vector\n *\n * @param[in] name Name of vector\n * @param[in] v Vector\n */\nvoid print_shape(const std::string &name, const vecx_t &v);\n\n/**\n * Print array\n *\n * @param[in] name Name of array\n * @param[in] array Target array\n * @param[in] size Size of target array\n */\nvoid print_array(const std::string &name,\n                 const real_t *array,\n                 const size_t size);\n\n/**\n * Print vector `v` with a `name`.\n */\nvoid print_vector(const std::string &name, const vecx_t &v);\n\n/**\n * Print matrix `m` with a `name`.\n */\nvoid print_matrix(const std::string &name, const matx_t &m);\n\n/**\n * Print quaternion `q` with a `name`.\n */\nvoid print_quaternion(const std::string &name, const quat_t &q);\n\n/**\n * Array to string\n *\n * @param[in] array Target array\n * @param[in] size Size of target array\n * @returns String of array\n */\nstd::string array2str(const real_t *array, const size_t size);\n\n/**\n * Convert real_t array to Eigen::Vector\n *\n * @param[in] x Input array\n * @param[in] size Size of input array\n * @param[out] y Output vector\n */\nvoid array2vec(const real_t *x, const size_t size, vecx_t &y);\n\n/**\n * Vector to array\n *\n * @param[in] v Vector\n * @returns Array\n */\nreal_t *vec2array(const vecx_t &v);\n\n/**\n * Matrix to array\n *\n * @param[in] m Matrix\n * @returns Array\n */\nreal_t *mat2array(const matx_t &m);\n\n/**\n * Quaternion to array\n *\n * *VERY IMPORTANT*: The returned array is (x, y, z, w).\n *\n * @param[in] q Quaternion\n * @returns Array\n */\nreal_t *quat2array(const quat_t &q);\n\n/**\n * Vector to array\n *\n * @param[in] v Vector\n * @param[out] out Output array\n */\nvoid vec2array(const vecx_t &v, real_t *out);\n\n/**\n * Matrix to array\n *\n * @param[in] m Matrix\n * @param[in] out Output array\n */\nvoid mat2array(const matx_t &m, real_t *out);\n\n/**\n * Matrix to list of vectors\n *\n * @param[in] m Matrix\n * @param[in] row_wise Row wise\n * @returns Vectors\n */\nstd::vector<vecx_t> mat2vec(const matx_t &m, const bool row_wise = true);\n\n/**\n * Matrix to list of vectors of size 3\n *\n * @param[in] m Matrix\n * @param[in] row_wise Row wise\n * @returns Vectors\n */\nvec3s_t mat2vec3(const matx_t &m, const bool row_wise = true);\n\n/**\n * Matrix to list of vectors of size 3\n *\n * @param[in] m Matrix\n * @param[in] row_wise Row wise\n * @returns Vectors\n */\nvec2s_t mat2vec2(const matx_t &m, const bool row_wise = true);\n\n/**\n * Vectors to matrix\n */\nmatx_t vecs2mat(const vec3s_t &vs);\n\n/**\n * Vector to string\n *\n * @param[in] v Vector\n * @param[in] brackets Brakcets around vector string\n * @returns Vector as a string\n */\nstd::string vec2str(const vecx_t &v, const bool brackets = true);\n\n/**\n * Array to string\n *\n * @param[in] arr Array\n * @param[in] len Length of array\n * @param[in] brackets Brakcets around vector string\n * @returns Array as a string\n */\nstd::string arr2str(const real_t *arr, const size_t len, bool brackets = true);\n\n/**\n * Matrix to string\n *\n * @param[in] m Matrix\n * @param[in] indent Indent string\n * @returns Array as a string\n */\nstd::string mat2str(const matx_t &m, const std::string &indent = \"  \");\n\n/**\n * Normalize vector x\n */\nvec2_t normalize(const vec2_t &x);\n\n/**\n * Normalize vector `v`.\n */\nvec3_t normalize(const vec3_t &v);\n\n/**\n * Condition number of `A`.\n */\nreal_t cond(const matx_t &A);\n\n/**\n * Zeros-matrix\n *\n * @param rows Number of rows\n * @param cols Number of cols\n * @returns Zeros matrix\n */\nmatx_t zeros(const int rows, const int cols);\n\n/**\n * Zeros square matrix\n *\n * @param size Square size of matrix\n * @returns Zeros matrix\n */\nmatx_t zeros(const int size);\n\n/**\n * Identity-matrix\n *\n * @param rows Number of rows\n * @param cols Number of cols\n * @returns Identity matrix\n */\nmatx_t I(const int rows, const int cols);\n\n/**\n * Identity square matrix\n *\n * @param size Square size of matrix\n * @returns Identity square matrix\n */\nmatx_t I(const int size);\n\n/**\n * Ones-matrix\n *\n * @param rows Number of rows\n * @param cols Number of cols\n * @returns Ones square matrix\n */\nmatx_t ones(const int rows, const int cols);\n\n/**\n * Ones square matrix\n *\n * @param size Square size of matrix\n * @returns Ones square matrix\n */\nmatx_t ones(const int size);\n\n/**\n * Horizontally stack matrices A and B\n *\n * @param A Matrix A\n * @param B Matrix B\n * @returns Stacked matrix\n */\nmatx_t hstack(const matx_t &A, const matx_t &B);\n\n/**\n * Vertically stack matrices A and B\n *\n * @param A Matrix A\n * @param B Matrix B\n * @returns Stacked matrix\n */\nmatx_t vstack(const matx_t &A, const matx_t &B);\n\n/**\n * Diagonally stack matrices A and B\n *\n * @param A Matrix A\n * @param B Matrix B\n * @returns Stacked matrix\n */\nmatx_t dstack(const matx_t &A, const matx_t &B);\n\n/**\n * Skew symmetric-matrix\n *\n * @param w Input vector\n * @returns Skew symmetric matrix\n */\nmat3_t skew(const vec3_t &w);\n\n/**\n * Skew symmetric-matrix squared\n *\n * @param w Input vector\n * @returns Skew symmetric matrix squared\n */\nmat3_t skewsq(const vec3_t &w);\n\n/**\n * Enforce Positive Semi-Definite\n *\n * @param A Input matrix\n * @returns Positive semi-definite matrix\n */\nmatx_t enforce_psd(const matx_t &A);\n\n/**\n * Null-space of A\n *\n * @param A Input matrix\n * @returns Null space of A\n */\nmatx_t nullspace(const matx_t &A);\n\n/**\n * Check if two matrices `A` and `B` are equal.\n */\nbool equals(const matx_t &A, const matx_t &B);\n\n/**\n * Load std::vector of real_ts to an Eigen::Matrix\n *\n * @param[in] x Matrix values\n * @param[in] rows Number of matrix rows\n * @param[in] cols Number of matrix colums\n * @param[out] y Output matrix\n */\nvoid load_matrix(const std::vector<real_t> &x,\n                 const int rows,\n                 const int cols,\n                 matx_t &y);\n\n/**\n * Load an Eigen::Matrix into a std::vector of real_ts\n *\n * @param[in] A Matrix\n * @param[out] x Output vector of matrix values\n */\nvoid load_matrix(const matx_t A, std::vector<real_t> &x);\n\n/** Pseudo Inverse via SVD **/\nmatx_t pinv(const matx_t &A, const real_t tol=1e-4);\n\n/** Rank of matrix A **/\nlong int rank(const matx_t &A);\n\n/**\n * Perform Schur's Complement\n */\nint schurs_complement(matx_t &H, vecx_t &b,\n                      const size_t m, const size_t r,\n                      const bool precond=false, const bool debug=false);\n\n\n// /**\n//  * Recover covariance(i, l) (a specific value in the covariance matrix) from\n//  * the upper triangular matrix `U` with precomputed diagonal vector containing\n//  * `diag(U)^{-1}`. Computed covariances will be stored in the `hash` to avoid\n//  * recomputing the value again.\n//  */\n// real_t covar_recover(const long i, const long l,\n//                      const matx_t &U, const vecx_t &diag,\n//                      mat_hash_t &hash);\n//\n// /**\n//  * From the Hessian matrix `H`, recover the covariance values defined in\n//  * `indicies`. Returns a matrix hashmap of covariance values.\n//  */\n// mat_hash_t covar_recover(const matx_t &H, const mat_indicies_t &indicies);\n\n/******************************************************************************\n *                                 Geometry\n *****************************************************************************/\n\n/**\n * Sinc function.\n */\nreal_t sinc(const real_t x);\n\n/**\n * Degrees to radians\n *\n * @param[in] d Degree to be converted\n * @return Degree in radians\n */\nreal_t deg2rad(const real_t d);\n\n/**\n * Degrees to radians\n *\n * @param[in] d Degree to be converted\n * @return Degree in radians\n */\nvec3_t deg2rad(const vec3_t d);\n\n/**\n * Radians to degree\n *\n * @param[in] r Radian to be converted\n * @return Radian in degrees\n */\nreal_t rad2deg(const real_t r);\n\n/**\n * Radians to degree\n *\n * @param[in] r Radian to be converted\n * @return Radian in degrees\n */\nvec3_t rad2deg(const vec3_t &r);\n\n/**\n * Wrap angle in degrees to 180\n *\n * @param[in] d Degrees\n * @return Angle wraped to 180\n */\nreal_t wrap180(const real_t d);\n\n/**\n * Wrap angle in degrees to 360\n *\n * @param[in] d Degrees\n * @return Angle wraped to 360\n */\nreal_t wrap360(const real_t d);\n\n/**\n * Wrap angle in radians to PI\n *\n * @param[in] r Radians\n * @return Angle wraped to PI\n */\nreal_t wrapPi(const real_t r);\n\n/**\n * Wrap angle in radians to 2 PI\n *\n * @param[in] r Radians\n * @return Angle wraped to 2 PI\n */\nreal_t wrap2Pi(const real_t r);\n\n/**\n * Create a circle point of radius `r` at angle `theta` radians.\n */\nvec2_t circle(const real_t r, const real_t theta);\n\n/**\n * Create the sphere point with sphere radius `rho` at longitude `theta`\n * [radians] and latitude `phi` [radians].\n */\nvec3_t sphere(const real_t rho, const real_t theta, const real_t phi);\n\n/**\n * Create look at matrix.\n */\nmat4_t lookat(const vec3_t &cam_pos,\n              const vec3_t &target,\n              const vec3_t &up_axis = vec3_t{0.0, -1.0, 0.0});\n\n/**\n * Cross-Track error based on waypoint line between p1, p2, and robot position\n *\n * @param[in] p1 Waypoint 1\n * @param[in] p2 Waypoint 2\n * @param[in] pos Robot position\n * @return Cross track error\n */\nreal_t cross_track_error(const vec2_t &p1, const vec2_t &p2, const vec2_t &pos);\n\n/**\n * Check if point `pos` is left or right of line formed by `p1` and `p2`\n *\n * @param[in] p1 Waypoint 1\n * @param[in] p2 Waypoint 2\n * @param[in] pos Robot position\n * @returns\n *    - 1: Point is left of waypoint line formed by `p1` and `p2`\n *    - 2: Point is right of waypoint line formed by `p1` and `p2`\n *    - 0: Point is colinear with waypoint line formed by `p1` and `p2`\n */\nint point_left_right(const vec2_t &p1, const vec2_t &p2, const vec2_t &pos);\n\n/**\n * Calculate closest point given waypoint line between `p1`, `p2` and robot\n * position\n *\n * @param[in] p1 Waypoint 1\n * @param[in] p2 Waypoint 2\n * @param[in] p3 Robot position\n * @param[out] closest Closest point\n * @returns\n *    Unit number denoting where the closest point is on waypoint line. For\n *    example, a return value of 0.5 denotes the closest point is half-way\n *    (50%) of the waypoint line, alternatively a negative number denotes the\n *    closest point is behind the first waypoint.\n */\nreal_t closest_point(const vec2_t &p1,\n                     const vec2_t &p2,\n                     const vec2_t &p3,\n                     vec2_t &closest);\n\n#define EARTH_RADIUS_M 6378137.0\n\n/**\n * Calculate new latitude and logitude coordinates with an offset in North and\n * East direction.\n *\n * IMPORTANT NOTE: This function is only an approximation. As such do not rely\n * on this function for precise latitude, longitude offsets.\n *\n * @param lat_ref Latitude of origin (decimal format)\n * @param lon_ref Longitude of origin (decimal format)\n * @param offset_N Offset in North direction (meters)\n * @param offset_E Offset in East direction (meters)\n * @param lat_new New latitude (decimal format)\n * @param lon_new New longitude (decimal format)\n */\nvoid latlon_offset(real_t lat_ref,\n                   real_t lon_ref,\n                   real_t offset_N,\n                   real_t offset_E,\n                   real_t *lat_new,\n                   real_t *lon_new);\n\n/**\n * Calculate difference in distance in North and East from two GPS coordinates\n *\n * IMPORTANT NOTE: This function is only an approximation. As such do not rely\n * on this function for precise latitude, longitude diffs.\n *\n * @param lat_ref Latitude of origin (decimal format)\n * @param lon_ref Longitude of origin (decimal format)\n * @param lat Latitude of point of interest (decimal format)\n * @param lon Longitude of point of interest (decimal format)\n * @param dist_N Distance of point of interest in North axis [m]\n * @param dist_E Distance of point of interest in East axis [m]\n */\nvoid latlon_diff(real_t lat_ref,\n                 real_t lon_ref,\n                 real_t lat,\n                 real_t lon,\n                 real_t *dist_N,\n                 real_t *dist_E);\n\n/**\n * Calculate Euclidean distance between two GPS coordintes\n *\n * IMPORTANT NOTE: This function is only an approximation. As such do not rely\n * on this function for precise latitude, longitude distance.\n *\n * @param lat_ref Latitude of origin (decimal format)\n * @param lon_ref Longitude of origin (decimal format)\n * @param lat Latitude of point of interest (decimal format)\n * @param lon Longitude of point of interest (decimal format)\n *\n * @returns Euclidean distance between two GPS coordinates [m]\n */\nreal_t latlon_dist(real_t lat_ref, real_t lon_ref, real_t lat, real_t lon);\n\n/*****************************************************************************\n *                         DIFFERENTIAL GEOMETRY\n *****************************************************************************/\n\nnamespace lie {\n\nmat3_t Exp(const vec3_t &phi);\nvec3_t Log(const mat3_t &C);\nmat3_t Jr(const vec3_t &psi);\n\n} // namespace lie\n\n/******************************************************************************\n *                                STATISTICS\n *****************************************************************************/\n\n/**\n * Create random integer\n *\n * @param[in] ub Upper bound\n * @param[in] lb Lower bound\n * @return Random integer\n */\nint randi(const int ub, const int lb);\n\n/**\n * Create random real_t\n *\n * @param[in] ub Upper bound\n * @param[in] lb Lower bound\n * @return Random floating point\n */\nreal_t randf(const real_t ub, const real_t lb);\n\n/**\n * Sum values in vector.\n *\n * @param[in] x Array of numbers\n * @return Sum of vector\n */\nreal_t sum(const std::vector<real_t> &x);\n\n/** Calculate median given an array of numbers */\nreal_t median(const std::vector<real_t> &v);\n\n/** Mean */\nvec3_t mean(const vec3s_t &x);\n\n/** Mean */\nreal_t mean(const std::vector<real_t> &x);\n\n/** Variance */\nreal_t var(const std::vector<real_t> &x);\n\n/** Standard Deviation */\nreal_t stddev(const std::vector<real_t> &x);\n\n/** Root Mean Squared Error.  */\nreal_t rmse(const std::vector<real_t> &x);\n\n/**\n * Shannon Entropy of a given covariance matrix `covar`.\n */\nreal_t shannon_entropy(const matx_t &covar);\n\n/**\n * Multivariate normal.\n */\nvec3_t mvn(std::default_random_engine &engine,\n           const vec3_t &mu = vec3_t{0.0, 0.0, 0.0},\n           const vec3_t &stdev = vec3_t{1.0, 1.0, 1.0});\n\n/**\n * Gassian normal.\n * http://c-faq.com/lib/gaussian.html\n */\nreal_t gauss_normal();\n\n/*****************************************************************************\n *                               TRANSFORM\n *****************************************************************************/\n\n/**\n * Form a 4x4 homogeneous transformation matrix from a\n * rotation matrix `C` and translation vector `r`.\n */\ntemplate <typename T>\nEigen::Matrix<T, 4, 4> tf(const Eigen::Matrix<T, 3, 3> &C,\n                          const Eigen::Matrix<T, 3, 1> &r) {\n  Eigen::Matrix<T, 4, 4> transform = Eigen::Matrix<T, 4, 4>::Identity();\n  transform.block(0, 0, 3, 3) = C;\n  transform.block(0, 3, 3, 1) = r;\n  return transform;\n}\n\n/**\n * Form a 4x4 homogeneous transformation matrix from a pointer to real_t array\n * containing (quaternion + translation) 7 elements: (qw, qx, qy, qz, x, y, z)\n */\nmat4_t tf(const double *params);\n\n/**\n * Form a 4x4 homogeneous transformation matrix from a pointer to real_t array\n * containing (quaternion + translation) 7 elements: (qw, qx, qy, qz, x, y, z)\n */\nmat4_t tf(const vecx_t &params);\n\n/**\n * Form a 4x4 homogeneous transformation matrix from a\n * rotation matrix `C` and translation vector `r`.\n */\nmat4_t tf(const mat3_t &C, const vec3_t &r);\n\n/**\n * Form a 4x4 homogeneous transformation matrix from a\n * Hamiltonian quaternion `q` and translation vector `r`.\n */\nmat4_t tf(const quat_t &q, const vec3_t &r);\n\n/**\n * Extract rotation from transform\n */\ninline mat3_t tf_rot(const mat4_t &tf) { return tf.block<3, 3>(0, 0); }\n\n/**\n * Extract rotation and convert to quaternion from transform\n */\ninline quat_t tf_quat(const mat4_t &tf) { return quat_t{tf.block<3, 3>(0, 0)}; }\n\n/**\n * Extract translation from transform\n */\ninline vec3_t tf_trans(const mat4_t &tf) { return tf.block<3, 1>(0, 3); }\n\n\n/**\n * Perturb the rotation element in the tranform `T` by `step_size` at index\n * `i`. Where i = 0 for x-axis, i = 1 for y-axis, and i = 2 for z-axis.\n */\nmat4_t tf_perturb_rot(const mat4_t &T, real_t step_size, const int i);\n\n/**\n * Perturb the translation element in the tranform `T` by `step_size` at index\n * `i`. Where i = 0 for x-axis, i = 1 for y-axis, and i = 2 for z-axis.\n */\nmat4_t tf_perturb_trans(const mat4_t &T, real_t step_size, const int i);\n\n/**\n * Transform point `p` with transform `T`.\n */\nvec3_t tf_point(const mat4_t &T, const vec3_t &p);\n\n/**\n * Rotation matrix around x-axis (counter-clockwise, right-handed).\n * @returns Rotation matrix\n */\nmat3_t rotx(const real_t theta);\n\n/**\n * Rotation matrix around y-axis (counter-clockwise, right-handed).\n * @returns Rotation matrix\n */\nmat3_t roty(const real_t theta);\n\n/**\n * Rotation matrix around z-axis (counter-clockwise, right-handed).\n * @returns Rotation matrix\n */\nmat3_t rotz(const real_t theta);\n\n/**\n * Convert euler sequence 123 to rotation matrix R\n * This function assumes we are performing a body fixed intrinsic rotation.\n *\n * Source:\n *\n *     Kuipers, Jack B. Quaternions and Rotation Sequences: A Primer with\n *     Applications to Orbits, Aerospace, and Virtual Reality. Princeton, N.J:\n *     Princeton University Press, 1999. Print.\n *\n *     Page 86.\n *\n * @returns Rotation matrix\n */\nmat3_t euler123(const vec3_t &euler);\n\n/**\n * Convert euler sequence 321 to rotation matrix R\n * This function assumes we are performing a body fixed intrinsic rotation.\n *\n * Source:\n *\n *     Kuipers, Jack B. Quaternions and Rotation Sequences: A Primer with\n *     Applications to Orbits, Aerospace, and Virtual Reality. Princeton, N.J:\n *     Princeton University Press, 1999. Print.\n *\n *     Page 86.\n *\n * @returns Rotation matrix\n */\nmat3_t euler321(const vec3_t &euler);\n\n/**\n * Convert roll, pitch and yaw to quaternion.\n */\nquat_t euler2quat(const vec3_t &euler);\n\n/**\n * Convert rotation vectors to rotation matrix using measured acceleration\n * `a_m` from an IMU and gravity vector `g`.\n */\nmat3_t vecs2rot(const vec3_t &a_m, const vec3_t &g);\n\n/**\n * Convert rotation vector `rvec` to rotation matrix.\n */\nmat3_t rvec2rot(const vec3_t &rvec, const real_t eps = 1e-5);\n\n/**\n * Convert quaternion to euler angles.\n */\nvec3_t quat2euler(const quat_t &q);\n\n/**\n * Convert quaternion to rotation matrix.\n */\nmat3_t quat2rot(const quat_t &q);\n\n/**\n * Convert small angle euler angle to quaternion.\n */\nquat_t quat_delta(const vec3_t &dalpha);\n\n/**\n * Return left quaternion product matrix.\n */\nmat4_t quat_lmul(const quat_t &q);\n\n/**\n * Return left quaternion product matrix (but only for x, y, z components).\n */\nmat3_t quat_lmul_xyz(const quat_t &q);\n\n/**\n * Return right quaternion product matrix.\n */\nmat4_t quat_rmul(const quat_t &q);\n\n/**\n * Return right quaternion product matrix (but only for x, y, z components).\n */\nmat3_t quat_rmul_xyz(const quat_t &q);\n\n/**\n * Return only the x, y, z, components of a quaternion matrix.\n */\nmat3_t quat_mat_xyz(const mat4_t &Q);\n\n/**\n * Add noise to rotation matrix `rot`, where noise `n` is in degrees.\n */\nmat3_t add_noise(const mat3_t &rot, const real_t n);\n\n/**\n * Add noise to position vector `pos`, where noise `n` is in meters.\n */\nvec3_t add_noise(const vec3_t &pos, const real_t n);\n\n/**\n * Add noise to transform `pose`, where `pos_n` is in meters and `rot_n` is in\n * degrees.\n */\nmat4_t add_noise(const mat4_t &pose, const real_t pos_n, const real_t rot_n);\n\n/**\n * Initialize attitude using IMU gyroscope `w_m` and accelerometer `a_m`\n * measurements. The calculated attitude outputted into to `C_WS`. Note: this\n * function does not calculate initial yaw angle in the world frame. Only the\n * roll, and pitch are inferred from IMU measurements.\n */\nvoid imu_init_attitude(const vec3s_t w_m,\n                       const vec3s_t a_m,\n                       mat3_t &C_WS,\n                       const size_t buffer_size = 50);\n\n/*****************************************************************************\n *                                    TIME\n *****************************************************************************/\n\n/**\n * Print timestamp.\n */\nvoid timestamp_print(const timestamp_t &ts, const std::string &prefix = \"\");\n\n/**\n * Convert ts to second.\n */\nreal_t ts2sec(const timestamp_t &ts);\n\n/**\n * Convert nano-second to second.\n */\nreal_t ns2sec(const uint64_t ns);\n\n/**\n * Start timer.\n */\nstruct timespec tic();\n\n/**\n * Stop timer and return number of seconds.\n */\nfloat toc(struct timespec *tic);\n\n/**\n * Stop timer and return miliseconds elasped.\n */\nfloat mtoc(struct timespec *tic);\n\n/**\n * Get time now in milliseconds since epoch\n */\nreal_t time_now();\n\n/**\n * Profiler\n */\nstruct profiler_t {\n  std::map<std::string, timespec> timers;\n  std::map<std::string, float> record;\n\n  profiler_t() {}\n\n  void start(const std::string &key) {\n    timers[key] = tic();\n  }\n\n  float stop(const std::string &key) {\n    record[key] = toc(&timers[key]);\n    return record[key];\n  }\n\n  void print(const std::string &key) {\n    printf(\"[%s]: %.4fs\\n\", key.c_str(), stop(key));\n  }\n};\n\n/*****************************************************************************\n *                               NETWORKING\n ****************************************************************************/\n\n/**\n * Return IP and Port info from socket file descriptor `sockfd` to `ip` and\n * `port`. Returns `0` for success and `-1` for failure.\n */\nint ip_port_info(const int sockfd, char *ip, int *port);\n\n/**\n * Return IP and Port info from socket file descriptor `sockfd` to `ip` and\n * `port`. Returns `0` for success and `-1` for failure.\n */\nint ip_port_info(const int sockfd, std::string &ip, int &port);\n\n/**\n * TCP server\n */\nstruct tcp_server_t {\n  int port = 8080;\n  int sockfd = -1;\n  std::vector<int> conns;\n  void *(*conn_thread)(void *) = nullptr;\n\n  tcp_server_t(int port_ = 8080);\n};\n\n/**\n * TCP client\n */\nstruct tcp_client_t {\n  std::string server_ip;\n  int server_port = 8080;\n  int sockfd = -1;\n  int (*loop_cb)(tcp_client_t &) = nullptr;\n\n  tcp_client_t(const std::string &server_ip_ = \"127.0.0.1\",\n               int server_port_ = 8080);\n};\n\n/**\n * Configure TCP server\n */\nint tcp_server_config(tcp_server_t &server);\n\n/**\n * Loop TCP server\n */\nint tcp_server_loop(tcp_server_t &server);\n\n/**\n * Configure TCP client\n */\nint tcp_client_config(tcp_client_t &client);\n\n/**\n * Loop TCP client\n */\nint tcp_client_loop(tcp_client_t &client);\n\n/******************************************************************************\n *                              INTERPOLATION\n *****************************************************************************/\n\n/**\n * Linear interpolation between two points.\n *\n * @param[in] a First point\n * @param[in] b Second point\n * @param[in] t Unit number\n * @returns Linear interpolation\n */\ntemplate <typename T>\nT lerp(const T &a, const T &b, const real_t t) {\n  return a * (1.0 - t) + b * t;\n}\n\n/**\n * Slerp\n */\nquat_t slerp(const quat_t &q_start, const quat_t &q_end, const real_t alpha);\n\n/**\n * Interpolate between two poses `p0` and `p1` with parameter `alpha`.\n */\nmat4_t interp_pose(const mat4_t &p0, const mat4_t &p1, const real_t alpha);\n\n/**\n * Interpolate `poses` where each pose has a timestamp in `timestamps` and the\n * interpolation points in time are in `interp_ts`. The results are recorded\n * in `interp_poses`.\n * @returns 0 for success, -1 for failure\n */\nvoid interp_poses(const timestamps_t &timestamps,\n                  const mat4s_t &poses,\n                  const timestamps_t &interp_ts,\n                  mat4s_t &interped_poses,\n                  const real_t threshold = 0.001);\n\n/**\n * Get the closest pose in `poses` where each pose has a timestamp in\n * `timestamps` and the target points in time are in `target_ts`. The results\n * are recorded in `result`.\n * @returns 0 for success, -1 for failure\n */\nvoid closest_poses(const timestamps_t &timestamps,\n                   const mat4s_t &poses,\n                   const timestamps_t &interp_ts,\n                   mat4s_t &result);\n\n\n/**\n * Let `t0` and `t1` be timestamps from two signals. If one of them is measured\n * at a higher rate, the goal is to interpolate the lower rate signal so that\n * it aligns with the higher rate one.\n *\n * This function will determine which timestamp deque will become the reference\n * signal and the other will become the target signal. Based on this the\n * interpolation points will be based on the reference signal.\n *\n * Additionally, this function ensures the interpolation timestamps are\n * achievable by:\n *\n * - interp start > target start\n * - interp end < target end\n *\n * **Note**: This function will not include timestamps from the target\n * (lower-rate) signal. The returned interpolation timestamps only returns\n * **interpolation points** to match the reference signal (higher-rate).\n *\n * @returns Interpolation timestamps from two timestamp deques `t0` and `t1`.\n */\nstd::deque<timestamp_t> lerp_timestamps(const std::deque<timestamp_t> &t0,\n                                        const std::deque<timestamp_t> &t1);\n\n/**\n * Given the interpolation timestamps `lerp_ts`, target timestamps\n * `target_ts` and target data `target_data`. This function will:\n *\n * 1: Interpolate the `target_data` at the interpolation points defined by\n *    `target_ts`.\n * 2: Disgard data that are not in the target timestamp\n */\nvoid lerp_data(const std::deque<timestamp_t> &lerp_ts,\n               std::deque<timestamp_t> &target_ts,\n               std::deque<vec3_t> &target_data,\n               const bool keep_old = false);\n\n/** Lerp pose */\nmat4_t lerp_pose(const timestamp_t &t0,\n                 const mat4_t &pose0,\n                 const timestamp_t &t1,\n                 const mat4_t &pose1,\n                 const timestamp_t &t_lerp);\n\n/**\n * Given two data signals with timestamps `ts0`, `vs0`, `ts1`, and `vs1`, this\n * function determines which data signal is at a lower rate and performs linear\n * interpolation inorder to synchronize against the higher rate data signal.\n *\n * The outcome of this function is that both data signals will have:\n *\n * - Same number of timestamps.\n * - Lower-rate data will be interpolated against the higher rate data.\n *\n * **Note**: This function will drop values from the start and end of both\n * signals inorder to synchronize them.\n */\nvoid lerp_data(std::deque<timestamp_t> &ts0,\n               std::deque<vec3_t> &vs0,\n               std::deque<timestamp_t> &ts1,\n               std::deque<vec3_t> &vs1);\n\ntypedef Eigen::Spline<real_t, 1> Spline1D;\ntypedef Eigen::Spline<real_t, 2> Spline2D;\ntypedef Eigen::Spline<real_t, 3> Spline3D;\n\n#define SPLINE1D(X, Y, DEG)                                                    \\\n  Eigen::SplineFitting<Spline1D>::Interpolate(X, DEG, Y)\n\n#define SPLINE2D(X, Y, DEG)                                                    \\\n  Eigen::SplineFitting<Spline2D>::Interpolate(X, DEG, Y)\n\n#define SPLINE3D(X, Y, DEG)                                                    \\\n  Eigen::SplineFitting<Spline3D>::Interpolate(X, DEG, Y)\n\n/**\n * Continuous trajectory generator\n */\nstruct ctraj_t {\n  const timestamps_t timestamps;\n  const vec3s_t positions;\n  const quats_t orientations;\n\n  const real_t ts_s_start;\n  const real_t ts_s_end;\n  const real_t ts_s_gap;\n\n  Spline3D pos_spline;\n  Spline3D rvec_spline;\n\n  ctraj_t(const timestamps_t &timestamps,\n          const vec3s_t &positions,\n          const quats_t &orientations);\n};\n\n/**\n * Container for multiple continuous trajectories\n */\ntypedef std::vector<ctraj_t> ctrajs_t;\n\n/**\n * Initialize continuous trajectory.\n */\nvoid ctraj_init(ctraj_t &ctraj);\n\n/**\n * Calculate pose `T_WB` at timestamp `ts`.\n */\nmat4_t ctraj_get_pose(const ctraj_t &ctraj, const timestamp_t ts);\n\n/**\n * Calculate velocity `v_WB` at timestamp `ts`.\n */\nvec3_t ctraj_get_velocity(const ctraj_t &ctraj, const timestamp_t ts);\n\n/**\n * Calculate acceleration `a_WB` at timestamp `ts`.\n */\nvec3_t ctraj_get_acceleration(const ctraj_t &ctraj, const timestamp_t ts);\n\n/**\n * Calculate angular velocity `w_WB` at timestamp `ts`.\n */\nvec3_t ctraj_get_angular_velocity(const ctraj_t &ctraj, const timestamp_t ts);\n\n/**\n * Save trajectory to file\n */\nint ctraj_save(const ctraj_t &ctraj, const std::string &save_path);\n\n/**\n * SIM IMU\n */\nstruct sim_imu_t {\n  // IMU parameters\n  real_t rate = 0.0;        // IMU rate [Hz]\n  real_t tau_a = 0.0;       // Reversion time constant for accel [s]\n  real_t tau_g = 0.0;       // Reversion time constant for gyro [s]\n  real_t sigma_g_c = 0.0;   // Gyro noise density [rad/s/sqrt(Hz)]\n  real_t sigma_a_c = 0.0;   // Accel noise density [m/s^s/sqrt(Hz)]\n  real_t sigma_gw_c = 0.0;  // Gyro drift noise density [rad/s^s/sqrt(Hz)]\n  real_t sigma_aw_c = 0.0;  // Accel drift noise density [m/s^2/sqrt(Hz)]\n  real_t g = 9.81;          // Gravity vector [ms-2]\n\n  // IMU flags and biases\n  bool started = false;\n  vec3_t b_g = zeros(3, 1);\n  vec3_t b_a = zeros(3, 1);\n  timestamp_t ts_prev = 0;\n};\n\n/**\n * Reset IMU\n */\nvoid sim_imu_reset(sim_imu_t &imu);\n\n/**\n * Simulate IMU measurement\n */\nvoid sim_imu_measurement(sim_imu_t &imu,\n                         std::default_random_engine &rndeng,\n                         const timestamp_t &ts,\n                         const mat4_t &T_WS_W,\n                         const vec3_t &w_WS_W,\n                         const vec3_t &a_WS_W,\n                         vec3_t &a_WS_S,\n                         vec3_t &w_WS_S);\n\n/*****************************************************************************\n *                                CONTROL\n *****************************************************************************/\n\n/**\n * PID Controller\n */\nstruct pid_t {\n  real_t error_prev = 0.0;\n  real_t error_sum = 0.0;\n\n  real_t error_p = 0.0;\n  real_t error_i = 0.0;\n  real_t error_d = 0.0;\n\n  real_t k_p = 0.0;\n  real_t k_i = 0.0;\n  real_t k_d = 0.0;\n\n  pid_t();\n  pid_t(const real_t k_p, const real_t k_i, const real_t k_d);\n  ~pid_t();\n};\n\n/**\n * `pid_t` to output stream\n */\nstd::ostream &operator<<(std::ostream &os, const pid_t &pid);\n\n/**\n * Update controller\n *\n * @returns Controller command\n */\nreal_t pid_update(pid_t &p,\n                  const real_t setpoint,\n                  const real_t actual,\n                  const real_t dt);\n\n/**\n * Update controller\n *\n * @returns Controller command\n */\nreal_t pid_update(pid_t &p, const real_t error, const real_t dt);\n\n/**\n * Reset controller\n */\nvoid pid_reset(pid_t &p);\n\n/**\n * Carrot control\n */\nstruct carrot_ctrl_t {\n  vec3s_t waypoints;\n  vec3_t wp_start = vec3_t::Zero();\n  vec3_t wp_end = vec3_t::Zero();\n  size_t wp_index = 0;\n  real_t look_ahead_dist = 0.0;\n\n  carrot_ctrl_t();\n  ~carrot_ctrl_t();\n};\n\n/**\n * Configure carrot control using a list of position `waypoints` (x, y, z), and\n * a `look_ahead` distance in [m].\n *\n * @returns 0 for success, -1 for failure\n */\nint carrot_ctrl_configure(carrot_ctrl_t &cc,\n                          const vec3s_t &waypoints,\n                          const real_t look_ahead_dist);\n\n/**\n * Calculate closest point along current trajectory using current position\n * `pos`, and outputs the closest point in `result`.\n *\n * @returns A number to denote progress along the waypoint, if -1 then the\n * position is before `wp_start`, 0 if the position is between `wp_start` and\n * `wp_end`, and finally 1 if the position is after `wp_end`.\n */\nint carrot_ctrl_closest_point(const carrot_ctrl_t &cc,\n                              const vec3_t &pos,\n                              vec3_t &result);\n\n/**\n * Calculate carrot point using current position `pos`, and outputs the carrot\n * point in `result`.\n *\n * @returns A number to denote progress along the waypoint, if -1 then the\n * position is before `wp_start`, 0 if the position is between `wp_start` and\n * `wp_end`, and finally 1 if the position is after `wp_end`.\n */\nint carrot_ctrl_carrot_point(const carrot_ctrl_t &cc,\n                             const vec3_t &pos,\n                             vec3_t &result);\n\n/**\n * Update carrot controller using current position `pos` and outputs the carrot\n * point in `result`.\n *\n * @returns 0 for success, 1 for all waypoints reached and -1 for failure\n */\nint carrot_ctrl_update(carrot_ctrl_t &cc, const vec3_t &pos, vec3_t &carrot_pt);\n\n/******************************************************************************\n *                               MEASUREMENTS\n *****************************************************************************/\n\nstruct meas_t {\n  timestamp_t ts = 0;\n\n  meas_t() {}\n  meas_t(const timestamp_t &ts_) : ts{ts_} {}\n  virtual ~meas_t() {}\n};\n\nstruct imu_meas_t {\n  timestamp_t ts = 0;\n  vec3_t accel{0.0, 0.0, 0.0};\n  vec3_t gyro{0.0, 0.0, 0.0};\n\n  imu_meas_t() {}\n\n  imu_meas_t(const timestamp_t &ts_, const vec3_t &accel_, const vec3_t &gyro_)\n    : ts{ts_}, accel{accel_}, gyro{gyro_} {}\n\n  ~imu_meas_t() {}\n};\n\nstruct imu_data_t {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n  timestamps_t timestamps;\n  vec3s_t accel;\n  vec3s_t gyro;\n\n  void add(const timestamp_t &ts, const vec3_t &acc, const vec3_t &gyr) {\n    timestamps.push_back(ts);\n    accel.push_back(acc);\n    gyro.push_back(gyr);\n  }\n\n  size_t size() const { return timestamps.size(); }\n  size_t size() { return static_cast<const imu_data_t &>(*this).size(); }\n\n  timestamp_t last_ts() const { return timestamps.back(); }\n  timestamp_t last_ts() { return static_cast<const imu_data_t &>(*this).last_ts(); }\n\n  void clear() {\n    timestamps.clear();\n    accel.clear();\n    gyro.clear();\n  }\n};\n\n// struct image_t : meas_t {\n//   int width = 0;\n//   int height = 0;\n//   float *data = nullptr;\n//\n//   image_t() {}\n//\n//   image_t(const timestamp_t ts_, const int width_, const int height_)\n//       : meas_t{ts_}, width{width_}, height{height_} {\n//     data = new float[width * height];\n//   }\n//\n//   image_t(const timestamp_t ts_,\n//           const int width_,\n//           const int height_,\n//           float *data_)\n//       : meas_t{ts_}, width{width_}, height{height_}, data{data_} {}\n//\n//   virtual ~image_t() {\n//     if (data) {\n//       free(data);\n//     }\n//   }\n// };\n\nstruct cam_frame_t {\n  timestamp_t ts = 0;\n  vec2s_t keypoints;\n  std::vector<size_t> feature_ids;\n\n  cam_frame_t() {}\n\n  cam_frame_t(const timestamp_t &ts_,\n              const vec2s_t &keypoints_,\n              const std::vector<size_t> feature_ids_)\n    : ts{ts_}, keypoints{keypoints_}, feature_ids{feature_ids_} {}\n\n  ~cam_frame_t() {}\n};\n\n/******************************************************************************\n *                                 MODELS\n *****************************************************************************/\n\n/**\n * Create DH transform from link n to link n-1 (end to front)\n *\n * @param[in] theta\n * @param[in] d\n * @param[in] a\n * @param[in] alpha\n *\n * @returns DH transform\n */\nmat4_t dh_transform(const real_t theta,\n                    const real_t d,\n                    const real_t a,\n                    const real_t alpha);\n\n/**\n * 2-DOF Gimbal Model\n */\nstruct gimbal_model_t {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  // Parameter vector of transform from\n  // static camera to base-mechanism\n  vecx_t tau_s = zeros(6, 1);\n\n  // Parameter vector of transform from\n  // end-effector to dynamic camera\n  vecx_t tau_d = zeros(6, 1);\n\n  // First gibmal-joint\n  real_t Lambda1 = 0.0;\n  vec3_t w1 = zeros(3, 1);\n\n  // Second gibmal-joint\n  real_t Lambda2 = 0.0;\n  vec3_t w2 = zeros(3, 1);\n\n  real_t theta1_offset = 0.0;\n  real_t theta2_offset = 0.0;\n\n  gimbal_model_t();\n  gimbal_model_t(const vec6_t &tau_s,\n                 const vec6_t &tau_d,\n                 const real_t Lambda1,\n                 const vec3_t w1,\n                 const real_t Lambda2,\n                 const vec3_t w2,\n                 const real_t theta1_offset = 0.0,\n                 const real_t theta2_offset = 0.0);\n  virtual ~gimbal_model_t();\n};\n\n/**\n * Set gimbal attitude\n *\n * @param[in,out] model Model\n * @param[in] roll Roll [rads]\n * @param[in] pitch Pitch [rads]\n */\nvoid gimbal_model_set_attitude(gimbal_model_t &model,\n                               const real_t roll,\n                               const real_t pitch);\n\n/**\n * Get gimbal joint angle\n *\n * @param[in] model Model\n * @returns Gimbal joint angles\n */\nvec2_t gimbal_model_get_joint_angles(const gimbal_model_t &model);\n\n/**\n * Returns transform from static camera to base mechanism\n *\n * @param[in] model Model\n * @returns Transform\n */\nmat4_t gimbal_model_T_BS(const gimbal_model_t &model);\n\n/**\n * Returns transform from base mechanism to end-effector\n *\n * @param[in] model Model\n * @returns Transform\n */\nmat4_t gimbal_model_T_EB(const gimbal_model_t &model);\n\n/**\n * Returns transform from end-effector to dynamic camera\n *\n * @param[in] model Model\n * @returns Transform\n */\nmat4_t gimbal_model_T_DE(const gimbal_model_t &model);\n\n/**\n * Returns transform from static to dynamic camera\n *\n * @param[in] model Model\n * @returns Transform\n */\nmat4_t gimbal_model_T_DS(const gimbal_model_t &model);\n\n/**\n * Returns transform from static to dynamic camera\n *\n * @param[in,out] model Model\n * @param[in] theta Gimbal roll and pitch [radians]\n * @returns Transform from static to dynamic camera\n */\nmat4_t gimbal_model_T_DS(gimbal_model_t &model, const vec2_t &theta);\n\n/**\n * gimbal_model_t to output stream\n */\nstd::ostream &operator<<(std::ostream &os, const gimbal_model_t &gimbal);\n\n/**\n * Calculate target angular velocity and time taken to traverse a desired\n * circle * trajectory of radius r and velocity v\n *\n * @param[in] r Desired circle radius\n * @param[in] v Desired trajectory velocity\n * @param[in] w Target angular velocity\n * @param[in] time Target time taken to complete circle trajectory\n **/\nvoid circle_trajectory(const real_t r, const real_t v, real_t *w, real_t *time);\n\n/**\n * Two wheel robot\n */\nstruct two_wheel_t {\n  vec3_t r_G = vec3_t::Zero();\n  vec3_t v_G = vec3_t::Zero();\n  vec3_t a_G = vec3_t::Zero();\n  vec3_t rpy_G = vec3_t::Zero();\n  vec3_t w_G = vec3_t::Zero();\n\n  real_t vx_desired = 0.0;\n  real_t yaw_desired = 0.0;\n\n  pid_t vx_controller{0.1, 0.0, 0.1};\n  pid_t yaw_controller{0.1, 0.0, 0.1};\n\n  vec3_t a_B = vec3_t::Zero();\n  vec3_t v_B = vec3_t::Zero();\n  vec3_t w_B = vec3_t::Zero();\n\n  two_wheel_t() {}\n\n  two_wheel_t(const vec3_t &r_G_, const vec3_t &v_G_, const vec3_t &rpy_G_)\n      : r_G{r_G_}, v_G{v_G_}, rpy_G{rpy_G_} {}\n\n  ~two_wheel_t() {}\n\n  void update(const real_t dt) {\n    const vec3_t r_G_prev = r_G;\n    const vec3_t v_G_prev = v_G;\n    const vec3_t rpy_G_prev = rpy_G;\n\n    r_G += euler321(rpy_G) * v_B * dt;\n    v_G = (r_G - r_G_prev) / dt;\n    a_G = (v_G - v_G_prev) / dt;\n\n    rpy_G += euler321(rpy_G) * w_B * dt;\n    w_G = rpy_G - rpy_G_prev;\n    a_B = euler123(rpy_G) * a_G;\n\n    // Wrap angles to +/- pi\n    for (int i = 0; i < 3; i++) {\n      rpy_G(i) = (rpy_G(i) > M_PI) ? rpy_G(i) - 2 * M_PI : rpy_G(i);\n      rpy_G(i) = (rpy_G(i) < -M_PI) ? rpy_G(i) + 2 * M_PI : rpy_G(i);\n    }\n  }\n};\n\n/**\n * MAV model\n */\nstruct mav_model_t {\n  vec3_t attitude{0.0, 0.0, 0.0};         ///< Attitude in global frame\n  vec3_t angular_velocity{0.0, 0.0, 0.0}; ///< Angular velocity in global frame\n  vec3_t position{0.0, 0.0, 0.0};         ///< Position in global frame\n  vec3_t linear_velocity{0.0, 0.0, 0.0};  ///< Linear velocity in global frame\n\n  real_t Ix = 0.0963; ///< Moment of inertia in x-axis\n  real_t Iy = 0.0963; ///< Moment of inertia in y-axis\n  real_t Iz = 0.1927; ///< Moment of inertia in z-axis\n\n  real_t kr = 0.1; ///< Rotation drag constant\n  real_t kt = 0.2; ///< Translation drag constant\n\n  real_t l = 0.9; ///< MAV arm length\n  real_t d = 1.0; ///< drag constant\n\n  real_t m = 1.0;  ///< Mass\n  real_t g = 9.81; ///< Gravity\n};\n\n/**\n * Update\n *\n * @param[in,out] qm Model\n * @param[in] motor_inputs Motor inputs (m1, m2, m3, m4)\n * @param[in] dt Time difference (s)\n * @returns 0 for success, -1 for failure\n */\nint mav_model_update(mav_model_t &qm,\n                     const vec4_t &motor_inputs,\n                     const real_t dt);\n\n/*****************************************************************************\n *                                  CV\n ****************************************************************************/\n\n/**\n * Compare `cv::Mat` whether they are equal\n *\n * @param m1 First matrix\n * @param m2 Second matrix\n * @returns true or false\n */\nbool is_equal(const cv::Mat &m1, const cv::Mat &m2);\n\n/**\n * Convert cv::Mat to Eigen::Matrix\n *\n * @param x Input matrix\n * @param y Output matrix\n */\nvoid convert(const cv::Mat &x, matx_t &y);\n\n/**\n * Convert Eigen::Matrix to cv::Mat\n *\n * @param x Input matrix\n * @param y Output matrix\n */\nvoid convert(const matx_t &x, cv::Mat &y);\n\n/**\n * Convert cv::Mat to Eigen::Matrix\n *\n * @param x Input matrix\n * @returns Matrix as Eigen::Matrix\n */\nmatx_t convert(const cv::Mat &x);\n\n/**\n * Convert Eigen::Matrix to cv::Mat\n *\n * @param x Input matrix\n * @returns Matrix as cv::Mat\n */\ncv::Mat convert(const matx_t &x);\n\n/**\n * Sort Keypoints\n *\n * @param keypoints\n * @param limit\n * @returns Sorted keypoints by response\n */\nstd::vector<cv::KeyPoint> sort_keypoints(\n    const std::vector<cv::KeyPoint> keypoints, const size_t limit = 0);\n\n/**\n * Convert gray-scale image to rgb image\n *\n * @param image\n *\n * @returns RGB image\n */\ncv::Mat gray2rgb(const cv::Mat &image);\n\n/**\n * Convert rgb image to gray-scale image\n *\n * @param image\n *\n * @returns Gray-scale image\n */\ncv::Mat rgb2gray(const cv::Mat &image);\n\n/**\n * Create ROI from an image\n *\n * @param[in] image Input image\n * @param[in] width ROI width\n * @param[in] height ROI height\n * @param[in] cx ROI center x-axis\n * @param[in] cy ROI center y-axis\n *\n * @returns ROI\n */\ncv::Mat roi(const cv::Mat &image,\n            const int width,\n            const int height,\n            const real_t cx,\n            const real_t cy);\n\n/**\n * Compare two keypoints based on the response.\n *\n * @param[in] kp1 First keypoint\n * @param[in] kp2 Second keypoint\n * @returns Boolean to denote if first keypoint repose is larger than second\n */\nbool keypoint_compare_by_response(const cv::KeyPoint &kp1,\n                                  const cv::KeyPoint &kp2);\n\n/**\n * Calculate reprojection error\n *\n * @param[in] measured Measured image pixels\n * @param[in] projected Projected image pixels\n * @returns Reprojection error\n */\nreal_t reprojection_error(const vec2s_t &measured, const vec2s_t &projected);\n\n/**\n * Calculate reprojection error\n *\n * @param[in] measured Measured image pixels\n * @param[in] projected Projected image pixels\n * @returns Reprojection error\n */\nreal_t reprojection_error(const std::vector<cv::Point2f> &measured,\n                          const std::vector<cv::Point2f> &projected);\n\n/**\n * Create feature mask\n *\n * @param[in] image_width Image width\n * @param[in] image_height Image height\n * @param[in] points Points\n * @param[in] patch_width Patch width\n *\n * @returns Feature mask\n */\nmatx_t feature_mask(const int image_width,\n                    const int image_height,\n                    const std::vector<cv::Point2f> points,\n                    const int patch_width);\n\n/**\n * Create feature mask\n *\n * @param[in] image_width Image width\n * @param[in] image_height Image height\n * @param[in] keypoints Keypoints\n * @param[in] patch_width Patch width\n *\n * @returns Feature mask\n */\nmatx_t feature_mask(const int image_width,\n                    const int image_height,\n                    const std::vector<cv::KeyPoint> keypoints,\n                    const int patch_width);\n\n/**\n * Create feature mask\n *\n * @param[in] image_width Image width\n * @param[in] image_height Image height\n * @param[in] points Points\n * @param[in] patch_width Patch width\n *\n * @returns Feature mask\n */\ncv::Mat feature_mask_opencv(const int image_width,\n                            const int image_height,\n                            const std::vector<cv::Point2f> points,\n                            const int patch_width);\n\n/**\n * Create feature mask\n *\n * @param[in] image_width Image width\n * @param[in] image_height Image height\n * @param[in] keypoints Keypoints\n * @param[in] patch_width Patch width\n *\n * @returns Feature mask\n */\ncv::Mat feature_mask_opencv(const int image_width,\n                            const int image_height,\n                            const std::vector<cv::KeyPoint> keypoints,\n                            const int patch_width);\n\n/**\n * Equi undistort image\n *\n * @param[in] K Camera matrix K\n * @param[in] D Distortion vector D\n * @param[in] image Input image\n *\n * @returns Undistorted image using radial-tangential distortion\n */\ncv::Mat radtan_undistort_image(const mat3_t &K,\n                               const vecx_t &D,\n                               const cv::Mat &image);\n\n/**\n * Equi undistort image\n *\n * @param[in] K Camera matrix K\n * @param[in] D Distortion vector D\n * @param[in] image Input image\n * @param[in] balance Balance\n * @param[in,out] Knew New camera matrix K\n *\n * @returns Undistorted image using equidistant distortion\n */\ncv::Mat equi_undistort_image(const mat3_t &K,\n                             const vecx_t &D,\n                             const cv::Mat &image,\n                             const real_t balance,\n                             cv::Mat &Knew);\n/**\n * Illumination invariant transform.\n *\n * @param[in] image Image\n * @param[in] lambda_1 Lambad 1\n * @param[in] lambda_2 Lambad 2\n * @param[in] lambda_3 Lambad 3\n */\nvoid illum_invar_transform(cv::Mat &image,\n                           const real_t lambda_1,\n                           const real_t lambda_2,\n                           const real_t lambda_3);\n\n/**\n * Draw tracks\n *\n * @param[in] img_cur Current image frame\n * @param[in] p0 Previous corners\n * @param[in] p1 Current corners\n * @param[in] status Corners status\n *\n * @returns Image with feature matches between previous and current frame\n */\ncv::Mat draw_tracks(const cv::Mat &img_cur,\n                    const std::vector<cv::Point2f> p0,\n                    const std::vector<cv::Point2f> p1,\n                    const std::vector<uchar> &status);\n\n/**\n * Draw tracks\n *\n * @param[in] img_cur Current image frame\n * @param[in] p0 Previous corners\n * @param[in] p1 Current corners\n * @param[in] status Corners status\n *\n * @returns Image with feature matches between previous and current frame\n */\ncv::Mat draw_tracks(const cv::Mat &img_cur,\n                    const std::vector<cv::Point2f> p0,\n                    const std::vector<cv::Point2f> p1,\n                    const std::vector<uchar> &status);\n\n/**\n * Draw matches\n *\n * @param[in] img0 Image frame 0\n * @param[in] img1 Image frame 1\n * @param[in] k0 Previous keypoints\n * @param[in] k1 Current keypoints\n * @param[in] status Inlier vector\n *\n * @returns Image with feature matches between frame 0 and 1\n */\ncv::Mat draw_matches(const cv::Mat &img0,\n                     const cv::Mat &img1,\n                     const std::vector<cv::Point2f> k0,\n                     const std::vector<cv::Point2f> k1,\n                     const std::vector<uchar> &status);\n\n/**\n * Draw matches\n *\n * @param[in] img0 Previous image frame\n * @param[in] img1 Current image frame\n * @param[in] k0 Previous keypoints\n * @param[in] k1 Current keypoints\n * @param[in] matches Feature matches\n *\n * @returns Image with feature matches between previous and current frame\n */\ncv::Mat draw_matches(const cv::Mat &img0,\n                     const cv::Mat &img1,\n                     const std::vector<cv::KeyPoint> k0,\n                     const std::vector<cv::KeyPoint> k1,\n                     const std::vector<cv::DMatch> &matches);\n\n/**\n * Draw grid features\n *\n * @param[in] image Image frame\n * @param[in] grid_rows Grid rows\n * @param[in] grid_cols Grid cols\n * @param[in] features List of features\n *\n * @returns Grid features image\n */\ncv::Mat draw_grid_features(const cv::Mat &image,\n                           const int grid_rows,\n                           const int grid_cols,\n                           const std::vector<cv::Point2f> features);\n\n/**\n * Draw grid features\n *\n * @param[in] image Image frame\n * @param[in] grid_rows Grid rows\n * @param[in] grid_cols Grid cols\n * @param[in] features List of features\n *\n * @returns Grid features image\n */\ncv::Mat draw_grid_features(const cv::Mat &image,\n                           const int grid_rows,\n                           const int grid_cols,\n                           const std::vector<cv::KeyPoint> features);\n\n/**\n * Grid fast\n *\n * @param[in] image Input image\n * @param[in] max_corners Max number of corners\n * @param[in] grid_rows Number of grid rows\n * @param[in] grid_cols Number of grid cols\n * @param[in] threshold Fast threshold\n * @param[in] nonmax_suppression Nonmax Suppression\n *\n * @returns List of keypoints\n */\nstd::vector<cv::Point2f> grid_fast(const cv::Mat &image,\n                                   const int max_corners = 100,\n                                   const int grid_rows = 5,\n                                   const int grid_cols = 5,\n                                   const real_t threshold = 10.0,\n                                   const bool nonmax_suppression = true);\n\n/**\n * Grid good\n *\n * @param[in] image Input image\n * @param[in] max_corners Max number of corners\n * @param[in] grid_rows Number of grid rows\n * @param[in] grid_cols Number of grid cols\n * @param[in] quality_level Quality level\n * @param[in] min_distance Min distance\n * @param[in] mask Mask\n * @param[in] block_size Block size\n * @param[in] use_harris_detector Use Harris detector\n * @param[in] k Free parameter for Harris detector\n *\n * @returns List of points\n */\nstd::vector<cv::Point2f> grid_good(const cv::Mat &image,\n                                   const int max_corners = 100,\n                                   const int grid_rows = 5,\n                                   const int grid_cols = 5,\n                                   const real_t quality_level = 0.01,\n                                   const real_t min_distance = 10,\n                                   const cv::Mat mask = cv::Mat(),\n                                   const int block_size = 3,\n                                   const bool use_harris_detector = false,\n                                   const real_t k = 0.04);\n\n/**\n * Distortion model\n */\nstruct distortion_t {\n  vecx_t params;\n\n  distortion_t() {}\n\n  distortion_t(const vecx_t &params_)\n    : params{params_} {}\n\n  distortion_t(const real_t *params_, const size_t params_size_) {\n    params.resize(params_size_);\n    for (size_t i = 0; i < params_size_; i++) {\n      params(i) = params_[i];\n    }\n  }\n\n  virtual ~distortion_t() {}\n\n  virtual vec2_t distort(const vec2_t &p) = 0;\n  virtual vec2_t distort(const vec2_t &p) const = 0;\n\n  virtual vec2_t undistort(const vec2_t &p) = 0;\n  virtual vec2_t undistort(const vec2_t &p) const = 0;\n\n  virtual mat2_t J_point(const vec2_t &p) = 0;\n  virtual mat2_t J_point(const vec2_t &p) const = 0;\n\n  virtual matx_t J_dist(const vec2_t &p) = 0;\n  virtual matx_t J_dist(const vec2_t &p) const = 0;\n\n  // virtual void operator=(const distortion_t &src) throw() = 0;\n};\n\n/**\n * No distortion\n */\nstruct nodist_t : distortion_t {\n  static const size_t params_size = 0;\n\n  nodist_t() {}\n  nodist_t(const vecx_t &) {}\n  nodist_t(const real_t *) {}\n  ~nodist_t() {}\n\n  vec2_t distort(const vec2_t &p) {\n    return static_cast<const nodist_t &>(*this).distort(p);\n  }\n\n  vec2_t distort(const vec2_t &p) const {\n    return p;\n  }\n\n  vec2_t undistort(const vec2_t &p) {\n    return static_cast<const nodist_t &>(*this).undistort(p);\n  }\n\n  vec2_t undistort(const vec2_t &p) const {\n    return p;\n  }\n\n  mat2_t J_point(const vec2_t &p) {\n    return static_cast<const nodist_t &>(*this).J_point(p);\n  }\n\n  mat2_t J_point(const vec2_t &p) const {\n    UNUSED(p);\n    return I(2);\n  }\n\n  matx_t J_dist(const vec2_t &p) {\n    return static_cast<const nodist_t &>(*this).J_dist(p);\n  }\n\n  matx_t J_dist(const vec2_t &p) const {\n    UNUSED(p);\n    matx_t J;\n    J.resize(2, 0);\n    return J;\n  }\n};\n\n/**\n * Radial-tangential distortion\n */\nstruct radtan4_t : distortion_t {\n  static const size_t params_size = 4;\n\n  radtan4_t() {}\n\n  radtan4_t(const vecx_t &params_)\n    : distortion_t{params_} {}\n\n  radtan4_t(const real_t *dist_params)\n    : distortion_t{dist_params, params_size} {}\n\n  radtan4_t(const real_t k1,\n            const real_t k2,\n            const real_t p1,\n            const real_t p2)\n    : distortion_t{vec4_t{k1, k2, p1, p2}} {}\n\n  virtual ~radtan4_t() {}\n\n  real_t k1() { return static_cast<const radtan4_t &>(*this).k1(); }\n  real_t k2() { return static_cast<const radtan4_t &>(*this).k2(); }\n  real_t p1() { return static_cast<const radtan4_t &>(*this).p1(); }\n  real_t p2() { return static_cast<const radtan4_t &>(*this).p2(); }\n  real_t k1() const { return params(0); }\n  real_t k2() const { return params(1); }\n  real_t p1() const { return params(2); }\n  real_t p2() const { return params(3); }\n\n  vec2_t distort(const vec2_t &p) {\n    return static_cast<const radtan4_t &>(*this).distort(p);\n  }\n\n  vec2_t distort(const vec2_t &p) const {\n    const real_t x = p(0);\n    const real_t y = p(1);\n\n    // Apply radial distortion\n    const real_t x2 = x * x;\n    const real_t y2 = y * y;\n    const real_t r2 = x2 + y2;\n    const real_t r4 = r2 * r2;\n    const real_t radial_factor = 1 + (k1() * r2) + (k2() * r4);\n    const real_t x_dash = x * radial_factor;\n    const real_t y_dash = y * radial_factor;\n\n    // Apply tangential distortion\n    const real_t xy = x * y;\n    const real_t x_ddash = x_dash + (2 * p1() * xy + p2() * (r2 + 2 * x2));\n    const real_t y_ddash = y_dash + (p1() * (r2 + 2 * y2) + 2 * p2() * xy);\n\n    return vec2_t{x_ddash, y_ddash};\n  }\n\n  vec2_t undistort(const vec2_t &p0) {\n    return static_cast<const radtan4_t &>(*this).undistort(p0);\n  }\n\n  vec2_t undistort(const vec2_t &p0) const {\n    vec2_t p = p0;\n    int max_iter = 5;\n\n    for (int i = 0; i < max_iter; i++) {\n      // Error\n      const vec2_t p_distorted = distort(p);\n      const vec2_t err = (p0 - p_distorted);\n\n      // Jacobian\n      mat2_t J = J_point(p);\n      const mat2_t pinv = (J.transpose() * J).inverse() * J.transpose();\n      const vec2_t dp = pinv * err;\n      p = p + dp;\n\n      if ((err.transpose() * err) < 1.0e-15) {\n        break;\n      }\n    }\n\n    return p;\n  }\n\n  mat2_t J_point(const vec2_t &p) {\n    return static_cast<const radtan4_t &>(*this).J_point(p);\n  }\n\n  mat2_t J_point(const vec2_t &p) const {\n    const real_t x = p(0);\n    const real_t y = p(1);\n\n    const real_t x2 = x * x;\n    const real_t y2 = y * y;\n    const real_t r2 = x2 + y2;\n    const real_t r4 = r2 * r2;\n\n    // Let p = [x; y] normalized point\n    // Let p' be the distorted p\n    // The jacobian of p' w.r.t. p (or dp'/dp) is:\n    mat2_t J_point;\n    J_point(0, 0) = 1 + k1() * r2 + k2() * r4;\n    J_point(0, 0) += 2 * p1() * y + 6 * p2() * x;\n    J_point(0, 0) += x * (2 * k1() * x + 4 * k2() * x * r2);\n    J_point(1, 0) = 2 * p1() * x + 2 * p2() * y;\n    J_point(1, 0) += y * (2 * k1() * x + 4 * k2() * x * r2);\n    J_point(0, 1) = J_point(1, 0);\n    J_point(1, 1) = 1 + k1() * r2 + k2() * r4;\n    J_point(1, 1) += 6 * p1() * y + 2 * p2() * x;\n    J_point(1, 1) += y * (2 * k1() * y + 4 * k2() * y * r2);\n    // Above is generated using sympy\n\n    return J_point;\n  }\n\n  matx_t J_dist(const vec2_t &p) {\n    return static_cast<const radtan4_t &>(*this).J_dist(p);\n  }\n\n  matx_t J_dist(const vec2_t &p) const {\n    const real_t x = p(0);\n    const real_t y = p(1);\n\n    const real_t xy = x * y;\n    const real_t x2 = x * x;\n    const real_t y2 = y * y;\n    const real_t r2 = x2 + y2;\n    const real_t r4 = r2 * r2;\n\n    mat_t<2, 4> J_dist = zeros(2, 4);\n    J_dist(0, 0) = x * r2;\n    J_dist(0, 1) = x * r4;\n    J_dist(0, 2) = 2 * xy;\n    J_dist(0, 3) = 3 * x2 + y2;\n\n    J_dist(1, 0) = y * r2;\n    J_dist(1, 1) = y * r4;\n    J_dist(1, 2) = x2 + 3 * y2;\n    J_dist(1, 3) = 2 * xy;\n\n    return J_dist;\n  }\n};\n\nstd::ostream &operator<<(std::ostream &os, const radtan4_t &radtan4);\n\n/**\n * Equi-distant distortion\n */\nstruct equi4_t : distortion_t {\n  static const size_t params_size = 4;\n\n  equi4_t() {}\n\n  equi4_t(const vecx_t &dist_params)\n    : distortion_t{dist_params} {}\n\n  equi4_t(const real_t *dist_params)\n    : distortion_t{dist_params, params_size} {}\n\n  equi4_t(const real_t k1,\n          const real_t k2,\n          const real_t k3,\n          const real_t k4) {\n    params.resize(4);\n    params << k1, k2, k3, k4;\n  }\n\n  ~equi4_t() {}\n\n  real_t k1() { return static_cast<const equi4_t &>(*this).k1(); }\n  real_t k2() { return static_cast<const equi4_t &>(*this).k2(); }\n  real_t k3() { return static_cast<const equi4_t &>(*this).k3(); }\n  real_t k4() { return static_cast<const equi4_t &>(*this).k4(); }\n\n  real_t k1() const { return this->params(0); }\n  real_t k2() const { return this->params(1); }\n  real_t k3() const { return this->params(2); }\n  real_t k4() const { return this->params(3); }\n\n  vec2_t distort(const vec2_t &p) {\n    return static_cast<const equi4_t &>(*this).distort(p);\n  }\n\n  vec2_t distort(const vec2_t &p) const {\n    const real_t r = p.norm();\n    if (r < 1e-8) {\n      return p;\n    }\n\n    // Apply equi distortion\n    const real_t th = atan(r);\n    const real_t th2 = th * th;\n    const real_t th4 = th2 * th2;\n    const real_t th6 = th4 * th2;\n    const real_t th8 = th4 * th4;\n    const real_t thd = th * (1 + k1() * th2 + k2() * th4 + k3() * th6 + k4() * th8);\n    const real_t x_dash = (thd / r) * p(0);\n    const real_t y_dash = (thd / r) * p(1);\n\n    return vec2_t{x_dash, y_dash};\n  }\n\n  vec2_t undistort(const vec2_t &p) {\n    return static_cast<const equi4_t &>(*this).undistort(p);\n  }\n\n  vec2_t undistort(const vec2_t &p) const {\n    const real_t thd = sqrt(p(0) * p(0) + p(1) * p(1));\n\n    real_t th = thd; // Initial guess\n    for (int i = 20; i > 0; i--) {\n      const real_t th2 = th * th;\n      const real_t th4 = th2 * th2;\n      const real_t th6 = th4 * th2;\n      const real_t th8 = th4 * th4;\n      th = thd / (1 + k1() * th2 + k2() * th4 + k3() * th6 + k4() * th8);\n    }\n\n    const real_t scaling = tan(th) / thd;\n    return vec2_t{p(0) * scaling, p(1) * scaling};\n  }\n\n  mat2_t J_point(const vec2_t &p) {\n    return static_cast<const equi4_t &>(*this).J_point(p);\n  }\n\n  mat2_t J_point(const vec2_t &p) const {\n    const real_t x = p(0);\n    const real_t y = p(1);\n    const real_t r = p.norm();\n    const real_t th = atan(r);\n    const real_t th2 = th * th;\n    const real_t th4 = th2 * th2;\n    const real_t th6 = th4 * th2;\n    const real_t th8 = th4 * th4;\n    const real_t thd = th * (1.0 + k1() * th2 + k2() * th4 + k3() * th6 + k4() * th8);\n    const real_t s = thd / r;\n\n    // Form jacobian\n    const real_t th_r = 1.0 / (r * r + 1.0);\n    real_t thd_th = 1.0 + 3.0 * k1() * th2;\n    thd_th += 5.0 * k2() * th4;\n    thd_th += 7.0 * k3() * th6;\n    thd_th += 9.0 * k4() * th8;\n    const real_t s_r = thd_th * th_r / r - thd / (r * r);\n    const real_t r_x = 1.0 / r * x;\n    const real_t r_y = 1.0 / r * y;\n\n    mat2_t J_point = I(2);\n    J_point(0, 0) = s + x * s_r * r_x;\n    J_point(0, 1) = x * s_r * r_y;\n    J_point(1, 0) = y * s_r * r_x;\n    J_point(1, 1) = s + y * s_r * r_y;\n\n    return J_point;\n  }\n\n  matx_t J_dist(const vec2_t &p) {\n    return static_cast<const equi4_t &>(*this).J_dist(p);\n  }\n\n  matx_t J_dist(const vec2_t &p) const {\n    const real_t x = p(0);\n    const real_t y = p(1);\n    const real_t r = p.norm();\n    const real_t th = atan(r);\n\n    const real_t th3 = th * th * th;\n    const real_t th5 = th3 * th * th;\n    const real_t th7 = th5 * th * th;\n    const real_t th9 = th7 * th * th;\n\n    matx_t J_dist = zeros(2, 4);\n    J_dist(0, 0) = x * th3 / r;\n    J_dist(0, 1) = x * th5 / r;\n    J_dist(0, 2) = x * th7 / r;\n    J_dist(0, 3) = x * th9 / r;\n\n    J_dist(1, 0) = y * th3 / r;\n    J_dist(1, 1) = y * th5 / r;\n    J_dist(1, 2) = y * th7 / r;\n    J_dist(1, 3) = y * th9 / r;\n\n    return J_dist;\n  }\n};\n\nstd::ostream &operator<<(std::ostream &os, const equi4_t &equi4);\n\n/**\n * Projection model\n */\ntemplate <typename DM = nodist_t>\nstruct projection_t {\n  int resolution[2] = {0, 0};\n  vecx_t params;\n  DM distortion;\n\n  projection_t() {}\n\n  projection_t(const int resolution_[2],\n               const vecx_t &proj_params_,\n               const vecx_t &dist_params_)\n    : resolution{resolution_[0], resolution_[1]},\n      params{proj_params_},\n      distortion{dist_params_} {}\n\n  projection_t(const int resolution_[2],\n               const vecx_t &params_,\n               const size_t proj_params_size_,\n               const size_t dist_params_size_)\n    : projection_t{resolution_,\n                   params_.head(proj_params_size_),\n                   params_.tail(dist_params_size_)} {}\n\n  ~projection_t() {}\n\n  virtual mat2_t J_point() = 0;\n  virtual mat2_t J_point() const = 0;\n\n  virtual matx_t J_proj(const vec2_t &p) = 0;\n  virtual matx_t J_proj(const vec2_t &p) const = 0;\n\n  virtual matx_t J_dist(const vec2_t &p) = 0;\n  virtual matx_t J_dist(const vec2_t &p) const = 0;\n};\n\n/**\n * Pinhole projection model\n */\ntemplate <typename DM = nodist_t>\nstruct pinhole_t : projection_t<DM> {\n  static const size_t proj_params_size = 4;\n  static const size_t dist_params_size = DM::params_size;\n  static const size_t params_size = proj_params_size + dist_params_size;\n\n  pinhole_t() {}\n\n  pinhole_t(const int resolution[2],\n            const vecx_t &proj_params,\n            const vecx_t &dist_params)\n    : projection_t<DM>{resolution, proj_params, dist_params} {}\n\n  pinhole_t(const int resolution[2],\n            const vecx_t &params)\n    : projection_t<DM>{resolution, params, proj_params_size, DM::params_size} {}\n\n  pinhole_t(const int resolution[2],\n            const real_t fx,\n            const real_t fy,\n            const real_t cx,\n            const real_t cy)\n      : projection_t<DM>{resolution, vec4_t{fx, fy, cx, cy}, zeros(0)} {}\n\n  ~pinhole_t() {}\n\n  real_t fx() { return static_cast<const pinhole_t &>(*this).fx(); }\n  real_t fy() { return static_cast<const pinhole_t &>(*this).fy(); }\n  real_t cx() { return static_cast<const pinhole_t &>(*this).cx(); }\n  real_t cy() { return static_cast<const pinhole_t &>(*this).cy(); }\n\n  real_t fx() const { return this->params(0); }\n  real_t fy() const { return this->params(1); }\n  real_t cx() const { return this->params(2); }\n  real_t cy() const { return this->params(3); }\n\n  vecx_t proj_params() {\n    return static_cast<const pinhole_t &>(*this).proj_params();\n  }\n\n  vecx_t proj_params() const {\n    return this->params;\n  }\n\n  vecx_t dist_params() {\n    return static_cast<const pinhole_t &>(*this).dist_params();\n  }\n\n  vecx_t dist_params() const {\n    return this->distortion.params;\n  }\n\n  mat3_t K() {\n    return static_cast<const pinhole_t &>(*this).K();\n  }\n\n  mat3_t K() const {\n    mat3_t K = zeros(3, 3);\n    K(0, 0) = fx();\n    K(1, 1) = fy();\n    K(0, 2) = cx();\n    K(1, 2) = cy();\n    K(2, 2) = 1.0;\n    return K;\n  }\n\n  int project(const vec3_t &p_C, vec2_t &z_hat) {\n    return static_cast<const pinhole_t &>(*this).project(p_C, z_hat);\n  }\n\n  int project(const vec3_t &p_C, vec2_t &z_hat) const {\n    // Check validity of the point, simple depth test.\n    const real_t x = p_C(0);\n    const real_t y = p_C(1);\n    const real_t z = p_C(2);\n    if (z < 0.0) {\n      return -1;\n    }\n\n    // Project, distort and then scale and center\n    const vec2_t p{x / z, y / z};\n    const vec2_t p_dist = this->distortion.distort(p);\n    z_hat(0) = fx() * p_dist(0) + cx();\n    z_hat(1) = fy() * p_dist(1) + cy();\n\n    // Check projection\n    const bool x_ok = (z_hat(0) >= 0 && z_hat(0) <= this->resolution[0]);\n    const bool y_ok = (z_hat(1) >= 0 && z_hat(1) <= this->resolution[1]);\n    if (x_ok == false || y_ok == false) {\n      return -2;\n    }\n\n    return 0;\n  }\n\n  int project(const vec3_t &p_C, vec2_t &z_hat, mat_t<2, 3> &J_h) {\n    return static_cast<const pinhole_t &>(*this).project(p_C, z_hat, J_h);\n  }\n\n  int project(const vec3_t &p_C, vec2_t &z_hat, mat_t<2, 3> &J_h) const {\n    int retval = project(p_C, z_hat);\n\n    // Projection Jacobian\n    const real_t x = p_C(0);\n    const real_t y = p_C(1);\n    const real_t z = p_C(2);\n    mat_t<2, 3> J_proj = zeros(2, 3);\n    J_proj(0, 0) = 1.0 / z;\n    J_proj(1, 1) = 1.0 / z;\n    J_proj(0, 2) = -x / (z * z);\n    J_proj(1, 2) = -y / (z * z);\n\n    // Measurement Jacobian\n    const vec2_t p{x / z, y / z};\n    J_h = J_point() * this->distortion.J_point(p) * J_proj;\n\n    return retval;\n  }\n\n  int back_project(const vec2_t &kp, vec3_t &ray) {\n    const real_t px = (kp(0) - cx()) / fx();\n    const real_t py = (kp(1) - cy()) / fy();\n    const vec2_t p{px, py};\n\n    const vec2_t p_undist = this->distortion.undistort(p);\n    ray(0) = p_undist(0);\n    ray(1) = p_undist(1);\n    ray(2) = 1.0;\n\n    return 0;\n  }\n\n  vec2_t undistort(const vec2_t &z) {\n    return this->distortion.undistort(z);\n  }\n\n  mat2_t J_point() {\n    return static_cast<const pinhole_t &>(*this).J_point();\n  }\n\n  mat2_t J_point() const {\n    mat2_t J_K = zeros(2, 2);\n    J_K(0, 0) = fx();\n    J_K(1, 1) = fy();\n    return J_K;\n  }\n\n  matx_t J_proj(const vec2_t &p) {\n    return static_cast<const pinhole_t &>(*this).J_proj(p);\n  }\n\n  matx_t J_proj(const vec2_t &p) const {\n    const real_t x = p(0);\n    const real_t y = p(1);\n\n    mat_t<2, 4> J_proj = zeros(2, 4);\n    J_proj(0, 0) = x;\n    J_proj(1, 1) = y;\n    J_proj(0, 2) = 1;\n    J_proj(1, 3) = 1;\n\n    return J_proj;\n  }\n\n  matx_t J_dist(const vec2_t &p) {\n    return static_cast<const pinhole_t &>(*this).J_dist(p);\n  }\n\n  matx_t J_dist(const vec2_t &p) const {\n    return J_point() * this->distortion.J_dist(p);\n  }\n\n  matx_t J_params(const vec2_t &p) {\n    return static_cast<const pinhole_t &>(*this).J_params(p);\n  }\n\n  matx_t J_params(const vec2_t &p) const {\n    const vec2_t p_dist = this->distortion.distort(p);\n\n    matx_t J = zeros(2, params_size);\n    J.block(0, 0, 2, proj_params_size) = J_proj(p_dist);\n    J.block(0, dist_params_size, 2, proj_params_size) = J_dist(p);\n    return J;\n  }\n};\n\ntypedef pinhole_t<radtan4_t> pinhole_radtan4_t;\ntypedef pinhole_t<equi4_t> pinhole_equi4_t;\ntypedef pinhole_t<nodist_t> pinhole_ideal_t;\n\ntemplate <typename DM>\nstd::ostream &operator<<(std::ostream &os, const pinhole_t<DM> &pinhole) {\n  os << \"fx: \" << pinhole.fx() << std::endl;\n  os << \"fy: \" << pinhole.fy() << std::endl;\n  os << \"cx: \" << pinhole.cx() << std::endl;\n  os << \"cy: \" << pinhole.cy() << std::endl;\n\n  os << std::endl;\n  os << pinhole.distortion << std::endl;\n  return os;\n}\n\nreal_t pinhole_focal(const int image_size, const real_t fov);\n\nmat3_t pinhole_K(const real_t fx,\n                 const real_t fy,\n                 const real_t cx,\n                 const real_t cy);\n\nmat3_t pinhole_K(const vec4_t &params);\n\nmat3_t pinhole_K(const int img_w,\n                 const int img_h,\n                 const real_t lens_hfov,\n                 const real_t lens_vfov);\n\ntemplate <typename CAMERA_TYPE>\nint solvepnp(const CAMERA_TYPE &cam,\n             const vec2s_t keypoints,\n             const vec3s_t object_points,\n             mat4_t &T_CF) {\n  assert(keypoints.size() == object_points.size());\n\n  // Create object points (counter-clockwise, from bottom left)\n  size_t nb_points = keypoints.size();\n  std::vector<cv::Point3f> obj_pts;\n  std::vector<cv::Point2f> img_pts;\n  for (size_t i = 0; i < nb_points; i++) {\n    const vec2_t kp = cam.undistort(keypoints[i]);\n    const vec3_t pt = object_points[i];\n    img_pts.emplace_back(kp(0), kp(1));\n    obj_pts.emplace_back(pt(0), pt(1), pt(2));\n  }\n\n  // Extract out camera intrinsics\n  const double fx = cam.proj_params()(0);\n  const double fy = cam.proj_params()(1);\n  const double cx = cam.proj_params()(2);\n  const double cy = cam.proj_params()(3);\n\n  // Solve pnp\n  cv::Vec4f distortion_params(0, 0, 0, 0); // SolvPnP assumes radtan\n  cv::Mat camera_matrix(3, 3, CV_32FC1, 0.0f);\n  camera_matrix.at<float>(0, 0) = fx;\n  camera_matrix.at<float>(1, 1) = fy;\n  camera_matrix.at<float>(0, 2) = cx;\n  camera_matrix.at<float>(1, 2) = cy;\n  camera_matrix.at<float>(2, 2) = 1.0;\n\n  cv::Mat rvec;\n  cv::Mat tvec;\n  cv::solvePnP(obj_pts,\n              img_pts,\n              camera_matrix,\n              distortion_params,\n              rvec,\n              tvec,\n              false,\n              CV_ITERATIVE);\n\n  // Form relative tag pose as a 4x4 tfation matrix\n  // -- Convert Rodrigues rotation vector to rotation matrix\n  cv::Mat R;\n  cv::Rodrigues(rvec, R);\n  // -- Form full transformation matrix\n  T_CF = tf(convert(R), convert(tvec));\n\n  return 0;\n}\n\n/******************************************************************************\n *                               PARAMETERS\n *****************************************************************************/\n\nstruct imu_params_t {\n  real_t rate = 0.0;        // IMU rate [Hz]\n  real_t tau_a = 0.0;       // Reversion time constant for accel [s]\n  real_t tau_g = 0.0;       // Reversion time constant for gyro [s]\n  real_t sigma_g_c = 0.0;   // Gyro noise density [rad/s/sqrt(Hz)]\n  real_t sigma_a_c = 0.0;   // Accel noise density [m/s^s/sqrt(Hz)]\n  real_t sigma_gw_c = 0.0;  // Gyro drift noise density [rad/s^s/sqrt(Hz)]\n  real_t sigma_aw_c = 0.0;  // Accel drift noise density [m/s^2/sqrt(Hz)]\n  real_t g = 9.81;          // Gravity vector [ms-2]\n};\n\n/*****************************************************************************\n *                               SIMULATION\n *****************************************************************************/\n\nenum sim_event_type_t {\n  NOT_SET,\n  CAMERA,\n  IMU,\n};\n\nstruct sim_event_t {\n  sim_event_type_t type = NOT_SET;\n  int sensor_id = 0;\n  timestamp_t ts = 0;\n  imu_meas_t imu;\n  cam_frame_t frame;\n\n  // Camera event\n  sim_event_t(const int sensor_id_,\n              const timestamp_t &ts_,\n              const vec2s_t &keypoints_,\n              const std::vector<size_t> &feature_idxs_)\n    : type{CAMERA},\n      sensor_id{sensor_id_},\n      ts{ts_},\n      frame{ts_, keypoints_, feature_idxs_} {}\n\n  // IMU event\n  sim_event_t(const int sensor_id_, const timestamp_t &ts_,\n              const vec3_t &accel_, const vec3_t &gyro_)\n    : type{IMU}, sensor_id{sensor_id_}, ts{ts_}, imu{ts_, accel_, gyro_} {}\n};\n\nstruct vio_sim_data_t {\n  // Settings\n  real_t sensor_velocity = 0.3;\n  real_t cam_rate = 30;\n  real_t imu_rate = 400;\n\n  // Scene data\n  vec3s_t features;\n\n  // Camera data\n  timestamps_t cam_ts;\n  vec3s_t cam_pos_gnd;\n  quats_t cam_rot_gnd;\n  mat4s_t cam_poses_gnd;\n  vec3s_t cam_pos;\n  quats_t cam_rot;\n  mat4s_t cam_poses;\n  std::vector<std::vector<size_t>> observations;\n  std::vector<vec2s_t> keypoints;\n\n  // IMU data\n  timestamps_t imu_ts;\n  vec3s_t imu_acc;\n  vec3s_t imu_gyr;\n  vec3s_t imu_pos;\n  quats_t imu_rot;\n  mat4s_t imu_poses;\n  vec3s_t imu_vel;\n\n  // Simulation timeline\n  std::multimap<timestamp_t, sim_event_t> timeline;\n\n  // Add IMU measurement to timeline\n  void add(const int sensor_id,\n           const timestamp_t &ts,\n           const vec3_t &accel,\n           const vec3_t &gyro);\n\n  // Add camera frame to timeline\n  void add(const int sensor_id,\n           const timestamp_t &ts,\n           const vec2s_t &keypoints,\n           const std::vector<size_t> &feature_idxs);\n\n  void save(const std::string &dir);\n};\n\nvoid sim_circle_trajectory(const real_t circle_r, vio_sim_data_t &sim_data);\n\n} //  namespace yac\n#endif // YAC_CORE_HPP\n", "meta": {"hexsha": "0c3f15286800fe35c320bf57ebbb1f114319fc5e", "size": 99025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "yac/lib/core.hpp", "max_stars_repo_name": "chutsu/yac", "max_stars_repo_head_hexsha": "789c8b4116197e3a4b0232568414eec5489836da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-04-29T17:25:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T05:57:27.000Z", "max_issues_repo_path": "yac/lib/core.hpp", "max_issues_repo_name": "chutsu/yac", "max_issues_repo_head_hexsha": "789c8b4116197e3a4b0232568414eec5489836da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-26T04:44:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T17:56:35.000Z", "max_forks_repo_path": "yac/lib/core.hpp", "max_forks_repo_name": "chutsu/yac", "max_forks_repo_head_hexsha": "789c8b4116197e3a4b0232568414eec5489836da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-15T18:04:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-13T13:19:58.000Z", "avg_line_length": 26.4560512958, "max_line_length": 93, "alphanum_fraction": 0.5945973239, "num_tokens": 26852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.43508812396782176}}
{"text": "#ifndef STAN__PROB__DISTRIBUTIONS__MULTIVARIATE__CONTINUOUS__MULTI_NORMAL_SUFFICIENT_HPP\n#define STAN__PROB__DISTRIBUTIONS__MULTIVARIATE__CONTINUOUS__MULTI_NORMAL_SUFFICIENT_HPP\n\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/mat/err/check_ldlt_factor.hpp>\n#include <stan/math/prim/mat/err/check_symmetric.hpp>\n#include <stan/math/prim/scal/err/check_size_match.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive.hpp>\n#include <stan/math/prim/mat/fun/trace_inv_quad_form_ldlt.hpp>\n#include <stan/math/prim/mat/fun/log_determinant_ldlt.hpp>\n#include <stan/math/prim/scal/meta/return_type.hpp>\n#include <stan/math/prim/scal/meta/VectorViewMvt.hpp>\n#include <stan/math/prim/scal/meta/max_size_mvt.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n\nnamespace stan {\n\n  namespace prob {\n\n    template <typename T_sample, typename T_loc, typename T_covar>\n    typename boost::math::tools::promote_args<T_sample, typename scalar_type<T_loc>::type, T_covar>::type\n    multi_normal_sufficient_log(const int sampleSize,\n\t\t\t\tconst Eigen::Matrix<T_sample,Eigen::Dynamic,1>& sampleMu,\n\t\t\t\tconst Eigen::Matrix<T_sample,Eigen::Dynamic,Eigen::Dynamic>& sampleSigma,\n\t\t\t\tconst T_loc& mu,\n\t\t\t\tconst Eigen::Matrix<T_covar,Eigen::Dynamic,Eigen::Dynamic>& Sigma) {\n      static const char *function(\"stan::prob::multi_normal_sufficient_log\");\n      typedef typename boost::math::tools::promote_args<T_sample, typename scalar_type<T_loc>::type, T_covar>::type param_t;\n      typedef param_t lp_type;\n      lp_type lp(0.0);\n\t   \n      using stan::math::check_size_match;\n      using stan::math::check_finite;\n      using stan::math::check_not_nan;\n      using stan::math::check_positive;\n      using stan::math::check_symmetric;\n      using stan::math::check_ldlt_factor;\n\t   \n      check_size_match(function,\n                       \"Rows of covariance parameter\", sampleSigma.rows(), \n                       \"columns of covariance parameter\", sampleSigma.cols());\n      check_positive(function, \"Covariance matrix rows\", sampleSigma.rows());\n      check_symmetric(function, \"Covariance matrix\", sampleSigma);\n\n      check_size_match(function,\n                       \"Rows of covariance parameter\", Sigma.rows(), \n                       \"columns of covariance parameter\", Sigma.cols());\n      check_positive(function, \"Covariance matrix rows\", Sigma.rows());\n      check_symmetric(function, \"Covariance matrix\", Sigma);\n      \n      check_size_match(function, \n                       \"Size of data location\", sampleMu.size(),\n                       \"size of model location\", mu.size());\n      check_size_match(function, \n                       \"Size of data covariance\", sampleSigma.rows(), \n                       \"size of model covariance\", Sigma.rows());\n  \n      stan::math::LDLT_factor<param_t,Eigen::Dynamic,Eigen::Dynamic> ldlt_Sigma(Sigma);\n      check_ldlt_factor(function, \"LDLT_Factor of covariance parameter\", ldlt_Sigma);\n\n      Eigen::Matrix<param_t, Eigen::Dynamic, Eigen::Dynamic> ss;\n      ss = mdivide_left_ldlt(ldlt_Sigma, sampleSigma);\n\n      lp += (ss.diagonal().sum() + log_determinant_ldlt(ldlt_Sigma)) * (sampleSize - 1);\n\n      lp_type lp_location(0.0);\n      {\n\tEigen::Matrix<param_t, Eigen::Dynamic, 1> y_minus_mu(mu.size());\n\n\tfor (int j = 0; j < mu.size(); j++)\n\t  y_minus_mu(j) = mu(j) - sampleMu(j);\n\n\tlp_location = trace_inv_quad_form_ldlt(ldlt_Sigma, y_minus_mu) * sampleSize;\n\t// Could avoid re-solving Sigma\n\t// lp_location = quad_form(ss, y_minus_mu).diagonal().sum() * sampleSize;\n      }\n      return (lp + lp_location) * -0.5;\n    }\n  }\n}\n\n#endif\n", "meta": {"hexsha": "da420ed96790f15a35ff593af5ac6008662b4fe8", "size": 3754, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/multi_normal_sufficient.hpp", "max_stars_repo_name": "JuKa87/OpenMx", "max_stars_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/multi_normal_sufficient.hpp", "max_issues_repo_name": "JuKa87/OpenMx", "max_issues_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/multi_normal_sufficient.hpp", "max_forks_repo_name": "JuKa87/OpenMx", "max_forks_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.6511627907, "max_line_length": 124, "alphanum_fraction": 0.6979222163, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4350881170726708}}
{"text": "#pragma once\n\n#include <Core/CoreMacros.hpp>\n#include <Core/Math/Math.hpp>\n#include <Eigen/Core>\n#include <Eigen/Geometry> //homogeneous\n#include <random>\n\nnamespace Ra {\nnamespace Core {\nnamespace Utils {\n\n/*!\n * Colors are defined as vector4, i.e. 4 Scalars in RGBA order.\n * displayable colors should have all their coordinates between 0 and 1.\n *\n * \\warning Vector arithmetics can be used to add, substract, multiply or divide colors with\n * scalars and other colors. In that case, alpha is treated as any other component. It is fine for\n * most cases, however adding two colors (e.g. Blue()+Red()) may lead to unconsistent\n * alpha: Blue()+Red() = {1, 0, 1, 2}.\n * In that case, only the rgb values need to be added:\n * \\code\n * Color result = Color::fromRGB( Blue().rgb()+Red().rgb() ); // result = {1, 0, 1, 1}\n * \\endcode\n * The validity of alpha can be checked using hasValidAlpha().\n */\ntemplate <typename _Scalar>\nclass ColorBase : public Eigen::Matrix<_Scalar, 4, 1>\n{\n  public:\n    using VectorType = Eigen::Matrix<_Scalar, 4, 1>;\n\n    explicit inline ColorBase() : ColorBase( _Scalar( 1. ), _Scalar( 1. ), _Scalar( 1. ) ) {}\n\n    template <typename S2>\n    inline ColorBase( S2 r, S2 g, S2 b, S2 alpha = S2( 1 ) ) :\n        VectorType( _Scalar( r ), _Scalar( g ), _Scalar( b ), _Scalar( alpha ) ) {}\n\n    /// Copy constructor\n    template <typename S2>\n    inline ColorBase( const ColorBase<S2>& other ) : VectorType( other.template cast<_Scalar>() ) {}\n\n    /// Copy constructor from Eigen expressions: `ColorBase<_Scalar> c( (*this) * 255 );`\n    template <typename Derived>\n    inline ColorBase( const Eigen::MatrixBase<Derived>& v ) :\n        VectorType( v.template cast<_Scalar>() ) {}\n\n    /// cast operator, mandatory to use Vector arithmetic\n    operator VectorType() { return *this; }\n\n    /// convert the color expressed in sRGB color space to linear RGB\n    static inline ColorBase sRGBToLinearRGB( const ColorBase& srgb ) {\n        ColorBase<_Scalar> c( srgb );\n        for ( auto& u : c.rgb() )\n        {\n            if ( u < 0.04045_ra ) { u /= 12.92_ra; }\n            else\n            { u = std::pow( ( u + 0.055_ra ) / 1.055_ra, 2.4_ra ); }\n        }\n        return c;\n    }\n\n    /// convert the color expressed in linear RGB color space to sRGB\n    static inline ColorBase linearRGBTosRGB( const ColorBase& lrgb ) {\n        ColorBase<_Scalar> c( lrgb );\n        for ( auto& u : c.rgb() )\n        {\n            if ( u < 0.0031308_ra ) { u *= 12.92_ra; }\n            else\n            { u = 1.055_ra * std::pow( u, 1_ra / 2.4_ra ) - 0.055_ra; }\n        }\n        return c;\n    }\n\n    template <typename Derived>\n    static inline ColorBase fromRGB( const Eigen::MatrixBase<Derived>& rgb,\n                                     Scalar alpha = Scalar( 1. ) ) {\n        ColorBase c( rgb.template cast<_Scalar>().homogeneous() );\n        c.alpha() = alpha;\n        return c;\n    }\n\n    Eigen::Block<VectorType, 3, 1> rgb() { return ( *this ).template head<3>(); }\n    const Eigen::Block<VectorType, 3, 1> rgb() const { return ( *this ).template head<3>(); }\n\n    Scalar alpha() const { return ( *this )( 3 ); }\n    Scalar& alpha() { return ( *this )( 3 ); }\n    bool hasValidAlpha() const { return Math::checkRange( alpha(), 0_ra, 1_ra ); }\n\n    static inline ColorBase<_Scalar> Alpha() {\n        return ColorBase<_Scalar>( _Scalar( 0. ), _Scalar( 0. ), _Scalar( 0. ), _Scalar( 0. ) );\n    }\n\n    static inline ColorBase<_Scalar> Black() {\n        return ColorBase<_Scalar>( _Scalar( 0. ), _Scalar( 0. ), _Scalar( 0. ) );\n    }\n\n    static inline ColorBase<_Scalar> Red() {\n        return ColorBase<_Scalar>( _Scalar( 1. ), _Scalar( 0. ), _Scalar( 0. ) );\n    }\n\n    static inline ColorBase<_Scalar> Green() {\n        return ColorBase<_Scalar>( _Scalar( 0. ), _Scalar( 1. ), _Scalar( 0. ) );\n    }\n\n    static inline ColorBase<_Scalar> Blue() {\n        return ColorBase<_Scalar>( _Scalar( 0. ), _Scalar( 0. ), _Scalar( 1. ) );\n    }\n\n    static inline ColorBase<_Scalar> Yellow() {\n        return ColorBase<_Scalar>( _Scalar( 1. ), _Scalar( 1. ), _Scalar( 0. ) );\n    }\n\n    static inline ColorBase<_Scalar> Magenta() {\n        return ColorBase<_Scalar>( _Scalar( 1. ), _Scalar( 0. ), _Scalar( 1. ) );\n    }\n\n    static inline ColorBase<_Scalar> Cyan() {\n        return ColorBase<_Scalar>( _Scalar( 0. ), _Scalar( 1. ), _Scalar( 1. ) );\n    }\n\n    static inline ColorBase<_Scalar> White() {\n        return ColorBase<_Scalar>( _Scalar( 1. ), _Scalar( 1. ), _Scalar( 1. ) );\n    }\n\n    static inline ColorBase<_Scalar> Grey( _Scalar f = _Scalar( 0.5 ), _Scalar a = _Scalar( 1. ) ) {\n        return ColorBase<_Scalar>( f, f, f, a );\n    }\n\n    static inline ColorBase<_Scalar> Skin() {\n        return ColorBase<_Scalar>( _Scalar( 1.0 ), _Scalar( 0.87 ), _Scalar( 0.74 ) );\n    }\n    // Convert to/from various int formats\n\n    static inline ColorBase<_Scalar> fromChars( uchar r, uchar g, uchar b, uchar a = 0xff ) {\n        return ColorBase<_Scalar>( _Scalar( r ) / 255.0f,\n                                   _Scalar( g ) / 255.0f,\n                                   _Scalar( b ) / 255.0f,\n                                   _Scalar( a ) / 255.0f );\n    }\n\n    static inline ColorBase<_Scalar> fromRGBA32( uint32_t rgba ) {\n        uchar r = uchar( ( rgba >> 24 ) & 0xff );\n        uchar g = uchar( ( rgba >> 16 ) & 0xff );\n        uchar b = uchar( ( rgba >> 8 ) & 0xff );\n        uchar a = uchar( ( rgba >> 0 ) & 0xff );\n        return fromChars( r, g, b, a );\n    }\n\n    static inline ColorBase<_Scalar> fromARGB32( uint32_t argb ) {\n        uchar a = uchar( ( argb >> 24 ) & 0xff );\n        uchar r = uchar( ( argb >> 16 ) & 0xff );\n        uchar g = uchar( ( argb >> 8 ) & 0xff );\n        uchar b = uchar( ( argb >> 0 ) & 0xff );\n        return fromChars( r, g, b, a );\n    }\n\n    static inline ColorBase<_Scalar> fromHSV( const _Scalar hue,\n                                              const _Scalar saturation = 1.0,\n                                              const _Scalar value      = 1.0,\n                                              const _Scalar alpha      = 1.0 ) {\n        ColorBase<_Scalar> c;\n\n        if ( saturation == 0.0f )\n        {\n            c[0] = c[1] = c[2] = value;\n            c[3]               = alpha;\n            return c;\n        }\n        _Scalar h  = ( ( hue == 1.0f ) ? 0.0f : hue ) * 6.0f;\n        int i      = int( std::floor( h ) );\n        _Scalar v1 = value * ( 1.0f - saturation );\n        _Scalar v2 = value * ( 1.0f - ( saturation * ( h - i ) ) );\n        _Scalar v3 = value * ( 1.0f - ( saturation * ( 1.0f - h - i ) ) );\n        switch ( i )\n        {\n        case 0: {\n            c[0] = value;\n            c[1] = v3;\n            c[2] = v1;\n        }\n        break;\n        case 1: {\n            c[0] = v2;\n            c[1] = value;\n            c[2] = v1;\n        }\n        break;\n        case 2: {\n            c[0] = v1;\n            c[1] = value;\n            c[2] = v3;\n        }\n        break;\n        case 3: {\n            c[0] = v1;\n            c[1] = v2;\n            c[2] = value;\n        }\n        break;\n        case 4: {\n            c[0] = v3;\n            c[1] = v1;\n            c[2] = value;\n        }\n        break;\n        default: {\n            c[0] = value;\n            c[1] = v1;\n            c[2] = v2;\n        }\n        break;\n        }\n        c[3] = alpha;\n        return c;\n    }\n\n    inline uint32_t toRGBA32() const {\n        ColorBase<_Scalar> c( ( *this ) * 255 );\n        Eigen::Matrix<int, 4, 1> scaled( c.x(), c.y(), c.z(), c.w() );\n        return ( uint32_t( scaled( 0 ) ) << 24 ) | ( uint32_t( scaled( 1 ) ) << 16 ) |\n               ( uint32_t( scaled( 2 ) ) << 8 ) | ( uint32_t( scaled( 3 ) ) << 0 );\n    }\n\n    inline uint32_t toARGB32() const {\n        ColorBase<_Scalar> c( ( *this ) * 255 );\n        Eigen::Matrix<int, 4, 1> scaled( c.x(), c.y(), c.z(), c.w() );\n        return ( uint32_t( scaled( 3 ) ) << 24 ) | ( uint32_t( scaled( 0 ) ) << 16 ) |\n               ( uint32_t( scaled( 1 ) ) << 8 ) | ( uint32_t( scaled( 2 ) ) << 0 );\n    }\n\n    static inline std::vector<ColorBase<_Scalar>> scatter( const uint size, const _Scalar gamma ) {\n        std::vector<ColorBase<_Scalar>> color( size );\n        if ( size > 1 )\n            for ( uint i = 0; i < size; ++i )\n            {\n                color[i] = fromHSV( ( _Scalar( i ) / _Scalar( size - 1 ) ) * 0.777 );\n                color[i] = ( color[i] + ColorBase<_Scalar>::Constant( gamma ) ) * 0.5;\n            }\n        else\n        { color[0] = Red(); }\n        std::shuffle( color.begin(), color.end(), std::mt19937( std::random_device()() ) );\n        return color;\n    }\n};\n\nusing Color  = ColorBase<Scalar>;\nusing Colorf = ColorBase<float>;\nusing Colord = ColorBase<double>;\n\n} // namespace Utils\n} // namespace Core\n} // namespace Ra\n", "meta": {"hexsha": "624c52df00e14cd3256d6c5ba13c9de7efc2e9ca", "size": 8800, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/Utils/Color.hpp", "max_stars_repo_name": "Yasoo31/Radium-Engine", "max_stars_repo_head_hexsha": "e22754d0abe192207fd946509cbd63c4f9e52dd4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 78.0, "max_stars_repo_stars_event_min_datetime": "2017-12-01T12:23:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:08:09.000Z", "max_issues_repo_path": "src/Core/Utils/Color.hpp", "max_issues_repo_name": "Yasoo31/Radium-Engine", "max_issues_repo_head_hexsha": "e22754d0abe192207fd946509cbd63c4f9e52dd4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 527.0, "max_issues_repo_issues_event_min_datetime": "2017-09-25T13:05:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T18:47:44.000Z", "max_forks_repo_path": "src/Core/Utils/Color.hpp", "max_forks_repo_name": "Yasoo31/Radium-Engine", "max_forks_repo_head_hexsha": "e22754d0abe192207fd946509cbd63c4f9e52dd4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2018-01-04T22:08:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T08:13:41.000Z", "avg_line_length": 34.6456692913, "max_line_length": 100, "alphanum_fraction": 0.51375, "num_tokens": 2623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.43508811707267075}}
{"text": "/*=============================================================================\n\nPHAS0100ASSIGNMENT2: PHAS0100 Assignment 2 Gravitational N-body Simulation\n\nCopyright (c) University College London (UCL). All rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.\n\nSee LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include <CLI11.hpp>\n#include <nbsimBasicTypes.h>\n#include <nbsimMyFunctions.h>\n#include <nbsimExceptionMacro.h>\n#include <iostream>\n#include <string.h>\n#include <stdio.h>\n#include <ctime>\n#include <chrono>\n#include <omp.h>\n#include <iomanip>\n#include \"nbsimSolarSystemData.ipp\"\n\n// Example, header-only library, included in project for simplicity's sake.\n#include <Eigen/Dense>\n#include <unsupported/Eigen/NonLinearOptimization>\n\n#define YEAR2SEC 365*24*60*60\n/**\n * \\brief Demo file to check that includes and library linkage is correct.\n */\nint main(int argc, char** argv)\n{\n\n\tint returnStatus = EXIT_FAILURE;\n\tint ibody = 0;\n\tEigen::Vector3d pos, vel, r, rcom, p;\n\tdouble mass, mtotal;\n\tstd::shared_ptr<nbsim::MassiveParticle> planet[9];\n\tdouble ts = 0.0000274 * YEAR2SEC, dur = 1* YEAR2SEC;\n\n\n\tstd::string names[9];\n\tCLI::App app{\"Solar system simulator\"};\n\t//app.require_subcommand(1);\n\n\n\tCLI11_PARSE(app, argc, argv);\n\n\t/* Init planets */\n\tfor (int ibody=0; ibody <9; ibody++) {\n\t\t//std::cout << nbsim::solarSystemData[ibody].name << std::endl;\n\t\tnames[ibody] = nbsim::solarSystemData[ibody].name;\n\t\tmass = nbsim::solarSystemData[ibody].mu / GRAV;\n\t\tpos = nbsim::solarSystemData[ibody].position;\n\t\tvel = nbsim::solarSystemData[ibody].velocity;\n\t\tplanet[ibody] = std::make_shared<nbsim::MassiveParticle>(pos, vel, mass);\n\t}\n\t/* Add mutual attraction */\n\tfor (int i=0; i <9; i++) {\n\t\tfor (int j=0; j<9; j++) {\n\t\t\t//printf(\"Adding %d to %d\\n\", j, i);\n\t\t\tif (i != j) planet[i]->addAttractor(planet[j]);\n\t\t}\n\t}\n\n\t/* start timing */\n\tstd::clock_t c_start = std::clock();\n\tauto t_start = std::chrono::high_resolution_clock::now();\n\t/* simulate */\n\tfor (double t=0; t<dur; t+=ts) {\n#ifdef DEBUG\n\t\t{\n\t\t\t/* calculate rcom and ptotal */\n\t\t\trcom << 0,0,0;\n\t\t\tp << 0,0,0;\n\t\t\tmtotal = 0;\n\t\t\tfor (int i=0; i<9; i++) {\n\t\t\t\tmass = planet[i]->getMass();\n\t\t\t\trcom += mass * planet[i]->getPosition();\n\t\t\t\tp += mass * planet[i]->getVelocity();\n\t\t\t\tmtotal += mass;\n\t\t\t}\n\t\t\trcom = rcom / mtotal;\n\t\t\tstd::cout << \"rcom = \" << std::endl << rcom << std::endl\n\t\t\t\t<< \"ptotal = \" << std::endl << p <<std::endl\n\t\t\t\t<< \"mtotal = \" << mtotal << std::endl;\n\t\t}\n#endif\n#pragma omp parallel for\n\t\tfor (int i=0; i<9; i++) {\n\t\t\tplanet[i]->calculateAcceleration();\n\t\t}\n#pragma omp parallel for\n\t\tfor (int i=0; i<9; i++) {\n\t\t\tplanet[i]->integrateTimestep(ts);\n\t\t}\n\t}\n\t/* stop timing */\n    std::clock_t c_end = std::clock();\n    auto t_end = std::chrono::high_resolution_clock::now();\n \n\t/* output res */\n\tfor (int i=0; i<9; i++) {\n\t\tstd::cout << names[i] << std::endl;\n\t\tstd::cout << planet[i]->getPosition() << std::endl;\n\t}\n\t\t{\n\t\t\t/* calculate rcom and ptotal */\n\t\t\trcom << 0,0,0;\n\t\t\tp << 0,0,0;\n\t\t\tmtotal = 0;\n\t\t\tfor (int i=0; i<9; i++) {\n\t\t\t\tmass = planet[i]->getMass();\n\t\t\t\trcom += mass * planet[i]->getPosition();\n\t\t\t\tp += mass * planet[i]->getVelocity();\n\t\t\t\tmtotal += mass;\n\t\t\t}\n\t\t\trcom = rcom / mtotal;\n\t\t\tstd::cout << \"rcom = \" << std::endl << rcom << std::endl\n\t\t\t\t<< \"ptotal = \" << std::endl << p <<std::endl\n\t\t\t\t<< \"mtotal = \" << mtotal << std::endl;\n\t\t}\n\n    std::cout << std::fixed << std::setprecision(2) << \"CPU time used: \"\n              << 1000.0 * (c_end - c_start) / CLOCKS_PER_SEC / 1000 << \" s\\n\"\n              << \"Wall clock time passed: \"\n              << std::chrono::duration<double, std::milli>(t_end-t_start).count() / 1000\n              << \" s\\n\";\n\treturn 0;\n}\n", "meta": {"hexsha": "ceecfb1e9bab2b4369a41e012466ffb8f899d3aa", "size": 3867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/CommandLineApps/solarSystemSimulator.cpp", "max_stars_repo_name": "Tr0py/cpp-lean", "max_stars_repo_head_hexsha": "c35d2425736389fed8e45d39238dd696aba5485e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/CommandLineApps/solarSystemSimulator.cpp", "max_issues_repo_name": "Tr0py/cpp-lean", "max_issues_repo_head_hexsha": "c35d2425736389fed8e45d39238dd696aba5485e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/CommandLineApps/solarSystemSimulator.cpp", "max_forks_repo_name": "Tr0py/cpp-lean", "max_forks_repo_head_hexsha": "c35d2425736389fed8e45d39238dd696aba5485e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4338235294, "max_line_length": 88, "alphanum_fraction": 0.5924489268, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.43508811707267075}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.\n\n// This file was modified by Oracle on 2015.\n// Modifications copyright (c) 2015 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MATRIX_TRANSFORMERS_HPP\n#define BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MATRIX_TRANSFORMERS_HPP\n\n\n#include <cstddef>\n\n#include <boost/qvm/mat.hpp>\n#include <boost/qvm/vec.hpp>\n#include <boost/qvm/mat_access.hpp>\n#include <boost/qvm/vec_access.hpp>\n#include <boost/qvm/mat_operations.hpp>\n#include <boost/qvm/vec_mat_operations.hpp>\n#include <boost/qvm/map_mat_mat.hpp>\n#include <boost/qvm/map_mat_vec.hpp>\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/coordinate_promotion.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_coordinate_type.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace transform\n{\n\nnamespace detail { namespace matrix_transformer\n{\n\ntemplate\n<\n    typename Point,\n    std::size_t Dimension = 0,\n    std::size_t DimensionCount = geometry::dimension<Point>::value\n>\nstruct set_point_from_vec\n{\n    template <typename Vector>\n    static inline void apply(Point & p, Vector const& v)\n    {\n        typedef typename geometry::coordinate_type<Point>::type coord_t;\n        set<Dimension>(p, boost::numeric_cast<coord_t>(qvm::A<Dimension>(v)));\n        set_point_from_vec<Point, Dimension + 1, DimensionCount>::apply(p, v);\n    }\n};\n\ntemplate\n<\n    typename Point,\n    std::size_t DimensionCount\n>\nstruct set_point_from_vec<Point, DimensionCount, DimensionCount>\n{\n    template <typename Vector>\n    static inline void apply(Point &, Vector const&) {}\n};\n\ntemplate\n<\n    typename Point,\n    std::size_t Dimension = 0,\n    std::size_t DimensionCount = geometry::dimension<Point>::value\n>\nstruct set_vec_from_point\n{\n    template <typename Vector>\n    static inline void apply(Point const& p, Vector & v)\n    {\n        qvm::A<Dimension>(v) = get<Dimension>(p);\n        set_vec_from_point<Point, Dimension + 1, DimensionCount>::apply(p, v);\n    }\n};\n\ntemplate\n<\n    typename Point,\n    std::size_t DimensionCount\n>\nstruct set_vec_from_point<Point, DimensionCount, DimensionCount>\n{\n    template <typename Vector>\n    static inline void apply(Point const&, Vector &) {}\n};\n\ntemplate\n<\n    typename CalculationType,\n    std::size_t Dimension1,\n    std::size_t Dimension2\n>\nclass matrix_transformer\n{\nprotected :\n    typedef CalculationType ct;\n    typedef boost::qvm::mat<ct, Dimension2 + 1, Dimension1 + 1> matrix_type;\n    matrix_type m_matrix;\npublic :\n    matrix_type const& matrix() const { return m_matrix; }\n    template <typename P1, typename P2>\n    inline bool apply(P1 const& p1, P2& p2) const\n    {\n        assert_dimension_greater_equal<P1,Dimension1>();\n        assert_dimension_greater_equal<P2,Dimension2>();\n        qvm::vec<ct,Dimension1 + 1> p1temp;\n        qvm::A<Dimension1>(p1temp) = 1;\n        qvm::vec<ct,Dimension2 + 1> p2temp;\n        set_vec_from_point<P1, 0, Dimension1>::apply(p1, p1temp);\n        p2temp = m_matrix * p1temp;\n        set_point_from_vec<P2, 0, Dimension2>::apply(p2, p2temp);\n        return true;\n    }\n\n};\n\n}} // namespace detail::matrix_transform\n\n/*!\n\\brief Affine transformation strategy in Cartesian system.\n\\details The strategy serves as a generic definition of an affine transformation\n         matrix and procedure for applying it to a given point.\n\\see http://en.wikipedia.org/wiki/Affine_transformation\n     and http://www.devmaster.net/wiki/Transformation_matrices\n\\ingroup strategies\n\\tparam Dimension1 number of dimensions to transform from\n\\tparam Dimension2 number of dimensions to transform to\n */\ntemplate\n<\n    typename CalculationType,\n    std::size_t Dimension1,\n    std::size_t Dimension2\n>\nclass matrix_transformer : public detail::matrix_transformer::matrix_transformer<CalculationType, Dimension1, Dimension2>\n{\npublic:\n    template<typename Matrix>\n    inline matrix_transformer(Matrix const& matrix)\n    {\n        qvm::assign(this->m_matrix, matrix);\n    }\n    inline matrix_transformer() {}\n};\n\n\ntemplate <typename CalculationType>\nclass matrix_transformer<CalculationType, 2, 2> : public detail::matrix_transformer::matrix_transformer<CalculationType, 2, 2>\n{\n    typedef CalculationType ct;\npublic :\n    template<typename Matrix>\n    inline matrix_transformer(Matrix const& matrix)\n    {\n        qvm::assign(this->m_matrix, matrix);\n    }\n\n    inline matrix_transformer() {}\n\n    inline matrix_transformer(\n                ct const& m_0_0, ct const& m_0_1, ct const& m_0_2,\n                ct const& m_1_0, ct const& m_1_1, ct const& m_1_2,\n                ct const& m_2_0, ct const& m_2_1, ct const& m_2_2)\n    {\n        qvm::A<0,0>(this->m_matrix) = m_0_0;   qvm::A<0,1>(this->m_matrix) = m_0_1;   qvm::A<0,2>(this->m_matrix) = m_0_2;\n        qvm::A<1,0>(this->m_matrix) = m_1_0;   qvm::A<1,1>(this->m_matrix) = m_1_1;   qvm::A<1,2>(this->m_matrix) = m_1_2;\n        qvm::A<2,0>(this->m_matrix) = m_2_0;   qvm::A<2,1>(this->m_matrix) = m_2_1;   qvm::A<2,2>(this->m_matrix) = m_2_2;\n    }\n\n    template <typename P1, typename P2>\n    inline bool apply(P1 const& p1, P2& p2) const\n    {\n        assert_dimension_greater_equal<P1, 2>();\n        assert_dimension_greater_equal<P2, 2>();\n\n        ct const& c1 = get<0>(p1);\n        ct const& c2 = get<1>(p1);\n\n        typedef typename geometry::coordinate_type<P2>::type ct2;\n        set<0>(p2, boost::numeric_cast<ct2>(c1 * qvm::A<0,0>(this->m_matrix) + c2 * qvm::A<0,1>(this->m_matrix) + qvm::A<0,2>(this->m_matrix)));\n        set<1>(p2, boost::numeric_cast<ct2>(c1 * qvm::A<1,0>(this->m_matrix) + c2 * qvm::A<1,1>(this->m_matrix) + qvm::A<1,2>(this->m_matrix)));\n\n        return true;\n    }\n};\n\n\n// It IS possible to go from 3 to 2 coordinates\ntemplate <typename CalculationType>\nclass matrix_transformer<CalculationType, 3, 2> : public detail::matrix_transformer::matrix_transformer<CalculationType, 3, 2>\n{\n    typedef CalculationType ct;\npublic :\n    template<typename Matrix>\n    inline matrix_transformer(Matrix const& matrix)\n    {\n        qvm::assign(this->m_matrix, matrix);\n    }\n\n    inline matrix_transformer() {}\n\n    inline matrix_transformer(\n                ct const& m_0_0, ct const& m_0_1, ct const& m_0_2,\n                ct const& m_1_0, ct const& m_1_1, ct const& m_1_2,\n                ct const& m_2_0, ct const& m_2_1, ct const& m_2_2)\n    {\n        qvm::A<0,0>(this->m_matrix) = m_0_0;   qvm::A<0,1>(this->m_matrix) = m_0_1;   qvm::A<0,2>(this->m_matrix) = 0;   qvm::A<0,3>(this->m_matrix) = m_0_2;\n        qvm::A<1,0>(this->m_matrix) = m_1_0;   qvm::A<1,1>(this->m_matrix) = m_1_1;   qvm::A<1,2>(this->m_matrix) = 0;   qvm::A<1,3>(this->m_matrix) = m_1_2;\n        qvm::A<2,0>(this->m_matrix) = m_2_0;   qvm::A<2,1>(this->m_matrix) = m_2_1;   qvm::A<2,2>(this->m_matrix) = 0;   qvm::A<2,3>(this->m_matrix) = m_2_2;\n    }\n\n    template <typename P1, typename P2>\n    inline bool apply(P1 const& p1, P2& p2) const\n    {\n        assert_dimension_greater_equal<P1, 3>();\n        assert_dimension_greater_equal<P2, 2>();\n\n        ct const& c1 = get<0>(p1);\n        ct const& c2 = get<1>(p1);\n        ct const& c3 = get<2>(p1);\n\n        typedef typename geometry::coordinate_type<P2>::type ct2;\n\n        set<0>(p2, boost::numeric_cast<ct2>(\n            c1 * qvm::A<0,0>(this->m_matrix) + c2 * qvm::A<0,1>(this->m_matrix) + c3 * qvm::A<0,2>(this->m_matrix) + qvm::A<0,3>(this->m_matrix)));\n        set<1>(p2, boost::numeric_cast<ct2>(\n            c1 * qvm::A<1,0>(this->m_matrix) + c2 * qvm::A<1,1>(this->m_matrix) + c3 * qvm::A<1,2>(this->m_matrix) + qvm::A<1,3>(this->m_matrix)));\n\n        return true;\n    }\n\n};\n\n\ntemplate <typename CalculationType>\nclass matrix_transformer<CalculationType, 3, 3> : public detail::matrix_transformer::matrix_transformer<CalculationType, 3, 3>\n{\n    typedef CalculationType ct;\npublic :\n    template<typename Matrix>\n    inline matrix_transformer(Matrix const& matrix)\n    {\n        qvm::assign(this->m_matrix, matrix);\n    }\n\n    inline matrix_transformer() {}\n\n    inline matrix_transformer(\n                ct const& m_0_0, ct const& m_0_1, ct const& m_0_2, ct const& m_0_3,\n                ct const& m_1_0, ct const& m_1_1, ct const& m_1_2, ct const& m_1_3,\n                ct const& m_2_0, ct const& m_2_1, ct const& m_2_2, ct const& m_2_3,\n                ct const& m_3_0, ct const& m_3_1, ct const& m_3_2, ct const& m_3_3\n                )\n    {\n        qvm::A<0,0>(this->m_matrix) = m_0_0; qvm::A<0,1>(this->m_matrix) = m_0_1; qvm::A<0,2>(this->m_matrix) = m_0_2; qvm::A<0,3>(this->m_matrix) = m_0_3;\n        qvm::A<1,0>(this->m_matrix) = m_1_0; qvm::A<1,1>(this->m_matrix) = m_1_1; qvm::A<1,2>(this->m_matrix) = m_1_2; qvm::A<1,3>(this->m_matrix) = m_1_3;\n        qvm::A<2,0>(this->m_matrix) = m_2_0; qvm::A<2,1>(this->m_matrix) = m_2_1; qvm::A<2,2>(this->m_matrix) = m_2_2; qvm::A<2,3>(this->m_matrix) = m_2_3;\n        qvm::A<3,0>(this->m_matrix) = m_3_0; qvm::A<3,1>(this->m_matrix) = m_3_1; qvm::A<3,2>(this->m_matrix) = m_3_2; qvm::A<3,3>(this->m_matrix) = m_3_3;\n    }\n\n    template <typename P1, typename P2>\n    inline bool apply(P1 const& p1, P2& p2) const\n    {\n        assert_dimension_greater_equal<P1, 3>();\n        assert_dimension_greater_equal<P2, 3>();\n\n        ct const& c1 = get<0>(p1);\n        ct const& c2 = get<1>(p1);\n        ct const& c3 = get<2>(p1);\n\n        typedef typename geometry::coordinate_type<P2>::type ct2;\n\n        set<0>(p2, boost::numeric_cast<ct2>(\n            c1 * qvm::A<0,0>(this->m_matrix) + c2 * qvm::A<0,1>(this->m_matrix) + c3 * qvm::A<0,2>(this->m_matrix) + qvm::A<0,3>(this->m_matrix)));\n        set<1>(p2, boost::numeric_cast<ct2>(\n            c1 * qvm::A<1,0>(this->m_matrix) + c2 * qvm::A<1,1>(this->m_matrix) + c3 * qvm::A<1,2>(this->m_matrix) + qvm::A<1,3>(this->m_matrix)));\n        set<2>(p2, boost::numeric_cast<ct2>(\n            c1 * qvm::A<2,0>(this->m_matrix) + c2 * qvm::A<2,1>(this->m_matrix) + c3 * qvm::A<2,2>(this->m_matrix) + qvm::A<2,3>(this->m_matrix)));\n\n        return true;\n    }\n};\n\n\n/*!\n\\brief Strategy of translate transformation in Cartesian system.\n\\details Translate moves a geometry a fixed distance in 2 or 3 dimensions.\n\\see http://en.wikipedia.org/wiki/Translation_%28geometry%29\n\\ingroup strategies\n\\tparam Dimension1 number of dimensions to transform from\n\\tparam Dimension2 number of dimensions to transform to\n */\ntemplate\n<\n    typename CalculationType,\n    std::size_t Dimension1,\n    std::size_t Dimension2\n>\nclass translate_transformer\n{\n};\n\n\ntemplate<typename CalculationType>\nclass translate_transformer<CalculationType, 2, 2> : public matrix_transformer<CalculationType, 2, 2>\n{\npublic :\n    // To have translate transformers compatible for 2/3 dimensions, the\n    // constructor takes an optional third argument doing nothing.\n    inline translate_transformer(CalculationType const& translate_x,\n                CalculationType const& translate_y,\n                CalculationType const& = 0)\n        : matrix_transformer<CalculationType, 2, 2>(\n                1, 0, translate_x,\n                0, 1, translate_y,\n                0, 0, 1)\n    {}\n};\n\n\ntemplate <typename CalculationType>\nclass translate_transformer<CalculationType, 3, 3> : public matrix_transformer<CalculationType, 3, 3>\n{\npublic :\n    inline translate_transformer(CalculationType const& translate_x,\n                CalculationType const& translate_y,\n                CalculationType const& translate_z)\n        : matrix_transformer<CalculationType, 3, 3>(\n                1, 0, 0, translate_x,\n                0, 1, 0, translate_y,\n                0, 0, 1, translate_z,\n                0, 0, 0, 1)\n    {}\n\n};\n\n\n/*!\n\\brief Strategy of scale transformation in Cartesian system.\n\\details Scale scales a geometry up or down in all its dimensions.\n\\see http://en.wikipedia.org/wiki/Scaling_%28geometry%29\n\\ingroup strategies\n\\tparam Dimension1 number of dimensions to transform from\n\\tparam Dimension2 number of dimensions to transform to\n*/\ntemplate\n<\n    typename CalculationType,\n    std::size_t Dimension1,\n    std::size_t Dimension2\n>\nclass scale_transformer\n{\n};\n\ntemplate\n<\n    typename CalculationType,\n    std::size_t Dimension1\n>\nclass scale_transformer<CalculationType, Dimension1, Dimension1> : public matrix_transformer<CalculationType, Dimension1, Dimension1>\n{\npublic:\n    inline scale_transformer(CalculationType const& scale)\n    {\n        boost::qvm::set_identity(this->m_matrix);\n        this->m_matrix*=scale;\n        qvm::A<Dimension1,Dimension1>(this->m_matrix) = 1;\n    }\n};\n\ntemplate <typename CalculationType>\nclass scale_transformer<CalculationType, 2, 2> : public matrix_transformer<CalculationType, 2, 2>\n{\n\npublic :\n    inline scale_transformer(CalculationType const& scale_x,\n                CalculationType const& scale_y,\n                CalculationType const& = 0)\n        : matrix_transformer<CalculationType, 2, 2>(\n                scale_x, 0,       0,\n                0,       scale_y, 0,\n                0,       0,       1)\n    {}\n\n\n    inline scale_transformer(CalculationType const& scale)\n        : matrix_transformer<CalculationType, 2, 2>(\n                scale, 0,     0,\n                0,     scale, 0,\n                0,     0,     1)\n    {}\n};\n\n\ntemplate <typename CalculationType>\nclass scale_transformer<CalculationType, 3, 3> : public matrix_transformer<CalculationType, 3, 3>\n{\npublic :\n    inline scale_transformer(CalculationType const& scale_x,\n                CalculationType const& scale_y,\n                CalculationType const& scale_z)\n        : matrix_transformer<CalculationType, 3, 3>(\n                scale_x, 0,       0,       0,\n                0,       scale_y, 0,       0,\n                0,       0,       scale_z, 0,\n                0,       0,       0,       1)\n    {}\n\n\n    inline scale_transformer(CalculationType const& scale)\n        : matrix_transformer<CalculationType, 3, 3>(\n                scale, 0,     0,     0,\n                0,     scale, 0,     0,\n                0,     0,     scale, 0,\n                0,     0,     0,     1)\n    {}\n};\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\n\ntemplate <typename DegreeOrRadian>\nstruct as_radian\n{};\n\n\ntemplate <>\nstruct as_radian<radian>\n{\n    template <typename T>\n    static inline T get(T const& value)\n    {\n        return value;\n    }\n};\n\ntemplate <>\nstruct as_radian<degree>\n{\n    template <typename T>\n    static inline T get(T const& value)\n    {\n        typedef typename promote_floating_point<T>::type promoted_type;\n        return value * math::d2r<promoted_type>();\n    }\n\n};\n\n\ntemplate\n<\n    typename CalculationType,\n    std::size_t Dimension1,\n    std::size_t Dimension2\n>\nclass rad_rotate_transformer\n    : public transform::matrix_transformer<CalculationType, Dimension1, Dimension2>\n{\npublic :\n    inline rad_rotate_transformer(CalculationType const& angle)\n        : transform::matrix_transformer<CalculationType, Dimension1, Dimension2>(\n                 cos(angle), sin(angle), 0,\n                -sin(angle), cos(angle), 0,\n                 0,          0,          1)\n    {}\n};\n\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\n/*!\n\\brief Strategy for rotate transformation in Cartesian coordinate system.\n\\details Rotate rotates a geometry by a specified angle about a fixed point (e.g. origin).\n\\see http://en.wikipedia.org/wiki/Rotation_%28mathematics%29\n\\ingroup strategies\n\\tparam DegreeOrRadian degree/or/radian, type of rotation angle specification\n\\note A single angle is needed to specify a rotation in 2D.\n      Not yet in 3D, the 3D version requires special things to allow\n      for rotation around X, Y, Z or arbitrary axis.\n\\todo The 3D version will not compile.\n */\ntemplate\n<\n    typename DegreeOrRadian,\n    typename CalculationType,\n    std::size_t Dimension1,\n    std::size_t Dimension2\n>\nclass rotate_transformer : public detail::rad_rotate_transformer<CalculationType, Dimension1, Dimension2>\n{\n\npublic :\n    inline rotate_transformer(CalculationType const& angle)\n        : detail::rad_rotate_transformer\n            <\n                CalculationType, Dimension1, Dimension2\n            >(detail::as_radian<DegreeOrRadian>::get(angle))\n    {}\n};\n\n\n}} // namespace strategy::transform\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MATRIX_TRANSFORMERS_HPP\n", "meta": {"hexsha": "70f11b889be14f616c35b34c0b0d227c3a29f157", "size": 17062, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/strategies/transform/matrix_transformers.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "lib/boost_1.78.0/boost/geometry/strategies/transform/matrix_transformers.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "lib/boost_1.78.0/boost/geometry/strategies/transform/matrix_transformers.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 31.891588785, "max_line_length": 157, "alphanum_fraction": 0.6541437112, "num_tokens": 5046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.435073246973073}}
{"text": "#include \"hyperopt.h\"\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/max.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/min.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\n#include <boost/math/distributions/students_t.hpp>\n#include <cmath>\n#include <tbb/mutex.h>\n#include <tbb/parallel_for_each.h>\n#include <tbb/parallel_for.h>\n\n#include \"export.h\"\n#include \"ndarray_ops.h\"\n#include \"predict.h\"\n#include \"train.h\"\n#include \"utils.h\"\n\nnamespace curfil {\n\nbool continueSearching(const std::vector<double>& currentBestLosses,\n        const std::vector<double>& currentRunLosses) {\n\n    static const size_t MIN_SAMPLES = 3;\n\n    if (currentBestLosses.empty()) {\n        CURFIL_INFO(\"current best is empty. continue searching\");\n        return true;\n    }\n\n    // we want a minimum of three samples\n    if (currentRunLosses.size() < MIN_SAMPLES) {\n        CURFIL_INFO(\"too few elements in current run: \" << currentRunLosses.size()\n                << \". continue searching\");\n        return true;\n    }\n\n    boost::accumulators::accumulator_set<double,\n            boost::accumulators::features<boost::accumulators::tag::max,\n                    boost::accumulators::tag::mean,\n                    boost::accumulators::tag::variance> > acc1;\n\n    boost::accumulators::accumulator_set<double,\n            boost::accumulators::features<boost::accumulators::tag::min,\n                    boost::accumulators::tag::mean,\n                    boost::accumulators::tag::variance> > acc2;\n\n    acc1 = std::for_each(currentBestLosses.begin(), currentBestLosses.end(), acc1);\n    acc2 = std::for_each(currentRunLosses.begin(), currentRunLosses.end(), acc2);\n\n    double worstCurrentBest = boost::accumulators::max(acc1);\n    double bestOfCurrentLosses = boost::accumulators::min(acc2);\n\n    // continue if any loss is at least as good as the worst loss of the currently best\n    if (bestOfCurrentLosses <= worstCurrentBest) {\n        CURFIL_INFO(\"best run of current parameters is at least as good as the worst run with the best parameters: \"\n                << bestOfCurrentLosses << \" <= \" << worstCurrentBest\n                << \". continue searching\");\n        return true;\n    }\n\n    // http://www.boost.org/doc/libs/1_53_0/libs/math/doc/sf_and_dist/html/math_toolkit/dist/stat_tut/weg/st_eg/two_sample_students_t.html\n\n    double Sm1 = boost::accumulators::mean(acc1);                 // Sm1 = Sample 1 Mean.\n    double variance1 = boost::accumulators::variance(acc1);\n    double Sd1 = std::sqrt(variance1);                            // Sd1 = Sample 1 Standard Deviation.\n    unsigned Sn1 = currentBestLosses.size();                      // Sn1 = Sample 1 Size.\n\n    double Sm2 = boost::accumulators::mean(acc2);                 // Sm2 = Sample 2 Mean.\n    double variance2 = boost::accumulators::variance(acc2);\n    double Sd2 = std::sqrt(variance2);                            // Sd2 = Sample 2 Standard Deviation.\n    unsigned Sn2 = currentRunLosses.size();                       // Sn2 = Sample 2 Size.\n    double alpha = 0.005;                                         // alpha = Significance Level.\n\n    // Degrees of freedom:\n    double v = Sn1 + Sn2 - 2;\n    // Pooled variance:\n    double sp = sqrt(((Sn1 - 1) * Sd1 * Sd1 + (Sn2 - 1) * Sd2 * Sd2) / v);\n    // t-statistic:\n    double t_stat = (Sm1 - Sm2) / (sp * sqrt(1.0 / Sn1 + 1.0 / Sn2));\n\n    boost::math::students_t dist(v);\n    double q = boost::math::cdf(boost::math::complement(dist, fabs(t_stat)));\n\n    CURFIL_INFO(\"Sm1: \" << Sm1 << \", Sd1: \" << Sd1 << \", Sn1: \" << Sn1);\n    CURFIL_INFO(\"Sm2: \" << Sm2 << \", Sd2: \" << Sd2 << \", Sn2: \" << Sn2);\n    CURFIL_INFO(\"q: \" << q << \", alpha: \" << alpha);\n\n    // continue if we reject hypothesis that sample 1 mean loss is less than sample 2 mean loss. then we do not know and need to continue searching\n    return (q > alpha);\n}\n\ndouble Result::getLoss() const {\n    double accuracy;\n    switch (lossFunctionType) {\n        case LossFunctionType::CLASS_ACCURACY:\n            accuracy = getClassAccuracy();\n            break;\n        case LossFunctionType::CLASS_ACCURACY_WITHOUT_VOID:\n            accuracy = getClassAccuracyWithoutVoid();\n            break;\n        case LossFunctionType::PIXEL_ACCURACY:\n            accuracy = getPixelAccuracy();\n            break;\n        case LossFunctionType::PIXEL_ACCURACY_WITHOUT_VOID:\n            accuracy = getPixelAccuracyWithoutVoid();\n            break;\n        default:\n            throw std::runtime_error(\"unknown type of loss function\");\n    }\n    assertProbability(accuracy);\n    return 1.0 - accuracy;\n}\n\nmongo::BSONObj Result::toBSON() const {\n\n    mongo::BSONObjBuilder o(256);\n    o << \"randomSeed\" << getRandomSeed();\n    o << \"loss\" << getLoss();\n    o << \"classAccuracy\" << getClassAccuracy();\n    o << \"classAccuracyWithoutVoid\" << getClassAccuracyWithoutVoid();\n    o << \"pixelAccuracy\" << getPixelAccuracy();\n    o << \"pixelAccuracyWithoutVoid\" << getPixelAccuracyWithoutVoid();\n\n    mongo::BSONArrayBuilder confusionMatrixArray;\n    for (size_t label = 0; label < confusionMatrix.getNumClasses(); label++) {\n        mongo::BSONArrayBuilder confusionMatrixRow;\n        for (size_t prediction = 0; prediction < confusionMatrix.getNumClasses(); prediction++) {\n            double probability = confusionMatrix(label, prediction);\n            confusionMatrixRow.append(probability);\n        }\n        confusionMatrixArray.append(confusionMatrixRow.arr());\n    }\n    o << \"confusionMatrix\" << confusionMatrixArray.arr();\n\n    return o.obj();\n}\n\nLossFunctionType HyperoptClient::parseLossFunction(const std::string& lossFunctionString) {\n    if (lossFunctionString == \"classAccuracy\") {\n        return LossFunctionType::CLASS_ACCURACY;\n    } else if (lossFunctionString == \"classAccuracyWithoutVoid\") {\n        return LossFunctionType::CLASS_ACCURACY_WITHOUT_VOID;\n    }\n    else if (lossFunctionString == \"pixelAccuracy\") {\n        return LossFunctionType::PIXEL_ACCURACY;\n    }\n    else if (lossFunctionString == \"pixelAccuracyWithoutVoid\") {\n        return LossFunctionType::PIXEL_ACCURACY_WITHOUT_VOID;\n    } else {\n        throw std::runtime_error(std::string(\"unknown type of loss function: \") + lossFunctionString);\n    }\n}\n\nconst Result HyperoptClient::test(const RandomForestImage& randomForest,\n        const std::vector<LabeledRGBDImage>& testImages) {\n\n    tbb::mutex totalMutex;\n    utils::Average averageAccuracy;\n    utils::Average averageAccuracyWithoutVoid;\n\n    std::vector<int> indices(testImages.size(), 0);\n    for (size_t i = 0; i < testImages.size(); i++) {\n        indices[i] = i;\n    }\n\n    const LabelType numClasses = randomForest.getNumClasses();\n\n    CURFIL_INFO(\"testing \" << testImages.size() << \" images with \" << static_cast<int>(numClasses) << \" classes\");\n\n    ConfusionMatrix totalConfusionMatrix(numClasses);\n\n    tbb::parallel_for_each(indices.begin(), indices.end(), [&](const int& i) {\n        const RGBDImage& image = testImages[i].getRGBDImage();\n        const LabelImage& groundTruth = testImages[i].getLabelImage();\n\n        LabelImage prediction = randomForest.predict(image);\n\n        tbb::mutex::scoped_lock lock(totalMutex);\n\n        ConfusionMatrix confusionMatrix;\n        double accuracy = calculatePixelAccuracy(prediction, groundTruth, true, &confusionMatrix);\n        double accuracyWithoutVoid = calculatePixelAccuracy(prediction, groundTruth, false);\n\n        totalConfusionMatrix += confusionMatrix;\n\n        averageAccuracy.addValue(accuracy);\n        averageAccuracyWithoutVoid.addValue(accuracyWithoutVoid);\n    });\n\n    tbb::mutex::scoped_lock lock(totalMutex);\n    double accuracy = averageAccuracy.getAverage();\n    double accuracyWithoutVoid = averageAccuracyWithoutVoid.getAverage();\n\n    CURFIL_INFO(\"accuracy (no void): \" << accuracy << \" (\" << accuracyWithoutVoid << \")\");\n\n    return Result(totalConfusionMatrix, accuracy, accuracyWithoutVoid, lossFunction);\n}\n\nRandomForestImage HyperoptClient::train(size_t trees,\n        const TrainingConfiguration& configuration,\n        const std::vector<LabeledRGBDImage>& trainImages) {\n\n    CURFIL_INFO(\"trees: \" << trees);\n    CURFIL_INFO(configuration);\n\n    // Train\n\n    RandomForestImage randomForest(trees, configuration);\n\n    // parallel training is not thoroughly tested yet\n    static const bool trainTreesSequentially = true;\n\n    utils::Timer trainTimer;\n    randomForest.train(trainImages, trainTreesSequentially);\n    trainTimer.stop();\n\n    CURFIL_INFO(\"training took \" << trainTimer.format(2) <<\n            \" (\" << std::setprecision(3) << trainTimer.getSeconds() / 60.0 << \" min)\");\n\n    mongo::BSONObjBuilder featureBuilder(64);\n    for (const auto& featureCount : randomForest.countFeatures()) {\n        featureBuilder.append(featureCount.first, static_cast<int>(featureCount.second));\n    }\n\n    mongo::BSONObjBuilder builder(64);\n    builder.append(\"training_time_millis\", trainTimer.getMilliseconds());\n    builder.append(\"featureCounts\", featureBuilder.obj());\n\n    log(1, builder.obj());\n\n    return randomForest;\n}\n\ndouble HyperoptClient::measureTrueLoss(unsigned int numTrees, TrainingConfiguration configuration,\n        const double histogramBias, double& variance) {\n\n    boost::accumulators::accumulator_set<double,\n            boost::accumulators::features<boost::accumulators::tag::mean,\n                    boost::accumulators::tag::variance> > acc;\n\n    static const size_t TRUE_LOSS_RUNS = 2;\n\n    CURFIL_INFO(\"measuring true loss\");\n\n    Sampler sampler(randomSeed, 1, 100000);\n\n    for (size_t run = 0; run < TRUE_LOSS_RUNS; run++) {\n\n        CURFIL_INFO(\"true loss run \" << (run + 1) << \"/\" << TRUE_LOSS_RUNS);\n\n        const int seedOfRun = sampler.getNext();\n\n        configuration.setRandomSeed(seedOfRun);\n\n        RandomForestImage forest = train(numTrees, configuration, allRGBDImages);\n        forest.normalizeHistograms(histogramBias);\n        Result result = test(forest, allTestImages);\n\n        result.setRandomSeed(seedOfRun);\n\n        CURFIL_INFO(result.getConfusionMatrix());\n\n        log(2, BSON(\"trueLossRun\" << static_cast<int>(run)\n                << \"result\" << result.toBSON()));\n\n        acc(result.getLoss());\n    }\n\n    variance = boost::accumulators::variance(acc);\n\n    double trueLoss = boost::accumulators::mean(acc);\n\n    CURFIL_INFO(\"true loss: \" << trueLoss);\n\n    return trueLoss;\n}\n\ndouble HyperoptClient::getAverageLossAndVariance(const std::vector<Result>& results, double& variance) {\n\n    boost::accumulators::accumulator_set<double,\n            boost::accumulators::features<boost::accumulators::tag::mean,\n                    boost::accumulators::tag::variance> > acc;\n\n    for (const Result& result : results) {\n        acc(result.getLoss());\n    }\n\n    variance = boost::accumulators::variance(acc);\n\n    return boost::accumulators::mean(acc);\n}\n\nvoid HyperoptClient::randomSplit(const int randomSeed, const double testRatio,\n        std::vector<LabeledRGBDImage>& trainImages,\n        std::vector<LabeledRGBDImage>& testImages) {\n\n    boost::mt19937 rng(randomSeed);\n    boost::uniform_real<> dist(0.0, 1.0);\n\n    trainImages.clear();\n    testImages.clear();\n\n    while (testImages.empty() || trainImages.empty()) {\n        for (const auto& image : allRGBDImages) {\n            double random = dist(rng);\n            if (random < testRatio) {\n                testImages.push_back(image);\n            } else {\n                trainImages.push_back(image);\n            }\n        }\n    }\n\n    CURFIL_INFO(\"random split of \" << testRatio <<\n            \". train images: \" << trainImages.size() <<\n            \", test images: \" << testImages.size());\n}\n\nvoid HyperoptClient::handle_task(const mongo::BSONObj& task) {\n    try {\n        CURFIL_INFO(\"got task object: \" << task.toString());\n\n        const unsigned int numTrees = getParameterDouble(task, \"numTrees\");\n        const unsigned int samplesPerImage = getParameterDouble(task, \"samplesPerImage\");\n        const unsigned int featureCount = getParameterDouble(task, \"featureCount\");\n        const unsigned int minSampleCount = getParameterDouble(task, \"minSampleCount\");\n        const int maxDepth = getParameterDouble(task, \"maxDepth\");\n        const uint16_t boxRadius = getParameterDouble(task, \"boxRadius\");\n        const uint16_t regionSize = getParameterDouble(task, \"regionSize\");\n        const uint16_t thresholds = getParameterDouble(task, \"thresholds\");\n        const double histogramBias = getParameterDouble(task, \"histogramBias\");\n        const AccelerationMode accelerationMode = AccelerationMode::GPU_ONLY;\n\n        std::vector<Result> results;\n\n        Sampler sampler(randomSeed, 1, 100000);\n\n        static const int RUNS = 5;\n        const double testRatio = 1.0 / RUNS;\n\n        std::vector<double> currentRunLosses;\n\n        for (int run = 0; run < RUNS; run++) {\n\n            CURFIL_INFO(\"starting run \" << (run + 1) << \"/\" << RUNS);\n\n            const int seedOfRun = sampler.getNext();\n\n            std::vector<LabeledRGBDImage> trainImages;\n            std::vector<LabeledRGBDImage> testImages;\n\n            randomSplit(seedOfRun, testRatio, trainImages, testImages);\n\n            unsigned int imageCacheSize = 0;\n            unsigned int maxSamplesPerBatch = 0;\n\n            determineImageCacheSizeAndSamplesPerBatch(trainImages, deviceIds, featureCount, thresholds,\n                    imageCacheSizeMB, imageCacheSize, maxSamplesPerBatch);\n\n            TrainingConfiguration configuration(seedOfRun, samplesPerImage, featureCount, minSampleCount, maxDepth,\n                    boxRadius, regionSize, thresholds, numThreads, maxImages, imageCacheSize, maxSamplesPerBatch,\n                    accelerationMode, useCIELab, useDepthFilling, deviceIds, subsamplingType, ignoredColors);\n\n            mongo::BSONObj msg = BSON(\"run\" << run\n                    << \"randomSeed\" << seedOfRun\n                    << \"numTrainImages\" << static_cast<int>(trainImages.size())\n                    << \"numTestImages\" << static_cast<int>(testImages.size()));\n\n            log(3, msg);\n            checkpoint();\n\n            RandomForestImage forest = train(numTrees, configuration, trainImages);\n            forest.normalizeHistograms(histogramBias);\n            Result result = test(forest, testImages);\n            result.setRandomSeed(seedOfRun);\n\n            results.push_back(result);\n\n            currentRunLosses.push_back(result.getLoss());\n\n            log(3, result.toBSON());\n            checkpoint();\n\n            mongo::BSONObj bestTask;\n            if (get_best_task(bestTask)) {\n\n                CURFIL_INFO(\"best task so far: \" << bestTask.getObjectField(\"result\").toString());\n\n                std::vector<double> currentBestLosses;\n\n                mongo::BSONElementSet values;\n                bestTask.getFieldsDotted(\"result.results.loss\", values);\n\n                for (const mongo::BSONElement& loss : values) {\n                    currentBestLosses.push_back(loss.Double());\n                }\n\n                if (!continueSearching(currentBestLosses, currentRunLosses)) {\n                    log(1, BSON(\"stopSearching\" << true\n                            << \"run\" << run\n                            << \"currentBestLosses\" << currentBestLosses\n                            << \"currentRunLosses\" << currentRunLosses ));\n                    CURFIL_INFO(\"stop searching\");\n                    break;\n                } else {\n                    CURFIL_INFO(\"continue searching\");\n                }\n            } else {\n                CURFIL_INFO(\"no finished task so far\");\n            }\n\n        }\n\n        double lossVariance;\n        double loss = getAverageLossAndVariance(results, lossVariance);\n\n        unsigned int imageCacheSize = 0;\n        unsigned int maxSamplesPerBatch = 0;\n\n        determineImageCacheSizeAndSamplesPerBatch(allRGBDImages, deviceIds, featureCount, thresholds,\n                imageCacheSizeMB, imageCacheSize, maxSamplesPerBatch);\n\n        TrainingConfiguration configuration(randomSeed, samplesPerImage, featureCount, minSampleCount, maxDepth,\n                boxRadius, regionSize, thresholds, numThreads, maxImages, imageCacheSize, maxSamplesPerBatch,\n                accelerationMode, useCIELab, useDepthFilling, deviceIds, subsamplingType, ignoredColors);\n\n        double trueLossVariance;\n        double trueLoss = measureTrueLoss(numTrees, configuration, histogramBias, trueLossVariance);\n\n        mongo::BSONObjBuilder builder(64);\n\n        builder << \"status\" << \"ok\";\n        builder << \"loss\" << loss << \"loss_variance\" << lossVariance;\n        builder << \"true_loss\" << trueLoss << \"true_loss_variance\" << trueLossVariance;\n\n        std::vector<mongo::BSONObj> resultsDetails;\n        for (size_t i = 0; i < results.size(); i++) {\n            resultsDetails.push_back(results[i].toBSON());\n        }\n\n        builder.append(\"results\", resultsDetails);\n\n        finish(builder.obj(), true);\n\n    } catch (const std::runtime_error& e) {\n        CURFIL_ERROR(e.what());\n        finish(BSON(\"status\" << \"fail\" << \"why\" << e.what()), false);\n        throw e;\n    }\n\n}\n\ndouble HyperoptClient::getParameterDouble(const mongo::BSONObj& task, const std::string& field) {\n    const mongo::BSONObj vals = task.getObjectField(\"vals\");\n    if (!vals.hasField(field.c_str())) {\n        throw std::runtime_error(task.toString() + \" has no value '\" + field + \"'\");\n    }\n    const mongo::BSONElement value = vals.getField(field);\n    const std::vector<mongo::BSONElement> a = value.Array();\n    return a.at(0).Double();\n}\n\nvoid HyperoptClient::run() {\n\n    mongo::BSONObj result;\n    if (get_best_task(result)) {\n        CURFIL_INFO(\"best result so far: \" << result[\"result\"].toString());\n    } else {\n        CURFIL_INFO(\"no best result so far\");\n    }\n\n    CURFIL_INFO(\"running client\");\n    bool log_when_waiting = true;\n    while (true) {\n        mongo::BSONObj task;\n        if (!get_next_task(task)) {\n            if (log_when_waiting)\n                CURFIL_INFO(\"no task in queue. waiting...\");\n            log_when_waiting = false;\n            sleep(1);\n        } else {\n            handle_task(task);\n            log_when_waiting = true;\n        }\n    }\n}\n\n}\n", "meta": {"hexsha": "73de932ee19aab24979dbdfc63e2a0411ca320a3", "size": 18229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/curfil/hyperopt.cpp", "max_stars_repo_name": "amueller/curfil", "max_stars_repo_head_hexsha": "47c97be43abe62035f4da290276176f0120c0be0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-14T13:43:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-13T20:56:42.000Z", "max_issues_repo_path": "src/curfil/hyperopt.cpp", "max_issues_repo_name": "amueller/curfil", "max_issues_repo_head_hexsha": "47c97be43abe62035f4da290276176f0120c0be0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/curfil/hyperopt.cpp", "max_forks_repo_name": "amueller/curfil", "max_forks_repo_head_hexsha": "47c97be43abe62035f4da290276176f0120c0be0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1262729124, "max_line_length": 147, "alphanum_fraction": 0.6369521093, "num_tokens": 4210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.6001883592602051, "lm_q1q2_score": 0.43505870173506017}}
{"text": "#ifndef MATHTOOLBOX_ACQUISITION_FUNCTIONS_HPP\n#define MATHTOOLBOX_ACQUISITION_FUNCTIONS_HPP\n\n#include <Eigen/Core>\n#include <functional>\n\nnamespace mathtoolbox\n{\n    double GetExpectedImprovement(const Eigen::VectorXd&                               x,\n                                  const std::function<double(const Eigen::VectorXd&)>& mu,\n                                  const std::function<double(const Eigen::VectorXd&)>& sigma,\n                                  const Eigen::VectorXd&                               x_best);\n\n    Eigen::VectorXd\n    GetExpectedImprovementDerivative(const Eigen::VectorXd&                                        x,\n                                     const std::function<double(const Eigen::VectorXd&)>&          mu,\n                                     const std::function<double(const Eigen::VectorXd&)>&          sigma,\n                                     const Eigen::VectorXd&                                        x_best,\n                                     const std::function<Eigen::VectorXd(const Eigen::VectorXd&)>& mu_derivative,\n                                     const std::function<Eigen::VectorXd(const Eigen::VectorXd&)>& sigma_derivative);\n\n    /// \\param hyperparam The hyperparameter that controls the trade-off of exploration and exploitation. Specifically,\n    /// this hyperparameter corresponds to the square root of the beta in [Srinivas et al. ICML '10]. Setting this to\n    /// zero means pure exploitation, and setting to a very large value means (almost) pure exploration. This value\n    /// needs to be non-negative.\n    double GetGaussianProcessUpperConfidenceBound(const Eigen::VectorXd&                               x,\n                                                  const std::function<double(const Eigen::VectorXd&)>& mu,\n                                                  const std::function<double(const Eigen::VectorXd&)>& sigma,\n                                                  const double                                         hyperparam);\n\n    /// \\param hyperparam The hyperparameter that controls the trade-off of exploration and exploitation. Specifically,\n    /// this hyperparameter corresponds to the square root of the beta in [Srinivas et al. ICML '10]. Setting this to\n    /// zero means pure exploitation, and setting to a very large value means (almost) pure exploration. This value\n    /// needs to be non-negative.\n    Eigen::VectorXd GetGaussianProcessUpperConfidenceBoundDerivative(\n        const Eigen::VectorXd&                                        x,\n        const std::function<double(const Eigen::VectorXd&)>&          mu,\n        const std::function<double(const Eigen::VectorXd&)>&          sigma,\n        const double                                                  hyperparam,\n        const std::function<Eigen::VectorXd(const Eigen::VectorXd&)>& mu_derivative,\n        const std::function<Eigen::VectorXd(const Eigen::VectorXd&)>& sigma_derivative);\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_ACQUISITION_FUNCTIONS_HPP\n", "meta": {"hexsha": "b8c284ffe8b433e3b089ab4a995e8cd66fa3219a", "size": 3047, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/acquisition-functions.hpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "include/mathtoolbox/acquisition-functions.hpp", "max_issues_repo_name": "yuki-koyama/mathtoolbox", "max_issues_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "include/mathtoolbox/acquisition-functions.hpp", "max_forks_repo_name": "yuki-koyama/mathtoolbox", "max_forks_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 67.7111111111, "max_line_length": 119, "alphanum_fraction": 0.5628487036, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4350587017350601}}
{"text": "/*\n\nPICCANTE\nThe hottest HDR imaging library!\nhttp://vcg.isti.cnr.it/piccante\n\nCopyright (C) 2014\nVisual Computing Laboratory - ISTI CNR\nhttp://vcg.isti.cnr.it\nFirst author: Francesco Banterle\n\nThis Source Code Form is subject to the terms of the Mozilla Public\nLicense, v. 2.0. If a copy of the MPL was not distributed with this\nfile, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n*/\n\n#ifndef PIC_COMPUTER_VISION_FUNDAMENTAL_HPP\n#define PIC_COMPUTER_VISION_FUNDAMENTAL_HPP\n\n#include <vector>\n#include <random>\n#include <stdlib.h>\n\n#include \"../base.hpp\"\n\n#include \"../image.hpp\"\n\n#include \"../filtering/filter_luminance.hpp\"\n#include \"../filtering/filter_gaussian_2d.hpp\"\n\n#include \"../util/math.hpp\"\n#include \"../util/eigen_util.hpp\"\n\n#include \"../features_matching/orb_descriptor.hpp\"\n#include \"../features_matching/feature_matcher.hpp\"\n#include \"../features_matching/binary_feature_lsh_matcher.hpp\"\n#include \"../computer_vision/nelder_mead_opt_fundamental.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n#ifndef PIC_EIGEN_NOT_BUNDLED\n    #include \"../externals/Eigen/Dense\"\n    #include \"../externals/Eigen/SVD\"\n    #include \"../externals/Eigen/Geometry\"\n#else\n    #include <Eigen/Dense>\n    #include <Eigen/SVD>\n    #include <Eigen/Geometry>\n#endif\n\n#endif\n\nnamespace pic {\n\n#ifndef PIC_DISABLE_EIGEN\n\n/**\n * @brief estimateFundamental estimates the foundamental matrix between image 1 to image 2\n * @param points0 is an array of points computed from image 1.\n * @param points1 is an array of points computed from image 2.\n * @return It returns the fundamental matrix, F_{1,2}.\n */\nPIC_INLINE Eigen::Matrix3d estimateFundamental(std::vector< Eigen::Vector2f > &points0,\n                                    std::vector< Eigen::Vector2f > &points1)\n{\n    Eigen::Matrix3d F;\n\n    if((points0.size() != points1.size()) || (points0.size() < 8)) {\n        F.setZero();\n        return F;\n    }\n\n    //shift and scale points for numerical stability\n    Eigen::Vector3f transform_0 = ComputeNormalizationTransform(points0);\n    Eigen::Vector3f transform_1 = ComputeNormalizationTransform(points1);\n\n    Eigen::Matrix3d mat_0 = getShiftScaleMatrix(transform_0);\n    Eigen::Matrix3d mat_1 = getShiftScaleMatrix(transform_1);\n\n    Eigen::MatrixXd A(points0.size(), 9);\n\n    //set up the linear system\n    for(unsigned int i = 0; i < points0.size(); i++) {\n\n        //transform coordinates for increasing stability of the system\n        Eigen::Vector2f p0 = points0[i];\n        Eigen::Vector2f p1 = points1[i];\n\n        p0[0] = (p0[0] - transform_0[0]) / transform_0[2];\n        p0[1] = (p0[1] - transform_0[1]) / transform_0[2];\n\n        p1[0] = (p1[0] - transform_1[0]) / transform_1[2];\n        p1[1] = (p1[1] - transform_1[1]) / transform_1[2];\n\n        A(i, 0) = p0[0] * p1[0];\n        A(i, 1) = p0[0] * p1[1];\n        A(i, 2) = p0[0];\n        A(i, 3) = p0[1] * p1[0];\n        A(i, 4) = p0[1] * p1[1];\n        A(i, 5) = p0[1];\n        A(i, 6) = p1[0];\n        A(i, 7) = p1[1];\n        A(i, 8) = 1.0;\n    }\n\n    //solve the linear system\n    Eigen::JacobiSVD< Eigen::MatrixXd > svd(A, Eigen::ComputeFullV);\n    Eigen::MatrixXd V = svd.matrixV();\n\n    int n = int(V.cols()) - 1;\n\n    F(0, 0) = V(0, n);\n    F(1, 0) = V(1, n);\n    F(2, 0) = V(2, n);\n\n    F(0, 1) = V(3, n);\n    F(1, 1) = V(4, n);\n    F(2, 1) = V(5, n);\n\n    F(0, 2) = V(6, n);\n    F(1, 2) = V(7, n);\n    F(2, 2) = V(8, n);\n\n    //compute the final F matrix\n    Eigen::Matrix3d mat_1_t = Eigen::Transpose< Eigen::Matrix3d >(mat_1);\n    F = mat_1_t * F * mat_0;\n\n    //enforce singularity\n    Eigen::JacobiSVD< Eigen::MatrixXd > svdF(F, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Eigen::Matrix3d Uf = svdF.matrixU();\n    Eigen::Matrix3d Vf = svdF.matrixV();\n    Eigen::Vector3d Df = svdF.singularValues();\n    Df[2] = 0.0;\n\n    Eigen::Matrix3d F_new = Uf * DiagonalMatrix(Df) * Eigen::Transpose< Eigen::Matrix3d >(Vf);\n\n    double norm = MAX(Df[0], Df[1]);\n    return F_new / norm;\n}\n\n/**\n * @brief estimateFundamentalRansac\n * @param points0\n * @param points1\n * @param inliers\n * @param maxIterations\n * @return\n */\nPIC_INLINE Eigen::Matrix3d estimateFundamentalRansac(std::vector< Eigen::Vector2f > &points0,\n                                          std::vector< Eigen::Vector2f > &points1,\n                                          std::vector< unsigned int > &inliers,\n                                          unsigned int maxIterations = 100,\n                                          double threshold = 0.01,\n                                          unsigned int seed = 1)\n{\n    if(points0.size() < 9) {\n        return estimateFundamental(points0, points1);\n    }\n\n    Eigen::Matrix3d F;\n    int nSubSet = 8;\n\n    std::mt19937 m(seed);\n\n    unsigned int n = int(points0.size());\n\n    unsigned int *subSet = new unsigned int [nSubSet];\n\n    inliers.clear();\n\n    for(unsigned int i = 0; i < maxIterations; i++) {\n        getRandomPermutation(m, subSet, nSubSet, n);\n\n        std::vector< Eigen::Vector2f > sub_points0;\n        std::vector< Eigen::Vector2f > sub_points1;\n\n        for(int j = 0; j < nSubSet; j++) {\n            unsigned int k = subSet[j];\n            sub_points0.push_back(points0[k]);\n            sub_points1.push_back(points1[k]);\n        }\n\n        Eigen::Matrix3d tmpF = estimateFundamental(sub_points0, sub_points1);\n\n        //is it a good one?\n        std::vector< unsigned int > tmp_inliers;\n\n        for(unsigned int j = 0; j < n; j++) {\n            Eigen::Vector3d p0 = Eigen::Vector3d(points0[j][0], points0[j][1], 1.0);\n            Eigen::Vector3d p1 = Eigen::Vector3d(points1[j][0], points1[j][1], 1.0);\n\n            Eigen::Vector3d tmpF_p0 = tmpF * p0;\n            double n0 = sqrt(tmpF_p0[0] * tmpF_p0[0] + tmpF_p0[1] * tmpF_p0[1]);\n            if(n0 >  0.0) {\n                tmpF_p0 /= n0;\n            }\n\n            double err = fabs(tmpF_p0.dot(p1));\n\n            if(err < threshold){\n                tmp_inliers.push_back(j);\n            }\n        }\n\n        //get the inliers\n        if(tmp_inliers.size() > inliers.size()) {\n            F = tmpF;\n            inliers.clear();\n            inliers.assign(tmp_inliers.begin(), tmp_inliers.end());\n        }\n    }\n\n    //improve estimate with inliers only\n    if(inliers.size() > 7) {\n\n        #ifdef PIC_DEBUG\n            printf(\"Better estimate using inliers only.\\n\");\n        #endif\n\n        std::vector< Eigen::Vector2f > sub_points0;\n        std::vector< Eigen::Vector2f > sub_points1;\n\n        for(unsigned int i = 0; i < inliers.size(); i++) {\n            sub_points0.push_back(points0[inliers[i]]);\n            sub_points1.push_back(points1[inliers[i]]);\n        }\n\n        F = estimateFundamental(sub_points0, sub_points1);\n    }\n\n    return F;\n}\n    \n/**\n * @brief estimateFundamentalWithNonLinearRefinement\n * @param F\n * @return\n */\nPIC_INLINE Eigen::Matrix3d estimateFundamentalWithNonLinearRefinement(std::vector< Eigen::Vector2f > &points0,\n                                                           std::vector< Eigen::Vector2f > &points1,\n                                                           std::vector< unsigned int >    &inliers,\n                                                           unsigned int maxIterationsRansac = 100,\n                                                           double thresholdRansac = 0.01,\n                                                           unsigned int seed = 1,\n                                                           unsigned int maxIterationsNonLinear = 10000,\n                                                           float thresholdNonLinear = 1e-4f\n                                                           )\n{\n    Eigen::Matrix3d F = estimateFundamentalRansac(points0, points1, inliers, maxIterationsRansac, thresholdRansac, seed);\n\n    //non-linear refinement using Nelder-Mead\n    NelderMeadOptFundamental nmf(points0, points1, inliers);\n        \n    float F_data_opt[9];\n    nmf.run(getLinearArrayFromMatrix(F), 9, thresholdNonLinear, maxIterationsNonLinear, &F_data_opt[0]);\n    F = getMatrixdFromLinearArray(F_data_opt, 3, 3);\n\n    return F;\n}\n\n/**\n * @brief noramalizeFundamentalMatrix\n * @param F\n * @return\n */\nPIC_INLINE Eigen::Matrix3d noramalizeFundamentalMatrix(Eigen::Matrix3d F)\n{\n    Eigen::JacobiSVD< Eigen::Matrix3d > svdF(F, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Eigen::Matrix3d Uf = svdF.matrixU();\n    Eigen::Matrix3d Vf = svdF.matrixV();\n    Eigen::Vector3d Df = svdF.singularValues();\n    Df[2] = 0.0;\n\n    Eigen::Matrix3d F_new = Uf * DiagonalMatrix(Df) * Eigen::Transpose< Eigen::Matrix3d >(Vf);\n\n    double norm = MAX(Df[0], Df[1]);\n    return F_new / norm;\n}\n\n/**\n * @brief extractFundamentalMatrix\n * @param M0\n * @param M1\n * @param e0\n * @param e1\n * @return\n */\nPIC_INLINE Eigen::Matrix3d extractFundamentalMatrix(Eigen::Matrix34d &M0, Eigen::Matrix34d &M1, Eigen::VectorXd &e0, Eigen::VectorXd &e1) {\n\n    Eigen::Matrix3d M0_3 = getSquareMatrix(M0);\n    Eigen::Matrix3d M1_3 = getSquareMatrix(M1);\n\n\n    Eigen::Matrix3d M0_inv = M0_3.inverse();\n    Eigen::Vector3d c0 = - M0_inv * getLastColumn(M0);\n    e1 = M1 * addOne(c0);\n\n    Eigen::Matrix3d M1_inv = M1_3.inverse();\n    Eigen::Vector3d c1 = - M1_inv * getLastColumn(M1);\n    e0 = M0 * addOne(c1);\n\n    Eigen::Matrix3d F;\n\n    F(0, 0) =  0.0;\n    F(0, 1) = -e1(2);\n    F(0, 2) =  e1(1);\n\n    F(1, 0) =  e1(2);\n    F(1, 1) =  0.0;\n    F(1, 2) = -e1(0);\n\n    F(2, 0) = -e1(1);\n    F(2, 1) =  e1(0);\n    F(2, 2) =  0.0;\n\n    F = F * M1_3 * M0_inv;\n\n    Eigen::JacobiSVD< Eigen::Matrix3d > svdF(F, Eigen::ComputeThinU | Eigen::ComputeThinV);\n    Eigen::Vector3d Df = svdF.singularValues();\n\n    double norm = MAX(Df[0], MAX(Df[1], Df[2]));\n    return F / norm;\n}\n\n/**\n * @brief estimateFundamentalFromImages\n * @param img0\n * @param img1\n * @return\n */\nPIC_INLINE  Eigen::Matrix3d estimateFundamentalFromImages(Image *img0,\n                                                          Image *img1,\n                                                          std::vector< Eigen::Vector2f > &m0,\n                                                          std::vector< Eigen::Vector2f > &m1,\n                                                          std::vector< unsigned int > &inliers)\n{\n    Eigen::Matrix3d F;\n    if(img0 == NULL || img1 == NULL) {\n        return F;\n    }\n\n    m0.clear();\n    m1.clear();\n    inliers.clear();\n\n    //corners\n    std::vector< Eigen::Vector2f > corners_from_img0;\n    std::vector< Eigen::Vector2f > corners_from_img1;\n\n    //compute the luminance images\n    Image *L0 = FilterLuminance::execute(img0, NULL, LT_CIE_LUMINANCE);\n    Image *L1 = FilterLuminance::execute(img1, NULL, LT_CIE_LUMINANCE);\n\n    //extract corners\n    HarrisCornerDetector hcd(2.5f, 5);\n    hcd.execute(L0, &corners_from_img0);\n    hcd.execute(L1, &corners_from_img1);\n\n    //compute ORB descriptors for each corner and image\n\n    //apply a gaussian filter to luminance images\n    Image *L0_flt = FilterGaussian2D::execute(L0, NULL, 2.5f);\n    Image *L1_flt = FilterGaussian2D::execute(L1, NULL, 2.5f);\n\n    //compute ORB descriptor\n    ORBDescriptor b_desc(31, 512);\n\n    std::vector< unsigned int *> descs0;\n    b_desc.getAll(L0_flt, corners_from_img0, descs0);\n\n    std::vector< unsigned int *> descs1;\n    b_desc.getAll(L1_flt, corners_from_img1, descs1);\n\n    //match ORB descriptors\n    std::vector< Eigen::Vector3i > matches;\n    int n = b_desc.getDescriptorSize();\n\n    //BinaryFeatureBruteForceMatcher bffm_bin(&descs1, n);\n    BinaryFeatureLSHMatcher bffm_bin(&descs1, n, 64);\n    bffm_bin.getAllMatches(descs0, matches);\n\n    //get matches\n    FeatureMatcher<unsigned int>::filterMatches(corners_from_img0, corners_from_img1, matches, m0, m1);\n\n    //estimate the fundamental matrix\n    F = estimateFundamentalWithNonLinearRefinement(m0, m1, inliers, 1000, 0.5, 1, 1000, 1e-4f);\n\n    delete L0;\n    delete L1;\n    delete L0_flt;\n    delete L1_flt;\n\n    return F;\n}\n    \n#endif // PIC_DISABLE_EIGEN\n\n} // end namespace pic\n\n#endif // PIC_COMPUTER_VISION_FUNDAMENTAL_HPP\n", "meta": {"hexsha": "5cd91cdf37e5f24a277e3f380c46d0d2e1258a46", "size": 11996, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/computer_vision/fundamental_matrix.hpp", "max_stars_repo_name": "ecarpita93/HPC_projet_1", "max_stars_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/computer_vision/fundamental_matrix.hpp", "max_issues_repo_name": "ecarpita93/HPC_projet_1", "max_issues_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/computer_vision/fundamental_matrix.hpp", "max_forks_repo_name": "ecarpita93/HPC_projet_1", "max_forks_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8407960199, "max_line_length": 139, "alphanum_fraction": 0.5846948983, "num_tokens": 3553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4350587017350601}}
{"text": "// Software License Agreement (BSD-3-Clause)\n//\n// Copyright 2018 The University of North Carolina at Chapel Hill\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n//\n// 1. Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above\n//    copyright notice, this list of conditions and the following\n//    disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its\n//    contributors may be used to endorse or promote products derived\n//    from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n// OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//! @author Jeff Ichnowski\n\n#ifndef LINEAR_H\n#define LINEAR_H\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\nnamespace nao_cup {\n    template <typename S>\n    using Transform = Eigen::Transform<S, 3, Eigen::Isometry>;\n\n    template <typename S>\n    using Vec2 = Eigen::Matrix<S, 2, 1>;\n    template <typename S>\n    using Vec3 = Eigen::Matrix<S, 3, 1>;\n    template <typename S>\n    using Vec4 = Eigen::Matrix<S, 4, 1>;\n\n    template <typename S>\n    S v3_len(const Vec3<S> *v) { return v->norm(); }\n\n    template <typename S>\n    S v3_dot(const Vec3<S> *a, const Vec3<S> *b) {\n        return a->dot(*b);\n    }\n\n    template <typename S>\n    S v3_dist(const Vec3<S> *a, const Vec3<S> *b) {\n        return (*a - *b).norm();\n    }\n\n    template <typename S>\n    void v3_sub(Vec3<S>* r, const Vec3<S>* a, const Vec3<S>* b) { *r = *a - *b; }\n\n    template <typename S>\n    void v3_add(Vec3<S>* r, const Vec3<S>* a, const Vec3<S>* b) { *r = *a + *b; }\n\n    template <typename S>\n    void v3_scale(Vec3<S>* r, const Vec3<S> *v, S s) { *r = *v * s; }\n\n\n    template <typename S>\n    void m4_mul(\n        Transform<S>* r,\n        const Transform<S> *a,\n        const Transform<S> *b)\n    {\n        *r = *a * *b;\n    }\n\n    template <typename S>\n    void m4_rotate(\n        Transform<S> *m,\n        const Transform<S> *t,\n        S a, S x, S y, S z)\n    {\n        *m = *t * Eigen::AngleAxis<S>(a, Vec3<S>(x, y, z));\n    }\n\n    template <typename S>\n    void m4_translate(Transform<S> *m, const Transform<S> *t, S x, S y, S z) {\n        *m = *t * Eigen::Translation<S, 3>(x, y, z);\n    }\n\n    template <typename S>\n    void m4_transform_i3(Vec3<S> *r, const Transform<S> *m, S x, S y, S z) {\n        *r = *m * Vec3<S>(x, y, z);\n    }\n\n    template <typename S>\n    void m4_extract_translation(\n        Vec3<S>* r,\n        const Transform<S> *m)\n    {\n        *r = m->translation().template head<3>();\n    }\n\n    template <typename S>\n    void m4_transform_i(Vec4<S> *r, const Transform<S> *m, S x, S y, S z, S w) {\n        *r = *m * Vec4<S>(x, y, z, w);\n    }\n\n    template <typename S>\n    void m4_transform_i(Vec3<S>* r, const Transform<S> *m, S x, S y, S z) {\n        *r = *m * Vec3<S>(x, y, z);\n    }\n\n    template <typename S>\n    void v3_norm(Vec3<S> *r, const Vec3<S> *a) {\n        *r = a->normalized();\n    }\n\n    template <typename S>\n    S v3_dist_segment_point(const Vec3<S> *s0, const Vec3<S> *s1, const Vec3<S> *pt) {\n        Vec3<S> v, w;\n        S c1, c2, b;\n\n        v3_sub(&v, s1, s0);\n        v3_sub(&w, pt, s0);\n\n        c1 = v3_dot(&w, &v);\n        if (c1 <= 0.0) {\n            return v3_len(&w);\n        }\n\n        c2 = v3_dot(&v, &v);\n        if (c2 <= c1) {\n            return v3_dist(pt, s1);\n        }\n\n        b = c1 / c2;\n\n        v3_scale(&v, &v, b);\n        v3_add(&v, s0, &v);\n\n        return v3_dist(&v, pt);\n    }\n}\n\n#endif /* LINEAR_H */\n", "meta": {"hexsha": "3dce6b9e115dc7beb8c20d6086663ff5c5b3e9c7", "size": 4509, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "demo/nao_cup/src/linear.hpp", "max_stars_repo_name": "elishafer/mpt", "max_stars_repo_head_hexsha": "e0997259fbd1431bab4b5ffb6f0d2f00fa380660", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2018-09-28T17:28:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T20:30:32.000Z", "max_issues_repo_path": "demo/nao_cup/src/linear.hpp", "max_issues_repo_name": "elishafer/mpt", "max_issues_repo_head_hexsha": "e0997259fbd1431bab4b5ffb6f0d2f00fa380660", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-11-21T20:16:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-27T12:55:31.000Z", "max_forks_repo_path": "demo/nao_cup/src/linear.hpp", "max_forks_repo_name": "elishafer/mpt", "max_forks_repo_head_hexsha": "e0997259fbd1431bab4b5ffb6f0d2f00fa380660", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2019-05-15T00:18:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T00:41:37.000Z", "avg_line_length": 29.0903225806, "max_line_length": 86, "alphanum_fraction": 0.6025726325, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4350587017350601}}
{"text": "#include <iostream>\n#include <optional>\n#include <sstream>\n#include <stdexcept>\n\n#include <ceres/ceres.h>\n#include <gflags/gflags.h>\n#include <glog/logging.h>\n#include <Eigen/Dense>\n#include <boost/asio.hpp>\n\n#include \"farm_ng/calibration/align_sensor_rig.pb.h\"\n#include \"farm_ng/calibration/calibrate_multi_view_apriltag_rig.pb.h\"\n#include \"farm_ng/calibration/calibrate_multi_view_lidar.pb.h\"\n#include \"farm_ng/calibration/local_parameterization.h\"\n#include \"farm_ng/calibration/multi_view_apriltag_rig_calibrator.h\"\n#include \"farm_ng/calibration/multi_view_lidar_model.pb.h\"\n\n#include \"farm_ng/perception/apriltag.h\"\n#include \"farm_ng/perception/point_cloud.h\"\n\n#include \"farm_ng/core/blobstore.h\"\n#include \"farm_ng/core/event_log_reader.h\"\n#include \"farm_ng/core/init.h\"\n#include \"farm_ng/core/ipc.h\"\n\n#include \"farm_ng/perception/pose_utils.h\"\n#include \"farm_ng/perception/tensor.h\"\n\n#include \"farm_ng/perception/time_series.h\"\n\n#include <Eigen/Dense>\n\nDEFINE_string(result, \"aligned_sensor_rig.json\", \"Output path.\");\nDEFINE_string(output_config, \"\",\n              \"output a config json file to the given path.\");\nDEFINE_string(config, \"\", \"Load config from ajson file.\");\n\nDEFINE_string(multi_view_lidar_model, \"\",\n              \"Path to the multi_view_lidar_model to align\");\n\nDEFINE_int32(floor_tag, 313, \"A tag on the floor.\");\nDEFINE_double(floor_distance_threshold, 0.1,\n              \"Distance from floor to consider tags belonging to the floor.\");\n\nnamespace fs = boost::filesystem;\n\nnamespace farm_ng::calibration {\nEigen::Matrix3Xd ToMatrix(const std::vector<Eigen::Vector3d>& points) {\n  return Eigen::Map<const Eigen::Matrix3Xd>(points[0].data(), 3, points.size());\n}\nEigen::Hyperplane<double, 3> FitPlaneToPoints(const Eigen::Matrix3Xd& points) {\n  Eigen::Vector3d mean = points.rowwise().mean();\n  Eigen::Matrix3Xd points_centered = points.colwise() - mean;\n  auto svd =\n      points_centered.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeThinV);\n  Eigen::Vector3d normal = svd.matrixU().col(2);\n  LOG(INFO) << \"p=\" << mean.transpose() << \" n=\" << normal.transpose();\n  return Eigen::Hyperplane<double, 3>(normal, mean);\n}\n\n// based on https://github.com/nghiaho12/rigid_transform_3D/blob/master/rigid_transform_3D.py\n// http://nghiaho.com/?page_id=671\nSophus::SE3d FitAPoseB(const Eigen::Matrix3Xd& points_a,\n                       const Eigen::Matrix3Xd& points_b) {\n  Eigen::Vector3d mean_a = points_a.rowwise().mean();\n  Eigen::Vector3d mean_b = points_b.rowwise().mean();\n  Eigen::Matrix3Xd points_a_centered = points_a.colwise() - mean_a;\n  Eigen::Matrix3Xd points_b_centered = points_b.colwise() - mean_b;\n  Eigen::MatrixXd a_H_b = points_a_centered * points_b_centered.transpose();\n  auto svd = a_H_b.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Eigen::MatrixXd V = svd.matrixV();\n  Eigen::MatrixXd U = svd.matrixU();\n  Eigen::Matrix3d b_R_a = V * U.transpose();\n  if (b_R_a.determinant() < 0) {\n    V.col(2) *= -1;\n    b_R_a = V * U.transpose();\n    CHECK_GE(b_R_a.determinant(), 0);\n  }\n  Eigen::Matrix4d b_pose_a = Eigen::Matrix4d::Identity();\n  b_pose_a.block<3, 3>(0, 0) = b_R_a;\n  b_pose_a.block<3, 1>(0, 3) = mean_b - b_R_a * mean_a;\n  auto a_pose_b = Sophus::SE3d(b_pose_a).inverse();\n  return a_pose_b;\n}\n\nint align_sensor_rig(AlignSensorRigConfiguration config) {\n  CHECK_GT(config.floor_tag_ids_size(), 0);\n  MultiViewLidarModel lidar_model =\n      core::ReadProtobufFromResource<MultiViewLidarModel>(config.model());\n\n  perception::PoseGraph pose_graph;\n  for (const perception::ApriltagRig::Node& node :\n       lidar_model.apriltag_rig().nodes()) {\n    pose_graph.AddPose(node.pose());\n  }\n  std::string floor_tag_name = perception::FrameRigTag(\n      lidar_model.apriltag_rig().name(), config.floor_tag_ids(0));\n  perception::PoseGraph floor_tag_graph =\n      pose_graph.AveragePoseGraph(floor_tag_name);\n  double floor_distance_thresh = config.floor_distance_threshold();\n  std::vector<Eigen::Vector3d> floor_points_tag_rig;\n\n  for (const perception::ApriltagRig::Node& node :\n       lidar_model.apriltag_rig().nodes()) {\n    auto floor_tag_pose_tag =\n        floor_tag_graph.CheckAverageAPoseB(floor_tag_name, node.frame_name());\n    double err = 0;\n    auto points_tag = perception::PointsTag(node);\n    for (auto point_tag : points_tag) {\n      // LOG(INFO) << \"point_tag: \" << point_tag.transpose();\n      err = std::max(err, std::abs((floor_tag_pose_tag * point_tag).z()));\n    }\n    if (err < floor_distance_thresh) {\n      LOG(INFO) << node.frame_name() << \" on floor err: \" << err;\n      Sophus::SE3d tag_rig_pose_tag = ProtoToSophus(\n          node.pose(), lidar_model.apriltag_rig().name(), node.frame_name());\n      for (auto point_tag : points_tag) {\n        floor_points_tag_rig.push_back(tag_rig_pose_tag * point_tag);\n      }\n    } else {\n      // LOG(INFO) << node.frame_name() << \" err : \" << err;\n    }\n  }\n\n  std::vector<Eigen::Vector3d> points_camera_rig;\n\n  for (int i = 0; i < lidar_model.measurements_size(); ++i) {\n    const auto& m_i0 = lidar_model.measurements(i);\n    Sophus::SE3d camera_rig_pose_apriltag_rig = ProtoToSophus(\n        m_i0.camera_rig_pose_apriltag_rig(), lidar_model.camera_rig().name(),\n        lidar_model.apriltag_rig().name());\n    for (auto floor_point_tag_rig : floor_points_tag_rig) {\n      points_camera_rig.push_back(camera_rig_pose_apriltag_rig *\n                                  floor_point_tag_rig);\n    }\n  }\n  perception::PoseGraph sensor_rig_graph;\n  sensor_rig_graph.AddPoses(lidar_model.lidar_poses());\n  auto plane_camera_rig = FitPlaneToPoints(ToMatrix(points_camera_rig));\n  for (auto pose : lidar_model.lidar_poses()) {\n    auto sensor_name = pose.frame_b();\n    auto camera_rig_pose_sensor = sensor_rig_graph.CheckAverageAPoseB(\n        lidar_model.camera_rig().name(), sensor_name);\n    LOG(INFO) << \"sensor_name: \" << sensor_name << \" distance to ground: \"\n              << plane_camera_rig.signedDistance(\n                     camera_rig_pose_sensor.translation());\n  }\n\n  std::vector<Eigen::Vector3d> points_base;\n  std::vector<Eigen::Vector3d> points_rig;\n  Eigen::Hyperplane<double, 3> plane_base(Eigen::Vector3d(0, 0, 1.0),\n                                          Eigen::Vector3d(0, 0, 0));\n  for (auto pose : config.base_pose_sensor_measured()) {\n    Sophus::SE3d base_pose_sensor =\n        perception::ProtoToSophus(pose, config.base_frame(), pose.frame_b());\n    points_base.push_back(base_pose_sensor.translation());\n    points_base.push_back(\n        plane_base.projection(base_pose_sensor.translation()));\n\n    Sophus::SE3d rig_pose_sensor = sensor_rig_graph.CheckAverageAPoseB(\n        lidar_model.camera_rig().name(), pose.frame_b());\n    points_rig.push_back(rig_pose_sensor.translation());\n    points_rig.push_back(\n        plane_camera_rig.projection(rig_pose_sensor.translation()));\n  }\n  Sophus::SE3d base_pose_rig =\n      FitAPoseB(ToMatrix(points_base), ToMatrix(points_rig));\n  AlignSensorRigResult result;\n  result.set_base_frame(config.base_frame());\n  for (auto pose : lidar_model.lidar_poses()) {\n    auto sensor_name = pose.frame_b();\n    auto camera_rig_pose_sensor = sensor_rig_graph.CheckAverageAPoseB(\n        lidar_model.camera_rig().name(), sensor_name);\n    auto base_pose_sensor = base_pose_rig * camera_rig_pose_sensor;\n    perception::SophusToProto(base_pose_sensor, config.base_frame(),\n                              sensor_name, result.add_base_pose_sensor());\n    LOG(INFO) << result.base_pose_sensor(result.base_pose_sensor_size() - 1)\n                     .ShortDebugString();\n  }\n\n  farm_ng::core::WriteProtobufToJsonFile(FLAGS_result, result);\n\n  return 0;\n}\n\n}  // namespace farm_ng::calibration\n\nint main(int argc, char* argv[]) {\n  gflags::ParseCommandLineFlags(&argc, &argv, true);\n  FLAGS_logtostderr = 1;\n  std::string filename = boost::filesystem::path(argv[0]).filename().string();\n  google::InitGoogleLogging(filename.c_str());\n  farm_ng::calibration::AlignSensorRigConfiguration config;\n  if (!FLAGS_config.empty()) {\n    config = farm_ng::core::ReadProtobufFromJsonFile<\n        farm_ng::calibration::AlignSensorRigConfiguration>(FLAGS_config);\n  } else {\n    config.set_floor_distance_threshold(FLAGS_floor_distance_threshold);\n    config.add_floor_tag_ids(FLAGS_floor_tag);\n    config.mutable_model()->set_path(FLAGS_multi_view_lidar_model);\n    config.mutable_model()->set_content_type(\n        farm_ng::core::ContentTypeProtobufBinary<\n            farm_ng::calibration::MultiViewLidarModel>());\n  }\n  if (!FLAGS_output_config.empty()) {\n    farm_ng::core::WriteProtobufToJsonFile(FLAGS_output_config, config);\n    return 0;\n  }\n  return farm_ng::calibration::align_sensor_rig(config);\n}\n", "meta": {"hexsha": "efff60e8617c5f914f75f226f33eec7853888028", "size": 8670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/calibration/cpp/farm_ng/align_sensor_rig.cpp", "max_stars_repo_name": "greidy/tractor", "max_stars_repo_head_hexsha": "9bf2eab084fa422bf3627104be4542fc2ca2439d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T23:40:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T19:13:35.000Z", "max_issues_repo_path": "modules/calibration/cpp/farm_ng/align_sensor_rig.cpp", "max_issues_repo_name": "greidy/tractor", "max_issues_repo_head_hexsha": "9bf2eab084fa422bf3627104be4542fc2ca2439d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 151.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T08:56:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-13T05:58:01.000Z", "max_forks_repo_path": "modules/calibration/cpp/farm_ng/align_sensor_rig.cpp", "max_forks_repo_name": "greidy/tractor", "max_forks_repo_head_hexsha": "9bf2eab084fa422bf3627104be4542fc2ca2439d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T22:15:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T20:01:42.000Z", "avg_line_length": 40.8962264151, "max_line_length": 93, "alphanum_fraction": 0.7110726644, "num_tokens": 2296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143060406073, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.43503719069375096}}
{"text": "#include <algorithm>\n//#include <boost/iterator/counting_iterator.hpp>\n#include <ibs>\n#include <iterator>\n#include <math.h>\n#include <numeric>\n#include <vector>\n// gets the particle times and uses the phase acceptance and number of bins\n// to generate an integer which is than binned/histogram by\n// ParticleTimesToHistogram\nstruct ParticleTimesToInteger {\n  /*\n  0 -> tauahat = half the phase acceptance\n  1 -> nbins = numbers of bins to use in binning\n  2 -> t synchronous to shift the center of the distribution to zero for the\n  binning\n  */\n  int operator()(std::vector<double> &data, std::vector<double> &params) const {\n    double out;\n    double dtsamp2 = 2 * params[0] / params[1];\n    // std::printf(\"%-30s %12.8e\\n\", \"dtsamp2\", dtsamp2);\n    out = (data[4] - params[2] + params[0]) / dtsamp2;\n    // std::printf(\"%-30s %12.8e\\n\", \"data[4]\", data[4]);\n    // std::printf(\"%-30s %12.8e\\n\", \"out doub\", out);\n    out = (int)(out + 0.5);\n    // std::printf(\"%-30s %12.8e\\n\", \"out int\", out);\n    return out;\n  }\n};\n\nvoid denseHistogram(std::vector<int> data, std::vector<int> &histogram,\n                    int nbins, double tauhat) {\n  std::vector<int> input = data;\n  std::sort(input.begin(), input.end());\n\n  int numBins = nbins + 1;\n  histogram.resize(numBins);\n  for (int i = 0; i < numBins; i++) {\n    auto upper = std::upper_bound(input.begin(), input.end(), i);\n    histogram[i] = std::distance(input.begin(), upper);\n  }\n  /*\n    for (std::vector<int>::iterator i = histogram.begin(); i != histogram.end();\n         i++) {\n      std::printf(\"%12i\\n\", *i);\n    }\n  */\n  std::adjacent_difference(histogram.begin(), histogram.end(),\n                           histogram.begin());\n}\n\nstd::vector<int>\nParticlesTimesToHistogram(std::vector<std::vector<double>> &data, int nbins,\n                          double tauhat, double ts) {\n\n  int n = data.size();\n  std::vector<int> timecomponent(n);\n  std::vector<int> histogram;\n  std::vector<double> param;\n\n  param.push_back(tauhat);\n  param.push_back(nbins);\n  param.push_back(ts);\n  std::vector<std::vector<double>> p(n);\n  std::fill(p.begin(), p.end(), param);\n  /*\n  std::printf(\"%-30s %12.8e\\n\", \"tauhat\", tauhat);\n  std::printf(\"%-30s %12i\\n\", \"nbins\", nbins);\n  std::printf(\"%-30s %12.8e\\n\", \"ts\", ts);\n\n  for (std::vector<double>::iterator i = param.begin(); i != param.end(); i++) {\n    std::printf(\"%12.8e\\n\", *i);\n  }\n\n  // print out for debug\n  std::for_each(p.begin(), p.end(), [](std::vector<double> &particle) {\n    std::printf(\"%12.8e %12.8e %12.8e \\n\", particle[0], particle[1],\n                particle[2]);\n  });\n\n  std::printf(\"\\n\");\n*/\n  std::transform(data.begin(), data.end(), p.begin(), timecomponent.begin(),\n                 ParticleTimesToInteger());\n  /*\n    for (std::vector<int>::iterator i = timecomponent.begin();\n         i != timecomponent.end(); i++) {\n      std::printf(\"%12i\\n\", *i);\n    }\n    */\n  denseHistogram(timecomponent, histogram, nbins, tauhat);\n  /*\n  for (std::vector<int>::iterator i = histogram.begin(); i != histogram.end();\n       i++) {\n    std::printf(\"%3i\", *i);\n  };\n  std::printf(\"\\n\");\n  */\n  return histogram;\n}\n\n/*\n ********************************************************************************\n ********************************************************************************\n * REF:\n * https://stackoverflow.com/questions/14924912/computing-column-sums-of-matrix-vectorvectordouble-with-iterators\n ********************************************************************************\n */\nstd::vector<double> getColumnMeans(std::vector<std::vector<double>> &dist) {\n  std::vector<double> colsums(dist[0].size());\n\n  std::for_each(dist.begin(), dist.end(), [&](const std::vector<double> &row) {\n    std::transform(\n        row.begin(), row.end(), colsums.begin(), colsums.begin(),\n        [&](double d1, double d2) { return (d1 + d2) / dist.size(); });\n  });\n\n  return colsums;\n}\n\nstd::vector<double> vectorMultiply(std::vector<double> x,\n                                   std::vector<double> y) {\n  std::transform(x.begin(), x.end(), y.begin(), x.begin(),\n                 std::multiplies<double>());\n  return x;\n}\n\nstd::vector<double> vectorAdd(std::vector<double> x, std::vector<double> y) {\n  std::transform(x.begin(), x.end(), y.begin(), x.begin(), std::plus<double>());\n  return x;\n}\n\nstd::vector<double> vectorSub(std::vector<double> x, std::vector<double> y) {\n  std::transform(x.begin(), x.end(), y.begin(), x.begin(),\n                 std::minus<double>());\n  return x;\n}\nstd::vector<double> CalcRMS(std::vector<std::vector<double>> &dist) {\n  std::vector<double> avg = getColumnMeans(dist);\n\n  // for (std::vector<double>::const_iterator i = avg.begin(); i != avg.end();\n  // ++i)\n  //  std::printf(\"%-30s %12.8e\\n\", \"avg\", *i);\n\n  std::vector<std::vector<double>> avgarr(dist.size());\n  std::fill(avgarr.begin(), avgarr.end(), avg);\n\n  // std::for_each(avgarr.begin(), avgarr.end(), [](std::vector<double> &a) {\n  //  std::printf(\"%12.8e %12.8e %12.8e %12.8e %12.8e %12.8e\\n\", a[0], a[1],\n  //  a[2],\n  //              a[3], a[4], a[5]);\n  //});\n  std::vector<std::vector<double>> distcopy = dist;\n  std::transform(dist.begin(), dist.end(), avgarr.begin(), distcopy.begin(),\n                 vectorSub);\n  std::transform(distcopy.begin(), distcopy.end(), distcopy.begin(),\n                 distcopy.begin(), vectorMultiply);\n\n  std::vector<double> MS = getColumnMeans(distcopy);\n  std::transform(MS.begin(), MS.end(), MS.begin(), (double (*)(double))sqrt);\n\n  return MS;\n}\n\nstd::vector<double> HistogramToSQRTofCumul(std::vector<int> inputHistogram,\n                                           double coeff) {\n\n  /* The name is a badly chose here as it was originally used to calculate\n   * cumulated distributions which      */\n  /* turned out to be not necessary - the function takes a histogram as input,\n   * multiplies it with a constant  */\n  /* vector before taking the sqrt of each element. This produces a vector\n   * that is used in the IBSNew routine */\n  /* to multiply with particle momenta representing the IBS contribution */\n  int n = inputHistogram.size();\n\n  std::vector<double> vcoeff(n);\n  std::fill(vcoeff.begin(), vcoeff.end(), coeff);\n  /*\n  for (std::vector<double>::const_iterator i = vcoeff.begin();\n       i != vcoeff.end(); ++i)\n    std::printf(\"%-30s %12.8e\\n\", \"avg\", *i);\n    */\n  // fill constant vector\n\n  // multiply with constant\n  std::transform(inputHistogram.begin(), inputHistogram.end(), vcoeff.begin(),\n                 vcoeff.begin(), std::multiplies<double>());\n\n  // take sqrt\n  std::transform(vcoeff.begin(), vcoeff.end(), vcoeff.begin(),\n                 (double (*)(double))sqrt);\n\n  return vcoeff;\n}\n\nstd::map<std::string, double> readInput(std::string filename) {\n  std::vector<std::string> ALLOWEDKEYS{\n      \"bucket\",      \"atomNumber\", \"charge\",    \"nMacro\",\n      \"nReal\",       \"nbins\",      \"sigs\",      \"seed\",\n      \"ex\",          \"ey\",         \"timeRatio\", \"fracibstot\",\n      \"ibsCoupling\", \"model\",      \"nturns\",    \"nwrite\"};\n\n  std::map<std::string, double> out;\n  std::string line;\n  std::ifstream file(filename);\n\n  std::getline(file, line);\n\n  // check if file is open\n  if (file.is_open()) {\n    std::string key;\n    double value;\n    std::istringstream iss(line);\n    iss >> key >> value;\n\n    vector<string>::iterator it =\n        find(ALLOWEDKEYS.begin(), ALLOWEDKEYS.end(), key);\n    // cout << key << \" \" << value << \" \" << endl;\n    if (it != ALLOWEDKEYS.end()) {\n      out[key] = value;\n    }\n    while (!file.eof()) {\n      std::getline(file, line);\n      std::istringstream iss(line);\n      iss >> key >> value;\n\n      vector<string>::iterator it =\n          find(ALLOWEDKEYS.begin(), ALLOWEDKEYS.end(), key);\n      // cout << key << \" \" << value << \" \" << endl;\n      if (it != ALLOWEDKEYS.end()) {\n        out[key] = value;\n      }\n    }\n\n    file.close();\n  }\n  return out;\n}\n\nbool isInLong(std::vector<double> particle, double tauhat, double synctime) {\n  return !(abs(particle[4] - synctime) < tauhat);\n}", "meta": {"hexsha": "d281c4b70fc4252028964dcf9bf50d4b70c7951e", "size": 8014, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/utils.cpp", "max_stars_repo_name": "tomerten/ctelib", "max_stars_repo_head_hexsha": "582c215667e240a65f07ac75468e0870bee88a4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/utils.cpp", "max_issues_repo_name": "tomerten/ctelib", "max_issues_repo_head_hexsha": "582c215667e240a65f07ac75468e0870bee88a4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/utils.cpp", "max_forks_repo_name": "tomerten/ctelib", "max_forks_repo_head_hexsha": "582c215667e240a65f07ac75468e0870bee88a4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9794238683, "max_line_length": 113, "alphanum_fraction": 0.5716246569, "num_tokens": 2164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4350166339417342}}
{"text": "#include \"drake/solvers/fbstab/components/riccati_linear_solver.h\"\n\n#include <cmath>\n#include <iostream>\n#include <stdexcept>\n\n#include <Eigen/Dense>\n\n#include \"drake/solvers/fbstab/components/mpc_data.h\"\n#include \"drake/solvers/fbstab/components/mpc_residual.h\"\n#include \"drake/solvers/fbstab/components/mpc_variable.h\"\n\nnamespace drake {\nnamespace solvers {\nnamespace fbstab {\n\nusing VectorXd = Eigen::VectorXd;\nusing MatrixXd = Eigen::MatrixXd;\n\nRiccatiLinearSolver::RiccatiLinearSolver(int N, int nx, int nu, int nc) {\n  if (N <= 0 || nx <= 0 || nu <= 0 || nc <= 0) {\n    throw std::runtime_error(\n        \"In RiccatiLinearSolver::RiccatiLinearSolver: all inputs must be \"\n        \"positive.\");\n  }\n  N_ = N;\n  nx_ = nx;\n  nu_ = nu;\n  nc_ = nc;\n  nz_ = (N_ + 1) * (nx_ + nu_);\n  nl_ = (N_ + 1) * (nx_);\n  nv_ = (N_ + 1) * (nc_);\n\n  Q_.resize(N + 1);\n  S_.resize(N + 1);\n  R_.resize(N + 1);\n\n  P_.resize(N + 1);\n  SG_.resize(N + 1);\n  M_.resize(N + 1);\n  L_.resize(N + 1);\n  SM_.resize(N + 1);\n  AM_.resize(N + 1);\n\n  h_.resize(N + 1);\n  th_.resize(N + 1);\n\n  for (int i = 0; i < N + 1; i++) {\n    Q_[i].resize(nx, nx);\n    S_[i].resize(nu, nx);\n    R_[i].resize(nu, nu);\n\n    P_[i].resize(nx, nu);\n    SG_[i].resize(nu, nu);\n    M_[i].resize(nx, nx);\n    L_[i].resize(nx, nx);\n    SM_[i].resize(nu, nx);\n    AM_[i].resize(nx, nx);\n\n    h_[i].resize(nx);\n    th_[i].resize(nx);\n  }\n\n  gamma_.resize(nv_);\n  mus_.resize(nv_);\n  Gamma_.resize(nc, N + 1);\n\n  Etemp_.resize(nc, nx);\n  Ltemp_.resize(nc, nu);\n  Linv_.resize(nx, nx);\n\n  tx_.resize(nx);\n  tu_.resize(nu);\n  tl_.resize(nx);\n  r1_.resize(nz_);\n  r2_.resize(nl_);\n  r3_.resize(nv_);\n}\n\nbool RiccatiLinearSolver::Initialize(const MpcVariable& x,\n                                     const MpcVariable& xbar, double sigma) {\n  const MpcData* const data = x.data();\n  if (xbar.data_ != data) {\n    throw std::runtime_error(\n        \"In RiccatiLinearSolver::Initialize: x and xbar have mismatched \"\n        \"problem data.\");\n  }\n  if (!MpcVariable::SameSize(x, xbar)) {\n    throw std::runtime_error(\n        \"In RiccatiLinearSolver::Initialize: x and xbar are not the same \"\n        \"size.\");\n  }\n  if (sigma <= 0) {\n    throw std::runtime_error(\n        \"In RiccatiLinearSolver::Initialize: sigma must be positive.\");\n  }\n\n  Eigen::Vector2d temp;\n  for (int i = 0; i < nv_; i++) {\n    const double ys = x.y()(i) + sigma * (x.v()(i) - xbar.v()(i));\n    temp = PFBGradient(ys, x.v()(i));\n\n    gamma_(i) = temp(0);\n    mus_(i) = temp(1) + sigma * temp(0);\n    Gamma_(i) = gamma_(i) / mus_(i);\n  }\n  // Compute the barrier augmented Hessian.\n  for (int i = 0; i < N_ + 1; i++) {\n    const MatrixXd& Ei = (*data->E_)[i];\n    const MatrixXd& Li = (*data->L_)[i];\n\n    Q_[i].triangularView<Eigen::Lower>() =\n        (*data->Q_)[i] + sigma * MatrixXd::Identity(nx_, nx_);\n    R_[i].triangularView<Eigen::Lower>() =\n        (*data->R_)[i] + sigma * MatrixXd::Identity(nu_, nu_);\n    S_[i] = (*data->S_)[i];\n\n    // Add barriers associated with E(i)x(i) + L(i)u(i) + d(i) <=0\n    // Q(i) += E(i)'*diag(Gamma(i))*E(i)\n    Etemp_.noalias() = Gamma_.col(i).asDiagonal() * Ei;\n    Q_[i].triangularView<Eigen::Lower>() += Ei.transpose() * Etemp_;\n\n    // R(i) += L(i)'*diag(Gamma(i))*L(i)\n    Ltemp_.noalias() = Gamma_.col(i).asDiagonal() * Li;\n    R_[i].triangularView<Eigen::Lower>() += Li.transpose() * Ltemp_;\n\n    // S(i) += L(i) ' * diag(Gamma(i)) * E(i)\n    S_[i].noalias() += Li.transpose() * Etemp_;\n  }\n\n  // Begin the matrix potion of the Riccati recursion.\n  // Base case: L(0) = chol(sigma*I).\n  L_[0] = sqrt(sigma) * MatrixXd::Identity(nx_, nx_);\n\n#define FBSTAB_LLT_CHECK(llt)           \\\n  {                                     \\\n    if (llt.info() != Eigen::Success) { \\\n      return false;                     \\\n    }                                   \\\n  }\n\n  for (int i = 0; i < N_; i++) {\n    // Compute inv(L(i)) then\n    // compute QQ = Q+inv(L*L') = Q + inv(L)'*inv(L)\n    // and factor M = chol(QQ) in place.\n    Linv_ = MatrixXd::Identity(nx_, nx_);\n    L_[i].triangularView<Eigen::Lower>().solveInPlace(Linv_);\n    L_[i].triangularView<Eigen::Lower>().transpose().solveInPlace(Linv_);\n    M_[i].triangularView<Eigen::Lower>() = Q_[i] + Linv_;\n    Eigen::LLT<Eigen::Ref<MatrixXd>> llt1(M_[i]);\n    FBSTAB_LLT_CHECK(llt1);\n\n    // Compute AM = A*inv(M)'.\n    AM_[i] = (*data->A_)[i];\n    M_[i]\n        .triangularView<Eigen::Lower>()\n        .transpose()\n        .solveInPlace<Eigen::OnTheRight>(AM_[i]);\n\n    // Compute SM = S*inv(M)'.\n    SM_[i] = S_[i];\n    M_[i]\n        .triangularView<Eigen::Lower>()\n        .transpose()\n        .solveInPlace<Eigen::OnTheRight>(SM_[i]);\n\n    // Factor SG = chol(R - SM*SM') in place.\n    SG_[i].noalias() = R_[i] - SM_[i] * SM_[i].transpose();\n    Eigen::LLT<Eigen::Ref<MatrixXd>> llt2(SG_[i]);\n    FBSTAB_LLT_CHECK(llt2);\n\n    // Compute P = (A*inv(QQ)S' - B)*inv(SG)',\n    //           = (AM*SM' - B)*inv(SG)'.\n    P_[i].noalias() = AM_[i] * SM_[i].transpose();\n    P_[i] -= (*data->B_)[i];\n    SG_[i]\n        .triangularView<Eigen::Lower>()\n        .transpose()\n        .solveInPlace<Eigen::OnTheRight>(P_[i]);\n\n    // Compute L(i+1) = chol(Pi)\n    // where Pi = P*P' + AM*AM' + sigma I.\n    L_[i + 1] = sigma * MatrixXd::Identity(nx_, nx_);\n    L_[i + 1].noalias() += P_[i] * P_[i].transpose();\n    L_[i + 1].noalias() += AM_[i] * AM_[i].transpose();\n    Eigen::LLT<Eigen::Ref<MatrixXd>> llt3(L_[i + 1]);\n    FBSTAB_LLT_CHECK(llt3);\n  }\n\n  // Finish the recursion, i.e., perform the i = N step.\n  Linv_ = MatrixXd::Identity(nx_, nx_);\n  L_[N_].triangularView<Eigen::Lower>().solveInPlace(Linv_);\n  L_[N_].triangularView<Eigen::Lower>().transpose().solveInPlace(Linv_);\n\n  // Compute M = chol(Q + inv(L*L')).\n  M_[N_].triangularView<Eigen::Lower>() = Q_[N_] + Linv_;\n  Eigen::LLT<Eigen::Ref<MatrixXd>> llt4(M_[N_]);\n  FBSTAB_LLT_CHECK(llt4);\n\n  // Compute SM = S*inv(M)'.\n  SM_[N_] = S_[N_];\n  M_[N_]\n      .triangularView<Eigen::Lower>()\n      .transpose()\n      .solveInPlace<Eigen::OnTheRight>(SM_[N_]);\n\n  // Compute SG = chol(R - SM*SM').\n  SG_[N_].noalias() = R_[N_] - SM_[N_] * SM_[N_].transpose();\n  Eigen::LLT<Eigen::Ref<MatrixXd>> llt5(SG_[N_]);\n  FBSTAB_LLT_CHECK(llt5);\n\n#undef FBSTAB_LLT_CHECK\n  return true;\n}\n\nbool RiccatiLinearSolver::Solve(const MpcResidual& r, MpcVariable* dx) const {\n  const MpcData* const data = dx->data();\n  if (r.nz_ != dx->nz_ || r.nl_ != dx->nl_ || r.nv_ != dx->nv_) {\n    throw std::runtime_error(\n        \"In RiccatiLinearSolver::Solve: r and dx size mismatch.\");\n  }\n  // Compute the post-elimination residual,\n  // r1 = rz - A'*(rv./mus) and r2 = -rl.\n  r1_ = r.z_;\n  r3_ = r.v_.cwiseQuotient(mus_);  // r3_ is used as a temp here\n  data->gemvAT(r3_, -1.0, 1.0, &r1_);\n  r2_ = -r.l_;\n  // Get reshaped aliases for r1 and r2.\n  Eigen::Map<MatrixXd> r1(r1_.data(), nx_ + nu_, N_ + 1);\n  Eigen::Map<MatrixXd> r2(r2_.data(), nx_, N_ + 1);\n\n  // Begin the vector portion of the Riccati recursion.\n  // Base case: theta(0) = -rl(0), h(0) = inv(L*L')*theta(0) - rx(0).\n  th_[0] = r2.col(0);\n  h_[0] = th_[0];\n  L_[0].triangularView<Eigen::Lower>().solveInPlace(h_[0]);\n  L_[0].triangularView<Eigen::Lower>().transpose().solveInPlace(h_[0]);\n  h_[0].noalias() -= r1.block(0, 0, nx_, 1);  // r1(0) = [rx(0);ru(0)]\n\n  // Main loop:\n  for (int i = 0; i < N_; i++) {\n    // Compute theta(i+1).\n    // tx = inv(M)*h\n    tx_ = h_[i];\n    M_[i].triangularView<Eigen::Lower>().solveInPlace(tx_);\n\n    // tu = inv(SG)*(SM*tx + ru)\n    // r1(i) = [rx(i);ru(i)], block extracts ru(i)\n    tu_.noalias() = SM_[i] * tx_;\n    tu_.noalias() += r1.block(nx_, i, nu_, 1);\n    SG_[i].triangularView<Eigen::Lower>().solveInPlace(tu_);\n\n    const auto rlp = r2.col(i + 1);\n    th_[i + 1].noalias() = P_[i] * tu_ + AM_[i] * tx_;\n    th_[i + 1].noalias() += rlp;\n\n    // Compute h(i+1).\n    const auto rxp = r1.block(0, i + 1, nx_, 1);\n    h_[i + 1] = th_[i + 1];\n    L_[i + 1].triangularView<Eigen::Lower>().solveInPlace(h_[i + 1]);\n    L_[i + 1].triangularView<Eigen::Lower>().transpose().solveInPlace(\n        h_[i + 1]);\n    h_[i + 1].noalias() -= rxp;\n  }\n\n  // Begin the backwards recursion for the solution\n  // by computing xN,uN, and lN.\n  // u(N) = inv(SG*SG')*(SM*inv(M)*h + ru)\n  tx_ = h_[N_];\n  M_[N_].triangularView<Eigen::Lower>().solveInPlace(tx_);\n  tu_.noalias() = SM_[N_] * tx_;\n  tu_ += r1.block(nx_, N_, nu_, 1);\n  SG_[N_].triangularView<Eigen::Lower>().solveInPlace(tu_);\n  SG_[N_].triangularView<Eigen::Lower>().transpose().solveInPlace(tu_);\n\n  // x(N) = -inv(M')*(inv(M)*h + SM'*u(N))\n  tx_ = h_[N_];\n  M_[N_].triangularView<Eigen::Lower>().solveInPlace(tx_);\n  tx_.noalias() += SM_[N_].transpose() * tu_;\n  M_[N_].triangularView<Eigen::Lower>().transpose().solveInPlace(tx_);\n  tx_ *= -1.0;\n\n  // l(N) = -inv(L*L')* (xN + theta)\n  tl_ = tx_ + th_[N_];\n  L_[N_].triangularView<Eigen::Lower>().solveInPlace(tl_);\n  L_[N_].triangularView<Eigen::Lower>().transpose().solveInPlace(tl_);\n  tl_ *= -1.0;\n\n  // Copy these into the solution vector.\n  // Using reshaped aliases to make indexing easier.\n  Eigen::Map<MatrixXd> dz(dx->z_->data(), nx_ + nu_, N_ + 1);\n  Eigen::Map<MatrixXd> dl(dx->l_->data(), nx_, N_ + 1);\n\n  dz.block(0, N_, nx_, 1) = tx_;\n  dz.block(nx_, N_, nu_, 1) = tu_;\n  dl.col(N_) = tl_;\n\n  // The main backwards recursion loop.\n  for (int i = N_ - 1; i >= 0; i--) {\n    // Solve SG'*u(i) = inv(SG)*(SM*inv(M)*h + ru) + P'*l(i+1)\n    tx_ = h_[i];\n    M_[i].triangularView<Eigen::Lower>().solveInPlace(tx_);\n\n    // This is an alias.\n    auto ui = dz.block(nx_, i, nu_, 1);  // dz(i) = [xi;ui], extract ui\n    ui.noalias() = SM_[i] * tx_;\n    ui += r1.block(nx_, i, nu_, 1);  // SM*tx + ru\n    SG_[i].triangularView<Eigen::Lower>().solveInPlace(ui);\n    ui.noalias() += P_[i].transpose() * dl.col(i + 1);\n    SG_[i].triangularView<Eigen::Lower>().transpose().solveInPlace(ui);\n\n    // Solve -M'*x(i) = inv(M)*h + SM'*u(i) + AM'*l(i+1)\n    // This is an alias.\n    auto xi = dz.block(0, i, nx_, 1);\n\n    xi = h_[i];\n    M_[i].triangularView<Eigen::Lower>().solveInPlace(xi);\n    xi.noalias() += SM_[i].transpose() * ui;\n    xi.noalias() += AM_[i].transpose() * dl.col(i + 1);\n    M_[i].triangularView<Eigen::Lower>().transpose().solveInPlace(xi);\n    xi *= -1.0;\n\n    // Solve -L*L' * l(i) = theta(i) + x(i).\n    auto li = dl.col(i);\n    li = th_[i] + xi;\n    L_[i].triangularView<Eigen::Lower>().solveInPlace(li);\n    L_[i].triangularView<Eigen::Lower>().transpose().solveInPlace(li);\n    li *= -1.0;\n  }\n\n  // Recover the inequality duals by solving\n  // diag(mus)* dv = (rv + diag(gamma)*A*dz).\n  VectorXd& dv = dx->v();\n  dv = r.v_;\n  // r3_ = A*dz, r3_ is being used as a temp.\n  data->gemvA(dx->z(), 1.0, 0.0, &r3_);\n  dv += gamma_.asDiagonal() * r3_;\n  dv = dv.cwiseQuotient(mus_);\n\n  // Compute dy = b - A*dz.\n  VectorXd& dy = dx->y();\n  data->gemvA(dx->z(), -1.0, 0.0, &dy);\n  data->axpyb(1.0, &dy);\n\n  return true;\n}\n\nEigen::Vector2d RiccatiLinearSolver::PFBGradient(double a, double b) const {\n  const double r = sqrt(a * a + b * b);\n  const double d = 1.0 / sqrt(2.0);\n\n  Eigen::Vector2d v;\n  if (r < zero_tolerance_) {\n    v(0) = alpha_ * (1.0 - d);\n    v(1) = alpha_ * (1.0 - d);\n\n  } else if ((a > 0) && (b > 0)) {\n    v(0) = alpha_ * (1.0 - a / r) + (1.0 - alpha_) * b;\n    v(1) = alpha_ * (1.0 - b / r) + (1.0 - alpha_) * a;\n\n  } else {\n    v(0) = alpha_ * (1.0 - a / r);\n    v(1) = alpha_ * (1.0 - b / r);\n  }\n\n  return v;\n}\n\n}  // namespace fbstab\n}  // namespace solvers\n}  // namespace drake\n", "meta": {"hexsha": "3a844365b8c68cedb4c62876076be0ac5181204b", "size": 11476, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/fbstab/components/riccati_linear_solver.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "solvers/fbstab/components/riccati_linear_solver.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/fbstab/components/riccati_linear_solver.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 30.8494623656, "max_line_length": 78, "alphanum_fraction": 0.5641338445, "num_tokens": 4169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.43482845960607963}}
{"text": "#include <iostream>\n#include <cstdlib>\n#include <cstdio>\n#include <armadillo>\n#include <random>\n\n#include <mpi.h>\n\n#include \"transactions.hh\"\n#include \"histograms.hh\"\n\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char **argv) {\n  int mpiSize, mpiRank;\n\n  MPI_Init(&argc, &argv);\n  MPI_Comm_size(MPI_COMM_WORLD, &mpiSize);\n  MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank);\n\n  if(argc <= 6) {\n    if(mpiRank == 0) {\n      fprintf(stderr, \"Usage: %s OUTPUT-FILE NUM-AGENTS NUM-TRANSACTIONS NUM-RUNS INITIAL-MONEY [LAMBDA] [ALPHA] [S-FACTOR]\\n\", argv[0]);\n    }\n    MPI_Finalize();\n    exit(0);\n  }\n\n  // read parameters\n  const char *filename;\n  int N;      // number of agents\n  int K;      // number of transactions\n  int R;      // number of runs\n  double m0;  // initial money for each agent\n  double l;   // lambda parameter\n  double a;   // alpha parameter\n  double S;   // \"S-factor\", affects accuracy and slowness of simulations with α≠0 or γ≠0 (default: 1.0)\n  if(mpiRank == 0) {\n    // mandatory arguments\n    filename = argv[1];\n    N = atoi(argv[2]);\n    K = atoi(argv[3]);\n    R = atoi(argv[4]);\n    m0 = atof(argv[5]);\n\n    // optional arguments\n    l  = (argc > 6 ? atof(argv[6]) : 0.0);\n    a  = (argc > 7 ? atof(argv[7]) : 0.0);\n    S  = (argc > 8 ? atof(argv[8]) : 1.0);\n  }\n\n  if(mpiRank == 0) {\n    fprintf(stderr, \"Running with parameters:\\n\");\n    fprintf(stderr, \"  N = %d\\n\", N);\n    fprintf(stderr, \"  K = %d\\n\", K);\n    fprintf(stderr, \"  R = %d\\n\", R);\n    fprintf(stderr, \" m0 = %.3f\\n\", m0);\n    fprintf(stderr, \"  λ = %.3f\\n\", l);\n    fprintf(stderr, \"  α = %.3f\\n\", a);\n    fprintf(stderr, \"  S = %.1f\\n\", S);\n  }\n\n  // broadcast parameters to all nodes\n  MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD);\n  MPI_Bcast(&K, 1, MPI_INT, 0, MPI_COMM_WORLD);\n  MPI_Bcast(&R, 1, MPI_INT, 0, MPI_COMM_WORLD);\n  MPI_Bcast(&m0, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n  MPI_Bcast(&l, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n  MPI_Bcast(&a, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n  MPI_Bcast(&S, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\n  // reseed simulation with true random seed\n  // (so that the different processes don't make the exact same simulations)\n  seed_simulation();\n\n  // list of all agents after each run\n  vector<double> m(N * R, 1);\n\n  // find start and end indices for range of runs to be done\n  // by this process\n  size_t runsPerProcess = R / mpiSize;\n  size_t startRun = mpiRank * runsPerProcess;\n  size_t endRun = startRun + runsPerProcess;\n  if(endRun > R) endRun = R;\n  if(mpiRank == mpiSize - 1 && endRun < R) endRun = R;\n\n  // do all runs (parallelized)\n  for(size_t r = startRun; r < endRun; r++) {\n    // simulate transactions\n    // (store resulting money distribution in a subvector)\n    vector<double> m_dist = simulate_transactions(N, K, m0, l, S, a);\n\n    copy(begin(m_dist), end(m_dist), begin(m) + (r * N));\n  }\n\n  // send all data to process #0\n  double *mptr = m.data();\n  if(mpiRank == 0) {\n    for(int p = 1; p < mpiSize; p++) {\n      size_t pStartRun = p * runsPerProcess;\n      size_t pEndRun   = pStartRun + runsPerProcess;\n      if(pEndRun > R) pEndRun = R;\n      if(p == mpiSize - 1 && pEndRun < R) pEndRun = R;\n\n      MPI_Recv(&mptr[N * pStartRun], N * (pEndRun - pStartRun), MPI_DOUBLE, p, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n    }\n  } else {\n    MPI_Send(&mptr[N * startRun], N * (endRun - startRun), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);\n  }\n\n  // save histogram data to file (for plotting)\n  if(mpiRank == 0)\n    save_histogram(m, 0.01, filename);\n\n  MPI_Finalize();\n  return 0;\n}\n", "meta": {"hexsha": "4d78c0b00cc4a9018ba5a6c2de156cb0dd99cfa9", "size": 3536, "ext": "cc", "lang": "C++", "max_stars_repo_path": "project5/code/5d.cc", "max_stars_repo_name": "frxstrem/fys3150", "max_stars_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project5/code/5d.cc", "max_issues_repo_name": "frxstrem/fys3150", "max_issues_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project5/code/5d.cc", "max_forks_repo_name": "frxstrem/fys3150", "max_forks_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7142857143, "max_line_length": 137, "alphanum_fraction": 0.619061086, "num_tokens": 1152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.6825737473266735, "lm_q1q2_score": 0.4348204965509632}}
{"text": "#pragma once\n\n#include <string>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"../Config/config.hh\"\n#include \"../Math/math.hh\"\n\nnamespace bold\n{\n  typedef std::function<Eigen::Vector2d(Eigen::Vector3d const&)> Projector;\n\n  class CameraModel\n  {\n  public:\n    /// Initialises a CameraModel using parameters defined in configuration.\n    CameraModel()\n    : CameraModel(Config::getStaticValue<int>(\"camera.image-width\"),\n                  Config::getStaticValue<int>(\"camera.image-height\"),\n                  Config::getStaticValue<double>(\"camera.field-of-view.vertical-degrees\"),\n                  Config::getStaticValue<double>(\"camera.field-of-view.horizontal-degrees\"))\n    {}\n\n    /// Initialises a CameraModel using the specified parameters.\n    CameraModel(ushort imageWidth, ushort imageHeight, double rangeVerticalDegs, double rangeHorizontalDegs);\n\n    ushort imageWidth() const { return d_imageWidth; }\n    ushort imageHeight() const { return d_imageHeight; }\n\n    double focalLength() const { return d_focalLength; }\n    double rangeVerticalDegs() const { return d_rangeVerticalDegs; }\n    double rangeVerticalRads() const { return Math::degToRad(d_rangeVerticalDegs); }\n    double rangeHorizontalDegs() const { return d_rangeHorizontalDegs; }\n    double rangeHorizontalRads() const { return Math::degToRad(d_rangeHorizontalDegs); }\n\n    /** Gets the direction, in camera coordinates, of the specified pixel.\n     * Returns a unit vector.\n     */\n    Eigen::Vector3d directionForPixel(Eigen::Vector2d const& pixel) const;\n\n    Maybe<Eigen::Vector2d> pixelForDirection(Eigen::Vector3d const& direction) const;\n\n    /** Gets a projection matrix\n     *\n     * This matrix projects from camera frame onto image frame, up to\n     * a scaling factor, which is given in the z element of the\n     * transformed vector. i.e to get the pixel coordinate p of a\n     * point v with projection matrix T: p' = Tv, p = p'/p'_z.\n     */\n    Eigen::Affine3d getImageCameraTransform() const { return d_projectionTransform; }\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  private:\n    ushort d_imageWidth;\n    ushort d_imageHeight;\n    double d_focalLength;\n    double d_rangeVerticalDegs;\n    double d_rangeHorizontalDegs;\n    Eigen::Affine3d d_projectionTransform;\n  };\n}\n", "meta": {"hexsha": "7c091a1f1cde73c389896b79181c1c8c36fae16c", "size": 2274, "ext": "hh", "lang": "C++", "max_stars_repo_path": "CameraModel/cameramodel.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CameraModel/cameramodel.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CameraModel/cameramodel.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.53125, "max_line_length": 109, "alphanum_fraction": 0.7115215479, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.43473682042632683}}
{"text": "// Copyright (c) 2018, ETH Zurich and UNC Chapel Hill.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above copyright\n//       notice, this list of conditions and the following disclaimer in the\n//       documentation and/or other materials provided with the distribution.\n//\n//     * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of\n//       its contributors may be used to endorse or promote products derived\n//       from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de)\n\n#include \"base/polynomial.h\"\n\n#include <Eigen/Eigenvalues>\n\n#include \"util/logging.h\"\n\nnamespace colmap {\nnamespace {\n\n// Remove leading zero coefficients.\nEigen::VectorXd RemoveLeadingZeros(const Eigen::VectorXd& coeffs) {\n  Eigen::VectorXd::Index num_zeros = 0;\n  for (; num_zeros < coeffs.size(); ++num_zeros) {\n    if (coeffs(num_zeros) != 0) {\n      break;\n    }\n  }\n  return coeffs.tail(coeffs.size() - num_zeros);\n}\n\n// Remove trailing zero coefficients.\nEigen::VectorXd RemoveTrailingZeros(const Eigen::VectorXd& coeffs) {\n  Eigen::VectorXd::Index num_zeros = 0;\n  for (; num_zeros < coeffs.size(); ++num_zeros) {\n    if (coeffs(coeffs.size() - 1 - num_zeros) != 0) {\n      break;\n    }\n  }\n  return coeffs.head(coeffs.size() - num_zeros);\n}\n\n}  // namespace\n\nbool FindLinearPolynomialRoots(const Eigen::VectorXd& coeffs,\n                               Eigen::VectorXd* real, Eigen::VectorXd* imag) {\n  CHECK_EQ(coeffs.size(), 2);\n\n  if (coeffs(0) == 0) {\n    return false;\n  }\n\n  if (real != nullptr) {\n    real->resize(1);\n    (*real)(0) = -coeffs(1) / coeffs(0);\n  }\n\n  if (imag != nullptr) {\n    imag->resize(1);\n    (*imag)(0) = 0;\n  }\n\n  return true;\n}\n\nbool FindQuadraticPolynomialRoots(const Eigen::VectorXd& coeffs,\n                                  Eigen::VectorXd* real,\n                                  Eigen::VectorXd* imag) {\n  CHECK_EQ(coeffs.size(), 3);\n\n  const double a = coeffs(0);\n  if (a == 0) {\n    return FindLinearPolynomialRoots(coeffs.tail(2), real, imag);\n  }\n\n  const double b = coeffs(1);\n  const double c = coeffs(2);\n  if (b == 0 && c == 0) {\n    if (real != nullptr) {\n      real->resize(1);\n      (*real)(0) = 0;\n    }\n    if (imag != nullptr) {\n      imag->resize(1);\n      (*imag)(0) = 0;\n    }\n    return true;\n  }\n\n  const double d = b * b - 4 * a * c;\n\n  if (d >= 0) {\n    const double sqrt_d = std::sqrt(d);\n    if (real != nullptr) {\n      real->resize(2);\n      if (b >= 0) {\n        (*real)(0) = (-b - sqrt_d) / (2 * a);\n        (*real)(1) = (2 * c) / (-b - sqrt_d);\n      } else {\n        (*real)(0) = (2 * c) / (-b + sqrt_d);\n        (*real)(1) = (-b + sqrt_d) / (2 * a);\n      }\n    }\n    if (imag != nullptr) {\n      imag->resize(2);\n      imag->setZero();\n    }\n  } else {\n    if (real != nullptr) {\n      real->resize(2);\n      real->setConstant(-b / (2 * a));\n    }\n    if (imag != nullptr) {\n      imag->resize(2);\n      (*imag)(0) = std::sqrt(-d) / (2 * a);\n      (*imag)(1) = -(*imag)(0);\n    }\n  }\n\n  return true;\n}\n\nbool FindPolynomialRootsDurandKerner(const Eigen::VectorXd& coeffs_all,\n                                     Eigen::VectorXd* real,\n                                     Eigen::VectorXd* imag) {\n  CHECK_GE(coeffs_all.size(), 2);\n\n  const Eigen::VectorXd coeffs = RemoveLeadingZeros(coeffs_all);\n\n  const int degree = coeffs.size() - 1;\n\n  if (degree <= 0) {\n    return false;\n  } else if (degree == 1) {\n    return FindLinearPolynomialRoots(coeffs, real, imag);\n  } else if (degree == 2) {\n    return FindQuadraticPolynomialRoots(coeffs, real, imag);\n  }\n\n  // Initialize roots.\n  Eigen::VectorXcd roots(degree);\n  roots(degree - 1) = std::complex<double>(1, 0);\n  for (int i = degree - 2; i >= 0; --i) {\n    roots(i) = roots(i + 1) * std::complex<double>(1, 1);\n  }\n\n  // Iterative solver.\n  const int kMaxNumIterations = 100;\n  const double kMaxRootChange = 1e-10;\n  for (int iter = 0; iter < kMaxNumIterations; ++iter) {\n    double max_root_change = 0.0;\n    for (int i = 0; i < degree; ++i) {\n      const std::complex<double> root_i = roots(i);\n      std::complex<double> numerator = coeffs[0];\n      std::complex<double> denominator = coeffs[0];\n      for (int j = 0; j < degree; ++j) {\n        numerator = numerator * root_i + coeffs[j + 1];\n        if (i != j) {\n          denominator = denominator * (root_i - roots(j));\n        }\n      }\n      const std::complex<double> root_i_change = numerator / denominator;\n      roots(i) = root_i - root_i_change;\n      max_root_change =\n          std::max(max_root_change, std::abs(root_i_change.real()));\n      max_root_change =\n          std::max(max_root_change, std::abs(root_i_change.imag()));\n    }\n\n    // Break, if roots do not change anymore.\n    if (max_root_change < kMaxRootChange) {\n      break;\n    }\n  }\n\n  if (real != nullptr) {\n    real->resize(degree);\n    *real = roots.real();\n  }\n  if (imag != nullptr) {\n    imag->resize(degree);\n    *imag = roots.imag();\n  }\n\n  return true;\n}\n\nbool FindPolynomialRootsCompanionMatrix(const Eigen::VectorXd& coeffs_all,\n                                        Eigen::VectorXd* real,\n                                        Eigen::VectorXd* imag) {\n  CHECK_GE(coeffs_all.size(), 2);\n\n  Eigen::VectorXd coeffs = RemoveLeadingZeros(coeffs_all);\n\n  const int degree = coeffs.size() - 1;\n\n  if (degree <= 0) {\n    return false;\n  } else if (degree == 1) {\n    return FindLinearPolynomialRoots(coeffs, real, imag);\n  } else if (degree == 2) {\n    return FindQuadraticPolynomialRoots(coeffs, real, imag);\n  }\n\n  // Remove the coefficients where zero is a solution.\n  coeffs = RemoveTrailingZeros(coeffs);\n\n  // Check if only zero is a solution.\n  if (coeffs.size() == 1) {\n    if (real != nullptr) {\n      real->resize(1);\n      (*real)(0) = 0;\n    }\n    if (imag != nullptr) {\n      imag->resize(1);\n      (*imag)(0) = 0;\n    }\n    return true;\n  }\n\n  // Fill the companion matrix.\n  Eigen::MatrixXd C(coeffs.size() - 1, coeffs.size() - 1);\n  C.setZero();\n  for (Eigen::MatrixXd::Index i = 1; i < C.rows(); ++i) {\n    C(i, i - 1) = 1;\n  }\n  C.row(0) = -coeffs.tail(coeffs.size() - 1) / coeffs(0);\n\n  // Solve for the roots of the polynomial.\n  Eigen::EigenSolver<Eigen::MatrixXd> solver(C, false);\n  if (solver.info() != Eigen::Success) {\n    return false;\n  }\n\n  // If there are trailing zeros, we must add zero as a solution.\n  const int effective_degree =\n      coeffs.size() - 1 < degree ? coeffs.size() : coeffs.size() - 1;\n\n  if (real != nullptr) {\n    real->resize(effective_degree);\n    real->head(coeffs.size() - 1) = solver.eigenvalues().real();\n    if (effective_degree > coeffs.size() - 1) {\n      (*real)(real->size() - 1) = 0;\n    }\n  }\n  if (imag != nullptr) {\n    imag->resize(effective_degree);\n    imag->head(coeffs.size() - 1) = solver.eigenvalues().imag();\n    if (effective_degree > coeffs.size() - 1) {\n      (*imag)(imag->size() - 1) = 0;\n    }\n  }\n\n  return true;\n}\n\n\n\n// Stolen from PoseLib implementation\n/* Solves the quadratic equation a*x^2 + b*x + c = 0 */\ninline double sign(const double z) { return z < 0 ? -1.0 : 1.0; }\n\nint SolveQuadraticReal(double a, double b, double c, double roots[2]) {\n  double b2m4ac = b * b - 4 * a * c;\n  if (b2m4ac < 0) return 0;\n\n  double sq = std::sqrt(b2m4ac);\n\n  // Choose sign to avoid cancellations\n  roots[0] = (b > 0) ? (2 * c) / (-b - sq) : (2 * c) / (-b + sq);\n  roots[1] = c / (a * roots[0]);\n\n  return 2;\n}\nvoid SolveCubicRealSingleRoot(double c2, double c1, double c0, double& root) {\n  double a = c1 - c2 * c2 / 3.0;\n  double b = (2.0 * c2 * c2 * c2 - 9.0 * c2 * c1) / 27.0 + c0;\n  double c = b * b / 4.0 + a * a * a / 27.0;\n  if (c > 0) {\n    c = std::sqrt(c);\n    b *= -0.5;\n    root = std::cbrt(b + c) + std::cbrt(b - c) - c2 / 3.0;\n  } else {\n    c = 3.0 * b / (2.0 * a) * std::sqrt(-3.0 / a);\n    root = 2.0 * std::sqrt(-a / 3.0) * std::cos(std::acos(c) / 3.0) - c2 / 3.0;\n  }\n}\n/* Solves the quartic equation x^4 + b*x^3 + c*x^2 + d*x + e = 0 */\nint SolveQuarticReal(double b, double c, double d, double e, double roots[4]) {\n  // Find depressed quartic\n  double p = c - 3.0 * b * b / 8.0;\n  double q = b * b * b / 8.0 - 0.5 * b * c + d;\n  double r =\n      (-3.0 * b * b * b * b + 256.0 * e - 64.0 * b * d + 16.0 * b * b * c) /\n      256.0;\n\n  // Resolvent cubic is now\n  // U^3 + 2*p U^2 + (p^2 - 4*r) * U - q^2\n  double bb = 2.0 * p;\n  double cc = p * p - 4.0 * r;\n  double dd = -q * q;\n\n  // Solve resolvent cubic\n  double u2;\n  SolveCubicRealSingleRoot(bb, cc, dd, u2);\n\n  if (u2 < 0) return 0;\n\n  double u = sqrt(u2);\n\n  double s = -u;\n  double t = (p + u * u + q / u) / 2.0;\n  double v = (p + u * u - q / u) / 2.0;\n\n  int sols = 0;\n  double disc = u * u - 4.0 * v;\n  if (disc > 0) {\n    roots[0] = (-u - sign(u) * std::sqrt(disc)) / 2.0;\n    roots[1] = v / roots[0];\n    sols += 2;\n  }\n  disc = s * s - 4.0 * t;\n  if (disc > 0) {\n    roots[sols] = (-s - sign(s) * std::sqrt(disc)) / 2.0;\n    roots[sols + 1] = t / roots[sols];\n    sols += 2;\n  }\n\n  for (int i = 0; i < sols; i++) {\n    roots[i] = roots[i] - b / 4.0;\n\n    // do one step of newton refinement\n    double x = roots[i];\n    double x2 = x * x;\n    double x3 = x * x2;\n    double dx = -(x2 * x2 + b * x3 + c * x2 + d * x + e) /\n                (4.0 * x3 + 3.0 * b * x2 + 2.0 * c * x + d);\n    roots[i] = x + dx;\n  }\n  return sols;\n}\n\n}  // namespace colmap\n", "meta": {"hexsha": "0aa23eaa2431016b2f17e784957884ccd8a8312a", "size": 10476, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/base/polynomial.cc", "max_stars_repo_name": "vlarsson/radialsfm", "max_stars_repo_head_hexsha": "bd849f5f13faf93bd8d6a8e4c406be98ccec5884", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2020-12-14T11:53:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T16:44:21.000Z", "max_issues_repo_path": "src/base/polynomial.cc", "max_issues_repo_name": "xiaoteng-whu/radialsfm", "max_issues_repo_head_hexsha": "bd849f5f13faf93bd8d6a8e4c406be98ccec5884", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/base/polynomial.cc", "max_forks_repo_name": "xiaoteng-whu/radialsfm", "max_forks_repo_head_hexsha": "bd849f5f13faf93bd8d6a8e4c406be98ccec5884", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-12-15T01:39:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T08:19:57.000Z", "avg_line_length": 28.7802197802, "max_line_length": 79, "alphanum_fraction": 0.5721649485, "num_tokens": 3236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4347368056782702}}
{"text": "#ifndef EXPSUM_REDUCTION_CHOLESKY_CAUCHY_HPP\n#define EXPSUM_REDUCTION_CHOLESKY_CAUCHY_HPP\n\n#include <armadillo>\n#include <cassert>\n\nnamespace expsum\n{\n//\n// Rank-revealing Cholesky decomposition for a positive-definite quasi-Cauchy\n// matrix.\n//\n// This class computes the Cholesky decomposition of ``$n \\times n$``\n// quasi-Cauchy matrix defined as\n//\n// ``` math\n//  C_{ij} = \\frac{a_{i}^{} b_{j}^{}}{x_{i}^{} + y_{i}^{}}.\n// ```\n//\ntemplate <typename T>\nstruct cholesky_quasi_cauchy\n{\npublic:\n    using value_type = T;\n    using real_type  = typename arma::get_pod_type<T>::result;\n    using size_type  = arma::uword;\n\n    using vector_type      = arma::Col<value_type>;\n    using matrix_type      = arma::Mat<value_type>;\n    using real_vector_type = arma::Col<real_type>;\n    //\n    // Pre-compute pivot order for the Cholesky factorization of Cauchy matrix.\n    //\n    static size_type pivot_order(vector_type& a, vector_type& b, vector_type& x,\n                                 vector_type& y, real_type delta,\n                                 arma::uvec& ipiv, vector_type& g);\n    //\n    // Compute Cholesky factors (`X` and diagonal part of `D`).\n    //\n    // The arrays `a,b,x,y` must be properly reordered by calling `pivot_order`\n    // beforehand, so that the diagonal part of Cholesky factors appear in\n    // decesnding order.\n    //\n    // @a vector of length ``$n$`` defining quasi-Cauchy matrix (reordered)\n    // @b vector of length ``$n$`` defining quasi-Cauchy matrix (reordered)\n    // @x vector of length ``$n$`` defining quasi-Cauchy matrix (reordered)\n    // @y vector of length ``$n$`` defining quasi-Cauchy matrix (reordered)\n    // @L Cholesky factor (lower triangular matrix)\n    // @d diagonal elements of Cholesky factor ``$D$``\n    // @alpha vector of length ``$n$`` as working space\n    // @beta  vector of length ``$n$`` as working space\n    //\n    static void factorize(const vector_type& a, const vector_type& b,\n                          const vector_type& x, const vector_type& y,\n                          matrix_type& L, real_vector_type& d,\n                          vector_type& alpha, vector_type& beta);\n    //\n    // Apply permutation matrix generated by previous decomposition *in-place.*\n    //\n    // @X $n \\times k$ matrix that the row-permutation matrix is applied.\n    // @ipiv vector of index with size $n$. Permutation index obtained by\n    //       `pivot_order` or `pivot_order_sym`.\n    // @work working space of size $n$.\n    //\n    template <typename MatX>\n    static void apply_row_permutation(MatX& X, const arma::uvec& ipiv,\n                                      vector_type& work)\n    {\n        const size_type n = ipiv.size();\n        assert(X.n_rows == n && work.n_elem == n);\n\n        for (size_type j = 0; j < X.n_cols; ++j)\n        {\n            for (size_type i = 0; i < n; ++i)\n            {\n                work(ipiv(i)) = X(i, j);\n            }\n            X.col(j) = work;\n        }\n    }\n    //\n    // Reconstruct matrix from Cholesky factor\n    //\n    // @X Cholesky factor computed by `cholesky_quasi_cauchy::run`.\n    // @d Cholesky factor computed by `cholesky_quasi_cauchy::run`.\n    //\n    static matrix_type reconstruct(const matrix_type& X, const arma::uvec& ipiv,\n                                   const real_vector_type& d)\n    {\n        matrix_type PX(X);\n        vector_type work(X.n_rows);\n        apply_row_permutation(PX, ipiv, work);\n\n        return matrix_type(PX * arma::diagmat(arma::square(d)) * PX.t());\n    }\n};\n\n//------------------------------------------------------------------------------\n// Implementation of member functions\n//------------------------------------------------------------------------------\ntemplate <typename T>\ntypename cholesky_quasi_cauchy<T>::size_type\ncholesky_quasi_cauchy<T>::pivot_order(vector_type& a, vector_type& b,\n                                      vector_type& x, vector_type& y,\n                                      real_type delta, arma::uvec& ipiv,\n                                      vector_type& g)\n{\n    const size_type n = a.size();\n    assert(b.size() == n);\n    assert(x.size() == n);\n    assert(y.size() == n);\n    assert(ipiv.size() == n);\n    assert(g.size() == n);\n    //\n    // Set cutoff for GECP termination\n    //\n    const auto eta = arma::Datum<real_type>::eps * delta * delta;\n    //\n    // Form vector g(i) = a(i) * b(i) / (x(i) + y(i))\n    //\n    g = (a % b) / (x + y);\n    //\n    // Initialize permutation matrix\n    //\n    ipiv = arma::linspace<arma::uvec>(0, n - 1, n);\n\n    size_type m = 0;\n    while (m < n)\n    {\n        //\n        // Find m <= l < n such that |g(l)| = max_{m<=k<n}|g(k)|\n        //\n        const auto l    = arma::abs(g.tail(n - m)).index_max() + m;\n        const auto gmax = std::abs(g(l));\n\n        if (gmax < eta)\n        {\n            break;\n        }\n\n        if (l != m)\n        {\n            // Swap elements\n            std::swap(g(l), g(m));\n            std::swap(a(l), a(m));\n            std::swap(b(l), b(m));\n            std::swap(x(l), x(m));\n            std::swap(y(l), y(m));\n            // Swap _rows_ of permutation matrix\n            std::swap(ipiv(l), ipiv(m));\n        }\n\n        // Update diagonal of Schur complement\n        const auto xm = x(m);\n        const auto ym = y(m);\n        for (size_type k = m + 1; k < n; ++k)\n        {\n            g(k) *= (x(k) - xm) * (y(k) - ym) / ((x(k) + ym) * (y(k) + xm));\n        }\n        ++m;\n    }\n    //\n    // Returns the truncation size\n    //\n    return m;\n}\n\ntemplate <typename T>\nvoid cholesky_quasi_cauchy<T>::factorize(const vector_type& a,\n                                         const vector_type& b,\n                                         const vector_type& x,\n                                         const vector_type& y, matrix_type& L,\n                                         real_vector_type& d,\n                                         vector_type& alpha, vector_type& beta)\n{\n    const auto n = L.n_rows;\n    const auto m = L.n_cols;\n    assert(a.size() == n);\n    assert(b.size() == n);\n    assert(x.size() == n);\n    assert(y.size() == n);\n    assert(d.size() == m);\n    assert(alpha.size() == n);\n    assert(beta.size() == n);\n\n    alpha = a;\n    beta  = b;\n\n    L.zeros();\n    for (size_type l = 0; l < n; ++l)\n    {\n        L(l, 0) = alpha(l) * beta(0) / (x(l) + y(0));\n    }\n\n    for (size_type k = 1; k < m; ++k)\n    {\n        // Upgrade generators\n        const auto xkm1 = x(k - 1);\n        const auto ykm1 = y(k - 1);\n        for (size_type l = k; l < n; ++l)\n        {\n            alpha(l) *= (x(l) - xkm1) / (x(l) + ykm1);\n            beta(l) *= (y(l) - ykm1) / (y(l) + xkm1);\n        }\n        // Extract k-th column for Cholesky factors\n        for (size_type l = k; l < n; ++l)\n        {\n            L(l, k) = alpha(l) * beta(k) / (x(l) + y(k));\n        }\n    }\n    //\n    // Scale strictly lower triangular part of G\n    //   - diagonal part of G contains D**2\n    //   - L = tril(G) * D^{-2} + I\n    //\n    for (size_type j = 0; j < m; ++j)\n    {\n        const auto djj   = std::real(L(j, j));\n        const auto scale = real_type(1) / djj;\n        d(j)             = std::sqrt(djj);\n        L(j, j) = real_type(1);\n        for (size_type i = j + 1; i < n; ++i)\n        {\n            L(i, j) *= scale;\n        }\n    }\n\n    return;\n}\n\n} // namespace: expsum\n\n#endif /* EXPSUM_REDUCTION_CHOLESKY_CAUCHY_HPP */\n", "meta": {"hexsha": "48561dc6bf302ec3b28a6315b8db143abead8523", "size": 7397, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/reduction/cholesky_quasi_cauchy.hpp", "max_stars_repo_name": "hide-ikeno/expsum", "max_stars_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/expsum/reduction/cholesky_quasi_cauchy.hpp", "max_issues_repo_name": "hide-ikeno/expsum", "max_issues_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/expsum/reduction/cholesky_quasi_cauchy.hpp", "max_forks_repo_name": "hide-ikeno/expsum", "max_forks_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6111111111, "max_line_length": 80, "alphanum_fraction": 0.4984453157, "num_tokens": 2016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4346662890677762}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2009 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef SCHUR_SOLVER_HH\n#define SCHUR_SOLVER_HH\n\n/**\n * @file\n * @brief  Routines for the solution of (sparse) linear systems\n * @author Anton Schiela\n */\n\n#include <iostream>\n#include <memory> // std::unique_ptr\n\n#include <boost/timer/timer.hpp>\n\n\n#include \"dune/common/fmatrix.hh\"\n#include \"dune/istl/matrix.hh\"\n\n#include \"linalg/umfpack_solve.hh\"\n#include \"linalg/linearsystem.hh\"\n#include \"linalg/simpleLAPmatrix.hh\"\n#include \"algorithm/opt_interface.hh\"\n#include \"algorithm/newton_bridge.hh\"\n\nnamespace Kaskade\n{\n\n/** \n * \\ingroup linalg \n * \\brief Adapter class for DUNE::IterativeSolver\n */\n\n\nvoid printVec(std::vector<double> const&v, int vend=1000000);\n\n\ntemplate<class Factorization=UMFFactorization<double> >\nclass BlockLUFactorization\n{\npublic:\n/// needs a matrix\n  static const bool needMatrix = true;\ntemplate<class Sys>\nBlockLUFactorization(Sys const& lin, int start2, int end2, int start3, int end3)\n  {\n    MatrixAsTriplet<double> matL;\n    lin.getMatrixBlocks(matL,start3,end3,start2,end2);\n    matA.resize(0);\n    lin.getMatrixBlocks(matA,start2,end2,start2,end2);\n    boost::timer::cpu_timer timer;\n    factoredL.reset(new Factorization(matL.nrows(),\n                                      2,\n                                      matL.ridx, \n                                      matL.cidx, \n                                      matL.data,\n                                      MatrixProperties::GENERAL));\n  }\n\n  void resetBlock22(MatrixAsTriplet<double>const & matA_) { matA = matA_; };\n    \n  void solve(std::vector<double>const& rhs, std::vector<double>& sol, int nr=1);\n  MatrixAsTriplet<double> matA;\n  std::unique_ptr<Factorization> factoredL;\n};\n\nvoid printVec(std::vector<double> const&v, int vend)\n{\n  int endv=v.size();\n  if(vend < v.size()) endv=vend;\n  for(int i=0; i< endv; ++i)\n  {\n    if(i%5 == 0)  std::cout << \".  \" << v[i] << std::endl;\n    else std::cout << \"   \" << v[i] << std::endl;\n\n  }\n}\n\ntemplate<class Factorization>\nvoid BlockLUFactorization<Factorization>::solve(std::vector<double>const& rhs, std::vector<double>& sol, int nr)\n{\n  int r=rhs.size()/2/nr;\n  std::vector<double> rhs1(r*nr);\n  std::vector<double> rhs2(r*nr);\n  std::vector<double> sol1(r*nr);\n  std::vector<double> sol2(r*nr);\n  for(int i=0; i<nr; ++i)\n  for(int j=0; j<r; ++j)\n  {\n    rhs1[i*r+j]=rhs[i*2*r+j];\n    rhs2[i*r+j]=-rhs[i*2*r+r+j];\n  }\n  factoredL->solve(rhs2,sol2,false);  // solve system\n  //  factoredL->solve(rhs2,sol2,nr,false);  // solve system\n  matA.axpy(rhs1,sol2,1.0,nr);\n  factoredL->solve(rhs1,sol1,true);  //solve transposed system\n  // factoredL->solve(rhs1,sol1,nr,true);  //solve transposed system\n  sol.resize(2*r*nr);\n  for(int i=0; i<nr; ++i)\n  for(int j=0; j<r; ++j)\n  {\n    sol[i*2*r+j]=-sol2[i*r+j];\n    sol[i*2*r+r+j]=sol1[i*r+j];\n  }\n};\n\n\nstruct BlockSchurParameters\n{\n  BlockSchurParameters(bool reg_)\n    : refactorizeInner(true), refactorizeOuter(true)\n  {\n    if(reg_) regularizationMethod=AddId; else regularizationMethod=None;\n  }\n\n  BlockSchurParameters(bool reg_, bool innerf_, bool outerf_)\n    : refactorizeInner(innerf_), refactorizeOuter(outerf_)\n  {\n    if(reg_) regularizationMethod=AddId; else regularizationMethod=None;\n  }\n\n  bool refactorizeInner, refactorizeOuter;\n  typedef enum { None=0, AddId=1, IterateType::CG = 2} RegularizationMethod;\n\n  RegularizationMethod regularizationMethod;\n};\n\n\n\ntemplate<class Factorization, class VariableSet>\nclass DirectBlockSchurSolver : public AbstractNormalDirection, public Dune::Preconditioner<typename VariableSet::Descriptions::template CoefficientVectorRepresentation<>::type,\n typename VariableSet::Descriptions::template CoefficientVectorRepresentation<>::type> \n{\npublic:\n  typedef typename VariableSet::Descriptions::template CoefficientVectorRepresentation<>::type Domain;\n  typedef Domain Range;\n\n  int start1, end1, start2, end2, start3, end3;\n\n/// needs a matrix\n  static const bool needMatrix = true;\n\n  DirectBlockSchurSolver(bool doregularize = false) : \n    start1(0), end1(1), \n    start2(1), end2(2), \n    start3(2), end3(3),\n    report(false), paras(doregularize)\n  {}\n\n  virtual void pre(Domain &x, Range &b) {}\n\n  virtual void apply (Domain &v, const Range &d) {\n    \n    std::vector<double> r(rows1),s(rows2),t(rows3), sol1(rows1+rows2+rows3);\n\n    d.write(sol1.begin());\n\n    for(int i=0; i<rows1; ++i) r[i]=sol1[i];\n    for(int i=0; i<rows2; ++i) s[i]=sol1[i+rows1];\n    for(int i=0; i<rows3; ++i) t[i]=sol1[i+rows1+rows2];\n    \n    resolveN(sol1,r,s,t);\n\n    v.read(sol1.begin());\n  }\n  virtual void post (Domain &x) {}\n\n  void onChangedLinearization() {flushFactorization(); }\n\n  void flushFactorization() \n  { \n    if(factorization.get() && paras.refactorizeInner) factorization.reset(); \n    mC.setSize(0,0);\n    B.resize(0);\n    AinvB.resize(0);\n    matANormal.flush();\n  }\n\n  bool report;\n\n  void resetParameters(BlockSchurParameters const& p_) { paras=p_; }\n\n  virtual void computeCorrectionAndAdjointCorrection(AbstractVector& correction, AbstractVector& adjointCorrection, AbstractLinearization& linearization)\n  {\n    SparseLinearSystem& lins=dynamic_cast<SparseLinearSystem &>(linearization);\n    flushFactorization();\n    buildNewSchurComplement(lins);\n\n    std::vector<double> r,s,t, sol1, sol2;\n    \n    lins.getRHSBlocks(r,start1,end1);\n    lins.getRHSBlocks(s,start2,end2);\n    lins.getRHSBlocks(t,start3,end3);\n\n    std::vector<double> r0(r.size(),0.0),s0(s.size(),0.0),t0(t.size(),0.0);\n    resolveN(sol1,r0,s0,t);\n    resolveN(sol2,r,s,t0);\n\n    dynamic_cast<Bridge::Vector<VariableSet>& >(correction).read(sol1);\n    dynamic_cast<Bridge::Vector<VariableSet>& >(adjointCorrection).read(sol2);\n    correction *= -1.0;\n    adjointCorrection *= -1.0;\n  }\n\n  virtual void computeSimplifiedCorrection(AbstractVector& correction, AbstractLinearization const& lin) const\n  {\n    SparseLinearSystem const& lins=dynamic_cast<SparseLinearSystem const&>(lin);\n\n    std::vector<double> t, sol1;\n    lins.getRHSBlocks(t,start3,end3);\n    std::vector<double> r0(rows1,0.0),s0(rows2,0.0);\n    resolveN(sol1,r0,s0,t);\n    dynamic_cast<Bridge::Vector<VariableSet>& >(correction).read(sol1);\n    correction *= -1.0;\n  }\n\nprivate:\n\n  void resolveN(std::vector<double>& sol, std::vector<double>const &rhs0,std::vector<double>const &rhs1, std::vector<double>const &rhs2) const;\n\n  void fwd(std::vector<double>& sol, std::vector<double>const &r,std::vector<double>const &s,std::vector<double>const &t) const;\n  void bwd(std::vector<double>& sol, std::vector<double>const &x2,std::vector<double>const &s,std::vector<double>const &t) const;\n\n\n  void buildNewSchurComplement(SparseLinearSystem const& lin,int task);\n\n  std::unique_ptr<BlockLUFactorization<Factorization> > factorization; //\n  MatrixAsTriplet<double> matANormal;\n  Dune::Matrix<Dune::FieldMatrix<double,1,1> > mC,mCNormal;\n  std::vector<double> B,AinvB;\n\n  int rowsB, colsBC, rowsC;\n  int rows1, rows2, rows3;\n\n  BlockSchurParameters paras;\n\n};\n\n//  UU UY BU* ...  C B* B*\n//  YU YY AY* ...  B A  A\n//  BU AY 00  ...  B A  A\n//  .. .. ..  ...\ntemplate<class Factorization, class VariableSet>\nvoid DirectBlockSchurSolver<Factorization, VariableSet>::buildNewSchurComplement(SparseLinearSystem const& lin,int task=0)\n{\n    boost::timer::cpu_timer timer;\n    if(report) std::cout << \"Schur Complement: \" << std::flush;\n\n    MatrixAsTriplet<double> matB, matC;\n    rowsB=lin.rows(start2,end3);\n    colsBC=lin.cols(start1,end1);\n    rowsC=lin.rows(start1,end1);\n    if(task==0)\n    {\n      rows1=lin.rows(start1,end1);\n      rows2=lin.rows(start2,end2);\n      rows3=lin.rows(start3,end3);\n    }\n\n    if(paras.refactorizeOuter || !factorization.get() || B.size()==0)\n    {\n      if(report) std::cout << \"Outer, \" << std::flush;\n      if(task==0)\n      {\n        flushFactorization();\n      }\n\n      if((task==0 && paras.refactorizeInner) || !factorization.get())\n      {\n        factorization.reset(new BlockLUFactorization<Factorization>(lin,start2,end2,start3,end3));\n        lin.getMatrixBlocks(matANormal,start2,end2, start2, end2);\n      }\n      else\n      {\n        MatrixAsTriplet<double> matA;\n        lin.getMatrixBlocks(matA,start2,end2, start2, end2);\n        factorization->resetBlock22(matA);\n      }\n\n  \n// Matrix = [C B^T; B A]; rhs=[r2, r1]; sol=[x_2,x_1]\n// Compute sol via the Schur complement\n// B is stored in column-first formal in a vector B(i,j)=B[i+j*rowsB]\n      if(task==0 || B.size()==0)\n      {\n        matB.resize(0);\n        lin.getMatrixBlocks(matB,start2,end3, start1, end1);\n        B.resize(0);\n        matB.toVector(B);\n      }\n\n// Compute A^{-1}B\n      AinvB.resize(0);\n      factorization->solve(B,AinvB,colsBC);\n\n    }\n\n\n// Compute C as a full matrix\n    matC.resize(0);\n    lin.getMatrixBlocks(matC,start1,end1, start1, end1);\n    mC.setSize(rowsC, colsBC);\n    mC=0.0;\n    matC.addToMatrix(mC);\n\n// Compute S := B^T A^{-1}B-C\n    for(int i=0; i<rowsC; ++i)\n      for(int j=0; j<colsBC; ++j)\n      {\n        mC[i][j] *= -1.0;\n        for(int k=0; k<rowsB; ++k) mC[i][j] += B[i*rowsB+k]*AinvB[j*rowsB+k];\n      }\n    if(task==0)\n    {\n      mCNormal.setSize(rowsC, colsBC);\n      mCNormal = mC;\n    }\n    if(report) std::cout << \"Finished: \" << (double)(timer.elapsed().user)/1e9 << \" sec.\" << std::endl;\n}\n\ntemplate<class Factorization, class VariableSet>\nvoid DirectBlockSchurSolver<Factorization,VariableSet>::resolveN(std::vector<double>& sol, std::vector<double>const &r,std::vector<double>const &s,std::vector<double>const &t) const\n{\n  std::vector<double> xx2;\n\n  fwd(xx2,r,s,t);\n\n  std::vector<double> x2(xx2.size(),0.0);\n\n  // Compute x2 := S^{-1}xx_2\n\n  LeastSquares(SLAPMatrix<double>(mCNormal), xx2, x2);  \n\n  bwd(sol,x2,s,t);\n}\n\ntemplate<class Factorization, class VariableSet>\nvoid DirectBlockSchurSolver<Factorization,VariableSet>::fwd(std::vector<double>& sol, std::vector<double>const &r,std::vector<double>const &s,std::vector<double>const &t) const\n{\n    std::vector<double> xx1, r1;\n\n    r1.reserve(s.size()+t.size());\n\n    for(int i=0; i<s.size();++i) r1.push_back(s[i]);\n    for(int i=0; i<t.size();++i) r1.push_back(t[i]);\n// Compute xx1=A^{-1}r1\n\n    xx1.resize(r1.size());\n    factorization->solve(r1,xx1);\n\n// Compute sol := -r2+B^T xx1\n\n    sol.resize(r.size());\n    for(int i=0; i<r.size(); ++i)\n    {\n      sol[i]=-r[i];\n      for(int k=0; k<xx1.size(); ++k)\n        sol[i]+=B[i*rowsB+k]*xx1[k];\n    }\n}\n\ntemplate<class Factorization, class VariableSet>\nvoid DirectBlockSchurSolver<Factorization,VariableSet>::bwd\n(std::vector<double>& sol, std::vector<double>const &x2,std::vector<double>const &s,std::vector<double>const &t) const\n{\n  std::vector<double> xx1,x1;\n\n   xx1.reserve(s.size()+t.size());\n\n    for(int i=0; i<s.size();++i) xx1.push_back(s[i]);\n    for(int i=0; i<t.size();++i) xx1.push_back(t[i]);\n\n// Compute xx1 := r1-B x2\n    for(int i=0; i<xx1.size(); ++i)\n      for(int k=0; k<x2.size(); ++k)\n        xx1[i]-=B[k*rowsB+i]*x2[k];\n\n// Compute x1 = A^{-1}xx1\n    factorization->solve(xx1,x1);    \n\n// sol=[x2;x1]\n    sol.reserve(x2.size()+x1.size());//x2.size()+x1.size());\n    sol.resize(x2.size()+x1.size(),0.0);\n    int k=0;\n    for(int i=0; i< x2.size(); ++i)\n    {\n      sol[k]=x2[i];\n      ++k;\n    }\n    for(int i=0; i< x1.size(); ++i)\n    {\n      sol[k]=x1[i];\n      ++k;\n    }\n}\n\n\n}  // namespace Kaskade\n#endif\n", "meta": {"hexsha": "bf4e7883090959a81511eecef89e07cd2a2d64c2", "size": 12170, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/linalg/schur_solver.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/linalg/schur_solver.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/linalg/schur_solver.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 29.6107055961, "max_line_length": 181, "alphanum_fraction": 0.6139687757, "num_tokens": 3643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4344874075395497}}
{"text": "#ifndef BAYES_CLASSIFIER_HPP\n#define BAYES_CLASSIFIER_HPP\n\n#include <cmath>\n\n#include <utility>\n#include <vector>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace osrm\n{\nnamespace engine\n{\nnamespace map_matching\n{\n\nstruct NormalDistribution\n{\n    NormalDistribution(const double mean, const double standard_deviation)\n        : mean(mean), standard_deviation(standard_deviation)\n    {\n    }\n\n    // FIXME implement log-probability version since it's faster\n    double Density(const double val) const\n    {\n        using namespace boost::math::constants;\n\n        const double x = val - mean;\n        return 1.0 / (std::sqrt(two_pi<double>()) * standard_deviation) *\n               std::exp(-x * x / (standard_deviation * standard_deviation));\n    }\n\n    double mean;\n    double standard_deviation;\n};\n\nstruct LaplaceDistribution\n{\n    LaplaceDistribution(const double location, const double scale)\n        : location(location), scale(scale)\n    {\n    }\n\n    // FIXME implement log-probability version since it's faster\n    double Density(const double val) const\n    {\n        const double x = std::abs(val - location);\n        return 1.0 / (2. * scale) * std::exp(-x / scale);\n    }\n\n    double location;\n    double scale;\n};\n\ntemplate <typename PositiveDistributionT, typename NegativeDistributionT, typename ValueT>\nclass BayesClassifier\n{\n  public:\n    enum class ClassLabel : unsigned\n    {\n        NEGATIVE,\n        POSITIVE\n    };\n    using ClassificationT = std::pair<ClassLabel, double>;\n\n    BayesClassifier(PositiveDistributionT positive_distribution,\n                    NegativeDistributionT negative_distribution,\n                    const double positive_apriori_probability)\n        : positive_distribution(std::move(positive_distribution)),\n          negative_distribution(std::move(negative_distribution)),\n          positive_apriori_probability(positive_apriori_probability),\n          negative_apriori_probability(1. - positive_apriori_probability)\n    {\n    }\n\n    // Returns label and the probability of the label.\n    ClassificationT classify(const ValueT &v) const\n    {\n        const double positive_postpriori =\n            positive_apriori_probability * positive_distribution.Density(v);\n        const double negative_postpriori =\n            negative_apriori_probability * negative_distribution.Density(v);\n        const double norm = positive_postpriori + negative_postpriori;\n\n        if (positive_postpriori > negative_postpriori)\n        {\n            return std::make_pair(ClassLabel::POSITIVE, positive_postpriori / norm);\n        }\n\n        return std::make_pair(ClassLabel::NEGATIVE, negative_postpriori / norm);\n    }\n\n  private:\n    PositiveDistributionT positive_distribution;\n    NegativeDistributionT negative_distribution;\n    double positive_apriori_probability;\n    double negative_apriori_probability;\n};\n}\n}\n}\n\n#endif // BAYES_CLASSIFIER_HPP\n", "meta": {"hexsha": "70e2cfd30ebd00d8817526eba50e9cc63c0f91fd", "size": 2896, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/engine/map_matching/bayes_classifier.hpp", "max_stars_repo_name": "jhermsmeier/osrm-backend", "max_stars_repo_head_hexsha": "7b11cd3a11c939c957eeff71af7feddaa86e7f82", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-02-21T02:02:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T13:49:31.000Z", "max_issues_repo_path": "include/engine/map_matching/bayes_classifier.hpp", "max_issues_repo_name": "serarca/osrm-backend", "max_issues_repo_head_hexsha": "3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 288.0, "max_issues_repo_issues_event_min_datetime": "2019-02-21T01:34:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-27T12:19:10.000Z", "max_forks_repo_path": "include/engine/map_matching/bayes_classifier.hpp", "max_forks_repo_name": "serarca/osrm-backend", "max_forks_repo_head_hexsha": "3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-21T20:51:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-13T09:22:24.000Z", "avg_line_length": 27.320754717, "max_line_length": 90, "alphanum_fraction": 0.6964779006, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321796478255, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.4342222268762238}}
{"text": "/***************************************************************************\n/* Javier Juan Albarracin - jajuaal1@ibime.upv.es                         */\n/* Universidad Politecnica de Valencia, Spain                             */\n/*                                                                        */\n/* Copyright (C) 2020 Javier Juan Albarracin                              */\n/*                                                                        */\n/***************************************************************************\n* SVFMM <-> Python data type conversions                                   *\n***************************************************************************/\n\n#ifndef PYSVFMM_HPP\n#define PYSVFMM_HPP\n\n#define cimg_display 0\n#include <CImg.h>\n#include <Eigen/Dense>\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <pybind11/eigen.h>\n#include <SpatiallyVariantFiniteMixtureModel.hpp>\n#include <Distributions/MultivariateNormal.hpp>\n#include <Distributions/MultivariateTStudent.hpp>\n#include <Distributions/Gamma.hpp>\n#include <MarkovRandomFields/MarkovRandomField.hpp>\n#include <MarkovRandomFields/FrequentistGaussMarkovRandomField.hpp>\n#include <MarkovRandomFields/FrequentistTStudentMarkovRandomField.hpp>\n#include <MarkovRandomFields/FrequentistNonLocalMarkovRandomField.hpp>\n#include <MarkovRandomFields/BayesianGaussMarkovRandomField.hpp>\n#include <MarkovRandomFields/BayesianTStudentMarkovRandomField.hpp>\n#include <MarkovRandomFields/BayesianNonLocalMarkovRandomField.hpp>\n#include <PyCImg.hpp>\n#include <PySTL.hpp>\n#include <cstdint>\n#include <stdexcept>\n#include <sstream>\n#include <string>\n#include <omp.h>\n\nnamespace py = pybind11;\nusing namespace cimg_library;\nusing namespace Eigen;\n\ntemplate<typename T>\nusing ndarray = py::array_t<T, py::array::c_style | py::array::forcecast>;\n\n\ntemplate<typename Distribution, int Dimensions>\nndarray<double> muToNumpy(const SpatiallyVariantFiniteMixtureModel<Distribution, Dimensions> *svfmm)\n{\n    const int K = svfmm->components();\n    const int D = svfmm->spectrum();\n\n    ndarray<double> output({K, D});\n    py::buffer_info info = output.request();\n\n    double *ptr = (double*) info.ptr;\n    for (int i = 0; i < K; ++i)\n    {\n        for (int j = 0; j < D; ++j)\n        {\n            ptr[j * K + i] = (*svfmm)[i].mu()(j);\n        }\n    }\n\n    return output;\n}\n\n\ntemplate<typename Distribution, int Dimensions>\nndarray<double> sigmaToNumpy(const SpatiallyVariantFiniteMixtureModel<Distribution, Dimensions> *svfmm)\n{\n    const int K = svfmm->components();\n    const int D = svfmm->spectrum();\n\n    ndarray<double> output({D, D, K});\n    py::buffer_info info = output.request();\n\n    double *ptr = (double*) info.ptr;\n    for (int i = 0; i < K; ++i)\n    {\n        for (int j = 0; j < D; ++j)\n        {\n            for (int k = 0; k < D; ++k)\n            {\n                ptr[(i * D * D) + (k * D) + j] = (*svfmm)[i].sigma()(j, k);\n            }\n        }\n    }\n    return output;\n}\n\n\ntemplate<int Dimensions>\nndarray<double> nuToNumpy(const SpatiallyVariantFiniteMixtureModel<MultivariateTStudent, Dimensions> *svfmm)\n{\n    const int K = svfmm->components();\n\n    ndarray<double> output({K});\n    py::buffer_info info = output.request();\n    \n    double *ptr = (double*) info.ptr;\n    for (int i = 0; i < K; ++i)\n    {\n        ptr[i] = (*svfmm)[i].nu();\n    }\n    \n    return output;\n}\n\n\ntemplate<int Dimensions>\nndarray<double> kToNumpy(const SpatiallyVariantFiniteMixtureModel<Gamma, Dimensions> *svfmm)\n{\n    const int K = svfmm->components();\n\n    ndarray<double> output({K});\n    py::buffer_info info = output.request();\n    \n    double *ptr = (double*) info.ptr;\n    for (int i = 0; i < K; ++i)\n    {\n        ptr[i] = (*svfmm)[i].k();\n    }\n    \n    return output;\n}\n\n\ntemplate<int Dimensions>\nndarray<double> thetaToNumpy(const SpatiallyVariantFiniteMixtureModel<Gamma, Dimensions> *svfmm)\n{\n    const int K = svfmm->components();\n\n    ndarray<double> output({K});\n    py::buffer_info info = output.request();\n    \n    double *ptr = (double*) info.ptr;\n    for (int i = 0; i < K; ++i)\n    {\n        ptr[i] = (*svfmm)[i].theta();\n    }\n    \n    return output;\n}\n\n/***************************** Python SVFMM Base *****************************/\n\nclass PySVFMMBase\n{\npublic:\n    enum Mode { SEGMENTATION, MIXTURE, COMPLETE };\n};\n\n\n/***************************** Python SVFMM *****************************/\n\ntemplate<typename Distribution, int Dimensions>\nclass PySVFMM : public PySVFMMBase\n{\npublic:\n    static py::dict toPython(const SpatiallyVariantFiniteMixtureModel<Distribution, Dimensions> *svfmm, const CImg<bool> &mask, const PySVFMMBase::Mode mode);\n};\n\ntemplate<typename Distribution, int Dimensions>\npy::dict PySVFMM<Distribution, Dimensions>::toPython(const SpatiallyVariantFiniteMixtureModel<Distribution, Dimensions> *svfmm, const CImg<bool> &mask, const PySVFMMBase::Mode mode)\n{\n    std::stringstream s;\n    s << \"In function \" << __PRETTY_FUNCTION__ << \" ==> Function must be specialized for each distribution type.\" << std::endl;\n    throw std::runtime_error(s.str());\n\n    return py::dict();\n}\n\n/***************************** Template Specialization Multivariate Normal *****************************/\n\ntemplate<int Dimensions>\nclass PySVFMM<MultivariateNormal, Dimensions> : public PySVFMMBase\n{\npublic:\n    static py::dict toPython(const SpatiallyVariantFiniteMixtureModel<MultivariateNormal, Dimensions> *svfmm, const CImg<bool> &mask, const PySVFMMBase::Mode mode);\n};\n\ntemplate<int Dimensions>\npy::dict PySVFMM<MultivariateNormal, Dimensions>::toPython(const SpatiallyVariantFiniteMixtureModel<MultivariateNormal, Dimensions> *svfmm, const CImg<bool> &mask, const PySVFMMBase::Mode mode)\n{\n    py::dict output = py::dict();\n\n    if (mode == SEGMENTATION || mode == MIXTURE || mode == COMPLETE)\n    {\n        output[\"segmentation\"] = PyCImg::toNumpy(EigenCImg::toCImg(svfmm->labels().array() + 1, mask));\n    }\n    \n    if (mode == MIXTURE || mode == COMPLETE)\n    {\n        output[\"mu\"] = muToNumpy(svfmm);\n        output[\"sigma\"] = sigmaToNumpy(svfmm);\n        output[\"priors\"] = PyCImg::toNumpy(EigenCImg::toCImg(svfmm->coefficients(), mask));\n        output[\"posteriors\"] = PyCImg::toNumpy(EigenCImg::toCImg(svfmm->posteriorProbabilities(), mask));\n        output[\"loglikelihood\"] = PySTL::toNumpy(svfmm->logLikelihoodHistory());\n\n    }\n\n    if (mode == COMPLETE)\n    {\n        py::dict mrf = py::dict();\n\n        const MarkovRandomFieldBase::Model model = svfmm->spatialCoefficients().get()->model();\n        const MarkovRandomFieldBase::Tropism tropism = svfmm->spatialCoefficients().get()->tropism();\n        const MarkovRandomFieldBase::Topology topology = svfmm->spatialCoefficients().get()->topology();\n        const MarkovRandomFieldBase::Estimation estimation = svfmm->spatialCoefficients().get()->estimation();\n\n        mrf[\"cliques\"] = svfmm->spatialCoefficients().get()->cliques();\n        mrf[\"connectivity\"] = svfmm->spatialCoefficients().get()->connectivity();\n        mrf[\"nodes\"] = svfmm->spatialCoefficients().get()->nodes();\n        mrf[\"classes\"] = svfmm->spatialCoefficients().get()->classes();\n        mrf[\"model\"] = model == MarkovRandomFieldBase::GAUSS ? \"gaussian\" : (MarkovRandomFieldBase::TSTUDENT ? \"tstudent\" : \"nonlocal\");\n        mrf[\"tropism\"] = tropism == MarkovRandomFieldBase::ISOTROPIC ? \"isotropic\" : \"anisotropic\";\n        mrf[\"topology\"] = topology == MarkovRandomFieldBase::ORTHOGONAL ? \"orthogonal\" : \"complete\";\n        mrf[\"estimation\"] = estimation == MarkovRandomFieldBase::FREQUENTIST ? \"frequentist\" : \"bayesian\";\n        \n        const MarkovRandomField<Dimensions> *ptr_ = svfmm->spatialCoefficients().get();\n\n        // Gauss\n        if (model == MarkovRandomFieldBase::GAUSS && tropism == MarkovRandomFieldBase::ISOTROPIC && estimation == MarkovRandomFieldBase::BAYESIAN)\n        {\n            const BayesianIsotropicGaussMarkovRandomField<Dimensions> *ptr = static_cast<const BayesianIsotropicGaussMarkovRandomField<Dimensions>*>(ptr_);\n            mrf[\"sigma\"] = ptr->sigma();\n        }\n        if (model == MarkovRandomFieldBase::GAUSS && tropism == MarkovRandomFieldBase::ISOTROPIC && estimation == MarkovRandomFieldBase::FREQUENTIST)\n        {\n            const FrequentistIsotropicGaussMarkovRandomField<Dimensions> *ptr = static_cast<const FrequentistIsotropicGaussMarkovRandomField<Dimensions>*>(ptr_);\n            mrf[\"sigma\"] = ptr->sigma();\n        }\n        if (model == MarkovRandomFieldBase::GAUSS && tropism == MarkovRandomFieldBase::ANISOTROPIC && estimation == MarkovRandomFieldBase::BAYESIAN)\n        {\n            const BayesianAnisotropicGaussMarkovRandomField<Dimensions> *ptr = static_cast<const BayesianAnisotropicGaussMarkovRandomField<Dimensions>*>(ptr_);\n            mrf[\"sigma\"] = ptr->sigma();\n        }\n        if (model == MarkovRandomFieldBase::GAUSS && tropism == MarkovRandomFieldBase::ANISOTROPIC && estimation == MarkovRandomFieldBase::FREQUENTIST)\n        {\n            const FrequentistAnisotropicGaussMarkovRandomField<Dimensions> *ptr = static_cast<const FrequentistAnisotropicGaussMarkovRandomField<Dimensions>*>(ptr_);\n            mrf[\"sigma\"] = ptr->sigma();\n        }\n        // T-student\n        if (model == MarkovRandomFieldBase::TSTUDENT && tropism == MarkovRandomFieldBase::ISOTROPIC && estimation == MarkovRandomFieldBase::BAYESIAN)\n        {\n            const BayesianIsotropicTStudentMarkovRandomField<Dimensions> *ptr = static_cast<const BayesianIsotropicTStudentMarkovRandomField<Dimensions>*>(ptr_);\n            mrf[\"sigma\"] = ptr->sigma();\n            mrf[\"nu\"] = ptr->nu();\n        }\n        if (model == MarkovRandomFieldBase::TSTUDENT && tropism == MarkovRandomFieldBase::ISOTROPIC && estimation == MarkovRandomFieldBase::FREQUENTIST)\n        {\n            const FrequentistIsotropicTStudentMarkovRandomField<Dimensions> *ptr = static_cast<const FrequentistIsotropicTStudentMarkovRandomField<Dimensions>*>(ptr_);\n            mrf[\"sigma\"] = ptr->sigma();\n            mrf[\"nu\"] = ptr->nu();\n        }\n        if (model == MarkovRandomFieldBase::TSTUDENT && tropism == MarkovRandomFieldBase::ANISOTROPIC && estimation == MarkovRandomFieldBase::BAYESIAN)\n        {\n            const BayesianAnisotropicTStudentMarkovRandomField<Dimensions> *ptr = static_cast<const BayesianAnisotropicTStudentMarkovRandomField<Dimensions>*>(ptr_);\n            mrf[\"sigma\"] = ptr->sigma();\n            mrf[\"nu\"] = ptr->nu();\n        }\n        if (model == MarkovRandomFieldBase::TSTUDENT && tropism == MarkovRandomFieldBase::ANISOTROPIC && estimation == MarkovRandomFieldBase::FREQUENTIST)\n        {\n            const FrequentistAnisotropicTStudentMarkovRandomField<Dimensions> *ptr = static_cast<const FrequentistAnisotropicTStudentMarkovRandomField<Dimensions>*>(ptr_);\n            mrf[\"sigma\"] = ptr->sigma();\n            mrf[\"nu\"] = ptr->nu();\n        }\n        // Non-Local\n        if (model == MarkovRandomFieldBase::NONLOCAL && tropism == MarkovRandomFieldBase::ISOTROPIC && estimation == MarkovRandomFieldBase::BAYESIAN)\n        {\n            const BayesianIsotropicNonLocalMarkovRandomField<Dimensions> *ptr = static_cast<const BayesianIsotropicNonLocalMarkovRandomField<Dimensions>*>(ptr_);\n            mrf[\"sigma\"] = ptr->sigma();\n            mrf[\"nu\"] = ptr->nu();\n            mrf[\"patch_size\"] = ptr->patchSize();\n            mrf[\"chi2_sigma\"] = ptr->chi2Sigma();\n        }\n        if (model == MarkovRandomFieldBase::NONLOCAL && tropism == MarkovRandomFieldBase::ISOTROPIC && estimation == MarkovRandomFieldBase::FREQUENTIST)\n        {\n            const FrequentistIsotropicNonLocalMarkovRandomField<Dimensions> *ptr = static_cast<const FrequentistIsotropicNonLocalMarkovRandomField<Dimensions>*>(ptr_);\n            mrf[\"sigma\"] = ptr->sigma();\n            mrf[\"nu\"] = ptr->nu();\n            mrf[\"patch_size\"] = ptr->patchSize();\n            mrf[\"chi2_sigma\"] = ptr->chi2Sigma();\n        }\n        if (model == MarkovRandomFieldBase::NONLOCAL && tropism == MarkovRandomFieldBase::ANISOTROPIC && estimation == MarkovRandomFieldBase::BAYESIAN)\n        {\n            const BayesianAnisotropicNonLocalMarkovRandomField<Dimensions> *ptr = static_cast<const BayesianAnisotropicNonLocalMarkovRandomField<Dimensions>*>(ptr_);\n            mrf[\"sigma\"] = ptr->sigma();\n            mrf[\"nu\"] = ptr->nu();\n            mrf[\"patch_size\"] = ptr->patchSize();\n            mrf[\"chi2_sigma\"] = ptr->chi2Sigma();\n        }\n        if (model == MarkovRandomFieldBase::NONLOCAL && tropism == MarkovRandomFieldBase::ANISOTROPIC && estimation == MarkovRandomFieldBase::FREQUENTIST)\n        {\n            const FrequentistAnisotropicNonLocalMarkovRandomField<Dimensions> *ptr = static_cast<const FrequentistAnisotropicNonLocalMarkovRandomField<Dimensions>*>(ptr_);\n            mrf[\"sigma\"] = ptr->sigma();\n            mrf[\"nu\"] = ptr->nu();\n            mrf[\"patch_size\"] = ptr->patchSize();\n            mrf[\"chi2_sigma\"] = ptr->chi2Sigma();\n        }\n\n        output[\"mrf\"] = mrf;\n    }\n\n    return output;\n}\n\n#endif", "meta": {"hexsha": "e561190f5a8d68f70846ad41d0923fb55cacfba0", "size": 13027, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PySVFMM.hpp", "max_stars_repo_name": "javierjuan/tools", "max_stars_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PySVFMM.hpp", "max_issues_repo_name": "javierjuan/tools", "max_issues_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PySVFMM.hpp", "max_forks_repo_name": "javierjuan/tools", "max_forks_repo_head_hexsha": "fd51855d3babccabc2cf95e9d7ac00c0a390f7fc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1585760518, "max_line_length": 193, "alphanum_fraction": 0.6334535964, "num_tokens": 3358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.43418868739439526}}
{"text": "#include <boost/lexical_cast.hpp>\n#include <dai/alldai.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include \"dai/emrun.h\"\n#include <dai/util.h>\n#include <string>\n#include <sys/stat.h>\n#include <time.h>\n#include <boost/tokenizer.hpp>\n#include <iomanip>      // std::setprecision\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include<math.h>\nusing namespace std;\nusing namespace dai;\nusing namespace boost;\nstd::string& trim(std::string& s, const char* t = \" \\t\\n\\r\\f\\v\")\n{\n\ts.erase(0, s.find_first_not_of(t));\n\ts.erase(s.find_last_not_of(t) + 1);\n\treturn s;\n}\ndouble euclideanDist(double v1[],double v2[],int length)\n{\n    double distance=0;\n    for(int i=0;i<length;i++)\n    {\n        distance = distance+ pow((v1[i]-v2[i]),2); //Euclidean distance\n        //cout<<v1[i]<<\" \"<<v2[i]<<\" \"<<distance;\n    }\n   // cout<<\"**** \"<<distance<<endl;\n    distance = sqrt(distance);\n    return distance;\n}\ndouble klDist(double v1[],double v2[],int length)\n{\n    double distance=0;\n    for(int i=0;i<length;i++)\n    {\n        distance = distance + (v1[i]* log0( v1[i]/v2[i])); // KL distance\n       // cout<<( v1[i]/v2[i])<<\" \"<<(v1[i]* std::log( v1[i]/v2[i]))<<endl;\n       // cout<<distance<<\"+\";\n    }\n    //cout<<\"=\"<<distance<<endl;\n    return distance;\n}\nvoid calculateDistance(string child, string child1)\n{\n    \n        const char* childfgfile = &child[0];\n        const char* childfgfile1 = &child1[0];\n        //cout<<\"child file \"<< childfgfile<<endl;\n        string line1,line2;\n        ifstream p1 (childfgfile);\n        ifstream c1 (childfgfile1);\n        getline(p1,line1);\n        getline(c1,line2);\n        \n        int factor =0;\n        int no_factors = 0;\n        int* factor_names;\n        int factor_pos=0;\n        int* states_arr;\n        int no_states = 1;\n        int arr_size =1;\n        int factor_states =0;\n        int tot_arrays =0;\n        int arr_set =0;\n        int arr_set_states =0;\n        int no_arr_arrset =0;\n        int stat =0;\n        int p_c = 0;\n        double pmut=0,pm=0,distval=0;\n        while(getline(p1,line1)&&getline(c1,line2))\n        {\n            line1 = trim(line1);\n            line2 = trim(line2);\n            //cout<<p_c<<\" \"<<pmut<<\" \"<<pm<<\" \"<<line1<<endl;\n            stringstream ss(line1);\n            stringstream ss1(line2);\n            if(line1.empty())\n            {\n                p_c = 0;\n                stat =0;\n                //cout<<\"factor variable \"<<factor<<endl;\n                //seed();\n                //pmut = unifRand(); // generates random a value between 0 and 1 for child1\n                //cout<<\"Mutation probability \"<<pmut<<endl;\n                no_states = 1;\n                arr_size =1;\n                factor++;\n            }\n            if(pmut>pm)\n            {\n                //c1<<line1<<endl;\n                //cout<<\"No mutation\"<<endl;\n                //p_c++;\n                //continue;\n            }\n            if(pmut<=pm) //do mutation handling the constraint that the states of the random variable sum to 1.\n            {\n                //cout<<\"Mutation happening \"<<endl;\n                double sumo=0,sumo1=0;\n                if(p_c == 0)\n                {\n                    //c1<<line1<<endl;\n                }\n                if(p_c == 1)\n                {\n                    ss>>no_factors;\n                    //cout<<\"no. of factors \"<<no_factors<<endl;\n                    //c1<<no_factors<<endl;\n                }\n                if(p_c == 2)\n                {\n                    factor_names = new int[no_factors];\n                    std::vector<std::string> fields;\n                    fields = tokenizeString( line1, true,\"  \");\n                    for( size_t i = 0; i < fields.size(); ++i )\n                    {\n                        stringstream n;\n                        n << fields[i];\n                        string s = n.str();\n                        if( s.find_first_not_of(\" \")!= std::string::npos)\n                        {\n                            //c1<<s<<\" \";\n                            n >> factor_names[i];\n                            if(factor_names[i] == (factor-1))\n                                factor_pos =i;\n                        }\n                    }\n                    //c1<<endl;\n                  //  cout<<\"factor position \"<<factor_pos<<endl;\n                }\n                if(p_c == 3)\n                {\n                    states_arr = new int[no_factors];\n                    std::vector<std::string> fields1;\n                    fields1 = tokenizeString( line1, true,\"  \");\n                    for( size_t j = 0; j < fields1.size(); ++j )\n                    {\n                        stringstream n1;\n                        n1 << fields1[j];\n                        string state = n1.str();\n                        if( state.find_first_not_of(\" \")!= std::string::npos)\n                        {\n                            //c1<<state<<\" \";\n                            n1 >> states_arr[j];\n                            no_states = no_states * states_arr[j];\n                            if(j < factor_pos)\n                                arr_size = arr_size * states_arr[j];\n                            if(j == factor_pos)\n                            {\n                                factor_states = states_arr[j];\n                                arr_set_states = arr_size*states_arr[j];\n                            }\n                        }\n                    }\n                    //c1<<endl;\n                    tot_arrays = no_states/arr_size;\n                    arr_set = no_states/arr_set_states;\n                    no_arr_arrset = factor_states;\n                    //cout<<\"array size \"<<arr_size<<endl;\n                   // cout<<no_states<<\"\\t\"<<\"no. of states \"<<no_states<<\"\\t\"<<\"total arrays \"<<tot_arrays<<\"\\t\"<<\"array set \"<<arr_set<<\"\\t\"<<\"no. arrays \"<<no_arr_arrset<<\"\\t\"<<\"factor states \"<<factor_states<<endl;\n                    //c1<<no_states<<endl;\n                }\n                if(p_c >= 5)\n                {\n                    int k=0;\n                    while(k<arr_set)\n                    {\n                        std::vector< double * > Arrays, Arrays1;\n                        for(int l=0; l<no_arr_arrset; l++)\n                        {\n                            Arrays.push_back( new double[arr_size]);\n                            Arrays1.push_back( new double[arr_size]);\n                        }\n                        vector<double*>::iterator it2,it21;\n                        it2=Arrays.begin();\n                        it21=Arrays1.begin();\n                        //get the current cpt values and copy them in the array\n                        int l=0;\n                        while(l<no_arr_arrset)\n                        {\n                            double* arr = *it2;\n                            double* arr1 = *it21;\n                           // cout<<\"new arr\"<<endl;\n                            int m=0;\n                            while(m<arr_size)\n                            {\n                                line1 = trim(line1);\n                                line2 = trim(line2);\n                                //cout<<line1 <<\" \"<<line2<<endl;\n                                std::vector<std::string> values,values1;\n//                                values = tokenizeString( line1, true,\" +\");\n//                                values1 = tokenizeString( line2, true,\" +\");\n                                char_separator<char> sep(\"                 \");\n                                tokenizer<char_separator<char>> tokens(line1, sep);\n                                for (const auto& t : tokens) {\n                                    //cout<<t;\n                                    if(t!=\" \")\n                                    {\n                                        values.push_back(t);\n                                        // cout<<\"pushed \"<<t<<endl;\n                                    }\n                                }\n                                //cout<<endl;\n                                tokenizer<char_separator<char>> tokens1(line2, sep);\n                                for (const auto& t : tokens1) {\n                                    //cout<<t;\n                                    if(t!=\" \")\n                                    {\n                                        values1.push_back(t);\n                                        //cout<<\"pushed \"<<t<<endl;\n                                    }\n                                }\n                                int ii=0;\n                                //cout<<values.size()<<\" \"<<values1.size()<<endl;\n                                for( size_t j = 0; j < values.size(); ++j )\n                                {\n                                    stringstream n1,n2;\n                                    n1 << values[j];\n                                    n2 << values1[j];\n                                    string state = n1.str();\n                                    string state1 = n2.str();\n                                    //cout<<state<<\" !! \"<<state1<<\" !! \"<<endl;\n                                    if( state.find_first_not_of(\" \")!= std::string::npos && state1.find_first_not_of(\" \")!= std::string::npos)\n                                    {\n                                        if(ii==1)\n                                        {\n                                            n1 >> arr[m];\n                                            n2 >> arr1[m];\n                                            //cout<<p_c<<\" \"<<line1<<\" \"<<\"arrval = \"<<values[0]<<\"\\tarr[m]\"<<arr[m]<<\" m = \"<<m<<endl;\n                                            m++;\n                                            if(m<arr_size)\n                                            {\n                                             getline(p1,line1);\n                                             getline(c1,line2);\n                                            }\n                                            ii=0;\n                                        }\n                                        else\n                                            ii=1;\n                                    } //end of if\n                                } // end of for\n                            } // end of while -m\n                            l++;\n                            if(l<no_arr_arrset)\n                            {\n                                getline(p1,line1);\n                                getline(c1,line2);\n                            }\n                            ++it2; ++it21;\n                        } //end of while -l\n                       // cout<<\"new val\"<<endl;\n                        vector<double*>::iterator it,it1;\n                        double sumarr[arr_size];\n                        for(int m=0; m<arr_size; m++)\n                        {\n                            it=Arrays.begin();\n                            it1=Arrays1.begin();\n                            double valarr[no_arr_arrset],valarr1[no_arr_arrset];\n                            for(int l=0; l<no_arr_arrset; l++) // stdnormal rand values are generated and sum is found\n                            {\n                                double* arr = *it;\n                                double* arr1 = *it1;\n                                double val = arr[m];\n                                double val1 =  arr1[m];\n                                valarr[l]=val;\n                                valarr1[l]=val1;\n                                cout<<val<<\" \"<<val1<<endl;\n                                ++it; ++it1;\n                            }\n                            \n                            sumo+=euclideanDist(valarr,valarr1,no_arr_arrset);\n                            sumo1+=klDist(valarr,valarr1,no_arr_arrset);\n                           // cout<<endl;\n                        }\n                        k++;\n                        if(k<arr_set)\n                         {\n                             getline(p1,line1);\n                             getline(c1,line2);\n                         }\n                    }// end of while -k\n                    cout<<\"******\"<<no_states<<\" \"<<factor<<\" \"<<sumo<<\" \"<<sumo1<<\" \"<<endl;\n                    distval = distval+sumo;\n                }// end of if p_c>=5\n                \n            } // end of if pmut<p_m\n            p_c++;\n        } // end of while loop\n        c1.close();\n    p1.close();\n    cout<<distval<<endl;\n}\n// Type for storing a joint state of all variables\nint main(int argc, char *argv[]) {\ntime_t timer1, timer2;\ntime(&timer1);\nclock_t tStart = clock();\n    string child,child1;\n//    if(argc.length!=2){\n//     child =  \"/Applications/Utilities/libDAI-0.3.1/alarmnew_factor_graphs/alarm1l.fg\";\n//     child1 =  \"/Applications/Utilities/libDAI-0.3.1/alarmnew_factor_graphs/alarm2l.fg\";\n//    }\n//    else\n    {\n        stringstream ss2(argv[1]);\n        child = ss2.str();\n        stringstream ss3(argv[2]);\n        child1 = ss3.str();\n    }\n    calculateDistance(child,child1);\n\ntime(&timer2);\ndouble t = difftime(timer2,timer1);\n(clock() - tStart)/CLOCKS_PER_SEC;\ndouble t_c = (clock() - tStart)/CLOCKS_PER_SEC;\n//cout<<\"Time taken: \"<<t<<\"s\"<<endl;\n//cout<<\" Processor Time taken: \"<<t_c<<\"s\"<<endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "ec2dc7cbcbaaf22c3d8bf344387548f5ef8c3589", "size": 13324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/computeDistance.cpp", "max_stars_repo_name": "Priyaaks/libDAI_P", "max_stars_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/computeDistance.cpp", "max_issues_repo_name": "Priyaaks/libDAI_P", "max_issues_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/computeDistance.cpp", "max_forks_repo_name": "Priyaaks/libDAI_P", "max_forks_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6219512195, "max_line_length": 218, "alphanum_fraction": 0.3586760733, "num_tokens": 2620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4341198068405906}}
{"text": "#pragma once\n\n#include <set>\n\n#include <Eigen/Eigenvalues>\n\n#include \"CompressedPauliString.hpp\"\n#include \"Operator.hpp\"\n\n#include \"../utils.hpp\"\n\nnamespace yavque\n{\n\nnamespace detail\n{\n\n\tbool commute(const std::map<uint32_t, Pauli>& p1,\n\t             const std::map<uint32_t, Pauli>& p2);\n\tstd::string extract_pauli_string(const std::map<uint32_t, Pauli>& pmap);\n\n\tclass SumPauliStringImpl\n\t{\n\tpublic:\n\t\tusing PauliString = std::map<uint32_t, Pauli>;\n\n\tprivate:\n\t\tconst uint32_t num_qubits_;\n\t\tstd::vector<PauliString> pauli_strings_;\n\t\tmutable std::vector<std::shared_ptr<detail::CompressedPauliString>> cps_;\n\n\t\tvoid update_cps() const\n\t\t{\n\t\t\tfor(std::size_t n = cps_.size(); n < pauli_strings_.size(); ++n)\n\t\t\t{\n\t\t\t\tcps_.emplace_back(CPSFactory::get_instance().get_pauli_string_for(\n\t\t\t\t\textract_pauli_string(pauli_strings_[n])));\n\t\t\t}\n\t\t}\n\n\tpublic:\n\t\texplicit SumPauliStringImpl(uint32_t num_qubits) : num_qubits_{num_qubits} { }\n\n\t\texplicit SumPauliStringImpl(uint32_t num_qubits,\n\t\t                            std::vector<PauliString> pauli_strings)\n\t\t\t: num_qubits_{num_qubits}, pauli_strings_{std::move(pauli_strings)}\n\t\t{\n\t\t\t// check sites pauli strings applied < num_qubits\n\t\t}\n\n\t\texplicit SumPauliStringImpl(uint32_t num_qubits,\n\t\t                            std::vector<PauliString>&& pauli_strings)\n\t\t\t: num_qubits_{num_qubits}, pauli_strings_{std::move(pauli_strings)}\n\t\t{\n\t\t}\n\n\t\tuint32_t num_qubits() const { return num_qubits_; }\n\n\t\tvoid add(const std::map<uint32_t, Pauli>& rhs)\n\t\t{\n\t\t\t// check sites pauli strings applied < num_qubits\n\t\t\tpauli_strings_.push_back(rhs);\n\t\t}\n\n\t\tvoid add(std::map<uint32_t, Pauli>&& rhs)\n\t\t{\n\t\t\t// check sites pauli strings applied < num_qubits\n\t\t\tpauli_strings_.emplace_back(std::move(rhs));\n\t\t}\n\n\t\tbool mutually_commuting() const\n\t\t{\n\t\t\tfor(uint32_t i = 0; i < pauli_strings_.size() - 1; ++i)\n\t\t\t{\n\t\t\t\tfor(uint32_t j = i + 1; j < pauli_strings_.size(); ++j)\n\t\t\t\t{\n\t\t\t\t\tif(!commute(pauli_strings_[i], pauli_strings_[j]))\n\t\t\t\t\t{\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tEigen::VectorXcd apply(const Eigen::VectorXcd& vec) const\n\t\t{\n\t\t\tassert(vec.size() == (1U << num_qubits_));\n\n\t\t\tif(cps_.size() < pauli_strings_.size())\n\t\t\t{\n\t\t\t\tupdate_cps();\n\t\t\t}\n\n\t\t\tEigen::VectorXcd res = Eigen::VectorXcd::Zero(vec.size());\n\t\t\tfor(std::size_t n = 0; n < pauli_strings_.size(); ++n)\n\t\t\t{\n\t\t\t\tconst auto& pauli_string = pauli_strings_[n];\n\t\t\t\tstd::vector<uint32_t> indices;\n\t\t\t\tstd::transform(pauli_string.cbegin(), pauli_string.cend(),\n\t\t\t\t               std::back_inserter(indices),\n\t\t\t\t               [](const auto& p) { return p.first; });\n\t\t\t\tres += cps_[n]->apply(indices, vec);\n\t\t\t}\n\t\t\treturn res;\n\t\t}\n\n\t\t/* this function makes sense only when operators are mutually commuting\n\t\t *\n\t\t * */\n\t\tEigen::VectorXcd apply_exp(cx_double t, const Eigen::VectorXcd& vec) const\n\t\t{\n\t\t\tassert(vec.size() == (1U << num_qubits_));\n\n\t\t\tif(cps_.size() < pauli_strings_.size())\n\t\t\t{\n\t\t\t\tupdate_cps();\n\t\t\t}\n\n\t\t\tEigen::VectorXcd res = vec;\n\t\t\tfor(std::size_t n = 0; n < pauli_strings_.size(); ++n)\n\t\t\t{\n\t\t\t\tconst auto& pauli_string = pauli_strings_[n];\n\t\t\t\tstd::vector<uint32_t> indices;\n\t\t\t\tstd::transform(pauli_string.cbegin(), pauli_string.cend(),\n\t\t\t\t               std::back_inserter(indices),\n\t\t\t\t               [](const auto& p) { return p.first; });\n\t\t\t\tres = cps_[n]->apply_exp(t, indices, res);\n\t\t\t}\n\t\t\treturn res;\n\t\t}\n\t};\n} // namespace detail\n\nclass SumPauliString final : public Operator\n{\npublic:\n\tusing PauliString = std::map<uint32_t, Pauli>;\n\nprivate:\n\tstd::shared_ptr<const detail::SumPauliStringImpl> p_;\n\tcx_double constant_ = 1.0;\n\n\tvoid dagger_in_place_impl() override { constant_ = std::conj(constant_); }\n\npublic:\n\texplicit SumPauliString(const uint32_t num_qubits, const std::string& name = {})\n\t\t: Operator(1U << num_qubits, name),\n\t\t  p_{std::make_shared<detail::SumPauliStringImpl>(num_qubits)}\n\t{\n\t}\n\n\texplicit SumPauliString(const uint32_t num_qubits,\n\t                        const std::vector<std::map<uint32_t, Pauli>>& pauli_strings,\n\t                        const std::string& name = {})\n\t\t: Operator(1U << num_qubits, name),\n\t\t  p_{std::make_shared<detail::SumPauliStringImpl>(num_qubits, pauli_strings)}\n\t{\n\t}\n\n\texplicit SumPauliString(std::shared_ptr<const detail::SumPauliStringImpl> p,\n\t                        const std::string& name = {}, cx_double constant = 1.0)\n\t\t: Operator(1U << p->num_qubits(), name), p_{std::move(p)}, constant_{constant}\n\t{\n\t}\n\n\t[[nodiscard]] bool mutually_commuting() const { return p_->mutually_commuting(); }\n\n\t[[nodiscard]] std::shared_ptr<const detail::SumPauliStringImpl> get_impl() const\n\t{\n\t\treturn p_;\n\t}\n\t/* This function might be slow.\n\t */\n\tSumPauliString& operator+=(const PauliString& str)\n\t{\n\t\tauto p = std::make_shared<detail::SumPauliStringImpl>(*p_);\n\t\tp->add(str);\n\t\tp_ = std::move(p);\n\t\treturn *this;\n\t}\n\n\tSumPauliString& operator+=(PauliString&& str)\n\t{\n\t\tauto p = std::make_shared<detail::SumPauliStringImpl>(*p_);\n\t\tp->add(std::move(str));\n\t\tp_ = std::move(p);\n\t\treturn *this;\n\t}\n\n\tSumPauliString(const SumPauliString&) = default;\n\tSumPauliString(SumPauliString&&) = default;\n\n\tSumPauliString& operator=(const SumPauliString&) = delete;\n\tSumPauliString& operator=(SumPauliString&&) = delete;\n\n\t~SumPauliString() override = default;\n\n\t[[nodiscard]] std::unique_ptr<Operator> clone() const override\n\t{\n\t\tauto cloned = std::make_unique<SumPauliString>(*this);\n\t\treturn cloned;\n\t}\n\n\t[[nodiscard]] Eigen::VectorXcd apply_right(const Eigen::VectorXcd& st) const override\n\t{\n\t\treturn constant_ * p_->apply(st);\n\t}\n};\n\n} // namespace yavque\n", "meta": {"hexsha": "6fd27658844417446525a7411beeead9d45ef16d", "size": 5567, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/yavque/Operators/SumPauliString.hpp", "max_stars_repo_name": "chaeyeunpark/Yavque", "max_stars_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/yavque/Operators/SumPauliString.hpp", "max_issues_repo_name": "chaeyeunpark/Yavque", "max_issues_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/yavque/Operators/SumPauliString.hpp", "max_forks_repo_name": "chaeyeunpark/Yavque", "max_forks_repo_head_hexsha": "eccc7e1a4fb2ebb2e9d27a1bacb4b72ce6ba726d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2594339623, "max_line_length": 86, "alphanum_fraction": 0.6587030717, "num_tokens": 1654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370114, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4341197992276146}}
{"text": "/// My typedefs\n#include <inttypes.h>\n#include <boost/cstdint.hpp>\n#include <boost/integer_traits.hpp>\n\ntypedef int32_t    node_t;\ntypedef int32_t    edge_t;\ntypedef int64_t    cost_t;\n\n/// From STL library\n#include <vector>\nusing std::vector;\n\n#include <string>\n\nusing std::pair;\nusing std::make_pair;\n\n/// Label for the labeling and/or dijkstra algorithm\nenum Label { UNREACHED, LABELED, SCANNED };\n\n/// Data structure to store Key-Value pairs in a \n/// PriorityQueue (as a Fibonacci heap)\nstruct ValueKey {\n   cost_t d;\n   node_t u;\n   ValueKey(cost_t _d, node_t _u)\n      : d(_d), u(_u) {}\n   /// The relation establishes the order in the PriorityQueue\n   inline bool operator<(ValueKey const & rhs) const { return d < rhs.d; }\n};\n\n#include <boost/heap/fibonacci_heap.hpp>\ntypedef boost::heap::fibonacci_heap<ValueKey>  FibonacciHeap;\n\n#include <boost/heap/d_ary_heap.hpp>\ntypedef boost::heap::d_ary_heap<ValueKey, boost::heap::arity<2>, boost::heap::mutable_<true> >  BinaryHeap;\n\n#include <boost/heap/d_ary_heap.hpp>\ntypedef boost::heap::d_ary_heap<ValueKey, boost::heap::arity<3>, boost::heap::mutable_<true> >  TernaryHeap;\n\n#include <boost/heap/skew_heap.hpp>\ntypedef boost::heap::skew_heap<ValueKey, boost::heap::mutable_<true> >  SkewHeap;\n\n#include <boost/heap/pairing_heap.hpp>\ntypedef boost::heap::pairing_heap<ValueKey>  PairingHeap;\n\n#include <boost/heap/binomial_heap.hpp>\ntypedef boost::heap::binomial_heap<ValueKey>  BinomialHeap;\n\n/// Simple Arc class: store tuple (i,j,c)\nclass Arc {\n   public:\n      node_t    w;  /// Target node\n      cost_t    c;  /// Cost of the arc\n      /// Standard constructor\n      Arc ( node_t _w, cost_t _c ) \n         : w(_w), c(_c) {}\n};\n\n/// Forward and Backward star: intrusive list\ntypedef std::vector<Arc>                 FSArcList;\ntypedef FSArcList::iterator              FSArcIter;\n\n///--------------------------------------------------------------------------------\n/// Class of graph to compute RCSP with superadditive cost\nclass Digraph {\n   private:\n      node_t  n;\n      edge_t  m;\n\n      vector<FSArcList>  Nc;   /// Nodes container\n\n      /// Initialize distance vector with Infinity\n      /// Maybe it is better to intialize with an upper bound on the optimal path (optimal rcsp path)\n      const cost_t Inf;\n\n   public:\n      ///Standard constructor\n      Digraph( node_t _n, edge_t _m ) \n         : n(_n), m(_m), Inf(std::numeric_limits<cost_t>::max())\n      {\n         assert( n < Inf && m < Inf );\n         Nc.reserve(n);\n         /// Reserve memory for the set of arcs\n         int avg_degree = m/n+1;\n         for ( int i = 0; i < n; ++i ) {\n            FSArcList tmp;\n            tmp.reserve(avg_degree);\n            Nc.push_back(tmp);\n         }\n      }\n      \n      void addArc( node_t i, node_t j, cost_t c ) {    \n         Nc[i].push_back( Arc(j, c) );\n      }\n     \n      ///--------------------------------------------------\n      /// Shortest Path for a graph with positive weights\n      /// With a Fibonacci Heap, as given in the book \"Algorithms\" by Vazirani et all.\n      /// NOTE: since 'increase' is O(1), while 'decrease' is O(log n)\n      /// We use negative distances in the heap, i.e., we start with distance labels set to -\\infinity\n      /// However, the distance labels are kept with the correct value \n      template <typename PriorityQueue>\n      cost_t spp ( node_t S, node_t T, vector<node_t>& P ) {    \n         typedef typename PriorityQueue::handle_type     handle_t;\n\n         PriorityQueue     H;\n         vector<handle_t>  K(n);\n         vector<Label>     Q(n,UNREACHED);  /// true if it is in the heap\n         \n         /// Initialize the source distance\n         //D[S] = 0;\n         K[S] = H.push( ValueKey(0,S) );\n         while ( !H.empty() ) {\n            /// u = deleteMin(H)\n            ValueKey p = H.top();\n            H.pop();\n            node_t u  = p.u;\n            Q[u] = SCANNED;\n            cost_t Du = -(*K[u]).d;\n            if ( u == T ) { break; }\n            /// for all edges (u, v) \\in E\n            for ( FSArcIter it = Nc[u].begin(), it_end = Nc[u].end(); it != it_end; ++it ) {\n               node_t v   = it->w;\n               if ( Q[v] != SCANNED ) {\n                  cost_t Duv = it->c;\n                  cost_t Dv  = Du + Duv;\n                  if ( Q[v] == UNREACHED ) {\n                     P[v] = u;\n                     Q[v] = LABELED;\n                     K[v] = H.push( ValueKey(-Dv,v) );\n                  } else {\n                     if ( -(*K[v]).d > Dv ) {\n                        P[v] = u;\n                        H.increase( K[v], ValueKey(-Dv,v) );\n                     }\n                  }\n               }\n            }\n         }\n         assert( R[T] == SCANNED );\n         return -(*K[T]).d;\n      }\n};\n\n/// Boost Timer\n#include <boost/progress.hpp>\nusing boost::timer;\n\n#include <fstream>\n\nusing namespace boost;\n\n/// Read input data, build graph, and run Dijkstra\ncost_t runDijkstra( char* argv[] ) {\n   /// Read instance from the OR-lib\n   std::ifstream infile(argv[1]); \n   if (!infile) \n      exit ( EXIT_FAILURE ); \n\n   int n;     /// Number of variables\n   int m;     /// Number of constraints\n\n   // reads file of the form\n   // #nodes #edges\n   // e_1 = v_i v_j cost[e_m]\n   // ..\n   // e_m = v_i v_j cost[e_m]\n   \n   /// Read the first line\n   infile >> n >> m;\n   fprintf(stdout,\"n %d, m %d\\n\", n, m);\n   /// Build the graph\n   Digraph G (n, m);\n   \n   int v, w;\n   cost_t c;\n   for ( int i = 0; i < m; i++ ) {\n      infile >> v >> w >> c;\n      G.addArc(v-1, w-1, c);\n   }\n   \n   vector<node_t> P(n);\n   cost_t T_dist; \n   \n   timer TIMER;\n   for ( int i = 0; i < 50; ++i ) {\n      double t0 = TIMER.elapsed();\n      node_t S = i;\n      node_t T = n-1-i;\n      T_dist = G.spp<BinaryHeap>(S, T, P);\n      fprintf(stdout,\"Time %.4f Cost %\"PRId64\"\\n\", TIMER.elapsed()-t0, T_dist);\n   }\n   fprintf(stdout,\"Tot %.4f\\n\", TIMER.elapsed());\n\n   return T_dist;\n}\n\n///------------------------------------------------------------------------------------------\n/// Main function\nint\nmain (int argc, char **argv)\n{\n   if ( argc != 2 ) {\n      fprintf(stdout, \"usage: ./dijkstra <filename>\\n\");\n      exit ( EXIT_FAILURE );\n   }\n   /// Measure overall time\n   timer TIMER;\n   /// Invoke the different Dijkstra algorithm implementations\n   cost_t T_dist = runDijkstra(argv);\n   /// Print basic figures\n   fprintf(stdout,\"Cost %\"PRId64\" - Time %.3f\\n\", T_dist, TIMER.elapsed());\n\n   return 0;\n}\n", "meta": {"hexsha": "8e55feb3b5fb234e47ef8dec72904292b93a197a", "size": 6446, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Dijkstra/dijkstra.cc", "max_stars_repo_name": "772700563/MyBlogEntries", "max_stars_repo_head_hexsha": "ea579ab0698d59bc1af0fac08a059c16f11336c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-10-20T09:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-05T05:16:33.000Z", "max_issues_repo_path": "Dijkstra/dijkstra.cc", "max_issues_repo_name": "772700563/MyBlogEntries", "max_issues_repo_head_hexsha": "ea579ab0698d59bc1af0fac08a059c16f11336c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-07-08T03:27:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-21T19:35:11.000Z", "max_forks_repo_path": "Dijkstra/dijkstra.cc", "max_forks_repo_name": "772700563/MyBlogEntries", "max_forks_repo_head_hexsha": "ea579ab0698d59bc1af0fac08a059c16f11336c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-08-03T06:33:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T12:58:26.000Z", "avg_line_length": 29.5688073394, "max_line_length": 108, "alphanum_fraction": 0.5349053677, "num_tokens": 1739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4341197992276145}}
{"text": "/*\n-------------------------------------------------------------------------\n   This file is part of BayesOpt, an efficient C++ library for \n   Bayesian optimization.\n\n   Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n   BayesOpt is free software: you can redistribute it and/or modify it \n   under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   BayesOpt is distributed in the hope that it will be useful, but \n   WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.\n------------------------------------------------------------------------\n*/\n\n#include <ctime>\n#include \"bayesopt/bayesopt.h\"                 // For the C API\n#include \"bayesopt/bayesopt.hpp\"               // For the C++ API\n#include <boost/numeric/ublas/assignment.hpp> // <<= op assigment\n\n\n/* Function to be used for C-API testing */\ndouble testFunction(unsigned int n, const double *x,\n\t\t    double *gradient, /* NULL if not needed */\n\t\t    void *func_data)\n{\n  double f = 10.;\n  for (unsigned int i = 0; i < n; ++i)\n    {\n      f += (x[i] - .53) * (x[i] - .53);\n    }\n  return f;\n}\n\n/* Class to be used for C++-API testing */\nclass ExampleQuadratic: public bayesopt::ContinuousModel\n{\n public:\n\n  ExampleQuadratic(size_t dim,bayesopt::Parameters param):\n    ContinuousModel(dim,param) {}\n\n  double evaluateSample( const vectord &Xi ) \n  {\n    double x[100];\n    for (size_t i = 0; i < Xi.size(); ++i)\n      {\n\tx[i] = Xi(i);\t\n      }\n    return testFunction(Xi.size(),x,NULL,NULL);\n  };\n\n\n  bool checkReachability( const vectord &query )\n  { return true; };\n \n};\n\n\nint main(int nargs, char *args[])\n{    \n  int n = 10;                   // Number of dimensions\n  clock_t start, end;\n  double diff,diff2;\n\n  // Common configuration\n  // See parameters.h for the available options.\n  // Some parameters did not need to be changed for default, but we have done it for\n  // illustrative purpose.\n  bayesopt::Parameters par = initialize_parameters_to_default();\n\n  par.kernel.name = \"kSum(kSEISO,kConst)\";\n  par.kernel.hp_mean <<= 1.0, 1.0;\n  par.kernel.hp_std <<= 1.0, 1.0;\n\n  par.mean.name = \"mConst\";\n  par.mean.coef_mean <<= 1.0;\n  par.mean.coef_std <<= 1.0;\n  \n\n  par.surr_name = \"sStudentTProcessJef\";\n  par.noise = 1e-10;\n\n  par.sc_type = SC_MAP;\n  par.l_type = L_EMPIRICAL;\n\n  par.n_iterations = 100;    // Number of iterations\n  par.random_seed = 0;\n  par.n_init_samples = 15;\n  par.n_iter_relearn = 0;\n\n  /*******************************************/\n  std::cout << \"Running C++ interface\" << std::endl;\n\n  ExampleQuadratic opt(n,par);\n  vectord result(n);\n\n  // Run C++ interface\n  start = clock();\n  opt.optimize(result);\n  end = clock();\n  diff = (double)(end-start) / (double)CLOCKS_PER_SEC;\n\n  /*******************************************/\n  std::cout << \"Running C inferface\" << std::endl;\n  \n  // Prepare C interface\n  double low[128], up[128], xmin[128], fmin[128];\n\n  // Lower and upper bounds\n  for (int i = 0; i < n; ++i) \n    {\n      low[i] = 0.;    \n      up[i] = 1.;\n    }\n\n  // Run C interface\n  start = clock();\n  bayes_optimization(n,&testFunction,NULL,low,up,xmin,fmin,par.generate_bopt_params());\n  end = clock();\n  diff2 = (double)(end-start) / (double)CLOCKS_PER_SEC;\n  /*******************************************/\n\n\n  // Results\n  std::cout << \"Final result C++: \" << result << std::endl;\n  std::cout << \"Elapsed time in C++: \" << diff << \" seconds\" << std::endl;\n\n  std::cout << \"Final result C: [\" << n <<\"](\" << xmin[0];\n  for (int i = 1; i < n; ++i )\n    {\n      std::cout << \",\" << xmin[i];      \n    }\n  std::cout << \")\" << std::endl;\n  std::cout << \"Elapsed time in C: \" << diff2 << \" seconds\" << std::endl;\n\n}\n\n", "meta": {"hexsha": "2498a385a00aa559840cf6a9590058c045f777e8", "size": 4043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/examples/bo_cont.cpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/examples/bo_cont.cpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/examples/bo_cont.cpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 27.6917808219, "max_line_length": 87, "alphanum_fraction": 0.581746228, "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203136, "lm_q2_score": 0.6297746213017459, "lm_q1q2_score": 0.4341071757330642}}
{"text": "\r\n#include <NTL/mat_lzz_pE.h>\r\n\r\n#include <NTL/new.h>\r\n\r\nNTL_START_IMPL\r\n\r\n  \r\nvoid add(mat_zz_pE& X, const mat_zz_pE& A, const mat_zz_pE& B)  \r\n{  \r\n   long n = A.NumRows();  \r\n   long m = A.NumCols();  \r\n  \r\n   if (B.NumRows() != n || B.NumCols() != m)   \r\n      LogicError(\"matrix add: dimension mismatch\");  \r\n  \r\n   X.SetDims(n, m);  \r\n  \r\n   long i, j;  \r\n   for (i = 1; i <= n; i++)   \r\n      for (j = 1; j <= m; j++)  \r\n         add(X(i,j), A(i,j), B(i,j));  \r\n}  \r\n  \r\nvoid sub(mat_zz_pE& X, const mat_zz_pE& A, const mat_zz_pE& B)  \r\n{  \r\n   long n = A.NumRows();  \r\n   long m = A.NumCols();  \r\n  \r\n   if (B.NumRows() != n || B.NumCols() != m)  \r\n      LogicError(\"matrix sub: dimension mismatch\");  \r\n  \r\n   X.SetDims(n, m);  \r\n  \r\n   long i, j;  \r\n   for (i = 1; i <= n; i++)  \r\n      for (j = 1; j <= m; j++)  \r\n         sub(X(i,j), A(i,j), B(i,j));  \r\n}  \r\n\r\nvoid negate(mat_zz_pE& X, const mat_zz_pE& A)  \r\n{  \r\n   long n = A.NumRows();  \r\n   long m = A.NumCols();  \r\n  \r\n  \r\n   X.SetDims(n, m);  \r\n  \r\n   long i, j;  \r\n   for (i = 1; i <= n; i++)  \r\n      for (j = 1; j <= m; j++)  \r\n         negate(X(i,j), A(i,j));  \r\n}  \r\n  \r\nvoid mul_aux(mat_zz_pE& X, const mat_zz_pE& A, const mat_zz_pE& B)  \r\n{  \r\n   long n = A.NumRows();  \r\n   long l = A.NumCols();  \r\n   long m = B.NumCols();  \r\n  \r\n   if (l != B.NumRows())  \r\n      LogicError(\"matrix mul: dimension mismatch\");  \r\n  \r\n   X.SetDims(n, m);  \r\n  \r\n   long i, j, k;  \r\n   zz_pX acc, tmp;  \r\n  \r\n   for (i = 1; i <= n; i++) {  \r\n      for (j = 1; j <= m; j++) {  \r\n         clear(acc);  \r\n         for(k = 1; k <= l; k++) {  \r\n            mul(tmp, rep(A(i,k)), rep(B(k,j)));  \r\n            add(acc, acc, tmp);  \r\n         }  \r\n         conv(X(i,j), acc);  \r\n      }  \r\n   }  \r\n}  \r\n  \r\n  \r\nvoid mul(mat_zz_pE& X, const mat_zz_pE& A, const mat_zz_pE& B)  \r\n{  \r\n   if (&X == &A || &X == &B) {  \r\n      mat_zz_pE tmp;  \r\n      mul_aux(tmp, A, B);  \r\n      X = tmp;  \r\n   }  \r\n   else  \r\n      mul_aux(X, A, B);  \r\n}  \r\n  \r\n  \r\nstatic\r\nvoid mul_aux(vec_zz_pE& x, const mat_zz_pE& A, const vec_zz_pE& b)  \r\n{  \r\n   long n = A.NumRows();  \r\n   long l = A.NumCols();  \r\n  \r\n   if (l != b.length())  \r\n      LogicError(\"matrix mul: dimension mismatch\");  \r\n  \r\n   x.SetLength(n);  \r\n  \r\n   long i, k;  \r\n   zz_pX acc, tmp;  \r\n  \r\n   for (i = 1; i <= n; i++) {  \r\n      clear(acc);  \r\n      for (k = 1; k <= l; k++) {  \r\n         mul(tmp, rep(A(i,k)), rep(b(k)));  \r\n         add(acc, acc, tmp);  \r\n      }  \r\n      conv(x(i), acc);  \r\n   }  \r\n}  \r\n  \r\n  \r\nvoid mul(vec_zz_pE& x, const mat_zz_pE& A, const vec_zz_pE& b)  \r\n{  \r\n   if (&b == &x || A.position1(x) != -1) {\r\n      vec_zz_pE tmp;\r\n      mul_aux(tmp, A, b);\r\n      x = tmp;\r\n   }\r\n   else\r\n      mul_aux(x, A, b);\r\n}  \r\n\r\nstatic\r\nvoid mul_aux(vec_zz_pE& x, const vec_zz_pE& a, const mat_zz_pE& B)  \r\n{  \r\n   long n = B.NumRows();  \r\n   long l = B.NumCols();  \r\n  \r\n   if (n != a.length())  \r\n      LogicError(\"matrix mul: dimension mismatch\");  \r\n  \r\n   x.SetLength(l);  \r\n  \r\n   long i, k;  \r\n   zz_pX acc, tmp;  \r\n  \r\n   for (i = 1; i <= l; i++) {  \r\n      clear(acc);  \r\n      for (k = 1; k <= n; k++) {  \r\n         mul(tmp, rep(a(k)), rep(B(k,i)));\r\n         add(acc, acc, tmp);  \r\n      }  \r\n      conv(x(i), acc);  \r\n   }  \r\n}  \r\n\r\nvoid mul(vec_zz_pE& x, const vec_zz_pE& a, const mat_zz_pE& B)\r\n{\r\n   if (&a == &x) {\r\n      vec_zz_pE tmp;\r\n      mul_aux(tmp, a, B);\r\n      x = tmp;\r\n   }\r\n   else\r\n      mul_aux(x, a, B);\r\n\r\n}\r\n\r\n     \r\n  \r\nvoid ident(mat_zz_pE& X, long n)  \r\n{  \r\n   X.SetDims(n, n);  \r\n   long i, j;  \r\n  \r\n   for (i = 1; i <= n; i++)  \r\n      for (j = 1; j <= n; j++)  \r\n         if (i == j)  \r\n            set(X(i, j));  \r\n         else  \r\n            clear(X(i, j));  \r\n} \r\n\r\n\r\nvoid determinant(zz_pE& d, const mat_zz_pE& M_in)\r\n{\r\n   long k, n;\r\n   long i, j;\r\n   long pos;\r\n   zz_pX t1, t2;\r\n   zz_pX *x, *y;\r\n\r\n   const zz_pXModulus& p = zz_pE::modulus();\r\n\r\n   n = M_in.NumRows();\r\n\r\n   if (M_in.NumCols() != n)\r\n      LogicError(\"determinant: nonsquare matrix\");\r\n\r\n   if (n == 0) {\r\n      set(d);\r\n      return;\r\n   }\r\n\r\n\r\n   UniqueArray<vec_zz_pX> M_store;\r\n   M_store.SetLength(n);\r\n   vec_zz_pX *M = M_store.get();\r\n\r\n   for (i = 0; i < n; i++) {\r\n      M[i].SetLength(n);\r\n      for (j = 0; j < n; j++) {\r\n         M[i][j].rep.SetMaxLength(2*deg(p)-1);\r\n         M[i][j] = rep(M_in[i][j]);\r\n      }\r\n   }\r\n\r\n   zz_pX det;\r\n   set(det);\r\n\r\n   for (k = 0; k < n; k++) {\r\n      pos = -1;\r\n      for (i = k; i < n; i++) {\r\n         rem(t1, M[i][k], p);\r\n         M[i][k] = t1;\r\n         if (pos == -1 && !IsZero(t1))\r\n            pos = i;\r\n      }\r\n\r\n      if (pos != -1) {\r\n         if (k != pos) {\r\n            swap(M[pos], M[k]);\r\n            negate(det, det);\r\n         }\r\n\r\n         MulMod(det, det, M[k][k], p);\r\n\r\n         // make M[k, k] == -1 mod p, and make row k reduced\r\n\r\n         InvMod(t1, M[k][k], p);\r\n         negate(t1, t1);\r\n         for (j = k+1; j < n; j++) {\r\n            rem(t2, M[k][j], p);\r\n            MulMod(M[k][j], t2, t1, p);\r\n         }\r\n\r\n         for (i = k+1; i < n; i++) {\r\n            // M[i] = M[i] + M[k]*M[i,k]\r\n\r\n            t1 = M[i][k];   // this is already reduced\r\n\r\n            x = M[i].elts() + (k+1);\r\n            y = M[k].elts() + (k+1);\r\n\r\n            for (j = k+1; j < n; j++, x++, y++) {\r\n               // *x = *x + (*y)*t1\r\n\r\n               mul(t2, *y, t1);\r\n               add(*x, *x, t2);\r\n            }\r\n         }\r\n      }\r\n      else {\r\n         clear(d);\r\n         return;\r\n      }\r\n   }\r\n\r\n   conv(d, det);\r\n}\r\n\r\nlong IsIdent(const mat_zz_pE& A, long n)\r\n{\r\n   if (A.NumRows() != n || A.NumCols() != n)\r\n      return 0;\r\n\r\n   long i, j;\r\n\r\n   for (i = 1; i <= n; i++)\r\n      for (j = 1; j <= n; j++)\r\n         if (i != j) {\r\n            if (!IsZero(A(i, j))) return 0;\r\n         }\r\n         else {\r\n            if (!IsOne(A(i, j))) return 0;\r\n         }\r\n\r\n   return 1;\r\n}\r\n            \r\n\r\nvoid transpose(mat_zz_pE& X, const mat_zz_pE& A)\r\n{\r\n   long n = A.NumRows();\r\n   long m = A.NumCols();\r\n\r\n   long i, j;\r\n\r\n   if (&X == & A) {\r\n      if (n == m)\r\n         for (i = 1; i <= n; i++)\r\n            for (j = i+1; j <= n; j++)\r\n               swap(X(i, j), X(j, i));\r\n      else {\r\n         mat_zz_pE tmp;\r\n         tmp.SetDims(m, n);\r\n         for (i = 1; i <= n; i++)\r\n            for (j = 1; j <= m; j++)\r\n               tmp(j, i) = A(i, j);\r\n         X.kill();\r\n         X = tmp;\r\n      }\r\n   }\r\n   else {\r\n      X.SetDims(m, n);\r\n      for (i = 1; i <= n; i++)\r\n         for (j = 1; j <= m; j++)\r\n            X(j, i) = A(i, j);\r\n   }\r\n}\r\n   \r\n\r\nvoid solve(zz_pE& d, vec_zz_pE& X, \r\n           const mat_zz_pE& A, const vec_zz_pE& b)\r\n\r\n{\r\n   long n = A.NumRows();\r\n   if (A.NumCols() != n)\r\n      LogicError(\"solve: nonsquare matrix\");\r\n\r\n   if (b.length() != n)\r\n      LogicError(\"solve: dimension mismatch\");\r\n\r\n   if (n == 0) {\r\n      set(d);\r\n      X.SetLength(0);\r\n      return;\r\n   }\r\n\r\n   long i, j, k, pos;\r\n   zz_pX t1, t2;\r\n   zz_pX *x, *y;\r\n\r\n   const zz_pXModulus& p = zz_pE::modulus();\r\n\r\n\r\n   UniqueArray<vec_zz_pX> M_store;\r\n   M_store.SetLength(n);\r\n   vec_zz_pX *M = M_store.get();\r\n\r\n   for (i = 0; i < n; i++) {\r\n      M[i].SetLength(n+1);\r\n      for (j = 0; j < n; j++) {\r\n         M[i][j].rep.SetMaxLength(2*deg(p)-1);\r\n         M[i][j] = rep(A[j][i]);\r\n      }\r\n      M[i][n].rep.SetMaxLength(2*deg(p)-1);\r\n      M[i][n] = rep(b[i]);\r\n   }\r\n\r\n   zz_pX det;\r\n   set(det);\r\n\r\n   for (k = 0; k < n; k++) {\r\n      pos = -1;\r\n      for (i = k; i < n; i++) {\r\n         rem(t1, M[i][k], p);\r\n         M[i][k] = t1;\r\n         if (pos == -1 && !IsZero(t1)) {\r\n            pos = i;\r\n         }\r\n      }\r\n\r\n      if (pos != -1) {\r\n         if (k != pos) {\r\n            swap(M[pos], M[k]);\r\n            negate(det, det);\r\n         }\r\n\r\n         MulMod(det, det, M[k][k], p);\r\n\r\n         // make M[k, k] == -1 mod p, and make row k reduced\r\n\r\n         InvMod(t1, M[k][k], p);\r\n         negate(t1, t1);\r\n         for (j = k+1; j <= n; j++) {\r\n            rem(t2, M[k][j], p);\r\n            MulMod(M[k][j], t2, t1, p);\r\n         }\r\n\r\n         for (i = k+1; i < n; i++) {\r\n            // M[i] = M[i] + M[k]*M[i,k]\r\n\r\n            t1 = M[i][k];   // this is already reduced\r\n\r\n            x = M[i].elts() + (k+1);\r\n            y = M[k].elts() + (k+1);\r\n\r\n            for (j = k+1; j <= n; j++, x++, y++) {\r\n               // *x = *x + (*y)*t1\r\n\r\n               mul(t2, *y, t1);\r\n               add(*x, *x, t2);\r\n            }\r\n         }\r\n      }\r\n      else {\r\n         clear(d);\r\n         return;\r\n      }\r\n   }\r\n\r\n   X.SetLength(n);\r\n   for (i = n-1; i >= 0; i--) {\r\n      clear(t1);\r\n      for (j = i+1; j < n; j++) {\r\n         mul(t2, rep(X[j]), M[i][j]);\r\n         add(t1, t1, t2);\r\n      }\r\n      sub(t1, t1, M[i][n]);\r\n      conv(X[i], t1);\r\n   }\r\n\r\n   conv(d, det);\r\n}\r\n\r\nvoid inv(zz_pE& d, mat_zz_pE& X, const mat_zz_pE& A)\r\n{\r\n   long n = A.NumRows();\r\n   if (A.NumCols() != n)\r\n      LogicError(\"inv: nonsquare matrix\");\r\n\r\n   if (n == 0) {\r\n      set(d);\r\n      X.SetDims(0, 0);\r\n      return;\r\n   }\r\n\r\n   long i, j, k, pos;\r\n   zz_pX t1, t2;\r\n   zz_pX *x, *y;\r\n\r\n   const zz_pXModulus& p = zz_pE::modulus();\r\n\r\n\r\n   UniqueArray<vec_zz_pX> M_store;\r\n   M_store.SetLength(n);\r\n   vec_zz_pX *M = M_store.get();\r\n\r\n   for (i = 0; i < n; i++) {\r\n      M[i].SetLength(2*n);\r\n      for (j = 0; j < n; j++) {\r\n         M[i][j].rep.SetMaxLength(2*deg(p)-1);\r\n         M[i][j] = rep(A[i][j]);\r\n         M[i][n+j].rep.SetMaxLength(2*deg(p)-1);\r\n         clear(M[i][n+j]);\r\n      }\r\n      set(M[i][n+i]);\r\n   }\r\n\r\n   zz_pX det;\r\n   set(det);\r\n\r\n   for (k = 0; k < n; k++) {\r\n      pos = -1;\r\n      for (i = k; i < n; i++) {\r\n         rem(t1, M[i][k], p);\r\n         M[i][k] = t1;\r\n         if (pos == -1 && !IsZero(t1)) {\r\n            pos = i;\r\n         }\r\n      }\r\n\r\n      if (pos != -1) {\r\n         if (k != pos) {\r\n            swap(M[pos], M[k]);\r\n            negate(det, det);\r\n         }\r\n\r\n         MulMod(det, det, M[k][k], p);\r\n\r\n         // make M[k, k] == -1 mod p, and make row k reduced\r\n\r\n         InvMod(t1, M[k][k], p);\r\n         negate(t1, t1);\r\n         for (j = k+1; j < 2*n; j++) {\r\n            rem(t2, M[k][j], p);\r\n            MulMod(M[k][j], t2, t1, p);\r\n         }\r\n\r\n         for (i = k+1; i < n; i++) {\r\n            // M[i] = M[i] + M[k]*M[i,k]\r\n\r\n            t1 = M[i][k];   // this is already reduced\r\n\r\n            x = M[i].elts() + (k+1);\r\n            y = M[k].elts() + (k+1);\r\n\r\n            for (j = k+1; j < 2*n; j++, x++, y++) {\r\n               // *x = *x + (*y)*t1\r\n\r\n               mul(t2, *y, t1);\r\n               add(*x, *x, t2);\r\n            }\r\n         }\r\n      }\r\n      else {\r\n         clear(d);\r\n         return;\r\n      }\r\n   }\r\n\r\n   X.SetDims(n, n);\r\n   for (k = 0; k < n; k++) {\r\n      for (i = n-1; i >= 0; i--) {\r\n         clear(t1);\r\n         for (j = i+1; j < n; j++) {\r\n            mul(t2, rep(X[j][k]), M[i][j]);\r\n            add(t1, t1, t2);\r\n         }\r\n         sub(t1, t1, M[i][n+k]);\r\n         conv(X[i][k], t1);\r\n      }\r\n   }\r\n\r\n   conv(d, det);\r\n}\r\n\r\n\r\n\r\nlong gauss(mat_zz_pE& M_in, long w)\r\n{\r\n   long k, l;\r\n   long i, j;\r\n   long pos;\r\n   zz_pX t1, t2, t3;\r\n   zz_pX *x, *y;\r\n\r\n   long n = M_in.NumRows();\r\n   long m = M_in.NumCols();\r\n\r\n   if (w < 0 || w > m)\r\n      LogicError(\"gauss: bad args\");\r\n\r\n   const zz_pXModulus& p = zz_pE::modulus();\r\n\r\n\r\n   UniqueArray<vec_zz_pX> M_store;\r\n   M_store.SetLength(n);\r\n   vec_zz_pX *M = M_store.get();\r\n\r\n   for (i = 0; i < n; i++) {\r\n      M[i].SetLength(m);\r\n      for (j = 0; j < m; j++) {\r\n         M[i][j].rep.SetMaxLength(2*deg(p)-1);\r\n         M[i][j] = rep(M_in[i][j]);\r\n      }\r\n   }\r\n\r\n   l = 0;\r\n   for (k = 0; k < w && l < n; k++) {\r\n\r\n      pos = -1;\r\n      for (i = l; i < n; i++) {\r\n         rem(t1, M[i][k], p);\r\n         M[i][k] = t1;\r\n         if (pos == -1 && !IsZero(t1)) {\r\n            pos = i;\r\n         }\r\n      }\r\n\r\n      if (pos != -1) {\r\n         swap(M[pos], M[l]);\r\n\r\n         InvMod(t3, M[l][k], p);\r\n         negate(t3, t3);\r\n\r\n         for (j = k+1; j < m; j++) {\r\n            rem(M[l][j], M[l][j], p);\r\n         }\r\n\r\n         for (i = l+1; i < n; i++) {\r\n            // M[i] = M[i] + M[l]*M[i,k]*t3\r\n\r\n            MulMod(t1, M[i][k], t3, p);\r\n\r\n            clear(M[i][k]);\r\n\r\n            x = M[i].elts() + (k+1);\r\n            y = M[l].elts() + (k+1);\r\n\r\n            for (j = k+1; j < m; j++, x++, y++) {\r\n               // *x = *x + (*y)*t1\r\n\r\n               mul(t2, *y, t1);\r\n               add(t2, t2, *x);\r\n               *x = t2;\r\n            }\r\n         }\r\n\r\n         l++;\r\n      }\r\n   }\r\n   \r\n   for (i = 0; i < n; i++)\r\n      for (j = 0; j < m; j++)\r\n         conv(M_in[i][j], M[i][j]);\r\n\r\n   return l;\r\n}\r\n\r\nlong gauss(mat_zz_pE& M)\r\n{\r\n   return gauss(M, M.NumCols());\r\n}\r\n\r\nvoid image(mat_zz_pE& X, const mat_zz_pE& A)\r\n{\r\n   mat_zz_pE M;\r\n   M = A;\r\n   long r = gauss(M);\r\n   M.SetDims(r, M.NumCols());\r\n   X = M;\r\n}\r\n\r\nvoid kernel(mat_zz_pE& X, const mat_zz_pE& A)\r\n{\r\n   long m = A.NumRows();\r\n   long n = A.NumCols();\r\n\r\n   mat_zz_pE M;\r\n   long r;\r\n\r\n   transpose(M, A);\r\n   r = gauss(M);\r\n\r\n   X.SetDims(m-r, m);\r\n\r\n   long i, j, k, s;\r\n   zz_pX t1, t2;\r\n\r\n   zz_pE T3;\r\n\r\n   vec_long D;\r\n   D.SetLength(m);\r\n   for (j = 0; j < m; j++) D[j] = -1;\r\n\r\n   vec_zz_pE inverses;\r\n   inverses.SetLength(m);\r\n\r\n   j = -1;\r\n   for (i = 0; i < r; i++) {\r\n      do {\r\n         j++;\r\n      } while (IsZero(M[i][j]));\r\n\r\n      D[j] = i;\r\n      inv(inverses[j], M[i][j]); \r\n   }\r\n\r\n   for (k = 0; k < m-r; k++) {\r\n      vec_zz_pE& v = X[k];\r\n      long pos = 0;\r\n      for (j = m-1; j >= 0; j--) {\r\n         if (D[j] == -1) {\r\n            if (pos == k)\r\n               set(v[j]);\r\n            else\r\n               clear(v[j]);\r\n            pos++;\r\n         }\r\n         else {\r\n            i = D[j];\r\n\r\n            clear(t1);\r\n\r\n            for (s = j+1; s < m; s++) {\r\n               mul(t2, rep(v[s]), rep(M[i][s]));\r\n               add(t1, t1, t2);\r\n            }\r\n\r\n            conv(T3, t1);\r\n            mul(T3, T3, inverses[j]);\r\n            negate(v[j], T3);\r\n         }\r\n      }\r\n   }\r\n}\r\n   \r\nvoid mul(mat_zz_pE& X, const mat_zz_pE& A, const zz_pE& b_in)\r\n{\r\n   zz_pE b = b_in;\r\n   long n = A.NumRows();\r\n   long m = A.NumCols();\r\n\r\n   X.SetDims(n, m);\r\n\r\n   long i, j;\r\n   for (i = 0; i < n; i++)\r\n      for (j = 0; j < m; j++)\r\n         mul(X[i][j], A[i][j], b);\r\n}\r\n\r\nvoid mul(mat_zz_pE& X, const mat_zz_pE& A, const zz_p& b_in)\r\n{\r\n   NTL_zz_pRegister(b);\r\n   b = b_in;\r\n   long n = A.NumRows();\r\n   long m = A.NumCols();\r\n\r\n   X.SetDims(n, m);\r\n\r\n   long i, j;\r\n   for (i = 0; i < n; i++)\r\n      for (j = 0; j < m; j++)\r\n         mul(X[i][j], A[i][j], b);\r\n}\r\n\r\nvoid mul(mat_zz_pE& X, const mat_zz_pE& A, long b_in)\r\n{\r\n   NTL_zz_pRegister(b);\r\n   b = b_in;\r\n   long n = A.NumRows();\r\n   long m = A.NumCols();\r\n\r\n   X.SetDims(n, m);\r\n\r\n   long i, j;\r\n   for (i = 0; i < n; i++)\r\n      for (j = 0; j < m; j++)\r\n         mul(X[i][j], A[i][j], b);\r\n}\r\n\r\nvoid diag(mat_zz_pE& X, long n, const zz_pE& d_in)  \r\n{  \r\n   zz_pE d = d_in;\r\n   X.SetDims(n, n);  \r\n   long i, j;  \r\n  \r\n   for (i = 1; i <= n; i++)  \r\n      for (j = 1; j <= n; j++)  \r\n         if (i == j)  \r\n            X(i, j) = d;  \r\n         else  \r\n            clear(X(i, j));  \r\n} \r\n\r\nlong IsDiag(const mat_zz_pE& A, long n, const zz_pE& d)\r\n{\r\n   if (A.NumRows() != n || A.NumCols() != n)\r\n      return 0;\r\n\r\n   long i, j;\r\n\r\n   for (i = 1; i <= n; i++)\r\n      for (j = 1; j <= n; j++)\r\n         if (i != j) {\r\n            if (!IsZero(A(i, j))) return 0;\r\n         }\r\n         else {\r\n            if (A(i, j) != d) return 0;\r\n         }\r\n\r\n   return 1;\r\n}\r\n\r\n\r\nlong IsZero(const mat_zz_pE& a)\r\n{\r\n   long n = a.NumRows();\r\n   long i;\r\n\r\n   for (i = 0; i < n; i++)\r\n      if (!IsZero(a[i]))\r\n         return 0;\r\n\r\n   return 1;\r\n}\r\n\r\nvoid clear(mat_zz_pE& x)\r\n{\r\n   long n = x.NumRows();\r\n   long i;\r\n   for (i = 0; i < n; i++)\r\n      clear(x[i]);\r\n}\r\n\r\n\r\nmat_zz_pE operator+(const mat_zz_pE& a, const mat_zz_pE& b)\r\n{\r\n   mat_zz_pE res;\r\n   add(res, a, b);\r\n   NTL_OPT_RETURN(mat_zz_pE, res);\r\n}\r\n\r\nmat_zz_pE operator*(const mat_zz_pE& a, const mat_zz_pE& b)\r\n{\r\n   mat_zz_pE res;\r\n   mul_aux(res, a, b);\r\n   NTL_OPT_RETURN(mat_zz_pE, res);\r\n}\r\n\r\nmat_zz_pE operator-(const mat_zz_pE& a, const mat_zz_pE& b)\r\n{\r\n   mat_zz_pE res;\r\n   sub(res, a, b);\r\n   NTL_OPT_RETURN(mat_zz_pE, res);\r\n}\r\n\r\n\r\nmat_zz_pE operator-(const mat_zz_pE& a)\r\n{\r\n   mat_zz_pE res;\r\n   negate(res, a);\r\n   NTL_OPT_RETURN(mat_zz_pE, res);\r\n}\r\n\r\n\r\nvec_zz_pE operator*(const mat_zz_pE& a, const vec_zz_pE& b)\r\n{\r\n   vec_zz_pE res;\r\n   mul_aux(res, a, b);\r\n   NTL_OPT_RETURN(vec_zz_pE, res);\r\n}\r\n\r\nvec_zz_pE operator*(const vec_zz_pE& a, const mat_zz_pE& b)\r\n{\r\n   vec_zz_pE res;\r\n   mul_aux(res, a, b);\r\n   NTL_OPT_RETURN(vec_zz_pE, res);\r\n}\r\n\r\nvoid inv(mat_zz_pE& X, const mat_zz_pE& A)\r\n{\r\n   zz_pE d;\r\n   inv(d, X, A);\r\n   if (d == 0) ArithmeticError(\"inv: non-invertible matrix\");\r\n}\r\n\r\nvoid power(mat_zz_pE& X, const mat_zz_pE& A, const ZZ& e)\r\n{\r\n   if (A.NumRows() != A.NumCols()) LogicError(\"power: non-square matrix\");\r\n\r\n   if (e == 0) {\r\n      ident(X, A.NumRows());\r\n      return;\r\n   }\r\n\r\n   mat_zz_pE T1, T2;\r\n   long i, k;\r\n\r\n   k = NumBits(e);\r\n   T1 = A;\r\n\r\n   for (i = k-2; i >= 0; i--) {\r\n      sqr(T2, T1);\r\n      if (bit(e, i))\r\n         mul(T1, T2, A);\r\n      else\r\n         T1 = T2;\r\n   }\r\n\r\n   if (e < 0)\r\n      inv(X, T1);\r\n   else\r\n      X = T1;\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "2879e4529e634e8a3907f20d638b3ac34997d3ea", "size": 17406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/mat_lzz_pE.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WinNTL-8_1_2/src/mat_lzz_pE.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WinNTL-8_1_2/src/mat_lzz_pE.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.0761245675, "max_line_length": 75, "alphanum_fraction": 0.3827990348, "num_tokens": 6129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.6893056231680122, "lm_q1q2_score": 0.4341071686327798}}
{"text": "/*\n * This member function is defined in a separate source file to allow different\n * optimization options when using clang as it does not allow per function\n * optimizations as does gcc function attributes.\n */\n#include <cmath>\n#include <tuple>\n#include <boost/math/tools/roots.hpp>\n#include \"bicycle/bicycle.h\"\n#include \"constants.h\"\n\nnamespace {\n    inline model::real_t square(model::real_t x) {\n        return x*x;\n    }\n}\n\nnamespace model {\n\nreal_t Bicycle::solve_constraint_pitch(real_t roll, real_t steer, real_t guess, size_t max_iterations) const {\n    // constraint function generated by script 'generate_pitch.py'.\n    static constexpr int digits = std::numeric_limits<real_t>::digits*2/3;\n    static constexpr real_t two = static_cast<real_t>(2.0);\n    static constexpr real_t one_five = static_cast<real_t>(1.5);\n    static constexpr real_t min = static_cast<real_t>(0.0);\n    static constexpr real_t max = constants::pi/2;\n    boost::uintmax_t max_it = max_iterations;\n\n    auto constraint_function = [this, roll, steer](real_t pitch)->std::tuple<real_t, real_t> {\n        return std::make_tuple(\n((m_rf*square(std::cos(pitch))*square(std::cos(roll)) +\n(m_d3*std::sqrt(square(-std::sin(pitch)*std::cos(roll)*std::cos(steer) + std::sin(roll)*std::sin(steer)) +\nsquare(std::cos(pitch))*square(std::cos(roll))) +\nm_rf*(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer)))*(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer)))*std::abs(std::cos(roll)) +\nstd::sqrt(square(-std::sin(pitch)*std::cos(roll)*std::cos(steer) + std::sin(roll)*std::sin(steer)) +\nsquare(std::cos(pitch))*square(std::cos(roll)))*(-m_d1*std::abs(std::cos(roll))*std::sin(pitch) +\nm_d2*std::abs(std::cos(roll))*std::cos(pitch) -\nm_rr*std::cos(roll))*std::cos(roll))/(std::sqrt(square(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer)) + square(std::cos(pitch))*square(std::cos(roll)))*std::abs(std::cos(roll)))\n                ,\n((m_rf*square(std::cos(pitch))*square(std::cos(roll)) +\n(m_d3*std::sqrt(square(-std::sin(pitch)*std::cos(roll)*std::cos(steer) + std::sin(roll)*std::sin(steer)) +\nsquare(std::cos(pitch))*square(std::cos(roll))) +\nm_rf*(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer)))*(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer)))*std::abs(std::cos(roll)) +\nstd::sqrt(square(-std::sin(pitch)*std::cos(roll)*std::cos(steer) + std::sin(roll)*std::sin(steer)) +\nsquare(std::cos(pitch))*square(std::cos(roll)))*(-m_d1*std::abs(std::cos(roll))*std::sin(pitch) +\nm_d2*std::abs(std::cos(roll))*std::cos(pitch) -\nm_rr*std::cos(roll))*std::cos(roll))*((-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer))*std::cos(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(pitch)*std::cos(pitch)*square(std::cos(roll)))/(std::pow(square(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer)) +\nsquare(std::cos(pitch))*square(std::cos(roll)), one_five)*std::abs(std::cos(roll))) +\n((-m_d1*std::abs(std::cos(roll))*std::cos(pitch) -\nm_d2*std::abs(std::cos(roll))*std::sin(pitch))*std::sqrt(square(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer)) + square(std::cos(pitch))*square(std::cos(roll)))*std::cos(roll) +\n(-(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer))*std::cos(pitch)*std::cos(roll)*std::cos(steer) -\nstd::sin(pitch)*std::cos(pitch)*square(std::cos(roll)))*(-m_d1*std::abs(std::cos(roll))*std::sin(pitch) +\nm_d2*std::abs(std::cos(roll))*std::cos(pitch) -\nm_rr*std::cos(roll))*std::cos(roll)/std::sqrt(square(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer)) + square(std::cos(pitch))*square(std::cos(roll))) +\n(-two*m_rf*std::sin(pitch)*std::cos(pitch)*square(std::cos(roll)) -\n(m_d3*std::sqrt(square(-std::sin(pitch)*std::cos(roll)*std::cos(steer) + std::sin(roll)*std::sin(steer)) +\nsquare(std::cos(pitch))*square(std::cos(roll))) +\nm_rf*(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer)))*std::cos(pitch)*std::cos(roll)*std::cos(steer) +\n(m_d3*(-(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer))*std::cos(pitch)*std::cos(roll)*std::cos(steer) -\nstd::sin(pitch)*std::cos(pitch)*square(std::cos(roll)))/std::sqrt(square(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer)) +\nsquare(std::cos(pitch))*square(std::cos(roll))) -\nm_rf*std::cos(pitch)*std::cos(roll)*std::cos(steer))*(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer)))*std::abs(std::cos(roll)))/(std::sqrt(square(-std::sin(pitch)*std::cos(roll)*std::cos(steer) +\nstd::sin(roll)*std::sin(steer)) +\nsquare(std::cos(pitch))*square(std::cos(roll)))*std::abs(std::cos(roll)))\n                );\n    };\n    return boost::math::tools::newton_raphson_iterate(constraint_function, guess, min, max, digits, max_it);\n}\n\n} // namespace model\n", "meta": {"hexsha": "efe7e332124761e1ed2385f31d41945008c742c7", "size": 5023, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/bicycle/bicycle_solve_constraint_pitch.cc", "max_stars_repo_name": "oliverlee/biketest", "max_stars_repo_head_hexsha": "074b0b03455021c52a13efe583b1816bc5daad4e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-12-14T01:22:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-07T05:15:04.000Z", "max_issues_repo_path": "src/bicycle/bicycle_solve_constraint_pitch.cc", "max_issues_repo_name": "oliverlee/biketest", "max_issues_repo_head_hexsha": "074b0b03455021c52a13efe583b1816bc5daad4e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-01-12T15:20:57.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-02T16:09:37.000Z", "max_forks_repo_path": "src/bicycle/bicycle_solve_constraint_pitch.cc", "max_forks_repo_name": "oliverlee/biketest", "max_forks_repo_head_hexsha": "074b0b03455021c52a13efe583b1816bc5daad4e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-07T05:15:05.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T05:15:05.000Z", "avg_line_length": 58.4069767442, "max_line_length": 126, "alphanum_fraction": 0.6633485965, "num_tokens": 1736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.434051511665188}}
{"text": "#include <opengv/optimization_tools/objective_function_tools/OptimalUPnPFunctionInfo.hpp>\n#include <Eigen/Dense>\n#include <opengv/Indices.hpp>\n#include <iostream>\n\nOptimalUPnPFunctionInfo::OptimalUPnPFunctionInfo(const opengv::absolute_pose::AbsoluteAdapterBase & adapter){\n  //Initialize class members\n  Mr  = Eigen::MatrixXd::Zero(9,9);\n  vr  = Eigen::MatrixXd::Zero(9,1);;\n  Mrt = Eigen::MatrixXd::Zero(9,3);\n  vt  = Eigen::MatrixXd::Zero(3,1);\n  Eigen::MatrixXd constant = Eigen::MatrixXd::Zero(1,1); //Used for debugging\n  n   = 0;\n  opengv::Indices indices(adapter.getNumberCorrespondences());\n  int total_points = (int) indices.size();\n  n = total_points;\n  \n  //Used to store all the information needed\n  Eigen::MatrixXd C_all = Eigen::MatrixXd::Zero(3, total_points);\n  Eigen::MatrixXd V_all = Eigen::MatrixXd::Zero(3, total_points);\n  Eigen::MatrixXd X_all = Eigen::MatrixXd::Zero(3, total_points);\n  //**************************\n  Eigen::Matrix3d id = Eigen::Matrix3d::Identity(3,3);\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(3 * n, n + 3);\n  // This time all the information is needed beforehand\n  for( int i = 0; i < total_points; i++ )\n  {\n    C_all.block<3,1>(0,i)  = adapter.getCamOffset(indices[i]);\n    X_all.block<3,1>(0,i)  = adapter.getPoint(indices[i]);\n    V_all.block<3,1>(0,i)  = adapter.getCamRotation(indices[i]) * adapter.getBearingVector(indices[i]);\n    A.block<3,1>(3 * i, i) = adapter.getCamRotation(indices[i]) * adapter.getBearingVector(indices[i]);\n    A.block<3,3>(3 * i, n) = -Eigen::Matrix3d::Identity(3,3);\n  }\n  //std::cout << \"A matrix: \" << std::endl << A << std::endl;\n  Eigen::MatrixXd U = ((A.transpose() * A).inverse() * A.transpose() ).block(0,0, n, 3 * n);\n  //std::cout << \"U\" << std::endl << U << std::endl;\n  /*std::cout << \"Data:\" << std::endl;\n  std::cout << \"ci\" << std::endl << C_all << std::endl;\n  std::cout << \"xi\" << std::endl << X_all << std::endl;\n  std::cout << \"vi\" << std::endl << V_all << std::endl;*/\n\n  Eigen::MatrixXd D = Eigen::MatrixXd::Zero(3,9);\n  Eigen::MatrixXd v = Eigen::MatrixXd::Zero(3,1);\n\n  Eigen::MatrixXd fi = Eigen::MatrixXd::Zero(3,1);\n  Eigen::MatrixXd pi = Eigen::MatrixXd::Zero(3,1);\n  Eigen::MatrixXd vi = Eigen::MatrixXd::Zero(3,1);\n\n  Eigen::MatrixXd fj      = Eigen::MatrixXd::Zero(3,1);\n  Eigen::MatrixXd pj      = Eigen::MatrixXd::Zero(3,1);\n  Eigen::MatrixXd vj      = Eigen::MatrixXd::Zero(3,1);\n  Eigen::MatrixXd u_total = Eigen::MatrixXd::Zero(1, n);\n  Eigen::MatrixXd uij     = Eigen::MatrixXd::Zero(3,1);\n  \n  //Start building the D matrix and v vector from wich the residual can be calculated\n  for(int i = 0; i < n; ++i) {\n    \n    fi = V_all.block<3,1>(0, i);\n    pi = X_all.block<3,1>(0, i);\n    vi = C_all.block<3,1>(0, i);\n    u_total = U.block(i,0, 1, 3 * n);\n    double internal_coefficient = 0;\n    Eigen::MatrixXd internal_vector = Eigen::MatrixXd::Zero(1,9);\n    D = Eigen::MatrixXd::Zero(3,9);\n    v = Eigen::MatrixXd::Zero(3,1);\n    for(int j = 0; j < n; ++j){\n      uij = u_total.block(0, 3 * j , 1, 3);\n      pj = X_all.block<3,1>(0, j);\n      vj = C_all.block<3,1>(0, j);\n      internal_vector.block<1,3>(0,0) = pj(0,0) * uij;\n      internal_vector.block<1,3>(0,3) = pj(1,0) * uij;\n      internal_vector.block<1,3>(0,6) = pj(2,0) * uij;\n     \n      internal_coefficient = internal_coefficient + (uij * vj)(0,0);\n     \n      D = D + (fi * internal_vector);\n    }\n    \n    Eigen::MatrixXd Dr_i = Eigen::MatrixXd::Zero(3,9);\n    Dr_i.block<3,3>(0,0) = pi(0,0) * Eigen::MatrixXd::Identity(3,3);\n    Dr_i.block<3,3>(0,3) = pi(1,0) * Eigen::MatrixXd::Identity(3,3);\n    Dr_i.block<3,3>(0,6) = pi(2,0) * Eigen::MatrixXd::Identity(3,3);\n    D = D - Dr_i;\n    v = vi - fi * internal_coefficient;\n    \n    Mr  = Mr  + D.transpose() * D;\n    Mrt = Mrt - 2 * D.transpose();\n    vr  = vr  + 2 * D.transpose() * v;\n    vt  = vt  - 2 * v;\n    constant = constant + v.transpose() * v;\n  }\n  \n  /*Eigen::MatrixXd r = Eigen::MatrixXd::Zero(9,1);\n  r(0,0) = rot(0,0);\n  r(1,0) = rot(1,0);\n  r(2,0) = rot(2,0);\n  r(3,0) = rot(0,1);\n  r(4,0) = rot(1,1);\n  r(5,0) = rot(2,1);\n  r(6,0) = rot(0,2);\n  r(7,0) = rot(1,2);\n  r(8,0) = rot(2,2);*/\n \n  //std::cout << \"The squared residual: \" << std::endl;\n  //std::cout << (r.transpose() * Mr * r + vr.transpose() * r + r.transpose() * Mrt * trans + vt.transpose() * trans + constant + n * trans.transpose() * trans) << std::endl;\n  /*std::cout << \"Mr:  \"      << std::endl << Mr       << std::endl;\n  std::cout << \"vr:  \"      << std::endl << vr       << std::endl;\n  std::cout << \"Mrt: \"      << std::endl << Mrt      << std::endl;\n  std::cout << \"vt:  \"      << std::endl << vt       << std::endl;\n  std::cout << \"n:   \"      << std::endl << n        << std::endl;\n  std::cout << \"constant: \" << std::endl << constant << std::endl;\n  std::cout << \"R_: \"       << std::endl << rot      << std::endl;\n  std::cout << \"t_: \"       << std::endl << trans    << std::endl;*/ \n}\n\nOptimalUPnPFunctionInfo::~OptimalUPnPFunctionInfo(){};\n\ndouble OptimalUPnPFunctionInfo::objective_function_value(const opengv::rotation_t & rotation, const opengv::translation_t & translation){\n  const double * p = &rotation(0);\n  Map<const Matrix<double,1,9> > r(p, 1, 9);\n  Eigen::MatrixXd e = (r * Mr * r.transpose() + vr.transpose() * r.transpose() + r * Mrt * translation + vt.transpose() * translation + n * translation.transpose() * translation);\n  return ( e(0,0) );\n}\n\nopengv::rotation_t OptimalUPnPFunctionInfo::rotation_gradient(const opengv::rotation_t & rotation, const opengv::translation_t & translation){\n  const double * p = &rotation(0);\n  Map<const Matrix<double,1,9> > r(p, 1, 9);\n  Eigen::MatrixXd result = (2 * Mr * r.transpose()) + ( Mrt * translation ) + vr;\n  double * ptr = &result(0);\n  Map<Matrix<double, 3,3> > m(ptr, 3, 3);\n  return m ;\n}\n\nopengv::translation_t OptimalUPnPFunctionInfo::translation_gradient(const opengv::rotation_t & rotation, const opengv::translation_t & translation){\n  const double * p = &rotation(0);\n  Map<const Matrix<double,1,9> > r(p, 1, 9);\n  return (  2 * n * translation + Mrt.transpose() * r.transpose() + vt )  ;\n}\n", "meta": {"hexsha": "1ac7e2780ebb064682ac6a5894de66029d608444", "size": 6090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimization_tools/objective_function_tools/OptimalUPnPFunctionInfo.cpp", "max_stars_repo_name": "mateus03/2018AMMPoseSolver", "max_stars_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-05-15T12:41:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T10:42:52.000Z", "max_issues_repo_path": "src/optimization_tools/objective_function_tools/OptimalUPnPFunctionInfo.cpp", "max_issues_repo_name": "mateus03/2018AMMPoseSolver", "max_issues_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimization_tools/objective_function_tools/OptimalUPnPFunctionInfo.cpp", "max_forks_repo_name": "mateus03/2018AMMPoseSolver", "max_forks_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-27T18:11:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T18:11:14.000Z", "avg_line_length": 43.8129496403, "max_line_length": 179, "alphanum_fraction": 0.5957307061, "num_tokens": 2044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835371034368, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.434051511665188}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n\n**/\n//==================================================================================================\n#ifndef BOOST_SIMD_HYPERBOLIC_HPP_INCLUDED\n#define BOOST_SIMD_HYPERBOLIC_HPP_INCLUDED\n\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-functions\n    @defgroup group-hyperbolic  Hyperbolic functions\n\n    Those functions provides scalar and SIMD version of\n    hyperbolic  and inverse hyperbolic functions.\n  **/\n\n  /*!\n    @ingroup group-callable\n    @defgroup group-callable-hyperbolic Hyperbolic Callable Objects\n    Callable objects version of @ref group-hyperbolic\n\n    Their specific semantic limitations are similar to those of their function\n    equivalents as described in the @ref group-hyperbolic section.\n  **/\n} }\n\n#include <boost/simd/function/acosh.hpp>\n#include <boost/simd/function/acoth.hpp>\n#include <boost/simd/function/acsch.hpp>\n#include <boost/simd/function/asech.hpp>\n#include <boost/simd/function/asinh.hpp>\n#include <boost/simd/function/atanh.hpp>\n#include <boost/simd/function/cosh.hpp>\n#include <boost/simd/function/coth.hpp>\n#include <boost/simd/function/csch.hpp>\n#include <boost/simd/function/sech.hpp>\n#include <boost/simd/function/sinhc.hpp>\n#include <boost/simd/function/sinhcosh.hpp>\n#include <boost/simd/function/sinh.hpp>\n#include <boost/simd/function/tanh.hpp>\n\n#endif\n", "meta": {"hexsha": "204344f7ed83006d6ec67cddd00a02654437e03d", "size": 1611, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/hyperbolic.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/hyperbolic.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/hyperbolic.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5882352941, "max_line_length": 100, "alphanum_fraction": 0.6672873991, "num_tokens": 354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4339875009477029}}
{"text": "/*--------------------------------------------------------------------\n\nSearch for LCG multiplier using the LLL-Spectral Test!  January 2000\n\nAuthors: Karl Entacher, Karl.Entacher@fh-sbg.ac.at \n\n         Thomas Schell, Dept. of Scientific Computing, Univ. Salzburg\n\n--------------------------------------------------------------------*/\n\n// Modified by e 2018-05-10 for LCG with power of two modulus\n\n\n/*-------------Libraries (needs Victor Shoups NTL-Lib----------------*/\n\n#include <iostream>\n\n#include <fstream>\n\n#include <time.h>\n\n#include <sys/resource.h>\n\n#include <math.h>\n\n#include <float.h>\n\n#include <NTL/ZZ.h>\n\n#include <NTL/RR.h>\n\n#include <NTL/mat_ZZ.h>\n\n#include <NTL/LLL.h>\n\n\n\nusing namespace std;\nusing namespace NTL;\n\n\n/*------------------------ Definitions ------------------------------*/\n\n\n\nZZ lambda, modul, seed;\n\n\n\nstruct {\n\n  ZZ lambda;\n\n  double min_norm_x_x;\n\n} best;\n\n\n#define MAX_DIMS 24\n\n#define DIMS 24 // TODO: make this a command line arg\n\ndouble fact[MAX_DIMS];\n\nRR fact_RR[MAX_DIMS];\n\nconst int x_xmax = DIMS;       /* Test for dimensions <= DIMS */\n\nconst ZZ n_min=to_ZZ(1);\n\n//const ZZ n_max=to_ZZ(10000);\nconst ZZ n_max=to_ZZ(1000000);\n\n\n\n/*-----------------------------------------------------------------------\n\n   Call the function with:\n\n        lll_search [\"output-file\"] [power-of-two-modulus] [seed]\n\n   Example:\n\n        lll_esearch \"output-file\" 340282366920938463463374607431768211456 3\n\n  ----------------------------------------------------------------------*/\n\n\n\nint main(int argc, char *argv[])\n{\n\n/*--------------------------    Input-Check        -----------------------*/\n\n    if (!(argc == 4))\n    {\n        cout << \"lll_search_rnd <output-file-name> <power-of-two-modulus> <seed>\" << endl;\n        exit(0);\n    }\n\n/*--------- reads the input-parameters: \"file\" modulus seed ------*/\n\n    ofstream out_file(argv[1], ios::out);\n\n    modul = to_ZZ(argv[2]);\n\n    //seed = to_ZZ(argv[3]);\n    SetSeed((const unsigned char *)argv[3], strlen(argv[3]));\n\n    long blen = (long )(log(modul)/log(2.0)) - 2L;\n\n/*------------- output of modulus and seed ---------------*/\n\n    out_file << modul;\n\n    //out_file << seed;\n\n    out_file << \" \" << blen;\n\n    out_file << \" \" << RandomBits_ZZ(blen);\n\n    out_file << endl;\n\n\n/*------------- Constants for the normalized Spectral Test   -----------------*/\n\n    fact[0] = 0.0;                                // intentionally left uninitialized -> not used\n\n#if 0\n\n    fact[1] = to_double(to_RR(1.0) / pow(to_RR(4.0/3.0), to_RR(1.0/4.0)) / pow(to_RR(modul), to_RR(1.0/2.0)));\n\n    fact[2] = to_double(to_RR(1.0) / pow(to_RR(2.0), to_RR(1.0/6.0)) / pow(to_RR(modul), to_RR(1.0/3.0)));\n\n    fact[3] = to_double(to_RR(1.0) / pow(to_RR(2.0), to_RR(1.0/4.0)) / pow(to_RR(modul), to_RR(1.0/4.0)));\n\n    fact[4] = to_double(to_RR(1.0) / pow(to_RR(2.0), to_RR(3.0/10.0)) / pow(to_RR(modul), to_RR(1.0/5.0)));\n\n    fact[5] = to_double(to_RR(1.0) / pow(to_RR(64.0/3.0), to_RR(1.0/12.0)) / pow(to_RR(modul), to_RR(1.0/6.0)));\n\n    fact[6] = to_double(to_RR(1.0) / pow(to_RR(2.0), to_RR(3.0/7.0)) / pow(to_RR(modul), to_RR(1.0/7.0)));\n\n    fact[7] = to_double(to_RR(1.0) / pow(to_RR(2.0), to_RR(1.0/2.0)) / pow(to_RR(modul), to_RR(1.0/8.0)));\n\n#else\n\n  fact_RR[0] = to_RR(0.0);  // intentionally left uninitialized -> not used\n\n  fact_RR[1] = to_RR(0.2886751345948128822545744);\n\n  fact_RR[2] = to_RR(0.1767766952966368811002111);\n\n  fact_RR[3] = to_RR(0.125);\n\n  fact_RR[4] = to_RR(0.0883883476483184405501055);\n\n  fact_RR[5] = to_RR(0.0721687836487032205636436);\n\n  fact_RR[6] = to_RR(0.0625);\n\n  fact_RR[7] = to_RR(0.0625);\n\n  fact_RR[8] = to_RR(0.06007);\n\n  fact_RR[9] = to_RR(0.05953);\n\n  fact_RR[10] = to_RR(0.06136);\n\n  fact_RR[11] = to_RR(0.06559);\n\n  fact_RR[12] = to_RR(0.07253);\n\n  fact_RR[13] = to_RR(0.08278);\n\n  fact_RR[14] = to_RR(0.09735);\n\n  fact_RR[15] = to_RR(0.11774);\n\n  fact_RR[16] = to_RR(0.14624);\n\n  fact_RR[17] = to_RR(0.18629);\n\n  fact_RR[18] = to_RR(0.24308);\n\n  fact_RR[19] = to_RR(0.32454);\n\n  fact_RR[20] = to_RR(0.44289);\n\n  fact_RR[21] = to_RR(0.61722);\n\n  fact_RR[22] = to_RR(0.87767);\n\n  fact_RR[23] = to_RR(1.27241);\n\n\n  for (int i = 1; i < x_xmax; i++)\n  {\n    fact[i] = to_double(1 / (to_RR(2) * pow(fact_RR[i] * to_RR(modul), to_RR(1.0) / to_RR(i+1))));\n  }\n\n#endif\n\n/*------------Search, Matrix (Basis) Input, LLL und Output -------------*/\n\n    best.lambda = to_ZZ(0);\n\n    best.min_norm_x_x = 0.0;\n\n    ZZ t_h = to_ZZ(10);\n\n    struct rusage cur_ru;\n\n    for (ZZ n = n_min; n <= n_max; n++)\n    {\n        double min_norm_x_x = 0.0;\n\n        lambda = RandomBits_ZZ(blen) * 4 + 1;\n\n        mat_ZZ x;\n\n        x.SetDims(x_xmax, x_xmax);\n\n        min_norm_x_x = 1.0;\n\n        for (int j = 2; j <= x_xmax; j++)\n        {\n\n            x.SetDims(j,j);\n\n            x[0][0] = modul;     // first index = rows, second index = columns\n\n            for (int i = 1; i < j; i++)          // fill in the 1s\n\n                x[i][i] = 1;\n\n            for (int i = 1; i < j; i++)\n\n                x[i][0] =-(power(lambda, i)); \n\n            ZZ det, rg;\n\n            rg = LLL(det, x, 0);\n\n            double min_x_x = to_double(x[0] * x[0]);\n\n            for (int i = 1; i < j; i++)\n            {\n                double x_x = to_double(x[i] * x[i]);\n\n                if (min_x_x > x_x)\n\n                    min_x_x = x_x;\n            }\n\n            double norm_x_x = fact[j-1] * sqrt(min_x_x);\n\n            if (min_norm_x_x > norm_x_x)\n\n                min_norm_x_x = norm_x_x;\n        }\n\n        if (min_norm_x_x > best.min_norm_x_x)\n        {\n            best.min_norm_x_x = min_norm_x_x;\n\n            best.lambda = lambda;\n\n            getrusage(RUSAGE_SELF, &cur_ru);\n\n            out_file << \"time\\t\" << cur_ru.ru_utime.tv_sec << \"\\tn\\t\" << n << \"\\tl\\t\" << lambda << \"\\t\" << min_norm_x_x << endl;\n        }\n\n        ZZ n_ = n - n_min;\n\n        if (n_ >= t_h)\n        {\n            getrusage(RUSAGE_SELF, &cur_ru);\n\n            cout << n_ << \"\\t\" << cur_ru.ru_utime.tv_sec << endl;\n\n            t_h *= 10;\n        }\n    }\n\n    getrusage(RUSAGE_SELF, &cur_ru);\n\n    cout << \"total time elapsed\\t\" << cur_ru.ru_utime.tv_sec << endl;\n\n    out_file << \"time\\t\" << cur_ru.ru_utime.tv_sec << \"\\tl\\t\" << best.lambda << \"\\t\" << best.min_norm_x_x << endl;\n\n    out_file.close();\n\n}\n", "meta": {"hexsha": "309d2d8ee6f4b11f79484cced30557e60dc125d5", "size": 6279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spectraltest/lll_esearch.cpp", "max_stars_repo_name": "dcurrie/minstd64e", "max_stars_repo_head_hexsha": "4394167cae18052e84bbcb3f20df28508a8ecf26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spectraltest/lll_esearch.cpp", "max_issues_repo_name": "dcurrie/minstd64e", "max_issues_repo_head_hexsha": "4394167cae18052e84bbcb3f20df28508a8ecf26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spectraltest/lll_esearch.cpp", "max_forks_repo_name": "dcurrie/minstd64e", "max_forks_repo_head_hexsha": "4394167cae18052e84bbcb3f20df28508a8ecf26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3571428571, "max_line_length": 128, "alphanum_fraction": 0.5113871636, "num_tokens": 2123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.43398749518696916}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n */\n\n#include <boost/make_shared.hpp>\n#include \"tudat/astro/gravitation/gravityFieldModel.h\"\n\nnamespace tudat\n{\nnamespace gravitation\n{\n\n//! Set predefined central gravity field settings.\nstd::shared_ptr< GravityFieldModel > getPredefinedCentralGravityField(\n    BodiesWithPredefinedCentralGravityFields bodyWithPredefinedCentralGravityField )\n{\n    double gravitationalParameter = 0.0;\n\n    // Select body with prefined central gravity field.\n    switch( bodyWithPredefinedCentralGravityField )\n    {\n    case sun:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 1.32712440018e20;\n\n        break;\n\n    case mercury:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.2, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 2.203289218e13;\n\n        break;\n\n    case venus:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.2, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 3.2485504415e14;\n\n        break;\n\n    case earth:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.2, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 3.9859383624e14;\n\n        break;\n\n    case moon:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.2, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 4.903686391e12;\n\n        break;\n\n    case mars:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.2, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 4.2828018915e13;\n\n        break;\n\n    case jupiter:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.3, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 1.2668579374e17;\n\n        break;\n\n    case saturn:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.3, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 3.793100511400001e16;\n\n        break;\n\n    case uranus:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.3, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 5.793943348799999e15;\n\n        break;\n\n    case neptune:\n\n        // Set gravitational parameter [m^3 s^-2].\n        // Reference: Mass taken from Table 1.3, pg. 6, (de Pater, 2010), value\n        //            of gravitational constant taken from\n        //            http://ssd.jpl.nasa.gov/?constants#ref.\n        gravitationalParameter = 6.834733937e15;\n\n        break;\n\n    default:\n\n        std::string errorMessage = \"Desired predefined central gravity field \" +\n                std::to_string( bodyWithPredefinedCentralGravityField ) +\n                \" does not exist\";\n        throw std::runtime_error( errorMessage );\n    }\n    return std::make_shared< GravityFieldModel >( gravitationalParameter );\n}\n\n} // namespace gravitation\n} // namespace tudat\n", "meta": {"hexsha": "370d907b37f746c5da22c33d826a19980f247bed", "size": 4551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/astro/gravitation/gravityFieldModel.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/astro/gravitation/gravityFieldModel.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/astro/gravitation/gravityFieldModel.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7410071942, "max_line_length": 84, "alphanum_fraction": 0.6099758295, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4339874951869691}}
{"text": "/*\n * MatrixCreator.cc\n *\n *  Created on: 28.06.2017\n *      Author: thies\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/work_stream.h>\n#include <deal.II/fe/fe_update_flags.h>\n#include <forward/MatrixCreator.h>\n\n#include <functional>\n\nnamespace wavepi {\nnamespace forward {\n\nusing namespace dealii;\n\ninline double square(const double x) {\n   return x * x;\n}\n\ntemplate<int dim>\nMatrixCreator<dim>::LaplaceAssemblyScratchData::LaplaceAssemblyScratchData(const FiniteElement<dim> &fe,\n      const Quadrature<dim> &quad)\n      : fe_values(fe, quad, update_values | update_gradients | update_quadrature_points | update_JxW_values) {\n}\n\ntemplate<int dim>\nMatrixCreator<dim>::LaplaceAssemblyScratchData::LaplaceAssemblyScratchData(\n      const LaplaceAssemblyScratchData &scratch_data)\n      :\n            fe_values(scratch_data.fe_values.get_fe(), scratch_data.fe_values.get_quadrature(),\n                  update_values | update_gradients | update_quadrature_points | update_JxW_values) {\n}\n\ntemplate<int dim>\nMatrixCreator<dim>::MassAssemblyScratchData::MassAssemblyScratchData(const FiniteElement<dim> &fe,\n      const Quadrature<dim> &quad)\n      : fe_values(fe, quad, update_values | update_quadrature_points | update_JxW_values) {\n}\n\ntemplate<int dim>\nMatrixCreator<dim>::MassAssemblyScratchData::MassAssemblyScratchData(const MassAssemblyScratchData &scratch_data)\n      :\n            fe_values(scratch_data.fe_values.get_fe(), scratch_data.fe_values.get_quadrature(),\n                  update_values | update_quadrature_points | update_JxW_values) {\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::local_assemble_A_cc(const LightFunction<dim> * const rho, const LightFunction<dim> * const q,\n      const double time, const typename DoFHandler<dim>::active_cell_iterator &cell,\n      LaplaceAssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n      const double val_a = 1.0 / rho->evaluate(scratch_data.fe_values.quadrature_point(q_point), time);\n      const double val_q = q->evaluate(scratch_data.fe_values.quadrature_point(q_point), time);\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n         for (unsigned int j = 0; j < dofs_per_cell; ++j)\n            copy_data.cell_matrix(i, j) += (val_a * scratch_data.fe_values.shape_grad(i, q_point)\n                  * scratch_data.fe_values.shape_grad(j, q_point)\n                  + val_q * scratch_data.fe_values.shape_value(i, q_point)\n                        * scratch_data.fe_values.shape_value(j, q_point)) * scratch_data.fe_values.JxW(q_point);\n      }\n   }\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::local_assemble_A_dd(const Vector<double> &rho, const Vector<double> &q,\n      const typename DoFHandler<dim>::active_cell_iterator &cell, LaplaceAssemblyScratchData &scratch_data,\n      AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n      double val_a = 0;\n      double val_q = 0;\n\n      for (unsigned int k = 0; k < dofs_per_cell; ++k) {\n         const double val_shape = scratch_data.fe_values.shape_value(k, q_point);\n\n         val_a += rho[copy_data.local_dof_indices[k]] * val_shape;\n         val_q += q[copy_data.local_dof_indices[k]] * val_shape;\n      }\n      val_a = 1.0 / val_a;\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n         for (unsigned int j = 0; j < dofs_per_cell; ++j)\n            copy_data.cell_matrix(i, j) += (val_a * scratch_data.fe_values.shape_grad(i, q_point)\n                  * scratch_data.fe_values.shape_grad(j, q_point)\n                  + val_q * scratch_data.fe_values.shape_value(i, q_point)\n                        * scratch_data.fe_values.shape_value(j, q_point)) * scratch_data.fe_values.JxW(q_point);\n   }\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::local_assemble_A_cd(const LightFunction<dim> * const rho, const Vector<double> &q,\n      const double time, const typename DoFHandler<dim>::active_cell_iterator &cell,\n      LaplaceAssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n      const double val_a = 1.0 / rho->evaluate(scratch_data.fe_values.quadrature_point(q_point), time);\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n         for (unsigned int j = 0; j < dofs_per_cell; ++j) {\n            copy_data.cell_matrix(i, j) += val_a * scratch_data.fe_values.shape_grad(i, q_point)\n                  * scratch_data.fe_values.shape_grad(j, q_point) * scratch_data.fe_values.JxW(q_point);\n\n            for (unsigned int k = 0; k < dofs_per_cell; ++k)\n               copy_data.cell_matrix(i, j) += q[copy_data.local_dof_indices[k]]\n                     * scratch_data.fe_values.shape_value(k, q_point) * scratch_data.fe_values.shape_value(i, q_point)\n                     * scratch_data.fe_values.shape_value(j, q_point) * scratch_data.fe_values.JxW(q_point);\n         }\n      }\n   }\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::local_assemble_A_dc(const Vector<double> &rho, const LightFunction<dim> * const q,\n      const double time, const typename DoFHandler<dim>::active_cell_iterator &cell,\n      LaplaceAssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n      const double val_q = q->evaluate(scratch_data.fe_values.quadrature_point(q_point), time);\n\n      double val_a = 0;\n      for (unsigned int k = 0; k < dofs_per_cell; ++k)\n         val_a += rho[copy_data.local_dof_indices[k]] * scratch_data.fe_values.shape_value(k, q_point);\n      val_a = 1.0 / val_a;\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n         for (unsigned int j = 0; j < dofs_per_cell; ++j) {\n            copy_data.cell_matrix(i, j) += (val_q * scratch_data.fe_values.shape_value(i, q_point)\n                  * scratch_data.fe_values.shape_value(j, q_point)\n                  + val_a * scratch_data.fe_values.shape_grad(i, q_point)\n                        * scratch_data.fe_values.shape_grad(j, q_point)) * scratch_data.fe_values.JxW(q_point);\n         }\n      }\n   }\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::local_assemble_mass_d(const Vector<double> &c,\n      const typename DoFHandler<dim>::active_cell_iterator &cell, MassAssemblyScratchData &scratch_data,\n      AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n         for (unsigned int j = 0; j < dofs_per_cell; ++j)\n            for (unsigned int k = 0; k < dofs_per_cell; ++k)\n               copy_data.cell_matrix(i, j) += c[copy_data.local_dof_indices[k]]\n                     * scratch_data.fe_values.shape_value(k, q_point) * scratch_data.fe_values.shape_value(i, q_point)\n                     * scratch_data.fe_values.shape_value(j, q_point) * scratch_data.fe_values.JxW(q_point);\n   }\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::local_assemble_mass_c(const LightFunction<dim> * const c, const double time,\n      const typename DoFHandler<dim>::active_cell_iterator &cell, MassAssemblyScratchData &scratch_data,\n      AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n      const double val = c->evaluate(scratch_data.fe_values.quadrature_point(q_point), time);\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n         for (unsigned int j = 0; j < dofs_per_cell; ++j)\n            copy_data.cell_matrix(i, j) += val * scratch_data.fe_values.shape_value(i, q_point)\n                  * scratch_data.fe_values.shape_value(j, q_point) * scratch_data.fe_values.JxW(q_point);\n   }\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::local_assemble_C_cc(const LightFunction<dim> * const rho, const LightFunction<dim> * const c,\n      const double time_rho, const double time_c, const typename DoFHandler<dim>::active_cell_iterator &cell,\n      MassAssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n      const double val_a = 1.0 / rho->evaluate(scratch_data.fe_values.quadrature_point(q_point), time_rho);\n      const double val_c = 1.0 / square(c->evaluate(scratch_data.fe_values.quadrature_point(q_point), time_c));\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n         for (unsigned int j = 0; j < dofs_per_cell; ++j)\n            copy_data.cell_matrix(i, j) += val_c * val_a * scratch_data.fe_values.shape_value(i, q_point)\n                  * scratch_data.fe_values.shape_value(j, q_point) * scratch_data.fe_values.JxW(q_point);\n   }\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::local_assemble_C_dd(const Vector<double> &rho, const Vector<double> &c,\n      const typename DoFHandler<dim>::active_cell_iterator &cell, MassAssemblyScratchData &scratch_data,\n      AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n      double val_a = 0;\n      double val_c = 0;\n\n      for (unsigned int k = 0; k < dofs_per_cell; ++k) {\n         const double val_shape = scratch_data.fe_values.shape_value(k, q_point);\n\n         val_a += rho[copy_data.local_dof_indices[k]] * val_shape;\n         val_c += c[copy_data.local_dof_indices[k]] * val_shape;\n      }\n\n      val_a = 1.0 / val_a;\n      val_c = 1.0 / (val_c * val_c);\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n         for (unsigned int j = 0; j < dofs_per_cell; ++j)\n            copy_data.cell_matrix(i, j) += val_c * val_a * scratch_data.fe_values.shape_value(i, q_point)\n                  * scratch_data.fe_values.shape_value(j, q_point) * scratch_data.fe_values.JxW(q_point);\n   }\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::local_assemble_C_cd(const LightFunction<dim> * const rho, const Vector<double> &c,\n      const double time_rho, const typename DoFHandler<dim>::active_cell_iterator &cell,\n      MassAssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n      const double val_a = 1.0 / rho->evaluate(scratch_data.fe_values.quadrature_point(q_point), time_rho);\n\n      double val_c = 0;\n      for (unsigned int k = 0; k < dofs_per_cell; ++k)\n         val_c += c[copy_data.local_dof_indices[k]] * scratch_data.fe_values.shape_value(k, q_point);\n      val_c = 1.0 / (val_c * val_c);\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n         for (unsigned int j = 0; j < dofs_per_cell; ++j)\n            copy_data.cell_matrix(i, j) += val_c * val_a * scratch_data.fe_values.shape_value(i, q_point)\n                  * scratch_data.fe_values.shape_value(j, q_point) * scratch_data.fe_values.JxW(q_point);\n      }\n   }\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::local_assemble_C_dc(const Vector<double> &rho, const LightFunction<dim> * const c,\n      const double time_c, const typename DoFHandler<dim>::active_cell_iterator &cell,\n      MassAssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n      const double val_c = 1.0 / square(c->evaluate(scratch_data.fe_values.quadrature_point(q_point), time_c));\n\n      double val_a = 0;\n      for (unsigned int k = 0; k < dofs_per_cell; ++k)\n         val_a += rho[copy_data.local_dof_indices[k]] * scratch_data.fe_values.shape_value(k, q_point);\n      val_a = 1.0 / val_a;\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n         for (unsigned int j = 0; j < dofs_per_cell; ++j)\n            copy_data.cell_matrix(i, j) += val_c * val_a * scratch_data.fe_values.shape_value(i, q_point)\n                  * scratch_data.fe_values.shape_value(j, q_point) * scratch_data.fe_values.JxW(q_point);\n      }\n   }\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::local_assemble_D_intermediate_d(const Vector<double> &rho_current,\n      const Vector<double> &rho_next, const typename DoFHandler<dim>::active_cell_iterator &cell,\n      MassAssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n      double val_current = 0;\n      double val_next = 0;\n\n      for (unsigned int k = 0; k < dofs_per_cell; ++k) {\n         const double val_shape = scratch_data.fe_values.shape_value(k, q_point);\n\n         val_current += rho_current[copy_data.local_dof_indices[k]] * val_shape;\n         val_next += rho_next[copy_data.local_dof_indices[k]] * val_shape;\n      }\n\n      val_next = 1.0 / val_next;\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n         for (unsigned int j = 0; j < dofs_per_cell; ++j)\n            copy_data.cell_matrix(i, j) += val_current * val_next * scratch_data.fe_values.shape_value(i, q_point)\n                  * scratch_data.fe_values.shape_value(j, q_point) * scratch_data.fe_values.JxW(q_point);\n   }\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::local_assemble_D_intermediate_c(const LightFunction<dim> * const rho,\n      const double time_current, const double time_next, const typename DoFHandler<dim>::active_cell_iterator &cell,\n      MassAssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {\n   const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;\n   const unsigned int n_q_points = scratch_data.fe_values.get_quadrature().size();\n\n   copy_data.cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n   copy_data.local_dof_indices.resize(dofs_per_cell);\n   scratch_data.fe_values.reinit(cell);\n\n   cell->get_dof_indices(copy_data.local_dof_indices);\n\n   for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n      const double val_current = rho->evaluate(scratch_data.fe_values.quadrature_point(q_point), time_current);\n      const double val_next = 1.0 / rho->evaluate(scratch_data.fe_values.quadrature_point(q_point), time_next);\n\n      for (unsigned int i = 0; i < dofs_per_cell; ++i)\n         for (unsigned int j = 0; j < dofs_per_cell; ++j)\n            copy_data.cell_matrix(i, j) += val_current * val_next * scratch_data.fe_values.shape_value(i, q_point)\n                  * scratch_data.fe_values.shape_value(j, q_point) * scratch_data.fe_values.JxW(q_point);\n   }\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::copy_local_to_global(SparseMatrix<double> &matrix, const AssemblyCopyData &copy_data) {\n   for (unsigned int i = 0; i < copy_data.local_dof_indices.size(); ++i) {\n      for (unsigned int j = 0; j < copy_data.local_dof_indices.size(); ++j)\n         matrix.add(copy_data.local_dof_indices[i], copy_data.local_dof_indices[j], copy_data.cell_matrix(i, j));\n   }\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::create_A_matrix(std::shared_ptr<DoFHandler<dim>> dof, const Quadrature<dim> &quad,\n      SparseMatrix<double> &matrix, std::shared_ptr<LightFunction<dim>> rho, std::shared_ptr<LightFunction<dim>> q,\n      const double time) {\n   AssertThrow(rho, ExcZero());\n   AssertThrow(q, ExcZero());\n\n   WorkStream::run(dof->begin_active(), dof->end(),\n         std::bind(&MatrixCreator<dim>::local_assemble_A_cc, rho.get(), q.get(), time, std::placeholders::_1,\n               std::placeholders::_2, std::placeholders::_3),\n         std::bind(&MatrixCreator<dim>::copy_local_to_global, std::ref(matrix), std::placeholders::_1),\n         LaplaceAssemblyScratchData(dof->get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::create_A_matrix(std::shared_ptr<DoFHandler<dim>> dof, const Quadrature<dim> &quad,\n      SparseMatrix<double> &matrix, std::shared_ptr<LightFunction<dim>> rho, const Vector<double> &q,\n      const double time) {\n   AssertThrow(rho, ExcZero());\n   Assert(q.size() == dof->n_dofs(), ExcDimensionMismatch(q.size(), dof->n_dofs()));\n\n   WorkStream::run(dof->begin_active(), dof->end(),\n         std::bind(&MatrixCreator<dim>::local_assemble_A_cd, rho.get(), std::ref(q), time, std::placeholders::_1,\n               std::placeholders::_2, std::placeholders::_3),\n         std::bind(&MatrixCreator<dim>::copy_local_to_global, std::ref(matrix), std::placeholders::_1),\n         LaplaceAssemblyScratchData(dof->get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::create_A_matrix(std::shared_ptr<DoFHandler<dim>> dof, const Quadrature<dim> &quad,\n      SparseMatrix<double> &matrix, const Vector<double> &rho, std::shared_ptr<LightFunction<dim>> q,\n      const double time) {\n   AssertThrow(q, ExcZero());\n   Assert(rho.size() == dof->n_dofs(), ExcDimensionMismatch(rho.size(), dof->n_dofs()));\n\n   WorkStream::run(dof->begin_active(), dof->end(),\n         std::bind(&MatrixCreator<dim>::local_assemble_A_dc, std::ref(rho), q.get(), time, std::placeholders::_1,\n               std::placeholders::_2, std::placeholders::_3),\n         std::bind(&MatrixCreator<dim>::copy_local_to_global, std::ref(matrix), std::placeholders::_1),\n         LaplaceAssemblyScratchData(dof->get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::create_A_matrix(std::shared_ptr<DoFHandler<dim>> dof, const Quadrature<dim> &quad,\n      SparseMatrix<double> &matrix, const Vector<double> &rho, const Vector<double> &q) {\n   Assert(rho.size() == dof->n_dofs(), ExcDimensionMismatch(rho.size(), dof->n_dofs()));\n   Assert(q.size() == dof->n_dofs(), ExcDimensionMismatch(q.size(), dof->n_dofs()));\n\n   WorkStream::run(dof->begin_active(), dof->end(),\n         std::bind(&MatrixCreator<dim>::local_assemble_A_dd, std::ref(rho), std::ref(q), std::placeholders::_1,\n               std::placeholders::_2, std::placeholders::_3),\n         std::bind(&MatrixCreator<dim>::copy_local_to_global, std::ref(matrix), std::placeholders::_1),\n         LaplaceAssemblyScratchData(dof->get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::create_C_matrix(std::shared_ptr<DoFHandler<dim>> dof, const Quadrature<dim> &quad,\n      SparseMatrix<double> &matrix, std::shared_ptr<LightFunction<dim>> rho, std::shared_ptr<LightFunction<dim>> c,\n      const double time_rho, const double time_c) {\n   AssertThrow(rho, ExcZero());\n   AssertThrow(c, ExcZero());\n\n   WorkStream::run(dof->begin_active(), dof->end(),\n         std::bind(&MatrixCreator<dim>::local_assemble_C_cc, rho.get(), c.get(), time_rho, time_c,\n               std::placeholders::_1, std::placeholders::_2, std::placeholders::_3),\n         std::bind(&MatrixCreator<dim>::copy_local_to_global, std::ref(matrix), std::placeholders::_1),\n         MassAssemblyScratchData(dof->get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::create_C_matrix(std::shared_ptr<DoFHandler<dim>> dof, const Quadrature<dim> &quad,\n      SparseMatrix<double> &matrix, std::shared_ptr<LightFunction<dim>> rho, const Vector<double> &c,\n      const double time_rho) {\n   AssertThrow(rho, ExcZero());\n   Assert(c.size() == dof->n_dofs(), ExcDimensionMismatch(c.size(), dof->n_dofs()));\n\n   WorkStream::run(dof->begin_active(), dof->end(),\n         std::bind(&MatrixCreator<dim>::local_assemble_C_cd, rho.get(), std::ref(c), time_rho, std::placeholders::_1,\n               std::placeholders::_2, std::placeholders::_3),\n         std::bind(&MatrixCreator<dim>::copy_local_to_global, std::ref(matrix), std::placeholders::_1),\n         MassAssemblyScratchData(dof->get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::create_C_matrix(std::shared_ptr<DoFHandler<dim>> dof, const Quadrature<dim> &quad,\n      SparseMatrix<double> &matrix, const Vector<double> &rho, std::shared_ptr<LightFunction<dim>> c,\n      const double time_c) {\n   AssertThrow(c, ExcZero());\n   Assert(rho.size() == dof->n_dofs(), ExcDimensionMismatch(rho.size(), dof->n_dofs()));\n\n   WorkStream::run(dof->begin_active(), dof->end(),\n         std::bind(&MatrixCreator<dim>::local_assemble_C_dc, std::ref(rho), c.get(), time_c, std::placeholders::_1,\n               std::placeholders::_2, std::placeholders::_3),\n         std::bind(&MatrixCreator<dim>::copy_local_to_global, std::ref(matrix), std::placeholders::_1),\n         MassAssemblyScratchData(dof->get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::create_C_matrix(std::shared_ptr<DoFHandler<dim>> dof, const Quadrature<dim> &quad,\n      SparseMatrix<double> &matrix, const Vector<double> &rho, const Vector<double> &c) {\n   Assert(rho.size() == dof->n_dofs(), ExcDimensionMismatch(rho.size(), dof->n_dofs()));\n   Assert(c.size() == dof->n_dofs(), ExcDimensionMismatch(c.size(), dof->n_dofs()));\n\n   WorkStream::run(dof->begin_active(), dof->end(),\n         std::bind(&MatrixCreator<dim>::local_assemble_C_dd, std::ref(rho), std::ref(c), std::placeholders::_1,\n               std::placeholders::_2, std::placeholders::_3),\n         std::bind(&MatrixCreator<dim>::copy_local_to_global, std::ref(matrix), std::placeholders::_1),\n         MassAssemblyScratchData(dof->get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::create_D_intermediate_matrix(std::shared_ptr<DoFHandler<dim>> dof, const Quadrature<dim> &quad,\n      SparseMatrix<double> &matrix, const Vector<double> &rho_current, const Vector<double> &rho_next) {\n   Assert(rho_current.size() == dof->n_dofs(), ExcDimensionMismatch(rho_current.size(), dof->n_dofs()));\n   Assert(rho_next.size() == dof->n_dofs(), ExcDimensionMismatch(rho_next.size(), dof->n_dofs()));\n\n   WorkStream::run(dof->begin_active(), dof->end(),\n         std::bind(&MatrixCreator<dim>::local_assemble_D_intermediate_d, std::ref(rho_current), std::ref(rho_next),\n               std::placeholders::_1, std::placeholders::_2, std::placeholders::_3),\n         std::bind(&MatrixCreator<dim>::copy_local_to_global, std::ref(matrix), std::placeholders::_1),\n         MassAssemblyScratchData(dof->get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::create_D_intermediate_matrix(std::shared_ptr<DoFHandler<dim>> dof, const Quadrature<dim> &quad,\n      SparseMatrix<double> &matrix, std::shared_ptr<LightFunction<dim>> rho, double current_time, double next_time) {\n   AssertThrow(rho, ExcZero());\n\n   WorkStream::run(dof->begin_active(), dof->end(),\n         std::bind(&MatrixCreator<dim>::local_assemble_D_intermediate_c, rho.get(), current_time, next_time,\n               std::placeholders::_1, std::placeholders::_2, std::placeholders::_3),\n         std::bind(&MatrixCreator<dim>::copy_local_to_global, std::ref(matrix), std::placeholders::_1),\n         MassAssemblyScratchData(dof->get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::create_mass_matrix(std::shared_ptr<DoFHandler<dim>> dof, const Quadrature<dim> &quad,\n      SparseMatrix<double> &matrix, const Vector<double> &c) {\n   Assert(c.size() == dof->n_dofs(), ExcDimensionMismatch(c.size(), dof->n_dofs()));\n\n   WorkStream::run(dof->begin_active(), dof->end(),\n         std::bind(&MatrixCreator<dim>::local_assemble_mass_d, std::ref(c), std::placeholders::_1,\n               std::placeholders::_2, std::placeholders::_3),\n         std::bind(&MatrixCreator<dim>::copy_local_to_global, std::ref(matrix), std::placeholders::_1),\n         MassAssemblyScratchData(dof->get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate<int dim>\nvoid MatrixCreator<dim>::create_mass_matrix(std::shared_ptr<DoFHandler<dim>> dof, const Quadrature<dim> &quad,\n      SparseMatrix<double> &matrix, std::shared_ptr<LightFunction<dim>> c, const double time) {\n   AssertThrow(c, ExcZero());\n\n   WorkStream::run(dof->begin_active(), dof->end(),\n         std::bind(&MatrixCreator<dim>::local_assemble_mass_c, c.get(), time, std::placeholders::_1,\n               std::placeholders::_2, std::placeholders::_3),\n         std::bind(&MatrixCreator<dim>::copy_local_to_global, std::ref(matrix), std::placeholders::_1),\n         MassAssemblyScratchData(dof->get_fe(), quad), AssemblyCopyData());\n}\n\ntemplate class MatrixCreator<1> ;\ntemplate class MatrixCreator<2> ;\ntemplate class MatrixCreator<3> ;\n\n}  // namespace forward\n} /* namespace wavepi */\n", "meta": {"hexsha": "e62e931bb66c312d530c66ed5ffebdd9c51156ce", "size": 28123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/forward/MatrixCreator.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/forward/MatrixCreator.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/forward/MatrixCreator.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.6872791519, "max_line_length": 120, "alphanum_fraction": 0.7039078334, "num_tokens": 7207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4339874951869691}}
{"text": "/**\n *          Copyright Matthias Walter 2010.\n * Distributed under the Boost Software License, Version 1.0.\n *    (See accompanying file LICENSE_1_0.txt or copy at\n *          http://www.boost.org/LICENSE_1_0.txt)\n **/\n\n#ifndef SIGNING_HPP_\n#define SIGNING_HPP_\n\n#include \"total_unimodularity.hpp\"\n\n#include <set>\n\n#include <boost/type_traits/is_const.hpp>\n\n#include \"matrix_transposed.hpp\"\n#include \"matrix_permuted.hpp\"\n#include \"matrix_reorder.hpp\"\n#include \"matrix.hpp\"\n#include \"bipartite_graph_bfs.hpp\"\n\nnamespace unimod\n{\n\n  /**\n   * Generic function to find a non-zero column and swap it to a given position.\n   *\n   * @param matrix The given matrix\n   * @param column_first First index of a column range\n   * @param column_beyond Beyond index of a column range\n   * @param row_first First index of a row range\n   * @param row_beyond Beyond index of a row range\n   * @param target_column Column to be swapped to\n   * @return Whether a non-zero column was found.\n   */\n\n  template <typename MatrixType>\n  bool find_nonzero_column(MatrixType& matrix, size_t column_first, size_t column_beyond, size_t row_first, size_t row_beyond, size_t target_column)\n  {\n    for (size_t column = column_first; column < column_beyond; ++column)\n    {\n      for (size_t row = row_first; row < row_beyond; ++row)\n      {\n        if (matrix(row, column) != 0)\n        {\n          matrix_permute2(matrix, target_column, column);\n          return true;\n        }\n\n      }\n    }\n    return false;\n  }\n\n  /**\n   * Takes a spanning tree in the bipartite graph of a matrix and a set of nodes to be signed.\n   *\n   * @param matrix The given matrix\n   * @param spanning_tree A spanning tree\n   * @param dim Index-mapping for bipartite graph\n   * @param nodes Set of nodes\n   * @param current_index Current index in the spanning tree\n   * @param column The column to be signed\n   * @param changes Necessary changes to the entries in the column\n   */\n\n  template <typename MatrixType>\n  void check_sign(const MatrixType& matrix, const std::vector <bipartite_graph_bfs_node>& spanning_tree, const bipartite_graph_dimensions& dim,\n      const std::set <size_t>& nodes, size_t current_index, size_t column, std::map <size_t, bool>& changes)\n  {\n    /// Root does never change.\n    if (spanning_tree[current_index].predecessor == current_index)\n    {\n      changes[dim.index_to_row(current_index)] = false;\n      return;\n    }\n\n    /// Search for ancestors until reaching one of the given nodes.\n    int value = matrix(dim.index_to_row(current_index), column);\n    size_t last, index = current_index;\n    do\n    {\n      last = index;\n      index = spanning_tree[index].predecessor;\n      std::pair <size_t, size_t> coords = dim.indexes_to_coordinates(index, last);\n      value += matrix(coords.first, coords.second);\n    }\n    while (nodes.find(index) == nodes.end());\n\n    /// If the ancestor is not yet processed, we recurse.\n    if (changes.find(dim.index_to_row(index)) == changes.end())\n    {\n      check_sign(matrix, spanning_tree, dim, nodes, index, column, changes);\n    }\n\n    value += matrix(dim.index_to_row(index), column);\n    if (changes[dim.index_to_row(index)])\n    {\n      value += 2;\n    }\n\n    value = (value >= 0 ? value : -value) % 4;\n    /// If sum (modulo 4) is not 0, we'd like to change the current one\n    changes[dim.index_to_row(current_index)] = (value == 2);\n\n    if (value != 0 && value != 2)\n    {\n      throw std::logic_error(\"Signing procedure: modulo-sum of cycle was neither 0, nor 2!\");\n    }\n  }\n\n  /**\n   * A functor which compares the absolute values.\n   */\n\n  template <typename T>\n  struct abs_greater\n  {\n    /**\n     * Comparison function\n     *\n     * @param first First value\n     * @param second Second value\n     * @return true if and only if the |first| > |second|\n     */\n\n    bool operator()(const T& first, const T& second)\n    {\n      T abs_first = first >= 0 ? first : -first;\n      T abs_second = second >= 0 ? second : -second;\n      return abs_first > abs_second;\n    }\n  };\n\n  /**\n   * Generic signing function of a matrix, which might also be const.\n   * Running time: O (height * width^2)\n   *\n   * @param matrix The given matrix\n   * @param violator Pointer to violator indices to be filled.\n   * @return true if and only if the matrix is signed already.\n   */\n\n  template <typename M>\n  bool sign_matrix(M& matrix, submatrix_indices* violator)\n  {\n    bool result = true;\n    matrix_permuted <M> permuted(matrix);\n    size_t handled_rows = 0;\n\n    /// Go trough column by column.\n    for (size_t handled_columns = 0; handled_columns < permuted.size2(); ++handled_columns)\n    {\n      if (find_nonzero_column(permuted, handled_columns, permuted.size2(), 0, handled_rows, handled_columns))\n      {\n        /// There is a non-zero column right of the already-handled submatrix.\n\n        std::set <size_t> start_nodes;\n        std::set <size_t> end_nodes;\n        std::set <size_t> all_nodes;\n\n        bipartite_graph_dimensions dim(handled_rows, handled_columns);\n        for (size_t row = 0; row < handled_rows; ++row)\n        {\n          if (permuted(row, handled_columns) != 0)\n          {\n            size_t index = dim.row_to_index(row);\n            if (start_nodes.empty())\n              start_nodes.insert(index);\n            else\n              end_nodes.insert(index);\n            all_nodes.insert(index);\n          }\n        }\n\n        /// Start a BFS on bipartite graph of the submatrix and look for shortest paths from first 1 to all others\n\n        std::vector <bipartite_graph_bfs_node> bfs_result;\n        if (!bipartite_graph_bfs(permuted, dim, start_nodes, end_nodes, true, bfs_result))\n          throw std::logic_error(\"Signing procedure: Did not reach all nodes via bfs!\");\n\n        /// Evaluate matrix-entries on the shortest paths\n        std::map <size_t, bool> changes;\n        for (typename std::set <size_t>::const_iterator iter = end_nodes.begin(); iter != end_nodes.end(); ++iter)\n        {\n          check_sign(permuted, bfs_result, dim, all_nodes, *iter, handled_columns, changes);\n        }\n\n        /// Checking changes\n        for (std::map <size_t, bool>::iterator iter = changes.begin(); iter != changes.end(); ++iter)\n        {\n          if (!iter->second)\n            continue;\n\n          if (boost::is_const <M>::value)\n          {\n            if (violator)\n            {\n              /// Find the violator, going along the path\n              std::set <size_t> violator_rows, violator_columns;\n\n              size_t index = iter->first;\n              do\n              {\n                if (dim.is_row(index))\n                  violator_rows.insert(permuted.perm1()(dim.index_to_row(index)));\n                else\n                  violator_columns.insert(permuted.perm2()(dim.index_to_column(index)));\n\n                index = bfs_result[index].predecessor;\n              }\n              while (all_nodes.find(index) == all_nodes.end());\n              violator_rows.insert(permuted.perm1()(dim.index_to_row(index)));\n              violator_columns.insert(permuted.perm2()(handled_columns));\n\n              /// Fill violator data\n              violator->rows = submatrix_indices::indirect_array_type(violator_rows.size());\n              violator->columns = submatrix_indices::indirect_array_type(violator_columns.size());\n              size_t i = 0;\n              for (std::set <size_t>::const_iterator iter = violator_rows.begin(); iter != violator_rows.end(); ++iter)\n                violator->rows[i++] = *iter;\n              i = 0;\n              for (std::set <size_t>::const_iterator iter = violator_columns.begin(); iter != violator_columns.end(); ++iter)\n                violator->columns[i++] = *iter;\n            }\n            return false;\n          }\n          else\n          {\n            /// We are not just testing, so swap the sign on a one.\n            size_t real_row = permuted.perm1()(dim.index_to_row(iter->first));\n            size_t real_column = permuted.perm2()(handled_columns);\n            matrix_set_value(matrix, real_row, real_column, -matrix(real_row, real_column));\n\n            result = false;\n          }\n        }\n\n        matrix_reorder_rows(permuted, handled_rows, permuted.size1(), handled_columns, permuted.size2(), abs_greater <int> ());\n\n        /// Augment submatrix by rows with 1 in the new column.\n        while (handled_rows < permuted.size1())\n        {\n          if (permuted(handled_rows, handled_columns) == 0)\n            break;\n          else\n            ++handled_rows;\n        }\n      }\n      else\n      {\n        /// Handled upper-left submatrix and lower-right submatrix are disconnected\n        for (size_t column = handled_columns; column < permuted.size2(); ++column)\n        {\n          size_t count = 0;\n          for (size_t row = handled_rows; row < permuted.size1(); ++row)\n          {\n            if (permuted(row, column) != 0)\n              ++count;\n          }\n\n          /// A zero column can be skipped, as it is handled by definition.\n          if (count > 0)\n          {\n            /// Found a nonzero column and swap ones to the top.\n            matrix_reorder_rows(permuted, handled_rows, permuted.size1(), handled_columns, permuted.size2(), abs_greater <int> ());\n            while (handled_rows < permuted.size1())\n            {\n              if (permuted(handled_rows, handled_columns) == 0)\n                break;\n              else\n                ++handled_rows;\n            }\n\n            break;\n          }\n        }\n      }\n    }\n\n    return result;\n  }\n\n}\n\n#endif /* SIGNING_HPP_ */\n", "meta": {"hexsha": "1f6b856229a1c05e8ed8c387d7d9ef084ec65181", "size": 9538, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "unimodularity-library-1.2c/src/signing.hpp", "max_stars_repo_name": "vios-fish/CompetitiveProgramming", "max_stars_repo_head_hexsha": "6953f024e4769791225c57ed852cb5efc03eb94b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-05T21:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-08T01:33:12.000Z", "max_issues_repo_path": "src/signing.hpp", "max_issues_repo_name": "vbraun/unimodularity-library", "max_issues_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/signing.hpp", "max_forks_repo_name": "vbraun/unimodularity-library", "max_forks_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1180555556, "max_line_length": 148, "alphanum_fraction": 0.6058922206, "num_tokens": 2269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4339820292105083}}
{"text": "/*=========================================================================\r\n\r\n  Program:   Insight Segmentation & Registration Toolkit\r\n  Module:    $RCSfile: itkSparseKernelTransform.txx,v $\r\n  Language:  C++\r\n  Date:      $Date: 2006-11-28 14:22:18 $\r\n  Version:   $Revision: 1.1 $\r\n\r\n  Copyright (c) Insight Software Consortium. All rights reserved.\r\n  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.\r\n\r\n     This software is distributed WITHOUT ANY WARRANTY; without even\r\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\r\n     PURPOSE.  See the above copyright notices for more information.\r\n\r\n=========================================================================*/\r\n#ifndef _itkSparseKernelTransform_txx\r\n#define _itkSparseKernelTransform_txx\r\n#include \"itkSparseKernelTransform.h\"\r\n\r\n// Report timings\r\n#include <itkTimeProbe.h>\r\n#include <itkTimeProbesCollectorBase.h>\r\n\r\n#include <Eigen/Sparse>\r\n#include <Eigen/SparseLU>\r\n\r\n#include <vector>\r\n\r\nnamespace itk\r\n{\r\n\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nSparseKernelTransform()\r\n  : Transform<TScalarType, NDimensions,NDimensions>(1)\r\n//:Superclass(\r\n                         //   NDimensions,\r\n                           // NDimensions )\r\n  // the second NDimensions is associated is provided as\r\n  // a tentative number for initializing the Jacobian.\r\n  // The matrix can be resized at run time so this number\r\n  // here is irrelevant. The correct size of the Jacobian\r\n  // will be NDimension X NDimension.NumberOfLandMarks.\r\n{\r\n\r\n    // m_I.set_identity();\r\n    m_I               = IMatrixType::Identity();\r\n    m_SourceLandmarks = PointSetType::New();\r\n    m_TargetLandmarks = PointSetType::New();\r\n    m_Displacements   = VectorSetType::New();\r\n    m_WMatrixComputed = false;\r\n\r\n    m_LMatrixComputed  = false;\r\n    m_LInverseComputed = false;\r\n\r\n    m_Stiffness = 0.0;\r\n\r\n    Eigen::setNbThreads(8);\r\n}\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\n~SparseKernelTransform()\r\n{\r\n}\r\n\r\ntemplate<class TScalarType, unsigned int NDimensions>\r\ninline void SparseKernelTransform<TScalarType,\r\n  NDimensions>::ComputeJacobianWithRespectToParameters(\r\n    const InputPointType & in, JacobianType & jacobian) const {}\r\n\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nSetSourceLandmarks(PointSetType * landmarks)\r\n{\r\n    itkDebugMacro(\"setting SourceLandmarks to \" << landmarks );\r\n    if (this->m_SourceLandmarks != landmarks)\r\n    {\r\n        this->m_SourceLandmarks = landmarks;\r\n        this->UpdateParameters();\r\n        this->Modified();\r\n\r\n        // these are invalidated when the source lms change\r\n        m_WMatrixComputed  = false;\r\n        m_LMatrixComputed  = false;\r\n        m_LInverseComputed = false;\r\n\r\n        // you must recompute L and Linv - this does not require the targ lms\r\n        // Linverse is only needed ofr Jacobian computation, I will defer this in case Jacobian is needed\r\n        // we will assume by default that this transform is used only for warping, if it is a part of optimization\r\n        // the GetJacobian will feel that the inverse is not computed and will compute it\r\n        //this->ComputeLInverse();\r\n        this->ComputeL();\r\n\r\n    }\r\n}\r\n\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nSetTargetLandmarks(PointSetType * landmarks)\r\n{\r\n    itkDebugMacro(\"setting TargetLandmarks to \" << landmarks );\r\n    if (this->m_TargetLandmarks != landmarks)\r\n    {\r\n        this->m_TargetLandmarks = landmarks;\r\n        // this is invalidated when the target lms change\r\n        m_WMatrixComputed=false;\r\n        this->ComputeWMatrix();\r\n        this->UpdateParameters();\r\n        this->Modified();\r\n    }\r\n\r\n}\r\n\r\n\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nconst typename SparseKernelTransform<TScalarType, NDimensions>::GMatrixType &\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nComputeG( const InputVectorType & ) const\r\n{\r\n    //\r\n    // Should an Exception be thrown here  ?\r\n    //\r\n    itkWarningMacro(<< \"ComputeG() should be reimplemented in the subclass !!\");\r\n    return m_GMatrix;\r\n}\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nconst typename SparseKernelTransform<TScalarType, NDimensions>::GMatrixType &\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nComputeReflexiveG( PointsIterator ) const\r\n{\r\n    m_GMatrix = GMatrixType::Zero();\r\n    for(unsigned d = 0; d < NDimensions; d++)\r\n        m_GMatrix(d,d) = m_Stiffness;\r\n\r\n    //m_GMatrix.fill( NumericTraits< TScalarType >::Zero );\r\n    //m_GMatrix.fill_diagonal( m_Stiffness );\r\n\r\n    return m_GMatrix;\r\n}\r\n\r\n\r\n\r\n\r\n/**\r\n * Default implementation of the the method. This can be overloaded\r\n * in transforms whose kernel produce diagonal G matrices.\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nComputeDeformationContribution( const InputPointType  & thisPoint,\r\n                                OutputPointType & result     ) const\r\n{\r\n\r\n    unsigned long numberOfLandmarks = m_SourceLandmarks->GetNumberOfPoints();\r\n\r\n    PointsIterator sp  = m_SourceLandmarks->GetPoints()->Begin();\r\n\r\n    for(unsigned int lnd=0; lnd < numberOfLandmarks; lnd++ )\r\n    {\r\n        const GMatrixType & Gmatrix = ComputeG( thisPoint - sp->Value() );\r\n        for(unsigned int dim=0; dim < NDimensions; dim++ )\r\n        {\r\n            for(unsigned int odim=0; odim < NDimensions; odim++ )\r\n            {\r\n                result[ odim ] += Gmatrix(dim, odim ) * m_DMatrix(dim,lnd);\r\n            }\r\n        }\r\n        ++sp;\r\n    }\r\n\r\n}\r\n\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid SparseKernelTransform<TScalarType, NDimensions>\r\n::ComputeD(void) const\r\n{\r\n    unsigned long numberOfLandmarks = m_SourceLandmarks->GetNumberOfPoints();\r\n\r\n    PointsIterator sp  = m_SourceLandmarks->GetPoints()->Begin();\r\n    PointsIterator tp  = m_TargetLandmarks->GetPoints()->Begin();\r\n    PointsIterator end = m_SourceLandmarks->GetPoints()->End();\r\n\r\n    m_Displacements->Reserve( numberOfLandmarks );\r\n    typename VectorSetType::Iterator vt = m_Displacements->Begin();\r\n\r\n    while( sp != end )\r\n    {\r\n        vt->Value() = tp->Value() - sp->Value();\r\n        vt++;\r\n        sp++;\r\n        tp++;\r\n    }\r\n    //\tstd::cout<<\" Computed displacements \"<<m_Displacements<<std::endl;\r\n}\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid SparseKernelTransform<TScalarType, NDimensions>\r\n::ComputeWMatrix(void) const\r\n{\r\n    itk::TimeProbe clock;\r\n\r\n    //\tstd::cout<<\"Computing W matrix\"<<std::endl;\r\n\r\n    //typedef vnl_svd<TScalarType>  SVDSolverType;\r\n\r\n    if(!m_LMatrixComputed) {\r\n        this->ComputeL();\r\n    }\r\n    this->ComputeY();\r\n\r\n    //SVDSolverType svd( m_LMatrix, 1e-8 );\r\n    //m_WMatrix = svd.solve( m_YMatrix );\r\n\r\n    clock.Start();\r\n\r\n    //Eigen::BiCGSTAB<LMatrixType>  solver;\r\n    Eigen::BiCGSTAB<LMatrixType, Eigen::IncompleteLUT<double> >  solver;\r\n    solver.preconditioner().setDroptol(1e-10);\r\n    solver.preconditioner().setFillfactor(1000);\r\n\r\n    //    Eigen::SparseLU<LMatrixType> solver;\r\n    solver.compute(m_LMatrix);\r\n\r\n    if(solver.info()!= Eigen::Success) {\r\n        // decomposition failed\r\n        std::cerr << \"LMatrix failed to decompose ...!\" << std::endl;\r\n        return;\r\n    }\r\n\r\n    unsigned long numberOfLandmarks = m_SourceLandmarks->GetNumberOfPoints();\r\n    m_WMatrix = WMatrixType::Zero(NDimensions*(numberOfLandmarks+NDimensions+1), 1);\r\n    m_WMatrix = solver.solve(m_YMatrix);\r\n\r\n    //    m_WMatrix = WMatrixType::Random(NDimensions*(numberOfLandmarks+NDimensions+1), 1);\r\n    //    solver.setMaxIterations(1);\r\n    //    int i = 0;\r\n    //    do {\r\n    //        m_WMatrix = solver.solveWithGuess(m_YMatrix,m_WMatrix);\r\n    //        std::cout << \"#iteration: \" << i << \" \" << \"estimated error: \" << solver.error() << std::endl;\r\n    //        ++i;\r\n    //    } while (solver.info()!= Eigen::Success && i<100);\r\n\r\n    // std::cout << \"#iterations: \" << solver.iterations() << std::endl;\r\n    // std::cout << \"estimated error: \" << solver.error() << std::endl;\r\n\r\n    std::cout  << solver.error() << std::endl;\r\n    if(solver.info() != Eigen::Success) {\r\n        // solving failed\r\n        std::cerr << \"solving sparse system failed ...!\" << std::endl;\r\n        return;\r\n    }\r\n\r\n    clock.Stop();\r\n    // std::cout << \"Computing Wmatrix:\" << std::endl;\r\n    // std::cout << \"Mean: \" << clock.GetMean() << std::endl;\r\n    // std::cout << \"Total: \" << clock.GetTotal() << std::endl;\r\n\r\n    this->ReorganizeW();\r\n    m_WMatrixComputed=true;\r\n}\r\n\r\n/**\r\n * postponed till needing the jacobian for this class\r\n */\r\n//template <class TScalarType, unsigned int NDimensions>\r\n//void SparseKernelTransform<TScalarType, NDimensions>::\r\n//ComputeLInverse(void) const\r\n//{\r\n//    // Assumes that L has already been computed\r\n//    // Necessary for the jacobian\r\n//    if(!m_LMatrixComputed) {\r\n//        this->ComputeL();\r\n//    }\r\n//    //std::cout<<\"LMatrix is:\"<<std::endl;\r\n//    //std::cout<<m_LMatrix<<std::endl;\r\n\r\n//    itk::TimeProbesCollectorBase timeCollector;\r\n//    if (0){\r\n//        timeCollector.Start( \"ComputeLInverse\" );\r\n//        m_LMatrixInverse=vnl_matrix_inverse<TScalarType> (m_LMatrix);\r\n//        timeCollector.Stop( \"ComputeLInverse\" );\r\n//    }\r\n\r\n//    // Convert to sparse matrix\r\n//    // Because of the special storage scheme of a SparseMatrix, special care has to be taken when adding new nonzero entries.\r\n//    // For instance, the cost of a single purely random insertion into a SparseMatrix is O(nnz),\r\n//    // where nnz is the current number of non-zero coefficients.\r\n//    // The simplest way to create a sparse matrix while guaranteeing good performance is thus to first build a list of\r\n//    // so-called triplets, and then convert it to a SparseMatrix.\r\n//    typedef Eigen::SparseMatrix<ScalarType> SpMat; // declares a column-major sparse matrix type of double\r\n//    typedef Eigen::Triplet<ScalarType> Triplet;\r\n//    SpMat A(m_LMatrix.rows(),m_LMatrix.cols());\r\n\r\n//    std::vector<Triplet> tripletList;\r\n//    for ( unsigned int r = 0; r < m_LMatrix.rows(); r++ )\r\n//        for ( unsigned int c = 0; c < m_LMatrix.cols(); c++ )\r\n//        {\r\n//            ScalarType val = m_LMatrix.get( r, c );\r\n//            if ( val != 0 )\r\n//                tripletList.push_back(Triplet(r,c,val));\r\n//        }\r\n//    A.setFromTriplets(tripletList.begin(), tripletList.end());\r\n//    timeCollector.Stop( \"ConvertLToSparse\" );\r\n\r\n//    // Method 4: LU Decomposition\r\n//    // Depends on local ITK vnl_sparse_lu modification\r\n//    timeCollector.Start( \"ComputeLSparseInverse\" );\r\n//    unsigned long numberOfLandmarks = m_SourceLandmarks->GetNumberOfPoints();\r\n//    //    vnl_sparse_symmetric_eigensystem eigSys;\r\n//    //    eigSys.CalculateNPairs(lSparseMatrix,NDimensions*(numberOfLandmarks+NDimensions+1), false);\r\n//    //    //LSparseMatrixType lMatrixInverse = vnl_sparse_lu( lSparseMatrix ).inverse();\r\n//    //    timeCollector.Stop( \"ComputeLSparseInverse\" );\r\n\r\n\r\n//    m_LInverseComputed=true;\r\n//    //std::cout<<\"LMatrix inverse is:\"<<std::endl;\r\n//    //std::cout<<m_LMatrixInverse<<std::endl;\r\n//}\r\n\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid SparseKernelTransform<TScalarType, NDimensions>::\r\nComputeL(void) const\r\n{\r\n    unsigned long numberOfLandmarks = m_SourceLandmarks->GetNumberOfPoints();\r\n    //vnl_matrix<TScalarType> O2(NDimensions*(NDimensions+1),\r\n    //                           NDimensions*(NDimensions+1), 0);\r\n\r\n    this->ComputeP();\r\n    this->ComputeK();\r\n\r\n    //m_LMatrix.set_size( NDimensions*(numberOfLandmarks+NDimensions+1),\r\n    //                    NDimensions*(numberOfLandmarks+NDimensions+1) );\r\n    //m_LMatrix.fill( 0.0 );\r\n    m_LMatrix = LMatrixType( NDimensions*(numberOfLandmarks+NDimensions+1),\r\n                             NDimensions*(numberOfLandmarks+NDimensions+1) );\r\n\r\n    //std::vector<TripletType> tripletList;\r\n\r\n    // putting KMATRIX\r\n    //m_LMatrix.update( m_KMatrix, 0, 0 );\r\n    //it.value();\r\n    //it.row(); // row index\r\n    //it.col(); // col index (here it is equal to k)\r\n    //it.index(); // inner index, here it is equal to it.row()\r\n    for (int k = 0; k < m_KMatrix.outerSize(); ++k) // column index\r\n        for (typename KMatrixType::InnerIterator it(m_KMatrix,k); it; ++it)\r\n            m_LMatrix.insert(it.row(), it.col()) = it.value() ;\r\n    //tripletList.push_back( TripletType ( it.row(), it.col(), it.value() ) );\r\n\r\n    // putting PMATRIX - will keep the lower only ??\r\n    //m_LMatrix.update( m_PMatrix, 0, m_KMatrix.columns() );\r\n    //m_LMatrix.update( m_PMatrix.transpose(), m_KMatrix.rows(), 0);\r\n    for (int p = 0; p < m_PMatrix.outerSize(); ++p) // column index\r\n        for (typename PMatrixType::InnerIterator it(m_PMatrix,p); it; ++it)\r\n        {\r\n            // fill P -> upper\r\n            m_LMatrix.insert(it.row(), NDimensions*numberOfLandmarks + it.col()) = it.value() ;\r\n            //tripletList.push_back( TripletType ( it.row(), NDimensions*numberOfLandmarks + it.col(), it.value() ) );\r\n\r\n            // fill P.transpose -> lower\r\n            m_LMatrix.insert(NDimensions*numberOfLandmarks + it.col(),  it.row()) = it.value() ;\r\n            //tripletList.push_back( TripletType ( NDimensions*numberOfLandmarks + it.col(),  it.row(), it.value() ) );\r\n        }\r\n    //m_LMatrix.update( O2, m_KMatrix.rows(), m_KMatrix.columns());\r\n\r\n    //    // shireen: for debugging let's make sure that the L matrix is sparse (based on gaussian basis)\r\n    //    std::ofstream ofs;\r\n    //    ofs.open(\"Lsparse.csv\");\r\n    //    for (int k = 0; k < m_LMatrix.outerSize(); ++k) // column index\r\n    //        for (typename LMatrixType::InnerIterator it(m_LMatrix,k); it; ++it)\r\n    //            ofs << it.row()  << \", \" << it.col()  << \", \" << it.value() << std::endl;\r\n    //    ofs.close();\r\n\r\n\r\n    // std::cout << \"Lmatrix - nnz = \"  << m_LMatrix.nonZeros() << std::endl;\r\n    m_LMatrix.makeCompressed();\r\n\r\n    //m_LMatrix.setFromTriplets(tripletList.begin(), tripletList.end());\r\n    m_LMatrixComputed=1;\r\n}\r\n\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid SparseKernelTransform<TScalarType, NDimensions>::\r\nComputeK(void) const\r\n{\r\n    unsigned long numberOfLandmarks = m_SourceLandmarks->GetNumberOfPoints();\r\n    GMatrixType G;\r\n    //std::vector<TripletType> tripletList;\r\n\r\n    m_KMatrix = KMatrixType( NDimensions * numberOfLandmarks,\r\n                             NDimensions * numberOfLandmarks );\r\n    //m_KMatrix.set_size( NDimensions * numberOfLandmarks,\r\n    //                    NDimensions * numberOfLandmarks );\r\n\r\n    //m_KMatrix.fill( 0.0 );\r\n\r\n    PointsIterator p1  = m_SourceLandmarks->GetPoints()->Begin();\r\n    PointsIterator end = m_SourceLandmarks->GetPoints()->End();\r\n\r\n    // K matrix is symmetric, so only evaluate the upper triangle and\r\n    // store the values in both the upper and lower triangle\r\n    unsigned int i = 0;\r\n    while( p1 != end )\r\n    {\r\n        PointsIterator p2 = p1; // start at the diagonal element\r\n        unsigned int j = i;\r\n\r\n        // Compute the block diagonal element, i.e. kernel for pi->pi\r\n        //G = ComputeReflexiveG(p1);\r\n\r\n        // force to compute the basis on the diagonal\r\n        const InputVectorType s = p1.Value() - p1.Value();\r\n        G = ComputeG(s); // the basis\r\n\r\n        //m_KMatrix.update(G, i*NDimensions, i*NDimensions);\r\n        for(unsigned int d = 0; d < NDimensions; d++)\r\n        {\r\n            if(G(d,d) != 0 )\r\n                m_KMatrix.insert(i*NDimensions+d ,i*NDimensions+d) = G(d,d) + m_Stiffness; // this is as a regularizer\r\n            //tripletList.push_back(TripletType(i*NDimensions+d ,i*NDimensions+d, m_GMatrix(d,d)));\r\n        }\r\n\r\n        p2++;\r\n        j++;\r\n\r\n        // Compute the upper (and copy into lower) triangular part of K\r\n        // only save the lower part, don't need it\r\n        while( p2 != end )\r\n        {\r\n            const InputVectorType s = p1.Value() - p2.Value();\r\n            G = ComputeG(s); // the basis\r\n\r\n            // write value in upper and lower triangle of matrix\r\n            for(unsigned int ii = 0 ; ii < NDimensions; ii++)\r\n                for(unsigned int jj = 0 ; jj < NDimensions; jj++)\r\n                {\r\n                    if (G(ii,jj) != 0)\r\n                    {\r\n                        m_KMatrix.insert(i*NDimensions+ii ,j*NDimensions+jj) = G(ii,jj); // upper\r\n                        m_KMatrix.insert(j*NDimensions+ii ,i*NDimensions+jj) = G(ii,jj); // lower\r\n                    }\r\n\r\n                    //tripletList.push_back(TripletType(i*NDimensions+ii ,j*NDimensions+jj, G(ii,jj)));\r\n                    //tripletList.push_back(TripletType(j*NDimensions+ii ,i*NDimensions+jj, G(ii,jj)));\r\n                }\r\n\r\n            // m_KMatrix.update(G, i*NDimensions, j*NDimensions);\r\n            // m_KMatrix.update(G, j*NDimensions, i*NDimensions);\r\n            p2++;\r\n            j++;\r\n        }\r\n        p1++;\r\n        i++;\r\n    }\r\n    //std::cout<<\"K matrix: \"<<std::endl;\r\n    //std::cout<<m_KMatrix<<std::endl;\r\n\r\n    //    // shireen: for debugging let's make sure that the L matrix is sparse (based on gaussian basis)\r\n    //    std::ofstream ofs;\r\n    //    ofs.open(\"Ksparse.csv\");\r\n    //    for (int k = 0; k < m_KMatrix.outerSize(); ++k) // column index\r\n    //        for (typename KMatrixType::InnerIterator it(m_KMatrix,k); it; ++it)\r\n    //            ofs << it.row()  << \", \" << it.col()  << \", \" << it.value() << std::endl;\r\n    //    ofs.close();\r\n\r\n    // std::cout << \"Kmatrix - nnz = \"  << m_KMatrix.nonZeros() << std::endl;\r\n    m_KMatrix.makeCompressed();\r\n\r\n    //m_KMatrix.setFromTriplets(tripletList.begin(), tripletList.end());\r\n}\r\n\r\n\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid SparseKernelTransform<TScalarType, NDimensions>::\r\nComputeP() const\r\n{\r\n    unsigned long numberOfLandmarks = m_SourceLandmarks->GetNumberOfPoints();\r\n\r\n    //IMatrixType I = IMatrixType::Identity();\r\n    //IMatrixType temp;\r\n    InputPointType p;\r\n\r\n    //I.set_identity();\r\n\r\n    //std::vector<TripletType> tripletList;\r\n\r\n    //m_PMatrix.set_size( NDimensions*numberOfLandmarks,\r\n    //                    NDimensions*(NDimensions+1) );\r\n    //m_PMatrix.fill( 0.0 );\r\n    m_PMatrix = PMatrixType(NDimensions*numberOfLandmarks,\r\n                            NDimensions*(NDimensions+1) );\r\n    for (unsigned int i = 0; i < numberOfLandmarks; i++)\r\n    {\r\n        m_SourceLandmarks->GetPoint(i, &p);\r\n        for (unsigned int j = 0; j < NDimensions; j++)\r\n        {\r\n            //temp = I * p[j];\r\n            for(unsigned int d = 0 ; d < NDimensions; d++)\r\n            {\r\n                m_PMatrix.insert(i*NDimensions + d, j*NDimensions + d) = p[j];\r\n                //tripletList.push_back( TripletType( i*NDimensions + d, j*NDimensions + d, p[j] ) );\r\n            }\r\n            //m_PMatrix.update(temp, i*NDimensions, j*NDimensions);\r\n        }\r\n\r\n        for(unsigned int d = 0 ; d < NDimensions; d++)\r\n        {\r\n            m_PMatrix.insert(i*NDimensions + d, NDimensions*NDimensions + d) = 1;\r\n            //tripletList.push_back( TripletType( i*NDimensions + d, NDimensions*NDimensions + d, 1 ) );\r\n        }\r\n        //m_PMatrix.update(I, i*NDimensions, NDimensions*NDimensions);\r\n    }\r\n\r\n    // std::cout << \"Pmatrix - nnz = \"  << m_PMatrix.nonZeros() << std::endl;\r\n    m_PMatrix.makeCompressed();\r\n    //m_PMatrix.setFromTriplets(tripletList.begin(), tripletList.end());\r\n}\r\n\r\n\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid SparseKernelTransform<TScalarType, NDimensions>::\r\nComputeY(void) const\r\n{\r\n    unsigned long numberOfLandmarks = m_SourceLandmarks->GetNumberOfPoints();\r\n\r\n    this->ComputeD();\r\n\r\n    typename VectorSetType::ConstIterator displacement =\r\n            m_Displacements->Begin();\r\n\r\n    //m_YMatrix.set_size( NDimensions*(numberOfLandmarks+NDimensions+1), 1);\r\n    //m_YMatrix.fill( 0.0 );\r\n    m_YMatrix = YMatrixType::Zero(NDimensions*(numberOfLandmarks+NDimensions+1), 1);\r\n    \r\n    for (unsigned int i = 0; i < numberOfLandmarks; i++)\r\n    {\r\n        for (unsigned int j = 0; j < NDimensions; j++)\r\n        {\r\n            m_YMatrix(i*NDimensions+j, 0) = displacement.Value()[j];\r\n            //m_YMatrix.put(i*NDimensions+j, 0, displacement.Value()[j]);\r\n        }\r\n        displacement++;\r\n    }\r\n\r\n    for (unsigned int i = 0; i < NDimensions*(NDimensions+1); i++)\r\n    {\r\n        m_YMatrix(numberOfLandmarks*NDimensions+i, 0) = 0;\r\n        //m_YMatrix.put(numberOfLandmarks*NDimensions+i, 0, 0);\r\n    }\r\n}\r\n\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid\r\nSparseKernelTransform<TScalarType, NDimensions>\r\n::ReorganizeW(void) const\r\n{\r\n    unsigned long numberOfLandmarks = m_SourceLandmarks->GetNumberOfPoints();\r\n\r\n    // The deformable (non-affine) part of the registration goes here\r\n    m_DMatrix = DMatrixType::Zero(NDimensions,numberOfLandmarks);\r\n    //m_DMatrix.set_size(NDimensions,numberOfLandmarks);\r\n\r\n    unsigned int ci = 0;\r\n    for(unsigned int lnd=0; lnd < numberOfLandmarks; lnd++ )\r\n    {\r\n        for(unsigned int dim=0; dim < NDimensions; dim++ )\r\n        {\r\n            //std::cout << m_WMatrix(ci,0) << std::endl;\r\n            m_DMatrix(dim,lnd) = m_WMatrix(ci++,0);\r\n        }\r\n    }\r\n\r\n    // This matrix holds the rotational part of the Affine component\r\n    m_AMatrix = AMatrixType::Zero(NDimensions, NDimensions);\r\n    for(unsigned int j=0; j < NDimensions; j++ )\r\n    {\r\n        for(unsigned int i=0; i < NDimensions; i++ )\r\n        {\r\n            m_AMatrix(i,j) = m_WMatrix(ci++,0);\r\n        }\r\n    }\r\n\r\n    // This vector holds the translational part of the Affine component\r\n    m_BVector = BMatrixType::Zero(NDimensions,1);\r\n    for(unsigned int k=0; k < NDimensions; k++ )\r\n    {\r\n        m_BVector(k) = m_WMatrix(ci++,0);\r\n    }\r\n\r\n    // release WMatrix memory by assigning a small one.\r\n    m_WMatrix = WMatrixType(1,1);\r\n\r\n    m_WMatrixComputed=1;\r\n\r\n    //    std::ofstream ofs;\r\n    //    ofs.open(\"D.csv\");\r\n    //    for (int k = 0; k < m_DMatrix.outerSize(); ++k) // column index\r\n    //        for (typename DMatrixType::InnerIterator it(m_DMatrix,k); it; ++it)\r\n    //            ofs << it.row()  << \", \" << it.col()  << \", \" << it.value() << std::endl;\r\n    //    ofs.close();\r\n}\r\n\r\n\r\n\r\n/**\r\n *\r\n */\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\ntypename SparseKernelTransform<TScalarType, NDimensions>::OutputPointType\r\nSparseKernelTransform<TScalarType, NDimensions>\r\n::TransformPoint(const InputPointType& thisPoint) const\r\n{\r\n\r\n    OutputPointType result;\r\n\r\n    typedef typename OutputPointType::ValueType ValueType;\r\n\r\n    result.Fill( NumericTraits< ValueType >::Zero );\r\n\r\n    this->ComputeDeformationContribution( thisPoint, result );\r\n\r\n    // Add the rotational part of the Affine component\r\n    for(unsigned int j=0; j < NDimensions; j++ )\r\n    {\r\n        for(unsigned int i=0; i < NDimensions; i++ )\r\n        {\r\n            result[i] += m_AMatrix(i,j) * thisPoint[j];\r\n        }\r\n    }\r\n\r\n\r\n\r\n    // This vector holds the translational part of the Affine component\r\n    for(unsigned int k=0; k < NDimensions; k++ )\r\n    {\r\n        result[k] += m_BVector(k) + thisPoint[k];\r\n    }\r\n\r\n    return result;\r\n\r\n}\r\n\r\n\r\n\r\n\r\n//// Compute the Jacobian in one position - POSTPONED\r\n//template <class TScalarType, unsigned int NDimensions>\r\n//const typename SparseKernelTransform<TScalarType,NDimensions>::JacobianType &\r\n//SparseKernelTransform< TScalarType,NDimensions>::\r\n//GetJacobian( const InputPointType & thisPoint) const\r\n//{\r\n//    if(!m_LInverseComputed) {\r\n//        this->ComputeLInverse();\r\n//    }\r\n//    unsigned long numberOfLandmarks = m_SourceLandmarks->GetNumberOfPoints();\r\n//    Superclass::m_Jacobian.SetSize(NDimensions, numberOfLandmarks*NDimensions);\r\n//    Superclass::m_Jacobian.Fill( 0.0 );\r\n\r\n//    PointsIterator sp  = m_SourceLandmarks->GetPoints()->Begin();\r\n//    for(unsigned int lnd=0; lnd < numberOfLandmarks; lnd++ )\r\n//    {\r\n//        const GMatrixType & Gmatrix = ComputeG( thisPoint - sp->Value() );\r\n//        ///std::cout<<\"G for landmark \"<<lnd<<std::endl<<Gmatrix<<std::endl;\r\n//        for(unsigned int dim=0; dim < NDimensions; dim++ )\r\n//        {\r\n//            for(unsigned int odim=0; odim < NDimensions; odim++ )\r\n//            {\r\n//                for(unsigned int lidx=0; lidx < numberOfLandmarks*NDimensions; lidx++ )\r\n//                {\r\n//                    Superclass::m_Jacobian[ odim ] [lidx] += Gmatrix(dim, odim ) *\r\n//                            m_LMatrixInverse[lnd*NDimensions+dim][lidx];\r\n//                }\r\n//            }\r\n//        }\r\n//        ++sp;\r\n\r\n//    }\r\n//    for(unsigned int odim=0; odim < NDimensions; odim++ )\r\n//    {\r\n//        for(unsigned int lidx=0; lidx < numberOfLandmarks*NDimensions; lidx++ )\r\n//        {\r\n//            for(unsigned int dim=0; dim < NDimensions; dim++ )\r\n//            {\r\n//                Superclass::m_Jacobian[ odim ] [lidx] += thisPoint[dim] *\r\n//                        m_LMatrixInverse[(numberOfLandmarks+dim)*NDimensions+odim][lidx];\r\n//            }\r\n\r\n//            Superclass::m_Jacobian[ odim ] [lidx] += m_LMatrixInverse[(numberOfLandmarks+NDimensions)*NDimensions+odim][lidx];\r\n//        }\r\n//    }\r\n\r\n//    return Superclass::m_Jacobian;\r\n\r\n//}\r\n\r\n// Set to the identity transform - ie make the  Source and target lm the same\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nSetIdentity()\r\n{\r\n    this->SetParameters(this->GetFixedParameters());\r\n}\r\n\r\n// Set the parameters\r\n// NOTE that in this transformation both the Source and Target\r\n// landmarks could be considered as parameters. It is assumed\r\n// here that the Target landmarks are provided by the user and\r\n// are not changed during the optimization process required for\r\n// registration.\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nSetParameters( const ParametersType & parameters )\r\n{\r\n    //\tstd::cout<<\"Setting parameters to \"<<parameters<<std::endl;\r\n    typename PointsContainer::Pointer landmarks = PointsContainer::New();\r\n    const unsigned int numberOfLandmarks =  parameters.Size() / NDimensions;\r\n    landmarks->Reserve( numberOfLandmarks );\r\n\r\n    PointsIterator itr = landmarks->Begin();\r\n    PointsIterator end = landmarks->End();\r\n\r\n    InputPointType  landMark;\r\n\r\n    unsigned int pcounter = 0;\r\n    while( itr != end )\r\n    {\r\n        for(unsigned int dim=0; dim<NDimensions; dim++)\r\n        {\r\n            landMark[ dim ] = parameters[ pcounter ];\r\n            pcounter++;\r\n        }\r\n        itr.Value() = landMark;\r\n        itr++;\r\n    }\r\n\r\n    // m_SourceLandmarks->SetPoints( landmarks );\r\n    m_TargetLandmarks->SetPoints( landmarks );\r\n\r\n    // W MUST be recomputed if the target lms are set\r\n    this->ComputeWMatrix();\r\n\r\n    //  if(!m_LInverseComputed) {\r\n    //  this->ComputeLInverse();\r\n    //  }\r\n\r\n    // Modified is always called since we just have a pointer to the\r\n    // parameters and cannot know if the parameters have changed.\r\n    this->Modified();\r\n\r\n}\r\n\r\n// Set the fixed parameters\r\n// Since the API of the SetParameters() function sets the\r\n// source landmarks, this function was added to support the\r\n// setting of the target landmarks, and allowing the Transform\r\n// I/O mechanism to be supported.\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nSetFixedParameters( const ParametersType & parameters )\r\n{\r\n    typename PointsContainer::Pointer landmarks = PointsContainer::New();\r\n    const unsigned int numberOfLandmarks =  parameters.Size() / NDimensions;\r\n\r\n    landmarks->Reserve( numberOfLandmarks );\r\n\r\n    PointsIterator itr = landmarks->Begin();\r\n    PointsIterator end = landmarks->End();\r\n\r\n    InputPointType  landMark;\r\n\r\n    unsigned int pcounter = 0;\r\n    while( itr != end )\r\n    {\r\n        for(unsigned int dim=0; dim<NDimensions; dim++)\r\n        {\r\n            landMark[ dim ] = parameters[ pcounter ];\r\n            pcounter++;\r\n        }\r\n        itr.Value() = landMark;\r\n        itr++;\r\n    }\r\n\r\n    //  m_TargetLandmarks->SetPoints( landmarks );\r\n    m_SourceLandmarks->SetPoints( landmarks );\r\n\r\n    // these are invalidated when the source lms change\r\n    m_WMatrixComputed=false;\r\n    m_LMatrixComputed=false;\r\n    m_LInverseComputed=false;\r\n\r\n    // you must recompute L and Linv - this does not require the targ lms\r\n    //this->ComputeLInverse();\r\n    this->ComputeL();\r\n\r\n}\r\n\r\n\r\n// Update parameters array\r\n// They are the components of all the landmarks in the source space\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nUpdateParameters( void ) const\r\n{\r\n    this->m_Parameters = ParametersType( m_TargetLandmarks->GetNumberOfPoints() * NDimensions );\r\n\r\n    PointsIterator itr = m_TargetLandmarks->GetPoints()->Begin();\r\n    PointsIterator end = m_TargetLandmarks->GetPoints()->End();\r\n\r\n    unsigned int pcounter = 0;\r\n    while( itr != end )\r\n    {\r\n        InputPointType  landmark = itr.Value();\r\n        for(unsigned int dim=0; dim<NDimensions; dim++)\r\n        {\r\n            this->m_Parameters[ pcounter ] = landmark[ dim ];\r\n            pcounter++;\r\n        }\r\n        itr++;\r\n    }\r\n}\r\n\r\n\r\n\r\n\r\n// Get the parameters\r\n// They are the components of all the landmarks in the source space\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nconst typename SparseKernelTransform<TScalarType, NDimensions>::ParametersType &\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nGetParameters( void ) const\r\n{\r\n    this->UpdateParameters();\r\n    return this->m_Parameters;\r\n\r\n}\r\n\r\n\r\n// Get the fixed parameters\r\n// This returns the target landmark locations\r\n// This was added to support the Transform Reader/Writer mechanism\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nconst typename SparseKernelTransform<TScalarType, NDimensions>::ParametersType &\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nGetFixedParameters( void ) const\r\n{\r\n    this->m_FixedParameters = ParametersType( m_SourceLandmarks->GetNumberOfPoints() * NDimensions );\r\n\r\n    PointsIterator itr = m_SourceLandmarks->GetPoints()->Begin();\r\n    PointsIterator end = m_SourceLandmarks->GetPoints()->End();\r\n\r\n    unsigned int pcounter = 0;\r\n    while( itr != end )\r\n    {\r\n        InputPointType  landmark = itr.Value();\r\n        for(unsigned int dim=0; dim<NDimensions; dim++)\r\n        {\r\n            this->m_FixedParameters[ pcounter ] = landmark[ dim ];\r\n            pcounter++;\r\n        }\r\n        itr++;\r\n    }\r\n\r\n    return this->m_FixedParameters;\r\n\r\n}\r\n\r\n\r\n\r\ntemplate <class TScalarType, unsigned int NDimensions>\r\nvoid\r\nSparseKernelTransform<TScalarType, NDimensions>::\r\nPrintSelf(std::ostream& os, Indent indent) const\r\n{\r\n    Superclass::PrintSelf(os,indent);\r\n    if (m_SourceLandmarks)\r\n    {\r\n        os << indent << \"SourceLandmarks: \" << std::endl;\r\n        m_SourceLandmarks->Print(os,indent.GetNextIndent());\r\n    }\r\n    if (m_TargetLandmarks)\r\n    {\r\n        os << indent << \"TargetLandmarks: \" << std::endl;\r\n        m_TargetLandmarks->Print(os,indent.GetNextIndent());\r\n    }\r\n    if (m_Displacements)\r\n    {\r\n        os << indent << \"Displacements: \" << std::endl;\r\n        m_Displacements->Print(os,indent.GetNextIndent());\r\n    }\r\n    os << indent << \"Stiffness: \" << m_Stiffness << std::endl;\r\n}\r\n} // namespace itk\r\n\r\n#endif\r\n", "meta": {"hexsha": "e753dab4e2880e5b503ceade792fe6f71244e536", "size": 31900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Libs/Alignment/Transforms/itkSparseKernelTransform.cpp", "max_stars_repo_name": "SCIInstitute/shapeworks", "max_stars_repo_head_hexsha": "cbd44fdeb83270179c2331f2ba8431cf7330a4ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-04-26T15:29:58.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-05T18:39:12.000Z", "max_issues_repo_path": "Libs/Alignment/Transforms/itkSparseKernelTransform.cpp", "max_issues_repo_name": "SCIInstitute/shapeworks", "max_issues_repo_head_hexsha": "cbd44fdeb83270179c2331f2ba8431cf7330a4ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 35.0, "max_issues_repo_issues_event_min_datetime": "2015-05-22T18:26:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-03T18:09:40.000Z", "max_forks_repo_path": "Libs/Alignment/Transforms/itkSparseKernelTransform.cpp", "max_forks_repo_name": "SCIInstitute/shapeworks", "max_forks_repo_head_hexsha": "cbd44fdeb83270179c2331f2ba8431cf7330a4ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-06-18T18:56:12.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-17T19:15:06.000Z", "avg_line_length": 33.5789473684, "max_line_length": 129, "alphanum_fraction": 0.6144514107, "num_tokens": 7925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4339122827474802}}
{"text": "/**\n* This file is part of Fast-Planner.\n*\n* Copyright 2019 Boyu Zhou, Aerial Robotics Group, Hong Kong University of Science and Technology, <uav.ust.hk>\n* Developed by Boyu Zhou <bzhouai at connect dot ust dot hk>, <uv dot boyuzhou at gmail dot com>\n* for more information see <https://github.com/HKUST-Aerial-Robotics/Fast-Planner>.\n* If you use this code, please cite the respective publications as\n* listed on the above website.\n*\n* Fast-Planner is free software: you can redistribute it and/or modify\n* it under the terms of the GNU Lesser General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* Fast-Planner is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public License\n* along with Fast-Planner. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n\n\n#include <Eigen/Eigen>\n#include <cmath>\n#include <iostream>\n#include <plan_env/raycast.h>\n\nint signum(int x) {\n  return x == 0 ? 0 : x < 0 ? -1 : 1;\n}\n\ndouble mod(double value, double modulus) {\n  return fmod(fmod(value, modulus) + modulus, modulus);\n}\n\ndouble intbound(double s, double ds) {\n  // Find the smallest positive t such that s+t*ds is an integer.\n  if (ds < 0) {\n    return intbound(-s, -ds);\n  } else {\n    s = mod(s, 1);\n    // problem is now s+t*ds = 1\n    return (1 - s) / ds;\n  }\n}\n\nvoid Raycast(const Eigen::Vector3d& start, const Eigen::Vector3d& end, const Eigen::Vector3d& min,\n             const Eigen::Vector3d& max, int& output_points_cnt, Eigen::Vector3d* output) {\n  //    std::cout << start << ' ' << end << std::endl;\n  // From \"A Fast Voxel Traversal Algorithm for Ray Tracing\"\n  // by John Amanatides and Andrew Woo, 1987\n  // <http://www.cse.yorku.ca/~amana/research/grid.pdf>\n  // <http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.3443>\n  // Extensions to the described algorithm:\n  //   • Imposed a distance limit.\n  //   • The face passed through to reach the current cube is provided to\n  //     the callback.\n\n  // The foundation of this algorithm is a parameterized representation of\n  // the provided ray,\n  //                    origin + t * direction,\n  // except that t is not actually stored; rather, at any given point in the\n  // traversal, we keep track of the *greater* t values which we would have\n  // if we took a step sufficient to cross a cube boundary along that axis\n  // (i.e. change the integer part of the coordinate) in the variables\n  // tMaxX, tMaxY, and tMaxZ.\n\n  // Cube containing origin point.\n  int x = (int)std::floor(start.x());\n  int y = (int)std::floor(start.y());\n  int z = (int)std::floor(start.z());\n  int endX = (int)std::floor(end.x());\n  int endY = (int)std::floor(end.y());\n  int endZ = (int)std::floor(end.z());\n  Eigen::Vector3d direction = (end - start);\n  double maxDist = direction.squaredNorm();\n\n  // Break out direction vector.\n  double dx = endX - x;\n  double dy = endY - y;\n  double dz = endZ - z;\n\n  // Direction to increment x,y,z when stepping.\n  int stepX = (int)signum((int)dx);\n  int stepY = (int)signum((int)dy);\n  int stepZ = (int)signum((int)dz);\n\n  // See description above. The initial values depend on the fractional\n  // part of the origin.\n  double tMaxX = intbound(start.x(), dx);\n  double tMaxY = intbound(start.y(), dy);\n  double tMaxZ = intbound(start.z(), dz);\n\n  // The change in t when taking a step (always positive).\n  double tDeltaX = ((double)stepX) / dx;\n  double tDeltaY = ((double)stepY) / dy;\n  double tDeltaZ = ((double)stepZ) / dz;\n\n  // Avoids an infinite loop.\n  if (stepX == 0 && stepY == 0 && stepZ == 0) return;\n\n  double dist = 0;\n  while (true) {\n    if (x >= min.x() && x < max.x() && y >= min.y() && y < max.y() && z >= min.z() && z < max.z()) {\n      output[output_points_cnt](0) = x;\n      output[output_points_cnt](1) = y;\n      output[output_points_cnt](2) = z;\n\n      output_points_cnt++;\n      dist = sqrt((x - start(0)) * (x - start(0)) + (y - start(1)) * (y - start(1)) +\n                  (z - start(2)) * (z - start(2)));\n\n      if (dist > maxDist) return;\n\n      /*            if (output_points_cnt > 1500) {\n                      std::cerr << \"Error, too many racyast voxels.\" <<\n         std::endl;\n                      throw std::out_of_range(\"Too many raycast voxels\");\n                  }*/\n    }\n\n    if (x == endX && y == endY && z == endZ) break;\n\n    // tMaxX stores the t-value at which we cross a cube boundary along the\n    // X axis, and similarly for Y and Z. Therefore, choosing the least tMax\n    // chooses the closest cube boundary. Only the first case of the four\n    // has been commented in detail.\n    if (tMaxX < tMaxY) {\n      if (tMaxX < tMaxZ) {\n        // Update which cube we are now in.\n        x += stepX;\n        // Adjust tMaxX to the next X-oriented boundary crossing.\n        tMaxX += tDeltaX;\n      } else {\n        z += stepZ;\n        tMaxZ += tDeltaZ;\n      }\n    } else {\n      if (tMaxY < tMaxZ) {\n        y += stepY;\n        tMaxY += tDeltaY;\n      } else {\n        z += stepZ;\n        tMaxZ += tDeltaZ;\n      }\n    }\n  }\n}\n\nvoid Raycast(const Eigen::Vector3d& start, const Eigen::Vector3d& end, const Eigen::Vector3d& min,\n             const Eigen::Vector3d& max, std::vector<Eigen::Vector3d>* output) {\n  //    std::cout << start << ' ' << end << std::endl;\n  // From \"A Fast Voxel Traversal Algorithm for Ray Tracing\"\n  // by John Amanatides and Andrew Woo, 1987\n  // <http://www.cse.yorku.ca/~amana/research/grid.pdf>\n  // <http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.3443>\n  // Extensions to the described algorithm:\n  //   • Imposed a distance limit.\n  //   • The face passed through to reach the current cube is provided to\n  //     the callback.\n\n  // The foundation of this algorithm is a parameterized representation of\n  // the provided ray,\n  //                    origin + t * direction,\n  // except that t is not actually stored; rather, at any given point in the\n  // traversal, we keep track of the *greater* t values which we would have\n  // if we took a step sufficient to cross a cube boundary along that axis\n  // (i.e. change the integer part of the coordinate) in the variables\n  // tMaxX, tMaxY, and tMaxZ.\n\n  // Cube containing origin point.\n  int x = (int)std::floor(start.x());\n  int y = (int)std::floor(start.y());\n  int z = (int)std::floor(start.z());\n  int endX = (int)std::floor(end.x());\n  int endY = (int)std::floor(end.y());\n  int endZ = (int)std::floor(end.z());\n  Eigen::Vector3d direction = (end - start);\n  double maxDist = direction.squaredNorm();\n\n  // Break out direction vector.\n  double dx = endX - x;\n  double dy = endY - y;\n  double dz = endZ - z;\n\n  // Direction to increment x,y,z when stepping.\n  int stepX = (int)signum((int)dx);\n  int stepY = (int)signum((int)dy);\n  int stepZ = (int)signum((int)dz);\n\n  // See description above. The initial values depend on the fractional\n  // part of the origin.\n  double tMaxX = intbound(start.x(), dx);\n  double tMaxY = intbound(start.y(), dy);\n  double tMaxZ = intbound(start.z(), dz);\n\n  // The change in t when taking a step (always positive).\n  double tDeltaX = ((double)stepX) / dx;\n  double tDeltaY = ((double)stepY) / dy;\n  double tDeltaZ = ((double)stepZ) / dz;\n\n  output->clear();\n\n  // Avoids an infinite loop.\n  if (stepX == 0 && stepY == 0 && stepZ == 0) return;\n\n  double dist = 0;\n  while (true) {\n    if (x >= min.x() && x < max.x() && y >= min.y() && y < max.y() && z >= min.z() && z < max.z()) {\n      output->push_back(Eigen::Vector3d(x, y, z));\n\n      dist = (Eigen::Vector3d(x, y, z) - start).squaredNorm();\n\n      if (dist > maxDist) return;\n\n      if (output->size() > 1500) {\n        std::cerr << \"Error, too many racyast voxels.\" << std::endl;\n        throw std::out_of_range(\"Too many raycast voxels\");\n      }\n    }\n\n    if (x == endX && y == endY && z == endZ) break;\n\n    // tMaxX stores the t-value at which we cross a cube boundary along the\n    // X axis, and similarly for Y and Z. Therefore, choosing the least tMax\n    // chooses the closest cube boundary. Only the first case of the four\n    // has been commented in detail.\n    if (tMaxX < tMaxY) {\n      if (tMaxX < tMaxZ) {\n        // Update which cube we are now in.\n        x += stepX;\n        // Adjust tMaxX to the next X-oriented boundary crossing.\n        tMaxX += tDeltaX;\n      } else {\n        z += stepZ;\n        tMaxZ += tDeltaZ;\n      }\n    } else {\n      if (tMaxY < tMaxZ) {\n        y += stepY;\n        tMaxY += tDeltaY;\n      } else {\n        z += stepZ;\n        tMaxZ += tDeltaZ;\n      }\n    }\n  }\n}\n\nbool RayCaster::setInput(const Eigen::Vector3d& start,\n                         const Eigen::Vector3d& end /* , const Eigen::Vector3d& min,\n                         const Eigen::Vector3d& max */) {\n  start_ = start;\n  end_ = end;\n  // max_ = max;\n  // min_ = min;\n\n  x_ = (int)std::floor(start_.x());\n  y_ = (int)std::floor(start_.y());\n  z_ = (int)std::floor(start_.z());\n  endX_ = (int)std::floor(end_.x());\n  endY_ = (int)std::floor(end_.y());\n  endZ_ = (int)std::floor(end_.z());\n  direction_ = (end_ - start_);\n  maxDist_ = direction_.squaredNorm();\n\n  // Break out direction vector.\n  dx_ = endX_ - x_;\n  dy_ = endY_ - y_;\n  dz_ = endZ_ - z_;\n\n  // Direction to increment x,y,z when stepping.\n  stepX_ = (int)signum((int)dx_);\n  stepY_ = (int)signum((int)dy_);\n  stepZ_ = (int)signum((int)dz_);\n\n  // See description above. The initial values depend on the fractional\n  // part of the origin.\n  tMaxX_ = intbound(start_.x(), dx_);\n  tMaxY_ = intbound(start_.y(), dy_);\n  tMaxZ_ = intbound(start_.z(), dz_);\n\n  // The change in t when taking a step (always positive).\n  tDeltaX_ = ((double)stepX_) / dx_;\n  tDeltaY_ = ((double)stepY_) / dy_;\n  tDeltaZ_ = ((double)stepZ_) / dz_;\n\n  dist_ = 0;\n\n  step_num_ = 0;\n\n  // Avoids an infinite loop.\n  if (stepX_ == 0 && stepY_ == 0 && stepZ_ == 0)\n    return false;\n  else\n    return true;\n}\n\nbool RayCaster::step(Eigen::Vector3d& ray_pt) {\n  // if (x_ >= min_.x() && x_ < max_.x() && y_ >= min_.y() && y_ < max_.y() &&\n  // z_ >= min_.z() && z_ <\n  // max_.z())\n  ray_pt = Eigen::Vector3d(x_, y_, z_);\n\n  // step_num_++;\n\n  // dist_ = (Eigen::Vector3d(x_, y_, z_) - start_).squaredNorm();\n\n  if (x_ == endX_ && y_ == endY_ && z_ == endZ_) {\n    return false;\n  }\n\n  // if (dist_ > maxDist_)\n  // {\n  //   return false;\n  // }\n\n  // tMaxX stores the t-value at which we cross a cube boundary along the\n  // X axis, and similarly for Y and Z. Therefore, choosing the least tMax\n  // chooses the closest cube boundary. Only the first case of the four\n  // has been commented in detail.\n  if (tMaxX_ < tMaxY_) {\n    if (tMaxX_ < tMaxZ_) {\n      // Update which cube we are now in.\n      x_ += stepX_;\n      // Adjust tMaxX to the next X-oriented boundary crossing.\n      tMaxX_ += tDeltaX_;\n    } else {\n      z_ += stepZ_;\n      tMaxZ_ += tDeltaZ_;\n    }\n  } else {\n    if (tMaxY_ < tMaxZ_) {\n      y_ += stepY_;\n      tMaxY_ += tDeltaY_;\n    } else {\n      z_ += stepZ_;\n      tMaxZ_ += tDeltaZ_;\n    }\n  }\n\n  return true;\n}", "meta": {"hexsha": "755794d3587f16639c301084a7edc1a62a42c3dd", "size": 11251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TIE_navigation/plan_env/src/raycast.cpp", "max_stars_repo_name": "ZJU-FAST-Lab/Terrestrial-Aerial-Navigation", "max_stars_repo_head_hexsha": "3602623ff8cb9735c6ece8c25772a3809cb0362e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2022-01-09T06:35:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T02:34:39.000Z", "max_issues_repo_path": "src/TIE_navigation/plan_env/src/raycast.cpp", "max_issues_repo_name": "RoboticsZhang/Terrestrial-Aerial-Navigation", "max_issues_repo_head_hexsha": "d73b6fa9d51985f442fda6d0e282226cb7a45186", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TIE_navigation/plan_env/src/raycast.cpp", "max_forks_repo_name": "RoboticsZhang/Terrestrial-Aerial-Navigation", "max_forks_repo_head_hexsha": "d73b6fa9d51985f442fda6d0e282226cb7a45186", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-09T05:44:24.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T05:44:24.000Z", "avg_line_length": 32.5173410405, "max_line_length": 111, "alphanum_fraction": 0.6059905786, "num_tokens": 3399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.43391227684662603}}
{"text": "/*\n * TreeIkSolverVel_wdls.hpp\n *\n *  Created on: Nov 28, 2008\n *      Author: rubensmits\n */\n\n#ifndef TREEIKSOLVERVEL_WDLS_HPP_\n#define TREEIKSOLVERVEL_WDLS_HPP_\n\n#include \"treeiksolver.hpp\"\n#include \"treejnttojacsolver.hpp\"\n#include <Eigen/Core>\n\nnamespace KDL {\n\n    class TreeIkSolverVel_wdls: public TreeIkSolverVel {\n    public:\n        static const int E_SVD_FAILED = -100; //! Child SVD failed\n\n        TreeIkSolverVel_wdls(const Tree& tree, const std::vector<std::string>& endpoints);\n        virtual ~TreeIkSolverVel_wdls();\n        \n        virtual double CartToJnt(const JntArray& q_in, const Twists& v_in, JntArray& qdot_out);\n\n        /*\n         * Set the joint space weighting matrix\n         *\n         * @param weight_js joint space weighting symmetric matrix,\n         * default : identity.  M_q : This matrix being used as a\n         * weight for the norm of the joint space speed it HAS TO BE\n         * symmetric and positive definite. We can actually deal with\n         * matrices containing a symmetric and positive definite block\n         * and 0s otherwise. Taking a diagonal matrix as an example, a\n         * 0 on the diagonal means that the corresponding joints will\n         * not contribute to the motion of the system. On the other\n         * hand, the bigger the value, the most the corresponding\n         * joint will contribute to the overall motion. The obtained\n         * solution q_dot will actually minimize the weighted norm\n         * sqrt(q_dot'*(M_q^-2)*q_dot). In the special case we deal\n         * with, it does not make sense to invert M_q but what is\n         * important is the physical meaning of all this : a joint\n         * that has a zero weight in M_q will not contribute to the\n         * motion of the system and this is equivalent to saying that\n         * it gets an infinite weight in the norm computation.  For\n         * more detailed explanation : vincent.padois@upmc.fr\n         */\n        void setWeightJS(const Eigen::MatrixXd& Mq);\n        const Eigen::MatrixXd& getWeightJS() const {return Wq;}\n        \n        /*\n         * Set the task space weighting matrix\n         *\n         * @param weight_ts task space weighting symmetric matrix,\n         * default: identity M_x : This matrix being used as a weight\n         * for the norm of the error (in terms of task space speed) it\n         * HAS TO BE symmetric and positive definite. We can actually\n         * deal with matrices containing a symmetric and positive\n         * definite block and 0s otherwise. Taking a diagonal matrix\n         * as an example, a 0 on the diagonal means that the\n         * corresponding task coordinate will not be taken into\n         * account (ie the corresponding error can be really big). If\n         * the rank of the jacobian is equal to the number of task\n         * space coordinates which do not have a 0 weight in M_x, the\n         * weighting will actually not impact the results (ie there is\n         * an exact solution to the velocity inverse kinematics\n         * problem). In cases without an exact solution, the bigger\n         * the value, the most the corresponding task coordinate will\n         * be taken into account (ie the more the corresponding error\n         * will be reduced). The obtained solution will minimize the\n         * weighted norm sqrt(|x_dot-Jq_dot|'*(M_x^2)*|x_dot-Jq_dot|).\n         * For more detailed explanation : vincent.padois@upmc.fr\n         */\n        void setWeightTS(const Eigen::MatrixXd& Mx);\n        const Eigen::MatrixXd& getWeightTS() const {return Wy;}\n\n        void setLambda(const double& lambda);\n        double getLambda () const {return lambda;}\n\n    private:\n        Tree tree;\n        TreeJntToJacSolver jnttojacsolver;\n        Jacobians jacobians;\n        \n        Eigen::MatrixXd J, Wy, Wq, J_Wq, Wy_J_Wq, U, V, Wy_U, Wq_V;\n        Eigen::VectorXd t, Wy_t, qdot, tmp, S;\n        double lambda;\n    };\n    \n}\n\n#endif /* TREEIKSOLVERVEL_WDLS_HPP_ */\n", "meta": {"hexsha": "d6873d1b737f6d40ff4d63b371786e5c0fe719ff", "size": 3969, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdparty/kdl/src/treeiksolvervel_wdls.hpp", "max_stars_repo_name": "rocos-sia/rocos-app", "max_stars_repo_head_hexsha": "83aa8aa31dd303d77693cfc5ad48055d051fa4bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-12-06T15:30:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:21:40.000Z", "max_issues_repo_path": "3rdparty/kdl/src/treeiksolvervel_wdls.hpp", "max_issues_repo_name": "thinkexist1989/rocos-app", "max_issues_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/kdl/src/treeiksolvervel_wdls.hpp", "max_forks_repo_name": "thinkexist1989/rocos-app", "max_forks_repo_head_hexsha": "7d6ab256c8212504b0a8bbe1ec1dea0c41ea3ff2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.6774193548, "max_line_length": 95, "alphanum_fraction": 0.6535651298, "num_tokens": 947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.43391227684662603}}
{"text": "// written by bastiaan konings schuiling 2008 - 2014\n// this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important.\n// i do not offer support, so don't ask. to be used for inspiration :)\n\n#include \"bluntmath.hpp\"\n\n#include <cmath>\n\n#include <boost/random.hpp>\n\n#include <boost/thread/mutex.hpp>\n\nnamespace blunted {\n\n  unsigned int fastrandseed;\n  unsigned int max_uint;\n\n  boost::mutex randMutex;\n\n  typedef boost::mt19937 BaseGenerator;\n  typedef boost::uniform_real<float> Distribution;\n  typedef boost::variate_generator<BaseGenerator, Distribution> Generator;\n  BaseGenerator base;\n  Distribution dist;\n  Generator rng(base, dist);\n\n  real clamp(const real value, const real min, const real max) {\n    assert(max >= min);\n    if (min > value) return min;\n    if (max < value) return max;\n    return value;\n  }\n\n  real NormalizedClamp(const real value, const real min, const real max) {\n    assert(max > min);\n    real banana = clamp(value, min, max);\n    banana = (banana - min) / (max - min);\n    return banana;\n  }\n\n  real invsqrt(real fvalue) {\n    return 1. / sqrt(fvalue);\n  }\n\n  float dot_product(real v1[3], real v2[3]) {\n    return (v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]);\n  }\n\n  void normalize(real v[3]) {\n    real f = 1.0f / sqrt(dot_product(v, v));\n\n    v[0] *= f;\n    v[1] *= f;\n    v[2] *= f;\n  }\n\n  bool sign(real n) {\n    return n >= 0;\n  }\n\n  signed int signSide(real n) {\n    return n >= 0 ? 1 : -1;\n  }\n\n  bool is_odd(int n) {\n    return n & 1;\n  }\n\n  void randomseed() {\n    rng.engine().seed(static_cast<unsigned int>(std::time(0)));\n  }\n\n  inline real boostrandom() {\n    return rng();\n  }\n\n  real random(real min, real max) {\n    float stretch = max - min;\n\n    randMutex.lock();\n    real value = min + (boostrandom() * stretch);\n    randMutex.unlock();\n    return value;\n  }\n\n  int pot(int x) {\n    int val = 1;\n    while (val < x) {\n      val *= 2;\n    }\n    return val;\n  }\n\n  real ModulateIntoRange(real min, real max, real value) {\n    real step = max - min;\n    real newValue = value;\n    while (newValue < min) newValue += step;\n    while (newValue > max) newValue -= step;\n    return newValue;\n  }\n\n}\n", "meta": {"hexsha": "27816d742481913f1279b7f7131e6b7216194bd4", "size": 2215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/base/math/bluntmath.cpp", "max_stars_repo_name": "vi3itor/Blunted2", "max_stars_repo_head_hexsha": "318af452e51174a3a4634f3fe19b314385838992", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 56.0, "max_stars_repo_stars_event_min_datetime": "2020-07-22T22:11:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T08:11:43.000Z", "max_issues_repo_path": "GameplayFootball/src/base/math/bluntmath.cpp", "max_issues_repo_name": "ElsevierSoftwareX/SOFTX-D-20-00016", "max_issues_repo_head_hexsha": "48c28adb72aa167a251636bc92111b3c43c0be67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-04-22T07:06:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-22T12:54:52.000Z", "max_forks_repo_path": "GameplayFootball/src/base/math/bluntmath.cpp", "max_forks_repo_name": "ElsevierSoftwareX/SOFTX-D-20-00016", "max_forks_repo_head_hexsha": "48c28adb72aa167a251636bc92111b3c43c0be67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2017-11-07T16:52:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T02:42:48.000Z", "avg_line_length": 21.5048543689, "max_line_length": 132, "alphanum_fraction": 0.6216704289, "num_tokens": 636, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4339122709457717}}
{"text": "/* author: jakob fischer (mail@jakobfischer.eu)\n * description: \n * Tool for solving a ODE for a reaction system given as an jrnf-file. The concentration and time\n * are read and written from / to a comma seperated file. Every row / line represents one time step.\n * the first column contains the time of this step, the second the mean of the quadratic change \n * (<f(x)> ;dx/dt = f(x)). Then follow the concentrations of all species. \n *\n * One version of the program (option \"simulate\" calculates effective reaction rates directly\n * from formation enthalpies and activation energies given in the network description. \n * (\\beta = 1/(k_b T) = 1). This allows higher precision and usage of an explicit solver which\n * is over all faster for small networks (< 50 species). \n *\n * TODO There seems to be a problem with exceptionally short steps (distances in the\n *      <times> vector given to integrate_times) as well as with very wide steps. This\n *      occurs when the \"write_log\" option lead to output step sizes below 1e-7 or \n *      above 1e7. The solution for now is to first use linear stepping, then \n *      \"write_log_abs\" and at larger timescale linear stepping again. \n *      Giving a minimal and maximal step size as parameter might be a good \n *      improvement for future versions! \n */\n\n#include <iostream>\n#include <fstream>\n#include <ctime>\n#include <utility>\n\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n\n#include <algorithm>\n#include \"tools/cl_para.h\"\n#include \"net_tools/reaction_network.h\"\n#include \"net_tools/reaction_network_fileop.h\"\n#include \"net_tools/network_tools.h\"\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n\n#ifndef GIT_VERSION\n#define GIT_VERSION \"no version\"\n#endif\n\n// version string increment if mayor changes happen\nconst string odeint_rnet_version_string=\"1x00x00\";\n\n// various ublas types needed for implicit solver\ntypedef boost::numeric::ublas::vector< double > vector_type;\ntypedef boost::numeric::ublas::matrix< double > matrix_type;\ntypedef boost::numeric::ublas::matrix< int > matrix_type_int;\n\n\n/*\n * Main class that bundles the functionality to load reaction networks and \n * files containing species' concentration. Every object is associated with\n * an network and concentration file at creation. The class offers methods\n * for solving the ODE defined by the network and write the results to the\n * concentration file.\n */\n\nclass reaction_network_system {\n    double beta;                // beta = 1/(k_b T)\n    std::vector<species> sp;    // The reaction\n    std::vector<reaction> re;   // network\n    // initial time, concentration loaded with concentration file\n    double initial_t;    \n    vector_type initial_con;\n    std::string fn_concentration;      // filename\n\n    matrix_type_int N, N_in, N_out;    // stoichiometric matrices\n    // List that contains for each column in N_in / N_out (= for each reaction)\n    // a vector of those rows (species) that are nonzero.\n    std::vector< std::vector<size_t> > N_in_list, N_out_list;\n    // Intermediate values / thermodynamic values\n    vector_type Ea, mu0, e_bs_in, e_bs_out, e_m_bEa;\n\npublic:\n\n    /*\n     * Simple calculation of concentration change (rhs / f(x)) from species \n     * concentration and reaction constants (<k>, <k_b>).\n     */\n\n    struct fast_system {\n        reaction_network_system& rns;\n\n        fast_system(reaction_network_system& rns_) : rns(rns_)  {}\n\n        // <x> - state / concentration;  dxdt - change / rhs (output)\n        void operator()( const vector_type &x , vector_type &dxdt , double /* t */ ) {\n\n            for(size_t i=0; i<rns.sp.size(); ++i) \n                dxdt[i]=0;\n    \n            for(size_t i=0; i<rns.re.size(); ++i) {\n                double rate_f=rns.re[i].get_k();\n\t        double rate_b=rns.re[i].get_k_b();\n\t \n                for(size_t j=0; j<rns.re[i].get_no_educt_s(); ++j)\n                    rate_f *= x[rns.re[i].get_educt_id(j)];\n\n                for(size_t j=0; j<rns.re[i].get_no_product_s(); ++j)\n                    rate_b *= x[rns.re[i].get_product_id(j)];\n\t   \n                for(size_t j=0; j<rns.re[i].get_no_educt_s(); ++j)\n                    dxdt[rns.re[i].get_educt_id(j)] -= (rate_f - rate_b);\n\n                for(size_t j=0; j<rns.re[i].get_no_product_s(); ++j)\n                    dxdt[rns.re[i].get_product_id(j)] += (rate_f - rate_b);\n             }\n\n            for(size_t i=0; i<rns.sp.size(); ++i)\n                if(rns.sp[i].is_constant())\n\t            dxdt[i]=0;\n         }\n    };\n\n\n    /*\n     * Calculation of concentration change (rhs) from species concentration \n     * and thermodynamic values (energies).\n     */\n\n    struct stiff_system {\n        reaction_network_system& rns;\n\n        stiff_system(reaction_network_system& rns_) : rns(rns_)  {}\n\n        // Function to calculate reaction rates of state <x> into <rates>.\n        void calculate_rates(const vector_type &x, vector_type &rates) {\n            vector_type a2(rns.re.size()), a3(rns.re.size());\n            for(size_t j=0; j<rns.N.size2(); ++j) { \n                a2(j) = 1;\n                a3(j) = 1; \n\n                for(size_t k=0; k<x.size(); ++k) {             \n                    if(rns.N_in(k,j) != 0) \n                        a2(j) *= pow(x(k), rns.N_in(k,j));\n\n                    if(rns.N_out(k,j) != 0) \n                        a3(j) *= pow(x(k), rns.N_out(k,j));\n                }\n            }         \n\n            rates = element_prod(rns.e_m_bEa, element_prod(a2, rns.e_bs_in) - element_prod(a3, rns.e_bs_out));\n        }\n\n        // <x> - state / concentration;  <J> - Jacobi matrix (output);  dfdt - time partial differential (output)\n        void operator()( const vector_type &x , vector_type &dxdt , double /* t */ ) {\n            vector_type a2(rns.re.size()), a3(rns.re.size());\n            for(size_t j=0; j<rns.N.size2(); ++j) { \n                a2(j) = 1;\n                a3(j) = 1; \n\n                for(size_t l=0; l<rns.N_in_list[j].size(); ++l) \n                        a2(j) *= pow(x(rns.N_in_list[j][l]), rns.N_in(rns.N_in_list[j][l],j));\n\n                for(size_t l=0; l<rns.N_out_list[j].size(); ++l) \n                        a3(j) *= pow(x(rns.N_out_list[j][l]), rns.N_out(rns.N_out_list[j][l],j));\n\n            }         \n\n            dxdt = prod(rns.N, element_prod(rns.e_m_bEa, element_prod(a2, rns.e_bs_in) - element_prod(a3, rns.e_bs_out)));\n\n            for(size_t k=0; k<x.size(); ++k)\n                if(rns.sp[k].is_constant())\n                    dxdt(k) = 0;\n        }\n    };\n\n\n    /*\n     * Calculation of Jacobi matrix from species concentration and thermodynamic\n     * values (energies).\n     */\n\n    struct stiff_system_jacobi {\n        const reaction_network_system& rns;\n\n        stiff_system_jacobi(const reaction_network_system& rns_) : rns(rns_)  {}\n\n        // <x> - state / concentration;  <J> - Jacobi matrix (output);  dfdt - time partial differential (output)\n        void operator()( const vector_type & x  , matrix_type &J , const double & /* t */ , vector_type &dfdt ) {\n            for(size_t i=0; i<x.size(); ++i) {\n                for(size_t l=0; l<x.size(); ++l) {\n                    double s(0);\n                    \n                    for(size_t k=0; k<rns.re.size(); ++k) {    \n                        double p1(1), p2(1);    // p1 = \\prod_{j \\neq k} {x_j}^N_{jk}^\\mathrm{in}\n                                                // p2 = \\prod_{j \\neq k} {x_j}^N_{jk}^\\mathrm{out}\n\n                        for(size_t m=0; m<rns.N_in_list[k].size(); ++m) {\n                            size_t j=rns.N_in_list[k][m];\n                            \n                            if(j != l)\n                                p1 *= x(j);\n                        }\n    \n                        for(size_t m=0; m<rns.N_out_list[k].size(); ++m) {\n                            size_t j=rns.N_out_list[k][m];\n\n                            if(j != l && rns.N_out(j,k) != 0)\n                                p2 *= x(j);\n                        } \n                      \n                        s += rns.N(i,k)*rns.e_m_bEa(k)*(rns.e_bs_in(k)*rns.N_in(l,k)*pow(x(l), rns.N_in(l,k)-1)*p1 - \n                                                        rns.e_bs_out(k)*rns.N_out(l,k)*pow(x(l),rns.N_out(l,k)-1)*p2);              \n                    }                    \n\n                    J(i,l) = s;\n                    if(rns.sp[i].is_constant())\n                        J(i,l) = 0;\n                }\n            }                               \n\n            dfdt = boost::numeric::ublas::zero_vector<double>(x.size());\n        }\n    };\n\n\n    /*\n     * Constructor that loads the network file as well as the concentration file\n     * (for initial concentration). Also all temporary values that are necessary to\n     * solve (calculate rhs + Jacobi matrix) the ode faster are calculated.\n     */\n\n    reaction_network_system(const std::string& fn_network, const std::string& fn_concentration_) \n        : fn_concentration(fn_concentration_), beta(1) {\n        // load network into <re> and <sp>\n        read_jrnf_reaction_n(fn_network, sp, re);\n    \n\t// Remove 1-0 and 0-1 reactions. Such reactions are there to ballance flow through the boundary conditions\n        std::remove_if (re.begin(), re.end(), \n                        [] (reaction& re) -> bool { \n                            return re.get_no_educt() == 1 && re.get_no_product() == 0 || \n                                   re.get_no_educt() == 0 && re.get_no_product() == 1; });\n\t\t\n        // Calculate stoichiometric matrices, activation energies and their logarithms...\n        N_in = N_out = boost::numeric::ublas::zero_matrix<double>(sp.size(), re.size());\n        Ea =  e_bs_in = e_bs_out = e_m_bEa = boost::numeric::ublas::zero_vector<double>(re.size());\n        mu0 = boost::numeric::ublas::zero_vector<double>(sp.size());\n\n        // Load species standard gibbs energy / chemical energy into mu0\n        for(size_t i=0; i<sp.size(); ++i)\n            mu0(i) = sp[i].get_energy();\n\n        // Load / calculate reaction specific quantities like activation Energy \n        // <Ea> and joint energy of educts <m0_educts> or products <mu0_products>.\n        for(size_t i=0; i<re.size(); ++i) {\n            double mu0_educts(0), mu0_products(0);\n\n            for(size_t j=0; j<re[i].get_no_educt_s(); ++j) {\n                size_t id(re[i].get_educt_id(j)),  mul(re[i].get_educt_mul(j));\n                N_in(id,i) += mul;\n                mu0_educts += sp[id].get_energy()*mul;\n            }\n\n            for(size_t j=0; j<re[i].get_no_product_s(); ++j) {\n                size_t id(re[i].get_product_id(j)),  mul(re[i].get_product_mul(j));\n                N_out(id,i) += mul;\n                mu0_products += sp[id].get_energy()*mul;\n            }\n            \n            Ea(i) = re[i].get_activation()+max(mu0_educts,mu0_products);\n            e_bs_in(i) = exp(beta*mu0_educts);\n            e_bs_out(i) = exp(beta*mu0_products);\n            e_m_bEa(i) = exp(-beta*Ea(i));\n        }\n\n        N = N_out-N_in;\n\n        // Build lists (for speedup)        \n        for(size_t i=0; i<re.size(); ++i) {\n            N_in_list.push_back(std::vector<size_t>());\n            N_out_list.push_back(std::vector<size_t>());\n\n            for(size_t j=0; j<sp.size(); ++j) {\n                if(N_in(j,i) != 0)\n                    N_in_list[i].push_back(j);\n\n                if(N_out(j,i) != 0)\n                    N_out_list[i].push_back(j);\n            }\n        }\n        \n        // Read last line of concentration file and write initial concentration to initial_con\n        // and initial time to initial_t. When done, open the same file for appending...\n        initial_con = boost::numeric::ublas::zero_vector<double>(sp.size());\n\n        std::ifstream  data(fn_concentration.c_str());\n\n        if(!data.good()) {\n           std::cout << \"Could not open concentration file: \" << fn_concentration << std::endl;\n           return;\n        }\n\n        std::string line;\n        std::getline(data,line);       // dont want the header\n        double last_msd=0;\n\n        // Get line of actual data\n        while(!std::getline(data,line).eof()) {\n            std::stringstream ls(line);\n            std::string cell;\n\n            // read in value by value and count its position to place it in the\n            // right variables\n            size_t cnt=0;\n            while(std::getline(ls,cell,',')) {\n                std::stringstream in(cell);       \n    \n                if(cnt == 0) \n                    in >> initial_t ;\n                else if(cnt == 1)\n                    in >> last_msd;                \n                else if(cnt <= sp.size()+1)\n                    in >> initial_con(cnt-2);\n                else\n                    std::cout << \"Error at reading csv / concentration file!\" << std::endl;\n\n                ++cnt;\n            }\n        }\n\n        std::cout << \"Simulating file: \" << fn_concentration << std::endl;\n        std::cout << \"Loaded concentration file with starting time \" << initial_t << std::endl;\n        data.close();        \n    }\n\n\n    /*\n     * To check some differential equations or the algorithm it might be usefull\n     * to calculate the right hand side of the differential equation for a given\n     * concentration vector.\n     */\n\n    void print_rhs() {\n        vector_type x(initial_con);\n        vector_type dxdt=boost::numeric::ublas::zero_vector<double>(sp.size());\n \n        // calculate rhs - operator saves it do dxdt\n        stiff_system(*this)(x, dxdt, 0);\n\n        cout << \"righthandside:\" << endl;\n        for(size_t i=0; i<dxdt.size(); ++i)\n            cout << \"/  \" << dxdt(i) << \"  /\";\n        cout << endl;\n    }\n\n\n    /*\n     * Method for calling the system that uses energetics for calculating effective\n     * rates and allows usage of a stiff solver - implicit stepper. System (f(x)) \n     * is defined in \"stiff_system\" (rhs) and \"stiff_system_jacobi (Jacobi matrix).\n     *\n     * Tmax           - time up to that ode is solved\n     * deltaT         - initial step size for addaptive stepper (does not relate to time output is written) \n     * solve_implicit - do use implicit solver?\n     * wint           - number of time output is written to output file between time of last \n     *                  entry in concentration file and Tmax\n     * write_log = 0  - linearly spaced times for output\n     *           = 1  - logarithmically spaced (relative -> log(t-t0) is equidist.)\n     *           = 2  - logarithmically spaced (absolute -> log(t) is equidist.)             \n     */\n\n    void run(double Tmax=25000, double deltaT=0.1, bool solve_implicit=true, \n             size_t wint=500, size_t write_log=0) {    \n        fstream out(fn_concentration.c_str(), std::ios_base::out | std::ios_base::app);\n        out.precision(25);\n\n        size_t t0 = time(NULL);  \n\n        // Init solver and start\n        vector_type x(initial_con), last_con(initial_con);\n        double last_write(initial_t);\n        \n        // Function that is called by stepper and writes concentration (<vec>) to file.\n        auto write_state = [this, &out, t0, wint, deltaT, Tmax, &last_con, &last_write]( const vector_type &vec , const double t ) {\n            // calculate mean square distance from last write\n            double last_msd=0;\n            for(size_t i=0; i<vec.size(); ++i)\n                 last_msd += (vec[i]-last_con[i])*(vec[i]-last_con[i]);\n\n            if(t != last_write)\n                last_msd /= (vec.size()*(t-last_write));\n            last_write=t;\n            last_con=vec;\n\n            // write time and msd ...\n            out << t << \",\" << last_msd;\n            // and concentrations\n            for(size_t l=0; l<vec.size(); ++l)\n                out << \",\" << vec(l);\n\n            out << std::endl;\n        };\n\n\n        size_t step_no = 0;  // Number of steps done by integrator (for diagnostics)\n        // Calculate vector of time points at which \"write_state\" will be called.\n        std::vector<double> times( wint );\n        for( size_t i=0 ; i<wint ; ++i ) \n            if(write_log == 0) \n                // linearly spaced output times\n                times[i] = initial_t + double(i+1)/(wint)*(Tmax-initial_t);\n            else if(write_log == 1 || initial_t == 0) \n                // logarithmically spaced output times (relative to t0)\n                times[i] = initial_t + (exp(double(i+1))-1)/(exp(double(wint))-1)*(Tmax-initial_t);\n            else \n                // if t0!=0 and one want's logarithmically spaced times (relative to t=0)!\n                times[i] = initial_t*pow(exp(1/double(wint)*log(Tmax/initial_t)),double(i+1));\n\n        // Call integrator - returns number of steps. Either implicit or explicit stepper is used.\n        step_no = solve_implicit ?\n                      integrate_times( make_controlled< rosenbrock4< double > >( 1.0e-6 , 1.0e-6 ) ,\n                                       make_pair( stiff_system(*this) , stiff_system_jacobi(*this) ) ,\n                                       x , times, deltaT, write_state) :\n                      integrate_times( make_controlled< runge_kutta_dopri5< vector_type > >( 1.0e-6 , 1.0e-6 ) ,\n                                       stiff_system(*this) , x, times, deltaT, write_state);\n\n        // print time + steps needed and close file\n        size_t t1 = time(NULL);\n        std::cout << \"Run took \" << t1-t0 << \" seconds and \" << step_no << \" steps!\" << std::endl;\n        out.close();\n   }\n\n\n   /* \n    * The fastint integration (calculating forward and backward rates directly \n    * through reaction constants) needs the networks to be exanded what this \n    * method ensures (multiple occurance of same educt product in same reaction\n    * has to be explicit - \"A + A\" instead of \"2 A\").\n    */\n\n    void initialize_fastint() {\n        for(size_t i=0; i<re.size(); ++i) {\n            for(size_t j=0; j<re[i].get_no_educt_s(); ++j) { \n                if(re[i].get_educt_mul(j) > 1.1) {\n                    re[i].add_educt_s(re[i].get_educt_id(j), re[i].get_educt_mul(j)-1);\n                    re[i].set_educt_mul(j,1.0);\n                }\n            }\n\n            for(size_t j=0; j<re[i].get_no_product_s(); ++j) { \n                if(re[i].get_product_mul(j) > 1.1) {\n                    re[i].add_product_s(re[i].get_product_id(j), re[i].get_product_mul(j)-1);\n                    re[i].set_product_mul(j,1.0);\n                }\n            }\n        }\n    }\n\n    /*\n     * Method for calling the simple / fast integrator that uses explicit stepping and \n     * the reaction constants defined in the network object. System (f(x)) is defined \n     * in \"fast_system\".\n     * For description of method's parameters see method \"run\" above.\n     */\n\n    void run_fastint(double Tmax=25000, double deltaT=0.1, size_t wint=500, size_t write_log=0) {\n        fstream out(fn_concentration.c_str(), std::ios_base::out | std::ios_base::app);\n        out.precision(25);\n\n        size_t t0 = time(NULL);\n\n        vector_type x(initial_con), last_con(initial_con);\n        double last_write(initial_t);\n         \n        // Function that is called by stepper and writes concentration (<vec>) to file.\n        auto write_state = [this, &out, t0, wint, deltaT, Tmax, &last_con, &last_write]( const vector_type &vec , const double t ) {\n            // calculate mean square distance from last write\n            double last_msd=0;\n            for(size_t i=0; i<vec.size(); ++i)\n                 last_msd += (vec[i]-last_con[i])*(vec[i]-last_con[i]);\n            if(t != last_write)\n                last_msd /= (vec.size()*(t-last_write));\n            last_write=t;\n            last_con=vec;\n\n            // write time + msd...\n            out << t << \",\" << last_msd;\n            // ...and all concentrations\n            for(size_t l=0; l<vec.size(); ++l)\n                out << \",\" << vec(l);\n\n            // If msd (change of concentration) per time and per species is less \n            // than 1e-20 but not zero this integrator stops early because the\n            // assumption is that the network is converged. (Might not be true in\n            // the strict sense for all imaginable networks that can be simulated!)\n            if(last_msd > 1e-44 && last_msd < 1e-20) {\n                std::cout << \"Reached msd < 1e-20 condition - exiting early!\" << std::endl;\n                size_t t1 = time(NULL);\n                std::cout << \"Run took \" << t1-t0 << \" seconds!\" << std::endl;\n                exit(0);\n            }\n\n            out << std::endl;\n        };\n\n        // Calculate vector of time points at which \"write_state\" will be called.\n        // For details see same code in method \"run\" above.\n        std::vector<double> times( wint );\n        for( size_t i=0 ; i<wint ; ++i ) \n            if(write_log == 0) \n                times[i] = initial_t + double(i+1)/(wint)*(Tmax-initial_t);\n            else if(write_log == 1 || initial_t == 0) \n                times[i] = initial_t + (exp(double(i+1))-1)/(exp(double(wint))-1)*(Tmax-initial_t);\n            else \n                times[i] = initial_t*pow(exp(1/double(wint)*log(Tmax/initial_t)),double(i+1));\n\n        // Call integrator - returns number of steps\n        size_t step_no = integrate_times( make_dense_output< runge_kutta_dopri5< vector_type > >( 1.0e-6 , 1.0e-6 ) ,\n                         fast_system(*this) , x, times, deltaT, write_state);\n\n        // print time + steps needed and close file\n        size_t t1 = time(NULL);\n        std::cout << \"Run took \" << t1-t0 << \" seconds and \" << step_no << \" steps!\" << std::endl;\n        out.close();\n   }\n};\n\n\n/*\n * Main-Function. Manages commandline parameter and prints help screen.\n * All the real work is done through using the reaction_network_system \n * class (above).\n */\n\nint main(int argc, const char *argv []){\n    srand(time(0));\n    std::cout << \"odeint_rnet version \" << odeint_rnet_version_string << \" (commit:\" \n              << GIT_VERSION << \")\" << std::endl;\n    \n    cl_para cl(argc, argv);  // create class to query command line parameters\n    \n\n    // Prints the right hand side of the ODE (f(x)) for diagnostic purposes.\n\n    if(cl.have_param(\"print_rhs\")) {\n        std::string fn_network, fn_concentration;      \n\n        if(cl.have_param(\"net\")) \n            fn_network=cl.get_param(\"net\");\n        else {\n            cout << \"You have to give the name of reaction network by 'net'!\" << endl;  \n            return 1;\n        }\n    \n        if(cl.have_param(\"con\")) \n            fn_concentration=cl.get_param(\"con\");\n        else {\n            cout << \"You have to give the name of the concentration file by 'con'!\" << endl;   \n            return 1;\n        }\n\n        // load network and concentration file and call function to print right hand side\n        reaction_network_system rns = reaction_network_system(fn_network, fn_concentration); \n        rns.print_rhs();  \n    }  \n\n\n    // Simulates / integrates a reaction network while holding the boundary point \n    // species (constant=true) constant. Effective reaction rates are calculated \n    // directly from chemical energies. Stiff solver is available with option\n    // \"solve_implicit\". Very slow for larger networks (>50 species).\n    \n    if(cl.have_param(\"simulate\")) {\n        std::string fn_network, fn_concentration;      \n\n        if(cl.have_param(\"net\")) \n            fn_network=cl.get_param(\"net\");\n        else {\n            cout << \"You have to give the name of reaction network by 'net'!\" << endl;  \n            return 1;\n        }\n    \n        if(cl.have_param(\"con\")) \n            fn_concentration=cl.get_param(\"con\");\n        else {\n            cout << \"You have to give the name of the concentration file by 'con'!\" << endl;   \n            return 1;\n        }\n\n        // Initial time-step for integrator\n        double deltaT = cl.have_param(\"deltaT\") ? cl.get_param_d(\"deltaT\") : 0.1;   \n        // ODE is integrated up to <Tmax>\n        double Tmax = cl.have_param(\"Tmax\") ? cl.get_param_d(\"Tmax\") : 25000;  \n        // Number of times the output is written between initial time and <Tmax> \n        double wint = cl.have_param(\"wint\") ? cl.get_param_d(\"wint\") : 500;\n        // Use implicit solver?\n        bool solve_implicit=cl.have_param(\"solve_implicit\");    \n        // Is output given logarithmically spaced? (Or linearly?)        \n        size_t write_log=0;\n        if(cl.have_param(\"write_log\"))\n            write_log=1;\n        if(cl.have_param(\"write_log_abs\"))\n            write_log=2;\n            \n        std::cout << \"Parameters are deltaT=\" << deltaT << \"  and Tmax=\" << Tmax\n                  << \"   wint=\" << wint << std::endl;\n\n        if(write_log == 1) \n            cout << \"Period of output will be equidistant on logscale (from t=t_0).\" << endl;\n\n        if(write_log == 2) \n            cout << \"Period of output will be equidistant on logscale (from t=0).\" << endl;\n\n        if(solve_implicit)\n            cout << \"Stiff solver is used!\" << endl;\n\n        // Load reaction network and concentration file\n        reaction_network_system rns = reaction_network_system(fn_network, fn_concentration); \n\n        // Simulate ODE (and write results to file)\n        // The method gives diagnostic feedback to the user through console output\n        rns.run(Tmax, deltaT, solve_implicit, wint, write_log);\n    }  \n\n\n    // Simulates / integrates a reaction network while holding the boundary point \n    // species (constant=true) constant. Official parameter to call this is \n    // \"fastint\", the option to call using \"simsim\" is maintained for backward\n    // compatibility. This integrator is faster as the one above, especially for\n    // larger (>50 species) networks. It uses the reaction constants present in \n    // the network and no stiff solver. \n\n    if(cl.have_param(\"fastint\") || cl.have_param(\"simsim\")) {\n        std::string fn_network, fn_concentration;      \n\n        if(cl.have_param(\"net\")) \n            fn_network=cl.get_param(\"net\");\n        else {\n            cout << \"You have to give the name of reaction network by 'net'!\" << endl;  \n            return 1;\n        }\n    \n        if(cl.have_param(\"con\")) \n            fn_concentration=cl.get_param(\"con\");\n        else {\n            cout << \"You have to give the name of the concentration file by 'con'!\" << endl;   \n            return 1;\n        }\n\n        // Initial time-step for integrator\n        double deltaT = cl.have_param(\"deltaT\") ? cl.get_param_d(\"deltaT\") : 0.1;   \n        // ODE is integrated up to <Tmax>\n        double Tmax = cl.have_param(\"Tmax\") ? cl.get_param_d(\"Tmax\") : 25000;  \n        // Number of times the output is written between initial time and <Tmax> \n        double wint = cl.have_param(\"wint\") ? cl.get_param_d(\"wint\") : 500;\n        // Is output given logarithmically spaced? (Or linearly?)        \n        size_t write_log=0;\n        if(cl.have_param(\"write_log\"))\n            write_log=1;\n        if(cl.have_param(\"write_log_abs\"))\n            write_log=2;\n            \n        std::cout << \"Parameters are deltaT=\" << deltaT << \"  and Tmax=\" << Tmax\n                  << \"   wint=\" << wint << std::endl;\n\n        if(write_log == 1) \n            cout << \"Period of output will be equidistant on logscale (from t=t_0).\" << endl;\n\n        if(write_log == 2) \n            cout << \"Period of output will be equidistant on logscale (from t=0).\" << endl;\n\n\n        // Load reaction network and concentration file\n        reaction_network_system rns = reaction_network_system(fn_network, fn_concentration); \n\n        // Simulate ODE (and write results to file)\n        // The method gives diagnostic feedback to the user through console output\n        rns.initialize_fastint();\n        rns.run_fastint(Tmax, deltaT, wint, write_log);\n    }  \n\n    \n    // User interface / help dialogue\n    if(cl.have_param(\"help\") || cl.have_param(\"info\")) {\n        cout << \"          odeint_rnet\" << endl;  \n        cout << \"          ===========\" << endl;\n        cout << \" call with parameter 'info' or 'help' for showing this screen\" << endl;\n        cout << \"current version is \" << odeint_rnet_version_string << \" (commit:\" << GIT_VERSION << \")\" << endl;\n        cout << endl;\n        cout << \"-'print_rhs': load reaction network 'net', (last) concentration in 'con'! and\" << endl;\n        cout << \"prints  right hand side of ode for diagnostic purposes.\" << endl;\n\tcout << endl;\n        cout << \"-'simulate': load reaction network 'net' and simulate file 'con'!. Parameters are:\" << endl;\n        cout << \"   x'deltaT': Integration interval (relevant for integrator, not for output!)\" << endl;\n        cout << \"   x'Tmax': Time up to which the system is simulated\" << endl;\n        cout << \"   x'wint': number of output times between Tstart and Tmax\" << endl;\n        cout << \"   x'write_log': write output logarithmically spaced (from t=t_0)\" << endl;\n        cout << \"   x'write_log_abs': write output logarithmically spaced from (t=0)\" << endl;\n        cout << \"   x'solve_implicit': use stiff solver (might be slower for big nets!)\" << endl;\n        cout << endl;\n        cout << \"-'fastint': load reaction network 'net' and simulate file 'con'!. Other than above\" << endl;\n        cout << \"   this integrator does not offer a stiff solver. It also does not use energies to\" << endl;\n        cout << \"   calculate effective rates directly but uses reaction constants. Parameters are:\" << endl;\n        cout << \"   x'deltaT': Integration interval (relevant for integrator, not for output!)\" << endl;\n        cout << \"   x'Tmax': Time up to which the system is simulated\" << endl;\n        cout << \"   x'wint': number of output times between Tstart and Tmax\" << endl;    \n        cout << \"   x'write_log': write output logarithmically spaced (from t=t_0)\" << endl;\n        cout << \"   x'write_log_abs': write output logarithmically spaced from (t=0)\" << endl;\n\tcout << endl;\n    } \n}\n", "meta": {"hexsha": "4d8486f2fe4530be58a0b5584629ee419f121754", "size": 29892, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "jakob-fischer/jrnf_int", "max_stars_repo_head_hexsha": "560f984b3f29de3294021c6fe2890e2c3e7f2b91", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "jakob-fischer/jrnf_int", "max_issues_repo_head_hexsha": "560f984b3f29de3294021c6fe2890e2c3e7f2b91", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "jakob-fischer/jrnf_int", "max_forks_repo_head_hexsha": "560f984b3f29de3294021c6fe2890e2c3e7f2b91", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.3399433428, "max_line_length": 132, "alphanum_fraction": 0.5574735715, "num_tokens": 7473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4338407198559663}}
{"text": "#include <armadillo>\n\n// pybind11\n#include <pybind11/numpy.h>\n#include <pybind11/stl.h>\n#include <pybind11/pybind11.h>\nnamespace py = pybind11;\n\n// Carma\n#include <carma/carma.h>\n\nstruct _neigh {\n    arma::mat data;\n    arma::colvec weights;\n    arma::uword n_rows;\n    _neigh(const arma::mat& m, const arma::mat& w):\n        data(w.n_elem, m.n_cols, arma::fill::zeros),\n        weights(w.n_elem, arma::fill::zeros),\n        n_rows(0) {}\n};\n\ntypedef _neigh neigh_t;\n\nvoid neigh_vec(neigh_t& n,\n               const arma::mat& m,\n               const arma::uword m_nrow,\n               const arma::uword m_ncol,\n               const arma::mat& w,\n               const arma::uword m_b,\n               const arma::uword m_i,\n               const arma::uword m_j) {\n\n    arma::uword w_leg_i = w.n_rows / 2, w_leg_j = w.n_cols / 2;\n\n    // copy values\n    arma::uword k = 0;\n    for (arma::uword i = 0; i < w.n_rows; ++i)\n        for (arma::uword j = 0; j < w.n_cols; ++j)\n            if (m_i + i >= w_leg_i && m_j + j >= w_leg_j &&\n                m_i + i < w_leg_i + m_nrow &&\n                m_j + j < w_leg_j + m_ncol &&\n                arma::is_finite(m(m_j + m_i * m_ncol, 0))) {\n\n                n.data(k, m_b) = m((m_j + j - w_leg_j) +\n                    (m_i + i - w_leg_i) * m_ncol, m_b);\n                n.weights(k++) = w(i, j);\n            }\n    n.n_rows = k;\n}\n\narma::colvec nm_post_mean_x(const arma::colvec& x,\n                            const arma::mat& sigma,\n                            const arma::colvec& mu0,\n                            const arma::mat& sigma0) {\n\n    // inverse sigma0\n    arma::mat inv_sum_weights(arma::size(sigma0));\n    inv_sum_weights = arma::inv(sigma + sigma0);\n\n    return sigma * inv_sum_weights * mu0 + sigma0 * inv_sum_weights * x;\n}\n\narma::mat bayes_smoother(const arma::mat& m,\n                         const arma::uword m_nrow,\n                         const arma::uword m_ncol,\n                         const arma::mat& w,\n                         const arma::mat& sigma,\n                         bool covar_sigma0) {\n\n    // initialize result matrix\n    arma::mat res(arma::size(m), arma::fill::none);\n    res.fill(arma::datum::nan);\n\n    // prior mean vector (neighbourhood)\n    arma::colvec mu0(m.n_cols, arma::fill::zeros);\n\n    // prior co-variance matrix (neighbourhood)\n    arma::mat sigma0(arma::size(sigma), arma::fill::zeros);\n\n    // neighbourhood\n    neigh_t neigh(m, w);\n\n    // compute values for each pixel\n    for (arma::uword i = 0; i < m_nrow; ++i)\n        for (arma::uword j = 0; j < m_ncol; ++j) {\n\n            // fill neighbours values\n            for (arma::uword b = 0; b < m.n_cols; ++b)\n                neigh_vec(neigh, m, m_nrow, m_ncol, w, b, i, j);\n\n            if (neigh.n_rows == 0) continue;\n\n            // compute prior mean\n            mu0 = arma::mean(neigh.data.rows(0, neigh.n_rows - 1), 0).as_col();\n\n            // compute prior sigma\n            sigma0 = arma::cov(neigh.data.rows(0, neigh.n_rows - 1), 0);\n\n            // prior sigma covariance\n            if (!covar_sigma0) {\n\n                // clear non main diagonal cells\n                sigma0.elem(arma::trimatu_ind(\n                        arma::size(sigma0), 1)).fill(0.0);\n                sigma0.elem(arma::trimatl_ind(\n                        arma::size(sigma0), -1)).fill(0.0);\n            }\n\n            // evaluate multivariate bayesian\n            res.row(j + i * m_ncol) =\n                nm_post_mean_x(m.row(j + i * m_ncol).as_col(),\n                               sigma, mu0, sigma0).as_row();\n        }\n    return res;\n}\n\narma::mat kernel_smoother(const arma::mat& m,\n                          const arma::uword m_nrow,\n                          const arma::uword m_ncol,\n                          const arma::mat& w,\n                          const bool normalised) {\n\n    // initialize result matrix\n    arma::mat res(arma::size(m), arma::fill::none);\n    res.fill(arma::datum::nan);\n\n    // neighbourhood\n    neigh_t neigh(m, w);\n\n    // compute values for each pixel\n    for (arma::uword b = 0; b < m.n_cols; ++b)\n        for (arma::uword i = 0; i < m_nrow; ++i)\n            for (arma::uword j = 0; j < m_ncol; ++j) {\n\n                // fill neighbours values\n                neigh_vec(neigh, m, m_nrow, m_ncol, w, b, i, j);\n\n                if (neigh.n_rows == 0) continue;\n\n                // normalise weight values\n                if (normalised)\n                    neigh.weights = neigh.weights /\n                        arma::sum(neigh.weights.subvec(0, neigh.n_rows - 1));\n\n                // compute kernel neighbourhood weighted mean\n                res(j + i * m_ncol, b) = arma::as_scalar(\n                    neigh.weights.subvec(0, neigh.n_rows - 1).as_row() *\n                        neigh.data.col(b).subvec(0, neigh.n_rows - 1));\n            }\n    return res;\n}\n\narma::mat bilinear_smoother(const arma::mat& m,\n                            const arma::uword m_nrow,\n                            const arma::uword m_ncol,\n                            const arma::mat& w,\n                            double tau) {\n\n    // initialize result matrix\n    arma::mat res(arma::size(m), arma::fill::none);\n    res.fill(arma::datum::nan);\n\n    // neighbourhood\n    neigh_t neigh(m, w);\n\n    // compute values for each pixel\n    for (arma::uword b = 0; b < m.n_cols; ++b)\n        for (arma::uword i = 0; i < m_nrow; ++i)\n            for (arma::uword j = 0; j < m_ncol; ++j) {\n\n                // fill neighbours values\n                neigh_vec(neigh, m, m_nrow, m_ncol, w, b, i, j);\n\n                if (neigh.n_rows == 0) continue;\n\n                // compute bilinear weight\n                arma::colvec bln_weight = neigh.weights % arma::normpdf(\n                    neigh.data.col(b) - m(j + i * m_ncol, b), 0, tau);\n\n                // normalise weight values\n                bln_weight = bln_weight /\n                    arma::sum(bln_weight.subvec(0, neigh.n_rows - 1));\n\n                // compute kernel neighbourhood weighted mean\n                res(j + i * m_ncol, b) = arma::as_scalar(\n                    bln_weight.subvec(0, neigh.n_rows - 1).as_row() *\n                    neigh.data.col(b).subvec(0, neigh.n_rows - 1));\n            }\n    return res;\n}\n\nvoid PyInit_smoothing(py::module &m) {\n    m.def(\"bayes_smoother\", &bayes_smoother, \"Bayes Smoother\");\n\n    m.def(\"kernel_smoother\", &kernel_smoother, \"Kernel Smoother\");\n\n    m.def(\"bilinear_smoother\", &bilinear_smoother, \"Bilinear Smoother\");\n}\n", "meta": {"hexsha": "a9edd39083268b87ddad2be588083b8b7cec2657", "size": 6490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python/smoothing_utils.cpp", "max_stars_repo_name": "brazil-data-cube/datacube-classification", "max_stars_repo_head_hexsha": "727c045c58c06fd87cb26d408201e34b9e471e9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-20T03:26:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T21:20:27.000Z", "max_issues_repo_path": "src/python/smoothing_utils.cpp", "max_issues_repo_name": "brazil-data-cube/datacube-classification", "max_issues_repo_head_hexsha": "727c045c58c06fd87cb26d408201e34b9e471e9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-04-20T03:14:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-20T03:14:53.000Z", "max_forks_repo_path": "src/python/smoothing_utils.cpp", "max_forks_repo_name": "brazil-data-cube/datacube-classification", "max_forks_repo_head_hexsha": "727c045c58c06fd87cb26d408201e34b9e471e9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6130653266, "max_line_length": 79, "alphanum_fraction": 0.5023112481, "num_tokens": 1767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4337364053895992}}
{"text": "// Method for converting transfer function to system of first order differential equations for evaluation numerically is in Ogata, 4th ed, page 78.\n// Use Mathematica StateSpaceModel instead of Ogata as basis for conversion of TF to State Space.\n\n// Step response achieved by setting u(t) = 1, in derivative term, see MMA State Space model in Plasticity.nb, subsection on Utilities for preparing C++ code.\n\n// Chop p0 in calling routine\n// Bound p1 >= 1e-7 in calling routine\n\n#include <iostream>\n#include <vector>\n#include <cassert>\n#include <string>\n#include <map>\n\n#include <gsl/gsl_poly.h>\n#include <gsl/gsl_complex_math.h>\n#include <gsl/gsl_integration.h>\n#include <gsl/gsl_errno.h>\n#include <gsl/gsl_matrix.h>\n#include <gsl/gsl_odeiv2.h>\n#include <gsl/gsl_spline.h>\n\n#include <boost/math/tools/polynomial.hpp>\n\n#include \"fmt/format.h\"\n#include \"Performance.h\"\n\n// steps for interpolation, 5000 comes very close to Mathematica numerical results, check timing\nconst int steps = 5000;\n\nunsigned debugPerformance = 0;\nvoid debugPerformanceOn(unsigned d) {debugPerformance=d;}\n\ndouble \tMaxRootRealPart(const std::vector<double>& coeff);\ndouble \tH2sq(const std::vector<double>& num, const std::vector<double>& den);\ndouble \tintegrandH2(double w, void *p);\nint \tderiv (double t, const double x[], double f[], void *p);\ndouble \tstepPerformance(const std::vector<double>& num, const std::vector<double>& den, double tmax, signalType s);\ndouble \tintegrandStep(double y, void *p);\n\nstruct my_params {const std::vector<double>& num; const std::vector<double>& den;};\nstruct stepParam {gsl_spline *spline; gsl_interp_accel *acc;};\n\n// Do chopping to set param to zero if close and check bounds before call\n\ndouble performance(const std::vector<double>& num, const std::vector<double>& den,\n\t\t\t\t\tdouble gamma, double tmax, signalType s)\n{\n\tif (MaxRootRealPart(den) > -1e-6) return 1e20;\n\tif (debugPerformance){\n\t\tdouble sf = stepPerformance(num, den, tmax, s);\n\t\tdouble hf = H2sq(num,den);\n\t\tstd::map<signalType,std::string> signal = \n\t\t\t{{signalType::output, \"output\"}, {signalType::controlOpen,\"cntrlO\"}, {signalType::controlClosed,\"cntrlC\"}};\n\t\tstd::cout << fmt::format(\"step = {}, h2 = {} for {}\\n\", sf, hf, signal[s]);\n\t\treturn sf + gamma*hf;\n\t}\n\telse\n\t\treturn stepPerformance(num, den, tmax, s) + gamma*H2sq(num,den);\n}\n\n// coeff of polynomial from low order to high order terms\ndouble MaxRootRealPart(const std::vector<double>& coeff) \n{\n\tauto n = coeff.size();\n\t// std::cout << \"n = \" << n << std::endl;\n    std::vector<double> z(2*(n-1));\n\tgsl_poly_complex_workspace * w\n\t  = gsl_poly_complex_workspace_alloc (n);\n\tif (GSL_SUCCESS != gsl_poly_complex_solve(coeff.data(), n, w, z.data())){\n\t\tgsl_poly_complex_workspace_free (w);\n\t\treturn 1.0;\t\t// positive value is marked as unstable\n\t}\n\tgsl_poly_complex_workspace_free (w);\n\n\tdouble max = -1e20;\n\tfor (unsigned i = 0; i < n-1; i++) {\n\t  // std::cout << fmt::format(\"z{} = {:+.18f} {:+.18f}\\n\", i, z[2*i], z[2*i+1]);\n\t  if (z[2*i] > max) max = z[2*i];\n\t}\n\treturn max;\n}\n\n// In the following, check that integrand gets small at large frequency, required for H2 integral to converge. If not then if order of numerator = order of denominator, then integration will be infinite, because at high frequency, high order terms in numerator and denominator dominate, and so given same order of those terms, the system does not go to zero at high frequency. Correct for this by redefining the num/den transfer function as (num/den - high order num coeff/high order den coeff). This subtraction removes the Dirac delta impulse component of the dynamics, which corresponds in frequency space to a uniform addition to the absolute value of the tf at all frequencies equal to the amount subtracted off. Does not change dynamics, except to remove impulse at time zero acting over infinitesimal duration.\n\n// returns square of H2 value\ndouble H2sq(const std::vector<double>& num, const std::vector<double>& den)\n{\n\tbool sizeFix = false;\n\tboost::math::tools::polynomial<double> poly_newnum;\n\tboost::math::tools::polynomial<double> poly_newden;\n\tif (num.size() == den.size()){\t\t\t// deleting dirac impulse for equal-sized num & den\n\t\tdouble numHiOrder = num.back();\n\t\tdouble denHiOrder = den.back();\n\t\tboost::math::tools::polynomial<double> polyn(num.begin(), num.end());\n\t\tboost::math::tools::polynomial<double> polyd(den.begin(), den.end());\n\t\tpoly_newnum = denHiOrder*polyn - numHiOrder*polyd;\n\t\tpoly_newden = denHiOrder*polyd;\n\t\t// high order term in new numerator should be zero and automatically dropped, reducing size\n\t\tif (poly_newnum.data().size() != polyn.data().size() - 1){\n\t\t\tif (poly_newnum.data().back() < 1e-5)\n\t\t\t\tpoly_newnum.data().pop_back();\n\t\t\telse\n\t\t\t\tassert(poly_newnum.data().size() == polyn.data().size() - 1);\n\t\t}\n\t\tsizeFix = true;\n// \t\tstd::cout << \"Num = \" << polyn << std::endl;\n// \t\tstd::cout << \"Den = \" << polyd << std::endl;\n// \t\tstd::cout << \"NN  = \" << poly_newnum << std::endl;\n// \t\tstd::cout << \"ND  = \" << poly_newden << std::endl;\n\t}\n\t\n\tgsl_function F;\n\tF.function = &integrandH2;\n    // if size fixed above, use newnum and newden\n    const std::vector<double>& n = (sizeFix) ? poly_newnum.data() : num;\n    const std::vector<double>& d = (sizeFix) ? poly_newden.data() : den;\n    my_params params {n, d};\n    F.params = &params;\n\tif (integrandH2(1e10, F.params) > 1e-3) return 1e20; \t// should not happen, because den.size > num.size\n\tdouble result, error;\n\tgsl_integration_workspace *w = gsl_integration_workspace_alloc (1000);\n\t// std::cout << \"h2 int start\" << std::endl;\n\tif (GSL_SUCCESS != gsl_integration_qagi(&F, 0, 1e-7, 1000, w, &result, &error))\n\t\tresult = 1e30;\n\t// std::cout << \"h2 int end\" << std::endl;\n\tgsl_integration_workspace_free(w);\n\treturn result / (2.0*M_PI);\n}\n\ndouble integrandH2(double w, void *p)\n{\n\tgsl_complex s;\n\tmy_params *params = static_cast<my_params *>(p);\n\tconst std::vector<double>& num = params->num;\n\tconst std::vector<double>& den = params->den;\n\tGSL_SET_COMPLEX(&s, 0, w);\n    int numSize = static_cast<int>(num.size());\n    int denSize = static_cast<int>(den.size());\n\treturn gsl_complex_abs2(gsl_complex_div(gsl_poly_complex_eval(num.data(), numSize, s),\n\t\t\t\t\t\t\t\tgsl_poly_complex_eval(den.data(), denSize, s)));\n}\n\n// deriv works for both output signal and control signal, see MMA file\n// Possible speed up by optimizing deriv, see callgrind source code line by line weighting of time cost.\n\nint deriv(double t, const double x[], double f[], void *p)\n{\n\t(void)(t); /* avoid unused parameter warning */\n\tmy_params *params = static_cast<my_params *>(p);\n\tconst std::vector<double>& den = params->den;\n\tauto lastrow = den.size()-2;\n\tf[lastrow] = 0;\n\tfor (unsigned i = 0; i < lastrow; ++i){\n\t\tf[i] = x[i+1];\n\t\tf[lastrow] -= den[i]*x[i];\n\t}\n\tf[lastrow] -= den[lastrow]*x[lastrow];\n\tf[lastrow] /= den.back();\n\t// next line for input, u(t) = 1 for step input\n\tf[lastrow] += 1;\n\treturn GSL_SUCCESS;\n}\n\n// must make different ycoeff for output and control signals\n// for output, same coeff for open and closed loops\n// for control signals, diff coeff for open and closed loops\n// see MMA file\n\ndouble stepPerformance(const std::vector<double>& num, const std::vector<double>& den, double tmax, signalType s)\n{\n\tdouble time[steps+1];\n\tdouble y[steps+1];\n\tmy_params params = {num, den};\n\tauto dim = den.size()-1;\t// dimensions of state space model for dynamics\n\tgsl_odeiv2_system sys = {deriv, NULL, dim, &params};\n    // see GSL docs for alternative algorithms\n\tgsl_odeiv2_driver *d =\n\t\tgsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rkf45, 1e-6, 1e-6, 0.0);\n\tdouble t = 0.0;\n\tdouble denBack = den.back();\n\t\n\t// coefficients to get output, initialize with values for each case, max dim is 4, so use that\n\tdouble ycoeff[4];\n\tunsigned long ydim;\t\t// number of output coefficients to get output y, varies by problem, set explicitly\n\tdouble yinputCoeff = 0;\t// must add yinputCoeff * input to output; input=1 for the step response \n\t\n\tif (s == signalType::output){ // case of output signal, same for open and closed loops\n\t\tydim = 3; \n\t\tycoeff[0] = num[0]/denBack; ycoeff[1] = num[1]/denBack; ycoeff[2] = num[2]/denBack;\n\t}\n\telse {\n\t\t// cases of control signal, # coeff is always dimension of problem, dim\n\t\tydim = dim;\n\t\tdouble numBack = num.back();\n\t\tyinputCoeff = numBack / denBack;\n\t\tif (s == signalType::controlOpen) { // control signal, open loop\n\t\t\tfor (unsigned i = 0; i < ydim; ++i)\n\t\t\t\tycoeff[i] = (num[i] - den[i]*yinputCoeff) / denBack;\n\t\t}\n\t\telse if (s == signalType::controlClosed) { // control signal, closed loop\n\t\t\tfor (unsigned i = 0; i < ydim; ++i){\n\t\t\t\tycoeff[i] = (num[i] - den[i]*yinputCoeff) / denBack;\n\t\t\t\tif (debugPerformance >= 2) std::cout << ycoeff[i] << \" \";\n\t\t\t}\n\t\t\tif (debugPerformance >= 2) std::cout << yinputCoeff << std::endl;\n\t\t\tif (debugPerformance >= 2){\n\t\t\t\tfor (auto& n : den) std::cout << -n/denBack << \" \";\n\t\t\t\tstd::cout << std::endl;\n\t\t\t\tfor (auto& n : num) std::cout << n << \" \";\n\t\t\t\tstd::cout << std::endl;\n\t\t\t\tfor (auto& n : den) std::cout << n << \" \";\n\t\t\t\tstd::cout << std::endl;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tassert(false);\t// should not be here, signal must be one of above types\n\t\t}\n\t}\n\n\ttime[0] = 0.0;\n\t// at time zero with step, dominated by infinite freq, so if order of den > num, then at time zero,\n\t// initial value is zero, if order den=num, then ratio of highest order terms,\n\t// order num>den should not happen\n\ty[0] = (den.size() > num.size()) ? 0.0 : num.back()/den.back(); \n    std::vector<double> x(den.size()-1,0); // 0 at end causes zero initialization\n\tfor (int i = 1; i <= steps; i++){\n\t\t// add one to tmax, so that interpolation extends past boundary for integration\n\t\t// otherwise, can get an error when interpolating close to the upper boundary\n\t  \tdouble ti = i * (tmax+1.0) / static_cast<double>(steps);\n\t  \tint status = gsl_odeiv2_driver_apply(d, &t, ti, x.data());\n\t\tassert(status == GSL_SUCCESS);\n\t\ttime[i] = t;\n\t\ty[i] = 0;\n\t\tfor (unsigned j = 0; j < ydim; ++j)\n\t\t\ty[i] += ycoeff[j] * x[j];\n\t\ty[i] += yinputCoeff;\n\t\t// if (i % 100 == 0) std::cout << fmt::format(\"{:7.3f} {:8.6f}\\n\", time[i], y[i]);\n\t\tif (debugPerformance >= 3 && i % 100 == 0 && s == signalType::controlClosed) \n\t\t\tstd::cout << fmt::format(\"{:7.3f} {:8.6f}\\n\", time[i], y[i]);\n\t}\n\tgsl_odeiv2_driver_free (d);\n\t\n\tgsl_interp_accel *acc = gsl_interp_accel_alloc();\n    gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline, steps);\n    if (GSL_SUCCESS != gsl_spline_init (spline, time, y, steps)){\n    \tgsl_spline_free (spline);\n    \tgsl_interp_accel_free (acc);\n    \treturn 1e20;\n    }\n    \n    // std::cout << gsl_spline_eval(spline, 19.9689, acc) << std::endl;\n    \n\tstepParam integrParam = {spline, acc};\n    gsl_function F;\n\tF.function = &integrandStep;\n\tF.params = &integrParam;\n\tdouble result, error;\n\tgsl_integration_workspace *w = gsl_integration_workspace_alloc (1000);\n\t// std::cout << \"step int start\" << std::endl;\n\t// using 1e-6 for abs and rel error\n\tdouble errtol = 1e-6;\n\tif (GSL_SUCCESS != gsl_integration_qag(&F, 0.0, tmax, errtol, errtol, 1000, 6, w, &result, &error)){\n\t\tgsl_integration_cquad_workspace *ctable = gsl_integration_cquad_workspace_alloc(200);\n\t\tif (GSL_SUCCESS != gsl_integration_cquad(&F, 0, tmax, errtol, errtol, ctable, &result, &error, NULL)){\n     \t\tboost::math::tools::polynomial<double> poly_newnum(num.begin(), num.end());\n\t\t\tboost::math::tools::polynomial<double> poly_newden(den.begin(), den.end());\n\t\t\tif (true){\n\t\t\t\tstd::cout << \"Step integration error, with num = \" << poly_newnum << std::endl;\n\t\t\t\tstd::cout << \"                         and den = \" << poly_newden << std::endl;\n\t\t\t\tstd::cout << \"                      and result = \" << result << std::endl;\n\t\t\t}\n    \t\tresult = 1e20;\n    \t}\n    \tgsl_integration_cquad_workspace_free(ctable);\n\t}\n\t// std::cout << \"step int end\" << std::endl;\n\tgsl_integration_workspace_free(w);\n\n    gsl_spline_free (spline);\n    gsl_interp_accel_free (acc);\n\n\treturn result;\n}\n\ndouble integrandStep(double t, void *p)\n{\n\tstepParam *params = static_cast<stepParam *>(p);\n\tdouble z = 1.0 - gsl_spline_eval(params->spline, t, params->acc);\n\treturn z*z;\n}\n\n", "meta": {"hexsha": "d361c3ba552e96b2ccb8f7f02632ae5b3f306b80", "size": 12072, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Performance.cc", "max_stars_repo_name": "evolbio/design2", "max_stars_repo_head_hexsha": "7f1856e682382e91e56569de2a6d64a61cc424cc", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Performance.cc", "max_issues_repo_name": "evolbio/design2", "max_issues_repo_head_hexsha": "7f1856e682382e91e56569de2a6d64a61cc424cc", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Performance.cc", "max_forks_repo_name": "evolbio/design2", "max_forks_repo_head_hexsha": "7f1856e682382e91e56569de2a6d64a61cc424cc", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2013651877, "max_line_length": 817, "alphanum_fraction": 0.6746189529, "num_tokens": 3544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.43373640538959907}}
{"text": "#pragma once\n#include <type_traits>\n#include <Eigen/Dense>\n#include <fastad_bits/reverse/core/var_view.hpp>\n#include <fastad_bits/reverse/core/eval.hpp>\n#include <autoppl/util/traits/var_traits.hpp>\n#include <autoppl/util/packs/ptr_pack.hpp>\n#include <autoppl/util/logging.hpp>\n#include <autoppl/util/time/stopwatch.hpp>\n#include <autoppl/math/math.hpp>\n#include <autoppl/mcmc/sampler_tools.hpp>\n#include <autoppl/mcmc/result.hpp>\n#include <autoppl/mcmc/base_mcmc.hpp>\n#include <autoppl/mcmc/hmc/nuts/tree_utils.hpp>\n#include <autoppl/mcmc/hmc/leapfrog.hpp>\n#include <autoppl/mcmc/hmc/hamiltonian.hpp>\n#include <autoppl/mcmc/hmc/nuts/configs.hpp>\n\nnamespace ppl {\nnamespace mcmc {\n\n/**\n * Checks if state is entroping based on integrated momentum vector\n * across the path and the scaled momentum at the ends of the path.\n *\n * @param   rho             integrated momentum vector\n * @param   p_beg_scaled    scaled momentum beginning of \n *                          current path (given the direction)\n * @param   p_end_scaled    scaled momentum end of \n *                          current path (given the direction).\n */\ntemplate <class MatType1, class MatType2, class MatType3>\nbool check_entropy(const MatType1& rho, \n                   const MatType2& p_beg_scaled,\n                   const MatType3& p_end_scaled)\n{\n    return rho.dot(p_beg_scaled) > 0 &&\n           rho.dot(p_end_scaled) > 0;\n}\n\n/**\n * Building binary tree for sampling candidates.\n * Helper function to obtain the forward/backward-most position and momentum.\n * Accept/reject policy is based on UniformDistType parameter and GenType\n *\n * Note that the caller, i.e. nuts(), MUST have theta_adj already pre-computed\n * (theta_adj is a member of input and input will be an instance of TreeInput).\n *\n * @param   n_params            number of (continuous) parameters\n * @param   input               TreeInput-like input object\n * @param   depth               current depth of building tree\n * @param   unif_sampler        an object like std::uniform_distribution(0,1)\n *                              used for metropolis acceptance\n * @param   gen                 rng device\n * @param   momentum_handler    MomentumHandler-like object to compute \n *                              kinetic energy and momentum\n * @param   tree_cache          pointer to cache memory that will be used by build_tree.\n *                              The array of doubles must be of size n_params * 7 * max_depth.\n */\ntemplate <class InputType\n        , class UniformDistType\n        , class GenType\n        , class MomentumHandlerType\n    >\nTreeOutput build_tree(size_t n_params, \n                      InputType& input, \n                      uint8_t depth,\n                      UniformDistType& unif_sampler,\n                      GenType& gen,\n                      MomentumHandlerType& momentum_handler,\n                      double* tree_cache)\n{\n    constexpr double delta_max = 1000;  // suggested by Gelman\n\n    // base case\n    if (depth == 0) {\n        double new_potential = leapfrog(input.ad_expr_ref.get(),\n                                        input.theta_ref.get(),\n                                        input.theta_adj_ref.get(),\n                                        input.tp_adj_ref.get(),\n                                        input.p_most_ref.get(),\n                                        momentum_handler,\n                                        input.v * input.epsilon,\n                                        true // always reuse previous adjoint\n                                        );\n        double new_kinetic = momentum_handler.kinetic(input.p_most_ref.get());\n        double new_ham = hamiltonian(new_potential, new_kinetic);\n\n        // update number of leapfrogs\n        ++(input.n_leapfrog_ref.get());\n\n        // update LSE of weights\n        if (std::isnan(new_ham)) { new_ham = math::inf<double>; }\n        input.log_sum_weight_ref.get() = math::lse(\n                input.log_sum_weight_ref.get(), \n                input.ham - new_ham);\n\n        // update sum of probabilities\n        input.sum_metro_prob_ref.get() += (input.ham - new_ham > 0) ? \n                1 : std::exp(input.ham - new_ham);\n\n        // always copy into theta_prime \n        input.theta_prime_ref.get() = input.theta_ref.get();\n\n        // update momenta of beginning of subtree (moving in the direction of input.v)\n        input.p_beg_ref.get() = input.p_most_ref.get();\n        input.p_beg_scaled_ref.get() = \n            momentum_handler.dkinetic_dr(input.p_most_ref.get());\n\n        // update momenta of end of subtree (moving in the direction of input.v)\n        input.p_end_ref.get() = input.p_beg_ref.get();\n        input.p_end_scaled_ref.get() = input.p_beg_scaled_ref.get();\n\n        // update integrated momentum\n        input.rho_ref.get() += input.p_most_ref.get();\n\n        // return validity and new potential \n        return TreeOutput(\n                (new_ham - input.ham <= delta_max),\n                new_potential\n            );\n    }\n\n    // recursion\n    Eigen::Map<Eigen::VectorXd> p_end_inner(tree_cache, n_params);\n    Eigen::Map<Eigen::VectorXd> p_end_scaled_inner(tree_cache + n_params, n_params);\n    Eigen::Map<Eigen::VectorXd> rho_first(tree_cache + 2*n_params, n_params);\n    rho_first.setZero();\n    double log_sum_weight_first = math::neg_inf<double>;\n\n    tree_cache += 3 * n_params; // update position of tree cache\n\n    // create a new input for first recursion\n    // some references have to rebound\n    InputType first_input = input; \n    first_input.p_end_ref = p_end_inner;\n    first_input.p_end_scaled_ref = p_end_scaled_inner;\n    first_input.rho_ref = rho_first;\n    first_input.log_sum_weight_ref = log_sum_weight_first;\n\n    // build first subtree\n    TreeOutput first_output = \n        build_tree(n_params, first_input, depth - 1, \n                   unif_sampler, gen, momentum_handler,\n                   tree_cache);\n\n    // if first subtree is already invalid, early exit\n    // note that caller will break out of doubling process now,\n    // so we do not have to worry about updating the other momentum vectors\n    if (!first_output.valid) { return first_output; }\n\n    // second recursion\n    Eigen::Map<Eigen::VectorXd> theta_double_prime(tree_cache, n_params);\n    Eigen::Map<Eigen::VectorXd> p_beg_inner(tree_cache + n_params, n_params);\n    Eigen::Map<Eigen::VectorXd> p_beg_scaled_inner(tree_cache + 2*n_params, n_params);\n    Eigen::Map<Eigen::VectorXd> rho_second(tree_cache + 3*n_params, n_params);\n    rho_second.setZero();\n    double log_sum_weight_second = math::neg_inf<double>;\n\n    tree_cache += 4 * n_params;\n\n    // create a new input for second recursion\n    InputType second_input = input;\n    second_input.theta_prime_ref = theta_double_prime;\n    second_input.p_beg_ref = p_beg_inner;\n    second_input.p_beg_scaled_ref = p_beg_scaled_inner;\n    second_input.rho_ref = rho_second;\n    second_input.log_sum_weight_ref = log_sum_weight_second;\n\n    // build second subtree\n    TreeOutput second_output = \n        build_tree(n_params, second_input, depth - 1, \n                   unif_sampler, gen, momentum_handler,\n                   tree_cache);\n\n    // if second subtree is invalid, early exit\n    // note that we must return first output since it has the potential\n    // of the first proposal and we ignore the second proposal\n    if (!second_output.valid) { \n        first_output.valid = false;\n        return first_output; \n    }\n\n    // create output to return at the end\n    TreeOutput output;\n\n    // sample proposal and update corresponding potential\n    double log_sum_weight_curr = math::lse(\n            log_sum_weight_first, log_sum_weight_second\n            );\n    input.log_sum_weight_ref.get() = math::lse(\n            input.log_sum_weight_ref.get(), log_sum_weight_curr\n            );\n\n    // note: accept_prob is mathematically guaranteed to be <= 1\n    double accept_prob = std::exp(log_sum_weight_second - log_sum_weight_curr);\n    bool accept = accept_or_reject(accept_prob, unif_sampler, gen);\n    if (accept) { \n        input.theta_prime_ref.get() = \n            second_input.theta_prime_ref.get();\n        output.potential = second_output.potential;\n    } else {\n        output.potential = first_output.potential;\n    }\n\n    // check if current subtree is still valid based\n    // on entropy condition\n    auto rho_curr = rho_first + rho_second;\n    input.rho_ref.get() += rho_curr;\n    output.valid =\n        check_entropy(rho_curr,\n                      input.p_beg_scaled_ref.get(),\n                      input.p_end_scaled_ref.get()) &&\n        check_entropy(rho_first + p_beg_inner, \n                      input.p_beg_scaled_ref.get(), \n                      p_beg_scaled_inner) &&\n        check_entropy(p_end_inner + rho_second, \n                      p_end_scaled_inner, \n                      input.p_end_scaled_ref.get());\n\n    return output;\n}\n\n/**\n * Finds a reasonable epsilon for NUTS algorithm.\n *\n * @param   eps                 initial epsilon (see Gelman's paper)\n * @param   ad_expr             AD expression bound to theta and theta_adj\n * @param   theta               vector of theta values\n * @param   theta_adj           vector of theta adjoints\n * @param   gen                 rng device\n * @param   momentum_handler    MomentumHandler-like object \n */\ntemplate <class ADExprType\n        , class MatType\n        , class GenType\n        , class MomentumHandlerType>\ndouble find_reasonable_epsilon(double eps,\n                               ADExprType& ad_expr,\n                               MatType& theta,\n                               MatType& theta_adj,\n                               MatType& tp_adj,\n                               GenType& gen,\n                               MomentumHandlerType& momentum_handler)\n{\n    // See (STAN) for reference: if epsilon is way out of bounds, just return eps\n    if (eps <= 0 || eps > 1e7) return eps;\n\n    const double diff_bound = std::log(0.8);\n\n    size_t n_params = theta.rows(); // theta is expected to be vector-like\n\n    Eigen::MatrixXd mat(n_params, 3);\n    Eigen::Map<Eigen::VectorXd> r(mat.col(0).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> theta_orig(mat.col(1).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> theta_adj_orig(mat.col(2).data(), n_params);\n\n    // sample momentum vector based on handler\n    momentum_handler.sample(r, gen);\n\n    // differentiate first to get adjoints and hamiltonian\n    const double potential_orig = -ad::autodiff(ad_expr); \n    double kinetic_orig = momentum_handler.kinetic(r);\n    double ham_orig = hamiltonian(potential_orig, kinetic_orig);\n\n    // save original value and adjoint\n    theta_orig = theta;\n    theta_adj_orig = theta_adj;\n    \n    // get current hamiltonian after leapfrog\n    double potential_curr = leapfrog(\n            ad_expr, theta, theta_adj, tp_adj,\n            r, momentum_handler, eps, true);\n    double kinetic_curr = momentum_handler.kinetic(r);\n    double ham_curr = hamiltonian(potential_curr, kinetic_curr);\n\n    int a = (ham_orig - ham_curr > diff_bound) ? 1 : -1;\n\n    while (1) {\n\n        // check if break condition holds\n        if ( ((a == 1) && !(ham_orig - ham_curr > diff_bound)) || \n             ((a == -1) && !(ham_orig - ham_curr < diff_bound)) ) {\n            break;\n        }\n\n        // update epsilon\n        eps *= (a == -1) ? 0.5 : 2;\n\n        // copy back original value and adjoint\n        theta = theta_orig;\n        theta_adj = theta_adj_orig;\n\n        // recompute original hamiltonian with new momentum\n        momentum_handler.sample(r, gen);\n        kinetic_orig = momentum_handler.kinetic(r);\n        ham_orig = hamiltonian(potential_orig, kinetic_orig);\n\n        // leapfrog and compute current hamiltonian\n        potential_curr = leapfrog(\n                ad_expr, theta, theta_adj, tp_adj,\n                r, momentum_handler, eps, true);\n        kinetic_curr = momentum_handler.kinetic(r);\n        ham_curr = hamiltonian(potential_curr, kinetic_curr);\n\n    }\n\n    // copy back original value and adjoint\n    theta = theta_orig;\n    theta_adj = theta_adj_orig;\n\n    return eps;\n}\n\n/**\n * No-U-Turn Sampler (NUTS)\n *\n * User must ensure that the program does not have any discrete parameters.\n * Discrete data is allowed.\n *\n * @param   program     program expression used to determine log-pdf\n * @param   config      NUTS configuration object\n * @param   pack        offset pack result of activating program.\n *                      It will likely be util::OffsetPack where each offset\n *                      value is equivalent to the total number of values needed,\n *                      i.e. if pack.uc_offset is 10, there is exactly 10 unconstrained values\n *                      for the program.\n * @param   res         result object of calling NUTS that will be populated with samples and other information.\n */\n\ntemplate <class ProgramType\n        , class OffsetPackType\n        , class MCMCResultType\n        , class NUTSConfigType = NUTSConfig<>>\nvoid nuts_(ProgramType& program, \n           const NUTSConfigType& config,\n           const OffsetPackType& pack,\n           MCMCResultType& res)\n{\n    assert(std::get<1>(pack).uc_offset == 0);\n    assert(std::get<1>(pack).tp_offset == 0);\n    assert(std::get<1>(pack).c_offset == 0);\n    assert(std::get<1>(pack).v_offset == 0);\n\n    auto& offset_pack = std::get<0>(pack);\n    size_t n_params = offset_pack.uc_offset;\n\n    // initialization of meta-variables\n    std::mt19937 gen(config.seed);\n    std::uniform_int_distribution direction_sampler(0, 1);\n    std::uniform_real_distribution unif_sampler(0., 1.);\n\n    // Transformed parameters, constrained parameter, visit count cache\n    // This can be shared across all AD expressions since only one expression\n    // will be evaluated at a time.\n    Eigen::MatrixXd tp_mat(offset_pack.tp_offset, 2);\n    Eigen::Map<Eigen::VectorXd> tp_val(tp_mat.col(0).data(), offset_pack.tp_offset);\n    Eigen::Map<Eigen::VectorXd> tp_adj(tp_mat.col(1).data(), offset_pack.tp_offset);\n    Eigen::VectorXd constrained(offset_pack.c_offset);\n    Eigen::Matrix<size_t, Eigen::Dynamic, 1> visit(offset_pack.v_offset);\n    tp_mat.setZero();\n    constrained.setZero();\n    visit.setZero();\n\n    // momentum matrix (for stability reasons we require knowing 4 momentum)\n    // left-subtree backwardmost momentum => bb\n    // left-subtree forwardmost momentum => bf\n    // right-subtree backwardmost momentum => fb\n    // right-subtree forwardmost momentum => ff\n    // scaled versions are based on hamiltonian adjusted covariance matrix\n    Eigen::MatrixXd cache_mat(n_params, 18);\n    cache_mat.setZero();\n    Eigen::Map<Eigen::VectorXd> p_bb(cache_mat.col(0).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> p_bb_scaled(cache_mat.col(1).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> p_bf(cache_mat.col(2).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> p_bf_scaled(cache_mat.col(3).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> p_fb(cache_mat.col(4).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> p_fb_scaled(cache_mat.col(5).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> p_ff(cache_mat.col(6).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> p_ff_scaled(cache_mat.col(7).data(), n_params);\n\n    // position matrix for thetas and adjoints\n    Eigen::Map<Eigen::VectorXd> theta_bb(cache_mat.col(8).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> theta_bb_adj(cache_mat.col(9).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> theta_ff(cache_mat.col(10).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> theta_ff_adj(cache_mat.col(11).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> theta_curr(cache_mat.col(12).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> theta_curr_adj(cache_mat.col(13).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> theta_prime(cache_mat.col(14).data(), n_params);\n\n    // integrated momentum vectors (more stable than checking entropy with theta_ff - theta_bb)\n    // forward-subtree => rho_f\n    // backward-subtree => rho_b\n    // combined subtrees => rho\n    Eigen::Map<Eigen::VectorXd> rho_f(cache_mat.col(15).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> rho_b(cache_mat.col(16).data(), n_params);\n    Eigen::Map<Eigen::VectorXd> rho(cache_mat.col(17).data(), n_params);\n\n    // build-tree helper function cache line\n    Eigen::VectorXd tree_cache(n_params * 7 * config.max_depth);\n    tree_cache.setZero();\n\n    // AD Expressions for L(theta) (log-pdf up to constant at theta)\n    // Note that these expressions are the only ones used ever.\n    auto theta_bb_ad_expr = program.ad_log_pdf(util::make_ptr_pack(\n            theta_bb.data(), theta_bb_adj.data(), \n            tp_val.data(), tp_adj.data(),\n            constrained.data(), visit.data() ));\n    auto theta_ff_ad_expr = program.ad_log_pdf(util::make_ptr_pack(\n            theta_ff.data(), theta_ff_adj.data(),\n            tp_val.data(), tp_adj.data(),\n            constrained.data(), visit.data() ));\n    auto theta_curr_ad_expr = program.ad_log_pdf(util::make_ptr_pack(\n            theta_curr.data(), theta_curr_adj.data(),\n            tp_val.data(), tp_adj.data(),\n            constrained.data(), visit.data() ));\n\n    // bind every AD expression to the same cache line\n    auto size_pack = theta_bb_ad_expr.bind_cache_size();\n    Eigen::VectorXd ad_val_buf(size_pack(0));\n    Eigen::VectorXd ad_adj_buf(size_pack(1));\n    theta_bb_ad_expr.bind_cache({ad_val_buf.data(), ad_adj_buf.data()});\n    theta_ff_ad_expr.bind_cache({ad_val_buf.data(), ad_adj_buf.data()});\n    theta_curr_ad_expr.bind_cache({ad_val_buf.data(), ad_adj_buf.data()});\n    \n    // initializes first sample into theta_curr\n    // TODO: allow users to choose how to initialize first point?\n    program.bind(util::make_ptr_pack(\n                theta_curr.data(), nullptr,\n                tp_val.data(), nullptr,\n                constrained.data(), visit.data()));\n    program.init_params(gen, config.prune);\n\n    // initialize current potential (will be \"previous\" starting in for-loop)\n    double potential_prev = -ad::evaluate(theta_curr_ad_expr);\n\n    // initialize momentum handler\n    using var_adapter_policy_t = typename \n        nuts_config_traits<NUTSConfigType>::var_adapter_policy_t;\n    mcmc::MomentumHandler<var_adapter_policy_t> momentum_handler(n_params);\n\n    // initialize step adapter\n    const double log_eps = std::log(\n        mcmc::find_reasonable_epsilon(\n            1., // initial epsilon\n            theta_curr_ad_expr, theta_curr, \n            theta_curr_adj, tp_adj,\n            gen, momentum_handler)); \n    mcmc::StepAdapter step_adapter(log_eps);        // initialize step adapter with initial log-epsilon\n    step_adapter.step_config = config.step_config;  // copy step configs from user\n\n    // initialize variance adapter\n    mcmc::VarAdapter<var_adapter_policy_t> var_adapter(\n            n_params, config.warmup, config.var_config.init_buffer,\n            config.var_config.term_buffer, config.var_config.window_base\n            );\n\n    // construct miscellaneous objects \n    auto logger = util::ProgressLogger(config.samples + config.warmup, \"NUTS\");\n    util::StopWatch<> stopwatch_warmup;\n    util::StopWatch<> stopwatch_sampling;\n\n    // start timing warmup\n    stopwatch_warmup.start();\n\n    for (size_t i = 0; i < config.samples + config.warmup; ++i) {\n\n        // if warmup is finished, stop timing warmup and start timing sampling\n        if (i == config.warmup) {\n            stopwatch_warmup.stop();\n            stopwatch_sampling.start();\n        }\n\n        logger.printProgress(i);\n\n        // re-initialize vectors to current theta as the \"root\" of tree\n        theta_bb = theta_curr;\n        theta_ff = theta_bb;\n        mcmc::reset_autodiff(theta_bb_ad_expr, theta_bb_adj, tp_adj); \n        theta_ff_adj = theta_bb_adj;   // no need to differentiate again\n\n        // initialize values for multinomial sampling\n        // this is the total log sum weight over full tree\n        double log_sum_weight = 0.;\n\n        // initialize values used to adapt stepsize\n        size_t n_leapfrog = 0;\n        double sum_metro_prob = 0.;\n\n        // p ~ N(0, M) (depending on momentum handler)\n        momentum_handler.sample(p_bb, gen); \n        p_bf = p_bb;\n        p_fb = p_bb;\n        p_ff = p_bb;\n\n        // scaled p by hamiltonian dkinetic_dr\n        p_bb_scaled = momentum_handler.dkinetic_dr(p_bb);\n        p_bf_scaled = p_bb_scaled;\n        p_fb_scaled = p_bb_scaled;\n        p_ff_scaled = p_bb_scaled;\n\n        // re-initialize integrated momentum vectors\n        rho = p_bb;\n\n        const double kinetic = momentum_handler.kinetic(p_bb);\n        const double ham_prev = mcmc::hamiltonian(potential_prev, kinetic);\n\n        // Note that this object can be reused since all members\n        // are guaranteed to overwritten by build_tree.\n        mcmc::TreeOutput output;\n\n        for (size_t depth = 0; depth < config.max_depth; ++depth) {\n\n            // zero-out subtree integrated momentum vectors\n            rho_b.setZero();\n            rho_f.setZero();\n\n            double log_sum_weight_subtree = math::neg_inf<double>;\n            \n            int8_t v = 2 * direction_sampler(gen) - 1; // -1 or 1\n            if (v == -1) {\n                auto input = mcmc::TreeInput(\n                    // position information to update\n                    theta_bb_ad_expr, theta_bb, theta_bb_adj, tp_adj,\n                    theta_prime, p_bb,\n                    // momentum vectors to update\n                    p_bf, p_bb, p_bf_scaled, p_bb_scaled, rho_b,\n                    // stats to update to adapt step size at the end\n                    n_leapfrog, log_sum_weight_subtree, sum_metro_prob, \n                    // other miscellaneous variables\n                    v, std::exp(step_adapter.log_eps), ham_prev\n                );\n                rho_f = rho;\n                p_fb = p_bb;\n                p_fb_scaled = p_bb_scaled;\n\n                output = mcmc::build_tree(n_params, input, depth, \n                                          unif_sampler, gen, momentum_handler,\n                                          tree_cache.data());\n            } else {\n                auto input = mcmc::TreeInput(\n                    // correct position information to update\n                    theta_ff_ad_expr, theta_ff, theta_ff_adj, tp_adj,\n                    theta_prime, p_ff,\n                    // correct momentum vectors to update\n                    p_fb, p_ff, p_fb_scaled, p_ff_scaled, rho_f,\n                    // stats to update to adapt step size at the end\n                    n_leapfrog, log_sum_weight_subtree, sum_metro_prob, \n                    // other miscellaneous variables\n                    v, std::exp(step_adapter.log_eps), ham_prev\n                );\n                rho_b = rho;\n                p_bf = p_ff;\n                p_bf_scaled = p_ff_scaled;\n\n                output = mcmc::build_tree(n_params, input, depth, \n                                          unif_sampler, gen, momentum_handler,\n                                          tree_cache.data());\n            }\n\n            // early break if starting to U-Turn\n            if (!output.valid) break;\n            \n            // if new subtree's weight is greater than previous subtree's weight\n            // always accept!\n            if (log_sum_weight_subtree > log_sum_weight) {\n                theta_curr = theta_prime;\n                potential_prev = output.potential;\n            } else {\n                double p = std::exp(log_sum_weight_subtree - log_sum_weight);\n                if (mcmc::accept_or_reject(p, unif_sampler, gen)) {\n                    theta_curr = theta_prime;\n                    potential_prev = output.potential;\n                }\n            }\n\n            // update total log_sum_weight\n            log_sum_weight = math::lse(log_sum_weight, log_sum_weight_subtree);\n\n            // check if proposals are still \n            // - entroping in the full tree\n            // - entroping from backwards-subtree to forwards-subtree\n            // - entroping from forwards-subtree to backwards-subtree\n            // This is a much stronger than the original paper's entropy condition.\n            // This most likely reduces the depth to avoid unnecessary computation.\n            \n            rho = rho_b + rho_f;\n\n            bool valid = \n                mcmc::check_entropy(rho, p_bb_scaled, p_ff_scaled) &&\n                mcmc::check_entropy(rho_b + p_fb, p_bb_scaled, p_fb_scaled) &&\n                mcmc::check_entropy(p_bf + rho_f, p_bf_scaled, p_ff_scaled)\n                ;\n\n            if (!valid) break;\n\n        } // end tree doubling for-loop\n        \n        // Warmup Adapt!\n        if (i < config.warmup) {\n\n            // epsilon dual averaging\n            step_adapter.adapt(sum_metro_prob / static_cast<double>(n_leapfrog));\n\n            // adapt variance only if adapting policy is diag_var or dense_var \n            if constexpr (std::is_same_v<var_adapter_policy_t, diag_var> ||\n                          std::is_same_v<var_adapter_policy_t, dense_var>) {\n                const bool update = var_adapter.adapt(theta_curr, momentum_handler.get_m_inverse());\n                if (update) {\n                    double log_eps = std::log( mcmc::find_reasonable_epsilon(\n                                        std::exp(step_adapter.log_eps),\n                                        theta_curr_ad_expr, theta_curr, \n                                        theta_curr_adj, tp_adj,\n                                        gen, momentum_handler) ); \n                    step_adapter.reset();\n                    step_adapter.init(log_eps);\n                }\n            }\n\n            // if last warmup iteration\n            if (i == config.warmup - 1) {\n                step_adapter.log_eps = step_adapter.log_eps_bar;\n            }\n        }\n\n        // store sample theta_curr only after burning\n        if (i >= config.warmup) {\n            res.cont_samples.row(i-config.warmup) = theta_curr;\n        }\n\n    } // end for-loop to sample 1 point\n\n    // stop timing sampling\n    stopwatch_sampling.stop();\n\n    // save output results\n    res.warmup_time = stopwatch_warmup.elapsed();\n    res.sampling_time = stopwatch_sampling.elapsed();\n}\n\n} // namespace mcmc\n\ntemplate <class ExprType\n        , class NUTSConfigType = NUTSConfig<>>\ninline auto nuts(const ExprType& expr, \n                 const NUTSConfigType& config = NUTSConfigType())\n{\n    return mcmc::base_mcmc(expr, config, \n            [](auto& program, const auto& config,\n               const auto& pack, auto& res) {\n                res.name = \"nuts\";\n                mcmc::nuts_(program, config, pack, res);\n            });\n}\n\n} // namespace ppl\n", "meta": {"hexsha": "ed728c06af2d31e52f4391733775f67cc205cf90", "size": 26753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/autoppl/mcmc/hmc/nuts/nuts.hpp", "max_stars_repo_name": "JamesYang007/autoppl", "max_stars_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-04-12T19:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T19:05:38.000Z", "max_issues_repo_path": "include/autoppl/mcmc/hmc/nuts/nuts.hpp", "max_issues_repo_name": "JamesYang007/autoppl", "max_issues_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-04-26T14:55:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T19:21:50.000Z", "max_forks_repo_path": "include/autoppl/mcmc/hmc/nuts/nuts.hpp", "max_forks_repo_name": "JamesYang007/autoppl", "max_forks_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T04:45:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:28:42.000Z", "avg_line_length": 40.7199391172, "max_line_length": 112, "alphanum_fraction": 0.6141367323, "num_tokens": 5999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4337329026990114}}
{"text": "#ifndef WITHIN_BIGGLES_KALMAN_FILTER_HPP__\n#error \"This file should only be included by kalman_filter.hpp\"\n#endif // WITHIN_BIGGLES_KALMAN_FILTER_HPP__\n\n#include <boost/assert.hpp>\n#include <boost/foreach.hpp>\n#include <cmath>\n#include <deque>\n#include <Eigen/Dense>\n\n#include \"detail/physics.hpp\"\n#include \"tools/debug.hpp\"\n\nnamespace biggles\n{\n\ntemplate<typename OutputIterator>\nvoid rts_smooth(const kalman_filter& filter,\n                OutputIterator output_reversed_states_and_covariances)\n{\n    // Rauch-Tung-Striebel smoother:\n    //\n    // L_t = Sigma_{t|t} A^T P_{t+1|t}^{-1}\n    //\n    // mu_{t|T} = mu_{t|t} + L_t(mu_{t+1|T} - mu_{t+1|t})\n    //\n    // P_{t|T} = P_{t|t} + L_t(P_{t+1|T} - P_{t+1|t})L^T_t\n\n    // the state evolution matrix: X_{k+1} = A X_k + <noise>\n    Eigen::Matrix4f A(Eigen::Matrix4f::Identity());\n    BOOST_ASSERT(filter.dynamic_drag() == 1);\n    A(0,1) = A(2,3) = filter.dynamic_drag(); // <- off-diagonal velocity integration\n\n    const kalman_filter::states_and_cov_deque& correction_states_and_covs(filter.corrections());\n    const kalman_filter::states_and_cov_deque& prediction_states_and_covs(filter.predictions());\n\n    // final interpolated state is output of forward filter, this is mu_{T|T} and Sigma_{T|T}\n    if (not is_symmetric(correction_states_and_covs.back().second) and\n            measure_asymmetry(correction_states_and_covs.back().second) > 0.f) {\n        OK(\"foo\");\n        OK1(correction_states_and_covs.back().second);\n        OK1(correction_states_and_covs.back().first);\n        BOOST_ASSERT(measure_asymmetry(correction_states_and_covs.back().second)==0.f);\n    }\n    *output_reversed_states_and_covariances = correction_states_and_covs.back();\n    ++output_reversed_states_and_covariances;\n\n    // iterator pointing to mu_{t+1|t}, starting at t = T-1\n    kalman_filter::states_and_cov_deque::const_reverse_iterator pred_it(prediction_states_and_covs.rbegin());\n\n    // iterator pointing to mu_{t|t}, starting at t = T-1\n    kalman_filter::states_and_cov_deque::const_reverse_iterator corr_it(++correction_states_and_covs.rbegin());\n\n    for(kalman_filter::state_covariance_pair prior_pair(correction_states_and_covs.back());\n        corr_it != correction_states_and_covs.rend();\n        ++pred_it, ++corr_it, ++output_reversed_states_and_covariances)\n    {\n        // mu_{t+1|t} and Sigma_{t+1|t}\n        const Eigen::Vector4f& pred_state(pred_it->first);\n        const Eigen::Matrix4f& pred_cov(pred_it->second);\n\n        // mu_{t|t} and Sigma_{t|t}\n        const Eigen::Vector4f& corr_state(corr_it->first);\n        const Eigen::Matrix4f& corr_cov(corr_it->second);\n\n        // mu_{t+1|T} and Sigma_{t+1|T}\n        const Eigen::Vector4f& last_smoothed_state(prior_pair.first);\n        const Eigen::Matrix4f& last_smoothed_cov(prior_pair.second);\n\n        // calculate the RTS smoothed values\n        Eigen::Matrix4f L = corr_cov * A.transpose() * pred_cov.inverse();\n        Eigen::Vector4f smoothed_state = corr_state + L * (last_smoothed_state - pred_state);\n        Eigen::Matrix4f smoothed_cov = corr_cov + L * (last_smoothed_cov - pred_cov) * L.transpose();\n        smoothed_cov = enforce_symmetry(smoothed_cov);\n\n        if (not is_symmetric(corr_cov) and measure_asymmetry(corr_cov) > 0.f) {\n            OK(\"rts_smooth\");\n            OK1(corr_cov);\n            OK(measure_asymmetry(corr_cov));\n            BOOST_ASSERT(measure_asymmetry(corr_cov)==0.f);\n        }\n\n        if (not is_symmetric(smoothed_cov) and measure_asymmetry(smoothed_cov) > 0.f) {\n            OK(\"rts_smooth\");\n            OK1(smoothed_cov);\n            OK(measure_asymmetry(corr_cov));\n            OK(measure_asymmetry(smoothed_cov));\n            BOOST_ASSERT(measure_asymmetry(smoothed_cov)==0.f);\n        }\n\n        // record smoothed state and covariance\n        prior_pair = kalman_filter::state_covariance_pair(smoothed_state, smoothed_cov);\n        *output_reversed_states_and_covariances = prior_pair;\n    }\n}\n\n}\n", "meta": {"hexsha": "4442cc34e3c8645293517cb60e790f66b271d1bd", "size": 3966, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "include/biggles/kalman_filter.tcc", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "include/biggles/kalman_filter.tcc", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/biggles/kalman_filter.tcc", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4693877551, "max_line_length": 111, "alphanum_fraction": 0.6845688351, "num_tokens": 1075, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4337329026990114}}
{"text": "/******************************************************************************\n\n  This source file is part of the Avogadro project.\n\n  Copyright 2008-2009 Marcus D. Hanwell\n  Copyright 2010-2013 Kitware, Inc.\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************/\n\n#include \"slaterset.h\"\n\n#include <cmath>\n#include <iostream>\n\n#include <Eigen/LU>\n\nusing std::vector;\nusing std::cout;\nusing std::endl;\nusing Eigen::SelfAdjointEigenSolver;\n\nnamespace Avogadro {\nnamespace Core {\n\nSlaterSet::SlaterSet() : m_initialized(false)\n{\n}\n\nSlaterSet::~SlaterSet()\n{\n}\n\nbool SlaterSet::addSlaterIndices(const std::vector<int>& i)\n{\n  m_slaterIndices = i;\n  return true;\n}\n\nbool SlaterSet::addSlaterTypes(const std::vector<int>& t)\n{\n  m_initialized = false;\n  m_slaterTypes = t;\n  return true;\n}\n\nbool SlaterSet::addZetas(const std::vector<double>& z)\n{\n  m_initialized = false;\n  m_zetas = z;\n  return true;\n}\n\nbool SlaterSet::addPQNs(const std::vector<int>& pqns)\n{\n  m_initialized = false;\n  m_pqns = pqns;\n  return true;\n}\n\nbool SlaterSet::addOverlapMatrix(const Eigen::MatrixXd& m)\n{\n  m_initialized = false;\n  m_overlap.resize(m.rows(), m.cols());\n  m_overlap = m;\n  return true;\n}\n\nbool SlaterSet::addEigenVectors(const Eigen::MatrixXd& e)\n{\n  m_eigenVectors.resize(e.rows(), e.cols());\n  m_eigenVectors = e;\n  return true;\n}\n\nbool SlaterSet::addDensityMatrix(const Eigen::MatrixXd& d)\n{\n  m_density.resize(d.rows(), d.cols());\n  m_density = d;\n  return true;\n}\n\nunsigned int SlaterSet::molecularOrbitalCount(ElectronType)\n{\n  return static_cast<unsigned int>(m_overlap.cols());\n}\n\nvoid SlaterSet::outputAll()\n{\n}\n\nvoid SlaterSet::initCalculation()\n{\n  if (m_initialized)\n    return;\n\n  m_normalized.resize(m_overlap.cols(), m_overlap.rows());\n\n  SelfAdjointEigenSolver<MatrixX> s(m_overlap);\n  MatrixX p = s.eigenvectors();\n  MatrixX m =\n    p * s.eigenvalues().array().inverse().array().sqrt().matrix().asDiagonal() *\n    p.inverse();\n  m_normalized = m * m_eigenVectors;\n\n  if (!(m_overlap * m * m).eval().isIdentity())\n    cout << \"Identity test FAILED - do you need a newer version of Eigen?\\n\";\n\n  m_factors.resize(m_zetas.size());\n  m_PQNs = m_pqns;\n  // Calculate the normalizations of the orbitals.\n  for (size_t i = 0; i < m_zetas.size(); ++i) {\n    switch (m_slaterTypes[i]) {\n      case S:\n        m_factors[i] = pow(2.0 * m_zetas[i], m_pqns[i] + 0.5) *\n                       sqrt(1.0 / (4.0 * M_PI) / factorial(2 * m_pqns[i]));\n        m_PQNs[i] -= 1;\n        break;\n      case PX:\n      case PY:\n      case PZ:\n        m_factors[i] = pow(2.0 * m_zetas[i], m_pqns[i] + 0.5) *\n                       sqrt(3.0 / (4.0 * M_PI) / factorial(2 * m_pqns[i]));\n        m_PQNs[i] -= 2;\n        break;\n      case X2:\n        m_factors[i] = 0.5 * pow(2.0 * m_zetas[i], m_pqns[i] + 0.5) *\n                       sqrt(15.0 / (4.0 * M_PI) / factorial(2 * m_pqns[i]));\n        m_PQNs[i] -= 3;\n        break;\n      case XZ:\n        m_factors[i] = pow(2.0 * m_zetas[i], m_pqns[i] + 0.5) *\n                       sqrt(15.0 / (4.0 * M_PI) / factorial(2 * m_pqns[i]));\n        m_PQNs[i] -= 3;\n        break;\n      case Z2:\n        m_factors[i] = (0.5 / sqrt(3.0)) *\n                       pow(2.0 * m_zetas[i], m_pqns[i] + 0.5) *\n                       sqrt(15.0 / (4.0 * M_PI) / factorial(2 * m_pqns[i]));\n        m_PQNs[i] -= 3;\n        break;\n      case YZ:\n      case XY:\n        m_factors[i] = pow(2.0 * m_zetas[i], m_pqns[i] + 0.5) *\n                       sqrt(15.0 / (4.0 * M_PI) / factorial(2 * m_pqns[i]));\n        m_PQNs[i] -= 3;\n        break;\n      default:\n        cout << \"Orbital \" << i << \" not handled, type \" << m_slaterTypes[i]\n             << endl;\n    }\n  }\n  // Convert the exponents into Angstroms\n  for (size_t i = 0; i < m_zetas.size(); ++i)\n    m_zetas[i] = m_zetas[i] / BOHR_TO_ANGSTROM_D;\n\n  m_initialized = true;\n}\n\ninline unsigned int SlaterSet::factorial(unsigned int n)\n{\n  if (n <= 1)\n    return n;\n  return (n * factorial(n - 1));\n}\n\n} // End namespace Core\n} // End namespace Avogadro\n", "meta": {"hexsha": "a715177dda4c08b20669485fc666a1a686378e7f", "size": 4429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "avogadro/core/slaterset.cpp", "max_stars_repo_name": "berquist/avogadrolibs", "max_stars_repo_head_hexsha": "e169315d8f9527d6b8bee1b7426eabb8a188073b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 244.0, "max_stars_repo_stars_event_min_datetime": "2015-09-09T15:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:44:21.000Z", "max_issues_repo_path": "avogadro/core/slaterset.cpp", "max_issues_repo_name": "berquist/avogadrolibs", "max_issues_repo_head_hexsha": "e169315d8f9527d6b8bee1b7426eabb8a188073b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 670.0, "max_issues_repo_issues_event_min_datetime": "2015-05-08T18:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T19:47:08.000Z", "max_forks_repo_path": "avogadro/core/slaterset.cpp", "max_forks_repo_name": "berquist/avogadrolibs", "max_forks_repo_head_hexsha": "e169315d8f9527d6b8bee1b7426eabb8a188073b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 129.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T01:18:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T08:50:25.000Z", "avg_line_length": 25.1647727273, "max_line_length": 80, "alphanum_fraction": 0.5832016256, "num_tokens": 1312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.43368599536356367}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// TensionFieldTheory.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//  Implements a field theory relaxed energy density for a fully generic,\n//  potentially anisotropic, 2D \"C-based\" energy density. Here \"C-based\" means\n//  the energy density is expressed in terms of the Cauchy-Green deformation\n//  tensor.\n//  Our implementation is based on the applied math paper\n//  [Pipkin1994:\"Relaxed energy densities for large deformations of membranes\"]\n//  whose optimality criterion for the wrinkling strain we use to obtain a\n//  slightly less expensive optimization formulation.\n//\n//  We implement the second derivatives needed for a Newton-based equilibrium\n//  solver; these are nontrivial since they must account for the dependence of\n//  the wrinkling strain on C.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Created:  06/28/2020 19:01:21\n////////////////////////////////////////////////////////////////////////////////\n#ifndef TENSIONFIELDTHEORY_HH\n#define TENSIONFIELDTHEORY_HH\n#include <Eigen/Dense>\n#include <MeshFEM/Types.hh>\n#include <stdexcept>\n#include <iostream>\n#include <MeshFEM/newton_optimizer/dense_newton.hh>\n\ntemplate<class _Psi>\nstruct IsotropicWrinkleStrainProblem {\n    using Psi      = _Psi;\n    using Real     = typename Psi::Real;\n    using VarType  = Eigen::Matrix<Real, 1, 1>;\n    using HessType = Eigen::Matrix<Real, 1, 1>;\n    using M2d      = Mat2_T<Real>;\n\n    IsotropicWrinkleStrainProblem(Psi &psi, const M2d &C, const Vec2_T<Real> &n)\n        : m_psi(psi), m_C(C), m_nn(n * n.transpose()) { }\n\n    void setC(const M2d &C) { m_C = C; }\n    const M2d &getC() const { return m_C; }\n\n    size_t numVars() const { return 1; }\n    void setVars(const VarType &vars) {\n        m_a = vars;\n        m_psi.setC(m_C + m_a[0] * m_nn);\n    }\n    const VarType &getVars() const { return m_a; }\n\n    Real energy()      const { return m_psi.energy(); }\n    VarType gradient() const { return  VarType(0.5 * doubleContract(m_nn, m_psi.PK2Stress())          ); }\n    HessType hessian() const { return HessType(0.5 * doubleContract(m_psi.delta_PK2Stress(m_nn), m_nn)); }\n\n    void solve() { dense_newton(*this, /* maxIter = */ 100, /*gradTol = */1e-14, /* verbose = */ false); }\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    VarType m_a = VarType::Zero();\n    Psi &m_psi;\n    M2d m_C, m_nn;\n};\n\ntemplate<class _Psi>\nstruct AnisotropicWrinkleStrainProblem {\n    using Psi      = _Psi;\n    using Real     = typename Psi::Real;\n    using VarType  = Vec2_T<Real>;\n    using HessType = Mat2_T<Real>;\n    using M2d      = Mat2_T<Real>;\n\n    AnisotropicWrinkleStrainProblem(Psi &psi, const M2d &C, const VarType &n)\n        : m_psi(psi), m_C(C), m_ntilde(n) { }\n\n    void setC(const M2d &C) { m_C = C; }\n    const M2d &getC() const { return m_C; }\n\n    size_t numVars() const { return 2; }\n    void setVars(const VarType &vars) {\n        m_ntilde = vars;\n        m_psi.setC(m_C + m_ntilde * m_ntilde.transpose());\n    }\n    const VarType &getVars() const { return m_ntilde; }\n    Real energy() const { return m_psi.energy(); }\n\n    // S : (0.5 * (n delta_n^T + delta_n n^T))\n    //  = S : n delta_n^T = (S n) . delta_n\n    VarType gradient() const { return m_psi.PK2Stress() * m_ntilde; }\n\n    //   psi(n * n^T)\n    //  dpsi = n^T psi'(n * n^T) . dn\n    // d2psi = dn_a^T psi'(n * n^T) . dn_b + n^T (psi'' : (n * dn_a^T)) . dn_b\n    //       = psi' : (dn_a dn_b^T) + ...\n    HessType hessian() const {\n        HessType h = m_psi.PK2Stress(); // psi' : (dn_a dn_b^T)\n        M2d dnn(M2d::Zero());\n        dnn.col(0) = m_ntilde;\n        h.row(0) += m_ntilde.transpose() * m_psi.delta_PK2Stress(symmetrized_x2(dnn));\n        dnn.col(0).setZero();\n        dnn.col(1) = m_ntilde;\n        h.row(1) += m_ntilde.transpose() * m_psi.delta_PK2Stress(symmetrized_x2(dnn));\n        if (h.array().isNaN().any()) throw std::runtime_error(\"NaN Hessian\");\n        if (std::abs(h(0, 1) - h(1, 0)) > 1e-10 * std::abs(h(1, 0)) + 1e-10)\n            throw std::runtime_error(\"Asymmetric Hessian\");\n        return h;\n    }\n\n    void solve() { dense_newton(*this, /* maxIter = */ 100, /*gradTol = */1e-14, /* verbose = */ false); }\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    Psi &m_psi;\n    M2d m_C;\n    VarType m_ntilde = VarType::Zero();\n};\n\n// Define a relaxed 2D C-based energy based on a given 2D C-based energy `Psi_C`\ntemplate<class Psi_C>\nstruct RelaxedEnergyDensity {\n    static_assert(Psi_C::EDType == EDensityType::CBased,\n                  \"Tension field theory only works on C-based energy densities\");\n    static constexpr size_t N = Psi_C::N;\n    static constexpr size_t Dimension = N;\n    static constexpr EDensityType EDType = EDensityType::CBased;\n\n    using Matrix = typename Psi_C::Matrix;\n    using Real   = typename Psi_C::Real;\n    using ES     = Eigen::SelfAdjointEigenSolver<Matrix>;\n    using V2d    = Vec2_T<Real>;\n    static_assert(N == 2, \"Tension field theory relaxation only defined for 2D energies\");\n\n    static std::string name() {\n        return std::string(\"Relaxed\") + Psi_C::name();\n    }\n\n    // Forward all constructor arguments to m_psi\n    template<class... Args>\n    RelaxedEnergyDensity(Args&&... args)\n         : m_psi(std::forward<Args>(args)...),\n           m_anisoProb(m_psi, Matrix::Identity(), V2d::Zero()) { }\n\n    // We need a custom copy constructor since m_anisoProb contains a\n    // reference to this->m_psi\n    RelaxedEnergyDensity(const RelaxedEnergyDensity &b)\n        : m_psi(b.m_psi),\n          m_anisoProb(m_psi, Matrix::Identity(), V2d::Zero()) {\n        setC(b.m_C);\n    }\n\n    // Note: UninitializedDeformationTag argument must be a rvalue reference so it exactly\n    // matches the type passed by the constructor call\n    // RelaxedEnergyDensity(b, UninitializedDeformationTag()); otherwise the\n    // perfect forwarding constructor above will be preferred for this call,\n    // incorrectly forwarding b to Psi's constructor.\n    RelaxedEnergyDensity(const RelaxedEnergyDensity &b, UninitializedDeformationTag &&)\n        : m_psi(b.m_psi, UninitializedDeformationTag()),\n          m_anisoProb(m_psi, Matrix::Identity(), V2d::Zero()) {\n        setC(b.m_C);\n    }\n\n    void setC(const Matrix &C) {\n        m_C = C;\n        if (!relaxationEnabled()) {\n            m_psi.setC(C);\n            return;\n        }\n\n        // Note: Eigen guarantees eigenvalues are sorted in ascending order.\n        ES C_eigs(C);\n        // std::cout << \"C eigenvalues: \" << C_eigs.eigenvalues().transpose() << std::endl;\n        // Detect full compression\n        if (C_eigs.eigenvalues()[1] < 1) {\n            m_tensionState = 0;\n            m_wrinkleStrain = -C;\n            return;\n        }\n\n        m_psi.setC(C);\n        ES S_eigs(m_psi.PK2Stress());\n        // Detect full tension\n        // std::cout << \"S eigenvalues: \" << S_eigs.eigenvalues().transpose() << std::endl;\n        if (S_eigs.eigenvalues()[0] >= -1e-12) {\n            m_tensionState = 2;\n            m_wrinkleStrain.setZero();\n            return;\n        }\n\n        // Handle partial tension\n        m_tensionState = 1;\n        // In the isotropic case, principal stress and strain directions\n        // coincide, and the wrinkling strain must be in the form\n        // a n n^T, where n is the eigenvector corresponding to the smallest\n        // stress eigenvalue and a > 0 is an unknown.\n        // This simplifies the determination of wrinkling strain to a convex\n        // 1D optimization problem that we solve with Newton's method.\n        V2d n = S_eigs.eigenvectors().col(0);\n        using IWSP = IsotropicWrinkleStrainProblem<Psi_C>;\n        IWSP isoProb(m_psi, C, n);\n        // std::cout << \"Solving isotropic wrinkle strain problem\" << std::endl;\n        isoProb.setVars(typename IWSP::VarType{0.0});\n        isoProb.solve();\n        Real a = isoProb.getVars()[0];\n        if (a < 0) throw std::runtime_error(\"Invalid wrinkle strain\");\n\n        // We use this isotropic assumption to obtain initial guess for the\n        // anisotropic case, where the wrinkling strain is in the form\n        //      n_tilde n_tilde^T\n        // with a 2D vector n_tilde as the unknown.\n        m_anisoProb.setC(C);\n        // std::cout << \"Solving anisotropic wrinkle strain problem\" << std::endl;\n        m_anisoProb.setVars(std::sqrt(a) * n);\n        m_anisoProb.solve();\n        auto ntilde = m_anisoProb.getVars();\n        m_wrinkleStrain = -ntilde * ntilde.transpose();\n\n        // {\n        //     ES S_eigs_new(m_psi.PK2Stress());\n        //     std::cout << \"new S eigenvalues: \" << S_eigs_new.eigenvalues().transpose() << std::endl;\n        // }\n    }\n\n    Real energy() const {\n        if (relaxationEnabled() && fullCompression()) return 0.0;\n        return m_psi.energy();\n    }\n\n    Matrix PK2Stress() const {\n        if (relaxationEnabled() && fullCompression()) return Matrix::Zero();\n        // By envelope theorem, the wrinkling strain's perturbation can be\n        // neglected, and the stress is simply the stress of the underlying\n        // material model evaluated on the \"elastic strain\".\n        return m_psi.PK2Stress();\n    }\n\n    template<class Mat_>\n    Matrix delta_PK2Stress(const Mat_ &dC) const {\n        if (!relaxationEnabled() || fullTension()) return m_psi.delta_PK2Stress(dC);\n        if (fullCompression()) return Matrix::Zero();\n\n        // n solves m_anisoProb:\n        //     (psi') n = 0\n        // delta_n solves:\n        //     (psi'' : dC + n delta n) n + (psi') delta_n = 0\n        //     (psi'' : n delta_n) n + (psi') delta_n = -(psi'' : dC) n\n        //     H delta_n = -(psi'' : dC) n\n        auto ntilde = m_anisoProb.getVars();\n        V2d delta_n = -m_anisoProb.hessian().inverse() * (m_psi.delta_PK2Stress(dC.matrix()) * ntilde);\n\n        // In the partial tension case, we need to account for the wrinkling\n        // strain perturbation.\n        return m_psi.delta_PK2Stress(dC.matrix() + ntilde * delta_n.transpose()\n                                                 + delta_n * ntilde.transpose());\n    }\n\n    template<class Mat_, class Mat2_>\n    Matrix delta2_PK2Stress(const Mat_ &/* dF_a */, const Mat2_ &/* dF_b */) const {\n        throw std::runtime_error(\"Unimplemented\");\n    }\n\n    V2d principalBiotStrains() const {\n        ES es(m_C);\n        return es.eigenvalues().array().sqrt() - 1.0;\n    }\n\n    const Matrix &wrinkleStrain() const { return m_wrinkleStrain; }\n\n    bool fullCompression() const { return m_tensionState == 0; }\n    bool partialTension()  const { return m_tensionState == 1; }\n    bool fullTension()     const { return m_tensionState == 2; }\n    int tensionState()     const { return m_tensionState; }\n\n    // Copying is super dangerous since we m_anisoProb uses a reference to m_psi...\n    RelaxedEnergyDensity &operator=(const RelaxedEnergyDensity &) = delete;\n\n    // Direct access to the energy density for debugging or\n    // to change the material properties\n    Psi_C &psi() { return m_psi; }\n    const Psi_C &psi() const { return m_psi; }\n\n    // Turn on or off the tension field theory approximation\n    void setRelaxationEnabled(bool enable) {\n        m_relaxationEnabled = enable;\n        setC(m_C);\n    }\n\n    bool relaxationEnabled() const { return m_relaxationEnabled; }\n\n    void copyMaterialProperties(const RelaxedEnergyDensity &other) { psi().copyMaterialProperties(other.psi()); }\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n    // Tension state:\n    //      0: compression in all directions\n    //      1: partial tension\n    //      2: tension in all directions\n    int m_tensionState = 2;\n    Psi_C m_psi;\n    Matrix m_wrinkleStrain = Matrix::Zero(),\n           m_C = Matrix::Identity(); // full Cauchy-Green deformation tensor.\n    AnisotropicWrinkleStrainProblem<Psi_C> m_anisoProb;\n    bool m_relaxationEnabled = true;\n};\n\n#endif /* end of include guard: TENSIONFIELDTHEORY_HH */\n", "meta": {"hexsha": "04375a304f2cd29a9b0c5eb3ce8b357124ad381c", "size": 11956, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/lib/MeshFEM/EnergyDensities/TensionFieldTheory.hh", "max_stars_repo_name": "MeshFEM/MeshFEM", "max_stars_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "src/lib/MeshFEM/EnergyDensities/TensionFieldTheory.hh", "max_issues_repo_name": "MeshFEM/MeshFEM", "max_issues_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "src/lib/MeshFEM/EnergyDensities/TensionFieldTheory.hh", "max_forks_repo_name": "MeshFEM/MeshFEM", "max_forks_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 39.3289473684, "max_line_length": 113, "alphanum_fraction": 0.6134994982, "num_tokens": 3318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104788995148792, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.4336859855654373}}
{"text": "/* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */\n#include <malloc.h>\n#include \"Utils.h\"\n#include \"TraceStoreCol.h\"\n#include \"IonH5Eigen.h\"\n//#define EIGEN_USE_MKL_ALL 1\n#include <Eigen/Dense>\n#include <Eigen/LU>\n\n#define MIN_SAMPLE_WELL 100\n#define SMOOTH_REDUCE_STEP 10\n#define SMOOTH_REDUCE_REGION 100\n#define INTEGRATION_START 6\n#define INTEGRATION_END 12\nvoid TraceStoreCol::WellProj(TraceStoreCol &store,\n                             std::vector<KeySeq> & key_vectors,\n                             vector<char> &filter,\n                             vector<float> &mad) {\n  int useable_flows = 0;\n  for (size_t i = 0; i < key_vectors.size(); i++) {\n    useable_flows = std::max((int)key_vectors[i].usableKeyFlows, useable_flows);\n    //    useable_flows = std::max(store.GetNumFlows(), (size_t)useable_flows);\n  }\n  Eigen::VectorXf norm(store.mFrameStride * useable_flows);\n  Eigen::VectorXf sum(store.mFrameStride * useable_flows);\n\n  norm.setZero();\n  sum.setZero();\n  int start_frame = store.GetNumFrames() - 2;\n  int end_frame = store.GetNumFrames();\n  int count = 0;\n  for (int frame_ix = start_frame; frame_ix < end_frame; frame_ix++) {\n    count++;\n    int16_t *__restrict data_start = store.GetMemPtr() + frame_ix * store.mFlowFrameStride;\n    int16_t *__restrict data_end = data_start + store.mFrameStride * useable_flows;\n    float *__restrict norm_start = &norm[0];\n    while(data_start != data_end) {\n      *norm_start++ += *data_start++;\n    }\n  }\n\n  // std::vector<ChipReduction> smoothed_avg(useable_flows);\n  // int x_clip = mCols;\n  // int y_clip = mRows;\n  // if (mUseMeshNeighbors == 0) {\n  //   x_clip = THUMBNAIL_SIZE;\n  //   y_clip = THUMBNAIL_SIZE;\n  // }\n  // int last_frame = store.GetNumFrames() - 1;\n  // for (int flow_ix = 0; flow_ix < useable_flows; flow_ix++) {\n  //   smoothed_avg[flow_ix].Init(mRows, mCols, 1,\n  //                              SMOOTH_REDUCE_STEP, SMOOTH_REDUCE_STEP,\n  //                              y_clip, x_clip,\n  //                              SMOOTH_REDUCE_STEP * SMOOTH_REDUCE_STEP * .4);\n  //   smoothed_avg[flow_ix].ReduceFrame(&mData[0] + flow_ix * mFrameStride + last_frame  * mFlowFrameStride, &filter[0], 0);\n  //   smoothed_avg[flow_ix].SmoothBlocks(SMOOTH_REDUCE_REGION, SMOOTH_REDUCE_REGION);\n  // }\n  // int x_count = 0;\n  // for (int flow_ix = 0; flow_ix < useable_flows; flow_ix++) {\n  //   for (size_t row_ix = 0; row_ix < mRows; row_ix++) {\n  //     for (size_t col_ix = 0; col_ix < mCols; col_ix++) {\n  //       float avg = smoothed_avg[flow_ix].GetSmoothEst(row_ix, col_ix, 0);\n  //       norm[x_count] = avg;\n  //       x_count++;\n  //     }\n  //   }\n  // }\n\n  norm = norm / count;\n  //  start_frame = INTEGRATION_START;\n  //  end_frame = INTEGRATION_END;\n  start_frame = 5;\n  end_frame = store.GetNumFrames() - 6;\n  \n  for (int frame_ix = start_frame; frame_ix < end_frame; frame_ix++) {\n    int16_t *__restrict data_start = store.GetMemPtr() + frame_ix * store.mFlowFrameStride;\n    int16_t *__restrict data_end = data_start + store.mFrameStride * useable_flows;\n    float *__restrict norm_start = &norm[0];\n    float *__restrict sum_start = &sum[0];\n    int well_offset = 0;\n    while(data_start != data_end) {\n      if (*norm_start == 0.0f) {\n        *norm_start = 1.0f;\n        // avoid divide by zero but mark that something is wrong with this well..\n        if (filter[well_offset] == 0) {\n          filter[well_offset] = 6;\n        }\n      }\n      *sum_start += *data_start / *norm_start;\n      well_offset++;\n      // reset each flow\n      if (well_offset == (int) store.mFrameStride) {\n        well_offset = 0;\n      }\n      sum_start++;\n      data_start++;\n      norm_start++;\n    }\n  }\n  \n  Eigen::MatrixXf flow_mat(store.mFrameStride, useable_flows);\n  for (int flow_ix = 0; flow_ix < flow_mat.cols(); flow_ix++) {\n    for (size_t well_ix = 0; well_ix < store.mFrameStride; well_ix++) {\n      flow_mat(well_ix, flow_ix) = sum(flow_ix * store.mFrameStride + well_ix);\n    }\n  }\n\n  Eigen::VectorXf n2;\n  n2 = flow_mat.rowwise().squaredNorm();\n  n2 = n2.array().sqrt();\n  float *n2_start = n2.data();\n  float *n2_end = n2_start + n2.rows();\n  while (n2_start != n2_end) {\n    if (*n2_start == 0.0f) { *n2_start = 1.0f; }\n    n2_start++;\n  }\n  for (int flow_ix = 0; flow_ix < flow_mat.cols(); flow_ix++) {\n    flow_mat.col(flow_ix).array() = flow_mat.col(flow_ix).array() / n2.array();\n  }\n\n\n  Eigen::VectorXf proj;\n  Eigen::VectorXf max_abs_proj(flow_mat.rows());\n  max_abs_proj.setZero();\n  for (size_t key_ix = 0; key_ix < key_vectors.size(); key_ix++) {\n    Eigen::VectorXf key(useable_flows);\n    key.setZero();\n    for (int f_ix = 0; f_ix < useable_flows; f_ix++) {\n      key[f_ix] = key_vectors[key_ix].flows[f_ix];\n    }\n    proj = flow_mat * key;\n    proj = proj.array().abs();\n    for (int i = 0; i < proj.rows(); i++) {\n      max_abs_proj(i) = max(max_abs_proj(i), proj(i));\n    }\n  }\n  \n  for (int i = 0; i < max_abs_proj.rows(); i++) {\n    mad[i] = max_abs_proj(i);\n  }\n  \n}\n\nvoid TraceStoreCol::Init(Mask &mask, size_t frames, const char *flowOrder,\n       int numFlowsBuff, int maxFlow, int rowStep, int colStep) {\n\n    pthread_mutex_init (&mLock, NULL);\n    mUseMeshNeighbors = 1;\n    mRowRefStep = rowStep;\n    mColRefStep = colStep;\n    mMinRefProbes = floor (mRowRefStep * mColRefStep * .1);\n    mRows = mask.H();\n    mCols = mask.W();\n    mFrames = frames;\n    mFrameStride = mRows * mCols;\n    mFlows = mFlowsBuf = maxFlow;\n    mFlowFrameStride = mFrameStride * maxFlow;\n    mMaxDist = 2 * sqrt(rowStep*rowStep + colStep+colStep);\n    mFlowOrder = flowOrder;\n    \n    mWells = mRows * mCols;\n    mUseAsReference.resize (mWells, false);\n    int keep = 0;\n    int empties = 0;\n    mRefGridsValid.resize (mFlowsBuf, 0);\n    mRefGrids.resize (mFlowsBuf);\n    mData.resize (mWells * mFrames * mFlowsBuf);\n    std::fill (mData.begin(), mData.end(), 0);\n  }\n\n/**\n * Create the basis splines for order requested at a particular value of x.\n * From \"A Practical Guide To Splines - Revised Edition\" by Carl de Boor p 111\n * the algorithm for BSPLVB. The value of the spline coefficients can be calculated\n * based on a cool recursion. This is a simplified and numerically stable algorithm\n * that seems to be the basis of most bspline implementations including gsl, matlab,etc.\n * @param all_knots - Original knots vector augmented with order number of endpoints\n * @param n_knots - Total number of knots.\n * @param order - Order or order of polynomials, 4 for cubic splines.\n * @param i - index of value x in knots such that all_knots[i] <= x && all_knots[i+1] > x\n * @param x - value that we want to evaluate spline at.\n * @param b - memory to write our coefficients into, must be at least order long.\n */\nvoid basis_spline_xi_v2(float *all_knots, int n_knots, int order, int i, float x, float *b) {\n  b[0] = 1;\n  double kr[order];\n  double kl[order];\n  double term;\n  double saved;\n  for (int j = 0; j < order - 1; j++) {\n    kr[j] = all_knots[i + j + 1] - x; // k right values\n    kl[j] = x - all_knots[i - j];     // k left values\n    saved = 0;\n    for (int r = 0; r <= j; r++) {\n      term = b[r] / (kr[r] + kl[j-r]);\n      b[r] = saved + kr[r] * term;\n      saved = kl[j-r] * term;\n    }\n    b[j+1] = saved;\n  }\n}\n\n/**\n * Create the augmented knots vector and fill in matrix Xt with the spline basis vectors\n */\nvoid basis_splines_endreps_local_v2(float *knots, int n_knots, int order, int *boundaries, int n_boundaries,  Eigen::MatrixXf &Xt) {\n  assert(n_boundaries == 2 && boundaries[0] < boundaries[1]);\n  int n_rows = boundaries[1] - boundaries[0]; // this is frames so evaluate at each frame we'll need\n  int n_cols = n_knots + order;  // number of basis vectors we'll have at end \n  Xt.resize(n_cols, n_rows); // swapped to transpose later. This order lets us use it as a scratch space\n  Xt.fill(0);\n  int n_std_knots = n_knots + 2 * order;\n  float std_knots[n_std_knots];\n\n  // Repeat the boundary knots on there to ensure linear out side of knots\n  for (int i = 0; i < order; i++) {\n    std_knots[i] = boundaries[0];\n  }\n  // Our original boundary knots here\n  for (int i = 0; i < n_knots; i++) {\n    std_knots[i+order] = knots[i];\n  }\n  // Repeat the boundary knots on there to ensure linear out side of knots\n  for (int i = 0; i < order; i++) {\n    std_knots[i+order+n_knots] = boundaries[1];\n  }\n  // Evaluate our basis splines at each frame.\n  for (int i = boundaries[0]; i < boundaries[1]; i++) {\n    int idx = -1;\n    // find index such that i >= knots[idx] && i < knots[idx+1]\n    float *val = std::upper_bound(std_knots, std_knots + n_std_knots - 1, 1.0f * i);\n    idx = val - std_knots - 1;\n    assert(idx >= 0);\n    float *f = Xt.data() + i * n_cols + idx - (order - 1); //column offset\n    basis_spline_xi_v2(std_knots, n_std_knots, order, idx, i, f);\n  }\n  // Put in our conventional format where each column is a basis vector\n  Xt.transposeInPlace();\n}\n\nvoid FillInKnots(const std::string &strategy, int n_frame, std::vector<float> &knots) {\n  if (strategy != \"no-knots\") {\n    if (strategy == \"even4\") {\n      float stride = n_frame / 3.0f;\n      knots.push_back(stride);\n      knots.push_back(stride * 2.0f);\n    }\n    else if (strategy == \"every4\") {\n      int current = 4;\n      while (current < (n_frame -1)) {\n        knots.push_back(current);\n        current+=4;\n      }\n    }\n    else if (strategy == \"every3\") {\n      int current = 3;\n      while (current < (n_frame -1)) {\n        knots.push_back(current);\n        current+=3;\n      }\n    }\n    else if (strategy == \"middle\") {\n      float stride = n_frame / 2.0f;\n      knots.push_back(stride);\n    }\n    else if (strategy.find(\"explicit:\") == 0) {\n      string spec = strategy.substr(9, strategy.length() - 9);\n      knots = char2Vec<float>(spec.c_str(), ',');\n    }\n    else {\n      assert(false);\n    }\n  }\n}\n\nvoid TraceStoreCol::SplineLossyCompress(const std::string &strategy, int order, char *bad_wells, float *mad) {\n  Eigen::MatrixXf Basis;\n  vector<float> knots;\n  FillInKnots(strategy, mFrames, knots);\n  //  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> Basis(, compressed.n_frames, compressed.n_basis);\n  if (!knots.empty()) {\n    int boundaries[2];\n    boundaries[0] = 0;\n    boundaries[1] = mFrames;\n    basis_splines_endreps_local_v2(&knots[0], knots.size(), order, boundaries, sizeof(boundaries)/sizeof(boundaries[0]), Basis);\n  }\n  Eigen::MatrixXf SX = (Basis.transpose() * Basis).inverse() * Basis.transpose();\n  Eigen::MatrixXf Y(mFlowFrameStride, mFrames);\n  //  Eigen::MatrixXf FlowMeans(mFlows, mFrames);\n\n  //  FlowMeans.setZero();\n  int good_wells = 0;\n  char *bad_start = bad_wells;\n  char *bad_end = bad_start + mFrameStride;\n  while(bad_start != bad_end) {\n    if (*bad_start++ == 0) {\n      good_wells++;\n    }\n  }\n  \n  // if nothing good then skip it\n  if (good_wells < MIN_SAMPLE_WELL) {\n    return;\n  }\n\n  std::vector<ChipReduction> smoothed_avg(mFlows);\n  int x_clip = mCols;\n  int y_clip = mRows;\n  if (mUseMeshNeighbors == 0) {\n    x_clip = THUMBNAIL_SIZE;\n    y_clip = THUMBNAIL_SIZE;\n  }\n  for (size_t flow_ix = 0; flow_ix < mFlows; flow_ix++) {\n    smoothed_avg[flow_ix].Init(mRows, mCols, mFrames,\n                               SMOOTH_REDUCE_STEP, SMOOTH_REDUCE_STEP,\n                               y_clip, x_clip,\n                               SMOOTH_REDUCE_STEP * SMOOTH_REDUCE_STEP * .4);\n    for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n      smoothed_avg[flow_ix].ReduceFrame(&mData[0] + flow_ix * mFrameStride + frame_ix * mFlowFrameStride, bad_wells, frame_ix);\n    }\n    smoothed_avg[flow_ix].SmoothBlocks(SMOOTH_REDUCE_REGION, SMOOTH_REDUCE_REGION);\n  }\n\n  float *y_start = Y.data();\n  float *y_end = Y.data() + mData.size();\n  int16_t *trace_start = &mData[0];\n  while(y_start != y_end) {\n    *y_start++ = *trace_start++;\n  }\n\n  // // get the flow means per frame.\n  // for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n  //   for(size_t flow_ix = 0; flow_ix < mFlows; flow_ix++) {\n  //     float *start = Y.data() + mFlowFrameStride * frame_ix + flow_ix * mFrameStride;\n  //     float *end = start + mFrameStride;\n  //     float *sum = &FlowMeans(flow_ix, frame_ix);\n  //     char *bad = bad_wells;\n  //     while (start != end) {\n  //       if (*bad == 0) {\n  //         *sum += *start;\n  //       }\n  //       start++;\n  //       bad++;\n  //     }\n  //     *sum /= good_wells;\n  //   }\n  // }\n\n  // subtract off flow,frame avg\n  for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n    for(size_t flow_ix = 0; flow_ix < mFlows; flow_ix++) {\n      float *start = Y.data() + mFlowFrameStride * frame_ix + flow_ix * mFrameStride;\n      float *end = start + mFrameStride;\n      for (size_t row = 0; row < mRows; row++) {\n        for (size_t col = 0; col < mCols; col++) {\n          float avg = smoothed_avg[flow_ix].GetSmoothEst(row, col, frame_ix);\n          *start++ -= avg;\n        }\n      }\n    }\n  }\n\n\n  // // subtract them off\n  // Eigen::VectorXf col_mean = Y.colwise().sum();\n  // col_mean /= Y.rows();\n\n  // for (int i = 0; i < Y.cols(); i++) {\n  //   Y.col(i).array() -= col_mean.coeff(i);\n  // }\n\n  // Get coefficients to solve\n  Eigen::MatrixXf B = Y * SX.transpose();\n  // Uncompress data into yhat matrix\n  Eigen::MatrixXf Yhat = B * Basis.transpose();\n\n\n  // add the flow/frame averages back\n  for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n    for(size_t flow_ix = 0; flow_ix < mFlows; flow_ix++) {\n      float *start = Y.data() + mFlowFrameStride * frame_ix + flow_ix * mFrameStride;\n      float *end = start + mFrameStride;\n      float *hstart = Yhat.data() + mFlowFrameStride * frame_ix + flow_ix * mFrameStride;\n      for (size_t row = 0; row < mRows; row++) {\n        for (size_t col = 0; col < mCols; col++) {\n          float avg = smoothed_avg[flow_ix].GetSmoothEst(row, col, frame_ix);\n          *start++ += avg;\n          *hstart++ += avg;\n        }\n      }\n    }\n  }\n\n  // for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n  //   for(size_t flow_ix = 0; flow_ix < mFlows; flow_ix++) {\n  //     float *start = Y.data() + mFlowFrameStride * frame_ix + flow_ix * mFrameStride;\n  //     float *hstart = Yhat.data() + mFlowFrameStride * frame_ix + flow_ix * mFrameStride;\n  //     float *end = start + mFrameStride;\n  //     float avg = FlowMeans(flow_ix, frame_ix);\n  //     while (start != end) {\n  //       *start++ += avg;\n  //       *hstart++ += avg;\n  //     }\n  //   }\n  // }\n\n  // for (int i = 0; i < Yhat.cols(); i++) {\n  //   Yhat.col(i).array() += col_mean.coeff(i);\n  //   Y.col(i).array() += col_mean.coeff(i);\n  // }\n\n  float *yhat_start = Yhat.data();\n  float *yhat_end = Yhat.data() + mData.size();\n  trace_start = &mData[0];\n  while(yhat_start != yhat_end) {\n    *trace_start++ = (int)(*yhat_start + .5);\n    yhat_start++;\n  }\n\n  Y = Y - Yhat;\n  Eigen::VectorXf M = Y.rowwise().squaredNorm();\n\n  for (size_t flow_ix = 0; flow_ix < mFlows; flow_ix++) {\n    float *mad_start = mad;\n    float *mad_end = mad_start + mFrameStride;\n    float *m_start = M.data() + flow_ix * mFrameStride;\n    while (mad_start != mad_end) {\n      *mad_start += *m_start;\n      mad_start++;\n      m_start++;\n    }\n  }\n\n  float *mad_start = mad;\n  float *mad_end = mad + mFrameStride;\n  int norm_factor = mFlows * mFrames;\n  while (mad_start != mad_end) {\n    *mad_start /= norm_factor;\n    mad_start++;\n  }\n}\n\n\nvoid TraceStoreCol::SplineLossyCompress(const std::string &strategy, int order, int flow_ix, char *bad_wells, float *mad) {\n  Eigen::MatrixXf Basis;\n  vector<float> knots;\n  FillInKnots(strategy, mFrames, knots);\n  //  Eigen::Map<Eigen::MatrixXf, Eigen::Aligned> Basis(, compressed.n_frames, compressed.n_basis);\n  if (!knots.empty()) {\n    int boundaries[2];\n    boundaries[0] = 0;\n    boundaries[1] = mFrames;\n    basis_splines_endreps_local_v2(&knots[0], knots.size(), order, boundaries, sizeof(boundaries)/sizeof(boundaries[0]), Basis);\n  }\n  Eigen::MatrixXf SX = (Basis.transpose() * Basis).inverse() * Basis.transpose();\n  Eigen::MatrixXf Y(mFrameStride, mFrames);\n  //  Eigen::MatrixXf FlowMeans(mFlows, mFrames);\n\n  //  FlowMeans.setZero();\n  int good_wells = 0;\n  char *bad_start = bad_wells;\n  char *bad_end = bad_start + mFrameStride;\n  while(bad_start != bad_end) {\n    if (*bad_start++ == 0) {\n      good_wells++;\n    }\n  }\n  \n  // if nothing good then skip it\n  if (good_wells < MIN_SAMPLE_WELL) {\n    return;\n  }\n\n  ChipReduction smoothed_avg;\n  int x_clip = mCols;\n  int y_clip = mRows;\n  if (mUseMeshNeighbors == 0) {\n    x_clip = THUMBNAIL_SIZE;\n    y_clip = THUMBNAIL_SIZE;\n  }\n\n  smoothed_avg.Init(mRows, mCols, mFrames,\n                    SMOOTH_REDUCE_STEP, SMOOTH_REDUCE_STEP,\n                    y_clip, x_clip,\n                    SMOOTH_REDUCE_STEP * SMOOTH_REDUCE_STEP * .4);\n  for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n    smoothed_avg.ReduceFrame(&mData[0] + flow_ix * mFrameStride + frame_ix * mFlowFrameStride, bad_wells, frame_ix);\n  }\n  smoothed_avg.SmoothBlocks(SMOOTH_REDUCE_REGION, SMOOTH_REDUCE_REGION);\n\n\n  for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n    float *y_start = Y.data() + frame_ix * mFrameStride;\n    float *y_end = y_start + mFrameStride;\n    int16_t *trace_start = &mData[0] + flow_ix * mFrameStride + frame_ix * mFlowFrameStride;\n    while(y_start != y_end) {\n      *y_start++ = *trace_start++;\n    }\n  }\n    \n  // subtract off flow,frame avg\n  for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n    float *start = Y.data() + mFrameStride * frame_ix;\n    float *end = start + mFrameStride;\n    for (size_t row = 0; row < mRows; row++) {\n      for (size_t col = 0; col < mCols; col++) {\n        float avg = smoothed_avg.GetSmoothEst(row, col, frame_ix);\n        *start++ -= avg;\n      }\n    }\n  }\n\n  // Get coefficients to solve\n  Eigen::MatrixXf B = Y * SX.transpose();\n  // Uncompress data into yhat matrix\n  Eigen::MatrixXf Yhat = B * Basis.transpose();\n\n\n  // add the flow/frame averages back\n  for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n    float *start = Y.data() + mFrameStride * frame_ix;\n    float *end = start + mFrameStride;\n    float *hstart = Yhat.data() + mFrameStride * frame_ix;\n    for (size_t row = 0; row < mRows; row++) {\n      for (size_t col = 0; col < mCols; col++) {\n        float avg = smoothed_avg.GetSmoothEst(row, col, frame_ix);\n        *start++ += avg;\n        *hstart++ += avg;\n      }\n    }\n  }\n\n  for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n    float *yhat_start = Yhat.data() + frame_ix * mFrameStride;\n    float *yhat_end = yhat_start + mFrameStride;\n    int16_t *trace_start = &mData[0] + flow_ix * mFrameStride + frame_ix * mFlowFrameStride;\n    while(yhat_start != yhat_end) {\n      *trace_start++ = (int)(*yhat_start + .5f);\n      yhat_start++;\n    }\n  }\n\n  Y = Y - Yhat;\n  Eigen::VectorXf M = Y.rowwise().squaredNorm();\n\n  float *mad_start = mad;\n  float *mad_end = mad_start + mFrameStride;\n  float *m_start = M.data();\n  while (mad_start != mad_end) {\n    *mad_start += *m_start;\n    mad_start++;\n    m_start++;\n  }\n\n  mad_start = mad;\n  mad_end = mad + mFrameStride;\n  int norm_factor = mFrames;// mFlows * mFrames;\n  while (mad_start != mad_end) {\n    *mad_start /= norm_factor;\n    mad_start++;\n  }\n}\n\n\n\n// Compress a block of a data using pca\nvoid TraceStoreCol::PcaLossyCompress(int row_start, int row_end,\n                                     int col_start, int col_end,\n                                     int flow_ix,\n                                     float *ssq, char *filters,\n                                     int row_step, int col_step,\n                                     int num_pca) {\n\n  Eigen::MatrixXf Ysub, Y, S, Basis;\n\n  int loc_num_wells = (col_end - col_start) * (row_end - row_start);\n  int loc_num_cols = col_end - col_start;\n\n  // Take a sample of the data at rate step, avoiding flagged wells\n  // Count the good rows\n  int sample_wells = 0;\n  for (int row_ix = row_start; row_ix < row_end; row_ix+= row_step) {\n    char *filt_start = filters + row_ix * mCols + col_start;\n    char *filt_end = filt_start + loc_num_cols;\n    while (filt_start < filt_end) {\n      if (*filt_start == 0) {\n        sample_wells++;\n      }\n      filt_start += col_step;\n    }\n  }\n  // try backing off to every well rather than just sampled if we didn't get enough\n  if (sample_wells < MIN_SAMPLE_WELL) {\n    row_step = 1;\n    col_step = 1;\n    int sample_wells = 0;\n    for (int row_ix = row_start; row_ix < row_end; row_ix+= row_step) {\n      char *filt_start = filters + row_ix * mCols + col_start;\n      char *filt_end = filt_start + loc_num_cols;\n      while (filt_start < filt_end) {\n        if (*filt_start == 0) {\n          sample_wells++;\n        }\n        filt_start += col_step;\n      }\n    }\n  }\n\n  if (sample_wells < MIN_SAMPLE_WELL) {\n    return; // just give up\n  }\n\n  // Copy the sampled data in Matrix, frame major\n  Ysub.resize(sample_wells, mFrames);\n  for (int frame_ix = 0; frame_ix < (int)mFrames; frame_ix++) {\n    int sample_offset = 0;\n    for (int row_ix = row_start; row_ix < row_end; row_ix+=row_step) {\n      size_t store_offset = row_ix * mCols + col_start;\n      char *filt_start = filters + store_offset;\n      char *filt_end = filt_start + loc_num_cols;\n      int16_t *trace_start = &mData[0] + (mFlowFrameStride * frame_ix) + (flow_ix * mFrameStride) + store_offset;\n      float *ysub_start = Ysub.data() + sample_wells * frame_ix + sample_offset;\n      while (filt_start < filt_end) {\n        if (*filt_start == 0) {\n          *ysub_start = *trace_start;\n          ysub_start++;\n          sample_offset++;\n        }\n        trace_start += col_step;\n        filt_start += col_step;\n      }\n    }\n  }\n\n  // Copy in all the data into working matrix\n  Y.resize(loc_num_wells, (int)mFrames);\n  for (int frame_ix = 0; frame_ix < (int)mFrames; frame_ix++) {\n    for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n      size_t store_offset = row_ix * mCols + col_start;\n      int16_t *trace_start = &mData[0] + (mFlowFrameStride * frame_ix) + (flow_ix * mFrameStride) + store_offset;\n      int16_t *trace_end = trace_start + loc_num_cols;\n      float * y_start = Y.data() + loc_num_wells * frame_ix + (row_ix - row_start) * loc_num_cols;\n      while( trace_start != trace_end ) {\n        *y_start++ = *trace_start++;\n      }\n    }\n  }\n  Eigen::VectorXf col_mean = Y.colwise().sum();\n  col_mean /= Y.rows();\n\n  for (int i = 0; i < Y.cols(); i++) {\n    Y.col(i).array() -= col_mean.coeff(i);\n  }\n  // Create scatter matrix\n  S = Ysub.transpose() * Ysub;\n  // Compute the eigenvectors\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> es;\n  es.compute(S);\n  Eigen::MatrixXf Pca_Basis = es.eigenvectors();\n  Eigen::VectorXf Pca_Values = es.eigenvalues();\n  // Copy top eigen vectors into basis for projection\n  Basis.resize(mFrames, num_pca);\n  for (int i = 0; i < Basis.cols(); i++) {\n    //    Basis.col(i) = es.eigenvectors().col(es.eigenvectors().cols() - i -1);\n    Basis.col(i) = Pca_Basis.col(Pca_Basis.cols() - i - 1);\n  }\n  // Create solver matrix, often not a good way of solving things but eigen vectors should be stable and fast\n  Eigen::MatrixXf SX = (Basis.transpose() * Basis).inverse() * Basis.transpose();\n  // Get coefficients to solve\n  Eigen::MatrixXf B = Y * SX.transpose();\n  // Uncompress data into yhat matrix\n  Eigen::MatrixXf Yhat = B * Basis.transpose();\n\n  for (int i = 0; i < Yhat.cols(); i++) {\n    Yhat.col(i).array() += col_mean.coeff(i);\n    Y.col(i).array() += col_mean.coeff(i);\n  }\n  \n  // H5File h5(\"pca_lossy.h5\");\n  // h5.Open();\n  // char buff[256];\n  // snprintf(buff, sizeof(buff), \"/Y_%d_%d_%d\", flow_ix, row_start, col_start);\n  // H5Eigen::WriteMatrix(h5, buff, Y);\n  // snprintf(buff, sizeof(buff), \"/Yhat_%d_%d_%d\", flow_ix, row_start, col_start);\n  // H5Eigen::WriteMatrix(h5, buff, Yhat);\n  // snprintf(buff, sizeof(buff), \"/Basis_%d_%d_%d\", flow_ix, row_start, col_start);\n  // H5Eigen::WriteMatrix(h5, buff, Basis);\n  // h5.Close();\n  // Copy data out of yhat matrix into original data structure, keeping track of residuals\n  for (int frame_ix = 0; frame_ix < (int)mFrames; frame_ix++) {\n    for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n      size_t store_offset = row_ix * mCols + col_start;\n      int16_t *trace_start = &mData[0] + mFlowFrameStride * frame_ix + flow_ix * mFrameStride + store_offset;\n      int16_t *trace_end = trace_start + loc_num_cols;\n      float * ssq_start = ssq + store_offset;\n      size_t loc_offset = (row_ix - row_start) * loc_num_cols;\n      float * y_start = Y.data() + loc_num_wells * frame_ix + loc_offset;\n      float * yhat_start = Yhat.data() + loc_num_wells * frame_ix + loc_offset;\n      while( trace_start != trace_end ) {\n        *trace_start = (int16_t)(*yhat_start + .5);\n        float val = *y_start - *yhat_start;\n        *ssq_start += val * val;\n        y_start++;\n        yhat_start++;\n        trace_start++;\n        ssq_start++;\n      }\n    }\n  }\n\n  // divide ssq data out for per frame avg\n  for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n    size_t store_offset = row_ix * mCols + col_start;\n    float * ssq_start = ssq + store_offset;\n    float * ssq_end = ssq_start + loc_num_cols;\n    while (ssq_start != ssq_end) {\n      *ssq_start /= mFrames;\n      ssq_start++;\n    }\n  }\n}\n\nbool TraceStoreCol::PcaLossyCompressChunk(int row_start, int row_end,\n                                          int col_start, int col_end,\n                                          int num_rows, int num_cols, int num_frames,\n                                          int frame_stride,\n                                          int flow_ix, int flow_frame_stride,\n                                          short *data, bool replace,\n                                          float *ssq, char *filters,\n                                          int row_step, int col_step,\n                                          int num_pca) {\n\n  Eigen::MatrixXf Ysub, Y, S, Basis;\n\n  int loc_num_wells = (col_end - col_start) * (row_end - row_start);\n  int loc_num_cols = col_end - col_start;\n\n  // Take a sample of the data at rate step, avoiding flagged wells\n  // Count the good rows\n  int sample_wells = 0;\n  for (int row_ix = row_start; row_ix < row_end; row_ix+= row_step) {\n    char *filt_start = filters + row_ix * num_cols + col_start;\n    char *filt_end = filt_start + loc_num_cols;\n    while (filt_start < filt_end) {\n      if (*filt_start == 0) {\n        sample_wells++;\n      }\n      filt_start += col_step;\n    }\n  }\n  // try backing off to every well rather than just sampled if we didn't get enough\n  if (sample_wells < MIN_SAMPLE_WELL) {\n    row_step = 1;\n    col_step = 1;\n    int sample_wells = 0;\n    for (int row_ix = row_start; row_ix < row_end; row_ix+= row_step) {\n      char *filt_start = filters + row_ix * num_cols + col_start;\n      char *filt_end = filt_start + loc_num_cols;\n      while (filt_start < filt_end) {\n        if (*filt_start == 0) {\n          sample_wells++;\n        }\n        filt_start += col_step;\n      }\n    }\n  }\n\n  if (sample_wells < MIN_SAMPLE_WELL) {\n    return false; // just give up\n  }\n\n  // Got enough data to work with, zero out the ssq array for accumulation\n  for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n    float *ssq_start = ssq + row_ix * num_cols + col_start;\n    float *ssq_end = ssq_start + loc_num_cols;\n    while (ssq_start != ssq_end) {\n      *ssq_start++ = 0;\n    }\n  }\n  // Copy the sampled data in Matrix, frame major\n  Ysub.resize(sample_wells, num_frames);\n  for (int frame_ix = 0; frame_ix < (int)num_frames; frame_ix++) {\n    int sample_offset = 0;\n    for (int row_ix = row_start; row_ix < row_end; row_ix+=row_step) {\n      size_t store_offset = row_ix * num_cols + col_start;\n      char *filt_start = filters + store_offset;\n      char *filt_end = filt_start + loc_num_cols;\n      int16_t *trace_start = data + (flow_frame_stride * frame_ix) + (flow_ix * frame_stride) + store_offset;\n      float *ysub_start = Ysub.data() + sample_wells * frame_ix + sample_offset;\n      while (filt_start < filt_end) {\n        if (*filt_start == 0) {\n          *ysub_start = *trace_start;\n          ysub_start++;\n          sample_offset++;\n        }\n        trace_start += col_step;\n        filt_start += col_step;\n      }\n    }\n  }\n\n  // Copy in all the data into working matrix\n  Y.resize(loc_num_wells, (int)num_frames);\n  for (int frame_ix = 0; frame_ix < (int)num_frames; frame_ix++) {\n    for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n      size_t store_offset = row_ix * num_cols + col_start;\n      int16_t *trace_start = data + (flow_frame_stride * frame_ix) + (flow_ix * frame_stride) + store_offset;\n      int16_t *trace_end = trace_start + loc_num_cols;\n      float * y_start = Y.data() + loc_num_wells * frame_ix + (row_ix - row_start) * loc_num_cols;\n      while( trace_start != trace_end ) {\n        *y_start++ = *trace_start++;\n      }\n    }\n  }\n  Eigen::VectorXf col_mean = Y.colwise().sum();\n  col_mean /= Y.rows();\n\n  for (int i = 0; i < Y.cols(); i++) {\n    Y.col(i).array() -= col_mean.coeff(i);\n  }\n  // Create scatter matrix\n  S = Ysub.transpose() * Ysub;\n  // Compute the eigenvectors\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> es;\n  es.compute(S);\n  Eigen::MatrixXf Pca_Basis = es.eigenvectors();\n  Eigen::VectorXf Pca_Values = es.eigenvalues();\n  // Copy top eigen vectors into basis for projection\n  Basis.resize(num_frames, num_pca);\n  for (int i = 0; i < Basis.cols(); i++) {\n    //    Basis.col(i) = es.eigenvectors().col(es.eigenvectors().cols() - i -1);\n    Basis.col(i) = Pca_Basis.col(Pca_Basis.cols() - i - 1);\n  }\n  // Create solver matrix, often not a good way of solving things but eigen vectors should be stable and fast\n  Eigen::MatrixXf SX = (Basis.transpose() * Basis).inverse() * Basis.transpose();\n  // Get coefficients to solve\n  Eigen::MatrixXf B = Y * SX.transpose();\n  // Uncompress data into yhat matrix\n  Eigen::MatrixXf Yhat = B * Basis.transpose();\n\n  for (int i = 0; i < Yhat.cols(); i++) {\n    Yhat.col(i).array() += col_mean.coeff(i);\n    Y.col(i).array() += col_mean.coeff(i);\n  }\n  \n  // H5File h5(\"pca_lossy.h5\");\n  // h5.Open();\n  // char buff[256];\n  // snprintf(buff, sizeof(buff), \"/Y_%d_%d_%d\", flow_ix, row_start, col_start);\n  // H5Eigen::WriteMatrix(h5, buff, Y);\n  // snprintf(buff, sizeof(buff), \"/Yhat_%d_%d_%d\", flow_ix, row_start, col_start);\n  // H5Eigen::WriteMatrix(h5, buff, Yhat);\n  // snprintf(buff, sizeof(buff), \"/Basis_%d_%d_%d\", flow_ix, row_start, col_start);\n  // H5Eigen::WriteMatrix(h5, buff, Basis);\n  // h5.Close();\n  // Copy data out of yhat matrix into original data structure, keeping track of residuals\n  for (int frame_ix = 0; frame_ix < (int)num_frames; frame_ix++) {\n    for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n      size_t store_offset = row_ix * num_cols + col_start;\n      int16_t *trace_start = data + flow_frame_stride * frame_ix + flow_ix * frame_stride + store_offset;\n      int16_t *trace_end = trace_start + loc_num_cols;\n      float * ssq_start = ssq + store_offset;\n      size_t loc_offset = (row_ix - row_start) * loc_num_cols;\n      float * y_start = Y.data() + loc_num_wells * frame_ix + loc_offset;\n      float * yhat_start = Yhat.data() + loc_num_wells * frame_ix + loc_offset;\n      while( trace_start != trace_end ) {\n        if (replace) {\n          *trace_start = (int16_t)(*yhat_start + .5);\n        }\n        float val = *y_start - *yhat_start;\n        *ssq_start += val * val;\n        y_start++;\n        yhat_start++;\n        trace_start++;\n        ssq_start++;\n      }\n    }\n  }\n\n  // divide ssq data out for per frame avg\n  for (int row_ix = row_start; row_ix < row_end; row_ix++) {\n    size_t store_offset = row_ix * num_cols + col_start;\n    float * ssq_start = ssq + store_offset;\n    float * ssq_end = ssq_start + loc_num_cols;\n    while (ssq_start != ssq_end) {\n      *ssq_start /= num_frames;\n      ssq_start++;\n    }\n  }\n  return true;\n}\n\nvoid TraceStoreCol::SplineLossyCompress(const std::string &strategy, int order, int flow_ix, char *bad_wells, \n                                        float *mad, size_t num_rows, size_t num_cols, size_t num_frames, size_t num_flows,\n                                        int use_mesh_neighbors, size_t frame_stride, size_t flow_frame_stride, int16_t *data) {\n  Eigen::MatrixXf Basis;\n  vector<float> knots;\n  FillInKnots(strategy, num_frames, knots);\n  if (!knots.empty()) {\n    int boundaries[2];\n    boundaries[0] = 0;\n    boundaries[1] = num_frames;\n    basis_splines_endreps_local_v2(&knots[0], knots.size(), order, boundaries, sizeof(boundaries)/sizeof(boundaries[0]), Basis);\n  }\n  Eigen::MatrixXf SX = (Basis.transpose() * Basis).inverse() * Basis.transpose();\n  Eigen::MatrixXf Y(frame_stride, num_frames);\n  //  Eigen::MatrixXf FlowMeans(num_flows, num_frames);\n\n  //  FlowMeans.setZero();\n  int good_wells = 0;\n  char *bad_start = bad_wells;\n  char *bad_end = bad_start + frame_stride;\n  while(bad_start != bad_end) {\n    if (*bad_start++ == 0) {\n      good_wells++;\n    }\n  }\n  \n  // if nothing good then skip it\n  if (good_wells < MIN_SAMPLE_WELL) {\n    return;\n  }\n\n  ChipReduction smoothed_avg;\n  int x_clip = num_cols;\n  int y_clip = num_rows;\n  if (use_mesh_neighbors == 0) {\n    x_clip = THUMBNAIL_SIZE;\n    y_clip = THUMBNAIL_SIZE;\n  }\n\n  smoothed_avg.Init(num_rows, num_cols, num_frames,\n                    SMOOTH_REDUCE_STEP, SMOOTH_REDUCE_STEP,\n                    y_clip, x_clip,\n                    SMOOTH_REDUCE_STEP * SMOOTH_REDUCE_STEP * .4);\n  for (size_t frame_ix = 0; frame_ix < num_frames; frame_ix++) {\n    smoothed_avg.ReduceFrame(data + flow_ix * frame_stride + frame_ix * flow_frame_stride, bad_wells, frame_ix);\n  }\n  smoothed_avg.SmoothBlocks(SMOOTH_REDUCE_REGION, SMOOTH_REDUCE_REGION);\n\n\n  for (size_t frame_ix = 0; frame_ix < num_frames; frame_ix++) {\n    float *y_start = Y.data() + frame_ix * frame_stride;\n    float *y_end = y_start + frame_stride;\n    int16_t *trace_start = data + flow_ix * frame_stride + frame_ix * flow_frame_stride;\n    while(y_start != y_end) {\n      *y_start++ = *trace_start++;\n    }\n  }\n    \n  // subtract off flow,frame avg\n  for (size_t frame_ix = 0; frame_ix < num_frames; frame_ix++) {\n    float *start = Y.data() + frame_stride * frame_ix;\n    float *end = start + frame_stride;\n    for (size_t row = 0; row < num_rows; row++) {\n      for (size_t col = 0; col < num_cols; col++) {\n        float avg = smoothed_avg.GetSmoothEst(row, col, frame_ix);\n        *start++ -= avg;\n      }\n    }\n  }\n\n  // Get coefficients to solve\n  Eigen::MatrixXf B = Y * SX.transpose();\n  // Uncompress data into yhat matrix\n  Eigen::MatrixXf Yhat = B * Basis.transpose();\n\n\n  // add the flow/frame averages back\n  for (size_t frame_ix = 0; frame_ix < num_frames; frame_ix++) {\n    float *start = Y.data() + frame_stride * frame_ix;\n    float *end = start + frame_stride;\n    float *hstart = Yhat.data() + frame_stride * frame_ix;\n    for (size_t row = 0; row < num_rows; row++) {\n      for (size_t col = 0; col < num_cols; col++) {\n        float avg = smoothed_avg.GetSmoothEst(row, col, frame_ix);\n        *start++ += avg;\n        *hstart++ += avg;\n      }\n    }\n  }\n\n  for (size_t frame_ix = 0; frame_ix < num_frames; frame_ix++) {\n    float *yhat_start = Yhat.data() + frame_ix * frame_stride;\n    float *yhat_end = yhat_start + frame_stride;\n    int16_t *trace_start = data + flow_ix * frame_stride + frame_ix * flow_frame_stride;\n    while(yhat_start != yhat_end) {\n      *trace_start++ = (int)(*yhat_start + .5f);\n      yhat_start++;\n    }\n  }\n\n  Y = Y - Yhat;\n  Eigen::VectorXf M = Y.rowwise().squaredNorm();\n\n  float *mad_start = mad;\n  float *mad_end = mad_start + frame_stride;\n  float *m_start = M.data();\n  while (mad_start != mad_end) {\n    *mad_start += *m_start;\n    mad_start++;\n    m_start++;\n  }\n\n  mad_start = mad;\n  mad_end = mad + frame_stride;\n  int norm_factor = num_frames;// num_flows * num_frames;\n  while (mad_start != mad_end) {\n    *mad_start /= norm_factor;\n    mad_start++;\n  }\n}\n\nint TraceStoreCol::PrepareReference(size_t flowIx, std::vector<char> &filteredWells) {\n    mRefWells.resize(mUseAsReference.size());\n    for (size_t i = 0; i < mRefWells.size(); i++) {\n      if (mUseAsReference[i]) {\n        mRefWells[i] = 0;\n      }\n      else {\n        mRefWells[i] = 1;\n      }\n    }\n    assert(flowIx < mRefReduction.size());\n\n    int x_clip = mCols;\n    int y_clip = mRows;\n    if (mUseMeshNeighbors == 0) {\n      x_clip = THUMBNAIL_SIZE;\n      y_clip = THUMBNAIL_SIZE;\n    }\n    mRefReduction[flowIx].Init(mRows, mCols, mFrames,\n                               REF_REDUCTION_SIZE, REF_REDUCTION_SIZE, \n                               y_clip, x_clip, 1);\n    for (size_t frame_ix = 0; frame_ix < mFrames; frame_ix++) {\n      mRefReduction[flowIx].ReduceFrame(&mData[0] + flowIx * mFrameStride + frame_ix * mFlowFrameStride, &mRefWells[0], frame_ix);\n    }\n    mRefReduction[flowIx].SmoothBlocks(REF_SMOOTH_SIZE, REF_SMOOTH_SIZE);\n    return TSM_OK;\n  }\n\n\nint TraceStoreCol::PrepareReferenceOld (size_t flowIx, std::vector<char> &filteredWells) {\n    int fIdx = flowIx;\n    CalcReference (mRowRefStep, mColRefStep, flowIx, mRefGrids[fIdx], filteredWells);\n    mRefGridsValid[fIdx] = 1;\n    mFineRefGrids.resize (mRefGrids.size());\n    mFineRefGrids[fIdx].Init (mRows, mCols, mRowRefStep/2, mColRefStep/2);\n    int numBin = mFineRefGrids[fIdx].GetNumBin();\n    int rowStart = -1, rowEnd = -1, colStart = -1, colEnd = -1;\n    for (int binIx = 0; binIx < numBin; binIx++) {\n      mFineRefGrids[fIdx].GetBinCoords (binIx, rowStart, rowEnd, colStart, colEnd);\n      vector<float> &trace = mFineRefGrids[fIdx].GetItem (binIx);\n      CalcMedianReference ( (rowEnd + rowStart) /2, (colEnd + colStart) /2, mRefGrids[fIdx],\n                            mDist, mValues, trace);\n    }\n    return TSM_OK;\n  }\n\n\nint TraceStoreCol::CalcMedianReference (size_t row, size_t col,\n                           GridMesh<std::vector<float> > &regionMed,\n                           std::vector<double> &dist,\n                           std::vector<std::vector<float> *> &values,\n                           std::vector<float> &reference) {\n    int retVal = TraceStore::TS_OK;\n    reference.resize(mFrames);\n    std::fill(reference.begin(), reference.end(), 0.0);\n    regionMed.GetClosestNeighbors (row, col, mUseMeshNeighbors, dist, values);\n    int num_good = 0;\n    size_t valSize = values.size();\n    for (size_t i =0; i < valSize; i++) {\n      if (values[i]->size() > 0) {\n        num_good++;\n      }\n    }\n    // try reaching a little farther if no good reference close by\n    if (num_good == 0) {\n      regionMed.GetClosestNeighbors (row, col, 2*mUseMeshNeighbors, dist, values);\n    }\n    size_t size = 0;\n    double maxDist = 0;\n    for (size_t i = 0; i < values.size(); i++) {\n        size = max (values[i]->size(), size);\n        maxDist = max(dist[i], maxDist);\n    }\n    reference.resize (size);\n    std::fill (reference.begin(), reference.end(), 0.0);\n    double distWeight = 0;\n         valSize = values.size();\n\n    for (size_t i = 0; i < valSize; i++) {\n      if (values[i]->size()  == 0) {\n        continue;\n      }\n      double w = TraceStore::WeightDist (dist[i], mRowRefStep); //1/sqrt(dist[i]+1);\n      distWeight += w;\n      size_t vSize = values[i]->size();\n      for (size_t j = 0; j < vSize; j++) {\n        reference[j] += w * values[i]->at (j);\n      }\n    }\n    // Divide by our total weight to get weighted mean\n    if (distWeight > 0)  {\n      for (size_t i = 0; i < reference.size(); i++) {\n        reference[i] /= distWeight;\n      }\n      retVal = TraceStore::TS_OK;\n    }\n    else {\n      retVal = TraceStore::TS_BAD_DATA;\n    }\n    return retVal;\n  }\n", "meta": {"hexsha": "ee355ae9357963042290e0b3df4b42878b03e6f7", "size": 39669, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Analysis/Separator/TraceStoreCol.cpp", "max_stars_repo_name": "konradotto/TS", "max_stars_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 125.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T05:43:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T17:15:59.000Z", "max_issues_repo_path": "Analysis/Separator/TraceStoreCol.cpp", "max_issues_repo_name": "konradotto/TS", "max_issues_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2015-02-10T09:13:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T02:32:38.000Z", "max_forks_repo_path": "Analysis/Separator/TraceStoreCol.cpp", "max_forks_repo_name": "konradotto/TS", "max_forks_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 98.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T01:25:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T17:29:42.000Z", "avg_line_length": 35.5775784753, "max_line_length": 132, "alphanum_fraction": 0.6137538128, "num_tokens": 11740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.4336270307839906}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP\n#define STAN_MATH_PRIM_MAT_PROB_ORDERED_LOGISTIC_LPMF_HPP\n\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/scal/fun/inv_logit.hpp>\n#include <stan/math/prim/scal/fun/log1m.hpp>\n#include <stan/math/prim/scal/fun/log1m_exp.hpp>\n#include <stan/math/prim/scal/fun/log1p_exp.hpp>\n#include <stan/math/prim/scal/err/check_bounded.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_greater.hpp>\n#include <stan/math/prim/scal/err/check_less.hpp>\n#include <stan/math/prim/scal/err/check_less_or_equal.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/err/check_positive.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/mat/prob/categorical_rng.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n\nnamespace stan {\n  namespace math {\n\n    template <typename T>\n    inline T log_inv_logit_diff(const T& alpha, const T& beta) {\n      using std::exp;\n      return beta + log1m_exp(alpha - beta) - log1p_exp(alpha)\n        - log1p_exp(beta);\n    }\n\n    /**\n     * Returns the (natural) log probability of the specified integer\n     * outcome given the continuous location and specified cutpoints\n     * in an ordered logistic model.\n     *\n     * <p>Typically the continous location\n     * will be the dot product of a vector of regression coefficients\n     * and a vector of predictors for the outcome.\n     *\n     * @tparam propto True if calculating up to a proportion.\n     * @tparam T_loc Location type.\n     * @tparam T_cut Cut-point type.\n     * @param y Outcome.\n     * @param lambda Location.\n     * @param c Positive increasing vector of cutpoints.\n     * @return Log probability of outcome given location and\n     * cutpoints.\n\n     * @throw std::domain_error If the outcome is not between 1 and\n     * the number of cutpoints plus 2; if the cutpoint vector is\n     * empty; if the cutpoint vector contains a non-positive,\n     * non-finite value; or if the cutpoint vector is not sorted in\n     * ascending order.\n     */\n    template <bool propto, typename T_lambda, typename T_cut>\n    typename boost::math::tools::promote_args<T_lambda, T_cut>::type\n    ordered_logistic_lpmf(int y, const T_lambda& lambda,\n                         const Eigen::Matrix<T_cut, Eigen::Dynamic, 1>& c) {\n      using std::exp;\n      using std::log;\n\n      static const char* function(\"ordered_logistic\");\n\n      int K = c.size() + 1;\n\n      check_bounded(function, \"Random variable\", y, 1, K);\n      check_finite(function, \"Location parameter\", lambda);\n      check_greater(function, \"Size of cut points parameter\", c.size(), 0);\n      for (int i = 1; i < c.size(); ++i)\n        check_greater(function, \"Cut points parameter\", c(i), c(i - 1));\n\n      check_finite(function, \"Cut points parameter\", c(c.size()-1));\n      check_finite(function, \"Cut points parameter\", c(0));\n\n      // log(1 - inv_logit(lambda))\n      if (y == 1)\n        return -log1p_exp(lambda - c(0));\n\n      // log(inv_logit(lambda - c(K-3)));\n      if (y == K) {\n        return -log1p_exp(c(K-2) - lambda);\n      }\n\n      // if (2 < y < K) { ... }\n      // log(inv_logit(lambda - c(y-2)) - inv_logit(lambda - c(y-1)))\n      return log_inv_logit_diff(c(y-2) - lambda,\n                                c(y-1) - lambda);\n    }\n\n    template <typename T_lambda, typename T_cut>\n    typename boost::math::tools::promote_args<T_lambda, T_cut>::type\n    ordered_logistic_lpmf(int y, const T_lambda& lambda,\n                         const Eigen::Matrix<T_cut, Eigen::Dynamic, 1>& c) {\n      return ordered_logistic_lpmf<false>(y, lambda, c);\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "5cc0021b03240ec4b6dc2f59b606e9bbdef2e7d7", "size": 3749, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/ordered_logistic_lpmf.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/ordered_logistic_lpmf.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/ordered_logistic_lpmf.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.49, "max_line_length": 76, "alphanum_fraction": 0.6644438517, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4336212767310496}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MTL_BIT_MASKING_INCLUDE\n#define MTL_BIT_MASKING_INCLUDE\n\n#include <boost/type_traits/is_same.hpp>\n#include <boost/mpl/if.hpp>\n\n#include <boost/numeric/mtl/utility/tag.hpp>\n\nnamespace mtl {\n\n/*\n     The bit masks are row masks, that mean 1s represent rows and 0s columns.\n\n     Bit masks:\n\n     i-order (cyrillic i):\n     ---------------------\n  \n     binary:     01010101 ... 01\n     0x55555555\n\n\n     z-order:\n     --------\n     \n     binary:     10101010 ... 10\n     0xaaaaaaaa\n\n     row major:\n     ----------\n\n     with 2^k columns\n     binary:    111111111...1000...0\n                             ------- k 0s at the end (LSB), all bits before 1s (MSB)\n\n     column major:\n     -------------\n\n     with 2^k rows\n     binary:    000000000...0111...1\n                             ------- k 1s at the end (LSB), all bits before 0s (MSB)\n\n     hybrid (Doppled):\n     -----------------\n\n     i-order\n     with 2^k by 2^k base case\n     row major\n     binary     0101....011...10...0\n                               ----- k 0s at the end (LSB); means columns\n                          ----- k 1s before; means rows\n                ---------- i order\n     e.g. 32 by 32 base case 0101...01 11111 00000 = 0x555557e0\n\n     column major\n     binary     0101....010...01...1\n                               ----- k 1s at the end (LSB); means rows\n                          ----- k 0s before; means columns\n                ---------- i order\n     e.g. 32 by 32 base case 0101...01 00000 11111 = 0x5555541f\n\n     Shark-tooth base case:\n     ----------------------\n\n     2^t tooth length\n     in  2^k by 2^k base case (of course t <= k)\n     row-major\n     binary     1..1 00..0 1..1\n                           ---- t 1s at the end (LSB); means 2^t tooth allong rows\n                     ---- k 0s before; means columns\n                ---- k-t 1s before; means rows\n\n     column-major\n     binary     0..0 11..1 0..0\n                           ---- t 0s at the end (LSB); means 2^t tooth allong columns\n                     ---- k 1s before; means rows\n                ---- k-t 0s before; means columns\n\n\n*/\n\n\n// Mask for the last N bits\ntemplate <unsigned long N>\nstruct lsb_mask\n{\n    static const unsigned long value= (lsb_mask<N-1>::value << 1) | 1;\n};\n\n\ntemplate <>\nstruct lsb_mask<0>\n{\n    static const unsigned long value= 0;\n};\n\n\n/// Last N bits of Value\ntemplate <unsigned long N, unsigned long Value>\nstruct lsb_bits\n{\n    static const unsigned long value= lsb_mask<N>::value & Value;\n};\n\n\n/// Compares two masks\ntemplate <unsigned long Mask1, unsigned long Mask2>\nstruct same_mask\n{\n    static const bool value= false;\n};\n\ntemplate <unsigned long Mask>\nstruct same_mask<Mask, Mask>\n{\n    static const bool value= true;\n};\n\n\n/// Row-major mask for 2^K by 2^K base case\ntemplate <unsigned long K>\nstruct row_major_mask\n{\n    static const unsigned long value= lsb_mask<K>::value << K;\n};\n\n\n/// Column-major mask for 2^K by 2^K base case\ntemplate <unsigned long K>\nstruct col_major_mask\n    : public lsb_mask<K>\n{};\n\n\n/// Checks whether 2^K by 2^K base case of hybric matrix, defined by Mask, is a row-major matrix\ntemplate <unsigned long K, unsigned long Mask>\nstruct is_k_power_base_case_row_major\n{\n    static const bool value= same_mask<lsb_bits<2*K, Mask>::value, row_major_mask<K>::value>::value;\n    // typedef \n};\n\n\n/// Checks whether 2^K by 2^K base case of hybric matrix, defined by Mask, is a column-major matrix\ntemplate <unsigned long K, unsigned long Mask>\nstruct is_k_power_base_case_col_major\n{\n    static const bool value= same_mask<lsb_bits<2*K, Mask>::value, col_major_mask<K>::value>::value;\n};\n\n\n/// Checks whether 32x32 base case of hybric matrix, defined by Mask, is a row-major matrix\ntemplate <unsigned long Mask>\nstruct is_32_base_case_row_major\n    : public is_k_power_base_case_row_major<5, Mask>\n{};\n\n\n/// Checks whether 32x32 base case of hybric matrix, defined by Mask, is a col-major matrix\ntemplate <unsigned long Mask>\nstruct is_32_base_case_col_major\n    : public is_k_power_base_case_col_major<5, Mask>\n{};\n\n\n/// Row-major mask for 2^K by 2^K base case with 2^T shark teeth\ntemplate <unsigned long K, unsigned long T>\nstruct row_major_shark_mask\n{\n    static const unsigned long value= (lsb_mask<K-T>::value << (K+T)) | lsb_mask<T>::value;\n};\n\n\n/// Row-major mask for 2^K by 2^K base case with 2^T shark teeth\ntemplate <unsigned long K, unsigned long T>\nstruct col_major_shark_mask\n{\n    static const unsigned long value= lsb_mask<K>::value << T;\n};\n\n\n/** Checks whether 2^K by 2^K base case of hybric matrix, defined by Mask,\n    is a row-major matrix shark-tooth with 2^T tooth length\n**/\ntemplate <unsigned long K, unsigned long T, unsigned long Mask>\nstruct is_k_power_base_case_row_major_t_shark\n{\n    static const bool value= same_mask<lsb_bits<2*K, Mask>::value, row_major_shark_mask<K, T>::value>::value;\n};\n\n\n/** Checks whether 2^K by 2^K base case of hybric matrix, defined by Mask,\n    is a col-major matrix shark-tooth with 2^T tooth length\n**/\ntemplate <unsigned long K, unsigned long T, unsigned long Mask>\nstruct is_k_power_base_case_col_major_t_shark\n{\n    static const bool value= same_mask<lsb_bits<2*K, Mask>::value, col_major_shark_mask<K, T>::value>::value;\n};\n\n  // e-order\n/// N-order mask of N bits\ntemplate <unsigned long N>\nstruct i_order_mask\n{\n    // Check if N is even !!!\n    static const unsigned long value= (i_order_mask<N-2>::value << 2) | 1;\n};\n\ntemplate<> struct i_order_mask<0> : public lsb_mask<0> {};  // set to 0\n\n\n/// Z-order mask of N bits\ntemplate <unsigned long N>\nstruct z_order_mask\n{\n    // Check if N is even !!!\n    static const unsigned long value= (z_order_mask<N-2>::value << 2) | 2;\n};\n\ntemplate<> struct z_order_mask<0> : public lsb_mask<0> {};  // set to 0\n\n\n/** Generate arbitrary hybrid mask.\n    \\param IOrder if true then i-order otherwise z-order\n    \\param K      2^K by 2^K base case \n    \\param Orientation  mtl::row_major or mtl::col_major\n    \\param T      2^T tooth length\n**/\ntemplate <bool IOrder, unsigned long K, typename Orientation, unsigned long T>\nclass generate_mask\n{\n    static const unsigned long rec_size= 8 * sizeof(unsigned long) - 2 * K,\n\trec_part= (IOrder ? i_order_mask<rec_size>::value : z_order_mask<rec_size>::value) << 2*K;\n    typedef typename boost::mpl::if_<\n\tboost::is_same<Orientation, row_major>\n      , row_major_shark_mask<K, T>\n      , col_major_shark_mask<K, T>\n    >::type base_part_type;\npublic:\n    static const unsigned long value= rec_part | base_part_type::value;\n};\n\n\n} // namespace mtl\n\n#endif // MTL_BIT_MASKING_INCLUDE\n", "meta": {"hexsha": "6bb09ffb2906ba71be4fc140c0fd5d45c2dd5cf4", "size": 7012, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/recursion/bit_masking.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/recursion/bit_masking.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/recursion/bit_masking.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 26.9692307692, "max_line_length": 109, "alphanum_fraction": 0.6361950941, "num_tokens": 1935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.6548947155710234, "lm_q1q2_score": 0.43348978477449723}}
{"text": "/*\n// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a\n// component of the Texas A&M University System.\n\n// All rights reserved.\n\n// The information and source code contained herein is the exclusive\n// property of TEES and may not be disclosed, examined or reproduced\n// in whole or in part without explicit written authorization from TEES.\n*/\n\n#ifndef STAPL_BENCHMARK_LONESTAR_AGGLOMERATIVECLUSTERING_HPP\n#define STAPL_BENCHMARK_LONESTAR_AGGLOMERATIVECLUSTERING_HPP\n\n#include <iostream>\n#include <sstream>\n#include <map>\n\n#include <stapl/utility/do_once.hpp>\n#include <stapl/containers/array/array.hpp>\n#include <stapl/views/array_view.hpp>\n\n#include <stapl/containers/graph/hierarchical_graph.hpp>\n#include <stapl/containers/graph/views/hgraph_view.hpp>\n#include <stapl/containers/graph/dynamic_graph.hpp>\n#include <stapl/containers/graph/graph.hpp>\n#include <stapl/containers/graph/views/graph_view.hpp>\n#include <stapl/containers/graph/algorithms/hierarchical_view.hpp>\n#include <stapl/views/repeated_view.hpp>\n#include <stapl/views/native_view.hpp>\n#include <stapl/containers/graph/algorithms/create_level.hpp>\n#include <stapl/containers/graph/algorithms/graph_io.hpp>\n#include <stapl/containers/graph/views/property_maps.hpp>\n\n#include <stapl/algorithms/algorithm.hpp>\n#include <stapl/skeletons/utility/tags.hpp>\n#include <boost/random.hpp>\n\nusing namespace stapl;\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Holds the actual points to be clustered.\n//////////////////////////////////////////////////////////////////////\nstruct my_point\n{\n  double m_x, m_y, m_z;\n\n  my_point(double val=0.0)\n    : m_x(val), m_y(val), m_z(val)\n  { }\n\n  void set(double x, double y, double z)\n  {\n    m_x = x;\n    m_y = y;\n    m_z = z;\n  }\n\n  void set(my_point const& other)\n  {\n    m_x = other.m_x;\n    m_y = other.m_y;\n    m_z = other.m_z;\n  }\n\n  void scale(double factor)\n  {\n    m_x *= factor;\n    m_y *= factor;\n    m_z *= factor;\n  }\n\n  void sub(my_point const& other)\n  {\n    m_x -= other.m_x;\n    m_y -= other.m_y;\n    m_z -= other.m_z;\n  }\n\n  void add(my_point const& other)\n  {\n    m_x += other.m_x;\n    m_y += other.m_y;\n    m_z += other.m_z;\n  }\n\n  double get_Magnitude() const\n  {\n    return m_x*m_x + m_y*m_y + m_z*m_z;\n  }\n\n  double get_SquaredEuclideanDistance(my_point const& other) const\n  {\n    return pow(other.m_x - m_x, 2)\n         + pow(other.m_y - m_y, 2)\n         + pow(other.m_z - m_z, 2);\n  }\n\n  double get_EuclideanDistance(my_point const& other) const\n  {\n    return sqrt(get_SquaredEuclideanDistance(other));\n  }\n\n  double get_ManhattanDistance(my_point const& other) const\n  {\n    return std::abs(other.m_x - m_x)\n         + std::abs(other.m_y - m_y)\n         + std::abs(other.m_z - m_z);\n  }\n\n  double get_DotProduct(my_point const& other) const\n  {\n    return other.m_x * m_x\n         + other.m_y * m_y\n         + other.m_z * m_z;\n  }\n\n  double get_CosineSimilarity(my_point const& other) const\n  {\n    return get_DotProduct(other) / (get_Magnitude() * other.get_Magnitude());\n  }\n\n  double get_Distance(my_point const& other) const\n  {\n    return get_SquaredEuclideanDistance(other);\n  }\n\n  void define_type(stapl::typer& t)\n  {\n    t.member(m_x);\n    t.member(m_y);\n    t.member(m_z);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Stores the points in a full cluster, weight, and nearest neighbor.\n//////////////////////////////////////////////////////////////////////\nclass my_vertex_property\n{\nprivate:\n  /// @todo Currently only a single point average of all\n  /// the true points is stored. This is naive. It will later be changed.\n  my_point m_centroid;\n\n  /// The number of points in the cluster.\n  int m_count;\n\n  /// The ID of the closest cluster.\n  size_t m_my_nearest_neighbor;\n\npublic:\n  typedef int property_type;\n\n  my_vertex_property()\n    : m_centroid(0.0), m_count(0), m_my_nearest_neighbor(0)\n  { }\n\n  my_vertex_property(my_point const& other)\n    : m_centroid(other), m_count(1), m_my_nearest_neighbor(0)\n  { }\n\n  my_point get_Centroid() const\n  {\n    return m_centroid;\n  }\n\n  void set_Centroid(double new_x, double new_y, double new_z)\n  {\n    m_centroid.set(new_x, new_y, new_z);\n  }\n\n  void set_Centroid(my_vertex_property const& other)\n  {\n    m_centroid = other.m_centroid;\n    m_count = other.m_count;\n  }\n\n  size_t get_nearest_neighbor() const\n  {\n    return m_my_nearest_neighbor;\n  }\n\n  void set_nearest_neighbor(size_t nearest_neighbor_id)\n  {\n    m_my_nearest_neighbor = nearest_neighbor_id;\n  }\n\n  double get_Distance(const my_vertex_property& other) const\n  {\n    return m_centroid.get_Distance(other.m_centroid);\n  }\n\n  int get_Count() const\n  {\n    return m_count;\n  }\n\n  //////////////////////////////////////////////////////////////////////\n  /// @todo Merges this vertex with another and returns a\n  /// new my_vertex_property. This is currently naive, using centroids.\n  /// @param other The other cluster to be merged.\n  /// @return my_vertex_property The new, merged, cluster.\n  //////////////////////////////////////////////////////////////////////\n  my_vertex_property mergeVertex(const my_vertex_property& other) const\n  {\n    //calculate centroid\n    my_point p1(m_centroid);\n    my_point p2(other.m_centroid);\n\n    p1.scale(m_count);\n    p2.scale(other.m_count);\n\n    p1.add(p2);\n    p1.scale(1.0 / (other.m_count + m_count));\n\n    my_vertex_property vp_out(p1);\n    vp_out.m_count = other.m_count + m_count;\n\n    return vp_out;\n  }\n\n  my_vertex_property operator=(my_vertex_property const& vertex)\n  {\n    m_centroid = vertex.m_centroid;\n    m_count = vertex.m_count;\n    m_my_nearest_neighbor = vertex.m_my_nearest_neighbor;\n    return my_vertex_property(vertex);\n  }\n\n  void define_type(stapl::typer& t)\n  {\n    t.member(m_centroid);\n    t.member(m_count);\n    t.member(m_my_nearest_neighbor);\n  }\n};\n\n\nnamespace stapl\n{\n  STAPL_PROXY_HEADER(my_vertex_property)\n  {\n    STAPL_PROXY_DEFINES(my_vertex_property)\n    STAPL_PROXY_METHOD_RETURN(get_Centroid, my_point)\n    STAPL_PROXY_METHOD(set_Centroid, double, double, double)\n    STAPL_PROXY_METHOD(set_Centroid, my_vertex_property)\n    STAPL_PROXY_METHOD_RETURN(get_nearest_neighbor, size_t)\n    STAPL_PROXY_METHOD(set_nearest_neighbor, size_t)\n    STAPL_PROXY_METHOD_RETURN(get_Distance, my_vertex_property&, double)\n    STAPL_PROXY_METHOD_RETURN(get_Count, int)\n    STAPL_PROXY_METHOD_RETURN(mergeVertex, my_vertex_property,\n      my_vertex_property)\n    STAPL_PROXY_METHOD_RETURN(operator=, my_vertex_property,\n      my_vertex_property)\n    STAPL_PROXY_METHOD(define_type, stapl::typer)\n  };\n}\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Work function to merge vertices.\n//////////////////////////////////////////////////////////////////////\nstruct functor_merge_vertex\n{\n  typedef my_vertex_property result_type;\n\n  result_type operator()(my_vertex_property& vertex1,\n                         my_vertex_property const& vertex2)\n  {\n    return vertex1.mergeVertex(vertex2);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Creates pairs of the vertices to be merged in the next level.\n//////////////////////////////////////////////////////////////////////\nstruct make_node_pairs\n{\n  typedef std::pair<size_t, double> result_type;\n\n  my_vertex_property m_vertex_prop;\n  size_t m_vertex_descriptor;\n\n  make_node_pairs(my_vertex_property clust_prop, size_t vertex_id)\n    : m_vertex_prop(clust_prop), m_vertex_descriptor(vertex_id)\n  { }\n\n  template<typename GraphNode>\n  result_type operator()(GraphNode element) const\n  {\n    if (element.descriptor() != m_vertex_descriptor) {\n      double distance =\n         m_vertex_prop.get_Distance(element.property().property);\n      return std::make_pair(element.descriptor(), distance);\n    }\n    return std::make_pair(0, 0.0);\n  }\n\n  void define_type(typer &t)\n  {\n    t.member(m_vertex_prop);\n    t.member(m_vertex_descriptor);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Reduces two single element pairs to the smaller value.\n/// Multi-element pairs are preferred.\n//////////////////////////////////////////////////////////////////////\nstruct pick_smaller_node\n{\n  typedef std::pair<size_t, double> result_type;\n\n  result_type operator()(result_type el1, result_type el2) const\n  {\n    const result_type null_value = result_type(0, 0.0);\n\n    if (el1 != null_value && el2 != null_value) {\n      if (el1.second < el2.second) {\n        return el1;\n      } else {\n        return el2;\n      }\n    } else if (el1 == null_value) {\n      return el2;\n    } else {\n      return el1;\n    }\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Work function to determine the nearest neighbors\n/// for all of the clusters.\n//////////////////////////////////////////////////////////////////////\nstruct find_nearest_node\n{\n  typedef void result_type;\n\n  find_nearest_node()\n  { }\n\n  template<typename Node, typename GraphView>\n  result_type operator()(Node node, const GraphView g_view)\n  {\n    make_node_pairs pairs_wf(\n            node.property().property, node.descriptor());\n    size_t mynearestnode =\n        (nc_map_reduce(pairs_wf, pick_smaller_node(), g_view)).first;\n    node.property().property.set_nearest_neighbor(mynearestnode);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Gives an empty property. This is needed for create_level.\n//////////////////////////////////////////////////////////////////////\nstruct empty_functor\n{\n  typedef int value_type;\n\n  template<class Graph>\n  properties::no_property operator()(Graph& g, size_t lvl) const\n  {\n    return properties::no_property();\n  }\n\n  template<class EdgePropertyType>\n  properties::no_property operator()(EdgePropertyType& p,\n                                     properties::no_property const& ref) const\n  {\n    return properties::no_property();\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Creates a property map of the graph, indicating which vertices are\n/// to be clustered with which other vertices.\n//////////////////////////////////////////////////////////////////////\nstruct create_property_map\n{\n  typedef void result_type;\n\n  create_property_map()\n  { }\n\n  template<typename Vertex, typename PropMap, typename GraphView>\n  result_type operator()\n    (Vertex element, PropMap& property_map, GraphView whole_graph)\n  {\n    size_t element_descriptor = element.descriptor();\n    size_t element_nearest_node =\n      element.property().property.get_nearest_neighbor();\n    if (whole_graph[element_nearest_node].property()\n         .property.get_nearest_neighbor() == element_descriptor) {\n      // Nodes are to be clustered\n      if (element_descriptor < element_nearest_node) {\n        property_map[element_descriptor] = element_descriptor;\n      } else {\n        property_map[element_descriptor] = element_nearest_node;\n      }\n    } else {\n      // Node is not to be clustered\n      property_map[element_descriptor] = element_descriptor;\n    }\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Used to fill the graph used in @ref agglomerative_clustering\n/// with starting points.\n//////////////////////////////////////////////////////////////////////\nstruct fill_graph\n{\n  typedef void result_type;\n\n  template<typename Vertex, typename Point>\n  void operator()(Vertex element, Point point) {\n    element.property() = my_vertex_property(point);\n  }\n};\n\n\n//////////////////////////////////////////////////////////////////////\n/// @brief Wrapper class for agglomerative clustering algorithm\n/// Class needed to store so as to contain typedef for return_type\n//////////////////////////////////////////////////////////////////////\nclass agglomerative_clustering\n{\nprivate:\n  typedef stapl::static_array<size_t> array_type;\n  typedef array_view<array_type> array_vw;\n  typedef graph<stapl::DIRECTED, stapl::MULTIEDGES,\n    super_vertex_property<my_vertex_property>,\n    super_edge_property<properties::no_property> > graph_type;\n  typedef graph_view<graph_type> graph_vw;\n  typedef graph_external_property_map<graph_vw, size_t, array_vw>\n    graph_ext_prop_map;\n\npublic:\n  typedef std::vector<graph_vw> return_type;\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Agglomeratively clusters an array of points.\n  /// @param inputView The view of the graph to be clustered.\n  //////////////////////////////////////////////////////////////////////\n  template<typename View>\n  return_type cluster(View inputView) {\n    graph_type* g = new graph_type(inputView.size());\n    graph_vw g_vw(g);\n\n    map_func(fill_graph(), g_vw, inputView);\n\n    std::vector<graph_vw> g_level_vw;\n    g_level_vw.push_back(g_vw);\n\n    while (g_vw.size() > 1)\n    {\n      //Generates the array of nearest neighbors\n      nc_map_func(find_nearest_node(), g_vw, make_repeat_view(g_vw));\n\n      array_type group_array(g_vw.size());\n      array_vw group_array_vw(group_array);\n      nc_map_func(create_property_map(), g_vw, make_repeat_view(group_array_vw),\n        make_repeat_view(g_vw));\n\n      graph_ext_prop_map group_id_prop_map(g_vw, group_array_vw);\n\n      g_level_vw.push_back(create_level(g_vw, group_id_prop_map,\n        functor_merge_vertex(), empty_functor()));\n\n      g_vw = g_level_vw.back();\n    }\n    return g_level_vw;\n  }\n\n  #ifdef SHOW_RESULTS\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Converts a point to its RGB hex representation.\n  //////////////////////////////////////////////////////////////////////\n  std::string ConvertPointToRGBColor(my_point const& point) {\n    char b[10];\n    sprintf(&b[0], \"%02X\", (unsigned char)(point.m_x * 255));\n    sprintf(&b[2], \"%02X\", (unsigned char)(point.m_y * 255));\n    sprintf(&b[4], \"%02X\", (unsigned char)(point.m_z * 255));\n    return std::string(b);\n  }\n\n  //////////////////////////////////////////////////////////////////////\n  /// @brief Writes the graph to a dot file (colors points using RGB)\n  /// @todo Make more efficient version that does not redundantly build strings\n  /// during the creation of dot file.\n  //////////////////////////////////////////////////////////////////////\n  template<typename Clusters>\n  void printgraph2dotfile(Clusters clusters, char const* file=\"cluster.dot\")\n  {\n    std::map<size_t, std::map<size_t, std::string> > mymap;\n\n    do_once([&clusters, &mymap, file, this](void) {\n      for (size_t lvl=0; lvl<clusters.size(); ++lvl) {\n        for (size_t n=0; n<clusters[lvl].size(); ++n) {\n          auto v = clusters[lvl][n];\n          int v_id = v.descriptor();\n          if (v.property().children.size() == 1) {\n            mymap[lvl][v_id] =  mymap[lvl-1][v.property().children[0]];\n            continue;\n          }\n          std::stringstream ss;\n          ss << \"subgraph cluster_\" << lvl << \"_\" << v_id << \" {\\n\";\n\n          for (size_t k=0; k<v.property().children.size(); ++k) {\n            ss << mymap[lvl-1][v.property().children[k]] << \"\\n\";\n          }\n          if (lvl != 0) {\n            ss << \"label = \\\"\";\n          } else {\n            ss << \"\\\"[\" << v_id<< \"]\\\\n\";\n          }\n          my_point p = v.property().property.get_Centroid();\n          ss << p.m_x << \"\\\\n\" << p.m_y << \"\\\\n\" << p.m_z << \"\\\";\\n\";\n          ss << \"style=\\\"filled\\\";fillcolor=\\\"#\";\n          ss << ConvertPointToRGBColor(p) << \"\\\";\\n}\\n\";\n\n          mymap[lvl][v_id] = ss.str();\n        }\n      }\n      std::ofstream ofile;\n      ofile.open(file, std::fstream::out);\n      ofile << \"digraph pGraph {\\n\";\n      ofile << mymap[clusters.size()-1][0];\n      ofile << \"}\\n\";\n      ofile.close();\n    });\n    rmi_fence();\n  }\n  #endif\n};\n\n\n\n#endif /* STAPL_BENCHMARK_LONESTAR_AGGLOMERATIVECLUSTERING_HPP */\n", "meta": {"hexsha": "b2d3c147b07a09ea5c676faf9ff1cda78defe2fa", "size": 15885, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stapl_release/benchmarks/lonestar/agglomerativeclustering/agglomerativeclustering.hpp", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stapl_release/benchmarks/lonestar/agglomerativeclustering/agglomerativeclustering.hpp", "max_issues_repo_name": "parasol-ppl/PPL_utils", "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stapl_release/benchmarks/lonestar/agglomerativeclustering/agglomerativeclustering.hpp", "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8818181818, "max_line_length": 80, "alphanum_fraction": 0.5962858042, "num_tokens": 3659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.709019146082187, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.43348152463506145}}
{"text": "// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef NETKET_NDM_SPIN_PHASE_HPP\n#define NETKET_NDM_SPIN_PHASE_HPP\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n#include \"Machine/rbm_spin.hpp\"\n#include \"Utils/all_utils.hpp\"\n#include \"Utils/lookup.hpp\"\n#include \"abstract_density_matrix.hpp\"\n\nnamespace netket {\n\n/** Neural Density Matrix machine class with spin 1/2 hidden units.\nThis version has real-valued weights and two NDMs parameterizing phase and\namplitude\n *\n */\nclass NdmSpinPhase : public AbstractDensityMatrix {\n  // number of visible units\n  int nv_;\n\n  // number of hidden units\n  int nh_;\n\n  // number of ancillary units\n  int na_;\n\n  // number of parameters\n  int npar_;\n\n  // visible units bias\n  RealVectorType b1_;\n  RealVectorType b2_;\n\n  // hidden units bias\n  RealVectorType h1_;\n  RealVectorType h2_;\n\n  // ancillary units bias\n  RealVectorType d1_;\n\n  // hidden unit weights\n  RealMatrixType W1_;\n  RealMatrixType W2_;\n\n  // ancillary unit weights\n  RealMatrixType U1_;\n  RealMatrixType U2_;\n\n  // Caches\n  RealVectorType thetas_r1_;\n  RealVectorType thetas_r2_;\n  RealVectorType thetas_c1_;\n  RealVectorType thetas_c2_;\n  RealVectorType lnthetas_r1_;\n  RealVectorType lnthetas_r2_;\n  RealVectorType lnthetas_c1_;\n  RealVectorType lnthetas_c2_;\n  RealVectorType thetasnew_r1_;\n  RealVectorType thetasnew_r2_;\n  RealVectorType thetasnew_c1_;\n  RealVectorType thetasnew_c2_;\n  RealVectorType lnthetasnew_r1_;\n  RealVectorType lnthetasnew_r2_;\n  RealVectorType lnthetasnew_c1_;\n  RealVectorType lnthetasnew_c2_;\n\n  RealVectorType thetas_a1_;\n  RealVectorType thetas_a2_;\n  RealVectorType thetasnew_a1_;\n  RealVectorType thetasnew_a2_;\n  VectorType pi_;\n  VectorType lnpi_;\n  VectorType lnpinew_;\n\n  bool useb_;\n  bool useh_;\n  bool used_;\n\n  const Complex I_;\n\n public:\n  explicit NdmSpinPhase(std::shared_ptr<const AbstractHilbert> hilbert,\n                        int nhidden = 0, int nancilla = 0, int alpha = 0,\n                        int beta = 0, bool useb = true, bool useh = true,\n                        bool used = true)\n      : AbstractDensityMatrix(hilbert),\n        nv_(hilbert->Size()),\n        useb_(useb),\n        useh_(useh),\n        used_(used),\n        I_(0, 1) {\n    nh_ = std::max(nhidden, alpha * nv_);\n    na_ = std::max(nancilla, beta * nv_);\n    Init();\n  }\n\n  void Init() {\n    W1_.resize(nv_, nh_);\n    U1_.resize(nv_, na_);\n    b1_.resize(nv_);\n    h1_.resize(nh_);\n    d1_.resize(na_);\n\n    W2_.resize(nv_, nh_);\n    U2_.resize(nv_, na_);\n    b2_.resize(nv_);\n    h2_.resize(nh_);\n\n    thetas_r1_.resize(nh_);\n    thetas_r2_.resize(nh_);\n    thetas_c1_.resize(nh_);\n    thetas_c2_.resize(nh_);\n\n    lnthetas_r1_.resize(nh_);\n    lnthetas_r2_.resize(nh_);\n    lnthetas_c1_.resize(nh_);\n    lnthetas_c2_.resize(nh_);\n\n    thetasnew_r1_.resize(nh_);\n    thetasnew_r2_.resize(nh_);\n    thetasnew_c1_.resize(nh_);\n    thetasnew_c2_.resize(nh_);\n\n    lnthetasnew_r1_.resize(nh_);\n    lnthetasnew_r2_.resize(nh_);\n    lnthetasnew_c1_.resize(nh_);\n    lnthetasnew_c2_.resize(nh_);\n\n    thetas_a1_.resize(na_);\n    thetas_a2_.resize(na_);\n    thetasnew_a1_.resize(na_);\n    thetasnew_a2_.resize(na_);\n    pi_.resize(na_);\n    lnpi_.resize(na_);\n    lnpinew_.resize(na_);\n\n    npar_ = 2 * nv_ * (nh_ + na_);\n\n    if (useb_) {\n      npar_ += 2 * nv_;\n    } else {\n      b1_.setZero();\n      b2_.setZero();\n    }\n\n    if (useh_) {\n      npar_ += 2 * nh_;\n    } else {\n      h1_.setZero();\n      h2_.setZero();\n    }\n\n    if (used_) {\n      npar_ += na_;\n    } else {\n      d1_.setZero();\n    }\n\n    InfoMessage() << \"Phase NDM Initizialized with nvisible = \" << nv_\n                  << \" and nhidden  = \" << nh_ << \" and nancilla = \" << na_\n                  << std::endl;\n    InfoMessage() << \"Using visible   bias = \" << useb_ << std::endl;\n    InfoMessage() << \"Using hidden    bias  = \" << useh_ << std::endl;\n    InfoMessage() << \"Using ancillary bias  = \" << used_ << std::endl;\n  }\n\n  int Nvisible() const override { return nv_; }\n\n  int Nhidden() const { return nh_; }\n\n  int Nancilla() const { return na_; }\n\n  int Npar() const override { return npar_; }\n\n  void InitRandomPars(int seed, double sigma) override {\n    RealVectorType par(npar_);\n\n    netket::RandomGaussian(par, seed, sigma);\n\n    SetParameters(VectorType(par));\n  }\n\n  void InitLookup(VisibleConstType v, LookupType &lt) override {\n    if (lt.VectorSize() == 0) {\n      lt.AddVector(h1_.size());  // row 1\n      lt.AddVector(h2_.size());  // row 2\n      lt.AddVector(h1_.size());  // col 1\n      lt.AddVector(h2_.size());  // col 2\n      lt.AddVector(d1_.size());  // ancilla modulus\n      lt.AddVector(d1_.size());  // ancilla phase\n    }\n    if (lt.V(0).size() != h1_.size()) {\n      lt.V(0).resize(h1_.size());\n    }\n    if (lt.V(1).size() != h2_.size()) {\n      lt.V(1).resize(h2_.size());\n    }\n    if (lt.V(2).size() != h1_.size()) {\n      lt.V(2).resize(h1_.size());\n    }\n    if (lt.V(3).size() != h2_.size()) {\n      lt.V(3).resize(h2_.size());\n    }\n    if (lt.V(4).size() != d1_.size()) {\n      lt.V(4).resize(d1_.size());\n    }\n    if (lt.V(5).size() != d1_.size()) {\n      lt.V(5).resize(d1_.size());\n    }\n\n    VisibleConstType vr = v.head(GetHilbertPhysical().Size());\n    VisibleConstType vc = v.tail(GetHilbertPhysical().Size());\n\n    lt.V(0) = (W1_.transpose() * vr + h1_);\n    lt.V(1) = (W2_.transpose() * vr + h2_);\n    lt.V(2) = (W1_.transpose() * vc + h1_);\n    lt.V(3) = (W2_.transpose() * vc + h2_);\n\n    lt.V(4) = (0.5 * U1_.transpose() * (vr + vc) + d1_);\n    lt.V(5) = (0.5 * U2_.transpose() * (vr - vc));\n  }\n\n  void UpdateLookup(VisibleConstType v, const std::vector<int> &tochange,\n                    const std::vector<double> &newconf,\n                    LookupType &lt) override {\n    VisibleConstType vr = v.head(GetHilbertPhysical().Size());\n    VisibleConstType vc = v.tail(GetHilbertPhysical().Size());\n\n    if (tochange.size() != 0) {\n      for (std::size_t s = 0; s < tochange.size(); s++) {\n        const int sf = tochange[s];\n        if (sf < Nvisible()) {\n          lt.V(0) += W1_.row(sf) * (newconf[s] - vr(sf));\n          lt.V(1) += W2_.row(sf) * (newconf[s] - vr(sf));\n\n          lt.V(4) += 0.5 * U1_.row(sf) * (newconf[s] - vr(sf));\n          lt.V(5) += 0.5 * U2_.row(sf) * (newconf[s] - vr(sf));\n        } else {\n          const int sfc = sf - Nvisible();\n          lt.V(2) += W1_.row(sfc) * (newconf[s] - vc(sfc));\n          lt.V(3) += W2_.row(sfc) * (newconf[s] - vc(sfc));\n\n          lt.V(4) += 0.5 * U1_.row(sfc) * (newconf[s] - vc(sfc));\n          lt.V(5) -= 0.5 * U2_.row(sfc) * (newconf[s] - vc(sfc));\n        }\n      }\n    }\n  }\n\n  VectorType DerLog(VisibleConstType v) override {\n    LookupType ltnew;\n    InitLookup(v, ltnew);\n    return DerLog(v, ltnew);\n  }\n\n  VectorType DerLog(VisibleConstType v, const LookupType &lt) override {\n    VisibleConstType vr = v.head(GetHilbertPhysical().Size());\n    VisibleConstType vc = v.tail(GetHilbertPhysical().Size());\n\n    VectorType der(npar_);\n\n    const int impar = (npar_ + na_ * used_) / 2;\n\n    if (useb_) {\n      der.head(nv_) = 0.5 * (vr + vc);\n      der.segment(impar, nv_) = I_ * 0.5 * (vr - vc);\n    }\n\n    RbmSpin::tanh(lt.V(0).real(), lnthetas_r1_);\n    RbmSpin::tanh(lt.V(1).real(), lnthetas_r2_);\n    RbmSpin::tanh(lt.V(2).real(), lnthetas_c1_);\n    RbmSpin::tanh(lt.V(3).real(), lnthetas_c2_);\n\n    if (useh_) {\n      der.segment(useb_ * nv_, nh_) = 0.5 * (lnthetas_r1_ + lnthetas_c1_);\n      der.segment(impar + useb_ * nv_, nh_) =\n          I_ * 0.5 * (lnthetas_r2_ - lnthetas_c2_);\n    }\n\n    thetas_a1_ = 0.5 * U1_.transpose() * (vr + vc) + d1_;\n    thetas_a2_ = 0.5 * U2_.transpose() * (vr - vc);\n    RbmSpin::tanh(lt.V(4).real() + I_ * lt.V(5).real(), lnpi_);\n\n    if (used_) {\n      der.segment(useb_ * nv_ + useh_ * nh_, na_) = lnpi_;\n    }\n\n    const int initw_1 = nv_ * useb_ + nh_ * useh_ + na_ * used_;\n    const int initw_2 = nv_ * useb_ + nh_ * useh_;\n\n    MatrixType wder =\n        0.5 * (vr * lnthetas_r1_.transpose() + vc * lnthetas_c1_.transpose());\n    der.segment(initw_1, nv_ * nh_) =\n        Eigen::Map<VectorType>(wder.data(), nv_ * nh_);\n\n    wder = 0.5 * I_ *\n           (vr * lnthetas_r2_.transpose() - vc * lnthetas_c2_.transpose());\n    der.segment(impar + initw_2, nv_ * nh_) =\n        Eigen::Map<VectorType>(wder.data(), nv_ * nh_);\n\n    const int initu_1 = initw_1 + nv_ * nh_;\n    const int initu_2 = initw_2 + nv_ * nh_;\n\n    MatrixType uder = 0.5 * (vr + vc) * lnpi_.transpose();\n    der.segment(initu_1, nv_ * na_) =\n        Eigen::Map<VectorType>(uder.data(), nv_ * na_);\n\n    uder = 0.5 * I_ * (vr - vc) * lnpi_.transpose();\n    der.segment(impar + initu_2, nv_ * na_) =\n        Eigen::Map<VectorType>(uder.data(), nv_ * na_);\n\n    return der;\n  }\n\n  VectorType GetParameters() override {\n    VectorType pars(npar_);\n\n    const int impar = (npar_ + na_ * used_) / 2;\n\n    if (useb_) {\n      pars.head(nv_) = b1_;\n      pars.segment(impar, nv_) = b2_;\n    }\n\n    if (useh_) {\n      pars.segment(nv_ * useb_, nh_) = h1_;\n      pars.segment(impar + nv_ * useb_, nh_) = h2_;\n    }\n\n    if (used_) {\n      pars.segment(useb_ * nv_ + useh_ * nh_, na_) = d1_;\n    }\n\n    const int initw_1 = nv_ * useb_ + nh_ * useh_ + na_ * used_;\n    const int initw_2 = nv_ * useb_ + nh_ * useh_;\n\n    pars.segment(initw_1, nv_ * nh_) =\n        Eigen::Map<RealVectorType>(W1_.data(), nv_ * nh_);\n    pars.segment(impar + initw_2, nv_ * nh_) =\n        Eigen::Map<RealVectorType>(W2_.data(), nv_ * nh_);\n\n    const int initu_1 = initw_1 + nv_ * nh_;\n    const int initu_2 = initw_2 + nv_ * nh_;\n\n    pars.segment(initu_1, nv_ * na_) =\n        Eigen::Map<RealVectorType>(U1_.data(), nv_ * na_);\n    pars.segment(impar + initu_2, nv_ * na_) =\n        Eigen::Map<RealVectorType>(U2_.data(), nv_ * na_);\n\n    return pars;\n  }\n\n  void SetParameters(VectorConstRefType pars) override {\n    const int impar = (npar_ + na_ * used_) / 2;\n\n    if (useb_) {\n      b1_ = pars.head(nv_).real();\n      b2_ = pars.segment(impar, nv_).real();\n    }\n\n    if (useh_) {\n      h1_ = pars.segment(useb_ * nv_, nh_).real();\n      h2_ = pars.segment(impar + useb_ * nv_, nh_).real();\n    }\n\n    if (used_) {\n      d1_ = pars.segment(useb_ * nv_ + useh_ * nh_, na_).real();\n    }\n\n    const int initw_1 = nv_ * useb_ + nh_ * useh_ + na_ * used_;\n    const int initw_2 = nv_ * useb_ + nh_ * useh_;\n\n    VectorType Wpars = pars.segment(initw_1, nv_ * nh_);\n    W1_ = Eigen::Map<MatrixType>(Wpars.data(), nv_, nh_).real();\n\n    Wpars = pars.segment(impar + initw_2, nv_ * nh_);\n    W2_ = Eigen::Map<MatrixType>(Wpars.data(), nv_, nh_).real();\n\n    const int initu_1 = initw_1 + nv_ * nh_;\n    const int initu_2 = initw_2 + nv_ * nh_;\n\n    VectorType Upars = pars.segment(initu_1, nv_ * na_);\n    U1_ = Eigen::Map<MatrixType>(Upars.data(), nv_, na_).real();\n\n    Upars = pars.segment(impar + initu_2, nv_ * na_);\n    U2_ = Eigen::Map<MatrixType>(Upars.data(), nv_, na_).real();\n  }\n\n  // Value of the logarithm of the wave-function\n  Complex LogVal(VisibleConstType v) override {\n    VisibleConstType vr = v.head(GetHilbertPhysical().Size());\n    VisibleConstType vc = v.tail(GetHilbertPhysical().Size());\n\n    RbmSpin::lncosh(W1_.transpose() * vr + h1_, lnthetas_r1_);\n    RbmSpin::lncosh(W2_.transpose() * vr + h2_, lnthetas_r2_);\n    RbmSpin::lncosh(W1_.transpose() * vc + h1_, lnthetas_c1_);\n    RbmSpin::lncosh(W2_.transpose() * vc + h2_, lnthetas_c2_);\n\n    thetas_a1_ = 0.5 * U1_.transpose() * (vr + vc) + d1_;\n    thetas_a2_ = 0.5 * U2_.transpose() * (vr - vc);\n    RbmSpin::lncosh(thetas_a1_ + I_ * thetas_a2_, lnpi_);\n\n    auto gamma_1 =\n        0.5 * (lnthetas_r1_.sum() + lnthetas_c1_.sum() + (vr + vc).dot(b1_));\n\n    auto gamma_2 =\n        0.5 * (lnthetas_r2_.sum() - lnthetas_c2_.sum() + (vr - vc).dot(b2_));\n\n    return gamma_1 + I_ * gamma_2 + lnpi_.sum();\n  }\n\n  // Value of the logarithm of the wave-function\n  // using pre-computed look-up tables for efficiency\n  Complex LogVal(VisibleConstType v, const LookupType &lt) override {\n    VisibleConstType vr = v.head(GetHilbertPhysical().Size());\n    VisibleConstType vc = v.tail(GetHilbertPhysical().Size());\n\n    RbmSpin::lncosh(lt.V(0).real(), lnthetas_r1_);\n    RbmSpin::lncosh(lt.V(1).real(), lnthetas_r2_);\n    RbmSpin::lncosh(lt.V(2).real(), lnthetas_c1_);\n    RbmSpin::lncosh(lt.V(3).real(), lnthetas_c2_);\n    RbmSpin::lncosh(lt.V(4).real() + I_ * lt.V(5).real(), lnpi_);\n\n    auto gamma_1 =\n        0.5 * (lnthetas_r1_.sum() + lnthetas_c1_.sum() + (vr + vc).dot(b1_));\n    auto gamma_2 =\n        0.5 * (lnthetas_r2_.sum() - lnthetas_c2_.sum() + (vr - vc).dot(b2_));\n\n    return gamma_1 + I_ * gamma_2 + lnpi_.sum();\n  }\n\n  // Difference between logarithms of values, when one or more visible variables\n  // are being flipped\n  VectorType LogValDiff(\n      VisibleConstType v, const std::vector<std::vector<int>> &tochange,\n      const std::vector<std::vector<double>> &newconf) override {\n    VisibleConstType vr = v.head(GetHilbertPhysical().Size());\n    VisibleConstType vc = v.tail(GetHilbertPhysical().Size());\n\n    const std::size_t nconn = tochange.size();\n\n    thetas_r1_ = (W1_.transpose() * vr + h1_);\n    thetas_r2_ = (W2_.transpose() * vr + h2_);\n    thetas_c1_ = (W1_.transpose() * vc + h1_);\n    thetas_c2_ = (W2_.transpose() * vc + h2_);\n\n    RbmSpin::lncosh(thetas_r1_, lnthetas_r1_);\n    RbmSpin::lncosh(thetas_r2_, lnthetas_r2_);\n    RbmSpin::lncosh(thetas_c1_, lnthetas_c1_);\n    RbmSpin::lncosh(thetas_c2_, lnthetas_c2_);\n\n    thetas_a1_ = 0.5 * U1_.transpose() * (vr + vc) + d1_;\n    thetas_a2_ = 0.5 * U2_.transpose() * (vr - vc);\n    RbmSpin::lncosh(thetas_a1_ + I_ * thetas_a2_, lnpi_);\n\n    Complex logtsum = 0.5 * (lnthetas_r1_.sum() + lnthetas_c1_.sum()) +\n                      0.5 * I_ * (lnthetas_r2_.sum() - lnthetas_c2_.sum()) +\n                      lnpi_.sum();\n\n    VectorType logvaldiffs = VectorType::Zero(nconn);\n    for (std::size_t k = 0; k < nconn; k++) {\n      if (tochange[k].size() != 0) {\n        thetasnew_r1_ = thetas_r1_;\n        thetasnew_r2_ = thetas_r2_;\n        thetasnew_c1_ = thetas_c1_;\n        thetasnew_c2_ = thetas_c2_;\n\n        thetasnew_a1_ = thetas_a1_;\n        thetasnew_a2_ = thetas_a2_;\n\n        for (std::size_t s = 0; s < tochange[k].size(); s++) {\n          const int sf = tochange[k][s];\n\n          if (sf < Nvisible()) {\n            logvaldiffs(k) += 0.5 * b1_(sf) * (newconf[k][s] - vr(sf));\n            logvaldiffs(k) += 0.5 * I_ * b2_(sf) * (newconf[k][s] - vr(sf));\n\n            thetasnew_r1_ += W1_.row(sf) * (newconf[k][s] - vr(sf));\n            thetasnew_r2_ += W2_.row(sf) * (newconf[k][s] - vr(sf));\n            thetasnew_a1_ += 0.5 * U1_.row(sf) * (newconf[k][s] - vr(sf));\n            thetasnew_a2_ += 0.5 * U2_.row(sf) * (newconf[k][s] - vr(sf));\n          } else {\n            const int sfc = tochange[k][s] - Nvisible();\n            logvaldiffs(k) += 0.5 * b1_(sfc) * (newconf[k][s] - vc(sfc));\n            logvaldiffs(k) -= 0.5 * I_ * b2_(sfc) * (newconf[k][s] - vc(sfc));\n\n            thetasnew_c1_ += W1_.row(sfc) * (newconf[k][s] - vc(sfc));\n            thetasnew_c2_ += W2_.row(sfc) * (newconf[k][s] - vc(sfc));\n            thetasnew_a1_ += 0.5 * U1_.row(sfc) * (newconf[k][s] - vc(sfc));\n            thetasnew_a2_ -= 0.5 * U2_.row(sfc) * (newconf[k][s] - vc(sfc));\n          }\n        }\n        RbmSpin::lncosh(thetasnew_r1_, lnthetasnew_r1_);\n        RbmSpin::lncosh(thetasnew_r2_, lnthetasnew_r2_);\n        RbmSpin::lncosh(thetasnew_c1_, lnthetasnew_c1_);\n        RbmSpin::lncosh(thetasnew_c2_, lnthetasnew_c2_);\n        RbmSpin::lncosh(thetasnew_a1_ + I_ * thetasnew_a2_, lnpinew_);\n\n        logvaldiffs(k) +=\n            0.5 * (lnthetasnew_r1_.sum() + lnthetasnew_c1_.sum()) +\n            0.5 * I_ * (lnthetasnew_r2_.sum() - lnthetasnew_c2_.sum()) +\n            lnpinew_.sum() - logtsum;\n      }\n    }\n    return logvaldiffs;\n  }\n\n  // Difference between logarithms of values, when one or more visible variables\n  // are being flipped Version using pre-computed look-up tables for efficiency\n  // on a small number of spin flips\n  Complex LogValDiff(VisibleConstType v, const std::vector<int> &tochange,\n                     const std::vector<double> &newconf,\n                     const LookupType &lt) override {\n    VisibleConstType vr = v.head(GetHilbertPhysical().Size());\n    VisibleConstType vc = v.tail(GetHilbertPhysical().Size());\n\n    Complex logvaldiff = 0.;\n\n    if (tochange.size() != 0) {\n      RbmSpin::lncosh(lt.V(0).real(), lnthetas_r1_);\n      RbmSpin::lncosh(lt.V(1).real(), lnthetas_r2_);\n      RbmSpin::lncosh(lt.V(2).real(), lnthetas_c1_);\n      RbmSpin::lncosh(lt.V(3).real(), lnthetas_c2_);\n      RbmSpin::lncosh(lt.V(4).real() + I_ * lt.V(5).real(), lnpi_);\n\n      thetasnew_r1_ = lt.V(0).real();\n      thetasnew_r2_ = lt.V(1).real();\n      thetasnew_c1_ = lt.V(2).real();\n      thetasnew_c2_ = lt.V(3).real();\n      thetasnew_a1_ = lt.V(4).real();\n      thetasnew_a2_ = lt.V(5).real();\n\n      for (std::size_t s = 0; s < tochange.size(); s++) {\n        const int sf = tochange[s];\n\n        if (sf < Nvisible()) {\n          logvaldiff += 0.5 * b1_(sf) * (newconf[s] - vr(sf));\n          logvaldiff += 0.5 * I_ * b2_(sf) * (newconf[s] - vr(sf));\n\n          thetasnew_r1_ += W1_.row(sf) * (newconf[s] - vr(sf));\n          thetasnew_r2_ += W2_.row(sf) * (newconf[s] - vr(sf));\n          thetasnew_a1_ += 0.5 * U1_.row(sf) * (newconf[s] - vr(sf));\n          thetasnew_a2_ += 0.5 * U2_.row(sf) * (newconf[s] - vr(sf));\n        } else {\n          const int sfc = tochange[s] - Nvisible();\n          logvaldiff += 0.5 * b1_(sfc) * (newconf[s] - vc(sfc));\n          logvaldiff -= 0.5 * I_ * b2_(sfc) * (newconf[s] - vc(sfc));\n\n          thetasnew_c1_ += W1_.row(sfc) * (newconf[s] - vc(sfc));\n          thetasnew_c2_ += W2_.row(sfc) * (newconf[s] - vc(sfc));\n          thetasnew_a1_ += 0.5 * U1_.row(sfc) * (newconf[s] - vc(sfc));\n          thetasnew_a2_ -= 0.5 * U2_.row(sfc) * (newconf[s] - vc(sfc));\n        }\n      }\n\n      RbmSpin::lncosh(thetasnew_r1_, lnthetasnew_r1_);\n      RbmSpin::lncosh(thetasnew_r2_, lnthetasnew_r2_);\n      RbmSpin::lncosh(thetasnew_c1_, lnthetasnew_c1_);\n      RbmSpin::lncosh(thetasnew_c2_, lnthetasnew_c2_);\n      RbmSpin::lncosh(thetasnew_a1_ + I_ * thetasnew_a2_, lnpinew_);\n\n      logvaldiff += 0.5 * (lnthetasnew_r1_.sum() + lnthetasnew_c1_.sum());\n      logvaldiff -= 0.5 * (lnthetas_r1_.sum() + lnthetas_c1_.sum());\n      logvaldiff += 0.5 * I_ * (lnthetasnew_r2_.sum() - lnthetasnew_c2_.sum());\n      logvaldiff -= 0.5 * I_ * (lnthetas_r2_.sum() - lnthetas_c2_.sum());\n      logvaldiff += (lnpinew_.sum() - lnpi_.sum());\n    }\n    return logvaldiff;\n  }\n\n  inline static double lncosh(double x) {\n    const double xp = std::abs(x);\n    if (xp <= 12.) {\n      return std::log(std::cosh(xp));\n    } else {\n      const static double log2v = std::log(2.);\n      return xp - log2v;\n    }\n  }\n\n  void Save(const std::string &filename) const override {\n    json state;\n    state[\"Name\"] = \"NdmSpinPhase\";\n    state[\"Nvisible\"] = nv_;\n    state[\"Nhidden\"] = nh_;\n    state[\"Nancilla\"] = na_;\n    state[\"UseVisibleBias\"] = useb_;\n    state[\"UseHiddenBias\"] = useh_;\n    state[\"UseAncillaBias\"] = used_;\n    state[\"b1\"] = b1_;\n    state[\"h1\"] = h1_;\n    state[\"d1\"] = d1_;\n    state[\"W1\"] = W1_;\n    state[\"U1\"] = U1_;\n\n    state[\"b2\"] = b2_;\n    state[\"h2\"] = h2_;\n    state[\"W2\"] = W2_;\n    state[\"U2\"] = U2_;\n    WriteJsonToFile(state, filename);\n  }\n\n  void Load(const std::string &filename) override {\n    auto pars = ReadJsonFromFile(filename);\n    std::string name = FieldVal<std::string>(pars, \"Name\");\n    if (name != \"NdmSpinPhase\") {\n      throw InvalidInputError(\n          \"Error while constructing RbmSpinPhase from input parameters\");\n    }\n\n    if (FieldExists(pars, \"Nvisible\")) {\n      nv_ = FieldVal<int>(pars, \"Nvisible\");\n    }\n    if (nv_ != GetHilbertPhysical().Size()) {\n      throw InvalidInputError(\n          \"Number of visible units is incompatible with given \"\n          \"Hilbert space\");\n    }\n\n    if (FieldExists(pars, \"Nhidden\")) {\n      nh_ = FieldVal<int>(pars, \"Nhidden\");\n    } else {\n      nh_ = nv_ * double(FieldVal<double>(pars, \"Alpha\"));\n    }\n\n    if (FieldExists(pars, \"Nancilla\")) {\n      na_ = FieldVal<int>(pars, \"Nancilla\");\n    } else {\n      na_ = nv_ * double(FieldVal<double>(pars, \"Beta\"));\n    }\n\n    useb_ = FieldOrDefaultVal(pars, \"UseVisibleBias\", true);\n    useh_ = FieldOrDefaultVal(pars, \"UseHiddenBias\", true);\n    used_ = FieldOrDefaultVal(pars, \"UseAncillaBias\", true);\n\n    Init();\n\n    // Loading parameters, if defined in the input\n    if (FieldExists(pars, \"b1\")) {\n      b1_ = FieldVal<RealVectorType>(pars, \"b1\");\n      b2_ = FieldVal<RealVectorType>(pars, \"b2\");\n    } else {\n      b1_.setZero();\n      b2_.setZero();\n    }\n\n    if (FieldExists(pars, \"h1\")) {\n      h1_ = FieldVal<RealVectorType>(pars, \"h1\");\n      h2_ = FieldVal<RealVectorType>(pars, \"h2\");\n    } else {\n      h1_.setZero();\n      h2_.setZero();\n    }\n\n    if (FieldExists(pars, \"d1\")) {\n      d1_ = FieldVal<RealVectorType>(pars, \"d1\");\n    } else {\n      d1_.setZero();\n    }\n\n    if (FieldExists(pars, \"W1\")) {\n      W1_ = FieldVal<RealMatrixType>(pars, \"W1\");\n      W2_ = FieldVal<RealMatrixType>(pars, \"W2\");\n    }\n\n    if (FieldExists(pars, \"U1\")) {\n      U1_ = FieldVal<RealMatrixType>(pars, \"U1\");\n      U2_ = FieldVal<RealMatrixType>(pars, \"U2\");\n    }\n  }\n\n  bool IsHolomorphic() const noexcept override { return false; }\n};\n\n}  // namespace netket\n\n#endif  // NETKET_NDM_SPIN_PHASE_HPP\n", "meta": {"hexsha": "e539f7cd1336664422c02b74ad23518133735c1b", "size": 22069, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Sources/Machine/DensityMatrices/ndm_spin_phase.hpp", "max_stars_repo_name": "tvieijra/netket", "max_stars_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-29T02:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T18:52:33.000Z", "max_issues_repo_path": "Sources/Machine/DensityMatrices/ndm_spin_phase.hpp", "max_issues_repo_name": "tvieijra/netket", "max_issues_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-11-04T14:38:01.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-08T16:56:10.000Z", "max_forks_repo_path": "Sources/Machine/DensityMatrices/ndm_spin_phase.hpp", "max_forks_repo_name": "tvieijra/netket", "max_forks_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-02T07:29:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-04T21:55:21.000Z", "avg_line_length": 31.7997118156, "max_line_length": 80, "alphanum_fraction": 0.5937287598, "num_tokens": 7460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.43345879741192916}}
{"text": "#include <iostream>\n#include <map>\n#include <vector>\n#include <utility>\n#include <tuple>\n#include <regex>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing boost::multiprecision::uint128_t;\n\nclass Part2 {\npublic:\n    Part2(int max_score);\n    std::pair<uint128_t, uint128_t> solve(int p1, int p2, int s1, int s2);\n\nprivate:\n    int max_;\n\n    std::vector<std::tuple<int, int, int>> throws;\n    std::map<std::tuple<int, int, int, int>, std::pair<uint128_t, uint128_t>> cache_;\n};\n\nPart2::Part2(int max_score) : max_(max_score) {\n    for (int d1 = 1; d1 <= 3; ++d1) {\n        for (int d2 = 1; d2 <= 3; ++d2) {\n            for (int d3 = 1; d3 <= 3; ++d3) {\n                throws.emplace_back(d1,d2,d3);\n            }\n        }\n    }\n}\n\nstd::pair<uint128_t, uint128_t> Part2::solve(int p1, int p2, int s1, int s2) {\n    if (s1 >= max_)\n        return std::make_pair(1, 0);\n    if (s2 >= max_)\n        return std::make_pair(0, 1);\n\n    auto q = std::make_tuple(p1, p2, s1, s2);\n    auto a = cache_.find(q);\n    if (a != cache_.end()) {\n        return a->second;\n    }\n    auto score = std::make_pair<uint128_t,uint128_t>(0, 0);\n    for (auto& a : throws) {\n        auto [d1, d2, d3] = a;\n        int new_p1 = p1 + d1 + d2 + d3;\n        new_p1 %= 10;\n        if (new_p1 == 0) new_p1 = 10;\n        int new_s1 = s1 + new_p1;\n        auto [p2_wins, p1_wins] = solve(p2, new_p1, s2, new_s1);\n        score.first += p1_wins;\n        score.second += p2_wins;\n    }\n\n    cache_[q] = score;\n    return score;\n}\n\nint main(int argc, char** argv) {\n\n    int player_1_start = 0;\n    int player_2_start = 0;\n\n    for (int i = 0; i < 2; ++i) {\n        std::string input;\n        getline(std::cin, input);\n        const std::regex re(R\"(Player \\d starting position: (\\d*))\");\n        std::smatch match;\n        if (regex_search(input, match, re)) {\n            if (i == 0)\n                player_1_start = stoi(match.str(1));\n            else\n                player_2_start = stoi(match.str(1));\n        }\n    }\n\n    int player_1 = 0;\n    int player_2 = 0;\n\n    int p1 = player_1_start;\n    int p2 = player_2_start;\n\n    int dice = 1;\n    while (player_1 < 1000 && player_2 < 1000) {\n        p1 += 3*dice + 3;\n        dice += 3;\n        p1 %= 10;\n        if (p1 == 0) p1 = 10;\n        player_1 += p1;\n        if (player_1 >= 1000)\n            break;\n        p2 += 3*dice + 3;\n        dice += 3;\n        p2 %= 10;\n        if (p2 == 0) p2 = 10;\n        player_2 += p2;\n    }\n\n    int part_1 = std::min(player_1, player_2) * (dice-1);\n    std::cout << part_1 << std::endl;\n\n    Part2 part2(21);\n    auto a = part2.solve(player_1_start, player_2_start, 0, 0);\n    std::cout << std::max(a.first, a.second) << std::endl;\n\n    return 0;\n}", "meta": {"hexsha": "f668ec8610c9a6c7d0e4ea20e8eebe4c9c488f34", "size": 2713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2021/day_21/day_21.cpp", "max_stars_repo_name": "andrewparr/advent-of-code", "max_stars_repo_head_hexsha": "f2b476ac837e1d42d180418e81abf900e9c3a1b6", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2021/day_21/day_21.cpp", "max_issues_repo_name": "andrewparr/advent-of-code", "max_issues_repo_head_hexsha": "f2b476ac837e1d42d180418e81abf900e9c3a1b6", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2021/day_21/day_21.cpp", "max_forks_repo_name": "andrewparr/advent-of-code", "max_forks_repo_head_hexsha": "f2b476ac837e1d42d180418e81abf900e9c3a1b6", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8899082569, "max_line_length": 85, "alphanum_fraction": 0.5226686325, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4334587912280619}}
{"text": "/********************************************************************************\n*  This file is part of CinoLib                                                 *\n*  Copyright(C) 2016: Marco Livesu                                              *\n*                                                                               *\n*  The MIT License                                                              *\n*                                                                               *\n*  Permission is hereby granted, free of charge, to any person obtaining a      *\n*  copy of this software and associated documentation files (the \"Software\"),   *\n*  to deal in the Software without restriction, including without limitation    *\n*  the rights to use, copy, modify, merge, publish, distribute, sublicense,     *\n*  and/or sell copies of the Software, and to permit persons to whom the        *\n*  Software is furnished to do so, subject to the following conditions:         *\n*                                                                               *\n*  The above copyright notice and this permission notice shall be included in   *\n*  all copies or substantial portions of the Software.                          *\n*                                                                               *\n*  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR   *\n*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,     *\n*  FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE *\n*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER       *\n*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      *\n*  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS *\n*  IN THE SOFTWARE.                                                             *\n*                                                                               *\n*  Author(s):                                                                   *\n*                                                                               *\n*     Marco Livesu (marco.livesu@gmail.com)                                     *\n*     http://pers.ge.imati.cnr.it/livesu/                                       *\n*                                                                               *\n*     Italian National Research Council (CNR)                                   *\n*     Institute for Applied Mathematics and Information Technologies (IMATI)    *\n*     Via de Marini, 6                                                          *\n*     16149 Genoa,                                                              *\n*     Italy                                                                     *\n*********************************************************************************/\n#include <cinolib/laplacian.h>\n#include <cinolib/symbols.h>\n#include <Eigen/Sparse>\n\nnamespace cinolib\n{\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<class M, class V, class E, class P>\nCINO_INLINE\nstd::vector<Eigen::Triplet<double>> laplacian_matrix_entries(const AbstractMesh<M,V,E,P> & m,\n                                                             const int mode,\n                                                             const int n) // diagonally replicate n times\n{\n    std::vector<Entry> entries;\n\n    unsigned int nv = m.num_verts();\n    std::vector<unsigned int> base(n);\n    for(int i=0; i<n; ++i) base[i] = nv*i;\n\n    for(unsigned int vid=0; vid<m.num_verts(); ++vid)\n    {\n        std::vector<std::pair<unsigned int,double>> wgts;\n        m.vert_weights(vid, mode, wgts);\n        double sum = 0.0;\n        for(auto item : wgts)\n        {\n            for(int i=0; i<n; ++i)\n            {\n                entries.push_back(Entry(base[i] + vid, base[i] + item.first, item.second));\n            }\n            sum -= item.second;\n        }\n        if(sum == 0.0)\n        {\n            std::cerr << \"WARNING: null row in the matrix! (disconnected vertex? I put 1 in the diagonal)\" << std::endl;\n            sum = 1.0;\n        }\n        for(int i=0; i<n; ++i)\n        {\n            entries.push_back(Entry(base[i] + vid, base[i] + vid, sum));\n        }\n    }\n\n    return entries;\n}\n\n//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\ntemplate<class M, class V, class E, class P>\nCINO_INLINE\nEigen::SparseMatrix<double> laplacian(const AbstractMesh<M,V,E,P> & m, const int mode, const int n)\n{\n    std::vector<Entry> entries = laplacian_matrix_entries(m, mode, n);\n\n    unsigned int nv = n*m.num_verts();\n    Eigen::SparseMatrix<double> L(nv,nv);\n    L.setFromTriplets(entries.begin(), entries.end());\n\n    return L;\n}\n\n}\n", "meta": {"hexsha": "0fd842b0c731308ef34dec6eefebc8f2b9413c77", "size": 4768, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "include/cinolib/laplacian.tpp", "max_stars_repo_name": "francescozoccheddu/cinolib", "max_stars_repo_head_hexsha": "6d6f7d359db673aca1c203a208f50e0a7a362b76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/cinolib/laplacian.tpp", "max_issues_repo_name": "francescozoccheddu/cinolib", "max_issues_repo_head_hexsha": "6d6f7d359db673aca1c203a208f50e0a7a362b76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cinolib/laplacian.tpp", "max_forks_repo_name": "francescozoccheddu/cinolib", "max_forks_repo_head_hexsha": "6d6f7d359db673aca1c203a208f50e0a7a362b76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.68, "max_line_length": 120, "alphanum_fraction": 0.4228187919, "num_tokens": 876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4334587912280619}}
{"text": "// Copyright © 2016-2021 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n\n#pragma once\n\n#include <boost/numeric/odeint.hpp>\n#include <functional>\n\nnamespace vinecopulib {\n\nnamespace tools_integration {\n\ninline double\nintegrate_zero_to_one(std::function<double(double)> f)\n{\n  boost::numeric::odeint::runge_kutta_dopri5<double> stepper;\n  double lb = 1e-12;\n  double ub = 1.0 - lb;\n  double x = 0.0;\n  auto ifunc = [f](const double /* x */, double& dxdt, const double t) {\n    dxdt = f(t);\n  };\n  integrate_adaptive(boost::numeric::odeint::make_controlled(lb, lb, stepper),\n                     ifunc,\n                     x,\n                     lb,\n                     ub,\n                     lb);\n  return x;\n}\n}\n}\n", "meta": {"hexsha": "579e96496e8642a0688448cbb3210d38872406a3", "size": 928, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/vinecopulib/misc/tools_integration.hpp", "max_stars_repo_name": "tvatter/vinecoplib", "max_stars_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-05-05T13:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-15T23:40:01.000Z", "max_issues_repo_path": "include/vinecopulib/misc/tools_integration.hpp", "max_issues_repo_name": "vinecopulib/vinecopulib", "max_issues_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 264.0, "max_issues_repo_issues_event_min_datetime": "2017-03-28T10:07:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-23T10:04:39.000Z", "max_forks_repo_path": "include/vinecopulib/misc/tools_integration.hpp", "max_forks_repo_name": "tvatter/vinecoplib", "max_forks_repo_head_hexsha": "ae34d56408437e6eeacec40a51a8fa8dac378672", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-04-24T13:54:47.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T16:56:17.000Z", "avg_line_length": 25.7777777778, "max_line_length": 79, "alphanum_fraction": 0.6314655172, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4334587912280618}}
{"text": "#if !defined(BALSA_GEOMETRY_TRIANGLE_MESH_EARCLIPPING_HPP)\n#define BALSA_GEOMETRY_TRIANGLE_MESH_EARCLIPPING_HPP\n#include <list>\n\n#include <range/v3/view/subrange.hpp>\n#include <range/v3/view/sliding.hpp>\n#include <range/v3/algorithm/copy.hpp>\n#include <range/v3/view/take_exactly.hpp>\n#include <range/v3/view/cycle.hpp>\n#include <range/v3/range/conversion.hpp>\n#include \"balsa/eigen/stl2eigen.hpp\"\n#include <Eigen/Core>\n#include \"balsa/geometry/winding_number.hpp\"\n#include \"balsa/geometry/get_angle.hpp\"\n#include \"balsa/eigen/types.hpp\"\n#include \"balsa/eigen/shape_checks.hpp\"\n#include <numbers>\n#include <utility>\n\nnamespace balsa::geometry::triangle_mesh {\ntemplate<eigen::concepts::Vec2Compatible VDerived, std::forward_iterator BeginIt, std::forward_iterator EndIt>\nrequires std::is_integral_v<std::decay_t<decltype(*std::declval<BeginIt>())>>\n  std::vector<std::array<std::decay_t<decltype(*std::declval<BeginIt>())>, 3>> earclipping_stl(\n    const VDerived &V,\n    const BeginIt &beginit,\n    const EndIt &endit) {\n    using Index = std::decay_t<decltype(*std::declval<BeginIt>())>;\n    using Face = std::array<int, 3>;\n    std::vector<Face> stlF;\n\n    auto range = ranges::subrange(beginit, endit);\n\n\n    if constexpr (std::is_integral_v<std::decay_t<decltype(*beginit)>>) {\n\n        size_t size = std::distance(beginit, endit);\n        stlF.reserve(size - 2);\n        double inner_ang_sum = 0;\n        double outer_ang_sum = 0;\n        auto triplets = range | ranges::views::cycle// pretend range is cyclic\n                        | ranges::views::sliding(3)// take sequences of triplets\n                        | ranges::views::take_exactly(std::distance(beginit, endit));// we only want to see each cycle once\n        for (auto &&triplet : triplets) {\n            Face f;\n            ranges::copy(triplet, f.begin());\n            const auto &[ai, bi, ci] = f;\n            auto a = V.col(ai);\n            auto b = V.col(bi);\n            auto c = V.col(ci);\n            double ang = get_positive_clamped_angle(get_angle(c - b, a - b));\n            inner_ang_sum += ang;\n            outer_ang_sum += 2 * std::numbers::pi_v<double> - ang;\n        }\n\n        bool reverse_orientation = outer_ang_sum < inner_ang_sum;\n        if (reverse_orientation) {\n        }\n\n        std::list<Index> CL(beginit, endit);\n\n        auto is_earclip = [&](const Face &f) -> bool {\n            auto a = V.col(f[0]);\n            auto b = V.col(f[1]);\n            auto c = V.col(f[2]);\n            auto cb = c - b;\n            auto ab = a - b;\n            // balsa::Vec2d n(-ac.y(),ac.x());\n            /*\n            if(cb.x() * ab.y() -  cb.y() * ab.x() < 1e-12) {\n                return false;\n            }\n            */\n            if (cb.x() * ab.y() - cb.y() * ab.x() < 1e-10) {\n                return false;\n            }\n            // double ang = balsa::geometry::trigonometry::angle(cb,ab)(0);\n            double ang = get_positive_clamped_angle(get_angle(c - b, a - b));\n            if (ang > std::numbers::pi_v<double> || ang < 0) {\n                return false;\n            }\n\n            for (auto &&i : range) {\n                if (i == f[0] || i == f[1] || i == f[2]) {\n                    continue;\n                }\n                auto v = V.col(i);\n                if (interior_winding_number(V, f, v)) {\n                    return false;\n                }\n            }\n            return true;\n        };\n\n        while (CL.size() > 3) {\n            bool earclipped = false;\n\n            for (auto it = CL.begin(); it != CL.end(); ++it) {\n                auto it1 = it;\n                it1++;\n                if (it1 == CL.end()) {\n                    it1 = CL.begin();\n                }\n                auto it2 = it1;\n                it2++;\n                if (it2 == CL.end()) {\n                    it2 = CL.begin();\n                }\n                Face f{ { *it, *it1, *it2 } };\n                if (reverse_orientation) {\n                    std::swap(f[0], f[2]);\n                }\n                if (is_earclip(f)) {\n                    stlF.push_back(f);\n                    CL.erase(it1);\n                    earclipped = true;\n                    break;\n                }\n            }\n            if (!earclipped) {\n                // logging::warn() << \"Earclipping failed!\";\n                auto it = CL.begin();\n                auto it1 = it;\n                it1++;\n                auto it2 = it1;\n                it2++;\n                Face f{ { *it, *it1, *it2 } };\n\n\n                stlF.push_back(f);\n                CL.erase(it1);\n            }\n        }\n\n        Face f;\n        std::copy(CL.begin(), CL.end(), f.begin());\n        auto a = V.col(f[0]);\n        auto b = V.col(f[1]);\n        auto c = V.col(f[2]);\n        auto cb = c - b;\n        auto ab = a - b;\n        // auto ac = a - c;\n        if (cb.x() * ab.y() - cb.y() * ab.x() < 1e-10) {\n            std::swap(f[0], f[1]);\n        }\n        stlF.push_back(f);\n        //} else {\n        //    size_t size = 0;\n        //    for (auto &&c : ranges::subrange(beginit, endit)) {\n        //        size += c.size() - 2;\n        //    }\n        //    stlF.reserve(size);\n\n        //    for (auto &&c : ranges::subrange(beginit, endit)) {\n        //        if (c.size() >= 3) {\n        //            auto F = earclipping_stl(V, c.begin(), c.end());\n        //            stlF.insert(stlF.end(), F.begin(), F.end());\n        //        }\n        //    }\n    }\n    return stlF;\n}\n// both return balsa::eigen::ColVectors<integral_type, 3>\ntemplate<eigen::concepts::ColVecs2Compatible VDerived, typename Container>\n\nauto earclipping(const VDerived &V,\n                 const Container &C) {\n    return eigen::stl2eigen(earclipping_stl(V, C.begin(), C.end()));\n}\ntemplate<eigen::concepts::ColVecs2Compatible VDerived, typename T>\nauto earclipping(const VDerived &V,\n                 const std::initializer_list<T> &C) {\n    return eigen::stl2eigen(earclipping_stl(V, C.begin(), C.end()));\n}\n}// namespace balsa::geometry::triangle_mesh\n#endif\n", "meta": {"hexsha": "10823d05a4df02ea35fdf961b59cbfd809fa18ca", "size": 6024, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/balsa/geometry/triangle_mesh/earclipping.hpp", "max_stars_repo_name": "mtao/balsa", "max_stars_repo_head_hexsha": "1552f3a367a80dfc41fffc50b5628b46ba716ab8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/balsa/geometry/triangle_mesh/earclipping.hpp", "max_issues_repo_name": "mtao/balsa", "max_issues_repo_head_hexsha": "1552f3a367a80dfc41fffc50b5628b46ba716ab8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/balsa/geometry/triangle_mesh/earclipping.hpp", "max_forks_repo_name": "mtao/balsa", "max_forks_repo_head_hexsha": "1552f3a367a80dfc41fffc50b5628b46ba716ab8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2272727273, "max_line_length": 123, "alphanum_fraction": 0.4878818061, "num_tokens": 1581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4334587912280618}}
{"text": "/******************************************************************************\n * Author:   Laurent Kneip                                                    *\n * Contact:  kneip.laurent@gmail.com                                          *\n * License:  Copyright (c) 2013 Laurent Kneip, ANU. All rights reserved.      *\n *                                                                            *\n * Redistribution and use in source and binary forms, with or without         *\n * modification, are permitted provided that the following conditions         *\n * are met:                                                                   *\n * * Redistributions of source code must retain the above copyright           *\n *   notice, this list of conditions and the following disclaimer.            *\n * * Redistributions in binary form must reproduce the above copyright        *\n *   notice, this list of conditions and the following disclaimer in the      *\n *   documentation and/or other materials provided with the distribution.     *\n * * Neither the name of ANU nor the names of its contributors may be         *\n *   used to endorse or promote products derived from this software without   *\n *   specific prior written permission.                                       *\n *                                                                            *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"*\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  *\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *\n * ARE DISCLAIMED. IN NO EVENT SHALL ANU OR THE CONTRIBUTORS BE LIABLE        *\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT         *\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY  *\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF     *\n * SUCH DAMAGE.                                                               *\n ******************************************************************************/\n\n\n#include <opengv/sac_problems/relative_pose/MultiCentralRelativePoseSacProblem.hpp>\n\n#include <opengv/relative_pose/methods.hpp>\n#include <opengv/triangulation/methods.hpp>\n#include <Eigen/NonLinearOptimization>\n#include <Eigen/NumericalDiff>\n\nbool\nopengv::sac_problems::\n    relative_pose::MultiCentralRelativePoseSacProblem::computeModelCoefficients(\n    const std::vector<std::vector<int> > &indices,\n    model_t & outModel) const\n{\n  std::vector<std::shared_ptr<translations_t> > multiTranslations;\n  std::vector<std::shared_ptr<rotations_t> > multiRotations;\n\n  for(size_t pairIndex = 0; pairIndex < _adapter.getNumberPairs(); pairIndex++)\n  {\n    std::vector<int> serializedIndices;\n    for(\n        size_t correspondenceIndex = 0;\n        correspondenceIndex < indices[pairIndex].size();\n        correspondenceIndex++ )\n      serializedIndices.push_back(_adapter.convertMultiIndex(\n          pairIndex, indices[pairIndex][correspondenceIndex] ));\n    \n    essential_t essentialMatrix =\n        opengv::relative_pose::eightpt(_adapter,serializedIndices);\n\n    //Decompose the essential matrix into rotations and translations\n    std::shared_ptr<translations_t> translations(new translations_t());\n    std::shared_ptr<rotations_t> rotations(new rotations_t());\n\n    Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n    W(0,1) = -1;\n    W(1,0) = 1;\n    W(2,2) = 1;\n\n    Eigen::JacobiSVD< Eigen::MatrixXd > SVD(\n        essentialMatrix,\n        Eigen::ComputeFullV | Eigen::ComputeFullU );\n    Eigen::VectorXd singularValues = SVD.singularValues();\n\n    // check for bad essential matrix\n    if( singularValues[2] > 0.001 ) {};\n    // continue; //singularity constraints not applied -> removed because too harsh\n    if( singularValues[1] < 0.75 * singularValues[0] ) {};\n    // continue; //bad essential matrix -> removed because too harsh\n\n    // maintain scale\n    double scale = singularValues[0];\n\n    // get possible rotation and translation vectors\n    rotation_t Ra = SVD.matrixU() * W * SVD.matrixV().transpose();\n    rotation_t Rb = SVD.matrixU() * W.transpose() * SVD.matrixV().transpose();\n    translation_t t = scale*SVD.matrixU().col(2);\n\n    // change sign if det = -1\n    if( Ra.determinant() < 0 ) Ra = -Ra;\n    if( Rb.determinant() < 0 ) Rb = -Rb;\n\n    //Store the decomposition, and already convert to our convention\n    translations->push_back(t);\n    translations->push_back(-t); //this is not needed actually!\n    rotations->push_back(Ra);\n    rotations->push_back(Rb);\n\n    multiTranslations.push_back(translations);\n    multiRotations.push_back(rotations);\n  }\n\n\n  for(size_t pairIndex = 0; pairIndex < _adapter.getNumberPairs(); pairIndex++)\n  {\n    //For each pair, find the right rotation and translation by our critera\n    //\n    //\n    //fill outModel with that (it is a vector of transformations. A\n    //transformation is 3x4 with R from frame 2 to 1, and position of 2 in 1)\n  }\n\n  return true;\n}\n\nvoid\nopengv::sac_problems::\n    relative_pose::MultiCentralRelativePoseSacProblem::getSelectedDistancesToModel(\n    const model_t & model,\n    const std::vector<std::vector<int> > & indices,\n    std::vector<std::vector<double> > & scores) const\n{\n  Eigen::Matrix<double,4,1> p_hom;\n  p_hom[3] = 1.0;\n\n  for( size_t pairIndex = 0; pairIndex < indices.size(); pairIndex++ )\n  {\n    translation_t translation = model[pairIndex].col(3);\n    rotation_t rotation = model[pairIndex].block<3,3>(0,0);\n\n    for(\n        size_t correspondenceIndex = 0;\n        correspondenceIndex < indices[pairIndex].size();\n        correspondenceIndex++ )\n    {\n      _adapter.sett12(translation);\n      _adapter.setR12(rotation);\n\n      transformation_t inverseSolution;\n      inverseSolution.block<3,3>(0,0) = rotation.transpose();\n      inverseSolution.col(3) =\n          -inverseSolution.block<3,3>(0,0)*translation;\n\n      p_hom.block<3,1>(0,0) =\n          opengv::triangulation::triangulate2(\n              _adapter,\n              _adapter.convertMultiIndex(\n              pairIndex, indices[pairIndex][correspondenceIndex] ));\n\n      bearingVector_t reprojection1 = p_hom.block<3,1>(0,0);\n      bearingVector_t reprojection2 = inverseSolution * p_hom;\n      reprojection1 = reprojection1 / reprojection1.norm();\n      reprojection2 = reprojection2 / reprojection2.norm();\n      bearingVector_t f1 = _adapter.getBearingVector1(pairIndex,correspondenceIndex);\n      bearingVector_t f2 = _adapter.getBearingVector2(pairIndex,correspondenceIndex);\n\n      //bearing-vector based outlier criterium (select threshold accordingly):\n      //1-(f1'*f2) = 1-cos(alpha) \\in [0:2]\n      double reprojError1 = 1.0 - (f1.transpose() * reprojection1);\n      double reprojError2 = 1.0 - (f2.transpose() * reprojection2);\n      scores[pairIndex].push_back(reprojError1 + reprojError2);\n    }\n  }\n}\n\nvoid\nopengv::sac_problems::\n    relative_pose::MultiCentralRelativePoseSacProblem::optimizeModelCoefficients(\n    const std::vector<std::vector<int> > & inliers,\n    const model_t & model,\n    model_t & optimized_model)\n{\n  optimized_model = model; //todo: include non-linear optimization of model\n}\n\nstd::vector<int>\nopengv::sac_problems::\n    relative_pose::MultiCentralRelativePoseSacProblem::getSampleSizes() const\n{\n  std::vector<int> sampleSizes;\n  for(size_t pairIndex = 0; pairIndex < _adapter.getNumberPairs(); pairIndex++)\n    sampleSizes.push_back(_sampleSize);\n\n  return sampleSizes;\n}\n", "meta": {"hexsha": "25f446a31037f50f513e819db96fe1de532c4af6", "size": 7713, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sac_problems/relative_pose/MultiCentralRelativePoseSacProblem.cpp", "max_stars_repo_name": "skn123/opengv", "max_stars_repo_head_hexsha": "91f4b19c73450833a40e463ad3648aae80b3a7f3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 794.0, "max_stars_repo_stars_event_min_datetime": "2015-01-16T22:25:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T23:59:20.000Z", "max_issues_repo_path": "src/sac_problems/relative_pose/MultiCentralRelativePoseSacProblem.cpp", "max_issues_repo_name": "skn123/opengv", "max_issues_repo_head_hexsha": "91f4b19c73450833a40e463ad3648aae80b3a7f3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2015-01-14T11:09:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-19T13:31:39.000Z", "max_forks_repo_path": "src/sac_problems/relative_pose/MultiCentralRelativePoseSacProblem.cpp", "max_forks_repo_name": "skn123/opengv", "max_forks_repo_head_hexsha": "91f4b19c73450833a40e463ad3648aae80b3a7f3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 276.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:18:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T09:05:06.000Z", "avg_line_length": 41.4677419355, "max_line_length": 85, "alphanum_fraction": 0.6455335148, "num_tokens": 1789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4334587912280618}}
{"text": "#include \"util_3drotation_log_exp.h\"\n#include <OpenMesh/Core/IO/MeshIO.hh>\n#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <string>\n#include <iostream>\n#include <pybind11/numpy.h>\n#include <pybind11/pybind11.h>\n#include <vector>;\n\nnamespace py=pybind11;\n\nstruct TriTraits : public OpenMesh::DefaultTraits\n{\n  /// Use double precision points\n  typedef OpenMesh::Vec3d Point;\n  /// Use double precision Normals\n  typedef OpenMesh::Vec3d Normal;\n  /// Use double precision TexCood2D\n  typedef OpenMesh::Vec2d TexCoord2D;\n\n  /// Use RGBA Color\n  typedef OpenMesh::Vec4f Color;\n\n    /// Status\n    VertexAttributes(OpenMesh::Attributes::Status);\n    FaceAttributes(OpenMesh::Attributes::Status);\n    EdgeAttributes(OpenMesh::Attributes::Status);\n\n//    VertexAttributes(\n//            OpenMesh::Attributes::\n//            )\n};\n\n/// Simple Name for Mesh\ntypedef OpenMesh::TriMesh_ArrayKernelT<TriTraits>  TriMesh;\n\nclass DR_feature{\npublic:\n    DR_feature();\n\tvoid read_ref_mesh(std::string ref_mesh_name);\n\tvoid read_defor_mesh(std::string defor_mesh_name);\n\tstd::vector<double> get_feature(std::string ref_mesh_name, std::string defor_mesh_name);\n\n\nprivate:\n\tTriMesh ref_mesh_;\n\tTriMesh defor_mesh_;\n\n\tOpenMesh::EPropHandleT<double> LB_weights;\n\tOpenMesh::VPropHandleT<Eigen::Matrix3d> T_matrixs;\nprivate:\n\tvoid compute_ref_LB_weight();\n    void compute_Ti(TriMesh::VertexHandle v_it,TriMesh::VertexHandle v_to_it);\n};\n\nDR_feature::DR_feature(){\n\tref_mesh_.add_property(LB_weights);\n\tdefor_mesh_.add_property(T_matrixs);\n}\n\nvoid DR_feature::read_ref_mesh(std::string ref_mesh_name){\n\tif(!OpenMesh::IO::read_mesh(ref_mesh_, ref_mesh_name)){\n        std::cout<<\"read_ref_mesh_ : read file wrong!!!\"<<std::endl;\n        return ;\n    }\n\n    compute_ref_LB_weight();\n}\n\nvoid DR_feature::compute_ref_LB_weight(){\n\tTriMesh::EdgeIter e_it, e_end(ref_mesh_.edges_end());\n    TriMesh::HalfedgeHandle    h0, h1, h2;\n    TriMesh::VertexHandle      v0, v1;\n    TriMesh::Point             p0, p1, p2, d0, d1;\n    TriMesh::Scalar w;\n    for (e_it=ref_mesh_.edges_begin(); e_it!=e_end; e_it++)\n    {\n        w  = 0.0;\n        if(ref_mesh_.is_boundary(*e_it))\n        {\n            h0 = ref_mesh_.halfedge_handle(e_it.handle(),0);\n            if(ref_mesh_.is_boundary(h0))\n                h0 = ref_mesh_.opposite_halfedge_handle(h0);\n\n            v0 = ref_mesh_.to_vertex_handle(h0);\n            v1 = ref_mesh_.from_vertex_handle(h0);\n            p0 = ref_mesh_.point(v0);\n            p1 = ref_mesh_.point(v1);\n            h1 = ref_mesh_.next_halfedge_handle(h0);\n            p2 = ref_mesh_.point(ref_mesh_.to_vertex_handle(h1));\n            d0 = (p0-p2).normalize();\n            d1 = (p1-p2).normalize();\n            w += 2.0 / tan(acos(std::min(0.99, std::max(-0.99, (d0|d1)))));\n            w = std::max(0.0, w);\n\n            if(std::isnan(w))\n                std::cout<<\"Some weight NAN\"<<std::endl;\n            ref_mesh_.property(LB_weights,e_it) = w;\n            continue;\n        }\n        h0 = ref_mesh_.halfedge_handle(e_it.handle(),0);\n        v0 = ref_mesh_.to_vertex_handle(h0);\n        p0 = ref_mesh_.point(v0);\n\n        h1 = ref_mesh_.opposite_halfedge_handle(h0);\n        v1 = ref_mesh_.to_vertex_handle(h1);\n        p1 = ref_mesh_.point(v1);\n\n        h2 = ref_mesh_.next_halfedge_handle(h0);\n        p2 = ref_mesh_.point(ref_mesh_.to_vertex_handle(h2));\n        d0 = (p0 - p2).normalize();\n        d1 = (p1 - p2).normalize();\n        w += 1.0/ tan(acos(std::max(-1.0, std::min(1.0, dot(d1,d0) ))));\n\n        h2 = ref_mesh_.next_halfedge_handle(h1);\n        p2 = ref_mesh_.point(ref_mesh_.to_vertex_handle(h2));\n        d0 = (p0 - p2).normalize();\n        d1 = (p1 - p2).normalize();\n        w += 1.0 / tan(acos(std::max(-1.0, std::min(1.0, dot(d1,d0)))));\n\n        if(std::isnan(w))\n            std::cout<<\"Some weight is NAN\"<<std::endl;\n        w = std::max(0.0, w);\n        ref_mesh_.property(LB_weights,e_it) = w;\n    }\n}\n\nvoid DR_feature::read_defor_mesh(std::string _filename){\n\tif(!OpenMesh::IO::read_mesh(defor_mesh_,_filename))\n    {\n        std::cout<<\"read_defor_mesh : read file wrong\"<<std::endl;\n        return ;\n    }\n\n    TriMesh::FaceIter f_it = defor_mesh_.faces_begin();\n    for(;f_it!=defor_mesh_.faces_end();f_it++)\n    {\n        TriMesh::FaceHandle f_h = *f_it;\n        TriMesh::FaceVertexIter fe_it0,fe_it1;\n        fe_it0 = ref_mesh_.fv_iter(f_h);\n        fe_it1 = defor_mesh_.fv_iter(f_h);\n        int v00,v01,v02,v10,v11,v12;\n        v00 = (*fe_it0).idx();fe_it0++;\n        v01 = (*fe_it0).idx();fe_it0++;\n        v02 = (*fe_it0).idx();fe_it0++;\n\n        v10 = (*fe_it1).idx();fe_it1++;\n        v11 = (*fe_it1).idx();fe_it1++;\n        v12 = (*fe_it1).idx();fe_it1++;\n\n        if(v00 == v10)\n        {\n            if(v01!=v11||v02!=v12)\n            {\n                std::cout<<\"defor and ref are not compatible!!!\"<<std::endl;\n                return;\n            }\n        }\n        else if(v00 == v11)\n        {\n            if(v01!=v12||v02!=v10)\n            {\n                std::cout<<\"defor and ref are not compatible!!!\"<<std::endl;\n                return;\n            }\n        }\n        else if(v00 == v12)\n        {\n            if(v01!=v10||v02!=v11)\n            {\n                std::cout<<\"defor and ref are not compatible!!!\"<<std::endl;\n                return;\n            }\n        }\n        else\n        {\n            std::cout<<\"defor and ref are not compatible!!!\"<<std::endl;\n            return;\n        }\n    }\n\n    TriMesh::VertexIter v_it, v_to_it;\n    for(v_it=ref_mesh_.vertices_begin(),v_to_it=defor_mesh_.vertices_begin()\n        ;v_it!=ref_mesh_.vertices_end()&&v_to_it!=defor_mesh_.vertices_end()\n        ;v_it++,v_to_it++)\n    {\n        if((*v_it).idx()!=(*v_to_it).idx())\n            std::cout<<\"DR_feature::compute_ref_to_defor_Tmatrixs different topology!!!\"<<std::endl;\n        compute_Ti(*v_it,*v_to_it);\n    }\n\n}\n\nvoid DR_feature::compute_Ti(TriMesh::VertexHandle v_it, TriMesh::VertexHandle v_to_it){\n    if(v_it.idx()!=v_to_it.idx())\n    \tstd::cout<<\"compute_Ti correspond is wrong!!!\"<<std::endl;\n    TriMesh::VertexEdgeIter veiter=ref_mesh_.ve_iter(v_it);\n    int v_id = v_it.idx();\n    TriMesh::Point p0,p1;\n    p0 = ref_mesh_.point(v_it);\n    p1 = defor_mesh_.point(v_to_it);\n    Eigen::Matrix3d L,RI;\n    L.setZero();\n    RI.setZero();\n    double tolerance = 1.0e-6;\n    TriMesh::HalfedgeHandle h_e=ref_mesh_.halfedge_handle(v_it);\n    TriMesh::VertexHandle test_v = ref_mesh_.to_vertex_handle(h_e);\n    TriMesh::Point tp0,tp1;\n    tp0 = ref_mesh_.point(v_it); tp1 = ref_mesh_.point(test_v);\n    double scale=1.0;\n    if(((tp0[0]-tp1[0])*(tp0[0]-tp1[0])+(tp0[1]-tp1[1])*(tp0[1]-tp1[1])+(tp0[2]-tp1[2])*(tp0[2]-tp1[2]))<0.1)\n        scale = 100;\n\n    for(;veiter.is_valid();veiter++)\n    {\n        double weight = 1.0;\n        int to_id;\n        TriMesh::VertexHandle to_v=ref_mesh_.to_vertex_handle(ref_mesh_.halfedge_handle(*veiter, 0));\n        if(to_v.idx()==v_id)\n            to_v = ref_mesh_.from_vertex_handle(ref_mesh_.halfedge_handle(*veiter, 0));\n        to_id = to_v.idx();\n        Eigen::Vector3d eij0,eij1;\n        TriMesh::Point q0,q1;\n        q0 = ref_mesh_.point(to_v);\n        q1 = defor_mesh_.point(to_v);\n        eij0(0) = p0[0]-q0[0];\n        eij0(1) = p0[1]-q0[1];\n        eij0(2) = p0[2]-q0[2];\n        eij0*=weight*scale;\n\n        eij1(0) = p1[0]-q1[0];\n        eij1(1) = p1[1]-q1[1];\n        eij1(2) = p1[2]-q1[2];\n        eij1*=weight*scale;\n\n        L+=eij1*eij0.transpose();\n        RI+=eij0*eij0.transpose();\n    }\n    Eigen::Matrix3d T;\n    if(fabs(RI.determinant())>tolerance)\n         T = L*RI.inverse();\n    else\n    {\n        Eigen::JacobiSVD<Eigen::MatrixXd> svd(RI, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        Eigen::Matrix3d U,V;\n        U=svd.matrixU();\n        V=svd.matrixV();\n        Eigen::Matrix3d S_inv(svd.singularValues().asDiagonal());\n        for(int i=0;i<3;i++)\n        {\n            if(fabs(S_inv(i,i))>tolerance)\n                S_inv(i,i)=1.0/S_inv(i,i);\n            else\n                S_inv(i,i)=0.0;\n        }\n        T = L*V*S_inv*U.transpose();\n    }\n    defor_mesh_.property(T_matrixs,v_it) = T;\n}\n\n\nstd::vector<double> DR_feature::get_feature(std::string ref_mesh_name, std::string defor_mesh_name){\n\tread_ref_mesh(ref_mesh_name);\n\tread_defor_mesh(defor_mesh_name);\n\n\tstd::vector<double> dr_feature;\n\n\tTriMesh::VertexIter v_it;\n    for(v_it=defor_mesh_.vertices_begin(); v_it!=defor_mesh_.vertices_end(); v_it++)\n    {\n        Eigen::Matrix3d T = defor_mesh_.property(T_matrixs,*v_it);\n        Eigen::JacobiSVD<Eigen::MatrixXd> svd(T, Eigen::ComputeThinU | Eigen::ComputeThinV);\n        Eigen::Matrix3d U,V;\n        U=svd.matrixU();\n        V=svd.matrixV();\n        Eigen::Matrix3d S(svd.singularValues().asDiagonal());\n        Eigen::Matrix3d Temp=Eigen::Matrix3d::Identity();\n        Temp(2,2) = (U*V.transpose()).determinant();\n        Eigen::Matrix3d R=U*Temp*V.transpose();\n        Eigen::Matrix3d Scale = V*Temp*S*V.transpose();\n        Eigen::Matrix3d logR = rotation_log_exp::log(R);\n\n        dr_feature.push_back(Scale(0, 0));\n        dr_feature.push_back(Scale(0, 1));\n        dr_feature.push_back(Scale(0, 2));\n        dr_feature.push_back(Scale(1, 1));\n        dr_feature.push_back(Scale(1, 2));\n        dr_feature.push_back(Scale(2, 2));\n        dr_feature.push_back(logR(0, 1));\n        dr_feature.push_back(logR(0, 2));\n        dr_feature.push_back(logR(1, 2));\n    }\n    return dr_feature;\n}\n\npy::array_t<double> get_dr(std::string ref_mesh_name, std::string defor_mesh_name){\n\tDR_feature feature;\n\tstd::vector<double> temp = feature.get_feature(ref_mesh_name, defor_mesh_name);\n\n    auto result = py::array_t<double>(temp.size());\n    auto result_buffer = result.request();\n    double *result_ptr = (double *)result_buffer.ptr;\n\n    std::memcpy(result_ptr, temp.data(), temp.size()*sizeof(double));\n\n    return result;\n\n}\n\n PYBIND11_MODULE(get_dr, m){\n    m.doc() = \"get dr\";\n    m.def(\"get_dr\", &get_dr, \"get_dr\"); \n }", "meta": {"hexsha": "74daa799de9a3454316e2924428e7d5c05241fee", "size": 10028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "get_dr.cpp", "max_stars_repo_name": "QianyiWu/get_dr_py", "max_stars_repo_head_hexsha": "9cd143c27a35e5aa5ddd6522914af79027d497f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T08:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T21:05:09.000Z", "max_issues_repo_path": "third_party/get_dr_py/get_dr.cpp", "max_issues_repo_name": "QianyiWu/DR-Learning-for-3D-Face", "max_issues_repo_head_hexsha": "fee8931e9bed5c1e3f69c290783fcaf4bcf967c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-24T01:04:36.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-14T04:13:30.000Z", "max_forks_repo_path": "third_party/get_dr_py/get_dr.cpp", "max_forks_repo_name": "QianyiWu/DR-Learning-for-3D-Face", "max_forks_repo_head_hexsha": "fee8931e9bed5c1e3f69c290783fcaf4bcf967c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-02-26T07:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T21:05:12.000Z", "avg_line_length": 31.8349206349, "max_line_length": 109, "alphanum_fraction": 0.598723574, "num_tokens": 3012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.43345878504419433}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <stdexcept>\n#include <Eigen/Geometry>\n#include <visualization_msgs/Marker.h>\n#include <arc_utilities/voxel_grid.hpp>\n#include <arc_utilities/pretty_print.hpp>\n#include <sdf_tools/sdf.hpp>\n\n#ifndef SDF_GENERATION_HPP\n#define SDF_GENERATION_HPP\n\nnamespace sdf_generation\n{\n    struct bucket_cell\n    {\n        double distance_square;\n        int32_t update_direction;\n        uint32_t location[3];\n        uint32_t closest_point[3];\n    };\n\n    typedef VoxelGrid::VoxelGrid<bucket_cell> DistanceField;\n\n    inline int GetDirectionNumber(const int dx, const int dy, const int dz)\n    {\n        return ((dx + 1) * 9) + ((dy + 1) * 3) + (dz + 1);\n    }\n\n    inline std::vector<std::vector<std::vector<std::vector<int>>>> MakeNeighborhoods()\n    {\n        std::vector<std::vector<std::vector<std::vector<int>>>> neighborhoods;\n        neighborhoods.resize(2);\n        for (size_t n = 0; n < neighborhoods.size(); n++)\n        {\n            neighborhoods[n].resize(27);\n            // Loop through the source directions\n            for (int dx = -1; dx <= 1; dx++)\n            {\n                for (int dy = -1; dy <= 1; dy++)\n                {\n                    for (int dz = -1; dz <= 1; dz++)\n                    {\n                        int direction_number = GetDirectionNumber(dx, dy, dz);\n                        // Loop through the target directions\n                        for (int tdx = -1; tdx <= 1; tdx++)\n                        {\n                            for (int tdy = -1; tdy <= 1; tdy++)\n                            {\n                                for (int tdz = -1; tdz <= 1; tdz++)\n                                {\n                                    if (tdx == 0 && tdy == 0 && tdz == 0)\n                                    {\n                                        continue;\n                                    }\n                                    if (n >= 1)\n                                    {\n                                        if ((abs(tdx) + abs(tdy) + abs(tdz)) != 1)\n                                        {\n                                            continue;\n                                        }\n                                        if ((dx * tdx) < 0 || (dy * tdy) < 0 || (dz * tdz) < 0)\n                                        {\n                                            continue;\n                                        }\n                                    }\n                                    std::vector<int> new_point;\n                                    new_point.resize(3);\n                                    new_point[0] = tdx;\n                                    new_point[1] = tdy;\n                                    new_point[2] = tdz;\n                                    neighborhoods[n][direction_number].push_back(new_point);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        return neighborhoods;\n    }\n\n    inline double ComputeDistanceSquared(const int32_t x1, const int32_t y1, const int32_t z1, const int32_t x2, const int32_t y2, const int32_t z2)\n    {\n        int32_t dx = x1 - x2;\n        int32_t dy = y1 - y2;\n        int32_t dz = z1 - z2;\n        return double((dx * dx) + (dy * dy) + (dz * dz));\n    }\n\n    inline DistanceField BuildDistanceField(const Eigen::Isometry3d& grid_origin_tranform,\n                                            const double grid_resolution,\n                                            const int64_t grid_num_x_cells,\n                                            const int64_t grid_num_y_cells,\n                                            const int64_t grid_num_z_cells,\n                                            const std::vector<VoxelGrid::GRID_INDEX>& points)\n    {\n        // Make the DistanceField container\n        bucket_cell default_cell;\n        default_cell.distance_square = std::numeric_limits<double>::infinity();\n        DistanceField distance_field(grid_origin_tranform, grid_resolution, grid_num_x_cells, grid_num_y_cells, grid_num_z_cells, default_cell);\n        // Compute maximum distance square\n        long max_distance_square = (distance_field.GetNumXCells() * distance_field.GetNumXCells()) + (distance_field.GetNumYCells() * distance_field.GetNumYCells()) + (distance_field.GetNumZCells() * distance_field.GetNumZCells());\n        // Make bucket queue\n        std::vector<std::vector<bucket_cell>> bucket_queue(max_distance_square + 1);\n        bucket_queue[0].reserve(points.size());\n        // Set initial update direction\n        int initial_update_direction = GetDirectionNumber(0, 0, 0);\n        // Mark all points with distance zero and add to the bucket queue\n        for (size_t index = 0; index < points.size(); index++)\n        {\n            const VoxelGrid::GRID_INDEX& current_index = points[index];\n            std::pair<bucket_cell&, bool> query = distance_field.GetMutable(current_index);\n            if (query.second)\n            {\n                query.first.location[0] = current_index.x;\n                query.first.location[1] = current_index.y;\n                query.first.location[2] = current_index.z;\n                query.first.closest_point[0] = current_index.x;\n                query.first.closest_point[1] = current_index.y;\n                query.first.closest_point[2] = current_index.z;\n                query.first.distance_square = 0.0;\n                query.first.update_direction = initial_update_direction;\n                bucket_queue[0].push_back(query.first);\n            }\n            // If the point is outside the bounds of the SDF, skip\n            else\n            {\n                throw std::runtime_error(\"Point for BuildDistanceField out of bounds\");\n            }\n        }\n        // Process the bucket queue\n        std::vector<std::vector<std::vector<std::vector<int>>>> neighborhoods = MakeNeighborhoods();\n        for (size_t bq_idx = 0; bq_idx < bucket_queue.size(); bq_idx++)\n        {\n            std::vector<bucket_cell>::iterator queue_itr = bucket_queue[bq_idx].begin();\n            while (queue_itr != bucket_queue[bq_idx].end())\n            {\n                // Get the current location\n                bucket_cell& cur_cell = *queue_itr;\n                double x = cur_cell.location[0];\n                double y = cur_cell.location[1];\n                double z = cur_cell.location[2];\n                // Pick the update direction\n                int D = bq_idx;\n                if (D > 1)\n                {\n                    D = 1;\n                }\n                // Make sure the update direction is valid\n                if (cur_cell.update_direction < 0 || cur_cell.update_direction > 26)\n                {\n                    ++queue_itr;\n                    continue;\n                }\n                // Get the current neighborhood list\n                std::vector<std::vector<int>>& neighborhood = neighborhoods[D][cur_cell.update_direction];\n                // Update the distance from the neighboring cells\n                for (size_t nh_idx = 0; nh_idx < neighborhood.size(); nh_idx++)\n                {\n                    // Get the direction to check\n                    int dx = neighborhood[nh_idx][0];\n                    int dy = neighborhood[nh_idx][1];\n                    int dz = neighborhood[nh_idx][2];\n                    int nx = x + dx;\n                    int ny = y + dy;\n                    int nz = z + dz;\n                    std::pair<bucket_cell&, bool> neighbor_query = distance_field.GetMutable((int64_t)nx, (int64_t)ny, (int64_t)nz);\n                    if (!neighbor_query.second)\n                    {\n                        // \"Neighbor\" is outside the bounds of the SDF\n                        continue;\n                    }\n                    // Update the neighbor's distance based on the current\n                    int new_distance_square = ComputeDistanceSquared(nx, ny, nz, cur_cell.closest_point[0], cur_cell.closest_point[1], cur_cell.closest_point[2]);\n                    if (new_distance_square > max_distance_square)\n                    {\n                        // Skip these cases\n                        continue;\n                    }\n                    if (new_distance_square < neighbor_query.first.distance_square)\n                    {\n                        // If the distance is better, time to update the neighbor\n                        neighbor_query.first.distance_square = new_distance_square;\n                        neighbor_query.first.closest_point[0] = cur_cell.closest_point[0];\n                        neighbor_query.first.closest_point[1] = cur_cell.closest_point[1];\n                        neighbor_query.first.closest_point[2] = cur_cell.closest_point[2];\n                        neighbor_query.first.location[0] = nx;\n                        neighbor_query.first.location[1] = ny;\n                        neighbor_query.first.location[2] = nz;\n                        neighbor_query.first.update_direction = GetDirectionNumber(dx, dy, dz);\n                        // Add the neighbor into the bucket queue\n                        bucket_queue[new_distance_square].push_back(neighbor_query.first);\n                    }\n                }\n                // Increment the queue iterator\n                ++queue_itr;\n            }\n            // Clear the current queue now that we're done with it\n            bucket_queue[bq_idx].clear();\n        }\n        return distance_field;\n    }\n\n    template<typename T>\n    inline std::pair<sdf_tools::SignedDistanceField, std::pair<double, double>> ExtractSignedDistanceField(const Eigen::Isometry3d& grid_origin_tranform,\n                                                                                                           const double grid_resolution,\n                                                                                                           const int64_t grid_num_x_cells,\n                                                                                                           const int64_t grid_num_y_cells,\n                                                                                                           const int64_t grid_num_z_cells,\n                                                                                                           const std::function<bool(const VoxelGrid::GRID_INDEX&)>& is_filled_fn,\n                                                                                                           const float oob_value,\n                                                                                                           const std::string& frame)\n    {\n        std::vector<VoxelGrid::GRID_INDEX> filled;\n        std::vector<VoxelGrid::GRID_INDEX> free;\n        for (int64_t x_index = 0; x_index < grid_num_x_cells; x_index++)\n        {\n            for (int64_t y_index = 0; y_index < grid_num_y_cells; y_index++)\n            {\n                for (int64_t z_index = 0; z_index < grid_num_z_cells; z_index++)\n                {\n                    const VoxelGrid::GRID_INDEX current_index(x_index, y_index, z_index);\n                    if (is_filled_fn(current_index))\n                    {\n                        // Mark as filled\n                        filled.push_back(current_index);\n                    }\n                    else\n                    {\n                        // Mark as free space\n                        free.push_back(current_index);\n                    }\n                }\n            }\n        }\n        // Make two distance fields (one for distance to filled voxels, one for distance to free voxels\n        const DistanceField filled_distance_field = BuildDistanceField(grid_origin_tranform, grid_resolution, grid_num_x_cells, grid_num_y_cells, grid_num_z_cells, filled);\n        const DistanceField free_distance_field = BuildDistanceField(grid_origin_tranform, grid_resolution, grid_num_x_cells, grid_num_y_cells, grid_num_z_cells, free);\n        // Generate the SDF\n        sdf_tools::SignedDistanceField new_sdf(grid_origin_tranform, frame, grid_resolution, grid_num_x_cells, grid_num_y_cells, grid_num_z_cells, oob_value);\n        double max_distance = -std::numeric_limits<double>::infinity();\n        double min_distance = std::numeric_limits<double>::infinity();\n        for (int64_t x_index = 0; x_index < new_sdf.GetNumXCells(); x_index++)\n        {\n            for (int64_t y_index = 0; y_index < new_sdf.GetNumYCells(); y_index++)\n            {\n                for (int64_t z_index = 0; z_index < new_sdf.GetNumZCells(); z_index++)\n                {\n                    const double distance1 = std::sqrt(filled_distance_field.GetImmutable(x_index, y_index, z_index).first.distance_square) * new_sdf.GetResolution();\n                    const double distance2 = std::sqrt(free_distance_field.GetImmutable(x_index, y_index, z_index).first.distance_square) * new_sdf.GetResolution();\n                    const double distance = distance1 - distance2;\n                    if (distance > max_distance)\n                    {\n                        max_distance = distance;\n                    }\n                    if (distance < min_distance)\n                    {\n                        min_distance = distance;\n                    }\n                    new_sdf.SetValue(x_index, y_index, z_index, distance);\n                }\n            }\n        }\n        std::pair<double, double> extrema(max_distance, min_distance);\n        return std::pair<sdf_tools::SignedDistanceField, std::pair<double, double>>(new_sdf, extrema);\n    }\n\n    template<typename T, typename BackingStore=std::vector<T>>\n    inline std::pair<sdf_tools::SignedDistanceField, std::pair<double, double>> ExtractSignedDistanceField(const VoxelGrid::VoxelGrid<T, BackingStore>& grid, const std::function<bool(const VoxelGrid::GRID_INDEX&)>& is_filled_fn, const float oob_value, const std::string& frame, const bool add_virtual_border)\n    {\n      (void)(add_virtual_border);\n      const Eigen::Vector3d cell_sizes = grid.GetCellSizes();\n      if ((cell_sizes.x() != cell_sizes.y()) || (cell_sizes.x() != cell_sizes.z()))\n      {\n        throw std::invalid_argument(\"Grid must have uniform resolution\");\n      }\n      if (add_virtual_border == false)\n      {\n        // This is the conventional single-pass result\n        return ExtractSignedDistanceField<T>(grid.GetOriginTransform(), cell_sizes.x(), grid.GetNumXCells(), grid.GetNumYCells(), grid.GetNumZCells(), is_filled_fn, oob_value, frame);\n      }\n      else\n      {\n        const int64_t x_axis_size_offset = (grid.GetNumXCells() > 1) ? (int64_t)2 : (int64_t)0;\n        const int64_t x_axis_query_offset = (grid.GetNumXCells() > 1) ? (int64_t)1 : (int64_t)0;\n        const int64_t y_axis_size_offset = (grid.GetNumYCells() > 1) ? (int64_t)2 : (int64_t)0;\n        const int64_t y_axis_query_offset = (grid.GetNumYCells() > 1) ? (int64_t)1 : (int64_t)0;\n        const int64_t z_axis_size_offset = (grid.GetNumZCells() > 1) ? (int64_t)2 : (int64_t)0;\n        const int64_t z_axis_query_offset = (grid.GetNumZCells() > 1) ? (int64_t)1 : (int64_t)0;\n        // We need to lie about the size of the grid to add a virtual border\n        const int64_t num_x_cells = grid.GetNumXCells() + x_axis_size_offset;\n        const int64_t num_y_cells = grid.GetNumYCells() + y_axis_size_offset;\n        const int64_t num_z_cells = grid.GetNumZCells() + z_axis_size_offset;\n        // Make some deceitful helper functions that hide our lies about size\n        // For the free space SDF, we lie and say the virtual border is filled\n        const std::function<bool(const VoxelGrid::GRID_INDEX&)> free_is_filled_fn\n            = [&] (const VoxelGrid::GRID_INDEX& virtual_border_grid_index)\n        {\n          // Is there a virtual border on our axis?\n          if (x_axis_size_offset > 0)\n          {\n            // Are we a virtual border cell?\n            if ((virtual_border_grid_index.x == 0)\n                || (virtual_border_grid_index.x == (num_x_cells - 1)))\n            {\n              return true;\n            }\n          }\n          // Is there a virtual border on our axis?\n          if (y_axis_size_offset > 0)\n          {\n            // Are we a virtual border cell?\n            if ((virtual_border_grid_index.y == 0)\n                || (virtual_border_grid_index.y == (num_y_cells - 1)))\n            {\n              return true;\n            }\n          }\n          // Is there a virtual border on our axis?\n          if (z_axis_size_offset > 0)\n          {\n            // Are we a virtual border cell?\n            if ((virtual_border_grid_index.z == 0)\n                || (virtual_border_grid_index.z == (num_z_cells - 1)))\n            {\n              return true;\n            }\n          }\n          const VoxelGrid::GRID_INDEX real_grid_index(\n                virtual_border_grid_index.x - x_axis_query_offset,\n                virtual_border_grid_index.y - y_axis_query_offset,\n                virtual_border_grid_index.z - z_axis_query_offset);\n          return is_filled_fn(real_grid_index);\n        };\n        // For the filled space SDF, we lie and say the virtual border is empty\n        const std::function<bool(const VoxelGrid::GRID_INDEX&)> filled_is_filled_fn\n            = [&] (const VoxelGrid::GRID_INDEX& virtual_border_grid_index)\n        {\n          // Is there a virtual border on our axis?\n          if (x_axis_size_offset > 0)\n          {\n            // Are we a virtual border cell?\n            if ((virtual_border_grid_index.x == 0)\n                || (virtual_border_grid_index.x == (num_x_cells - 1)))\n            {\n              return false;\n            }\n          }\n          // Is there a virtual border on our axis?\n          if (y_axis_size_offset > 0)\n          {\n            // Are we a virtual border cell?\n            if ((virtual_border_grid_index.y == 0)\n                || (virtual_border_grid_index.y == (num_y_cells - 1)))\n            {\n              return false;\n            }\n          }\n          // Is there a virtual border on our axis?\n          if (z_axis_size_offset > 0)\n          {\n            // Are we a virtual border cell?\n            if ((virtual_border_grid_index.z == 0)\n                || (virtual_border_grid_index.z == (num_z_cells - 1)))\n            {\n              return false;\n            }\n          }\n          const VoxelGrid::GRID_INDEX real_grid_index(\n                virtual_border_grid_index.x - x_axis_query_offset,\n                virtual_border_grid_index.y - y_axis_query_offset,\n                virtual_border_grid_index.z - z_axis_query_offset);\n          return is_filled_fn(real_grid_index);\n        };\n        // Make both SDFs\n        auto free_sdf_result = ExtractSignedDistanceField<T>(grid.GetOriginTransform(), cell_sizes.x(), num_x_cells, num_y_cells, num_z_cells, free_is_filled_fn, oob_value, frame);\n        auto filled_sdf_result = ExtractSignedDistanceField<T>(grid.GetOriginTransform(), cell_sizes.x(), num_x_cells, num_y_cells, num_z_cells, filled_is_filled_fn, oob_value, frame);\n        // Combine to make a single SDF\n        sdf_tools::SignedDistanceField combined_sdf(grid.GetOriginTransform(), frame, cell_sizes.x(), grid.GetNumXCells(), grid.GetNumYCells(), grid.GetNumZCells(), oob_value);\n        for (int64_t x_idx = 0; x_idx < combined_sdf.GetNumXCells(); x_idx++)\n        {\n          for (int64_t y_idx = 0; y_idx < combined_sdf.GetNumYCells(); y_idx++)\n          {\n            for (int64_t z_idx = 0; z_idx < combined_sdf.GetNumZCells(); z_idx++)\n            {\n              const int64_t query_x_idx = x_idx + x_axis_query_offset;\n              const int64_t query_y_idx = y_idx + y_axis_query_offset;\n              const int64_t query_z_idx = z_idx + z_axis_query_offset;\n              const float free_sdf_value\n                  = free_sdf_result.first.GetImmutable(\n                      query_x_idx, query_y_idx, query_z_idx).first;\n              const float filled_sdf_value\n                  = filled_sdf_result.first.GetImmutable(\n                      query_x_idx, query_y_idx, query_z_idx).first;\n              if (free_sdf_value >= 0.0)\n              {\n                combined_sdf.SetValue(x_idx, y_idx, z_idx, free_sdf_value);\n              }\n              else if (filled_sdf_value <= -0.0)\n              {\n                combined_sdf.SetValue(x_idx, y_idx, z_idx, filled_sdf_value);\n              }\n              else\n              {\n                combined_sdf.SetValue(x_idx, y_idx, z_idx, 0.0f);\n              }\n            }\n          }\n        }\n        // Get the combined max/min values\n        const std::pair<double, double> combined_extrema(\n              free_sdf_result.second.first, filled_sdf_result.second.second);\n        return std::make_pair(combined_sdf, combined_extrema);\n      }\n    }\n\n    template<typename T, typename BackingStore=std::vector<T>>\n    inline std::pair<sdf_tools::SignedDistanceField, std::pair<double, double>> ExtractSignedDistanceField(const VoxelGrid::VoxelGrid<T, BackingStore>& grid, const std::function<bool(const T&)>& is_filled_fn, const float oob_value, const std::string& frame)\n    {\n        const std::function<bool(const VoxelGrid::GRID_INDEX&)> real_is_filled_fn = [&] (const VoxelGrid::GRID_INDEX& index)\n        {\n            const T& stored = grid.GetImmutable(index).first;\n            // If it matches an object to use OR there are no objects supplied\n            if (is_filled_fn(stored))\n            {\n                // Mark as filled\n                return true;\n            }\n            else\n            {\n                // Mark as free space\n                return false;\n            }\n        };\n        return ExtractSignedDistanceField(grid, real_is_filled_fn, oob_value, frame, false);\n    }\n}\n\n#endif // SDF_GENERATION_HPP\n", "meta": {"hexsha": "c447253cb40a427696eec9b3b5707b07adacad8b", "size": 21916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sdf_tools/sdf_generation.hpp", "max_stars_repo_name": "hujiawei-sjtu/sdf_tools", "max_stars_repo_head_hexsha": "deefe5f03c062b8f312d35b3d30202f7462b3000", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 159.0, "max_stars_repo_stars_event_min_datetime": "2017-04-27T00:30:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:35:19.000Z", "max_issues_repo_path": "include/sdf_tools/sdf_generation.hpp", "max_issues_repo_name": "hujiawei-sjtu/sdf_tools", "max_issues_repo_head_hexsha": "deefe5f03c062b8f312d35b3d30202f7462b3000", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2017-08-22T23:45:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-04T01:59:59.000Z", "max_forks_repo_path": "include/sdf_tools/sdf_generation.hpp", "max_forks_repo_name": "hujiawei-sjtu/sdf_tools", "max_forks_repo_head_hexsha": "deefe5f03c062b8f312d35b3d30202f7462b3000", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2017-03-16T23:01:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T12:50:23.000Z", "avg_line_length": 49.2494382022, "max_line_length": 308, "alphanum_fraction": 0.5257802519, "num_tokens": 4552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396211, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.43330629474861343}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C)  2017 Cord Harms\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file localcorrsurface.hpp\n    \\brief Local Correlation surface derived ....\n*/\n\n#include <ql/experimental/termstructures/Helper/ParticleMethodUtils.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/experimental/templatemodels/multiasset/localcorrelationSLVmodel.hpp>\n#include <ql/experimental/templatemodels/montecarlo/montecarlomodells.hpp>\n#include <ql/experimental/templatemodels/montecarlo/mcpayoffT.hpp>\n#include <ql/math/interpolations/linearinterpolation.hpp>\n#include <math.h>\n#include <boost/math/distributions.hpp>\n#include <boost/shared_ptr.hpp>\n#include <ql\\pricingengines\\blackscholescalculator.hpp>\n\nnamespace QuantLib {\n\n\tvoid ParticleMethodUtils::calibrateFX(Handle<LocalCorrSurfaceABFFX>& surface, const std::string& kernelIn, unsigned int numberOfPaths, Time maxTime,\n\t\tTime deltaT, Time tMin, Real kappa, Real sigmaAVR, Real exponentN, Real gridMinQuantile,\n\t\tReal gridMaxQuantile, unsigned int ns1, unsigned int ns2) {\n\t\t\n\t\tboost::shared_ptr<KernelInterface> kernel;\n\n\t\tif (kernelIn == \"QuarticKernel\") {\n\t\t\tkernel = boost::shared_ptr<KernelInterface>(new QuarticKernel());\n\t\t}\n\t\telse {\n\t\t\tQL_REQUIRE(false, \"Kernel not supported. Supported is: QuarticKernel\");\n\t\t}\n\n\t\tstd::vector<boost::shared_ptr<QuantLib::HestonSLVProcess>> processes = surface->getProcesses();\n\t\tboost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>\t\t\t    processToCal= surface->getProcessToCal();\n\n\t\t//build assetModel for simulation\n\t\tboost::shared_ptr<YieldTermStructure> yld(new FlatForward(processToCal->blackVolatility()->referenceDate(),0, processToCal->blackVolatility()->dayCounter()));\n\t\tHandle<YieldTermStructure> yldH = Handle<YieldTermStructure>(yld);\n\t\tstd::vector<std::string> aliases(2);\n\t\taliases[0] = \"fx1\";\n\t\taliases[1] = \"fx2\";\n\t\tHandle<LocalCorrTermStructure> surfaceGen(surface.currentLink());\n\t\tboost::shared_ptr<LocalCorrelationSLVModel> assetModel = boost::shared_ptr<LocalCorrelationSLVModel>((new LocalCorrelationSLVModel(yldH, aliases, processes, surfaceGen)));\n\n\t\tstd::vector<Time>& times = surface->getTimes();\n\t\tstd::vector<std::vector<Real>>& strikes = surface->getStrikes();\n\t\tstd::vector<std::vector<Real>>& surfaceF = surface->getSurfaceF();\n\n\t\t//time grid from t=0 to maxTime:\n\t\ttimes.resize(1);\n\t\ttimes[0] = 0;\n\t\tsize_t i = 0;\n\t\twhile (times[i] < maxTime) {\n\t\t\ttimes.push_back(times[i]+deltaT);\n\t\t\ti++;\n\t\t}\n\t\tsurface->setInterpolationTime<Linear>();\n\n\t\tRealMCSimulation simulation(assetModel, times, times, numberOfPaths,1,true,true,false);\n\t\tsimulation.prepareForSlicedSimulation();\n\t\tsimulation.simulate(0, false);\n\n\t\t//create strike grid. \n\t\t//the strike grid depends on simulation results (min and max quantile)\n\t\t//the simulation itself depends on local correlation which itself is calibrated using this function.\n\t\t//Consequence: strike grid can merely be calculated iteratively during calibration\n\t\t\n\t\tsize_t numberStrikes;\n\t\tReal strikeStep;\n\t\tsurfaceF.resize(times.size());\n\t\tstrikes.resize(times.size());\n\t\tstd::vector<Real> state;\n\t\tstd::vector<Real> assets(2);\n\t\tstd::vector<Real> crossFX(numberOfPaths);\n\n\t\tReal vol1;\n\t\tReal vol2;\n\t\tstd::vector<Real> vol3;\n\t\tstd::vector<Real> eNum;\n\t\tstd::vector<Real> eDen;\n\t\tstd::vector<Real> eScale;\n\t\tReal a = 0;\n\t\tReal b = 0;\n\t\tReal kernelV = 0;\n\t\tReal bandwidth = 0;\n\t\tReal minPosBw;\n\t\tReal maxNegBw;\n\t\tReal bwIn;\n\t\tReal bwRatio;\n\n\t\t//Calculate local correlation successively over time\n\n\t\tfor (size_t i = 1; i < surfaceF.size()-1; i++) //iteration over time, for i=0 nothing to do as correlation independent of a,b,f. In last entry, no additional simulation necessary.\n\t\t{\n\t\t\tnumberStrikes = numberStrikeGrid(times[i],ns1,ns2);\n\t\t\tQL_REQUIRE(numberStrikes>1,\"ns1 or ns2 has to be increased, strike grid cannot be calculated.\");\n\t\t\tsimulation.simulate(i,false);\n\n\t\t\t//Now strike grid can be calculated\n\n\t\t\tsurfaceF[i].resize(numberStrikes);\n\t\t\tstrikes[i].resize(numberStrikes);\n\t\t\tfor (size_t k = 0; k < numberOfPaths; k++)\n\t\t\t{\n\t\t\t\tstate = simulation.state(k, times[i]);\n\t\t\t\tassets[0] = processes[0]->s0()->value() * std::exp(state[0]);\n\t\t\t\tassets[1] = processes[1]->s0()->value() * std::exp(state[1]);\n\t\t\t\tcrossFX[k] = getCrossFX(assets[0] , assets[1]);\n\t\t\t}\n\n\t\t\tstd::sort(crossFX.begin(),crossFX.end());\n\n\t\t\tstrikes[i][0] = crossFX[(size_t)(numberOfPaths*gridMinQuantile)];\n\t\t\tstrikes[i][strikes[i].size()-1] = crossFX[(size_t)(numberOfPaths*gridMaxQuantile)];\n\n\t\t\tstrikeStep = (strikes[i][strikes[i].size() - 1] - strikes[i][0]) / (numberStrikes-1);\n\n\t\t\tQL_ASSERT(strikeStep > 0, \"Error. StrikeStep shouldn't be zero for time \" << times[i] << \". Check volatility.\");\n\n\t\t\tbandwidth = ParticleMethodUtils::bandwidth(times[i], getCrossFX(processes[0]->s0()->value(),processes[1]->s0()->value()), kappa, sigmaAVR, tMin, numberOfPaths, exponentN);\n\n\t\t\tfor (size_t j = 1; j < strikes[i].size()-1; j++)\n\t\t\t{\n\t\t\t\tstrikes[i][j] = strikes[i][j-1] + strikeStep;\n\t\t\t}\n\n\t\t\t//Particle method for that time step \n\n\t\t\teNum.resize(strikes[i].size());\n\t\t\teDen.resize(strikes[i].size());\n\t\t\teScale.resize(strikes[i].size());\n\t\t\tvol3.resize(strikes[i].size());\n\n\t\t\tfor (size_t j = 0; j < strikes[i].size(); j++)\n\t\t\t{\n\t\t\t\teNum[j] = 0;\n\t\t\t\teDen[j] = 0;\n\t\t\t\teScale[j] = 0;\n\t\t\t\tvol3[j] = processToCal->localVolatility()->localVol(times[i], strikes[i][j], true);\n\t\t\t}\n\n\t\t\tfor (size_t k = 0; k < numberOfPaths; k++) //particle method: over MC paths\n\t\t\t{\n\t\t\t\tstate = simulation.state(k, times[i]);\n\n\t\t\t\tassets[0] = processes[0]->s0()->value() * std::exp(state[0]);\n\t\t\t\tassets[1] = processes[1]->s0()->value() * std::exp(state[1]);\n\n\t\t\t\tstate[2] = state[2] < 0 ? 0.0001 : state[2];//heston vol might become negative (dep. on feller constant)\n\t\t\t\tstate[3] = state[3] < 0 ? 0.0001 : state[3];\n\n\t\t\t\tvol1 = processes[0]->leverageFct()->localVol(times[i], assets[0], true)*std::sqrt(state[2]); //*ai from Heston\n\t\t\t\tvol2 = processes[1]->leverageFct()->localVol(times[i], assets[1], true)*std::sqrt(state[3]);\n\n\t\t\t\ta = surface->localA(times[i], assets, true);\n\t\t\t\tb = surface->localB(times[i], assets, true);\n\n\t\t\t\tif (vol1 != vol1 || vol2 != vol2)\n\t\t\t\t\tQL_FAIL(\"surface of asset1 oder asset2 not well defined\");\n\n\t\t\t\tfor (size_t j = 0; j < surfaceF[i].size(); j++) //iteration over strike dimension\n\t\t\t\t{\n\n\t\t\t\t\tminPosBw = 10000000;\n\t\t\t\t\tmaxNegBw = -10000000;\n\n\t\t\t\t\tbwIn = getCrossFX(assets[0], assets[1]) - strikes[i][j];\n\t\t\t\t\tbwRatio = bwIn / bandwidth;\n\n\t\t\t\t\tif (bwRatio > maxNegBw && bwRatio <= 0) maxNegBw = bwRatio;\n\t\t\t\t\tif (bwRatio < minPosBw && bwRatio >= 0) minPosBw = bwRatio;\n\n\t\t\t\t\tkernelV = assets[1] * ParticleMethodUtils::kernel(bandwidth, bwIn, kernel);\n\n\t\t\t\t\teNum[j] += (vol1*vol1 + vol2*vol2 + 2 * a*vol1*vol2 / b)*kernelV;\n\t\t\t\t\teDen[j] += vol1*vol2*kernelV / b;\n\t\t\t\t\teScale[j] += kernelV;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tfor (size_t j = 0; j < surfaceF[i].size(); j++) //iteration over strike dimension\n\t\t\t{\n\t\t\t\tQL_REQUIRE(eScale[j] != 0, std::string(\"ParticleMethodUtils::calibrateFX: resulting bandwidth is too small for calibration (support: < \") + std::to_string(maxNegBw)\n\t\t\t\t\t+ std::string(\" and > \") + std::to_string(minPosBw)\n\t\t\t\t\t+ std::string(\"). Either decrease number of MC paths or increase exponentN or kappa.\"));\n\t\t\t\tif (eNum[j] != eNum[j] || vol3 != vol3 || eScale[j] != eScale[j] || eDen[j] != eDen[j] || eDen[j] == 0)\n\t\t\t\t\tQL_FAIL(\"surface not well defined.\");\n\t\t\t\tsurfaceF[i][j] = (eNum[j] - vol3[j] * vol3[j]* eScale[j]) / (2 * eDen[j]);\n\t\t\t}\n\t\t\t//set interpolation on new dimension:\n\t\t\tsurface->setInterpolationStrike<Linear>(i);\n\t\t}\n\t}\t  \n\n\tvoid ParticleMethodUtils::calibrateIndex(Handle<LocalCorrSurfaceABFIndex>& surface, const std::string& kernelIn, unsigned int numberOfPaths, Time maxTime,\n\t\tTime deltaT, Time tMin, Real kappa, Real sigmaAVR, Real exponentN, Real gridMinQuantile,\n\t\tReal gridMaxQuantile, unsigned int ns1, unsigned int ns2) {\n\n\t\tboost::shared_ptr<KernelInterface> kernel;\n\n\t\tif (kernelIn == \"QuarticKernel\") {\n\t\t\tkernel = boost::shared_ptr<KernelInterface>(new QuarticKernel());\n\t\t}\n\t\telse {\n\t\t\tQL_REQUIRE(false, \"Kernel not supported. Supported is: QuarticKernel\");\n\t\t}\n\n\t\tstd::vector<boost::shared_ptr<QuantLib::HestonSLVProcess>> processes = surface->getProcesses();\n\t\tboost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>\t\t\t    processToCal = surface->getProcessToCal();\n\n\t\t//build assetModel for simulation\n\t\tboost::shared_ptr<YieldTermStructure> yld(new FlatForward(processToCal->blackVolatility()->referenceDate(), 0, processToCal->blackVolatility()->dayCounter()));\n\t\tHandle<YieldTermStructure> yldH = Handle<YieldTermStructure>(yld);\n\t\tstd::vector<std::string> aliases(2);\n\t\taliases[0] = \"index1\";\n\t\taliases[1] = \"index2\";\n\t\tHandle<LocalCorrTermStructure> surfaceGen(surface.currentLink());\n\t\tboost::shared_ptr<LocalCorrelationSLVModel> assetModel = boost::shared_ptr<LocalCorrelationSLVModel>((new LocalCorrelationSLVModel(yldH, aliases, processes, surfaceGen)));\n\n\t\tstd::vector<Time>& times = surface->getTimes();\n\t\tstd::vector<std::vector<Real>>& strikes = surface->getStrikes();\n\t\tstd::vector<std::vector<Real>>& surfaceF = surface->getSurfaceF();\n\n\t\t//time grid from t=0 to maxTime:\n\t\ttimes.resize(1);\n\t\ttimes[0] = 0;\n\t\tsize_t i = 0;\n\t\twhile (times[i] < maxTime) {\n\t\t\ttimes.push_back(times[i] + deltaT);\n\t\t\ti++;\n\t\t}\n\t\tsurface->setInterpolationTime<Linear>();\n\n\t\tRealMCSimulation simulation(assetModel, times, times, numberOfPaths, 1, true, true, false);\n\t\tsimulation.prepareForSlicedSimulation();\n\t\tsimulation.simulate(0, false);\n\n\t\t//create strike grid. \n\t\t//the strike grid depends on simulation results (min and max quantile)\n\t\t//the simulation itself depends on local correlation which itself is calibrated using this function.\n\t\t//Consequence: strike grid can merely be calculated iteratively during calibration\n\n\t\tsize_t numberStrikes;\n\t\tReal strikeStep;\n\t\tsurfaceF.resize(times.size());\n\t\tstrikes.resize(times.size());\n\t\tstd::vector<Real> state;\n\t\tstd::vector<Real> assets(processes.size());\n\t\tstd::vector<Real> indexVals(numberOfPaths);\n\n\t\tstd::vector<Real> vol(processes.size());\n\t\tstd::vector<Real> vol3;\n\t\tstd::vector<Real> eNum;\n\t\tstd::vector<Real> eDen;\n\t\tstd::vector<Real> eScale;\n\t\tReal a = 0;\n\t\tReal b = 0;\n\t\tReal kernelV = 0;\n\t\tReal bandwidth = 0;\n\t\tReal minPosBw;\n\t\tReal maxNegBw;\n\t\tReal bwIn;\n\t\tReal bwRatio;\n\t\tdouble indexStart;\n\t\t\n\t\t//Calculate local correlation successively over time\n\n\t\tfor (size_t i = 1; i < surfaceF.size() - 1; i++) //iteration over time, for i=0 nothing to do as correlation independent of a,b,f. In last entry, no additional simulation necessary.\n\t\t{\n\t\t\tnumberStrikes = numberStrikeGrid(times[i], ns1, ns2);\n\t\t\tQL_REQUIRE(numberStrikes>1, \"ns1 or ns2 has to be increased, strike grid cannot be calculated.\");\n\t\t\tsimulation.simulate(i, false);\n\n\t\t\t//Now strike grid can be calculated\n\n\t\t\tsurfaceF[i].resize(numberStrikes);\n\t\t\tstrikes[i].resize(numberStrikes);\n\t\t\tfor (size_t k = 0; k < numberOfPaths; k++)\n\t\t\t{\n\t\t\t\tstate = simulation.state(k, times[i]);\n\t\t\t\tindexVals[k] = surface->localFStrike(times[i],state);\n\t\t\t}\n\n\t\t\tstd::sort(indexVals.begin(), indexVals.end());\n\n\t\t\tstrikes[i][0] = indexVals[(size_t)(numberOfPaths*gridMinQuantile)];\n\t\t\tstrikes[i][strikes[i].size() - 1] = indexVals[(size_t)(numberOfPaths*gridMaxQuantile)];\n\n\t\t\tstrikeStep = (strikes[i][strikes[i].size() - 1] - strikes[i][0]) / (numberStrikes - 1);\n\t\t\tQL_ASSERT(strikeStep > 0, \"Error. StrikeStep shouldn't be zero for time \" << times[i] << \". Check volatility.\");\n\t\t\tindexStart = surface->localFStrike(times[i], std::vector<Real>(processes.size(), 0));\n\n\t\t\tbandwidth = ParticleMethodUtils::bandwidth(times[i], abs(indexStart)>1 ? abs(indexStart) : 1, kappa, sigmaAVR, tMin, numberOfPaths, exponentN);\n\n\t\t\tfor (size_t j = 1; j < strikes[i].size() - 1; j++)\n\t\t\t{\n\t\t\t\tstrikes[i][j] = strikes[i][j - 1] + strikeStep;\n\t\t\t}\n\n\t\t\t//Particle method for that time step \n\n\t\t\teNum.resize(strikes[i].size());\n\t\t\teDen.resize(strikes[i].size());\n\t\t\teScale.resize(strikes[i].size());\n\t\t\tvol3.resize(strikes[i].size());\n\n\t\t\tfor (size_t j = 0; j < strikes[i].size(); j++)\n\t\t\t{\n\t\t\t\teNum[j] = 0;\n\t\t\t\teDen[j] = 0;\n\t\t\t\teScale[j] = 0;\n\t\t\t\tif (surface->possibleNegativeIndex()) {\n\t\t\t\t\tvol3[j] = getLocalVolFromPriceFormula(processToCal,strikes[i][j],times[i],surface->getProcessToCalBlackVolShift());\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tvol3[j] = processToCal->localVolatility()->localVol(times[i], strikes[i][j], true);\n\t\t\t}\n\n\t\t\tfor (size_t k = 0; k < numberOfPaths; k++) //particle method: over MC paths\n\t\t\t{\n\t\t\t\tstate = simulation.state(k, times[i]);\n\n\t\t\t\tfor (size_t j = 0; j < assets.size(); j++)\n\t\t\t\t{\n\t\t\t\t\tassets[j] = processes[j]->s0()->value() * std::exp(state[j]);\n\t\t\t\t\tstate[j+processes.size()] = state[j + processes.size()] < 0 ? 0.0001 : state[j + processes.size()];//heston vol might become negative (dep. on feller constant)\n\t\t\t\t\tvol[j] = processes[j]->leverageFct()->localVol(times[i], assets[j], true)*std::sqrt(state[j + processes.size()]); //*ai from Heston\n\t\t\t\t\tif (vol[j] != vol[j])\n\t\t\t\t\t\tQL_FAIL(std::string(\"surface of asset \") + std::to_string(j) + std::string(\" not well defined\"));\n\t\t\t\t}\n\n\t\t\t\tReal vol0 = surface->getIndexCovariance(LocalCorrSurfaceABFIndex::CTSIndexCovarianceType::CORR0, assets, vol);\n\t\t\t\tReal vol1 = surface->getIndexCovariance(LocalCorrSurfaceABFIndex::CTSIndexCovarianceType::CORR1, assets, vol);\n\n\t\t\t\ta = surface->localA(times[i], assets, true);\n\t\t\t\tb = surface->localB(times[i], assets, true);\n\n\t\t\t\tReal indexVal = surface->localFStrike(times[i], state);\n\n\t\t\t\tfor (size_t j = 0; j < surfaceF[i].size(); j++) //iteration over strike dimension\n\t\t\t\t{\n\n\t\t\t\t\tminPosBw = 10000000;\n\t\t\t\t\tmaxNegBw = -10000000;\n\n\t\t\t\t\tbwIn = indexVal - strikes[i][j];\n\t\t\t\t\tbwRatio = bwIn / bandwidth;\n\n\t\t\t\t\tif (bwRatio > maxNegBw && bwRatio <= 0) maxNegBw = bwRatio;\n\t\t\t\t\tif (bwRatio < minPosBw && bwRatio >= 0) minPosBw = bwRatio;\n\n\t\t\t\t\tkernelV = ParticleMethodUtils::kernel(bandwidth, bwIn, kernel);\n\n\t\t\t\t\teNum[j] += (vol0 - a*(vol1-vol0) / b)*kernelV;\n\t\t\t\t\teDen[j] += (vol1 - vol0)*kernelV / b;\n\t\t\t\t\teScale[j] += kernelV;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (size_t j = 0; j < surfaceF[i].size(); j++) //iteration over strike dimension\n\t\t\t{\n\t\t\t\tQL_REQUIRE(eScale[j] != 0, std::string(\"ParticleMethodUtils::calibrateIndex: resulting bandwidth is too small for calibration (support: < \") + std::to_string(maxNegBw)\n\t\t\t\t\t+ std::string(\" and > \") + std::to_string(minPosBw)\n\t\t\t\t\t+ std::string(\"). Either decrease number of MC paths or increase exponentN or kappa.\"));\n\t\t\t\tif (eNum[j] != eNum[j] || vol3[j] != vol3[j] || eScale[j] != eScale[j] || eDen[j] != eDen[j] || eDen[j] == 0)\n\t\t\t\t\tQL_FAIL(\"surface not well defined.\");\n\t\t\t\tif (surface->possibleNegativeIndex()) {\n\t\t\t\t\tsurfaceF[i][j] = (vol3[j] * eScale[j] - eNum[j]) / (eDen[j]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tsurfaceF[i][j] = ( vol3[j] * vol3[j] * strikes[i][j]* strikes[i][j] * eScale[j]- eNum[j]) / (eDen[j]);\n\t\t\t}\n\t\t\t//set interpolation on new dimension:\n\t\t\tsurface->setInterpolationStrike<Linear>(i);\n\t\t}\n\t}\n\n\n\tReal ParticleMethodUtils::bandwidth(Time t, Real s0, Real kappa, Real sigmaAVR, Real tMin, unsigned int numberOfPaths, Real exponentN) {\n\t\tReal mult = pow(numberOfPaths, exponentN);\n\t\treturn kappa*sigmaAVR* s0 * sqrt(t>tMin ? t : tMin) * mult;\n\t}\n\n\tReal ParticleMethodUtils::kernel(Real bandwidth, Real x, boost::shared_ptr<KernelInterface>& kernel) {\n\t\tQL_REQUIRE(bandwidth != 0, \"Error in ParticleMethodUtils: bandwidth is not allowed to be zero.\");\n\t\treturn kernel->value(x / bandwidth) / bandwidth;\n\t}\n\tsize_t ParticleMethodUtils::numberStrikeGrid(Time t, unsigned int ns1, unsigned int ns2) {\n\t\tReal numberOfStrikes = ns1*sqrt(t);\n\t\treturn (numberOfStrikes > ns2) ? ((size_t)numberOfStrikes) : (ns2);\n\t}\n\t\n\tReal ParticleMethodUtils::getCrossFX(Real asset1, Real asset2) {\n\t\treturn asset1 / asset2;\n\t}\n\n\tReal ParticleMethodUtils::getLocalVolFromPriceFormula(boost::shared_ptr<QuantLib::GeneralizedBlackScholesProcess>& processToCal, Real strike, Time t, Real indShift) {\n\t\tdouble negIndVol;\n\t\tdouble negIndPriceT;\n\t\tdouble negIndPrice;\n\t\tdouble negIndPriceUp;\n\t\tdouble negIndPriceDn;\n\t\tdouble negIndTimeBmp = 0.0001;\n\t\tdouble negIndAssetBmp = 0.001;\n\t\tdouble negIndAsset;\n\t\tdouble dCdt;\n\t\tdouble dCdKdK;\n\t\tdouble dCdK;\n\n\t\tnegIndVol = processToCal->blackVolatility()->blackVol(t, strike, true);\n\t\tnegIndPrice = BlackScholesCalculator(Option::Type::Call, strike + indShift, processToCal->x0() + indShift, processToCal->dividendYield()->discount(t),\n\t\t\tnegIndVol*sqrt(t), processToCal->riskFreeRate()->discount(t)).value();\n\n\t\tnegIndVol = processToCal->blackVolatility()->blackVol(t + negIndTimeBmp, strike, true);\n\t\tnegIndPriceT = BlackScholesCalculator(Option::Type::Call, strike + indShift, processToCal->x0() + indShift, processToCal->dividendYield()->discount(t + negIndTimeBmp),\n\t\t\tnegIndVol*sqrt(t + negIndTimeBmp), processToCal->riskFreeRate()->discount(t + negIndTimeBmp)).value();\n\n\t\tdCdt = (negIndPriceT - negIndPrice) / negIndTimeBmp;\n\n\t\tnegIndAsset = strike>1 ? strike * (1 + negIndAssetBmp) : strike + negIndAssetBmp;\n\t\tnegIndVol = processToCal->blackVolatility()->blackVol(t, negIndAsset, true);\n\t\tnegIndPriceUp = BlackScholesCalculator(Option::Type::Call, negIndAsset + indShift, processToCal->x0() + indShift, processToCal->dividendYield()->discount(t),\n\t\t\tnegIndVol*sqrt(t), processToCal->riskFreeRate()->discount(t)).value();\n\n\t\tnegIndAsset = strike>1 ? strike * (1 - negIndAssetBmp) : strike - negIndAssetBmp;\n\t\tnegIndVol = processToCal->blackVolatility()->blackVol(t, negIndAsset, true);\n\t\tnegIndPriceDn = BlackScholesCalculator(Option::Type::Call, negIndAsset + indShift, processToCal->x0() + indShift, processToCal->dividendYield()->discount(t),\n\t\t\tnegIndVol*sqrt(t), processToCal->riskFreeRate()->discount(t)).value();\n\n\t\tnegIndAsset = strike>1 ? negIndAssetBmp*strike : negIndAssetBmp;\n\t\tdCdKdK = (negIndPriceUp - 2 * negIndPrice + negIndPriceDn) / (negIndAsset * negIndAsset);\n\t\t\n\t\tdCdK = (negIndPriceUp - negIndPriceDn) / (2 * negIndAsset);\n\n\t\tReal rate = processToCal->riskFreeRate()->zeroRate(t, Compounding::Continuous);\n\t\tReal div = processToCal->dividendYield()->zeroRate(t, Compounding::Continuous);\n\n\t\tQL_REQUIRE(abs(dCdKdK) > QL_EPSILON, \"local vol for cross asset delivers NaN (t=\" << t << \", strike=\" << strike << \")\");\n\n\t\treturn 2 * (dCdt + strike * dCdK*(rate-div) + div*negIndPrice) / dCdKdK;\n\n\t}\n}\n", "meta": {"hexsha": "25b9845a30901fe6ca447691e67da807e4b211ea", "size": 18932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/termstructures/Helper/ParticleMethodUtils.cpp", "max_stars_repo_name": "cordharms/QuantLib", "max_stars_repo_head_hexsha": "f401fb61e02e82ba1d546e373e5652c961fcdf9e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/experimental/termstructures/Helper/ParticleMethodUtils.cpp", "max_issues_repo_name": "cordharms/QuantLib", "max_issues_repo_head_hexsha": "f401fb61e02e82ba1d546e373e5652c961fcdf9e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-05-17T06:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:08:46.000Z", "max_forks_repo_path": "ql/experimental/termstructures/Helper/ParticleMethodUtils.cpp", "max_forks_repo_name": "cordharms/QuantLib", "max_forks_repo_head_hexsha": "f401fb61e02e82ba1d546e373e5652c961fcdf9e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:16:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:16:13.000Z", "avg_line_length": 41.0672451193, "max_line_length": 183, "alphanum_fraction": 0.68962603, "num_tokens": 5738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4333062895363696}}
{"text": "//\n//  main.cpp\n//  HRMeasure\n//\n//  Created by WuH on 2017/6/26.\n//  Copyright © 2017年 WuH. All rights reserved.\n//\n#include \"opencv2/core/core_c.h\"\n#include <dlib/image_processing/frontal_face_detector.h>\n#include <dlib/image_processing/render_face_detections.h>\n#include <dlib/image_processing.h>\n#include <dlib/gui_widgets.h>\n#include <dlib/image_io.h>\n#include <dlib/image_processing.h>\n#include <dlib/opencv/cv_image.h>\n\n#include <iostream>\n#include <opencv2/opencv.hpp>\n#include <opencv2/highgui.hpp>\n#include <queue>\n#include <cmath>\n#include <time.h>\n#include <chrono>\n#include <pthread.h>\n#include <armadillo>\n#include <itpp/signal/fastica.h>\n#include <stdlib.h>\n#include \"matplotlibcpp.h\"\n\nusing namespace dlib;\nusing namespace cv;\nusing namespace std;\nusing namespace std::chrono;\nusing namespace arma;\nusing namespace itpp;\nnamespace plt = matplotlibcpp;\n\nstruct Frame {\npublic:\n    cv::Mat frame;\n    double time;\n};\n\nstruct ROI {\npublic:\n    cv::Mat roi;\n    double time;\n};\n\n#define MAXT 201\nmilliseconds start_time;\nbool isCalculating;\nbool isDetecting;\npthread_t cal_thread;\npthread_t roi_thread;\nstd::queue<Frame> frames;\n\nCascadeClassifier faces_cascade;\n\n\n\nstruct RGB_color\n{\npublic:\n    double r, g, b;\n    RGB_color() {}\n    RGB_color(double _r,double _g, double _b):r(_r), g(_g), b(_b) {}\n    RGB_color(const RGB_color & A) {r = A.r, g = A.g, b = A.b;}\n};\n\nclass Signal\n{\nprivate:\n    RGB_color sig[MAXT];\n    double times[MAXT];\n    int nowT, headT;\n    bool flag;\npublic:\n    Signal() {nowT = headT = 0; flag = 0;}\n    /* Insert avg. color of ROI */\n    void insert(const RGB_color & a, const double & time)\n    {\n        sig[nowT] = a;\n        times[nowT] = time;\n        nowT = (nowT + 1) % MAXT;\n        if(nowT == headT) headT = (headT + 1) % MAXT, flag = 1;\n    }\n    bool full() {return flag;}\n    /* Calculate BVP */\n    double calc_BVP()\n    {\n        /* filter */\n        /* undo */\n        /* SOBI */\n        int nows = (nowT - headT + MAXT) % MAXT;\n        if(nows < 100) return 0.0;\n        double sel = -10000.0;\n        int sel_i = 0;\n        arma::mat tmp;\n        rowvec even_times = linspace<rowvec>(times[headT], times[nowT - 1], nows);\n        rowvec timesv = zeros<rowvec>(nows);\n        for(int i = headT, j = 0; i != nowT; i = (i + 1) % MAXT, j++) timesv(j) = times[i];\n        tmp.set_size(3, nows);\n        for(int i = headT, j = 0; i != nowT; i = (i + 1) % MAXT, j++)\n        {\n            tmp(0, j) = sig[i].r;\n            tmp(1, j) = sig[i].g;\n            tmp(2, j) = sig[i].b;\n        }\n        \n        \n        std::vector<double> rgbx(nows), rgby(nows);\n        for (int i = 0; i < nows; i++) {\n            rgbx.at(i) = i;\n            rgby.at(i) = tmp(0,i);\n        }\n        \n        plt::plot(rgbx, rgby);\n        plt::title(\"rgb red\");\n        plt::legend();\n        plt::save(\"/Users/apple/Desktop/testpics/rgbred.png\");\n        \n        for (int i = 0; i < nows; i++) {\n            rgbx.at(i) = i;\n            rgby.at(i) = tmp(1,i);\n        }\n        \n        plt::figure();\n        plt::plot(rgbx, rgby);\n        plt::title(\"rgb green\");\n        plt::legend();\n        plt::save(\"/Users/apple/Desktop/testpics/rgbgreen.png\");\n        \n        for (int i = 0; i < nows; i++) {\n            rgbx.at(i) = i;\n            rgby.at(i) = tmp(2,i);\n        }\n        \n        plt::figure();\n        plt::plot(rgbx, rgby);\n        plt::title(\"rgb blue\");\n        plt::legend();\n        plt::save(\"/Users/apple/Desktop/testpics/rgbblue.png\");\n\n        \n        for(int i = 0; i < 3; ++i)\n        {\n            double avg = mean(tmp.row(i)), std = stddev(tmp.row(i));\n            tmp.row(i).transform([avg, std](double x) {return (x - avg) / (std + 0.0001);});\n        }\n        cout << \"START SOBI!\" << endl;\n        arma::mat H;\n        SOBI(tmp, 3, 20, H);\n        cout << \"END SOBI!\" << endl;\n        arma::mat sur = H * tmp;\n        cx_mat raws;\n        for(int i = 0; i < 3; ++i)\n        {\n            rowvec tmp3;\n            interp1(timesv, sur.row(i), even_times, tmp3);\n            sur.row(i) = tmp3;\n            raws = fft(sur.row(i));\n            double tmp2 = kurt(abs(raws));\n            if(tmp2 > sel)\n                sel = tmp2, sel_i = i;\n        }\n        rowvec sor = sur.row(sel_i);\n        cout << \"End Select\" << endl;\n        /* End of SOBI */\n        /* Calculate BVP */\n        raws = fft(sor);\n        \n        cout<<\"&&&&&&&&&\"<< abs(raws) <<endl;\n        double ans = 0, BVP = 0;\n        for(int i = 0; i < nows / 2 + 1; ++i)\n        {\n            if (abs(raws(i)) > ans && ((double)i) / (even_times[nows - 1] - even_times[0]) * 60 > 40\n                        && ((double)i) / (even_times[nows - 1] - even_times[0]) * 60< 200)\n                ans = abs(raws(i)), BVP = ((double)i) / (even_times[nows - 1] - even_times[0]) * 60;\n        }\n        \n\n        cout << \"BVP is: \" << BVP << endl;\n        return BVP;\n        /* End of Calculate */\n    }\n    \n    /* Helper Function */\n    double sqr(double x)\n    {\n        return x * x;\n    }\n    double kurt(const rowvec & A)\n    {\n        int n = A.size();\n        double B4 = 0.0, B2 = 0.0;\n        for(int i = 0; i < n; ++i)\n            B4 += sqr(sqr(A(i))), B2 += sqr(A(i));\n        return B4 * n / (B2 * B2) - 3;\n    }\n    \n    void stdcov(const arma::mat & X, int tau, arma::mat & C)\n    {\n        int N = X.n_cols, m = X.n_rows;\n        arma::vec m1 = zeros<arma::vec>(m), m2 = zeros<arma::vec>(m);\n        arma::mat R = X.cols(0, N - tau - 1) * X.cols(tau, N - 1).t() / (N - tau);\n        for(int i = 0; i < m; ++i)\n        {\n            m1[i] = mean(X.row(i).cols(0, N - tau - 1));\n            m2[i] = mean(X.row(i).cols(tau, N - 1));\n        }\n        C = R - m1 * m2.t();\n        C = (C + C.t()) / 2;\n    }\n    void joint_diag(const arma::mat & A, double jthresh, cx_mat & V, cx_mat & D)\n    {\n        int m = A.n_rows, nm = A.n_cols;\n        arma::mat b1 = zeros<arma::mat>(3, 3), b2 = zeros<arma::mat>(3, 3);\n        b1 << 1 << 0 << 0 << endr << 0 << 1 << 1 << endr << 0 << 0 << 0 << endr;\n        b2 << 0 << 0 << 0 << endr << 0 << 0 << 0 << endr << 0 << -1 << 1 << endr;\n        cx_mat B = cx_mat(b1, b2);\n        cx_mat Bt = B.t();\n        cx_mat Ip = zeros<cx_mat>(1, nm);\n        cx_mat Iq = zeros<cx_mat>(1, nm);\n        cx_mat g = zeros<cx_mat>(3, m);\n        cx_mat G = zeros<cx_mat>(2, 2);\n        arma::vec ev = zeros<arma::vec>(3);\n        arma::mat vcp = zeros<arma::mat>(3, 3);\n        double c = 0;\n        cx_double s = 0;\n        V = eye<cx_mat>(m, m);\n        D = zeros<cx_mat>(m, nm);\n        D.set_real(A);\n        for(int encore = 1; encore;)\n        {\n            encore = 0;\n            for(int p = 0; p < m - 1; ++p)\n                for(int q = p + 1; q < m; ++q)\n                {\n                    cx_rowvec t1 = zeros<cx_rowvec>(nm / m), t2 = zeros<cx_rowvec>(nm / m);\n                    cx_rowvec t3 = zeros<cx_rowvec>(nm / m), t4 = zeros<cx_rowvec>(nm / m);\n                    for(int i = p; i < nm; i += m) t1((i - p) / m) = D(p, i), t2((i - p) / m) = D(q, i);\n                    for(int i = q; i < nm; i += m) t3((i - q) / m) = D(q, i), t4((i - q) / m) = D(p, i);\n                    g = join_vert(t1 - t3, join_vert(t4, t2));\n                    eig_sym(ev, vcp, real((B * (g * g.t())) * B.t()));\n                    arma::vec angles = vcp.col(2);\n                    if(angles[0] < 0)\n                        angles = angles * (-1);\n                    c = sqrt(0.5 + angles[0] / 2);\n                    s = cx_double(angles[1], -angles[2]) * 0.5 / c;\n                    if(abs(s) > jthresh)\n                    {\n                        encore = 1;\n                        G << c << -conj(s) << endr << s << c << endr;\n                        cx_mat tmp = join_horiz(V.col(p), V.col(q)) * G;\n                        V.col(p) = tmp.col(0), V.col(q) = tmp.col(1);\n                        tmp = G.t() * join_vert(D.row(p), D.row(q));\n                        D.row(p) = tmp.row(0), D.row(q) = tmp.row(1);\n                        for(int ip = p, iq = q; ip < nm && iq < nm; ip += m, iq += m)\n                        {\n                            cx_colvec dip = D.col(ip), diq = D.col(iq);\n                            D.col(ip) = (dip * c) + (diq * s); \n                            D.col(iq) = (diq * c) - (dip * conj(s));\n                        } \n                    }\n                }\n        }\n    }\n    void SOBI(const arma::mat & A, int n, int num_tau, arma::mat & H)\n    {\n        int N = A.n_cols, m = A.n_rows;\n        double tiny = 1e-8;\n        arma::mat Rx, tmp;\n        stdcov(A, 0, Rx);\n        arma::mat uu, vv;\n        arma::vec dd;\n        svd(uu, dd, vv, Rx);\n        arma::mat d = diagmat(dd);\n        arma::mat Q = sqrtmat_sympd(pinv(d)) * uu.t();\n        arma::mat z = Q * A;\n        arma::mat Rz = zeros<arma::mat>(n, num_tau * n);\n        \n        for(int i = 1; i <= num_tau; ++i)\n        {\n            stdcov(z, i - 1, tmp);\n            Rz.cols((i - 1) * n, i * n - 1) = tmp.cols(0, n - 1);\n        }\n        cx_mat v, d2;\n        joint_diag(Rz, tiny, v, d2);\n        H = real(v.t()) * Q;\n    }\n}HR;\n\n\n\nScalar roiMean(cv::Mat roi){\n    Scalar avg;\n    Scalar std;\n    cv::meanStdDev(roi, avg, std);\n    return avg;\n}\ncv::Mat getROI(cv::Mat img, Rect FOI) {\n    \n\n    Rect ROI;\n    ROI.x = FOI.x+FOI.width*0.5-FOI.width*0.25/2;\n    ROI.y = FOI.y+FOI.height*0.18-FOI.height*0.15/2;\n    ROI.width = FOI.width*0.25;\n    ROI.height = FOI.height*0.15;\n    \n    Point p1(ROI.x, ROI.y);\n    Point p2(ROI.x+ROI.width, ROI.y+ROI.height);\n    cv::rectangle(img, p1, p2, Scalar(255, 0, 0));\n    \n    cv::Mat ROIm = img(ROI);\n    \n    return ROIm;\n}\n\nvoid saveROI(ROI roi_tmp){\n    \n    double r, g, b;\n    Scalar mean = roiMean(roi_tmp.roi);\n    r = mean[2];\n    g = mean[1];\n    b = mean[0];\n    HR.insert(RGB_color(r, g, b), roi_tmp.time);\n}\n\nvoid * calculate(void * arg) {\n    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);\n    while(true) {\n        pthread_testcancel();\n        cout << \"Heart Rate\" << HR.calc_BVP() << endl;\n//        sleep(2);\n    }\n    return NULL;\n}\n\nvoid changeState() {\n    isCalculating = !isCalculating;\n}\n\nvoid keyHandler(VideoCapture &cap) {\n    char key = (char) cv::waitKey(10);\n    if( key == 27 ) {\n        pthread_cancel(roi_thread);\n        if (isCalculating) {\n            pthread_cancel(cal_thread);\n        }\n        cv::destroyAllWindows();\n        cap.release();\n    }\n    if( key == 32 ) {\n        changeState();\n        if(isCalculating == true) {\n            int succ = pthread_create(&cal_thread, NULL, calculate, NULL);\n            if(succ == 0) {\n                printf(\"start calculating in new thread\\n\");\n            }\n        }\n        else {\n            printf(\"stop calculating\\n\");\n            pthread_cancel(cal_thread);\n        }\n    }\n}\n\nRect getfacerect(cv::Mat frame){\n\n    cv::Mat img = frame;\n    cv::Mat img_gray;\n    cv::cvtColor(img, img_gray, COLOR_BGR2GRAY);\n    equalizeHist(img_gray, img_gray);\n    \n    std::vector<Rect> faces;\n    faces_cascade.detectMultiScale(img_gray,faces,1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(50, 50) );\n    \n    Rect FOI = Rect(1,1,2,2);\n    \n    if(faces.size() > 1) {\n        int maxsize = faces[0].area();\n        \n        FOI = faces[0];\n        for ( size_t i = 1; i < faces.size(); ++i) {\n            int tmp = faces[i].area();\n            if( tmp > maxsize ) {\n                maxsize = tmp;\n                FOI = faces[i];\n            }\n        }\n    }\n    else if(faces.size() == 1) {\n        FOI = faces[0];\n    }\n    \n    return FOI;\n}\n\n\nvoid gettenface(Frame tenframe[]) {\n    Rect facearea;\n    int hasface = 0;\n    \n    for(int i = 0; i < 10; i++) {\n        \n        cv::Mat face = tenframe[i].frame;\n        facearea = getfacerect(face);\n        \n        if(facearea != Rect(1,1,2,2)) {\n            hasface = i;\n            break;\n        }\n    }\n    ROI roi_tmp;\n    for(int i = hasface; i < 10; i++) {\n        roi_tmp.time = tenframe[i].time;\n        roi_tmp.roi = getROI(tenframe[i].frame, facearea);\n        saveROI(roi_tmp);\n        \n        Point p1(facearea.x, facearea.y);\n        Point p2(facearea.x+facearea.width, facearea.y+facearea.height);\n        cv::rectangle(roi_tmp.roi, p1, p2, Scalar(255, 0, 0));\n        \n        char strchar[10];\n        gcvt(roi_tmp.time, 15, strchar);\n        string str = strchar;\n        \n        imwrite(\"/Users/apple/Library/Mobile\\ Documents/com~apple~CloudDocs/Desktop/HRMeasure/roi\"+str+\".jpg\", roi_tmp.roi);\n    }\n}\n// In this function, take out the first frame in the queue and process it.\n// Get the location of the top of eyebrow to calculate\n// Call ROI calculate function in the end\nROI getRoiWithDlib(Frame frameparam) {\n    \n    cout << \"getRoiWithDlib\" << endl;\n    \n    dlib::frontal_face_detector face_detector = get_frontal_face_detector();\n    \n    shape_predictor sp;\n    \n    deserialize(\"/Users/apple/Library/Mobile\\ Documents/com~apple~CloudDocs/Documents/ceca/projects/HRMeasure/shape_predictors/shape_predictor_68_face_landmarks.dat\") >> sp;\n    \n    \n    Frame frametmp = frameparam;\n\n    cv::Mat frame = frametmp.frame;\n    array2d<dlib::rgb_pixel> img;\n    assign_image(img, dlib::cv_image<rgb_pixel>(frame));\n    \n    //pyramid_up(img);\n    \n    image_window win;\n    win.clear_overlay();\n    win.set_image(img);\n    \n    cout << \"test5\" <<endl;\n    \n    // Now tell the face detector to give us a list of bounding boxes\n    // around all the faces in the image.\n    std::vector<dlib::rectangle> dets = face_detector(img);\n    \n    cout << \"test6\" <<endl;\n    \n    // Choose the largest face to process\n    unsigned long facenum = dets.size();\n    \n    cout << \"face num\" << facenum << endl;\n    \n    dlib::rectangle face;\n    if(facenum > 1) {\n        unsigned long maxsize = dets[0].area();\n        \n        face = dets[0];\n        \n        for(unsigned long j = 1; j < facenum; ++j) {\n            unsigned long tmp = dets[j].area();\n            if(tmp > maxsize) {\n                maxsize = tmp;\n                face = dets[j];\n            }\n         }\n    }\n    else if(facenum == 1) {\n        face = dets[0];\n    }\n    \n\n    full_object_detection shape = sp(img, face);\n\n    \n    dlib::point rightpoint = shape.part(20);\n    dlib::point leftpoint = shape.part(23);\n    Rect ROI;\n    \n    ROI.x = rightpoint.x();\n    ROI.width = leftpoint.x() - rightpoint.x();\n\n    if (rightpoint.y() <= leftpoint.y()) {\n        ROI.y = 0.66 *face.top() + 0.33 * rightpoint.y();\n        ROI.height = ROI.y - rightpoint.y();\n    }\n    else {\n        ROI.y = 0.66 *face.top() + 0.33 * leftpoint.y();\n        ROI.height = ROI.y - leftpoint.y();\n    }\n    \n    \n    struct ROI ROItmp;\n    ROItmp.time = frametmp.time;\n    ROItmp.roi = frame(ROI);\n\n    // For debug\n    Point p1(ROI.x, ROI.y);\n    Point p2(ROI.x+ROI.width, ROI.y+ROI.height);\n    cv::rectangle(frame, p1, p2, Scalar(255, 0, 0));\n    imshow(\"frame2\", frame);\n\n    char strchar[10];\n    gcvt(frametmp.time, 15, strchar);\n    string str = strchar;\n    \n    imwrite(\"/Users/apple/Desktop/testpics/rois/roi\"+str+\".jpg\", ROItmp.roi);\n    // For debug\n\n    return ROItmp;\n}\nvoid * processThreadDlib(void * arg) {\n    while (frames.size() > 0) {\n        cout << \"frame num\" << frames.size() << endl;\n        Frame frame = frames.front();\n        frames.pop();\n        \n        ROI roi_tmp;\n        roi_tmp = getRoiWithDlib(frame);\n        saveROI(roi_tmp);\n    }\n    return NULL;\n}\nvoid * processThreadTenFrames(void * arg) {\n    while (frames.size() > 0) {\n        //cout << \"frame num\" << frames.size() << endl;\n        if(frames.size() > 10) {\n            Frame tenframe[10];\n            Frame tenframeout[10];\n            for(int i = 0; i < 10; ++i) {\n                tenframe[i] = frames.front();\n                frames.pop();\n            }\n            gettenface(tenframe);\n        }\n    }\n    return NULL;\n}\nint saveFrame() {\n    VideoCapture cap(0);\n    if(!cap.isOpened())\n        return -1;\n    \n    while(cap.isOpened()) {\n        Frame frame_in;\n        cap >> frame_in.frame;\n        \n        milliseconds ms = duration_cast< milliseconds >(system_clock::now().time_since_epoch());\n        frame_in.time = ((double)(ms.count() - start_time.count())) / 1000;\n\n        \n        frames.push(frame_in);\n        imshow(\"frame\", frame_in.frame);\n        keyHandler(cap);\n        if (isDetecting == false) {\n            isDetecting = true;\n            int out_thread;\n            //out_thread = pthread_create(&roi_thread, NULL, processThreadTenFrames, NULL);\n            out_thread = pthread_create(&roi_thread, NULL, processThreadDlib, NULL);\n            if (out_thread == 0) {\n                printf(\"start show thread\\n\");\n            }\n        }\n    }\n    return 1;\n}\n\nint main(int argc, const char * argv[]) {\n    start_time = duration_cast< milliseconds >(system_clock::now().time_since_epoch());\n    isCalculating = false;\n    isDetecting = false;\n    \n    faces_cascade.load(\"/Users/apple/Library/Mobile\\ Documents/com~apple~CloudDocs/Documents/ceca/projects/HRMeasure/Haarcascades/haarcascade_frontalface_alt2.xml\");\n    \n    if(faces_cascade.empty()) {\n        printf(\"fail loading cascade\\n\");\n    }\n\n    int openVideo = saveFrame();\n    if( openVideo < 0 ) {\n        printf(\"error open camera\\n\");\n    }\n    return 0;\n}\n\n\n\n\n//cv::Mat getFace(cv::Mat frame_in) {\n//\n//\n//    cv::Mat img = frame_in;\n//    cv::Mat img_gray;\n//    cv::cvtColor(img, img_gray, COLOR_BGR2GRAY);\n//    equalizeHist(img_gray, img_gray);\n//\n//    vector<Rect> faces;\n//    faces_cascade.detectMultiScale(img_gray,faces,1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(50, 50) );\n//\n//    Rect FOI;\n//\n//    if(faces.size() > 1) {\n//        int maxsize = faces[0].area();\n//\n//        FOI = faces[0];\n//        for ( size_t i = 1; i < faces.size(); ++i) {\n//            int tmp = faces[i].area();\n//            if( tmp > maxsize ) {\n//                maxsize = tmp;\n//                FOI = faces[i];\n//            }\n//        }\n//    }\n//    else if(faces.size() == 1) {\n//        FOI = faces[0];\n//    }\n//\n//    cv::Mat ROI = getROI(img, FOI);\n//    saveROI(ROI);\n//\n//    Point p1(FOI.x, FOI.y);\n//    Point p2(FOI.x+FOI.width, FOI.y+FOI.height);\n//    rectangle(img, p1, p2, Scalar(255, 0, 0));\n//\n//    return img;\n//}\n", "meta": {"hexsha": "c7a1664f51fbd034d7a1f740e69f02751cee953b", "size": 18216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Alexandmrwh/HeartRateMeasure", "max_stars_repo_head_hexsha": "e713645b4e783be61dbffffb5e32e0b43b36e87d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T02:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-05T02:59:00.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "Alexandmrwh/HeartRateMeasure", "max_issues_repo_head_hexsha": "e713645b4e783be61dbffffb5e32e0b43b36e87d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "Alexandmrwh/HeartRateMeasure", "max_forks_repo_head_hexsha": "e713645b4e783be61dbffffb5e32e0b43b36e87d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2857142857, "max_line_length": 173, "alphanum_fraction": 0.4959376372, "num_tokens": 5458, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4332740021639}}
{"text": "#ifndef SKYLARK_LOCAL_COMPUTATIONS_HPP\n#define SKYLARK_LOCAL_COMPUTATIONS_HPP\n\n#include <boost/math/special_functions/bessel.hpp>\n\n#include <unordered_map>\n#include <unordered_set>\n#include <queue>\n\nextern \"C\" {\n\nvoid EL_BLAS(sgemv)(const char*, const El::Int *, const El::Int *,\n    const float *, const float *, const El::Int *,\n    const float *, const El::Int *, const float *, float *, const El::Int *);\n\nvoid EL_BLAS(dgemv)(const char*, const El::Int *, const El::Int *,\n    const double *, const double *, const El::Int *,\n    const double *, const El::Int *, const double *, double *, const El::Int *);\n\n}\n\nnamespace skylark { namespace ml {\n\n/**\n * Localized solution of Time-Dependent Personalized PageRank.\n *\n * For details on Time-Dependent PPR, the algorithm, the gaureentess of the\n * output, and the parameters, see:\n *\n * \"Community Detection Using Time-Dependent PageRank\"\n * by Haim Avron and Lior Horesh\n *\n * @tparam GraphType type of graph object. Needs to support the following:\n *                   GraphType::vertex_type - type of vertex.\n *                   GraphType::num_edges() - number of edges.\n *                   GraphType::deg(node) - debgree of a node.\n *                   GraphType::adjanct_begin(node),\n *                   GraphType::adjanct_end(node) -\n *                    begining and end iterators to adjancy container\n *                    container can be any type.\n * @tparam T datatype (e.g. double) for the function on nodes. Must be numeric.\n * @param G input graph\n * @param s seed function on nodes (i.e. map from node to numeric value).\n * @param y output function - or each node the function defines NX values\n *          for NX different time points in [0, gamma].\n * @param x NX-sized vector with the time values on which y reports the values.\n * @param alpha,gamma,epsilon, NX - parameters (see paper).\n */\ntemplate<typename GraphType, typename T>\nvoid TimeDependentPPR(const GraphType& G,\n    const std::unordered_map<typename GraphType::vertex_type, T>& s,\n    std::unordered_map<typename GraphType::vertex_type, El::Matrix<T> *>& y,\n    El::Matrix<T> &x, double alpha = 0.85, double gamma = 5.0,\n    double epsilon = 0.001, int NX = 4) {\n\n    typedef typename GraphType::vertex_type vertex_type;\n\n    if (!El::Initialized())\n        SKYLARK_THROW_EXCEPTION (\n            base::skylark_exception()\n               << base::error_msg(\"Elemental was not initialized\") );\n\n    // Find minimum N, caching it since it involves costly computations of\n    // Bessel functions.\n    static std::unordered_map<std::pair<double, double>, int,\n                              utility::pair_hasher_t> Nmap;\n    auto epsgamma = std::make_pair(epsilon, gamma);\n    const double pi = boost::math::constants::pi<double>();\n    if (Nmap.count(epsgamma) == 0) {\n        int minN = 10;\n        double C = 20.0 * std::sqrt(minN) * std::exp(-gamma/2);\n        while (C * boost::math::cyl_bessel_i(minN, gamma) * pow(0.8, minN) >\n            epsilon / (gamma * (1 + (2 / pi) * log(minN - 1))))\n            minN++;\n        Nmap[epsgamma] = minN;\n    }\n    int minN = Nmap[epsgamma];\n\n    // N is taken to be the minimum multiple of NX that is bigger or equal\n    // to minN.\n    const El::Int N = minN % NX == 0 ? minN : (minN / NX + 1) * NX;\n    const El::Int NR = N / NX;\n\n    // Setup matrices associated with Chebyshev spectral diff\n    // We cache them to keep costs low (can be crucial for\n    // when finding the cluster is very fast).\n    static std::unordered_map<std::pair<int, double>, El::Matrix<T>*,\n                              utility::pair_hasher_t> Dmap;\n\n    auto ngamma = std::make_pair(N, gamma);\n    if (Dmap.count(ngamma) == 0) {\n        El::Matrix<T> *D = new El::Matrix<T>(N, N);\n        Dmap[ngamma] = D;\n\n        El::Matrix<T> D0;\n        nla::ChebyshevDiffMatrix(N, D0, x, 0, gamma);\n        for(int i = 0; i < N; i++)\n            D0.Set(i, i, D0.Get(i, i) + 1.0);\n\n        El::Matrix<T> R(N, N);\n        El::qr::Explicit(D0, R);\n\n        for(int j = 0; j < N; j++)\n            D->Set(N-1, j, D0.Get(j, N-1));\n\n        El::Matrix<T> Q1, R1;\n        base::ColumnView(Q1, D0, 0, N - 1);\n        El::View(R1, R, 0, 0, N-1, N-1);\n\n        El::Pseudoinverse(R1);\n\n        El::Matrix<T> DU;\n        base::RowView(DU, *D, 0, N-1);\n        El::Gemm(El::NORMAL, El::TRANSPOSE, 1.0, R1, Q1, 0.0, DU);\n    }\n\n    const El::Matrix<T> *D_ = Dmap[ngamma];\n\n    El::Matrix<T> x1;\n    nla::ChebyshevPoints(N, x1, 0, gamma);\n    x.Resize(NX, 1);\n    for(int i = 0; i < NX; i++)\n        x.Set(i, 0, x1.Get(i * NR, 0));\n\n    // Constants for convergence.\n    double LC = 1 + (2 / pi) * log(N - 1);\n    double C = (alpha < 1) ?\n        (1-alpha) * epsilon / ((1 - exp((alpha - 1) * gamma)) * LC) :\n        epsilon / (gamma * LC);\n\n    // From now on, do not use Elemental to avoid overheads.\n    const T *D = D_->LockedBuffer();\n    const T *u = D_->LockedBuffer() + N - 1;\n\n    typedef std::pair<bool, T*> rypair_t;\n    std::unordered_map<vertex_type, rypair_t> rymap;\n    std::queue<vertex_type> violating;\n\n    // Initialize non-zero functions, and their residual, which is not\n    // fully computed yet (but we know that needs to be inserted into the queue).\n    for(auto it = s.begin(); it != s.end(); it++) {\n        const vertex_type &node = it->first;\n        const T &v = it->second;\n\n        T *ry = new T[N + NX];\n        std::fill(ry, ry + N, -alpha * v);\n        std::fill(ry + N, ry + N + NX, v);\n        rymap[node] = rypair_t(true, ry);\n        violating.push(node);\n    }\n\n    // Initialize to just zero for all nodes adjanct to seeds, that\n    // are not seeds themselves. Residual is not fully computed yet.\n    for(auto it = s.begin(); it != s.end(); it++) {\n        const vertex_type &node = it->first;\n\n        for(auto it = G.adjanct_begin(node); it != G.adjanct_end(node); it++) {\n            const vertex_type &onode = *it;\n            if (rymap.count(onode) == 0) {\n                T *ry = new T[N + NX];\n                std::fill(ry, ry + N + NX, 0);\n                rymap[onode] = rypair_t(false, ry);\n            }\n        }\n    }\n\n    // Update the residual based on seeds\n    for(auto it = s.begin(); it != s.end(); it++) {\n        const vertex_type &node = it->first;\n\n        T *ry = rymap[node].second;\n\n        size_t deg = G.degree(node);\n        T v = alpha * ry[N] / deg;\n        for(auto it = G.adjanct_begin(node); it != G.adjanct_end(node); it++) {\n            const vertex_type &onode = *it;\n            size_t odeg = G.degree(onode);\n\n            rypair_t& ryopair = rymap[onode];\n            T *ro = ryopair.second;\n            bool inq = false;\n            double B = C * odeg;\n            for(int j = 0; j < N; j++) {\n                ro[j] += v;\n                inq = inq || (std::abs(ro[j]) > B);\n            }\n            if (!ryopair.first && inq) {\n                violating.push(onode);\n                ryopair.first = true;\n            }\n        }\n    }\n\n    // Main loop\n    T dyp[N];\n    while(!violating.empty()) {\n        vertex_type node = violating.front();\n        violating.pop();\n\n        // Solve locally, and update rymap[node].\n        rypair_t& rpair = rymap[node];\n        T *ry = rpair.second;\n\n        // Compute correction to y, and the new residual.\n        T done = 1.0, dzero = 0.0;\n        El::Int ione = 1;\n        if (std::is_same<T, float>::value)\n            EL_BLAS(sgemv)(\"Normal\", &N, &N, (float *)&done, (float *)D, &N,\n                (float *)ry, &ione, (float *)&dzero, (float *)dyp, &ione);\n        else\n            EL_BLAS(dgemv)(\"Normal\", &N, &N, (double *)&done, (double *)D, &N,\n                (double *)ry, &ione, (double *)&dzero, (double *)dyp, &ione);\n        for(int i = 0; i < NX; i++)\n            ry[N + i] += dyp[i * NR];\n        T v = dyp[N-1];\n        for(int i = 0; i < N; i++)\n            ry[i] = v * u[i * N];\n\n        // No longer in queue.\n        rpair.first = false;\n\n        // Update residuals\n        size_t deg = G.degree(node);\n        for(auto it = G.adjanct_begin(node); it != G.adjanct_end(node); it++) {\n            const vertex_type &onode = *it;\n            size_t odeg = G.degree(onode);\n\n            // Add it to rymap, if not already there.\n            if (rymap.count(onode) == 0) {\n                T *rynew = new T[N + NX];\n                std::fill(rynew, rynew + N + NX, 0);\n                rymap[onode] = rypair_t(false, rynew);\n            }\n\n            rypair_t& ryopair = rymap[onode];\n            bool inq = false;\n            T *ryo = ryopair.second;\n            T c = alpha / deg;\n            double B = C * odeg;\n            for(int i = 0; i < N - 1; i++) {\n                ryo[i] += c *  dyp[i];\n                inq = inq || (std::abs(ryo[i]) > B);\n            }\n            inq = inq || (std::abs(ryo[N - 1]) > B);\n            if (!ryopair.first && inq) {\n                violating.push(onode);\n                ryopair.first = true;\n            }\n        }\n    }\n\n    // Yank values to y, freeing other parts of ry in the process.\n    y.clear();\n    for(auto it = rymap.begin(); it != rymap.end(); it++) {\n        if (it->second.second[N] != 0) {\n            El::Matrix<T> *yv = new El::Matrix<T>(NX, 1);\n            for(int i = 0; i < NX; i++)\n                yv->Set(i, 0, it->second.second[N + i]);\n            y[it->first] = yv;\n        }\n        delete it->second.second;\n    }\n}\n\n/**\n * Find a local cluster in a graph using a set of seed nodes.\n *\n * Based on the algorithm in\n * \"Community Detection Using Time-Dependent PageRank\"\n * by Haim Avron and Lior Horesh\n *\n * @tparam GraphType type of graph object. Needs to support the following:\n *                   GraphType::vertex_type - type of vertex.\n *                   GraphType::num_edges() - number of edges.\n *                   GraphType::deg(node) - debgree of a node.\n *                   GraphType::adjanct_begin(node),\n *                   GraphType::adjanct_end(node) -\n *                    begining and end iterators to adjancy container\n *                    container can be any type.\n * @param G input graph\n * @param seeds seed nodes\n * @param cluster output cluster of nodes\n * @param alpha,gamma,epsilon, NX - parameters (see paper).\n * @param recursive - recursively run on output as seed until conductance\n *                    steps reducing.\n */\ntemplate<typename GraphType>\ndouble FindLocalCluster(const GraphType& G,\n    const std::unordered_set<typename GraphType::vertex_type>& seeds,\n    std::unordered_set<typename GraphType::vertex_type>& cluster,\n    double alpha = 0.85, double gamma = 5.0, double epsilon = 0.001, int NX = 4,\n    bool recursive = false) {\n\n    typedef typename GraphType::vertex_type vertex_type;\n    double currentcond = -1;\n    cluster = seeds;\n    bool improve;\n    El::Matrix<double> x;\n\n    do {\n        // Create seed set.\n        std::unordered_map<vertex_type, double> s;\n        for(auto it = cluster.begin(); it != cluster.end(); it++)\n            s[*it] = 1.0 / cluster.size();\n\n        // Run the diffusion\n        std::unordered_map<vertex_type, El::Matrix<double>*> y;\n        TimeDependentPPR(G, s, y, x, alpha, gamma, epsilon, NX);\n\n        // Go over the y output at the different time samples,\n        // find the best prefix and if better conductance, store it.\n        improve = false;\n        for (int t = 0; t < NX; t++) {\n            // Sort (descending) the non-zero components based on their normalized\n            // y values (normalized by degree).\n            std::vector<std::pair<double, vertex_type> > vals(y.size());\n            int i = 0;\n            for(auto it = y.begin(); it != y.end(); it++) {\n                vertex_type node = it->first;\n                double val = - it->second->Get(t, 0) / G.degree(node);\n                vals[i] = std::make_pair(val, node);\n                i++;\n            }\n            std::sort(vals.begin(), vals.end());\n\n            // Find the best prefix\n            int volS = 0, cutS = 0;\n            double bestcond = 1.0;\n            int bestprefix = 0;\n            int Gvol = G.num_edges();\n            std::unordered_set<vertex_type> currentset;\n            for (int i = 0; i < vals.size(); i++) {\n                vertex_type node = vals[i].second;\n                size_t deg = G.degree(node);\n                volS += deg;\n                for(auto it = G.adjanct_begin(node);\n                    it != G.adjanct_end(node); it++) {\n                    const vertex_type &onode = *it;\n                    if (currentset.count(onode))\n                        cutS--;\n                    else\n                        cutS++;\n                }\n\n                double condS =\n                    static_cast<double>(cutS) / std::min(volS, Gvol - volS);\n                if (condS < bestcond) {\n                    bestcond = condS;\n                    bestprefix = i;\n                }\n                currentset.insert(node);\n            }\n\n            if (currentcond == -1 || bestcond < 0.999999 * currentcond) {\n                // We have a new best cluster - the best perfix.\n                improve = true;\n                cluster.clear();\n                for(int i = 0; i <= bestprefix; i++)\n                    cluster.insert(vals[i].second);\n                currentcond = bestcond;\n            }\n        }\n\n        // Clear y\n        for(auto it = y.begin(); it != y.end(); it++)\n            delete it->second;\n    } while (recursive && improve);\n\n    return currentcond;\n}\n\n} }   // namespace skylark::ml\n\n#endif // SKYLARK_LOCAL_COMPUTATIONS_HPP\n", "meta": {"hexsha": "b81e7661eb01cc1f930b3cdb140585b0b391d5a4", "size": 13515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ml/graph/local_computations.hpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "ml/graph/local_computations.hpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "ml/graph/local_computations.hpp", "max_forks_repo_name": "xdata-skylark/libskylark", "max_forks_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 36.04, "max_line_length": 82, "alphanum_fraction": 0.5280059193, "num_tokens": 3676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110203, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4332739952184492}}
{"text": "/*\n * Copyright (c) 2013-2019 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef AFFINE_HPP\n#define AFFINE_HPP\n\n// Affine Arithmetic\n\n#include <iostream>\n#include <stdexcept>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\n#include <map> //@hylagi\n\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n\n#include <kv/convert.hpp>\n\n\n/*\n * define simplicity of affine arithmetic\n *\n *   value of AFFINE_SIMPLE                   | 0 | 1 | 2\n *  ------------------------------------------+---+---+---\n *   add dummy epsilin on linear operation    | o | x | x\n *   add dummy epsilin on nonlinear operation | o | o | x\n *\n *  default: 1\n */\n\n#ifndef AFFINE_SIMPLE\n#define AFFINE_SIMPLE 1\n#endif\n\n/*\n * select the method for multiplication\n *\n *  0: Stolfi's simple method (default, O(n))\n *  1: better multiplication (give smaller extra epsilon but slow, O(n^2))\n *  2: best multiplication (give smallest extra epsilon but slow, O(n^2))\n */\n\n#ifndef AFFINE_MULT\n#define AFFINE_MULT 0\n#endif\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T> class affine;\n\ntemplate <class C, class T> struct acceptable_s<C, affine<T> > {\n  static const bool value = boost::is_same<C, interval<T> >::value || boost::is_convertible<C, std::string>::value;\n};\n\ntemplate <class C, class T> struct acceptable_n<C, affine<T> > {\n  static const bool value = convertible<C, T>::value && (!acceptable_s<C, affine<T> >::value);\n};\n\ntemplate <class C, class T> struct convertible<C, affine<T> > {\n  static const bool value = acceptable_n<C, affine<T> >::value || acceptable_s<C, affine<T> >::value || boost::is_same<C, affine<T> >::value;\n};\n\n#if 0\ntemplate <class C, class T> struct acceptable_n<C, affine<T> > {\n  static const bool value = convertible<C, T>::value && (!boost::is_same<C, interval<T> >::value) && (!boost::is_convertible<C, std::string>::value);\n};\n\ntemplate <class C, class T> struct convertible<C, affine<T> > {\n  static const bool value = convertible<C, T>::value || boost::is_same<C, interval<T> >::value || boost::is_convertible<C, std::string>::value || boost::is_same<C, affine<T> >::value;\n};\n#endif\n\n\n\ntemplate <class T> class affine {\n  public:\n  ub::vector<T> a;\n  #if AFFINE_SIMPLE >= 1\n  T er;\n  #endif\n\n  typedef T base_type;\n\n  static int& maxnum() {\n    static int m = 0;\n    #pragma omp threadprivate(m)\n    return m;\n  }\n\n  friend inline T rad(const affine& x) {\n    int i, xs;\n    T r(0.);\n\n    xs = x.a.size();\n\n    rop<T>::begin();\n    for (i=1; i<xs; i++) {\n      using std::abs;\n      r = rop<T>::add_up(r, abs(x.a(i)));\n    }\n    #if AFFINE_SIMPLE >= 1\n    r = rop<T>::add_up(r, x.er);\n    #endif\n    rop<T>::end();\n\n    return r;\n  }\n\n  friend inline interval<T> to_interval(const affine& x) {\n    T t1, t2, t3;\n\n    t1 = rad(x);\n    rop<T>::begin();\n    t2 = rop<T>::sub_down(x.a(0), t1);\n    t3 = rop<T>::add_up(x.a(0), t1);\n    rop<T>::end();\n    return interval<T>(t2, t3);\n  }\n\n  interval<T> as_interval() const{ // @hylagi modified\n    T t1, t2, t3;\n    t1 = rad(*this);\n    rop<T>::begin();\n    t2 = rop<T>::sub_down(a(0), t1);\n    t3 = rop<T>::add_up(a(0), t1);\n    rop<T>::end();\n    return interval<T>(t2, t3);\n  }\n\n  affine() {\n  }\n\n  template <class C> explicit affine(const C& x, typename boost::enable_if_c< acceptable_n<C, affine>::value >::type* =0) {\n    a.resize(1);\n    a(0) = x;\n    #if AFFINE_SIMPLE >= 1\n    er = 0.;\n    #endif\n  }\n\n  template <class C> explicit affine(const C& x, typename boost::enable_if_c< acceptable_s<C, affine>::value >::type* =0) {\n    int i;\n    interval<T> I(x);\n    maxnum()++;\n    a.resize(maxnum()+1);\n\n\n    rop<T>::begin();\n    a(0) = rop<T>::mul_up(rop<T>::add_up(I.upper(), I.lower()), T(0.5));\n    a(maxnum()) = rop<T>::sub_up(a(0), I.lower());\n    rop<T>::end();\n\n    for (i=1; i<maxnum(); i++) a(i) = 0.;\n\n    #if AFFINE_SIMPLE >= 1\n    er = 0.;\n    #endif\n  }\n\n  template <class C> typename boost::enable_if_c< acceptable_n<C, affine>::value, affine& >::type operator=(const C& x) {\n    a.resize(1);\n    a(0) = x;\n    #if AFFINE_SIMPLE >= 1\n    er = 0.;\n    #endif\n\n    return *this;\n  }\n\n  template <class C> typename boost::enable_if_c< acceptable_s<C, affine>::value, affine& >::type operator=(const C& x) {\n    int i;\n    interval<T> I(x);\n    maxnum()++;\n    a.resize(maxnum()+1);\n\n    rop<T>::begin();\n    a(0) = rop<T>::mul_up(rop<T>::add_up(I.upper(), I.lower()), T(0.5));\n    a(maxnum()) = rop<T>::sub_up(a(0), I.lower());\n    rop<T>::end();\n\n    for (i=1; i<maxnum(); i++) a(i) = 0.;\n\n    #if AFFINE_SIMPLE >= 1\n    er = 0.;\n    #endif\n\n    return *this;\n  }\n\n  T get_coef (int i) const {\n    if (i >= a.size()) return T(0.);\n    else return a(i);\n  }\n\n  T get_mid() const {\n    return a(0);\n  }\n\n  T get_err() const {\n    #if AFFINE_SIMPLE >= 1\n    return er;\n    #else\n    return T(0.);\n    #endif\n  }\n\n  friend affine operator+(const affine& x, const affine& y) {\n    affine r;\n    int xs, ys, i;\n    T err(0.);\n\n    #if AFFINE_SIMPLE == 0\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #endif\n\n    xs = x.a.size();\n    ys = y.a.size();\n    if (xs > ys) {\n      #if AFFINE_SIMPLE >= 1\n      r.a.resize(xs);\n      #endif\n      rop<T>::begin();\n      for (i=0; i<ys; i++) {\n        r.a(i) = rop<T>::add_down(x.a(i), y.a(i));\n      }\n      for (i=0; i<ys; i++) {\n        err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::add_up(x.a(i), y.a(i)), r.a(i)));\n      }\n      rop<T>::end();\n\n      for (i=ys; i<xs; i++) {\n        r.a(i) = x.a(i);\n      }\n      #if AFFINE_SIMPLE == 0\n      for (i=xs; i<maxnum(); i++) {\n        r.a(i) = 0.;\n      }\n      #endif\n    } else {\n      #if AFFINE_SIMPLE >= 1\n      r.a.resize(ys);\n      #endif\n      rop<T>::begin();\n      for (i=0; i<xs; i++) {\n        r.a(i) = rop<T>::add_down(x.a(i), y.a(i));\n      }\n      for (i=0; i<xs; i++) {\n        err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::add_up(x.a(i), y.a(i)), r.a(i)));\n      }\n      rop<T>::end();\n\n      for (i=xs; i<ys; i++) {\n        r.a(i) = y.a(i);\n      }\n      #if AFFINE_SIMPLE == 0\n      for (i=ys; i<maxnum(); i++) {\n        r.a(i) = 0.;\n      }\n      #endif\n    }\n    #if AFFINE_SIMPLE >= 1\n    rop<T>::begin();\n    r.er = rop<T>::add_up(rop<T>::add_up(x.er, y.er), err);\n    rop<T>::end();\n    #else\n    r.a(maxnum()) = err;\n    #endif\n    return r;\n  }\n\n  // same as operator+, but do not add extra epsilon.\n  // This function can be used for adding affine variables\n  // which have no common epsilons.\n\n  friend affine append(const affine& x, const affine& y) {\n    affine r;\n    int xs, ys, i;\n\n    xs = x.a.size();\n    ys = y.a.size();\n\n    if (xs > ys) {\n      r.a.resize(xs);\n      for (i=0; i<ys; i++) {\n        r.a(i) = x.a(i) + y.a(i);\n      }\n      for (i=ys; i<xs; i++) {\n        r.a(i) = x.a(i);\n      }\n    } else {\n      r.a.resize(ys);\n      for (i=0; i<xs; i++) {\n        r.a(i) = x.a(i) + y.a(i);\n      }\n      for (i=xs; i<ys; i++) {\n        r.a(i) = y.a(i);\n      }\n    }\n    #if AFFINE_SIMPLE >= 1\n    r.er = x.er + y.er;\n    #endif\n    return r;\n  }\n\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine >::type operator+(const affine& x, const C& y) {\n    affine r;\n    int xs, i;\n    T err;\n\n    xs = x.a.size();\n\n    #if AFFINE_SIMPLE == 0\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #else\n    r.a.resize(xs);\n    #endif\n\n    rop<T>::begin();\n    r.a(0) = rop<T>::add_down(x.a(0), (T)y);\n    err = rop<T>::sub_up(rop<T>::add_up(x.a(0), (T)y), r.a(0));\n    rop<T>::end();\n\n    for (i=1; i<xs; i++) {\n      r.a(i) = x.a(i);\n    }\n    #if AFFINE_SIMPLE == 0\n    for (i=xs; i<maxnum(); i++) {\n      r.a(i) = 0.;\n    }\n    #endif\n    #if AFFINE_SIMPLE >= 1\n    rop<T>::begin();\n    r.er = rop<T>::add_up(x.er, err);\n    rop<T>::end();\n    #else\n    r.a(maxnum()) = err;\n    #endif\n    return r;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine >::type operator+(const C& x, const affine& y) {\n    affine r;\n    int ys, i;\n    T err;\n\n    ys = y.a.size();\n\n    #if AFFINE_SIMPLE == 0\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #else\n    r.a.resize(ys);\n    #endif\n\n    rop<T>::begin();\n    r.a(0) = rop<T>::add_down((T)x, y.a(0));\n    err = rop<T>::sub_up(rop<T>::add_up((T)x, y.a(0)), r.a(0));\n    rop<T>::end();\n\n    for (i=1; i<ys; i++) {\n      r.a(i) = y.a(i);\n    }\n    #if AFFINE_SIMPLE == 0\n    for (i=ys; i<maxnum(); i++) {\n      r.a(i) = 0.;\n    }\n    #endif\n    #if AFFINE_SIMPLE >= 1\n    rop<T>::begin();\n    r.er = rop<T>::add_up(y.er, err);\n    rop<T>::end();\n    #else\n    r.a(maxnum()) = err;\n    #endif\n    return r;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine >::type operator+(const affine& x, const C& y) {\n    return x + affine(y);\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine >::type operator+(const C& x, const affine& y) {\n    return affine(x) + y;\n  }\n\n  friend affine& operator+=(affine& x, const affine& y) {\n    x = x + y;\n    return x;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine& >::type operator+=(affine& x, const C& y) {\n    x = x + y;\n    return x;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine& >::type operator+=(affine& x, const C& y) {\n    x = x + y;\n    return x;\n  }\n\n  friend affine operator-(const affine& x, const affine& y) {\n    affine r;\n    int xs, ys, i;\n    T err(0.);\n\n    #if AFFINE_SIMPLE == 0\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #endif\n\n    xs = x.a.size();\n    ys = y.a.size();\n    if (xs > ys) {\n      #if AFFINE_SIMPLE >= 1\n      r.a.resize(xs);\n      #endif\n      rop<T>::begin();\n      for (i=0; i<ys; i++) {\n        r.a(i) = rop<T>::sub_down(x.a(i), y.a(i));\n      }\n      for (i=0; i<ys; i++) {\n        err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::sub_up(x.a(i), y.a(i)), r.a(i)));\n      }\n      rop<T>::end();\n\n      for (i=ys; i<xs; i++) {\n        r.a(i) = x.a(i);\n      }\n      #if AFFINE_SIMPLE == 0\n      for (i=xs; i<maxnum(); i++) {\n        r.a(i) = 0.;\n      }\n      #endif\n    } else {\n      #if AFFINE_SIMPLE >= 1\n      r.a.resize(ys);\n      #endif\n      rop<T>::begin();\n      for (i=0; i<xs; i++) {\n        r.a(i) = rop<T>::sub_down(x.a(i), y.a(i));\n      }\n      for (i=0; i<xs; i++) {\n        err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::sub_up(x.a(i), y.a(i)), r.a(i)));\n      }\n      rop<T>::end();\n\n      for (i=xs; i<ys; i++) {\n        r.a(i) = - y.a(i);\n      }\n      #if AFFINE_SIMPLE == 0\n      for (i=ys; i<maxnum(); i++) {\n        r.a(i) = 0.;\n      }\n      #endif\n    }\n    #if AFFINE_SIMPLE >= 1\n    rop<T>::begin();\n    r.er = rop<T>::add_up(rop<T>::add_up(x.er, y.er), err);\n    rop<T>::end();\n    #else\n    r.a(maxnum()) = err;\n    #endif\n    return r;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine >::type operator-(const affine& x, const C& y) {\n    affine r;\n    int xs, i;\n    T err;\n\n    xs = x.a.size();\n\n    #if AFFINE_SIMPLE == 0\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #else\n    r.a.resize(xs);\n    #endif\n\n    rop<T>::begin();\n    r.a(0) = rop<T>::sub_down(x.a(0), (T)y);\n    err = rop<T>::sub_up(rop<T>::sub_up(x.a(0), (T)y), r.a(0));\n    rop<T>::end();\n\n    for (i=1; i<xs; i++) {\n      r.a(i) = x.a(i);\n    }\n    #if AFFINE_SIMPLE == 0\n    for (i=xs; i<maxnum(); i++) {\n      r.a(i) = 0.;\n    }\n    #endif\n    #if AFFINE_SIMPLE >= 1\n    rop<T>::begin();\n    r.er = rop<T>::add_up(x.er, err);\n    rop<T>::end();\n    #else\n    r.a(maxnum()) = err;\n    #endif\n    return r;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine >::type operator-(const C& x, const affine& y) {\n    affine r;\n    int ys, i;\n    T err;\n\n    ys = y.a.size();\n\n    #if AFFINE_SIMPLE == 0\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #else\n    r.a.resize(ys);\n    #endif\n\n    rop<T>::begin();\n    r.a(0) = rop<T>::sub_down((T)x, y.a(0));\n    err = rop<T>::sub_up(rop<T>::sub_up((T)x, y.a(0)), r.a(0));\n    rop<T>::end();\n\n    for (i=1; i<ys; i++) {\n      r.a(i) = - y.a(i);\n    }\n    #if AFFINE_SIMPLE == 0\n    for (i=ys; i<maxnum(); i++) {\n      r.a(i) = 0.;\n    }\n    #endif\n    #if AFFINE_SIMPLE >= 1\n    rop<T>::begin();\n    r.er = rop<T>::add_up(y.er, err);\n    rop<T>::end();\n    #else\n    r.a(maxnum()) = err;\n    #endif\n    return r;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine >::type operator-(const affine& x, const C& y) {\n    return x - affine(y);\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine >::type operator-(const C& x, const affine& y) {\n    return affine(x) - y;\n  }\n\n  friend affine& operator-=(affine& x, const affine& y) {\n    x = x - y;\n    return x;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine& >::type operator-=(affine& x, const C& y) {\n    x = x - y;\n    return x;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine& >::type operator-=(affine& x, const C& y) {\n    x = x - y;\n    return x;\n  }\n\n  friend affine operator-(const affine& x) {\n    affine r;\n\n    r.a = - x.a;\n    #if AFFINE_SIMPLE >= 1\n    r.er = x.er;\n    #endif\n    return r;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine >::type operator*(const affine& x, const C& y) {\n    affine r;\n    int xs, i;\n    T err(0.);\n\n    xs = x.a.size();\n\n    #if AFFINE_SIMPLE == 0\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #else\n    r.a.resize(xs);\n    #endif\n\n    rop<T>::begin();\n    for (i=0; i<xs; i++) {\n      r.a(i) = rop<T>::mul_down(x.a(i), (T)y);\n    }\n    for (i=0; i<xs; i++) {\n      err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::mul_up(x.a(i), (T)y), r.a(i)));\n    }\n    rop<T>::end();\n\n    #if AFFINE_SIMPLE == 0\n    for (i=xs; i<maxnum(); i++) r.a(i) = 0.;\n    #endif\n    #if AFFINE_SIMPLE >= 1\n    rop<T>::begin();\n    using std::abs;\n    r.er = rop<T>::add_up(rop<T>::mul_up(x.er, T(abs(y))), err);\n    rop<T>::end();\n    #else\n    r.a(maxnum()) = err;\n    #endif\n\n    return r;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine >::type operator*(const C& x, const affine& y) {\n    affine r;\n    int ys, i;\n    T err(0.);\n\n    ys = y.a.size();\n\n    #if AFFINE_SIMPLE == 0\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #else\n    r.a.resize(ys);\n    #endif\n\n    rop<T>::begin();\n    for (i=0; i<ys; i++) {\n      r.a(i) = rop<T>::mul_down((T)x, y.a(i));\n    }\n    for (i=0; i<ys; i++) {\n      err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::mul_up((T)x, y.a(i)), r.a(i)));\n    }\n    rop<T>::end();\n\n    #if AFFINE_SIMPLE == 0\n    for (i=ys; i<maxnum(); i++) r.a(i) = 0.;\n    #endif\n    #if AFFINE_SIMPLE >= 1\n    rop<T>::begin();\n    using std::abs;\n    r.er = rop<T>::add_up(rop<T>::mul_up(y.er, T(abs(x))), err);\n    rop<T>::end();\n    #else\n    r.a(maxnum()) = err;\n    #endif\n\n    return r;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine >::type operator*(const affine& x, const C& y) {\n    return x * affine(y);\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine >::type operator*(const C& x, const affine& y) {\n    return affine(x) * y;\n  }\n\n\n  #if AFFINE_MULT >= 1\n\n  static interval<T> bestmult_error(const affine& x, const affine& y)\n  {\n    int n, i, j, s;\n    bool f1, f2;\n    ub::vector<T> vx, vy;\n    kv::interval<T> tmp, C, D, E, X, Y;\n\n    n = std::max(x.a.size(), y.a.size()) - 1;\n\n    #if AFFINE_SIMPLE >= 1\n    vx.resize(n+3);\n    vy.resize(n+3);\n    #else\n    vx.resize(n+1);\n    vy.resize(n+1);\n    #endif\n\n    for (i=0; i<x.a.size(); i++) {\n      vx(i) = x.a(i);\n    }\n    for (i=x.a.size(); i<=n; i++) {\n      vx(i) = 0.;\n    }\n    for (i=0; i<y.a.size(); i++) {\n      vy(i) = y.a(i);\n    }\n    for (i=y.a.size(); i<=n; i++) {\n      vy(i) = 0.;\n    }\n\n    #if AFFINE_SIMPLE >= 1\n    vx(n+1) = x.er;\n    vy(n+1) = 0.;\n    vx(n+2) = 0.;\n    vy(n+2) = y.er;\n    n += 2;\n    #endif\n\n    E = 0.;\n\n    #if AFFINE_MULT == 1\n    for (i=1; i<=n; i++) {\n      X = vx(i);\n      Y = vy(i);\n      E += X * Y * interval<T>(0., 1.);\n      for (j=i+1; j<=n; j++) {\n        tmp = X * vy(j) + Y * vx(j);\n        E += tmp * interval<T>(-1., 1.);\n      }\n    }\n    #else // AFFINE_MULT == 1\n\n    for (i=1; i<=n; i++) {\n      X = vx(i);\n      Y = vy(i);\n      if (X == 0. && Y == 0.) continue;\n      C = D = 0.;\n      for (j=1; j<=n; j++) {\n        if (j == i) continue;\n        if (vy(j) == 0. && vx(j) == 0.) continue;\n        tmp = X * vy(j) - Y * vx(j);\n        if (tmp.lower() >= 0.) {\n          C += vx(j);\n          D += vy(j);\n        } else if (tmp.upper() <= 0.) {\n          C -= vx(j);\n          D -= vy(j);\n        } else {\n          if ((X.upper() > 0. && vx(j) < 0.)\n          || (X.lower() < 0. && vx(j) > 0.)) {\n            X -= vx(j);\n            Y -= vy(j);\n          } else {\n            X += vx(j);\n            Y += vy(j);\n          }\n        }\n      }\n      E = interval<T>::hull(E, X * Y + (X * D + Y * C) + C * D);\n      E = interval<T>::hull(E, X * Y - (X * D + Y * C) + C * D);\n      if (!zero_in(X * Y) ){\n        tmp = -0.5 * (X * D + Y * C) / (X * Y);\n        if (overlap(tmp, interval<T>(-1., 1.))) {\n          E = interval<T>::hull(E, X * Y * tmp * tmp + (X * D + Y * C) * tmp + C * D);\n        }\n      }\n    }\n\n    #endif // AFFINE_MULT == 1\n\n    return E;\n  }\n\n  #endif // AFFINE_MULT >= 1\n\n  friend affine operator*(const affine& x, const affine& y) {\n    affine r;\n    int i, j, xs, ys;\n    T err;\n    T tmp_u, tmp_l;\n\n    // if (&x == &y) return square(x);\n\n    xs = x.a.size();\n    ys = y.a.size();\n\n    #if AFFINE_SIMPLE != 2\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #else\n    r.a.resize(std::max(xs, ys));\n    #endif\n\n    rop<T>::begin();\n    r.a(0) = rop<T>::mul_down(x.a(0), y.a(0));\n    err = rop<T>::sub_up(rop<T>::mul_up(x.a(0), y.a(0)), r.a(0));\n    rop<T>::end();\n\n    if (xs > ys) {\n      rop<T>::begin();\n      for (i=1; i<ys; i++) {\n        r.a(i) = rop<T>::add_down(rop<T>::mul_down(y.a(0), x.a(i)), rop<T>::mul_down(x.a(0), y.a(i)));\n      }\n      for (i=ys; i<xs; i++) {\n        r.a(i) = rop<T>::mul_down(y.a(0), x.a(i));\n      }\n      for (i=1; i<ys; i++) {\n        err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::add_up(rop<T>::mul_up(y.a(0), x.a(i)), rop<T>::mul_up(x.a(0), y.a(i))), r.a(i)));\n      }\n      for (i=ys; i<xs; i++) {\n        err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::mul_up(y.a(0), x.a(i)), r.a(i)));\n      }\n      rop<T>::end();\n      #if AFFINE_SIMPLE != 2\n      for (i=xs; i<maxnum(); i++) {\n        r.a(i) = 0.;\n      }\n      #endif\n    } else {\n      rop<T>::begin();\n      for (i=1; i<xs; i++) {\n        r.a(i) = rop<T>::add_down(rop<T>::mul_down(y.a(0), x.a(i)), rop<T>::mul_down(x.a(0), y.a(i)));\n      }\n      for (i=xs; i<ys; i++) {\n        r.a(i) = rop<T>::mul_down(x.a(0), y.a(i));\n      }\n      for (i=1; i<xs; i++) {\n        err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::add_up(rop<T>::mul_up(y.a(0), x.a(i)), rop<T>::mul_up(x.a(0), y.a(i))), r.a(i)));\n      }\n      for (i=xs; i<ys; i++) {\n        err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::mul_up(x.a(0), y.a(i)), r.a(i)));\n      }\n      rop<T>::end();\n      #if AFFINE_SIMPLE != 2\n      for (i=ys; i<maxnum(); i++) {\n        r.a(i) = 0.;\n      }\n      #endif\n    }\n\n    #if AFFINE_MULT >= 1\n\n    interval<T> E;\n    E = r.a(0) + bestmult_error(x, y);\n    rop<T>::begin();\n    r.a(0) = rop<T>::mul_up(rop<T>::add_up(E.upper(), E.lower()), 0.5);\n    err = rop<T>::add_up(err, rop<T>::sub_up(r.a(0), E.lower()));\n    rop<T>::end();\n\n    #else // AFFINE_MULT >= 1\n\n    tmp_l = rad(x);\n    tmp_u = rad(y);\n    rop<T>::begin();\n    err = rop<T>::add_up(err, rop<T>::mul_up(tmp_l, tmp_u));\n    rop<T>::end();\n\n    #endif // AFFINE_MULT >= 1\n\n    #if AFFINE_SIMPLE >= 1\n    rop<T>::begin();\n    using std::abs;\n    err = rop<T>::add_up(err, rop<T>::add_up(rop<T>::mul_up(abs(y.a(0)), x.er), rop<T>::mul_up(abs(x.a(0)), y.er)));\n    rop<T>::end();\n    #endif\n\n    #if AFFINE_SIMPLE == 2\n    r.er = err;\n    #else\n    r.a(maxnum()) = err;\n    # if AFFINE_SIMPLE == 1\n    r.er = 0.;\n    # endif\n    #endif\n\n    return r;\n  }\n\n  friend affine& operator*=(affine& x, const affine& y) {\n    x = x * y;\n    return x;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine& >::type operator*=(affine& x, const C& y) {\n    x = x * y;\n    return x;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine& >::type operator*=(affine& x, const C& y) {\n    x = x * y;\n    return x;\n  }\n\n\n  friend affine inv(const affine& x) {\n    affine r;\n    T err;\n    interval<T> I, tmp, range;\n    T a, b, l, u;\n    int i, xs;\n\n    xs = x.a.size();\n\n    #if AFFINE_SIMPLE == 2\n    r.a.resize(xs);\n    #else\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #endif\n\n    I = to_interval(x);\n    l = I.lower();\n    u = I.upper();\n    if (l < 0. && u > 0.) {\n      throw std::domain_error(\"affine: division by 0\");\n    }\n\n    a = -1. /(l * u);\n    tmp = a; // tmp is used to force interval calculation\n    if (u > 0.) {\n      range = 2. * sqrt(-tmp);\n    } else {\n      range = -2. * sqrt(-tmp);\n    }\n    tmp = l;\n    range = interval<T>::hull(range, 1./tmp - a * tmp);\n    tmp = u;\n    range = interval<T>::hull(range, 1./tmp - a * tmp);\n\n    rop<T>::begin();\n    b = rop<T>::mul_up(rop<T>::add_up(range.upper(), range.lower()), T(0.5));\n    err = rop<T>::sub_up(b, range.lower());\n    for (i=1; i<xs; i++) {\n      r.a(i) = rop<T>::mul_down(x.a(i), a);\n    }\n    for (i=1; i<xs; i++) {\n      err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::mul_up(x.a(i), a), r.a(i)));\n    }\n    #if AFFINE_SIMPLE != 2\n    for (i=xs; i<maxnum(); i++) r.a(i) = 0.;\n    #endif\n    l = rop<T>::add_down(rop<T>::mul_down(x.a(0), a), b);\n    u = rop<T>::add_up(rop<T>::mul_up(x.a(0), a), b);\n    r.a(0) = rop<T>::mul_up(rop<T>::add_up(l, u), T(0.5));\n    err = rop<T>::add_up(err, rop<T>::sub_up(r.a(0), l));\n    #if AFFINE_SIMPLE >= 1\n    // err += abs(a) * x.er;\n    using std::abs;\n    err = rop<T>::add_up(err, rop<T>::mul_up(abs(a), x.er));\n    #endif\n    rop<T>::end();\n\n    #if AFFINE_SIMPLE == 2\n    r.er = err;\n    #else\n    r.a(maxnum()) = err;\n    # if AFFINE_SIMPLE == 1\n    r.er = 0.;\n    # endif\n    #endif\n\n    return r;\n  }\n\n  friend affine operator/(const affine& x, const affine& y) {\n    return x * inv(y);\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine >::type operator/(const C& x, const affine& y) {\n    return x * inv(y);\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine >::type operator/(const affine& x, const C& y) {\n    affine r;\n    int xs, i;\n    T err(0.);\n\n    xs = x.a.size();\n\n    #if AFFINE_SIMPLE == 0\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #else\n    r.a.resize(xs);\n    #endif\n\n    rop<T>::begin();\n    for (i=0; i<xs; i++) {\n      r.a(i) = rop<T>::div_down(x.a(i), (T)y);\n    }\n    for (i=0; i<xs; i++) {\n      err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::div_up(x.a(i), (T)y), r.a(i)));\n    }\n    rop<T>::end();\n\n    #if AFFINE_SIMPLE == 0\n    for (i=xs; i<maxnum(); i++) r.a(i) = 0.;\n    #endif\n    #if AFFINE_SIMPLE >= 1\n    // r.er = x.er / abs(y) + err;\n    rop<T>::begin();\n    using std::abs;\n    r.er = rop<T>::add_up(err, rop<T>::div_up(x.er, T(abs(y))));\n    rop<T>::end();\n    #else\n    r.a(maxnum()) = err;\n    #endif\n\n    return r;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine >::type operator/(const affine& x, const C& y) {\n    return x / affine(y);\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine >::type operator/(const C& x, const affine& y) {\n    return affine(x) / y;\n  }\n\n  friend affine& operator/=(affine& x, const affine& y) {\n    x = x / y;\n    return x;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine& >::type operator/=(affine& x, const C& y) {\n    x = x / y;\n    return x;\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine& >::type operator/=(affine& x, const C& y) {\n    x = x / y;\n    return x;\n  }\n\n\n  friend affine sqrt(const affine& x) {\n    affine r;\n    T err;\n    interval<T> I, tmp, range;\n    T a, b, l, u;\n    int i, xs;\n\n    xs = x.a.size();\n\n    #if AFFINE_SIMPLE == 2\n    r.a.resize(xs);\n    #else\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #endif\n\n    I = to_interval(x);\n    l = I.lower();\n    u = I.upper();\n    if (l < 0.) {\n      throw std::domain_error(\"affine: sqrt of negative value\");\n\n    }\n\n    using std::sqrt;\n    a = 1. /(sqrt(l) + sqrt(u));\n    tmp = a;\n    range = 1. / (4. * tmp);\n    tmp = l;\n    range = interval<T>::hull(range, sqrt(tmp) - a * tmp);\n    tmp = u;\n    range = interval<T>::hull(range, sqrt(tmp) - a * tmp);\n\n    rop<T>::begin();\n    b = rop<T>::mul_up(rop<T>::add_up(range.upper(), range.lower()), T(0.5));\n    err = rop<T>::sub_up(b, range.lower());\n    for (i=1; i<xs; i++) {\n      r.a(i) = rop<T>::mul_down(x.a(i), a);\n    }\n    for (i=1; i<xs; i++) {\n      err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::mul_up(x.a(i), a), r.a(i)));\n    }\n    #if AFFINE_SIMPLE != 2\n    for (i=xs; i<maxnum(); i++) r.a(i) = 0.;\n    #endif\n    l = rop<T>::add_down(rop<T>::mul_down(x.a(0), a), b);\n    u = rop<T>::add_up(rop<T>::mul_up(x.a(0), a), b);\n    r.a(0) = rop<T>::mul_up(rop<T>::add_up(l, u), T(0.5));\n    err = rop<T>::add_up(err, rop<T>::sub_up(r.a(0), l));\n    #if AFFINE_SIMPLE >= 1\n    // err += abs(a) * x.er;\n    using std::abs;\n    err = rop<T>::add_up(err, rop<T>::mul_up(abs(a), x.er));\n    #endif\n    rop<T>::end();\n\n    #if AFFINE_SIMPLE == 2\n    r.er = err;\n    #else\n    r.a(maxnum()) = err;\n    # if AFFINE_SIMPLE == 1\n    r.er = 0.;\n    # endif\n    #endif\n\n    return r;\n  }\n\n  friend affine square(const affine& x) {\n    affine r;\n    T err;\n    interval<T> I, tmp, range;\n    T a, b, l, u;\n    int i, xs;\n\n    xs = x.a.size();\n\n    #if AFFINE_SIMPLE == 2\n    r.a.resize(xs);\n    #else\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #endif\n\n    I = to_interval(x);\n    l = I.lower();\n    u = I.upper();\n\n    a = l + u;\n    tmp = a;\n    range = - tmp * tmp * 0.25;\n    tmp = l;\n    // range = hull(range, tmp * tmp - a * tmp);\n    range = interval<T>::hull(range, tmp * (tmp - a));\n    tmp = u;\n    range = interval<T>::hull(range, tmp * (tmp - a));\n\n    rop<T>::begin();\n    b = rop<T>::mul_up(rop<T>::add_up(range.upper(), range.lower()), T(0.5));\n    err = rop<T>::sub_up(b, range.lower());\n    for (i=1; i<xs; i++) {\n      r.a(i) = rop<T>::mul_down(x.a(i), a);\n    }\n    for (i=1; i<xs; i++) {\n      err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::mul_up(x.a(i), a), r.a(i)));\n    }\n    #if AFFINE_SIMPLE != 2\n    for (i=xs; i<maxnum(); i++) r.a(i) = 0.;\n    #endif\n    l = rop<T>::add_down(rop<T>::mul_down(x.a(0), a), b);\n    u = rop<T>::add_up(rop<T>::mul_up(x.a(0), a), b);\n    r.a(0) = rop<T>::mul_up(rop<T>::add_up(l, u), T(0.5));\n    err = rop<T>::add_up(err, rop<T>::sub_up(r.a(0), l));\n    #if AFFINE_SIMPLE >= 1\n    // err += abs(a) * x.er;\n    using std::abs;\n    err = rop<T>::add_up(err, rop<T>::mul_up(abs(a), x.er));\n    #endif\n    rop<T>::end();\n\n    #if AFFINE_SIMPLE == 2\n    r.er = err;\n    #else\n    r.a(maxnum()) = err;\n    # if AFFINE_SIMPLE == 1\n    r.er = 0.;\n    # endif\n    #endif\n\n    return r;\n  }\n\n  friend affine exp(const affine& x) {\n    affine r;\n    T err;\n    interval<T> I, tmp, range;\n    T a, b, l, u;\n    int i, xs;\n\n    xs = x.a.size();\n\n    #if AFFINE_SIMPLE == 2\n    r.a.resize(xs);\n    #else\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #endif\n\n    I = to_interval(x);\n    l = I.lower();\n    u = I.upper();\n\n    using std::exp;\n    if (u == l) a = exp(u);\n    else a = (exp(u) - exp(l)) / (u - l);\n    tmp = a;\n    range = tmp * (1. - log(tmp));\n    tmp = l;\n    range = interval<T>::hull(range, exp(tmp) - a * tmp);\n    tmp = u;\n    range = interval<T>::hull(range, exp(tmp) - a * tmp);\n\n    rop<T>::begin();\n    b = rop<T>::mul_up(rop<T>::add_up(range.upper(), range.lower()), T(0.5));\n    err = rop<T>::sub_up(b, range.lower());\n    for (i=1; i<xs; i++) {\n      r.a(i) = rop<T>::mul_down(x.a(i), a);\n    }\n    for (i=1; i<xs; i++) {\n      err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::mul_up(x.a(i), a), r.a(i)));\n    }\n    #if AFFINE_SIMPLE != 2\n    for (i=xs; i<maxnum(); i++) r.a(i) = 0.;\n    #endif\n    l = rop<T>::add_down(rop<T>::mul_down(x.a(0), a), b);\n    u = rop<T>::add_up(rop<T>::mul_up(x.a(0), a), b);\n    r.a(0) = rop<T>::mul_up(rop<T>::add_up(l, u), T(0.5));\n    err = rop<T>::add_up(err, rop<T>::sub_up(r.a(0), l));\n    #if AFFINE_SIMPLE >= 1\n    // err += abs(a) * x.er;\n    using std::abs;\n    err = rop<T>::add_up(err, rop<T>::mul_up(abs(a), x.er));\n    #endif\n    rop<T>::end();\n\n    #if AFFINE_SIMPLE == 2\n    r.er = err;\n    #else\n    r.a(maxnum()) = err;\n    # if AFFINE_SIMPLE == 1\n    r.er = 0.;\n    # endif\n    #endif\n\n    return r;\n  }\n\n  friend affine log(const affine& x) {\n    affine r;\n    T err;\n    interval<T> I, tmp, range;\n    T a, b, l, u;\n    int i, xs;\n\n    xs = x.a.size();\n\n    #if AFFINE_SIMPLE == 2\n    r.a.resize(xs);\n    #else\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #endif\n\n    I = to_interval(x);\n    l = I.lower();\n    u = I.upper();\n\n    if (l <= 0.) {\n      throw std::domain_error(\"affine: log of nagative value\");\n    }\n\n    using std::log;\n    if (u == l) a = 1. / u;\n    else a = (log(u) - log(l)) / (u - l);\n    tmp = a;\n    range = log(1. / tmp) - 1.;\n    tmp = l;\n    range = interval<T>::hull(range, log(tmp) - a * tmp);\n    tmp = u;\n    range = interval<T>::hull(range, log(tmp) - a * tmp);\n\n    rop<T>::begin();\n    b = rop<T>::mul_up(rop<T>::add_up(range.upper(), range.lower()), T(0.5));\n    err = rop<T>::sub_up(b, range.lower());\n    for (i=1; i<xs; i++) {\n      r.a(i) = rop<T>::mul_down(x.a(i), a);\n    }\n    for (i=1; i<xs; i++) {\n      err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::mul_up(x.a(i), a), r.a(i)));\n    }\n    #if AFFINE_SIMPLE != 2\n    for (i=xs; i<maxnum(); i++) r.a(i) = 0.;\n    #endif\n    l = rop<T>::add_down(rop<T>::mul_down(x.a(0), a), b);\n    u = rop<T>::add_up(rop<T>::mul_up(x.a(0), a), b);\n    r.a(0) = rop<T>::mul_up(rop<T>::add_up(l, u), T(0.5));\n    err = rop<T>::add_up(err, rop<T>::sub_up(r.a(0), l));\n    #if AFFINE_SIMPLE >= 1\n    // err += abs(a) * x.er;\n    using std::abs;\n    err = rop<T>::add_up(err, rop<T>::mul_up(abs(a), x.er));\n    #endif\n    rop<T>::end();\n\n    #if AFFINE_SIMPLE == 2\n    r.er = err;\n    #else\n    r.a(maxnum()) = err;\n    # if AFFINE_SIMPLE == 1\n    r.er = 0.;\n    # endif\n    #endif\n\n    return r;\n  }\n\n  friend affine abs(const affine& x) {\n    affine r;\n    T err;\n    interval<T> I, range;\n    T a, b, l, u;\n    int i, xs;\n\n    I = to_interval(x);\n    l = I.lower();\n    u = I.upper();\n\n    if (l >= 0.) {\n      return x;\n    }\n    if (u <= 0.) {\n      return -x;\n    }\n\n    xs = x.a.size();\n\n    #if AFFINE_SIMPLE == 2\n    r.a.resize(xs);\n    #else\n    maxnum()++;\n    r.a.resize(maxnum()+1);\n    #endif\n\n    a = (u + l) / (u - l);\n\n    range = 0.;\n    range = interval<T>::hull(range, u - a * u);\n    range = interval<T>::hull(range, -l - a * l);\n\n    rop<T>::begin();\n    b = rop<T>::mul_up(rop<T>::add_up(range.upper(), range.lower()), T(0.5));\n    err = rop<T>::sub_up(b, range.lower());\n    for (i=1; i<xs; i++) {\n      r.a(i) = rop<T>::mul_down(x.a(i), a);\n    }\n    for (i=1; i<xs; i++) {\n      err = rop<T>::add_up(err, rop<T>::sub_up(rop<T>::mul_up(x.a(i), a), r.a(i)));\n    }\n    #if AFFINE_SIMPLE != 2\n    for (i=xs; i<maxnum(); i++) r.a(i) = 0.;\n    #endif\n    l = rop<T>::add_down(rop<T>::mul_down(x.a(0), a), b);\n    u = rop<T>::add_up(rop<T>::mul_up(x.a(0), a), b);\n    r.a(0) = rop<T>::mul_up(rop<T>::add_up(l, u), T(0.5));\n    err = rop<T>::add_up(err, rop<T>::sub_up(r.a(0), l));\n    #if AFFINE_SIMPLE >= 1\n    // err += abs(a) * x.er;\n    using std::abs;\n    err = rop<T>::add_up(err, rop<T>::mul_up(abs(a), x.er));\n    #endif\n    rop<T>::end();\n\n    #if AFFINE_SIMPLE == 2\n    r.er = err;\n    #else\n    r.a(maxnum()) = err;\n    # if AFFINE_SIMPLE == 1\n    r.er = 0.;\n    # endif\n    #endif\n\n    return r;\n  }\n\n  // lazy implementation of integer pow\n  friend affine pow(const affine& x, int y) {\n    affine r, xp;\n    int a, tmp;\n\n    if (y == 0) return affine(1.);\n\n    a = (y >= 0) ? y : -y;\n\n    tmp = a;\n    r = 1.;\n    xp = x;\n    while (tmp != 0) {\n      if (tmp % 2 != 0) {\n        r *= xp;\n      }\n      tmp /= 2;\n      xp = xp * xp;\n    }\n\n    if (y < 0) {\n      r = 1. / r;\n    }\n\n    return r;\n  }\n\n  friend affine pow(const affine& x, const affine& y) {\n    return exp(y * log(x));\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value && ! boost::is_integral<C>::value, affine >::type pow(const affine& x, const C& y) {\n    return pow(x, affine(y));\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine >::type pow(const affine& x, const C& y) {\n    return pow(x, affine(y));\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_n<C, affine>::value, affine >::type pow(const C& x, const affine& y) {\n    return pow(affine(x), y);\n  }\n\n  template <class C> friend typename boost::enable_if_c< acceptable_s<C, affine>::value, affine >::type pow(const C& x, const affine& y) {\n    return pow(affine(x), y);\n  }\n\n  // lazy implementation of sin\n  friend affine sin(const affine& x) {\n    // return sin((interval<T>)(x.a(0))) + cos(to_interval(x)) * (x - x.a(0));\n\n    affine tmp;\n    interval<T> r, r2;\n    T m;\n\n    tmp = x;\n    tmp.a(0) = 0.;\n    r = sin((interval<T>)(x.a(0)));\n    r2 = cos(to_interval(x));\n    m = mid(r2);\n    r += (r2 - m) * to_interval(tmp);\n    \n    return r + m * tmp;\n  }\n\n  // lazy implementation of cos\n  friend affine cos(const affine& x) {\n    // return cos((interval<T>)(x.a(0))) - sin(to_interval(x)) * (x - x.a(0));\n\n    affine tmp;\n    interval<T> r, r2;\n    T m;\n\n    tmp = x;\n    tmp.a(0) = 0.;\n    r = cos((interval<T>)(x.a(0)));\n    r2 = -sin(to_interval(x));\n    m = mid(r2);\n    r += (r2 - m) * to_interval(tmp);\n    \n    return r + m * tmp;\n  }\n\n  // lazy implementation of tan\n  friend affine tan(const affine& x) {\n    // return tan((interval<T>)(x.a(0))) + pow(cos(to_interval(x)), -2) * (x - x.a(0));\n\n    affine tmp;\n    interval<T> r, r2;\n    T m;\n\n    tmp = x;\n    tmp.a(0) = 0.;\n    r = tan((interval<T>)(x.a(0)));\n    r2 = pow(cos(to_interval(x)), -2);\n    m = mid(r2);\n    r += (r2 - m) * to_interval(tmp);\n    \n    return r + m * tmp;\n  }\n\n  // lazy implementation of asin\n  friend affine asin(const affine& x) {\n    // return asin((interval<T>)(x.a(0))) + (1. / sqrt(1. - pow(to_interval(x), 2))) * (x - x.a(0));\n\n    affine tmp;\n    interval<T> r, r2;\n    T m;\n\n    tmp = x;\n    tmp.a(0) = 0.;\n    r = asin((interval<T>)(x.a(0)));\n    r2 = 1. / sqrt(1. - pow(to_interval(x), 2));\n    m = mid(r2);\n    r += (r2 - m) * to_interval(tmp);\n    \n    return r + m * tmp;\n  }\n\n  // lazy implementation of acos\n  friend affine acos(const affine& x) {\n    // return acos((interval<T>)(x.a(0))) + (- 1. / sqrt(1. - pow(to_interval(x), 2))) * (x - x.a(0));\n\n    affine tmp;\n    interval<T> r, r2;\n    T m;\n\n    tmp = x;\n    tmp.a(0) = 0.;\n    r = acos((interval<T>)(x.a(0)));\n    r2 = - 1. / sqrt(1. - pow(to_interval(x), 2));\n    m = mid(r2);\n    r += (r2 - m) * to_interval(tmp);\n    \n    return r + m * tmp;\n  }\n\n  // lazy implementation of atan\n  friend affine atan(const affine& x) {\n    // return atan((interval<T>)(x.a(0))) + (1. / sqrt(1. + pow(to_interval(x), 2))) * (x - x.a(0));\n\n    affine tmp;\n    interval<T> r, r2;\n    T m;\n\n    tmp = x;\n    tmp.a(0) = 0.;\n    r = atan((interval<T>)(x.a(0)));\n    r2 = 1. / sqrt(1. + pow(to_interval(x), 2));\n    m = mid(r2);\n    r += (r2 - m) * to_interval(tmp);\n    \n    return r + m * tmp;\n  }\n\n  // lazy implementation of sinh\n  friend affine sinh(const affine& x) {\n    // return sinh((interval<T>)(x.a(0))) + cosh(to_interval(x)) * (x - x.a(0));\n\n    affine tmp;\n    interval<T> r, r2;\n    T m;\n\n    tmp = x;\n    tmp.a(0) = 0.;\n    r = sinh((interval<T>)(x.a(0)));\n    r2 = cosh(to_interval(x));\n    m = mid(r2);\n    r += (r2 - m) * to_interval(tmp);\n    \n    return r + m * tmp;\n  }\n\n  // lazy implementation of cosh\n  friend affine cosh(const affine& x) {\n    // return cosh((interval<T>)(x.a(0))) + sinh(to_interval(x)) * (x - x.a(0));\n\n    affine tmp;\n    interval<T> r, r2;\n    T m;\n\n    tmp = x;\n    tmp.a(0) = 0.;\n    r = cosh((interval<T>)(x.a(0)));\n    r2 = sinh(to_interval(x));\n    m = mid(r2);\n    r += (r2 - m) * to_interval(tmp);\n    \n    return r + m * tmp;\n  }\n\n  // lazy implementation of tanh\n  friend affine tanh(const affine& x) {\n    // return tanh((interval<T>)(x.a(0))) + pow(cosh(to_interval(x)), -2) * (x - x.a(0));\n\n    affine tmp;\n    interval<T> r, r2;\n    T m;\n\n    tmp = x;\n    tmp.a(0) = 0.;\n    r = tanh((interval<T>)(x.a(0)));\n    r2 = pow(cosh(to_interval(x)), -2);\n    m = mid(r2);\n    r += (r2 - m) * to_interval(tmp);\n    \n    return r + m * tmp;\n  }\n\n  // lazy implementation of asinh\n  friend affine asinh(const affine& x) {\n    // return asinh((interval<T>)(x.a(0))) + (1 / sqrt(pow(to_interval(x), 2) + 1)) * (x - x.a(0));\n\n    affine tmp;\n    interval<T> r, r2;\n    T m;\n\n    tmp = x;\n    tmp.a(0) = 0.;\n    r = asinh((interval<T>)(x.a(0)));\n    r2 = 1 / sqrt(pow(to_interval(x), 2) + 1);\n    m = mid(r2);\n    r += (r2 - m) * to_interval(tmp);\n    \n    return r + m * tmp;\n  }\n\n  // lazy implementation of acosh\n  friend affine acosh(const affine& x) {\n    // return acosh((interval<T>)(x.a(0))) + (1 / sqrt(pow(to_interval(x), 2) - 1)) * (x - x.a(0));\n\n    affine tmp;\n    interval<T> r, r2;\n    T m;\n\n    tmp = x;\n    tmp.a(0) = 0.;\n    r = acosh((interval<T>)(x.a(0)));\n    r2 = 1 / sqrt(pow(to_interval(x), 2) - 1);\n    m = mid(r2);\n    r += (r2 - m) * to_interval(tmp);\n    \n    return r + m * tmp;\n  }\n\n  // lazy implementation of atanh\n  friend affine atanh(const affine& x) {\n    // return atanh((interval<T>)(x.a(0))) + (1 / (1 - pow(to_interval(x), 2))) * (x - x.a(0));\n\n    affine tmp;\n    interval<T> r, r2;\n    T m;\n\n    tmp = x;\n    tmp.a(0) = 0.;\n    r = atanh((interval<T>)(x.a(0)));\n    r2 = 1 / (1 - pow(to_interval(x), 2));\n    m = mid(r2);\n    r += (r2 - m) * to_interval(tmp);\n    \n    return r + m * tmp;\n  }\n\n  friend std::ostream& operator<<(std::ostream& s, const affine& x) {\n    int i;\n\n    s << \"[(\" << x.a(0) << \")\";\n    for (i=1; i<x.a.size(); i++) {\n      s << \"+(\" << x.a(i) << \")e\" << i;\n    }\n    #if AFFINE_SIMPLE >= 1\n    s << \"+(\" << x.er << \")er\";\n    #endif\n    s << \"]\";\n\n    return s;\n  }\n\n  friend inline void split(const affine& x, int n, affine& y, affine& z) {\n    int i;\n    int s = x.a.size();\n  \n    y.a.resize(s);\n    z.a.resize(s);\n    for (i=0; i<=n; i++) {\n      y.a(i) = x.a(i);\n      z.a(i) = 0.;\n    }\n    for (i=n+1; i<s; i++) {\n      y.a(i) = 0.;\n      z.a(i) = x.a(i);\n    }\n    #if AFFINE_SIMPLE >= 1\n    y.er = 0.;\n    z.er = x.er;\n    #endif\n  }\n\n  void resize() {\n    int i;\n    ub::vector<T> r;\n\n    r.resize(maxnum()+1);\n    for (i=0; i<=maxnum(); i++) {\n      r(i) = a(i);\n    }\n\n    a = r;\n  }\n};\n\n\ntemplate <class T> inline ub::vector< interval<T> > to_interval(const ub::vector< affine<T> >& x) {\n  int s = x.size();\n  ub::vector< interval<T> > r;\n  int i;\n\n  r.resize(s);\n  for (i=0; i<s; i++) r(i) = to_interval(x(i));\n\n  return r;\n}\n\n\n/*\n * epsilon_reduce(x, n, n_limit)\n *  x: vector of affine (overwrited)\n *  reduce the number of epsilons to n if the number of epsilons > n_limit.\n *  \n *  s: size of x\n *  keep n-s \"important\" epsilons and convert other \"non-important\" epsilons\n *  to s-dimensional rectangular.\n */\n\n\n// a class to store column vector and its \"importance\"\n\ntemplate <class T> class ep_reduce_v {\n  public:\n  ub::vector<T> v;\n  T score;\n  int index; // @hylagi to identify intervalized dummy variables\n  void calc_score() {\n    int s = v.size();\n    int i, j;\n    T m1, m2, tmp;\n    using std::abs;\n    if (s<2){score = abs(v(0)); return;} // @hylagi\n    m1 = abs(v(0));\n    if (s == 1) {\n      score = m1;\n      return;\n    }\n    m2 = abs(v(1));\n    if (m2 > m1) {\n      tmp = m2; m2 = m1; m1 = tmp;\n    }\n    for (i=2; i<s; i++) {\n      tmp = abs(v(i));\n      if (tmp > m1) {\n        m2 = m1; m1 = tmp;\n      } else if (tmp > m2) {\n        m2 = tmp;\n      }\n    }\n    if (m1 == 0.) score = 0.;\n    else score = (m1*m2)/(m1+m2);\n  }\n};\n\n\n// function to sort column vector by score\n\ntemplate <class T> inline bool ep_reduce_cmp(ep_reduce_v<T>* a, ep_reduce_v<T>* b) {\n#ifdef EP_REDUCE_REVERSE\n  return a->score < b->score;\n#else\n  return a->score > b->score;\n#endif\n}\n//template <class T> inline void epsilon_reduce(ub::vector< affine<T> >& x, int n, int n_limit = 0) {\ntemplate <class T> inline std::map<int, int> epsilon_reduce(ub::vector< affine<T> >& x, int n, int n_limit = 0) { // @hylagi modified\n  int s = x.size();\n  int m = affine<T>::maxnum();\n  int i, j;\n  std::vector< ep_reduce_v<T> > a;\n  std::vector< ep_reduce_v<T>* > pa;\n  ub::vector< affine<T> > r;\n  T tmp;\n  std::map<int, int> result_map; // @hylagi\n\n  if (n_limit < n) n_limit = n;\n\n  // if (m <= n_limit) return;\n  // if (n < s) return; // impossible\n  // @hylagi modified\n  if (m <= n_limit) return result_map;\n  if (n < s) return result_map; // impossible\n\n  a.resize(m);\n  pa.resize(m);\n\n  for (i=1; i<=m; i++) {\n    a[i-1].v.resize(s);\n    a[i-1].index = i; // @hylagi\n    result_map.insert(std::make_pair(i, -1)); // @hylagi\n    for (j=0; j<s; j++) {\n      a[i-1].v(j) = (i < x(j).a.size()) ? x(j).a(i) : (T)0.;\n    }\n    a[i-1].calc_score();\n    pa[i-1] = &(a[i-1]);\n  }\n\n#ifdef EP_REDUCE_REVERSE\n  std::partial_sort(pa.begin(), pa.begin()+m-n+s, pa.end(), ep_reduce_cmp<T>);\n#else\n  std::partial_sort(pa.begin(), pa.begin()+n-s, pa.end(), ep_reduce_cmp<T>);\n#endif\n\n  r.resize(s);\n  for (i=0; i<s; i++) {\n    r(i).a.resize(n+1);\n    r(i).a(0) = x(i).a(0);\n    for (j=0; j<n-s; j++) {\n#ifdef EP_REDUCE_REVERSE\n      r(i).a(j+1) = pa[m-1-j]->v(i);\n      result_map[pa[m-1-j]->index] = j+1; // @hylagi\n#else\n      r(i).a(j+1) = pa[j]->v(i);\n#endif\n    }\n    tmp = 0.;\n    rop<T>::begin();\n    for (j=n-s; j<m; j++) {\n      using std::abs;\n#ifdef EP_REDUCE_REVERSE\n      tmp = rop<T>::add_up(tmp, abs(pa[m-1-j]->v(i)));\n#else\n      tmp = rop<T>::add_up(tmp, abs(pa[j]->v(i)));\n#endif\n    }\n    #if AFFINE_SIMPLE >= 1\n    tmp = rop<T>::add_up(tmp, x(i).er);\n    #endif\n    rop<T>::end();\n    for (j=n-s; j<n; j++) {\n      r(i).a(j+1) = 0.;\n    }\n    r(i).a(n-s+i+1) = tmp;\n    #if AFFINE_SIMPLE >= 1\n    r(i).er = 0.;\n    #endif\n  }\n\n  x = r;\n  affine<T>::maxnum() = n;\n  return result_map; //@hylagi\n}\n\n\n\n// simple version of epsilon_reduce\n// keep ep_1...ep_n and \"intervalize\" epsilons newer than ep_n\n\ntemplate <class T> inline void epsilon_reduce2(ub::vector< affine<T> >& x, int n) {\n  int s = x.size();\n  int i, j;\n  T tmp;\n\n  for (i=0; i<s; i++) {\n    tmp = 0.;\n    rop<T>::begin();\n    for (j=n+1; j<x(i).a.size(); j++) {\n      using std::abs;\n      tmp = rop<T>::add_up(tmp, abs(x(i).a(j)));\n    }\n    #if AFFINE_SIMPLE >= 1\n    tmp = rop<T>::add_up(tmp, x(i).er);\n    #endif\n    rop<T>::end();\n\n    x(i).a.resize(n+1+i+1, true);\n    for (j=0; j<i; j++) {\n      x(i).a(n+1+j) = 0.;\n    }\n    x(i).a(n+1+i) = tmp;\n    #if AFFINE_SIMPLE >= 1\n    x(i).er = 0.;\n    #endif\n  }\n\n  affine<T>::maxnum() = n + s;\n}\n\n\ntemplate <class T> struct constants< affine<T> > {\n  static affine<T> pi() {\n    static const affine<T> tmp(constants< interval<T> >::pi());\n    return tmp;\n  }\n\n  static affine<T> e() {\n    static const affine<T> tmp(constants< interval<T> >::e());\n    return tmp;\n  }\n\n  static affine<T> ln2() {\n    static const affine<T> tmp(constants< interval<T> >::ln2());\n    return tmp;\n  }\n  static affine<T> str(const std::string& s) {\n    return affine<T>(constants< interval<T> >::str(s));\n  }\n  static affine<T> str(const std::string& s1, const std::string& s2) {\n    return affine<T>(constants< interval<T> >::str(s1, s2));\n  }\n};\n\n\n} // namespace kv\n\n#endif //AFFINE_HPP\n", "meta": {"hexsha": "b7a01f62d7ce9166b8307cef0a1c95773e522b82", "size": 44516, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/interval/kv/affine.hpp", "max_stars_repo_name": "takafumihoriuchi/HyLaGI", "max_stars_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T07:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T07:11:09.000Z", "max_issues_repo_path": "src/interval/kv/affine.hpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interval/kv/affine.hpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6159151194, "max_line_length": 183, "alphanum_fraction": 0.4985398508, "num_tokens": 15525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.43320573594549694}}
{"text": "/*\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2013 Fernando J. Iglesias Garcia\n * Copyright (C) 2013 Fernando J. Iglesias Garcia\n */\n\n#ifdef HAVE_EIGEN3\n\n#include <shogun/distance/CustomMahalanobisDistance.h>\n#include <Eigen/Dense>\n\nusing namespace shogun;\nusing namespace Eigen;\n\nCCustomMahalanobisDistance::CCustomMahalanobisDistance() : CRealDistance()\n{\n\tregister_params();\n}\n\nCCustomMahalanobisDistance::CCustomMahalanobisDistance(CFeatures* l, CFeatures* r, SGMatrix<float64_t> m)\n: CRealDistance()\n{\n\tregister_params();\n\tCRealDistance::init(l, r);\n\tm_mahalanobis_matrix = m;\n}\n\nvoid CCustomMahalanobisDistance::register_params()\n{\n\tSG_ADD(&m_mahalanobis_matrix, \"m_mahalanobis_matrix\", \"Mahalanobis matrix\", MS_NOT_AVAILABLE)\n}\n\nCCustomMahalanobisDistance::~CCustomMahalanobisDistance()\n{\n\tcleanup();\n}\n\nvoid CCustomMahalanobisDistance::cleanup()\n{\n}\n\nconst char* CCustomMahalanobisDistance::get_name() const\n{\n\treturn \"CustomMahalanobisDistance\";\n}\n\nEDistanceType CCustomMahalanobisDistance::get_distance_type()\n{\n\treturn D_CUSTOMMAHALANOBIS;\n}\n\nfloat64_t CCustomMahalanobisDistance::compute(int32_t idx_a, int32_t idx_b)\n{\n\t// Get feature vectors that will be used to compute the distance; casts\n\t// are safe, features are checked to be dense in DenseDistance::init\n\tSGVector<float64_t> avec = static_cast<CDenseFeatures<float64_t>*>(lhs)->get_feature_vector(idx_a);\n\tSGVector<float64_t> bvec = static_cast<CDenseFeatures<float64_t>*>(rhs)->get_feature_vector(idx_b);\n\n\tREQUIRE(avec.vlen == bvec.vlen, \"In CCustomMahalanobisDistance::compute the \"\n\t\t\t\"feature vectors must have the same number of elements\")\n\n\t// Compute the distance between the feature vectors\n\n\t// Compute the difference vector and wrap in Eigen vector\n\tconst VectorXd dvec = Map<const VectorXd>(avec, avec.vlen) - Map<const VectorXd>(bvec, bvec.vlen);\n\t// Wrap Mahalanobis distance in Eigen matrix\n\tMap<const MatrixXd> M(m_mahalanobis_matrix.matrix, m_mahalanobis_matrix.num_rows,\n\t\t\tm_mahalanobis_matrix.num_cols);\n\n\treturn dvec.transpose()*M*dvec;\n}\n\n#endif /* HAVE_EIGEN3 */\n", "meta": {"hexsha": "d9bcfce5538fd92a37578828c7a70155ccc9440e", "size": 2284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/shogun/distance/CustomMahalanobisDistance.cpp", "max_stars_repo_name": "srgnuclear/shogun", "max_stars_repo_head_hexsha": "33c04f77a642416376521b0cd1eed29b3256ac13", "max_stars_repo_licenses": ["Ruby", "MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-11-05T18:31:14.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-05T18:31:14.000Z", "max_issues_repo_path": "src/shogun/distance/CustomMahalanobisDistance.cpp", "max_issues_repo_name": "waderly/shogun", "max_issues_repo_head_hexsha": "9288b6fa38e001d63c32188f7f847dadea66e2ae", "max_issues_repo_licenses": ["Ruby", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/shogun/distance/CustomMahalanobisDistance.cpp", "max_forks_repo_name": "waderly/shogun", "max_forks_repo_head_hexsha": "9288b6fa38e001d63c32188f7f847dadea66e2ae", "max_forks_repo_licenses": ["Ruby", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2820512821, "max_line_length": 105, "alphanum_fraction": 0.7793345009, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4331818707949549}}
{"text": "//  Copyright John Maddock 2006.\n//  Copyright Paul A. Bristow 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_STATS_STUDENTS_T_HPP\n#define BOOST_STATS_STUDENTS_T_HPP\n\n// http://en.wikipedia.org/wiki/Student%27s_t_distribution\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3664.htm\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/special_functions/beta.hpp> // for ibeta(a, b, x).\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n\n#include <utility>\n\n#ifdef BOOST_MSVC\n# pragma warning(push)\n# pragma warning(disable: 4702) // unreachable code (return after domain_error throw).\n#endif\n\nnamespace boost{ namespace math{\n\ntemplate <class RealType = double, class Policy = policies::policy<> >\nclass students_t_distribution\n{\npublic:\n   typedef RealType value_type;\n   typedef Policy policy_type;\n\n   students_t_distribution(RealType i) : m_df(i)\n   { // Constructor.\n      RealType result;\n      detail::check_df(\n         \"boost::math::students_t_distribution<%1%>::students_t_distribution\", m_df, &result, Policy());\n   } // students_t_distribution\n\n   RealType degrees_of_freedom()const\n   {\n      return m_df;\n   }\n\n   // Parameter estimation:\n   static RealType find_degrees_of_freedom(\n      RealType difference_from_mean,\n      RealType alpha,\n      RealType beta,\n      RealType sd,\n      RealType hint = 100);\n\nprivate:\n   //\n   // Data members:\n   //\n   RealType m_df;  // degrees of freedom are a real number.\n};\n\ntypedef students_t_distribution<double> students_t;\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> range(const students_t_distribution<RealType, Policy>& /*dist*/)\n{ // Range of permissible values for random variable x.\n   using boost::math::tools::max_value;\n   return std::pair<RealType, RealType>(-max_value<RealType>(), max_value<RealType>());\n}\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> support(const students_t_distribution<RealType, Policy>& /*dist*/)\n{ // Range of supported values for random variable x.\n   // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\n   using boost::math::tools::max_value;\n   return std::pair<RealType, RealType>(-max_value<RealType>(), max_value<RealType>());\n}\n\ntemplate <class RealType, class Policy>\ninline RealType pdf(const students_t_distribution<RealType, Policy>& dist, const RealType& t)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   RealType degrees_of_freedom = dist.degrees_of_freedom();\n   // Error check:\n   RealType error_result;\n   if(false == detail::check_df(\n      \"boost::math::pdf(const students_t_distribution<%1%>&, %1%)\", degrees_of_freedom, &error_result, Policy()))\n      return error_result;\n   // Might conceivably permit df = +infinity and use normal distribution.\n   RealType result;\n   RealType basem1 = t * t / degrees_of_freedom;\n   if(basem1 < 0.125)\n   {\n      result = exp(-boost::math::log1p(basem1, Policy()) * (1+degrees_of_freedom) / 2);\n   }\n   else\n   {\n      result = pow(1 / (1 + basem1), (degrees_of_freedom + 1) / 2);\n   }\n   result /= sqrt(degrees_of_freedom) * boost::math::beta(degrees_of_freedom / 2, RealType(0.5f), Policy());\n   return result;\n} // pdf\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const students_t_distribution<RealType, Policy>& dist, const RealType& t)\n{\n   RealType degrees_of_freedom = dist.degrees_of_freedom();\n   // Error check:\n   RealType error_result;\n   if(false == detail::check_df(\n      \"boost::math::cdf(const students_t_distribution<%1%>&, %1%)\", degrees_of_freedom, &error_result, Policy()))\n      return error_result;\n\n   if (t == 0)\n   {\n     return 0.5;\n   }\n   //\n   // Calculate probability of Student's t using the incomplete beta function.\n   // probability = ibeta(degrees_of_freedom / 2, 1/2, degrees_of_freedom / (degrees_of_freedom + t*t))\n   //\n   // However when t is small compared to the degrees of freedom, that formula\n   // suffers from rounding error, use the identity formula to work around\n   // the problem:\n   //\n   // I[x](a,b) = 1 - I[1-x](b,a)\n   //\n   // and:\n   //\n   //     x = df / (df + t^2)\n   //\n   // so:\n   //\n   // 1 - x = t^2 / (df + t^2)\n   //\n   RealType t2 = t * t;\n   RealType probability;\n   if(degrees_of_freedom > 2 * t2)\n   {\n      RealType z = t2 / (degrees_of_freedom + t2);\n      probability = ibetac(static_cast<RealType>(0.5), degrees_of_freedom / 2, z, Policy()) / 2;\n   }\n   else\n   {\n      RealType z = degrees_of_freedom / (degrees_of_freedom + t2);\n      probability = ibeta(degrees_of_freedom / 2, static_cast<RealType>(0.5), z, Policy()) / 2;\n   }\n   return (t > 0 ? 1   - probability : probability);\n} // cdf\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const students_t_distribution<RealType, Policy>& dist, const RealType& p)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n   //\n   // Obtain parameters:\n   //\n   RealType degrees_of_freedom = dist.degrees_of_freedom();\n   RealType probability = p;\n   //\n   // Check for domain errors:\n   //\n   static const char* function = \"boost::math::quantile(const students_t_distribution<%1%>&, %1%)\";\n   RealType error_result;\n   if(false == detail::check_df(\n      function, degrees_of_freedom, &error_result, Policy())\n         && detail::check_probability(function, probability, &error_result, Policy()))\n      return error_result;\n\n   // Special cases, regardless of degrees_of_freedom.\n   if (probability == 0)\n      return -policies::raise_overflow_error<RealType>(function, 0, Policy());\n   if (probability == 1)\n     return policies::raise_overflow_error<RealType>(function, 0, Policy());\n   if (probability == static_cast<RealType>(0.5))\n     return 0;\n   //\n   // This next block is disabled in favour of a faster method than\n   // incomplete beta inverse, code retained for future reference:\n   //\n#if 0\n   //\n   // Calculate quantile of Student's t using the incomplete beta function inverse:\n   //\n   probability = (probability > 0.5) ? 1 - probability : probability;\n   RealType t, x, y;\n   x = ibeta_inv(degrees_of_freedom / 2, RealType(0.5), 2 * probability, &y);\n   if(degrees_of_freedom * y > tools::max_value<RealType>() * x)\n      t = tools::overflow_error<RealType>(function);\n   else\n      t = sqrt(degrees_of_freedom * y / x);\n   //\n   // Figure out sign based on the size of p:\n   //\n   if(p < 0.5)\n      t = -t;\n\n   return t;\n#endif\n   //\n   // Depending on how many digits RealType has, this may forward\n   // to the incomplete beta inverse as above.  Otherwise uses a\n   // faster method that is accurate to ~15 digits everywhere\n   // and a couple of epsilon at double precision and in the central \n   // region where most use cases will occur...\n   //\n   return boost::math::detail::fast_students_t_quantile(degrees_of_freedom, probability, Policy());\n} // quantile\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const complemented2_type<students_t_distribution<RealType, Policy>, RealType>& c)\n{\n   return cdf(c.dist, -c.param);\n}\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const complemented2_type<students_t_distribution<RealType, Policy>, RealType>& c)\n{\n   return -quantile(c.dist, c.param);\n}\n\n//\n// Parameter estimation follows:\n//\nnamespace detail{\n//\n// Functors for finding degrees of freedom:\n//\ntemplate <class RealType, class Policy>\nstruct sample_size_func\n{\n   sample_size_func(RealType a, RealType b, RealType s, RealType d)\n      : alpha(a), beta(b), ratio(s*s/(d*d)) {}\n\n   RealType operator()(const RealType& df)\n   {\n      if(df <= tools::min_value<RealType>())\n         return 1;\n      students_t_distribution<RealType, Policy> t(df);\n      RealType qa = quantile(complement(t, alpha));\n      RealType qb = quantile(complement(t, beta));\n      qa += qb;\n      qa *= qa;\n      qa *= ratio;\n      qa -= (df + 1);\n      return qa;\n   }\n   RealType alpha, beta, ratio;\n};\n\n}  // namespace detail\n\ntemplate <class RealType, class Policy>\nRealType students_t_distribution<RealType, Policy>::find_degrees_of_freedom(\n      RealType difference_from_mean,\n      RealType alpha,\n      RealType beta,\n      RealType sd,\n      RealType hint)\n{\n   static const char* function = \"boost::math::students_t_distribution<%1%>::find_degrees_of_freedom\";\n   //\n   // Check for domain errors:\n   //\n   RealType error_result;\n   if(false == detail::check_probability(\n      function, alpha, &error_result, Policy())\n         && detail::check_probability(function, beta, &error_result, Policy()))\n      return error_result;\n\n   if(hint <= 0)\n      hint = 1;\n\n   detail::sample_size_func<RealType, Policy> f(alpha, beta, sd, difference_from_mean);\n   tools::eps_tolerance<RealType> tol(policies::digits<RealType, Policy>());\n   boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();\n   std::pair<RealType, RealType> r = tools::bracket_and_solve_root(f, hint, RealType(2), false, tol, max_iter, Policy());\n   RealType result = r.first + (r.second - r.first) / 2;\n   if(max_iter == policies::get_max_root_iterations<Policy>())\n   {\n      policies::raise_evaluation_error<RealType>(function, \"Unable to locate solution in a reasonable time:\"\n         \" either there is no answer to how many degrees of freedom are required\"\n         \" or the answer is infinite.  Current best guess is %1%\", result, Policy());\n   }\n   return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType mean(const students_t_distribution<RealType, Policy>& )\n{\n   return 0;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType variance(const students_t_distribution<RealType, Policy>& dist)\n{\n   // Error check:\n   RealType error_result;\n   if(false == detail::check_df(\n      \"boost::math::variance(students_t_distribution<%1%> const&, %1%)\", dist.degrees_of_freedom(), &error_result, Policy()))\n      return error_result;\n\n   RealType v = dist.degrees_of_freedom();\n   return v / (v - 2);\n}\n\ntemplate <class RealType, class Policy>\ninline RealType mode(const students_t_distribution<RealType, Policy>& /*dist*/)\n{\n   return 0;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType median(const students_t_distribution<RealType, Policy>& /*dist*/)\n{\n   return 0;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType skewness(const students_t_distribution<RealType, Policy>& dist)\n{\n   if(dist.degrees_of_freedom() <= 3)\n   {\n      policies::raise_domain_error<RealType>(\n         \"boost::math::skewness(students_t_distribution<%1%> const&, %1%)\",\n         \"Skewness is undefined for degrees of freedom <= 3, but got %1%.\",\n         dist.degrees_of_freedom(), Policy());\n   }\n   return 0;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis(const students_t_distribution<RealType, Policy>& dist)\n{\n   RealType df = dist.degrees_of_freedom();\n   if(df <= 3)\n   {\n      policies::raise_domain_error<RealType>(\n         \"boost::math::kurtosis(students_t_distribution<%1%> const&, %1%)\",\n         \"Skewness is undefined for degrees of freedom <= 3, but got %1%.\",\n         df, Policy());\n   }\n   return 3 * (df - 2) / (df - 4);\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis_excess(const students_t_distribution<RealType, Policy>& dist)\n{\n   // see http://mathworld.wolfram.com/Kurtosis.html\n   RealType df = dist.degrees_of_freedom();\n   if(df <= 3)\n   {\n      policies::raise_domain_error<RealType>(\n         \"boost::math::kurtosis_excess(students_t_distribution<%1%> const&, %1%)\",\n         \"Skewness is undefined for degrees of freedom <= 3, but got %1%.\",\n         df, Policy());\n   }\n   return 6 / (df - 4);\n}\n\n} // namespace math\n} // namespace boost\n\n#ifdef BOOST_MSVC\n# pragma warning(pop)\n#endif\n\n// This include must be at the end, *after* the accessors\n// for this distribution have been defined, in order to\n// keep compilers that support two-phase lookup happy.\n#include <boost/math/distributions/detail/derived_accessors.hpp>\n\n#endif // BOOST_STATS_STUDENTS_T_HPP\n", "meta": {"hexsha": "14bdf9cfe029cd6f3b082bdeb5cf37eda5b9a2ab", "size": 12201, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "vegastrike/boost/1_35/boost/math/distributions/students_t.hpp", "max_stars_repo_name": "Ezeer/VegaStrike_win32FR", "max_stars_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-04T09:40:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-04T09:40:26.000Z", "max_issues_repo_path": "vegastrike/boost/1_35/boost/math/distributions/students_t.hpp", "max_issues_repo_name": "Ezeer/VegaStrike_win32FR", "max_issues_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vegastrike/boost/1_35/boost/math/distributions/students_t.hpp", "max_forks_repo_name": "Ezeer/VegaStrike_win32FR", "max_forks_repo_head_hexsha": "75891b9ccbdb95e48e15d3b4a9cd977955b97d1f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-05-05T22:29:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T14:18:54.000Z", "avg_line_length": 32.536, "max_line_length": 125, "alphanum_fraction": 0.6869928694, "num_tokens": 3183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.4331329689572634}}
{"text": "#ifndef CY_NNQS_UTILITY_HPP\n#define CY_NNQS_UTILITY_HPP\n#include <memory>\n#include <random>\n#include <utility>\n\n#include <Eigen/Dense>\n#include \"Utilities/type_traits.hpp\"\n\nnamespace yannq\n{\n\n//! stable implementation of log(cosh(x)) for real x\ntemplate<typename T>\ninline typename std::enable_if<!is_complex_type<T>::value, T>::type logCosh(T x)\n{\n    const T xp = std::abs(x);\n    if (xp <= 12.) {\n        return std::log(std::cosh(xp));\n    } else {\n        const static T log2v = std::log(2.);\n        return xp - log2v;\n    }   \n}\n\n//! stable implementation of log(cosh(x)) for complex x\ntemplate<typename T>\ninline typename std::enable_if<is_complex_type<T>::value, T>::type logCosh(T x)\n{\n    const auto xr = x.real();\n    const auto xi = x.imag();\n\n    T res = logCosh(xr);\n    res += std::log(T{std::cos(xi), std::tanh(xr) * std::sin(xi)});\n\n    return res;\n}\n\ntemplate<typename T>\ntypename std::enable_if<!is_complex_type<T>::value, T>::type real(const T& v)\n{\n\treturn v;\n}\n\n/*\ntemplate<typename StateT, class AuxData, class Container, class Observable>\nauto calcObs(const AuxData& ad, const Container& sr, Observable& obs)\n\t-> typename std::result_of<Observable(StateT)>::type\n{\n\tusing ResultType = typename std::result_of<Observable(StateT)>::type;\n\tResultType res{};\n\tfor(const auto& elt: sr)\n\t{\n\t\tauto s = construct_state<StateT>(ad, make_rtuple(elt));\n\t\tres += obs(s);\n\t}\n\tres /= sr.size();\n\treturn res;\n}\n*/\n\n//! generate a random vector in the computational basis\ntemplate <typename RandomEngine>\nEigen::VectorXi randomSigma(int n, RandomEngine& re)\n{\n\tEigen::VectorXi sigma(n);\n\tstd::uniform_int_distribution<> uid(0, 1);\n\t//randomly initialize currSigma\n\tfor(int i = 0; i < n; i++)\n\t{\n\t\tsigma(i) = -2*uid(re)+1;\n\t}\n\treturn sigma;\n}\n//! generate a random vector in the computational basis with the constraint that\n//! the number |1>=|\\sigma_z = -1> is nup.\ntemplate <typename RandomEngine>\nEigen::VectorXi randomSigma(int n, int nup, RandomEngine& re)\n{\n\tstd::vector<int> sigma(n,-1);\n\t//randomly initialize currSigma\n\tfor(int i = nup; i < n; i++)\n\t{\n\t\tsigma[i] = 1;\n\t}\n\tstd::shuffle(sigma.begin(), sigma.end(), re);\n\treturn Eigen::Map<Eigen::VectorXi>(sigma.data(), n);\n}\n\n//! generate a vector that the binary representation is val.\nEigen::VectorXi toSigma(int length, uint32_t val)\n{\n\tEigen::VectorXi res(length);\n\tfor(int i = 0; i < length; i++)\n\t{\n\t\tres(i) = 1-2*((val >> i) & 1);\n\t}\n\treturn res;\n}\n\n//! returns the binary representation of sigma.\nlong long int toValue(const Eigen::VectorXi& sigma)\n{\n\tlong long int res = 0;\n\tfor(int i = 0; i < sigma.size(); i++)\n\t{\n\t\tres += (1 << i)*((1-sigma(i))/2);\n\t}\n\treturn res;\n}\n\n\n//! for complex type T, generate a vector filled with samples from normal distribution.\ntemplate<typename T, class RandomEngine, typename std::enable_if<is_complex_type<T>::value, int>::type = 0 >\nEigen::Matrix<T, Eigen::Dynamic, 1> randomVector(RandomEngine&& re, \n\t\tremove_complex_t<T> sigma, std::size_t nelt)\n{\n\tEigen::Matrix<T, Eigen::Dynamic, 1> res(nelt);\n\tstd::normal_distribution<typename remove_complex<T>::type> dist(0.0, sigma);\n\tfor(std::size_t i = 0; i < nelt; i++)\n\t{\n\t\tres(i) = T{dist(re),dist(re)};\n\t}\n\treturn res;\n}\n//! for real type T, generate a vector filled with samples from normal distribution.\ntemplate<typename T, class RandomEngine, typename std::enable_if<!is_complex_type<T>::value, int>::type = 0 >\nEigen::Matrix<T, Eigen::Dynamic, 1> randomVector(RandomEngine&& re, \n\t\tremove_complex_t<T> sigma, std::size_t nelt)\n{\n\tEigen::Matrix<T, Eigen::Dynamic, 1> res(nelt);\n\tstd::normal_distribution<T> dist(0.0, sigma);\n\tfor(std::size_t i = 0; i < nelt; i++)\n\t{\n\t\tres(i) = dist(re);\n\t}\n\treturn res;\n}\n\n}//namespace yannq\n\n#endif//CY_NNQS_UTILITY_HPP\n", "meta": {"hexsha": "0e553b4d233adaf4956efcb7d421c99ee9e36740", "size": 3719, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Utilities/Utility.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Utilities/Utility.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Utilities/Utility.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.006993007, "max_line_length": 109, "alphanum_fraction": 0.6735681635, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4330784274282532}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_GIS_GEOGRAPHIC_STRATEGIES_ANDOYER_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_GIS_GEOGRAPHIC_STRATEGIES_ANDOYER_HPP\n\n\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/extensions/gis/geographic/detail/ellipsoid.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n\n/*!\n\\brief Point-point distance approximation taking flattening into account\n\\ingroup distance\n\\tparam RadiusType Type of specified radius of the Earth\n\\tparam CalculationType \\tparam_calculation\n\\author After Andoyer, 19xx, republished 1950, republished by Meeus, 1999\n\\note Although not so well-known, the approximation is very good: in all cases the results\nare about the same as Vincenty. In my (Barend's) testcases the results didn't differ more than 6 m\n\\see http://nacc.upc.es/tierra/node16.html\n\\see http://sci.tech-archive.net/Archive/sci.geo.satellite-nav/2004-12/2724.html\n\\see http://home.att.net/~srschmitt/great_circle_route.html (implementation)\n\\see http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115 (implementation)\n\\see http://futureboy.homeip.net/frinksamp/navigation.frink (implementation)\n\\see http://www.voidware.com/earthdist.htm (implementation)\n*/\ntemplate\n<\n    typename RadiusType,\n    typename CalculationType = void\n>\nclass andoyer\n{\npublic :\n    template <typename Point1, typename Point2>\n    struct calculation_type\n        : promote_floating_point\n          <\n              typename select_calculation_type\n                  <\n                      Point1,\n                      Point2,\n                      CalculationType\n                  >::type\n          >\n    {};\n\n    typedef RadiusType radius_type;\n\n    inline andoyer()\n        : m_ellipsoid()\n    {}\n\n    explicit inline andoyer(RadiusType f)\n        : m_ellipsoid(f)\n    {}\n\n    explicit inline andoyer(geometry::detail::ellipsoid<RadiusType> const& e)\n        : m_ellipsoid(e)\n    {}\n\n\n    template <typename Point1, typename Point2>\n    inline typename calculation_type<Point1, Point2>::type\n    apply(Point1 const& point1, Point2 const& point2) const\n    {\n        return calc<typename calculation_type<Point1, Point2>::type>\n            (\n                get_as_radian<0>(point1), get_as_radian<1>(point1),\n                get_as_radian<0>(point2), get_as_radian<1>(point2)\n            );\n    }\n\n    inline geometry::detail::ellipsoid<RadiusType> ellipsoid() const\n    {\n        return m_ellipsoid;\n    }\n\n    inline RadiusType radius() const\n    {\n        return m_ellipsoid.a();\n    }\n\n\nprivate :\n    geometry::detail::ellipsoid<RadiusType> m_ellipsoid;\n\n    template <typename CT, typename T>\n    inline CT calc(T const& lon1,\n                T const& lat1,\n                T const& lon2,\n                T const& lat2) const\n    {\n        CT const G = (lat1 - lat2) / 2.0;\n        CT const lambda = (lon1 - lon2) / 2.0;\n\n        if (geometry::math::equals(lambda, 0.0)\n            && geometry::math::equals(G, 0.0))\n        {\n            return 0.0;\n        }\n\n        CT const F = (lat1 + lat2) / 2.0;\n\n        CT const sinG2 = math::sqr(sin(G));\n        CT const cosG2 = math::sqr(cos(G));\n        CT const sinF2 = math::sqr(sin(F));\n        CT const cosF2 = math::sqr(cos(F));\n        CT const sinL2 = math::sqr(sin(lambda));\n        CT const cosL2 = math::sqr(cos(lambda));\n\n        CT const S = sinG2 * cosL2 + cosF2 * sinL2;\n        CT const C = cosG2 * cosL2 + sinF2 * sinL2;\n\n        CT const c0 = 0;\n        CT const c1 = 1;\n        CT const c2 = 2;\n        CT const c3 = 3;\n\n        if (geometry::math::equals(S, c0) || geometry::math::equals(C, c0))\n        {\n            return c0;\n        }\n\n        CT const omega = atan(sqrt(S / C));\n        CT const r3 = c3 * sqrt(S * C) / omega; // not sure if this is r or greek nu\n        CT const D = c2 * omega * m_ellipsoid.a();\n        CT const H1 = (r3 - c1) / (c2 * C);\n        CT const H2 = (r3 + c1) / (c2 * S);\n        CT const f = m_ellipsoid.f();\n\n        return D * (c1 + f * H1 * sinF2 * cosG2 - f * H2 * cosF2 * sinG2);\n    }\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct tag<andoyer<RadiusType, CalculationType> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename RadiusType, typename CalculationType, typename P1, typename P2>\nstruct return_type<andoyer<RadiusType, CalculationType>, P1, P2>\n    : andoyer<RadiusType, CalculationType>::template calculation_type<P1, P2>\n{};\n\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct comparable_type<andoyer<RadiusType, CalculationType> >\n{\n    typedef andoyer<RadiusType, CalculationType> type;\n};\n\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct get_comparable<andoyer<RadiusType, CalculationType> >\n{\n    static inline andoyer<RadiusType, CalculationType> apply(andoyer<RadiusType, CalculationType> const& input)\n    {\n        return input;\n    }\n};\n\ntemplate <typename RadiusType, typename CalculationType, typename P1, typename P2>\nstruct result_from_distance<andoyer<RadiusType, CalculationType>, P1, P2>\n{\n    template <typename T>\n    static inline typename return_type<andoyer<RadiusType, CalculationType>, P1, P2>::type \n        apply(andoyer<RadiusType, CalculationType> const& , T const& value)\n    {\n        return value;\n    }\n};\n\n\ntemplate <typename Point1, typename Point2>\nstruct default_strategy<point_tag, Point1, Point2, geographic_tag, geographic_tag>\n{\n    typedef strategy::distance::andoyer<typename select_coordinate_type<Point1, Point2>::type> type;\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n}} // namespace strategy::distance\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_GIS_GEOGRAPHIC_STRATEGIES_ANDOYER_HPP\n", "meta": {"hexsha": "4c29e7141d3cace4a376a7611e929af004ca19b5", "size": 6399, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/gis/geographic/strategies/andoyer.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "boost/geometry/extensions/gis/geographic/strategies/andoyer.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "boost/geometry/extensions/gis/geographic/strategies/andoyer.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 29.3532110092, "max_line_length": 111, "alphanum_fraction": 0.672761369, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4330784274282532}}
{"text": "#include <votca/ctp/ewald3d.h>\n#include <votca/tools/globals.h>\n#include <boost/format.hpp>\n#include <algorithm>\n\n\nusing boost::format;\n\nnamespace votca { namespace ctp {\n\n\nEwald3D3D::~Ewald3D3D() { ; }\n    \n    \nEwald3D3D::Ewald3D3D(Topology *top, PolarTop *ptop, Property *opt, Logger *log) \n  : Ewald3DnD(top, ptop, opt, log) {}\n\n\nEWD::triple<> Ewald3D3D::ConvergeReciprocalSpaceSum(vector<PolarSeg*> &target) {\n\n    const double int2eV = votca::tools::globals::conversion::int2eV;\n        \n    vector<PolarSeg*>::iterator sit;\n    vector<APolarSite*> ::iterator pit;    \n    \n    // CELLS OF THE RECIPROCAL LATTICE: SUM OVER ELLIPSOIDAL SHELLS\n    // ... Shell-size increment is magnitude of largest reciprocal cell vector\n    // ... Tschebyschow/Euclidean norm is used to group k-vectors into k-shells \n    \n    vector< vector<vec> > shell_ks;\n    vector< vector<vec> >::iterator shellit;\n    double shell_dk = (maxnorm(_A) > maxnorm(_B)) ?\n        ((maxnorm(_A) > maxnorm(_C)) ? maxnorm(_A) : maxnorm(_C)) \n      : ((maxnorm(_B) > maxnorm(_C)) ? maxnorm(_B) : maxnorm(_C));\n    // Determine all k-vectors within k-space cut-off\n    vector< vec >::iterator kit;\n    vector< vec > ks;\n    for (int kx = -_NA_max; kx < _NA_max+1; ++kx) {\n        for (int ky = -_NB_max; ky < _NB_max+1; ++ky) {\n            for (int kz = -_NC_max; kz < _NC_max+1; ++kz) {\n                if (kx == 0 && ky == 0 && kz == 0) continue;\n                vec k = kx*_A + ky*_B + kz*_C;\n                if (maxnorm(k) > _K_co) continue;\n                ks.push_back(k);\n            }\n        }\n    }\n    // Sort according to magnitude\n    std::sort(ks.begin(), ks.end(), _eucsort);\n    // Group into shells\n    int shell_idx = 0;\n    kit = ks.begin();\n    shell_ks.resize(int(_K_co/shell_dk+0.5)+1);\n    double shell_k = shell_dk;\n    while (shell_k <= _K_co) {\n        for ( ; kit < ks.end(); ++kit) {\n            vec k = *kit;\n            if (maxnorm(k) <= shell_k) {\n                // Add to current shell\n                shell_ks[shell_idx].push_back(k);\n            }\n            else {\n                // Open new shell\n                shell_k += shell_dk;\n                shell_idx += 1;\n                shell_ks[shell_idx].push_back(k);\n                break;\n            }\n        }\n        // All k-vectors consumed?\n        if (kit == ks.end()) break;\n    }\n//    for (int i = 0; i < shell_ks.size(); ++i) {\n//        std::ofstream ofs;\n//        string outfile = (format(\"shell_%1$d.out\") % (i+1)).str();\n//        ofs.open(outfile.c_str(), ofstream::out);\n//        for (kit = shell_ks[i].begin(); kit < shell_ks[i].end(); ++kit) {\n//            ofs << (*kit).getX() << \" \" << (*kit).getY() << \" \" << (*kit).getZ() << endl;\n//        }\n//        ofs.close();\n//    }\n     \n        \n    // K=K TERM\n    CTP_LOG(logDEBUG,*_log) << flush;\n    double EKK_fgC_bgP = 0.0;    \n    unsigned int N_EKK_memory = (unsigned int)(0.5*(_NA_max+_NB_max)+0.5);\n    int N_K_proc = 0;\n    int N_shells_proc = 0;\n    vector< double > dEKKs;\n    _converged_K = false;\n    \n    double re_E = 0.0;\n    double im_E = 0.0;\n    \n    for (shellit = shell_ks.begin(); shellit < shell_ks.end(); ++shellit, ++N_shells_proc) {\n        \n        for (kit = (*shellit).begin(); kit < (*shellit).end(); ++kit, ++N_K_proc) {\n            vec k = *kit;\n\n            // K-DEPENDENT FACTOR\n            double K = abs(k);\n            double expkk_k = 4*M_PI*exp(-K*K/(4*_alpha*_alpha)) / (K*K);        \n\n            CTP_LOG(logDEBUG,*_log)\n                << (format(\"k[%5$d] = %1$+1.3f %2$+1.3f %3$+1.3f   |K| = %4$+1.3f 1/nm\") \n                % (k.getX()) % (k.getY()) % (k.getZ()) % K % (N_shells_proc+1));\n\n            // STRUCTURE FACTORS\n            // Calculate structure factor S(k) for FGC\n            double qcos_fgC = 0.0;\n            double qsin_fgC = 0.0;\n            for (sit = target.begin(); sit < target.end(); ++sit) {\n                for (pit = (*sit)->begin(); pit < (*sit)->end(); ++pit) {\n                    qcos_fgC += (*pit)->Q00 * cos(k * (*pit)->getPos());\n                    qsin_fgC += (*pit)->Q00 * sin(k * (*pit)->getPos());\n                }\n            }        \n            // Calculate structure factor S(-k) for BGP\n            double qcos_bgP = 0.0;\n            double qsin_bgP = 0.0;\n            for (sit = _bg_P.begin(); sit < _bg_P.end(); ++sit) {\n                for (pit = (*sit)->begin(); pit < (*sit)->end(); ++pit) {\n                    qcos_bgP += (*pit)->Q00 * cos(-k * (*pit)->getPos());\n                    qsin_bgP += (*pit)->Q00 * sin(-k * (*pit)->getPos());\n                }\n            }\n            // Structure-factor product\n            double re_s1s2 = qcos_fgC*qcos_bgP - qsin_fgC*qsin_bgP;\n            double im_s1s2 = qsin_fgC*qcos_bgP + qcos_fgC*qsin_bgP;\n\n            // REAL & IMAGINARY ENERGY\n            double re_dE = expkk_k * re_s1s2;\n            double im_dE = expkk_k * im_s1s2;        \n            re_E += re_dE;\n            im_E += im_dE;\n\n            CTP_LOG(logDEBUG,*_log)\n                << (format(\"    Re(dE) = %1$+1.7f\")\n                % (re_dE/_LxLyLz*int2eV));\n\n            CTP_LOG(logDEBUG,*_log)\n                << (format(\"    Re(E) = %1$+1.7f Im(E) = %2$+1.7f\")\n                % (re_E/_LxLyLz*int2eV) % (im_E/_LxLyLz*int2eV));        \n\n            // CONVERGED?\n            double dEKK = sqrt(re_dE*re_dE + im_dE*im_dE);\n            double dEKK_rms = 0.0;\n            if (dEKKs.size() < N_EKK_memory) {\n                dEKKs.resize(N_EKK_memory,dEKK);\n            }\n            else {\n                dEKKs[N_K_proc % N_EKK_memory] = dEKK;\n            }\n            for (unsigned int i = 0; i < dEKKs.size(); ++i) {\n                dEKK_rms += dEKKs[i]*dEKKs[i];\n            }\n            dEKK_rms /= dEKKs.size();\n            dEKK_rms = sqrt(dEKK_rms);\n\n            CTP_LOG(logDEBUG,*_log)\n                << (format(\"   RMS(%2$d) = %1$+1.7f\") \n                % (dEKK_rms/_LxLyLz*int2eV) % N_EKK_memory) << flush;\n\n            if (dEKK_rms/_LxLyLz*int2eV <= _crit_dE && N_K_proc > 2 && N_shells_proc > 0) {\n                _converged_K = true;\n                CTP_LOG(logDEBUG,*_log)\n                    << (format(\":::: Converged to precision as of |K| = %1$+1.3f 1/nm\") \n                    % K ) << flush;\n                break;\n            }\n        } // Sum over k's in k-shell\n        if (_converged_K) break;\n    } // Sum over k-shells\n    \n    EKK_fgC_bgP = re_E/_LxLyLz;\n    return EWD::triple<>(EKK_fgC_bgP,0,0);\n}\n\n\nEWD::triple<> Ewald3D3D::CalculateShapeCorrection(vector<PolarSeg*> &target) {\n    \n    vector<PolarSeg*>::iterator sit1; \n    vector<APolarSite*> ::iterator pit1;\n    vector<PolarSeg*>::iterator sit2; \n    vector<APolarSite*> ::iterator pit2;\n    \n    double EJ = 0.0;\n    \n    if (_shape == \"xyslab\") {\n        // DIRECT CALCULATION VIA DOUBLE LOOP\n        // TODO The double-loop can be avoided, but direct summation as below \n        //      appears to be more stable from a numerical point of view\n        for (sit1 = target.begin(); sit1 < target.end(); ++sit1) {\n           for (sit2 = _bg_P.begin(); sit2 < _bg_P.end(); ++sit2) {\n              for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n                 for (pit2 = (*sit2)->begin(); pit2 < (*sit2)->end(); ++pit2) {\n                    double za = (*pit1)->getPos().getZ();\n                    double zb = (*pit2)->getPos().getZ();\n                    EJ += (za-zb)*(za-zb) * (*pit1)->getQ00()*(*pit2)->getQ00();\n                 }\n              }\n           }\n        }\n\n        //    // DECOMPOSITION INTO CHARGE-DENSITY MULTIPOLE MOMENTS\n        //    vec DA = vec(0,0,0);\n        //    vec DA = vec(0,0,0);\n        //    double QA = 0.0;\n        //    double DZZBG = 0.0;\n        //    for (sit1 = target.begin(); sit1 < target.end(); ++sit1) {\n        //        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n        //            DA += (*pit1)->getQ00() * (*pit1)->getPos();\n        //            QA += (*pit1)->getQ00();\n        //        }\n        //    }\n        //    for (sit1 = _bg_P.begin(); sit1 < _bg_P.end(); ++sit1) {\n        //        for (pit1 = (*sit1)->begin(); pit1 < (*sit1)->end(); ++pit1) {\n        //            double zb = (*pit1)->getPos().getZ();\n        //            DB += (*pit1)->getQ00() * (*pit1)->getPos();\n        //            DZZB += (*pit1)->getQ00() * zb*zb;\n        //        }\n        //    }\n        //    EJ = QA*DZZB - 2*(DA.getZ())*(DB.getZ());\n\n        EJ *= - 2*M_PI/_LxLyLz;\n    }\n    else {\n        CTP_LOG(logERROR,*_log)\n            << (format(\"Shape %1$s not implemented. Setting EJ = 0.0 ...\") \n            % _shape) << flush;\n        EJ = 0.0;\n    }\n        \n    return EWD::triple<>(EJ,0,0);\n}\n\n\ndouble Ewald3D3D::CalculateSq2(vec &k) {\n    vector<PolarSeg*>::iterator sit; \n    vector<APolarSite*> ::iterator pit;    \n    double cs = 0.0;\n    double ss = 0.0;    \n    for (sit = _bg_P.begin(); sit < _bg_P.end(); ++sit) {\n        for (pit = (*sit)->begin(); pit < (*sit)->end(); ++pit) {\n            cs += (*pit)->Q00 * cos(k * (*pit)->getPos());\n            ss += (*pit)->Q00 * sin(k * (*pit)->getPos());\n        }\n    }    \n    return cs*cs + ss*ss;\n}\n    \n    \n}}\n", "meta": {"hexsha": "448635c9214e9c8b91078f15803d5719afd5a0ec", "size": 9191, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libctp/ewald3d.cc", "max_stars_repo_name": "jimbach/ctp", "max_stars_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libctp/ewald3d.cc", "max_issues_repo_name": "jimbach/ctp", "max_issues_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libctp/ewald3d.cc", "max_forks_repo_name": "jimbach/ctp", "max_forks_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0431372549, "max_line_length": 92, "alphanum_fraction": 0.4696986182, "num_tokens": 2906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4330784274282532}}
{"text": "#define DEBUG 1\n/**\n * File    : D.cpp\n * Author  : Kazune Takahashi\n * Created : 2020/1/18 21:28:34\n * Powered by Visual Studio Code\n */\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n// ----- boost -----\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n// ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n// constexpr ll MOD{998244353LL}; // be careful\nconstexpr ll MAX_SIZE{3000010LL};\n// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n  }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n  }\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(const Mint &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(const Mint &a) { return *this += -a; }\n  Mint &operator*=(const Mint &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(const Mint &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }\n  bool operator<(const Mint &a) const { return x < a.x; }\n  bool operator<=(const Mint &a) const { return x <= a.x; }\n  bool operator>(const Mint &a) const { return x > a.x; }\n  bool operator>=(const Mint &a) const { return x >= a.x; }\n  bool operator==(const Mint &a) const { return x == a.x; }\n  bool operator!=(const Mint &a) const { return !(*this == a); }\n  const Mint power(ll N)\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n  return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)\n{\n  return Mint<MOD>{lhs} / rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n  return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n  return stream << a.x;\n}\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i = 2LL; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i = 1LL; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\nll lcm(ll x, ll y) { return x / gcd(x, y) * y; }\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\nconstexpr int infty{100000};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n\n// ----- SegTree -----\n\ntemplate <typename T>\nclass SegTree\n{ // 0-indexed, [0, N).\nprivate:\n  int N;\n  vector<T> dat;\n  T unit;  // モノイドの単位元\n  T(*func) // モノイドの演算\n  (T, T);\n  T(*_update) // update で値をどうするか書く\n  (T, T);\n\npublic:\n  SegTree() {}\n\n  SegTree(int n, T unit, T (*func)(T, T), T (*_update)(T, T)) : N{1}, unit{unit}, func{func}, _update{_update}\n  {\n    while (N < n)\n    {\n      N *= 2;\n    }\n    dat = vector<T>(2 * N - 1, unit);\n  }\n\n  void update(int k, T a)\n  {\n    k += N - 1;\n    dat[k] = _update(dat[k], a);\n    while (k > 0)\n    {\n      k = (k - 1) / 2;\n      dat[k] = func(dat[k * 2 + 1], dat[k * 2 + 2]);\n    }\n  }\n\nprivate:\n  T find(int a, int b, int k, int l, int r)\n  {\n    if (r <= a || b <= l)\n    {\n      return unit;\n    }\n    if (a <= l && r <= b)\n    {\n      return dat[k];\n    }\n    T vl = find(a, b, k * 2 + 1, l, (l + r) / 2);\n    T vr = find(a, b, k * 2 + 2, (l + r) / 2, r);\n    return func(vl, vr);\n  }\n\npublic:\n  T find(int a, int b)\n  { // [a, b) の find をする。\n    return find(a, b, 0, 0, N);\n  }\n};\n\n// ----- frequently used examples -----\n\n// for +\nauto func2 = [](auto x, auto y) {\n  return x + y;\n};\nauto _update2 = [](auto x, auto y) {\n  return y;\n};\nconstexpr ll unit2{0LL};\n\n// ----- main() -----\n\nstruct Card\n{\n  int A, B;\n};\n\nusing Info = tuple<int, int>;\n\nint main()\n{\n  int N;\n  cin >> N;\n  vector<Card> V(N);\n  for (auto i = 0; i < N; ++i)\n  {\n    cin >> V[i].A;\n  }\n  for (auto i = 0; i < N; ++i)\n  {\n    cin >> V[i].B;\n  }\n  for (auto i = 1; i < N; i += 2)\n  {\n    swap(V[i].A, V[i].B);\n  }\n  if (N == 1)\n  {\n    cout << 0 << endl;\n    return 0;\n  }\n  int ans{infty};\n  for (auto k = 0; k < (1 << N); ++k)\n  {\n    int cnt{0};\n    for (auto i = 0; i < N; ++i)\n    {\n      cnt += (k >> i) & 1;\n    }\n    if (cnt == N - N / 2)\n    {\n      vector<Info> X, Y;\n      for (auto i = 0; i < N; ++i)\n      {\n        if ((k >> i) & 1)\n        {\n          X.push_back(Info(V[i].A, i));\n        }\n        else\n        {\n          Y.push_back(Info(V[i].B, i));\n        }\n      }\n      sort(X.begin(), X.end());\n      sort(Y.begin(), Y.end());\n      vector<Info> Z;\n      int x = 0, y = 0;\n      while (x < static_cast<int>(X.size()))\n      {\n        Z.push_back(X[x]);\n        ++x;\n        if (y < static_cast<int>(Y.size()))\n        {\n          Z.push_back(Y[y]);\n          ++y;\n        }\n      }\n      assert(static_cast<int>(Z.size()) == N);\n      bool ok{true};\n      for (auto i = 0; i < N - 1; ++i)\n      {\n        if (get<0>(Z[i]) > get<0>(Z[i + 1]))\n        {\n          ok = false;\n          break;\n        }\n      }\n      if (!ok)\n      {\n        continue;\n      }\n#if DEBUG == 1\n      for (auto i = 0; i < N; ++i)\n      {\n        cerr << \"Z[\" << i << \"] = (\" << get<0>(Z[i]) << \", \" << get<1>(Z[i]) << \")\" << endl;\n      }\n#endif\n      SegTree<ll> tree{N, unit2, func2, _update2};\n      int tmp{0};\n      for (auto i = 0; i < N; ++i)\n      {\n        int v{get<1>(Z[i])};\n        tmp += tree.find(v, N);\n        tree.update(v, 1);\n      }\n      ch_min(ans, tmp);\n    }\n  }\n  if (ans == infty)\n  {\n    cout << -1 << endl;\n  }\n  else\n  {\n    cout << ans << endl;\n  }\n}\n", "meta": {"hexsha": "504cea1e0b70054afad17ff88d4bdf19cf555ad6", "size": 7653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2020/0118_keyence2020/D.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2020/0118_keyence2020/D.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2020/0118_keyence2020/D.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 20.1926121372, "max_line_length": 110, "alphanum_fraction": 0.4988893244, "num_tokens": 2618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4330784274282532}}
{"text": "/* boost random/faure.hpp header file\n *\n * Copyright Justinas Vygintas Daugmaudis 2010-2018\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_RANDOM_FAURE_HPP\n#define BOOST_RANDOM_FAURE_HPP\n\n#include <boost/random/detail/qrng_base.hpp>\n\n#include <cmath>\n#include <vector>\n#include <algorithm>\n\n#include <boost/assert.hpp>\n\nnamespace boost {\nnamespace random {\n\n/** @cond */\nnamespace detail {\n\nnamespace qrng_tables {\n\n// There is no particular reason why 187 first primes were chosen\n// to be put into this table. The only reason was, perhaps, that\n// the number of dimensions for Faure generator would be around\n// the same order of magnitude as the number of dimensions supported\n// by the Sobol qrng.\nstruct primes\n{\n  typedef unsigned short value_type;\n\n  BOOST_STATIC_CONSTANT(int, number_of_primes = 187);\n\n  // A function that returns lower bound prime for a given n\n  static value_type lower_bound(std::size_t n)\n  {\n    static const value_type prim_a[number_of_primes] = {\n      2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,\n      59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,\n      127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,\n      191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251,\n      257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,\n      331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,\n      401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,\n      467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557,\n      563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619,\n      631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,\n      709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787,\n      797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863,\n      877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953,\n      967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031,\n      1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093,\n      1097, 1103, 1109, 1117 };\n\n    qrng_detail::dimension_assert(\"Faure\", n, prim_a[number_of_primes - 1]);\n\n    return *std::lower_bound(prim_a, prim_a + number_of_primes, n);\n  }\n};\n\n} // namespace qrng_tables\n} // namespace detail\n\nnamespace qrng_detail {\nnamespace fr {\n\n// Returns the integer part of the logarithm base Base of arg.\n// In erroneous situations, e.g., integer_log(base, 0) the function\n// returns 0 and does not report the error. This is the intended\n// behavior.\ntemplate <typename T>\ninline T integer_log(T base, T arg)\n{\n  T ilog = T();\n  while (base <= arg)\n  {\n    arg /= base; ++ilog;\n  }\n  return ilog;\n}\n\n// Perform exponentiation by squaring (potential for code reuse in multiprecision::powm)\ntemplate <typename T>\ninline T integer_pow(T base, T e)\n{\n  T result = static_cast<T>(1);\n  while (e)\n  {\n    if (e & static_cast<T>(1))\n      result *= base;\n    e >>= 1;\n    base *= base;\n  }\n  return result;\n}\n\n} // namespace fr\n\n// Computes a table of binomial coefficients modulo qs.\ntemplate<typename RealType, typename SeqSizeT, typename PrimeTable>\nstruct binomial_coefficients\n{\n  typedef RealType value_type;\n  typedef SeqSizeT size_type;\n\n  // Binomial values modulo qs_base will never be bigger than qs_base.\n  // We can choose an appropriate integer type to hold modulo values and\n  // shave off memory footprint.\n  typedef typename PrimeTable::value_type packed_uint_t;\n\n  // default copy c-tor is fine\n\n  explicit binomial_coefficients(std::size_t dimension)\n  {\n    resize(dimension);\n  }\n\n  void resize(std::size_t dimension)\n  {\n    qs_base = PrimeTable::lower_bound(dimension);\n\n    // Throw away previously computed coefficients.\n    // This will trigger recomputation on next update\n    coeff.clear();\n  }\n\n  template <typename Iterator>\n  void update(size_type seq, Iterator first, Iterator last)\n  {\n    if (first != last)\n    {\n      const size_type ilog = fr::integer_log(static_cast<size_type>(qs_base), seq);\n      const size_type hisum = ilog + 1;\n      if (coeff.size() != size_hint(hisum)) {\n        ytemp.resize(static_cast<std::size_t>(hisum)); // cast safe because log is small\n        compute_coefficients(hisum);\n        qs_pow = fr::integer_pow(static_cast<size_type>(qs_base), ilog);\n      }\n\n      *first = compute_recip(seq, ytemp.rbegin());\n\n      // Find other components using the Faure method.\n      ++first;\n      for ( ; first != last; ++first)\n      {\n        *first = RealType();\n        RealType r = static_cast<RealType>(1);\n\n        for (size_type i = 0; i != hisum; ++i)\n        {\n          RealType ztemp = ytemp[static_cast<std::size_t>(i)] * upper_element(i, i, hisum);\n          for (size_type j = i + 1; j != hisum; ++j)\n            ztemp += ytemp[static_cast<std::size_t>(j)] * upper_element(i, j, hisum);\n\n          // Sum ( J <= I <= HISUM ) ( old ytemp(i) * binom(i,j) ) mod QS.\n          ytemp[static_cast<std::size_t>(i)] = std::fmod(ztemp, static_cast<RealType>(qs_base));\n          r *= static_cast<RealType>(qs_base);\n          *first += ytemp[static_cast<std::size_t>(i)] / r;\n        }\n      }\n    }\n  }\n\nprivate:\n  inline static size_type size_hint(size_type n)\n  {\n    return n * (n + 1) / 2;\n  }\n\n  packed_uint_t& upper_element(size_type i, size_type j, size_type dim)\n  {\n    BOOST_ASSERT( i < dim );\n    BOOST_ASSERT( j < dim );\n    BOOST_ASSERT( i <= j );\n    return coeff[static_cast<std::size_t>((i * (2 * dim - i + 1)) / 2 + j - i)];\n  }\n\n  template<typename Iterator>\n  RealType compute_recip(size_type seq, Iterator out) const\n  {\n    // Here we do\n    //   Sum ( 0 <= J <= HISUM ) YTEMP(J) * QS**J\n    //   Sum ( 0 <= J <= HISUM ) YTEMP(J) / QS**(J+1)\n    // in one go\n    RealType r = RealType();\n    size_type m, k = qs_pow;\n    for( ; k != 0; ++out, seq = m, k /= qs_base )\n    {\n      m  = seq % k;\n      RealType v  = static_cast<RealType>((seq - m) / k); // RealType <- size type\n      r += v;\n      r /= static_cast<RealType>(qs_base);\n      *out = v; // saves double dereference\n    }\n    return r;\n  }\n\n  void compute_coefficients(const size_type n)\n  {\n    // Resize and initialize to zero\n    coeff.resize(static_cast<std::size_t>(size_hint(n)));\n    std::fill(coeff.begin(), coeff.end(), packed_uint_t());\n\n    // The first row and the diagonal is assigned to 1\n    upper_element(0, 0, n) = 1;\n    for (size_type i = 1; i < n; ++i)\n    {\n      upper_element(0, i, n) = 1;\n      upper_element(i, i, n) = 1;\n    }\n\n    // Computes binomial coefficients MOD qs_base\n    for (size_type i = 1; i < n; ++i)\n    {\n      for (size_type j = i + 1; j < n; ++j)\n      {\n        upper_element(i, j, n) = ( upper_element(i, j-1, n) +\n                                   upper_element(i-1, j-1, n) ) % qs_base;\n      }\n    }\n  }\n\nprivate:\n  packed_uint_t qs_base;\n\n  // here we cache precomputed data; note that binomial coefficients have\n  // to be recomputed iff the integer part of the logarithm of seq changes,\n  // which happens relatively rarely.\n  std::vector<packed_uint_t> coeff; // packed upper (!) triangular matrix\n  std::vector<RealType> ytemp;\n  size_type qs_pow;\n};\n\n} // namespace qrng_detail\n\ntypedef detail::qrng_tables::primes default_faure_prime_table;\n\n/** @endcond */\n\n//!Instantiations of class template faure_engine model a \\quasi_random_number_generator.\n//!The faure_engine uses the algorithm described in\n//! \\blockquote\n//!Henri Faure,\n//!Discrepance de suites associees a un systeme de numeration (en dimension s),\n//!Acta Arithmetica,\n//!Volume 41, 1982, pages 337-351.\n//! \\endblockquote\n//\n//! \\blockquote\n//!Bennett Fox,\n//!Algorithm 647:\n//!Implementation and Relative Efficiency of Quasirandom\n//!Sequence Generators,\n//!ACM Transactions on Mathematical Software,\n//!Volume 12, Number 4, December 1986, pages 362-376.\n//! \\endblockquote\n//!\n//!In the following documentation @c X denotes the concrete class of the template\n//!faure_engine returning objects of type @c RealType, u and v are the values of @c X.\n//!\n//!Some member functions may throw exceptions of type @c std::bad_alloc.\ntemplate<typename RealType, typename SeqSizeT, typename PrimeTable = default_faure_prime_table>\nclass faure_engine\n  : public qrng_detail::qrng_base<\n      faure_engine<RealType, SeqSizeT, PrimeTable>\n    , qrng_detail::binomial_coefficients<RealType, SeqSizeT, PrimeTable>\n    , SeqSizeT\n    >\n{\n  typedef faure_engine<RealType, SeqSizeT, PrimeTable> self_t;\n\n  typedef qrng_detail::binomial_coefficients<RealType, SeqSizeT, PrimeTable> lattice_t;\n  typedef qrng_detail::qrng_base<self_t, lattice_t, SeqSizeT> base_t;\n\n  friend class qrng_detail::qrng_base<self_t, lattice_t, SeqSizeT>;\n\npublic:\n  typedef RealType result_type;\n\n  /** @copydoc boost::random::niederreiter_base2_engine::min() */\n  static BOOST_CONSTEXPR result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()\n  { return static_cast<result_type>(0); }\n\n  /** @copydoc boost::random::niederreiter_base2_engine::max() */\n  static BOOST_CONSTEXPR result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()\n  { return static_cast<result_type>(1); }\n\n  //!Effects: Constructs the `s`-dimensional default Faure quasi-random number generator.\n  //!\n  //!Throws: bad_alloc, invalid_argument.\n  explicit faure_engine(std::size_t s)\n    : base_t(s) // initialize the binomial table here\n  {}\n\n  /** @copydetails boost::random::niederreiter_base2_engine::seed(UIntType)\n   * Throws: bad_alloc.\n   */\n  void seed(SeqSizeT init = 0)\n  {\n    compute_seq(init);\n    base_t::reset_seq(init);\n  }\n\n#ifdef BOOST_RANDOM_DOXYGEN\n  //=========================Doxygen needs this!==============================\n\n  /** @copydoc boost::random::niederreiter_base2_engine::dimension() */\n  std::size_t dimension() const { return base_t::dimension(); }\n\n  /** @copydoc boost::random::niederreiter_base2_engine::operator()() */\n  result_type operator()()\n  {\n    return base_t::operator()();\n  }\n\n  /** @copydoc boost::random::niederreiter_base2_engine::discard(boost::uintmax_t)\n   * Throws: bad_alloc.\n   */\n  void discard(boost::uintmax_t z)\n  {\n    base_t::discard(z);\n  }\n\n  /** Returns true if the two generators will produce identical sequences of outputs. */\n  BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(faure_engine, x, y)\n  { return static_cast<const base_t&>(x) == y; }\n\n  /** Returns true if the two generators will produce different sequences of outputs. */\n  BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(faure_engine)\n\n  /** Writes the textual representation of the generator to a @c std::ostream. */\n  BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, faure_engine, s)\n  { return os << static_cast<const base_t&>(s); }\n\n  /** Reads the textual representation of the generator from a @c std::istream. */\n  BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, faure_engine, s)\n  { return is >> static_cast<base_t&>(s); }\n\n#endif // BOOST_RANDOM_DOXYGEN\n\nprivate:\n/** @cond hide_private_members */\n  void compute_seq(SeqSizeT seq)\n  {\n    qrng_detail::check_seed_sign(seq);\n    this->lattice.update(seq, this->state_begin(), this->state_end());\n  }\n/** @endcond */\n};\n\n/**\n * @attention This specialization of \\faure_engine supports up to 1117 dimensions.\n *\n * However, it is possible to provide your own prime table to \\faure_engine should the default one be insufficient.\n */\ntypedef faure_engine<double, boost::uint_least64_t, default_faure_prime_table> faure;\n\n} // namespace random\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_FAURE_HPP\n", "meta": {"hexsha": "4301c301b5ff478873ec22969f7e7eaee927af34", "size": 11474, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/random/faure.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/random/faure.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/random/faure.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 31.1793478261, "max_line_length": 115, "alphanum_fraction": 0.6650688513, "num_tokens": 3376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.43307687354066876}}
{"text": "#include \"generalizedassignmentsolver/algorithms/lagrelax_lbfgs.hpp\"\n\n#include \"knapsacksolver/algorithms/minknap.hpp\"\n#include \"knapsacksolver/algorithms/bellman.hpp\"\n\n#include <dlib/optimization.h>\n\n#include <algorithm>\n#include <iomanip>\n#include <limits>\n\nusing namespace generalizedassignmentsolver;\nusing namespace dlib;\n\ntypedef matrix<double,0,1> column_vector;\n\n////////////////////////////////////////////////////////////////////////////////\n/////////////////////////// lagrelax_assignment_lbfgs //////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\nLagRelaxAssignmentLbfgsOutput& LagRelaxAssignmentLbfgsOutput::algorithm_end(Info& info)\n{\n    //FFOT_PUT(info, \"Algorithm\", \"Iterations\", it);\n    Output::algorithm_end(info);\n    //FFOT_VER(info, \"Iterations: \" << it << std::endl);\n    return *this;\n}\n\nclass LagRelaxAssignmentLbfgsFunction\n{\n\npublic:\n\n    LagRelaxAssignmentLbfgsFunction(\n            const Instance& instance,\n            LagRelaxAssignmentLbfgsOptionalParameters& p,\n            ItemIdx number_of_unfixed_items,\n            const std::vector<ItemIdx>& item_indices):\n        instance_(instance), p_(p), item_indices_(item_indices), grad_(number_of_unfixed_items)\n    {\n        ItemIdx n = instance_.number_of_items();\n        AgentIdx m = instance_.number_of_agents();\n\n        // Compute knapsack capacities\n        kp_capacities_.resize(m);\n        for (AgentIdx i = 0; i < m; ++i) {\n            kp_capacities_[i] = instance.capacity(i);\n            for (ItemIdx j = 0; j < n; ++j) {\n                if (p.fixed_alt != NULL && (*p.fixed_alt)[j][i] == 1)\n                    kp_capacities_[i] -= instance.weight(j, i);\n            }\n            if (kp_capacities_[i] < 0)\n                std::cout << \"ERROR i \" << i << \" c \" << kp_capacities_[i] << std::endl;\n        }\n\n        // Initialize kp_indices_\n        kp_indices_.resize(n);\n    }\n\n    virtual ~LagRelaxAssignmentLbfgsFunction() { }\n\n    double f(const column_vector& x);\n\n    const column_vector der(const column_vector& x) const { (void)x; return grad_; }\n\nprivate:\n\n    const Instance& instance_;\n    LagRelaxAssignmentLbfgsOptionalParameters& p_;\n    /** item_indices_[j] is the index of item j in mu and grad_. */\n    const std::vector<ItemIdx>& item_indices_;\n\n    column_vector grad_;\n\n    std::vector<knapsacksolver::Weight> kp_capacities_;\n    /** kp_indices_[j] is the index of item j in the current KP. */\n    std::vector<knapsacksolver::ItemIdx> kp_indices_;\n\n};\n\ndouble LagRelaxAssignmentLbfgsFunction::f(const column_vector& mu)\n{\n    ItemIdx n = instance_.number_of_items();\n    AgentIdx m = instance_.number_of_agents();\n\n    // Initialize bound and gradient;\n    double l = 0;\n    for (ItemIdx j = 0; j < n; ++j)\n        if (item_indices_[j] >= 0)\n            l += mu(item_indices_[j]);\n    std::fill(grad_.begin(), grad_.end(), 1);\n\n    Weight mult = 10000;\n    for (AgentIdx i = 0; i < m; ++i) {\n        // Create knapsack instance\n        knapsacksolver::Instance kp_instance;\n        kp_instance.set_capacity(kp_capacities_[i]);\n        knapsacksolver::ItemIdx j_kp = 0;\n        for (ItemIdx j = 0; j < n; ++j) {\n            if ((p_.fixed_alt != NULL && (*p_.fixed_alt)[j][i] >= 0)\n                    || instance_.weight(j, i) > kp_capacities_[i]) {\n                kp_indices_[j] = -1;\n                continue;\n            }\n            knapsacksolver::Profit profit = std::ceil(mult * mu(j) - mult * instance_.cost(j, i));\n            if (profit <= 0) {\n                kp_indices_[j] = -1;\n                continue;\n            }\n            kp_instance.add_item(instance_.weight(j, i), profit);\n            kp_indices_[j] = j_kp;\n            j_kp++;\n        }\n\n        // Solve knapsack instance\n        //auto kp_output = knapsacksolver::bellman_array_all(kp_instance, Info().set_verbose(false));\n        auto kp_output = knapsacksolver::minknap(kp_instance);\n        //std::cout << \"i \" << i << \" opt \" << kp_output.solution.profit() << std::endl;\n\n        // Update bound and gradient\n        for (ItemIdx j = 0; j < n; ++j) {\n            if (kp_indices_[j] >= 0 && kp_output.solution.contains_idx(kp_indices_[j])) {\n                grad_(item_indices_[j])--;\n                l += instance_.cost(j, i) - mu(item_indices_[j]);\n            }\n        }\n    }\n\n    return l;\n}\n\nLagRelaxAssignmentLbfgsOutput generalizedassignmentsolver::lagrelax_assignment_lbfgs(\n        const Instance& instance,\n        LagRelaxAssignmentLbfgsOptionalParameters parameters)\n{\n    init_display(instance, parameters.info);\n    FFOT_VER(parameters.info,\n               \"Algorithm\" << std::endl\n            << \"---------\" << std::endl\n            << \"Lagrangian Relaxation - Assignment Constraints (LBFGS)\" << std::endl\n            << std::endl);\n\n    LagRelaxAssignmentLbfgsOutput output(instance, parameters.info);\n\n    ItemIdx n = instance.number_of_items();\n    AgentIdx m = instance.number_of_agents();\n\n    // Compute c0, item_indices and number_of_unfixed_items\n    ItemIdx item_idx = 0;\n    Cost c0 = 0;\n    std::vector<ItemIdx> item_indices(n, -2);\n    for (ItemIdx j = 0; j < n; ++j) {\n        for (AgentIdx i = 0; i < m; ++i) {\n            if (parameters.fixed_alt != NULL && (*parameters.fixed_alt)[j][i] == 1) {\n                c0 += instance.cost(j, i);\n                item_indices[j] = -1;\n                break;\n            }\n        }\n        if (item_indices[j] == -2) {\n            item_indices[j] = item_idx;\n            item_idx++;\n        }\n    }\n    ItemIdx number_of_unfixed_items = item_idx;\n\n    // Initialize multipliers\n    column_vector mu(number_of_unfixed_items);\n    if (parameters.initial_multipliers != NULL) {\n        for (ItemIdx j = 0; j < n; ++j)\n            if (item_indices[j] >= 0)\n                mu(item_indices[j]) = (*parameters.initial_multipliers)[j];\n    } else {\n        for (ItemIdx j = 0; j < n; ++j)\n            mu(j) = 0;\n    }\n\n    // Solve\n    LagRelaxAssignmentLbfgsFunction func(instance, parameters, number_of_unfixed_items, item_indices);\n    auto f   = [&func](const column_vector& x) { return func.f(x); };\n    auto def = [&func](const column_vector& x) { return func.der(x); };\n    auto stop_strategy = objective_delta_stop_strategy(0.0001);\n    //auto stop_strategy = gradient_norm_stop_strategy().be_verbose(),\n    double res = find_max(\n            lbfgs_search_strategy(256),\n            stop_strategy,\n            f,\n            def,\n            mu,\n            std::numeric_limits<double>::max());\n\n    // Compute output parameters\n    Cost lb = c0 + std::ceil(res - FFOT_TOL);\n    output.update_lower_bound(lb, std::stringstream(\"\"), parameters.info);\n    output.multipliers.resize(n);\n    for (ItemIdx j = 0; j < n; ++j)\n        if (item_indices[j] >= 0)\n            output.multipliers[j] = mu(item_indices[j]);\n\n    return output.algorithm_end(parameters.info);\n}\n\n////////////////////////////////////////////////////////////////////////////////\n//////////////////////////// lagrelax_knapsack_lbfgs ///////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\nLagRelaxKnapsackLbfgsOutput& LagRelaxKnapsackLbfgsOutput::algorithm_end(Info& info)\n{\n    //FFOT_PUT(info, \"Algorithm\", \"Iterations\", it);\n    Output::algorithm_end(info);\n    //FFOT_VER(info, \"Iterations: \" << it << std::endl);\n    return *this;\n}\n\nclass LagRelaxKnapsackLbfgsFunction\n{\n\npublic:\n\n    LagRelaxKnapsackLbfgsFunction(const Instance& instance):\n        instance_(instance),\n        x_(instance.number_of_items()),\n        grad_(instance.number_of_agents())\n    {  }\n    virtual ~LagRelaxKnapsackLbfgsFunction() { };\n\n    double f(const column_vector& x);\n\n    const column_vector der(const column_vector& x) const { (void)x; return grad_; }\n\n    AgentIdx agent(ItemIdx j) const { return x_(j); }\n\nprivate:\n\n    const Instance& instance_;\n    column_vector x_;\n    column_vector grad_;\n\n};\n\ndouble LagRelaxKnapsackLbfgsFunction::f(const column_vector& mu)\n{\n    ItemIdx n = instance_.number_of_items();\n    AgentIdx m = instance_.number_of_agents();\n\n    // Initialize bound and gradient\n    double l = 0;\n    for (AgentIdx i = 0; i < m; ++i) {\n        l += mu(i) * instance_.capacity(i);\n        grad_(i) = instance_.capacity(i);\n    }\n\n    for (ItemIdx j = 0; j < n; ++j) {\n        // Solve the trivial Generalized Upper Bound Problem\n        AgentIdx i_best = -1;\n        double rc_best = -1;\n        for (AgentIdx i = 0; i < m; ++i) {\n            double rc = instance_.cost(j, i) - mu(i) * instance_.weight(j, i);\n            if (i_best == -1\n                    || rc_best > rc\n                    // If the minimum reduced cost of a job is reached for\n                    // several agents, schedule the job on the agent with the\n                    // most available remaining capacity.\n                    // Without this condition, the relaxation fails to get the\n                    // optimal bound (the one from the linear relaxation) for\n                    // some instances.\n                    || (rc_best == rc && grad_(i) > grad_(i_best))) {\n                i_best = i;\n                rc_best = rc;\n            }\n        }\n\n        // Update bound and gradient\n        grad_(i_best) -= instance_.weight(j, i_best);\n        x_(j) = i_best;\n        l += rc_best;\n    }\n\n    return l;\n}\n\nLagRelaxKnapsackLbfgsOutput generalizedassignmentsolver::lagrelax_knapsack_lbfgs(\n        const Instance& instance,\n        Info info)\n{\n    init_display(instance, info);\n    FFOT_VER(info,\n               \"Algorithm\" << std::endl\n            << \"---------\" << std::endl\n            << \"Lagrangian Relaxation - Knapsack Constraints (LBFGS)\" << std::endl\n            << std::endl);\n\n    LagRelaxKnapsackLbfgsOutput output(instance, info);\n\n    AgentIdx m = instance.number_of_agents();\n    ItemIdx n = instance.number_of_items();\n\n    // Initialize multipliers\n    column_vector mu(m);\n    column_vector mu_lower(m);\n    column_vector mu_upper(m);\n    for (AgentIdx i = 0; i < m; ++i) {\n        //mu_lower(i) = 0;\n        //mu_upper(i) = std::numeric_limits<double>::max();\n        mu(i) = 0;\n        mu_lower(i) = -std::numeric_limits<double>::max();\n        mu_upper(i) = 0;\n    }\n\n    // Solve\n    LagRelaxKnapsackLbfgsFunction func(instance);\n    auto f   = [&func](const column_vector& x) { return func.f(x); };\n    auto def = [&func](const column_vector& x) { return func.der(x); };\n    auto stop_strategy = objective_delta_stop_strategy();\n    //auto stop_strategy = gradient_norm_stop_strategy();\n    double res = find_max_box_constrained(\n            lbfgs_search_strategy(256),\n            stop_strategy,\n            f,\n            def,\n            mu,\n            mu_lower,\n            mu_upper);\n\n    // Compute output parameters\n    Cost lb = std::ceil(res - FFOT_TOL);\n    output.update_lower_bound(lb, std::stringstream(\"\"), info);\n    output.multipliers.resize(m);\n    for (AgentIdx i = 0; i < m; ++i)\n        output.multipliers[i] = mu(i);\n    func.f(mu);\n    for (ItemIdx j = 0; j < n; ++j) {\n        output.x.push_back(std::vector<double>(instance.number_of_agents(), 0));\n        output.x[j][func.agent(j)] = 1;\n    }\n\n    return output.algorithm_end(info);\n}\n\n", "meta": {"hexsha": "67b0b936e0febe2683a7cebc087185e098e12b14", "size": 11233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generalizedassignmentsolver/algorithms/lagrelax_lbfgs.cpp", "max_stars_repo_name": "fontanf/GAP", "max_stars_repo_head_hexsha": "4fea39fbd34548a9820dd5c426580920d8d4b873", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-22T16:29:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-22T16:29:12.000Z", "max_issues_repo_path": "generalizedassignmentsolver/algorithms/lagrelax_lbfgs.cpp", "max_issues_repo_name": "fontanf/gap", "max_issues_repo_head_hexsha": "4fea39fbd34548a9820dd5c426580920d8d4b873", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generalizedassignmentsolver/algorithms/lagrelax_lbfgs.cpp", "max_forks_repo_name": "fontanf/gap", "max_forks_repo_head_hexsha": "4fea39fbd34548a9820dd5c426580920d8d4b873", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0382352941, "max_line_length": 102, "alphanum_fraction": 0.5700169144, "num_tokens": 2832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.43307687354066876}}
{"text": "#ifndef UKF_H\n#define UKF_H\n\n#include <functional>\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>\n\nclass UKF {\n\n    public:\n\n        // Available sigma point types\n        enum sig_type {JU, CUT4, CUT6, CUT8};\n\n        // Dynamical model type\n        typedef std::function <Eigen::VectorXd (double, double,\n            const Eigen::VectorXd&, const Eigen::VectorXd&)> dyn_model;\n\n        // Measurement model type\n        typedef std::function <Eigen::VectorXd (double,\n            const Eigen::VectorXd&)> meas_model;\n\n        // Dimensions of state, measurement, & process noise\n        const int nx, nz, nw;\n\n        // Indicates whether process noise is additive\n        const bool addw;\n\n        // Dynamical model: x(tf) = f(ti, tf, x(ti), w)\n        const dyn_model f;\n\n        // Measurement model: z = h(t, x) + v\n        const meas_model h;\n\n        // Process & measurement noise covariance\n        const Eigen::MatrixXd Pww, Pnn;\n\n        // Cholesky decomposition of process noise covariance\n        const Eigen::MatrixXd Cww;\n\n        // Standardized sigma points & weights\n        const Eigen::MatrixXd Sp, Su;\n        const Eigen::VectorXd wp, wu;\n\n        // Number of sigma points in prediction & update step\n        const int nsp, nsu;\n\n        // Constructor\n        UKF (\n            const dyn_model& f_,\n            const meas_model& h_,\n            bool addw_,\n            double t0,\n            const Eigen::VectorXd& xm0,\n            const Eigen::MatrixXd& Pxx0,\n            const Eigen::MatrixXd& Pww_,\n            const Eigen::MatrixXd& Pnn_,\n            sig_type stype,\n            double k);\n\n        // Prediction step\n        void predict(double tp);\n\n        // Update step with one measurement\n        void update(const Eigen::VectorXd& z);\n\n        // Run filter for sequence of measurements\n        void run(const Eigen::VectorXd& tz, const Eigen::MatrixXd& Z);\n\n        // Generate standardized sigma points\n        static Eigen::MatrixXd sigmaSt(sig_type stype, int n, double k);\n\n        // Generate sigma point weights\n        static Eigen::VectorXd sigmaWt(sig_type stype, int n, double k);\n\n        // Times\n        std::vector<double> t;\n\n        // State estimates\n        std::vector<Eigen::VectorXd> xest;\n\n        // State estimate covariances\n        std::vector<Eigen::MatrixXd> Pxx;\n\n        // Reset filter\n        void reset(\n            double t0,\n            const Eigen::VectorXd& xm0,\n            const Eigen::MatrixXd& Pxx0\n        );\n\n        // Save results\n        void save(const std::string& filename);\n\n        // Directory for CUT files\n        static std::string cut_dir;\n\n};\n\n#endif\n", "meta": {"hexsha": "d1459acdb9c188625c88e1e47dde0dd43651a2c7", "size": 2661, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ukf.hpp", "max_stars_repo_name": "SIOSlab/HOUSE", "max_stars_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ukf.hpp", "max_issues_repo_name": "SIOSlab/HOUSE", "max_issues_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ukf.hpp", "max_forks_repo_name": "SIOSlab/HOUSE", "max_forks_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8349514563, "max_line_length": 72, "alphanum_fraction": 0.5779782037, "num_tokens": 595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.43307687354066865}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2016 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef PSHAPEFUNCTIONS_HH\n#define PSHAPEFUNCTIONS_HH\n\n#include <tuple>\n#include <vector>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <memory>\n\n#include <boost/multi_array.hpp>\n\n\n#include \"fem/barycentric.hh\"\n#include \"fem/fixdune.hh\"\n#include \"fem/mllgeometry.hh\"\n#include \"linalg/dynamicMatrix.hh\"\n\nnamespace Kaskade\n{\n  /** \\ingroup fem\n   * \\brief Shape functions\n   *\n   * This class provides a common interface to the access of shape functions\n   *\n   * \\tparam ctype the scalar type used for coordinates (usually double)\n   * \\tparam dim the spatial dimension\n   * \\tparam T  Scalar type, the value field type of the shape functions\n   * \\tparam comp number of components\n   *\n   * A shape function lives on the reference element and may be scalar valued or vector valued:\n   * \\f[ \\phi: R^d \\to T^m \\f]\n   * with the spatial (grid) dimension \\f$ d \\f$, the value field type \\f$ T \\f$ (either a complex\n   * or a real type), and the vectorial dimension \\f$ m \\f$ (comp) of the image space. Shape function\n   * values are indeed defined not only on the reference element but on whole \\f$ R^d \\f$, even though\n   * the values outside the reference elements may be of little interest.\n   * It is possible to evaluate the shape function and its derivative.\n   *\n   */\n  template <class ctype, int dim, class T=double, int comp=1> \n  class ShapeFunction\n  {\n  public:\n    virtual ~ShapeFunction() {}\n\n    /**\n     * \\brief Creates a copy of the actual derived shape function.\n     */\n    virtual std::unique_ptr<ShapeFunction> clone() const = 0;\n\n    /**\n     * \\brief Evaluates the shape function (all components at once).\n     */\n    virtual Dune::FieldVector<T,comp> evaluateFunction(Dune::FieldVector<ctype,dim> const& xi) const = 0;\n\n    /**\n     * \\brief Evaluates the derivative of the shape function (all components and all directions at once).\n     */\n    virtual Dune::FieldMatrix<T,comp,dim> evaluateDerivative(Dune::FieldVector<ctype,dim> const& xi) const = 0;\n\n    /**\n     * \\brief Evaluates the second derivative of the shape function (all components and all directions at once).\n     */\n    virtual Tensor3<T,comp,dim,dim> evaluate2ndDerivative(Dune::FieldVector<ctype,dim> const& xi) const { \n      std::cerr << \"NOT IMPLEMENTED: \" << __FILE__ << \":\" << __LINE__ << \"\\n\"; \n      abort();\n    }\n\n    /**\n     * \\brief Returns a tuple (nominalOrder,codim,entity,index) giving detailed information about the location of the shape function. \n     * \n     * Each shape function is associated to a certain subentity of the element.\n     *\n     * nominalOrder is a nonnegative ordering parameter that is usually\n     * the polynomial order of the shape function, but need not coincide.\n     *\n     * codim is the codimension of the subentity to which the shape\n     * function is associated, entity is the number of the subentity,\n     * and index is the number of the shape function among those that\n     * are associated to the same subentity.\n     */\n    virtual std::tuple<int,int,int,int> location() const = 0;\n  };\n\n  //---------------------------------------------------------------------\n  /** \\ingroup fem\n   *  \\brief A set of shape functions\n   *\n   *\n   * \\tparam ctype scalar type for coordinates\n   * \\tparam dimension spatial dimension \n   * \\tparam T  scalar type\n   * \\tparam comp number of components\n   */\n  template <class ctype, int dimension, class T, int comp=1>   \n  class ShapeFunctionSet\n  {\n  public:\n    /// Scalar field type\n    typedef T Scalar;\n    /// type of one shape function\n    typedef ShapeFunction<ctype,dimension,T,comp> value_type;\n    \n    /**\n     * \\brief A matrix type mapping one-component coefficient vectors.\n     */\n    typedef DynamicMatrix<Dune::FieldMatrix<T,1,1> > Matrix;\n\n    /// Constructor\n    ShapeFunctionSet(Dune::GeometryType gt):\n      order_(-1), size_(-1),\n      gt_(gt),\n      refElem(&Dune::ReferenceElements<ctype,dimension>::general(gt))\n    {}\n\n    ShapeFunctionSet(ShapeFunctionSet const& other)\n    : iNodes(other.iNodes), projection(other.projection), order_(other.order_), size_(other.size_),\n      gt_(other.gt_), refElem(&Dune::ReferenceElements<ctype,dimension>::general(gt_))\n    {}\n\n    /**\n     * \\brief Number of components of the shape function values.\n     */\n    static int const comps = comp;\n\n\n    virtual ~ShapeFunctionSet() {}\n\n\n    /// Random access to a shape function\n    virtual value_type const& operator[](int i) const = 0;\n\n    /**\n     * \\brief Number of shape functions in the set.\n     */\n    virtual int size() const { return size_; }\n\n    /**\n     * \\brief Maximal polynomial order of shape functions.\n     */\n    int order() const { return order_; }\n\n    /// Type of geometry on which the shape functions are defined.\n    Dune::GeometryType type() const { return gt_; }\n\n    /**\n     * Returns a reference to the reference element on which this shape\n     * function set is defined.\n     */\n    Dune::ReferenceElement<ctype,dimension> const& referenceElement() const { return *refElem; }\n\n    /// A container type for holding interpolation points in the reference elements.\n    typedef std::vector<Dune::FieldVector<ctype,dimension> > InterpolationNodes;\n\n    /// A twodimensional array type for holding shape function values\n    /// evaluated at a set of nodes.\n    typedef DynamicMatrix<Dune::FieldMatrix<T,comp,1> > SfValueArray;\n\n    /**\n     * \\brief Initialize the hierarchical projection matrix based on the given\n     * lower order shape function set.\n     */\n    void initHierarchicalProjection(ShapeFunctionSet<ctype,dimension,T,comp> const* sfl)\n    {\n      // If no lower order shape function set is given, we assume an\n      // empty set, i.e. the projection is just zero.\n      if (!sfl || size()==0) {\n        projection.setSize(size(),size());\n//       projection = 0 // causes compilation error with dune-2.4.0 and clang++ on OS X (Darwin)\n        projection.fill(0);\n        return;\n      }\n\n      // Compute the hierarchic projection P = I_h E_l(x_h) I_l E_h(x_l),\n      // where E_h(x_l) the evaluation of high order shape functions at\n      // low order nodes, I_l the low order interpolation, E_l(x_h) the\n      // evaluation of low order shape functions at high order nodes,\n      // and I_h the high order shape function evaluation.\n\n      // Compute the local restriction matrix A\n      SfValueArray Ehxl;\n      evaluate(sfl->interpolationNodes(),Ehxl);  // E_h(x_l)\n      Matrix A;\n      sfl->interpolate(Ehxl,A);                  // I_l  E_h(x_l)\n\n      // Compute the local prolongation matrix B\n      SfValueArray Elxh;\n      sfl->evaluate(interpolationNodes(),Elxh);  // E_l(x_h)\n      Matrix B;\n      interpolate(Elxh,B);                       // I_h E_l(x_h)\n\n      // Compute projection P=B*A\n      MatMult(projection,B,A);\n    }\n\n\n\n    /**\n     * @brief Interpolation points.\n     *\n     * Provides interpolation points such\n     * that the shape function coefficients can be computed from\n     * function values at interpolation nodes by multiplication by this\n     * matrix.  The interpolation points are guaranteed to be inside the\n     * reference element associated to this shape function set.\n     */\n    InterpolationNodes const& interpolationNodes() const { return iNodes; }\n\n\n    /**\n     * @brief Left-multiplies the provided matrix with the interpolation\n     * matrix of the shape function set.\n     *\n     * Each column of A is interpreted as values of some function\n     * evaluated at this shape function set's interpolation points (see\n     * below). The columns of the output array IA then contain the shape\n     * function coefficients such that the corresponding\n     * linearcombination of shape functions \"interpolates\" that function\n     * in the interpolation points. What \"interpolation\" means is up to\n     * the actual implementation.\n     *\n     * IA is automatically resized if needed.\n     *\n     * Storage order: A[i][j] contains the value of function j at\n     * interpolation node i.\n     */\n    virtual void interpolate(SfValueArray const& A, Matrix& IA) const = 0;\n\n    /**\n     * @brief Evaluate shape function set at a set of points. In\n     * notation of the LocalToGlobalMapperConcept, this gives the matrix\n     * \\f$ \\Phi \\f$: the entry Phi[i][j] is the value of shape function\n     * j evaluated at iNodes[i].\n     *\n     * @param iNodes the points at which the shape functions are to be evaluated.\n     * \\param phi    the array that is filled with shape function values. The array\n     *               will be resized if needed.\n     */\n    void evaluate(InterpolationNodes const& iNodes, SfValueArray& phi) const\n    {\n      int s = size();\n      phi.setSize(iNodes.size(),s);\n\n      for (int j=0; j<s; ++j) {\n        value_type const& sf = (*this)[j];\n        for (int i=0; i<iNodes.size(); ++i) {\n          Dune::FieldVector<T,comp> v = sf.evaluateFunction(iNodes[i]);\n          for (int k=0; k<comp; ++k)\n            phi[i][j][k] = v[k];  // todo: improve efficiency! cache directly!\n        }\n      }\n    }\n\n    /**\n     * \\brief Returns a square matrix that projects shape function\n     * coefficients to a subspace spanned by shape functions of lower\n     * order.  This is intended to be used to implement embedded error\n     * estimators. The actual definition of this subspace depends on the\n     * shape function set specified in the call to\n     * initHierarchicalProjection().\n     */\n    Matrix const& hierarchicProjection() const\n    {\n      // check that the projection has been properly initialized.\n      assert(projection.N()==size() && projection.M()==size());\n\n      return projection;\n    }\n\n    virtual void removeShapeFunction(size_t index) {}\n\n  protected:\n    InterpolationNodes iNodes;\n    Matrix             projection;\n    int                order_;\n    int                size_;\n\n  private:\n    Dune::GeometryType gt_;\n    Dune::ReferenceElement<ctype,dimension> const* refElem;\n   };\n\n  //---------------------------------------------------------------------\n  /**\n   * \\brief Restricted shape function set.\n   * Introduces a new local ordering for the shape functions. To retrieve the original shape function id use getId(int newLocalId)\n   * \\todo docme: what is is good for? Which ordering? Why \"restricted\"?\n   */\n  template <class ShapeFunctionSet_>\n  class RestrictedShapeFunctionSet: public ShapeFunctionSet_\n  {\n  public:\n    /// Grid type\n    //typedef typename ShapeFunctionSet_::Grid Grid; causes compiler error\n    /// Scalar field type\n    typedef typename ShapeFunctionSet_::Scalar Scalar;\n    /// type of one shape function\n    typedef typename ShapeFunctionSet_::value_type value_type;\n\n    explicit RestrictedShapeFunctionSet(int order) : ShapeFunctionSet_(order) {}\n\n    RestrictedShapeFunctionSet(ShapeFunctionSet_ const& other) : ShapeFunctionSet_(other) {}\n    RestrictedShapeFunctionSet(RestrictedShapeFunctionSet const& other) : ShapeFunctionSet_(other) {}\n    /// Copy constructor. Resets restriction ids\n    RestrictedShapeFunctionSet(RestrictedShapeFunctionSet const& other, std::vector<int>* ids_) : ShapeFunctionSet_(other) {}\n\n    virtual ~RestrictedShapeFunctionSet(){}\n\n    /**\n     * \\param ids_ vector of used ids of the shape function set\n     */\n    void setRestriction(std::vector<int> const& ids_)\n    {\n      if(ids_.size()==0)\n      {\n        this->sf.clear();\n        this->iNodes.clear();\n        this->size_ = 0;\n        return;\n      }\n\n\n      for(int i=this->sf.size()-1; i>-1; --i)\n        if(std::find(ids_.begin(),ids_.end(),i)==ids_.end()) this->removeShapeFunction(i);\n\n      this->size_ = ids_.size();\n    }\n  };\n\n  //---------------------------------------------------------------------\n\n  /**\n   * \\brief Base class for sets of shape function containers.\n   *\n   * \\tparam ctype scalar type for coordinates\n   * \\tparam dimension spatial dimension\n   * \\tparam T the scalar shape function return value\n   * \\tparam comp the number of components of the shape functions' values\n   */\n  template <class ctype, int dimension, class T, int comp=1>\n  class ShapeFunctionSetContainer\n  {\n  public:\n    typedef ShapeFunctionSet<ctype,dimension,T,comp> value_type;\n\n    virtual ~ShapeFunctionSetContainer() {}\n\n\n    /// access a shape function via type and order\n    virtual value_type const& operator() (Dune::GeometryType type, int order) const = 0;\n  };\n\n  //---------------------------------------------------------------------\n  //---------------------------------------------------------------------\n\n  /**\n   * For a given shape function set \\arg sfs which is defined on a\n   * simplex and permits a simple coupling, and a given permutation \\arg\n   * vPermutation of the vertices of the simplex defining an affine\n   * spatial transformation \\f$ f \\f$, this function returns a\n   * permutation \\arg sfPermutation of the shape functions and a sign\n   * vector \\arg sign, such that\n   *\n   * \\f[ \\mathrm{sign[k]}\\phi_{\\mathrm{sfPermutation[k]}}(f(x)) =\n   * \\phi_k(x). \\f]\n   */\n  template <class ShapeFunctionSet>\n  void computeSimplexSfPermutation(ShapeFunctionSet const& sfs,\n      int const* vPermutation,\n      int*       sfPermutation,\n      int*       sign)\n  {\n    assert(vPermutation);\n    assert(sfPermutation);\n    assert(sign);\n\n    // Ok, we rely on the evaluation & interpolation of the shape\n    // function set. First we evaluate the shape functions on the\n    // interpolation nodes transformed by f, then we interpolate these\n    // values. This gives us a matrix which, if the shape function set\n    // indeed allows simple coupling, is a signed permutation\n    // matrix. Finally we extract the signs and the permutation from\n    // this matrix.\n\n    // Get the interpolation nodes. Make a copy because we need to\n    // modify them.\n    typedef typename ShapeFunctionSet::InterpolationNodes InterpolationNodes;\n    InterpolationNodes in = sfs.interpolationNodes();\n\n\n    // Transform the nodes. This is done by permuting their barycentric\n    // coordinates. Remember that the interpolation nodes are given in\n    // Cartesian, not in barycentric coordinates. This determines the\n    // loop termination for j.\n    for (int i=0; i<in.size(); ++i) {\n      Dune::FieldVector<typename ShapeFunctionSet::Grid::ctype,ShapeFunctionSet::Grid::dimension+1> b = barycentric(in[i]);\n      for (int j=0; j<ShapeFunctionSet::Grid::dimension; ++j)\n        in[i][j] = b[vPermutation[j]];\n    }\n\n\n    // Evaluate the shape functions at the transformed nodes.\n    typename ShapeFunctionSet::SfValueArray phi(in.size(),sfs.size());\n    sfs.evaluate(in,phi);\n\n    // Interpolate the shape function values.\n    typename ShapeFunctionSet::Matrix P(sfs.size(),sfs.size());\n    sfs.interpolate(phi,P);\n\n\n#ifndef NDEBUG\n    // Check that the permutation matrix is indeed a signed permutation\n    bool ok = true;\n    for (int i=0; i<sfs.size(); ++i) {\n      double rowSum = 0;\n      double colSum = 0;\n      for (int j=0; j<sfs.size(); ++j) {\n        if (std::abs(P[i][j])>1e-8 && std::abs(1-std::abs(P[i][j]))>1e-8) ok = false;\n        rowSum += std::abs(P[i][j]);\n        colSum += std::abs(P[j][i]);\n      }\n      if (std::abs(rowSum-1)>1e-8 || std::abs(colSum-1)>1e-8) ok = false;\n    }\n    if (!ok) {\n      std::cout << \"\\nPermutation matrix:\\n\";\n      for (int i=0; i<P.N(); ++i) {\n        for (int j=0; j<P.M(); ++j)\n          std::cout << std::setw(2) << P[i][j] << \" \";\n        std::cout << \"\\n\";\n      }\n    }\n#endif\n\n\n    // Extract the permutation and the sign.\n    for (int i=0; i<sfs.size(); ++i)\n      for (int j=0; j<sfs.size(); ++j)\n        if (std::abs(P[j][i])>0.5) {\n          sfPermutation[i] = j; // XXX or the other way round?\n          sign[i] = P[j][i]>0? 1: -1;\n          break;\n        }\n\n  }\n} // end of namespace Kaskade\n\n#endif\n", "meta": {"hexsha": "f825558e3852ad0ceefcc292c58eb52e67fe36ab", "size": 16625, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/fem/pshapefunctions.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/fem/pshapefunctions.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/fem/pshapefunctions.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 36.1413043478, "max_line_length": 134, "alphanum_fraction": 0.6173233083, "num_tokens": 4037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.43291903284438016}}
{"text": "/* =========================================================================\n   Copyright (c) 2010-2016, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** \\example eigen-with-viennacl.cpp\n*\n*   This tutorial shows how data can be directly transferred from the <a href=\"http://eigen.tuxfamily.org/\">Eigen Library</a> to ViennaCL objects using the built-in convenience wrappers.\n*\n*   The first step is to include the necessary headers and activate the Eigen convenience functions in ViennaCL:\n**/\n\n// System headers\n#include <iostream>\n\n// Eigen headers\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n// IMPORTANT: Must be set prior to any ViennaCL includes if you want to use ViennaCL algorithms on Eigen objects\n#define VIENNACL_WITH_EIGEN 1\n\n\n// ViennaCL includes\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n\n\n// Helper functions for this tutorial:\n#include \"vector-io.hpp\"\n\n/**\n*   The following is a set of auxiliary dispatchers for obtaining the right Eigen types for a given floating point type.\n*   This is merely an implementation detail, so feel free to skip over it.\n**/\n\n//dense matrix:\ntemplate<typename T>\nstruct Eigen_dense_matrix\n{\n  typedef typename T::ERROR_NO_EIGEN_TYPE_AVAILABLE   error_type;\n};\n\ntemplate<>\nstruct Eigen_dense_matrix<float>\n{\n  typedef Eigen::MatrixXf  type;\n};\n\ntemplate<>\nstruct Eigen_dense_matrix<double>\n{\n  typedef Eigen::MatrixXd  type;\n};\n\n\n//sparse matrix\ntemplate<typename T>\nstruct Eigen_vector\n{\n  typedef typename T::ERROR_NO_EIGEN_TYPE_AVAILABLE   error_type;\n};\n\ntemplate<>\nstruct Eigen_vector<float>\n{\n  typedef Eigen::VectorXf  type;\n};\n\ntemplate<>\nstruct Eigen_vector<double>\n{\n  typedef Eigen::VectorXd  type;\n};\n\n\n\n/**\n*    The following function contains the main code for this tutorial.\n*    It consists of the following steps:\n*      - Creates Eigen matrices and vectors\n*      - Initializes them with data\n*      - Create ViennaCL objects\n*      - Copy them over to the respective ViennaCL objects\n*      - Compute matrix-vector products in both Eigen and ViennaCL and compare results.\n*\n**/\ntemplate<typename ScalarType>\nvoid run_tutorial()\n{\n  /**\n  * Get Eigen matrix and vector types for the provided ScalarType.\n  * Involves a little bit of template-metaprogramming.\n  **/\n  typedef typename Eigen_dense_matrix<ScalarType>::type  EigenMatrix;\n  typedef typename Eigen_vector<ScalarType>::type        EigenVector;\n\n  /**\n  * Create and fill dense matrices from the Eigen library:\n  **/\n  EigenMatrix eigen_densemat(6, 5);\n  EigenMatrix eigen_densemat2(6, 5);\n  eigen_densemat(0,0) = 2.0;   eigen_densemat(0,1) = -1.0;\n  eigen_densemat(1,0) = -1.0;  eigen_densemat(1,1) =  2.0;  eigen_densemat(1,2) = -1.0;\n  eigen_densemat(2,1) = -1.0;  eigen_densemat(2,2) = -1.0;  eigen_densemat(2,3) = -1.0;\n  eigen_densemat(3,2) = -1.0;  eigen_densemat(3,3) =  2.0;  eigen_densemat(3,4) = -1.0;\n                               eigen_densemat(5,4) = -1.0;  eigen_densemat(4,4) = -1.0;\n  Eigen::Map<EigenMatrix> eigen_densemat_map(eigen_densemat.data(), 6, 5); // same as eigen_densemat, but emulating user-provided buffer\n\n  /**\n  * Create and fill sparse matrices from the Eigen library:\n  **/\n  Eigen::SparseMatrix<ScalarType, Eigen::RowMajor> eigen_sparsemat(6, 5);\n  Eigen::SparseMatrix<ScalarType, Eigen::RowMajor> eigen_sparsemat2(6, 5);\n  eigen_sparsemat.reserve(5*2);\n  eigen_sparsemat.insert(0,0) = 2.0;   eigen_sparsemat.insert(0,1) = -1.0;\n  eigen_sparsemat.insert(1,1) = 2.0;   eigen_sparsemat.insert(1,2) = -1.0;\n  eigen_sparsemat.insert(2,2) = -1.0;  eigen_sparsemat.insert(2,3) = -1.0;\n  eigen_sparsemat.insert(3,3) = 2.0;   eigen_sparsemat.insert(3,4) = -1.0;\n  eigen_sparsemat.insert(5,4) = -1.0;\n  //eigen_sparsemat.endFill();\n\n  /**\n  * Create and fill a few vectors from the Eigen library:\n  **/\n  EigenVector eigen_rhs(5);\n  Eigen::Map<EigenVector> eigen_rhs_map(eigen_rhs.data(), 5);\n  EigenVector eigen_result(6);\n  EigenVector eigen_temp(6);\n\n  eigen_rhs(0) = 10.0;\n  eigen_rhs(1) = 11.0;\n  eigen_rhs(2) = 12.0;\n  eigen_rhs(3) = 13.0;\n  eigen_rhs(4) = 14.0;\n\n\n  /**\n  * Create the corresponding ViennaCL objects:\n  **/\n  viennacl::vector<ScalarType> vcl_rhs(5);\n  viennacl::vector<ScalarType> vcl_result(6);\n  viennacl::matrix<ScalarType> vcl_densemat(6, 5);\n  viennacl::compressed_matrix<ScalarType> vcl_sparsemat(6, 5);\n\n\n  /**\n  * Directly copy the Eigen objects to ViennaCL objects\n  **/\n  viennacl::copy(&(eigen_rhs[0]), &(eigen_rhs[0]) + 5, vcl_rhs.begin());  // Method 1: via iterator interface (cf. std::copy())\n  viennacl::copy(eigen_rhs, vcl_rhs);                                     // Method 2: via built-in wrappers (convenience layer)\n  viennacl::copy(eigen_rhs_map, vcl_rhs);                                 // Same as method 2, but for a mapped vector\n\n  viennacl::copy(eigen_densemat, vcl_densemat);\n  viennacl::copy(eigen_densemat_map, vcl_densemat); //same as above, using mapped matrix\n  viennacl::copy(eigen_sparsemat, vcl_sparsemat);\n  std::cout << \"VCL sparsematrix dimensions: \" << vcl_sparsemat.size1() << \", \" << vcl_sparsemat.size2() << std::endl;\n\n  // For completeness: Copy matrices from ViennaCL back to Eigen:\n  viennacl::copy(vcl_densemat, eigen_densemat2);\n  viennacl::copy(vcl_sparsemat, eigen_sparsemat2);\n\n\n  /**\n  * Run dense matrix-vector products and compare results:\n  **/\n  eigen_result = eigen_densemat * eigen_rhs;\n  vcl_result = viennacl::linalg::prod(vcl_densemat, vcl_rhs);\n  viennacl::copy(vcl_result, eigen_temp);\n  std::cout << \"Difference for dense matrix-vector product: \" << (eigen_result - eigen_temp).norm() << std::endl;\n  std::cout << \"Difference for dense matrix-vector product (Eigen->ViennaCL->Eigen): \"\n            << (eigen_densemat2 * eigen_rhs - eigen_temp).norm() << std::endl;\n\n  /**\n  * Run sparse matrix-vector products and compare results:\n  **/\n  eigen_result = eigen_sparsemat * eigen_rhs;\n  vcl_result = viennacl::linalg::prod(vcl_sparsemat, vcl_rhs);\n  viennacl::copy(vcl_result, eigen_temp);\n  std::cout << \"Difference for sparse matrix-vector product: \" << (eigen_result - eigen_temp).norm() << std::endl;\n  std::cout << \"Difference for sparse matrix-vector product (Eigen->ViennaCL->Eigen): \"\n            << (eigen_sparsemat2 * eigen_rhs - eigen_temp).norm() << std::endl;\n}\n\n\n/**\n*   In the main() routine we only call the worker function defined above with both single and double precision arithmetic.\n**/\nint main(int, char *[])\n{\n  std::cout << \"----------------------------------------------\" << std::endl;\n  std::cout << \"## Single precision\" << std::endl;\n  std::cout << \"----------------------------------------------\" << std::endl;\n  run_tutorial<float>();\n\n#ifdef VIENNACL_HAVE_OPENCL\n  if ( viennacl::ocl::current_device().double_support() )\n#endif\n  {\n    std::cout << \"----------------------------------------------\" << std::endl;\n    std::cout << \"## Double precision\" << std::endl;\n    std::cout << \"----------------------------------------------\" << std::endl;\n    run_tutorial<double>();\n  }\n\n  /**\n  *   That's it. Print a success message and exit.\n  **/\n  std::cout << std::endl;\n  std::cout << \"!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!\" << std::endl;\n  std::cout << std::endl;\n\n}\n", "meta": {"hexsha": "f3862ce23d3f5edaaa688baeb7c8b1be04bb5a64", "size": 7862, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/eigen-with-viennacl.cpp", "max_stars_repo_name": "yuchengs/viennacl-dev", "max_stars_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 224.0, "max_stars_repo_stars_event_min_datetime": "2015-02-15T21:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:27:03.000Z", "max_issues_repo_path": "examples/tutorial/eigen-with-viennacl.cpp", "max_issues_repo_name": "yuchengs/viennacl-dev", "max_issues_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 189.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T17:08:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T06:23:22.000Z", "max_forks_repo_path": "examples/tutorial/eigen-with-viennacl.cpp", "max_forks_repo_name": "yuchengs/viennacl-dev", "max_forks_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 84.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T14:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T14:51:17.000Z", "avg_line_length": 34.4824561404, "max_line_length": 186, "alphanum_fraction": 0.6455100483, "num_tokens": 2094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.6757645944891558, "lm_q1q2_score": 0.4329190286610974}}
{"text": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_HISTOGRAM_ACCUMULATORS_MEAN_HPP\n#define BOOST_HISTOGRAM_ACCUMULATORS_MEAN_HPP\n\n#include <boost/core/nvp.hpp>\n#include <boost/histogram/fwd.hpp> // for mean<>\n#include <boost/throw_exception.hpp>\n#include <cassert>\n#include <stdexcept>\n#include <type_traits>\n\nnamespace boost {\nnamespace histogram {\nnamespace accumulators {\n\n/** Calculates mean and variance of sample.\n\n  Uses Welfords's incremental algorithm to improve the numerical\n  stability of mean and variance computation.\n*/\ntemplate <class ValueType>\nclass mean {\npublic:\n  using value_type = ValueType;\n  using const_reference = const value_type&;\n\n  mean() = default;\n\n  /// Allow implicit conversion from mean<T>\n  template <class T>\n  mean(const mean<T>& o) noexcept\n      : sum_{o.sum_}, mean_{o.mean_}, sum_of_deltas_squared_{o.sum_of_deltas_squared_} {}\n\n  /// Initialize to external count, mean, and variance\n  mean(const_reference n, const_reference mean, const_reference variance) noexcept\n      : sum_(n), mean_(mean), sum_of_deltas_squared_(variance * (n - 1)) {}\n\n  /// Insert sample x\n  void operator()(const_reference x) noexcept {\n    sum_ += static_cast<value_type>(1);\n    const auto delta = x - mean_;\n    mean_ += delta / sum_;\n    sum_of_deltas_squared_ += delta * (x - mean_);\n  }\n\n  /// Insert sample x with weight w\n  void operator()(const weight_type<value_type>& w, const_reference x) noexcept {\n    sum_ += w.value;\n    const auto delta = x - mean_;\n    mean_ += w.value * delta / sum_;\n    sum_of_deltas_squared_ += w.value * delta * (x - mean_);\n  }\n\n  /// Add another mean accumulator\n  mean& operator+=(const mean& rhs) noexcept {\n    if (sum_ != 0 || rhs.sum_ != 0) {\n      const auto tmp = mean_ * sum_ + rhs.mean_ * rhs.sum_;\n      sum_ += rhs.sum_;\n      mean_ = tmp / sum_;\n    }\n    sum_of_deltas_squared_ += rhs.sum_of_deltas_squared_;\n    return *this;\n  }\n\n  /** Scale by value\n\n   This acts as if all samples were scaled by the value.\n  */\n  mean& operator*=(const_reference s) noexcept {\n    mean_ *= s;\n    sum_of_deltas_squared_ *= s * s;\n    return *this;\n  }\n\n  bool operator==(const mean& rhs) const noexcept {\n    return sum_ == rhs.sum_ && mean_ == rhs.mean_ &&\n           sum_of_deltas_squared_ == rhs.sum_of_deltas_squared_;\n  }\n\n  bool operator!=(const mean& rhs) const noexcept { return !operator==(rhs); }\n\n  /// Return how many samples were accumulated\n  const_reference count() const noexcept { return sum_; }\n\n  /// Return mean value of accumulated samples\n  const_reference value() const noexcept { return mean_; }\n\n  /// Return variance of accumulated samples\n  value_type variance() const noexcept { return sum_of_deltas_squared_ / (sum_ - 1); }\n\n  template <class Archive>\n  void serialize(Archive& ar, unsigned version) {\n    if (version == 0) {\n      // read only\n      std::size_t sum;\n      ar& make_nvp(\"sum\", sum);\n      sum_ = static_cast<value_type>(sum);\n    } else {\n      ar& make_nvp(\"sum\", sum_);\n    }\n    ar& make_nvp(\"mean\", mean_);\n    ar& make_nvp(\"sum_of_deltas_squared\", sum_of_deltas_squared_);\n  }\n\nprivate:\n  value_type sum_{};\n  value_type mean_{};\n  value_type sum_of_deltas_squared_{};\n};\n\n} // namespace accumulators\n} // namespace histogram\n} // namespace boost\n\n#ifndef BOOST_HISTOGRAM_DOXYGEN_INVOKED\n\nnamespace boost {\nnamespace serialization {\n\ntemplate <class T>\nstruct version;\n\n// version 1 for boost::histogram::accumulators::mean<T>\ntemplate <class T>\nstruct version<boost::histogram::accumulators::mean<T>> : std::integral_constant<int, 1> {\n};\n\n} // namespace serialization\n} // namespace boost\n\nnamespace std {\ntemplate <class T, class U>\n/// Specialization for boost::histogram::accumulators::mean.\nstruct common_type<boost::histogram::accumulators::mean<T>,\n                   boost::histogram::accumulators::mean<U>> {\n  using type = boost::histogram::accumulators::mean<common_type_t<T, U>>;\n};\n} // namespace std\n\n#endif\n\n#endif\n", "meta": {"hexsha": "11563561cfe94b61bd736e788b7793eb20cbc7c2", "size": 4107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/lib/include/boost/histogram/accumulators/mean.hpp", "max_stars_repo_name": "mamil/demo", "max_stars_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2019-02-12T12:53:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T14:14:38.000Z", "max_issues_repo_path": "boost/lib/include/boost/histogram/accumulators/mean.hpp", "max_issues_repo_name": "mamil/demo", "max_issues_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "boost/lib/include/boost/histogram/accumulators/mean.hpp", "max_forks_repo_name": "mamil/demo", "max_forks_repo_head_hexsha": "32240d95b80175549e6a1904699363ce672a1591", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T04:03:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T18:53:47.000Z", "avg_line_length": 27.75, "max_line_length": 90, "alphanum_fraction": 0.6915023131, "num_tokens": 1051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.4329190193880704}}
{"text": "// Copyright 2004 The Trustees of Indiana University.\n\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef _ALG_CTX_BWTC_H\n#define _ALG_CTX_BWTC_H\n\n#include <stack>\n#include <vector>\n#include <boost/graph/overloading.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/relax.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/type_traits/is_convertible.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <algorithm>\n\n#include <functional>\n\nusing namespace boost;\n\nnamespace nctx {\n\nnamespace detail { namespace graph {\n\n  /**\n   * @brief Dijkstra visitor keeping track of vertices, shortest paths and updates due to decisions on constraints.\n   * \n   * This visitor is based on the Boost implementation. The corresponding documentation states:\n   * \n   * Customized visitor passed to Dijkstra's algorithm by Brandes'\n   * betweenness centrality algorithm. This visitor is responsible for\n   * keeping track of the order in which vertices are discovered, the\n   * predecessors on the shortest path(s) to a vertex, and the number\n   * of shortest paths.\n   * \n   * In the extension of nctx, this visitor is also responsible for keeping track of the decisions resulting from the decision function. If the function prohibits traversal to a descending node, the visitor rolls back distance updates by Dijkstra's algorithm.\n   */\n  template<typename Graph, typename WeightMap, typename IncomingMap,\n           typename DistanceMap, typename PathCountMap>\n  struct brandes_dijkstra_visitor : public bfs_visitor<>\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\n    typedef typename std::function<bool(typename graph_traits<Graph>::vertex_descriptor, typename graph_traits<Graph>::vertex_descriptor, typename graph_traits<Graph>::vertex_descriptor)> decision_function;\n\n    brandes_dijkstra_visitor(std::stack<vertex_descriptor>& ordered_vertices,\n                             WeightMap weight,\n                             IncomingMap incoming,\n                             DistanceMap distance,\n                             PathCountMap path_count_constraint,\n                             PathCountMap path_count_unconstraint,\n                             decision_function &betw_decision_fct,\n                             vertex_descriptor s)\n      : ordered_vertices(ordered_vertices), weight(weight), \n        incoming(incoming), distance(distance),\n        path_count_constraint(path_count_constraint),\n        path_count_unconstraint(path_count_unconstraint), betw_decision_fct(betw_decision_fct),\n        s(s)\n    { }\n\n    /**\n     * Whenever an edge e = (v, w) is relaxed, the incoming edge list\n     * for w is set to {(v, w)} and the shortest path count of w is set to\n     * the number of paths that reach {v}.\n     */\n    void edge_relaxed(edge_descriptor e, const Graph& g) \n    { \n      vertex_descriptor v = source(e, g), w = target(e, g);\n      incoming[w].clear();\n      incoming[w].push_back(e);\n      put(path_count_unconstraint, w, get(path_count_unconstraint, v));\n      if(betw_decision_fct(s,v,w)){\n        put(path_count_constraint, w, get(path_count_constraint, v));\n      }\n    }\n\n    /**\n     * If an edge e = (v, w) was not relaxed, it may still be the case\n     * that we've found more equally-short paths, so include {(v, w)} in the\n     * incoming edges of w and add all of the shortest paths to v to the\n     * shortest path count of w.\n     */\n    void edge_not_relaxed(edge_descriptor e, const Graph& g) \n    {\n      typedef typename property_traits<WeightMap>::value_type weight_type;\n      typedef typename property_traits<DistanceMap>::value_type distance_type;\n      vertex_descriptor v = source(e, g), w = target(e, g);\n\n      distance_type d_v = get(distance, v), d_w = get(distance, w);\n      weight_type w_e = get(weight, e);\n      closed_plus<distance_type> combine;\n      if (d_w == combine(d_v, w_e)) {\n        put(path_count_unconstraint, w, get(path_count_unconstraint, w) + get(path_count_unconstraint, v));\n        incoming[w].push_back(e);\n        if(betw_decision_fct(s,v,w)){\n          put(path_count_constraint, w, get(path_count_constraint, w) + get(path_count_constraint, v));\n        }\n      }\n      \n    }\n\n    /// Keep track of vertices as they are reached\n    void examine_vertex(vertex_descriptor w, const Graph&) \n    { \n      ordered_vertices.push(w);\n    }\n\n  private:\n    std::stack<vertex_descriptor>& ordered_vertices;\n    WeightMap weight;\n    IncomingMap incoming;\n    DistanceMap distance;\n    PathCountMap path_count_constraint;\n    PathCountMap path_count_unconstraint;\n    decision_function &betw_decision_fct;\n    vertex_descriptor s;\n  };\n\n  /**\n   * Function object that calls Dijkstra's shortest paths algorithm\n   * using the Dijkstra visitor for the Brandes betweenness centrality\n   * algorithm.\n   */\n  template<typename WeightMap, typename Graph, typename BetweennessDecisionFunction>\n  struct brandes_dijkstra_shortest_paths\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n    //~ typedef typename BetweennessDecisionFunction = std::function<bool(vertex_descriptor, vertex_descriptor, vertex_descriptor)>;\n    brandes_dijkstra_shortest_paths(WeightMap weight_map,\n               BetweennessDecisionFunction &betw_decision_fct) \n      : weight_map(weight_map), betw_decision_fct(betw_decision_fct) { }\n\n    template<typename IncomingMap, typename DistanceMap, \n             typename PathCountMap, typename VertexIndexMap>\n    void \n    operator()(Graph& g, \n               vertex_descriptor s,\n               std::stack<vertex_descriptor>& ov,\n               IncomingMap incoming,\n               DistanceMap distance,\n               PathCountMap path_count_constraint,\n               PathCountMap path_count_unconstraint,\n               VertexIndexMap vertex_index)\n    {\n      typedef brandes_dijkstra_visitor<Graph, WeightMap, IncomingMap, \n                                       DistanceMap, PathCountMap> visitor_type;\n      visitor_type visitor(ov, weight_map, incoming, distance, \n        path_count_constraint, \n        path_count_unconstraint, betw_decision_fct, s);\n      \n      boost::dijkstra_shortest_paths(g, s, \n                              boost::weight_map(weight_map)\n                              .vertex_index_map(vertex_index)\n                              .distance_map(distance)\n                              .visitor(visitor));\n    }\n\n  private:\n    BetweennessDecisionFunction betw_decision_fct;\n    WeightMap weight_map;\n  };\n\n  // When the edge centrality map is a dummy property map, no\n  // initialization is needed.\n  template<typename Iter>\n  inline void \n  init_centrality_map(std::pair<Iter, Iter>, dummy_property_map) { }\n\n  // When we have a real edge centrality map, initialize all of the\n  // centralities to zero.\n  template<typename Iter, typename Centrality>\n  void \n  init_centrality_map(std::pair<Iter, Iter> keys, Centrality centrality_map)\n  {\n    typedef typename property_traits<Centrality>::value_type \n      centrality_type;\n    while (keys.first != keys.second) {\n      put(centrality_map, *keys.first, centrality_type(0));\n      ++keys.first;\n    }\n  }\n\n  // When the edge centrality map is a dummy property map, no update\n  // is performed.\n  template<typename Key, typename T>\n  inline void \n  update_centrality(dummy_property_map, const Key&, const T&) { }\n\n  // When we have a real edge centrality map, add the value to the map\n  template<typename CentralityMap, typename Key, typename T>\n  inline void \n  update_centrality(CentralityMap centrality_map, Key k, const T& x)\n  { put(centrality_map, k, get(centrality_map, k) + x); }\n\n  template<typename Iter>\n  inline void \n  divide_centrality_by_two(std::pair<Iter, Iter>, dummy_property_map) {}\n\n  template<typename Iter, typename CentralityMap>\n  inline void\n  divide_centrality_by_two(std::pair<Iter, Iter> keys, \n                           CentralityMap centrality_map)\n  {\n    typename property_traits<CentralityMap>::value_type two(2);\n    while (keys.first != keys.second) {\n      put(centrality_map, *keys.first, get(centrality_map, *keys.first) / two);\n      ++keys.first;\n    }\n  }\n\n  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\n           typename IncomingMap, typename DistanceMap, \n           typename DependencyMap, typename PathCountMap,\n           typename VertexIndexMap, typename ShortestPaths> \n  void \n  brandes_betweenness_centrality_impl(const Graph& g, \n                                      CentralityMap centrality,     // C_B\n                                      EdgeCentralityMap edge_centrality_map,\n                                      IncomingMap incoming, // P\n                                      DistanceMap distance,         // d\n                                      DependencyMap dependency,     // delta\n                                      PathCountMap path_count_constraint,      // sigma\n                                      PathCountMap path_count_unconstraint,      // sigma\n                                      VertexIndexMap vertex_index,\n                                      ShortestPaths shortest_paths)\n  {\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n    //~ const BglGraph<T>& g = *(gc.get_graph());\n    // Initialize centrality\n    init_centrality_map(vertices(g), centrality);\n    init_centrality_map(edges(g), edge_centrality_map);\n\n    std::stack<vertex_descriptor> ordered_vertices;\n    vertex_iterator s, s_end;\n    for (boost::tie(s, s_end) = vertices(g); s != s_end; ++s) {\n      // Initialize for this iteration\n      vertex_iterator w, w_end;\n      for (boost::tie(w, w_end) = vertices(g); w != w_end; ++w) {\n        incoming[*w].clear();\n        put(path_count_constraint, *w, 0);\n        put(path_count_unconstraint, *w, 0);\n        put(dependency, *w, 0);\n      }\n      put(path_count_constraint, *s, 1);\n      put(path_count_unconstraint, *s, 1);\n      \n      // Execute the shortest paths algorithm. This will be either\n      // Dijkstra's algorithm or a customized breadth-first search,\n      // depending on whether the graph is weighted or unweighted.\n      shortest_paths(g, *s, ordered_vertices, incoming, distance,\n                     path_count_constraint, \n                     path_count_unconstraint, vertex_index);\n      \n      while (!ordered_vertices.empty()) {\n        vertex_descriptor w = ordered_vertices.top();\n        ordered_vertices.pop();\n        \n        typedef typename property_traits<IncomingMap>::value_type\n          incoming_type;\n        typedef typename incoming_type::iterator incoming_iterator;\n        typedef typename property_traits<DependencyMap>::value_type \n          dependency_type;\n        \n        for (incoming_iterator vw = incoming[w].begin();\n             vw != incoming[w].end(); ++vw) {\n          vertex_descriptor v = source(*vw, g);\n          //~ dependency_type factor_raw = dependency_type(get(path_count_unconstraint, v))\n            //~ / dependency_type(get(path_count_unconstraint, w));\n          \n          if(dependency_type(get(path_count_constraint, w)) > dependency_type(0)){\n            bool ctx_fac = (dependency_type(get(path_count_constraint, v)) != dependency_type(get(path_count_unconstraint, v)))\n              && (dependency_type(get(path_count_constraint, w)) != dependency_type(get(path_count_unconstraint, w)));\n            \n            //~ dependency_type factor = \n              //~ ((dependency_type(get(path_count_unconstraint, v)) + dependency_type(get(path_count_constraint, v))) / dependency_type(2))\n              //~ / ((dependency_type(get(path_count_unconstraint, w)) + dependency_type(get(path_count_constraint, w))) / dependency_type(2));\n            dependency_type factor = (ctx_fac) ?\n              (dependency_type(get(path_count_constraint, v)) / dependency_type(get(path_count_constraint, w)))\n              * (dependency_type(get(path_count_unconstraint, v)) / dependency_type(get(path_count_unconstraint, w)))\n              :\n              dependency_type(get(path_count_unconstraint, v)) / dependency_type(get(path_count_unconstraint, w));\n            //~ if(factor_raw == dependency_type(0)){\n              //~ std::cout << *s << \" | \" << v << \" -> \" << w <<  \": true: \" << factor_raw << \" \\t fac: \" << factor << std::endl;\n              //~ std::cout << \"\\t  constraint v: \\t\" << dependency_type(get(path_count_constraint, v)) << std::endl\n                        //~ << \"\\tunconstraint v: \\t\" << dependency_type(get(path_count_unconstraint, v)) << std::endl\n                        //~ << \"\\t  constraint w: \\t\" << dependency_type(get(path_count_constraint, w)) << std::endl\n                        //~ << \"\\tunconstraint w: \\t\" << dependency_type(get(path_count_unconstraint, w)) << std::endl;\n            //~ }\n            //~ if(dependency_type(get(path_count_constraint, v)) != dependency_type(get(path_count_unconstraint, v)))\n              //~ std::cout << *s << \" | \" << v << \" -> \" << w <<  \": true: \" << factor_raw << \" \\t fac: \" << factor << std::endl\n                        //~ << \"\\t  constraint v: \\t\" << dependency_type(get(path_count_constraint, v)) << std::endl\n                        //~ << \"\\tunconstraint v: \\t\" << dependency_type(get(path_count_unconstraint, v)) << std::endl;\n            factor *= (dependency_type(1) + get(dependency, w));\n            put(dependency, v, get(dependency, v) + factor);\n            update_centrality(edge_centrality_map, *vw, factor);\n          }\n        }\n        \n        if (w != *s) {\n          update_centrality(centrality, w, get(dependency, w));\n        }\n      }\n    }\n\n    typedef typename graph_traits<Graph>::directed_category directed_category;\n    const bool is_undirected = \n      is_convertible<directed_category*, undirected_tag*>::value;\n    if (is_undirected) {\n      divide_centrality_by_two(vertices(g), centrality);\n      divide_centrality_by_two(edges(g), edge_centrality_map);\n    }\n  }\n\n} } // end namespace detail::graph\n\ntemplate<typename Graph, typename CentralityMap, typename EdgeCentralityMap, \n         typename IncomingMap, typename DistanceMap, \n         typename DependencyMap, typename PathCountMap, \n         typename VertexIndexMap, typename WeightMap,\n         typename BetweennessDecisionFunction>    \nvoid \nbrandes_betweenness_centrality(const Graph& g, \n                               CentralityMap centrality,     // C_B\n                               EdgeCentralityMap edge_centrality_map,\n                               IncomingMap incoming, // P\n                               DistanceMap distance,         // d\n                               DependencyMap dependency,     // delta\n                               PathCountMap path_count_constraint,      // sigma\n                               PathCountMap path_count_unconstraint,      // sigma\n                               VertexIndexMap vertex_index,\n                               WeightMap weight_map,\n                               BetweennessDecisionFunction &betw_decision_fct\n                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))\n{\n  \n  detail::graph::brandes_dijkstra_shortest_paths<WeightMap, const Graph, BetweennessDecisionFunction>\n    shortest_paths(weight_map,betw_decision_fct);\n\n  detail::graph::brandes_betweenness_centrality_impl(g, centrality, \n                                                     edge_centrality_map,\n                                                     incoming, distance,\n                                                     dependency, path_count_constraint,\n                                                     path_count_unconstraint,\n                                                     vertex_index, \n                                                     shortest_paths);\n}\n\nnamespace detail { namespace graph {\n  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\n           typename WeightMap, typename VertexIndexMap,\n           typename BetweennessDecisionFunction>\n  void \n  brandes_betweenness_centrality_dispatch2(const Graph& g,\n                                           CentralityMap centrality,\n                                           EdgeCentralityMap edge_centrality_map,\n                                           WeightMap weight_map,\n                                           VertexIndexMap vertex_index,\n                                           BetweennessDecisionFunction &betw_decision_fct)\n  {\n    typedef typename graph_traits<Graph>::degree_size_type degree_size_type;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\n    typedef typename mpl::if_c<(is_same<CentralityMap, \n                                        dummy_property_map>::value),\n                                         EdgeCentralityMap, \n                               CentralityMap>::type a_centrality_map;\n    typedef typename property_traits<a_centrality_map>::value_type \n      centrality_type;\n\n    typename graph_traits<Graph>::vertices_size_type V = num_vertices(g);\n    \n    std::vector<std::vector<edge_descriptor> > incoming(V);\n    std::vector<centrality_type> distance(V);\n    std::vector<centrality_type> dependency(V);\n    std::vector<degree_size_type> path_count_constraint(V);\n    std::vector<degree_size_type> path_count_unconstraint(V);\n\n    brandes_betweenness_centrality(\n      g, centrality, edge_centrality_map,\n      make_iterator_property_map(incoming.begin(), vertex_index),\n      make_iterator_property_map(distance.begin(), vertex_index),\n      make_iterator_property_map(dependency.begin(), vertex_index),\n      make_iterator_property_map(path_count_constraint.begin(), vertex_index),\n      make_iterator_property_map(path_count_unconstraint.begin(), vertex_index),\n      vertex_index,\n      weight_map,\n      betw_decision_fct);\n  }\n  \n\n  template<typename Graph, typename CentralityMap, typename EdgeCentralityMap,\n           typename VertexIndexMap>\n  void \n  brandes_betweenness_centrality_dispatch2(const Graph& g,\n                                           CentralityMap centrality,\n                                           EdgeCentralityMap edge_centrality_map,\n                                           VertexIndexMap vertex_index)\n  {\n    typedef typename graph_traits<Graph>::degree_size_type degree_size_type;\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\n    typedef typename mpl::if_c<(is_same<CentralityMap, \n                                        dummy_property_map>::value),\n                                         EdgeCentralityMap, \n                               CentralityMap>::type a_centrality_map;\n    typedef typename property_traits<a_centrality_map>::value_type \n      centrality_type;\n\n    typename graph_traits<Graph>::vertices_size_type V = num_vertices(g);\n    \n    std::vector<std::vector<edge_descriptor> > incoming(V);\n    std::vector<centrality_type> distance(V);\n    std::vector<centrality_type> dependency(V);\n    std::vector<degree_size_type> path_count(V);\n\n    brandes_betweenness_centrality(\n      g, centrality, edge_centrality_map,\n      make_iterator_property_map(incoming.begin(), vertex_index),\n      make_iterator_property_map(distance.begin(), vertex_index),\n      make_iterator_property_map(dependency.begin(), vertex_index),\n      make_iterator_property_map(path_count.begin(), vertex_index),\n      vertex_index);\n  }\n\n  template<typename Graph, typename WeightMap, typename BetweennessDecisionFunction>\n  struct brandes_betweenness_centrality_dispatch1\n  {\n    template<typename CentralityMap, \n             typename EdgeCentralityMap, typename VertexIndexMap>\n    static void \n    run(const Graph& g, CentralityMap centrality, \n        EdgeCentralityMap edge_centrality_map, VertexIndexMap vertex_index,\n        WeightMap weight_map,\n        BetweennessDecisionFunction &betw_decision_fct)\n    {\n      brandes_betweenness_centrality_dispatch2(g, centrality, edge_centrality_map,\n                                               weight_map, vertex_index,\n                                               betw_decision_fct);\n    }\n  };\n\n  template <typename T>\n  struct is_bgl_named_params {\n    BOOST_STATIC_CONSTANT(bool, value = false);\n  };\n\n  template <typename Param, typename Tag, typename Rest>\n  struct is_bgl_named_params<bgl_named_params<Param, Tag, Rest> > {\n    BOOST_STATIC_CONSTANT(bool, value = true);\n  };\n\n} } // end namespace detail::graph\n\n// DocString: betweenness_ctx\n/**\n * @brief Betweenness centrality with dynamic contextual constraints.\n * \n * Using this function allows obtaining betweenness centrality under dynamic contextual constraints. Enforcement of constraints is the task of the given user-defined function.\n * \n * The function enforcing contextual constraints is evaluated at each node during shortest path traversal. The function needs to evaluate to True or False allowing an edge to be visited or not. As parameters, the current state of the betweenness calculation is passed to the function, i.e. the starting node for which a centrality value is being calculated, the current node, and the descending node in question. If the function returns False, the descending node is not being visited. \n * \n * The three nodes are passed as indices allowing for access of (external) attribute and other associated information.\n * \n * Note that the decision function is evaluated more than once during path traversal. That means, there should not happen any resource-intense computation inside this function. Also, it does not allow to keep track of the status of calculation, e.g. by calculating the visited edges or something similar.\n * \n * If the decision function simply returns True all the time, this function results in the unaltered betweenness centrality values.\n * \n * Obtaining betweenness centrality is based on Brandes' efficient algorithm. At the current stage, the implementation allows for single-core execution only.\n * \n * @param g The graph object\n * @param betw_decision_fct A function enforcing constraints. The signature of the function is ``(vertex index, vertex index, vertex index) -> Bool``.\n * \n */\ntemplate<typename Graph, typename Param, typename Tag, typename Rest, typename DecisionFunction>\nvoid \nbrandes_betweenness_centrality_ctx(const Graph& g, \n                               const bgl_named_params<Param,Tag,Rest>& params,\n                               DecisionFunction &betw_decision_fct\n                               BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))\n{\n  typedef bgl_named_params<Param,Tag,Rest> named_params;\n  typedef typename get_param_type<edge_weight_t, named_params>::type ew;\n  \n  detail::graph::brandes_betweenness_centrality_dispatch1<Graph, ew, DecisionFunction>::run(\n    g, \n    choose_param(get_param(params, vertex_centrality), \n                 dummy_property_map()),\n    choose_param(get_param(params, edge_centrality), \n                 dummy_property_map()),\n    choose_param(get_param(params, vertex_index), \n                 dummy_property_map()),\n    get_param(params, edge_weight),\n    betw_decision_fct);\n    \n}\n\n// disable_if is required to work around problem with MSVC 7.1 (it seems to not\n// get partial ordering getween this overload and the previous one correct)\n//~ template<typename Graph, typename CentralityMap>\n//~ typename disable_if<detail::graph::is_bgl_named_params<CentralityMap>,\n                    //~ void>::type\n//~ brandes_betweenness_centrality(const Graph& g, CentralityMap centrality\n                               //~ BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))\n//~ {\n  //~ detail::graph::brandes_betweenness_centrality_dispatch2(\n    //~ g, centrality, dummy_property_map(), get(vertex_index, g)); //TODO INDIZES\n//~ }\n\n//~ template<typename Graph, typename CentralityMap, typename EdgeCentralityMap>\n//~ void \n//~ brandes_betweenness_centrality(const Graph& g, CentralityMap centrality,\n                               //~ EdgeCentralityMap edge_centrality_map\n                               //~ BOOST_GRAPH_ENABLE_IF_MODELS_PARM(Graph,vertex_list_graph_tag))\n//~ {\n  //~ detail::graph::brandes_betweenness_centrality_dispatch2(\n    //~ g, centrality, edge_centrality_map, get(vertex_index, g)); //TODO INDIZES\n//~ }\n\n/**\n * Converts \"absolute\" betweenness centrality (as computed by the\n * brandes_betweenness_centrality algorithm) in the centrality map\n * into \"relative\" centrality. The result is placed back into the\n * given centrality map.\n */\ntemplate<typename Graph, typename CentralityMap>\nvoid \nrelative_betweenness_centrality(const Graph& g, CentralityMap centrality)\n{\n  typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\n  typedef typename property_traits<CentralityMap>::value_type centrality_type;\n\n  typename graph_traits<Graph>::vertices_size_type n = num_vertices(g);\n  centrality_type factor = centrality_type(2)/centrality_type(n*n - 3*n + 2);\n  vertex_iterator v, v_end;\n  for (boost::tie(v, v_end) = vertices(g); v != v_end; ++v) {\n    put(centrality, *v, factor * get(centrality, *v));\n  }\n}\n\n} // end namespace boost\n\n#endif // BOOST_GRAPH_BRANDES_BETWEENNESS_CENTRALITY_HPP\n", "meta": {"hexsha": "6fb747f216cd2930dad816e7bfe20cb51d57b89d", "size": 25798, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/nctx/topology/betweenness_centrality_ctx.hpp", "max_stars_repo_name": "nctx/py3nctx", "max_stars_repo_head_hexsha": "ee01aeaf675bbfd38dc4f37115d577a7796d2c80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-28T10:12:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T04:04:30.000Z", "max_issues_repo_path": "src/nctx/topology/betweenness_centrality_ctx.hpp", "max_issues_repo_name": "nctx/py3nctx", "max_issues_repo_head_hexsha": "ee01aeaf675bbfd38dc4f37115d577a7796d2c80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nctx/topology/betweenness_centrality_ctx.hpp", "max_forks_repo_name": "nctx/py3nctx", "max_forks_repo_head_hexsha": "ee01aeaf675bbfd38dc4f37115d577a7796d2c80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.650994575, "max_line_length": 486, "alphanum_fraction": 0.6586557097, "num_tokens": 5457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.43265776396372463}}
{"text": "//|\n//|    Copyright (C) 2019 Learning Algorithms and Systems Laboratory, EPFL, Switzerland\n//|    Authors:  Konstantinos Chatzilygeroudis (maintainer)\n//|              Bernardo Fichera\n//|              Walid Amanhoud\n//|    email:    costashatz@gmail.com\n//|              bernardo.fichera@epfl.ch\n//|              walid.amanhoud@epfl.ch\n//|    Other contributors:\n//|              Yoan Mollard (yoan@aubrune.eu)\n//|    website:  lasa.epfl.ch\n//|\n//|    This file is part of iiwa_ros.\n//|\n//|    iiwa_ros is free software: you can redistribute it and/or modify\n//|    it under the terms of the GNU General Public License as published by\n//|    the Free Software Foundation, either version 3 of the License, or\n//|    (at your option) any later version.\n//|\n//|    iiwa_ros is distributed in the hope that it will be useful,\n//|    but WITHOUT ANY WARRANTY; without even the implied warranty of\n//|    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n//|    GNU General Public License for more details.\n//|\n#include <Eigen/Dense>\n\n#include <pluginlib/class_list_macros.hpp>\n\n#include <iiwa_control/custom_effort_controller.hpp>\n\n#include <Corrade/Containers/PointerStl.h>\n\n#include <robot_controllers/CascadeController.hpp>\n#include <robot_controllers/SumController.hpp>\n\nnamespace iiwa_control {\n    template <class MatT>\n    Eigen::Matrix<typename MatT::Scalar, MatT::ColsAtCompileTime, MatT::RowsAtCompileTime> pseudo_inverse(const MatT& mat, typename MatT::Scalar tolerance = typename MatT::Scalar{1e-4}) // choose appropriately\n    {\n        typedef typename MatT::Scalar Scalar;\n        auto svd = mat.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);\n        const auto& singularValues = svd.singularValues();\n        Eigen::Matrix<Scalar, MatT::ColsAtCompileTime, MatT::RowsAtCompileTime> singularValuesInv(mat.cols(), mat.rows());\n        singularValuesInv.setZero();\n        for (unsigned int i = 0; i < singularValues.size(); ++i) {\n            if (singularValues(i) > tolerance) {\n                singularValuesInv(i, i) = Scalar{1} / singularValues(i);\n            }\n            else {\n                singularValuesInv(i, i) = Scalar{0};\n            }\n        }\n        return svd.matrixV() * singularValuesInv * svd.matrixU().adjoint();\n    }\n\n    std::vector<std::vector<std::string>> get_types(const std::string& input, const std::string& output)\n    {\n        std::vector<std::vector<std::string>> result(2);\n\n        // Input\n        std::string s = input;\n        std::string delimiter = \"|\";\n\n        size_t pos = 0;\n        std::string token;\n        while ((pos = s.find(delimiter)) != std::string::npos) {\n            token = s.substr(0, pos);\n            result[0].push_back(token);\n            s.erase(0, pos + delimiter.length());\n        }\n        // add the last one to the list\n        result[0].push_back(s);\n\n        // Output\n        s = output;\n        delimiter = \"|\";\n\n        pos = 0;\n        token = \"\";\n        while ((pos = s.find(delimiter)) != std::string::npos) {\n            token = s.substr(0, pos);\n            result[1].push_back(token);\n            s.erase(0, pos + delimiter.length());\n        }\n        // add the last one to the list\n        result[1].push_back(s);\n\n        return result;\n    }\n\n    void set_types(CustomEffortController::ControllerPtr& ctrl, const std::vector<std::string>& input, const std::vector<std::string>& output)\n    {\n        robot_controllers::IOTypes input_type, output_type;\n        for (auto& s : input) {\n            if (s == \"Position\")\n                input_type = input_type | robot_controllers::IOType::Position;\n            else if (s == \"Orientation\")\n                input_type = input_type | robot_controllers::IOType::Orientation;\n            else if (s == \"Velocity\")\n                input_type = input_type | robot_controllers::IOType::Velocity;\n            else if (s == \"AngularVelocity\")\n                input_type = input_type | robot_controllers::IOType::AngularVelocity;\n            else if (s == \"Acceleration\")\n                input_type = input_type | robot_controllers::IOType::Acceleration;\n            else if (s == \"AngularAcceleration\")\n                input_type = input_type | robot_controllers::IOType::AngularAcceleration;\n            else if (s == \"Force\")\n                input_type = input_type | robot_controllers::IOType::Force;\n            else if (s == \"Torque\")\n                input_type = input_type | robot_controllers::IOType::Torque;\n        }\n\n        for (auto& s : output) {\n            if (s == \"Position\")\n                output_type = output_type | robot_controllers::IOType::Position;\n            else if (s == \"Orientation\")\n                output_type = output_type | robot_controllers::IOType::Orientation;\n            else if (s == \"Velocity\")\n                output_type = output_type | robot_controllers::IOType::Velocity;\n            else if (s == \"AngularVelocity\")\n                output_type = output_type | robot_controllers::IOType::AngularVelocity;\n            else if (s == \"Acceleration\")\n                output_type = output_type | robot_controllers::IOType::Acceleration;\n            else if (s == \"AngularAcceleration\")\n                output_type = output_type | robot_controllers::IOType::AngularAcceleration;\n            else if (s == \"Force\")\n                output_type = output_type | robot_controllers::IOType::Force;\n            else if (s == \"Torque\")\n                output_type = output_type | robot_controllers::IOType::Torque;\n        }\n\n        ctrl->SetIOTypes(input_type, output_type);\n    }\n\n    void set_input_space(CustomEffortController::ControllerPtr& ctrl, size_t space_dim)\n    {\n        size_t input_dim = 0;\n\n        if (ctrl->GetInput().GetType() & robot_controllers::IOType::Position) {\n            input_dim += space_dim;\n        }\n        if (ctrl->GetInput().GetType() & robot_controllers::IOType::Orientation) {\n            input_dim += 3; // This is fixed to 3D\n        }\n        if (ctrl->GetInput().GetType() & robot_controllers::IOType::Velocity) {\n            input_dim += space_dim;\n        }\n        if (ctrl->GetInput().GetType() & robot_controllers::IOType::AngularVelocity) {\n            input_dim += 3; // This is fixed to 3D\n        }\n        if (ctrl->GetInput().GetType() & robot_controllers::IOType::Acceleration) {\n            input_dim += space_dim;\n        }\n        if (ctrl->GetInput().GetType() & robot_controllers::IOType::AngularAcceleration) {\n            input_dim += 3; // This is fixed to 3D\n        }\n        if (ctrl->GetInput().GetType() & robot_controllers::IOType::Force) {\n            input_dim += space_dim;\n        }\n        if (ctrl->GetInput().GetType() & robot_controllers::IOType::Torque) {\n            input_dim += 3; // This is fixed to 3D\n        }\n\n        robot_controllers::RobotParams params = ctrl->GetParams();\n        params.input_dim_ = input_dim;\n        // TO-DO: We assume same input/output\n        params.output_dim_ = input_dim;\n\n        ctrl->SetParams(params);\n    }\n\n    CustomEffortController::CustomEffortController() {}\n\n    CustomEffortController::~CustomEffortController() { sub_command_.shutdown(); }\n\n    bool CustomEffortController::init(hardware_interface::EffortJointInterface* hw, ros::NodeHandle& n)\n    {\n        // List of controlled joints\n        std::string param_name = \"joints\";\n        if (!n.getParam(param_name, joint_names_)) {\n            ROS_ERROR_STREAM(\"Failed to getParam '\" << param_name << \"' (namespace: \" << n.getNamespace() << \").\");\n            return false;\n        }\n        n_joints_ = joint_names_.size();\n\n        if (n_joints_ == 0) {\n            ROS_ERROR_STREAM(\"List of joint names is empty.\");\n            return false;\n        }\n\n        // Get URDF\n        urdf::Model urdf;\n        if (!urdf.initParam(\"robot_description\")) {\n            ROS_ERROR(\"Failed to parse urdf file\");\n            return false;\n        }\n\n        // Get basic parameters\n        n.param<std::string>(\"params/space\", operation_space_, \"joint\"); // Default operation space is task-space\n\n        // Check the operational space\n        if (operation_space_ == \"task\") {\n            space_dim_ = 3;\n\n            // Get the URDF XML from the parameter server\n            std::string urdf_string, full_param;\n            std::string robot_description = \"robot_description\";\n            std::string end_effector;\n\n            // gets the location of the robot description on the parameter server\n            if (!n.searchParam(robot_description, full_param)) {\n                ROS_ERROR(\"Could not find parameter %s on parameter server\", robot_description.c_str());\n                return false;\n            }\n\n            // search and wait for robot_description on param server\n            while (urdf_string.empty()) {\n                ROS_INFO_ONCE_NAMED(\"CustomEffortController\", \"CustomEffortController is waiting for model\"\n                                                              \" URDF in parameter [%s] on the ROS param server.\",\n                    robot_description.c_str());\n\n                n.getParam(full_param, urdf_string);\n\n                usleep(100000);\n            }\n            ROS_INFO_STREAM_NAMED(\"CustomEffortController\", \"Received urdf from param server, parsing...\");\n\n            // Get the end-effector\n            n.param<std::string>(\"params/end_effector\", end_effector, \"iiwa_link_ee\");\n\n            // Initialize iiwa tools\n            tools_.init_rbdyn(urdf_string, end_effector);\n        }\n        else\n            space_dim_ = n_joints_;\n\n        // Read Controllers from Params\n        std::map<std::string, ControllerPtr> controllers;\n        std::vector<std::string> ctrl_names;\n\n        XmlRpc::XmlRpcValue symbols;\n\n        n.getParam(\"controllers\", symbols);\n\n        assert(symbols.getType() == XmlRpc::XmlRpcValue::TypeStruct);\n        for (XmlRpc::XmlRpcValue::iterator i = symbols.begin(); i != symbols.end(); ++i) {\n            // ROS_WARN_STREAM(i->first << \": \" << i->second.getType());\n            std::string name = i->first;\n            std::string type, input, output;\n            std::vector<double> param_values;\n            n.getParam(\"controllers/\" + name + \"/type\", type);\n            n.getParam(\"controllers/\" + name + \"/params\", param_values);\n            n.getParam(\"controllers/\" + name + \"/input\", input);\n            n.getParam(\"controllers/\" + name + \"/output\", output);\n\n            if (type.size() == 0) {\n                ROS_WARN_STREAM(\"Could not find type of controller '\" << name << \"'. Skipping this controller!\");\n                continue;\n            }\n\n            auto ctrl = manager_.loadAndInstantiate(type);\n\n            if (ctrl) {\n                robot_controllers::RobotParams params;\n                params.input_dim_ = space_dim_;\n                params.output_dim_ = space_dim_;\n\n                params.time_step_ = 0.01; // TO-DO: Get this from controller manager or yaml\n\n                params.values_ = param_values;\n\n                ctrl->SetParams(params);\n\n                // TO-DO: Maybe separate input and output\n                if (input.size() > 0 && output.size() > 0) {\n                    std::vector<std::vector<std::string>> tt = get_types(input, output);\n                    if (tt.size() == 2)\n                        set_types(ctrl, tt[0], tt[1]);\n                }\n\n                set_input_space(ctrl, space_dim_);\n\n                controllers[name] = std::move(ctrl);\n                ctrl_names.push_back(name);\n            }\n        }\n\n        XmlRpc::XmlRpcValue symbols_structure;\n        n.getParam(\"structure\", symbols_structure);\n\n        if (symbols_structure.getType() == XmlRpc::XmlRpcValue::TypeStruct) {\n            for (XmlRpc::XmlRpcValue::iterator i = symbols_structure.begin(); i != symbols_structure.end(); ++i) {\n                // ROS_WARN_STREAM(i->first << \": \" << i->second.getType());\n                std::string name = i->first;\n                std::vector<std::string> sub;\n                n.getParam(\"structure/\" + name, sub);\n                bool is_sum = false;\n                if (name.find(\"Add\") == 0) {\n                    controllers[name] = ControllerPtr(new robot_controllers::SumController);\n                    is_sum = true;\n                }\n                else if (name.find(\"Cascade\") == 0) {\n                    controllers[name] = ControllerPtr(new robot_controllers::CascadeController);\n                }\n                else {\n                    ROS_WARN_STREAM(\"Cannot identify the type of the controller by the name: '\" << name << \"'. Ignoring!\");\n                    continue;\n                }\n                // std::cout << sub.size() << std::endl;\n                for (size_t k = 0; k < sub.size(); k++) {\n                    // ROS_WARN_STREAM(\"    \" << sub[k]);\n                    if (is_sum)\n                        static_cast<robot_controllers::SumController*>(controllers[name].get())->AddController(std::move(controllers[sub[k]]));\n                    else\n                        static_cast<robot_controllers::CascadeController*>(controllers[name].get())->AddController(std::move(controllers[sub[k]]));\n                    ctrl_names.erase(std::remove(ctrl_names.begin(), ctrl_names.end(), sub[k]), ctrl_names.end());\n                    controllers.erase(sub[k]);\n                }\n\n                // Initialize parameters\n                robot_controllers::RobotParams params;\n                params.input_dim_ = space_dim_;\n                params.output_dim_ = space_dim_;\n\n                params.time_step_ = 0.01; // TO-DO: Get this from controller manager or yaml\n                controllers[name]->SetParams(params);\n\n                set_input_space(controllers[name], space_dim_);\n\n                ctrl_names.push_back(name);\n            }\n        }\n\n        null_space_control_ = false;\n        if (operation_space_ == \"task\") {\n            std::vector<double> joints;\n            n.getParam(\"params/null_space/joints\", joints);\n            null_space_control_ = (joints.size() == n_joints_);\n\n            if (null_space_control_) {\n                null_space_joint_config_ = Eigen::VectorXd::Map(joints.data(), joints.size());\n\n                null_space_Kp_ = 20.;\n                null_space_Kd_ = 0.1;\n                null_space_max_torque_ = 10.;\n\n                n.getParam(\"params/null_space/Kp\", null_space_Kp_);\n                n.getParam(\"params/null_space/Kp\", null_space_Kd_);\n                n.getParam(\"params/null_space/max_torque\", null_space_max_torque_);\n            }\n        }\n\n        unsigned int ctrl_size = ctrl_names.size();\n\n        if (ctrl_size == 0) {\n            ROS_ERROR_STREAM(\"Could not load specified controllers! Exiting..!\");\n            return false;\n        }\n\n        if (ctrl_size == 1) {\n            controller_ = std::move(controllers[ctrl_names[0]]);\n\n            set_input_space(controller_, space_dim_);\n        }\n        else {\n            controller_.reset(new robot_controllers::SumController);\n            for (unsigned int i = 0; i < ctrl_size; i++) {\n                static_cast<robot_controllers::SumController*>(controller_.get())->AddController(std::move(controllers[ctrl_names[i]]));\n            }\n\n            set_input_space(controller_, space_dim_);\n        }\n\n        // Initialize the controller(s)\n        if (!controller_->Init()) {\n            ROS_ERROR(\"Controllers could not be initialized! Exiting!\");\n            return false;\n        }\n\n        for (unsigned int i = 0; i < n_joints_; i++) {\n            try {\n                joints_.push_back(hw->getHandle(joint_names_[i]));\n            }\n            catch (const hardware_interface::HardwareInterfaceException& e) {\n                ROS_ERROR_STREAM(\"Exception thrown: \" << e.what());\n                return false;\n            }\n\n            urdf::JointConstSharedPtr joint_urdf = urdf.getJoint(joint_names_[i]);\n            if (!joint_urdf) {\n                ROS_ERROR(\"Could not find joint '%s' in urdf\", joint_names_[i].c_str());\n                return false;\n            }\n            joint_urdfs_.push_back(joint_urdf);\n        }\n\n        // Get controller command size\n        cmd_dim_ = 0;\n\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::Position) {\n            cmd_dim_ += space_dim_;\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::Orientation) {\n            cmd_dim_ += 3; // This is fixed to 3D\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::Velocity) {\n            cmd_dim_ += space_dim_;\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::AngularVelocity) {\n            cmd_dim_ += 3; // This is fixed to 3D\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::Acceleration) {\n            cmd_dim_ += space_dim_;\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::AngularAcceleration) {\n            cmd_dim_ += 3; // This is fixed to 3D\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::Force) {\n            cmd_dim_ += space_dim_;\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::Torque) {\n            cmd_dim_ += 3; // This is fixed to 3D\n        }\n\n        std::vector<double> init_cmd(cmd_dim_, 0.0);\n        has_orientation_ = false;\n        if (operation_space_ == \"task\") {\n            has_orientation_ = ((controller_->GetInput().GetType() & robot_controllers::IOType::Orientation)) ? true : false;\n            bool has_position = ((controller_->GetInput().GetType() & robot_controllers::IOType::Position)) ? true : false;\n            if (has_position || has_orientation_) {\n                // if task space, we need to alter the initial command\n                iiwa_tools::RobotState robot_state;\n                robot_state.position.resize(n_joints_);\n                robot_state.velocity.resize(n_joints_);\n\n                for (size_t i = 0; i < n_joints_; i++) {\n                    robot_state.position[i] = joints_[i].getPosition();\n                    robot_state.velocity[i] = joints_[i].getVelocity();\n                }\n\n                auto ee_state = tools_.perform_fk(robot_state);\n                Eigen::AngleAxisd aa(ee_state.orientation);\n                Eigen::VectorXd o = aa.axis() * aa.angle();\n                Eigen::VectorXd p = ee_state.translation;\n\n                size_t offset = 0;\n                if (has_orientation_)\n                    offset = 3;\n\n                for (size_t i = 0; i < 3; i++) {\n                    if (has_orientation_)\n                        init_cmd[i] = o(i);\n                    if (has_position)\n                        init_cmd[i + offset] = p(i);\n                }\n            }\n        }\n\n        ROS_INFO_STREAM(\"Initial command: \" << Eigen::VectorXd::Map(init_cmd.data(), init_cmd.size()).transpose());\n\n        commands_buffer_.writeFromNonRT(init_cmd);\n\n        sub_command_ = n.subscribe<std_msgs::Float64MultiArray>(\"command\", 1, &CustomEffortController::commandCB, this);\n\n        return true;\n    }\n\n    void CustomEffortController::update(const ros::Time& time, const ros::Duration& period)\n    {\n        std::vector<double>& commands = *commands_buffer_.readFromRT();\n\n        Eigen::MatrixXd jac(6, n_joints_);\n        Eigen::MatrixXd jac_deriv(6, n_joints_);\n        Eigen::MatrixXd jac_t_pinv(n_joints_, 6);\n        Eigen::VectorXd eef(6);\n\n        if (operation_space_ == \"task\") {\n            iiwa_tools::RobotState robot_state;\n            robot_state.position.resize(n_joints_);\n            robot_state.velocity.resize(n_joints_);\n\n            for (size_t i = 0; i < n_joints_; i++) {\n                robot_state.position[i] = joints_[i].getPosition();\n                robot_state.velocity[i] = joints_[i].getVelocity();\n            }\n\n            std::tie(jac, jac_deriv) = tools_.jacobians(robot_state);\n            jac_t_pinv = pseudo_inverse(Eigen::MatrixXd(jac.transpose()));\n            auto ee_state = tools_.perform_fk(robot_state);\n            Eigen::AngleAxisd aa(ee_state.orientation);\n            eef.head(3) = aa.axis() * aa.angle();\n            eef.tail(3) = ee_state.translation;\n        }\n\n        Eigen::VectorXd cmd(n_joints_);\n\n        cmd = Eigen::VectorXd::Map(commands.data(), commands.size());\n\n        robot_controllers::RobotState curr_state, robot_state;\n        curr_state.position_ = Eigen::VectorXd::Zero(n_joints_);\n        curr_state.velocity_ = Eigen::VectorXd::Zero(n_joints_);\n        curr_state.acceleration_ = Eigen::VectorXd::Zero(n_joints_);\n        curr_state.force_ = Eigen::VectorXd::Zero(n_joints_);\n\n        for (unsigned int i = 0; i < n_joints_; i++) {\n            curr_state.position_(i) = joints_[i].getPosition();\n            curr_state.velocity_(i) = joints_[i].getVelocity();\n            // curr_state.acceleration_(i) = joints_[i].getAcceleration();\n            // TO-DO: Fill acceleration\n            curr_state.force_(i) = joints_[i].getEffort();\n        }\n\n        if (operation_space_ == \"task\") {\n            if (null_space_control_)\n                robot_state = curr_state;\n\n            Eigen::VectorXd pos = eef;\n            Eigen::VectorXd vel = jac * curr_state.velocity_;\n            Eigen::VectorXd acc = jac * curr_state.acceleration_ + jac_deriv * curr_state.velocity_;\n            Eigen::VectorXd f = jac_t_pinv * curr_state.force_; // TO-DO: This is not perfect, but should be enough\n\n            curr_state.position_ = pos.tail(3);\n            curr_state.velocity_ = vel.tail(3);\n            curr_state.acceleration_ = acc.tail(3);\n            curr_state.force_ = f.tail(3);\n\n            if (has_orientation_) {\n                curr_state.orientation_ = pos.head(3);\n                curr_state.angular_velocity_ = vel.head(3);\n                curr_state.angular_acceleration_ = acc.head(3);\n                curr_state.torque_ = f.head(3);\n            }\n        }\n\n        // Update desired state in controller\n        robot_controllers::RobotState desired_state;\n        unsigned int size = curr_state.position_.size();\n        unsigned int index = 0;\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::Orientation) {\n            desired_state.orientation_ = cmd.segment(index, 3);\n            index += 3;\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::Position) {\n            desired_state.position_ = cmd.segment(index, size);\n            index += size;\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::AngularVelocity) {\n            desired_state.angular_velocity_ = cmd.segment(index, 3);\n            index += 3;\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::Velocity) {\n            desired_state.velocity_ = cmd.segment(index, size);\n            index += size;\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::AngularAcceleration) {\n            desired_state.angular_acceleration_ = cmd.segment(index, 3);\n            index += 3;\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::Acceleration) {\n            desired_state.acceleration_ = cmd.segment(index, size);\n            index += size;\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::Torque) {\n            desired_state.torque_ = cmd.segment(index, 3);\n            index += 3;\n        }\n        if (controller_->GetInput().GetType() & robot_controllers::IOType::Force) {\n            desired_state.force_ = cmd.segment(index, size);\n            // index += size;\n        }\n\n        controller_->SetInput(desired_state);\n\n        // Update control torques given current velocity\n        controller_->Update(curr_state);\n\n        Eigen::VectorXd output; // = Eigen::VectorXd::Zero(space_dim_);\n        if (operation_space_ == \"task\") {\n            output = Eigen::VectorXd::Zero(2 * space_dim_);\n            if (controller_->GetOutput().GetType() & robot_controllers::IOType::Force)\n                output.tail(3) = controller_->GetOutput().desired_.force_;\n            if (controller_->GetOutput().GetType() & robot_controllers::IOType::Torque)\n                output.head(3) = controller_->GetOutput().desired_.torque_;\n        }\n        else // regular controller\n            output = controller_->GetOutput().desired_.force_;\n\n        if (operation_space_ == \"task\") {\n            // output.head(3) = Eigen::VectorXd::Zero(3);\n            output = jac.transpose() * output;\n\n            // Add null-space signal if wanted\n            if (null_space_control_) {\n                Eigen::VectorXd null_space_signal = null_space_Kp_ * (null_space_joint_config_ - robot_state.position_) - null_space_Kd_ * robot_state.velocity_;\n                Eigen::VectorXd null_space_force = (Eigen::MatrixXd::Identity(n_joints_, n_joints_) - jac.transpose() * jac_t_pinv) * null_space_signal;\n                for (int i = 0; i < null_space_force.size(); i++) {\n                    if (null_space_force(i) > null_space_max_torque_)\n                        null_space_force(i) = null_space_max_torque_;\n                    else if (null_space_force(i) < -null_space_max_torque_)\n                        null_space_force(i) = -null_space_max_torque_;\n                }\n                output = output + null_space_force;\n            }\n        }\n\n        // ROS_INFO_STREAM(\"Effort: \" << output.transpose());\n\n        std::vector<double> commanded_effort(n_joints_, 0.);\n\n        Eigen::VectorXd::Map(commanded_effort.data(), commanded_effort.size()) = output;\n\n        for (unsigned int i = 0; i < n_joints_; i++) {\n            enforceJointLimits(commanded_effort[i], i);\n            joints_[i].setCommand(commanded_effort[i]);\n        }\n    }\n\n    void CustomEffortController::commandCB(const std_msgs::Float64MultiArrayConstPtr& msg)\n    {\n        if (msg->data.size() != cmd_dim_) {\n            ROS_ERROR_STREAM(\"Dimension of command (\" << msg->data.size() << \") is not correct! Not executing!\");\n            return;\n        }\n\n        commands_buffer_.writeFromNonRT(msg->data);\n    }\n\n    void CustomEffortController::enforceJointLimits(double& command, unsigned int index)\n    {\n        // Check that this joint has applicable limits\n        if (command > joint_urdfs_[index]->limits->effort) // above upper limit\n        {\n            command = joint_urdfs_[index]->limits->effort;\n        }\n        else if (command < -joint_urdfs_[index]->limits->effort) // below lower limit\n        {\n            command = -joint_urdfs_[index]->limits->effort;\n        }\n    }\n} // namespace iiwa_control\n\nPLUGINLIB_EXPORT_CLASS(iiwa_control::CustomEffortController, controller_interface::ControllerBase)\n", "meta": {"hexsha": "21b0bf7da3456daf4125c160f7cd7314e4b7938d", "size": 26804, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "robot_control/iiwa_ros-master/iiwa_control/src/custom_effort_controller.cpp", "max_stars_repo_name": "stanFurrer/Multimodal-solution-for-grasp-stability-prediction", "max_stars_repo_head_hexsha": "b7d07a217e2a4846f3fe782fe7c3f4942f3299b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "robot_control/iiwa_ros-master/iiwa_control/src/custom_effort_controller.cpp", "max_issues_repo_name": "stanFurrer/Multimodal-solution-for-grasp-stability-prediction", "max_issues_repo_head_hexsha": "b7d07a217e2a4846f3fe782fe7c3f4942f3299b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "robot_control/iiwa_ros-master/iiwa_control/src/custom_effort_controller.cpp", "max_forks_repo_name": "stanFurrer/Multimodal-solution-for-grasp-stability-prediction", "max_forks_repo_head_hexsha": "b7d07a217e2a4846f3fe782fe7c3f4942f3299b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6858475894, "max_line_length": 209, "alphanum_fraction": 0.573794956, "num_tokens": 5989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.5544704649604274, "lm_q1q2_score": 0.4324830203983844}}
{"text": "#pragma once\n#include <model.hpp>\n#include <pybind11/eigen.h>\n#include <Eigen/Dense>\n#include <utils.hpp>\n#include <exception>\n#include <vector>\n#include <iostream>\n#include <fstream>\n\nnamespace dummyml\n{\n\nclass gaussian_process : public Model\n{\nprivate:\n    EigenMatrix _x;\n    EigenMatrix _y;\n    EigenMatrix _C_inv;\n    double _alpha;\n    std::unique_ptr<kernel> _kernel;\npublic:\n    struct MetaData{\n        Eigen::Index _n;\n        Eigen::Index _f;\n        kernel::type _t;\n        double _a;\n        Eigen::Index check_sum;\n        MetaData() = default;\n        MetaData(const gaussian_process& model):\n            _n(model._x.rows()),\n            _f(model._x.cols()),\n            _t(model._kernel->_T),\n            _a(model._alpha),\n            check_sum(\n                model._x.rows() ^\n                model._x.cols() ^\n                model._kernel->_T\n            ){}\n        bool is_check_sum_correct(){\n            return (_n ^ _f ^ _t) == check_sum;\n        }\n    };\n    gaussian_process(const char* filename){\n        load(filename);\n    }\n    gaussian_process(\n        double alpha = 0.2,\n        kernel::type k_type = kernel::type::LinearKernel\n    ): _alpha(alpha), _kernel(get_kernel(k_type)){}\n    gaussian_process(\n        nparray_d x,\n        nparray_d y,\n        double alpha = 0.2,\n        kernel::type k_type = kernel::type::LinearKernel\n    ): _alpha(alpha), _kernel(get_kernel(k_type)){\n        fit(x, y);\n    }\n    double run_kernel(double x, double y){\n        return (*_kernel)(x,y);\n    }\n    void load(const char* file_name){\n        std::fstream fin_bin(file_name,std::ios_base::in | std::ios_base::binary);\n        if(fin_bin.fail()){\n            throw std::runtime_error(\n                \"[ERROR] gaussian_process load: failed to load model.\"\n            );\n        }\n        MetaData meta;\n        fin_bin.read(\n            dummy_cast<char*,MetaData*>(&meta),\n            sizeof(MetaData)\n        );\n        if(!meta.is_check_sum_correct()){\n            throw std::runtime_error(\n                \"[ERROR] gaussian_process load: MetaData mismatch.\"\n            );\n        }\n        _alpha = meta._a;\n        _kernel = get_kernel(meta._t);\n        _x = EigenMatrix(meta._n, meta._f);\n        _y = EigenMatrix(meta._n, 1);\n        _C_inv = EigenMatrix(meta._n, meta._n);\n        fin_bin.read(\n            dummy_cast<char*,double*>(_x.data()),\n            sizeof(double) * _x.size()\n        ).read(\n            dummy_cast<char*,double*>(_y.data()),\n            sizeof(double) * _y.size()\n        ).read(\n            dummy_cast<char*,double*>(_C_inv.data()),\n            sizeof(double) * _C_inv.size()\n        );\n        return;\n    }\n    void save(const char* file_name){\n        std::fstream fout_bin(file_name,std::ios_base::out | std::ios_base::binary);\n        if(fout_bin.fail()){\n            throw std::runtime_error(\n                \"[ERROR] gaussian_process save: failed to save model.\"\n            );\n        }\n        MetaData meta(*this);\n        fout_bin.write(\n            dummy_cast<char*,MetaData*>(&meta),\n            sizeof(MetaData)\n        ).write(\n            dummy_cast<char*,double*>(_x.data()),\n            sizeof(double) * _x.size()\n        ).write(\n            dummy_cast<char*,double*>(_y.data()),\n            sizeof(double) * _y.size()\n        ).write(\n            dummy_cast<char*,double*>(_C_inv.data()),\n            sizeof(double) * _C_inv.size()\n        );\n        return;\n    }\n    void fit(nparray_d x, nparray_d y){\n        auto x_buf_info = x.request();\n        auto y_buf_info = y.request();\n        if(x_buf_info.shape[0] != y_buf_info.shape[0]){\n            throw std::length_error(\n                \"[ERROR] gaussian_process fit: data & label counts mismatch.\"\n            );\n        }\n        size_t dataset_size = x_buf_info.shape[0];\n        size_t feature_size = x_buf_info.shape[1];\n        double* x_ptr = (double*)x_buf_info.ptr;\n        double* y_ptr = (double*)y_buf_info.ptr;\n        \n        // copy x,y to _x,_y\n        _x.resize(dataset_size, feature_size);\n        _y.resize(dataset_size, 1);\n        _C_inv.resize(dataset_size, dataset_size);\n        memcpy(_x.data(), x_ptr, dataset_size * feature_size * sizeof(double));\n        memcpy(_y.data(), y_ptr, dataset_size                * sizeof(double));\n        \n        // calculate _C_inv\n        for(size_t row = 0;row < dataset_size; ++row)\n            for(size_t col = row;col < dataset_size; ++col)\n                _C_inv(col, row) = _C_inv(row, col) = (*_kernel)(_x.row(row), _x.row(col));\n        for(size_t diag = 0;diag < dataset_size; ++diag)\n            _C_inv(diag ,diag) += _alpha;\n        _C_inv = _C_inv.inverse();\n        return;\n    }\n    nparray_d operator()(nparray_d x){\n        auto x_buf_info = x.request();\n        size_t dataset_size = _x.rows();\n        size_t feature_size = _x.cols();\n        if(x_buf_info.shape[0] != feature_size){\n            throw std::length_error(\n                \"[ERROR] gaussian_process operator(): x size & feature size mismatch.\"\n            );\n        }\n        EigenVector x_vec(feature_size);\n        EigenMatrix kt_vec(1, dataset_size);\n        memcpy(x_vec.data(), x_buf_info.ptr, _x.cols()*sizeof(double));\n\n        for(size_t i = 0;i < dataset_size;++i)\n            kt_vec(0, i) = (*_kernel)(_x.row(i), x_vec);\n        EigenMatrix ktC_inv = kt_vec * _C_inv;\n        nparray_d result(2);\n        double* result_ptr = (double*)result.request().ptr;\n        result_ptr[0] = (ktC_inv * _y)(0);\n        result_ptr[1] =\n            ((*_kernel)(x_vec, x_vec) + _alpha) -  // c\n            (ktC_inv * kt_vec.transpose())(0);// kt * C^-1 * k\n        return result;\n    }\n    void set_alpha(double alpha){\n        _alpha = alpha;\n    }\n};\n\n} // namespace dummyml\n\nvoid export_gaussian_process(py::module_ &);", "meta": {"hexsha": "a217f4db7445b6c05b1054af6888d94bf8d44e39", "size": 5797, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dummyml/gaussian_process.hpp", "max_stars_repo_name": "BlenderWang9487/DummyML", "max_stars_repo_head_hexsha": "42177c45778d79d4200d0e039dafc67ab29b4a8b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/dummyml/gaussian_process.hpp", "max_issues_repo_name": "BlenderWang9487/DummyML", "max_issues_repo_head_hexsha": "42177c45778d79d4200d0e039dafc67ab29b4a8b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dummyml/gaussian_process.hpp", "max_forks_repo_name": "BlenderWang9487/DummyML", "max_forks_repo_head_hexsha": "42177c45778d79d4200d0e039dafc67ab29b4a8b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3854748603, "max_line_length": 91, "alphanum_fraction": 0.5454545455, "num_tokens": 1414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257127, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4324830203983844}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_GIS_GEOGRAPHIC_STRATEGIES_VINCENTY_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_GIS_GEOGRAPHIC_STRATEGIES_VINCENTY_HPP\n\n#include <boost/math/constants/constants.hpp>\n\n\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/extensions/gis/geographic/detail/ellipsoid.hpp>\n\n\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n/*!\n\\brief Distance calculation formulae on latlong coordinates, after Vincenty, 1975\n\\ingroup distance\n\\tparam Point1 \\tparam_first_point\n\\tparam Point2 \\tparam_second_point\n\\tparam CalculationType \\tparam_calculation\n\\author See http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf\n\\author Adapted from various implementations to get it close to the original document\n    - http://www.movable-type.co.uk/scripts/LatLongVincenty.html\n    - http://exogen.case.edu/projects/geopy/source/geopy.distance.html\n    - http://futureboy.homeip.net/fsp/colorize.fsp?fileName=navigation.frink\n\n*/\ntemplate\n<\n    typename RadiusType,\n    typename CalculationType = void\n>\nclass vincenty\n{\npublic :\n    template <typename Point1, typename Point2>\n    struct calculation_type\n        : promote_floating_point\n          <\n              typename select_calculation_type\n                  <\n                      Point1,\n                      Point2,\n                      CalculationType\n                  >::type\n          >\n    {};\n\n    typedef RadiusType radius_type;\n\n    inline vincenty()\n    {}\n\n    explicit inline vincenty(geometry::detail::ellipsoid<RadiusType> const& e)\n        : m_ellipsoid(e)\n    {}\n\n    template <typename Point1, typename Point2>\n    inline typename calculation_type<Point1, Point2>::type\n    apply(Point1 const& point1, Point2 const& point2) const\n    {\n        return calculate<typename calculation_type<Point1, Point2>::type>\n            (\n                get_as_radian<0>(point1), get_as_radian<1>(point1),\n                get_as_radian<0>(point2), get_as_radian<1>(point2)\n            );\n    }\n\n    inline geometry::detail::ellipsoid<RadiusType> ellipsoid() const\n    {\n        return m_ellipsoid;\n    }\n\n    inline RadiusType radius() const\n    {\n        // For now return the major axis. It is used in distance_cross_track, from point-to-line\n        return m_ellipsoid.a();\n    }\n\nprivate :\n    geometry::detail::ellipsoid<RadiusType> m_ellipsoid;\n\n    template <typename CT, typename T>\n    inline CT calculate(T const& lon1,\n                T const& lat1,\n                T const& lon2,\n                T const& lat2) const\n    {\n        CT const c2 = 2;\n        CT const pi = geometry::math::pi<CT>();\n        CT const two_pi = c2 * pi;\n\n        // lambda: difference in longitude on an auxiliary sphere\n        CT L = lon2 - lon1;\n        CT lambda = L;\n\n        if (L < -pi) L += two_pi;\n        if (L > pi) L -= two_pi;\n\n        if (math::equals(lat1, lat2) && math::equals(lon1, lon2))\n        {\n            return CT(0);\n        }\n\n        // U: reduced latitude, defined by tan U = (1-f) tan phi\n        CT const c1 = 1;\n        CT const one_min_f = c1 - m_ellipsoid.f();\n\n        CT const U1 = atan(one_min_f * tan(lat1)); // above (1)\n        CT const U2 = atan(one_min_f * tan(lat2)); // above (1)\n\n        CT const cos_U1 = cos(U1);\n        CT const cos_U2 = cos(U2);\n        CT const sin_U1 = sin(U1);\n        CT const sin_U2 = sin(U2);\n\n        // alpha: azimuth of the geodesic at the equator\n        CT cos2_alpha;\n        CT sin_alpha;\n\n        // sigma: angular distance p1,p2 on the sphere\n        // sigma1: angular distance on the sphere from the equator to p1\n        // sigma_m: angular distance on the sphere from the equator to the midpoint of the line\n        CT sigma;\n        CT sin_sigma;\n        CT cos2_sigma_m;\n\n        CT previous_lambda;\n\n        CT const c3 = 3;\n        CT const c4 = 4;\n        CT const c6 = 6;\n        CT const c16 = 16;\n\n        CT const c_e_12 = 1e-12;\n\n        do\n        {\n            previous_lambda = lambda; // (13)\n            CT sin_lambda = sin(lambda);\n            CT cos_lambda = cos(lambda);\n            sin_sigma = sqrt(math::sqr(cos_U2 * sin_lambda) + math::sqr(cos_U1 * sin_U2 - sin_U1 * cos_U2 * cos_lambda)); // (14)\n            CT cos_sigma = sin_U1 * sin_U2 + cos_U1 * cos_U2 * cos_lambda; // (15)\n            sin_alpha = cos_U1 * cos_U2 * sin_lambda / sin_sigma; // (17)\n            cos2_alpha = c1 - math::sqr(sin_alpha);\n            cos2_sigma_m = math::equals(cos2_alpha, 0) ? 0 : cos_sigma - c2 * sin_U1 * sin_U2 / cos2_alpha; // (18)\n\n            CT C = m_ellipsoid.f()/c16 * cos2_alpha * (c4 + m_ellipsoid.f() * (c4 - c3 * cos2_alpha)); // (10)\n            sigma = atan2(sin_sigma, cos_sigma); // (16)\n            lambda = L + (c1 - C) * m_ellipsoid.f() * sin_alpha *\n                (sigma + C * sin_sigma * ( cos2_sigma_m + C * cos_sigma * (-c1 + c2 * math::sqr(cos2_sigma_m)))); // (11)\n\n        } while (geometry::math::abs(previous_lambda - lambda) > c_e_12\n                && geometry::math::abs(lambda) < pi);\n\n        CT sqr_u = cos2_alpha * (math::sqr(m_ellipsoid.a()) - math::sqr(m_ellipsoid.b())) / math::sqr(m_ellipsoid.b()); // above (1)\n\n        // Oops getting hard here\n        // (again, problem is that ttmath cannot divide by doubles, which is OK)\n        CT const c47 = 47;\n        CT const c74 = 74;\n        CT const c128 = 128;\n        CT const c256 = 256;\n        CT const c175 = 175;\n        CT const c320 = 320;\n        CT const c768 = 768;\n        CT const c1024 = 1024;\n        CT const c4096 = 4096;\n        CT const c16384 = 16384;\n\n        CT A = c1 + sqr_u/c16384 * (c4096 + sqr_u * (-c768 + sqr_u * (c320 - c175 * sqr_u))); // (3)\n        CT B = sqr_u/c1024 * (c256 + sqr_u * ( -c128 + sqr_u * (c74 - c47 * sqr_u))); // (4)\n        CT delta_sigma = B * sin_sigma * ( cos2_sigma_m + (B/c4) * (cos(sigma)* (-c1 + c2 * cos2_sigma_m)\n                - (B/c6) * cos2_sigma_m * (-c3 + c4 * math::sqr(sin_sigma)) * (-c3 + c4 * cos2_sigma_m))); // (6)\n\n        return m_ellipsoid.b() * A * (sigma - delta_sigma); // (19)\n    }\n};\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct tag<vincenty<RadiusType, CalculationType> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename RadiusType, typename CalculationType, typename P1, typename P2>\nstruct return_type<vincenty<RadiusType, CalculationType>, P1, P2>\n    : vincenty<RadiusType, CalculationType>::template calculation_type<P1, P2>\n{};\n\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct comparable_type<vincenty<RadiusType, CalculationType> >\n{\n    typedef vincenty<RadiusType, CalculationType> type;\n};\n\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct get_comparable<vincenty<RadiusType, CalculationType> >\n{\n    static inline vincenty<RadiusType, CalculationType> apply(vincenty<RadiusType, CalculationType> const& input)\n    {\n        return input;\n    }\n};\n\ntemplate <typename RadiusType, typename CalculationType, typename P1, typename P2>\nstruct result_from_distance<vincenty<RadiusType, CalculationType>, P1, P2 >\n{\n    template <typename T>\n    static inline typename return_type<vincenty<RadiusType, CalculationType>, P1, P2>::type\n        apply(vincenty<RadiusType, CalculationType> const& , T const& value)\n    {\n        return value;\n    }\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n// We might add a vincenty-like strategy also for point-segment distance, but to calculate the projected point is not trivial\n\n\n\n}} // namespace strategy::distance\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_GIS_GEOGRAPHIC_STRATEGIES_VINCENTY_HPP\n", "meta": {"hexsha": "627700f91472fc078517ae159027363f5f73183f", "size": 8297, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/gis/geographic/strategies/vincenty.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "boost/geometry/extensions/gis/geographic/strategies/vincenty.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "boost/geometry/extensions/gis/geographic/strategies/vincenty.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 32.1589147287, "max_line_length": 132, "alphanum_fraction": 0.6401108835, "num_tokens": 2216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799928900257126, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.43248302039838427}}
{"text": "// Copyright (C) 2015 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/estimators/estimate_similarity_transformation_2d_3d.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <limits>\n#include <memory>\n#include <vector>\n\n#include \"theia/sfm/camera/camera.h\"\n#include \"theia/sfm/create_and_initialize_ransac_variant.h\"\n#include \"theia/sfm/feature.h\"\n#include \"theia/sfm/similarity_transformation.h\"\n#include \"theia/sfm/transformation/gdls_similarity_transform.h\"\n#include \"theia/solvers/estimator.h\"\n#include \"theia/solvers/sample_consensus_estimator.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\nnamespace {\n\ninline void TransformCamera(const SimilarityTransformation& sim_transform,\n                            Camera* camera) {\n  const Eigen::Vector3d old_position = camera->GetPosition();\n  const Eigen::Vector3d new_position =\n      sim_transform.scale * sim_transform.rotation *\n      old_position + sim_transform.translation;\n  camera->SetPosition(new_position);\n\n  const Eigen::Matrix3d old_orientation =\n      camera->GetOrientationAsRotationMatrix();\n  const Eigen::Matrix3d new_orientation =\n      old_orientation * sim_transform.rotation.transpose();\n  camera->SetOrientationFromRotationMatrix(new_orientation);\n}\n\n// An estimator for computing the similarity transformation from 4 2D-3D\n// correspondences using the gDLS algorithm to minimize reprojection error.\nclass GdlsSimilarityTransformationEstimator\n    : public Estimator<CameraAndFeatureCorrespondence2D3D,\n                       SimilarityTransformation> {\n public:\n  GdlsSimilarityTransformationEstimator() {}\n\n  // 3 correspondences are needed to determine the absolute pose.\n  double SampleSize() const { return 4; }\n\n  // Estimates candidate absolute poses from correspondences.\n  bool EstimateModel(\n      const std::vector<CameraAndFeatureCorrespondence2D3D>& correspondences,\n      std::vector<SimilarityTransformation>* similarity_transformations) const {\n    std::vector<Eigen::Vector3d> ray_origins(4), ray_directions(4),\n        world_points(4);\n    for (int i = 0; i < 4; i++) {\n      ray_origins[i] = correspondences[i].camera.GetPosition();\n      ray_directions[i] = correspondences[i].camera.PixelToUnitDepthRay(\n          correspondences[i].observation).normalized();\n      world_points[i] = correspondences[i].point3d.hnormalized();\n    }\n\n    // Compute the similarity transformation. Note that this function computes\n    // R, t, and s such that:\n    //\n    //   s * c_i + alpha_i * x_i = R * X_i + t\n    //\n    // where c_i is the camera position, alpha_i is the depth of the feature,\n    // x_i is the unit-norm feature observation, and X_i is the 3D point.\n    std::vector<Eigen::Quaterniond> rotations;\n    std::vector<Eigen::Vector3d> translations;\n    std::vector<double> scales;\n    GdlsSimilarityTransform(ray_origins,\n                            ray_directions,\n                            world_points,\n                            &rotations,\n                            &translations,\n                            &scales);\n\n    // Aggregate the solutions, modifying the output so that R, t, s are of the\n    // more useful form of:\n    //\n    //   s * R * (c_i + alpha_i * x_i) + t = X_i\n    //\n    // which transforms only the camera coordinate system so that it is aligned\n    // with the 3D points.\n    for (int i = 0; i < rotations.size(); i++) {\n      SimilarityTransformation similarity_transformation;\n      similarity_transformation.rotation =\n          rotations[i].toRotationMatrix().transpose();\n      similarity_transformation.translation =\n          similarity_transformation.rotation * -translations[i];\n      similarity_transformation.scale = scales[i];\n      similarity_transformations->emplace_back(similarity_transformation);\n    }\n    return similarity_transformations->size() > 0;\n  }\n\n  // The error for a correspondences given an absolute pose. This is the squared\n  // reprojection error.\n  double Error(\n      const CameraAndFeatureCorrespondence2D3D& correspondence,\n      const SimilarityTransformation& similarity_transformation) const {\n    // Apply the similarity transformation to the camera.\n    Camera transformed_camera = correspondence.camera;\n    TransformCamera(similarity_transformation, &transformed_camera);\n\n    Eigen::Vector2d reprojection;\n    // If the point is reprojected behind the camera, return the maximum\n    // possible error.\n    if (transformed_camera.ProjectPoint(correspondence.point3d, &reprojection) <\n        0) {\n      return std::numeric_limits<double>::max();\n    }\n\n    // Return the squared reprojection error.\n    return (correspondence.observation - reprojection).squaredNorm();\n  }\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(GdlsSimilarityTransformationEstimator);\n};\n\n}  // namespace\n\nbool EstimateSimilarityTransformation2D3D(\n    const RansacParameters& ransac_params,\n    const RansacType& ransac_type,\n    const std::vector<CameraAndFeatureCorrespondence2D3D>& correspondences,\n    SimilarityTransformation* similarity_transformation,\n    RansacSummary* ransac_summary) {\n  GdlsSimilarityTransformationEstimator similarity_transformation_estimator;\n  std::unique_ptr <\n      SampleConsensusEstimator<GdlsSimilarityTransformationEstimator> > ransac =\n      CreateAndInitializeRansacVariant(ransac_type,\n                                       ransac_params,\n                                       similarity_transformation_estimator);\n  // Estimate the absolute pose.\n  return ransac->Estimate(correspondences,\n                          similarity_transformation,\n                          ransac_summary);\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "4473b6bd158ea322039a867f2963449fe6e31c64", "size": 7361, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/estimators/estimate_similarity_transformation_2d_3d.cc", "max_stars_repo_name": "LEON-MING/TheiaSfM_Leon", "max_stars_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-17T17:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T09:21:38.000Z", "max_issues_repo_path": "src/theia/sfm/estimators/estimate_similarity_transformation_2d_3d.cc", "max_issues_repo_name": "LEON-MING/TheiaSfM_Leon", "max_issues_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/estimators/estimate_similarity_transformation_2d_3d.cc", "max_forks_repo_name": "LEON-MING/TheiaSfM_Leon", "max_forks_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T08:45:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-11T05:32:16.000Z", "avg_line_length": 41.5875706215, "max_line_length": 80, "alphanum_fraction": 0.7172938459, "num_tokens": 1597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4324708127429243}}
{"text": "#include <cmath>\n#include <vector>\n#include <string>\n#include \"multi_lidar_calib/common.h\"\n#include \"multi_lidar_calib/tic_toc.h\"\n#include <nav_msgs/Odometry.h>\n#include <opencv/cv.h>\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/filters/voxel_grid.h>\n#include <pcl/kdtree/kdtree_flann.h>\n#include <pcl/io/io.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/io/obj_io.h>\n#include <pcl/PolygonMesh.h>\n#include <pcl/point_cloud.h>\n#include <pcl/io/vtk_lib_io.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <pcl/sample_consensus/method_types.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/segmentation/sac_segmentation.h>\n#include <pcl/filters/extract_indices.h>\n#include <pcl/sample_consensus/ransac.h>\n#include <pcl/sample_consensus/sac_model_plane.h>\n#include <pcl/sample_consensus/sac_model_sphere.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <pcl/sample_consensus/sac_model_perpendicular_plane.h>\n#include <pcl/filters/passthrough.h>    ///直通滤波相关\n#include <ros/ros.h>\n#include <sensor_msgs/Imu.h>\n#include <sensor_msgs/PointCloud2.h>\n#include <tf/transform_datatypes.h>\n#include <tf/transform_broadcaster.h>\n\n #include <ceres/ceres.h>\n #include \"lidarFactor.hpp\"\n\n#include <pcl/features/vfh.h>\n#include <pcl/features/normal_3d.h>\n#include <boost/thread/thread.hpp>\n#include <pcl/common/common_headers.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/console/parse.h>\n#include <pcl/visualization/pcl_visualizer.h>\n#include <sstream>\n#include<vector>\n\n#include<mutex>\n\n#define PI 3.1415926\n\nusing std::atan2;\nusing std::cos;\nusing std::sin;\n\ndouble lidar_z_height = -1;\n\nros::Publisher  pubFittedPlane;\n\ndouble parameters[7] = {0, 0, 0, 1, 0, 0, 0}; // 激光雷达间相对位姿关系 \n\nEigen::Map<Eigen::Quaterniond> q_to_be_optimized(parameters);\nEigen::Map<Eigen::Vector3d> t_to_be_optimized(parameters + 4);\n\n\nvoid planeFitting(pcl::PointCloud<pcl::PointXYZ>::Ptr extracted_cloud, pcl::ModelCoefficients::Ptr & coefficients)\n{   \n\n    pcl::PointIndices::Ptr inliers (new pcl::PointIndices);\n    pcl::SACSegmentation<pcl::PointXYZ> seg;\n    seg.setOptimizeCoefficients (true);\n    seg.setModelType (pcl::SACMODEL_PLANE);\n    seg.setMethodType (pcl::SAC_RANSAC);\n    seg.setDistanceThreshold (0.01);\n     seg.setInputCloud(extracted_cloud);\n    seg.segment (*inliers, *coefficients);\n\n    // // ax + by + cz + d = 0，其中法向量为(a, b, c)\n    // std::cout<<\"平面参数：\"<<std::endl;\n    // std::cout<<\"a：\"<<coefficients->values[0]<<std::endl;\n    // std::cout<<\"b：\"<<coefficients->values[1]<<std::endl;\n    // std::cout<<\"c：\"<<coefficients->values[2]<<std::endl;\n    // std::cout<<\"d：\"<<coefficients->values[3]<<std::endl;\n    double a,b,c,d;\n    a =   coefficients->values[0];\n    b =  coefficients->values[1];\n    c =  coefficients->values[2];\n    d =  coefficients->values[3];\n    // double numerator = fabs(  a*x_c+b*y_c+c*z_c+d  );\n    // double denominator = std::sqrt(  a*a+b*b+c*c );\n    // double distanceToArea = numerator/ denominator;\n    pcl::PointCloud<pcl::PointXYZ>::Ptr fittedPlaneCloud(new pcl::PointCloud<pcl::PointXYZ>);\n    for (int i=0; i<inliers->indices.size();i++)\n    {\n        int ind = inliers->indices[i];\n         fittedPlaneCloud->points.push_back(  extracted_cloud->points[ind]  );\n    }\n\n    sensor_msgs::PointCloud2 fittedPlaneCloudMsg;\n    pcl::toROSMsg(*fittedPlaneCloud, fittedPlaneCloudMsg);\n    fittedPlaneCloudMsg.header.stamp = ros::Time::now();\n    fittedPlaneCloudMsg.header.frame_id = \"/rslidar\";\n    pubFittedPlane.publish(fittedPlaneCloudMsg);\n\n}\n\n\n\n\nint main(int argc, char **argv)\n{\n\n    ros::init(argc, argv, \"multi_lidar_calibration\");\n\tros::NodeHandle nh;\n    pubFittedPlane = nh.advertise<sensor_msgs::PointCloud2>(\"/fitted_plane\", 100);\n\n    for (int iterCount = 0; iterCount < 10; iterCount++)\n    {\n\n            ceres::LossFunction *loss_function = new ceres::HuberLoss(0.1);\n            ceres::LocalParameterization *q_parameterization =\n                new ceres::EigenQuaternionParameterization();\n            ceres::Problem::Options problem_options;\n\n            ceres::Problem problem(problem_options);\n            problem.AddParameterBlock(parameters, 4, q_parameterization);\n            problem.AddParameterBlock(parameters + 4, 3);\n\n            for (int k=0; k<36; k++)\n            {\n\n                std::stringstream ss;\n                std::string filename_pt0 = \"/media/mjy/Samsung_T5/linux/DX/data/0812forcalib/pcd_select/\";\n                std::string filename_pt1 = \"/media/mjy/Samsung_T5/linux/DX/data/0812forcalib/pcd_select/\";\n                ss << k+1;\n                std::string num = ss.str();\n                filename_pt0.append(num);\n                filename_pt0.append(\"_0.pcd\");   \n                filename_pt1.append(num);\n                filename_pt1.append(\"_1.pcd\");  \n                \n                std::cout<<\"Extracting \"<<k<<\" pointcloud from \"<<  filename_pt0<<std::endl;\n                std::cout<<\"Extracting \"<<k<<\" pointcloud from \"<<  filename_pt1<<std::endl;\n                pcl::PointCloud<pcl::PointXYZ>::Ptr cloud0(new pcl::PointCloud<pcl::PointXYZ>);\n                pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1(new pcl::PointCloud<pcl::PointXYZ>);\n\n                if (pcl::io::loadPCDFile<pcl::PointXYZ> (filename_pt0, *cloud0) == -1)\n                    {\n                    PCL_ERROR (\"Couldn't read PCD file \\n\");\n                    }\n                if (pcl::io::loadPCDFile<pcl::PointXYZ> (filename_pt1, *cloud1) == -1)\n                    {\n                    PCL_ERROR (\"Couldn't read PCD file \\n\");\n                    }\n\n                \n                pcl::ModelCoefficients::Ptr coefficients0 (new pcl::ModelCoefficients);\n                planeFitting(cloud0, coefficients0);\n                pcl::ModelCoefficients::Ptr coefficients1 (new pcl::ModelCoefficients);\n                planeFitting(cloud1,coefficients1);\n\n                // 两平面法线的夹角作为一个损失值\n                Eigen::Vector3d norm0(coefficients0->values[0], coefficients0->values[1], coefficients0->values[2]);\n                Eigen::Vector3d norm1(coefficients1->values[0], coefficients1->values[1], coefficients1->values[2]);\n                ceres::CostFunction *cost_function;\n                cost_function = LidarNormFactor::Create(norm0, norm1);\n                problem.AddResidualBlock(cost_function, loss_function, parameters, parameters + 4);\n\n\n\n\n                TicToc t_solver;\n                ceres::Solver::Options options;\n                options.linear_solver_type = ceres::DENSE_QR;\n                options.max_num_iterations = 10;\n                options.minimizer_progress_to_stdout = false;\n                options.check_gradients = false;\n                options.gradient_check_relative_precision = 1e-4;\n                ceres::Solver::Summary summary;\n                ceres::Solve(options, &problem, &summary);\n\n\n                sleep(0.2);\n\n            }\n\n    }\n\n\n\n\n    printf(\"result q %f %f %f %f result t %f %f %f\\n\", parameters[3], parameters[0], parameters[1], parameters[2],parameters[4], parameters[5], parameters[6]);\n    std::cout<<q_to_be_optimized.matrix()<<std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "6c150b124d19cf0fb0961ce9aab0896280998028", "size": 7161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "multi_lidar_calib/src/bpk.cpp", "max_stars_repo_name": "BIT-MJY/Multiple_Lidar_Calibration", "max_stars_repo_head_hexsha": "6bee0699a7a9a1c98b897206f38ae0d4e34524b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2021-08-13T05:52:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T05:01:35.000Z", "max_issues_repo_path": "multi_lidar_calib/src/bpk.cpp", "max_issues_repo_name": "Student865/Multiple_Lidar_Calibration", "max_issues_repo_head_hexsha": "58d70b1863d6e1524f61ec9c69acaf9edbb84198", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-09-11T14:40:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T13:21:00.000Z", "max_forks_repo_path": "multi_lidar_calib/src/bpk.cpp", "max_forks_repo_name": "Student865/Multiple_Lidar_Calibration", "max_forks_repo_head_hexsha": "58d70b1863d6e1524f61ec9c69acaf9edbb84198", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2021-08-13T12:09:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T08:15:01.000Z", "avg_line_length": 36.1666666667, "max_line_length": 159, "alphanum_fraction": 0.6402737048, "num_tokens": 1860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4324708127429243}}
{"text": "#include \"Tillotson.hpp\"\n#include <assert.h>\n#include <boost/math/tools/roots.hpp>\n#include <boost/math/tools/minima.hpp>\n#include <iostream>\n#include \"../../misc/universal_error.hpp\"\n#include \"../../misc/utils.hpp\"\n\nTillotson::Tillotson(double a, double b, double A, double B, double rho0, double E0, double EIV, double ECV, double\n\talpha, double beta, bool negative_pressure,size_t e_index) :\n\ta_(a), b_(b), A_(A), B_(B), rho0_(rho0), E0_(E0), EIV_(EIV), ECV_(ECV), alpha_(alpha), beta_(beta),\n\tnegative_pressure_(negative_pressure), temp_d_(0), temp_p_(0), e_index_(e_index){}\n\ndouble Tillotson::dp2EI(double d, double p) const\n{\n\tdouble eta = d / rho0_;\n\tdouble c = E0_ * eta*eta;\n\tdouble AB = (A_ - 2 * B_)*eta + (B_ - A_) + B_ * eta*eta;\n\tdouble A_B = A_ - B_;\n\tdouble sqr = std::sqrt(d*c * 2 * (a_ - b_)*(p - (A_B + eta * B_)*(eta - 1)) + d * d*c*c*(a_ + b_)*(a_ + b_) + (p - (eta - 1)*(A_B + eta * B_))\n\t\t*(p - (eta - 1)*(A_B + eta * B_)));\n\tdouble first_part = p - AB - a_ * c*d - b_ * c*d;\n\tdouble E = (first_part + sqr) / (2 * a_*d);\n\tif (E < 0)\n\t{\n\t\tE = p * 0.001 / d;\n\t}\n\tassert(E > 0);\n\treturn E;\n}\n\ndouble Tillotson::dp2EIV(double d, double p) const\n{\n\tdouble eta = d / rho0_;\n\tdouble mu = eta - 1;\n\tdouble c = E0_ * eta*eta;\n\tdouble A = A_ * mu;\n\tdouble eta2 = alpha_ * (rho0_ / d - 1) * (rho0_ / d - 1);\n\tdouble exp_alpha = (eta2 > 100) ? 0 : std::exp(-eta2);\n\tdouble eta3 = beta_ * (rho0_ / d - 1);\n\tdouble exp_beta = (eta3 > 100) ? 0 : A * std::exp(-eta3);\n\tdouble b = b_ * exp_alpha;\n\tdouble AB = exp_alpha * exp_beta;\n\tdouble E = (p - AB - a_ * c*d - b * c*d + sqrt(4 * a_*c*d*(p - AB) + std::pow(AB + (a_ + b)*c*d - p, 2))) /\n\t\t(2 * a_*d);\n\tif (E < 0)\n\t{\n\t\t//std::cout << \"d \" << d << \" p \" << p << std::endl;\n\t\tE = p * 0.001 / d;\n\t}\n\tassert(E > 0);\n\treturn E;\n}\n\ndouble Tillotson::de2pI(double d, double e)const\n{\n\tdouble eta = d / rho0_;\n\tdouble c = E0_ * eta*eta;\n\tdouble AB = (A_ - 2 * B_)*eta + (B_ - A_) + B_ * eta*eta;\n\tdouble res = 0;\n\t//if (negative_pressure_)\n\t\t//res = (a_ + b_ / (e / c + 1))*d*e + AB;\n\t//else\n\tres = std::max((a_ + b_ / (e / c + 1))*d*e + AB, a_*d*e*1e-7);\n\treturn res;\n}\n\ndouble Tillotson::de2pII(double d, double e)const\n{\n\tdouble P2 = de2pI(d, EIV_);\n\tdouble P3 = de2pIV(d, ECV_);\n\treturn std::max(((e - EIV_)*P3 + (ECV_ - e)*P2) / (ECV_ - EIV_), a_*d*e*1e-7);\n}\n\ndouble Tillotson::de2pIV(double d, double e)const\n{\n\tdouble eta = d / rho0_;\n\tif (alpha_ > 100 * eta*eta)\n\t\treturn a_ * d*e;\n\tdouble mu = eta - 1;\n\tdouble c = E0_ * eta*eta;\n\tdouble A = A_ * mu;\n\tdouble eta2 = alpha_ * (rho0_ / d - 1) * (rho0_ / d - 1);\n\tdouble exp_alpha = (eta2 > 100) ? 0 : std::exp(-eta2);\n\tdouble eta3 = beta_ * (rho0_ / d - 1);\n\tdouble exp_beta = (eta3 > 100) ? 0 : A * std::exp(-eta3);\n\t//if (negative_pressure_)\n\t\treturn a_ * d*e + exp_alpha * (b_*d*e / (e / c + 1) + exp_beta);\n\t//else\n\t//\treturn std::max(a_*d*e + exp_alpha * (b_*d*e / (e / c + 1) + exp_beta), a_ *d*e*1e-7);\n}\n\ndouble Tillotson::dep2cI(double d, double e, double p) const\n{\n\tdouble eta = d / rho0_;\n\tdouble w0 = e / (E0_*eta*eta) + 1;\n\tdouble gamma = a_ + b_ / w0;\n\tdouble res = (gamma + 1)*p / d + (A_ + B_ * (eta*eta - 1)) / d + b_ * (w0 - 1)*(2 * e - p / d) / (w0*w0);\n\tres = std::max(res, 1e-10*E0_);\n\treturn res;\n}\n\ndouble Tillotson::dep2cIV(double d, double e, double p) const\n{\n\tdouble eta = d / rho0_;\n\tdouble w0 = e / (E0_*eta*eta) + 1;\n\tdouble z = 1.0 / eta - 1.0;\n\tdouble afactor = (alpha_*z*z > 100) ? 0 : std::exp(-alpha_ * z*z);\n\tdouble res0 = p * (a_ + b_ * afactor / w0 + 1) / d;\n\tdouble bfactor = (beta_*z > 100) ? 0 : std::exp(-beta_ * z);\n\tdouble res1 = A_ * bfactor*afactor*(1 + (eta - 1)*(beta_ + 2 * alpha_*z - eta) / (eta*eta)) / rho0_;\n\tres1 += b_ * d*e*afactor*(2 * alpha_*z*w0 / rho0_ + (p / d - 2 * e) / (E0_*d)) / (w0*w0*eta*eta);\n\tdouble res = std::max(res0 + res1, 1e-10*E0_);\n\treturn res;\n}\n\nstruct dp2eII\n{\n\tdp2eII(Tillotson const& eos) : eos_(eos)\n\t{}\n\n\tdouble operator()(double e)\n\t{\n\t\tdouble res = std::abs(1.0 - eos_.de2pII(eos_.temp_d_, e) / eos_.temp_p_);\n\t\treturn res;\n\t}\nprivate:\n\tTillotson const& eos_;\n};\n\n\ndouble Tillotson::dp2e(double d, double p, tvector const & tracers, vector<string> const & tracernames) const\n{\n\tif(tracernames.size() > 0)\n\t\treturn tracers[e_index_];\n\n\tdouble eta = d / rho0_;\n\tdouble mu = eta - 1;\n\tdouble c = E0_ * eta*eta;\n\tdouble A = A_ * mu;\n\tif (d >= rho0_)\n\t{\n\t\treturn dp2EI(d, p);\n\t}\n\telse\n\t{\n\t\tdouble e4 = dp2EIV(d, p);\n\t\tdouble p4 = de2pI(d, e4);\n\t\tdouble e1 = dp2EI(d, p);\n\t\tdouble p1 = de2pI(d, e1);\n\t\t//double p1 = de2pI(d, e1);\n\t\tif (e1 < EIV_ && p1 > 0)\n\t\t\treturn dp2EI(d, p);\n\t\tif (p4<0 || e4>=ECV_)\n\t\t\treturn e4;\n\t\t\n\t\ttemp_d_ = d;\n\t\ttemp_p_ = p;\n\t\tboost::uintmax_t it = 50;\n\t\tstd::pair<double, double> res,res2;\n\t\ttry\n\t\t{\n\t\t\t//res = boost::math::tools::toms748_solve(dp2eII(*this), EIV_, ECV_, boost::math::tools::eps_tolerance<double>(30), it);\n\t\t\tres=boost::math::tools::brent_find_minima(dp2eII(*this), EIV_, ECV_, 30, it);\n\t\t\t//res2 = boost::math::tools::brent_find_minima(dp2eII(*this), EIV_, 0.5*(EIV_+ECV_), 30, it);\n\t\t}\n\t\tcatch (boost::exception const& eo)\n\t\t{\n\t\t\tdouble eta2 = alpha_ * (rho0_ / d - 1) * (rho0_ / d - 1);\n\t\t\tdouble exp_alpha = (eta2 > 100) ? 0 : std::exp(-eta2);\n\t\t\tdouble eta3 = beta_ * (rho0_ / d - 1);\n\t\t\tdouble exp_beta = (eta3 > 100) ? 0 : A * std::exp(-eta3);\n\t\t\tdouble PIV = de2pI(d, EIV_);\n\t\t\tdouble PCV = 0;\n\t\t\tif (negative_pressure_)\n\t\t\t\tPCV = a_ * d*ECV_ + exp_alpha * (b_*d*ECV_ / (ECV_ / c + 1) + exp_beta);\n\t\t\telse\n\t\t\t\tPCV = std::max(a_*d*ECV_ + exp_alpha * (b_*d*ECV_ / (ECV_ / c + 1) + exp_beta), (a_ + b_)*d*ECV_*1e-7);\n\t\t\tstd::cout << \" EIV_ \" << EIV_ << \" ECV_ \" << ECV_ << \" density \" << d << \" pressure \" << p << \" PIV \" << PIV << \" PCV \" << PCV << std::endl;\n\t\t}\n\t\tdouble result = res.first;\n\t\t//double result = res.second > res2.second ? res2.first : res.first;\n\t\tif (result > EIV_ && result < ECV_)\n\t\t{\n\t\t\tdouble newp = de2p(d, result);\n\t\t\tif (newp > p*0.001)\n\t\t\t{\n\t\t\t\tif (std::abs(p - newp) > 0.001*std::abs(p))\n\t\t\t\t{\n\t\t\t\t\tUniversalError eo(\"No dp2e convergence\");\n\t\t\t\t\teo.AddEntry(\"Density\", d);\n\t\t\t\t\teo.AddEntry(\"Pressure\", p);\n\t\t\t\t\teo.AddEntry(\"New Pressure\", newp);\n\t\t\t\t\teo.AddEntry(\"EIV\", EIV_);\n\t\t\t\t\teo.AddEntry(\"ECV\", ECV_);\n\t\t\t\t\teo.AddEntry(\"First energy\", res.first);\n\t\t\t\t\teo.AddEntry(\"Second energy\", res.second);\n\t\t\t\t\teo.AddEntry(\"First pressure\", de2p(d, res.first));\n\t\t\t\t\teo.AddEntry(\"Second pressure\", de2p(d, res.second));\n\t\t\t\t\tthrow eo;\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert(result > 0);\n\t\t\treturn result;\n\t\t}\n\t\treturn e4;\n\t}\n}\n\ndouble Tillotson::de2p(double d, double e, tvector const& /*tracers*/, vector<string> const& /*tracernames*/) const\n{\n\tif (d >= rho0_)\n\t{\n\t\treturn de2pI(d, e);\n\t}\n\telse\n\t{\n\t\tif (e <= EIV_)\n\t\t\treturn de2pI(d, e);\n\t\tif (e >= ECV_)\n\t\t\treturn de2pIV(d, e);\n\t\treturn de2pII(d, e);\n\t}\n}\n\ndouble Tillotson::de2c(double d, double e, tvector const & tracers, vector<string> const & tracernames) const\n{\n\tdouble p = de2p(d, e, tracers, tracernames);\n\treturn dp2c(d, p, tracers, tracernames);\n}\n\ndouble Tillotson::dp2c(double d, double p, tvector const & tracers, vector<string> const & tracernames) const\n{\n\tdouble e = dp2e(d, p, tracers, tracernames);\n\tif (d >= rho0_)\n\t{\n\t\tdouble res = dep2cI(d, e, p);\n\t\tassert(res > 0);\n\t\treturn std::sqrt(res);\n\t}\n\telse\n\t{\n\t\tif (e <= EIV_)\n\t\t{\n\t\t\tdouble res = dep2cI(d, e, p);\n\t\t\tassert(res > 0);\n\t\t\treturn std::sqrt(res);\n\t\t}\n\t\t//double e4 = dp2EIV(d, p);\n\t\tif (e >= ECV_)\n\t\t{\n\t\t\tdouble res = dep2cIV(d, e, p);\n\t\t\tassert(res > 0);\n\t\t\treturn std::sqrt(res);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble c1 = dep2cI(d, e, p);\n\t\t\tdouble c4 = dep2cIV(d, e, p);\n\t\t\tdouble res = std::sqrt((c1*(ECV_ - e) + c4 * (e - EIV_)) / (ECV_ - EIV_));\n\t\t\tassert(res > 0);\n\t\t\treturn res;\n\t\t}\n\t}\n}\n\ndouble Tillotson::dp2s(double /*d*/, double /*p*/, tvector const & /*tracers*/, vector<string> const & /*tracernames*/) const\n{\n\tstd::cout << \"dp2s not implemented\" << std::endl;\n\tassert(false);\n\treturn 0;\n}\n\ndouble Tillotson::sd2p(double /*s*/, double /*d*/, tvector const & /*tracers*/, vector<string> const & /*tracernames*/) const\n{\n\tstd::cout << \"sd2p not implemented\" << std::endl;\n\tassert(false);\n\treturn 0;\n}\n\nTillotson::~Tillotson(void)\n{}\n\n", "meta": {"hexsha": "fea9684744b6adc949059058fed5764fce6fa72f", "size": 8112, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/newtonian/common/Tillotson.cpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/newtonian/common/Tillotson.cpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/newtonian/common/Tillotson.cpp", "max_forks_repo_name": "GalaxyHunters/Vivid", "max_forks_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-29T09:39:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-25T19:17:49.000Z", "avg_line_length": 28.5633802817, "max_line_length": 143, "alphanum_fraction": 0.5808678501, "num_tokens": 3187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.43247081274292426}}
{"text": "\n#pragma once \n\n#include <vector>\n#include <cppsim/circuit_builder.hpp>\n#include <cppsim/type.hpp>\n#include <cppsim/simulator.hpp>\n#include <cppsim/utility.hpp>\n#include \"problem.hpp\"\n#include \"optimizer.hpp\"\n#include \"differential.hpp\"\n#include <functional>\n#include <Eigen/Dense>\n\nclass QuantumCircuitEnergyMinimizationSolver {\nprivate:\n    ParametricQuantumCircuit* _circuit;\n    const std::function<ParametricQuantumCircuit* (UINT, UINT)>* _circuit_construction;\n    UINT _param_count;\n    std::vector<double> _parameter;\n    double loss;\npublic:\n    bool verbose;\n    QuantumCircuitEnergyMinimizationSolver(const std::function<ParametricQuantumCircuit*(UINT,UINT)>* circuit_generator, UINT param_count = 0) {\n        _circuit_construction = circuit_generator;\n        _param_count = param_count;\n        _circuit = NULL;\n        verbose = false;\n    };\n    virtual ~QuantumCircuitEnergyMinimizationSolver() {\n    }\n\n    virtual void solve(\n        EnergyMinimizationProblem* instance,\n        UINT max_iteration = 100,\n        std::string optimizer_name = \"GD\",\n        std::string differentiation_method = \"HalfPi\"\n    ) {\n        if (_circuit != NULL) {\n            delete _circuit;\n            _circuit = NULL;\n        }\n        _circuit = (*_circuit_construction)(instance->get_qubit_count(), _param_count);\n        auto _simulator = new ParametricQuantumCircuitSimulator(_circuit);\n        _param_count = _simulator->get_parametric_gate_count();\n\n        _parameter = std::vector<double>(_param_count, 0.);\n        std::vector<double> gradient(_param_count);\n        Random random;\n        random.set_seed(0);\n        for (auto& val : _parameter) val = random.uniform()*acos(0.0)*4;\n        \n        GradientBasedOptimizer* optimizer;\n        QuantumCircuitGradientDifferentiation* differentiation;\n\n\n        if (optimizer_name == \"Adam\") {\n            optimizer = new AdamOptimizer(_param_count);\n        }\n        else if (optimizer_name == \"GD\") {\n            optimizer = new GradientDecentOptimizer(_param_count);\n        }\n        else return;\n        if (differentiation_method == \"HalfPi\") {\n            differentiation = new GradientByHalfPi();\n        }\n        std::vector<double> old_param;\n        for (UINT iteration = 0; iteration < max_iteration; ++iteration) {\n            loss = differentiation->compute_gradient(_simulator, instance, _parameter, &gradient);\n\n            if(verbose){\n                std::cout << \" *** epoch \" << iteration << \" *** \" << std::endl;\n                std::cout << \" * loss = \" << loss << std::endl;\n                old_param = _parameter;\n            }\n\n            optimizer->apply_gradient(&_parameter, gradient);\n\n            if (verbose) {\n                for (UINT i = 0; i < _param_count; ++i) {\n                    std::cout << \" ** id \" << i << \" para = \" << old_param[i] << \" -> \" << _parameter[i] << \" , grad = \" << gradient[i] << std::endl;\n                }\n            }\n        }\n        delete optimizer;\n        delete differentiation;\n        delete _simulator;\n    }\n    virtual double get_loss() { return loss; }\n    virtual std::vector<double> get_parameter() { return _parameter; }\n    ParametricQuantumCircuitSimulator* get_quantum_circuit_simulator() {\n        return new ParametricQuantumCircuitSimulator(_circuit);\n    }\n};\n\n\n\nclass DiagonalizationEnergyMinimizationSolver {\nprivate:\n    ParametricQuantumCircuit* _circuit;\n    const std::function<ParametricQuantumCircuit* (UINT, UINT)>* _circuit_construction;\n    UINT _param_count;\n    std::vector<double> _parameter;\n    double loss;\npublic:\n    bool verbose;\n    DiagonalizationEnergyMinimizationSolver() {\n        verbose = false;\n    };\n    virtual ~DiagonalizationEnergyMinimizationSolver() {\n    }\n\n    virtual void solve(\n        EnergyMinimizationProblem* instance\n    ) {\n        const UINT qubit_count = instance->get_qubit_count();\n        const UINT term_count = instance->get_term_count();\n        const ITYPE matrix_dim = 1ULL << qubit_count;\n\n        ComplexMatrix observable_matrix = ComplexMatrix::Zero(matrix_dim, matrix_dim);\n        for (UINT term_index = 0; term_index < term_count; ++term_index) {\n            auto Pauli_operator = instance->get_Pauli_operator(term_index);\n            double coef = Pauli_operator->get_coef();\n            auto target_index_list = Pauli_operator->get_index_list();\n            auto pauli_id_list = Pauli_operator->get_pauli_id_list();\n            \n            std::vector<UINT> whole_pauli_id_list(qubit_count, 0);\n            for (UINT i = 0; i < target_index_list.size(); ++i) {\n                whole_pauli_id_list[target_index_list[i]] = pauli_id_list[i];\n            }\n\n            ComplexMatrix pauli_matrix;\n            get_Pauli_matrix(pauli_matrix,whole_pauli_id_list);\n            observable_matrix += coef*pauli_matrix;\n        }\n\n        observable_matrix.eigenvalues();\n        Eigen::SelfAdjointEigenSolver<ComplexMatrix> eigen_solver(observable_matrix);\n        loss = eigen_solver.eigenvalues()[0];\n\n        if (verbose)    std::cout << \"Eigenvalues : \" << std::endl << eigen_solver.eigenvalues() << std::endl;\n    }\n    virtual double get_loss() { return loss; }\n};\n", "meta": {"hexsha": "a8b99743229b0be5b12b0a72443a1bde561a30f6", "size": 5174, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/vqcsim/solver.hpp", "max_stars_repo_name": "mshrn/qulacs", "max_stars_repo_head_hexsha": "2fbe8b5f27c093278d33bf6c44c63a09d6332437", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-22T18:35:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T18:35:25.000Z", "max_issues_repo_path": "src/vqcsim/solver.hpp", "max_issues_repo_name": "mshrn/qulacs", "max_issues_repo_head_hexsha": "2fbe8b5f27c093278d33bf6c44c63a09d6332437", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vqcsim/solver.hpp", "max_forks_repo_name": "mshrn/qulacs", "max_forks_repo_head_hexsha": "2fbe8b5f27c093278d33bf6c44c63a09d6332437", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6827586207, "max_line_length": 149, "alphanum_fraction": 0.6335523773, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4323966888548266}}
{"text": "#include <iostream>\n#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n\n#include <Eigen/Core>\n#include <igl/polar_dec.h>\n#include <igl/polar_svd.h>\n\nnamespace py = pybind11;\n\n\ntemplate<typename float_t>\npy::array_t<float_t> inv3(py::array_t<float_t, py::array::c_style> & Ts)\n{\n    auto Ts_buf = Ts.request();\n    float_t *pT = (float_t*)Ts_buf.ptr;\n\n    auto result = py::array_t<float_t, py::array::c_style>(Ts_buf.size);\n    auto result_buf = result.request();\n    float_t *pR = (float_t*)result_buf.ptr;\n\n    for (size_t idx = 0; idx < Ts_buf.shape[0]; idx++) {\n        const float_t T00 = pT[0], T01 = pT[1], T02 = pT[2];\n        const float_t T10 = pT[3], T11 = pT[4], T12 = pT[5];\n        const float_t T20 = pT[6], T21 = pT[7], T22 = pT[8];\n        const float_t det = T00 * (T22 * T11 - T21 * T12) \\\n                         - T10 * (T22 * T01 - T21 * T02) \\\n                         + T20 * (T12 * T01 - T11 * T02);\n        const float_t invDet = 1. / det;\n        pR[0] =  (T11 * T22 - T21 * T12) * invDet;\n        pR[1] = -(T01 * T22 - T02 * T21) * invDet;\n        pR[2] =  (T01 * T12 - T02 * T11) * invDet;\n        pR[3] = -(T10 * T22 - T12 * T20) * invDet;\n        pR[4] =  (T00 * T22 - T02 * T20) * invDet;\n        pR[5] = -(T00 * T12 - T10 * T02) * invDet;\n        pR[6] =  (T10 * T21 - T20 * T11) * invDet;\n        pR[7] = -(T00 * T21 - T20 * T01) * invDet;\n        pR[8] =  (T00 * T11 - T10 * T01) * invDet;\n\n        pT += 3*3;\n        pR += 3*3;\n    }\n\n    return result;\n}\n\ntemplate<typename float_t>\npy::array_t<float_t> inv2(py::array_t<float_t, py::array::c_style> & Ts)\n{\n    auto Ts_buf = Ts.request();\n    float_t *pT = (float_t*)Ts_buf.ptr;\n\n    auto result = py::array_t<float_t, py::array::c_style>(Ts_buf.size);\n    auto result_buf = result.request();\n    float_t *pR = (float_t*)result_buf.ptr;\n\n    for (size_t idx = 0; idx < Ts_buf.shape[0]; idx++) {\n        const float_t T00 = pT[0], T01 = pT[1];\n        const float_t T10 = pT[2], T11 = pT[3];\n        const float_t det = T00 * T11 - T01 * T10;\n        const float_t invDet = 1. / det;\n        pR[0] =  T11 * invDet;\n        pR[1] = -1 * T01 * invDet;\n        pR[2] = -1 * T10 * invDet;\n        pR[3] = T00 * invDet;\n\n        pT += 2*2;\n        pR += 2*2;\n    }\n\n    return result;\n}\n\ntemplate<typename float_t>\npy::array_t<float_t> matmat(\n        py::array_t<float_t, py::array::c_style> & a,\n        py::array_t<float_t, py::array::c_style> & b\n    )\n{\n    auto a_buf = a.request();\n    float_t *p_a = (float_t*)a_buf.ptr;\n    auto b_buf = b.request();\n    float_t *p_b = (float_t*)b_buf.ptr;\n\n    auto result = py::array_t<float_t, py::array::c_style>(\n            {a_buf.shape[0], a_buf.shape[1], b_buf.shape[2]});\n    auto result_buf = result.request();\n    float_t *p_res = (float_t*)result_buf.ptr;\n\n    const size_t n_rows_a = a_buf.shape[1];\n    const size_t n_cols_a = a_buf.shape[2];\n    const size_t n_rows_b = b_buf.shape[1];\n    const size_t n_cols_b = b_buf.shape[2];\n    assert(n_cols_a == n_rows_b);\n    for (size_t idx = 0; idx < a_buf.shape[0]; idx++) {\n        for (size_t row_a = 0; row_a < n_rows_a; row_a++) {\n            for (size_t col_b = 0; col_b < n_cols_b; col_b++) {\n                float_t sum = 0.0;\n                for (size_t k = 0; k < n_cols_a; k++) {\n                    const float_t ai = p_a[row_a * n_cols_a + k];\n                    const float_t bi = p_b[k * n_cols_b + col_b];\n                    sum += ai * bi;\n                }\n                *p_res = sum;\n                p_res++;\n            }\n        }\n        p_a += n_cols_a * n_rows_a;\n        p_b += n_cols_b * n_rows_b;\n    }\n\n    return result;\n}\n\ntemplate<typename float_t>\npy::array_t<float_t> matvec(\n        py::array_t<float_t, py::array::c_style> & mats,\n        py::array_t<float_t, py::array::c_style> & vecs\n    )\n{\n    auto mats_buf = mats.request();\n    float_t *p_mats = (float_t*)mats_buf.ptr;\n    auto vecs_buf = vecs.request();\n    float_t *p_vecs = (float_t*)vecs_buf.ptr;\n\n    auto result = py::array_t<float_t, py::array::c_style>({mats_buf.shape[0], mats_buf.shape[1]});\n    auto result_buf = result.request();\n    float_t *p_res = (float_t*)result_buf.ptr;\n\n    const size_t mat_stride1 = mats_buf.strides[1] / sizeof(float_t);\n    for (size_t idx = 0; idx < mats_buf.shape[0]; idx++) {\n        for (size_t row = 0; row < mats_buf.shape[1]; row++) {\n            float_t sum = 0.0;\n            for (size_t k = 0; k < mats_buf.shape[2]; k++) {\n                sum += *(p_mats++) * p_vecs[k];\n            }\n            *p_res = sum;\n            p_res++;\n        }\n        p_vecs += vecs_buf.shape[1];\n    }\n\n    return result;\n}\n\ntemplate<typename float_t>\npy::array_t<float_t> cross3(\n        py::array_t<float_t, py::array::c_style> & a,\n        py::array_t<float_t, py::array::c_style> & b\n    )\n{\n    auto a_buf = a.request();\n    float_t *p_a = (float_t*)a_buf.ptr;\n    auto b_buf = b.request();\n    float_t *p_b = (float_t*)b_buf.ptr;\n\n    auto result = py::array_t<float_t, py::array::c_style>(\n            {a_buf.shape[0], a_buf.shape[1]});\n    auto result_buf = result.request();\n    float_t *p_res = (float_t*)result_buf.ptr;\n\n    for (size_t idx = 0; idx < a_buf.shape[0]; idx++) {\n        const double ax = p_a[0];\n        const double ay = p_a[1];\n        const double az = p_a[2];\n        const double bx = p_b[0];\n        const double by = p_b[1];\n        const double bz = p_b[2];\n        p_res[0] = ay * bz - az * by;\n        p_res[1] = az * bx - ax * bz;\n        p_res[2] = ax * by - ay * bx;\n        p_res += 3;\n        p_a += 3;\n        p_b += 3;\n    }\n\n    return result;\n}\n\n\ntemplate<typename float_t>\npy::array_t<float_t> multikron(\n        py::array_t<float_t, py::array::c_style> & a,\n        py::array_t<float_t, py::array::c_style> & b\n    )\n{\n    auto a_buf = a.request();\n    float_t *p_a = (float_t*)a_buf.ptr;\n    auto b_buf = b.request();\n    float_t *p_b = (float_t*)b_buf.ptr;\n\n    const auto n_rows_a = a_buf.shape[1];\n    const auto n_cols_a = a_buf.shape[2];\n    const auto n_rows_b = b_buf.shape[1];\n    const auto n_cols_b = b_buf.shape[2];\n\n    auto result = py::array_t<float_t, py::array::c_style>(\n            {a_buf.shape[0], n_rows_a * n_rows_b, n_cols_a * n_cols_b});\n    auto result_buf = result.request();\n    float_t *p_res = (float_t*)result_buf.ptr;\n\n    for (size_t idx = 0; idx < a_buf.shape[0]; idx++) {\n        // iterate over rows of a\n        for (size_t row_a = 0; row_a < n_rows_a; row_a++) {\n            // iterate over rows of b\n            for (size_t row_b = 0; row_b < n_rows_b; row_b++) {\n                // iterate over columns of a\n                for (size_t col_a = 0; col_a < n_cols_a; col_a++) {\n                    // iterate over columns of b\n                    for (size_t col_b = 0; col_b < n_cols_b; col_b++) {\n                        const float_t ai = p_a[row_a * n_cols_a + col_a];\n                        const float_t bi = p_b[row_b * n_cols_b + col_b];\n                        *p_res = ai * bi;\n                        p_res++;\n                    }\n                }\n            }\n        }\n        // next matrix\n        p_a += n_cols_a * n_rows_a;\n        p_b += n_cols_b * n_rows_b;\n    }\n\n    return result;\n}\n\n\nstd::tuple<py::array_t<double>, py::array_t<double>>\npolarDecompose(py::array_t<double, py::array::c_style> Ms)\n{\n    using RowMat3d = Eigen::Matrix<double, 3, 3, Eigen::RowMajor>;\n\n    auto Ms_raw = Ms.unchecked<3>();\n    // allocate output matrices\n    auto Rs = py::array_t<double>({Ms_raw.shape(0), 3l, 3l});\n    auto Rs_raw = Rs.mutable_unchecked<3>();\n    auto Ss = py::array_t<double>({Ms_raw.shape(0), 3l, 3l});\n    auto Ss_raw = Ss.mutable_unchecked<3>();\n\n    RowMat3d U;\n    RowMat3d V;\n    Eigen::Matrix<double,3,1> S;\n\n    for (int i = 0; i < Ms_raw.shape(0); ++i) {\n        const RowMat3d Mi = Eigen::Map<const RowMat3d>(Ms_raw.data(i, 0, 0));\n        Eigen::Map<RowMat3d> Ri_map(Rs_raw.mutable_data(i, 0, 0));\n        Eigen::Map<RowMat3d> Si_map(Ss_raw.mutable_data(i, 0, 0));\n        RowMat3d Ri = Ri_map; // performs copy, since igl::polar_dec does not take Eigen::Map\n        RowMat3d Si = Si_map;\n        //igl::polar_dec(Mi, Ri, Si);\n        igl::polar_svd(Mi, Ri, Si, U, S, V);\n        // TODO: use igl::polar_svd3x3?\n        // write back results\n        Ri_map = Ri;\n        Si_map = Si;\n    }\n\n    return std::make_tuple(Rs, Ss);\n}\n\n\nPYBIND11_MODULE(_fastmath_ext, m) {\n    m.def(\"inv3\", &inv3<float>);\n    m.def(\"inv3\", &inv3<double>);\n    m.def(\"inv2\", &inv2<float>);\n    m.def(\"inv2\", &inv2<double>);\n    m.def(\"matmat\", &matmat<double>);\n    m.def(\"matvec\", &matvec<double>);\n    m.def(\"cross3\", &cross3<double>);\n    m.def(\"multikron\", &multikron<double>);\n    m.def(\"polar_dec\", &polarDecompose);\n}\n", "meta": {"hexsha": "abcca9c4801ed7a2c4abb039b59cf9a0afc9ea0d", "size": 8747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fastmath.cpp", "max_stars_repo_name": "tneumann/cgtools", "max_stars_repo_head_hexsha": "8f77b6a4642fe79ac85b8449ebd3f72ea0e56032", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-05-02T14:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-15T16:07:19.000Z", "max_issues_repo_path": "src/fastmath.cpp", "max_issues_repo_name": "tneumann/cgtools", "max_issues_repo_head_hexsha": "8f77b6a4642fe79ac85b8449ebd3f72ea0e56032", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fastmath.cpp", "max_forks_repo_name": "tneumann/cgtools", "max_forks_repo_head_hexsha": "8f77b6a4642fe79ac85b8449ebd3f72ea0e56032", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-02T14:08:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T03:47:29.000Z", "avg_line_length": 32.0402930403, "max_line_length": 99, "alphanum_fraction": 0.5427003544, "num_tokens": 2852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.43239550114340947}}
{"text": "#ifndef _NETWORK_H_\n#define _NETWORK_H_\n\n#include <boost/multi_array.hpp>\n#include <algorithm>\n#include <cassert>\n#include <chrono>\n#include <cmath>\n#include <cstdlib>\n#include <cstdint>\n#include <ctime>\n#include <limits>\n#include <fstream>\n#include <iostream>\n#include <numeric>\n#include <memory>\n#include <random>\n#include <vector>\n#include \"tbb/tbb.h\"\n#include \"Data.hpp\"\n#include \"Params.hpp\"\n\n#ifdef NDEBUG\n#define UNREACHABLE() __builtin_unreachable()\n#else\n#define UNREACHABLE() __builtin_trap()\n#endif\n\n/// Sigmoid activation function.\nstruct Sigmoid {\n  static float compute(float z) { return 1.0f / (1.0f + std::exp(-z)); }\n  static float deriv(float z) { return compute(z) * (1.0f - compute(z)); }\n};\n\n/// Rectified linear activation function.\nstruct ReLU {\n  static float compute(float z) { return std::max(0.0f, z); }\n  static float deriv(float z) { return z > 0.0f ? 1.0f : 0.0f; }\n};\n\ntemplate<float (*activationFnDeriv)(float)>\nstruct QuadraticCost {\n  static float compute(float activation, float label) {\n    return 0.5f * std::pow(std::abs(activation - label), 2);\n  }\n  static float delta(float z, float activation, float label) {\n    return (activation - label) * activationFnDeriv(z);\n  }\n};\n\nstruct CrossEntropyCost {\n  static float compute(float activation, float label) {\n    return (-label * std::log(activation))\n             - ((1.0f - label) * std::log(1.0f - activation));\n  }\n  static float delta(float z, float activation, float label) {\n    return activation - label;\n  }\n};\n\n/// Helper functions for conversions between 1D and 3D coordinates.\nstatic inline unsigned getX(unsigned index, unsigned dimX) {\n  return index % dimX;\n}\nstatic inline unsigned getY(unsigned index, unsigned dimX, unsigned dimY) {\n  return (index / dimX) % dimY;\n}\nstatic inline unsigned getZ(unsigned index, unsigned dimX, unsigned dimY) {\n  return (index / (dimX * dimY)) /* % dimZ */;\n}\nstatic inline unsigned getIndex(unsigned x, unsigned y, unsigned z,\n                                unsigned dimX, unsigned dimY) {\n  return ((dimX * dimY) * z) + (dimX * y) + x;\n}\n\ntemplate<unsigned mbSize>\nstruct Neuron {\n  /// Each neuron in the network can be indexed by a one- or three-dimensional\n  /// coordinate, and stores a weighted input, an activation and an error.\n  /// x and y are coordinates in the 2D image plane, z indexes depth.\n  unsigned index, x, y, z;\n  float weightedInputs[mbSize];\n  float activations[mbSize];\n  float errors[mbSize];\n  Neuron(unsigned index) : index(index) {}\n  Neuron(unsigned x, unsigned y, unsigned z) : x(x), y(y), z(z) {}\n};\n\ntemplate <unsigned mbSize>\nstruct Layer {\n  virtual void initialiseDefaultWeights(std::default_random_engine&) = 0;\n  virtual void feedForward(unsigned mb) = 0;\n  virtual void calcBwdError(unsigned mb) = 0;\n  virtual void backPropogate(unsigned mb) = 0;\n  virtual void endBatch(unsigned numTrainingImages) = 0;\n  virtual void setInputs(Layer<mbSize> *layer) = 0;\n  virtual void setOutputs(Layer<mbSize> *layer) = 0;\n  virtual float getBwdError(unsigned index, unsigned mb) = 0;\n  virtual float getBwdError(unsigned x, unsigned y, unsigned z, unsigned mb) = 0;\n  virtual Neuron<mbSize> &getNeuron(unsigned index) = 0;\n  virtual Neuron<mbSize> &getNeuron(unsigned x, unsigned y, unsigned z) = 0;\n  virtual unsigned getNumDims() = 0;\n  virtual unsigned getDim(unsigned i) = 0;\n  virtual unsigned size() = 0;\n};\n\n///===--------------------------------------------------------------------===///\n/// Input layer.\n///===--------------------------------------------------------------------===///\ntemplate <unsigned mbSize,\n          unsigned imageX,\n          unsigned imageY>\nclass InputLayer : public Layer<mbSize> {\n  // x, y, z dimensions of input image.\n  boost::multi_array<Neuron<mbSize>*, 3> neurons;\n\npublic:\n  InputLayer() :\n    neurons(boost::extents[imageX][imageY][1]) {\n    for (unsigned x = 0; x < imageX; ++x) {\n      for (unsigned y = 0; y < imageY; ++y) {\n        neurons[x][y][0] = new Neuron<mbSize>(x, y, 0);\n      }\n    }\n  }\n  void setImage(Image &image, unsigned mb) {\n    assert(image.size() == neurons.num_elements() && \"invalid image size\");\n    for (unsigned i = 0; i < image.size(); ++i) {\n      neurons[i % imageX][i / imageX][0]->activations[mb] = image[i];\n    }\n  }\n  void initialiseDefaultWeights(std::default_random_engine&) override {\n    UNREACHABLE();\n  }\n  virtual void calcBwdError(unsigned) override {\n    UNREACHABLE();\n  }\n  void feedForward(unsigned) override {\n    UNREACHABLE();\n  }\n  void backPropogate(unsigned) override {\n    UNREACHABLE();\n  }\n  void endBatch(unsigned) override {\n    UNREACHABLE();\n  }\n  void setInputs(Layer<mbSize>*) override {\n    UNREACHABLE();\n  }\n  void setOutputs(Layer<mbSize>*) override {\n    UNREACHABLE();\n  }\n  float getBwdError(unsigned, unsigned) override {\n    UNREACHABLE();\n  }\n  float getBwdError(unsigned, unsigned, unsigned, unsigned) override {\n    UNREACHABLE();\n  }\n  Neuron<mbSize> &getNeuron(unsigned i) override {\n    assert(i < neurons.num_elements() && \"Neuron index out of range.\");\n    return *neurons[i % imageX][i / imageX][0];\n  }\n  Neuron<mbSize> &getNeuron(unsigned x, unsigned y, unsigned z) override {\n    assert(z == 0 && \"Input image has depth 1\");\n    return *neurons[x][y][z];\n  }\n  unsigned getNumDims() override { return neurons.num_dimensions(); }\n  unsigned getDim(unsigned i) override { return neurons.shape()[i]; }\n  unsigned size() override { return neurons.num_elements(); }\n};\n\n///===--------------------------------------------------------------------===///\n/// Fully-connected neuron.\n///===--------------------------------------------------------------------===///\ntemplate <unsigned mbSize,\n          float (*activationFn)(float) = nullptr,\n          float (*activationFnDeriv)(float) = nullptr>\nclass FullyConnectedNeuron : public Neuron<mbSize> {\nprotected:\n  float learningRate;\n  float lambda;\n  Layer<mbSize> *inputs;\n  Layer<mbSize> *outputs;\n  std::vector<float> weights;\n  float bias;\n\npublic:\n  FullyConnectedNeuron(unsigned index, float learningRate, float lambda) :\n    Neuron<mbSize>(index),\n    learningRate(learningRate), lambda(lambda),\n    inputs(nullptr), outputs(nullptr) {}\n\n  void initialiseDefaultWeights(std::default_random_engine &gen) {\n    // Initialise all weights with random values from normal distribution with\n    // mean 0 and stdandard deviation 1, divided by the square root of the\n    // number of input connections.\n    std::normal_distribution<float> distribution(0, 1.0f);\n    for (unsigned i = 0; i < inputs->size(); ++i) {\n      float weight = distribution(gen) / std::sqrt(inputs->size());\n      weights.push_back(weight);\n    }\n    bias = distribution(gen);\n  }\n\n  void feedForward(unsigned mb) {\n    float weightedInput = 0.0f;\n    for (unsigned i = 0; i < inputs->size(); ++i) {\n      weightedInput += inputs->getNeuron(i).activations[mb] * weights[i];\n    }\n    weightedInput += bias;\n    this->weightedInputs[mb] = weightedInput;\n    this->activations[mb] = activationFn(weightedInput);\n  }\n\n  void backPropogate(unsigned mb) {\n    // Get the weight-error sum component from the next layer, then multiply by\n    // the sigmoid derivative to get the error for this neuron.\n    float error = outputs->getBwdError(this->index, mb);\n    error *= activationFnDeriv(this->weightedInputs[mb]);\n    this->errors[mb] = error;\n  }\n\n  void endBatch(unsigned numTrainingImages) {\n    // For each weight.\n    for (unsigned i = 0; i < inputs->size(); ++i) {\n      float weightDelta = 0.0f;\n      // For each batch element, average input activation x error (rate of\n      // change of cost w.r.t. weight) and multiply by learning rate.\n      // Note that FC layers can only be followed by FC layers.\n      for (unsigned j = 0; j < mbSize; ++j) {\n        weightDelta += inputs->getNeuron(i).activations[j] * this->errors[j];\n      }\n      weightDelta *= learningRate / mbSize;\n      float reg = 1.0f - (learningRate * (lambda / numTrainingImages));\n      weights[i] *= reg; // Regularisation term.\n      weights[i] -= weightDelta;\n    }\n    // For each batch element, average the errors (error is equal to rate of\n    // change of cost w.r.t. bias) and multiply by learning rate.\n    float biasDelta = 0.0f;\n    for (unsigned j = 0; j < mbSize; ++j) {\n      biasDelta += this->errors[j];\n    }\n    biasDelta *= learningRate / mbSize;\n    bias -= biasDelta;\n  }\n\n  void setInputs(Layer<mbSize> *inputs) { this->inputs = inputs; }\n  void setOutputs(Layer<mbSize> *outputs) { this->outputs = outputs; }\n  unsigned numWeights() { return weights.size(); }\n  float getWeight(unsigned i) { return weights.at(i); }\n};\n\n///===--------------------------------------------------------------------===///\n/// Fully-connected layer.\n///===--------------------------------------------------------------------===///\ntemplate <unsigned mbSize,\n          unsigned layerSize,\n          unsigned prevSize,\n          float (*activationFn)(float),\n          float (*activationFnDeriv)(float)>\nclass FullyConnectedLayer : public Layer<mbSize> {\n  using FullyConnectedNeuronTy =\n      FullyConnectedNeuron<mbSize, activationFn, activationFnDeriv>;\n  Layer<mbSize> *inputs;\n  Layer<mbSize> *outputs;\n  std::vector<FullyConnectedNeuronTy> neurons;\n  boost::multi_array<float, 2> bwdErrors; // [mb][i]\n\npublic:\n  FullyConnectedLayer(Params params) :\n      bwdErrors(boost::extents[mbSize][prevSize]) {\n    for (unsigned i = 0; i < layerSize; ++i) {\n      auto n = FullyConnectedNeuronTy(i, params.learningRate, params.lambda);\n      neurons.push_back(n);\n    }\n  }\n\n  void setInputs(Layer<mbSize> *layer) override {\n    inputs = layer;\n    for (auto &neuron : neurons) {\n      neuron.setInputs(layer);\n    }\n  }\n\n  void setOutputs(Layer<mbSize> *layer) override {\n    outputs = layer;\n    for (auto &neuron : neurons) {\n      neuron.setOutputs(layer);\n    }\n  }\n\n  void initialiseDefaultWeights(std::default_random_engine &gen) override {\n    for (auto &neuron : neurons) {\n      neuron.initialiseDefaultWeights(gen);\n    }\n  }\n\n  void feedForward(unsigned mb) override {\n    for (auto &neuron : neurons) {\n      neuron.feedForward(mb);\n    }\n  }\n\n  /// Calculate the l+1 component of the error for each neuron in prev layer.\n  void calcBwdError(unsigned mb) override {\n    for (unsigned i = 0; i < inputs->size(); ++i) {\n      float error = 0.0f;\n      for (auto &neuron : neurons) {\n        error += neuron.getWeight(i) * neuron.errors[mb];\n      }\n      bwdErrors[mb][i] = error;\n    }\n  }\n\n  /// Update errors from next layer.\n  void backPropogate(unsigned mb) override {\n    for (auto &neuron : neurons) {\n      neuron.backPropogate(mb);\n    }\n  }\n\n  void endBatch(unsigned numTrainingImages) override {\n    for (auto &neuron : neurons) {\n      neuron.endBatch(numTrainingImages);\n    }\n  }\n\n  float getBwdError(unsigned index, unsigned mb) override {\n    return bwdErrors[mb][index];\n  }\n\n  float getBwdError(unsigned, unsigned, unsigned, unsigned) override {\n    UNREACHABLE();\n  }\n\n  Neuron<mbSize> &getNeuron(unsigned index) override {\n    return neurons.at(index);\n  }\n\n  Neuron<mbSize> &getNeuron(unsigned, unsigned, unsigned) override {\n    UNREACHABLE();\n  }\n\n  unsigned getNumDims() override { return 1; }\n\n  unsigned getDim(unsigned i) override {\n    assert(i == 0 && \"Layer is 1D\");\n    return neurons.size();\n  }\n\n  unsigned size() override { return neurons.size(); }\n};\n\n///===--------------------------------------------------------------------===///\n/// Softmax neuron.\n///===--------------------------------------------------------------------===///\ntemplate <unsigned mbSize,\n          float (*costFn)(float, float),\n          float (*costDelta)(float, float, float)>\nclass SoftMaxNeuron : public FullyConnectedNeuron<mbSize> {\n\npublic:\n  SoftMaxNeuron(unsigned index, float learningRate, float lambda) :\n      FullyConnectedNeuron<mbSize>(index, learningRate, lambda) {}\n\n  void feedForward(unsigned mb) {\n    // Only calculate weighted inputs.\n    float weightedInput = 0.0f;\n    for (unsigned i = 0; i < this->inputs->size(); ++i) {\n      weightedInput +=\n        this->inputs->getNeuron(i).activations[mb] * this->weights[i];\n    }\n    weightedInput += this->bias;\n    this->weightedInputs[mb] = weightedInput;\n  }\n\n  void backPropogate(unsigned) { UNREACHABLE(); }\n\n  void computeOutputError(uint8_t label, unsigned mb) {\n    float y = label == this->index ? 1.0f : 0.0f;\n    float error = costDelta(this->weightedInputs[mb], this->activations[mb], y);\n    this->errors[mb] = error;\n  }\n\n  float computeOutputCost(uint8_t label, unsigned mb) {\n    return costFn(this->activations[mb], label);\n  }\n\n  float sumSquaredWeights() {\n    float result = 0.0f;\n    for (auto weight : this->weights) {\n      result += std::pow(weight, 2.0f);\n    }\n    return result;\n  }\n};\n\n///===--------------------------------------------------------------------===///\n/// Softmax layer.\n///===--------------------------------------------------------------------===///\ntemplate <unsigned mbSize,\n          unsigned layerSize,\n          unsigned prevSize,\n          float (*costFn)(float, float),\n          float (*costDelta)(float, float, float)>\nclass SoftMaxLayer : public Layer<mbSize> {\n  using SoftMaxNeuronTy = SoftMaxNeuron<mbSize, costFn, costDelta>;\n  Layer<mbSize> *inputs;\n  Layer<mbSize> *outputs;\n  std::vector<SoftMaxNeuronTy> neurons;\n  boost::multi_array<float, 2> bwdErrors; // [mb][i]\n\npublic:\n  SoftMaxLayer(float learningRate, float lambda) :\n      bwdErrors(boost::extents[mbSize][prevSize]) {\n    for (unsigned i = 0; i < layerSize; ++i) {\n      this->neurons.push_back(SoftMaxNeuronTy(i, learningRate, lambda));\n    }\n  }\n\n  void setInputs(Layer<mbSize> *layer) override {\n    inputs = layer;\n    for (auto &neuron : neurons) {\n      neuron.setInputs(layer);\n    }\n  }\n\n  void setOutputs(Layer<mbSize>*) override {\n    UNREACHABLE();\n  }\n\n  void initialiseDefaultWeights(std::default_random_engine &gen) override {\n    for (auto &neuron : neurons) {\n      neuron.initialiseDefaultWeights(gen);\n    }\n  }\n\n  void feedForward(unsigned mb) override {\n    // Calculate weighted inputs for each neuron.\n    // Sum the exponential values of the weighted inputs across neurons.\n    float sum = 0.0f;\n    for (auto &neuron : neurons) {\n      neuron.feedForward(mb);\n      sum += std::exp(neuron.weightedInputs[mb]);\n    }\n    // Calculate each of the neuron's activations.\n    for (auto &neuron : neurons) {\n      neuron.activations[mb] = std::exp(neuron.weightedInputs[mb]) / sum;\n    }\n  }\n\n  /// Calculate the l+1 component of the error for each neuron in prev layer.\n  void calcBwdError(unsigned mb) override {\n    for (unsigned i = 0; i < inputs->size(); ++i) {\n      float error = 0.0f;\n      for (auto &neuron : neurons) {\n        error += neuron.getWeight(i) * neuron.errors[mb];\n      }\n      bwdErrors[mb][i] = error;\n    }\n  }\n\n  /// Update errors from next layer.\n  void backPropogate(unsigned mb) override {\n    for (auto &neuron : neurons) {\n      neuron.backPropogate(mb);\n    }\n  }\n\n  void endBatch(unsigned numTrainingImages) override {\n    for (auto &neuron : neurons) {\n      neuron.endBatch(numTrainingImages);\n    }\n  }\n\n  /// Determine the index of the highest output activation.\n  unsigned readOutput(unsigned mb) {\n    unsigned result = 0;\n    float max = std::numeric_limits<float>::min();\n    for (unsigned i = 0; i < neurons.size(); ++i) {\n      float output = neurons[i].activations[mb];\n      if (output > max) {\n        result = i;\n        max = output;\n      }\n    }\n    return result;\n  }\n\n  void computeOutputError(uint8_t label, unsigned mb) {\n    for (auto &neuron : neurons) {\n      neuron.computeOutputError(label, mb);\n    }\n  }\n\n  float computeOutputCost(uint8_t label, unsigned mb) {\n    float outputCost = 0.0f;\n    for (auto &neuron : neurons) {\n      neuron.computeOutputCost(label, mb);\n    }\n    return outputCost;\n  }\n\n  float sumSquaredWeights() {\n    float result = 0.0f;\n    for (auto &neuron : neurons) {\n      result += neuron.sumSquaredWeights();\n    }\n    return result;\n  }\n\n  float getBwdError(unsigned index, unsigned mb) override {\n    return bwdErrors[mb][index];\n  }\n\n  float getBwdError(unsigned, unsigned, unsigned, unsigned) override {\n    UNREACHABLE();\n  }\n\n  Neuron<mbSize> &getNeuron(unsigned index) override {\n    return neurons.at(index);\n  }\n\n  Neuron<mbSize> &getNeuron(unsigned, unsigned, unsigned) override {\n    UNREACHABLE();\n  }\n\n  unsigned getNumDims() override { return 1; }\n\n  unsigned getDim(unsigned i) override {\n    assert(i == 0 && \"Layer is 1D\");\n    return neurons.size();\n  }\n\n  unsigned size() override { return neurons.size(); }\n};\n\n///===--------------------------------------------------------------------===///\n/// Convolutional neuron.\n///===--------------------------------------------------------------------===///\ntemplate <unsigned mbSize,\n          float (*activationFn)(float),\n          float (*activationFnDeriv)(float)>\nclass ConvNeuron : public Neuron<mbSize> {\n  Layer<mbSize> *inputs;\n  Layer<mbSize> *outputs;\n  unsigned dimX;\n  unsigned dimY;\n\npublic:\n  ConvNeuron(unsigned x, unsigned y, unsigned z, unsigned dimX, unsigned dimY) :\n      Neuron<mbSize>(x, y, z), dimX(dimX), dimY(dimY) {}\n\n  void feedForward(boost::multi_array_ref<float, 4> &weights,\n                   boost::multi_array_ref<float, 1> &bias,\n                   unsigned mb) {\n    // Convolve using each weight.\n    // (z is the index of the feature map.)\n    float weightedInput = 0.0f;\n    for (unsigned a = 0; a < weights.shape()[1]; ++a) {\n      for (unsigned b = 0; b < weights.shape()[2]; ++b) {\n        for (unsigned c = 0; c < weights.shape()[3]; ++c) {\n          unsigned inputX = this->x + a;\n          unsigned inputY = this->y + b;\n          float input = inputs->getNeuron(inputX, inputY, c).activations[mb];\n          weightedInput += input * weights[this->z][a][b][c];\n        }\n      }\n    }\n    // Add bias and apply non linerarity.\n    weightedInput += bias[this->z];\n    this->weightedInputs[mb] = weightedInput;\n    this->activations[mb] = activationFn(weightedInput);\n  }\n\n  void backPropogate(unsigned mb) {\n    // If next layer is 1D, map the x, y, z coordinates onto it.\n    unsigned index =\n      getIndex(this->x, this->y, this->z, this->dimX, this->dimY);\n    float error = outputs->getNumDims() == 1\n                    ? outputs->getBwdError(index, mb)\n                    : outputs->getBwdError(this->x, this->y, this->z, mb);\n    error *= activationFnDeriv(this->weightedInputs[mb]);\n    this->errors[mb] = error;\n  }\n\n  void setInputs(Layer<mbSize> *inputs) { this->inputs = inputs; }\n  void setOutputs(Layer<mbSize> *outputs) { this->outputs = outputs; }\n};\n\n///===--------------------------------------------------------------------===///\n/// Convolutional layer\n///\n/// kernelX is num cols\n/// kernelY is num rows\n/// neuron(x, y) is row y, col x\n/// weights(a, b) is row b, col a\n///===--------------------------------------------------------------------===///\ntemplate <unsigned mbSize,\n          unsigned kernelX,\n          unsigned kernelY,\n          unsigned kernelZ,\n          unsigned inputX,\n          unsigned inputY,\n          unsigned inputZ,\n          unsigned numFMs,\n          float (*activationFn)(float),\n          float (*activationFnDeriv)(float)>\nclass ConvLayer : public Layer<mbSize> {\n  using ConvNeuronTy = ConvNeuron<mbSize, activationFn, activationFnDeriv>;\n  float learningRate;\n  float lambda;\n  Layer<mbSize> *inputs;\n  Layer<mbSize> *outputs;\n  boost::multi_array<float, 1> bias;            // [fm]\n  boost::multi_array<float, 4> weights;         // [fm][x][y][z]\n  boost::multi_array<ConvNeuronTy*, 3> neurons; // [fm][x][y]\n  boost::multi_array<float, 4> bwdErrors;       // [mb][x][y][z]\n\npublic:\n  ConvLayer(Params params) :\n      learningRate(params.learningRate), lambda(params.lambda),\n      inputs(nullptr), outputs(nullptr),\n      bias(boost::extents[numFMs]),\n      weights(boost::extents[numFMs][kernelX][kernelY][kernelZ]),\n      neurons(boost::extents[numFMs][inputX-kernelX+1][inputY-kernelY+1]),\n      bwdErrors(boost::extents[mbSize][inputX][inputY][inputZ]) {\n    static_assert(inputZ == kernelZ, \"Kernel depth should match input depth\");\n    unsigned dimX = neurons.shape()[1];\n    unsigned dimY = neurons.shape()[2];\n    for (unsigned fm = 0; fm < numFMs; ++fm) {\n      for (unsigned x = 0; x < dimX; ++x) {\n        for (unsigned y = 0; y < dimY; ++y) {\n          neurons[fm][x][y] = new ConvNeuronTy(x, y, fm, dimX, dimY);\n        }\n      }\n    }\n  }\n\n  void initialiseDefaultWeights(std::default_random_engine &gen) override {\n    // Initialise weights random distribution of mean 0 and standard deviation\n    // 1, then scale it by 1/sqrt(number of inputs).\n    std::normal_distribution<float> distribution(0, 1.0f);\n    float scale =\n        std::sqrt(weights.shape()[1] * weights.shape()[2] * weights.shape()[3]);\n    for (unsigned fm = 0; fm < weights.shape()[0]; ++fm) {\n      for (unsigned a = 0; a < weights.shape()[1]; ++a) {\n        for (unsigned b = 0; b < weights.shape()[2]; ++b) {\n          for (unsigned c = 0; c < weights.shape()[3]; ++c) {\n            weights[fm][a][b][c] = distribution(gen) / scale;\n          }\n        }\n      }\n      bias[fm] = distribution(gen);\n    }\n  }\n\n  void feedForward(unsigned mb) override {\n    for (unsigned fm = 0; fm < neurons.shape()[0]; ++fm) {\n      for (unsigned x = 0; x < neurons.shape()[1]; ++x) {\n        for (unsigned y = 0; y < neurons.shape()[2]; ++y) {\n          neurons[fm][x][y]->feedForward(weights, bias, mb);\n        }\n      }\n    }\n  }\n\n  void calcBwdError(unsigned mb) override {\n    // Calculate the l+1 component of the error for each neuron in prev layer.\n    for (unsigned x = 0; x < inputX; ++x) {\n      for (unsigned y = 0; y < inputY; ++y) {\n        for (unsigned z = 0; z < inputZ; ++z) {\n          // Sum over all feature maps.\n          float error = 0.0f;\n          for (unsigned fm = 0; fm < numFMs; ++fm) {\n            for (unsigned a = 0; a < weights.shape()[1]; ++a) {\n              for (unsigned b = 0; b < weights.shape()[2]; ++b) {\n                if (a <= x && b <= y &&\n                    x - a < neurons.shape()[1] &&\n                    y - b < neurons.shape()[2]) {\n                  float ne = neurons[fm][x - a][y - b]->errors[mb];\n                  error += weights[fm][a][b][z] * ne;\n                }\n              }\n            }\n          }\n          bwdErrors[mb][x][y][z] = error;\n        }\n      }\n    }\n  }\n\n  void backPropogate(unsigned mb) override {\n    // Update errors from next layer.\n    for (unsigned fm = 0; fm < neurons.shape()[0]; ++fm) {\n      for (unsigned x = 0; x < neurons.shape()[1]; ++x) {\n        for (unsigned y = 0; y < neurons.shape()[2]; ++y) {\n          neurons[fm][x][y]->backPropogate(mb);\n        }\n      }\n    }\n  }\n\n  void endBatch(unsigned numTrainingImages) override {\n    // For each feature map.\n    for (unsigned fm = 0; fm < numFMs; ++fm) {\n      // For each weight, calculate the delta and update the weight.\n      for (unsigned a = 0; a < weights.shape()[1]; ++a) {\n        for (unsigned b = 0; b < weights.shape()[2]; ++b) {\n          for (unsigned c = 0; c < weights.shape()[3]; ++c) {\n            float weightDelta = 0.0f;\n            // For each item of the minibatch.\n            for (unsigned mb = 0; mb < mbSize; ++mb) {\n              // For each neuron.\n              for (unsigned x = 0; x < neurons.shape()[1]; ++x) {\n                for (unsigned y = 0; y < neurons.shape()[2]; ++y) {\n                  float i = inputs->getNeuron(x + a, y + b, c).activations[mb];\n                  weightDelta += i * neurons[fm][x][y]->errors[mb];\n                }\n              }\n            }\n            weightDelta *= learningRate / mbSize;\n            float reg = 1.0f - (learningRate * (lambda / numTrainingImages));\n            weights[fm][a][b][c] *= reg; // Regularisation term.\n            weights[fm][a][b][c] -= weightDelta;\n          }\n        }\n      }\n      // Calculate bias delta and update it.\n      float biasDelta = 0.0f;\n      // For each item of the minibatch.\n      for (unsigned mb = 0; mb < mbSize; ++mb) {\n        // For each neuron.\n        for (unsigned x = 0; x < neurons.shape()[1]; ++x) {\n          for (unsigned y = 0; y < neurons.shape()[2]; ++y) {\n            biasDelta += neurons[fm][x][y]->errors[mb];\n          }\n        }\n      }\n      biasDelta *= learningRate / mbSize;\n      bias[fm] -= biasDelta;\n    }\n  }\n\n  float getBwdError(unsigned x, unsigned y, unsigned z, unsigned mb) override {\n    return bwdErrors[mb][x][y][z];\n  }\n\n  void setInputs(Layer<mbSize> *layer) override {\n    assert(layer->size() == inputX * inputY * inputZ &&\n           \"Invalid input layer size\");\n    inputs = layer;\n    std::for_each(neurons.data(), neurons.data() + neurons.num_elements(),\n                  [layer](ConvNeuronTy *n){ n->setInputs(layer); });\n  }\n\n  void setOutputs(Layer<mbSize> *layer) override {\n    outputs = layer;\n    std::for_each(neurons.data(), neurons.data() + neurons.num_elements(),\n                  [layer](ConvNeuronTy *n){ n->setOutputs(layer); });\n  }\n\n  float getBwdError(unsigned, unsigned) override {\n    UNREACHABLE(); // No FC layers preceed conv layers.\n  }\n\n  Neuron<mbSize> &getNeuron(unsigned index) override {\n    // Map a 1D index onto the 3D neurons (for Conv <- FC connections).\n    unsigned dimX = neurons.shape()[1];\n    unsigned dimY = neurons.shape()[2];\n    unsigned x = getX(index, dimX);\n    unsigned y = getY(index, dimX, dimY);\n    unsigned z = getZ(index, dimX, dimY);\n    return *neurons[z][x][y];\n  }\n\n  Neuron<mbSize> &getNeuron(unsigned x, unsigned y, unsigned z) override {\n    // Feature maps is inner dimension but corresponds to z.\n    return *neurons[z][x][y];\n  }\n\n  unsigned getDim(unsigned i) override {\n    assert(i <= 2 && \"Dimension out of range.\");\n    // Feature maps is inner dimension but corresponds to z.\n    return i == 2 ? neurons.shape()[0] : neurons.shape()[i + 1];\n  }\n\n  unsigned getNumDims() override { return neurons.num_dimensions(); }\n  unsigned size() override { return neurons.num_elements(); }\n};\n\n///===--------------------------------------------------------------------===///\n/// Max pool layer\n///===--------------------------------------------------------------------===///\ntemplate <unsigned mbSize,\n          unsigned poolX,\n          unsigned poolY,\n          unsigned inputX,\n          unsigned inputY,\n          unsigned inputZ>\nclass MaxPoolLayer : public Layer<mbSize> {\n  Layer<mbSize> *inputs;\n  Layer<mbSize> *outputs;\n  boost::multi_array<Neuron<mbSize>*, 3> neurons; // [x][y][z]\n\npublic:\n  MaxPoolLayer() :\n      inputs(nullptr), outputs(nullptr),\n      neurons(boost::extents[inputX / poolX][inputY / poolY][inputZ]) {\n    static_assert(inputX % poolX == 0, \"Dimension x mismatch with pooling\");\n    static_assert(inputY % poolY == 0, \"Dimension y mismatch with pooling\");\n    for (unsigned x = 0; x < neurons.shape()[0]; ++x) {\n      for (unsigned y = 0; y < neurons.shape()[1]; ++y) {\n        for (unsigned z = 0; z < neurons.shape()[2]; ++z) {\n          neurons[x][y][z] = new Neuron<mbSize>(x, y, z);\n        }\n      }\n    }\n  }\n\n  void initialiseDefaultWeights(std::default_random_engine&) override {\n    /* Skip */\n  }\n\n  void feedForward(unsigned mb) override {\n    // For each neuron in this layer.\n    for (unsigned x = 0; x < neurons.shape()[0]; ++x) {\n      for (unsigned y = 0; y < neurons.shape()[1]; ++y) {\n        for (unsigned z = 0; z < neurons.shape()[2]; ++z) {\n          // Take maximum activation over pool area.\n          float weightedInput = std::numeric_limits<float>::min();\n          for (unsigned a = 0; a < poolX; ++a) {\n            for (unsigned b = 0; b < poolY; ++b) {\n              unsigned nX = (x * poolX) + a;\n              unsigned nY = (y * poolY) + b;\n              float input = inputs->getNeuron(nX, nY, z).activations[mb];\n              float max = std::max(weightedInput, input);\n              neurons[x][y][z]->activations[mb] = max;\n            }\n          }\n        }\n      }\n    }\n  }\n\n  void calcBwdError(unsigned) override { /* Skip */ }\n  void backPropogate(unsigned) override { /* Skip */ }\n\n  float getBwdError(unsigned x, unsigned y, unsigned z, unsigned mb) override {\n    // Forward the backwards error component from the next layer.\n    unsigned nX = x / poolX;\n    unsigned nY = y / poolY;\n    unsigned nZ = z;\n    unsigned dimX = neurons.shape()[0];\n    unsigned dimY = neurons.shape()[1];\n    // If next layer is 1D, map the x, y, z coordinates onto it.\n    unsigned index = getIndex(nX, nY, nZ, dimX, dimY);\n    return outputs->getNumDims() == 1\n             ? outputs->getBwdError(index, mb)\n             : outputs->getBwdError(nX, nY, nZ, mb);\n  }\n\n  void endBatch(unsigned) override { /* Skip */ }\n\n  float getBwdError(unsigned, unsigned) override {\n    UNREACHABLE(); // No FC layers preceed max-pooling layers.\n  }\n\n  void setInputs(Layer<mbSize> *layer) override {\n    assert(layer->size() == poolX * poolY * neurons.num_elements() &&\n           \"invalid input layer size\");\n    inputs = layer;\n  }\n\n  void setOutputs(Layer<mbSize> *layer) override { outputs = layer; }\n\n  Neuron<mbSize> &getNeuron(unsigned index) override {\n    // Map a 1D index onto the 3D neurons (for Conv <- FC connections).\n    unsigned dimX = neurons.shape()[0];\n    unsigned dimY = neurons.shape()[1];\n    unsigned x = getX(index, dimX);\n    unsigned y = getY(index, dimX, dimY);\n    unsigned z = getZ(index, dimX, dimY);\n    return *neurons[x][y][z];\n  }\n\n  Neuron<mbSize> &getNeuron(unsigned x, unsigned y, unsigned z) override {\n    return *neurons[x][y][z];\n  }\n\n  unsigned getNumDims() override { return neurons.num_dimensions(); }\n  unsigned getDim(unsigned i) override { return neurons.shape()[i]; }\n  unsigned size() override { return neurons.num_elements(); }\n};\n\n///===--------------------------------------------------------------------===///\n/// The network.\n///===--------------------------------------------------------------------===///\ntemplate <unsigned mbSize,\n          unsigned inputX,\n          unsigned inputY,\n          unsigned softMaxSize,\n          unsigned lastLayerSize,\n          float (*costFn)(float, float),\n          float (*costDelta)(float, float, float)>\nclass Network {\n  using SoftMaxLayerTy = SoftMaxLayer<mbSize, softMaxSize, lastLayerSize,\n                                      costFn, costDelta>;\n  using LayerTy = Layer<mbSize>;\n  Params params;\n  InputLayer<mbSize, inputX, inputY> inputLayer;\n  SoftMaxLayerTy *softMaxLayer;\n  std::vector<LayerTy*> layers;\n  std::default_random_engine generator;\n\npublic:\n  Network(Params params, std::vector<LayerTy*> layers_) :\n      params(params), layers(layers_), generator(params.seed) {\n    softMaxLayer = new SoftMaxLayerTy(params.learningRate, params.lambda);\n    layers.push_back(softMaxLayer);\n    // Set neuron inputs.\n    layers[0]->setInputs(&inputLayer);\n    layers[0]->initialiseDefaultWeights(generator);\n    for (unsigned i = 1; i < layers.size(); ++i) {\n      layers[i]->setInputs(layers[i - 1]);\n      layers[i]->initialiseDefaultWeights(generator);\n    }\n    // Set neuron outputs.\n    for (unsigned i = 0; i < layers.size() - 1; ++i) {\n      layers[i]->setOutputs(layers[i + 1]);\n    }\n  }\n\n  /// The forward pass.\n  void feedForward(unsigned mb) {\n    for (auto layer : layers) {\n      layer->feedForward(mb);\n    }\n  }\n\n  /// The backward pass.\n  void backPropogate(Image &image, uint8_t label, unsigned mb) {\n    // Set input.\n    inputLayer.setImage(image, mb);\n    // Feed forward.\n    feedForward(mb);\n    // Compute output error in last layer.\n    softMaxLayer->computeOutputError(label, mb);\n    softMaxLayer->calcBwdError(mb);\n    // Backpropagate the error and calculate component for next layer.\n    for (int i = layers.size() - 2; i > 0; --i) {\n      layers[i]->backPropogate(mb);\n      layers[i]->calcBwdError(mb);\n    }\n    layers[0]->backPropogate(mb);\n  }\n\n  void updateMiniBatch(std::vector<Image>::iterator trainingImagesIt,\n                       std::vector<uint8_t>::iterator trainingLabelsIt,\n                       unsigned numTrainingImages) {\n    // For each training image and label, back propogate.\n    // Parallelise over the elements of the minibatch to improve performance.\n    tbb::parallel_for(size_t(0), size_t(mbSize), [=](size_t i) {\n      backPropogate(*(trainingImagesIt + i), *(trainingLabelsIt + i), i);\n    });\n    // Gradient descent: for every neuron, compute the new weights and biases.\n    for (int i = layers.size() - 1; i >= 0; --i) {\n      layers[i]->endBatch(numTrainingImages);\n    }\n  }\n\n  float imageCost(Image &image, uint8_t label,\n                  unsigned numImages, float regularisation, unsigned mb) {\n    inputLayer.setImage(image, mb);\n    feedForward(mb);\n    float cost = softMaxLayer->computeOutputCost(label, mb) / numImages;\n    cost += regularisation;\n    return cost;\n  }\n\n  /// Calculate the total cost for a dataset.\n  /// Parallelise over the test images (up to the minibatch size).\n  float evaluateTotalCost(std::vector<Image> &testImages,\n                          std::vector<uint8_t> &testLabels) {\n    float regularisation = 0.5f * (params.lambda / testImages.size())\n                            * softMaxLayer->sumSquaredWeights();\n    float cost = 0.0f;\n    for (unsigned i = 0, end = testImages.size(); i < end; i += mbSize) {\n      auto mbStart = std::chrono::high_resolution_clock::now();\n      // Parallel reduce over the minibatch.\n      cost +=\n        tbb::parallel_reduce(\n          tbb::blocked_range<size_t>(0, mbSize), 0.0f,\n          [&](const tbb::blocked_range<size_t> &r, float total) {\n            for (size_t mb = r.begin(); mb < r.end(); ++mb) {\n              total += imageCost(*(testImages.begin() + i + mb),\n                                 *(testLabels.begin() + i + mb),\n                                 testImages.size(), regularisation, mb);\n            }\n            return total;\n          }, std::plus<float>());\n      auto mbEnd = std::chrono::high_resolution_clock::now();\n      auto ms =\n        std::chrono::duration_cast<std::chrono::milliseconds>(mbEnd-mbStart);\n      float imagesPerSec = (float(mbSize) / ms.count()) * 1000.0f;\n      std::cout << \"\\rEvaluate cost \" << i << \" / \" << end\n                << \" (\" << imagesPerSec << \" imgs/s)\";\n    }\n    return cost;\n  }\n\n  bool testImage(Image &image, uint8_t label, unsigned mb) {\n    inputLayer.setImage(image, mb);\n    feedForward(mb);\n    return softMaxLayer->readOutput(mb) == label;\n  }\n\n  /// Evaluate the test set and return the number of correct classifications.\n  /// Parallelise over the test images (up to the minibatch size).\n  unsigned evaluateAccuracy(std::vector<Image> &testImages,\n                            std::vector<uint8_t> &testLabels) {\n    unsigned result = 0;\n    for (unsigned i = 0, end = testImages.size(); i < end; i += mbSize) {\n      auto mbStart = std::chrono::high_resolution_clock::now();\n      // Parallel reduce over the minibatch.\n      result +=\n        tbb::parallel_reduce(\n          tbb::blocked_range<size_t>(0, mbSize), 0,\n          [&](const tbb::blocked_range<size_t> &r, unsigned total) {\n            for (size_t mb = r.begin(); mb < r.end(); ++mb) {\n              total += testImage(*(testImages.begin() + i + mb),\n                                 *(testLabels.begin() + i + mb), mb);\n            }\n            return total;\n          }, std::plus<unsigned>());\n      auto mbEnd = std::chrono::high_resolution_clock::now();\n      auto ms =\n        std::chrono::duration_cast<std::chrono::milliseconds>(mbEnd-mbStart);\n      float imagesPerSec = (float(mbSize) / ms.count()) * 1000.0f;\n      std::cout << \"\\rEvaluate accuracy \" << i << \" / \" << end\n                << \" (\" << imagesPerSec << \" imgs/s)\";\n    }\n    return result;\n  }\n\n  void SGD(Data &data) {\n    // For each epoch.\n    for (unsigned epoch = 0; epoch < params.numEpochs; ++epoch) {\n      auto epochStart = std::chrono::high_resolution_clock::now();\n      // Identically randomly shuffle the training images and labels.\n      std::uniform_int_distribution<unsigned> distribution;\n      unsigned seed = distribution.operator ()(generator);\n      std::shuffle(data.getTrainingLabels().begin(),\n                   data.getTrainingLabels().end(),\n                   std::default_random_engine(seed));\n      std::shuffle(data.getTrainingImages().begin(),\n                   data.getTrainingImages().end(),\n                   std::default_random_engine(seed));\n      // For each mini batch.\n      unsigned numTrainingImages = data.getTrainingImages().size();\n      for (unsigned i = 0; i < numTrainingImages; i += mbSize) {\n        auto mbStart = std::chrono::high_resolution_clock::now();\n        updateMiniBatch(data.getTrainingImages().begin() + i,\n                        data.getTrainingLabels().begin() + i,\n                        mbSize);\n        auto mbEnd = std::chrono::high_resolution_clock::now();\n        auto ms =\n          std::chrono::duration_cast<std::chrono::milliseconds>(mbEnd-mbStart);\n        float imagesPerSec = (float(mbSize) / ms.count()) * 1000.0f;\n        std::cout << \"\\rMinibatch \" << i << \" / \" << numTrainingImages\n                  << \" (\" << imagesPerSec << \" imgs/s)\";\n        if (i % params.monitorInterval == 0) {\n          std::cout << '\\r' << std::string(100, ' ');\n          // Evaluate the test set.\n          if (params.monitorEvaluationAccuracy) {\n            unsigned result = evaluateAccuracy(data.getValidationImages(),\n                                               data.getValidationLabels());\n            std::cout << '\\r' << std::string(100, ' ');\n            std::cout << \"\\rAccuracy on evaluation data: \"\n                      << result << \" / \" << data.getValidationImages().size()\n                      << '\\n';\n          }\n          if (params.monitorEvaluationCost) {\n            float cost = evaluateTotalCost(data.getValidationImages(),\n                                           data.getValidationLabels());\n            std::cout << '\\r' << std::string(100, ' ');\n            std::cout << \"\\rCost on evaluation data: \" << cost << \"\\n\";\n          }\n          if (params.monitorTrainingAccuracy) {\n            unsigned result = evaluateAccuracy(data.getTestImages(),\n                                               data.getTestLabels());\n            std::cout << '\\r' << std::string(100, ' ');\n            std::cout << \"\\rAccuracy on test data: \"\n                      << result << \" / \" << data.getTestImages().size()\n                      << '\\n';\n          }\n          if (params.monitorTrainingCost) {\n            float cost = evaluateTotalCost(data.getTestImages(),\n                                           data.getTestLabels());\n            std::cout << '\\r' << std::string(100, ' ');\n            std::cout << \"\\rCost on test data: \" << cost << \"\\n\";\n          }\n        }\n      }\n      std::cout << '\\n';\n      // Display end of epoch and time.\n      auto epochEnd = std::chrono::high_resolution_clock::now();\n      auto s =\n        std::chrono::duration_cast<std::chrono::seconds>(epochEnd-epochStart);\n      std::cout << \"Epoch \" << epoch << \" complete in \" << s.count() << \" s.\\n\";\n    }\n  }\n};\n\n#endif\n", "meta": {"hexsha": "3ad2f9cab1d6d17f7eb6764b2b2d64b7dcef4717", "size": 39222, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Network.hpp", "max_stars_repo_name": "jameshanlon/mnist-neural-net", "max_stars_repo_head_hexsha": "6d582ca8644d51d80f7baa1f243363b3521b6a2f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-25T02:16:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T09:53:26.000Z", "max_issues_repo_path": "Network.hpp", "max_issues_repo_name": "jameshanlon/mnist-neural-net", "max_issues_repo_head_hexsha": "6d582ca8644d51d80f7baa1f243363b3521b6a2f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Network.hpp", "max_forks_repo_name": "jameshanlon/mnist-neural-net", "max_forks_repo_head_hexsha": "6d582ca8644d51d80f7baa1f243363b3521b6a2f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1136974038, "max_line_length": 81, "alphanum_fraction": 0.583906991, "num_tokens": 10103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4323954961967681}}
{"text": "// Flatten.cpp : Defines the entry point for the console application.\n//\n#ifdef WIN32\n#define NOMINMAX\n#include <windows.h>\n#endif\n\n#if defined (__APPLE__) || defined (OSX)\n\t#include <OpenGL/gl.h>\n\t#include <GLUT/glut.h>\n#else\n\t#include <GL/gl.h>\n\t#include <GL/glut.h>\n#endif\n\n#include \"GA/c3ga.h\"\n#include \"GA/c3ga_util.h\"\n#include \"GA/gl_util.h\"\n\n#include \"primitivedraw.h\"\n#include \"gahelper.h\"\n#include \"Laplacian.h\"\n\n#include <memory>\n\n#include <vector>\n#include <map>\n#include \"numerics.h\"\n#include \"HalfEdge/Mesh.h\"\n#include \"GARotorEstimator.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/Geometry>\n\nconst char *WINDOW_TITLE = \"Interactive 3D Shape Deformation using Conformal Geometric Algebra\";\n\n// GLUT state information\nint g_viewportWidth = 800;\nint g_viewportHeight = 600;\n\nvoid display();\nvoid reshape(GLint width, GLint height);\nvoid MouseButton(int button, int state, int x, int y);\nvoid MouseMotion(int x, int y);\nvoid KeyboardUpFunc(unsigned char key, int x, int y);\nvoid SpecialFunc(int key, int x, int y);\nvoid SpecialUpFunc(int key, int x, int y);\nvoid Idle();\nvoid DestroyWindow();\n\nusing namespace c3ga;\nusing namespace std;\nusing namespace numerics;\n\nclass Camera\n{\npublic:\n\tfloat\t\tpos[3];\n\tfloat\t\tfw[3];\n\tfloat\t\tup[3];\n\tfloat\t\ttranslateVel;\n\tfloat\t\trotateVel;\n\n\tCamera()\n\t{\n\t\tfloat\t\t_pos[] = { 0, 0, -2};\n\t\tfloat\t\t_fw[] = { 0, 0, 1 };\n\t\tfloat\t\t_up[] = { 0, 1, 0 };\n\n\t\ttranslateVel = 0.005;\n\t\trotateVel = 0.005;\n\t\tmemcpy(pos, _pos, sizeof(float)*3);\n\t\tmemcpy(fw, _fw, sizeof(float)*3);\n\t\tmemcpy(up, _up, sizeof(float)*3);\n\t}\n\n\tvoid glLookAt()\n\t{\n\t\tgluLookAt( pos[0], pos[1], pos[2], fw[0],  fw[1],  fw[2], up[0],  up[1],  up[2] );\n\t}\n};\n\nclass VertexBuffer\n{\npublic:\n\tstd::vector<Eigen::Vector3d> deformedPositions; //deformed mesh positions\n\tstd::map<int,Eigen::Vector3d> constrainedPositions; //positional constraints\n\tstd::vector<Eigen::Vector3d> laplacianCoordinates; //laplacian Coordinates\n\tstd::vector<Eigen::Vector3d> normals; //for rendering (lighting)\n\tstd::vector<Eigen::Vector3d> normalsOrig; //original normals\n\tstd::vector<Eigen::Quaterniond> rotors;\n\tint size;\n\n\tVertexBuffer() : size(0)\n\t{\n\t}\n\n\tvoid resize(int size)\n\t{\n\t\tthis->size = size;\n\t\tdeformedPositions.resize(size);\n\t\tlaplacianCoordinates.resize(size);\n\t\tnormals.resize(size);\n\t\tnormalsOrig.resize(size);\n\t\trotors.resize(size);\n\t}\n\tint get_size() { return size; }\n};\n\nclass IndexBuffer{\npublic:\n\tstd::vector<int> faces;\n\tint size;\n\n\tIndexBuffer() : size(0)\n\t{\n\t}\n\n\tvoid resize(int size)\n\t{\n\t\tthis->size = size;\n\t\tfaces.resize(size);\n\t}\n\tint get_size() { return size; }\n\n};\n\nclass Handle\n{\npublic:\n\trotor R;\n\ttranslator T;\n\ttranslator Tcenter;\n\tdualSphere dS;\n\tstd::set<int> constraints;\n\n\tHandle() {\n\t\tT = _rotor(1.0);\n\t\tR = _translator(1.0);\n\t\tTcenter = _translator(1.0);\n\t}\n\tHandle(dualSphere dS)\n\t{\n\t\tnormalizedPoint x = DualSphereCenter(dS);\n\t\tTcenter = exp( -0.5*_vectorE3GA(x)*ni );\n\t\tT = _translator(1.0);\n\t\tR = _rotor(1.0);\n\t\tthis->dS = dS;\n\t}\n\n\tTRversor GetTRVersor()\n\t{\n\t\treturn _TRversor(T * _TRversor(Tcenter * R * inverse(Tcenter)));\n\t}\n};\n\nCamera g_camera;\nMesh mesh;\nvectorE3GA g_prevMousePos;\nbool g_rotateModel = false;\nbool g_rotateModelOutOfPlane = false;\nrotor g_modelRotor = _rotor(1.0);\nbool g_rotateKeyRotors = false;\nbool g_translateKeyRotors = false;\nbool g_computeBasis = false;\nfloat g_dragDistance = -1.0f;\nint g_dragObject;\nstd::shared_ptr<SparseMatrix> A;\nEigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> solver;\nint systemType = LaplaceBeltrami; //MeanValue; //LaplaceBeltrami\nbool g_showSpheres = true;\nbool g_showWires = false;\nbool g_iterateManyTimes = false;\nEigen::MatrixXd b3;\nEigen::MatrixXd xyz;\n\nVertexBuffer vertexDescriptors;\nIndexBuffer triangles;\nstd::vector<Handle> handles;\n\n\nEigen::Affine3d MotorToMatrix(const TRversor &R) {\n\tTRversor Ri = inverse(R);\n\n\t// compute images of basis vectors:\n\tc3ga::flatPoint imageOfE1NI = _flatPoint(R * c3ga::e1ni * Ri);\n\tc3ga::flatPoint imageOfE2NI = _flatPoint(R * c3ga::e2ni * Ri);\n\tc3ga::flatPoint imageOfE3NI = _flatPoint(R * c3ga::e3ni * Ri);\n\tc3ga::flatPoint imageOfNONI = _flatPoint(R * c3ga::noni * Ri);\n\n\t// create matrix representation:\n\tEigen::Affine3d M;\n\tM(0, 0) = imageOfE1NI.m_c[0];\n\tM(1, 0) = imageOfE1NI.m_c[1];\n\tM(2, 0) = imageOfE1NI.m_c[2];\n\tM(3, 0) = imageOfE1NI.m_c[3];\n\tM(0, 1) = imageOfE2NI.m_c[0];\n\tM(1, 1) = imageOfE2NI.m_c[1];\n\tM(2, 1) = imageOfE2NI.m_c[2];\n\tM(3, 1) = imageOfE2NI.m_c[3];\n\tM(0, 2) = imageOfE3NI.m_c[0];\n\tM(1, 2) = imageOfE3NI.m_c[1];\n\tM(2, 2) = imageOfE3NI.m_c[2];\n\tM(3, 2) = imageOfE3NI.m_c[3];\n\tM(0, 3) = imageOfNONI.m_c[0];\n\tM(1, 3) = imageOfNONI.m_c[1];\n\tM(2, 3) = imageOfNONI.m_c[2];\n\tM(3, 3) = imageOfNONI.m_c[3];\n\treturn M;\n}\n\n\nvoid ComputeLaplacianCoordinates(std::shared_ptr<SparseMatrix> A, Mesh* mesh, std::vector<Eigen::Vector3d>& laplacianCoordinates)\n{\n\tstd::fill(laplacianCoordinates.begin(), laplacianCoordinates.end(), Eigen::Vector3d(0,0,0));\n\n\tauto numRows = A->numRows();\n\n\tfor( int i = 0; i < numRows ; ++i)\n\t{\n\t\tSparseMatrix::RowIterator aIter = A->iterator(i);\n\t\tfor( ; !aIter.end() ; ++aIter )\n\t\t{\n\t\t\tauto j = aIter.columnIndex();\n\t\t\tlaplacianCoordinates[i] += mesh->vertexAt(j).p * aIter.value();\n\t\t}\n\t}\n}\n\nbool is_constrained(std::vector<Handle>& handles, int vertex)\n{\n\tfor(Handle& handle : handles) {\n\t\tif(handle.constraints.find(vertex) != handle.constraints.end())\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid PreFactor(std::shared_ptr<SparseMatrix> A, std::vector<Handle>& handles)\n{\n\tEigen::SparseMatrix<double> Lc = Eigen::SparseMatrix<double>(A->numRows(), A->numColumns());\n\n\tauto numRows = A->numRows();\n\tfor( int i = 0; i < numRows ; ++i)\n\t{\n\t\tif(!is_constrained(handles, i))\n\t\t{\n\t\t\tSparseMatrix::RowIterator aIter = A->iterator(i);\n\t\t\tfor( ; !aIter.end() ; ++aIter )\n\t\t\t{\n\t\t\t\tauto j = aIter.columnIndex();\n\t\t\t\tLc.insert(i, j) = (*A)(i,j);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLc.insert(i, i) = 1.0;\n\t\t}\n\t}\n\tLc.makeCompressed();\n\tsolver.compute(Lc);\n\tif(solver.info() != Eigen::Success) {\n\t\t// TODO: error handling\n\t}\n}\n\nint main(int argc, char* argv[])\n{\n\tmesh.readOBJ(\"cactus2.obj\"); //armadillo-5k-smooth.obj female.obj david.obj rabbit.obj tyra.obj horse.obj cylinder.obj bar.obj planewithpeaks.obj dragon.obj catHead.obj  cactus.obj  bunny.obj  764_hand-olivier-10kf.obj armadillo.obj\n\n\tmesh.CenterAndNormalize();\n\n\tmesh.computeNormals();\n\n\t// GLUT Window Initialization:\n\tglutInit (&argc, argv);\n\tglutInitWindowSize(g_viewportWidth, g_viewportHeight);\n\tglutInitDisplayMode( GLUT_RGB | GLUT_ALPHA | GLUT_DOUBLE | GLUT_DEPTH);\n\tglutCreateWindow(WINDOW_TITLE);\n\n\t// Register callbacks:\n\tglutDisplayFunc(display);\n\tglutReshapeFunc(reshape);\n\tglutMouseFunc(MouseButton);\n\tglutMotionFunc(MouseMotion);\n\tglutKeyboardUpFunc(KeyboardUpFunc);\n\tglutSpecialFunc(SpecialFunc);\n\tglutSpecialUpFunc(SpecialUpFunc);\n\tglutIdleFunc(Idle);\n\tatexit(DestroyWindow);\n\n\tInitializeDrawing();\n\n\t//cactus.obj\n\thandles.push_back(Handle(_dualSphere(c3gaPoint(.0, .04, 0.7) - 0.5*SQR(0.15)*ni)));\n\thandles.push_back(Handle(_dualSphere(c3gaPoint(.0, .04, -0.8) - 0.5*SQR(0.15)*ni)));\n\n\t////cylinder.obj\n\t//handles.push_back( boost::shared_ptr<Handle>( new Handle( _dualSphere(c3gaPoint(.0, 0.9,.0) - 0.5*SQR(0.25)*ni), false, P1 ) ) );\n\t//handles.push_back( boost::shared_ptr<Handle>( new Handle( _dualSphere(c3gaPoint(.0,-0.9,.0) - 0.5*SQR(0.25)*ni), true, P2 ) ) );\n\n\t//Armadillo Pie y Mano\n\t//handles.push_back( boost::shared_ptr<Handle>( new Handle( _dualSphere(c3gaPoint(-.5, 0.45,-.3) - 0.5*SQR(0.15)*ni), false, P1 ) ) );\n\t//handles.push_back( boost::shared_ptr<Handle>( new Handle( _dualSphere(c3gaPoint(.2,-0.6,.1) - 0.5*SQR(0.15)*ni), true, P2 ) ) );\n\t//Armadillo Pubis y Cabeza\n\t//handles.push_back( boost::shared_ptr<Handle>( new Handle( _dualSphere(c3gaPoint(.0, 0.4,-.2) - 0.5*SQR(0.15)*ni), false, P1 ) ) );\n\t//handles.push_back( boost::shared_ptr<Handle>( new Handle( _dualSphere(c3gaPoint(.0,-0.05,.1) - 0.5*SQR(0.15)*ni), true, P2 ) ) );\n\n\tvertexDescriptors.resize(mesh.numVertices());\n\ttriangles.resize(mesh.numFaces()*3);\n\tint n = vertexDescriptors.get_size();\n\n\tfor(Vertex& vertex : mesh.getVertices()) {\n\t\tvertexDescriptors.normalsOrig[vertex.ID] = vertex.n;\n\n\t\tnormalizedPoint position = c3gaPoint( vertex.p.x(), vertex.p.y(), vertex.p.z() );\n\n\t\tfor( Handle& handle : handles)\n\t\t{\n\t\t\tTRversor TR = handle.GetTRVersor();\n\n\t\t\tif( _double(position << (TR * handle.dS * inverse(TR))) > 0 ) //inside the sphere\n\t\t\t{\n\t\t\t\thandle.constraints.insert(vertex.ID);\n\t\t\t\tvertexDescriptors.constrainedPositions[vertex.ID] = vertex.p;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor(Face& face : mesh.getFaces()) {\n\t\tint i = face.ID;\n\t\tint\tv1 = face.edge->vertex->ID;\n\t\tint\tv2 = face.edge->next->vertex->ID;\n\t\tint\tv3 = face.edge->next->next->vertex->ID;\n\t\ttriangles.faces[i*3 + 0] = v1;\n\t\ttriangles.faces[i*3 + 1] = v2;\n\t\ttriangles.faces[i*3 + 2] = v3;\n\t}\n\n\tA = CreateLaplacianMatrix( &mesh, systemType );\n\t\n\tComputeLaplacianCoordinates(A, &mesh, vertexDescriptors.laplacianCoordinates);\n\n\tb3 = Eigen::MatrixXd(A->numRows(), 3);\n\n\tPreFactor(A, handles);\n\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nvoid SolveLinearSystem(VertexBuffer& vertexDescriptors)\n{\n\tint n = vertexDescriptors.get_size();\n\tfor( int i = 0 ; i < n ; ++i ) {\n\t\tb3.row(i) = vertexDescriptors.laplacianCoordinates[i];\n\t}\n\n\tfor( Handle& handle : handles) {\n\t\tEigen::Affine3d M = MotorToMatrix(handle.GetTRVersor());\n\t\tfor(int i : handle.constraints) {\n\t\t\tb3.row(i) = M * vertexDescriptors.constrainedPositions[i];\n\t\t}\n\t}\n\n\txyz = solver.solve(b3);\n\n\tfor( int i = 0 ; i < n ; ++i )\n\t{\n\t\tvertexDescriptors.deformedPositions[i] = xyz.row(i);\n\t\tvertexDescriptors.normals[i] = vertexDescriptors.rotors[i]._transformVector(vertexDescriptors.normalsOrig[i]);\n\t}\n}\n\nvoid UpdateLaplaciansRotation(Mesh *mesh, std::shared_ptr<SparseMatrix> A, VertexBuffer& vertexDescriptors)\n{\n\tEigen::Matrix3d m;\n\tfor( Vertex& vertex : mesh->getVertices() )\n\t{\n\t\tm.setZero();\n\t\tint i = vertex.ID;\n\t\tconst Eigen::Vector3d &pi = mesh->vertexAt(i).p;\n\t\tconst Eigen::Vector3d &tpi = vertexDescriptors.deformedPositions[i];\n\t\tdouble S = 0;\n\t\tfor(Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator() ; !edgeAroundIter.end() ; edgeAroundIter++)\n\t\t{\n\t\t\tint j = edgeAroundIter.edge_out()->pair->vertex->ID;\n\t\t\tconst Eigen::Vector3d &pj = mesh->vertexAt(j).p;\n\t\t\tconst Eigen::Vector3d &tpj = vertexDescriptors.deformedPositions[j];\n\t\t\tconst double wij = (*A)(i, j);\n\t\t\tEigen::Vector3d eij = (pj - pi);\n\t\t\tEigen::Vector3d teij = tpj - tpi;\n\t\t\tm += (wij * eij) * teij.transpose();\n\t\t\tS += eij.dot(eij) * wij;\n\t\t\tS += teij.dot(teij) * wij;\n\t\t}\n\t\tvertexDescriptors.rotors[i] = GARotorEstimator(m, S);\n\t}\n\n\tstd::fill(vertexDescriptors.laplacianCoordinates.begin(), vertexDescriptors.laplacianCoordinates.end(), Eigen::Vector3d(0,0,0));\n\tfor(Vertex& vertex : mesh->getVertices())\n\t{\n\t\tint i = vertex.ID;\n\t\tfor(Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator() ; !edgeAroundIter.end() ; edgeAroundIter++)\n\t\t{\n\t\t\tint j = edgeAroundIter.edge_out()->pair->vertex->ID;\n\t\t\tdouble wij = (*A)(i, j);\n\t\t\tEigen::Quaterniond &Ri = vertexDescriptors.rotors[i];\n\t\t\tEigen::Quaterniond &Rj = vertexDescriptors.rotors[j];\n\t\t\tEigen::Vector3d V = mesh->vertexAt(j).p - mesh->vertexAt(i).p;\n\t\t\tvertexDescriptors.laplacianCoordinates[i] += 0.5 * wij * (Ri._transformVector(V) + Rj._transformVector(V));\n\t\t}\n\t}\n}\n\nvoid display()\n{\n\t/*\n\t *\tmatrices\n\t */\n\tglViewport( 0, 0, g_viewportWidth, g_viewportHeight );\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tpickLoadMatrix();\n\tGLpick::g_frustumFar = 1000.0;\n\tGLpick::g_frustumNear = .1;\n\tgluPerspective( 60.0, (double)g_viewportWidth/(double)g_viewportHeight, GLpick::g_frustumNear, GLpick::g_frustumFar );\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\n\tglShadeModel(GL_SMOOTH);\t//gouraud shading\n\tglClearDepth(1.0f);\n\tglClearColor( .75f, .75f, .75f, .0f );\n\tglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );\n\n\t/*\n\t *\testados\n\t */\n\tglEnable(GL_CULL_FACE);\t\t//face culling\n\tglCullFace( GL_BACK );\n\tglFrontFace( GL_CCW );\n\tglEnable(GL_DEPTH_TEST);\t//z-buffer\n\tglDepthFunc(GL_LEQUAL);\n\n\t/*\n\t *\tiluminacion\n\t */\n\tfloat\t\tambient[] = { .3f, .3f, .3f, 1.f };\n\tfloat\t\tdiffuse[] = { .3f, .3f, .3f, 1.f };\n\tfloat\t\tposition[] = { .0f, 0.f, -150.f, 1.f };\n\tfloat\t\tspecular[] = { 1.f, 1.f, 1.f };\n\n\tglLightfv( GL_LIGHT0, GL_AMBIENT, ambient );\n\tglLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );\n\tglLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0);\n\tglLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.0125);\n\tglEnable(  GL_LIGHT0   );\n\tglEnable(  GL_LIGHTING );\n\tglMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, specular );\n\tglMaterialf( GL_FRONT_AND_BACK, GL_SHININESS, 50.f );\n\n\tglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n\n\tglLoadIdentity();\n\n\tg_camera.glLookAt();\n\n\tglLightfv( GL_LIGHT0, /*GL_POSITION*/GL_SPOT_DIRECTION, position );\n\tglPushMatrix();\n\n\trotorGLMult(g_modelRotor);\n\n\tif(!g_computeBasis)\n\n\t{\n\t\tstatic bool oneTime = true;\n\t\tif(oneTime || (g_rotateKeyRotors || g_translateKeyRotors))\n\t\t{\n\t\t\tif(oneTime == true)\n\t\t\t{\n\t\t\t\tSolveLinearSystem(vertexDescriptors);\n\t\t\t}\n\n\t\t\toneTime = false;\n\n\t\t\tfor(int i = 0 ; i < 10 ; ++i)\n\t\t\t{\n\t\t\t\tUpdateLaplaciansRotation(&mesh, A, vertexDescriptors);\n\t\t\t\tSolveLinearSystem(vertexDescriptors);\n\t\t\t}\n\t\t}\n\t}\n\tif(g_iterateManyTimes)\n\t{\n\t\tfor(int i = 0 ; i < 400 ; ++i)\n\t\t{\n\t\t\tUpdateLaplaciansRotation(&mesh, A, vertexDescriptors);\n\t\t\tSolveLinearSystem(vertexDescriptors);\n\t\t}\n\t\tg_iterateManyTimes = false;\n\t}\n\n\tif (GLpick::g_pickActive) glLoadName((GLuint)-1);\n\n\tdouble alpha = 1.0;\n\n\t//glEnable (GL_BLEND);\n\t//glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\t//alpha = 0.5;\n\n\t//Mesh-Faces Rendering\n\tglPolygonMode( GL_FRONT_AND_BACK, GL_FILL /*GL_LINE GL_FILL GL_POINT*/);\n\tglEnable (GL_POLYGON_OFFSET_FILL);\n\tglPolygonOffset (1., 1.);\n\tglColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);\n\tglEnable( GL_COLOR_MATERIAL );\n\tif (GLpick::g_pickActive) glLoadName((GLuint)10);\n\n\tglColor4d( 1, 1, 1, alpha );\n\tglEnableClientState(GL_NORMAL_ARRAY);\n\tglEnableClientState(GL_VERTEX_ARRAY);\n\tglVertexPointer(3, GL_DOUBLE, 0, &vertexDescriptors.deformedPositions[0]);\n\tglNormalPointer(GL_DOUBLE, 0, &vertexDescriptors.normals[0]);\n\t// draw the model\n\tglDrawElements(GL_TRIANGLES, triangles.get_size(), GL_UNSIGNED_INT, &triangles.faces[0]);\n\t// deactivate vertex arrays after drawing\n\tglDisableClientState(GL_VERTEX_ARRAY);\n\tglDisableClientState(GL_NORMAL_ARRAY);\n\n\tif(g_showWires)\n\t{\n\t\tif (!GLpick::g_pickActive)\n\t\t{\n\t\t\t//Mesh-Edges Rendering (superimposed to faces)\n\t\t\tglPolygonMode( GL_FRONT_AND_BACK, GL_LINE /*GL_LINE GL_FILL GL_POINT*/);\n\t\t\tglColor4d( .5, .5, .5, alpha );\n\t\t\tglDisable( GL_LIGHTING );\n\t\t\t\tglEnableClientState(GL_VERTEX_ARRAY);\n\t\t\t\tglVertexPointer(3, GL_DOUBLE, 0, &vertexDescriptors.deformedPositions[0]);\n\t\t\t\t// draw the model\n\t\t\t\tglDrawElements(GL_TRIANGLES, triangles.get_size(), GL_UNSIGNED_INT, &triangles.faces[0]);\n\t\t\t\t// deactivate vertex arrays after drawing\n\t\t\t\tglDisableClientState(GL_VERTEX_ARRAY);\n\t\t\tglEnable( GL_LIGHTING );\n\t\t}\n\t}\n\tglDisable( GL_COLOR_MATERIAL );\n\tglDisable(GL_POLYGON_OFFSET_FILL);\n\n\t//glDisable (GL_BLEND);\n\n\tif(g_showSpheres)\n\t{\n\t\t//Handles rendering\n\t\tglPolygonMode( GL_FRONT_AND_BACK, GL_FILL /*GL_LINE GL_FILL GL_POINT*/);\n\n\t\tfloat\tturcoise[] = { .0f, .5f, .5f, 0.3f };\n\t\tfloat\tred[] = { .5f, .0f, .0f, 0.3f };\n\n\t\tfor( int k = 0 ; k < handles.size() ; ++k)\n\t\t{\n\t\t\tif (GLpick::g_pickActive) glLoadName((GLuint)k);\n\t\t\tTRversor R = handles[k].GetTRVersor();\n\t\t\tDrawTransparentDualSphere( _dualSphere( R * handles[k].dS * inverse(R) ), turcoise );\n\t\t}\t\t\n\t}\n\n\tglPopMatrix();\n\n\tglutSwapBuffers();\n}\n\nvoid reshape(GLint width, GLint height)\n{\n\tg_viewportWidth = width;\n\tg_viewportHeight = height;\n\n\t// redraw viewport\n\tglutPostRedisplay();\n}\n\nvectorE3GA mousePosToVector(int x, int y) {\n\tx -= g_viewportWidth / 2;\n\ty -= g_viewportHeight / 2;\n\treturn _vectorE3GA((float)-x * e1 - (float)y * e2);\n}\n\nvoid MouseButton(int button, int state, int x, int y)\n{\n\tg_rotateModel = false;\n\tg_rotateKeyRotors = false;\n\tg_translateKeyRotors = false;\n\n\tif (button == GLUT_LEFT_BUTTON)\n\t{\n\t\tg_prevMousePos = mousePosToVector(x, y);\n\n\t\tGLpick::g_pickWinSize = 1;\n\t\tg_dragObject = pick(x, g_viewportHeight - y, display, &g_dragDistance);\n\n\t\tif(g_dragObject == -1 || g_dragObject == 10 )\n\t\t{\n\t\t\tvectorE3GA mousePos = mousePosToVector(x, y);\n\t\t\tg_rotateModel = true;\n\n\t\t\tif ((_Float(norm_e(mousePos)) / _Float(norm_e(g_viewportWidth * e1 + g_viewportHeight * e2))) < 0.2)\n\t\t\t\tg_rotateModelOutOfPlane = true;\n\t\t\telse g_rotateModelOutOfPlane = false;\n\t\t}\n\t\telse if(g_dragObject >= 0 && g_dragObject < handles.size())\n\t\t{\n\t\t\tg_rotateKeyRotors = true;\n\t\t}\n\t}\n\n\tif (button == GLUT_RIGHT_BUTTON)\n\t{\n\t\tg_prevMousePos = mousePosToVector(x, y);\n\n\t\tGLpick::g_pickWinSize = 1;\n\t\tg_dragObject = pick(x, g_viewportHeight - y, display, &g_dragDistance);\n\n\t\tif(g_dragObject >= 0 && g_dragObject < handles.size())\n\t\t\tg_translateKeyRotors = true;\n\t}\n}\n\nvoid MouseMotion(int x, int y)\n{\n\tif (g_rotateModel || g_rotateKeyRotors || g_translateKeyRotors )\n\t{\n\t\t// get mouse position, motion\n\t\tvectorE3GA mousePos = mousePosToVector(x, y);\n\t\tvectorE3GA motion = mousePos - g_prevMousePos;\n\n\t\tif (g_rotateModel)\n\t\t{\n\t\t\t// update rotor\n\t\t\tif (g_rotateModelOutOfPlane)\n\t\t\t\tg_modelRotor = exp(g_camera.rotateVel * (motion ^ e3) ) * g_modelRotor;\n\t\t\telse \n\t\t\t\tg_modelRotor = exp(0.00001f * (motion ^ mousePos) ) * g_modelRotor;\n\t\t}\n\t\tif(g_rotateKeyRotors)\n\t\t{\n\t\t\t//rotor R1 =  _rotor( inverse(g_modelRotor) * exp(-g_camera.rotateVel * (motion ^ e3) ) * g_modelRotor);\n\t\t\trotor R1 =  _rotor( exp(-g_camera.rotateVel * (motion ^ e3) ) );\n\t\t\tif(g_dragObject < handles.size())\n\t\t\t{\n\t\t\t\trotor R = handles[g_dragObject].R;\n\t\t\t\thandles[g_dragObject].R = normalize(_TRversor( R1 * R  ) );\n\t\t\t}\n\t\t}\n\n\t\tif(g_translateKeyRotors)\n\t\t{\n\t\t\tnormalizedTranslator T1 = _normalizedTranslator(inverse(g_modelRotor) * exp( _freeVector(-g_camera.translateVel*motion*ni) ) * g_modelRotor);\n\t\t\tif(g_dragObject < handles.size())\n\t\t\t{\n\t\t\t\ttranslator T = handles[g_dragObject].T;\n\t\t\t\thandles[g_dragObject].T = normalize(_TRversor( T1 * T ));\n\t\t\t}\n\t\t}\n\n\t\t// remember mouse pos for next motion:\n\t\tg_prevMousePos = mousePos;\n\n\t\t// redraw viewport\n\t\tglutPostRedisplay();\n\t}\n}\n\nvoid SpecialFunc(int key, int x, int y)\n{\n\tswitch(key) {\n\t\tcase GLUT_KEY_F1 :\n\t\t\t{\n\t\t\t\tint mod = glutGetModifiers();\n\t\t\t\tif(mod == GLUT_ACTIVE_CTRL || mod == GLUT_ACTIVE_SHIFT )\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GLUT_KEY_UP:\n\t\t\t{\n\t\t\t\tif(g_rotateKeyRotors)\n\t\t\t\t{\n\t\t\t\t\thandles[g_dragObject].dS = ChangeDualSphereRadiusSize(handles[g_dragObject].dS, 0.025);\n\n\t\t\t\t\t// redraw viewport\n\t\t\t\t\tglutPostRedisplay();\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GLUT_KEY_DOWN:\n\t\t\t{\n\t\t\t\tif(g_rotateKeyRotors)\n\t\t\t\t{\n\t\t\t\t\thandles[g_dragObject].dS = ChangeDualSphereRadiusSize(handles[g_dragObject].dS, -0.025);\n\n\t\t\t\t\t// redraw viewport\n\t\t\t\t\tglutPostRedisplay();\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t}\n}\n\n\nvoid SpecialUpFunc(int key, int x, int y)\n{\n}\n\nvoid KeyboardUpFunc(unsigned char key, int x, int y)\n{\n\tif(key == 'w' || key == 'W')\n\t{\n\t\tg_showWires = !g_showWires;\n\t\tglutPostRedisplay();\n\t}\n\t\n\tif( key == 'h' || key == 'H' )\n\t{\n\t\tg_showSpheres = !g_showSpheres;\n\t\tglutPostRedisplay();\n\t}\n\n\tif( key == 'x' || key == 'X' )\n\t{\n\t\tg_iterateManyTimes = true;\n\t\tglutPostRedisplay();\n\t}\n}\n\nvoid Idle()\n{\n\t// redraw viewport\n\t//glutPostRedisplay();\n}\n\nvoid DestroyWindow()\n{\n\tReleaseDrawing();\n}\n\n", "meta": {"hexsha": "42887dfc88c1d4751b63a5f822828737e1832af0", "size": 19260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Flatten/Flatten.cpp", "max_stars_repo_name": "mauriciocele/arap-svd", "max_stars_repo_head_hexsha": "bbefe4b0f18d7cd5e834b4c54e518f0d70f49565", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Flatten/Flatten.cpp", "max_issues_repo_name": "mauriciocele/arap-svd", "max_issues_repo_head_hexsha": "bbefe4b0f18d7cd5e834b4c54e518f0d70f49565", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Flatten/Flatten.cpp", "max_forks_repo_name": "mauriciocele/arap-svd", "max_forks_repo_head_hexsha": "bbefe4b0f18d7cd5e834b4c54e518f0d70f49565", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7142857143, "max_line_length": 233, "alphanum_fraction": 0.6865524403, "num_tokens": 6150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080671950640465, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4323954863034848}}
{"text": "#ifndef SHIFT_MATH_FIXED_HPP\n#define SHIFT_MATH_FIXED_HPP\n\n#include <type_traits>\n#include <boost/operators.hpp>\n#include \"shift/core/types.hpp\"\n\nnamespace shift::math\n{\ntemplate <typename K, std::size_t F>\nclass fixed;\n}\n\nnamespace std\n{\n/// Returns the squared magnitude of the scalar value (|value|^2).\ntemplate <typename K, std::size_t F>\nshift::math::fixed<K, F> norm(const shift::math::fixed<K, F>& value)\n{\n  return value * value;\n}\n\n/// Returns the magnitude of the scalar value (|value|).\ntemplate <typename K, std::size_t F>\nshift::math::fixed<K, F> abs(shift::math::fixed<K, F> value)\n{\n  value.data() = std::abs(value.data());\n  return value;\n}\n\n///\ntemplate <typename K, std::size_t F>\nshift::math::fixed<K, F> floor(shift::math::fixed<K, F> value)\n{\n  if ((value.data() & shift::math::fixed<K, F>::fractional_mask) != 0)\n  {\n    if (value.data() >= 0)\n      return shift::math::fixed<K, F>(static_cast<K>(value));\n    else\n      return shift::math::fixed<K, F>(static_cast<K>(value) - 1);\n  }\n  else\n    return value;\n}\n\n///\ntemplate <typename K, std::size_t F>\nshift::math::fixed<K, F> ceil(shift::math::fixed<K, F> value)\n{\n  if (value.data() & shift::math::fixed<K, F>::fractional_mask != 0)\n  {\n    if (value.data() >= 0)\n      return shift::math::fixed<K, F>(static_cast<K>(value) + 1);\n    else\n      return shift::math::fixed<K, F>(static_cast<K>(value));\n  }\n  else\n    return value;\n}\n\n///\ntemplate <typename K, std::size_t F>\nshift::math::fixed<K, F> round(shift::math::fixed<K, F> value)\n{\n  return shift::math::fixed<K, F>(\n    static_cast<K>(value + shift::math::fixed<K, F>::one / 2));\n}\n}\n\nnamespace shift::math\n{\n/// A fixed-point arithmetic class\ntemplate <typename K, std::size_t F>\nclass fixed : boost::operators<fixed<K, F>>, boost::shiftable<fixed<K, F>, int>\n{\npublic:\n  static_assert(std::is_integral<K>::value,\n                \"K in fixed<K, F> must be a signed integral type.\");\n\n  using storage_type = K;\n\n  static const std::size_t total_bits = sizeof(K);\n  static const std::size_t fractional_bits = F;\n  static const std::size_t fractional_mask = (1 << F) - 1;\n  static const std::size_t integer_mask = ~fractional_mask;\n  static const std::size_t integer_bits = total_bits - F;\n  static const K one = K(1) << fractional_bits;\n\n  struct direct_copy\n  {\n  };\n\npublic:\n  /// Default constructor.\n  fixed() : _number(0)\n  {\n  }\n\n  /// Copy constructor.\n  fixed(const fixed& other) : _number(other._number)\n  {\n  }\n\n  /// Copy constructor.\n  /// ToDo...\n  // template <typename K2, std::size_t F2>\n  // fixed(const fixed<K2, F2>& other) : _number(other._number)\n  //{\n  //}\n\n  /// Constructor which interprets the passed value as correctly formatted\n  /// fixed point number.\n  fixed(K value, direct_copy&) : _number(value)\n  {\n  }\n\n  /// Constructor from a signed integral type T.\n  template <typename T, ENABLE_IF(std::is_integral<T>::value)>\n  fixed(T number) : _number(static_cast<K>(number) << fractional_bits)\n  {\n  }\n\n  /// Constructor from a floating-point type.\n  template <typename T, ENABLE_IF(std::is_floating_point<T>::value)>\n  fixed(T number) : _number(static_cast<K>(one * number))\n  {\n  }\n\n  /// Conversion operator to signed integral type T.\n  template <typename T, ENABLE_IF(std::is_integral<T>::value)>\n  operator T() const\n  {\n    static_assert(sizeof(T) * 8 >= sizeof(K) * 8 - fractional_bits,\n                  \"Cannot convert fixed-point number to type T because of \"\n                  \"possible loss of data.\");\n    return static_cast<T>(_number >> fractional_bits);\n  }\n\n  /// Conversion operator to floating-point type T.\n  template <typename T, ENABLE_IF(std::is_floating_point<T>::value)>\n  operator T() const\n  {\n    return static_cast<T>(_number) / (1 << fractional_bits);\n  }\n\n  /// Returns a reference to the internal number store.\n  storage_type& data()\n  {\n    return _number;\n  }\n\n  /// Assignment operator.\n  fixed& operator=(const fixed& other)\n  {\n    _number = other._number;\n    return *this;\n  }\n\n  ///\n  bool operator==(const fixed& other) const\n  {\n    return _number == other._number;\n  }\n\n  ///\n  bool operator<(const fixed& other) const\n  {\n    return _number < other._number;\n  }\n\n  ///\n  bool operator!() const\n  {\n    return !_number;\n  }\n\n  ///\n  fixed operator~() const\n  {\n    return fixed(~_number, direct_copy());\n  }\n\n  ///\n  fixed operator-() const\n  {\n    return fixed(-t._number, direct_copy());\n  }\n\n  ///\n  fixed& operator++()\n  {\n    _number += one;\n    return *this;\n  }\n\n  ///\n  fixed& operator--()\n  {\n    _number -= one;\n    return *this;\n  }\n\n  ///\n  fixed& operator+=(const fixed& other)\n  {\n    _number += other._number;\n    return *this;\n  }\n\n  ///\n  fixed& operator-=(const fixed& other)\n  {\n    _number -= other._number;\n    return *this;\n  }\n\n  ///\n  fixed& operator&=(const fixed& other)\n  {\n    _number &= other._number;\n    return *this;\n  }\n\n  ///\n  fixed& operator|=(const fixed& other)\n  {\n    _number |= other._number;\n    return *this;\n  }\n\n  ///\n  fixed& operator^=(const fixed& other)\n  {\n    _number ^= other._number;\n    return *this;\n  }\n\n  ///\n  fixed& operator>>=(const int& other)\n  {\n    _number >>= other;\n    return *this;\n  }\n\n  ///\n  fixed& operator<<=(const int& other)\n  {\n    _number <<= other;\n    return *this;\n  }\n\n  ///\n  fixed& operator>>=(const fixed& other)\n  {\n    _number >>= static_cast<K>(other);\n    return *this;\n  }\n\n  ///\n  fixed& operator<<=(const fixed& other)\n  {\n    _number <<= static_cast<K>(other);\n    return *this;\n  }\n\nprivate:\n  storage_type _number;\n};\n}\n\n#endif\n", "meta": {"hexsha": "826db05f56bdd876fe213f1f049fb31535fa2478", "size": 5526, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "shift/math/public/shift/math/fixed.hpp", "max_stars_repo_name": "cspanier/shift", "max_stars_repo_head_hexsha": "5b3b9be310155fbc57d165d06259b723a5728828", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-11-28T18:14:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-06T07:44:36.000Z", "max_issues_repo_path": "shift/math/public/shift/math/fixed.hpp", "max_issues_repo_name": "cspanier/shift", "max_issues_repo_head_hexsha": "5b3b9be310155fbc57d165d06259b723a5728828", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-06T21:01:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-19T07:52:52.000Z", "max_forks_repo_path": "shift/math/public/shift/math/fixed.hpp", "max_forks_repo_name": "cspanier/shift", "max_forks_repo_head_hexsha": "5b3b9be310155fbc57d165d06259b723a5728828", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3161764706, "max_line_length": 79, "alphanum_fraction": 0.6207021354, "num_tokens": 1529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.43235884252778156}}
{"text": "/// General Matrix Multiplication\n#include <HElib/FHE.h>\n#include <HElib/FHEContext.h>\n#include <HElib/EncryptedArray.h>\n#include <HElib/NumbTh.h>\n\n#include \"SMP/DoublePacking.hpp\"\n#include \"SMP/Matrix.hpp\"\n#include \"SMP/Timer.hpp\"\n#include <boost/asio.hpp>\n#include <boost/asio/ip/tcp.hpp>\n#include <iostream>\n#include <numeric>\n#include <list>\nusing boost::asio::ip::tcp;\nstatic void print_time(std::string const& doc, Duration_t const& dur) {\n    std::cout << doc << \" \" << time_as_millsecond(dur) << std::endl;\n}\n\ninline long round_div(long a, long b) {\n    return (a + b - 1) / b;\n}\n\nvoid zero(Matrix &mat) {\n    for (long i = 0; i < mat.NumRows(); i++)\n        for (long j = 0; j < mat.NumCols(); j++)\n            mat[i][j] = 0;\n}\n\nvoid randomize(Matrix &mat) {\n    for (long i = 0; i < mat.NumRows(); i++)\n        for (long j = 0; j < mat.NumCols(); j++)\n            mat[i][j] = NTL::RandomBnd(2L);\n}\n\nvoid mod_to_plain(Matrix &mat, long prime) {\n    for (long i = 0; i < mat.NumRows(); i++)\n        for (long j = 0; j < mat.NumCols(); j++)\n            mat[i][j] %= prime;\n}\n\nstruct Duplication {\n    long blk_id;\n    long dup;\n    long slots_left;\n};\n\nDuplication compute_duplications(const long total_rows, \n                                 const long x_blk_id, \n                                 const long num_slots) {\n    long N = std::min((x_blk_id  + 1) * num_slots, total_rows) - x_blk_id * num_slots;\n    Duplication d;\n    d.blk_id = x_blk_id;\n    d.dup = num_slots / N;\n    d.slots_left = num_slots - d.dup * N;\n    return d;\n}\n\nstd::vector<long> compute_rotations(long x_blk, long total_rows_X,\n                                    long y_blk, long total_rows_Y,\n                                    long num_slots) {\n    auto dupA = compute_duplications(total_rows_X, x_blk, num_slots);\n    auto dupB = compute_duplications(total_rows_Y, y_blk, num_slots);\n    std::vector<long> rotations;\n    long sze;\n    // fully packed\n    if (dupA.dup == 1 and dupB.dup == 1) {\n        sze = num_slots;\n    } else if (dupA.slots_left != 0 or dupB.slots_left != 0) {\n        // cumble to implement, so just skip this case\n        std::cout << \"cumble\\n\" << std::endl;\n        sze = num_slots;\n    } else {\n        long NA = (num_slots - dupA.slots_left) / dupA.dup;\n        long NB = (num_slots - dupB.slots_left) / dupB.dup;\n        sze = std::max(NA, NB) / (dupA.dup * dupB.dup);\n        sze = std::max(1L, sze);\n    }\n    rotations.resize(sze);\n    std::iota(rotations.begin(), rotations.end(), 0);\n    return rotations;\n}\n\nvoid fill_compute(Matrix& mat, \n                  int x, int y, int k,\n                  const std::vector<NTL::zz_pX> &slots,\n                  const EncryptedArray *ea) {\n    const long l = ea->size();\n    const long d = ea->getDegree();\n    long row_start = x * l;\n    long row_end = row_start + l;\n    long col_start = y * l;\n    long col_end = col_start + l;\n\n    assert(slots.size() == l);\n    for (long ll = 0; ll < l; ll++) {\n        long computed = NTL::coeff(slots[ll], d - 1)._zz_p__rep;\n        long row = row_start + ll;\n        long col = col_start + ll + k;\n        if (col >= col_end)\n            col = col_start + col % l;\n        mat.put(row, col, computed);\n    }\n}\n\nlong ceil_round(long a, long l) {\n    return (a + l - 1) / l * l;\n}\n\nFHEcontext receive_context(std::istream &s) {\n    unsigned long m, p, r;\n    std::vector<long> gens, ords;\n    readContextBase(s, m, p, r, gens, ords);\n    FHEcontext context(m, p, r, gens, ords);\n    s >> context;\n    return context;\n}\n\nvoid send_context(std::ostream &s, FHEcontext const& context) {\n    writeContextBase(s, context);\n    s << context;\n}\n\nvoid play_client(tcp::iostream &conn, \n                 FHESecKey &sk, \n                 FHEcontext &context,\n                 const long n1,\n                 const long n2,\n                 const long n3) {\n    FHEPubKey ek(sk);\n    ek.makeSymmetric();\n    conn << ek;\n    const EncryptedArray *ea = context.ea;\n    const long l = ea->size();\n    const long d = ea->getDegree();\n\n    NTL::SetSeed(NTL::to_ZZ(123));\n    Matrix A, B, ground_truth;\n    A.SetDims(n1, n2);\n    B.SetDims(n2, n3);\n    randomize(A);\n    randomize(B);\n    ground_truth = mul(A, B);\n    mod_to_plain(ground_truth, context.alMod.getPPowR());\n    /// print grouth truth for debugging\n    // save_matrix(std::cout, ground_truth);\n    const long MAX_X1 = round_div(A.NumRows(), l);\n    const long MAX_Y1 = round_div(A.NumCols(), d);\n    const long MAX_X2 = round_div(B.NumCols(), l);\n\n    std::vector<std::vector<Ctxt>> uploading; \n    uploading.resize(MAX_X1, std::vector<Ctxt>(MAX_Y1, sk));\n    auto start_time = Clock::now();\n    /// encrypt matrix \n    for (int x = 0; x < MAX_X1; x++) {\n        for (int k = 0; k < MAX_Y1; k++) {\n            internal::BlockId blk = {x, k};\n            auto packed_rows = internal::partition(A, blk, *ea, false);\n            //ea->skEncrypt(uploading[x][k], sk, packed_rows.polys);\n        }\n    }\n    auto end_time = Clock::now();\n    print_time(\"encryption\", end_time - start_time);\n\n    /// send ciphertexts of matrix \n    start_time = Clock::now();\n    for (auto const& row : uploading) {\n        for (auto const& ctx : row)\n            conn << ctx;\n    }\n    std::cout << MAX_X1 * MAX_Y1 << \" ciphertexts sent\" << std::endl;\n    end_time = Clock::now();\n    print_time(\"client->server\", end_time - start_time);\n\n    /// waiting results\n    long rows_of_A = A.NumRows();\n    long rows_of_Bt = B.NumCols(); // Bt::Rows = B::Cols\n    std::list<Ctxt> ret_ctxs;\n    for (int x = 0; x < MAX_X1; x++) {\n        for (int y = 0; y < MAX_X2; y++) {\n            size_t num_rots = compute_rotations(x, rows_of_A, \n                                                y, rows_of_Bt, l).size();\n            for (size_t k = 0; k < num_rots; k++) {\n                Ctxt result(sk);\n                conn >> result;\n                ret_ctxs.emplace_back(result);\n            }\n        }\n    }\n    /// decrypt\n    Matrix computed;\n    computed.SetDims(A.NumRows(), B.NumCols());\n    zero(computed);\n    int x = 0;\n    int y = 0;\n    auto itr = ret_ctxs.begin();\n    std::vector<NTL::zz_pX> slots;\n    start_time = Clock::now();\n    for (int x = 0; x < MAX_X1; x++) {\n        for (int y = 0; y < MAX_X2; y++) {\n            size_t num_rots  = compute_rotations(x, rows_of_A, \n                                                 y, rows_of_Bt, l).size();\n            for (size_t k = 0; k < num_rots; k++) {\n                //ea->decrypt(*itr++, sk, slots); \n                fill_compute(computed, x, y, k, slots, ea);\n            }\n        }\n    }\n    end_time = Clock::now();\n    print_time(\"decryption\", end_time - start_time);\n    if (!::is_same(ground_truth, computed)) \n        std::cerr << \"The computation seems wrong \" << std::endl;\n    else \n        std::cout << \"passed\" << std::endl;\n}\n\nvoid my_encode(EncryptedArray const& ea, \n               zzX &ret,\n               std::vector<NTL::zz_pX> &slots) {\n    auto const& encoder = ea.getContext().alMod.getDerived(PA_zz_p());\n    NTL::zz_pX tmp;\n    encoder.CRT_reconstruct(tmp, slots);\n    // NTL::conv(ret, tmp);\n}\n\nvoid play_server(tcp::iostream &conn, \n                 const long n1,\n                 const long n2,\n                 const long n3) {\n    auto context = receive_context(conn);\n    const EncryptedArray *ea = context.ea;\n    const long l = ea->size();\n    const long d = ea->getDegree();\n    FHEPubKey ek(context);\n    conn >> ek;\n    NTL::SetSeed(NTL::to_ZZ(123));\n\n    Matrix A, B;\n    A.SetDims(n1, n2);\n    B.SetDims(n2, n3);\n    randomize(A);\n    randomize(B);\n\n    const long MAX_X1 = round_div(A.NumRows(), l);\n    const long MAX_Y1 = round_div(A.NumCols(), d);\n    Matrix Bt;\n    transpose(&Bt, B);\n    const long MAX_X2 = round_div(Bt.NumRows(), l);\n    const long MAX_Y2 = round_div(Bt.NumCols(), d);\n    auto start_time = Clock::now();\n    std::vector<std::vector<NewPlaintextArray>> precomputed;\n    precomputed.resize(MAX_X2, std::vector<NewPlaintextArray>(MAX_Y1, *ea));\n    for (int y = 0; y < MAX_X2; y++) {\n        for (int k = 0; k < MAX_Y1; k++) {\n            internal::BlockId blk = {y, k};\n            auto packed_rows = internal::partition(Bt, blk, *ea, true);\n            encode(*ea, precomputed[y][k], packed_rows.polys);\n        }\n    }\n    auto end_time = Clock::now();\n    print_time(\"precomputation\", end_time - start_time);\n\n    /// receving ciphertexts from the client \n    std::vector<std::vector<Ctxt>> received; \n    received.resize(MAX_X1, std::vector<Ctxt>(MAX_Y1, ek));\n    for (int x = 0; x < MAX_X1; x++) {\n        for (int k = 0; k < MAX_Y1; k++)\n            conn >> received[x][k];\n    }\n\n    /// compute the matrix mulitplication\n    long rows_of_A = A.NumRows();\n    long rows_of_Bt = Bt.NumRows();\n    size_t send_ctx = 0;\n    zzX packed_polys;\n    Duration_t computation(0), network(0);\n    for (int x = 0; x < MAX_X1; x++) {\n        for (int y = 0; y < MAX_X2; y++) {\n            start_time = Clock::now();\n            std::vector<long> rotations = compute_rotations(x, rows_of_A, \n                                                            y, rows_of_Bt, l);\n            size_t num_rotations = rotations.size();\n            std::vector<Ctxt> summations(num_rotations, ek);\n            for (int k = 0; k < MAX_Y1; k++) {\n                for (size_t rot = 0; rot < num_rotations; rot++) {\n                    auto rotated(precomputed[y][k]);\n                    rotate(*ea, rotated, -rotations[rot]);\n                    /// pack the polys into one poly\n                    //my_encode(*ea, packed_polys, rotated.getData());\n                    Ctxt client_ctx(received[x][k]);\n                    /// ctx * plain\n                    client_ctx.multByConstant(packed_polys);\n                    summations[rot] += client_ctx;\n                }\n            }\n            for (auto &sm : summations) \n                sm.modDownToLevel(1);\n            end_time = Clock::now();\n            computation += (end_time - start_time);\n\n            start_time = Clock::now();\n            for (auto const&sm : summations) \n                conn << sm;\n            end_time = Clock::now();\n            network += (end_time - start_time);\n            send_ctx += summations.size();\n        }\n    }\n    print_time(\"computation\", computation);\n    print_time(\"server->client\", network);\n    std::cout << \"Sent \" << send_ctx << \" ciphertexts\" << std::endl;\n}\n\nint run_client(long n1, long n2, long n3) {\n    tcp::iostream conn(\"127.0.0.1\", \"12345\");\n    if (!conn) {\n        std::cerr << \"Can not connect to server!\" << std::endl;\n        return -1;\n    }\n    const long m = 8192;\n    //const long p = 641;\n    const long p = 3329;\n    const long r = 1;\n    const long L = 3;\n    FHEcontext context(m, p, r);\n    context.bitsPerLevel = 14 + std::ceil(std::log(m)/2 + r* std::log(p));\n    buildModChain(context, L);\n    std::cout << \"kappa = \" << context.securityLevel() << std::endl;\n    FHESecKey sk(context);\n    sk.GenSecKey(64);\n    /// send FHEcontext obj\n    send_context(conn, context);\n    /// send the evaluation key\n    play_client(conn, sk, context, n1, n2, n3);\n    conn.close();\n    return 1;\n}\n\nint run_server(long n1, long n2, long n3) {\n    boost::asio::io_service ios;\n    tcp::endpoint endpoint(tcp::v4(), 12345);\n    tcp::acceptor acceptor(ios, endpoint);\n\n    for (;;) {\n        tcp::iostream conn;\n        boost::system::error_code err;\n        acceptor.accept(*conn.rdbuf(), err);\n        if (!err) {\n            std::cout << \"Connected!\" << std::endl;\n            play_server(conn, n1, n2, n3);\n            break;\n        }\n    }  \n}\n\nint main(int argc, char *argv[]) {\n    ArgMapping argmap;\n    long role;\n    long n1 = 8; \n    long n2 = 8; \n    long n3 = 8;\n    argmap.arg(\"N\", n1, \"n1\");\n    argmap.arg(\"M\", n2, \"n2\");\n    argmap.arg(\"D\", n3, \"n3\");\n    argmap.arg(\"R\", role, \"role\");\n    argmap.parse(argc, argv);\n    if (role == 0) {\n        return run_server(n1, n2, n3);\n    } else if (role == 1) {\n        return run_client(n1, n2, n3);\n    }\n}\n", "meta": {"hexsha": "281b42fa2a62c58b201f806fe9043f67f22cb5d8", "size": 12012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_GMM.cpp", "max_stars_repo_name": "Vampsj/SMP", "max_stars_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_GMM.cpp", "max_issues_repo_name": "Vampsj/SMP", "max_issues_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_GMM.cpp", "max_forks_repo_name": "Vampsj/SMP", "max_forks_repo_head_hexsha": "ec332ed29bc33685d050478090e0a679ddef0e4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2037533512, "max_line_length": 86, "alphanum_fraction": 0.5427072927, "num_tokens": 3436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802476562641, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.43235884252778156}}
{"text": "#include <cstdlib>\n#include <iostream>\n\n#include <boost/units/systems/si/electric_potential.hpp>\n#include <boost/units/systems/si/current.hpp>\n#include <boost/units/systems/si/resistance.hpp>\n#include <boost/units/systems/si/io.hpp>\n\nint main()\n{\n    using namespace boost::units;\n    using namespace boost::units::si;\n\n    quantity<current> I = 5 * amperes;\n    quantity<resistance> R = 10 * ohms;\n\n    std::cout << \"I = \" << I << std::endl;\n    std::cout << \"R = \" << R << std::endl;\n    std::cout << \"U = I * R = \" << I * R << std::endl;\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "1eed3f7fea3bf207eaea349a87fdf1f5e86af0c1", "size": 568, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_package/test_package.cpp", "max_stars_repo_name": "bincrafters/conan-boost_units", "max_stars_repo_head_hexsha": "c371863785ae5b86b3d88fe4accb981655030b28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test_package/test_package.cpp", "max_issues_repo_name": "bincrafters/conan-boost_units", "max_issues_repo_head_hexsha": "c371863785ae5b86b3d88fe4accb981655030b28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_package/test_package.cpp", "max_forks_repo_name": "bincrafters/conan-boost_units", "max_forks_repo_head_hexsha": "c371863785ae5b86b3d88fe4accb981655030b28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8181818182, "max_line_length": 56, "alphanum_fraction": 0.6285211268, "num_tokens": 168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.769080247656264, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4323588425277815}}
{"text": "#include <cstdio>\n#include <string>\n#include <cstdlib>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <Eigen/Dense>\n#include <vector>\n\n#include \"global.h\"\n#include \"DimRed.h\"\n#include \"DFE.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nusing std::ifstream;\nusing std::string;\n\nvoid process_cmdline(char *argv[], char **train_file, char **test_file, char **option_file, char **label_train_file,\n\tchar **train_red_file, char **test_red_file, char **tsf_file) {\n\t\n\t*train_file\t= argv[1];\n\t*test_file\t= argv[2];\n\t*option_file\t= argv[3];\n\t*label_train_file = argv[4];\n\t*train_red_file\t= argv[5];\n\t*test_red_file\t= argv[6];\n    *tsf_file = argv[7];\n}\n\nvoid process_cmdline_dev(char *argv[], char **train_file, char **dev_file, char **test_file, char **option_file, char **label_train_file, char **label_dev_file,\n\tchar **train_red_file, char **dev_red_file, char **test_red_file, char **tsf_file) {\n\t\n\t*train_file\t= argv[1];\n\t*dev_file = argv[2];\n\t*test_file\t= argv[3];\n    *option_file\t= argv[4];\n\t*label_train_file = argv[5];\n\t*label_dev_file = argv[6];\n\t*train_red_file\t= argv[7];\n\t*dev_red_file = argv[8];\n\t*test_red_file = argv[9];\n    *tsf_file = argv[10];\n}\n\n\nint main(int argc, char *argv[]){\n\n\tchar *train_file, *dev_file, *test_file, *option_file, *label_train_file, *label_dev_file, *train_red_file, *dev_red_file, *test_red_file, *tsf_file;\n\tif (argc==8) {\n\t\tprocess_cmdline(argv, &train_file, &test_file, &option_file, &label_train_file, &train_red_file, &test_red_file, &tsf_file);\n\t} else if (argc==11)  {\t// use dev dataset\n\t\tprocess_cmdline_dev(argv, &train_file, &dev_file, &test_file, &option_file, &label_train_file, &label_dev_file, &train_red_file, &dev_red_file, &test_red_file, &tsf_file);\n\t} else {\n\t\tcout<<\"Command line error!\"<<endl;\n\t}\n\n\tDataReader data_input(option_file);\n\tdata_input.SetParameters();\n    data_input.ReadData(train_file, test_file, label_train_file);\n    if (use_dev==1) {data_input.ReadDevData(dev_file, label_dev_file);}\n\n\tDimRed *dim_red;\n    dim_red = new DFE();\n    dim_red->setParameters();\n    dim_red->setTrainData(num_train, num_dim, &data_input, data_input.getLabTrain());\n    if (use_dev==1) {dim_red->setDevData(num_dev, num_dim, &data_input, data_input.getLabDev());}\n    dim_red->setTestData(num_test, num_dim, &data_input);\n    dim_red->PerformTrainProcess();\n\t\n    // remove data saved in DataReader\n    data_input.RemoveData();\n    \n    cout<<\"Finding \"<<num_tsf_dim<<\" tsf dimensions\"<<endl;\n    MatrixXd tsf_mat;\n    for (int i=0; i<num_tsf_dim; i++) {\n    \tcout<<\"tsf_dim: \"<<i<<endl;\n    \tif (i==0) {\n    \t\tdim_red->PerformTrain();\n            tsf_mat = dim_red->getTsf();\n    \t} else {\n\t\t\tdim_red->setTsfOld(tsf_mat);\n\t\t\tdim_red->PerformTrain();\n            MatrixXd tsf_mat_new = dim_red->getTsf();\n            MatrixXd tsf_mat_old = dim_red->getTsfOld();\n            MatrixXd tsf_mat_tmp(tsf_mat_old.rows(), tsf_mat_old.cols()+tsf_mat_new.cols());\n            tsf_mat_tmp.block(0,0, tsf_mat_old.rows(), tsf_mat_old.cols()) = tsf_mat_old;\n            tsf_mat_tmp.block(0, tsf_mat_old.cols(), tsf_mat_new.rows(), tsf_mat_new.cols()) = tsf_mat_new;\n            tsf_mat = tsf_mat_tmp;\n    \t}\n    \t\n    \t// output the tsf matrix\n\t\tcout<<tsf_mat.rows()<<\" \"<<tsf_mat.cols()<<endl;\n\t\tofstream write_tsf_mat(tsf_file, ios_base::trunc);\n\t\tfor (int i=0; i<tsf_mat.rows(); i++) {\n\t\t    for (int j=0; j<tsf_mat.cols(); j++) {\n\t\t        write_tsf_mat<<tsf_mat(i,j)<<\" \";\n\t\t    }\n\t\t    write_tsf_mat<<\"\\n\";\n\t\t}\n\t\twrite_tsf_mat.close();\n    }\n    \n    // perform dev and test reduction\n    if (use_dev==1) {dim_red->PerformDev();}\n    dim_red->PerformTest();\n\n\tMatrixXd train_data_red=dim_red->getTrainRed();\n\tMatrixXd dev_data_red;\n\tif (use_dev==1) {dev_data_red=dim_red->getDevRed();}\n\tMatrixXd test_data_red=dim_red->getTestRed();\n\n    ofstream write_result(train_red_file, ios_base::trunc);\n    for (int i=0; i<train_data_red.rows(); i++) {\n        for (int j=0; j<train_data_red.cols(); j++) {\n            write_result<<train_data_red(i,j)<<\" \";\n        }\n        write_result<<\"\\n\";\n    }\n    write_result.close();\n\n\tif (use_dev==1) {\n\t\tofstream write_dev_result(dev_red_file, ios_base::trunc);\n\t\tfor (int i=0; i<dev_data_red.rows(); i++) {\n\t\t    for (int j=0; j<dev_data_red.cols(); j++) {\n\t\t        write_dev_result<<dev_data_red(i,j)<<\" \";\n\t\t    }\n\t\t    write_dev_result<<\"\\n\";\n\t\t}\n\t\twrite_dev_result.close();\n    }\n\n    cout<<test_data_red.rows()<<\" \"<<test_data_red.cols()<<endl;\n    ofstream write_test_result(test_red_file, ios_base::trunc);\n    for (int i=0; i<test_data_red.rows(); i++) {\n        for (int j=0; j<test_data_red.cols(); j++) {\n            write_test_result<<test_data_red(i,j)<<\" \";\n        }\n        write_test_result<<\"\\n\";\n    }\n    write_test_result.close();\n    \n    delete dim_red;\n\n\texit(0);\n}\n", "meta": {"hexsha": "c4c621975e93f3ce7dfc682d0e153871f05c098b", "size": 4800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "shuai-huang/DR-MIM", "max_stars_repo_head_hexsha": "5e0948852cc04e35c6fd4e1cb677fc5e55f378be", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "shuai-huang/DR-MIM", "max_issues_repo_head_hexsha": "5e0948852cc04e35c6fd4e1cb677fc5e55f378be", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "shuai-huang/DR-MIM", "max_forks_repo_head_hexsha": "5e0948852cc04e35c6fd4e1cb677fc5e55f378be", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4324324324, "max_line_length": 173, "alphanum_fraction": 0.6558333333, "num_tokens": 1424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4323588306259023}}
{"text": "// Copyright (C) 2016-2018 T. Zachary Laine\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. (See\r\n// accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//[ calc3\r\n#include <boost/yap/expression.hpp>\r\n\r\n#include <boost/hana/maximum.hpp>\r\n\r\n#include <iostream>\r\n\r\n\r\n// Look! A transform!  This one transforms the expression tree into the arity\r\n// of the expression, based on its placeholders.\r\n//[ calc3_get_arity_xform\r\nstruct get_arity\r\n{\r\n    // Base case 1: Match a placeholder terminal, and return its arity as the\r\n    // result.\r\n    template <long long I>\r\n    boost::hana::llong<I> operator() (boost::yap::expr_tag<boost::yap::expr_kind::terminal>,\r\n                                      boost::yap::placeholder<I>)\r\n    { return boost::hana::llong_c<I>; }\r\n\r\n    // Base case 2: Match any other terminal.  Return 0; non-placeholders do\r\n    // not contribute to arity.\r\n    template <typename T>\r\n    auto operator() (boost::yap::expr_tag<boost::yap::expr_kind::terminal>, T &&)\r\n    {\r\n        using namespace boost::hana::literals;\r\n        return 0_c;\r\n    }\r\n\r\n    // Recursive case: Match any expression not covered above, and return the\r\n    // maximum of its children's arities.\r\n    template <boost::yap::expr_kind Kind, typename... Arg>\r\n    auto operator() (boost::yap::expr_tag<Kind>, Arg &&... arg)\r\n    {\r\n        return boost::hana::maximum(\r\n            boost::hana::make_tuple(\r\n                boost::yap::transform(\r\n                    boost::yap::as_expr(std::forward<Arg>(arg)),\r\n                    get_arity{}\r\n                )...\r\n            )\r\n        );\r\n    }\r\n};\r\n//]\r\n\r\nint main ()\r\n{\r\n    using namespace boost::yap::literals;\r\n\r\n    // These lambdas wrap our expressions as callables, and allow us to check\r\n    // the arity of each as we call it.\r\n\r\n    auto expr_1 = 1_p + 2.0;\r\n\r\n    auto expr_1_fn = [expr_1](auto &&... args) {\r\n        auto const arity = boost::yap::transform(expr_1, get_arity{});\r\n        static_assert(arity.value == sizeof...(args), \"Called with wrong number of args.\");\r\n        return evaluate(expr_1, args...);\r\n    };\r\n\r\n    auto expr_2 = 1_p * 2_p;\r\n\r\n    auto expr_2_fn = [expr_2](auto &&... args) {\r\n        auto const arity = boost::yap::transform(expr_2, get_arity{});\r\n        static_assert(arity.value == sizeof...(args), \"Called with wrong number of args.\");\r\n        return evaluate(expr_2, args...);\r\n    };\r\n\r\n    auto expr_3 = (1_p - 2_p) / 2_p;\r\n\r\n    auto expr_3_fn = [expr_3](auto &&... args) {\r\n        auto const arity = boost::yap::transform(expr_3, get_arity{});\r\n        static_assert(arity.value == sizeof...(args), \"Called with wrong number of args.\");\r\n        return evaluate(expr_3, args...);\r\n    };\r\n\r\n    // Displays \"5\"\r\n    std::cout << expr_1_fn(3.0) << std::endl;\r\n\r\n    // Displays \"6\"\r\n    std::cout << expr_2_fn(3.0, 2.0) << std::endl;\r\n\r\n    // Displays \"0.5\"\r\n    std::cout << expr_3_fn(3.0, 2.0) << std::endl;\r\n\r\n    // Static-asserts with \"Called with wrong number of args.\"\r\n    //std::cout << expr_3_fn(3.0) << std::endl;\r\n\r\n    // Static-asserts with \"Called with wrong number of args.\"\r\n    //std::cout << expr_3_fn(3.0, 2.0, 1.0) << std::endl;\r\n\r\n    return 0;\r\n}\r\n//]\r\n", "meta": {"hexsha": "47c5e0431b9f1cc13ffee73de72477fb61be4979", "size": 3242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/yap/example/calc3.cpp", "max_stars_repo_name": "Talustus/boost_src", "max_stars_repo_head_hexsha": "ffe074de008f6e8c46ae1f431399cf932164287f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "third_party/boost/libs/yap/example/calc3.cpp", "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "third_party/boost/libs/yap/example/calc3.cpp", "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 32.099009901, "max_line_length": 93, "alphanum_fraction": 0.5814312153, "num_tokens": 889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.432349226720785}}
{"text": "/*                         P L A N E . C\n * BRL-CAD\n *\n * Copyright (c) 2004-2021 United States Government as represented by\n * the U.S. Army Research Laboratory.\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this file; see the file named COPYING for more\n * information.\n */\n/** @addtogroup plane */\n/** @{ */\n/** @file libbn/plane.c\n *\n * @brief\n * Some useful routines for dealing with planes and lines.\n *\n */\n\n#include \"common.h\"\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <math.h>\n\n#include <Eigen/SVD>\n\n#include \"bu/debug.h\"\n#include \"bu/log.h\"\n#include \"vmath.h\"\n#include \"bn/mat.h\"\n#include \"bn/plane.h\"\n#include \"bn/tol.h\"\n\n#define UNIT_SQ_TOL 1.0e-13\n\n#if defined(HAVE_NEXTAFTER) && !defined(HAVE_DECL_NEXTAFTER) && !defined(__cplusplus)\nextern double nextafter(double x, double y);\n#endif\n#if defined(HAVE_NEXTAFTERF) && !defined(HAVE_DECL_NEXTAFTERF) && !defined(__cplusplus)\nextern float nextafterf(float x, float y);\n#endif\n#if defined(HAVE_MODFF) && !defined(HAVE_DECL_MODFF) && !defined(__cplusplus)\nextern float modff(float x, float *iptr);\n#endif\n\ndouble\nbn_dist_pnt3_pnt3(const fastf_t *a, const fastf_t *b)\n{\n    vect_t diff;\n\n    VSUB2(diff, a, b);\n    return MAGNITUDE(diff);\n}\n\n\nint\nbn_pnt3_pnt3_equal(const fastf_t *a, const fastf_t *b, const struct bn_tol *tol)\n{\n    fastf_t tmp = tol->dist_sq;\n    fastf_t ab, abx, aby, abz;\n\n    abx = a[X]-b[X];\n    ab = abx * abx;\n    if (ab > tmp) {\n\treturn 0;\n    }\n    aby = a[Y]-b[Y];\n    ab += (aby * aby);\n    if (ab > tmp) {\n\treturn 0;\n    }\n    abz = a[Z]-b[Z];\n    ab += (abz * abz);\n    if (ab > tmp) {\n\treturn 0;\n    }\n\n    return 1;\n}\n\n\n/**\n * @return 1\tif the two points are equal, within the tolerance\n * @return 0\tif the two points are not \"the same\"\n */\nint\nbn_pnt2_pnt2_equal(const fastf_t *a, const fastf_t *b, const struct bn_tol *tol)\n{\n    vect_t diff;\n\n    BN_CK_TOL(tol);\n    V2SUB2(diff, b, a);\n    if (MAG2SQ(diff) < tol->dist_sq) return 1;\n    return 0;\n}\n\n\nint\nbn_3pnts_collinear(fastf_t *a, fastf_t *b, fastf_t *c, const struct bn_tol *tol)\n{\n    fastf_t mag_ab, mag_bc, mag_ca, max_len, dist_sq;\n    fastf_t cos_a, cos_b, cos_c;\n    vect_t ab, bc, ca;\n    int max_edge_no;\n\n    VSUB2(ab, b, a);\n    VSUB2(bc, c, b);\n    VSUB2(ca, a, c);\n    mag_ab = MAGNITUDE(ab);\n    mag_bc = MAGNITUDE(bc);\n    mag_ca = MAGNITUDE(ca);\n\n    /* If two or more points are the same, by definition we're collinear */\n    if (NEAR_ZERO(mag_ab,tol->dist_sq) ||  NEAR_ZERO(mag_bc,tol->dist_sq) || NEAR_ZERO(mag_ca,tol->dist_sq))\n\treturn 1;\n\n    /* find longest edge */\n    max_len = mag_ab;\n    max_edge_no = 1;\n\n    if (mag_bc > max_len) {\n\tmax_len = mag_bc;\n\tmax_edge_no = 2;\n    }\n\n    if (mag_ca > max_len) {\n\tmax_edge_no = 3;\n    }\n\n    switch (max_edge_no) {\n\tdefault:\n\tcase 1:\n\t    cos_b = (-VDOT(ab, bc))/(mag_ab * mag_bc);\n\t    dist_sq = mag_bc*mag_bc*(1.0 - cos_b*cos_b);\n\t    break;\n\tcase 2:\n\t    cos_c = (-VDOT(bc, ca))/(mag_bc * mag_ca);\n\t    dist_sq = mag_ca*mag_ca*(1.0 - cos_c*cos_c);\n\t    break;\n\tcase 3:\n\t    cos_a = (-VDOT(ca, ab))/(mag_ca * mag_ab);\n\t    dist_sq = mag_ab*mag_ab*(1.0 - cos_a*cos_a);\n\t    break;\n    }\n\n    if (dist_sq <= tol->dist_sq)\n\treturn 1;\n    else\n\treturn 0;\n}\n\n\nint\nbn_3pnts_distinct(const fastf_t *a, const fastf_t *b, const fastf_t *c, const struct bn_tol *tol)\n{\n    vect_t B_A;\n    vect_t C_A;\n    vect_t C_B;\n\n    BN_CK_TOL(tol);\n    VSUB2(B_A, b, a);\n    if (MAGSQ(B_A) <= tol->dist_sq) return 0;\n    VSUB2(C_A, c, a);\n    if (MAGSQ(C_A) <= tol->dist_sq) return 0;\n    VSUB2(C_B, c, b);\n    if (MAGSQ(C_B) <= tol->dist_sq) return 0;\n    return 1;\n}\n\n\nint\nbn_npnts_distinct(const int npt, const point_t *pts, const struct bn_tol *tol)\n{\n    int i, j;\n    point_t r;\n\n    BN_CK_TOL(tol);\n\n    for (i=0;i<npt;i++)\n\tfor (j=i+1;j<npt;j++) {\n\t    VSUB2(r, pts[i], pts[j]);\n\t    if (MAGSQ(r) <= tol->dist_sq)\n\t\treturn 0;\n\t}\n    return 1;\n}\n\n\nint\nbn_make_plane_3pnts(fastf_t *plane,\n\t\t const fastf_t *a,\n\t\t const fastf_t *b,\n\t\t const fastf_t *c,\n\t\t const struct bn_tol *tol)\n{\n    vect_t B_A;\n    vect_t C_A;\n    vect_t C_B;\n    fastf_t mag;\n\n    BN_CK_TOL(tol);\n\n    VSUB2(B_A, b, a);\n    if (MAGSQ(B_A) <= tol->dist_sq) return -1;\n    VSUB2(C_A, c, a);\n    if (MAGSQ(C_A) <= tol->dist_sq) return -1;\n    VSUB2(C_B, c, b);\n    if (MAGSQ(C_B) <= tol->dist_sq) return -1;\n\n    VCROSS(plane, B_A, C_A);\n\n    /* Ensure unit length normal */\n    if ((mag = MAGNITUDE(plane)) <= SMALL_FASTF)\n\treturn -1;\t/* FAIL */\n    mag = 1/mag;\n    VSCALE(plane, plane, mag);\n\n    /* Find distance from the origin to the plane */\n    /* XXX Should do with pt that has smallest magnitude (closest to origin) */\n    plane[3] = VDOT(plane, a);\n\n    return 0;\t\t/* OK */\n}\n\n\nint\nbn_make_pnt_3planes(fastf_t *pt, const fastf_t *a, const fastf_t *b, const fastf_t *c)\n{\n    vect_t v1;\n    fastf_t dot;\n\n    /* Find a vector perpendicular to vectors b and c (parallel to planes B\n     * and C).\n     */\n    VCROSS(v1, b, c);\n\n    /* If vector a is perpendicular to that vector, then two of the three\n     * planes are parallel. We test by examining their dot product, which is\n     * also the determinant of the matrix M^T:\n     * [ a[X]  a[Y]  a[Z] ]\n     * [ b[X]  b[Y]  b[Z] ]\n     * [ c[X]  c[Y]  c[Z] ]\n     */\n    dot = VDOT(a, v1);\n\n    if (ZERO(dot)) {\n\treturn -1;\n    } else {\n\tvect_t v2, v3;\n\tfastf_t det, aH, bH, cH;\n\n\tVCROSS(v2, a, c);\n\tVCROSS(v3, a, b);\n\n\t/* Since this algorithm assumes unit-length direction vectors, we need\n\t * to calculate the scale factors associated with the unitized\n\t * equivalents of the planes.\n\t */\n\taH = MAGNITUDE(a) * a[H];\n\tbH = MAGNITUDE(b) * b[H];\n\tcH = MAGNITUDE(c) * c[H];\n\n\t/* We use the fact that det(M) = 1 / det(M^T) to calculate the\n\t * determinant of matrix M:\n\t * [ a[X] b[X] c[X] ]\n\t * [ a[Y] b[Y] c[Y] ]\n\t * [ a[Z] b[Z] c[Z] ]\n\t */\n\tdet = 1 / dot;\n\n\tpt[X] = det * (aH * v1[X] - bH * v2[X] + cH * v3[X]);\n\tpt[Y] = det * (aH * v1[Y] - bH * v2[Y] + cH * v3[Y]);\n\tpt[Z] = det * (aH * v1[Z] - bH * v2[Z] + cH * v3[Z]);\n    }\n    return 0;\n}\n\n\nint\nbn_2line3_colinear(const fastf_t *p1,\n\t\t   const fastf_t *d1,\n\t\t   const fastf_t *p2,\n\t\t   const fastf_t *d2,\n\t\t   double range,\n\t\t   const struct bn_tol *tol)\n{\n    fastf_t mag1;\n    fastf_t mag2;\n    point_t tail;\n\n    BN_CK_TOL(tol);\n\n    if (!p1 || !d1 || !p2 || !d2) {\n\tgoto fail;\n    }\n\n    if ((mag1 = MAGNITUDE(d1)) < SMALL_FASTF) bu_bomb(\"bn_2line3_colinear() mag1 zero\\n\");\n    if ((mag2 = MAGNITUDE(d2)) < SMALL_FASTF) bu_bomb(\"bn_2line3_colinear() mag2 zero\\n\");\n\n    /* Impose a general angular tolerance to reject \"obviously\" non-parallel lines */\n    /* tol->para and RT_DOT_TOL are too tight a tolerance.  0.1 is 5 degrees */\n    if (fabs(VDOT(d1, d2)) < 0.9 * mag1 * mag2) goto fail;\n\n    /* See if start points are within tolerance of other line */\n    if (bn_distsq_line3_pnt3(p1, d1, p2) > tol->dist_sq) goto fail;\n    if (bn_distsq_line3_pnt3(p2, d2, p1) > tol->dist_sq) goto fail;\n\n    VJOIN1(tail, p1, range/mag1, d1);\n    if (bn_distsq_line3_pnt3(p2, d2, tail) > tol->dist_sq) goto fail;\n\n    VJOIN1(tail, p2, range/mag2, d2);\n    if (bn_distsq_line3_pnt3(p1, d1, tail) > tol->dist_sq) goto fail;\n\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_2line3colinear(range=%g) ret=1\\n\", range);\n    }\n    return 1;\nfail:\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_2line3colinear(range=%g) ret=0\\n\", range);\n    }\n    return 0;\n}\n\n\nint\nbn_dist_pnt3_line3(fastf_t *dist, fastf_t *pca, const fastf_t *a, const fastf_t *dir, const fastf_t *p, const struct bn_tol *tol)\n{\n    vect_t AtoP;\t/* P-A */\n    vect_t unit_dir;\t/* unitized dir vector */\n    fastf_t A_P_sq;\t/* |P-A|**2 */\n    fastf_t t;\t\t/* distance along ray of projection of P */\n    fastf_t dsq;\t/* square of distance from p to line */\n\n    if (UNLIKELY(bu_debug & BU_DEBUG_MATH))\n\tbu_log(\"bn_dist_pnt3_line3(a=(%f %f %f), dir=(%f %f %f), p=(%f %f %f)\\n\" ,\n\t       V3ARGS(a), V3ARGS(dir), V3ARGS(p));\n\n    BN_CK_TOL(tol);\n\n    /* Check proximity to endpoint A */\n    VSUB2(AtoP, p, a);\n    A_P_sq = MAGSQ(AtoP);\n    if (A_P_sq < tol->dist_sq) {\n\t/* P is within the tol->dist radius circle around A */\n\tVMOVE(pca, a);\n\t*dist = 0.0;\n\treturn 0;\n    }\n\n    VMOVE(unit_dir, dir);\n    VUNITIZE(unit_dir);\n\n    /* compute distance (in actual units) along line to PROJECTION of\n     * point p onto the line: point pca\n     */\n    t = VDOT(AtoP, unit_dir);\n\n    VJOIN1(pca, a, t, unit_dir);\n    dsq = A_P_sq - t*t;\n    if (dsq < tol->dist_sq) {\n\t/* P is within tolerance of the line */\n\t*dist = 0.0;\n\treturn 1;\n    } else {\n\t/* P is off line */\n\t*dist = sqrt(dsq);\n\treturn 2;\n    }\n}\n\n\nint\nbn_dist_line3_line3(fastf_t *dist, const fastf_t *p1, const fastf_t *d1, const fastf_t *p2, const fastf_t *d2, const struct bn_tol *tol)\n{\n    fastf_t d1_d2;\n    point_t a1, a2;\n    vect_t a1_to_a2;\n    vect_t p2_to_p1;\n    fastf_t min_dist;\n    fastf_t tol_dist_sq;\n    fastf_t tol_dist;\n\n    BN_CK_TOL(tol);\n\n    if (tol->dist > 0.0)\n\ttol_dist = tol->dist;\n    else\n\ttol_dist = BN_TOL_DIST;\n\n    if (tol->dist_sq > 0.0)\n\ttol_dist_sq = tol->dist_sq;\n    else\n\ttol_dist_sq = tol_dist * tol_dist;\n\n    if (!NEAR_EQUAL(MAGSQ(d1), 1.0, tol_dist_sq)) {\n\tbu_log(\"bn_dist_line3_line3: non-unit length direction vector (%f %f %f)\\n\", V3ARGS(d1));\n\tbu_bomb(\"bn_dist_line3_line3\\n\");\n    }\n\n    if (!NEAR_EQUAL(MAGSQ(d2), 1.0, tol_dist_sq)) {\n\tbu_log(\"bn_dist_line3_line3: non-unit length direction vector (%f %f %f)\\n\", V3ARGS(d2));\n\tbu_bomb(\"bn_dist_line3_line3\\n\");\n    }\n\n    d1_d2 = VDOT(d1, d2);\n\n    if (BN_VECT_ARE_PARALLEL(d1_d2, tol)) {\n\tif (bn_dist_line3_pnt3(p1, d1, p2) > tol_dist)\n\t    return -2; /* parallel, but not collinear */\n\telse\n\t    return -1; /* parallel and collinear */\n    }\n\n    VSUB2(p2_to_p1, p1, p2);\n    dist[0] = (d1_d2 * VDOT(p2_to_p1, d2) - VDOT(p2_to_p1, d1))/(1.0 - d1_d2 * d1_d2);\n    dist[1] = dist[0] * d1_d2 + VDOT(p2_to_p1, d2);\n\n    VJOIN1(a1, p1, dist[0], d1);\n    VJOIN1(a2, p2, dist[1], d2);\n\n    VSUB2(a1_to_a2, a2, a1);\n    min_dist = MAGNITUDE(a1_to_a2);\n    if (min_dist < tol_dist)\n\treturn 0;\n    else\n\treturn 1;\n}\n\n\nint\nbn_dist_line3_lseg3(fastf_t *dist, const fastf_t *p, const fastf_t *d, const fastf_t *a, const fastf_t *b, const struct bn_tol *tol)\n{\n    vect_t a_to_b;\n    vect_t a_dir;\n    fastf_t len_ab;\n    int outside_segment;\n    int ret;\n\n    BN_CK_TOL(tol);\n\n    VSUB2(a_to_b, b, a);\n    len_ab = MAGNITUDE(a_to_b);\n    VSCALE(a_dir, a_to_b, (1.0/len_ab));\n\n    ret = bn_dist_line3_line3(dist, p, d, a, a_dir, tol);\n\n    if (ret < 0) {\n\tvect_t to_a, to_b;\n\tfastf_t dist_to_a, dist_to_b;\n\n\tVSUB2(to_a, a, p);\n\tVSUB2(to_b, b, p);\n\tdist_to_a = VDOT(to_a, d);\n\tdist_to_b = VDOT(to_b, d);\n\n\tif (dist_to_a <= dist_to_b) {\n\t    dist[0] = dist_to_a;\n\t    dist[1] = 0.0;\n\t} else {\n\t    dist[0] = dist_to_b;\n\t    dist[1] = 1.0;\n\t}\n\treturn ret;\n    }\n\n    if (dist[1] >= (-tol->dist) && dist[1] <= len_ab + tol->dist) {\n\t/* intersect or closest approach between a and b */\n\toutside_segment = 0;\n\tdist[1] = dist[1]/len_ab;\n\tCLAMP(dist[1], 0.0, 1.0);\n    } else {\n\toutside_segment = 1;\n\tdist[1] = dist[1]/len_ab;\n    }\n\n    return 2*ret + outside_segment;\n}\n\n\nint\nbn_isect_line3_plane(fastf_t *dist,\n\t\t     const fastf_t *pt,\n\t\t     const fastf_t *dir,\n\t\t     const fastf_t *plane,\n\t\t     const struct bn_tol *tol)\n{\n    fastf_t slant_factor;\n    fastf_t norm_dist;\n    fastf_t dot;\n    vect_t local_dir;\n\n    BN_CK_TOL(tol);\n\n    norm_dist = plane[3] - VDOT(plane, pt);\n    slant_factor = VDOT(plane, dir);\n    VMOVE(local_dir, dir);\n    VUNITIZE(local_dir);\n    dot = VDOT(plane, local_dir);\n\n    if (slant_factor < -SMALL_FASTF && dot < -tol->perp) {\n\t*dist = norm_dist/slant_factor;\n\treturn 1;\t\t\t/* HIT, entering */\n    } else if (slant_factor > SMALL_FASTF && dot > tol->perp) {\n\t*dist = norm_dist/slant_factor;\n\treturn 2;\t\t\t/* HIT, leaving */\n    }\n\n    /*\n     * Ray is parallel to plane when dir.N == 0.\n     */\n    *dist = 0;\t\t/* sanity */\n    if (norm_dist < -tol->dist)\n\treturn -2;\t/* missed, outside */\n    if (norm_dist > tol->dist)\n\treturn -1;\t/* missed, inside */\n    return 0;\t\t/* Ray lies in the plane */\n}\n\n\nint\nbn_isect_2planes(fastf_t *pt,\n\t\t fastf_t *dir,\n\t\t const fastf_t *a,\n\t\t const fastf_t *b,\n\t\t const fastf_t *rpp_min,\n\t\t const struct bn_tol *tol)\n{\n    vect_t abs_dir;\n    plane_t pl;\n    int i;\n\n    VSETALL(pt, 0.0);  /* sanity */\n    VSETALL(dir, 0.0); /* sanity */\n\n    if ((i = bn_coplanar(a, b, tol)) != 0) {\n\tif (i > 0) {\n\t    return -1; /* planes are coplanar */\n\t}\n\treturn -2;     /* planes are parallel but not coplanar */\n    }\n\n    /* Direction vector for ray is perpendicular to both plane\n     * normals.\n     */\n    VCROSS(dir, a, b);\n\n    /* Select an axis-aligned plane which has its normal pointing\n     * along the same axis as the largest magnitude component of the\n     * direction vector.  If the largest magnitude component is\n     * negative, reverse the direction vector, so that model is \"in\n     * front\" of start point.\n     */\n    abs_dir[X] = fabs(dir[X]);\n    abs_dir[Y] = fabs(dir[Y]);\n    abs_dir[Z] = fabs(dir[Z]);\n\n    if (ZERO(abs_dir[X])) {\n\tabs_dir[X] = 0.0;\n    }\n    if (ZERO(abs_dir[Y])) {\n\tabs_dir[Y] = 0.0;\n    }\n    if (ZERO(abs_dir[Z])) {\n\tabs_dir[Z] = 0.0;\n    }\n\n    if (abs_dir[X] >= abs_dir[Y]) {\n\tif (abs_dir[X] >= abs_dir[Z]) {\n\t    VSET(pl, 1, 0, 0);\t/* X */\n\t    pl[W] = rpp_min[X];\n\t    if (dir[X] < -SMALL_FASTF) {\n\t\tVREVERSE(dir, dir);\n\t    }\n\t} else {\n\t    VSET(pl, 0, 0, 1);\t/* Z */\n\t    pl[W] = rpp_min[Z];\n\t    if (dir[Z] < -SMALL_FASTF) {\n\t\tVREVERSE(dir, dir);\n\t    }\n\t}\n    } else {\n\tif (abs_dir[Y] >= abs_dir[Z]) {\n\t    VSET(pl, 0, 1, 0);\t/* Y */\n\t    pl[W] = rpp_min[Y];\n\t    if (dir[Y] < -SMALL_FASTF) {\n\t\tVREVERSE(dir, dir);\n\t    }\n\t} else {\n\t    VSET(pl, 0, 0, 1);\t/* Z */\n\t    pl[W] = rpp_min[Z];\n\t    if (dir[Z] < -SMALL_FASTF) {\n\t\tVREVERSE(dir, dir);\n\t    }\n\t}\n    }\n\n    /* Intersection of the 3 planes defines ray start point */\n    if (bn_make_pnt_3planes(pt, pl, a, b) < 0) {\n\treturn -3;  /* error, should be intersection but unable to find */\n    }\n\n    /* success, line of intersection stored in 'pt' and 'dir' */\n    return 0;\n}\n\n\nint\nbn_isect_line2_line2(fastf_t *dist, const fastf_t *p, const fastf_t *d, const fastf_t *a, const fastf_t *c, const struct bn_tol *tol)\n/* dist[2] */\n\n\n{\n    fastf_t hx, hy;\t\t/* A - P */\n    fastf_t det;\n    fastf_t det1;\n    vect_t unit_d;\n    vect_t unit_c;\n    vect_t unit_h;\n    int parallel;\n    int parallel1;\n\n    BN_CK_TOL(tol);\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_isect_line2_line2() p=(%g, %g), d=(%g, %g)\\n\\t\\t\\ta=(%g, %g), c=(%g, %g)\\n\",\n\t       V2ARGS(p), V2ARGS(d), V2ARGS(a), V2ARGS(c));\n    }\n\n    /*\n     * From the two components q and r, form a system of 2 equations\n     * in 2 unknowns.  Solve for t and u in the system:\n     *\n     * Px + t * Dx = Ax + u * Cx\n     * Py + t * Dy = Ay + u * Cy\n     * or\n     * t * Dx - u * Cx = Ax - Px\n     * t * Dy - u * Cy = Ay - Py\n     *\n     * Let H = A - P, resulting in:\n     *\n     * t * Dx - u * Cx = Hx\n     * t * Dy - u * Cy = Hy\n     *\n     * or\n     *\n     * [ Dx  -Cx ]   [ t ]   [ Hx ]\n     * [         ] * [   ] = [    ]\n     * [ Dy  -Cy ]   [ u ]   [ Hy ]\n     *\n     * This system can be solved by direct substitution, or by finding\n     * the determinants by Cramer's rule:\n     *\n     *\t             [ Dx  -Cx ]\n     *\tdet(M) = det [         ] = -Dx * Cy + Cx * Dy\n     *\t             [ Dy  -Cy ]\n     *\n     * If det(M) is zero, then the lines are parallel (perhaps\n     * collinear).  Otherwise, exactly one solution exists.\n     */\n    det = c[X] * d[Y] - d[X] * c[Y];\n\n    /*\n     * det(M) is non-zero, so there is exactly one solution.  Using\n     * Cramer's rule, det1(M) replaces the first column of M with the\n     * constant column vector, in this case H.  Similarly, det2(M)\n     * replaces the second column.  Computation of the determinant is\n     * done as before.\n     *\n     * Now,\n     *\n     *\t                  [ Hx  -Cx ]\n     *\t              det [         ]\n     *\t    det1(M)       [ Hy  -Cy ]   -Hx * Cy + Cx * Hy\n     *\tt = ------- = --------------- = ------------------\n     *\t     det(M) det(M)        -Dx * Cy + Cx * Dy\n     *\n     * and\n     *\n     *\t                  [ Dx   Hx ]\n     *\t              det [         ]\n     *\t    det2(M)       [ Dy   Hy ]    Dx * Hy - Hx * Dy\n     *\tu = ------- = --------------- = ------------------\n     *\t     det(M) det(M)        -Dx * Cy + Cx * Dy\n     */\n    hx = a[X] - p[X];\n    hy = a[Y] - p[Y];\n    det1 = (c[X] * hy - hx * c[Y]);\n\n    unit_d[0] = d[0];\n    unit_d[1] = d[1];\n    unit_d[2] = 0.0;\n    VUNITIZE(unit_d);\n    unit_c[0] = c[0];\n    unit_c[1] = c[1];\n    unit_c[2] = 0.0;\n    VUNITIZE(unit_c);\n    unit_h[0] = hx;\n    unit_h[1] = hy;\n    unit_h[2] = 0.0;\n    VUNITIZE(unit_h);\n\n    if (fabs(VDOT(unit_d, unit_c)) >= tol->para)\n\tparallel = 1;\n    else\n\tparallel = 0;\n\n    if (fabs(VDOT(unit_h, unit_c)) >= tol->para)\n\tparallel1 = 1;\n    else\n\tparallel1 = 0;\n\n    /* XXX This zero tolerance here should actually be\n     * XXX determined by something like\n     * XXX max(c[X], c[Y], d[X], d[Y]) / MAX_FASTF_DYNAMIC_RANGE\n     * XXX In any case, nothing smaller than 1e-16\n     */\n#define DETERMINANT_TOL 1.0e-14\t\t/* XXX caution on non-IEEE machines */\n    if (parallel || NEAR_ZERO(det, DETERMINANT_TOL)) {\n\t/* Lines are parallel */\n\tif (!parallel1 && !NEAR_ZERO(det1, DETERMINANT_TOL)) {\n\t    /* Lines are NOT collinear, just parallel */\n\t    if (bu_debug & BU_DEBUG_MATH) {\n\t\tbu_log(\"\\tparallel, not co-linear.  det=%e, det1=%g\\n\", det, det1);\n\t    }\n\t    return -1;\t/* parallel, no intersection */\n\t}\n\n\t/*\n\t * Lines are collinear.\n\t * Determine t as distance from P to A.\n\t * Determine u as distance from P to (A+C).  [special!]\n\t * Use largest direction component, for numeric stability\n\t * (and avoiding division by zero).\n\t */\n\tif (fabs(d[X]) >= fabs(d[Y])) {\n\t    dist[0] = hx/d[X];\n\t    dist[1] = (hx + c[X]) / d[X];\n\t} else {\n\t    dist[0] = hy/d[Y];\n\t    dist[1] = (hy + c[Y]) / d[Y];\n\t}\n\tif (bu_debug & BU_DEBUG_MATH) {\n\t    bu_log(\"\\tcollinear, t = %g, u = %g\\n\", dist[0], dist[1]);\n\t}\n\treturn 0;\t/* Lines collinear */\n    }\n    if (bu_debug & BU_DEBUG_MATH) {\n\t/* XXX This print is temporary */\n\tbu_log(\"\\thx=%g, hy=%g, det=%g, det1=%g, det2=%g\\n\", hx, hy, det, det1, (d[X] * hy - hx * d[Y]));\n    }\n    det = 1/det;\n    dist[0] = det * det1;\n    dist[1] = det * (d[X] * hy - hx * d[Y]);\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"\\tintersection, t = %g, u = %g\\n\", dist[0], dist[1]);\n    }\n\n    return 1;\t\t/* Intersection found */\n}\n\n\nint\nbn_isect_line2_lseg2(fastf_t *dist,\n\t\t     const fastf_t *p,\n\t\t     const fastf_t *d,\n\t\t     const fastf_t *a,\n\t\t     const fastf_t *c,\n\t\t     const struct bn_tol *tol)\n{\n    fastf_t f;\n    fastf_t ctol;\n    int ret;\n    point_t b;\n\n    BN_CK_TOL(tol);\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_isect_line2_lseg2() p=(%g, %g), pdir=(%g, %g)\\n\\t\\t\\ta=(%g, %g), adir=(%g, %g)\\n\",\n\t       V2ARGS(p), V2ARGS(d), V2ARGS(a), V2ARGS(c));\n    }\n\n    /* To keep the values of u between 0 and 1.  C should NOT be\n     * scaled to have unit length.  However, it is a good idea to make\n     * sure that C is a non-zero vector, (i.e., that A and B are\n     * distinct).\n     */\n    if ((ctol = MAG2SQ(c)) <= tol->dist_sq) {\n\tret = -4;\t\t/* points A and B are not distinct */\n\tgoto out;\n    }\n\n    /* Detecting collinearity is difficult, and very very important.\n     * As a first step, check to see if both points A and B lie within\n     * tolerance of the line.  If so, then the line segment AC is ON\n     * the line.\n     */\n    V2ADD2(b, a, c);\n    if (bn_distsq_line2_point2(p, d, a) <= tol->dist_sq  &&\n\t(ctol=bn_distsq_line2_point2(p, d, b)) <= tol->dist_sq) {\n\tif (bu_debug & BU_DEBUG_MATH) {\n\t    bu_log(\"b=(%g, %g), b_dist_sq=%g\\n\", V2ARGS(b), ctol);\n\t    bu_log(\"bn_isect_line2_lseg2() pnts A and B within tol of line\\n\");\n\t}\n\t/* Find the parametric distance along the ray */\n\tdist[0] = bn_dist_pnt2_along_line2(p, d, a);\n\tdist[1] = bn_dist_pnt2_along_line2(p, d, b);\n\tret = 0;\t\t/* Collinear */\n\tgoto out;\n    }\n\n    if ((ret = bn_isect_line2_line2(dist, p, d, a, c, tol)) < 0) {\n\t/* Lines are parallel, non-collinear */\n\tret = -3;\t\t/* No intersection found */\n\tgoto out;\n    }\n    if (ret == 0) {\n\tfastf_t dtol;\n\t/* Lines are collinear */\n\t/* If P within tol of either endpoint (0, 1), make exact. */\n\tdtol = tol->dist / sqrt(MAG2SQ(d));\n\tif (bu_debug & BU_DEBUG_MATH) {\n\t    bu_log(\"bn_isect_line2_lseg2() dtol=%g, dist[0]=%g, dist[1]=%g\\n\",\n\t\t   dtol, dist[0], dist[1]);\n\t}\n\tif (dist[0] > -dtol && dist[0] < dtol) dist[0] = 0;\n\telse if (dist[0] > 1-dtol && dist[0] < 1+dtol) dist[0] = 1;\n\n\tif (dist[1] > -dtol && dist[1] < dtol) dist[1] = 0;\n\telse if (dist[1] > 1-dtol && dist[1] < 1+dtol) dist[1] = 1;\n\tret = 0;\t\t/* Collinear */\n\tgoto out;\n    }\n\n    /* The two lines are claimed to intersect at a point.  First,\n     * validate that hit point represented by dist[0] is in fact on\n     * and between A--B.  (Nearly parallel lines can result in odd\n     * situations here).  The performance hit of doing this is vastly\n     * preferable to returning wrong answers.  Know a faster\n     * algorithm?\n     */\n    {\n\tfastf_t ab_dist = 0;\n\tpoint_t hit_pt;\n\tpoint_t hit2;\n\n\tV2JOIN1(hit_pt, p, dist[0], d);\n\tV2JOIN1(hit2, a, dist[1], c);\n\t/* Check both hit point value calculations */\n\tif (bn_pnt2_pnt2_equal(a, hit_pt, tol) ||\n\t    bn_pnt2_pnt2_equal(a, hit2, tol)) {\n\t    dist[1] = 0;\n\t}\n\tif (bn_pnt2_pnt2_equal(b, hit_pt, tol) ||\n\t    bn_pnt2_pnt2_equal(b, hit_pt, tol)) {\n\t    dist[1] = 1;\n\t}\n\n\tret = bn_isect_pnt2_lseg2(&ab_dist, a, b, hit_pt, tol);\n\tif (bu_debug & BU_DEBUG_MATH) {\n\t    /* XXX This is temporary */\n\t    V2PRINT(\"a\", a);\n\t    V2PRINT(\"hit\", hit_pt);\n\t    V2PRINT(\"b\", b);\n\t    bu_log(\"bn_isect_pnt2_lseg2() hit2d=(%g, %g) ab_dist=%g, ret=%d\\n\", hit_pt[X], hit_pt[Y], ab_dist, ret);\n\t    bu_log(\"\\tother hit2d=(%g, %g)\\n\", hit2[X], hit2[Y]);\n\t}\n\tif (ret <= 0) {\n\t    if (ab_dist < 0) {\n\t\tret = -2;\t/* Intersection < A */\n\t    } else {\n\t\tret = -1;\t/* Intersection >B */\n\t    }\n\t    goto out;\n\t}\n\tif (ret == 1) {\n\t    dist[1] = 0;\n\t    ret = 1;\t/* Intersect is at A */\n\t    goto out;\n\t}\n\tif (ret == 2) {\n\t    dist[1] = 1;\n\t    ret = 2;\t/* Intersect is at B */\n\t    goto out;\n\t}\n\t/* ret == 3, hit_pt is between A and B */\n\n\tif (!bn_between(a[X], hit_pt[X], b[X], tol) ||\n\t    !bn_between(a[Y], hit_pt[Y], b[Y], tol)) {\n\t    bu_bomb(\"bn_isect_line2_lseg2() hit_pt not between A and B!\\n\");\n\t}\n    }\n\n    /* If the dist[1] parameter is outside the range (0..1), reject\n     * the intersection, because it falls outside the line segment\n     * A--B.\n     *\n     * Convert the tol->dist into allowable deviation in terms of\n     * (0..1) range of the parameters.\n     */\n    ctol = tol->dist / sqrt(ctol);\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_isect_line2_lseg2() ctol=%g, dist[1]=%g\\n\", ctol, dist[1]);\n    }\n    if (dist[1] < -ctol) {\n\tret = -2;\t\t/* Intersection < A */\n\tgoto out;\n    }\n    if ((f=(dist[1]-1)) > ctol) {\n\tret = -1;\t\t/* Intersection > B */\n\tgoto out;\n    }\n\n    /* Check for ctoly intersection with one of the vertices */\n    if (dist[1] < ctol) {\n\tdist[1] = 0;\n\tret = 1;\t\t/* Intersection at A */\n\tgoto out;\n    }\n    if (f >= -ctol) {\n\tdist[1] = 1;\n\tret = 2;\t\t/* Intersection at B */\n\tgoto out;\n    }\n    ret = 3;\t\t\t/* Intersection between A and B */\nout:\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_isect_line2_lseg2() dist[0]=%g, dist[1]=%g, ret=%d\\n\",\n\t       dist[0], dist[1], ret);\n    }\n    return ret;\n}\n\n\nint\nbn_isect_lseg2_lseg2(fastf_t *dist,\n\t\t     const fastf_t *p,\n\t\t     const fastf_t *pdir,\n\t\t     const fastf_t *q,\n\t\t     const fastf_t *qdir,\n\t\t     const struct bn_tol *tol)\n{\n    fastf_t ptol;\n    fastf_t qtol; /* length in parameter space == tol->dist */\n    int status;\n\n    BN_CK_TOL(tol);\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_isect_lseg2_lseg2() p=(%g, %g), pdir=(%g, %g)\\n\\t\\tq=(%g, %g), qdir=(%g, %g)\\n\",\n\t       V2ARGS(p), V2ARGS(pdir), V2ARGS(q), V2ARGS(qdir));\n    }\n\n    status = bn_isect_line2_line2(dist, p, pdir, q, qdir, tol);\n    if (status < 0) {\n\t/* Lines are parallel, non-collinear */\n\treturn -1;\t/* No intersection */\n    }\n    if (status == 0) {\n\tint nogood = 0;\n\t/* Lines are collinear */\n\t/* If P within tol of either endpoint (0, 1), make exact. */\n\tptol = tol->dist / sqrt(MAG2SQ(pdir));\n\tif (bu_debug & BU_DEBUG_MATH) {\n\t    bu_log(\"ptol=%g\\n\", ptol);\n\t}\n\n\tif (NEAR_ZERO(dist[0], ptol))\n\t    dist[0] = 0.0;\n\telse if (NEAR_EQUAL(dist[0], 1.0, ptol))\n\t    dist[0] = 1.0;\n\n\tif (NEAR_ZERO(dist[1], ptol))\n\t    dist[1] = 0.0;\n\telse if (NEAR_EQUAL(dist[1], 1.0, ptol))\n\t    dist[1] = 1.0;\n\n\tif (dist[1] < 0 || dist[1] > 1) nogood = 1;\n\tif (dist[0] < 0 || dist[0] > 1) nogood++;\n\tif (nogood >= 2)\n\t    return -1;\t/* collinear, but not overlapping */\n\tif (bu_debug & BU_DEBUG_MATH) {\n\t    bu_log(\"  HIT collinear!\\n\");\n\t}\n\treturn 0;\t\t/* collinear and overlapping */\n    }\n    /* Lines intersect */\n    /* If within tolerance of an endpoint (0, 1), make exact. */\n    ptol = tol->dist / sqrt(MAG2SQ(pdir));\n\n    if (NEAR_ZERO(dist[0], ptol))\n\tdist[0] = 0;\n    else if (NEAR_EQUAL(dist[0], 1.0, ptol))\n\tdist[0] = 1;\n\n    qtol = tol->dist / sqrt(MAG2SQ(qdir));\n    if (NEAR_ZERO(dist[1], ptol))\n\tdist[1] = 0;\n    else if (NEAR_EQUAL(dist[1], 1.0, ptol))\n\tdist[1] = 1;\n\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"ptol=%g, qtol=%g\\n\", ptol, qtol);\n    }\n    if (dist[0] < 0 || dist[0] > 1 || dist[1] < 0 || dist[1] > 1) {\n\tif (bu_debug & BU_DEBUG_MATH) {\n\t    bu_log(\"  MISS\\n\");\n\t}\n\treturn -1;\t\t/* missed */\n    }\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"  HIT!\\n\");\n    }\n    return 1;\t\t\t/* hit, normal intersection */\n}\n\n\nint\nbn_isect_lseg3_lseg3(fastf_t *dist,\n\t\t     const fastf_t *p,\n\t\t     const fastf_t *pdir,\n\t\t     const fastf_t *q,\n\t\t     const fastf_t *qdir,\n\t\t     const struct bn_tol *tol)\n{\n    fastf_t ptol;\n    fastf_t qtol; /* length in parameter space == tol->dist */\n    fastf_t pmag, qmag;\n    int status;\n    int ret;\n\n    BN_CK_TOL(tol);\n    if (UNLIKELY(bu_debug & BU_DEBUG_MATH)) {\n\tbu_log(\"bn_isect_lseg3_lseg3() p=(%g, %g, %g), pdir=(%g, %g, %g)\\n\\t\\tq=(%g, %g, %g), qdir=(%g, %g, %g)\\n\",\n\t       V3ARGS(p), V3ARGS(pdir), V3ARGS(q), V3ARGS(qdir));\n    }\n\n    status = bn_isect_line3_line3(&dist[0], &dist[1], p, pdir, q, qdir, tol);\n\n    /* It is expected that dist[0] and dist[1] returned from\n     * 'bn_isect_line3_line3' are the actual distance to the\n     * intersect, i.e. not scaled. Distances in the opposite of the\n     * line direction vector result in a negative distance.\n     */\n\n    /* sanity check */\n    if (UNLIKELY(status < -2 || status > 1)) {\n\tbu_bomb(\"bn_isect_lseg3_lseg3() function 'bn_isect_line3_line3' returned an invalid status\\n\");\n    }\n\n    if (status == -1) {\n\t/* Infinite lines do not intersect and are not parallel\n\t * therefore line segments do not intersect and are not\n\t * parallel.\n\t */\n\tif (UNLIKELY(bu_debug & BU_DEBUG_MATH)) {\n\t    bu_log(\"bn_isect_lseg3_lseg3(): MISS, line segments do not intersect and are not parallel\\n\");\n\t}\n\tret = -3; /* missed */\n\tgoto out;\n    }\n\n    if (status == -2) {\n\t/* infinite lines do not intersect, they are parallel */\n\tif (UNLIKELY(bu_debug & BU_DEBUG_MATH)) {\n\t    bu_log(\"bn_isect_lseg3_lseg3(): MISS, line segments are parallel, i.e. do not intersect\\n\");\n\t}\n\tret = -2; /* missed (line segments are parallel) */\n\tgoto out;\n    }\n\n    pmag = MAGNITUDE(pdir);\n    qmag = MAGNITUDE(qdir);\n\n    if (UNLIKELY(pmag < SMALL_FASTF)) {\n\tbu_bomb(\"bn_isect_lseg3_lseg3(): |p|=0\\n\");\n    }\n\n    if (UNLIKELY(qmag < SMALL_FASTF)) {\n\tbu_bomb(\"bn_isect_lseg3_lseg3(): |q|=0\\n\");\n    }\n\n    ptol = tol->dist / pmag;\n    qtol = tol->dist / qmag;\n    dist[0] = dist[0] / pmag;\n    if (status == 0) {  /* infinite lines are collinear */\n\t/* When line segments are collinear, dist[1] has an alternate\n\t * interpretation: it's the parameter along p (not q)\n\t * therefore dist[1] must be scaled by pmag not qmag.\n\t */\n\tdist[1] = dist[1] / pmag;\n    } else {\n\tdist[1] = dist[1] / qmag;\n    }\n\n    if (UNLIKELY(bu_debug & BU_DEBUG_MATH)) {\n\tbu_log(\"ptol=%g, qtol=%g\\n\", ptol, qtol);\n    }\n\n    /* If 'p' within tol of either endpoint (0.0, 1.0), make exact. */\n    if (NEAR_ZERO(dist[0], ptol)) {\n\tdist[0] = 0.0;\n    } else if (NEAR_EQUAL(dist[0], 1.0, ptol)) {\n\tdist[0] = 1.0;\n    }\n\n    if (status == 0) {  /* infinite lines are collinear */\n\t/* When line segments are collinear, dist[1] has an alternate\n\t * interpretation: it's the parameter along p (not q)\n\t * therefore dist[1] must use tolerance ptol not qtol.  If 'q'\n\t * within tol of either endpoint (0.0, 1.0), make exact.\n\t */\n\tif (NEAR_ZERO(dist[1], ptol)) {\n\t    dist[1] = 0.0;\n\t} else if (NEAR_EQUAL(dist[1], 1.0, ptol)) {\n\t    dist[1] = 1.0;\n\t}\n    } else {\n\t/* If 'q' within tol of either endpoint (0.0, 1.0), make exact. */\n\tif (NEAR_ZERO(dist[1], qtol)) {\n\t    dist[1] = 0.0;\n\t} else if (NEAR_EQUAL(dist[1], 1.0, qtol)) {\n\t    dist[1] = 1.0;\n\t}\n    }\n\n    if (status == 0) {  /* infinite lines are collinear */\n\t/* Lines are collinear */\n\tif ((dist[0] > 1.0+ptol && dist[1] > 1.0+ptol) || (dist[0] < -ptol && dist[1] < -ptol)) {\n\t    if (UNLIKELY(bu_debug & BU_DEBUG_MATH)) {\n\t\tbu_log(\"bn_isect_lseg3_lseg3(): MISS, line segments are collinear but not overlapping!\\n\");\n\t    }\n\t    ret = -1;   /* line segments are collinear but not overlapping */\n\t    goto out;\n\t}\n\n\tif (UNLIKELY(bu_debug & BU_DEBUG_MATH)) {\n\t    bu_log(\"bn_isect_lseg3_lseg3(): HIT, line segments are collinear and overlapping!\\n\");\n\t}\n\n\tret = 0; /* line segments are collinear and overlapping */\n\tgoto out;\n    }\n\n    /* At this point we know the infinite lines intersect and are not\n     * collinear.\n     */\n\n    if (dist[0] < -ptol || dist[0] > 1.0+ptol || dist[1] < -qtol || dist[1] > 1.0+qtol) {\n\tif (UNLIKELY(bu_debug & BU_DEBUG_MATH)) {\n\t    bu_log(\"bn_isect_lseg3_lseg3(): MISS, infinite lines intersect but line segments do not!\\n\");\n\t}\n\tret = -3;  /* missed, infinite lines intersect but line segments do not */\n\tgoto out;\n    }\n\n    if (UNLIKELY(bu_debug & BU_DEBUG_MATH)) {\n\tbu_log(\"bn_isect_lseg3_lseg3(): HIT, line segments intersect!\\n\");\n    }\n\n    /* sanity check */\n    if (UNLIKELY(dist[0] < -SMALL_FASTF || dist[0] > 1.0 || dist[1] < -SMALL_FASTF || dist[1] > 1.0)) {\n\tbu_bomb(\"bn_isect_lseg3_lseg3(): INTERNAL ERROR, intersect distance values must be in the range 0-1\\n\");\n    }\n\n    ret = 1; /* hit, line segments intersect */\n\nout:\n\n    return ret;\n}\n\n\nint\nbn_isect_line3_line3(fastf_t *pdist,        /* see above */\n\t\t     fastf_t *qdist,        /* see above */\n\t\t     const fastf_t *p0,     /* line p start point */\n\t\t     const fastf_t *pdir_i, /* line p direction, must not be unit vector */\n\t\t     const fastf_t *q0,     /* line q start point */\n\t\t     const fastf_t *qdir_i, /* line q direction, must not be unit vector */\n\t\t     const struct bn_tol *tol)\n{\n    fastf_t b, d, e, sc, tc, sc_numerator, tc_numerator, denominator;\n    vect_t w0, qc_to_pc, u_scaled, v_scaled, v_scaled_to_u_scaled, tmp_vec, p0_to_q1;\n    point_t p1, q1;\n    fastf_t pdir_mag_sq;\n    fastf_t qdir_mag_sq;\n\n    int parallel = 0;\n    int colinear = 0;\n    fastf_t dot, d1, d2, d3, d4;\n    vect_t pdir, qdir;\n\n    VMOVE(pdir, pdir_i);\n    VMOVE(qdir, qdir_i);\n\n    pdir_mag_sq = MAGSQ(pdir);\n    qdir_mag_sq = MAGSQ(qdir);\n\n    if (UNLIKELY((pdir_mag_sq < tol->dist_sq) || (qdir_mag_sq < tol->dist_sq))) {\n\tbu_log(\"  p0 = %g %g %g\\n\", V3ARGS(p0));\n\tbu_log(\"pdir = %g %g %g\\n\", V3ARGS(pdir));\n\tbu_log(\"  q0 = %g %g %g\\n\", V3ARGS(q0));\n\tbu_log(\"qdir = %g %g %g\\n\", V3ARGS(qdir));\n\tbu_bomb(\"bn_isect_line3_line3(): input vector(s) 'pdir' and/or 'qdir' is zero magnitude.\\n\");\n    }\n\n    *pdist = 0.0;\n    *qdist = 0.0;\n\n    /* assumes pdir & qdir are not unit vectors */\n    VADD2(p1, p0, pdir);\n    VADD2(q1, q0, qdir);\n\n    VSUB2(p0_to_q1, q1, p0);\n\n    if (bn_lseg3_lseg3_parallel(p0, p1, q0, q1, tol)) {\n\tparallel = 1;\n\td1 = bn_distsq_line3_pnt3(q0,qdir,p0);\n\td2 = bn_distsq_line3_pnt3(q0,qdir,p1);\n\td3 = bn_distsq_line3_pnt3(p0,pdir,q0);\n\td4 = bn_distsq_line3_pnt3(p0,pdir,q1);\n\tif (NEAR_ZERO(d1, tol->dist_sq) && NEAR_ZERO(d2, tol->dist_sq) &&\n\t    NEAR_ZERO(d3, tol->dist_sq) && NEAR_ZERO(d4, tol->dist_sq)) {\n\t    colinear = 1;\n\t}\n    }\n\n    VSUB2(w0, p0, q0);\n    b = VDOT(pdir, qdir);\n    d = VDOT(pdir, w0);\n    e = VDOT(qdir, w0);\n    denominator = pdir_mag_sq * qdir_mag_sq - b * b;\n\n\n    if (UNLIKELY(!parallel && colinear)) {\n\tbu_bomb(\"bn_isect_line3_line3(): logic error, lines colinear but not parallel\\n\");\n    }\n\n    if (parallel && !colinear)\n\treturn -2; /* no intersection, lines are parallel */\n\n    if (parallel && colinear) {\n\n\t/* when collinear pdist has a different meaning, it is the\n\t * distance from p0 to q0\n\t */\n\t*pdist = MAGNITUDE(w0); /* w0 is opposite direction of p0 to q0 */\n\tdot = VDOT(pdir, w0);\n\tif (dot > SMALL_FASTF) {\n\t    *pdist = -(*pdist);\n\t}\n\n\t/* when collinear qdist has a different meaning, it is the\n\t * distance from p0 to q1\n\t */\n\t*qdist = MAGNITUDE(p0_to_q1);\n\n\t/* if vectors pdir and p0_to_q1 are not the same direction\n\t * then make the distance negative\n\t */\n\tdot = VDOT(pdir, p0_to_q1);\n\tif (dot < -SMALL_FASTF) {\n\t    *qdist = -(*qdist);\n\t}\n\n\treturn 0; /* collinear intersection */\n    }\n\n    sc_numerator = (b * e - qdir_mag_sq * d);\n    tc_numerator = (pdir_mag_sq * e - b * d);\n\n    if (ZERO(denominator) && !ZERO(sc_numerator)) {\n\tdenominator = 0.0;\n\tsc = MAX_FASTF;\n    } else if (!ZERO(denominator) && ZERO(sc_numerator)) {\n\tsc_numerator = 0.0;\n\tsc = 0.0;\n    } else if (ZERO(denominator) && ZERO(sc_numerator)) {\n\tsc_numerator = 0.0;\n\tdenominator = 0.0;\n\tsc = 1.0;\n    } else {\n\tsc = sc_numerator / denominator;\n    }\n    if (ZERO(denominator) && !ZERO(tc_numerator)) {\n\tdenominator = 0.0;\n\ttc = MAX_FASTF;\n    } else if (!ZERO(denominator) && ZERO(tc_numerator)) {\n\ttc_numerator = 0.0;\n\ttc = 0.0;\n    } else if (ZERO(denominator) && ZERO(tc_numerator)) {\n\ttc_numerator = 0.0;\n\tdenominator = 0.0;\n\ttc = 1.0;\n    } else {\n\ttc = tc_numerator / denominator;\n    }\n\n    VSCALE(u_scaled, pdir, sc_numerator);\n    VSCALE(v_scaled, qdir, tc_numerator);\n    VSUB2(v_scaled_to_u_scaled, u_scaled, v_scaled);\n\n    if (ZERO(denominator)) {\n\tVSCALE(tmp_vec, v_scaled_to_u_scaled, MAX_FASTF);\n    } else {\n\tVSCALE(tmp_vec, v_scaled_to_u_scaled, 1.0/denominator);\n    }\n\n    VADD2(qc_to_pc, w0, tmp_vec);\n\n    if (MAGSQ(qc_to_pc) <= tol->dist_sq) {\n\t*pdist = sc * sqrt(pdir_mag_sq);\n\t*qdist = tc * sqrt(qdir_mag_sq);\n\treturn 1; /* intersection */\n    } else {\n\treturn -1; /* no intersection */\n    }\n}\n\n\nint\nbn_isect_line_lseg(fastf_t *t, const fastf_t *p, const fastf_t *d, const fastf_t *a, const fastf_t *b, const struct bn_tol *tol)\n{\n    vect_t ab, pa, pb;\t\t/* direction vectors a->b, p->a, p->b */\n    fastf_t ab_mag;\n    fastf_t pa_mag_sq;\n    fastf_t pb_mag_sq;\n    fastf_t d_mag_sq;\n    int code;\n    fastf_t dist1, dist2, d1, d2;\n    int colinear = 0;\n    fastf_t dot;\n\n    BN_CK_TOL(tol);\n\n    *t = 0.0;\n\n    d_mag_sq = MAGSQ(d);\n    if (UNLIKELY(NEAR_ZERO(d_mag_sq, tol->dist_sq))) {\n\tbu_bomb(\"bn_isect_line_lseg(): ray direction vector zero magnitude\\n\");\n    }\n\n    VSUB2(ab, b, a);\n    ab_mag = MAGNITUDE(ab);\n    if (ab_mag < tol->dist) {\n\t/* points A and B are not distinct */\n\treturn -4;\n    }\n\n    VSUB2(pa, a, p);\n    pa_mag_sq = MAGSQ(pa);\n    if (pa_mag_sq < tol->dist_sq) {\n\t/* Intersection at vertex A */\n\t*t = sqrt(pa_mag_sq);\n\treturn 1;\n    }\n\n    VSUB2(pb, b, p);\n    pb_mag_sq = MAGSQ(pb);\n    if (pb_mag_sq < tol->dist_sq) {\n\t/* Intersection at vertex B */\n\t*t = sqrt(pb_mag_sq);\n\treturn 2;\n    }\n\n    /* Just check that the vertices of the line segment are\n     * within distance tolerance of the ray. It may cause problems\n     * to also require the ray start and end points to be within\n     * distance tolerance of the infinite line associated with\n     * the line segment.\n     */\n    d1 = bn_distsq_line3_pnt3(p,d,a); /* distance of point a to ray */\n    d2 = bn_distsq_line3_pnt3(p,d,b); /* distance of point b to ray */\n\n    colinear = 0;\n    if (NEAR_ZERO(d1, tol->dist_sq) && NEAR_ZERO(d2, tol->dist_sq)) {\n\tcolinear = 1;\n\n\tdist1 = sqrt(pa_mag_sq);\n\tdist2 = sqrt(pb_mag_sq);\n\n\t/* if the direction of the pa vector is in the\n\t * opposite direction of the ray, then make the\n\t * distance negative\n\t */\n\tdot = VDOT(pa, d);\n\tif (dot < -SMALL_FASTF) {\n\t    dist1 = -dist1;\n\t}\n\n\t/* if the direction of the pb vector is in the\n\t * opposite direction of the ray, then make the\n\t * distance negative\n\t */\n\tdot = VDOT(pb, d);\n\tif (dot < -SMALL_FASTF) {\n\t    dist2 = -dist2;\n\t}\n    }\n\n    if (colinear && dist1 < SMALL_FASTF && dist2 < SMALL_FASTF) {\n\t/* lines are collinear but 'a' and 'b' are not on the ray */\n\treturn -1; /* no intersection */\n    }\n\n    if (colinear && (dist1 > SMALL_FASTF) && (dist2 > SMALL_FASTF)) {\n\t/* lines are collinear and both points 'a' and 'b' are on the ray. */\n\t/* return the distance to the closest point */\n\tif (dist2 > dist1) {\n\t    *t = dist1;\n\t} else {\n\t    *t = dist2;\n\t}\n\treturn 0;\n    }\n\n    if (colinear && (dist1 > SMALL_FASTF) && (dist2 < SMALL_FASTF)) {\n\t/* lines are collinear and 'a' is on the ray but 'b' is not. */\n\t/* return the distance to 'a' */\n\t*t = dist1;\n\treturn 0;\n    }\n\n    if (colinear && (dist1 < SMALL_FASTF) && (dist2 > SMALL_FASTF)) {\n\t/* lines are collinear and 'b' is on the ray but 'a' is not. */\n\t/* return the distance to 'b' */\n\t*t = dist2;\n\treturn 0;\n    }\n\n    dist1 = 0.0; /* sanity */\n    dist2 = 0.0; /* sanity */\n    code = bn_isect_line3_line3(&dist1, &dist2, p, d, a, ab, tol);\n\n    if (UNLIKELY(code == 0)) {\n\tbu_bomb(\"bn_isect_line_lseg(): we should have already detected a collinear condition\\n\");\n    }\n\n    if (code < 0) {\n\treturn -1; /* no intersection */\n    }\n\n    if (code == 1) {\n\tif (dist1 < -(tol->dist)) {\n\t    /* the ray did isect the line segment but in the\n\t     * negative direction so this is not really a hit\n\t     */\n\t    return -1; /* no intersection */\n\t}\n    }\n\n    if (code == 1) {\n\t/* determine if isect was before a, between a & b or after b */\n\tvect_t d_unit;\n\tvect_t  a_to_isect_pt, b_to_isect_pt;\n\tpoint_t isect_pt;\n\tfastf_t a_to_isect_pt_mag_sq, b_to_isect_pt_mag_sq;\n\n\tVMOVE(d_unit, d);\n\tVUNITIZE(d_unit);\n\n\tdist1 = fabs(dist1); /* sanity */\n\tVSCALE(isect_pt, d_unit, dist1);\n\tVADD2(isect_pt, isect_pt, p);\n\tVSUB2(a_to_isect_pt, isect_pt, a);\n\tVSUB2(b_to_isect_pt, isect_pt, b);\n\n\ta_to_isect_pt_mag_sq = MAGSQ(a_to_isect_pt);\n\tb_to_isect_pt_mag_sq = MAGSQ(b_to_isect_pt);\n\n\t*t = dist1;\n\n\tif (a_to_isect_pt_mag_sq < tol->dist_sq) {\n\t    /* isect at point a of line segment */\n\t    return 1;\n\t}\n\n\tif (b_to_isect_pt_mag_sq < tol->dist_sq) {\n\t    /* isect at point b of line segment */\n\t    return 2;\n\t}\n\n\tif (UNLIKELY((a_to_isect_pt_mag_sq < tol->dist_sq) && (b_to_isect_pt_mag_sq < tol->dist_sq))) {\n\t    bu_bomb(\"bn_isect_line_lseg(): this case should already been caught. i.e. zero length line segment\\n\");\n\t}\n\n\tdot = VDOT(a_to_isect_pt, ab);\n\tif (dot < -SMALL_FASTF) {\n\t    /* isect before point a of infinite line associated\n\t     * with the line segment a->b\n\t     */\n\t    return -3;\n\t}\n\n\tdot = VDOT(b_to_isect_pt, ab);\n\tif (dot > SMALL_FASTF) {\n\t    /* isect after point b of infinite line associated\n\t     * with the line segment a->b\n\t     */\n\t    return -2;\n\t}\n\n\treturn 3; /* isect on line segment a->b but\n\t\t   * not on the end points\n\t\t   */\n    }\n\n    bu_bomb(\"bn_isect_line_lseg(): logic error, should not be here\\n\");\n\n    return 0;  /* quite compiler warning */\n}\n\n\ndouble\nbn_dist_line3_pnt3(const fastf_t *pt, const fastf_t *dir, const fastf_t *a)\n{\n    vect_t f;\n    fastf_t FdotD;\n\n    if ((FdotD = MAGNITUDE(dir)) <= SMALL_FASTF) {\n\tFdotD = 0.0;\n\tgoto out;\n    }\n    VSUB2(f, a, pt);\n    FdotD = VDOT(f, dir) / FdotD;\n    FdotD = MAGSQ(f) - FdotD * FdotD;\n    if (FdotD <= SMALL_FASTF) {\n\tFdotD = 0.0;\n\tgoto out;\n    }\n    FdotD = sqrt(FdotD);\nout:\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_dist_line3_pnt3() ret=%g\\n\", FdotD);\n    }\n    return FdotD;\n}\n\n\ndouble\nbn_distsq_line3_pnt3(const fastf_t *pt, const fastf_t *dir, const fastf_t *a)\n{\n    vect_t f;\n    fastf_t FdotD;\n\n    VSUB2(f, pt, a);\n    FdotD = MAGNITUDE(dir);\n    if (ZERO(FdotD)) {\n\tFdotD = 0.0;\n\tgoto out;\n    }\n    FdotD = VDOT(f, dir) / FdotD;\n    FdotD = VDOT(f, f) - FdotD * FdotD;\n    if (FdotD < SMALL_FASTF) {\n\tFdotD = 0.0;\n    }\nout:\n    if (UNLIKELY(bu_debug & BU_DEBUG_MATH)) {\n\tbu_log(\"bn_distsq_line3_pnt3() ret=%g\\n\", FdotD);\n    }\n    return FdotD;\n}\n\n\ndouble\nbn_dist_line_origin(const fastf_t *pt, const fastf_t *dir)\n{\n    fastf_t PTdotD;\n\n    if ((PTdotD = MAGNITUDE(dir)) <= SMALL_FASTF)\n\treturn 0.0;\n    PTdotD = VDOT(pt, dir) / PTdotD;\n    if ((PTdotD = VDOT(pt, pt) - PTdotD * PTdotD) <= SMALL_FASTF)\n\treturn 0.0;\n    return sqrt(PTdotD);\n}\n\n\ndouble\nbn_dist_line2_pnt2(const fastf_t *pt, const fastf_t *dir, const fastf_t *a)\n{\n    vect_t f;\n    fastf_t FdotD;\n\n    V2SUB2(f, pt, a);\n    if ((FdotD = sqrt(MAG2SQ(dir))) <= SMALL_FASTF)\n\treturn 0.0;\n    FdotD = V2DOT(f, dir) / FdotD;\n    if ((FdotD = V2DOT(f, f) - FdotD * FdotD) <= SMALL_FASTF)\n\treturn 0.0;\n    return sqrt(FdotD);\n}\n\n\ndouble\nbn_distsq_line2_point2(const fastf_t *pt, const fastf_t *dir, const fastf_t *a)\n{\n    vect_t f;\n    fastf_t FdotD;\n\n    V2SUB2(f, pt, a);\n    if ((FdotD = sqrt(MAG2SQ(dir))) <= SMALL_FASTF)\n\treturn 0.0;\n    FdotD = V2DOT(f, dir) / FdotD;\n    if ((FdotD = V2DOT(f, f) - FdotD * FdotD) <= SMALL_FASTF)\n\treturn 0.0;\n    return FdotD;\n}\n\n\ndouble\nbn_area_of_triangle(const fastf_t *a, const fastf_t *b, const fastf_t *c)\n{\n    double t;\n    double area;\n\n    t =\ta[Y] * (b[Z] - c[Z]) -\n\tb[Y] * (a[Z] - c[Z]) +\n\tc[Y] * (a[Z] - b[Z]);\n    area  = t*t;\n    t =\ta[Z] * (b[X] - c[X]) -\n\tb[Z] * (a[X] - c[X]) +\n\tc[Z] * (a[X] - b[X]);\n    area += t*t;\n    t = \ta[X] * (b[Y] - c[Y]) -\n\tb[X] * (a[Y] - c[Y]) +\n\tc[X] * (a[Y] - b[Y]);\n    area += t*t;\n\n    return 0.5 * sqrt(area);\n}\n\n\nint\nbn_isect_pnt_lseg(fastf_t *dist,\n\t\t  const fastf_t *a,\n\t\t  const fastf_t *b,\n\t\t  const fastf_t *p,\n\t\t  const struct bn_tol *tol)\n{\n    vect_t AtoP, BtoP, AtoB, ABunit; /* unit vector from A to B */\n    fastf_t APprABunit;\t/* Mag of projection of AtoP onto ABunit */\n    fastf_t distsq;\n\n    BN_CK_TOL(tol);\n\n    VSUB2(AtoP, p, a);\n    if (MAGSQ(AtoP) < tol->dist_sq)\n\treturn 1;\t/* P at A */\n\n    VSUB2(BtoP, p, b);\n    if (MAGSQ(BtoP) < tol->dist_sq)\n\treturn 2;\t/* P at B */\n\n    VSUB2(AtoB, b, a);\n    VMOVE(ABunit, AtoB);\n    distsq = MAGSQ(ABunit);\n    if (distsq < tol->dist_sq)\n\treturn -1;\t/* A equals B, and P isn't there */\n    distsq = 1/sqrt(distsq);\n    VSCALE(ABunit, ABunit, distsq);\n\n    /* Similar to bn_dist_line_pnt(), except we never actually have to\n     * do the sqrt that the other routine does.\n     */\n\n    /* find dist as a function of ABunit, actually the projection of\n     * AtoP onto ABunit\n     */\n    APprABunit = VDOT(AtoP, ABunit);\n\n    /* because of pythgorean theorem ... */\n    distsq = MAGSQ(AtoP) - APprABunit * APprABunit;\n    if (distsq > tol->dist_sq)\n\treturn -1;\t/* dist pnt to line too large */\n\n    /* Distance from the point to the line is within tolerance. */\n    *dist = VDOT(AtoP, AtoB) / MAGSQ(AtoB);\n\n    if (*dist > 1.0 || *dist < -SMALL_FASTF)\t/* P outside AtoB */\n\treturn -2;\n\n    return 3;\t/* P on AtoB */\n}\n\n\n/**\n * @param dist is distance along line from A to P\n * @param a is line start point\n * @param b is line end point\n * @param p is line intersect point\n * @param tol contains the tolerances used for calculations\n */\nint\nbn_isect_pnt2_lseg2(fastf_t *dist, const fastf_t *a, const fastf_t *b, const fastf_t *p, const struct bn_tol *tol)\n{\n    vect_t AtoP,\n\tBtoP,\n\tAtoB,\n\tABunit;\t/* unit vector from A to B */\n    fastf_t APprABunit;\t/* Mag of projection of AtoP onto ABunit */\n    fastf_t distsq;\n\n    BN_CK_TOL(tol);\n\n    V2SUB2(AtoP, p, a);\n    if (MAG2SQ(AtoP) < tol->dist_sq)\n\treturn 1;\t/* P at A */\n\n    V2SUB2(BtoP, p, b);\n    if (MAG2SQ(BtoP) < tol->dist_sq)\n\treturn 2;\t/* P at B */\n\n    V2SUB2(AtoB, b, a);\n    V2MOVE(ABunit, AtoB);\n    distsq = MAG2SQ(ABunit);\n    if (distsq < tol->dist_sq) {\n\tif (bu_debug & BU_DEBUG_MATH) {\n\t    bu_log(\"distsq A=%g\\n\", distsq);\n\t}\n\treturn -1;\t/* A equals B, and P isn't there */\n    }\n    distsq = 1/sqrt(distsq);\n    V2SCALE(ABunit, ABunit, distsq);\n\n    /* Similar to bn_dist_line_pt, except we never actually have to do\n     * the sqrt that the other routine does.\n     */\n\n    /* find dist as a function of ABunit, actually the projection of\n     * AtoP onto ABunit\n     */\n    APprABunit = V2DOT(AtoP, ABunit);\n\n    /* because of pythgorean theorem ... */\n    distsq = MAG2SQ(AtoP) - APprABunit * APprABunit;\n    if (distsq > tol->dist_sq) {\n\tif (bu_debug & BU_DEBUG_MATH) {\n\t    V2PRINT(\"ABunit\", ABunit);\n\t    bu_log(\"distsq B=%g\\n\", distsq);\n\t}\n\treturn -1;\t/* dist pt to line too large */\n    }\n\n    /* Distance from the point to the line is within tolerance. */\n    *dist = V2DOT(AtoP, AtoB) / MAG2SQ(AtoB);\n\n    if (*dist > 1.0 || *dist < 0.0)\t/* P outside AtoB */\n\treturn -2;\n\n    return 3;\t/* P on AtoB */\n}\n\n\n/**\n * This is a support function for the test function\n * \"bn_distsq_pnt3_lseg3_v2\".\n */\nHIDDEN int\nare_equal(fastf_t a_in, fastf_t b_in, fastf_t t)\n{\n    fastf_t ai, af, bi, bf, a, b;\n    int ret = 0;\n\n    /* hack to deal with possible underlying types for fastf_t */\n    if (sizeof(fastf_t) == sizeof(float)) {\n\ta = nextafterf((float)a_in, (float)b_in);\n\tb = nextafterf((float)b_in, (float)a_in);\n\taf = modff((float)a, (float *)&ai);\n\tbf = modff((float)b, (float *)&bi);\n    } else if (sizeof(fastf_t) == sizeof(double)) {\n\ta = nextafter((double)a_in, (double)b_in);\n\tb = nextafter((double)b_in, (double)a_in);\n\taf = modf((double)a, (double *)&ai);\n\tbf = modf((double)b, (double *)&bi);\n    } else {\n\tbu_bomb(\"are_equal(): unexpect size for type fastf_t\");\n    }\n\n    if (EQUAL(ai, bi)) {\n\tif (NEAR_EQUAL(af, bf, t)) {\n\t    ret = 1;\n\t}\n    } else {\n\tif (NEAR_EQUAL(a, b, t)) {\n\t    ret = 1;\n\t}\n    }\n\n    return ret;\n}\n\n\nint\nbn_distsq_pnt3_lseg3_v2(fastf_t *dist_sq_out, const fastf_t *a, const fastf_t *b, const fastf_t *p, const struct bn_tol *tol)\n{\n    vect_t AtoB, BtoP;\n    vect_t AtoP = VINIT_ZERO;\n    fastf_t AtoB_mag_sq, AtoP_mag_sq, AtoPCA_mag_sq, PtoPCA_mag_sq, BtoP_mag_sq;\n    fastf_t dot, dt, dist_sq;\n    int ret;\n    int flip;\n\n    dt = tol->dist_sq;\n\n    flip = 0;\n    if (bn_pnt3_pnt3_equal(a, b, tol)) {\n\t/* (A=B) */\n\tif (bn_pnt3_pnt3_equal(a, p, tol)) {\n\t    /* (A=B) (A=P) (B=P) */\n\t    dist_sq = 0.0;\n\t    ret = 1;\n\t} else {\n\t    /* (A=B) (A!=P) */\n\t    dist_sq = MAGSQ(AtoP);\n\t    ret = 3;\n\t}\n    } else {\n\t/* (A!=B) */\n\tif (bn_pnt3_pnt3_equal(a, p, tol)) {\n\t    /* (A!=B) (A=P) */\n\t    dist_sq = 0.0;\n\t    ret = 1;\n\t} else if (bn_pnt3_pnt3_equal(b, p, tol)) {\n\t    /* (A!=B) (B=P) */\n\t    dist_sq = 0.0;\n\t    ret = 2;\n\t} else {\n\t    /* (A!=B) (A!=P) (B!=P) */\n\t    VSUB2(AtoB, b, a);\n\t    VSUB2(AtoP, p, a);\n\t    VSUB2(BtoP, p, b);\n\n\t    dot = VDOT(AtoP, AtoB);\n\n\t    if (ZERO(dot)) {\n\t\t/* dot product undefined with (AtoP dot AtoB) */\n\t\t/* try flipping A and B */\n\t\tVSUB2(AtoB, a, b);\n\t\tVSUB2(AtoP, p, b);\n\t\tVSUB2(BtoP, p, a);\n\t\tdot = VDOT(AtoP, AtoB);\n\t\tflip = 1;\n\t    }\n\t    if (ZERO(dot)) {\n\t\tbu_bomb(\"bn_distsq_pnt3_lseg3_v2(): failed\");\n\t    }\n\n\t    AtoB_mag_sq = MAGSQ(AtoB);\n\t    AtoP_mag_sq = MAGSQ(AtoP);\n\t    BtoP_mag_sq = MAGSQ(BtoP);\n\n\t    if (dot > SMALL_FASTF) {\n\t\tAtoPCA_mag_sq = (dot * dot) / AtoB_mag_sq;\n\t\tif (are_equal(AtoPCA_mag_sq, 0.0, dt)) {\n\t\t    /* (PCA=A) (B!=P) */\n\t\t    /* lsegs AtoB and AtoP are perpendicular */\n\t\t    dist_sq = AtoP_mag_sq;\n\t\t    ret = 3;\n\t\t} else if (are_equal(AtoPCA_mag_sq, AtoB_mag_sq, dt)) {\n\t\t    /* (PCA=B) (B!=P) */\n\t\t    dist_sq = BtoP_mag_sq;\n\t\t    ret = 4;\n\t\t} else if (AtoPCA_mag_sq < AtoB_mag_sq) {\n\t\t    /* (PCA!=A) (PCA!=B) (B!=P) */\n\t\t    /* PCA is on lseg AtoB */\n\t\t    PtoPCA_mag_sq = fabs(AtoP_mag_sq - AtoPCA_mag_sq);\n\n\t\t    if (PtoPCA_mag_sq < dt) {\n\t\t\t/* P is on lseg AtoB */\n\t\t\tdist_sq = 0.0;\n\t\t\tret = 0;\n\t\t    } else {\n\t\t\tdist_sq = PtoPCA_mag_sq;\n\t\t\tret = 5;\n\t\t    }\n\t\t} else {\n\t\t    /* AtoPCA_mag > AtoB_mag */\n\t\t    /* P is to the right of B, above/below lseg AtoB. */\n\t\t    /* both P and PCA and not within tolerance of lseg AtoB */\n\t\t    dist_sq = BtoP_mag_sq;\n\t\t    ret = 4;\n\t\t}\n\t    } else {\n\t\t/* dot is neg */\n\t\tAtoPCA_mag_sq = (dot * dot) / AtoB_mag_sq;\n\t\tif (AtoPCA_mag_sq < dt) {\n\t\t    /* (PCA=A), lsegs AtoB and AtoP are perpendicular */\n\t\t    dist_sq = AtoP_mag_sq;\n\t\t    ret = 3;\n\t\t} else {\n\t\t    /* (PCA!=A), PCA is not on lseg AtoB */\n\t\t    /* both P and PCA and not within tolerance of lseg AtoB */\n\t\t    dist_sq = AtoP_mag_sq;\n\t\t    ret = 3;\n\t\t}\n\t    }\n\t}\n    }\n\n    if (flip && ret == 3) {\n\tret = 4;\n    } else if (flip && ret == 4) {\n\tret = 3;\n    }\n\n    *dist_sq_out = dist_sq;\n    return ret;\n}\n\n\nint\nbn_dist_pnt3_lseg3(fastf_t *dist,\n\t\t  fastf_t *pca,\n\t\t  const fastf_t *a,\n\t\t  const fastf_t *b,\n\t\t  const fastf_t *p,\n\t\t  const struct bn_tol *tol)\n{\n    vect_t PtoA;\t\t/* P-A */\n    vect_t PtoB;\t\t/* P-B */\n    vect_t AtoB;\t\t/* B-A */\n    fastf_t P_A_sq;\t\t/* |P-A|**2 */\n    fastf_t P_B_sq;\t\t/* |P-B|**2 */\n    fastf_t B_A;\t\t/* |B-A| */\n    fastf_t t;\t\t/* distance along ray of projection of P */\n\n    BN_CK_TOL(tol);\n\n    if (UNLIKELY(bu_debug & BU_DEBUG_MATH)) {\n\tbu_log(\"bn_dist_pnt3_lseg3() a=(%g, %g, %g) b=(%g, %g, %g)\\n\\tp=(%g, %g, %g), tol->dist=%g sq=%g\\n\",\n\t       V3ARGS(a),\n\t       V3ARGS(b),\n\t       V3ARGS(p),\n\t       tol->dist, tol->dist_sq);\n    }\n\n    /* Check proximity to endpoint A */\n    VSUB2(PtoA, p, a);\n    if ((P_A_sq = MAGSQ(PtoA)) < tol->dist_sq) {\n\t/* P is within the tol->dist radius circle around A */\n\tVMOVE(pca, a);\n\tif (UNLIKELY(bu_debug & BU_DEBUG_MATH)) bu_log(\"  at A\\n\");\n\t*dist = 0.0;\n\treturn 1;\n    }\n\n    /* Check proximity to endpoint B */\n    VSUB2(PtoB, p, b);\n    if ((P_B_sq = MAGSQ(PtoB)) < tol->dist_sq) {\n\t/* P is within the tol->dist radius circle around B */\n\tVMOVE(pca, b);\n\tif (UNLIKELY(bu_debug & BU_DEBUG_MATH)) bu_log(\"  at B\\n\");\n\t*dist = 0.0;\n\treturn 2;\n    }\n\n    VSUB2(AtoB, b, a);\n    B_A = sqrt(MAGSQ(AtoB));\n\n    /* compute distance (in actual units) along line to PROJECTION of\n     * point p onto the line: point pca\n     */\n    t = VDOT(PtoA, AtoB) / B_A;\n    if (UNLIKELY(bu_debug & BU_DEBUG_MATH)) {\n\tbu_log(\"bn_dist_pnt3_lseg3() B_A=%g, t=%g\\n\",\n\t       B_A, t);\n    }\n\n    if (t <= SMALL_FASTF) {\n\t/* P is \"left\" of A */\n\tif (UNLIKELY(bu_debug & BU_DEBUG_MATH)) bu_log(\"  left of A\\n\");\n\tVMOVE(pca, a);\n\t*dist = sqrt(P_A_sq);\n\treturn 3;\n    }\n    if (t < B_A) {\n\t/* PCA falls between A and B */\n\tfastf_t dsq;\n\tfastf_t param_dist;\t/* parametric dist */\n\n\t/* Find PCA */\n\tparam_dist = t / B_A;\t\t/* Range 0..1 */\n\tVJOIN1(pca, a, param_dist, AtoB);\n\n\t/* Find distance from PCA to line segment (Pythagoras) */\n\tif ((dsq = P_A_sq - t * t) <= tol->dist_sq) {\n\t    if (UNLIKELY(bu_debug & BU_DEBUG_MATH)) bu_log(\"  ON lseg\\n\");\n\t    /* Distance from PCA to lseg is zero, give param instead */\n\t    *dist = param_dist;\t/* special! */\n\t    return 0;\n\t}\n\tif (UNLIKELY(bu_debug & BU_DEBUG_MATH)) bu_log(\"  closest to lseg\\n\");\n\t*dist = sqrt(dsq);\n\treturn 5;\n    }\n    /* P is \"right\" of B */\n    if (UNLIKELY(bu_debug & BU_DEBUG_MATH)) bu_log(\"  right of B\\n\");\n    VMOVE(pca, b);\n    *dist = sqrt(P_B_sq);\n    return 4;\n}\n\n\nint\nbn_dist_pnt2_lseg2(fastf_t *dist_sq, fastf_t *pca, const fastf_t *a, const fastf_t *b, const fastf_t *p, const struct bn_tol *tol)\n{\n    vect_t PtoA;\t\t/* P-A */\n    vect_t PtoB;\t\t/* P-B */\n    vect_t AtoB;\t\t/* B-A */\n    fastf_t P_A_sq;\t\t/* |P-A|**2 */\n    fastf_t P_B_sq;\t\t/* |P-B|**2 */\n    fastf_t B_A;\t\t/* |B-A| */\n    fastf_t t;\t\t/* distance along ray of projection of P */\n\n    BN_CK_TOL(tol);\n\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_dist_pnt3_lseg3() a=(%g, %g, %g) b=(%g, %g, %g)\\n\\tp=(%g, %g, %g), tol->dist=%g sq=%g\\n\",\n\t       V3ARGS(a),\n\t       V3ARGS(b),\n\t       V3ARGS(p),\n\t       tol->dist, tol->dist_sq);\n    }\n\n\n    /* Check proximity to endpoint A */\n    V2SUB2(PtoA, p, a);\n    if ((P_A_sq = MAG2SQ(PtoA)) < tol->dist_sq) {\n\t/* P is within the tol->dist radius circle around A */\n\tV2MOVE(pca, a);\n\tif (bu_debug & BU_DEBUG_MATH) bu_log(\"  at A\\n\");\n\t*dist_sq = 0.0;\n\treturn 1;\n    }\n\n    /* Check proximity to endpoint B */\n    V2SUB2(PtoB, p, b);\n    if ((P_B_sq = MAG2SQ(PtoB)) < tol->dist_sq) {\n\t/* P is within the tol->dist radius circle around B */\n\tV2MOVE(pca, b);\n\tif (bu_debug & BU_DEBUG_MATH) bu_log(\"  at B\\n\");\n\t*dist_sq = 0.0;\n\treturn 2;\n    }\n\n    V2SUB2(AtoB, b, a);\n    B_A = sqrt(MAG2SQ(AtoB));\n\n    /* compute distance (in actual units) along line to PROJECTION of\n     * point p onto the line: point pca\n     */\n    t = V2DOT(PtoA, AtoB) / B_A;\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_dist_pnt3_lseg3() B_A=%g, t=%g\\n\",\n\t       B_A, t);\n    }\n\n    if (t <= 0) {\n\t/* P is \"left\" of A */\n\tif (bu_debug & BU_DEBUG_MATH) bu_log(\"  left of A\\n\");\n\tV2MOVE(pca, a);\n\t*dist_sq = P_A_sq;\n\treturn 3;\n    }\n    if (t < B_A) {\n\t/* PCA falls between A and B */\n\tfastf_t dsq;\n\tfastf_t param_dist;\t/* parametric dist */\n\n\t/* Find PCA */\n\tparam_dist = t / B_A;\t\t/* Range 0..1 */\n\tV2JOIN1(pca, a, param_dist, AtoB);\n\n\t/* Find distance from PCA to line segment (Pythagoras) */\n\tif ((dsq = P_A_sq - t * t) <= tol->dist_sq) {\n\t    if (bu_debug & BU_DEBUG_MATH) bu_log(\"  ON lseg\\n\");\n\t    /* Distance from PCA to lseg is zero, give param instead */\n\t    *dist_sq = param_dist;\t/* special! Not squared. */\n\t    return 0;\n\t}\n\tif (bu_debug & BU_DEBUG_MATH) bu_log(\"  closest to lseg\\n\");\n\t*dist_sq = dsq;\n\treturn 5;\n    }\n    /* P is \"right\" of B */\n    if (bu_debug & BU_DEBUG_MATH) bu_log(\"  right of B\\n\");\n    V2MOVE(pca, b);\n    *dist_sq = P_B_sq;\n    return 4;\n}\n\n\nvoid\nbn_rotate_bbox(fastf_t *omin, fastf_t *omax, const fastf_t *mat, const fastf_t *imin, const fastf_t *imax)\n{\n    point_t local;\t\t/* vertex point in local coordinates */\n    point_t model;\t\t/* vertex point in model coordinates */\n\n#define ROT_VERT(a, b, c) {\t\t\t\\\n\tVSET(local, a[X], b[Y], c[Z]);\t\t\\\n\tMAT4X3PNT(model, mat, local);\t\t\\\n\tVMINMAX(omin, omax, model);\t\t\\\n    }\n\n    ROT_VERT(imin, imin, imin);\n    ROT_VERT(imin, imin, imax);\n    ROT_VERT(imin, imax, imin);\n    ROT_VERT(imin, imax, imax);\n    ROT_VERT(imax, imin, imin);\n    ROT_VERT(imax, imin, imax);\n    ROT_VERT(imax, imax, imin);\n    ROT_VERT(imax, imax, imax);\n#undef ROT_VERT\n}\n\n\nvoid\nbn_rotate_plane(fastf_t *oplane, const fastf_t *mat, const fastf_t *iplane)\n{\n    point_t orig_pt;\n    point_t new_pt;\n\n    /* First, pick a point that lies on the original halfspace */\n    VSCALE(orig_pt, iplane, iplane[3]);\n\n    /* Transform the surface normal */\n    MAT4X3VEC(oplane, mat, iplane);\n\n    /* Transform the point from original to new halfspace */\n    MAT4X3PNT(new_pt, mat, orig_pt);\n\n    /*\n     * The transformed normal is all that is required.\n     * The new distance is found from the transformed point on the plane.\n     */\n    oplane[3] = VDOT(new_pt, oplane);\n}\n\n\nint\nbn_coplanar(const fastf_t *a, const fastf_t *b, const struct bn_tol *tol)\n{\n    fastf_t dot;\n    vect_t pt_a, pt_b;\n    BN_CK_TOL(tol);\n\n    if (!NEAR_EQUAL(MAGSQ(a), 1.0, VUNITIZE_TOL) || !NEAR_EQUAL(MAGSQ(b), 1.0, VUNITIZE_TOL)) {\n\tbu_bomb(\"bn_coplanar(): input vector(s) 'a' and/or 'b' is not a unit vector.\\n\");\n    }\n\n    VSCALE(pt_a, a, fabs(a[W]));\n    VSCALE(pt_b, b, fabs(b[W]));\n    dot = VDOT(a, b);\n\n    if (NEAR_ZERO(dot, tol->perp)) {\n\treturn 0; /* planes are perpendicular */\n    }\n\n    /* parallel is when dot is within tol->perp of either -1 or 1 */\n    if ((dot <= -SMALL_FASTF) ? (NEAR_EQUAL(dot, -1.0, tol->perp)) : (NEAR_EQUAL(dot, 1.0, tol->perp))) {\n\tif (bn_pnt3_pnt3_equal(pt_a, pt_b, tol)) {\n\t    /* true when planes are coplanar */\n\t    if (dot >= SMALL_FASTF) {\n\t\t/* true when plane normals in same direction */\n\t\treturn 1;\n\t    } else {\n\t\t/* true when plane normals in opposite direction */\n\t\treturn 2;\n\t    }\n\t} else {\n\t    return -1;\n\t}\n    }\n    return 0;\n}\n\n\ndouble\nbn_angle_measure(fastf_t *vec, const fastf_t *x_dir, const fastf_t *y_dir)\n{\n    fastf_t xproj, yproj;\n    fastf_t gam;\n    fastf_t ang;\n\n    xproj = -VDOT(vec, x_dir);\n    yproj = -VDOT(vec, y_dir);\n    gam = atan2(yproj, xproj);\t/* -pi..+pi */\n    ang = M_PI + gam;\t\t/* 0..+2pi */\n    if (ang < -SMALL_FASTF) {\n\tdo {\n\t    ang += M_2PI;\n\t} while (ang < -SMALL_FASTF);\n    } else if (ang > M_2PI) {\n\tdo {\n\t    ang -= M_2PI;\n\t} while (ang > M_2PI);\n    }\n    if (UNLIKELY(ang < -SMALL_FASTF || ang > M_2PI))\n\tbu_bomb(\"bn_angle_measure() angle out of range\\n\");\n\n    return ang;\n}\n\n\ndouble\nbn_dist_pnt3_along_line3(const fastf_t *p, const fastf_t *d, const fastf_t *x)\n{\n    vect_t x_p;\n\n    VSUB2(x_p, x, p);\n    return VDOT(x_p, d);\n}\n\n\ndouble\nbn_dist_pnt2_along_line2(const fastf_t *p, const fastf_t *d, const fastf_t *x)\n{\n    vect_t x_p;\n    double ret;\n\n    V2SUB2(x_p, x, p);\n    ret = V2DOT(x_p, d);\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_dist_pnt2_along_line2() p=(%g, %g), d=(%g, %g), x=(%g, %g) ret=%g\\n\",\n\t       V2ARGS(p),\n\t       V2ARGS(d),\n\t       V2ARGS(x),\n\t       ret);\n    }\n    return ret;\n}\n\n\nint\nbn_between(double left, double mid, double right, const struct bn_tol *tol)\n{\n    BN_CK_TOL(tol);\n\n    if (left < right) {\n\tif (NEAR_EQUAL(left, right, tol->dist*0.1)) {\n\t    left -= tol->dist*0.1;\n\t    right += tol->dist*0.1;\n\t}\n\tif (mid < left || mid > right) goto fail;\n\treturn 1;\n    }\n    /* The 'right' value is lowest */\n    if (NEAR_EQUAL(left, right, tol->dist*0.1)) {\n\tright -= tol->dist*0.1;\n\tleft += tol->dist*0.1;\n    }\n    if (mid < right || mid > left) goto fail;\n    return 1;\nfail:\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_between(%.17e, %.17e, %.17e) ret=0 FAIL\\n\",\n\t       left, mid, right);\n    }\n    return 0;\n}\n\n\nint\nbn_does_ray_isect_tri(\n    const point_t pt,\n    const vect_t dir,\n    const point_t V,\n    const point_t A,\n    const point_t B,\n    point_t inter)\t\t\t/* output variable */\n{\n    vect_t VP, VA, VB, AB, AP, N;\n    fastf_t NdotDir;\n    plane_t pl;\n    fastf_t dist;\n\n    /* intersect with plane */\n\n    VSUB2(VA, A, V);\n    VSUB2(VB, B, V);\n    VCROSS(pl, VA, VB);\n    VUNITIZE(pl);\n\n    NdotDir = VDOT(pl, dir);\n    if (ZERO(NdotDir))\n\treturn 0;\n\n    pl[W] = VDOT(pl, V);\n\n    dist = (pl[W] - VDOT(pl, pt))/NdotDir;\n    VJOIN1(inter, pt, dist, dir);\n\n    /* determine if point is within triangle */\n    VSUB2(VP, inter, V);\n    VCROSS(N, VA, VP);\n    if (VDOT(N, pl) < 0.0)\n\treturn 0;\n\n    VCROSS(N, VP, VB);\n    if (VDOT(N, pl) < 0.0)\n\treturn 0;\n\n    VSUB2(AB, B, A);\n    VSUB2(AP, inter, A);\n    VCROSS(N, AB, AP);\n    if (VDOT(N, pl) < 0.0)\n\treturn 0;\n\n    return 1;\n}\n\n\nint\nbn_hlf_class(const fastf_t *half_eqn, const fastf_t *min, const fastf_t *max, const struct bn_tol *tol)\n{\n    int current_classification;\n    fastf_t d;\n\n#define CHECK_PT(x, y, z)\t\t\t\t\t\\\n    d = (x)*half_eqn[0] + (y)*half_eqn[1] + (z)*half_eqn[2] - half_eqn[3]; \\\n    if (d < -tol->dist) {\t\t\t\t\t\\\n\tif (current_classification == BN_CLASSIFY_OUTSIDE)\t\\\n\t    return BN_CLASSIFY_OVERLAPPING;\t\t\t\\\n\telse current_classification = BN_CLASSIFY_INSIDE;\t\\\n    } else if (d > tol->dist) {\t\t\t\t\t\\\n\tif (current_classification == BN_CLASSIFY_INSIDE)\t\\\n\t    return BN_CLASSIFY_OVERLAPPING;\t\t\t\\\n\telse current_classification = BN_CLASSIFY_OUTSIDE;\t\\\n    } else return BN_CLASSIFY_OVERLAPPING\n\n    current_classification = BN_CLASSIFY_UNIMPLEMENTED;\n    CHECK_PT(min[X], min[Y], min[Z]);\n    CHECK_PT(min[X], min[Y], max[Z]);\n    CHECK_PT(min[X], max[Y], min[Z]);\n    CHECK_PT(min[X], max[Y], max[Z]);\n    CHECK_PT(max[X], min[Y], min[Z]);\n    CHECK_PT(max[X], min[Y], max[Z]);\n    CHECK_PT(max[X], max[Y], min[Z]);\n    CHECK_PT(max[X], max[Y], max[Z]);\n    if (current_classification == BN_CLASSIFY_UNIMPLEMENTED)\n\tbu_log(\"bn_hlf_class: error in implementation\\\nmin = (%g, %g, %g), max = (%g, %g, %g), half_eqn = (%g, %g, %g, %g)\\n\",\n\t       V3ARGS(min), V3ARGS(max), V3ARGS(half_eqn),\n\t       half_eqn[3]);\n    return current_classification;\n}\n\n\nint\nbn_distsq_line3_line3(fastf_t *dist, fastf_t *P, fastf_t *d_in, fastf_t *Q, fastf_t *e_in, fastf_t *pt1, fastf_t *pt2)\n{\n    fastf_t de, denom;\n    vect_t diff, PmQ, tmp;\n    vect_t d, e;\n    fastf_t len_e, inv_len_e, len_d, inv_len_d;\n    int ret=0;\n\n    len_e = MAGNITUDE(e_in);\n    if (ZERO(len_e))\n\tbu_bomb(\"bn_distsq_line3_line3() called with zero length vector\\n\");\n    inv_len_e = 1.0 / len_e;\n\n    len_d = MAGNITUDE(d_in);\n    if (ZERO(len_d))\n\tbu_bomb(\"bn_distsq_line3_line3() called with zero length vector\\n\");\n    inv_len_d = 1.0 / len_d;\n\n    VSCALE(e, e_in, inv_len_e);\n    VSCALE(d, d_in, inv_len_d);\n    de = VDOT(d, e);\n\n    if (ZERO(de)) {\n\t/* lines are perpendicular */\n\tdist[0] = VDOT(Q, d) - VDOT(P, d);\n\tdist[1] = VDOT(P, e) - VDOT(Q, e);\n    } else {\n\tVSUB2(PmQ, P, Q);\n\tdenom = 1.0 - de*de;\n\tif (ZERO(denom)) {\n\t    /* lines are parallel */\n\t    dist[0] = 0.0;\n\t    dist[1] = VDOT(PmQ, d);\n\t    ret = 1;\n\t} else {\n\t    VBLEND2(tmp, 1.0, e, -de, d);\n\t    dist[1] = VDOT(PmQ, tmp)/denom;\n\t    dist[0] = dist[1] * de - VDOT(PmQ, d);\n\t}\n    }\n    VJOIN1(pt1, P, dist[0], d);\n    VJOIN1(pt2, Q, dist[1], e);\n    VSUB2(diff, pt1, pt2);\n    dist[0] *= inv_len_d;\n    dist[1] *= inv_len_e;\n    dist[2] =  MAGSQ(diff);\n    return ret;\n}\n\n\nint\nbn_isect_planes(fastf_t *pt, const fastf_t (*planes)[4], const size_t pl_count)\n{\n    mat_t matrix;\n    mat_t inverse;\n    vect_t hpq;\n    fastf_t det;\n    size_t i;\n\n    if (bu_debug & BU_DEBUG_MATH) {\n\tbu_log(\"bn_isect_planes:\\n\");\n\tfor (i=0; i<pl_count; i++) {\n\t    bu_log(\"Plane #%zu (%f %f %f %f)\\n\", i, V4ARGS(planes[i]));\n\t}\n    }\n\n    MAT_ZERO(matrix);\n    VSET(hpq, 0.0, 0.0, 0.0);\n\n    for (i=0; i<pl_count; i++) {\n\tmatrix[0] += planes[i][X] * planes[i][X];\n\tmatrix[5] += planes[i][Y] * planes[i][Y];\n\tmatrix[10] += planes[i][Z] * planes[i][Z];\n\tmatrix[1] += planes[i][X] * planes[i][Y];\n\tmatrix[2] += planes[i][X] * planes[i][Z];\n\tmatrix[6] += planes[i][Y] * planes[i][Z];\n\thpq[X] += planes[i][X] * planes[i][H];\n\thpq[Y] += planes[i][Y] * planes[i][H];\n\thpq[Z] += planes[i][Z] * planes[i][H];\n    }\n\n    matrix[4] = matrix[1];\n    matrix[8] = matrix[2];\n    matrix[9] = matrix[6];\n    matrix[15] = 1.0;\n\n    /* Check that we don't have a singular matrix */\n    det = bn_mat_determinant(matrix);\n    if (ZERO(det))\n\treturn 1;\n\n    bn_mat_inv(inverse, matrix);\n\n    MAT4X3PNT(pt, inverse, hpq);\n\n    return 0;\n\n}\n\n\nint\nbn_lseg3_lseg3_parallel(const point_t sg1pt1, const point_t sg1pt2,\n\t\t\tconst point_t sg2pt1, const point_t sg2pt2,\n\t\t\tconst struct bn_tol *tol)\n{\n    vect_t e_dif[2]    = {{0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}};\n    vect_t e_dif_a[2]  = {{0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}};\n    fastf_t e_rr[2][3] = {{0.0, 0.0, 0.0}, {0.0, 0.0, 0.0}};\n    char e_sc[2][3] = {{0, 0, 0}, {0, 0, 0}};\n    fastf_t dist = tol->dist;\n    fastf_t tmp;\n    int i, j;\n\n    VSUB2(e_dif[0], sg1pt2, sg1pt1);\n    VSUB2(e_dif[1], sg2pt2, sg2pt1);\n\n    for ( i = 0 ; i < 2 ; i++ ) {\n\tfor ( j = 0 ; j < 3 ; j++ ) {\n\t    e_dif_a[i][j] = fabs(e_dif[i][j]);\n\t}\n    }\n\n    for ( i = 0 ; i < 2 ; i++ ) {\n\tif ((e_dif_a[i][X] < dist) && (e_dif_a[i][Y] > dist)) {\n\t    e_sc[i][0] = 1;\n\t} else if ((e_dif_a[i][X] > dist) && (e_dif_a[i][Y] < dist)) {\n\t    e_sc[i][0] = 2;\n\t} else if ((e_dif_a[i][X] < dist) && (e_dif_a[i][Y] < dist)) {\n\t    e_sc[i][0] = 3;\n\t} else {\n\t    e_rr[i][0] = e_dif[i][Y] / e_dif[i][X];\n\t    e_sc[i][0] = 0;\n\t}\n\tif ((e_dif_a[i][X] < dist) && (e_dif_a[i][Z] > dist)) {\n\t    e_sc[i][1] = 1;\n\t} else if ((e_dif_a[i][X] > dist) && (e_dif_a[i][Z] < dist)) {\n\t    e_sc[i][1] = 2;\n\t} else if ((e_dif_a[i][X] < dist) && (e_dif_a[i][Z] < dist)) {\n\t    e_sc[i][1] = 3;\n\t} else {\n\t    e_rr[i][1] = e_dif[i][Z] / e_dif[i][X];\n\t    e_sc[i][1] = 0;\n\t}\n\tif ((e_dif_a[i][Y] < dist) && (e_dif_a[i][Z] > dist)) {\n\t    e_sc[i][2] = 1;\n\t} else if ((e_dif_a[i][Y] > dist) && (e_dif_a[i][Z] < dist)) {\n\t    e_sc[i][2] = 2;\n\t} else if ((e_dif_a[i][Y] < dist) && (e_dif_a[i][Z] < dist)) {\n\t    e_sc[i][2] = 3;\n\t} else {\n\t    e_rr[i][2] = e_dif[i][Z] / e_dif[i][Y];\n\t    e_sc[i][2] = 0;\n\t}\n    }\n\n    /* loop thru (rise/run) ratios from xy, xz and yz planes */\n    for ( i = 0 ; i < 3 ; i++ ) {\n\tif (e_sc[0][i] != e_sc[1][i]) {\n\t    return 0;\n\t}\n\tif (e_sc[0][i] == 0) {\n\t    tmp = e_rr[0][i] - e_rr[1][i];\n\t    if (fabs(tmp) > dist) {\n\t\treturn 0;\n\t    }\n\t}\n    }\n\n    return 1;\n}\n\n// Use SVD algorithm from Soderkvist to fit a plane to vertex points\n// http://www.math.ltu.se/~jove/courses/mam208/svd.pdf\nextern \"C\" int\nbn_fit_plane(point_t *c, vect_t *n, int npnts, point_t *pnts)\n{\n    if (!c || !n || npnts <= 0 || !pnts) {\n\treturn -1;\n    }\n\n    // 1.  Find the center point\n    point_t center = VINIT_ZERO;\n    for (int i = 0; i < npnts; i++) {\n\tVADD2(center, pnts[i], center);\n    }\n    VSCALE(center, center, 1.0/(fastf_t)npnts);\n\n    // 2.  Transfer the points into Eigen data types\n    Eigen::MatrixXd A(3, npnts);\n    for (int i = 0; i < npnts; i++) {\n\tA(0,i) = pnts[i][X] - center[X];\n\tA(1,i) = pnts[i][Y] - center[Y];\n\tA(2,i) = pnts[i][Z] - center[Z];\n    }\n\n    // 3.  Perform SVD\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeThinU);\n\n    // 4.  Normal is in column 3 of U matrix\n    vect_t normal;\n    normal[X] = svd.matrixU()(0,2);\n    normal[Y] = svd.matrixU()(1,2);\n    normal[Z] = svd.matrixU()(2,2);\n\n    // 5.  Set the outputs\n    VMOVE(*c, center);\n    VMOVE(*n, normal);\n\n    return 0;\n}\n\n\n/** @} */\n/*\n * Local Variables:\n * mode: C\n * tab-width: 8\n * indent-tabs-mode: t\n * c-file-style: \"stroustrup\"\n * End:\n * ex: shiftwidth=4 tabstop=8\n */\n", "meta": {"hexsha": "d55a1ac69171ea9f2ce559438e225e2048452ff3", "size": 65744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libbn/plane.cpp", "max_stars_repo_name": "ejno/brlcad", "max_stars_repo_head_hexsha": "b21b3e1728ade0fea2d36a105609566cb114c382", "max_stars_repo_licenses": ["BSD-4-Clause", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libbn/plane.cpp", "max_issues_repo_name": "ejno/brlcad", "max_issues_repo_head_hexsha": "b21b3e1728ade0fea2d36a105609566cb114c382", "max_issues_repo_licenses": ["BSD-4-Clause", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libbn/plane.cpp", "max_forks_repo_name": "ejno/brlcad", "max_forks_repo_head_hexsha": "b21b3e1728ade0fea2d36a105609566cb114c382", "max_forks_repo_licenses": ["BSD-4-Clause", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4624322231, "max_line_length": 136, "alphanum_fraction": 0.5807069847, "num_tokens": 23626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266734, "lm_q2_score": 0.63341027751814, "lm_q1q2_score": 0.432349226720785}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include \"gradient.hpp\"\n#include \"hllc.hpp\"\n#include \"mesh.hpp\"\n#include \"slope_limiter.hpp\"\n\n// Note: this class will compute the rate of change due to the fluxes.\n// Note: the reason we made this a class is that it allows you to allocate\n//       buffers, once at the beginning of the simulation. Add these buffers\n//       as needed.\nclass FluxRateOfChange {\n  public:\n    explicit FluxRateOfChange(int n_cells) {\n        // Allocate buffers as needed.\n    }\n\n    void operator()(Eigen::MatrixXd &dudt,\n                    const Eigen::MatrixXd &u,\n                    const Mesh &mesh) const {\n\n        // Compute the rate of change of u.\n        // Note: Please use the method `computeFlux` to abstract\n        // away the details of computing the flux through a\n        // given interface.\n        // Note: You can use `assert_valid_flux` to check\n        // if what `computeFlux` returns makes any sense.\n        // Note: Do not assume `dudt` is filled with zeros.\n    }\n\n    void assert_valid_flux(const Mesh &mesh,\n                           int i,\n                           int k,\n                           const EulerState &nF) const {\n        // This is mostly for debugging (but also important to check in\n        // real simulations!): Make sure our flux contribution is not\n        // nan (ie. it is not not a number, ie it is a number)\n        if (!euler::isValidFlux(nF)) {\n            // clang-format off\n            throw std::runtime_error(\n                \"invalid value detected in numerical flux, \" + euler::to_string(nF)\n                + \"\\nat triangle: \" + std::to_string(i)\n                + \"\\nedge:        \" + std::to_string(k)\n                + \"\\nis_boundary: \" + std::to_string(!mesh.isValidNeighbour(i, k)));\n            // clang-format on\n        }\n    }\n\n    /// Compute the flux through the k-th interface of cell i.\n    EulerState computeFlux(const Eigen::MatrixXd &U,\n                           int i,\n                           int k,\n                           const Mesh &mesh) const {\n        auto boundary_type = mesh.getBoundaryType(i, k);\n\n        if (boundary_type == Mesh::BoundaryType::INTERIOR_EDGE) {\n            return computeInteriorFlux(U, i, k, mesh);\n        } else {\n            if (boundary_type == Mesh::BoundaryType::OUTFLOW_EDGE) {\n                return computeOutflowFlux(U, i, k, mesh);\n            } else /* boundary_type == Mesh::BoundaryType::WING_EDGE */\n            {\n                return computeReflectiveFlux(U, i, k, mesh);\n            }\n        }\n    }\n\n    /// Compute the outflow flux through the k-th interface of cell i.\n    /** Note: you know that edge k is an outflow edge.\n     */\n    EulerState computeOutflowFlux(const Eigen::MatrixXd &U,\n                                  int i,\n                                  int k,\n                                  const Mesh &mesh) const {\n        // Implement the outflow flux boundary condition.\n        return EulerState{};\n    }\n\n    /// Compute the reflective boundary flux through the k-th edge of cell i.\n    /** Note: you know that edge k is a reflective/wall boundary edge.\n     */\n    EulerState computeReflectiveFlux(const Eigen::MatrixXd &U,\n                                     int i,\n                                     int k,\n                                     const Mesh &mesh) const {\n\n        // Implement the reflective flux boundary condition.\n        return EulerState{};\n    }\n\n    /// Compute the flux through the k-th interface of cell i.\n    /** Note: This edge is an interior edge, therefore approximate the flux\n     * through this edge with the appropriate FVM formulas.\n     */\n    EulerState computeInteriorFlux(const Eigen::MatrixXd &U,\n                                   int i,\n                                   int k,\n                                   const Mesh &mesh) const {\n        // Reconstruct the trace values of U and compute\n        // the numerical flux through the k-th interface of\n        // cell i.\n        return EulerState{};\n    }\n\n\n  private:\n    // add any member variables you might need here.\n};\n", "meta": {"hexsha": "5d1eddc53ff482518764ac94544f739a3c2320ce", "size": 4141, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_handout/unstructured_euler/numerical_flux.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series2_handout/unstructured_euler/numerical_flux.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series2_handout/unstructured_euler/numerical_flux.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 37.3063063063, "max_line_length": 84, "alphanum_fraction": 0.5452789181, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.4323492138171908}}
{"text": "#include <boost/gil/extension/io/png.hpp>\n#include <boost/gil/image.hpp>\n#include <boost/gil/image_processing/hessian.hpp>\n#include <boost/gil/image_processing/numeric.hpp>\n#include <boost/gil/image_view.hpp>\n#include <fstream>\n#include <functional>\n#include <iostream>\n#include <set>\n#include <vector>\n\nnamespace gil = boost::gil;\n\n// some images might produce artifacts\n// when converted to grayscale,\n// which was previously observed on\n// canny edge detector for test input\n// used for this example.\n// the algorithm here follows sRGB gamma definition\n// taken from here (luminance calculation):\n// https://en.wikipedia.org/wiki/Grayscale\ngil::gray8_image_t to_grayscale(gil::rgb8_view_t original) {\n  gil::gray8_image_t output_image(original.dimensions());\n  auto output = gil::view(output_image);\n  constexpr double max_channel_intensity =\n      (std::numeric_limits<std::uint8_t>::max)();\n  for (long int y = 0; y < original.height(); ++y) {\n    for (long int x = 0; x < original.width(); ++x) {\n      // scale the values into range [0, 1] and calculate linear intensity\n      auto &p = original(x, y);\n      double red_intensity =\n          p.at(std::integral_constant<int, 0>{}) / max_channel_intensity;\n      double green_intensity =\n          p.at(std::integral_constant<int, 1>{}) / max_channel_intensity;\n      double blue_intensity =\n          p.at(std::integral_constant<int, 2>{}) / max_channel_intensity;\n      auto linear_luminosity = 0.2126 * red_intensity +\n                               0.7152 * green_intensity +\n                               0.0722 * blue_intensity;\n\n      // perform gamma adjustment\n      double gamma_compressed_luminosity = 0;\n      if (linear_luminosity < 0.0031308) {\n        gamma_compressed_luminosity = linear_luminosity * 12.92;\n      } else {\n        gamma_compressed_luminosity =\n            1.055 * std::pow(linear_luminosity, 1 / 2.4) - 0.055;\n      }\n\n      // since now it is scaled, descale it back\n      output(x, y) = gamma_compressed_luminosity * max_channel_intensity;\n    }\n  }\n\n  return output_image;\n}\n\nvoid apply_gaussian_blur(gil::gray8_view_t input_view,\n                         gil::gray8_view_t output_view) {\n  constexpr static auto filter_height = 5ull;\n  constexpr static auto filter_width = 5ull;\n  constexpr static double filter[filter_height][filter_width] = {\n      2,  4, 6, 4, 2,  4, 9, 12, 9, 4, 5, 12, 15,\n      12, 5, 4, 9, 12, 9, 4, 2,  4, 5, 4, 2,\n  };\n  constexpr double factor = 1.0 / 159;\n  constexpr double bias = 0.0;\n\n  const auto height = input_view.height();\n  const auto width = input_view.width();\n  for (std::ptrdiff_t x = 0; x < width; ++x) {\n    for (std::ptrdiff_t y = 0; y < height; ++y) {\n      double intensity = 0.0;\n      for (std::ptrdiff_t filter_y = 0; filter_y < filter_height; ++filter_y) {\n        for (std::ptrdiff_t filter_x = 0; filter_x < filter_width; ++filter_x) {\n          int image_x = x - filter_width / 2 + filter_x;\n          int image_y = y - filter_height / 2 + filter_y;\n          if (image_x >= input_view.width() || image_x < 0 ||\n              image_y >= input_view.height() || image_y < 0) {\n            continue;\n          }\n          const auto &pixel = input_view(image_x, image_y);\n          intensity += pixel.at(std::integral_constant<int, 0>{}) *\n                       filter[filter_y][filter_x];\n        }\n      }\n      auto &pixel = output_view(gil::point_t(x, y));\n      pixel = (std::min)((std::max)(int(factor * intensity + bias), 0), 255);\n    }\n  }\n}\n\nstd::vector<gil::point_t> suppress(gil::gray32f_view_t harris_response,\n                                   double harris_response_threshold) {\n  std::vector<gil::point_t> corner_points;\n  for (gil::gray32f_view_t::coord_t y = 1; y < harris_response.height() - 1;\n       ++y) {\n    for (gil::gray32f_view_t::coord_t x = 1; x < harris_response.width() - 1;\n         ++x) {\n      auto value = [](gil::gray32f_pixel_t pixel) {\n        return pixel.at(std::integral_constant<int, 0>{});\n      };\n      double values[9] = {value(harris_response(x - 1, y - 1)),\n                          value(harris_response(x, y - 1)),\n                          value(harris_response(x + 1, y - 1)),\n                          value(harris_response(x - 1, y)),\n                          value(harris_response(x, y)),\n                          value(harris_response(x + 1, y)),\n                          value(harris_response(x - 1, y + 1)),\n                          value(harris_response(x, y + 1)),\n                          value(harris_response(x + 1, y + 1))};\n\n      auto maxima = *std::max_element(\n          values, values + 9, [](double lhs, double rhs) { return lhs < rhs; });\n\n      if (maxima == value(harris_response(x, y)) &&\n          std::count(values, values + 9, maxima) == 1 &&\n          maxima >= harris_response_threshold) {\n        corner_points.emplace_back(x, y);\n      }\n    }\n  }\n\n  return corner_points;\n}\n\nint main(int argc, char *argv[]) {\n  if (argc != 5) {\n    std::cout << \"usage: \" << argv[0]\n              << \" <input.png> <odd-window-size>\"\n                 \" <hessian-response-threshold> <output.png>\\n\";\n    return -1;\n  }\n\n  std::size_t window_size = std::stoul(argv[2]);\n  long hessian_determinant_threshold = std::stol(argv[3]);\n\n  gil::rgb8_image_t input_image;\n\n  gil::read_image(argv[1], input_image, gil::png_tag{});\n\n  auto input_view = gil::view(input_image);\n  auto grayscaled = to_grayscale(input_view);\n  gil::gray8_image_t smoothed_image(grayscaled.dimensions());\n  auto smoothed = gil::view(smoothed_image);\n  apply_gaussian_blur(gil::view(grayscaled), smoothed);\n  gil::gray16s_image_t x_gradient_image(grayscaled.dimensions());\n  gil::gray16s_image_t y_gradient_image(grayscaled.dimensions());\n\n  auto x_gradient = gil::view(x_gradient_image);\n  auto y_gradient = gil::view(y_gradient_image);\n  auto scharr_x = gil::generate_dx_scharr();\n  gil::detail::convolve_2d(smoothed, scharr_x, x_gradient);\n  auto scharr_y = gil::generate_dy_scharr();\n  gil::detail::convolve_2d(smoothed, scharr_y, y_gradient);\n\n  gil::gray32f_image_t m11(x_gradient.dimensions());\n  gil::gray32f_image_t m12_21(x_gradient.dimensions());\n  gil::gray32f_image_t m22(x_gradient.dimensions());\n  gil::compute_hessian_entries(x_gradient, y_gradient, gil::view(m11),\n                               gil::view(m12_21), gil::view(m22));\n\n  gil::gray32f_image_t hessian_response(x_gradient.dimensions());\n  auto gaussian_kernel = gil::generate_gaussian_kernel(window_size, 0.84089642);\n  gil::compute_hessian_responses(gil::view(m11), gil::view(m12_21),\n                                 gil::view(m22), gaussian_kernel,\n                                 gil::view(hessian_response));\n\n  auto corner_points =\n      suppress(gil::view(hessian_response), hessian_determinant_threshold);\n  for (auto point : corner_points) {\n    input_view(point) = gil::rgb8_pixel_t(0, 0, 0);\n    input_view(point).at(std::integral_constant<int, 1>{}) = 255;\n  }\n  gil::write_view(argv[4], input_view, gil::png_tag{});\n}\n", "meta": {"hexsha": "f6e4cab2cfc849c3a9c135247b58e77f782d3294", "size": 6994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/hessian.cpp", "max_stars_repo_name": "sdebionne/gil-reformated", "max_stars_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/hessian.cpp", "max_issues_repo_name": "sdebionne/gil-reformated", "max_issues_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/hessian.cpp", "max_forks_repo_name": "sdebionne/gil-reformated", "max_forks_repo_head_hexsha": "7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5141242938, "max_line_length": 80, "alphanum_fraction": 0.6221046611, "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4323492090936783}}
{"text": "#pragma once\n\n#include <iostream>\n#include <type_traits>\n#include <unordered_set>\n#include <vector>\n\n#include <boost/heap/fibonacci_heap.hpp>\n\n#include \"heap.hpp\"\n#include \"hypergraph.hpp\"\n#include \"cut.hpp\"\n\nnamespace hypergraphlib {\n\n// A context for vertex ordering calculations\ntemplate<typename Heap>\nstruct OrderingContext {\n  // Constructor\n  OrderingContext(const std::vector<int> &vertices, size_t capacity) : heap(vertices, capacity) {}\n\n  // Heap for tracking which vertices are most tightly connected to the\n  // ordering\n  Heap heap;\n\n  std::unordered_map<\n      int, boost::heap::fibonacci_heap<std::pair<size_t, int>>::handle_type>\n      handles;\n\n  // A mapping of edges to the number of vertices inside the edges that have not\n  // been ordered\n  std::unordered_map<int, int> edge_to_num_vertices_outside_ordering;\n\n  // Vertices that have been marked as used by the ordering\n  std::unordered_set<int> used_vertices;\n\n  // Edges that have been marked as used by the ordering\n  std::unordered_set<int> used_edges;\n};\n\n/* The method for calculating a vertex ordering for maximum adjacency and tight,\n * and Queyranne orderings is very similar - maintain how \"tight\" each vertex is\n * and repeatedly add the \"tightest\" vertex. The only difference is how\n * \"tightness\" is defined for each ordering. The \"_tighten\" functions define how\n * each ordering maintains tightness.\n *\n * Each of these methods runs in time linear to the number of edges incident on\n * v.\n */\n\n// See [KW'96] for more details\ntemplate<typename HypergraphType>\nvoid maximum_adjacency_ordering_tighten(\n    const HypergraphType &hypergraph,\n    OrderingContext<typename HypergraphType::Heap> &ctx,\n    const int v) {\n  // We are adding v to the ordering so far, and need to update the keys for the\n  // other vertices\n  // Check each edge e incident on v\n  for (const int e : hypergraph.edges_incident_on(v)) {\n    // If e has already been used, then skip it\n    if (ctx.used_edges.find(e) != std::end(ctx.used_edges)) {\n      continue;\n    }\n    // For every vertex u in e that is not v and not already in the ordering,\n    // increment its key (it is one edge tighter now)\n    // TODO I think vertices need to be removed from the edge's incidence list\n    //      to maintain the runtime.\n    for (const int u : hypergraph.edges().at(e)) {\n      if (ctx.used_vertices.find(u) == std::end(ctx.used_vertices)) {\n        if constexpr (std::is_same_v<HypergraphType, Hypergraph>) {\n          ctx.heap.increment(u);\n        } else {\n          ctx.heap.increment(u, edge_weight(hypergraph, e));\n        }\n      }\n    }\n    ctx.used_edges.insert(e);\n  }\n}\n\n// See [MW'00] for more details\ntemplate<typename HypergraphType>\nvoid tight_ordering_tighten(\n    const HypergraphType &hypergraph,\n    OrderingContext<typename HypergraphType::Heap> &ctx,\n    const int v) {\n  // For every edge e incident on v\n  for (const int e : hypergraph.edges_incident_on(v)) {\n    // Tighten this edge\n    ctx.edge_to_num_vertices_outside_ordering.at(e) -= 1ul;\n    // If the edge only has one vertex u left that is outside the ordering,\n    // increase the key of u\n    if (ctx.edge_to_num_vertices_outside_ordering.at(e) == 1) {\n      for (const int u : hypergraph.edges().at(e)) {\n        if (ctx.used_vertices.find(u) == std::end(ctx.used_vertices)) {\n          if constexpr (std::is_same_v<HypergraphType, Hypergraph>) {\n            ctx.heap.increment(u);\n          } else {\n            ctx.heap.increment(u, edge_weight(hypergraph, e));\n          }\n        }\n      }\n    }\n  }\n}\n\n// See [Q'98] for more details\ntemplate<typename HypergraphType>\nvoid queyranne_ordering_tighten(\n    const HypergraphType &hypergraph,\n    OrderingContext<typename HypergraphType::Heap> &ctx,\n    const int v) {\n  maximum_adjacency_ordering_tighten(hypergraph, ctx, v);\n  tight_ordering_tighten(hypergraph, ctx, v);\n}\n\ntemplate<typename HypergraphType>\nusing tightening_t =\nstd::add_pointer_t<void(const HypergraphType &, OrderingContext<typename HypergraphType::Heap> &, const int)>;\n\n/* Given a method to update the \"tightness\" of different vertices, computes a\n * vertex ordering and returns the ordering as well as a list of how tight each\n * vertex was when it was added to the ordering.\n *\n * Time complexity: O(p), where p is the size of the hypergraph, assuming that\n * TIGHTEN runs in time linear to the number of edges incident on the selected\n * vertex.\n */\ntemplate<typename HypergraphType, tightening_t<HypergraphType> TIGHTEN>\ninline std::pair<std::vector<int>, std::vector<double>>\nordering(const HypergraphType &hypergraph, const int a) {\n  std::vector<int> ordering = {a};\n  std::vector<double> tightness = {0};\n  std::vector<int> vertices_without_a;\n\n  for (const auto v : hypergraph.vertices()) {\n    if (v == a) {\n      continue;\n    }\n    vertices_without_a.emplace_back(v);\n  }\n\n  // Multiply edges by 2 for Queyranne ordering\n  OrderingContext<typename HypergraphType::Heap> ctx(vertices_without_a, 2 * hypergraph.num_edges() + 1);\n  for (const auto &[e, vertices] : hypergraph.edges()) {\n    ctx.edge_to_num_vertices_outside_ordering.insert({e, vertices.size()});\n  }\n\n  const auto tighten = [&hypergraph, &ctx](const int v) {\n    ctx.used_vertices.insert(v);\n    // It is the responsibility of TIGHTEN to update the context\n    TIGHTEN(hypergraph, ctx, v);\n  };\n\n  tighten(a);\n\n  while (ordering.size() < hypergraph.num_vertices()) {\n    const auto[k, v] = ctx.heap.pop_key_val();\n    ordering.emplace_back(v);\n    // We need k / 2 instead of just k because this is just used for Queyranne\n    // for now\n    tightness.push_back(k / 2.0);\n    tighten(v);\n  }\n\n  return {ordering, tightness};\n}\n\n/* Returns a maximum adjacency ordering of vertices, starting with vertex a.\n * Linear in the number of vertices across all hyperedges.\n *\n * Here, tightness for a vertex v is the number of edges that intersect the\n * ordering so far and v.\n *\n * See [KW'96] for more details.\n */\ntemplate<typename HypergraphType>\ninline std::vector<int> maximum_adjacency_ordering(const HypergraphType &hypergraph,\n                                                   const int a) {\n  return ordering<HypergraphType, maximum_adjacency_ordering_tighten>(hypergraph, a).first;\n}\n\n/* Return a tight ordering of vertices, starting with vertex a. Linear in the\n * number of vertices across all hyperedges.\n *\n * Here, tightness is the number of edges connecting a vertex v to the\n * ordering so far that consist of vertices either in the ordering or v\n * itself.\n *\n * Takes time linear with the size of the hypergraph.\n *\n * See [MW'00] for more details.\n */\ntemplate<typename HypergraphType>\ninline std::vector<int> tight_ordering(const HypergraphType &hypergraph, const int a) {\n  return ordering<HypergraphType, tight_ordering_tighten>(hypergraph, a).first;\n}\n\n/* Return a Queyranne ordering of vertices, starting with vertex a.\n *\n * Takes time linear with the size of the hypergraph.\n *\n * See [Q'98] for more details.\n */\ntemplate<typename HypergraphType>\ninline std::vector<int> queyranne_ordering(const HypergraphType &hypergraph, const int a) {\n  return ordering<HypergraphType, queyranne_ordering_tighten>(hypergraph, a).first;\n}\n\ntemplate<typename HypergraphType>\ninline std::pair<std::vector<int>,\n                 std::vector<double>> queyranne_ordering_with_tightness(const HypergraphType &hypergraph, const int a) {\n  return ordering<HypergraphType, queyranne_ordering_tighten>(hypergraph, a);\n}\n\ntemplate<typename HypergraphType>\nusing ordering_t = std::add_pointer_t<std::vector<int>(const HypergraphType &, const int)>;\n\n/* Given a hypergraph and a function that orders the vertices, find the min cut\n * by repeatedly finding and contracting pendant pairs.\n *\n * Time complexity: O(np), where n is the number of vertices and p is the size\n * of the hypergraph\n *\n * Ordering should be one of `tight_ordering`, `queyranne_ordering`, or\n * `maximum_adjacency_ordering`.\n */\ntemplate<typename HypergraphType, ordering_t<HypergraphType> Ordering, bool ReturnPartitions>\nauto vertex_ordering_minimum_cut_start_vertex(HypergraphType &hypergraph,\n                                              const int a) -> typename HypergraphCutRet<HypergraphType,\n                                                                                        ReturnPartitions>::T {\n  hypergraph.remove_singleton_and_empty_hyperedges();\n  auto min_cut_of_phase = HypergraphCutRet<HypergraphType, ReturnPartitions>::max();\n  while (hypergraph.num_vertices() > 1) {\n    auto ordering = Ordering(hypergraph, a);\n    const auto cut_of_phase = one_vertex_cut<ReturnPartitions>(hypergraph, ordering.back());\n    hypergraph = merge_vertices(hypergraph, *(std::end(ordering) - 2),\n                                *(std::end(ordering) - 1));\n    min_cut_of_phase = std::min(min_cut_of_phase, cut_of_phase);\n  }\n  return min_cut_of_phase;\n}\n\ntemplate<typename HypergraphType, ordering_t<HypergraphType> Ordering, bool ReturnPartitions>\nauto vertex_ordering_mincut(HypergraphType &hypergraph) -> typename HypergraphCutRet<HypergraphType,\n                                                                                     ReturnPartitions>::T {\n  const auto a = *std::begin(hypergraph.vertices());\n  return vertex_ordering_minimum_cut_start_vertex<HypergraphType, Ordering, ReturnPartitions>(hypergraph, a);\n}\n\ntemplate<typename HypergraphType>\ninline auto MW_min_cut(HypergraphType &hypergraph) {\n  return vertex_ordering_mincut<HypergraphType, tight_ordering, true>(hypergraph);\n}\ntemplate<typename HypergraphType>\ninline auto MW_min_cut_value(HypergraphType &hypergraph) {\n  return vertex_ordering_mincut<HypergraphType, tight_ordering, false>(hypergraph);\n}\n\ntemplate<typename HypergraphType>\ninline auto Q_min_cut(HypergraphType &hypergraph) {\n  return vertex_ordering_mincut<HypergraphType, queyranne_ordering, true>(hypergraph);\n}\ntemplate<typename HypergraphType>\ninline auto Q_min_cut_value(HypergraphType &hypergraph) {\n  return vertex_ordering_mincut<HypergraphType, queyranne_ordering, false>(hypergraph);\n}\n\ntemplate<typename HypergraphType>\ninline auto KW_min_cut(HypergraphType &hypergraph) {\n  return vertex_ordering_mincut<HypergraphType, maximum_adjacency_ordering, true>(hypergraph);\n}\ntemplate<typename HypergraphType>\ninline auto KW_min_cut_value(HypergraphType &hypergraph) {\n  return vertex_ordering_mincut<HypergraphType, maximum_adjacency_ordering, false>(hypergraph);\n}\n\n}\n", "meta": {"hexsha": "20a2d25e51552a6ad23888cccb202fc4bf41630e", "size": 10425, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/hypergraph/include/hypergraph/order.hpp", "max_stars_repo_name": "vsui/hypergraph-k-cut", "max_stars_repo_head_hexsha": "1134ca254fb709bce62a4506c931362d84a06894", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T07:31:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T08:36:50.000Z", "max_issues_repo_path": "lib/hypergraph/include/hypergraph/order.hpp", "max_issues_repo_name": "vsui/hypergraph-k-cut", "max_issues_repo_head_hexsha": "1134ca254fb709bce62a4506c931362d84a06894", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/hypergraph/include/hypergraph/order.hpp", "max_forks_repo_name": "vsui/hypergraph-k-cut", "max_forks_repo_head_hexsha": "1134ca254fb709bce62a4506c931362d84a06894", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2321428571, "max_line_length": 120, "alphanum_fraction": 0.7173141487, "num_tokens": 2516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.682573734412324, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4323492090936782}}
{"text": "#include \"iisph.hpp\"\n#include \"spatial/2d/neighborhood_spatial_hashing.hpp\"\n#include \"kernel_debrun_spiky.hpp\"\n#include \"kernel_poly6.hpp\"\n#include \"kernel_poly_viscosity.hpp\"\n#include \"generic/eigen.hpp\"\n#include \"generic/is_finite.hpp\"\n\n#include <iostream>\n#include <boost/log/trivial.hpp>\n\nnamespace GooBalls {\n\nnamespace d2 {\n\nnamespace Physics {\n\nusing namespace Spatial;\n\nIISPH::IISPH(){\n    // Decent defaults\n    m_kernelDensity = std::make_unique<Poly6>();\n    m_kernelPressure = std::make_unique<DebrunSpiky>();\n    m_kernelViscosity = std::make_unique<PolyViscosity>();\n}\n\nvoid IISPH::densityKernel(std::unique_ptr<Kernel>&& k) {\n    m_kernelDensity = std::move(k);\n}\nvoid IISPH::pressureKernel(std::unique_ptr<Kernel>&& k) {\n    m_kernelPressure = std::move(k);\n}\nvoid IISPH::viscosityKernel(std::unique_ptr<Kernel>&& k) {\n    m_kernelViscosity = std::move(k);\n}\n\nvoid IISPH::computeTotalForce(Scene& scene, TimeStep dt){\n    if(scene.fluid.get() == nullptr){\n        return;\n    }\n    prepareFluid(scene);\n    prepareBoundary(scene);\n    assert(m_kernelDensity.get() != nullptr);\n    assert(m_kernelPressure.get() != nullptr);\n    assert(m_kernelViscosity.get() != nullptr);\n    const Float h = scene.fluid->h();\n    m_kernelDensity->setH(h);\n    m_kernelPressure->setH(h);\n    m_kernelViscosity->setH(h);\n    auto& pos = scene.fluid->particles_position();\n    assert(is_finite(pos));\n    Float K = scene.fluid->stiffnessConstant(); // gas constant dependent on temperature, TODO: correct value?\n\n    // p_i = k rho0 / gamma ((rho_i/rho0)^gamma - 1)\n    // F^p_i = m_i sum_j m_j ( p_i / rho_i^2 + p_j / rho_j^2) \\nabbla W_ij\n    // v^adv_i = v_i + dt * F^adv_i / m_i\n    // rho^adv_i = rho_i + dt * sum_j m_j v^adv_ij \\nabbla W_ij\n    // dt^2 sum_j (m_j/m_i F^p_i - F^p_j) * \\nabbla W_ij = rho0 - rho^adv_i\n    // sum_j a_ij p_j = b_i = rho_0 - rho^adv_i\n\n    scene.fluid->fluid_neighborhood->inRange(pos, h);\n    //computeFluidPressure(scene);\n    predictAdvection(scene, dt, *m_kernelDensity);\n    pressureSolve(scene, dt, *m_kernelDensity);\n    computeMomentumPreservingPressureForce(scene, *m_kernelDensity);\n    //computeStandardPressureForce(scene, *m_kernelDensity);\n\n    FPressure = FPressure.array().min(100*K).max(-100*K);\n    FViscosity = FViscosity.array().min(100*K).max(-100*K);\n    assert(is_finite(FPressure));\n    assert(is_finite(FViscosity));\n    assert(is_finite(FSurface));\n    scene.fluid->particles_total_force() = FPressure + FGravity + FViscosity;\n}\n\n\nvoid IISPH::predictAdvection(Scene& scene, TimeStep dt, const Kernel& kernel) {\n    const auto& pos = scene.fluid->particles_position();\n    const auto& vs = scene.fluid->particles_velocity();\n    const auto& ps = scene.fluid->particles_pressure();\n    const auto& ms = scene.fluid->particles_mass();\n    const auto& rho = scene.fluid->particles_density();\n    const auto& fluid_index = scene.fluid->fluid_neighborhood->indexes();\n    int PN = vs.rows();\n    // for all particle i do\n    //     compute rho_i(t) = sum_j m_j W_ij\n    computeFluidDensity(scene, *m_kernelDensity);\n    //     compute F^adv_i = F^SurfaceTension_i + F^Gravity_i + F^Visco_i + ...\n    computeGravityForce(scene);\n    computeStandardViscosityForce(scene, *m_kernelViscosity);\n    // TODO: computeSurfaceTensionForce();\n    const auto Fadv = FGravity + FViscosity;\n    //     predict v^adv_i = v_i + dt F^adv_i / m_i\n    Coordinates2d da = Fadv.array().colwise() / ms.array();\n    Coordinates2d Vadv = vs + dt*da;\n    //     d_ii = - dt^2 sum_j m_j/rho_i^2 \\nabbla W_ij\n    dii.resize(PN, 2);\n    auto dt2 = dt*dt;\n    for(int i = 0; i < PN; ++i){\n        const auto& index = fluid_index[i];\n        Coordinates2d diis(index.size(), 2);\n        Coordinates2d jpos;\n        Coordinates2d wGrad;\n        pickRows(pos, index, jpos);\n        auto xij = -(jpos.rowwise() - pos.row(i));\n        kernel.compute(xij, nullptr, &wGrad, nullptr);\n        for(size_t j = 0; j < index.size(); ++j){\n            int jj = index[j];\n            diis.row(j) = ms[jj] * wGrad.row(j);\n        }\n        dii.row(i) = - dt2/(rho[i]*rho[i]) * diis.colwise().sum();\n    }\n\n    // for all particle i do\n    // rho^adv_i = rho_i + dt sum_j m_j * v^adv_ij * \\nabbla W_ij\n    rhoAdv = rho;\n    // initializing pi is a bit of an art\n    // these are possibilities, last chosen by paper:\n    // p^0_i = 0\n    // p^0_i = p_i(t-dt).\n    // p^0_i = 0.5 p_i(t - dt)\n    p0 = 0.5* ps;\n    //p0.setZero(PN, 1);\n    aii.resize(PN, 1);\n    for(int i = 0; i < PN; ++i){\n        const auto& index = fluid_index[i];\n        Coordinates1d rhos(index.size(), 1);\n        Coordinates2d jpos;\n        Coordinates2d wGrad;\n        pickRows(pos, index, jpos);\n        auto xij = -(jpos.rowwise() - pos.row(i));\n        kernel.compute(xij, nullptr, &wGrad, nullptr);\n        for(size_t j = 0; j < index.size(); ++j){\n            int jj = index[j];\n            rhos[j] = ms[jj] * (Vadv.row(i) - Vadv.row(jj)).dot(wGrad.row(j));\n        }\n        rhoAdv[i] += dt*rhos.sum();\n        // compute a_ii = sum_j m_j (d_ii - d_ji) nabbla W_ij\n        Coordinates1d aiis (index.size(), 1);\n        for(size_t j = 0; j < index.size(); ++j){\n            int jj = index[j];\n            // d_ij = - dt^2 * m_j / rho_j^2 \\nabbla W_ij\n            TranslationVector dji = dt2 * ms[i] / (rho[i]*rho[i]) * wGrad.row(j);\n            aiis[j] = ms[jj] * (dii.row(i) - dji).dot(wGrad.row(j));\n        }\n        aii[i] = aiis.sum();\n    }\n}\n\nvoid IISPH::pressureSolve(Scene& scene, TimeStep dt, const Kernel& kernel) {\n    // rho^l_avg = 1/n * sum_i rho^l_i\n    // l = 0\n    // while rho^l_avg - rho0 > eta OR l < 2 do\n    // for all particle i do:\n    //    sum_j d_ij p^l_j = dt^2 sum_j - m_j / rho_j^2 p^l_j \\nabbla _Wij\n    // for all particle i do:\n    //    comptue p^(l+1)_i = (1 - omega) p^l_i + omega/a_ii ( rho0 - rho^adv_i - sum_j m_j (sum_j d_ij p^l_j - d_jj p^l_j - sum_{k!= i} d_ji p^l_k ) \\nabbla W_ij)\n    //    p_i(t) = p_i^l\n    // l = l + 1\n    const auto& ms = scene.fluid->particles_mass();\n    const auto& rho = scene.fluid->particles_density();\n    const auto& pos = scene.fluid->particles_position();\n    auto& ps = scene.fluid->particles_pressure();\n    auto rho0 = scene.fluid->rest_density();\n    auto PN = pos.rows();\n    const auto& fluid_index = scene.fluid->fluid_neighborhood->indexes();\n    Float eta = 0.01*rho0;\n    Coordinates1d p1;\n    Coordinates1d rhol;\n    Coordinates2d dp; // sum_j dij p^l_j, for given i\n    p1.resize(PN, 1);\n    rhol.setZero(PN, 1);\n    dp.resize(PN, 2);\n    Float omega = 0.5; // relaxation factor\n    int l = 0;\n    do {\n        //    sum_j d_ij p^l_j = - dt^2 sum_j m_j / rho_j^2 p^l_j \\nabbla _Wij\n        for(int i = 0; i < PN; ++i){\n            const auto& index = fluid_index[i];\n            Coordinates2d jpos;\n            pickRows(pos, index, jpos);\n            Coordinates2d wGrad;\n            Coordinates2d xij = -(jpos.rowwise() - pos.row(i));\n            kernel.compute(xij, nullptr, &wGrad, nullptr);\n            Coordinates2d dps(index.size(), 2);\n            for(size_t j = 0; j < index.size(); ++j){\n                int jj = index[j];\n                dps.row(j) = ms[jj] / (rho[jj] * rho[jj]) * p0[jj] * wGrad.row(j);\n            }\n            dp.row(i) = -dt*dt * dps.colwise().sum();\n        }\n        //    comptue p^(l+1)_i = (1 - omega) p^l_i + omega/a_ii (rho0 - rho^adv_i - A_i)\n        //         A_i = sum_j m_j (dp_i - d_jj p^l_j - dpp_j ) \\nabbla W_ij\n        //             dp_i = sum_j d_ij p^l_j\n        //             dpp_j = sum_{k!= i} d_jk p^l_k = sum_k d_jk p_k^l - d_ji p_i^l\n        //             sum_k d_jk p_k^l = dp.row(j)\n        //             d_ij = -dt^2 m_j / rho_j^2 \\nabbla W_ij\n        // compute A_j and store in p1[i]\n        for(int i = 0; i < PN; ++i){\n            const auto& indexI = fluid_index[i];\n            Coordinates2d jpos;\n            pickRows(pos, indexI, jpos);\n            Coordinates2d wGradI;\n            Coordinates2d xij = -(jpos.rowwise() - pos.row(i));\n            kernel.compute(xij, nullptr, &wGradI, nullptr);\n            Coordinates1d Ais(indexI.size());\n            Coordinates2d wGradJ;\n            for(size_t j = 0; j < indexI.size(); ++j){\n                int jj = indexI[j];\n                kernel.compute(-xij.row(j), nullptr, &wGradJ, nullptr);\n                TranslationVector dppj = dp.row(jj) - (-dt*dt*ms[i]/(rho[i]*rho[i]) * wGradJ * p0[i]);\n                Ais[j] = ms[jj]*(dp.row(i) - dii.row(jj)*p0[jj] - dppj).dot(wGradI.row(j));\n            }\n            p1[i] = Ais.sum();\n        }\n        p1 = (1.0 - omega) * p0.array() + omega/aii.array() * (rho0 - rhoAdv.array() - p1.array());\n        std::swap(p0, p1);\n        ps = p0;\n        //std::cout << p0.mean() << \"\\n\";\n        computeMomentumPreservingPressureForce(scene, *m_kernelDensity);\n        Coordinates2d dv = dt*(FPressure.array().colwise() / ms.array());\n        assert(is_finite(dv));\n        for(int i = 0; i < PN; ++i){\n            const auto& index = fluid_index[i];\n            Coordinates2d jpos;\n            pickRows(pos, index, jpos);\n            Coordinates2d wGrad;\n            Coordinates2d xij = -(jpos.rowwise() - pos.row(i));\n            kernel.compute(xij, nullptr, &wGrad, nullptr);\n            assert(is_finite(wGrad));\n            rhol[i] = 0.0;\n            for(size_t j = 0; j < index.size(); ++j){\n                int jj = index[j];\n                rhol[i] += ms[jj] * (dv.row(i) - dv.row(jj)).dot(wGrad.row(j));\n            }\n            rhol[i] *= dt;\n        }\n        l++;\n        assert(is_finite(ps));\n        assert(is_finite(rhol));\n        if(l > 400){\n            BOOST_LOG_TRIVIAL(info) << \"reached maximum number of iterations with rhol=\" << rhol.maxCoeff() << \" avg: \" << rhol.mean() << \", eta: \" << eta;\n            break;\n        }\n    } while (rhol.mean() > eta || l < 2);\n    //    p_i(t) = p_i^(l+1)\n}\n\nvoid IISPH::advance(Scene& scene, TimeStep dt){\n    if(scene.fluid.get() == nullptr){\n        return;\n    }\n    if(scene.fluid->particles_position().rows() == 0){\n        return;\n    }\n    computeTotalForce(scene, dt);\n    Coordinates2d a;\n    // a_i = f_i / rho_i\n    const auto& rho = scene.fluid->particles_density();\n    const auto& Ftotal = scene.fluid->particles_total_force();\n    a.resize(rho.rows(), 2);\n    a.col(0) = Ftotal.col(0).array() / rho.array();\n    a.col(1) = Ftotal.col(1).array() / rho.array();\n    auto& pos = scene.fluid->particles_position();\n    auto& vs = scene.fluid->particles_velocity();\n    vs = vs + dt * a;\n    scene.room.restrictFluid(* scene.fluid);\n    pos = pos + dt * vs;\n    limitVelocity(scene);\n}\n\n\n} // Physics\n\n} // d2\n\n} // GooBalls\n", "meta": {"hexsha": "b826b5ca7f217e96c37079c48c166cc6b0cd8ba0", "size": 10633, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/physics/2d/iisph.cpp", "max_stars_repo_name": "Fluci/GooBalls", "max_stars_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lib/physics/2d/iisph.cpp", "max_issues_repo_name": "Fluci/GooBalls", "max_issues_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/physics/2d/iisph.cpp", "max_forks_repo_name": "Fluci/GooBalls", "max_forks_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2482014388, "max_line_length": 163, "alphanum_fraction": 0.5718988056, "num_tokens": 3262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4323433034360014}}
{"text": "// Copyright (C) 2018 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Victor Fragoso (victor.fragoso@mail.wvu.edu)\n\n#include \"theia/sfm/pose/upnp.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n\n#include <algorithm>\n#include <complex>\n#include <utility>\n#include <vector>\n\n#include \"theia/alignment/alignment.h\"\n#include \"theia/math/util.h\"\n#include \"theia/sfm/pose/build_upnp_action_matrix.h\"\n#include \"theia/sfm/pose/build_upnp_action_matrix_using_symmetry.h\"\n\nnamespace theia {\n\nnamespace {\ntypedef Eigen::Matrix<double, 3, 10> Matrix3x10d;\ntypedef Eigen::Matrix<double, 8, 8> Matrix8d;\ntypedef Eigen::Matrix<std::complex<double>, 8, 8> Matrix8cd;\ntypedef Eigen::Matrix<double, 10, 10> Matrix10d;\ntypedef Eigen::Matrix<double, 16, 16> Matrix16d;\ntypedef Eigen::Matrix<std::complex<double>, 16, 16> Matrix16cd;\ntypedef Eigen::Matrix<double, 10, 1> Vector10d;\n\nconst int kNumMaxRotations = 16;\nconst int kNumMaxRotationsExploitingSymmetry = 8;\nconst int kNumMinCorrespondences = 4;\n\n// Helper structure to simplify function argument list.\nstruct InputDatum {\n  InputDatum(const std::vector<Eigen::Vector3d>& _ray_origins,\n             const std::vector<Eigen::Vector3d>& _ray_directions,\n             const std::vector<Eigen::Vector3d>& _world_points) :\n      ray_origins(_ray_origins),\n      ray_directions(_ray_directions),\n      world_points(_world_points) {}\n  ~InputDatum() = default;\n\n  const std::vector<Eigen::Vector3d>& ray_origins;\n  const std::vector<Eigen::Vector3d>& ray_directions;\n  const std::vector<Eigen::Vector3d>& world_points;\n};\n\n// Computes the H Matrix (see Eq. (6)) and the outer products of the ray\n// directions, since these are used to compute matrix V (Eq. (5)).\ninline Eigen::Matrix3d ComputeHMatrixAndRayDirectionsOuterProducts(\n    const InputDatum& input_datum,\n    std::vector<Eigen::Matrix3d>* outer_products) {\n  const std::vector<Eigen::Vector3d>& ray_directions =\n      input_datum.ray_directions;\n  CHECK_NOTNULL(outer_products)->reserve(ray_directions.size());\n  Eigen::Matrix3d h_inverse;\n  h_inverse.setZero();\n  for (const Eigen::Vector3d& ray : ray_directions) {\n    outer_products->emplace_back(ray * ray.transpose());\n    h_inverse -= outer_products->back();\n  }\n  h_inverse += ray_directions.size() * Eigen::Matrix3d::Identity();\n  return h_inverse.inverse();\n}\n\ninline Matrix3x10d LeftMultiply(const Eigen::Vector3d& point) {\n  Matrix3x10d phi_mat;\n  // Row 0.\n  phi_mat(0, 0) = point.x();\n  phi_mat(0, 1) = point.x();\n  phi_mat(0, 2) = -point.x();\n  phi_mat(0, 3) = -point.x();\n  phi_mat(0, 4) = 0.0;\n  phi_mat(0, 5) = 2 * point.z();\n  phi_mat(0, 6) = -2 * point.y();\n  phi_mat(0, 7) = 2 * point.y();\n  phi_mat(0, 8) = 2 * point.z();\n  phi_mat(0, 9) = 0.0;\n\n  // Row 1.\n  phi_mat(1, 0) = point.y();\n  phi_mat(1, 1) = -point.y();\n  phi_mat(1, 2) = point.y();\n  phi_mat(1, 3) = -point.y();\n  phi_mat(1, 4) = -2.0 * point.z();\n  phi_mat(1, 5) = 0.0;\n  phi_mat(1, 6) = 2 * point.x();\n  phi_mat(1, 7) = 2 * point.x();\n  phi_mat(1, 8) = 0.0;\n  phi_mat(1, 9) = 2 * point.z();\n\n  // Row 3.\n  phi_mat(2, 0) = point.z();\n  phi_mat(2, 1) = -point.z();\n  phi_mat(2, 2) = -point.z();\n  phi_mat(2, 3) = point.z();\n  phi_mat(2, 4) = 2.0 * point.y();\n  phi_mat(2, 5) = -2.0 * point.x();\n  phi_mat(2, 6) = 0.0;\n  phi_mat(2, 7) = 0.0;\n  phi_mat(2, 8) = 2.0 * point.x();\n  phi_mat(2, 9) = 2.0 * point.y();\n  return phi_mat;\n}\n\ninline std::vector<Eigen::Matrix3d> ComputeHelperMatrices(\n    const InputDatum& input_datum,\n    const std::vector<Eigen::Matrix3d>& outer_products,\n    const Eigen::Matrix3d& h_matrix,\n    Matrix3x10d* g_matrix,\n    Eigen::Vector3d* j_matrix) {\n  const std::vector<Eigen::Vector3d>& world_points = input_datum.world_points;\n  const std::vector<Eigen::Vector3d>& ray_origins = input_datum.ray_origins;\n  CHECK_EQ(ray_origins.size(), outer_products.size());\n  CHECK_NOTNULL(g_matrix)->setZero();\n  CHECK_NOTNULL(j_matrix)->setZero();\n  const Eigen::Matrix3d identity = Eigen::Matrix3d::Identity();\n  std::vector<Eigen::Matrix3d> v_matrices(\n      world_points.size(), Eigen::Matrix3d::Zero());\n  for (int i = 0; i < ray_origins.size(); ++i) {\n    const Eigen::Matrix3d& outer_product = outer_products[i];\n    // Computation following Eq. (5).\n    v_matrices[i] = h_matrix * (outer_product - identity);\n    const Eigen::Matrix3d& v_matrix = v_matrices[i];\n    // Compute the left multiplication matrix or Phi matrix in the paper.\n    const Matrix3x10d left_multiply_mat = LeftMultiply(world_points[i]);\n    *j_matrix += v_matrix * ray_origins[i];\n    *g_matrix += v_matrix * left_multiply_mat;\n  }\n  return v_matrices;\n}\n\n// Computes the block matrices that compose the M matrix in Eq. 17. These\n// blocks are:\n// quadratic_penalty_matrix = \\sum A_i^T * A_i,\n// linear_penalty_vector = \\sum A_i^T * b_i ,\n// gamma = \\sum b_i^T * b_i.\nvoid ComputeCostParameters(\n    const InputDatum& input_datum,\n    const std::vector<Eigen::Matrix3d>& outer_products,\n    const Matrix3x10d& g_matrix,\n    const Eigen::Vector3d& j_matrix,\n    Upnp::CostParameters* cost_params) {\n  const Eigen::Matrix3d identity = Eigen::Matrix3d::Identity();\n  const std::vector<Eigen::Vector3d>& world_points = input_datum.world_points;\n  const std::vector<Eigen::Vector3d>& ray_origins = input_datum.ray_origins;\n  Matrix10d& a_matrix = CHECK_NOTNULL(cost_params)->quadratic_penalty_mat;\n  Vector10d& b_vector = cost_params->linear_penalty_vector;\n  double& gamma = cost_params->gamma;\n\n  // Gamma is the sum of the dot products of b_matrices.\n  for (int i = 0; i < world_points.size(); ++i) {\n    // Compute the left multiplication matrix or Phi matrix in the paper.\n    const Matrix3x10d left_multiply_mat = LeftMultiply(world_points[i]);\n    const Eigen::Matrix3d outer_prod_minus_identity =\n        outer_products[i] - identity;\n\n    // Compute the i-th a_matrix.\n    const Matrix3x10d temp_a_mat =\n        outer_prod_minus_identity * (left_multiply_mat + g_matrix);\n    a_matrix += temp_a_mat.transpose() * temp_a_mat;\n\n    // Compute the i-th b_vector.\n    const Eigen::Vector3d temp_b_mat =\n        -outer_prod_minus_identity * (ray_origins[i] + j_matrix);\n    b_vector += temp_a_mat.transpose() * temp_b_mat;\n\n    // Compute the i-th gamma.\n    gamma += temp_b_mat.squaredNorm();\n  }\n}\n\n// Constructs the vector s as indicated in Eq. 12.\ninline Vector10d ComputeRotationVector(const Eigen::Quaterniond& rotation) {\n  Vector10d rotation_vector;\n  // Set the values of the rotation vector.\n  rotation_vector[0] = rotation.w() * rotation.w();\n  rotation_vector[1] = rotation.x() * rotation.x();\n  rotation_vector[2] = rotation.y() * rotation.y();\n  rotation_vector[3] = rotation.z() * rotation.z();\n  rotation_vector[4] = rotation.w() * rotation.x();\n  rotation_vector[5] = rotation.w() * rotation.y();\n  rotation_vector[6] = rotation.w() * rotation.z();\n  rotation_vector[7] = rotation.x() * rotation.y();\n  rotation_vector[8] = rotation.x() * rotation.z();\n  rotation_vector[9] = rotation.y() * rotation.z();\n  return rotation_vector;\n}\n\nEigen::Vector3d ComputeTranslation(\n    const InputDatum& input_datum,\n    const Eigen::Quaterniond& rotation,\n    const std::vector<Eigen::Matrix3d>& v_matrices) {\n  Eigen::Vector3d translation = Eigen::Vector3d::Zero();\n  for (int i = 0; i < input_datum.world_points.size(); ++i) {\n    translation +=\n        v_matrices[i] *\n        (rotation * input_datum.world_points[i] - input_datum.ray_origins[i]);\n  }\n  return translation;\n}\n\nstd::vector<Eigen::Vector3d> ComputeTranslations(\n    const InputDatum& input_datum,\n    const std::vector<Eigen::Quaterniond>& rotations,\n    const std::vector<Eigen::Matrix3d>& v_matrices) {\n  std::vector<Eigen::Vector3d> translations(rotations.size());\n  const int num_points = input_datum.world_points.size();\n  const int num_rotations = rotations.size();\n  for (int i = 0; i < num_rotations; ++i) {\n    translations[i] = ComputeTranslation(input_datum, rotations[i], v_matrices);\n  }\n  return translations;\n}\n\nstd::vector<double> ComputeCostsAndRankSolutions(\n    const Upnp::CostParameters& cost_params,\n    std::vector<Eigen::Quaterniond>* solution_rotations,\n    std::vector<Eigen::Vector3d>* solution_translations) {\n  std::vector<double> costs(solution_rotations->size(), 0.0);\n  std::vector<std::pair<int, double>> indexes_and_costs;\n  indexes_and_costs.reserve(costs.size());\n  // 1. Compute the costs of the solutions.\n  for (int i = 0; i < costs.size(); ++i) {\n    costs[i] = Upnp::EvaluateCost(cost_params, solution_rotations->at(i));\n    indexes_and_costs.emplace_back(i, costs[i]);\n  }\n\n  // 2. Sort the costs such that the best rotation (i.e., lowest error) is the\n  // first solution.\n  std::sort(indexes_and_costs.begin(), indexes_and_costs.end(),\n            [](const std::pair<int, double>& lhs,\n               const std::pair<int, double>& rhs) {\n              return lhs.second < rhs.second;\n            });\n\n  // 3. Rank the solutions.\n  std::vector<Eigen::Quaterniond> ranked_rotations(costs.size());\n  std::vector<Eigen::Vector3d> ranked_translations(costs.size());\n  for (int i = 0; i < costs.size(); ++i) {\n    costs[i] = indexes_and_costs[i].second;\n    ranked_rotations[i] = solution_rotations->at(indexes_and_costs[i].first);\n    ranked_translations[i] =\n        solution_translations->at(indexes_and_costs[i].first);\n  }\n\n  *solution_rotations = std::move(ranked_rotations);\n  *solution_translations = std::move(ranked_translations);\n  \n  return costs;\n}\n\nvoid DiscardBadSolutions(const InputDatum& input_datum,\n                         std::vector<Eigen::Quaterniond>* solution_rotations,\n                         std::vector<Eigen::Vector3d>* solution_translations) {\n  CHECK_EQ(CHECK_NOTNULL(solution_rotations)->size(),\n           CHECK_NOTNULL(solution_translations)->size());\n  std::vector<Eigen::Quaterniond> final_rotations;\n  std::vector<Eigen::Vector3d> final_translations;\n  final_rotations.reserve(solution_rotations->size());\n  final_translations.reserve(solution_translations->size());\n\n  // Useful aliases.\n  const std::vector<Eigen::Vector3d>& world_points = input_datum.world_points;\n  const std::vector<Eigen::Vector3d>& ray_origins = input_datum.ray_origins;\n  const std::vector<Eigen::Vector3d>& ray_directions =\n      input_datum.ray_directions;\n\n  // For every computed solution, check that points are in front of camera.\n  for (int i = 0; i < solution_rotations->size(); ++i) {\n    const Eigen::Quaterniond& soln_rotation = solution_rotations->at(i);\n    const Eigen::Vector3d& soln_translation = solution_translations->at(i);\n\n    // Check that all points are in front of the camera. Discard the solution\n    // if this is not the case.\n    bool all_points_in_front_of_camera = true;\n\n    for (int j = 0; j < world_points.size(); ++j) {\n      const Eigen::Vector3d transformed_point =\n          soln_rotation * world_points[j] + soln_translation - ray_origins[j];\n\n      // Find the rotation that puts the image ray at [0, 0, 1] i.e. looking\n      // straightforward from the camera.\n      const Eigen::Quaterniond unrot =\n          Eigen::Quaterniond::FromTwoVectors(ray_directions[j],\n                                             Eigen::Vector3d::UnitZ());\n\n      // Rotate the transformed point and check if the z coordinate is\n      // negative. This will indicate if the point is projected behind the\n      // camera.\n      const Eigen::Vector3d rotated_projection = unrot * transformed_point;\n      if (rotated_projection.z() < 0) {\n        all_points_in_front_of_camera = false;\n        break;\n      }\n    }\n\n    if (all_points_in_front_of_camera) {\n      final_rotations.emplace_back(soln_rotation);\n      final_translations.emplace_back(soln_translation);\n    }\n  }\n\n  // Set the final solutions.\n  std::swap(*solution_rotations, final_rotations);\n  std::swap(*solution_translations, final_translations);\n}\n\n// The observed pattern is that duplicate rotations appear consequtively in the\n// vector, i.e., rotation[i] == rotation[i + 1] is common.\nstd::vector<Eigen::Quaterniond> RemoveDuplicateRotations(\n    const std::vector<Eigen::Quaterniond>& candidate_rotations) {\n  const double kAngleThreshold = DegToRad(0.1);\n  std::vector<Eigen::Quaterniond> rotations;\n  rotations.reserve(candidate_rotations.size());\n\n  // If no rotations then return empty vector.\n  if (candidate_rotations.empty()) {\n    return rotations;\n  }\n\n  for (int i = 0; i < candidate_rotations.size(); ++i) {\n    bool duplicate_rotation = false;\n    const Eigen::Quaterniond& candidate_rotation = candidate_rotations[i];\n    for (int j = rotations.size() - 1; j >= 0; --j) {\n      if (candidate_rotation.angularDistance(rotations[j]) < kAngleThreshold) {\n        duplicate_rotation = true;\n        break;\n      }\n    }\n    if (!duplicate_rotation) {\n      rotations.push_back(candidate_rotation);\n    }\n  }\n  return rotations;\n}\n\n}  // namespace\n\ninline std::vector<Eigen::Quaterniond>\nUpnp::ComputeRotations(const int num_correspondences) {\n  // Build the action matrix.\n  std::vector<Eigen::Quaterniond> candidate_rotations;\n  if (use_minimal_template_ && num_correspondences <= kNumMinCorrespondences) {\n    candidate_rotations = SolveForRotationsFromMinimalSample();\n  }\n  candidate_rotations = SolveForRotationsFromNonMinimalSample();\n  // Remove duplicate solutions.\n  return RemoveDuplicateRotations(candidate_rotations);\n}\n\ndouble Upnp::EvaluateCost(const Upnp::CostParameters& parameters,\n                          const Eigen::Quaterniond& rotation) {\n  // Compute the quaternion vector.\n  const Vector10d rotation_vector = ComputeRotationVector(rotation);\n  return (rotation_vector.transpose() *\n          parameters.quadratic_penalty_mat * rotation_vector +\n          2.0 * parameters.linear_penalty_vector.transpose() *\n          rotation_vector)(0, 0) + parameters.gamma;\n}\n\ndouble Upnp::ComputeResidual(const Eigen::Vector3d& ray_origin,\n                             const Eigen::Vector3d& ray_direction,\n                             const Eigen::Vector3d& world_point,\n                             const Eigen::Quaterniond& rotation,\n                             const Eigen::Vector3d& translation) {\n  const Eigen::Quaterniond unrot =\n      Eigen::Quaterniond::FromTwoVectors(ray_direction,\n                                         Eigen::Vector3d::UnitZ());\n  const Eigen::Vector3d reprojected_point =\n      rotation * world_point + translation - ray_origin;\n  const Eigen::Vector3d unrot_reprojected_point = unrot * reprojected_point;\n  const Eigen::Vector3d unrot_ray_direction = unrot * ray_direction;\n  return (unrot_reprojected_point.hnormalized() -\n          unrot_ray_direction.hnormalized()).norm();\n}\n\nstd::vector<Eigen::Matrix3d> Upnp::ComputeCostParameters(\n    const std::vector<Eigen::Vector3d>& ray_origins,\n    const std::vector<Eigen::Vector3d>& ray_directions,\n    const std::vector<Eigen::Vector3d>& world_points) {\n  const InputDatum input_datum(ray_origins, ray_directions, world_points);\n  // 1. Compute the H matrix and the outer products of the ray directions.\n  std::vector<Eigen::Matrix3d> outer_products;\n  const Eigen::Matrix3d h_matrix =\n      ComputeHMatrixAndRayDirectionsOuterProducts(input_datum, &outer_products);\n\n  // 2. Compute matrices J and G from page 132 or 6-th page in the paper.\n  Matrix3x10d g_matrix;\n  Eigen::Vector3d j_matrix;\n  const std::vector<Eigen::Matrix3d> v_matrices =\n      ComputeHelperMatrices(input_datum,\n                            outer_products,\n                            h_matrix,\n                            &g_matrix,\n                            &j_matrix);\n\n  // 3. Compute matrix the block-matrix of matrix M from Eq. 17.\n  theia::ComputeCostParameters(input_datum,\n                               outer_products,\n                               g_matrix,\n                               j_matrix,\n                               &cost_params_);\n\n  return v_matrices;\n}\n\n\nstd::vector<Eigen::Quaterniond> Upnp::SolveForRotationsFromNonMinimalSample() {\n  std::vector<Eigen::Quaterniond> rotations(kNumMaxRotationsExploitingSymmetry);\n  // Build action matrix.\n  const Matrix8d action_matrix = BuildActionMatrixUsingSymmetry(\n      cost_params_.quadratic_penalty_mat,\n      cost_params_.linear_penalty_vector,\n      &non_minimal_sample_template_matrix_);\n\n  const Eigen::EigenSolver<Matrix8d> eigen_solver(action_matrix);\n  const Matrix8cd eigen_vectors = eigen_solver.eigenvectors();\n\n  for (int i = 0; i < rotations.size(); ++i) {\n    // According to the original implementation, the complex solutions\n    // can be good, in particular when the number of correspondences is really\n    // low. The solutions simply ignore the imaginary part.\n    rotations[i] = Eigen::Quaterniond(eigen_vectors(4, i).real(),\n                                      eigen_vectors(5, i).real(),\n                                      eigen_vectors(6, i).real(),\n                                      eigen_vectors(7, i).real()).normalized();\n  }\n\n  return rotations;\n}\n\nstd::vector<Eigen::Quaterniond> Upnp::SolveForRotationsFromMinimalSample() {\n  std::vector<Eigen::Quaterniond> rotations(kNumMaxRotations);\n  // Build action matrix.\n  const Matrix16d action_matrix =\n      BuildActionMatrix(cost_params_.quadratic_penalty_mat,\n                        cost_params_.linear_penalty_vector,\n                        &minimal_sample_template_matrix_);\n\n  const Eigen::EigenSolver<Matrix16d> eigen_solver(action_matrix, true);\n  const Matrix16cd eigen_vectors = eigen_solver.eigenvectors();\n\n  for (int i = 0; i < rotations.size(); ++i) {\n    // According to the original implementation, the complex solutions\n    // can be good, in particular when the number of correspondences is really\n    // low. The solutions simply ignore the imaginary part.\n    Eigen::Vector4d quaternion(eigen_vectors(11, i).real(),\n                               eigen_vectors(12, i).real(),\n                               eigen_vectors(13, i).real(),\n                               eigen_vectors(14, i).real());\n\n    if (quaternion[0] < 0.0) {\n      quaternion *= -1.0;\n    }\n\n    rotations[i] = Eigen::Quaterniond(quaternion[0],\n                                      quaternion[1],\n                                      quaternion[2],\n                                      quaternion[3]).normalized();\n  }\n\n  return rotations;\n}\n\nbool Upnp::EstimatePose(const std::vector<Eigen::Vector3d>& ray_origins,\n                        const std::vector<Eigen::Vector3d>& ray_directions,\n                        const std::vector<Eigen::Vector3d>& world_points,\n                        std::vector<Eigen::Quaterniond>* solution_rotations,\n                        std::vector<Eigen::Vector3d>* solution_translations,\n                        std::vector<double>* solution_costs) {\n  CHECK_NOTNULL(solution_rotations)->clear();\n  CHECK_NOTNULL(solution_translations)->clear();\n  CHECK_EQ(ray_origins.size(), ray_directions.size());\n  CHECK_EQ(world_points.size(), ray_directions.size());\n\n  // Compute Upnp cost parameters.\n  const InputDatum input_datum(ray_origins, ray_directions, world_points);\n  const std::vector<Eigen::Matrix3d> v_matrices =\n      ComputeCostParameters(ray_origins, ray_directions, world_points);\n\n  // Compute rotations.\n  *solution_rotations = ComputeRotations(world_points.size());\n\n  // Compute translation.\n  *solution_translations =\n      ComputeTranslations(input_datum, *solution_rotations, v_matrices);\n\n  // Discard solutions that have points behind the camera.\n  DiscardBadSolutions(input_datum, solution_rotations, solution_translations);\n\n  if (solution_costs) {\n    *solution_costs = ComputeCostsAndRankSolutions(cost_params_,\n                                                   solution_rotations,\n                                                   solution_translations);\n  }\n\n  return !solution_rotations->empty();\n}\n\nUpnp::CostParameters Upnp(const std::vector<Eigen::Vector3d>& ray_origins,\n                          const std::vector<Eigen::Vector3d>& ray_directions,\n                          const std::vector<Eigen::Vector3d>& world_points,\n                          std::vector<Eigen::Quaterniond>* solution_rotations,\n                          std::vector<Eigen::Vector3d>* solution_translations) {\n  class Upnp estimator;\n  CHECK(estimator.EstimatePose(ray_origins,\n                               ray_directions,\n                               world_points,\n                               solution_rotations,\n                               solution_translations))\n      << \"Could not estimate pose\";\n  return estimator.cost_params();\n}\n\nUpnp::CostParameters Upnp(const std::vector<Eigen::Vector2d>& normalized_pixels,\n                          const std::vector<Eigen::Vector3d>& world_points,\n                          std::vector<Eigen::Quaterniond>* solution_rotations,\n                          std::vector<Eigen::Vector3d>* solution_translations) {\n  CHECK_EQ(normalized_pixels.size(), world_points.size());\n  std::vector<Eigen::Vector3d> ray_directions(world_points.size());\n  std::vector<Eigen::Vector3d> ray_origins(world_points.size());\n\n  // Compute the ray directions and origins from the normalized pixels.\n  for (int i = 0; i < world_points.size(); ++i) {\n    ray_directions[i] = normalized_pixels[i].homogeneous().normalized();\n    ray_origins[i].setZero();\n  }\n\n  return Upnp(ray_origins, ray_directions, world_points,\n              solution_rotations, solution_translations);\n}\n\n}  // namespace theia\n\n", "meta": {"hexsha": "24e80f6704669f06636a57fc33a9c6be94af30cc", "size": 23081, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/upnp.cc", "max_stars_repo_name": "maxchernet/TheiaSfM", "max_stars_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 770.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T14:32:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:54:33.000Z", "max_issues_repo_path": "src/theia/sfm/pose/upnp.cc", "max_issues_repo_name": "maxchernet/TheiaSfM", "max_issues_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 237.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T18:50:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T05:21:48.000Z", "max_forks_repo_path": "src/theia/sfm/pose/upnp.cc", "max_forks_repo_name": "maxchernet/TheiaSfM", "max_forks_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 278.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T06:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:25:21.000Z", "avg_line_length": 40.4929824561, "max_line_length": 80, "alphanum_fraction": 0.6762271999, "num_tokens": 5721, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126792, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4323433011153569}}
{"text": "#include <iostream>\n#include <string>\n#include <armadillo>\n#include <time.h>\n#include \"ga.h\"\n\n\nusing namespace std;\nusing namespace arma;\n\n//------------------------------------------------------------------------------------------------------------------------\n//------------------------------------------------------------------------------------------------------------------------\nmat ga_eval(mat DNAS, vec fitness, double alpha, double reg, double temperature){ \n\n  int DNASrows = DNAS.n_rows;\n  int DNAScols = DNAS.n_cols;\n//  fitness *= 1/max(abs(fitness));\n\n  double myMax=max(max(abs(DNAS)));\n\n\tdouble randBuff=0;\n  double aveDNAS=sum(sum(abs(DNAS),0)) /DNASrows/DNAScols;\n\n\tdouble mutRat=0.1*temperature;//*DNAScols;\n\tdouble mutAmmount=0.001*aveDNAS*temperature;\n\n  double bigMutRat=0.001*temperature;//*DNAScols;\n\tdouble bigMutAmmount=0.005*aveDNAS*temperature;\n\n  double veryBigMutRat=0.0001*temperature;//*DNAScols;\n\tdouble verBigMutAmmount=1.0*aveDNAS*temperature;\n\n\tint decision[2*DNASrows];\n\tint myindex;\n\n  rowvec baby = zeros<rowvec>(DNAScols);\n\tvec orderedV(DNASrows);\n\n\tmat orderedDNAS(DNASrows,DNAScols);\n\tmat newDNAS(DNASrows,DNAScols);\n  // without this activation, higher fitness the better.\n fitness.save(\"fitness.save\",raw_ascii);\n\tfitness=-fitness - reg*sum(DNAS%DNAS,1);\n vec regVec = reg*sum(DNAS%DNAS,1);\n regVec.save(\"regVec.save\",raw_ascii);\n\n\n\tuvec q = sort_index(fitness,\"descend\");\n\n  for(int j=0;j < DNASrows; j++){\n     orderedDNAS.row(j)= DNAS.row(q(j)); \n\t   orderedV(j) = fitness(q(j));\n\t} \n\n \n fitness.save(\"fitness2.save\",raw_ascii);\n q.save(\"q.save\",raw_ascii);\n vec y = exp(alpha*orderedV)/sum(exp(alpha*orderedV));\n y.save(\"y.save\",raw_ascii);\n vec z = cumsum(y); \n z.save(\"z.save\",raw_ascii);\n\n y.save(\"distri.dat\",raw_ascii);\n z.save(\"cumsum.dat\",raw_ascii);\n\n  for(int j=0;j < 2*DNASrows; j++){\n    myindex = index_min(abs(z - (double)(rand() + 1)/(RAND_MAX))  );\n    decision[j] = myindex;\n  }\n\n    //BEGIN MATING RITUAL\t\n\t  for(int i=0; i < 2*DNAS.n_rows-1; i = i + 2){\n\t\t//cout << \"THE I\" << (i)/2 << endl;\n       baby =  orderedDNAS.row(decision[i]);\n\t   //MIXING\n\t  for(int j=0; j <DNAScols; j++){\n       if((double)(rand() + 1)/(RAND_MAX) < 0.5) baby(j) = orderedDNAS.row(decision[i+1])(j);\n\t  }\n\t  //SMALL MUTATION\n\t  for(int j=0; j <DNAScols; j++){\n       randBuff = (double)(rand() + 1)/(RAND_MAX);\n       if((double)(rand() + 1)/(RAND_MAX) < mutRat) baby(j) = baby(j) + baby(j) * mutAmmount*(2*randBuff-1);\n\t  }\n\t  //LARGE MUTATION\n\t  for(int j=0; j <DNAScols; j++){\n       randBuff = (double)(rand() + 1)/(RAND_MAX);\n       if((double)(rand() + 1)/(RAND_MAX) < bigMutRat) baby(j) = baby(j) + baby(j) * bigMutAmmount*(2*randBuff-1);\n\t  }\n\t  for(int j=0; j <DNAScols; j++){\n       randBuff = (double)(rand() + 1)/(RAND_MAX);\n       if((double)(rand() + 1)/(RAND_MAX) < veryBigMutRat) baby(j) = baby(j) + baby(j) * verBigMutAmmount*(2*randBuff-1);\n\t  }\n\n\tnewDNAS.row(i/2) = baby; \n\t}\n\n\n\treturn newDNAS;\n}\n//------------------------------------------------------------------------------------------------------------------------\n//------------------------------------------------------------------------------------------------------------------------\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "6719c95ebd104c96c5c9fc230f7969cd3e659c99", "size": 3264, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ga.cpp", "max_stars_repo_name": "Aki78/PongAI", "max_stars_repo_head_hexsha": "dbda72f5aa13917ec97adf26b839446d3cfaa888", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ga.cpp", "max_issues_repo_name": "Aki78/PongAI", "max_issues_repo_head_hexsha": "dbda72f5aa13917ec97adf26b839446d3cfaa888", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ga.cpp", "max_forks_repo_name": "Aki78/PongAI", "max_forks_repo_head_hexsha": "dbda72f5aa13917ec97adf26b839446d3cfaa888", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-20T09:44:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-20T09:44:29.000Z", "avg_line_length": 20.5283018868, "max_line_length": 122, "alphanum_fraction": 0.5321691176, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933315126792, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4323433011153569}}
{"text": "/*\n* Copyright 2019 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés\n*/\n\n /*\n * \\author Christian Bouchard\n */\n\n#ifndef HULLOVERLAP_HPP\n#define HULLOVERLAP_HPP\n\n#include <iostream>\n#include <cstdint>\n\n#include <vector>\n\n#include <utility>      // std::pair, std::make_pair\n\n#include <pcl/common/common_headers.h>\n\n#include <pcl/point_types.h>\n#include <pcl/surface/concave_hull.h>\n\n#include <pcl/PointIndices.h>\n\n#include <pcl/ModelCoefficients.h>\n#include <pcl/filters/project_inliers.h>\n\n#include <pcl/segmentation/extract_polygonal_prism_data.h>\n\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry> // For cross product\n\n\nclass HullOverlap \n{\n\npublic:    \n\n\t/**\n\t* Creates a HullOverlap\n\t*\n\t* @param line1In Point cloud for line #1\n\t* @param line2In Point cloud for line #2\n    * @param a projection plane coefficient 'a' in ax + by + cz + d = 0\n    * @param b projection plane coefficient 'b' in ax + by + cz + d = 0\n    * @param c projection plane coefficient 'c' in ax + by + cz + d = 0\n    * @param d projection plane coefficient 'd' in ax + by + cz + d = 0\n    * @param alpha1 Concave hull computation parameter to use with line #1\n    * @param alpha2 Concave hull computation parameter to use with line #2\n\t*/\n    HullOverlap( pcl::PointCloud<pcl::PointXYZ>::ConstPtr line1In, \n                    pcl::PointCloud<pcl::PointXYZ>::ConstPtr line2In,\n                    double a, double b, double c, double d,\n                    double alphaLine1 = 1.0, double alphaLine2 = 1.0 )\n                    :   line1( line1In ), line2( line2In ),                     \n                        a( a ), b( b ), c( c ), d( d ),\n                        alphaLine1( alphaLine1 ), alphaLine2( alphaLine2 ),\n\n                        coefficients ( new pcl::ModelCoefficients() ),\n\n                        line1InPlane (new pcl::PointCloud<pcl::PointXYZ>),\n                        line2InPlane (new pcl::PointCloud<pcl::PointXYZ>),\n\n                        line1InPlane2D (new pcl::PointCloud<pcl::PointXYZ>),\n                        line2InPlane2D (new pcl::PointCloud<pcl::PointXYZ>),\n\n                        hull1Vertices (new pcl::PointCloud<pcl::PointXYZ>),\n                        hull2Vertices (new pcl::PointCloud<pcl::PointXYZ>),\n                    \n                       // Initialize to dummy values\n                       vector1( 1, 0, 0 ), vector2( 0, 1, 0 ), refPoint( 0.0, 0.0, 0.0 )\n\n    {       \n        coefficients->values.resize(4);\n        coefficients->values[0] = a;\n        coefficients->values[1] = b;\n        coefficients->values[2] = c;\n        coefficients->values[3] = d;\n    }\n\n\n\t/**\n\t* Returns a pair with the number of points in line #1 and in line #2 that are in the overlap area of the two lines.\n\t* The points are place in the point clouds pointed to by line1InBothHull and line2InBothHull\n    *    \n\t* @param[out] line1InBothHull Point cloud of points in line #1 in the overlap area of the two lines\n\t* @param[out] line2InBothHull Point cloud of points in line #2 in the overlap area of the two lines\n\t*/\n    std::pair< uint64_t, uint64_t > computePointsInBothHulls( pcl::PointCloud<pcl::PointXYZ>::Ptr line1InBothHull,\n                                                              pcl::PointCloud<pcl::PointXYZ>::Ptr line2InBothHull )\n    {\n        return computeHullsAndPointsInBothHulls( line1InBothHull, line2InBothHull, true );\n    }\n\n\nprivate:\n\n\t/**\n\t* Returns a pair with the number of points in line #1 and in line #2 that are in the overlap area of the two lines,\n\t* the points are place in the point clouds pointed to by line1InBothHull and line2InBothHull\n    *    \n\t* @param[out] line1InBothHull Point cloud of points in line #1 in the overlap area of the two lines\n\t* @param[out] line2InBothHull Point cloud of points in line #2 in the overlap area of the two lines\n    * @param[in] line2InBothHull minimalMemory bool variable, true to specify to try and minimize the memory usage\n\t*/\n    // Was public when wanted to look at details of projection, etc\n    std::pair< uint64_t, uint64_t > computeHullsAndPointsInBothHulls( pcl::PointCloud<pcl::PointXYZ>::Ptr line1InBothHull = nullptr,\n                                                                        pcl::PointCloud<pcl::PointXYZ>::Ptr line2InBothHull = nullptr, \n                                                                        const bool minimalMemory = false )\n    {\n        \n        if ( line1InBothHull != nullptr )\n            line1InBothHull->clear();\n\n        if ( line2InBothHull != nullptr )\n            line2InBothHull->clear();\n\n\n        std::cout << \"\\nProjecting line 1 in plane\\n\" << std::endl;\n\n        // Project line 1 in plane\n        createCloudFromProjectionInPlane( line1, line1InPlane );\n\n        std::cout << \"line1InPlane->points.size(): \" << line1InPlane->points.size() << \"\\n\" << std::endl;        \n\n        computeTwoVectorsAndRefPoint();\n\n        std::cout << \"\\nExpressing points of line 1 in the projection plane using a 2D coordinate system\\n\" << std::endl;\n\n        createCloudInPlane2D( line1InPlane, line1InPlane2D );    \n\n        if ( minimalMemory )\n        {\n            // Delete the dynamically allocated memory\n            line1InPlane.reset();\n            line1InPlane = nullptr;            \n        }\n\n        std::cout << \"line1InPlane2D->points.size(): \" << line1InPlane2D->points.size() << \"\\n\" << std::endl; \n\n\n        std::cout << \"\\nProjecting line 2 in plane\\n\" << std::endl;\n\n        // Project line 2 in plane\n        createCloudFromProjectionInPlane( line2, line2InPlane );\n\n        std::cout << \"line2InPlane->points.size(): \" << line2InPlane->points.size() << \"\\n\" << std::endl;\n\n\n        std::cout << \"\\nExpressing points of line 2 in the projection plane using a 2D coordinate system\\n\" << std::endl;\n\n        createCloudInPlane2D( line2InPlane, line2InPlane2D );\n\n        if ( minimalMemory )\n        {\n            // Delete the dynamically allocated memory\n            line2InPlane.reset();\n            line2InPlane = nullptr;            \n        }\n\n\n        std::cout << \"line2InPlane2D->points.size(): \" << line2InPlane2D->points.size() << \"\\n\" << std::endl;\n\n\n        //http://www.pointclouds.org/documentation/tutorials/hull_2d.php\n\n        std::cout << \"\\nFinding Hull 1\\n\" << std::endl;\n\n        // Create a Concave Hull for line 1\n        computeVerticesOfConcaveHull( line1InPlane2D, alphaLine1, hull1Vertices, hull1PointIndices, ! minimalMemory );\n\n\n        std::cout << \"Finding Hull 2\\n\" << std::endl;\n\n        // Create a Concave Hull for line 2\n        computeVerticesOfConcaveHull( line2InPlane2D, alphaLine2, hull2Vertices, hull2PointIndices, ! minimalMemory );    \n\n        std::cout << \"hull1Vertices->points.size(): \" << hull1Vertices->points.size() << \"\\n\" \n            << \"hull2Vertices->points.size(): \" << hull2Vertices->points.size() << \"\\n\" << std::endl;\n\n\n        // If the hulls of the lines where found correctly, points of line 1 are within the hull of line 1.\n        // So only need to check that a point of line 1 is part of hull 2 to know that it is part of both hulls.\n        // Same idea for points of line 2.\n\n\n        if ( line1InBothHull != nullptr && line2InBothHull != nullptr )\n        {\n            if ( minimalMemory )\n            {\n                std::cout << \"Finding points of Line 1 inside Hull 2\\n\\n\" << std::endl;\n            \n                findPointsInHullOnlyPoints( line1, line1InPlane2D, line1InBothHull, hull2Vertices );\n\n                // Delete the dynamically allocated memory\n                line1InPlane2D.reset();\n                line1InPlane2D = nullptr;    \n\n                hull2Vertices.reset();\n                hull2Vertices = nullptr;\n\n                std::cout << \"Finding points of Line 2 inside Hull 1\\n\\n\" << std::endl;\n\n                findPointsInHullOnlyPoints( line2, line2InPlane2D, line2InBothHull, hull1Vertices );\n\n                // Delete the dynamically allocated memory\n                line2InPlane2D.reset();\n                line2InPlane2D = nullptr;    \n\n                hull1Vertices.reset();\n                hull1Vertices = nullptr;\n\n                std::cout << \"line1InBothHull->points.size(): \" << line1InBothHull->points.size() << \"\\n\" \n                    << \"line2InBothHull->points.size(): \" << line2InBothHull->points.size() << \"\\n\" << std::endl;\n\n                return std::make_pair( line1InBothHull->size(), line2InBothHull->size() );\n\n            }\n            else\n            {\n                \n                std::cout << \"Finding points of Line 1 inside Hull 2 (and the indices)\\n\\n\" << std::endl;\n            \n                findPointsInHull( line1, line1InPlane2D, line1InBothHull, line1InBothHullPointIndices, hull2Vertices );\n\n\n                std::cout << \"Finding points of Line 2 inside Hull 1 (and the indices)\\n\\n\" << std::endl;\n\n                findPointsInHull( line2, line2InPlane2D, line2InBothHull, line2InBothHullPointIndices, hull1Vertices );\n\n\n                std::cout << \"line1InBothHull->points.size(): \" << line1InBothHull->points.size() << \"\\n\" \n                    << \"line2InBothHull->points.size(): \" << line2InBothHull->points.size() << \"\\n\" << std::endl;\n\n                return std::make_pair( line1InBothHull->size(), line2InBothHull->size() );\n\n\n            }\n            \n            \n        }   \n        else\n        {\n            std::cout << \"Finding indices of points of Line 1 inside Hull 2\\n\\n\" << std::endl;\n        \n            findPointsInHullOnlyPointIndices( line1InPlane2D, line1InBothHullPointIndices, hull2Vertices );\n\n\n            std::cout << \"Finding indices of points of Line 2 inside Hull 1\\n\\n\" << std::endl;\n\n            findPointsInHullOnlyPointIndices( line2InPlane2D, line2InBothHullPointIndices, hull1Vertices );\n\n\n            std::cout << \"line1InBothHullPointIndices.size(): \" << line1InBothHullPointIndices.size() << \"\\n\" \n                << \"line2InBothHullPointIndices.size(): \" << line2InBothHullPointIndices.size() << \"\\n\" << std::endl; \n\n            return std::make_pair( line1InBothHullPointIndices.size(), line2InBothHullPointIndices.size() );\n        }\n\n\n    }\n\n    // These functions were public when wanted to look at details of projection, etc\n    // pcl::PointCloud<pcl::PointXYZ>::ConstPtr getConstPtrLineInPlane( const bool isLine1 )\n    // {\n    //     if ( isLine1 )\n    //         return line1InPlane;\n    //     else \n    //         return line2InPlane;\n    // }\n\n    // const std::vector< int > * getConstPtrVerticesIndices( const bool isLine1 )\n    // {\n    //     if ( isLine1 )\n    //         return & ( hull1PointIndices.indices );\n    //     else \n    //         return & ( hull2PointIndices.indices );\n    // }\n\n    // const std::vector< uint64_t > * getConstPtrlineInBothHullPointIndices( const bool isLine1 )\n    // {\n    //     if ( isLine1 )\n    //         return & ( line1InBothHullPointIndices );\n    //     else \n    //         return & ( line2InBothHullPointIndices );\n    // }\n\n\n\n\n\n\t/**\n\t* Computes the projection of a point cloud onto a plane\n    *  \n    * @param[in] cloudIn Point cloud to project on the plane\n    * @param[out] cloudOut Point cloud resulting from the projection\n\t*/\n    void createCloudFromProjectionInPlane( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,\n                                                pcl::PointCloud<pcl::PointXYZ>::Ptr cloudOut )\n    {\n        cloudOut->clear();\n        cloudOut->reserve( cloudIn->points.size() );\n\n        // Create the filtering object\n        pcl::ProjectInliers<pcl::PointXYZ> proj;\n        proj.setModelType( pcl::SACMODEL_PLANE );\n\n        proj.setInputCloud( cloudIn );\n        proj.setModelCoefficients( coefficients );\n\n        proj.filter( *cloudOut );\n    }\n\n\n\t/**\n\t* Computes two vectors and sets a reference point used to express point positions on the\n    * projection plane using only two dimensions \n\t*/\n    void computeTwoVectorsAndRefPoint()\n    {\n\n        // Two vectors and a reference point to span the projection plane\n        // so that points in the projection plane can be expressed in\n        // a coordinate system with vector1, vector2, and refPoint.\n\n        refPoint = line1InPlane->points[ 0 ];\n\n        // Vector #1: from first point in line to last point in line, normalized    \n\n        const uint64_t nbPointLine1 = line1InPlane->points.size();\n\n\n        vector1 << line1InPlane->points[ nbPointLine1 - 1 ].x - line1InPlane->points[ 0 ].x,\n                    line1InPlane->points[ nbPointLine1 - 1 ].y - line1InPlane->points[ 0 ].y,\n                    line1InPlane->points[ nbPointLine1 - 1 ].z - line1InPlane->points[ 0 ].z;\n\n        std::cout << \"vector1 before normalization:\\n\" << vector1 << \"\\n\\n\"; \n\n\n        vector1 = vector1 / vector1.norm();\n\n        std::cout << \"vector1 after normalization:\\n\" << vector1 << \"\\n\\n\"; \n\n\n        Eigen::Vector3d normalToPlane;\n\n        normalToPlane <<  a, b, c;\n\n        // Vector #2: perpendicular to the normal to the plane and to vector #1\n        vector2 = normalToPlane.cross( vector1 );\n\n        std::cout << \"vector2 before normalization:\\n\" << vector2 << \"\\n\\n\"; \n\n\n        vector2 = vector2 / vector2.norm();\n\n        std::cout << \"vector2 after normalization:\\n\" << vector2 << \"\\n\\n\";   \n\n        // Sanity check\n        std::cout << \"vector1 dot vector2: \" << vector1.dot( vector2 ) << \"    (should be 0)\\n\\n\";\n    }\n\n\n\t/**\n\t* Computes a 2D representation of points on the projection plane\n    *  \n    * @param[in] cloudIn Point cloud on the projection plane expressed in 3D\n    * @param[out] cloudOut Point cloud on the projection plane expressed in 2D\n\t*/\n    void createCloudInPlane2D( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,\n                            pcl::PointCloud<pcl::PointXYZ>::Ptr cloudOut )\n    {\n        // Build a point cloud where points in the projection plane are expressed in\n        // the coordinate system with vector1, vector2, and refPoint.\n\n        cloudOut->clear();\n        cloudOut->reserve( cloudIn->points.size() );\n\n        for ( uint64_t count = 0; count < cloudIn->points.size(); count++ )\n        {\n            pcl::PointXYZ point;\n\n            // projection along vector 1\n            point.x = ( cloudIn->points[ count ].x - refPoint.x ) * vector1( 0 )\n                        + ( cloudIn->points[ count ].y - refPoint.y ) * vector1( 1 )\n                        + ( cloudIn->points[ count ].z - refPoint.z ) * vector1( 2 );\n\n            // projection along vector 2\n            point.y = ( cloudIn->points[ count ].x - refPoint.x ) * vector2( 0 )\n                        + ( cloudIn->points[ count ].y - refPoint.y ) * vector2( 1 )\n                        + ( cloudIn->points[ count ].z - refPoint.z ) * vector2( 2 );                    \n\n            point.z = 0;\n\n            cloudOut->push_back( point );\n\n        }\n    }\n\n\n\t/**\n\t* Computes the vertices of a concave hull for points on the projection plane\n    *  \n    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D\n    * @param[in] alpha Concave hull computation parameter to use\n    * @param[out] hullVertices Computed vertices of the concave hull\n    * @param[out] hullPointIndices Indices of the points in cloudIn making up the hull\n    * @param[in] keepInformation bool variable, true to specify to put the indices of the points in cloudIn in hullPointIndices\n\t*/\n    void computeVerticesOfConcaveHull( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,\n                                        const double alpha, \n                                        pcl::PointCloud<pcl::PointXYZ>::Ptr hullVertices,\n                                        pcl::PointIndices & hullPointIndices, const bool keepInformation = true )\n    {\n\n        hullVertices->clear();\n\n        pcl::ConcaveHull<pcl::PointXYZ> concaveHull;\n\n        if ( keepInformation )\n            concaveHull.setKeepInformation( true ); // To be able to use function getHullPointIndices()\n\n        concaveHull.setInputCloud( cloudIn );\n        concaveHull.setAlpha( alpha );\n        concaveHull.reconstruct( * hullVertices );\n\n        if ( keepInformation )\n            // Get indices of points making the hull\n            concaveHull.getHullPointIndices( hullPointIndices );\n    }\n\n\t/**\n\t* Find points that are within a concave hull. \n    * Provides the points and their indices within the original line\n    *  \n    * @param[in] lineOriginal Point cloud of points on the line\n    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D\n    * @param[out] cloudOut Point cloud of points on the line that are within the hull\n    * @param[out] indexPointInHull Indices of the points on the line that are within the hull\n    * @param[in] hullVertices Vertices of the concave hull\n\t*/\n    void findPointsInHull( pcl::PointCloud<pcl::PointXYZ>::ConstPtr lineOriginal,\n                                pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn, \n                                pcl::PointCloud<pcl::PointXYZ>::Ptr cloudOut,\n                                std::vector< uint64_t > & indexPointInHull,\n                                pcl::PointCloud<pcl::PointXYZ>::ConstPtr hullVertices )    \n    {\n        cloudOut->clear();\n        indexPointInHull.clear();\n\n        for ( uint64_t count = 0; count < cloudIn->points.size(); count++ )\n        {\n            if ( pcl::isXYPointIn2DXYPolygon( cloudIn->points[ count ], *hullVertices ) )\n            {\n                cloudOut->push_back( lineOriginal->points[ count ] );\n                indexPointInHull.push_back( count );\n            }\n        }\n    \n    }\n\n\n\t/**\n\t* Find indices of points that are within a concave hull. \n    *  \n    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D\n    * @param[out] indexPointInHull Indices of the points on the line that are within the hull\n    * @param[in] hullVertices Vertices of the concave hull\n\t*/\n    void findPointsInHullOnlyPointIndices( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn, \n                                    std::vector< uint64_t > & indexPointInHull,\n                                    pcl::PointCloud<pcl::PointXYZ>::ConstPtr hullVertices )    \n    {\n        indexPointInHull.clear();\n\n        for ( uint64_t count = 0; count < cloudIn->points.size(); count++ )\n        {\n            if ( pcl::isXYPointIn2DXYPolygon( cloudIn->points[ count ], *hullVertices ) )\n                indexPointInHull.push_back( count );\n        }\n    \n    }\n\n\t/**\n\t* Find points that are within a concave hull. \n    *  \n    * @param[in] lineOriginal Point cloud of points on the line\n    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D\n    * @param[out] cloudOut Point cloud of points on the line that are within the hull\n    * @param[in] hullVertices Vertices of the concave hull\n\t*/\n    void findPointsInHullOnlyPoints( pcl::PointCloud<pcl::PointXYZ>::ConstPtr lineOriginal,\n                                    pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn, \n                                    pcl::PointCloud<pcl::PointXYZ>::Ptr cloudOut,\n                                    pcl::PointCloud<pcl::PointXYZ>::ConstPtr hullVertices )    \n    {\n        cloudOut->clear();\n\n        for ( uint64_t count = 0; count < cloudIn->points.size(); count++ )\n        {\n            if ( pcl::isXYPointIn2DXYPolygon( cloudIn->points[ count ], *hullVertices ) )\n                cloudOut->push_back( lineOriginal->points[ count ] );\n        }\n    \n    }\n\n\n\n\n// ----------------------------- Variables ------------------------------------------------\n\n    /**Point cloud for line #1*/\n    const pcl::PointCloud<pcl::PointXYZ>::ConstPtr line1;\n\n    /**Point cloud for line #2*/\n    const pcl::PointCloud<pcl::PointXYZ>::ConstPtr line2;\n\n    \n    /**Projection plane coefficient 'a' in ax + by + cz + d = 0*/\n    const double a;\n\n    /**Projection plane coefficient 'b' in ax + by + cz + d = 0*/\n    const double b; \n\n    /**Projection plane coefficient 'c' in ax + by + cz + d = 0*/\n    const double c; \n\n    /**Projection plane coefficient 'd' in ax + by + cz + d = 0*/\n    const double d;\n\n\n    /**Concave hull computation parameter to use with line #1*/\n    double alphaLine1; // Alpha value to compute the concave hull for line #1\n\n    /**Concave hull computation parameter to use with line #2*/\n    double alphaLine2; // Alpha value to compute the concave hull for line #2\n\n    /**Coefficients for the plane, ax + by + cz + d = 0 */\n    pcl::ModelCoefficients::Ptr coefficients;\n\n    /**Point cloud of the projection of line #1 on the plane, expressed in 3D*/\n    pcl::PointCloud<pcl::PointXYZ>::Ptr line1InPlane;\n\n    /**Point cloud of the projection of line #2 on the plane, expressed in 3D*/    \n    pcl::PointCloud<pcl::PointXYZ>::Ptr line2InPlane;\n\n    /**Point cloud of the projection of line #1 on the plane, expressed in 2D*/\n    pcl::PointCloud<pcl::PointXYZ>::Ptr line1InPlane2D;\n\n    /**Point cloud of the projection of line #2 on the plane, expressed in 2D*/\n    pcl::PointCloud<pcl::PointXYZ>::Ptr line2InPlane2D;\n\n\n    /**Vertices of the concave hull for line #1*/\n    pcl::PointCloud<pcl::PointXYZ>::Ptr hull1Vertices;\n\n    /**Vertices of the concave hull for line #2*/\n    pcl::PointCloud<pcl::PointXYZ>::Ptr hull2Vertices;\n\n    /**Indices of the points in line #1 whose projection on the plane makes up its hull*/\n    pcl::PointIndices hull1PointIndices;\n\n    /**Indices of the points in line #2 whose projection on the plane makes up its hull*/\n    pcl::PointIndices hull2PointIndices;\n\n    /**Indices of the points in line #1 that are within both hulls*/\n    std::vector< uint64_t > line1InBothHullPointIndices;\n\n    /**Indices of the points in line #2 that are within both hulls*/\n    std::vector< uint64_t > line2InBothHullPointIndices;       \n\n\n    /**First computed orthonormal vector used to express points on the projection plane in 2D*/\n    Eigen::Vector3d vector1;\n\n    /**Second computed orthonormal vector used to express points on the projection plane in 2D*/\n    Eigen::Vector3d vector2;\n\n    /**Referenced point used to express points on the projection plane in 2D*/\n    pcl::PointXYZ refPoint;\n\n};\n\n#endif", "meta": {"hexsha": "7384258eef2844388456f562ba6a2cb9d7ebb825", "size": 22154, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/HullOverlap.hpp", "max_stars_repo_name": "EmileGagne/MBES-lib", "max_stars_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HullOverlap.hpp", "max_issues_repo_name": "EmileGagne/MBES-lib", "max_issues_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HullOverlap.hpp", "max_forks_repo_name": "EmileGagne/MBES-lib", "max_forks_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8054607509, "max_line_length": 135, "alphanum_fraction": 0.599936806, "num_tokens": 5531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4323366665437445}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Geometry>\n\nnamespace dr {\n\ntemplate<typename Scalar, int AmbientDim, int MatrixOptions, int PlaneOptions>\nEigen::Matrix<Scalar, AmbientDim, 1, MatrixOptions> rejection(\n\tEigen::Matrix<Scalar, AmbientDim, 1, MatrixOptions> const & vector,\n\tEigen::Hyperplane<Scalar, AmbientDim, PlaneOptions> const & plane\n) {\n\treturn vector - plane.projection(vector);\n}\n\ntemplate<typename Scalar, int AmbientDim, int MatrixOptions, int PlaneOptions>\nEigen::Matrix<Scalar, AmbientDim, 1, MatrixOptions> reflection(\n\tEigen::Matrix<Scalar, AmbientDim, 1, MatrixOptions> const & vector,\n\tEigen::Hyperplane<Scalar, AmbientDim, PlaneOptions> const & plane\n) {\n\treturn vector - 2 * rejection(vector, plane);\n}\n\n}\n", "meta": {"hexsha": "7375c0770a99ff23a2dbb388e7eb30d5243608f6", "size": 728, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dr_eigen/plane.hpp", "max_stars_repo_name": "delftrobotics/dr_eigen", "max_stars_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-06-02T14:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-02T14:14:37.000Z", "max_issues_repo_path": "include/dr_eigen/plane.hpp", "max_issues_repo_name": "delftrobotics/dr_eigen", "max_issues_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dr_eigen/plane.hpp", "max_forks_repo_name": "delftrobotics/dr_eigen", "max_forks_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.652173913, "max_line_length": 78, "alphanum_fraction": 0.7637362637, "num_tokens": 176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.43233665945385163}}
{"text": "#pragma once\n\n#include \"coma/Core\"\n#include <Eigen/Core>\n#include <RBDyn/MultiBody.h>\n\ntemplate <int Order>\nEigen::MatrixXd makeDiag(const Eigen::MatrixXd& mat)\n{\n    constexpr int ord = Order;\n    Eigen::MatrixXd out = Eigen::MatrixXd::Zero(ord * mat.rows(), ord * mat.cols());\n    for (int i = 0; i < ord; ++i)\n        out.block(i * mat.rows(), i * mat.cols(), mat.rows(), mat.cols()) = mat;\n\n    return out;\n}\n\ntemplate <typename CrossNOp>\nEigen::MatrixXd generateD(const CrossNOp& cx)\n{\n    constexpr int n_vec = coma::internal::traits<CrossNOp>::n_vec;\n    using Scalar = typename coma::internal::traits<CrossNOp>::Scalar;\n    using mat_t = Eigen::Matrix<Scalar, 6 * n_vec, 6 * n_vec>;\n    using sub_mat_t = Eigen::Matrix<Scalar, 6, 6 * n_vec>;\n    Eigen::MatrixXd D_N = Eigen::MatrixXd::Zero(6 * (n_vec - 1), 6 * (n_vec - 1));\n    for (int i = 0; i < n_vec - 1; ++i)\n        D_N.block<6, 6>(6 * i, 6 * i) = Eigen::Matrix6d::Identity() / (i + 1);\n    return mat_t::Identity() + (mat_t() << sub_mat_t::Zero(), D_N * cx.dualMatrix().template topRows<6 * (n_vec - 1)>()).finished();\n}\n\n// M = I + Cd * I * C\ntemplate <typename Tree>\nstd::vector<Eigen::MatrixXd> getSubTreeInertia(const rbd::MultiBody& mb, const Tree& tree)\n{\n    constexpr int ord = Tree::order;\n    std::vector<Eigen::MatrixXd> M(mb.nrBodies(), Eigen::MatrixXd::Zero(6 * ord, 6 * ord));\n    const auto& bodies = mb.bodies();\n    const auto& pred = mb.predecessors();\n    for (int i = mb.nrBodies() - 1; i >= 0; --i) {\n        M[i] += makeDiag<ord>(bodies[i].inertia().matrix());\n        int p = pred[i]; // parent\n        if (p != -1) {\n            auto C_p_b = tree.links[p].inverse() * tree.links[i];\n            M[p] += C_p_b.template dualMatrix<ord>() * M[i] * C_p_b.inverse().template matrix<ord>();\n        }\n    }\n\n    return M;\n}\n\nnamespace detail {\n\ntemplate <typename Transf, typename CMTM, size_t Order>\nstruct CMTMSetter {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints);\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 0> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T);\n    }\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 1> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T, S * dqs[0].col(t).segment(pos, dof));\n    }\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 2> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T, S * dqs[0].col(t).segment(pos, dof), S * dqs[1].col(t).segment(pos, dof));\n    }\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 3> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T, S * dqs[0].col(t).segment(pos, dof), S * dqs[1].col(t).segment(pos, dof), S * dqs[2].col(t).segment(pos, dof));\n    }\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 4> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T, S * dqs[0].col(t).segment(pos, dof), S * dqs[1].col(t).segment(pos, dof), S * dqs[2].col(t).segment(pos, dof),\n            S * dqs[3].col(t).segment(pos, dof));\n    }\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 5> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T, S * dqs[0].col(t).segment(pos, dof), S * dqs[1].col(t).segment(pos, dof), S * dqs[2].col(t).segment(pos, dof),\n            S * dqs[3].col(t).segment(pos, dof), S * dqs[4].col(t).segment(pos, dof));\n    }\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 6> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T, S * dqs[0].col(t).segment(pos, dof), S * dqs[1].col(t).segment(pos, dof), S * dqs[2].col(t).segment(pos, dof),\n            S * dqs[3].col(t).segment(pos, dof), S * dqs[4].col(t).segment(pos, dof), S * dqs[5].col(t).segment(pos, dof));\n    }\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 7> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T, S * dqs[0].col(t).segment(pos, dof), S * dqs[1].col(t).segment(pos, dof), S * dqs[2].col(t).segment(pos, dof),\n            S * dqs[3].col(t).segment(pos, dof), S * dqs[4].col(t).segment(pos, dof), S * dqs[5].col(t).segment(pos, dof),\n            S * dqs[6].col(t).segment(pos, dof));\n    }\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 8> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T, S * dqs[0].col(t).segment(pos, dof), S * dqs[1].col(t).segment(pos, dof), S * dqs[2].col(t).segment(pos, dof),\n            S * dqs[3].col(t).segment(pos, dof), S * dqs[4].col(t).segment(pos, dof), S * dqs[5].col(t).segment(pos, dof),\n            S * dqs[6].col(t).segment(pos, dof), S * dqs[7].col(t).segment(pos, dof));\n    }\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 9> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T, S * dqs[0].col(t).segment(pos, dof), S * dqs[1].col(t).segment(pos, dof), S * dqs[2].col(t).segment(pos, dof),\n            S * dqs[3].col(t).segment(pos, dof), S * dqs[4].col(t).segment(pos, dof), S * dqs[5].col(t).segment(pos, dof),\n            S * dqs[6].col(t).segment(pos, dof), S * dqs[7].col(t).segment(pos, dof), S * dqs[8].col(t).segment(pos, dof));\n    }\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 10> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T, S * dqs[0].col(t).segment(pos, dof), S * dqs[1].col(t).segment(pos, dof), S * dqs[2].col(t).segment(pos, dof),\n            S * dqs[3].col(t).segment(pos, dof), S * dqs[4].col(t).segment(pos, dof), S * dqs[5].col(t).segment(pos, dof),\n            S * dqs[6].col(t).segment(pos, dof), S * dqs[7].col(t).segment(pos, dof), S * dqs[8].col(t).segment(pos, dof),\n            S * dqs[9].col(t).segment(pos, dof));\n    }\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 11> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T, S * dqs[0].col(t).segment(pos, dof), S * dqs[1].col(t).segment(pos, dof), S * dqs[2].col(t).segment(pos, dof),\n            S * dqs[3].col(t).segment(pos, dof), S * dqs[4].col(t).segment(pos, dof), S * dqs[5].col(t).segment(pos, dof),\n            S * dqs[6].col(t).segment(pos, dof), S * dqs[7].col(t).segment(pos, dof), S * dqs[8].col(t).segment(pos, dof),\n            S * dqs[9].col(t).segment(pos, dof), S * dqs[10].col(t).segment(pos, dof));\n    }\n};\n\ntemplate <typename Transf, typename CMTM>\nstruct CMTMSetter<Transf, CMTM, 12> {\n    static void impl(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n    {\n        joints.set(T, S * dqs[0].col(t).segment(pos, dof), S * dqs[1].col(t).segment(pos, dof), S * dqs[2].col(t).segment(pos, dof),\n            S * dqs[3].col(t).segment(pos, dof), S * dqs[4].col(t).segment(pos, dof), S * dqs[5].col(t).segment(pos, dof),\n            S * dqs[6].col(t).segment(pos, dof), S * dqs[7].col(t).segment(pos, dof), S * dqs[8].col(t).segment(pos, dof),\n            S * dqs[9].col(t).segment(pos, dof), S * dqs[10].col(t).segment(pos, dof), S * dqs[11].col(t).segment(pos, dof));\n    }\n};\n\n}\n\ntemplate<typename Transf, typename CMTM, size_t Order>\nvoid CMTMSet(const Transf& T, const Eigen::MatrixXd& S, const std::vector<Eigen::MatrixXd>& dqs, int t, int pos, int dof, CMTM& joints)\n{\n    detail::CMTMSetter<Transf, CMTM, Order>::impl(T, S, dqs, t, pos, dof, joints);\n}\n", "meta": {"hexsha": "79721e48d17fdf78621342e19d46e20ca0bf7a5d", "size": 8849, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "algo_v0/utils.hpp", "max_stars_repo_name": "vsamy/cdm", "max_stars_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-16T11:41:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T16:48:29.000Z", "max_issues_repo_path": "algo_v0/utils.hpp", "max_issues_repo_name": "vsamy/cdm", "max_issues_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "algo_v0/utils.hpp", "max_forks_repo_name": "vsamy/cdm", "max_forks_repo_head_hexsha": "f2d29cad0a2b349d2b6f732ab786791c35a6b509", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.320855615, "max_line_length": 144, "alphanum_fraction": 0.6114815233, "num_tokens": 2982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.43233665945385163}}
{"text": "#include <pybind11/pybind11.h>\n#include <pybind11/numpy.h>\n#include <armadillo>\n\nnamespace py = pybind11;\n\nusing namespace arma;\n\n\ntypedef py::array_t<double, py::array::f_style | py::array::forcecast> array_tf;\ntypedef py::array_t<double, py::array::c_style | py::array::forcecast> array_tc;\n\n\ncube array_to_cube(array_tf m) {\n\n    py::buffer_info _m_buff = m.request();\n    int n_rows = _m_buff.shape[0];\n    int n_cols = _m_buff.shape[1];\n    int n_slices = _m_buff.shape[2];\n\n    cube _m_arma((double *)_m_buff.ptr, n_rows, n_cols, n_slices);\n\n    return _m_arma;\n}\n\n\nmat array_to_mat(array_tf m) {\n\n    py::buffer_info _m_buff = m.request();\n    int n_rows = _m_buff.shape[0];\n    int n_cols = _m_buff.shape[1];\n\n    mat _m_arma((double *)_m_buff.ptr, n_rows, n_cols);\n\n    return _m_arma;\n}\n\n\nvec array_to_vec(array_tf m) {\n\n    py::buffer_info _m_buff = m.request();\n    int n_rows = _m_buff.shape[0];\n\n    vec _m_vec((double *)_m_buff.ptr, n_rows);\n\n    return _m_vec;\n}\n\n\narray_tf cube_to_array(cube m) {\n\n    auto _m_array = array_tf({m.n_rows, m.n_cols, m.n_slices});\n\n    py::buffer_info _m_buff = _m_array.request();\n    std::memcpy(_m_buff.ptr, m.memptr(), sizeof(double) * m.n_rows * m.n_cols * m.n_slices);\n\n    return _m_array;\n}\n\n\narray_tf mat_to_array(mat m) {\n\n    auto _m_array = array_tf({m.n_rows, m.n_cols});\n\n    py::buffer_info _m_buff = _m_array.request();\n    std::memcpy(_m_buff.ptr, m.memptr(), sizeof(double) * m.n_rows * m.n_cols);\n\n    return _m_array;\n}\n\n\narray_tf vec_to_array(vec m) {\n\n    auto _m_array = array_tf({m.n_rows});\n\n    py::buffer_info _m_buff = _m_array.request();\n    std::memcpy(_m_buff.ptr, m.memptr(), sizeof(double) * m.n_rows);\n\n    return _m_array;\n}\n\n\npy::tuple kl_divergence(array_tf _p_K, array_tf _p_kff, array_tf _p_sigma_ctl,\n                        array_tf _q_K, array_tf _q_kff, array_tf _q_sigma_ctl,\n                        array_tf _mu_x, array_tf _sigma_x,\n                        int dm_state, int dm_act, int nb_steps) {\n\n    cube p_K = array_to_cube(_p_K);\n    mat p_kff = array_to_mat(_p_kff);\n    cube p_sigma_ctl = array_to_cube(_p_sigma_ctl);\n\n    cube q_K = array_to_cube(_q_K);\n    mat q_kff = array_to_mat(_q_kff);\n    cube q_sigma_ctl = array_to_cube(_q_sigma_ctl);\n\n    mat mu_x  = array_to_mat(_mu_x);\n    cube sigma_x = array_to_cube(_sigma_x);\n\n    vec kl(nb_steps);\n\n    for(int i = 0; i < nb_steps; i++) {\n        mat q_lambda_ctl = inv_sympd(q_sigma_ctl.slice(i));\n\n        mat diff_K = (q_K.slice(i) - p_K.slice(i)).t() * q_lambda_ctl * (q_K.slice(i) - p_K.slice(i));\n        mat diff_crs = (q_K.slice(i) - p_K.slice(i)).t() * q_lambda_ctl * (- q_kff.col(i) + p_kff.col(i));\n        mat diff_kff = (- q_kff.col(i) + p_kff.col(i)).t() * q_lambda_ctl * (- q_kff.col(i) + p_kff.col(i));\n\n        kl(i) = as_scalar(0.5 * log( det(q_sigma_ctl.slice(i)) / det(p_sigma_ctl.slice(i)) )\n\t\t                  + 0.5 * trace(q_lambda_ctl * p_sigma_ctl.slice(i))\n\t\t                  - 0.5 * dm_act\n\t\t                  + 0.5 * trace(diff_K * sigma_x.slice(i))\n\t\t                  + 0.5 * mu_x.col(i).t() * diff_K * mu_x.col(i)\n\t\t                  - mu_x.col(i).t() * diff_crs\n\t\t                  + 0.5 * diff_kff);\n    }\n\n    array_tf _kl = vec_to_array(kl);\n\n    py::tuple output =  py::make_tuple(_kl);\n    return output;\n}\n\ndouble quad_expectation(array_tf _mu, array_tf _sigma_s,\n                        array_tf _Q, array_tf _q, double _q0) {\n\n    vec mu  = array_to_vec(_mu);\n    mat sigma_s = array_to_mat(_sigma_s);\n\n    mat Q = array_to_mat(_Q);\n    vec q = array_to_vec(_q);\n\n\tdouble result = as_scalar(mu.t() * Q * mu) + as_scalar(mu.t() * q) + _q0 + trace(Q * sigma_s);\n\treturn result;\n}\n\npy::tuple augment_cost(array_tf _Cxx, array_tf _cx, array_tf _Cuu,\n                       array_tf _cu, array_tf _Cxu, array_tf _c0,\n                       array_tf _K, array_tf _kff, array_tf _sigma_ctl,\n                       array_tf _alpha, int dm_state, int dm_act, int nb_steps) {\n\n    // inputs\n    cube Cxx = array_to_cube(_Cxx);\n    mat cx = array_to_mat(_cx);\n    cube Cuu = array_to_cube(_Cuu);\n    mat cu = array_to_mat(_cu);\n    cube Cxu = array_to_cube(_Cxu);\n    vec c0 = array_to_vec(_c0);\n\n    cube K = array_to_cube(_K);\n    mat kff = array_to_mat(_kff);\n    cube sigma_ctl = array_to_cube(_sigma_ctl);\n\n    vec alpha = array_to_vec(_alpha);\n\n    // outputs\n    cube agCxx(dm_state, dm_state, nb_steps + 1);\n    mat agcx(dm_state, nb_steps + 1);\n    cube agCuu(dm_act, dm_act, nb_steps + 1);\n    mat agcu(dm_act, nb_steps + 1);\n    cube agCxu(dm_state, dm_act, nb_steps + 1);\n    vec agc0(nb_steps + 1);\n\n    for (int i = 0; i < nb_steps; i++) {\n        mat lambda_ctl = inv_sympd(sigma_ctl.slice(i));\n\n        agCxx.slice(i) = Cxx.slice(i) + 0.5 * alpha(i) * K.slice(i).t() * lambda_ctl * K.slice(i);\n        agCuu.slice(i) = Cuu.slice(i) + 0.5 * alpha(i) * lambda_ctl;\n        agCxu.slice(i) = Cxu.slice(i) - 0.5 * alpha(i) * K.slice(i).t() * lambda_ctl;\n        agcx.col(i) = cx.col(i) + alpha(i) * K.slice(i).t() * lambda_ctl * kff.col(i);\n        agcu.col(i) = cu.col(i) - alpha(i) * lambda_ctl * kff.col(i);\n        agc0(i) = as_scalar(c0(i) + 0.5 * alpha(i) * log( det(2. * datum::pi * sigma_ctl.slice(i)) )\n                            + 0.5 * alpha(i) * kff.col(i).t() * lambda_ctl * kff.col(i));\n    }\n\n    // last time step\n    agCxx.slice(nb_steps) = Cxx.slice(nb_steps);\n    agcx.col(nb_steps) = cx.col(nb_steps);\n    agCuu.slice(nb_steps) = Cuu.slice(nb_steps);\n    agcu.col(nb_steps) = cu.col(nb_steps);\n    agCxu.slice(nb_steps) = Cxu.slice(nb_steps);\n    agc0(nb_steps) = c0(nb_steps);\n\n    // transform outputs to numpy\n    array_tf _agCxx = cube_to_array(agCxx);\n    array_tf _agcx = mat_to_array(agcx);\n    array_tf _agCuu =  cube_to_array(agCuu);\n    array_tf _agcu = mat_to_array(agcu);\n    array_tf _agCxu =  cube_to_array(agCxu);\n    array_tf _agc0 = vec_to_array(agc0);\n\n    py::tuple output =  py::make_tuple(_agCxx, _agcx, _agCuu, _agcu, _agCxu, _agc0);\n    return output;\n}\n\npy::tuple forward_pass(array_tf _mu_x0, array_tf _sigma_x0,\n                       array_tf _A, array_tf _B, array_tf _c, array_tf _sigma_dyn,\n                       array_tf _K, array_tf _kff, array_tf _sigma_ctl,\n                       int dm_state, int dm_act, int nb_steps) {\n\n    // inputs\n    vec mu_x0 = array_to_vec(_mu_x0);\n    mat sigma_x0 = array_to_mat(_sigma_x0);\n\n    cube A = array_to_cube(_A);\n    cube B = array_to_cube(_B);\n    mat c = array_to_mat(_c);\n    cube sigma_dyn = array_to_cube(_sigma_dyn);\n\n    cube K = array_to_cube(_K);\n    mat kff = array_to_mat(_kff);\n    cube sigma_ctl = array_to_cube(_sigma_ctl);\n\n    // outputs\n    mat mu_x(dm_state, nb_steps + 1);\n    cube sigma_x(dm_state, dm_state, nb_steps + 1);\n\n    mat mu_u(dm_act, nb_steps);\n    cube sigma_u(dm_act, dm_act, nb_steps);\n\n    mat mu_xu(dm_state + dm_act, nb_steps + 1);\n    cube sigma_xu(dm_state + dm_act, dm_state + dm_act, nb_steps + 1);\n\n    mu_x.col(0) = mu_x0;\n    sigma_x.slice(0) = sigma_x0;\n\n    for (int i = 0; i < nb_steps; i++) {\n\n        // mu_u = K * mu_x + k\n        mu_u.col(i) = K.slice(i) * mu_x.col(i) + kff.col(i);\n\n        // sigma_u = sigma_ctl + K * sigma_x * K_T\n        sigma_u.slice(i) = sigma_ctl.slice(i) + K.slice(i) * sigma_x.slice(i) * K.slice(i).t();\n        sigma_u.slice(i) = 0.5 * (sigma_u.slice(i) + sigma_u.slice(i).t());\n\n        // sigma_xu =   [[sigma_x,      sigma_x * K_T],\n        //               [K*sigma_x,    sigma_u    ]]\n        sigma_xu.slice(i) = join_vert(join_horiz(sigma_x.slice(i), sigma_x.slice(i) * K.slice(i).t()),\n                                        join_horiz(K.slice(i) * sigma_x.slice(i), sigma_u.slice(i)));\n        sigma_xu.slice(i) = 0.5 * (sigma_xu.slice(i) + sigma_xu.slice(i).t());\n\n        // mu_xu =  [[mu_x],\n        //           [mu_u]],\n        mu_xu.col(i) = join_vert(mu_x.col(i), mu_u.col(i));\n\n        // sigma_x_next = sigma_dyn + [A B] * sigma_xu * [A B]^T\n        sigma_x.slice(i+1) = sigma_dyn.slice(i) + join_horiz(A.slice(i), B.slice(i)) * sigma_xu.slice(i) *\n                                                              join_vert(A.slice(i).t(), B.slice(i).t());\n        sigma_x.slice(i+1) = 0.5 * (sigma_x.slice(i+1) + sigma_x.slice(i+1).t());\n\n        // mu_x_next = [A B] * [s a]^T + c\n        mu_x.col(i+1) = join_horiz(A.slice(i), B.slice(i)) * mu_xu.col(i) + c.col(i);\n\n        if(i == nb_steps - 1) {\n            mu_xu.col(i+1) = join_vert(mu_x.col(i+1), zeros<vec>(dm_act));\n            sigma_xu.slice(i+1).submat(0, 0, dm_state - 1, dm_state - 1) = sigma_x.slice(i+1);\n        }\n    }\n\n    // transform outputs to numpy\n    array_tf _mu_x = mat_to_array(mu_x);\n    array_tf _sigma_x = cube_to_array(sigma_x);\n    array_tf _mu_u =  mat_to_array(mu_u);\n    array_tf _sigma_u = cube_to_array(sigma_u);\n    array_tf _mu_xu =  mat_to_array(mu_xu);\n    array_tf _sigma_xu = cube_to_array(sigma_xu);\n\n    py::tuple output =  py::make_tuple(_mu_x, _sigma_x, _mu_u, _sigma_u, _mu_xu, _sigma_xu);\n    return output;\n}\n\n\npy::tuple backward_pass(array_tf _Cxx, array_tf _cx, array_tf _Cuu,\n                        array_tf _cu, array_tf _Cxu, array_tf _c0,\n                        array_tf _A, array_tf _B, array_tf _c, array_tf _sigma_dyn,\n                        array_tf _alpha, int dm_state, int dm_act, int nb_steps) {\n\n    // inputs\n    cube Cxx = array_to_cube(_Cxx);\n    mat cx = array_to_mat(_cx);\n    cube Cuu = array_to_cube(_Cuu);\n    mat cu = array_to_mat(_cu);\n    cube Cxu = array_to_cube(_Cxu);\n    vec c0 = array_to_vec(_c0);\n\n    cube A = array_to_cube(_A);\n    cube B = array_to_cube(_B);\n    mat c = array_to_mat(_c);\n    cube sigma_dyn = array_to_cube(_sigma_dyn);\n\n    vec alpha = array_to_vec(_alpha);\n\n    // outputs\n    cube Q(dm_state + dm_act, dm_state + dm_act, nb_steps);\n    cube Qxx(dm_state, dm_state, nb_steps);\n    cube Qux(dm_act, dm_state, nb_steps);\n    cube Quu(dm_act, dm_act, nb_steps);\n    cube Quu_inv(dm_act, dm_act, nb_steps);\n    mat qx(dm_state, nb_steps);\n    mat qu(dm_act, nb_steps);\n    vec q0(nb_steps);\n\n    cube V(dm_state, dm_state, nb_steps + 1);\n    mat v(dm_state, nb_steps + 1);\n    vec v0(nb_steps + 1);\n\n    cube K(dm_act, dm_state, nb_steps);\n    mat kff(dm_act, nb_steps);\n    cube sigma_ctl(dm_act, dm_act, nb_steps);\n    cube lambda_ctl(dm_act, dm_act, nb_steps);\n\n    int _diverge = 0;\n\n    // last time step\n    V.slice(nb_steps) = Cxx.slice(nb_steps);\n    v.col(nb_steps) = cx.col(nb_steps);\n    v0(nb_steps) = c0(nb_steps);\n\n\tfor(int i = nb_steps - 1; i>= 0; --i)\n\t{\n        Qxx.slice(i) = - (Cxx.slice(i) + A.slice(i).t() * V.slice(i+1) * A.slice(i)) / alpha(i);\n        Quu.slice(i) = - (Cuu.slice(i) + B.slice(i).t() * V.slice(i+1) * B.slice(i)) / alpha(i);\n        Qux.slice(i) = - (Cxu.slice(i) + A.slice(i).t() * V.slice(i+1) * B.slice(i)).t() / alpha(i);\n\n        qu.col(i) = - (cu.col(i) + 2.0 * B.slice(i).t() * V.slice(i+1) * c.col(i) + B.slice(i).t() * v.col(i+1)) / alpha(i);\n        qx.col(i) = - (cx.col(i) + 2.0 * A.slice(i).t() * V.slice(i+1) * c.col(i) + A.slice(i).t() * v.col(i+1)) / alpha(i);\n        q0(i) = - as_scalar(c0(i) + v0(i+1) + c.col(i).t() * V.slice(i+1) * c.col(i)\n                            + trace(V.slice(i+1) * sigma_dyn.slice(i)) + v.col(i+1).t() * c.col(i)) / alpha(i);\n\n        if ((Quu.slice(i)).is_sympd()) {\n            _diverge = i;\n            break;\n        }\n\n        Quu_inv.slice(i) = inv(Quu.slice(i));\n        K.slice(i) = - Quu_inv.slice(i) * Qux.slice(i);\n        kff.col(i) = - 0.5 * Quu_inv.slice(i) * qu.col(i);\n\n        sigma_ctl.slice(i) = - 0.5 * Quu_inv.slice(i);\n        sigma_ctl.slice(i) = 0.5 * (sigma_ctl.slice(i).t() + sigma_ctl.slice(i));\n\n        lambda_ctl.slice(i) = - (Quu.slice(i).t() + Quu.slice(i));\n        lambda_ctl.slice(i) = 0.5 * (lambda_ctl.slice(i).t() + lambda_ctl.slice(i));\n\n        V.slice(i) = - alpha(i) * (Qxx.slice(i) + Qux.slice(i).t() * K.slice(i));\n        V.slice(i) = 0.5 * (V.slice(i) + V.slice(i).t());\n\n        v.col(i) = - alpha(i) * (qx.col(i) + 2. * Qux.slice(i).t() * kff.col(i));\n        v0(i) = - alpha(i) * (as_scalar(0.5 * qu.col(i).t() * kff.col(i)) + q0(i)\n                              + 0.5 * (dm_act * log (2. * datum::pi) - log(det(- 2. * Quu.slice(i)))));\n\t}\n\n    // transform outputs to numpy\n    array_tf _Qxx = cube_to_array(Qxx);\n    array_tf _Qux = cube_to_array(Qux);\n    array_tf _Quu = cube_to_array(Quu);\n\n    array_tf _qx = mat_to_array(qx);\n    array_tf _qu = mat_to_array(qu);\n    array_tf _q0 = mat_to_array(q0);\n\n    array_tf _V = cube_to_array(V);\n    array_tf _v = mat_to_array(v);\n    array_tf _v0 = vec_to_array(v0);\n\n    array_tf _K = cube_to_array(K);\n    array_tf _kff = mat_to_array(kff);\n    array_tf _sigma_ctl = cube_to_array(sigma_ctl);\n\n    py::tuple output =  py::make_tuple(_Qxx, _Qux, _Quu, _qx, _qu, _q0,\n                                        _V, _v, _v0,\n                                        _K, _kff, _sigma_ctl, _diverge);\n\n    return output;\n}\n\n\nPYBIND11_MODULE(core, m)\n{\n    m.def(\"kl_divergence\", &kl_divergence);\n    m.def(\"quad_expectation\", &quad_expectation);\n    m.def(\"augment_cost\", &augment_cost);\n    m.def(\"forward_pass\", &forward_pass);\n    m.def(\"backward_pass\", &backward_pass);\n}\n", "meta": {"hexsha": "7b40dd057ddf497b0635f7937dd0b52be378461f", "size": 13197, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trajopt/gps/src/util.cpp", "max_stars_repo_name": "Oak2d2/trajopt", "max_stars_repo_head_hexsha": "82d69e81571d06d61ff9b472f1e715c48999cd78", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2019-06-17T11:49:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:56.000Z", "max_issues_repo_path": "trajopt/gps/src/util.cpp", "max_issues_repo_name": "Oak2d2/trajopt", "max_issues_repo_head_hexsha": "82d69e81571d06d61ff9b472f1e715c48999cd78", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-10T13:40:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-06T09:22:47.000Z", "max_forks_repo_path": "trajopt/gps/src/util.cpp", "max_forks_repo_name": "Oak2d2/trajopt", "max_forks_repo_head_hexsha": "82d69e81571d06d61ff9b472f1e715c48999cd78", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-07-05T11:29:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T12:56:56.000Z", "avg_line_length": 34.2779220779, "max_line_length": 124, "alphanum_fraction": 0.5866484807, "num_tokens": 4220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4321459554008441}}
{"text": "/*\n! Program for 2D explicit finite element analysis of incompressible Navier-Stokes\n!\n!\n! Author: Dr. Chennakesava Kadapa\n! Date  : 17-May-2018\n! Place : Swansea, UK\n!\n!\n*/\n\n\n#include \"headersBasic.h\"\n#include \"headersEigen.h\"\n#include \"elementutilitiescfd.h\"\n#include \"SolutionData.h\"\n#include \"BernsteinElem2DINSTria6Node.h\"\n#include \"BernsteinElem2DINSQuad9Node.h\"\n#include <Eigen/SuperLUSupport>\n\n\nusing namespace std;\n\n\n\nint main(int argc, char* argv[])\n{\n    double tstart, tend;\n\n    int ndim=2, ndof=2, npElem=6;\n    double fact, xNode[50], yNode[50];\n\n    vector<vector<int> > ElemDofArray;\n\n    int  nElem, nNode, nDBC, nFBC;\n    int  ee, ii, jj, kk, ind, count, row, col;\n    int  n1, n2, n3, n4, n5, n6, nsize;\n    int  nn, dof;\n    int  rr, cc;\n\n\n    string  infileNodes, infileElems, infileDBCs, infileOutput;\n    string  infileFBCs, charTemp, outFileName;\n\n    //Set file names\n    //The file names are specified as inputs from the command line\n    if(argc == 0)\n    {\n        cerr << \" Error in input data \" << endl;\n        cerr <<  \"Number of input files is not sufficient \" << endl;\n        cerr <<  \"You must enter names of THREE files\" << endl;\n        cerr <<  \"a.) Node file, b.) Element file, and c.) Dirichlet BC file\" << endl;\n        cerr << \"Aborting...\" << endl;\n    }\n    else\n    {\n       infileNodes = argv[1];\n       infileElems = argv[2];\n       infileDBCs  = argv[3];\n\n       //if(argc == 5)\n         //infileFBCs  = argv[3];\n\n       if(argc == 5)\n         infileOutput = argv[4];\n    }\n\n\n    // Read nodal data files\n    /////////////////////////////////////\n\n    std::ifstream  infile_nodes(infileNodes);\n    std::ifstream  infile_elems(infileElems);\n    std::ifstream  infile_DBCs(infileDBCs);\n    std::ifstream  infile_FBCs(infileFBCs);\n\n    if(infile_nodes.fail())\n    {\n       cout << \" Could not open the input nodes file \" << endl;\n       exit(1);\n    }\n\n    double  val[50];\n    int  val2[50];\n\n    std::string line;\n\n    // read nodal coordinates\n    ////////////////////////////////////////////\n\n    cout << \" reading nodes \" << endl;\n\n    nNode = 0;\n    while (std::getline(infile_nodes, line))\n      ++nNode;\n\n    vector<vector<double> >  node_coords(nNode, vector<double>(3));\n\n    infile_nodes.clear();\n    infile_nodes.seekg(0, infile_nodes.beg);\n\n      ii=0;\n      while(infile_nodes >> val[0] >> val[1] >> val[2] )\n      {\n        //printf(\"%12.6f \\t %12.6f \\t %12.6f \\n\", val[0], val[1], val[2]);\n\n        node_coords[ii][0] = val[1];\n        node_coords[ii][1] = val[2];\n        node_coords[ii][2] = 0.0;\n\n        ii++;\n      }\n\n\n    // read elements\n    ////////////////////////////////////////////\n    cout << \" reading elements \" << endl;\n\n    if(infile_elems.fail())\n    {\n       cout << \" Could not open the input elements file \" << endl;\n       exit(1);\n    }\n\n\n    nElem = 0;\n    while (std::getline(infile_elems, line))\n      ++nElem;\n\n    cout << \" nElem   \" << nElem << endl;\n\n    infile_elems.clear();\n    infile_elems.seekg(0, infile_elems.beg);\n\n    vector<vector<int> >  elemNodeConn(nElem, vector<int>(npElem));\n\n    ee=0;\n    if(npElem == 6)\n    {\n      while(infile_elems >> val2[0] >> val2[1] >> val2[2] >> val2[3] >> val2[4] >> val2[5] >> val2[6] >> val2[7] >> val2[8] >> val2[9] )\n      {\n        //printf(\"%6d \\t %6d \\t %6d \\t %6d \\n\", val2[4], val2[5], val2[6], val2[7]);\n\n        for(ii=0; ii<npElem; ii++)\n          elemNodeConn[ee][ii] = val2[4+ii]-1;\n\n        ee++;\n      }\n    }\n    else if(npElem == 9)\n    {\n      while(infile_elems >> val2[0] >> val2[1] >> val2[2] >> val2[3] >> val2[4] >> val2[5] >> val2[6] >> val2[7] >> val2[8] >> val2[9] >> val2[10] >> val2[11] >> val2[12] )\n      {\n        //printf(\"%6d \\t %6d \\t %6d \\t %6d \\n\", val2[4], val2[5], val2[6], val2[7]);\n\n        for(ii=0; ii<npElem; ii++)\n          elemNodeConn[ee][ii] = val2[4+ii]-1;\n\n        ee++;\n      }\n    }\n    else\n    {\n      cerr << \" Invalid npElem \" << npElem << endl;\n      exit(-1);\n    }\n    //\n    // Read Dirichlet BC data\n    //\n    ////////////////////////////////////////////\n    cout << \" reading DBCs \" << endl;\n\n    if(infile_DBCs.fail())\n    {\n       cout << \" Could not open the input elements file \" << endl;\n       exit(1);\n    }\n\n    vector<vector<double> >  DirichletBCs;\n    vector<double>  vecDblTemp(3);\n\n    nDBC = 0;\n    while(infile_DBCs >> val[0] >> val[1] >> val[2] )\n    {\n      vecDblTemp[0] = val[0]-1;\n      vecDblTemp[1] = val[1]-1;\n      vecDblTemp[2] = val[2];\n\n      //if( val[1] <= ndof )\n      //{\n        DirichletBCs.push_back(vecDblTemp);\n        nDBC++;\n      //}\n    }\n\n    cout << \" nDBC  = \" << '\\t' << nDBC << endl;\n\n    infile_nodes.close();\n    infile_elems.close();\n    infile_DBCs.close();\n\n    //\n    // Read Output data\n    //\n    ////////////////////////////////////////////\n\n    vector<int>  OutputData;\n\n    if( !infileOutput.empty() )\n    {\n      std::ifstream  infile_output(infileOutput);\n\n      cout << \" reading output data \" << endl;\n\n      if(infile_output.fail())\n      {\n        cout << \" Could not open the input elements file \" << endl;\n        exit(1);\n      }\n\n      ii = 0;\n      while (std::getline(infile_output, line))\n        ++ii;\n\n      infile_output.clear();\n      infile_output.seekg(0, infile_output.beg);\n\n      OutputData.resize(ii);\n\n      ee=0;\n      while(infile_output >> val[0] )\n      {\n        OutputData[ee] = val[0]-1;\n        ee++;\n      }\n\n      infile_output.close();\n    }\n\n    cout << \" Input files have been read successfully \\n\\n \" << endl;\n\n\n      vector<vector<int> >  midNodeData;\n\n      midNodeData.resize(nNode);\n\n      for(ii=0; ii<nNode; ii++)\n      {\n        midNodeData[ii].resize(3);\n\n        midNodeData[ii][0] = 0;  midNodeData[ii][1] = 0;  midNodeData[ii][2] = 0;\n      }\n\n    int nNode_Pres=0;\n    vector<int>  pressure_nodes;\n    if(npElem == 6)\n    {\n      for(ee=0; ee<nElem; ee++)\n      {\n        ii = elemNodeConn[ee][3];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][0];\n        midNodeData[ii][2] = elemNodeConn[ee][1];\n\n        ii = elemNodeConn[ee][4];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][1];\n        midNodeData[ii][2] = elemNodeConn[ee][2];\n\n        ii = elemNodeConn[ee][5];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][2];\n        midNodeData[ii][2] = elemNodeConn[ee][0];\n\n        pressure_nodes.push_back(elemNodeConn[ee][0]);\n        pressure_nodes.push_back(elemNodeConn[ee][1]);\n        pressure_nodes.push_back(elemNodeConn[ee][2]);\n      }\n    }\n    else if(npElem == 9)\n    {\n      for(ee=0; ee<nElem; ee++)\n      {\n        ii = elemNodeConn[ee][4];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][0];\n        midNodeData[ii][2] = elemNodeConn[ee][1];\n\n        ii = elemNodeConn[ee][5];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][1];\n        midNodeData[ii][2] = elemNodeConn[ee][2];\n\n        ii = elemNodeConn[ee][6];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][2];\n        midNodeData[ii][2] = elemNodeConn[ee][3];\n\n        ii = elemNodeConn[ee][7];\n        midNodeData[ii][0] = 1;\n        midNodeData[ii][1] = elemNodeConn[ee][3];\n        midNodeData[ii][2] = elemNodeConn[ee][0];\n\n        pressure_nodes.push_back(elemNodeConn[ee][0]);\n        pressure_nodes.push_back(elemNodeConn[ee][1]);\n        pressure_nodes.push_back(elemNodeConn[ee][2]);\n        pressure_nodes.push_back(elemNodeConn[ee][3]);\n      }\n    }\n\n    findUnique(pressure_nodes);\n    nNode_Pres = pressure_nodes.size();\n\n    vector<int>  pressure_nodes_map(nNode,-1);\n\n    for(ii=0; ii<nNode_Pres; ii++)\n    {\n      pressure_nodes_map[pressure_nodes[ii]] = ii;\n    }\n\n\n    vector<vector<int> >  ID;\n    vector<vector<bool> >  NodeType;\n    vector<int>  assyForSoln;\n\n    NodeType.resize(nNode);\n\n    ID.resize(nNode);\n\n    for(ii=0;ii<nNode;ii++)\n    {\n      NodeType[ii].resize(ndof);\n      ID[ii].resize(ndof);\n\n      for(jj=0;jj<ndof;jj++)\n      {\n        NodeType[ii][jj] = false;\n        ID[ii][jj] = -1;\n      }\n    }\n\n    // fix the pressure at all the mid nodes\n    for(ii=0; ii<nNode; ii++)\n    {\n      if(midNodeData[ii][0])\n        NodeType[ii][2] = true;\n    }\n\n    if(npElem == 9)\n    {\n      for(ee=0; ee<nElem; ee++)\n      {\n        NodeType[elemNodeConn[ee][8]][2] = true;\n      }\n    }\n\n    // fix the specified Dirichlet BCs\n    for(ii=0; ii<nDBC; ii++)\n    {\n      //cout << ii << '\\t' << DirichletBCs[ii][0] << '\\t' << DirichletBCs[ii][1] << endl;\n      NodeType[DirichletBCs[ii][0]][DirichletBCs[ii][1]] = true;\n    }\n\n    //for(ii=0; ii<totalDOF; ii++)\n      //cout << ii << '\\t' << assyForSoln[ii] << endl;\n\n    int totalDOF = 0;\n    for(ii=0;ii<nNode;ii++)\n    {\n      for(jj=0;jj<ndof;jj++)\n      {\n        //cout << ii << '\\t' << jj << '\\t' << NodeType[ii][jj] << endl;\n        if(!NodeType[ii][jj])\n        {\n          ID[ii][jj] = totalDOF++;\n          assyForSoln.push_back(ii*ndof+jj);\n        }\n      }\n    }\n\n      cout << \" Mesh statistics .....\\n\" << endl;\n      cout << \" nElem          = \" << '\\t' << nElem << endl;\n      cout << \" nNode          = \" << '\\t' << nNode  << endl;\n      cout << \" npElem         = \" << '\\t' << npElem << endl;\n      cout << \" ndof           = \" << '\\t' << ndof << endl;\n      cout << \" Total DOF      = \" << '\\t' << totalDOF << endl;\n\n\n      vector<vector<int> >  LM;\n\n      LM.resize(nElem);\n\n      for(ee=0;ee<nElem;ee++)\n      {\n        npElem = elemNodeConn[ee].size();\n\n        //printVector(IEN[ee]);\n\n        ind = ndof*npElem;\n        LM[ee].resize(ind);\n\n        for(ii=0;ii<npElem;ii++)\n        {\n          ind = ndof*ii;\n\n          kk = elemNodeConn[ee][ii];\n\n          for(jj=0;jj<ndof;jj++)\n          {\n            LM[ee][ind+jj] = ID[kk][jj];\n          }\n        }\n      }\n\n      printf(\"\\n element DOF values initialised \\n\\n\");\n\n      /////////////////////////////////////////\n      //\n      // Eigen based solver\n      //\n      /////////////////////////////////////////\n\n      cout << \" Eigen based solver \" << totalDOF << endl;\n\n////////////////////////////////////////////\n////////////////////////////////////////////\n////////////////////////////////////////////\n\n\n      double  xx, yy;\n\n      // loop over the nodes and adjust nodal coordinates\n      for(nn=0; nn<nNode; nn++)\n      {\n        if( midNodeData[nn][0] )\n        {\n          n1 = midNodeData[nn][1];\n          n2 = midNodeData[nn][2];\n\n          xx = 0.25*node_coords[n1][0] + 0.25*node_coords[n2][0];\n          yy = 0.25*node_coords[n1][1] + 0.25*node_coords[n2][1];\n\n          node_coords[nn][0] = 2.0*(node_coords[nn][0] - xx);\n          node_coords[nn][1] = 2.0*(node_coords[nn][1] - yy);\n        }\n      }\n\n\n      double  elemData[50];\n\n      //density\n      elemData[0] = 1.0;\n      //viscosity\n      //elemData[1] = 1.0;\n      elemData[1] = 0.025;\n      //Body force in X-, Y- and Z- direction\n      elemData[2] = 0.0;   elemData[3] = 0.0; elemData[4] = 0.0;\n      //beta\n      elemData[5] = 2.0;\n\n      double  fact1, fact2;\n\n      // create elements and prepare element data\n      BernsteinElem2DINSTria6Node   **elems;\n      //BernsteinElem2DINSQuad9Node   **elems;\n\n      elems = new BernsteinElem2DINSTria6Node* [nElem];\n      //elems = new BernsteinElem2DINSQuad9Node* [nElem];\n\n      for(ee=0;ee<nElem;ee++)\n      {\n        elems[ee] = new BernsteinElem2DINSTria6Node;\n        //elems[ee] = new BernsteinElem2DINSQuad9Node;\n\n        elems[ee]->nodeNums = elemNodeConn[ee];\n\n        //elems[ee]->SolnData = &(SolnData);\n\n        elems[ee]->prepareElemData(node_coords);\n\n        elems[ee]->forAssyVec = LM[ee];\n      }\n\n      cout << \" elements are created and prepated \" << endl;\n      cout << \" Computing the solution \\n\" << endl;\n\n      ///////////////////////////////////////////////////////////////\n      ///////////////////////////////////////////////////////////////\n      ///////////////////////////////////////////////////////////////\n\n     cout << \" nNode_Pres = \" << nNode_Pres << endl;\n\n      vector<int>  vecTempInt1, vecTempInt2;\n\n    // to compute inf-sup number\n\n    //nNode_Pres = nNode;\n\n    ind = npElem*ndim;\n    MatrixXd  Kuu(ind,ind), Kup(ind,9), Kpp(9,9);\n\n    MatrixXd  Kglobal, Mglobal, eigen_vectors;\n    VectorXd  eigen_values, eigvec, Flocal, vecTemp;\n    MatrixXd  Vmat, Qmat, Bmat;\n\n    Vmat.resize(totalDOF, totalDOF);\n    Bmat.resize(totalDOF, nNode_Pres);\n    Qmat.resize(totalDOF, totalDOF);\n\n    Kglobal.resize(totalDOF, totalDOF);\n    Mglobal.resize(nNode_Pres, nNode_Pres);\n\n    Kglobal.setZero();\n    Mglobal.setZero();\n    Vmat.setZero();\n    Bmat.setZero();\n    Qmat.setZero();\n\n    /////////////////////////////////////////\n    // compute and assemble matrices\n    /////////////////////////////////////////\n\n    for(ee=0; ee<nElem; ee++)  // loop over all the elements\n    {\n        //cout << \"       elem... : \" << (ee+1) << endl;\n\n        elems[ee]->toComputeInfSupCondition(node_coords, elemData, Kuu, Kup, Kpp);\n\n        vecTempInt1=elems[ee]->forAssyVec;\n        vecTempInt2=elems[ee]->nodeNums;\n\n        n1=vecTempInt1.size();\n        n2=3;\n\n        //printVector(vecTempInt1);\n        //printVector(vecTempInt2);\n\n        // Kuu\n        for(ii=0; ii<n1; ii++)\n        {\n          rr = vecTempInt1[ii];\n          if( rr != -1 )\n          {\n            for(jj=0; jj<n1; jj++)\n            {\n              cc = vecTempInt1[jj];\n              if( cc != -1 )\n              {\n                 Kglobal(rr, cc) += Kuu(ii,jj);\n              }\n            }\n          }\n        }\n\n        //cout << \" aaaaaaaaaaa \" << endl;\n\n        // Kup\n        for(ii=0; ii<n1; ii++)\n        {\n          rr = vecTempInt1[ii];\n          if( rr != -1 )\n          {\n            for(jj=0; jj<n2; jj++)\n            {\n              cc = pressure_nodes_map[vecTempInt2[jj]];\n              //cc = vecTempInt2[jj];\n\n              Bmat(rr,cc) += Kup(ii,jj);\n            }\n          }\n        }\n\n        //cout << \" aaaaaaaaaaa \" << endl;\n\n        // Kpp\n        for(ii=0; ii<n2; ii++)\n        {\n          rr = pressure_nodes_map[vecTempInt2[ii]];\n          //rr = vecTempInt2[ii];\n\n          for(jj=0; jj<n2; jj++)\n          {\n            cc = pressure_nodes_map[vecTempInt2[jj]];\n            //cc = vecTempInt2[jj];\n\n            Mglobal(rr, cc) += Kpp(ii,jj);\n          }\n        }\n    }\n\n    cout << \"  Solving eigenvalue problem ... \" << endl;\n\n    Kglobal = Kglobal.inverse();\n    //printMatrix(Vmat);\n    //printf(\"\\n\\n\");\n    //printMatrix(globalK);\n    //printf(\"\\n\\n\");\n    //printMatrix(globalM);\n    //printf(\"\\n\\n\");\n    Kglobal = (Bmat.transpose()*Kglobal)*Bmat;\n\n    GeneralizedSelfAdjointEigenSolver<MatrixXd> es(Kglobal, Mglobal, EigenvaluesOnly);\n    eigen_values = es.eigenvalues();\n    //eigen_vectors = es.eigenvectors();\n\n    //EigenSolver<MatrixXd>  es(Kglobal, EigenvaluesOnly);\n    //cout << \"The eigenvalues of A are:\" << endl << es.eigenvalues() << endl;\n    //eigen_values = es.eigenvalues().col(0);\n\n    cout << \"  Eigen analysis successfully completed ... \" << endl;\n\n    cout << \" The first \" << min(20, (int) eigen_values.rows()) << \" eigenvalues are ... \" << endl;\n\n    for(int ii=0;ii<min(20, (int) eigen_values.rows());ii++)\n      printf(\"\\t %5d \\t %12.10f \\t %12.10f \\n\", (ii+1), eigen_values(ii), sqrt(abs(eigen_values(ii))));\n\n\n\n    if(elems != NULL)\n    {\n      for(ii=0;ii<nElem;ii++)\n        delete elems[ii];\n\n      delete [] elems;\n      elems = NULL;\n    }\n\n    cout << \" Program is successful \\n \" << endl;\n\n    return 1;\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "9b7db23a7640141f0d8a3e6b749987373fd2e9a2", "size": 15525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/infsup.cpp", "max_stars_repo_name": "M4rkD/XCFD", "max_stars_repo_head_hexsha": "e4b6156a8823cbe0771c44df16539e7491e9fe11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-28T18:06:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-28T18:06:34.000Z", "max_issues_repo_path": "src/infsup.cpp", "max_issues_repo_name": "M4rkD/XCFD", "max_issues_repo_head_hexsha": "e4b6156a8823cbe0771c44df16539e7491e9fe11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-08-09T13:01:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-09T14:57:53.000Z", "max_forks_repo_path": "src/infsup.cpp", "max_forks_repo_name": "M4rkD/XCFD", "max_forks_repo_head_hexsha": "e4b6156a8823cbe0771c44df16539e7491e9fe11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-07-29T14:01:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-18T17:10:03.000Z", "avg_line_length": 24.2957746479, "max_line_length": 172, "alphanum_fraction": 0.4942995169, "num_tokens": 4647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4321177141004978}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_DETAIL_CONSTANT_PIO_2LO_HPP_INCLUDED\n#define BOOST_SIMD_DETAIL_CONSTANT_PIO_2LO_HPP_INCLUDED\n\n#include <boost/simd/config.hpp>\n#include <boost/simd/detail/brigand.hpp>\n#include <boost/simd/detail/dispatch.hpp>\n#include <boost/simd/detail/constant_traits.hpp>\n#include <boost/simd/detail/dispatch/function/make_callable.hpp>\n#include <boost/simd/detail/dispatch/hierarchy/functions.hpp>\n#include <boost/simd/detail/dispatch/as.hpp>\n\n/*\n\n\n    @ingroup group-constant\n\n    This constant is such that, for pairs of types (T, Tup)\n    (namely (float,  double) and (double, long double)) the sum:\n\n    abs(Tup(Pio_2lo<T>())+Tup(Pio_2<T>())-Pio_2\\< Tup \\>()) is  less than\n    a few Eps<Tup>().\n\n\n    This is used to improve accurracy when computing sums of the kind\n    \\f$\\pi/2 + x\\f$ with x small,  by replacing them by\n    Pio_2 + (Pio_2lo + x)\n\n    @par Semantic:\n\n    For type T:\n\n    @code\n    T r = Pio_2lo<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    if T is double\n      r = 6.123233995736766e-17\n    else if T is float\n      r = -4.3711388e-08\n    @endcode\n\n    @return a value of type T\n\n*/\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n    struct pio_2lo_ : boost::dispatch::constant_value_<pio_2lo_>\n    {\n      BOOST_DISPATCH_MAKE_CALLABLE(ext,pio_2lo_,boost::dispatch::constant_value_<pio_2lo_>);\n      BOOST_SIMD_REGISTER_CONSTANT(0, 0XB33BBD2EUL, 0X3C91A62633145C07ULL);\n    };\n  }\n\n  namespace ext\n  {\n    BOOST_DISPATCH_FUNCTION_DECLARATION(tag, pio_2lo_)\n  }\n\n  namespace detail\n  {\n    BOOST_DISPATCH_CALLABLE_DEFINITION(tag::pio_2lo_,pio_2lo);\n  }\n\n  template<typename T> BOOST_FORCEINLINE auto Pio_2lo()\n  BOOST_NOEXCEPT_DECLTYPE(detail::pio_2lo( boost::dispatch::as_<T>{}))\n  {\n    return detail::pio_2lo( boost::dispatch::as_<T>{} );\n  }\n} }\n\n#include <boost/simd/arch/common/scalar/constant/constant_value.hpp>\n#include <boost/simd/arch/common/simd/constant/constant_value.hpp>\n\n#endif\n", "meta": {"hexsha": "ed487ea794086bc000da9d28c0147f6a3bb5b51f", "size": 2336, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/detail/constant/pio_2lo.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "include/boost/simd/detail/constant/pio_2lo.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/detail/constant/pio_2lo.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 25.6703296703, "max_line_length": 100, "alphanum_fraction": 0.6455479452, "num_tokens": 642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.432117706438796}}
{"text": "\n#include <NTL/lzz_pX.h>\n\n\nNTL_START_IMPL\n\n\n// NOTE: these are declared extern in lzz_pX.h\n\nconst long zz_pX_mod_crossover[5] = {45, 45, 90, 180, 180};\nconst long zz_pX_mul_crossover[5] = {150, 150, 300, 500, 500};\nconst long zz_pX_newton_crossover[5] = {150, 150, 300, 700, 700};\nconst long zz_pX_div_crossover[5] = {180, 180, 350, 750, 750};\nconst long zz_pX_halfgcd_crossover[5] = {90, 90, 180, 350, 350};\nconst long zz_pX_gcd_crossover[5] = {400, 400, 800, 1400, 1400};\nconst long zz_pX_bermass_crossover[5] = {400, 480, 900, 1600, 1600};\nconst long zz_pX_trace_crossover[5] = {200, 350, 450, 800, 800};\n\n\n\n\nconst zz_pX& zz_pX::zero()\n{\n   static const zz_pX z; // GLOBAL (assumes C++11 thread-safe init)\n   return z;\n}\n\n\n\nistream& operator>>(istream& s, zz_pX& x)\n{\n   NTL_INPUT_CHECK_RET(s, s >> x.rep);\n   x.normalize();\n   return s;\n}\n\nostream& operator<<(ostream& s, const zz_pX& a)\n{\n   return s << a.rep;\n}\n\n\nvoid zz_pX::normalize()\n{\n   long n;\n   const zz_p* p;\n\n   n = rep.length();\n   if (n == 0) return;\n   p = rep.elts() + n;\n   while (n > 0 && IsZero(*--p)) {\n      n--;\n   }\n   rep.SetLength(n);\n}\n\n\nlong IsZero(const zz_pX& a)\n{\n   return a.rep.length() == 0;\n}\n\n\nlong IsOne(const zz_pX& a)\n{\n    return a.rep.length() == 1 && IsOne(a.rep[0]);\n}\n\nvoid GetCoeff(zz_p& x, const zz_pX& a, long i)\n{\n   if (i < 0 || i > deg(a))\n      clear(x);\n   else\n      x = a.rep[i];\n}\n\nvoid SetCoeff(zz_pX& x, long i, zz_p a)\n{\n   long j, m;\n\n   if (i < 0) \n      LogicError(\"SetCoeff: negative index\");\n\n   if (NTL_OVERFLOW(i, 1, 0))\n      ResourceError(\"overflow in SetCoeff\");\n\n   m = deg(x);\n\n   if (i > m && IsZero(a)) return; \n\n   if (i > m) {\n      x.rep.SetLength(i+1);\n      for (j = m+1; j < i; j++)\n         clear(x.rep[j]);\n   }\n   x.rep[i] = a;\n   x.normalize();\n}\n\nvoid SetCoeff(zz_pX& x, long i, long a)\n{\n   if (a == 1)\n      SetCoeff(x, i);\n   else\n      SetCoeff(x, i, to_zz_p(a));\n}\n\nvoid SetCoeff(zz_pX& x, long i)\n{\n   long j, m;\n\n   if (i < 0) \n      LogicError(\"coefficient index out of range\");\n\n   if (NTL_OVERFLOW(i, 1, 0))\n      ResourceError(\"overflow in SetCoeff\");\n\n   m = deg(x);\n\n   if (i > m) {\n      x.rep.SetLength(i+1);\n      for (j = m+1; j < i; j++)\n         clear(x.rep[j]);\n   }\n   set(x.rep[i]);\n   x.normalize();\n}\n\n\nvoid SetX(zz_pX& x)\n{\n   clear(x);\n   SetCoeff(x, 1);\n}\n\n\nlong IsX(const zz_pX& a)\n{\n   return deg(a) == 1 && IsOne(LeadCoeff(a)) && IsZero(ConstTerm(a));\n}\n      \n      \n\nconst zz_p coeff(const zz_pX& a, long i)\n{\n   if (i < 0 || i > deg(a))\n      return zz_p::zero();\n   else\n      return a.rep[i];\n}\n\n\nconst zz_p LeadCoeff(const zz_pX& a)\n{\n   if (IsZero(a))\n      return zz_p::zero();\n   else\n      return a.rep[deg(a)];\n}\n\nconst zz_p ConstTerm(const zz_pX& a)\n{\n   if (IsZero(a))\n      return zz_p::zero();\n   else\n      return a.rep[0];\n}\n\n\n\nvoid conv(zz_pX& x, zz_p a)\n{\n   if (IsZero(a))\n      x.rep.SetLength(0);\n   else {\n      x.rep.SetLength(1);\n      x.rep[0] = a;\n   }\n}\n\nvoid conv(zz_pX& x, long a)\n{\n   if (a == 0) {\n      x.rep.SetLength(0);\n      return;\n   }\n   \n   zz_p t;\n\n   conv(t, a);\n   conv(x, t);\n}\n\nvoid conv(zz_pX& x, const ZZ& a)\n{\n   if (a == 0) {\n      x.rep.SetLength(0);\n      return;\n   }\n   \n   zz_p t;\n\n   conv(t, a);\n   conv(x, t);\n}\n\n\nvoid conv(zz_pX& x, const vec_zz_p& a)\n{\n   x.rep = a;\n   x.normalize();\n}\n\n\nvoid add(zz_pX& x, const zz_pX& a, const zz_pX& b)\n{\n   long da = deg(a);\n   long db = deg(b);\n   long minab = min(da, db);\n   long maxab = max(da, db);\n   x.rep.SetLength(maxab+1);\n\n   long i;\n   const zz_p *ap, *bp; \n   zz_p* xp;\n   long p = zz_p::modulus();\n\n   for (i = minab+1, ap = a.rep.elts(), bp = b.rep.elts(), xp = x.rep.elts();\n        i; i--, ap++, bp++, xp++)\n      xp->LoopHole() = AddMod(rep(*ap), rep(*bp), p);\n\n   if (da > minab && &x != &a)\n      for (i = da-minab; i; i--, xp++, ap++)\n         *xp = *ap;\n   else if (db > minab && &x != &b)\n      for (i = db-minab; i; i--, xp++, bp++)\n         *xp = *bp;\n   else\n      x.normalize();\n}\n\nvoid add(zz_pX& x, const zz_pX& a, zz_p b)\n{\n   if (a.rep.length() == 0) {\n      conv(x, b);\n   }\n   else {\n      if (&x != &a) x = a;\n      add(x.rep[0], x.rep[0], b);\n      x.normalize();\n   }\n}\n\n\nvoid sub(zz_pX& x, const zz_pX& a, const zz_pX& b)\n{\n   long da = deg(a);\n   long db = deg(b);\n   long minab = min(da, db);\n   long maxab = max(da, db);\n   x.rep.SetLength(maxab+1);\n\n   long i;\n   const zz_p *ap, *bp; \n   zz_p* xp;\n   long p = zz_p::modulus();\n\n   for (i = minab+1, ap = a.rep.elts(), bp = b.rep.elts(), xp = x.rep.elts();\n        i; i--, ap++, bp++, xp++)\n      xp->LoopHole() = SubMod(rep(*ap), rep(*bp), p);\n\n   if (da > minab && &x != &a)\n      for (i = da-minab; i; i--, xp++, ap++)\n         *xp = *ap;\n   else if (db > minab)\n      for (i = db-minab; i; i--, xp++, bp++)\n         xp->LoopHole() = NegateMod(rep(*bp), p);\n   else\n      x.normalize();\n\n}\n\nvoid sub(zz_pX& x, const zz_pX& a, zz_p b)\n{\n   if (a.rep.length() == 0) {\n      x.rep.SetLength(1);\n      negate(x.rep[0], b);\n   }\n   else {\n      if (&x != &a) x = a;\n      sub(x.rep[0], x.rep[0], b);\n   }\n   x.normalize();\n}\n\nvoid sub(zz_pX& x, zz_p a, const zz_pX& b)\n{\n   negate(x, b);\n   add(x, x, a);\n}\n\nvoid negate(zz_pX& x, const zz_pX& a)\n{\n   long n = a.rep.length();\n   x.rep.SetLength(n);\n\n   const zz_p* ap = a.rep.elts();\n   zz_p* xp = x.rep.elts();\n   long i;\n   long p = zz_p::modulus();\n\n   for (i = n; i; i--, ap++, xp++)\n      xp->LoopHole() = NegateMod(rep(*ap), p);\n}\n\nvoid mul(zz_pX& x, const zz_pX& a, const zz_pX& b)\n{\n   if (&a == &b) {\n      sqr(x, a);\n      return;\n   }\n\n   if (deg(a) > NTL_zz_pX_MUL_CROSSOVER && deg(b) > NTL_zz_pX_MUL_CROSSOVER)\n      FFTMul(x, a, b);\n   else\n      PlainMul(x, a, b);\n}\n\nvoid sqr(zz_pX& x, const zz_pX& a)\n{\n   if (deg(a) > NTL_zz_pX_MUL_CROSSOVER)\n      FFTSqr(x, a);\n   else\n      PlainSqr(x, a);\n}\n\n/* \"plain\" multiplication and squaring actually incorporates Karatsuba */\n\nvoid PlainMul(zz_p *xp, const zz_p *ap, long sa, const zz_p *bp, long sb)\n{\n   if (sa == 0 || sb == 0) return;\n\n   long sx = sa+sb-1;\n\n\n   if (sa < sb) {\n      { long t = sa; sa = sb; sb = t; }\n      { const zz_p *t = ap; ap = bp; bp = t; }\n   }\n\n   long i, j;\n\n   for (i = 0; i < sx; i++)\n      clear(xp[i]);\n\n   long p = zz_p::modulus();\n   mulmod_t pinv = zz_p::ModulusInverse();\n\n   for (i = 0; i < sb; i++) {\n      long t1 = rep(bp[i]);\n      mulmod_precon_t bpinv = PrepMulModPrecon(t1, p, pinv); \n      zz_p *xp1 = xp+i;\n      for (j = 0; j < sa; j++) {\n         long t2;\n         t2 = MulModPrecon(rep(ap[j]), t1, p, bpinv);\n         xp1[j].LoopHole() = AddMod(t2, rep(xp1[j]), p);\n      }\n   }\n}\n\nstatic inline \nvoid reduce(zz_p& r, long a, long p, mulmod_t pinv)\n{\n   // DIRT: uses undocumented MulMod feature (see sp_arith.h)\n   r.LoopHole() = MulMod(a, 1L, p, pinv);\n}\n\nvoid PlainMul_long(zz_p *xp, const zz_p *ap, long sa, const zz_p *bp, long sb)\n{\n   if (sa == 0 || sb == 0) return;\n\n   long d = sa+sb-2;\n\n   long i, j, jmin, jmax;\n\n   long accum;\n\n   long p = zz_p::modulus();\n   mulmod_t pinv = zz_p::ModulusInverse();\n\n   for (i = 0; i <= d; i++) {\n      jmin = max(0, i-(sb-1));\n      jmax = min((sa-1), i);\n      accum = 0;\n      for (j = jmin; j <= jmax; j++) {\n         accum += rep(ap[j])*rep(bp[i-j]);\n      }\n      reduce(xp[i], accum, p, pinv);\n   }\n}\n\n#define KARX (16)\n\nvoid KarFold(zz_p *T, const zz_p *b, long sb, long hsa)\n{\n   long m = sb - hsa;\n   long i;\n   long p = zz_p::modulus();\n\n   for (i = 0; i < m; i++)\n      T[i].LoopHole() = AddMod(rep(b[i]), rep(b[hsa+i]), p);\n\n   for (i = m; i < hsa; i++)\n      T[i] = b[i];\n}\n\nvoid KarSub(zz_p *T, const zz_p *b, long sb)\n{\n   long i;\n   long p = zz_p::modulus();\n\n   for (i = 0; i < sb; i++)\n      T[i].LoopHole() = SubMod(rep(T[i]), rep(b[i]), p);\n}\n\nvoid KarAdd(zz_p *T, const zz_p *b, long sb)\n{\n   long i;\n   long p = zz_p::modulus();\n\n   for (i = 0; i < sb; i++)\n      T[i].LoopHole() = AddMod(rep(T[i]), rep(b[i]), p);\n}\n\nvoid KarFix(zz_p *c, const zz_p *b, long sb, long hsa)\n{\n   long i;\n   long p = zz_p::modulus();\n\n   for (i = 0; i < hsa; i++)\n      c[i] = b[i];\n\n   for (i = hsa; i < sb; i++)\n      c[i].LoopHole() = AddMod(rep(c[i]), rep(b[i]), p);\n}\n\n\nvoid KarMul(zz_p *c, const zz_p *a, long sa, const zz_p *b, long sb, zz_p *stk)\n{\n   if (sa < sb) {\n      { long t = sa; sa = sb; sb = t; }\n      { const zz_p *t = a; a = b; b = t; }\n   }\n\n   if (sb < KARX) {\n      PlainMul(c, a, sa, b, sb);\n      return;\n   }\n\n   long hsa = (sa + 1) >> 1;\n\n   if (hsa < sb) {\n      /* normal case */\n\n      long hsa2 = hsa << 1;\n\n      zz_p *T1, *T2, *T3;\n\n      T1 = stk; stk += hsa;\n      T2 = stk; stk += hsa;\n      T3 = stk; stk += hsa2 - 1;\n\n      /* compute T1 = a_lo + a_hi */\n\n      KarFold(T1, a, sa, hsa);\n\n      /* compute T2 = b_lo + b_hi */\n\n      KarFold(T2, b, sb, hsa);\n\n      /* recursively compute T3 = T1 * T2 */\n\n      KarMul(T3, T1, hsa, T2, hsa, stk);\n\n      /* recursively compute a_hi * b_hi into high part of c */\n      /* and subtract from T3 */\n\n      KarMul(c + hsa2, a+hsa, sa-hsa, b+hsa, sb-hsa, stk);\n      KarSub(T3, c + hsa2, sa + sb - hsa2 - 1);\n\n\n      /* recursively compute a_lo*b_lo into low part of c */\n      /* and subtract from T3 */\n\n      KarMul(c, a, hsa, b, hsa, stk);\n      KarSub(T3, c, hsa2 - 1);\n\n      clear(c[hsa2 - 1]);\n\n      /* finally, add T3 * X^{hsa} to c */\n\n      KarAdd(c+hsa, T3, hsa2-1);\n   }\n   else {\n      /* degenerate case */\n\n      zz_p *T;\n\n      T = stk; stk += hsa + sb - 1;\n\n      /* recursively compute b*a_hi into high part of c */\n\n      KarMul(c + hsa, a + hsa, sa - hsa, b, sb, stk);\n\n      /* recursively compute b*a_lo into T */\n\n      KarMul(T, a, hsa, b, sb, stk);\n\n      KarFix(c, T, hsa + sb - 1, hsa);\n   }\n}\n\nvoid KarMul_long(zz_p *c, const zz_p *a, long sa, const zz_p *b, long sb, zz_p *stk)\n{\n   if (sa < sb) {\n      { long t = sa; sa = sb; sb = t; }\n      { const zz_p *t = a; a = b; b = t; }\n   }\n\n   if (sb < KARX) {\n      PlainMul_long(c, a, sa, b, sb);\n      return;\n   }\n\n   long hsa = (sa + 1) >> 1;\n\n   if (hsa < sb) {\n      /* normal case */\n\n      long hsa2 = hsa << 1;\n\n      zz_p *T1, *T2, *T3;\n\n      T1 = stk; stk += hsa;\n      T2 = stk; stk += hsa;\n      T3 = stk; stk += hsa2 - 1;\n\n      /* compute T1 = a_lo + a_hi */\n\n      KarFold(T1, a, sa, hsa);\n\n      /* compute T2 = b_lo + b_hi */\n\n      KarFold(T2, b, sb, hsa);\n\n      /* recursively compute T3 = T1 * T2 */\n\n      KarMul_long(T3, T1, hsa, T2, hsa, stk);\n\n      /* recursively compute a_hi * b_hi into high part of c */\n      /* and subtract from T3 */\n\n      KarMul_long(c + hsa2, a+hsa, sa-hsa, b+hsa, sb-hsa, stk);\n      KarSub(T3, c + hsa2, sa + sb - hsa2 - 1);\n\n\n      /* recursively compute a_lo*b_lo into low part of c */\n      /* and subtract from T3 */\n\n      KarMul_long(c, a, hsa, b, hsa, stk);\n      KarSub(T3, c, hsa2 - 1);\n\n      clear(c[hsa2 - 1]);\n\n      /* finally, add T3 * X^{hsa} to c */\n\n      KarAdd(c+hsa, T3, hsa2-1);\n   }\n   else {\n      /* degenerate case */\n\n      zz_p *T;\n\n      T = stk; stk += hsa + sb - 1;\n\n      /* recursively compute b*a_hi into high part of c */\n\n      KarMul_long(c + hsa, a + hsa, sa - hsa, b, sb, stk);\n\n      /* recursively compute b*a_lo into T */\n\n      KarMul_long(T, a, hsa, b, sb, stk);\n\n      KarFix(c, T, hsa + sb - 1, hsa);\n   }\n}\n\n\nvoid PlainMul(zz_pX& c, const zz_pX& a, const zz_pX& b)\n{\n   long sa = a.rep.length();\n   long sb = b.rep.length();\n\n   if (sa == 0 || sb == 0) {\n      clear(c);\n      return;\n   }\n\n   if (sa == 1) {\n      mul(c, b, a.rep[0]);\n      return;\n   }\n\n   if (sb == 1) {\n      mul(c, a, b.rep[0]);\n      return;\n   }\n\n   if (&a == &b) {\n      PlainSqr(c, a);\n      return;\n   }\n\n   vec_zz_p mem;\n\n   const zz_p *ap, *bp;\n   zz_p *cp;\n\n   if (&a == &c) {\n      mem = a.rep;\n      ap = mem.elts();\n   }\n   else\n      ap = a.rep.elts();\n\n   if (&b == &c) {\n      mem = b.rep;\n      bp = mem.elts();\n   }\n   else\n      bp = b.rep.elts();\n\n   c.rep.SetLength(sa+sb-1);\n   cp = c.rep.elts();\n\n   long p = zz_p::modulus();\n   long use_long = (p < NTL_SP_BOUND/KARX && p*KARX < NTL_SP_BOUND/p);\n\n   if (sa < KARX || sb < KARX) {\n      if (use_long) \n         PlainMul_long(cp, ap, sa, bp, sb);\n      else\n         PlainMul(cp, ap, sa, bp, sb);\n   }\n   else {\n      /* karatsuba */\n\n      long n, hn, sp;\n\n      n = max(sa, sb);\n      sp = 0;\n      do {\n         hn = (n+1) >> 1;\n         sp += (hn << 2) - 1;\n         n = hn;\n      } while (n >= KARX);\n\n      vec_zz_p stk;\n      stk.SetLength(sp);\n\n      if (use_long) \n         KarMul_long(cp, ap, sa, bp, sb, stk.elts());\n      else\n         KarMul(cp, ap, sa, bp, sb, stk.elts());\n   }\n\n   c.normalize();\n}\n\nvoid PlainSqr_long(zz_p *xp, const zz_p *ap, long sa)\n{\n   if (sa == 0) return;\n\n   long da = sa-1;\n   long d = 2*da;\n\n   long i, j, jmin, jmax, m, m2;\n\n   long accum;\n   long p = zz_p::modulus();\n   mulmod_t pinv = zz_p::ModulusInverse();\n\n   for (i = 0; i <= d; i++) {\n      jmin = max(0, i-da);\n      jmax = min(da, i);\n      m = jmax - jmin + 1;\n      m2 = m >> 1;\n      jmax = jmin + m2 - 1;\n      accum = 0;\n      for (j = jmin; j <= jmax; j++) {\n         accum += rep(ap[j])*rep(ap[i-j]);\n      }\n      accum += accum;\n      if (m & 1) {\n         accum += rep(ap[jmax + 1])*rep(ap[jmax + 1]);\n      }\n\n      reduce(xp[i], accum, p, pinv);\n   }\n}\n\n\nvoid PlainSqr(zz_p *xp, const zz_p *ap, long sa)\n{\n   if (sa == 0) return;\n\n   long i, j, k, cnt;\n\n   cnt = 2*sa-1;\n   for (i = 0; i < cnt; i++)\n      clear(xp[i]);\n\n   long p = zz_p::modulus();\n   mulmod_t pinv = zz_p::ModulusInverse();\n   long t1, t2;\n\n   i = -1;\n   for (j = 0; j <= sa-2; j++) {\n      i += 2;\n\n      t1 = MulMod(rep(ap[j]), rep(ap[j]), p, pinv);\n      t2 = rep(xp[i-1]);\n      t2 = AddMod(t2, t2, p);\n      t2 = AddMod(t2, t1, p);\n      xp[i-1].LoopHole() = t2;\n\n      cnt = sa - 1 - j;\n      const zz_p *ap1 = ap+(j+1);\n      zz_p *xp1 = xp+i;\n      t1 = rep(ap[j]);\n      mulmod_precon_t tpinv = PrepMulModPrecon(t1, p, pinv); \n\n      for (k = 0; k < cnt; k++) {\n         t2 = MulModPrecon(rep(ap1[k]), t1, p, tpinv);\n         t2 = AddMod(t2, rep(xp1[k]), p);\n         xp1[k].LoopHole() = t2;\n      }\n      t2 = rep(*xp1);\n      t2 = AddMod(t2, t2, p);\n      (*xp1).LoopHole() = t2;\n   }\n\n\n   t1 = rep(ap[sa-1]);\n   t1 = MulMod(t1, t1, p, pinv);\n   xp[2*sa-2].LoopHole() = t1;\n}\n\n#define KARSX (30)\n\nvoid KarSqr(zz_p *c, const zz_p *a, long sa, zz_p *stk)\n{\n   if (sa < KARSX) {\n      PlainSqr(c, a, sa);\n      return;\n   }\n\n   long hsa = (sa + 1) >> 1;\n   long hsa2 = hsa << 1;\n\n   zz_p *T1, *T2;\n\n   T1 = stk; stk += hsa;\n   T2 = stk; stk += hsa2-1;\n\n   KarFold(T1, a, sa, hsa);\n   KarSqr(T2, T1, hsa, stk);\n\n\n   KarSqr(c + hsa2, a+hsa, sa-hsa, stk);\n   KarSub(T2, c + hsa2, sa + sa - hsa2 - 1);\n\n\n   KarSqr(c, a, hsa, stk);\n   KarSub(T2, c, hsa2 - 1);\n\n   clear(c[hsa2 - 1]);\n\n   KarAdd(c+hsa, T2, hsa2-1);\n}\n\nvoid KarSqr_long(zz_p *c, const zz_p *a, long sa, zz_p *stk)\n{\n   if (sa < KARSX) {\n      PlainSqr_long(c, a, sa);\n      return;\n   }\n\n   long hsa = (sa + 1) >> 1;\n   long hsa2 = hsa << 1;\n\n   zz_p *T1, *T2;\n\n   T1 = stk; stk += hsa;\n   T2 = stk; stk += hsa2-1;\n\n   KarFold(T1, a, sa, hsa);\n   KarSqr_long(T2, T1, hsa, stk);\n\n\n   KarSqr_long(c + hsa2, a+hsa, sa-hsa, stk);\n   KarSub(T2, c + hsa2, sa + sa - hsa2 - 1);\n\n\n   KarSqr_long(c, a, hsa, stk);\n   KarSub(T2, c, hsa2 - 1);\n\n   clear(c[hsa2 - 1]);\n\n   KarAdd(c+hsa, T2, hsa2-1);\n}\n\nvoid PlainSqr(zz_pX& c, const zz_pX& a)\n{\n   if (IsZero(a)) {\n      clear(c);\n      return;\n   }\n\n   vec_zz_p mem;\n\n   const zz_p *ap;\n   zz_p *cp;\n\n   long sa = a.rep.length();\n\n   if (&a == &c) {\n      mem = a.rep;\n      ap = mem.elts();\n   }\n   else\n      ap = a.rep.elts();\n\n   c.rep.SetLength(2*sa-1);\n   cp = c.rep.elts();\n\n   long p = zz_p::modulus();\n   long use_long = (p < NTL_SP_BOUND/KARSX && p*KARSX < NTL_SP_BOUND/p);\n\n   if (sa < KARSX) {\n      if (use_long) \n         PlainSqr_long(cp, ap, sa);\n      else\n         PlainSqr(cp, ap, sa);\n   }\n   else {\n      /* karatsuba */\n\n      long n, hn, sp;\n\n      n = sa;\n      sp = 0;\n      do {\n         hn = (n+1) >> 1;\n         sp += hn+hn+hn - 1;\n         n = hn;\n      } while (n >= KARSX);\n\n      vec_zz_p stk;\n      stk.SetLength(sp);\n\n      if (use_long) \n         KarSqr_long(cp, ap, sa, stk.elts());\n      else\n         KarSqr(cp, ap, sa, stk.elts());\n   }\n\n   c.normalize();\n}\n\n\nvoid PlainDivRem(zz_pX& q, zz_pX& r, const zz_pX& a, const zz_pX& b)\n{\n   long da, db, dq, i, j, LCIsOne;\n   const zz_p *bp;\n   zz_p *qp;\n   zz_p *xp;\n\n\n   zz_p LCInv, t;\n   zz_p s;\n\n   da = deg(a);\n   db = deg(b);\n\n   if (db < 0) ArithmeticError(\"zz_pX: division by zero\");\n\n   if (da < db) {\n      r = a;\n      clear(q);\n      return;\n   }\n\n   zz_pX lb;\n\n   if (&q == &b) {\n      lb = b;\n      bp = lb.rep.elts();\n   }\n   else\n      bp = b.rep.elts();\n\n   if (IsOne(bp[db]))\n      LCIsOne = 1;\n   else {\n      LCIsOne = 0;\n      inv(LCInv, bp[db]);\n   }\n\n   vec_zz_p x;\n   if (&r == &a)\n      xp = r.rep.elts();\n   else {\n      x = a.rep;\n      xp = x.elts();\n   }\n\n   dq = da - db;\n   q.rep.SetLength(dq+1);\n   qp = q.rep.elts();\n\n   long p = zz_p::modulus();\n   mulmod_t pinv = zz_p::ModulusInverse();\n\n   for (i = dq; i >= 0; i--) {\n      t = xp[i+db];\n      if (!LCIsOne)\n         mul(t, t, LCInv);\n      qp[i] = t;\n      negate(t, t);\n\n      long T = rep(t);\n      mulmod_precon_t Tpinv = PrepMulModPrecon(T, p, pinv); \n\n      for (j = db-1; j >= 0; j--) {\n         long S = MulModPrecon(rep(bp[j]), T, p, Tpinv);\n         S = AddMod(S, rep(xp[i+j]), p);\n         xp[i+j].LoopHole() = S;\n      }\n   }\n\n   r.rep.SetLength(db);\n   if (&r != &a) {\n      for (i = 0; i < db; i++)\n         r.rep[i] = xp[i];\n   }\n   r.normalize();\n}\n\nvoid PlainDiv(zz_pX& q, const zz_pX& a, const zz_pX& b)\n{\n   long da, db, dq, i, j, LCIsOne;\n   const zz_p *bp;\n   zz_p *qp;\n   zz_p *xp;\n\n\n   zz_p LCInv, t;\n   zz_p s;\n\n   da = deg(a);\n   db = deg(b);\n\n   if (db < 0) ArithmeticError(\"zz_pX: division by zero\");\n\n   if (da < db) {\n      clear(q);\n      return;\n   }\n\n   zz_pX lb;\n\n   if (&q == &b) {\n      lb = b;\n      bp = lb.rep.elts();\n   }\n   else\n      bp = b.rep.elts();\n\n   if (IsOne(bp[db]))\n      LCIsOne = 1;\n   else {\n      LCIsOne = 0;\n      inv(LCInv, bp[db]);\n   }\n\n   vec_zz_p x;\n   x.SetLength(da+1-db);\n   for (i = db; i <= da; i++)\n      x[i-db] = a.rep[i];\n\n   xp = x.elts();\n\n\n\n   dq = da - db;\n   q.rep.SetLength(dq+1);\n   qp = q.rep.elts();\n\n   long p = zz_p::modulus();\n   mulmod_t pinv = zz_p::ModulusInverse();\n\n   for (i = dq; i >= 0; i--) {\n      t = xp[i];\n      if (!LCIsOne)\n         mul(t, t, LCInv);\n      qp[i] = t;\n      negate(t, t);\n\n      long T = rep(t);\n      mulmod_precon_t Tpinv = PrepMulModPrecon(T, p, pinv); \n\n      long lastj = max(0, db-i);\n\n      for (j = db-1; j >= lastj; j--) {\n         long S = MulModPrecon(rep(bp[j]), T, p, Tpinv);\n         S = AddMod(S, rep(xp[i+j-db]), p);\n         xp[i+j-db].LoopHole() = S;\n      }\n   }\n}\n\n\nvoid PlainRem(zz_pX& r, const zz_pX& a, const zz_pX& b)\n{\n   long da, db, dq, i, j, LCIsOne;\n   const zz_p *bp;\n   zz_p *xp;\n\n\n   zz_p LCInv, t;\n   zz_p s;\n\n   da = deg(a);\n   db = deg(b);\n\n   if (db < 0) ArithmeticError(\"zz_pX: division by zero\");\n\n   if (da < db) {\n      r = a;\n      return;\n   }\n\n   bp = b.rep.elts();\n\n   if (IsOne(bp[db]))\n      LCIsOne = 1;\n   else {\n      LCIsOne = 0;\n      inv(LCInv, bp[db]);\n   }\n\n   vec_zz_p x;\n\n   if (&r == &a)\n      xp = r.rep.elts();\n   else {\n      x = a.rep;\n      xp = x.elts();\n   }\n\n   dq = da - db;\n\n   long p = zz_p::modulus();\n   mulmod_t pinv = zz_p::ModulusInverse();\n\n   for (i = dq; i >= 0; i--) {\n      t = xp[i+db];\n      if (!LCIsOne)\n         mul(t, t, LCInv);\n      negate(t, t);\n\n      long T = rep(t);\n      mulmod_precon_t Tpinv = PrepMulModPrecon(T, p, pinv); \n\n      for (j = db-1; j >= 0; j--) {\n         long S = MulModPrecon(rep(bp[j]), T, p, Tpinv);\n         S = AddMod(S, rep(xp[i+j]), p);\n         xp[i+j].LoopHole() = S;\n      }\n   }\n\n   r.rep.SetLength(db);\n   if (&r != &a) {\n      for (i = 0; i < db; i++)\n         r.rep[i] = xp[i];\n   }\n   r.normalize();\n}\n\n\nvoid mul(zz_pX& x, const zz_pX& a, zz_p b)\n{\n   if (IsZero(b)) {\n      clear(x);\n      return;\n   }\n\n   if (IsOne(b)) {\n      x = a;\n      return;\n   }\n\n   long i, da;\n\n   const zz_p *ap;\n   zz_p* xp;\n\n   long t;\n   t = rep(b);\n   long p = zz_p::modulus();\n   mulmod_t pinv = zz_p::ModulusInverse();\n   mulmod_precon_t bpinv = PrepMulModPrecon(t, p, pinv); \n\n   da = deg(a);\n   x.rep.SetLength(da+1);\n   ap = a.rep.elts();\n   xp = x.rep.elts();\n\n   for (i = 0; i <= da; i++) \n      xp[i].LoopHole() = MulModPrecon(rep(ap[i]), t, p, bpinv);\n\n   x.normalize();\n}\n\n\n\nvoid PlainGCD(zz_pX& x, const zz_pX& a, const zz_pX& b)\n{\n   zz_p t;\n\n   if (IsZero(b))\n      x = a;\n   else if (IsZero(a))\n      x = b;\n   else {\n      long n = max(deg(a),deg(b)) + 1;\n      zz_pX u(INIT_SIZE, n), v(INIT_SIZE, n);\n\n      u = a;\n      v = b;\n      do {\n         PlainRem(u, u, v);\n         swap(u, v);\n      } while (!IsZero(v));\n\n      x = u;\n   }\n\n   if (IsZero(x)) return;\n   if (IsOne(LeadCoeff(x))) return;\n\n   /* make gcd monic */\n\n\n   inv(t, LeadCoeff(x)); \n   mul(x, x, t); \n}\n\n\n\n         \n\nvoid PlainXGCD(zz_pX& d, zz_pX& s, zz_pX& t, const zz_pX& a, const zz_pX& b)\n{\n   zz_p z;\n\n\n   if (IsZero(b)) {\n      set(s);\n      clear(t);\n      d = a;\n   }\n   else if (IsZero(a)) {\n      clear(s);\n      set(t);\n      d = b;\n   }\n   else {\n      long e = max(deg(a), deg(b)) + 1;\n\n      zz_pX temp(INIT_SIZE, e), u(INIT_SIZE, e), v(INIT_SIZE, e), u0(INIT_SIZE, e), v0(INIT_SIZE, e), \n            u1(INIT_SIZE, e), v1(INIT_SIZE, e), u2(INIT_SIZE, e), v2(INIT_SIZE, e), q(INIT_SIZE, e);\n\n\n      set(u1); clear(v1);\n      clear(u2); set(v2);\n      u = a; v = b;\n\n      do {\n         DivRem(q, u, u, v);\n         swap(u, v);\n         u0 = u2;\n         v0 = v2;\n         mul(temp, q, u2);\n         sub(u2, u1, temp);\n         mul(temp, q, v2);\n         sub(v2, v1, temp);\n         u1 = u0;\n         v1 = v0;\n      } while (!IsZero(v));\n\n      d = u;\n      s = u1;\n      t = v1;\n   }\n\n   if (IsZero(d)) return;\n   if (IsOne(LeadCoeff(d))) return;\n\n   /* make gcd monic */\n\n   inv(z, LeadCoeff(d));\n   mul(d, d, z);\n   mul(s, s, z);\n   mul(t, t, z);\n}\n\n\nvoid MulMod(zz_pX& x, const zz_pX& a, const zz_pX& b, const zz_pX& f)\n{\n   if (deg(a) >= deg(f) || deg(b) >= deg(f) || deg(f) == 0) \n      LogicError(\"MulMod: bad args\");\n\n   zz_pX t;\n\n   mul(t, a, b);\n   rem(x, t, f);\n}\n\nvoid SqrMod(zz_pX& x, const zz_pX& a, const zz_pX& f)\n{\n   if (deg(a) >= deg(f) || deg(f) == 0) LogicError(\"SqrMod: bad args\");\n\n   zz_pX t;\n\n   sqr(t, a);\n   rem(x, t, f);\n}\n\n\nvoid InvMod(zz_pX& x, const zz_pX& a, const zz_pX& f)\n{\n   if (deg(a) >= deg(f) || deg(f) == 0) LogicError(\"InvMod: bad args\");\n\n   zz_pX d, xx, t;\n\n   XGCD(d, xx, t, a, f);\n   if (!IsOne(d))\n      InvModError(\"zz_pX InvMod: can't compute multiplicative inverse\");\n\n   x = xx;\n}\n\nlong InvModStatus(zz_pX& x, const zz_pX& a, const zz_pX& f)\n{\n   if (deg(a) >= deg(f) || deg(f) == 0) LogicError(\"InvModStatus: bad args\");\n\n   zz_pX d, t;\n\n   XGCD(d, x, t, a, f);\n   if (!IsOne(d)) {\n      x = d;\n      return 1;\n   }\n   else\n      return 0;\n}\n\n\n\n\nstatic\nvoid MulByXModAux(zz_pX& h, const zz_pX& a, const zz_pX& f)\n{\n   long i, n, m;\n   zz_p* hh;\n   const zz_p *aa, *ff;\n\n   zz_p t, z;\n\n   n = deg(f);\n   m = deg(a);\n\n   if (m >= n || n == 0) LogicError(\"MulByXMod: bad args\");\n\n   if (m < 0) {\n      clear(h);\n      return;\n   }\n\n   if (m < n-1) {\n      h.rep.SetLength(m+2);\n      hh = h.rep.elts();\n      aa = a.rep.elts();\n      for (i = m+1; i >= 1; i--)\n         hh[i] = aa[i-1];\n      clear(hh[0]);\n   }\n   else {\n      h.rep.SetLength(n);\n      hh = h.rep.elts();\n      aa = a.rep.elts();\n      ff = f.rep.elts();\n      negate(z, aa[n-1]);\n      if (!IsOne(ff[n]))\n         div(z, z, ff[n]);\n      for (i = n-1; i >= 1; i--) {\n         mul(t, z, ff[i]);\n         add(hh[i], aa[i-1], t);\n      }\n      mul(hh[0], z, ff[0]);\n      h.normalize();\n   }\n}\n\nvoid MulByXMod(zz_pX& h, const zz_pX& a, const zz_pX& f)\n{\n   if (&h == &f) {\n      zz_pX hh;\n      MulByXModAux(hh, a, f);\n      h = hh;\n   }\n   else\n      MulByXModAux(h, a, f);\n}\n\n\nvoid random(zz_pX& x, long n)\n{\n   x.rep.SetLength(n);\n   VectorRandom(n, x.rep.elts());\n   x.normalize();\n}\n\n\n\n\n\nvoid fftRep::DoSetSize(long NewK, long NewNumPrimes)\n{\n   if (NewK < -1) LogicError(\"bad arg to fftRep::SetSize()\");\n   \n   if (NewK >= NTL_BITS_PER_LONG-1)\n      ResourceError(\"bad arg to fftRep::SetSize()\");\n\n   if (NewK == -1) {\n      k = -1;\n      return;\n   }\n\n   if (NewNumPrimes == 0) \n      NewNumPrimes = zz_pInfo->NumPrimes;\n\n   if (MaxK >= 0 && NumPrimes != NewNumPrimes)\n      LogicError(\"fftRep: inconsistent use\");\n\n   if (NewK <= MaxK) {\n      k = NewK;\n      return;\n   }\n\n   UniqueArray<long> new_tbl[4];\n   long i;\n\n   for (i = 0; i < NewNumPrimes; i++) \n      new_tbl[i].SetLength(1L << NewK);\n\n   for (i = 0; i < NewNumPrimes; i++) \n      tbl[i].move(new_tbl[i]);\n\n   NumPrimes = NewNumPrimes;\n   k = MaxK = NewK;\n}\n\nvoid fftRep::SetSize(long NewK)\n{\n   DoSetSize(NewK, 0);\n}\n\n\nfftRep& fftRep::operator=(const fftRep& R)\n{\n   if (this == &R) return *this;\n\n   if (MaxK >= 0 && R.MaxK >= 0 && NumPrimes != R.NumPrimes)\n      LogicError(\"fftRep: inconsistent use\");\n\n   if (R.k < 0) {\n      k = -1;\n      len = 0;\n      return *this;\n   }\n\n   DoSetSize(R.k, R.NumPrimes);\n   len = R.len;\n\n   long i, j;\n\n   for (i = 0; i < NumPrimes; i++)\n      for (j = 0; j < len; j++)\n         tbl[i][j] = R.tbl[i][j];\n\n   return *this;\n}\n\n\n\nstatic inline\nvoid FromModularRep(zz_p& res, long *a, zz_pInfoT* info)\n{\n   long n = info->NumPrimes;\n   long p = info->p;\n   mulmod_t pinv = info->pinv;\n   long *CoeffModP = info->CoeffModP.elts();\n   double *x = info->x.elts();\n   long *u = info->u.elts();\n   mulmod_precon_t *uqinv = info->uqinv.elts();\n   long MinusMModP = info->MinusMModP;\n   mulmod_precon_t MinusMModPpinv = info->MinusMModPpinv;\n   mulmod_precon_t *CoeffModPpinv = info->CoeffModPpinv.elts();\n\n   long q, s, t;\n   long i;\n   double y;\n\n   y = double(0L);\n   t = 0;\n\n   for (i = 0; i < n; i++) {\n      s = MulModPrecon(a[i], u[i], GetFFTPrime(i), uqinv[i]);\n      y = y + double(s)*GetFFTPrimeRecip(i);\n\n\n      // DIRT: uses undocumented MulMod feature (see sp_arith.h)\n      // input s is not reduced mod p\n      s = MulModPrecon(s, CoeffModP[i], p, CoeffModPpinv[i]);\n\n      t = AddMod(t, s, p);\n   }\n\n   q = (long) (y + 0.5);\n\n   // DIRT: uses undocumented MulMod feature (see sp_arith.h)\n   // input q may not be reduced mod p\n   s = MulModPrecon(q, MinusMModP, p, MinusMModPpinv);\n\n   t = AddMod(t, s, p);\n   res.LoopHole() = t;\n\n}\n\n\n#if 0\n// converts entries lo..lo+cnt-1 in R and stores results into res\nstatic \nvoid FromModularRep(zz_p* res, const fftRep& R, long lo, long cnt, \n                    zz_pInfoT* info)\n{\n   if (cnt <= 0) return;\n\n   long nprimes = info->NumPrimes;\n   long p = info->p;\n   mulmod_t pinv = info->pinv;\n   long *CoeffModP = info->CoeffModP.elts();\n   double *x = info->x.elts();\n   long *u = info->u.elts();\n   mulmod_precon_t *uqinv = info->uqinv.elts();\n   long MinusMModP = info->MinusMModP;\n   mulmod_precon_t MinusMModPpinv = info->MinusMModPpinv;\n   mulmod_precon_t *CoeffModPpinv = info->CoeffModPpinv.elts();\n\n   long primes[4];\n   double prime_recip[4];\n   long *tbl[4];\n\n   long q, s, t;\n   long i, j;\n   double y;\n\n   for (i = 0; i < nprimes; i++) {\n      primes[i] = GetFFTPrime(i);\n      prime_recip[i] = GetFFTPrimeRecip(i);\n      tbl[i] = R.tbl[i].get();\n   }\n\n   for (j = 0; j < cnt; j++) {\n      y = double(0L);\n      t = 0;\n\n      for (i = 0; i < nprimes; i++) {\n         s = MulModPrecon(tbl[i][j+lo], u[i], primes[i], uqinv[i]);\n         y = y + double(s)*prime_recip[i];\n\n\n         // DIRT: uses undocumented MulMod feature (see sp_arith.h)\n         // input s is not reduced mod p\n         s = MulModPrecon(s, CoeffModP[i], p, CoeffModPpinv[i]);\n\n         t = AddMod(t, s, p);\n      }\n\n      q = (long) (y + 0.5);\n\n      // DIRT: uses undocumented MulMod feature (see sp_arith.h)\n      // input q may not be reduced mod p\n      s = MulModPrecon(q, MinusMModP, p, MinusMModPpinv);\n\n      t = AddMod(t, s, p);\n      res[j].LoopHole() = t;\n   }\n\n}\n#else\n\n#define NTL_FMR_LOOP_BODY(i) \\\n         s = MulModPrecon(tbl[i][j+lo], u[i], primes[i], uqinv[i]);\\\n         y = y + double(s)*prime_recip[i];\\\n\\\n\\\n         /* DIRT: uses undocumented MulMod feature (see sp_arith.h) */\\\n         /* input s is not reduced mod p */\\\n         s = MulModPrecon(s, CoeffModP[i], p, CoeffModPpinv[i]);\\\n\\\n         t = AddMod(t, s, p);\\\n\n\n#define NTL_FMP_OUTER_LOOP(XXX) \\\n   for (j = 0; j < cnt; j++) {\\\n      y = double(0L);\\\n      t = 0;\\\n      XXX \\\n      q = (long) (y + 0.5);\\\n      /* DIRT: uses undocumented MulMod feature (see sp_arith.h) */\\\n      /* input q may not be reduced mod p */\\\n      s = MulModPrecon(q, MinusMModP, p, MinusMModPpinv);\\\n      t = AddMod(t, s, p);\\\n      res[j].LoopHole() = t;\\\n   }\\\n\n\n\n// converts entries lo..lo+cnt-1 in R and stores results into res\nstatic \nvoid FromModularRep(zz_p* res, const fftRep& R, long lo, long cnt, \n                    zz_pInfoT* info)\n{\n   if (cnt <= 0) return;\n\n   long nprimes = info->NumPrimes;\n   long p = info->p;\n   mulmod_t pinv = info->pinv;\n   long *CoeffModP = info->CoeffModP.elts();\n   double *x = info->x.elts();\n   long *u = info->u.elts();\n   mulmod_precon_t *uqinv = info->uqinv.elts();\n   long MinusMModP = info->MinusMModP;\n   mulmod_precon_t MinusMModPpinv = info->MinusMModPpinv;\n   mulmod_precon_t *CoeffModPpinv = info->CoeffModPpinv.elts();\n\n   long primes[4];\n   double prime_recip[4];\n   long *tbl[4];\n\n   long q, s, t;\n   long i, j;\n   double y;\n\n   for (i = 0; i < nprimes; i++) {\n      primes[i] = GetFFTPrime(i);\n      prime_recip[i] = GetFFTPrimeRecip(i);\n      tbl[i] = R.tbl[i].get();\n   }\n\n   if (nprimes == 1) {\n      long *tbl_0 = tbl[0];\n      mulmod_precon_t CoeffModPpinv_0 = CoeffModPpinv[0];\n      long primes_0 = primes[0];\n      long hp0 = primes_0 >> 1;\n      \n      for (j = 0; j < cnt; j++) {\n         s = tbl_0[j+lo];\n\n         // DIRT: uses undocumented MulMod feature (see sp_arith.h)\n         // input s is not reduced mod p\n         t = MulModPrecon(s, 1, p, CoeffModPpinv_0);\n\n         res[j].LoopHole() = AddMod(t, sp_SignMask(hp0-s) & MinusMModP, p);\n      }\n   }\n   else if (nprimes == 2) {\n      NTL_FMP_OUTER_LOOP( NTL_FMR_LOOP_BODY(0) NTL_FMR_LOOP_BODY(1) )\n   }\n   else if (nprimes == 3) {\n      NTL_FMP_OUTER_LOOP( NTL_FMR_LOOP_BODY(0) NTL_FMR_LOOP_BODY(1) NTL_FMR_LOOP_BODY(2) )\n   }\n   else { // nprimes == 4\n      NTL_FMP_OUTER_LOOP( NTL_FMR_LOOP_BODY(0) NTL_FMR_LOOP_BODY(1) NTL_FMR_LOOP_BODY(2)  NTL_FMR_LOOP_BODY(3) )\n   }\n}\n\n\n\n\n#endif\n\n\n\n\nvoid TofftRep_trunc(fftRep& y, const zz_pX& x, long k, \n                    long len, long lo, long hi)\n// computes an n = 2^k point convolution.\n// if deg(x) >= 2^k, then x is first reduced modulo X^n-1.\n{\n   zz_pInfoT *info = zz_pInfo;\n   long p = info->p;\n\n   long n, i, j, m, j1;\n   long accum;\n   long nprimes = info->NumPrimes;\n\n\n   if (k > info->MaxRoot) \n      ResourceError(\"Polynomial too big for FFT\");\n\n   if (lo < 0)\n      LogicError(\"bad arg to TofftRep\");\n\n   hi = min(hi, deg(x));\n\n   y.SetSize(k);\n   n = 1L << k;\n\n   y.len = len = FFTRoundUp(len, k);\n\n   m = max(hi-lo + 1, 0);\n   long ilen = FFTRoundUp(m, k);\n\n   const zz_p *xx = x.rep.elts();\n\n   FFTPrimeInfo *p_info = info->p_info;\n\n   if (p_info) {\n      if (n >= m) {\n         long *yp = &y.tbl[0][0];\n         for (j = 0; j < m; j++) {\n            yp[j] = rep(xx[j+lo]);\n         }\n         for (j = m; j < ilen; j++) {\n            yp[j] = 0;\n         }\n      }\n      else {\n         for (j = 0; j < n; j++) {\n            accum = rep(xx[j+lo]);\n            for (j1 = j + n; j1 < m; j1 += n)\n               accum = AddMod(accum, rep(xx[j1+lo]), p);\n            y.tbl[0][j] = accum;\n         }\n      }\n   }\n   else {\n      if (n >= m) {\n         for (i = 0; i < nprimes; i++) {\n            long q = GetFFTPrime(i);\n            long *yp = &y.tbl[i][0];\n            for (j = 0; j < m; j++) {\n               long t = rep(xx[j+lo]);\n               t = sp_CorrectExcess(t, q);\n               yp[j] = t;\n            }\n            for (j = m; j < ilen; j++) {\n               yp[j] = 0;\n            }\n         }\n      }\n      else {\n         for (j = 0; j < n; j++) {\n            accum = rep(xx[j+lo]);\n            for (j1 = j + n; j1 < m; j1 += n)\n               accum = AddMod(accum, rep(xx[j1+lo]), p);\n            for (i = 0; i < nprimes; i++) {\n               long q = GetFFTPrime(i);\n               long t = accum;\n               t = sp_CorrectExcess(t, q);\n               y.tbl[i][j] = t;\n            }\n         }\n      }\n   }\n   \n\n   if (p_info) {\n      long *yp = &y.tbl[0][0];\n      FFTFwd_trunc(yp, yp, k, *p_info, len, ilen);\n   } \n   else {\n      for (i = 0; i < nprimes; i++) {\n         long *yp = &y.tbl[i][0];\n         FFTFwd_trunc(yp, yp, k, i, len, ilen);\n      }\n   }\n}\n\n\n\nvoid RevTofftRep(fftRep& y, const vec_zz_p& x, \n                 long k, long lo, long hi, long offset)\n// computes an n = 2^k point convolution of X^offset*x[lo..hi] mod X^n-1\n// using \"inverted\" evaluation points.\n\n{\n   zz_pInfoT *info = zz_pInfo;\n   long p = info->p;\n\n   long n, i, j, m, j1;\n   long accum;\n   long NumPrimes = info->NumPrimes;\n\n   if (k > info->MaxRoot) \n      ResourceError(\"Polynomial too big for FFT\");\n\n   if (lo < 0)\n      LogicError(\"bad arg to TofftRep\");\n\n   hi = min(hi, x.length()-1);\n\n   y.SetSize(k);\n\n   n = 1L << k;\n   y.len = n;\n\n   m = max(hi-lo + 1, 0);\n\n   const zz_p *xx = x.elts();\n\n   FFTPrimeInfo *p_info = info->p_info;\n\n   offset = offset & (n-1);\n\n   if (p_info) {\n      for (j = 0; j < n; j++) {\n         if (j >= m) {\n            y.tbl[0][offset] = 0;\n         }\n         else {\n            accum = rep(xx[j+lo]);\n            for (j1 = j + n; j1 < m; j1 += n)\n               accum = AddMod(accum, rep(xx[j1+lo]), p);\n               y.tbl[0][offset] = accum;\n         }\n         offset = (offset + 1) & (n-1);\n      }\n   }\n   else {\n      for (j = 0; j < n; j++) {\n         if (j >= m) {\n            for (i = 0; i < NumPrimes; i++)\n               y.tbl[i][offset] = 0;\n         }\n         else {\n            accum = rep(xx[j+lo]);\n            for (j1 = j + n; j1 < m; j1 += n)\n               accum = AddMod(accum, rep(xx[j1+lo]), p);\n            for (i = 0; i < NumPrimes; i++) {\n               long q = GetFFTPrime(i);\n               long t = accum;\n               t = sp_CorrectExcess(t, q);\n               y.tbl[i][offset] = t;\n            }\n         }\n         offset = (offset + 1) & (n-1);\n      }\n   }\n\n\n   if (p_info) {\n      long *yp = &y.tbl[0][0];\n      FFTRev1_trans(yp, yp, k, *p_info);\n   }\n   else {\n      for (i = 0; i < info->NumPrimes; i++) {\n         long *yp = &y.tbl[i][0];\n         FFTRev1_trans(yp, yp, k, i);\n      }\n   }\n}\n\nvoid FromfftRep(zz_pX& x, fftRep& y, long lo, long hi)\n\n   // converts from FFT-representation to coefficient representation\n   // only the coefficients lo..hi are computed\n   \n\n{\n   zz_pInfoT *info = zz_pInfo;\n\n   long k, n, i, j, l;\n   long NumPrimes = info->NumPrimes;\n\n\n   k = y.k;\n   n = (1L << k);\n\n   hi = min(hi, n-1);\n   l = hi-lo+1;\n   l = max(l, 0);\n\n   long len = y.len;\n   if (len <= hi) LogicError(\"FromfftRep: bad len\"); \n\n   FFTPrimeInfo *p_info = info->p_info;\n\n   if (p_info) {\n      long *yp = &y.tbl[0][0];\n      FFTRev1_trunc(yp, yp, k, *p_info, len);\n   }\n   else {\n      for (i = 0; i < NumPrimes; i++) {\n         long *yp = &y.tbl[i][0];\n         FFTRev1_trunc(yp, yp, k, i, len);\n      }\n   }\n\n   x.rep.SetLength(l);\n\n   if (p_info) {\n      zz_p *xp = x.rep.elts();\n      long *yp = &y.tbl[0][0];\n      for (j = 0; j < l; j++) \n         xp[j].LoopHole() = yp[j+lo];\n   }\n   else {\n      FromModularRep(x.rep.elts(), y, lo, l, info);\n   }\n\n   x.normalize();\n}\n\nvoid RevFromfftRep(vec_zz_p& x, fftRep& y, long lo, long hi)\n\n   // converts from FFT-representation to coefficient representation\n   // using \"inverted\" evaluation points.\n   // only the coefficients lo..hi are computed\n   \n\n{\n   zz_pInfoT *info = zz_pInfo;\n\n   long k, n, i, j, l;\n   long NumPrimes = info->NumPrimes;\n\n\n   k = y.k;\n   n = (1L << k);\n\n   if (y.len != n) LogicError(\"RevFromfftRep: bad len\");\n\n   FFTPrimeInfo *p_info = info->p_info;\n\n   if (p_info) {\n      long *yp = &y.tbl[0][0];\n      FFTFwd_trans(yp, yp, k, *p_info);\n   }\n   else {\n      for (i = 0; i < NumPrimes; i++) {\n         long *yp = &y.tbl[i][0];\n         FFTFwd_trans(yp, yp, k, i);\n      }\n   }\n\n   hi = min(hi, n-1);\n   l = hi-lo+1;\n   l = max(l, 0);\n   x.SetLength(l);\n\n   if (p_info) {\n      zz_p *xp = x.elts();\n      long *yp = &y.tbl[0][0];\n      for (j = 0; j < l; j++) \n         xp[j].LoopHole() = yp[j+lo];\n   }\n   else {\n      FromModularRep(x.elts(), y, lo, l, info);\n   }\n}\n\nvoid NDFromfftRep(zz_pX& x, const fftRep& y, long lo, long hi, fftRep& z)\n{\n   zz_pInfoT *info = zz_pInfo;\n   \n   long k, n, i, j, l;\n   long NumPrimes = info->NumPrimes;\n\n\n   k = y.k;\n   n = (1L << k);\n\n   hi = min(hi, n-1);\n   l = hi-lo+1;\n   l = max(l, 0);\n\n   long len = y.len;\n   if (len <= hi) LogicError(\"FromfftRep: bad len\");\n\n   z.SetSize(k);\n\n   FFTPrimeInfo *p_info = info->p_info;\n\n   if (p_info) {\n      long *zp = &z.tbl[0][0];\n      const long *yp = &y.tbl[0][0];\n      FFTRev1_trunc(zp, yp, k, *p_info, len);\n   }\n   else {\n      for (i = 0; i < NumPrimes; i++) {\n         long *zp = &z.tbl[i][0];\n         const long *yp = &y.tbl[i][0];\n         FFTRev1_trunc(zp, yp, k, i, len);\n      }\n   }\n\n   x.rep.SetLength(l);\n\n   if (p_info) {\n      zz_p *xp = x.rep.elts();\n      long *zp = &z.tbl[0][0];\n      for (j = 0; j < l; j++) \n         xp[j].LoopHole() = zp[j+lo];\n   }\n   else {\n      FromModularRep(x.rep.elts(), z, lo, l, info);\n   }\n\n   x.normalize();\n}\n\nvoid NDFromfftRep(zz_pX& x, fftRep& y, long lo, long hi)\n{\n   fftRep z;\n   NDFromfftRep(x, y, lo, hi, z);\n}\n\nvoid FromfftRep(zz_p* x, fftRep& y, long lo, long hi)\n\n   // converts from FFT-representation to coefficient representation\n   // only the coefficients lo..hi are computed\n   \n\n{\n   zz_pInfoT *info = zz_pInfo;\n\n   long k, n, i, j;\n   long NumPrimes = info->NumPrimes;\n\n\n   k = y.k;\n   n = (1L << k);\n\n\n   //if (y.len <= min(hi, n-1)) LogicError(\"FromfftRep: bad len\");\n   if (y.len != n) LogicError(\"FromfftRep: bad len\");\n\n   FFTPrimeInfo *p_info = info->p_info;\n\n   if (p_info) {\n      long *yp = &y.tbl[0][0];\n      FFTRev1(yp, yp, k, *p_info);\n\n      for (j = lo; j <= hi; j++) {\n         if (j >= n)\n            clear(x[j-lo]);\n         else {\n            x[j-lo].LoopHole() = y.tbl[0][j];\n         }\n      }\n   }\n   else {\n      for (i = 0; i < NumPrimes; i++) {\n         long *yp = &y.tbl[i][0];\n         FFTRev1(yp, yp, k, i);\n      }\n\n      // take coefficients lo..min(hi, n-1) from y\n      // zero out coefficients max(n, lo)..hi\n   \n      long l = min(hi, n-1) - lo + 1;\n      l = max(l, 0);\n      FromModularRep(x, y, lo, l, info); \n      for (j = max(n, lo); j <= hi; j++) clear(x[j-lo]);\n   }\n}\n\n\nvoid mul(fftRep& z, const fftRep& x, const fftRep& y)\n{\n   zz_pInfoT *info = zz_pInfo;\n\n   long k, n, i, j;\n\n   if (x.k != y.k) LogicError(\"FFT rep mismatch\");\n\n   k = x.k;\n   n = 1L << k;\n\n   z.SetSize(k);\n\n   long len = z.len = min(x.len, y.len);\n\n   FFTPrimeInfo *p_info = info->p_info;\n\n   if (p_info) {\n      long *zp = &z.tbl[0][0];\n      const long *xp = &x.tbl[0][0];\n      const long *yp = &y.tbl[0][0];\n      long q = p_info->q;\n      mulmod_t qinv = p_info->qinv;\n\n      if (NormalizedModulus(qinv)) {\n         for (j = 0; j < len; j++)\n            zp[j] = NormalizedMulMod(xp[j], yp[j], q, qinv);\n      }\n      else {\n         for (j = 0; j < len; j++)\n            zp[j] = MulMod(xp[j], yp[j], q, qinv);\n      }\n   }\n   else {\n      for (i = 0; i < info->NumPrimes; i++) {\n         long *zp = &z.tbl[i][0];\n         const long *xp = &x.tbl[i][0];\n         const long *yp = &y.tbl[i][0];\n         long q = GetFFTPrime(i);\n         mulmod_t qinv = GetFFTPrimeInv(i);\n   \n         for (j = 0; j < len; j++)\n            zp[j] = NormalizedMulMod(xp[j], yp[j], q, qinv);\n      }\n   }\n}\n\nvoid sub(fftRep& z, const fftRep& x, const fftRep& y)\n{\n   zz_pInfoT *info = zz_pInfo;\n\n   long k, n, i, j;\n\n   if (x.k != y.k) LogicError(\"FFT rep mismatch\");\n\n   k = x.k;\n   n = 1L << k;\n\n   z.SetSize(k);\n\n   long len = z.len = min(x.len, y.len);\n\n   FFTPrimeInfo *p_info = info->p_info;\n\n   if (p_info) {\n      long *zp = &z.tbl[0][0];\n      const long *xp = &x.tbl[0][0];\n      const long *yp = &y.tbl[0][0];\n      long q = p_info->q;\n\n      for (j = 0; j < len; j++)\n         zp[j] = SubMod(xp[j], yp[j], q);\n   }\n   else {\n      for (i = 0; i < info->NumPrimes; i++) {\n         long *zp = &z.tbl[i][0];\n         const long *xp = &x.tbl[i][0];\n         const long *yp = &y.tbl[i][0];\n         long q = GetFFTPrime(i);\n   \n         for (j = 0; j < len; j++)\n            zp[j] = SubMod(xp[j], yp[j], q);\n      }\n   }\n}\n\nvoid add(fftRep& z, const fftRep& x, const fftRep& y)\n{\n   zz_pInfoT *info = zz_pInfo;\n\n   long k, n, i, j;\n\n   if (x.k != y.k) LogicError(\"FFT rep mismatch\");\n\n   k = x.k;\n   n = 1L << k;\n\n   z.SetSize(k);\n\n   long len = z.len = min(x.len, y.len);\n\n   FFTPrimeInfo *p_info = info->p_info;\n\n   if (p_info) {\n      long *zp = &z.tbl[0][0];\n      const long *xp = &x.tbl[0][0];\n      const long *yp = &y.tbl[0][0];\n      long q = p_info->q;\n\n      for (j = 0; j < len; j++)\n         zp[j] = AddMod(xp[j], yp[j], q);\n   }\n   else {\n      for (i = 0; i < info->NumPrimes; i++) {\n         long *zp = &z.tbl[i][0];\n         const long *xp = &x.tbl[i][0];\n         const long *yp = &y.tbl[i][0];\n         long q = GetFFTPrime(i);\n   \n         for (j = 0; j < len; j++)\n            zp[j] = AddMod(xp[j], yp[j], q);\n      }\n   }\n}\n\n\nvoid reduce(fftRep& x, const fftRep& a, long k)\n  // reduces a 2^l point FFT-rep to a 2^k point FFT-rep\n  // input may alias output\n{\n   zz_pInfoT *info = zz_pInfo;\n\n   long i, j, l, n;\n   long* xp;\n   const long* ap;\n\n   l = a.k;\n   n = 1L << k;\n\n   if (l < k) LogicError(\"reduce: bad operands\");\n   if (a.len < n) LogicError(\"reduce: bad len\");\n\n   x.SetSize(k);\n   x.len = n;\n\n   if (&x == &a) return;\n\n   for (i = 0; i < info->NumPrimes; i++) {\n      ap = &a.tbl[i][0];   \n      xp = &x.tbl[i][0];\n      for (j = 0; j < n; j++) \n         xp[j] = ap[j];\n   }\n}\n\n\nvoid AddExpand(fftRep& x, const fftRep& a)\n//  x = x + (an \"expanded\" version of a)\n{\n   zz_pInfoT *info = zz_pInfo;\n\n   long i, j, l, k, n;\n\n   l = x.k;\n   k = a.k;\n   n = 1L << k;\n\n   if (l < k) LogicError(\"AddExpand: bad args\");\n   if (x.len < n) LogicError(\"AddExpand: bad len\");\n\n   FFTPrimeInfo *p_info = info->p_info;\n   \n   if (p_info) {\n      long q = p_info->q;\n      const long *ap = &a.tbl[0][0];\n      long *xp = &x.tbl[0][0];\n      for (j = 0; j < n; j++) {\n         xp[j] = AddMod(xp[j], ap[j], q);\n      }\n   }\n   else {\n      for (i = 0; i < info->NumPrimes; i++) {\n         long q = GetFFTPrime(i);\n         const long *ap = &a.tbl[i][0];\n         long *xp = &x.tbl[i][0];\n         for (j = 0; j < n; j++) {\n            xp[j] = AddMod(xp[j], ap[j], q);\n         }\n      }\n   }\n}\n\n\nvoid FFTMul(zz_pX& x, const zz_pX& a, const zz_pX& b)\n{\n   if (IsZero(a) || IsZero(b)) {\n      clear(x);\n      return;\n   }\n\n   long da = deg(a);\n   long db = deg(b);\n   long d = da+db;\n   long k = NextPowerOfTwo(d+1);\n\n   fftRep R1(INIT_SIZE, k), R2(INIT_SIZE, k);\n\n   TofftRep_trunc(R1, a, k, d+1);\n   TofftRep_trunc(R2, b, k, d+1);\n   mul(R1, R1, R2);\n   FromfftRep(x, R1, 0, d);\n}\n\nvoid FFTSqr(zz_pX& x, const zz_pX& a)\n{\n   if (IsZero(a)) {\n      clear(x);\n      return;\n   }\n\n   long da = deg(a);\n   long d = 2*da;\n   long k = NextPowerOfTwo(d+1);\n\n   fftRep R1(INIT_SIZE, k);\n\n   TofftRep_trunc(R1, a, k, d+1);\n   mul(R1, R1, R1);\n   FromfftRep(x, R1, 0, d);\n}\n\n\nvoid CopyReverse(zz_pX& x, const zz_pX& a, long lo, long hi)\n\n   // x[0..hi-lo] = reverse(a[lo..hi]), with zero fill\n   // input may not alias output\n\n{\n   long i, j, n, m;\n\n   n = hi-lo+1;\n   m = a.rep.length();\n\n   x.rep.SetLength(n);\n\n   const zz_p* ap = a.rep.elts();\n   zz_p* xp = x.rep.elts();\n\n   for (i = 0; i < n; i++) {\n      j = hi-i;\n      if (j < 0 || j >= m)\n         clear(xp[i]);\n      else\n         xp[i] = ap[j];\n   }\n\n   x.normalize();\n} \n\nvoid copy(zz_pX& x, const zz_pX& a, long lo, long hi)\n\n   // x[0..hi-lo] = a[lo..hi], with zero fill\n   // input may not alias output\n\n{\n   long i, j, n, m;\n\n   n = hi-lo+1;\n   m = a.rep.length();\n\n   x.rep.SetLength(n);\n\n   const zz_p* ap = a.rep.elts();\n   zz_p* xp = x.rep.elts();\n\n   for (i = 0; i < n; i++) {\n      j = lo + i;\n      if (j < 0 || j >= m)\n         clear(xp[i]);\n      else\n         xp[i] = ap[j];\n   }\n\n   x.normalize();\n} \n\n\nvoid rem21(zz_pX& x, const zz_pX& a, const zz_pXModulus& F)\n{\n   long i, da, ds, n, kk;\n\n   da = deg(a);\n   n = F.n;\n\n   if (da > 2*n-2)\n      LogicError(\"bad args to rem(zz_pX,zz_pX,zz_pXModulus)\");\n\n\n   if (da < n) {\n      x = a;\n      return;\n   }\n\n   if (!F.UseFFT || da - n <= NTL_zz_pX_MOD_CROSSOVER) {\n      PlainRem(x, a, F.f);\n      return;\n   }\n\n   fftRep R1(INIT_SIZE, F.l);\n   zz_pX P1(INIT_SIZE, n);\n\n   TofftRep_trunc(R1, a, F.l, 2*n-3, n, 2*(n-1));\n   mul(R1, R1, F.HRep);\n   FromfftRep(P1, R1, n-2, 2*n-4);\n\n   TofftRep(R1, P1, F.k);\n   mul(R1, R1, F.FRep);\n   FromfftRep(P1, R1, 0, n-1);\n\n   ds = deg(P1);\n\n   kk = 1L << F.k;\n\n   x.rep.SetLength(n);\n   const zz_p* aa = a.rep.elts();\n   const zz_p* ss = P1.rep.elts();\n   zz_p* xx = x.rep.elts();\n\n   for (i = 0; i < n; i++) {\n      if (i <= ds)\n         sub(xx[i], aa[i], ss[i]);\n      else\n         xx[i] = aa[i];\n\n      if (i + kk <= da)\n         add(xx[i], xx[i], aa[i+kk]);\n   }\n\n   x.normalize();\n}\n\n\nvoid DivRem21(zz_pX& q, zz_pX& x, const zz_pX& a, const zz_pXModulus& F)\n{\n   long i, da, ds, n, kk;\n\n   da = deg(a);\n   n = F.n;\n\n   if (da > 2*n-2)\n      LogicError(\"bad args to rem(zz_pX,zz_pX,zz_pXModulus)\");\n\n\n   if (da < n) {\n      x = a;\n      clear(q);\n      return;\n   }\n\n   if (!F.UseFFT || da - n <= NTL_zz_pX_MOD_CROSSOVER) {\n      PlainDivRem(q, x, a, F.f);\n      return;\n   }\n\n   fftRep R1(INIT_SIZE, F.l);\n   zz_pX P1(INIT_SIZE, n), qq;\n\n   TofftRep_trunc(R1, a, F.l, 2*n-3, n, 2*(n-1));\n   mul(R1, R1, F.HRep);\n   FromfftRep(P1, R1, n-2, 2*n-4);\n   qq = P1;\n\n   TofftRep(R1, P1, F.k);\n   mul(R1, R1, F.FRep);\n   FromfftRep(P1, R1, 0, n-1);\n\n   ds = deg(P1);\n\n   kk = 1L << F.k;\n\n   x.rep.SetLength(n);\n   const zz_p* aa = a.rep.elts();\n   const zz_p* ss = P1.rep.elts();\n   zz_p* xx = x.rep.elts();\n\n   for (i = 0; i < n; i++) {\n      if (i <= ds)\n         sub(xx[i], aa[i], ss[i]);\n      else\n         xx[i] = aa[i];\n\n      if (i + kk <= da)\n         add(xx[i], xx[i], aa[i+kk]);\n   }\n\n   x.normalize();\n   q = qq;\n}\n\nvoid div21(zz_pX& x, const zz_pX& a, const zz_pXModulus& F)\n{\n   long da, n;\n\n   da = deg(a);\n   n = F.n;\n\n   if (da > 2*n-2)\n      LogicError(\"bad args to rem(zz_pX,zz_pX,zz_pXModulus)\");\n\n\n   if (da < n) {\n      clear(x);\n      return;\n   }\n\n   if (!F.UseFFT || da - n <= NTL_zz_pX_MOD_CROSSOVER) {\n      PlainDiv(x, a, F.f);\n      return;\n   }\n\n   fftRep R1(INIT_SIZE, F.l);\n   zz_pX P1(INIT_SIZE, n);\n\n   TofftRep_trunc(R1, a, F.l, 2*n-3, n, 2*(n-1));\n   mul(R1, R1, F.HRep);\n   FromfftRep(x, R1, n-2, 2*n-4);\n}\n\n\nvoid rem(zz_pX& x, const zz_pX& a, const zz_pXModulus& F)\n{\n   long da = deg(a);\n   long n = F.n;\n\n   if (n < 0) LogicError(\"rem: uninitialized modulus\");\n\n   if (da <= 2*n-2) {\n      rem21(x, a, F);\n      return;\n   }\n   else if (!F.UseFFT || da-n <= NTL_zz_pX_MOD_CROSSOVER) {\n      PlainRem(x, a, F.f);\n      return;\n   }\n\n   zz_pX buf(INIT_SIZE, 2*n-1);\n\n   long a_len = da+1;\n\n   while (a_len > 0) {\n      long old_buf_len = buf.rep.length();\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      buf.rep.SetLength(old_buf_len+amt);\n\n      long i;\n\n      for (i = old_buf_len+amt-1; i >= amt; i--)\n         buf.rep[i] = buf.rep[i-amt];\n\n      for (i = amt-1; i >= 0; i--)\n         buf.rep[i] = a.rep[a_len-amt+i];\n\n      buf.normalize();\n\n      rem21(buf, buf, F);\n\n      a_len -= amt;\n   }\n\n   x = buf;\n}\n\nvoid DivRem(zz_pX& q, zz_pX& r, const zz_pX& a, const zz_pXModulus& F)\n{\n   long da = deg(a);\n   long n = F.n;\n\n   if (n < 0) LogicError(\"DivRem: uninitialized modulus\");\n\n   if (da <= 2*n-2) {\n      DivRem21(q, r, a, F);\n      return;\n   }\n   else if (!F.UseFFT || da-n <= NTL_zz_pX_MOD_CROSSOVER) {\n      PlainDivRem(q, r, a, F.f);\n      return;\n   }\n\n   zz_pX buf(INIT_SIZE, 2*n-1);\n   zz_pX qbuf(INIT_SIZE, n-1);\n\n   zz_pX qq;\n   qq.rep.SetLength(da-n+1);\n\n   long a_len = da+1;\n   long q_hi = da-n+1;\n\n   while (a_len > 0) {\n      long old_buf_len = buf.rep.length();\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      buf.rep.SetLength(old_buf_len+amt);\n\n      long i;\n\n      for (i = old_buf_len+amt-1; i >= amt; i--)\n         buf.rep[i] = buf.rep[i-amt];\n\n      for (i = amt-1; i >= 0; i--)\n         buf.rep[i] = a.rep[a_len-amt+i];\n\n      buf.normalize();\n\n      DivRem21(qbuf, buf, buf, F);\n      long dl = qbuf.rep.length();\n      a_len = a_len - amt;\n      for(i = 0; i < dl; i++)\n         qq.rep[a_len+i] = qbuf.rep[i];\n      for(i = dl+a_len; i < q_hi; i++)\n         clear(qq.rep[i]);\n      q_hi = a_len;\n   }\n\n   r = buf;\n\n   qq.normalize();\n   q = qq;\n}\n\nvoid div(zz_pX& q, const zz_pX& a, const zz_pXModulus& F)\n{\n   long da = deg(a);\n   long n = F.n;\n\n   if (n < 0) LogicError(\"div: uninitialized modulus\");\n\n   if (da <= 2*n-2) {\n      div21(q, a, F);\n      return;\n   }\n   else if (!F.UseFFT || da-n <= NTL_zz_pX_MOD_CROSSOVER) {\n      PlainDiv(q, a, F.f);\n      return;\n   }\n\n   zz_pX buf(INIT_SIZE, 2*n-1);\n   zz_pX qbuf(INIT_SIZE, n-1);\n\n   zz_pX qq;\n   qq.rep.SetLength(da-n+1);\n\n   long a_len = da+1;\n   long q_hi = da-n+1;\n\n   while (a_len > 0) {\n      long old_buf_len = buf.rep.length();\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      buf.rep.SetLength(old_buf_len+amt);\n\n      long i;\n\n      for (i = old_buf_len+amt-1; i >= amt; i--)\n         buf.rep[i] = buf.rep[i-amt];\n\n      for (i = amt-1; i >= 0; i--)\n         buf.rep[i] = a.rep[a_len-amt+i];\n\n      buf.normalize();\n\n      a_len = a_len - amt;\n      if (a_len > 0)\n         DivRem21(qbuf, buf, buf, F);\n      else\n         div21(qbuf, buf, F);\n\n      long dl = qbuf.rep.length();\n      for(i = 0; i < dl; i++)\n         qq.rep[a_len+i] = qbuf.rep[i];\n      for(i = dl+a_len; i < q_hi; i++)\n         clear(qq.rep[i]);\n      q_hi = a_len;\n   }\n\n   qq.normalize();\n   q = qq;\n}\n\n\nvoid MulMod(zz_pX& x, const zz_pX& a, const zz_pX& b, const zz_pXModulus& F)\n{\n   long  da, db, d, n, k;\n\n   da = deg(a);\n   db = deg(b);\n   n = F.n;\n\n   if (n < 0) LogicError(\"MulMod: uninitialized modulus\");\n\n   if (da >= n || db >= n)\n      LogicError(\"bad args to MulMod(zz_pX,zz_pX,zz_pX,zz_pXModulus)\");\n\n   if (da < 0 || db < 0) {\n      clear(x);\n      return;\n   }\n\n   if (!F.UseFFT || da <= NTL_zz_pX_MUL_CROSSOVER || db <= NTL_zz_pX_MUL_CROSSOVER) {\n      zz_pX P1;\n      mul(P1, a, b);\n      rem(x, P1, F);\n      return;\n   }\n\n   d = da + db + 1;\n\n   k = NextPowerOfTwo(d);\n   k = max(k, F.k);\n\n   fftRep R1(INIT_SIZE, k), R2(INIT_SIZE, F.l);\n   zz_pX P1(INIT_SIZE, n);\n\n   long len;\n   if (zz_p::IsFFTPrime()) \n      len = n;\n   else\n      len = 1L << F.k;\n\n   TofftRep_trunc(R1, a, k, max(1L << F.k, d));\n   TofftRep_trunc(R2, b, k, max(1L << F.k, d));\n   mul(R1, R1, R2);\n   NDFromfftRep(P1, R1, n, d-1, R2); // save R1 for future use\n\n   TofftRep_trunc(R2, P1, F.l, 2*n-3);\n   mul(R2, R2, F.HRep);\n   FromfftRep(P1, R2, n-2, 2*n-4);\n\n   TofftRep_trunc(R2, P1, F.k, len);\n   mul(R2, R2, F.FRep);\n   reduce(R1, R1, F.k);\n   sub(R1, R1, R2);\n   FromfftRep(x, R1, 0, n-1);\n}\n\nvoid SqrMod(zz_pX& x, const zz_pX& a, const zz_pXModulus& F)\n{\n   long  da, d, n, k;\n\n   da = deg(a);\n   n = F.n;\n\n   if (n < 0) LogicError(\"SqrMod: uninitialized modulus\");\n\n   if (da >= n) \n      LogicError(\"bad args to SqrMod(zz_pX,zz_pX,zz_pXModulus)\");\n\n   if (!F.UseFFT || da <= NTL_zz_pX_MUL_CROSSOVER) {\n      zz_pX P1;\n      sqr(P1, a);\n      rem(x, P1, F);\n      return;\n   }\n\n\n   d = 2*da + 1;\n\n   k = NextPowerOfTwo(d);\n   k = max(k, F.k);\n\n   fftRep R1(INIT_SIZE, k), R2(INIT_SIZE, F.l);\n   zz_pX P1(INIT_SIZE, n);\n\n   long len;\n   if (zz_p::IsFFTPrime()) \n      len = n;\n   else\n      len = 1L << F.k;\n\n   TofftRep_trunc(R1, a, k, max(1L << F.k, d));\n   mul(R1, R1, R1);\n   NDFromfftRep(P1, R1, n, d-1, R2); // save R1 for future use\n\n   TofftRep_trunc(R2, P1, F.l, 2*n-3);\n   mul(R2, R2, F.HRep);\n   FromfftRep(P1, R2, n-2, 2*n-4);\n\n   TofftRep_trunc(R2, P1, F.k, len);\n   mul(R2, R2, F.FRep);\n   reduce(R1, R1, F.k);\n   sub(R1, R1, R2);\n   FromfftRep(x, R1, 0, n-1);\n}\n\nvoid PlainInvTrunc(zz_pX& x, const zz_pX& a, long m)\n\n   /* x = (1/a) % X^m, input not output, constant term a is nonzero */\n\n{\n   long i, k, n, lb;\n   zz_p v, t;\n   zz_p s;\n   const zz_p* ap;\n   zz_p* xp;\n   \n\n   n = deg(a);\n\n   if (n < 0) ArithmeticError(\"division by zero\");\n\n   inv(s, ConstTerm(a));\n\n   if (n == 0) {\n      conv(x, s);\n      return;\n   }\n\n   ap = a.rep.elts();\n   x.rep.SetLength(m);\n   xp = x.rep.elts();\n\n   xp[0] = s;\n\n   long is_one = IsOne(s);\n\n   for (k = 1; k < m; k++) {\n      clear(v);\n      lb = max(k-n, 0);\n      for (i = lb; i <= k-1; i++) {\n         mul(t, xp[i], ap[k-i]);\n         add(v, v, t);\n      }\n      xp[k] = v;\n      negate(xp[k], xp[k]);\n      if (!is_one) mul(xp[k], xp[k], s);\n   }\n\n   x.normalize();\n}\n\n\nvoid trunc(zz_pX& x, const zz_pX& a, long m)\n\n// x = a % X^m, output may alias input \n\n{\n   if (m < 0) LogicError(\"trunc: bad args\");\n\n   if (&x == &a) {\n      if (x.rep.length() > m) {\n         x.rep.SetLength(m);\n         x.normalize();\n      }\n   }\n   else {\n      long n;\n      long i;\n      zz_p* xp;\n      const zz_p* ap;\n\n      n = min(a.rep.length(), m);\n      x.rep.SetLength(n);\n\n      xp = x.rep.elts();\n      ap = a.rep.elts();\n\n      for (i = 0; i < n; i++) xp[i] = ap[i];\n\n      x.normalize();\n   }\n}\n\nvoid CyclicReduce(zz_pX& x, const zz_pX& a, long m)\n\n// computes x = a mod X^m-1\n\n{\n   long n = deg(a);\n   long i, j;\n   long accum;\n   long p = zz_p::modulus();\n\n   if (n < m) {\n      x = a;\n      return;\n   }\n\n   if (&x != &a)\n      x.rep.SetLength(m);\n\n   for (i = 0; i < m; i++) {\n      accum = rep(a.rep[i]);\n      for (j = i + m; j <= n; j += m)\n         accum = AddMod(accum, rep(a.rep[j]), p);\n      x.rep[i].LoopHole() = accum;\n   }\n\n   if (&x == &a)\n      x.rep.SetLength(m);\n\n   x.normalize();\n}\n\n\n\nvoid InvTrunc(zz_pX& x, const zz_pX& a, long m)\n{\n   if (m < 0) LogicError(\"InvTrunc: bad args\");\n   if (m == 0) {\n      clear(x);\n      return;\n   }\n\n   if (NTL_OVERFLOW(m, 1, 0))\n      ResourceError(\"overflow in InvTrunc\");\n\n   if (&x == &a) {\n      zz_pX la;\n      la = a;\n      if (m > NTL_zz_pX_NEWTON_CROSSOVER && deg(a) > 0)\n         NewtonInvTrunc(x, la, m);\n      else\n         PlainInvTrunc(x, la, m);\n   }\n   else {\n      if (m > NTL_zz_pX_NEWTON_CROSSOVER && deg(a) > 0)\n         NewtonInvTrunc(x, a, m);\n      else\n         PlainInvTrunc(x, a, m);\n   }\n}\n   \n\n\nvoid build(zz_pXModulus& x, const zz_pX& f)\n{\n   x.f = f;\n   x.n = deg(f);\n\n   x.tracevec.make();\n\n   if (x.n <= 0)\n      LogicError(\"build: deg(f) must be at least 1\");\n\n   if (x.n <= NTL_zz_pX_MOD_CROSSOVER + 1) {\n      x.UseFFT = 0;\n      return;\n   }\n\n   x.UseFFT = 1;\n\n   x.k = NextPowerOfTwo(x.n);\n   x.l = NextPowerOfTwo(2*x.n - 3);\n   TofftRep(x.FRep, f, x.k);\n\n   zz_pX P1(INIT_SIZE, x.n+1), P2(INIT_SIZE, x.n);\n\n   CopyReverse(P1, f, 0, x.n);\n   InvTrunc(P2, P1, x.n-1);\n\n   CopyReverse(P1, P2, 0, x.n-2);\n   TofftRep(x.HRep, P1, x.l);\n}\n\nzz_pXModulus::zz_pXModulus(const zz_pX& ff)\n{\n   build(*this, ff);\n}\n\nzz_pXMultiplier::zz_pXMultiplier(const zz_pX& b, const zz_pXModulus& F)\n{\n   build(*this, b, F);\n}\n\n\n\nvoid build(zz_pXMultiplier& x, const zz_pX& b, \n                         const zz_pXModulus& F)\n{\n   long db;\n   long n = F.n;\n\n   if (n < 0) LogicError(\"build zz_pXMultiplier: uninitialized modulus\"); \n\n   x.b = b;\n   db = deg(b);\n\n   if (db >= n) LogicError(\"build zz_pXMultiplier: deg(b) >= deg(f)\");\n\n   if (!F.UseFFT || db <= NTL_zz_pX_MOD_CROSSOVER) {\n      x.UseFFT = 0;\n      return;\n   }\n\n   x.UseFFT = 1;\n\n   fftRep R1(INIT_SIZE, F.l);\n   zz_pX P1(INIT_SIZE, n);\n   \n\n   TofftRep_trunc(R1, b, F.l, 2*n-2);\n   reduce(x.B2, R1, F.k);\n   mul(R1, R1, F.HRep);\n   FromfftRep(P1, R1, n-1, 2*n-3); \n\n   TofftRep(x.B1, P1, F.l);\n   // could be truncated to length max(1L << F.k, 2*n-2), except\n   // for the usage in UpdateMap, where we would have to investigate\n   // further\n\n}\n\n\nvoid MulMod(zz_pX& x, const zz_pX& a, const zz_pXMultiplier& B,\n                                      const zz_pXModulus& F)\n{\n\n   long n = F.n;\n   long da;\n\n   da = deg(a);\n\n   if (da >= n)\n      LogicError(\" bad args to MulMod(zz_pX,zz_pX,zz_pXMultiplier,zz_pXModulus)\");\n\n   if (da < 0) {\n      clear(x);\n      return;\n   }\n\n   if (!B.UseFFT || !F.UseFFT || da <= NTL_zz_pX_MOD_CROSSOVER) {\n      zz_pX P1;\n      mul(P1, a, B.b);\n      rem(x, P1, F);\n      return;\n   }\n\n   zz_pX P1(INIT_SIZE, n), P2(INIT_SIZE, n);\n   fftRep R1(INIT_SIZE, F.l), R2(INIT_SIZE, F.l);\n\n   long len;\n   if (zz_p::IsFFTPrime()) \n      len = n;\n   else\n      len = 1L << F.k;\n\n   TofftRep_trunc(R1, a, F.l, max(1L << F.k, 2*n-2));\n   mul(R2, R1, B.B1);\n   FromfftRep(P1, R2, n-1, 2*n-3);\n\n   reduce(R1, R1, F.k);\n   mul(R1, R1, B.B2);\n   TofftRep_trunc(R2, P1, F.k, len);\n   mul(R2, R2, F.FRep);\n   sub(R1, R1, R2);\n\n   FromfftRep(x, R1, 0, n-1);\n}\n   \n\nvoid PowerXMod(zz_pX& hh, const ZZ& e, const zz_pXModulus& F)\n{\n   if (F.n < 0) LogicError(\"PowerXMod: uninitialized modulus\");\n\n   if (IsZero(e)) {\n      set(hh);\n      return;\n   }\n\n   long n = NumBits(e);\n   long i;\n\n   zz_pX h;\n\n   h.SetMaxLength(F.n);\n   set(h);\n\n   for (i = n - 1; i >= 0; i--) {\n      SqrMod(h, h, F);\n      if (bit(e, i))\n         MulByXMod(h, h, F.f);\n   }\n\n   if (e < 0) InvMod(h, h, F);\n\n   hh = h;\n}\n\n\n\nvoid PowerXPlusAMod(zz_pX& hh, zz_p a, const ZZ& e, const zz_pXModulus& F)\n{\n   if (F.n < 0) LogicError(\"PowerXPlusAMod: uninitialized modulus\");\n\n   if (IsZero(e)) {\n      set(hh);\n      return;\n   }\n\n   zz_pX t1(INIT_SIZE, F.n), t2(INIT_SIZE, F.n);\n   long n = NumBits(e);\n   long i;\n\n   zz_pX h;\n\n   h.SetMaxLength(F.n);\n   set(h);\n\n   for (i = n - 1; i >= 0; i--) {\n      SqrMod(h, h, F);\n      if (bit(e, i)) {\n         MulByXMod(t1, h, F.f);\n         mul(t2, h, a);\n         add(h, t1, t2);\n      }\n   }\n\n   if (e < 0) InvMod(h, h, F);\n\n   hh = h;\n}\n\n\n\nvoid PowerMod(zz_pX& h, const zz_pX& g, const ZZ& e, const zz_pXModulus& F)\n{\n   if (deg(g) >= F.n) LogicError(\"PowerMod: bad args\");\n\n   if (IsZero(e)) {\n      set(h);\n      return;\n   }\n\n   zz_pXMultiplier G;\n\n   zz_pX res;\n\n   long n = NumBits(e);\n   long i;\n\n   build(G, g, F);\n\n   res.SetMaxLength(F.n);\n   set(res);\n\n   for (i = n - 1; i >= 0; i--) {\n      SqrMod(res, res, F);\n      if (bit(e, i))\n         MulMod(res, res, G, F);\n   }\n\n   if (e < 0) InvMod(res, res, F);\n\n   h = res;\n}\n\n\nvoid NewtonInvTrunc(zz_pX& x, const zz_pX& a, long m)\n{\n   x.SetMaxLength(m);\n\n   long i;\n   long t;\n\n\n   t = NextPowerOfTwo(2*m-1);\n\n   fftRep R1(INIT_SIZE, t), R2(INIT_SIZE, t);\n   zz_pX P1(INIT_SIZE, m);\n\n   long log2_newton = NextPowerOfTwo(NTL_zz_pX_NEWTON_CROSSOVER)-1;\n\n   PlainInvTrunc(x, a, 1L << log2_newton);\n   long k = 1L << log2_newton;\n   long a_len = min(m, a.rep.length());\n\n   while (k < m) {\n      long l = min(2*k, m);\n\n      t = NextPowerOfTwo(2*k);\n      TofftRep(R1, x, t);\n      mul(R1, R1, R1);\n      FromfftRep(P1, R1, 0, l-1);\n\n      t = NextPowerOfTwo(deg(P1) + min(l, a_len));\n      TofftRep(R1, P1, t);\n      TofftRep(R2, a, t, 0, min(l, a_len)-1);\n      mul(R1, R1, R2);\n      FromfftRep(P1, R1, k, l-1);\n      \n      x.rep.SetLength(l);\n      long y_len = P1.rep.length();\n      for (i = k; i < l; i++) {\n         if (i-k >= y_len)\n            clear(x.rep[i]);\n         else\n            negate(x.rep[i], P1.rep[i-k]);\n      }\n      x.normalize();\n\n      k = l;\n   }\n}\n\n\n\n\nvoid FFTDivRem(zz_pX& q, zz_pX& r, const zz_pX& a, const zz_pX& b)\n{\n   long n = deg(b);\n   long m = deg(a);\n   long k, l;\n\n   if (m < n) {\n      clear(q);\n      r = a;\n      return;\n   }\n\n   if (m >= 3*n) {\n      zz_pXModulus B;\n      build(B, b);\n      DivRem(q, r, a, B);\n      return;\n   }\n\n   zz_pX P1, P2, P3;\n\n   CopyReverse(P3, b, 0, n);\n   InvTrunc(P2, P3, m-n+1);\n   CopyReverse(P1, P2, 0, m-n);\n\n   k = NextPowerOfTwo(2*(m-n)+1);\n   long k1 = NextPowerOfTwo(n);\n   long mx = max(k1, k);\n\n   fftRep R1(INIT_SIZE, mx), R2(INIT_SIZE, mx);\n\n   TofftRep(R1, P1, k);\n   TofftRep(R2, a, k, n, m);\n   mul(R1, R1, R2);\n   FromfftRep(P3, R1, m-n, 2*(m-n));\n   \n   l = 1L << k1;\n\n   \n   TofftRep(R1, b, k1);\n   TofftRep(R2, P3, k1);\n   mul(R1, R1, R2);\n   FromfftRep(P1, R1, 0, n-1);\n   CyclicReduce(P2, a, l);\n   trunc(r, P2, n);\n   sub(r, r, P1);\n   q = P3;\n}\n\n\n\n\nvoid FFTDiv(zz_pX& q, const zz_pX& a, const zz_pX& b)\n{\n\n   long n = deg(b);\n   long m = deg(a);\n   long k;\n\n   if (m < n) {\n      clear(q);\n      return;\n   }\n\n   if (m >= 3*n) {\n      zz_pXModulus B;\n      build(B, b);\n      div(q, a, B);\n      return;\n   }\n\n   zz_pX P1, P2, P3;\n\n   CopyReverse(P3, b, 0, n);\n   InvTrunc(P2, P3, m-n+1);\n   CopyReverse(P1, P2, 0, m-n);\n\n   k = NextPowerOfTwo(2*(m-n)+1);\n\n   fftRep R1(INIT_SIZE, k), R2(INIT_SIZE, k);\n\n   TofftRep(R1, P1, k);\n   TofftRep(R2, a, k, n, m);\n   mul(R1, R1, R2);\n   FromfftRep(q, R1, m-n, 2*(m-n));\n}\n\n\n\nvoid FFTRem(zz_pX& r, const zz_pX& a, const zz_pX& b)\n{\n   long n = deg(b);\n   long m = deg(a);\n   long k, l;\n\n   if (m < n) {\n      r = a;\n      return;\n   }\n\n   if (m >= 3*n) {\n      zz_pXModulus B;\n      build(B, b);\n      rem(r, a, B);\n      return;\n   }\n\n   zz_pX P1, P2, P3;\n\n   CopyReverse(P3, b, 0, n);\n   InvTrunc(P2, P3, m-n+1);\n   CopyReverse(P1, P2, 0, m-n);\n\n   k = NextPowerOfTwo(2*(m-n)+1);\n   long k1 = NextPowerOfTwo(n);\n   long mx = max(k, k1);\n\n   fftRep R1(INIT_SIZE, mx), R2(INIT_SIZE, mx);\n\n   TofftRep(R1, P1, k);\n   TofftRep(R2, a, k, n, m);\n   mul(R1, R1, R2);\n   FromfftRep(P3, R1, m-n, 2*(m-n));\n   \n   l = 1L << k1;\n\n   \n   TofftRep(R1, b, k1);\n   TofftRep(R2, P3, k1);\n   mul(R1, R1, R2);\n   FromfftRep(P3, R1, 0, n-1);\n   CyclicReduce(P2, a, l);\n   trunc(r, P2, n);\n   sub(r, r, P3);\n}\n\n\nvoid DivRem(zz_pX& q, zz_pX& r, const zz_pX& a, const zz_pX& b)\n{\n   if (deg(b) > NTL_zz_pX_DIV_CROSSOVER && deg(a) - deg(b) > NTL_zz_pX_DIV_CROSSOVER)\n      FFTDivRem(q, r, a, b);\n   else\n      PlainDivRem(q, r, a, b);\n}\n\nvoid div(zz_pX& q, const zz_pX& a, const zz_pX& b)\n{\n   if (deg(b) > NTL_zz_pX_DIV_CROSSOVER && deg(a) - deg(b) > NTL_zz_pX_DIV_CROSSOVER)\n      FFTDiv(q, a, b);\n   else\n      PlainDiv(q, a, b);\n}\n\nvoid div(zz_pX& q, const zz_pX& a, zz_p b)\n{\n   zz_p t;\n   inv(t, b);\n   mul(q, a, t);\n}\n\n\nvoid rem(zz_pX& r, const zz_pX& a, const zz_pX& b)\n{\n   if (deg(b) > NTL_zz_pX_DIV_CROSSOVER && deg(a) - deg(b) > NTL_zz_pX_DIV_CROSSOVER)\n      FFTRem(r, a, b);\n   else\n      PlainRem(r, a, b);\n}\n\n\n\nlong operator==(const zz_pX& a, long b)\n{\n   if (b == 0)\n      return IsZero(a);\n\n   if (b == 1)\n      return IsOne(a);\n\n   long da = deg(a);\n\n   if (da > 0)\n      return 0;\n\n   zz_p bb;\n   bb = b;\n\n   if (da < 0)\n      return IsZero(bb);\n\n   return a.rep[0] == bb;\n}\n\nlong operator==(const zz_pX& a, zz_p b)\n{\n   if (IsZero(b))\n      return IsZero(a);\n\n   long da = deg(a);\n\n   if (da != 0)\n      return 0;\n\n   return a.rep[0] == b;\n}\n\nvoid power(zz_pX& x, const zz_pX& a, long e)\n{\n   if (e < 0) {\n      ArithmeticError(\"power: negative exponent\");\n   }\n\n   if (e == 0) {\n      x = 1;\n      return;\n   }\n\n   if (a == 0 || a == 1) {\n      x = a;\n      return;\n   }\n\n   long da = deg(a);\n\n   if (da == 0) {\n      x = power(ConstTerm(a), e);\n      return;\n   }\n\n   if (da > (NTL_MAX_LONG-1)/e)\n      ResourceError(\"overflow in power\");\n\n   zz_pX res;\n   res.SetMaxLength(da*e + 1);\n   res = 1;\n   \n   long k = NumBits(e);\n   long i;\n\n   for (i = k - 1; i >= 0; i--) {\n      sqr(res, res);\n      if (bit(e, i))\n         mul(res, res, a);\n   }\n\n   x = res;\n}\n\nvoid reverse(zz_pX& x, const zz_pX& a, long hi)\n{\n   if (hi < 0) { clear(x); return; }\n   if (NTL_OVERFLOW(hi, 1, 0))\n      ResourceError(\"overflow in reverse\");\n\n   if (&x == &a) {\n      zz_pX tmp;\n      CopyReverse(tmp, a, 0, hi);\n      x = tmp;\n   }\n   else\n      CopyReverse(x, a, 0, hi);\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "a1b612ed895dc81fc2b18b5b0bc787d833dc43ba", "size": 64080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/NTL/src/lzz_pX.cpp", "max_stars_repo_name": "manel1874/libscapi", "max_stars_repo_head_hexsha": "8cf705162af170c04c8e2299213f52888193cabe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 160.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T09:32:19.000Z", "max_issues_repo_path": "src/lzz_pX.cpp", "max_issues_repo_name": "LittleNewton/Discrete_Logarithm", "max_issues_repo_head_hexsha": "28721af6db022e0e9f0b426fb3bf861d13de1592", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2016-12-26T07:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T16:34:31.000Z", "max_forks_repo_path": "lib/NTL/src/lzz_pX.cpp", "max_forks_repo_name": "manel1874/libscapi", "max_forks_repo_head_hexsha": "8cf705162af170c04c8e2299213f52888193cabe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2016-10-10T17:56:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:56:39.000Z", "avg_line_length": 18.981042654, "max_line_length": 112, "alphanum_fraction": 0.4905586767, "num_tokens": 24124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.4321177064387959}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#include <boost/hana/ext/std/utility.hpp>\n#include <boost/hana/maybe.hpp>\n#include <boost/hana/tuple.hpp>\n#include <boost/hana/type.hpp>\n\n#include <type_traits>\nusing namespace boost::hana;\n\n\n//! [foldlM]\nauto builtin_common_t = sfinae([](auto t, auto u) -> decltype(type<\n    std::decay_t<decltype(true ? traits::declval(t) : traits::declval(u))>\n>) { return {}; });\n\ntemplate <typename ...T>\nstruct common_type { };\n\ntemplate <typename T, typename U>\nstruct common_type<T, U>\n    : std::conditional_t<std::is_same<std::decay_t<T>, T>{} &&\n                         std::is_same<std::decay_t<U>, U>{},\n        decltype(builtin_common_t(type<T>, type<U>)),\n        common_type<std::decay_t<T>, std::decay_t<U>>\n    >\n{ };\n\ntemplate <typename T1, typename ...Tn>\nstruct common_type<T1, Tn...>\n    : decltype(foldlM<Maybe>(tuple_t<Tn...>,\n                             type<std::decay_t<T1>>,\n                             sfinae(metafunction<common_type>)))\n{ };\n\ntemplate <typename ...Ts>\nusing common_type_t = typename common_type<Ts...>::type;\n\nstatic_assert(std::is_same<\n    common_type_t<char, short, char, short>, int>{}\n, \"\");\n\nstatic_assert(std::is_same<\n    common_type_t<char, double, short, char, short, double>, double>{}\n, \"\");\n\nstatic_assert(std::is_same<\n    common_type_t<char, short, float, short>, float\n>{}, \"\");\n\nstatic_assert(\n    sfinae(metafunction<common_type>)(type<int>, type<int>, type<int*>) == nothing\n, \"\");\n//! [foldlM]\n\nint main() { }\n", "meta": {"hexsha": "367ad45a9e4386dc523b6d90446cb6a77a804cc7", "size": 1639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/foldable.foldlM.cpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/foldable.foldlM.cpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/foldable.foldlM.cpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.868852459, "max_line_length": 82, "alphanum_fraction": 0.6400244051, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.43211769877709383}}
{"text": "#include \"cnn/math.h\"\n\n#include <random>\n#include <vector>\n#include <cstring>\n#include <boost/random/discrete_distribution.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\n#if HAVE_CUDA\n#include \"cnn/cuda.h\"\n#endif\n\nusing namespace std;\n\nnamespace cnn {\n\n    extern mt19937* rndeng;\n\n    boost::mt19937 boost_rand_gen;\n\n    cnn::real rand01() {\n      uniform_real_distribution<cnn::real> distribution(0, 1);\n      return distribution(*rndeng);\n    }\n\n    int rand0n(int n) {\n      assert(n > 0);\n      int x = rand01() * n;\n      while(n == x) { x = rand01() * n; }\n      return x;\n    }\n\n    cnn::real rand_normal() {\n      normal_distribution<cnn::real> distribution(0, 1);\n      return distribution(*rndeng);\n    }\n\n    int rand0n_uniform(int n)\n    {\n        assert(n > 0);\n        uniform_int_distribution<> distribution(0, n);\n        return distribution(*rndeng);\n    }\n\n    std::vector<int> rand0n_uniform(int vecsize, int n_exclusive)\n    {\n        std::vector<int> res(vecsize);\n        for (int i = 0; i < vecsize; i++)\n            res[i] = rand0n_uniform(n_exclusive);\n\n        return res;\n    }\n\n    std::vector<int> rand0n_uniform(int vecsize, int n_exclusive, const std::vector<cnn::real>& sample_dist)\n    {\n        std::vector<int> res(vecsize);\n        boost::random::discrete_distribution<int> d(sample_dist.begin(), sample_dist.end());\n        for (int i = 0; i < vecsize; i++)\n            res[i] = d(*rndeng);\n\n        return res;\n    }\n\n    int sample_accoding_to_distribution_of(const vector<cnn::real>& probabilities)\n    {\n        std::vector<cnn::real> cumulative;\n        int sz = probabilities.size();\n        std::partial_sum(&probabilities[0], &probabilities[0] + sz,\n            std::back_inserter(cumulative));\n        boost::uniform_real<> dist(0, cumulative.back());\n        boost::variate_generator<boost::mt19937&, boost::uniform_real<> > die(boost_rand_gen, dist);\n        return (std::lower_bound(cumulative.begin(), cumulative.end(), die()) - cumulative.begin());\n    }\n} // namespace cnn\n", "meta": {"hexsha": "9860b04e14722a54742c3b8ba8b8ae1e53891ebb", "size": 2117, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cnn/math.cc", "max_stars_repo_name": "kaishengyao/cnn", "max_stars_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-09-10T07:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-17T03:02:38.000Z", "max_issues_repo_path": "cnn/math.cc", "max_issues_repo_name": "kaishengyao/cnn", "max_issues_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cnn/math.cc", "max_forks_repo_name": "kaishengyao/cnn", "max_forks_repo_head_hexsha": "a034b837e88f82bd8adf2c5b0a5defb26fd52096", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-09-08T12:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-26T07:32:47.000Z", "avg_line_length": 27.4935064935, "max_line_length": 108, "alphanum_fraction": 0.6263580538, "num_tokens": 541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4320673256650652}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n\n#include \"Utils/GeometricDerivatives/NormalModeAnalysis.h\"\n#include \"Utils/Constants.h\"\n#include \"Utils/GeometricDerivatives/HessianUtilities.h\"\n#include \"Utils/GeometricDerivatives/NormalMode.h\"\n#include \"Utils/GeometricDerivatives/NormalModesContainer.h\"\n#include <Eigen/Core>\n#include <vector>\n\nnamespace Scine {\nnamespace Utils {\nnamespace NormalModeAnalysis {\n\ninline NormalModesContainer calculate(HessianUtilities& diagonalizer, int nAtoms) {\n  Eigen::VectorXd eigenvalues = diagonalizer.getInternalEigenvalues();\n  Eigen::MatrixXd cartesianDisplacements = diagonalizer.getBackTransformedInternalEigenvectors();\n\n  NormalModesContainer modesContainer;\n  DisplacementCollection dc(nAtoms, 3);\n  for (int i = 0; i < cartesianDisplacements.cols(); ++i) {\n    for (int j = 0; j < nAtoms; ++j) {\n      dc.row(j) = cartesianDisplacements.col(i).segment(3 * j, 3);\n    }\n\n    double freq = getWaveNumber(eigenvalues[i]);\n    NormalMode m(freq, dc);\n    modesContainer.add(std::move(m));\n  }\n  return modesContainer;\n}\n\nNormalModesContainer calculateNormalModes(const HessianMatrix& hessian, const AtomCollection& atoms) {\n  return calculateNormalModes(hessian, atoms.getElements(), atoms.getPositions());\n}\n\nNormalModesContainer calculateNormalModes(const HessianMatrix& hessian, const ElementTypeCollection& elements,\n                                          const PositionCollection& positions) {\n  int nAtoms = elements.size();\n\n  HessianUtilities diagonalizer(hessian, elements, positions, true);\n\n  return calculate(diagonalizer, nAtoms);\n}\n\nNormalModesContainer calculateOrthogonalNormalModes(const HessianMatrix& hessian, const ElementTypeCollection& elements,\n                                                    const PositionCollection& positions, const GradientCollection& gradient) {\n  assert(gradient.size() == hessian.rows() && \"Gradient dimension and hessian dimension do not match! (must be 3*N)\");\n  int nAtoms = elements.size();\n\n  HessianUtilities diagonalizer(hessian, elements, positions, gradient, true);\n\n  return calculate(diagonalizer, nAtoms);\n}\n\ndouble getWaveNumber(double value) {\n  double f1 = Constants::invCentimeter_per_hartree * sqrt(Constants::u_per_electronRestMass); // for conversion to cm^-1\n  double f2 = value < 0 ? -1 : 1; // for imaginary frequencies, will be shown as negative frequencies\n\n  return f1 * f2 * std::sqrt(f2 * value);\n}\n\n} // namespace NormalModeAnalysis\n} // namespace Utils\n} // namespace Scine\n", "meta": {"hexsha": "f3ea5798bbcf42573d3bc31f8edfff877f311a8c", "size": 2672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/GeometricDerivatives/NormalModeAnalysis.cpp", "max_stars_repo_name": "qcscine/utilities", "max_stars_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Utils/GeometricDerivatives/NormalModeAnalysis.cpp", "max_issues_repo_name": "qcscine/utilities", "max_issues_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-19T14:34:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:07:18.000Z", "max_forks_repo_path": "src/Utils/Utils/GeometricDerivatives/NormalModeAnalysis.cpp", "max_forks_repo_name": "qcscine/utilities", "max_forks_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T16:44:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T20:48:19.000Z", "avg_line_length": 37.6338028169, "max_line_length": 126, "alphanum_fraction": 0.7320359281, "num_tokens": 607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4320673256650652}}
{"text": "#ifndef SKYLARK_QRLT_DATA_HPP\n#define SKYLARK_QRLT_DATA_HPP\n\n#ifndef SKYLARK_SKETCH_HPP\n#error \"Include top-level sketch.hpp instead of including individuals headers\"\n#endif\n\n#include <boost/math/special_functions/erf.hpp>\n#include <vector>\n\nnamespace skylark { namespace sketch {\n\n\n/**\n * Random Laplace Transform (data)\n *\n * Sketch transform into Eucledian space of fuctions in an RKHS\n * implicitly defined by a vector and a semigroup kernel.\n *\n * Use quasi-random features.\n *\n * See:\n *\n * Jiyan Yang, Vikas Sindhwani, Quanfu Fan, Haim Avron, Michael Mahoney\n * Random Laplace Feature Maps for Semigroup Kernels on Histograms\n * CVPR 2014\n *\n * Yang, Sindhawni, Avron and Mahoney\n * Quasi-Monte Carlo Feature Maps for Shift-Invariant Kernels\n * ICML 2014\n *\n */\ntemplate <template <typename, typename> class KernelDistribution,\n          template <typename> class QMCSequenceType>\nstruct QRLT_data_t : public sketch_transform_data_t {\n\n    typedef double value_type;\n    typedef quasi_dense_transform_data_t<KernelDistribution, QMCSequenceType>\n    underlying_data_type;\n    typedef QMCSequenceType<value_type> sequence_type;\n    typedef sketch_transform_data_t base_t;\n\n    static size_t qmc_sequence_dim(size_t N)  { return N; }\n\n    QRLT_data_t (int N, int S, double inscale, double outscale,\n        const sequence_type& sequence, int skip,  base::context_t& context)\n        : base_t(N, S, context, \"QRLT\"), _inscale(inscale),\n          _outscale(outscale), _sequence(sequence), _skip(skip) {\n\n        context = build();\n    }\n\n    /**\n     *  Serializes a sketch to a string.\n     *\n     *  @return property_tree describing the sketch.\n     */\n    virtual boost::property_tree::ptree to_ptree() const {\n        SKYLARK_THROW_EXCEPTION (\n          base::sketch_exception()\n              << base::error_msg(\n                 \"Do not yet support serialization of generic QRLT transform\"));\n\n        return boost::property_tree::ptree();\n    }\n\n    virtual sketch_transform_t<boost::any, boost::any> *get_transform() const {\n        SKYLARK_THROW_EXCEPTION (\n          base::sketch_exception()\n              << base::error_msg(\n                 \"Trying to create concrete transform of QRLT_data_t\"));\n\n        return nullptr;\n    }\n\nprotected:\n\n    typedef typename underlying_data_type::value_accessor_type accessor_type;\n\n\n    QRLT_data_t (int N, int S, double inscale, double outscale,\n        const sequence_type& sequence, int skip,\n        const base::context_t& context, std::string type)\n        : base_t(N, S, context, type), _inscale(inscale),\n          _outscale(outscale), _sequence(sequence), _skip(skip) {\n\n    }\n\n   base::context_t build() {\n       base::context_t ctx = base_t::build();\n       _underlying_data = boost::shared_ptr<underlying_data_type>(new\n           underlying_data_type(base_t::_N, base_t::_S, _inscale,\n               _sequence, _skip, ctx));\n       return ctx;\n   }\n\n    double _inscale;\n    double _outscale; /** Scaling for exponential factor */\n    boost::shared_ptr<underlying_data_type> _underlying_data;\n    /**< Data of the underlying dense transformation */\n    sequence_type _sequence;\n    const int _skip;\n};\n\nnamespace internal {\n\n// There is no boost::math class for levy's distribution.\n// However, we need only the quantile function, which\n// we implement in this skeleton.\n\ntemplate <class ValueType = double,\n          class Policy = boost::math::policies::policy<> >\nstruct levy_distribution_t\n{\n    typedef ValueType value_type;\n    typedef Policy policy_type;\n\n    levy_distribution_t(value_type mean = 0, value_type scale = 1)\n        : _mean(mean), _scale(scale) {\n\n    }\n\n    value_type get_mean() const {\n        return _mean;\n    }\n\n    value_type get_scale() const {\n        return _scale;\n    }\n\nprivate:\n    value_type _mean;\n    value_type _scale;\n};\n\n// I have no idea how the compiler/boost finds this function!\n// It works on my machine, but I hope it will not break in others...\ntemplate <class RealType, class Policy>\ninline RealType quantile(const internal::levy_distribution_t<RealType,\n    Policy>& dist,\n    const RealType& p) {\n    RealType v = boost::math::erfc_inv(p, Policy());\n    return dist.get_scale() / (2 * v * v) + dist.get_mean();\n}\n\n}\n\n/**\n * Quasi Random Features for Exponential Semigroup\n */\ntemplate<template <typename> class QMCSequenceType>\nstruct ExpSemigroupQRLT_data_t :\n        public QRLT_data_t<internal::levy_distribution_t,\n                           QMCSequenceType> {\n\n    typedef QRLT_data_t<internal::levy_distribution_t,\n                        QMCSequenceType> base_t;\n\n    typedef typename base_t::sequence_type sequence_type;\n\n    /// Params structure\n    struct params_t : public sketch_params_t {\n\n        params_t(double beta, const sequence_type& sequence, int skip) :\n            beta(beta), sequence(sequence), skip(skip) {\n\n        }\n\n        const double beta;\n        const sequence_type sequence;\n        const int skip;\n    };\n\n    ExpSemigroupQRLT_data_t(int N, int S, double beta,\n        const sequence_type& sequence, int skip,\n        base::context_t& context)\n        : base_t(N, S, beta * beta / 2, std::sqrt(1.0 / S),\n            sequence, skip, context, \"ExpSemigroupQRLT\"),\n          _beta(beta), _sequence(sequence), _skip(skip) {\n\n        context = base_t::build();\n    }\n\n    ExpSemigroupQRLT_data_t(int N, int S, const params_t& params,\n        base::context_t& context)\n        : base_t(N, S, params.beta * params.beta / 2, std::sqrt(1.0 / S),\n            params.sequence, params.skip, context, \"ExpSemigroupQRLT\"),\n          _beta(params.beta), _sequence(params.sequence),\n          _skip(params.skip) {\n\n        context = base_t::build();\n    }\n\n    ExpSemigroupQRLT_data_t(const boost::property_tree::ptree &pt) :\n        base_t(pt.get<int>(\"N\"), pt.get<int>(\"S\"),\n            pt.get<double>(\"beta\") * pt.get<double>(\"beta\") / 2,\n            std::sqrt(1.0 / pt.get<double>(\"S\")),\n            sequence_type(pt.get_child(\"sequence\")), pt.get<int>(\"skip\"),\n            base::context_t(pt.get_child(\"creation_context\")), \"ExpSemiGroupQRLT\"),\n        _beta(pt.get<double>(\"beta\")),\n        _sequence(pt.get_child(\"sequence\")),  _skip(pt.get<int>(\"skip\")) {\n\n        base_t::build();\n    }\n\n    /**\n     *  Serializes a sketch to a string.\n     *\n     *  @return property_tree describing the sketch.\n     */\n    virtual boost::property_tree::ptree to_ptree() const {\n        boost::property_tree::ptree pt;\n        sketch_transform_data_t::add_common(pt);\n        pt.put_child(\"sequence\", _sequence.to_ptree());\n        pt.put(\"beta\", _beta);\n        pt.put(\"skip\", _skip);\n        return pt;\n    }\n\n    /**\n     * Get a concrete sketch transform based on the data\n     */\n    virtual sketch_transform_t<boost::any, boost::any> *get_transform() const;\n\nprotected:\n    ExpSemigroupQRLT_data_t(int N, int S, double beta,\n        const sequence_type& sequence, int skip,\n        const skylark::base::context_t& context, std::string type)\n        : base_t(N, S,  beta * beta / 2, std::sqrt(1.0 / S), context, type),\n          _beta(beta), _sequence(sequence), _skip(skip) {\n\n    }\n\n\nprivate:\n    const double _beta;\n    const sequence_type _sequence;\n    const int _skip;\n};\n\n} } /** namespace skylark::sketch */\n\n#endif /** SKYLARK_QRLT_DATA_HPP */\n", "meta": {"hexsha": "4307ff383b283ee2f2572f7dcdd88bc7a68a3e32", "size": 7287, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sketch/QRLT_data.hpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "sketch/QRLT_data.hpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "sketch/QRLT_data.hpp", "max_forks_repo_name": "xdata-skylark/libskylark", "max_forks_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 29.8647540984, "max_line_length": 83, "alphanum_fraction": 0.6532180596, "num_tokens": 1788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.43200586688772463}}
{"text": "#ifndef _CELERITE2_INTERFACE_HPP_DEFINED_\n#define _CELERITE2_INTERFACE_HPP_DEFINED_\n\n#include <Eigen/Core>\n#include \"forward.hpp\"\n\nnamespace celerite2 {\nnamespace core {\n\n#define MakeEmptyWork(BaseType)                                                                                                                      \\\n  typedef typename BaseType::Scalar Scalar;                                                                                                          \\\n  typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Empty;                                                              \\\n  Empty\n\n/**\n * \\brief Compute the Cholesky factorization of the system\n *\n * This computes `d` and `W` such that:\n *\n * `diag(a) + tril(U*V^T) + triu(V*U^T) = L*diag(d)*L^T`\n *\n * where\n *\n * `L = 1 + tril(U*W^T)`\n *\n * This can be safely applied in place: `d_out` can point to `a` and `W_out` can\n * point to `V`, and the memory will be reused.\n *\n * @param t     (N,): The input coordinates (must be sorted)\n * @param c     (J,): The transport coefficients\n * @param a     (N,): The diagonal component\n * @param U     (N, J): The first low rank matrix\n * @param V     (N, J): The second low rank matrix\n * @param d_out (N,): The diagonal component of the Cholesky factor\n * @param W_out (N, J): The second low rank component of the Cholesky factor\n */\ntemplate <typename Input, typename Coeffs, typename Diag, typename LowRank, typename DiagOut, typename LowRankOut>\nEigen::Index factor(const Eigen::MatrixBase<Input> &t,         // (N,)\n                    const Eigen::MatrixBase<Coeffs> &c,        // (J,)\n                    const Eigen::MatrixBase<Diag> &a,          // (N,)\n                    const Eigen::MatrixBase<LowRank> &U,       // (N, J)\n                    const Eigen::MatrixBase<LowRank> &V,       // (N, J)\n                    Eigen::MatrixBase<DiagOut> const &d_out,   // (N,)\n                    Eigen::MatrixBase<LowRankOut> const &W_out // (N, J)\n) {\n  MakeEmptyWork(Diag) S;\n  return factor<false>(t, c, a, U, V, d_out, W_out, S);\n}\n\n/**\n * \\brief Compute the solution of a lower triangular linear equation\n *\n * This computes `Z` such that:\n *\n * `Y = L * Y`\n *\n * where\n *\n * `L = 1 + tril(U*W^T)`\n *\n * This can be safely applied in place.\n *\n * @param t     (N,): The input coordinates (must be sorted)\n * @param c     (J,): The transport coefficients\n * @param U     (N, J): The first low rank matrix\n * @param W     (N, J): The second low rank matrix\n * @param Y     (N, Nrhs): The right hand side\n * @param Z_out (N, Nrhs): The solution of this equation\n */\ntemplate <typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut>\nvoid solve_lower(const Eigen::MatrixBase<Input> &t,               // (N,)\n                 const Eigen::MatrixBase<Coeffs> &c,              // (J,)\n                 const Eigen::MatrixBase<LowRank> &U,             // (N, J)\n                 const Eigen::MatrixBase<LowRank> &W,             // (N, J)\n                 const Eigen::MatrixBase<RightHandSide> &Y,       // (N, nrhs)\n                 Eigen::MatrixBase<RightHandSideOut> const &Z_out // (N, nrhs)\n) {\n  MakeEmptyWork(Input) F;\n  solve_lower<false>(t, c, U, W, Y, Z_out, F);\n}\n\n/**\n * \\brief Compute the solution of a upper triangular linear equation\n *\n * This computes `Z` such that:\n *\n * `Y = L^T * Y`\n *\n * where\n *\n * `L = 1 + tril(U*W^T)`\n *\n * This can be safely applied in place.\n *\n * @param t     (N,): The input coordinates (must be sorted)\n * @param c     (J,): The transport coefficients\n * @param U     (N, J): The first low rank matrix\n * @param W     (N, J): The second low rank matrix\n * @param Y     (N, Nrhs): The right hand side\n * @param Z_out (N, Nrhs): The solution of this equation\n */\ntemplate <typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut>\nvoid solve_upper(const Eigen::MatrixBase<Input> &t,               // (N,)\n                 const Eigen::MatrixBase<Coeffs> &c,              // (J,)\n                 const Eigen::MatrixBase<LowRank> &U,             // (N, J)\n                 const Eigen::MatrixBase<LowRank> &W,             // (N, J)\n                 const Eigen::MatrixBase<RightHandSide> &Y,       // (N, nrhs)\n                 Eigen::MatrixBase<RightHandSideOut> const &Z_out // (N, nrhs)\n) {\n  MakeEmptyWork(Input) F;\n  solve_upper<false>(t, c, U, W, Y, Z_out, F);\n}\n\n/**\n * \\brief Apply a strictly lower matrix multiply\n *\n * This computes:\n *\n * `Z += tril(U * V^T) * Y`\n *\n * where `tril` is the strictly lower triangular function.\n *\n * Note that this will *update* the value of `Z`.\n *\n * @param t     (N,): The input coordinates (must be sorted)\n * @param c     (J,): The transport coefficients\n * @param U     (N, J): The first low rank matrix\n * @param V     (N, J): The second low rank matrix\n * @param Y     (N, Nrhs): The matrix to be multiplied\n * @param Z_out (N, Nrhs): The matrix to be updated\n */\ntemplate <typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut>\nvoid matmul_lower(const Eigen::MatrixBase<Input> &t,               // (N,)\n                  const Eigen::MatrixBase<Coeffs> &c,              // (J,)\n                  const Eigen::MatrixBase<LowRank> &U,             // (N, J)\n                  const Eigen::MatrixBase<LowRank> &V,             // (N, J)\n                  const Eigen::MatrixBase<RightHandSide> &Y,       // (N, nrhs)\n                  Eigen::MatrixBase<RightHandSideOut> const &Z_out // (N, nrhs)\n) {\n  MakeEmptyWork(Input) F;\n  matmul_lower<false>(t, c, U, V, Y, Z_out, F);\n}\n\n/**\n * \\brief Apply a strictly upper matrix multiply\n *\n * This computes:\n *\n * `Z += triu(V * U^T) * Y`\n *\n * where `triu` is the strictly lower triangular function.\n *\n * Note that this will *update* the value of `Z`.\n *\n * @param t     (N,): The input coordinates (must be sorted)\n * @param c     (J,): The transport coefficients\n * @param U     (N, J): The first low rank matrix\n * @param V     (N, J): The second low rank matrix\n * @param Y     (N, Nrhs): The matrix to be multiplied\n * @param Z_out (N, Nrhs): The matrix to be updated\n */\ntemplate <typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut>\nvoid matmul_upper(const Eigen::MatrixBase<Input> &t,               // (N,)\n                  const Eigen::MatrixBase<Coeffs> &c,              // (J,)\n                  const Eigen::MatrixBase<LowRank> &U,             // (N, J)\n                  const Eigen::MatrixBase<LowRank> &V,             // (N, J)\n                  const Eigen::MatrixBase<RightHandSide> &Y,       // (N, nrhs)\n                  Eigen::MatrixBase<RightHandSideOut> const &Z_out // (N, nrhs)\n) {\n  MakeEmptyWork(Input) F;\n  matmul_upper<false>(t, c, U, V, Y, Z_out, F);\n}\n\n/**\n * \\brief The general lower-triangular dot product of a rectangular celerite system\n *\n * @param t1     (N,): The left input coordinates (must be sorted)\n * @param t2     (M,): The right input coordinates (must be sorted)\n * @param c      (J,): The transport coefficients\n * @param U      (N, J): The first low rank matrix\n * @param V      (M, J): The second low rank matrix\n * @param Y      (M, Nrhs): The matrix that will be multiplied\n * @param Z_out  (N, Nrhs): The result of the operation\n */\ntemplate <typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut>\nvoid general_matmul_lower(const Eigen::MatrixBase<Input> &t1,              // (N,)\n                          const Eigen::MatrixBase<Input> &t2,              // (M,)\n                          const Eigen::MatrixBase<Coeffs> &c,              // (J,)\n                          const Eigen::MatrixBase<LowRank> &U,             // (N, J)\n                          const Eigen::MatrixBase<LowRank> &V,             // (M, J)\n                          const Eigen::MatrixBase<RightHandSide> &Y,       // (M, nrhs)\n                          Eigen::MatrixBase<RightHandSideOut> const &Z_out // (N, nrhs)\n) {\n  MakeEmptyWork(Input) F;\n  general_matmul_lower<false>(t1, t2, c, U, V, Y, Z_out, F);\n}\n\n/**\n * \\brief The general upper-triangular dot product of a rectangular celerite system\n *\n * @param t1     (N,): The left input coordinates (must be sorted)\n * @param t2     (M,): The right input coordinates (must be sorted)\n * @param c      (J,): The transport coefficients\n * @param U      (N, J): The first low rank matrix\n * @param V      (M, J): The second low rank matrix\n * @param Y      (M, Nrhs): The matrix that will be multiplied\n * @param Z_out  (N, Nrhs): The result of the operation\n */\ntemplate <typename Input, typename Coeffs, typename LowRank, typename RightHandSide, typename RightHandSideOut>\nvoid general_matmul_upper(const Eigen::MatrixBase<Input> &t1,              // (N,)\n                          const Eigen::MatrixBase<Input> &t2,              // (M,)\n                          const Eigen::MatrixBase<Coeffs> &c,              // (J,)\n                          const Eigen::MatrixBase<LowRank> &U,             // (N, J)\n                          const Eigen::MatrixBase<LowRank> &V,             // (M, J)\n                          const Eigen::MatrixBase<RightHandSide> &Y,       // (M, nrhs)\n                          Eigen::MatrixBase<RightHandSideOut> const &Z_out // (N, nrhs)\n) {\n  MakeEmptyWork(Input) F;\n  general_matmul_upper<false>(t1, t2, c, U, V, Y, Z_out, F);\n}\n\n} // namespace core\n} // namespace celerite2\n\n#endif // _CELERITE2_INTERFACE_HPP_DEFINED_\n", "meta": {"hexsha": "4f6ce6d08038e6efc5b63ced23e7f9e464a8dbdd", "size": 9549, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/include/celerite2/interface.hpp", "max_stars_repo_name": "jacksonloper/celerite2", "max_stars_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-10-10T02:43:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:59:21.000Z", "max_issues_repo_path": "c++/include/celerite2/interface.hpp", "max_issues_repo_name": "jacksonloper/celerite2", "max_issues_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T18:50:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T10:33:04.000Z", "max_forks_repo_path": "c++/include/celerite2/interface.hpp", "max_forks_repo_name": "jacksonloper/celerite2", "max_forks_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-11-09T18:12:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T20:20:59.000Z", "avg_line_length": 42.2522123894, "max_line_length": 150, "alphanum_fraction": 0.562153105, "num_tokens": 2589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.43200586027441495}}
{"text": "#include \"estimator.h\"\n#include <boost/math/special_functions/digamma.hpp>\n\nnamespace statiskit\n{    \n    PoissonDistributionMLEstimation::PoissonDistributionMLEstimation() : ActiveEstimation< PoissonDistribution, DiscreteUnivariateDistributionEstimation >()\n    {}\n\n    PoissonDistributionMLEstimation::PoissonDistributionMLEstimation(PoissonDistribution const * estimated, UnivariateData const * data) : ActiveEstimation< PoissonDistribution, DiscreteUnivariateDistributionEstimation >(estimated, data)\n    {}\n\n    PoissonDistributionMLEstimation::PoissonDistributionMLEstimation(const PoissonDistributionMLEstimation& estimation) : ActiveEstimation< PoissonDistribution, DiscreteUnivariateDistributionEstimation >(estimation)\n    {}\n\n    PoissonDistributionMLEstimation::~PoissonDistributionMLEstimation()\n    {}\n\n    PoissonDistributionMLEstimation::Estimator::Estimator()\n    {}\n\n    PoissonDistributionMLEstimation::Estimator::Estimator(const Estimator& estimator)\n    {}\n\n    PoissonDistributionMLEstimation::Estimator::~Estimator()\n    {}\n\n    std::unique_ptr< UnivariateDistributionEstimation > PoissonDistributionMLEstimation::Estimator::operator() (const UnivariateData& data, const bool& lazy) const\n    {\n        if(data.get_sample_space()->get_outcome() != DISCRETE)\n        { throw statiskit::sample_space_error(DISCRETE); }\n        std::unique_ptr< UnivariateDistributionEstimation > estimation; \n        UnivariateMeanEstimation::Estimator estimator = UnivariateMeanEstimation::Estimator();\n        std::unique_ptr< UnivariateLocationEstimation > _estimation = estimator(data);\n        double mean = _estimation->get_location(); \n        if(boost::math::isfinite(mean))\n        {\n            PoissonDistribution* poisson = new PoissonDistribution(mean);\n            if(lazy)\n            { estimation = std::make_unique< LazyEstimation< PoissonDistribution, DiscreteUnivariateDistributionEstimation > >(poisson); }\n            else\n            { estimation = std::make_unique< PoissonDistributionMLEstimation >(poisson, &data); }\n        }\n        return estimation;\n    }\n\n    std::unique_ptr< UnivariateDistributionEstimation::Estimator > PoissonDistributionMLEstimation::Estimator::copy() const\n    { return std::make_unique< Estimator >(*this); }\n\n    BinomialDistributionMLEstimation::BinomialDistributionMLEstimation() : OptimizationEstimation<unsigned int, BinomialDistribution, DiscreteUnivariateDistributionEstimation >()\n    {}\n\n    BinomialDistributionMLEstimation::BinomialDistributionMLEstimation(BinomialDistribution const * estimated, UnivariateData const * data) : OptimizationEstimation<unsigned int, BinomialDistribution, DiscreteUnivariateDistributionEstimation >(estimated, data)\n    {}\n    \n    BinomialDistributionMLEstimation::BinomialDistributionMLEstimation(const BinomialDistributionMLEstimation& estimation) : OptimizationEstimation<unsigned int, BinomialDistribution, DiscreteUnivariateDistributionEstimation >(estimation)\n    {}\n\n    BinomialDistributionMLEstimation::~BinomialDistributionMLEstimation()\n    {}\n\n    BinomialDistributionMLEstimation::Estimator::Estimator() : OptimizationEstimation<unsigned int, BinomialDistribution, DiscreteUnivariateDistributionEstimation >::Estimator()\n    { _force = false; }\n    \n    BinomialDistributionMLEstimation::Estimator::Estimator(const Estimator& estimator) : OptimizationEstimation<unsigned int, BinomialDistribution, DiscreteUnivariateDistributionEstimation >::Estimator(estimator)\n    { _force = estimator._force; }\n\n    BinomialDistributionMLEstimation::Estimator::~Estimator()\n    {}\n\n    std::unique_ptr< UnivariateDistributionEstimation > BinomialDistributionMLEstimation::Estimator::operator() (const UnivariateData& data, const bool& lazy) const\n    {\n        if(data.get_sample_space()->get_outcome() != DISCRETE)\n        { throw statiskit::sample_space_error(DISCRETE); }\n        std::unique_ptr< UnivariateDistributionEstimation > estimation;\n        UnivariateMeanEstimation::Estimator mean_estimator = UnivariateMeanEstimation::Estimator();\n        std::unique_ptr< UnivariateLocationEstimation > mean_estimation = mean_estimator(data);\n        double mean = mean_estimation->get_location();\n        UnivariateVarianceEstimation::Estimator variance_estimator = UnivariateVarianceEstimation::Estimator(false);\n        std::unique_ptr< UnivariateDispersionEstimation > variance_estimation = variance_estimator(data, mean);\n        double variance = variance_estimation->get_dispersion(); \n        if(variance > mean && !_force)\n        { throw overdispersion_error(); }\n        unsigned int kappa = std::max<int>(round(pow(mean, 2)/(mean - variance)), static_cast< DiscreteElementaryEvent* >(data.compute_maximum().get())->get_value());\n        BinomialDistribution* binomial = new BinomialDistribution(kappa, mean/double(kappa));\n        if(!lazy)\n        {\n            estimation = std::make_unique< BinomialDistributionMLEstimation >(binomial, &data);\n            static_cast< BinomialDistributionMLEstimation* >(estimation.get())->_iterations.push_back(kappa);\n        }\n        else\n        { estimation = std::make_unique< LazyEstimation< BinomialDistribution, DiscreteUnivariateDistributionEstimation > >(binomial); }\n        double curr, prev = binomial->loglikelihood(data);\n        unsigned int its = 1;\n        --kappa;\n        if(kappa > mean)\n        {\n            if(!lazy)\n            { static_cast< BinomialDistributionMLEstimation* >(estimation.get())->_iterations.push_back(kappa); }\n            binomial->set_kappa(kappa);\n            binomial->set_pi(mean/double(kappa));\n            curr = binomial->loglikelihood(data);\n        }\n        else\n        { curr = prev; }\n        if(curr > prev) {\n            if (mean/(kappa-1) >= 0.0 && mean/(kappa-1) <= 1.0) {\n                do\n                {\n                    prev = curr;\n                    --kappa;\n                    if(!lazy)\n                    { static_cast< BinomialDistributionMLEstimation* >(estimation.get())->_iterations.push_back(kappa); }\n                    binomial->set_kappa(kappa);\n                    binomial->set_pi(mean/double(kappa));\n                    curr = binomial->loglikelihood(data);\n                    ++its;\n                } while(run(its, __impl::reldiff(prev, curr)) && curr > prev);\n            }\n            if(curr < prev)\n            {\n                ++kappa;\n                if(!lazy)\n                { static_cast< BinomialDistributionMLEstimation* >(estimation.get())->_iterations.push_back(kappa); }\n                binomial->set_kappa(kappa);\n                binomial->set_pi(mean/double(kappa));\n            }\n        }\n        else\n        {\n            curr = prev;\n            do\n            {\n                prev = curr;\n                ++kappa;\n                if(!lazy)\n                { static_cast< BinomialDistributionMLEstimation* >(estimation.get())->_iterations.push_back(kappa); }\n                binomial->set_kappa(kappa);\n                binomial->set_pi(mean/double(kappa));\n                curr = binomial->loglikelihood(data);\n                ++its;\n            } while(run(its, __impl::reldiff(prev, curr)) && curr > prev);\n            if(curr < prev)\n            {\n                --kappa;\n                if(!lazy)\n                { static_cast< BinomialDistributionMLEstimation* >(estimation.get())->_iterations.push_back(kappa); }\n                binomial->set_kappa(kappa);\n                binomial->set_pi(mean/double(kappa));\n            }\n        }\n        return estimation;\n    }\n\n    bool BinomialDistributionMLEstimation::Estimator::get_force() const\n    { return _force; }\n\n    void BinomialDistributionMLEstimation::Estimator::set_force(const bool& force)\n    { _force = force; }\n\n    std::unique_ptr< UnivariateDistributionEstimation::Estimator > BinomialDistributionMLEstimation::Estimator::copy() const\n    { return std::make_unique< Estimator >(*this); }\n\n    BinomialDistributionMMEstimation::BinomialDistributionMMEstimation() : ActiveEstimation< BinomialDistribution, DiscreteUnivariateDistributionEstimation >()\n    {}\n\n    BinomialDistributionMMEstimation::BinomialDistributionMMEstimation(BinomialDistribution const * estimated, UnivariateData const * data) : ActiveEstimation< BinomialDistribution, DiscreteUnivariateDistributionEstimation >(estimated, data)\n    {}\n    \n    BinomialDistributionMMEstimation::BinomialDistributionMMEstimation(const BinomialDistributionMMEstimation& estimation) : ActiveEstimation< BinomialDistribution, DiscreteUnivariateDistributionEstimation >(estimation)\n    {}\n\n    BinomialDistributionMMEstimation::~BinomialDistributionMMEstimation()\n    {}\n\n    BinomialDistributionMMEstimation::Estimator::Estimator()\n    {\n        _location = new UnivariateMeanEstimation::Estimator();\n        _dispersion = new UnivariateVarianceEstimation::Estimator(false);\n    }\n\n    BinomialDistributionMMEstimation::Estimator::Estimator(const Estimator& estimator)\n    {\n        _location = estimator._location->copy().release();\n        _dispersion = estimator._dispersion->copy().release();\n    }\n\n    BinomialDistributionMMEstimation::Estimator::~Estimator()\n    {\n        delete _location;\n        delete _dispersion;\n    }\n\n    std::unique_ptr< UnivariateDistributionEstimation > BinomialDistributionMMEstimation::Estimator::operator() (const UnivariateData& data, const bool& lazy) const\n    {\n        if(data.get_sample_space()->get_outcome() != DISCRETE)\n        { throw statiskit::sample_space_error(DISCRETE); }\n        std::unique_ptr< UnivariateDistributionEstimation > estimation; \n        std::unique_ptr< UnivariateLocationEstimation > mean_estimation = (*_location)(data);\n        double mean = mean_estimation->get_location(); \n        std::unique_ptr< UnivariateDispersionEstimation > variance_estimation = (*_dispersion)(data, mean);\n        double variance = variance_estimation->get_dispersion(); \n        if(boost::math::isfinite(mean) && boost::math::isfinite(variance) && mean > variance)\n        {\n            unsigned int kappa = std::max<int>(round(pow(mean, 2)/(mean - variance)), static_cast< DiscreteElementaryEvent* >(data.compute_maximum().get())->get_value());\n            BinomialDistribution* binomial = new BinomialDistribution(kappa, mean/double(kappa));\n            if(lazy)\n            { estimation = std::make_unique< LazyEstimation< BinomialDistribution, DiscreteUnivariateDistributionEstimation > >(binomial); }\n            else\n            { estimation = std::make_unique< BinomialDistributionMMEstimation >(binomial, &data); }\n        }\n        else\n        { throw overdispersion_error(); }\n        return estimation;\n    }\n\n    std::unique_ptr< UnivariateDistributionEstimation::Estimator > BinomialDistributionMMEstimation::Estimator::copy() const\n    { return std::make_unique< Estimator >(*this); }\n\n    UnivariateLocationEstimation::Estimator* BinomialDistributionMMEstimation::Estimator::get_location()\n    { return _location; }\n\n    void BinomialDistributionMMEstimation::Estimator::set_location(const UnivariateLocationEstimation::Estimator& location)\n    { _location = location.copy().release(); }\n\n    UnivariateDispersionEstimation::Estimator* BinomialDistributionMMEstimation::Estimator::get_dispersion()\n    { return _dispersion; }\n\n    void BinomialDistributionMMEstimation::Estimator::set_dispersion(const UnivariateDispersionEstimation::Estimator& dispersion)\n    { _dispersion = dispersion.copy().release(); }\n\n    LogarithmicDistributionMLEstimation::LogarithmicDistributionMLEstimation() : OptimizationEstimation<double, LogarithmicDistribution, DiscreteUnivariateDistributionEstimation >()\n    {}\n\n    LogarithmicDistributionMLEstimation::LogarithmicDistributionMLEstimation(LogarithmicDistribution const * estimated, UnivariateData const * data) : OptimizationEstimation<double, LogarithmicDistribution, DiscreteUnivariateDistributionEstimation >(estimated, data)     \n    {}\n\n    LogarithmicDistributionMLEstimation::LogarithmicDistributionMLEstimation(const LogarithmicDistributionMLEstimation& estimation) : OptimizationEstimation<double, LogarithmicDistribution, DiscreteUnivariateDistributionEstimation >(estimation)     \n    {}\n\n    LogarithmicDistributionMLEstimation::~LogarithmicDistributionMLEstimation()\n    {}\n\n    LogarithmicDistributionMLEstimation::Estimator::Estimator()\n    {}\n\n    LogarithmicDistributionMLEstimation::Estimator::Estimator(const Estimator& estimator)\n    {}\n\n    LogarithmicDistributionMLEstimation::Estimator::~Estimator()\n    {}\n\n    std::unique_ptr< UnivariateDistributionEstimation > LogarithmicDistributionMLEstimation::Estimator::operator() (const UnivariateData& data, const bool& lazy) const\n    {\n        if(data.get_sample_space()->get_outcome() != DISCRETE)\n        { throw statiskit::sample_space_error(DISCRETE); }\n        std::unique_ptr< UnivariateDistributionEstimation > estimation;\n        UnivariateMeanEstimation::Estimator mean_estimator = UnivariateMeanEstimation::Estimator();\n        std::unique_ptr< UnivariateLocationEstimation > mean_estimation = mean_estimator(data);\n        double mean = mean_estimation->get_location();\n        double theta = 1 + 2 * (mean - 1);\n        if(theta <= 1)\n        { throw parameter_error(\"data\", \" has a mean inferior or equal to 1\"); }\n        theta = 1 - 1 / theta;\n        LogarithmicDistribution* logarithmic = new LogarithmicDistribution(theta);\n        if(!lazy)\n        {\n            estimation = std::make_unique< LogarithmicDistributionMLEstimation >(logarithmic, &data);\n            static_cast< LogarithmicDistributionMLEstimation* >(estimation.get())->_iterations.push_back(theta);\n        }\n        else\n        { estimation = std::make_unique< LazyEstimation< LogarithmicDistribution, DiscreteUnivariateDistributionEstimation > >(logarithmic); }\n        double prev, curr = logarithmic->loglikelihood(data);\n        unsigned int its = 0;\n        do\n        {\n            prev = curr;\n            theta = mean * log(1 - theta) / (mean * log(1 - theta) - 1);\n            if(theta > 0. && theta < 1.)\n            {\n                if(!lazy)\n                { static_cast< LogarithmicDistributionMLEstimation* >(estimation.get())->_iterations.push_back(theta); }\n                logarithmic->set_theta(theta);\n                curr = logarithmic->loglikelihood(data);\n                ++its;\n            }\n        } while(run(its, __impl::reldiff(prev, curr)) && curr > prev);\n        return estimation;\n    }\n\n    std::unique_ptr< UnivariateDistributionEstimation::Estimator > LogarithmicDistributionMLEstimation::Estimator::copy() const\n    { return std::make_unique< Estimator >(*this); }\n\n    GeometricDistributionMLEstimation::GeometricDistributionMLEstimation() : ActiveEstimation<GeometricDistribution, DiscreteUnivariateDistributionEstimation >()\n    {}\n\n    GeometricDistributionMLEstimation::GeometricDistributionMLEstimation(GeometricDistribution const * estimated, UnivariateData const * data) : ActiveEstimation<GeometricDistribution, DiscreteUnivariateDistributionEstimation >(estimated, data)     \n    {}\n\n    GeometricDistributionMLEstimation::GeometricDistributionMLEstimation(const GeometricDistributionMLEstimation& estimation) : ActiveEstimation<GeometricDistribution, DiscreteUnivariateDistributionEstimation >(estimation)     \n    {}\n\n    GeometricDistributionMLEstimation::~GeometricDistributionMLEstimation()\n    {}\n\n    GeometricDistributionMLEstimation::Estimator::Estimator()\n    {}\n\n    GeometricDistributionMLEstimation::Estimator::Estimator(const Estimator& estimator)\n    {}\n\n    GeometricDistributionMLEstimation::Estimator::~Estimator()\n    {}\n\n    std::unique_ptr< UnivariateDistributionEstimation > GeometricDistributionMLEstimation::Estimator::operator() (const UnivariateData& data, const bool& lazy) const\n    {\n        if(data.get_sample_space()->get_outcome() != DISCRETE)\n        { throw statiskit::sample_space_error(DISCRETE); }\n        UnivariateMeanEstimation::Estimator mean_estimator = UnivariateMeanEstimation::Estimator();\n        std::unique_ptr< UnivariateLocationEstimation > mean_estimation = mean_estimator(data);\n        double mean = mean_estimation->get_location(); \n        GeometricDistribution* geometric = new GeometricDistribution(1 - 1 / mean);\n        std::unique_ptr< UnivariateDistributionEstimation > estimation;\n        if(lazy)\n        { estimation = std::make_unique< LazyEstimation< GeometricDistribution, DiscreteUnivariateDistributionEstimation > >(geometric); }\n        else\n        { estimation = std::make_unique< GeometricDistributionMLEstimation >(geometric, &data); }\n        return estimation;\n    }\n\n    std::unique_ptr< UnivariateDistributionEstimation::Estimator > GeometricDistributionMLEstimation::Estimator::copy() const\n    { return std::make_unique< Estimator >(*this); }\n\n    NegativeBinomialDistributionMLEstimation::NegativeBinomialDistributionMLEstimation() : OptimizationEstimation<double, NegativeBinomialDistribution, DiscreteUnivariateDistributionEstimation >()\n    {}\n\n    NegativeBinomialDistributionMLEstimation::NegativeBinomialDistributionMLEstimation(NegativeBinomialDistribution const * estimated, UnivariateData const * data) : OptimizationEstimation<double, NegativeBinomialDistribution, DiscreteUnivariateDistributionEstimation >(estimated, data)\n    {}\n    \n    NegativeBinomialDistributionMLEstimation::NegativeBinomialDistributionMLEstimation(const NegativeBinomialDistributionMLEstimation& estimation) : OptimizationEstimation<double, NegativeBinomialDistribution, DiscreteUnivariateDistributionEstimation >(estimation)\n    {}\n\n    NegativeBinomialDistributionMLEstimation::~NegativeBinomialDistributionMLEstimation()\n    {}\n\n    NegativeBinomialDistributionMLEstimation::Estimator::Estimator() : OptimizationEstimation<double, NegativeBinomialDistribution, DiscreteUnivariateDistributionEstimation >::Estimator()\n    { _force = false; }\n    \n    NegativeBinomialDistributionMLEstimation::Estimator::Estimator(const Estimator& estimator) : OptimizationEstimation<double, NegativeBinomialDistribution, DiscreteUnivariateDistributionEstimation >::Estimator(estimator)\n    { _force = estimator._force; }\n\n    NegativeBinomialDistributionMLEstimation::Estimator::~Estimator()\n    {}\n\n    std::unique_ptr< UnivariateDistributionEstimation > NegativeBinomialDistributionMLEstimation::Estimator::operator() (const UnivariateData& data, const bool& lazy) const\n    {\n        if(data.get_sample_space()->get_outcome() != DISCRETE)\n        { throw statiskit::sample_space_error(DISCRETE); }\n        std::unique_ptr< UnivariateDistributionEstimation > estimation;\n        UnivariateMeanEstimation::Estimator mean_estimator = UnivariateMeanEstimation::Estimator();\n        std::unique_ptr< UnivariateLocationEstimation > mean_estimation = mean_estimator(data);\n        double mean = mean_estimation->get_location();\n        UnivariateVarianceEstimation::Estimator variance_estimator = UnivariateVarianceEstimation::Estimator(false);\n        std::unique_ptr< UnivariateDispersionEstimation > variance_estimation = variance_estimator(data, mean);\n        double variance = variance_estimation->get_dispersion();\n        if(variance < mean && !_force)\n        { throw underdispersion_error(); }\n        double total = data.compute_total(), kappa;\n        if(variance > mean)\n        { kappa = pow(mean, 2)/(variance - mean); }\n        else\n        { kappa = 1.; }\n        NegativeBinomialDistribution* negative_binomial = new NegativeBinomialDistribution(kappa, mean / (mean + kappa));\n        if(!lazy)\n        {\n            estimation = std::make_unique< NegativeBinomialDistributionMLEstimation >(negative_binomial, &data);\n            static_cast< NegativeBinomialDistributionMLEstimation* >(estimation.get())->_iterations.push_back(kappa);\n        }\n        else\n        { estimation = std::make_unique< LazyEstimation< NegativeBinomialDistribution, DiscreteUnivariateDistributionEstimation > >(negative_binomial); }\n        double prev, curr = negative_binomial->loglikelihood(data);\n        unsigned int its = 1;\n        do\n        {\n            prev = curr;\n            double alpha = 0;\n            std::unique_ptr< UnivariateData::Generator > generator = data.generator();\n            while(generator->is_valid())\n            {\n                const UnivariateEvent* event = generator->event();\n                if(event && event->get_event() == ELEMENTARY)\n                {\n                    for(int nu = 0, max_nu = static_cast< const DiscreteElementaryEvent* >(event)->get_value(); nu < max_nu; ++nu)\n                    { alpha += nu / (nu + kappa); }\n                }\n                ++(*generator);\n            }\n            alpha /= -total;\n            alpha += mean;\n            kappa = alpha / log(1 + mean/kappa);\n            if(kappa > 0.)\n            {\n                if(!lazy)\n                { static_cast< NegativeBinomialDistributionMLEstimation* >(estimation.get())->_iterations.push_back(kappa); }\n                negative_binomial->set_kappa(kappa);\n                negative_binomial->set_pi(mean / (mean + kappa));\n                curr = negative_binomial->loglikelihood(data);\n                ++its;\n            }\n        } while(run(its, __impl::reldiff(prev, curr)) && curr > prev);\n        return estimation;\n    }\n\n    bool NegativeBinomialDistributionMLEstimation::Estimator::get_force() const\n    { return _force; }\n\n    void NegativeBinomialDistributionMLEstimation::Estimator::set_force(const bool& force)\n    { _force = force; }\n\n    std::unique_ptr< UnivariateDistributionEstimation::Estimator > NegativeBinomialDistributionMLEstimation::Estimator::copy() const\n    { return std::make_unique< Estimator >(*this); }\n\n    NegativeBinomialDistributionMMEstimation::NegativeBinomialDistributionMMEstimation() : ActiveEstimation< NegativeBinomialDistribution, DiscreteUnivariateDistributionEstimation >()\n    {}\n\n    NegativeBinomialDistributionMMEstimation::NegativeBinomialDistributionMMEstimation(NegativeBinomialDistribution const * estimated, UnivariateData const * data) : ActiveEstimation< NegativeBinomialDistribution, DiscreteUnivariateDistributionEstimation >(estimated, data)\n    {}\n    \n    NegativeBinomialDistributionMMEstimation::NegativeBinomialDistributionMMEstimation(const NegativeBinomialDistributionMMEstimation& estimation) : ActiveEstimation< NegativeBinomialDistribution, DiscreteUnivariateDistributionEstimation >(estimation)\n    {}\n    \n    NegativeBinomialDistributionMMEstimation::~NegativeBinomialDistributionMMEstimation()\n    {}\n\n    NegativeBinomialDistributionMMEstimation::Estimator::Estimator()\n    {\n        _location = new UnivariateMeanEstimation::Estimator();\n        _dispersion = new UnivariateVarianceEstimation::Estimator(false);\n    }\n\n    NegativeBinomialDistributionMMEstimation::Estimator::Estimator(const Estimator& estimator)\n    {\n        _location = estimator._location->copy().release();\n        _dispersion = estimator._dispersion->copy().release();\n    }\n\n    NegativeBinomialDistributionMMEstimation::Estimator::~Estimator()\n    {\n        delete _location;\n        delete _dispersion;\n    }\n\n    std::unique_ptr< UnivariateDistributionEstimation > NegativeBinomialDistributionMMEstimation::Estimator::operator() (const UnivariateData& data, const bool& lazy) const\n    {\n        if(data.get_sample_space()->get_outcome() != DISCRETE)\n        { throw statiskit::sample_space_error(DISCRETE); }\n        std::unique_ptr< UnivariateDistributionEstimation > estimation; \n        std::unique_ptr< UnivariateLocationEstimation > mean_estimation = (*_location)(data);\n        double mean = mean_estimation->get_location(); \n        std::unique_ptr< UnivariateDispersionEstimation > variance_estimation = (*_dispersion)(data, mean);\n        double variance = variance_estimation->get_dispersion(); \n        if(boost::math::isfinite(mean) && boost::math::isfinite(variance) && variance > mean)\n        {\n            NegativeBinomialDistribution* negbinomial = new NegativeBinomialDistribution(pow(mean, 2)/(variance - mean), 1. - mean/variance);\n            if(lazy)\n            { estimation = std::make_unique< LazyEstimation< NegativeBinomialDistribution, DiscreteUnivariateDistributionEstimation > >(negbinomial); }\n            else\n            { estimation = std::make_unique< NegativeBinomialDistributionMMEstimation >(negbinomial, &data); }\n        }\n        else\n        { throw underdispersion_error(); }\n        return estimation;\n    }\n\n    std::unique_ptr< UnivariateDistributionEstimation::Estimator > NegativeBinomialDistributionMMEstimation::Estimator::copy() const\n    { return std::make_unique< Estimator >(*this); }\n    \n    UnivariateLocationEstimation::Estimator* NegativeBinomialDistributionMMEstimation::Estimator::get_location()\n    { return _location; }\n\n    void NegativeBinomialDistributionMMEstimation::Estimator::set_location(const UnivariateLocationEstimation::Estimator& mean)\n    { _location = mean.copy().release(); }\n\n    UnivariateDispersionEstimation::Estimator* NegativeBinomialDistributionMMEstimation::Estimator::get_dispersion()\n    { return _dispersion; }\n\n    void NegativeBinomialDistributionMMEstimation::Estimator::set_dispersion(const UnivariateDispersionEstimation::Estimator& dispersion)\n    { _dispersion = dispersion.copy().release(); }\n\n    NormalDistributionMLEstimation::NormalDistributionMLEstimation() : ActiveEstimation< NormalDistribution, ContinuousUnivariateDistributionEstimation >()\n    {}\n\n    NormalDistributionMLEstimation::NormalDistributionMLEstimation(NormalDistribution const * estimated, UnivariateData const * data) : ActiveEstimation< NormalDistribution, ContinuousUnivariateDistributionEstimation >(estimated, data)\n    {}\n\n    NormalDistributionMLEstimation::NormalDistributionMLEstimation(const NormalDistributionMLEstimation& estimation) : ActiveEstimation< NormalDistribution, ContinuousUnivariateDistributionEstimation >(estimation)\n    {}\n\n    NormalDistributionMLEstimation::~NormalDistributionMLEstimation()\n    {}\n\n    NormalDistributionMLEstimation::Estimator::Estimator()\n    {}\n\n    NormalDistributionMLEstimation::Estimator::~Estimator()\n    {}\n\n    std::unique_ptr< UnivariateDistributionEstimation > NormalDistributionMLEstimation::Estimator::operator() (const UnivariateData& data, const bool& lazy) const\n    {\n        if(data.get_sample_space()->get_outcome() != CONTINUOUS)\n        { throw statiskit::sample_space_error(CONTINUOUS); }\n        std::unique_ptr< UnivariateDistributionEstimation > estimation;\n        UnivariateMeanEstimation::Estimator mean_estimator = UnivariateMeanEstimation::Estimator();\n        std::unique_ptr< UnivariateLocationEstimation > mean_estimation = mean_estimator(data);\n        double mean = mean_estimation->get_location(); \n        UnivariateVarianceEstimation::Estimator variance_estimator = UnivariateVarianceEstimation::Estimator(false);\n        std::unique_ptr< UnivariateDispersionEstimation > variance_estimation = variance_estimator(data, mean);\n        double std_err = sqrt(variance_estimation->get_dispersion()); \n        if(boost::math::isfinite(mean) && boost::math::isfinite(std_err))\n        {\n            NormalDistribution* normal = new NormalDistribution(mean, std_err);\n            if(lazy)\n            { estimation = std::make_unique< LazyEstimation< NormalDistribution, ContinuousUnivariateDistributionEstimation > >(normal); }\n            else\n            { estimation = std::make_unique< NormalDistributionMLEstimation >(normal, &data); }\n        }\n        return estimation;\n    }\n\n    std::unique_ptr< UnivariateDistributionEstimation::Estimator > NormalDistributionMLEstimation::Estimator::copy() const\n    { return std::make_unique< Estimator >(*this); }\n\n    UnivariateHistogramDistributionEstimation::UnivariateHistogramDistributionEstimation() : ActiveEstimation< UnivariateHistogramDistribution, ContinuousUnivariateDistributionEstimation >()\n    {}\n\n    UnivariateHistogramDistributionEstimation::UnivariateHistogramDistributionEstimation(UnivariateHistogramDistribution const * estimated, UnivariateData const * data) : ActiveEstimation< UnivariateHistogramDistribution, ContinuousUnivariateDistributionEstimation >(estimated, data)\n    {}\n\n    UnivariateHistogramDistributionEstimation::UnivariateHistogramDistributionEstimation(const UnivariateHistogramDistributionEstimation& estimation) : ActiveEstimation< UnivariateHistogramDistribution, ContinuousUnivariateDistributionEstimation >(estimation)\n    {}\n\n    UnivariateHistogramDistributionEstimation::~UnivariateHistogramDistributionEstimation()\n    {}\n\n    UnivariateHistogramDistributionEstimation::Estimator::Estimator()\n    { _nb_bins = 0; }\n\n    UnivariateHistogramDistributionEstimation::Estimator::Estimator(const Estimator& estimator)\n    { _nb_bins = estimator._nb_bins; }\n\n    UnivariateHistogramDistributionEstimation::Estimator::~Estimator()\n    {}\n\n    std::unique_ptr< UnivariateDistributionEstimation > UnivariateHistogramDistributionEstimation::Estimator::operator() (const UnivariateData& data, const bool& lazy) const\n    {\n        if(data.get_sample_space()->get_outcome() != CONTINUOUS)\n        { throw statiskit::sample_space_error(CONTINUOUS); }\n        std::unique_ptr< UnivariateDistributionEstimation > estimation;\n        auto bins = std::set< double >();\n        double total = 0., min = std::numeric_limits< double >::infinity(), max = -1 * std::numeric_limits< double >::infinity();\n        std::unique_ptr< UnivariateData::Generator > generator = data.generator();\n        double nb_bins = 0;\n        while(generator->is_valid())\n        {\n            auto event = generator->event();\n            if(event && event->get_event() == ELEMENTARY)\n            {\n                auto cevent = static_cast< const ContinuousElementaryEvent* >(event);\n                min = std::min(min, cevent->get_value());\n                max = std::max(max, cevent->get_value());\n                total += generator->weight(); \n                nb_bins += 1;                           \n            }\n            ++(*generator);\n        }\n        if(_nb_bins != 0)\n        { nb_bins = _nb_bins; }\n        bins.insert(min - .5 / total * (max - min));\n        for(Index index = 1; index < nb_bins; ++index)\n        { bins.insert(*(bins.rbegin()) + 1. / nb_bins * (max-min)); }\n        bins.insert(max + .5 / nb_bins * (max - min));\n        if(bins.size() > 1)\n        {\n            auto lengths = std::vector< double >(bins.size()-1, 0.);\n            std::set< double >::iterator itl = bins.begin(), itr, it_end = bins.end();\n            itr = itl;\n            ++itr;\n            while(itr != it_end)\n            {\n                lengths[distance(bins.begin(), itl)] = *itr - *itl;\n                ++itl;\n                ++itr;\n            }\n            auto densities = std::vector< double >(bins.size()-1, 0.);\n            std::set< double >::iterator it;\n            generator = data.generator();\n            while(generator->is_valid())\n            {\n                auto event = generator->event();\n                if(event)\n                {\n                    if(event->get_event() == ELEMENTARY)\n                    {\n                        it = bins.upper_bound(static_cast< const ContinuousElementaryEvent* >(event)->get_value());\n                        if(it == bins.end())\n                        { densities.back() += generator->weight() / (lengths.back() * total); }\n                        else if(it == bins.begin())\n                        { densities.front() += generator->weight() / (lengths.front() * total); }\n                        else\n                        { densities[distance(bins.begin(), it) - 1] += generator->weight() /(lengths[distance(bins.begin(), it) - 1] * total); }\n                    }\n                }\n                ++(*generator);\n            }\n            UnivariateHistogramDistribution* histogram = new UnivariateHistogramDistribution(bins, densities);\n            if(lazy)\n            { estimation = std::make_unique< LazyEstimation< UnivariateHistogramDistribution, ContinuousUnivariateDistributionEstimation > >(histogram); }\n            else\n            { estimation = std::make_unique< UnivariateHistogramDistributionEstimation >(histogram, &data); }\n        }\n        else\n        { throw sample_size_error(1); }\n        return estimation;\n    }\n\n    std::unique_ptr< UnivariateDistributionEstimation::Estimator > UnivariateHistogramDistributionEstimation::Estimator::copy() const\n    { return std::make_unique< Estimator >(*this); }\n\n    const unsigned int& UnivariateHistogramDistributionEstimation::Estimator::get_nb_bins() const\n    { return _nb_bins; }\n\n    void UnivariateHistogramDistributionEstimation::Estimator::set_nb_bins(const unsigned int& nb_bins)\n    { _nb_bins = nb_bins; }\n\n    RegularUnivariateHistogramDistributionSlopeHeuristicSelection::RegularUnivariateHistogramDistributionSlopeHeuristicSelection(const UnivariateData* data) : SlopeHeuristicSelection< ContinuousUnivariateDistributionEstimation >(data)\n    {}\n\n    RegularUnivariateHistogramDistributionSlopeHeuristicSelection::RegularUnivariateHistogramDistributionSlopeHeuristicSelection(const RegularUnivariateHistogramDistributionSlopeHeuristicSelection& selection) : SlopeHeuristicSelection< ContinuousUnivariateDistributionEstimation >(selection)\n    {}\n\n    RegularUnivariateHistogramDistributionSlopeHeuristicSelection::~RegularUnivariateHistogramDistributionSlopeHeuristicSelection()\n    {}\n\n    RegularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::Estimator()\n    { _maxbins = 100; }\n\n    RegularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::Estimator(const Estimator& estimator)\n    { _maxbins = estimator._maxbins; }\n\n    RegularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::~Estimator()\n    {}\n\n    std::unique_ptr< UnivariateDistributionEstimation > RegularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::operator() (const UnivariateData& data, const bool& lazy) const\n    {\n        if(data.get_sample_space()->get_outcome() != CONTINUOUS)\n        { throw statiskit::sample_space_error(CONTINUOUS); }\n        RegularUnivariateHistogramDistributionSlopeHeuristicSelection* cache;\n        if(lazy)\n        { cache = new RegularUnivariateHistogramDistributionSlopeHeuristicSelection(nullptr); }\n        else\n        { cache = new RegularUnivariateHistogramDistributionSlopeHeuristicSelection(&data); }\n        std::set< double > bins = std::set< double >();\n        UnivariateHistogramDistributionEstimation::Estimator estimator = UnivariateHistogramDistributionEstimation::Estimator();\n        for(Index nb_bins = _maxbins; nb_bins > 0; --nb_bins)\n        {\n            estimator.set_nb_bins(nb_bins);\n            try\n            {\n                std::unique_ptr< UnivariateDistributionEstimation > estimation = estimator(data, true);\n                UnivariateHistogramDistribution* estimated = const_cast< UnivariateHistogramDistribution* >(static_cast< const UnivariateHistogramDistribution* >(estimation->get_estimated()));\n                cache->add(estimated->get_nb_parameters(), estimated->loglikelihood(data), static_cast< UnivariateHistogramDistribution* >(estimated->copy().release()));\n            } \n            catch(const std::exception& error)\n            {}\n        }\n        cache->finalize();\n        std::unique_ptr< UnivariateDistributionEstimation > estimation;\n        if(lazy)\n        {\n            estimation = std::make_unique< LazyEstimation< UnivariateHistogramDistribution, ContinuousUnivariateDistributionEstimation > >(static_cast< UnivariateHistogramDistribution* >(cache->get_estimated()->copy().release()));\n            delete cache;\n        }\n        else\n        { estimation.reset(cache); }\n        return estimation;\n    }\n\n    std::unique_ptr< UnivariateDistributionEstimation::Estimator > RegularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::copy() const\n    { return std::make_unique< Estimator >(*this); }\n\n    const unsigned int& RegularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::get_maxbins() const\n    { return _maxbins; }\n\n    void RegularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::set_maxbins(const unsigned int& maxbins)\n    {\n        if(maxbins == 0)\n        { throw statiskit::lower_bound_error(\"maxbins\", 0, 0, true); }\n        _maxbins = maxbins;\n    }\n\n    IrregularUnivariateHistogramDistributionSlopeHeuristicSelection::IrregularUnivariateHistogramDistributionSlopeHeuristicSelection(const UnivariateData* data) : SlopeHeuristicSelection< ContinuousUnivariateDistributionEstimation >(data)\n    {}\n\n    IrregularUnivariateHistogramDistributionSlopeHeuristicSelection::IrregularUnivariateHistogramDistributionSlopeHeuristicSelection(const IrregularUnivariateHistogramDistributionSlopeHeuristicSelection& selection) : SlopeHeuristicSelection< ContinuousUnivariateDistributionEstimation >(selection)\n    {}\n    \n    IrregularUnivariateHistogramDistributionSlopeHeuristicSelection::~IrregularUnivariateHistogramDistributionSlopeHeuristicSelection()\n    {}\n\n    IrregularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::Estimator()\n    {\n        _maxbins = 100; \n        _constant = 1.;\n    }\n\n    IrregularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::Estimator(const Estimator& estimator)\n    { \n        _maxbins = estimator._maxbins;\n        _constant = estimator._constant;\n    }\n\n    IrregularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::~Estimator()\n    {}\n\n    std::unique_ptr< UnivariateDistributionEstimation > IrregularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::operator() (const UnivariateData& data, const bool& lazy) const\n    {\n        if(data.get_sample_space()->get_outcome() != CONTINUOUS)\n        { throw statiskit::sample_space_error(CONTINUOUS); }\n        IrregularUnivariateHistogramDistributionSlopeHeuristicSelection* cache;\n        if(lazy)\n        { cache = new IrregularUnivariateHistogramDistributionSlopeHeuristicSelection(nullptr); }\n        else\n        { cache = new IrregularUnivariateHistogramDistributionSlopeHeuristicSelection(&data); }\n        std::set< double > bins = std::set< double >();\n        unsigned int elements = 0;\n        double total = 0., min = std::numeric_limits< double >::infinity(), max = -1 * std::numeric_limits< double >::infinity();\n        std::unique_ptr< UnivariateData::Generator > generator = data.generator();\n        while(generator->is_valid())\n        {\n            const UnivariateEvent* event = generator->event();\n            if(event && event->get_event() == ELEMENTARY)\n            {\n                const ContinuousElementaryEvent* cevent = static_cast< const ContinuousElementaryEvent* >(event);\n                min = std::min(min, cevent->get_value());\n                max = std::max(max, cevent->get_value());\n                total += generator->weight();    \n            }\n            ++(*generator);\n        }\n        bins.insert(min - .5 / _maxbins * (max - min));\n        for(Index index = 1; index < _maxbins; ++index)\n        { bins.insert(*(bins.rbegin()) + 1. / _maxbins * (max-min)); }\n        bins.insert(max + .5 / _maxbins * (max - min));\n        if(bins.size() > 1)\n        {\n            std::vector< double > lengths = std::vector< double >(bins.size()-1, 0.);\n            std::set< double >::iterator itl = bins.begin(), itr, it_end = bins.end();\n            itr = itl;\n            ++itr;\n            while(itr != it_end)\n            {\n                lengths[distance(bins.begin(), itl)] = *itr - *itl;\n                ++itl;\n                ++itr;\n            }\n            std::vector< double > densities = std::vector< double >(bins.size()-1, 0.);\n            std::set< double >::iterator it;\n            generator = data.generator();\n            while(generator->is_valid())\n            {\n                const UnivariateEvent* event = generator->event();\n                if(event)\n                {\n                    if(event->get_event() == ELEMENTARY)\n                    {\n                        it = bins.upper_bound(static_cast< const ContinuousElementaryEvent* >(event)->get_value());\n                        if(it == bins.end())\n                        { densities.back() += generator->weight() /(lengths.back() * total); }\n                        else if(it == bins.begin())\n                        { densities.front() +=  generator->weight() /(lengths.front() * total); }\n                        else\n                        { densities[distance(bins.begin(), it) - 1] += generator->weight() /(lengths[distance(bins.begin(), it) - 1] * total); }\n                    }\n                }\n                ++(*generator);\n            }\n            std::vector< double > entropies = std::vector< double >(densities.size()-1, std::numeric_limits< double >::quiet_NaN());\n            for(Index index = 0, max_index = densities.size()-1; index < max_index; ++index)\n            {\n                entropies[index] = 0;\n                if(densities[index] > 0.)\n                { entropies[index] += lengths[index] * densities[index] * log(densities[index]); }\n                if(densities[index + 1] > 0.)\n                { entropies[index] += lengths[index + 1] * densities[index + 1] * log(densities[index + 1]); }\n                double p = (lengths[index] * densities[index] + lengths[index + 1] * densities[index+1]) / (lengths[index] + lengths[index + 1]);\n                if(p > 0.)\n                { entropies[index] -= (lengths[index] + lengths[index + 1]) * p * log(p); }\n                else\n                { entropies[index] = std::numeric_limits< double >::infinity(); }\n            }\n            double score = 0.;\n            while(bins.size() > 2)\n            {\n                std::vector< double >::iterator it = std::min_element(entropies.begin(), entropies.end()), itr;\n                if(*it > 0)\n                {\n                    score -= *it;\n                    // if(bins.size() < _maxbins)\n                    // {\n                        UnivariateHistogramDistribution* current = new UnivariateHistogramDistribution(bins, densities);\n                        double penshape = bins.size()-1;\n                        penshape = penshape * (1 + _constant * log(_maxbins) - _constant * log(penshape));\n                        cache->add(penshape, score, current);\n                    // }\n                }\n                itr = it;\n                ++itr;\n                densities[distance(entropies.begin(), itr)] = lengths[distance(entropies.begin(), it)] * densities[distance(entropies.begin(), it)] + lengths[distance(entropies.begin(), itr)] * densities[distance(entropies.begin(), itr)];\n                densities[distance(entropies.begin(), itr)] /= lengths[distance(entropies.begin(), it)] + lengths[distance(entropies.begin(), itr)];\n                lengths[distance(entropies.begin(), itr)] = lengths[distance(entropies.begin(), it)] + lengths[distance(entropies.begin(), itr)];\n                std::vector< double >::iterator itd = densities.begin();\n                advance(itd, distance(entropies.begin(), it));\n                densities.erase(itd);\n                std::vector< double >::iterator itl = lengths.begin();\n                advance(itl, distance(entropies.begin(), it));\n                lengths.erase(itl);\n                std::set< double >::iterator itb = bins.begin();\n                advance(itb, distance(entropies.begin(), itr));\n                bins.erase(itb);\n                // TODO optimize\n                entropies = std::vector< double >(densities.size()-1, std::numeric_limits< double >::quiet_NaN());\n                for(Index index = 0, max_index = densities.size()-1; index < max_index; ++index)\n                { \n                    entropies[index] = 0;\n                    if(densities[index] > 0.)\n                    { entropies[index] += lengths[index] * densities[index] * log(densities[index]); }\n                    if(densities[index + 1] > 0.)\n                    { entropies[index] += lengths[index + 1] * densities[index + 1] * log(densities[index + 1]); }\n                    double p = (lengths[index] * densities[index] + lengths[index + 1] * densities[index+1]) / (lengths[index] + lengths[index + 1]);\n                    if(p > 0.)\n                    { entropies[index] -= (lengths[index] + lengths[index + 1]) * p * log(p); }\n                    else\n                    { entropies[index] = std::numeric_limits< double >::infinity(); }\n                }\n            }\n            cache->finalize();\n        }\n        else\n        { throw sample_size_error(1); }\n        std::unique_ptr< UnivariateDistributionEstimation > estimation;\n        if(lazy)\n        {\n            estimation = std::make_unique< LazyEstimation< UnivariateHistogramDistribution, ContinuousUnivariateDistributionEstimation > >(static_cast<  UnivariateHistogramDistribution* >(cache->get_estimated()->copy().release()));\n            delete cache;\n        }\n        else\n        { estimation.reset(cache); }\n        return estimation;\n    }\n\n    std::unique_ptr< UnivariateDistributionEstimation::Estimator > IrregularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::copy() const\n    { return std::make_unique< Estimator >(*this); }\n\n    const unsigned int& IrregularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::get_maxbins() const\n    { return _maxbins; }\n\n    void IrregularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::set_maxbins(const unsigned int& maxbins)\n    {\n        if(maxbins == 0)\n        { throw statiskit::lower_bound_error(\"maxbins\", 0, 0, true); }\n        _maxbins = maxbins;\n    }\n    \n    const double& IrregularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::get_constant() const\n    { return _constant; }\n\n    void IrregularUnivariateHistogramDistributionSlopeHeuristicSelection::Estimator::set_constant(const double& constant)\n    {\n        if(constant <= 0.)\n        { throw statiskit::lower_bound_error(\"constant\", constant, 0.0, true); }\n        _constant = constant;\n    }\n\n    SingularDistributionEstimation::~SingularDistributionEstimation()\n    {}\n\n    SingularDistributionEstimation::Estimator::~Estimator()\n    {}\n\n    MultinomialSingularDistributionEstimation::MultinomialSingularDistributionEstimation(MultinomialSingularDistribution const * estimated, MultivariateData const * data) : ActiveEstimation< MultinomialSingularDistribution, SingularDistributionEstimation >(estimated, data)\n    {}\n\n    MultinomialSingularDistributionEstimation::MultinomialSingularDistributionEstimation(const MultinomialSingularDistributionEstimation& estimation) : ActiveEstimation< MultinomialSingularDistribution, SingularDistributionEstimation >(estimation)\n    {}\n\n    MultinomialSingularDistributionEstimation::~MultinomialSingularDistributionEstimation()\n    {}\n\n    MultinomialSingularDistributionEstimation::Estimator::Estimator()\n    {}\n\n    MultinomialSingularDistributionEstimation::Estimator::Estimator(const Estimator& estimator)\n    {}\n\n    MultinomialSingularDistributionEstimation::Estimator::~Estimator()\n    {}\n\n    std::unique_ptr< SingularDistributionEstimation > MultinomialSingularDistributionEstimation::Estimator::operator() (const MultivariateData& data, const bool& lazy) const\n    {\n        std::unique_ptr< SingularDistributionEstimation > estimation;\n        std::unique_ptr< MultivariateData::Generator > generator = data.generator();\n        Eigen::VectorXd pi = Eigen::VectorXd::Zero(generator->event()->size());\n        while(generator->is_valid())\n        {\n            const MultivariateEvent* mevent = generator->event();\n            for(Index component = 0, max_component = mevent->size(); component < max_component; ++component)\n            {\n                const UnivariateEvent* uevent = mevent->get(component);\n                if(uevent && uevent->get_outcome() == DISCRETE && uevent->get_event() == ELEMENTARY)\n                { pi[component] += generator->weight() * static_cast< const DiscreteElementaryEvent* >(uevent)->get_value(); }\n            }\n            ++(*generator);\n        }\n        MultinomialSingularDistribution* estimated = new MultinomialSingularDistribution(pi);\n        if(lazy)\n        { estimation = std::make_unique< LazyEstimation< MultinomialSingularDistribution, SingularDistributionEstimation > >(estimated); }\n        else\n        { estimation = std::make_unique< MultinomialSingularDistributionEstimation >(estimated, &data); }\n        return estimation;\n    }\n\n    DirichletMultinomialSingularDistributionEstimation::DirichletMultinomialSingularDistributionEstimation(DirichletMultinomialSingularDistribution const * estimated, MultivariateData const * data) : OptimizationEstimation<Eigen::VectorXd, DirichletMultinomialSingularDistribution, SingularDistributionEstimation >(estimated, data)\n    {}\n\n    DirichletMultinomialSingularDistributionEstimation::DirichletMultinomialSingularDistributionEstimation(const DirichletMultinomialSingularDistributionEstimation& estimation) : OptimizationEstimation<Eigen::VectorXd, DirichletMultinomialSingularDistribution, SingularDistributionEstimation >(estimation)\n    {}\n\n    DirichletMultinomialSingularDistributionEstimation::~DirichletMultinomialSingularDistributionEstimation()\n    {}\n\n    DirichletMultinomialSingularDistributionEstimation::Estimator::Estimator() : PolymorphicCopy<SingularDistributionEstimation::Estimator, Estimator, OptimizationEstimation<Eigen::VectorXd, DirichletMultinomialSingularDistribution, SingularDistributionEstimation >::Estimator >() \n    {}\n\n    DirichletMultinomialSingularDistributionEstimation::Estimator::Estimator(const Estimator& estimator) : PolymorphicCopy<SingularDistributionEstimation::Estimator, Estimator, OptimizationEstimation<Eigen::VectorXd, DirichletMultinomialSingularDistribution, SingularDistributionEstimation >::Estimator >(estimator)\n    {}\n\n    DirichletMultinomialSingularDistributionEstimation::Estimator::~Estimator()\n    {}\n\n    std::unique_ptr< SingularDistributionEstimation > DirichletMultinomialSingularDistributionEstimation::Estimator::operator() (const MultivariateData& data, const bool& lazy) const\n    {\n        std::unique_ptr< SingularDistributionEstimation > estimation;\n        double total = data.compute_total();\n        Eigen::VectorXd prev, curr = Eigen::VectorXd::Ones(data.get_sample_space()->size());\n        DirichletMultinomialSingularDistribution* estimated = new DirichletMultinomialSingularDistribution(curr);\n        if(lazy)\n        { estimation = std::make_unique< LazyEstimation< DirichletMultinomialSingularDistribution, SingularDistributionEstimation > >(estimated); }\n        else\n        { estimation = std::make_unique< DirichletMultinomialSingularDistributionEstimation >(estimated, &data); }\n        unsigned int its = 0;\n        do\n        {\n            prev = curr;\n            Eigen::VectorXd temp = Eigen::VectorXd::Zero(data.get_sample_space()->size());\n            for(Index component = 0, max_component = data.get_sample_space()->size(); component < max_component; ++component)\n            {\n                std::unique_ptr< MultivariateData::Generator > generator = data.generator();\n                while(generator->is_valid())\n                {\n                    const MultivariateEvent* mevent = generator->event();\n                    if(mevent)\n                    {\n                        const UnivariateEvent* uevent = mevent->get(component);\n                        if(uevent && uevent->get_outcome() == DISCRETE && uevent->get_event() == ELEMENTARY)\n                        { temp[component] += generator->weight() * boost::math::digamma(static_cast< const DiscreteElementaryEvent* >(uevent)->get_value() + prev[component]); }\n                    }\n                    ++(*generator);\n                }\n                temp[component] -= total * boost::math::digamma(prev[component]);\n            }\n            std::pair< double, double > sums = std::make_pair(0., curr.sum());\n            std::unique_ptr< MultivariateData::Generator > generator = data.generator();\n            while(generator->is_valid())\n            {\n                const MultivariateEvent* event = generator->event();\n                if(event)\n                {\n                    int value = 0;\n                    for(Index component = 0, max_component = data.get_sample_space()->size(); component < max_component; ++component)\n                    {\n                        const UnivariateEvent* uevent = event->get(component);\n                        if(uevent && uevent->get_outcome() == DISCRETE && uevent->get_event() == ELEMENTARY)\n                        { value += static_cast< const DiscreteElementaryEvent* >(uevent)->get_value(); }\n                    }\n                    sums.first += generator->weight() * boost::math::digamma(value + sums.second);\n                }\n                ++(*generator);\n            }\n            sums.first -= total * boost::math::digamma(sums.second);\n            temp /= sums.first;\n            if(temp.minCoeff() >= 0.)\n            { \n                curr = prev.cwiseProduct(temp);\n                if(!lazy)\n                { static_cast< DirichletMultinomialSingularDistributionEstimation* >(estimation.get())->_iterations.push_back(curr); }\n            }\n            ++its;\n        } while(run(its, __impl::reldiff(prev, curr)));\n        estimated->set_alpha(curr);\n        return estimation;\n    }\n\n    SplittingDistributionEstimation::SplittingDistributionEstimation(SplittingDistribution const * estimated, MultivariateData const * data) : ActiveEstimation< SplittingDistribution, DiscreteMultivariateDistributionEstimation >(estimated, data)\n    {\n        _sum = nullptr;\n        _singular = nullptr;\n    }\n\n    SplittingDistributionEstimation::SplittingDistributionEstimation(const SplittingDistributionEstimation& estimation) : ActiveEstimation< SplittingDistribution, DiscreteMultivariateDistributionEstimation >(estimation)\n    {\n        _sum = estimation._sum;\n        _singular = estimation._singular;\n    }\n\n    SplittingDistributionEstimation::~SplittingDistributionEstimation()\n    {\n        if(_sum)\n        { delete _sum; }\n        if(_singular)\n        { delete _singular; }\n    }\n\n    const DiscreteUnivariateDistributionEstimation* SplittingDistributionEstimation::get_sum() const\n    { return _sum; }\n\n    const SingularDistributionEstimation* SplittingDistributionEstimation::get_singular() const\n    { return _singular; }\n\n    SplittingDistributionEstimation::Estimator::Estimator()\n    {\n        _sum = nullptr;\n        _singular = nullptr;\n    }\n\n    SplittingDistributionEstimation::Estimator::Estimator(const Estimator& estimator)\n    {\n        if(estimator._sum)\n        { _sum = static_cast< DiscreteUnivariateDistributionEstimation::Estimator* >((estimator._sum->copy()).release()); }\n        else\n        { _sum = nullptr; }\n        if(estimator._singular)\n        { _singular = estimator._singular->copy().release(); }\n        else\n        { _singular = nullptr; }    \n    }\n\n    SplittingDistributionEstimation::Estimator::~Estimator()\n    {\n        if(_sum)\n        {\n            delete _sum;\n            _sum = nullptr;\n        }\n        if(_singular)\n        {\n            delete _singular;\n            _singular = nullptr;\n        }\n    }\n\n    std::unique_ptr< MultivariateDistributionEstimation > SplittingDistributionEstimation::Estimator::operator() (const MultivariateData& data, const bool& lazy) const\n    {\n        UnivariateDataFrame* sum_data = new UnivariateDataFrame(get_NN());\n        std::unique_ptr< MultivariateData::Generator > generator = data.generator();\n        while(generator->is_valid())\n        {\n            int value = 0;\n            const MultivariateEvent* mevent = generator->event();\n            for(Index component = 0, max_component = mevent->size(); component < max_component; ++component)\n            {\n                const UnivariateEvent* uevent = mevent->get(component);\n                if(uevent && uevent->get_outcome() == DISCRETE && uevent->get_event() == ELEMENTARY)\n                { value += static_cast< const DiscreteElementaryEvent* >(uevent)->get_value(); }\n            }\n            DiscreteElementaryEvent* sum_event = new DiscreteElementaryEvent(value);\n            sum_data->add_event(sum_event);\n            ++(*generator);\n        }\n        WeightedUnivariateData weighted_sum_data = WeightedUnivariateData(sum_data);\n        Index index = 0;\n        generator = data.generator();\n        while(generator->is_valid())\n        {\n            weighted_sum_data.set_weight(index, generator->weight());\n            ++index;\n            ++(*generator);\n        }\n        DiscreteUnivariateDistributionEstimation* sum = static_cast< DiscreteUnivariateDistributionEstimation* >(((*_sum)(weighted_sum_data, lazy)).release());\n        delete sum_data;\n        SingularDistributionEstimation* singular = (*_singular)(data, lazy).release();\n        SplittingDistribution* estimated = new SplittingDistribution(*(static_cast< const DiscreteUnivariateDistribution* >(sum->get_estimated())), *(singular->get_estimated()));\n        std::unique_ptr< MultivariateDistributionEstimation > estimation;\n        if(lazy)\n        { \n            estimation = std::make_unique< LazyEstimation< SplittingDistribution, DiscreteMultivariateDistributionEstimation > >(estimated);\n            if(sum)\n            { delete sum; }\n            if(singular)\n            { delete singular; }\n        }\n        else\n        {\n            estimation = std::make_unique< SplittingDistributionEstimation >(estimated, &data);\n            static_cast< SplittingDistributionEstimation* >(estimation.get())->_sum = sum;\n            static_cast< SplittingDistributionEstimation* >(estimation.get())->_singular = singular;\n        }\n        return estimation;\n    }\n\n    const DiscreteUnivariateDistributionEstimation::Estimator* SplittingDistributionEstimation::Estimator::get_sum() const\n    { return _sum; }\n\n    void  SplittingDistributionEstimation::Estimator::set_sum(const DiscreteUnivariateDistributionEstimation::Estimator& sum)\n    {\n        if(_sum)\n        { delete _sum; }\n        _sum = static_cast< DiscreteUnivariateDistributionEstimation::Estimator* >(sum.copy().release());\n    }\n\n    const SingularDistributionEstimation::Estimator* SplittingDistributionEstimation::Estimator::get_singular() const\n    { return _singular; }\n\n    void SplittingDistributionEstimation::Estimator::set_singular(const SingularDistributionEstimation::Estimator& singular)\n    { \n        if(_singular)\n        { delete _singular; }\n        _singular = static_cast< SingularDistributionEstimation::Estimator* >(singular.copy().release());\n    }\n\n    std::unordered_set< uintptr_t > SplittingDistributionEstimation::Estimator::children() const\n    {\n        std::unordered_set< uintptr_t > ch;\n        ch.insert(compute_identifier(*_sum));\n        __impl::merge(ch, compute_children(*_sum));\n        ch.insert(compute_identifier(*_singular));\n        __impl::merge(ch, compute_children(*_singular));\n        return ch;\n    }\n\n    NegativeMultinomialDistributionEstimation::NegativeMultinomialDistributionEstimation() : OptimizationEstimation<double, SplittingDistribution, DiscreteMultivariateDistributionEstimation >()\n    {}\n   \n    NegativeMultinomialDistributionEstimation::NegativeMultinomialDistributionEstimation(SplittingDistribution const * estimated, MultivariateData const * data) : OptimizationEstimation<double, SplittingDistribution, DiscreteMultivariateDistributionEstimation >(estimated, data)\n    {}\n\n    NegativeMultinomialDistributionEstimation::NegativeMultinomialDistributionEstimation(const NegativeMultinomialDistributionEstimation& estimation) : OptimizationEstimation<double, SplittingDistribution, DiscreteMultivariateDistributionEstimation >(estimation)\n    {}\n\n    NegativeMultinomialDistributionEstimation::~NegativeMultinomialDistributionEstimation()\n    {}\n\n    NegativeMultinomialDistributionEstimation::WZ99Estimator::WZ99Estimator() : OptimizationEstimation<double, SplittingDistribution, DiscreteMultivariateDistributionEstimation >::Estimator()\n    {}\n\n    NegativeMultinomialDistributionEstimation::WZ99Estimator::WZ99Estimator(const WZ99Estimator& estimator) : OptimizationEstimation<double, SplittingDistribution, DiscreteMultivariateDistributionEstimation >::Estimator(estimator)\n    {}\n\n    NegativeMultinomialDistributionEstimation::WZ99Estimator::~WZ99Estimator()\n    {}\n\n    std::unique_ptr< MultivariateDistributionEstimation > NegativeMultinomialDistributionEstimation::WZ99Estimator::operator() (const MultivariateData& data, const bool& lazy) const\n    {\n        const MultivariateSampleSpace* sample_space = data.get_sample_space();\n        for(Index index = 0, max_index = sample_space->size(); index < max_index; ++index)\n        {\n            if(sample_space->get(index)->get_outcome() != DISCRETE)\n            { throw statiskit::sample_space_error(DISCRETE); }\n        }\n        std::unique_ptr< MultivariateDistributionEstimation > estimation;\n        MultivariateMeanEstimation::Estimator mean_estimator = MultivariateMeanEstimation::Estimator();\n        std::unique_ptr< MultivariateLocationEstimation > mean_estimation = mean_estimator(data);\n        Eigen::VectorXd mean = mean_estimation->get_location();\n        MultivariateVarianceEstimation::Estimator covariance_estimator = MultivariateVarianceEstimation::Estimator();\n        std::unique_ptr< MultivariateDispersionEstimation > covariance_estimation = covariance_estimator(data, mean);\n        Eigen::MatrixXd covariance = covariance_estimation->get_dispersion();\n        double total = data.compute_total(), kappa;\n        double _location = mean.sum(), variance = 0.;\n        for(Index i = 0, max_i = sample_space->size(); i < max_i; ++i)\n        {\n            for(Index j = 0; j <= i; ++j)\n            { variance += covariance(i, j); }\n        }\n        if(variance > _location)\n        { kappa = pow(_location, 2)/(variance - _location); }\n        else\n        { kappa = 1.; }\n        double q =  _location / (_location + kappa);\n        NegativeBinomialDistribution negative_binomial = NegativeBinomialDistribution(kappa, 1. - q);\n        SplittingDistribution* negative_multinomial = new SplittingDistribution(negative_binomial, MultinomialSingularDistribution(mean * q / kappa));\n        if(!lazy)\n        {\n            estimation = std::make_unique< NegativeMultinomialDistributionEstimation >(negative_multinomial, &data);\n            static_cast< NegativeMultinomialDistributionEstimation* >(estimation.get())->_iterations.push_back(kappa);\n        }\n        else\n        { estimation = std::make_unique< LazyEstimation< SplittingDistribution, DiscreteMultivariateDistributionEstimation > >(negative_multinomial); }\n        double prev, curr = kappa; //negative_multinomial->loglikelihood(data);\n        unsigned int its = 1;\n        double chisq = 0.;\n        std::unique_ptr< MultivariateData::Generator > generator = data.generator();\n        while(generator->is_valid())\n        {\n            const MultivariateEvent* event = generator->event();\n            if(event)\n            {\n                for(Index index = 0, max_index = event->size(); index < max_index; ++index)\n                {\n                    const UnivariateEvent* uevent = event->get(index); \n                    if(uevent && uevent->get_event() == ELEMENTARY)\n                    { chisq += generator->weight() / total * pow(static_cast< const DiscreteElementaryEvent* >(uevent)->get_value() - mean(index), 2.) / mean(index); }\n                }\n            }\n            ++(*generator);\n        }        \n        do\n        {\n            prev = curr;\n            double _chisq = 0;\n            generator = data.generator();\n            while(generator->is_valid())\n            {\n                const MultivariateEvent* event = generator->event();\n                if(event)\n                {\n                    for(Index index = 0, max_index = event->size(); index < max_index; ++index)\n                    {\n                        const UnivariateEvent* uevent = event->get(index); \n                        if(uevent && uevent->get_event() == ELEMENTARY)\n                        { _chisq += generator->weight() / total * pow(static_cast< const DiscreteElementaryEvent* >(uevent)->get_value() - mean(index), 2.) / (mean(index) * (1 + mean(index) / kappa)); }\n                    }\n                }\n                ++(*generator);\n            }    \n            kappa *= chisq / _chisq;\n            if(kappa > 0.)\n            {\n                if(!lazy)\n                { static_cast< NegativeMultinomialDistributionEstimation* >(estimation.get())->_iterations.push_back(kappa); }\n                negative_binomial.set_kappa(kappa);\n                q =  _location / (_location + kappa);\n                negative_binomial.set_pi(1. - q);\n                negative_multinomial->set_sum(negative_binomial);\n                static_cast< MultinomialSingularDistribution* >(negative_multinomial->get_singular())->set_pi(mean * q / kappa);\n                // curr = negative_multinomial->loglikelihood(data);\n                curr = kappa;\n                ++its;\n            }\n        } while(run(its, __impl::reldiff(prev, curr)));\n        return estimation;\n    }\n\n    std::unique_ptr< MultivariateDistributionEstimation::Estimator > NegativeMultinomialDistributionEstimation::WZ99Estimator::copy() const\n    { return std::make_unique< NegativeMultinomialDistributionEstimation::WZ99Estimator >(*this); }\n}\n", "meta": {"hexsha": "ceb81488e9ea9de7de48dc2754c7d34930c631d1", "size": 65765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/estimator.cpp", "max_stars_repo_name": "StatisKit/Core", "max_stars_repo_head_hexsha": "79d8ec07c203eb7973a6cf482852ddb2e8e1e93e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/estimator.cpp", "max_issues_repo_name": "StatisKit/Core", "max_issues_repo_head_hexsha": "79d8ec07c203eb7973a6cf482852ddb2e8e1e93e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-03-20T14:23:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-09T11:57:57.000Z", "max_forks_repo_path": "src/cpp/estimator.cpp", "max_forks_repo_name": "StatisKit/Core", "max_forks_repo_head_hexsha": "79d8ec07c203eb7973a6cf482852ddb2e8e1e93e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-04-28T07:41:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T18:17:20.000Z", "avg_line_length": 52.0292721519, "max_line_length": 331, "alphanum_fraction": 0.6715578195, "num_tokens": 14306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4320058536611051}}
{"text": "#include <string>\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <stdio.h>\n#include <cstdio>\n#include <ctime>\n#include <chrono>\n#include <vector>\n#include <climits>\n#include <utility>                          // for std::pair\n#include \"algo.hh\"\n\n//includes from boost librabry\n#include <boost/config.hpp>\n#include <boost/utility.hpp>                // for boost::tie\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/property_map/property_map.hpp>\n\n#define OUTPUT 0\n\nusing namespace std;\nusing namespace boost;\n\ntemplate<class F, class T>\nvoid dijkstra(const vector<F> &graph, int root, vector<T> &dist);\n\n/* Reads data from a gph-file\n * and computes the longest shortest path\n * to the vertex 1.\n * The boost-graph library is used for\n * the shortest path computation.\n * \n */\npair<int,int> algo1(char* filename){\n  \n  ifstream    file(filename);\n  string      line;\n  \n  if(!file){\n    cout << \"Could not open file\" << endl;\n    exit(EXIT_FAILURE);\n  }\n  \n  //property weighted graph\n  typedef property <edge_weight_t, int> EdgeWeightProperty;\n  //typedef for graph type: undirected, weighted graph\n  typedef adjacency_list <listS, vecS, undirectedS, no_property, EdgeWeightProperty> BoostGraph;\n  //typedef to describe vertecies in boost library\n  typedef graph_traits <BoostGraph>::vertex_descriptor vertex_descriptor;\n  //typedef for edges in the graph\n  typedef pair<int, int> VPair;\n  \n  //read number of vertices and edges\n  getline(file, line, ' ');\n  const int numV = stoi(line);\n  getline(file, line, '\\n');\n  const int numE = stoi(line);\n#if OUTPUT\n  fprintf(stdout, \"number of vertices: %i | number of edges: %i\\n\",  numV, numE);\n  fprintf(stdout, \"Edges \\t\\t Weight\\n\");\n  fprintf(stdout, \"---- \\t\\t ----\\n\");\n#endif\n  \n  VPair* edges;          //edges as pair of vertices\n  int*  weights;         //weights of an edge\n\n  try{\n    //dynamic memory allocation\n    edges   = new VPair [numE];\n    weights = new int [numE];\n\n  } catch (bad_alloc& ba) {\n    fprintf(stderr, \"Too many edges. try a smaller graph\");\n  }\n  \n  int edgecount = 0;\n  \n  //loop over all lines in the file\n  while( getline(file, line) ){\n\n    stringstream linestream(line);\n    string       vertex1, vertex2, weight;\n\n    try{\n      getline(linestream, vertex1, ' ');\n      getline(linestream, vertex2, ' ');\n      getline(linestream, weight, '\\n');\n\n      edges[edgecount] = VPair(stoi(vertex1), stoi(vertex2));    //store edges as pairs of vertices\n      weights[edgecount] = stoi(weight);                         //store corresponding weights\n\n      #if OUTPUT\n      fprintf(stdout, \"(%i,%i) \\t\\t %i \\n\", edges[edgecount].first, edges[edgecount].second, weights[edgecount]);\n      #endif\n\n    } catch (invalid_argument& ia){\n      //when data is not a digit,\n      //std::stoi throws an invalid argument exception\n    } catch ( ... ){}\n\n    edgecount++;\n  }//while\n\n  file.close();\n\n  //create graph containig edges and weights\n  BoostGraph g (edges, edges + numE, weights, numV);\n\n  //setup for shortest path solver\n  property_map<BoostGraph, edge_weight_t>::type weightmap = get(edge_weight, g);\n  vector<vertex_descriptor> pre(num_vertices(g));\n  //vector to store distances to source vertex\n  vector<int> dist(num_vertices(g));\n  //define source vertex to which shortest path shall be\n  //computed from all other vertecies in graph g\n  vertex_descriptor source = vertex(edges[0].first, g);\n\n  //use dijkstra algorithm, since all edges are positive\n  dijkstra_shortest_paths(g, source,\n                          predecessor_map(make_iterator_property_map(pre.begin(), get(vertex_index, g))).\n                          distance_map(make_iterator_property_map(dist.begin(), get(vertex_index, g))));\n\n  delete[] edges;\n  delete[] weights;\n  \n  int maxdist = 0;\n  int vertex  = 0;\n\n  //iterate over all vertecies and update\n  //maximum disntance, if needed\n  graph_traits < BoostGraph >::vertex_iterator vi, vend;\n  tie(vi, vend) = vertices(g);\n  vi++;\n  for (; vi != vend; ++vi) {\n\n    if(dist[*vi] > maxdist){\n      maxdist = dist[*vi];\n      vertex  = *vi;\n    }\n  }\n  \n  return VPair(vertex, maxdist);\n  \n}\n\n\n\n\n/* Reads data from a gph-file\n * and computes the longest shortest path\n * to vertex with index 1.\n * This method uses a self-written\n * Dijkstra-algorithm.\n * \n */\npair<int,int> algo2(char*filename){\n  \n  ifstream    file(filename);\n  string      line;\n\n  if(!file){\n    cout << \"Could not open file\" << endl;\n    exit(EXIT_FAILURE);\n  }\n  \n  typedef int vertex_;\n  typedef int weight_;\n\n  /* Edge\n   * pair of ints containing the weight and\n   * the vertex pointed to. This is useful\n   * for the adjacency list\n   */\n  typedef pair<vertex_, weight_> Edge;\n\n  /* Graph\n   * An adjacency list representing the graph.\n   * graph[i] returns a list with Edge elements.\n   */\n  typedef vector< vector<Edge> > Graph;\n  \n  //read number of vertices and edges\n   getline(file, line, ' ');\n   const int numV = stoi(line);\n   getline(file, line, '\\n');\n   const int numE = stoi(line);\n   \n #if OUTPUT\n   fprintf(stdout, \"number of vertices: %i | number of edges: %i\\n\",  numV, numE);\n   fprintf(stdout, \"Edges \\t\\t Weight\\n\");\n   fprintf(stdout, \"---- \\t\\t ----\\n\");\n #endif\n\n\n   Graph graph(numV);\n\n   int  edgecount = 0;\n   //loop over all lines in the file\n   while( getline(file, line) ){\n\n     stringstream linestream(line);\n     string       vertex1, vertex2, weight;\n\n     try{\n       getline(linestream, vertex1, ' ');\n       getline(linestream, vertex2, ' ');\n       getline(linestream, weight, '\\n');\n\n       //add both directions, since undirected graph\n       graph[stoi(vertex1)-1].push_back(Edge(stoi(vertex2)-1, stoi(weight)));\n       graph[stoi(vertex2)-1].push_back(Edge(stoi(vertex1)-1, stoi(weight)));\n\n     } catch (invalid_argument& ia){\n       //when data is not a digit,\n       //std::stoi throws an invalid argument exception\n     } catch ( ... ){}\n\n     edgecount++;\n   }//while\n\n   file.close();\n\n   int maxdist = 0;\n   int vertex  = 0;\n  \n   //initialize distance\n   vector<weight_> dist(numV, INT_MAX);\n\n   dijkstra<vector<Edge>, weight_>(graph, 0,  dist);\n\n   for(uint i = 0; i < dist.size(); ++i){\n     if(dist[i] > maxdist){\n       maxdist = dist[i];\n       vertex  = i+1;\n     }\n   }\n  \n   return pair<int,int>(vertex, maxdist);\n  \n}\n\ntemplate<class F, class T>\nvoid dijkstra(const vector<F> &graph, int root, vector<T> &dist) {\n  \n  typedef pair<int,int> Edge;\n\n  /* A set helps insertion and insert/erase/find operations in logarithmic time.\n   * This set maintains Edge(distance,vertex number) sorted on basis of distance\n   */\n  set< Edge > pq;\n  set< Edge > ::iterator it;\n\n  int u,v,wt;\n\n  dist[root] = 0;\n  pq.insert(Edge(root,0));\n\n  while(pq.size() != 0){\n    it = pq.begin();\n    u = it->first;\n    pq.erase(it);\n\n    for(vector<Edge>::const_iterator i = graph[u].begin(); i != graph[u].end(); i++){\n      v  = i->first;\n      wt = i->second;\n\n      if(dist[v] > dist[u] + wt){\n        if(dist[v] != INT_MAX){\n          pq.erase(Edge(v,dist[v]));\n        }\n        dist[v] = dist[u] + wt;\n        pq.insert(Edge(v,dist[v]));\n      }\n    }\n  }//while\n\n} //dijkstra", "meta": {"hexsha": "7da2d6c6906f4a45b6760f586f541c3daea9f9b0", "size": 7181, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Baumann/ex5/algo.cc", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Baumann/ex5/algo.cc", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Baumann/ex5/algo.cc", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 25.7383512545, "max_line_length": 113, "alphanum_fraction": 0.6301350787, "num_tokens": 1898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6297746004557471, "lm_q1q2_score": 0.4319935439606219}}
{"text": "/*\n *            Copyright 2009-2020 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n// Third party includes\n#include <boost/format.hpp>\n\n// VOTCA includes\n#include <votca/tools/elements.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/gyration.h\"\n#include \"votca/xtp/vxc_grid.h\"\n\nusing namespace votca::tools;\n\nnamespace votca {\nnamespace xtp {\n\nvoid Density2Gyration::Initialize(tools::Property& options) {\n  std::string key = Identify();\n\n  std::string statestring = options.get(key + \".state\").as<std::string>();\n  _state.FromString(statestring);\n  _dostateonly = options.ifExistsReturnElseReturnDefault<bool>(\n      key + \".difference_to_groundstate\", false);\n  _gridsize = options.ifExistsReturnElseReturnDefault<std::string>(\n      key + \".gridsize\", \"medium\");\n}\n\nvoid Density2Gyration::AnalyzeDensity(const Orbitals& orbitals) {\n  XTP_LOG(Log::error, _log) << \"===== Running on \" << OPENMP::getMaxThreads()\n                            << \" threads ===== \" << std::flush;\n\n  const QMMolecule& Atomlist = orbitals.QMAtoms();\n  BasisSet bs;\n  bs.Load(orbitals.getDFTbasisName());\n  AOBasis basis;\n  basis.Fill(bs, Atomlist);\n  AnalyzeGeometry(Atomlist);\n\n  // setup numerical integration grid\n  Vxc_Grid grid;\n  grid.GridSetup(_gridsize, Atomlist, basis);\n  DensityIntegration<Vxc_Grid> numway(grid);\n\n  if (!_dostateonly) {\n    Eigen::MatrixXd DMAT_tot = orbitals.DensityMatrixFull(_state);\n    Gyrationtensor gyro = numway.IntegrateGyrationTensor(DMAT_tot);\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;\n    es.computeDirect(gyro.gyration);\n    XTP_LOG(Log::error, _log)\n        << TimeStamp() << \" Converting to Eigenframe \" << std::flush;\n    XTP_LOG(Log::error, _log) << TimeStamp() << \" Reporting \" << std::flush;\n    ReportAnalysis(_state.ToLongString(), gyro, es);\n\n  } else {\n    // hole density first\n    std::array<Eigen::MatrixXd, 2> DMAT =\n        orbitals.DensityMatrixExcitedState(_state);\n    Gyrationtensor gyro_hole = numway.IntegrateGyrationTensor(DMAT[0]);\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es_h;\n    es_h.computeDirect(gyro_hole.gyration);\n    XTP_LOG(Log::error, _log)\n        << TimeStamp() << \" Converting to Eigenframe \" << std::flush;\n    XTP_LOG(Log::error, _log) << TimeStamp() << \" Reporting \" << std::flush;\n    ReportAnalysis(\"hole\", gyro_hole, es_h);\n\n    // electron density\n    Gyrationtensor gyro_electron = numway.IntegrateGyrationTensor(DMAT[1]);\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es_e;\n    es_e.computeDirect(gyro_electron.gyration);\n    XTP_LOG(Log::error, _log)\n        << TimeStamp() << \" Converting to Eigenframe \" << std::flush;\n    XTP_LOG(Log::error, _log) << TimeStamp() << \" Reporting \" << std::flush;\n    ReportAnalysis(\"electron\", gyro_electron, es_e);\n  }\n  return;\n}\n\nvoid Density2Gyration::AnalyzeGeometry(const QMMolecule& atoms) {\n\n  tools::Elements elements;\n  double mass = 0.0;\n  Eigen::Vector3d centroid = Eigen::Vector3d::Zero();\n  Eigen::Matrix3d gyration = Eigen::Matrix3d::Zero();\n  for (const QMAtom& atom : atoms) {\n    double m = elements.getMass(atom.getElement());\n    const Eigen::Vector3d& pos = atom.getPos();\n    mass += m;\n    centroid += m * pos;\n    gyration += m * pos * pos.transpose();\n  }\n  centroid /= mass;\n  gyration /= mass;\n  gyration -= centroid * centroid.transpose();\n  Gyrationtensor gyro;\n  gyro.mass = mass;\n  gyro.centroid = centroid;\n  gyro.gyration = gyration;\n  Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> es;\n  es.computeDirect(gyro.gyration);\n  ReportAnalysis(\"geometry\", gyro, es);\n}\n\nvoid Density2Gyration::ReportAnalysis(\n    std::string label, const Gyrationtensor& gyro,\n    const Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d>& es) {\n\n  XTP_LOG(Log::error, _log)\n      << \"---------------- \" << label << \" ----------------\" << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Norm               = %1$9.4f \") % (gyro.mass))\n      << std::flush;\n\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Centroid x         = %1$9.4f Ang\") %\n          (gyro.centroid.x() * tools::conv::bohr2ang))\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Centroid y         = %1$9.4f Ang\") %\n          (gyro.centroid.y() * tools::conv::bohr2ang))\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Centroid y         = %1$9.4f Ang\") %\n          (gyro.centroid.z() * tools::conv::bohr2ang))\n      << std::flush;\n\n  double RA2 = tools::conv::bohr2ang * tools::conv::bohr2ang;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Gyration Tensor xx = %1$9.4f Ang^2\") %\n          (gyro.gyration(0, 0) * RA2))\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Gyration Tensor xy = %1$9.4f Ang^2\") %\n          (gyro.gyration(0, 1) * RA2))\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Gyration Tensor xz = %1$9.4f Ang^2\") %\n          (gyro.gyration(0, 2) * RA2))\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Gyration Tensor yy = %1$9.4f Ang^2\") %\n          (gyro.gyration(1, 1) * RA2))\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Gyration Tensor yz = %1$9.4f Ang^2\") %\n          (gyro.gyration(1, 2) * RA2))\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Gyration Tensor zz = %1$9.4f Ang^2\") %\n          (gyro.gyration(2, 2) * RA2))\n      << std::flush;\n\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Gyration Tensor D1 = %1$9.4f Ang^2\") %\n          (es.eigenvalues()[0] * RA2))\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Gyration Tensor D2 = %1$9.4f Ang^2\") %\n          (es.eigenvalues()[1] * RA2))\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Gyration Tensor D3 = %1$9.4f Ang^2\") %\n          (es.eigenvalues()[2] * RA2))\n      << std::flush;\n\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Radius of Gyration = %1$9.4f Ang\") %\n          (std::sqrt(es.eigenvalues().sum()) * tools::conv::bohr2ang))\n      << std::flush;\n\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Tensor EF Axis 1 1 = %1$9.4f \") %\n          es.eigenvectors().col(0).x())\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Tensor EF Axis 1 2 = %1$9.4f \") %\n          es.eigenvectors().col(0).y())\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Tensor EF Axis 1 3 = %1$9.4f \") %\n          es.eigenvectors().col(0).z())\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Tensor EF Axis 2 1 = %1$9.4f \") %\n          es.eigenvectors().col(1).x())\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Tensor EF Axis 2 2 = %1$9.4f \") %\n          es.eigenvectors().col(1).y())\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Tensor EF Axis 2 3 = %1$9.4f \") %\n          es.eigenvectors().col(1).z())\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Tensor EF Axis 3 1 = %1$9.4f \") %\n          es.eigenvectors().col(2).x())\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Tensor EF Axis 3 2 = %1$9.4f \") %\n          es.eigenvectors().col(2).y())\n      << std::flush;\n  XTP_LOG(Log::error, _log)\n      << (boost::format(\"  Tensor EF Axis 3 3 = %1$9.4f \") %\n          es.eigenvectors().col(2).z())\n      << std::flush;\n}\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "60d5484ed5c4dd270df3faf8029e7f77f5d751a8", "size": 8059, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/gyration.cc", "max_stars_repo_name": "fossabot/xtp", "max_stars_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/gyration.cc", "max_issues_repo_name": "fossabot/xtp", "max_issues_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/gyration.cc", "max_forks_repo_name": "fossabot/xtp", "max_forks_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3464912281, "max_line_length": 77, "alphanum_fraction": 0.6021838938, "num_tokens": 2513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4319335632222488}}
{"text": "#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <math.h>\n#include <omp.h>\n#include <iostream>\n\n#include \"mvnormal.h\"\n#include \"linop.h\"\n#include \"bpmfutils.h\"\n#include \"macauoneprior.h\"\n\nusing namespace std; \nusing namespace Eigen;\n\ntemplate<class FType>\nvoid MacauOnePrior<FType>::init(const int nlatent, std::unique_ptr<FType> &Fmat) {\n  num_latent = nlatent;\n\n  // parameters of Normal-Gamma distributions\n  mu     = VectorXd::Constant(num_latent, 0.0);\n  lambda = VectorXd::Constant(num_latent, 10.0);\n  // their hyperparameter (lambda_0)\n  l0 = 2.0;\n  lambda_a0 = 1.0;\n  lambda_b0 = 1.0;\n\n  // side information\n  F       = std::move(Fmat);\n  F_colsq = col_square_sum(*F);\n\n  Uhat = MatrixXd::Constant(num_latent, F->rows(), 0.0);\n  beta = MatrixXd::Constant(num_latent, F->cols(), 0.0);\n\n  // initial value (should be determined automatically)\n  // Hyper-prior for lambda_beta (mean 1.0):\n  lambda_beta     = VectorXd::Constant(num_latent, 5.0);\n  lambda_beta_a0 = 0.1;\n  lambda_beta_b0 = 0.1;\n}\n\ntemplate<class FType>\nvoid MacauOnePrior<FType>::sample_latents(\n    Eigen::MatrixXd &U,\n    const Eigen::SparseMatrix<double> &Ymat,\n    double mean_value,\n    const Eigen::MatrixXd &V,\n    double alpha,\n    const int num_latent)\n{\n  const int N = U.cols();\n  const int D = U.rows();\n\n#pragma omp parallel for schedule(dynamic, 4)\n  for (int i = 0; i < N; i++) {\n\n    const int nnz = Ymat.outerIndexPtr()[i + 1] - Ymat.outerIndexPtr()[i];\n    VectorXd Yhat(nnz);\n\n    // precalculating Yhat and Qi\n    int idx = 0;\n    VectorXd Qi = lambda;\n    for (SparseMatrix<double>::InnerIterator it(Ymat, i); it; ++it, idx++) {\n      Qi.noalias() += alpha * V.col(it.row()).cwiseAbs2();\n      Yhat(idx)     = mean_value + U.col(i).dot( V.col(it.row()) );\n    }\n    VectorXd rnorms(num_latent);\n    bmrandn_single(rnorms);\n\n    for (int d = 0; d < D; d++) {\n      // computing Lid\n      const double uid = U(d, i);\n      double Lid = lambda(d) * (mu(d) + Uhat(d, i));\n\n      idx = 0;\n      for ( SparseMatrix<double>::InnerIterator it(Ymat, i); it; ++it, idx++) {\n        const double vjd = V(d, it.row());\n        // L_id += alpha * (Y_ij - k_ijd) * v_jd\n        Lid += alpha * (it.value() - (Yhat(idx) - uid*vjd)) * vjd;\n      }\n      // Now use Lid and Qid to update uid\n      double uid_old = U(d, i);\n      double uid_var = 1.0 / Qi(d);\n\n      // sampling new u_id ~ Norm(Lid / Qid, 1/Qid)\n      U(d, i) = Lid * uid_var + sqrt(uid_var) * rnorms(d);\n\n      // updating Yhat\n      double uid_delta = U(d, i) - uid_old;\n      idx = 0;\n      for (SparseMatrix<double>::InnerIterator it(Ymat, i); it; ++it, idx++) {\n        Yhat(idx) += uid_delta * V(d, it.row());\n      }\n    }\n  }\n}\n\ntemplate<class FType>\nvoid MacauOnePrior<FType>::sample_latents(\n        ProbitNoise& noiseModel,\n        TensorData & data,\n        std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples,\n        int mode,\n        const int num_latent)\n{\n  throw std::runtime_error(\"Unimplemented: sample_latents\");\n}\n\ntemplate<class FType>\nvoid MacauOnePrior<FType>::sample_latents(\n        double noisePrecision,\n        TensorData & data,\n        std::vector< std::unique_ptr<Eigen::MatrixXd> > & samples,\n        int mode,\n        const int num_latent)\n{\n  auto& sparseMode = (*data.Y)[mode];\n  auto& U = samples[mode];\n  const int N = U->cols();\n  const int D = num_latent;\n  VectorView<Eigen::MatrixXd> view(samples, mode);\n  const int nmodes1 = view.size();\n  const double mean_value = data.mean_value;\n\n  if (U->rows() != num_latent) {\n    throw std::runtime_error(\"U->rows() must be equal to num_latent.\");\n  }\n\n  Eigen::VectorXi & row_ptr = sparseMode->row_ptr;\n  Eigen::MatrixXi & indices = sparseMode->indices;\n  Eigen::VectorXd & values  = sparseMode->values;\n\n#pragma omp parallel for schedule(dynamic, 8)\n  for (int i = 0; i < N; i++) {\n    // looping over all non-zeros for row i of the mode\n    // precalculating Yhat and Qi\n    const int nnz = row_ptr(i + 1) - row_ptr(i);\n    VectorXd Yhat(nnz);\n    VectorXd tmpd(nnz);\n    VectorXd Qi = lambda;\n\n    for (int idx = 0; idx < nnz; idx++) {\n      int j = idx + row_ptr(i);\n      VectorXd prod = VectorXd::Ones(D);\n      for (int m = 0; m < nmodes1; m++) {\n        auto v = view.get(m)->col(indices(j, m));\n        prod.noalias() = prod.cwiseProduct(v);\n      }\n      Qi.noalias() += noisePrecision * prod.cwiseAbs2();\n      Yhat(idx) = mean_value + U->col(i).dot(prod);\n    }\n\n    // generating random numbers\n    VectorXd rnorms(num_latent);\n    bmrandn_single(rnorms);\n\n    for (int d = 0; d < D; d++) {\n      // computing Lid\n      const double uid = (*U)(d, i);\n      double Lid = lambda(d) * (mu(d) + Uhat(d, i));\n      \n      for (int idx = 0; idx < nnz; idx++) {\n        int j = idx + row_ptr(i);\n\n        // computing t = vjd * wkd * ..\n        double t = 1.0;\n        for (int m = 0; m < nmodes1; m++) {\n          t *= (*view.get(m))(d, indices(j, m));\n        }\n        tmpd(idx) = t;\n        // L_id += alpha * (Y_ijk - k_ijkd) * v_jd * wkd\n        Lid += noisePrecision * (values(j) - (Yhat(idx) - uid * t)) * t;\n      }\n      // Now use Lid and Qid to update uid\n      double uid_old = uid;\n      double uid_var = 1.0 / Qi(d);\n\n      // sampling new u_id ~ Norm(Lid / Qid, 1/Qid)\n      (*U)(d, i) = Lid * uid_var + sqrt(uid_var) * rnorms(d);\n\n      // updating Yhat\n      double uid_delta = (*U)(d, i) - uid_old;\n      for (int idx = 0; idx < nnz; idx++) {\n        Yhat(idx) += uid_delta * tmpd(idx);\n      }\n    }\n  }\n}\n\ntemplate<class FType>\nvoid MacauOnePrior<FType>::update_prior(const Eigen::MatrixXd &U) {\n  sample_mu_lambda(U);\n  sample_beta(U);\n  compute_uhat(Uhat, *F, beta);\n  sample_lambda_beta();\n}\n\ntemplate<class FType>\nvoid MacauOnePrior<FType>::sample_mu_lambda(const Eigen::MatrixXd &U) {\n  MatrixXd Lambda(num_latent, num_latent);\n  MatrixXd WI(num_latent, num_latent);\n  WI.setIdentity();\n  int N = U.cols();\n\n  MatrixXd Udelta(num_latent, N);\n#pragma omp parallel for schedule(static)\n  for (int i = 0; i < N; i++) {\n    for (int d = 0; d < num_latent; d++) {\n      Udelta(d, i) = U(d, i) - Uhat(d, i);\n    }\n  }\n  tie(mu, Lambda) = CondNormalWishart(Udelta, VectorXd::Constant(num_latent, 0.0), 2.0, WI, num_latent);\n  lambda = Lambda.diagonal();\n}\n\ntemplate<class FType>\nvoid MacauOnePrior<FType>::sample_beta(const Eigen::MatrixXd &U) {\n  // updating beta and beta_var\n  const int nfeat = beta.cols();\n  const int N = U.cols();\n  const int blocksize = 4;\n\n  MatrixXd Z;\n\n#pragma omp parallel for private(Z) schedule(static, 1)\n  for (int dstart = 0; dstart < num_latent; dstart += blocksize) {\n    const int dcount = std::min(blocksize, num_latent - dstart);\n    Z.resize(dcount, U.cols());\n\n    for (int i = 0; i < N; i++) {\n      for (int d = 0; d < dcount; d++) {\n        int dx = d + dstart;\n        Z(d, i) = U(dx, i) - mu(dx) - Uhat(dx, i);\n      }\n    }\n\n    for (int f = 0; f < nfeat; f++) {\n      VectorXd zx(dcount), delta_beta(dcount), randvals(dcount);\n      // zx = Z[dstart : dstart + dcount, :] * F[:, f]\n      At_mul_Bt(zx, *F, f, Z);\n      // TODO: check if sampling randvals for whole [nfeat x dcount] matrix works faster\n      bmrandn_single( randvals );\n\n      for (int d = 0; d < dcount; d++) {\n        int dx = d + dstart;\n        double A_df     = lambda_beta(dx) + lambda(dx) * F_colsq(f);\n        double B_df     = lambda(dx) * (zx(d) + beta(dx,f) * F_colsq(f));\n        double A_inv    = 1.0 / A_df;\n        double beta_new = B_df * A_inv + sqrt(A_inv) * randvals(d);\n        delta_beta(d)   = beta(dx,f) - beta_new;\n\n        beta(dx, f)     = beta_new;\n      }\n      // Z[dstart : dstart + dcount, :] += F[:, f] * delta_beta'\n      add_Acol_mul_bt(Z, *F, f, delta_beta);\n    }\n  }\n}\n\ntemplate<class FType>\nvoid MacauOnePrior<FType>::sample_latents(ProbitNoise & noise, Eigen::MatrixXd &U, const Eigen::SparseMatrix<double> &mat,\n                                          double mean_value, const Eigen::MatrixXd &samples, const int num_latent) {\n //TODO\n throw std::runtime_error(\"Not implemented!\");\n}\n\ntemplate<class FType>\nvoid MacauOnePrior<FType>::sample_lambda_beta() {\n  double lambda_beta_a = lambda_beta_a0 + beta.cols() / 2.0;\n  VectorXd lambda_beta_b = VectorXd::Constant(beta.rows(), lambda_beta_b0);\n  const int D = beta.rows();\n  const int F = beta.cols();\n#pragma omp parallel\n  {\n    VectorXd tmp(D);\n    tmp.setZero();\n#pragma omp for schedule(static)\n    for (int f = 0; f < F; f++) {\n      for (int d = 0; d < D; d++) {\n        tmp(d) += square(beta(d, f));\n      }\n    }\n#pragma omp critical\n    {\n      lambda_beta_b += tmp / 2;\n    }\n  }\n  for (int d = 0; d < D; d++) {\n    lambda_beta(d) = rgamma(lambda_beta_a, 1.0 / lambda_beta_b(d));\n  }\n}\n\ntemplate<class FType>\nvoid MacauOnePrior<FType>::saveModel(std::string prefix) {\n  writeToCSVfile(prefix + \"-latentmean.csv\", mu);\n  writeToCSVfile(prefix + \"-link.csv\", beta);\n}\n\ntemplate class MacauOnePrior<SparseFeat>;\ntemplate class MacauOnePrior<SparseDoubleFeat>;\n", "meta": {"hexsha": "00c997049ae1713c66e53a283ca8a328298b141a", "size": 8940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/macau-cpp/macauoneprior.cpp", "max_stars_repo_name": "jaak-s/macau", "max_stars_repo_head_hexsha": "99e31452bbc302ab9967070c1d8e44d3008f19cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2016-02-27T22:18:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:17:39.000Z", "max_issues_repo_path": "lib/macau-cpp/macauoneprior.cpp", "max_issues_repo_name": "potatopaul/macau", "max_issues_repo_head_hexsha": "dadf9d5da67c89d541d972663edc44af7b23d287", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-05-23T14:14:53.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-16T08:12:40.000Z", "max_forks_repo_path": "lib/macau-cpp/macauoneprior.cpp", "max_forks_repo_name": "potatopaul/macau", "max_forks_repo_head_hexsha": "dadf9d5da67c89d541d972663edc44af7b23d287", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T12:13:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T15:05:59.000Z", "avg_line_length": 29.8, "max_line_length": 122, "alphanum_fraction": 0.594966443, "num_tokens": 2741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956580903722561, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4319335632222488}}
{"text": "#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include <stdio.h>\n#include <math.h>\n\n#include <cmath>\n#include <memory>\n#include <vector>\n#include <limits>\n#include <random>\n#include <cmath>\n\n#include \"statespace.hpp\"\n\nusing namespace boost::numeric::ublas;\n\n\nint udu(matrix<double> &M_mat, matrix<double> &U_mat, vector<double> &d_vec, unsigned int state_size) {\n\n  unsigned int n = M_mat.size1();\n  double *M = &(M_mat(0,0));\n  double *U = &(U_mat(0,0));\n  double *d = &(d_vec(0));\n\n  // this method stolen from pykalman.sqrt.bierman by Daniel Duckworth (BSD license)\n  /*Construct the UDU' decomposition of a positive, semidefinite matrix M\n\n    Parameters\n    ----------\n    M : [n, n] array\n        Matrix to factorize\n\n    Returns\n    -------\n    UDU : UDU_decomposition of size n\n        UDU' representation of M\n  */\n\n\n\n  // make M upper triangular\n  for (unsigned i=0; i < state_size; ++i) {\n    for (unsigned idx=i*n; idx < i*n+i; ++idx) {\n      M[idx] = 0;\n    }\n  }\n\n  // initialize U as the identity\n  for (unsigned i=0; i < state_size; ++i) {\n    for (unsigned idx=i*n; idx < i*n+state_size; ++idx) {\n      U[idx] = 0;\n    }\n  }\n  for (unsigned i=0; i < state_size; ++i) {\n    U[i*n+i] = 1;\n  }\n\n  // note j cannot be unsigned, to handle state_size=0\n  for (int j=state_size-1; j >= 1; --j) {\n    d[j] = M[j*n+j];\n    double alpha = 0.0;\n    double beta = 0.0;\n    if (d[j] > 0) {\n      alpha = 1.0 / d[j];\n    } else {\n      if (fabs(d[j] > 1e-5) ) {\n\tprintf(\"WARNING: nonpositive d[%d] %f in udu decomp\\n\", j, d[j]);\n\treturn -1;\n      }\n      d[j] = 0.0;\n      alpha = 0.0;\n    }\n    for (unsigned k=0; k < j; ++k) {\n      beta = M[k*n+ j ];\n      U[k*n+ j] = alpha * beta;\n      for (unsigned kk=0; kk <= k; ++kk) {\n\tM[kk*n+ k] = M[kk*n+k] - beta * U[kk*n+j];\n      }\n    }\n  }\n  d[0] = M[0];\n\n  if (d[0] < 0) {\n    printf(\"ERROR: udu decomposition on non-posdef matrix with M(0,0)=%f\\n\", M[0]);\n    return -1;\n  }\n  return 0;\n}\n\n\nFilterState::FilterState(int max_dimension, double eps_stationary) {\n  this->eps_stationary = eps_stationary;\n  this->at_fixed_point=false;\n  this->alpha = 0;\n  this->wasnan = false;\n\n  this->obs_U = matrix<double>(max_dimension, max_dimension);\n  this->pred_U = matrix<double>(max_dimension, max_dimension);\n  this->tmp_U1 = matrix<double>(max_dimension, max_dimension);\n  this->tmp_U2 = matrix<double>(max_dimension, max_dimension);\n\n  // we only ever write to the upper triangle of this matrix, so\n  // zeroing the full matrix now guarantees that it will always be zero.\n  this->obs_U.clear();\n  this->pred_U.clear();\n  this->tmp_U1.clear();\n  this->tmp_U2.clear();\n\n  this->P = matrix<double>(max_dimension, max_dimension);\n\n  this->obs_d = vector<double>(max_dimension);\n  this->pred_d = vector<double>(max_dimension);\n  this->obs_d.clear();\n  this->pred_d.clear();\n\n  this->gain = vector<double>(max_dimension);\n  this->f = vector<double>(max_dimension);\n  this->v = vector<double>(max_dimension);\n\n  this->xk = vector<double>(max_dimension);\n}\n\nvoid print_vec(const vector<double> & v) {\n  for(unsigned i=0; i < v.size(); ++i) {\n    printf(\"%.3f \", v(i));\n  }\n  printf(\"\\n\");\n}\n\nvoid print_mat(const matrix<double> & m) {\n  for(unsigned i=0; i < m.size1(); ++i) {\n    for(unsigned j=0; j < m.size2(); ++j) {\n      printf(\"%.3f \", m(i,j));\n    }\n    printf(\"\\n\");\n  }\n  printf(\"\\n\");\n}\n\nvoid write_vec(const char *fname, const vector<double> & v) {\n  FILE *f = fopen(fname, \"w\");\n  if (f == NULL)\n    {\n      printf(\"Error opening file!\\n\");\n      exit(1);\n    }\n  for(unsigned i=0; i < v.size(); ++i) {\n    fprintf(f, \"%.12f \", v(i));\n  }\n  fprintf(f, \"\\n\");\n  fclose(f);\n\n}\n\n\nvoid write_mat_col(const char *fname, const matrix<double> & m) {\n\n  FILE *f = fopen(fname, \"w\");\n  if (f == NULL)\n    {\n      printf(\"Error opening file!\\n\");\n      exit(1);\n    }\n\n  for(unsigned i=0; i < m.size1(); ++i) {\n    for(unsigned j=0; j < m.size2(); ++j) {\n      fprintf(f, \"%.12f \", m(i,j));\n    }\n    fprintf(f, \"\\n\");\n  }\n  fprintf(f, \"\\n\");\n\n  fclose(f);\n}\n\nvoid write_stuff(const char *item, unsigned int k, const vector<double> & v) {\n  char fname[100];\n  snprintf(fname, 100, \"matrices/%s_c_%d.txt\", item, k);\n  write_vec(fname, v);\n}\n\nvoid write_stuff(const char *item, unsigned int k, const matrix<double> & m) {\n  char fname[100];\n  snprintf(fname, 100, \"matrices/%s_c_%d.txt\", item, k);\n  write_mat_col(fname, m);\n}\n\n\nvoid print_mat_col(const matrix<double> & m) {\n  for(unsigned i=0; i < m.size1(); ++i) {\n    for(unsigned j=0; j < m.size2(); ++j) {\n      printf(\"%.3f \", m(i,j));\n    }\n    printf(\"\\n\");\n  }\n  printf(\"\\n\");\n}\n\n\n#include <cblas.h>\nvoid compute_explicit_cov_atlas(FilterState &cache,\n\t\t\t\tmatrix<double> &U,\n\t\t\t\tvector<double> &d,\n\t\t\t\tint prev_state_size) {\n\n  matrix<double> &mtmp = cache.tmp_U2;\n  matrix<double> &P = cache.P;\n  unsigned state_size = cache.state_size;\n\n  if (prev_state_size == -1) {\n    prev_state_size = state_size;\n  }\n\n  // U has dimension (ss x pss)\n  for (unsigned i=0; i < state_size; ++i) {\n    for (unsigned j=0; j < prev_state_size; ++j) {\n      mtmp(i,j) = U(i,j) * d(j);\n    }\n  }\n\n  cblas_dgemm(CblasRowMajor,\n\t      CblasNoTrans,\n\t      CblasTrans,\n\t      state_size,  state_size, prev_state_size, 1.0,\n\t      &(mtmp(0,0)), mtmp.size2(),\n\t      &(U(0,0)), U.size2(),\n\t      0.0, &(P(0,0)), P.size2());\n\n}\n\n/* void compute_explicit_cov(FilterState &cache,\n\t\t\t  matrix<double> &U_tmp,\n\t\t\t  vector<double> &d_tmp,\n\t\t\t  int prev_state_size) {\n\n  // this is the original version of this function in ublas.\n  // it's slow and superceded by the atlas version above.\n\n  matrix<double> &mtmp = cache.tmp_U2;\n  matrix<double> &P = cache.P;\n  unsigned state_size = cache.state_size;\n\n  if (prev_state_size == -1) {\n    prev_state_size = state_size;\n  }\n\n  // construct the cov matrix\n  for (unsigned i=0; i < prev_state_size; ++i) {\n    subrange(mtmp, 0, state_size, i, i+1) = subrange(U_tmp, 0, state_size, i, i+1);\n    subrange(mtmp, 0, state_size, i, i+1) *= d_tmp(i);\n  }\n  noalias(subrange(P, 0, state_size, 0, state_size))\t\t\\\n    = prod(subrange(mtmp, 0, state_size, 0, prev_state_size),\n\t   trans(subrange(U_tmp, 0, state_size, 0, prev_state_size)));\n} */\n\n\n\nvoid FilterState::init_priors(StateSpaceModel &ssm) {\n  this->pred_d.clear();\n  this->xk.clear();\n\n  this->state_size = ssm.prior_mean(&(this->xk(0)));\n  this->state_size = ssm.prior_vars(&(this->pred_d(0)));\n\n  this->pred_U.clear();\n  for (unsigned i=0; i < ssm.max_dimension; ++i) {\n    this->pred_U(i,i) = 1;\n  }\n\n  return;\n}\n\nvoid FilterState::init_incremental_state(StateSpaceModel &ssm, int k) {\n  /*\n    Initialize the state to a high-variance prior on the state variables\n    active at some (nonzero) step k. This allows us to start filtering\n    somewhere other than the beginning of the sequence.\n   */\n\n  this->pred_d.clear();\n  this->xk.clear();\n  this->state_size = ssm.state_size_at_timestep(k);\n\n  for (unsigned i=0; i < ssm.max_dimension; ++i) {\n    this->pred_d(i) = 1e8;\n  }\n\n  this->pred_U.clear();\n  for (unsigned i=0; i < ssm.max_dimension; ++i) {\n    this->pred_U(i,i) = 1;\n  }\n\n  return;\n}\n\n\ndouble kalman_observe_sqrt(StateSpaceModel &ssm, FilterState &cache, int k, double zk) {\n\n  // if needed, use this for isnan: #include <boost/math/special_functions/fpclassify.hpp>\n  if (std::isnan(zk)) {\n    // printf(\"declaring nan at timestep %d, val %f\\n\", k, zk);\n    if (!cache.wasnan && cache.at_fixed_point) {\n       cache.at_fixed_point = false;\n    }\n    cache.wasnan = true;\n\n    // no observation, so the predicted state becomes the \"observed\" state\n    cache.obs_d = cache.pred_d;\n    cache.obs_U = cache.pred_U;\n\n    return 0;\n  } else {\n    if (cache.wasnan && cache.at_fixed_point) {\n       cache.at_fixed_point = false;\n    }\n    cache.wasnan = false;\n  }\n\n  double alpha = cache.alpha;\n  unsigned int state_size = cache.state_size;\n  if (!cache.at_fixed_point || !ssm.stationary(k)) {\n    cache.at_fixed_point = false;\n\n    matrix<double> &U_old = cache.pred_U;\n    vector<double> &d_old = cache.pred_d;\n\n    matrix<double> &U = cache.obs_U;\n    vector<double> &d = cache.obs_d;\n    vector<double> &K = cache.gain;\n    vector<double> &f = cache.f;\n    vector<double> &v = cache.v;\n    double r = ssm.observation_noise(k);\n\n    K.clear();\n\n    ssm.apply_observation_matrix(U_old, 0,\n\t\t\t\t k, &(f(0)), &(v(0)), state_size);\n\n\n\n    for (unsigned i=0; i < state_size; ++i) {\n      v(i) = d_old(i)*f(i);\n    }\n\n\n    D(write_stuff(\"U_obs_old\", k, U_old);)\n      D(write_stuff(\"d_obs_old\", k, d_old);)\n      D(write_stuff(\"f\", k, f);)\n      D(write_stuff(\"v\", k, v);)\n\n    alpha = r + v(0)*f(0);\n    if (alpha > 1e-20) {\n       d(0) = d_old(0) * r/alpha;\n    } else {\n      //printf(\"step %d correcting initial alpha from %f to 1e-20\\n\", k, alpha);\n      d(0) = d_old(0);\n      alpha = 1e-20;\n    }\n    // printf(\"   alpha C: %f\\n\", alpha);\n    K(0)=v(0);\n\n    U(0, 0) = U_old(0,0);\n    for (unsigned j=1; j < state_size; ++j) {\n      double old_alpha = alpha;\n      alpha += v(j)*f(j);\n      //printf(\"   alpha C %d: %f\\n\", j, alpha);\n      if (alpha > 1e-20) {\n\td(j) = d_old(j) * (old_alpha/alpha);\n\t//printf(\"d = %f * %f = %f\\n\" , d_old(j), old_alpha/alpha, d(j));\n      } else {\n\t//printf(\"step %d correcting alpha from %f to 1e-20\\n\", k, alpha);\n\td(j) = d_old(j);\n\talpha = 1e-20;\n      }\n\n      for (unsigned i=0; i < state_size; ++i) {\n\tU(i, j) = U_old(i,j) - (K(i)/old_alpha)*f(j);\n        K(i) += v(j) * U_old(i,j);\n      }\n\n    }\n    cache.alpha = alpha;\n\n      D(write_stuff(\"U_obs\", k, U);)\n      D(write_stuff(\"d_obs\", k, d);)\n\n  }\n\n  // given the Kalman gain from the covariance update, compute\n  // the updated mean vector.\n  vector<double> &xk = cache.xk;\n  double pred_z = ssm.apply_observation_matrix(&(xk(0)), k) + ssm.observation_bias(k);\n  cache.pred_z = pred_z;\n  double yk = zk - pred_z;\n  for (unsigned i=0; i < state_size; ++i) {\n    xk(i) += cache.gain(i) * yk/alpha;\n  }\n\n  // also compute log marginal likelihood for this observation\n  double step_ell = -.5 * log(2*PI*alpha) - .5 * yk*yk / alpha;\n\n  //printf(\"step %d (C) pred %.4f alpha %.4f z %.4f y %.4f ell %.4f\\n\", k, pred_z, alpha, zk, yk, step_ell);\n\n  if (std::isnan(step_ell)) {\n    printf(\"step %d (C) pred %.4f alpha %.4f z %.4f y %.4f ell %.4f\\n\", k, pred_z, alpha, zk, yk, step_ell);\n    //print_vec(cache.obs_d);\n    //printf(\"\\n\");\n    //print_vec(cache.xk);\n    //exit(-1);\n    step_ell = -INFINITY;\n  }\n\n  return step_ell;\n}\n\nint kalman_predict_sqrt(StateSpaceModel &ssm, FilterState &cache, int k, bool force_P) {\n\n  unsigned int prev_state_size = cache.state_size;\n\n  vector<double> &tmp = cache.f;\n\n  unsigned int state_size = ssm.apply_transition_matrix( &(cache.xk(0)), k,  &(tmp(0)));\n  cache.state_size = state_size;\n\n  vector<double> &xk = cache.xk;\n  subrange(xk, 0, state_size) = subrange(tmp, 0, state_size);\n  ssm.transition_bias(k, &(xk(0)));\n\n  D(write_stuff(\"xk_posttransit\", k, xk);)\n\n  if (cache.at_fixed_point and ssm.stationary(k)) {\n    return 0;\n  }\n\n  cache.at_fixed_point = false;\n\n  matrix<double> &U_old = cache.obs_U;\n  vector<double> &d_old = cache.obs_d;\n\n  matrix<double> &U_tmp = cache.tmp_U1;\n  vector<double> &d_tmp = cache.v;\n\n  // get transition noise into temporary storage\n  ssm.transition_noise_diag(k, &(tmp(0)));\n\n  /* pushing the covariance P through the transition model F yields\n     FPF'. In a factored representation, this is FUDU'F', so we just need\n     to compute FU. */\n  unsigned int min_size = std::min(prev_state_size, state_size);\n\n\n\n  D(write_stuff(\"U_pretransit\", k, U_old);)\n\n\n  // COMMENTED OUT: this loop is equivalent to the matrix-valued transition call\n  // directly below. I'm leaving it in for debugging and to run speed comparisons.\n\n    /*\n  for (int i=0; i < min_size; ++i) {\n    // THIS ONLY WORKS IF U_old is in column-major order\n    ssm.apply_transition_matrix(&(column(U_old, i)(0) ), k, &(d_tmp(0)) );\n    noalias(column(U_tmp, i)) = d_tmp;\n    }*/\n  subrange(d_tmp, 0, prev_state_size) = subrange(d_old, 0, prev_state_size);\n  ssm.apply_transition_matrix(U_old, 0, k, U_tmp, 0, prev_state_size);\n  for (unsigned i=prev_state_size; i < state_size; ++i) {\n    d_tmp(i) = 0;\n    for (unsigned j=0; j < state_size; ++j) {\n      U_tmp(j, i) = 0;\n    }\n  }\n\n    D(write_stuff(\"d_posttransit\", k, d_tmp);)\n    D(write_stuff(\"U_posttransit\", k, U_tmp);)\n\n  // if there is transition noise, do the expensive reconstruction/factoring step\n  if (force_P || state_size != prev_state_size || norm_2(subrange(tmp, 0, state_size)) > 0) {\n\n    compute_explicit_cov_atlas(cache, U_tmp, d_tmp, prev_state_size);\n    // add transition noise\n    matrix<double> &P = cache.P;\n\n\n    D(write_stuff(\"P_prenoise\", k, P);)\n\n\n    for (unsigned i=0; i < state_size; ++i) {\n      P(i,i) += tmp(i);\n    }\n    //printf(\"noise at time %d \", k);\n    //print_vec(tmp);\n\n\n      D(write_stuff(\"P\", k, P);)\n\n\n    // printf(\"step %d state size %d\\n\", k, state_size);\n\n    // udu overwrites the cov matrix, so we need to\n    // save it if we're going to explicitly use it\n    // later on.\n    matrix<double> & mtmp = cache.tmp_U2;\n    if (force_P) {\n      mtmp = P;\n    }\n\n    // get the new factored representation\n    int err = udu(P, U_tmp, d_tmp, state_size);\n    if (err != 0) {\n      return err;\n    }\n\n      D(write_stuff(\"d_decomp\", k, d_tmp);)\n      D(write_stuff(\"U_decomp\", k, U_tmp);)\n\n    if (force_P) {\n      P = mtmp;\n    }\n\n  }\n\n  // if our factored representation is (almost) the same as the previous invocation,\n  // we've reached a stationary state\n  matrix<double> &U_cached = cache.pred_U;\n  vector<double> &d_cached = cache.pred_d;\n  if (ssm.stationary(k)) {\n    if (k > 0 && ssm.stationary(k-1)) {\n      bool potential_fixed_point = true;\n      for (unsigned i=0; i < state_size; ++i) {\n\tif (std::abs(d_tmp(i) - d_cached(i)) > cache.eps_stationary) {\n\t  potential_fixed_point=false;\n\t  break;\n\t}\n\tfor (unsigned j=0; j < state_size; ++j) {\n\t  if (std::abs(U_tmp(i,j) - U_cached(i,j)) > cache.eps_stationary) {\n\t    potential_fixed_point=false;\n\t    break;\n\t  }\n\t}\n\tif (!potential_fixed_point) {\n\t  break;\n\t}\n      }\n      if (potential_fixed_point) {\n\tcache.at_fixed_point = true;\n      }\n    }\n  }\n  if (!cache.at_fixed_point) {\n    subrange(U_cached, 0, state_size, 0, state_size) = subrange(U_tmp, 0, state_size, 0, state_size);\n    subrange(d_cached, 0, state_size) = subrange(d_tmp, 0, state_size);\n  }\n  return 0;\n}\n\ndouble filter_likelihood(StateSpaceModel &ssm, const vector<double> &z) {\n  FilterState cache(ssm.max_dimension, 1e-10);\n  cache.init_priors(ssm);\n  unsigned int N = z.size();\n  double ell = 0;\n\n  D(write_stuff(\"U_prior\", 0, cache.pred_U);)\n  D(write_stuff(\"d_prior\", 0, cache.pred_d);)\n  D(write_stuff(\"xk_prior\", 0, cache.xk);)\n\n    if (N == 0) {\n      return ell;\n    }\n\n  double step_ell = kalman_observe_sqrt(ssm, cache, 0, z(0));\n  if (std::isinf(step_ell)) {\n    return step_ell;\n  }\n  ell += step_ell;\n\n\n\n  D(write_stuff(\"U_post_obs\", 0, cache.obs_U);)\n    D(write_stuff(\"d_post_obs\", 0, cache.obs_d);)\n    D(write_stuff(\"xk_post_obs\", 0, cache.xk);)\n\n  for (unsigned k=1; k < N; ++k) {\n    int err = kalman_predict_sqrt(ssm, cache, k, false);\n\n    if (err != 0) {\n      return -INFINITY;\n    }\n\n    D(write_stuff(\"U_post_predict\", k, cache.pred_U);)\n    D(write_stuff(\"d_post_predict\", k, cache.pred_d);)\n    D(write_stuff(\"xk_post_predict\", k, cache.xk);)\n\n    double step_ell = kalman_observe_sqrt(ssm, cache, k, z(k));\n    if (std::isinf(step_ell)) {\n      return step_ell;\n    }\n    ell += step_ell;\n\n      D(write_stuff(\"U_post_obs\", k, cache.obs_U);)\n      D(write_stuff(\"d_post_obs\", k, cache.obs_d);)\n      D(write_stuff(\"xk_post_obs\", k, cache.xk);)\n\n\n\n  }\n  return ell;\n}\n\n\ndouble filter_incremental(StateSpaceModel &ssm, \n\t\t\t  const vector<double> &z,\n\t\t\t  double * ells,\n\t\t\t  int filter_start_idx,\n\t\t\t  int incr_start_idx,\n\t\t\t  int incr_end_idx,\n\t\t\t  int update_ells,\n\t\t\t  double step_ell_tol,\n\t\t\t  int * steps_processed,\n\t\t\t  int * errcode) {\n  \n\n  unsigned int N = z.size();\n  if ((filter_start_idx < 0) || (incr_start_idx < filter_start_idx) || (incr_start_idx >= N)) {\n    printf(\"fatal: filter_incremental received bad indices (%d, %d, %d) for signal of size %d\\n\", \n\t   filter_start_idx, incr_start_idx, incr_end_idx, N);\n  }\n\n  FilterState cache(ssm.max_dimension, 1e-10);\n  if (filter_start_idx == 0) {\n    cache.init_priors(ssm);\n  } else {\n    cache.init_incremental_state(ssm, filter_start_idx);\n  }\n\n  double total_discrepancy = 0;\n  double step_ell_discrepancy;\n  double step_ell;\n\n  //printf(\"update ells %d\\n\", update_ells);\n\n  // do some initial filtering steps to \"warm up\" the hidden state\n  for (unsigned k=filter_start_idx; k < incr_start_idx; ++k) {\n    step_ell = kalman_observe_sqrt(ssm, cache, k, z(k));\n    if (std::isinf(step_ell)) {\n      *errcode = ERR_INCR_NUMERIC;\n      return -INFINITY;\n    }\n\n    int err = kalman_predict_sqrt(ssm, cache, k+1, false);\n    if (err != 0) {\n      *errcode = ERR_INCR_NUMERIC;\n      return -INFINITY;\n    }\n\n    \n    step_ell_discrepancy= step_ell - ells[k];\n\n    if (k == incr_start_idx-1) {\n      // check that our likelihood calculations are now in sync with the\n      // previous calculation.\n      if ( fabs(step_ell_discrepancy) > step_ell_tol ) {\n\t// printf(\"warmup %d discrepancy %.10f\\n\", k, step_ell_discrepancy);\n         *errcode = ERR_INCR_INIT;\n         return -INFINITY;\n      }\n    }  \n  }\n\n  // now start the \"normal\" filtering process with an observation step\n  step_ell = kalman_observe_sqrt(ssm, cache, incr_start_idx, z(incr_start_idx));\n  if (std::isinf(step_ell)) {\n    *errcode = ERR_INCR_NUMERIC;\n    return step_ell;\n  }\n  step_ell_discrepancy = step_ell - ells[incr_start_idx];\n  if (update_ells) {\n    ells[incr_start_idx] = step_ell;\n  }\n  total_discrepancy += step_ell_discrepancy;\n\n  //printf(\"first obs %d discrepancy %.2f\\n\", incr_start_idx, step_ell_discrepancy);\n\n  *steps_processed = N - filter_start_idx;\n  int match_counter = 0;\n  for (unsigned k=incr_start_idx+1; k < N; ++k) {\n    int err = kalman_predict_sqrt(ssm, cache, k, false);\n\n    if (err != 0) {\n      *errcode = ERR_INCR_NUMERIC;\n      return -INFINITY;\n    }\n\n    step_ell = kalman_observe_sqrt(ssm, cache, k, z(k));\n    if (std::isinf(step_ell)) {\n      *errcode = ERR_INCR_NUMERIC;\n      return -INFINITY;\n    }\n    step_ell_discrepancy = step_ell - ells[k];\n    if (update_ells) {\n      ells[k] = step_ell;\n    }\n    total_discrepancy += step_ell_discrepancy;\n    //printf(\"step %d discrepancy %.2f\\n\", k, step_ell_discrepancy);\n\n\n    // quit filtering if we're past the end idx and the likelihoods seem to \n    // have reverted to their previous values\n    if ((k > incr_end_idx) && (fabs(step_ell_discrepancy) < step_ell_tol)) {\n      *steps_processed = k - filter_start_idx;\n      match_counter += 1;\n      if (match_counter >= 5) {\n\tbreak;\n      }\n    }\n  }\n  return total_discrepancy;\n}\n\nvoid step_obs_likelihoods(StateSpaceModel &ssm, const vector<double> &z,\n\t\t\t  vector<double> & ells,\n\t\t\t  vector<double> & preds,\n\t\t\t  vector<double> & alphas) {\n  FilterState cache(ssm.max_dimension, 1e-10);\n  cache.init_priors(ssm);\n  unsigned int N = z.size();\n  \n  if (N == 0) {\n    return;\n  }\n\n  ells(0) = kalman_observe_sqrt(ssm, cache, 0, z(0));\n  preds(0) = cache.pred_z;\n  alphas(0) = cache.alpha;\n  for (unsigned k=1; k < N; ++k) {\n    kalman_predict_sqrt(ssm, cache, k, false);\n    ells(k) = kalman_observe_sqrt(ssm, cache, k, z(k));\n    preds(k) = cache.pred_z;\n    alphas(k) = cache.alpha;\n    //printf(\"got ell %f at step %d\\n\", ells(k), k);\n  }\n}\n\n\nvoid mean_obs(StateSpaceModel &ssm, vector<double> & result) {\n  vector<double> x(ssm.max_dimension);\n  vector<double> x2(ssm.max_dimension);\n  x.clear();\n  x2.clear();\n\n  ssm.prior_mean(&(x(0)));\n\n  for (unsigned k = 0; k < result.size(); ++k) {\n    result[k] = ssm.apply_observation_matrix(&(x(0)), k);\n    result[k] += ssm.observation_bias(k);\n\n    if (k+1 < result.size()) {\n      ssm.apply_transition_matrix(&(x(0)), k+1, &(x2(0)));\n      ssm.transition_bias(k+1, &(x2(0)));\n    }\n    x = x2; // this copy is unnecessary, we could swap\n            // pointers instead, but it doesn't\n            // matter cause this method is never the\n            // performance bottleneck.\n  }\n}\n\nvoid obs_var(StateSpaceModel &ssm, vector<double> & result) {\n  FilterState cache(ssm.max_dimension, 1e-10);\n  cache.init_priors(ssm);\n  compute_explicit_cov_atlas(cache, cache.pred_U, cache.pred_d, -1);\n\n  matrix<double> P = cache.P;\n\n  for (unsigned k = 0; k < result.size(); ++k) {\n    ssm.apply_observation_matrix(P, 0,\n    \t\t\t\t k, &(cache.f(0)), &(cache.v(0)), cache.f.size());\n    result(k) = ssm.apply_observation_matrix(&(cache.f(0)), k);\n    result(k) += ssm.observation_noise(k);\n    if (k+1 < result.size()) {\n\n      ssm.apply_transition_matrix(P, 0, k+1, cache.obs_U, 0, ssm.max_dimension);\n      cache.obs_U = trans(cache.obs_U);\n      ssm.apply_transition_matrix(cache.obs_U, 0, k+1, P, 0, ssm.max_dimension);\n\n      vector<double> &tmp = cache.f;\n      ssm.transition_noise_diag(k+1, &(tmp(0)));\n      for (unsigned i=0; i < ssm.max_dimension; ++i) {\n\tP(i,i) += tmp(i);\n      }\n    }\n  }\n}\n\nvoid prior_sample(StateSpaceModel &ssm, vector<double> & result, unsigned long seed) {\n  FilterState cache(ssm.max_dimension, 1e-10);\n  cache.init_priors(ssm);\n\n  std::mt19937 gen(seed);\n  std::normal_distribution<double> randn(0,1);\n  /* auto randn = std::bind(std::normal_distribution<double>(0,1),\n\t\t\t     ); */\n\n  printf(\"seed with %lu, first randn %f\\n\", seed, randn(gen));\n\n  // sample initial state from the prior\n  vector<double> &d = cache.pred_d;\n  for (unsigned i=0; i < ssm.max_dimension; ++i) {\n    cache.xk(i) += randn(gen) * sqrt(d(i));\n  }\n\n\n  unsigned k = 0;\n  result(k) = ssm.apply_observation_matrix(&(cache.xk(0)), k);\n  result(k) += ssm.observation_bias(k);\n\n  for (k=1; k < result.size(); ++k) {\n    cache.obs_d = cache.pred_d;\n    cache.obs_U = cache.pred_U;\n\n    vector<double> &tmp = cache.f;\n    unsigned int state_size = ssm.apply_transition_matrix( &(cache.xk(0)), k,  &(tmp(0)));\n    vector<double> &xk = cache.xk;\n    subrange(xk, 0, state_size) = subrange(tmp, 0, state_size);\n    ssm.transition_bias(k, &(xk(0)));\n\n    ssm.transition_noise_diag(k, &(tmp(0)));\n    for (unsigned i=0; i < state_size; ++i) {\n      cache.xk(i) += randn(gen) * sqrt(tmp(i));\n    }\n\n    result(k) = ssm.apply_observation_matrix(&(cache.xk(0)), k);\n    result(k) += ssm.observation_bias(k);\n    result(k) += randn(gen) * sqrt(ssm.observation_noise(k));\n\n  }\n}\n\n\n\n\ndouble all_filtered_cssm_coef_marginals(TransientCombinedSSM &ssm,\n\t\t\t\t      const vector<double> &z,\n\t\t\t\t      vector<double> & step_ells,\n\t\t\t\t      std::vector<vector<double> > & cmeans,\n\t\t\t\t      std::vector<vector<double> > & cvars) {\n  FilterState cache(ssm.max_dimension, 1e-10);\n  cache.init_priors(ssm);\n  ssm.init_coef_priors(cmeans, cvars);\n\n  unsigned int N = z.size();\n  double ell = 0;\n\n  if (N == 0) {\n    return ell;\n  }\n\n  step_ells[0] = kalman_observe_sqrt(ssm, cache, 0, z(0));\n  ell += step_ells[0];\n  compute_explicit_cov_atlas(cache, cache.obs_U, cache.obs_d, -1);\n  ssm.extract_all_coefs(cache, 0, cmeans, cvars);\n  for (unsigned k=1; k < N; ++k) {\n    kalman_predict_sqrt(ssm, cache, k, false);\n    step_ells[k] = kalman_observe_sqrt(ssm, cache, k, z(k));\n    ell += step_ells[k];\n\n    compute_explicit_cov_atlas(cache, cache.obs_U, cache.obs_d, -1);\n    ssm.extract_all_coefs(cache, k, cmeans, cvars);\n  }\n  return ell;\n}\n\ndouble tssm_component_means(TransientCombinedSSM &ssm,\n\t\t\t    const vector<double> &z,\n\t\t\t    std::vector<vector<double> > & means) {\n\n  if (means.size() != ssm.n_ssms) {\n    printf(\"component_means() needs exactly one vector for each component SSM\\n\");\n    exit(-1);\n  }\n\n  FilterState cache(ssm.max_dimension, 1e-10);\n  cache.init_priors(ssm);\n\n  unsigned int N = z.size();\n  double ell = 0;\n\n  if (N == 0) {\n    return ell;\n  }\n\n  ell += kalman_observe_sqrt(ssm, cache, 0, z(0));\n  ssm.extract_component_means(&(cache.xk(0)), 0, means);\n  for (unsigned k=1; k < N; ++k) {\n    kalman_predict_sqrt(ssm, cache, k, false);\n    ell += kalman_observe_sqrt(ssm, cache, k, z(k));\n    ssm.extract_component_means(&(cache.xk(0)), k, means);\n  }\n  return ell;\n}\n\n\ndouble tssm_component_vars(TransientCombinedSSM &ssm,\n\t\t\t  const vector<double> &z,\n\t\t\t  std::vector<vector<double> > & vars) {\n\n  if (vars.size() != ssm.n_ssms) {\n    printf(\"component_vars() needs exactly one vector for each component SSM\\n\");\n    exit(-1);\n  }\n\n  FilterState cache(ssm.max_dimension, 1e-10);\n  cache.init_priors(ssm);\n  compute_explicit_cov_atlas(cache, cache.pred_U, cache.pred_d, -1);\n\n  unsigned int N = z.size();\n  double ell = 0;\n\n  if (N == 0) {\n    return ell;\n  }\n\n  ell += kalman_observe_sqrt(ssm, cache, 0, z(0));\n  compute_explicit_cov_atlas(cache, cache.obs_U, cache.obs_d, -1);\n  ssm.extract_component_vars(cache.P, cache.tmp_U2, 0, vars);\n  for (unsigned k=1; k < N; ++k) {\n    kalman_predict_sqrt(ssm, cache, k, false);\n    ell += kalman_observe_sqrt(ssm, cache, k, z(k));\n    compute_explicit_cov_atlas(cache, cache.obs_U, cache.obs_d, -1);\n    ssm.extract_component_vars(cache.P, cache.tmp_U2, k, vars);\n  }\n  return ell;\n}\n", "meta": {"hexsha": "694767cec1782ab3a79e2a51a4d131ba236f3282", "size": 25177, "ext": "cc", "lang": "C++", "max_stars_repo_path": "models/statespace/fast_c/statespace.cc", "max_stars_repo_name": "davmre/sigvisa", "max_stars_repo_head_hexsha": "91a1f163b8f3a258dfb78d88a07f2a11da41bd04", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/statespace/fast_c/statespace.cc", "max_issues_repo_name": "davmre/sigvisa", "max_issues_repo_head_hexsha": "91a1f163b8f3a258dfb78d88a07f2a11da41bd04", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/statespace/fast_c/statespace.cc", "max_forks_repo_name": "davmre/sigvisa", "max_forks_repo_head_hexsha": "91a1f163b8f3a258dfb78d88a07f2a11da41bd04", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8985042735, "max_line_length": 108, "alphanum_fraction": 0.6199706081, "num_tokens": 7900, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145997, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4318311379317428}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ARITHMETIC_DETERMINANT_HPP\n#define BOOST_GEOMETRY_ARITHMETIC_DETERMINANT_HPP\n\n\n#include <cstddef>\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/geometries/concepts/point_concept.hpp>\n#include <boost/geometry/util/select_coordinate_type.hpp>\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate <typename ReturnType, typename U, typename V>\nclass calculate_determinant\n{\n    template <typename T>\n    static inline ReturnType rt(T const& v)\n    {\n        return boost::numeric_cast<ReturnType>(v);\n    }\n\npublic :\n\n    static inline ReturnType apply(U const& ux, U const& uy\n                                 , V const& vx, V const& vy)\n    {\n        return rt(ux) * rt(vy) - rt(uy) * rt(vx);\n    }\n};\n\ntemplate <typename ReturnType, typename U, typename V>\ninline ReturnType determinant(U const& ux, U const& uy\n                            , V const& vx, V const& vy)\n{\n    return calculate_determinant\n        <\n            ReturnType, U, V\n        >::apply(ux, uy, vx, vy);\n}\n\n\ntemplate <typename ReturnType, typename U, typename V>\ninline ReturnType determinant(U const& u, V const& v)\n{\n    BOOST_CONCEPT_ASSERT( (concept::ConstPoint<U>) );\n    BOOST_CONCEPT_ASSERT( (concept::ConstPoint<V>) );\n\n    return calculate_determinant\n        <\n            ReturnType, \n            typename geometry::coordinate_type<U>::type,\n            typename geometry::coordinate_type<V>::type\n        >::apply(get<0>(u), get<1>(u), get<0>(v), get<1>(v));\n}\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ARITHMETIC_DETERMINANT_HPP\n", "meta": {"hexsha": "db3b867096d219162f4b91ef8c9606b14f602d62", "size": 2096, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/geometry/arithmetic/determinant.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-12-05T19:34:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T09:07:09.000Z", "max_issues_repo_path": "boost/boost/geometry/arithmetic/determinant.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2015-07-22T07:35:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T16:03:06.000Z", "max_forks_repo_path": "boost/boost/geometry/arithmetic/determinant.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T02:03:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T00:41:50.000Z", "avg_line_length": 27.2207792208, "max_line_length": 79, "alphanum_fraction": 0.6798664122, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.43183113169757814}}
{"text": "//\r\n// Expansion Hunter\r\n// Copyright 2016-2019 Illumina, Inc.\r\n// All rights reserved.\r\n//\r\n// Author: Xiao Chen <xchen2@illumina.com>\r\n//         Egor Dolzhenko <edolzhenko@illumina.com>\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n//      http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n//\r\n//\r\n#include \"genotyping/CopyNumberGenotyper.hh\"\r\n#include <boost/math/distributions/normal.hpp>\r\n#include <math.h>\r\n#include <numeric>\r\n\r\nusing boost::optional;\r\nusing boost::math::normal_distribution;\r\nusing std::vector;\r\n\r\nnamespace ehunter\r\n{\r\n\r\nCopyNumberGenotyper::CopyNumberGenotyper(\r\n    int maxCopyNumber, double depthScaleFactor, double standardDeviationOfCN2,\r\n    const std::vector<double>& meanDepthValues, const std::vector<double>& priorCopyNumberFreq)\r\n    : maxCopyNumber_(maxCopyNumber)\r\n    , depthScaleFactor_(depthScaleFactor)\r\n    , standardDeviationOfCN2_(standardDeviationOfCN2)\r\n    , meanDepthValues_(meanDepthValues)\r\n    , priorCopyNumberFreq_(priorCopyNumberFreq)\r\n{\r\n    if (maxCopyNumber_ + 1 != static_cast<int>(meanDepthValues_.size()))\r\n    {\r\n        throw std::runtime_error(\"Number of mean values is inconsistent with total copy number states.\");\r\n    }\r\n\r\n    if (maxCopyNumber_ + 1 != static_cast<int>(priorCopyNumberFreq_.size()))\r\n    {\r\n        throw std::runtime_error(\"Number of prior frequencies is inconsistent with total copy number states.\");\r\n    }\r\n}\r\n\r\nboost::optional<int> CopyNumberGenotyper::genotype(double normalizedDepth) const\r\n{\r\n    const double adjustedDepth = normalizedDepth / depthScaleFactor_;\r\n    std::vector<double> likelihoodOfAllCN;\r\n    std::vector<double> pvalueOfAllCN;\r\n\r\n    for (int currentGenotype = 0; currentGenotype != maxCopyNumber_ + 1; currentGenotype++)\r\n    {\r\n        std::pair<double, double> likelihoodAndPvalue = genotypeLikelihoodAndPvalue(currentGenotype, adjustedDepth);\r\n        double currentLikelihood = likelihoodAndPvalue.first;\r\n        double currentPvalue = likelihoodAndPvalue.second;\r\n        likelihoodOfAllCN.emplace_back(currentLikelihood);\r\n        pvalueOfAllCN.emplace_back(currentPvalue);\r\n    }\r\n\r\n    const std::pair<int, double> bestGenotypeAndPosterior = getBestGenotypeAndPosterior(likelihoodOfAllCN);\r\n    const int bestGenotype = bestGenotypeAndPosterior.first;\r\n    const double posteriorProbabilityOfBestGenotype = bestGenotypeAndPosterior.second;\r\n    const bool posteriorCheck = posteriorProbabilityOfBestGenotype > posteriorProbabilityThreshold_;\r\n    const bool pvalueCheck = pvalueOfAllCN[bestGenotype] > pvalueThreshold_;\r\n    const optional<int> genotype = (posteriorCheck && pvalueCheck) ? bestGenotype : optional<int>();\r\n    return genotype;\r\n}\r\n\r\nstd::pair<int, double>\r\nCopyNumberGenotyper::getBestGenotypeAndPosterior(const std::vector<double>& likelihoodOfAllCN) const\r\n{\r\n    double sumOfLikelihood = 0;\r\n    for (double likelihoodValue : likelihoodOfAllCN)\r\n    {\r\n        sumOfLikelihood += likelihoodValue;\r\n    }\r\n\r\n    assert(!likelihoodOfAllCN.empty());\r\n    auto maxElement = max_element(likelihoodOfAllCN.begin(), likelihoodOfAllCN.end());\r\n    const double maxLikelihood = *maxElement;\r\n    std::pair<int, double> bestGenotypeAndPosterior;\r\n    bestGenotypeAndPosterior.first = distance(likelihoodOfAllCN.begin(), maxElement);\r\n    bestGenotypeAndPosterior.second = maxLikelihood / sumOfLikelihood;\r\n\r\n    return bestGenotypeAndPosterior;\r\n}\r\n\r\nstd::pair<double, double>\r\nCopyNumberGenotyper::genotypeLikelihoodAndPvalue(int currentGenotype, double adjustedDepth) const\r\n{\r\n    assert(currentGenotype < (int)meanDepthValues_.size());\r\n    assert(currentGenotype < (int)priorCopyNumberFreq_.size());\r\n\r\n    const double meanValue = meanDepthValues_[currentGenotype];\r\n    // standard deviation for each CN state can be computed from CN2 except for CN0 it is pre-defined\r\n    const double standardDeviation\r\n        = currentGenotype == 0 ? standardDeviationOfCN0_ : standardDeviationOfCN2_ * sqrt(double(currentGenotype) / 2);\r\n    const double priorFreq = priorCopyNumberFreq_[currentGenotype];\r\n\r\n    const normal_distribution<> cnDistribution(meanValue, standardDeviation);\r\n    const double genotypeLikelihood = priorFreq * pdf(cnDistribution, adjustedDepth);\r\n    const double cumulativeFrequency = cdf(cnDistribution, adjustedDepth);\r\n    const double pvalue = std::min(cumulativeFrequency, 1 - cumulativeFrequency);\r\n\r\n    std::pair<double, double> likelihoodAndPvalue;\r\n    likelihoodAndPvalue.first = genotypeLikelihood;\r\n    likelihoodAndPvalue.second = pvalue;\r\n\r\n    return likelihoodAndPvalue;\r\n}\r\n}\r\n", "meta": {"hexsha": "8f7661614de7d1ec4a21e604fb26a404770ab4f7", "size": 5021, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "genotyping/CopyNumberGenotyper.cpp", "max_stars_repo_name": "AlesMaver/ExpansionHunter", "max_stars_repo_head_hexsha": "274903d26a33cfbc546aac98c85bbfe51701fd3b", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "genotyping/CopyNumberGenotyper.cpp", "max_issues_repo_name": "AlesMaver/ExpansionHunter", "max_issues_repo_head_hexsha": "274903d26a33cfbc546aac98c85bbfe51701fd3b", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "genotyping/CopyNumberGenotyper.cpp", "max_forks_repo_name": "AlesMaver/ExpansionHunter", "max_forks_repo_head_hexsha": "274903d26a33cfbc546aac98c85bbfe51701fd3b", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4958677686, "max_line_length": 120, "alphanum_fraction": 0.7414857598, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4318311316975781}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n\n#ifndef BOOST_MP_INT_FUNC_HPP\n#define BOOST_MP_INT_FUNC_HPP\n\n#include <boost/multiprecision/number.hpp>\n\nnamespace boost{ namespace multiprecision{\n\nnamespace default_ops\n{\n\ntemplate <class Backend>\ninline void eval_qr(const Backend& x, const Backend& y, Backend& q, Backend& r)\n{\n   eval_divide(q, x, y);\n   eval_modulus(r, x, y);\n}\n\ntemplate <class Backend, class Integer>\ninline Integer eval_integer_modulus(const Backend& x, Integer val)\n{\n   BOOST_MP_USING_ABS\n   using default_ops::eval_modulus;\n   using default_ops::eval_convert_to;\n   typedef typename boost::multiprecision::detail::canonical<Integer, Backend>::type int_type;\n   Backend t;\n   eval_modulus(t, x, static_cast<int_type>(val));\n   Integer result;\n   eval_convert_to(&result, t);\n   return abs(result);\n}\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4127)\n#endif\n\ntemplate <class B>\ninline void eval_gcd(B& result, const B& a, const B& b)\n{\n   using default_ops::eval_lsb;\n   using default_ops::eval_is_zero;\n   using default_ops::eval_get_sign;\n\n   int shift;\n\n   B u(a), v(b);\n\n   int s = eval_get_sign(u);\n\n   /* GCD(0,x) := x */\n   if(s < 0)\n   {\n      u.negate();\n   }\n   else if(s == 0)\n   {\n      result = v;\n      return;\n   }\n   s = eval_get_sign(v);\n   if(s < 0)\n   {\n      v.negate();\n   }\n   else if(s == 0)\n   {\n      result = u;\n      return;\n   }\n\n   /* Let shift := lg K, where K is the greatest power of 2\n   dividing both u and v. */\n\n   unsigned us = eval_lsb(u);\n   unsigned vs = eval_lsb(v);\n   shift = (std::min)(us, vs);\n   eval_right_shift(u, us);\n   eval_right_shift(v, vs);\n\n   do \n   {\n      /* Now u and v are both odd, so diff(u, v) is even.\n      Let u = min(u, v), v = diff(u, v)/2. */\n      s = u.compare(v);\n      if(s > 0)\n         u.swap(v);\n      if(s == 0)\n         break;\n      eval_subtract(v, u);\n      vs = eval_lsb(v);\n      eval_right_shift(v, vs);\n   } \n   while(true);\n\n   result = u;\n   eval_left_shift(result, shift);\n}\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\ntemplate <class B>\ninline void eval_lcm(B& result, const B& a, const B& b)\n{\n   typedef typename mpl::front<typename B::unsigned_types>::type ui_type;\n   B t;\n   eval_gcd(t, a, b);\n\n   if(eval_is_zero(t))\n   {\n      result = static_cast<ui_type>(0);\n   }\n   else\n   {\n      eval_divide(result, a, t);\n      eval_multiply(result, b);\n   }\n   if(eval_get_sign(result) < 0)\n      result.negate();\n}\n\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<number_category<Backend>::value == number_kind_integer>::type \n   divide_qr(const number<Backend, ExpressionTemplates>& x, const number<Backend, ExpressionTemplates>& y,\n   number<Backend, ExpressionTemplates>& q, number<Backend, ExpressionTemplates>& r)\n{\n   using default_ops::eval_qr;\n   eval_qr(x.backend(), y.backend(), q.backend(), r.backend());\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates, class tag, class A1, class A2, class A3, class A4>\ninline typename enable_if_c<number_category<Backend>::value == number_kind_integer>::type \n   divide_qr(const number<Backend, ExpressionTemplates>& x, const multiprecision::detail::expression<tag, A1, A2, A3, A4>& y,\n   number<Backend, ExpressionTemplates>& q, number<Backend, ExpressionTemplates>& r)\n{\n   divide_qr(x, number<Backend, ExpressionTemplates>(y), q, r);\n}\n\ntemplate <class tag, class A1, class A2, class A3, class A4, class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<number_category<Backend>::value == number_kind_integer>::type \n   divide_qr(const multiprecision::detail::expression<tag, A1, A2, A3, A4>& x, const number<Backend, ExpressionTemplates>& y,\n   number<Backend, ExpressionTemplates>& q, number<Backend, ExpressionTemplates>& r)\n{\n   divide_qr(number<Backend, ExpressionTemplates>(x), y, q, r);\n}\n\ntemplate <class tag, class A1, class A2, class A3, class A4, class tagb, class A1b, class A2b, class A3b, class A4b, class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<number_category<Backend>::value == number_kind_integer>::type \n   divide_qr(const multiprecision::detail::expression<tag, A1, A2, A3, A4>& x, const multiprecision::detail::expression<tagb, A1b, A2b, A3b, A4b>& y,\n   number<Backend, ExpressionTemplates>& q, number<Backend, ExpressionTemplates>& r)\n{\n   divide_qr(number<Backend, ExpressionTemplates>(x), number<Backend, ExpressionTemplates>(y), q, r);\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates, class Integer>\ninline typename enable_if<mpl::and_<is_integral<Integer>, mpl::bool_<number_category<Backend>::value == number_kind_integer> >, Integer>::type \n   integer_modulus(const number<Backend, ExpressionTemplates>& x, Integer val)\n{\n   using default_ops::eval_integer_modulus;\n   return eval_integer_modulus(x.backend(), val);\n}\n\ntemplate <class tag, class A1, class A2, class A3, class A4, class Integer>\ninline typename enable_if<mpl::and_<is_integral<Integer>, mpl::bool_<number_category<typename multiprecision::detail::expression<tag, A1, A2, A3, A4>::result_type>::value == number_kind_integer> >, Integer>::type \n   integer_modulus(const multiprecision::detail::expression<tag, A1, A2, A3, A4>& x, Integer val)\n{\n   typedef typename multiprecision::detail::expression<tag, A1, A2, A3, A4>::result_type result_type;\n   return integer_modulus(result_type(x), val);\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<number_category<Backend>::value == number_kind_integer, unsigned>::type \n   lsb(const number<Backend, ExpressionTemplates>& x)\n{\n   using default_ops::eval_lsb;\n   return eval_lsb(x.backend());\n}\n\ntemplate <class tag, class A1, class A2, class A3, class A4>\ninline typename enable_if_c<number_category<typename multiprecision::detail::expression<tag, A1, A2, A3, A4>::result_type>::value == number_kind_integer, unsigned>::type \n   lsb(const multiprecision::detail::expression<tag, A1, A2, A3, A4>& x)\n{\n   typedef typename multiprecision::detail::expression<tag, A1, A2, A3, A4>::result_type number_type;\n   number_type n(x);\n   using default_ops::eval_lsb;\n   return eval_lsb(n.backend());\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<number_category<Backend>::value == number_kind_integer, bool>::type \n   bit_test(const number<Backend, ExpressionTemplates>& x, unsigned index)\n{\n   using default_ops::eval_bit_test;\n   return eval_bit_test(x.backend(), index);\n}\n\ntemplate <class tag, class A1, class A2, class A3, class A4>\ninline typename enable_if_c<number_category<typename multiprecision::detail::expression<tag, A1, A2, A3, A4>::result_type>::value == number_kind_integer, bool>::type \n   bit_test(const multiprecision::detail::expression<tag, A1, A2, A3, A4>& x, unsigned index)\n{\n   typedef typename multiprecision::detail::expression<tag, A1, A2, A3, A4>::result_type number_type;\n   number_type n(x);\n   using default_ops::eval_bit_test;\n   return eval_bit_test(n.backend(), index);\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<number_category<Backend>::value == number_kind_integer, number<Backend, ExpressionTemplates>&>::type \n   bit_set(number<Backend, ExpressionTemplates>& x, unsigned index)\n{\n   using default_ops::eval_bit_set;\n   eval_bit_set(x.backend(), index);\n   return x;\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<number_category<Backend>::value == number_kind_integer, number<Backend, ExpressionTemplates>&>::type \n   bit_unset(number<Backend, ExpressionTemplates>& x, unsigned index)\n{\n   using default_ops::eval_bit_unset;\n   eval_bit_unset(x.backend(), index);\n   return x;\n}\n\ntemplate <class Backend, expression_template_option ExpressionTemplates>\ninline typename enable_if_c<number_category<Backend>::value == number_kind_integer, number<Backend, ExpressionTemplates>&>::type \n   bit_flip(number<Backend, ExpressionTemplates>& x, unsigned index)\n{\n   using default_ops::eval_bit_flip;\n   eval_bit_flip(x.backend(), index);\n   return x;\n}\n\nnamespace detail{\n\n//\n// Within powm, we need a type with twice as many digits as the argument type, define\n// a traits class to obtain that type:\n//\ntemplate <class Backend>\nstruct double_precision_type\n{\n   typedef Backend type;\n};\n\n//\n// Calculate (a^p)%c:\n//\ntemplate <class Backend>\nvoid eval_powm(Backend& result, const Backend& a, const Backend& p, const Backend& c)\n{\n   using default_ops::eval_bit_test;\n   using default_ops::eval_get_sign;\n   using default_ops::eval_multiply;\n   using default_ops::eval_modulus;\n   using default_ops::eval_right_shift;\n\n   typedef typename double_precision_type<Backend>::type double_type;\n   typedef typename canonical<unsigned char, double_type>::type ui_type;\n   \n   double_type x, y(a), b(p), t;\n   x = ui_type(1u);\n\n   while(eval_get_sign(b) > 0)\n   {\n      if(eval_bit_test(b, 0))\n      {\n         eval_multiply(t, x, y);\n         eval_modulus(x, t, c);\n      }\n      eval_multiply(t, y, y);\n      eval_modulus(y, t, c);\n      eval_right_shift(b, ui_type(1));\n   }\n   Backend x2(x);\n   eval_modulus(result, x2, c);\n}\n\ntemplate <class Backend, class Integer>\nvoid eval_powm(Backend& result, const Backend& a, const Backend& p, Integer c)\n{\n   typedef typename double_precision_type<Backend>::type double_type;\n   typedef typename canonical<unsigned char, double_type>::type ui_type;\n   typedef typename canonical<Integer, double_type>::type i1_type;\n   typedef typename canonical<Integer, Backend>::type i2_type;\n\n   using default_ops::eval_bit_test;\n   using default_ops::eval_get_sign;\n   using default_ops::eval_multiply;\n   using default_ops::eval_modulus;\n   using default_ops::eval_right_shift;\n\n   if(eval_get_sign(p) < 0)\n   {\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"powm requires a positive exponent.\"));\n   }\n\n   double_type x, y(a), b(p), t;\n   x = ui_type(1u);\n\n   while(eval_get_sign(b) > 0)\n   {\n      if(eval_bit_test(b, 0))\n      {\n         eval_multiply(t, x, y);\n         eval_modulus(x, t, static_cast<i1_type>(c));\n      }\n      eval_multiply(t, y, y);\n      eval_modulus(y, t, static_cast<i1_type>(c));\n      eval_right_shift(b, ui_type(1));\n   }\n   Backend x2(x);\n   eval_modulus(result, x2, static_cast<i2_type>(c));\n}\n\ntemplate <class Backend, class Integer>\ntypename enable_if<is_unsigned<Integer> >::type eval_powm(Backend& result, const Backend& a, Integer b, const Backend& c)\n{\n   typedef typename double_precision_type<Backend>::type double_type;\n   typedef typename canonical<unsigned char, double_type>::type ui_type;\n\n   using default_ops::eval_bit_test;\n   using default_ops::eval_get_sign;\n   using default_ops::eval_multiply;\n   using default_ops::eval_modulus;\n   using default_ops::eval_right_shift;\n\n   double_type x, y(a), t;\n   x = ui_type(1u);\n\n   while(b > 0)\n   {\n      if(b & 1)\n      {\n         eval_multiply(t, x, y);\n         eval_modulus(x, t, c);\n      }\n      eval_multiply(t, y, y);\n      eval_modulus(y, t, c);\n      b >>= 1;\n   }\n   Backend x2(x);\n   eval_modulus(result, x2, c);\n}\n\ntemplate <class Backend, class Integer>\ntypename enable_if<is_signed<Integer> >::type eval_powm(Backend& result, const Backend& a, Integer b, const Backend& c)\n{\n   if(b < 0)\n   {\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"powm requires a positive exponent.\"));\n   }\n   eval_powm(result, a, static_cast<typename make_unsigned<Integer>::type>(b), c);\n}\n\ntemplate <class Backend, class Integer1, class Integer2>\ntypename enable_if<is_unsigned<Integer1> >::type eval_powm(Backend& result, const Backend& a, Integer1 b, Integer2 c)\n{\n   typedef typename double_precision_type<Backend>::type double_type;\n   typedef typename canonical<unsigned char, double_type>::type ui_type;\n   typedef typename canonical<Integer1, double_type>::type i1_type;\n   typedef typename canonical<Integer2, Backend>::type i2_type;\n\n   using default_ops::eval_bit_test;\n   using default_ops::eval_get_sign;\n   using default_ops::eval_multiply;\n   using default_ops::eval_modulus;\n   using default_ops::eval_right_shift;\n\n   double_type x, y(a), t;\n   x = ui_type(1u);\n\n   while(b > 0)\n   {\n      if(b & 1)\n      {\n         eval_multiply(t, x, y);\n         eval_modulus(x, t, static_cast<i1_type>(c));\n      }\n      eval_multiply(t, y, y);\n      eval_modulus(y, t, static_cast<i1_type>(c));\n      b >>= 1;\n   }\n   Backend x2(x);\n   eval_modulus(result, x2, static_cast<i2_type>(c));\n}\n\ntemplate <class Backend, class Integer1, class Integer2>\ntypename enable_if<is_signed<Integer1> >::type eval_powm(Backend& result, const Backend& a, Integer1 b, Integer2 c)\n{\n   if(b < 0)\n   {\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"powm requires a positive exponent.\"));\n   }\n   eval_powm(result, a, static_cast<typename make_unsigned<Integer1>::type>(b), c);\n}\n\nstruct powm_func\n{\n   template <class T, class U, class V>\n   void operator()(T& result, const T& b, const U& p, const V& m)const\n   {\n      eval_powm(result, b, p, m);\n   }\n};\n\n}\n\ntemplate <class T, class U, class V>\ninline typename enable_if<\n   mpl::and_<\n      mpl::bool_<number_category<T>::value == number_kind_integer>, \n      mpl::or_<\n         is_number<T>,\n         is_number_expression<T>\n      >,\n      mpl::or_<\n         is_number<U>,\n         is_number_expression<U>,\n         is_integral<U>\n      >,\n      mpl::or_<\n         is_number<V>,\n         is_number_expression<V>,\n         is_integral<V>\n      >\n   >,\n   detail::expression<detail::function, detail::powm_func, T, U, V> >::type \n   powm(const T& b, const U& p, const V& mod)\n{\n   return detail::expression<detail::function, detail::powm_func, T, U, V>(\n      detail::powm_func(), b, p, mod);\n}\n\n}} //namespaces\n\n#endif\n\n\n", "meta": {"hexsha": "4f7787759e243fd6bae66a1539e0fa047d6af6ab", "size": 14045, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost/boost/multiprecision/detail/integer_ops.hpp", "max_stars_repo_name": "creatologist/openFrameworks0084", "max_stars_repo_head_hexsha": "aa74f188f105b62fbcecb7baf2b41d56d97cf7bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T01:54:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T00:41:48.000Z", "max_issues_repo_path": "libs/boost/boost/multiprecision/detail/integer_ops.hpp", "max_issues_repo_name": "creatologist/openFrameworks0084", "max_issues_repo_head_hexsha": "aa74f188f105b62fbcecb7baf2b41d56d97cf7bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-09-26T10:58:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-06T09:10:33.000Z", "max_forks_repo_path": "libs/boost/boost/multiprecision/detail/integer_ops.hpp", "max_forks_repo_name": "creatologist/openFrameworks0084", "max_forks_repo_head_hexsha": "aa74f188f105b62fbcecb7baf2b41d56d97cf7bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T02:03:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-15T00:41:50.000Z", "avg_line_length": 31.3504464286, "max_line_length": 213, "alphanum_fraction": 0.6983268067, "num_tokens": 3654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746404, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.43183113169757803}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// importance_sampling::example::sampler.cpp                                 //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <iterator>\n#include <boost/range.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/format.hpp>\n#include <boost/function.hpp>\n#include <boost/typeof/typeof.hpp>\n#include <boost/utility/result_of.hpp>\n#include <boost/math/tools/precision.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/ref.hpp>\n#include <boost/foreach.hpp>\n\n#include <boost/fusion/include/at_key.hpp>\n#include <boost/fusion/include/pair.hpp>\n#include <boost/fusion/include/map.hpp>\n#include <boost/fusion/include/make_map.hpp>\n\n#include <boost/math/tools/precision.hpp>\n\n#include <boost/statistics/detail/accumulator/statistics/proportion_less_than.hpp>\n#include <boost/statistics/detail/distribution_common/distributions/reference/wrapper.hpp>\n#include <boost/statistics/detail/distribution_common/meta/random/generator.hpp>\n#include <boost/statistics/detail/distribution_common/functor/log_unnormalized_pdf.hpp>\n#include <boost/statistics/detail/distribution_toolkit/distributions/normal/include.hpp>\n#include <boost/statistics/detail/distribution_toolkit/map_pdf/ratio_pdf/include.hpp>\n\n#include <boost/statistics/detail/non_parametric/kolmogorov_smirnov/check_convergence.hpp>\n\n#include <boost/statistics/detail/fusion/at_key/functor.hpp>\n#include <boost/statistics/detail/fusion/at_key/range.hpp>\n#include <boost/statistics/detail/non_parametric/kolmogorov_smirnov/statistic.hpp>\n\n#include <boost/statistics/detail/importance_sampling/weights/prepare_weights.hpp>\n#include <boost/statistics/detail/importance_sampling/random/include.hpp>\n#include <boost/statistics/detail/importance_sampling/statistics/percentage_effective_sample_size.hpp>\n\nvoid example_sampler(std::ostream& os){\n    os << \"->example_sampler : \\n\";\n\n    // Sample from N(x|mu,sigma^2)N(x|mu,sigma^2) = N(x|mu,sigma^2/2), \n    // using SIR with N(x|mu+sigma,sigma^2) as proposal density. \n    // The quality of the sample is assessed by a series of \n    // kolmorov-distances along the the sample size of the targets.    \n    using namespace boost;\n    namespace stat = boost::statistics::detail;\n    namespace dist = stat::distribution;\n    namespace tk = stat::distribution::toolkit;\n    namespace is = stat::importance_sampling;\n\n    typedef std::string                                 str_;\n    typedef double                                      val_;\n    typedef std::vector<val_>                           vals_;\n    typedef range_iterator<vals_>::type                 vals_it_;\n    typedef math::normal_distribution<val_>             dist_;\n    typedef mt19937                                     urng_;\n    typedef is::prepare_weights<val_>                   prepare_weights_;\n\n    typedef stat::accumulator::tag::percentage_effective_sample_size tag_ess_;\n    typedef stat::accumulator::tag::proportion_less_than tag_plt_; \n    typedef boost::accumulators::stats<tag_ess_,tag_plt_> stats_;\n    typedef boost::accumulators::accumulator_set<val_,stats_> acc_;\n    typedef std::size_t                                 size_;\n\n    typedef boost::mpl::int_<0> k0_;\n    typedef boost::mpl::int_<1> k1_;\n\ttypedef boost::fusion::result_of::make_map<k0_,k1_,val_,val_>::type data_;\n    typedef std::vector<data_>                          vec_data_;\n    typedef range_iterator<vec_data_>::type             vec_data_it_;\n\n    typedef stat::fusion::at_key::meta_range<\n        vec_data_it_,\n        k0_\n    >::type range1_;\n    typedef is::sampler<range1_,val_>                   \tis_sampler_;\n    typedef boost::variate_generator<urng_&,is_sampler_> \tvg_;\n\n    // Constants\n    const unsigned n_p          = 5e4;             \n    const val_ max_log          = 100.0;           \n    const val_ mu               = 0.0;\n    const val_ sigma            = 1.0;\n    const val_ t_mu             = mu + sigma;\n    const val_ t_sigma          = sigma/sqrt(2.0);\n    const val_ eps = boost::math::tools::epsilon<val_>();\n\n    const unsigned n_loops  = 7;\n    const unsigned n1       = 1e1;\n    const unsigned n2       = 1e1;\n\n    prepare_weights_ prepare_weights( max_log );\n    dist_ p_d( mu, sigma );       // proposal\n    dist_ t_d( t_mu, t_sigma );   // target\n\n    urng_ urng;\n\n    vec_data_ proposals(n_p); \n    {\n        // Generate proposal values and their log_pdf\n        // {(x,log_pdf(x)):i=1,...,n_p}\n\t\tBOOST_AUTO(vg,dist::make_random_generator(urng,p_d));        \n        BOOST_FOREACH(data_& data,proposals){\n        \tval_ x = vg();\n\t\t\tboost::fusion::at_key<k0_>(data) = x;\n            boost::fusion::at_key<k1_>(data) = log_unnormalized_pdf(p_d,x);\n\t\t}        \n    }\n    vals_ is_weights( n_p );\n    {\n        // is_weights <- log_pdf(t_d) - log_pdf(p_d)\n\n        vals_it_ i = boost::begin( is_weights );\n        BOOST_FOREACH(const data_& d, proposals)\n        {\n            *i = log_unnormalized_pdf( t_d, fusion::at_key<k0_>(d) ) \n                - fusion::at_key<k1_>(d);\n            ++i;\n        }\n\n    }\n    { \n        //is_weights <- exp(is_weights + c )\n        prepare_weights(\n            boost::begin(is_weights),\n            boost::end(is_weights)\n        );\n        os << \"weights : \" << std::endl\n            << prepare_weights_::header << \" = \"\n            << prepare_weights << std::endl;\n    }\n    {\n        acc_ acc = std::for_each(\n            boost::begin(is_weights),\n            boost::end(is_weights),\n            acc_(( stat::accumulator::keyword::threshold = eps ))\n        );\n        val_ ess = boost::accumulators::extract_result<tag_ess_>(acc);\n        val_ plt_eps = boost::accumulators::extract_result<tag_plt_>(acc);\n        const std::string str \n        \t= (boost::format(\"(ess,plt_eps) = (%1%,%2%)\")% ess % plt_eps).str();\n        os << str << std::endl;\n    }\n    {\n        range1_ r1 = stat::fusion::at_key::make_range<k0_>(\n            boost::begin(proposals),\n            boost::end(proposals)\n        );\n        vg_ vg(\n            urng,\n            is_sampler_(\n                is_weights,\n                r1\n            )\n        );\n        vec_data_ targets;\n        {\n            os << \"proposal : \" << description(p_d) << std::endl; \n            os << \"target : \" \t<< description(t_d) << std::endl; \n\t\t\tnamespace ks = boost::statistics::detail::kolmogorov_smirnov;\n\t\t\ttypedef ks::check_convergence<val_> check_;\n\t        check_ check;\n\t\t\tcheck(n_loops,n1,n2,t_d,vg,os);\n\n        }\n    }\n\n    os << \"<-\" << std::endl;\n\n}\n\n\n", "meta": {"hexsha": "f4bbc263b3a43564f47f578d3bec5875d7a5df09", "size": 7237, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "importance_sampling/libs/statistics/detail/importance_sampling/example/sampler.cpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "importance_sampling/libs/statistics/detail/importance_sampling/example/sampler.cpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "importance_sampling/libs/statistics/detail/importance_sampling/example/sampler.cpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7005347594, "max_line_length": 102, "alphanum_fraction": 0.6048086224, "num_tokens": 1713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.831143031127974, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4317965262628747}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *\n *\n */\n\n#include <cmath>\n\n#include <Eigen/Geometry>\n\n#include \"Tudat/Mathematics/BasicMathematics/rotationAboutArbitraryAxis.h\"\n\nnamespace tudat\n{\nnamespace basic_mathematics\n{\n\n//! Compute rotation of point about arbitrary axis\nEigen::Vector3d computeRotationOfPointAboutArbitraryAxis(\n        const Eigen::Vector3d& originOfRotation,\n        const double angleOfRotation,\n        const Eigen::Vector3d& axisOfRotation,\n        const Eigen::Vector3d& initialPositionOfPoint )\n{\n\n    //Declare and initialize rotation matrix\n    Eigen::Matrix3d rotationMatrix = Eigen::Matrix3d::Zero( );\n\n    // Compute rotation matrix using AngleAxis object.\n    rotationMatrix = Eigen::AngleAxisd( angleOfRotation, axisOfRotation.normalized( ) );\n\n    // Compute initial of position of point with respect to origin of rotation.\n    const Eigen::Vector3d initialPositionOfPointWithRespectToOriginOfRotation =\n            initialPositionOfPoint - originOfRotation;\n\n    // Compute rotation of point about axis of rotation with respect to origin of rotation.\n    const Eigen::Vector3d rotatedPositionWithRespectToOriginOfRotation =\n            rotationMatrix * initialPositionOfPointWithRespectToOriginOfRotation;\n\n    //Return position with respect to the chosen arbitrary origin after rotation about\n    //arbitrary axis.\n    return rotatedPositionWithRespectToOriginOfRotation + originOfRotation;\n\n}\n\n//! Compute rotation of vector about arbitrary axis\nEigen::Vector3d computeRotationOfVectorAboutArbitraryAxis(\n        const Eigen::Vector3d& originOfRotation,\n        const double angleOfRotation,\n        const Eigen::Vector3d& axisOfRotation,\n        const Eigen::Vector3d& initialPositionOfVectorTail,\n        const Eigen::Vector3d& initialVector )\n{\n\n    // Compute rotation of the tail of vector. Resulted position is with respect to the chosen\n    // arbitrary origin.\n    Eigen::Vector3d rotatedPositionOfVectorTail =\n            computeRotationOfPointAboutArbitraryAxis( originOfRotation, angleOfRotation,\n                                                      axisOfRotation, initialPositionOfVectorTail );\n\n    // Compute rotation of the head of vector. Resulted position is with respect to the chosen\n    // arbitrary origin.\n    Eigen::Vector3d rotatedPositionOfVectorHead =\n            computeRotationOfPointAboutArbitraryAxis( originOfRotation, angleOfRotation,\n                                                      axisOfRotation,\n                                                      initialPositionOfVectorTail + initialVector );\n\n    // Return rotated vector with respect to the chosen arbitrary origin\n    return rotatedPositionOfVectorHead - rotatedPositionOfVectorTail;\n\n}\n\n} // namespace basic_mathematics\n} // namespace tudat\n", "meta": {"hexsha": "299c0f44f0b27b4e18db8521a5799130fbab2b64", "size": 3289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/rotationAboutArbitraryAxis.cpp", "max_stars_repo_name": "ViktorJordanov/tudat", "max_stars_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Mathematics/BasicMathematics/rotationAboutArbitraryAxis.cpp", "max_issues_repo_name": "ViktorJordanov/tudat", "max_issues_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Mathematics/BasicMathematics/rotationAboutArbitraryAxis.cpp", "max_forks_repo_name": "ViktorJordanov/tudat", "max_forks_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8045977011, "max_line_length": 100, "alphanum_fraction": 0.7138948009, "num_tokens": 698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505782, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.43159092016119344}}
{"text": "/* Copyright (c) 2017, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n// g++ -Wall -std=c++1z -I /usr/include/eigen3/ main.cpp -o test \n#include <random>\n#include <cmath>\n#include <iostream>\n#include <Eigen/Dense>\n#include \"vmf.hpp\"\n#include \"vmfPrior.hpp\"\n#include \"normal.hpp\"\n#include \"sample.hpp\"\n\nint main() {\n\n  std::mt19937 rnd(1);\n\n  vMF<float,3> vmfA(Eigen::Vector3f(1,0,0), 500);\n  vMF<float,3> vmfB(Eigen::Vector3f(cos(5*M_PI/180.),sin(5*M_PI/180.),0), 500);\n  Eigen::Matrix3f SigmaO = 0.0001*Eigen::Matrix3f::Identity();\n  Normal<float,3> gaussO(SigmaO);\n  float tauO = 500.;\n\n  size_t N=100;\n  std::vector<std::vector<Eigen::Vector3f>> n; // normals\n  std::vector<std::vector<Eigen::Vector3f>> xn; // normal observations\n  std::vector<std::vector<Eigen::Vector3f>> x; // loc observations\n  std::vector<std::vector<Eigen::Vector3f>> p; // plane location\n  for (size_t i=0; i<N; ++i) {\n    n.push_back(std::vector<Eigen::Vector3f>());\n    xn.push_back(std::vector<Eigen::Vector3f>());\n    x.push_back(std::vector<Eigen::Vector3f>());\n    p.push_back(std::vector<Eigen::Vector3f>());\n    for (size_t j=0; j<N; ++j) {\n      if (i<N/2) {\n        n[i].push_back(vmfA.sample(rnd));\n        xn[i].push_back(vmfA.sample(rnd));\n        x[i].push_back(Eigen::Vector3f(1.,(i-N*0.25)/float(0.25*N),(j-N*0.5)/float(0.5*N)));\n      }\n      if (i>=N/2) {\n        n[i].push_back(vmfB.sample(rnd));\n        xn[i].push_back(vmfB.sample(rnd));\n        x[i].push_back(Eigen::Vector3f((N*0.75-i)/float(0.25*N),1.,(j-N*0.5)/float(0.5*N)));\n      }\n      p[i].push_back(x[i][j]);\n      x[i][j] += gaussO.sample(rnd);\n      p[i][j] += gaussO.sample(rnd);\n//      std::cout << i << \" \" << j << \": \"  <<  x[i][j][0] << \"\\t\" << x[i][j][1] << std::endl;\n    }\n  }\n  std::cout << \"have \" << n.size() << \" input data\" << std::endl;\n\n  std::vector<Eigen::Vector3f> xSum(1, Eigen::Vector3f::Zero());\n  std::vector<std::vector<uint32_t>> z(n.size());\n  for (size_t i=0; i<n.size(); ++i) \n    for (size_t j=0; j<n[i].size(); ++j)  {\n      xSum[0] += n[i][j];\n      z[i].push_back(0);\n    }\n  std::vector<float> counts(1, n.size()*n.size());\n  std::vector<vMF<float,3>> vmfs;\n  vMFprior<float> base(Eigen::Vector3f(0,0,1), .1, 0.0);\n  float logAlpha = log(10.);\n  float lambda = .10;\n\n  vmfs.push_back(base.sample(rnd));\n  for (size_t it=0; it<10000; ++it) {\n    // sample labels | parameters\n    size_t K = vmfs.size();\n    for (size_t i=0; i<n.size(); ++i) {\n      for (size_t j=0; j<n[i].size(); ++j) {\n        Eigen::VectorXf logPdfs(K+1);\n        Eigen::VectorXf pdfs(K+1);\n\n        Eigen::VectorXf neighNs = Eigen::VectorXf::Zero(K);\n//        if (i+1<N) neighNs[z[i+1][j]] += 1.f;\n//        if (i>=1)  neighNs[z[i-1][j]] += 1.f;\n//        if (j+1<N) neighNs[z[i][j+1]] += 1.f;\n//        if (j>=1)  neighNs[z[i][j-1]] += 1.f;\n\n        if (i+1<N) neighNs[z[i+1][j]] += n[i+1][j].dot(n[i][j]);\n        if (i>=1)  neighNs[z[i-1][j]] += n[i-1][j].dot(n[i][j]);\n        if (j+1<N) neighNs[z[i][j+1]] += n[i][j+1].dot(n[i][j]);\n        if (j>=1)  neighNs[z[i][j-1]] += n[i][j-1].dot(n[i][j]);\n\n//        if (i+1<N) neighNs[z[i+1][j]] += vmfs[z[i+1][j]].mu_.dot(n[i][j]);\n//        if (i>=1)  neighNs[z[i-1][j]] += vmfs[z[i-1][j]].mu_.dot(n[i][j]);\n//        if (j+1<N) neighNs[z[i][j+1]] += vmfs[z[i][j+1]].mu_.dot(n[i][j]);\n//        if (j>=1)  neighNs[z[i][j-1]] += vmfs[z[i][j-1]].mu_.dot(n[i][j]);\n\n//        if (i+1<N) neighNs[z[i+1][j]] += vmfs[z[i+1][j]].mu_.dot(vmfs[z[i][j]].mu_);\n//        if (i>=1)  neighNs[z[i-1][j]] += vmfs[z[i-1][j]].mu_.dot(vmfs[z[i][j]].mu_);\n//        if (j+1<N) neighNs[z[i][j+1]] += vmfs[z[i][j+1]].mu_.dot(vmfs[z[i][j]].mu_);\n//        if (j>=1)  neighNs[z[i][j-1]] += vmfs[z[i][j-1]].mu_.dot(vmfs[z[i][j]].mu_);\n\n        for (size_t k=0; k<K; ++k) {\n          logPdfs[k] = lambda*(neighNs[k]-4);\n          if (z[i][j] == k) {\n            // TODO what if last in cluster\n            logPdfs[k] += log(counts[k]-1)+vmfs[k].logPdf(n[i][j]);\n          } else {\n            logPdfs[k] += log(counts[k])+vmfs[k].logPdf(n[i][j]);\n          }\n        }\n        logPdfs[K] = logAlpha + base.logMarginal(n[i][j]);\n        logPdfs = logPdfs.array() - logSumExp<float>(logPdfs);\n        pdfs = logPdfs.array().exp();\n        size_t zPrev = z[i][j];\n        z[i][j] = sampleDisc(pdfs, rnd);\n        //      std::cout << z[i] << \" \" << K << \": \" << pdfs.transpose() << std::endl;\n        if (z[i][j] == K) {\n          vmfs.push_back(base.posterior(n[i][j],1).sample(rnd));\n          counts.push_back(0);\n          xSum.push_back(Eigen::Vector3f::Zero());\n          K++;\n        }\n        if (zPrev != z[i][j]) {\n          counts[zPrev] --;\n          counts[z[i][j]] ++;\n          xSum[zPrev] -= n[i][j];\n          xSum[z[i][j]] += n[i][j];\n        }\n      }\n    }\n//    std::cout << \"sample parameters\" << std::endl;\n    // sample parameters | labels\n//    for (size_t i=0; i<n.size(); ++i) {\n//      xSum[z[i]] += n[i]; // TODO: can fold in above as well\n//    }\n    for (size_t k=0; k<K; ++k) {\n      if (counts[k] > 0) {\n        vmfs[k] = base.posterior(xSum[k],counts[k]).sample(rnd);\n      }\n    }\n    std::cout << \"counts \" << K << \": \";\n    for (size_t k=0; k<K; ++k) if (counts[k] > 0) std::cout << counts[k] << \" \";\n    std::cout << \"\\ttaus: \" ;\n    for (size_t k=0; k<K; ++k) if (counts[k] > 0) std::cout << vmfs[k].tau_ << \" \";\n    std::cout << std::endl;\n//    for (size_t k=0; k<K; ++k) \n//      if (counts[k] > 0) {\n//        std::cout << vmfs[k].mu_.transpose() << std::endl;\n//      }\n\n    // sample ns\n    for (size_t k=0; k<K; ++k) \n      xSum[k] = Eigen::Vector3f::Zero();\n    for (size_t i=0; i<n.size(); ++i) {\n      for (size_t j=0; j<n[i].size(); ++j) {\n        Eigen::Vector3f mu = xn[i][j]*tauO + vmfs[z[i][j]].mu_*vmfs[z[i][j]].tau_;\n        n[i][j] = vMF<float,3>(mu).sample(rnd);\n        xSum[z[i][j]] += n[i][j];\n      }\n    }\n//    std::cout << n[N/4][N/2].transpose() << \"\\t\" << n[(3*N)/4][N/2].transpose() << std::endl;\n//    std::cout << xn[N/4][N/2].transpose() << \"\\t\" << xn[(3*N)/4][N/2].transpose() << std::endl;\n\n    // sample locations\n    for (size_t i=0; i<x.size(); ++i) {\n      for (size_t j=0; j<x[i].size(); ++j) {\n        Eigen::Matrix3f SigmaPl;\n        Eigen::Matrix3f Info =  SigmaO.inverse();\n        Eigen::Vector3f xi = SigmaO.ldlt().solve(x[i][j]);\n        if (i+1<N && z[i][j] == z[i+1][j]) {\n          SigmaPl = vmfs[z[i+1][j]].mu_*vmfs[z[i+1][j]].mu_.transpose();\n          Info += SigmaPl;\n          xi += SigmaPl*p[i+1][j];\n        }\n        if (i>=1 && z[i][j] == z[i-1][j])  {\n          SigmaPl = vmfs[z[i-1][j]].mu_*vmfs[z[i-1][j]].mu_.transpose();\n          Info += SigmaPl;\n          xi += SigmaPl*p[i-1][j];\n        }\n        if (j+1<N && z[i][j] == z[i][j+1]) {\n          SigmaPl = vmfs[z[i][j+1]].mu_*vmfs[z[i][j+1]].mu_.transpose();\n          Info += SigmaPl;\n          xi += SigmaPl*p[i][j+1];\n        }                                           \n        if (j>=1 && z[i][j] == z[i][j-1])  {                                \n          SigmaPl = vmfs[z[i][j-1]].mu_*vmfs[z[i][j-1]].mu_.transpose();\n          Info += SigmaPl;\n          xi += SigmaPl*p[i][j-1];\n        }\n        Eigen::Matrix3f Sigma = Info.inverse();\n        Eigen::Vector3f mu = Sigma*xi;\n//        std::cout << xi.transpose() << \" \" << mu.transpose() << std::endl;\n        p[i][j] = Normal<float,3>(mu, Sigma).sample(rnd);\n      }\n    }\n//    std::cout << p[N/4][N/2].transpose() << \"\\t\" << p[(3*N)/4][N/2].transpose() << std::endl;\n//    std::cout << x[N/4][N/2].transpose() << \"\\t\" << x[(3*N)/4][N/2].transpose() << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "e11505dc1b5725cdb24c04439b02b01e7947d347", "size": 7645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/dpvmf/mainMRFDPvMFPlanes.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "experiments/dpvmf/mainMRFDPvMFPlanes.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "experiments/dpvmf/mainMRFDPvMFPlanes.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 39.2051282051, "max_line_length": 97, "alphanum_fraction": 0.4817527796, "num_tokens": 2823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.4315595540685473}}
{"text": "// Copyright (c) 2017 Franka Emika GmbH\n// Use of this source code is governed by the Apache-2.0 license, see LICENSE\n#include <array>\n#include <atomic>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <iterator>\n#include <mutex>\n#include <thread>\n\n#include <Eigen/Core>\n#include <Eigen/Eigen>\n\n#include <franka/duration.h>\n#include <franka/exception.h>\n#include <franka/model.h>\n#include <franka/rate_limiting.h>\n#include <franka/robot.h>\n\nnamespace {\ntemplate <class T, size_t N>\nstd::ostream& operator<<(std::ostream& ostream, const std::array<T, N>& array) {\n  ostream << \"[\";\n  std::copy(array.cbegin(), array.cend() - 1, std::ostream_iterator<T>(ostream, \",\"));\n  std::copy(array.cend() - 1, array.cend(), std::ostream_iterator<T>(ostream));\n  ostream << \"]\";\n  return ostream;\n}\n}  // anonymous namespace\n\n\nint main(int argc, char** argv) {\n  // Check whether the required arguments were passed.\n  if (argc != 2) {\n    std::cerr << \"Usage: \" << argv[0] << \" <robot-hostname>\" << std::endl;\n    return -1;\n  }\n\n  // Initialize data fields for the print thread.\n  struct {\n    std::mutex mutex;\n    bool has_data;\n    franka::RobotState robot_state;\n    std::array<double, 7> tau_d_calculated;\n    std::array<double, 7> tau_d_last;\n    std::array<double, 7> gravity;\n    std::array<double, 7> coriolis;\n    std::array<double, 42> jacobian_array;\n  } print_data{};\n  std::atomic_bool running{true};\n  const double print_rate = 10.0;\n  // Start print thread.\n  std::thread print_thread([print_rate, &print_data, &running]() {\n    while (running) {\n      // Sleep to achieve the desired print rate.\n      std::this_thread::sleep_for(\n          std::chrono::milliseconds(static_cast<int>((1.0 / print_rate * 1000.0))));\n\n      // Try to lock data to avoid read write collisions.\n      if (print_data.mutex.try_lock()) {\n        if (print_data.has_data) {\n          // std::array<double, 7> tau_error{};\n          // double error_rms(0.0);\n          // std::array<double, 7> tau_d_actual{};\n          // for (size_t i = 0; i < 7; ++i) {\n          //   tau_d_actual[i] = print_data.tau_d_last[i] + print_data.gravity[i];\n          //   tau_error[i] = tau_d_actual[i] - print_data.robot_state.tau_J[i];\n          //   error_rms += std::pow(tau_error[i], 2.0) / tau_error.size();\n          // }\n          // error_rms = std::sqrt(error_rms);\n          const Eigen::Matrix<double, 7, 1> mytorques(print_data.robot_state.tau_ext_hat_filtered.data());\n          const Eigen::Matrix<double, 6, 7> jacobian(print_data.jacobian_array.data());\n\n          const Eigen::MatrixXd jacobianPinv1 = ( jacobian * jacobian.transpose() ).inverse() * jacobian;\n          const Eigen::VectorXd mywrench1= jacobianPinv1 * mytorques;\n\n          Eigen::FullPivLU<Eigen::Matrix<double, 6, 6>> lu_decomp_ = Eigen::FullPivLU<Eigen::Matrix<double, 6, 6>>();\n          lu_decomp_.compute( jacobian * jacobian.transpose() );\n          const Eigen::MatrixXd jacobianPinv2 = lu_decomp_.inverse() * jacobian;\n          const Eigen::VectorXd mywrench2 = jacobianPinv2 * mytorques;\n\n          Eigen::JacobiSVD<Eigen::Matrix<double, 7, 6>> svdT = Eigen::JacobiSVD<Eigen::Matrix<double, 7, 6>>();\n          svdT.setThreshold(0.08); //critical singular value threshold is 0.08\n          svdT.compute(jacobian.transpose(), Eigen::ComputeThinU | Eigen::ComputeThinV);\n          const Eigen::VectorXd mywrench3 = svdT.solve(mytorques);\n\n          const Eigen::MatrixXd U = svdT.matrixU();\n          const Eigen::MatrixXd V = svdT.matrixV();\n          const Eigen::VectorXd Svec  = svdT.singularValues();\n          Eigen::Matrix<double, 6, 6> S = Eigen::Matrix<double, 6, 6>::Zero();\n          S.diagonal() = Svec;\n          Eigen::Matrix<double, 6, 6> Sinv = Eigen::Matrix<double, 6, 6>::Zero();\n          // Sinv = S.inverse();\n          for(int i=0; i<6; i++){\n            if (Svec(i)>=0.08){\n              Sinv(i,i) = 1.0 / Svec(i);\n            }\n          }\n          const Eigen::MatrixXd jacobianPinv4 = V * Sinv * U.transpose();\n          const Eigen::VectorXd mywrench4 = jacobianPinv4 * mytorques;\n\n\n          // Print data to console\n          std::cout << \"control_command_success_rate: \" <<  print_data.robot_state.control_command_success_rate << std::endl\n                    << \"joint configuration: \" <<  print_data.robot_state.q << std::endl\n                    // << \"jacobian: \\n\" << jacobian << std::endl\n                    // << \"U: \\n\" << U << std::endl\n                    // << \"V: \\n\" << V << std::endl\n                    // << \"S: \\n\" << S << std::endl\n                    // << \"Sinv: \\n\" << Sinv << std::endl\n                    // << \"jacobianPinv: \\n\" << jacobianPinv1.row(0) << std::endl\n                    // << \"jacobianPinv: \\n\" << jacobianPinv2.row(0) << std::endl\n                    // << \"jacobianPinv: \\n\" << jacobianPinv4.row(0) << std::endl\n                    // << \"jacobian-singularValues: \" << svdT.singularValues().transpose() << std::endl\n                    << \"External torque, filtered: \" <<  print_data.robot_state.tau_ext_hat_filtered << std::endl\n                    // << \"end-effector wrench (base frame)     : \" <<  print_data.robot_state.K_F_ext_hat_K << std::endl\n                    << \"end-effector wrench (stiffness frame): \" <<  print_data.robot_state.O_F_ext_hat_K << std::endl\n                    << \"end-effector wrench (stiffness frame): \" <<  mywrench1.transpose() << std::endl\n                    << \"end-effector wrench (stiffness frame): \" <<  mywrench2.transpose() << std::endl\n                    << \"end-effector wrench (stiffness frame): \" <<  mywrench3.transpose() << std::endl\n                    << \"end-effector wrench (stiffness frame): \" <<  mywrench4.transpose() << std::endl\n                    // << \"tau_error [Nm]: \" << tau_error << std::endl\n                    // << \"tau_commanded [Nm]: \" << tau_d_actual << std::endl\n                    // << \"tau_measured [Nm]: \" << print_data.robot_state.tau_J << std::endl\n                    // << \"root mean square of tau_error [Nm]: \" << error_rms << std::endl\n                    << \"-----------------------\" << std::endl\n                    ;\n          print_data.has_data = false;\n        }\n        print_data.mutex.unlock();\n      }\n    }\n  });\n\n  try {\n    franka::Robot robot(argv[1]);\n    robot.setJointImpedance({{3000, 3000, 3000, 2500, 2500, 2000, 2000}}); //values taken from https://github.com/frankaemika/libfranka/blob/master/examples/examples_common.cpp#L18\n    robot.setCartesianImpedance({{3000, 3000, 3000, 300, 300, 300}}); //values taken from https://github.com/frankaemika/libfranka/blob/master/examples/examples_common.cpp#L19\n    // robot.setJointImpedance({{100,100,100,100,100,100,100}}); \n    // robot.setCartesianImpedance({{100,100,100,10,10,10}});\n    robot.setCollisionBehavior(\n        {{20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0}}, {{20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0}},\n        {{20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0}}, {{20.0, 20.0, 18.0, 18.0, 16.0, 14.0, 12.0}},\n        {{20.0, 20.0, 20.0, 25.0, 25.0, 25.0}}, {{20.0, 20.0, 20.0, 25.0, 25.0, 25.0}},\n        {{20.0, 20.0, 20.0, 25.0, 25.0, 25.0}}, {{20.0, 20.0, 20.0, 25.0, 25.0, 25.0}});\n\n    //TODO: be careful with this mode!\n    robot.setCollisionBehavior(\n        {{2000.0, 2000.0, 1800.0, 1800.0, 1600.0, 1400.0, 1200.0}}, {{2000.0, 2000.0, 1800.0, 1800.0, 1600.0, 1400.0, 1200.0}},\n        {{2000.0, 2000.0, 1800.0, 1800.0, 1600.0, 1400.0, 1200.0}}, {{2000.0, 2000.0, 1800.0, 1800.0, 1600.0, 1400.0, 1200.0}},\n        {{2000.0, 2000.0, 2000.0, 2500.0, 2500.0, 2500.0}}, {{2000.0, 2000.0, 2000.0, 2500.0, 2500.0, 2500.0}},\n        {{2000.0, 2000.0, 2000.0, 2500.0, 2500.0, 2500.0}}, {{2000.0, 2000.0, 2000.0, 2500.0, 2500.0, 2500.0}});\n    \n    franka::Model model = robot.loadModel();\n\n    // const std::array<double, 7> d_gains = {{50.0, 50.0, 50.0, 50.0, 30.0, 25.0, 15.0}};\n    const std::array<double, 7> d_gains = {{15.0, 15.0, 15.0, 15.0, 9.0, 8.0, 4.0}};\n    // const std::array<double, 7> d_gains = {{5.0, 5.0, 5.0, 5.0, 3.0, 2.5, 1.5}};\n    // const std::array<double, 7> d_gains = {{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}}; //TODO pure gravity compensation mode (with coriolis) performs very bad\n\n    // Define callback for the joint torque control loop.\n    std::function<franka::Torques(const franka::RobotState&, franka::Duration)>\n        impedance_control_callback =\n            [&print_data, &model, d_gains](\n                const franka::RobotState& state, franka::Duration /*period*/) -> franka::Torques {\n\n      const std::array<double, 7> gravity = model.gravity(state);\n      const std::array<double, 7> coriolis = model.coriolis(state);\n      const std::array<double, 42> jacobian_array = model.zeroJacobian(franka::Frame::kEndEffector, state);\n\n      // Compute torque command\n      std::array<double, 7> tau_d_calculated;\n      for (size_t i = 0; i < 7; i++) {\n        tau_d_calculated[i] = - d_gains[i] * state.dq[i] + coriolis[i];\n      }\n\n      // The following line is only necessary for printing the rate limited torque. As we activated\n      // rate limiting for the control loop (activated by default), the torque would anyway be\n      // adjusted!\n      std::array<double, 7> tau_d_rate_limited =\n          franka::limitRate(franka::kMaxTorqueRate, tau_d_calculated, state.tau_J_d);\n\n      // Update data to print.\n      if (print_data.mutex.try_lock()) {\n        print_data.has_data = true;\n        print_data.robot_state = state;\n        print_data.tau_d_calculated = tau_d_calculated;\n        print_data.tau_d_last = tau_d_rate_limited;\n        print_data.gravity = gravity;\n        print_data.coriolis = coriolis;\n        print_data.jacobian_array = jacobian_array;\n        print_data.mutex.unlock();\n      }\n\n      // Send torque command.\n      return tau_d_rate_limited;\n    };\n\n    // Start real-time control loop.\n    robot.control(impedance_control_callback);\n\n  } catch (const franka::Exception& ex) {\n    running = false;\n    std::cerr << ex.what() << std::endl;\n  }\n\n  if (print_thread.joinable()) {\n    print_thread.join();\n  }\n  return 0;\n}\n", "meta": {"hexsha": "c3f3720d3e3e89ae2706881cc7ef8289cdf78a3e", "size": 10097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GravComp.cpp", "max_stars_repo_name": "ndehio/mc_franka", "max_stars_repo_head_hexsha": "230fda2c0f872ccd9cd387159b46ca769930519b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GravComp.cpp", "max_issues_repo_name": "ndehio/mc_franka", "max_issues_repo_head_hexsha": "230fda2c0f872ccd9cd387159b46ca769930519b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GravComp.cpp", "max_forks_repo_name": "ndehio/mc_franka", "max_forks_repo_head_hexsha": "230fda2c0f872ccd9cd387159b46ca769930519b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.4037558685, "max_line_length": 180, "alphanum_fraction": 0.587501238, "num_tokens": 3186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.705785040214066, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4315042506075675}}
{"text": "/*=========================================================================\n *\n *  Copyright David Doria 2012 daviddoria@gmail.com\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http://www.apache.org/licenses/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*/\n\n#ifndef CorrelationAcceptanceVisitor_HPP\n#define CorrelationAcceptanceVisitor_HPP\n\n#include <boost/graph/graph_traits.hpp>\n\n// Parent class\n#include \"Visitors/AcceptanceVisitors/AcceptanceVisitorParent.h\"\n#include \"Visitors/AcceptanceVisitors/VarianceFunctor.hpp\"\n#include \"Visitors/AcceptanceVisitors/AverageFunctor.hpp\"\n\n// Custom\n#include \"ITKHelpers/ITKHelpers.h\"\n\n// ITK\n#include \"itkAddImageFilter.h\"\n#include \"itkMultiplyImageFilter.h\"\n#include \"itkImageRegion.h\"\n\n/**\n\n */\ntemplate <typename TGraph, typename TImage>\nstruct CorrelationAcceptanceVisitor : public AcceptanceVisitorParent<TGraph>\n{\n  TImage* Image;\n  Mask* MaskImage;\n\n  const unsigned int HalfWidth;\n\n  float Threshold;\n\n  typedef typename boost::graph_traits<TGraph>::vertex_descriptor VertexDescriptorType;\n\n  CorrelationAcceptanceVisitor(TImage* const image, Mask* const mask,\n                               const unsigned int halfWidth, const float threshold, const std::string& visitorName = \"CorrelationAcceptanceVisitor\") :\n  AcceptanceVisitorParent<TGraph>(visitorName), Image(image), MaskImage(mask),\n    HalfWidth(halfWidth), Threshold(threshold)\n  {\n\n  }\n\n  bool AcceptMatch(VertexDescriptorType target, VertexDescriptorType source, float& computedEnergy) const override\n  {\n    itk::Index<2> targetPixel = ITKHelpers::CreateIndex(target);\n    itk::ImageRegion<2> targetRegion = ITKHelpers::GetRegionInRadiusAroundPixel(targetPixel, HalfWidth);\n\n    itk::Index<2> sourcePixel = ITKHelpers::CreateIndex(source);\n    itk::ImageRegion<2> sourceRegion = ITKHelpers::GetRegionInRadiusAroundPixel(sourcePixel, HalfWidth);\n\n    typedef itk::Image<float, 2> FloatImageType;\n    \n    typedef itk::VectorMagnitudeImageFilter<TImage, FloatImageType> VectorMagnitudeFilterType;\n    typename VectorMagnitudeFilterType::Pointer magnitudeFilter = VectorMagnitudeFilterType::New();\n    magnitudeFilter->SetInput(Image);\n    magnitudeFilter->Update();\n\n    std::vector<itk::Offset<2> > validOffsets = MaskImage->GetValidOffsetsInRegion(targetRegion);\n\n    FloatImageType::Pointer sourceImage = FloatImageType::New();\n//     sourceImage->SetRegions(ITKHelpers::CornerRegion(sourceRegion.GetSize()));\n//     sourceImage->Allocate();\n    ITKHelpers::ExtractRegion(magnitudeFilter->GetOutput(), sourceRegion, sourceImage.GetPointer());\n\n    FloatImageType::Pointer targetImage = FloatImageType::New();\n//     sourceImage->SetRegions(ITKHelpers::CornerRegion(targetRegion.GetSize()));\n//     sourceImage->Allocate();\n    ITKHelpers::ExtractRegion(magnitudeFilter->GetOutput(), targetRegion, targetImage.GetPointer());\n\n    std::vector<itk::Index<2> > validIndices = ITKHelpers::OffsetsToIndices(validOffsets);\n\n    VarianceFunctor varianceFunctor;\n    AverageFunctor averageFunctor;\n    /////////// Target region //////////\n    std::vector<FloatImageType::PixelType> validPixelsTargetRegion = ITKHelpers::GetPixelValues(targetImage.GetPointer(), validIndices);\n    typename TypeTraits<FloatImageType::PixelType>::LargerType targetMean = averageFunctor(validPixelsTargetRegion);\n    typename TypeTraits<FloatImageType::PixelType>::LargerType targetStandardDeviation = sqrt(varianceFunctor(validPixelsTargetRegion));\n\n    typedef itk::AddImageFilter <FloatImageType, FloatImageType, FloatImageType> AddImageFilterType;\n    AddImageFilterType::Pointer targetAddImageFilter = AddImageFilterType::New();\n    targetAddImageFilter->SetInput(targetImage);\n    targetAddImageFilter->SetConstant2(-1.0f * targetMean);\n    targetAddImageFilter->Update();\n\n    typedef itk::MultiplyImageFilter<FloatImageType, FloatImageType, FloatImageType> MultiplyImageFilterType;\n    MultiplyImageFilterType::Pointer targetMultiplyImageFilter = MultiplyImageFilterType::New();\n    targetMultiplyImageFilter->SetInput(targetImage);\n    targetMultiplyImageFilter->SetConstant(1.0f/targetStandardDeviation);\n    targetMultiplyImageFilter->Update();\n\n    /////////// Source region //////////\n    std::vector<FloatImageType::PixelType> validPixelsSourceRegion = ITKHelpers::GetPixelValues(sourceImage.GetPointer(), validIndices);\n    typename TypeTraits<FloatImageType::PixelType>::LargerType sourceMean = averageFunctor(validPixelsSourceRegion);\n    typename TypeTraits<FloatImageType::PixelType>::LargerType sourceStandardDeviation = sqrt(varianceFunctor(validPixelsSourceRegion));\n\n    AddImageFilterType::Pointer sourceAddImageFilter = AddImageFilterType::New();\n    sourceAddImageFilter->SetInput(sourceImage);\n    sourceAddImageFilter->SetConstant2(-1.0f * sourceMean);\n    sourceAddImageFilter->Update();\n\n    MultiplyImageFilterType::Pointer sourceMultiplyImageFilter = MultiplyImageFilterType::New();\n    sourceMultiplyImageFilter->SetInput(sourceImage);\n    sourceMultiplyImageFilter->SetConstant(1.0f/sourceStandardDeviation);\n    sourceMultiplyImageFilter->Update();\n\n    // Initialize\n    computedEnergy = 0.0f;\n    \n    for(std::vector<itk::Index<2> >::const_iterator iter = validIndices.begin(); iter != validIndices.end(); ++iter)\n    {\n      computedEnergy += (sourceMultiplyImageFilter->GetOutput()->GetPixel(*iter) * targetMultiplyImageFilter->GetOutput()->GetPixel(*iter));\n    }\n\n    computedEnergy /= static_cast<float>(validIndices.size());\n\n    if(computedEnergy < Threshold)\n      {\n      std::cout << this->VisitorName << \": Match accepted (\" << computedEnergy << \" is less than \" << Threshold << \")\" << std::endl << std::endl;\n      return true;\n      }\n    else\n      {\n      std::cout << this->VisitorName << \": Match rejected (\" << computedEnergy << \" is greater than \" << Threshold << \")\" << std::endl << std::endl;\n      return false;\n      }\n  };\n\n};\n\n#endif\n", "meta": {"hexsha": "218dca3565e9f3a8b5340ada209bf560b8eec05d", "size": 6411, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Visitors/AcceptanceVisitors/CorrelationAcceptanceVisitor.hpp", "max_stars_repo_name": "jingtangliao/ff", "max_stars_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 39.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T07:59:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T18:11:46.000Z", "max_issues_repo_path": "Visitors/AcceptanceVisitors/CorrelationAcceptanceVisitor.hpp", "max_issues_repo_name": "jingtangliao/ff", "max_issues_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-24T09:56:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-24T14:45:46.000Z", "max_forks_repo_path": "Visitors/AcceptanceVisitors/CorrelationAcceptanceVisitor.hpp", "max_forks_repo_name": "jingtangliao/ff", "max_forks_repo_head_hexsha": "d308fe62045e241a4822bb855df97ee087420d9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2015-01-11T15:10:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:02:10.000Z", "avg_line_length": 43.3175675676, "max_line_length": 150, "alphanum_fraction": 0.7332709406, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.431504235473351}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_PQLAQuadrature.hpp\n//! \\author Philip Britt\n//! \\brief  PQLA Direction Quadrature handler declaration\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_PQLA_QUADRATURE\n#define UTILITY_PQLA_QUADRATURE\n\n// Boost Includes\n#include <boost/serialization/version.hpp>\n#include <boost/serialization/export.hpp>\n#include <boost/serialization/shared_ptr.hpp>\n\n// FRENSIE includes\n#include \"Utility_Vector.hpp\"\n#include \"Utility_Tuple.hpp\"\n#include \"Utility_Array.hpp\"\n#include \"Utility_ExplicitSerializationTemplateInstantiationMacros.hpp\"\n#include \"Utility_SerializationHelpers.hpp\"\n\nnamespace Utility{\n\nstruct SphericalTriangle\n{\n  /*! Vector that contains a tuple representing spherical triangle parameters.\n   * \\details First element of the tuple is an array that contains the\n   * 2-norm direction representing a vertex of the triangle. \n   * Second is the length of the spherical triangle side opposite from that vertex\n   * (or angle that the 2 other vertices of the triangle make with each other).\n   * Third is the angle made from the sides of the spherical triangle from that vertex.\n   * Note their order does NOT matter so long as they are consistent with the above definition\n   */\n  std::vector<std::tuple<std::array<double, 3>, double, double>> triangle_parameter_vector;\n\n  //! Area of the triangle\n  double area;\n\n    //! Processes spherical triangle information\n  void computeAndStoreTriangleParameters(std::vector<std::array<double, 3>>& vertex_vector);\n\n  // Serialize the data\n  template<typename Archive>\n  void serialize(Archive& ar, const unsigned version)\n  { \n    ar & BOOST_SERIALIZATION_NVP(triangle_parameter_vector);\n    ar & BOOST_SERIALIZATION_NVP(area);\n  }\n};\n\nclass PQLAQuadrature\n{\n\n  public:\n\n  //! Constructor\n  PQLAQuadrature(unsigned quadrature_order);\n\n  //! Destructor\n  ~PQLAQuadrature()\n  { /* ... */ }\n\n  //! Find which triangle bin a direction vector is in\n  size_t findTriangleBin(const std::array<double, 3>& direction) const;\n\n  //! Find which triangle bin a direction vector is in\n  size_t findTriangleBin(const double x_direction, const double y_direction, const double z_direction) const;\n\n  //! Return the order of the quadrature\n  unsigned getQuadratureOrder() const;\n\n  //! Get the total number of triangles\n  size_t getNumberOfTriangles() const;\n  \n  //! Get the area of a specific spherical triangle\n  double getTriangleArea(const size_t triangle_index) const;\n\n  /*! Get a random direction from within a spherical triangle (evenly distributed probability) - reference here\n   * \\details reference: Stratified Sampling of Spherical Triangles, James Arvo, SIGGRAPH '95\n   */\n  void sampleIsotropicallyFromTriangle(std::array<double, 3>& direction_vector, \n                                       const size_t triangle_index) const;\n\n  const std::vector<SphericalTriangle>& getSphericalTriangleVector() const;\n\n  private:\n\n  //! Default constructor (for archiving)\n  PQLAQuadrature()\n  { /* ... */ }\n\n  //! Vector operation for the purpose of sampleIsotropicallyFromTriangle\n  void isotropicSamplingVectorOperation(const std::array<double, 3>& vertex_1,\n                                        const std::array<double, 3>& vertex_2,\n                                        std::array<double, 3>& result_vector) const;\n\n  //! Converts direction vector to 1-norm normalized vector\n  void normalizeVectorToOneNorm(const std::array<double, 3>& direction_2_norm,\n                                 std::array<double, 3>& direction_1_norm) const;\n  \n  //! Converts direction vector to 1-norm normalized vector\n  void normalizeVectorToOneNorm(const double x_direction, \n                                  const double y_direction, \n                                  const double z_direction,\n                                  std::array<double, 3>& direction_1_norm) const;\n\n  //! Take lower bounding plane indices of direction vector to form triangle index\n  size_t calculatePositiveTriangleBinIndex(const unsigned i_x, const unsigned i_y, const unsigned i_z) const;\n\n  //! Take direction signs to calculate secondary index\n  size_t findSecondaryIndex(const bool x_sign, const bool y_sign, const bool z_sign) const;\n\n  //! Quadrature order\n  unsigned d_quadrature_order;\n\n  //! Vector that stores POSITIVE DOMAIN spherical triangles\n  std::vector<SphericalTriangle> d_spherical_triangle_vector;\n\n  //! Serialize the data\n  template<typename Archive>\n  void serialize(Archive& ar, const unsigned version);\n\n  //! Declare the boost serialization access object as a friend\n  friend class boost::serialization::access;\n\n};\n\n// Serialize the data\ntemplate<typename Archive>\nvoid PQLAQuadrature::serialize(Archive& ar, const unsigned version)\n{\n  // Serialize the member data\n  ar & BOOST_SERIALIZATION_NVP(d_quadrature_order);\n  ar & BOOST_SERIALIZATION_NVP(d_spherical_triangle_vector);\n}\n\n} // end Utility namespace\n\nBOOST_SERIALIZATION_CLASS_VERSION(PQLAQuadrature, Utility, 0);\nBOOST_SERIALIZATION_CLASS_EXPORT_STANDARD_KEY(PQLAQuadrature, Utility);\nEXTERN_EXPLICIT_CLASS_SERIALIZE_INST(Utility, PQLAQuadrature);\n\n#endif // end UTILITY_PQLA_QUADRATURE\n\n//---------------------------------------------------------------------------//\n// end Utility_PQLADiscetization.hpp\n//---------------------------------------------------------------------------//", "meta": {"hexsha": "3d6404e640f8880156a21001bf74461ec2f9346f", "size": 5440, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/direction_discretization/src/Utility_PQLAQuadrature.hpp", "max_stars_repo_name": "psbritt/FRENSIE", "max_stars_repo_head_hexsha": "c992179a7663a4c529b63705ed7b4ddbe410c924", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-14T19:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T17:44:09.000Z", "max_issues_repo_path": "packages/utility/direction_discretization/src/Utility_PQLAQuadrature.hpp", "max_issues_repo_name": "psbritt/FRENSIE", "max_issues_repo_head_hexsha": "c992179a7663a4c529b63705ed7b4ddbe410c924", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T19:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T03:36:08.000Z", "max_forks_repo_path": "packages/utility/direction_discretization/src/Utility_PQLAQuadrature.hpp", "max_forks_repo_name": "psbritt/FRENSIE", "max_forks_repo_head_hexsha": "c992179a7663a4c529b63705ed7b4ddbe410c924", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T18:59:51.000Z", "avg_line_length": 36.5100671141, "max_line_length": 111, "alphanum_fraction": 0.6900735294, "num_tokens": 1150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.43144674114858894}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2014 Anton Bikineev\n//  Copyright 2014 Christopher Kormanyos\n//  Copyright 2014 John Maddock\n//  Copyright 2014 Paul Bristow\n//  Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_HYPERGEOMETRIC_1F1_HPP\n#define BOOST_MATH_HYPERGEOMETRIC_1F1_HPP\n\n#include <boost/config.hpp>\n\n#if defined(BOOST_NO_CXX11_AUTO_DECLARATIONS) || defined(BOOST_NO_CXX11_LAMBDAS) || defined(BOOST_NO_CXX11_UNIFIED_INITIALIZATION_SYNTAX)\n# error \"hypergeometric_1F1 requires a C++11 compiler\"\n#endif\n\n#include <boost/math/policies/policy.hpp>\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_series.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_asym.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_rational.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_1F1_recurrence.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_1F1_by_ratios.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_pade.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_1F1_bessel.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_1F1_scaled_series.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_pFq_checked_series.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_1F1_addition_theorems_on_z.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_1F1_large_abz.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_1F1_small_a_negative_b_by_ratio.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_1F1_negative_b_regions.hpp>\n\nnamespace boost { namespace math { namespace detail {\n\n   // check when 1F1 series can't decay to polynom\n   template <class T>\n   inline bool check_hypergeometric_1F1_parameters(const T& a, const T& b)\n   {\n      BOOST_MATH_STD_USING\n\n         if ((b <= 0) && (b == floor(b)))\n         {\n            if ((a >= 0) || (a < b) || (a != floor(a)))\n               return false;\n         }\n\n      return true;\n   }\n\n   template <class T, class Policy>\n   T hypergeometric_1F1_divergent_fallback(const T& a, const T& b, const T& z, const Policy& pol, int& log_scaling)\n   {\n      BOOST_MATH_STD_USING\n      const char* function = \"hypergeometric_1F1_divergent_fallback<%1%>(%1%,%1%,%1%)\";\n      //\n      // We get here if either:\n      // 1) We decide up front that Tricomi's method won't work, or:\n      // 2) We've called Tricomi's method and it's failed.\n      //\n      if (b > 0)\n      {\n         // Commented out since recurrence seems to always be better?\n#if 0\n         if ((z < b) && (a > -50))\n            // Might as well use a recurrence in preference to z-recurrence:\n            return hypergeometric_1F1_backward_recurrence_for_negative_a(a, b, z, pol, function, log_scaling);\n         T z_limit = fabs((2 * a - b) / (sqrt(fabs(a))));\n         int k = 1 + itrunc(z - z_limit);\n         // If k is too large we destroy all the digits in the result:\n         T convergence_at_50 = (b - a + 50) * k / (z * 50);\n         if ((k > 0) && (k < 50) && (fabs(convergence_at_50) < 1) && (z > z_limit))\n         {\n            return boost::math::detail::hypergeometric_1f1_recurrence_on_z_minus_zero(a, b, T(z - k), k, pol, log_scaling);\n         }\n#endif\n         if (z < b)\n            return hypergeometric_1F1_backward_recurrence_for_negative_a(a, b, z, pol, function, log_scaling);\n         else\n            return hypergeometric_1F1_backwards_recursion_on_b_for_negative_a(a, b, z, pol, function, log_scaling);\n      }\n      else  // b < 0\n      {\n         if (a < 0)\n         {\n            if ((b < a) && (z < -b / 4))\n               return hypergeometric_1F1_from_function_ratio_negative_ab(a, b, z, pol, log_scaling);\n            else\n            {\n               //\n               // Solve (a+n)z/((b+n)n) == 1 for n, the number of iterations till the series starts to converge.\n               // If this is well away from the origin then it's probably better to use the series to evaluate this.\n               // Note that if sqr is negative then we have no solution, so assign an arbitrarily large value to the\n               // number of iterations.\n               //\n               bool can_use_recursion = (z - b + 100 < boost::math::policies::get_max_series_iterations<Policy>()) && (100 - a < boost::math::policies::get_max_series_iterations<Policy>());\n               T sqr = 4 * a * z + b * b - 2 * b * z + z * z;\n               T iterations_to_convergence = sqr > 0 ? T(0.5f * (-sqrt(sqr) - b + z)) : T(-a - b);\n               if(can_use_recursion && ((std::max)(a, b) + iterations_to_convergence > -300))\n                  return hypergeometric_1F1_backwards_recursion_on_b_for_negative_a(a, b, z, pol, function, log_scaling);\n               //\n               // When a < b and if we fall through to the series, then we get divergent behaviour when b crosses the origin\n               // so ideally we would pick another method.  Otherwise the terms immediately after b crosses the origin may\n               // suffer catestrophic cancellation....\n               //\n               if((a < b) && can_use_recursion)\n                  return hypergeometric_1F1_backwards_recursion_on_b_for_negative_a(a, b, z, pol, function, log_scaling);\n            }\n         }\n         else\n         {\n            //\n            // Start by getting the domain of the recurrence relations, we get either:\n            //   -1     Backwards recursion is stable and the CF will converge to double precision.\n            //   +1     Forwards recursion is satble and the CF will converge to double precision.\n            //    0     No man's land, we're not far enough away from the crossover point to get double precision from either CF.\n            //\n            // At higher than double precision we need to be further away from the crossover location to\n            // get full converge, but it's not clear how much further - indeed at quad precision it's\n            // basically impossible to ever get forwards iteration to work.  Backwards seems to work\n            // OK as long as a > 1 whatever the precision tbough.\n            //\n            int domain = hypergeometric_1F1_negative_b_recurrence_region(a, b, z);\n            if ((domain < 0) && ((a > 1) || (boost::math::policies::digits<T, Policy>() <= 64)))\n               return hypergeometric_1F1_from_function_ratio_negative_b(a, b, z, pol, log_scaling);\n            else if (domain > 0)\n            {\n               if (boost::math::policies::digits<T, Policy>() <= 64)\n                  return hypergeometric_1F1_from_function_ratio_negative_b_forwards(a, b, z, pol, log_scaling);\n               try \n               {\n                  return hypergeometric_1F1_checked_series_impl(a, b, z, pol, log_scaling);\n               }\n               catch (const evaluation_error&)\n               {\n                  //\n                  // The series failed, try the recursions instead and hope we get at least double precision:\n                  //\n                  return hypergeometric_1F1_from_function_ratio_negative_b_forwards(a, b, z, pol, log_scaling);\n               }\n            }\n            //\n            // We could fall back to Tricomi's approximation if we're in the transition zone\n            // betweeen the above two regions.  However, I've been unable to find any examples\n            // where this is better than the series, and there are many cases where it leads to\n            // quite grievous errors.\n            /*\n            else if (allow_tricomi)\n            {\n               T aa = a < 1 ? T(1) : a;\n               if (z < fabs((2 * aa - b) / (sqrt(fabs(aa * b)))))\n                  return hypergeometric_1F1_AS_13_3_7_tricomi(a, b, z, pol, log_scaling);\n            }\n            */\n         }\n      }\n\n      // If we get here, then we've run out of methods to try, use the checked series which will\n      // raise an error if the result is garbage:\n      return hypergeometric_1F1_checked_series_impl(a, b, z, pol, log_scaling);\n   }\n\n   template <class T>\n   bool is_convergent_negative_z_series(const T& a, const T& b, const T& z, const T& b_minus_a)\n   {\n      BOOST_MATH_STD_USING\n      //\n      // Filter out some cases we don't want first:\n      //\n      if((b_minus_a > 0) && (b > 0))\n      {\n         if (a < 0)\n            return false;\n      }\n      //\n      // Generic check: we have small initial divergence and are convergent after 10 terms:\n      //\n      if ((fabs(z * a / b) < 2) && (fabs(z * (a + 10) / ((b + 10) * 10)) < 1))\n      {\n         // Double check for divergence when we cross the origin on a and b:\n         if (a < 0)\n         {\n            T n = 300 - floor(a);\n            if (fabs((a + n) * z / ((b + n) * n)) < 1)\n            {\n               if (b < 0)\n               {\n                  T m = 3 - floor(b);\n                  if (fabs((a + m) * z / ((b + m) * m)) < 1)\n                     return true;\n               }\n               else\n                  return true;\n            }\n         }\n         else if (b < 0)\n         {\n            T n = 3 - floor(b);\n            if (fabs((a + n) * z / ((b + n) * n)) < 1)\n               return true;\n         }\n      }\n      if ((b > 0) && (a < 0))\n      {\n         //\n         // For a and z both negative, we're OK with some initial divergence as long as\n         // it occurs before we hit the origin, as to start with all the terms have the\n         // same sign.\n         //\n         // https://www.wolframalpha.com/input/?i=solve+(a%2Bn)z+%2F+((b%2Bn)n)+%3D%3D+1+for+n\n         //\n         T sqr = 4 * a * z + b * b - 2 * b * z + z * z;\n         T iterations_to_convergence = sqr > 0 ? T(0.5f * (-sqrt(sqr) - b + z)) : T(-a + b);\n         if (iterations_to_convergence < 0)\n            iterations_to_convergence = 0.5f * (sqrt(sqr) - b + z);\n         if (a + iterations_to_convergence < -50)\n         {\n            // Need to check for divergence when we cross the origin on a:\n            if (a > -1)\n               return true;\n            T n = 300 - floor(a);\n            if(fabs((a + n) * z / ((b + n) * n)) < 1)\n               return true;\n         }\n      }\n      return false;\n   }\n\n   template <class T>\n   inline T cyl_bessel_i_shrinkage_rate(const T& z)\n   {\n      // Approximately the ratio I_10.5(z/2) / I_9.5(z/2), this gives us an idea of how quickly\n      // the Bessel terms in A&S 13.6.4 are converging:\n      if (z < -160)\n         return 1;\n      if (z < -40)\n         return 0.75f;\n      if (z < -20)\n         return 0.5f;\n      if (z < -7)\n         return 0.25f;\n      if (z < -2)\n         return 0.1f;\n      return 0.05f;\n   }\n\n   template <class T>\n   inline bool hypergeometric_1F1_is_13_3_6_region(const T& a, const T& b, const T& z)\n   {\n      BOOST_MATH_STD_USING\n      if(fabs(a) == 0.5)\n         return false;\n      if ((z < 0) && (fabs(10 * a / b) < 1) && (fabs(a) < 50))\n      {\n         T shrinkage = cyl_bessel_i_shrinkage_rate(z);\n         // We want the first term not too divergent, and convergence by term 10:\n         if ((fabs((2 * a - 1) * (2 * a - b) / b) < 2) && (fabs(shrinkage * (2 * a + 9) * (2 * a - b + 10) / (10 * (b + 10))) < 0.75))\n            return true;\n      }\n      return false;\n   }\n\n   template <class T>\n   inline bool hypergeometric_1F1_need_kummer_reflection(const T& a, const T& b, const T& z)\n   {\n      BOOST_MATH_STD_USING\n      //\n      // Check to see if we should apply Kummer's relation or not:\n      //\n      if (z > 0)\n         return false;\n      if (z < -1)\n         return true;\n      //\n      // When z is small and negative, things get more complex.\n      // More often than not we do not need apply Kummer's relation and the\n      // series is convergent as is, but we do need to check:\n      //\n      if (a > 0)\n      {\n         if (b > 0)\n         {\n            return fabs((a + 10) * z / (10 * (b + 10))) < 1;  // Is the 10'th term convergent?\n         }\n         else\n         {\n            return true;  // Likely to be divergent as b crosses the origin\n         }\n      }\n      else // a < 0\n      {\n         if (b > 0)\n         {\n            return false;  // Terms start off all positive and then by the time a crosses the origin we *must* be convergent.\n         }\n         else\n         {\n            return true;  // Likely to be divergent as b crosses the origin, but hard to rationalise about!\n         }\n      }\n   }\n\n      \n   template <class T, class Policy>\n   T hypergeometric_1F1_imp(const T& a, const T& b, const T& z, const Policy& pol, int& log_scaling)\n   {\n      BOOST_MATH_STD_USING // exp, fabs, sqrt\n\n      static const char* const function = \"boost::math::hypergeometric_1F1<%1%,%1%,%1%>(%1%,%1%,%1%)\";\n\n      if ((z == 0) || (a == 0))\n         return T(1);\n\n      // undefined result:\n      if (!detail::check_hypergeometric_1F1_parameters(a, b))\n         return policies::raise_domain_error<T>(\n            function,\n            \"Function is indeterminate for negative integer b = %1%.\",\n            b,\n            pol);\n\n      // other checks:\n      if (a == -1)\n         return 1 - (z / b);\n\n      const T b_minus_a = b - a;\n\n      // 0f0 a == b case;\n      if (b_minus_a == 0)\n      {\n         int scale = itrunc(z, pol);\n         log_scaling += scale;\n         return exp(z - scale);\n      }\n      // Special case for b-a = -1, we don't use for small a as it throws the digits of a away and leads to large errors:\n      if ((b_minus_a == -1) && (fabs(a) > 0.5))\n      {\n         // for negative small integer a it is reasonable to use truncated series - polynomial\n         if ((a < 0) && (a == ceil(a)) && (a > -50))\n            return detail::hypergeometric_1F1_generic_series(a, b, z, pol, log_scaling, function);\n\n         return (b + z) * exp(z) / b;\n      }\n\n      if ((a == 1) && (b == 2))\n         return boost::math::expm1(z, pol) / z;\n\n      if ((b - a == b) && (fabs(z / b) < policies::get_epsilon<T, Policy>()))\n         return 1;\n      //\n      // Special case for A&S 13.3.6:\n      //\n      if (z < 0)\n      {\n         if (hypergeometric_1F1_is_13_3_6_region(a, b, z))\n         {\n            // a is tiny compared to b, and z < 0\n            // 13.3.6 appears to be the most efficient and often the most accurate method.\n            T r = boost::math::detail::hypergeometric_1F1_AS_13_3_6(b_minus_a, b, T(-z), a, pol, log_scaling);\n            int scale = itrunc(z, pol);\n            log_scaling += scale;\n            return r * exp(z - scale);\n         }\n         if ((b < 0) && (fabs(a) < 1e-2))\n         {\n            //\n            // This is a tricky area, potentially we have no good method at all:\n            //\n            if (b - ceil(b) == a)\n            {\n               // Fractional parts of a and b are genuinely equal, we might as well\n               // apply Kummer's relation and get a truncated series:\n               int scaling = itrunc(z);\n               T r = exp(z - scaling) * detail::hypergeometric_1F1_imp<T>(b_minus_a, b, -z, pol, log_scaling);\n               log_scaling += scaling;\n               return r;\n            }\n            if ((b < -1) && (max_b_for_1F1_small_a_negative_b_by_ratio(z) < b))\n               return hypergeometric_1F1_small_a_negative_b_by_ratio(a, b, z, pol, log_scaling);\n            if ((b > -1) && (b < -0.5f))\n            {\n               // Recursion is meta-stable:\n               T first = hypergeometric_1F1_imp(a, T(b + 2), z, pol);\n               T second = hypergeometric_1F1_imp(a, T(b + 1), z, pol);\n               return tools::apply_recurrence_relation_backward(hypergeometric_1F1_recurrence_small_b_coefficients<T>(a, b, z, 1), 1, first, second);\n            }\n            //\n            // We've got nothing left but 13.3.6, even though it may be initially divergent:\n            //\n            T r = boost::math::detail::hypergeometric_1F1_AS_13_3_6(b_minus_a, b, T(-z), a, pol, log_scaling);\n            int scale = itrunc(z, pol);\n            log_scaling += scale;\n            return r * exp(z - scale);\n         }\n      }\n      //\n      // Asymptotic expansion for large z\n      // TODO: check region for higher precision types.\n      // Use recurrence relations to move to this region when a and b are also large.\n      //\n      if (detail::hypergeometric_1F1_asym_region(a, b, z, pol))\n      {\n         int saved_scale = log_scaling;\n         try\n         {\n            return hypergeometric_1F1_asym_large_z_series(a, b, z, pol, log_scaling);\n         }\n         catch (const evaluation_error&)\n         {\n         }\n         //\n         // Very occationally our convergence criteria don't quite go to full precision\n         // and we have to try another method:\n         //\n         log_scaling = saved_scale;\n      }\n\n      if ((fabs(a * z / b) < 3.5) && (fabs(z * 100) < fabs(b)) && ((fabs(a) > 1e-2) || (b < -5)))\n         return detail::hypergeometric_1F1_rational(a, b, z, pol);\n\n      if (hypergeometric_1F1_need_kummer_reflection(a, b, z))\n      {\n         if (a == 1)\n            return detail::hypergeometric_1F1_pade(b, z, pol);\n         if (is_convergent_negative_z_series(a, b, z, b_minus_a))\n         {\n            if ((boost::math::sign(b_minus_a) == boost::math::sign(b)) && ((b > 0) || (b < -200)))\n            {\n               // Series is close enough to convergent that we should be OK,\n               // In this domain b - a ~ b and since 1F1[a, a, z] = e^z 1F1[b-a, b, -z]\n               // and 1F1[a, a, -z] = e^-z the result must necessarily be somewhere near unity.\n               // We have to rule out b small and negative becuase if b crosses the origin early\n               // in the series (before we're pretty much converged) then all bets are off.\n               // Note that this can go badly wrong when b and z are both large and negative,\n               // in that situation the series goes in waves of large and small values which\n               // may or may not cancel out.  Likewise the initial part of the series may or may\n               // not converge, and even if it does may or may not give a correct answer!\n               // For example 1F1[-small, -1252.5, -1043.7] can loose up to ~800 digits due to\n               // cancellation and is basically incalculable via this method.\n               return hypergeometric_1F1_checked_series_impl(a, b, z, pol, log_scaling);\n            }\n         }\n         // Let's otherwise make z positive (almost always)\n         // by Kummer's transformation\n         // (we also don't transform if z belongs to [-1,0])\n         int scaling = itrunc(z);\n         T r = exp(z - scaling) * detail::hypergeometric_1F1_imp<T>(b_minus_a, b, -z, pol, log_scaling);\n         log_scaling += scaling;\n         return r;\n      }\n      //\n      // Check for initial divergence:\n      //\n      bool series_is_divergent = (a + 1) * z / (b + 1) < -1;\n      if (series_is_divergent && (a < 0) && (b < 0) && (a > -1))\n         series_is_divergent = false;   // Best off taking the series in this situation\n      //\n      // If series starts off non-divergent, and becomes divergent later\n      // then it's because both a and b are negative, so check for later\n      // divergence as well:\n      //\n      if (!series_is_divergent && (a < 0) && (b < 0) && (b > a))\n      {\n         //\n         // We need to exclude situations where we're over the initial \"hump\"\n         // in the series terms (ie series has already converged by the time\n         // b crosses the origin:\n         //\n         //T fa = fabs(a);\n         //T fb = fabs(b);\n         T convergence_point = sqrt((a - 1) * (a - b)) - a;\n         if (-b < convergence_point)\n         {\n            T n = -floor(b);\n            series_is_divergent = (a + n) * z / ((b + n) * n) < -1;\n         }\n      }\n      else if (!series_is_divergent && (b < 0) && (a > 0))\n      {\n         // Series almost always become divergent as b crosses the origin:\n         series_is_divergent = true;\n      }\n      if (series_is_divergent && (b < -1) && (b > -5) && (a > b))\n         series_is_divergent = false;  // don't bother with divergence, series will be OK\n\n      //\n      // Test for alternating series due to negative a,\n      // in particular, see if the series is initially divergent\n      // If so use the recurrence relation on a:\n      //\n      if (series_is_divergent)\n      {\n         if((a < 0) && (floor(a) == a) && (-a < policies::get_max_series_iterations<Policy>()))\n            // This works amazingly well for negative integer a:\n            return hypergeometric_1F1_backward_recurrence_for_negative_a(a, b, z, pol, function, log_scaling);\n         //\n         // In what follows we have to set limits on how large z can be otherwise\n         // the Bessel series become large and divergent and all the digits cancel out.\n         // The criteria are distinctly empiracle rather than based on a firm analysis\n         // of the terms in the series.\n         //\n         if (b > 0)\n         {\n            T z_limit = fabs((2 * a - b) / (sqrt(fabs(a))));\n            if ((z < z_limit) && hypergeometric_1F1_is_tricomi_viable_positive_b(a, b, z))\n               return detail::hypergeometric_1F1_AS_13_3_7_tricomi(a, b, z, pol, log_scaling);\n         }\n         else  // b < 0\n         {\n            if (a < 0)\n            {\n               T z_limit = fabs((2 * a - b) / (sqrt(fabs(a))));\n               //\n               // I hate these hard limits, but they're about the best we can do to try and avoid\n               // Bessel function internal failures: these will be caught and handled\n               // but up the expense of this function call:\n               //\n               if (((z < z_limit) || (a > -500)) && ((b > -500) || (b - 2 * a > 0)) && (z < -a))\n               {\n                  //\n                  // Outside this domain we will probably get better accuracy from the recursive methods.\n                  //\n                  if(!(((a < b) && (z > -b)) || (z > z_limit)))\n                     return detail::hypergeometric_1F1_AS_13_3_7_tricomi(a, b, z, pol, log_scaling);\n                  //\n                  // When b and z are both very small, we get large errors from the recurrence methods\n                  // in the fallbacks.  Tricomi seems to work well here, as does direct series evaluation\n                  // at least some of the time.  Picking the right method is not easy, and sometimes this\n                  // is much worse than the fallback.  Overall though, it's a reasonable choice that keeps\n                  // the very worst errors under control.\n                  //\n                  if(b > -1)\n                     return detail::hypergeometric_1F1_AS_13_3_7_tricomi(a, b, z, pol, log_scaling);\n               }\n            }\n            //\n            // We previosuly used Tricomi here, but it appears to be worse than\n            // the recurrence-based algorithms in hypergeometric_1F1_divergent_fallback.\n            /*\n            else\n            {\n               T aa = a < 1 ? T(1) : a;\n               if (z < fabs((2 * aa - b) / (sqrt(fabs(aa * b)))))\n                  return detail::hypergeometric_1F1_AS_13_3_7_tricomi(a, b, z, pol, log_scaling);\n            }*/\n         }\n\n         return hypergeometric_1F1_divergent_fallback(a, b, z, pol, log_scaling);\n      }\n\n      if (hypergeometric_1F1_is_13_3_6_region(b_minus_a, b, T(-z)))\n      {\n         // b_minus_a is tiny compared to b, and -z < 0\n         // 13.3.6 appears to be the most efficient and often the most accurate method.\n         return boost::math::detail::hypergeometric_1F1_AS_13_3_6(a, b, z, b_minus_a, pol, log_scaling);\n      }\n#if 0\n      if ((a > 0) && (b > 0) && (a * z / b > 2))\n      {\n         //\n         // Series is initially divergent and slow to converge, see if applying\n         // Kummer's relation can improve things:\n         //\n         if (is_convergent_negative_z_series(b_minus_a, b, T(-z), b_minus_a))\n         {\n            int scaling = itrunc(z);\n            T r = exp(z - scaling) * detail::hypergeometric_1F1_checked_series_impl(b_minus_a, b, T(-z), pol, log_scaling);\n            log_scaling += scaling;\n            return r;\n         }\n\n      }\n#endif\n      if ((a > 0) && (b > 0) && (a * z > 50))\n         return detail::hypergeometric_1F1_large_abz(a, b, z, pol, log_scaling);\n\n      if (b < 0)\n         return detail::hypergeometric_1F1_checked_series_impl(a, b, z, pol, log_scaling);\n      \n      return detail::hypergeometric_1F1_generic_series(a, b, z, pol, log_scaling, function);\n   }\n\n   template <class T, class Policy>\n   inline T hypergeometric_1F1_imp(const T& a, const T& b, const T& z, const Policy& pol)\n   {\n      BOOST_MATH_STD_USING // exp, fabs, sqrt\n      int log_scaling = 0;\n      T result = hypergeometric_1F1_imp(a, b, z, pol, log_scaling);\n      //\n      // Actual result will be result * e^log_scaling.\n      //\n#ifndef BOOST_NO_CXX11_THREAD_LOCAL\n    static const thread_local int max_scaling = itrunc(boost::math::tools::log_max_value<T>()) - 2;\n    static const thread_local T max_scale_factor = exp(T(max_scaling));\n#else\n    int max_scaling = itrunc(boost::math::tools::log_max_value<T>()) - 2;\n      T max_scale_factor = exp(T(max_scaling));\n#endif\n\n      while (log_scaling > max_scaling)\n      {\n         result *= max_scale_factor;\n         log_scaling -= max_scaling;\n      }\n      while (log_scaling < -max_scaling)\n      {\n         result /= max_scale_factor;\n         log_scaling += max_scaling;\n      }\n      if (log_scaling)\n         result *= exp(T(log_scaling));\n      return result;\n   }\n\n   template <class T, class Policy>\n   inline T log_hypergeometric_1F1_imp(const T& a, const T& b, const T& z, int* sign, const Policy& pol)\n   {\n      BOOST_MATH_STD_USING // exp, fabs, sqrt\n      int log_scaling = 0;\n      T result = hypergeometric_1F1_imp(a, b, z, pol, log_scaling);\n      if (sign)\n      *sign = result < 0 ? -1 : 1;\n     result = log(fabs(result)) + log_scaling;\n      return result;\n   }\n\n   template <class T, class Policy>\n   inline T hypergeometric_1F1_regularized_imp(const T& a, const T& b, const T& z, const Policy& pol)\n   {\n      BOOST_MATH_STD_USING // exp, fabs, sqrt\n      int log_scaling = 0;\n      T result = hypergeometric_1F1_imp(a, b, z, pol, log_scaling);\n      //\n      // Actual result will be result * e^log_scaling / tgamma(b).\n      //\n    int result_sign = 1;\n    T scale = log_scaling - boost::math::lgamma(b, &result_sign, pol);\n#ifndef BOOST_NO_CXX11_THREAD_LOCAL\n      static const thread_local T max_scaling = boost::math::tools::log_max_value<T>() - 2;\n    static const thread_local T max_scale_factor = exp(max_scaling);\n#else\n    T max_scaling = boost::math::tools::log_max_value<T>() - 2;\n    T max_scale_factor = exp(max_scaling);\n#endif\n\n      while (scale > max_scaling)\n      {\n         result *= max_scale_factor;\n         scale -= max_scaling;\n      }\n      while (scale < -max_scaling)\n      {\n         result /= max_scale_factor;\n     scale += max_scaling;\n      }\n      if (scale != 0)\n         result *= exp(scale);\n      return result * result_sign;\n   }\n\n} // namespace detail\n\ntemplate <class T1, class T2, class T3, class Policy>\ninline typename tools::promote_args<T1, T2, T3>::type hypergeometric_1F1(T1 a, T2 b, T3 z, const Policy& /* pol */)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n      typedef typename tools::promote_args<T1, T2, T3>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n   return policies::checked_narrowing_cast<result_type, Policy>(\n      detail::hypergeometric_1F1_imp<value_type>(\n         static_cast<value_type>(a),\n         static_cast<value_type>(b),\n         static_cast<value_type>(z),\n         forwarding_policy()),\n      \"boost::math::hypergeometric_1F1<%1%>(%1%,%1%,%1%)\");\n}\n\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type hypergeometric_1F1(T1 a, T2 b, T3 z)\n{\n   return hypergeometric_1F1(a, b, z, policies::policy<>());\n}\n\ntemplate <class T1, class T2, class T3, class Policy>\ninline typename tools::promote_args<T1, T2, T3>::type hypergeometric_1F1_regularized(T1 a, T2 b, T3 z, const Policy& /* pol */)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n      typedef typename tools::promote_args<T1, T2, T3>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy,\n      policies::promote_float<false>,\n      policies::promote_double<false>,\n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n   return policies::checked_narrowing_cast<result_type, Policy>(\n      detail::hypergeometric_1F1_regularized_imp<value_type>(\n         static_cast<value_type>(a),\n         static_cast<value_type>(b),\n         static_cast<value_type>(z),\n         forwarding_policy()),\n      \"boost::math::hypergeometric_1F1<%1%>(%1%,%1%,%1%)\");\n}\n\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type hypergeometric_1F1_regularized(T1 a, T2 b, T3 z)\n{\n   return hypergeometric_1F1_regularized(a, b, z, policies::policy<>());\n}\n\ntemplate <class T1, class T2, class T3, class Policy>\ninline typename tools::promote_args<T1, T2, T3>::type log_hypergeometric_1F1(T1 a, T2 b, T3 z, const Policy& /* pol */)\n{\n  BOOST_FPU_EXCEPTION_GUARD\n    typedef typename tools::promote_args<T1, T2, T3>::type result_type;\n  typedef typename policies::evaluation<result_type, Policy>::type value_type;\n  typedef typename policies::normalise<\n    Policy,\n    policies::promote_float<false>,\n    policies::promote_double<false>,\n    policies::discrete_quantile<>,\n    policies::assert_undefined<> >::type forwarding_policy;\n  return policies::checked_narrowing_cast<result_type, Policy>(\n    detail::log_hypergeometric_1F1_imp<value_type>(\n      static_cast<value_type>(a),\n      static_cast<value_type>(b),\n      static_cast<value_type>(z),\n      0,\n      forwarding_policy()),\n    \"boost::math::hypergeometric_1F1<%1%>(%1%,%1%,%1%)\");\n}\n\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type log_hypergeometric_1F1(T1 a, T2 b, T3 z)\n{\n  return log_hypergeometric_1F1(a, b, z, policies::policy<>());\n}\n\ntemplate <class T1, class T2, class T3, class Policy>\ninline typename tools::promote_args<T1, T2, T3>::type log_hypergeometric_1F1(T1 a, T2 b, T3 z, int* sign, const Policy& /* pol */)\n{\n  BOOST_FPU_EXCEPTION_GUARD\n    typedef typename tools::promote_args<T1, T2, T3>::type result_type;\n  typedef typename policies::evaluation<result_type, Policy>::type value_type;\n  typedef typename policies::normalise<\n    Policy,\n    policies::promote_float<false>,\n    policies::promote_double<false>,\n    policies::discrete_quantile<>,\n    policies::assert_undefined<> >::type forwarding_policy;\n  return policies::checked_narrowing_cast<result_type, Policy>(\n    detail::log_hypergeometric_1F1_imp<value_type>(\n      static_cast<value_type>(a),\n      static_cast<value_type>(b),\n      static_cast<value_type>(z),\n      sign,\n      forwarding_policy()),\n    \"boost::math::hypergeometric_1F1<%1%>(%1%,%1%,%1%)\");\n}\n\ntemplate <class T1, class T2, class T3>\ninline typename tools::promote_args<T1, T2, T3>::type log_hypergeometric_1F1(T1 a, T2 b, T3 z, int* sign)\n{\n  return log_hypergeometric_1F1(a, b, z, sign, policies::policy<>());\n}\n\n\n  } } // namespace boost::math\n\n#endif // BOOST_MATH_HYPERGEOMETRIC_HPP\n", "meta": {"hexsha": "3351cc2a285852d1a799aacb32fcab6a835f68e4", "size": 31855, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/special_functions/hypergeometric_1F1.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 597.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T10:59:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:59:36.000Z", "max_issues_repo_path": "boost/math/special_functions/hypergeometric_1F1.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 137.0, "max_issues_repo_issues_event_min_datetime": "2018-10-12T10:52:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T15:26:49.000Z", "max_forks_repo_path": "boost/math/special_functions/hypergeometric_1F1.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 112.0, "max_forks_repo_forks_event_min_datetime": "2018-07-26T04:36:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:29:34.000Z", "avg_line_length": 40.9447300771, "max_line_length": 189, "alphanum_fraction": 0.5785590959, "num_tokens": 8680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4314467341531434}}
{"text": "// [[Rcpp::plugins(openmp)]]\n#include <omp.h>\n#include <Rcpp.h>\n#include <RcppEigen.h>\n#include <Eigen/Core>\n#include <random>\n#include \"distributions.h\"\n#include \"concurrentqueue.h\"\n\n// [[Rcpp::depends(RcppEigen)]]\nusing namespace Rcpp;\nusing namespace RcppEigen;\nusing namespace Eigen;\nusing Eigen::Matrix;\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\nusing Eigen::SparseVector;\nusing Eigen::LLT;\nusing Eigen::Lower;\nusing Eigen::Map;\nusing Eigen::Upper;\ntypedef Map<MatrixXd> MapMatd;\n\ntemplate<typename Scalar>\nstruct scalar_normal_dist_op\n{\n  static std::mt19937 rng;                        // The uniform pseudo-random algorithm\n  mutable std::normal_distribution<Scalar> norm; // gaussian combinator\n\n  EIGEN_EMPTY_STRUCT_CTOR(scalar_normal_dist_op)\n\n    template<typename Index>\n    inline const Scalar operator() (Index, Index = 0) const { return norm(rng); }\n    inline void seed(const uint64_t &s) { rng.seed(s); }\n};\n\ntemplate<typename Scalar>\nstd::mt19937 scalar_normal_dist_op<Scalar>::rng;\n\n\ntemplate<typename Scalar>\nstruct exponential_functor\n{\n  exponential_functor(){}\n\n  const Scalar operator()(const Scalar& x) const{ return exp_rng(x); }\n\n};\n\n\ninline MatrixXd AtA(const MapMatd& A) {\n  int n(A.cols());\n  return MatrixXd(n,n).setZero().selfadjointView<Lower>()\n                      .rankUpdate(A.adjoint());\n}\n\ntemplate<typename Scalar>\nstruct inv_gamma_functor\n{\n  inv_gamma_functor(const Scalar& vd):m_a(vd){}\n\n  const Scalar operator()(const Scalar& x) const{ return inv_gamma_rate_rng(0.5 + 0.5*m_a,x); }\n  Scalar  m_a;\n};\n\ntemplate<typename Scalar>\nstruct gamma_functor\n{\n  gamma_functor(const Scalar& vd):m_a(vd){}\n\n  const Scalar operator()(const Scalar& x) const{ return gamma_rng(0.5 + 0.5*m_a,x); }\n  Scalar  m_a;\n};\n\ntemplate<typename Scalar>\nstruct inv_gamma_functor_init\n{\n  inv_gamma_functor_init(){}\n\n  const Scalar operator()(const Scalar& x) const{ return inv_gamma_rate_rng(0.5,x); }\n\n};\n\ntemplate<typename Scalar>\nstruct inv_gamma_functor_init_v\n{\n  inv_gamma_functor_init_v(const Scalar& vd):m_a(vd){}\n\n  const Scalar operator()(const Scalar& x) const{ return inv_gamma_rate_rng(0.5*m_a,m_a*x); }\n  Scalar  m_a;\n};\n\n/*\n* Bayes R sampler\n* outputFile- The file in which the samples aftare burnin will be stored\n* seed- random seed\n* max_iterations- total of number of samples taken.\n* burn_in - integer leq than max_iterations, number of samples used for burn in, after which, al samples will  be stored in the outputFile\n* thinning- thinning regime, not implemented\n* X- matrix of snp markers, or covariates of interest\n* Y- vector of response variates, must have the same number of rows as X\n* sigma0- variance of the zero-centered normal prior over the intercept\n* v0E- degrees of  freedom of the prior inverse scaled chi-squared distribution over residues variance\n* s02E - scale parameter of the prior inverse scaled chi-squared distribution over residues variance\n* v0G- degrees of freedom of the prior inverse scaled chi-squared distribution over genetic effects variance\n* s02G- scale parameter of the prior inverse scaled chi-squared distribution over genetic effects variance\n*/\n// [[Rcpp::export]]\nvoid HorseshoeR(std::string outputFile, int seed, int max_iterations, int burn_in, int thinning, Eigen::MatrixXd X, Eigen::VectorXd Y,double A, double v0E, double s02E, double vL, double vT,double c2,double vC,double sC) {\n  int flag;\n  moodycamel::ConcurrentQueue<Eigen::VectorXd> q;\n  flag=0;\n  int N(Y.size());\n  int M(X.cols());\n  VectorXd components(M);\n\n  ////////////validate inputs\n\n  if(max_iterations < burn_in || max_iterations<1 || burn_in<1) //validations related to mcmc burnin and iterations\n  {\n    std::cout<<\"error: burn_in has to be a positive integer and smaller than the maximum number of iterations \";\n    return;\n  }\n\n\n\n  Eigen::initParallel();\n  Eigen::setNbThreads(10);\n  double sum_beta_sqr;\n\n\n#pragma omp parallel num_threads(2) shared(flag,q,M,N)\n{\n#pragma omp sections\n{\n\n  {\n\n    //mean and residual variables\n    double mu; // mean or intercept\n    double sigmaG; //genetic variance\n    double sigmaE; // residuals variance\n\n    //component variables\n    VectorXd lambda(M);\n    VectorXd v(M);\n    VectorXd phi(M);\n    VectorXd chi(M);\n    double tau;\n    double eta;\n    //linear model variables\n    MatrixXd beta(M,1); // effect sizes\n    VectorXd y_tilde(N); // variable containing the adjusted residuals to exclude the effects of a given marker\n    VectorXd epsilon(N); // variable containing the residuals\n\n    //sampler variables\n    VectorXd sample(2*M+4+N); // varible containg a sambple of all variables in the model, M marker effects, M component assigned to markers, sigmaE, sigmaG, mu, iteration number and Explained variance\n    std::vector<int> markerI;\n    for (int i=0; i<M; ++i) {\n      markerI.push_back(i);\n    }\n\n\n    int marker;\n    double acum;\n\n\n    y_tilde.setZero();\n\n    beta.setZero();\n    tau=beta_rng(1,1);\n\n    mu=0;\n\n\n    v=(v.setOnes().array()).unaryExpr(inv_gamma_functor<double>(0));\n    v.setOnes();\n    //std::cout<< \"initial v\" << eta;\n    lambda=v.unaryExpr(inv_gamma_functor_init_v<double>(vL));\n    lambda.setOnes();\n\n\n\n\n    std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();\n    epsilon= Y.array() - mu - (X*beta).array();\n    sigmaE=epsilon.squaredNorm()/N*0.5;\n\n    eta=inv_gamma_rate_rng(0.5,1/(sigmaE*pow(A,2)));\n    //eta=0.00001;\n    std::cout<< \"initial eta \" << eta<<\"\\n\";\n    tau=(1.0/eta)*inv_gamma_rate_rng(0.5*vT,vT);\n\n    // tau=1/A;\n    std::cout<< \"initial tau \" << tau<<\"\\n\";\n\n\n    for(int iteration=0; iteration < max_iterations; iteration++){\n\n      if(iteration>0)\n        if( iteration % (int)std::ceil(max_iterations/10) ==0)\n        {\n          std::cout << \"iteration: \"<<iteration <<\"\\n\";\n          std::cout<< \" tau \" << tau<<\"\\n\";\n          std::cout<< \" eta \" << eta<<\"\\n\";\n          std::cout<< \"sigmaE\" << sigmaE<<\"\\n\";\n        }\n\n\n        epsilon= epsilon.array()+mu;//  we substract previous value\n        mu = norm_rng(epsilon.sum()/(double)N, sigmaE/(double)N); //update mu\n        epsilon= epsilon.array()-mu;// we substract again now epsilon =Y-mu-X*beta\n\n\n        std::random_shuffle(markerI.begin(), markerI.end());\n\n        eta = inv_gamma_rate_rng(0.5+0.5*vT,(1.0/(sigmaE*A*A))+vT/tau);\n        v=(vL/(lambda).array()+1.0).unaryExpr(inv_gamma_functor<double>(vL));\n        for(int j=0; j < M; j++){\n\n          marker= markerI[j];\n\n\n          y_tilde= epsilon.array()+(X.col(marker)*beta(marker,0)).array();//now y_tilde= Y-mu-X*beta+ X.col(marker)*beta(marker)_old\n\n\n\n          // std::cout<< muk;\n          //we compute the denominator in the variance expression to save computations\n          //denom=X.col(marker).squaredNorm()+(sigmaE/(tau*c2*lambda[marker]/(tau*lambda[marker]+c2)));\n          //muk for the other components is computed according to equaitons\n          //muk= (X.col(marker).cwiseProduct(y_tilde)).sum()/denom;\n          //beta(marker,0)=norm_rng(muk,sigmaE/denom);\n          beta(marker,0)=(X.col(marker).cwiseProduct(y_tilde)).sum()/(X.col(marker).squaredNorm()+(sigmaE/(tau*c2*lambda[marker]/(tau*lambda[marker]+c2))))+sqrt(sigmaE/(X.col(marker).squaredNorm()+(sigmaE/(tau*c2*lambda[marker]/(tau*lambda[marker]+c2)))))*norm_rng(0,1);\n\n\n\n          epsilon=y_tilde-X.col(marker)*beta(marker,0);//now epsilon contains Y-mu - X*beta+ X.col(marker)*beta(marker)_old- X.col(marker)*beta(marker)_new\n\n        }\n\n        lambda=(vL*v.cwiseInverse()+(0.5*beta.cwiseProduct(beta)*(1.0/tau))).unaryExpr(inv_gamma_functor<double>(vL));\n        //  if(iteration==0)\n        //  std::cout<< \" lambda \" << lambda<<\"\\n\";\n        tau= inv_gamma_rate_rng(0.5*(M+vT),vT/eta+((0.5)*((beta.array().pow(2))/lambda.array()).sum()));\n\n        //tau=A;\n         c2=inv_gamma_rate_rng(0.5*vC+0.5*M,vC*sC*0.5+0.5*beta.squaredNorm());\n        //  c2=sC;\n\n\n\n        sigmaE=inv_scaled_chisq_rng(v0E+N,((epsilon).squaredNorm()+v0E*s02E)/(v0E+N));\n\n        if(iteration >= burn_in)\n        {\n          if(iteration % thinning == 0){\n            sample<< iteration,mu,beta,sigmaE,tau,lambda,epsilon;\n            q.enqueue(sample);\n          }\n\n        }\n\n    }\n\n    std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();\n    auto duration = std::chrono::duration_cast<std::chrono::seconds>( t2 - t1 ).count();\n    std::cout << \"duration: \"<<duration << \"s\\n\";\n    flag=1;\n  }\n#pragma omp section\n{\n  bool queueFull;\n  queueFull=0;\n  std::ofstream outFile;\n  outFile.open(outputFile);\n  VectorXd sampleq(2*M+4+N);\n  IOFormat CommaInitFmt(StreamPrecision, DontAlignCols, \", \", \", \", \"\", \"\", \"\", \"\");\n  outFile<< \"iteration,\"<<\"mu,\";\n  for(unsigned int i = 0; i < M; ++i){\n    outFile << \"beta[\" << (i+1) << \"],\";\n\n  }\n  outFile<<\"sigmaE,\"<<\"tau,\";\n  for(unsigned int i = 0; i < M; ++i){\n    outFile << \"lambda[\" << (i+1) << \"],\";\n  }\n  for(unsigned int i = 0; i < N; ++i){\n    outFile << \"epsilon[\" << (i+1) << \"],\";\n  }\n  outFile<<\"\\n\";\n\n  while(!flag ){\n    if(q.try_dequeue(sampleq))\n      outFile<< sampleq.transpose().format(CommaInitFmt) << \"\\n\";\n  }\n}\n\n}\n}\n\n}\n\n/*** R\nM=3000\nN=2000\nMT=200\nB=matrix(rnorm(M,sd=sqrt(0.5/MT)),ncol=1)\n  B[sample(1:M,M-MT),1]=0\nX <- matrix(rnorm(M*N), N, M); var(X[,1])\n  G <- X%*%B; var(G)\n    Y=X%*%B+rnorm(N,sd=sqrt((1-var(G)))); var(Y)\n    Y=scale(Y)\n    X=scale(X)\n    vT=1\n    vL=1\n    A=1500\n    A=(1/sqrt(N))*A/(M-A)\n    c2=1.0\n    v0E=0.001\n    s02E=0.001\n    vC=10\n    sC=10.0\n\n    HorseshoeR(\"./test2.csv\",1, 20000,10000 ,10,X, Y, A,  v0E, s02E,  vL,  vT, c2,vC,sC)\n      library(readr)\n     library(data.table)\n      tmp <- fread(\"./test2.csv\")\n      tmp<-as.matrix(tmp)\n      plot(B,colMeans(tmp[,grep(\"beta\",colnames(tmp))]))\n      summary(lm(B~colMeans(tmp[,grep(\"beta\",colnames(tmp))])))\n      lines(B,B)\n      abline(h=0)\n      G <- X%*%B;\n    var(G)\n      tmp<-as.data.frame(tmp)\n\n      mean(tmp$sigmaE)\n      plot(tmp$sigmaE)\n      plot(tmp$mu)\n      plot(tmp$tau)\n      hist(as.matrix(tmp[,grep(\"beta\",names(tmp))]))\n\n\n\n\n      */\n\n\n", "meta": {"hexsha": "e586d292f0e20e37497f67ef1f39c08e722a14da", "size": 10025, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HorseshoeR.cpp", "max_stars_repo_name": "ctggroup/BayesRRcpp", "max_stars_repo_head_hexsha": "23381fcc5db93916f875c005529c8b8cba6fd78a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-14T16:05:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T16:05:16.000Z", "max_issues_repo_path": "src/HorseshoeR.cpp", "max_issues_repo_name": "ctggroup/BayesRRcpp", "max_issues_repo_head_hexsha": "23381fcc5db93916f875c005529c8b8cba6fd78a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HorseshoeR.cpp", "max_forks_repo_name": "ctggroup/BayesRRcpp", "max_forks_repo_head_hexsha": "23381fcc5db93916f875c005529c8b8cba6fd78a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6428571429, "max_line_length": 270, "alphanum_fraction": 0.6422942643, "num_tokens": 2914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4314467341531432}}
{"text": "#include \"matchers/matcher.h\"\n#include \"opencv2/opencv.hpp\"\n#include \"camera/CameraModel.h\"\n#include \"types/Frame.h\"\n//#include \"extractors/FASTextractor.h\"\n#include \"extractors/ORBextractor.h\"\n#include \"types/Map.h\"\n#include \"types/MapPoint.h\"\n#include \"mapping/LocalBA.h\"\n#include \"Viewer.h\"\n#include <memory>\n#include <Eigen/Geometry>\n#include <thread>\n#include <sophus/se3.hpp>\n#include <iostream>\n#include <stdint.h>\n#include <unordered_set>\n#include \"g2o/stuff/sampler.h\"\n#include<suitesparse/cholmod.h>\n\nusing namespace TRACKING_BENCH;\n\n\n// simple direct\nusing namespace std;\n\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\n\n// Camera intrinsics\ndouble fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n// baseline\ndouble baseline = 0.573;\n// paths\nstring left_file = \"/home/lyc/share/slambook2-master/slambook2-master/ch8/left.png\";\nstring disparity_file = \"/home/lyc/code/slam_bench/trackingBench-SLAM/data/disparity.png\";\n\n\n// useful typedefs\ntypedef Eigen::Matrix<double, 6, 6> Matrix6d;\ntypedef Eigen::Matrix<double, 2, 6> Matrix26d;\ntypedef Eigen::Matrix<double, 6, 1> Vector6d;\n\n/// class for accumulator jacobians in parallel\nclass JacobianAccumulator {\npublic:\n    JacobianAccumulator(\n            const cv::Mat &img1_,\n            const cv::Mat &img2_,\n            const VecVector2d &px_ref_,\n            const vector<double> depth_ref_,\n            Sophus::SE3d &T21_) :\n            img1(img1_), img2(img2_), px_ref(px_ref_), depth_ref(depth_ref_), T21(T21_) {\n        projection = VecVector2d(px_ref.size(), Eigen::Vector2d(0, 0));\n    }\n\n    /// accumulate jacobians in a range\n    void accumulate_jacobian(const cv::Range &range);\n\n    /// get hessian matrix\n    Matrix6d hessian() const { return H; }\n\n    /// get bias\n    Vector6d bias() const { return b; }\n\n    /// get total cost\n    double cost_func() const { return cost; }\n\n    /// get projected points\n    VecVector2d projected_points() const { return projection; }\n\n    /// reset h, b, cost to zero\n    void reset() {\n        H = Matrix6d::Zero();\n        b = Vector6d::Zero();\n        cost = 0;\n    }\n\nprivate:\n    const cv::Mat &img1;\n    const cv::Mat &img2;\n    const VecVector2d &px_ref;\n    const vector<double> depth_ref;\n    Sophus::SE3d &T21;\n    VecVector2d projection; // projected points\n\n    std::mutex hessian_mutex;\n    Matrix6d H = Matrix6d::Zero();\n    Vector6d b = Vector6d::Zero();\n    double cost = 0;\n};\n\n/**\n * pose estimation using direct method\n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationMultiLayer(\n        const cv::Mat &img1,\n        const cv::Mat &img2,\n        const VecVector2d &px_ref,\n        const vector<double> depth_ref,\n        Sophus::SE3d &T21\n);\n\n/**\n * pose estimation using direct method\n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationSingleLayer(\n        const cv::Mat &img1,\n        const cv::Mat &img2,\n        const VecVector2d &px_ref,\n        const vector<double> depth_ref,\n        Sophus::SE3d &T21\n);\n\n// bilinear interpolation\ninline float GetPixelValue(const cv::Mat &img, float x, float y) {\n    // boundary check\n    if (x < 0) x = 0;\n    if (y < 0) y = 0;\n    if (x >= img.cols) x = img.cols - 1;\n    if (y >= img.rows) y = img.rows - 1;\n    uchar *data = &img.data[int(y) * img.step + int(x)];\n    float xx = x - floor(x);\n    float yy = y - floor(y);\n//    std::cout<<\"f1: \"<<(1 - xx) * (1 - yy)<<\" x1: \"<<(int)data[0]<<std::endl;\n//    std::cout<<\"f2: \"<<xx * (1 - yy)<<\" x2: \"<<(int)data[1]<<std::endl;\n//    std::cout<<\"f3: \"<<(1 - xx) * yy<<\" x3: \"<<(int)data[img.step]<<std::endl;\n//    std::cout<<\"f4: \"<<xx * yy<<\" x4: \"<<(int)data[img.step + 1]<<std::endl;\n    return float(\n            (1 - xx) * (1 - yy) * data[0] +\n            xx * (1 - yy) * data[1] +\n            (1 - xx) * yy * data[img.step] +\n            xx * yy * data[img.step + 1]\n    );\n}\n\n\nvoid DirectPoseEstimationSingleLayer(\n        const cv::Mat &img1,\n        const cv::Mat &img2,//new\n        const VecVector2d &px_ref,\n        const vector<double> depth_ref,\n        Sophus::SE3d &T21) {\n\n    const int iterations = 10;\n    double cost = 0, lastCost = 0;\n    auto t1 = chrono::steady_clock::now();\n    JacobianAccumulator jaco_accu(img1, img2, px_ref, depth_ref, T21);\n\n    for (int iter = 0; iter < iterations; iter++) {\n        jaco_accu.reset();\n        cv::parallel_for_(cv::Range(0, px_ref.size()),\n                          std::bind(&JacobianAccumulator::accumulate_jacobian, &jaco_accu, std::placeholders::_1));\n        Matrix6d H = jaco_accu.hessian();\n        Vector6d b = jaco_accu.bias();\n\n        // solve update and put it into estimation\n        Vector6d update = H.ldlt().solve(b);\n        T21 = Sophus::SE3d::exp(-update) * T21;\n        cost = jaco_accu.cost_func();\n\n        if (std::isnan(update[0])) {\n            // sometimes occurred when we have a black or white patch and H is irreversible\n            cout << \"update is nan\" << endl;\n            break;\n        }\n        if (iter > 0 && cost > lastCost) {\n            cout << \"cost increased: \" << cost << \", \" << lastCost << endl;\n            break;\n        }\n        if (update.norm() < 1e-3) {\n            // converge\n            break;\n        }\n\n        lastCost = cost;\n        cout << \"iteration: \" << iter << \", cost: \" << cost << endl;\n    }\n\n    cout << \"T21 = \\n\" << T21.matrix() << endl;\n    auto t2 = chrono::steady_clock::now();\n    auto time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n    cout << \"direct method for single layer: \" << time_used.count() << endl;\n\n    // plot the projected pixels here\n    cv::Mat img2_show;\n    cv::cvtColor(img2, img2_show, CV_GRAY2BGR);\n    VecVector2d projection = jaco_accu.projected_points();\n    for (size_t i = 0; i < px_ref.size(); ++i) {\n        auto p_ref = px_ref[i];\n        auto p_cur = projection[i];\n        if (p_cur[0] > 0 && p_cur[1] > 0) {\n            cv::circle(img2_show, cv::Point2f(p_cur[0], p_cur[1]), 2, cv::Scalar(0, 250, 0), 2);\n            cv::line(img2_show, cv::Point2f(p_ref[0], p_ref[1]), cv::Point2f(p_cur[0], p_cur[1]),\n                     cv::Scalar(0, 250, 0));\n        }\n    }\n    cv::imshow(\"current\", img2_show);\n    cv::waitKey(0);\n}\n\nvoid JacobianAccumulator::accumulate_jacobian(const cv::Range &range) {\n\n    // parameters\n    const int half_patch_size = 2;\n    int cnt_good = 0;\n    Matrix6d hessian = Matrix6d::Zero();\n    Vector6d bias = Vector6d::Zero();\n    double cost_tmp = 0;\n\n    for (size_t i = range.start; i < range.end; i++) {\n\n        // compute the projection in the second image\n        Eigen::Vector3d point_ref =\n                depth_ref[i] * Eigen::Vector3d((px_ref[i][0] - cx) / fx, (px_ref[i][1] - cy) / fy, 1);\n        Eigen::Vector3d point_cur = T21 * point_ref;\n        if (point_cur[2] < 0)   // depth invalid\n            continue;\n\n        float u = fx * point_cur[0] / point_cur[2] + cx, v = fy * point_cur[1] / point_cur[2] + cy;\n        if (u < half_patch_size || u > img2.cols - half_patch_size || v < half_patch_size ||\n            v > img2.rows - half_patch_size)\n            continue;\n\n        projection[i] = Eigen::Vector2d(u, v);\n        double X = point_ref[0], Y = point_ref[1], Z = point_ref[2],\n                Z2 = Z * Z, Z_inv = 1.0 / Z, Z2_inv = Z_inv * Z_inv;\n        cnt_good++;\n\n        // and compute error and jacobian\n        for (int y = -half_patch_size; y < half_patch_size; y++)\n            for (int x = -half_patch_size; x < half_patch_size; x++) {\n\n                double error = GetPixelValue(img2, u + x, v + y) -\n                               GetPixelValue(img1, px_ref[i][0] + x, px_ref[i][1] + y);\n\n                Matrix26d J_pixel_xi;\n                Eigen::Vector2d J_img_pixel;\n\n                J_pixel_xi(0, 0) = fx * Z_inv;\n                J_pixel_xi(0, 1) = 0;\n                J_pixel_xi(0, 2) = -fx * X * Z2_inv;\n                J_pixel_xi(0, 3) = -fx * X * Y * Z2_inv;\n                J_pixel_xi(0, 4) = fx + fx * X * X * Z2_inv;\n                J_pixel_xi(0, 5) = -fx * Y * Z_inv;\n\n                J_pixel_xi(1, 0) = 0;\n                J_pixel_xi(1, 1) = fy * Z_inv;\n                J_pixel_xi(1, 2) = -fy * Y * Z2_inv;\n                J_pixel_xi(1, 3) = -fy - fy * Y * Y * Z2_inv;\n                J_pixel_xi(1, 4) = fy * X * Y * Z2_inv;\n                J_pixel_xi(1, 5) = fy * X * Z_inv;\n\n                J_img_pixel = Eigen::Vector2d(\n                        0.5 * (GetPixelValue(img1, px_ref[i][0] + 1 + x, px_ref[i][1] + y) - GetPixelValue(img1, px_ref[i][0] - 1 + x, px_ref[i][1] + y)),\n                        0.5 * (GetPixelValue(img1, px_ref[i][0] + x, px_ref[i][1] + 1 + y) - GetPixelValue(img1, px_ref[i][0] + x, px_ref[i][1] - 1 + y))\n                );\n\n                // total jacobian\n                Vector6d J = -1.0 * (J_img_pixel.transpose() * J_pixel_xi).transpose();\n\n                hessian += J * J.transpose();\n                bias += -error * J;\n                cost_tmp += error * error;\n                std::cout<<\" H \"<<J * J.transpose()<<std::endl;\n                std::cout<<\" b \"<<-error * J<<std::endl;\n            }\n        std::cout<<\"H: \"<<hessian<<std::endl;\n        std::cout<<\"bias: \"<<bias<<std::endl;\n    }\n\n    if (cnt_good) {\n        // set hessian, bias and cost\n        unique_lock<mutex> lck(hessian_mutex);\n        H += hessian;\n        b += bias;\n        cost += cost_tmp / cnt_good;\n    }\n    //std::cout<<\" mean cost: \"<<std::endl;\n}\n\nvoid DirectPoseEstimationMultiLayer(\n        const cv::Mat &img1,\n        const cv::Mat &img2,\n        const VecVector2d &px_ref,\n        const vector<double> depth_ref,\n        Sophus::SE3d &T21)\n{\n    // parameters\n    int pyramids = 4;\n    double pyramid_scale = 0.5;\n    double scales[] = {1.0, 0.5, 0.25, 0.125};\n\n    // create pyramids\n    vector<cv::Mat> pyr1, pyr2; // image pyramids\n    for (int i = 0; i < pyramids; i++) {\n        if (i == 0) {\n            pyr1.push_back(img1);\n            pyr2.push_back(img2);\n        } else {\n            cv::Mat img1_pyr, img2_pyr;\n            cv::resize(pyr1[i - 1], img1_pyr,\n                       cv::Size(pyr1[i - 1].cols * pyramid_scale, pyr1[i - 1].rows * pyramid_scale));\n            cv::resize(pyr2[i - 1], img2_pyr,\n                       cv::Size(pyr2[i - 1].cols * pyramid_scale, pyr2[i - 1].rows * pyramid_scale));\n            pyr1.push_back(img1_pyr);\n            pyr2.push_back(img2_pyr);\n        }\n    }\n\n    double fxG = fx, fyG = fy, cxG = cx, cyG = cy;  // backup the old values\n    for (int level = pyramids - 1; level >= 0; level--) {\n        VecVector2d px_ref_pyr; // set the keypoints in this pyramid level\n        for (auto &px: px_ref) {\n            px_ref_pyr.push_back(scales[level] * px);\n        }\n\n        // scale fx, fy, cx, cy in different pyramid levels\n        fx = fxG * scales[level];\n        fy = fyG * scales[level];\n        cx = cxG * scales[level];\n        cy = cyG * scales[level];\n        DirectPoseEstimationSingleLayer(pyr1[level], pyr2[level], px_ref_pyr, depth_ref, T21);\n    }\n\n}\n\n\nvoid LoadImages(const string &strPathToSequence, vector<string> &vstrImageLeft,\n                vector<string> &vstrImageRight, vector<double> &vTimestamps)\n{\n    ifstream fTimes;\n    string strPathTimeFile = strPathToSequence + \"/times.txt\";\n    fTimes.open(strPathTimeFile.c_str());\n    while(!fTimes.eof())\n    {\n        string s;\n        getline(fTimes,s);\n        if(!s.empty())\n        {\n            stringstream ss;\n            ss << s;\n            double t;\n            ss >> t;\n            vTimestamps.push_back(t);\n        }\n    }\n\n    string strPrefixLeft = strPathToSequence + \"/image_0/\";\n    string strPrefixRight = strPathToSequence + \"/image_1/\";\n\n    const int nTimes = vTimestamps.size();\n    vstrImageLeft.resize(nTimes);\n    vstrImageRight.resize(nTimes);\n\n    for(int i=0; i<nTimes; i++)\n    {\n        stringstream ss;\n        ss << setfill('0') << setw(6) << i;\n        vstrImageLeft[i] = strPrefixLeft + ss.str() + \".png\";\n        vstrImageRight[i] = strPrefixRight + ss.str() + \".png\";\n    }\n}\n\nvoid LoadKittiGroundTruth(const string& file, vector<Eigen::Matrix3d>& R, vector<Eigen::Vector3d>& t)\n{\n    ifstream fTimes;\n    fTimes.open(file.c_str());\n    R.reserve(1000);\n    t.reserve(1000);\n\n    while(!fTimes.eof())\n    {\n        Eigen::Vector3d t0;\n        Eigen::Matrix3d R0;\n\n        string s;\n        for (int i = 0; i < 3; i ++)\n        {\n            for (int j = 0;j < 3; j ++)\n            {\n                getline(fTimes,s,' ');\n                R0(i, j) =  std::atof(s.c_str());\n            }\n            if (i == 2)\n                getline(fTimes,s);\n            else\n                getline(fTimes,s,' ');\n            t0(i) = std::atof(s.c_str());\n        }\n        R.emplace_back(R0.transpose());\n        t.emplace_back(- R0.transpose() * t0);\n        //getline(fTimes,s);\n    }\n}\n\n\n\nvoid test_projection()\n{\n\n    // Load Images Paths\n    std::vector<string> imageLeft;\n    std::vector<string> imageRight;\n    std::vector<double> timeStamp;\n    LoadImages( \"/media/lyc/ 其他/dataset/sequences/00\",\n                imageLeft, imageRight, timeStamp);\n    string left_file = \"/home/lyc/code/slam_bench/trackingBench-SLAM/data/left.png\";\n    string right_file = \"/home/lyc/code/slam_bench/trackingBench-SLAM/data/right.png\";\n    string disparity_file = \"/home/lyc/code/slam_bench/trackingBench-SLAM/data/disparity.png\";\n    // Load ground truth\n    cv::Mat disparity = cv::imread(disparity_file, 0);\n    std::vector<Eigen::Matrix3d> gtR;\n    std::vector<Eigen::Vector3d> gtT;\n    LoadKittiGroundTruth(\"/home/lyc/share/data_odometry_poses/dataset/poses/00.txt\",\n                         gtR, gtT);\n\n    //\n    // 内参\n    double fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n    // 间距\n    double d = 0.573;\n\n    auto extractor_ptr = std::make_shared<ORBExtractor>();\n    auto local_ba = std::make_shared<LocalBA>();\n\n    std::shared_ptr<Frame> key_frame, last_frame;\n    auto matcher_ptr = std::make_shared<Matcher>();\n    auto map_ptr = std::make_shared<TRACKING_BENCH::Map>();\n\n    // viewer\n    auto viewer = std::make_shared<Viewer>();\n    viewer->SetCameraPos(Eigen::Matrix4f::Identity());\n    viewer->Run();\n\n    // view gt pos\n    std::vector<cv::KeyPoint> keyPoints_ref;\n    std::vector<Eigen::Matrix4f> kfs_pos;\n\n    // for images\n    for (int i = 0;i < 2;i +=1)\n    {\n        cv::Mat imLeft, imRight, show;\n        std::vector<cv::KeyPoint> keyPoints_r, keyPoints_l;\n        cv::Mat descriptors_r, descriptors_l;\n        // 0. read image to frame\n        imLeft = cv::imread(imageLeft[i], CV_LOAD_IMAGE_UNCHANGED);\n        static auto camera_ptr = std::make_shared<PinholeCamera>(imLeft.cols, imLeft.rows,fx, fy, cx, cy);\n        cv::Mat out;\n\n        auto cur_frame_ptr = std::make_shared<Frame>(imLeft, 0, 5, 0.6, camera_ptr);\n        if(last_frame != nullptr)\n        {\n            cur_frame_ptr->SetPose(last_frame->GetPose());\n        }\n        else\n        {\n            Eigen::Matrix4f pos = Eigen::Matrix4f::Identity();\n            pos.block<3, 3>(0, 0) = gtR.at(i).cast<float>();\n            pos.block<3, 1>(0 ,3) = gtT.at(i).cast<float>();\n            cur_frame_ptr->SetPose(pos);\n            viewer->SetCameraPos(cur_frame_ptr->GetPoseInverse());\n        }\n\n        // 1. match points\n        if (last_frame != nullptr)\n        {\n            // match with last frame\n//            auto matches = matcher_ptr->searchByBow(cur_frame_ptr, cur_frame_ptr, true);\n//            auto matches = matcher_ptr->searchByBF(cur_frame_ptr, key_frame, 0, 5, 10, 30);\n//            auto matches = matcher_ptr->searchByViolence(cur_frame_ptr, key_frame, 0, 5, 50);\n            // matches by optical flow\n//            std::vector<cv::Point2f> pts;\n//            std::vector<cv::KeyPoint> kps;\n//            auto matches = matcher_ptr->searchByOPFlow(cur_frame_ptr, last_frame, pts, true, true);\n//            kps.reserve(pts.size());\n//            for (auto& pt:pts)\n//            {\n//                cv::KeyPoint kp;\n//                kp.pt = pt;\n//                kps.emplace_back(kp);\n//            }\n//            cur_frame_ptr->SetKeys(kps, cur_frame_ptr);\n            // matches by projection frame\n\n//            extractor_ptr->operator()(cur_frame_ptr->GetImagePyramid(),\n//                                      cur_frame_ptr->GetScaleFactors(),\n//                                      2000,\n//                                      80,\n//                                      30,\n//                                      keyPoints_l,\n//                                      descriptors_l);\n//\n//            cur_frame_ptr->SetKeys(keyPoints_l, cur_frame_ptr, descriptors_l);\n//            cur_frame_ptr->AssignFeaturesToGrid();\n\n            Eigen::Matrix4f pos = Eigen::Matrix4f::Identity();\n            pos.block<3, 3>(0, 0) = gtR.at(i).cast<float>();\n            pos.block<3, 1>(0 ,3) = gtT.at(i).cast<float>();\n            pos(2, 3) = -0.85;\n            cur_frame_ptr->SetPose(last_frame->GetPose());//pos);//last_frame->GetPose());\n\n//            matcher_ptr->setProjectionParam(30, 50, 30, true, 30);\n//            auto matches = matcher_ptr->searchByProjection(cur_frame_ptr, key_frame);\n\n            // matches by projection map\n//            matcher_ptr->setProjectionParam(30, 50, 30, true, 20);\n//            auto matches = matcher_ptr->searchByProjection(map_ptr, cur_frame_ptr, 0.6);\n//\n//            // assign map point\n//            for (auto &item:matches)\n//            {\n//                // last frame\n////                shared_ptr<MapPoint> mp = last_frame->GetMapPoint(item.trainIdx);\n//                // key frame\n////                shared_ptr<MapPoint> mp = key_frame->GetMapPoint(item.trainIdx);\n//                // map\n//                shared_ptr<MapPoint> mp = map_ptr->GetAllMapPoints().at(item.trainIdx);\n//                if (mp != nullptr)\n//                    cur_frame_ptr->AddMapPoint(mp, item.queryIdx);\n//            }\n//\n//            for (auto& m:matches)\n//            {\n//                m.trainIdx =  map_ptr->GetAllMapPoints().at(m.trainIdx)->GetReferenceFeature()->idxF;\n//            }\n\n            // direct\n            matcher_ptr->setDirectParam(4, 0, 20, 20, 0.01);\n            auto matches = matcher_ptr->searchByDirect(map_ptr, cur_frame_ptr, last_frame);\n            // pnp\n            cur_frame_ptr->SetPose(Eigen::Matrix4f::Identity());\n            local_ba->PoseOptimization(cur_frame_ptr);\n            std::cout<<\"current pose Twc: \"<<cur_frame_ptr->GetPoseInverse()<<std::endl;\n            // feature align\n            cv::Mat show2 = cur_frame_ptr->GetImagePyramid()[0].clone();\n            cv::cvtColor(show2,show2,CV_GRAY2BGR);\n            for (const auto& f:cur_frame_ptr->GetKeys())\n            {\n                cv::line(show2,\n                         cv::Point((int)f->px.x(), (int)f->px.y()),\n                         cv::Point((int)f->point->GetReferenceFeature()->px.x(), (int)f->point->GetReferenceFeature()->px.y()),\n                         cv::Scalar(255,0,0), 2);\n            }\n            cv::imshow(\"image align\", show2);\n            cv::waitKey(0);\n\n//            cv::drawMatches(imLeft,\n//                            keyPoints_l,\n//                            key_frame->GetImagePyramid().at(0),\n//                            keyPoints_ref, matches, show);\n//            cv::imshow(\"match\", show);\n\n\n            // 2. pose optimization\n//            local_ba->PoseOptimization(cur_frame_ptr);\n\n            std::cout<<\"current pose Twc: \"<<cur_frame_ptr->GetPoseInverse()<<std::endl;\n            std::cout<<\"ground truth pose Twc: \"<<pos.inverse()<<std::endl;\n        }\n\n\n        kfs_pos.emplace_back(cur_frame_ptr->GetPoseInverse());\n        viewer->SetKeyFrames(kfs_pos);\n        if(i % 10 == 0)\n        {// 3. key frame\n\n            extractor_ptr->operator()(cur_frame_ptr->GetImagePyramid(),\n                                      cur_frame_ptr->GetScaleFactors(),\n                                      2000,\n                                      80,\n                                      30,\n                                      keyPoints_l,\n                                      descriptors_l);\n\n            cur_frame_ptr->SetKeys(keyPoints_l, cur_frame_ptr, descriptors_l);\n            cur_frame_ptr->AssignFeaturesToGrid();\n            imRight = cv::imread(imageRight[i], CV_LOAD_IMAGE_UNCHANGED);\n//            cv::imshow(\"right\", imRight);\n            static auto right_camera_ptr = std::make_shared<PinholeCamera>(imLeft.cols, imLeft.rows, fx, fy, cx, cy);\n//            right_camera_ptr->UndistortImage(imRight, imRight);\n            // 4. add map points by stereo\n            auto right_frame_ptr = std::make_shared<Frame>(imRight, 0, 5, 0.6, right_camera_ptr);\n//            extractor_ptr->operator()(cur_frame_ptr->GetImagePyramid(),\n//                                      cur_frame_ptr->GetScaleFactors(),\n//                                      2000,\n//                                      80,\n//                                      30,\n//                                      keyPoints_r,\n//                                      descriptors_r);\n//            right_frame_ptr->SetKeys(keyPoints_r, right_frame_ptr, descriptors_r);\n\n            auto depth = local_ba->AddMapPointsByStereo(cur_frame_ptr, right_frame_ptr, d*fx, fx);\n            float sum_err = 0, cnt = 0;\n            for (size_t j = 0; j < depth.size(); j ++)\n            {\n                if(depth[j] > 0)\n                {\n\n                    int u = (int)cur_frame_ptr->GetKey(j)->kp.pt.x;\n                    int v = (int)cur_frame_ptr->GetKey(j)->kp.pt.y;\n\n                    double disp = disparity.at<uchar>(v, u);\n                    disp = (disp)/fx;\n                    float err = abs(depth[j]/5 - d/disp);\n                    sum_err += err;\n                    cnt ++;\n\n                    depth[j] = d/disp;\n\n                    Eigen::Vector3f norm;\n                    norm[0] = (u-cx)/fx;\n                    norm[1] = (v-cy)/fy;\n                    norm[2] = 1;\n\n//                    const auto& pt = cur_frame_ptr->GetKey(j);\n//                    norm = camera_ptr->Cam2World(pt->px);\n\n                    const Eigen::Matrix3f& R = cur_frame_ptr->GetRotation();\n                    Eigen::Vector3f t = cur_frame_ptr->GetTranslation();\n//                    t.x() += 0.5;\n                    auto mp = std::make_shared<MapPoint>(R * norm * depth[j] + t, map_ptr, cur_frame_ptr, cur_frame_ptr->GetKey(j), cur_frame_ptr->GetDescriptor(j));\n\n                    cur_frame_ptr->AddMapPoint(mp, j);\n                    map_ptr->AddMapPoint(mp);\n                    map_ptr->AddKeyFrame(cur_frame_ptr);\n                }\n            }\n            std::cout<<\" error: \"<<sum_err<<\" mean: \"<<sum_err/cnt<<\" cnt: \"<<cnt<<std::endl;\n            viewer->SetMapPoints(map_ptr->GetAllMapPoints(), cur_frame_ptr->GetMapPointMatches());\n            keyPoints_ref = keyPoints_l;\n            key_frame = cur_frame_ptr;\n        }\n        last_frame = cur_frame_ptr;\n        // visualization\n        cv::waitKey(2);\n    }\n    for(int i = 0;i < gtR.size();i += 1)\n    {\n        Eigen::Matrix4f pos = Eigen::Matrix4f::Identity();\n        pos.block<3, 3>(0, 0) = gtR.at(i).cast<float>().transpose();\n        pos.block<3, 1>(0 ,3) = -  pos.block<3, 3>(0, 0) * gtT.at(i).cast<float>();\n        kfs_pos.emplace_back(pos);\n    }\n    cv::waitKey(0);\n    viewer->RequestFinish();\n}\n\n\nint test_direct()\n{\n    std::vector<string> imageLeft;\n    std::vector<string> imageRight;\n    std::vector<double> timeStamp;\n\n    LoadImages( \"/media/lyc/ 其他/dataset/sequences/00\",\n                imageLeft, imageRight, timeStamp);\n\n    cv::Mat left_img = cv::imread(imageLeft[0], 0);\n    cv::Mat disparity_img = cv::imread(disparity_file, 0);\n\n    // let's randomly pick pixels in the first image and generate some 3d points in the first image's frame\n    cv::RNG rng;\n    int nPoints = 1;\n    int boarder = 2;\n    VecVector2d pixels_ref;\n    vector<double> depth_ref;\n    for (int i = 0; i < nPoints; i++)\n    {\n        int x = 130;//rng.uniform(boarder, left_img.cols - boarder);  // don't pick pixels close to boarder\n        int y = 73;//rng.uniform(boarder, left_img.rows - boarder);  // don't pick pixels close to boarder\n        int disparity = disparity_img.at<uchar>(y, x);\n        double depth = fx * baseline / disparity; // you know this is disparity to depth\n        depth_ref.push_back(depth);\n        pixels_ref.push_back(Eigen::Vector2d(x, y));\n    }\n    // estimates 01~05.png's pose using this information\n    Sophus::SE3d T_cur_ref;\n\n    //for (int i = 1; i < 6; i++) {  // 1~10\n    cv::Mat img = cv::imread(imageLeft[1], 0);\n    // try single layer by uncomment this line\n    // DirectPoseEstimationSingleLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref);\n    DirectPoseEstimationMultiLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref);\n    //}\n    return 0;\n}\n\nvoid test_direct2()\n{\n    std::vector<string> imageLeft;\n    std::vector<string> imageRight;\n    std::vector<double> timeStamp;\n\n    LoadImages( \"/media/lyc/ 其他/dataset/sequences/00\",\n                imageLeft, imageRight, timeStamp);\n\n    auto matcher_ptr = std::make_shared<Matcher>();\n\n    cv::Mat left_img = cv::imread(imageLeft[0], 0);\n    cv::Mat disparity_img = cv::imread(disparity_file, 0);\n\n    // let's randomly pick pixels in the first image and generate some 3d points in the first image's frame\n    cv::RNG rng;\n    int nPoints = 2000;\n    int boarder = 20;\n    VecVector2d pixels_ref;\n    vector<double> depth_ref;\n    auto map_ptr = std::make_shared<TRACKING_BENCH::Map>();\n\n    auto camera_ptr = std::make_shared<PinholeCamera>(left_img.cols, left_img.rows,fx, fy, cx, cy);\n    cv::Mat img = cv::imread(imageLeft[1], 0);\n\n    auto ref_frame_ptr = std::make_shared<Frame>(left_img, 0, 4, 0.5, camera_ptr);\n    auto cur_frame_ptr = std::make_shared<Frame>(img, 0, 4, 0.5, camera_ptr);\n\n    std::vector<cv::KeyPoint> kps;\n    // generate pixels in ref and load depth data\n    for (int i = 0; i < nPoints; i++)\n    {\n        int x = rng.uniform(boarder, left_img.cols - boarder);  // don't pick pixels close to boarder\n        int y = rng.uniform(boarder, left_img.rows - boarder);  // don't pick pixels close to boarder\n        int disparity = disparity_img.at<uchar>(y, x);\n        double depth = fx * baseline / disparity; // you know this is disparity to depth\n        depth_ref.push_back(depth);\n        pixels_ref.push_back(Eigen::Vector2d(x, y));\n        kps.emplace_back(cv::Point2f((float)x,(float)y),0);\n    }\n    ref_frame_ptr->SetKeys(kps, ref_frame_ptr);\n\n    for (int i = 0;i < nPoints; i++)\n    {\n        Eigen::Vector3f norm;\n        norm[0] = (pixels_ref.at(i).x() - cx)/fx;\n        norm[1] = (pixels_ref.at(i).y() - cy)/fy;\n        norm[2] = 1;\n        auto mp = std::make_shared<MapPoint>(norm * depth_ref[i], map_ptr, ref_frame_ptr, ref_frame_ptr->GetKey(i), cv::Mat());\n\n        ref_frame_ptr->AddMapPoint(mp, i);\n        map_ptr->AddMapPoint(mp);\n    }\n    ref_frame_ptr->SetPose(Eigen::Matrix4f::Identity());\n    Eigen::Matrix4f init_gauss = Eigen::Matrix4f::Identity();\n    cur_frame_ptr->SetPose(init_gauss);\n\n    matcher_ptr->setDirectParam(3, 0, 10, 5, 0.0001);\n    auto T_cur_ref = matcher_ptr->SparseImageAlign(cur_frame_ptr, ref_frame_ptr);\n    std::cout<<\"T: \"<<T_cur_ref<<std::endl;\n\n}\n\n\nvoid test_image_align()\n{\n    std::vector<string> imageLeft;\n    std::vector<string> imageRight;\n    std::vector<double> timeStamp;\n\n    LoadImages( \"/media/lyc/ 其他/dataset/sequences/00\",\n                imageLeft, imageRight, timeStamp);\n\n    auto matcher_ptr = std::make_shared<Matcher>();\n\n    cv::Mat left_img = cv::imread(imageLeft[0], 0);\n    cv::Mat disparity_img = cv::imread(disparity_file, 0);\n\n    // let's randomly pick pixels in the first image and generate some 3d points in the first image's frame\n    cv::RNG rng;\n    int nPoints = 1;\n    int boarder = 20;\n    VecVector2d pixels_ref;\n    vector<double> depth_ref;\n    auto map_ptr = std::make_shared<TRACKING_BENCH::Map>();\n\n    auto camera_ptr = std::make_shared<PinholeCamera>(left_img.cols, left_img.rows,fx, fy, cx, cy);\n    cv::Mat img = cv::imread(imageLeft[1], 0);\n\n    auto ref_frame_ptr = std::make_shared<Frame>(left_img, 0, 4, 0.5, camera_ptr);\n    auto cur_frame_ptr = std::make_shared<Frame>(img, 0, 4, 0.5, camera_ptr);\n\n    std::vector<cv::KeyPoint> kps;\n    // generate pixels in ref and load depth data\n    for (int i = 0; i < nPoints; i++)\n    {\n        int x = 130;//rng.uniform(boarder, left_img.cols - boarder);  // don't pick pixels close to boarder\n        int y = 73;//rng.uniform(boarder, left_img.rows - boarder);  // don't pick pixels close to boarder\n        int disparity = disparity_img.at<uchar>(y, x);\n        double depth = fx * baseline / disparity; // you know this is disparity to depth\n        depth_ref.push_back(depth);\n        pixels_ref.push_back(Eigen::Vector2d(x, y));\n        kps.emplace_back(cv::Point2f((float)x,(float)y),0, 0, 0, 1);\n    }\n    ref_frame_ptr->SetKeys(kps, ref_frame_ptr);\n\n    ref_frame_ptr->SetPose(Eigen::Matrix4f::Identity());\n    Eigen::Matrix4f init_gauss = Eigen::Matrix4f::Identity();\n    cur_frame_ptr->SetPose(init_gauss);\n    for (int i = 0;i < nPoints; i++)\n    {\n        Eigen::Vector3f norm;\n        norm[0] = (pixels_ref.at(i).x() - cx)/fx;\n        norm[1] = (pixels_ref.at(i).y() - cy)/fy;\n        norm[2] = 1;\n        auto mp = std::make_shared<MapPoint>(norm * depth_ref[i], map_ptr, ref_frame_ptr, ref_frame_ptr->GetKey(i), cv::Mat());\n\n        ref_frame_ptr->AddMapPoint(mp, i);\n        map_ptr->AddMapPoint(mp);\n\n        Eigen::Vector2f px_cur(130, 73);\n\n        cv::Mat show1 = cur_frame_ptr->GetImagePyramid()[0].clone();\n        cv::Mat show2 = ref_frame_ptr->GetImagePyramid()[0].clone();\n        cv::cvtColor(show1, show1, CV_GRAY2BGR);\n        cv::cvtColor(show2, show2, CV_GRAY2BGR);\n        cv::circle(show2, cv::Point((int)px_cur[0], (int)px_cur[1]), 5, cv::Scalar(255, 0, 0), 5);\n\n        std::cout<<\"before \"<<std::endl<<px_cur<<std::endl;\n        matcher_ptr->FindMatchDirect(mp, cur_frame_ptr, px_cur);\n        std::cout<<\"after \"<<std::endl<<px_cur<<std::endl;\n\n        cv::circle(show1, cv::Point((int)px_cur[0], (int)px_cur[1]), 5, cv::Scalar(255, 0, 0), 5);\n\n        cv::imshow(\"before\", show2);\n        cv::imshow(\"after\", show1);\n        cv::waitKey(0);\n    }\n\n    ref_frame_ptr->SetPose(Eigen::Matrix4f::Identity());\n    cur_frame_ptr->SetPose(Eigen::Matrix4f::Identity());\n\n//    const cv::Mat& cur_img, uint8_t* ref_patch_with_border, uint8_t* ref_patch, const int n_iter, Eigen::Vector2f& cur_ps_estimate, bool no_simd = false\n    int half_patch_size = 4;\n    uint8_t patch[half_patch_size*half_patch_size*4] __attribute__((aligned(16)));\n    uint8_t patch_with_border[(half_patch_size+1)*(half_patch_size+1)*4] __attribute__((aligned(16)));\n\n    Eigen::Vector2f px_scaled(65, 36.5);\n    const int cur_step = ref_frame_ptr->GetImagePyramid()[1].step.p[0];\n\n    for(int y=0; y<(half_patch_size+1)*2; ++y)\n    {\n        uint8_t *it = (uint8_t *) ref_frame_ptr->GetImagePyramid()[1].data + ((int)px_scaled[1] + y - half_patch_size-1) * cur_step + (int)px_scaled[0] - half_patch_size-1;\n        for (int x = 0; x < (half_patch_size+1)*2; ++x, ++it)\n        {\n            int id = x + y*(half_patch_size+1)*2;\n            patch_with_border[id] = *it;\n        }\n    }\n\n    uint8_t* patch_ptr = patch;\n    for(int y = 1; y < half_patch_size*2 + 1; ++y, patch_ptr += half_patch_size*2)\n    {\n        uint8_t* y_ptr = patch_with_border + y * (half_patch_size*2 + 2) + 1;\n        for(int x = 0; x < half_patch_size*2; ++x)\n            patch_ptr[x] = y_ptr[x];\n    }\n\n    cv::Mat show1 = cur_frame_ptr->GetImagePyramid()[1].clone();\n    cv::Mat show2 = ref_frame_ptr->GetImagePyramid()[1].clone();\n    cv::cvtColor(show1, show1, CV_GRAY2BGR);\n    cv::cvtColor(show2, show2, CV_GRAY2BGR);\n\n    cv::circle(show2, cv::Point((int)px_scaled[0], (int)px_scaled[1]), 5, cv::Scalar(255, 0, 0), 5);\n\n    std::cout<<\" before: \"<<px_scaled<<std::endl;\n    matcher_ptr->Align2D(cur_frame_ptr->GetImagePyramid()[1], patch_with_border, patch, 40, px_scaled);\n    std::cout<<\" align: \"<<px_scaled<<std::endl;\n    cv::circle(show1, cv::Point((int)px_scaled[0], (int)px_scaled[1]), 5, cv::Scalar(255, 0, 0), 5);\n\n    cv::imshow(\"before\", show2);\n    cv::imshow(\"after\", show1);\n    cv::waitKey(0);\n}\n\nint main()\n{\n    //test_direct();\n    //test_direct2();\n    test_projection();\n//    test_image_align();\n    return 0;\n}\n", "meta": {"hexsha": "75a3a437da4d45f16ac57aec8ed090f355efae1a", "size": 32608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_projection.cpp", "max_stars_repo_name": "linyicheng1/trackingBench-SLAM", "max_stars_repo_head_hexsha": "2a110a43bb54867428faa218915cb03596f66e9e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-11T08:32:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T08:32:16.000Z", "max_issues_repo_path": "test/test_projection.cpp", "max_issues_repo_name": "linyicheng1/trackingBench-SLAM", "max_issues_repo_head_hexsha": "2a110a43bb54867428faa218915cb03596f66e9e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_projection.cpp", "max_forks_repo_name": "linyicheng1/trackingBench-SLAM", "max_forks_repo_head_hexsha": "2a110a43bb54867428faa218915cb03596f66e9e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5970819304, "max_line_length": 172, "alphanum_fraction": 0.5612733072, "num_tokens": 9269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4314133693219749}}
{"text": "/*\n\nCopyright (c) 2005-2015, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#ifndef _RUNGEKUTTAFEHLBERGIVPODESOLVER_HPP_\n#define _RUNGEKUTTAFEHLBERGIVPODESOLVER_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"AbstractOneStepIvpOdeSolver.hpp\"\n\n/**\n * A concrete one step ODE solver class that employs the Runge Kutta\n * Fehlberg adaptive solver (RKF45).\n *\n * This solver is good for problems where you need to be able to\n * guarantee the accuracy of the answer as it is specified via the\n * tolerance parameter.\n *\n * The solver should also be reasonably fast as it increases the\n * timestep when the solutions are changing slowly, whilst maintaining\n * accuracy.\n */\nclass RungeKuttaFehlbergIvpOdeSolver : public AbstractIvpOdeSolver\n{\nfriend class TestRungeKuttaFehlbergIvpOdeSolver;\n\nprivate:\n    /** Needed for serialization. */\n    friend class boost::serialization::access;\n    /**\n     * Archive, never used directly - boost uses this.\n     *\n     * @param archive the archive\n     * @param version the current version of this class\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n        // This calls serialize on the base class - all member variables instantiated on construction or temporary.\n        archive & boost::serialization::base_object<AbstractIvpOdeSolver>(*this);\n    }\n\n    /*\n     * All these are here for more efficient memory allocation, rather than\n     * because they need to be member variables.\n     */\n\n    double m1932o2197;  /**< Working memory: numerical value for the fraction 1932/2197.  */\n    double m7200o2197;  /**< Working memory: numerical value for the fraction 7200/2197.  */\n    double m7296o2197;  /**< Working memory: numerical value for the fraction 7296/2197.  */\n    double m12o13;      /**< Working memory: numerical value for the fraction 12/13.      */\n    double m439o216;    /**< Working memory: numerical value for the fraction 439/216.    */\n    double m3680o513;   /**< Working memory: numerical value for the fraction 3680/513.   */\n    double m845o4104;   /**< Working memory: numerical value for the fraction 845/4104.   */\n    double m8o27;       /**< Working memory: numerical value for the fraction 8/27.       */\n    double m3544o2565;  /**< Working memory: numerical value for the fraction 3544/2565.  */\n    double m1859o4104;  /**< Working memory: numerical value for the fraction 1859/4104.  */\n    double m1o360;      /**< Working memory: numerical value for the fraction 1/360.      */\n    double m128o4275;   /**< Working memory: numerical value for the fraction 128/4275.   */\n    double m2197o75240; /**< Working memory: numerical value for the fraction 2197/75240. */\n    double m2o55;       /**< Working memory: numerical value for the fraction 2/55.       */\n    double m25o216;     /**< Working memory: numerical value for the fraction 25/216.     */\n    double m1408o2565;  /**< Working memory: numerical value for the fraction 1408/2565.  */\n    double m2197o4104;  /**< Working memory: numerical value for the fraction 2197/4104.  */\n\n    std::vector<double> mError; /**< Error expression, used to adjust the timestep in the RKF45 method. */\n\n    std::vector<double> mk1;  /**< Working memory: expression k1 in the RKF45 method.  */\n    std::vector<double> mk2;  /**< Working memory: expression k2 in the RKF45 method.  */\n    std::vector<double> mk3;  /**< Working memory: expression k3 in the RKF45 method.  */\n    std::vector<double> mk4;  /**< Working memory: expression k4 in the RKF45 method.  */\n    std::vector<double> mk5;  /**< Working memory: expression k5 in the RKF45 method.  */\n    std::vector<double> mk6;  /**< Working memory: expression k6 in the RKF45 method.  */\n    std::vector<double> myk2; /**< Working memory: expression yk2 in the RKF45 method. */\n    std::vector<double> myk3; /**< Working memory: expression yk3 in the RKF45 method. */\n    std::vector<double> myk4; /**< Working memory: expression yk4 in the RKF45 method. */\n    std::vector<double> myk5; /**< Working memory: expression yk5 in the RKF45 method. */\n    std::vector<double> myk6; /**< Working memory: expression yk6 in the RKF45 method. */\n\nprotected:\n\n    /**\n     * Method that actually performs the solving on behalf of the public Solve methods.\n     *\n     * @param rSolution  an ODE solution to input data into if requited\n     * @param pAbstractOdeSystem  the ODE system to solve\n     * @param rCurrentYValues  the current (initial) state; results will also be returned in here\n     * @param rWorkingMemory  working memory; same size as rCurrentYValues\n     * @param startTime  initial time\n     * @param endTime  time to solve to\n     * @param maxTimeStep  the maximum size of timestep allowable\n     * @param minTimeStep  the maximum size of timestep allowable (to prevent huge loops)\n     * @param tolerance  how accurate the numerical solution must be\n     * @param outputSolution whether to output into rSolution (or save time by not doing)\n     */\n    void InternalSolve(OdeSolution& rSolution,\n                       AbstractOdeSystem* pAbstractOdeSystem,\n                       std::vector<double>& rCurrentYValues,\n                       std::vector<double>& rWorkingMemory,\n                       double startTime,\n                       double endTime,\n                       double maxTimeStep,\n                       double minTimeStep,\n                       double tolerance,\n                       bool outputSolution);\n\n    /**\n     * Calculate the solution to the ODE system at the next timestep.\n     * Updates the mError vector with current error.\n     *\n     * @param pAbstractOdeSystem  the ODE system to solve\n     * @param timeStep  dt\n     * @param time  the current time\n     * @param rCurrentYValues  the current (initial) state\n     * @param rNextYValues  the state at the next timestep\n     */\n    void CalculateNextYValue(AbstractOdeSystem* pAbstractOdeSystem,\n                             double timeStep,\n                             double time,\n                             std::vector<double>& rCurrentYValues,\n                             std::vector<double>& rNextYValues);\n\n    /**\n     * Use the error approximation of the last call to the CalculateNextYValue()\n     * method to change the time step appropriately.\n     *\n     * @param rCurrentStepSize  the current step size being used (returns answer via this reference)\n     * @param rError  the error in the approximation at this time step\n     * @param rTolerance  the tolerance required\n     * @param rMaxTimeStep  the maximum timestep to be used\n     * @param rMinTimeStep  the minimum timestep to be used (to prevent huge loops)\n     */\n    void AdjustStepSize(double& rCurrentStepSize,\n                        const double& rError,\n                        const double& rTolerance,\n                        const double& rMaxTimeStep,\n                        const double& rMinTimeStep);\n\npublic:\n\n    /**\n     * Constructor.\n     */\n    RungeKuttaFehlbergIvpOdeSolver();\n\n    /**\n     * Solves a system of ODEs using a specified one-step ODE solver and returns\n     * the solution as an OdeSolution object.\n     *\n     * @param pAbstractOdeSystem  pointer to the concrete ODE system to be solved\n     * @param rYValues  a standard vector specifying the intial condition of each\n     *                  solution variable in the system (this can be the initial\n     *                  conditions vector stored in the ODE system)\n     * @param startTime  the time at which the initial conditions are specified\n     * @param endTime  the time to which the system should be solved and the solution\n     *                 returned\n     * @param timeStep  the time interval to be used by the solver\n     * @param ignoredSamplingTime  the interval at which to sample the solution to the ODE system\n     *                             (ignored in this class as the timestep is variable)\n     *\n     * @return OdeSolution is an object containing an integer of the number of\n     * equations, a stdAbstractOdeSystem::vector of times and a std::vector of std::vectors where\n     * each of those vectors contains the solution for one variable of the ODE\n     * system at those times.\n     */\n    OdeSolution Solve(AbstractOdeSystem* pAbstractOdeSystem,\n                      std::vector<double>& rYValues,\n                      double startTime,\n                      double endTime,\n                      double timeStep,\n                      double ignoredSamplingTime);\n\n    /**\n     * Second version of Solve. Solves a system of ODEs using a specified one-step\n     * ODE solver. This method does not return the solution and therefore does not\n     * take in a sampling time. Instead, the mStateVariables component in the ODE\n     * system object is updated.\n     *\n     * @param pAbstractOdeSystem  pointer to the concrete ODE system to be solved\n     * @param rYValues  a standard vector specifying the intial condition of each\n     *                  solution variable in the system (this can be the initial\n     *                  conditions vector stored in the ODE system)\n     * @param startTime  the time at which the initial conditions are specified\n     * @param endTime  the time to which the system should be solved and the solution\n     *                 returned\n     * @param timeStep  the time interval to be used by the solver\n     */\n    void Solve(AbstractOdeSystem* pAbstractOdeSystem,\n               std::vector<double>& rYValues,\n               double startTime,\n               double endTime,\n               double timeStep);\n\n};\n\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(RungeKuttaFehlbergIvpOdeSolver)\n\n#endif //_RUNGEKUTTAFEHLBERGIVPODESOLVER_HPP_\n", "meta": {"hexsha": "4491d991c34ca4a3897b5adf1895edc4c382d0a0", "size": 11419, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ode/src/solver/RungeKuttaFehlbergIvpOdeSolver.hpp", "max_stars_repo_name": "ktunya/ChasteMod", "max_stars_repo_head_hexsha": "88ac65b00473cd730d348c783bd74b2b39de5f69", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ode/src/solver/RungeKuttaFehlbergIvpOdeSolver.hpp", "max_issues_repo_name": "ktunya/ChasteMod", "max_issues_repo_head_hexsha": "88ac65b00473cd730d348c783bd74b2b39de5f69", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ode/src/solver/RungeKuttaFehlbergIvpOdeSolver.hpp", "max_forks_repo_name": "ktunya/ChasteMod", "max_forks_repo_head_hexsha": "88ac65b00473cd730d348c783bd74b2b39de5f69", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.008583691, "max_line_length": 115, "alphanum_fraction": 0.6794815658, "num_tokens": 2634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.43131209178437585}}
{"text": "#include \"teca_integrated_vapor_transport.h\"\n\n#include \"teca_cartesian_mesh.h\"\n#include \"teca_array_collection.h\"\n#include \"teca_variant_array.h\"\n#include \"teca_metadata.h\"\n#include \"teca_coordinate_util.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <cmath>\n\n#if defined(TECA_HAS_BOOST)\n#include <boost/program_options.hpp>\n#endif\n\nusing std::string;\nusing std::vector;\nusing std::cerr;\nusing std::endl;\nusing std::cos;\n\n//#define TECA_DEBUG\n\nnamespace {\ntemplate <typename coord_t, typename num_t>\nvoid cartesian_ivt(unsigned long nx, unsigned long ny,\n    unsigned long nz, const coord_t *plev, const num_t *wind,\n    const num_t *q, num_t *ivt)\n{\n    unsigned long nxy = nx*ny;\n    unsigned long nxyz = nxy*nz;\n\n    // compute the integrand\n    num_t *f = (num_t*)malloc(nxyz*sizeof(num_t));\n    for (unsigned long i = 0; i < nxyz; ++i)\n        f[i] = wind[i]*q[i];\n\n    // initialize the result\n    memset(ivt, 0, nxy*sizeof(num_t));\n\n    // work an x-y slice at  a time\n    unsigned long nzm1 = nz - 1;\n    for (unsigned long k = 0; k < nzm1; ++k)\n    {\n        // dp over the slice\n        num_t h2 = num_t(0.5) * (plev[k+1] - plev[k]);\n\n        // the current two x-y-planes of data\n        unsigned long knxy = k*nxy;\n        num_t *f_k0 = f + knxy;\n        num_t *f_k1 = f_k0 + nxy;\n\n        // accumulate this plane of data using trapazoid rule\n        for (unsigned long q = 0; q < nxy; ++q)\n        {\n            ivt[q] += h2 * (f_k0[q] + f_k1[q]);\n        }\n    }\n\n    // free up the integrand\n    free(f);\n\n    // check the sign, in this way we can handle both increasing and decreasing\n    // pressure coordinates\n    num_t s = plev[1] - plev[0] < num_t(0) ? num_t(-1) : num_t(1);\n\n    // scale by -1/g\n    num_t m1g = s/num_t(9.80665);\n    for (unsigned long i = 0; i < nxy; ++i)\n        ivt[i] *= m1g;\n}\n\ntemplate <typename coord_t, typename num_t>\nvoid cartesian_ivt(unsigned long nx, unsigned long ny,\n    unsigned long nz, const coord_t *plev, const num_t *wind,\n    const char *wind_valid, const num_t *q, const char *q_valid,\n    num_t *ivt)\n{\n    unsigned long nxy = nx*ny;\n    unsigned long nxyz = nxy*nz;\n\n    // compute the mask\n    char *mask = (char*)malloc(nxyz);\n    for (unsigned long i = 0; i < nxyz; ++i)\n        mask[i] = wind_valid[i] && q_valid[i] ? 1 : 0;\n\n    // compute the integrand\n    num_t *f = (num_t*)malloc(nxyz*sizeof(num_t));\n    for (unsigned long i = 0; i < nxyz; ++i)\n        f[i] = wind[i]*q[i];\n\n    // initialize the result\n    memset(ivt, 0, nxy*sizeof(num_t));\n\n    // work an x-y slice at a time\n    unsigned long nzm1 = nz - 1;\n    for (unsigned long k = 0; k < nzm1; ++k)\n    {\n        // dp over the slice\n        num_t h2 = num_t(0.5) * (plev[k+1] - plev[k]);\n\n        // the current two x-y-planes of data\n        unsigned long knxy = k*nxy;\n        num_t *f_k0 = f + knxy;\n        num_t *f_k1 = f_k0 + nxy;\n\n        char *mask_k0 = mask + knxy;\n        char *mask_k1 = mask_k0 + nxy;\n\n        // accumulate this plane of data using trapazoid rule\n        for (unsigned long q = 0; q < nxy; ++q)\n        {\n            ivt[q] += ((mask_k0[q] && mask_k1[q]) ?\n               h2 * (f_k0[q] + f_k1[q]) : num_t(0));\n        }\n    }\n\n    // free up the integrand and mask\n    free(mask);\n    free(f);\n\n    // check the sign, in this way we can handle both increasing and decreasing\n    // pressure coordinates\n    num_t s = plev[1] - plev[0] < num_t(0) ? num_t(-1) : num_t(1);\n\n    // scale by -1/g\n    num_t m1g = s/num_t(9.80665);\n    for (unsigned long i = 0; i < nxy; ++i)\n        ivt[i] *= m1g;\n}\n}\n\n// --------------------------------------------------------------------------\nteca_integrated_vapor_transport::teca_integrated_vapor_transport() :\n    wind_u_variable(\"ua\"), wind_v_variable(\"va\"),\n    specific_humidity_variable(\"hus\"), ivt_u_variable(\"ivt_u\"),\n    ivt_v_variable(\"ivt_v\"), fill_value(1.0e20)\n{\n    this->set_number_of_input_connections(1);\n    this->set_number_of_output_ports(1);\n}\n\n// --------------------------------------------------------------------------\nteca_integrated_vapor_transport::~teca_integrated_vapor_transport()\n{}\n\n#if defined(TECA_HAS_BOOST)\n// --------------------------------------------------------------------------\nvoid teca_integrated_vapor_transport::get_properties_description(\n    const string &prefix, options_description &global_opts)\n{\n    options_description opts(\"Options for \"\n        + (prefix.empty()?\"teca_integrated_vapor_transport\":prefix));\n\n    opts.add_options()\n        TECA_POPTS_GET(std::string, prefix, wind_u_variable,\n            \"name of the variable containg the lon component of the wind vector\")\n        TECA_POPTS_GET(std::string, prefix, wind_v_variable,\n            \"name of the variable containg the lat component of the wind vector\")\n        TECA_POPTS_GET(std::string, prefix, specific_humidity_variable,\n            \"name of the variable containg the specific humidity\")\n        TECA_POPTS_GET(double, prefix, fill_value,\n            \"the value of the NetCDF _FillValue attribute\")\n        ;\n\n    this->teca_algorithm::get_properties_description(prefix, opts);\n\n    global_opts.add(opts);\n}\n\n// --------------------------------------------------------------------------\nvoid teca_integrated_vapor_transport::set_properties(\n    const string &prefix, variables_map &opts)\n{\n    this->teca_algorithm::set_properties(prefix, opts);\n\n    TECA_POPTS_SET(opts, std::string, prefix, wind_u_variable)\n    TECA_POPTS_SET(opts, std::string, prefix, wind_v_variable)\n    TECA_POPTS_SET(opts, std::string, prefix, specific_humidity_variable)\n    TECA_POPTS_SET(opts, double, prefix, fill_value)\n}\n#endif\n\n// --------------------------------------------------------------------------\nteca_metadata teca_integrated_vapor_transport::get_output_metadata(\n    unsigned int port,\n    const std::vector<teca_metadata> &input_md)\n{\n#ifdef TECA_DEBUG\n    std::cerr << teca_parallel_id()\n        << \"teca_integrated_vapor_transport::get_output_metadata\" << std::endl;\n#endif\n    (void)port;\n\n    // set things up in the first pass, and don't modify in subsequent passes\n    // due to threading concerns\n\n    if (this->get_number_of_derived_variables() == 0)\n    {\n        // the base class will handle dealing with the transformation of\n        // mesh dimensions and reporting the array we produce, but we have\n        // to determine the data type and tell the name of the produced array.\n        const teca_metadata &md = input_md[0];\n\n        teca_metadata attributes;\n        if (md.get(\"attributes\", attributes))\n        {\n            TECA_FATAL_ERROR(\"Failed to determine output data type \"\n                \"because attributes are misisng\")\n            return teca_metadata();\n        }\n\n        teca_metadata u_atts;\n        if (attributes.get(this->wind_u_variable, u_atts))\n        {\n            TECA_FATAL_ERROR(\"Failed to determine output data type \"\n                \"because attributes for \\\"\" << this->wind_u_variable\n                << \"\\\" are misisng\")\n            return teca_metadata();\n        }\n\n        int type_code = 0;\n        if (u_atts.get(\"type_code\", type_code))\n        {\n            TECA_FATAL_ERROR(\"Failed to determine output data type \"\n                \"because attributes for \\\"\" << this->wind_u_variable\n                << \"\\\" is misisng a \\\"type_code\\\"\")\n            return teca_metadata();\n        }\n\n        teca_array_attributes ivt_u_atts(\n            type_code, teca_array_attributes::point_centering,\n            0, \"kg m^{-1} s^{-1}\", \"longitudinal integrated vapor transport\",\n            \"the longitudinal component of integrated vapor transport\",\n            1, this->fill_value);\n\n        teca_array_attributes ivt_v_atts(\n            type_code, teca_array_attributes::point_centering,\n            0, \"kg m^{-1} s^{-1}\", \"latitudinal integrated vapor transport\",\n            \"the latitudinal component of integrated vapor transport\",\n            this->fill_value);\n\n        // install name and attributes of the output variables in the base classs\n        this->append_derived_variable(this->ivt_u_variable);\n        this->append_derived_variable(this->ivt_v_variable);\n\n        this->append_derived_variable_attribute(ivt_u_atts);\n        this->append_derived_variable_attribute(ivt_v_atts);\n\n    }\n\n    if (this->get_number_of_dependent_variables() == 0)\n    {\n        // install the names of the input variables in the base class\n        this->append_dependent_variable(this->wind_u_variable);\n        this->append_dependent_variable(this->wind_v_variable);\n        this->append_dependent_variable(this->specific_humidity_variable);\n    }\n\n    // invoke the base class method, which does the work of transforming\n    // the mesh and reporting the variables and their attributes.\n    return teca_vertical_reduction::get_output_metadata(port, input_md);\n}\n\n// --------------------------------------------------------------------------\nstd::vector<teca_metadata> teca_integrated_vapor_transport::get_upstream_request(\n    unsigned int port,\n    const std::vector<teca_metadata> &input_md,\n    const teca_metadata &request)\n{\n    // invoke the base class method\n    return teca_vertical_reduction::get_upstream_request(port, input_md, request);\n}\n\n// --------------------------------------------------------------------------\nconst_p_teca_dataset teca_integrated_vapor_transport::execute(\n    unsigned int port,\n    const std::vector<const_p_teca_dataset> &input_data,\n    const teca_metadata &request)\n{\n#ifdef TECA_DEBUG\n    std::cerr << teca_parallel_id()\n        << \"teca_integrated_vapor_transport::execute\" << std::endl;\n#endif\n    (void)port;\n\n    // get the input mesh\n    const_p_teca_cartesian_mesh in_mesh\n        = std::dynamic_pointer_cast<const teca_cartesian_mesh>(input_data[0]);\n\n    if (!in_mesh)\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IVT because a cartesian mesh is required.\")\n        return nullptr;\n    }\n\n    // get the input dimensions\n    unsigned long extent[6] = {0};\n    if (in_mesh->get_extent(extent))\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IVT because mesh extent is missing.\")\n        return nullptr;\n    }\n\n    unsigned long nx = extent[1] - extent[0] + 1;\n    unsigned long ny = extent[3] - extent[2] + 1;\n    unsigned long nz = extent[5] - extent[4] + 1;\n\n    // get the pressure coordinates\n    const_p_teca_variant_array p = in_mesh->get_z_coordinates();\n    if (!p)\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IVT because pressure coordinates are missing\")\n        return nullptr;\n    }\n\n    if (p->size() < 2)\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IVT because z dimensions \"\n            << p->size() << \" < 2 as required by the integration method\")\n        return nullptr;\n    }\n\n    // gather the input arrays\n    const_p_teca_variant_array wind_u =\n        in_mesh->get_point_arrays()->get(this->wind_u_variable);\n\n    if (!wind_u)\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IVT because longitudinal wind \\\"\"\n            << this->wind_u_variable << \"\\\" is missing\")\n        return nullptr;\n    }\n\n    const_p_teca_variant_array wind_u_valid =\n           in_mesh->get_point_arrays()->get(this->wind_u_variable + \"_valid\");\n\n    const_p_teca_variant_array wind_v =\n        in_mesh->get_point_arrays()->get(this->wind_v_variable);\n\n    if (!wind_v)\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IVT because latitudinal wind \\\"\"\n            << this->wind_v_variable << \"\\\" is missing\")\n        return nullptr;\n    }\n\n    const_p_teca_variant_array wind_v_valid =\n           in_mesh->get_point_arrays()->get(this->wind_v_variable + \"_valid\");\n\n    const_p_teca_variant_array q =\n        in_mesh->get_point_arrays()->get(this->specific_humidity_variable);\n\n    if (!q)\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IVT because specific humidity \\\"\"\n            << this->specific_humidity_variable << \"\\\" is missing\")\n        return nullptr;\n    }\n\n    const_p_teca_variant_array q_valid =\n           in_mesh->get_point_arrays()->get(this->specific_humidity_variable + \"_valid\");\n\n    // the base class will construct the output mesh\n    p_teca_cartesian_mesh out_mesh\n        = std::dynamic_pointer_cast<teca_cartesian_mesh>(\n            std::const_pointer_cast<teca_dataset>(\n                teca_vertical_reduction::execute(port, input_data, request)));\n\n    if (!out_mesh)\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IVT because the output mesh was \"\n            \"not constructed\")\n        return nullptr;\n    }\n\n    // allocate the output arrays\n    unsigned long nxy = nx*ny;\n    p_teca_variant_array ivt_u = wind_u->new_instance(nxy);\n    p_teca_variant_array ivt_v = wind_u->new_instance(nxy);\n\n    // store the result\n    out_mesh->get_point_arrays()->set(this->ivt_u_variable, ivt_u);\n    out_mesh->get_point_arrays()->set(this->ivt_v_variable, ivt_v);\n\n    // calculate IVT\n    NESTED_TEMPLATE_DISPATCH_FP(const teca_variant_array_impl,\n        p.get(), _COORDS,\n\n        const NT_COORDS *p_p = static_cast<TT_COORDS*>(p.get())->get();\n\n        NESTED_TEMPLATE_DISPATCH_FP(teca_variant_array_impl,\n            ivt_u.get(), _DATA,\n\n            NT_DATA *p_ivt_u = static_cast<TT_DATA*>(ivt_u.get())->get();\n            NT_DATA *p_ivt_v = static_cast<TT_DATA*>(ivt_v.get())->get();\n\n            const NT_DATA *p_wind_u = static_cast<const TT_DATA*>(wind_u.get())->get();\n            const NT_DATA *p_wind_v = static_cast<const TT_DATA*>(wind_v.get())->get();\n            const NT_DATA *p_q = static_cast<const TT_DATA*>(q.get())->get();\n\n            const char *p_wind_u_valid = nullptr;\n            const char *p_wind_v_valid = nullptr;\n            const char *p_q_valid = nullptr;\n            if (wind_u_valid)\n            {\n                using TT_MASK = teca_char_array;\n\n                p_wind_u_valid = dynamic_cast<const TT_MASK*>(wind_u_valid.get())->get();\n                p_wind_v_valid = dynamic_cast<const TT_MASK*>(wind_v_valid.get())->get();\n                p_q_valid = dynamic_cast<const TT_MASK*>(q_valid.get())->get();\n\n                ::cartesian_ivt(nx, ny, nz, p_p, p_wind_u, p_wind_u_valid, p_q, p_q_valid, p_ivt_u);\n                ::cartesian_ivt(nx, ny, nz, p_p, p_wind_v, p_wind_v_valid, p_q, p_q_valid, p_ivt_v);\n            }\n            else\n            {\n                ::cartesian_ivt(nx, ny, nz, p_p, p_wind_u, p_q, p_ivt_u);\n                ::cartesian_ivt(nx, ny, nz, p_p, p_wind_v, p_q, p_ivt_v);\n            }\n            )\n        )\n\n    // pass 2D arrays through.\n    p_teca_array_collection in_arrays =\n        std::const_pointer_cast<teca_array_collection>(in_mesh->get_point_arrays());\n\n    p_teca_array_collection out_arrays = out_mesh->get_point_arrays();\n\n    int n_arrays = in_arrays->size();\n    for (int i = 0; i < n_arrays; ++i)\n    {\n        p_teca_variant_array array = in_arrays->get(i);\n        if (array->size() == nxy)\n        {\n            // pass the array.\n            out_arrays->append(in_arrays->get_name(i), array);\n        }\n    }\n\n    return out_mesh;\n}\n", "meta": {"hexsha": "6de75c40fd622adfe5ede95bb745d461a6a41250", "size": 15010, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "alg/teca_integrated_vapor_transport.cxx", "max_stars_repo_name": "LBL-EESA/TECA", "max_stars_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T14:22:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T05:02:25.000Z", "max_issues_repo_path": "alg/teca_integrated_vapor_transport.cxx", "max_issues_repo_name": "LBL-EESA/TECA", "max_issues_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 476.0, "max_issues_repo_issues_event_min_datetime": "2016-11-28T18:06:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-25T05:31:42.000Z", "max_forks_repo_path": "alg/teca_integrated_vapor_transport.cxx", "max_forks_repo_name": "LBL-EESA/TECA", "max_forks_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2017-04-25T18:15:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-28T18:16:05.000Z", "avg_line_length": 33.7303370787, "max_line_length": 100, "alphanum_fraction": 0.6147235177, "num_tokens": 3763, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.43131209178437585}}
{"text": "#include <Eigen/Dense>\n#include <assert.h>\n#include <boost/math/special_functions/sign.hpp>\n#include <iostream>\n#include <math.h>\n\n#include \"grid.hpp\"\n#include \"spdlog/spdlog.h\"\n\nusing namespace Eigen;\nusing namespace SnowSimulator;\n\n// ============================================================================\n// GRIDCELL METHODS\n// ============================================================================\n\nGridCell::GridCell() {}\n\nvoid GridCell::addMaterialPoint(MaterialPoint *materialPoint) {\n  m_materialPoints.push_back(materialPoint);\n  materialPoint->m_cell = this;\n}\n\nvoid GridCell::clear() { m_materialPoints.clear(); }\n\n// ============================================================================\n// GRIDNODE METHODS\n// ============================================================================\n\nGridNode::GridNode(Vector3i idx, Grid *grid)\n    : m_idx(idx), m_grid(grid), m_mass(0), m_velocity(Vector3f::Zero()),\n      m_nextVelocity(Vector3f::Zero()), m_force(Vector3f::Zero()) {}\n\nVector3f GridNode::position() const {\n  return m_idx.cast<float>() * m_grid->m_spacing;\n}\n\nvoid GridNode::zeroForce() { m_force = Vector3f::Zero(); }\n\nvoid GridNode::addForce(Vector3f force) { m_force += force; }\n\n/**\n * The cubic B-spline formulation of the grid basis function used for\n * determining how particle properties are transferred to the grid. Both\n * this function and the gradient of this function below are called for each\n * pair of particle and grid node. This is referred to as N in the paper.\n */\nfloat GridNode::cubicBSpline(float x) const {\n  float absx = fabs(x);\n\n  if (absx >= 2) {\n    return 0;\n  } else if (absx < 1) {\n    return (0.5f * absx - 1.f) * absx * absx + (2.0f / 3);\n  } else {\n    return (((-1.0f / 6) * absx + 1) * absx - 2) * absx + (4.0f / 3);\n  }\n}\n\nfloat GridNode::gradCubicBSpline(float x) const {\n  float absx = fabs(x);\n  // int sign = copysign(1, x);\n  int sign = x > 0 ? 1 : -1;\n\n  if (absx < 1) {\n    return sign * (1.5 * absx - 2) * absx;\n  } else if (absx < 2) {\n    return sign * ((-0.5f * absx + 2) * absx - 2);\n  } else {\n    return 0;\n  }\n}\n\n/**\n * Computes the weight necessary for rasterizing the properties of a\n * materialPoint to the grid. This is referred to as w in the paper.\n */\nfloat GridNode::basisFunction(Vector3f particlePos) const {\n  Vector3f offset = particlePos / m_grid->m_spacing - m_idx.cast<float>();\n\n  return cubicBSpline(offset.x()) * cubicBSpline(offset.y()) *\n         cubicBSpline(offset.z());\n}\n\nVector3f GridNode::gradBasisFunction(Vector3f particlePos) const {\n  float invSpacing = 1.0f / m_grid->m_spacing;\n  Vector3f offset = invSpacing * particlePos - m_idx.cast<float>();\n\n  float gx = gradCubicBSpline(offset.x()) * cubicBSpline(offset.y()) *\n             cubicBSpline(offset.z());\n  float gy = cubicBSpline(offset.x()) * gradCubicBSpline(offset.y()) *\n             cubicBSpline(offset.z());\n  float gz = cubicBSpline(offset.x()) * cubicBSpline(offset.y()) *\n             gradCubicBSpline(offset.z());\n  return Vector3f(gx, gy, gz);\n}\n\n// ============================================================================\n// GRID METHODS\n// ============================================================================\n\nGrid::Grid(Vector3f origin, Vector3i dimensions, float spacing)\n    : m_origin(origin), m_dim(dimensions), m_spacing(spacing) {\n  auto logger = spdlog::get(\"snowsim\");\n\n  logger->info(\"Creating grid of size ({}, {}, {})\", m_dim.x(), m_dim.y(),\n               m_dim.z());\n\n  int num_nodes = m_dim.prod();\n  logger->info(\"Total node count: {}\", num_nodes);\n\n  // Allocate space for each of the gridNodes\n\n  logger->info(\"Allocating grid nodes and cells...\");\n\n  for (int i = 0; i < num_nodes; i++) {\n    GridNode *node = new GridNode(idxToVector(i), this);\n    m_gridNodes.push_back(node);\n    m_gridCells.push_back(new GridCell());\n  }\n\n  // Make sure each GridNode has a reference to the 4^3 surrounding GridCells\n  // within the support radius of the basis function.\n  // Each GridCell also needs to know about the 6^3 surrounding GridNodes.\n\n  logger->info(\"Linking grid nodes to neighboring cells...\");\n\n  for (int i = 0; i < num_nodes; i++) {\n    Vector3i idx = idxToVector(i);\n    GridNode *current = m_gridNodes[i];\n\n    // GridCell indexing is such that the corresponding GridNode is at the\n    // top-left corner of the GridCell.\n\n    Vector3i minIdx = (idx.array() - 2).max(0);\n    Vector3i maxIdx = (idx.array() + 1).min(m_dim.array() - 1);\n\n    for (int ox = minIdx.x(); ox < maxIdx.x(); ox++) {\n      for (int oy = minIdx.y(); oy < maxIdx.y(); oy++) {\n        for (int oz = minIdx.z(); oz < maxIdx.z(); oz++) {\n          int cellIdx = vectorToIdx(Vector3i(ox, oy, oz));\n          GridCell *neighborCell = m_gridCells[cellIdx];\n          current->m_neighborCells.push_back(neighborCell);\n        }\n      }\n    }\n  }\n}\n\nstd::vector<GridNode *> Grid::getAllNodes() { return m_gridNodes; }\n", "meta": {"hexsha": "d8ed3e507973ab2ea78ec69cbb74cce4e3b23ef7", "size": 4909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/grid.cpp", "max_stars_repo_name": "kvchen/snowsim", "max_stars_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/grid.cpp", "max_issues_repo_name": "kvchen/snowsim", "max_issues_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-14T16:38:11.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-14T16:38:11.000Z", "max_forks_repo_path": "src/grid.cpp", "max_forks_repo_name": "kvchen/snowsim", "max_forks_repo_head_hexsha": "09a75f24e86cc340ed327074904255fb08a3e7eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5099337748, "max_line_length": 79, "alphanum_fraction": 0.5878997759, "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.43131209178437585}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// asy_distribution.hpp                                                      //\n//                                                                           //\n//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_COMMON_ASY_DISTRIBUTION_HPP_ER_2010\n#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_PEARSON_CHISQ_COMMON_ASY_DISTRIBUTION_HPP_ER_2010\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/policies/policy.hpp>\n\nnamespace boost { \nnamespace statistics{\nnamespace detail{\nnamespace contingency_table{\nnamespace pearson_chisq_statistic{\n\n    namespace result_of{\n\n        template<typename T1,\n            typename Policy = boost::math::policies::policy<> >\n        struct asy_distribution{\n            typedef boost::math::chi_squared_distribution<T1,Policy> type;\n        };\n\n    }// result_of\n            \n    template<typename T1,typename AccSet,typename H0,typename Policy>\n    typename pearson_chisq_statistic::result_of::asy_distribution<T1,Policy>::type \n    asy_distribution(\n        const H0& hypothesis,\n        const AccSet& acc,\n        const Policy& pol\n    )\n    {\n        namespace ns = pearson_chisq_statistic;\n        typedef typename ns::result_of::asy_distribution<\n            T1,Policy>::type result_;\n        T1 df = static_cast<T1>( ns::degrees_of_freedom( hypothesis, acc ) );\n        return result_( df );\n    }\n\n    template<typename T1,typename AccSet,typename H0>\n    typename pearson_chisq_statistic::result_of::asy_distribution<T1>::type \n    asy_distribution(\n        const H0& hypothesis,\n        const AccSet& acc\n    ){\n        typedef boost::math::policies::policy<> pol_;\n        return asy_distribution<T1>( hypothesis, acc, pol_() );\n    }\n\n}// pearson_chisq_statistic\n}// contingency_table\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "f5255be4181c9f251d021e1787af119b0fe97557", "size": 2245, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/pearson_chisq/common/asy_distribution.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/pearson_chisq/common/asy_distribution.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "non_parametric/boost/statistics/detail/non_parametric/backup_once_in_trunk/non_parametric/contingency_table/pearson_chisq/common/asy_distribution.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8032786885, "max_line_length": 114, "alphanum_fraction": 0.6062360802, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4313120917843758}}
{"text": "//\n// Created by keszocze on 10.10.18.\n//\n\n#pragma once\n\n#include <vector>\n#include <cudd/cplusplus/cuddObj.hh>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace abo::error_metrics {\n\n    /**\n     * @brief Computes the error rate, i.e. the number of inputs for which f_hat differs from f\n     * The result is scaled to lie between 0 and 1\n     * The error rate is computed symbolically using BDDs\n     * @param mgr The BDD object manager\n     * @param f The original function\n     * @param f_hat The approximated function. Must have the same number of bits as f\n     * @return The computed error rate in the interval [0, 1]\n     */\n    double error_rate(const Cudd & mgr, const  std::vector<BDD>& f, const std::vector<BDD>& f_hat);\n    double error_rate(const Cudd & mgr, const BDD& f, const BDD& f_hat);\n\n    /**\n     * @brief Computes the error rate, i.e. the number of inputs for which f_hat differs from f\n     * The result is scaled to lie between 0 and 1\n     * The error rate is computed symbolically using ADDs\n     * The computation time will be significantly longer than the BDD variant\n     * @param mgr The BDD object manager\n     * @param f The original function\n     * @param f_hat The approximated function. Must have the same number of bits as f\n     * @return The computed error rate in the interval [0, 1]\n     */\n    double error_rate_add(const Cudd &mgr, const std::vector<BDD> &f, const std::vector<BDD> &f_hat);\n\n    /**\n     * @brief Approximates the error rate, i.e. the number of inputs for which f_hat differs from f\n     * The result is scaled to lie between 0 and 1\n     * The result is computed using sampling, no proper guarantee on the introduced error can be given\n     * @param mgr The BDD object manager\n     * @param f The original function\n     * @param f_hat The approximated function. Must have the same number of bits as f\n     * @param samples The number of samples to use\n     * @return The approximated error rate in the interval [0, 1]\n     */\n    double error_rate_sampling(const Cudd &mgr, const std::vector<BDD>& f, const std::vector<BDD>& f_hat, long samples = 10000);\n\n    /**\n     * @brief Approximates the error rate, i.e. the number of inputs for which f_hat differs from f\n     * The result is scaled to lie between 0 and 1\n     * The result is computed using an improved sampling method that offers faster convergence than\n     * the regular error rate, but still no proper guarantee on the introduced error can be given\n     * @param mgr The BDD object manager\n     * @param f The original function\n     * @param f_hat The approximated function. Must have the same number of bits as f\n     * @param samples The number of samples to use\n     * @return The approximated error rate in the interval [0, 1]\n     */\n    double error_rate_efficient_sampling(const Cudd &mgr, const std::vector<BDD>& f, const std::vector<BDD>& f_hat, long samples = 10000);\n}\n", "meta": {"hexsha": "8c095ff94fd27b9b590ae1c2a4755617c47b05d5", "size": 2911, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/error_metrics/error_rate.hpp", "max_stars_repo_name": "andreaswendler/abo", "max_stars_repo_head_hexsha": "d5d31e0714365960fb9c02a6a5b240c07ac3a738", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/error_metrics/error_rate.hpp", "max_issues_repo_name": "andreaswendler/abo", "max_issues_repo_head_hexsha": "d5d31e0714365960fb9c02a6a5b240c07ac3a738", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/error_metrics/error_rate.hpp", "max_forks_repo_name": "andreaswendler/abo", "max_forks_repo_head_hexsha": "d5d31e0714365960fb9c02a6a5b240c07ac3a738", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2063492063, "max_line_length": 138, "alphanum_fraction": 0.6952937135, "num_tokens": 745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.6548947290421275, "lm_q1q2_score": 0.43119415940600947}}
{"text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <Eigen/Core>\n\nstd::vector<Eigen::VectorXd> read_coordinates(std::string file_name) {\n  std::string s;\n  std::vector<Eigen::VectorXd> return_points;\n  std::ifstream scan_poses_file (file_name);\n  if (scan_poses_file.is_open())\n  {\n    while ( getline (scan_poses_file,s) )\n    {\n      Eigen::VectorXd pointPose(3);\n      int ind = 0;\n      // parse the string\n      std::string delimiter = \" \";\n      size_t pos = 0;\n      std::string token;\n      while ((pos = s.find(delimiter)) != std::string::npos) {\n          token = s.substr(0, pos);\n          pointPose(ind) =  std::stod(token);\n          s.erase(0, pos + delimiter.length());\n          ind += 1;\n      }\n      pointPose(ind) = std::stod(s);\n      return_points.push_back(pointPose);\n    }\n    scan_poses_file.close();\n  }\n  return return_points;\n\n}\n\nint main(void)\n{\n\n    std::vector<Eigen::VectorXd> img_1 = read_coordinates(\"/home/nehil/catkin_ws_registration/src/tracking_results/aruco_in_pos_2.txt\");\n    std::vector<Eigen::VectorXd> img_2 = read_coordinates(\"/home/nehil/catkin_ws_registration/src/tracking_results/aruco_in_pos_3.txt\");\n    std::cout << img_1.size() << std::endl;\n    std::cout << img_2.size() << std::endl;\n    double distance_x = 0;\n    double distance_y = 0;\n    double distance_z = 0;\n    double distance = 0;\n    for(unsigned int i = 0; i < img_1.size(); i++) {\n      distance_x += std::abs((img_2[i].x() - img_1[i].x()));\n      distance_y += std::abs((img_2[i].y() - img_1[i].y()));\n      distance_z += (img_2[i].z() - img_1[i].z());\n      auto point_dist = std::sqrt(std::pow(img_2[i].x() - img_1[i].x(), 2) + std::pow(img_2[i].y() - img_1[i].y(), 2) + std::pow(img_2[i].z() - img_1[i].z(), 2)) - 206.0f;\n      std::cout << i + 1 << \" : \" << point_dist << std::endl;\n      distance += point_dist;\n    }\n    //std::cout << \"Diff in x: \" << distance_x/img_1.size() << \"\\nDiff in y: \" << distance_y/img_1.size() << \"\\nDiff in z: \" << distance_z/img_1.size() << \"\\n\";\n    std::cout << \"Euclidean distance: \" << distance/img_1.size() << std::endl;\n    return 0;\n}\n", "meta": {"hexsha": "69d2ffb5c1f6022be06f034aa4c5c9c943f58bc3", "size": 2130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/test_checker_board.cpp", "max_stars_repo_name": "NehilDanis/shape_registration", "max_stars_repo_head_hexsha": "b328f6a4d4dd9f42cb8babe4f8c737b451f669ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/test_checker_board.cpp", "max_issues_repo_name": "NehilDanis/shape_registration", "max_issues_repo_head_hexsha": "b328f6a4d4dd9f42cb8babe4f8c737b451f669ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/test_checker_board.cpp", "max_forks_repo_name": "NehilDanis/shape_registration", "max_forks_repo_head_hexsha": "b328f6a4d4dd9f42cb8babe4f8c737b451f669ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-10-04T13:33:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T13:54:18.000Z", "avg_line_length": 36.1016949153, "max_line_length": 171, "alphanum_fraction": 0.5957746479, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.6513548646660543, "lm_q1q2_score": 0.43114669390666094}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include \"FHE.h\"\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n#include \"matmul.h\"\n#include <NTL/ZZ.h>\n#include <NTL/lzz_pXFactoring.h>\n#include <cassert>\n#include <cstdio>\n\nstatic bool noPrint = false;\n\nstatic MatMulBase*\nbuildSingleBlockMatrix(const EncryptedArray& ea, const vector<ZZX>& vec);\n\n\ntemplate<class type> class SingleBlockMatrix : public BlockMatMul<type> {\n  PA_INJECT(type) \n\n  Mat<R> data;\n\npublic:\n  SingleBlockMatrix(const EncryptedArray& _ea, const vector<ZZX>& vec) :\n    BlockMatMul<type>(_ea)\n  { \n    RBak bak; bak.save(); _ea.getAlMod().restoreContext();\n    long d = _ea.getDegree();\n\n    data.SetDims(d, d);\n    for (long i = 0; i < d; i++) \n      for (long j = 0; j < d; j++) \n         conv(data[i][j], coeff(vec[i], j));\n  }\n\n  virtual bool get(Mat<R>& out, long i, long j) const\n  {\n    assert(i >= 0 && i < this->getEA().size());\n    assert(j >= 0 && j < this->getEA().size());\n    if (i != j) return true;\n    out = data;\n    return false;\n  }\n};\n\nstatic MatMulBase*\nbuildSingleBlockMatrix(const EncryptedArray& ea, const vector<ZZX>& vec)\n{\n  switch (ea.getTag()) {\n    case PA_GF2_tag: {\n      return new SingleBlockMatrix<PA_GF2>(ea, vec);\n    }\n    case PA_zz_p_tag: {\n      return new SingleBlockMatrix<PA_zz_p>(ea, vec);\n    }\n    default: return nullptr;\n  }\n}\n\n\ntemplate<class type> class MultiBlockMatrix : public BlockMatMul<type> {\n  PA_INJECT(type) \n\n  Vec< Mat<R> > data;\n\npublic:\n  MultiBlockMatrix(const EncryptedArray& _ea, const vector<vector<ZZX> >& vec):\n    BlockMatMul<type>(_ea)\n  { \n    RBak bak; bak.save(); _ea.getAlMod().restoreContext();\n    long n = _ea.size();\n    long d = _ea.getDegree();\n\n    data.SetLength(n);\n    for (long k = 0; k < n; k++) {\n      data[k].SetDims(d, d);\n      for (long i = 0; i < d; i++) \n        for (long j = 0; j < d; j++) \n           conv(data[k][i][j], coeff(vec[k][i], j));\n    }\n  }\n\n  virtual bool get(Mat<R>& out, long i, long j) const {\n    assert(i >= 0 && i < this->getEA().size());\n    assert(j >= 0 && j < this->getEA().size());\n    if (i != j) return true;\n    out = data[i];\n    return false;\n  }\n};\n\nstatic MatMulBase* buildMultiBlockMatrix(const EncryptedArray& ea,\n\t\t\t\t\t const vector< vector<ZZX> >& vec)\n{\n  switch (ea.getTag()) {\n    case PA_GF2_tag: {\n      return new MultiBlockMatrix<PA_GF2>(ea, vec);\n    }\n    case PA_zz_p_tag: {\n      return new MultiBlockMatrix<PA_zz_p>(ea, vec);\n    }\n    default: return nullptr;\n  }\n}\n\n\n\nvoid  TestIt(long m, long p, long r, long d)\n{\n  if (!noPrint)\n    cout << \"\\n\\n******** TestIt\" << (isDryRun()? \"(dry run):\" : \":\")\n       << \" m=\" << m \n       << \", p=\" << p\n       << \", r=\" << r\n       << \", d=\" << d\n       << endl;\n\n  FHEcontext context(m, p, r);\n  buildModChain(context, /*L=*/3, /*c=*/2);\n\n  ZZX G;\n  if (d == 0) {\n    G = context.alMod.getFactorsOverZZ()[0];\n    d = deg(G);\n  }\n  else\n    G = makeIrredPoly(p, d);\n\n  if (!noPrint) {\n    context.zMStar.printout();\n    cout << endl;\n    cout << \"G = \" << G << \"\\n\";\n\n    cout << \"generating keys and key-switching matrices... \" << std::flush;\n  }\n  FHESecKey secretKey(context);\n  const FHEPubKey& publicKey = secretKey;\n  secretKey.GenSecKey(/*w=*/64);// A Hamming-weight-w secret key\n  addSome1DMatrices(secretKey); // compute key-switching matrices that we need\n  addFrbMatrices(secretKey); // compute key-switching matrices that we need\n  if (!noPrint) {\n    cout << \"done\\n\";\n    cout << \"computing masks and tables for rotation... \" << std::flush;\n  }\n  EncryptedArray ea(context, G);\n  if (!noPrint)\n    cout << \"done\\n\";\n\n  long nslots = ea.size();\n\n  NewPlaintextArray p0(ea);\n  NewPlaintextArray pp0(ea);\n\n  Ctxt c0(publicKey);\n\n  if (!noPrint)\n    cout << \"\\nTest #1: Apply the same linear transformation to all slots\\n\";\n  {\n  vector<ZZX> LM(d); // LM selects even coefficients\n  for (long j = 0; j < d; j++) \n    if (j % 2 == 0) LM[j] = ZZX(j, 1);\n\n  // \"building\" the linearized-polynomial coefficients\n  vector<ZZX> C;\n  ea.buildLinPolyCoeffs(C, LM);\n\n  random(ea, p0);  \n  ea.encrypt(c0, publicKey, p0);\n  applyLinPoly1(ea, c0, C);\n  ea.decrypt(c0, secretKey, pp0);\n\n  shared_ptr<MatMulBase> mat(buildSingleBlockMatrix(ea, LM));\n  NewPlaintextArray p1(p0);\n  blockMatMul(p1, *mat);\n  if (equals(ea, pp0, p1))\n    cout << \"GOOD\\n\";\n  else\n    cout << \"BAD\\n\";\n  }\n\n\n  if (!noPrint)\n    cout << \"\\nTest #2: Apply different transformations to the different slots\\n\";\n  {\n  vector< vector<ZZX> > LM(nslots); \n  // LM[i] rotates the coefficients in the i'th slot by (i % d)\n  for (long i = 0; i < nslots; i++) {\n    LM[i].resize(d);\n    for (long j = 0; j < d; j++)  {\n      long jj = (i+j) % d;\n      LM[i][j] = ZZX(jj, 1);\n    }\n  }\n\n  // \"building\" the linearized-polynomial coefficients\n  vector< vector<ZZX> > C(nslots);\n  for (long i = 0; i < nslots; i++)\n    ea.buildLinPolyCoeffs(C[i], LM[i]);\n\n  random(ea, p0);\n  ea.encrypt(c0, publicKey, p0);\n  applyLinPolyMany(ea, c0, C); // apply the linearized polynomials\n  ea.decrypt(c0, secretKey, pp0);\n\n  shared_ptr<MatMulBase> mat(buildMultiBlockMatrix(ea, LM));\n  NewPlaintextArray p1(p0);\n  blockMatMul(p1, *mat);\n  if (equals(ea, pp0, p1))\n    cout << \"GOOD\\n\";\n  else\n    cout << \"BAD\\n\";\n  }\n\n  if (!noPrint)\n    cout << \"\\nTest #3: Testing low-level (cached) implementation\\n\";\n  {\n  vector< vector<ZZX> > LM(nslots); \n  // LM[i] adds coefficients (i % d) and (i+1 % d) in the i'th slot\n  for (long i = 0; i < nslots; i++) {\n    LM[i].resize(d);\n    for (long j = 0; j < d; j++)  {\n      if ( j == (i % d) || j == ((i+1)%d) )\n\tLM[i][j] = conv<ZZX>(1L);\n    }\n  }\n\n  // \"building\" the linearized-polynomial coefficients\n  vector< vector<ZZX> > C(nslots);\n  for (long i = 0; i < nslots; i++)\n    ea.buildLinPolyCoeffs(C[i], LM[i]);\n\n  // \"encoding\" the linearized-polynomial coefficients\n  vector<ZZX> encodedC(d);\n  for (long j = 0; j < d; j++) {\n    vector<ZZX> v(nslots);\n    for (long i = 0; i < nslots; i++) v[i] = C[i][j];\n    ea.encode(encodedC[j], v);\n  }\n\n  random(ea, p0);  \n  ea.encrypt(c0, publicKey, p0);\n  applyLinPolyLL(c0, encodedC, ea.getDegree()); // apply linearized polynomials\n  ea.decrypt(c0, secretKey, pp0);\n\n  shared_ptr<MatMulBase> mat(buildMultiBlockMatrix(ea, LM));\n  NewPlaintextArray p1(p0);\n  blockMatMul(p1, *mat);\n  if (equals(ea, pp0, p1))\n    cout << \"GOOD\\n\";\n  else\n    cout << \"BAD\\n\";\n  }\n}\n\n\nint main(int argc, char *argv[]) \n{\n  ArgMapping amap;\n\n  bool dry = false;\n  amap.arg(\"dry\", dry, \"dry=1 for a dry-run\");\n\n  long m=91;\n  amap.arg(\"m\", m, \"use specified value as modulus\");\n\n  long p=2;\n  amap.arg(\"p\", p, \"plaintext base\");\n\n  long r=1;\n  amap.arg(\"r\", r,  \"lifting\");\n\n  long d=0;\n  amap.arg(\"d\", d, \"degree of the field extension\");\n  amap.note(\"d == 0 => factors[0] defines extension\");\n\n  amap.arg(\"noPrint\", noPrint, \"suppress printouts\");\n\n  amap.parse(argc, argv);\n\n  long repeat = 2;\n  setTimersOn();\n  setDryRun(dry);\n  for (long repeat_cnt = 0; repeat_cnt < repeat; repeat_cnt++) {\n    TestIt(m, p, r, d);\n  }\n\n}\n", "meta": {"hexsha": "c931e3ba0250ac3f963ef6adf75f39a8233a3087", "size": 7595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Test_LinPoly.cpp", "max_stars_repo_name": "bryongloden/HElib", "max_stars_repo_head_hexsha": "c13dff5ce752fb9fcec9ef81a8db1c0f146fff39", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-29T17:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T06:46:20.000Z", "max_issues_repo_path": "src/Test_LinPoly.cpp", "max_issues_repo_name": "bryongloden/HElib", "max_issues_repo_head_hexsha": "c13dff5ce752fb9fcec9ef81a8db1c0f146fff39", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-10-17T08:04:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-28T06:36:40.000Z", "max_forks_repo_path": "src/Test_LinPoly.cpp", "max_forks_repo_name": "bryongloden/HElib", "max_forks_repo_head_hexsha": "c13dff5ce752fb9fcec9ef81a8db1c0f146fff39", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-10-16T09:14:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-10T07:24:51.000Z", "avg_line_length": 25.5723905724, "max_line_length": 82, "alphanum_fraction": 0.6047399605, "num_tokens": 2443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.4311466849470576}}
{"text": "/*\n * This file belongs to the Galois project, a C++ library for exploiting parallelism.\n * The code is being released under the terms of the 3-Clause BSD License (a\n * copy is located in LICENSE.txt at the top-level directory).\n *\n * Copyright (C) 2018, The University of Texas at Austin. All rights reserved.\n * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS\n * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF\n * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF\n * DEALING OR USAGE OF TRADE.  NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH\n * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances\n * shall University be liable for incidental, special, indirect, direct or\n * consequential damages or loss of profits, interruption of business, or\n * related expenses which may arise from use of Software or Documentation,\n * including but not limited to those resulting from defects in Software and/or\n * Documentation, or loss or inaccuracy of data of any kind.\n */\n\n#include \"galois/Galois.h\"\n#include \"galois/Timer.h\"\n#include \"galois/Timer.h\"\n#include \"galois/graphs/Graph.h\"\n#include \"galois/graphs/LCGraph.h\"\n#include \"galois/Reduction.h\"\n#include \"galois/ParallelSTL.h\"\n#include \"galois/substrate/PaddedLock.h\"\n#include \"Lonestar/BoilerPlate.h\"\n\n#ifdef HAS_EIGEN\n#include <Eigen/Sparse>\n#endif\n\n#include <random>\n#include <iostream>\n#include <cassert>\n#include <algorithm>\n#include <fstream>\n#include <vector>\n\n/**           CONFIG           **/\n\nstatic const char* const name =\n    \"Stochastic Gradient Descent for Linear Support Vector Machines\";\nstatic const char* const desc = \"Implements a linear support vector machine \"\n                                \"using stochastic gradient descent\";\nstatic const char* const url = \"sgdsvm\";\n\nenum class UpdateType {\n  Wild,\n  WildOrig,\n  ReplicateByThread,\n  ReplicateBySocket,\n  Staleness\n};\n\nenum class AlgoType {\n  PrimalStochasticGradientDescent,\n  LeastSquares,\n  DualCoordinateDescentL1Loss,\n  DualCoordinateDescentL2Loss\n};\n\nnamespace cll = llvm::cl;\nstatic cll::opt<std::string> inputGraphFilename(cll::Positional,\n                                                cll::desc(\"<graph input file>\"),\n                                                cll::Required);\nstatic cll::opt<std::string> inputLabelFilename(cll::Positional,\n                                                cll::desc(\"<label input file>\"),\n                                                cll::Required);\nstatic cll::opt<double>\n    creg(\"creg\", cll::desc(\"the regularization parameter C\"), cll::init(1.0));\nstatic cll::opt<bool>\n    shuffleSamples(\"shuffle\", cll::desc(\"shuffle samples between iterations\"),\n                   cll::init(false));\nstatic cll::opt<unsigned> SEED(\"seed\", cll::desc(\"random seed\"),\n                               cll::init(~0U));\nstatic cll::opt<bool> printObjective(\"printObjective\",\n                                     cll::desc(\"print objective value\"),\n                                     cll::init(false));\nstatic cll::opt<bool> printAccuracy(\"printAccuracy\",\n                                    cll::desc(\"print accuracy value\"),\n                                    cll::init(true));\nstatic cll::opt<double>\n    fractionTraining(\"fractionTraining\",\n                     cll::desc(\"fraction of samples to use for training\"),\n                     cll::init(0.8));\nstatic cll::opt<size_t>\n    numberTraining(\"numberTraining\",\n                   cll::desc(\"number of samples to use for training\"),\n                   cll::init(0));\nstatic cll::opt<double> tol(\"tol\", cll::desc(\"convergence tolerance\"),\n                            cll::init(0.1));\nstatic cll::opt<unsigned>\n    maxIterations(\"maxIterations\", cll::desc(\"maximum number of iterations\"),\n                  cll::init(1000));\nstatic cll::opt<unsigned> fixedIterations(\n    \"fixedIterations\",\n    cll::desc(\"run specific number of iterations, ignoring convergence\"),\n    cll::init(0));\nstatic cll::opt<UpdateType> updateType(\n    \"update\", cll::desc(\"Update type:\"),\n    cll::values(clEnumValN(UpdateType::Wild, \"wild\",\n                           \"unsynchronized (default)\"),\n                clEnumValN(UpdateType::WildOrig, \"wildorig\", \"unsynchronized\"),\n                clEnumValN(UpdateType::ReplicateByThread, \"replicateByThread\",\n                           \"thread replication\"),\n                clEnumValN(UpdateType::ReplicateBySocket, \"replicateBySocket\",\n                           \"socket replication\"),\n                clEnumValN(UpdateType::Staleness, \"staleness\", \"stale reads\"),\n                clEnumValEnd),\n    cll::init(UpdateType::Wild));\nstatic cll::opt<AlgoType> algoType(\n    \"algo\", cll::desc(\"Algorithm:\"),\n    cll::values(\n        clEnumValN(AlgoType::PrimalStochasticGradientDescent, \"psgd\",\n                   \"primal stochastic gradient descent (default)\"),\n        clEnumValN(AlgoType::DualCoordinateDescentL1Loss, \"dcdl1\",\n                   \"Dual coordinate descent L1 loss\"),\n        clEnumValN(AlgoType::DualCoordinateDescentL2Loss, \"dcdl2\",\n                   \"Dual coordinate descent L2 loss\"),\n#ifdef HAS_EIGEN\n        clEnumValN(AlgoType::LeastSquares, \"ls\",\n                   \"minimize l2 norm of residual as least squares problem\"),\n#endif\n        clEnumValEnd),\n    cll::init(AlgoType::PrimalStochasticGradientDescent));\n\n/**          DATA TYPES        **/\n\ntypedef struct Node {\n  double w;  // weight - relevant for variable nodes\n  int field; // variable nodes - variable count, sample nodes - label\n  Node() : w(0.0), field(0) {}\n} Node;\n\nusing Graph =\n    galois::graphs::LC_CSR_Graph<Node,\n                                 double>::with_out_of_line_lockable<true>::type;\nusing GNode = Graph::GraphNode;\n\n/**         CONSTANTS AND PARAMETERS       **/\nunsigned NUM_SAMPLES   = 0;\nunsigned NUM_VARIABLES = 0;\n\nunsigned variableNodeToId(GNode variable_node) {\n  return ((unsigned)variable_node) - NUM_SAMPLES;\n}\n\n// undef to test specialization for dense feature space\n//#define DENSE\n//#define DENSE_NUM_FEATURES 500\n\ntemplate <typename T, UpdateType UT>\nclass DiffractedCollection {\n  galois::substrate::PerThreadStorage<T*> thread;\n  galois::substrate::PerSocketStorage<T*> socket;\n  galois::LargeArray<T> old;\n  size_t size;\n  unsigned num_threads;\n  unsigned num_sockets;\n\n  template <typename GetFn>\n  void doMerge(const GetFn& getFn) {\n    bool byThread =\n        UT == UpdateType::ReplicateByThread || UT == UpdateType::Staleness;\n    double* local = byThread ? *thread.getLocal() : *socket.getLocal();\n    galois::do_all(boost::counting_iterator<unsigned>(0),\n                   boost::counting_iterator<unsigned>(size), [&](unsigned i) {\n                     unsigned n = byThread ? num_threads : num_sockets;\n                     for (unsigned j = 1; j < n; j++) {\n                       double o = byThread ? (*thread.getRemote(j))[i]\n                                           : (*socket.getRemoteByPkg(j))[i];\n                       local[i] += o;\n                     }\n                     local[i] /= n;\n                     auto& v = getFn(i);\n                     if (UT == UpdateType::Staleness)\n                       v = (old[i] = local[i]);\n                     else\n                       v = local[i];\n                   });\n    galois::on_each([&](unsigned tid, unsigned total) {\n      switch (UT) {\n      case UpdateType::Staleness:\n      case UpdateType::ReplicateByThread:\n        if (tid)\n          std::copy(local, local + size, *thread.getLocal());\n        break;\n      case UpdateType::ReplicateBySocket:\n        if (tid && galois::substrate::getThreadPool().isLeader(tid))\n          std::copy(local, local + size, *socket.getLocal());\n        break;\n      default:\n        abort();\n      }\n    });\n  }\n\npublic:\n  DiffractedCollection(size_t n) : size(n) {\n    num_threads = galois::getActiveThreads();\n    num_sockets = galois::substrate::getThreadPool().getCumulativeMaxSocket(\n                      num_threads - 1) +\n                  1;\n\n    if (UT == UpdateType::Staleness)\n      old.create(n);\n    switch (UT) {\n    case UpdateType::ReplicateByThread:\n    case UpdateType::Staleness:\n      galois::on_each([n, this](unsigned tid, unsigned total) {\n        T* p               = new T[n];\n        *thread.getLocal() = p;\n        std::fill(p, p + n, 0);\n      });\n    case UpdateType::ReplicateBySocket:\n      galois::on_each([n, this](unsigned tid, unsigned total) {\n        if (galois::substrate::getThreadPool().isLeader(tid)) {\n          T* p               = new T[n];\n          *socket.getLocal() = p;\n          std::fill(p, p + n, 0);\n        }\n      });\n    case UpdateType::Wild:\n    case UpdateType::WildOrig:\n      break;\n    default:\n      abort();\n    }\n  }\n\n  struct Accessor {\n    T* rptr;\n    T* wptr;\n    T* bptr;\n\n    Accessor(T* p) : rptr(p), wptr(p), bptr(nullptr) {}\n    Accessor(T* p1, T* p2) : rptr(p1), wptr(p2), bptr(nullptr) {}\n    Accessor(T* p1, T* p2, T* p3) : rptr(p1), wptr(p2), bptr(p3) {}\n\n    T& read(T& addr, ptrdiff_t x) {\n      switch (UT) {\n      case UpdateType::WildOrig:\n      case UpdateType::Wild:\n        return addr;\n      default:\n        return rptr[x];\n      }\n    }\n    T& write(T& addr, ptrdiff_t x) {\n      switch (UT) {\n      case UpdateType::WildOrig:\n      case UpdateType::Wild:\n        return addr;\n      default:\n        return wptr[x];\n      }\n    }\n    void writeBig(T& addr, const T& value) {\n      if (!bptr)\n        return;\n      assert(rptr == wptr);\n      bptr[std::distance(wptr, &addr)] = value;\n    }\n  };\n\n  Accessor get() {\n    if (num_sockets > 1 && UT == UpdateType::ReplicateBySocket) {\n      unsigned tid       = galois::substrate::ThreadPool::getTID();\n      unsigned my_socket = galois::substrate::ThreadPool::getSocket();\n      unsigned next      = (my_socket + 1) % num_sockets;\n      return Accessor{*socket.getLocal(), *socket.getLocal(),\n                      *socket.getRemoteByPkg(next)};\n    }\n\n    switch (UT) {\n    case UpdateType::Wild:\n    case UpdateType::WildOrig:\n    case UpdateType::Staleness:\n      return Accessor{&old[0], *thread.getLocal()};\n    case UpdateType::ReplicateBySocket:\n      return Accessor{*socket.getLocal()};\n    case UpdateType::ReplicateByThread:\n      return Accessor{*thread.getLocal()};\n    default:\n      abort();\n    }\n  }\n\n  template <typename GetFn>\n  void merge(const GetFn& getFn) {\n    switch (UT) {\n    case UpdateType::Wild:\n    case UpdateType::WildOrig:\n      return;\n    case UpdateType::Staleness:\n    case UpdateType::ReplicateBySocket:\n    case UpdateType::ReplicateByThread:\n      return doMerge(getFn);\n    default:\n      abort();\n    }\n  }\n};\n\ntemplate <UpdateType UT>\nstruct LinearSVM {\n  typedef int tt_needs_per_iter_alloc;\n  typedef int tt_does_not_need_aborts;\n\n  Graph& g;\n  DiffractedCollection<double, UT>& dstate;\n  galois::GAccumulator<size_t>& bigUpdates;\n  double learningRate;\n\n#ifdef DENSE\n  Node* baseNodeData;\n  ptrdiff_t edgeOffset;\n  double* baseEdgeData;\n#endif\n\n  LinearSVM(Graph& _g, DiffractedCollection<double, UT>& d, double _lr,\n            galois::GAccumulator<size_t>& b)\n      : g(_g), dstate(d), bigUpdates(b), learningRate(_lr) {\n#ifdef DENSE\n    baseNodeData = &g.getData(g.getEdgeDst(g.edge_begin(0)));\n    edgeOffset   = std::distance(&g.getData(NUM_SAMPLES), baseNodeData);\n    baseEdgeData = &g.getEdgeData(g.edge_begin(0));\n#endif\n  }\n\n  void operator()(GNode n, galois::UserContext<GNode>& ctx) {\n    galois::PerIterAllocTy& alloc = ctx.getPerIterAlloc();\n\n    // Store edge data in iteration-local temporary to reduce cache misses\n#ifdef DENSE\n    const ptrdiff_t size = DENSE_NUM_FEATURES;\n#else\n    ptrdiff_t size =\n        std::distance(g.edge_begin(n, galois::MethodFlag::UNPROTECTED),\n                      g.edge_end(n, galois::MethodFlag::UNPROTECTED));\n#endif\n    // regularized factors\n    double* rfactors = (double*)alloc.allocate(sizeof(double) * size);\n    // document weights\n    double* dweights = (double*)alloc.allocate(sizeof(double) * size);\n    // model weights\n    double* mweights = (double*)alloc.allocate(sizeof(double) * size);\n    // write destinations\n    double** wptrs = (double**)alloc.allocate(sizeof(double*) * size);\n\n    // Gather\n    size_t cur = 0;\n    double dot = 0.0;\n    auto d     = dstate.get();\n#ifdef DENSE\n    double* myEdgeData = &baseEdgeData[size * n];\n    for (cur = 0; cur < size;) {\n      int varCount = baseNodeData[cur].field;\n#else\n    for (auto edge_it : g.out_edges(n)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& var_data      = g.getData(variable_node);\n      int varCount        = var_data.field;\n#endif\n\n      double weight;\n#ifdef DENSE\n      weight = d.read(baseNodeData[cur].w, cur + edgeOffset);\n#else\n      wptrs[cur]    = &d.write(var_data.w, variableNodeToId(variable_node));\n      weight        = d.read(var_data.w, variableNodeToId(variable_node));\n#endif\n      mweights[cur] = weight;\n#ifdef DENSE\n      dweights[cur] = myEdgeData[cur];\n#else\n      dweights[cur] = g.getEdgeData(edge_it);\n#endif\n      if (UT == UpdateType::WildOrig) {\n        rfactors[cur] = (creg * varCount);\n      } else {\n        rfactors[cur] = mweights[cur] / (creg * varCount);\n      }\n      dot += mweights[cur] * dweights[cur];\n      cur += 1;\n    }\n\n    Node& sample_data = g.getData(n);\n    int label         = sample_data.field;\n\n    bool bigUpdate = label * dot < 1;\n    if (bigUpdate)\n      bigUpdates += size;\n    for (cur = 0; cur < size; ++cur) {\n      double delta;\n      if (UT == UpdateType::WildOrig) {\n        if (bigUpdate)\n          delta = learningRate *\n                  (*wptrs[cur] / rfactors[cur] - label * dweights[cur]);\n        else\n          delta = *wptrs[cur] / rfactors[cur];\n      } else {\n        if (bigUpdate)\n          delta = learningRate * (rfactors[cur] - label * dweights[cur]);\n        else\n          delta = rfactors[cur];\n      }\n#ifdef DENSE\n      d.write(baseNodeData[cur].w, cur + edgeOffset) = mweights[cur] - delta;\n#else\n      if (UT == UpdateType::WildOrig) {\n        double v    = *wptrs[cur] - delta;\n        *wptrs[cur] = v;\n        if (bigUpdate)\n          d.writeBig(*wptrs[cur], v);\n      } else {\n        double v    = mweights[cur] - delta;\n        *wptrs[cur] = v;\n        if (bigUpdate)\n          d.writeBig(*wptrs[cur], v);\n      }\n#endif\n    }\n  }\n};\n\nvoid printParameters(const std::vector<GNode>& trainingSamples,\n                     const std::vector<GNode>& testingSamples) {\n  std::cout << \"Input graph file: \" << inputGraphFilename << \"\\n\";\n  std::cout << \"Input label file: \" << inputLabelFilename << \"\\n\";\n  std::cout << \"Threads: \" << galois::getActiveThreads() << \"\\n\";\n  std::cout << \"Samples: \" << NUM_SAMPLES << \"\\n\";\n  std::cout << \"Variables: \" << NUM_VARIABLES << \"\\n\";\n  std::cout << \"Training samples: \" << trainingSamples.size() << \"\\n\";\n  std::cout << \"Testing samples: \" << testingSamples.size() << \"\\n\";\n  std::cout << \"Algo type: \";\n  switch (algoType) {\n  case AlgoType::PrimalStochasticGradientDescent:\n    std::cout << \"primal stochastic gradient descent\";\n    break;\n  case AlgoType::DualCoordinateDescentL1Loss:\n    std::cout << \"dual coordinate descent L1 Loss\";\n    break;\n  case AlgoType::DualCoordinateDescentL2Loss:\n    std::cout << \"dual coordinate descent L2 Loss\";\n    break;\n  case AlgoType::LeastSquares:\n    std::cout << \"least squares\";\n    break;\n  default:\n    abort();\n  }\n  std::cout << \"\\n\";\n\n  std::cout << \"Update type: \";\n  switch (updateType) {\n  case UpdateType::Wild:\n    std::cout << \"wild\";\n    break;\n  case UpdateType::WildOrig:\n    std::cout << \"wild orig\";\n    break;\n  case UpdateType::ReplicateByThread:\n    std::cout << \"replicate by thread\";\n    break;\n  case UpdateType::ReplicateBySocket:\n    std::cout << \"replicate by socket\";\n    break;\n  case UpdateType::Staleness:\n    std::cout << \"stale reads\";\n    break;\n  default:\n    abort();\n  }\n  std::cout << \"\\n\";\n}\n\nvoid initializeVariableCounts(Graph& g) {\n  for (auto n : g) {\n    for (auto edge_it : g.out_edges(n)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& data          = g.getData(variable_node);\n      data.field++; // increase count of variable occurrences\n    }\n  }\n}\n\nunsigned loadLabels(Graph& g, std::string filename) {\n  std::ifstream infile(filename);\n\n  unsigned sample_id;\n  int label;\n  int num_labels = 0;\n  while (infile >> sample_id >> label) {\n    g.getData(sample_id).field = label;\n    ++num_labels;\n  }\n\n  return num_labels;\n}\n\nsize_t getNumCorrect(Graph& g, std::vector<GNode>& testing_samples) {\n  galois::GAccumulator<size_t> correct;\n\n  galois::do_all(testing_samples.begin(), testing_samples.end(), [&](GNode n) {\n    double sum = 0.0;\n    Node& data = g.getData(n);\n    int label  = data.field;\n    for (auto edge_it : g.out_edges(n)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& data          = g.getData(variable_node);\n      double weight       = g.getEdgeData(edge_it);\n      sum += data.w * weight;\n    }\n\n    if (sum <= 0.0 && label == -1) {\n      correct += 1;\n    } else if (sum > 0.0 && label == 1) {\n      correct += 1;\n    }\n  });\n\n  return correct.reduce();\n}\n\ndouble getPrimalObjective(Graph& g, const std::vector<GNode>& trainingSamples) {\n  // 0.5 * w^Tw + C * sum_i [max(0, 1 - y_i * w^T * x_i)]^2\n  galois::GAccumulator<double> objective;\n\n  galois::do_all(trainingSamples.begin(), trainingSamples.end(), [&](GNode n) {\n    double sum = 0.0;\n    Node& data = g.getData(n);\n    int label  = data.field;\n    for (auto edge_it : g.out_edges(n)) {\n      GNode variable_node = g.getEdgeDst(edge_it);\n      Node& data          = g.getData(variable_node);\n      double weight       = g.getEdgeData(edge_it);\n      sum += data.w * weight;\n    }\n\n    double o = std::max(0.0, 1 - label * sum);\n    objective += o * o;\n  });\n\n  galois::GAccumulator<double> norm;\n  galois::do_all(boost::counting_iterator<size_t>(0),\n                 boost::counting_iterator<size_t>(NUM_VARIABLES),\n                 [&](size_t i) {\n                   double v = g.getData(i + NUM_SAMPLES).w;\n                   norm += v * v;\n                 });\n  return objective.reduce() * creg + 0.5 * norm.reduce();\n}\n\ntemplate <UpdateType UT>\nvoid runPrimalSgd(Graph& g, std::mt19937& gen,\n                  std::vector<GNode>& trainingSamples,\n                  std::vector<GNode>& testingSamples) {\n  galois::TimeAccumulator accumTimer;\n  accumTimer.start();\n\n  DiffractedCollection<double, UT> dstate(NUM_VARIABLES);\n\n  galois::StatTimer sgdTime(\"SgdTime\");\n\n  unsigned iterations = maxIterations;\n  double minObj       = std::numeric_limits<double>::max();\n  if (fixedIterations)\n    iterations = fixedIterations;\n\n  for (unsigned iter = 1; iter <= iterations; ++iter) {\n    sgdTime.start();\n\n    // include shuffling time in the time taken per iteration\n    // also: not parallel\n    if (shuffleSamples)\n      std::shuffle(trainingSamples.begin(), trainingSamples.end(), gen);\n\n    double learning_rate = 30 / (100.0 + iter);\n    auto ts_begin        = trainingSamples.begin();\n    auto ts_end          = trainingSamples.end();\n    auto ln              = galois::loopname(\"LinearSVM\");\n    auto wl = galois::wl<galois::worklists::PerSocketChunkFIFO<32>>();\n    galois::GAccumulator<size_t> bigUpdates;\n\n    galois::Timer flopTimer;\n    flopTimer.start();\n\n    galois::for_each(ts_begin, ts_end,\n                     LinearSVM<UT>(g, dstate, learning_rate, bigUpdates), ln,\n                     wl);\n\n    flopTimer.stop();\n    sgdTime.stop();\n\n    size_t numBigUpdates = bigUpdates.reduce();\n    double flop   = 4 * g.sizeEdges() + 2 + 3 * numBigUpdates + g.sizeEdges();\n    size_t millis = flopTimer.get();\n    double gflops = 0;\n    if (millis)\n      gflops = flop / millis / 1e6;\n\n    dstate.merge(\n        [&g](ptrdiff_t x) -> double& { return g.getData(x + NUM_SAMPLES).w; });\n\n    accumTimer.stop();\n    std::cout << iter << \" GFLOP/s \" << gflops << \" \"\n              << \"(\" << millis / 1e3 << \" s)\"\n              << \" AccumTime \" << accumTimer.get() / 1e3;\n    accumTimer.start();\n    if (printAccuracy) {\n      std::cout << \" Accuracy: \"\n                << getNumCorrect(g, testingSamples) /\n                       (double)testingSamples.size();\n    }\n    double obj = 0;\n    if (!fixedIterations) {\n      obj = getPrimalObjective(g, trainingSamples);\n    }\n    if (printObjective) {\n      std::cout << \" Obj: \" << obj;\n    }\n    std::cout << \"\\n\";\n    if (!fixedIterations) {\n      if (std::fabs((obj - minObj) / minObj) < tol) {\n        std::cout << \"Converged in \" << iter << \" iterations.\\n\";\n        return;\n      }\n      minObj = std::min(obj, minObj);\n    }\n  }\n\n  if (!fixedIterations)\n    std::cout << \"Failed to converge\\n\";\n}\n\ndouble getDualObjective(Graph& g, const std::vector<GNode>& trainingSamples,\n                        double* diag, const std::vector<double>& alpha) {\n  // 0.5 * w^Tw + C * sum_i [max(0, 1 - y_i * w^T * x_i)]^2\n  galois::GAccumulator<double> objective;\n\n  galois::do_all(trainingSamples.begin(), trainingSamples.end(), [&](GNode n) {\n    // Node& data = g.getData(n);\n    int label = g.getData(n).field;\n    objective += alpha[n] * (alpha[n] * diag[label + 1] - 2);\n  });\n\n  galois::do_all(boost::counting_iterator<size_t>(0),\n                 boost::counting_iterator<size_t>(NUM_VARIABLES),\n                 [&](size_t i) {\n                   double v = g.getData(i + NUM_SAMPLES).w;\n                   objective += v * v;\n                 });\n  return objective.reduce();\n}\n\n// TODO(ddn): Parallelize\n// See Algorithm 3 of Hsieh et al., ICML 2008\nvoid runDualCoordinateDescent(Graph& g, std::mt19937& gen,\n                              std::vector<GNode>& trainingSamples,\n                              std::vector<GNode>& testingSamples,\n                              bool useL1Loss) {\n  galois::TimeAccumulator accumTimer;\n  accumTimer.start();\n\n  std::vector<double> alpha(NUM_SAMPLES);\n  std::vector<double> QD(NUM_SAMPLES);\n\n  double diag[] = {0.5 / creg, 0, 0.5 / creg};\n  double ub[]   = {std::numeric_limits<double>::max(), 0,\n                 std::numeric_limits<double>::max()};\n  if (useL1Loss) {\n    diag[0] = 0;\n    diag[2] = 0;\n    ub[0]   = creg;\n    ub[2]   = creg;\n  }\n\n  for (auto ii = g.begin(), ei = g.begin() + NUM_SAMPLES; ii != ei; ++ii) {\n    int& label = g.getData(*ii).field;\n    if (label != 1 && label != -1) {\n      label = label <= 0 ? -1 : 1;\n    }\n\n    QD[*ii] = diag[label + 1];\n    for (auto edge : g.out_edges(*ii)) {\n      double val = g.getEdgeData(edge);\n      QD[*ii] += val * val;\n    }\n  }\n\n  galois::StatTimer cdTime(\"CDTime\");\n  double maxPG              = std::numeric_limits<double>::max();\n  double minPG              = std::numeric_limits<double>::lowest();\n  std::vector<GNode> active = trainingSamples;\n  std::vector<GNode> activeNew;\n  unsigned iter;\n  for (iter = 1; iter <= maxIterations; ++iter) {\n    cdTime.start();\n\n    double maxPGNew = std::numeric_limits<double>::lowest();\n    double minPGNew = std::numeric_limits<double>::max();\n    if (iter != 1 && shuffleSamples) {\n      std::shuffle(active.begin(), active.end(), gen);\n    }\n\n    galois::Timer flopTimer;\n    flopTimer.start();\n    size_t flop = 0;\n    for (GNode n : active) {\n      double G  = 0;\n      int label = g.getData(n).field;\n      flop += 2 * std::distance(g.edge_begin(n), g.edge_end(n));\n      for (auto edge : g.out_edges(n)) {\n        G += g.getData(g.getEdgeDst(edge)).w * g.getEdgeData(edge);\n      }\n      G = G * label - 1;\n      G += alpha[n] * diag[label + 1];\n      flop += 3;\n\n      double C  = ub[label + 1];\n      double PG = 0;\n      if (alpha[n] == 0) {\n        if (G > maxPG) {\n          continue;\n        } else if (G < 0) {\n          PG = G;\n        }\n      } else if (alpha[n] == C) {\n        if (G < minPG) {\n          continue;\n        } else if (G > 0) {\n          PG = G;\n        }\n      } else {\n        PG = G;\n      }\n      maxPGNew = std::max(maxPGNew, PG);\n      minPGNew = std::min(minPGNew, PG);\n\n      if (std::fabs(PG) > 1.0e-12) {\n        double a = alpha[n];\n        alpha[n] = std::min(std::max(alpha[n] - G / QD[n], 0.0), C);\n        double d = (alpha[n] - a) * label;\n        flop += 3;\n        flop += 2 * std::distance(g.edge_begin(n), g.edge_end(n));\n        for (auto edge : g.out_edges(n)) {\n          double& w = g.getData(g.getEdgeDst(edge)).w;\n          w += d * g.getEdgeData(edge);\n        }\n      }\n      activeNew.push_back(n);\n    }\n    flopTimer.stop();\n    cdTime.stop();\n\n    accumTimer.stop();\n    size_t millis = flopTimer.get();\n    double gflops = 0;\n    if (millis)\n      gflops = flop / millis / 1e6;\n    std::cout << iter << \" GFLOP/s \" << gflops << \" \"\n              << \"(\" << millis / 1e3 << \" s)\"\n              << \" AccumTime \" << accumTimer.get() / 1e3 << \" ActiveSet \"\n              << active.size();\n    accumTimer.start();\n    if (printAccuracy) {\n      double accuracy =\n          getNumCorrect(g, testingSamples) / (double)testingSamples.size();\n      std::cout << \" Accuracy: \" << accuracy;\n    }\n    if (printObjective) {\n      std::cout << \" Obj: \"\n                << getDualObjective(g, trainingSamples, diag, alpha);\n    }\n    std::cout << \"\\n\";\n\n    active.clear();\n    std::swap(active, activeNew);\n\n    if (maxPGNew - minPGNew <= tol) {\n      if (active.size() == trainingSamples.size()) {\n        std::cout << \"Converged in \" << iter << \" iterations\\n\";\n        return;\n      } else {\n        active = trainingSamples;\n        maxPG  = std::numeric_limits<double>::max();\n        minPG  = std::numeric_limits<double>::lowest();\n      }\n    } else {\n      maxPG = maxPGNew;\n      minPG = minPGNew;\n      if (maxPG <= 0)\n        maxPG = std::numeric_limits<double>::max();\n      if (minPG >= 0)\n        minPG = std::numeric_limits<double>::lowest();\n    }\n  }\n\n  std::cout << \"Failed to converge\\n\";\n}\n\n#ifdef HAS_EIGEN\nvoid runLeastSquares(Graph& g, std::mt19937& gen,\n                     std::vector<GNode>& trainingSamples,\n                     std::vector<GNode>& testingSamples) {\n  Eigen::SparseMatrix<double> A(NUM_SAMPLES, NUM_VARIABLES);\n  {\n    typedef Eigen::Triplet<double> Triplet;\n    std::vector<Triplet> triplets{g.sizeEdges()};\n    {\n      auto it = triplets.begin();\n      for (auto n : g) {\n        for (auto edge : g.out_edges(n)) {\n          *it++ =\n              Triplet(n, g.getEdgeDst(edge) - NUM_SAMPLES, g.getEdgeData(edge));\n        }\n      }\n    }\n    A.setFromTriplets(triplets.begin(), triplets.end());\n  }\n\n  Eigen::VectorXd b(NUM_SAMPLES);\n  size_t cur = 0;\n  for (auto ii = g.begin(), ei = g.begin() + NUM_SAMPLES; ii != ei; ++ii) {\n    b(cur++) = g.getData(*ii).field;\n  }\n\n  // Least-squares problem: minimize ||Ax - b||_2\n  // normal equation: A^T A x = A^T b\n  Eigen::VectorXd x;\n  // Cholesky is almost always faster but QR is more numerically stable\n  if (g.sizeEdges() > 10000) {\n    // Solve normal equation directly with Cholesky\n    Eigen::SparseMatrix<double> AT  = A.transpose();\n    Eigen::SparseMatrix<double> ATA = AT * A;\n    for (int i = 0; i < ATA.rows(); ++i)\n      ATA.coeffRef(i, i) += creg;\n    Eigen::VectorXd ATb = AT * b;\n    Eigen::ConjugateGradient<Eigen::SparseMatrix<double>> solver;\n    solver.compute(ATA);\n    x = solver.solve(ATb);\n    std::cout << \"cg iterations: \" << solver.iterations() << \"\\n\";\n    std::cout << \"cg est error: \" << solver.error() << \"\\n\";\n  } else {\n    // TODO add L2 regularizer\n    // Decompose normal equation\n    // A = QR\n    // A^T A x = A^T b\n    // R^T Q^T Q R x = R^T Q^T b => ... => R x = Q^T b\n    Eigen::SparseQR<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>>\n        solver;\n    solver.compute(A);\n    if (solver.info() != Eigen::Success) {\n      GALOIS_DIE(\"factorization failed\");\n    }\n    Eigen::VectorXd QTb = solver.matrixQ().transpose() * b;\n    int r               = solver.rank();\n    Eigen::VectorXd out;\n    out.resize(A.cols());\n    out.topRows(r) = solver.matrixR()\n                         .topLeftCorner(r, r)\n                         .triangularView<Eigen::Upper>()\n                         .solve(QTb.topRows(r));\n    out.bottomRows(out.rows() - r).setZero();\n    x = solver.colsPermutation() * out;\n  }\n\n  // Verify\n  {\n    for (size_t i = 0; i < NUM_VARIABLES; ++i) {\n      g.getData(i + NUM_SAMPLES).w = x(i);\n    }\n    std::vector<GNode> allSamples(g.begin(), g.begin() + NUM_SAMPLES);\n    size_t n = getNumCorrect(g, allSamples);\n    std::cout << \"All: \" << n / (double)NUM_SAMPLES << \" (\" << n << \"/\"\n              << NUM_SAMPLES << \")\\n\";\n    n = getNumCorrect(g, testingSamples);\n    std::cout << \"Testing: \" << n / (double)testingSamples.size() << \" (\" << n\n              << \"/\" << testingSamples.size() << \")\\n\";\n  }\n}\n#endif\n\nint main(int argc, char** argv) {\n  LonestarStart(argc, argv, name, desc, url);\n  galois::StatManager statManager;\n\n  Graph g;\n  galois::graphs::readGraph(g, inputGraphFilename);\n  NUM_SAMPLES = loadLabels(g, inputLabelFilename);\n  initializeVariableCounts(g);\n  NUM_VARIABLES = g.size() - NUM_SAMPLES;\n  assert(NUM_SAMPLES > 0 && NUM_VARIABLES > 0);\n\n  // put samples in a list and shuffle them\n  std::random_device rd;\n  std::mt19937 gen(SEED == ~0U ? rd() : SEED);\n\n  std::vector<GNode> allSamples(g.begin(), g.begin() + NUM_SAMPLES);\n  std::shuffle(allSamples.begin(), allSamples.end(), gen);\n\n  // copy a fraction of the samples to the training samples list\n  unsigned numTraining = numberTraining;\n  if (numTraining == 0 || numTraining >= NUM_SAMPLES)\n    numTraining = std::min(\n        static_cast<unsigned>(NUM_SAMPLES * fractionTraining), NUM_SAMPLES);\n  std::vector<GNode> trainingSamples(allSamples.begin(),\n                                     allSamples.begin() + numTraining);\n  // the remainder of samples go into the testing samples list\n  std::vector<GNode> testingSamples(allSamples.begin() + numTraining,\n                                    allSamples.end());\n\n  printParameters(trainingSamples, testingSamples);\n  if (printAccuracy) {\n    std::cout << \"Initial\";\n    if (printAccuracy) {\n      std::cout << \" Accuracy: \"\n                << getNumCorrect(g, testingSamples) /\n                       (double)testingSamples.size();\n    }\n    std::cout << \"\\n\";\n  }\n\n  galois::StatTimer timer;\n  timer.start();\n  switch (algoType) {\n  case AlgoType::PrimalStochasticGradientDescent:\n    switch (updateType) {\n    case UpdateType::Wild:\n      runPrimalSgd<UpdateType::Wild>(g, gen, trainingSamples, testingSamples);\n      break;\n    case UpdateType::WildOrig:\n      runPrimalSgd<UpdateType::WildOrig>(g, gen, trainingSamples,\n                                         testingSamples);\n      break;\n    case UpdateType::ReplicateBySocket:\n      runPrimalSgd<UpdateType::ReplicateBySocket>(g, gen, trainingSamples,\n                                                  testingSamples);\n      break;\n    case UpdateType::ReplicateByThread:\n      runPrimalSgd<UpdateType::ReplicateByThread>(g, gen, trainingSamples,\n                                                  testingSamples);\n      break;\n    case UpdateType::Staleness:\n      runPrimalSgd<UpdateType::Staleness>(g, gen, trainingSamples,\n                                          testingSamples);\n      break;\n    default:\n      abort();\n    }\n    break;\n  case AlgoType::DualCoordinateDescentL1Loss:\n    runDualCoordinateDescent(g, gen, trainingSamples, testingSamples, true);\n    break;\n  case AlgoType::DualCoordinateDescentL2Loss:\n    runDualCoordinateDescent(g, gen, trainingSamples, testingSamples, false);\n    break;\n#ifdef HAS_EIGEN\n  case AlgoType::LeastSquares:\n    runLeastSquares(g, gen, trainingSamples, testingSamples);\n    break;\n#endif\n  default:\n    abort();\n  }\n  timer.stop();\n\n  return 0;\n}\n", "meta": {"hexsha": "ba026eec0e468bacba2415c57bd3c5bc27e52157", "size": 31734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/experimental/svm/svm.cpp", "max_stars_repo_name": "rohankadekodi/compilers_project", "max_stars_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lonestar/experimental/svm/svm.cpp", "max_issues_repo_name": "rohankadekodi/compilers_project", "max_issues_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-02-27T19:24:51.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T21:04:28.000Z", "max_forks_repo_path": "lonestar/experimental/svm/svm.cpp", "max_forks_repo_name": "rohankadekodi/compilers_project", "max_forks_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-17T22:00:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-24T10:18:02.000Z", "avg_line_length": 32.6145940391, "max_line_length": 85, "alphanum_fraction": 0.5849246865, "num_tokens": 8427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6513548511303336, "lm_q1q2_score": 0.4311466762590353}}
{"text": "/**********************************************************************\r\n*  Copyright (c) 2008-2015, Alliance for Sustainable Energy.  \r\n*  All rights reserved.\r\n*  \r\n*  This library is free software; you can redistribute it and/or\r\n*  modify it under the terms of the GNU Lesser General Public\r\n*  License as published by the Free Software Foundation; either\r\n*  version 2.1 of the License, or (at your option) any later version.\r\n*  \r\n*  This library is distributed in the hope that it will be useful,\r\n*  but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n*  Lesser General Public License for more details.\r\n*  \r\n*  You should have received a copy of the GNU Lesser General Public\r\n*  License along with this library; if not, write to the Free Software\r\n*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\r\n**********************************************************************/\r\n\r\n#ifndef UTILITIES_DATA_VECTOR_HPP\r\n#define UTILITIES_DATA_VECTOR_HPP\r\n\r\n#include \"../UtilitiesAPI.hpp\"\r\n\r\n#include <boost/numeric/ublas/io.hpp>\r\n#include <boost/numeric/ublas/vector.hpp>\r\n\r\nnamespace openstudio {\r\n\r\n/// Workaround to get Vector typedef, http://www.gotw.ca/gotw/079.htm\r\nstruct UTILITIES_API VectorStruct\r\n{\r\n  typedef boost::numeric::ublas::vector<double> VectorType;\r\n  typedef boost::numeric::ublas::scalar_vector<double> ScalarVectorType;\r\n};\r\n\r\n/// Vector \r\ntypedef VectorStruct::VectorType Vector;\r\n\r\n/// ScalarVector \r\ntypedef VectorStruct::ScalarVectorType ScalarVector;\r\n\r\n/// Helper function to construct Vector from std::vector<double>.\r\nUTILITIES_API Vector createVector(const std::vector<double>& values);\r\n\r\n/// Helper function to construct Vector from std::vector<long>\r\nUTILITIES_API Vector createVector(const std::vector<long>& values);\r\n\r\nUTILITIES_API std::vector<double> toStandardVector(const Vector& values);\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n// Begin SWIG'able, copy and paste into Vector.i\r\n//////////////////////////////////////////////////////////////////////////\r\n\r\n/** @name Operators */\r\n//@{\r\n\r\nUTILITIES_API bool operator==(const Vector& lhs, const Vector& rhs);\r\nUTILITIES_API bool operator!=(const Vector& lhs, const Vector& rhs);\r\n\r\n//@}\r\n/** @name Interpolation */\r\n//@{\r\n\r\n// The following link has hints for interpolation\r\n// http://o2scl.sourceforge.net/o2scl/html/index.html#intp_section\r\n\r\n/** Enum to specify the interpolation method. */\r\nenum InterpMethod{LinearInterp, NearestInterp, HoldLastInterp, HoldNextInterp};\r\n\r\n/** Enum to specify the extrapolation method. */\r\nenum ExtrapMethod{NoneExtrap, NearestExtrap};\r\n\r\n/** Data structure for holding interpolation information. */\r\nstruct UTILITIES_API InterpInfo{\r\n  bool extrapolated; // was point out of range\r\n  unsigned ia, ib; // indices of two nearest points\r\n  double wa, wb; // weights of two nearest points\r\n};\r\n\r\n/** Linear interpolation of the function y = f(x) at point xi. Assumes that x is strictly \r\n *  increasing. */\r\nUTILITIES_API InterpInfo interpInfo(const Vector& x, double xi);\r\n\r\n/** Linear interpolation of the function y = f(x) at point xi. Assumes that x is strictly \r\n *  increasing */\r\nUTILITIES_API double interp(const Vector& x, const Vector& y, double xi, \r\n                            InterpMethod interpMethod = LinearInterp, \r\n                            ExtrapMethod extrapMethod = NoneExtrap);\r\n\r\n/** Linear interpolation of the function y = f(x) at points xi. Assumes that x is strictly \r\n *  increasing. */\r\nUTILITIES_API Vector interp(const Vector& x, const Vector& y, const Vector& xi, \r\n                            InterpMethod interpMethod = LinearInterp, \r\n                            ExtrapMethod extrapMethod = NoneExtrap);\r\n\r\n//@}\r\n/** @name Common Methods and Vector Operations */\r\n//@{\r\n\r\n/** Generates a Vector of N points randomly drawn between and including a and b. */\r\nUTILITIES_API Vector randVector(double a, double b, unsigned N);\r\n\r\n/** Generates a Vector of N points linearly spaced between and including a and b. */\r\nUTILITIES_API Vector linspace(double a, double b, unsigned N);\r\n\r\n/** Generates a Vector linearly spaced points starting at a and ending before or at b with \r\n *  interval delta. */\r\nUTILITIES_API Vector deltaSpace(double a, double b, double delta);\r\n\r\n/** Generates a Vector of N points logarithmically spaced between and including base^a and \r\n *  base^b. */\r\nUTILITIES_API Vector logspace(double a, double b, unsigned N, double base = 10.0);\r\n\r\n/** Take the natural logarithm of elements of a Vector. */\r\nUTILITIES_API Vector log(const Vector& x);\r\n\r\n/** Take the logarithm of elements of a Vector with certain base. */\r\nUTILITIES_API Vector log(const Vector& x, double base);\r\n\r\n/** Compute the cumulative sum of a Vector. */\r\nUTILITIES_API Vector cumsum(const Vector& x, double runningSum = 0.0);\r\n\r\n/** Returns the dot product between lhs and rhs. */\r\nUTILITIES_API double dot(const Vector& lhs, const Vector& rhs);\r\n\r\n/** Returns the sum of vector's values. */\r\nUTILITIES_API double sum(const Vector& vector);\r\n\r\n/** Returns the largest element of vector. */\r\nUTILITIES_API double maximum(const Vector& vector);\r\n\r\n/** Returns the smallest element of vector. */\r\nUTILITIES_API double minimum(const Vector& vector);\r\n\r\n/** Returns the mean of vector's values */\r\nUTILITIES_API double mean(const Vector& vector);\r\n\r\n/** Returns the sample variance of vector's values. */\r\nUTILITIES_API double variance(const Vector& vector);\r\n\r\n/** Returns the standard deviation of vector's values. */\r\nUTILITIES_API double stdDev(const Vector& vector);\r\n\r\n/** Returns std::function pointer to sum(const Vector&). */\r\nUTILITIES_API std::function<double (const Vector&)> sumVectorFunctor();\r\n\r\n/** Returns std::function pointer to maximum(const Vector&). */\r\nUTILITIES_API std::function<double (const Vector&)> maximumVectorFunctor();\r\n\r\n/** Returns std::function pointer to minimum(const Vector&). */\r\nUTILITIES_API std::function<double (const Vector&)> minimumVectorFunctor();\r\n\r\n/** Returns std::function pointer to mean(const Vector&). */\r\nUTILITIES_API std::function<double (const Vector&)> meanVectorFunctor();\r\n\r\n/** Returns std::function pointer to variance(const Vector&). */\r\nUTILITIES_API std::function<double (const Vector&)> varianceVectorFunctor();\r\n\r\n/** Returns std::function pointer to stdDev(const Vector&). */\r\nUTILITIES_API std::function<double (const Vector&)> stdDevVectorFunctor();\r\n\r\n/** Evaluates functor(vector). For use in SWIG bindings. */\r\nUTILITIES_API double evaluateDoubleFromVectorFunctor(\r\n    const std::function<double (const Vector&)>& functor,\r\n    const Vector& vector);\r\n\r\n//@}\r\n\r\n} // openstudio\r\n\r\n#endif //UTILITIES_DATA_VECTOR_HPP\r\n", "meta": {"hexsha": "6d20d6f79b326273aadcb341f5a1de4303ccdad5", "size": 6792, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/data/Vector.hpp", "max_stars_repo_name": "BIMDataHub/OpenStudio-1", "max_stars_repo_head_hexsha": "13ec115b00aa6a2af1426ceb26446f05014c8c8d", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-05-02T21:04:15.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-28T09:47:22.000Z", "max_issues_repo_path": "openstudiocore/src/utilities/data/Vector.hpp", "max_issues_repo_name": "BIMDataHub/OpenStudio-1", "max_issues_repo_head_hexsha": "13ec115b00aa6a2af1426ceb26446f05014c8c8d", "max_issues_repo_licenses": ["blessing"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openstudiocore/src/utilities/data/Vector.hpp", "max_forks_repo_name": "BIMDataHub/OpenStudio-1", "max_forks_repo_head_hexsha": "13ec115b00aa6a2af1426ceb26446f05014c8c8d", "max_forks_repo_licenses": ["blessing"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-12T21:52:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-12T21:52:36.000Z", "avg_line_length": 39.2601156069, "max_line_length": 92, "alphanum_fraction": 0.6866902238, "num_tokens": 1440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.43114147348287074}}
{"text": "//=======================================================================\n// Copyright 2000 University of Notre Dame.\n// Authors: Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n\n#ifndef BOOST_EDGE_CONNECTIVITY\n#define BOOST_EDGE_CONNECTIVITY\n\n// WARNING: not-yet fully tested!\n\n#include <boost/config.hpp>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <boost/graph/edmonds_karp_max_flow.hpp>\n\nnamespace boost {\n\n  namespace detail {\n\n    template <class Graph>\n    inline\n    std::pair<typename graph_traits<Graph>::vertex_descriptor,\n              typename graph_traits<Graph>::degree_size_type>\n    min_degree_vertex(Graph& g)\n    {\n      typedef graph_traits<Graph> Traits;\n      typename Traits::vertex_descriptor p;\n      typedef typename Traits::degree_size_type size_type;\n      size_type delta = (std::numeric_limits<size_type>::max)();\n\n      typename Traits::vertex_iterator i, iend;\n      for (tie(i, iend) = vertices(g); i != iend; ++i)\n        if (degree(*i, g) < delta) {\n          delta = degree(*i, g);\n          p = *i;\n        }\n      return std::make_pair(p, delta);\n    }\n\n    template <class Graph, class OutputIterator>\n    void neighbors(const Graph& g, \n                   typename graph_traits<Graph>::vertex_descriptor u,\n                   OutputIterator result)\n    {\n      typename graph_traits<Graph>::adjacency_iterator ai, aend;\n      for (tie(ai, aend) = adjacent_vertices(u, g); ai != aend; ++ai)\n        *result++ = *ai;\n    }\n\n    template <class Graph, class VertexIterator, class OutputIterator>\n    void neighbors(const Graph& g, \n                   VertexIterator first, VertexIterator last,\n                   OutputIterator result)\n    {\n      for (; first != last; ++first)\n        neighbors(g, *first, result);\n    }\n\n  } // namespace detail\n\n  // O(m n)\n  template <class VertexListGraph, class OutputIterator>\n  typename graph_traits<VertexListGraph>::degree_size_type\n  edge_connectivity(VertexListGraph& g, OutputIterator disconnecting_set)\n  {\n    //-------------------------------------------------------------------------\n    // Type Definitions\n    typedef graph_traits<VertexListGraph> Traits;\n    typedef typename Traits::vertex_iterator vertex_iterator;\n    typedef typename Traits::edge_iterator edge_iterator;\n    typedef typename Traits::out_edge_iterator out_edge_iterator;\n    typedef typename Traits::vertex_descriptor vertex_descriptor;\n    typedef typename Traits::degree_size_type degree_size_type;\n    typedef color_traits<default_color_type> Color;\n\n    typedef adjacency_list_traits<vecS, vecS, directedS> Tr;\n    typedef typename Tr::edge_descriptor Tr_edge_desc;\n    typedef adjacency_list<vecS, vecS, directedS, no_property, \n      property<edge_capacity_t, degree_size_type,\n        property<edge_residual_capacity_t, degree_size_type,\n          property<edge_reverse_t, Tr_edge_desc> > > > \n      FlowGraph;\n    typedef typename graph_traits<FlowGraph>::edge_descriptor edge_descriptor;\n\n    //-------------------------------------------------------------------------\n    // Variable Declarations\n    vertex_descriptor u, v, p, k;\n    edge_descriptor e1, e2;\n    bool inserted;\n    vertex_iterator vi, vi_end;\n    edge_iterator ei, ei_end;\n    degree_size_type delta, alpha_star, alpha_S_k;\n    std::set<vertex_descriptor> S, neighbor_S;\n    std::vector<vertex_descriptor> S_star, non_neighbor_S;\n    std::vector<default_color_type> color(num_vertices(g));\n    std::vector<edge_descriptor> pred(num_vertices(g));\n\n    //-------------------------------------------------------------------------\n    // Create a network flow graph out of the undirected graph\n    FlowGraph flow_g(num_vertices(g));\n\n    typename property_map<FlowGraph, edge_capacity_t>::type\n      cap = get(edge_capacity, flow_g);\n    typename property_map<FlowGraph, edge_residual_capacity_t>::type\n      res_cap = get(edge_residual_capacity, flow_g);\n    typename property_map<FlowGraph, edge_reverse_t>::type\n      rev_edge = get(edge_reverse, flow_g);\n\n    for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\n      u = source(*ei, g), v = target(*ei, g);\n      tie(e1, inserted) = add_edge(u, v, flow_g);\n      cap[e1] = 1;\n      tie(e2, inserted) = add_edge(v, u, flow_g);\n      cap[e2] = 1; // not sure about this\n      rev_edge[e1] = e2;\n      rev_edge[e2] = e1;\n    }\n\n    //-------------------------------------------------------------------------\n    // The Algorithm\n\n    tie(p, delta) = detail::min_degree_vertex(g);\n    S_star.push_back(p);\n    alpha_star = delta;\n    S.insert(p);\n    neighbor_S.insert(p);\n    detail::neighbors(g, S.begin(), S.end(), \n                      std::inserter(neighbor_S, neighbor_S.begin()));\n\n    std::set_difference(vertices(g).first, vertices(g).second,\n                        neighbor_S.begin(), neighbor_S.end(),\n                        std::back_inserter(non_neighbor_S));\n\n    while (!non_neighbor_S.empty()) { // at most n - 1 times\n      k = non_neighbor_S.front();\n\n      alpha_S_k = edmonds_karp_max_flow\n        (flow_g, p, k, cap, res_cap, rev_edge, &color[0], &pred[0]);\n\n      if (alpha_S_k < alpha_star) {\n        alpha_star = alpha_S_k;\n        S_star.clear();\n        for (tie(vi, vi_end) = vertices(flow_g); vi != vi_end; ++vi)\n          if (color[*vi] != Color::white())\n            S_star.push_back(*vi);\n      }\n      S.insert(k);\n      neighbor_S.insert(k);\n      detail::neighbors(g, k, std::inserter(neighbor_S, neighbor_S.begin()));\n      non_neighbor_S.clear();\n      std::set_difference(vertices(g).first, vertices(g).second,\n                          neighbor_S.begin(), neighbor_S.end(),\n                          std::back_inserter(non_neighbor_S));\n    }\n    //-------------------------------------------------------------------------\n    // Compute edges of the cut [S*, ~S*]\n    std::vector<bool> in_S_star(num_vertices(g), false);\n    typename std::vector<vertex_descriptor>::iterator si;\n    for (si = S_star.begin(); si != S_star.end(); ++si)\n      in_S_star[*si] = true;\n\n    degree_size_type c = 0;\n    for (si = S_star.begin(); si != S_star.end(); ++si) {\n      out_edge_iterator ei, ei_end;\n      for (tie(ei, ei_end) = out_edges(*si, g); ei != ei_end; ++ei)\n        if (!in_S_star[target(*ei, g)]) {\n          *disconnecting_set++ = *ei;\n          ++c;\n        }\n    }\n    return c;\n  }\n\n} // namespace boost\n\n#endif // BOOST_EDGE_CONNECTIVITY\n", "meta": {"hexsha": "d52bf9cc1196c0248ff98a2031b0578f25486250", "size": 6622, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/edge_connectivity.hpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/graph/edge_connectivity.hpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/graph/edge_connectivity.hpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3846153846, "max_line_length": 79, "alphanum_fraction": 0.5952884325, "num_tokens": 1520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.43114146558437416}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <vector>\n#include <memory>\n#include <iostream>\n#include <iomanip>\n#include <boost/noncopyable.hpp>\n#include \"Eigen/Core\"\n#include \"Eigen/LU\"\n#include \"metro/regression/Design.hpp\"\n#include \"metro/regression/LogLikelihood.hpp\"\n#include \"metro/regression/NormalWeightedLogLikelihood.hpp\"\n\n// #define DEBUG_NORMALWEIGHTEDLOGLIKELIHOOD 1\n\nnamespace metro {\n\tnamespace regression {\n\t\tnamespace impl {\n\t\t\tdouble compute_mvn_constant( int const k, double determinant ) {\n\t\t\t\treturn -0.5 * k * std::log( 2 * 3.141592654 ) - 0.5 * std::log( determinant ) ;\n\t\t\t}\n\t\t}\n\n\t\tNormalWeightedLogLikelihood::UniquePtr NormalWeightedLogLikelihood::create(\n\t\t\tLogLikelihood::UniquePtr ll,\n\t\t\tVector const mean,\n\t\t\tMatrix const covariance,\n\t\t\tNormalisation normalisation\n\t\t) {\n\t\t\treturn UniquePtr( new NormalWeightedLogLikelihood( ll, mean, covariance, normalisation ) ) ;\n\t\t}\n\n\t\tNormalWeightedLogLikelihood::NormalWeightedLogLikelihood(\n\t\t\tLogLikelihood::UniquePtr ll,\n\t\t\tVector const mean,\n\t\t\tMatrix const covariance,\n\t\t\tNormalisation normalisation\n\t\t):\n\t\t\tm_ll( ll ),\n\t\t\tm_mean( mean ),\n\t\t\tm_covariance( covariance ),\n\t\t\tm_normalisation( normalisation ),\n\t\t\tm_solver( covariance ),\n\t\t\tm_inverse_covariance( m_solver.solve( Matrix::Identity( mean.size(), mean.size() ))),\n\t\t\tm_constant( impl::compute_mvn_constant( m_mean.size(), m_covariance.determinant() ))\n\t\t{}\n\n\t\tstd::string NormalWeightedLogLikelihood::get_parameter_name( std::size_t i ) const {\n\t\t\treturn m_ll->get_parameter_name(i) ;\n\t\t}\n\t\tNormalWeightedLogLikelihood::IntegerMatrix NormalWeightedLogLikelihood::identify_parameters() const {\n\t\t\treturn m_ll->identify_parameters() ;\n\t\t}\n\t\t\n\t\tint NormalWeightedLogLikelihood::number_of_parameters() const {\n\t\t\treturn m_ll->number_of_parameters() ;\n\t\t}\n\n\t\tint NormalWeightedLogLikelihood::number_of_outcomes() const {\n\t\t\treturn m_ll->number_of_outcomes() ;\n\t\t}\n\t\t\n\t\tvoid NormalWeightedLogLikelihood::evaluate_at( Point const& parameters, int const numberOfDerivatives ) {\n\t\t\tm_ll->evaluate_at( parameters, numberOfDerivatives ) ;\n\t\t\tevaluate_impl( numberOfDerivatives ) ;\n\t\t}\n\n\t\tvoid NormalWeightedLogLikelihood::evaluate( int const numberOfDerivatives ) {\n\t\t\tm_ll->evaluate( numberOfDerivatives ) ;\n\t\t\tevaluate_impl( numberOfDerivatives ) ;\n\t\t}\n\n\t\tvoid NormalWeightedLogLikelihood::evaluate_impl( int const numberOfDerivatives ) {\n\t\t\tVector const& parameters = m_ll->parameters() ;\n\t\t\tVector solved = m_solver.solve( parameters - m_mean ) ;\n\t\t\tm_log_density = -0.5 * ((parameters - m_mean).transpose() * solved)(0) ;\n\t\t\tm_value_of_first_derivative = -solved ;\n\t\t\tm_value_of_second_derivative = -m_inverse_covariance ;\n\n#if DEBUG_NORMALWEIGHTEDLOGLIKELIHOOD\n\t\t\tstd::cerr << \"NormalWeightedLogLikelihood::evaluate_impl()\\:\\n\" ;\n\t\t\tstd::cerr << \"parameters = \" << parameters.transpose() << \".\\n\" ;\n\t\t\tstd::cerr << \"constant = \" << m_constant << \".\\n\" ;\n\t\t\tstd::cerr << \"solved = \\n\" << solved << \".\\n\" ;\n\t\t\tstd::cerr << \"log density = \" << m_log_density << \"\\n\" ;\n#endif\n\t\t}\n\t\n\t\tstd::string NormalWeightedLogLikelihood::get_summary() const {\n\t\t\tstd::ostringstream ostr ;\n\t\t\tostr << \"normal-weighted:\" << m_ll->get_summary() << \"\\n\" ;\n\t\t\tostr << \"normal-weighted: using the following prior covariance:\\n\" ;\n\t\t\tstd::size_t max_label_length = 0 ;\n\t\t\tfor( int i = 0; i < m_covariance.rows(); ++i ) {\n\t\t\t\tmax_label_length = std::max( max_label_length, m_ll->get_parameter_name(i).size() ) ;\n\t\t\t}\n\t\t\tostr\n\t\t\t\t<< std::setw(3) << \"\" << \"  \"\n\t\t\t\t<< std::setw( max_label_length + 2 ) << \"parameter\"\n\t\t\t\t<< \":\" ;\n\t\t\tfor( int j = 0; j < m_covariance.cols(); ++j ) {\n\t\t\t\tostr << \" \" << std::setw(5) << (j+1) ;\n\t\t\t}\n\t\t\tostr << \"\\n\" ;\n\t\t\tfor( int i = 0; i < m_covariance.rows(); ++i ) {\n\t\t\t\tostr << std::setw(3) << i+1\n\t\t\t\t\t<< \": \" << std::setw( max_label_length + 2 ) << m_ll->get_parameter_name(i) << \":\" ;\n\t\t\t\tfor( int j = 0; j < m_covariance.cols(); ++j ) {\n\t\t\t\t\tostr << \" \" << std::setw(5) << std::setprecision(4) << m_covariance(i,j) ;\n\t\t\t\t}\n\t\t\t\tostr << \"\\n\" ;\n\t\t\t}\n\t\t\treturn ostr.str() ;\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "c1a7da99beffd34711e2e14e3f6562a3e6f50246", "size": 4198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metro/src/regression/NormalWeightedLogLikelihood.cpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "metro/src/regression/NormalWeightedLogLikelihood.cpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "metro/src/regression/NormalWeightedLogLikelihood.cpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.694214876, "max_line_length": 107, "alphanum_fraction": 0.6753215817, "num_tokens": 1209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.43112053039030285}}
{"text": "\n#include <iostream>\n#include <map>\n#include <fstream>\n\n#include <unsupported/Eigen/KroneckerProduct>\n#include <Eigen/Geometry>\n\n#include <polyvec/curve-tracer/bezier_merging.hpp>\n#include <polyvec/utils/num.hpp>\n#include <polyvec/geometry/angle.hpp>\n#include <polyvec/geometry/line.hpp>\n#include <polyvec/utils/string.hpp>\n#include <polyvec/geometry/winding_number.hpp>\n#include <polyvec/curve-tracer/curve_bezier.hpp>\n#include <polyvec/shortest-path/dijkstra.hpp>\n#include <polyvec/io/vtk_curve_writer.hpp>\n\n\nNAMESPACE_BEGIN ( polyfit )\nNAMESPACE_BEGIN ( BezierMerging )\n\n// ===========================================\n// Control points parameterization\n// ===========================================\n\nvoid\nPointParameters::is_potracable ( bool& result, Eigen::Vector2d& oo, double& alpha, double& beta ) const {\n\n#define undoable() do{ result = false; return; }while(0)\n\n    // const double norm_cap = 10000;\n\n    // if ( control_points.norm() > norm_cap ) {\n    //     undoable();\n    // }\n\n\n\n    bool is_inflection_okay =  !AngleUtils::have_opposite_convexity_with_tol (\n                                   control_points.col ( 0 ),\n                                   control_points.col ( 1 ),\n                                   control_points.col ( 2 ),\n                                   control_points.col ( 3 )\n                               );\n\n    if ( !is_inflection_okay ) {\n        undoable();\n    }\n\n    double lhs_at, rhs_at;\n    bool do_intersect = ::polyvec::LineUtils::intersect (\n                            control_points.col ( 0 ),  control_points.col ( 1 ),\n                            control_points.col ( 3 ),  control_points.col ( 2 ),\n                            lhs_at,\n                            rhs_at );\n\n    bool is_intersection_okay = do_intersect && ( lhs_at >= 1. )  && ( rhs_at >= 1. );\n\n    if ( !is_intersection_okay ) {\n        undoable();\n    }\n\n    oo = ::polyvec::LineUtils::line_at ( control_points.col ( 0 ),  control_points.col ( 1 ), lhs_at );\n    alpha = 1. / lhs_at;\n    beta = 1. / rhs_at;\n    result = true;\n\n#undef undoable\n}\n\n\nbool\nPointParameters::is_potracable () const {\n    Eigen::Vector2d oy;\n    double alpha, beta;\n    bool potracable;\n    is_potracable ( potracable, oy, alpha, beta );\n    return potracable;\n}\n\nPotraceParameters\nPointParameters::as_potrace_params() const {\n    bool potracable;\n    Eigen::Vector2d oy;\n    double alpha, beta;\n    PotraceParameters ans;\n\n    is_potracable ( potracable, oy, alpha, beta );\n\n    if ( potracable ) {\n        ans.alpha = alpha;\n        ans.beta = beta;\n        Mat23 p0, p1;\n        //\n        p0.col ( 0 ) << -1, 0;\n        p0.col ( 1 ) << 0, 1;\n        p0.col ( 2 ) << 1, 0;\n        //\n        p1.col ( 0 ) << control_points.col ( 0 );\n        p1.col ( 1 ) << oy;\n        p1.col ( 2 ) << control_points.col ( 3 );\n        //\n        find_affine_transformation ( p0, p1, ans.A, ans.b );\n    } else {\n        assert_break ( 0 );\n    }\n\n    return ans;\n}\n\n// ===========================================\n// Potrace parameterization\n// ===========================================\n\ndouble\nPotraceParameters::get_areaz() const {\n    return 3./10* ( 2*alpha + 2*beta - alpha*beta );\n}\n\n\ndouble\nPotraceParameters::get_areay() const {\n    return std::abs ( polyvec::Num::determinant ( A ) ) *get_areaz();\n}\n\nPointParameters\nPotraceParameters::get_zz() const {\n    Mat24 ans;\n    ans.col ( 0 ) << -1, 0;\n    ans.col ( 1 ) << -1+alpha, alpha;\n    ans.col ( 2 ) << 1-beta, beta;\n    ans.col ( 3 ) << 1, 0;\n\n    return {ans};\n}\n\nEigen::Vector2d\nPotraceParameters::get_oz() {\n    return Eigen::Vector2d ( 0, 1 );\n}\n\nPointParameters\nPotraceParameters::get_yy() const {\n    return { ( A*get_zz().control_points ).colwise() + b};\n}\n\nEigen::Vector2d\nPotraceParameters::get_oy() const {\n    return A*get_oz() + b;\n}\n\nPotraceParameters\nPotraceParameters::equiparamed() const {\n    PotraceParameters ans;\n    ans = *this;\n    ans.alpha = ans.beta = 2 - std::sqrt ( ( 2-alpha ) * ( 2-beta ) );\n    return ans;\n}\n\nbool\nPotraceParameters::is_ccw() const {\n    return polyvec::Num::determinant ( A ) < 0;\n}\n\n\n// stolen from potrace <3\n// calculate (p1-p0)x(p3-p2)\nnamespace {\n\tdouble\n\t\t_cprod(const Eigen::Vector2d& p0, const Eigen::Vector2d& p1, const Eigen::Vector2d& p2, const Eigen::Vector2d& p3) {\n\t\tdouble x1, y1, x2, y2;\n\n\t\tx1 = p1.x() - p0.x();\n\t\ty1 = p1.y() - p0.y();\n\t\tx2 = p3.x() - p2.x();\n\t\ty2 = p3.y() - p2.y();\n\n\t\treturn x1 * y2 - x2 * y1;\n\t}\n\n\t// calculate the point t in [0..1] on the (convex) bezier curve\n\t//   (p0,p1,p2,p3) which is tangent to q1-q0. Return -1.0 if there is no\n\t//   solution in [0..1].\n\tdouble\n\t\t_tangent(const Eigen::Vector2d& p0, const Eigen::Vector2d& p1, const Eigen::Vector2d& p2, const Eigen::Vector2d& p3, const Eigen::Vector2d& q0,\n\t\t\tconst Eigen::Vector2d& q1) {\n\t\tdouble A, B, C;   /* (1-t)^2 A + 2(1-t)t B + t^2 C = 0 */\n\t\tdouble a, b, c;   /* a t^2 + b t + c = 0 */\n\t\tdouble d, s, r1, r2;\n\n\t\tA = _cprod(p0, p1, q0, q1);\n\t\tB = _cprod(p1, p2, q0, q1);\n\t\tC = _cprod(p2, p3, q0, q1);\n\n\t\ta = A - 2 * B + C;\n\t\tb = -2 * A + 2 * B;\n\t\tc = A;\n\n\t\td = b * b - 4 * a * c;\n\n\t\tif ((std::abs(a) < 1e-12)\n\t\t\t&& (std::abs(b) > 1e-12)\n\t\t\t&& (-c / b >= 0)\n\t\t\t&& (-c / b <= 1.)) {\n\t\t\treturn -c / b;\n\t\t}\n\n\t\tif ((std::abs(a) < 1e-12) || (d < 1e-12)) {\n\t\t\treturn -1.0;\n\t\t}\n\n\t\ts = sqrt(d);\n\n\t\tr1 = (-b + s) / (2 * a);\n\t\tr2 = (-b - s) / (2 * a);\n\n\t\tif (r1 >= 0 && r1 <= 1) {\n\t\t\treturn r1;\n\t\t}\n\t\telse if (r2 >= 0 && r2 <= 1) {\n\t\t\treturn r2;\n\t\t}\n\t\telse {\n\t\t\treturn -1.0;\n\t\t}\n\t}\n}\n\nvoid\nPotraceParameters::t_for_tangent ( const Eigen::Vector2d& tangent_y, double& t, bool& success ) const {\n    const Mat24 yy = get_yy().control_points;\n    t = _tangent ( yy.col ( 0 ), yy.col ( 1 ), yy.col ( 2 ), yy.col ( 3 ), Eigen::Vector2d::Zero(), tangent_y.normalized() );\n\n    if ( t < 0 ) {\n        success = false;\n    } else {\n        success = true;\n    }\n\n# if 0 // my own attempt. Potrace seems nicer.\n    const double pi = ::polyvec::constants::PI;\n    // Find the tangent in the reference coordiantes\n    Eigen::Vector2d tangent_z = Num::solve_linear_system ( A, tangent_y );\n    const Eigen::Vector2d zz = get_zz().control_points;\n    assert_break ( tangent_z.norm() > 1e-10 );\n    // Now find the angle of the tangent with the x axis\n    // also find the begin and end angle of the bezier\n    const double angle = std::atan2 ( tangent_z.y(), tangent_z.x() );\n    const double begin_angle = std::atan2 ( zz.col ( 1 ).y() - zz.col ( 0 ).y(), zz.col ( 1 ).x() - zz.col ( 0 ).x() );\n    const double end_angle = std::atan2 ( zz.col ( 3 ).y() - zz.col ( 2 ).y(), zz.col ( 3 ).x() - zz.col ( 2 ).x() );\n    assert_break ( std::abs ( begin_angle-pi/4 ) < 1e-5 );\n    assert_break ( std::abs ( end_angle+pi/4 ) < 1e-5 );\n#endif\n}\n\n// ===========================================\n// Functions\n// ===========================================\n\nvoid\nfind_affine_transformation ( const Mat23& points0, const Mat23& points1, Eigen::Matrix2d& A, Eigen::Vector2d& b ) {\n    Eigen::Matrix<double, 6, 6> LHS;\n    Eigen::Matrix<double, 6, 1> RHS;\n    Eigen::Matrix<double, 6, 1> unknowns;\n\n    Eigen::Matrix2d eye =  Eigen::Matrix2d::Identity();\n\n    LHS.block<2, 4> ( 0, 0 ) = Eigen::kroneckerProduct ( points0.col ( 0 ).transpose(), eye );\n    LHS.block<2, 4> ( 2, 0 ) = Eigen::kroneckerProduct ( points0.col ( 1 ).transpose(), eye );\n    LHS.block<2, 4> ( 4, 0 ) = Eigen::kroneckerProduct ( points0.col ( 2 ).transpose(), eye );\n    //\n    LHS.block<2, 2> ( 0, 4 ) = eye;\n    LHS.block<2, 2> ( 2, 4 ) = eye;\n    LHS.block<2, 2> ( 4, 4 ) = eye;\n    //\n    RHS.segment<2> ( 0 ) = points1.col ( 0 );\n    RHS.segment<2> ( 2 ) = points1.col ( 1 );\n    RHS.segment<2> ( 4 ) = points1.col ( 2 );\n\n    // Debugging\n    //std::cout << LHS << std::endl;\n    //std::cout << Num::determinant(LHS) << std::endl;\n\n    unknowns = polyvec::Num::solve_linear_system ( LHS, RHS );\n\n    A.col ( 0 ) = unknowns.segment<2> ( 0 );\n    A.col ( 1 ) = unknowns.segment<2> ( 2 );\n    b = unknowns.segment<2> ( 4 );\n\n    // Make sure it is working\n    const double error = ( ( A*points0 ).colwise() + b - points1 ).norm() ;\n    assert_break ( error < 1e-10 );\n}\n\nnamespace {\nbool\nskip_comments ( FILE* fl ) {\n    char tmp[4096];\n    bool is_there_more_to_read = false;\n    assert_break ( fl );\n\n    for ( ;; ) {\n        const int c = fgetc ( fl );\n\n        if ( c ==EOF ) {\n            is_there_more_to_read = false;\n            break;\n        } else if ( c == '#' ) {\n            fgets ( tmp, 4096, fl );\n            continue;\n        } else if ( ( c != ' ' ) && ( c != '\\n' ) && ( c != '\\r' ) ) {\n            int success = fseek ( fl, -1, SEEK_CUR );\n            assert ( success == 0 );\n            is_there_more_to_read = true;\n            break;\n        }\n    }\n\n    return is_there_more_to_read;\n}\n}\n\nvoid\ndump_curve_sequence ( const std::vector<Eigen::Matrix2Xd>& curves, FILE* file ) {\n    fprintf ( file, \"# N curves \\n %d \\n\", ( int ) curves.size() );\n\n    for ( int i = 0 ; i < curves.size() ; ++ i ) {\n        fprintf ( file, \"# Curve %d, n points \\n %d \\n\", i, ( int ) curves[i].cols() );\n\n        for ( int j = 0 ; j < curves[i].cols() ; ++ j ) {\n            fprintf ( file, \"%.12g \", curves[i] ( 0, j ) );\n        }\n\n        fprintf ( file, \"\\n\" );\n\n        for ( int j = 0 ; j < curves[i].cols() ; ++ j ) {\n            fprintf ( file, \"%.12g \", curves[i] ( 1, j ) );\n        }\n\n        fprintf ( file, \"\\n\" );\n    }\n}\n\nstd::vector<Eigen::Matrix2Xd>\nread_curve_sequence ( FILE* file ) {\n#define ENSURE(X) if(!(X)) {assert_break(0);}\n\n    int n_curves;\n    ENSURE ( skip_comments ( file ) );\n    ENSURE ( fscanf ( file, \"%d\", &n_curves ) == 1 );\n\n    std::vector<Eigen::Matrix2Xd> curves ( n_curves );\n\n    for ( int i = 0 ; i < curves.size() ; ++ i ) {\n        int n_points;\n        ENSURE ( skip_comments ( file ) );\n        ENSURE ( fscanf ( file, \"%d\", &n_points ) == 1 );\n        curves[i].resize ( 2, n_points );\n\n        ENSURE ( skip_comments ( file ) );\n\n        for ( int j = 0 ; j < curves[i].cols() ; ++ j ) {\n            ENSURE ( fscanf ( file, \"%lf\", &curves[i] ( 0, j ) ) == 1 );\n        }\n\n        ENSURE ( skip_comments ( file ) );\n\n        for ( int j = 0 ; j < curves[i].cols() ; ++ j ) {\n            ENSURE ( fscanf ( file, \"%lf\", &curves[i] ( 1, j ) ) == 1 );\n        }\n    }\n\n    return curves;\n\n\n#undef ENSURE\n}\n\n\nvoid merged_curve (\n    const std::vector<Eigen::Matrix2d>& line_begin,\n    const std::vector<Mat24>& beziers,\n    const std::vector<Eigen::Matrix2d>& line_end,\n    FILE* verbose,\n    bool& doable,\n    Mat24& ans_mat ) {\n\n    PotraceParameters ans;\n\n\n    auto eprintf = [verbose] ( const std::string strr ) {\n        if ( verbose ) {\n            fprintf ( verbose, \"%s\", strr.c_str() );\n        }\n    };\n\n#define undoable() do{doable =false; eprintf(\"\"); return;}while(0)\n\n    assert_break ( line_begin.size() <= 1 );\n    assert_break ( line_end.size() <= 1 );\n    assert_break ( beziers.size() >= 1 );\n\n    // ============\n    // First check that each bezier should be potracable\n    // ============\n    for ( int i = 0 ; i < ( int ) beziers.size() ; ++i ) {\n        if ( !PointParameters ( {beziers[i]} ).is_potracable() ) {\n            eprintf ( StringUtils::fmt ( \"curve[%d] is not potracable \\n\", i ) );\n            undoable();\n        }\n    }\n\n    // ============\n    // Now check that transitions from each curve also does not\n    // introduce an inflection\n    // The assumption is that the tangents of all the transitions match\n    // ============\n\n    // line begin\n    if ( line_begin.size() ) {\n        if ( AngleUtils::have_opposite_convexity (\n                    line_begin[0].col ( 0 ),\n                    beziers[0].col ( 1 ),\n                    beziers[0].col ( 2 ),\n                    beziers[0].col ( 3 ) ) ) {\n            eprintf ( StringUtils::fmt ( \"line0 to bezier 1 inflected \\n\" ) );\n            undoable();\n        }\n    }\n\n    // line end\n    if ( line_end.size() ) {\n        if ( AngleUtils::have_opposite_convexity (\n                    beziers.back().col ( 0 ),\n                    beziers.back().col ( 1 ),\n                    beziers.back().col ( 2 ),\n                    line_end[0].col ( 1 ) ) ) {\n            eprintf ( StringUtils::fmt ( \"line_end to bezier end inflected \\n\" ) );\n            undoable();\n        }\n    }\n\n    // Beziers\n    for ( int i = 0 ; i < ( int ) beziers.size()-1 ; ++i ) {\n        if ( AngleUtils::have_opposite_convexity (\n                    beziers[i].col ( 1 ),\n                    beziers[i].col ( 2 ),\n                    beziers[i+1].col ( 1 ),\n                    beziers[i+1].col ( 2 ) ) ) {\n            eprintf ( StringUtils::fmt ( \"bezier[%d] to bezier[%d] inflected \\n\", i, i +1 ) );\n            undoable();\n        }\n    }\n\n    // ============\n    //   Check that the first and last line intersection each other\n    // ============\n    Eigen::Vector2d y0, y3, oy;\n    {\n        Eigen::Matrix2d ray_begin;\n        Eigen::Matrix2d ray_end;\n\n        if ( line_begin.size() ) {\n            ray_begin = line_begin.front();\n        } else {\n            ray_begin = beziers.front().leftCols<2>();\n        }\n\n        if ( line_end.size() ) {\n            ray_end = line_end.front();\n        } else {\n            ray_end = beziers.back().rightCols<2>();\n        }\n\n        ray_end.rowwise().reverseInPlace();\n\n        double lhs_at, rhs_at;\n        const bool do_intersect = ::polyvec::LineUtils::intersect ( ray_begin.col ( 0 ), ray_begin.col ( 1 ), ray_end.col ( 0 ), ray_end.col ( 1 ), lhs_at, rhs_at );\n\n        if ( ( !do_intersect )\n                || ( lhs_at < 1. )\n                || ( rhs_at < 1. ) ) {\n            eprintf ( StringUtils::fmt ( \"Intersection Problem \\n\" ) );\n            undoable();\n        }\n\n        y0 = ray_begin.col ( 0 );\n        y3 = ray_end.col ( 0 );\n        oy = ::polyvec::LineUtils::line_at ( ray_begin.col ( 0 ), ray_begin.col ( 1 ), lhs_at );\n\n        // This is intersecting on the other side of the universe\n        if ( oy.norm() > 10000 ) {\n            //polyvec::VtkCurveWriter writer;\n            //writer.add_polyline( ray_begin );\n            //writer.add_polyline( ray_end   );\n            //writer.dump(\"DAMN.vtk\");\n            undoable();\n        }\n    }\n\n    // ============\n    //  Now find the area of the bezier sequence\n    // ============\n    double area_shape = 0;\n    {\n        auto find_carpet  = [&line_begin, &line_end, &beziers] {\n\n            Eigen::Matrix2Xd carpet ( 2, beziers.size() + line_begin.size() + line_end.size() + 1 );\n            int colid = 0;\n\n            if ( line_begin.size() ) {\n                carpet.col ( colid ) = line_begin.front().col ( 0 );\n                ++colid;\n            }\n\n            for ( int i = 0 ; i < ( int ) beziers.size() ; ++i ) {\n                carpet.col ( colid ) = beziers[i].col ( 0 );\n                ++colid;\n            }\n\n            if ( line_end.size() ) {\n                carpet.col ( colid ) = line_end.front().col ( 0 );\n                ++colid;\n                carpet.col ( colid ) = line_end.front().col ( 1 );\n                ++colid;\n            } else {\n                carpet.col ( colid ) = beziers.back().col ( 3 );\n                ++colid;\n            }\n\n            assert_break ( colid == ( int ) carpet.cols() );\n\n            return carpet;\n        }; // find carpet\n\n        bool is_carpet_ccw;\n        double area_carpet;\n        Eigen::Matrix2Xd carpet = find_carpet ();\n        ::polyvec::WindingNumber::compute_orientation ( carpet, is_carpet_ccw, area_carpet );\n\n        double area_beziers = 0;\n\n        for ( int i = 0 ; i < ( int ) beziers.size() ; ++i ) {\n            area_beziers += PointParameters ( {beziers[i]} ).as_potrace_params().get_areay();\n        }\n\n        area_shape = area_carpet + area_beziers;\n    }\n\n    //\n    // If we are here, we can finally create the merged bezier\n    //\n    {\n        Mat23 p0, p1;\n        //\n        p0.col ( 0 ) << -1, 0;\n        p0.col ( 1 ) << 0, 1;\n        p0.col ( 2 ) << 1, 0;\n        //\n        p1.col ( 0 ) << y0;\n        p1.col ( 1 ) << oy;\n        p1.col ( 2 ) << y3;\n        //\n        find_affine_transformation ( p0, p1, ans.A, ans.b );\n\n        const double area_ref  =  area_shape / std::abs ( polyvec::Num::determinant ( ans.A ) );\n\n        assert_break( !std::isnan( area_ref ) );\n        if ( ( area_ref > 1.19 ) ) {\n            eprintf ( StringUtils::fmt ( \"Area Problem \\n\" ) );\n            undoable();\n        }\n\n        ans.alpha =   ans.beta  = 2. - sqrt ( 4-10*area_ref/3. ) ;\n        assert_break (  ans.beta > 0 );\n\n        if ( ans.beta > 1 ) {\n            // DEBUGGING - TEMP, REMOVE\n            //for (auto bz : beziers ) {\n            //    std::cout << bz.row(0) << \" \" << bz.row(1) << std::endl;\n            // }\n            undoable();\n        }\n\n        assert_break ( area_ref > 0 );\n        assert_break ( std::abs ( area_ref - ans.get_areaz() ) < 1e-4 );\n        ans_mat = ans.get_yy().control_points;\n        doable = true;\n    }\n\n#undef undoable\n}\n\nvoid\nis_merge_acceptable (\n    const std::vector<Mat24>& beziers,\n    const Mat24& merged_bezier,\n    const double tolerance,\n    const double alphamax,\n    double& penalty,\n    bool& is_acceptable ) {\n\n    //\n    // HELPERS\n    //\n\n    auto get_distance = [] ( const PotraceParameters &bzp, ::polyvec::BezierCurve &bz, const Eigen::Vector2d& p0, const Eigen::Vector2d& p1,\n    bool &proj_success, double &dist ) {\n        double t;\n        bzp.t_for_tangent ( p1-p0, t, proj_success );\n\n        if ( !proj_success ) {\n            return;\n        }\n\n        dist = ::polyvec::LineUtils::distance_from_point ( p0, p1, bz.pos ( t ) );\n    };\n\n    auto get_distance_signed = [] ( const PotraceParameters &bzp,  ::polyvec::BezierCurve &bz, const Eigen::Vector2d& p0, const Eigen::Vector2d& p1,\n    const Eigen::Vector2d pforsign,  bool &proj_success, double &dist ) {\n        double t;\n        bzp.t_for_tangent ( p1-p0, t, proj_success );\n\n        if ( !proj_success ) {\n            return;\n        }\n\n        const double dist_pref =  ::polyvec::LineUtils::signed_distance_from_point ( p0, p1, pforsign );\n        dist =  ::polyvec::LineUtils::signed_distance_from_point ( p0, p1, bz.pos ( t ) );\n\n        if ( dist*dist_pref < 0 ) {\n            dist = -std::abs ( dist );\n        } else {\n            dist = std::abs ( dist );\n        }\n    };\n\n    auto check_distance_a = [tolerance] ( const double dist_a ) {\n        assert_break ( dist_a >= 0 );\n\n        if ( dist_a > tolerance ) {\n            return false;\n        }\n\n        return true;\n    };\n\n    auto check_distance_b = [tolerance] ( const double dist_b ) {\n        if ( dist_b < -tolerance ) {\n            return false;\n        }\n\n        return true;\n    };\n\n\n\n    //\n    // Loop over all beziers. Calculate the dist_a and dist_b distances\n    // from the potrace paper.\n    //\n    penalty = 0;\n    is_acceptable = true;\n    ::polyvec::BezierCurve eval_ctx;\n    eval_ctx.set_control_points ( merged_bezier );\n    PotraceParameters project_ctx;\n    project_ctx = PointParameters ( {merged_bezier} ).as_potrace_params();\n\n    //\n    // Check alpha\n    //\n    if ( project_ctx.alpha > alphamax ) {\n        is_acceptable = false;\n        return;\n    }\n\n    //\n    // Check distace\n    //\n    for ( int i = 0 ; i < ( int ) beziers.size() ; ++i ) {\n\n        // dist a\n        const Eigen::Vector2d a = PointParameters ( {beziers[i]} ).as_potrace_params().get_oy();\n\n        if ( i < ( int ) beziers.size() -1 ) {\n            const Eigen::Vector2d anext = PointParameters ( {beziers[i+1]} ).as_potrace_params().get_oy();\n            bool can_project;\n            double dist_a;\n            get_distance ( project_ctx, eval_ctx, a, anext, can_project, dist_a );\n\n            if ( ( !can_project ) || ( !check_distance_a ( dist_a ) ) ) {\n                is_acceptable = false;\n                return;\n            }\n\n            penalty += dist_a * dist_a;\n        } // end of dist a\n\n        // dist b\n        {\n            const Eigen::Vector2d b = beziers[i].col ( 0 );\n            const Eigen::Vector2d bnext =  beziers[i].col ( 3 );\n            bool can_project;\n            double dist_b;\n            get_distance_signed ( project_ctx, eval_ctx, b, bnext, a, can_project, dist_b );\n\n            if ( ( !can_project ) || ( !check_distance_b ( dist_b ) ) ) {\n                is_acceptable = false;\n                return;\n            }\n\n            penalty += dist_b * dist_b;\n        } // end of dist b\n    } // end of beziers\n\n} //  merge_penalty()\n\nvoid merge_penalty (\n    const std::vector<Mat24>& beziers,\n    const Mat24& merged_bezier,\n    double& penalty ) {\n\n    // Do a one sided projection of the points\n    constexpr int n_samples = 10;\n\n    penalty = 0;\n    ::polyvec::BezierCurve big_eval_ctx;\n    big_eval_ctx.set_control_points ( merged_bezier );\n\n    for ( int i = 0 ; i < ( int ) beziers.size() ; ++i ) {\n        ::polyvec::BezierCurve sub_eval_ctx;\n        sub_eval_ctx.set_control_points ( beziers[i] );\n        // This is a question . Should we multiply by length?\n        const double weight = 1. / n_samples *  sub_eval_ctx.length();\n        // Perhaps not\n        // const double weight = 1. / n_samples;\n\n\n        for ( int j = 1 ; j < ( n_samples+1 ) ; ++j ) {\n            const double t_sub = 1. / ( n_samples+1 ) * j ;\n            const Eigen::Vector2d point_sub = sub_eval_ctx.pos ( t_sub );\n            const double t_big = big_eval_ctx.project ( point_sub );\n            const Eigen::Vector2d point_big = big_eval_ctx.pos ( t_big );\n            penalty += weight * ( point_big-point_sub ).norm();\n        } // end of points\n    }  // end of bezeirs\n}\n\nvoid\nmerge_curves (\n    const std::vector<Eigen::Matrix2Xd>& curves_in, // lines of bezier control points\n    const bool is_circular,\n    const MergeRecursivelyOptions options,\n\tconst std::set<Regularity::SymmetryPair>& symmetric_curves,\n    std::vector<Eigen::Matrix2Xd>& curves_out,\n    std::vector<std::vector<int>>& out2in  ) {\n\n    const int n_curves = ( int ) curves_in.size();\n\n    //\n    // Check if a curve is right after a corner\n    //\n    auto is_line_after_corner = [&n_curves, &curves_in, &is_circular] ( const int i ) {\n        if ( ( i == 0 ) && ( !is_circular ) ) {\n            return false;\n        } else {\n            const int iprev = ( ( i-1 )+n_curves ) %n_curves;\n\n            if ( ( curves_in[iprev].cols() == 2 )\n                    && ( curves_in[i].cols() == 2 ) ) {\n                return true;\n            } else {\n                return false;\n            }\n        }\n    };\n\n    //\n    // Prepare the data for a merge curve\n    //\n    auto get_merge_data = [&n_curves, &curves_in, &is_circular]\n                          ( const int i,\n                            const int n_merge,\n                            std::vector<Mat22>& line_begin,\n                            std::vector<Mat24>& beziers,\n                            std::vector<Mat22>& line_end,\n    std::vector<int>& parent_ids ) {\n\n        assert_break ( is_circular || ( n_merge+i<=n_curves ) );\n        line_begin.resize ( 0 );\n        line_end.resize ( 0 );\n        beziers.resize ( 0 );\n        parent_ids.resize ( 0 );\n\n        for ( int offset = 0 ; offset < n_merge ; ++offset ) {\n            const int curve_id = ( i + offset ) %n_curves;\n\n            if ( ( curves_in[curve_id].cols() == 2 ) && ( offset==0 ) ) {\n                line_begin.push_back ( curves_in[curve_id] );\n            } else if ( ( curves_in[curve_id].cols() == 2 ) && ( offset==n_merge-1 ) ) {\n                line_end.push_back ( curves_in[curve_id] );\n            } \n            else {\n                assert_break ( curves_in[curve_id].cols() == 4 );\n                beziers.push_back ( curves_in[curve_id] );\n            }\n\n            parent_ids.push_back ( curve_id );\n        }\n\n    };\n\n    //\n    // Convert a curves end or begin point into node ids\n    //\n    auto n_graph_nodes = [&is_circular, &curves_in, &n_curves]() {\n        if ( is_circular  ) {\n            return n_curves;\n        } else {\n            return n_curves+1;\n        }\n    };\n    auto curve_end_node = [&is_circular, &curves_in, &n_curves] ( const int i ) {\n        if ( is_circular && ( i == n_curves-1 ) ) {\n            return 0;\n        } else {\n            return i+1;\n        }\n    };\n    auto curve_begin_node = [&is_circular, &curves_in, &n_curves] ( const int i ) {\n        return i;\n    };\n\n    //\n    // All the possible merge situations\n    //\n    std::vector<ShortestPath::Node> graph_nodes ( n_graph_nodes() );\n    std::map<std::pair<int, int>, int> mc_map;\n    std::vector<double> mc_penalty;\n    std::vector<std::vector<int>> mc_parent_ids;\n    std::vector<Eigen::Matrix2Xd> mc_pts;\n\n    //\n    // Create all the merge candidates\n    //\n    {\n        std::vector<Mat22> line_begin;\n        std::vector<Mat24> beziers;\n        std::vector<Mat22> line_end;\n        ShortestPath::Node node;\n        std::vector<int> parent_ids;\n        Mat24 merged_bezier;\n        bool is_merge_doable;\n        double potrace_penalty;\n        double distace_penalty;\t\t\n\n        for ( int cbeginid = 0 ; cbeginid < n_curves ; ++cbeginid ) {\n            const int max_n_merge = is_circular ? n_curves : n_curves - cbeginid;\n\n\t\t\t// find the next symmetry pair after the current curve\n\t\t\tauto next_symmetry = std::lower_bound(symmetric_curves.begin(), symmetric_curves.end(), Regularity::SymmetryPair(cbeginid, cbeginid, -1));\n\t\t\tif (next_symmetry == symmetric_curves.end())\n\t\t\t\tnext_symmetry = symmetric_curves.begin(); //wrap around\n\n\t\t\t// We employ the following strategy to promote symmetries:\n\t\t\t// A merge is only valid if all its symmetries are completely within the\n\t\t\t// merge or none is (i.e., it is ok if only one curve of symmetry pairs\n\t\t\t// is within the merge). This is evaluated independently for each \n\t\t\t// participating symmetric region\n\n\t\t\tstruct SymmetryInfo\n\t\t\t{\n\t\t\t\t// stores the number of symmetric pairs that are completely\n\t\t\t\t// contained\n\t\t\t\tint n_complete_symmetries = 0;\n\n\t\t\t\t// stores the number of symmetric paris where only one part is\n\t\t\t\t// contained\n\t\t\t\tint n_partial_symmetries = 0;\n\t\t\t};\n\n\t\t\tstd::map<int, SymmetryInfo> symmetry_info;\n\n            for ( int n_merge = 1 ; n_merge <= max_n_merge ; ++n_merge ) {\n\n\t\t\t\tconst int cendid = (cbeginid + n_merge - 1) % n_curves;\n\t\t\t\t\n\t\t\t\t// check if we have new symmetries\n\t\t\t\twhile (next_symmetry != symmetric_curves.end() && next_symmetry->first == cendid)\n\t\t\t\t{\n\t\t\t\t\tauto& info = symmetry_info[next_symmetry->region];\n\t\t\t\t\t// check if the other curve is already in the merge\n\t\t\t\t\tif (PathUtils::contains_closed(curves_in.size(), cbeginid, cendid, next_symmetry->second, is_circular))\n\t\t\t\t\t{\n\t\t\t\t\t\t++info.n_complete_symmetries;\n\t\t\t\t\t\t--info.n_partial_symmetries;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\t++info.n_partial_symmetries;\n\n\t\t\t\t\t++next_symmetry;\n\t\t\t\t\tif (next_symmetry == symmetric_curves.end())\n\t\t\t\t\t\tnext_symmetry = symmetric_curves.begin(); //wrap around\n\t\t\t\t}\n\n                // If n_merge is just 1 then we don't have to do much\n                // The fit is accepted and the error is 0\n                if ( n_merge==1 ) {\n                    mc_pts.push_back ( curves_in[cbeginid] );\n                    mc_penalty.push_back ( 0 );\n                    mc_parent_ids.push_back ( {cbeginid} );\n                } else {\n\t\t\t\t\t\n                    // Check that we do not pass a corner                    \n                    const int cendidm1 = ( cbeginid+n_merge-2 ) %n_curves;\n\n                    // Handle lines\n                    if ( options.allow_merging_lines ) {\n                        // If were were fitting to potrace data this should be enough\n                        if (  is_line_after_corner ( cendid ) ) {\n                            break;\n                        }\n                        // For ed's assymetric case, we also need this\n                        if ( ( curves_in[cendidm1].cols() == 2 ) && ( cendidm1 != cbeginid) ) {\n                            break;\n                        }\n                    }\n\n                    // New strategy, should work for Ed too\n                    // Simply don't let cbeginid or cendid to become line\n                    // basically we are not attempting to merge lines with anything\n                    if ( !options.allow_merging_lines ) {\n                        if ( ( curves_in[cbeginid].cols() == 2 ) || ( curves_in[cendid].cols() == 2 ) ) {\n                            break;\n                        }\n                    }\n\n\t\t\t\t\tbool symmetry_valid = true;\n\t\t\t\t\tfor(auto& info : symmetry_info)\n\t\t\t\t\t\tif (info.second.n_complete_symmetries > 0 && info.second.n_partial_symmetries > 0)\n\t\t\t\t\t\t\tsymmetry_valid = false; // violates symmetry\n\t\t\t\t\tif (!symmetry_valid)\n\t\t\t\t\t\tcontinue;\n\n                    // Get info needed for merging\n                    get_merge_data ( cbeginid, n_merge, line_begin, beziers, line_end, parent_ids );\n\n                    // Merge the curve\n                    merged_curve ( line_begin, beziers, line_end, nullptr, is_merge_doable, merged_bezier );\n\n                    if ( !is_merge_doable ) {\n                        continue;\n                    }\n\n                    // Check if acceptable\n                    is_merge_acceptable ( beziers, merged_bezier, options.distance_tolerance, options.alpha_max, potrace_penalty, is_merge_doable );\n\n                    if ( !is_merge_doable ) {\n                        continue;\n                    }\n\n                    // Find the penalty\n                    merge_penalty ( beziers, merged_bezier, distace_penalty );\n\n                    // Add to the curve to nodes\n                    mc_pts.push_back ( merged_bezier );\n                    mc_penalty.push_back ( distace_penalty );\n                    mc_parent_ids.push_back ( parent_ids );\n\n                } // end of more than one curve\n\n            } // end of n_merge\n        } // end of begin id\n    } // end of creating the merge candidates\n\n\n    //\n    // Now create a graph\n    //\n    for ( int node_id = 0 ; node_id < n_graph_nodes() ; ++node_id  ) {\n        graph_nodes[node_id].v = node_id;\n    }\n\n    for ( int mcid = 0 ; mcid < ( int ) mc_parent_ids.size() ; ++mcid ) {\n        const int node_from = curve_begin_node ( mc_parent_ids[mcid].front() );\n        const int node_to = curve_end_node ( mc_parent_ids[mcid].back() );\n        graph_nodes[node_from].add_neighbor(node_to, mc_penalty[mcid] + options.per_bezier_const );\n        mc_map.insert ( std::make_pair ( std::make_pair ( node_from, node_to ), mcid ) );\n    }\n\n\n    // Find the shortest path\n    {\n        std::vector<Eigen::Index> P;\n        ShortestPath::State state;\n\n        if ( is_circular ) {\n            ShortestPath::find_cycle ( state, graph_nodes, {0}, P );\n            // Debugging\n            // ShortestPath::print_graph ( graph_nodes, stderr );\n        } else {\n            ShortestPath::find ( state, graph_nodes, 0, n_graph_nodes()-1, P );\n        }\n\n        const int max_node_offset = is_circular ? ( int ) P.size() : ( int ) P.size()-1;\n\n        curves_out.resize ( 0 );\n        out2in.resize ( 0 );\n\n        for ( int nodeoffset = 0 ; nodeoffset <  max_node_offset ; ++nodeoffset ) {\n            const int node_from = (int)P[nodeoffset];\n            const int node_to = (int)P[ ( nodeoffset+1 ) %P.size()];\n            auto mc_id_it = mc_map.find ( std::make_pair ( node_from, node_to ) );\n            assert_break ( mc_id_it != mc_map.end() );\n            const int mc_id = (int)mc_id_it->second;\n\n            curves_out.push_back ( mc_pts[ mc_id ] );\n            out2in.push_back ( mc_parent_ids[ mc_id ] );\n        }\n\n    }\n\n} // merge_recursively()\n\nNAMESPACE_END ( BezierMerging )\nNAMESPACE_END ( polyfit )\n\n", "meta": {"hexsha": "2e8247adc911a70ef13a99d4f343d11a25116516", "size": 31639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/polyvec/curve-tracer/bezier_merging.cpp", "max_stars_repo_name": "ShnitzelKiller/polyfit", "max_stars_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T17:25:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T05:49:12.000Z", "max_issues_repo_path": "source/polyvec/curve-tracer/bezier_merging.cpp", "max_issues_repo_name": "ShnitzelKiller/polyfit", "max_issues_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-08-26T13:54:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T07:19:22.000Z", "max_forks_repo_path": "source/polyvec/curve-tracer/bezier_merging.cpp", "max_forks_repo_name": "ShnitzelKiller/polyfit", "max_forks_repo_head_hexsha": "51ddc6365a794db1678459140658211cb78f65b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-26T23:26:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-04T09:06:07.000Z", "avg_line_length": 30.7473275024, "max_line_length": 165, "alphanum_fraction": 0.524763741, "num_tokens": 8742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744584140003, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.43112052101480314}}
{"text": "//\n// Implements Tree-iLQR.\n//\n// Arun Venkatraman (arunvenk@cs.cmu.edu)\n// December 2016\n//\n\n#pragma once\n\n#include <ilqr/tree.hh>\n#include <ilqr/ilqr_node.hh>\n\n#include <Eigen/Dense>\n\n#include <memory>\n#include <list>\n#include <vector>\n\nnamespace ilqr\n{\n\n// State-Action-Cost-Value(CostToGo).\nstruct SACV\n{\n    Eigen::VectorXd x;\n    Eigen::VectorXd u;\n    double c;\n    double probability;\n    double value;\n};\n\n// Shared pointer to a Node in the underlying Tree structure of the iLQR-Tree. Calling ->item()\n// returns a shared pointer to the iLQRNode that holds the state/control/dynamics/etc.\n// information.\nusing TreeNodePtr = std::shared_ptr<data::Node<iLQRNode>>;\n\nclass iLQRTree \n{\npublic:\n    iLQRTree(int state_dim, int control_dim);\n    virtual ~iLQRTree() = default;\n\n    // Construct a iLQRNode which represents the dynamics, cost functions as\n    // well as the state and control policy at a specific time step along the\n    // tree. Nominal state and control inputs are passed and used for the\n    // initial Taylor expansions of the cost and dynamics functions.\n    std::shared_ptr<iLQRNode> make_ilqr_node(const Eigen::VectorXd &x_star,\n            const Eigen::VectorXd &u_star, const DynamicsFunc &dynamics, const\n            CostFunc &cost, const double probablity);\n\n    // Add the root node to the iLQR Tree with similar arguments to the\n    // make_ilqr_node function.\n    TreeNodePtr add_root(const Eigen::VectorXd &x_star, const Eigen::VectorXd\n            &u_star, const DynamicsFunc &dynamics, const CostFunc &cost);\n    \n    // Add a iLQRNode as the root node to the iLQR Tree. Requires the\n    // probability to be 1. \n    TreeNodePtr add_root(const std::shared_ptr<iLQRNode> &ilqr_node);\n\n    // Add a list of iLQRNodes as children under a parent. The probabilities\n    // must sum to 1.\n    std::vector<TreeNodePtr> add_nodes(const\n            std::vector<std::shared_ptr<iLQRNode>> &ilqr_nodes, TreeNodePtr\n            &parent);\n\n    // Get the root node of the Tree.\n    TreeNodePtr root();\n\n    // Forward pass to generate new nominal points for iLQR.\n    // The step-size is controlled by alpha (alpha * K).\n    void forward_tree_update(const double alpha);\n\n    // Do a full bellman backup on the tree.\n    void bellman_tree_backup();\n\n    // Returns a Tree of states-action-costs-value with expected cost-to-gos.\n    data::Tree<SACV> forward_pass(const Eigen::VectorXd &x0, const TreeNodePtr &top = nullptr, const double top_alpha = 1.0);\n\nprivate:\n    int state_dim_ = 0;\n    int control_dim_ = 0;\n\n    data::Tree<iLQRNode> tree_;\n\n    // Zeros matrix of size [state_dim +1] x [state_dim +1]. Used as\n    // initialization for the zeros matrix.\n    const QuadraticValue ZERO_VALUE_; \n\n    // Special case for just the leaves of the tree. We can compute this by\n    // giving the leaves synthetic children with $V_{T+1} = 0$.\n    void control_and_value_for_leaves();\n\n    // Backups the value matrix and control gains matrix from the children of\n    // the node to get the value and control policies for the parents of the\n    // children. Returns a list of all the parents.\n    std::list<TreeNodePtr> backup_to_parents(const std::list<TreeNodePtr>\n            &all_children);\n\n};\n\n} // namespace ilqr\n", "meta": {"hexsha": "ec199ce3c9f3b2db120027d9319e52f323c0a77e", "size": 3241, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/ilqr/ilqr_tree.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/ilqr/ilqr_tree.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ilqr/ilqr_tree.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 31.7745098039, "max_line_length": 125, "alphanum_fraction": 0.6970070966, "num_tokens": 827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.4310517782347008}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file interpolateddiscountcurve.hpp\n    \\brief interpolated discount term structure\n    \\ingroup termstructures\n*/\n\n#ifndef quantext_interpolated_discount_curve_hpp\n#define quantext_interpolated_discount_curve_hpp\n\n#include <boost/make_shared.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <qle/quotes/logquote.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\n\n//! InterpolatedDiscountCurve based on loglinear interpolation of DiscountFactors\n/*! InterpolatedDiscountCurve based on loglinear interpolation of DiscountFactors,\n    flat fwd extrapolation is always enabled, the term structure has always a\n    floating reference date\n\n        \\ingroup termstructures\n    */\nclass InterpolatedDiscountCurve : public YieldTermStructure {\npublic:\n    enum class Interpolation { logLinear, linearZero };\n    enum class Extrapolation { flatFwd, flatZero };\n    //! \\name Constructors\n    //@{\n    //! default constructor\n    InterpolatedDiscountCurve(const std::vector<Time>& times, const std::vector<Handle<Quote>>& quotes,\n                              const Natural settlementDays, const Calendar& cal, const DayCounter& dc,\n                              const Interpolation interpolation = Interpolation::logLinear,\n                              const Extrapolation extrapolation = Extrapolation::flatFwd)\n        : YieldTermStructure(settlementDays, cal, dc), times_(times), interpolation_(interpolation),\n          extrapolation_(extrapolation) {\n        initalise(quotes);\n    }\n\n    //! constructor that takes a vector of dates\n    InterpolatedDiscountCurve(const std::vector<Date>& dates, const std::vector<Handle<Quote>>& quotes,\n                              const Natural settlementDays, const Calendar& cal, const DayCounter& dc,\n                              const Interpolation interpolation = Interpolation::logLinear,\n                              const Extrapolation extrapolation = Extrapolation::flatFwd)\n        : YieldTermStructure(settlementDays, cal, dc), times_(dates.size()), interpolation_(interpolation),\n          extrapolation_(extrapolation) {\n        for (Size i = 0; i < dates.size(); ++i)\n            times_[i] = timeFromReference(dates[i]);\n        initalise(quotes);\n    }\n    //@}\n\nprivate:\n    void initalise(const std::vector<Handle<Quote>>& quotes) {\n        QL_REQUIRE(times_.size() > 1, \"at least two times required\");\n        QL_REQUIRE(times_[0] == 0.0, \"First time must be 0, got \" << times_[0]); // or date=asof\n        QL_REQUIRE(times_.size() == quotes.size(), \"size of time and quote vectors do not match\");\n        for (Size i = 0; i < quotes.size(); ++i) {\n            quotes_.push_back(boost::make_shared<LogQuote>(quotes[i]));\n        }\n        for (Size i = 0; i < times_.size() - 1; ++i)\n            timeDiffs_.push_back(times_[i + 1] - times_[i]);\n    }\n\n    //! \\name TermStructure interface\n    //@{\n    Date maxDate() const { return Date::maxDate(); } // flat fwd extrapolation\n    //@}\n\nprotected:\n    DiscountFactor discountImpl(Time t) const {\n        if (t > this->times_.back() && extrapolation_ == Extrapolation::flatZero) {\n            Real tMax = this->times_.back();\n            Real dMax = std::exp(quotes_.back()->value());\n            return std::pow(dMax, t / tMax);\n        }\n        std::vector<Time>::const_iterator it = std::upper_bound(times_.begin(), times_.end(), t);\n        Size i = std::min<Size>(it - times_.begin(), times_.size() - 1);\n        Real weight = (times_[i] - t) / timeDiffs_[i - 1];\n        if (interpolation_ == Interpolation::logLinear || t > this->times_.back()) {\n            // this handles flat fwd extrapolation (t > times.back()) as well\n            Real value = (1.0 - weight) * quotes_[i]->value() + weight * quotes_[i - 1]->value();\n            return ::exp(value);\n        } else {\n            Real value =\n                (1.0 - weight) * quotes_[i]->value() / times_[i] + weight * quotes_[i - 1]->value() / times_[i - 1];\n            return ::exp(t * value);\n        }\n    }\n\nprivate:\n    std::vector<Time> times_;\n    std::vector<Time> timeDiffs_;\n    std::vector<boost::shared_ptr<Quote>> quotes_;\n    Interpolation interpolation_;\n    Extrapolation extrapolation_;\n};\n\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "c0ba7f97b102a6003ba71f7da6fee782e6450731", "size": 4984, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/interpolateddiscountcurve.hpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/termstructures/interpolateddiscountcurve.hpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/termstructures/interpolateddiscountcurve.hpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 41.8823529412, "max_line_length": 116, "alphanum_fraction": 0.6546950241, "num_tokens": 1165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4309898154392066}}
{"text": "//=======================================================================\n// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file bounded_degree_mst_oracle.hpp\n * @brief\n * @author Piotr Godlewski\n * @version 1.0\n * @date 2013-06-05\n */\n#ifndef PAAL_BOUNDED_DEGREE_MST_ORACLE_HPP\n#define PAAL_BOUNDED_DEGREE_MST_ORACLE_HPP\n\n#include \"paal/iterative_rounding/min_cut.hpp\"\n#include \"paal/lp/lp_base.hpp\"\n\n#include <boost/optional.hpp>\n#include <boost/range/as_array.hpp>\n\n#include <vector>\n\nnamespace paal {\nnamespace ir {\n\n/**\n * @class bdmst_violation_checker\n * @brief Violations checker for the separation oracle\n *      in the bounded degree minimum spanning tree problem.\n */\nclass bdmst_violation_checker {\n    using AuxEdge = min_cut_finder::Edge;\n    using AuxVertex = min_cut_finder::Vertex;\n    using AuxEdgeList = std::vector<AuxEdge>;\n    using Violation = boost::optional<double>;\n\n  public:\n    using Candidate = std::pair<AuxVertex, AuxVertex>;\n    using CandidateList = std::vector<Candidate>;\n\n    /**\n     * Returns an iterator range of violated constraint candidates.\n     */\n    template <typename Problem, typename LP>\n    const CandidateList &get_violation_candidates(const Problem &problem,\n                                                  const LP &lp) {\n        fill_auxiliary_digraph(problem, lp);\n        initialize_candidates(problem);\n        return m_candidate_list;\n    }\n\n    /**\n     * Checks if the given constraint candidate is violated an if it is,\n     * returns the violation value and violated constraint ID.\n     */\n    template <typename Problem>\n    Violation check_violation(Candidate candidate, const Problem &problem) {\n        double violation = find_violation(candidate.first, candidate.second);\n        if (problem.get_compare().g(violation, 0)) {\n            return violation;\n        } else {\n            return Violation{};\n        }\n    }\n\n    /**\n     * Adds a violated constraint to the LP.\n     */\n    template <typename Problem, typename LP>\n    void add_violated_constraint(Candidate violating_pair,\n                                 const Problem &problem, LP &lp) {\n        if (violating_pair != m_min_cut.get_last_cut()) {\n            find_violation(violating_pair.first, violating_pair.second);\n        }\n\n        auto const &g = problem.get_graph();\n        auto const &index = problem.get_index();\n\n        lp::linear_expression expr;\n        for (auto const &e : problem.get_edge_map().right) {\n            auto u = get(index, source(e.second, g));\n            auto v = get(index, target(e.second, g));\n            if (m_min_cut.is_in_source_set(u) &&\n                m_min_cut.is_in_source_set(v)) {\n                expr += e.first;\n            }\n        }\n        lp.add_row(std::move(expr) <= m_min_cut.source_set_size() - 2);\n    }\n\n  private:\n\n    /**\n     * Creates the auxiliary directed graph used for feasibility testing.\n     */\n    template <typename Problem, typename LP>\n    void fill_auxiliary_digraph(const Problem &problem, const LP &lp) {\n        auto const &g = problem.get_graph();\n        auto const &index = problem.get_index();\n        m_vertices_num = num_vertices(g);\n        m_min_cut.init(m_vertices_num);\n        m_src_to_v.resize(m_vertices_num);\n        m_v_to_trg.resize(m_vertices_num);\n\n        for (auto const &e : problem.get_edge_map().right) {\n            lp::col_id col_idx = e.first;\n            double col_val = lp.get_col_value(col_idx) / 2;\n\n            if (!problem.get_compare().e(col_val, 0)) {\n                auto u = get(index, source(e.second, g));\n                auto v = get(index, target(e.second, g));\n                m_min_cut.add_edge_to_graph(u, v, col_val, col_val);\n            }\n        }\n\n        m_src = m_min_cut.add_vertex_to_graph();\n        m_trg = m_min_cut.add_vertex_to_graph();\n\n        for (auto v : boost::as_array(vertices(g))) {\n            auto aux_v = get(index, v);\n            m_src_to_v[aux_v] = m_min_cut\n                .add_edge_to_graph(m_src, aux_v, degree_of(problem, v, lp) / 2)\n                .first;\n            m_v_to_trg[aux_v] =\n                m_min_cut.add_edge_to_graph(aux_v, m_trg, 1).first;\n        }\n    }\n\n    /**\n     * Initializes the list of cut candidates.\n     */\n    template <typename Problem>\n    void initialize_candidates(const Problem &problem) {\n        auto const &g = problem.get_graph();\n        auto const &index = problem.get_index();\n        auto src = *(std::next(vertices(g).first, rand() % m_vertices_num));\n        auto aux_src = get(index, src);\n        m_candidate_list.clear();\n        for (auto v : boost::as_array(vertices(g))) {\n            if (v != src) {\n                auto aux_v = get(index, v);\n                m_candidate_list.push_back(std::make_pair(aux_src, aux_v));\n                m_candidate_list.push_back(std::make_pair(aux_v, aux_src));\n            }\n        }\n    }\n\n    /**\n     * Calculates the sum of the variables for edges incident with a given\n     * vertex.\n     */\n    template <typename Problem, typename LP, typename Vertex>\n    double degree_of(const Problem &problem, const Vertex &v, const LP &lp) {\n        double res = 0;\n\n        for (auto e : boost::as_array(out_edges(v, problem.get_graph()))) {\n            auto col_id = problem.edge_to_col(e);\n            if (col_id) {\n                res += lp.get_col_value(*col_id);\n            }\n        }\n        return res;\n    }\n\n    /**\n     * Finds the most violated set of vertices containing \\c src and not\n     * containing \\c trg and returns its violation value.\n     * @param src vertex to be contained in the violating set\n     * @param trg vertex not to be contained in the violating set\n     * @return violation of the found set\n     */\n    double find_violation(AuxVertex src, AuxVertex trg) {\n        double orig_cap = m_min_cut.get_capacity(m_src_to_v[src]);\n\n        m_min_cut.set_capacity(m_src_to_v[src], m_vertices_num);\n        // capacity of m_src_to_v[trg] does not change\n        m_min_cut.set_capacity(m_v_to_trg[src], 0);\n        m_min_cut.set_capacity(m_v_to_trg[trg], m_vertices_num);\n\n        double min_cut_weight = m_min_cut.find_min_cut(m_src, m_trg);\n        double violation = m_vertices_num - 1 - min_cut_weight;\n\n        // reset the original values for the capacities\n        m_min_cut.set_capacity(m_src_to_v[src], orig_cap);\n        // capacity of m_src_to_v[trg] does not change\n        m_min_cut.set_capacity(m_v_to_trg[src], 1);\n        m_min_cut.set_capacity(m_v_to_trg[trg], 1);\n\n        return violation;\n    }\n\n    int m_vertices_num;\n\n    AuxVertex m_src;\n    AuxVertex m_trg;\n\n    AuxEdgeList m_src_to_v;\n    AuxEdgeList m_v_to_trg;\n\n    CandidateList m_candidate_list;\n\n    min_cut_finder m_min_cut;\n};\n\n} //! ir\n} //! paal\n#endif // PAAL_BOUNDED_DEGREE_MST_ORACLE_HPP\n", "meta": {"hexsha": "e88adf9e3582bc67eb3ca0e29b3c9fa509f8c3b1", "size": 6990, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/iterative_rounding/bounded_degree_min_spanning_tree/bounded_degree_mst_oracle.hpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/paal/iterative_rounding/bounded_degree_min_spanning_tree/bounded_degree_mst_oracle.hpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/paal/iterative_rounding/bounded_degree_min_spanning_tree/bounded_degree_mst_oracle.hpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 33.1279620853, "max_line_length": 79, "alphanum_fraction": 0.6101573677, "num_tokens": 1643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.5506073655352405, "lm_q1q2_score": 0.430939731222091}}
{"text": "/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*-\n *\n * $Id: ext.cpp 21225 2014-11-28 21:06:02Z phyy-nx $\n */\n#include <cctbx/boost_python/flex_fwd.h>\n#include <boost/python.hpp>\n#include <boost/python/class.hpp>\n#include <scitbx/array_family/flex_types.h>\n#include <scitbx/array_family/shared.h>\n#include <scitbx/math/basic_statistics.h>\n#include <cctbx/miller.h>\n#include <cctbx/uctbx.h>\n\n/*\n\nThis file contains an implmentation of calc_avg_I from\npostrefine/mod_util.py, which averages observed intensities,\ndoes outlier rejection and computes various statistics.\n\n*/\n\nusing namespace boost::python;\n\nnamespace prime {\n  enum Average_Mode {\n    Average,  ///< normal avearaging\n    Weighted, ///< weighted averaging\n    Final     ///< averaging done when the postrefinement is finishing\n  };\n\n  typedef\n    scitbx::af::shared<cctbx::miller::index<int> > shared_miller;\n\n  struct average_result_store {\n    // class for returning results\n    shared_miller miller_index;\n    scitbx::af::shared<double> I_avg;\n    scitbx::af::shared<double> sigI_avg;\n    scitbx::af::shared<double> r_meas_w_top;\n    scitbx::af::shared<double> r_meas_w_btm;\n    scitbx::af::shared<double> r_meas_top;\n    scitbx::af::shared<double> r_meas_btm;\n    scitbx::af::shared<int> multiplicity;\n    scitbx::af::shared<double> I_avg_even;\n    scitbx::af::shared<double> I_avg_odd;\n    scitbx::af::shared<double> I_avg_even_h;\n    scitbx::af::shared<double> I_avg_odd_h;\n    scitbx::af::shared<double> I_avg_even_k;\n    scitbx::af::shared<double> I_avg_odd_k;\n    scitbx::af::shared<double> I_avg_even_l;\n    scitbx::af::shared<double> I_avg_odd_l;\n    std::string txt_obs_out;\n    std::string txt_reject_out;\n  };\n\n  class averaging_engine {\n    // interface for computing averages\n    const int group_no_;\n    const scitbx::af::shared<int> group_id_list_;\n    const shared_miller miller_index_;\n    const shared_miller miller_index_ori_;\n    const scitbx::af::shared<double> I_;\n    const scitbx::af::shared<double> sigI_;\n    const scitbx::af::shared<double> G_;\n    const scitbx::af::shared<double> B_;\n    const scitbx::af::shared<double> p_set_;\n    const scitbx::af::shared<double> rs_set_;\n    const scitbx::af::shared<double> wavelength_set_;\n    const scitbx::af::shared<double> sin_theta_over_lambda_sq_;\n    const scitbx::af::shared<double> SE_;\n    const scitbx::af::shared<std::string> pickle_filename_set_;\n    public:\n    Average_Mode avg_mode_;\n    double sigma_max_;\n    bool flag_volume_correction_;\n    int n_rejection_cycle_;\n    bool flag_output_verbose_;\n\n    public: averaging_engine(\n      // main constructor, used for passing in arrays. other parmaters exposed\n      // as properties to python\n      int group_no,\n      scitbx::af::shared<int> group_id_list,\n      const shared_miller& miller_index,\n      const shared_miller& miller_index_ori,\n      const scitbx::af::shared<double>& I,\n      const scitbx::af::shared<double>& sigI,\n      const scitbx::af::shared<double>& G,\n      const scitbx::af::shared<double>& B,\n      const scitbx::af::shared<double>& p_set,\n      const scitbx::af::shared<double>& rs_set,\n      const scitbx::af::shared<double>& wavelength_set,\n      const scitbx::af::shared<double>& sin_theta_over_lambda_sq,\n      const scitbx::af::shared<double>& SE,\n      const scitbx::af::shared<std::string>& pickle_filename_set\n      ):\n        group_no_(group_no),\n        group_id_list_(group_id_list),\n        miller_index_(miller_index),\n        miller_index_ori_(miller_index_ori),\n        I_(I),sigI_(sigI),G_(G),B_(B),p_set_(p_set),\n        rs_set_(rs_set),\n        wavelength_set_(wavelength_set),\n        sin_theta_over_lambda_sq_(sin_theta_over_lambda_sq),\n        SE_(SE),\n        pickle_filename_set_(pickle_filename_set)\n    {\n      avg_mode_ = Average;\n      sigma_max_ = 99.0;\n      flag_volume_correction_ = true;\n      n_rejection_cycle_ = 1;\n      flag_output_verbose_ = false;\n    }\n\n    void calc_avg_two_halves(\n      const scitbx::af::shared<double>& I_full_group,\n      const scitbx::af::shared<double>& SE_norm,\n      const Average_Mode& avg_mode_,\n      double& I_avg_even,\n      double& I_avg_odd\n      )\n    {\n      double I_even_sum = 0;\n      double I_odd_sum = 0;\n      double I_even_weighted_sum = 0;\n      double I_odd_weighted_sum = 0;\n      double SE_norm_even_sum = 0;\n      double SE_norm_odd_sum = 0;\n      I_avg_even = 0;\n      I_avg_odd = 0;\n      if (I_full_group.size() > 2) {\n        for (int i = 0; i < I_full_group.size(); i++) {\n          if (i % 2 == 0) {\n            I_even_sum += I_full_group[i];\n            I_even_weighted_sum += I_full_group[i] * SE_norm[i];\n            SE_norm_even_sum += SE_norm[i];\n          }\n          else {\n            I_odd_sum += I_full_group[i];\n            I_odd_weighted_sum += I_full_group[i] * SE_norm[i];\n            SE_norm_odd_sum += SE_norm[i];\n          }\n        }\n\n        if (I_full_group.size() % 2 == 1) {\n          I_odd_sum += I_full_group[I_full_group.size()-1];\n          I_odd_weighted_sum += I_full_group[I_full_group.size()-1] * SE_norm[SE_norm.size()-1];\n          SE_norm_odd_sum += SE_norm[SE_norm.size()-1];\n        }\n\n        if (avg_mode_ == Weighted || avg_mode_ == Final) {\n          I_avg_even = I_even_weighted_sum/SE_norm_even_sum;\n          I_avg_odd = I_odd_weighted_sum/SE_norm_odd_sum;\n        }\n        else {\n          SCITBX_ASSERT(avg_mode_ == Average);\n          int size;\n          if(I_full_group.size() % 2 == 1)\n            size = (I_full_group.size()+1)/2;\n          else\n            size = I_full_group.size()/2;\n          I_avg_even = I_even_sum/size;\n          I_avg_odd = I_odd_sum/size;\n        }\n      }\n    }\n\n    static const double CONST_SE_MIN_WEIGHT;\n    static const double CONST_SE_MAX_WEIGHT;\n    static const double CONST_SIG_I_FACTOR;\n\n    public: average_result_store\n    calc_avg_I() {\n      /*\n      Average the intensites.\n\n      I_ is an array with N observations.  miller_indices is an array with M indices.\n      M should always be <= N. Observations are arranged into groups where the members\n      of the same group have the same miller index.  group_id_list is N long and indexes\n      each observation to a group and its miller index. group_id_list should be sorted\n      (ascending) and that sort order applied to G, B, etc.\n      */\n\n      average_result_store results;\n      std::ostringstream txt_obs_out;\n      std::ostringstream txt_reject_out;\n\n      // convert to the full intensity and calculate mosaic spread (currently only logged)\n      scitbx::af::shared<double> I_full;\n      scitbx::af::shared<double> sigI_full;\n      scitbx::af::shared<double> mosaic_radian_set;\n      for(int x = 0; x < G_.size(); x++) {\n        double tmp1 = G_[x] *std::exp(-2*B_[x]*sin_theta_over_lambda_sq_[x]);\n        double tmp2 = I_[x];\n        double tmp3 = p_set_[x];\n        if (x==0)\n          printf(\"c++ check overflow: %70.70f\\n\",tmp1*tmp2); // Without this printf, I_full comes out differently between\n                                                               // python and cpp in the highest significant digits. No idea why.\n        I_full.push_back(tmp2/(tmp1*tmp3));\n        sigI_full.push_back(sigI_[x]/(G_[x] * std::exp(-2*B_[x]*sin_theta_over_lambda_sq_[x]) * p_set_[x]));\n        mosaic_radian_set.push_back(2 * rs_set_[x] * wavelength_set_[x]);\n      }\n\n      if (flag_volume_correction_)\n        for (int x = 0; x < I_full.size(); x++){\n          I_full[x] *= (4.0/3.0) * (rs_set_[x]);\n          sigI_full[x] *= (4.0/3.0) * (rs_set_[x]);\n        }\n\n      // Iterate over each group of intensites. They will match a single miller_index each\n      int obs_ptr = 0; // this will track along the intensites array as each group is processed\n      for (int g = 0; g < group_no_; g++) {\n        SCITBX_ASSERT(group_id_list_[obs_ptr] == g); // this verifies that group_id_list is sorted\n\n        int obs_ptr_start = obs_ptr;\n\n        // gather intensites and errors for this group\n        double max_w = CONST_SE_MAX_WEIGHT;\n        double min_w = std::sqrt(CONST_SE_MIN_WEIGHT);\n        scitbx::af::shared<double> I_group;\n        scitbx::af::shared<double> sigI_group;\n        scitbx::af::shared<double> I_full_group;\n        scitbx::af::shared<double> sigI_full_group;\n        scitbx::af::shared<double> SE_group;\n        cctbx::miller::index<int> current_index;\n        shared_miller current_index_ori;\n        scitbx::af::shared<std::string>pickle_filename_set_group;\n        std::ostringstream txt_reject_out_group;\n\n        scitbx::af::shared<int> valid_ptrs;\n\n        bool found_one = false;\n        while (obs_ptr < I_.size()) {\n          if (group_id_list_[obs_ptr] != g) {\n            break; // found them all\n          }\n\n          if (found_one) {\n            SCITBX_ASSERT(current_index == miller_index_[obs_ptr]);\n          }\n          else {\n            found_one = true;\n            current_index = miller_index_[obs_ptr];\n          }\n          I_group.push_back(I_[obs_ptr]);\n          sigI_group.push_back(sigI_[obs_ptr]);\n          I_full_group.push_back(I_full[obs_ptr]);\n          sigI_full_group.push_back(sigI_full[obs_ptr]);\n          SE_group.push_back(SE_[obs_ptr]);\n          current_index_ori.push_back(miller_index_ori_[obs_ptr]);\n          pickle_filename_set_group.push_back(pickle_filename_set_[obs_ptr]);\n          valid_ptrs.push_back(obs_ptr);\n          obs_ptr++;\n        }\n        SCITBX_ASSERT(found_one);\n\n        // log\n        char buf[512];\n        sprintf(buf, \"Reflection: %d,%d,%d\\nmeanI    medI  sigI_est sigI_true delta_sigI   n_refl\\n\",current_index[0],current_index[1],current_index[2]);\n        txt_obs_out << buf;\n        scitbx::af::shared<double> I_full_group_copy;\n        for (int i = 0; i < I_full_group.size(); i++)\n          I_full_group_copy.push_back(I_full_group[i]);\n        scitbx::math::basic_statistics<double> basic_stat(I_full_group_copy.const_ref());\n        scitbx::math::median_functor mf;\n\n        double median_I = mf(I_full_group_copy.ref());\n        double mean_I = basic_stat.mean;\n        double std_I = 0;\n        //if (I_full_group.size() > 1)\n        std_I = basic_stat.biased_standard_deviation; // based on what I think numpy is doing compared to basic_statistics\n\n        sprintf(buf, \"%6.2f %6.2f %8.2f %8.0f\\n\", mean_I, median_I, std_I, double(I_full_group.size()));\n        txt_obs_out << buf;\n\n        //reject outliers\n        if (I_full_group.size() > 2) {\n          for (int i_rejection = 0; i_rejection < n_rejection_cycle_; i_rejection++) {\n            scitbx::af::shared<double> I_full_group_copy;\n            for (int i = 0; i < I_full_group.size(); i++)\n              I_full_group_copy.push_back(I_full_group[i]);\n            scitbx::math::basic_statistics<double> basic_stat(I_full_group_copy.const_ref());\n            scitbx::math::median_functor mf;\n\n            scitbx::af::shared<double> I_group_filtered;\n            scitbx::af::shared<double> sigI_group_filtered;\n            scitbx::af::shared<double> I_full_group_filtered;\n            scitbx::af::shared<double> sigI_full_group_filtered;\n            scitbx::af::shared<double> SE_group_filtered;\n            shared_miller current_index_ori_filtered;\n            scitbx::af::shared<std::string> pickle_filename_set_group_filtered;\n\n            scitbx::af::shared<int> valid_ptrs_filtered;\n\n            double median_I = mf(I_full_group_copy.ref());\n            double mean_I = basic_stat.mean;\n            double std_I = basic_stat.biased_standard_deviation; // based on what I think numpy is doing compared to basic_statistics\n\n            for (int i = 0; i < I_full_group.size(); i++) {\n              double I_full_as_sigma = (I_full_group[i] - median_I) / std_I;\n              if (std::abs(I_full_as_sigma) > sigma_max_) {\n                char buf[512];\n                sprintf(buf, \"%s %3.0f %3.0f %3.0f %10.2f %10.2f\\n\", pickle_filename_set_group[i].c_str(),\n                  double(current_index_ori[i][0]), double(current_index_ori[i][1]), double(current_index_ori[i][2]), I_group[i], sigI_group[i]);\n                txt_reject_out_group << buf;\n              }\n              else {\n                I_group_filtered.push_back(I_group[i]);\n                sigI_group_filtered.push_back(sigI_group[i]);\n                I_full_group_filtered.push_back(I_full_group[i]);\n                sigI_full_group_filtered.push_back(sigI_full_group[i]);\n                SE_group_filtered.push_back(SE_group[i]);\n                current_index_ori_filtered.push_back(current_index_ori[i]);\n                pickle_filename_set_group_filtered.push_back(pickle_filename_set_group[i]);\n                valid_ptrs_filtered.push_back(valid_ptrs[i]);\n              }\n            }\n            I_group = I_group_filtered;\n            sigI_group = sigI_group_filtered;\n            I_full_group = I_full_group_filtered;\n            sigI_full_group = sigI_full_group_filtered;\n            SE_group = SE_group_filtered;\n            current_index_ori = current_index_ori_filtered;\n            pickle_filename_set_group = pickle_filename_set_group_filtered;\n            valid_ptrs = valid_ptrs_filtered;\n\n            char buf[512];\n            sprintf(buf, \"%6.2f %6.2f %8.2f %8.0f\\n\", mean_I, median_I, std_I, double(I_full_group.size()));\n            txt_obs_out << buf;\n\n            if (I_full_group.size() <= 3)\n              break;\n          }\n          if (I_full_group.size() == 0) {\n            printf(\"miller_index (%d, %d, %d) rejected at calc_avg\", current_index[0], current_index[1], current_index[2]);\n            continue;\n          }\n        }\n        // normalize the SE\n        scitbx::af::shared<double> SE_norm;\n        double se_max = scitbx::af::max(SE_group.ref());\n        double se_min = scitbx::af::min(SE_group.ref());\n        double SE_norm_val;\n        if (SE_group.size() == 1 || ((se_max-se_min) < 0.1) || avg_mode_ == Average) {\n          SE_norm_val = 1;\n          for (int i = 0; i < SE_group.size(); i++) {\n            SE_norm.push_back(SE_norm_val);\n          }\n        }\n        else {\n          double m = (max_w - min_w)/(se_min-se_max);\n          double b = max_w - (m*se_min);\n\n          for (int i = 0; i < SE_group.size(); i++) {\n            SE_norm.push_back( (m*SE_group[i]) + b);\n          }\n        }\n\n        double SE_norm_sum = scitbx::af::sum(SE_norm.const_ref());\n        SCITBX_ASSERT(SE_norm_sum != 0);\n        scitbx::af::shared<double> avg_tmp;\n        for (int i = 0; i < SE_norm.size(); i++) {\n          avg_tmp.push_back(SE_norm[i] * I_full_group[i]);\n        }\n\n        double I_avg = scitbx::af::sum(avg_tmp.const_ref())/SE_norm_sum;\n        double sigI_avg = scitbx::af::mean(sigI_full_group.const_ref());\n\n        //Rmeas, Rmeas_w, multiplicity\n        int multiplicity = I_full_group.size();\n        double r_meas_w_top = 0;\n        double r_meas_w_btm = 0;\n        double r_meas_top = 0;\n        double r_meas_btm = 0;\n        double r_meas = 0;\n        double r_meas_w = 0;\n        if (multiplicity > 1) {\n          for (int i = 0; i < multiplicity; i++) {\n            r_meas_w_top += std::pow(((I_full_group[i] - I_avg)*SE_norm[i]),2);\n            r_meas_w_btm += std::pow(I_full_group[i]*SE_norm[i],2);\n            r_meas_top += std::abs(((I_full_group[i] - I_avg)*SE_norm[i]));\n            r_meas_btm += std::abs(I_full_group[i]*SE_norm[i]);\n          }\n          r_meas_w = r_meas_w_top/r_meas_w_btm;\n          r_meas = r_meas_top/r_meas_btm;\n        }\n\n        //for calculation of cc1/2\n        //separate the observations into two groups\n        double I_avg_even = 0;\n        double I_avg_odd = 0;\n        double I_avg_even_h = 0;\n        double I_avg_odd_h = 0;\n        double I_avg_even_k = 0;\n        double I_avg_odd_k = 0;\n        double I_avg_even_l = 0;\n        double I_avg_odd_l = 0;\n\n        calc_avg_two_halves(I_full_group, SE_norm, avg_mode_, I_avg_even, I_avg_odd);\n\n        //select reflections on h axis\n        scitbx::af::shared<double> I_full_group_h;\n        scitbx::af::shared<double> SE_norm_h;\n        scitbx::af::shared<double> I_full_group_k;\n        scitbx::af::shared<double> SE_norm_k;\n        scitbx::af::shared<double> I_full_group_l;\n        scitbx::af::shared<double> SE_norm_l;\n        for (int i = 0; i < I_full_group.size(); i++) {\n          if (current_index_ori[i][0] == 0) {\n            I_full_group_h.push_back(I_full_group[i]);\n            SE_norm_h.push_back(SE_norm[i]);\n          }\n\n          if (current_index_ori[i][1] == 0) {\n            I_full_group_k.push_back(I_full_group[i]);\n            SE_norm_k.push_back(SE_norm[i]);\n          }\n\n          if (current_index_ori[i][2] == 0) {\n            I_full_group_l.push_back(I_full_group[i]);\n            SE_norm_l.push_back(SE_norm[i]);\n          }\n        }\n\n\n        calc_avg_two_halves(I_full_group_h, SE_norm_h, avg_mode_, I_avg_even_h, I_avg_odd_h);\n        calc_avg_two_halves(I_full_group_k, SE_norm_k, avg_mode_, I_avg_even_k, I_avg_odd_k);\n        calc_avg_two_halves(I_full_group_l, SE_norm_l, avg_mode_, I_avg_even_l, I_avg_odd_l);\n\n\n        // save the results for this group\n        results.miller_index.push_back(current_index);\n        results.I_avg.push_back(I_avg);\n        results.sigI_avg.push_back(sigI_avg);\n        results.r_meas_w_top.push_back(r_meas_w_top);\n        results.r_meas_w_btm.push_back(r_meas_w_btm);\n        results.r_meas_top.push_back(r_meas_top);\n        results.r_meas_btm.push_back(r_meas_btm);\n        results.multiplicity.push_back(multiplicity);\n        results.I_avg_even.push_back(I_avg_even);\n        results.I_avg_odd.push_back(I_avg_odd);\n        results.I_avg_even_h.push_back(I_avg_even_h);\n        results.I_avg_odd_h.push_back(I_avg_odd_h);\n        results.I_avg_even_k.push_back(I_avg_even_k);\n        results.I_avg_odd_k.push_back(I_avg_odd_k);\n        results.I_avg_even_l.push_back(I_avg_even_l);\n        results.I_avg_odd_l.push_back(I_avg_odd_l);\n\n        if (flag_output_verbose_) {\n          txt_obs_out << \"    I_o        sigI_o    G      B     Eoc      rs    lambda rocking(deg) W     I_full     sigI_full\\n\";\n          for (int i = 0; i < I_full_group.size(); i++) {\n            char buf[512];\n            sprintf(buf, \"%10.2f %10.2f %6.2f %6.2f %6.2f %8.5f %8.5f %8.5f %6.2f %10.2f %10.2f\\n\",\n              I_group[i],sigI_group[i],1/G_[valid_ptrs[i]],B_[valid_ptrs[i]],p_set_[valid_ptrs[i]],rs_set_[valid_ptrs[i]],\n              wavelength_set_[valid_ptrs[i]],mosaic_radian_set[valid_ptrs[i]]*180/scitbx::constants::pi,SE_norm[i],\n              I_full_group[i],sigI_full[i]);\n            txt_obs_out << buf;\n          }\n          char buf[512];\n          sprintf(buf, \"Merged I, sigI: %6.2f, %6.2f\\n\",I_avg,sigI_avg);\n          txt_obs_out << buf;\n          sprintf(buf, \"Rmeas: %6.2f Qw: %6.2f\\n\",r_meas,r_meas_w);\n          txt_obs_out << buf;\n          sprintf(buf, \"No. total observed: %4.0f No. after rejection: %4.0f\\n\", double(obs_ptr-obs_ptr_start), double(I_full_group.size()));\n          txt_obs_out << buf;\n          txt_obs_out << \"List of rejected observations:\\n\";\n          txt_obs_out << txt_reject_out_group.str();\n        }\n        txt_reject_out << txt_reject_out_group.str();\n      }\n      results.txt_obs_out = txt_obs_out.str();\n      results.txt_reject_out = txt_reject_out.str();\n\n      return results;\n    }\n  };\n\n\nconst double averaging_engine::CONST_SE_MIN_WEIGHT = 0.17;\nconst double averaging_engine::CONST_SE_MAX_WEIGHT = 1.0;\nconst double averaging_engine::CONST_SIG_I_FACTOR = 1.5;\n\nnamespace boost_python { namespace {\n  void\n  init_module() {\n    using namespace boost::python;\n    typedef return_value_policy<return_by_value> rbv;\n    typedef default_call_policies dcp;\n    typedef averaging_engine w_t;\n\n    class_<w_t>(\"averaging_engine\", no_init)\n      .def(init<int,scitbx::af::shared<int>,\n        const shared_miller&,const shared_miller&,\n        const scitbx::af::shared<double>&,\n        const scitbx::af::shared<double>&,\n        const scitbx::af::shared<double>&,\n        const scitbx::af::shared<double>&,\n        const scitbx::af::shared<double>&,\n        const scitbx::af::shared<double>&,\n        const scitbx::af::shared<double>&,\n        const scitbx::af::shared<double>&,\n        const scitbx::af::shared<double>&,\n        const scitbx::af::shared<std::string>&\n        >(\n        (arg(\"group_no\"),arg(\"group_id_list\"),\n        arg(\"miller_list\"),arg(\"miller_list_ori\"),arg(\"I\"),arg(\"sigI\"),\n        arg(\"G\"),arg(\"B\"),arg(\"p_set\"),arg(\"rs_set\"),\n        arg(\"wavelength_set\"),arg(\"sin_theta_over_lambda_sq\"),arg(\"SE\"),\n        arg(\"pickle_filename_set\")\n        )))\n      .def(\"calc_avg_I\", &averaging_engine::calc_avg_I)\n      .add_property(\"avg_mode\",\n        make_getter(&averaging_engine::avg_mode_, rbv()),\n        make_setter(&averaging_engine::avg_mode_, dcp()))\n      .add_property(\"sigma_max\",\n        make_getter(&averaging_engine::sigma_max_, rbv()),\n        make_setter(&averaging_engine::sigma_max_, dcp()))\n      .add_property(\"flag_volume_correction\",\n        make_getter(&averaging_engine::flag_volume_correction_, rbv()),\n        make_setter(&averaging_engine::flag_volume_correction_, dcp()))\n      .add_property(\"n_rejection_cycle\",\n        make_getter(&averaging_engine::n_rejection_cycle_, rbv()),\n        make_setter(&averaging_engine::n_rejection_cycle_, dcp()))\n      .add_property(\"flag_output_verbose\",\n        make_getter(&averaging_engine::flag_output_verbose_, rbv()),\n        make_setter(&averaging_engine::flag_output_verbose_, dcp()))\n      ;\n\n    class_<average_result_store>(\"average_result_store\",init<>())\n      .add_property(\"miller_index\",\n        make_getter(&average_result_store::miller_index, rbv()),\n        make_setter(&average_result_store::miller_index, dcp()))\n      .add_property(\"I_avg\",\n        make_getter(&average_result_store::I_avg, rbv()),\n        make_setter(&average_result_store::I_avg, dcp()))\n      .add_property(\"sigI_avg\",\n        make_getter(&average_result_store::sigI_avg, rbv()),\n        make_setter(&average_result_store::sigI_avg, dcp()))\n      .add_property(\"r_meas_w_top\",\n        make_getter(&average_result_store::r_meas_w_top, rbv()),\n        make_setter(&average_result_store::r_meas_w_top, dcp()))\n      .add_property(\"r_meas_w_btm\",\n        make_getter(&average_result_store::r_meas_w_btm, rbv()),\n        make_setter(&average_result_store::r_meas_w_btm, dcp()))\n      .add_property(\"r_meas_top\",\n        make_getter(&average_result_store::r_meas_top, rbv()),\n        make_setter(&average_result_store::r_meas_top, dcp()))\n      .add_property(\"r_meas_btm\",\n        make_getter(&average_result_store::r_meas_btm, rbv()),\n        make_setter(&average_result_store::r_meas_btm, dcp()))\n      .add_property(\"multiplicity\",\n        make_getter(&average_result_store::multiplicity, rbv()),\n        make_setter(&average_result_store::multiplicity, dcp()))\n      .add_property(\"I_avg_even\",\n        make_getter(&average_result_store::I_avg_even, rbv()),\n        make_setter(&average_result_store::I_avg_even, dcp()))\n      .add_property(\"I_avg_odd\",\n        make_getter(&average_result_store::I_avg_odd, rbv()),\n        make_setter(&average_result_store::I_avg_odd, dcp()))\n      .add_property(\"I_avg_even_h\",\n        make_getter(&average_result_store::I_avg_even_h, rbv()),\n        make_setter(&average_result_store::I_avg_even_h, dcp()))\n      .add_property(\"I_avg_odd_h\",\n        make_getter(&average_result_store::I_avg_odd_h, rbv()),\n        make_setter(&average_result_store::I_avg_odd_h, dcp()))\n      .add_property(\"I_avg_even_k\",\n        make_getter(&average_result_store::I_avg_even_k, rbv()),\n        make_setter(&average_result_store::I_avg_even_k, dcp()))\n      .add_property(\"I_avg_odd_k\",\n        make_getter(&average_result_store::I_avg_odd_k, rbv()),\n        make_setter(&average_result_store::I_avg_odd_k, dcp()))\n      .add_property(\"I_avg_even_l\",\n        make_getter(&average_result_store::I_avg_even_l, rbv()),\n        make_setter(&average_result_store::I_avg_even_l, dcp()))\n      .add_property(\"I_avg_odd_l\",\n        make_getter(&average_result_store::I_avg_odd_l, rbv()),\n        make_setter(&average_result_store::I_avg_odd_l, dcp()))\n      .add_property(\"txt_obs_out\",\n        make_getter(&average_result_store::txt_obs_out, rbv()),\n        make_setter(&average_result_store::txt_obs_out, dcp()))\n      .add_property(\"txt_reject_out\",\n        make_getter(&average_result_store::txt_reject_out, rbv()),\n        make_setter(&average_result_store::txt_reject_out, dcp()))\n    ;\n  };\n\n  using namespace boost::python;\n\n  void export_average_mode()\n  {\n    enum_<Average_Mode>(\"Average_Mode\")\n      .value(\"Average\", Average)\n      .value(\"Weighted\", Weighted)\n      .value(\"Final\", Final);\n  }\n\n}}} // namespace prime::boost_python::<anonymous>\n\nBOOST_PYTHON_MODULE(prime_ext)\n{\n  prime::boost_python::init_module();\n  prime::boost_python::export_average_mode();\n\n}\n\n", "meta": {"hexsha": "844c6c868045b64e5c9e99cca020b3be606f41a9", "size": 24879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "prime/ext.cpp", "max_stars_repo_name": "dperl-sol/cctbx_project", "max_stars_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 155.0, "max_stars_repo_stars_event_min_datetime": "2016-11-23T12:52:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:35:44.000Z", "max_issues_repo_path": "prime/ext.cpp", "max_issues_repo_name": "dperl-sol/cctbx_project", "max_issues_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 590.0, "max_issues_repo_issues_event_min_datetime": "2016-12-10T11:31:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T23:10:09.000Z", "max_forks_repo_path": "prime/ext.cpp", "max_forks_repo_name": "dperl-sol/cctbx_project", "max_forks_repo_head_hexsha": "b9e390221a2bc4fd00b9122e97c3b79c632c6664", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 115.0, "max_forks_repo_forks_event_min_datetime": "2016-11-15T08:17:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T15:30:14.000Z", "avg_line_length": 41.0544554455, "max_line_length": 153, "alphanum_fraction": 0.6340286989, "num_tokens": 6560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4309397256395575}}
{"text": "//-----------------------------------------------------------------------------\n// Created on: 03 December 2016\n//-----------------------------------------------------------------------------\n// Copyright (c) 2017, Sergey Slyadnev\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n//    * Redistributions of source code must retain the above copyright\n//      notice, this list of conditions and the following disclaimer.\n//    * Redistributions in binary form must reproduce the above copyright\n//      notice, this list of conditions and the following disclaimer in the\n//      documentation and/or other materials provided with the distribution.\n//    * Neither the name of the copyright holder(s) nor the\n//      names of all contributors may be used to endorse or promote products\n//      derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY\n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//-----------------------------------------------------------------------------\n\n// Own include\n#include <asiAlgo_PlaneOnPoints.h>\n\n// Eigen includes\n#pragma warning(disable : 4701 4702)\n#include <Eigen/Dense>\n#pragma warning(default : 4701 4702)\n\n#undef COUT_DEBUG\n#if defined COUT_DEBUG\n  #pragma message(\"===== warning: COUT_DEBUG is enabled\")\n#endif\n\n//-----------------------------------------------------------------------------\n\nbool compare(const std::pair<double, int>& p1, const std::pair<double, int>& p2)\n{\n  return p1.first > p2.first;\n}\n\n//-----------------------------------------------------------------------------\n\nasiAlgo_PlaneOnPoints::asiAlgo_PlaneOnPoints(ActAPI_ProgressEntry progress,\n                                             ActAPI_PlotterEntry  plotter)\n: ActAPI_IAlgorithm(progress, plotter)\n{}\n\n//-----------------------------------------------------------------------------\n\nbool asiAlgo_PlaneOnPoints::Build(const std::vector<gp_XYZ>& points,\n                                  gp_Pln&                    result) const\n{\n  return this->internalBuild(points, result);\n}\n\n//-----------------------------------------------------------------------------\n\nbool asiAlgo_PlaneOnPoints::Build(const Handle(asiAlgo_BaseCloud<double>)& points,\n                                  gp_Pln&                                  result) const\n{\n  // Repack point cloud to a vector.\n  std::vector<gp_XYZ> pointsVec;\n  //\n  for ( int k = 0; k < points->GetNumberOfElements(); ++k )\n    pointsVec.push_back( points->GetElement(k) );\n\n  return this->internalBuild(pointsVec, result);\n}\n\n//-----------------------------------------------------------------------------\n\nbool asiAlgo_PlaneOnPoints::internalBuild(const std::vector<gp_XYZ>& points,\n                                          gp_Pln&                    result) const\n{\n  const int nPts = (int) points.size();\n\n  /* ======================\n   *  Calculate mean point\n   * ====================== */\n\n  gp_XYZ mu;\n  for ( size_t i = 0; i < points.size(); ++i )\n  {\n    mu += points[i];\n  }\n  mu /= nPts;\n\n  /* =========================\n   *  Build covariance matrix\n   * ========================= */\n\n  Eigen::Matrix3d C;\n  for ( int j = 1; j <= 3; ++j )\n  {\n    for ( int k = 1; k <= 3; ++k )\n    {\n      C(j-1, k-1) = 0.0; // TODO: is that necessary?\n    }\n  }\n\n  for ( size_t i = 0; i < points.size(); ++i )\n  {\n    const gp_XYZ& p      = points[i];\n    gp_XYZ        p_dash = p - mu;\n\n    for ( int j = 1; j <= 3; ++j )\n    {\n      for ( int k = 1; k <= 3; ++k )\n      {\n        C(j-1, k-1) += ( p_dash.Coord(j)*p_dash.Coord(k) );\n      }\n    }\n  }\n\n  for ( int j = 1; j <= 3; ++j )\n  {\n    for ( int k = 1; k <= 3; ++k )\n    {\n      C(j-1, k-1) /= nPts;\n    }\n  }\n\n  Eigen::EigenSolver<Eigen::Matrix3d> EigenSolver(C);\n\n#if defined COUT_DEBUG\n  std::cout << \"\\tCovariance matrix: \" << std::endl << C << std::endl;\n  std::cout << \"\\tThe eigen values of C are:\" << std::endl << EigenSolver.eigenvalues() << std::endl;\n  std::cout << \"\\tThe matrix of eigenvectors, V, is:\" << std::endl << EigenSolver.eigenvectors() << std::endl << std::endl;\n#endif\n\n  Eigen::Vector3cd v1 = EigenSolver.eigenvectors().col(0);\n  Eigen::Vector3cd v2 = EigenSolver.eigenvectors().col(1);\n  Eigen::Vector3cd v3 = EigenSolver.eigenvectors().col(2);\n\n  gp_Vec V[3] = { gp_Vec( v1.x().real(), v1.y().real(), v1.z().real() ),\n                  gp_Vec( v2.x().real(), v2.y().real(), v2.z().real() ),\n                  gp_Vec( v3.x().real(), v3.y().real(), v3.z().real() ) };\n  //\n  std::vector< std::pair<double, int> >\n    lambda { std::pair<double, int>( EigenSolver.eigenvalues()(0).real(), 0 ),\n             std::pair<double, int>( EigenSolver.eigenvalues()(1).real(), 1 ),\n             std::pair<double, int>( EigenSolver.eigenvalues()(2).real(), 2 ) };\n  //\n  std::sort(lambda.begin(), lambda.end(), compare);\n  //\n  gp_Ax1 ax_X(mu, V[lambda[0].second]);\n  gp_Ax1 ax_Y(mu, V[lambda[1].second]);\n  gp_Ax1 ax_Z(mu, V[lambda[2].second]);\n  //\n  gp_Vec vec_X( ax_X.Direction() );\n  gp_Vec vec_Y( ax_Y.Direction() );\n  gp_Vec vec_Z( ax_Z.Direction() );\n  //\n  if ( (vec_X ^ vec_Y).Magnitude() < gp::Resolution() ||\n       (vec_X ^ vec_Z).Magnitude() < gp::Resolution() ||\n       (vec_Y ^ vec_Z).Magnitude() < gp::Resolution() )\n  {\n    std::cout << \"Warning: degenerated normal\" << std::endl;\n    return false; // Degenerated normal\n  }\n\n  // Check if the system is right-handed\n  const double ang = ax_X.Direction().AngleWithRef( ax_Y.Direction(), ax_Z.Direction() );\n  if ( ang < 0 )\n  {\n    gp_Ax1 tmp = ax_X;\n    ax_X = ax_Y;\n    ax_Y = tmp;\n  }\n\n  // Store results\n  gp_Ax3 ax3( gp_Pnt(mu), ax_Z.Direction(), ax_X.Direction() );\n  result.SetPosition(ax3);\n  //\n  return true;\n}\n", "meta": {"hexsha": "8430ba31a52976a5a6c594d38a501cad21374da8", "size": 6500, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/asiAlgo/points/asiAlgo_PlaneOnPoints.cpp", "max_stars_repo_name": "sasobadovinac/AnalysisSitus", "max_stars_repo_head_hexsha": "304d39c64258d4fcca888eb8e68144eca50e785a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-04T01:36:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T07:11:01.000Z", "max_issues_repo_path": "src/asiAlgo/points/asiAlgo_PlaneOnPoints.cpp", "max_issues_repo_name": "sasobadovinac/AnalysisSitus", "max_issues_repo_head_hexsha": "304d39c64258d4fcca888eb8e68144eca50e785a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/asiAlgo/points/asiAlgo_PlaneOnPoints.cpp", "max_forks_repo_name": "sasobadovinac/AnalysisSitus", "max_forks_repo_head_hexsha": "304d39c64258d4fcca888eb8e68144eca50e785a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-25T18:14:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-25T18:14:30.000Z", "avg_line_length": 34.7593582888, "max_line_length": 123, "alphanum_fraction": 0.5484615385, "num_tokens": 1637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4309397256395574}}
{"text": "/**\n * @file TriangleElement.cpp\n * @author Adam Li (adamli@umich.edu)\n * @date 2021-11-12\n * \n * @brief Implements TriangleElement from meshGenerator.py. \n * \n */\n\n#include \"TriangleElement.hpp\"\n#include <cstring>\n#include <cstdlib>\n#include <Eigen/Dense>\n#include \"TriangularMesh.hpp\"\n\nusing sel_map::core::ElemArray;\nusing sel_map::core::ElemArrayBase;\n\n#include \"core/EigenMathUtil.hpp\"\nnamespace EigenMathUtil = sel_map::core::EigenMathUtil;\n\n//Avoid rewriting the whole thing everytime\nusing sel_map::mesh::TriangularMesh;\nusing sel_map::mesh::TriangleElement;\nusing sel_map::mesh::Element;\n\n// TriangleElement::TriangleElement(const std::reference_wrapper<TriangularMesh>& parentMesh, unsigned int index, double elementLength, unsigned int pointLimit, float heightPartition,\n//                     double heightSafetyCheck, unsigned int classes)\n//                       : Element<TriangularMesh>(parentMesh, index, elementLength, pointLimit, heightPartition, heightSafetyCheck, classes)\n//                     //   , lambdas()\nTriangleElement::TriangleElement(const std::reference_wrapper<TriangularMesh>& parentMesh, unsigned int index)\n                      : Element<TriangularMesh>(parentMesh, index)\n{\n    // Initializer\n    active = false;\n}\n\nTriangleElement::~TriangleElement()\n{\n    // Destructor\n}\n\nvoid TriangleElement::reset()\n{\n    active = false;\n    dirichletParamsForTerrainClass.setZero();\n}\n\n/**\n * @brief Computes the Barycentric coordinates of all points within the element from Cartesian points.\n */\n// void TriangleElement::cartesianToBarycentric()\n// {\n//     // Auto keywords in eigen are really dangerous, oops\n//     // These are all effectively Map<vector2d, unaligned> types\n//     auto vertices = parentMesh.get().vertexVector(simplex(), Eigen::all);\n//     auto v1 = vertices(0, Eigen::seqN(Eigen::fix<0>, Eigen::fix<2>));\n//     auto v2 = vertices(0, Eigen::seqN(Eigen::fix<0>, Eigen::fix<2>));\n//     auto v3 = vertices(0, Eigen::seqN(Eigen::fix<0>, Eigen::fix<2>));\n//     // These two variables should never be touched again! they're just intermediates\n//     auto area_iexp1 = v2 - v1;\n//     auto area_iexp2 = v3 - v1;\n//     double area = EigenMathUtil::crossProduct2D(area_iexp1, area_iexp2);\n\n//     // This is effectively Map<ArrayXd, aligned> type\n//     auto eigenPointsArray = points.getEigenArray();\n//     auto eigenLambdaArray = lambdas.reserve(points.length(), true).getEigenArray();\n    \n//     // The following is simplified to keep eveything in scalar math\n//     // alpha = abs(np.cross(p2-self.points[:,0:2], p3-self.points[:,0:2]) / area)\n//     // beta  = abs(np.cross(p1-self.points[:,0:2], p3-self.points[:,0:2]) / area)\n//     // gamma = abs(np.cross(p1-self.points[:,0:2], p2-self.points[:,0:2]) / area)\n//     // self.lambdas = np.array([alpha, beta, gamma])\n    \n//     double v1_x_v2 = EigenMathUtil::crossProduct2D(v1, v2);\n//     double v1_x_v3 = EigenMathUtil::crossProduct2D(v1, v3);\n//     double v2_x_v3 = EigenMathUtil::crossProduct2D(v2, v3);\n\n//     // update alpha\n//     eigenLambdaArray.col(0) = ((v2_x_v3\n//                                  + (v2(1) - v3(1)) * eigenPointsArray.col(0)\n//                                  + (v3(0) - v2(0)) * eigenPointsArray.col(1)\n//                               ) / area).abs();\n\n//     // update beta\n//     eigenLambdaArray.col(1) = ((v1_x_v3\n//                                  + (v1(1) - v3(1)) * eigenPointsArray.col(0)\n//                                  + (v3(0) - v1(0)) * eigenPointsArray.col(1)\n//                               ) / area).abs();\n\n//     // update gamma\n//     eigenLambdaArray.col(2) = ((v1_x_v2\n//                                  + (v1(1) - v2(1)) * eigenPointsArray.col(0)\n//                                  + (v2(0) - v1(0)) * eigenPointsArray.col(1)\n//                               ) / area).abs();\n// }\n\nvoid TriangleElement::computeElementNormal()\n{\n    // auto vertices = parentMesh.get().vertexVector(simplex(), Eigen::all);\n    // auto a = vertices(2, Eigen::seqN(Eigen::fix<0>(), Eigen::fix<3>()));\n    // auto b = vertices(1, Eigen::seqN(Eigen::fix<0>(), Eigen::fix<3>()));\n    // auto c = vertices(0, Eigen::seqN(Eigen::fix<0>(), Eigen::fix<3>()));\n\n    // auto v1 = a - b;\n    // auto v2 = c - b;\n    // normal = v1.matrix().cross(v2.matrix());\n}\n\n\nEigen::Block<Eigen::Array<unsigned int, -1, 3, 1>, 1, 3, true> TriangleElement::simplex()\n{\n    return parentMesh.get().simplices.row(index);\n}\n", "meta": {"hexsha": "594fbaa951682a477082b62bdcf7c17c617a959f", "size": 4452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sel_map_mesh/src/TriangleElement.cpp", "max_stars_repo_name": "roahmlab/sel_map", "max_stars_repo_head_hexsha": "51c5ac738eb7475f409f826c0d30f555f98757b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-02-24T21:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T20:00:09.000Z", "max_issues_repo_path": "sel_map_mesh/src/TriangleElement.cpp", "max_issues_repo_name": "roahmlab/sel_map", "max_issues_repo_head_hexsha": "51c5ac738eb7475f409f826c0d30f555f98757b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sel_map_mesh/src/TriangleElement.cpp", "max_forks_repo_name": "roahmlab/sel_map", "max_forks_repo_head_hexsha": "51c5ac738eb7475f409f826c0d30f555f98757b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7130434783, "max_line_length": 183, "alphanum_fraction": 0.6075920934, "num_tokens": 1219, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.43089181025966744}}
{"text": "#include <cassert>\n#include <NTL/RR.h>\n#include \"ring.h\"\n\n/**********************************************************************/\nostream& operator<< (ostream& s, const ring& rg) {\n  s << rg.label << \": type = \" << rg.type << \", mR = \" << rg.mR << \", pR = \" << rg.pR\n    << \", gR = \" << rg.gR << \", tR = \" << rg.tR << \", depth = \" << rg.depth << endl;\n  \n  return s;\n}\n\nostream& operator<< (ostream& s, const param& prm) {\n  s << endl << \"<\" << prm.label << \">\" << endl;\n  s << \"l = \" << prm.l << \", \";\n  s << \"r = \" << prm.r << \", \";\n  s << \"s = \" << prm.s << \", \";\n  s << \"lw = \" << prm.lw << endl;\n  s << prm.rg << prm.ns;\n  \n  return s;\n}\n\n/**********************************************************************/\nvoid ring::to_eta (ZZ_pX& w, vec_ZZ_p& a) {\n  if (type != prime) {\n    cout << \"Error: to_eta\" << endl;\n    cout << \"- not yet implemented for \" << type << \"-type\" << endl;\n  }\n\n  for (long i = 0; i < gR; ++i) w += a[i] * conv<ZZ_pX>(eta(i));\n}\n\nvoid ring::to_delta (ZZ_pX& w, vec_ZZ_p& a) {\n  if (type != prime) {\n    cout << \"Error: to_eta\" << endl;\n    cout << \"- not yet implemented for \" << type << \"-type\" << endl;\n  }\n\n  for (long i = 0; i < gR; ++i) w += a[i] * delta(i);\n}\n\nvoid mult (vec_ZZ_p& x, const vec_ZZ_p& a, const vec_ZZ_p& b) {\n  for (long i = 0; i < a.length(); ++i) x[i] = a[i] * b[i];\n}\n\nvoid sqr (vec_ZZ_p& x, const vec_ZZ_p& a) {\n  for (long i = 0; i < a.length(); ++i) x[i] = sqr(a[i]);\n}\n\nvoid add_scalar (vec_ZZ_p& x, const vec_ZZ_p& a, const ZZ_p& b) {\n  for (long i = 0; i < a.length(); ++i) x[i] = a[i] + b;\n}\n\nvoid add_scalar (vec_ZZ_p& x, const ZZ_p& a, const vec_ZZ_p& b) {\n  for (long i = 0; i < b.length(); ++i) x[i] = a + b[i];\n}\n\nvoid zzx_convolution (vec_ZZ_p& c, const vec_ZZ_p& a, const vec_ZZ_p& b) {\n  ZZ_pX aX, bX;\n  long g = a.length();\n\n  aX.SetLength(g);\n  bX.SetLength(g);\n  c.SetLength(g);\n\n  aX[0] = a[0];\n  for (long i = 1; i < g; ++i) aX[i] = a[g - i];\n  for (long i = 0; i < g; ++i) bX[i] = b[i];  \n  \n  ZZ_pX w = aX * bX;\n  w.SetLength(2*g-1);\n  \n  // c = w mod m, m = x^gR - 1\n  for (long i = 0; i < g-1; i++) c[i] = w[i] + w[i + g];\n  c[g-1] = w[g-1];\n}\n\n// Transpose a (m*n)-dim. vector 'a'\n// into a m x n matrix (m-dim vector of n-dim vector)'w'\nvoid mat (Vec<vec_ZZ_p>& aa, const vec_ZZ_p& a, const long n, const long m) {\n  aa.SetLength(m);\n  for (long j = 0; j < m; ++j) aa[j].SetLength(n);\n  \n  for (long j = 0; j < m; ++j)\n    for (long i = 0; i < n; ++i)\n      aa[j][i] = a[i + n*j];\n}\n\n// returns m-dim vector of n-dim vectors\nvoid mat (Vec<vec_ZZ>& aa, const vec_ZZ& a, const long n, const long m) {\n  aa.SetLength(m);\n  for (long j = 0; j < m; ++j) aa[j].SetLength(n);\n  \n  for (long j = 0; j < m; ++j)\n    for (long i = 0; i < n; ++i)\n      aa[j][i] = a[i + n*j];\n}\n\nvoid transpose (Vec<vec_ZZ_p>& b, const Vec<vec_ZZ_p>& a) {\n  long m = a.length();\n  long n = a[0].length();\n\n  b.SetLength(n);\n  for (long j = 0; j < n; ++j) b[j].SetLength(m);\n\n  for (long j = 0; j < n; ++j)\n    for (long i = 0; i < m; ++i)\n      b[j][i] = a[i][j];\n}\n\nvoid transpose (Vec<vec_ZZ>& b, const Vec<vec_ZZ>& a) {\n  long m = a.length();\n  long n = a[0].length();\n\n  b.SetLength(n);\n  for (long j = 0; j < n; ++j) b[j].SetLength(m);\n\n  for (long i = 0; i < m; ++i)\n    for (long j = 0; j < n; ++j)\n      b[j][i] = a[i][j];\n}\n\n\nvoid vec (vec_ZZ_p& b, const Vec<vec_ZZ_p>& a) {\n  long m = a.length();\n  long n = a[0].length();\n\n  b.SetLength(m*n);\n\n  for (long i = 0; i < m; ++i)\n    for (long j = 0; j < n; ++j)\n      b[i*n+j] = a[i][j];\n}\n\nvoid transpose_vec (vec_ZZ_p& b, const Vec<vec_ZZ_p>& a) {\n  long m = a.length();\n  long n = a[0].length();\n\n  b.SetLength(m*n);\n\n  for (long i = 0; i < n; ++i)\n    for (long j = 0; j < m; ++j)\n      b[i*m+j] = a[j][i];\n}\n\nvoid transpose_vec (vec_ZZ& b, const Vec<vec_ZZ>& a) {\n  long m = a.length();\n  long n = a[0].length();\n\n  b.SetLength(m*n);\n\n  for (long i = 0; i < n; ++i)\n    for (long j = 0; j < m; ++j)\n      b[i*m+j] = a[j][i];\n}\n\nvoid diagonal (vec_ZZ& MD, const long k, const vec_ZZ& M) {\n  long dim = M.length();\n  MD.SetLength(dim);\n\n  for (long i = 0; i < dim; ++i) MD[i] = M[(i+(i+k)) % dim];\n}\n\nvoid diagonal (vec_ZZ_p& MD, const long k, const vec_ZZ_p& M) {\n  long dim = M.length();\n  MD.SetLength(dim);\n\n  for (long i = 0; i < dim; ++i) MD[i] = M[(i+(i+k)) % dim];\n}\n\nvoid naiveApplyMatrix (vec_ZZ_p& b, const vec_ZZ_p& m, const vec_ZZ_p& a) {\n  long dim = m.length();\n  vec_ZZ_p S; S.SetLength(dim);\n\n  vec_ZZ_p aa; //aa.SetLength(dim);\n  VectorCopy(aa, a, dim);\n\n  for (long i=0; i < dim; ++i) {\n    vec_ZZ_p md;\n    diagonal(md, i, m);\n    \n    vec_ZZ_p w; w.SetLength(dim);\n    mult(w, md, aa);\n\n    shift(aa);\n    S += w;\n  }\n\n  b = S;\n}\n\nvoid applyMatrix (vec_ZZ_p& b, const vec_ZZ_p& m, const vec_ZZ_p& a) {\n  zzx_convolution(b, a, m);\n  //naiveApplyMatrix(b, m, a);  // slow, for debug only\n}\n\nvoid ring::applyOmega (vec_ZZ_p& b, const vec_ZZ_p& a) {\n  if (type == prime) {\n    vec_ZZ_p w = conv<vec_ZZ_p>(omega);\n    applyMatrix(b, w, a);\n  }\n  else {  // type == composite\n    long gl = left->gR;\n    long gr = right->gR;\n    \n    Vec<vec_ZZ_p> w;\n    mat(w, a, gr, gl);\n    for (long i = 0; i < gl; ++i) right->applyOmega(w[i], w[i]);\n\n    Vec<vec_ZZ_p> wt;\n    transpose(wt, w);\n    for (long j = 0; j < gr; ++j) left->applyOmega(wt[j], wt[j]);\n    \n    transpose_vec(b, wt);\n  }\n}\n\nvoid ring::applyOmega (vec_ZZ& b, const vec_ZZ& a) {\n  vec_ZZ_p _b;\n  applyOmega(_b, conv<vec_ZZ_p>(a));\n  b = conv<vec_ZZ>(_b);\n}\n\nvoid ring::applyOmegaInv (vec_ZZ_p& b, const vec_ZZ_p& a) {\n  if (type == prime) {\n    vec_ZZ_p w = conv<vec_ZZ_p>(omega_inv);\n    applyMatrix(b, w, a);\n  }\n  else {  // type == composite\n    long gl = left->gR;\n    long gr = right->gR;\n    \n    Vec<vec_ZZ_p> w;\n    mat(w, a, gr, gl);\n    for (long i = 0; i < gl; ++i) right->applyOmegaInv(w[i], w[i]);\n\n    Vec<vec_ZZ_p> wt;\n    transpose(wt, w);\n    for (long j = 0; j < gr; ++j) left->applyOmegaInv(wt[j], wt[j]);\n    \n    transpose_vec(b, wt);\n  }\n}\n\nvoid ring::applyOmegaInv (vec_ZZ& b, const vec_ZZ& a) {\n  vec_ZZ_p _b;\n  applyOmegaInv(_b, conv<vec_ZZ_p>(a));\n  b = conv<vec_ZZ>(_b);\n}\n\n/**********************************************************************/\nZZ inf_norm (const vec_ZZ& a) {\n  ZZ w(0);\n  for (long i = 0; i < a.length(); ++i) \n    if (w < abs(a[i])) w = abs(a[i]);\n  return w;\n}\n\nvoid center_lift (vec_ZZ& b, const vec_ZZ_p& a) {\n  b.SetLength(a.length());\n  ZZ q = ZZ_p::modulus();\n  for (long i=0; i < a.length(); ++i) {\n    if (conv<ZZ>(a[i]) >= q/2) b[i] = conv<ZZ>(a[i]) - q;\n    else b[i] = conv<ZZ>(a[i]);\n  }\n}\n\nvoid center_lift (vec_ZZ& b, const vec_ZZ& a, ZZ& p) {\n  ZZ_pContext context;\n  context.save();  \n\n  ZZ_p::init(p);\n  center_lift(b, conv<vec_ZZ_p>(a));\n\n  context.restore();\n}\n\nvec_ZZ center_lift (const vec_ZZ_p& a) {\n  vec_ZZ b;\n  center_lift(b, a);\n  return b;\n}\n\nvec_ZZ center_lift (const vec_ZZ& a, ZZ& p) {\n  vec_ZZ b;\n  center_lift(b, a, p);\n  return b;\n}\n\n// q -> q1\nvoid rescale (vec_ZZ &b, const vec_ZZ &a, const ZZ& q, const ZZ& q1) {\n  b.SetLength(a.length());\n  for (long i = 0; i < a.length(); ++i) {\n    b[i] = (a[i] * q1 + q/2) / q;\n    if (b[i] >= q1) b[i] -= q1;\n    //b[i] = b[i] % q1;  /*@@*/\n  }\n}\n\nvoid lsd_rescale (vec_ZZ &b, const vec_ZZ &a, const ZZ& P, const ZZ& t) {\n  long dim = a.length();\n  b.SetLength(dim);\n  vec_ZZ delta;\n  delta.SetLength(dim);\n\n  ZZ _g, u, v;\n  XGCD(_g, u, v, P, t);  // 1 = w = u*P + v*t\n  ZZ w1 = v*t; // = 1 mod P, = 0 mod t\n  \n  for (long i = 0; i < dim; ++i) {\n    delta[i] = (((- a[i]) % P) * w1) % (P*t);\n    b[i] = (a[i] + delta[i]) / P;\n  }  \n}\n\n/***********************************************************************/\n/* returns the power decomp of x mod 2^n  */\nvoid power_decomp (Vec<vec_ZZ>& z, long n, const vec_ZZ& x) {\n  long dim = x.length();\n  vec_ZZ zero; zero.SetLength(dim);\n\n  z.SetLength(n);\n  for (long j = 0; j < n; ++j) z[j] = zero;\n\n  Vec<Vec<vec_ZZ>> y;\n  y.SetLength(n);\n  for (long i = 0; i < n; ++i) {\n    y[i].SetLength(n-i);\n    for (long j = 0; j < n-i; ++j) y[i][j] = zero;\n  }\n\n  for (long i = 0; i < n; ++i) {\n    // y[i][0] = (x - sum_{j=0}^{i-1} 2^j * y[j][i-j]) / 2^i\n    y[i][0] = x;\n    for (long j = 0; j < i; ++j) {\n      for (long k = 0; k < dim; ++k) {\n\ty[i][0][k] = (y[i][0][k] - y[j][i-j][k]) % power(ZZ(2), n);\n\ty[i][0][k] /= ZZ(2);\n      }\n    }\n\n    // y[i][j] = y[i][j-1]^2  (j = 1..(n-1-i))\n    for (long j = 1; j < n-i; ++j) {\n      for (long k = 0; k < dim; ++k) y[i][j][k] = (y[i][j-1][k] * y[i][j-1][k]) % power(ZZ(2), n);\n    }\n  }\n\n  for (long i = 0; i < n; ++i) {\n    z[i] = y[i][n-1-i];\n    for (long k = 0; k < dim; ++k) z[i][k] = z[i][k] % power(ZZ(2), n-i);\n  }  \n}\n\n// returns (x >> m) mod 2^(n-m) given (x mod 2^n)\nvoid right_shift (vec_ZZ& z, const vec_ZZ& x, long m, long n) {\n  long dim = x.length();\n  vec_ZZ zero; zero.SetLength(dim);\n\n  long l = n - m;\n\n  Vec<vec_ZZ> y; y.SetLength(n);\n  for (long j = 0; j < n; ++j) y[j] = zero;\n  power_decomp(y, n, x);\n\n  // Drop the least m bits (LowerClear)\n  for (long i = 0; i < l; ++i) y[i] = y[m+i];\n\n  // z = y[0] + 2*y[1] + ... + 2^(l-1)*y[l-1]\n  z = zero;\n  for (long i = 0; i < l; ++i) {\n    // z = (z + (2^i)*y[i]) % 2^l\n    vec_ZZ w = zero;\n    for (long j = 0; j < dim; ++j) {\n      w[j] = (power(ZZ(2),i) * y[i][j]) % power(ZZ(2),l);\n      z[j] = (z[j] + w[j]) % power(ZZ(2),l);\n    }\n  }\n}\n\nvoid right_shift (vec_ZZ_p& z, const vec_ZZ_p& x, long m, long n) {\n  vec_ZZ _z; _z.SetLength(x.length());\n  right_shift(_z, conv<vec_ZZ>(x), m, n);\n  z = conv<vec_ZZ_p>(_z);\n}\n\n// returns the (i,j)-th component of the cyclic matrix with the first row of 'm'\nZZ_p to_mat (const vec_ZZ_p& m, long i, long j) {\n  long dim = m.length();\n  assert(0 <= i && i < dim && 0 <= j && j < dim);\n  return m[(i + j) % dim];\n}\n\n/***********************************************************************/\n\n/* returns the tensor product of a and a1 */\nvoid tensor_prod (vec_ZZ& A, const vec_ZZ& a, const vec_ZZ& a1, const ZZ& q) {\n  long gout = a.length();\n  long gin = a1.length();\n\n  for (long i = 0; i < gout; ++i) {\n    for (long j = 0; j < gin; ++j) {\n      A[i*gin + j] = (a[i] * a1[j]) % q;\n    }\n  }\n}\n\n// left shift of vectors\nvoid shift (vec_ZZ& b, const long i, const vec_ZZ& a) {\n  long dim = a.length();\n  vec_ZZ w;\n  w.SetLength(dim);\n  for (long j = 0; j < dim; ++j) w[j] = a[(j + i) % dim];\n  b = w;\n}\n\nvoid shift (vec_ZZ_p& b, const long i, const vec_ZZ_p& a) {\n  long dim = a.length();\n  vec_ZZ_p w;\n  w.SetLength(dim);\n  for (long j = 0; j < dim; ++j) w[j] = a[(j + i) % dim];\n  b = w;\n}\n\nvec_ZZ shift (const long i, const vec_ZZ& a) {\n  vec_ZZ w;\n  shift(w, i, a);\n  return w;\n}\n\n// one-position left shift\nvoid shift (vec_ZZ_p& a) {\n  long dim = a.length();\n  ZZ_p w = a[0];\n  for (long i = 1; i < dim; ++i) a[i-1] = a[i];\n  a[dim-1] = w;\n}\n\nvoid shift_right (vec_ZZ& b, const long i, const vec_ZZ& a) {\n  shift(b, a.length()-i, a);\n}\n\nvoid shift_right (vec_ZZ_p& b, const long i, const vec_ZZ_p& a) {\n  shift(b, a.length()-i, a);\n}\n\n// one-position right shift\nvoid right_shift (vec_ZZ_p& a) {\n  long dim = a.length();\n  ZZ_p w = a[dim-1];\n  for (long i = dim-1; i > 0; --i) a[i] = a[i-1];\n  a[0] = w;\n}\n\nvoid ring::deep_shift (string _label, vec_ZZ& v, long i) {\n  if ((type == prime) && (label == _label)) {\n    shift(v, (i<0)?(i+gR):i, v);\n  }\n  else if ((type == prime) && (label != _label)) {\n    return;\n  }\n  else {  // composite ring\n    long gl = left->gR;\n    long gr = right->gR;\n    \n    Vec<vec_ZZ> w;\n    mat(w, v, gr, gl);\n    for (long j = 0; j < gl; ++j) right->deep_shift(_label, w[j], i);\n\n    Vec<vec_ZZ> wt;\n    transpose(wt, w);\n    for (long j = 0; j < gr; ++j) left->deep_shift(_label, wt[j], i);\n\n    transpose_vec(v, wt);\n  }\n}\n\nvoid ring::deep_shift_right (string _label, vec_ZZ& v, long i) {\n  deep_shift(_label, v, -i);\n}\n\n/***********************************************************************/\nvoid get_subrings (ring& rg, Vec<ring>& subrings) {\n  if (rg.type == prime) {\n    append(subrings, rg);\n  }\n  else {  // type == composite\n    get_subrings(*(rg.right), subrings);\n    get_subrings(*(rg.left), subrings);\n  }  \n}\n\nlong ring::get_subrings (Vec<ring>& subrings) {\n  ::get_subrings(*this, subrings);\n  return subrings.length();\n}\n\nlong param::get_subrings (Vec<ring>& subrings) {\n  return rg.get_subrings(subrings);\n}\n\nlong ring::get_subring_index (string label) {\n  Vec<ring> subrings;\n  long depth = get_subrings(subrings);\n\n    for (long i = 0; i < depth; ++i) {\n      if (subrings[i].label == label) return i;\n    }\n\n    return -1;\n}\n\nvec_ZZ ring::index_convert (long j) {\n  vec_ZZ tensor_index;\n  tensor_index.SetLength(depth);\n\n  long jj = j;\n  \n  for (long i = 0; i < depth; ++i) {\n    long a = jj % subrings[i].gR;\n    tensor_index[i] = a;\n    jj = (jj - a) / subrings[i].gR;\n  }\n\n  return tensor_index;\n}\n\n// y = (x, x, ..., x) where x is assumed to be an element of the right subring\nvoid ring::embed_1 (vec_ZZ& y, vec_ZZ& x) {\n  y.SetLength(gR);\n  for (long i = 0; i < left->gR; ++i) {\n    for (long j = 0; j < right->gR; ++j) {\n      y[i*right->gR + j] = x[j];\n    }\n  }\n}\n\nvec_ZZ ring::embed_1 (vec_ZZ& x) {\n  vec_ZZ y;\n  embed_1(y, x);\n  return y;\n}\n\n// y = (x, 0, 0, ..., 0) where x is assumed to be an element of the right subring\nvoid ring::embed_0 (vec_ZZ& y, vec_ZZ& x) {\n  y.SetLength(gR);\n  for (long j = 0; j < right->gR; ++j) {\n    y[j] = x[j];\n  }\n}\n\nvec_ZZ ring::embed_0 (vec_ZZ& x) {\n  vec_ZZ y;\n  embed_0(y, x);\n  return y;\n}\n\n// y = (x, 0, 0, ..., 0) where x is assumed to be an element of the prime subring with label subring_label\nvoid ring::embed_0 (vec_ZZ& y, string subring_label, vec_ZZ& x) {\n  y.SetLength(gR);\n  long d = get_subring_index(subring_label);\n\n  for (long j = 0; j < gR; ++j) {\n    vec_ZZ tensor_index = index_convert(j);\n    long skip = 0;\n    for (long k = 0; k < tensor_index.length(); ++k) {\n      if (k != d && tensor_index[k] != 0) {\n        skip = 1;\n        break;\n      }\n    }\n    if (!skip) y[j] = x[conv<long>(tensor_index[d])];\n  }\n}\n\nvec_ZZ ring::embed_0 (string subring_label, vec_ZZ& x) {\n  vec_ZZ y;\n  embed_0(y, subring_label, x);\n  return y;\n}\n\n// y = (x, x, ..., x) where x is assumed to be an element of the prime subring with label subring_label\nvoid ring::embed_1 (vec_ZZ& y, string subring_label, vec_ZZ& x) {\n  y.SetLength(gR);\n  long d = get_subring_index(subring_label);\n\n  for (long j = 0; j < gR; ++j) {\n    vec_ZZ tensor_index = index_convert(j);\n    y[j] = x[conv<long>(tensor_index[d])];\n  }\n}\n\nvec_ZZ ring::embed_1 (string subring_label, vec_ZZ& x) {\n  vec_ZZ y;\n  embed_1(y, subring_label, x);\n  return y;\n}\n\n// y = (-x, -x, ..., -x) where x is assumed to be an element of the prime subring with label subring_label\nvoid ring::embed_11 (vec_ZZ& y, string subring_label, vec_ZZ& x) {\n  y.SetLength(gR);\n  long d = get_subring_index(subring_label);\n\n  for (long j = 0; j < gR; ++j) {\n    vec_ZZ tensor_index = index_convert(j);\n    y[j] = -x[conv<long>(tensor_index[d])];\n  }\n}\n\nvec_ZZ ring::embed_11 (string subring_label, vec_ZZ& x) {\n  vec_ZZ y;\n  embed_11(y, subring_label, x);\n  return y;\n}\n\n// trace to the right ring\nvoid ring::trace (vec_ZZ& y, vec_ZZ& x, ZZ& q) {\n  y.SetLength(right->gR);\n  for (long j = 0; j < x.length(); ++j) {\n    long i = j % right->gR;\n    y[i] = (y[i] + x[j]) % q;\n  }\n}\n\n// trace to the subring of label 'subring_label'\n// -- the subring must be prime\nvoid ring::trace (vec_ZZ& y, string subring_label, vec_ZZ& x, ZZ& q) {\n  //y.SetLength(gR);\n  long d = get_subring_index(subring_label);\n  y.SetLength(subrings[d].gR);\n\n  for (long j = 0; j < x.length(); ++j) {\n    vec_ZZ tensor_index = index_convert(j);\n    long i = conv<long>(tensor_index[d]);\n    y[i] = (y[i] + x[j]) % q;\n  }\n}\n\n// returns the i-th diagonal vector of the extended Omega matrix,\n// corresponding to the subring with label '_label'\nvoid ring::deep_omega (vec_ZZ& extended_omega, string _label, long i) {\n  Vec<ring> subrings;\n  get_subrings(subrings);\n  long d = get_subring_index(_label);\n  \n  vec_ZZ omg;\n  diagonal(omg, i, subrings[d].omega);\n  \n  //embed_0(extended_omega, _label, omg); /*@@*/\n  embed_1(extended_omega, _label, omg); /*@@*/\n}\n\n// returns the i-th diagonal vector of the extended Omega_inv matrix,\n// corresponding to the subring with label '_label'\nvoid ring::deep_omega_inv (vec_ZZ& extended_omega_inv, string _label, long i) {\n  Vec<ring> subrings;\n  get_subrings(subrings);\n  long d = get_subring_index(_label);\n  \n  vec_ZZ omg_inv;\n  diagonal(omg_inv, i, subrings[d].omega_inv);\n\n  //embed_0(extended_omega_inv, _label, omg_inv); /*@@*/\n  embed_1(extended_omega_inv, _label, omg_inv); /*@@*/\n}\n\n", "meta": {"hexsha": "df8be3ccafa0ddb0f7bd46f23ceb65a663167d70", "size": 16563, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ring.cpp", "max_stars_repo_name": "aritalab/SRHE", "max_stars_repo_head_hexsha": "38161f1e62edc72a6d0afa638d057579f7005095", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ring.cpp", "max_issues_repo_name": "aritalab/SRHE", "max_issues_repo_head_hexsha": "38161f1e62edc72a6d0afa638d057579f7005095", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ring.cpp", "max_forks_repo_name": "aritalab/SRHE", "max_forks_repo_head_hexsha": "38161f1e62edc72a6d0afa638d057579f7005095", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.832083958, "max_line_length": 106, "alphanum_fraction": 0.5309424621, "num_tokens": 6312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.43089181025966744}}
{"text": "/*\n * fft.cpp\n *\n *  Created on: 13.12.2012\n *      Author: stephaniebayer\n */\n\n#include \"fft.h\"\n\n#include<vector>\n#include \"Cipher_elg.h\"\n#include \"G_q.h\"\n#include \"Mod_p.h\"\n#include \"functions.h\"\n#include \"multi_expo.h\"\n\n#include <NTL/ZZ.h>\n#include <NTL/mat_ZZ.h>\nNTL_CLIENT\n\nfft::fft() {\n\t// TODO Auto-generated constructor stub\n\n}\n\nfft::~fft() {\n\t// TODO Auto-generated destructor stub\n}\n\n\n\nZZ fft::r_o_u(ZZ gen, long m, ZZ ord){\n//\tZZ ord = H.get_ord();\n\tZZ rou;\n\tZZ pow;\n\tZZ temp;\n\tlong t = 2*m;\n\tif ((ord-1) % t  == 0)\n\t{\n\t\ttemp = (ord-1)/t;\n\t\tPowerMod(rou,gen,temp , ord);\n\n\t\t\tif(GCD(rou,ord)==to_ZZ(1))\n\t\t\t{\n\n\t\t\t\tif (t&1)\n\t\t\t\t{\n\t\t\t\t\tPowerMod(pow,rou,t, ord);\n\t\t\t\t\tif(pow==1){\n\t\t\t\t\t\t//cout<<\"rou: \"<<ord<<\" \"<<rou;\n\t\t\t\t\t\treturn rou;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tPowerMod(pow,rou,t/2,ord);\n\t\t\t\t\tif(pow == (ord-1))\n\t\t\t\t\t{\n\t\t\t\t\t\t//cout<<\"rou \"<<ord<<\" \"<<rou;\n\t\t\t\t\t\treturn rou;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t}\n\telse\n\t{\n\t\tcout << \"There is no\" << 2*m <<\"-th root of unity\"<< endl;\n\t\treturn to_ZZ(1);\n\t}\n\treturn to_ZZ(1);\n}\n\nlong fft::to_long(vector<int>* bit_r){\n\n\tlong  t, length;\n\tdouble two,i;\n\ttwo = 2;\n\n\tlength =bit_r->size();\n\tt=0;\n\tfor(i = 0; i<length; i++ ){\n\t\tt =t +bit_r->at(i)*pow(two,i);\n\t}\n\treturn t;\n}\n\nvoid fft::bitreverse(long& z, long x, long d){\n\tlong i;\n\tvector<int>* temp=0;\n\ttemp = new vector<int>(d);\n\tfor(i = 0; i<d; i++){\n\t\tif(bit(x,i)==1){\n\t\t\ttemp->at(d-i-1)=1;\n\t\t}\n\t\telse{\n\t\t\ttemp->at(d-i-1)=0;\n\t\t}\n\t}\n\tz = to_long(temp);\n\tdelete temp;\n}\n\n\nvoid  fft::brevorder(vector<ZZ>* ret, vector<ZZ>* v){\n\n\tlong i,k,d,l, lv;\n\tZZ temp;\n\n\tlv = v->size();\n\tl=ret->size();\n\td = NumBits(l)-1;\n\tfor(i = 0; i<lv; i++){\n\t\tret->at(i)=v->at(i);\n\t}\n\tfor(i = 0; i<l; i++){\n\t\tbitreverse(k,i,d);\n\t\tif(i<k){\n\t\t\ttemp = ret->at(i);\n\t\t\tret->at(i) = ret->at(k);\n\t\t\tret->at(k)= temp;\n\t\t}\n\t}\n}\n\n\nvoid fft::FFT(vector<ZZ>* fft, vector<ZZ>* v , long N, ZZ rootofunity, ZZ ord){\n\n\tint n, m, m2, i, i0, i1, k, l;\n\tZZ rho, rr, z;\n\tdouble two = 2;\n\tl= v->size();\n\n\t//cout<<fft->size()<< \"  \"<<N;\n\tbrevorder(fft,v);\n\n    n = NumBits(N)-1;\t//(* N = 2**n *)\n    for(k= 0; k<n; k++){\n    \t//cout<<k<<\" \";\n   \t\tm =  pow(two,k);\n    \tm2 = 2*m;\n    \trr = 1;\n    \tPowerMod(rho,rootofunity,pow(two, n-k-1),ord);\n    //\tcout<<m2<<\" rho \"<<rho<<\" \"<<m<<\" \";\n        for (i = 0; i<m; i++){\n        \ti0=i;\n\t\t\t//cout<<\" rr \"<<rr;\n\t\t\t\twhile( i0 < N){\n\t\t\t\t\ti1=i0+m; //cout<<\" : \"<<i0<<\" \"<<i1<<\" \";\n\t\t\t\t\tMulMod(z, fft->at(i1), rr, ord);        //(* rr = rho**i *)\n\t\t\t\t\t//cout<<\" z \"<<z<<\" \";\n\t\t\t\t\tSubMod(fft->at(i1),fft->at(i0), z, ord);\n\t\t\t\t\t//cout<<fft->at(i0)<<\" \"<<fft->at(i1)<<\" \";\n\t\t\t\t\tAddMod(fft->at(i0), fft->at(i0), z, ord);\n\t\t\t\t\t//cout<<fft->at(i0)<<\" \"<<fft->at(i1)<<\" \";\n\t\t\t\t\ti0 = i0 + m2;\n\t\t\t\t}\n\t\t\t\tMulMod(rr ,rr,rho, ord) ;\n\n        }\n      //  cout<<endl;\n    }\n\n}\n\nvoid fft::FFTinv(vector<ZZ>* ret, vector<ZZ>* points, long N, ZZ rootofunity, ZZ ord){\nlong  i;\nZZ s, omega;\n\tInvMod(omega, rootofunity, ord);\n    InvMod(s,to_ZZ(N),ord);\n    FFT(ret, points,N,omega,ord);\n    for (i = 0; i< N; i++){\n        MulMod(ret->at(i), s , ret->at(i), ord);\n    }\n}\n\n\nvoid fft::fft_in(vector<ZZ>* ret, vector<ZZ>* v, ZZ rootofunity, ZZ ord, ZZ mod){\n\tint nb,t,t2,i,i0,i1,k,l;\n\tZZ rho, rr, z;\n\tdouble two = 2;\n\tl = v->size();\n\n\tbrevorder(ret, v);\n\tnb = NumBits(l)-1;\n\n\tfor(k = 0 ;  k<nb; k++){\n\t\tt =  pow(two,k);\n\t\tt2 = 2*t;\n\t\trr = 1;\n\t\tPowerMod(rho,rootofunity,pow(two, nb-k-1),ord);\n\t\tfor(i = 0; i<t; i ++){\n\t\t\ti0 = i;\n\t\t\tif(rr != 1){\n\t\t\t\twhile (i0 < l){\n\t\t\t\t\ti1=i0+t;\n\t\t\t\t\tPowerMod(z,ret->at(i1), rr, mod);\n\t\t\t\t\tMulMod(ret->at(i1),ret->at(i0), InvMod(z,mod),mod);\n\t\t\t\t\tMulMod(ret->at(i0),ret->at(i0), z, mod);\n\t\t\t\t\ti0 = i0 + t2;\n\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\twhile (i0 < l){\n\t\t\t\t\ti1=i0+t;\n\t\t\t\t\tz = ret->at(i1);\n\t\t\t\t\tMulMod(ret->at(i1),ret->at(i0), InvMod(z,mod),mod);\n\t\t\t\t\tMulMod(ret->at(i0),ret->at(i0), z, mod);\n\t\t\t\t\ti0 = i0 + t2;\n\n\t\t\t\t}\n\t\t\t}\n\t\t\t MulMod(rr, rr,rho,ord);\n\t\t}\n\t}\n}\n\n\nvoid fft::fft_sum_in(vector<ZZ>* ret, vector<ZZ>* v, ZZ rootofunity, ZZ ord){\n\tint nb,t,t2,i,i0,i1,k,l;\n\tZZ rho, rr, z;\n\tdouble two = 2;\n\tl = v->size();\n\n\tbrevorder(ret, v);\n\tnb = NumBits(l)-1;\n\tfor(k = 0 ;  k<nb; k++){\n\t\tt =  pow(two,k);\n\t\tt2 = 2*t;\n\t\trr = 1;\n\t\tPowerMod(rho,rootofunity,pow(two, nb-k-1),ord);\n\t\tfor(i = 0; i<t; i ++){\n\t\t\ti0 = i;\n\t\t\twhile (i0 < l){\n\t\t\t\ti1=i0+t;\n\t\t\t\tMulMod(z,ret->at(i1), rr, ord);\n\t\t\t\tSubMod(ret->at(i1),ret->at(i0), z, ord);\n\t\t\t\tAddMod(ret->at(i0),ret->at(i0), z, ord);\n\t\t\t\ti0 = i0 + t2;\n\n\t\t\t}\n\t\t\t MulMod(rr,rr,rho,ord);\n\t\t}\n\t}\n}\n\n\nvoid fft::fft_mult_cipher(vector<vector<vector<ZZ>* >*>* ret, vector<vector<Cipher_elg>* >* v, ZZ rootofunity, ZZ ord, ZZ mod){\n\n\tvector<vector<ZZ>* >* fft = 0;\n\tvector<ZZ>* temp_u = 0;\n\tvector<ZZ>* temp_v = 0;\n\tlong i,j, m, n,l;\n\n\tn= v->at(0)->size();\n\tm = v->size();\n\tl=2*m;\n\n\tfor(i = 0; i<n; i++){\n\t\tfft =new vector<vector<ZZ>* >(2);\n\t\ttemp_u = new vector<ZZ>(l);\n\t\ttemp_v = new vector<ZZ>(l);\n\t\ttemp_u ->at(0) = to_ZZ(1);\n\t\ttemp_v ->at(0) = to_ZZ(1);\n\t\tfor(j = 1; j <=m; j++){\n\t\t\ttemp_u->at(j)=v->at(j-1)->at(i).get_u();\n\t\t\ttemp_v->at(j)=v->at(j-1)->at(i).get_v();\n\t\t}\n\t\tfor(j = m+1; j<l; j++){\n\t\t\ttemp_u->at(j) = to_ZZ(1);\n\t\t\ttemp_v->at(j) = to_ZZ(1);\n\t\t}\n\t\tfft->at(0)=new vector<ZZ>(l);\n\t\tfft->at(1)=new vector<ZZ>(l);\n\n\t\tfft_in(fft->at(0), temp_u, rootofunity, ord, mod);\n\t\tfft_in(fft->at(1), temp_v,rootofunity, ord, mod);\n\t\tret->at(i)=fft;\n\t\tdelete temp_u;\n\t\tdelete temp_v;\n\t}\n}\n\n\nvoid fft::fft_matrix(vector<vector<ZZ>* >*  ret, vector<vector<ZZ>* >* T, ZZ rootofunity, ZZ ord){\n\n\tvector<ZZ>*  fft = 0;\n\tvector<ZZ>* temp = 0;\n\tlong i,j, m, n,l;\n\tdouble two = 2;\n\tint e;\n//\tcout<<\"in sumT \"<< T->size();\n\tn= T->at(0)->size();\n\tm = T->size();\n\t//In the case of the Ciphertexts m is a power of 2, in the normal setting m is odd in our case\n\tif(m%2==0){\n\t\te = NumBits(2*m+1)-\t1;\n\t}\n\telse{\n\t\te = NumBits(2*m+1);\n\t}\n\tl = pow(two, e);\n\tfor(i = 0; i<n; i++){\n\t\ttemp = new vector<ZZ>(m);\n\t\tfor(j = 0; j <m; j++){\n\t\t\ttemp->at(j)=T->at(j)->at(i);\n\t\t}\n\t\tfft=new vector<ZZ>(l);\n\t\tFFT(fft, temp, l, rootofunity, ord );\n\t\t//fft_sum_in(fft, temp, rootofunity, ord);\n\t\tret->at(i)=fft;\n\t\tdelete temp;\n\t}\n//\tcout<<endl;\n}\n\nvoid fft::fft_matrix_inv(vector<vector<ZZ>* >*  ret, vector<vector<ZZ>* >* T, ZZ rootofunity, ZZ ord){\n\n\tvector<ZZ>*  fft = 0;\n\tvector<ZZ>* temp = 0;\n\tlong i,j, m, n,l;\n\tdouble two = 2;\n\tint e;\n\t//cout<<\"in sumT \"<< ret->size();\n\t//In the case of the Ciphertexts m is a power of 2, in the normal setting m is odd in our case\n\tn= T->at(0)->size();\n\tm = T->size();\n\tif(m%2==0){\n\t\te = NumBits(2*m+1)-\t1;\n\t}\n\telse{\n\t\te = NumBits(2*m+1);\n\t}\n\tl = pow(two, e);\n//\tcout<<\" l ist \"<<l<<endl;\n\tfor(i = 0; i<n; i++){\n\t\ttemp = new vector<ZZ>(m);\n\t\tfor(j = 0; j <m; j++){\n\t\t\ttemp->at(j)=T->at(m-j-1)->at(i);\n\t\t}\n\t\tfft=new vector<ZZ>(l);\n\t\tFFT(fft, temp, l, rootofunity, ord );\n\t\t//fft_sum_in(fft, temp, rootofunity, ord);\n\t\tret->at(i)=fft;\n\t\tdelete temp;\n\t}\n\t//cout<<endl;\n}\n\n\nvoid fft::sum_t(vector<vector<ZZ>*>* ret, vector<vector<ZZ>* >* T, ZZ rootofunity, ZZ ord){\n\tvector<ZZ>* tem =  0;\n\tZZ temp, t;\n\tlong m,n,k,i,j,te,l;\n\tm = T->size();\n\tn = T->at(0)->size();\n\tl=2*m;\n\tfor(k= 0; k<l; k++){\n\t\ttem = new vector<ZZ>(n);\n\t\tfor(j = 0; j<n;j++){\n\t\t\ttemp = 0;\n\t\t\tfor (i = m-1; i>= 0; i--){\n\t\t\t\tPowerMod(t,rootofunity, i*(k+1),ord);\n\t\t\t\tte =fabs(i-m+1);\n\t\t\t\tMulMod(t,t,T->at(te)->at(j),ord);\n\t\t\t\tAddMod(temp, temp, t,ord);\n\t\t\t}\n\t\t\ttem->at(j) = temp;\n\t\t}\n\t\tret->at(k) = tem;\n\n\t}\n}\n\n\n\n void fft::calc_Pk(vector<vector<ZZ>*>* ret, vector<vector<Cipher_elg>* >* v, vector<vector<ZZ>* >* T, ZZ rootofunity, ZZ ord, ZZ mod, int omega_sw){\n\tlong j,m,n,l;\n\tvector<vector<vector<ZZ>* >*>* fft_t=0;\n\tvector<vector<ZZ>* >* sumT=0;\n\tZZ temp_u, te_u, temp_v, te_v,temp ;\n\tm = T->size();\n\tn= T->at(0)->size();\n\tvector<ZZ>* ret_u = new vector<ZZ>(2*m);\n\tvector<ZZ>* ret_v = new vector<ZZ>(2*m);\n\n\tfft_t = new vector<vector<vector<ZZ>* >*>(n);\n\tfft::fft_mult_cipher(fft_t, v,rootofunity, ord, mod);\n\n\tsumT = new vector<vector<ZZ>* >(n);\n\tfft::fft_matrix_inv(sumT, T, rootofunity, ord);\n\n\tl=2*m-1;\n\tfor (j = 0; j<l; j++){\n\n\t\tmulti_expo::multi_expo_LL(temp_u,fft_t, sumT, omega_sw ,j+1,0);\n\t\tmulti_expo::multi_expo_LL(temp_v,fft_t, sumT, omega_sw ,j+1,1);\n\t\tret_u->at(j) = temp_u;\n\t\tret_v->at(j) = temp_v;\n\t}\n\n\n\tmulti_expo::multi_expo_LL(temp_u ,fft_t, sumT, omega_sw ,0,0);\n\tmulti_expo::multi_expo_LL(temp_v ,fft_t, sumT, omega_sw ,0,1);\n\tret_u->at(l) = temp_u;\n\tret_v->at(l) = temp_v;\n\n\tret->at(0) = ret_u;\n\tret->at(1) = ret_v;\n\n\tFunctions::delete_vector(fft_t);\n\tFunctions::delete_vector(sumT);\n\n}\n\nvoid fft::calc_m( vector<vector<ZZ>*>* M , long m, ZZ rootofunity, ZZ ord){\n\tvector<ZZ>* Rootofunity;\n\tvector<ZZ>* div;\n\tZZ prod,temp,temp_1;\n\tlong i,j,l;\n\tl=2*m;\n\tvector<ZZ>* Rootofun = new vector<ZZ>(l);\n\tdiv =new vector<ZZ>(l);\n\n\tRootofun->at(0) = rootofunity;\n\tfor(i = 1; i<l; i++){\n\t\tMulMod(Rootofun->at(i), Rootofun->at(i-1), rootofunity,ord);\n\t}\n\tfor(i = 0 ; i<l; i++){\n\t\tprod = 1;\n\t\tfor(j = 0; j<l; j++){\n\t\t\tif (i!=j){\n\t\t\t\tMulMod(prod,prod, SubMod(Rootofun->at(i),Rootofun->at(j),ord),ord);\n\t\t\t}\n\t\t}\n\t\tdiv->at(i)= prod;\n\t}\n\tfor(i = 0; i<l; i++){\n\t\tRootofunity = new vector<ZZ>(l);\n\t\tRootofunity->at(2*m-1) = to_ZZ(1);\n\t\tPowerMod(temp,rootofunity, i+1,ord);\n\n\t\tfor(j = l-2; j>=0; j--){\n\t\t\t MulMod(Rootofunity->at(j),Rootofunity->at(j+1),temp,ord);\n\t\t}\n\t\tfor(j = l-1; j>=0; j--){\n\t\t\t MulMod(Rootofunity->at(j),Rootofunity->at(j), InvMod(div->at(i),ord),ord);\n\t\t}\n\t\tM->at(i) = Rootofunity;\n\t}\n\tdelete Rootofun;\n\tdelete div;\n}\n\n\n\n\n", "meta": {"hexsha": "2816158b8e9b950e7db6da2cc3e893a53aeb7c44", "size": 9341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fft.cpp", "max_stars_repo_name": "derbear/verifiable-shuffle", "max_stars_repo_head_hexsha": "edcf6acb13500ddd731c642ef29dae7b113076ac", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T14:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T08:28:26.000Z", "max_issues_repo_path": "src/fft.cpp", "max_issues_repo_name": "derbear/verifiable-shuffle", "max_issues_repo_head_hexsha": "edcf6acb13500ddd731c642ef29dae7b113076ac", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fft.cpp", "max_forks_repo_name": "derbear/verifiable-shuffle", "max_forks_repo_head_hexsha": "edcf6acb13500ddd731c642ef29dae7b113076ac", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T06:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T15:21:49.000Z", "avg_line_length": 20.3951965066, "max_line_length": 149, "alphanum_fraction": 0.5328123327, "num_tokens": 3753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835411997897, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.4307919531014023}}
{"text": "// g2o - General Graph Optimization\n// Copyright (C) 2012 R. Kümmerle\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright notice,\n//   this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright\n//   notice, this list of conditions and the following disclaimer in the\n//   documentation and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n// IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iostream>\n\n#ifdef G2O_USE_VENDORED_CERES\n#include \"g2o/EXTERNAL/ceres/autodiff.h\"\n#else\n#include <ceres/internal/autodiff.h>\n#endif\n\n#include \"g2o/core/auto_differentiation.h\"\n#include \"g2o/core/base_binary_edge.h\"\n#include \"g2o/core/base_vertex.h\"\n#include \"g2o/core/batch_stats.h\"\n#include \"g2o/core/block_solver.h\"\n#include \"g2o/core/optimization_algorithm_levenberg.h\"\n#include \"g2o/core/solver.h\"\n#include \"g2o/core/sparse_optimizer.h\"\n#include \"g2o/solvers/pcg/linear_solver_pcg.h\"\n#include \"g2o/stuff/command_args.h\"\n\n#if defined G2O_HAVE_CHOLMOD\n#include \"g2o/solvers/cholmod/linear_solver_cholmod.h\"\n#else\n#include \"g2o/solvers/eigen/linear_solver_eigen.h\"\n#endif\n\nusing namespace std;\n\nnamespace g2o {\nnamespace bal {\nusing Vector9 = VectorN<9>;\n}\n}  // namespace g2o\n\n/**\n * \\brief camera vertex which stores the parameters for a pinhole camera\n *\n * The parameters of the camera are\n * - rx,ry,rz representing the rotation axis, whereas the angle is given by\n * ||(rx,ry,rz)||\n * - tx,ty,tz the translation of the camera\n * - f the focal length of the camera\n * - k1, k2 two radial distortion parameters\n */\nclass VertexCameraBAL : public g2o::BaseVertex<9, g2o::bal::Vector9> {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n  VertexCameraBAL() {}\n\n  virtual bool read(std::istream& /*is*/) {\n    cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n    return false;\n  }\n\n  virtual bool write(std::ostream& /*os*/) const {\n    cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n    return false;\n  }\n\n  virtual void setToOriginImpl() {\n    cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n  }\n\n  virtual void oplusImpl(const double* update) {\n    g2o::bal::Vector9::ConstMapType v(update, VertexCameraBAL::Dimension);\n    _estimate += v;\n  }\n};\n\n/**\n * \\brief 3D world feature\n *\n * A 3D point feature in the world\n */\nclass VertexPointBAL : public g2o::BaseVertex<3, g2o::Vector3> {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n  VertexPointBAL() {}\n\n  virtual bool read(std::istream& /*is*/) {\n    cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n    return false;\n  }\n\n  virtual bool write(std::ostream& /*os*/) const {\n    cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n    return false;\n  }\n\n  virtual void setToOriginImpl() {\n    cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n  }\n\n  virtual void oplusImpl(const double* update) {\n    g2o::Vector3::ConstMapType v(update);\n    _estimate += v;\n  }\n};\n\n/**\n * \\brief edge representing the observation of a world feature by a camera\n *\n * see: http://grail.cs.washington.edu/projects/bal/\n * We use a pinhole camera model; the parameters we estimate for each camera\n * area rotation R, a translation t, a focal length f and two radial distortion\n * parameters k1 and k2. The formula for projecting a 3D point X into a camera\n * R,t,f,k1,k2 is:\n * P  =  R * X + t     (conversion from world to camera coordinates)\n * p  = -P / P.z       (perspective division)\n * p' =  f * r(p) * p  (conversion to pixel coordinates) where P.z is the third\n * (z) coordinate of P.\n *\n * In the last equation, r(p) is a function that computes a scaling factor to\n * undo the radial distortion: r(p) = 1.0 + k1 * ||p||^2 + k2 * ||p||^4.\n *\n * This gives a projection in pixels, where the origin of the image is the\n * center of the image, the positive x-axis points right, and the positive\n * y-axis points up (in addition, in the camera coordinate system, the positive\n * z-axis points backwards, so the camera is looking down the negative z-axis,\n * as in OpenGL).\n */\nclass EdgeObservationBAL\n    : public g2o::BaseBinaryEdge<2, g2o::Vector2, VertexCameraBAL,\n                                 VertexPointBAL> {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n  EdgeObservationBAL() {}\n  virtual bool read(std::istream& /*is*/) {\n    cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n    return false;\n  }\n  virtual bool write(std::ostream& /*os*/) const {\n    cerr << __PRETTY_FUNCTION__ << \" not implemented yet\" << endl;\n    return false;\n  }\n\n  /**\n   * templatized function to compute the error as described in the comment above\n   */\n  template <typename T>\n  bool operator()(const T* p_camera, const T* p_point, T* p_error) const {\n    typename g2o::VectorN<9, T>::ConstMapType camera(p_camera);\n    typename g2o::VectorN<3, T>::ConstMapType point(p_point);\n\n    typename g2o::VectorN<3, T> p;\n\n    // Rodrigues' formula for the rotation\n    T theta = camera.template head<3>().norm();\n    if (theta > T(0)) {\n      g2o::VectorN<3, T> v = camera.template head<3>() / theta;\n      T cth = cos(theta);\n      T sth = sin(theta);\n\n      g2o::VectorN<3, T> vXp = v.cross(point);\n      T vDotp = v.dot(point);\n      T oneMinusCth = T(1) - cth;\n\n      p = point * cth + vXp * sth + v * vDotp * oneMinusCth;\n    } else {\n      // taylor expansion for theta close to zero\n      p = point + camera.template head<3>().cross(point);\n    }\n\n    // translation of the camera\n    p += camera.template segment<3>(3);\n\n    // perspective division\n    g2o::VectorN<2, T> projectedPoint = -p.template head<2>() / p(2);\n\n    // conversion to pixel coordinates\n    T radiusSqr = projectedPoint.squaredNorm();\n    const T& f = camera(6);\n    const T& k1 = camera(7);\n    const T& k2 = camera(8);\n    T r_p = T(1) + k1 * radiusSqr + k2 * radiusSqr * radiusSqr;\n    g2o::VectorN<2, T> prediction = f * r_p * projectedPoint;\n\n    // compute the error\n    typename g2o::VectorN<2, T>::MapType error(p_error);\n    error = prediction - measurement().cast<T>();\n    (void)error;\n    return true;\n  }\n\n  G2O_MAKE_AUTO_AD_FUNCTIONS\n};\n\nint main(int argc, char** argv) {\n  int maxIterations;\n  bool verbose;\n  bool usePCG;\n  string outputFilename;\n  string inputFilename;\n  string statsFilename;\n  g2o::CommandArgs arg;\n  arg.param(\"i\", maxIterations, 5, \"perform n iterations\");\n  arg.param(\"o\", outputFilename, \"\", \"write points into a vrml file\");\n  arg.param(\"pcg\", usePCG, false, \"use PCG instead of the Cholesky\");\n  arg.param(\"v\", verbose, false, \"verbose output of the optimization process\");\n  arg.param(\"stats\", statsFilename, \"\", \"specify a file for the statistics\");\n  arg.paramLeftOver(\"graph-input\", inputFilename, \"\",\n                    \"file which will be processed\");\n\n  arg.parseArgs(argc, argv);\n\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<9, 3>> BalBlockSolver;\n#ifdef G2O_HAVE_CHOLMOD\n  string choleskySolverName = \"CHOLMOD\";\n  typedef g2o::LinearSolverCholmod<BalBlockSolver::PoseMatrixType>\n      BalLinearSolver;\n#else\n  string choleskySolverName = \"Eigen\";\n  typedef g2o::LinearSolverEigen<BalBlockSolver::PoseMatrixType>\n      BalLinearSolver;\n#endif\n  typedef g2o::LinearSolverPCG<BalBlockSolver::PoseMatrixType>\n      BalLinearSolverPCG;\n\n  g2o::SparseOptimizer optimizer;\n  std::unique_ptr<g2o::LinearSolver<BalBlockSolver::PoseMatrixType>>\n      linearSolver;\n  if (usePCG) {\n    cout << \"Using PCG\" << endl;\n    linearSolver = g2o::make_unique<BalLinearSolverPCG>();\n  } else {\n    cout << \"Using Cholesky: \" << choleskySolverName << endl;\n    auto cholesky = g2o::make_unique<BalLinearSolver>();\n    cholesky->setBlockOrdering(true);\n    linearSolver = std::move(cholesky);\n  }\n  g2o::OptimizationAlgorithmLevenberg* solver =\n      new g2o::OptimizationAlgorithmLevenberg(\n          g2o::make_unique<BalBlockSolver>(std::move(linearSolver)));\n\n  // solver->setUserLambdaInit(1);\n  optimizer.setAlgorithm(solver);\n  if (statsFilename.size() > 0) {\n    optimizer.setComputeBatchStatistics(true);\n  }\n\n  vector<VertexPointBAL*> points;\n  vector<VertexCameraBAL*> cameras;\n\n  // parse BAL dataset\n  cout << \"Loading BAL dataset \" << inputFilename << endl;\n  {\n    ifstream ifs(inputFilename.c_str());\n    int numCameras, numPoints, numObservations;\n    ifs >> numCameras >> numPoints >> numObservations;\n\n    cerr << PVAR(numCameras) << \" \" << PVAR(numPoints) << \" \"\n         << PVAR(numObservations) << endl;\n\n    int id = 0;\n    cameras.reserve(numCameras);\n    for (int i = 0; i < numCameras; ++i, ++id) {\n      VertexCameraBAL* cam = new VertexCameraBAL;\n      cam->setId(id);\n      optimizer.addVertex(cam);\n      cameras.push_back(cam);\n    }\n\n    points.reserve(numPoints);\n    for (int i = 0; i < numPoints; ++i, ++id) {\n      VertexPointBAL* p = new VertexPointBAL;\n      p->setId(id);\n      p->setMarginalized(true);\n      bool addedVertex = optimizer.addVertex(p);\n      if (!addedVertex) {\n        cerr << \"failing adding vertex\" << endl;\n      }\n      points.push_back(p);\n    }\n\n    // read in the observation\n    for (int i = 0; i < numObservations; ++i) {\n      int camIndex, pointIndex;\n      double obsX, obsY;\n      ifs >> camIndex >> pointIndex >> obsX >> obsY;\n\n      assert(camIndex >= 0 && (size_t)camIndex < cameras.size() &&\n             \"Index out of bounds\");\n      VertexCameraBAL* cam = cameras[camIndex];\n      assert(pointIndex >= 0 && (size_t)pointIndex < points.size() &&\n             \"Index out of bounds\");\n      VertexPointBAL* point = points[pointIndex];\n\n      EdgeObservationBAL* e = new EdgeObservationBAL;\n      e->setVertex(0, cam);\n      e->setVertex(1, point);\n      e->setInformation(g2o::Matrix2::Identity());\n      e->setMeasurement(g2o::Vector2(obsX, obsY));\n      bool addedEdge = optimizer.addEdge(e);\n      if (!addedEdge) {\n        cerr << \"error adding edge\" << endl;\n      }\n    }\n\n    // read in the camera params\n    for (int i = 0; i < numCameras; ++i) {\n      g2o::bal::Vector9 cameraParameter;\n      for (int j = 0; j < 9; ++j) ifs >> cameraParameter(j);\n      VertexCameraBAL* cam = cameras[i];\n      cam->setEstimate(cameraParameter);\n    }\n\n    // read in the points\n    for (int i = 0; i < numPoints; ++i) {\n      g2o::Vector3 p;\n      ifs >> p(0) >> p(1) >> p(2);\n      VertexPointBAL* point = points[i];\n      point->setEstimate(p);\n    }\n  }\n  cout << \"done.\" << endl;\n\n  cout << \"Initializing ... \" << flush;\n  optimizer.initializeOptimization();\n  cout << \"done.\" << endl;\n  optimizer.setVerbose(verbose);\n  cout << \"Start to optimize\" << endl;\n  optimizer.optimize(maxIterations);\n\n  if (statsFilename != \"\") {\n    cerr << \"writing stats to file \\\"\" << statsFilename << \"\\\" ... \";\n    ofstream fout(statsFilename.c_str());\n    const g2o::BatchStatisticsContainer& bsc = optimizer.batchStatistics();\n    for (size_t i = 0; i < bsc.size(); i++) fout << bsc[i] << endl;\n    cerr << \"done.\" << endl;\n  }\n\n  // dump the points\n  if (outputFilename.size() > 0) {\n    ofstream fout(outputFilename.c_str());  // loadable with meshlab\n    fout << \"#VRML V2.0 utf8\\n\"\n         << \"Shape {\\n\"\n         << \"  appearance Appearance {\\n\"\n         << \"    material Material {\\n\"\n         << \"      diffuseColor \" << 1 << \" \" << 0 << \" \" << 0 << \"\\n\"\n         << \"      ambientIntensity 0.2\\n\"\n         << \"      emissiveColor 0.0 0.0 0.0\\n\"\n         << \"      specularColor 0.0 0.0 0.0\\n\"\n         << \"      shininess 0.2\\n\"\n         << \"      transparency 0.0\\n\"\n         << \"    }\\n\"\n         << \"  }\\n\"\n         << \"  geometry PointSet {\\n\"\n         << \"    coord Coordinate {\\n\"\n         << \"      point [\\n\";\n    for (vector<VertexPointBAL*>::const_iterator it = points.begin();\n         it != points.end(); ++it) {\n      fout << (*it)->estimate().transpose() << endl;\n    }\n    fout << \"    ]\\n\"\n         << \"  }\\n\"\n         << \"}\\n\"\n         << \"  }\\n\";\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "936223737004083773f662ccb918070ecc6c59c7", "size": 12837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/g2o/g2o/examples/bal/bal_example.cpp", "max_stars_repo_name": "Refstop/VSLAM_Example", "max_stars_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "3rdparty/g2o/g2o/examples/bal/bal_example.cpp", "max_issues_repo_name": "Refstop/VSLAM_Example", "max_issues_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3rdparty/g2o/g2o/examples/bal/bal_example.cpp", "max_forks_repo_name": "Refstop/VSLAM_Example", "max_forks_repo_head_hexsha": "060b9419f79f035d1c9ebfa75ad46e2e9a53e992", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0, "max_line_length": 80, "alphanum_fraction": 0.6484381086, "num_tokens": 3527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.43071980586483855}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2021 Ilias Khairullin <ilias@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_RANDOM_ALGEBRAIC_RANDOM_DEVICE_HPP\n#define CRYPTO3_RANDOM_ALGEBRAIC_RANDOM_DEVICE_HPP\n\n#include <type_traits>\n\n#include <boost/random/random_device.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n#include <nil/crypto3/algebra/type_traits.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace random {\n            /*!\n             * @brief\n             * @tparam AlgebraicType denote an some algebraic type (field, curve group types).\n             *\n             * algebraic_random_device is adapter wrapping boost::random_device producing random values of algebraic\n             * type.\n             *\n             * The class template algebraic_random_device models a \\UniformRandomBitGenerator.\n             * https://en.cppreference.com/w/cpp/named_req/UniformRandomBitGenerator\n             */\n            template<typename AlgebraicType, typename = void>\n            struct algebraic_random_device;\n\n            template<typename AlgebraicType>\n            struct algebraic_random_device<\n                AlgebraicType, typename std::enable_if<algebra::is_field<AlgebraicType>::value &&\n                                                       !algebra::is_extended_field<AlgebraicType>::value>::type> {\n            protected:\n                typedef AlgebraicType field_type;\n                typedef typename field_type::value_type field_value_type;\n                typedef typename field_type::integral_type integral_type;\n\n                typedef boost::random_device internal_generator_type;\n                typedef boost::random::uniform_int_distribution<integral_type> internal_distribution_type;\n\n                constexpr static integral_type _min = 0;\n                constexpr static integral_type _max = field_type::modulus - 1;\n\n            public:\n                typedef field_value_type result_type;\n\n                /** Returns a random value in the range [min, max]. */\n                result_type operator()() {\n                    return dist(gen);\n                }\n\n                /** Returns the smallest value that the \\algebraic_random_device can produce. */\n                constexpr static inline result_type min() {\n                    constexpr result_type min_value(_min);\n                    return min_value;\n                }\n\n                /** Returns the largest value that the \\algebraic_random_device can produce. */\n                constexpr static inline result_type max() {\n                    constexpr result_type max_value(_max);\n                    return max_value;\n                }\n\n            protected:\n                internal_generator_type gen;\n                internal_distribution_type dist = internal_distribution_type(_min, _max);\n            };\n\n            template<typename AlgebraicType>\n            struct algebraic_random_device<\n                AlgebraicType, typename std::enable_if<algebra::is_field<AlgebraicType>::value &&\n                                                       algebra::is_extended_field<AlgebraicType>::value>::type> {\n            protected:\n                typedef AlgebraicType extended_field_type;\n                typedef typename extended_field_type::value_type extended_field_value_type;\n                typedef typename extended_field_type::underlying_field_type underlying_field_type;\n\n                typedef algebraic_random_device<underlying_field_type> internal_generator_type;\n\n            public:\n                typedef extended_field_value_type result_type;\n\n                /** Returns a random value in the range [min, max]. */\n                result_type operator()() {\n                    result_type result;\n                    for (auto &coord : result.data) {\n                        coord = gen();\n                    }\n\n                    return result;\n                }\n\n                /** Returns the smallest value that the \\algebraic_random_device can produce. */\n                // TODO: evaluate min_value at compile-time\n                constexpr static inline result_type min() {\n                    result_type min_value;\n                    for (auto &coord : min_value.data) {\n                        coord = internal_generator_type::min();\n                    }\n\n                    return min_value;\n                }\n\n                /** Returns the largest value that the \\algebraic_random_device can produce. */\n                // TODO: evaluate max_value at compile-time\n                constexpr static inline result_type max() {\n                    result_type max_value;\n                    for (auto &coord : max_value.data) {\n                        coord = internal_generator_type::max();\n                    }\n\n                    return max_value;\n                }\n\n            protected:\n                internal_generator_type gen;\n            };\n\n            template<typename AlgebraicType>\n            struct algebraic_random_device<\n                AlgebraicType, typename std::enable_if<algebra::is_curve_group<AlgebraicType>::value>::type> {\n            protected:\n                typedef AlgebraicType group_type;\n                typedef typename group_type::value_type group_value_type;\n                typedef typename group_type::curve_type::scalar_field_type scalar_field_type;\n\n                typedef algebraic_random_device<scalar_field_type> internal_generator_type;\n\n            public:\n                typedef group_value_type result_type;\n\n                /**\n                 * Returns a random value in the range [min, max]. Elements of group are ordered in exponent growing\n                 * order with respect to group base element.\n                 */\n                // TODO: check correctness of the generation method\n                result_type operator()() {\n                    return result_type::one() * gen();\n                }\n\n                /** Returns the smallest value that the \\algebraic_random_device can produce. */\n                // TODO: evaluate returned value at compile-time\n                constexpr static inline result_type min() {\n                    return result_type::zero();\n                }\n\n                /** Returns the largest value that the \\algebraic_random_device can produce. */\n                // TODO: evaluate returned value at compile-time\n                constexpr static inline result_type max() {\n                    return result_type::one() * (scalar_field_type::modulus - 1);\n                }\n\n            protected:\n                internal_generator_type gen;\n            };\n        }    // namespace random\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_RANDOM_ALGEBRAIC_RANDOM_DEVICE_HPP\n", "meta": {"hexsha": "249c196ab1b69802ca379f1730dd3c7577ccd5d4", "size": 8060, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/random/include/nil/crypto3/random/algebraic_random_device.hpp", "max_stars_repo_name": "Curryrasul/knapsack-snark", "max_stars_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "libs/random/include/nil/crypto3/random/algebraic_random_device.hpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/random/include/nil/crypto3/random/algebraic_random_device.hpp", "max_forks_repo_name": "Curryrasul/knapsack-snark", "max_forks_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:53:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:53:21.000Z", "avg_line_length": 43.8043478261, "max_line_length": 116, "alphanum_fraction": 0.5861042184, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4305124578109728}}
{"text": "/*\n * GridMapMath.hpp\n *\n *  Created on: Dec 2, 2013\n *      Author: Péter Fankhauser\n *\t Institute: ETH Zurich, Autonomous Systems Lab\n */\n\n#pragma once\n\n#include <Eigen/Core>\n#include <vector>\n#include <map>\n\nnamespace grid_map_lib {\n\n/*!\n * Gets the position of a cell specified by its index in the map frame.\n * @param[out] position the position of the center of the cell in the map frame.\n * @param[in] index of the cell.\n * @param[in] mapLength the lengths in x and y direction.\n * @param[in] mapPosition the position of the map.\n * @param[in] resolution the resolution of the map.\n * @param[in] bufferSize the size of the buffer (optional).\n * @param[in] bufferStartIndex the index of the starting point of the circular buffer (optional).\n * @return true if successful, false if index not within range of buffer.\n */\nbool getPositionFromIndex(Eigen::Vector2d& position,\n                          const Eigen::Array2i& index,\n                          const Eigen::Array2d& mapLength,\n                          const Eigen::Vector2d& mapPosition,\n                          const double& resolution,\n                          const Eigen::Array2i& bufferSize,\n                          const Eigen::Array2i& bufferStartIndex = Eigen::Array2i::Zero());\n\n/*!\n * Gets the index of the cell which contains a position in the map frame.\n * @param[out] index of the cell.\n * @param[in] position the position in the map frame.\n * @param[in] mapLength the lengths in x and y direction.\n * @param[in] mapPosition the position of the map.\n * @param[in] resolution the resolution of the map.\n * @param[in] bufferSize the size of the buffer (optional).\n * @param[in] bufferStartIndex the index of the starting point of the circular buffer (optional).\n * @return true if successful, false if position outside of map.\n */\nbool getIndexFromPosition(Eigen::Array2i& index,\n                          const Eigen::Vector2d& position,\n                          const Eigen::Array2d& mapLength,\n                          const Eigen::Vector2d& mapPosition,\n                          const double& resolution,\n                          const Eigen::Array2i& bufferSize,\n                          const Eigen::Array2i& bufferStartIndex = Eigen::Array2i::Zero());\n\n/*!\n * Checks if position is within the map boundaries.\n * @param[in] position the position which is to be checked.\n * @param[in] mapLength the length of the map.\n * @param[in] mapPosition the position of the map.\n * @return true if position is within map, false otherwise.\n */\nbool checkIfPositionWithinMap(const Eigen::Vector2d& position,\n                              const Eigen::Array2d& mapLength,\n                              const Eigen::Vector2d& mapPosition);\n\n/*!\n * Gets the position of the data structure origin.\n * @param[in] position the position of the map.\n * @param[in] mapLength the map length.\n * @param[out] positionOfOrigin the position of the data structure origin.\n */\nvoid getPositionOfDataStructureOrigin(const Eigen::Vector2d& position,\n                                      const Eigen::Array2d& mapLength,\n                                      Eigen::Vector2d& positionOfOrigin);\n\n/*!\n * Computes how many cells/indeces the map is moved based on a position shift in\n * the grid map frame. Use this function if you are moving the grid map\n * and want to ensure that the cells match before and after.\n * @param[out] indexShift the corresponding shift of the indices.\n * @param[in] positionShift the desired position shift.\n * @param[in] resolution the resolution of the map.\n * @return true if successful.\n */\nbool getIndexShiftFromPositionShift(Eigen::Array2i& indexShift,\n                                    const Eigen::Vector2d& positionShift,\n                                    const double& resolution);\n\n/*!\n * Computes the corresponding position shift from a index shift. Use this function\n * if you are moving the grid map and want to ensure that the cells match\n * before and after.\n * @param[out] positionShift the corresponding shift in position in the grid map frame.\n * @param[in] indexShift the desired shift of the indeces.\n * @param[in] resolution the resolution of the map.\n * @return true if successful.\n */\nbool getPositionShiftFromIndexShift(Eigen::Vector2d& positionShift,\n                                    const Eigen::Array2i& indexShift,\n                                    const double& resolution);\n\n/*!\n * Checks if index is within range of the buffer.\n * @param[in] index to check.\n * @param[in] bufferSize the size of the buffer.\n * @return true if index is within, and false if index is outside of the buffer.\n */\nbool checkIfIndexWithinRange(const Eigen::Array2i& index, const Eigen::Array2i& bufferSize);\n\n/*!\n * Maps an index that runs out of the range of the circular buffer back into allowed the region.\n * This is the 2d version of mapIndexWithinRange(int&, const int&).\n * @param[in/out] index the indeces that will be mapped into the valid region of the buffer.\n * @param[in] bufferSize the size of the buffer.\n */\nvoid mapIndexWithinRange(Eigen::Array2i& index,\n                         const Eigen::Array2i& bufferSize);\n\n/*!\n * Maps an index that runs out of the range of the circular buffer back into allowed the region.\n * @param[in/out] index the index that will be mapped into the valid region of the buffer.\n * @param[in] bufferSize the size of the buffer.\n */\nvoid mapIndexWithinRange(int& index, const int& bufferSize);\n\n/*!\n * Limits (cuts off) the position to lie inside the map.\n * @param[in/out] position the position to be limited.\n * @param[in] mapLength the lengths in x and y direction.\n * @param[in] mapPosition the position of the map.\n */\nvoid limitPositionToRange(Eigen::Vector2d& position,\n                          const Eigen::Array2d& mapLength,\n                          const Eigen::Vector2d& mapPosition);\n\n/*!\n * Provides the alignment transformation from the buffer order (outer/inner storage)\n * and the map frame (x/y-coordinate).\n * @return the alignment transformation.\n */\nconst Eigen::Matrix2i getBufferOrderToMapFrameAlignment();\n\n/*!\n * Given a map and a desired submap (defined by position and size), this function computes\n * various information about the submap. The returned submap might be smaller than the requested\n * size as it respects the boundaries of the map.\n * @param[out] submapTopLeftIndex the top left index of the returned submap.\n * @param[out] submapBufferSize the buffer size of the returned submap.\n * @param[out] submapPosition the position of the submap (center) in the map frame.\n * @param[out] submapLength the length of the submap.\n * @param[out] requestedIndexInSubmap the index in the submap that corresponds to the requested\n *             position of the submap.\n * @param[in] requestedSubmapPosition the requested submap position (center) in the map frame.\n * @param[in] requestedSubmapLength the requested submap length.\n * @param[in] mapLength the lengths in x and y direction.\n * @param[in] mapPosition the position of the map.\n * @param[in] resolution the resolution of the map.\n * @param[in] bufferSize the buffer size of the map.\n * @param[in] bufferStartIndex the index of the starting point of the circular buffer (optional).\n * @return true if successful.\n */\nbool getSubmapInformation(Eigen::Array2i& submapTopLeftIndex,\n                          Eigen::Array2i& submapBufferSize,\n                          Eigen::Vector2d& submapPosition,\n                          Eigen::Array2d& submapLength,\n                          Eigen::Array2i& requestedIndexInSubmap,\n                          const Eigen::Vector2d& requestedSubmapPosition,\n                          const Eigen::Vector2d& requestedSubmapLength,\n                          const Eigen::Array2d& mapLength,\n                          const Eigen::Vector2d& mapPosition,\n                          const double& resolution,\n                          const Eigen::Array2i& bufferSize,\n                          const Eigen::Array2i& bufferStartIndex = Eigen::Array2i::Zero());\n\n/*!\n * Computes the regions in the circular buffer that make up the data for\n * a requested submap.\n * @param[out] submapIndeces the list of indeces (top-left) for the buffer regions.\n * @param[out] submapSizes the sizes of the buffer regions.\n * @param[in] submapIndex the index (top-left) for the requested submap.\n * @param[in] submapBufferSize the size of the requested submap.\n * @param[in] bufferSize the buffer size of the map.\n * @param[in] bufferStartIndex the index of the starting point of the circular buffer (optional).\n * @return true if successful, false if requested submap is not fully contained in the map.\n */\nbool getBufferRegionsForSubmap(std::vector<Eigen::Array2i>& submapIndeces,\n                               std::vector<Eigen::Array2i>& submapSizes,\n                               const Eigen::Array2i& submapIndex,\n                               const Eigen::Array2i& submapBufferSize,\n                               const Eigen::Array2i& bufferSize,\n                               const Eigen::Array2i& bufferStartIndex = Eigen::Array2i::Zero());\n\n/*!\n * Increases the index by one to iterate through the map.\n * Increments either to the neighboring index to the right or to\n * the start of the lower row. Returns false if end of iterations are reached.\n * @param[in/out] index the index in the map that is incremented (corrected for the circular buffer).\n * @param[in] bufferSize the map buffer size.\n * @param[in] bufferStartIndex the map buffer start index.\n * @return true if successfully incremented indeces, false if end of iteration limits are reached.\n */\nbool incrementIndex(Eigen::Array2i& index, const Eigen::Array2i& bufferSize,\n                    const Eigen::Array2i& bufferStartIndex = Eigen::Array2i::Zero());\n\n/*!\n * Increases the index by one to iterate through the cells of a submap.\n * Increments either to the neighboring index to the right or to\n * the start of the lower row. Returns false if end of iterations are reached.\n *\n * Note: This function does not check if submap actually fits to the map. This needs\n * to be checked before separately.\n *\n * @param[in/out] submapIndex the index in the submap that is incremented.\n * @param[out] index the index in the map that is incremented (corrected for the circular buffer).\n * @param[in] submapTopLefIndex the top left index of the submap.\n * @param[in] submapBufferSize the submap buffer size.\n * @param[in] bufferSize the map buffer size.\n * @param[in] bufferStartIndex the map buffer start index.\n * @return true if successfully incremented indeces, false if end of iteration limits are reached.\n */\nbool incrementIndexForSubmap(Eigen::Array2i& submapIndex, Eigen::Array2i& index, const Eigen::Array2i& submapTopLeftIndex,\n                             const Eigen::Array2i& submapBufferSize, const Eigen::Array2i& bufferSize,\n                             const Eigen::Array2i& bufferStartIndex = Eigen::Array2i::Zero());\n\n/*!\n * Returns the 1d index corresponding to the 2d index for either row- or column-major format.\n * Note: Eigen is defaulting to column-major format.\n * @param[in] index the 2d index.\n * @param[in] bufferSize the map buffer size.\n * @param[in] (optional) rowMajor if the 1d index is generated for row-major format.\n * @return the 1d index.\n */\nunsigned int get1dIndexFrom2dIndex(const Eigen::Array2i& index, const Eigen::Array2i& bufferSize, const bool rowMajor);\n\n/*!\n * The definition of the buffer regions.\n */\nenum class BufferRegion\n{\n  TopLeft,\n  TopRight,\n  BottomLeft,\n  BottomRight\n};\n\n/*!\n * The definition of the position in the list for the buffer regions.\n */\nstatic std::map<BufferRegion, int> bufferRegionIndeces =\n{\n{ BufferRegion::TopLeft, 0 },\n{ BufferRegion::TopRight, 1 },\n{ BufferRegion::BottomLeft, 2 },\n{ BufferRegion::BottomRight, 3 } };\n\n} // namespace\n", "meta": {"hexsha": "c689d6cac3394904288d69e2055bcb2a2d626013", "size": 11839, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "IHMCPerception/catkin_ws/src/grid_map/grid_map_lib/include/grid_map_lib/GridMapMath.hpp", "max_stars_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_stars_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 170.0, "max_stars_repo_stars_event_min_datetime": "2016-02-01T18:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:28:01.000Z", "max_issues_repo_path": "IHMCPerception/catkin_ws/src/grid_map/grid_map_lib/include/grid_map_lib/GridMapMath.hpp", "max_issues_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_issues_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 162.0, "max_issues_repo_issues_event_min_datetime": "2016-01-29T17:04:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T16:25:37.000Z", "max_forks_repo_path": "IHMCPerception/catkin_ws/src/grid_map/grid_map_lib/include/grid_map_lib/GridMapMath.hpp", "max_forks_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_forks_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2016-01-28T22:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:11:24.000Z", "avg_line_length": 46.0661478599, "max_line_length": 122, "alphanum_fraction": 0.6763240139, "num_tokens": 2655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5888891307678321, "lm_q1q2_score": 0.43051245090979046}}
{"text": "/*\nAuthors: Deevashwer Rathee\nCopyright:\nCopyright (c) 2021 Microsoft Research\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include \"LinearOT/linear-ot.h\"\n#include <cmath>\n\n#define MAX_NUM_OT (1 << 20)\n\n#define USE_EIGEN\n#ifdef USE_EIGEN\n#include <Eigen/Dense>\n#endif\n\nusing namespace std;\nusing namespace sci;\n\nvoid matrix_transpose(uint64_t *A, int32_t m, int32_t n, int d = 1) {\n  uint64_t *tmpA = new uint64_t[m * n * d];\n  memcpy(tmpA, A, m * n * d * sizeof(uint64_t));\n  for (int i = 0; i < m; i++) {\n    for (int j = 0; j < n; j++) {\n      if (d == 1) {\n        A[j * m + i] = tmpA[i * n + j];\n      } else {\n        memcpy(A + (j * m + i) * d, tmpA + (i * n + j) * d,\n               d * sizeof(uint64_t));\n      }\n    }\n  }\n  delete[] tmpA;\n}\n\nLinearOT::LinearOT(int party, NetIO *io, OTPack<NetIO> *otpack) {\n  this->party = party;\n  this->io = io;\n  this->otpack = otpack;\n  this->aux = new AuxProtocols(party, io, otpack);\n  this->trunc = new Truncation(party, io, otpack, aux);\n  this->xt = new XTProtocol(party, io, otpack, aux);\n}\n\nLinearOT::~LinearOT() {\n  delete aux;\n  delete trunc;\n}\n\nvoid LinearOT::hadamard_cleartext(int dim, uint64_t *inA, uint64_t *inB,\n                                  uint64_t *outC) {\n  matmul_cleartext(1, dim, 1, inA, inB, outC, false);\n}\n\n#ifdef USE_EIGEN\nvoid matmul_cleartext_eigen(int dim1, int dim2, int dim3, uint64_t *inA,\n                            uint64_t *inB, uint64_t *outC) {\n  Eigen::Matrix<uint64_t, Eigen::Dynamic, Eigen::Dynamic> eigen_A(dim1, dim2);\n  Eigen::Matrix<uint64_t, Eigen::Dynamic, Eigen::Dynamic> eigen_B(dim2, dim3);\n  Eigen::Matrix<uint64_t, Eigen::Dynamic, Eigen::Dynamic> eigen_C(dim1, dim3);\n\n  for (int i = 0; i < dim1; i++) {\n    for (int j = 0; j < dim2; j++) {\n      eigen_A(i, j) = Arr2DIdxRowM(inA, dim1, dim2, i, j);\n    }\n  }\n  for (int i = 0; i < dim2; i++) {\n    for (int j = 0; j < dim3; j++) {\n      eigen_B(i, j) = Arr2DIdxRowM(inB, dim2, dim3, i, j);\n    }\n  }\n  eigen_C = eigen_A * eigen_B;\n  for (int i = 0; i < dim1; i++) {\n    for (int j = 0; j < dim3; j++) {\n      Arr2DIdxRowM(outC, dim1, dim3, i, j) = eigen_C(i, j);\n    }\n  }\n}\n#endif\n\nvoid LinearOT::matmul_cleartext(int dim1, int dim2, int dim3, uint64_t *inA,\n                                uint64_t *inB, uint64_t *outC,\n                                bool accumulate) {\n  if (!accumulate) {\n    for (int i = 0; i < dim1; i++) {\n      for (int j = 0; j < dim3; j++) {\n        for (int k = 0; k < dim2; k++) {\n          outC[dim2 * dim3 * i + dim2 * j + k] =\n              inA[dim2 * i + k] * inB[dim3 * k + j];\n        }\n      }\n    }\n    return;\n  }\n#ifndef USE_EIGEN\n  for (int i = 0; i < dim1; i++) {\n    for (int j = 0; j < dim3; j++) {\n      outC[i * dim3 + j] = 0;\n      for (int k = 0; k < dim2; k++) {\n        outC[i * dim3 + j] += (inA[dim2 * i + k] * inB[dim3 * k + j]);\n      }\n    }\n  }\n#else\n  assert(accumulate == true && \"Eigen not configured for accumulate = false\");\n  matmul_cleartext_eigen(dim1, dim2, dim3, inA, inB, outC);\n#endif\n}\n\nvoid LinearOT::hadamard_cross_terms(int32_t dim, uint64_t *inA, uint64_t *inB,\n                                    uint64_t *outC, int32_t bwA, int32_t bwB,\n                                    int32_t bwC, MultMode mode) {\n  matmul_cross_terms(1, dim, 1, inA, inB, outC, bwA, bwB, bwC, false, mode);\n}\n\nvoid LinearOT::hadamard_product(int32_t dim, uint64_t *inA, uint64_t *inB,\n                                uint64_t *outC, int32_t bwA, int32_t bwB,\n                                int32_t bwC, bool signed_arithmetic,\n                                bool signed_B, MultMode mode, uint8_t *msbA,\n                                uint8_t *msbB) {\n  matrix_multiplication(1, dim, 1, inA, inB, outC, bwA, bwB, bwC,\n                        signed_arithmetic, signed_B, false, mode, msbA, msbB);\n}\n\nvoid LinearOT::matmul_cross_terms(int32_t dim1, int32_t dim2, int32_t dim3,\n                                  uint64_t *inA, uint64_t *inB, uint64_t *outC,\n                                  int32_t bwA, int32_t bwB, int32_t bwC,\n                                  bool accumulate, MultMode mode) {\n  bool use_straight_ot = false, use_reversed_ot = false;\n  uint64_t maskC = (bwC == 64 ? -1 : ((1ULL << bwC) - 1));\n  uint64_t *inS, *inR;\n  int32_t bwR, dimS1, dimS2, dimR1, dimR2;\n  // A whole row of values is multiplied to a element using only bwR OTs\n  bool row_batching;\n  if (mode == MultMode::Alice_has_A) {\n    use_straight_ot = true;\n    row_batching = false;\n  } else if (mode == MultMode::Bob_has_A) {\n    use_straight_ot = true;\n    row_batching = true;\n  } else if (mode == MultMode::Alice_has_B) {\n    use_reversed_ot = true;\n    row_batching = false;\n  } else if (mode == MultMode::Bob_has_B) {\n    use_reversed_ot = true;\n    row_batching = true;\n  } else {\n    use_straight_ot = true;\n    use_reversed_ot = true;\n    // if (bwA*dim1*dim2 > bwB*dim2*dim3) {\n    if (bwA > bwB) {\n      row_batching = false;\n    } else {\n      row_batching = true;\n    }\n  }\n  if (row_batching) {\n    inS = inB;\n    inR = inA;\n    bwR = bwA;\n    dimS1 = dim2;\n    dimS2 = dim3;\n    dimR1 = dim1;\n    dimR2 = dim2;\n  } else {\n    // inS = inA;\n    inS = new uint64_t[dim1 * dim2];\n    memcpy(inS, inA, dim1 * dim2 * sizeof(uint64_t));\n    inR = inB;\n    bwR = bwB;\n    dimS1 = dim1;\n    dimS2 = dim2;\n    dimR1 = dim2;\n    dimR2 = dim3;\n  }\n\n  int32_t num_ot = dimR1 * dimR2 * bwR;\n  int32_t msgs_per_ot = (row_batching ? dimS2 : dimS1);\n  int32_t dim = dimR1 * dimR2;\n  // max_num_ot is multiple of dim\n  int32_t max_num_ot = ceil(float(MAX_NUM_OT) / (dim * msgs_per_ot)) * dim;\n  int32_t batch_size;\n  if (num_ot < max_num_ot)\n    batch_size = num_ot;\n  else\n    batch_size = max_num_ot;\n\n  uint64_t *corr = new uint64_t[batch_size * msgs_per_ot];\n  uint64_t *ABs = new uint64_t[batch_size * msgs_per_ot];\n  uint64_t *ABr = new uint64_t[batch_size * msgs_per_ot];\n  bool *choice = new bool[batch_size];\n  uint64_t *tmpR = new uint64_t[dim];\n  memcpy(tmpR, inR, dim * sizeof(uint64_t));\n\n  memset(ABs, 0, batch_size * msgs_per_ot * sizeof(uint64_t));\n  memset(ABr, 0, batch_size * msgs_per_ot * sizeof(uint64_t));\n  if (accumulate) {\n    memset(outC, 0, dim1 * dim3 * sizeof(uint64_t));\n  } else {\n    memset(outC, 0, dim1 * dim2 * dim3 * sizeof(uint64_t));\n  }\n  if (!row_batching) {\n    // inplace transposing is fine because inS is a copy if row_batching = false\n    matrix_transpose(inS, dimS1, dimS2);\n  }\n\n  for (int i = 0; i < num_ot; i += batch_size) {\n    vector<int> msg_len;\n    if (batch_size <= num_ot - i)\n      msg_len.resize(batch_size / dim);\n    else\n      msg_len.resize((num_ot - i) / dim);\n    for (int j = i; j < i + batch_size and j < num_ot; j += dim) {\n      int bit_offset = i / dim;\n      int bit_idx = j / dim;\n      msg_len[bit_idx - bit_offset] = bwC - bit_idx;\n      for (int k = j; k < j + dim and k < i + batch_size; k++) {\n        int inp_idx = k - j;\n        int row_idx_R = inp_idx / dimR2;\n        int col_idx_R = inp_idx % dimR2;\n        for (int h = 0; h < msgs_per_ot; h++) {\n          uint64_t elemS;\n          if (row_batching)\n            elemS = inS[col_idx_R * dimS2 + h];\n          // To preserve locality, inS is tranposed if row_batching = false\n          else\n            elemS = inS[row_idx_R * dimS1 + h];\n          // else elemS = inS[h*dimS2 + row_idx_R];\n          corr[(k - i) * msgs_per_ot + h] =\n              ((elemS << bit_idx) & maskC) >> bit_idx;\n        }\n        choice[k - i] = (bool)(tmpR[inp_idx] & 1);\n        tmpR[inp_idx] >>= 1;\n      }\n    }\n    if (use_straight_ot) {\n      if (party == sci::ALICE) {\n        if (batch_size <= num_ot - i) {\n          otpack->iknp_straight->send_batched_cot(ABs, corr, msg_len,\n                                                  batch_size, msgs_per_ot);\n        } else {\n          otpack->iknp_straight->send_batched_cot(ABs, corr, msg_len,\n                                                  num_ot - i, msgs_per_ot);\n        }\n      } else { // party == sci::BOB\n        if (batch_size <= num_ot - i) {\n          otpack->iknp_straight->recv_batched_cot(ABr, choice, msg_len,\n                                                  batch_size, msgs_per_ot);\n        } else {\n          otpack->iknp_straight->recv_batched_cot(ABr, choice, msg_len,\n                                                  num_ot - i, msgs_per_ot);\n        }\n      }\n    }\n    if (use_reversed_ot) {\n      if (party == sci::ALICE) {\n        if (batch_size <= num_ot - i) {\n          otpack->iknp_reversed->recv_batched_cot(ABr, choice, msg_len,\n                                                  batch_size, msgs_per_ot);\n        } else {\n          otpack->iknp_reversed->recv_batched_cot(ABr, choice, msg_len,\n                                                  num_ot - i, msgs_per_ot);\n        }\n      } else { // party == sci::BOB\n        if (batch_size <= num_ot - i) {\n          otpack->iknp_reversed->send_batched_cot(ABs, corr, msg_len,\n                                                  batch_size, msgs_per_ot);\n        } else {\n          otpack->iknp_reversed->send_batched_cot(ABs, corr, msg_len,\n                                                  num_ot - i, msgs_per_ot);\n        }\n      }\n    }\n    for (int h = 0; h < dim2; h++) {\n      for (int j = i; j < i + batch_size and j < num_ot; j += dim) {\n        int bit_idx = j / dim;\n        for (int k = 0; k < dim1 * dim3; k++) {\n          int row_idx = (row_batching ? k / dim3 : k / dim1);\n          int col_idx = (row_batching ? k % dim3 : k % dim1);\n          int idx;\n          if (row_batching)\n            idx = (j - i + row_idx * dimR2 + h) * msgs_per_ot + col_idx;\n          // To preserve locality, outC-transpose is computed if row_batching =\n          // false\n          else\n            idx = (j - i + h * dimR2 + row_idx) * msgs_per_ot + col_idx;\n          if (use_straight_ot) {\n            uint64_t temp = (party == ALICE ? -ABs[idx] : ABr[idx]) << bit_idx;\n            if (accumulate) {\n              outC[k] += temp;\n            } else {\n              outC[k * dim2 + h] += temp;\n            }\n          }\n          if (use_reversed_ot) {\n            uint64_t temp = (party == BOB ? -ABs[idx] : ABr[idx]) << bit_idx;\n            if (accumulate) {\n              outC[k] += temp;\n            } else {\n              outC[k * dim2 + h] += temp;\n            }\n          }\n        }\n      }\n    }\n  }\n  if (!row_batching) {\n    if (accumulate) {\n      matrix_transpose(outC, dim3, dim1);\n    } else {\n      matrix_transpose(outC, dim3, dim1, dim2);\n    }\n  }\n\n  if (accumulate) {\n    for (int k = 0; k < dim1 * dim3; k++) {\n      outC[k] &= maskC;\n    }\n  } else {\n    for (int k = 0; k < dim1 * dim2 * dim3; k++) {\n      outC[k] &= maskC;\n    }\n  }\n\n  delete[] corr;\n  delete[] ABs;\n  delete[] ABr;\n  delete[] choice;\n  delete[] tmpR;\n  if (!row_batching)\n    delete[] inS;\n}\n\nvoid LinearOT::matmul_multiplexer(int32_t dim1, int32_t dim2, int32_t dim3,\n                                  uint64_t *inA, uint64_t *inB, uint64_t *outC,\n                                  int32_t bwA, int32_t bwB, int32_t bwC,\n                                  bool accumulate, MultMode mode) {\n  assert(bwA == 1 || bwB == 1);\n  assert(bwC < (bwA + bwB));\n\n  bool use_straight_ot = false, use_reversed_ot = false;\n  uint64_t maskC = (bwC == 64 ? -1 : ((1ULL << bwC) - 1));\n  uint64_t *inS, *inR;\n  int32_t dimS1, dimS2, dimR1, dimR2;\n  // A whole row of values is multiplied to a bit\n  bool row_batching;\n  if (bwB == 1) {\n    inS = new uint64_t[dim1 * dim2];\n    memcpy(inS, inA, dim1 * dim2 * sizeof(uint64_t));\n    inR = inB;\n    dimS1 = dim1;\n    dimS2 = dim2;\n    dimR1 = dim2;\n    dimR2 = dim3;\n    if (mode == MultMode::Alice_has_A)\n      use_straight_ot = true;\n    else if (mode == MultMode::Bob_has_A)\n      use_reversed_ot = true;\n    else {\n      use_straight_ot = true;\n      use_reversed_ot = true;\n    }\n    row_batching = false;\n  } else { // bwA == 1\n    inS = inB;\n    inR = inA;\n    dimS1 = dim2;\n    dimS2 = dim3;\n    dimR1 = dim1;\n    dimR2 = dim2;\n    if (mode == MultMode::Alice_has_B)\n      use_straight_ot = true;\n    else if (mode == MultMode::Bob_has_B)\n      use_reversed_ot = true;\n    else {\n      use_straight_ot = true;\n      use_reversed_ot = true;\n    }\n    row_batching = true;\n  }\n\n  int32_t dim = dimR1 * dimR2;\n  int32_t msgs_per_ot = (row_batching ? dimS2 : dimS1);\n\n  PRG128 prg;\n  uint64_t *data = new uint64_t[2 * dim * msgs_per_ot];\n  uint64_t *ABs = new uint64_t[dim * msgs_per_ot];\n  uint64_t *ABr = new uint64_t[dim * msgs_per_ot];\n  uint8_t *choice = new uint8_t[dim];\n\n  if (accumulate) {\n    for (int k = 0; k < dim1 * dim3; k++) {\n      outC[k] = 0;\n    }\n  } else {\n    for (int k = 0; k < dim1 * dim2 * dim3; k++) {\n      outC[k] = 0;\n    }\n  }\n  memset(ABs, 0, dim * msgs_per_ot * sizeof(uint64_t));\n  memset(ABr, 0, dim * msgs_per_ot * sizeof(uint64_t));\n\n  if (!row_batching) {\n    // inplace transposing is fine because inS is a copy if row_batching = false\n    matrix_transpose(inS, dimS1, dimS2);\n  }\n\n  if (use_straight_ot && party == ALICE) {\n    prg.random_data(ABs, dim * msgs_per_ot * sizeof(uint64_t));\n  }\n  if (use_reversed_ot && party == BOB) {\n    prg.random_data(ABs, dim * msgs_per_ot * sizeof(uint64_t));\n  }\n\n  for (int i = 0; i < dim; i++) {\n    int row_idx_R = i / dimR2;\n    int col_idx_R = i % dimR2;\n\n    choice[i] = (bool)(inR[i] & 1);\n    uint64_t choice_bit = choice[i];\n    for (int h = 0; h < msgs_per_ot; h++) {\n      uint64_t elemS;\n      if (row_batching)\n        elemS = inS[col_idx_R * dimS2 + h];\n      // To preserve locality, inS is tranposed if row_batching = false\n      else\n        elemS = inS[row_idx_R * dimS1 + h];\n      int idx = i * msgs_per_ot + h;\n      data[idx * 2] = (ABs[idx] + elemS * choice_bit) & maskC;\n      data[idx * 2 + 1] = (ABs[idx] + elemS * (1 - choice_bit)) & maskC;\n    }\n  }\n  if (party == sci::ALICE) {\n    if (use_straight_ot) {\n      otpack->iknp_straight->send_batched_got(data, dim, bwC, msgs_per_ot);\n    }\n    if (use_reversed_ot) {\n      otpack->iknp_reversed->recv_batched_got(ABr, choice, dim, bwC,\n                                              msgs_per_ot);\n    }\n  } else { // party == sci::BOB\n    if (use_straight_ot) {\n      otpack->iknp_straight->recv_batched_got(ABr, choice, dim, bwC,\n                                              msgs_per_ot);\n    }\n    if (use_reversed_ot) {\n      otpack->iknp_reversed->send_batched_got(data, dim, bwC, msgs_per_ot);\n    }\n  }\n  for (int h = 0; h < dim2; h++) {\n    for (int k = 0; k < dim1 * dim3; k++) {\n      int row_idx = (row_batching ? k / dim3 : k / dim1);\n      int col_idx = (row_batching ? k % dim3 : k % dim1);\n      int idx;\n      if (row_batching)\n        idx = (row_idx * dimR2 + h) * msgs_per_ot + col_idx;\n      // To preserve locality, outC-transpose is computed if row_batching =\n      // false\n      else\n        idx = (h * dimR2 + row_idx) * msgs_per_ot + col_idx;\n      if (use_straight_ot) {\n        uint64_t temp = (party == ALICE ? -ABs[idx] : ABr[idx]);\n        if (accumulate) {\n          outC[k] += temp;\n        } else {\n          outC[k * dim2 + h] += temp;\n        }\n      }\n      if (use_reversed_ot) {\n        uint64_t temp = (party == BOB ? -ABs[idx] : ABr[idx]);\n        if (accumulate) {\n          outC[k] += temp;\n        } else {\n          outC[k * dim2 + h] += temp;\n        }\n      }\n    }\n  }\n  if (!row_batching) {\n    if (accumulate) {\n      matrix_transpose(outC, dim3, dim1);\n    } else {\n      matrix_transpose(outC, dim3, dim1, dim2);\n    }\n  }\n\n  if (accumulate) {\n    for (int k = 0; k < dim1 * dim3; k++) {\n      outC[k] &= maskC;\n    }\n  } else {\n    for (int k = 0; k < dim1 * dim2 * dim3; k++) {\n      outC[k] &= maskC;\n    }\n  }\n\n  delete[] data;\n  delete[] ABs;\n  delete[] ABr;\n  delete[] choice;\n  if (!row_batching)\n    delete[] inS;\n}\n\nvoid LinearOT::matrix_multiplication(int32_t dim1, int32_t dim2, int32_t dim3,\n                                     uint64_t *inA, uint64_t *inB,\n                                     uint64_t *outC, int32_t bwA, int32_t bwB,\n                                     int32_t bwC, bool signed_arithmetic,\n                                     bool signed_B, bool accumulate,\n                                     MultMode mode, uint8_t *msbA,\n                                     uint8_t *msbB) {\n  assert(bwC <= 64);\n  assert((bwC <= (bwA + bwB)) && (bwC >= bwA) && (bwC >= bwB));\n  int32_t extra_bits = (accumulate ? ceil(log2(dim2)) : 0);\n  uint64_t *tmpA = new uint64_t[dim1 * dim2];\n  uint64_t *tmpB = new uint64_t[dim2 * dim3];\n\n  bool sender_A = false;\n  bool sender_B = false;\n  if (mode == MultMode::Alice_has_A || mode == MultMode::Alice_has_B) {\n    sender_A = true;\n  } else if (mode == MultMode::Bob_has_A || mode == MultMode::Bob_has_B) {\n    sender_B = true;\n  } else {\n    if (bwA > bwB) {\n      sender_A = true;\n    } else {\n      sender_B = true;\n    }\n  }\n  if (sender_A) {\n    if (mode == MultMode::Alice_has_A || mode == MultMode::Bob_has_A) {\n      for (int i = 0; i < dim1 * dim2; i++) {\n        tmpA[i] = (signed_arithmetic ? signed_val(inA[i], bwA) : inA[i]);\n      }\n    } else {\n      if (signed_arithmetic) {\n        xt->s_extend(dim1 * dim2, inA, tmpA, bwA, bwA + extra_bits, msbA);\n      } else {\n        xt->z_extend(dim1 * dim2, inA, tmpA, bwA, bwA + extra_bits, msbA);\n      }\n    }\n    memcpy(tmpB, inB, dim2 * dim3 * sizeof(uint64_t));\n    bwA = bwA + extra_bits;\n  } else if (sender_B) {\n    if (mode == MultMode::Alice_has_B || mode == MultMode::Bob_has_B) {\n      for (int i = 0; i < dim2 * dim3; i++) {\n        tmpB[i] = ((signed_arithmetic && signed_B) ? signed_val(inB[i], bwB)\n                                                   : inB[i]);\n      }\n    } else {\n      if (signed_arithmetic && signed_B) {\n        xt->s_extend(dim2 * dim3, inB, tmpB, bwB, bwB + extra_bits, msbB);\n      } else {\n        xt->z_extend(dim2 * dim3, inB, tmpB, bwB, bwB + extra_bits, msbB);\n      }\n    }\n    memcpy(tmpA, inA, dim1 * dim2 * sizeof(uint64_t));\n    bwB = bwB + extra_bits;\n  }\n  bwC = bwC + extra_bits;\n  uint64_t maskA = (bwA == 64 ? -1 : ((1ULL << bwA) - 1));\n  uint64_t maskB = (bwB == 64 ? -1 : ((1ULL << bwB) - 1));\n  uint64_t maskC = (bwC == 64 ? -1 : ((1ULL << bwC) - 1));\n  uint64_t pow_A = 1ULL << bwA;\n  uint64_t pow_B = 1ULL << bwB;\n  uint64_t pow_A_2 = (1ULL << (bwA - 1));\n  uint64_t pow_B_2 = (1ULL << (bwB - 1));\n  int32_t dim;\n  if (accumulate)\n    dim = dim1 * dim3;\n  else\n    dim = dim1 * dim2 * dim3;\n\n  for (int i = 0; i < dim1 * dim2; i++) {\n    if (signed_arithmetic) {\n      if (mode == MultMode::Alice_has_A) {\n        tmpA[i] = (party == ALICE ? tmpA[i] + pow_A_2 : 0) & maskA;\n      } else if (mode == MultMode::Bob_has_A) {\n        tmpA[i] = (party == BOB ? tmpA[i] + pow_A_2 : 0) & maskA;\n      } else {\n        tmpA[i] = (tmpA[i] + (party == BOB ? pow_A_2 : 0)) & maskA;\n      }\n    } else {\n      tmpA[i] = tmpA[i] & maskA;\n    }\n  }\n  for (int i = 0; i < dim2 * dim3; i++) {\n    if (signed_arithmetic && signed_B) {\n      if (mode == MultMode::Alice_has_B) {\n        tmpB[i] = (party == ALICE ? tmpB[i] + pow_B_2 : 0) & maskB;\n      } else if (mode == MultMode::Bob_has_B) {\n        tmpB[i] = (party == BOB ? tmpB[i] + pow_B_2 : 0) & maskB;\n      } else {\n        tmpB[i] = (tmpB[i] + (party == BOB ? pow_B_2 : 0)) & maskB;\n      }\n    } else {\n      tmpB[i] = tmpB[i] & maskB;\n    }\n  }\n  uint64_t *cross_terms = new uint64_t[dim];\n  matmul_cross_terms(dim1, dim2, dim3, tmpA, tmpB, cross_terms, bwA, bwB, bwC,\n                     accumulate, mode);\n\n  uint64_t *local_terms = new uint64_t[dim];\n  if (party == ALICE &&\n      (mode == MultMode::Alice_has_A || mode == MultMode::Alice_has_B)) {\n    matmul_cleartext(dim1, dim2, dim3, tmpA, tmpB, local_terms, accumulate);\n  } else if (party == BOB &&\n             (mode == MultMode::Bob_has_A || mode == MultMode::Bob_has_B)) {\n    matmul_cleartext(dim1, dim2, dim3, tmpA, tmpB, local_terms, accumulate);\n  } else if (mode == MultMode::None) {\n    matmul_cleartext(dim1, dim2, dim3, tmpA, tmpB, local_terms, accumulate);\n  } else {\n    memset(local_terms, 0, dim * sizeof(uint64_t));\n  }\n\n  uint8_t *wA = new uint8_t[dim1 * dim2];\n  uint8_t *wB = new uint8_t[dim2 * dim3];\n  uint64_t *wA_B = new uint64_t[dim];\n  uint64_t *wB_A = new uint64_t[dim];\n\n  if (bwC > bwA) {\n    if (mode == MultMode::Alice_has_A || mode == MultMode::Bob_has_A) {\n      memset(wA, 0, dim1 * dim2 * sizeof(uint8_t));\n      memset(wA_B, 0, dim * sizeof(uint64_t));\n    } else {\n      if (msbA != nullptr) {\n        uint8_t *tmp_msbA = new uint8_t[dim1 * dim2];\n        if (signed_arithmetic) {\n          for (int i = 0; i < dim1 * dim2; i++) {\n            tmp_msbA[i] = (party == ALICE ? msbA[i] ^ 1 : msbA[i]);\n          }\n        } else {\n          for (int i = 0; i < dim1 * dim2; i++) {\n            tmp_msbA[i] = (sender_A && (extra_bits > 0) ? 0 : msbA[i]);\n          }\n        }\n        aux->MSB_to_Wrap(tmpA, tmp_msbA, wA, dim1 * dim2, bwA);\n        delete[] tmp_msbA;\n      } else {\n        aux->wrap_computation(tmpA, wA, dim1 * dim2, bwA);\n      }\n      uint64_t *wA64 = new uint64_t[dim1 * dim2];\n      for (int i = 0; i < dim1 * dim2; i++) {\n        wA64[i] = uint64_t(wA[i]);\n      }\n      matmul_multiplexer(dim1, dim2, dim3, wA64, tmpB, wA_B, 1, bwB, bwC - bwA,\n                         accumulate, mode);\n      delete[] wA64;\n    }\n  }\n  if (bwC > bwB) {\n    if (mode == MultMode::Alice_has_B || mode == MultMode::Bob_has_B) {\n      memset(wB, 0, dim2 * dim3 * sizeof(uint8_t));\n      memset(wB_A, 0, dim * sizeof(uint64_t));\n    } else {\n      if (msbB != nullptr) {\n        uint8_t *tmp_msbB = new uint8_t[dim2 * dim3];\n        if (signed_arithmetic && signed_B) {\n          for (int i = 0; i < dim2 * dim3; i++) {\n            tmp_msbB[i] = (party == ALICE ? msbB[i] ^ 1 : msbB[i]);\n          }\n        } else {\n          for (int i = 0; i < dim2 * dim3; i++) {\n            tmp_msbB[i] = (sender_B && (extra_bits > 0) ? 0 : msbB[i]);\n          }\n        }\n        aux->MSB_to_Wrap(tmpB, tmp_msbB, wB, dim2 * dim3, bwB);\n        delete[] tmp_msbB;\n      } else {\n        aux->wrap_computation(tmpB, wB, dim2 * dim3, bwB);\n      }\n      uint64_t *wB64 = new uint64_t[dim2 * dim3];\n      for (int i = 0; i < dim2 * dim3; i++) {\n        wB64[i] = uint64_t(wB[i]);\n      }\n      matmul_multiplexer(dim1, dim2, dim3, tmpA, wB64, wB_A, bwA, 1, bwC - bwB,\n                         accumulate, mode);\n      delete[] wB64;\n    }\n  }\n\n  uint64_t *tmpC = new uint64_t[dim];\n  int inner_loop_size = (accumulate ? dim2 : 1);\n  for (int i = 0; i < dim; i++) {\n    tmpC[i] =\n        (local_terms[i] + cross_terms[i] - pow_A * wA_B[i] - pow_B * wB_A[i]) &\n        maskC;\n    if (signed_arithmetic) {\n      for (int j = 0; j < inner_loop_size; j++) {\n        int idx = (accumulate ? i : i / dim2);\n        int common_idx = (accumulate ? j : i % dim2);\n        int row_idx = idx / dim3;\n        int col_idx = idx % dim3;\n        int A_idx = row_idx * dim2 + common_idx;\n        int B_idx = common_idx * dim3 + col_idx;\n        if (signed_B) {\n          if (party == ALICE) {\n            tmpC[i] = (tmpC[i] - pow_A_2 * (tmpB[B_idx] - pow_B * wB[B_idx]) -\n                       pow_B_2 * (tmpA[A_idx] - pow_A * wA[A_idx])) &\n                      maskC;\n          } else { // party == BOB\n            tmpC[i] = (tmpC[i] - pow_A_2 * (tmpB[B_idx] - pow_B * wB[B_idx]) -\n                       pow_B_2 * (tmpA[A_idx] - pow_A * wA[A_idx]) +\n                       pow_A_2 * pow_B_2) &\n                      maskC;\n          }\n        } else {\n          tmpC[i] =\n              (tmpC[i] - pow_A_2 * (tmpB[B_idx] - pow_B * wB[B_idx])) & maskC;\n        }\n      }\n    }\n  }\n  if (accumulate) {\n    trunc->truncate_and_reduce(dim1 * dim3, tmpC, outC, extra_bits, bwC);\n  } else {\n    memcpy(outC, tmpC, dim * sizeof(uint64_t));\n  }\n\n  delete[] cross_terms;\n  delete[] local_terms;\n  delete[] wA;\n  delete[] wB;\n  delete[] wA_B;\n  delete[] wB_A;\n  delete[] tmpA;\n  delete[] tmpB;\n  delete[] tmpC;\n}\n", "meta": {"hexsha": "2eb5baaaf0449156dba8c0eedea8742bc388673d", "size": 24946, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SCI/src/LinearOT/linear-ot.cpp", "max_stars_repo_name": "jaskiratsingh2000/EzPC", "max_stars_repo_head_hexsha": "f390bfe6afbeb03d8b885e7bd42bf5aaf81255f6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 221.0, "max_stars_repo_stars_event_min_datetime": "2019-05-16T16:42:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T14:05:31.000Z", "max_issues_repo_path": "SCI/src/LinearOT/linear-ot.cpp", "max_issues_repo_name": "jaskiratsingh2000/EzPC", "max_issues_repo_head_hexsha": "f390bfe6afbeb03d8b885e7bd42bf5aaf81255f6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 63.0, "max_issues_repo_issues_event_min_datetime": "2019-07-02T11:50:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:14:02.000Z", "max_forks_repo_path": "SCI/src/LinearOT/linear-ot.cpp", "max_forks_repo_name": "jaskiratsingh2000/EzPC", "max_forks_repo_head_hexsha": "f390bfe6afbeb03d8b885e7bd42bf5aaf81255f6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2019-08-30T08:44:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T08:08:33.000Z", "avg_line_length": 33.3949129853, "max_line_length": 80, "alphanum_fraction": 0.5367594003, "num_tokens": 8158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.6757645944891559, "lm_q1q2_score": 0.4304828565091409}}
{"text": "// Copyright (C) 2013 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/pose/essential_matrix_utils.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <glog/logging.h>\n\n#include <algorithm>\n\n#include \"theia/matching/feature_correspondence.h\"\n#include \"theia/sfm/pose/util.h\"\n#include \"theia/sfm/triangulation/triangulation.h\"\n#include \"theia/sfm/types.h\"\n\nnamespace theia {\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\n// Decomposes the essential matrix into the rotation R and translation t such\n// that E can be any of the four candidate solutions: [rotation1 | translation],\n// [rotation1 | -translation], [rotation2 | translation], [rotation2 |\n// -translation].\nvoid DecomposeEssentialMatrix(const Matrix3d& essential_matrix,\n                              Matrix3d* rotation1,\n                              Matrix3d* rotation2,\n                              Vector3d* translation) {\n  Matrix3d d;\n  d << 0, 1, 0, -1, 0, 0, 0, 0, 1;\n\n  const Eigen::JacobiSVD<Matrix3d> svd(\n      essential_matrix, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Eigen::Matrix3d U = svd.matrixU();\n  Eigen::Matrix3d V = svd.matrixV();\n  if (U.determinant() < 0) {\n    U.col(2) *= -1.0;\n  }\n\n  if (V.determinant() < 0) {\n    V.col(2) *= -1.0;\n  }\n\n  // Possible configurations.\n  *rotation1 = U * d * V.transpose();\n  *rotation2 = U * d.transpose() * V.transpose();\n  *translation = U.col(2).normalized();\n}\n\n// x = (R2 * X + t2)\n// x = (R2 * R1^t * X + t2)\n// x = (R2 * (R1^t * X - t1) + t2)\n// x = R2 * R1^t * X - R2 * t1 + t2\nvoid EssentialMatrixFromTwoProjectionMatrices(\n    const Matrix3x4d& pose1,\n    const Matrix3x4d& pose2,\n    Eigen::Matrix3d* essential_matrix) {\n  // Create the Ematrix from the poses.\n  const Eigen::Matrix3d R1 = pose1.leftCols<3>();\n  const Eigen::Matrix3d R2 = pose2.leftCols<3>();\n  const Eigen::Vector3d t1 = pose1.rightCols<1>();\n  const Eigen::Vector3d t2 = pose2.rightCols<1>();\n\n  // Pos1 = -R1^t * t1.\n  // Pos2 = -R2^t * t2.\n  // t = R1 * (pos2 - pos1).\n  // t = R1 * (-R2^t * t2 + R1^t * t1)\n  // t = t1 - R1 * R2^t * t2;\n\n  // Relative transformation between to cameras.\n  const Eigen::Matrix3d relative_rotation = R1 * R2.transpose();\n  const Eigen::Vector3d translation = (t1 - relative_rotation * t2).normalized();\n  *essential_matrix = CrossProductMatrix(translation) * relative_rotation;\n}\n\nint GetBestPoseFromEssentialMatrix(\n    const Matrix3d& essential_matrix,\n    const std::vector<FeatureCorrespondence>& normalized_correspondences,\n    Matrix3d* rotation,\n    Vector3d* position) {\n  // Decompose ematrix.\n  Matrix3d rotation1, rotation2;\n  Vector3d translation;\n  DecomposeEssentialMatrix(\n      essential_matrix, &rotation1, &rotation2, &translation);\n  const std::vector<Matrix3d> rotations = {\n      rotation1, rotation1, rotation2, rotation2};\n  const std::vector<Vector3d> positions = {\n      -rotations[0].transpose() * translation,\n      -rotations[1].transpose() * -translation,\n      -rotations[2].transpose() * translation,\n      -rotations[3].transpose() * -translation};\n\n  // From the 4 candidate poses, find the one with the most triangulated points\n  // in front of the camera.\n  std::vector<int> points_in_front_of_cameras(4, 0);\n  for (int i = 0; i < 4; i++) {\n    for (const auto& correspondence : normalized_correspondences) {\n      if (IsTriangulatedPointInFrontOfCameras(\n              correspondence, rotations[i], positions[i])) {\n        ++points_in_front_of_cameras[i];\n      }\n    }\n  }\n\n  // Find the pose with the most points in front of the camera.\n  const auto& max_element = std::max_element(points_in_front_of_cameras.begin(),\n                                             points_in_front_of_cameras.end());\n  const int max_index =\n      std::distance(points_in_front_of_cameras.begin(), max_element);\n\n  // Set the pose.\n  *rotation = rotations[max_index];\n  *position = positions[max_index];\n  return *max_element;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "13569b6869e8e2dc9dbb70c733ddee0cb4b7ad90", "size": 5673, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/essential_matrix_utils.cc", "max_stars_repo_name": "maxchernet/TheiaSfM", "max_stars_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 770.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T14:32:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:54:33.000Z", "max_issues_repo_path": "src/theia/sfm/pose/essential_matrix_utils.cc", "max_issues_repo_name": "maxchernet/TheiaSfM", "max_issues_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 237.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T18:50:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T05:21:48.000Z", "max_forks_repo_path": "src/theia/sfm/pose/essential_matrix_utils.cc", "max_forks_repo_name": "maxchernet/TheiaSfM", "max_forks_repo_head_hexsha": "603f3ad8bfea1e54fe23fa553f268760a9c9276c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 278.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T06:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:25:21.000Z", "avg_line_length": 37.5695364238, "max_line_length": 81, "alphanum_fraction": 0.6858804865, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.43047157846673695}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2007 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Authors: Martin Kronbichler, Uppsala University, \n *          Wolfgang Bangerth, Texas A&M University 2007, 2008 \n */ \n\n\n// @sect3{Include files}  \n\n// 像往常一样，第一步是包括这些著名的deal.II库文件和一些C++头文件的功能。\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/utilities.h> \n\n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/solver_gmres.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/block_sparsity_pattern.h> \n#include <deal.II/lac/affine_constraints.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_tools.h> \n#include <deal.II/grid/grid_refinement.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_renumbering.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/fe_values.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n#include <deal.II/numerics/solution_transfer.h> \n\n// 然后我们需要包括一些头文件，这些文件提供了矢量、矩阵和预处理类，这些类实现了各自Trilinos类的接口。特别是，我们将需要基于Trilinos的矩阵和向量类以及Trilinos预处理程序的接口。\n\n#include <deal.II/base/index_set.h> \n#include <deal.II/lac/trilinos_sparse_matrix.h> \n#include <deal.II/lac/trilinos_block_sparse_matrix.h> \n#include <deal.II/lac/trilinos_vector.h> \n#include <deal.II/lac/trilinos_parallel_block_vector.h> \n#include <deal.II/lac/trilinos_precondition.h> \n\n// 最后，这里有几个C++头文件还没有被上述头文件中的某个文件所包含。\n\n#include <iostream> \n#include <fstream> \n#include <memory> \n#include <limits> \n\n// 在这个顶层事项的最后，我们将所有deal.II的名字导入到全局命名空间。\n\nnamespace Step31 \n{ \n  using namespace dealii; \n// @sect3{Equation data}  \n\n// 同样，程序的下一阶段是定义方程数据，即各种边界条件、右手边和初始条件（记住，我们要解决的是一个时间依赖型系统）。这个定义的基本策略与  step-22  中的相同。不过关于细节，还是有一些区别。\n\n// 首先，我们没有在速度上设置任何不均匀的边界条件，因为正如介绍中所解释的，我们将使用无流条件  $\\mathbf{n}\\cdot\\mathbf{u}=0$  。所以剩下的是应力张量法线分量的切向部分的条件 <code>dim-1</code> ， $\\textbf{n} \\cdot [p \\textbf{1} - \\eta\\varepsilon(\\textbf{u})]$ ；我们假定这些分量的值是同质的，也就是说，一个自然的边界条件，不需要具体的动作（它作为零项出现在弱形式的右边）。\n\n// 对于温度  $T$  ，我们假设没有热能通量，即  $\\mathbf{n} \\cdot \\kappa \\nabla T=0$  。这也是一个边界条件，不需要我们做任何特别的事情。\n\n// 第二，我们必须设定温度的初始条件（速度和压力不需要初始条件，因为我们在这里考虑的准稳态情况下的斯托克斯方程没有速度或压力的时间导数）。在这里，我们选择一个非常简单的测试案例，即初始温度为零，所有的动力学都由温度的右手边驱动。\n\n// 第三，我们需要定义温度方程的右边。我们选择它在域的底部某处的三个圆（或三维球）内为常数，如介绍中所解释的那样，而在域外为零。\n\n// 最后，或者说首先，在这个命名空间的顶部，我们定义我们需要的各种材料常数（ $\\eta,\\kappa$ ，密度 $\\rho$ 和热膨胀系数 $\\beta$ ）。\n\n  namespace EquationData \n  { \n    constexpr double eta     = 1; \n    constexpr double kappa   = 1e-6; \n    constexpr double beta    = 10; \n    constexpr double density = 1; \n\n    template <int dim> \n    class TemperatureInitialValues : public Function<dim> \n    { \n    public: \n      TemperatureInitialValues() \n        : Function<dim>(1) \n      {} \n\n      virtual double value(const Point<dim> & /*p*/, \n                           const unsigned int /*component*/ = 0) const override \n      { \n        return 0; \n      } \n\n      virtual void vector_value(const Point<dim> &p, \n                                Vector<double> &  value) const override \n      { \n        for (unsigned int c = 0; c < this->n_components; ++c) \n          value(c) = TemperatureInitialValues<dim>::value(p, c); \n      } \n    }; \n\n    template <int dim> \n    class TemperatureRightHandSide : public Function<dim> \n    { \n    public: \n      TemperatureRightHandSide() \n        : Function<dim>(1) \n      {} \n\n      virtual double value(const Point<dim> & p, \n                           const unsigned int component = 0) const override \n      { \n        (void)component; \n        Assert(component == 0, \n               ExcMessage(\"Invalid operation for a scalar function.\")); \n\n        Assert((dim == 2) || (dim == 3), ExcNotImplemented()); \n\n        static const Point<dim> source_centers[3] = { \n          (dim == 2 ? Point<dim>(.3, .1) : Point<dim>(.3, .5, .1)), \n          (dim == 2 ? Point<dim>(.45, .1) : Point<dim>(.45, .5, .1)), \n          (dim == 2 ? Point<dim>(.75, .1) : Point<dim>(.75, .5, .1))}; \n        static const double source_radius = (dim == 2 ? 1. / 32 : 1. / 8); \n\n        return ((source_centers[0].distance(p) < source_radius) || \n                    (source_centers[1].distance(p) < source_radius) || \n                    (source_centers[2].distance(p) < source_radius) ? \n                  1 : \n                  0); \n      } \n\n      virtual void vector_value(const Point<dim> &p, \n                                Vector<double> &  value) const override \n      { \n        for (unsigned int c = 0; c < this->n_components; ++c) \n          value(c) = TemperatureRightHandSide<dim>::value(p, c); \n      } \n    }; \n  } // namespace EquationData \n\n//  @sect3{Linear solvers and preconditioners}  \n\n// 本节介绍了一些用于求解斯托克斯系统线性方程的对象，我们需要在每个时间步长中求解。这里使用的许多想法与 step-20 相同，其中介绍了基于Schur补的预处理程序和求解器，实际接口来自 step-22 （特别是 step-22 中 \"结果 \"部分的讨论，其中我们介绍了直接Schur补方法的替代品）。但是请注意，在这里我们不使用Schur补数来解决Stokes方程，尽管预处理程序中出现了一个近似的Schur补数（压力空间的质量矩阵）。\n\n  namespace LinearSolvers \n  { \n// @sect4{The <code>InverseMatrix</code> class template}  \n\n// 这个类是一个接口，用于计算 \"倒置 \"矩阵对向量的作用（使用 <code>vmult</code> 操作），其方式与 step-22 中的相应类相同：当请求这个类的对象的乘积时，我们使用CG方法解决与该矩阵有关的线性方程组，通过（模板化） <code>PreconditionerType</code> 类的预处理器加速。\n\n// 与 step-22 中同一类别的实现略有不同，我们让 <code>vmult</code> 函数接受任何类型的向量类型（但是，如果矩阵不允许与这种向量进行矩阵-向量乘积，它将产生编译器错误）。\n\n// 第二，我们捕捉解算器可能抛出的任何异常。原因如下。在调试这样的程序时，偶尔会犯一个错误，即把一个不确定或不对称的矩阵或预处理程序传递给当前的类。在这种情况下，求解器将不能收敛并抛出一个运行时异常。如果在这里没有被捕捉到，它就会在调用堆栈中传播，最后可能会在 <code>main()</code> 中出现，在那里我们会输出一个错误信息，说CG求解器失败。那么问题来了。哪个CG求解器？倒置质量矩阵的那个？用拉普拉斯算子反转左上角块的那个？还是在当前代码中我们使用线性求解器的其他几个嵌套位置中的一个CG求解器？在运行时异常中没有这方面的指示，因为它没有存储我们到达产生异常的地方的调用栈。\n//所以\n//与其让异常自由传播到 <code>main()</code> ，不如意识到如果内部求解器失败，外部函数能做的很少，不如将运行时异常转化为一个断言，该断言失败后会触发对 <code>abort()</code> 的调用，允许我们在调试器中追溯我们如何到达当前位置。\n\n    template <class MatrixType, class PreconditionerType> \n    class InverseMatrix : public Subscriptor \n    { \n    public: \n      InverseMatrix(const MatrixType &        m, \n                    const PreconditionerType &preconditioner); \n\n      template <typename VectorType> \n      void vmult(VectorType &dst, const VectorType &src) const; \n\n    private: \n      const SmartPointer<const MatrixType> matrix; \n      const PreconditionerType &           preconditioner; \n    }; \n\n    template <class MatrixType, class PreconditionerType> \n    InverseMatrix<MatrixType, PreconditionerType>::InverseMatrix( \n      const MatrixType &        m, \n      const PreconditionerType &preconditioner) \n      : matrix(&m) \n      , preconditioner(preconditioner) \n    {} \n\n    template <class MatrixType, class PreconditionerType> \n    template <typename VectorType> \n    void InverseMatrix<MatrixType, PreconditionerType>::vmult( \n      VectorType &      dst, \n      const VectorType &src) const \n    { \n      SolverControl        solver_control(src.size(), 1e-7 * src.l2_norm()); \n      SolverCG<VectorType> cg(solver_control); \n\n      dst = 0; \n\n      try \n        { \n          cg.solve(*matrix, dst, src, preconditioner); \n        } \n      catch (std::exception &e) \n        { \n          Assert(false, ExcMessage(e.what())); \n        } \n    } \n// @sect4{Schur complement preconditioner}  \n\n// 这是在介绍中详细描述的舒尔补码预处理程序的实现。与 step-20 和 step-22 相反，我们使用GMRES一次性解决块系统，并使用块结构矩阵的Schur补码来建立一个良好的预处理程序。\n\n// 让我们看看介绍中描述的理想预处理矩阵  $P=\\left(\\begin{array}{cc} A & 0 \\\\ B & -S \\end{array}\\right)$  。如果我们在线性系统的求解中应用这个矩阵，迭代式GMRES求解器的收敛性将受矩阵\n// @f{eqnarray*} P^{-1}\\left(\\begin{array}{cc} A &\n//  B^T \\\\ B & 0 \\end{array}\\right) = \\left(\\begin{array}{cc} I & A^{-1}\n//  B^T \\\\ 0 & I \\end{array}\\right), \n//  @f}\n//  的制约，这确实非常简单。基于精确矩阵的GMRES求解器将在一次迭代中收敛，因为所有的特征值都是相等的（任何Krylov方法最多需要多少次迭代就有多少个不同的特征值）。Silvester和Wathen提出了这样一个用于受阻斯托克斯系统的预处理程序（\"稳定的斯托克斯系统的快速迭代解第二部分。 Using general block preconditioners\", SIAM J. Numer. Anal., 31 (1994), pp.1352-1367）。)\n\n//用 $\\tilde{P}$ 代替 $P$ 可以保持这种精神：乘积 $P^{-1} A$ 仍将接近于特征值为1的矩阵，其分布不取决于问题大小。这让我们希望能够得到一个与问题规模无关的GMRES迭代次数。\n\n// 已经通过 step-20 和 step-22 教程的deal.II用户当然可以想象我们将如何实现这一点。 我们用一些由InverseMatrix类构建的近似逆矩阵取代 $P^{-1}$ 中的精确逆矩阵，逆舒尔补码将由压力质量矩阵 $M_p$ 近似（如介绍中提到的由 $\\eta^{-1}$ 加权）。正如在 step-22 的结果部分所指出的，我们可以通过应用一个预处理程序来取代 $A$ 的精确逆，在这种情况下，如介绍中所解释的那样，在一个矢量拉普拉斯矩阵上。这确实增加了（外部）GMRES的迭代次数，但仍然比精确的逆运算便宜得多，因为 <em> 的每个 </em> 外部求解器步骤（使用AMG预处理程序）需要20到35次CG迭代。\n\n// 考虑到上述解释，我们定义了一个具有 <code>vmult</code> 功能的预处理类，这就是我们在程序代码中进一步与通常的求解器函数交互所需要的。\n\n// 首先是声明。这与 step-20 中Schur补码的定义相似，不同的是我们在构造函数中需要更多的预处理程序，而且我们在这里使用的矩阵是建立在Trilinos之上的。\n\n    template <class PreconditionerTypeA, class PreconditionerTypeMp> \n    class BlockSchurPreconditioner : public Subscriptor \n    { \n    public: \n      BlockSchurPreconditioner( \n        const TrilinosWrappers::BlockSparseMatrix &S, \n        const InverseMatrix<TrilinosWrappers::SparseMatrix, \n                            PreconditionerTypeMp> &Mpinv, \n        const PreconditionerTypeA &                Apreconditioner); \n\n      void vmult(TrilinosWrappers::MPI::BlockVector &      dst, \n                 const TrilinosWrappers::MPI::BlockVector &src) const; \n\n    private: \n      const SmartPointer<const TrilinosWrappers::BlockSparseMatrix> \n        stokes_matrix; \n      const SmartPointer<const InverseMatrix<TrilinosWrappers::SparseMatrix, \n                                             PreconditionerTypeMp>> \n                                 m_inverse; \n      const PreconditionerTypeA &a_preconditioner; \n\n      mutable TrilinosWrappers::MPI::Vector tmp; \n    }; \n\n// 当使用 TrilinosWrappers::MPI::Vector 或 TrilinosWrappers::MPI::BlockVector, 时，Vector被使用IndexSet初始化。IndexSet不仅用于调整 TrilinosWrappers::MPI::Vector 的大小，而且还将 TrilinosWrappers::MPI::Vector 中的一个索引与一个自由度联系起来（更详细的解释见 step-40 ）。函数complete_index_set()创建了一个IndexSet，每个有效的索引都是这个集合的一部分。请注意，这个程序只能按顺序运行，如果并行使用，将抛出一个异常。\n\n    template <class PreconditionerTypeA, class PreconditionerTypeMp> \n    BlockSchurPreconditioner<PreconditionerTypeA, PreconditionerTypeMp>:: \n      BlockSchurPreconditioner( \n        const TrilinosWrappers::BlockSparseMatrix &S, \n        const InverseMatrix<TrilinosWrappers::SparseMatrix, \n                            PreconditionerTypeMp> &Mpinv, \n        const PreconditionerTypeA &                Apreconditioner) \n      : stokes_matrix(&S) \n      , m_inverse(&Mpinv) \n      , a_preconditioner(Apreconditioner) \n      , tmp(complete_index_set(stokes_matrix->block(1, 1).m())) \n    {} \n\n// 接下来是 <code>vmult</code> 函数。我们以三个连续的步骤实现上述 $P^{-1}$ 的动作。 在公式中，我们要计算 $Y=P^{-1}X$ ，其中 $X,Y$ 都是有两个块成分的向量。\n\n// 第一步用矩阵 $A$ 的预处理乘以矢量的速度部分，即计算 $Y_0={\\tilde A}^{-1}X_0$  。 然后将得到的速度矢量乘以 $B$ 并减去压力，即我们要计算 $X_1-BY_0$  。这第二步只作用于压力向量，由我们矩阵类的残差函数完成，只是符号不对。因此，我们改变临时压力向量中的符号，最后乘以反压力质量矩阵，得到最终的压力向量，完成我们对斯托克斯预处理的工作。\n\n    template <class PreconditionerTypeA, class PreconditionerTypeMp> \n    void \n    BlockSchurPreconditioner<PreconditionerTypeA, PreconditionerTypeMp>::vmult( \n      TrilinosWrappers::MPI::BlockVector &      dst, \n      const TrilinosWrappers::MPI::BlockVector &src) const \n    { \n      a_preconditioner.vmult(dst.block(0), src.block(0)); \n      stokes_matrix->block(1, 0).residual(tmp, dst.block(0), src.block(1)); \n      tmp *= -1; \n      m_inverse->vmult(dst.block(1), tmp); \n    } \n  } // namespace LinearSolvers \n\n//  @sect3{The <code>BoussinesqFlowProblem</code> class template}  \n\n// 定义了解决随时间变化的Boussinesq问题的顶层逻辑的类的定义主要是基于 step-22 的教程程序。主要的区别在于，现在我们还必须求解温度方程，这迫使我们为温度变量准备第二个DoFHandler对象，以及当前和之前的时间步骤的矩阵、右手边和求解向量。正如介绍中提到的，所有的线性代数对象都将使用相应的Trilinos功能的包装器。\n\n// 这个类的成员函数让人想起 step-21 ，在那里我们也使用了一个交错的方案，首先解决流动方程（这里是斯托克斯方程， step-21 是达西流），然后更新平流量（这里是温度，那里是饱和度）。新的函数主要涉及到确定时间步长，以及人工粘性稳定的适当大小。\n\n// 最后三个变量表示在下次调用相应的建立函数时，是否需要重建各种矩阵或预处理程序。这使得我们可以将相应的 <code>if</code> 移到相应的函数中，从而使我们的主 <code>run()</code> 函数保持干净，易于阅读。\n\n  template <int dim> \n  class BoussinesqFlowProblem \n  { \n  public: \n    BoussinesqFlowProblem(); \n    void run(); \n\n  private: \n    void   setup_dofs(); \n    void   assemble_stokes_preconditioner(); \n    void   build_stokes_preconditioner(); \n    void   assemble_stokes_system(); \n    void   assemble_temperature_system(const double maximal_velocity); \n    void   assemble_temperature_matrix(); \n    double get_maximal_velocity() const; \n    std::pair<double, double> get_extrapolated_temperature_range() const; \n    void                      solve(); \n    void                      output_results() const; \n    void                      refine_mesh(const unsigned int max_grid_level); \n\n    double compute_viscosity( \n      const std::vector<double> &        old_temperature, \n      const std::vector<double> &        old_old_temperature, \n      const std::vector<Tensor<1, dim>> &old_temperature_grads, \n      const std::vector<Tensor<1, dim>> &old_old_temperature_grads, \n      const std::vector<double> &        old_temperature_laplacians, \n      const std::vector<double> &        old_old_temperature_laplacians, \n      const std::vector<Tensor<1, dim>> &old_velocity_values, \n      const std::vector<Tensor<1, dim>> &old_old_velocity_values, \n      const std::vector<double> &        gamma_values, \n      const double                       global_u_infty, \n      const double                       global_T_variation, \n      const double                       cell_diameter) const; \n\n    Triangulation<dim> triangulation; \n    double             global_Omega_diameter; \n\n    const unsigned int        stokes_degree; \n    FESystem<dim>             stokes_fe; \n    DoFHandler<dim>           stokes_dof_handler; \n    AffineConstraints<double> stokes_constraints; \n\n    std::vector<IndexSet>               stokes_partitioning; \n    TrilinosWrappers::BlockSparseMatrix stokes_matrix; \n    TrilinosWrappers::BlockSparseMatrix stokes_preconditioner_matrix; \n\n    TrilinosWrappers::MPI::BlockVector stokes_solution; \n    TrilinosWrappers::MPI::BlockVector old_stokes_solution; \n    TrilinosWrappers::MPI::BlockVector stokes_rhs; \n\n    const unsigned int        temperature_degree; \n    FE_Q<dim>                 temperature_fe; \n    DoFHandler<dim>           temperature_dof_handler; \n    AffineConstraints<double> temperature_constraints; \n\n    TrilinosWrappers::SparseMatrix temperature_mass_matrix; \n    TrilinosWrappers::SparseMatrix temperature_stiffness_matrix; \n    TrilinosWrappers::SparseMatrix temperature_matrix; \n\n    TrilinosWrappers::MPI::Vector temperature_solution; \n    TrilinosWrappers::MPI::Vector old_temperature_solution; \n    TrilinosWrappers::MPI::Vector old_old_temperature_solution; \n    TrilinosWrappers::MPI::Vector temperature_rhs; \n\n    double       time_step; \n    double       old_time_step; \n    unsigned int timestep_number; \n\n    std::shared_ptr<TrilinosWrappers::PreconditionAMG> Amg_preconditioner; \n    std::shared_ptr<TrilinosWrappers::PreconditionIC>  Mp_preconditioner; \n\n    bool rebuild_stokes_matrix; \n    bool rebuild_temperature_matrices; \n    bool rebuild_stokes_preconditioner; \n  }; \n// @sect3{BoussinesqFlowProblem class implementation}  \n// @sect4{BoussinesqFlowProblem::BoussinesqFlowProblem}  \n\n// 这个类的构造函数是对  step-22  中的构造函数的扩展。我们需要添加涉及温度的各种变量。正如介绍中所讨论的，我们将再次使用 $Q_2\\times Q_1$ （Taylor-Hood）元素来表示斯托克斯部分，并使用 $Q_2$ 元素表示温度。然而，通过使用存储斯托克斯和温度有限元的多项式程度的变量，可以很容易地持续修改这些元素的程度以及下游使用的所有正交公式。此外，我们还初始化了时间步长以及矩阵组合和预处理的选项。\n\n  template <int dim> \n  BoussinesqFlowProblem<dim>::BoussinesqFlowProblem() \n    : triangulation(Triangulation<dim>::maximum_smoothing) \n    , global_Omega_diameter(std::numeric_limits<double>::quiet_NaN()) \n    , stokes_degree(1) \n    , stokes_fe(FE_Q<dim>(stokes_degree + 1), dim, FE_Q<dim>(stokes_degree), 1) \n    , stokes_dof_handler(triangulation) \n    , \n\n    temperature_degree(2) \n    , temperature_fe(temperature_degree) \n    , temperature_dof_handler(triangulation) \n    , \n\n    time_step(0) \n    , old_time_step(0) \n    , timestep_number(0) \n    , rebuild_stokes_matrix(true) \n    , rebuild_temperature_matrices(true) \n    , rebuild_stokes_preconditioner(true) \n  {} \n\n//  @sect4{BoussinesqFlowProblem::get_maximal_velocity}  \n\n// 开始这个类的真正功能是一个辅助函数，确定域内（事实上是正交点）的最大（ $L_\\infty$  ）速度。它是如何工作的，对所有已经达到本教程这一点的人来说应该是比较明显的。请注意，由于我们只对速度感兴趣，我们不使用 <code>stokes_fe_values.get_function_values</code> 来获取整个斯托克斯解的值（速度和压力），而是使用 <code>stokes_fe_values[velocities].get_function_values</code> 来提取速度部分。这样做的额外好处是，我们得到的是张量<1,dim>，而不是向量<double>中的一些分量，这样我们就可以马上用 <code>norm()</code> 函数来处理它，得到速度的大小。\n\n// 唯一值得思考的一点是如何选择我们在这里使用的正交点。由于这个函数的目标是通过查看每个单元格上的正交点来寻找域内的最大速度。所以我们应该问，我们应该如何最好地选择每个单元上的这些正交点。为此，回顾一下，如果我们有一个单一的 $Q_1$ 场（而不是高阶的矢量值场），那么最大值将在网格的一个顶点达到。换句话说，我们应该使用QTrapezoid类，它的正交点只在单元的顶点。\n\n// 对于高阶形状函数，情况更为复杂：最大值和最小值可能在形状函数的支持点之间达到（对于通常的 $Q_p$ 元素，支持点是等距的Lagrange插值点）；此外，由于我们正在寻找一个矢量值的最大幅值，我们更不能肯定地说潜在的最大点集合在哪里。然而，从直觉上讲，即使不能证明，拉格朗日插值点似乎也是比高斯点更好的选择。\n\n// 现在有不同的方法来产生一个正交公式，其正交点等于有限元的插值点。一种选择是使用 FiniteElement::get_unit_support_points() 函数，将输出减少到一组唯一的点以避免重复的函数评估，并使用这些点创建一个正交对象。另一个选择，这里选择的是使用QTrapezoid类，并将其与QIterated类相结合，该类在每个坐标方向的若干子单元上重复QTrapezoid公式。为了覆盖所有的支持点，我们需要对其进行 <code>stokes_degree+1</code> 次迭代，因为这是使用中的斯托克斯元素的多项式程度。\n\n  template <int dim> \n  double BoussinesqFlowProblem<dim>::get_maximal_velocity() const \n  { \n    const QIterated<dim> quadrature_formula(QTrapezoid<1>(), stokes_degree + 1); \n    const unsigned int   n_q_points = quadrature_formula.size(); \n\n    FEValues<dim> fe_values(stokes_fe, quadrature_formula, update_values); \n    std::vector<Tensor<1, dim>> velocity_values(n_q_points); \n    double                      max_velocity = 0; \n\n    const FEValuesExtractors::Vector velocities(0); \n\n    for (const auto &cell : stokes_dof_handler.active_cell_iterators()) \n      { \n        fe_values.reinit(cell); \n        fe_values[velocities].get_function_values(stokes_solution, \n                                                  velocity_values); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          max_velocity = std::max(max_velocity, velocity_values[q].norm()); \n      } \n\n    return max_velocity; \n  } \n\n//  @sect4{BoussinesqFlowProblem::get_extrapolated_temperature_range}  \n\n// 接下来是一个函数，确定从前两个时间步长推算到当前步长时， $\\Omega$ 内正交点的最低和最高温度。我们在计算人工粘性参数 $\\nu$ 时需要这个信息，正如在介绍中所讨论的那样。\n\n// 外推温度的公式是  $\\left(1+\\frac{k_n}{k_{n-1}} \\right)T^{n-1} + \\frac{k_n}{k_{n-1}} T^{n-2}$  。计算的方法是在所有正交点上循环，如果当前值比前一个值大/小，则更新最大和最小值。在对所有正交点进行循环之前，我们将存储最大和最小值的变量初始化为可表示为双数的最小和最大的数字。这样我们就知道它比最小/最大值大/小，并且所有正交点的循环最终会用正确的值来更新初始值。\n\n// 这里唯一值得一提的复杂情况是，在第一个时间步骤中， $T^{k-2}$ 当然还不能使用。在这种情况下，我们只能使用 $T^{k-1}$ ，这是我们从初始温度得到的。作为正交点，我们使用与前一个函数相同的选择，但不同的是，现在重复的数量由温度场的多项式程度决定。\n\n  template <int dim> \n  std::pair<double, double> \n  BoussinesqFlowProblem<dim>::get_extrapolated_temperature_range() const \n  { \n    const QIterated<dim> quadrature_formula(QTrapezoid<1>(), \n                                            temperature_degree); \n    const unsigned int   n_q_points = quadrature_formula.size(); \n\n    FEValues<dim> fe_values(temperature_fe, quadrature_formula, update_values); \n    std::vector<double> old_temperature_values(n_q_points); \n    std::vector<double> old_old_temperature_values(n_q_points); \n\n    if (timestep_number != 0) \n      { \n        double min_temperature = std::numeric_limits<double>::max(), \n               max_temperature = -std::numeric_limits<double>::max(); \n\n        for (const auto &cell : temperature_dof_handler.active_cell_iterators()) \n          { \n            fe_values.reinit(cell); \n            fe_values.get_function_values(old_temperature_solution, \n                                          old_temperature_values); \n            fe_values.get_function_values(old_old_temperature_solution, \n                                          old_old_temperature_values); \n\n            for (unsigned int q = 0; q < n_q_points; ++q) \n              { \n                const double temperature = \n                  (1. + time_step / old_time_step) * old_temperature_values[q] - \n                  time_step / old_time_step * old_old_temperature_values[q]; \n\n                min_temperature = std::min(min_temperature, temperature); \n                max_temperature = std::max(max_temperature, temperature); \n              } \n          } \n\n        return std::make_pair(min_temperature, max_temperature); \n      } \n    else \n      { \n        double min_temperature = std::numeric_limits<double>::max(), \n               max_temperature = -std::numeric_limits<double>::max(); \n\n        for (const auto &cell : temperature_dof_handler.active_cell_iterators()) \n          { \n            fe_values.reinit(cell); \n            fe_values.get_function_values(old_temperature_solution, \n                                          old_temperature_values); \n\n            for (unsigned int q = 0; q < n_q_points; ++q) \n              { \n                const double temperature = old_temperature_values[q]; \n\n                min_temperature = std::min(min_temperature, temperature); \n                max_temperature = std::max(max_temperature, temperature); \n              } \n          } \n\n        return std::make_pair(min_temperature, max_temperature); \n      } \n  } \n\n//  @sect4{BoussinesqFlowProblem::compute_viscosity}  \n\n// 最后一个工具函数计算单元 $\\nu|_K$ 上的人工粘度参数 $K$ ，作为外推温度、其梯度和Hessian（二阶导数）、速度、当前单元正交点上的所有右手 $\\gamma$ 和其他各种参数的函数，在介绍中已详细说明。\n\n// 这里有一些值得一提的通用常数。首先，我们需要固定 $\\beta$ ；我们选择 $\\beta=0.017\\cdot dim$ ，这个选择在本教程程序的结果部分有详细讨论。其次是指数 $\\alpha$ ； $\\alpha=1$ 对于目前的程序似乎很好用，尽管选择 $\\alpha = 2$ 可能会有一些额外的好处。最后，有一件事需要特别说明。在第一个时间步骤中，速度等于零， $\\nu|_K$ 的公式没有定义。在这种情况下，我们返回 $\\nu|_K=5\\cdot 10^3 \\cdot h_K$ ，这个选择无疑更多的是出于启发式的考虑（不过，它与第二个时间步骤中大多数单元的返回值处于同一数量级）。\n\n// 根据介绍中讨论的材料，该函数的其余部分应该是显而易见的。\n\n  template <int dim> \n  double BoussinesqFlowProblem<dim>::compute_viscosity( \n    const std::vector<double> &        old_temperature, \n    const std::vector<double> &        old_old_temperature, \n    const std::vector<Tensor<1, dim>> &old_temperature_grads, \n    const std::vector<Tensor<1, dim>> &old_old_temperature_grads, \n    const std::vector<double> &        old_temperature_laplacians, \n    const std::vector<double> &        old_old_temperature_laplacians, \n    const std::vector<Tensor<1, dim>> &old_velocity_values, \n    const std::vector<Tensor<1, dim>> &old_old_velocity_values, \n    const std::vector<double> &        gamma_values, \n    const double                       global_u_infty, \n    const double                       global_T_variation, \n    const double                       cell_diameter) const \n  { \n    constexpr double beta  = 0.017 * dim; \n    constexpr double alpha = 1.0; \n\n    if (global_u_infty == 0) \n      return 5e-3 * cell_diameter; \n\n    const unsigned int n_q_points = old_temperature.size(); \n\n    double max_residual = 0; \n    double max_velocity = 0; \n\n    for (unsigned int q = 0; q < n_q_points; ++q) \n      { \n        const Tensor<1, dim> u = \n          (old_velocity_values[q] + old_old_velocity_values[q]) / 2; \n\n        const double dT_dt = \n          (old_temperature[q] - old_old_temperature[q]) / old_time_step; \n        const double u_grad_T = \n          u * (old_temperature_grads[q] + old_old_temperature_grads[q]) / 2; \n\n        const double kappa_Delta_T = \n          EquationData::kappa * \n          (old_temperature_laplacians[q] + old_old_temperature_laplacians[q]) / \n          2; \n\n        const double residual = \n          std::abs((dT_dt + u_grad_T - kappa_Delta_T - gamma_values[q]) * \n                   std::pow((old_temperature[q] + old_old_temperature[q]) / 2, \n                            alpha - 1.)); \n\n        max_residual = std::max(residual, max_residual); \n        max_velocity = std::max(std::sqrt(u * u), max_velocity); \n      } \n\n    const double c_R            = std::pow(2., (4. - 2 * alpha) / dim); \n    const double global_scaling = c_R * global_u_infty * global_T_variation * \n                                  std::pow(global_Omega_diameter, alpha - 2.); \n\n    return ( \n      beta * max_velocity * \n      std::min(cell_diameter, \n               std::pow(cell_diameter, alpha) * max_residual / global_scaling)); \n  } \n\n//  @sect4{BoussinesqFlowProblem::setup_dofs}  \n\n// 这是一个函数，用于设置我们这里的DoFHandler对象（一个用于斯托克斯部分，一个用于温度部分），以及将本程序中线性代数所需的各种对象设置为合适的尺寸。它的基本操作与我们在  step-22  中的操作类似。\n\n// 该函数的主体首先列举了斯托克斯和温度系统的所有自由度。对于斯托克斯部分，自由度被排序，以确保速度优先于压力自由度，这样我们就可以将斯托克斯矩阵划分为一个 $2\\times 2$ 矩阵。作为与 step-22 的区别，我们不进行任何额外的DoF重新编号。在那个程序中，它得到了回报，因为我们的求解器严重依赖ILU，而我们在这里使用AMG，它对DoF编号不敏感。用于压力质量矩阵反演的IC预处理程序当然会利用类似Cuthill-McKee的重新编号，但是与速度部分相比，其成本很低，所以额外的工作并没有得到回报。\n\n// 然后，我们继续生成悬挂的节点约束，这些约束来自两个DoFHandler对象的自适应网格细化。对于速度，我们通过向已经存储了悬挂节点约束矩阵的对象添加约束来施加无流边界条件 $\\mathbf{u}\\cdot \\mathbf{n}=0$ 。函数中的第二个参数描述了总dof向量中的第一个速度分量，这里是零。变量 <code>no_normal_flux_boundaries</code> 表示要设置无通量边界条件的边界指标；这里是边界指标0。\n\n// 做完这些后，我们计算各块中的自由度数量。\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::setup_dofs() \n  { \n    std::vector<unsigned int> stokes_sub_blocks(dim + 1, 0); \n    stokes_sub_blocks[dim] = 1; \n\n    { \n      stokes_dof_handler.distribute_dofs(stokes_fe); \n      DoFRenumbering::component_wise(stokes_dof_handler, stokes_sub_blocks); \n\n      stokes_constraints.clear(); \n      DoFTools::make_hanging_node_constraints(stokes_dof_handler, \n                                              stokes_constraints); \n      std::set<types::boundary_id> no_normal_flux_boundaries; \n      no_normal_flux_boundaries.insert(0); \n      VectorTools::compute_no_normal_flux_constraints(stokes_dof_handler, \n                                                      0, \n                                                      no_normal_flux_boundaries, \n                                                      stokes_constraints); \n      stokes_constraints.close(); \n    } \n    { \n      temperature_dof_handler.distribute_dofs(temperature_fe); \n\n      temperature_constraints.clear(); \n      DoFTools::make_hanging_node_constraints(temperature_dof_handler, \n                                              temperature_constraints); \n      temperature_constraints.close(); \n    } \n\n    const std::vector<types::global_dof_index> stokes_dofs_per_block = \n      DoFTools::count_dofs_per_fe_block(stokes_dof_handler, stokes_sub_blocks); \n\n    const unsigned int n_u = stokes_dofs_per_block[0], \n                       n_p = stokes_dofs_per_block[1], \n                       n_T = temperature_dof_handler.n_dofs(); \n\n    std::cout << \"Number of active cells: \" << triangulation.n_active_cells() \n              << \" (on \" << triangulation.n_levels() << \" levels)\" << std::endl \n              << \"Number of degrees of freedom: \" << n_u + n_p + n_T << \" (\" \n              << n_u << '+' << n_p << '+' << n_T << ')' << std::endl \n              << std::endl; \n\n// 下一步是创建斯托克斯和温度系统矩阵的稀疏模式，以及建立斯托克斯预处理矩阵的预处理。如同在 step-22 中一样，我们选择使用DynamicSparsityPattern的封锁版本来创建模式。\n\n// 因此，我们首先释放存储在矩阵中的内存，然后建立一个BlockDynamicSparsityPattern类型的对象，该对象由 $2\\times 2$ 块（用于斯托克斯系统矩阵和预处理器）或DynamicSparsityPattern（用于温度部分）组成。然后我们用非零模式填充这些对象，考虑到对于斯托克斯系统矩阵，在压力-压力块中没有条目（但所有速度矢量分量相互耦合并与压力耦合）。同样，在斯托克斯预处理矩阵中，只有对角线块是非零的，因为我们使用了介绍中讨论的矢量拉普拉斯。这个算子只把拉普拉斯的每个矢量分量与它自己联系起来，而不是与其他矢量分量联系起来。然而，应用无流量边界条件产生的约束条件将在边界处再次耦合向量分量）。\n\n// 在生成稀疏模式时，我们直接应用悬挂节点和无流边界条件的约束。这种方法在 step-27 中已经使用过了，但与早期教程中的方法不同，在早期教程中我们先建立原始的稀疏模式，然后才加入约束条件产生的条目。这样做的原因是，在以后的装配过程中，我们要在将本地道夫转移到全局道夫时立即分配约束。因此，在受限自由度的位置不会有数据写入，所以我们可以通过将最后一个布尔标志设置为 <code>false</code> ，让 DoFTools::make_sparsity_pattern 函数省略这些条目。一旦稀疏性模式准备好了，我们就可以用它来初始化特里诺斯矩阵。由于Trilinos矩阵在内部存储了稀疏模式，所以在初始化矩阵之后，没有必要再保留稀疏模式。\n\n    stokes_partitioning.resize(2); \n    stokes_partitioning[0] = complete_index_set(n_u); \n    stokes_partitioning[1] = complete_index_set(n_p); \n    { \n      stokes_matrix.clear(); \n\n      BlockDynamicSparsityPattern dsp(2, 2); \n\n      dsp.block(0, 0).reinit(n_u, n_u); \n      dsp.block(0, 1).reinit(n_u, n_p); \n      dsp.block(1, 0).reinit(n_p, n_u); \n      dsp.block(1, 1).reinit(n_p, n_p); \n\n      dsp.collect_sizes(); \n\n      Table<2, DoFTools::Coupling> coupling(dim + 1, dim + 1); \n\n      for (unsigned int c = 0; c < dim + 1; ++c) \n        for (unsigned int d = 0; d < dim + 1; ++d) \n          if (!((c == dim) && (d == dim))) \n            coupling[c][d] = DoFTools::always; \n          else \n            coupling[c][d] = DoFTools::none; \n\n      DoFTools::make_sparsity_pattern( \n        stokes_dof_handler, coupling, dsp, stokes_constraints, false); \n\n      stokes_matrix.reinit(dsp); \n    } \n\n    { \n      Amg_preconditioner.reset(); \n      Mp_preconditioner.reset(); \n      stokes_preconditioner_matrix.clear(); \n\n      BlockDynamicSparsityPattern dsp(2, 2); \n\n      dsp.block(0, 0).reinit(n_u, n_u); \n      dsp.block(0, 1).reinit(n_u, n_p); \n      dsp.block(1, 0).reinit(n_p, n_u); \n      dsp.block(1, 1).reinit(n_p, n_p); \n\n      dsp.collect_sizes(); \n\n      Table<2, DoFTools::Coupling> coupling(dim + 1, dim + 1); \n      for (unsigned int c = 0; c < dim + 1; ++c) \n        for (unsigned int d = 0; d < dim + 1; ++d) \n          if (c == d) \n            coupling[c][d] = DoFTools::always; \n          else \n            coupling[c][d] = DoFTools::none; \n\n      DoFTools::make_sparsity_pattern( \n        stokes_dof_handler, coupling, dsp, stokes_constraints, false); \n\n      stokes_preconditioner_matrix.reinit(dsp); \n    } \n\n// 温度矩阵（或者说是矩阵，因为我们提供了一个温度质量矩阵和一个温度刚度矩阵，它们将在时间离散化中被加在一起）的创建与斯托克斯矩阵的生成相同；只是在这里要简单得多，因为我们不需要照顾任何块或组件之间的耦合。注意我们是如何初始化三个温度矩阵的。我们只使用稀疏模式对第一个矩阵进行再初始化，而对其余两个再初始化则使用先前生成的矩阵。这样做的原因是，从一个已经生成的矩阵进行重新初始化，可以让Trilinos重新使用稀疏模式，而不是为每个副本生成一个新的模式。这样可以节省一些时间和内存。\n\n    { \n      temperature_mass_matrix.clear(); \n      temperature_stiffness_matrix.clear(); \n      temperature_matrix.clear(); \n\n      DynamicSparsityPattern dsp(n_T, n_T); \n      DoFTools::make_sparsity_pattern(temperature_dof_handler, \n                                      dsp, \n                                      temperature_constraints, \n                                      false); \n\n      temperature_matrix.reinit(dsp); \n      temperature_mass_matrix.reinit(temperature_matrix); \n      temperature_stiffness_matrix.reinit(temperature_matrix); \n    } \n\n// 最后，我们将斯托克斯解的向量 $\\mathbf u^{n-1}$ 和 $\\mathbf u^{n-2}$ ，以及温度 $T^{n}$ 、 $T^{n-1}$ 和 $T^{n-2}$ （时间步进所需）和所有系统的右手边设置为正确的大小和块结构。\n\n    IndexSet temperature_partitioning = complete_index_set(n_T); \n    stokes_solution.reinit(stokes_partitioning, MPI_COMM_WORLD); \n    old_stokes_solution.reinit(stokes_partitioning, MPI_COMM_WORLD); \n    stokes_rhs.reinit(stokes_partitioning, MPI_COMM_WORLD); \n\n    temperature_solution.reinit(temperature_partitioning, MPI_COMM_WORLD); \n    old_temperature_solution.reinit(temperature_partitioning, MPI_COMM_WORLD); \n    old_old_temperature_solution.reinit(temperature_partitioning, \n                                        MPI_COMM_WORLD); \n\n    temperature_rhs.reinit(temperature_partitioning, MPI_COMM_WORLD); \n  } \n\n//  @sect4{BoussinesqFlowProblem::assemble_stokes_preconditioner}  \n\n// 这个函数组装了我们用于预处理斯托克斯系统的矩阵。我们需要的是速度分量上的矢量拉普拉斯矩阵和压力分量上的质量矩阵，并以 $\\eta^{-1}$ 加权。我们首先生成一个适当阶数的正交对象，即FEValues对象，它可以给出正交点的值和梯度（连同正交权重）。接下来我们为单元格矩阵和局部与全局DoF之间的关系创建数据结构。向量 <code>grad_phi_u</code> and <code>phi_p</code> 将保存基函数的值，以便更快地建立局部矩阵，正如在 step-22 中已经完成的那样。在我们开始对所有活动单元进行循环之前，我们必须指定哪些成分是压力，哪些是速度。\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::assemble_stokes_preconditioner() \n  { \n    stokes_preconditioner_matrix = 0; \n\n    const QGauss<dim> quadrature_formula(stokes_degree + 2); \n    FEValues<dim>     stokes_fe_values(stokes_fe, \n                                   quadrature_formula, \n                                   update_JxW_values | update_values | \n                                     update_gradients); \n\n    const unsigned int dofs_per_cell = stokes_fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell); \n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    std::vector<Tensor<2, dim>> grad_phi_u(dofs_per_cell); \n    std::vector<double>         phi_p(dofs_per_cell); \n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure(dim); \n\n    for (const auto &cell : stokes_dof_handler.active_cell_iterators()) \n      { \n        stokes_fe_values.reinit(cell); \n        local_matrix = 0; \n\n// 本地矩阵的创建相当简单。只有一个拉普拉斯项（关于速度）和一个由 $\\eta^{-1}$ 加权的质量矩阵需要生成，所以本地矩阵的创建在两行中完成。一旦本地矩阵准备好了（在每个正交点上循环查看本地矩阵的行和列），我们就可以得到本地的DoF指数，并将本地信息写入全局矩阵中。我们像在 step-27 中那样做，也就是说，我们直接应用本地悬挂节点的约束。这样做，我们就不必事后再做，而且我们也不会在消除约束时将矩阵的条目写成实际上将再次设置为零。\n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            for (unsigned int k = 0; k < dofs_per_cell; ++k) \n              { \n                grad_phi_u[k] = stokes_fe_values[velocities].gradient(k, q); \n                phi_p[k]      = stokes_fe_values[pressure].value(k, q); \n              } \n\n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                local_matrix(i, j) += \n                  (EquationData::eta * \n                     scalar_product(grad_phi_u[i], grad_phi_u[j]) + \n                   (1. / EquationData::eta) * phi_p[i] * phi_p[j]) * \n                  stokes_fe_values.JxW(q); \n          } \n\n        cell->get_dof_indices(local_dof_indices); \n        stokes_constraints.distribute_local_to_global( \n          local_matrix, local_dof_indices, stokes_preconditioner_matrix); \n      } \n  } \n\n//  @sect4{BoussinesqFlowProblem::build_stokes_preconditioner}  \n\n// 这个函数生成将用于Schur互补块预处理的内部预处理。由于只有当矩阵发生变化时才需要重新生成预处理程序，因此在矩阵没有变化的情况下，该函数不需要做任何事情（即标志 <code>rebuild_stokes_preconditioner</code> 的值为 <code>false</code> ）。否则，它的第一个任务是调用 <code>assemble_stokes_preconditioner</code> 来生成预处理矩阵。\n\n// 接下来，我们为速度-速度矩阵  $A$  设置预处理程序。正如介绍中所解释的，我们将使用基于矢量拉普拉斯矩阵 $\\hat{A}$ 的AMG预处理器（它在频谱上与斯托克斯矩阵 $A$ 接近）。通常， TrilinosWrappers::PreconditionAMG 类可以被看作是一个好的黑箱预处理程序，不需要任何特殊的知识。然而，在这种情况下，我们必须小心：因为我们为一个矢量问题建立了一个AMG，我们必须告诉预处理程序设置哪个道夫属于哪个矢量成分。我们使用 DoFTools::extract_constant_modes, 函数来做这件事，该函数生成一组 <code>dim</code> 向量，其中每个向量在向量问题的相应分量中为1，在其他地方为0。因此，这些是每个分量上的常数模式，这解释了变量的名称。\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::build_stokes_preconditioner() \n  { \n    if (rebuild_stokes_preconditioner == false) \n      return; \n\n    std::cout << \"   Rebuilding Stokes preconditioner...\" << std::flush; \n\n    assemble_stokes_preconditioner(); \n\n    Amg_preconditioner = std::make_shared<TrilinosWrappers::PreconditionAMG>(); \n\n    std::vector<std::vector<bool>> constant_modes; \n    FEValuesExtractors::Vector     velocity_components(0); \n    DoFTools::extract_constant_modes(stokes_dof_handler, \n                                     stokes_fe.component_mask( \n                                       velocity_components), \n                                     constant_modes); \n    TrilinosWrappers::PreconditionAMG::AdditionalData amg_data; \n    amg_data.constant_modes = constant_modes; \n\n// 接下来，我们再设置一些AMG预处理程序的选项。特别是，我们需要告诉AMG设置，我们对速度矩阵使用二次基函数（这意味着矩阵中有更多的非零元素，因此需要在内部选择一种更稳健的算法）。此外，我们希望能够控制粗化结构的建立方式。Trilinos平滑聚合AMG的方法是寻找哪些矩阵条目与对角线条目大小相似，以便代数式地建立一个粗网格结构。通过将参数 <code>aggregation_threshold</code> 设置为0.02，我们指定所有尺寸超过该行中一些对角线枢轴的百分之二的条目应该形成一个粗网格点。这个参数是比较特别的，对它进行一些微调会影响预处理程序的性能。根据经验，较大的 <code>aggregation_threshold</code> 值会减少迭代次数，但增加每次迭代的成本。看一下Trilinos的文档会提供更多关于这些参数的信息。有了这个数据集，我们就用我们想要的矩阵来初始化预处理程序。\n\n// 最后，我们也初始化预处理程序以反转压力质量矩阵。这个矩阵是对称的，表现良好，所以我们可以选择一个简单的预处理程序。我们坚持使用不完全Cholesky（IC）因子化预处理器，它是为对称矩阵设计的。我们也可以选择SSOR预处理器，其松弛系数约为1.2，但IC对我们的例子来说更便宜。我们把预处理程序包成一个 <code>std::shared_ptr</code> 指针，这使得下次重新创建预处理程序更加容易，因为我们不必关心破坏以前使用的对象。\n\n    amg_data.elliptic              = true; \n    amg_data.higher_order_elements = true; \n    amg_data.smoother_sweeps       = 2; \n    amg_data.aggregation_threshold = 0.02; \n    Amg_preconditioner->initialize(stokes_preconditioner_matrix.block(0, 0), \n                                   amg_data); \n\n    Mp_preconditioner = std::make_shared<TrilinosWrappers::PreconditionIC>(); \n    Mp_preconditioner->initialize(stokes_preconditioner_matrix.block(1, 1)); \n\n    std::cout << std::endl; \n\n    rebuild_stokes_preconditioner = false; \n  } \n\n//  @sect4{BoussinesqFlowProblem::assemble_stokes_system}  \n\n// 我们用于推进耦合的斯托克斯-温度系统的时滞方案迫使我们将装配（以及线性系统的解）分成两步。第一步是创建斯托克斯系统的矩阵和右手边，第二步是创建温度道夫的矩阵和右手边，这取决于速度的线性系统的结果。\n\n// 该函数在每个时间步长的开始时被调用。在第一个时间步骤中，或者如果网格已经改变，由 <code>rebuild_stokes_matrix</code> 表示，我们需要组装斯托克斯矩阵；另一方面，如果网格没有改变，矩阵已经有了，这就没有必要了，我们需要做的就是组装右手边的向量，它在每个时间步骤中都会改变。\n\n// 关于实现的技术细节，与  step-22  相比没有太大变化。我们重置矩阵和向量，在单元格上创建正交公式，然后创建相应的FEValues对象。对于更新标志，我们只在完全装配的情况下需要基函数导数，因为右手边不需要它们；像往常一样，根据当前需要选择最小的标志集，使程序中进一步调用  FEValues::reinit  的效率更高。\n\n// 有一件事需要评论&ndash；因为我们有一个单独的有限元和DoFHandler来处理温度问题，所以我们需要生成第二个FEValues对象来正确评估温度解决方案。要实现这一点并不复杂：只需使用温度结构，并为我们需要用于评估温度解决方案的基函数值设置一个更新标志。这里需要记住的唯一重要部分是，两个FEValues对象使用相同的正交公式，以确保我们在循环计算两个对象的正交点时得到匹配的信息。\n\n// 声明的过程中，有一些关于数组大小的快捷方式，本地矩阵和右手的创建，以及与全局系统相比，本地道夫的索引的向量。\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::assemble_stokes_system() \n  { \n    std::cout << \"   Assembling...\" << std::flush; \n\n    if (rebuild_stokes_matrix == true) \n      stokes_matrix = 0; \n\n    stokes_rhs = 0; \n\n    const QGauss<dim> quadrature_formula(stokes_degree + 2); \n    FEValues<dim>     stokes_fe_values( \n      stokes_fe, \n      quadrature_formula, \n      update_values | update_quadrature_points | update_JxW_values | \n        (rebuild_stokes_matrix == true ? update_gradients : UpdateFlags(0))); \n\n    FEValues<dim> temperature_fe_values(temperature_fe, \n                                        quadrature_formula, \n                                        update_values); \n\n    const unsigned int dofs_per_cell = stokes_fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    FullMatrix<double> local_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     local_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n// 接下来我们需要一个向量，它将包含前一个时间层的温度解在正交点的值，以组装动量方程右侧的源项。让我们把这个向量称为  <code>old_solution_values</code>  。\n\n// 我们接下来创建的向量集包含了基函数的评估以及它们的梯度和对称梯度，将用于创建矩阵。将这些放到自己的数组中，而不是每次都向FEValues对象索取这些信息，是为了加速装配过程的优化，详情请参见 step-22 。\n\n// 最后两个声明是用来从整个FE系统中提取各个块（速度、压力、温度）的。\n\n    std::vector<double> old_temperature_values(n_q_points); \n\n    std::vector<Tensor<1, dim>>          phi_u(dofs_per_cell); \n    std::vector<SymmetricTensor<2, dim>> grads_phi_u(dofs_per_cell); \n    std::vector<double>                  div_phi_u(dofs_per_cell); \n    std::vector<double>                  phi_p(dofs_per_cell); \n\n    const FEValuesExtractors::Vector velocities(0); \n    const FEValuesExtractors::Scalar pressure(dim); \n\n// 现在开始对问题中的所有单元格进行循环。我们正在为这个装配例程处理两个不同的DoFHandlers，所以我们必须为使用中的两个对象设置两个不同的单元格迭代器。这可能看起来有点奇怪，因为斯托克斯系统和温度系统都使用相同的网格，但这是保持自由度同步的唯一方法。循环中的第一条语句也是非常熟悉的，按照更新标志的规定对有限元数据进行更新，将局部数组清零，并在正交点处获得旧解的值。然后我们准备在单元格上的正交点上循环。\n\n    auto       cell             = stokes_dof_handler.begin_active(); \n    const auto endc             = stokes_dof_handler.end(); \n    auto       temperature_cell = temperature_dof_handler.begin_active(); \n\n    for (; cell != endc; ++cell, ++temperature_cell) \n      { \n        stokes_fe_values.reinit(cell); \n        temperature_fe_values.reinit(temperature_cell); \n\n        local_matrix = 0; \n        local_rhs    = 0; \n\n        temperature_fe_values.get_function_values(old_temperature_solution, \n                                                  old_temperature_values); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            const double old_temperature = old_temperature_values[q]; \n\n// 接下来我们提取与内积中的条款相关的基础函数的值和梯度。如 step-22 所示，这有助于加速装配。    一旦完成，我们开始在本地矩阵的行和列上进行循环，并将相关的乘积送入矩阵。右手边是由温度驱动的重力方向（在我们的例子中是垂直方向）的强迫项。 请注意，右手边的项总是生成的，而矩阵的贡献只有在 <code>rebuild_matrices</code> 标志要求时才会更新。\n\n            for (unsigned int k = 0; k < dofs_per_cell; ++k) \n              { \n                phi_u[k] = stokes_fe_values[velocities].value(k, q); \n                if (rebuild_stokes_matrix) \n                  { \n                    grads_phi_u[k] = \n                      stokes_fe_values[velocities].symmetric_gradient(k, q); \n                    div_phi_u[k] = \n                      stokes_fe_values[velocities].divergence(k, q); \n                    phi_p[k] = stokes_fe_values[pressure].value(k, q); \n                  } \n              } \n\n            if (rebuild_stokes_matrix) \n              for (unsigned int i = 0; i < dofs_per_cell; ++i) \n                for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                  local_matrix(i, j) += \n                    (EquationData::eta * 2 * (grads_phi_u[i] * grads_phi_u[j]) - \n                     div_phi_u[i] * phi_p[j] - phi_p[i] * div_phi_u[j]) * \n                    stokes_fe_values.JxW(q); \n\n            const Point<dim> gravity = \n              -((dim == 2) ? (Point<dim>(0, 1)) : (Point<dim>(0, 0, 1))); \n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              local_rhs(i) += (-EquationData::density * EquationData::beta * \n                               gravity * phi_u[i] * old_temperature) * \n                              stokes_fe_values.JxW(q); \n          } \n\n// 循环所有单元的最后一步是将局部贡献输入到全局矩阵和向量结构中，并将其输入到  <code>local_dof_indices</code>  指定的位置。 同样，我们让AffineConstraints类来完成将单元格矩阵元素插入全局矩阵的工作，这已经浓缩了悬挂的节点约束。\n\n        cell->get_dof_indices(local_dof_indices); \n\n        if (rebuild_stokes_matrix == true) \n          stokes_constraints.distribute_local_to_global(local_matrix, \n                                                        local_rhs, \n                                                        local_dof_indices, \n                                                        stokes_matrix, \n                                                        stokes_rhs); \n        else \n          stokes_constraints.distribute_local_to_global(local_rhs, \n                                                        local_dof_indices, \n                                                        stokes_rhs); \n      } \n\n    rebuild_stokes_matrix = false; \n\n    std::cout << std::endl; \n  } \n\n//  @sect4{BoussinesqFlowProblem::assemble_temperature_matrix}  \n\n// 这个函数组装温度方程中的矩阵。温度矩阵由两部分组成，质量矩阵和时间步长乘以刚度矩阵，由拉普拉斯项乘以扩散量给出。由于该矩阵取决于时间步长（从一个步长到另一个步长），温度矩阵需要在每个时间步长进行更新。我们可以简单地在每个时间步长中重新生成矩阵，但这并不真正有效，因为质量和拉普拉斯矩阵只有在我们改变网格时才会改变。因此，我们通过在这个函数中生成两个单独的矩阵，一个是质量矩阵，一个是刚度（扩散）矩阵，这样做更有效率。一旦我们知道了实际的时间步长，我们将把这个矩阵加上刚度矩阵乘以时间步长的总和。\n\n// 所以这第一步的细节非常简单。为了防止我们需要重建矩阵（即网格发生了变化），我们将数据结构归零，得到一个正交公式和一个FEValues对象，并为基函数创建局部矩阵、局部dof指数和评估结构。\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::assemble_temperature_matrix() \n  { \n    if (rebuild_temperature_matrices == false) \n      return; \n\n    temperature_mass_matrix      = 0; \n    temperature_stiffness_matrix = 0; \n\n    QGauss<dim>   quadrature_formula(temperature_degree + 2); \n    FEValues<dim> temperature_fe_values(temperature_fe, \n                                        quadrature_formula, \n                                        update_values | update_gradients | \n                                          update_JxW_values); \n\n    const unsigned int dofs_per_cell = temperature_fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    FullMatrix<double> local_mass_matrix(dofs_per_cell, dofs_per_cell); \n    FullMatrix<double> local_stiffness_matrix(dofs_per_cell, dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    std::vector<double>         phi_T(dofs_per_cell); \n    std::vector<Tensor<1, dim>> grad_phi_T(dofs_per_cell); \n\n// 现在，让我们开始在三角结构中的所有单元上进行循环。我们需要将局部矩阵清零，更新有限元评估，然后在每个正交点上循环矩阵的行和列，然后我们创建质量矩阵和刚度矩阵（拉普拉斯项乘以扩散  <code>EquationData::kappa</code>  。最后，我们让约束对象将这些值插入全局矩阵中，并直接将约束条件浓缩到矩阵中。\n\n    for (const auto &cell : temperature_dof_handler.active_cell_iterators()) \n      { \n        local_mass_matrix      = 0; \n        local_stiffness_matrix = 0; \n\n        temperature_fe_values.reinit(cell); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            for (unsigned int k = 0; k < dofs_per_cell; ++k) \n              { \n                grad_phi_T[k] = temperature_fe_values.shape_grad(k, q); \n                phi_T[k]      = temperature_fe_values.shape_value(k, q); \n              } \n\n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                { \n                  local_mass_matrix(i, j) += \n                    (phi_T[i] * phi_T[j] * temperature_fe_values.JxW(q)); \n                  local_stiffness_matrix(i, j) += \n                    (EquationData::kappa * grad_phi_T[i] * grad_phi_T[j] * \n                     temperature_fe_values.JxW(q)); \n                } \n          } \n\n        cell->get_dof_indices(local_dof_indices); \n\n        temperature_constraints.distribute_local_to_global( \n          local_mass_matrix, local_dof_indices, temperature_mass_matrix); \n        temperature_constraints.distribute_local_to_global( \n          local_stiffness_matrix, \n          local_dof_indices, \n          temperature_stiffness_matrix); \n      } \n\n    rebuild_temperature_matrices = false; \n  } \n\n//  @sect4{BoussinesqFlowProblem::assemble_temperature_system}  \n\n// 这个函数对温度矩阵进行第二部分的装配工作，实际添加压力质量和刚度矩阵（时间步长在这里起作用），以及创建依赖于速度的右手边。这个函数中的右侧装配的声明与其他装配例程中使用的声明基本相同，只是这次我们把自己限制在矢量上。我们将计算温度系统的残差，这意味着我们必须评估二阶导数，由更新标志 <code>update_hessians</code> 指定。\n\n// 温度方程通过流体速度与斯托克斯系统相耦合。解决方案的这两部分与不同的DoFHandlers相关联，因此我们需要再次创建第二个FEValues对象来评估正交点的速度。\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::assemble_temperature_system( \n    const double maximal_velocity) \n  { \n    const bool use_bdf2_scheme = (timestep_number != 0); \n\n    if (use_bdf2_scheme == true) \n      { \n        temperature_matrix.copy_from(temperature_mass_matrix); \n        temperature_matrix *= \n          (2 * time_step + old_time_step) / (time_step + old_time_step); \n        temperature_matrix.add(time_step, temperature_stiffness_matrix); \n      } \n    else \n      { \n        temperature_matrix.copy_from(temperature_mass_matrix); \n        temperature_matrix.add(time_step, temperature_stiffness_matrix); \n      } \n\n    temperature_rhs = 0; \n\n    const QGauss<dim> quadrature_formula(temperature_degree + 2); \n    FEValues<dim>     temperature_fe_values(temperature_fe, \n                                        quadrature_formula, \n                                        update_values | update_gradients | \n                                          update_hessians | \n                                          update_quadrature_points | \n                                          update_JxW_values); \n    FEValues<dim>     stokes_fe_values(stokes_fe, \n                                   quadrature_formula, \n                                   update_values); \n\n    const unsigned int dofs_per_cell = temperature_fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    Vector<double> local_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n// 接下来是向量的声明，用来保存旧的和更早的解决方案的值（分别作为时间级别 $n-1$ 和 $n-2$ 的符号）和当前单元的正交点的梯度。我们还声明了一个对象来保存温度的右侧值（ <code>gamma_values</code> ），并且我们再次使用温度基函数的快捷方式。最终，我们需要找到温度极值和计算域的直径，这将用于稳定参数的定义（我们得到了最大速度作为这个函数的输入）。\n\n    std::vector<Tensor<1, dim>> old_velocity_values(n_q_points); \n    std::vector<Tensor<1, dim>> old_old_velocity_values(n_q_points); \n    std::vector<double>         old_temperature_values(n_q_points); \n    std::vector<double>         old_old_temperature_values(n_q_points); \n    std::vector<Tensor<1, dim>> old_temperature_grads(n_q_points); \n    std::vector<Tensor<1, dim>> old_old_temperature_grads(n_q_points); \n    std::vector<double>         old_temperature_laplacians(n_q_points); \n    std::vector<double>         old_old_temperature_laplacians(n_q_points); \n\n    EquationData::TemperatureRightHandSide<dim> temperature_right_hand_side; \n    std::vector<double>                         gamma_values(n_q_points); \n\n    std::vector<double>         phi_T(dofs_per_cell); \n    std::vector<Tensor<1, dim>> grad_phi_T(dofs_per_cell); \n\n    const std::pair<double, double> global_T_range = \n      get_extrapolated_temperature_range(); \n\n    const FEValuesExtractors::Vector velocities(0); \n\n// 现在，让我们开始在三角结构中的所有单元格上进行循环。同样，我们需要两个单元格迭代器，平行走过两个参与的DoFHandler对象的单元格，用于斯托克斯和温度部分。在这个循环中，我们首先将局部rhs设置为零，然后在正交点上获得旧的解函数的值和导数，因为它们将被用于稳定参数的定义和作为方程中的系数，分别需要。请注意，由于温度有自己的DoFHandler和FEValues对象，我们在正交点得到整个解（反正只有标量温度场），而对于斯托克斯部分，我们仅限于通过使用 <code>stokes_fe_values[velocities].get_function_values</code> 提取速度部分（而忽略压力部分）。\n\n    auto       cell        = temperature_dof_handler.begin_active(); \n    const auto endc        = temperature_dof_handler.end(); \n    auto       stokes_cell = stokes_dof_handler.begin_active(); \n\n    for (; cell != endc; ++cell, ++stokes_cell) \n      { \n        local_rhs = 0; \n\n        temperature_fe_values.reinit(cell); \n        stokes_fe_values.reinit(stokes_cell); \n\n        temperature_fe_values.get_function_values(old_temperature_solution, \n                                                  old_temperature_values); \n        temperature_fe_values.get_function_values(old_old_temperature_solution, \n                                                  old_old_temperature_values); \n\n        temperature_fe_values.get_function_gradients(old_temperature_solution, \n                                                     old_temperature_grads); \n        temperature_fe_values.get_function_gradients( \n          old_old_temperature_solution, old_old_temperature_grads); \n\n        temperature_fe_values.get_function_laplacians( \n          old_temperature_solution, old_temperature_laplacians); \n        temperature_fe_values.get_function_laplacians( \n          old_old_temperature_solution, old_old_temperature_laplacians); \n\n        temperature_right_hand_side.value_list( \n          temperature_fe_values.get_quadrature_points(), gamma_values); \n\n        stokes_fe_values[velocities].get_function_values(stokes_solution, \n                                                         old_velocity_values); \n        stokes_fe_values[velocities].get_function_values( \n          old_stokes_solution, old_old_velocity_values); \n\n// 接下来，我们根据介绍中的讨论，使用专用函数计算用于稳定的人工粘性。有了这个，我们就可以进入正交点和局部rhs矢量分量的循环了。这里的术语相当冗长，但其定义遵循本方案介绍中开发的时间-离散系统。BDF-2方案比用于第一时间步的后向欧拉方案多需要一个旧时间步的术语（并且涉及更复杂的因素）。当所有这些都完成后，我们将局部向量分配到全局向量中（包括悬挂节点约束）。\n\n        const double nu = \n          compute_viscosity(old_temperature_values, \n                            old_old_temperature_values, \n                            old_temperature_grads, \n                            old_old_temperature_grads, \n                            old_temperature_laplacians, \n                            old_old_temperature_laplacians, \n                            old_velocity_values, \n                            old_old_velocity_values, \n                            gamma_values, \n                            maximal_velocity, \n                            global_T_range.second - global_T_range.first, \n                            cell->diameter()); \n\n        for (unsigned int q = 0; q < n_q_points; ++q) \n          { \n            for (unsigned int k = 0; k < dofs_per_cell; ++k) \n              { \n                grad_phi_T[k] = temperature_fe_values.shape_grad(k, q); \n                phi_T[k]      = temperature_fe_values.shape_value(k, q); \n              } \n\n            const double T_term_for_rhs = \n              (use_bdf2_scheme ? \n                 (old_temperature_values[q] * (1 + time_step / old_time_step) - \n                  old_old_temperature_values[q] * (time_step * time_step) / \n                    (old_time_step * (time_step + old_time_step))) : \n                 old_temperature_values[q]); \n\n            const Tensor<1, dim> ext_grad_T = \n              (use_bdf2_scheme ? \n                 (old_temperature_grads[q] * (1 + time_step / old_time_step) - \n                  old_old_temperature_grads[q] * time_step / old_time_step) : \n                 old_temperature_grads[q]); \n\n            const Tensor<1, dim> extrapolated_u = \n              (use_bdf2_scheme ? \n                 (old_velocity_values[q] * (1 + time_step / old_time_step) - \n                  old_old_velocity_values[q] * time_step / old_time_step) : \n                 old_velocity_values[q]); \n\n            for (unsigned int i = 0; i < dofs_per_cell; ++i) \n              local_rhs(i) += \n                (T_term_for_rhs * phi_T[i] - \n                 time_step * extrapolated_u * ext_grad_T * phi_T[i] - \n                 time_step * nu * ext_grad_T * grad_phi_T[i] + \n                 time_step * gamma_values[q] * phi_T[i]) * \n                temperature_fe_values.JxW(q); \n          } \n\n        cell->get_dof_indices(local_dof_indices); \n        temperature_constraints.distribute_local_to_global(local_rhs, \n                                                           local_dof_indices, \n                                                           temperature_rhs); \n      } \n  } \n\n//  @sect4{BoussinesqFlowProblem::solve}  \n\n// 这个函数可以解决线性方程组的问题。在介绍之后，我们从斯托克斯系统开始，在这里我们需要生成我们的块状舒尔预处理器。由于所有相关的动作都在类 <code>BlockSchurPreconditioner</code> 中实现，我们所要做的就是适当地初始化这个类。我们需要传递的是一个用于压力质量矩阵的 <code>InverseMatrix</code> 对象，我们使用相应的类和我们已经生成的IC预处理器以及用于速度-速度矩阵的AMG预处理器一起设置。注意， <code>Mp_preconditioner</code> 和 <code>Amg_preconditioner</code> 都只是指针，所以我们用 <code>*</code> 来传递实际的预处理对象。\n\n// 一旦预处理程序准备好了，我们就为该块系统创建一个GMRES求解器。由于我们使用的是Trilinos数据结构，我们必须在求解器中设置相应的模板参数。GMRES需要在内部存储每次迭代的临时向量（见 step-22 的结果部分的讨论）&ndash；它可以使用的向量越多，一般来说性能越好。为了控制内存需求，我们将向量的数量设置为100。这意味着在求解器的100次迭代中，每个临时向量都可以被存储。如果求解器需要更频繁地迭代以获得指定的容忍度，它将通过每100次迭代重新开始，在一个减少的向量集上工作。\n\n// 有了这些设置，我们求解系统并在斯托克斯系统中分配约束条件，即悬挂节点和无流体边界条件，以便即使在受约束的道夫下也有适当的解值。最后，我们把迭代次数写到屏幕上。\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::solve() \n  { \n    std::cout << \"   Solving...\" << std::endl; \n\n    { \n      const LinearSolvers::InverseMatrix<TrilinosWrappers::SparseMatrix, \n                                         TrilinosWrappers::PreconditionIC> \n        mp_inverse(stokes_preconditioner_matrix.block(1, 1), \n                   *Mp_preconditioner); \n\n      const LinearSolvers::BlockSchurPreconditioner< \n        TrilinosWrappers::PreconditionAMG, \n        TrilinosWrappers::PreconditionIC> \n        preconditioner(stokes_matrix, mp_inverse, *Amg_preconditioner); \n\n      SolverControl solver_control(stokes_matrix.m(), \n                                   1e-6 * stokes_rhs.l2_norm()); \n\n      SolverGMRES<TrilinosWrappers::MPI::BlockVector> gmres( \n        solver_control, \n        SolverGMRES<TrilinosWrappers::MPI::BlockVector>::AdditionalData(100)); \n\n      for (unsigned int i = 0; i < stokes_solution.size(); ++i) \n        if (stokes_constraints.is_constrained(i)) \n          stokes_solution(i) = 0; \n\n      gmres.solve(stokes_matrix, stokes_solution, stokes_rhs, preconditioner); \n\n      stokes_constraints.distribute(stokes_solution); \n\n      std::cout << \"   \" << solver_control.last_step() \n                << \" GMRES iterations for Stokes subsystem.\" << std::endl; \n    } \n\n// 一旦我们知道了斯托克斯解，我们就可以根据最大速度确定新的时间步长。我们必须这样做以满足CFL条件，因为对流项在温度方程中得到了明确的处理，正如在介绍中所讨论的那样。这里使用的时间步长公式的确切形式将在本程序的结果部分讨论。\n\n// 这里有一个插曲。该公式包含了对速度最大值的除法。然而，在计算开始时，我们有一个恒定的温度场（我们以恒定的温度开始，只有在源作用的第一个时间步长后，它才会变成非恒定的）。恒定温度意味着没有浮力作用，所以速度为零。除以它不可能得到什么好结果。\n\n// 为了避免产生无限的时间步长，我们问最大速度是否非常小（特别是小于我们在接下来的任何时间步长中遇到的值），如果是，我们就不除以零，而是除以一个小值，从而产生一个大的但有限的时间步长。\n\n    old_time_step                 = time_step; \n    const double maximal_velocity = get_maximal_velocity(); \n\n    if (maximal_velocity >= 0.01) \n      time_step = 1. / (1.7 * dim * std::sqrt(1. * dim)) / temperature_degree * \n                  GridTools::minimal_cell_diameter(triangulation) / \n                  maximal_velocity; \n    else \n      time_step = 1. / (1.7 * dim * std::sqrt(1. * dim)) / temperature_degree * \n                  GridTools::minimal_cell_diameter(triangulation) / .01; \n\n    std::cout << \"   \" \n              << \"Time step: \" << time_step << std::endl; \n\n    temperature_solution = old_temperature_solution; \n\n// 接下来我们用函数  <code>assemble_temperature_system()</code>  设置温度系统和右手边。 知道了温度方程的矩阵和右手边，我们设置了一个预处理程序和一个求解器。温度矩阵是一个质量矩阵（特征值在1左右）加上一个拉普拉斯矩阵（特征值在0和 $ch^{-2}$ 之间）乘以一个与时间步长成正比的小数字  $k_n$  。因此，产生的对称和正定矩阵的特征值在 $[1,1+k_nh^{-2}]$ 范围内（至于常数）。这个矩阵即使对于小的网格尺寸也只是适度的条件不良，我们通过简单的方法得到一个相当好的预处理，例如用一个不完全的Cholesky分解预处理（IC），我们也用它来预处理压力质量矩阵求解器。作为一个求解器，我们选择共轭梯度法CG。和以前一样，我们通过模板参数 <code>TrilinosWrappers::MPI::Vector</code> 告诉求解器使用Trilinos向量。最后，我们求解，分配悬挂节点约束，并写出迭代次数。\n\n    assemble_temperature_system(maximal_velocity); \n    { \n      SolverControl solver_control(temperature_matrix.m(), \n                                   1e-8 * temperature_rhs.l2_norm()); \n      SolverCG<TrilinosWrappers::MPI::Vector> cg(solver_control); \n\n      TrilinosWrappers::PreconditionIC preconditioner; \n      preconditioner.initialize(temperature_matrix); \n\n      cg.solve(temperature_matrix, \n               temperature_solution, \n               temperature_rhs, \n               preconditioner); \n\n      temperature_constraints.distribute(temperature_solution); \n\n      std::cout << \"   \" << solver_control.last_step() \n                << \" CG iterations for temperature.\" << std::endl; \n\n// 在这个函数的结尾，我们在向量中步进并读出最大和最小的温度值，我们也想输出这些值。在本程序的结果部分讨论的确定时间步长的正确常数时，这将非常有用。\n\n      double min_temperature = temperature_solution(0), \n             max_temperature = temperature_solution(0); \n      for (unsigned int i = 0; i < temperature_solution.size(); ++i) \n        { \n          min_temperature = \n            std::min<double>(min_temperature, temperature_solution(i)); \n          max_temperature = \n            std::max<double>(max_temperature, temperature_solution(i)); \n        } \n\n      std::cout << \"   Temperature range: \" << min_temperature << ' ' \n                << max_temperature << std::endl; \n    } \n  } \n\n//  @sect4{BoussinesqFlowProblem::output_results}  \n\n// 该函数将解决方案写入VTK输出文件，用于可视化，每隔10个时间步长就会完成。这通常是一个相当简单的任务，因为deal.II库提供的函数几乎为我们完成了所有的工作。与以前的例子相比，有一个新的函数。我们想把斯托克斯解和温度都看作一个数据集，但是我们已经根据两个不同的DoFHandler对象完成了所有的计算。幸运的是，DataOut类已经准备好处理这个问题。我们所要做的就是不要在一开始就附加一个单一的DoFHandler，然后将其用于所有添加的向量，而是为每个向量分别指定DoFHandler。剩下的就像  step-22  中所做的那样。我们创建解决方案的名称（这些名称将出现在各个组件的可视化程序中）。第一个 <code>dim</code> 分量是矢量速度，然后我们有斯托克斯部分的压力，而温度是标量。这些信息是用DataComponentInterpretation辅助类读出来的。接下来，我们将数据向量与它们的DoFHandler对象连接起来，根据自由度建立补丁，这些补丁是描述可视化程序数据的（子）元素。最后，我们打开一个文件（包括时间步数）并将vtk数据写入其中。\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::output_results() const \n  { \n    if (timestep_number % 10 != 0) \n      return; \n\n    std::vector<std::string> stokes_names(dim, \"velocity\"); \n    stokes_names.emplace_back(\"p\"); \n    std::vector<DataComponentInterpretation::DataComponentInterpretation> \n      stokes_component_interpretation( \n        dim + 1, DataComponentInterpretation::component_is_scalar); \n    for (unsigned int i = 0; i < dim; ++i) \n      stokes_component_interpretation[i] = \n        DataComponentInterpretation::component_is_part_of_vector; \n\n    DataOut<dim> data_out; \n    data_out.add_data_vector(stokes_dof_handler, \n                             stokes_solution, \n                             stokes_names, \n                             stokes_component_interpretation); \n    data_out.add_data_vector(temperature_dof_handler, \n                             temperature_solution, \n                             \"T\"); \n    data_out.build_patches(std::min(stokes_degree, temperature_degree)); \n\n    std::ofstream output(\"solution-\" + \n                         Utilities::int_to_string(timestep_number, 4) + \".vtk\"); \n    data_out.write_vtk(output); \n  } \n\n//  @sect4{BoussinesqFlowProblem::refine_mesh}  \n\n// 这个函数负责处理自适应网格细化。这个函数执行的三个任务是：首先找出需要细化/粗化的单元，然后实际进行细化，并最终在两个不同的网格之间传输解向量。第一个任务是通过对温度使用成熟的凯利误差估计器来实现的（对于这个程序，我们主要关注的是温度，我们需要在高温度梯度的区域保持精确，同时也要避免有太多的数值扩散）。第二项任务是实际进行再塑形。这也只涉及到基本函数，例如 <code>refine_and_coarsen_fixed_fraction</code> ，它可以细化那些具有最大估计误差的单元，这些误差合计占80%，并粗化那些具有最小误差的单元，这些误差合计占10%。\n\n// 如果像这样实施，我们会得到一个不会有太大进展的程序。请记住，我们期望的温度场几乎是不连续的（扩散率 $\\kappa$ 毕竟非常小），因此我们可以预期，一个自由适应的网格会越来越细化到大梯度的区域。网格大小的减少将伴随着时间步长的减少，需要大量的时间步长来解决给定的最终时间。这也会导致在几个网格细化周期后，网格的不连续性解决得比开始时好得多。\n\n// 特别是为了防止时间步长的减少和相应的大量时间步长，我们限制了网格的最大细化深度。为此，在细化指标应用于单元格后，我们简单地在最细层的所有单元格上循环，如果它们会导致网格层次过高，则取消对它们的细化选择。\n\n  template <int dim> \n  void \n  BoussinesqFlowProblem<dim>::refine_mesh(const unsigned int max_grid_level) \n  { \n    Vector<float> estimated_error_per_cell(triangulation.n_active_cells()); \n\n    KellyErrorEstimator<dim>::estimate(temperature_dof_handler, \n                                       QGauss<dim - 1>(temperature_degree + 1), \n                                       {}, \n                                       temperature_solution, \n                                       estimated_error_per_cell); \n\n    GridRefinement::refine_and_coarsen_fixed_fraction(triangulation, \n                                                      estimated_error_per_cell, \n                                                      0.8, \n                                                      0.1); \n    if (triangulation.n_levels() > max_grid_level) \n      for (auto &cell : \n           triangulation.active_cell_iterators_on_level(max_grid_level)) \n        cell->clear_refine_flag(); \n\n// 作为网格细化的一部分，我们需要将旧的网格中的解决方案向量转移到新的网格中。为此，我们使用SolutionTransfer类，我们必须准备好需要转移到新网格的解向量（一旦完成细化，我们将失去旧的网格，所以转移必须与细化同时发生）。我们肯定需要的是当前温度和旧温度（BDF-2时间步长需要两个旧的解决方案）。由于SolutionTransfer对象只支持在每个dof处理程序中传输一个对象，我们需要在一个数据结构中收集两个温度解决方案。此外，我们也选择转移斯托克斯解，因为我们需要前两个时间步长的速度，其中只有一个是在飞行中计算的。\n\n// 因此，我们为斯托克斯和温度的DoFHandler对象初始化了两个SolutionTransfer对象，将它们附加到旧的dof处理程序中。有了这个，我们就可以准备三角测量和数据向量的细化了（按这个顺序）。\n\n    std::vector<TrilinosWrappers::MPI::Vector> x_temperature(2); \n    x_temperature[0]                            = temperature_solution; \n    x_temperature[1]                            = old_temperature_solution; \n    TrilinosWrappers::MPI::BlockVector x_stokes = stokes_solution; \n\n    SolutionTransfer<dim, TrilinosWrappers::MPI::Vector> temperature_trans( \n      temperature_dof_handler); \n    SolutionTransfer<dim, TrilinosWrappers::MPI::BlockVector> stokes_trans( \n      stokes_dof_handler); \n\n    triangulation.prepare_coarsening_and_refinement(); \n    temperature_trans.prepare_for_coarsening_and_refinement(x_temperature); \n    stokes_trans.prepare_for_coarsening_and_refinement(x_stokes); \n\n// 现在一切都准备好了，所以进行细化，在新的网格上重新创建dof结构，并初始化矩阵结构和 <code>setup_dofs</code> 函数中的新向量。接下来，我们实际执行网格之间的插值解。我们为温度创建另一份临时向量（现在与新网格相对应），并让插值函数完成这项工作。然后，产生的向量数组被写入各自的向量成员变量中。\n\n// 记住，约束集将在setup_dofs()调用中为新的三角结构进行更新。\n\n    triangulation.execute_coarsening_and_refinement(); \n    setup_dofs(); \n\n    std::vector<TrilinosWrappers::MPI::Vector> tmp(2); \n    tmp[0].reinit(temperature_solution); \n    tmp[1].reinit(temperature_solution); \n    temperature_trans.interpolate(x_temperature, tmp); \n\n    temperature_solution     = tmp[0]; \n    old_temperature_solution = tmp[1]; \n\n// 在解决方案被转移后，我们再对被转移的解决方案实施约束。\n\n    temperature_constraints.distribute(temperature_solution); \n    temperature_constraints.distribute(old_temperature_solution); \n\n// 对于斯托克斯矢量，一切都一样&ndash;除了我们不需要另一个临时矢量，因为我们只是插值了一个矢量。最后，我们必须告诉程序，矩阵和预处理程序需要重新生成，因为网格已经改变。\n\n    stokes_trans.interpolate(x_stokes, stokes_solution); \n\n    stokes_constraints.distribute(stokes_solution); \n\n    rebuild_stokes_matrix         = true; \n    rebuild_temperature_matrices  = true; \n    rebuild_stokes_preconditioner = true; \n  } \n\n//  @sect4{BoussinesqFlowProblem::run}  \n\n// 这个函数执行Boussinesq程序中的所有基本步骤。它首先设置一个网格（根据空间维度，我们选择一些不同级别的初始细化和额外的自适应细化步骤，然后在 <code>dim</code> 维度上创建一个立方体，并首次设置了道夫。由于我们想用一个自适应细化的网格开始时间步进，我们执行一些预细化步骤，包括所有的装配、求解和细化，但实际上没有在时间上推进。相反，我们使用被人诟病的 <code>goto</code> 语句，在网格细化后立即跳出时间循环，从 <code>start_time_iteration</code> 标签开始的新网格上重新开始。( <code>goto</code> 的使用将在 step-26 中讨论) 。\n\n// 在我们开始之前，我们将初始值投影到网格上，并获得 <code>old_temperature_solution</code> 矢量的第一个数据。然后，我们初始化时间步数和时间步长，开始时间循环。\n\n  template <int dim> \n  void BoussinesqFlowProblem<dim>::run() \n  { \n    const unsigned int initial_refinement     = (dim == 2 ? 4 : 2); \n    const unsigned int n_pre_refinement_steps = (dim == 2 ? 4 : 3); \n\n    GridGenerator::hyper_cube(triangulation); \n    global_Omega_diameter = GridTools::diameter(triangulation); \n\n    triangulation.refine_global(initial_refinement); \n\n    setup_dofs(); \n\n    unsigned int pre_refinement_step = 0; \n\n  start_time_iteration: \n\n    VectorTools::project(temperature_dof_handler, \n                         temperature_constraints, \n                         QGauss<dim>(temperature_degree + 2), \n                         EquationData::TemperatureInitialValues<dim>(), \n                         old_temperature_solution); \n\n    timestep_number = 0; \n    time_step = old_time_step = 0; \n\n    double time = 0; \n\n    do \n      { \n        std::cout << \"Timestep \" << timestep_number << \":  t=\" << time \n                  << std::endl; \n\n// 时间循环的第一步都是显而易见的；我们组装斯托克斯系统、预处理程序、温度矩阵（矩阵和预处理程序实际上只在我们之前重新处理的情况下发生变化），然后进行求解。在继续下一个时间步骤之前，我们必须检查我们是否应该首先完成预精炼步骤，或者是否应该重新啮合（每五个时间步骤），精炼到一个与初始精炼和预精炼步骤一致的水平。循环的最后一个步骤是推进解，即把解复制到下一个 \"较早 \"的时间层。\n\n        assemble_stokes_system(); \n        build_stokes_preconditioner(); \n        assemble_temperature_matrix(); \n\n        solve(); \n\n        output_results(); \n\n        std::cout << std::endl; \n\n        if ((timestep_number == 0) && \n            (pre_refinement_step < n_pre_refinement_steps)) \n          { \n            refine_mesh(initial_refinement + n_pre_refinement_steps); \n            ++pre_refinement_step; \n            goto start_time_iteration; \n          } \n        else if ((timestep_number > 0) && (timestep_number % 5 == 0)) \n          refine_mesh(initial_refinement + n_pre_refinement_steps); \n\n        time += time_step; \n        ++timestep_number; \n\n        old_stokes_solution          = stokes_solution; \n        old_old_temperature_solution = old_temperature_solution; \n        old_temperature_solution     = temperature_solution; \n      } \n\n// 做以上所有的工作，直到我们到达时间100。\n\n    while (time <= 100); \n  } \n} // namespace Step31 \n\n//  @sect3{The <code>main</code> function}  \n\n// 主函数看起来与所有其他程序几乎一样。\n\n// 有一个区别是我们必须要注意的。这个程序使用了Trilinos，而通常情况下，Trilinos被配置为可以使用MPI在%parallel中运行。这并不意味着它<i>has</i>可以在%parallel中运行，事实上这个程序（不像 step-32 ）根本没有尝试使用MPI在%parallel中做任何事情。然而，Trilinos希望MPI系统被初始化。我们通过创建一个类型为 Utilities::MPI::MPI_InitFinalize 的对象来做到这一点，该对象使用给main()的参数（即 <code>argc</code> 和 <code>argv</code> ）初始化MPI（如果可用的话），并在对象超出范围时再次去初始化它。\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace dealii; \n      using namespace Step31; \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization( \n        argc, argv, numbers::invalid_unsigned_int); \n\n// 这个程序只能在串行中运行。否则，将抛出一个异常。\n\n      AssertThrow(Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD) == 1, \n                  ExcMessage( \n                    \"This program can only be run in serial, use ./step-31\")); \n\n      BoussinesqFlowProblem<2> flow_problem; \n      flow_problem.run(); \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n\n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "2c7722c44df9dc5a74a51752a3961f3e5bb126d5", "size": 67378, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-31/step-31.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-31/step-31.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-31/step-31.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7803768681, "max_line_length": 492, "alphanum_fraction": 0.657232331, "num_tokens": 26506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.430471571327195}}
{"text": "/*\n * Copyright (c) 2016-2017, Rafael Ballester-Ripoll\n *                          (Visualization and MultiMedia Lab, University of Zurich),\n *                          rballester@ifi.uzh.ch\n *\n * Licensed under the LGPLv3.0 (https://github.com/rballester/tthresh/blob/master/LICENSE)\n */\n#include \"memtrace.h\"\n#include <tthresh/compress.h>\n\n#include <iostream>\n#include <vector>\n#include <math.h>\n#include <Eigen/Dense>\n\n#include \"encode.hpp\"\n#include \"tucker.hpp\"\n#include \"io.hpp\"\n#include \"utils.hpp\"\n\n#ifdef _WIN32\ntypedef long double LLDOUBLE;\ntypedef long double LDOUBLE;\n#else\n#include <unistd.h>\ntypedef __float128 LLDOUBLE;\ntypedef __float80 LDOUBLE;\n#endif\n\n\n//int qneeded;\n//\n//double rle_time = 0;\n//double raw_time = 0;\n//\n//double price = -1, total_bits_core = -1, eps_core = -1;\n//size_t total_bits = 0;\n\nstruct EncodingStats\n{\n    int qneeded = 0;\n    double price = -1, total_bits_core = -1, eps_core = -1;\n    size_t total_bits = 0;\n};\n\nstatic std::vector<uint64_t> encode_array(\n    tthresh::zs& zs, EncodingStats& stats, \n    const double* c, size_t size, double eps_target, bool is_core, bool verbose=false) {\n\n    /**********************************************/\n    // Compute and save maximum (in absolute value)\n    /**********************************************/\n\n    if (is_core && verbose)\n        std::cout << \"Preliminaries... \" << std::endl;\n    double maximum = 0;\n    for (size_t i = 0; i < size; i++) {\n        if (abs(c[i]) > maximum)\n            maximum = abs(c[i]);\n    }\n    double scale = ldexp(1, 63-ilogb(maximum));\n\n    uint64_t tmp;\n    memcpy(&tmp, (void*)&scale, sizeof(scale)); //TODO: save maximum or scale?\n    tthresh::write_bits(zs, tmp, 64);\n\n    LLDOUBLE normsq = 0;\n    std::vector<uint64_t> coreq(size);\n\n    // 128-bit float arithmetics are slow, so we split the computation of normsq into partial sums\n    size_t stepsize = 100;\n    size_t nsteps = ceil(size/double(stepsize));\n    size_t pos = 0;\n    for (size_t i = 0; i < nsteps; ++i) {\n        LDOUBLE partial_normsq = 0;\n        for (size_t j = 0; j < stepsize; ++j) {\n            coreq[pos] = uint64_t(abs(c[pos])*scale);\n            partial_normsq += LDOUBLE(abs(c[pos]))*abs(c[pos]);\n            pos++;\n            if (pos == size)\n                break;\n        }\n        normsq += partial_normsq;\n        if (pos == size)\n            break;\n    }\n    normsq *= LLDOUBLE(scale)*LLDOUBLE(scale);\n\n    LLDOUBLE sse = normsq;\n    LDOUBLE last_eps = 1;\n    LDOUBLE thresh = eps_target*eps_target*normsq;\n\n    /**************/\n    // Encode array\n    /**************/\n\n    std::vector<uint64_t> current(size, 0);\n\n    //if (is_core and verbose)\n    //    stop_timer();\n    bool done = false;\n    stats.total_bits = 0;\n    size_t last_total_bits = stats.total_bits;\n    double eps_delta = 0, size_delta = 0, epsilon;\n    int q;\n    bool all_raw = false;\n    if (verbose)\n        std::cout << \"Encoding core...\" << std::endl;\n    for (q = 63; q >= 0; --q) {\n        if (verbose && is_core)\n            std::cout << \"Encoding core's bit plane p = \" << q << std::flush;\n        std::vector<uint64_t> rle;\n        LDOUBLE plane_sse = 0;\n        size_t plane_ones = 0;\n        size_t counter = 0;\n        size_t i;\n        std::vector<bool> raw;\n        for (i = 0; i < size; ++i) {\n            bool current_bit = ((coreq[i]>>q)&1ULL);\n            plane_ones += current_bit;\n            if (!all_raw && current[i] == 0) { // Feed to RLE\n                if (!current_bit)\n                    counter++;\n                else {\n                    rle.push_back(counter);\n                    counter = 0;\n                }\n            }\n            else { // Feed to raw stream\n                ++stats.total_bits;\n                raw.push_back(current_bit);\n            }\n\n            if (current_bit) {\n                plane_sse += (LDOUBLE(coreq[i] - current[i]));\n                current[i] |= 1ULL<<q;\n                if (plane_ones%100 == 0) {\n                    LDOUBLE k = 1ULL<<q;\n                    LDOUBLE sse_now = sse+(-2*k*plane_sse + k*k*plane_ones);\n                    if (sse_now <= thresh) {\n                        done = true;\n                        if (verbose)\n                            std::cout << \" <- breakpoint: coefficient \" << i << std::flush;\n                        break;\n                    }\n                }\n\n            }\n        }\n        if (verbose && is_core)\n            std::cout << std::endl;\n\n        LDOUBLE k = 1ULL<<q;\n        sse += -2*k*plane_sse + k*k*plane_ones;\n        rle.push_back(counter);\n\n        uint64_t rawsize = raw.size();\n        write_bits(zs, rawsize, 64);\n        stats.total_bits += 64;\n\n        {\n            //high_resolution_clock::time_point timenow = chrono::high_resolution_clock::now();\n            for (size_t i = 0; i < raw.size(); ++i)\n                write_bits(zs, raw[i], 1);\n            //raw_time += std::chrono::duration_cast<std::chrono::microseconds>(chrono::high_resolution_clock::now() - timenow).count()/1000.;\n        }\n        {\n            //high_resolution_clock::time_point timenow = chrono::high_resolution_clock::now();\n            uint64_t this_part = tthresh::encode(zs, rle);\n            //rle_time += std::chrono::duration_cast<std::chrono::microseconds>(chrono::high_resolution_clock::now() - timenow).count()/1000.;\n            stats.total_bits += this_part;\n        }\n\n        epsilon = sqrt(double(sse/normsq));\n        if (last_total_bits > 0) {\n            if (is_core) {\n                size_delta = (stats.total_bits - last_total_bits) / double(last_total_bits);\n                eps_delta = (last_eps - epsilon) / epsilon;\n            }\n            else {\n                if ((stats.total_bits/ stats.total_bits_core) / (epsilon/ stats.eps_core) >= stats.price)\n                    done = true;\n            }\n        }\n        last_total_bits = stats.total_bits;\n        last_eps = epsilon;\n\n        if (raw.size()/double(size) > 0.8)\n            all_raw = true;\n\n        write_bits(zs, all_raw, 1);\n        stats.total_bits++;\n\n        write_bits(zs, done, 1);\n        stats.total_bits++;\n\n        if (done)\n            break;\n    }\n    //if (verbose)\n    //    stop_timer();\n\n    /****************************************/\n    // Save signs of significant coefficients\n    /****************************************/\n\n    for (size_t i = 0; i < size; ++i) {\n        if (current[i] > 0) {\n            write_bits(zs, (c[i] > 0), 1);\n            stats.total_bits++;\n        }\n    }\n\n    if (is_core) {\n        stats.price = size_delta / eps_delta;\n        stats.eps_core = epsilon;\n        stats.total_bits_core = stats.total_bits;\n    }\n    return current;\n}\n\n\n\nvoid tthresh::compress(\n    std::ostream& out, const double* inputData, const std::vector<uint32_t>& dimensions,\n    tthresh::Target target, double targetValue, bool verbose)\n{\n    const int n = dimensions.size();\n    if (n == 0) {\n        std::cerr << \"Input array is zero-dimensional!\" << std::endl;\n        return;\n    }\n    size_t size = dimensions[0];\n    for (int i = 1; i < n; ++i) size *= dimensions[i];\n    if (size == 0) {\n        std::cerr << \"Input array is empty!\" << std::endl;\n        return;\n    }\n\n    std::vector<size_t> dimensionsProd;\n    cumulative_products(dimensions, dimensionsProd);\n\n    /********************************************/\n    // Save tensor dimensionality and sizes\n    /********************************************/\n    out.write(reinterpret_cast <const char*> (&n), sizeof(n));\n    out.write(reinterpret_cast <const char*> (dimensions.data()), n*sizeof(dimensions[0]));\n\n    /*****************************/\n    // Compute data norms\n    /*****************************/\n\n    double datamin = std::numeric_limits<double>::max(); // Tensor statistics\n    double datamax = std::numeric_limits<double>::min();\n    double datanorm = 0;\n    for (size_t i = 0; i < size; ++i) {\n        const auto data = inputData[i];\n        datamin = std::min(datamin, data); // Compute statistics, since we're at it\n        datamax = std::max(datamax, data);\n        datanorm += data * data;\n    }\n    datanorm = sqrt(datanorm);\n    if (verbose)\n        std::cout << \"Input statistics: min = \" << datamin << \", max = \" << datamax << \", norm = \" << datanorm << std::endl;\n\n    /**********************************************************************/\n    // Compute the target SSE (sum of squared errors) from the given metric\n    /**********************************************************************/\n\n    double sse;\n    if (target == compression::EPS)\n        sse = pow(targetValue * datanorm, 2);\n    else if (target == compression::RMSE)\n        sse = pow(targetValue, 2) * size;\n    else //PSNR\n        sse = pow((datamax - datamin) / (2 * (pow(10, targetValue / 20))), 2) * size;\n    double epsilon = sqrt(sse) / datanorm;\n    if (verbose) {\n        double rmse = sqrt(sse / size);\n        double psnr = 20 * log10((datamax - datamin) / (2 * rmse));\n        std::cout << \"We target eps = \" << epsilon << \", rmse = \" << rmse << \", psnr = \" << psnr << std::endl;\n    }\n\n    /*********************************/\n    // Create and decompose the tensor\n    /*********************************/\n\n    if (verbose)\n        std::cout << \"Tucker decomposition...\" << std::endl;\n    std::unique_ptr<double[]> c = std::make_unique<double[]>(size);\n\n    memcpy(c.get(), inputData, size * sizeof(double));\n\n    std::vector<Eigen::MatrixXd> Us(n); // Tucker factor matrices\n    tthresh::hosvd_compress(c.get(), Us, dimensions, dimensionsProd, verbose);\n\n//    if (verbose) {\n//        stop_timer();\n////        cout << \"RLE time (ms):\" << rle_time << endl;\n////        cout << \"Raw time (ms):\" << raw_time << endl;\n//    }\n\n    /**************************/\n    // Encode and save the core\n    /**************************/\n\n    zs zs(&out);\n    open_wbit(zs);\n    EncodingStats encodingStats;\n    std::vector<uint64_t> current = encode_array(zs, encodingStats, c.get(), size, epsilon, true, verbose);\n    close_wbit(zs);\n\n    /*******************************/\n    // Compute and save tensor ranks\n    /*******************************/\n\n    if (verbose)\n        std::cout << \"Computing ranks... \" << std::endl;;\n    std::vector<uint32_t> r(n, 0);\n    std::vector<size_t> indices(n, 0);\n    std::vector<Eigen::RowVectorXd > slicenorms(n);\n    for (int dim = 0; dim < n; ++dim) {\n        slicenorms[dim] = Eigen::RowVectorXd(dimensions[dim]);\n        slicenorms[dim].setZero();\n    }\n    for (size_t i = 0; i < size; ++i) {\n        if (current[i] > 0) {\n            for (int dim = 0; dim < n; ++dim) {\n                slicenorms[dim][indices[dim]] += double(current[i])*current[i];\n            }\n        }\n        indices[0]++;\n        int pos = 0;\n        while (indices[pos] >= dimensions[pos] && pos < n-1) {\n            indices[pos] = 0;\n            pos++;\n            indices[pos]++;\n        }\n    }\n\n    for (int dim = 0; dim < n; ++dim) {\n        for (size_t i = 0; i < dimensions[dim]; ++i) {\n            if (slicenorms[dim][i] > 0)\n                r[dim] = i+1;\n            slicenorms[dim][i] = sqrt(slicenorms[dim][i]);\n        }\n    }\n    //if (verbose)\n    //    stop_timer();\n\n    if (verbose) {\n        std::cout << \"Compressed tensor ranks:\";\n        for (uint8_t i = 0; i < n; ++i)\n            std::cout << \" \" << r[i];\n        std::cout << std::endl;\n    }\n    write_stream(zs, reinterpret_cast<unsigned char*> (&r[0]), n*sizeof(r[0]));\n\n    for (uint8_t i = 0; i < n; ++i) {\n        write_stream(zs, reinterpret_cast<uint8_t*> (slicenorms[i].data()), r[i]*sizeof(double));\n    }\n\n    std::vector<Eigen::MatrixXd> Uweighteds;\n    open_wbit(zs);\n    for (int dim = 0; dim < n; ++dim) {\n        Eigen::MatrixXd Uweighted = Us[dim].leftCols(r[dim]);\n        for (size_t col = 0; col < r[dim]; ++col)\n            Uweighted.col(col) = Uweighted.col(col)*slicenorms[dim][col];\n        Uweighteds.push_back(Uweighted);\n        encode_array(zs, encodingStats, Uweighted.data(), dimensions[dim]*r[dim], 0, false);//*(s[i]*s[i]/sprod[n]));  // TODO flatten in F order?\n    }\n    close_wbit(zs);\n    c.reset();\n    size_t newbits = zs.total_written_bytes * 8;\n    if (verbose) {\n        constexpr int io_type_size = sizeof(double);\n        std::cout << \"oldbits = \" << size * io_type_size * 8L << \", newbits = \" << newbits << \", compressionratio = \" << size * io_type_size * 8L / double(newbits)\n            << \", bpv = \" << newbits / double(size) << std::endl << std::flush;\n    }\n}\n\n", "meta": {"hexsha": "466360a2239f8a649d9c402547b6c0d9bfc70d97", "size": 12473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "compression/src/tthresh/compress.cpp", "max_stars_repo_name": "shamanDevel/fV-SRN", "max_stars_repo_head_hexsha": "966926ee678a0db0f1c67661537c4bb7eec0c56f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-12-06T05:08:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T15:11:06.000Z", "max_issues_repo_path": "compression/src/tthresh/compress.cpp", "max_issues_repo_name": "shamanDevel/fV-SRN", "max_issues_repo_head_hexsha": "966926ee678a0db0f1c67661537c4bb7eec0c56f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-02-07T10:07:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T14:13:50.000Z", "max_forks_repo_path": "compression/src/tthresh/compress.cpp", "max_forks_repo_name": "shamanDevel/fV-SRN", "max_forks_repo_head_hexsha": "966926ee678a0db0f1c67661537c4bb7eec0c56f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-12-13T07:02:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T15:46:44.000Z", "avg_line_length": 32.6518324607, "max_line_length": 163, "alphanum_fraction": 0.5070151527, "num_tokens": 3255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.43047157132719494}}
{"text": "//==============================================================================\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//         Copyright 2012 - 2014 NUMSCALE SAS\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EXPONENTIAL_FUNCTIONS_GENERIC_POW_HPP_INCLUDED\n#define NT2_EXPONENTIAL_FUNCTIONS_GENERIC_POW_HPP_INCLUDED\n\n#include <nt2/exponential/functions/pow.hpp>\n#include <nt2/include/functions/simd/rec.hpp>\n#include <nt2/include/functions/simd/negif.hpp>\n#include <nt2/include/functions/simd/is_ltz.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/bitwise_cast.hpp>\n#include <nt2/include/functions/simd/sqr.hpp>\n#include <nt2/include/functions/scalar/is_odd.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n#include <nt2/sdk/meta/as_unsigned.hpp>\n#include <boost/simd/operator/functions/details/assert_utils.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/assert.hpp>\n\nnamespace nt2 { namespace ext\n{\n  template<unsigned long long Exp, unsigned long long Odd = Exp%2>\n  struct pow_expander;\n\n  template<unsigned long long Exp>\n  struct pow_expander<Exp, 0ULL>\n  {\n    template<class A0>\n    static BOOST_FORCEINLINE A0 call(A0 const& a0)\n    {\n      return pow_expander<Exp/2>::call(sqr(a0));\n    }\n  };\n\n  template<unsigned long long Exp>\n  struct pow_expander<Exp, 1ULL>\n  {\n    template<class A0>\n    static BOOST_FORCEINLINE A0 call(A0 const& a0)\n    {\n      return a0*pow_expander<Exp/2>::call(sqr(a0));\n    }\n  };\n\n  template<>\n  struct pow_expander<0ULL, 0ULL>\n  {\n    template<class A0>\n    static BOOST_FORCEINLINE A0 call(A0 const&)\n    {\n      return One<A0>();\n    }\n  };\n\n  template<>\n  struct pow_expander<0ULL, 1ULL>\n  {\n    template<class A0>\n    static BOOST_FORCEINLINE A0 call(A0 const&)\n    {\n      return One<A0>();\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( pow_, tag::cpu_\n                            , (A0)(A1)\n                            , (generic_< arithmetic_<A0> >)\n                              (mpl_integral_< scalar_< uint_<A1> > >)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1) const\n    {\n      return pow_expander<A1::value>::call(a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( pow_, tag::cpu_\n                            , (A0)(A1)\n                            , (generic_< floating_<A0> >)\n                              (mpl_integral_< scalar_< int_<A1> > >)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1) const\n    {\n      return eval(a0, boost::mpl::bool_<(A1::value >= 0)>());\n    }\n\n    BOOST_FORCEINLINE result_type eval(A0 const& a0, boost::mpl::true_) const\n    {\n      return pow_expander<A1::value>::call(a0);\n    }\n\n    BOOST_FORCEINLINE result_type eval(A0 const& a0, boost::mpl::false_) const\n    {\n      return pow_expander<-A1::value>::call(rec(a0));\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( pow_, tag::cpu_\n                            , (A0)(A1)\n                            , (generic_< arithmetic_<A0> >)\n                              (scalar_< uint_<A1> >)\n                            )\n  {\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      A0 base = a0;\n      A1 exp = a1;\n\n      result_type result = One<result_type>();\n      while(exp)\n      {\n        if(is_odd(exp))\n            result *= base;\n        exp >>= 1;\n        base = sqr(base);\n      }\n\n      return result;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( pow_, tag::cpu_\n                            , (A0)(A1)\n                            , (generic_< integer_<A0> >)\n                              (generic_< int_<A1> >)\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE NT2_FUNCTOR_CALL(2)\n    {\n      BOOST_ASSERT_MSG( boost::simd::assert_all(a1 >= 0), \"integral pow with signed exponent\" );\n\n      typedef typename meta::as_unsigned<A1>::type utype;\n      return pow(a0, bitwise_cast<utype>(a1));\n    }\n  };\n\n\n  BOOST_DISPATCH_IMPLEMENT  ( pow_, tag::cpu_\n                            , (A0)(A1)\n                            , (generic_< floating_<A0> >)\n                              (generic_< int_<A1> >)\n                            )\n  {\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      typedef typename meta::as_unsigned<A1>::type utype;\n      typename meta::as_logical<A1>::type ltza1 = is_ltz(a1);\n      result_type p = pow(a0, bitwise_cast<utype>(negif(ltza1, a1)));\n      return if_else(ltza1, rec(p), p);\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "80e3c1fd28c998b36d4a99730e7bd1b0d881791e", "size": 4843, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/exponential/include/nt2/exponential/functions/generic/pow.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/exponential/include/nt2/exponential/functions/generic/pow.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/exponential/include/nt2/exponential/functions/generic/pow.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 27.9942196532, "max_line_length": 96, "alphanum_fraction": 0.5504852364, "num_tokens": 1216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.43047157132719494}}
{"text": "// This is main.\n// This is Car Parrinello molecular dynamics for simulating dynamics of ions near a nanoparticle (NP) surface\n// This will power app 2: nanosphere electrostatics lab. the app is part of the nanoparticle characterization framework.\n// The framework is expected to launch nanorod electrostatics lab, nanodisc electrostatics lab etc. apps\n// Problem : Compute the density profile of ions around a NP; and estimate a zeta potential or effective charge of the ion\n/* Useful studies :\t\n\t\t     1. Role of dielectric contrast\n\t\t     2. Role of valency of ions\n\t\t     3. Role of varying salt concentration\n\t\t     4. Role of NP charge\n*/\n\n/* @kadupitiya\n * e = E = 78.5 does simple MD; e != E invokes cpmd\n * these parameters produce good converged results that can be compared against the available data (which is plotted in the image sent separately):\n * -a 2.6775 -b 14.28 -e 2 -E 78.5 -V -60 -v 1 -g 1082 -m 6 -t 0.001 -s 10000 -p 100 -f 10 -M 6 -T 0.001 -k 0.0025 -q 0.001 -L 5 -l 5 -S 10000000 -P 100000 -F 100 -X 10000 -U 1000 -Y 500000 -W 1000000 -B 0.025\n * change valency v to 1 (red in image), 2 (green), 3 (blue); everything else can remain the same\n * m = M, k, t = T, q depend on g (the grid size); g depends on e & E, and a. higher the dielectric contrast, that is difference between e and E, higher g is needed to resolve the induced charge density.\n * the selection of these 5 parameters is made manually by monitoring energies, trial and error-- I spent a lot of time just doing that before submitting a useful run to get the ion density. i think there is a possibility of using ML to select these 5 CPMD parameters judiciously. we can pursue this tangentially to nanohub project; hoping it spirals into one of our collaborative hpc/ml projects.\n * the default parameters right now in boost are for a fast simulation that works. as you see they are different than the above parameters for different g etc.:\n * -a 2.6775 -b 14.28 -e 2 -E 78.5 -V -60 -v 1 -g 132 -m 1 -t 0.001 -s 10000 -p 100 -f 10 -M 1 -T 0.001 -k 0.01 -q 1 -L 5 -l 5 -S 50000 -P 10000 -F 100 -X 1000 -U 1000 -Y 10000 -W 10000 -B 0.1\n * the quick_check_polarized_data has a short run from these paramaters for you to perform a quick check against any code changes, if you want.\n * the following is slightly slower but produces a better profile (still far from converged):\n * -a 2.6775 -b 14.28 -e 2 -E 78.5 -V -60 -v 1 -g 132 -m 1 -t 0.001 -s 10000 -p 100 -f 10 -M 1 -T 0.001 -k 0.01 -q 1 -L 5 -l 5 -S 200000 -P 100000 -F 100 -X 10000 -U 10000 -Y 100000 -W 10000 -B 0.1\n * for cpmd, successful simulation demands more than energy conservation:\n * \t1. _ind_*.dat files in verifiles should roughly match the _cpmd_*.dat files in computedfiles\n * \t2. total_induced_charge.dat in outfiles should be very close to 0\n * \t3. track_deviation.dat in outfiles should be small (< 1) and stable-- usually this will happen if the above 2 criteria hold; see also average deviation before R in the output at the end-- should be small\n * \t4. and of course, R should be small like before (could be a bit higher than normal MD)\n */\n\n#include <boost/program_options.hpp>\n#include \"functions.h\"\n#include \"precalculations.h\"\n#include \"NanoParticleDisk.h\"\n#include \"NanoParticleSphere.h\"\n\n//MPI boundary parameters\nunsigned int lowerBoundIons;\nunsigned int upperBoundIons;\nunsigned int sizFVecIons;\nunsigned int extraElementsIons;\nunsigned int lowerBoundMesh;\nunsigned int upperBoundMesh;\nunsigned int sizFVecMesh;\nunsigned int extraElementsMesh;\nmpi::environment env;\nmpi::communicator world;\n\nvector<int> condensedIonsPerStep; // Number of condensed ions per step (after equilibrium) at specified frequency\n\nusing namespace boost::program_options;\n\nint main(int argc, char *argv[]) {\n\n    // Electrostatic system variables\n    double radius;        // radius of the dielectric sphere\n    double ein;            // permittivity of inside medium\n    double eout;            // permittivity of outside medium\n    int counterion_valency;    // counterion valency (positive by convention)\n    double counterion_diameter;    // counterion diameter\n    int salt_valency_in;        // salt valency inside\n    int salt_valency_out;        // salt valency outside\n    double salt_conc_in;        // salt concentration outside\t(enter in M)\n    double salt_conc_out;        // salt concentration outside\t(enter in M)\n    double saltion_diameter_in;    // inside salt ion diameter\t(positive and negative ions assumed to have same diameter at this point)\n    double saltion_diameter_out;  // outside salt ion diameter\t(positive and negative ions assumed to have same diameter at this point)\n    double real_T;            // temperature at which the system of ions is\n    double nanoparticle_bare_charge; // bare charge of the NP\n\n    // Simulation related variables\n    int total_gridpoints;        // total number of grid points that discretize the continuous interface\n    double Q;            // thermostat mass required to generate canonical ensemble\n    double fake_T;            // fake temperature useful for Car Parrinello dynamics\n    double fake_Q;            // fake thermostat mass required to generate canonical ensemble for fake degrees\n    unsigned int chain_length_real;\n    unsigned int chain_length_fake;\n    double box_radius;        // simulation box size, measured as radius in case of a sphere\n    double bin_width_R;        // width of the bins (in R direction) used to compute density profiles\n    double bin_width_Z;        // width of the bins (in Z direction) used to compute density profiles\n    CONTROL fmdremote;        // remote control for fmd\n    CONTROL cpmdremote;        // remote control for cpmd\n\n\n    // Different parts of the system\n    //INTERFACE nanoparticle;        // interface(s)\n    vector<PARTICLE> counterion;    // counterions\n    vector<PARTICLE> saltion_in;    // salt ions inside\n    vector<PARTICLE> saltion_out;    // salt ions outside\n    vector<PARTICLE> ion;        // all ions in the system\n    vector<VERTEX> s;        // all vertices\n\n    // Analysis\n    string np_shape; // np shape\n    NanoParticle *nanoParticle;\n    VECTOR3D np_pos(0, 0, 0);\n\n    // Get input values from the user\n    options_description desc(\"Usage:\\nrandom_mesh <options>\");\n    desc.add_options()\n            (\"help,h\", \"print usage message\")\n            (\"radius,a\", value<double>(&radius)->default_value(2.6775),\n             \"sphere radius\")                // enter in nanometers\n            (\"epsilon_in,e\", value<double>(&ein)->default_value(78.5), \"dielectric const inside\")\n            (\"epsilon_out,E\", value<double>(&eout)->default_value(78.5), \"dielectric const outside\")\n            (\"counterion_valency,v\", value<int>(&counterion_valency)->default_value(1), \"counterion valency\")\n            (\"nanoparticle_charge,V\", value<double>(&nanoparticle_bare_charge)->default_value(-60),\n             \"nanoparticle charge\")\n            (\"salt_valency_in,z\", value<int>(&salt_valency_in)->default_value(1), \"salt valency inside\")\n            (\"salt_valency_out,Z\", value<int>(&salt_valency_out)->default_value(1), \"salt valency outside\")\n            (\"salt_conc_in,c\", value<double>(&salt_conc_in)->default_value(0.0), \"salt concentration inside\")\n            (\"salt_conc_out,C\", value<double>(&salt_conc_out)->default_value(0.0), \"salt concentration outside\")\n            (\"counterion_diameter,x\", value<double>(&counterion_diameter)->default_value(0.357),\n             \"counterion diameter\")            // enter in nanometers\n            (\"saltion_diameter_in,d\", value<double>(&saltion_diameter_in)->default_value(0.357),\n             \"salt ion diameter inside\")        // enter in nanometers\n            (\"saltion_diameter_out,D\", value<double>(&saltion_diameter_out)->default_value(0.357),\n             \"salt ion diameter outside\")        // enter in nanometers\n            (\"total_gridpoints,g\", value<int>(&total_gridpoints)->default_value(132), \"gridpoints\")\n            (\"thermostat_mass,Q\", value<double>(&Q)->default_value(1.0), \"thermostat mass\")\n            (\"chain_length_real,L\", value<unsigned int>(&chain_length_real)->default_value(5),\n             \"chain length for real system: enter L+1 if you want L thermostats\")\n            (\"fake_temperature,k\", value<double>(&fake_T)->default_value(0.01), \"fake temperature\")\n            (\"fake_thermostat_mass,q\", value<double>(&fake_Q)->default_value(1.0), \"fake thermostat mass\")\n            (\"chain_length_fake,l\", value<unsigned int>(&chain_length_fake)->default_value(5),\n             \"chain length for fake system: enter L+1 if you want L thermostats\")\n            (\"box_radius,b\", value<double>(&box_radius)->default_value(14.28),\n             \"simulation box radius\")        // enter in nanometers\n            (\"bin_width_R,R\", value<double>(&bin_width_R)->default_value(0.1), \"bin width R\")\n            (\"bin_width_Z,B\", value<double>(&bin_width_Z)->default_value(0.2), \"bin width Z\")\n            (\"anneal_fmd,A\", value<char>(&fmdremote.anneal)->default_value('n'), \"anneal in fmd on?\")\n            (\"fmd_fake_mass,m\", value<double>(&fmdremote.fakemass)->default_value(1.0), \"fmd fake mass\")\n            (\"cpmd_fake_mass,M\", value<double>(&cpmdremote.fakemass)->default_value(1.0), \"cpmd fake mass\")\n            (\"fmd_timestep,t\", value<double>(&fmdremote.timestep)->default_value(0.001), \"time step used in fmd\")\n            (\"cpmd_timestep,T\", value<double>(&cpmdremote.timestep)->default_value(0.001), \"time step used in cpmd\")\n            (\"fmd_steps,s\", value<int>(&fmdremote.steps)->default_value(10000), \"steps used in fmd\")\n            (\"cpmd_steps,S\", value<int>(&cpmdremote.steps)->default_value(50000), \"steps used in cpmd\")\n            (\"fmd_eqm,p\", value<int>(&fmdremote.hiteqm)->default_value(100), \"production begin (fmd)\")\n            (\"cpmd_eqm,P\", value<int>(&cpmdremote.hiteqm)->default_value(10000), \"production begin (cpmd)\")\n            (\"fmd_freq,f\", value<int>(&fmdremote.freq)->default_value(10), \"sample frequency (fmd)\")\n            (\"cpmd_freq,F\", value<int>(&cpmdremote.freq)->default_value(100), \"sample frequency (cpmd)\")\n            (\"fmd_verify,y\", value<int>(&fmdremote.verify)->default_value(0), \"verify (fmd)\")\n            (\"cpmd_verify,Y\", value<int>(&cpmdremote.verify)->default_value(10000), \"verify (cpmd)\")\n            (\"cpmd_writedata,U\", value<int>(&cpmdremote.writedata)->default_value(1000), \"write data files\")\n            (\"cpmd_extra_compute,X\", value<int>(&cpmdremote.extra_compute)->default_value(1000),\n             \"compute additional (cpmd)\")\n            (\"cpmd_writedensity,W\", value<int>(&cpmdremote.writedensity)->default_value(10000), \"write density files\")\n            (\"np_shape,G\", value<string>(&np_shape)->default_value(\"Sphere\"), \"nanoparticle shape\")\n            (\"verbose,I\", value<bool>(&cpmdremote.verbose)->default_value(true),\n             \"verbose true: provides detailed output\");\n\n    variables_map vm;\n    store(parse_command_line(argc, argv, desc), vm);\n    notify(vm);\n    if (vm.count(\"help\")) {\n        if (world.rank() == 0)\n            std::cout << desc << \"\\n\";\n        return 0;\n    }\n\n    if (world.rank() == 0)\n        cout << \"\\nProgram starts\\n\";\n\n    int numOfNodes = world.size();\n    if (world.rank() == 0) {\n#pragma omp parallel default(shared)\n        {\n            if (omp_get_thread_num() == 0) {\n                printf(\"The app comes with MPI and OpenMP (Hybrid) parallelization)\\n\");\n                printf(\"Number of MPI processes used %d\\n\", numOfNodes);\n                printf(\"Number of OpenMP threads per MPI process %d\\n\", omp_get_num_threads());\n                printf(\"Make sure that number of grid points / ions is greater than %d\\n\",\n                       omp_get_num_threads() * numOfNodes);\n            }\n        }\n    }\n\n    //serve different NP for density bin\n    if (np_shape.compare(\"Sphere\") == 0) {\n        //Sphere\n        vector<BinShell> bin_pos, bin_neg;\n        vector<double> sample_density_pos, sample_density_neg;\n        NanoParticleSphere np(\"Sphere\", bin_pos, bin_neg, bin_width_R, ion, sample_density_pos, sample_density_neg, 0,\n                              0, cpmdremote,\n                              np_pos, radius / unitlength, ein, eout,\n                              nanoparticle_bare_charge);\n\n        nanoParticle = &np;\n\n    } else {\n        //disk\n\n        vector<vector<double> > density_pos, density_neg;\n        vector<vector<BinRing> > bin_disk_pos, bin_disk_neg;\n        NanoParticleDisk np(\"Disk\", bin_disk_pos, bin_disk_neg, bin_width_R, bin_width_Z, ion, density_pos, density_neg,\n                            0, 0, cpmdremote,\n                            np_pos, radius / unitlength, ein, eout,\n                            nanoparticle_bare_charge);\n\n        nanoParticle = &np;\n\n    }\n\n    // Set up the system\n    real_T = 1;\n\n    // set temperature\n    // make interface\n    nanoParticle->set_up(salt_conc_in, salt_conc_out, salt_valency_in, salt_valency_out, total_gridpoints,\n                         box_radius / unitlength);    // set up properties inside and outside the interface\n\n    // If running a standard simulation (charged particle and/or with salt) populate the ions:\n    if (abs(nanoparticle_bare_charge) > 0)\n        nanoParticle->put_counterions(counterion, counterion_valency, counterion_diameter, ion);                    // put counterions\tNote: ion contains all ions\n    if (salt_conc_in > 0)\n        nanoParticle->put_saltions_inside(saltion_in, salt_valency_in, salt_conc_in, saltion_diameter_in, ion);                // put salt ions inside\n    if (salt_conc_out > 0)\n        nanoParticle->put_saltions_outside(saltion_out, salt_valency_out, salt_conc_out, saltion_diameter_out, ion);            // put salt ions outside\n\n    //  If the charge is set to zero (for testing), insert test two test ions at chosen positions:\n    /*if (nanoparticle_bare_charge == 0)\n    {\n        ion.push_back(PARTICLE(int(ion.size()) + 1, counterion_diameter, counterion_valency, counterion_valency * 1.0, 1.0, eout, VECTOR3D(5 / unitlength,0,0)));\n        ion.push_back(PARTICLE(int(ion.size()) + 1, counterion_diameter, counterion_valency, counterion_valency * 1.0, 1.0, eout, VECTOR3D(6 / unitlength,0,0)));\n    }*/\n\n    nanoParticle->discretize(s,radius / unitlength);                                // discretize interface\n\n    // if dielectric environment inside and outside NP are different, NPs get polarized\n    if (nanoParticle->ein == nanoParticle->eout)\n        nanoParticle->POLARIZED = false;\n    else\n        nanoParticle->POLARIZED = true;\n\n    if (world.rank() == 0) {\n        if (nanoParticle->POLARIZED)\n            cout << \"NP is polarized \" << endl;\n        else\n            cout << \"NP is not polarized \" << endl;\n    }\n\n    nanoParticle->RANDOMIZE_ION_FEATURES = false;\n\n    // NOTE: sizing the arrays employed in precalculate functions\n    for (unsigned int k = 0; k < s.size(); k++) {\n        s[k].presumgwEw.resize(s.size());\n        s[k].presumgEwEq.resize(s.size());\n        s[k].presumgEwEw.resize(s.size());\n        s[k].presumfwEw.resize(s.size());\n        s[k].presumfEwEq.resize(s.size());\n        s[k].presumhEqEw.resize(s.size());\n    }\n\n    // could only do precalculate if CPMD\n    if (nanoParticle->POLARIZED)\n        precalculate(s, nanoParticle);                        // precalculate\n\n    for (unsigned int k = 0; k < s.size(); k++)               // get polar coordinates for the vertices\n        s[k].get_polar();\n\n    //make bins\n    nanoParticle->make_bins();\n\n    if (world.rank() == 0) {\n        // output to screen the parameters of the problem\n        cout << \"\\n\";\n        if (cpmdremote.verbose)\n            cout << \"Reduced units: scalefactor entering in Coloumb interaction is \" << scalefactor << endl;\n        cout << \"Units : length (cms) \" << unitlength * pow(10.0, -7) << \" | \" << \"energy(ergs) \" << unitenergy\n             << \" | \" << \"mass(g) \" << unitmass << \" | \" << \"time(s) \" << unittime << endl;\n        cout << \"Radius of the dielectric sphere (interface) \" << nanoParticle->radius << endl;\n        cout << \"Nanoparticle charge \" << nanoParticle->bare_charge << endl;\n        cout << \"Permittivity inside \" << nanoParticle->ein << endl;\n        cout << \"Permittivity outside \" << nanoParticle->eout << endl;\n        if (cpmdremote.verbose)\n            cout << \"Contrast strength \"\n                 << 2 * (nanoParticle->eout - nanoParticle->ein) / (nanoParticle->eout + nanoParticle->ein)\n                 << endl;\n        cout << \"Counterion valency \" << counterion_valency << endl;\n        if (cpmdremote.verbose) {\n            cout << \"Salt ion valency inside \" << salt_valency_in << endl;\n            cout << \"Salt ion valency outside \" << salt_valency_out << endl;\n            cout << \"Counterion diameter \" << counterion_diameter / unitlength << endl;\n            cout << \"Salt ion diameter inside \" << saltion_diameter_in / unitlength << endl;\n            cout << \"Salt ion diameter outside \" << saltion_diameter_out / unitlength << endl;\n            cout << \"Salt concentration inside \" << salt_conc_in << endl;\n            cout << \"Salt concentration outside \" << salt_conc_out << endl;\n            cout << \"Debye length inside \" << nanoParticle->inv_kappa_in << endl;\n            cout << \"Debye length outside \" << nanoParticle->inv_kappa_out << endl;\n            cout << \"Mean separation inside \" << nanoParticle->mean_sep_in << endl;\n            cout << \"Mean separation outside \" << nanoParticle->mean_sep_out << endl;\n        }\n        cout << \"Simulation box (spherical) radius \" << nanoParticle->box_radius << endl;\n        cout << \"Number of counterions \" << counterion.size() << endl;\n        if (cpmdremote.verbose) {\n            cout << \"Number of salt ions inside \" << saltion_in.size() << endl;\n            cout << \"Number of salt ions outside \" << saltion_out.size() << endl;\n            cout << \"Number of points discretizing the interface \" << s.size() << endl;\n            //cout << \"Binning width (uniform) \" << bin_disk[0][0].width_R << endl;\n            nanoParticle->printBinSize();\n        }\n    }\n    // write to files\n    // initial configuration\n    ofstream initial_configuration(\"outfiles/initialconfig.dat\");\n    if (world.rank() == 0)\n        for (unsigned int i = 0; i < ion.size(); i++)\n            initial_configuration << \"ion\" << setw(5) << ion[i].id << setw(15) << \"charge\" << setw(5) << ion[i].q\n                                  << setw(15) << \"position\" << setw(15) << ion[i].posvec << endl;\n    initial_configuration.close();\n\n    // initial density\n    nanoParticle->compute_initial_density_profile();\n\n    // some calculations before simulation begins\n    if (world.rank() == 0)\n        cout << \"Total charge inside the sphere \" << nanoParticle->total_charge_inside(ion) << endl;\n\n    // NEW NOTE : resizing the member arrays Gion and gradGion to store dynamic precalculations in fmd and cpmd force routines\n    for (unsigned int k = 0; k < s.size(); k++) {\n        s[k].Gion.resize(ion.size());\n        s[k].gradGion.resize(ion.size());\n    }\n\n    //MPI Boundary calculation for ions\n    unsigned int rangeIons = ion.size() / world.size() + 1.5;\n    lowerBoundIons = world.rank() * rangeIons;\n    upperBoundIons = (world.rank() + 1) * rangeIons - 1;\n    extraElementsIons = world.size() * rangeIons - ion.size();\n    sizFVecIons = upperBoundIons - lowerBoundIons + 1;\n    if (world.rank() == world.size() - 1) {\n        upperBoundIons = ion.size() - 1;\n        sizFVecIons = upperBoundIons - lowerBoundIons + 1 + extraElementsIons;\n    }\n    if (world.size() == 1) {\n        lowerBoundIons = 0;\n        upperBoundIons = ion.size() - 1;\n    }\n\n    //MPI Boundary calculation for meshPoints\n    unsigned int rangeMesh = s.size() / world.size() + 1.5;\n    lowerBoundMesh = world.rank() * rangeMesh;\n    upperBoundMesh = (world.rank() + 1) * rangeMesh - 1;\n    extraElementsMesh = world.size() * rangeMesh - s.size();\n    sizFVecMesh = upperBoundMesh - lowerBoundMesh + 1;\n    if (world.rank() == world.size() - 1) {\n        upperBoundMesh = s.size() - 1;\n        sizFVecMesh = upperBoundMesh - lowerBoundMesh + 1 + extraElementsMesh;\n    }\n    if (world.size() == 1) {\n        lowerBoundMesh = 0;\n        upperBoundMesh = s.size() - 1;\n    }\n\n    for (unsigned int k = 0; k < s.size(); k++) {\n        s[k].w = 0.0;                                // Initialize fake degree value\t\t(unconstrained)\n        s[k].wmean = 0.0;\n    }\n\n    // Fictitious molecular dynamics\n    if (nanoParticle->POLARIZED) {\n        if (world.rank() == 0)\n            cout << \"Polarized charges detected; simulation will proceed using dynamical optimization framework (CPMD)\"\n                 << endl;\n        fmd(s, ion, nanoParticle, fmdremote, cpmdremote);\n    } else if (world.rank() == 0)\n        cout << \"no induced charges; simulation will proceed using simple MD\" << endl;\n\n    ofstream induced_density(\"outfiles/induced_density.dat\");\n    if (world.rank() == 0)\n        // result of fmd\n        for (unsigned int k = 0; k < s.size(); k++)\n            induced_density << k + 1 << setw(15) << s[k].theta << setw(15) << s[k].phi << setw(15) << s[k].w << setw(15)\n                            << s[k].wmean << endl;\n\n    induced_density.close();\n    // prepare for cpmd : make real and fake baths\n\n    vector<THERMOSTAT> real_bath;\n    if (chain_length_real == 1)\n        real_bath.push_back(THERMOSTAT(0, real_T, 3 * ion.size(), 0.0, 0, 0));\n    else {\n        real_bath.push_back(THERMOSTAT(Q, real_T, 3 * ion.size(), 0, 0, 0));\n        while (real_bath.size() != chain_length_real - 1)\n            real_bath.push_back(THERMOSTAT(Q / (3 * ion.size()), real_T, 1, 0, 0, 0));\n        real_bath.push_back(THERMOSTAT(0, real_T, 3 * ion.size(), 0.0, 0,\n                                       0));            // finally, the coding trick: dummy bath (dummy bath always has zero mass)\n    }\n\n    vector<THERMOSTAT> fake_bath;\n    if (!nanoParticle->POLARIZED)\n        fake_T = 0;\n//K is used for thermostat fake_T is k\n    if (chain_length_fake == 1)\n        fake_bath.push_back(THERMOSTAT(0, fake_T, s.size(), 0.0, 0, 0));\n    else {\n        fake_bath.push_back(THERMOSTAT(fake_Q, fake_T, s.size(), 0, 0, 0));\n        while (fake_bath.size() != chain_length_fake - 1)\n            fake_bath.push_back(THERMOSTAT(fake_Q / s.size(), fake_T, 1, 0, 0, 0));\n        fake_bath.push_back(THERMOSTAT(0, fake_T, s.size(), 0.0, 0,\n                                       0));            // finally, the coding trick: dummy bath (dummy bath always has zero mass)\n    }\n    if (world.rank() == 0 && cpmdremote.verbose) {\n        cout << \"Number of chains for real system\" << setw(3) << real_bath.size() - 1 << endl;\n        cout << \"Number of chains for fake system\" << setw(3) << fake_bath.size() - 1 << endl;\n    }\n\n    // Car-Parrinello Molecular Dynamics\n    cpmd(ion, s, nanoParticle, real_bath, fake_bath, fmdremote, cpmdremote);\n\n    if (world.rank() == 0) {\n        // Post simulation analysis (useful for short runs, but performed otherwise too)\n        if (cpmdremote.verbose)\n            cout << \"MD trust factor R (should be < 0.05) is \" << compute_MD_trust_factor_R(cpmdremote.hiteqm) << endl;\n        if (nanoParticle->POLARIZED && cpmdremote.verbose)\n            cout << \"MD trust factor RV (should be < 0.15) is \" << compute_MD_trust_factor_R_v(cpmdremote.hiteqm)\n                 << endl;\n        //auto_correlation_function();\n        cout << \"Program ends\" << endl;\n        cout << endl;\n    }\n    return 0;\n}\n// End of main\n", "meta": {"hexsha": "f8c2831043f09137583c5eab058a2cec78ab0b74", "size": 23536, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "kadupitiya/np-electrostatics-lab", "max_stars_repo_head_hexsha": "bffef8d1f4b7d0cc3d46a240346408691902f31c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "kadupitiya/np-electrostatics-lab", "max_issues_repo_head_hexsha": "bffef8d1f4b7d0cc3d46a240346408691902f31c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "kadupitiya/np-electrostatics-lab", "max_forks_repo_head_hexsha": "bffef8d1f4b7d0cc3d46a240346408691902f31c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.3788235294, "max_line_length": 397, "alphanum_fraction": 0.6304384772, "num_tokens": 6210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4302656442689631}}
{"text": "/**\n * @file propagator.h\n * @brief NPDE homework NonLinSchroedingerEquation code\n * @author Oliver Rietmann\n * @date 04.05.2020\n * @copyright Developed at ETH Zurich\n */\n\n#include \"propagator.h\"\n\n#include <cmath>\n#include <complex>\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <Eigen/SparseLU>\n\nnamespace NonLinSchroedingerEquation {\n\n// KineticPropagator\n/* SAM_LISTING_BEGIN_1 */\nKineticPropagator::KineticPropagator(const SparseMatrixXd &A,\n                                     const SparseMatrixXcd &M, double tau) {\n  //====================\n  // Your code goes here\n  //====================\n}\n\nEigen::VectorXcd KineticPropagator::operator()(\n    const Eigen::VectorXcd &mu) const {\n  //====================\n  // Your code goes here\n  // Replace mu by its value after a timestep tau\n  return mu;\n  //====================\n}\n/* SAM_LISTING_END_1 */\n\n// InteractionPropagator\n/* SAM_LISTING_BEGIN_2 */\nInteractionPropagator::InteractionPropagator(double tau) {\n  //====================\n  // Your code goes here\n  //====================\n}\n\nEigen::VectorXcd InteractionPropagator::operator()(\n    const Eigen::VectorXcd &mu) const {\n  //====================\n  // Your code goes here\n  // Replace mu by its value after a timestep tau\n  return mu;\n  //====================\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\n//====================\n// Your code goes here\n// Change this dummy implementation of the constructor:\nSplitStepPropagator::SplitStepPropagator(const SparseMatrixXd &A,\n                                         const SparseMatrixXcd &M, double tau) {\n}\n//====================\n\nEigen::VectorXcd SplitStepPropagator::operator()(\n    const Eigen::VectorXcd &mu) const {\n  Eigen::VectorXcd nu(mu.size());\n  //====================\n  // Your code goes here\n  // Implement the Strang splitting\n  //====================\n  return nu;\n}\n/* SAM_LISTING_END_3 */\n\n}  // namespace NonLinSchroedingerEquation\n", "meta": {"hexsha": "bfcd651feddce99621a78ac5cf3f361b43127562", "size": 1932, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/NonLinSchroedingerEquation/templates/propagator.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/NonLinSchroedingerEquation/templates/propagator.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/NonLinSchroedingerEquation/templates/propagator.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7692307692, "max_line_length": 80, "alphanum_fraction": 0.5957556936, "num_tokens": 477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.4302656442689631}}
{"text": "// this file mainly refers to libint2's example\n\n#include \"jlcxx/jlcxx.hpp\"\n#include <libint2.hpp>\n#include <iostream>\n#include <thread>\n#include <mutex>\n#include <Eigen/Dense>\n\nusing Matrix = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\nstatic std::mutex mtx;\n\nsize_t nbasis(const std::vector<libint2::Shell> &shells)\n{\n    size_t n = 0;\n    for (const auto &shell : shells)\n        n += shell.size();\n    return n;\n}\n\nsize_t max_nprim(const std::vector<libint2::Shell> &shells)\n{\n    size_t n = 0;\n    for (auto shell : shells)\n        n = std::max(shell.nprim(), n);\n    return n;\n}\n\nint max_l(const std::vector<libint2::Shell> &shells)\n{\n    int l = 0;\n    for (auto shell : shells)\n        for (auto c : shell.contr)\n            l = std::max(c.l, l);\n    return l;\n}\n\nstd::vector<libint2::Shell> construct_shells(int Nshell, int *l, double *alpha, double *coeff, double *cart)\n{\n    std::vector<libint2::Shell> shells;\n    for (int i = 0; i < Nshell; ++i)\n    {\n        double *a = alpha + 3 * i;\n        double *d = coeff + 3 * i;\n        double *r = cart + 3 * i;\n        shells.push_back({{a[0], a[1], a[2]},\n                          {{l[i], false, {d[0], d[1], d[2]}}},\n                          {{r[0], r[1], r[2]}}});\n    }\n    return shells;\n}\n\nstd::vector<size_t> map_shell_to_basis_function(const std::vector<libint2::Shell>& shells) {\n  std::vector<size_t> result;\n  result.reserve(shells.size());\n\n  size_t n = 0;\n  for (auto shell: shells) {\n    result.push_back(n);\n    n += shell.size();\n  }\n\n  return result;\n}\n\n\n\nvoid Ve(double *ve, int Nshell, int *l, double *alpha, double *d, double *R) {\n  const auto shells = construct_shells(Nshell, l, alpha, d, R);\n  const auto n = nbasis(shells);\n  auto index = [&n](int i, int j, int k, int l) {\n        return n * (n * (n * l + k) + j) + i;\n  };\n  std::memset(ve, 0, n*n*n*n*sizeof(double));\n  libint2::Engine engine(libint2::Operator::coulomb, max_nprim(shells), max_l(shells), 0);\n\n  auto shell2bf = map_shell_to_basis_function(shells);\n\n  const auto& buf = engine.results();\n\n  for(auto s1=0; s1!=shells.size(); ++s1) {\n\n    auto bf1_first = shell2bf[s1];\n    auto n1 = shells[s1].size();\n\n    for(auto s2=0; s2!=shells.size(); ++s2) {\n\n      auto bf2_first = shell2bf[s2];\n      auto n2 = shells[s2].size();\n\n      for(auto s3=0; s3!=shells.size(); ++s3) {\n\n        auto bf3_first = shell2bf[s3];\n        auto n3 = shells[s3].size();\n\n        for(auto s4=0; s4!=shells.size(); ++s4) {\n\n          auto bf4_first = shell2bf[s4];\n          auto n4 = shells[s4].size();\n\n          engine.compute(shells[s1], shells[s2], shells[s3], shells[s4]);\n          const auto* buf_1234 = buf[0];\n          if (buf_1234 == nullptr)\n            continue;\n          for(auto f1=0, f1234=0; f1!=n1; ++f1) {\n            const auto bf1 = f1 + bf1_first;\n            for(auto f2=0; f2!=n2; ++f2) {\n              const auto bf2 = f2 + bf2_first;\n              for(auto f3=0; f3!=n3; ++f3) {\n                const auto bf3 = f3 + bf3_first;\n                for(auto f4=0; f4!=n4; ++f4, ++f1234) {\n                  const auto bf4 = f4 + bf4_first;\n                  ve[index(bf1, bf4, bf3, bf2)] = buf_1234[f1234];\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\n\n\n// copy from libint2's example\nvoid compute_2body_fock(double *veff, double* rho, int Nshell, int *l, double *alpha, double *d, double *R) {\n  const auto shells = construct_shells(Nshell, l, alpha, d, R);\n  const auto n = nbasis(shells);\n  Matrix G = Matrix::Zero(n,n);\n  Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>> D(rho, n, n);\n\n  // construct the 2-electron repulsion integrals engine\n  libint2::Engine engine(libint2::Operator::coulomb, max_nprim(shells), max_l(shells), 0);\n\n  auto shell2bf = map_shell_to_basis_function(shells);\n\n  const auto& buf = engine.results();\n\n  // The problem with the simple Fock builder is that permutational symmetries of the Fock,\n  // density, and two-electron integrals are not taken into account to reduce the cost.\n  // To make the simple Fock builder efficient we must rearrange our computation.\n  // The most expensive step in Fock matrix construction is the evaluation of 2-e integrals;\n  // hence we must minimize the number of computed integrals by taking advantage of their permutational\n  // symmetry. Due to the multiplicative and Hermitian nature of the Coulomb kernel (and realness\n  // of the Gaussians) the permutational symmetry of the 2-e ints is given by the following relations:\n  //\n  // (12|34) = (21|34) = (12|43) = (21|43) = (34|12) = (43|12) = (34|21) = (43|21)\n  //\n  // (here we use chemists' notation for the integrals, i.e in (ab|cd) a and b correspond to\n  // electron 1, and c and d -- to electron 2).\n  //\n  // It is easy to verify that the following set of nested loops produces a permutationally-unique\n  // set of integrals:\n  // foreach a = 0 .. n-1\n  //   foreach b = 0 .. a\n  //     foreach c = 0 .. a\n  //       foreach d = 0 .. (a == c ? b : c)\n  //         compute (ab|cd)\n  //\n  // The only complication is that we must compute integrals over shells. But it's not that complicated ...\n  //\n  // The real trick is figuring out to which matrix elements of the Fock matrix each permutationally-unique\n  // (ab|cd) contributes. STOP READING and try to figure it out yourself. (to check your answer see below)\n\n  // loop over permutationally-unique set of shells\n  for(auto s1=0; s1!=shells.size(); ++s1) {\n\n    auto bf1_first = shell2bf[s1]; // first basis function in this shell\n    auto n1 = shells[s1].size();   // number of basis functions in this shell\n\n    for(auto s2=0; s2<=s1; ++s2) {\n\n      auto bf2_first = shell2bf[s2];\n      auto n2 = shells[s2].size();\n\n      for(auto s3=0; s3<=s1; ++s3) {\n\n        auto bf3_first = shell2bf[s3];\n        auto n3 = shells[s3].size();\n\n        const auto s4_max = (s1 == s3) ? s2 : s3;\n        for(auto s4=0; s4<=s4_max; ++s4) {\n\n          auto bf4_first = shell2bf[s4];\n          auto n4 = shells[s4].size();\n\n          // compute the permutational degeneracy (i.e. # of equivalents) of the given shell set\n          auto s12_deg = (s1 == s2) ? 1.0 : 2.0;\n          auto s34_deg = (s3 == s4) ? 1.0 : 2.0;\n          auto s12_34_deg = (s1 == s3) ? (s2 == s4 ? 1.0 : 2.0) : 2.0;\n          auto s1234_deg = s12_deg * s34_deg * s12_34_deg;\n\n          engine.compute(shells[s1], shells[s2], shells[s3], shells[s4]);\n          const auto* buf_1234 = buf[0];\n          if (buf_1234 == nullptr)\n            continue; // if all integrals screened out, skip to next quartet\n\n          // ANSWER\n          // 1) each shell set of integrals contributes up to 6 shell sets of the Fock matrix:\n          //    F(a,b) += (ab|cd) * D(c,d)\n          //    F(c,d) += (ab|cd) * D(a,b)\n          //    F(b,d) -= 1/4 * (ab|cd) * D(a,c)\n          //    F(b,c) -= 1/4 * (ab|cd) * D(a,d)\n          //    F(a,c) -= 1/4 * (ab|cd) * D(b,d)\n          //    F(a,d) -= 1/4 * (ab|cd) * D(b,c)\n          // 2) each permutationally-unique integral (shell set) must be scaled by its degeneracy,\n          //    i.e. the number of the integrals/sets equivalent to it\n          // 3) the end result must be symmetrized\n          for(auto f1=0, f1234=0; f1!=n1; ++f1) {\n            const auto bf1 = f1 + bf1_first;\n            for(auto f2=0; f2!=n2; ++f2) {\n              const auto bf2 = f2 + bf2_first;\n              for(auto f3=0; f3!=n3; ++f3) {\n                const auto bf3 = f3 + bf3_first;\n                for(auto f4=0; f4!=n4; ++f4, ++f1234) {\n                  const auto bf4 = f4 + bf4_first;\n\n                  const auto value = buf_1234[f1234];\n\n                  const auto value_scal_by_deg = value * s1234_deg;\n\n                  G(bf1,bf2) += D(bf3,bf4) * value_scal_by_deg;\n                  G(bf3,bf4) += D(bf1,bf2) * value_scal_by_deg;\n                  G(bf1,bf3) -= 0.25 * D(bf2,bf4) * value_scal_by_deg;\n                  G(bf2,bf4) -= 0.25 * D(bf1,bf3) * value_scal_by_deg;\n                  G(bf1,bf4) -= 0.25 * D(bf2,bf3) * value_scal_by_deg;\n                  G(bf2,bf3) -= 0.25 * D(bf1,bf4) * value_scal_by_deg;\n                }\n              }\n            }\n          }\n\n        }\n      }\n    }\n  }\n\n  // symmetrize the result\n  for(int i=0; i<n; ++i)\n  {\n    for(int j=0; j<n; ++j)\n    {\n      veff[i*n + j] = (G(i,j) + G(j,i))/4.;\n    }\n  }\n}\n\nJLCXX_MODULE define_julia_module(jlcxx::Module &mod)\n{\n    mod.method(\"initialize\", [](){libint2::initialize();});\n    mod.method(\"Ve\", &Ve);\n    mod.method(\"Veff\", &compute_2body_fock);\n}", "meta": {"hexsha": "23367914e17125fb34d2b83cd018ed8d7128b77f", "size": 8556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/coulomb.cpp", "max_stars_repo_name": "0382/HartreeFock.jl", "max_stars_repo_head_hexsha": "1cf2c3eb52c84a23ada62196ae5e8739d02027a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deps/coulomb.cpp", "max_issues_repo_name": "0382/HartreeFock.jl", "max_issues_repo_head_hexsha": "1cf2c3eb52c84a23ada62196ae5e8739d02027a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "deps/coulomb.cpp", "max_forks_repo_name": "0382/HartreeFock.jl", "max_forks_repo_head_hexsha": "1cf2c3eb52c84a23ada62196ae5e8739d02027a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5529411765, "max_line_length": 109, "alphanum_fraction": 0.5600748013, "num_tokens": 2742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.43026563760551867}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_BESSEL_FUNCTIONS_SCALAR_Y0_HPP_INCLUDED\n#define NT2_BESSEL_FUNCTIONS_SCALAR_Y0_HPP_INCLUDED\n\n#include <nt2/bessel/functions/y0.hpp>\n#include <nt2/include/constants/digits.hpp>\n#include <nt2/include/constants/real.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/oneminus.hpp>\n#include <nt2/include/functions/scalar/sqr.hpp>\n#include <nt2/include/functions/scalar/sqrt.hpp>\n#include <nt2/include/functions/scalar/log.hpp>\n#include <nt2/include/functions/scalar/j0.hpp>\n#include <nt2/include/functions/scalar/rec.hpp>\n#include <nt2/include/functions/scalar/sin.hpp>\n#include <boost/simd/sdk/math.hpp>\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::y0_, tag::cpu_\n                            , (A0)\n                            , (scalar_< arithmetic_<A0> >)\n                            )\n  {\n\n    typedef typename boost::dispatch::meta::as_floating<A0>::type result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      return nt2::y0(result_type(a0));\n    }\n  };\n} }\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is double\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::y0_, tag::cpu_\n                            , (A0)\n                            , (scalar_< double_<A0> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      if (is_ltz(a0)||is_nan(a0)) return Nan<result_type>();\n      if (is_inf(a0)) return Zero<result_type>();\n      if (is_eqz(a0)) return Minf<result_type>();\n#if defined(BOOST_SIMD_HAS__Y0)\n      return ::_y0(a0);\n#elif defined(BOOST_SIMD_HAS_Y0)\n      return ::y0(a0);\n#else\n#error y0 not supported\n#endif\n    }\n  };\n} }\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is float\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::y0_, tag::cpu_\n                            , (A0)\n                            , (scalar_< single_<A0> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename meta::scalar_of<A0>::type stype;\n      if (is_ltz(a0)||is_nan(a0)) return Nan<result_type>();\n      if (is_inf(a0)) return Zero<result_type>();\n      if (is_eqz(a0)) return Minf<result_type>();\n      if (a0 <= Two<A0>())\n      {\n        A0 z = sqr(a0);\n        A0 p2 = (z-single_constant<A0, 0x3edd4b3a>())*\n          horner< NT2_HORNER_COEFF_T(stype, 5,\n                                     (0x33cb0920,\n                                      0xb71ded71,\n                                      0x3a0c1a3e,\n                                      0xbc81c8f4,\n                                      0x3e2edb4f\n                                       ) ) > (z);\n        return p2+single_constant<A0, 0x3f22f983>()*nt2::log(a0)*nt2::j0(a0);\n      }\n      A0 q = rec(a0);\n      A0 w = nt2::sqrt(q);\n      A0 p3 = w *\n        horner< NT2_HORNER_COEFF_T(stype, 8,\n                                   (0xbd8c100e,\n                                    0x3e3ef887,\n                                    0xbe5ba616,\n                                    0x3df54214,\n                                    0xbb69539e,\n                                    0xbd4b8bc1,\n                                    0xb6612dc2,\n                                    0x3f4c422a\n                                     ) ) > (q);\n       w = sqr(q);\n       A0 xn =  q*\n         horner< NT2_HORNER_COEFF_T(stype, 8,\n                                    (0x4201aee0,\n                                     0xc2113945,\n                                     0x418c7f6a,\n                                     0xc09f3306,\n                                     0x3f8040aa,\n                                     0xbe46a57f,\n                                     0x3d84ed6e,\n                                     0xbdffff97\n                                      ) ) > (w)-Pio_4<A0>();\n      return p3*nt2::sin(xn+a0);\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "2cd4ba15501eca75813a979ed39757f407633686", "size": 4903, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/bessel/include/nt2/bessel/functions/scalar/y0.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/bessel/include/nt2/bessel/functions/scalar/y0.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/bessel/include/nt2/bessel/functions/scalar/y0.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.273381295, "max_line_length": 80, "alphanum_fraction": 0.4238221497, "num_tokens": 1122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4302656376055186}}
{"text": "/* Copyright (C) 5/23/18 Julian Stobbe - All Rights Reserved\n * You may use, distribute and modify this code under the\n * terms of the MIT license.\n *\n * You should have received a copy of the MIT license with\n * this file.\n */\n\n#ifndef SRC_BLACKSCHOLES_NETWORK_HPP_\n#define SRC_BLACKSCHOLES_NETWORK_HPP_\n\n#define USE_SPARSE_INTERNAL 1\n\n\n#include <stdexcept>\n#include <algorithm>\n\n#include \"easylogging++.h\"\n// Tina's Random Number Generator\n#include \"trng/yarn2.hpp\"\n#include \"trng/uniform01_dist.hpp\"\n#include \"trng/lognormal_dist.hpp\"\n#include \"trng/correlated_normal_dist.hpp\"\n#include \"Eigen/Dense\"\n#include \"Eigen/Sparse\"\n#include <Eigen/SparseLU>\n\n#ifdef USE_MPI\n#include <boost/mpi.hpp>\n#endif\n\n#include <boost/serialization/vector.hpp>\n#include <boost/serialization/optional.hpp>\n\n\n#include \"ValuationConfig.h\"\n#include \"StatAcc.hpp\"\n#include \"RndGraphGen.hpp\"\n\nstruct BSParameters\n{\n    double T, r, sigma, S0, default_prob_scale;\n};\n\nstruct NetworkParameters\n{\n    int N, which_to_set;\n    double conn, colSums;\n};\n\n\nclass BlackScholesNetwork\n{\n    using Mat = Eigen::MatrixXd;\n    using Vec = Eigen::VectorXd;\nprivate:\n    double T, r, exprt;\n    int N;\n    bool initialized;\n    Vec x, S0, St, St_full, debt, solvent, sigma;\n    bool jacobian_set;\n    //Mat sigma_diag;\n#if USE_SPARSE_INTERNAL\n    Eigen::SparseLU<Eigen::SparseMatrix<double, Eigen::ColMajor>> lu;\n    Eigen::SparseMatrix<double, Eigen::ColMajor> Id;\n    Eigen::SparseMatrix<double, Eigen::ColMajor> M;\n    //Eigen::SparseMatrix<double, Eigen::ColMajor> GreekMat;\n    //Eigen::SparseMatrix<double, Eigen::ColMajor> Jrs;\n    //Eigen::SparseMatrix<double, Eigen::ColMajor> J_a;\n    //Eigen::SparseMatrix<double, Eigen::ColMajor> Z;\n#else\n    Mat M;\n    //Mat J_a;\n    Mat Id;\n    Eigen::PartialPivLU<Eigen::MatrixXd> lu;\n#endif\n    Mat GreekMat;\n\n    void set_solvent();\n\n\n\npublic:\n    BlackScholesNetwork(const BlackScholesNetwork&) = delete;\n\n    /* BlackScholesNetwork& operator=(const BlackScholesNetwork& rhs) = delete;\n    {\n        T = rhs.T;\n        r = rhs.r;\n        N = rhs.N;\n        M = rhs.M;\n        x = rhs.x;\n        S0 = rhs.S0;\n        St = rhs.St;\n        debt = rhs.debt;\n        solvent = rhs.solvent;\n        exprt = rhs.exprt;\n    }*/\n\n    //BlackScholesNetwork()\n    //{\n        //LOG(WARNING) << \"Default constructor for BlackScholesNetwork used. This could be unintentional.\";\n    //    initialized = false;\n    //}\n\n    /**\n     * @brief\n     * @param T         maturity\n     * @param r         interest rate\n     */\n    BlackScholesNetwork(const Eigen::Ref<Vec>& S0, const Eigen::Ref<Vec>& debt, const Eigen::Ref<Vec>& sigma_, const double T,const double r);\n\n    /**\n     * @brief\n     * @param M         Combined cross equity and cross debt matrix\n     * @param assets    exogenous assets\n     * @param debt      debts\n     * @param T         maturity\n     * @param r         interest rate\n     */\n    BlackScholesNetwork(const Eigen::Ref<Mat>& M, const Eigen::Ref<Vec>& S0, const Eigen::Ref<Vec>& assets, const Eigen::Ref<Vec>& debt, const Eigen::Ref<Vec>& sigma_, const double T, const double r);\n\n\n\n    /**\n     * @brief               Finds the fixed point of the cross holding problem at maturity T.\n     * @param iterations    maximum number of self consistency iterations.\n     * @return              returns vector of value of debt and value of equity.\n     */\n    const Mat run_valuation(unsigned int iterations);\n\n\n    inline void set_St(const Vec &st) {\n        if(st.size() != N)\n            throw std::logic_error(\"Mismatch between cross ownership matrix and assets!\");\n        St = st;\n        St_full = S0.array()*St.array();\n    }\n\n    void re_init(const Eigen::Ref<const Mat>& M_new)\n    {\n        if(M_new.rows() != S0.size()) throw std::logic_error(\"re-initialized with wrong M size!\");\n#if USE_SPARSE_INTERNAL\n        M = M_new.sparseView();\n        M.makeCompressed();\n#else\n        M = M_new;\n#endif\n    }\n\n    void re_init(const Eigen::Ref<const Mat>& M_new, const Eigen::Ref<const Vec> &s0, const Eigen::Ref<const Vec> &d, const Eigen::Ref<const Vec> &sigma_) {\n        N = M_new.rows();\n        //Jrs.resize(2*N, 2*N);\n        //J_a.resize(2*N, N);\n        x.resize(2*N);\n        x = Eigen::VectorXd::Zero(2*N);\n#if USE_SPARSE_INTERNAL\n        M = M_new.sparseView();\n        M.makeCompressed();\n        Id.resize(2*N, 2*N);\n        Id.setIdentity();\n#else\n        M = M_new;\n        lu = Eigen::PartialPivLU<Eigen::MatrixXd>(2*N);\n        Id.resize(2*N, 2*N);\n        Id.setIdentity();\n#endif\n        St.resize(N);\n        St_full.resize(N);\n        St = Eigen::VectorXd::Constant(N, 1.0);\n        if(s0.size() != N)\n            throw std::logic_error(\"Mismatch between cross ownership matrix and assets prefactor!\");\n        S0 = s0;\n        sigma.resize(N);\n        sigma = sigma_;\n        if(d.size() != N)\n            throw std::logic_error(\"Mismatch between cross ownership matrix and debts!\");\n        debt = d;\n        jacobian_set = false;\n        initialized = true;\n    }\n\n    //@TODO: consistent return typex\n    inline const Vec get_S0() const {\n        return S0;\n    }\n\n    inline const Vec get_St() const {\n        LOG(WARNING) << \"St does NOT contain S0!\";\n        return St;\n    }\n\n    inline const Vec get_debt() const {\n        return debt;\n    }\n\n    inline const Mat get_M() const {\n#if USE_SPARSE_INTERNAL\n        return Eigen::MatrixXd(M);\n#else\n        return M;\n#endif\n    }\n\n    const Vec get_assets();\n\n    //@TODO: move implementation to *.cpp\n    const Vec get_rs() {\n        return x;\n    }\n\n    const Vec get_valuation() {\n        Vec res = (x.head(N) + x.tail(N));\n        return res;\n    }\n\n   const Vec get_solvent() {\n        return solvent;\n   }\n\n\n    void set_jacobian();\n\n    Mat get_delta_v1() const;\n\n    Mat get_vega(const Eigen::MatrixXd Z) const;\n\n    Mat get_theta(const Eigen::MatrixXd Z) const;\n\n    Mat get_rho() const;\n    /*\n    std::vector<double> ret;\n    ret.resize(N);\n    Eigen::VectorXd::Map(&ret[0], N) = x.head(N) + x.tail(N);\n    return ret;*/\n\n\n    Eigen::MatrixXd get_pi() const;\n\n    Eigen::MatrixXd get_scalar_allGreeks(const Eigen::Ref<const Mat>& Z) const;\n\n    void debug_print();\n\n\n};\n#endif // SRC_MULTIVAR_BLACKSCHOLES_HPP_\n", "meta": {"hexsha": "3a87868f23645c3a05dddb78c3fd44af0da34470", "size": 6225, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/BlackScholesNetwork.hpp", "max_stars_repo_name": "Atomtomate/sys_risk", "max_stars_repo_head_hexsha": "b47cd40a7fec1305dbe70fde9b94815b41939b5c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BlackScholesNetwork.hpp", "max_issues_repo_name": "Atomtomate/sys_risk", "max_issues_repo_head_hexsha": "b47cd40a7fec1305dbe70fde9b94815b41939b5c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BlackScholesNetwork.hpp", "max_forks_repo_name": "Atomtomate/sys_risk", "max_forks_repo_head_hexsha": "b47cd40a7fec1305dbe70fde9b94815b41939b5c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2024291498, "max_line_length": 200, "alphanum_fraction": 0.6146184739, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.43020928535141534}}
{"text": "/**\n * @file OcpDescription.hpp\n * @author Brahayam Ponton (brahayam.ponton@tuebingen.mpg.de)\n * @license License BSD-3-Clause\n * @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft.\n * @date 2019-10-07\n */\n\n#pragma once\n\n#include <vector>\n#include <Eigen/Dense>\n#include <solver_lqr/SolverLqrSetting.hpp>\n\nnamespace solverlqr {\n\n  //! Class to define State of OCP\n  class StateBase\n  {\n    public:\n\t  StateBase(){}\n\t  StateBase(int xdim) { state_ = Eigen::VectorXd(xdim).setZero(); }\n\t  ~StateBase(){}\n\n\t  StateBase& operator= (const StateBase& rhs) { state_ = rhs.stateVector(); return *this; }\n\t  StateBase  operator* (double scalar) const { StateBase new_state; new_state.stateVector() = scalar*state_; return new_state; }\n\t  StateBase& operator*=(double scalar) { state_ *= scalar; return *this; }\n\t  StateBase  operator+ (const StateBase& rhs) const { StateBase new_state; new_state.stateVector() = state_+rhs.stateVector(); return new_state; }\n\t  StateBase& operator+=(const StateBase& rhs) { state_ += rhs.stateVector(); return *this; }\n\t  StateBase  operator/ (double scalar) const { StateBase new_state; new_state.stateVector() = state_/scalar; return new_state; }\n\t  StateBase& operator/=(double scalar) { state_ /= scalar; return *this; }\n\n      Eigen::VectorXd& stateVector() { return state_; }\n      const Eigen::VectorXd& stateVector() const { return state_; }\n      void resize(int xdim) { state_ = Eigen::VectorXd(xdim).setZero(); }\n\n    private:\n      Eigen::VectorXd state_;\n  };\n  StateBase operator* (double scalar, const StateBase& rhs);\n  StateBase operator- (const StateBase& lhs, const StateBase& rhs);\n\n\n  class StateSequence\n  {\n    public:\n      StateSequence(){}\n      StateSequence(int tdim, int xdim) { this->resize(tdim, xdim); }\n      ~StateSequence(){}\n\n      void resize(int tdim, int xdim);\n      void setRandom(double scaling = 1.0);\n      int size() const { return stateseq_.size(); }\n      StateBase& state(int id) { return stateseq_[id]; }\n      const StateBase& state(int id) const { return stateseq_[id]; }\n\n    private:\n      std::vector<StateBase> stateseq_;\n  };\n\n  //! Class to define Control of OCP\n  class ControlBase\n  {\n    public:\n      ControlBase(){}\n      ControlBase(int xdim, int udim);\n      ~ControlBase(){}\n\n      ControlBase& operator= (const ControlBase& rhs);\n      ControlBase  operator* (double scalar) const;\n      ControlBase& operator*=(double scalar);\n      ControlBase  operator+ (const ControlBase& rhs) const;\n      ControlBase& operator+=(const ControlBase& rhs);\n\n      void setZero() { feedforward_.setZero(); }\n      Eigen::MatrixXd& feedback() { return feedback_; }\n      Eigen::VectorXd& feedforward() { return feedforward_; }\n      const Eigen::MatrixXd& feedback() const { return feedback_; }\n      const Eigen::VectorXd& feedforward() const { return feedforward_; }\n      void setRandom(double scaling = 1.0) { feedforward_.setRandom(); feedforward_ *= scaling; }\n\n    private:\n      Eigen::MatrixXd feedback_;\n      Eigen::VectorXd feedforward_;\n  };\n  ControlBase operator*(double lhs_scalar, const ControlBase& rhs);\n\n  class ControlSequence\n  {\n    public:\n      ControlSequence(){}\n      ControlSequence(int tdim, int xdim, int udim) { this->resize(tdim, xdim, udim); }\n      ~ControlSequence(){}\n\n      void setRandom(double scaling = 1.0);\n      void resize(int tdim, int xdim, int udim);\n      int size() const { return controlseq_.size(); }\n      ControlBase& control(int id) { return controlseq_[id]; }\n      const ControlBase& control(int id) const { return controlseq_[id]; }\n\n      ControlSequence& operator= (const ControlSequence& rhs);\n      ControlSequence  operator* (double scalar) const;\n      ControlSequence& operator*=(double scalar);\n      ControlSequence  operator+ (const ControlSequence& rhs) const;\n      ControlSequence& operator+=(const ControlSequence& rhs);\n\n      static double controlSequenceGradientNorm(const ControlSequence& u1, const ControlSequence& u2);\n\n    private:\n      std::vector<ControlBase> controlseq_;\n  };\n  ControlSequence operator*(double lhs_scalar, const ControlSequence& rhs);\n\n  //! Optimal Control Problem Description Class\n  class OcpBase\n  {\n    public:\n\t  OcpBase(){}\n      ~OcpBase(){}\n      void initialize(const SolverLqrSetting& setting);\n\n      const double& dt() const { return this->getLqrSetting().get(SolverLqrDoubleParam_TimeStep); }\n      const int& tdim() const { return this->getLqrSetting().get(SolverLqrIntParam_TimeDimension); }\n      const int& xdim() const { return this->getLqrSetting().get(SolverLqrIntParam_StateDimension); }\n      const int& udim() const { return this->getLqrSetting().get(SolverLqrIntParam_ControlDimension); }\n\n      StateSequence& stateSeq() { return stateseq_; }\n      ControlSequence& controlSeq() { return controlseq_; }\n      const StateSequence& stateSeq() const { return stateseq_; }\n      const ControlSequence& controlSeq() const { return controlseq_; }\n      const SolverLqrSetting& getLqrSetting() const { return *setting_; }\n\n      virtual void configure(const YAML::Node& user_parameters) = 0;\n      virtual Eigen::MatrixXd processNoiseFilter(int time_id) const;\n      virtual Eigen::MatrixXd measurementNoiseFilter(int time_id) const;\n      virtual StateBase dynamics(const StateBase& state, const ControlBase& control, int time_id) = 0;\n      void internal_dynamics(const StateBase& state, const ControlBase& control, StateBase& new_state, int time_id);\n      virtual double objective(const StateBase& state, const ControlBase& control, int time_id, bool is_final_timestep) = 0;\n\n    private:\n      friend class Estimator;\n      friend class ForwardPass;\n      friend class BackwardPass;\n      friend class FiniteDifferences;\n\n    private:\n      StateSequence stateseq_;\n      ControlSequence controlseq_;\n      const SolverLqrSetting* setting_;\n  };\n\n}\n", "meta": {"hexsha": "d164506a52c38b9aeb2f2d75376113d2b163ae2e", "size": 5878, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solver_lqr/include/solver_lqr/OcpDescription.hpp", "max_stars_repo_name": "machines-in-motion/kino-dynamic-opt", "max_stars_repo_head_hexsha": "ba9188eea6b80b102b1d0880470bedc0faa5e243", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2019-11-18T17:39:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T00:38:22.000Z", "max_issues_repo_path": "solver_lqr/include/solver_lqr/OcpDescription.hpp", "max_issues_repo_name": "machines-in-motion/kino_dynamic_opt", "max_issues_repo_head_hexsha": "ba9188eea6b80b102b1d0880470bedc0faa5e243", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2019-11-11T19:54:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-07T13:41:47.000Z", "max_forks_repo_path": "solver_lqr/include/solver_lqr/OcpDescription.hpp", "max_forks_repo_name": "machines-in-motion/kino-dynamic-opt", "max_forks_repo_head_hexsha": "ba9188eea6b80b102b1d0880470bedc0faa5e243", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-15T14:36:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T10:42:19.000Z", "avg_line_length": 38.4183006536, "max_line_length": 147, "alphanum_fraction": 0.6915617557, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4301987765555449}}
{"text": "/**\n This file is part of Poisson Image Editing.\n \n Copyright Christoph Heindl 2015\n \n Poisson Image Editing is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n \n Poisson Image Editing is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with Poisson Image Editing.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n\n#include <blend/clone.h>\n#include <blend/poisson_solver.h>\n#include <opencv2/opencv.hpp>\n#pragma warning (push)\n#pragma warning (disable: 4244)\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#pragma warning (pop)\n\nnamespace blend {\n    \n    namespace detail {\n        bool findOverlap(cv::InputArray background,\n                         cv::InputArray foreground,\n                         int offsetX, int offsetY,\n                         cv::Rect &rBackground,\n                         cv::Rect &rForeground)\n        {\n            cv::Mat bg = background.getMat();\n            cv::Mat fg = foreground.getMat();\n\n            \n            rBackground = cv::Rect(0, 0, bg.cols, bg.rows) & \n                          cv::Rect(offsetX, offsetY, fg.cols, fg.rows);\n\n\n            // Compensate for negative offsets. If offset < 0, offset in foreground is positive.\n            rForeground = cv::Rect(std::max<int>(-offsetX, 0), \n                                   std::max<int>(-offsetY, 0), \n                                   rBackground.width, \n                                   rBackground.height);\n\n            \n            return rForeground.area() > 0;\n            \n        }\n        \n        void computeMixedGradientVectorField(cv::InputArray background,\n                                             cv::InputArray foreground,\n                                             cv::OutputArray vx_,\n                                             cv::OutputArray vy_)\n        {\n            cv::Mat bg = background.getMat();\n            cv::Mat fg = foreground.getMat();\n            \n            const int channels = bg.channels();\n            \n            vx_.create(bg.size(), CV_MAKETYPE(CV_32F, channels));\n            vy_.create(bg.size(), CV_MAKETYPE(CV_32F, channels));\n            \n            cv::Mat vx = vx_.getMat();\n            cv::Mat vy = vy_.getMat();\n            \n            cv::Mat kernelx = (cv::Mat_<float>(1, 3) << -0.5, 0, 0.5);\n            cv::Mat kernely = (cv::Mat_<float>(3, 1) << -0.5, 0, 0.5);\n            \n            cv::Mat vxf, vyf, vxb, vyb;\n            cv::filter2D(fg, vxf, CV_32F, kernelx, cv::Point(-1,-1), 0, cv::BORDER_REPLICATE);\n            cv::filter2D(fg, vyf, CV_32F, kernely, cv::Point(-1,-1), 0, cv::BORDER_REPLICATE);\n            cv::filter2D(bg, vxb, CV_32F, kernelx, cv::Point(-1,-1), 0, cv::BORDER_REPLICATE);\n            cv::filter2D(bg, vyb, CV_32F, kernely, cv::Point(-1,-1), 0, cv::BORDER_REPLICATE);\n            \n            \n            for(int id = 0; id <= (vx.rows * vx.cols * channels - channels); ++id)\n            {\n                const cv::Vec2f g[2] = {\n                    cv::Vec2f(vxf.ptr<float>()[id], vyf.ptr<float>()[id]),\n                    cv::Vec2f(vxb.ptr<float>()[id], vyb.ptr<float>()[id])\n                };\n                \n                int which = (g[0].dot(g[0]) > g[1].dot(g[1])) ? 0 : 1;\n                \n                vx.ptr<float>()[id] = g[which][0];\n                vy.ptr<float>()[id] = g[which][1];\n            }\n        }\n        \n        void computeWeightedGradientVectorField(cv::InputArray background,\n                                                cv::InputArray foreground,\n                                                cv::OutputArray vx,\n                                                cv::OutputArray vy,\n                                                float weightForeground)\n        {\n            \n            cv::Mat bg = background.getMat();\n            cv::Mat fg = foreground.getMat();\n            \n            cv::Mat kernelx = (cv::Mat_<float>(1, 3) << -0.5, 0, 0.5);\n            cv::Mat kernely = (cv::Mat_<float>(3, 1) << -0.5, 0, 0.5);\n            \n            cv::Mat vxf, vyf, vxb, vyb;\n            cv::filter2D(fg, vxf, CV_32F, kernelx, cv::Point(-1,-1), 0, cv::BORDER_REPLICATE);\n            cv::filter2D(fg, vyf, CV_32F, kernely, cv::Point(-1,-1), 0, cv::BORDER_REPLICATE);\n            cv::filter2D(bg, vxb, CV_32F, kernelx, cv::Point(-1,-1), 0, cv::BORDER_REPLICATE);\n            cv::filter2D(bg, vyb, CV_32F, kernely, cv::Point(-1,-1), 0, cv::BORDER_REPLICATE);\n            \n            cv::addWeighted(vxf, weightForeground, vxb, 1.f - weightForeground, 0, vx);\n            cv::addWeighted(vyf, weightForeground, vyb, 1.f - weightForeground, 0, vy);\n        }\n    }\n    \n    void seamlessClone(cv::InputArray background,\n                       cv::InputArray foreground,\n                       cv::InputArray foregroundMask,\n                       int offsetX,\n                       int offsetY,\n                       cv::OutputArray destination,\n                       CloneType type)\n    {\n        \n        // Copy original background as we only solve for the overlapping area of the translated foreground mask.\n        background.getMat().copyTo(destination);\n        \n        // Find overlapping region. We will only perform on this region\n        cv::Rect rbg, rfg;\n        if (!detail::findOverlap(background, foreground, offsetX, offsetY, rbg, rfg))\n            return;\n        \n        // Compute the guidance vector field\n        cv::Mat vx, vy;\n        switch (type) {\n            case CLONE_FOREGROUND_GRADIENTS:\n                detail::computeWeightedGradientVectorField(background.getMat()(rbg),\n                                                           foreground.getMat()(rfg),\n                                                           vx, vy,\n                                                           1.f);\n                break;\n                \n            case CLONE_AVERAGED_GRADIENTS:\n                detail::computeWeightedGradientVectorField(background.getMat()(rbg),\n                                                           foreground.getMat()(rfg),\n                                                           vx, vy,\n                                                           0.5f);\n                break;\n                \n            case CLONE_MIXED_GRADIENTS:\n                detail::computeMixedGradientVectorField(background.getMat()(rbg),\n                                                        foreground.getMat()(rfg),\n                                                        vx, vy);\n                break;\n                \n            default:\n                break;\n        }\n        \n        \n        // For the Poisson equation the divergence of the guidance field is necessary.\n        cv::Mat vxx, vyy;\n        cv::Mat kernelx = (cv::Mat_<float>(1, 3) << -0.5, 0, 0.5);\n        cv::Mat kernely = (cv::Mat_<float>(3, 1) << -0.5, 0, 0.5);\n        cv::filter2D(vx, vxx, CV_32F, kernelx);\n        cv::filter2D(vy, vyy, CV_32F, kernely);\n        \n        cv::Mat f = vxx + vyy;\n                \n        cv::Mat boundaryMask(rfg.size(), CV_8UC1);      \n        cv::threshold(foregroundMask.getMat()(rfg), boundaryMask, constants::UNKNOWN, constants::DIRICHLET_BD, cv::THRESH_BINARY_INV);\n        cv::rectangle(boundaryMask, cv::Rect(0, 0, boundaryMask.cols, boundaryMask.rows), constants::DIRICHLET_BD, 1);\n\n        cv::Mat boundaryValues(rfg.size(), CV_MAKETYPE(CV_32F, background.channels()));\n        background.getMat()(rbg).convertTo(boundaryValues, CV_32F);\n        \n        // Solve Poisson equation\n        cv::Mat result;\n        solvePoissonEquations(f,\n                              boundaryMask,\n                              boundaryValues,\n                              result);\n        \n        // Copy result to destination image.\n        result.convertTo(destination.getMat()(rbg), CV_8U);\n        \n    }\n    \n    \n}", "meta": {"hexsha": "420234a497c71d4d7089aa74e880d5510cefafda", "size": 8238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "poisson-image-editing/src/clone.cpp", "max_stars_repo_name": "eti-p-doray/inf8702", "max_stars_repo_head_hexsha": "1f420f6a6d8df5e9f5dce7c6192b622c761a909a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "poisson-image-editing/src/clone.cpp", "max_issues_repo_name": "eti-p-doray/inf8702", "max_issues_repo_head_hexsha": "1f420f6a6d8df5e9f5dce7c6192b622c761a909a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "poisson-image-editing/src/clone.cpp", "max_forks_repo_name": "eti-p-doray/inf8702", "max_forks_repo_head_hexsha": "1f420f6a6d8df5e9f5dce7c6192b622c761a909a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0306122449, "max_line_length": 134, "alphanum_fraction": 0.4859189124, "num_tokens": 1916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.43019030685880166}}
{"text": "//\r\n// $Id: Interpolator.hpp 9294 2016-01-15 20:00:16Z chambm $\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \r\n// you may not use this file except in compliance with the License. \r\n// You may obtain a copy of the License at \r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software \r\n// distributed under the License is distributed on an \"AS IS\" BASIS, \r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \r\n// See the License for the specific language governing permissions and \r\n// limitations under the License.\r\n//\r\n// The Original Code is the Quameter software.\r\n//\r\n// The Initial Developer of the Original Code is Matt Chambers.\r\n//\r\n// Copyright 2011 Vanderbilt University\r\n//\r\n// Contributor(s):\r\n//\r\n\r\n#include \"spline.hpp\"\r\n#include <vector>\r\n#include <boost/shared_array.hpp>\r\n\r\n\r\nnamespace freicore {\r\n\r\nusing std::vector;\r\n\r\nstruct Interpolator\r\n{\r\n    Interpolator(const vector<double>& x, const vector<double>& y)\r\n    {\r\n        _size = x.size();\r\n\r\n        if (_size < 4)\r\n            return;\r\n\r\n        BOOST_ASSERT(x.size() == y.size());\r\n\r\n        //_ypp.reset(spline_cubic_set(_size, const_cast<double*>(&x[0]), const_cast<double*>(&y[0]), 1, 0, 1, 0));\r\n\r\n        _ypp.reset(new double[_size]);\r\n        spline_pchip_set(_size, const_cast<double*>(&x[0]), const_cast<double*>(&y[0]), _ypp.get());\r\n    }\r\n\r\n    // uses interpolation on piecewise cubic splines to make an f(x) function evenly spaced on the x axis\r\n    void resample(vector<double>& x, vector<double>& y) const\r\n    {\r\n        BOOST_ASSERT(_size == x.size());\r\n        BOOST_ASSERT(_size == y.size());\r\n\r\n        if (x.size() < 4)\r\n            return;\r\n\r\n        //double minSampleSize = x[1] - x[0];\r\n        //for (int i=2; i < _size; ++i)\r\n            //minSampleSize = min(minSampleSize, x[i] - x[i-1]);\r\n\r\n        vector<double> sampleDeltas(_size, 0);\r\n        for (int i=1; i < _size; ++i)\r\n            sampleDeltas[i] = x[i] - x[i-1];\r\n        sort(sampleDeltas.begin(), sampleDeltas.end());\r\n\r\n        double minSampleSize = sampleDeltas[min(size_t(_size - 1), size_t(_size*0.01 + 1))];\r\n\r\n        size_t newSize = (x.back() - x.front()) / minSampleSize;\r\n\r\n        //double ypval, yppval;\r\n        vector<double> newX, newY;\r\n        newX.reserve(newSize);\r\n        newY.reserve(newSize);\r\n        newX.push_back(x[0]);\r\n        newY.push_back(y[0]);\r\n        for (size_t i=1; newX.back() < x.back(); ++i)\r\n        {\r\n            newX.push_back(newX.back() + minSampleSize);\r\n            newY.push_back(0);\r\n            int left = i-1;\r\n            //spline_cubic_val2(_size, &x[0], newX.back(), &left, &y[0], _ypp.get(), &newY.back(), &ypval, &yppval);\r\n            spline_pchip_val(_size, &x[0], &y[0], _ypp.get(), 1, &newX.back(), &newY.back());\r\n        }\r\n        swap(x, newX);\r\n        swap(y, newY);\r\n    }\r\n\r\n    double interpolate(const vector<double>& xs, const vector<double>& ys, double x) const\r\n    {\r\n        if (x < xs.front() || x > xs.back() || xs.size() < 4)\r\n            return 0;\r\n\r\n        //double ypval, yppval;\r\n        //return spline_cubic_val(_size, const_cast<double*>(&xs[0]), const_cast<double*>(&ys[0]), _ypp.get(), x, &ypval, &yppval);\r\n\r\n        double y;\r\n        spline_pchip_val(_size, const_cast<double*>(&xs[0]), const_cast<double*>(&ys[0]), _ypp.get(), 1, &x, &y);\r\n        return y;\r\n    }\r\n\r\n    private:\r\n    boost::shared_array<double> _ypp;\r\n    int _size;\r\n};\r\n\r\n} // namespace freicore\r\n", "meta": {"hexsha": "92265d4e3cdb28c84c017d48d55b483ba105a84d", "size": 3555, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz_tools/Bumbershoot/quameter/Interpolator.hpp", "max_stars_repo_name": "shze/pwizard-deb", "max_stars_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-12-28T21:24:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-18T03:52:05.000Z", "max_issues_repo_path": "pwiz_tools/Bumbershoot/quameter/Interpolator.hpp", "max_issues_repo_name": "shze/pwizard-deb", "max_issues_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pwiz_tools/Bumbershoot/quameter/Interpolator.hpp", "max_forks_repo_name": "shze/pwizard-deb", "max_forks_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3181818182, "max_line_length": 132, "alphanum_fraction": 0.5772151899, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.430139696443956}}
{"text": "#include <deal.II/base/utilities.h>\n\n#include \"poisson.h\"\n\n/**\n * \\mainpage Adaptive FEM for Poisson problem\n *\n * This is the starting code for laboratory number 7 of the course \"Theory and\n * Practice of Finite Element methods\".\n *\n * We solve the Poisson problem\n *\n * \\[\n * \\begin{split}\n * -\\Delta u &= f \\quad \\text{ in } \\Omega\\\\\n * n\\cdot \\nabla u &= g_N \\quad \\text{ on } \\partial\\Omega_N\\\\\n *  u &= g_D \\quad \\text{ on } \\partial\\Omega_D\n * \\end{split}\n * \\]\n *\n * on convex and Lipschitz domains $\\Omega$, using the Finite Element method,\n * and the deal.II library (www.dealii.org).\n */\n\nint\nmain(int argc, char **argv)\n{\n  Utilities::MPI::MPI_InitFinalize init(argc, argv);\n  std::string                      par_name = \"\";\n  if (argc > 1)\n    par_name = argv[1];\n\n  deallog.depth_console(2);\n  Poisson<2> laplace_problem;\n  laplace_problem.initialize(par_name);\n  laplace_problem.run();\n  return 0;\n}", "meta": {"hexsha": "38de1e49938f5f35f3afb63752ae942dc388f365", "size": 914, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/main.cc", "max_stars_repo_name": "dealii-courses/sissa-mhpc-lab-07-Nkana-valentin", "max_stars_repo_head_hexsha": "af3df84d2a37018e8c25541e684de09d5575e403", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/main.cc", "max_issues_repo_name": "dealii-courses/sissa-mhpc-lab-07-Nkana-valentin", "max_issues_repo_head_hexsha": "af3df84d2a37018e8c25541e684de09d5575e403", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/main.cc", "max_forks_repo_name": "dealii-courses/sissa-mhpc-lab-07-Nkana-valentin", "max_forks_repo_head_hexsha": "af3df84d2a37018e8c25541e684de09d5575e403", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-17T08:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T08:28:00.000Z", "avg_line_length": 24.0526315789, "max_line_length": 78, "alphanum_fraction": 0.6455142232, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4301396890660718}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_PIO_6_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_PIO_6_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n\n    @ingroup group-constant\n\n    Constant \\f$\\frac\\pi{6}\\f$.\n\n    @par Semantic:\n\n    For type T:\n\n    @code\n    T r = Pio_6<T>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = Pi<T>()/Six<T>();\n    @endcode\n\n    @return a value of type T\n\n**/\n  template<typename T> T Pio_6();\n\n  namespace functional\n  {\n    /*!\n      @ingroup group-callable-constant\n\n\n      Constant \\f$\\frac\\pi{6}\\f$.\n\n      Generate the  constant pio_6.\n\n      @return The Pio_6 constant for the proper type\n    **/\n    const boost::dispatch::functor<tag::pio_6_> pio_6 = {};\n  }\n} }\n#endif\n\n#include <boost/simd/constant/definition/pio_6.hpp>\n#include <boost/simd/arch/common/scalar/constant/constant_value.hpp>\n#include <boost/simd/arch/common/simd/constant/constant_value.hpp>\n\n#endif\n", "meta": {"hexsha": "13f09c1e2a41363209794bdaa2e6d2233bc63e05", "size": 1323, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/pio_6.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/pio_6.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/pio_6.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 20.671875, "max_line_length": 100, "alphanum_fraction": 0.5676492819, "num_tokens": 325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4301396890660718}}
{"text": "#include \"optimization_utils.hpp\"\n#include <boost/algorithm/clamp.hpp>\n#include <random>\n\nnamespace optimization\n{\nstd::vector<std::vector<double>> get_initial_positions(double left_bound, double right_bound, int dimension, int number_of_agents)\n{\n    std::vector<std::vector<double>> positions(number_of_agents, std::vector<double>(dimension, 0.));\n    for (auto &agent : positions)\n        for (auto &coord : agent)\n            coord = get_random(left_bound, right_bound);\n\n    return positions;\n}\n\ndouble get_random(double left_bound, double right_bound)\n{\n    static std::random_device rd;\n    static std::mt19937 gen(rd());\n    std::uniform_real_distribution<double> dist(left_bound, right_bound);\n\n    return dist(gen);\n}\n\nstd::vector<std::vector<double>> &clip_positions(std::vector<std::vector<double>> &positions, double left_bound, double right_bound)\n{\n    for (auto &agent : positions)\n        for (auto &coord : agent)\n            coord = boost::algorithm::clamp(coord, left_bound, right_bound);\n\n    return positions;\n}\n}", "meta": {"hexsha": "1188b526487149a5c1dad928633132e2caa6110b", "size": 1035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "optimization/optimization_utils.cpp", "max_stars_repo_name": "czeslavo/gwo", "max_stars_repo_head_hexsha": "709488a90840c0a2ed43635143c007adb91b47d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-06-04T02:09:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-25T12:48:11.000Z", "max_issues_repo_path": "optimization/optimization_utils.cpp", "max_issues_repo_name": "czeslavo/gwo", "max_issues_repo_head_hexsha": "709488a90840c0a2ed43635143c007adb91b47d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-14T22:37:39.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-15T08:54:06.000Z", "max_forks_repo_path": "optimization/optimization_utils.cpp", "max_forks_repo_name": "czeslavo/gwo", "max_forks_repo_head_hexsha": "709488a90840c0a2ed43635143c007adb91b47d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-03-07T07:50:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-03T08:31:30.000Z", "avg_line_length": 30.4411764706, "max_line_length": 132, "alphanum_fraction": 0.7111111111, "num_tokens": 233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4301396816881874}}
{"text": "/*\n\nCopyright (c) 2005-2015, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#ifndef NAGAIHONDAFORCE_HPP_\n#define NAGAIHONDAFORCE_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n#include \"Exception.hpp\"\n\n#include \"AbstractForce.hpp\"\n#include \"VertexBasedCellPopulation.hpp\"\n\n#include <iostream>\n\n/**\n * A force class for use in vertex-based simulations, based on a mechanical\n * model proposed by T. Nagai and H. Honda (\"A dynamic cell model for the formation\n * of epithelial tissues\", Philosophical Magazine Part B 81:699-719). In contrast to the force proposed\n * by Nagai and Honda this force has an additional force term implemented that scales with the perimeter\n * of a cell to simulate the surface membrane energy. This particular perimeter force term in turn differs from the one\n * proposed by Farhadifar et al (2007) in the sense that it employs a target perimeter.\n *\n * Each of the model parameter member variables are rescaled such that mDampingConstantNormal\n * takes the default value 1, whereas Nagai and Honda (who denote the parameter by\n * nu) take the value 0.01.\n */\ntemplate<unsigned DIM>\nclass NagaiHondaForce  : public AbstractForce<DIM>\n{\nfriend class TestForces;\n\nprivate:\n\n    friend class boost::serialization::access;\n    /**\n     * Boost Serialization method for archiving/checkpointing.\n     * Archives the object and its member variables.\n     *\n     * @param archive  The boost archive.\n     * @param version  The current version of this class.\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n        archive & boost::serialization::base_object<AbstractForce<DIM> >(*this);\n        archive & mNagaiHondaDeformationEnergyParameter;\n        archive & mNagaiHondaMembraneSurfaceEnergyParameter;\n        archive & mNagaiHondaCellCellAdhesionEnergyParameter;\n        archive & mNagaiHondaCellBoundaryAdhesionEnergyParameter;\n    }\n\nprotected:\n\n    /**\n     * Cell deformation energy parameter. Has units of kg s^-2 (cell size at equilibrium rest length)^-1.\n     */\n    double mNagaiHondaDeformationEnergyParameter;\n\n    /**\n     * Cell membrane energy parameter. Has units of kg (cell size at equilibrium rest length) s^-2.\n     */\n    double mNagaiHondaMembraneSurfaceEnergyParameter;\n\n    /**\n     * Cell-cell adhesion energy parameter. Has has units of kg (cell size at equilibrium rest length)^2 s^-2.\n     * This parameter corresponds to 1/2 of the Lambda parameter in forces proposed by Farhadifar et al (2007).\n     * This slight difference comes from the fact that when we apply the forces to a particular node, each\n     * edge is visited twice - and hence the force originating from that edge is applied twice.\n     */\n    double mNagaiHondaCellCellAdhesionEnergyParameter;\n\n    /**\n     * Cell-boundary adhesion energy parameter. Has units of kg (cell size at equilibrium rest length)^2 s^-2.\n     */\n    double mNagaiHondaCellBoundaryAdhesionEnergyParameter;\n\n\npublic:\n\n    /**\n     * Constructor.\n     */\n    NagaiHondaForce();\n\n    /**\n     * Destructor.\n     */\n    virtual ~NagaiHondaForce();\n\n    /**\n     * Overridden AddForceContribution() method.\n     *\n     * Calculates the force on each node in the vertex-based cell population based on the\n     * Nagai Honda model.\n     *\n     * @param rCellPopulation reference to the cell population\n     */\n    virtual void AddForceContribution(AbstractCellPopulation<DIM>& rCellPopulation);\n\n    /**\n     * Get the adhesion parameter for the edge between two given nodes.\n     *\n     * @param pNodeA one node\n     * @param pNodeB the other node\n     * @param rVertexCellPopulation reference to the cell population\n     *\n     * @return the adhesion parameter for this edge.\n     */\n    virtual double GetAdhesionParameter(Node<DIM>* pNodeA, Node<DIM>* pNodeB, VertexBasedCellPopulation<DIM>& rVertexCellPopulation);\n\n    /**\n     * @return mNagaiHondaDeformationEnergyParameter\n     */\n    double GetNagaiHondaDeformationEnergyParameter();\n\n    /**\n     * @return mNagaiHondaMembraneSurfaceEnergyParameter\n     */\n    double GetNagaiHondaMembraneSurfaceEnergyParameter();\n\n    /**\n     * @return mCellCellAdhesionEnergyParameter\n     */\n    double GetNagaiHondaCellCellAdhesionEnergyParameter();\n\n    /**\n     * @return mNagaiHondaCellBoundaryAdhesionEnergyParameter\n     */\n    double GetNagaiHondaCellBoundaryAdhesionEnergyParameter();\n\n    /**\n     * Set mNagaiHondaDeformationEnergyParameter.\n     *\n     * @param nagaiHondaDeformationEnergyParameter the new value of mNagaiHondaDeformationEnergyParameter\n     */\n    void SetNagaiHondaDeformationEnergyParameter(double nagaiHondaDeformationEnergyParameter);\n\n    /**\n     * Set mNagaiHondaMembraneSurfaceEnergyParameter.\n     *\n     * @param nagaiHondaMembraneSurfaceEnergyParameter the new value of mNagaiHondaMembraneSurfaceEnergyParameter\n     */\n    void SetNagaiHondaMembraneSurfaceEnergyParameter(double nagaiHondaMembraneSurfaceEnergyParameter);\n\n    /**\n     * Set mNagaiHondaCellCellAdhesionEnergyParameter. This parameter corresponds to 1/2 of the Lambda parameter in the forces by\n     * Farhadifar et al (2007).\n     *\n     * @param nagaiHondaCellCellAdhesionEnergyEnergyParameter the new value of mNagaiHondaCellCellAdhesionEnergyParameter\n     */\n    void SetNagaiHondaCellCellAdhesionEnergyParameter(double nagaiHondaCellCellAdhesionEnergyEnergyParameter);\n\n    /**\n     * Set mNagaiHondaCellBoundaryAdhesionEnergyParameter.\n     *\n     * @param nagaiHondaCellBoundaryAdhesionEnergyParameter the new value of mNagaiHondaCellBoundaryAdhesionEnergyParameter\n     */\n    void SetNagaiHondaCellBoundaryAdhesionEnergyParameter(double nagaiHondaCellBoundaryAdhesionEnergyParameter);\n\n    /**\n     * Overridden OutputForceParameters() method.\n     *\n     * @param rParamsFile the file stream to which the parameters are output\n     */\n    void OutputForceParameters(out_stream& rParamsFile);\n};\n\n#include \"SerializationExportWrapper.hpp\"\nEXPORT_TEMPLATE_CLASS_SAME_DIMS(NagaiHondaForce)\n\n#endif /*NAGAIHONDAFORCE_HPP_*/\n", "meta": {"hexsha": "b73aa13aee3fed5eac047b1cf65f605f1341fea3", "size": 7718, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/population/mechanics/NagaiHondaForce.hpp", "max_stars_repo_name": "ktunya/ChasteMod", "max_stars_repo_head_hexsha": "88ac65b00473cd730d348c783bd74b2b39de5f69", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cell_based/src/population/mechanics/NagaiHondaForce.hpp", "max_issues_repo_name": "ktunya/ChasteMod", "max_issues_repo_head_hexsha": "88ac65b00473cd730d348c783bd74b2b39de5f69", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cell_based/src/population/mechanics/NagaiHondaForce.hpp", "max_forks_repo_name": "ktunya/ChasteMod", "max_forks_repo_head_hexsha": "88ac65b00473cd730d348c783bd74b2b39de5f69", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6487804878, "max_line_length": 133, "alphanum_fraction": 0.7530448303, "num_tokens": 1726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.43010291001911327}}
{"text": "/**\n * \\file dcs/math/stats/distribution/gamma.hpp\n *\n * \\brief The Gamma probability distribution.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_MATH_STATS_DISTRIBUTION_GAMMA_HPP\n#define DCS_MATH_STATS_DISTRIBUTION_GAMMA_HPP\n\n\n#include <dcs/detail/config/boost.hpp>\n\n#if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(103500) // 1.35\n# \terror \"Required Boost library version >= 1.35\"\n#endif\n\n#include <boost/math/distributions/gamma.hpp>\n//#include <boost/random/gamma_distribution.hpp>\n//#include <boost/random/variate_generator.hpp>\n#include <cmath>\n#include <cstddef>\n#include <dcs/math/policies/policy.hpp>\n#include <dcs/math/random/uniform_01_adaptor.hpp>\n//#include <dcs/math/stats/distribution/detail/rgamma.cpp>\n//#include <dcs/math/constants.hpp>\n#include <iostream>\n#include <vector>\n\n\nnamespace dcs { namespace math { namespace stats {\n\nnamespace detail {\n\n} // Namespace detail\n\n\n/**\n * \\brief The Gamma distribution with shape parameter \\f$k\\f$ and scale\n *  parameter \\f$\\theta\\f$.\n *\n * \\tparam RealT The type used for real numbers.\n * \\tparam PolicyT The policy type.\n *\n * The probability density function (pdf):\n * \\f[\n *   \\Pr(x|k,\\theta) = x^{k-1} \\frac{\\exp{\\left(-x/\\theta\\right)}}{\\Gamma(k)\\,\\theta^k}\n * \\f]\n *\n * \\author Cosimo Anglano (cosimo.anglano@mfn.unipmn.it)\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate < typename RealT=double, typename PolicyT=::dcs::math::policies::policy<> >\nclass gamma_distribution\n{\n\tpublic: typedef RealT support_type;\n\tpublic: typedef RealT value_type;\n\tpublic: typedef PolicyT policy_type;\n\n\tpublic: explicit gamma_distribution(support_type shape, support_type scale=1)\n\t\t: dist_(shape, scale)\n\t{\n\t\t// empty\n\t}\n\n\n\t// compiler-generated copy ctor and assignment operator are fine\n\n\n\t/**\n\t * \\brief Generate a random number distributed according to this\n\t * gamma distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\return A random number distributed according to this gamma\n\t * distribution.\n\t *\n\t * A \\c gamma random number distribution produces random numbers\n\t * \\f$x \\ge 0\\f$ distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|k,\\theta) = x^{k-1} \\frac{\\exp{\\left(-x/\\theta\\right)}}{\\Gamma(k)\\,\\theta^k}\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\tsupport_type rand(UniformRandomGeneratorT& rng) const\n\t{\n/* Don't work: Actually (2010-01-21), Boost uses Gamma with only the parameter\n * shape. In principle this wouldn't be a problem since we may use the scaling\n * property gamma_rand(a,b)==b*gamma_rand(a); but for shape==1, it uses\n * Exp(rng()) which is wrong when b!=1 since Gamma(1,b) ~ Exp(1/b)\n *\n\t\ttypedef ::boost::gamma_distribution<support_type> rdist_type;\n\t\ttypedef ::boost::variate_generator<UniformRandomGeneratorT&, rdist_type> variate_type;\n\n\t\treturn dist_.scale() * variate_type(rng, rdist_type(dist_.shape()))();\n*/\n\t\t::dcs::math::random::uniform_01_adaptor<UniformRandomGeneratorT&, support_type> eng(rng);\n\t\tvalue_type r(0);\n\t\t//value_type ishape = static_cast<unsigned long>(dist_.shape()); // Not safe\n\t\tvalue_type ishape = ::std::floor(dist_.shape());\n\n\t\tif (dist_.shape() >= value_type(1))\n\t\t{\n\t\t\tvalue_type acc(0);\n\t\t\tfor (::std::size_t i = 0; i < ishape; ++i)\n\t\t\t{\n\t\t\t\tacc += ::std::log(eng());\n\t\t\t}\n\t\t\tr += -acc;\n\t\t}\n\t\tvalue_type diff = dist_.shape()-ishape;\n\t\tif (diff > 0)\n\t\t{\n/*\n\t\t\t// Acceptance-rejection method (see: http://en.wikipedia.org/wiki/Gamma_distribution#Generating_gamma-distributed_random_variables)\n\n\t\t\tvalue_type v0 = ::dcs::math::constants::e<value_type>::value/(::dcs::math::constants::e<value_type>::value + diff);\n\n\t\t\tvalue_type csi;\n\t\t\tvalue_type eta;\n\n\t\t\tdo\n\t\t\t{\n\t\t\t\tvalue_type u1 = eng();\n\t\t\t\tvalue_type u2 = eng();\n\t\t\t\tvalue_type u3 = eng();\n\n\t\t\t\tif (u1 <= v0)\n\t\t\t\t{\n\t\t\t\t\tcsi = ::std::pow(u2, value_type(1)/diff);\n\t\t\t\t\teta = u3*::std::pow(csi, diff-value_type(1));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcsi = value_type(1)-::std::log(u2);\n\t\t\t\t\teta = u3*::std::exp(-csi);\n\t\t\t\t}\n\n\t\t\t}\n\t\t\twhile (eta > (::std::pow(eta, diff-value_type(1))*::std::exp(-csi)));\n\t\t\t\t\n\t\t\tr = (csi - r);\n*/\n\n\t\t\t// this is the original code taken from rnd.cc (Anglano, 2005).\n\t\t\tvalue_type x;\n\t\t\tvalue_type y;\n\n\t\t\tdo {\n\t\t\t\tvalue_type u1 = eng();\n\t\t\t\tvalue_type u2 = eng();\n\t\t\t\tx = ::std::pow(u1, value_type(1)/diff);\n\t\t\t\ty = ::std::pow(u2, value_type(1)/dist_.scale());\n\t\t\t} while ((x+y)>1);\n\n\t\t\tx = (x/(x+y));\n\t\t\ty = -::std::log(eng());\n\n\t\t\tr += x*y;\n\t\t}\n\t\treturn dist_.scale()*r;\n\n/*\n\t\t// This uses a function coming from R\n\t\t::dcs::math::random::uniform_01_adaptor<UniformRandomGeneratorT&, support_type> eng(rng);\n\t\treturn detail::rgamma(dist_.shape(), dist_.scale(), eng);\n*/\n\t}\n\n\n\t/**\n\t * \\brief Generate a vector of random numbers distributed according to this\n\t * gamma distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\param n The number of random numbers to generate.\n\t * \\return A vector of random numbers distributed according to this\n\t * gamma distribution.\n\t *\n\t * A \\c gamma random number distribution produces random numbers\n\t * \\f$x \\ge 0\\f$ distributed according to the probability density function:\n\t * \\f[\n\t *   \\Pr(x|k,\\theta) = x^{k-1} \\frac{\\exp{\\left(-x/\\theta\\right)}}{\\Gamma(k)\\,\\theta^k}\n\t * \\f]\n\t */\n\tpublic: template <typename UniformRandomGeneratorT>\n\t\t::std::vector<support_type> rand(UniformRandomGeneratorT& rng, ::std::size_t n)\n\t{\n\t\t::std::vector<support_type> rnds(n);\n\n        for ( ; n > 0; --n)\n\t\t{\n\t\t\trnds.push_back(rand(rng));\n\t\t}\n\n\t\treturn rnds;\n\t}\n\n\n\tpublic: support_type shape() const\n\t{\n\t\treturn dist_.shape();\n\t}\n\n\n\tpublic: support_type scale() const\n\t{\n\t\treturn dist_.scale();\n\t}\n\n\n\tpublic: support_type location() const\n\t{\n\t\treturn support_type(0);\n\t}\n\n\n\tpublic: support_type quantile(value_type p) const\n\t{\n\t\treturn ::boost::math::quantile(dist_, p);\n\t}\n\n\n\tprivate: ::boost::math::gamma_distribution<value_type,policy_type> dist_;\n};\n\n\ntemplate <\n\ttypename CharT,\n\ttypename CharTraitsT,\n\ttypename RealT,\n\ttypename PolicyT\n>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os, gamma_distribution<RealT,PolicyT> const& dist)\n{\n\treturn os << \"Gamma(\"\n\t\t\t  << \"shape=\" <<  dist.shape()\n\t\t\t  << \", scale=\" <<  dist.scale()\n\t\t\t  << \")\";\n}\n\n}}} // Namespace dcs::math::stats\n\n\n#endif // DCS_MATH_STATS_DISTRIBUTION_GAMMA_HPP\n", "meta": {"hexsha": "e90f72d61b039ed7ef09626c875edef5141134fc", "size": 6962, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/stats/distribution/gamma.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/math/stats/distribution/gamma.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/math/stats/distribution/gamma.hpp", "max_forks_repo_name": "sguazt/dcsxx-commons", "max_forks_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4714828897, "max_line_length": 143, "alphanum_fraction": 0.6772479173, "num_tokens": 1980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4301029023091603}}
{"text": "/*\n Copyright (C) 2019 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/ \n\n#include <qle/instruments/brlcdiswap.hpp>\n\n#include <qle/cashflows/brlcdicouponpricer.hpp>\n#include <qle/cashflows/couponpricer.hpp>\n#include <ql/cashflows/overnightindexedcoupon.hpp>\n#include <ql/cashflows/simplecashflow.hpp>\n#include <ql/time/schedule.hpp>\n#include <ql/time/daycounters/business252.hpp>\n#include <boost/assign/list_of.hpp>\n\nusing namespace QuantLib;\nusing boost::assign::list_of;\nusing std::vector;\nusing std::pow;\n\nnamespace QuantExt {\n\n// Reason for use of convert_to_container:\n// https://stackoverflow.com/a/17805923/1771882\nBRLCdiSwap::BRLCdiSwap(Type type, Real nominal, const Date& startDate, const Date& endDate, Rate fixedRate, \n    const boost::shared_ptr<BRLCdi>& overnightIndex, Spread spread, bool telescopicValueDates) \n    : OvernightIndexedSwap(type, nominal, Schedule(list_of(startDate)(endDate).convert_to_container<vector<Date> >(), \n        NullCalendar(), QuantLib::Unadjusted, QuantLib::Unadjusted, 100 * Years), fixedRate, \n        overnightIndex->dayCounter(), overnightIndex, spread, 0, ModifiedFollowing, overnightIndex->fixingCalendar(), \n        telescopicValueDates), startDate_(startDate), endDate_(endDate), index_(overnightIndex) {\n\n    // Need to overwrite the fixed leg with the correct fixed leg for a standard BRL CDI swap\n    // Fixed leg is of the form: N [(1 + k) ^ \\delta - 1]\n    // where \\delta is the number of BRL business days in the period divided by 252 i.e. \n    // the day count fraction for the period on a Business252 basis.\n    Time dcf = index_->dayCounter().yearFraction(startDate_, endDate_);\n    Real fixedLegPayment = nominal * (pow(1.0 + fixedRate, dcf) - 1.0);\n    Date paymentDate = legs_[0].back()->date();\n    boost::shared_ptr<CashFlow> fixedCashflow = boost::make_shared<SimpleCashFlow>(fixedLegPayment, paymentDate);\n    legs_[0].clear();\n    legs_[0].push_back(fixedCashflow);\n    registerWith(fixedCashflow);\n\n    // Set the pricer on the BRL CDI coupon\n    QL_REQUIRE(legs_[1].size() == 1, \"BRLCdiSwap expected exactly one overnight coupon\");\n    boost::shared_ptr<OvernightIndexedCoupon> coupon = boost::dynamic_pointer_cast<OvernightIndexedCoupon>(legs_[1][0]);\n    coupon->setPricer(boost::make_shared<BRLCdiCouponPricer>());\n}\n\nReal BRLCdiSwap::fixedLegBPS() const {\n    \n    calculate();\n\n    static Spread basisPoint = 1.0e-4;\n    if (!close(endDiscounts_[0], 0.0) && endDiscounts_[0] != Null<DiscountFactor>()) {\n        DiscountFactor df = endDiscounts_[0];\n        Time dcf = index_->dayCounter().yearFraction(startDate_, endDate_);\n        legBPS_[0] = df * nominal() * (pow(1.0 + fixedRate() + basisPoint, dcf) - pow(1.0 + fixedRate(), dcf));\n        return legBPS_[0];\n    }\n\n    QL_FAIL(\"BRLCdiSwap cannot calculate fixed leg BPS because end discount is not populated\");\n}\n\nReal BRLCdiSwap::fairRate() const {\n    \n    calculate();\n    \n    if (!close(endDiscounts_[0], 0.0) && endDiscounts_[0] != Null<DiscountFactor>()) {\n        DiscountFactor df = endDiscounts_[0];\n        Time dcf = index_->dayCounter().yearFraction(startDate_, endDate_);\n        return pow(overnightLegNPV() / (nominal() * df) + 1.0, 1.0 / dcf) - 1.0;\n    }\n\n    QL_FAIL(\"BRLCdiSwap cannot calculate fair rate because end discount is not populated\");\n}\n\n}\n", "meta": {"hexsha": "5e84393fa0e9dc53b78c03f7b5e0a7c5106e1346", "size": 3982, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/instruments/brlcdiswap.cpp", "max_stars_repo_name": "PiotrSiejda/Engine", "max_stars_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantExt/qle/instruments/brlcdiswap.cpp", "max_issues_repo_name": "PiotrSiejda/Engine", "max_issues_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/qle/instruments/brlcdiswap.cpp", "max_forks_repo_name": "PiotrSiejda/Engine", "max_forks_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T02:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T02:04:10.000Z", "avg_line_length": 43.2826086957, "max_line_length": 120, "alphanum_fraction": 0.7237569061, "num_tokens": 1043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.42973515946269564}}
{"text": "#include <cmath>\n#include <fstream>\n#include <string>\n\n#include <boost/timer/timer.hpp>\n\n#include \"optimization.hh\"\n#include \"adaptive_refinement.hh\"\n#include \"linalg/linearsystem.hh\"\n#include \"linalg/triplet.hh\"\n#include \"./opt_aux/src/include/Fmin.h\"\n#include \"modelCreator.hh\"\n#include \"modelFunctions.hh\"\n\n#ifndef Cygwin\nusing std::to_string;\n#else\nstd::string to_string(size_t n)\n{\n  std::stringstream s; s << n; return s.str();\n}\n#endif\n\nnamespace Kaskade\n{\n  OptimizationParameters::OptimizationParameters(double desiredAccuracy_, int maxSteps_) : desiredAccuracy(desiredAccuracy_), maxSteps(maxSteps_) {}\n  \n  void OptimizationParameters::setThetaAim(double theta) { ThetaAim = theta; ensureAdmissibleThetas(); }\n  void OptimizationParameters::setThetaNormal(double theta) { ThetaNormal = theta; ensureAdmissibleThetas(); }\n  void OptimizationParameters::setThetaMax(double theta) { ThetaMax = theta; ensureAdmissibleThetas(); }\n  void OptimizationParameters::setThetas(double thetaNormal, double thetaAim, double thetaMax)\n  {\n    ThetaNormal = thetaNormal;\n    ThetaAim = thetaAim;\n    ThetaMax = thetaMax;\n    ensureAdmissibleThetas();\n  }\n  void OptimizationParameters::setEps(double eps_)\n  {\n    eps = eps_;\n    sqrtEps = sqrt(eps);\n    thirdSqrtEps = pow(eps,1./3.);\n  }\n\n  double OptimizationParameters::getThetaAim() const { return ThetaAim; }\n  double OptimizationParameters::getThetaNormal() const { return ThetaNormal; }\n  double OptimizationParameters::getThetaMax() const { return ThetaMax; }\n  double OptimizationParameters::getEps() const { return eps; }\n  double OptimizationParameters::getSqrtEps() const { return sqrtEps; }\n  double OptimizationParameters::getThirdSqrtEps() const { return thirdSqrtEps; }\n\n  void OptimizationParameters::ensureAdmissibleThetas()\n  {\n    if( !(ThetaAim < ThetaMax) ) \n    {\n      std::cout << \"OPTIMIZATION PARAMETERS: Warning: Inconsistent algorithmic parameters. (ThetaMax <= ThetaAIm)\" << std::endl;\n      std::cout << \"OPTIMIZATION PARAMETERS: Adjusting ThetaAim from \" << ThetaAim << \" to \";\n      ThetaAim = 0.9*ThetaMax;\n      std::cout << ThetaAim << std::endl;\n    } \n    if( !(ThetaNormal < ThetaAim) ) \n    {\n      std::cout << \"OPTIMIZATION PARAMETERS: Warning: Inconsistent algorithmic parameters. (ThetaAim <= ThetaNormal)\" << std::endl;\n      std::cout << \"OPTIMIZATION PARAMETERS: Adjusting ThetaNormal from \" << ThetaNormal << \" to \";\n      ThetaNormal = 0.9*ThetaAim;\n      std::cout << ThetaNormal << std::endl;\n    }     \n  }\n  \n  Optimization::~Optimization(){}\n\n  Optimization::Optimization(AbstractScalarProduct& nL, AbstractScalarProduct& nC, AbstractChart const& chart_, OptimizationParameters const& p_,\n                             AbstractCompositeStepErrorEstimator* errorEstimator_, int verbose_)\n    : normL(nL), normC(nC), chart(chart_.clone()), p(p_), errorEstimator(errorEstimator_),\n      verbose(verbose_),L(verbose), C(verbose)\n  {}\n\n  Optimization::Optimization(AbstractNormalDirection& normalSolver,\n                             AbstractTangentialSpace& tangentSpace_,\n                             AbstractScalarProduct& nL,\n                             OptimizationParameters const& p_, \n                             double omegaCinit, double omegaLinit, int verbose_):\n    normL(nL),\n    normC(nL),\n    chart(new PrimalChart()),\n    p(p_),\n    normalDirection(&normalSolver),\n    tangentSpace(&tangentSpace_),\n    verbose(verbose_),\n    L(verbose,omegaLinit), C(verbose,omegaCinit)\n  {}\n\n\n  Optimization::Optimization(AbstractNormalDirection& normalSolver,\n                             AbstractScalarProduct& nL,\n                             AbstractScalarProduct& nC,\n                             AbstractChart const& chart_,\n                             OptimizationParameters const& p_, int verbose_):\n    normL(nL),\n    normC(nC),\n    chart(chart_.clone()),\n    p(p_),\n    normalDirection(&normalSolver),\n    verbose(verbose_),\n    L(verbose), C(verbose)\n  {}\n\n  /// Return true, if convergence is detected, false otherwise\n  Convergence Optimization::convergenceTest(double nu, std::vector<double> const& tau, double normOfCorrection) const\n  {\n    if( verbose > 0 )\n    {\n      std::cout << csPre << \"Desired accuracy: \" << p.desiredAccuracy << \", ||x|| = \" << normOfIterate << std::endl;\n      std::cout << csPre << \"||dx|| = \" << normOfCorrection << std::endl;\n    }\n\n    //if( nu > 0.1 && normOfCorrection < p.getEps() ) return Convergence::Achieved;\n\n    if( !tangentSpace->localConvergenceLikely() ) return Convergence::Missed;\n\n    // no local convergence as long as at least one of the steps is damped\n    if( !noDamping(nu) || !noDamping(tau) ) return Convergence::Missed;\n    if( normOfCorrection < p.desiredAccuracy * normOfIterate ) return Convergence::Achieved;\n\n    return Convergence::Missed;\n  }\n\n\n  bool Optimization::adaptiveMeshRefinement(LagrangeLinearization& lin, double nu, std::vector<double> tau, AbstractFunctionSpaceElement const& correction)\n  {\n    double safetyFactorForDesiredAccuracy = 0.9;\n\n    if( !( noDamping(nu) && noDamping(tau) ) )\n    {\n      std::cout << csPre << \"Damping factors != 1 -> Skipping error estimation.\" << std::endl;\n      return false;\n    }\n\n    if(hbErrorEstimator->gridSize() > p.maxGridSize)\n    {\n      std::cout << csPre << \"Grid size: \" << hbErrorEstimator->gridSize() << \" > \" << p.maxGridSize << \". Skipping error estimation. \" << std::endl;\n      return false;\n    }\n\n      // estimate error\n    (*hbErrorEstimator)(lin, *iterate, correction, step, *iterate);\n\n    double absoluteError=hbErrorEstimator->estimatedAbsoluteError();\n    double requiredAbsoluteError=std::max(p.requiredRelativeError*normOfLastCorrection,p.desiredAccuracy*safetyFactorForDesiredAccuracy*normL(*iterate));\n    bool accuracyReached = absoluteError < requiredAbsoluteError;\n\n    if(verbose > 0)\n    {\n      std::cout << csPre << \"ERROR ESTIMATOR: err0=\" << p.requiredRelativeError*normOfLastCorrection << \", err1=\" << p.desiredAccuracy*safetyFactorForDesiredAccuracy << std::endl;\n      std::cout << csPre << \"ERROR ESTIMATOR: normOfAcceptedCorrection=\" << normOfLastCorrection << \", p.desiredAccuracy=\" << p.desiredAccuracy << std::endl;\n      std::cout << csPre << \"ERROR ESTIMATOR: absolute error: \" << absoluteError << \", required error: \" << requiredAbsoluteError << std::endl;\n    }\n\n    if(accuracyReached)\n    {\n      std::cout << \"ERROR ESTIMATOR: Discretization accuracy reached!\" << std::endl;\n      return false;\n    }\n\n    hbErrorEstimator->refineGrid();\n    return true;\n  }\n\n\n\n  int Optimization::runAlgorithm()\n  {\n    std::ofstream omegafile(\"omegas.log\");\n    std::ofstream coefffile(\"coeff.log\");\n    std::ofstream correctionfile(\"corrections.log\");\n    std::ofstream values(\"values.log\");\n    values.setf(std::ios::scientific,std::ios::floatfield);\n    values.precision(16);\n    std::ofstream steps(\"steps.log\");\n\n    double nu = 0;\n    std::vector<double> tau(1,0);\n    // Main loop\n    for( step=1 ; step <= p.maxSteps; ++step )\n    {\n      if(verbose > 0) std::cout <<  \"\\n --------------- Optimization-Step: \" << step << \" ----------------------\" << std::endl;\n\n      /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n      /* * * * * * * * * * * * * * * * Normal Step * * * * * * * * * * * * * * * * */\n      /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n      if( functionalN == nullptr ) std::cout << \"no normal lineraization\" << std::endl;\n      normalLinearization = functionalN->getLinearization(*iterate);\n      values << normalLinearization->eval() << std::endl;\n\n      normC.setOrigin(*normalLinearization);\n      normL.setOrigin(*normalLinearization);\n      std::unique_ptr<AbstractFunctionSpaceElement> normalStepResidual(iterate->initZeroVector()), adjointResidual(iterate->initZeroVector()), undampedStep(iterate->initZeroVector());\n      auto normalStepResult = computeNormalStep(normalStepResidual.get(),adjointResidual.get());\n\n      std::unique_ptr<AbstractFunctionSpaceElement> normalStep(std::move(normalStepResult.first)), adjointCorrection(std::move(normalStepResult.second));\n      undampedStep->axpy(1.0,*normalStep,\"primal\");\n      double normOfUndampedCorrection = 0;\n\n      double Lxdn_res = adjointResidual->applyAsDualTo(*normalStep,\"primal\")\n                      - normalStepResidual->applyAsDualTo(*adjointCorrection,\"primal\")\n                      + adjointResidual->applyAsDualTo(*normalStep,\"dual\");\n      if( verbose > 1 ) std::cout << csPre << \"Lxdn_res: \" << Lxdn_res << std::endl;\n      auto normNormal = normC( *normalStep );\n\n      // Predict damping factor for normal step\n      nu = (normNormal > 0) ? updateNormalStepDampingFactor(normNormal) : 1.;\n      if( verbose > 0 ) printNormalStep(normNormal,nu);\n\n      std::unique_ptr<AbstractFunctionSpaceElement> tmpIter(iterate->clone());\n      tmpIter->axpy(nu,*normalStep,\"primal\");\n      std::unique_ptr<AbstractLinearization> lin_x_nudn(functionalN->getLinearization(*tmpIter));\n\n      std::unique_ptr<AbstractFunctionSpaceElement> dc_x0_dn ( iterate->initZeroVector() );\n      normalLinearization->d2axpy(1.0,*dc_x0_dn, *normalStep, 2, 3, 0, 2);\n      double p_dc_x0_dn = iterate->applyAsDualTo(*dc_x0_dn,\"dual\");\n      double f_x1 = lin_x_nudn->eval();\n      double f_x0 = normalLinearization->eval();\n\n      double normalStepMonitor = ( ( std::fabs(f_x1 - f_x0) + std::fabs(p_dc_x0_dn) ) > 0 ) ? std::fabs( f_x1 - f_x0 + nu*p_dc_x0_dn - Lxdn_res ) / ( std::fabs(f_x1 - f_x0) + std::fabs(p_dc_x0_dn) ) : 0.;\n      if( normNormal < p.getSqrtEps()*normOfIterate || step == 1 ) normalStepMonitor = 0;\n      bool reliableQuadraticModel = true;//normalStepMonitor < 0.5;\n\n      if( verbose > 1 )\n      {\n        std::cout << \"f(x0) = \" << f_x0 << \", f(x1) = \" << f_x1 << \", nupc'(x0) = \" << nu << \"*\" << p_dc_x0_dn << std::endl;\n        std::cout << \"f(x1) - f(x0) = \" << f_x1 - f_x0 << std::endl;\n      }\n      if( verbose > 0 ) std::cout << csPre << \"NORMAL STEP MONITOR: \" << normalStepMonitor << \", is reliable: \" << reliableQuadraticModel << std::endl;\n\n      /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n      /* * * * * * * * * * * * * * * Tangential Step * * * * * * * * * * * * * * * */\n      /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n      double normTangential = 0;\n      normOfUndampedCorrection = normNormal;\n      std::vector<std::shared_ptr<AbstractFunctionSpaceElement> > tangentialBasis(1,iterate->clone());\n\n      std::unique_ptr<LagrangeLinearization> lagrangeLinearization(nullptr);\n\n      if(reliableQuadraticModel)\n      {\n        if(functionalT!=nullptr) tangentialLinearization = functionalT->getLinearization(*iterate);\n        else tangentialLinearization = nullptr;\n\n        lagrangeLinearization.reset(new LagrangeLinearization(normalLinearization.get(),tangentialLinearization.get(),*iterate));\n\n        tangentialBasis = computeTangentialStep(*lagrangeLinearization,*normalStep, nu, tau);\n        for(size_t i=0; i<tangentialBasis.size(); ++i) undampedStep->axpy(1.0,*tangentialBasis[i],\"primal\");\n        normTangential = normL(*tangentialBasis[0]);\n        normOfUndampedCorrection = normC(*undampedStep);\n      }\n      else\n      {\n        *tangentialBasis[0] *= 0;\n        tau[0] = 0;\n      }\n      if( verbose > 0 ) std::cout << csPre << \"Tangential step length: \" << normTangential << std::endl;\n      /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n      /* * * * * * * * * * * Lipschitz constants and damping * * * * * * * * * * * */\n      /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n      AcceptanceTest acceptanceTestResult = AcceptanceTest::Failed;\n      std::unique_ptr<AbstractFunctionSpaceElement> trialIterate(iterate->initZeroVector()), secondOrderCorrected(iterate->clone()), correction(iterate->initZeroVector());\n      double normCAtCorr = normNormal;\n      while(acceptanceTestResult != AcceptanceTest::Passed)\n      {\n        double eta = 1;\n        if( acceptanceTestResult == AcceptanceTest::LeftAdmissibleDomain ) nu *= 0.5;\n        else nu = updateNormalStepDampingFactor(normNormal);\n        if( verbose > 0 ) printNormalStep(normNormal,nu);\n        if(!reliableQuadraticModel)\n        {\n          correction = createCorrection(nu,*normalStep, tau, tangentialBasis);\n          normCAtCorr = normC(*correction);\n          // Compute Trial Iterate: first candidate: trialIterate = chart_x(dx)\n          *trialIterate *= 0;\n          chart->addPerturbation(*trialIterate,*correction,*normalLinearization);\n\n          std::unique_ptr<AbstractLinearization> lin_xplus(functionalN->getLinearization(*trialIterate));\n          auto simplifiedNormalStep = computeSimplifiedNormalStep( *lin_xplus, normalStepResidual.get());\n          simplifiedNormalStep->axpy( nu-1.0, *normalStep, \"primal\" );\n\n          updateConstraintD1LipschitzConstant( normC( *simplifiedNormalStep ), normCAtCorr );\n        }\n        else\n        {\n          QuadraticModelCreator quadraticModelCreator(*normalStep,tangentialBasis,*lagrangeLinearization,Lxdn_res);\n          NormModelCreator normModelCreatorL(*normalStep,tangentialBasis,normL);\n\n          QuadraticFunction normLModel(normModelCreatorL.create(nu));\n          QuadraticFunction quadraticModel(quadraticModelCreator.create(nu));\n          L.setL_xx(quadraticModel.quadraticPart[0][0]);\n          IsotropicCubicRegularization reg(normLModel,L.omega/6);\n          RegularizedQuadraticFunction cubic(quadraticModel, reg);\n          if( acceptanceTestResult == AcceptanceTest::LeftAdmissibleDomain ) tau[0] *= 0.5;\n          else updateTangentialDampingFactor(nu, normNormal, normTangential, cubic, tau);\n\n          // Compute Correction as a linear combination of normal step and basis vectors of tangent search space\n          correction = createCorrection(nu,*normalStep,tau,tangentialBasis);\n          auto normLAtCorr = sqrt(normLModel.d0(tau));\n          normCAtCorr = normC(*correction);\n          auto quadraticModelAtCorr = quadraticModel.d0(tau);\n          // Compute Trial Iterate: first candidate: trialIterate = chart_x(dx)\n          trialIterate = iterate->clone();\n          chart->addPerturbation(*trialIterate,*correction,*lagrangeLinearization);\n          if( !functionalN->inDomain(*trialIterate) || ( functionalT != nullptr && !functionalT->inDomain(*trialIterate) ) )\n          {\n            std::cout << csPre << \"Iterate leaves admissible domain: rejecting step.\" << std::endl;\n            acceptanceTestResult = AcceptanceTest::LeftAdmissibleDomain;\n          }\n          else\n          {\n            acceptanceTestResult = AcceptanceTest::Failed;\n            std::unique_ptr<AbstractLinearization> lin_xplus(functionalN->getLinearization(*trialIterate));\n            auto simplifiedNormalStep = computeSimplifiedNormalStep( *lin_xplus, normalStepResidual.get());\n            simplifiedNormalStep->axpy( nu-1.0, *normalStep, \"primal\" );\n            //for( size_t i = 0; i < tangentialBasis.size(); ++i ) simplifiedNormalStep->axpy( tau[i] - 1.0, *tangentialBasis[i], \"primal\" );\n\n            updateConstraintD1LipschitzConstant( normC( *simplifiedNormalStep ), normCAtCorr );\n\n            // Perform second order correction update secondOrderCorrected=chart_x(dx+ds)\n            std::unique_ptr<AbstractFunctionSpaceElement> secondOrderCorrection(simplifiedNormalStep->clone());\n            secondOrderCorrection->axpy(1.0,*correction,\"primal\");\n            *secondOrderCorrected = *iterate->clone();\n            chart->addPerturbation(*secondOrderCorrected,*secondOrderCorrection,*lagrangeLinearization);\n\n            eta = updateLagrangianD2LipschitzConstant(*lagrangeLinearization, *secondOrderCorrected, normLAtCorr, quadraticModelAtCorr, cubic, nu, tau,*normalStep,*trialIterate,*simplifiedNormalStep,*correction,Lxdn_res);\n          }\n        }\n\n        // Acceptance tests\n        if( acceptanceTestResult != AcceptanceTest::LeftAdmissibleDomain ) acceptanceTestResult = acceptanceTest(eta,nu,tau,normCAtCorr);\n        if(!regularityTest(nu,tau,reliableQuadraticModel)) return -1;\n\n        if( reliableQuadraticModel && (acceptanceTestResult==AcceptanceTest::TangentialStepFailed) && L.omega < (1 + 0.25*(1 - p.etaMin))*L.oldOmega )\n        {\n          if( verbose > 0 ) std::cout << csPre << \"Stagnating omegaL update. Accepting step.\" << std::endl;\n          acceptanceTestResult = AcceptanceTest::Passed;\n          if(eta < 0.1)\n          {\n            if( verbose > 0 ) std::cout << csPre << \"Ignoring tangential step.\" << std::endl;\n            for(size_t i=0; i<tangentialBasis.size(); ++i)\n            {\n              trialIterate->axpy(-tau[i],*tangentialBasis[i]);\n              secondOrderCorrected->axpy(-tau[i],*tangentialBasis[i]);\n            }\n          }\n        }\n\n        if(acceptanceTestResult == AcceptanceTest::Passed)\n        {\n          normOfLastCorrection = normCAtCorr;\n          normOfLastCorrection_Undamped = normOfUndampedCorrection;\n          correctionfile << normOfLastCorrection << \" \" << normL(*normalStep) << \" \" << normL(*tangentialBasis[0]) << std::endl;\n        }\n      }\n\n      // Error estimation\n      bool refinedMesh = false;\n      if( hbErrorEstimator != nullptr && tangentSpace->localConvergenceLikely()  && reliableQuadraticModel ) refinedMesh = adaptiveMeshRefinement(*lagrangeLinearization, nu,tau,*correction);\n\n      // at this point, *trialIterate is the combined step\n      // and *secondOrderCorrected is the second order corrected step\n      // if Theta > 0.25, this might be worse w.r.t feasibility than the original step\n      // use original step in this case\n      if(normalDirection)\n      {\n        if(C.theta > 0.25 || !reliableQuadraticModel)\n        {\n          if(verbose > 1) std::cout << csPre << \"Adding ordinary update\" << std::endl;\n        }\n        else\n        {\n          *trialIterate = *secondOrderCorrected;\n          if(verbose > 1) std::cout << csPre << \"Adding second order correction\" << std::endl;\n        }\n      }\n\n      iterate->swap(*trialIterate);\n      normOfIterate = normL(*iterate);\n//      *trialIterate -= *iterate;\n\n      /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n      /* * * * * * * * * * * * * * * * Write data  * * * * * * * * * * * * * * * * */\n      /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n      if( verbose > 0)\n      {\n        std::cout << \"\\n\" << csPre << \"Accepted step\" << std::endl;\n        printNormalStep(normNormal, nu);\n        printTangentialStep(normTangential, tau[0]);\n      }\n\n      if( verbose > 1 )\n      {\n        std::string name = std::string(\"iterate_\") + to_string(step);\n        iterate->writeToFile(name,false);\n      }\n\n      omegafile << \" \" << L.omega << \" \" << \" \" << C.omega << \" \" << std::endl;\n      coefffile << nu << \"  \" << tau[0] << std::endl;\n\n      if( !refinedMesh && convergenceTest(nu,tau,normL(*correction)) == Convergence::Achieved )\n      {\n        steps << step << std::endl;\n\n        if( verbose > 1 )\n        {\n          std::cout << csPre << \"overall normal step computation time: \" << normalStepComputationTime << std::endl;\n          std::cout << csPre << \"overall tangential step computation time: \" << tangentialStepComputationTime << std::endl;\n        }\n        return 1;\n      }\n    }\n    return -2;\n  }\n\n  void Optimization::solve(AbstractFunctional &fN, AbstractFunctional& fT, AbstractFunctionSpaceElement &x) { solve(fN,&fT,x); }\n\n  void Optimization::solve(AbstractFunctional& fN, AbstractFunctional* fT,AbstractFunctionSpaceElement& x)\n  {\n    functionalN = &fN;\n    functionalT = fT;\n\n    iterate = x.clone();\n    normalStepComputationTime = tangentialStepComputationTime = 0;\n    if( tangentSpace != nullptr ) tangentSpace->setEps(p.getEps());\n\n    normOfLastCorrection = normOfLastCorrection_Undamped = -1;\n    normOfIterate = 0;\n    auto terminationFlag = algorithmWrapper();\n    if(terminationFlag > 0 || terminationFlag == -2) x=*iterate;\n  }\n\n  void Optimization::solve(AbstractFunctional& fN, AbstractFunctional& fT, AbstractFunctionSpaceElement& x, AbstractHierarchicalErrorEstimator& hbErrorEstimator_)\n  {\n    hbErrorEstimator = &hbErrorEstimator_;\n    solve(fN,fT,x);\n  }\n\n\n  void Optimization::solve(AbstractFunctional& f, AbstractFunctionSpaceElement& x, AbstractHierarchicalErrorEstimator& hbErrorEstimator_)\n  {\n    hbErrorEstimator = &hbErrorEstimator_;\n    solve(f,nullptr,x);\n  }\n\n  bool Optimization::regularityTest(double nu, std::vector<double> const& tau, bool reliableQuadraticModel) const\n  {\n    bool passed = nu > p.minimalDampingFactor;\n    if(reliableQuadraticModel) passed = passed && tau[0] > p.minimalDampingFactor;\n    if(verbose > 0 && !passed) std::cout << csPre << \"Regularity test failed!!!\" << std::endl;\n    return passed;\n  }\n\n  std::pair<std::unique_ptr<AbstractFunctionSpaceElement>,std::unique_ptr<AbstractFunctionSpaceElement> > Optimization::computeNormalStep(AbstractFunctionSpaceElement* normalStepResidual, AbstractFunctionSpaceElement* adjointResidual)\n  {\n    std::pair<std::unique_ptr<AbstractFunctionSpaceElement>,std::unique_ptr<AbstractFunctionSpaceElement> > result(iterate->clone(),iterate->clone());\n    *(result.first) *= 0;\n    *(result.second) *= 0;\n\n    if(normalDirection) // constrained problem\n    {\n      // Compute normal step, compute update for Lagrange multiplier\n      if( step > 1 && std::fabs(normOfLastCorrection_Undamped-normOfLastCorrection) < p.getEps() * normOfLastCorrection_Undamped) normalDirection->setRelativeAccuracy(std::max(std::min(p.minimalAccuracy, C.omega*normOfLastCorrection),p.desiredAccuracy));\n      else normalDirection->setRelativeAccuracy(p.minimalAccuracy);\n      boost::timer::cpu_timer timer;\n      normalDirection->ordinaryAndAdjoint(*(result.first), *(result.second), *normalLinearization, normalStepResidual, adjointResidual);\n      normalStepComputationTime += (double)timer.elapsed().wall*1e-9;\n\n      if( verbose > 1 ) std::cout << \"normal step computation time: \" << boost::timer::format(timer.elapsed()) << std::endl;\n\n      iterate->axpy(1.0,*(result.second),\"dual\");\n    }\n    else // unconstrained problem\n      if(verbose > 0) std::cout << csPre << \"Unconstrained Problem\" << std::endl;\n    \n    return result;\n  }\n\n  std::vector<std::shared_ptr<AbstractFunctionSpaceElement> > Optimization::computeTangentialStep(LagrangeLinearization& lagrangeLinearization, AbstractFunctionSpaceElement const& normalStep, double nu, std::vector<double> const& tau)\n  {\n    std::vector<std::shared_ptr<AbstractFunctionSpaceElement> > tangentialBasis;\n    tangentialBasis.resize(1,std::shared_ptr<AbstractFunctionSpaceElement>(iterate->clone())); *(tangentialBasis[0]) *= 0;\n\n    if(!tangentSpace) return tangentialBasis;\n\n    double relativeAccuracy = std::max(p.desiredAccuracy,std::min(p.minimalAccuracy, L.omega * std::fabs(normOfLastCorrection)));\n    if(step > 1 && std::fabs(normOfLastCorrection_Undamped-normOfLastCorrection) < p.getEps() * normOfLastCorrection_Undamped && noDamping(nu))\n    {\n      if(tangentSpace) tangentSpace->setRelativeAccuracy(relativeAccuracy);\n      if(verbose > 1)\n      {\n        std::cout << csPre << \"desired contraction: \" << p.getThetaAim() << std::endl;\n      }\n    }\n    else tangentSpace->setRelativeAccuracy(p.minimalAccuracy);// * std::min(1.,normOfLastCorrection_Undamped));\n\n    boost::timer::cpu_timer timer;\n    tangentSpace->setLipschitzConstant(L.omega);\n    tangentSpace->basis(tangentialBasis, lagrangeLinearization, normalStep, nu, nullptr);\n    tangentialStepComputationTime += (double) timer.elapsed().wall * 1e-9;\n\n    if( verbose > 1 ) std::cout << \"tangential step computation time: \" << boost::timer::format(timer.elapsed()) << std::endl;\n\n    return tangentialBasis;\n  }\n\n  double Optimization::updateNormalStepDampingFactor(double normNormal) const\n  {\n    double nu = 1;\n    if(normNormal > p.getEps() && std::fabs(normNormal*C.omega) > p.getEps()) nu = std::min(1.0,/*2.0*/p.getThetaNormal()/(C.omega*normNormal));\n    if(noDamping(nu)) nu = 1;\n    return nu;\n  }\n\n  void Optimization::updateTangentialDampingFactor(double nu, double normNormal, double normTangential, RegularizedQuadraticFunction const& cubic, std::vector<double> &tau) const\n  {\n    if( tau.size()==1 )\n    {\n      tau[0] = 1.0;\n\n      if( normTangential < p.getSqrtEps() ) return;\n\n      double maxTauMax = 1;\n      double taumax = maxTauMax;\n      if( C.omega != 0.0  )\n      {\n        if( ( pow(p.getThetaAim()/C.omega,2)-pow(nu*normNormal,2) ) > 0 && normTangential > 0) taumax = sqrt(pow(p.getThetaAim()/C.omega,2)/*-pow(nu*normNormal,2)*/)/normTangential;//std::min(1.,normTangential);\n\n        if( taumax > maxTauMax && tangentSpace->localConvergenceLikely() )\n        {\n          if( verbose > 1 ) std::cout << csPre << \"reducing taumax: \" << taumax << \" to \" << maxTauMax << std::endl;\n          taumax = maxTauMax;\n        }\n      }\n      if( verbose > 1 ) std::cout << csPre << \"taumax: \" << taumax << std::endl;\n\n      if( taumax > 0.0 )\n      {\n        CubicModel1dForFmin cubicmodel(cubic);\n        double toleranceFmin = p.getThirdSqrtEps()*std::min(taumax,1.);\n        double taumin = 0;\n        tau[0] = Fmin(taumin,taumax,cubicmodel,toleranceFmin);\n      }\n\n      if( noDamping(tau) ) tau[0]=1.0;\n    }\n    else\n    {\n      if( tau.size() > 1 )\n      {\n        std::cout << csPre << \"Multidimensional search space not implemented\" << std::endl;\n        exit(-1);\n      }\n    }\n\n  }\n\n  std::unique_ptr<AbstractFunctionSpaceElement> Optimization::computeSimplifiedNormalStep(AbstractLinearization const& lin_xplus, AbstractFunctionSpaceElement* normalStepResidual)\n  {\n    std::unique_ptr<AbstractFunctionSpaceElement> simplifiedNormalStep(iterate->initZeroVector());\n    if(!normalDirection) return simplifiedNormalStep;\n\n    normalDirection->simplified(*simplifiedNormalStep,lin_xplus,nullptr);\n    return simplifiedNormalStep;\n  }\n\n  void Optimization::updateConstraintD1LipschitzConstant(double normSimplifiedNormal, double normCAtCorr)\n  {\n    if( verbose > 1 ) std::cout << csPre << \"normCAtCorr = \" << normCAtCorr << \", normSimplifiedNormal = \" << normSimplifiedNormal << std::endl;\n//    if( normCAtCorr > p.getEps() )\n    {\n      C.theta = normSimplifiedNormal/normCAtCorr; // contraction rate \n      bool lock = (C.theta < 0.25 && (normCAtCorr < p.getSqrtEps()*normOfIterate || normSimplifiedNormal < p.getEps()*normOfIterate) );\n      C.update(2*C.theta/normCAtCorr, lock);\n    }\n  }\n\n  double Optimization::updateLagrangianD2LipschitzConstant(AbstractLinearization const& lin_x0, AbstractFunctionSpaceElement const& secondOrderCorrected, double normLAtCorr, double quadraticModelAtCorr, RegularizedQuadraticFunction const& cubic, double nu, std::vector<double> const& tau,\n                                                           AbstractFunctionSpaceElement const& normalStep, AbstractFunctionSpaceElement const& trialIterate, AbstractFunctionSpaceElement const& sNormalStep, AbstractFunctionSpaceElement const& correction, double Lxdn_res)\n  {\n    double eta = 1;\n    if( tangentSpace == nullptr ) return eta;\n\n    std::unique_ptr<AbstractLinearization> lin_xplus(functionalN->getLinearization(trialIterate));\n    auto f_x0 = lin_x0.eval();\n    // compute: f(x_)-q(x)dx or alternative if high round-off is expected\n    double deltaf(0.0);\n    auto zero = tau;\n    for(double& d : zero) d = 0;\n\n//    if(normalDirection)\n//    {\n//      std::unique_ptr<AbstractFunctionSpaceElement> dc_x0_dn ( iterate->initZeroVector() ), lxxdn( iterate->initZeroVector() );\n//      lin_x0.d2axpy(1.0, *lxxdn, normalStep, 0, 2, 0, 2);\n//      lin_x0.d2axpy(1.0, *dc_x0_dn, normalStep, 2, 3, 0, 2);\n//      double p_dc_x0_dn = iterate->applyAsDualTo(*dc_x0_dn,\"dual\");\n//      double lxxdndn = normalStep.applyAsDualTo(*lxxdn);\n      std::unique_ptr<AbstractLinearization> lin_xbar=functionalN->getLinearization(secondOrderCorrected);\n      deltaf=lin_xbar->eval()-f_x0;\n      double deltaf_cor = deltaf - cubic.d0(zero);\n      if(std::fabs(cubic.d0(tau) - cubic.d0(zero)) > p.getSqrtEps()*normOfIterate/* && std::fabs(deltaf_cor) > p.getSqrtEps()*/) eta = deltaf_cor/( cubic.d0(tau) - cubic.d0(zero) ) ;\n      else eta = 1;\n      if( verbose > 1 )\n      {\n        std::cout << csPre << \"predicted decrease: \" << (cubic.d0(tau) - cubic.d0(zero)) << std::endl;\n        std::cout << csPre << \"actual decrease: \" << deltaf_cor << std::endl;\n        std::cout << csPre << \" eta = \" << eta << std::endl;\n      }\n      L.setFirstOrder( normLAtCorr, C.theta, deltaf - quadraticModelAtCorr );\n\n\n//    }\n//    else { assert(\"not implemented\"); }\n\n    if(L.highRoundOffError(true,p.getEps()*f_x0))\n    {\n      std::unique_ptr<AbstractFunctionSpaceElement> tmp1=iterate->clone();\n      // tmp1 = chart_x(0)-chart_x(dx+ds)\n      *tmp1 -= secondOrderCorrected;\n\n      lin_xbar->evald(*tmp1);\n      double p0_c_xbar=tmp1->applyAsDualTo(*iterate,\"dual\");  // p0 is dual component of *iterate\n\n      double p0_c_x0(0.0);\n      if(!noDamping(nu))\n      {\n        lin_x0.evald(*tmp1);\n        p0_c_x0=tmp1->applyAsDualTo(*iterate,\"dual\");     // p0 is dual component of *iterate\n      }\n\n      // Lx_xplus_ds = L_x(x_+,p_0) ds\n      double Lx_xplus_ds(0.0);\n      lin_xplus->evald(*tmp1);\n      Lx_xplus_ds=tmp1->applyAsDualTo(sNormalStep,\"primal\"); // delta s is primal component of *snormalStep\n\n      // secondorderestimate [ (L_x(x_+,p0)-L_x(x0,p0)-L_xx(x0,p0)dx)dx ] + [ L_x(x_+,p0)ds ]-[ p0 c(xbar)-(1-nu)p0 c(x0) ]\n      // each term in [...] is third order.\n      // the summands in the first (...) are first order (close to solution), the difference is second order -> first order round-off error effects\n      // close to a solution where nu = 1, the very last term vanishes -> then no other round-off error effects\n      // if nu is very small, and c(x_0) approx c(xbar), then round-off error is expected (try alternative?)\n\n      // tmp1 = L_x(x0,p0)+L_xx(x0,p0)dx\n      lin_x0.evald(*tmp1);\n      lin_x0.ddxpy(*tmp1,correction);\n\n      // tmp2=L_x(x_+,p0)-L_x(x0,p0)-L_xx(x0,p0)dx\n      std::unique_ptr<AbstractFunctionSpaceElement> tmp2=iterate->clone();\n      lin_xplus->evald(*tmp2);\n      (*tmp2)-=(*tmp1);\n\n      L.setSecondOrder(0.5*tmp2->applyAsDualTo(correction,\"primal\")+0.5*Lx_xplus_ds-(p0_c_xbar-(1-nu)*(p0_c_x0-Lxdn_res)));\n    }\n\n    L.update( std::fabs( eta - 1. ) < (1.-p.etaLock) );\n\n    if(verbose > 1)\n    {\n      std::cout << csPre << \"f(x_0): \" << f_x0 << \" f(x): \"  << f_x0+deltaf << \"  |  Decrease: \" << -deltaf << std::endl;\n      std::cout << csPre << \"Quadratic model q(x):\" << f_x0+quadraticModelAtCorr << std::endl;\n      std::cout << csPre << \"q(x)-f(x_0): \" << quadraticModelAtCorr << std::endl;\n      std::cout << csPre << \"q(x)-f(x): \" << quadraticModelAtCorr-deltaf << std::endl;\n    }\n\n    return eta;\n  }\n\n\n  AcceptanceTest Optimization::acceptanceTest(double eta, double nu, std::vector<double> const& tau, double normOfCorrection) const\n  {\n    if( nu > 0.1 && normOfCorrection < p.getEps() ) return AcceptanceTest::Passed;\n    if( noDamping(nu) && noDamping(tau) && (normOfCorrection) < p.getSqrtEps() ) return AcceptanceTest::Passed;\n    \n    if( eta < p.etaMin )\n    {\n      if( verbose > 0 ) std::cout << csPre << \"Rejecting due to small eta: \" << eta << \" < \" << p.etaMin << std::endl;\n      return AcceptanceTest::TangentialStepFailed;\n    }\n    \n    if(C.theta > p.getThetaMax())\n    {\n      if(verbose > 0) std::cout << csPre << \"Insufficient contraction:\" << C.theta << \" > \" << p.getThetaMax() << std::endl;\n      return AcceptanceTest::NormalStepFailed;\n    }\n\n    return AcceptanceTest::Passed;\n  }\n\n  bool Optimization::noDamping(double d) const\n  {\n    return std::fabs(d-1.) < dampingFactorTolerance;\n  }\n\n  bool Optimization::noDamping(std::vector<double> const& tau) const\n  {\n    for(double d : tau) if(!noDamping(d)) return false;\n    return true;\n  }\n\n\n  void Optimization::terminationMessage(int flag)\n  {\n    switch(flag)\n    {\n      case 1  : std::cout << csPre << \"Desired accuracy reached!\" << std::endl; break;\n      case -1 : std::cout << csPre << \"Regularity test failed!\" << std::endl;; break;\n      case -2 : std::cout << csPre << \"Maximum number of iterations reached!\" << std::endl; break;\n      default : Algorithm::terminationMessage(flag);\n    }\n  }\n\n  void Optimization::printNormalStep(double normNormal, double nu) const\n  {\n    std::cout << csPre << \"Normal step: \" << normNormal << std::endl;\n    std::cout << csPre << \"Damping factor: \" << nu << std::endl << std::endl;\n  }\n\n  void Optimization::printTangentialStep(double normTangential, double tau) const\n  {\n    std::cout << csPre << \"Tangential step: \" << normTangential << std::endl;\n    std::cout << csPre << \"Damping factor: \" << tau << std::endl << std::endl;\n\n  }\n\n  std::unique_ptr<AbstractFunctionSpaceElement> Optimization::createCorrection(double nu, const AbstractFunctionSpaceElement &normalStep, const std::vector<double> &tau, const std::vector<std::shared_ptr<AbstractFunctionSpaceElement> > &tangentialBasis) const\n  {\n    std::unique_ptr<AbstractFunctionSpaceElement> correction(normalStep.clone());\n    *correction *= 0.0;\n    correction->axpy(nu,normalStep,\"primal\");\n    for(size_t i=0; i<tangentialBasis.size();++i) correction->axpy(tau[i],*tangentialBasis[i],\"primal\");\n    return correction;\n  }\n\n  void Optimization::addCorrection(AbstractFunctionSpaceElement &v, double nu, const AbstractFunctionSpaceElement &normalStep, const std::vector<double> &tau, const std::vector<std::shared_ptr<AbstractFunctionSpaceElement> > &tangentialBasis) const\n  {\n    v.axpy(nu,normalStep,\"primal\");\n    for(size_t i=0; i<tangentialBasis.size(); ++i) v.axpy(tau[i],*tangentialBasis[i],\"primal\");\n  }\n}  // namespace Kaskade\n", "meta": {"hexsha": "75b2b5eddda8b5cbc81cf476e8acf776994722b1", "size": 33823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/algorithm/optimization.cpp", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/algorithm/optimization.cpp", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/algorithm/optimization.cpp", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 45.5222072678, "max_line_length": 288, "alphanum_fraction": 0.6458622831, "num_tokens": 9389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4296063949443668}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <vector>\n#include <unordered_set>\n#include <numeric>\n#include <iterator>\n#include <queue>\n#include <iostream>\n\ntemplate <int _Dims>\nclass Optimize {\npublic:\n    typedef Eigen::Array<float,_Dims,1> vars_type;\n    typedef std::function<float(vars_type)> funk_type;\n\n    Optimize(funk_type funk, vars_type min_bounds = -vars_type::Ones(), vars_type max_bounds = vars_type::Ones());\n    ~Optimize() {};\n\n    void setNumObservations(int num_observations) {num_observations_ = num_observations;};\n    void setMaxDepth(int max_depth) {max_depth_ = max_depth;};\n    void setThreshold(float threshold) {threshold_ = threshold;};\n    void setMaxIterations(int max_iterations) {max_iterations_=max_iterations;};\n\n    Optimize<_Dims>::vars_type run();\n\nprivate:\n\n    static int powint(int x, int p)//https://stackoverflow.com/a/1505791\n    {\n        if (p == 0) return 1;\n        if (p == 1) return x;\n        int tmp = powint(x, p/2);\n        if (p%2 == 0) return tmp * tmp;\n        else return x * tmp * tmp;\n    }\n\n    struct Split {\n        int dimension;\n        int left_index;\n        int right_index;\n        bool left_right; //Keep left or right side of split\n        Split(int dim, int left_idx, int right_idx, bool lr) : dimension(dim), left_index(left_idx), right_index(right_idx), left_right(lr){};\n    };\n\n    struct Partition {\n        std::vector<Split> splits;\n        std::vector<int> elements;\n\n        bool getClass(const Eigen::Matrix<float,-1,_Dims+1> & data, float threshold){\n            int low = 0;\n            for (auto ind : elements) {\n                if (data(ind,data.cols()-1) < threshold)\n                    low++;\n            }\n            return ((float) low / (float) elements.size())<=0.5;\n        };\n\n        void getBounds(const Eigen::Matrix<float,-1,_Dims+1> & data, vars_type & min, vars_type & max){\n            for (auto split : splits){\n                float x_left = data(split.left_index,split.dimension);\n                float x_right = data(split.right_index,split.dimension);\n                float x_mid = (x_left+x_right)/2;\n                if (split.left_right) {\n                    if (min(split.dimension) < x_mid)\n                        min(split.dimension) = x_mid;\n                } else {\n                    if (max(split.dimension) > x_mid)\n                        max(split.dimension) = x_mid;\n                }\n            }\n        };\n    };\n    \n    funk_type funk_;\n    vars_type min_bounds_;\n    vars_type max_bounds_;\n\n    int num_observations_ = 125;\n    float threshold_ = 3;\n    int max_depth_ = 10;\n    int max_iterations_ = 10;\n    float tolerance_ = 1e-6;\n\n    Eigen::Matrix<float,-1,_Dims+1> data_;\n    Eigen::Matrix<float,_Dims,_Dims> householder_ = Eigen::Matrix<float,_Dims,_Dims>::Identity();\n    \n    //Sample randomly from bounds\n    Eigen::Matrix<float,-1,_Dims+1> randSample(int n);\n    Eigen::Matrix<float,-1,_Dims+1> randSampleLow(int n, const std::vector<vars_type> & mins, const std::vector<vars_type> & maxs);\n\n    //Generates observations from random samples\n    void generateData() {\n        data_ = randSample(num_observations_); \n    };\n    void generateDataLow(const std::vector<vars_type> & mins, const std::vector<vars_type> & maxs) {\n        data_ = randSampleLow(num_observations_, mins, maxs); \n    };\n\n    //Sorts along each dimension and stores permutation\n    void sortData();\n    std::array<std::vector<int>,_Dims> permutations_;\n\n\n    float calculateGini(const std::vector<bool> & classified, int start, int end);\n    int findSplit(const Partition & main_part, Partition & left_part, Partition & right_part);\n\n    bool withinUnion(const vars_type & x, const std::vector<vars_type> & mins, const std::vector<vars_type> & maxs);\n\n};\n\n// Implementation\ntemplate <int _Dims>\nOptimize<_Dims>::Optimize(Optimize::funk_type funk, Optimize::vars_type min_bounds, Optimize::vars_type max_bounds) :\n    funk_(funk), \n    min_bounds_(min_bounds), \n    max_bounds_(max_bounds)\n{\n}\n\ntemplate <int _Dims>\ntypename Optimize<_Dims>::vars_type Optimize<_Dims>::run()\n{\n    //place box\n    generateData();\n\n    //partition box\n    std::vector<int> v(num_observations_);\n    std::iota(v.begin(),v.end(),0);\n\n    vars_type current_min = vars_type::Zero();\n    float current_min_f = std::numeric_limits<float>::max();\n\n    for (int k = 0; k < max_iterations_; k++){\n        //PCA to find dominant direction of hyper-ellipse\n        Eigen::JacobiSVD<Eigen::Matrix<float,-1,_Dims>> svd(data_.block(0,0,num_observations_,_Dims), Eigen::ComputeThinU | Eigen::ComputeThinV);\n        svd.computeV();\n        vars_type dominant = svd.matrixV().template block<1,_Dims>(0,0).transpose();\n        //Get Householder transformation matrix\n        vars_type e1 = vars_type::Zero();\n        e1(0) = 1;\n        vars_type u = e1 - dominant;\n        u.matrix().normalize();\n        householder_ = Eigen::Matrix<float,_Dims,_Dims>::Identity() - 2*u.matrix() * u.matrix().transpose();\n        \n        //Apply Householder transformation\n        bool no_transform = false;\n        if (!std::isnan(householder_.norm()) && !std::isnan(data_.block(0,0,num_observations_,_Dims).norm())){\n            data_.block(0,0,num_observations_,_Dims) = data_.block(0,0,num_observations_,_Dims).matrix() * householder_.transpose();\n        } else {\n            no_transform = true;\n        }        \n        sortData();\n        \n        std::queue<Partition> partition_queue;\n        std::vector<Partition> terminal;\n\n        Partition initial;\n        initial.elements = v;\n        partition_queue.push(initial);\n\n        int depth = 0;\n        while (depth < max_depth_){\n            std::queue<Partition> temp_queue;\n            while (!partition_queue.empty()){\n                auto part = partition_queue.front();\n                partition_queue.pop();\n\n                //Check stopping conditions\n                if (part.elements.size() <= 1){\n                    //terminal\n                    terminal.push_back(part);\n                    continue;\n                }\n\n                Partition left_part, right_part;\n                int split_ret = this->findSplit(part, left_part, right_part);\n\n                if (!split_ret) {\n                    terminal.push_back(part);\n                } else if (depth == max_depth_-1){\n                    terminal.push_back(left_part);\n                    terminal.push_back(right_part);\n                } else {\n                    temp_queue.push(left_part);\n                    temp_queue.push(right_part);\n                }\n            }\n            partition_queue = temp_queue;\n            depth++;\n        }\n\n        std::vector<vars_type> minimums;\n        std::vector<vars_type> maximums;\n        //Find bounding box in new coordinates\n        //We have 2^_Dims corners\n        vars_type new_min = householder_.transpose() * min_bounds_.matrix();\n        vars_type new_max = householder_.transpose() * max_bounds_.matrix();\n        for(int i = 0; i < powint(2,_Dims); i++) {\n            vars_type corner;\n            for (int j = 0; j < _Dims; j++){\n                if (i & powint(2,j))\n                    corner(j) = max_bounds_(j);\n                else \n                    corner(j) = min_bounds_(j);\n            }\n            vars_type corner_transformed = householder_.transpose() * corner.matrix();\n            for (int d = 0; d < _Dims; d++){\n                if (corner_transformed(d) < new_min(d))\n                    new_min(d) = corner_transformed(d);\n                if (corner_transformed(d) > new_max(d))\n                    new_max(d) = corner_transformed(d);\n            }\n        }\n        for (auto t : terminal) {\n            if (!t.getClass(data_,threshold_)){ //classified as low\n                vars_type min = new_min;\n                vars_type max = new_max;\n                t.getBounds(data_, min, max);\n                minimums.push_back(min);\n                maximums.push_back(max);\n            }\n        }\n \n        //Randomly sample in union of low partitions\n        generateDataLow(minimums,maximums);\n        \n        //Apply inverse Householder transformation\n        if (!no_transform){\n            data_.block(0,0,num_observations_,_Dims) = data_.block(0,0,num_observations_,_Dims).matrix() * householder_;\n        }\n\n        for (int i = 0; i < num_observations_; i++){\n            //Calculate f for new batch of points\n            data_(i,_Dims) = funk_(data_.template block<1,_Dims>(i,0));\n            //Check if f is new minimum\n            if (data_(i,_Dims) < current_min_f){\n                current_min = data_.template block<1,_Dims>(i,0);\n                current_min_f = data_(i,_Dims);\n            } \n        }\n    }\n    return current_min;\n}\n\ntemplate <int _Dims>\nEigen::Matrix<float,-1,_Dims+1> Optimize<_Dims>::randSample(int n)\n{\n    Eigen::Matrix<float,-1,_Dims+1> samples;\n    samples.resize(n,_Dims+1);\n    for (int i = 0; i < n; i++){\n        vars_type x = vars_type::Random();//between -1 and 1\n        x += 1;\n        x /= 2;\n        x *= max_bounds_-min_bounds_;\n        x += min_bounds_;\n        samples.template block<1,_Dims>(i,0) = x;\n        samples(i,_Dims) = funk_(x);\n    }\n    return samples;\n}\n\ntemplate <int _Dims>\nEigen::Matrix<float,-1,_Dims+1> Optimize<_Dims>::randSampleLow(int n, const std::vector<vars_type> & mins, const std::vector<vars_type> & maxs)\n{\n    Eigen::Matrix<float,-1,_Dims+1> samples;\n    samples.resize(n,_Dims+1);\n\n    //Create a new bounding box on which to sample\n    // vars_type new_min_bounds = mins[0];\n    // vars_type new_max_bounds = maxs[0];\n    vars_type new_min_bounds = mins[0];\n    vars_type new_max_bounds = maxs[0];\n\n    for (int i = 1; i < mins.size(); i++){\n        for (int d = 0; d < _Dims; d++){\n            if (mins[i](d) < new_min_bounds(d))\n                new_min_bounds(d) = mins[i](d);\n            if (maxs[i](d) > new_max_bounds(d))\n                new_max_bounds(d) = maxs[i](d);\n        }\n    }\n\n    for (int i = 0; i < n; i++){\n        vars_type x = vars_type::Random();//between -1 and 1\n        x += 1;\n        x /= 2;\n        x *= new_max_bounds-new_min_bounds;\n        x += new_min_bounds;\n        while (!withinUnion(x, mins, maxs)){\n            x = vars_type::Random();//between -1 and 1\n            x += 1;\n            x /= 2;\n            x *= new_max_bounds-new_min_bounds;\n            x += new_min_bounds;\n        }\n        samples.template block<1,_Dims>(i,0)= x;\n    }\n    return samples;\n}\n\ntemplate <int _Dims>\nfloat Optimize<_Dims>::calculateGini(const std::vector<bool> & classified, int start, int end)\n{\n    int num_low_int=0;\n    for (int i = start; i < end; i++){\n        if (!classified[i])\n            num_low_int++;\n    }\n    float num_low = num_low_int;\n    float num_total = end-start;\n\n    return 2*num_low/num_total * (1 - num_low/num_total);\n}\n\ntemplate <int _Dims>\nint Optimize<_Dims>::findSplit(const Optimize<_Dims>::Partition & main_part, Optimize<_Dims>::Partition & left_part, Optimize<_Dims>::Partition & right_part)\n{\n    auto indices = main_part.elements;\n\n    std::vector<int> v(data_.rows());\n    std::iota(v.begin(),v.end(),0);\n\n    //classify indices\n    std::unordered_set<int> low;\n    std::unordered_set<int> high;\n    \n    for (int i : indices){\n        if (data_(i,_Dims) < threshold_)\n            low.insert(i);\n        else\n            high.insert(i);    \n    }\n\n    //partition\n    float delta = 0;\n    for (int dim = 0; dim < _Dims; dim++){\n        auto p = permutations_[dim];\n        //keep only indices in current partition\n        for (auto it = p.begin(); it != p.end(); ){\n            if (low.find(*it)==low.end() && high.find(*it)==high.end())\n                it = p.erase(it);\n            else\n                ++it;\n        }\n        //sort indices in non-decreasing order along current dimension\n        std::vector<int> sorted_inds(indices.size());\n        std::transform(p.begin(), p.end(), sorted_inds.begin(), [&](int i){ return v[i]; });\n         //get class at each index\n        std::vector<bool> classified;\n        for (int ind : sorted_inds){\n            if (low.find(ind) == low.end())\n                classified.push_back(true); //high\n            else\n                classified.push_back(false); //low\n        }\n        //find best split\n        for (int i = 0; i < classified.size() - 1; i++){\n            float gini_left = calculateGini(classified, 0, i+1);\n            float gini_right = calculateGini(classified, i+1, classified.size());\n            float gini_all = calculateGini(classified, 0, classified.size());\n\n            float size_left = i+1;\n            float size_right = classified.size() - i - 1;\n            float size_all = classified.size();\n\n            float d = gini_all - gini_left*size_left/size_all - gini_right*size_right/size_all;\n\n            if (d > delta){\n                delta = d;\n                left_part = main_part;\n                right_part = main_part;\n\n                left_part.elements =std::vector<int>(sorted_inds.begin(),std::next(sorted_inds.begin(),i+1));\n                right_part.elements = std::vector<int>(std::next(sorted_inds.begin(),i+1),sorted_inds.end());\n\n                left_part.splits.push_back(Split(dim,sorted_inds[i],sorted_inds[i+1],false));\n                right_part.splits.push_back(Split(dim,sorted_inds[i],sorted_inds[i+1],true));\n            }\n        }\n    }\n    //Return 0 if stopping condition has been met\n    if (delta < tolerance_){\n        return 0;\n    }\n    return 1;\n}\n\ntemplate <int _Dims>\nvoid Optimize<_Dims>::sortData()\n{\n    //Each vector in permutations_ should contain the sorted indices along a dimension\n    for (int dim = 0; dim < _Dims; dim++){\n        std::vector<float> xi(data_.rows());\n        for (int i = 0; i < data_.rows(); i++)\n            xi[i] = data_(i,dim);\n        //sort in non-decreasing order\n        std::vector<int> p(xi.size());\n        std::iota(p.begin(), p.end(), 0);\n        std::sort(p.begin(), p.end(), [&](std::size_t i, std::size_t j){ return xi[i] < xi[j]; });\n        //store permutation\n        permutations_[dim] = p;\n    }\n}\n\ntemplate <int _Dims>\nbool Optimize<_Dims>::withinUnion(const vars_type & x, const std::vector<vars_type> & mins, const std::vector<vars_type> & maxs)\n{\n    for (int i = 0; i < mins.size(); i++){\n        if ((x-mins[i] < 0).count() == 0 && (maxs[i]-x < 0).count() == 0){\n            return true;\n        }\n    }\n    return false;\n}", "meta": {"hexsha": "4251523b767c582731a8b55d81e39cf71bf4fc68", "size": 14440, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Optimize.hpp", "max_stars_repo_name": "kevinh42/tree-opt", "max_stars_repo_head_hexsha": "afd55e7f92b3d275f042f6d107d3a1c6bc94c42f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-14T23:59:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-14T23:59:20.000Z", "max_issues_repo_path": "include/Optimize.hpp", "max_issues_repo_name": "kevinh42/tree-opt", "max_issues_repo_head_hexsha": "afd55e7f92b3d275f042f6d107d3a1c6bc94c42f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Optimize.hpp", "max_forks_repo_name": "kevinh42/tree-opt", "max_forks_repo_head_hexsha": "afd55e7f92b3d275f042f6d107d3a1c6bc94c42f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7951807229, "max_line_length": 157, "alphanum_fraction": 0.569598338, "num_tokens": 3592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.42953418251242714}}
{"text": "#include \"modules/neuralNetwork/layer/linear/linear.hpp\"\n#include \"modules/neuralNetwork/neuralNetwork.hpp\"\n\n#ifdef _KORALI_USE_CUDNN\n  #include \"auxiliar/cudaUtils.hpp\"\n#endif\n\n#ifdef _KORALI_USE_ONEDNN\n  #include \"auxiliar/dnnUtils.hpp\"\nusing namespace dnnl;\n#endif\n\n#include <Eigen/Dense>\nusing namespace Eigen;\n\nnamespace korali\n{\nnamespace neuralNetwork\n{\nnamespace layer\n{\n;\n\nvoid Linear::initialize()\n{\n  // Checking Layer size\n  if (_outputChannels == 0) KORALI_LOG_ERROR(\"Node count for layer (%lu) should be larger than zero.\\n\", _index);\n\n  // Checking position\n  if (_index == 0) KORALI_LOG_ERROR(\"Feed Forward layers cannot be the starting layer of the NN\\n\");\n  if (_index == _nn->_layers.size() - 1) KORALI_LOG_ERROR(\"Feed Forward layers cannot be the last layer of the NN\\n\");\n}\n\nstd::vector<float> Linear::generateInitialHyperparameters()\n{\n  std::vector<float> hyperparameters;\n\n  // If this is not the initial layer, calculate hyperparameters for weight and bias operation\n  if (_prevLayer != nullptr)\n  {\n    // Setting value for this layer's xavier constant\n    float xavierConstant = std::sqrt(6.0f) / std::sqrt(_outputChannels + _prevLayer->_outputChannels);\n\n    // Adding layer's weights hyperparameter values\n    for (size_t i = 0; i < _outputChannels; i++)\n      for (size_t j = 0; j < _prevLayer->_outputChannels; j++)\n        hyperparameters.push_back(_weightScaling * xavierConstant * _nn->_uniformGenerator->getRandomNumber());\n\n    // Adding layer's bias hyperparameter values\n    for (size_t i = 0; i < _outputChannels; i++)\n      hyperparameters.push_back(0.0f);\n  }\n\n  return hyperparameters;\n}\n\nvoid Linear::createHyperparameterMemory()\n{\n  // Checking Layer sizes\n  ssize_t OC = _outputChannels;\n  ssize_t IC = _prevLayer->_outputChannels;\n\n  // Setting hyperparameter count\n  _hyperparameterCount = IC * OC + OC;\n\n  if (_nn->_engine == \"Korali\")\n  {\n    _weightValues = (float *)malloc(IC * OC * sizeof(float));\n    _biasValues = (float *)malloc(OC * sizeof(float));\n  }\n\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    memory::dims weightDims = {OC, IC};\n    auto weightMemDesc = memory::desc(weightDims, memory::data_type::f32, memory::format_tag::ab);\n    _weightsMem = memory(weightMemDesc, _nn->_dnnlEngine);\n\n    auto biasMemDesc = memory::desc({OC}, memory::data_type::f32, memory::format_tag::a);\n    _biasMem = memory(biasMemDesc, _nn->_dnnlEngine);\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    cudnnErrCheck(cudnnCreateFilterDescriptor(&_weightsFilterDesc));\n    cudnnErrCheck(cudnnSetFilter4dDescriptor(_weightsFilterDesc, CUDNN_DATA_FLOAT, CUDNN_TENSOR_NCHW, OC, IC, 1, 1));\n    cudaErrCheck(cudaMalloc((void **)&_weightsFilter, IC * OC * sizeof(float)));\n\n    cudnnErrCheck(cudnnCreateTensorDescriptor(&_biasTensorDesc));\n    cudnnErrCheck(cudnnSetTensor4dDescriptor(_biasTensorDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, 1, OC, 1, 1));\n    cudaErrCheck(cudaMalloc((void **)&_biasTensor, OC * sizeof(float)));\n  }\n#endif\n}\n\nvoid Linear::copyHyperparameterPointers(Layer *dstLayer)\n{\n  Linear *dstPtr = dynamic_cast<Linear *>(dstLayer);\n  dstPtr->_hyperparameterCount = _hyperparameterCount;\n\n  if (_nn->_engine == \"Korali\")\n  {\n    dstPtr->_weightValues = _weightValues;\n    dstPtr->_biasValues = _biasValues;\n  }\n\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    dstPtr->_weightsMem = _weightsMem;\n    dstPtr->_biasMem = _biasMem;\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    dstPtr->_weightsFilterDesc = _weightsFilterDesc;\n    dstPtr->_weightsFilter = _weightsFilter;\n    dstPtr->_biasTensorDesc = _biasTensorDesc;\n    dstPtr->_biasTensor = _biasTensor;\n  }\n#endif\n}\n\nvoid Linear::createForwardPipeline()\n{\n  // Calling base layer function\n  Layer::createForwardPipeline();\n\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    // We create the inner product (Wx + b) operation\n    auto inner_product_d = inner_product_forward::desc(_propKind, _prevLayer->_outputMem[0].get_desc(), _weightsMem.get_desc(), _biasMem.get_desc(), _outputMem[0].get_desc());\n\n    // Create inner product primitive descriptor.\n    dnnl::primitive_attr forwardPrimitiveAttributes;\n    _forwardInnerProductPrimitiveDesc = inner_product_forward::primitive_desc(inner_product_d, forwardPrimitiveAttributes, _nn->_dnnlEngine);\n\n    // Create the weights+bias primitive.\n    _forwardInnerProductPrimitive = inner_product_forward(_forwardInnerProductPrimitiveDesc);\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    // Creating convolution operator\n    cudnnErrCheck(cudnnCreateConvolutionDescriptor(&_convolutionDesc));\n    cudnnErrCheck(cudnnSetConvolution2dDescriptor(_convolutionDesc, 0, 0, 1, 1, 1, 1, CUDNN_CONVOLUTION, CUDNN_DATA_FLOAT));\n    cudnnErrCheck(cudnnGetConvolutionForwardWorkspaceSize(_nn->_cuDNNHandle, _prevLayer->_outputTensorDesc, _weightsFilterDesc, _convolutionDesc, _outputTensorDesc, CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM, &_convolutionWorkspaceSize));\n\n    _convolutionWorkspace.resize(_nn->_timestepCount);\n    for (size_t t = 0; t < _nn->_timestepCount; t++)\n      cudaErrCheck(cudaMalloc((void **)&_convolutionWorkspace[t], _convolutionWorkspaceSize * sizeof(float)));\n  }\n#endif\n}\n\nvoid Linear::createBackwardPipeline()\n{\n  /*********************************************************************************\n   *  Initializing memory objects and primitives for BACKWARD propagation\n   *********************************************************************************/\n\n  // Checking Layer sizes\n  ssize_t OC = _outputChannels;\n  ssize_t IC = _prevLayer->_outputChannels;\n\n  // Calling base layer function\n  Layer::createBackwardPipeline();\n\n  if (_nn->_engine == \"Korali\")\n  {\n    _weightGradient = (float *)malloc(IC * OC * sizeof(float));\n    _biasGradient = (float *)malloc(OC * sizeof(float));\n  }\n\n// Creating backward propagation primitives\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    _weightsGradientMem = memory(_weightsMem.get_desc(), _nn->_dnnlEngine);\n    _biasGradientMem = memory(_biasMem.get_desc(), _nn->_dnnlEngine);\n\n    auto backwardDataDesc = inner_product_backward_data::desc(\n      _prevLayer->_outputGradientMem[0].get_desc(),\n      _weightsMem.get_desc(),\n      _outputGradientMem[0].get_desc());\n\n    // Create the primitive.\n    auto backwardDataPrimitiveDesc = inner_product_backward_data::primitive_desc(backwardDataDesc, _nn->_dnnlEngine, _forwardInnerProductPrimitiveDesc);\n    _backwardDataPrimitive = inner_product_backward_data(backwardDataPrimitiveDesc);\n\n    auto backwardWeightsDesc = inner_product_backward_weights::desc(\n      _prevLayer->_outputMem[0].get_desc(),\n      _weightsMem.get_desc(),\n      _biasMem.get_desc(),\n      _outputGradientMem[0].get_desc());\n\n    // Create the primitive.\n    auto backwardWeightsPrimitiveDesc = inner_product_backward_weights::primitive_desc(backwardWeightsDesc, _nn->_dnnlEngine, _forwardInnerProductPrimitiveDesc);\n    _backwardWeightsPrimitive = inner_product_backward_weights(backwardWeightsPrimitiveDesc);\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    cudaErrCheck(cudaMalloc((void **)&_weightsGradientFilter, IC * OC * sizeof(float)));\n    cudaErrCheck(cudaMalloc((void **)&_biasGradientTensor, OC * sizeof(float)));\n  }\n#endif\n}\n\nvoid Linear::forwardData(const size_t t)\n{\n  size_t N = _batchSize;\n  size_t IC = _prevLayer->_outputChannels;\n  size_t OC = _outputChannels;\n\n  if (_nn->_engine == \"Korali\")\n  {\n    // Performing Wx computation\n    Map<MatrixXf> matA(_weightValues, IC, OC);\n    Map<MatrixXf> matB(_prevLayer->_outputValues, IC, N);\n    Map<MatrixXf> matC(_outputValues, OC, N);\n\n    matC = matA.transpose() * matB;\n\n    // Adding Bias\n    for (size_t i = 0; i < N; i++)\n      for (size_t j = 0; j < OC; j++)\n        _outputValues[i * OC + j] += _biasValues[j];\n  }\n\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    // Arguments to the inner product operation\n    std::unordered_map<int, dnnl::memory> forwardInnerProductArgs;\n    forwardInnerProductArgs[DNNL_ARG_SRC] = _prevLayer->_outputMem[t];\n    forwardInnerProductArgs[DNNL_ARG_WEIGHTS] = _weightsMem;\n    forwardInnerProductArgs[DNNL_ARG_BIAS] = _biasMem;\n    forwardInnerProductArgs[DNNL_ARG_DST] = _outputMem[t];\n\n    _forwardInnerProductPrimitive.execute(_nn->_dnnlStream, forwardInnerProductArgs);\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    float alpha1 = 1.0f;\n    float alpha2 = 0.0f;\n    cudnnErrCheck(cudnnConvolutionForward(\n      _nn->_cuDNNHandle,\n      &alpha1,\n      _prevLayer->_outputTensorDesc,\n      _prevLayer->_outputTensor[t],\n      _weightsFilterDesc,\n      _weightsFilter,\n      _convolutionDesc,\n      CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM,\n      _convolutionWorkspace[t],\n      _convolutionWorkspaceSize,\n      &alpha2,\n      _outputTensorDesc,\n      _outputTensor[t]));\n\n    float alpha = 1.0f;\n    float beta = 1.0f;\n    cudnnAddTensor(_nn->_cuDNNHandle, &alpha, _biasTensorDesc, _biasTensor, &beta, _outputTensorDesc, _outputTensor[t]);\n  }\n#endif\n}\n\nvoid Linear::backwardData(const size_t t)\n{\n  int N = _batchSize;\n  int IC = _prevLayer->_outputChannels;\n  int OC = _outputChannels;\n\n  if (_nn->_mode == \"Inference\")\n    KORALI_LOG_ERROR(\"Requesting Layer backward data propagation but NN was configured for inference only.\\n\");\n\n  if (_nn->_engine == \"Korali\")\n  {\n    // Backward propagating Wx+b operation\n    Map<MatrixXf> matA(_weightValues, IC, OC);\n    Map<MatrixXf> matB(_outputGradient, OC, N);\n    Map<MatrixXf> matC(_prevLayer->_outputGradient, IC, N);\n\n    matC = matA * matB;\n  }\n\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    _backwardDataArgs[DNNL_ARG_DIFF_DST] = _outputGradientMem[t];             // Input\n    _backwardDataArgs[DNNL_ARG_WEIGHTS] = _weightsMem;                        // Input\n    _backwardDataArgs[DNNL_ARG_DIFF_SRC] = _prevLayer->_outputGradientMem[t]; // Output\n\n    _backwardDataPrimitive.execute(_nn->_dnnlStream, _backwardDataArgs);\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    float alpha = 1.0f;\n    float beta = 0.0f;\n    cudnnErrCheck(cudnnConvolutionBackwardData(\n      _nn->_cuDNNHandle,\n      &alpha,\n      _weightsFilterDesc,\n      _weightsFilter,\n      _outputTensorDesc,\n      _outputGradientTensor[t],\n      _convolutionDesc,\n      CUDNN_CONVOLUTION_BWD_DATA_ALGO_0,\n      _convolutionWorkspace[t],\n      _convolutionWorkspaceSize,\n      &beta,\n      _prevLayer->_outputTensorDesc,\n      _prevLayer->_outputGradientTensor[t]));\n  }\n#endif\n}\n\nvoid Linear::backwardHyperparameters(size_t t)\n{\n  const size_t N = _batchSize;\n  const size_t IC = _prevLayer->_outputChannels;\n  const size_t OC = _outputChannels;\n\n  if (_nn->_mode == \"Inference\")\n    KORALI_LOG_ERROR(\"Requesting Layer hyperparameter gradient propagation but NN was configured for inference only.\\n\");\n\n  if (_nn->_engine == \"Korali\")\n  {\n    // Performing Weight gradient calculation\n    Map<MatrixXf> matA(_prevLayer->_outputValues, IC, N);\n    Map<MatrixXf> matB(_outputGradient, OC, N);\n    Map<MatrixXf> matC(_weightGradient, IC, OC);\n\n    matC = matA * matB.transpose();\n\n    // Setting the bias values to all minibatch inputs\n    for (size_t j = 0; j < OC; j++) _biasGradient[j] = _outputGradient[0 * OC + j];\n    for (size_t i = 1; i < N; i++)\n      for (size_t j = 0; j < OC; j++) _biasGradient[j] += _outputGradient[i * OC + j];\n  }\n\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    // Arguments for the backward propagation of the gradient wrt Weights and Biases\n    std::unordered_map<int, dnnl::memory> backwardWeightsArgs;\n    backwardWeightsArgs[DNNL_ARG_SRC] = _prevLayer->_outputMem[t];    // Input\n    backwardWeightsArgs[DNNL_ARG_DIFF_DST] = _outputGradientMem[t];   // Input\n    backwardWeightsArgs[DNNL_ARG_DIFF_WEIGHTS] = _weightsGradientMem; // Output\n    backwardWeightsArgs[DNNL_ARG_DIFF_BIAS] = _biasGradientMem;       // Output\n\n    _backwardWeightsPrimitive.execute(_nn->_dnnlStream, backwardWeightsArgs);\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    float alpha = 1.0f;\n    float beta = 0.0f;\n\n    cudnnErrCheck(cudnnConvolutionBackwardBias(\n      _nn->_cuDNNHandle,\n      &alpha,\n      _outputTensorDesc,\n      _outputGradientTensor[t],\n      &beta,\n      _biasTensorDesc,\n      _biasGradientTensor));\n\n    cudnnErrCheck(cudnnConvolutionBackwardFilter(\n      _nn->_cuDNNHandle,\n      &alpha,\n      _prevLayer->_outputTensorDesc,\n      _prevLayer->_outputTensor[t],\n      _outputTensorDesc,\n      _outputGradientTensor[t],\n      _convolutionDesc,\n      CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0,\n      _convolutionWorkspace[t],\n      _convolutionWorkspaceSize,\n      &beta,\n      _weightsFilterDesc,\n      _weightsGradientFilter));\n  }\n#endif\n}\n\nvoid Linear::setHyperparameters(float *hyperparameters)\n{\n  size_t IC = _prevLayer->_outputChannels;\n  size_t OC = _outputChannels;\n\n  if (_nn->_engine == \"Korali\")\n  {\n    memcpy(_weightValues, &hyperparameters[0], IC * OC * sizeof(float));\n    memcpy(_biasValues, &hyperparameters[IC * OC], OC * sizeof(float));\n  }\n\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    write_to_dnnl_memory(&hyperparameters[0], _weightsMem);\n    write_to_dnnl_memory(&hyperparameters[IC * OC], _biasMem);\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    cudaErrCheck(cudaMemcpy(_weightsFilter, &hyperparameters[0], IC * OC * sizeof(float), cudaMemcpyHostToDevice));\n    cudaErrCheck(cudaMemcpy(_biasTensor, &hyperparameters[IC * OC], OC * sizeof(float), cudaMemcpyHostToDevice));\n  }\n#endif\n}\n\nvoid Linear::getHyperparameters(float *hyperparameters)\n{\n  size_t IC = _prevLayer->_outputChannels;\n  size_t OC = _outputChannels;\n\n  if (_nn->_engine == \"Korali\")\n  {\n    memcpy(&hyperparameters[0], _weightValues, IC * OC * sizeof(float));\n    memcpy(&hyperparameters[IC * OC], _biasValues, OC * sizeof(float));\n  }\n\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    read_from_dnnl_memory(&hyperparameters[0], _weightsMem);\n    read_from_dnnl_memory(&hyperparameters[IC * OC], _biasMem);\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    cudaErrCheck(cudaMemcpy(&hyperparameters[0], _weightsFilter, IC * OC * sizeof(float), cudaMemcpyDeviceToHost));\n    cudaErrCheck(cudaMemcpy(&hyperparameters[IC * OC], _biasTensor, OC * sizeof(float), cudaMemcpyDeviceToHost));\n  }\n#endif\n}\n\nvoid Linear::getHyperparameterGradients(float *gradient)\n{\n  size_t IC = _prevLayer->_outputChannels;\n  size_t OC = _outputChannels;\n\n  if (_nn->_engine == \"Korali\")\n  {\n    memcpy(&gradient[0], _weightGradient, IC * OC * sizeof(float));\n    memcpy(&gradient[IC * OC], _biasGradient, OC * sizeof(float));\n  }\n\n#ifdef _KORALI_USE_ONEDNN\n  if (_nn->_engine == \"OneDNN\")\n  {\n    read_from_dnnl_memory(&gradient[0], _weightsGradientMem);\n    read_from_dnnl_memory(&gradient[IC * OC], _biasGradientMem);\n  }\n#endif\n\n#ifdef _KORALI_USE_CUDNN\n  if (_nn->_engine == \"CuDNN\")\n  {\n    cudaErrCheck(cudaMemcpy(&gradient[0], _weightsGradientFilter, IC * OC * sizeof(float), cudaMemcpyDeviceToHost));\n    cudaErrCheck(cudaMemcpy(&gradient[IC * OC], _biasGradientTensor, OC * sizeof(float), cudaMemcpyDeviceToHost));\n  }\n#endif\n}\n\nvoid Linear::setConfiguration(knlohmann::json& js) \n{\n if (isDefined(js, \"Results\"))  eraseValue(js, \"Results\");\n\n Layer::setConfiguration(js);\n _type = \"layer/linear\";\n if(isDefined(js, \"Type\")) eraseValue(js, \"Type\");\n if(isEmpty(js) == false) KORALI_LOG_ERROR(\" + Unrecognized settings for Korali module: linear: \\n%s\\n\", js.dump(2).c_str());\n} \n\nvoid Linear::getConfiguration(knlohmann::json& js) \n{\n\n js[\"Type\"] = _type;\n Layer::getConfiguration(js);\n} \n\nvoid Linear::applyModuleDefaults(knlohmann::json& js) \n{\n\n std::string defaultString = \"{}\";\n knlohmann::json defaultJs = knlohmann::json::parse(defaultString);\n mergeJson(js, defaultJs); \n Layer::applyModuleDefaults(js);\n} \n\nvoid Linear::applyVariableDefaults() \n{\n\n Layer::applyVariableDefaults();\n} \n\n;\n\n} //layer\n} //neuralNetwork\n} //korali\n;\n", "meta": {"hexsha": "cd5c5e52bf02cae7033cca3000df0a35018da488", "size": 16129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/modules/neuralNetwork/layer/linear/linear.cpp", "max_stars_repo_name": "JonathanLehner/korali", "max_stars_repo_head_hexsha": "90f97d8e2fed2311f988f39cfe014f23ba7dd6cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2018-07-26T07:20:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T10:23:12.000Z", "max_issues_repo_path": "source/modules/neuralNetwork/layer/linear/linear.cpp", "max_issues_repo_name": "JonathanLehner/korali", "max_issues_repo_head_hexsha": "90f97d8e2fed2311f988f39cfe014f23ba7dd6cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 212.0, "max_issues_repo_issues_event_min_datetime": "2018-09-21T10:44:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T14:33:05.000Z", "max_forks_repo_path": "source/modules/neuralNetwork/layer/linear/linear.cpp", "max_forks_repo_name": "JonathanLehner/korali", "max_forks_repo_head_hexsha": "90f97d8e2fed2311f988f39cfe014f23ba7dd6cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2018-07-25T15:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T14:19:46.000Z", "avg_line_length": 30.605313093, "max_line_length": 236, "alphanum_fraction": 0.7061194122, "num_tokens": 4517, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.42953417570529334}}
{"text": "#include \"aabb.h\"\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\nusing namespace Eigen;\nusing namespace std;\n\naabb::aabb(const vec& low_bd, const vec& up_bd){\n  low_bd_ = low_bd;\n  up_bd_ = up_bd;\n}\naabb::aabb(const aabb& other){\n  low_bd_ = other.low_bd_;\n  up_bd_ = other.up_bd_;\n}\nvoid aabb::merge(const aabb& other){\n  for(size_t i = 0; i < 3; ++i){\n    if(low_bd_(i) > other.low_bd_(i))\n      low_bd_(i) = other.low_bd_(i);\n    if(up_bd_(i) < other.up_bd_(i))\n      up_bd_(i) = other.up_bd_(i);\n  }\n\n  {//check\n    for(size_t i = 0; i < 3; ++i){\n      assert(low_bd_(i) <= other.low_bd_(i));\n      assert(up_bd_(i) >= other.up_bd_(i));\n    }\n  }\n}\n\ntri_aabb::tri_aabb(const size_t& id, const vec& p1, const vec& p2, const vec& p3):id_(id){\n  p_.col(0) = p1;\n  p_.col(1) = p2;\n  p_.col(2) = p3;\n  id_ = id;\n  low_bd_ = p1;\n  up_bd_ = p1;\n  for(size_t i = 0; i < 3; ++i){\n    if(low_bd_(i) > p2(i))\n      low_bd_(i) = p2(i);\n    else if (up_bd_(i) < p2(i))\n      up_bd_(i) = p2(i);\n\n    if(low_bd_(i) > p3(i))\n      low_bd_(i) = p3(i);\n    else if (up_bd_(i) < p3(i))\n      up_bd_(i) = p3(i);\n  }\n\n  center = (p1 + p2 + p3) / 3.0;\n\n  \n  vec one_edge = p2 - p1, other_edge = p3 - p1;\n  normal_ = one_edge.cross(other_edge);\n  // normal_(0) = (p2(1) - p1(1)) * (p3(2) - p1(2)) - (p2(2) - p1(2)) * (p3(1) - p1(1));\n  // normal_(1) = (p2(0) - p1(0)) * (p3(2) - p1(2)) - (p2(2) - p1(2)) * (p3(0) - p1(0));\n  // normal_(2) = (p2(0) - p1(0)) * (p3(1) - p1(1)) - (p2(1) - p1(2)) * (p3(0) - p1(0));\n\n  double norm  = normal_.norm();\n  if(norm > 1e-6)\n    normal_ = normal_ / norm;\n  else\n    normal_ = vec::Zero();\n  d_ = -normal_.dot(p1) ;\n\n}\ntri_aabb::tri_aabb(const size_t& id, const tri& plane, const tri& n){\n  id_ = id;\n  p_ = plane;\n  n_ = n;\n  vec p1 = plane.col(0), p2 = plane.col(1), p3 = plane.col(2);\n  low_bd_ = p1;\n  up_bd_ = p1;\n  for(size_t i = 0; i < 3; ++i){\n    if(low_bd_(i) > p2(i))\n      low_bd_(i) = p2(i);\n    if (up_bd_(i) < p2(i))\n      up_bd_(i) = p2(i);\n\n    if(low_bd_(i) > p3(i))\n      low_bd_(i) = p3(i);\n    if (up_bd_(i) < p3(i))\n      up_bd_(i) = p3(i);\n  }\n\n  center = (p1 + p2 + p3) / 3.0;\n  vec one_edge = p2 - p1, other_edge = p3 - p1;\n  normal_ = one_edge.cross(other_edge);  \n  // normal_(0) = (p2(1) - p1(1)) * (p3(2) - p1(2)) - (p2(2) - p1(2)) * (p3(1) - p1(1));\n  // normal_(1) = (p2(0) - p1(0)) * (p3(2) - p1(2)) - (p2(2) - p1(2)) * (p3(0) - p1(0));\n  // normal_(2) = (p2(0) - p1(0)) * (p3(1) - p1(1)) - (p2(1) - p1(2)) * (p3(0) - p1(0));\n\n  double norm  = normal_.norm();\n  if(norm > 1e-6)\n    normal_ = normal_ / norm;\n  else\n    normal_ = vec::Zero();\n  d_ = -normal_.dot(p1) ;\n}\n\n\naabb merge_tri_aabbs(const std::vector<std::shared_ptr<tri_aabb>> tri_aabbs){\n  if(tri_aabbs.empty())\n    throw runtime_error(\"tri_aabbs is empty\");\n\n  bool bk =false;\n  if(tri_aabbs.size() == 90)\n    bk = true;\n  size_t num = 0;\n  aabb bd_box(tri_aabbs[0]->low_bd_, tri_aabbs[0]->up_bd_);\n  for(auto& one_bdbox : tri_aabbs){\n    bd_box.merge(*one_bdbox);\n    ++num;\n  }\n\n\n\n  {//check\n    for(size_t i = 0; i < tri_aabbs.size(); ++i){\n      for(size_t j = 0; j < 3; ++j){\n        assert(tri_aabbs[i]->low_bd_(j) >= bd_box.low_bd_(j));\n        assert(tri_aabbs[i]->up_bd_(j) <= bd_box.up_bd_(j));\n\n      }\n    }\n    \n  }\n\n  \n  return bd_box;\n}\n", "meta": {"hexsha": "2b052557ac027cc6b3029df0a2ffb0a6a5237257", "size": 3284, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/aabb.cpp", "max_stars_repo_name": "Chongyao/Monte-Carlo-Ray-Tracing", "max_stars_repo_head_hexsha": "d175300f089a4ed61c9548e5a2587e63cd843403", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/aabb.cpp", "max_issues_repo_name": "Chongyao/Monte-Carlo-Ray-Tracing", "max_issues_repo_head_hexsha": "d175300f089a4ed61c9548e5a2587e63cd843403", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/aabb.cpp", "max_forks_repo_name": "Chongyao/Monte-Carlo-Ray-Tracing", "max_forks_repo_head_hexsha": "d175300f089a4ed61c9548e5a2587e63cd843403", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6917293233, "max_line_length": 90, "alphanum_fraction": 0.528319123, "num_tokens": 1415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.42951421659650413}}
{"text": "\n#include <deal.II/base/function.h>\n#include <deal.II/base/function_parser.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/base/table_handler.h>\n\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/petsc_parallel_sparse_matrix.h>\n#include <deal.II/lac/petsc_parallel_vector.h>\n#include <deal.II/lac/petsc_solver.h>\n#include <deal.II/lac/petsc_precondition.h>\n#include <deal.II/lac/sparsity_tools.h>\n#include <deal.II/lac/vector.h>\n\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n#include <deal.II/distributed/grid_refinement.h>\n#include <deal.II/distributed/tria.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_system.h>\n#include <deal.II/fe/fe_q.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n\n// #include <boost/program_options.hpp>\n\n#include <mandy/function_tools.h>\n\n#include <mandy/elastic_problem.h>\n#include <mandy/piezoelectric_problem.h>\n\n#include <fstream>\n#include <iostream>\n\n#include <algorithm>    // std::transform\n#include <functional>   // std::plus\n\nnamespace aphex\n{\n\n  template <int dim>\n  class Aphex\n  {\n  public:\n\n    /**\n     * Class constructor.\n     */\n    Aphex (const std::string &prm);\n\n    /**\n     * Class destructor.\n     */\n    ~Aphex ();\n\n    /**\n     * Run.\n     */\n    void run ();\n    \n  private:\n\n    /**\n     * MPI communicator.\n     */\n    MPI_Comm mpi_communicator;\n    \n    /**\n     * A distributed grid on which all computations are done.\n     */\n    dealii::parallel::distributed::Triangulation<dim> triangulation;\n\n    /**\n     * Solution of the elastic problem.\n     */\n    dealii::PETScWrappers::MPI::Vector displacement;\n\n    /**\n     * Solution of the piezoelectric.\n     */\n    dealii::PETScWrappers::MPI::Vector piezoelectric_potential;\n    \n    /**\n     * Parallel iostream.\n     */\n    dealii::ConditionalOStream pcout;\n\n    /**\n     * Stop clock.\n     */\n    dealii::TimerOutput timer;\n    \n  };\n\n  \n  template <int dim>\n  Aphex<dim>::Aphex (const std::string &prm)\n    :\n    mpi_communicator (MPI_COMM_WORLD),\n    triangulation (mpi_communicator,\n\t\t   typename dealii::Triangulation<dim>::MeshSmoothing\n\t\t   (dealii::Triangulation<dim>::smoothing_on_refinement |\n\t\t    dealii::Triangulation<dim>::smoothing_on_coarsening)),\n    pcout (std::cout, (dealii::Utilities::MPI::this_mpi_process (mpi_communicator) == 0)),\n    timer (mpi_communicator, pcout,\n     \t   dealii::TimerOutput::summary,\n     \t   dealii::TimerOutput::wall_times)\n  {}\n  \n\n  template <int dim>\n  Aphex<dim>::~Aphex ()\n  {}\n\n  template <int dim>\n  void\n  Aphex<dim>::run ()\n  {\n    \n    try\n      {\n\n\tdealii::GridGenerator::hyper_cube (triangulation, -10, 10);\n\t// triangulation.refine_global (parameters.get_integer (\"Global mesh refinement steps\"));\n\ttriangulation.refine_global (2);\n\n\t{\n\t  dealii::TimerOutput::Scope time (timer, \"material\");\n\t  mandy::FunctionTools<3> material (triangulation, \"material.prm\");\n\t  material.run ();\n\t}\n\n\t{\n\t  dealii::TimerOutput::Scope time (timer, \"elastic problem\");\n\t  mandy::ElasticProblem<3> elastic_problem (triangulation, displacement,\n\t\t\t\t\t\t    mpi_communicator, \"elastic.prm\");\n\t  elastic_problem.run ();\n\t}\n\n\t{\n\t  dealii::TimerOutput::Scope time (timer, \"piezoelectric problem\");\n\t  mandy::PiezoelectricProblem<3> piezoelectric_problem (triangulation, displacement,\n\t\t\t\t\t\t\t\tmpi_communicator, \"piezoelectric.prm\");\n\t  piezoelectric_problem.run ();\n\t}\n\n      }\n    \n    catch (std::exception &exc)\n      {\n\tstd::cerr << std::endl << std::endl\n\t\t  << \"----------------------------------------------------\"\n\t\t  << std::endl;\n\tstd::cerr << \"Exception on processing: \" << std::endl\n\t\t  << exc.what() << std::endl\n\t\t  << \"Aborting!\" << std::endl\n\t\t  << \"----------------------------------------------------\"\n\t\t  << std::endl;\n      }\n    \n    catch (...)\n      {\n\tstd::cerr << std::endl << std::endl\n\t\t  << \"----------------------------------------------------\"\n\t\t  << std::endl;\n\tstd::cerr << \"Unknown exception!\" << std::endl\n\t\t  << \"Aborting!\" << std::endl\n\t\t  << \"----------------------------------------------------\"\n\t\t  << std::endl;\n      }\n    \n  } // run ()\n  \n} // namespace aphex\n\n/**\n * Main function: Initialise problem and run it.\n */\nint main (int argc, char *argv[])\n{\n  \n  // Initialise MPI\n  dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);\n\n  try\n    {\n#ifdef INCLUDED_EXTERNAL_BOOST\n      // Parse the commandline.\n      boost::program_options::options_description description {\"Options\"};\n      description.add_options ()\n\t(\"help\", \"Help screen\")\n\t(\"prm\", value<string> ()->default_value (\"aphex.prm\"), \"Parameter file\");\n\n      boost::program_options::variables_map vmap;\n      boost::program_options::store\n\t(boost::program_options::parse_command_line (argc, argv, description), vmap);\n\n      if (vmap.count (\"help\"))\n\tstd::cout << description\n\t\t  << std::endl;\n\n      else if (vmap.count (\"prm\"))\n\tstd::cout << \"Parameter file: \" << vmap[\"prm\"].as<string>\n\t\t  << std::endl;\n\n      // else if (...)\n#endif      \n\n      std::vector<std::string> args (argv+1, argv+argc);\n      \n      AssertThrow (args.size ()>0, dealii::ExcMessage (\"The number of input arguments must be greater than zero.\"));\n      \n      std::cout << std::endl << std::endl\n\t\t<< \"----------------------------------------------------\"\n\t\t<< std::endl\n\t\t<< \"Caught arguments: \";\n      for (unsigned int i=0; i<args.size (); ++i)\n\tstd::cout << std::endl << \"   \" << args[i];\n      std::cout  << std::endl\n\t\t << \"----------------------------------------------------\"\n\t\t << std::endl << std::endl;\n      \n      aphex::Aphex<3> aphex (args[1]);\n      aphex.run ();\n    }\n\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "9a2706226c25730aa33c004c381cd253076bf632", "size": 7072, "ext": "cc", "lang": "C++", "max_stars_repo_path": "aphex.cc", "max_stars_repo_name": "oneliefleft/mandy", "max_stars_repo_head_hexsha": "e791f7defbf3f13a63769ad7231ddd32dcfd1a32", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aphex.cc", "max_issues_repo_name": "oneliefleft/mandy", "max_issues_repo_head_hexsha": "e791f7defbf3f13a63769ad7231ddd32dcfd1a32", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-02-24T13:55:50.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-24T14:00:20.000Z", "max_forks_repo_path": "aphex.cc", "max_forks_repo_name": "oneliefleft/mandy", "max_forks_repo_head_hexsha": "e791f7defbf3f13a63769ad7231ddd32dcfd1a32", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9047619048, "max_line_length": 116, "alphanum_fraction": 0.5653280543, "num_tokens": 1818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4294944041289827}}
{"text": "#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/csparse/linear_solver_csparse.h>\n#include <g2o/types/sba/types_six_dof_expmap.h>\n#include <chrono>\n\nusing namespace std;\nusing namespace cv;\n\nvoid feature_matching(const Mat& img1, const Mat& img2,\n    std::vector<KeyPoint>& keypoints1,\n    std::vector<KeyPoint>& keypoints2,\n    std::vector< DMatch >& matches)\n    {\n        Mat descriptors_1, descriptors_2;\n        Ptr<FeatureDetector> detector = ORB::create();\n        Ptr<DescriptorExtractor> descriptor = ORB::create();\n        \n        // compute FAST corners \n        detector->detect(img1, keypoints1);\n        detector->detect(img2, keypoints2);\n\n        // compute BRIEF descriptor\n        descriptor->compute(img1, keypoints1, descriptors_1);\n        descriptor->compute(img2, keypoints2, descriptors_2);\n\n        Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(4);\n        /*\n        FLANNBASED = 1, \n        BRUTEFORCE = 2, \n        BRUTEFORCE_L1 = 3, \n        BRUTEFORCE_HAMMING = 4, \n        BRUTEFORCE_HAMMINGLUT = 5, \n        BRUTEFORCE_SL2 = 6 */\n\n        vector<DMatch> allmatches;\n        matcher->match(descriptors_1, descriptors_2, allmatches);\n\n        // Filter all match points\n        // Find maximum and minimum distance\n        double min_dist = 1000000, max_dist = 0;\n        for ( int i = 0; i < descriptors_1.rows; i++ )\n        {\n            double dist = allmatches[i].distance;\n            if ( dist < min_dist ) min_dist = dist;\n            if ( dist > max_dist ) max_dist = dist;\n        }\n\n        cout << \"max distance: \" << max_dist << endl;\n        cout << \"min distance: \" << min_dist << endl;\n\n        for ( int i = 0; i < descriptors_1.rows; i++ )\n        {\n            if ( allmatches[i].distance <= max ( 2*min_dist, 30.0 ) )\n            {\n                matches.push_back ( allmatches[i] );\n            }\n        }\n    }\n\nPoint2d pixel2cam ( const Point2d& p, const Mat& K )\n{\n    return Point2d\n           (\n               ( p.x - K.at<double> ( 0,2 ) ) / K.at<double> ( 0,0 ),\n               ( p.y - K.at<double> ( 1,2 ) ) / K.at<double> ( 1,1 )\n           );\n}\n\nvoid bundleAdjustment(\n    const vector<Point3f> points_3d,\n    const vector<Point2f> points_2d,\n    const Mat &K,\n    Mat &R, Mat &t){\n        typedef g2o::BlockSolver< g2o::BlockSolverTraits<6, 3>> Block;\n        // typedef g2o::BlockSolver_6_3 Block;\n\n        Block::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse<Block::PoseMatrixType>();\n        \n        // Routine in pose estimation\n        Block *solver_ptr = new Block(linearSolver);\n        g2o::OptimizationAlgorithmLevenberg *solver = new g2o::OptimizationAlgorithmLevenberg(solver_ptr);\n        g2o::SparseOptimizer optimizer;\n        optimizer.setAlgorithm (solver);\n        optimizer.setVerbose(true);\n\n        // Vertex SE(3)\n        g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap(); // Camera pose SE(3)\n        Eigen::Matrix3d R_mat;\n\n        R_mat <<\n            R.at<double> ( 0,0 ), R.at<double> ( 0,1 ), R.at<double> ( 0,2 ),\n            R.at<double> ( 1,0 ), R.at<double> ( 1,1 ), R.at<double> ( 1,2 ),\n            R.at<double> ( 2,0 ), R.at<double> ( 2,1 ), R.at<double> ( 2,2 );\n\n        pose->setId(0);\n        pose->setEstimate(g2o::SE3Quat(\n            R_mat,\n            Eigen::Vector3d(t.at<double> ( 0,0 ), t.at<double> ( 1,0 ), t.at<double> ( 2,0 ))\n        ));     // SE3Quat is 6 dimensional, first three rotation, last three translation. \n                // Actually it's using Quaternion\n        optimizer.addVertex(pose);\n        \n        int index = 1;\n        // landmarks, use g2o::VertexSBAPointXYZ\n        for (const Point3f p:points_3d){\n            g2o::VertexSBAPointXYZ* point = new g2o::VertexSBAPointXYZ();\n            point->setId(index++);\n            point->setEstimate(Eigen::Vector3d(p.x, p.y, p.z));   // easy to set up, only need Eigen::Vector3d\n            point->setMarginalized(true);\n            optimizer.addVertex(point);\n        }\n\n        // parameter: camera intrinsics. Routine setup \n        g2o::CameraParameters* camera = new g2o::CameraParameters (\n            K.at<double> ( 0,0 ), Eigen::Vector2d ( K.at<double> ( 0,2 ), K.at<double> ( 1,2 ) ), 0\n        );\n        camera->setId ( 0 );\n        optimizer.addParameter ( camera );\n\n        index = 1;\n        // Error terms. use edge g2o::EdgeProjectXYZ2UV from 3d to 2d. Routine\n        for(const Point2f p:points_2d){\n            g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();\n            edge->setId(index);\n            edge->setVertex(0, dynamic_cast<g2o::VertexSBAPointXYZ*> (optimizer.vertex(index++)));  \n            edge->setVertex(1, pose);    // One side to pose, another side to each landmark\n            edge->setMeasurement(Eigen::Vector2d(p.x, p.y));\n            edge->setParameterId(0, 0);\n            edge->setInformation(Eigen::Matrix2d::Identity());  //  infomation matrix, covariance matrix\n            optimizer.addEdge(edge);\n        }\n\n        chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n        // Setup and initial optimization. Routine\n        optimizer.setVerbose ( true );\n        optimizer.initializeOptimization();\n        optimizer.optimize ( 100 );\n        chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n        chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>> ( t2-t1 );\n        cout<<\"optimization costs time: \"<<time_used.count() <<\" seconds.\"<<endl;\n\n        cout<<endl<<\"after optimization:\"<<endl;\n        cout<<\"T=\"<<endl<<Eigen::Isometry3d ( pose->estimate() ).matrix() <<endl;\n\n    }\n\nint main(int argc, char** argv){\n\n     if ( argc != 5 )\n    {\n        cout<<\"usage: pose_estimation_3d2d img1 img2 depth1 depth2\"<<endl;\n        return 1;\n    }\n\n    Mat img_1 = imread ( argv[1], CV_LOAD_IMAGE_COLOR );\n    Mat img_2 = imread ( argv[2], CV_LOAD_IMAGE_COLOR );\n\n    vector<KeyPoint> keypoints_1, keypoints_2;\n    vector<DMatch> matches;\n    feature_matching ( img_1, img_2, keypoints_1, keypoints_2, matches );\n    cout<<\"Total \"<<matches.size() <<\" Matching Points\" <<endl;\n\n    Mat d1 = imread ( argv[3], CV_LOAD_IMAGE_UNCHANGED );      \n    Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n    vector<Point3f> pts_3d;\n    vector<Point2f> pts_2d;\n    for ( DMatch m:matches )\n    {\n        ushort d = d1.ptr<unsigned short> (int ( keypoints_1[m.queryIdx].pt.y )) [ int ( keypoints_1[m.queryIdx].pt.x ) ];\n        if ( d == 0 )   \n            continue;\n        float dd = d/5000.0;\n        Point2d p1 = pixel2cam ( keypoints_1[m.queryIdx].pt, K );\n        pts_3d.push_back ( Point3f ( p1.x*dd, p1.y*dd, dd ) );  // Find feature point's 3D coordinates from Depth image\n        pts_2d.push_back ( keypoints_2[m.trainIdx].pt );\n    }\n\n    cout<<\"3d-2d pairs: \"<<pts_3d.size() <<endl;\n\n    Mat r, t;\n    solvePnP ( pts_3d, pts_2d, K, Mat(), r, t, false ); \n    Mat R;\n    cv::Rodrigues ( r, R ); // Rodrigues formula: Rotation vector to rotation matrix\n\n    cout<<\"R=\"<<endl<<R<<endl;\n    cout<<\"t=\"<<endl<<t<<endl;\n\n    cout<<\"calling bundle adjustment\"<<endl;\n\n    bundleAdjustment ( pts_3d, pts_2d, K, R, t );\n}\n", "meta": {"hexsha": "7ca370e52b5a7ddfcc27e1b477c03983f76a1aa9", "size": 7549, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "front_end/pose_estimation_3d2d.cpp", "max_stars_repo_name": "shen338/MySLAM", "max_stars_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "front_end/pose_estimation_3d2d.cpp", "max_issues_repo_name": "shen338/MySLAM", "max_issues_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "front_end/pose_estimation_3d2d.cpp", "max_forks_repo_name": "shen338/MySLAM", "max_forks_repo_head_hexsha": "a59f09c0f5bb9f3fa3904e946f4c94b280c3faeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3712871287, "max_line_length": 122, "alphanum_fraction": 0.5942508942, "num_tokens": 2146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4294895477082684}}
{"text": "\r\n#include \"../../def_submodule.hpp\"\r\n\r\n#include \"../../../../../type/math/coord.hpp\"\r\n\r\n\r\nusing namespace ::math::linear::vector;\r\n\r\n#include <boost/python.hpp>\r\n\r\ntypedef GS_DDMRM::S_IceRay::S_type::GT_int               GTs_int;\r\ntypedef GS_DDMRM::S_IceRay::S_type::GT_size               GTs_size;\r\ntypedef GS_DDMRM::S_IceRay::S_type::GT_scalar             GTs_scalar;\r\n//typedef GS_DDMRM::S_IceRay::S_type::S_color::GT_scalar    GTs_color;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_int2D    GTs_cell2D;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_int3D    GTs_cell3D;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_int4D    GTs_cell4D;\r\n\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_size2D    GTs_size2D;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_size3D    GTs_size3D;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_size4D    GTs_size4D;\r\n\r\n\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_scalar2D  GTs_coord2D;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_scalar3D  GTs_coord3D;\r\ntypedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_scalar4D  GTs_coord4D;\r\n\r\nnamespace\r\n {\r\n\r\n  template < typename N_number, unsigned N_dimension>\r\n   N_number get( typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model<N_number, N_dimension>::T_typedef const&v, int P_index )\r\n    {\r\n     if( P_index >= 0 && P_index < v.size() )\r\n      {\r\n       return v.at( P_index );\r\n      }\r\n\r\n     PyErr_SetString( PyExc_IndexError, \"index out of range\" );\r\n     return 0;\r\n    }\r\n\r\n   template < typename N_scalar, typename N_number, unsigned N_dimension>\r\n    void set( typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model<N_scalar, N_dimension>::T_typedef & v, int P_index, N_number value )\r\n     {\r\n      if(P_index >= 0 && P_index < v.size())\r\n       {\r\n        v.at( P_index ) = value;\r\n        return;\r\n       }\r\n\r\n       PyErr_SetString(PyExc_IndexError, \"index out of range\" );\r\n       return;\r\n     }\r\n\r\n   template < typename N_number >\r\n    typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model< N_number, 2 >::T_typedef &\r\n    load2( typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model<N_number, 2 >::T_typedef & v, N_number x, N_number y )\r\n     {\r\n      v[0] = x;\r\n      v[1] = y;\r\n      return v;\r\n     }\r\n   template < typename N_number >\r\n    typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model< N_number, 3 >::T_typedef &\r\n    load3( typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model<N_number, 3 >::T_typedef & v, N_number x, N_number y, N_number z )\r\n     {\r\n      v[0] = x;\r\n      v[1] = y;\r\n      v[2] = z;\r\n      return v;\r\n     }\r\n\r\n   template < typename N_number >\r\n    typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model< N_number, 4 >::T_typedef &\r\n    load4( typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model<N_number, 4 >::T_typedef & v, N_number x, N_number y, N_number z, N_number t )\r\n     {\r\n      v[0] = x;\r\n      v[1] = y;\r\n      v[2] = z;\r\n      v[3] = t;\r\n      return v;\r\n     }\r\n\r\n   template < typename N_number, unsigned dimension_number >\r\n    typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model< N_number, dimension_number >::T_typedef &\r\n    fill( typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model<N_number, dimension_number >::T_typedef & v, N_number x )\r\n     {\r\n      ::math::linear::vector::fill( v, x );\r\n      return v;\r\n     }\r\n\r\n\r\n    template < typename N_number >\r\n     typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model< N_number, 3 >::T_typedef\r\n      GFs_cross\r\n       (\r\n         typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model<N_number, 3 >::T_typedef const& P_left\r\n        ,typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model<N_number, 3 >::T_typedef const& P_right\r\n       )\r\n       {\r\n        typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model<N_number, 3 >::T_typedef Ir_right;\r\n        ::math::linear::vector::cross( Ir_right, P_left, P_right );\r\n        return Ir_right;\r\n       }\r\n\r\n    template < typename N_number, unsigned N_dimension >\r\n     N_number\r\n     GFs_dot\r\n      (\r\n        typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model<N_number, N_dimension >::T_typedef const& P_left\r\n       ,typename GS_DDMRM::S_IceRay::S_type::S_coord::GC__model<N_number, N_dimension >::T_typedef const& P_right\r\n      )\r\n      {\r\n       return  ::math::linear::vector::dot( P_left, P_right );\r\n      }\r\n\r\n  }\r\n\r\nvoid expose_math_type_coord_cell()\r\n {\r\n//MAKE_SUBMODULE( IceRay );\r\n  MAKE_SUBMODULE( library   );\r\n  MAKE_SUBMODULE( math   );\r\n\r\n  boost::python::class_<GTs_cell2D>( \"MathTypeCell2D\" )\r\n    .def( boost::python::init<>() )\r\n  //.def( boost::python::init<GTs_int>() )\r\n  //.def( boost::python::init<GTs_scalar>() )\r\n  //.def( boost::python::init<GTs_int,GTs_int>( TODO ) )\r\n    .def( boost::python::init<GTs_cell2D>() )\r\n\r\n    .def(\"__getitem__\", &get<GTs_int, 2 > )\r\n    .def(\"__setitem__\", &set<GTs_int, GTs_int, 2 > )\r\n    .def(\"__setitem__\", &set<GTs_int, GTs_scalar, 2 > )\r\n\r\n    .def( \"load\",       &load2<GTs_size   >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"load\",       &load2<GTs_scalar >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"fill\",       &fill<GTs_size,2>, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n\r\n    .def( boost::python::self + boost::python::self )\r\n    .def( boost::python::self - boost::python::self )\r\n    .def( boost::python::self * GTs_size() )\r\n    .def( GTs_size() * boost::python::self  )\r\n    .def( boost::python::self / GTs_int() )\r\n    .def( boost::python::self /= GTs_int() )\r\n    .def( boost::python::self *= GTs_int() )\r\n    .def( boost::python::self += boost::python::self )\r\n    .def( boost::python::self -= boost::python::self )\r\n  ;\r\n\r\n  boost::python::class_<GTs_cell3D>( \"MathTypeCell3D\" )\r\n    .def( boost::python::init<>() )\r\n  //.def( boost::python::init<GTs_size>() )\r\n  //.def( boost::python::init<GTs_scalar>() )\r\n  //.def( boost::python::init<GTs_size,GTs_size,GTs_size>( TODO ) )\r\n   .def( boost::python::init<GTs_cell3D>() )\r\n\r\n    .def(\"__getitem__\", &get<GTs_int, 3 > )\r\n    .def(\"__setitem__\", &set<GTs_int, GTs_int, 3 > )\r\n    .def(\"__setitem__\", &set<GTs_int, GTs_scalar, 3 > )\r\n\r\n    .def( \"load\",       &load3<GTs_int   >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"load\",       &load3<GTs_scalar >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"fill\",       &fill<GTs_int,3>, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n\r\n    .def( boost::python::self + boost::python::self )\r\n    .def( boost::python::self - boost::python::self )\r\n    .def( boost::python::self * GTs_scalar() )\r\n    .def( GTs_scalar() * boost::python::self  )\r\n    .def( boost::python::self / GTs_int() )\r\n    .def( boost::python::self /= GTs_int() )\r\n    .def( boost::python::self *= GTs_int() )\r\n    .def( boost::python::self += boost::python::self )\r\n    .def( boost::python::self -= boost::python::self )\r\n  ;\r\n\r\n  boost::python::class_<GTs_cell4D>( \"MathTypeCell4D\" )\r\n    .def( boost::python::init<>() )\r\n    //.def( boost::python::init<GTs_int>() )\r\n    //.def( boost::python::init<GTs_scalar>() )\r\n    //.def( boost::python::init<GTs_int,GTs_int,GTs_int,GTs_int>( TODO ) )\r\n    .def( boost::python::init<GTs_cell4D>() )\r\n\r\n    .def(\"__getitem__\", &get<GTs_int, 4 > )\r\n    .def(\"__setitem__\", &set<GTs_int, GTs_int, 4 > )\r\n    .def(\"__setitem__\", &set<GTs_int, GTs_scalar, 4 > )\r\n\r\n    .def( \"load\",       &load4<GTs_int    >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"load\",       &load4<GTs_scalar >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"fill\",       &fill<GTs_int,   4>, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n\r\n    .def( boost::python::self + boost::python::self )\r\n    .def( boost::python::self - boost::python::self )\r\n    .def( boost::python::self * GTs_scalar() )\r\n    .def( GTs_scalar() * boost::python::self  )\r\n    .def( boost::python::self / GTs_int() )\r\n    .def( boost::python::self /= GTs_int() )\r\n    .def( boost::python::self *= GTs_int() )\r\n    .def( boost::python::self += boost::python::self )\r\n    .def( boost::python::self -= boost::python::self )\r\n    ;\r\n }\r\n\r\nvoid expose_math_type_coord_size()\r\n {\r\n//MAKE_SUBMODULE( IceRay );\r\n  MAKE_SUBMODULE( library   );\r\n  MAKE_SUBMODULE( math   );\r\n\r\n  boost::python::class_<GTs_size2D>( \"MathTypeSize2D\" )\r\n    .def( boost::python::init<>() )\r\n  //.def( boost::python::init<GTs_size>() )\r\n  //.def( boost::python::init<GTs_scalar>() )\r\n  //.def( boost::python::init<GTs_size,GTs_size>( TODO ) )\r\n    .def( boost::python::init<GTs_size2D>() )\r\n\r\n    .def(\"__getitem__\", &get<GTs_size, 2 > )\r\n    .def(\"__setitem__\", &set<GTs_size, GTs_size, 2 > )\r\n    .def(\"__setitem__\", &set<GTs_size, GTs_scalar, 2 > )\r\n\r\n    .def( \"load\",       &load2<GTs_size   >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"load\",       &load2<GTs_scalar >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"fill\",       &fill<GTs_size,2>, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n\r\n    .def( boost::python::self + boost::python::self )\r\n    .def( boost::python::self - boost::python::self )\r\n    .def( boost::python::self * GTs_size() )\r\n    .def( GTs_size() * boost::python::self  )\r\n    .def( boost::python::self / GTs_size() )\r\n    .def( boost::python::self /= GTs_size() )\r\n    .def( boost::python::self *= GTs_size() )\r\n    .def( boost::python::self += boost::python::self )\r\n    .def( boost::python::self -= boost::python::self )\r\n  ;\r\n\r\n  boost::python::class_<GTs_size3D>( \"MathTypeSize3D\" )\r\n    .def( boost::python::init<>() )\r\n  //.def( boost::python::init<GTs_size>() )\r\n  //.def( boost::python::init<GTs_scalar>() )\r\n  //.def( boost::python::init<GTs_size,GTs_size,GTs_size>( TODO ) )\r\n   .def( boost::python::init<GTs_size3D>() )\r\n\r\n    .def(\"__getitem__\", &get<GTs_size, 3 > )\r\n    .def(\"__setitem__\", &set<GTs_size, GTs_size, 3 > )\r\n    .def(\"__setitem__\", &set<GTs_size, GTs_scalar, 3 > )\r\n\r\n    .def( \"load\",       &load3<GTs_size   >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"load\",       &load3<GTs_scalar >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"fill\",       &fill<GTs_size,3>, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n\r\n    .def( boost::python::self + boost::python::self )\r\n    .def( boost::python::self - boost::python::self )\r\n    .def( boost::python::self * GTs_scalar() )\r\n    .def( GTs_scalar() * boost::python::self  )\r\n    .def( boost::python::self / GTs_size() )\r\n    .def( boost::python::self /= GTs_size() )\r\n    .def( boost::python::self *= GTs_size() )\r\n    .def( boost::python::self += boost::python::self )\r\n    .def( boost::python::self -= boost::python::self )\r\n  ;\r\n\r\n  boost::python::class_<GTs_size4D>( \"MathTypeSize4D\" )\r\n    .def( boost::python::init<>() )\r\n    //.def( boost::python::init<GTs_size>() )\r\n    //.def( boost::python::init<GTs_scalar>() )\r\n    //.def( boost::python::init<GTs_size,GTs_size,GTs_size,GTs_size>( TODO ) )\r\n    .def( boost::python::init<GTs_size4D>() )\r\n\r\n    .def(\"__getitem__\", &get<GTs_size, 4 > )\r\n    .def(\"__setitem__\", &set<GTs_size, GTs_size, 4 > )\r\n    .def(\"__setitem__\", &set<GTs_size, GTs_scalar, 4 > )\r\n\r\n    .def( \"load\",       &load4<GTs_size   >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"load\",       &load4<GTs_scalar >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"fill\",       &fill<GTs_size,4>, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n\r\n    .def( boost::python::self + boost::python::self )\r\n    .def( boost::python::self - boost::python::self )\r\n    .def( boost::python::self * GTs_scalar() )\r\n    .def( GTs_scalar() * boost::python::self  )\r\n    .def( boost::python::self / GTs_size() )\r\n    .def( boost::python::self /= GTs_size() )\r\n    .def( boost::python::self *= GTs_size() )\r\n    .def( boost::python::self += boost::python::self )\r\n    .def( boost::python::self -= boost::python::self )\r\n    ;\r\n }\r\n\r\n// TODO: s * v, v * s, v / s, v+v, v-v\r\nvoid expose_math_type_coord_scalar()\r\n {\r\n//MAKE_SUBMODULE( IceRay );\r\n  MAKE_SUBMODULE( library   );\r\n  MAKE_SUBMODULE( math   );\r\n\r\n  boost::python::class_<GTs_coord2D>( \"MathTypeCoord2D\" )\r\n    .def( boost::python::init<>() )\r\n  //.def( boost::python::init<GTs_scalar>() )\r\n  //.def( boost::python::init<GTs_scalar,GTs_scalar>( TODO ) )\r\n    .def( boost::python::init<GTs_coord2D>() )\r\n\r\n    .def(\"__getitem__\", &get<GTs_scalar, 2 > )\r\n    .def(\"__setitem__\", &set<GTs_scalar, GTs_scalar, 2 > )\r\n\r\n    .def( \"load\",        &load2<GTs_scalar >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"fill\",        &fill<GTs_scalar,2>, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n\r\n    .def( boost::python::self + boost::python::self )\r\n    .def( boost::python::self - boost::python::self )\r\n\r\n    .def( boost::python::self * GTs_scalar() )\r\n    .def( GTs_scalar() * boost::python::self  )\r\n\r\n    .def( boost::python::self / GTs_scalar() )\r\n\r\n    .def( boost::python::self /= GTs_scalar() )\r\n    .def( boost::python::self *= GTs_scalar() )\r\n\r\n    .def( boost::python::self += boost::python::self )\r\n    .def( boost::python::self -= boost::python::self )\r\n  ;\r\n\r\n  boost::python::def(\"MathCoord2D_dot\",  &GFs_dot<GTs_scalar, 2 > );\r\n\r\n  boost::python::def(\"MathLinearVector2DDot\",  &GFs_dot<GTs_scalar, 2 > );\r\n  boost::python::def(\"MathLinearVector3DLength\",  &::math::linear::vector::length<GTs_scalar,GTs_scalar, 4 > );\r\n\r\n  boost::python::class_<GTs_coord3D>( \"MathTypeCoord3D\" )\r\n    .def( boost::python::init<>() )\r\n   //.def( boost::python::init<GTs_scalar>() )\r\n   //.def( boost::python::init<GTs_scalar,GTs_scalar,GTs_scalar>( TODO ) )\r\n   .def( boost::python::init<GTs_coord3D>() )\r\n\r\n     .def( \"__getitem__\", &get<GTs_scalar, 3 > )\r\n     .def( \"__setitem__\", &set<GTs_scalar, GTs_scalar, 3 > )\r\n   //.def(\"__setitem__\", &set<GTs_scalar, GTs_size, 3 > )\r\n\r\n    .def( \"load\",        &load3<GTs_scalar >, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"fill\",        &fill<GTs_scalar,3>, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n\r\n    .def( boost::python::self + boost::python::self )\r\n    .def( boost::python::self - boost::python::self )\r\n\r\n    .def( boost::python::self * GTs_scalar() )\r\n    .def( GTs_scalar() * boost::python::self  )\r\n\r\n    .def( boost::python::self / GTs_scalar() )\r\n\r\n    .def( boost::python::self /= GTs_scalar() )\r\n    .def( boost::python::self *= GTs_scalar() )\r\n\r\n    .def( boost::python::self += boost::python::self )\r\n    .def( boost::python::self -= boost::python::self )\r\n   ;\r\n\r\n  boost::python::def(\"MathCoord3D_dot\",    &GFs_dot<GTs_scalar, 3 > );\r\n  boost::python::def(\"MathCoord3D_cross\",  &GFs_cross<GTs_scalar > );\r\n\r\n  boost::python::def(\"MathLinearVector3DDot\",  &GFs_dot<GTs_scalar, 2 > );\r\n  boost::python::def(\"MathLinearVector3DLength\",  &::math::linear::vector::length<GTs_scalar,GTs_scalar, 3 > );\r\n\r\n\r\n  boost::python::class_<GTs_coord4D>( \"MathTypeCoord4D\" )\r\n    .def( boost::python::init<>() )\r\n  //.def( boost::python::init<GTs_scalar>() )\r\n  //.def( boost::python::init<GTs_scalar,GTs_scalar,GTs_scalar,GTs_scalar>() )\r\n   .def( boost::python::init<GTs_coord4D>() )\r\n\r\n   .def(\"__getitem__\", &get<GTs_scalar, 4 > )\r\n   .def(\"__setitem__\", &set<GTs_scalar, GTs_scalar, 4 > )\r\n\r\n    .def( \"load\",       &load4<GTs_scalar>, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"load\",       &load4<GTs_size>, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n    .def( \"fill\",       &fill<GTs_scalar,4>, boost::python::return_value_policy<boost::python::return_by_value>() )\r\n\r\n    .def( boost::python::self + boost::python::self )\r\n    .def( boost::python::self - boost::python::self )\r\n    .def( boost::python::self * GTs_scalar() )\r\n    .def( GTs_scalar() * boost::python::self  )\r\n    .def( boost::python::self / GTs_scalar() )\r\n    .def( boost::python::self /= GTs_scalar() )\r\n    .def( boost::python::self *= GTs_scalar() )\r\n    .def( boost::python::self += boost::python::self )\r\n    .def( boost::python::self -= boost::python::self )\r\n   ;\r\n\r\n  boost::python::def(\"MathCoord4D_dot\",  &GFs_dot<GTs_scalar, 4 > );\r\n\r\n  boost::python::def(\"MathLinearVector4DDot\",  &GFs_dot<GTs_scalar, 2 > );\r\n  boost::python::def(\"MathLinearVector4DLength\",  &::math::linear::vector::length<GTs_scalar,GTs_scalar, 4 > );\r\n\r\n }\r\n\r\n\r\nvoid expose_math_type_coord_coord()\r\n {\r\n  expose_math_type_coord_cell();\r\n  expose_math_type_coord_size();\r\n  expose_math_type_coord_scalar();\r\n }", "meta": {"hexsha": "0650f05d69ac018c311e6ac631b57e2a109ab406", "size": 16932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/IceRay/main/interface/python/library/math/coord.cpp", "max_stars_repo_name": "dmilos/IceRay", "max_stars_repo_head_hexsha": "4e01f141363c0d126d3c700c1f5f892967e3d520", "max_stars_repo_licenses": ["MIT-0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-04T12:27:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T14:49:40.000Z", "max_issues_repo_path": "src/IceRay/main/interface/python/library/math/coord.cpp", "max_issues_repo_name": "dmilos/IceRay", "max_issues_repo_head_hexsha": "4e01f141363c0d126d3c700c1f5f892967e3d520", "max_issues_repo_licenses": ["MIT-0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/IceRay/main/interface/python/library/math/coord.cpp", "max_forks_repo_name": "dmilos/IceRay", "max_forks_repo_head_hexsha": "4e01f141363c0d126d3c700c1f5f892967e3d520", "max_forks_repo_licenses": ["MIT-0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T12:27:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T12:27:52.000Z", "avg_line_length": 42.2244389027, "max_line_length": 146, "alphanum_fraction": 0.6207772266, "num_tokens": 5349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.42948360339805713}}
{"text": "/** \n All of this code is written by Aman Agrawal \n (Indian Institute of Technology, Delhi)\n*/\n\n#include <bits/stdc++.h>\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n#include <Eigen/QR>\n#include \"time.h\"\n\n#include \"genotype.h\"\n#include \"mailman.h\"\n#include \"arguments.h\"\n#include \"helper.h\"\n#include \"storage.h\"\n\n#if SSE_SUPPORT==1\n\t#define fastmultiply fastmultiply_sse\n\t#define fastmultiply_pre fastmultiply_pre_sse\n#else\n\t#define fastmultiply fastmultiply_normal\n\t#define fastmultiply_pre fastmultiply_pre_normal\n#endif\n\nusing namespace Eigen;\nusing namespace std;\n\n// Storing in RowMajor Form\ntypedef Matrix<double, Dynamic, Dynamic, RowMajor> MatrixXdr;\n\n//Intermediate Variables\nint blocksize;\ndouble *partialsums;\ndouble *sum_op;\t\t\ndouble *yint_e;\ndouble *yint_m;\ndouble **y_e;\ndouble **y_m;\n\n\nstruct timespec t0;\n\nclock_t total_begin = clock();\n\ngenotype g;\nMatrixXdr geno_matrix; //(p,n)\n\nint MAX_ITER;\nint k,p,n;\nint k_orig;\n\nMatrixXdr c; //(p,k)\nMatrixXdr x; //(k,n)\nMatrixXdr v; //(p,k)\nMatrixXdr means; //(p,1)\nMatrixXdr stds; //(p,1)\n\noptions command_line_opts;\n\nbool debug = false;\nbool check_accuracy = false;\nbool var_normalize=false;\nint accelerated_em=0;\ndouble convergence_limit;\nbool memory_efficient = false;\nbool missing=false;\nbool fast_mode = true;\nbool text_version = false;\n\n\nvoid multiply_y_pre_fast(MatrixXdr &op, int Ncol_op ,MatrixXdr &res,bool subtract_means){\n\t\n\tfor(int k_iter=0;k_iter<Ncol_op;k_iter++){\n\t\tsum_op[k_iter]=op.col(k_iter).sum();\t\t\n\t}\n\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_time (); \n\t\t\tcout <<\"Starting mailman on premultiply\"<<endl;\n\t\t\tcout << \"Nops = \" << Ncol_op << \"\\t\" <<g.Nsegments_hori << endl;\n\t\t\tcout << \"Segment size = \" << g.segment_size_hori << endl;\n\t\t\tcout << \"Matrix size = \" <<g.segment_size_hori<<\"\\t\" <<g.Nindv << endl;\n\t\t\tcout << \"op = \" <<  op.rows () << \"\\t\" << op.cols () << endl;\n\t\t}\n\t#endif\n\n\n\t//TODO: Memory Effecient SSE FastMultipy\n\n\tfor(int seg_iter=0;seg_iter<g.Nsegments_hori-1;seg_iter++){\n\t\tmailman::fastmultiply(g.segment_size_hori,g.Nindv,Ncol_op,g.p[seg_iter],op,yint_m,partialsums,y_m);\n\t\tint p_base = seg_iter*g.segment_size_hori; \n\t\tfor(int p_iter=p_base; (p_iter<p_base+g.segment_size_hori) && (p_iter<g.Nsnp) ; p_iter++ ){\n\t\t\tfor(int k_iter=0;k_iter<Ncol_op;k_iter++) \n\t\t\t\tres(p_iter,k_iter) = y_m[p_iter-p_base][k_iter];\n\t\t}\n\t}\n\n\tint last_seg_size = (g.Nsnp%g.segment_size_hori !=0 ) ? g.Nsnp%g.segment_size_hori : g.segment_size_hori;\n\tmailman::fastmultiply(last_seg_size,g.Nindv,Ncol_op,g.p[g.Nsegments_hori-1],op,yint_m,partialsums,y_m);\t\t\n\tint p_base = (g.Nsegments_hori-1)*g.segment_size_hori;\n\tfor(int p_iter=p_base; (p_iter<p_base+g.segment_size_hori) && (p_iter<g.Nsnp) ; p_iter++){\n\t\tfor(int k_iter=0;k_iter<Ncol_op;k_iter++) \n\t\t\tres(p_iter,k_iter) = y_m[p_iter-p_base][k_iter];\n\t}\n\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_time (); \n\t\t\tcout <<\"Ending mailman on premultiply\"<<endl;\n\t\t}\n\t#endif\n\n\n\tif(!subtract_means)\n\t\treturn;\n\n\tfor(int p_iter=0;p_iter<p;p_iter++){\n \t\tfor(int k_iter=0;k_iter<Ncol_op;k_iter++){\t\t \n\t\t\tres(p_iter,k_iter) = res(p_iter,k_iter) - (g.get_col_mean(p_iter)*sum_op[k_iter]);\n\t\t\tif(var_normalize)\n\t\t\t\tres(p_iter,k_iter) = res(p_iter,k_iter)/(g.get_col_std(p_iter));\t\t\n \t\t}\t\t\n \t}\t\n\n}\n\nvoid multiply_y_post_fast(MatrixXdr &op_orig, int Nrows_op, MatrixXdr &res,bool subtract_means){\n\n\tMatrixXdr op;\n\top = op_orig.transpose();\n\n\tif(var_normalize && subtract_means){\n\t\tfor(int p_iter=0;p_iter<p;p_iter++){\n\t\t\tfor(int k_iter=0;k_iter<Nrows_op;k_iter++)\t\t\n\t\t\t\top(p_iter,k_iter) = op(p_iter,k_iter) / (g.get_col_std(p_iter));\t\t\n\t\t}\t\t\n\t}\n\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_time (); \n\t\t\tcout <<\"Starting mailman on postmultiply\"<<endl;\n\t\t}\n\t#endif\n\t\n\tint Ncol_op = Nrows_op;\n\n\n\tint seg_iter;\n\tfor(seg_iter=0;seg_iter<g.Nsegments_hori-1;seg_iter++){\n\t\tmailman::fastmultiply_pre(g.segment_size_hori,g.Nindv,Ncol_op, seg_iter * g.segment_size_hori, g.p[seg_iter],op,yint_e,partialsums,y_e);\n\t}\n\tint last_seg_size = (g.Nsnp%g.segment_size_hori !=0 ) ? g.Nsnp%g.segment_size_hori : g.segment_size_hori;\n\tmailman::fastmultiply_pre(last_seg_size,g.Nindv,Ncol_op, seg_iter * g.segment_size_hori, g.p[seg_iter],op,yint_e,partialsums,y_e);\n\n\tfor(int n_iter=0; n_iter<n; n_iter++)  {\n\t\tfor(int k_iter=0;k_iter<Ncol_op;k_iter++) {\n\t\t\tres(k_iter,n_iter) = y_e[n_iter][k_iter];\n\t\t\ty_e[n_iter][k_iter] = 0;\n\t\t}\n\t}\n\t\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_time (); \n\t\t\tcout <<\"Ending mailman on postmultiply\"<<endl;\n\t\t}\n\t#endif\n\n\n\tif(!subtract_means)\n\t\treturn;\n\n\tdouble *sums_elements = new double[Ncol_op];\n \tmemset (sums_elements, 0, Nrows_op * sizeof(int));\n\n \tfor(int k_iter=0;k_iter<Ncol_op;k_iter++){\t\t\n \t\tdouble sum_to_calc=0.0;\t\t\n \t\tfor(int p_iter=0;p_iter<p;p_iter++)\t\t\n \t\t\tsum_to_calc += g.get_col_mean(p_iter)*op(p_iter,k_iter);\t\t\n \t\tsums_elements[k_iter] = sum_to_calc;\t\t\n \t}\t\t\n \tfor(int k_iter=0;k_iter<Ncol_op;k_iter++){\t\t\n \t\tfor(int n_iter=0;n_iter<n;n_iter++)\t\t\n \t\t\tres(k_iter,n_iter) = res(k_iter,n_iter) - sums_elements[k_iter];\t\t\n \t}\n\n\n}\n\nvoid multiply_y_pre_naive_mem(MatrixXdr &op, int Ncol_op ,MatrixXdr &res){\n\tfor(int p_iter=0;p_iter<p;p_iter++){\n\t\tfor(int k_iter=0;k_iter<Ncol_op;k_iter++){\n\t\t\tdouble temp=0;\n\t\t\tfor(int n_iter=0;n_iter<n;n_iter++)\n\t\t\t\ttemp+= g.get_geno(p_iter,n_iter,var_normalize)*op(n_iter,k_iter);\n\t\t\tres(p_iter,k_iter)=temp;\n\t\t}\n\t}\n}\n\nvoid multiply_y_post_naive_mem(MatrixXdr &op, int Nrows_op ,MatrixXdr &res){\n\tfor(int n_iter=0;n_iter<n;n_iter++){\n\t\tfor(int k_iter=0;k_iter<Nrows_op;k_iter++){\n\t\t\tdouble temp=0;\n\t\t\tfor(int p_iter=0;p_iter<p;p_iter++)\n\t\t\t\ttemp+= op(k_iter,p_iter)*(g.get_geno(p_iter,n_iter,var_normalize));\n\t\t\tres(k_iter,n_iter)=temp;\n\t\t}\n\t}\n}\n\nvoid multiply_y_pre_naive(MatrixXdr &op, int Ncol_op ,MatrixXdr &res){\n\tres = geno_matrix * op;\n}\n\nvoid multiply_y_post_naive(MatrixXdr &op, int Nrows_op ,MatrixXdr &res){\n\tres = op * geno_matrix;\n}\n\nvoid multiply_y_post(MatrixXdr &op, int Nrows_op ,MatrixXdr &res,bool subtract_means){\n    if(fast_mode)\n        multiply_y_post_fast(op,Nrows_op,res,subtract_means);\n    else{\n\t\tif(memory_efficient)\n\t\t\tmultiply_y_post_naive_mem(op,Nrows_op,res);\n\t\telse\n\t\t\tmultiply_y_post_naive(op,Nrows_op,res);\n\t}\n}\n\nvoid multiply_y_pre(MatrixXdr &op, int Ncol_op ,MatrixXdr &res,bool subtract_means){\n    if(fast_mode)\n        multiply_y_pre_fast(op,Ncol_op,res,subtract_means);\n    else{\n\t\tif(memory_efficient)\n\t\t\tmultiply_y_pre_naive_mem(op,Ncol_op,res);\n\t\telse\n\t\t\tmultiply_y_pre_naive(op,Ncol_op,res);\n\t}\n}\n\npair<double,double> get_error_norm(MatrixXdr &c){\n\tHouseholderQR<MatrixXdr> qr(c);\n\tMatrixXdr Q;\n\tQ = qr.householderQ() * MatrixXdr::Identity(p,k);\n\tMatrixXdr q_t(k,p);\n\tq_t = Q.transpose();\n\tMatrixXdr b(k,n);\n\tmultiply_y_post(q_t,k,b,true);\n\tJacobiSVD<MatrixXdr> b_svd(b, ComputeThinU | ComputeThinV);\n\tMatrixXdr u_l,d_l,v_l; \n\tif(fast_mode)\n        u_l = b_svd.matrixU();\n    else\n        u_l = Q * b_svd.matrixU();\n\tv_l = b_svd.matrixV();\n\td_l = MatrixXdr::Zero(k,k);\n\tfor(int kk=0;kk<k; kk++)\n\t\td_l(kk,kk) = (b_svd.singularValues())(kk);\n\t\n\tMatrixXdr u_k,v_k,d_k;\n\tu_k = u_l.leftCols(k_orig);\n\tv_k = v_l.leftCols(k_orig);\n\td_k = MatrixXdr::Zero(k_orig,k_orig);\n\tfor(int kk =0 ; kk < k_orig ; kk++)\n\t\td_k(kk,kk)  =(b_svd.singularValues())(kk);\n\n\tMatrixXdr b_l,b_k;\n    b_l = u_l * d_l * (v_l.transpose());\n    b_k = u_k * d_k * (v_k.transpose());\n\n    if(fast_mode){\n        double temp_k = b_k.cwiseProduct(b).sum();\n        double temp_l = b_l.cwiseProduct(b).sum();\n        double b_knorm = b_k.norm();\n        double b_lnorm = b_l.norm();\n        double norm_k = (b_knorm*b_knorm) - (2*temp_k);\n        double norm_l = (b_lnorm*b_lnorm) - (2*temp_l);\t\n        return make_pair(norm_k,norm_l);\n    }\n    else{\n        MatrixXdr e_l(p,n);\n        MatrixXdr e_k(p,n);\n        for(int p_iter=0;p_iter<p;p_iter++){\n            for(int n_iter=0;n_iter<n;n_iter++){\n                e_l(p_iter,n_iter) = g.get_geno(p_iter,n_iter,var_normalize) - b_l(p_iter,n_iter);\n                e_k(p_iter,n_iter) = g.get_geno(p_iter,n_iter,var_normalize) - b_k(p_iter,n_iter);\n            }\n        }\n\n        double ek_norm = e_k.norm();\n        double el_norm = e_l.norm();\n        return make_pair(ek_norm,el_norm);\n    }\n}\n\nMatrixXdr run_EM_not_missing(MatrixXdr &c_orig){\n\t\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_time ();\n\t\t\tcout << \"Enter: run_EM_not_missing\" << endl;\n\t\t}\n\t#endif\n\n\tMatrixXdr c_temp(k,p);\n\tMatrixXdr c_new(p,k);\n\tc_temp = ( (c_orig.transpose()*c_orig).inverse() ) * (c_orig.transpose());\n\t\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_timenl ();\n\t\t}\n\t#endif\n\t\n\tMatrixXdr x_fn(k,n);\n\tmultiply_y_post(c_temp,k,x_fn,true);\n\t\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_timenl ();\n\t\t}\n\t#endif\n\t\n\tMatrixXdr x_temp(n,k);\n\tx_temp = (x_fn.transpose()) * ((x_fn*(x_fn.transpose())).inverse());\n\tmultiply_y_pre(x_temp,k,c_new,true);\n\t\n\t#if DEBUG==1\n\t\tif(debug){\n\t\t\tprint_time ();\n\t\t\tcout << \"Exiting: run_EM_not_missing\" << endl;\n\t\t}\n\t#endif\n\n\treturn c_new;\n}\n\nMatrixXdr run_EM_missing(MatrixXdr &c_orig){\n\t\n\tMatrixXdr c_new(p,k);\n\n\tMatrixXdr mu(k,n);\n\t\n\t// E step\n\tMatrixXdr c_temp(k,k);\n\tc_temp = c_orig.transpose() * c_orig;\n\n\tMatrixXdr T(k,n);\n\tMatrixXdr c_fn;\n\tc_fn = c_orig.transpose();\n\tmultiply_y_post(c_fn,k,T,false);\n\n\tMatrixXdr M_temp(k,1);\n\tM_temp = c_orig.transpose() *  means;\n\t\n\tfor(int j=0;j<n;j++){\n\t\tMatrixXdr D(k,k);\n\t\tMatrixXdr M_to_remove(k,1);\n\t\tD = MatrixXdr::Zero(k,k);\n\t\tM_to_remove = MatrixXdr::Zero(k,1);\n\t\tfor(int i=0;i<g.not_O_j[j].size();i++){\n\t\t\tint idx = g.not_O_j[j][i];\n\t\t\tD = D + (c_orig.row(idx).transpose() * c_orig.row(idx));\n\t\t\tM_to_remove = M_to_remove + (c_orig.row(idx).transpose()*g.get_col_mean(idx));\n\t\t}\n\t\tmu.col(j) = (c_temp-D).inverse() * ( T.col(j) - M_temp + M_to_remove);\n\t}\n\n\t// M step\n\n\tMatrixXdr mu_temp(k,k);\n\tmu_temp = mu * mu.transpose();\n\tMatrixXdr T1(p,k);\n\tMatrixXdr mu_fn;\n\tmu_fn = mu.transpose();\n\tmultiply_y_pre(mu_fn,k,T1,false);\n\tMatrixXdr mu_sum(k,1);\n\tmu_sum = MatrixXdr::Zero(k,1);\n\tmu_sum = mu.rowwise().sum();\n\n\tfor(int i=0;i<p;i++){\n\t\tMatrixXdr D(k,k);\n\t\tMatrixXdr mu_to_remove(k,1);\n\t\tD = MatrixXdr::Zero(k,k);\n\t\tmu_to_remove = MatrixXdr::Zero(k,1);\n\t\tfor(int j=0;j<g.not_O_i[i].size();j++){\n\t\t\tint idx = g.not_O_i[i][j];\n\t\t\tD = D + (mu.col(idx) * mu.col(idx).transpose());\n\t\t\tmu_to_remove = mu_to_remove + (mu.col(idx));\n\t\t}\n\t\tc_new.row(i) = (((mu_temp-D).inverse()) * (T1.row(i).transpose() -  ( g.get_col_mean(i) * (mu_sum-mu_to_remove)))).transpose();\n\t\tdouble mean;\n\t\tmean = g.get_col_sum(i);\n\t\tmean = mean -  (c_orig.row(i)*(mu_sum-mu_to_remove))(0,0);\n\t\tmean = mean * 1.0 / (n-g.not_O_i[i].size());\n\t\tg.update_col_mean(i,mean);\n\t}\n\treturn c_new;\n}\n\nMatrixXdr run_EM(MatrixXdr &c_orig){\n\t\n\tif(missing)\n\t\treturn run_EM_missing(c_orig);\n\telse\n\t\treturn run_EM_not_missing(c_orig);\n}\n\nvoid print_vals(){\n\n\tHouseholderQR<MatrixXdr> qr(c);\n\tMatrixXdr Q;\n\tQ = qr.householderQ() * MatrixXdr::Identity(p,k);\n\tMatrixXdr q_t(k,p);\n\tq_t = Q.transpose();\n\tMatrixXdr b(k,n);\n\tmultiply_y_post(q_t,k,b,true);\n\tJacobiSVD<MatrixXdr> b_svd(b, ComputeThinU | ComputeThinV);\n\tMatrixXdr u_l; \n\tu_l = b_svd.matrixU();\n\tMatrixXdr v_l;\n\tv_l = b_svd.matrixV();\n\tMatrixXdr u_k;\n\tMatrixXdr v_k,d_k;\n\tu_k = u_l.leftCols(k_orig);\n\tv_k = v_l.leftCols(k_orig);\n\n\tofstream evec_file;\n\tevec_file.open((string(command_line_opts.OUTPUT_PATH)+string(\"evecs.txt\")).c_str());\n\tevec_file<< std::setprecision(15) << Q*u_k << endl;\n\tevec_file.close();\n\tofstream eval_file;\n\teval_file.open((string(command_line_opts.OUTPUT_PATH)+string(\"evals.txt\")).c_str());\n\tfor(int kk =0 ; kk < k_orig ; kk++)\n\t\teval_file << std::setprecision(15)<< (b_svd.singularValues())(kk)<<endl;\n\teval_file.close();\n\n\tofstream proj_file;\n\tproj_file.open((string(command_line_opts.OUTPUT_PATH) + string(\"projections.txt\")).c_str());\n\tproj_file << std::setprecision(15)<< v_k<<endl;\n\tproj_file.close();\n\tif(debug){\n\t\tofstream c_file;\n\t\tc_file.open((string(command_line_opts.OUTPUT_PATH)+string(\"cvals.txt\")).c_str());\n\t\tc_file<<c<<endl;\n\t\tc_file.close();\n\t\t\n\t\td_k = MatrixXdr::Zero(k_orig,k_orig);\n\t\tfor(int kk =0 ; kk < k_orig ; kk++)\n\t\t\td_k(kk,kk)  =(b_svd.singularValues())(kk);\n\t\tMatrixXdr x_k;\n\t\tx_k = d_k * (v_k.transpose());\n\t\tofstream x_file;\n\t\tx_file.open((string(command_line_opts.OUTPUT_PATH) + string(\"xvals.txt\")).c_str());\n\t\tx_file<<x_k.transpose()<<endl;\n\t\tx_file.close();\n\t}\n}\n\nint main(int argc, char const *argv[]){\n\n\tclock_t io_begin = clock();\n    clock_gettime (CLOCK_REALTIME, &t0);\n\n\tpair<double,double> prev_error = make_pair(0.0,0.0);\n\tdouble prevnll=0.0;\n\n\tparse_args(argc,argv);\n\n\t\n\t//TODO: Memory Effecient Version of Mailman\n\n\tmemory_efficient = command_line_opts.memory_efficient;\n\ttext_version = command_line_opts.text_version;\n    fast_mode = command_line_opts.fast_mode;\n\tmissing = command_line_opts.missing;\n\n\t\n\tif(text_version){\n\t\tif(fast_mode)\n\t\t\tg.read_txt_mailman(command_line_opts.GENOTYPE_FILE_PATH,missing);\n\t\telse\n\t\t\tg.read_txt_naive(command_line_opts.GENOTYPE_FILE_PATH,missing);\n\t}\n\telse{\n\t\tg.read_plink(command_line_opts.GENOTYPE_FILE_PATH,missing,fast_mode);\n\t}\n\n\t//TODO: Implement these codes.\n\tif(missing && !fast_mode){\n\t\tcout<<\"Missing version works only with mailman i.e. fast mode\\n EXITING...\"<<endl;\n\t\texit(-1);\n\t}\n\tif(fast_mode && memory_efficient){\n\t\tcout<<\"Memory effecient version for mailman EM not yet implemented\"<<endl;\n\t\tcout<<\"Ignoring Memory effecient Flag\"<<endl;\n\t}\n\tif(missing && var_normalize){\n\t\tcout<<\"Missing version works only without variance normalization\\n EXITING...\"<<endl;\n\t\texit(-1);\n\t}\n\n    MAX_ITER =  command_line_opts.max_iterations ; \n\tk_orig = command_line_opts.num_of_evec ;\n\tdebug = command_line_opts.debugmode ;\n\tcheck_accuracy = command_line_opts.getaccuracy;\n\tvar_normalize = command_line_opts.var_normalize;\n\taccelerated_em = command_line_opts.accelerated_em;\n\tk = k_orig + command_line_opts.l;\n\tk = (int)ceil(k/10.0)*10;\n\tcommand_line_opts.l = k - k_orig;\n\tp = g.Nsnp;\n\tn = g.Nindv;\n\tconvergence_limit = command_line_opts.convergence_limit;\n\tbool toStop=false;\n\tif(convergence_limit!=-1)\n\t\ttoStop=true;\n\tsrand((unsigned int) time(0));\n\tc.resize(p,k);\n\tx.resize(k,n);\n\tv.resize(p,k);\n\tmeans.resize(p,1);\n\tstds.resize(p,1);\n\n\tif(!fast_mode && !memory_efficient){\n\t\tgeno_matrix.resize(p,n);\n\t\tg.generate_eigen_geno(geno_matrix,var_normalize);\n\t}\n\t\n\tclock_t io_end = clock();\n\n\t//TODO: Initialization of c with gaussian distribution\n\tc = MatrixXdr::Random(p,k);\n\n\n\t// Initial intermediate data structures\n\tblocksize = k;\n\tint hsegsize = g.segment_size_hori; \t// = log_3(n)\n\tint hsize = pow(3,hsegsize);\t\t \n\tint vsegsize = g.segment_size_ver; \t\t// = log_3(p)\n\tint vsize = pow(3,vsegsize);\t\t \n\n\tpartialsums = new double [blocksize];\n\tsum_op = new double[blocksize];\n\tyint_e = new double [hsize*blocksize];\n\tyint_m = new double [hsize*blocksize];\n\tmemset (yint_m, 0, hsize*blocksize * sizeof(double));\n\tmemset (yint_e, 0, hsize*blocksize * sizeof(double));\n\n\ty_e  = new double*[g.Nindv];\n\tfor (int i = 0 ; i < g.Nindv ; i++) {\n\t\ty_e[i] = new double[blocksize];\n\t\tmemset (y_e[i], 0, blocksize * sizeof(double));\n\t}\n\n\ty_m = new double*[hsegsize];\n\tfor (int i = 0 ; i < hsegsize ; i++)\n\t\ty_m[i] = new double[blocksize];\n\n\tfor(int i=0;i<p;i++){\n\t\tmeans(i,0) = g.get_col_mean(i);\n\t\tstds(i,0) = g.get_col_std(i);\n\t}\n\t\t\n\n\tofstream c_file;\n\tif(debug){\n\t\tc_file.open((string(command_line_opts.OUTPUT_PATH)+string(\"cvals_orig.txt\")).c_str());\n\t\tc_file<<c<<endl;\n\t\tc_file.close();\n\t\tprintf(\"Read Matrix\\n\");\n\t}\n\n\tcout<<\"Running on Dataset of \"<<g.Nsnp<<\" SNPs and \"<<g.Nindv<<\" Individuals\"<<endl;\n\n\t#if SSE_SUPPORT==1\n\t\tif(fast_mode)\n\t\t\tcout<<\"Using Optimized SSE FastMultiply\"<<endl;\n\t#endif\n\n\t\n\t\n\tclock_t it_begin = clock();\n\tfor(int i=0;i<MAX_ITER;i++){\n\n\t\tMatrixXdr c1,c2,cint,r,v;\n\t\tdouble a,nll;\n\t\tif(debug){\n\t\t\tprint_time (); \n\t\t\tcout << \"*********** Begin epoch \" << i << \"***********\" << endl;\n\t\t}\n\t\tif(accelerated_em!=0){\n\t\t\t#if DEBUG==1\n\t\t\t\tif(debug){\n\t\t\t\t\tprint_time();\n\t\t\t\t\tcout << \"Before EM\" << endl;\n\t\t\t\t}\n\t\t\t#endif\n\t\t\tc1 = run_EM(c);\n\t\t\tc2 = run_EM(c1);\n\t\t\t#if DEBUG==1\n\t\t\t\tif(debug){\n\t\t\t\t\tprint_time(); \n\t\t\t\t\tcout << \"After EM but before acceleration\" << endl;\n\t\t\t\t}\n\t\t\t#endif\n\t\t\tr = c1-c;\n\t\t\tv = (c2-c1) - r;\n\t\t\ta = -1.0 * r.norm() / (v.norm()) ;\n\t\t\tif(accelerated_em==1){\n\t\t\t\tif(a>-1){\n\t\t\t\t\ta=-1;\n\t\t\t\t\tcint=c2;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcint = c - 2*a*r + a*a*v;\n\t\t\t\t\tnll = get_error_norm(cint).second;\n\t\t\t\t\tif(i>0){\n\t\t\t\t\t\twhile(nll>prevnll && a<-1){\n\t\t\t\t\t\t\ta = 0.5 * (a-1);\n\t\t\t\t\t\t\tcint = c - 2*a*r +(a*a*v);\n\t\t\t\t\t\t\tnll = get_error_norm(cint).second;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tc = cint;\n\t\t\t}\n\t\t\telse if(accelerated_em==2){\n\t\t\t\tcint = c - 2*a*r + a*a*v;\n\t\t\t\tc = cint;\n\t\t\t\t// c = run_EM(cint);\t\t\t\t\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tc = run_EM(c);\n\t\t}\n\t\t\n\t\tif ( accelerated_em == 1 || check_accuracy || toStop) {\n\t\t\tpair<double,double> e = get_error_norm(c);\n\t\t\tprevnll = e.second;\n\t\t\tif(check_accuracy) \n\t\t\t\tcout<<\"Iteration \"<<i+1<<\"  \"<<std::setprecision(15)<<e.first<<\"  \"<<e.second<<endl;\n\t\t\tif(abs(e.first-prev_error.first)<=convergence_limit){\n\t\t\t\tcout<<\"Breaking after \"<<i+1<<\" iterations\"<<endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tprev_error = e;\n\t\t}\n\t\tif(debug){\n\t\t\tprint_time (); \n\t\t\tcout << \"*********** End epoch \" << i << \"***********\" << endl;\n\t\t}\n\n\t}\n\tclock_t it_end = clock();\n\n    print_vals();\n\t\t\n\tclock_t total_end = clock();\n\tdouble io_time = double(io_end - io_begin) / CLOCKS_PER_SEC;\n\tdouble avg_it_time = double(it_end - it_begin) / (MAX_ITER * 1.0 * CLOCKS_PER_SEC);\n\tdouble total_time = double(total_end - total_begin) / CLOCKS_PER_SEC;\n\tcout<<\"IO Time:  \"<< io_time << \"\\nAVG Iteration Time:  \"<<avg_it_time<<\"\\nTotal runtime:   \"<<total_time<<endl;\n\n\tdelete[] sum_op;\n\tdelete[] partialsums;\n\tdelete[] yint_e; \n\tdelete[] yint_m;\n\n\tfor (int i  = 0 ; i < hsegsize; i++)\n\t\tdelete[] y_m [i]; \n\tdelete[] y_m;\n\n\tfor (int i  = 0 ; i < g.Nindv; i++)\n\t\tdelete[] y_e[i]; \n\tdelete[] y_e;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "95b417f802d90306a94ff2837a2f94f22b609f78", "size": 17707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fastppca.cpp", "max_stars_repo_name": "aman71197/fast_em_pca", "max_stars_repo_head_hexsha": "d5708470ab4e97434f809fa1d5f54a7eec4f3daa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-07-17T21:45:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-16T07:24:36.000Z", "max_issues_repo_path": "src/fastppca.cpp", "max_issues_repo_name": "aman71197/fastPPCA", "max_issues_repo_head_hexsha": "d5708470ab4e97434f809fa1d5f54a7eec4f3daa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/fastppca.cpp", "max_forks_repo_name": "aman71197/fastPPCA", "max_forks_repo_head_hexsha": "d5708470ab4e97434f809fa1d5f54a7eec4f3daa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7743813683, "max_line_length": 138, "alphanum_fraction": 0.6622239792, "num_tokens": 5587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4294698415769343}}
{"text": "/*======================================================================\nCopyright 2019 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n======================================================================*/\n\n\n#include <cmath>\n\n#include <Eigen/Dense>\n#include \"PCV_Types.h\"\n\n#include \"Caster.h\"\n\nusing namespace Eigen;\n\nCaster::Caster(\n            double _Kx, double _Ky, double _ang,\n            double  _b, double  _r,\n            double  _f, double _Mf, double _If,\n            double _Ih, double _Ii, double _Is, double _It, double _Ij,\n            double _Ns, double _Nt, double _Nw,\n            double _px, double _py, double _Mp, double _Ip)\n    :Lambda(M3Z), Mu(V3Z),\n     Ce(M3I), Jdot(M3Z), A(M3Z), CC(V3Z), L_Pk(M3Z), Mu_Pk(V3Z)\n{\n Kx = _Kx;   Ky = _Ky;\n  b = _b;    bi= 1.0/b;   r = _r;    ri= 1.0/r;\n  f = _f;    e = f-b;    Mf = _Mf;  If = _If;\n Ih = _Ih;  Ii = _Ii;    Is = _Is;  It = _It;    Ij = _Ij;\n Ns = _Ns;  Nt = _Nt;    Nw = _Nw;\n px = _px;  py = _py;    Mp = _Mp;  Ip = _Ip;\n\n Px = Kx + px;\n Py = Ky + py;\n P2  = pow(Px,2) + pow(Py,2);\n\n enc_offset = (long)(((M_PI_2 - _ang) * Ns * ENC_RAD2CNT)+0.5);\n\n Fill_A();\n Fill_L_Pk();\n}\n\n\nvoid\nCaster::Fill_A()\n{\n  double mfe2Ifih= Mf*e*e + If + Ii + Ih;\n  double IsNs    = Is * Ns;\n  double ItNt    = It * Nt;\n  double ItNt2   = ItNt*Nt;\n\n  A(0,0) = mfe2Ifih + IsNs*Ns + ItNt;\n  A(0,1) = (Ii - Ih - ItNt2) * Nw;\n  A(0,2) = mfe2Ifih - IsNs - ItNt;\n\n  A(1,0) = A(0,1);\n  A(1,1) = Mf*r*r + (Ii + Ih + ItNt2)*Nw*Nw + Ij;\n  A(1,2) = (Ii - Ih + ItNt ) * Nw;\n\n  A(2,0) = A(0,2);\n  A(2,1) = A(1,2);\n  A(2,2) = mfe2Ifih + Is + It;\n}\n\n\ninline void\nCaster::Fill_CC()\n{\n  register double  u_w = u + w;\n  register double Mfre = Mf*r*e;\n\n  CC(0) =  Mfre * v * u_w;\n  CC(1) = -Mfre * pow(u_w,2);\n  CC(2) =  CC[0];\n}\n\n\nvoid\nCaster::Fill_L_Pk()\n{\n  L_Pk(0,0) =  Mp;\n  L_Pk(0,1) =  0.0;\n  L_Pk(0,2) = -Mp * Py;\n\n  L_Pk(1,0) =  0.0;\n  L_Pk(1,1) =  Mp;\n  L_Pk(1,2) =  Mp * Px;\n\n  L_Pk(2,0) = L_Pk(0,2);\n  L_Pk(2,1) = L_Pk(1,2);\n  L_Pk(2,2) = Ip + Mp*P2;\n}\n\n\ninline void\nCaster::Fill_Mu_Pk()\n{\n  register double w2  = pow(w,2);\n\n  Mu_Pk(0) = -Mp * Px * w2;\n  Mu_Pk(1) = -Mp * Py * w2;\n  Mu_Pk(2) =  0.0;\n}\n\n\ninline void\nCaster::Fill_Ce()  // Ce (C_theta) (a.k.a. Ji )\n{\n  Ce(0,0) =  bi*s;\n  Ce(0,1) = -bi*c;\n  Ce(0,2) = -bi*(Kx*c + Ky*s) - 1.0;\n\n  Ce(1,0) =  ri*c;\n  Ce(1,1) =  ri*s;\n  Ce(1,2) =  ri*(Kx*s - Ky*c);\n\n  Ce(2,0) =  0.0;\n  Ce(2,1) =  0.0;\n  Ce(2,2) =  1.0;\n}\n\n\ninline void\nCaster::Fill_Jdot()\n{\n  register double u_w = u + w;\n\n  Jdot(0,0) =  b*c*u_w;\n  Jdot(0,1) = -r*s*u_w;\n  Jdot(0,2) =  Kx*w + b*c*u_w;\n\n  Jdot(1,0) =  b*s*u_w;\n  Jdot(1,1) =  r*c*u_w;\n  Jdot(1,2) =  Ky*w + b*s*u_w;\n\n  Jdot(2,0) =  0.0;\n  Jdot(2,1) =  0.0;\n  Jdot(2,2) =  0.0;\n}\n\n\nvoid\nCaster::Fill_LM( double const _u,   // sigma dot\n                 double const _v,   //  rho  dot\n                 double const _w)   // theta dot\n{\n\n  static Vector3d   Qdot(3);\n\n  // SET STATE\n  Qdot[0] = u = _u;\n  Qdot[1] = v = _v;\n  Qdot[2] = w = _w;\n\n  // FILL JACOBIANS\n  Fill_Ce();\n  Fill_Jdot();\n\n  // FILL JT-SPACE CC VECTOR (NOTE: 'A' IS CONSTANT)\n  Fill_CC();\n  // FILL OP-SPACE CC VECTOR (NOTE: 'L_Pk' IS CONSTANT)\n  Fill_Mu_Pk();\n\n  //Lambda = L_Pk + (Cet * A * Ce)\n  Lambda = L_Pk + Ce.transpose() * A * Ce;\n\n  //Mu = Mu_Pk + [Cet * ( CC - (A*(Ce*(Jdot*Qdot))) )]\n  Mu = Mu_Pk + Ce.transpose()*(CC-(A*(Ce*(Jdot*Qdot))));\n}\n", "meta": {"hexsha": "b6c1c0d7b71684d7a603604cf0b24b2c65a05b4f", "size": 3842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Caster.cpp", "max_stars_repo_name": "google/powered-caster-vehicle", "max_stars_repo_head_hexsha": "ad231909e8cbe6785dbf682aac6bbe33797f92c8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T17:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-14T08:34:10.000Z", "max_issues_repo_path": "Caster.cpp", "max_issues_repo_name": "google/powered-caster-vehicle", "max_issues_repo_head_hexsha": "ad231909e8cbe6785dbf682aac6bbe33797f92c8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Caster.cpp", "max_forks_repo_name": "google/powered-caster-vehicle", "max_forks_repo_head_hexsha": "ad231909e8cbe6785dbf682aac6bbe33797f92c8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T18:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-16T23:17:59.000Z", "avg_line_length": 21.226519337, "max_line_length": 72, "alphanum_fraction": 0.5249869859, "num_tokens": 1629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4294698415769343}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_LAMBERT_W_HPP\n#define STAN_MATH_PRIM_FUN_LAMBERT_W_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/fun/boost_policy.hpp>\n#include <boost/math/special_functions/lambert_w.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Compute the Lambert W function on W0 branch for a value x.\n *\n * @tparam T type of value\n * @param x value\n * @return value of the W0 branch of the Lambert W function for x\n * @throw std::domain_error if x is less than or equal to `-e^(-1)`\n */\ntemplate <typename T, require_arithmetic_t<T>* = nullptr>\ninline double lambert_w0(const T& x) {\n  return boost::math::lambert_w0(x, boost_policy_t<>());\n}\n\n/**\n * Compute the Lambert W function on W-1 branch for a value x.\n *\n * @tparam T type of value\n * @param x value\n * @return value of the W-1 branch of the Lambert W function for x\n * @throw std::domain_error if x is less than or equal to `-e^(-1)` or greater\n * than or equal to 0\n */\ntemplate <typename T, require_arithmetic_t<T>* = nullptr>\ninline double lambert_wm1(const T& x) {\n  return boost::math::lambert_wm1(x, boost_policy_t<>());\n}\n\nnamespace internal {\n\n/**\n * Structure to wrap lambert_w0() so it can be vectorized.\n *\n * @tparam T type of variable\n * @param x variable\n * @return value of the W0 branch of the Lambert W function at x.\n * @throw std::domain_error if x is less than or equal to `-e^(-1)`\n */\nstruct lambert_w0_fun {\n  template <typename T>\n  static inline T fun(const T& x) {\n    return lambert_w0(x);\n  }\n};\n\n/**\n * Structure to wrap lambert_wm1() so it can be vectorized.\n *\n * @tparam T type of variable\n * @param x variable\n * @return value of the W-1 branch of the Lambert W function at x.\n * @throw std::domain_error if x is less than or equal to `-e^(-1)` or greater\n * than or equal to 0\n */\nstruct lambert_wm1_fun {\n  template <typename T>\n  static inline T fun(const T& x) {\n    return lambert_wm1(x);\n  }\n};\n}  // namespace internal\n\n/**\n * Vectorized version of lambert_w0().\n *\n * @tparam T type of container\n * @param x container\n * @return value of the W0 branch of the Lambert W function for each value in x\n * @throw std::domain_error if x is less than or equal to `-e^(-1)`\n */\ntemplate <typename T, require_not_stan_scalar_t<T>* = nullptr>\ninline auto lambert_w0(const T& x) {\n  return apply_scalar_unary<internal::lambert_w0_fun, T>::apply(x);\n}\n\n/**\n * Vectorized version of lambert_wm1().\n *\n * @tparam T type of container\n * @param x container\n * @return value of the W0 branch of the Lambert W function for each value in x\n * @throw std::domain_error if x is less than or equal to `-e^(-1)` or greater\n * than or equal to 0\n */\ntemplate <typename T, require_not_stan_scalar_t<T>* = nullptr>\ninline auto lambert_wm1(const T& x) {\n  return apply_scalar_unary<internal::lambert_wm1_fun, T>::apply(x);\n}\n\n}  // namespace math\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "f5f5f57003e14a8d83c066604dd0fc41eb8c58a7", "size": 2870, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/lambert_w.hpp", "max_stars_repo_name": "tiagocabaco/math", "max_stars_repo_head_hexsha": "1b300c592b680fbfde289f08dc75d1da9c61901d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/fun/lambert_w.hpp", "max_issues_repo_name": "tiagocabaco/math", "max_issues_repo_head_hexsha": "1b300c592b680fbfde289f08dc75d1da9c61901d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/fun/lambert_w.hpp", "max_forks_repo_name": "tiagocabaco/math", "max_forks_repo_head_hexsha": "1b300c592b680fbfde289f08dc75d1da9c61901d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8640776699, "max_line_length": 79, "alphanum_fraction": 0.7010452962, "num_tokens": 812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4294698359451053}}
{"text": "/*=========================================================================*/\n/*                                                                         */\n/* @file            Optimizer.cpp                                          */\n/* @author          Chirantan Ekbote (ekbote@seas.harvard.edu)             */\n/* @date            2012/11/14                                             */\n/* @version         0.3                                                    */\n/* @brief           Optimizer for generating bright and dark images        */\n/*                                                                         */\n/*=========================================================================*/\n\n#ifdef USE_OPENMP\n#include <omp.h>\n#endif\n#include <Eigen/SVD>\n\n#include \"../inc/Optimizer.h\"\n\n#define ROW(n)\t1*n,\t2*n,\t3*n,\t4*n,\t3*n,\t2*n,\t1*n\n\nnamespace pvrtex {\n// Optimization window information\nconst int Optimizer::window_width_ = 11;\nconst int Optimizer::window_height_ = 11;\nconst int Optimizer::matrix_rows_ = 121;\nconst int Optimizer::matrix_cols_ = 8;\nconst int Optimizer::offset_x_ = 4;\nconst int Optimizer::offset_y_ = 4;\n  \n// Weight matrices\nconst float Optimizer::kTopLeft[] =\n{\n  ROW(0.0625f), 0, 0, 0, 0,\t// 1/16\n  ROW(0.125f), 0, 0, 0, 0,\t// 2/16\n  ROW(0.1875f), 0, 0, 0, 0,\t// 3/16\n  ROW(0.25f), 0, 0, 0, 0,\t\t// 4/16\n  ROW(0.1875f), 0, 0, 0, 0,\t// 3/16\n  ROW(0.125f), 0, 0, 0, 0,\t// 2/16\n  ROW(0.0625f), 0, 0, 0, 0,\t// 1/16\n  ROW(0), 0, 0, 0, 0,\n  ROW(0), 0, 0, 0, 0,\n  ROW(0), 0, 0, 0, 0,\n  ROW(0), 0, 0, 0, 0\n};\nconst float Optimizer::kTopRight[] =\n{\n  0, 0, 0, 0, ROW(0.0625f),\t// 1/16\n  0, 0, 0, 0, ROW(0.125f),\t// 2/16\n  0, 0, 0, 0, ROW(0.1875f),\t// 3/16\n  0, 0, 0, 0, ROW(0.25f),\t\t// 4/16\n  0, 0, 0, 0, ROW(0.1875f),\t// 3/16\n  0, 0, 0, 0, ROW(0.125f),\t// 2/16\n  0, 0, 0, 0, ROW(0.0625f),\t// 1/16\n  ROW(0), 0, 0, 0, 0,\n  ROW(0), 0, 0, 0, 0,\n  ROW(0), 0, 0, 0, 0,\n  ROW(0), 0, 0, 0, 0\n};\nconst float Optimizer::kBottomLeft[] =\n{\n  ROW(0), 0, 0, 0, 0,\n  ROW(0), 0, 0, 0, 0,\n  ROW(0), 0, 0, 0, 0,\n  ROW(0), 0, 0, 0, 0,\n  ROW(0.0625f), 0, 0, 0, 0,\t// 1/16\n  ROW(0.125f), 0, 0, 0, 0,\t// 2/16\n  ROW(0.1875f), 0, 0, 0, 0,\t// 3/16\n  ROW(0.25f), 0, 0, 0, 0,\t\t// 4/16\n  ROW(0.1875f), 0, 0, 0, 0,\t// 3/16\n  ROW(0.125f), 0, 0, 0, 0,\t// 2/16\n  ROW(0.0625f), 0, 0, 0, 0,\t// 1/16\n};\nconst float Optimizer::kBottomRight[] =\n{\n  ROW(0), 0, 0, 0, 0,\n  ROW(0), 0, 0, 0, 0,\n  ROW(0), 0, 0, 0, 0,\n  ROW(0), 0, 0, 0, 0,\n  0, 0, 0, 0, ROW(0.0625f),\t// 1/16\n  0, 0, 0, 0, ROW(0.125f),\t// 2/16\n  0, 0, 0, 0, ROW(0.1875f),\t// 3/16\n  0, 0, 0, 0, ROW(0.25f),\t\t// 4/16\n  0, 0, 0, 0, ROW(0.1875f),\t// 3/16\n  0, 0, 0, 0, ROW(0.125f),\t// 2/16\n  0, 0, 0, 0, ROW(0.0625f)\t// 1/16\n};\n  \nOptimizer::Optimizer(const Eigen::MatrixXi &o, Eigen::MatrixXi &d,\n                     Eigen::MatrixXi &b, SOLVER s, util::DATA_FORMAT f) :\n  \n  dark_(d),\n  bright_(b),\n  orig_(o),\n  solv_(s),\n  format_(f)\n{\n  red_ = Eigen::MatrixXi(orig_.rows(), orig_.cols());\n  green_ = Eigen::MatrixXi(orig_.rows(), orig_.cols());\n  blue_ = Eigen::MatrixXi(orig_.rows(), orig_.cols());\n}\n  \nOptimizer::~Optimizer() {\n}\n  \nvoid Optimizer::ComputeUpdateVector() {\n  Eigen::MatrixXi comp = util::ModulateImage(util::Upscale4x4(dark_, format_),\n                                             util::Upscale4x4(bright_, format_),\n                                             mod_);\n#ifdef USE_OPENMP\n#pragma omp parallel for\n#endif\n  for (int y = 0; y < orig_.rows(); ++y) {\n    for (int x = 0; x < orig_.cols(); ++x) {\n      Eigen::Vector3i diff;\n      diff = (util::MakeColorVector(orig_(y,x), util::PVR888) -\n              util::MakeColorVector(comp(y,x), util::PVR888));\n      //        red_(y,x) = util::MakeRed(orig_(y,x));\n      //        green_(y,x) = util::MakeGreen(orig_(y,x));\n      //        blue_(y,x) = util::MakeBlue(orig_(y,x));\n      red_(y,x) = diff(0);\n      green_(y,x) = diff(1);\n      blue_(y,x) = diff(2);\n    }\n  }\n}\n  \nvoid Optimizer::OptimizeWindow(int j, int i) {\n  Eigen::MatrixXf a(matrix_rows_, matrix_cols_);\n  Eigen::MatrixXf w(matrix_rows_, matrix_cols_ / 2);\n  Eigen::VectorXf red(matrix_rows_);\n  Eigen::VectorXf green(matrix_rows_);\n  Eigen::VectorXf blue(matrix_rows_);\n  int idx, pixel_x, pixel_y;\n  float m, distance;\n  float r, g, b;\n    \n  /* Construct the optimization window */\n  for (int y = 0; y < window_height_; ++y) {\n    for (int x = 0; x < window_width_; ++x) {\n      /* Get the position of the pixel we want to fetch */\n      idx = y*window_width_ + x;\n      pixel_x = util::Clamp(offset_x_*i-1 + x, 0, mod_.cols()-1);\n      pixel_y = util::Clamp(offset_y_*j-1 + y, 0, mod_.rows()-1);\n        \n      /* Fetch the modulation value and the original color*/\n      m = mod_(pixel_y, pixel_x);\n      r = static_cast<float>(red_(pixel_y, pixel_x));\n      g = static_cast<float>(green_(pixel_y, pixel_x));\n      b = static_cast<float>(blue_(pixel_y, pixel_x));\n        \n      /* Fetch the distance weights and construct the matrix */\n      distance = kTopLeft[idx];\n      a(idx, 0) = distance * (1.0f - m);\n      a(idx, 1) = distance * m;\n      w(idx, 0) = distance;\n      red(idx) = distance * r;\n      green(idx) = distance * g;\n      blue(idx) = distance * b;\n        \n      /* Top right pxel */\n      distance = kTopRight[idx];\n      a(idx, 2) = distance * (1.0f - m);\n      a(idx, 3) = distance * m;\n      w(idx, 1) = distance;\n      red(idx) += distance * r;\n      green(idx) += distance * g;\n      blue(idx) += distance * b;\n        \n      /* Bottom left pixel */\n      distance = kBottomLeft[idx];\n      a(idx, 4) = distance * (1.0f - m);\n      a(idx, 5) = distance * m;\n      w(idx, 2) = distance;\n      red(idx) += distance * r;\n      green(idx) += distance * g;\n      blue(idx) += distance * b;\n        \n      /* Bottom right pixel */\n      distance = kBottomRight[idx];\n      a(idx, 6) = distance * (1.0f - m);\n      a(idx, 7) = distance * m;\n      w(idx, 3) = distance;\n      red(idx) += distance * r;\n      green(idx) += distance * g;\n      blue(idx) += distance * b;\n        \n    }\n  }\n    \n  /* Solve for the best colors */\n  Eigen::JacobiSVD<Eigen::MatrixXf> svd(a, Eigen::ComputeThinU |\n                                        Eigen::ComputeThinV);\n  Eigen::VectorXi optimal_red = svd.solve(red).cast<int>();\n  Eigen::VectorXi optimal_green;\n  Eigen::VectorXi optimal_blue;\n  if (format_ == util::PVR444) {\n    Eigen::JacobiSVD<Eigen::MatrixXf> svd_w(w, Eigen::ComputeThinU |\n                                            Eigen::ComputeThinV);\n    Eigen::Vector3i update;\n    optimal_green = svd_w.solve(green).cast<int>();\n    optimal_blue = svd_w.solve(blue).cast<int>();\n    \n    /* Update the dark and bright images */\n    for (int x = 0; x < 2; ++x) {\n      for (int y = 0; y < 2; ++y) {\n        idx = 4*y + 2*x;\n        update = Eigen::Vector3i(util::Clamp(optimal_red(idx), -32, 32),\n                                 util::Clamp(optimal_green(idx/2), -32, 32),\n                                 util::Clamp(optimal_blue(idx/2), -32, 32));\n        dark_(j+y, i+x) = util::MakeRGB(\n                              util::MakeColorVector(dark_(j+y, i+x), format_) +\n                              update, format_);\n        update(0) = util::Clamp(optimal_red(idx+1), -32, 32);\n        bright_(j+y, i+x) = util::MakeRGB(\n                                util::MakeColorVector(bright_(j+y, i+x), format_) +\n                                    update, format_);\n        \n      }\n    }\n  } else {\n    optimal_green = svd.solve(green).cast<int>();\n    optimal_blue = svd.solve(blue).cast<int>();\n    \n    /* Update the dark and bright images */\n    for (int x = 0; x < 2; ++x) {\n      for (int y = 0; y < 2; ++y) {\n        idx = 4*y + 2*x;\n        dark_(j+y, i+x) = util::MakeRGB(\n                              util::MakeColorVector(dark_(j+y, i+x), format_) +\n                              Eigen::Vector3i(\n                                  util::Clamp(optimal_red(idx), -32, 32),\n                                  util::Clamp(optimal_green(idx), -32, 32),\n                                  util::Clamp(optimal_blue(idx), -32, 32)),\n                                        format_);\n        bright_(j+y, i+x) = util::MakeRGB(\n                                util::MakeColorVector(bright_(j+y, i+x), format_) +\n                                Eigen::Vector3i(\n                                    util::Clamp(optimal_red(idx+1), -32, 32),\n                                    util::Clamp(optimal_green(idx+1), -32, 32),\n                                    util::Clamp(optimal_blue(idx+1), -32, 32)),\n                                          format_);\n        //      dark_(j+y, i+x) = util::Make565RGB(Eigen::Vector3i(optimal_red(idx),\n        //                                                         optimal_green(idx),\n        //                                                         optimal_blue(idx)));\n        //      bright_(j+y, i+x) = util::Make565RGB(Eigen::Vector3i(optimal_red(idx+1),\n        //                                                           optimal_green(idx+1),\n        //                                                           optimal_blue(idx+1)));\n        \n      }\n    }\n\n  }\n    \n}\n  \nvoid Optimizer::Optimize(const Eigen::MatrixXf &m) {\n  mod_ = m;\n  ComputeUpdateVector();\n#ifdef USE_OPENMP\n#pragma omp parallel for\n#endif\n  for (int j = 0; j < dark_.rows(); j+=2) {\n    for (int i = 0; i < dark_.cols(); i+=2) {\n      OptimizeWindow(j, i);\n    }\n  }\n}\n\nvoid Optimizer::WriteToFile(const char *filename) {\n    \n}\n\n} /* namespace pvrtex */\n\n", "meta": {"hexsha": "da8ba2a15b9fef4542fc53c91dbb049ae1363de3", "size": 9490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "compressor/src/Optimizer.cpp", "max_stars_repo_name": "jynnantonix/pvrtex", "max_stars_repo_head_hexsha": "f578ddcf8fd9982fa806473b6c4302b69d4f70ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-09-22T16:04:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T12:14:46.000Z", "max_issues_repo_path": "compressor/src/Optimizer.cpp", "max_issues_repo_name": "jynnantonix/pvrtex", "max_issues_repo_head_hexsha": "f578ddcf8fd9982fa806473b6c4302b69d4f70ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compressor/src/Optimizer.cpp", "max_forks_repo_name": "jynnantonix/pvrtex", "max_forks_repo_head_hexsha": "f578ddcf8fd9982fa806473b6c4302b69d4f70ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-08-13T06:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-03T01:16:23.000Z", "avg_line_length": 34.6350364964, "max_line_length": 91, "alphanum_fraction": 0.4703898841, "num_tokens": 3169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4293982571664369}}
{"text": "//\n//  KDTree.cpp\n//\n//\n//  Created by Sivaram Ambikasaran on 12/3/13.\n//\n//\n\n#include \"KDTree.hpp\"\n#include <Eigen/Dense>\n\nKDTree::KDTree(const unsigned n_Locations, const unsigned n_Dimension, double* locations, const unsigned n_Properties, double* properties, const unsigned MinParticlesInLeaf, const unsigned nLevels) {\n        this->n_Locations       =       n_Locations;\n        this->n_Dimension       =       n_Dimension;\n        this->n_Properties      =       n_Properties;\n        this->MinParticlesInLeaf=       MinParticlesInLeaf;\n        this->nLevels           =       nLevels;\n\n        sorted_Contents         =       Eigen::MatrixXd(n_Locations, n_Dimension+n_Properties);\n\n        unsigned count_Location =       0;\n        unsigned count_Property =       0;\n\n        for (unsigned j=0; j<n_Locations; ++j) {\n                for (unsigned k=0; k<n_Dimension; ++k) {\n                        sorted_Contents(j,k)    =       locations[count_Location];\n                        ++count_Location;\n                }\n                for (unsigned k=n_Dimension; k<n_Dimension+n_Properties; ++k) {\n                        sorted_Contents(j,k)    =       properties[count_Property];\n                        ++count_Property;\n                }\n        }\n}\n\nvoid KDTree::merge_Sorted_Lists(unsigned n_Left_Start, unsigned n_Left_Size, unsigned n_Right_Start, unsigned n_Right_Size, unsigned n_Index) {\n\n        Eigen::MatrixXd temp_List(n_Left_Size+n_Right_Size, n_Dimension+n_Properties);\n\n        unsigned j_Left =       n_Left_Start;\n        unsigned j_Right=       n_Right_Start;\n\n        unsigned j      =       0;\n\n        while (j_Left < n_Left_Start + n_Left_Size && j_Right < n_Right_Start + n_Right_Size) {\n                if (sorted_Contents(j_Left, n_Index) < sorted_Contents(j_Right, n_Index)) {\n                        temp_List.row(j)=       sorted_Contents.row(j_Left);\n                        ++j_Left;\n                }\n                else {\n                        temp_List.row(j)=       sorted_Contents.row(j_Right);\n                        ++j_Right;\n                }\n                ++j;\n        }\n\n        while (j_Left < n_Left_Start + n_Left_Size) {\n                temp_List.row(j)        =       sorted_Contents.row(j_Left);\n                ++j_Left;\n                ++j;\n        }\n\n        while (j_Right < n_Right_Start + n_Right_Size) {\n                temp_List.row(j)        =       sorted_Contents.row(j_Right);\n                ++j_Right;\n                ++j;\n        }\n\n        sorted_Contents.block(n_Left_Start, 0, n_Left_Size + n_Right_Size, n_Dimension+n_Properties)        =       temp_List;\n}\n\nvoid KDTree::merge_Sort(unsigned n_Start, unsigned n_Size, unsigned n_Index) {\n        if (n_Size<=1) {\n                //      Do nothing\n                return;\n        }\n        else {\n                unsigned n_Left_Start   =       n_Start;\n                unsigned n_Left_Size    =       n_Size/2;\n                unsigned n_Right_Start  =       n_Start+n_Left_Size;\n                unsigned n_Right_Size   =       n_Size-n_Left_Size;\n\n                merge_Sort(n_Left_Start, n_Left_Size, n_Index);\n                merge_Sort(n_Right_Start, n_Right_Size, n_Index);\n\n                merge_Sorted_Lists(n_Left_Start, n_Left_Size, n_Right_Start, n_Right_Size, n_Index);\n        }\n}\n\nint KDTree::sort_KDTree(unsigned n_Start, unsigned n_Size, unsigned n_Index, unsigned local_level, std::vector<int>& NumberOfParticlesInLeaves) {\n    // static int nLevels = 0;\n    n_Index                 =       n_Index%n_Dimension;\n    merge_Sort(n_Start, n_Size, n_Index);\n\n    unsigned n_Left_Start   =       n_Start;\n    unsigned n_Left_Size    =       n_Size/2;\n    unsigned n_Right_Start  =       n_Start+n_Left_Size;\n    unsigned n_Right_Size   =       n_Size-n_Left_Size;\n\n    ++n_Index;\n    n_Index                 =       n_Index%n_Dimension;\n\n    merge_Sort(n_Left_Start, n_Left_Size, n_Index);\n    unsigned n_Left_Bottom_Start   =       n_Left_Start;\n    unsigned n_Left_Bottom_Size    =       n_Left_Size/2;\n    unsigned n_Left_Top_Start  =       n_Left_Start+n_Left_Bottom_Size;\n    unsigned n_Left_Top_Size   =       n_Left_Size-n_Left_Bottom_Size;\n\n    merge_Sort(n_Right_Start, n_Right_Size, n_Index);\n    unsigned n_Right_Bottom_Start   =       n_Right_Start;\n    unsigned n_Right_Bottom_Size    =       n_Right_Size/2;\n    unsigned n_Right_Top_Start  =       n_Right_Start+n_Right_Bottom_Size;\n    unsigned n_Right_Top_Size   =       n_Right_Size-n_Right_Bottom_Size;\n\n    ++n_Index;\n    n_Index                 =       n_Index%n_Dimension;\n\n    if (local_level < nLevels) {\n    // if (n_Left_Bottom_Size >= MinParticlesInLeaf &&  n_Left_Top_Size >= MinParticlesInLeaf && n_Right_Bottom_Size >= MinParticlesInLeaf && n_Right_Top_Size >= MinParticlesInLeaf && local_level < nLevels) {\n      local_level++;\n      if(local_level==nLevels) {\n        // std::cout << n_Left_Bottom_Size << std::endl;\n        // std::cout << n_Left_Top_Size << std::endl;\n        // std::cout << n_Right_Bottom_Size << std::endl;\n        // std::cout << n_Right_Top_Size << std::endl;\n        // std::cout << \"--------------------------------\" << std::endl;\n        NumberOfParticlesInLeaves.push_back(n_Left_Bottom_Size);\n        NumberOfParticlesInLeaves.push_back(n_Left_Top_Size);\n        NumberOfParticlesInLeaves.push_back(n_Right_Bottom_Size);\n        NumberOfParticlesInLeaves.push_back(n_Right_Top_Size);\n      }\n      // std::cout << \"local_level: \" << local_level << std::endl;\n      sort_KDTree(n_Left_Bottom_Start, n_Left_Bottom_Size, n_Index, local_level, NumberOfParticlesInLeaves);\n      sort_KDTree(n_Left_Top_Start, n_Left_Top_Size, n_Index, local_level, NumberOfParticlesInLeaves);\n      sort_KDTree(n_Right_Bottom_Start, n_Right_Bottom_Size, n_Index, local_level, NumberOfParticlesInLeaves);\n      sort_KDTree(n_Right_Top_Start, n_Right_Top_Size, n_Index, local_level, NumberOfParticlesInLeaves);\n      // nLevels += 1;\n    }\n    return 0;\n    // return nLevels;\n}\n\nint KDTree::sort_KDTree(std::vector<int>& NumberOfParticlesInLeaves) {\n        if (n_Locations<=1) {\n                //      Do nothing\n                return 0;\n        }\n        else {\n                //      Number of point on the left cluster\n                return sort_KDTree(0, n_Locations, 0, 0, NumberOfParticlesInLeaves);\n        }\n}\n\nvoid KDTree::get_Location_Properties(double* locations, double* properties) {\n        unsigned count_Location         =       0;\n        unsigned count_Property         =       0;\n        for (unsigned j=0; j<n_Locations; ++j) {\n                for (unsigned k=0; k<n_Dimension; ++k) {\n                        locations[count_Location]       =       sorted_Contents(j,k);\n                        ++count_Location;\n                }\n                for (unsigned k=n_Dimension; k<n_Dimension+n_Properties; ++k) {\n                        properties[count_Property]      =       sorted_Contents(j,k);\n                        ++count_Property;\n                }\n        }\n}\n\nvoid KDTree::get_Location_Properties(const unsigned n_Index, double* location, double* properties) {\n        for (unsigned k=0; k<n_Dimension; ++k) {\n                location[k]     =       sorted_Contents(n_Index,k);\n        }\n        for (unsigned k=0; k<n_Properties; ++k) {\n                properties[k]   =       sorted_Contents(n_Index,k+n_Dimension);\n        }\n}\n\n/////////////////GLOBAL FUNCTIONS TO BE CALLED FROM MAIN ///////////////////////////\nvoid display(std::string display_String, unsigned n_Locations, unsigned n_Dimension, double* locations, unsigned n_Properties, double* properties) {\n        std::cout << display_String << std::endl;\n\n        unsigned count_Location  =       0;\n        unsigned count_Property  =       0;\n\n        for (unsigned j=0; j<n_Locations; ++j) {\n                for (unsigned k=0; k<n_Dimension; ++k) {\n                        std::cout << locations[count_Location] << \"\\t\";\n                        ++count_Location;\n                }\n                for (unsigned k=0; k<n_Properties; ++k) {\n                        std::cout << properties[count_Property] << \"\\t\";\n                        ++count_Property;\n                }\n                std::cout << std::endl;\n        }\n        std::cout << std::endl;\n}\n\nvoid sort_KDTree(unsigned N, unsigned n_Dimension, double* locations, unsigned n_Properties, double* properties, unsigned MinParticlesInLeaf, unsigned nLevels, double* sorted_Locations, double* sorted_Properties, std::vector<std::vector<int> >& boxNumbers, std::vector<int>& NumberOfParticlesInLeaves) {\n    KDTree* B                       =       new KDTree(N, n_Dimension, locations, n_Properties, properties, MinParticlesInLeaf, nLevels);\n    delete locations;\n    delete properties;\n    NumberOfParticlesInLeaves.reserve(pow(4,nLevels));\n    //      Sorts the locations based on KDTree.\n    B->sort_KDTree(NumberOfParticlesInLeaves);\n    // converting N ordering to the mirrored C ordering.\n    // The sorted locations that the KD Tree outputs, correspond to boxes in N ordering.\n    // So here we are generating N ordering sequence of box numbers in terms of the mirrored C ordering.\n    // only leaf level ordering is what we want: boxNumbers[nLevels]\n    std::vector<int> boxNumbersInLevel0;\n    boxNumbersInLevel0.push_back(0);//level 0\n    boxNumbers.push_back(boxNumbersInLevel0);\n    for (size_t j = 1; j <= nLevels; j++) {\n      std::vector<int> boxNumbersInALevel;\n      for (size_t k = 0; k < boxNumbers[j-1].size(); k++) {\n        boxNumbersInALevel.push_back(boxNumbers[j-1][k]*4 + 0);\n        boxNumbersInALevel.push_back(boxNumbers[j-1][k]*4 + 3);\n        boxNumbersInALevel.push_back(boxNumbers[j-1][k]*4 + 1);\n        boxNumbersInALevel.push_back(boxNumbers[j-1][k]*4 + 2);\n      }\n      boxNumbers.push_back(boxNumbersInALevel);\n    }\n    // Obtains the sorted location.\n    // sorted_Locations contains the locations sorted as per the KD Tree.(In N ordering of boxes)\n    B->get_Location_Properties(sorted_Locations, sorted_Properties);\n\n    // Display the sorted contents.\n   // display(\"Sorted contents: \", N, n_Dimension, sorted_Locations, n_Properties, sorted_Properties);\n   // exit(0);\n   // Take away from kD tree class: sorted_Locations, sorted_Properties, boxNumbers[nLevels], NumberOfParticlesInLeaves. Give these as inputs to FMM2DTree constructor.\n    /////////////////////////////////////////////////////////////////////////\n    /////////////////////////////////////////////////////////////////////////\n\n    /* example:\n    boxNumbers NumberOfParticlesInLeaves\n    0           4\n    3           4\n    1           4\n    2           4\n    */\n    delete B;\n}\n", "meta": {"hexsha": "d2605bc09b4f1e13366a94f4b6796a2593016436", "size": 10678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "KDTree.cpp", "max_stars_repo_name": "sivaramambikasaran/AFMM2D", "max_stars_repo_head_hexsha": "33eeee4b11fe9ce0a4247fb37e6ece60960f812a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KDTree.cpp", "max_issues_repo_name": "sivaramambikasaran/AFMM2D", "max_issues_repo_head_hexsha": "33eeee4b11fe9ce0a4247fb37e6ece60960f812a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KDTree.cpp", "max_forks_repo_name": "sivaramambikasaran/AFMM2D", "max_forks_repo_head_hexsha": "33eeee4b11fe9ce0a4247fb37e6ece60960f812a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9423868313, "max_line_length": 303, "alphanum_fraction": 0.589810826, "num_tokens": 2519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185318, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4293891614879835}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n    @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_MINMOD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MINMOD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n  /*!\n    @ingroup group-arithmetic\n\n    This function object computes the smallest of its parameter if they share the same sign,\n    zero instead.\n\n    @par Header <boost/simd/function/minmod.hpp>\n\n    @par Notes\n\n    Using `minmod(x, y)` is similar to `x*y > 0 ? min(x, y) : 0`\n\n    @see min, minnum, minnummag, minmag\n\n    @par Example:\n\n      @snippet minmod.cpp minmod\n\n    @par Possible output:\n\n      @snippet minmod.txt minmod\n\n  **/\n  Value minmod(Value const& x, Value const& y);\n} }\n#endif\n\n#include <boost/simd/function/scalar/minmod.hpp>\n#include <boost/simd/function/simd/minmod.hpp>\n\n#endif\n", "meta": {"hexsha": "5c8a7a1dec988ae215a30d93f9745ea35e0529a2", "size": 1158, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/minmod.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/minmod.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/minmod.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 24.125, "max_line_length": 100, "alphanum_fraction": 0.5829015544, "num_tokens": 258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834732, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.42938915420466256}}
{"text": "#include \"pre.h\"\n\n#include \"label.h\"\n\n#ifdef CMAKE_USE_DLIB\n#include <dlib/statistics.h>\n#include <dlib/svm.h>\n#endif\n\n#include <cassert>\n#include <cmath>\n\n\nnamespace pre\n{\n\n\ndat::Dataset logarithm( const dat::Dataset & d )\n{\n    double min {};\n    dat::apply( [ & ] ( label::Num, const dat::Spectrum & s )\n        {\n            for( const auto & point : s._y )\n            {\n                if( point < min )\n                {\n                    min = point;\n                }\n            }\n        }     , d );\n\n    dat::Dataset ret{ {}, d.second };\n    dat::apply( [ & ] ( label::Num l, const dat::Spectrum & s )\n        {\n            dat::Spectrum transformed{};\n            unsigned i {};\n            for( const auto & intensity : s._y )\n            {\n                const auto positive = intensity - min + 1;\n                const auto point = std::log( positive );\n                transformed._y[ i++ ] = point;\n            }\n            ret.first[ l ].push_back( transformed );\n        }      , ret );\n\n    return ret;\n}\n\n\nLog::Log( const dat::Dataset & )\n{\n}\n\n\ndat::Dataset Log::operator()( const dat::Dataset & d ) const\n{\n    return logarithm( d );\n}\n\n\nvoid normalize( dat::Dataset & d )\n{\n    dat::Spectrum mean {};\n    dat::apply( [ & ] ( label::Num, const dat::Spectrum & s )\n    {\n        auto src = s._y.cbegin();\n        const auto end = s._y.cend();\n        auto dest = mean._y.begin();\n        while( src < end )\n        {\n            * dest++ += * src++;\n        }\n    }      , d );\n    const auto c = dat::count( d );\n    for( auto & point : mean._y )\n    {\n        point /= c;\n    }\n\n    dat::Spectrum variance;\n    dat::apply( [ & ] ( label::Num, const dat::Spectrum & s )\n    {\n        auto sp = s._y.cbegin();\n        const auto end = s._y.cend();\n        auto dest = variance._y.begin();\n        while( sp < end )\n        {\n            const auto a = mean._y[ sp - s._y.cbegin()] ;\n            const auto diff = * sp - a;\n            * dest += diff * diff;\n            assert( diff * diff >= 0 );\n            ++ sp;\n            ++ dest;\n        }\n    }      , d );\n    for( auto & point : variance._y )\n    {\n        point = sqrt( point / ( c - 1 ) );\n        assert( point >= 0 );\n    }\n\n    dat::mutate( [ & ] ( label::Num, dat::Spectrum & s )\n    {\n        auto src = s._y.begin();\n        const auto end = s._y.cend();\n        auto m_it = mean._y.cbegin();\n        auto v_it = variance._y.cbegin();\n        while( src < end )\n        {\n            if( * v_it < 1e-12  )\n            {\n                * src = * m_it;\n            }\n            else\n            {\n                * src = ( * src - * m_it ) / * v_it;\n            }\n\n            ++src;\n            ++m_it;\n            ++v_it;\n        }\n    }      , d );\n}\n\n\n\nNorm::Norm( const dat::Dataset & )\n{\n}\n\n\ndat::Dataset Norm::operator()( const dat::Dataset & d ) const\n{\n    dat::Dataset ret{ d };\n    normalize( ret );\n    return ret;\n}\n\n\n\nstd::vector< size_t > rank_features( const dat::Dataset & )\n{\n    return {};\n}\n\n\n#ifdef CMAKE_USE_DLIB\ndat::Dataset lda( const dat::Dataset & d )\n{\n    dlib::matrix< double > samples;\n    samples.set_size( static_cast< long >( dat::count( d ) )\n                    , dat::Spectrum::_num_points );\n    std::vector< unsigned long > labels;\n    auto i = 0u;\n    dat::apply( [ & ] ( const label::Num l, const dat::Spectrum & s )\n        {\n            labels.push_back( static_cast< unsigned long >( l ) );\n            std::copy( s._y.cbegin()\n                     , s._y.cend()\n                     , samples.begin() + dat::Spectrum::_num_points * i++ );\n        }     , d );\n    const auto samples2 = samples;\n\n    dlib::matrix< double, 0, 1 > means;\n    dlib::compute_lda_transform( samples, means, labels );\n\n    dlib::matrix< double > ret = samples2 * samples - means; //crash\n    std::cout << samples.nc() << \", \" << samples.nr() << std::endl;\n    std::cout << samples2.nc() << \", \" << samples2.nr() << std::endl;\n    std::cout << ret.nc() << \", \" << ret.nr() << std::endl;\n\n    return {};\n}\n#endif // CMAKE_USE_DLIB\n\n\nshark::LinearModel<>\ntrain_encoder( std::vector< shark::RealVector > & inputs\n             , unsigned N\n             )\n{\n    const auto dataset{ shark::createUnlabeledDataFromRange( inputs ) };\n    shark::PCA pca{ dataset };\n    shark::LinearModel<> enc;\n    pca.encoder( enc, N );\n    return enc;\n}\n\n\nshark::LinearModel<> train_encoder( const dat::Dataset & train\n                                  , unsigned N\n                                  )\n{\n    std::vector< shark::RealVector > inputs;\n    dat::apply( [ & ] ( auto, const dat::Spectrum & s )\n    {\n        inputs.push_back( dat::to_shark_vector( s ) );\n    }\n    , train\n    );\n\n    return train_encoder( inputs, N );\n}\n\nshark::LinearModel<>\ntrain_encoder( const shark::ClassificationDataset & train\n             , unsigned N\n             )\n{\n    std::vector< shark::RealVector > vec;\n    for( auto e{ train.elements().begin()}; e < train.elements().end(); ++e )\n    {\n        vec.push_back( e->input );\n    }\n\n    return train_encoder( vec, N );\n}\n\n\nPCA::PCA( const dat::Dataset & train, unsigned dim )\n    : _enc{ train_encoder( train, dim ) }\n{\n}\n\n\nPCA::PCA( const shark::ClassificationDataset & train, unsigned dim )\n    : _enc{ train_encoder( train, dim ) }\n{\n}\n\n\ndat::Dataset PCA::operator()( const dat::Dataset & d ) const\n{\n    if( d.first.empty() )\n    {\n        return {};\n    }\n\n    std::vector< shark::RealVector > inputs;\n    std::vector< label::Num > labels;\n    dat::apply( [&] ( label::Num l, const dat::Spectrum & s )\n    {\n        shark::RealVector enc;\n        const auto vec{ dat::to_shark_vector( s ) };\n        _enc.eval( vec, enc );\n        inputs.push_back( std::move( enc ) );\n        labels.push_back( l );\n    }\n              , d );\n\n    const auto sharked{ shark::createLabeledDataFromRange( inputs, labels ) };\n    return dat::from_shark_dataset( sharked, d.second );\n}\n\n\nconst std::vector< std::string > ALL_PRE{ \"log\"\n                                        , \"norm\"\n\n#if defined(CMAKE_USE_OPENCV) || defined(CMAKE_USE_SHARK)\n                                         , \"pca\"\n#endif\n#if defined (CMAKE_USE_OPENCV) || defined (CMAKE_USE_DLIB)\n                                        , \"lda\"\n#endif\n                                        };\n\n\n}  // namespace pre\n", "meta": {"hexsha": "3b797c8b23668c5c536e028c52a0aa57e8eded9f", "size": 6299, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pre.cpp", "max_stars_repo_name": "MiroslavVitkov/rocks", "max_stars_repo_head_hexsha": "6ef277d1bf306de868db4fbcddc8af4cb17ed1c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pre.cpp", "max_issues_repo_name": "MiroslavVitkov/rocks", "max_issues_repo_head_hexsha": "6ef277d1bf306de868db4fbcddc8af4cb17ed1c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-07-06T08:52:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-06T08:59:19.000Z", "max_forks_repo_path": "src/pre.cpp", "max_forks_repo_name": "MiroslavVitkov/rocks", "max_forks_repo_head_hexsha": "6ef277d1bf306de868db4fbcddc8af4cb17ed1c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3296296296, "max_line_length": 78, "alphanum_fraction": 0.4838863312, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.865224072151174, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.42923232330389904}}
{"text": "/*\n * DeltaMeasure.cpp\n *\n *  Created on: 31.08.2017\n *      Author: thies\n */\n\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/grid/grid_tools.h>\n\n#include <base/ConstantMesh.h>\n#include <base/Norm.h>\n#include <measurements/DeltaMeasure.h>\n#include <measurements/SensorValues.h>\n\n#include <stddef.h>\n#include <cmath>\n#include <iostream>\n#include <string>\n#include <vector>\n\nnamespace wavepi {\nnamespace measurements {\n\nusing namespace dealii;\nusing namespace wavepi::base;\n\ntemplate <int dim>\nDeltaMeasure<dim>::DeltaMeasure(std::shared_ptr<SpaceTimeMesh<dim>> mesh,\n                                std::shared_ptr<SensorDistribution<dim>> points,\n                                std::shared_ptr<Norm<DiscretizedFunction<dim>>> norm)\n    : mesh(mesh), sensor_distribution(points), norm(norm) {\n  AssertThrow(mesh && norm, ExcNotInitialized());\n}\n\ntemplate <int dim>\nSensorValues<dim> DeltaMeasure<dim>::evaluate(const DiscretizedFunction<dim>& field) {\n  AssertThrow(sensor_distribution && sensor_distribution->size(), ExcNotInitialized());\n  AssertThrow(mesh == field.get_mesh(), ExcMessage(\"DeltaMeasure called with different meshes\"));\n  AssertThrow(*norm == *field.get_norm(), ExcMessage(\"DeltaMeasure called with different norms\"));\n\n  SensorValues<dim> res(sensor_distribution);\n  auto mapping = StaticMappingQ1<dim>::mapping;\n\n  if (std::dynamic_pointer_cast<ConstantMesh<dim>, SpaceTimeMesh<dim>>(mesh) &&\n      sensor_distribution->times_per_point_available()) {\n    // specialized implementation that is ordered by points, not time\n    // (most expensive operation is find_active_cell_around_point(...))\n    auto dof_handler = mesh->get_dof_handler(0);\n\n    for (size_t mpi = 0; mpi < sensor_distribution->get_points().size(); mpi++) {\n      auto pos = sensor_distribution->get_points()[mpi];\n\n      std::pair<typename DoFHandler<dim>::active_cell_iterator, Point<dim>> cell_point =\n          GridTools::find_active_cell_around_point(mapping, *dof_handler, pos);\n\n      Quadrature<dim> q(GeometryInfo<dim>::project_to_unit_cell(cell_point.second));\n      FEValues<dim> fe_values(mapping, dof_handler->get_fe(), q, UpdateFlags(update_values));\n      fe_values.reinit(cell_point.first);\n\n      const unsigned int dofs_per_cell = dof_handler->get_fe().dofs_per_cell;\n\n      std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n      cell_point.first->get_dof_indices(local_dof_indices);\n\n      for (size_t mti = 0; mti < sensor_distribution->get_times_per_point(mpi).size(); mti++) {\n        double mtime = sensor_distribution->get_times_per_point(mpi)[mti];\n        size_t ti    = mesh->nearest_time(mtime);\n\n        // (φ_i, δ_p) = fe_values.shape_value(i, 0)\n        // this loop calculates the dot product between field[ti] and δ_p directly\n        for (unsigned int i = 0; i < dofs_per_cell; i++)\n          res[sensor_distribution->index_times_per_point(mpi, mti)] +=\n              field[ti][local_dof_indices[i]] * fe_values.shape_value(i, 0);\n      }\n    }\n  } else {\n    size_t offset = 0;\n\n    for (size_t mti = 0; mti < sensor_distribution->get_times().size(); mti++) {\n      double mtime = sensor_distribution->get_times()[mti];\n\n      size_t ti        = mesh->nearest_time(mtime);\n      auto dof_handler = mesh->get_dof_handler(ti);\n\n      for (size_t msi = 0; msi < sensor_distribution->get_points_per_time(mti).size(); msi++) {\n        auto pos = sensor_distribution->get_points_per_time(mti)[msi];\n\n        std::pair<typename DoFHandler<dim>::active_cell_iterator, Point<dim>> cell_point =\n            GridTools::find_active_cell_around_point(mapping, *dof_handler, pos);\n\n        Quadrature<dim> q(GeometryInfo<dim>::project_to_unit_cell(cell_point.second));\n        FEValues<dim> fe_values(mapping, dof_handler->get_fe(), q, UpdateFlags(update_values));\n        fe_values.reinit(cell_point.first);\n\n        const unsigned int dofs_per_cell = dof_handler->get_fe().dofs_per_cell;\n\n        std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n        cell_point.first->get_dof_indices(local_dof_indices);\n\n        // (φ_i, δ_p) = fe_values.shape_value(i, 0)\n        // this loop calculates the dot product between field[ti] and δ_p directly\n        for (unsigned int i = 0; i < dofs_per_cell; i++)\n          res[msi + offset] += field[ti][local_dof_indices[i]] * fe_values.shape_value(i, 0);\n      }\n\n      offset += sensor_distribution->get_points_per_time(mti).size();\n    }\n  }\n\n  return res;\n}\n\ntemplate <int dim>\nSensorValues<dim> DeltaMeasure<dim>::zero() {\n  return SensorValues<dim>(sensor_distribution);\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> DeltaMeasure<dim>::adjoint(const SensorValues<dim>& measurements) {\n  AssertThrow(mesh && sensor_distribution && sensor_distribution->size(), ExcNotInitialized());\n\n  DiscretizedFunction<dim> res(mesh);\n  auto mapping  = StaticMappingQ1<dim>::mapping;\n  size_t offset = 0;\n\n  if (std::dynamic_pointer_cast<ConstantMesh<dim>, SpaceTimeMesh<dim>>(mesh) &&\n      sensor_distribution->times_per_point_available()) {\n    // specialized implementation that is ordered by points, not time\n    // (most expensive operation is find_active_cell_around_point(...))\n    auto dof_handler = mesh->get_dof_handler(0);\n\n    for (size_t mpi = 0; mpi < sensor_distribution->get_points().size(); mpi++) {\n      auto pos = sensor_distribution->get_points()[mpi];\n\n      std::pair<typename DoFHandler<dim>::active_cell_iterator, Point<dim>> cell_point =\n          GridTools::find_active_cell_around_point(mapping, *dof_handler, pos);\n\n      Quadrature<dim> q(GeometryInfo<dim>::project_to_unit_cell(cell_point.second));\n      FEValues<dim> fe_values(mapping, dof_handler->get_fe(), q, UpdateFlags(update_values));\n      fe_values.reinit(cell_point.first);\n\n      const unsigned int dofs_per_cell = dof_handler->get_fe().dofs_per_cell;\n\n      std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n      cell_point.first->get_dof_indices(local_dof_indices);\n\n      for (size_t mti = 0; mti < sensor_distribution->get_times_per_point(mpi).size(); mti++) {\n        double mtime = sensor_distribution->get_times_per_point(mpi)[mti];\n        size_t ti    = mesh->nearest_time(mtime);\n\n        // (φ_i, δ_p) = fe_values.shape_value(i, 0)\n        // this loop calculates the dot product between field[ti] and δ_p directly\n        for (unsigned int i = 0; i < dofs_per_cell; i++)\n          res[ti][local_dof_indices[i]] +=\n              measurements[sensor_distribution->index_times_per_point(mpi, mti)] * fe_values.shape_value(i, 0);\n      }\n    }\n  } else {\n    for (size_t mti = 0; mti < sensor_distribution->get_times().size(); mti++) {\n      double mtime = sensor_distribution->get_times()[mti];\n\n      size_t ti        = mesh->nearest_time(mtime);\n      auto dof_handler = mesh->get_dof_handler(ti);\n\n      for (size_t msi = 0; msi < sensor_distribution->get_points_per_time(mti).size(); msi++) {\n        auto pos = sensor_distribution->get_points_per_time(mti)[msi];\n\n        std::pair<typename DoFHandler<dim>::active_cell_iterator, Point<dim>> cell_point =\n            GridTools::find_active_cell_around_point(mapping, *dof_handler, pos);\n\n        Quadrature<dim> q(GeometryInfo<dim>::project_to_unit_cell(cell_point.second));\n        FEValues<dim> fe_values(mapping, dof_handler->get_fe(), q, UpdateFlags(update_values));\n        fe_values.reinit(cell_point.first);\n\n        const unsigned int dofs_per_cell = dof_handler->get_fe().dofs_per_cell;\n\n        std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n        cell_point.first->get_dof_indices(local_dof_indices);\n\n        // (φ_i, δ_p) = fe_values.shape_value(i, 0)\n        // this loop calculates dot products, not coefficients.\n        for (unsigned int i = 0; i < dofs_per_cell; i++)\n          res[ti][local_dof_indices[i]] += measurements[msi + offset] * fe_values.shape_value(i, 0);\n      }\n\n      offset += sensor_distribution->get_points_per_time(mti).size();\n    }\n  }\n\n  // indicate which norm we used for the adjoint\n  res.set_norm(norm);\n  res.dot_transform_inverse();\n\n  return res;\n}\n\ntemplate class DeltaMeasure<1>;\ntemplate class DeltaMeasure<2>;\ntemplate class DeltaMeasure<3>;\n\n}  // namespace measurements\n}  // namespace wavepi\n", "meta": {"hexsha": "1929b9dff0d35a4356199188e9d52740dcf01661", "size": 8277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/measurements/DeltaMeasure.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/measurements/DeltaMeasure.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/measurements/DeltaMeasure.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3756097561, "max_line_length": 111, "alphanum_fraction": 0.695541863, "num_tokens": 2035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4292126306780721}}
{"text": "// This file is part of LatNet Builder.\n//\n// Copyright (C) 2012-2021  The LatNet Builder author's, supervised by Pierre L'Ecuyer, Universite de Montreal.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"netbuilder/NetConstructionTraits.h\"\n\n#include \"latbuilder/GenSeq/GeneratingValues-PLR.h\"\n#include \"latbuilder/SeqCombiner.h\"\n#include \"latbuilder/Util.h\"\n\n#include <NTL/GF2X.h>\n#include <sstream>\n#include <boost/algorithm/string/erase.hpp>\n\n#include \"latticetester/ntlwrap.h\"\n\nnamespace NetBuilder {\n\n    const std::string NetConstructionTraits<NetConstruction::POLYNOMIAL>::name = \"Polynomial\";\n    \n    typedef typename NetConstructionTraits<NetConstruction::POLYNOMIAL>::GenValue GenValue;\n\n    typedef typename NetConstructionTraits<NetConstruction::POLYNOMIAL>::SizeParameter SizeParameter;\n\n    bool NetConstructionTraits<NetConstruction::POLYNOMIAL>::checkGenValue(const GenValue& genValue, const SizeParameter& sizeParameter)\n    {\n        return IsOne(GCD(genValue,sizeParameter));\n    }\n\n    unsigned int NetConstructionTraits<NetConstruction::POLYNOMIAL>::nRows(const SizeParameter& sizeParameter) {return (unsigned int) deg(sizeParameter); }\n\n    unsigned int NetConstructionTraits<NetConstruction::POLYNOMIAL>::nCols(const SizeParameter& sizeParameter) {return (unsigned int) deg(sizeParameter); }\n\n\n    void expandSeries(const GenValue& genValue, const SizeParameter& sizeParameter, std::vector<unsigned int>& expansion, unsigned int expansion_limit){\n        int m = (int) deg(sizeParameter); \n        for(int l = 1; l<= (int) expansion_limit ; l++){\n            int res =  (m-l >=0 && IsOne(coeff(genValue, m-l)))? 1 : 0;\n            int start = (l-m > 1) ? (l-m) : 1;\n            for( int p = start; p < l; p++){\n                res = ( res + expansion[p-1] * NTL::conv<int>(coeff(sizeParameter, m-(l-p)))) %2;        \n            }\n            expansion[l-1] = res;\n        }\n    }\n\n    GeneratingMatrix*  NetConstructionTraits<NetConstruction::POLYNOMIAL>::createGeneratingMatrix(const GenValue& genValue, const SizeParameter& sizeParameter, const Dimension& dimension_j, const unsigned int nRows)\n    {\n        unsigned int m = (unsigned int) (deg(sizeParameter));\n        unsigned int finalnRows = (nRows == 0)? m : nRows;\n        GeneratingMatrix* genMat = new GeneratingMatrix(finalnRows, m);\n        std::vector<unsigned int> expansion(finalnRows + m);\n        expandSeries(genValue, sizeParameter, expansion, finalnRows + m);\n        for(unsigned int c = 0; c < m; c++)\n        {\n            for(unsigned int row = 0; row < finalnRows; row++)\n            {\n                (*genMat)(row,c) = expansion[c + row];\n            }\n        }\n        return genMat;\n    }\n\n    typename NetConstructionTraits<NetConstruction::POLYNOMIAL>::GenValueSpaceCoordSeq NetConstructionTraits<NetConstruction::POLYNOMIAL>::genValueSpaceCoord(Dimension coord, const SizeParameter& sizeParameter)\n    {\n        if (coord==0)\n        {\n            Polynomial fakeModulus;\n            SetX(fakeModulus);\n            return GenValueSpaceCoordSeq(fakeModulus);\n        }\n        else\n        {\n           return GenValueSpaceCoordSeq(sizeParameter);\n        }\n    }\n\n    typename NetConstructionTraits<NetConstruction::POLYNOMIAL>::GenValueSpaceSeq NetConstructionTraits<NetConstruction::POLYNOMIAL>::genValueSpace(Dimension dimension, const SizeParameter& sizeParameter)\n    {\n        std::vector<GenValueSpaceCoordSeq> seqs;\n        seqs.reserve(dimension);\n        for(Dimension coord = 0; coord < dimension; ++coord)\n        {\n            seqs.push_back(genValueSpaceCoord(coord, sizeParameter));\n        }\n        return GenValueSpaceSeq(seqs);\n    }\n\n    std::string NetConstructionTraits<NetConstruction::POLYNOMIAL>::format(const std::vector<std::shared_ptr<GeneratingMatrix>>& genMatrices, const std::vector<std::shared_ptr<GenValue>>& genVals, const SizeParameter& sizeParameter, OutputStyle outputStyle, unsigned int interlacingFactor)\n    {\n        std::string res;\n        std::ostringstream stream;\n\n        if (outputStyle == OutputStyle::TERMINAL){\n            stream << \"Polynomial Digital Net - Modulus = \" << LatBuilder::IndexOfPolynomial(sizeParameter) << \" - GeneratingVector =\" << std::endl;\n            for (unsigned int coord = 0; coord < genVals.size(); coord++){\n                stream << \"  \" << LatBuilder::IndexOfPolynomial(*(genVals[coord])) << std::endl;\n            }\n        }\n\n        else if (outputStyle == OutputStyle::LATTICE){\n            stream << \"# Parameters for a polynomial lattice rule in base 2\" << std::endl;\n            stream << genVals.size() / interlacingFactor << \"      #  s =  \" << genVals.size() / interlacingFactor << \" dimensions\" << std::endl;\n            if (interlacingFactor > 1){\n                stream << interlacingFactor << \"    # Interlacing factor\" << std::endl;\n                stream << genVals.size() << \"    # Number of components = interlacing factor x dimension\" << std::endl;\n            }\n            stream << (int) deg(sizeParameter) << \"      # n = 2^\";\n            stream <<  (int) deg(sizeParameter) << \" = \" << (int)pow(2,deg(sizeParameter) ) << \" points\"<< std::endl;\n            \n            stream << LatBuilder::IndexOfPolynomial(sizeParameter) << \"   # polynomial modulus\" << std::endl;\n            stream << \"# Coordinates of generating vector, starting at j=1\" << std::endl;\n            std::string res;\n            for (unsigned int coord = 0; coord < genVals.size(); coord++){\n                res += std::to_string(LatBuilder::IndexOfPolynomial(*(genVals[coord]))) + \"\\n\";\n            }\n            res.pop_back();\n            stream << res;\n        }\n\n        res += stream.str();\n        return res;\n    }  \n}\n\n", "meta": {"hexsha": "6b517322488aebb2f84bc369cd4c5a7856fffff9", "size": 6229, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/NetBuilder/NetConstructionTraits-POLYNOMIAL.cc", "max_stars_repo_name": "YochevedDarmon/latnetbuilder", "max_stars_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NetBuilder/NetConstructionTraits-POLYNOMIAL.cc", "max_issues_repo_name": "YochevedDarmon/latnetbuilder", "max_issues_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NetBuilder/NetConstructionTraits-POLYNOMIAL.cc", "max_forks_repo_name": "YochevedDarmon/latnetbuilder", "max_forks_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1376811594, "max_line_length": 289, "alphanum_fraction": 0.6442446621, "num_tokens": 1485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.42921262462726145}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2015-2016 Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_FORMULAS_ANDOYER_INVERSE_HPP\r\n#define BOOST_GEOMETRY_FORMULAS_ANDOYER_INVERSE_HPP\r\n\r\n\r\n#include <boost/math/constants/constants.hpp>\r\n\r\n#include <boost/geometry/core/radius.hpp>\r\n#include <boost/geometry/core/srs.hpp>\r\n\r\n#include <boost/geometry/util/condition.hpp>\r\n#include <boost/geometry/util/math.hpp>\r\n\r\n#include <boost/geometry/algorithms/detail/flattening.hpp>\r\n\r\n#include <boost/geometry/formulas/differential_quantities.hpp>\r\n#include <boost/geometry/formulas/result_inverse.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry { namespace formula\r\n{\r\n\r\n/*!\r\n\\brief The solution of the inverse problem of geodesics on latlong coordinates,\r\n       Forsyth-Andoyer-Lambert type approximation with first order terms.\r\n\\author See\r\n    - Technical Report: PAUL D. THOMAS, MATHEMATICAL MODELS FOR NAVIGATION SYSTEMS, 1965\r\n      http://www.dtic.mil/docs/citations/AD0627893\r\n    - Technical Report: PAUL D. THOMAS, SPHEROIDAL GEODESICS, REFERENCE SYSTEMS, AND LOCAL GEOMETRY, 1970\r\n      http://www.dtic.mil/docs/citations/AD703541\r\n*/\r\ntemplate <\r\n    typename CT,\r\n    bool EnableDistance,\r\n    bool EnableAzimuth,\r\n    bool EnableReverseAzimuth = false,\r\n    bool EnableReducedLength = false,\r\n    bool EnableGeodesicScale = false\r\n>\r\nclass andoyer_inverse\r\n{\r\n    static const bool CalcQuantities = EnableReducedLength || EnableGeodesicScale;\r\n    static const bool CalcAzimuths = EnableAzimuth || EnableReverseAzimuth || CalcQuantities;\r\n    static const bool CalcFwdAzimuth = EnableAzimuth || CalcQuantities;\r\n    static const bool CalcRevAzimuth = EnableReverseAzimuth || CalcQuantities;\r\n\r\npublic:\r\n    typedef result_inverse<CT> result_type;\r\n\r\n    template <typename T1, typename T2, typename Spheroid>\r\n    static inline result_type apply(T1 const& lon1,\r\n                                    T1 const& lat1,\r\n                                    T2 const& lon2,\r\n                                    T2 const& lat2,\r\n                                    Spheroid const& spheroid)\r\n    {\r\n        result_type result;\r\n\r\n        // coordinates in radians\r\n\r\n        if ( math::equals(lon1, lon2) && math::equals(lat1, lat2) )\r\n        {\r\n            return result;\r\n        }\r\n\r\n        CT const c0 = CT(0);\r\n        CT const c1 = CT(1);\r\n        CT const pi = math::pi<CT>();\r\n        CT const f = detail::flattening<CT>(spheroid);\r\n\r\n        CT const dlon = lon2 - lon1;\r\n        CT const sin_dlon = sin(dlon);\r\n        CT const cos_dlon = cos(dlon);\r\n        CT const sin_lat1 = sin(lat1);\r\n        CT const cos_lat1 = cos(lat1);\r\n        CT const sin_lat2 = sin(lat2);\r\n        CT const cos_lat2 = cos(lat2);\r\n\r\n        // H,G,T = infinity if cos_d = 1 or cos_d = -1\r\n        // lat1 == +-90 && lat2 == +-90\r\n        // lat1 == lat2 && lon1 == lon2\r\n        CT cos_d = sin_lat1*sin_lat2 + cos_lat1*cos_lat2*cos_dlon;\r\n        // on some platforms cos_d may be outside valid range\r\n        if (cos_d < -c1)\r\n            cos_d = -c1;\r\n        else if (cos_d > c1)\r\n            cos_d = c1;\r\n\r\n        CT const d = acos(cos_d); // [0, pi]\r\n        CT const sin_d = sin(d);  // [-1, 1]\r\n        \r\n        if ( BOOST_GEOMETRY_CONDITION(EnableDistance) )\r\n        {\r\n            CT const K = math::sqr(sin_lat1-sin_lat2);\r\n            CT const L = math::sqr(sin_lat1+sin_lat2);\r\n            CT const three_sin_d = CT(3) * sin_d;\r\n\r\n            CT const one_minus_cos_d = c1 - cos_d;\r\n            CT const one_plus_cos_d = c1 + cos_d;\r\n            // cos_d = 1 or cos_d = -1 means that the points are antipodal\r\n\r\n            CT const H = math::equals(one_minus_cos_d, c0) ?\r\n                            c0 :\r\n                            (d + three_sin_d) / one_minus_cos_d;\r\n            CT const G = math::equals(one_plus_cos_d, c0) ?\r\n                            c0 :\r\n                            (d - three_sin_d) / one_plus_cos_d;\r\n\r\n            CT const dd = -(f/CT(4))*(H*K+G*L);\r\n\r\n            CT const a = get_radius<0>(spheroid);\r\n\r\n            result.distance = a * (d + dd);\r\n        }\r\n\r\n        if ( BOOST_GEOMETRY_CONDITION(CalcAzimuths) )\r\n        {\r\n            // sin_d = 0 <=> antipodal points\r\n            if (math::equals(sin_d, c0))\r\n            {\r\n                // T = inf\r\n                // dA = inf\r\n                // azimuth = -inf\r\n                result.azimuth = lat1 <= lat2 ? c0 : pi;\r\n            }\r\n            else\r\n            {\r\n                CT const c2 = CT(2);\r\n\r\n                CT A = c0;\r\n                CT U = c0;\r\n                if ( ! math::equals(cos_lat2, c0) )\r\n                {\r\n                    CT const tan_lat2 = sin_lat2/cos_lat2;\r\n                    CT const M = cos_lat1*tan_lat2-sin_lat1*cos_dlon;\r\n                    A = atan2(sin_dlon, M);\r\n                    CT const sin_2A = sin(c2*A);\r\n                    U = (f/ c2)*math::sqr(cos_lat1)*sin_2A;\r\n                }\r\n\r\n                CT B = c0;\r\n                CT V = c0;\r\n                if ( ! math::equals(cos_lat1, c0) )\r\n                {\r\n                    CT const tan_lat1 = sin_lat1/cos_lat1;\r\n                    CT const N = cos_lat2*tan_lat1-sin_lat2*cos_dlon;\r\n                    B = atan2(sin_dlon, N);\r\n                    CT const sin_2B = sin(c2*B);\r\n                    V = (f/ c2)*math::sqr(cos_lat2)*sin_2B;\r\n                }\r\n\r\n                CT const T = d / sin_d;\r\n\r\n                // even with sin_d == 0 checked above if the second point\r\n                // is somewhere in the antipodal area T may still be great\r\n                // therefore dA and dB may be great and the resulting azimuths\r\n                // may be some more or less arbitrary angles\r\n\r\n                if (BOOST_GEOMETRY_CONDITION(CalcFwdAzimuth))\r\n                {\r\n                    CT const dA = V*T - U;\r\n                    result.azimuth = A - dA;\r\n                    normalize_azimuth(result.azimuth, A, dA);\r\n                }\r\n\r\n                if (BOOST_GEOMETRY_CONDITION(CalcRevAzimuth))\r\n                {\r\n                    CT const dB = -U*T + V;\r\n                    result.reverse_azimuth = pi - B - dB;\r\n                    if (result.reverse_azimuth > pi)\r\n                    {\r\n                        result.reverse_azimuth -= 2 * pi;\r\n                    }\r\n                    normalize_azimuth(result.reverse_azimuth, B, dB);\r\n                }\r\n            }\r\n        }\r\n\r\n        if (BOOST_GEOMETRY_CONDITION(CalcQuantities))\r\n        {\r\n            typedef differential_quantities<CT, EnableReducedLength, EnableGeodesicScale, 1> quantities;\r\n            quantities::apply(dlon, sin_lat1, cos_lat1, sin_lat2, cos_lat2,\r\n                              result.azimuth, result.reverse_azimuth,\r\n                              get_radius<2>(spheroid), f,\r\n                              result.reduced_length, result.geodesic_scale);\r\n        }\r\n\r\n        return result;\r\n    }\r\n\r\nprivate:\r\n    static inline void normalize_azimuth(CT & azimuth, CT const& A, CT const& dA)\r\n    {\r\n        CT const c0 = 0;\r\n        \r\n        if (A >= c0) // A indicates Eastern hemisphere\r\n        {\r\n            if (dA >= c0) // A altered towards 0\r\n            {\r\n                if (azimuth < c0)\r\n                {\r\n                    azimuth = c0;\r\n                }\r\n            }\r\n            else // dA < 0, A altered towards pi\r\n            {\r\n                CT const pi = math::pi<CT>();\r\n                if (azimuth > pi)\r\n                {\r\n                    azimuth = pi;\r\n                }\r\n            }\r\n        }\r\n        else // A indicates Western hemisphere\r\n        {\r\n            if (dA <= c0) // A altered towards 0\r\n            {\r\n                if (azimuth > c0)\r\n                {\r\n                    azimuth = c0;\r\n                }\r\n            }\r\n            else // dA > 0, A altered towards -pi\r\n            {\r\n                CT const minus_pi = -math::pi<CT>();\r\n                if (azimuth < minus_pi)\r\n                {\r\n                    azimuth = minus_pi;\r\n                }\r\n            }\r\n        }\r\n    }\r\n};\r\n\r\n}}} // namespace boost::geometry::formula\r\n\r\n\r\n#endif // BOOST_GEOMETRY_FORMULAS_ANDOYER_INVERSE_HPP\r\n", "meta": {"hexsha": "612de413d95d4e7193592549ee4794d91c9bef54", "size": 8476, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/formulas/andoyer_inverse.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/formulas/andoyer_inverse.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/formulas/andoyer_inverse.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 34.1774193548, "max_line_length": 106, "alphanum_fraction": 0.5004719207, "num_tokens": 2008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.42921262462726145}}
{"text": "#include <vector>\n#include <type_traits>\n\n#include <boost/range/adaptor/transformed.hpp>\nnamespace ba = boost::adaptors;\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/functional.h>\nnamespace py = pybind11;\n\n#include <dionysus/row-reduction.h>\n#include <dionysus/ordinary-persistence.h>\n#include <dionysus/standard-reduction.h>\n\n#include \"filtration.h\"\n#include \"persistence.h\"                // to get access to PyReducedMatrix::Chain\n#include \"zigzag-persistence.h\"\n#include \"diagram.h\"\n#include \"progress.h\"\n\nPYBIND11_MAKE_OPAQUE(PyReducedMatrix::Chain);      // we want to provide our own binding for Chain\n\nstruct Time\n{\n            Time(float t_, size_t i_, unsigned dim_, bool dir_):\n                t(t_), i(i_), dim(dim_), dir(dir_)             {}\n\n    bool    operator<(const Time& other) const\n    {\n        if (t == other.t)\n        {\n            if (dir && !other.dir)      // add comes before remove\n                return true;\n            else if (!dir && other.dir)\n                return false;\n            else if (dim == other.dim)\n                return i < other.i;\n            else if (dir)\n                return dim < other.dim;\n            else // if (!dir)\n                return other.dim < dim;\n        }\n        else\n            return t < other.t;\n    }\n\n    float       t;\n    size_t      i;\n    unsigned    dim;\n    bool        dir;\n};\n\nclass PyTimeIndexMap\n{\n    public:\n        using ZZIndex           = PyZigzagPersistence::Index;\n        using FIndex            = size_t;\n        using Map               = std::unordered_map<ZZIndex, FIndex>;\n        using const_iterator    = Map::const_iterator;\n\n        void                    set(const ZZIndex& x, const FIndex& y)  { m_[x] = y; }\n        void                    remove(const ZZIndex& x)                { m_.erase(x); }\n\n        FIndex                  operator[](const ZZIndex& x) const      { return m_.find(x)->second; }\n        size_t                  size() const                            { return m_.size(); }\n\n        const_iterator          begin() const                           { return m_.begin(); }\n        const_iterator          end() const                             { return m_.end(); }\n\n    private:\n        Map     m_;\n};\n\nusing Times     = std::vector<std::vector<float>>;\nusing Callback  = std::function<void(size_t, float, bool, const PyZigzagPersistence*, const PyTimeIndexMap*)>;\n\nstd::tuple<PyZigzagPersistence, std::vector<PyDiagram>, PyTimeIndexMap>\nzigzag_homology_persistence(const PyFiltration&     f,\n                            const Times&            times_,\n                            PyZpField::Element      prime,\n                            const Callback&         callback,\n                            bool                    show_progress)\n{\n    using Index          = PyZigzagPersistence::Index;\n    using CellChainEntry = dionysus::ChainEntry<PyZpField, PySimplex>;\n    using ChainEntry     = dionysus::ChainEntry<PyZpField, Index>;\n\n    std::vector<Time> times;\n    for (size_t i = 0; i < times_.size(); ++i)\n    {\n        int dim = f[i].dimension();\n        bool dir = true;\n        for (float t : times_[i])\n        {\n            times.emplace_back(t, i, dim, dir);\n            dir = !dir;\n        }\n    }\n    std::sort(times.begin(), times.end());\n\n    std::unique_ptr<Progress> progress(new NoProgress);\n    if (show_progress)\n        progress = std::unique_ptr<Progress>(new ShowProgress(times.size()));\n\n    std::vector<PyDiagram> diagrams;\n    PyZpField field(prime);\n    PyZigzagPersistence persistence(field);\n    unsigned op = 0;\n    unsigned cell = 0;\n    std::vector<unsigned>   cells(f.size(), -1);\n    PyTimeIndexMap          cells_inv_;\n    for (auto& tt : times)\n    {\n        (*progress)();\n\n        size_t i = tt.i; float t = tt.t; bool dir = tt.dir;\n\n        auto& c = f[i];\n        if (dir)\n        {\n            cells_inv_.set(cell, i);\n            cells[i] = cell++;\n\n            Index pair = persistence.add(c.boundary(persistence.field()) |\n                                                    ba::transformed([&](const CellChainEntry& e)\n                                                    {\n                                                        auto idx = f.index(e.index());\n                                                        return ChainEntry(e.element(), cells[idx]);\n                                                    }));\n\n            if (pair != persistence.unpaired())\n            {\n                auto t_birth = times[pair].t;\n                if (t_birth != t)\n                {\n                    int dim = c.dimension()-1;\n                    while (dim+1 > diagrams.size())\n                        diagrams.emplace_back();\n                    diagrams[dim].emplace_back(t_birth, t, pair);\n                }\n            }\n\n            ++op;\n        } else\n        {\n            Index pair = persistence.remove(cells[i]);\n            cells_inv_.remove(cells[i]);\n            cells[i] = -1;\n            if (pair != persistence.unpaired())\n            {\n                auto t_birth = times[pair].t;\n                if (t_birth != t)\n                {\n                    int dim = c.dimension();\n                    while (dim+1 > diagrams.size())\n                        diagrams.emplace_back();\n                    diagrams[dim].emplace_back(t_birth, t, pair);\n                }\n            }\n            ++op;\n        }\n\n        callback(i,t,dir,&persistence,&cells_inv_);\n    }\n\n    // add infinite points\n    constexpr float inf = std::numeric_limits<float>::infinity();\n    for (auto& birth_idx : persistence.alive_ops())\n    {\n        auto i_birth   = times[birth_idx].i;\n        auto t_birth   = times[birth_idx].t;\n        auto dir_birth = times[birth_idx].dir;\n\n        int dim = f[i_birth].dimension();\n        if (!dir_birth)     // born on removal\n            dim -= 1;\n        while (dim+1 > diagrams.size())\n            diagrams.emplace_back();\n        diagrams[dim].emplace_back(t_birth, inf, birth_idx);\n    }\n\n    return std::make_tuple(std::move(persistence), std::move(diagrams), std::move(cells_inv_));\n}\n\n// custom iterator that preserves right filtration order\nstruct PyZZAliveCycleIterator\n{\n            PyZZAliveCycleIterator(const PyZigzagPersistence& zz_, py::object ref_):\n                zz(zz_), ref(ref_)\n    {\n        for (PyZigzagPersistence::Index x : zz.alive_cycles())\n            indices.push_back(x);\n        std::sort(indices.begin(), indices.end());\n    }\n\n    PyReducedMatrix::Chain  next()\n    {\n        if (idx == indices.size())\n            throw py::stop_iteration();\n\n        PyReducedMatrix::Chain c;\n        for (auto& x : zz.cycle(indices[idx]))\n            c.emplace_back(x.element(), std::get<0>(x.index()));\n        ++idx;\n        return c;\n    }\n\n    const PyZigzagPersistence&                  zz;\n    py::object                                  ref;\n    size_t                                      idx = 0;\n    std::vector<PyZigzagPersistence::Index>     indices;\n};\n\n#include \"chain.h\"\n\nvoid init_zigzag_persistence(py::module& m)\n{\n    using namespace pybind11::literals;\n    m.def(\"zigzag_homology_persistence\",   &zigzag_homology_persistence, \"filtration\"_a, \"times\"_a, \"prime\"_a = 2,\n                                                                         \"callback\"_a = Callback([](size_t, float, bool, const PyZigzagPersistence*, const PyTimeIndexMap*){}),\n                                                                         \"progress\"_a = false,\n          R\"(\n          compute zigzag homology persistence of the filtration with respect to the given times\n\n          Args:\n              filtration: an instance of :class:`~dionysus._dionysus.Filtration` with the set of simplices used in the zigzag construction\n              times:      a list of lists; the outer list runs parallel with the filtration;\n                          the inner list specifies for each simplex when it enters and leaves the zigzag\n                          (even entries, starting the indexing from 0, are interpreted as appearance times, odd entires as disappearance)\n              prime:      prime modulo which to perform computation\n              callback:   function to call after every step in the zigzag; it gets arguments `(i,t,d,zz,cells)`,\n                          where `i` is the index of the simplex being added or removed, `t` is the time,\n                          `d` is the \"direction\" (`True` if the simplex is being added, `False` if it`s being removed),\n                          `zz` is the current state of the :class:`~dionysus._dionysus.ZigzagPersistence`,\n                          `cells` is the map from the internal indices of the zigzag representation to the filtration indices,\n              progress:   show a progress bar.\n\n          Returns:\n              A triple. The first element is an instance of\n              :class:`~dionysus._dionysus.ZigzagPersistence`, which offers access to the cycles\n              alive at the end of the zigzag; the second is a list of\n              persistence diagrams; the third is an instance of\n              :class:`~dionysus._dionysus.TimeIndexMap` for translating cycles\n              from the internal representation to filtration indices.\n          )\");\n\n   py::class_<PyZZAliveCycleIterator>(m, \"ZZAliveCycleIterator\")\n        .def(\"__iter__\", [](PyZZAliveCycleIterator& it) -> PyZZAliveCycleIterator& { return it; })\n        .def(\"__next__\", &PyZZAliveCycleIterator::next);\n\n    py::class_<PyZigzagPersistence>(m, \"ZigzagPersistence\", \"representation of the current homology basis\")\n        .def(py::init<PyZpField>())\n        .def(\"__len__\",     &PyZigzagPersistence::alive_size,       \"number of alive cycles\")\n        .def(\"__iter__\",    [](py::object zz)   { return PyZZAliveCycleIterator(zz.cast<const PyZigzagPersistence&>(), zz); }, \"iterator over the alive cycles\")\n        .def(\"__repr__\",    [](const PyZigzagPersistence& zz)\n                            { std::ostringstream oss; oss << \"Zigzag persistence with \" << zz.alive_size() << \" alive cycles\"; return oss.str(); })\n    ;\n\n    py::class_<PyTimeIndexMap>(m, \"TimeIndexMap\", \"map from the internal representation of zigzag persistence to filtration indices\")\n        .def(\"__len__\",     &PyTimeIndexMap::size,                      \"size of the map\")\n        .def(\"__getitem__\", [](const PyTimeIndexMap& m, size_t i) { return m[i]; }, \"access the filtration index of the given internal index\")\n        .def(\"__iter__\",    [](const PyTimeIndexMap& m) { return py::make_iterator(m.begin(), m.end()); },\n                                py::keep_alive<0, 1>() /* Essential: keep object alive while iterator exists */,\n                                \"iterate over the entries of the map\")\n    ;\n}\n", "meta": {"hexsha": "10654bea744b951164d4e06d1df463b8d2f6565a", "size": 10795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bindings/python/zigzag-persistence.cpp", "max_stars_repo_name": "dlm/dionysus", "max_stars_repo_head_hexsha": "f7768668c6820adb1d49db291270ae3a99e14d18", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 114.0, "max_stars_repo_stars_event_min_datetime": "2017-07-19T21:43:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:54:11.000Z", "max_issues_repo_path": "bindings/python/zigzag-persistence.cpp", "max_issues_repo_name": "dlm/dionysus", "max_issues_repo_head_hexsha": "f7768668c6820adb1d49db291270ae3a99e14d18", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 50.0, "max_issues_repo_issues_event_min_datetime": "2017-07-19T21:39:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-02T17:40:19.000Z", "max_forks_repo_path": "bindings/python/zigzag-persistence.cpp", "max_forks_repo_name": "dlm/dionysus", "max_forks_repo_head_hexsha": "f7768668c6820adb1d49db291270ae3a99e14d18", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2017-08-17T17:11:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T09:59:57.000Z", "avg_line_length": 40.2798507463, "max_line_length": 175, "alphanum_fraction": 0.5339509032, "num_tokens": 2404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.42917608709806754}}
{"text": "#include \"TensorLines.hh\"\n\n#include \"TensorProductBezierTriangles.hh\"\n#include \"TensorCoreLinesEvaluator.hh\"\n#include \"TensorTopologyEvaluator.hh\"\n#include \"ParallelEigenvectorsEvaluator.hh\"\n\n#include <Eigen/Eigenvalues>\n#include <Eigen/LU>\n\n#include <boost/range/algorithm/min_element.hpp>\n#include <boost/range/algorithm_ext/insert.hpp>\n#include <boost/optional.hpp>\n\n#include <stack>\n#include <queue>\n#include <iterator>\n#include <complex>\n#include <type_traits>\n\nusing namespace cpp_utils;\n\nnamespace\n{\nusing namespace tl;\n\n/**\n * Representative Solution in a cluster of similar solutions\n */\ntemplate <typename Evaluator>\nstruct ClusterRepr\n{\n    std::size_t cluster_size;\n    Evaluator eval;\n};\n\n\n/**\n * Cluster all triangles in a list that are closer than a given distance\n *\n * @param cands List of candidates generated by parallelEigenvectorSearch()\n * @param epsilon Maximum distance of triangles in a cluster\n *\n * @return List of clusters (each cluster is a list of candidates)\n */\ntemplate <typename CandList>\nstd::vector<CandList>\nclusterTris(const CandList& cands, double epsilon)\n{\n    auto classes = std::vector<CandList>{};\n    for(const auto& t : cands)\n    {\n        classes.push_back({t});\n    }\n\n    auto has_close_elements = [&](const CandList& c1,\n                                  const CandList& c2) {\n        if(c1 == c2) return false;\n        for(const auto& t1 : c1)\n        {\n            for(const auto& t2 : c2)\n            {\n                if(distance(t1, t2) <= epsilon)\n                {\n                    return true;\n                }\n            }\n        }\n        return false;\n    };\n\n    auto changed = true;\n    while(changed)\n    {\n        changed = false;\n        for(auto it = std::begin(classes); it != std::end(classes); ++it)\n        {\n            auto jt = it;\n            ++jt;\n            for(; jt != std::end(classes); ++jt)\n            {\n                if(has_close_elements(*it, *jt))\n                {\n                    it->insert(std::end(*it), std::begin(*jt), std::end(*jt));\n                    jt = classes.erase(jt);\n                    --jt;\n                    changed = true;\n                }\n            }\n        }\n    }\n    return classes;\n}\n\n\n/**\n * @brief Select representative solutions for each cluster.\n * @details For each cluster, the solution candidate with the smallest error\n *      estimate is chosen as a representative. Also returns the number of\n *      elements in the cluster.\n *\n * @param clusters Vector of vectors of Evaluators representing solution\n *     clusters as produced by clusterTris().\n * @return A cluster representative for each input cluster.\n */\ntemplate <typename Evaluator>\nstd::vector<ClusterRepr<Evaluator>>\nfindRepresentatives(const std::vector<std::vector<Evaluator>>& clusters)\n{\n    static_assert(is_evaluator_v<Evaluator>,\n                  \"findRepresentatives requires a valid Evaluator!\");\n    auto result = std::vector<ClusterRepr<Evaluator>>{};\n    for(const auto& c : clusters)\n    {\n        using namespace boost;\n        using namespace boost::adaptors;\n        result.push_back(\n                {c.size(),\n                 *min_element(c, [](const auto& c1, const auto& c2) {\n                     return c1.error() < c2.error();\n                 })});\n    }\n    return result;\n}\n\n\n/**\n * @brief Compute context info for representatives\n * @details Computes global point position, eigenvalue order, presence of other\n *      imaginary eigenvalues, and packs into result list together with point\n *      position, eigenvector direction, eigenvalues.\n *\n * @param representatives TriPairs selected by findRepresentatives()\n * @param s_interp First tensor field on the triangle\n * @param t_interp Second tensor field on the triangle\n * @param tri Spatial triangle\n * @return List of TLPoints with context info\n */\nPointList\ncomputeContextInfoPEV(\n        const std::vector<\n            ClusterRepr<ParallelEigenvectorsEvaluator>>& representatives,\n        const TensorInterp& s_interp,\n        const TensorInterp& t_interp,\n        const Triangle& tri)\n{\n    auto points = PointList{};\n    points.reserve(representatives.size());\n\n    for(const auto& r : representatives)\n    {\n        const auto& pos_tri = r.eval.tris().pos_tri;\n        const auto& dir_tri = r.eval.tris().dir_tri;\n\n        auto result_center = pos_tri({1. / 3., 1. / 3., 1. / 3.});\n        auto result_dir = dir_tri({1. / 3., 1. / 3., 1. / 3.}).normalized();\n\n        // We want to know which eigenvector of each tensor field we have\n        // found (i.e. corresponding to largest, middle, or smallest\n        // eigenvalue)\n        // Therefore we explicitly compute the eigenvalues at the result\n        // position and check which ones the found eigenvector direction\n        // corresponds to.\n        // @todo: make this step optional\n\n        auto s = s_interp(result_center);\n        auto t = t_interp(result_center);\n\n        // Get eigenvalues from our computed direction\n        auto s_real_eigv = (s * result_dir).dot(result_dir);\n        auto t_real_eigv = (t * result_dir).dot(result_dir);\n\n        // Compute all eigenvalues using Eigen\n        auto s_eigvs = s.eigenvalues().eval();\n        auto t_eigvs = t.eigenvalues().eval();\n\n        // Find index of eigenvalue that is closest to the one we computed\n        using Vec3c = decltype(s_eigvs);\n        auto s_closest_index = Vec3d::Index{0};\n        (s_eigvs - Vec3c::Ones() * s_real_eigv)\n                .cwiseAbs()\n                .minCoeff(&s_closest_index);\n\n        auto t_closest_index = Vec3d::Index{0};\n        (t_eigvs - Vec3c::Ones() * t_real_eigv)\n                .cwiseAbs()\n                .minCoeff(&t_closest_index);\n\n        // Find which of the (real) eigenvalues ours is\n        auto count_larger_real = [](double ref,\n                                    const std::complex<double>& val) {\n            if(val.imag() != 0) return 0;\n            if(std::abs(ref) >= std::abs(val.real())) return 0;\n            return 1;\n        };\n        auto s_order = s_eigvs.unaryExpr([&](const std::complex<double>& val) {\n                                  return count_larger_real(\n                                          s_eigvs[s_closest_index].real(), val);\n                              })\n                               .sum();\n        auto t_order = t_eigvs.unaryExpr([&](const std::complex<double>& val) {\n                                  return count_larger_real(\n                                          t_eigvs[t_closest_index].real(), val);\n                              })\n                               .sum();\n\n        points.push_back(\n                TLPoint{tri(result_center),\n                         ERank(s_order),\n                         ERank(t_order),\n                         result_dir,\n                         s_real_eigv,\n                         t_real_eigv,\n                         s_eigvs.sum().imag() != 0,\n                         t_eigvs.sum().imag() != 0,\n                         r.cluster_size,\n                         (pos_tri[1] - pos_tri[0]).norm(),\n                         (dir_tri[1] - dir_tri[0]).norm(),\n                         0.});\n    }\n    return points;\n}\n\n\nPointList\ncomputeContextInfoTCL(\n        const std::vector<ClusterRepr<TensorCoreLinesEvaluator>>& representatives,\n        const TensorInterp& t_interp,\n        const TensorInterp& tx_interp,\n        const TensorInterp& ty_interp,\n        const TensorInterp& tz_interp,\n        const Triangle& tri)\n{\n    auto points = PointList{};\n    points.reserve(representatives.size());\n\n    for(const auto& r : representatives)\n    {\n        const auto& pos_tri = r.eval.tris().pos_tri;\n        const auto& dir_tri = r.eval.tris().dir_tri;\n\n        auto result_center = pos_tri({1. / 3., 1. / 3., 1. / 3.});\n        auto result_dir = dir_tri({1. / 3., 1. / 3., 1. / 3.}).normalized();\n\n        // We want to know which eigenvector of each tensor field we have\n        // found (i.e. corresponding to largest, middle, or smallest\n        // eigenvalue)\n        // Therefore we explicitly compute the eigenvalues at the result\n        // position and check which ones the found eigenvector direction\n        // corresponds to.\n        // @todo: make this step optional\n\n        auto t = t_interp(result_center);\n        auto tx = tx_interp(result_center);\n        auto ty = ty_interp(result_center);\n        auto tz = tz_interp(result_center);\n        auto dt = (tx * result_dir[0] + ty * result_dir[1] + tz * result_dir[2])\n                          .eval();\n\n        // Get eigenvalues from our computed direction\n        auto t_real_eigv = (t * result_dir).dot(result_dir);\n        auto dt_real_eigv = (dt * result_dir).dot(result_dir);\n\n        // Compute all eigenvalues using Eigen\n        auto t_eigvs = t.eigenvalues().eval();\n        auto dt_eigvs = dt.eigenvalues().eval();\n\n        // Find index of eigenvalue that is closest to the one we computed\n        using Vec3c = decltype(t_eigvs);\n        auto t_closest_index = Vec3d::Index{0};\n        (t_eigvs - Vec3c::Ones() * t_real_eigv)\n                .cwiseAbs()\n                .minCoeff(&t_closest_index);\n\n        auto dt_closest_index = Vec3d::Index{0};\n        (dt_eigvs - Vec3c::Ones() * dt_real_eigv)\n                .cwiseAbs()\n                .minCoeff(&dt_closest_index);\n\n        // Find which of the (real) eigenvalues ours is\n        auto count_larger_real = [](double ref,\n                                    const std::complex<double>& val) {\n            if(val.imag() != 0) return 0;\n            if(std::abs(ref) >= std::abs(val.real())) return 0;\n            return 1;\n        };\n        auto t_order = t_eigvs.unaryExpr([&](const std::complex<double>& val) {\n                                  return count_larger_real(\n                                          t_eigvs[t_closest_index].real(), val);\n                              })\n                               .sum();\n        auto dt_order =\n                dt_eigvs.unaryExpr([&](const std::complex<double>& val) {\n                            return count_larger_real(\n                                    dt_eigvs[dt_closest_index].real(), val);\n                        })\n                        .sum();\n\n        // det( (NablaT*R1)*R  ,  (NablaT*R2)*R ,  R )\n        auto r2 = Vec3d::Random().normalized().eval();\n        while(result_dir.cross(r2).norm() < 0.1)\n        {\n            r2 = Vec3d::Random().normalized().eval();\n        }\n        auto r1 = result_dir.cross(r2).normalized().eval();\n        r2 = r1.cross(result_dir).normalized().eval();\n        auto scale = t.operatorNorm();\n        auto stability = std::log(std::abs(\n                (Mat3d{} << ((tx * r1[0] + ty * r1[1] + tz * r1[2])\n                             * result_dir)\n                                    / scale,\n                 ((tx * r2[0] + ty * r2[1] + tz * r2[2]) * result_dir) / scale,\n                 result_dir)\n                        .finished()\n                        .determinant()));\n\n        points.push_back(\n                TLPoint{tri(result_center),\n                         ERank(t_order),\n                         ERank(dt_order),\n                         result_dir,\n                         t_real_eigv,\n                         dt_real_eigv,\n                         t_eigvs.sum().imag() != 0,\n                         dt_eigvs.sum().imag() != 0,\n                         r.cluster_size,\n                         (pos_tri[1] - pos_tri[0]).norm(),\n                         (dir_tri[1] - dir_tri[0]).norm(),\n                         stability});\n    }\n    return points;\n}\n\n\nPointList computeContextInfoTopo(\n        const std::vector<ClusterRepr<TensorTopologyEvaluator>>& representatives,\n        const Triangle& tri)\n{\n    auto points = PointList{};\n    points.reserve(representatives.size());\n\n    for(const auto& r : representatives)\n    {\n        const auto& pos_tri = r.eval.tris().pos_tri;\n\n        auto result_center = pos_tri({1. / 3., 1. / 3., 1. / 3.});\n\n        points.push_back(\n                TLPoint{tri(result_center),\n                         ERank::First,\n                         ERank::First,\n                         Vec3d::Zero(),\n                         0,\n                         0,\n                         false,\n                         false,\n                         r.cluster_size,\n                         (pos_tri[1] - pos_tri[0]).norm(),\n                         0,\n                         0});\n    }\n    return points;\n}\n\n\n/**\n * @brief Perform the recursive root search using an evaluator.\n * @details Performs a breadth-first recursive search for solutions of the\n *      starting evaluator. Terminates when all solutions have been found or\n *      when more than @a max_candidates are in the queue. In the latter case,\n *      @c boost::none is returned.\n *\n * @param start_ev Starting evaluator\n * @param max_candidates Maximum number of triangles produced during subdivision\n *     before early termination\n * @param num_splits Optional output parameter for storing the number of split\n *     operations performed\n * @param max_level Optional output parameter for storing the maximum\n *     subdivision level reached\n * @return A vector of solution candidates represented by Evaluators at the lowest\n *      subdivision level, or boost::none if the search was terminated early.\n */\ntemplate <typename Evaluator>\nboost::optional<std::vector<Evaluator>>\nrootSearch(const Evaluator& start_ev,\n           std::size_t max_candidates,\n           uint64_t* num_splits = nullptr,\n           uint64_t* max_level = nullptr)\n{\n    static_assert(is_evaluator_v<Evaluator>,\n                  \"rootSearch requires a valid Evaluator!\");\n\n    auto work_lst = std::queue<Evaluator>{};\n    work_lst.push(start_ev);\n    auto result = std::vector<Evaluator>{};\n\n    while(!work_lst.empty())\n    {\n        if(work_lst.size() > max_candidates) return boost::none;\n        auto ev = work_lst.front();\n        work_lst.pop();\n        if(num_splits) *num_splits += 1;\n        if(max_level && *max_level < ev.splitLevel())\n        {\n            *max_level = ev.splitLevel();\n        }\n\n        switch(ev.eval())\n        {\n            case Result::Split:\n                for(const auto& p : ev.split())\n                {\n                    work_lst.push(p);\n                }\n                break;\n            case Result::Accept:\n                result.push_back(ev);\n                break;\n            case Result::Discard:\n                break;\n        }\n    }\n\n    return result;\n}\n\n\n/**\n * Search for parallel eigenvector intersections with a triangle.\n *\n * @param s First tensor field (linear on a triangle)\n * @param t Second tensor field (linear on a triangle)\n * @param tri Physical location of the triangle\n * @param tolerance Error tolerance for subdivision\n * @param max_candidates Maximum number of triangles produced during subdivision\n *     before early termination\n * @param num_splits Optional output parameter for storing the number of split\n *     operations performed\n * @param max_level Optional output parameter for storing the maximum\n *     subdivision level reached\n * @return A vector of all found solution candidates and a vector of the\n *     rough eigenvector directions that resulted in early termination\n */\nstd::pair<std::vector<ParallelEigenvectorsEvaluator>, std::vector<Vec3d>>\nparallelEigenvectorSearch(const TensorInterp& s,\n                          const TensorInterp& t,\n                          const Triangle& tri,\n                          double tolerance,\n                          std::size_t max_candidates,\n                          uint64_t* num_splits = nullptr,\n                          uint64_t* max_level = nullptr)\n{\n    auto result = std::vector<ParallelEigenvectorsEvaluator>{};\n    // Stores directions for which the search was terminated because of\n    // too many splits\n    auto failed_dirs = std::vector<Vec3d>{};\n\n    auto compute_tri = [&](const Triangle& r) {\n        auto start_ev = ParallelEigenvectorsEvaluator(\n                {tri, r}, s, t, {tolerance});\n        auto solutions =\n                rootSearch(start_ev, max_candidates, num_splits, max_level);\n        if(solutions)\n        {\n            boost::insert(\n                    result,\n                    result.end(),\n                    solutions.value());\n        }\n        else\n        {\n            failed_dirs.push_back(r({1./3, 1./3, 1./3}));\n        }\n    };\n\n    // Four triangles covering hemisphere\n    auto dir_tris = std::array<Triangle, 4>{\n            Triangle{{Vec3d{1, 0, 0}, Vec3d{0, 1, 0}, Vec3d{0, 0, 1}}},\n            Triangle{{Vec3d{0, 1, 0}, Vec3d{-1, 0, 0}, Vec3d{0, 0, 1}}},\n            Triangle{{Vec3d{-1, 0, 0}, Vec3d{0, -1, 0}, Vec3d{0, 0, 1}}},\n            Triangle{{Vec3d{0, -1, 0}, Vec3d{1, 0, 0}, Vec3d{0, 0, 1}}}};\n\n    for(const auto& tri : dir_tris)\n    {\n        for(const auto& t : tri.split())\n        {\n            compute_tri(t);\n        }\n    }\n\n    return {result, failed_dirs};\n}\n\n\n\n/**\n * Search for tensor core line intersections with a triangle.\n *\n * @param t Tensor field (linear on a triangle)\n * @param dt derivatives of the tensor field (constant on a triangle)\n * @param tri Physical location of the triangle\n * @param tolerance Error tolerance for subdivision\n * @param max_candidates Maximum number of triangles produced during subdivision\n *     before early termination\n * @param num_splits Optional output parameter for storing the number of split\n *     operations performed\n * @param max_level Optional output parameter for storing the maximum\n *     subdivision level reached\n * @return A vector of all found solution candidates and a vector of the\n *     rough eigenvector directions that resulted in early termination\n */\nstd::pair<std::vector<TensorCoreLinesEvaluator>, std::vector<Vec3d>>\ntensorCoreLinesSearch(const TensorInterp& t,\n                         const std::array<TensorInterp, 3>& dt,\n                         const Triangle& tri,\n                         double tolerance,\n                         std::size_t max_candidates,\n                         uint64_t* num_splits = nullptr,\n                         uint64_t* max_level = nullptr)\n{\n    auto result = std::vector<TensorCoreLinesEvaluator>{};\n    // Stores directions for which the search was terminated because of\n    // too many splits\n    auto failed_dirs = std::vector<Vec3d>{};\n\n    auto compute_tri = [&](const Triangle& r) {\n        auto start_ev = TensorCoreLinesEvaluator(\n                {tri, r}, t, dt, {tolerance});\n        auto solutions =\n                rootSearch(start_ev, max_candidates, num_splits, max_level);\n        if(solutions)\n        {\n            boost::insert(result, result.end(), solutions.value());\n        }\n        else\n        {\n            failed_dirs.push_back(r({1. / 3, 1. / 3, 1. / 3}));\n        }\n    };\n\n    auto dir_tris = std::array<Triangle, 4>{\n            Triangle{{Vec3d{1, 0, 0}, Vec3d{0, 1, 0}, Vec3d{0, 0, 1}}},\n            Triangle{{Vec3d{0, 1, 0}, Vec3d{-1, 0, 0}, Vec3d{0, 0, 1}}},\n            Triangle{{Vec3d{-1, 0, 0}, Vec3d{0, -1, 0}, Vec3d{0, 0, 1}}},\n            Triangle{{Vec3d{0, -1, 0}, Vec3d{1, 0, 0}, Vec3d{0, 0, 1}}}};\n\n    for(const auto& tri : dir_tris)\n    {\n        for(const auto& t : tri.split())\n        {\n            compute_tri(t);\n        }\n    }\n\n    return {result, failed_dirs};\n}\n\n\n/**\n * Search for degenerate line intersections with a triangle.\n *\n * @param t Tensor field (linear on a triangle)\n * @param tri Physical location of the triangle\n * @param tolerance Error tolerance for subdivision\n * @param max_candidates Maximum number of triangles produced during subdivision\n *     before early termination\n * @param num_splits Optional output parameter for storing the number of split\n *     operations performed\n * @param max_level Optional output parameter for storing the maximum\n *     subdivision level reached\n * @return A vector of all found solution candidates and a vector of the\n *     rough eigenvector directions that resulted in early termination\n */\nstd::pair<std::vector<TensorTopologyEvaluator>, std::vector<Vec3d>>\ntensorTopologySearch(const TensorInterp& t,\n                     const Triangle& tri,\n                     double tolerance,\n                     std::size_t max_candidates,\n                     uint64_t* num_splits = nullptr,\n                     uint64_t* max_level = nullptr)\n{\n    auto start_ev = TensorTopologyEvaluator(\n            {tri, Triangle{{Vec3d::Zero(), Vec3d::Zero(), Vec3d::Zero()}}},\n            t,\n            {tolerance});\n    auto solutions =\n            rootSearch(start_ev, max_candidates, num_splits, max_level);\n\n    if(solutions)\n    {\n        return {solutions.value(), std::vector<Vec3d>{}};\n    }\n    else\n    {\n        return {std::vector<TensorTopologyEvaluator>{},\n                std::vector<Vec3d>{1, Vec3d::Zero()}};\n    }\n}\n\n} // namespace\n\n\nnamespace tl\n{\n\nTLResult findParallelEigenvectors(const std::array<Mat3d, 3>& s,\n                                   const std::array<Mat3d, 3>& t,\n                                   const std::array<Vec3d, 3>& x,\n                                   const TLOptions& opts)\n{\n    auto start_tri =\n            Triangle{{Vec3d{1., 0., 0.}, Vec3d{0., 1., 0.}, Vec3d{0., 0., 1.}}};\n\n    auto st = TensorInterp{{s[0], s[1], s[2]}};\n    auto tt = TensorInterp{{t[0], t[1], t[2]}};\n    auto xt = Triangle{{x[0], x[1], x[2]}};\n\n    auto num_splits = uint64_t{0};\n    auto max_level = uint64_t{0};\n    auto tris = parallelEigenvectorSearch(st,\n                                          tt,\n                                          start_tri,\n                                          opts.tolerance,\n                                          opts.max_candidates,\n                                          &num_splits,\n                                          &max_level);\n\n    auto clustered_tris = clusterTris(tris.first, opts.cluster_epsilon);\n\n    auto representatives = findRepresentatives(clustered_tris);\n\n    return {computeContextInfoPEV(representatives, st, tt, xt),\n            tris.second};\n}\n\n\nTLResult findParallelEigenvectors(const std::array<Mat3d, 3>& s,\n                                   const std::array<Mat3d, 3>& t,\n                                   const TLOptions& opts)\n{\n    return findParallelEigenvectors(\n            s,\n            t,\n            {Vec3d{1., 0., 0.}, Vec3d{0., 1., 0.}, Vec3d{0., 0., 1.}},\n            opts);\n}\n\n\nTLResult findTensorCoreLines(const std::array<Mat3d, 3>& t,\n                                 const std::array<Mat3d, 3>& dt,\n                                 const std::array<Vec3d, 3>& x,\n                                 const TLOptions& opts)\n{\n    auto start_tri =\n            Triangle{{Vec3d{1., 0., 0.}, Vec3d{0., 1., 0.}, Vec3d{0., 0., 1.}}};\n\n    auto tt = TensorInterp{{t[0], t[1], t[2]}};\n    auto tx = TensorInterp{{dt[0], dt[0], dt[0]}};\n    auto ty = TensorInterp{{dt[1], dt[1], dt[1]}};\n    auto tz = TensorInterp{{dt[2], dt[2], dt[2]}};\n    auto xt = Triangle{{x[0], x[1], x[2]}};\n\n    auto tolerance_scale = std::max({tt[0].operatorNorm(),\n                                     tt[1].operatorNorm(),\n                                     tt[2].operatorNorm()});\n\n    auto num_splits = uint64_t{0};\n    auto max_level = uint64_t{0};\n    auto tris = tensorCoreLinesSearch(tt,\n                                         {tx, ty, tz},\n                                         start_tri,\n                                         opts.tolerance*tolerance_scale,\n                                         opts.max_candidates,\n                                         &num_splits,\n                                         &max_level);\n\n    auto clustered_tris = clusterTris(tris.first, opts.cluster_epsilon);\n\n    auto representatives = findRepresentatives(clustered_tris);\n\n    return {computeContextInfoTCL(representatives, tt, tx, ty, tz, xt),\n            tris.second};\n}\n\n\nTLResult findTensorCoreLines(const std::array<Mat3d, 3>& t,\n                                 const std::array<Mat3d, 3>& dt,\n                                 const TLOptions& opts)\n{\n    return findTensorCoreLines(\n            t,\n            dt,\n            {Vec3d{1., 0., 0.}, Vec3d{0., 1., 0.}, Vec3d{0., 0., 1.}},\n            opts);\n}\n\nTLResult findTensorTopology(const std::array<Mat3d, 3>& t,\n                             const std::array<Vec3d, 3>& x,\n                             const TLOptions& opts)\n{\n    auto start_tri =\n            Triangle{{Vec3d{1., 0., 0.}, Vec3d{0., 1., 0.}, Vec3d{0., 0., 1.}}};\n\n    auto tt = TensorInterp{{t[0], t[1], t[2]}};\n    auto xt = Triangle{{x[0], x[1], x[2]}};\n\n    auto tolerance_scale = std::max({tt[0].operatorNorm(),\n                                     tt[1].operatorNorm(),\n                                     tt[2].operatorNorm()});\n\n    auto num_splits = uint64_t{0};\n    auto max_level = uint64_t{0};\n    auto tris = tensorTopologySearch(tt,\n                                     start_tri,\n                                     opts.tolerance * tolerance_scale,\n                                     opts.max_candidates,\n                                     &num_splits,\n                                     &max_level);\n\n    auto clustered_tris = clusterTris(tris.first, opts.cluster_epsilon);\n\n    auto representatives = findRepresentatives(clustered_tris);\n\n    return {computeContextInfoTopo(representatives, xt),\n            tris.second};\n}\n\n\nTLResult findTensorTopology(const std::array<Mat3d, 3>& t,\n                             const TLOptions& opts)\n{\n    return findTensorTopology(\n            t,\n            {Vec3d{1., 0., 0.}, Vec3d{0., 1., 0.}, Vec3d{0., 0., 1.}},\n            opts);\n}\n\n} // namespace tl\n", "meta": {"hexsha": "265fa8510bbbc6cab89568769bca3351cc76bf5d", "size": 25692, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/src/TensorLines.cc", "max_stars_repo_name": "timo-oster/tensor-lines", "max_stars_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/src/TensorLines.cc", "max_issues_repo_name": "timo-oster/tensor-lines", "max_issues_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/src/TensorLines.cc", "max_forks_repo_name": "timo-oster/tensor-lines", "max_forks_repo_head_hexsha": "b4f489452f3ce5b5f48042cc035e53d3fdaa675e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-13T00:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T00:08:09.000Z", "avg_line_length": 34.7658998647, "max_line_length": 82, "alphanum_fraction": 0.5403238362, "num_tokens": 6018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.42917608709806754}}
{"text": "/* ------------------------------------------------------\n *\n * @file marginal.cpp\n *\n * @brief Marginal effects for regression functions\n *\n *\n *//* ----------------------------------------------------------------------- */\n#include <limits>\n#include <dbconnector/dbconnector.hpp>\n#include <modules/shared/HandleTraits.hpp>\n#include <modules/prob/boost.hpp>\n#include <boost/math/distributions.hpp>\n#include <modules/prob/student.hpp>\n#include \"marginal.hpp\"\n\nnamespace madlib {\n\n// Use Eigen\nusing namespace dbal::eigen_integration;\n\nnamespace modules {\n\n// Import names from other MADlib modules\nusing dbal::NoSolutionFoundException;\n\nnamespace regress {\n\ninline double logistic(double x) {\n    return 1. / (1. + std::exp(-x));\n}\n\n/**\n * @brief Helper function that computes the final statistics for the marginal variance\n */\n\nAnyType margins_stateToResult(\n    const Allocator &inAllocator,\n    const ColumnVector &diagonal_of_variance_matrix,\n    const ColumnVector &inmarginal_effects_per_observation,\n    const double numRows) {\n\n    uint16_t n_basis_terms = static_cast<uint16_t>(inmarginal_effects_per_observation.size());\n    MutableNativeColumnVector marginal_effects(\n        inAllocator.allocateArray<double>(n_basis_terms));\n    MutableNativeColumnVector stdErr(\n        inAllocator.allocateArray<double>(n_basis_terms));\n    MutableNativeColumnVector tStats(\n        inAllocator.allocateArray<double>(n_basis_terms));\n    MutableNativeColumnVector pValues(\n        inAllocator.allocateArray<double>(n_basis_terms));\n\n    for (Index i = 0; i < n_basis_terms; ++i) {\n        marginal_effects(i) = inmarginal_effects_per_observation(i) / numRows;\n        stdErr(i) = std::sqrt(diagonal_of_variance_matrix(i));\n        tStats(i) = marginal_effects(i) / stdErr(i);\n\n        // p-values only make sense if numRows > coef.size()\n        if (numRows > n_basis_terms)\n            pValues(i) = 2. * prob::cdf( prob::normal(),\n                                         -std::abs(tStats(i)));\n    }\n\n    // Return all coefficients, standard errors, etc. in a tuple\n    // Note: p-values will return NULL if numRows <= coef.size\n    AnyType tuple;\n    tuple << marginal_effects\n          << stdErr\n          << tStats\n          << (numRows > n_basis_terms? pValues: Null());\n    return tuple;\n}\n// -------------------------------------------------------------------------\n\n\n// ---------------------------------------------------------------------------\n//             Marginal Effects Linear Regression States\n// ---------------------------------------------------------------------------\n\n/**\n * @brief State for marginal effects calculation for logistic regression\n *\n * TransitionState encapsualtes the transition state during the\n * marginal effects calculation for the logistic-regression aggregate function.\n * To the database, the state is exposed as a single DOUBLE PRECISION array,\n * to the C++ code it is a proper object containing scalars and vectors.\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length at least 5, and all elemenets are 0.\n *\n */\ntemplate <class Handle>\nclass MarginsLinregrInteractionState {\n    template <class OtherHandle>\n    friend class MarginsLinregrInteractionState;\n\n  public:\n    MarginsLinregrInteractionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n        rebind(static_cast<uint16_t>(mStorage[1]),\n               static_cast<uint16_t>(mStorage[2]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the marginal variance calculation state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(const Allocator &inAllocator,\n                           const uint16_t inWidthOfX,\n                           const uint16_t inNumBasis) {\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n                                             dbal::DoZero, dbal::ThrowBadAlloc>(\n                arraySize(inWidthOfX, inNumBasis));\n        rebind(inWidthOfX, inNumBasis);\n        widthOfX = inWidthOfX;\n        numBasis = inNumBasis;\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle>\n    MarginsLinregrInteractionState &operator=(\n        const MarginsLinregrInteractionState<OtherHandle> &inOtherState) {\n\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object by copying the intra-iteration\n     *     fields\n     */\n    template <class OtherHandle>\n    MarginsLinregrInteractionState &operator+=(\n        const MarginsLinregrInteractionState<OtherHandle> &inOtherState) {\n\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            widthOfX != inOtherState.widthOfX)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                                   \"states\");\n        numRows += inOtherState.numRows;\n        marginal_effects += inOtherState.marginal_effects;\n        delta += inOtherState.delta;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        numRows = 0;\n        training_data_vcov.fill(0);\n        marginal_effects.fill(0);\n        delta.fill(0);\n    }\n\n  private:\n    static inline size_t arraySize(const uint16_t inWidthOfX,\n                                   const uint16_t inNumBasis) {\n        return 4 + inNumBasis + (inWidthOfX + inNumBasis) * inWidthOfX;\n    }\n\n    /**\n     * @brief Rebind to a new storage array\n     *\n     * @param inWidthOfX The number of independent variables.\n     *\n     */\n    void rebind(uint16_t inWidthOfX, uint16_t inNumBasis) {\n        iteration.rebind(&mStorage[0]);\n        widthOfX.rebind(&mStorage[1]);\n        numBasis.rebind(&mStorage[2]);\n        numRows.rebind(&mStorage[3]);\n        marginal_effects.rebind(&mStorage[4], inNumBasis);\n        training_data_vcov.rebind(&mStorage[4 + inNumBasis], inWidthOfX, inWidthOfX);\n        delta.rebind(&mStorage[4 + inNumBasis + inWidthOfX * inWidthOfX],\n                     inNumBasis, inWidthOfX);\n    }\n    Handle mStorage;\n\n  public:\n    typename HandleTraits<Handle>::ReferenceToUInt32 iteration;\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;\n    typename HandleTraits<Handle>::ReferenceToUInt16 numBasis;\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap marginal_effects;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap training_data_vcov;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap delta;\n};\n// ----------------------------------------------------------------------\n\n/**\n * @brief Perform the marginal effects transition step\n */\nAnyType\nmargins_linregr_int_transition::run(AnyType &args) {\n    // Early return because of an exception has been \"thrown\"\n    // (actually \"warning\") in the previous invocations\n    if (args[0].isNull())\n        return Null();\n    MarginsLinregrInteractionState<MutableArrayHandle<double> > state = args[0];\n    if (args[1].isNull() || args[2].isNull() ||\n            args[3].isNull() || args[4].isNull()) {\n        return args[0];\n    }\n    MappedColumnVector x;\n    try {\n        // an exception is raised in the backend if args[2] contains nulls\n        MappedColumnVector xx = args[1].getAs<MappedColumnVector>();\n        // x is a const reference, we can only rebind to change its pointer\n        x.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    // The following check was added with MADLIB-138.\n    if (!dbal::eigen_integration::isfinite(x)) {\n        //throw std::domain_error(\"Design matrix is not finite.\");\n        warning(\"Design matrix is not finite.\");\n        return Null();\n     }\n\n    MappedColumnVector beta = args[2].getAs<MappedColumnVector>();\n\n    Matrix J_trans = args[4].getAs<MappedMatrix>();\n    J_trans.transposeInPlace(); // we actually pass-in J but transpose since\n                                // we only require J^T in our equations\n\n    if (state.numRows == 0) {\n        if (x.size() > std::numeric_limits<uint16_t>::max()) {\n            //throw std::domain_error(\"Number of independent variables cannot be \"\n            //                        \"larger than 65535.\");\n            warning(\"Number of independent variables cannot be larger than 65535.\");\n            return Null();\n        }\n        state.initialize(*this,\n                         static_cast<uint16_t>(beta.size()),\n                         static_cast<uint16_t>(J_trans.rows()));\n        Matrix training_data_vcov = args[3].getAs<MappedMatrix>();\n        state.training_data_vcov = training_data_vcov;\n    }\n\n    // Now do the transition step\n    state.numRows++;\n\n    // compute marginal effects and delta using 1st and 2nd derivatives\n    state.marginal_effects += J_trans * beta;\n    state.delta += J_trans;\n    return state;\n}\n\n\n/**\n * @brief Marginal effects: Merge transition states\n */\nAnyType\nmargins_linregr_int_merge::run(AnyType &args) {\n    // In case the aggregator should be terminated because\n    // an exception has been \"thrown\" in the transition function\n    if (args[0].isNull() || args[1].isNull())\n        return Null();\n    MarginsLinregrInteractionState<MutableArrayHandle<double> > stateLeft = args[0];\n    MarginsLinregrInteractionState<ArrayHandle<double> > stateRight = args[1];\n    // We first handle the trivial case where this function is called with one\n    // of the states being the initial state\n    if (stateLeft.numRows == 0)\n        return stateRight;\n    else if (stateRight.numRows == 0)\n        return stateLeft;\n\n    // Merge states together and return\n    stateLeft += stateRight;\n    return stateLeft;\n}\n\n/**\n * @brief Marginal effects: Final step\n */\nAnyType\nmargins_linregr_int_final::run(AnyType &args) {\n    // In case the aggregator should be terminated because\n    // an exception has been \"thrown\" in the transition function\n    if (args[0].isNull())\n        return Null();\n    // We request a mutable object.\n    // Depending on the backend, this might perform a deep copy.\n    MarginsLinregrInteractionState<ArrayHandle<double> > state = args[0];\n    // Aggregates that haven't seen any data just return Null.\n    if (state.numRows == 0)\n        return Null();\n\n    // Variance of the marginal effects (computed by delta method)\n    Matrix variance;\n    variance = state.delta * state.training_data_vcov;\n    // we only need the diagonal elements of the variance, so we perform a dot\n    // product of each row with itself to compute each diagonal element.\n    ColumnVector variance_diagonal =\n        variance.cwiseProduct(state.delta).rowwise().sum() / static_cast<double>(state.numRows * state.numRows);\n\n    // Computing the marginal effects\n    return margins_stateToResult(*this, variance_diagonal,\n                                 state.marginal_effects, static_cast<double>(state.numRows));\n}\n\n// ---------------------------------------------------------------------------\n//             Marginal Effects Logistic Regression States\n// ---------------------------------------------------------------------------\n/**\n * @brief State for marginal effects calculation for logistic regression\n *\n * TransitionState encapsualtes the transition state during the\n * marginal effects calculation for the logistic-regression aggregate function.\n * To the database, the state is exposed as a single DOUBLE PRECISION array,\n * to the C++ code it is a proper object containing scalars and vectors.\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length at least 5, and all elemenets are 0.\n *\n */\ntemplate <class Handle>\nclass MarginsLogregrInteractionState {\n    template <class OtherHandle>\n    friend class MarginsLogregrInteractionState;\n\n  public:\n    MarginsLogregrInteractionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n\n        rebind(static_cast<uint16_t>(mStorage[1]),\n               static_cast<uint16_t>(mStorage[2]),\n               static_cast<uint16_t>(mStorage[3]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the marginal variance calculation state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(const Allocator &inAllocator,\n                           const uint16_t inWidthOfX,\n                           const uint16_t inNumBasis,\n                           const uint16_t inNumCategoricals) {\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n                                             dbal::DoZero, dbal::ThrowBadAlloc>(\n                arraySize(inWidthOfX, inNumBasis, inNumCategoricals));\n        rebind(inWidthOfX, inNumBasis, inNumCategoricals);\n        widthOfX = inWidthOfX;\n        numBasis = inNumBasis;\n        numCategoricalVarsInSubset = inNumCategoricals;\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle>\n    MarginsLogregrInteractionState &operator=(\n        const MarginsLogregrInteractionState<OtherHandle> &inOtherState) {\n\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object by copying the intra-iteration\n     *     fields\n     */\n    template <class OtherHandle>\n    MarginsLogregrInteractionState &operator+=(\n        const MarginsLogregrInteractionState<OtherHandle> &inOtherState) {\n\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            widthOfX != inOtherState.widthOfX)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                                   \"states\");\n\n        numRows += inOtherState.numRows;\n        marginal_effects += inOtherState.marginal_effects;\n        delta += inOtherState.delta;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        numRows = 0;\n        marginal_effects.fill(0);\n        categorical_basis_indices.fill(0);\n        training_data_vcov.fill(0);\n        delta.fill(0);\n    }\n\n  private:\n    static inline size_t arraySize(const uint16_t inWidthOfX,\n                                   const uint16_t inNumBasis,\n                                   const uint16_t inNumCategoricals) {\n        return 5 + inNumBasis + inNumCategoricals + (inWidthOfX + inNumBasis) * inWidthOfX;\n    }\n\n    /**\n     * @brief Rebind to a new storage array\n     *\n     * @param inWidthOfX The number of independent variables.\n     *\n     */\n    void rebind(uint16_t inWidthOfX, uint16_t inNumBasis, uint16_t inNumCategoricals) {\n        iteration.rebind(&mStorage[0]);\n        widthOfX.rebind(&mStorage[1]);\n        numBasis.rebind(&mStorage[2]);\n        numCategoricalVarsInSubset.rebind(&mStorage[3]);\n        numRows.rebind(&mStorage[4]);\n        marginal_effects.rebind(&mStorage[5], inNumBasis);\n        training_data_vcov.rebind(&mStorage[5 + inNumBasis], inWidthOfX, inWidthOfX);\n        delta.rebind(&mStorage[5 + inNumBasis + inWidthOfX * inWidthOfX],\n                     inNumBasis, inWidthOfX);\n        if (inNumCategoricals > 0)\n            categorical_basis_indices.rebind(&mStorage[5 + inNumBasis +\n                                            (inWidthOfX + inNumBasis) * inWidthOfX],\n                                            inNumCategoricals);\n    }\n    Handle mStorage;\n\n  public:\n\n    typename HandleTraits<Handle>::ReferenceToUInt32 iteration;\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;\n    typename HandleTraits<Handle>::ReferenceToUInt16 numBasis;\n    typename HandleTraits<Handle>::ReferenceToUInt16 numCategoricalVarsInSubset;\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap marginal_effects;\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap categorical_basis_indices;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap training_data_vcov;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap delta;\n};\n// ----------------------------------------------------------------------\n\n/**\n * @brief Perform the marginal effects transition step\n */\nAnyType\nmargins_logregr_int_transition::run(AnyType &args) {\n    // Early return because of an exception has been \"thrown\"\n    // (actually \"warning\") in the previous invocations\n    if (args[0].isNull())\n        return Null();\n    MarginsLogregrInteractionState<MutableArrayHandle<double> > state = args[0];\n    if (args[1].isNull() || args[2].isNull() ||\n            args[3].isNull() || args[4].isNull()) {\n        return args[0];\n    }    MappedColumnVector f;\n    try {\n        // an exception is raised in the backend if args[2] contains nulls\n        MappedColumnVector xx = args[1].getAs<MappedColumnVector>();\n        // x is a const reference, we can only rebind to change its pointer\n        f.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    // The following check was added with MADLIB-138.\n    if (!dbal::eigen_integration::isfinite(f)) {\n        //throw std::domain_error(\"Design matrix is not finite.\");\n        warning(\"Design matrix is not finite.\");\n        return Null();\n    }\n\n    // beta is the coefficient vector from logistic regression\n    MappedColumnVector beta = args[2].getAs<MappedColumnVector>();\n\n    // basis_indices represents the indices (from beta) of which we want to\n    // compute the marginal effect. We don't need to compute the ME for all\n    // variables, thus basis_indices could be a subset of all indices.\n    MappedColumnVector basis_indices = args[4].getAs<MappedColumnVector>();\n\n    // below symbols match the ones used in the design doc\n    const uint16_t N = static_cast<uint16_t>(beta.size());\n    const uint16_t M = static_cast<uint16_t>(basis_indices.size());\n    assert(N >= M);\n\n    Matrix J;  // J: N * M\n    if (args[5].isNull()){\n        J = Matrix::Zero(N, M);\n        for (Index i = 0; i < M; ++i)\n            J(static_cast<Index>(basis_indices(i)), i) = 1;\n    } else{\n        J = args[5].getAs<MappedMatrix>();\n    }\n    assert(J.rows() == N && J.cols() == M);\n\n    MappedColumnVector categorical_indices;\n    uint16_t numCategoricalVars = 0;\n\n    if (!args[6].isNull()) {\n        // categorical_indices represents which indices (from beta) are\n        // categorical variables\n        try {\n            MappedColumnVector xx = args[6].getAs<MappedColumnVector>();\n            categorical_indices.rebind(xx.memoryHandle(), xx.size());\n        } catch (const ArrayWithNullException &e) {\n             //throw std::runtime_error(\"The categorical indices contain NULL values\");\n             warning(\"The categorical indices contain NULL values\");\n             return Null();\n        }\n        numCategoricalVars = static_cast<uint16_t>(categorical_indices.size());\n    }\n\n    if (state.numRows == 0) {\n        if (f.size() > std::numeric_limits<uint16_t>::max()) {\n            //throw std::domain_error(\"Number of independent variables cannot be \"\n            //                        \"larger than 65535.\");\n            warning(\"Number of independent variables cannot be larger than 65535.\");\n            return Null();\n        }\n        std::vector<uint16_t> tmp_cat_basis_indices;\n        if (numCategoricalVars > 0){\n            // find which of the variables in basis_indices are categorical\n            // and store only the indices for these variables in our state\n            for (Index i = 0; i < basis_indices.size(); ++i){\n                for (Index j = 0; j < categorical_indices.size(); ++j){\n                    if (basis_indices(i) == categorical_indices(j)){\n                        tmp_cat_basis_indices.push_back(static_cast<uint16_t>(i));\n                        continue;\n                    }\n                }\n            }\n            state.numCategoricalVarsInSubset = static_cast<uint16_t>(tmp_cat_basis_indices.size());\n        }\n        state.initialize(*this,\n                         static_cast<uint16_t>(N),\n                         static_cast<uint16_t>(M),\n                         static_cast<uint16_t>(state.numCategoricalVarsInSubset));\n\n        Matrix training_data_vcov = args[3].getAs<MappedMatrix>();\n        state.training_data_vcov = training_data_vcov;\n\n        if (state.numCategoricalVarsInSubset > 0){\n            for (int i=0; i < state.numCategoricalVarsInSubset; ++i){\n                state.categorical_basis_indices(i) = tmp_cat_basis_indices[i];\n            }\n        }\n    }\n\n    // Now do the transition step\n    state.numRows++;\n    double f_beta = dot(f, beta);\n    double p = std::exp(f_beta)/ (1 + std::exp(f_beta));\n\n    // compute marginal effects and delta using 1st and 2nd derivatives\n    ColumnVector J_trans_beta;\n    J_trans_beta = trans(J) * beta;\n    ColumnVector curr_margins = J_trans_beta * p * (1 - p);\n\n    Matrix curr_delta;\n    curr_delta = p * (1 - p) * (trans(J) +\n                                (1 - 2 * p) * J_trans_beta * trans(f));\n\n    // margins and delta using discrete differences for categoricals variables\n\n    // f_set_mat and f_unset_mat are matrices where each row corresponds to a\n    //  categorical basis variable and the columns correspond to all terms\n    // (basis and interaction)\n    Matrix f_set_mat;  // numCategoricalVarsInSubset x N\n    Matrix f_unset_mat;  // numCategoricalVarsInSubset x N\n    if (!args[7].isNull() && !args[8].isNull()){\n        // the matrix is read in column-order but passed in row-order\n        f_set_mat = args[7].getAs<MappedMatrix>();\n        f_set_mat.transposeInPlace();\n\n        f_unset_mat = args[8].getAs<MappedMatrix>();\n        f_unset_mat.transposeInPlace();\n    }\n\n    // PERFORMANCE TWEAK: for the no interaction case, f_set_mat and f_unset_mat\n    // only need column entries for the categorical variables (others are same\n    // as f). Since, passing a smaller matrix into the transition function is\n    // faster, for the no interaction case, we don't need to input the whole\n    // matrix into this function. For the interaction case, since it is unknown\n    // which indices have interaction, we require entries for all columns in the\n    // matrices.\n    bool no_interactions = (f_set_mat.cols() < N);\n    for (Index i = 0; i < state.numCategoricalVarsInSubset; ++i) {\n        // Note: categorical_indices are assumed to be zero-based\n        ColumnVector f_set;\n        ColumnVector f_unset;\n        ColumnVector shortened_f_set = f_set_mat.row(i);\n        ColumnVector shortened_f_unset = f_unset_mat.row(i);\n\n        if (no_interactions){\n            f_set = f;\n            f_unset = f;\n            for (Index j=0; j < shortened_f_set.size(); ++j){\n                f_set(static_cast<Index>(categorical_indices(j))) = shortened_f_set(j);\n                f_unset(static_cast<Index>(categorical_indices(j))) = shortened_f_unset(j);\n            }\n        } else {\n            f_set = shortened_f_set;\n            f_unset = shortened_f_unset;\n        }\n        double p_set = logistic(dot(f_set, beta));\n        double p_unset = logistic(dot(f_unset, beta));\n\n        curr_margins(static_cast<uint16_t>(state.categorical_basis_indices(i))) = p_set - p_unset;\n        curr_delta.row(static_cast<uint16_t>(state.categorical_basis_indices(i))) = (\n            p_set * (1 - p_set) * f_set - p_unset * (1 - p_unset) * f_unset);\n    }\n    state.marginal_effects += curr_margins;\n    state.delta += curr_delta;\n    return state;\n}\n\n\n/**\n * @brief Marginal effects: Merge transition states\n */\nAnyType\nmargins_logregr_int_merge::run(AnyType &args) {\n    // In case the aggregator should be terminated because\n    // an exception has been \"thrown\" in the transition function\n    if (args[0].isNull() || args[1].isNull())\n        return Null();\n    MarginsLogregrInteractionState<MutableArrayHandle<double> > stateLeft = args[0];\n    MarginsLogregrInteractionState<ArrayHandle<double> > stateRight = args[1];\n    // We first handle the trivial case where this function is called with one\n    // of the states being the initial state\n    if (stateLeft.numRows == 0)\n        return stateRight;\n    else if (stateRight.numRows == 0)\n        return stateLeft;\n\n    // Merge states together and return\n    stateLeft += stateRight;\n    return stateLeft;\n}\n\n/**\n * @brief Marginal effects: Final step\n */\nAnyType\nmargins_logregr_int_final::run(AnyType &args) {\n    // In case the aggregator should be terminated because\n    // an exception has been \"thrown\" in the transition function\n    if (args[0].isNull())\n        return Null();\n    // We request a mutable object.\n    // Depending on the backend, this might perform a deep copy.\n    MarginsLogregrInteractionState<MutableArrayHandle<double> > state = args[0];\n    // Aggregates that haven't seen any data just return Null.\n    if (state.numRows == 0)\n        return Null();\n\n    // Variance for marginal effects according to the delta method\n    Matrix variance;\n    variance = state.delta * state.training_data_vcov;\n\n    // we only need the diagonal elements of the variance, so we perform a dot\n    // product of each row with state.delta to compute each diagonal element.\n    // We divide by numRows^2 since we need the average variance\n    ColumnVector variance_diagonal =\n        variance.cwiseProduct(state.delta).rowwise().sum() / static_cast<double>(state.numRows * state.numRows);\n\n    // Computing the final results\n    return margins_stateToResult(*this, variance_diagonal,\n                                 state.marginal_effects, static_cast<double>(state.numRows));\n}\n// ------------------------ End of Logistic Marginal ---------------------------\n\n// ---------------------------------------------------------------------------\n//             Marginal Effects Multilogistic Regression\n// ---------------------------------------------------------------------------\n/**\n * @brief State for marginal effects calculation for multilogistic regression\n *\n * TransitionState encapsualtes the transition state during the\n * marginal effects calculation for the logistic-regression aggregate function.\n * To the database, the state is exposed as a single DOUBLE PRECISION array,\n * to the C++ code it is a proper object containing scalars and vectors.\n *\n * Note: We assume that the DOUBLE PRECISION array is initialized by the\n * database with length at least 5, and all elemenets are 0.\n *\n */\ntemplate <class Handle>\nclass MarginsMLogregrInteractionState {\n    template <class OtherHandle>\n    friend class MarginsMLogregrInteractionState;\n\n  public:\n    MarginsMLogregrInteractionState(const AnyType &inArray)\n        : mStorage(inArray.getAs<Handle>()) {\n\n        rebind(static_cast<uint16_t>(mStorage[0]),\n               static_cast<uint16_t>(mStorage[1]),\n               static_cast<uint16_t>(mStorage[2]),\n               static_cast<uint16_t>(mStorage[3]));\n    }\n\n    /**\n     * @brief Convert to backend representation\n     *\n     * We define this function so that we can use State in the\n     * argument list and as a return type.\n     */\n    inline operator AnyType() const {\n        return mStorage;\n    }\n\n    /**\n     * @brief Initialize the marginal variance calculation state.\n     *\n     * This function is only called for the first iteration, for the first row.\n     */\n    inline void initialize(const Allocator &inAllocator,\n                           const uint16_t inWidthOfX,\n                           const uint16_t inNumCategories,\n                           const uint16_t inNumBasis,\n                           const uint16_t inNumCategoricalVars) {\n        mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,\n                                             dbal::DoZero, dbal::ThrowBadAlloc>(\n                arraySize(inWidthOfX, inNumCategories, inNumBasis, inNumCategoricalVars));\n        rebind(inWidthOfX,  inNumCategories, inNumBasis, inNumCategoricalVars);\n        widthOfX = inWidthOfX;\n        numCategories = inNumCategories;\n        numBasis = inNumBasis;\n        numCategoricalVarsInSubset = inNumCategoricalVars;\n    }\n\n    /**\n     * @brief We need to support assigning the previous state\n     */\n    template <class OtherHandle>\n    MarginsMLogregrInteractionState &operator=(\n        const MarginsMLogregrInteractionState<OtherHandle> &inOtherState) {\n\n        for (size_t i = 0; i < mStorage.size(); i++)\n            mStorage[i] = inOtherState.mStorage[i];\n        return *this;\n    }\n\n    /**\n     * @brief Merge with another State object by copying the intra-iteration\n     *     fields\n     */\n    template <class OtherHandle>\n    MarginsMLogregrInteractionState &operator+=(\n        const MarginsMLogregrInteractionState<OtherHandle> &inOtherState) {\n\n        if (mStorage.size() != inOtherState.mStorage.size() ||\n            widthOfX != inOtherState.widthOfX)\n            throw std::logic_error(\"Internal error: Incompatible transition \"\n                                   \"states\");\n\n        numRows += inOtherState.numRows;\n        marginal_effects += inOtherState.marginal_effects;\n        delta += inOtherState.delta;\n        return *this;\n    }\n\n    /**\n     * @brief Reset the inter-iteration fields.\n     */\n    inline void reset() {\n        numRows = 0;\n        marginal_effects.fill(0);\n        categorical_basis_indices.fill(0);\n        training_data_vcov.fill(0);\n        delta.fill(0);\n    }\n\n  private:\n    static inline size_t arraySize(const uint16_t inWidthOfX,\n                                   const uint16_t inNumCategories,\n                                   const uint16_t inNumBasis,\n                                   const uint16_t inNumCategoricalVars) {\n        return 5 + (inNumCategories - 1) * (inNumBasis +\n                    inNumBasis*inWidthOfX*(inNumCategories - 1) +\n                    inWidthOfX*inWidthOfX*(inNumCategories - 1)) +\n                inNumCategoricalVars;\n    }\n\n    /**\n     * @brief Rebind to a new storage array\n     *\n     * @param inWidthOfX The number of independent variables.\n     *\n     */\n    void rebind(const uint16_t inWidthOfX,\n                const uint16_t inNumCategories,\n                const uint16_t inNumBasis,\n                const uint16_t inNumCategoricalVars) {\n\n        const uint16_t & L = inNumCategories;\n        const uint16_t & N = inWidthOfX;\n        const uint16_t & M = inNumBasis;\n\n        widthOfX.rebind(&mStorage[0]);\n        numCategories.rebind(&mStorage[1]);\n        numBasis.rebind(&mStorage[2]);\n        numCategoricalVarsInSubset.rebind(&mStorage[3]);\n        numRows.rebind(&mStorage[4]);\n\n        if (L == 0) { return; }\n\n        marginal_effects.rebind(&mStorage[5], M, L-1);\n\n        int current_length = 5 + M * (L - 1);\n\n        training_data_vcov.rebind(&mStorage[current_length], N*(L-1), N*(L-1));\n        current_length += N * (L - 1) * N * (L - 1);\n\n        delta.rebind(&mStorage[current_length], M*(L-1), N*(L-1));\n        current_length += N * (L - 1) * M * (L - 1);\n\n        if (inNumCategoricalVars > 0)\n            categorical_basis_indices.rebind(&mStorage[static_cast<uint16_t>(current_length)], inNumCategoricalVars);\n    }\n    Handle mStorage;\n\n  public:\n    // symbols in comments correspond to the design document\n    typename HandleTraits<Handle>::ReferenceToUInt16 widthOfX;       // N\n    typename HandleTraits<Handle>::ReferenceToUInt16 numCategories;  // L\n    typename HandleTraits<Handle>::ReferenceToUInt16 numBasis;       // M\n    typename HandleTraits<Handle>::ReferenceToUInt16 numCategoricalVarsInSubset;\n    typename HandleTraits<Handle>::ReferenceToUInt64 numRows;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap marginal_effects; // ME\n    typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap categorical_basis_indices;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap training_data_vcov;\n    typename HandleTraits<Handle>::MatrixTransparentHandleMap delta;   // S\n};\n// ----------------------------------------------------------------------\n\nnamespace {\ninline Index\nreindex(Index outer, Index inner, Index block) { return outer * block + inner; }\n}\n\n/**\n * @brief Perform the marginal effects transition step\n */\nAnyType\nmargins_mlogregr_int_transition::run(AnyType &args) {\n    // Early return because of an exception has been \"thrown\"\n    // (actually \"warning\") in the previous invocations\n    if (args[0].isNull())\n        return Null();\n    MarginsMLogregrInteractionState<MutableArrayHandle<double> > state = args[0];\n    if (args[1].isNull() || args[2].isNull() || args[3].isNull() ||\n        args[4].isNull()) {\n        return args[0];\n    }\n\n    MappedColumnVector f;\n    try {\n        // an exception is raised in the backend if args[1] contains nulls\n        MappedColumnVector xx = args[1].getAs<MappedColumnVector>();\n        // x is a const reference, we can only rebind to change its pointer\n        f.rebind(xx.memoryHandle(), xx.size());\n    } catch (const ArrayWithNullException &e) {\n        return args[0];\n    }\n\n    // The following check was added with MADLIB-138.\n    if (!dbal::eigen_integration::isfinite(f)) {\n        //throw std::domain_error(\"Design matrix is not finite.\");\n        warning(\"Design matrix is not finite.\");\n        return Null();\n    }\n\n    // coefficients are arranged in a matrix\n    MappedMatrix beta = args[2].getAs<MappedMatrix>();  // beta: N x (L - 1)\n\n    // basis_indices represents the indices (from beta) of which we want to\n    // compute the marginal effect. We don't need to compute the ME for all\n    // variables, thus basis_indices could be a subset of all indices.\n    MappedColumnVector basis_indices = args[4].getAs<MappedColumnVector>();\n\n    // all variable symbols correspond to the design document\n    const uint16_t N = static_cast<uint16_t>(beta.rows());\n    const uint16_t M = static_cast<uint16_t>(basis_indices.size());\n    assert(N >= M);\n\n    Matrix J;  // J: N x M\n    if (args[5].isNull()){\n        J = Matrix::Zero(N, M);\n        for (Index i = 0; i < M; ++i)\n            J(static_cast<Index>(basis_indices(i)), i) = 1;\n    } else{\n        J = args[5].getAs<MappedMatrix>();\n    }\n    assert(J.rows() == N && J.cols() == M);\n\n    MappedColumnVector categorical_indices;\n    uint16_t numCategoricalVars = 0;\n\n    if (!args[6].isNull()) {\n        // categorical_indices represents which indices (from beta) are\n        // categorical variables\n        try {\n            MappedColumnVector xx = args[6].getAs<MappedColumnVector>();\n            categorical_indices.rebind(xx.memoryHandle(), xx.size());\n        } catch (const ArrayWithNullException &e) {\n             //throw std::runtime_error(\"The categorical indices contain NULL values\");\n             warning(\"The categorical indices contain NULL values\");\n             return Null();\n        }\n        numCategoricalVars = static_cast<uint16_t>(categorical_indices.size());\n    }\n\n    if (state.numRows == 0) {\n        if (f.size() > std::numeric_limits<uint16_t>::max()) {\n            //throw std::domain_error(\"Number of independent variables cannot be \"\n            //                        \"larger than 65535.\");\n            warning(\"Number of independent variables cannot be larger than 65535.\");\n            return Null();\n        }\n        std::vector<uint16_t> tmp_cat_basis_indices;\n        if (numCategoricalVars > 0){\n            // find which of the variables in basis_indices are categorical\n            // and store only the indices for these variables in our state\n            for (Index i = 0; i < basis_indices.size(); ++i){\n                for (Index j = 0; j < categorical_indices.size(); ++j){\n                    if (basis_indices(i) == categorical_indices(j)){\n                        tmp_cat_basis_indices.push_back(static_cast<uint16_t>(i));\n                        continue;\n                    }\n                }\n            }\n            state.numCategoricalVarsInSubset = static_cast<uint16_t>(tmp_cat_basis_indices.size());\n        }\n        state.initialize(*this,\n                         static_cast<uint16_t>(J.rows()),\n                         static_cast<uint16_t>(beta.cols() + 1),\n                         static_cast<uint16_t>(J.cols()),\n                         static_cast<uint16_t>(state.numCategoricalVarsInSubset));\n\n        Matrix training_data_vcov = args[3].getAs<MappedMatrix>();\n        state.training_data_vcov = training_data_vcov;\n        if (state.numCategoricalVarsInSubset > 0){\n            for (int i=0; i < state.numCategoricalVarsInSubset; ++i){\n                state.categorical_basis_indices(i) = tmp_cat_basis_indices[i];\n            }\n        }\n    }\n\n    state.numRows++;\n\n    // all variable symbols correspond to the design document\n    const uint16_t & L = state.numCategories;\n    ColumnVector prob(trans(beta) * f);\n    Matrix J_trans_beta(trans(J) * beta);\n\n    // Calculate the odds ratio\n    prob = prob.array().exp();\n    double prob_sum = prob.sum();\n    prob = prob / (1 + prob_sum);\n\n    ColumnVector JBP(J_trans_beta * prob);\n    Matrix curr_margins = J_trans_beta * prob.asDiagonal() - JBP * trans(prob);\n\n    // compute delta using 2nd derivatives\n    // delta matrix is 2-D of size (L-1)M x (L-1)N:\n    //      row_index = [0, (L-1)M), col_index = [0, (L-1)N)\n    // row_index(m, l) = m * (L-1) + l\n    // col_index(n, l1) = n * (L-1) + l1\n    Index row_index, col_index;\n    int delta_l_l1;\n    for (int m = 0; m < M; m++){\n        // Skip the categorical variables\n        if (state.numCategoricalVarsInSubset > 0) {\n            bool is_categorical = false;\n            for(int i = 0; i < state.categorical_basis_indices.size(); i++)\n                if (m == state.categorical_basis_indices(i)) {\n                    is_categorical = true;\n                    break;\n                }\n             if (is_categorical)\n                continue;\n        }\n\n        for (int l=0; l < (L-1); l++){\n            row_index = reindex(m, l, L-1);\n            for (int n=0; n < N; n++){\n                for (int l1=0; l1 < (L-1); l1++){\n                    delta_l_l1 = (l==l1) ? 1 : 0;\n                    col_index = reindex(n, l1, L-1);\n                    state.delta(row_index, col_index) +=\n                        f(n)*(delta_l_l1 - prob(l1)) * curr_margins(m, l) +\n                        prob(l) * (delta_l_l1 * J(n, m) -\n                                   f(n) * curr_margins(m, l1) -\n                                   prob(l1) * J(n, m));\n                }\n            }\n        }\n    }\n\n    // update marginal effects and delta using discrete differences just for\n    // categorical variables\n    Matrix f_set_mat;   // numCategoricalVarsInSubset * N\n    Matrix f_unset_mat; // numCategoricalVarsInSubset * N\n    // the above matrices contain the f_set and f_unset for all categorical variables\n    if (!args[7].isNull() && !args[8].isNull()){\n        // the matrix is read in column-order but passed in row-order\n        f_set_mat = args[7].getAs<MappedMatrix>();\n        f_set_mat.transposeInPlace();\n\n        f_unset_mat = args[8].getAs<MappedMatrix>();\n        f_unset_mat.transposeInPlace();\n    }\n\n    // PERFORMANCE TWEAK: for the no interaction case, f_set_mat and f_unset_mat\n    // only need column entries for the categorical variables (others are same\n    // as f). Since, passing a smaller matrix into the transition function is\n    // faster, for the no interaction case, we don't need to input the whole\n    // matrix into this function. For the interaction case, since it is unknown\n    // which indices have interaction, we require entries for all columns in the\n    // matrices.\n    bool no_interactions = (f_set_mat.cols() < N);\n    for (Index i = 0; i < state.numCategoricalVarsInSubset; ++i) {\n        // Note: categorical_indices are assumed to be zero-based\n        ColumnVector f_set;\n        ColumnVector f_unset;\n        ColumnVector shortened_f_set = f_set_mat.row(i);\n        ColumnVector shortened_f_unset = f_unset_mat.row(i);\n\n        if (no_interactions){\n            f_set = f;\n            f_unset = f;\n            for (Index j=0; j < shortened_f_set.size(); ++j){\n                f_set(static_cast<Index>(categorical_indices(j))) = shortened_f_set(j);\n                f_unset(static_cast<Index>(categorical_indices(j))) = shortened_f_unset(j);\n            }\n        } else {\n            f_set = shortened_f_set;\n            f_unset = shortened_f_unset;\n        }\n\n        RowVector p_set(trans(f_set) * beta);\n        {\n            p_set = p_set.array().exp();\n            double p_sum = p_set.sum();\n            p_set = p_set / (1 + p_sum);\n        }\n\n        RowVector p_unset(trans(f_unset) * beta);\n        {\n            p_unset = p_unset.array().exp();\n            double p_sum = p_unset.sum();\n            p_unset = p_unset / (1 + p_sum);\n        }\n        // Compute the marginal effect using difference method\n        curr_margins.row(static_cast<uint16_t>(state.categorical_basis_indices(i))) = p_set - p_unset;\n\n        // Compute the delta using difference method\n        int m = static_cast<uint16_t>(state.categorical_basis_indices(i));\n        for (int l = 0; l < L - 1; l++) {\n            row_index = reindex(m, l, L - 1);\n            for (int n = 0; n < N; n++) {\n                for (int l1 = 0; l1 < L - 1; l1++) {\n                    double delta = - p_set(l) * p_set(l1) * f_set(n) + p_unset(l) * p_unset(l1) * f_unset(n);\n                    if (l1 == l)\n                        delta += p_set(l) * f_set(n) - p_unset(l) * f_unset(n);\n                    col_index = reindex(n, l1, L - 1);\n                    state.delta(row_index, col_index) += delta;\n                }\n            }\n        }\n\n    }\n    state.marginal_effects += curr_margins;\n    return state;\n}\n\n\n/**\n * @brief Marginal effects: Merge transition states\n */\nAnyType\nmargins_mlogregr_int_merge::run(AnyType &args) {\n    // In case the aggregator should be terminated because\n    // an exception has been \"thrown\" in the transition function\n    if (args[0].isNull() || args[1].isNull())\n        return Null();\n    MarginsMLogregrInteractionState<MutableArrayHandle<double> > stateLeft = args[0];\n    MarginsMLogregrInteractionState<ArrayHandle<double> > stateRight = args[1];\n    // We first handle the trivial case where this function is called with one\n    // of the states being the initial state\n    if (stateLeft.numRows == 0)\n        return stateRight;\n    else if (stateRight.numRows == 0)\n        return stateLeft;\n\n    // Merge states together and return\n    stateLeft += stateRight;\n    return stateLeft;\n}\n\n/**\n * @brief Marginal effects: Final step\n */\nAnyType\nmargins_mlogregr_int_final::run(AnyType &args) {\n    // In case the aggregator should be terminated because\n    // an exception has been \"thrown\" in the transition function\n    if (args[0].isNull())\n        return Null();\n    // We request a mutable object.\n    // Depending on the backend, this might perform a deep copy.\n    MarginsMLogregrInteractionState<MutableArrayHandle<double> > state = args[0];\n    // Aggregates that haven't seen any data just return Null.\n    if (state.numRows == 0)\n        return Null();\n\n    state.marginal_effects /= static_cast<double>(state.numRows);\n    Matrix marginal_effects_trans = trans(state.marginal_effects);\n    AnyType tuple;\n    tuple << marginal_effects_trans;\n\n    // Variance for marginal effects according to the delta method\n    Matrix variance(state.delta * state.training_data_vcov);\n    // // we only need the diagonal elements of the variance, so we perform a dot\n    // // product of each row with itself to compute each diagonal element.\n    // // We divide by numRows^2 since we need the average variance\n    Matrix std_err = variance.cwiseProduct(state.delta).rowwise().sum() / static_cast<double>(state.numRows * state.numRows);\n    std_err = std_err.array().sqrt();\n    std_err.resize(state.numCategories-1, state.numBasis);\n    tuple << std_err;\n\n    Matrix t_stats = marginal_effects_trans.cwiseQuotient(std_err);\n    tuple << t_stats;\n\n    // Note: p-values will return NULL if numRows <= coef.size\n    if (state.numRows > state.numBasis) {\n        MutableNativeMatrix p_values(\n                this->allocateArray<double>(state.numBasis * (state.numCategories-1)),\n                state.numCategories-1,\n                state.numBasis);\n        for (Index l = 0; l < p_values.rows(); l ++) {\n            for (Index m = 0; m < p_values.cols(); m ++) {\n                p_values(l,m) = 2. * prob::cdf(prob::normal(), -std::abs(t_stats(l,m)));\n            }\n        }\n        tuple << static_cast<Matrix>(p_values);\n    }\n\n    return tuple;\n}\n// ------------------------ End of Logistic Marginal ---------------------------\n\n\n} // namespace regress\n\n} // namespace modules\n\n} // namespace madlib\n", "meta": {"hexsha": "f3246ed8e1f4c615991c62c384e2a39901e0b2ac", "size": 45512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/regress/marginal.cpp", "max_stars_repo_name": "fmcquillan99/apache-madlib", "max_stars_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T07:44:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:45:18.000Z", "max_issues_repo_path": "src/modules/regress/marginal.cpp", "max_issues_repo_name": "fmcquillan99/apache-madlib", "max_issues_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-09-06T05:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-06T05:50:17.000Z", "max_forks_repo_path": "src/modules/regress/marginal.cpp", "max_forks_repo_name": "fmcquillan99/apache-madlib", "max_forks_repo_head_hexsha": "e2dea62d1eadc7f662f2d926c71f42332f414ca0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T20:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T20:50:13.000Z", "avg_line_length": 38.6022052587, "max_line_length": 125, "alphanum_fraction": 0.6170899982, "num_tokens": 10541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4291760805280773}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n#include <chrono>\n#include <ctime>\n#include \"helper_functions.h\"\n#include \"solve_network.h\"\n#include \"solve_dde.h\"\n#include \"backprop.h\"\n#include \"numerical_gradient.h\"\n#include \"katana_get_params.hh\"\n#include \"global_constants.h\"\n\n\nusing namespace std;\nusing namespace arma;\nusing namespace globalconstants;\n\nint main(int argc, char const *argv[])\n{\n\t// for cpu time measuring\n\tclock_t start_overall = clock();\n\tdouble cumulative_solve_time = 0.0;\n\tdouble cumulative_backprop_time = 0.0;\n\t\n\tarma_rng::set_seed_random();\n\t\n\t\n\t// ### ### ### --- OPTIONS --- ### ### ###\n\t\n\t// file name of the text file where parameters and results will be saved\n\tstring results_file_name = katana::getCmdOption(argv, argv + argc, \"-filename\", \"results.txt\");\n\t// print message to results file\n\tstring print_msg = \"Simulation of the deep learning delay system.\";\n\t\n\t// task, possible options are \"MNIST\", \"Fashion-MNIST\", \"CIFAR-10\", \"SVHN\"\n\tstring task = \"Fashion-MNIST-denoising\";\n\t// modify global_constants.h accordingly!\n\t\n\t// number of example images to save\n\tint save_examples = katana::getCmdOption(argv, argv + argc, \"-save_examples\", 0);\n\t\n\t// print weights (and diagonals) after each training epoch to text files in weights folder\n\tbool print_weights_to_file = false;\n\t\n\t// record data for time-signal video (or plot), only for MNIST or Fashion-MNIST\n\tbool record_data = katana::getCmdOption_bool(argv, argv + argc, \"-record_data\", false);\n\tint number_of_examples = katana::getCmdOption(argv, argv + argc, \"-record_examples\", 10);\n\t\n\t// If the following option is true, the program will not train the machine learning system.\n\t// Instead it will just choose diag indices n_prime according to the given paramters\n\t// and save them in the text file diag.txt. This will be done 6 times, i.e. the text file\n\t// will contain 6 lines of diag indices, which can be used for 6-fold cross validation\n\tbool make_diags = katana::getCmdOption_bool(argv, argv + argc, \"-make_diags\", false);\n\t// If the following option is true, the program will create initial weight files and abort.\n\tbool save_init_weights = katana::getCmdOption_bool(argv, argv + argc, \"-save_init_weights\", false);\n\t// If the following option is true, the program will load the initial weights from files instead of creating random weights.\n\t// Note that the corresponding diag file must be loaded as well.\n\tbool init_weights_from_file = katana::getCmdOption_bool(argv, argv + argc, \"-init_weights_from_file\", false);\n\t\n\t\n\t// option for system simulation\n\t// \"dde_ibp\":\tsemi-analytic heun method with modified trapezoidal rule employing integration-by-parts\n\t// \"dde_heun\":\tsemi-analytic heun method with standard trapezoidal rule\n\t// \"network\":\tsolves the equivalent network equations\n\t// \"network_decoupled\": solves network ignoring the additional direct linear connections of neighboring nodes and layers\n\tstring system_simu = katana::getCmdOption(argv, argv + argc, \"-system_simu\", \"dde_ibp\");\n\t\n\t// option for gradient computation\n\t// backprop_standard: newly derived backpropagation algorithm for the deep learning delay system (was derived for equivalent network)\n\t// backprop_classic: classical backpropagation algorithm, ignores the additional direct linear connections of neighboring nodes and layers\n\tstring grad_comp = katana::getCmdOption(argv, argv + argc, \"-grad_comp\", \"backprop_standard\");\n\t\n\t// gradient_check: compute numerical gradient (for dde_ibp) for comparision\n\tbool gradient_check = katana::getCmdOption_bool(argv, argv + argc, \"-gradient_check\", false);\n\tdouble epsilon_gradient_check = 1e-9;\n\tbool print_gradients_to_file = false;\n\t\n\t\n\t// ### ### ### --- PARAMETERS --- ### ### ### \n\t\n\t// M and P are defined in global_constants.h\n\t\n\t// task parameter\n\tdouble noise_sigma = 1.0;\n\t\n\t\n\t// ... for the system/network architectur:\n\t\n\tint N = katana::getCmdOption(argv, argv + argc, \"-N\", 100);  // number of nodes per hidden layer\n\tint L = katana::getCmdOption(argv, argv + argc, \"-L\", 2);  // number of hidden layers\n\tint D = katana::getCmdOption(argv, argv + argc, \"-D\", 50);  // number of delays (NOTE: must be the correct number also if diag_method == \"from_file\")\n\t\n\tdouble theta = katana::getCmdOption(argv, argv + argc, \"-theta\", 0.5);  // node separation\n\tdouble alpha = -1.0;  // factor in linear part of delay system\n\t\n\tstring diag_method = katana::getCmdOption(argv, argv + argc, \"-diag_method\", \"uniform\");  // method to choose diagonals\n\t// \"uniform\": uniform distribution with the additional condition that there is at least one n'_d < 0 and one n'_d > 0\n\t// \"equi_dist\": diagonals with equal distances in between, if D is an odd number: main diagonal and same number of upper and lower, \n\t//              if D is an even number and diag_distance is even: centered, e.g. -15, -5, 5, 15,\n\t//              if D is even and diag_distance is odd: centered around -0.5, e.g. -8, -3, 2, 7.\n\t// \"from_file\": diag indices are taken from a given text file\n\t// For a banded matrix as connection matrix choose equi_dist and diag_distance = 1\n\t// For a full connection matrix choose D = 2 * N - 1 (and either uniform or equi_dist with diag_distance = 1)\n\tint diag_distance = katana::getCmdOption(argv, argv + argc, \"-diag_distance\", 0);  // distance between diagonals if diag_method == \"equi_dist\",\n\t\t\t\t\t\t\t// minimum distance between diagonals if diag_method is \"uniform\", otherwise ignored\n\t\t\t\t\t\t\t// Do not choose diag_distance too large. If (D - 1) * (2 * diag_distance - 1) >= 2 * (N - diag_margin) - 1 and method is uniform, the program will abort.\n\tstring diag_file_path = katana::getCmdOption(argv, argv + argc, \"-diag_file_path\", \"diag.txt\"); // path to text file containing D interger numbers n_prime_d, ignored if method is not \"from_file\" \n\t\n\t\n\t// ... for the training:\n\tint number_of_epochs = katana::getCmdOption(argv, argv + argc, \"-number_of_epochs\", 100);\n\tdouble eta_0 = katana::getCmdOption(argv, argv + argc, \"-eta0\", 0.001);\n\tdouble eta_1 = katana::getCmdOption(argv, argv + argc, \"-eta1\", 1000.0);  // learning rate eta = min(eta_0, eta_1 / step)\n\tbool pixel_shift = katana::getCmdOption_bool(argv, argv + argc, \"-pixel_shift\", false);  // on-off switch for training input random 1-pixel shift\n\tint max_pixel_shift = katana::getCmdOption(argv, argv + argc, \"-max_pixel_shift\", 1);\n\tbool input_noise = katana::getCmdOption_bool(argv, argv + argc, \"-training_noise\", false);  // on-off switch for training input gaussian noise\n\tdouble training_noise_sigma = katana::getCmdOption(argv, argv + argc, \"-sigma\", 0.01);  // standard deviation of gaussian noise to disturb training input\n\tbool rotation = katana::getCmdOption_bool(argv, argv + argc, \"-rotation\", false);\n\tdouble max_rotation_degrees = katana::getCmdOption(argv, argv + argc, \"-max_rotation_degrees\", 15.0);\n\tbool horizontal_flip = katana::getCmdOption_bool(argv, argv + argc, \"-flip\", false);  // only for CIFAR-10\n\t// dropout\n\tdouble dropout_rate = katana::getCmdOption(argv, argv + argc, \"-dropout\", 0.0);\n\t\n\t// ... for weight initialization:\n\tdouble initial_input_weigt_radius = sqrt(6.0 / ((double)D/2.0 + (double)M + 1.0));\n\tdouble initial_hidden_weigt_radius =  sqrt(6.0 / ((double)D + 1.0));\n\tdouble initial_output_weigt_radius =  sqrt(6.0 / ((double)D/2.0 + (double)P + 1.0));\n\t\n\t\n\t// ... for numerics:\n\t\n\tint N_h = max(32 ,(int)(16 * theta));  // computation steps per virtual node for solving DDE\n\t\n\t// computational precision for sums with exp(alpha * theta * n) factor in summands\n\t// in the functions \"get_deltas\" and \"get_gradient\" in \"backprop.cpp\". \n\t// exp_precision = -35.0 means that terms, where exponential factor\n\t// is smaller than exp(-35), are ignored.\n\t// Since exp(-35) is approximately 6.3e-16, the gradient will still be computed with double precision. \n\tdouble exp_precision = -35.0;\n\t\n\t\n\t\n\t// ### ### ### --- ETC. --- ### ### ###\n\t\n\t// make diag text file and end program if make_diags option is true\n\tif (make_diags){\n\t\tofstream diag_file;\n\t\tdiag_file.open(\"diag.txt\");\n\t\tfor (int i = 0; i < 6; ++i){\n\t\t\tvector<int> diag_indices = get_diag_indices(N, D, diag_method, diag_distance, diag_file_path, 0);\n\t\t\tfor (int d = 0; d < D - 1; ++d){\n\t\t\t\tdiag_file << diag_indices[d] << \" \";\n\t\t\t}\n\t\t\tdiag_file << diag_indices[D - 1] << endl;\n\t\t}\n\t\tdiag_file.close();\n\t\tcout << \"The option make_diags was true.\" << endl;\n\t\tcout << \"Program made (or overrode) diag.txt\" << endl;\n\t\treturn 0;\n\t}\n\t\n\t// make initial weight files and diag file and end program if make_diags save_init_weights option is true\n\tif (save_init_weights){\n\t\tvector<int> diag_indices;\n\t\tofstream diag_file;\n\t\tdiag_file.open(\"diag.txt\");\n\t\tfor (int i = 0; i < 6; ++i){\n\t\t\tdiag_indices = get_diag_indices(N, D, diag_method, diag_distance, diag_file_path, 0);\n\t\t\tfor (int d = 0; d < D - 1; ++d){\n\t\t\t\tdiag_file << diag_indices[d] << \" \";\n\t\t\t}\n\t\t\tdiag_file << diag_indices[D - 1] << endl;\n\t\t}\n\t\tdiag_file.close();\n\t\tcout << \"The option save_init_weights was true.\" << endl;\n\t\tcout << \"Program made (or overrode) diag.txt\" << endl;\n\t\tmat input_weights(N, M + 1);\n\t\tmat output_weights(P, N + 1);\n\t\tcube hidden_weights(L - 1, N, N + 1);\n\t\tinitialize_weights(input_weights, hidden_weights, output_weights, D, L, N, diag_indices,\n\t\t\t\t\t\t   initial_input_weigt_radius, initial_hidden_weigt_radius, initial_output_weigt_radius, true);\t\n\t\tcout << \"Save initial weights and end program because the option save_init_weights is true.\" << endl;\n\t\treturn 0;\n\t}\n\t\n\t// The following lines are to create a look up table \"exp_table\"\n\t// which contains the values exp(alpha * theta * n)\n\t// which are often needed by the functions \"get_deltas\" and \"get_gradient\" in \"backprop.cpp\". \n\tvector<double> exp_table;\n\tint n = 0;\n\twhile (alpha * theta * double(n) >= - 35.0){\n\t\tdouble exp_value = exp(alpha * theta * double(n));\n\t\texp_table.push_back(exp_value);\n\t\t++n;\n\t}\n\t\n\t// make results file and print information about parameters\n\tprint_parameters(results_file_name, print_msg, task,\n\t\t\t\t\tsystem_simu, grad_comp, gradient_check,\n\t\t\t\t\tN, L, D, theta, alpha,\n\t\t\t\t\tdiag_method, diag_distance, diag_file_path,\n\t\t\t\t\tnumber_of_epochs, eta_0, eta_1,\n\t\t\t\t\tpixel_shift, input_noise, training_noise_sigma,\n\t\t\t\t\tN_h, exp_precision);\n\t\n\t// determine data directory\n\tstring data_dir = \"data-Fashion-MNIST\";\n\t\n\t// read image data from files to arrays:\n\tcube train_images(number_of_training_batches, training_batch_size, M);\n\tmat test_images(test_batch_size, M);\n\tint train_labels[number_of_training_batches][training_batch_size];\n\tint test_labels[test_batch_size];\n\tread_files(train_images, test_images, train_labels, test_labels, data_dir);\n\t\n\t\n\t// for video:\n\tvector<int> step_indices_for_video;\n\tif (record_data){\n\t\tfstream index_file;\n\t\tstring index_string;\n\t\tindex_file.open(\"video/step_indices.txt\", ios::in);\n\t\tdo {\n\t\t\tgetline(index_file, index_string);\n\t\t\tif (index_string != \"\"){\n\t\t\t\tint i = stoi(index_string);\n\t\t\t\tstep_indices_for_video.push_back(i);\n\t\t\t}\n\t\t} while (index_string != \"\");\n\t\tindex_file.close();\n\t}\n\t\n\t\n\t\n\t// ### ### ### --- INITIALIZATION --- ### ### ###\n\t\n\t\n\tvector<int> training_batch_indices;\n\tcout << \"Begin training.\" << endl;\n\tfor (int i = 0; i < number_of_training_batches; ++i){\n\t\ttraining_batch_indices.push_back(i);\n\t}\n\t\n\t// initialize arrays which are used below to store the current system states\n\tmat activations(L, N);\n\tmat node_states(L, N);\n\tdouble output_activations[P];\n\tdouble outputs[P];\n\tvec g_primes(N);\n\n\t// initialize arrays to store deltas and gradient\n\tmat deltas(L, N);\n\tdouble output_deltas[P];\n\tmat input_weight_gradient(N, M + 1, fill::zeros);\n\tmat output_weight_gradient(P, N + 1, fill::zeros);\n\tcube weight_gradient(L - 1, N, N + 1, fill::zeros);\n\n\tmat deltas_0(L, N);\n\tdouble output_deltas_0[P];\n\tmat input_weight_gradient_0(N, M + 1, fill::zeros);\n\tmat output_weight_gradient_0(P, N + 1, fill::zeros);\n\tcube weight_gradient_0(L - 1, N, N + 1, fill::zeros);\n\n\t// initialize arrays to eventually store numerical gradient\n\tmat num_input_weight_gradient(N, M + 1, fill::zeros);\n\tmat num_output_weight_gradient(P, N + 1, fill::zeros);\n\tcube num_weight_gradient(L - 1, N, N + 1, fill::zeros);\n\n\n\t// The function \"get_diag_indices\" returns D intergers n'_d between - N + 1 and N - 1.\n\t// The delays are then tau_d = N - n'_d.\n\tvector<int> diag_indices;\n\tdiag_indices = get_diag_indices(N, D, diag_method, diag_distance, diag_file_path, 0);\n\n\t// initialize weights.\n\tmat input_weights(N, M + 1, fill::zeros);\n\tmat output_weights(P, N + 1, fill::zeros);\n\tcube hidden_weights(L - 1, N, N + 1, fill::zeros);\n\tif (init_weights_from_file){\n\t\tload_initial_weights(input_weights, hidden_weights, output_weights);\n\t} else {\n\t\tinitialize_weights(input_weights, hidden_weights, output_weights, D, L, N, diag_indices,\n\t\t\t\t\t   initial_input_weigt_radius, initial_hidden_weigt_radius, initial_output_weigt_radius, false);\n\t}\n\n\t// weights for test_runs.\n\tmat input_weights_scaled(N, M + 1, fill::zeros);\n\tmat output_weights_scaled(P, N + 1, fill::zeros);\n\tcube hidden_weights_scaled(L - 1, N, N + 1, fill::zeros);\n\n\t// dropout mask for weights:\n\tmat input_weights_mask(N, M + 1, fill::ones);\n\tcube hidden_weights_mask(L - 1, N, N + 1, fill::ones);\n\tmat output_weights_mask(P, N + 1, fill::ones);\n\n\n\n\t// ### ### ### --- STOCHASTIC GRADIENT DESCENT TRAINING --- ### ### ###\n\n\n\t// vectors to track training accuracy and validition accuracy (and eventually cosine similarity):\n\tvector<double> training_accuracy_vector;\n\tvector<double> accuracy_vector;\n\tvector<double> similarity_vector;\n\n\t// vector and variables to measure and save cpu time needed for each epoch \n\tvector<double> time_vector;\n\tclock_t start;\n\tclock_t ende;\n\tdouble epoch_time;\n\n\n\t// loop over training epochs:\n\tfor (int epoch = 0; epoch < number_of_epochs; ++epoch){\n\n\t\tstart = clock();\n\n\t\t// make vector with randomly shuffled indices between 0 and 59999 for each epoch of the stochastic gradient descent \n\t\tvector<int> index_vector;\n\t\tfor (int index = 0; index < number_of_training_batches*training_batch_size; ++index){\n\t\t\tindex_vector.push_back(index);\n\t\t}\n\t\tshuffle(begin(index_vector), std::end(index_vector), rng);\n\n\t\t// loop over training steps:\n\t\tint step_index = 0;\n\t\tfor (int index : index_vector){\n\t\t\t++step_index;\n\n\t\t\t// choose random dropout nodes\n\t\t\tinput_weights_mask = mat(N, M + 1, fill::ones);\n\t\t\thidden_weights_mask = cube(L - 1, N, N + 1, fill::ones);\n\t\t\toutput_weights_mask = mat(P, N + 1, fill::ones);\n\t\t\t// input layer\n\t\t\tfor (int m = 0; m < M; ++m){\n\t\t\t\tdouble random_num = uniform(0.0, 1.0);\n\t\t\t\tif (random_num < dropout_rate){\n\t\t\t\t\tfor (int n = 0; n < N; ++n){\n\t\t\t\t\t\tinput_weights_mask(n, m) = 0.0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// first hidden layer\n\t\t\tif (L > 1){\n\t\t\t\tfor (int n = 0; n < N; ++n){\n\t\t\t\t\tdouble random_num = uniform(0.0, 1.0);\n\t\t\t\t\tif (random_num < dropout_rate){\n\t\t\t\t\t\tfor (int m = 0; m < M + 1; ++m){\n\t\t\t\t\t\t\tinput_weights_mask(n, m) = 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (int j = 0; j < N; ++j){\n\t\t\t\t\t\t\thidden_weights_mask(0, j, n) = 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// hidden layers except first and last\n\t\t\tfor (int l = 1; l < L - 1; ++l){\n\t\t\t\tfor (int n = 0; n < N; ++n){\n\t\t\t\t\tdouble random_num = uniform(0.0, 1.0);\n\t\t\t\t\tif (random_num < dropout_rate){\n\t\t\t\t\t\tfor (int i = 0; i < N + 1; ++i){\n\t\t\t\t\t\t\thidden_weights_mask(l - 1, n, i) = 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (int j = 0; j < N; ++j){\n\t\t\t\t\t\t\thidden_weights_mask(l, j, n) = 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// last hidden layer\n\t\t\tif (L > 1){\n\t\t\t\tfor (int n = 0; n < N; ++n){\n\t\t\t\t\tdouble random_num = uniform(0.0, 1.0);\n\t\t\t\t\tif (random_num < dropout_rate){\n\t\t\t\t\t\tfor (int i = 0; i < N + 1; ++i){\n\t\t\t\t\t\t\thidden_weights_mask(L - 2, n, i) = 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (int p = 0; p < P; ++p){\n\t\t\t\t\t\t\toutput_weights_mask(p, n) = 0.0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// record data for video: step 0 \n\t\t\tif (record_data && epoch == 0 && step_index == 1){\n\t\t\t\tint rec_step = 0;\n\t\t\t\tcout << \"record data after step: \" << rec_step << endl;\n\t\t\t\t//save weights\n\t\t\t\tstring input_file_name = \"video/weights_input_step_\" + to_string(rec_step) + \".txt\";\n\t\t\t\tstring hidden_file_name = \"video/weights_hidden_step_\" + to_string(rec_step) + \".txt\";\n\t\t\t\tstring output_file_name = \"video/weights_output_step_\" + to_string(rec_step) + \".txt\";\n\t\t\t\tinput_weights.save(input_file_name, csv_ascii);\n\t\t\t\thidden_weights.save(hidden_file_name, raw_ascii);\n\t\t\t\toutput_weights.save(output_file_name, csv_ascii);\n\t\t\t\t//run system with examples from validation batch and save input, output and x_states\n\t\t\t\tfor (int example_index = 0; example_index < number_of_examples; ++example_index){\n\t\t\t\t\t// select image as input\n\t\t\t\t\tvec input_data = test_images.row(example_index).t();\n\t\t\t\t\tint label = test_labels[index];\n\t\t\t\t\t// run system and record data for x_states\n\t\t\t\t\tsolve_dde_ibp(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights, hidden_weights, output_weights, diag_indices, theta, alpha,\n\t\t\t\t\t\t\t  N, L, N_h, example_index+1, rec_step);\n\t\t\t\t\t// save input and output\n\t\t\t\t\tstring input_file_name = \"video/vector_input_step_\" + to_string(rec_step) + \"_example_\" + to_string(example_index + 1) + \".txt\";\n\t\t\t\t\tinput_data.save(input_file_name, csv_ascii);\n\t\t\t\t\tstring output_file_name = \"video/vector_output_step_\" + to_string(rec_step) + \"_example_\" + to_string(example_index + 1) + \".txt\";\n\t\t\t\t\tofstream output_file;\n\t\t\t\t\toutput_file.open(output_file_name);\n\t\t\t\t\tfor (double y_p : outputs){\n\t\t\t\t\t\toutput_file << y_p << endl;\n\t\t\t\t\t}\n\t\t\t\t\toutput_file.close();\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tdouble eta = learning_rate(epoch, step_index, eta_0, eta_1);\n\n\t\t\t// select image as input\n\t\t\tdiv_t div_result = div(index, training_batch_size);\n\t\t\tint batch_index = training_batch_indices[div_result.quot];\n\t\t\tint image_index = div_result.rem;\n\t\t\tvec input_data = train_images.tube(batch_index, image_index);\n\t\t\tint label = train_labels[batch_index][image_index];\n\n\t\t\t// data augmentation or regression\n\t\t\tif (rotation && M == 3072){\n\t\t\t\tdouble rotation_degrees = uniform(-max_rotation_degrees, max_rotation_degrees);\n\t\t\t\trotation32(input_data, rotation_degrees);\n\t\t\t}\n\n\t\t\tif (pixel_shift && M == 784){\n\t\t\t\tpixel_shift28(input_data, max_pixel_shift);\n\t\t\t}\n\t\t\tif (pixel_shift && M == 3072){\n\t\t\t\tpixel_shift32(input_data, max_pixel_shift);\n\t\t\t}\n\t\t\tif (input_noise){\n\t\t\t\tvec training_noise = training_noise_sigma * vec(M, fill::randn);\n\t\t\t\tinput_data += training_noise;\n\t\t\t}\n\t\t\tif (horizontal_flip && M == 3072){\n\t\t\t\tdouble random_val = uniform(0,1);\n\t\t\t\tif (random_val > 0.5){\n\t\t\t\t\thorizontal_flip32(input_data);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// get target\n\t\t\tdouble targets[P];\n\t\t\tfor (int p = 0; p < P; ++p){\n\t\t\t\ttargets[p] = input_data(p);\n\t\t\t}\n\n\t\t\t// add noise to input:\n\t\t\tvec noise = noise_sigma * vec(M, fill::randn);\n\t\t\tinput_data += noise;\n\t\t\tfor (int m = 0; m < M; ++m){\n\t\t\t\tif (input_data[m] < 0.0){\n\t\t\t\t\tinput_data[m] = 0.0;\n\t\t\t\t}\n\t\t\t\tif (input_data[m] > 1.0){\n\t\t\t\t\tinput_data[m] = 1.0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// solve the DDE (or network)\n\t\t\tclock_t start_solve = clock();\n\t\t\tif (system_simu == \"dde_ibp\"){\n\t\t\t\tsolve_dde_ibp(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights%input_weights_mask, hidden_weights%hidden_weights_mask, output_weights%output_weights_mask, diag_indices, theta, alpha,\n\t\t\t\t\t\t\t  N, L, N_h);\n\t\t\t} else if (system_simu == \"dde_heun\"){\n\t\t\t\tsolve_dde_heun(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights%input_weights_mask, hidden_weights%hidden_weights_mask, output_weights%output_weights_mask, diag_indices, theta, alpha,\n\t\t\t\t\t\t\t  N, L, N_h);\n\t\t\t} else if (system_simu == \"network\"){\n\t\t\t\tsolve_network(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights%input_weights_mask, hidden_weights%hidden_weights_mask, output_weights%output_weights_mask, theta, alpha,\n\t\t\t\t\t\t\t  N, L);\n\t\t\t} else if (system_simu == \"network_decoupled\"){\n\t\t\t\tsolve_network_decoupled(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights%input_weights_mask, hidden_weights%hidden_weights_mask, output_weights%output_weights_mask, N, L);\n\t\t\t} else {\n\t\t\t\tcout << system_simu << \" is not a valid value for the system_simu option.\" << endl;\n\t\t\t\tabort();\n\t\t\t}\n\t\t\tclock_t end_solve = clock();\n\t\t\tcumulative_solve_time += (end_solve - start_solve) / (double)CLOCKS_PER_SEC;\n\n\n\n\t\t\t// compute deltas and gradient\n\t\t\tclock_t start_backprop = clock();\n\t\t\tmat f_prime_activations = f_prime_matrix(activations);\n\t\t\tif (grad_comp == \"backprop_standard\"){\n\t\t\t\tget_gradient_node_by_node(input_weight_gradient, weight_gradient, output_weight_gradient, input_data, node_states, f_prime_activations, g_primes, outputs, targets, hidden_weights%hidden_weights_mask, output_weights%output_weights_mask, diag_indices, N, L, theta, alpha);\t\n\t\t\t} else if (grad_comp == \"backprop_classic\"){\n\t\t\t\tget_gradient_classical_backprop(input_weight_gradient, weight_gradient, output_weight_gradient, input_data, node_states, f_prime_activations, g_primes, outputs, targets, hidden_weights%hidden_weights_mask, output_weights%output_weights_mask, diag_indices, N, L);\n\t\t\t} else {\n\t\t\t\tcout << grad_comp << \" is not a valid value for the grad_comp option.\" << endl;\n\t\t\t\tabort();\n\t\t\t}\n\t\t\tclock_t end_backprop = clock();\n\t\t\tcumulative_backprop_time += (end_backprop - start_backprop) / (double)CLOCKS_PER_SEC;\n\t\t\t// eventually compute numerical gradient for comparision and save numerical gradient and backprop gradient in files\n\t\t\tif (gradient_check && step_index == 1){\n\t\t\t\tif (system_simu != \"dde_ibp\"){\n\t\t\t\t\tcout << \"The option to compute the gradient numerically is only available if the method 'dde_ibp' is used to solve the delay system. \" << endl;\n\t\t\t\t\tcout << \"Set the option 'system_simu' to 'dde_ibp' or set the option 'num_gradient' to false.\" << endl;\n\t\t\t\t\tabort();\n\t\t\t\t}\n\t\t\t\tget_num_gradient(num_input_weight_gradient, num_weight_gradient, num_output_weight_gradient, \n\t\t\t\t\t\t\t\t activations, node_states, output_activations, outputs, g_primes, label,\n\t\t\t\t\t\t\t\t input_data, input_weights, hidden_weights, output_weights, diag_indices, theta, alpha, N, L, N_h, epsilon_gradient_check);\n\t\t\t\tif (print_gradients_to_file){\n\t\t\t\t\twrite_gradients_to_file(input_weight_gradient, weight_gradient, output_weight_gradient, num_input_weight_gradient, num_weight_gradient, num_output_weight_gradient, epoch + 1, step_index, 0);\n\t\t\t\t}\n\t\t\t\tdouble cos_sim = cosine_similarity(input_weight_gradient, weight_gradient, output_weight_gradient, num_input_weight_gradient, num_weight_gradient, num_output_weight_gradient);\n\t\t\t\tsimilarity_vector.push_back(cos_sim);\n\t\t\t}\n\n\n\t\t\tinput_weight_gradient = input_weight_gradient % input_weights_mask;\n\t\t\tweight_gradient = weight_gradient % hidden_weights_mask;\n\t\t\toutput_weight_gradient = output_weight_gradient % output_weights_mask;\n\n\t\t\t// perform weight updates\n\t\t\tinput_weights += - eta * input_weight_gradient;\n\t\t\thidden_weights += - eta * weight_gradient;\n\t\t\toutput_weights += - eta * output_weight_gradient;\n\n\n\n\t\t\t// record data for video: step 1 to end \n\t\t\tif (record_data && find(step_indices_for_video.begin(), step_indices_for_video.end(), epoch * 50000 + step_index) != step_indices_for_video.end()){\n\t\t\t\tint rec_step = epoch * 50000 + step_index;\n\t\t\t\tcout << \"record data after step: \" << rec_step << endl;\n\t\t\t\t//save weights\n\t\t\t\tstring input_file_name = \"video/weights_input_step_\" + to_string(rec_step) + \".txt\";\n\t\t\t\tstring hidden_file_name = \"video/weights_hidden_step_\" + to_string(rec_step) + \".txt\";\n\t\t\t\tstring output_file_name = \"video/weights_output_step_\" + to_string(rec_step) + \".txt\";\n\t\t\t\tinput_weights.save(input_file_name, csv_ascii);\n\t\t\t\thidden_weights.save(hidden_file_name, raw_ascii);\n\t\t\t\toutput_weights.save(output_file_name, csv_ascii);\n\t\t\t\t//run system with examples from validation batch and save input, output and x_states\n\t\t\t\tfor (int example_index = 0; example_index < number_of_examples; ++example_index){\n\t\t\t\t\t// select image as input\n\t\t\t\t\tvec input_data = test_images.row(example_index).t();\n\t\t\t\t\tint label = test_labels[index];\n\t\t\t\t\t// run system and record data for x_states\n\t\t\t\t\tsolve_dde_ibp(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights, hidden_weights, output_weights, diag_indices, theta, alpha,\n\t\t\t\t\t\t\t  N, L, N_h, example_index+1, rec_step);\n\t\t\t\t\t// save input and output\n\t\t\t\t\tstring input_file_name = \"video/vector_input_step_\" + to_string(rec_step) + \"_example_\" + to_string(example_index + 1) + \".txt\";\n\t\t\t\t\tinput_data.save(input_file_name, csv_ascii);\n\t\t\t\t\tstring output_file_name = \"video/vector_output_step_\" + to_string(rec_step) + \"_example_\" + to_string(example_index + 1) + \".txt\";\n\t\t\t\t\tofstream output_file;\n\t\t\t\t\toutput_file.open(output_file_name);\n\t\t\t\t\tfor (double y_p : outputs){\n\t\t\t\t\t\toutput_file << y_p << endl;\n\t\t\t\t\t}\n\t\t\t\t\toutput_file.close();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//weight scaling\n\t\tinput_weights_scaled = input_weights / (1.0 - dropout_rate);\n\t\thidden_weights_scaled = hidden_weights / (1.0 - dropout_rate);\n\t\toutput_weights_scaled = output_weights / (1.0 - dropout_rate);\n\n\t\t// loop to get accuracy on training set:\n\t\tdouble mse_sum = 0.0; ;  \n\t\tfor (int index = 0; index < number_of_training_batches *training_batch_size; ++index){\n\t\t\t//cout << \"validation step (on training set)\" << index + 1 << endl;\n\n\t\t\t// select image as input\n\t\t\tdiv_t div_result = div(index, training_batch_size);\n\t\t\tint batch_index = training_batch_indices[div_result.quot];\n\t\t\tint image_index = div_result.rem;\n\t\t\tvec input_data = train_images.tube(batch_index, image_index);\n\t\t\tint label = train_labels[batch_index][image_index];\n\n\t\t\t// get target\n\t\t\tdouble targets[P];\n\t\t\tfor (int p = 0; p < P; ++p){\n\t\t\t\ttargets[p] = input_data(p);\n\t\t\t}\n\n\t\t\t// add noise to input:\n\t\t\tvec noise = noise_sigma * vec(M, fill::randn);\n\t\t\tinput_data += noise;\n\t\t\tfor (int m = 0; m < M; ++m){\n\t\t\t\tif (input_data[m] < 0.0){\n\t\t\t\t\tinput_data[m] = 0.0;\n\t\t\t\t}\n\t\t\t\tif (input_data[m] > 1.0){\n\t\t\t\t\tinput_data[m] = 1.0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// solve the DDE (or network)\n\t\t\tclock_t start_solve = clock();\n\t\t\tif (system_simu == \"dde_ibp\"){\n\t\t\t\tsolve_dde_ibp(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights_scaled, hidden_weights_scaled, output_weights_scaled, diag_indices, theta, alpha,\n\t\t\t\t\t\t\t  N, L, N_h);\n\t\t\t} else if (system_simu == \"dde_heun\"){\n\t\t\t\tsolve_dde_heun(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights_scaled, hidden_weights_scaled, output_weights_scaled, diag_indices, theta, alpha,\n\t\t\t\t\t\t\t  N, L, N_h);\n\t\t\t} else if (system_simu == \"network\"){\n\t\t\t\tsolve_network(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights_scaled, hidden_weights_scaled, output_weights_scaled, theta, alpha,\n\t\t\t\t\t\t\t  N, L);\n\t\t\t} else if (system_simu == \"network_decoupled\"){\n\t\t\t\tsolve_network_decoupled(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights_scaled, hidden_weights_scaled, output_weights_scaled, N, L);\n\t\t\t} else {\n\t\t\t\tcout << system_simu << \" is not a valid value for the system_simu parameter.\" << endl;\n\t\t\t\tabort();\n\t\t\t}\n\t\t\tclock_t end_solve = clock();\n\t\t\tcumulative_solve_time += (end_solve - start_solve) / (double)CLOCKS_PER_SEC;\n\n\n\t\t\tdouble mse = 0;\n\t\t\tfor (int p = 0; p < P; ++p){\n\t\t\t\tmse += pow(outputs[p] - targets[p], 2.0);\n\t\t\t}\n\t\t\tmse = mse/(double)P;\n\t\t\tmse_sum += mse;\n\t\t}\n\t\ttraining_accuracy_vector.push_back(mse_sum / 50000.0);\n\n\t\t// loop for validation:\n\t\tmse_sum = 0.0; ;\n\t\tfor (int index = 0; index < test_batch_size; ++index){\n\n\t\t\tvec input_data = test_images.row(index).t();\n\t\t\tint label = test_labels[index];\n\n\t\t\t// get target\n\t\t\tdouble targets[P];\n\t\t\tfor (int p = 0; p < P; ++p){\n\t\t\t\ttargets[p] = input_data(p);\n\t\t\t}\n\n\t\t\t// add noise to input:\n\t\t\tvec noise = noise_sigma * vec(M, fill::randn);\n\t\t\tinput_data += noise;\n\t\t\tfor (int m = 0; m < M; ++m){\n\t\t\t\tif (input_data[m] < 0.0){\n\t\t\t\t\tinput_data[m] = 0.0;\n\t\t\t\t}\n\t\t\t\tif (input_data[m] > 1.0){\n\t\t\t\t\tinput_data[m] = 1.0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// solve the DDE (or network)\n\t\t\tclock_t start_solve = clock();\n\t\t\tif (system_simu == \"dde_ibp\"){\n\t\t\t\tsolve_dde_ibp(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights_scaled, hidden_weights_scaled, output_weights_scaled, diag_indices, theta, alpha,\n\t\t\t\t\t\t\t  N, L, N_h);\n\t\t\t} else if (system_simu == \"dde_heun\"){\n\t\t\t\tsolve_dde_heun(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights_scaled, hidden_weights_scaled, output_weights_scaled, diag_indices, theta, alpha,\n\t\t\t\t\t\t\t  N, L, N_h);\n\t\t\t} else if (system_simu == \"network\"){\n\t\t\t\tsolve_network(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights_scaled, hidden_weights_scaled, output_weights_scaled, theta, alpha,\n\t\t\t\t\t\t\t  N, L);\n\t\t\t} else if (system_simu == \"network_decoupled\"){\n\t\t\t\tsolve_network_decoupled(activations, node_states, output_activations, outputs, g_primes,\n\t\t\t\t\t\t\t  input_data, input_weights_scaled, hidden_weights_scaled, output_weights_scaled, N, L);\n\t\t\t} else {\n\t\t\t\tcout << system_simu << \" is not a valid value for the system_simu parameter.\" << endl;\n\t\t\t\tabort();\n\t\t\t}\n\t\t\tclock_t end_solve = clock();\n\t\t\tcumulative_solve_time += (end_solve - start_solve) / (double)CLOCKS_PER_SEC;\n\n\n\t\t\t// save example images\n\t\t\tif (index < save_examples){\n\t\t\t\tstring original_file_name = \"example_results/epoch_\" + to_string(epoch + 1) + \"_example_\" + to_string(index + 1) + \"_original.txt\";\n\t\t\t\tstring input_file_name = \"example_results/epoch_\" + to_string(epoch + 1) + \"_example_\" + to_string(index + 1) + \"_input.txt\";\n\t\t\t\tstring output_file_name = \"example_results/epoch_\" + to_string(epoch + 1) + \"_example_\" + to_string(index + 1) + \"_output.txt\";\n\t\t\t\tofstream original_file;\n\t\t\t\toriginal_file.open(original_file_name);\n\t\t\t\tfor (int p = 0; p < P; ++p){\n\t\t\t\t\toriginal_file << targets[p] << endl;\n\t\t\t\t}\n\t\t\t\toriginal_file.close();\n\t\t\t\tofstream input_file;\n\t\t\t\tinput_file.open(input_file_name);\n\t\t\t\tfor (int p = 0; p < P; ++p){\n\t\t\t\t\tinput_file << input_data(p) << endl;\n\t\t\t\t}\n\t\t\t\tinput_file.close();\n\t\t\t\tofstream output_file;\n\t\t\t\toutput_file.open(output_file_name);\n\t\t\t\tfor (int p = 0; p < P; ++p){\n\t\t\t\t\toutput_file << outputs[p] << endl;\n\t\t\t\t}\n\t\t\t\toutput_file.close();\n\t\t\t}\n\n\t\t\tdouble mse = 0;\n\t\t\tfor (int p = 0; p < P; ++p){\n\t\t\t\tmse += pow(outputs[p] - targets[p], 2.0);\n\t\t\t}\n\t\t\tmse = mse/(double)P;\n\t\t\tmse_sum += mse;\n\t\t}\n\t\taccuracy_vector.push_back(mse_sum / 10000.0);\n\n\t\tcout << \"epoch \" << epoch + 1 << \": validation MSE = \" << mse_sum / 10000.0 << endl;\n\t\t// eventually print weights to file at end of each epoch\n\t\tif (print_weights_to_file){\n\t\t\tprint_weights(input_weights_scaled, hidden_weights_scaled, output_weights_scaled, diag_indices, 0, epoch);\n\t\t}\n\n\t\tende = clock();\n\t\tepoch_time = ((double) (ende - start)) / (double)CLOCKS_PER_SEC;\n\t\ttime_vector.push_back(epoch_time);\n\t}\n\n\t// print result to file:\n\tprint_results(results_file_name, 0, diag_indices, training_accuracy_vector, accuracy_vector, similarity_vector);\n\n\t\n\t// for cpu time measuring\n\tclock_t end_overall = clock();\n\tdouble cpu_time_overall = (end_overall - start_overall) / (double)CLOCKS_PER_SEC;\n\tdouble cpu_time_residual = cpu_time_overall - cumulative_solve_time - cumulative_backprop_time;\n\tdouble cpu_time_solve_percentage = 100.0 * cumulative_solve_time / cpu_time_overall;\n\tdouble cpu_time_backprop_percentage = 100.0 * cumulative_backprop_time / cpu_time_overall;\n\tdouble cpu_time_residual_percentage = 100.0 * cpu_time_residual / cpu_time_overall;\n\t\n\t// get current time and date and print to results text file\n\tauto current_clock = chrono::system_clock::now();\n\ttime_t current_time = chrono::system_clock::to_time_t(current_clock);\n\tofstream results_file;\n\tresults_file.open(results_file_name, ios_base::app);\n\tresults_file << endl;\n\tresults_file << endl;\n\tresults_file << \"total cpu time (in seconds): \" << cpu_time_overall << endl;\n\tresults_file << \"cumulative cpu time for solving the DDE or network (in seconds): \" << cumulative_solve_time << \" (\" << cpu_time_solve_percentage << \"%)\" << endl;\n\tresults_file << \"cumulative cpu time for backpropagation (in seconds): \" << cumulative_backprop_time << \" (\" << cpu_time_backprop_percentage << \"%)\" << endl;\n\tresults_file << \"residual cpu time (in seconds): \" << cpu_time_residual << \" (\" << cpu_time_residual_percentage << \"%)\" << endl;\n\tresults_file << endl;\n\tresults_file << \"end of simulation: \" << ctime(&current_time);\n\tresults_file.close();\n\t\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "6a84aed6b6ae6f6e4fd17b6181a8416099ba541b", "size": 32510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "delay-system-denoising-test/main.cpp", "max_stars_repo_name": "flori-stelzer/deep-learning-delay-system", "max_stars_repo_head_hexsha": "e0772ceb831ab0a551adb2447a602171117a4261", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-09-01T01:57:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T08:26:27.000Z", "max_issues_repo_path": "delay-system-denoising-test/main.cpp", "max_issues_repo_name": "flori-stelzer/deep-learning-delay-system", "max_issues_repo_head_hexsha": "e0772ceb831ab0a551adb2447a602171117a4261", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-24T11:10:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-24T11:10:19.000Z", "max_forks_repo_path": "delay-system-denoising-test/main.cpp", "max_forks_repo_name": "flori-stelzer/deep-learning-delay-system", "max_forks_repo_head_hexsha": "e0772ceb831ab0a551adb2447a602171117a4261", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-17T07:58:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:26:30.000Z", "avg_line_length": 42.2756827048, "max_line_length": 275, "alphanum_fraction": 0.6953552753, "num_tokens": 8838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4291760739580869}}
{"text": "/*\n * Rody Oldenhuis\n * cosine Science & Computing BV\n * roldenhuis@cosine.nl\n *\n * PhysUnits.hh\n * Created: 31.08.2012 16:20:53 CEST\n */\n\n#ifndef _PHYSUNITS_HH\n#define _PHYSUNITS_HH\n\n#include <thread>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n// global helper variables\nnamespace\n{\n    union endian_t {\n        long l;\n        char c[sizeof(long)];\n    } __endian__t;\n}\n\n\n/// SI multiplier table\nnamespace si\n{\n    const double\n\n    // names          prefixes\n    yotta = 1e24,     Y  = yotta,\n    zetta = 1e21,     Z  = zetta,\n    exa   = 1e18,     E  = exa  ,\n    peta  = 1e15,     P  = peta ,\n    tera  = 1e12,     T  = tera ,\n    giga  = 1e9,      G  = giga ,\n    mega  = 1e6,      M  = mega ,\n    kilo  = 1e3,      k  = kilo ,\n    hecto = 1e2,      h  = hecto,\n    deca  = 1e1,      da = deca ,\n\n    deci  = 1e-1,     d  = deci ,\n    centi = 1e-2,     c  = centi,\n    milli = 1e-3,     m  = milli,\n    micro = 1e-6,     mu = micro,\n    nano  = 1e-9,     n  = nano ,\n    pico  = 1e-12,    p  = pico ,\n    femto = 1e-15,    f  = femto,\n    atto  = 1e-18,    a  = atto ,\n    zepto = 1e-21,    z  = zepto,\n    yocto = 1e-24,    y  = yocto;\n}\n\n\n/// Binary prefixes\nnamespace binary\n{\n    const double\n\n    // names          prefixes\n    kibi = 1.*1024,   ki = kibi,\n    mebi = ki*1024,   Mi = mebi,\n    gibi = Mi*1024,   Gi = gibi,\n    tebi = Gi*1024,   Ti = tebi,\n    pebi = Ti*1024,   Pi = pebi,\n    exbi = Pi*1024,   Ei = exbi,\n    zebi = Ei*1024,   Zi = zebi,\n    yobi = Zi*1024,   Yi = yobi;\n\n}\n\n\n/// Physics constants\nnamespace physics\n{\n    const double\n\n    c     = 299792458,       // speed of light [m/s]\n    au    = 1.49597870e11,   // unit distance [m]\n    KSun  = 1370,            // Solar constant [W/m^2]\n\n    // FIXME: (Rody Oldenhuis) DEPRACATED\n    //    Using Solar mass (or masses in general) introduces terrible numerical\n    //    inaccuracies everywhere due to current uncertainty in the value of\n    //    Newton's G. Use standard gravitational parameters (=GM); these have\n    //    up to 6 orders of magnitude better accuracy.\n    G     = 6.67384e-11,     // Gravitational constant [m^3/kg/s^2] (CODATA 2010 recommended value)\n    MSun  = 1.98855e30,      // Solar mass [kg]\n    // -----------------------------------------\n\n    k     = 1.3806488e-23,   // Boltzmann constant [J K^-1]\n    sigma = 5.670373e-8,     // Stefan-Boltzmann constant [W m^-2 K^-4]\n\n    // FIXME: (Rody Oldenhuis) Not really a \"constant\", more a unit...\n    // Use class Length for these things.\n    A     = 1.0e-10,         // Angstrom\n    // -----------------------------------------\n\n    NA    = 6.02214129e+23,  // Avogadro's constant [1/mol]\n    h     = 6.62606957e-34,  // Planck's constant [Js]\n    hbar  = 1.054571726e-34, // Reduced Plankc's constant, or Dirac's constant [Js]\n    re    = 2.817940285e-15, // Classical electron radius [m]\n    q     = 1.60217646e-19,  // Proton charge [C]\n\n    // FIXME: (Rody Oldenhuis) DEPRECATED\n    //   Only included because full conversion takes too much time.\n    //   Find files in need of conversion with \"grep 'physics::day' *.cc *.hh\"\n    //   and convert everything to class Time.\n    s        = 1,\n    minute   = 60*s,\n    hour     = 60*minute,\n    day      = 24*hour,\n    jyear    = 365.25*day,\n    jcentury = 100*jyear;\n    // -----------------------------------------\n\n}\n\n\n/// Mathematical constants\nnamespace math\n{\n    const double\n\n    pi         = 3.14159265358979323846264338327950288419716939937510,\n    pio2       = 1.57079632679489661923132169163975144209858469968755,\n    pio4       = 0.78539816339744830961566084581987572104929234984377,\n    pio6       = 0.52359877559829887307710723054658381403286156656251,\n    threepio2  = 4.71238898038468985769396507491925432629575409906265,\n    twopi      = 6.28318530717958647692528676655900576839433879875020,\n    tau        = twopi, // the TRUE circle constant!!\n    twotau     = 12.5663706143591729538505735331180115367886775975004,\n    oneopi     = 0.31830988618379067153776752674502872406891929148091, // 1/pi\n    twoopi     = 0.63661977236758134307553505349005744813783858296182, // 2/pi\n    oneosqrtpi = 0.56418958354775628694807945156077258584405062932900, // 1/sqrt(pi)\n    twoosqrtpi = 1.12837916709551257389615890312154517168810125865800, // 2/sqrt(pi)\n\n    sqrt2      = 1.41421356237309504880168872420969807856967187537694,\n    sqrt3      = 1.73205080756887729352744634150587236694280525381038,\n    sqrt1o2    = 0.70710678118654752440084436210484903928483593768847, // sqrt(1/2)\n    sqrt1o3    = 0.57735026918962576450914878050195745564760175127012, // sqrt(1/3)\n\n    epsilon    = std::numeric_limits<double>::epsilon(),\n    dx         = epsilon,\n    eps        = epsilon,\n    INF        = std::numeric_limits<double>::infinity(),\n    inf        = INF,\n    NaN        = std::numeric_limits<double>::quiet_NaN(),\n    nan        = NaN;\n\n\n    // some things needfloat versions of the above\n    const float\n\n    epsilonf = std::numeric_limits<float>::epsilon(),\n    dxf      = epsilonf,\n    epsf     = epsilonf;\n\n\n    // handy utilities\n    // ----------------\n\n    // signum: -1 for anything <0, +1 for anything >0, 0 for anything ==0.\n    template <typename T>\n    int signum(T in) {\n        return (in>0)-(in<0);\n    }\n\n    // negative-value-correct modulus\n    // NOTE: NOT the same as % or fmod()\n    template <typename T>\n    T mod(T x, T y) {\n        return (0==y) ? x : x-y*std::floor(x/y);\n    }\n\n    // FIXME: (Rody Oldenhuis) DEPRECATED\n    //   Only included because full conversion takes too much time.\n    //   Find files in need of conversion with \"grep 'math::deg' *.cc *.hh\"\n    //   and convert everything to class Angle.\n    const double\n        rad = 1.0,\n        deg = pi/180.0;\n    // -----------------------------------------\n}\n\n\n/// Constants specific to the system HIPSIM's being run on\nnamespace machine\n{\n    const unsigned int\n\n    // get number of physical cores present in the system\n    // platform-independent, > C++11\n    numCores = std::thread::hardware_concurrency();\n\n\n    // This machine's endianness\n    const bool\n\n    machine_is_msb = (__endian__t.l = 1, __endian__t.c[sizeof(long)-1] == 1),\n    machine_is_lsb = (__endian__t.l = 1, __endian__t.c[sizeof(long)-1] != 1);\n\n\n    // handy dandy utilities\n\n    template<typename T>\n    T change_endianness(T x)\n    {\n        char *b = (char *)(&x);\n        switch (sizeof(T))\n        {\n            case 1:\n                break;\n\n            case 2:\n                std::swap(b[0], b[1]);\n                break;\n\n            case 4:\n                std::swap(b[0], b[3]);\n                std::swap(b[1], b[2]);\n                break;\n\n            case 8:\n                std::swap(b[0], b[7]);\n                std::swap(b[1], b[6]);\n                std::swap(b[2], b[5]);\n                std::swap(b[3], b[4]);\n                break;\n\n            default:\n                static const bool cannot_swap = true;\n                assert(cannot_swap);\n        }\n        return x;\n    }\n\n    template<typename T>\n    void write_msb(std::ostream & os, T x) {\n        if (machine_is_lsb)\n            x = change_endianness(x);\n        os.write(reinterpret_cast<char *>(&x), sizeof(T));\n    }\n\n    template<typename T>\n    void write_lsb(std::ostream & os, T x) {\n        if (machine_is_msb)\n            x = change_endianness(x);\n        os.write(reinterpret_cast<char *>(&x), sizeof(T));\n    }\n\n    template<typename T>\n    void read_msb(std::istream & is, T & x) {\n        is.read(reinterpret_cast<char *>(&x), sizeof(T));\n        if (machine_is_lsb)\n        x = change_endianness(x);\n    }\n\n    template<typename T>\n    void read_lsb(std::istream & is, T & x) {\n        is.read(reinterpret_cast<char *>(&x), sizeof(T));\n        if (machine_is_msb)\n        x = change_endianness(x);\n    }\n\n}\n\n\n// base classes for all units\n// --------------------------\n\n// fwd declare everything\nnamespace _ignore{\n    class Unit;\n    template<typename T>class UnitOperators;\n}\n\n\n// fwd declare everything\nclass Angle;      class Energy;\nclass Length;     class Force;\nclass Area;       class Temperature;\nclass Volume;     class Mass;\nclass Time;       class Speed;\nclass Density;    class Pressure;\n\n\n// Math operators\ntemplate <typename T> T  abs(const _ignore::UnitOperators<T>& t);\ntemplate <typename T> T fabs(const _ignore::UnitOperators<T>& t);\n\n\n// definition of unit base classes\nnamespace _ignore\n{\n    // Base class for all units\n    class Unit\n    {\n    protected:\n        double value;\n        Unit(double value) : value(value) {}\n\n    public:\n        virtual ~Unit(){}\n\n        Unit() : value(0.0) {}\n        Unit(const Unit& obj) : value(obj.value) {}\n\n        // enforce string representation\n        virtual std::string toString() const = 0;\n\n    };\n\n    // RO: use CRTP pattern to have the definition of the operators all in\n    // one place, while guaranteeing that only same-type operators work. See\n    // http://stackoverflow.com/questions/12742728/\n    template <typename T>\n    class UnitOperators\n        : public Unit\n    {\n        friend T  abs<T>(const UnitOperators<T>& t);\n        friend T fabs<T>(const UnitOperators<T>& t);\n\n    protected:\n        UnitOperators(double value) : Unit(value){}\n\n    public:\n        virtual ~UnitOperators(){}\n\n        UnitOperators()             : Unit()    {}\n        UnitOperators(const T& obj) : Unit(obj) {}\n\n        // RO : use static_cast, and make this class a friend class of all\n        // classes subclassing it, as per\n        // http://stackoverflow.com/questions/12910883/\n        T&     operator= (const T& rhs)       { if (this!=&rhs) value = rhs.value; return static_cast<T&>(*this); }\n\n        bool   operator> (const T& rhs) const { return value >  rhs.value; }\n        bool   operator< (const T& rhs) const { return value <  rhs.value; }\n        bool   operator>=(const T& rhs) const { return value >= rhs.value; }\n        bool   operator<=(const T& rhs) const { return value <= rhs.value; }\n        bool   operator==(const T& rhs) const { return value == rhs.value; }\n        bool   operator!=(const T& rhs) const { return value != rhs.value; }\n\n        T&     operator+=(const T& rhs)       { value += rhs.value; return static_cast<T&>(*this); }\n        T&     operator-=(const T& rhs)       { value -= rhs.value; return static_cast<T&>(*this); }\n        T&     operator*=(double F)           { value *= F; return static_cast<T&>(*this); }\n        T&     operator/=(double F)           { value /= F; return static_cast<T&>(*this); }\n\n        T      operator+ (const T& rhs) const { return T(*this) += rhs; }\n        T      operator- (const T& rhs) const { return T(*this) -= rhs; }\n        T      operator- ()             const { return T(-value);}\n        T      operator+ ()             const { return T(+value);}\n\n        T      operator* (double F)     const { return T(*this) *= F; }\n        T      operator/ (double F)     const { return T(*this) /= F; }\n        double operator* (const T& rhs) const { return value*rhs.value; }\n        double operator/ (const T& rhs) const { return value/rhs.value; }\n\n        // some nice constant instances\n        static const T zero        ;\n        static const T dx          ;\n        static const T infinitesmal;\n        static const T small       ;\n        static const T NaN         ;\n        static const T nan         ;\n        static const T inf         ;\n        static const T infinite    ;\n        static const T infinity    ;\n\n    };\n\n}\n\n\n\n/**\n * @brief Object with units [angle]. Aimed at avoiding confusion between degrees, radians,...\n */\n\n/**\n * Angle\n * avoid confusion between degrees, radians, gradians\n *\n * @see Length @see Time @see Mass @see Temperature @see Energy\n * @see Area @see Force @see Speed\n *\n */\n\n\nclass Angle final\n    : public _ignore::UnitOperators<Angle>\n{\n    typedef _ignore::UnitOperators<Angle> base;\n    friend class _ignore::UnitOperators<Angle>;\n\nprivate:\n\n    // value is always in radians\n    explicit Angle(double value) : base(value) {};\n\npublic:\n   ~Angle(){}\n\n    // default value: 0\n    Angle() : base(){};\n    // copy constructor\n    Angle(const Angle& a2) : base(a2){};\n    Angle(const base&  a2) : base(a2){};\n\n    /// Angle is instantiated through named constructors\n    static Angle\n        radians    (double rad),\n        degrees    (double deg),\n        arcminutes (double moa),\n        arcseconds (double soa),\n        GRADIANS   (double grad); // NOTE: capitalized to avoid\n                                  // confusion w/ radians\n    /// Angle's different return types\n    double\n        radians    () const,\n        degrees    () const,\n        arcminutes () const,\n        arcseconds () const,\n        GRADIANS   () const; // NOTE: capitalized to avoid\n                             // confusion w/ radians\n    /// alternatively, one can use various pre-defined angles\n    static const Angle\n        tau ,   _360,\n        pi  ,   _180,\n        pio2,   _90 ,\n        pio4,   _45 ,\n        pio6,   _30 ;\n\n    /// wrap value into [-pi +pi) / [-180 +180)\n    Angle& wrap_posneg();\n    friend Angle wrap_posneg(const Angle& a); // free function\n\n    /// wrap value into [0 2pi) / [0 360)\n    Angle& wrap_positive();\n    friend Angle wrap_positive(const Angle& a); // free function\n\n    // NOTE: angles have no units -- it's OK for these\n    // operators to return Angles\n    using _ignore::UnitOperators<Angle>::operator/;\n    using _ignore::UnitOperators<Angle>::operator*;\n    Angle\n        operator/ (const Angle& a2) const,\n        operator* (const Angle& a2) const;\n\n    /// human-readable string representation\n    std::string toString() const;\n};\n\n\n/**\n * @brief Object with units of Length. Makes metric/imperial less prone to error.\n */\n\n/**\n * Lengths\n * make metric <-> imperial a bit less prone to error\n *\n * @see Angle @see Time @see Mass @see Temperature @see Energy\n * @see Area @see Force @see Speed\n */\nclass Length final\n    : public _ignore::UnitOperators<Length>\n{\n    typedef _ignore::UnitOperators<Length> base;\n    friend class _ignore::UnitOperators<Length>;\n\nprivate:\n    // value is always in [m]\n    explicit Length(double value) : base(value) {}\n\npublic:\n    ~Length(){}\n\n    // default\n    Length() : base() {}\n    // Copy constructor\n    Length (const Length& L2) : base(L2) {}\n    Length (const base&   L2) : base(L2) {}\n\n    /// Length is instantiated through named constructors\n    static Length\n        meters           (double m)  ,     m (double   m),\n        kilometers       (double km) ,    km (double  km),\n        nanometers       (double nm) ,    nm (double  nm),\n        microns          (double mu) ,    um (double  um),\n        micrometers      (double mu) ,\n        inches           (double in) ,    in (double  in),\n        feet             (double ft) ,    ft (double  ft),\n        foot             (double ft) ,\n        yards            (double yrd),\n        miles            (double mi) ,    mi (double  mi),\n        nauticalMiles    (double nmi),   nmi (double nmi),\n        astronomicalUnits(double au ),    AU (double  au),\n        angstroms        (double a)  ,     A (double   a);\n\n\n    /// Length can return various units of length\n    double\n        meters            () const,   m() const,\n        kilometers        () const,  km() const,\n        nanometers        () const,  nm() const,\n        microns           () const,  um() const,\n        micrometers       () const,\n        inches            () const,  in() const,\n        feet              () const,  ft() const,\n        foot              () const,\n        yards             () const,\n        miles             () const,  mi() const,\n        nauticalMiles     () const, nmi() const,\n        astronomicalUnits () const,  AU() const,\n        angstroms         () const,   A() const;\n\n    /// alternatively, one can use various constant lengths\n    static const Length\n\n        // SI\n        one_km, kilometer,          // 1 kilometer\n        one_m,  meter,              // 1 meter\n        one_mm, millimeter,         // 1 millimeter\n        one_um, micrometer, micron, // 1 micron\n        one_nm, nanometer,          // 1 nanometer\n\n        // NON-SI\n        one_AU, astronomicalUnit,\n        inch, one_ft, yard, mile, nauticalMile, angstrom;\n\n    ///cast operators\n    operator Energy() const; // wavelength to energy\n\n    /// Human-readable string representation\n    std::string toString() const;\n};\n\n\n/**\n * @brief\n */\n\n/**\n * Times\n * make hours, minute, seconds, etc. readable\n *\n * @see Angle @see Length @see Mass @see Temperature @see Energy\n * @see Area @see Force @see Speed\n */\nclass Time final\n    : public _ignore::UnitOperators<Time>\n{\n    typedef _ignore::UnitOperators<Time> base;\n    friend class _ignore::UnitOperators<Time>;\n\nprivate:\n    /// value is always given in seconds\n    explicit Time(double value) : _ignore::UnitOperators<Time>(value){}\n\npublic:\n   ~Time(){}\n\n    // default value\n    Time() : base(){}\n    // Copy constructor\n    Time (const Time& t2) : base(t2){}\n    Time (const base& t2) : base(t2){}\n\n    /// Time is instantiated through named constructors\n    static Time\n        microseconds(double ms),\n        milliseconds(double ms),\n        seconds     (double s),\n        minutes     (double m),\n        hours       (double h),\n        days        (double d),\n        years       (double y),\n        centuries   (double c);\n\n    /// Length can return various units of time\n    double\n        microseconds() const,\n        milliseconds() const,\n        seconds     () const,\n        minutes     () const,\n        hours       () const,\n        days        () const,\n        years       () const,\n        centuries   () const;\n\n    /// alternatively, one can use various pre-defined lengths\n    static const Time\n        microsecond,\n        millisecond,\n        second,\n        minute,\n        hour,\n        day,\n        year,\n        century;\n\n    // current unix time (seconds+microseconds)\n    static Time now ();\n    // boost version\n    static boost::posix_time::ptime now(void *);\n\n    /// Human-readable string representation\n    std::string toString() const;\n};\n\n\n\n/**\n * @brief\n */\n\n/**\n * Mass\n * make metric <-> imperial a bit less prone to error\n *\n * @see Angle @see Length @see Temperature @see Energy\n * @see Area @see Force @see Speed @see Time\n */\nclass Mass final\n    : public _ignore::UnitOperators<Mass>\n{\n    typedef _ignore::UnitOperators<Mass> base;\n    friend class _ignore::UnitOperators<Mass>;\n\nprivate:\n\n    // value is always in kg\n    explicit Mass(double value) : base(value){}\n\npublic:\n    ~Mass(){}\n\n    // default value\n    Mass() : base(){}\n    // Copy constructor\n    Mass (const Mass& m2) : base(m2){}\n    Mass (const base& m2) : base(m2){}\n\n    // nice named constructors\n    static Mass\n        kilogrammes (double kg ),  kg  (double kg ),  kilograms (double kg ),\n        pounds      (double lbs),  lbs (double lbs),\n        tonnes      (double T  ),\n        longTonnes  (double LT ),\n        shortTonnes (double sT ),\n        stones      (double st ),\n        ounces      (double st );\n\n    // various return values\n    double\n        kilogrammes() const,    kg  () const,  kilograms () const,\n        pounds     () const,    lbs () const,\n        tonnes     () const,\n        longTonnes () const,\n        shortTonnes() const,\n        stones     () const,\n        ounces     () const;\n\n    // constants\n    static const Mass\n        kilo,\n        pound,\n        tonne,\n        longTonne,\n        shortTonne,\n        stone,\n        ounce;\n\n    // Human-readable string representation\n    std::string toString() const;\n};\n\n\n\n/**\n * @brief\n */\n\n/**\n * Temperature\n *\n * @see Angle @see Length @see Mass @see Energy\n * @see Area @see Force @see Speed @see Time\n */\nclass Temperature final\n    : public _ignore::UnitOperators<Temperature>\n{\n    typedef _ignore::UnitOperators<Temperature> base;\n    friend class _ignore::UnitOperators<Temperature>;\n\nprivate:\n\n    // value is always in K\n    // NOTE: ensure temperature is POSITIVE\n    explicit Temperature(double value) : base(value<0.0?0.0:value) {}\n\npublic:\n   ~Temperature(){}\n\n    // default value\n    Temperature() : base(){}\n    // copy constructor\n    Temperature (const Temperature& T2) : base(T2){}\n    Temperature (const base&        T2) : base(T2){}\n\n    // nice named constructors\n    static Temperature\n        kelvin     (double K),\n        celsius    (double C),\n        fahrenheit (double F);\n\n    // various return values\n    double\n        kelvin     () const,\n        celsius    () const,\n        fahrenheit () const;\n\n    // constants\n    static const Temperature\n        K, // ZERO kelvin\n        C, // ZERO celcius\n        F; // ZERO fahrenheit\n\n    // NOTE: negative temperatures do not exist; exclude unary minus operator\n    Temperature& operator-();\n\n    // cast operators\n    operator Energy() const;\n\n    // Human-readable string representation\n    std::string toString() const;\n};\n\n\n\n/// Combined unit classes / operations\n\n\n/// Area = Length * Length\nclass Area final\n    : public _ignore::UnitOperators<Area>\n{\n    typedef _ignore::UnitOperators<Area> base;\n    friend class _ignore::UnitOperators<Area>;\n\nprivate:\n    // value is always in m²\n    explicit Area (double value) : base(value){}\n\npublic:\n   ~Area(){}\n\n    // default value\n    Area() : base(){}\n    // copy constructor\n    Area (const Area& E2) : base(E2){}\n    Area (const base& E2) : base(E2){}\n\n    // nice named constructors\n    static Area\n        squareMeters     (double m2  ),    m2 (double m2),\n        squareKilometers (double m2  ),   km2 (double km2),\n        squareMillimeters(double m2  ),   mm2 (double mm2),\n        ares             (double are ),\n        acres            (double acre),\n        hectares         (double ha  );\n\n    // various return values\n    double\n        squareMeters     () const,    m2 () const,\n        squareKilometers () const,   km2 () const,\n        squareMillimeters() const,   mm2 () const,\n        ares             () const,\n        acres            () const,\n        hectares         () const;\n\n    // constants\n    const static Area\n        squareMeter,\n        squareKilometer,\n        squareMillimeter,\n        are,\n        acre,\n        hectare;\n\n    // Human-readable string representation\n    std::string toString() const;\n\n};\n\n\n/// Volume = Length * Length * Length\nclass Volume final\n    : public _ignore::UnitOperators<Volume>\n{\n    typedef _ignore::UnitOperators<Volume> base;\n    friend class _ignore::UnitOperators<Volume>;\n\nprivate:\n    // value is always in m³\n    explicit Volume (double value) : base(value){}\n\npublic:\n   ~Volume(){}\n\n    // default value\n    Volume() : base(){}\n    // copy constructors\n    Volume (const Volume& V2) : base(V2){}\n    Volume (const base&   V2) : base(V2){}\n\n    // nice named constructors\n    static Volume\n        cubicKilometers (double km3  ),\n        cubicMeters     (double  m3  ),\n        cubicCentimeters(double cm3  ),\n        cubicMillimeters(double mm3  ),\n        cubicFeet       (double ft3  ),\n        cubicInches     (double in3  ),\n        litres          (double l    ),\n        gallons         (double g    ), // imperial gallon\n        USgallons       (double g    ); // US gallon\n\n    // various return values\n    double\n        cubicKilometers  () const,\n        cubicMeters      () const,\n        cubicCentimeters () const,\n        cubicMillimeters () const,\n        cubicFeet        () const,\n        cubicInches      () const,\n        litres           () const,\n        gallons          () const,\n        USgallons        () const;\n\n    // constants\n    const static Volume\n        cubicKilometer,    km3,\n        cubicMeter,         m3,\n        cubicCentimeter,   cm3,\n        cubicMillimeter,   mm3,\n        cubicFoot,         ft3,\n        cubicInch,         in3,\n        litre,               l,\n        gallon,              g,\n        USgallon,           Ug;\n\n    // Human-readable string representation\n    std::string toString() const;\n\n};\n\n/// Energy = Mass * Length / Time\nclass Energy final\n    : public _ignore::UnitOperators<Energy>\n{\n    typedef _ignore::UnitOperators<Energy> base;\n    friend class _ignore::UnitOperators<Energy>;\n\nprivate:\n    // value is always in Joules\n    explicit Energy (double value) : base(value){}\n\npublic:\n   ~Energy(){}\n\n    // default value\n    Energy() : base(){}\n    // copy constructor\n    Energy (const Energy& E2) : base(E2){}\n    Energy (const base&   E2) : base(E2){}\n\n    // nice named constructors\n    static Energy\n        joules        (double J),\n        electronVolts (double eV);\n\n    // various return values\n    double\n        joules       () const,\n        electronVolts() const;\n\n    // handy constants\n    static const Energy\n        joule       ,   J,\n        electronVolt,   eV;\n\n    // cast operators\n    operator Length()       const; // to wavelength\n    operator Temperature () const; // to temperature\n\n    // Human-readable string representation\n    std::string toString() const;\n};\n\n\n\n/// Force = Mass * Length / Time / Time\nclass Force final\n    : public _ignore::UnitOperators<Force>\n{\n    typedef _ignore::UnitOperators<Force> base;\n    friend class _ignore::UnitOperators<Force>;\n\nprivate:\n\n    // value is always in Newtons\n    explicit Force(double value) : base(value){}\n\npublic:\n   ~Force(){}\n\n    // default value\n    Force() : base(){}\n    // copy constructor\n    Force (const Force& F2) : base(F2){}\n    Force (const base&  F2) : base(F2){}\n\n    // nice named constructors\n    static Force\n        newtons (double N),  N (double n);\n\n    // various return values\n    double\n        newtons() const,   N () const;\n\n    // constants\n    static const Force\n        newton;\n\n    /// Human-readable string representation\n    std::string toString() const;\n};\n\n\n/// Speed = Length / Time\nclass Speed final\n    : public _ignore::UnitOperators<Speed>\n{\n    typedef _ignore::UnitOperators<Speed> base;\n    friend class _ignore::UnitOperators<Speed>;\n\nprivate:\n\n    // value is always given in m/s\n    explicit Speed (double value) : base(value){}\n\npublic:\n    ~Speed(){}\n\n    // default value\n    Speed() : base(){}\n    // copy  constructor\n    Speed (const Speed& s2) : base(s2){}\n    Speed (const base&  s2) : base(s2){}\n\n    // nice named constructors\n    static Speed\n        metersPerSecond     (double mps),    mps  (double mps),\n        knots               (double knt),    kt   (double knt),\n        kilometersPerHour   (double kph),    kph  (double kph),\n        kilometersPerSecond (double kps),    kps  (double kps),\n        milesPerHour        (double mph),    miph (double mph),\n        milesPerSecond      (double mps),    mips (double mps);\n\n    // various return values\n    double\n        metersPerSecond     () const,    mps  () const,\n        knots               () const,    kt   () const,\n        kilometersPerHour   () const,    kph  () const,\n        kilometersPerSecond () const,    kps  () const,\n        milesPerHour        () const,    miph () const,\n        milesPerSecond      () const,    mips () const;\n\n    // constants\n    static const Speed\n        meterPerSecond    ,\n        knot              ,\n        kilometerPerHour  ,\n        kilometerPerSecond,\n        milePerHour       ,\n        milePerSecond     ,\n\n        of_light          , c;\n\n    // NOTE: in principle, speed is a magnitude and thus always positive.\n    // However, negative speeds are used, so include unary minus operator.\n\n    // Human-readable string representation\n    std::string toString() const;\n};\n\n\n/// Pressure = Force / Area\nclass Pressure final\n    : public _ignore::UnitOperators<Pressure>\n{\n    typedef _ignore::UnitOperators<Pressure> base;\n    friend class _ignore::UnitOperators<Pressure>;\n\nprivate:\n\n     // value is always given in N/m²\n    explicit Pressure (double value) : base(value){}\n\n\npublic:\n    ~Pressure(){}\n\n    // default value\n    Pressure() : base(){}\n    // copy  constructors\n    Pressure (const Pressure& p2) : base(p2){}\n    Pressure (const base&     p2) : base(p2){}\n\n    // nice named constructors\n    static Pressure\n        pascals     (double Pa ),    Pa (double Pa ),\n        kiloPascals (double kPa),   kPa (double kPa),\n        bars        (double bar),\n        atmospheres (double atm),   atm(double atm);\n\n    // various return values\n\n    // constants\n\n    /// Human-readable string representation\n    std::string toString() const;\n};\n\n/// Density = Mass / Volume\nclass Density final\n    : public _ignore::UnitOperators<Density>\n{\n    typedef _ignore::UnitOperators<Density> base;\n    friend class _ignore::UnitOperators<Density>;\n\nprivate:\n\n     // value is always given in kg/m³\n    explicit Density (double value) : base(value){}\n\npublic:\n    ~Density(){}\n\n    // default value\n    Density() : base(){}\n    // copy  constructors\n    Density (const Density& d2) : base(d2){}\n    Density (const base&    d2) : base(d2){}\n\n    // nice named constructors\n    static Density\n        kilogramsPerCubicMeter  (double kgm3),\n        gramsPerCubicCentimeter (double gcm3),\n        tonnesPerCubicMeter     (double Mgm3),\n        kilogramsPerLiter       (double kgl ),\n        poundsPerCubicInch      (double lbscuin),\n        poundsPerCubicFoot      (double lbscuft);\n\n    // various return values\n    double\n        kilogramsPerCubicMeter  (),\n        gramsPerCubicCentimeter (),\n        tonnesPerCubicMeter     (),\n        kilogramsPerLiter       (),\n        poundsPerCubicInch      (),\n        poundsPerCubicFoot      ();\n\n\n    // constants\n    static const Density\n        kgm3,    kilogramPerCubicMeter,\n        gcm3,    gramPerCubicCentimeter,\n        Mgm3,    tonPerCubicMeter,         Tm3,\n        kgl ,    kilogramPerLiter,\n        lbscuin, poundPerCubicInch,        lbsin,\n        lbscuft, poundPerCubicFoot,        lbsft;\n\n    /// Human-readable string representation\n    std::string toString() const;\n\n};\n\n\n/// overload various relevant math operators\n\n// Angle\n// ---------------------------------\n\n// wrap value into [-pi +pi) / [-180 +180)\nAngle wrap_posneg(const Angle& a);\n\n// wrap value into [0 2pi) / [0 360)\nAngle wrap_positive(const Angle& a);\n\n// regular trig functions\ndouble sin  (const Angle& a);\ndouble cos  (const Angle& a);\ndouble tan  (const Angle& a);\n// FIXME: namespace conflict:\n//double csc  (const Angle& a);\ndouble sec  (const Angle& a);\ndouble cot  (const Angle& a);\n\n// hyperbolic trig functions\ndouble sinh (const Angle& a);\ndouble cosh (const Angle& a);\ndouble tanh (const Angle& a);\ndouble csch (const Angle& a);\ndouble sech (const Angle& a);\ndouble coth (const Angle& a);\n\n// Inverse trig functions need to be overloaded by return type,\n// which is \"obviously\" not possible. Therefore, define a few\n// leaf helper classes:\n\nnamespace _ignore\n{\n    class Invtrig : public UnitOperators<Angle> {\n    protected:\n        double value;\n    public:\n        operator double();\n        operator Angle ();\n        std::string toString() const; // NOTE: leave unimplemented\n    };\n}\n\n// regular inverse functions\nclass Asin   final : public _ignore::Invtrig { public: Asin (double value); };\nclass Acos   final : public _ignore::Invtrig { public: Acos (double value); };\nclass Atan   final : public _ignore::Invtrig { public: Atan (double value); };\nclass Atan2  final : public _ignore::Invtrig { public: Atan2(double y, double x); };\nclass Acsc   final : public _ignore::Invtrig { public: Acsc (double value); };\nclass Asec   final : public _ignore::Invtrig { public: Asec (double value); };\nclass Acot   final : public _ignore::Invtrig { public: Acot (double value); };\n\n// hyperbolic inverse functions\nclass Asinh  final : public _ignore::Invtrig { public: Asinh(double value); };\nclass Acosh  final : public _ignore::Invtrig { public: Acosh(double value); };\nclass Atanh  final : public _ignore::Invtrig { public: Atanh(double value); };\nclass Acsch  final : public _ignore::Invtrig { public: Acsch(double value); };\nclass Asech  final : public _ignore::Invtrig { public: Asech(double value); };\nclass Acoth  final : public _ignore::Invtrig { public: Acoth(double value); };\n\n\n/// Make  std::cout << {class}  work\nstd::ostream& operator<<(std::ostream& target, const _ignore::Unit& U);\n\n\n/// Make some cross-unit transformations valid\n\n// sqrt(Area) = Length\nLength sqrt(const Area& A);\n\n// Length * Length = Area\nArea   operator*(const Length& L1, const Length& L2);\n\n// Length * Area = Volume\nVolume operator*(const Length&  L, const Area&   A);\nVolume operator*(const Area&    A, const Length& L);\n\n// Mass / Volume = Density\nDensity operator/(const Mass&   M, const Volume& V);\n\n// Length / Time = Speed\nSpeed operator/ (const Length&  L, const Time&   t);\n\n// Speed * Time = Length\nLength operator*(const Speed&   s, const Time&   t);\nLength operator*(const Time&    t, const Speed&  s);\n\n// Length * Angle = (arc)Length\nLength operator*(const Length&  L, const Angle&  a);\nLength operator*(const Angle&   a, const Length& L);\n\n// Force * Length = Energy\nEnergy operator*(const Force&   F, const Length& L);\nEnergy operator*(const Length&  L, const Force&  F);\n\n// Force / Area = Pressure\nPressure operator/(const Force& F, const Area&   A);\n\n\n// Handy dandy physics utilities\n// (defined HERE because otherwise the unit classes are incomplete)\nnamespace physics\n{\n    // FIXME: (Rody Oldenhuis) DEPRECATED\n    // replaced by operator Length() in class Energy\n    inline double energy2wavelength(const double e) {\n        BOOST_ASSERT(e > 0);\n        return h*c/e;\n    }\n    inline Length energy2wavelength(const Energy& E){\n        BOOST_ASSERT(E > Energy::zero);\n        return Length::meters(h*c/E.joules());\n    }\n    // -----------------------------------------\n\n    // FIXME: (Rody Oldenhuis) DEPRECATED\n    // replaced by operator Energy() in class Length\n    inline double wavelength2energy(const double w) {\n        BOOST_ASSERT(w > 0);\n        return h*c/w;\n    }\n    inline Energy wavelength2energy(const Length& w) {\n        BOOST_ASSERT(w > Length::zero);\n        return Energy::joules(h*c/w.meters());\n    }\n    // -----------------------------------------\n\n    // FIXME: (Rody Oldenhuis) DEPRECATED\n    // replaced by operator Temperature() in class Energy\n    inline double energy2temperature(const double e) {\n        BOOST_ASSERT(e >= 0);\n        return e/k;\n    }\n    inline Temperature energy2temperature(const Energy& E) {\n        BOOST_ASSERT(E >= Energy::zero);\n        return Temperature::kelvin(E.joules()/k);\n    }\n    // -----------------------------------------\n\n    // FIXME: (Rody Oldenhuis) DEPRECATED\n    // replaced by operator Energy() in class Temperature\n    inline double temperature2energy(const double T) {\n        BOOST_ASSERT(T >= 0);\n        return T*k;\n    }\n    inline Energy temperature2energy(const Temperature& T) {\n        BOOST_ASSERT(T >= Temperature::zero);\n        return Energy::joules(T.kelvin()*k);\n    }\n    // -----------------------------------------\n}\n\n\n\n\n#endif\n\n\n\n", "meta": {"hexsha": "110ab1fbc74ccde06b840ec989e5c70189771a4e", "size": 34919, "ext": "hh", "lang": "C++", "max_stars_repo_path": "physics/old/PhysUnits.hh", "max_stars_repo_name": "rodyo/math_physics", "max_stars_repo_head_hexsha": "268581cf0dd2aa7e742523505ebf3c5026cf7fd2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "physics/old/PhysUnits.hh", "max_issues_repo_name": "rodyo/math_physics", "max_issues_repo_head_hexsha": "268581cf0dd2aa7e742523505ebf3c5026cf7fd2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "physics/old/PhysUnits.hh", "max_forks_repo_name": "rodyo/math_physics", "max_forks_repo_head_hexsha": "268581cf0dd2aa7e742523505ebf3c5026cf7fd2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.846092504, "max_line_length": 115, "alphanum_fraction": 0.5776224978, "num_tokens": 9106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.5428632831725051, "lm_q1q2_score": 0.42914988959851963}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2016 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifdef Cygwin\n// availability of std::to_string\n#define _GLIBCXX_USE_C99 1\n#endif\n\n#include <iostream>\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n#include \"dune/grid/uggrid.hh\"\n\n#include \"fem/gridmanager.hh\"\n#include \"fem/lagrangespace.hh\"\n//#include \"fem/hierarchicspace.hh\"\n#include \"utilities/kaskopt.hh\"\n#include \"utilities/gridGeneration.hh\" //  createUnitSquare\n\nusing namespace Kaskade;\n\n#include \"integrate-navierStokes.hh\"\n//#include \"integrate-Limex.hh\"\n\n#include \"navierStokes.hh\"\n\n\nstruct Initial_1Value \n{\n  using Scalar = double;\n  static int const components = 1;\n  using ValueType = Dune::FieldVector<Scalar,components>;\n\n  Initial_1Value(int c): component(c) {}\n  \n  template <class Cell> int order(Cell const&) const { return std::numeric_limits<int>::max(); }\n  template <class Cell>\n  ValueType value(Cell const& cell,\n                  Dune::FieldVector<typename Cell::Geometry::ctype,Cell::dimension> const& localCoordinate) const \n  {\n    Dune::FieldVector<typename Cell::Geometry::ctype,Cell::Geometry::coorddimension> x = cell.geometry().global(localCoordinate);\n\n    if (component==0)               // vector u = (u_1,u_2)\n    {\n      std::cout << \"Error: wrong call of Initial_1Value\" << std::endl;\n      return 0;\n    }\n    else if (component==1)          // scalar p\n    {\n      return 0;\n    }\n    else\n      assert(\"wrong index!\\n\"==0);\n      \n    return 0;\n  }\n\nprivate:\n  int component;\n};\n\nstruct Initial_2Value \n{\n  using Scalar = double;\n  static int const components = 2;\n  using ValueType = Dune::FieldVector<Scalar,components>;\n\n  Initial_2Value(int c): component(c) {}\n  \n  template <class Cell> int order(Cell const&) const { return std::numeric_limits<int>::max(); }\n  template <class Cell>\n  ValueType value(Cell const& cell,\n                  Dune::FieldVector<typename Cell::Geometry::ctype,Cell::dimension> const& localCoordinate) const \n  {\n    Dune::FieldVector<typename Cell::Geometry::ctype,Cell::Geometry::coorddimension> x = cell.geometry().global(localCoordinate);\n\n    ValueType result(0);\n    if (component==0)                    // vector u = (u_1,u_2), concrete\n    {\n      return result;\n    }\n    else\n      assert(\"wrong index!\\n\"==0);\n      \n    return result;\n  }\n\nprivate:\n  int component;\n};\n\n\n\nint main(int argc, char *argv[])\n{\n  using namespace boost::fusion;\n\n\n  int verbosityOpt = 1;  // print to console if arguments are changed\n  bool dump = false; // do not write properties into file\n  std::unique_ptr<boost::property_tree::ptree> pt = getKaskadeOptions(argc, argv, verbosityOpt, dump);\n\n  std::cout << \"Start Navier-Stokes tutorial programm.\" << std::endl;\n\n  boost::timer::cpu_timer totalTimer;\n\n  constexpr int dim = 2; \n  \n  constexpr int uIdx  = 0;\n  constexpr int pIdx  = 1;\n   \n  constexpr double rho    = 1.0;\n  constexpr double lambda = 0.0;\n  constexpr double mu     = 0.01;   // ----> Reynold number Re = 100\n\n  using Grid = Dune::UGGrid<dim>;\n  using H1Space = FEFunctionSpace<ContinuousLagrangeMapper<double,Grid::LeafGridView> >;\n  //using H1Space = FEFunctionSpace<ContinuousHierarchicMapper<double,Grid::LeafGridView> >;\n  using Spaces = vector<H1Space const*,H1Space const*>;\n  using VariableDescriptions = vector<Variable<SpaceIndex<1>,Components<2>,VariableId<uIdx> >,\n                                      Variable<SpaceIndex<0>,Components<1>,VariableId<pIdx> > >;\n  using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;\n  using CoefficientVectors = VariableSet::CoefficientVectorRepresentation<>::type;\n  using Functional = NavierStokesFunctional<double,VariableSet>;\n\n  constexpr int nvars = Functional::AnsatzVars::noOfVariables;\n  constexpr int neq   = Functional::TestVars::noOfVariables;\n \n  std::cout << std::endl;\n  std::cout << \"density rho     = \"  << rho    << std::endl;\n  std::cout << \"viscosity mu    = \"  << mu     << std::endl;\n\n  double dt, dtMax, tStart, tEnd, rTolT, aTolT, rTolX, aTolX, writeInterval;\n\n  tStart = 0.0; \n  \n  // command line parameters\n  int verbosity = getParameter(pt, \"verbosity\", 1);\n  int extrapolOrder = getParameter(pt, \"extrapolOrder\", 0);\n  int maxTimeSteps  = getParameter(pt, \"maxTimeSteps\", 51);\n\n  int refinements = getParameter(pt, \"refinements\", 6);\n  int order = getParameter(pt, \"order\", 2); // order for velocity space, order for pressure space is (order-1)\n  std::string empty;\n\n  std::string s(\"names.type.\");\n  s += getParameter(pt, \"solver.type\", empty);\n  bool direct = getParameter(pt, s, 0);\n    \n  s = \"names.direct.\" + getParameter(pt, \"solver.direct\", empty);\n  DirectType directType = static_cast<DirectType>(getParameter(pt, s, 4));  // 4: DirectType::UMFPACK3264\n\n  std::cout << std::endl;\n  std::cout << \"order of extrapolation in Limex : \" << extrapolOrder << std::endl;\n  std::cout << \"original mesh shall be refined  : \" << refinements << \" times\" << std::endl;\n  std::cout << \"discretization order in space   : \" << order << std::endl;\n  //std::cout << \"direct solver                   : \" << directType << std::endl;\n  std::cout << std::endl;\n\n  boost::timer::cpu_timer gridTimer;\n  // grid generation\n  Dune::FieldVector<double,dim> x0(0.0), length(1.0);\n  //GridManager<Grid> gridManager( createRectangle<Grid>(x0,length,0.5));   // mesh 2\n  GridManager<Grid> gridManager( createRectangle<Grid>(x0,length,1.0));     // mesh 1\n  gridManager.globalRefine(refinements);\n\n  std::cout << \"Initial grid: trs=\" << gridManager.grid().size(0) \n            << \" eds=\" << gridManager.grid().size(1) << \" pts=\" << gridManager.grid().size(2) \n            << std::endl << std::endl;\n  //std::cout << \"computing time for generation of initial mesh: \" << boost::timer::format(gridTimer.elapsed());\n\n\n  // construct involved spaces.\n\n  H1Space pressureSpace(gridManager,gridManager.grid().leafGridView(),order-1);\n  H1Space velocitySpace(gridManager,gridManager.grid().leafGridView(),order);\n\n\n  Spaces spaces(&pressureSpace,&velocitySpace);\n\n  // construct variable list.\n  // concrete 0: u = (u_1,u_2), velocity \n  //          1: p              pressure\n  std::string varNames[2] = { \"u\", \"p\" };\n\n  VariableSet variableSet(spaces,varNames);\n\n\n  // construct variational functional.\n  Functional F(tStart,rho,lambda,mu);\t\n\n  VariableSet::VariableSet x(variableSet);\n  VariableSet::VariableSet dx(variableSet);\n\n  F.time(tStart);\n  x = 0; \n  F.scaleInitialValue<uIdx>(Initial_2Value(uIdx),x);      // u\n  F.scaleInitialValue<pIdx>(Initial_1Value(pIdx),x);      // p\n  \n  std::cout << \"nvars = \" << nvars << std::endl;\n  std::cout << \"  neq = \" << neq   << std::endl;\n\n  \n  tStart = 0.0;\n  tEnd   = 800.0;           \t\n  dt     = 2e-2; \t\t\n  dtMax  = 2e-2; \n  \n  std::cout << \"start time = \"   << tStart       << std::endl;\n  std::cout << \"final time = \"   << tEnd         << std::endl;\n  std::cout << \"step size = \"    << dt           << std::endl;\n  std::cout << \"maxTimeSteps = \" << maxTimeSteps << std::endl;\n  std::cout << std::endl;\n  \n  rTolT = 1.0e+30;\t\t//2e-5;\t\t//1e-5/8.0;\n  aTolT = 1.0e+30;\t\t//2e-5;\t\t//1e-5/8.0;\n  rTolX = 1.0e+12;\t\t//1e-4;   1e-5*2.0;\n  aTolX = 1.0e+12;\t\t//1e-4;   1e-5*2.0;\n\n  std::cout << \"aTolT = \" << aTolT << std::endl;\n  std::cout << \"rTolT = \" << rTolT << std::endl;\n  std::cout << \"aTolX = \" << aTolX << std::endl;\n  std::cout << \"rTolX = \" << rTolX << std::endl;\n  std::cout << std::endl;\n\n  std::vector<VariableSet::VariableSet> solutions;\n  \n  x = integrate(gridManager,F,variableSet,spaces,\n                dt,dtMax,tEnd,maxTimeSteps,rTolT,aTolT,rTolX,aTolX,extrapolOrder,\n                std::back_inserter(solutions),writeInterval,x,DirectType::MUMPS,\n                verbosity);\n\n\n  //writeVTKFile(gridManager.grid().leafGridView(),x,\"navierStokes\", IoOptions(), order);\n  //std::cout << \"graphical output finished, data in VTK format is written into file stokes.vtu \\n\";\n\n  std::cout << \"total computing time: \" << boost::timer::format(totalTimer.elapsed()) << \"\\n\";\n  std::cout << \"End Navier-Stokes tutorial program\" << std::endl;\n}\n", "meta": {"hexsha": "7e8bdbd355bb94515f87ae2f4482232b9294ef64", "size": 8850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/instationary_NavierStokes/navierStokes.cpp", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/tutorial/instationary_NavierStokes/navierStokes.cpp", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/tutorial/instationary_NavierStokes/navierStokes.cpp", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 35.2589641434, "max_line_length": 129, "alphanum_fraction": 0.6025988701, "num_tokens": 2530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.6224593171945416, "lm_q1q2_score": 0.4290647115084066}}
{"text": "// Copyright (c) 2018 Steven Watanabe\n//\n// Distributed under the Boost Software License Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_UNITS2_DIMENSIONS_HPP_INCLUDED\n#define BOOST_UNITS2_DIMENSIONS_HPP_INCLUDED\n\n#include <boost/units2/unit.hpp>\n#include <boost/units2/def.hpp>\n#include <boost/units2/dimensions.hpp>\n#include <ratio>\n\nnamespace boost {\nnamespace units2 {\nnamespace si {\n\nBOOST_UNITS2_DEF(meter,length);\nBOOST_UNITS2_DEF(gram,mass);\nBOOST_UNITS2_DEF(second,time);\nBOOST_UNITS2_DEF(kelvin,temperature);\nBOOST_UNITS2_DEF(mole,amount);\nBOOST_UNITS2_DEF(ampere,current);\nBOOST_UNITS2_DEF(candela,luminous_intensity);\n\n// Extra units that are techically dimensionless\nBOOST_UNITS2_DEF(radian,angle);\nBOOST_UNITS2_DEF(steradian,solid_angle);\n\n// kilograms are actually the base unit, but for the sake\n// of naming consistency, we're defining it this way, since\n// it doesn't change the behavior significantly.\ninline constexpr const auto kilogram = std::kilo() * gram;\n\ninline constexpr const auto hertz = pow<-1>(second);\ninline constexpr const auto newton = meter*kilogram/pow<2>(second);\ninline constexpr const auto pascal = newton/pow<2>(meter);\ninline constexpr const auto joule = newton*meter;\ninline constexpr const auto watt = joule/second;\ninline constexpr const auto couloumb = second * ampere;\ninline constexpr const auto volt = watt/ampere;\ninline constexpr const auto farad = couloumb/volt;\ninline constexpr const auto ohm = volt/ampere;\ninline constexpr const auto siemens = ampere/volt;\ninline constexpr const auto weber = volt*second;\ninline constexpr const auto tesla = weber/pow<2>(meter);\ninline constexpr const auto henry = weber/ampere;\n// celsius = kelvin + std::ratio<27315,100>\ninline constexpr const auto lumen = candela*steradian;\ninline constexpr const auto lux = lumen/pow<2>(meter);\ninline constexpr const auto becquerel = pow<-1>(second);\ninline constexpr const auto gray = joule/kilogram;\ninline constexpr const auto sievert = joule/kilogram;\ninline constexpr const auto katal = mole/second;\n\n}\n}\n}\n\n#endif\n", "meta": {"hexsha": "ea0dcb6d40ba781bdc183c35ccb17f00ca63f03f", "size": 2123, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/units2/si.hpp", "max_stars_repo_name": "swatanabe/cppnow17-units", "max_stars_repo_head_hexsha": "e317aff5255afd11e3ebcd759ae3c824f6c95260", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T20:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-21T21:21:46.000Z", "max_issues_repo_path": "include/boost/units2/si.hpp", "max_issues_repo_name": "swatanabe/cppnow17-units", "max_issues_repo_head_hexsha": "e317aff5255afd11e3ebcd759ae3c824f6c95260", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/units2/si.hpp", "max_forks_repo_name": "swatanabe/cppnow17-units", "max_forks_repo_head_hexsha": "e317aff5255afd11e3ebcd759ae3c824f6c95260", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2419354839, "max_line_length": 67, "alphanum_fraction": 0.785209609, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.42892566000872273}}
{"text": "/* Copyright (c) 2016 - 2020, the adamantine authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#ifndef ELECTRON_BEAM_HH\n#define ELECTRON_BEAM_HH\n\n#include <deal.II/base/function_parser.h>\n\n#include <boost/property_tree/ptree.hpp>\n\nnamespace adamantine\n{\n/**\n * This structure stores all the physical properties necessary to define an\n * electron beam.\n */\nstruct BeamProperty\n{\npublic:\n  /**\n   * Absolute penetration of the electron beam into the material where 99% of\n   * the beam energy is absorbed.\n   */\n  double depth;\n  /**\n   * Energy conversion efficiency on the surface.\n   */\n  double energy_conversion_eff;\n  /**\n   * Efficiency of beam control.\n   */\n  double control_eff;\n  /**\n   * Square of the beam diameter.\n   */\n  double diameter_squared;\n  /**\n   * Maximum power of the beam.\n   */\n  double max_power;\n};\n\n/**\n * This class describes the evolution of an electron beam source.\n */\ntemplate <int dim>\nclass ElectronBeam : public dealii::Function<dim>\n{\npublic:\n  /**\n   * Constructor.\n   * \\param[in] database requires the following entries:\n   *   - <B>energy_conversion_efficiency</B>: double in \\f$[0,1]\\f$\n   *   - <B>control_efficiency</b>: double in \\f$[0,1]\\f$\n   *   - <B>depth</B>: double in \\f$[0,\\infty)\\f$\n   *   - <B>diameter</B>: double in \\f$[0,\\infty)\\f$\n   *   - <B>max_power</B>: double in \\f$[0, \\infty)\\f$ [optional: if not\n   *   defined, <i>current</i> and <i>voltage</i> need to be defined]\n   *   - <B>current</B>: double in \\f$[0, \\infty)\\f$ [optional: if defined\n   *   <i>voltage</i> should be defined too, if not defined <i>max_power</i>\n   *   should be defined]\n   *   - <B>voltage</B>: double in \\f$[0,\\infty)\\f$ [optional: if defined\n   *   <i>current</i> should be defined too, if not defined <i>max_power</i>\n   *   should be defined]\n   *   - <B>input_file</B>: name of the csv file that contains the successive\n   *   position of the electron beam [optional: if not defined then\n   *   <i>abscissa</i> and, in 3D, <i>ordinate</i> need to be defined]\n   *   - <B>delimiter</B>: delimiting character used in <i>input_file</i>\n   *   [required if <i>input_file</i> is defined]\n   *   - <B>abscissa</B>: string, abscissa of the beam as a function of time\n   *   (e.g. \"(t-1) * (t-2)\") [optional: need to be defined if <i>input_file</i>\n   *   is not defined]\n   *   - <B>ordinate</B>: string, ordinate of the beam as a function of time\n   *   [required only for three dimensional calculation and if <i>input_file</i>\n   *   is not defined]\n   */\n  ElectronBeam(boost::property_tree::ptree const &database);\n\n  /**\n   * Set the maximum height of the domain. This is the height at which the\n   * electron beam penetrate the material.\n   */\n  void set_max_height(double height);\n\n  /**\n   * Compute the heat source at a given point at the current time.\n   */\n  double value(dealii::Point<dim> const &point,\n               unsigned int const component = 0) const override;\n\n  /**\n   * Reset the current time and the position to the last saved state.\n   */\n  void rewind_time();\n\n  /**\n   * Save the current time and the position in the list of successive positions\n   * of the beam.\n   */\n  void save_time();\n\nprivate:\n  /**\n   * Flag is true if the beam is a point source of which the position is read\n   * from a\n   * file.\n   */\n  bool _is_point_source;\n\n  /**\n   * Height of the domain.\n   */\n  double _max_height;\n  /**\n   * Structure of the physical properties of the electron beam.\n   */\n  BeamProperty _beam;\n  /**\n   * Function that describes the position of the beam on the surface.\n   */\n  std::array<std::unique_ptr<dealii::Function<1>>, dim - 1> _position;\n};\n\ntemplate <int dim>\ninline void ElectronBeam<dim>::set_max_height(double height)\n{\n  _max_height = height;\n}\n} // namespace adamantine\n\n#endif\n", "meta": {"hexsha": "2eddcd598d29de5b7aa291e8686a5594e87f9974", "size": 3946, "ext": "hh", "lang": "C++", "max_stars_repo_path": "source/ElectronBeam.hh", "max_stars_repo_name": "stvdwtt/adamantine", "max_stars_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/ElectronBeam.hh", "max_issues_repo_name": "stvdwtt/adamantine", "max_issues_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/ElectronBeam.hh", "max_forks_repo_name": "stvdwtt/adamantine", "max_forks_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0147058824, "max_line_length": 80, "alphanum_fraction": 0.6561074506, "num_tokens": 1107, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.42892566000872273}}
{"text": "/**\r\n *                       _________ _______   __\r\n *                      /  _/ ___// ____/ | / /\r\n *                      / / \\__ \\/ __/ /  |/ /\r\n *                    _/ / ___/ / /___/ /|  /\r\n *                   /___//____/_____/_/ |_/\r\n *\r\n *  Isentropic model - ETH Zurich\r\n *  Copyright (C) 2016  Fabian Thuering (thfabian@student.ethz.ch)\r\n *\r\n *  This file is distributed under the MIT Open Source License. See\r\n *  LICENSE.TXT for details.\r\n */\r\n\r\n#define _USE_MATH_DEFINES\r\n#include <cmath>\r\n\r\n#include <Isen/Boundary.h>\r\n#include <Isen/Logger.h>\r\n#include <Isen/Output.h>\r\n#include <Isen/MeteoUtils.h>\r\n#include <Isen/Progressbar.h>\r\n#include <Isen/Solver.h>\r\n#include <Isen/Timer.h>\r\n\r\n#ifdef ISEN_PYTHON\r\n#include <boost/python.hpp>\r\n#endif\r\n\r\nISEN_NAMESPACE_BEGIN\r\n\r\nSolver::Solver(const std::shared_ptr<NameList>& namelist, Output::ArchiveType archiveType)\r\n{\r\n    // Copy NameList\r\n    namelist_ = std::make_shared<NameList>(*namelist);\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    Timer t;\r\n    LOG() << \"Allocating memory ... \" << logger::flush;\r\n\r\n    try\r\n    {\r\n        //-------------------------------------------------\r\n        // Define physical fields\r\n        //-------------------------------------------------\r\n\r\n        // Topography\r\n        topo_ = VectorXf::Zero(nxb);\r\n\r\n        // Horizontal velocity\r\n        zhtold_ = zhtnow_ = MatrixXf::Zero(nxb, nz1);\r\n\r\n        // Horizontal velocity\r\n        uold_ = unow_ = unew_ = MatrixXf::Zero(nxb1, nz);\r\n\r\n        // Isentropic density\r\n        sold_ = snow_ = snew_ = MatrixXf::Zero(nxb, nz);\r\n\r\n        // Montgomery potential\r\n        mtg_ = mtgnew_ = MatrixXf::Zero(nxb, nz);\r\n        mtg0_ = VectorXf::Zero(nz);\r\n\r\n        // Exner function\r\n        exn_ = MatrixXf::Zero(nxb, nz1);\r\n        exn0_ = VectorXf::Zero(nz1);\r\n\r\n        // Pressure\r\n        prs_ = MatrixXf::Zero(nxb, nz1);\r\n        prs0_ = VectorXf::Zero(nz1);\r\n\r\n        // Height-dependent diffusion coefficient\r\n        tau_ = VectorXf::Zero(nz);\r\n\r\n        // Upstream profile for theta\r\n        th0_ = VectorXf::Zero(nz1);\r\n\r\n        if(imoist)\r\n        {\r\n            // Precipitation\r\n            prec_ = VectorXf::Zero(nxb);\r\n\r\n            // Accumulated precipitation\r\n            tot_prec_ = VectorXf::Zero(nxb);\r\n\r\n            // Specific humidity\r\n            qvold_ = qvnow_ = qvnew_ = MatrixXf::Zero(nxb, nz);\r\n\r\n            // Specific cloud water content\r\n            qcold_ = qcnow_ = qcnew_ = MatrixXf::Zero(nxb, nz);\r\n\r\n            // Specific rain water content\r\n            qrold_ = qrnow_ = qrnew_ = MatrixXf::Zero(nxb, nz);\r\n\r\n            // Temperature\r\n            temp_ = MatrixXf::Zero(nxb, nz1);\r\n\r\n            // Parametrization\r\n            if(imicrophys == 1)\r\n                kessler_ = std::make_shared<Kessler>(namelist_);\r\n\r\n            if(imicrophys == 2)\r\n            {\r\n                // Rain-droplet number density\r\n                nrold_ = nrnow_ = nrnew_ = MatrixXf::Zero(nxb, nz);\r\n\r\n                // Cloud-droplet number density\r\n                ncold_ = ncnow_ = ncnew_ = MatrixXf::Zero(nxb, nz);\r\n            }\r\n\r\n            if(idthdt)\r\n            {\r\n                // Latent heating\r\n                dthetadt_ = MatrixXf::Zero(nxb, nz1);\r\n            }\r\n        }\r\n\r\n        //-------------------------------------------------\r\n        // Define fields at lateral boundaries\r\n        //-------------------------------------------------\r\n        tbnd1_ = tbnd2_ = VectorXf::Zero(1);\r\n\r\n        // Isentropic density\r\n        sbnd1_ = sbnd2_ = VectorXf::Zero(nz);\r\n\r\n        // Horizontal velocity\r\n        ubnd1_ = ubnd2_ = VectorXf::Zero(nz);\r\n\r\n        if(imoist)\r\n        {\r\n            // Specific humidity\r\n            qvbnd1_ = qvbnd2_ = VectorXf::Zero(nz);\r\n\r\n            // Specific cloud water content\r\n            qcbnd1_ = qcbnd2_ = VectorXf::Zero(nz);\r\n\r\n            // Specific rain water content\r\n            qrbnd1_ = qrbnd2_ = VectorXf::Zero(nz);\r\n\r\n            if(imicrophys == 2)\r\n            {\r\n                // Rain-droplet number density\r\n                nrbnd1_ = nrbnd2_ = VectorXf::Zero(nz);\r\n\r\n                // Cloud-droplet number density\r\n                ncbnd1_ = ncbnd2_ = VectorXf::Zero(nz);\r\n            }\r\n\r\n            if(idthdt)\r\n            {\r\n                // Latent heating\r\n                dthetadtbnd1_ = dthetadtbnd2_ = VectorXf::Zero(nz1);\r\n            }\r\n        }\r\n\r\n        //-------------------------------------------------\r\n        // Define scalar fields\r\n        //-------------------------------------------------\r\n        dtdx_ = dt / dx;\r\n        topofact_ = 1.0;\r\n    }\r\n    catch(std::bad_alloc&)\r\n    {\r\n        LOG() << logger::failed;\r\n        throw IsenException(\"out of memory\");\r\n    }\r\n    LOG_SUCCESS(t);\r\n\r\n    // Allocate space for output\r\n    output_ = std::make_shared<Output>(namelist_, archiveType);\r\n}\r\n\r\nvoid Solver::init() noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    // Make upstream profiles and initial conditions\r\n    //-------------------------------------------------------------\r\n    const double g2 = g * g;\r\n\r\n    Timer t;\r\n    LOG() << \"Create initial profile ... \" << logger::flush;\r\n\r\n    VectorXf z0 = VectorXf::Zero(nz1);\r\n\r\n    VectorXf rh0, qv0, qc0, qr0, nc0, nr0;\r\n    if(imoist)\r\n    {\r\n        rh0 = VectorXf::Zero(nz);\r\n\r\n        qv0 = VectorXf::Zero(nz);\r\n        qc0 = VectorXf::Zero(nz);\r\n        qr0 = VectorXf::Zero(nz);\r\n\r\n        if(imicrophys == 2)\r\n        {\r\n            nc0 = VectorXf::Zero(nz);\r\n            nr0 = VectorXf::Zero(nz);\r\n        }\r\n    }\r\n\r\n    // Upstream profile for Brunt-Vaisalla frequency (unstaggered)\r\n    //------------------------------------------------------------\r\n    VectorXf bv0 = bv00 * VectorXf::Ones(nz1).array();\r\n\r\n    // Upstream profile of theta (staggered)\r\n    // -----------------------------------------------------------\r\n    th0_ = th00 * VectorXf::Ones(nz1).array() + dth * VectorXf::LinSpaced(nz1, 0, nz1 - 1).array();\r\n\r\n    // Upstream profile for Exner function and pressure (staggered)\r\n    //-------------------------------------------------------------\r\n    exn0_[0] = exn00;\r\n    for(int k = 1; k < nz1; ++k)\r\n        exn0_[k] = exn0_[k - 1]\r\n                   - (16 * g2 * (th0_[k] - th0_[k - 1]) / (pow2(bv0[k - 1] + bv0[k]) * pow2(th0_[k - 1] + th0_[k])));\r\n\r\n    for(int k = 0; k < nz1; ++k)\r\n        prs0_[k] = pref * std::pow(exn0_[k] / cp, cpdr);\r\n\r\n    // Upstream profile for geometric height (staggered)\r\n    //-------------------------------------------------------------\r\n    z0[0] = z00;\r\n    for(int k = 1; k < nz1; ++k)\r\n        z0[k] = z0[k - 1] + (8 * g * (th0_[k] - th0_[k - 1]) / (pow2(bv0[k - 1] + bv0[k]) * (th0_[k - 1] + th0_[k])));\r\n\r\n    // Upstream profile for Montgomery potential (unstaggered)\r\n    //-------------------------------------------------------------\r\n    mtg0_[0] = g * z0[0] + th00 * exn0_[0] + dth * exn0_[0] / 2.;\r\n\r\n    double mtg0old = mtg0_[0];\r\n    for(int k = 1; k < nz; ++k)\r\n    {\r\n        std::swap(mtg0_[k], mtg0old);\r\n        mtg0_[k] += dth * exn0_[k];\r\n    }\r\n\r\n    // Upstream profile for isentropic density (unstaggered)\r\n    //-------------------------------------------------------------\r\n    VectorXf s0 = -1. / g * (prs0_.tail(nz1 - 1) - prs0_.head(nz1 - 1)) / dth;\r\n\r\n    // Upstream profile for velocity (unstaggered)\r\n    //-------------------------------------------------------------\r\n    VectorXf u0 = u00 * VectorXf::Ones(nz).array();\r\n\r\n    if(ishear)\r\n    {\r\n        for(int k = 0; k < k_shl; ++k)\r\n            u0(k) = u00_sh;\r\n\r\n        for(int k = k_shl; k < k_sht; ++k)\r\n            u0(k) = u00_sh - (u00_sh - u00) * (k - k_shl) / (k_sht - k_shl);\r\n\r\n        for(int k = k_sht; k < nz; ++k)\r\n            u0(k) = u00;\r\n    }\r\n\r\n    // Upstream profile for moisture (unstaggered)\r\n    //-------------------------------------------------------------\r\n    if(imoist)\r\n    {\r\n        double rhmax = 0.98;\r\n        const int kc = 12;\r\n        const int kw = 10;\r\n\r\n        for(int k = kc - kw; k < (kc + kw - 1); ++k)\r\n        {\r\n            double cos_k = std::cos((std::abs((k + 1) - kc) / double(kw)) * M_PI * 0.5);\r\n            rh0[k] = rhmax * cos_k * cos_k;\r\n        }\r\n\r\n        for(int k = 0; k < nz; ++k)\r\n        {\r\n            qv0[k] = MeteoUtils::rrmixv1(0.5 * (prs0_[k] + prs0_[k + 1]) / 100,\r\n                                         0.5 * (th0_[k] / cp * exn0_[k] + th0_[k + 1] / cp * exn0_[k + 1]), rh0[k],\r\n                                         MeteoUtils::ERelative);\r\n        }\r\n\r\n        // Upstream profile for number densities(unstaggered)\r\n        //---------------------------------------------------------\r\n        if(imicrophys == 2)\r\n        {\r\n            for(int k = 0; k < nz; ++k)\r\n            {\r\n                nc0[k] = 0;\r\n                nr0[k] = 0;\r\n            }\r\n        }\r\n    }\r\n\r\n    // Initial conditions for isentropic density (sigma), velocity u, and\r\n    // moisture qv\r\n    //-------------------------------------------------------------\r\n    sold_ = s0.transpose().replicate(sold_.rows(), 1);\r\n    snow_ = s0.transpose().replicate(snow_.rows(), 1);\r\n    mtg_ = mtg0_.transpose().replicate(mtg_.rows(), 1);\r\n    mtgnew_ = mtg0_.transpose().replicate(mtgnew_.rows(), 1);\r\n    uold_ = u0.transpose().replicate(uold_.rows(), 1);\r\n    unow_ = u0.transpose().replicate(unow_.rows(), 1);\r\n\r\n    if(imoist)\r\n    {\r\n        qvold_ = qv0.transpose().replicate(qvold_.rows(), 1);\r\n        qvnow_ = qv0.transpose().replicate(qvnow_.rows(), 1);\r\n        qcold_ = qc0.transpose().replicate(qcold_.rows(), 1);\r\n        qcnow_ = qc0.transpose().replicate(qcnow_.rows(), 1);\r\n        qrold_ = qr0.transpose().replicate(qrold_.rows(), 1);\r\n        qrnow_ = qr0.transpose().replicate(qrnow_.rows(), 1);\r\n\r\n        // Droplet density for 2-moment scheme\r\n        if(imicrophys == 2)\r\n        {\r\n            ncold_ = nc0.transpose().replicate(ncold_.rows(), 1);\r\n            ncnow_ = nc0.transpose().replicate(ncnow_.rows(), 1);\r\n            nrold_ = nr0.transpose().replicate(nrold_.rows(), 1);\r\n            nrnow_ = nr0.transpose().replicate(nrnow_.rows(), 1);\r\n        }\r\n    }\r\n\r\n    LOG_SUCCESS(t);\r\n\r\n    // Save boundary values for the lateral boundary relaxation\r\n    //-------------------------------------------------------------\r\n    if(irelax)\r\n    {\r\n        LOG() << \"Saving lateral boundary values ... \" << logger::flush;\r\n        t.start();\r\n\r\n        sbnd1_ = snow_.row(0);\r\n        sbnd2_ = snow_.row(snow_.rows() - 1);\r\n\r\n        ubnd1_ = unow_.row(0);\r\n        ubnd2_ = unow_.row(unow_.rows() - 1);\r\n\r\n        if(imoist)\r\n        {\r\n            qvbnd1_ = qvnow_.row(0);\r\n            qvbnd2_ = qvnow_.row(qvnow_.rows() - 1);\r\n\r\n            qcbnd1_ = qcnow_.row(0);\r\n            qcbnd2_ = qcnow_.row(qcnow_.rows() - 1);\r\n\r\n            qrbnd1_ = qrnow_.row(0);\r\n            qrbnd2_ = qrnow_.row(qrnow_.rows() - 1);\r\n\r\n            if(imicrophys == 2)\r\n            {\r\n                ncbnd1_ = ncnow_.row(0);\r\n                ncbnd2_ = ncnow_.row(ncnow_.rows() - 1);\r\n\r\n                nrbnd1_ = nrnow_.row(0);\r\n                nrbnd2_ = nrnow_.row(nrnow_.rows() - 1);\r\n            }\r\n\r\n            if(idthdt)\r\n            {\r\n                dthetadtbnd1_ = dthetadt_.row(0);\r\n                dthetadtbnd2_ = dthetadt_.row(dthetadt_.rows() - 1);\r\n            }\r\n        }\r\n\r\n        LOG_SUCCESS(t);\r\n    }\r\n\r\n    // Calculate geometric height (staggered)\r\n    //-------------------------------------------------------------\r\n    for(int k = 1; k < nz1; ++k)\r\n    {\r\n        zhtnow_.col(k) = zhtnow_.col(k - 1).array()\r\n                         - rdcp / g * 0.5 * (th0_[k - 1] * exn0_[k - 1] + th0_[k] * exn0_[k])\r\n                               * (prs0_[k] - prs0_[k - 1]) / (0.5 * (prs0_[k] + prs0_[k - 1]));\r\n    }\r\n\r\n    // Make topography\r\n    //-------------------------------------------------------------\r\n    LOG() << \"Creating topography ... \" << logger::flush;\r\n    t.start();\r\n\r\n    double x0 = (nxb - 1) / 2.0 + 1;\r\n    VectorXf x = (VectorXf::LinSpaced(nxb, 0, nxb - 1).array() + 1 - x0) * dx;\r\n\r\n    VectorXf toponf(nxb);\r\n    for(int i = 0; i < nxb; ++i)\r\n        toponf[i] = topomx * std::exp(-(pow2(x[i] / double(topowd))));\r\n\r\n    for(int i = 1; i < nxb - 1; ++i)\r\n        topo_[i] = toponf[i] + 0.25 * (toponf[i - 1] - 2.0 * toponf[i] + toponf[i + 1]);\r\n\r\n    LOG_SUCCESS(t);\r\n\r\n    // Switch between boundary relaxation / periodic boundary conditions\r\n    //-------------------------------------------------------------\r\n    if(irelax)\r\n    {\r\n        LOG() << \"Relax topography ... \" << logger::flush;\r\n        t.start();\r\n\r\n        tbnd1_[0] = topo_[0];\r\n        tbnd2_[0] = topo_[topo_.size() - 1];\r\n        Boundary::relax(topo_, nx, nb, tbnd1_, tbnd2_);\r\n\r\n        LOG_SUCCESS(t);\r\n    }\r\n    else\r\n    {\r\n        LOG() << \"Periodic topography ... \" << logger::flush;\r\n        t.start();\r\n        Boundary::periodic(topo_, nx, nb);\r\n        LOG_SUCCESS(t);\r\n    }\r\n\r\n    // Height-dependent diffusion coefficient\r\n    //-------------------------------------------------------------\r\n    LOG() << \"Height-dependent diffusion coefficient ... \" << logger::flush;\r\n    t.start();\r\n\r\n    tau_ = diff * VectorXf::Ones(nz).array();\r\n\r\n    for(int k = nz - nab; k < nz; ++k)\r\n    {\r\n        double sin_k = std::sin(0.5 * M_PI * ((k + 1) - (nz - nab)) / nab);\r\n        tau_(k) = diff + (diffabs - diff) * (sin_k * sin_k);\r\n    }\r\n\r\n    LOG_SUCCESS(t);\r\n\r\n    // Set up getter maps\r\n    //-------------------------------------------------------------\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"zhtold\", &zhtold_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"zhtnow\", &zhtnow_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"uold\", &uold_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"unow\", &unow_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"unew\", &unew_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"sold\", &sold_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"snow\", &snow_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"snew\", &snew_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"mtg\", &mtg_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"mtgnew\", &mtgnew_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"exn\", &exn_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"prs\", &prs_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"qvold\", &qvold_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"qvnow\", &qvnow_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"qvnew\", &qvnew_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"qrold\", &qrold_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"qrnow\", &qrnow_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"qrnew\", &qrnew_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"qcold\", &qcold_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"qcnow\", &qcnow_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"qcnew\", &qcnew_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"temp\", &temp_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"nrold\", &nrold_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"nrnow\", &nrnow_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"nrnew\", &nrnew_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"ncold\", &ncold_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"ncnow\", &ncnow_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"ncnew\", &ncnew_));\r\n    matMap_.insert(std::make_pair<std::string, MatrixXf*>(\"dthetadt\", &dthetadt_));\r\n\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"topo\", &topo_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"mtg0\", &mtg0_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"exn0\", &exn0_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"prs0\", &prs0_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"tau\", &tau_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"th0\", &th0_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"prec\", &prec_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"tot_prec\", &tot_prec_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"sbnd1\", &sbnd1_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"sbnd2\", &sbnd2_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"ubnd1\", &ubnd1_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"ubnd2\", &ubnd2_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"qvbnd1\", &qvbnd1_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"qvbnd2\", &qvbnd2_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"qcbnd1\", &qcbnd1_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"qcbnd2\", &qcbnd2_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"qrbnd1\", &qrbnd1_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"qrbnd2\", &qrbnd2_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"dthetadtbnd1\", &dthetadtbnd1_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"dthetadtbnd2\", &dthetadtbnd2_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"nrbnd1\", &nrbnd1_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"nrbnd2\", &nrbnd2_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"ncbnd1\", &ncbnd1_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"ncbnd2\", &ncbnd2_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"tbnd1\", &tbnd1_));\r\n    vecMap_.insert(std::make_pair<std::string, VectorXf*>(\"tbnd2\", &tbnd2_));\r\n\r\n    // Output initial fields\r\n    //-------------------------------------------------------------\r\n    if(iiniout)\r\n        output_->makeOutput(this);\r\n}\r\n\r\nconst MatrixXf& Solver::getMat(std::string name) const\r\n{\r\n    try\r\n    {\r\n        return *matMap_.at(name);\r\n    }\r\n    catch(std::out_of_range&)\r\n    {\r\n        throw IsenException(\"no matrix named '%s' in Solver\", name);\r\n    }\r\n}\r\n\r\nconst VectorXf& Solver::getVec(std::string name) const\r\n{\r\n    try\r\n    {\r\n        return *vecMap_.at(name);\r\n    }\r\n    catch(std::out_of_range&)\r\n    {\r\n        throw IsenException(\"no vector named '%s' in Solver\", name);\r\n    }\r\n}\r\n\r\nEigen::Map<MatrixXf> Solver::getField(std::string name) const\r\n{\r\n    if(matMap_.find(name) != matMap_.end())\r\n    {\r\n        const auto& mat = matMap_.at(name);\r\n        return Eigen::Map<MatrixXf>(const_cast<double*>(mat->data()), mat->rows(), mat->cols());\r\n    }\r\n    else if(vecMap_.find(name) != vecMap_.end())\r\n    {\r\n        const auto& vec = vecMap_.at(name);\r\n        return Eigen::Map<MatrixXf>(const_cast<double*>(vec->data()), vec->rows(), vec->cols());\r\n    }\r\n    else\r\n        throw IsenException(\"no field named '%s' in Solver\", name);\r\n}\r\n\r\nvoid Solver::run()\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    Timer t;\r\n\r\n    Progressbar pbar(nts);\r\n    const bool logIsDisabled = LOG().isDisabled();\r\n    Progressbar::disableProgressbar = logIsDisabled;\r\n\r\n    double curTime = 0;\r\n\r\n    // Loop over all time steps\r\n    //------------------------------------------------------------\r\n    for(int i = 1; i < (nts + 1); ++i)\r\n    {\r\n        if(!iprtcfl)\r\n            pbar.advance();\r\n\r\n        curTime += dt;\r\n        topofact_ = std::min(1., curTime / topotim);\r\n\r\n        // Special treatment of first time step\r\n        //--------------------------------------------------------\r\n        dtdx_ = i == 1 ? 0.5 * dt / dx : dt / dx;\r\n\r\n        // Prognostic step\r\n        //--------------------------------------------------------\r\n\r\n        // Isentropic mass density\r\n        progIsendens();\r\n\r\n        // Moisture scalars\r\n        if(imoist)\r\n            progMoisture();\r\n\r\n        // Velocity\r\n        progVelocity();\r\n\r\n        // Exchange boundaries if periodic\r\n        //--------------------------------------------------------\r\n        if(!irelax)\r\n            applyPeriodicBoundary();\r\n\r\n        // Relaxation of prognostic fields\r\n        //--------------------------------------------------------\r\n        if(irelax)\r\n            applyRelaxationBoundary();\r\n\r\n        uold_.swap(unow_);\r\n        sold_.swap(snow_);\r\n        qvold_.swap(qvnow_);\r\n        qcold_.swap(qcnow_);\r\n        qrold_.swap(qrnow_);\r\n\r\n        unow_.swap(unew_);\r\n        snow_.swap(snew_);\r\n        qvnow_.swap(qvnew_);\r\n        qcnow_.swap(qcnew_);\r\n        qrnow_.swap(qrnew_);\r\n\r\n        // Diffusion and gravity wave absorber\r\n        //--------------------------------------------------------\r\n        horizontalDiffusion();\r\n\r\n        if(!irelax)\r\n            applyPeriodicBoundary();\r\n\r\n        if(imoist)\r\n            clipMoisture();\r\n\r\n        unow_.swap(unew_);\r\n        snow_.swap(snew_);\r\n        qvnow_.swap(qvnew_);\r\n        qcnow_.swap(qcnew_);\r\n        qrnow_.swap(qrnew_);\r\n\r\n        // Diagnostic step\r\n        //--------------------------------------------------------\r\n\r\n        // Pressure\r\n        diagPressure();\r\n\r\n        // Montgomorey\r\n        diagMontgomery();\r\n\r\n        // Calculation of geometric height (staggered)\r\n        //--------------------------------------------------------\r\n        zhtnow_.swap(zhtold_);\r\n        geometricHeight();\r\n\r\n        // Microphysics\r\n        //---------------------------------------------------------\r\n        if(imoist)\r\n        {\r\n            if(imicrophys == 1) // Kessler scheme\r\n            {\r\n                kessler_->apply(\r\n                    // Output\r\n                    temp_, qvnew_, qcnew_, qrnew_, tot_prec_, prec_,\r\n\r\n                    // Input\r\n                    th0_, prs_, snow_, qvnow_, qcnow_, qrnow_, exn_, zhtnow_);\r\n            }\r\n            else if(imicrophys == 2) // Two-moment scheme\r\n            {\r\n                //TODO...\r\n            }\r\n\r\n            if(imicrophys > 0)\r\n            {\r\n                if(idthdt) // Diabatic flow\r\n                {\r\n                    //TODO...\r\n                }\r\n            }\r\n        }\r\n\r\n        qvnow_.swap(qvnew_);\r\n        qcnow_.swap(qcnew_);\r\n        qrnow_.swap(qrnew_);\r\n\r\n        // Check maximum CFL condition\r\n        //--------------------------------------------------------\r\n        double umax = computeCFL();\r\n        double cflmax = umax * dtdx_;\r\n\r\n        if(iprtcfl)\r\n            std::printf(\"CFL max: %f U max: %f m/s \\n\", cflmax, umax);\r\n\r\n        if(cflmax > 1)\r\n            warning(\"isen\", (boost::format(\"CFL condition violated (CFL max %f)\") % cflmax).str());\r\n        if(std::isnan(cflmax))\r\n            error(\"isen\", \"model encountered NaN values\");\r\n\r\n        // Output every 'iout'-th time step\r\n        //--------------------------------------------------------\r\n        if((i % iout) == 0)\r\n            output_->makeOutput(this);\r\n\r\n#ifdef ISEN_PYTHON\r\n        // Handle Python signals\r\n        //--------------------------------------------------------\r\n        if(PyErr_CheckSignals() == -1)\r\n            throw IsenException(\"PySolver::run : signal caught\");\r\n#endif\r\n    }\r\n\r\n    pbar.pause();\r\n    if(!logIsDisabled)\r\n        Progressbar::printBar('=');\r\n\r\n    if(logIsDisabled && itime)\r\n        std::printf(\"Elapsed time: %s\\n\", timeString(t.stop()).c_str());\r\n\r\n    LOG() << \"Finished time loop ...\";\r\n    LOG_SUCCESS(t);\r\n}\r\n\r\ndouble Solver::computeCFL() const noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    double umax = -std::numeric_limits<double>::max();\r\n    for(int k = 0; k < nz; ++k)\r\n        for(int i = 0; i < nxb; ++i)\r\n            umax = std::max(umax, std::fabs(unow_(i, k)));\r\n    return umax;\r\n}\r\n\r\nvoid Solver::horizontalDiffusion() noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    const int nxnb = nx + nb;\r\n    const int nxnb1 = nx + nb + 1;\r\n\r\n    for(int k = 0; k < nz; ++k)\r\n    {\r\n        const double tau = tau_(k);\r\n        const bool sel = tau_(k) > 0.0;\r\n        const bool negSel = !sel;\r\n\r\n        // Velocity\r\n        for(int i = nb; i < nxnb1; ++i)\r\n        {\r\n            unew_(i, k) = sel * (unow_(i, k) + 0.25 * tau * (unow_(i - 1, k) - 2 * unow_(i, k) + unow_(i + 1, k)))\r\n                          + negSel * unow_(i, k);\r\n        }\r\n\r\n        // Isentropic density\r\n        for(int i = nb; i < nxnb; ++i)\r\n        {\r\n            snew_(i, k) = sel * (snow_(i, k) + 0.25 * tau * (snow_(i - 1, k) - 2 * snow_(i, k) + snow_(i + 1, k)))\r\n                          + negSel * snow_(i, k);\r\n        }\r\n\r\n        if(imoist && imoist_diff)\r\n        {\r\n            // Water vapor (qv)\r\n            for(int i = nb; i < nxnb; ++i)\r\n            {\r\n                qvnew_(i, k)\r\n                    = sel * (qvnow_(i, k) + 0.25 * tau * (qvnow_(i - 1, k) - 2 * qvnow_(i, k) + qvnow_(i + 1, k)))\r\n                      + negSel * qvnow_(i, k);\r\n            }\r\n\r\n            // Specific cloud water content (qc)\r\n            for(int i = nb; i < nxnb; ++i)\r\n            {\r\n                qcnew_(i, k)\r\n                    = sel * (qcnow_(i, k) + 0.25 * tau * (qcnow_(i - 1, k) - 2 * qcnow_(i, k) + qcnow_(i + 1, k)))\r\n                      + negSel * qcnow_(i, k);\r\n            }\r\n\r\n            // Specific rain water content (qr)\r\n            for(int i = nb; i < nxnb; ++i)\r\n            {\r\n                qrnew_(i, k)\r\n                    = sel * (qrnow_(i, k) + 0.25 * tau * (qrnow_(i - 1, k) - 2 * qrnow_(i, k) + qrnow_(i + 1, k)))\r\n                      + negSel * qrnow_(i, k);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nvoid Solver::geometricHeight() noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    for(int i = 0; i < nxb; ++i)\r\n        zhtnow_(i, 0) = topo_(i) * topofact_;\r\n\r\n    const double rcpg05 = 0.5 * r / cp / g;\r\n    for(int k = 1; k < nz1; ++k)\r\n        for(int i = 0; i < nxb; ++i)\r\n        {\r\n            double th0exn = (th0_(k - 1) * exn_(i, k - 1) + th0_(k) * exn_(i, k));\r\n            double prs = (prs_(i, k) - prs_(i, k - 1)) / (0.5 * (prs_(i, k) + prs_(i, k - 1)));\r\n            zhtnow_(i, k) = zhtnow_(i, k - 1) - rcpg05 * th0exn * prs;\r\n        }\r\n}\r\n\r\nvoid Solver::applyPeriodicBoundary() noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    assert(!irelax);\r\n    Boundary::periodic(snew_, nx, nb);\r\n    Boundary::periodic(unew_, nx + 1, nb);\r\n\r\n    if(imoist)\r\n    {\r\n        Boundary::periodic(qvnew_, nx, nb);\r\n        Boundary::periodic(qcnew_, nx, nb);\r\n        Boundary::periodic(qrnew_, nx, nb);\r\n\r\n        if(imicrophys == 2)\r\n        {\r\n            Boundary::periodic(ncnew_, nx, nb);\r\n            Boundary::periodic(nrnew_, nx, nb);\r\n        }\r\n    }\r\n}\r\n\r\nvoid Solver::applyRelaxationBoundary() noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    assert(irelax);\r\n    Boundary::relax(snew_, nx, nb, sbnd1_, sbnd2_);\r\n    Boundary::relax(unew_, nx1, nb, ubnd1_, ubnd2_);\r\n\r\n    if(imoist)\r\n    {\r\n        Boundary::relax(qvnew_, nx, nb, qvbnd1_, qvbnd2_);\r\n        Boundary::relax(qcnew_, nx, nb, qcbnd1_, qcbnd2_);\r\n        Boundary::relax(qrnew_, nx, nb, qrbnd1_, qrbnd2_);\r\n\r\n        if(imicrophys == 2)\r\n        {\r\n            Boundary::relax(ncnew_, nx, nb, ncbnd1_, ncbnd2_);\r\n            Boundary::relax(nrnew_, nx, nb, nrbnd1_, nrbnd2_);\r\n        }\r\n    }\r\n}\r\n\r\nvoid Solver::clipMoisture() noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n            \r\n    auto clip = [&](MatrixXf& mat)\r\n    {\r\n        for(int k = 0; k < nz; ++k)\r\n            for(int i = 0; i < nxb; ++i)\r\n                mat(i, k) = mat(i, k) < 0.0 ? 0.0 : mat(i, k);\r\n    };\r\n\r\n    clip(qvnew_);\r\n    clip(qcnew_);\r\n    clip(qrnew_);\r\n}\r\n\r\nvoid Solver::diagMontgomery() noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    const double dth05 = dth * 0.5;\r\n    const double gtopofact_ = g * topofact_;\r\n\r\n    // Exner function\r\n    for(int k = 0; k < nz1; ++k)\r\n        for(int i = 0; i < nxb; ++i)\r\n            exn_(i, k) = cp * std::pow(prs_(i, k) / pref, rdcp);\r\n\r\n    // Montgomery\r\n    for(int i = 0; i < nxb; ++i)\r\n        mtg_(i, 0) = gtopofact_ * topo_(i) + th0_(0) * exn_(i, 0) + dth05 * exn_(i, 0);\r\n\r\n    for(int k = 1; k < nz; ++k)\r\n        for(int i = 0; i < nxb; ++i)\r\n            mtg_(i, k) = mtg_(i, k - 1) + dth * exn_(i, k);\r\n}\r\n\r\nvoid Solver::diagPressure() noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    const double gdth = g * dth;\r\n\r\n    for(int i = 0; i < nxb; ++i)\r\n        prs_(i, nz) = prs0_(nz);\r\n\r\n    for(int k = nz - 1; k >= 0; --k)\r\n        for(int i = 0; i < nxb; ++i)\r\n            prs_(i, k) = prs_(i, k + 1) + gdth * snow_(i, k);\r\n}\r\n\r\nvoid Solver::progIsendens() noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    const double dtdx05 = 0.5 * dtdx_;\r\n    const int nxnb = nx + nb;\r\n\r\n    for(int k = 0; k < nz; ++k)\r\n        for(int i = nb; i < nxnb; ++i)\r\n            snew_(i, k) = sold_(i, k)\r\n                          - (dtdx05) * (snow_(i + 1, k) * (unow_(i + 2, k) + unow_(i + 1, k))\r\n                                        - snow_(i - 1, k) * (unow_(i, k) + unow_(i - 1, k)));\r\n}\r\n\r\nvoid Solver::progVelocity() noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    const double dtdx = dtdx_;\r\n    const double dtdx2 = 2 * dtdx_;\r\n    const int nx1nb = nx + nb + 1;\r\n\r\n    for(int k = 0; k < nz; ++k)\r\n    {\r\n        for(int i = nb; i < nx1nb; ++i)\r\n        {\r\n            unew_(i, k) = uold_(i, k) - dtdx * unow_(i, k) * (unow_(i + 1, k) - unow_(i - 1, k))\r\n                          - dtdx2 * (mtg_(i, k) - mtg_(i - 1, k));\r\n        }\r\n    }\r\n}\r\n\r\nvoid Solver::progMoisture() noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n\r\n    const double dtdx05 = 0.5 * dtdx_;\r\n    const int nxnb = nx + nb;\r\n\r\n    // Water vapor (qv)\r\n    for(int k = 0; k < nz; ++k)\r\n        for(int i = nb; i < nxnb; ++i)\r\n            qvnew_(i, k)\r\n                = qvold_(i, k) - dtdx05 * (unow_(i, k) + unow_(i + 1, k)) * (qvnow_(i + 1, k) - qvnow_(i - 1, k));\r\n\r\n    // Specific cloud water content (qc)\r\n    for(int k = 0; k < nz; ++k)\r\n        for(int i = nb; i < nxnb; ++i)\r\n            qcnew_(i, k)\r\n                = qcold_(i, k) - dtdx05 * (unow_(i, k) + unow_(i + 1, k)) * (qcnow_(i + 1, k) - qcnow_(i - 1, k));\r\n\r\n    // Specific rain water content (qr)\r\n    for(int k = 0; k < nz; ++k)\r\n        for(int i = nb; i < nxnb; ++i)\r\n            qrnew_(i, k)\r\n                = qrold_(i, k) - dtdx05 * (unow_(i, k) + unow_(i + 1, k)) * (qrnow_(i + 1, k) - qrnow_(i - 1, k));\r\n}\r\n\r\nvoid Solver::progNumdens() noexcept\r\n{\r\n    SOLVER_DECLARE_ALL_ALIASES\r\n}\r\n\r\nvoid Solver::write(std::string filename)\r\n{\r\n    output_->write(filename);\r\n}\r\n\r\nISEN_NAMESPACE_END\r\n", "meta": {"hexsha": "c4e55be2191874636f6871710e7ddb29a16fbc1b", "size": 30643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/IsenCore/Solver.cpp", "max_stars_repo_name": "thfabian/Isen", "max_stars_repo_head_hexsha": "c03d8e3f4590f4208ce9f4d9141169ca6133cac3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-07-26T17:43:44.000Z", "max_stars_repo_stars_event_max_datetime": "2016-07-26T17:43:44.000Z", "max_issues_repo_path": "lib/IsenCore/Solver.cpp", "max_issues_repo_name": "thfabian/Isen", "max_issues_repo_head_hexsha": "c03d8e3f4590f4208ce9f4d9141169ca6133cac3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/IsenCore/Solver.cpp", "max_forks_repo_name": "thfabian/Isen", "max_forks_repo_head_hexsha": "c03d8e3f4590f4208ce9f4d9141169ca6133cac3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7033084312, "max_line_length": 119, "alphanum_fraction": 0.4716248409, "num_tokens": 9147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.42892566000872273}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_REM_PIO2_STRAIGHT_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_REM_PIO2_STRAIGHT_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing rem_pio2_straight capabilities\n\n    Computes the remainder modulo \\f$\\pi/2\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r, rc;\n    as_integer<T> n;\n    rem_pio2_straight<Range>(x, n, r);\n    @endcode\n\n    is similar to:\n\n    @code\n    as_integer<T> n = idivround2even(x, Pio_2<T>());\n    T r =  remainder(x, Pio_2<T>());\n    @endcode\n\n    @par Note:\n    @c rem_pio2_straight computes the remainder modulo \\f$\\pi/2\\f$ with straight algorithm,\n    and returns an angle quadrant which is always 1.\n    This is a very quick version accurate if the input\n    is in \\f$[\\pi/4,\\pi/2]\\f$. In fact it only substract \\f$\\pi/2\\f$ to the input\n    so it can be viewed as a specially accurate minuspio_2 function outside\n    the interval in which it can be used as a substitute to rem_pio2.\n\n    The reduction of the argument modulo \\f$\\pi/2\\f$ is generally\n    the most difficult part of trigonometric evaluations.\n    The accurate algorithm over the whole floating point range\n    is over costly and implies the knowledge\n    of a few hundred \\f$pi\\f$ decimals\n    some simpler algorithms as this one\n    can be used, but the precision is only insured on specific intervals.\n\n    @see rem_pio2, rem_pio2_medium,rem_2pi, rem_pio2_cephes,\n\n  **/\n  const boost::dispatch::functor<tag::rem_pio2_straight_> rem_pio2_straight = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/rem_pio2_straight.hpp>\n#include <boost/simd/function/simd/rem_pio2_straight.hpp>\n\n#endif\n", "meta": {"hexsha": "bfbb4b6b30342697c325f1e51a99d82fa5e75959", "size": 2170, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/rem_pio2_straight.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/function/rem_pio2_straight.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/rem_pio2_straight.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0, "max_line_length": 100, "alphanum_fraction": 0.6562211982, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4288795672360339}}
{"text": "#include \"ray.h\"\n#include \"utils.h\"\n#include <cmath>\n#include <numeric>\n#include <algorithm>\n#include <Eigen/Dense>\n\nusing Eigen::Vector3d;\n\nnamespace batoid {\n    Ray::Ray(double x, double y, double z, double vx, double vy, double vz, double _t=0.0,\n             double _wavelength=0.0, double _flux=1.0, bool _vignetted=false) :\n        r(Vector3d(x, y, z)), v(Vector3d(vx, vy, vz)), t(_t),\n        wavelength(_wavelength), flux(_flux), vignetted(_vignetted), failed(false) {}\n\n    Ray::Ray(Vector3d _r, Vector3d _v, double _t=0.0, double _wavelength=0.0,\n             double _flux=1.0, bool _vignetted=false) :\n        r(_r), v(_v), t(_t), wavelength(_wavelength), flux(_flux), vignetted(_vignetted),\n        failed(false) {}\n\n    Ray::Ray(const bool failed) :\n        r(Vector3d::Zero()), v(Vector3d::Zero()), t(0.0), wavelength(0.0), flux(0.0),\n        vignetted(true), failed(true) {}\n\n    std::string Ray::repr() const {\n        std::ostringstream oss(\"Ray(\", std::ios_base::ate);\n        if(failed)\n            oss << \"failed=True)\";\n        else {\n            oss << \"[\" << r[0] << \",\" << r[1] << \",\" << r[2] << \"],[\"\n                << v[0] << \",\" << v[1] << \",\" << v[2] << \"]\";\n            if (t != 0.0) oss << \", t=\" << t;\n            if (wavelength != 0.0) oss << \", wavelength=\" << wavelength;\n            if (flux != 1.0) oss << \", flux=\" << flux;\n            if (vignetted) oss << \", vignetted=True\";\n            oss << \")\";\n        }\n        return oss.str();\n    }\n\n    Vector3d Ray::positionAtTime(const double _t) const {\n        return r+v*(_t-t);\n    }\n\n    Ray Ray::propagatedToTime(const double _t) const {\n        return Ray(positionAtTime(_t), v, _t, wavelength, flux, vignetted);\n    }\n\n    void Ray::propagateInPlace(const double _t) {\n        r += v*(_t-t);\n        t = _t;\n    }\n\n    bool Ray::operator==(const Ray& other) const {\n        // All failed rays are equal\n        if (failed)\n            return other.failed;\n        if (other.failed)\n            return false;\n        return (r == other.r) &&\n               (v == other.v) &&\n               (t == other.t) &&\n               (wavelength == other.wavelength) &&\n               (flux == other.flux) &&\n               (vignetted == other.vignetted);\n    }\n\n    bool Ray::operator!=(const Ray& other) const {\n        return !(*this == other);\n    }\n\n    double Ray::phase(const Vector3d& _r, double _t) const {\n        return k().dot(_r-r) - (_t-t)*omega();\n    }\n\n    std::complex<double> Ray::amplitude(const Vector3d& _r, double _t) const {\n        return std::exp(std::complex<double>(0, 1)*phase(_r, _t));\n    }\n}\n", "meta": {"hexsha": "b7f3fbeebfa15aca63f6ceedbeaf2d41c6425365", "size": 2607, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ray.cpp", "max_stars_repo_name": "dkirkby/batoid", "max_stars_repo_head_hexsha": "734dccc289eb7abab77a62cdc14563ed5981753b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ray.cpp", "max_issues_repo_name": "dkirkby/batoid", "max_issues_repo_head_hexsha": "734dccc289eb7abab77a62cdc14563ed5981753b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ray.cpp", "max_forks_repo_name": "dkirkby/batoid", "max_forks_repo_head_hexsha": "734dccc289eb7abab77a62cdc14563ed5981753b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5875, "max_line_length": 90, "alphanum_fraction": 0.5201380898, "num_tokens": 757, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4288795672360339}}
{"text": "#pragma once\n\n#define GLM_ENABLE_EXPERIMENTAL 1\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Halide.h>\n#include <fstream>\n#include <glm/ext.hpp>\n#include <glm/glm.hpp>\n#include <halide_image_io.h>\n#include <iostream>\n#include <stdio.h>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <filesystem>\n#include <ImfRgbaFile.h>\n#include <ImfStringAttribute.h>\n#include <ImfMatrixAttribute.h>\n#include <ImfArray.h>\n#include <algorithm>\n#include <ImfNamespace.h>\n#include <tuple>\n#include <math.h>\n\n#include \"utilities.h\"\n\nnamespace IMF = OPENEXR_IMF_NAMESPACE;\n\nusing namespace IMF;\nusing namespace IMATH_NAMESPACE;\n\nusing std::string;\nusing std::stringstream;\nusing std::vector;\n\nusing namespace std;\nusing namespace Halide;\nusing namespace Halide::Tools;\nusing namespace Eigen;\nusing std::filesystem::directory_iterator;\n\nusing Vector4h = Matrix<Halide::Expr, 4, 1>;\nusing Matrix4h = Matrix<Halide::Expr, 4, 4>;\n\nVar x, y, c, i, pcx, pcy;\n\nstruct Point\n{\n    float x;\n    float y;\n    float z;\n    uint16_t r;\n    uint16_t g;\n    uint16_t b;\n};\n\nvoid saveImage(Expr result, size_t width, size_t height, const string &basename)\n{\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y) = cast<uint8_t>(clamp(result, 0.0f, 1.0f) * 255.0f);\n    byteResult.compile_jit(target);\n    Buffer<uint8_t> output(width, height);\n    byteResult.realize(output);\n    stringstream filename;\n    filename << basename << \".png\";\n    save_image(output, filename.str());\n}\n\nBuffer<uint8_t> loadImages(vector<string> filenames)\n{\n    if (filenames.empty())\n    {\n        throw std::invalid_argument(\"List of filenames cannot be empty\");\n    }\n    vector<Buffer<uint8_t>> images;\n    Func assigner;\n    assigner(x, y, c, i) = cast<uint8_t>(0);\n    for (int i = 0; i < filenames.size(); i++)\n    {\n        const auto filename = filenames[i];\n        images.push_back(load_image(filename));\n        assigner(x, y, c, i) = images[i](x, y, c);\n    }\n    Buffer<uint8_t> input(images[0].width(), images[0].height(), images[0].channels(), images.size());\n    assigner.realize(input);\n    return input;\n}\n\nVector4h makeAxBzCLine(Vector4h a, Vector4h b)\n{\n    Vector4h result;\n    result(0) = a(2) - b(2);\n    result(1) = b(0) - a(0);\n    result(2) = a(0) * b(2) - b(0) * a(2);\n    result(3) = 1.0f;\n    return result;\n}\n\nVector4h cross3(Vector4h a, Vector4h b)\n{\n    Vector4h res;\n    res(0) = a(1) * b(2) - a(2) * b(1);\n    res(1) = a(2) * b(0) - a(0) * b(2);\n    res(2) = a(0) * b(1) - a(1) * b(0);\n    res(3) = 0;\n    return res;\n}\n\nExpr dot3(Vector4h a, Vector4h b)\n{\n    Expr res;\n    res = a(0) * b(0) + a(1) * b(1) + a(2) * b(2);\n    return res;\n}\n\ntuple<Vector4h, Vector4h> pluckerLine(Vector4h p1, Vector4h p2)\n{\n    Vector4h l;\n    Vector4h l_dash;\n    l = p1(3) * p2 - p2(3) * p1;\n    l(3) = 0;\n    l_dash = cross3(p1, p2);\n    return {l, l_dash};\n}\n\nVector4h pluckerPlane(Vector4h l, Vector4h l_dash, Vector4h pluckPt)\n{\n    Vector4h u;\n    u = -pluckPt(3) * l_dash + cross3(pluckPt, l);\n    u(3) = dot3(pluckPt, l_dash);\n    return u;\n}\n\nVector4h intersectionLinePlane(Vector4h l, Vector4h l_dash, Vector4h plPlane)\n{\n    Vector4h intersection;\n    intersection = -plPlane(3) * l + cross3(plPlane, l_dash);\n    intersection(3) = dot3(plPlane, l);\n    return intersection;\n}\n\nbool conditionProjector(float x, float y, float z)\n{\n    return (x < -10.0f || x > 10.0f || y < -10.0f || y > 10.0f || z < -10.0f || z > 10.0f);\n}\n\nbool noCondition(float x, float y, float z)\n{\n    return false;\n}\n\nvoid saveImages(Expr result, size_t width, size_t height, size_t imageCount, const string &basename)\n{\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y, i) = cast<uint8_t>(clamp(result, 0.0f, 1.0f) * 255.0f);\n    byteResult.compile_jit(target);\n    Buffer<uint8_t> output(width, height, imageCount);\n    byteResult.realize(output);\n    for (int i = 0; i < imageCount; i++)\n    {\n        stringstream filename;\n        filename << basename << i << \".png\";\n        const Buffer<uint8_t> image = output.sliced(2, i);\n        save_image(image, filename.str());\n    }\n}\n\ntemplate <typename Function>\nvoid writeBufferToXYZFile(Buffer<float> &buffer, Buffer<uint8_t> &color, string filename, string deliminator, Function condFunc)\n{\n    std::vector<Point> points;\n    for (int j = 0; j < buffer.height(); j++)\n    {\n        for (int i = 0; i < buffer.width(); i++)\n        {\n            const auto x = buffer(i, j, 0);\n            const auto y = buffer(i, j, 1);\n            const auto z = buffer(i, j, 2);\n            uint8_t r = color(i, j, 0);\n            uint8_t g = color(i, j, 1);\n            uint8_t b = color(i, j, 2);\n            if (condFunc(x, y, z))\n            {\n                continue;\n            }\n            points.push_back({x, y, z, r, g, b});\n        }\n    }\n    std::ofstream outFile;\n    outFile.open(filename);\n    outFile << points.size() << \"\\n\";\n    const auto d = deliminator;\n    for (const auto &point : points)\n    {\n        outFile << point.x << d << point.y << d << point.z << d << point.r << d << point.g << d << point.b << \"\\n\";\n    }\n}\n\nvoid debugImageEXR(Expr channel1Expr, Expr channel2Expr, Expr channel3Expr, int width, int height, const char fileName[])\n{\n    channel1Expr = cast<float>(channel1Expr);\n    channel2Expr = cast<float>(channel2Expr);\n    channel3Expr = cast<float>(channel3Expr);\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y, c) = 0.0f;\n    byteResult(x, y, 0) = channel1Expr;\n    byteResult(x, y, 1) = channel2Expr;\n    byteResult(x, y, 2) = channel3Expr;\n    Buffer<float> output(width, height, 3);\n    byteResult.compile_jit(target);\n    byteResult.realize(output);\n\n    Array2D<Rgba> pixels;\n    pixels.resizeErase(height, width);\n    for (int row{0}; row < height; row++)\n    {\n        for (int col{0}; col < width; col++)\n        {\n            pixels[row][col].r = output(col, row, 0);\n            pixels[row][col].g = output(col, row, 1);\n            pixels[row][col].b = output(col, row, 2);\n        }\n    }\n    RgbaOutputFile file(fileName, width, height, WRITE_RGBA);\n    file.setFrameBuffer(&pixels[0][0], 1, width);\n    file.writePixels(height);\n}\n\nint main(int argc, char **argv)\n{\n    Buffer<uint8_t> input = load_image(\"images/scan-images/scan_30.png\");\n\n    Expr redFilter = input(x, y, 0) > 140;\n\n    Matrix4h K = read4x4MatFromCSV(\"matrices/cam-mat.csv\");\n    Matrix4h invK = read4x4MatFromCSV(\"matrices/inv-cam-mat.csv\");\n    Matrix4h T_CP = read4x4MatFromCSV(\"matrices/T-C1-C2.csv\");\n    Matrix4h T_WC = read4x4MatFromCSV(\"matrices/T-W-C1.csv\");\n    Vector4h t_CP{0, 0, 0, 0};\n    t_CP(0) = T_CP(0, 3);\n    t_CP(1) = T_CP(1, 3);\n    t_CP(2) = T_CP(2, 3);\n    t_CP(3) = T_CP(3, 3);\n    cout << t_CP << endl;\n\n    Vector4h scanNormal_P{1.0f, 0.0f, 0.0f, 1.0f};\n    Vector4h scanPlane_C = T_CP * scanNormal_P;\n    scanPlane_C(3) = -dot3(scanPlane_C, t_CP);\n\n    cout << scanPlane_C << endl;\n\n    Vector4h px{x, y, 1.0f, 0.0f};\n    Vector4h normCoord_C = invK * px;\n    Vector4h lineDash{0.0f, 0.0f, 0.0f, 0.0f};\n    Vector4h intersect = intersectionLinePlane(normCoord_C, lineDash, scanPlane_C);\n    intersect = intersect * redFilter;\n    intersect = intersect / intersect[3];\n    intersect = T_WC * intersect;\n    intersect = intersect / intersect[3];\n    //saveImage(intersect[2], 1920, 1080, \"images/debug/depth.png\");\n\n    Func result;\n    result(x, y, c) = 0.0f;\n    result(x, y, 0) = intersect[0];\n    result(x, y, 1) = intersect[1];\n    result(x, y, 2) = intersect[2];\n\n    Buffer<float> output(1920, 1080, 3);\n    result.realize(output);\n    vector<Point> points;\n    std::ofstream outFile;\n    outFile.open(\"pointclouds/singleScan.txt\");\n\n    for (int xxx = 0; xxx < output.width(); xxx++)\n    {\n        for (int yyy = 0; yyy < output.height(); yyy++)\n        {\n\n            float xPoint = output(xxx, yyy, 0);\n            float yPoint = output(xxx, yyy, 1);\n            float zPoint = output(xxx, yyy, 2);\n            if (abs(zPoint > 0.01))\n            {\n                outFile << xPoint << \";\" << yPoint << \";\" << zPoint << \"\\n\";\n            }\n            points.push_back({xPoint, yPoint, zPoint, 0, 0, 0});\n        }\n    }\n    outFile.close();\n\n    //debugImageEXR(intersect[2], intersect[2], intersect[2], 1920, 1080, \"images/debug/depth.exr\");\n}\n", "meta": {"hexsha": "16fcf816471fc0b8dd0e365afa3908b38851f7ae", "size": 8340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "laser-scanning/cpp/single-scan-pointcloud/singleScanPointcloud.cpp", "max_stars_repo_name": "olaals/prosjektoppgave", "max_stars_repo_head_hexsha": "048c5c01cf428846c76b1c27abd4c0f451056e03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "laser-scanning/cpp/single-scan-pointcloud/singleScanPointcloud.cpp", "max_issues_repo_name": "olaals/prosjektoppgave", "max_issues_repo_head_hexsha": "048c5c01cf428846c76b1c27abd4c0f451056e03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "laser-scanning/cpp/single-scan-pointcloud/singleScanPointcloud.cpp", "max_forks_repo_name": "olaals/prosjektoppgave", "max_forks_repo_head_hexsha": "048c5c01cf428846c76b1c27abd4c0f451056e03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9865771812, "max_line_length": 128, "alphanum_fraction": 0.6052757794, "num_tokens": 2645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4288795597149535}}
{"text": "#include \"opq.h\"\n\n#include <boost/math/constants/constants.hpp>\n#include <boost/thread/once.hpp>\n\n#include \"externals/cxx/namespace.hpp\"\n#include \"externals/cxx/pretty_function.hpp\"\n\n#include <stdexcept>\n\nBEGIN_NAMESPACE(rysq, asymptotic)\n\ntemplate<size_t N, typename T>\nstruct asymptotic_ {\n    static void roots(T X, T *R, T *W) {\n\tboost::call_once(once_flag, &asymptotic_<N,T>::initialize);\n\tT r = 1/X;\n\tT w = 1/sqrt(X);\n\tfor (size_t i = 0; i < N; ++i) {\n\t    R[i] = r*R_[i];\n\t    W[i] = w*W_[i];\n\t}\n    }\nprivate:\n    static T R_[N], W_[N];\n    static boost::once_flag once_flag;\n    static void initialize() {\n\tstatic const size_t n = 2*N;\n\tT beta[n], alpha[n] = { 0 };\n\tbeta[0] = boost::math::constants::root_pi<T>();\n\tfor (size_t i = 1; i < n; ++i) {\n\t    beta[i] = T(i)/2;\n\t}\n\tT r[n], w[n];\n\tint status = opq::coefficients(n, alpha, beta, r, w);\n\tif (status != 0)  {\n\t    throw std::runtime_error(PRETTY_FUNCTION(\"opq::coefficients returned \",\n\t\t\t\t\t\t     status));\n\t}\n\t// CALL RYSGW_(N,ALPHA,BETA,EPS,RTS,W_TS,IERR,W_RK) for\n\tfor (size_t i = 0; i < N; ++i) {\n\t    size_t j = i + N;\n\t    R_[i] = r[j]*r[j];\n\t    W_[i] = w[j];\n\t}\n    }\n};\ntemplate<size_t N, typename T> T asymptotic_<N,T>::R_[N];\ntemplate<size_t N, typename T> T asymptotic_<N,T>::W_[N];\n\ntemplate<size_t N, typename T>\nboost::once_flag asymptotic_<N,T>::once_flag = BOOST_ONCE_INIT;\n\n\ntemplate<size_t N, typename T>\nvoid roots(T X, T *R, T *W) {\n    asymptotic_<N,T>::roots(X, R, W);\n}\n\nEND_NAMESPACE(rysq, asymptotic)\n\n", "meta": {"hexsha": "bef2f8517a352ca1cf81c0739b924f8cb4a6d90f", "size": 1494, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gamess/libqc/rysq/src/roots/asymptotic.hpp", "max_stars_repo_name": "andremirt/v_cond", "max_stars_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gamess/libqc/rysq/src/roots/asymptotic.hpp", "max_issues_repo_name": "andremirt/v_cond", "max_issues_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gamess/libqc/rysq/src/roots/asymptotic.hpp", "max_forks_repo_name": "andremirt/v_cond", "max_forks_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0967741935, "max_line_length": 76, "alphanum_fraction": 0.6171352075, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4286968293265634}}
{"text": "/*!@file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include \"Molassembler/Shapes/PointGroupElements.h\"\n\n#include \"Molassembler/Temple/Functional.h\"\n#include \"boost/optional.hpp\"\n#include <Eigen/Geometry>\n\nnamespace Scine {\nnamespace Molassembler {\nnamespace Shapes {\nnamespace Elements {\nnamespace {\n\ntemplate<typename EnumType>\nconstexpr auto underlying(const EnumType e) {\n  return static_cast<std::underlying_type_t<EnumType>>(e);\n}\n\ninline bool collinear(const Eigen::Vector3d& a, const Eigen::Vector3d& b) {\n  return std::fabs(std::fabs(a.dot(b) / (a.norm() * b.norm())) - 1) <= 1e-8;\n}\n\ninline bool orthogonal(const Eigen::Vector3d& a, const Eigen::Vector3d& b) {\n  return std::fabs(a.dot(b) / (a.norm() * b.norm())) <= 1e-8;\n}\n\ntemplate<typename T>\ninline std::unique_ptr<SymmetryElement> wrap(T&& element) {\n  using Decayed = std::decay_t<T>;\n  return std::make_unique<Decayed>(std::forward<T>(element));\n}\n\nvoid addProperAxisElements(ElementsList& list, const Eigen::Vector3d& axis, const unsigned n) {\n  // C2 gives only a C2, but C3 should also give a C3², etc.\n  const Rotation element = Rotation::Cn(axis, n);\n  Rotation composite = element;\n  for(unsigned i = n; i > 1; --i) {\n    list.push_back(wrap(composite));\n    composite = element * composite;\n  }\n}\n\nvoid addImproperAxisElements(ElementsList& list, const Eigen::Vector3d& axis, const unsigned n) {\n  const Rotation element = Rotation::Sn(axis, n);\n  Rotation composite = element;\n  for(unsigned i = n; i > 1; --i) {\n    list.push_back(wrap(composite));\n    composite = element * composite;\n  }\n}\n\nElementsList Cnh(const unsigned n) {\n  const auto sigma_xy = Reflection::sigma_xy();\n\n  ElementsList elements;\n  elements.push_back(wrap(Identity::E()));\n  elements.push_back(wrap(sigma_xy));\n  std::vector<Rotation> rotations;\n  const Rotation element = Rotation::Cn_z(n);\n  Rotation composite = element;\n  for(unsigned i = n; i > 1; --i) {\n    rotations.push_back(composite);\n    composite = element * composite;\n  }\n  const unsigned S = rotations.size();\n  // Add sigma_xy modified Cn axes\n  for(unsigned i = 0; i < S; ++i) {\n    rotations.push_back(sigma_xy * rotations.at(i));\n  }\n  for(auto& rotation : rotations) {\n    elements.emplace_back(\n      wrap(std::move(rotation))\n    );\n  }\n  assert(elements.size() == 2 * n);\n  return elements;\n}\n\nElementsList Cnv(const unsigned n) {\n  ElementsList elements;\n  elements.push_back(wrap(Identity::E()));\n  addProperAxisElements(elements, Eigen::Vector3d::UnitZ(), n);\n  // Reflection planes include z and increment by pi/n along z\n  const auto rotation = Rotation::Cn_z(2 * n);\n  Eigen::Vector3d planeNormal = Eigen::Vector3d::UnitY();\n  for(unsigned i = 0; i < n; ++i) {\n    elements.push_back(\n      wrap(Reflection(planeNormal))\n    );\n    planeNormal = rotation.matrix() * planeNormal;\n  }\n  assert(elements.size() == 2 * n);\n  return elements;\n}\n\nElementsList Dn(const unsigned n) {\n  ElementsList elements;\n  elements.push_back(wrap(Identity::E()));\n  addProperAxisElements(elements, Eigen::Vector3d::UnitZ(), n);\n  // Dn groups have C2 axes along pi/n increments in the xy plane\n  const auto rotation = Rotation::Cn_z(2 * n);\n  Eigen::Vector3d c2axis = Eigen::Vector3d::UnitX();\n  for(unsigned i = 0; i < n; ++i) {\n    elements.push_back(wrap(Rotation::Cn(c2axis, 2)));\n    c2axis = rotation.matrix() * c2axis;\n  }\n  assert(elements.size() == 2 * n);\n  return elements;\n}\n\nElementsList Dnh(const unsigned n) {\n  ElementsList elements;\n  elements.push_back(wrap(Identity::E()));\n  elements.push_back(wrap(Reflection::sigma_xy()));\n  elements.reserve(4 * n);\n  std::vector<Rotation> rotations;\n  const Rotation element = Rotation::Cn_z(n);\n  Rotation composite = element;\n  for(unsigned i = n; i > 1; --i) {\n    rotations.push_back(composite);\n    composite = element * composite;\n  }\n  const unsigned S = rotations.size();\n  // Generate the S_n axes from the sigma_xy * C_n\n  for(unsigned i = 0; i < S; ++i) {\n    rotations.push_back(Reflection::sigma_xy() * rotations.at(i));\n  }\n  for(auto& rotation : rotations) {\n    elements.emplace_back(\n      wrap(std::move(rotation))\n    );\n  }\n\n  /* Dnh groups have C2 axes along pi/n increments in the xy plane\n   * and sigma_v planes perpendicular to those C2 axes\n   */\n  const auto rotation = Rotation::Cn_z(2 * n);\n  Eigen::Vector3d c2axis = Eigen::Vector3d::UnitX();\n  for(unsigned i = 0; i < n; ++i) {\n    elements.push_back(wrap(Rotation::Cn(c2axis, 2)));\n    elements.push_back(\n      wrap(Reflection(\n        Eigen::Vector3d::UnitZ().cross(c2axis)\n      ))\n    );\n    c2axis = rotation.matrix() * c2axis;\n  }\n\n  assert(elements.size() == 4 * n);\n  return elements;\n}\n\nElementsList Dnd(const unsigned n) {\n  const Eigen::Vector3d e_x = Eigen::Vector3d::UnitX();\n  const Eigen::Vector3d e_z = Eigen::Vector3d::UnitZ();\n\n  ElementsList elements;\n  elements.push_back(wrap(Identity::E()));\n  addImproperAxisElements(elements, e_z, 2 * n);\n  /* C2 axes */\n  const auto rotationMatrix = Rotation::Cn_z(2 * n).matrix();\n  Eigen::Vector3d c2axis = e_x;\n  for(unsigned i = 0; i < n; ++i) {\n    elements.push_back(wrap(Rotation::Cn(c2axis, 2)));\n    c2axis = rotationMatrix * c2axis;\n  }\n  /* sigma_ds */\n  Eigen::Vector3d planeNormal = (e_x + rotationMatrix * e_x).normalized().cross(e_z);\n  for(unsigned i = 0; i < n; ++i) {\n    elements.push_back(wrap(Reflection(planeNormal)));\n    planeNormal = rotationMatrix * planeNormal;\n  }\n  assert(elements.size() == 4 * n);\n  return elements;\n}\n\nElementsList I() {\n  ElementsList elements;\n  elements.push_back(wrap(Identity::E()));\n  elements.reserve(60);\n\n  const double phi = (1 + std::sqrt(5)) / 2;\n  Eigen::Matrix<double, 3, 6> axes;\n  axes << 0.0, 0.0, phi, -phi, 1.0, 1.0,\n          1.0, 1.0, 0.0, 0.0, phi, -phi,\n          phi, -phi, 1.0, 1.0, 0.0, 0.0;\n\n  /* 12 C5, 12 C5^2 */\n  for(unsigned i = 0; i < 6; ++i) {\n    addProperAxisElements(elements, axes.col(i), 5);\n  }\n\n  /* 15 C2 along sums of two positions*/\n  const Eigen::Matrix3d C5 = Eigen::AngleAxisd(2 * M_PI / 5, axes.col(0).normalized()).toRotationMatrix();\n  Eigen::Matrix3d twoAxesBases;\n  twoAxesBases.col(0) = (axes.col(0) + axes.col(2)) / 2;\n  twoAxesBases.col(1) = (axes.col(2) + axes.col(4)) / 2;\n  twoAxesBases.col(2) = (axes.col(2) - axes.col(3)) / 2;\n  for(unsigned i = 0; i < 3; ++i) {\n    Eigen::Vector3d compoundAxis = twoAxesBases.col(i);\n    for(unsigned j = 0; j < 5; ++j) {\n      elements.push_back(wrap(Rotation::Cn(compoundAxis, 2)));\n      compoundAxis = C5 * compoundAxis;\n    }\n  }\n\n  /* 20 C3 along sums of three positions*/\n  Eigen::Matrix<double, 3, 2> threeAxesBases;\n  threeAxesBases.col(0) = (axes.col(0) + axes.col(2) + axes.col(4)) / 3;\n  threeAxesBases.col(1) = (axes.col(2) + axes.col(4) - axes.col(3)) / 3;\n  for(unsigned i = 0; i < 2; ++i) {\n    Eigen::Vector3d compoundAxis = threeAxesBases.col(i);\n    for(unsigned j = 0; j < 5; ++j) {\n      elements.push_back(wrap(Rotation::Cn(compoundAxis, 3)));\n      elements.push_back(wrap(Rotation::Cn(-compoundAxis, 3)));\n      compoundAxis = C5 * compoundAxis;\n    }\n  }\n\n  assert(elements.size() == 60);\n  return elements;\n}\n\nElementsList Ih() {\n  ElementsList elements;\n  elements.push_back(wrap(Identity::E()));\n  elements.reserve(120);\n  /* i */\n  elements.push_back(wrap(Inversion::i()));\n  const double phi = (1 + std::sqrt(5)) / 2;\n  Eigen::Matrix<double, 3, 6> axes;\n  axes << 0.0, 0.0, phi, -phi, 1.0, 1.0,\n          1.0, 1.0, 0.0, 0.0, phi, -phi,\n          phi, -phi, 1.0, 1.0, 0.0, 0.0;\n\n  /* 12 S10, 12 S10^3, 12 C5, 12 C5^2 */\n  for(unsigned i = 0; i < 6; ++i) {\n    const auto& axis = axes.col(i);\n    elements.push_back(wrap(Rotation::Sn(axis, 10)));\n    elements.push_back(wrap(Rotation::Sn(-axis, 10)));\n    elements.push_back(wrap(Rotation::Sn(axis, 10, 3)));\n    elements.push_back(wrap(Rotation::Sn(-axis, 10, 3)));\n    // C5, C5^2, C5^3 = -C5^2, C5^4 = -C5\n    addProperAxisElements(elements, axis, 5);\n  }\n\n  /* 15 C2, 15 sigma along sums of two positions */\n  const Eigen::Matrix3d C5 = Eigen::AngleAxisd(2 * M_PI / 5, axes.col(0).normalized()).toRotationMatrix();\n  Eigen::Matrix3d twoAxesBases;\n  twoAxesBases.col(0) = (axes.col(0) + axes.col(2)) / 2;\n  twoAxesBases.col(1) = (axes.col(2) + axes.col(4)) / 2;\n  twoAxesBases.col(2) = (axes.col(2) - axes.col(3)) / 2;\n  for(unsigned i = 0; i < 3; ++i) {\n    Eigen::Vector3d compoundAxis = twoAxesBases.col(i);\n    for(unsigned j = 0; j < 5; ++j) {\n      elements.push_back(wrap(Rotation::Cn(compoundAxis, 2)));\n      elements.push_back(wrap(Reflection(compoundAxis)));\n      compoundAxis = C5 * compoundAxis;\n    }\n  }\n\n  /* 20 S6, 20 C3 along sums of three positions */\n  Eigen::Matrix<double, 3, 2> threeAxesBases;\n  threeAxesBases.col(0) = (axes.col(0) + axes.col(2) + axes.col(4)) / 3;\n  threeAxesBases.col(1) = (axes.col(2) + axes.col(4) - axes.col(3)) / 3;\n  for(unsigned i = 0; i < 2; ++i) {\n    Eigen::Vector3d compoundAxis = threeAxesBases.col(i);\n    for(unsigned j = 0; j < 5; ++j) {\n      elements.push_back(wrap(Rotation::Sn(compoundAxis, 6)));\n      elements.push_back(wrap(Rotation::Sn(-compoundAxis, 6)));\n      elements.push_back(wrap(Rotation::Cn(compoundAxis, 3)));\n      elements.push_back(wrap(Rotation::Cn(-compoundAxis, 3)));\n      compoundAxis = C5 * compoundAxis;\n    }\n  }\n  assert(elements.size() == 120);\n  return elements;\n}\n\n} // namespace\n\nIdentity Identity::E() {\n  return {};\n}\n\nSymmetryElement::Matrix Identity::matrix() const {\n  return Matrix::Identity();\n}\n\nboost::optional<SymmetryElement::Vector> Identity::vector() const {\n  return boost::none;\n}\n\nstd::string Identity::name() const {\n  return \"E\";\n}\n\nInversion Inversion::i() {\n  return {};\n}\n\nSymmetryElement::Matrix Inversion::matrix() const {\n  return -Matrix::Identity();\n}\n\nboost::optional<SymmetryElement::Vector> Inversion::vector() const {\n  return boost::none;\n}\n\nstd::string Inversion::name() const {\n  return \"i\";\n}\n\nRotation::Rotation(\n  const Eigen::Vector3d& passAxis,\n  const unsigned passN,\n  const unsigned passPower,\n  const bool passReflect\n) : axis(passAxis.normalized()),\n    n(passN),\n    power(passPower),\n    reflect(passReflect)\n{}\n\nRotation Rotation::Cn(const Eigen::Vector3d& axis, const unsigned n, const unsigned power) {\n  return Rotation(axis, n, power, false);\n}\n\nRotation Rotation::Sn(const Eigen::Vector3d& axis, const unsigned n, const unsigned power) {\n  return Rotation(axis, n, power, true);\n}\n\nRotation Rotation::operator * (const Rotation& rhs) const {\n  if(collinear(axis, rhs.axis)) {\n    if(n == rhs.n) {\n      return Rotation(axis, n, power + rhs.power, reflect xor rhs.reflect);\n    }\n\n    throw std::logic_error(\"Rotation data model cannot handle collinear multiplication of axes of different order n\");\n  }\n\n  if(orthogonal(axis, rhs.axis)) {\n    // Rotate rhs' axis by *this, but keep everything else\n    return Rotation(matrix() * rhs.axis, rhs.n, rhs.power, rhs.reflect);\n  }\n\n  throw std::logic_error(\"Rotation data model cannot handle non-orthogonal multiplication of rotations\");\n}\n\nSymmetryElement::Matrix Rotation::matrix() const {\n  if(!reflect) {\n    return Eigen::AngleAxisd(2 * M_PI * power / n, axis).toRotationMatrix();\n  }\n\n  const double angle = 2 * M_PI * power / n;\n  const double sine = std::sin(angle);\n  const double cosine = std::cos(angle);\n  const double onePlusCosine = 1 + cosine;\n\n  const double xx = cosine - axis(0) * axis(0) * onePlusCosine;\n  const double yy = cosine - axis(1) * axis(1) * onePlusCosine;\n  const double zz = cosine - axis(2) * axis(2) * onePlusCosine;\n\n  const double xy = - axis(0) * axis(1) * onePlusCosine;\n  const double xz = - axis(0) * axis(2) * onePlusCosine;\n  const double yz = - axis(1) * axis(2) * onePlusCosine;\n\n  const double x = axis(0) * sine;\n  const double y = axis(1) * sine;\n  const double z = axis(2) * sine;\n\n  Eigen::Matrix3d rotationMatrix;\n\n  rotationMatrix <<\n        xx, xy - z, xz + y,\n    xy + z,     yy, yz - x,\n    xz - y, yz + x,     zz;\n\n  return rotationMatrix;\n}\n\nboost::optional<SymmetryElement::Vector> Rotation::vector() const {\n  return axis;\n}\n\nstd::string Rotation::name() const {\n  std::string composite = (reflect ? \"S\" : \"C\");\n  composite += std::to_string(n);\n  if(power > 1) {\n    composite += \"^\" + std::to_string(power);\n  }\n  if(std::fabs(axis.z()) < 1e-8) {\n    composite += \"'\";\n  } else if(std::fabs(axis.x()) + std::fabs(axis.y()) > 1e-8) {\n    composite += (\n      \" along {\"\n      + std::to_string(axis.x()) + \", \"\n      + std::to_string(axis.y()) + \", \"\n      + std::to_string(axis.z()) + \"}\"\n    );\n  }\n  return composite;\n}\n\nReflection::Reflection(const Eigen::Vector3d& passNormal) : normal(passNormal.normalized()) {}\n\nReflection Reflection::sigma_xy() {\n  return Reflection(Eigen::Vector3d::UnitZ());\n}\n\nReflection Reflection::sigma_xz() {\n  return Reflection(Eigen::Vector3d::UnitY());\n}\n\nReflection Reflection::sigma_yz() {\n  return Reflection(Eigen::Vector3d::UnitX());\n}\n\nSymmetryElement::Matrix Reflection::matrix() const {\n  Eigen::Matrix3d reflection;\n\n  const double normalSquareNorm = normal.squaredNorm();\n\n  for(unsigned i = 0; i < 3; ++i) {\n    for(unsigned j = 0; j < 3; ++j) {\n      reflection(i, j) = (i == j ? 1 : 0) - 2 * normal(i) * normal(j) / normalSquareNorm;\n    }\n  }\n\n  return reflection;\n}\n\nboost::optional<SymmetryElement::Vector> Reflection::vector() const {\n  if(orthogonal(normal, Eigen::Vector3d::UnitZ())) {\n    return normal.cross(Eigen::Vector3d::UnitZ());\n  }\n\n  if(orthogonal(normal, Eigen::Vector3d::UnitX())) {\n    return normal.cross(Eigen::Vector3d::UnitX());\n  }\n\n  if(orthogonal(normal, Eigen::Vector3d::UnitY())) {\n    return normal.cross(Eigen::Vector3d::UnitY());\n  }\n\n  return boost::none;\n}\n\nstd::string Reflection::name() const {\n  std::string composite = \"sigma\";\n\n  if(normal.cwiseAbs().isApprox(Eigen::Vector3d::UnitZ(), 1e-8)) {\n    composite += \"h_\";\n  } else if(orthogonal(normal, Eigen::Vector3d::UnitZ())) {\n    composite += \"v_\";\n  } else {\n    composite += (\n      \" w/ normal {\"\n      + std::to_string(normal.x()) + \", \"\n      + std::to_string(normal.y()) + \", \"\n      + std::to_string(normal.z()) + \"}\"\n    );\n  }\n\n  if(normal.cwiseAbs().isApprox(Eigen::Vector3d::UnitX(), 1e-8)) {\n    composite += \" (yz)\";\n  } else if(normal.cwiseAbs().isApprox(Eigen::Vector3d::UnitY(), 1e-8)) {\n    composite += \" (xz)\";\n  }\n\n  return composite;\n}\n\nRotation operator * (const Rotation& rot, const Reflection& reflection) {\n  if(!collinear(rot.axis, reflection.normal)) {\n    throw std::logic_error(\"Cannot handle off-axis Rotation / Reflection combination\");\n  }\n\n  return Rotation(rot.axis, rot.n, rot.power, !rot.reflect);\n}\n\nRotation operator * (const Reflection& reflection, const Rotation& rot) {\n  return rot * reflection;\n}\n\nEigen::Matrix3d improperRotationMatrix(\n  const Eigen::Vector3d& axis,\n  const double angle\n) {\n  const double sine = std::sin(angle);\n  const double cosine = std::cos(angle);\n  const double onePlusCosine = 1 + cosine;\n\n  const double xx = cosine - axis(0) * axis(0) * onePlusCosine;\n  const double yy = cosine - axis(1) * axis(1) * onePlusCosine;\n  const double zz = cosine - axis(2) * axis(2) * onePlusCosine;\n\n  const double xy = - axis(0) * axis(1) * onePlusCosine;\n  const double xz = - axis(0) * axis(2) * onePlusCosine;\n  const double yz = - axis(1) * axis(2) * onePlusCosine;\n\n  const double x = axis(0) * sine;\n  const double y = axis(1) * sine;\n  const double z = axis(2) * sine;\n\n  Eigen::Matrix3d rotationMatrix;\n\n  rotationMatrix <<\n        xx, xy - z, xz + y,\n    xy + z,     yy, yz - x,\n    xz - y, yz + x,     zz;\n\n  return rotationMatrix;\n}\n\nEigen::Matrix3d properRotationMatrix(\n  const Eigen::Vector3d& axis,\n  const double angle\n) {\n  return Eigen::AngleAxisd(angle, axis).toRotationMatrix();\n}\n\nEigen::Matrix3d reflectionMatrix(const Eigen::Vector3d& planeNormal) {\n  Eigen::Matrix3d reflection;\n\n  const double normalSquareNorm = planeNormal.squaredNorm();\n\n  for(unsigned i = 0; i < 3; ++i) {\n    for(unsigned j = 0; j < 3; ++j) {\n      reflection(i, j) = (i == j ? 1 : 0) - 2 * planeNormal(i) * planeNormal(j) / normalSquareNorm;\n    }\n  }\n\n  return reflection;\n}\n\n//! Returns all symmetry elements of a point group\nElementsList symmetryElements(PointGroup group) noexcept {\n  if(group == PointGroup::Cinfv) {\n    group = PointGroup::C8v;\n  }\n\n  if(group == PointGroup::Dinfh) {\n    group = PointGroup::D8h;\n  }\n\n  const Identity E {};\n  const Inversion inversion {};\n\n  const auto e_x = Eigen::Vector3d::UnitX();\n  const auto e_y = Eigen::Vector3d::UnitY();\n  const auto e_z = Eigen::Vector3d::UnitZ();\n\n  const Reflection sigma_xy {e_z};\n  const Reflection sigma_xz {e_y};\n  const Reflection sigma_yz {e_x};\n\n  const double tetrahedronAngle = 2 * std::atan(std::sqrt(2));\n\n  ElementsList elements;\n  elements.push_back(wrap(E));\n\n  switch(group) {\n    case(PointGroup::C1):\n      return elements;\n\n    case(PointGroup::Ci):\n      {\n        elements.push_back(wrap(inversion));\n        return elements;\n      }\n\n    case(PointGroup::Cs):\n      {\n        elements.push_back(wrap(sigma_xy));\n        return elements;\n      }\n\n    case(PointGroup::C2):\n    case(PointGroup::C3):\n    case(PointGroup::C4):\n    case(PointGroup::C5):\n    case(PointGroup::C6):\n    case(PointGroup::C7):\n    case(PointGroup::C8):\n      {\n        const unsigned n = 2 + underlying(group) - underlying(PointGroup::C2);\n        addProperAxisElements(elements, e_z, n);\n        assert(elements.size() == n);\n        return elements;\n      }\n\n    case(PointGroup::C2h):\n    case(PointGroup::C3h):\n    case(PointGroup::C4h):\n    case(PointGroup::C5h):\n    case(PointGroup::C6h):\n    case(PointGroup::C7h):\n    case(PointGroup::C8h):\n      {\n        const unsigned n = 2 + underlying(group) - underlying(PointGroup::C2h);\n        std::vector<Rotation> rotations;\n        const Rotation element = Rotation::Cn(e_z, n);\n        Rotation composite = element;\n        for(unsigned i = n; i > 1; --i) {\n          rotations.push_back(composite);\n          composite = element * composite;\n        }\n        const unsigned S = rotations.size();\n        // Add sigma_xy modified Cn axes\n        for(unsigned i = 0; i < S; ++i) {\n          rotations.push_back(sigma_xy * rotations.at(i));\n        }\n        return Cnh(2 + underlying(group) - underlying(PointGroup::C2h));\n      }\n\n    case(PointGroup::C2v):\n    case(PointGroup::C3v):\n    case(PointGroup::C4v):\n    case(PointGroup::C5v):\n    case(PointGroup::C6v):\n    case(PointGroup::C7v):\n    case(PointGroup::C8v):\n      {\n        return Cnv(2 + underlying(group) - underlying(PointGroup::C2v));\n      }\n\n    case(PointGroup::S4):\n    case(PointGroup::S6):\n    case(PointGroup::S8):\n      {\n        const unsigned n = 4 + 2 * (underlying(group) - underlying(PointGroup::S4));\n        addImproperAxisElements(elements, e_z, n);\n        assert(elements.size() == n);\n        return elements;\n      }\n\n    case(PointGroup::D2):\n    case(PointGroup::D3):\n    case(PointGroup::D4):\n    case(PointGroup::D5):\n    case(PointGroup::D6):\n    case(PointGroup::D7):\n    case(PointGroup::D8):\n      {\n        return Dn(2 + underlying(group) - underlying(PointGroup::D2));\n      }\n\n    case(PointGroup::D2h):\n    case(PointGroup::D3h):\n    case(PointGroup::D4h):\n    case(PointGroup::D5h):\n    case(PointGroup::D6h):\n    case(PointGroup::D7h):\n    case(PointGroup::D8h):\n      {\n        return Dnh(2 + underlying(group) - underlying(PointGroup::D2h));\n      }\n\n    case(PointGroup::D2d):\n    case(PointGroup::D3d):\n    case(PointGroup::D4d):\n    case(PointGroup::D5d):\n    case(PointGroup::D6d):\n    case(PointGroup::D7d):\n    case(PointGroup::D8d):\n      {\n        return Dnd(2 + underlying(group) - underlying(PointGroup::D2d));\n      }\n\n    /* Cubic groups */\n    case(PointGroup::T):\n      {\n        elements.reserve(12);\n        const Eigen::Vector3d axis_2 = properRotationMatrix(e_y, tetrahedronAngle) * e_z;\n        const Eigen::Vector3d axis_3 = Rotation::Cn(e_z, 3).matrix() * axis_2;\n        const Eigen::Vector3d axis_4 = Rotation::Cn(e_z, 3).matrix() * axis_3;\n        addProperAxisElements(elements, e_z, 3);\n        addProperAxisElements(elements, axis_2, 3);\n        addProperAxisElements(elements, axis_3, 3);\n        addProperAxisElements(elements, axis_4, 3);\n        elements.push_back(wrap(Rotation::Cn((e_z + axis_2).normalized(), 2)));\n        elements.push_back(wrap(Rotation::Cn((e_z + axis_3).normalized(), 2)));\n        elements.push_back(wrap(Rotation::Cn((e_z + axis_4).normalized(), 2)));\n        assert(elements.size() == 12);\n        return elements;\n      }\n\n    case(PointGroup::Td):\n      {\n        elements.reserve(24);\n        Eigen::Matrix<double, 3, Eigen::Dynamic> positions(3, 4);\n        positions.col(0) = e_z;\n        positions.col(1) = properRotationMatrix(e_y, tetrahedronAngle) * e_z;\n        positions.col(2) = Rotation::Cn(e_z, 3).matrix() * positions.col(1);\n        positions.col(3) = Rotation::Cn(e_z, 3).matrix() * positions.col(2);\n        // C3 axes\n        addProperAxisElements(elements, e_z, 3);\n        addProperAxisElements(elements, positions.col(1), 3);\n        addProperAxisElements(elements, positions.col(2), 3);\n        addProperAxisElements(elements, positions.col(3), 3);\n        const Eigen::Vector3d axis_12 = (e_z + positions.col(1)).normalized();\n        const Eigen::Vector3d axis_13 = (e_z + positions.col(2)).normalized();\n        const Eigen::Vector3d axis_14 = (e_z + positions.col(3)).normalized();\n        // S4, C2, S4^3\n        addImproperAxisElements(elements, axis_12, 4);\n        addImproperAxisElements(elements, axis_13, 4);\n        addImproperAxisElements(elements, axis_14, 4);\n        // Sigma d\n        for(unsigned i = 0; i < 3; ++i) {\n          for(unsigned j = i + 1; j < 4; ++j) {\n            elements.push_back(\n              wrap(Reflection(\n                positions.col(i).cross(positions.col(j))\n              ))\n            );\n          }\n        }\n        assert(elements.size() == 24);\n        return elements;\n      }\n    case(PointGroup::Th):\n      {\n        elements.reserve(24);\n        /* i */\n        elements.push_back(wrap(inversion));\n        /* 4 S6, 4 C3, 4 C3^2, 4 S6^5 along lin. comb. of three axes */\n        { // +++ <-> ---\n          const Eigen::Vector3d axis_ppp = (  e_x + e_y + e_z).normalized();\n          addProperAxisElements(elements, axis_ppp, 3);\n          elements.push_back(wrap(Rotation::Sn(axis_ppp, 6)));\n          elements.push_back(wrap(Rotation::Sn(axis_ppp, 6, 5)));\n        }\n        { // ++- <-> --+\n          const Eigen::Vector3d axis_ppm = (  e_x + e_y - e_z).normalized();\n          addProperAxisElements(elements, axis_ppm, 3);\n          elements.push_back(wrap(Rotation::Sn(axis_ppm, 6)));\n          elements.push_back(wrap(Rotation::Sn(axis_ppm, 6, 5)));\n        }\n        { // +-+ <-> -+-\n          const Eigen::Vector3d axis_pmp = (  e_x - e_y + e_z).normalized();\n          addProperAxisElements(elements, axis_pmp, 3);\n          elements.push_back(wrap(Rotation::Sn(axis_pmp, 6)));\n          elements.push_back(wrap(Rotation::Sn(axis_pmp, 6, 5)));\n        }\n        { // -++ <-> +--\n          const Eigen::Vector3d axis_mpp = (- e_x + e_y + e_z).normalized();\n          addProperAxisElements(elements, axis_mpp, 3);\n          elements.push_back(wrap(Rotation::Sn(axis_mpp, 6)));\n          elements.push_back(wrap(Rotation::Sn(axis_mpp, 6, 5)));\n        }\n        /* 3 C2 along axes */\n        elements.push_back(wrap(Rotation::Cn(e_x, 2)));\n        elements.push_back(wrap(Rotation::Cn(e_y, 2)));\n        elements.push_back(wrap(Rotation::Cn(e_z, 2)));\n        /* 3 sigma_h with normals along axes */\n        elements.push_back(wrap(Reflection(e_x)));\n        elements.push_back(wrap(Reflection(e_y)));\n        elements.push_back(wrap(Reflection(e_z)));\n        assert(elements.size() == 24);\n        return elements;\n      }\n\n    case(PointGroup::O):\n      {\n        elements.reserve(24);\n        /* 6 C4, 3 C2 (C4^2) == C4, C2 and C4^3 along the coordinate axes */\n        addProperAxisElements(elements, e_x, 4);\n        addProperAxisElements(elements, e_y, 4);\n        addProperAxisElements(elements, e_z, 4);\n        /* 8 C3 along linear combinations of three axes */\n        { // +++ <-> ---\n          const Eigen::Vector3d axis_ppp = (  e_x + e_y + e_z).normalized();\n          addProperAxisElements(elements, axis_ppp, 3);\n        }\n        { // ++- <-> --+\n          const Eigen::Vector3d axis_ppm = (  e_x + e_y - e_z).normalized();\n          addProperAxisElements(elements, axis_ppm, 3);\n        }\n        { // +-+ <-> -+-\n          const Eigen::Vector3d axis_pmp = (  e_x - e_y + e_z).normalized();\n          addProperAxisElements(elements, axis_pmp, 3);\n        }\n        { // -++ <-> +--\n          const Eigen::Vector3d axis_mpp = (- e_x + e_y + e_z).normalized();\n          addProperAxisElements(elements, axis_mpp, 3);\n        }\n        /* 6 C2' along combinations of two axes */\n        elements.push_back(wrap(Rotation::Cn((e_x + e_y).normalized(), 2)));\n        elements.push_back(wrap(Rotation::Cn((e_x - e_y).normalized(), 2)));\n        elements.push_back(wrap(Rotation::Cn((e_x + e_z).normalized(), 2)));\n        elements.push_back(wrap(Rotation::Cn((e_x - e_z).normalized(), 2)));\n        elements.push_back(wrap(Rotation::Cn((e_y + e_z).normalized(), 2)));\n        elements.push_back(wrap(Rotation::Cn((e_y - e_z).normalized(), 2)));\n        assert(elements.size() == 24);\n        return elements;\n      }\n    case(PointGroup::Oh):\n      {\n        elements.push_back(wrap(inversion));\n        elements.reserve(48);\n        /* 8 C3 and 8 S6 share the linear combinations of three axes */\n        { // +++ <-> ---\n          const Eigen::Vector3d axis_ppp = (  e_x + e_y + e_z).normalized();\n          addProperAxisElements(elements, axis_ppp, 3);\n          elements.push_back(wrap(Rotation::Sn(axis_ppp, 6)));\n          elements.push_back(wrap(Rotation::Sn(-axis_ppp, 6)));\n        }\n        { // ++- <-> --+\n          const Eigen::Vector3d axis_ppm = (  e_x + e_y - e_z).normalized();\n          addProperAxisElements(elements, axis_ppm, 3);\n          elements.push_back(wrap(Rotation::Sn(axis_ppm, 6)));\n          elements.push_back(wrap(Rotation::Sn(-axis_ppm, 6)));\n        }\n        { // +-+ <-> -+-\n          const Eigen::Vector3d axis_pmp = (  e_x - e_y + e_z).normalized();\n          addProperAxisElements(elements, axis_pmp, 3);\n          elements.push_back(wrap(Rotation::Sn(axis_pmp, 6)));\n          elements.push_back(wrap(Rotation::Sn(-axis_pmp, 6)));\n        }\n        { // -++ <-> +--\n          const Eigen::Vector3d axis_mpp = (- e_x + e_y + e_z).normalized();\n          addProperAxisElements(elements, axis_mpp, 3);\n          elements.push_back(wrap(Rotation::Sn(axis_mpp, 6)));\n          elements.push_back(wrap(Rotation::Sn(-axis_mpp, 6)));\n        }\n        /* 6 C2 along linear combinations of two axes */\n        elements.push_back(wrap(Rotation::Cn((e_x + e_y).normalized(), 2)));\n        elements.push_back(wrap(Rotation::Cn((e_x - e_y).normalized(), 2)));\n        elements.push_back(wrap(Rotation::Cn((e_x + e_z).normalized(), 2)));\n        elements.push_back(wrap(Rotation::Cn((e_x - e_z).normalized(), 2)));\n        elements.push_back(wrap(Rotation::Cn((e_y + e_z).normalized(), 2)));\n        elements.push_back(wrap(Rotation::Cn((e_y - e_z).normalized(), 2)));\n        /* 6 C4 and 3 C2 (C4^2) along axes */\n        addProperAxisElements(elements, e_x, 4);\n        addProperAxisElements(elements, e_y, 4);\n        addProperAxisElements(elements, e_z, 4);\n        /* 6 S4 along axes */\n        elements.push_back(wrap(Rotation::Sn(  e_x, 4)));\n        elements.push_back(wrap(Rotation::Sn(- e_x, 4)));\n        elements.push_back(wrap(Rotation::Sn(  e_y, 4)));\n        elements.push_back(wrap(Rotation::Sn(- e_y, 4)));\n        elements.push_back(wrap(Rotation::Sn(  e_z, 4)));\n        elements.push_back(wrap(Rotation::Sn(- e_z, 4)));\n        /* 3 sigma h along combinations of two axes */\n        elements.push_back(wrap(sigma_xy));\n        elements.push_back(wrap(sigma_xz));\n        elements.push_back(wrap(sigma_yz));\n        /* 6 sigma d along linear combinations of three axes */\n        elements.push_back(wrap(Reflection((e_x + e_y).cross(e_z))));\n        elements.push_back(wrap(Reflection((e_x - e_y).cross(e_z))));\n        elements.push_back(wrap(Reflection((e_x + e_z).cross(e_y))));\n        elements.push_back(wrap(Reflection((e_x - e_z).cross(e_y))));\n        elements.push_back(wrap(Reflection((e_y + e_z).cross(e_x))));\n        elements.push_back(wrap(Reflection((e_y - e_z).cross(e_x))));\n        assert(elements.size() == 48);\n        return elements;\n      }\n\n    /* Icosahedral groups */\n    case(PointGroup::I):\n        return I();\n\n    case(PointGroup::Ih):\n        return Ih();\n\n    default:\n      return {};\n  }\n}\n\nunsigned order(const PointGroup group) {\n  const std::vector<unsigned> orders {\n    1, 2, 2, // C1, Ci, Cs\n    2, 3, 4, 5, 6, 7, 8, // Cn\n    4, 6, 8, 10, 12, 14, 16, // Cnh\n    4, 6, 8, 10, 12, 14, 16, // Cnv\n    4, 6, 8, // S4, S6, S8\n    4, 6, 8, 10, 12, 14, 16, // Dn\n    8, 12, 16, 20, 24, 28, 32, // Dnh\n    8, 12, 16, 20, 24, 28, 32, // Dnd\n    12, 24, 24, // T, Td, Th\n    24, 48, // O, Oh\n    60, 120, // I, Ih\n    16, 32 // Cinfv, Dinfh (forwarded to C8v and D8h)\n  };\n  return orders.at(underlying(group));\n}\n\nNpGroupingsMapType npGroupings(const ElementsList& elements) {\n  assert(elements.front()->matrix() == Elements::Identity().matrix());\n  const unsigned E = elements.size();\n\n  NpGroupingsMapType npGroupings;\n\n  auto testVector = [&](const Eigen::Vector3d& v) {\n    // Check if there is already a grouping for this vector\n    for(const auto& iterPair : npGroupings) {\n      if(Temple::any_of(\n        iterPair.second,\n        [&v](const ElementGrouping& grouping) -> bool {\n          return grouping.probePoint.isApprox(v, 1e-8);\n        }\n      )) {\n        return;\n      }\n    }\n\n    Eigen::Matrix<double, 3, Eigen::Dynamic> mappedPoints(3, E);\n    mappedPoints.col(0) = v;\n    unsigned np = 1;\n    std::vector<\n      std::vector<unsigned>\n    > groups {\n      {0}\n    };\n\n    for(unsigned i = 1; i < E; ++i) {\n      Eigen::Vector3d mapped = elements.at(i)->matrix() * mappedPoints.col(0);\n      bool found = false;\n      for(unsigned j = 0; j < np; ++j) {\n        if(mappedPoints.col(j).isApprox(mapped, 1e-8)) {\n          found = true;\n          groups.at(j).push_back(i);\n          break;\n        }\n      }\n\n      if(!found) {\n        mappedPoints.col(np) = mapped;\n        ++np;\n        groups.push_back(std::vector<unsigned> {i});\n      }\n    }\n\n    assert(std::is_sorted(std::begin(groups), std::end(groups)));\n\n    ElementGrouping grouping;\n    grouping.probePoint = mappedPoints.col(0);\n    grouping.groups = std::move(groups);\n    auto findIter = npGroupings.find(np);\n    if(findIter == std::end(npGroupings)) {\n      npGroupings.emplace(np, std::vector<ElementGrouping> {std::move(grouping)});\n    } else {\n      auto& groupingsList = findIter->second;\n      if(\n        !Temple::any_of(\n          groupingsList,\n          [&grouping](const ElementGrouping& group) -> bool {\n            return grouping.groups == group.groups;\n          }\n        )\n      ) {\n        groupingsList.push_back(std::move(grouping));\n      }\n    }\n  };\n\n  testVector(Eigen::Vector3d::UnitZ());\n  testVector(Eigen::Vector3d::UnitZ() + 0.1 * Eigen::Vector3d::UnitX());\n  testVector(Eigen::Vector3d::UnitX());\n  testVector(Eigen::Vector3d::UnitY());\n  testVector(Eigen::Vector3d::Zero());\n\n  for(const auto& elementPtr : elements) {\n    if(auto axisOption = elementPtr->vector()) {\n      testVector(*axisOption);\n    }\n  }\n\n  return npGroupings;\n}\n\n} // namespace Elements\n} // namespace Shapes\n} // namespace Molassembler\n} // namespace Scine\n", "meta": {"hexsha": "a6960d89bc8e6c6b7738724ed152624b2a856736", "size": 31815, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Molassembler/Shapes/PointGroupElements.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "src/Molassembler/Shapes/PointGroupElements.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Molassembler/Shapes/PointGroupElements.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 32.3652085453, "max_line_length": 118, "alphanum_fraction": 0.614647179, "num_tokens": 9403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4286968293265634}}
{"text": "#ifndef nomad__src__autodiff__first_order_hpp\n#define nomad__src__autodiff__first_order_hpp\n\n#include <iomanip>\n#include <string>\n#include <type_traits>\n\n#include <Eigen/Core>\n\n#include <src/var/var.hpp>\n#include <src/autodiff/exceptions.hpp>\n\nnamespace nomad {\n\n  template<class T_var>\n  void first_order_forward_adj(const T_var& v) {\n    for (nomad_idx_t i = 1; i <= v.node(); ++i)\n      var_nodes_[i].first_order_forward_adj();\n  }\n  \n  template<class T_var>\n  void first_order_reverse_adj(const T_var& v) {\n    var_nodes_[v.node()].first_grad() = 1.0;\n    for (nomad_idx_t i = v.node(); i > 0; --i)\n      var_nodes_[i].first_order_reverse_adj();\n  }\n\n  template <typename F>\n  typename std::enable_if<is_var<typename F::var_type>::value && F::var_type::order() >= 1, void >::type\n  gradient(const F& functional,\n           const Eigen::VectorXd& x,\n           double& f,\n           Eigen::VectorXd& g) {\n    \n    reset();\n\n    try {\n      \n      auto f_var = functional(x);\n      \n      \n      f = f_var.first_val();\n      first_order_reverse_adj(f_var);\n      \n      for (eigen_idx_t i = 0; i < x.size(); ++i)\n      g(i) = var_nodes_[i + 1].first_grad();\n      \n      reset();\n      \n    } catch (nomad_error& e) {\n      reset();\n      throw e;\n    }\n    \n  }\n  \n  template <typename F>\n  void gradient(const F& functional,\n                const Eigen::VectorXd& x,\n                Eigen::VectorXd& g) {\n    double f;\n    gradient(functional, x, f, g);\n  }\n  \n  template <typename F>\n  typename std::enable_if<is_var<typename F::var_type>::value && F::var_type::order() >= 0, void >::type\n  finite_diff_gradient(const F& functional,\n                       const Eigen::VectorXd& x,\n                       Eigen::VectorXd& g,\n                       const double epsilon = 1e-6) {\n    \n    Eigen::VectorXd x_dynam(x);\n    \n    for (eigen_idx_t i = 0; i < x.size(); ++i) {\n      \n      double delta_f = 0;\n      \n      x_dynam(i) += epsilon;\n      auto v1 = functional(x_dynam);\n      delta_f += v1.first_val();\n      reset();\n      \n      x_dynam(i) -= 2.0 * epsilon;\n      auto v2 = functional(x_dynam);\n      delta_f -= v2.first_val();\n      reset();\n      \n      x_dynam(i) += epsilon;\n      \n      delta_f /= 2.0 * epsilon;\n      \n      g(i) = delta_f;\n      \n    }\n    \n  }\n  \n  template <typename F>\n  void test_gradient(const F& functional,\n                     const Eigen::VectorXd& x,\n                     const double epsilon = 1e-6) {\n    \n    Eigen::VectorXd auto_grad(x.size());\n    try {\n      gradient(functional, x, auto_grad);\n    } catch (std::runtime_error& e) {\n      std::cout << \"Cannot compute Gradient Test\" << std::endl;\n      throw e;\n    }\n    \n    Eigen::VectorXd diff_grad(x.size());\n    try {\n      finite_diff_gradient(functional, x, diff_grad, epsilon);\n    } catch (std::runtime_error& e) {\n      std::cout << \"Cannot compute Gradient Test\" << std::endl;\n      throw e;\n    }\n    \n    std::cout.precision(6);\n    int width = 12;\n    int n_column = 4;\n    \n    std::cout << \"Gradient Test:\" << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"Component\"\n              << std::setw(width) << std::left << \"Automatic\"\n              << std::setw(width) << std::left << \"Finite\"\n              << std::setw(width) << std::left << \"Delta / \"\n              << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"(i)\"\n              << std::setw(width) << std::left << \"Derivative\"\n              << std::setw(width) << std::left << \"Difference\"\n              << std::setw(width) << std::left << \"Stepsize^{2}\"\n              << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    \n    Eigen::VectorXd x_dynam(x);\n    \n    for (eigen_idx_t i = 0; i < x.size(); ++i) {\n      std::cout << \"    \"\n                << std::setw(width) << std::left << i\n                << std::setw(width) << std::left << auto_grad(i)\n                << std::setw(width) << std::left << diff_grad(i)\n                << std::setw(width) << std::left << (auto_grad(i) - diff_grad(i)) / (epsilon * epsilon)\n                << std::endl;\n      \n    }\n    \n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << std::endl;\n    \n  }\n  \n  template <typename F>\n  typename std::enable_if<is_var<typename F::var_type>::value && F::var_type::order() >= 1, void >::type\n  gradient_dot_vector(const F& functional,\n                      const Eigen::VectorXd& x,\n                      const Eigen::VectorXd& v,\n                      double& f,\n                      double& grad_dot_v) {\n    \n    reset();\n    \n    try {\n      \n      auto f_var = functional(x);\n      \n      f = f_var.first_val();\n      \n      for (eigen_idx_t i = 0; i < x.size(); ++i)\n      var_nodes_[i + 1].first_grad() = v(i);\n      \n      first_order_forward_adj(f_var);\n      \n      grad_dot_v = f_var.first_grad();\n      \n      reset();\n      \n    } catch (nomad_error& e) {\n      reset();\n      throw e;\n    }\n    \n  }\n  \n  template <typename F>\n  void gradient_dot_vector(const F& functional,\n                           const Eigen::VectorXd& x,\n                           const Eigen::VectorXd& v,\n                           double& grad_dot_v) {\n    double f;\n    gradient_dot_vector(functional, x, v, f, grad_dot_v);\n  }\n  \n  template <typename F>\n  void test_gradient_dot_vector(const F& functional,\n                                const Eigen::VectorXd& x,\n                                const Eigen::VectorXd& v) {\n    \n    Eigen::VectorXd g_auto(x.size());\n    try {\n      gradient(functional, x, g_auto);\n    } catch (nomad_error& e) {\n      std::cout << \"Cannot compute Gradient Dot Vector Test\" << std::endl;\n      std::cout << e.what() << std::endl;\n    }\n    \n    double g_dot_v = g_auto.dot(v);\n    \n    double g_dot_v_auto;\n    try {\n      gradient_dot_vector(functional, x, v, g_dot_v_auto);\n    } catch (nomad_error& e) {\n      std::cout << \"Cannot compute Gradient Dot Vector Test\" << std::endl;\n      std::cout << e.what() << std::endl;\n    }\n    \n    std::cout.precision(6);\n    int width = 12;\n    int n_column = 2;\n    \n    std::cout << \"Gradient Dot Vector Test:\" << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"Automatic\"\n              << std::setw(width) << std::left << \"Exact\"\n              << std::endl;\n    std::cout << \"    \"\n              << std::setw(width) << std::left << \"Derivative\"\n              << std::setw(width) << std::left << \"\"\n              << std::endl;\n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    \n    std::cout << \"    \"\n              << std::setw(width) << std::left << g_dot_v_auto\n              << std::setw(width) << std::left << g_dot_v\n              << std::endl;\n    \n    std::cout << \"    \" << std::setw(n_column * width) << std::setfill('-')\n              << \"\" << std::setfill(' ') << std::endl;\n    std::cout << std::endl;\n    \n  }\n  \n}\n\n#endif\n", "meta": {"hexsha": "735cf5b584c08f7776760b0cf8f5af9488a010c6", "size": 7423, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/autodiff/first_order.hpp", "max_stars_repo_name": "stan-dev/nomad", "max_stars_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-12-11T20:06:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T18:59:58.000Z", "max_issues_repo_path": "src/autodiff/first_order.hpp", "max_issues_repo_name": "stan-dev/nomad", "max_issues_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-12-15T08:12:01.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-17T01:36:56.000Z", "max_forks_repo_path": "src/autodiff/first_order.hpp", "max_forks_repo_name": "stan-dev/nomad", "max_forks_repo_head_hexsha": "a21149ef9f4d53a198e6fdb06cfd0363d3df69e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-10-13T17:40:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T19:17:51.000Z", "avg_line_length": 29.1098039216, "max_line_length": 104, "alphanum_fraction": 0.4957564327, "num_tokens": 1969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.6442251064863697, "lm_q1q2_score": 0.42867417951673525}}
{"text": "// Copyright (c) 2008-2017 Emil Dotchevski and Reverge Studios, Inc.\n\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_QVM_E5F500D4618DBE7B51573B33821F\n#define BOOST_QVM_E5F500D4618DBE7B51573B33821F\n\n// This file was generated by a program. Do not edit manually.\n\n#include <boost/qvm/deduce_vec.hpp>\n#include <boost/qvm/enable_if.hpp>\n#include <boost/qvm/inline.hpp>\n#include <boost/qvm/mat_traits.hpp>\n#include <boost/qvm/vec_traits.hpp>\n\nnamespace boost {\nnamespace qvm {\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<mat_traits<A>::rows == 3 &&\n                                  mat_traits<A>::cols == 3 &&\n                                  vec_traits<B>::dim == 3,\n                              deduce_vec2<A, B, 3>>::type\n    operator*(A const &a, B const &b) {\n  typedef typename mat_traits<A>::scalar_type Ta;\n  typedef typename vec_traits<B>::scalar_type Tb;\n  Ta const a00 = mat_traits<A>::template read_element<0, 0>(a);\n  Ta const a01 = mat_traits<A>::template read_element<0, 1>(a);\n  Ta const a02 = mat_traits<A>::template read_element<0, 2>(a);\n  Ta const a10 = mat_traits<A>::template read_element<1, 0>(a);\n  Ta const a11 = mat_traits<A>::template read_element<1, 1>(a);\n  Ta const a12 = mat_traits<A>::template read_element<1, 2>(a);\n  Ta const a20 = mat_traits<A>::template read_element<2, 0>(a);\n  Ta const a21 = mat_traits<A>::template read_element<2, 1>(a);\n  Ta const a22 = mat_traits<A>::template read_element<2, 2>(a);\n  Tb const b0 = vec_traits<B>::template read_element<0>(b);\n  Tb const b1 = vec_traits<B>::template read_element<1>(b);\n  Tb const b2 = vec_traits<B>::template read_element<2>(b);\n  typedef typename deduce_vec2<A, B, 3>::type R;\n  BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim == 3);\n  R r;\n  vec_traits<R>::template write_element<0>(r) = a00 * b0 + a01 * b1 + a02 * b2;\n  vec_traits<R>::template write_element<1>(r) = a10 * b0 + a11 * b1 + a12 * b2;\n  vec_traits<R>::template write_element<2>(r) = a20 * b0 + a21 * b1 + a22 * b2;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct mul_mv_defined;\n\ntemplate <> struct mul_mv_defined<3, 3> { static bool const value = true; };\n} // namespace qvm_detail\n\ntemplate <class A, class B>\nBOOST_QVM_INLINE_OPERATIONS\n    typename lazy_enable_if_c<mat_traits<B>::rows == 3 &&\n                                  mat_traits<B>::cols == 3 &&\n                                  vec_traits<A>::dim == 3,\n                              deduce_vec2<A, B, 3>>::type\n    operator*(A const &a, B const &b) {\n  typedef typename vec_traits<A>::scalar_type Ta;\n  typedef typename mat_traits<B>::scalar_type Tb;\n  Ta const a0 = vec_traits<A>::template read_element<0>(a);\n  Ta const a1 = vec_traits<A>::template read_element<1>(a);\n  Ta const a2 = vec_traits<A>::template read_element<2>(a);\n  Tb const b00 = mat_traits<B>::template read_element<0, 0>(b);\n  Tb const b01 = mat_traits<B>::template read_element<0, 1>(b);\n  Tb const b02 = mat_traits<B>::template read_element<0, 2>(b);\n  Tb const b10 = mat_traits<B>::template read_element<1, 0>(b);\n  Tb const b11 = mat_traits<B>::template read_element<1, 1>(b);\n  Tb const b12 = mat_traits<B>::template read_element<1, 2>(b);\n  Tb const b20 = mat_traits<B>::template read_element<2, 0>(b);\n  Tb const b21 = mat_traits<B>::template read_element<2, 1>(b);\n  Tb const b22 = mat_traits<B>::template read_element<2, 2>(b);\n  typedef typename deduce_vec2<A, B, 3>::type R;\n  BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim == 3);\n  R r;\n  vec_traits<R>::template write_element<0>(r) = a0 * b00 + a1 * b10 + a2 * b20;\n  vec_traits<R>::template write_element<1>(r) = a0 * b01 + a1 * b11 + a2 * b21;\n  vec_traits<R>::template write_element<2>(r) = a0 * b02 + a1 * b12 + a2 * b22;\n  return r;\n}\n\nnamespace sfinae {\nusing ::boost::qvm::operator*;\n}\n\nnamespace qvm_detail {\ntemplate <int R, int C> struct mul_vm_defined;\n\ntemplate <> struct mul_vm_defined<3, 3> { static bool const value = true; };\n} // namespace qvm_detail\n\n} // namespace qvm\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "0e5b42a91b273593b495270645ee053dba3c18b5", "size": 4201, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/qvm/gen/vec_mat_operations3.hpp", "max_stars_repo_name": "henrywarhurst/matrix", "max_stars_repo_head_hexsha": "317a2a7c35c1c7e3730986668ad2270dc19809ef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/boost_1_72_0/boost/qvm/gen/vec_mat_operations3.hpp", "max_issues_repo_name": "henrywarhurst/matrix", "max_issues_repo_head_hexsha": "317a2a7c35c1c7e3730986668ad2270dc19809ef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/boost_1_72_0/boost/qvm/gen/vec_mat_operations3.hpp", "max_forks_repo_name": "henrywarhurst/matrix", "max_forks_repo_head_hexsha": "317a2a7c35c1c7e3730986668ad2270dc19809ef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.786407767, "max_line_length": 79, "alphanum_fraction": 0.6657938586, "num_tokens": 1277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.42859351444915306}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_BESSEL_FUNCTIONS_SCALAR_J0_HPP_INCLUDED\n#define NT2_BESSEL_FUNCTIONS_SCALAR_J0_HPP_INCLUDED\n\n#include <nt2/bessel/functions/j0.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/oneminus.hpp>\n#include <nt2/include/functions/scalar/sqr.hpp>\n#include <nt2/include/functions/scalar/sqrt.hpp>\n#include <nt2/include/functions/scalar/cos.hpp>\n#include <nt2/include/functions/scalar/is_inf.hpp>\n#include <nt2/include/constants/real.hpp>\n#include <nt2/include/constants/digits.hpp>\n#include <boost/simd/sdk/math.hpp>\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( j0_, tag::cpu_\n                            , (A0)\n                            , (scalar_< arithmetic_<A0> >)\n                            )\n  {\n    typedef typename boost::dispatch::meta::as_floating<A0>::type result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      return nt2::j0(result_type(a0));\n    }\n  };\n} }\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is double\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( j0_, tag::cpu_\n                            , (A0)\n                            , (scalar_< double_<A0> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      if (is_inf(a0)) return Zero<A0>();\n#if defined(BOOST_SIMD_HAS__J0)\n      return ::_j0(a0);\n#elif defined(BOOST_SIMD_HAS_J0)\n      return ::j0(a0);\n#else\n#error j0 not supported\n#endif\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is float\n/////////////////////////////////////////////////////////////////////////////\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( j0_, tag::cpu_\n                            , (A0)\n                            , (scalar_< single_<A0> >)\n                            )\n  {\n\n    typedef A0 result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename meta::scalar_of<A0>::type stype;\n      if (is_inf(a0)) return Zero<A0>();\n      A0 x = nt2::abs(a0);\n      // if (x < 1.0e-3f) return oneminus(Quarter<A0>()*sqr(x));\n      if (x <= Two<A0>())\n      {\n        A0 z = sqr(x);\n        return (z-single_constant<float,0x40b90fdc> ())*\n               horner< NT2_HORNER_COEFF_T(stype, 5,\n                      (0xb382511c,\n                       0x36d660a0,\n                       0xb9d01fb1,\n                       0x3c5a6271,\n                       0xbe3110a6\n                      ) ) > (z);\n      }\n      A0 q = rec(x);\n      const A0 p3 = nt2::sqrt(q) *\n        horner< NT2_HORNER_COEFF_T(stype, 8,\n               (0xbd8c100e,\n                0x3e3ef887,\n                0xbe5ba616,\n                0x3df54214,\n                0xbb69539e,\n                0xbd4b8bc1,\n                0xb6612dc2,\n                0x3f4c422a\n                ) ) > (q);\n            const A0 xn =  q*\n              horner< NT2_HORNER_COEFF_T(stype, 8,\n               (0x4201aee0,\n                0xc2113945,\n                0x418c7f6a,\n                0xc09f3306,\n                0x3f8040aa,\n                0xbe46a57f,\n                0x3d84ed6e,\n                0xbdffff97\n                ) ) > (sqr(q))-Pio_4<A0>();\n      return p3*nt2::cos(xn+x);\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "124033dd028d6abc658e49ad76788249f59cdc1e", "size": 4085, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/bessel/include/nt2/bessel/functions/scalar/j0.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/bessel/include/nt2/bessel/functions/scalar/j0.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/bessel/include/nt2/bessel/functions/scalar/j0.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 31.4230769231, "max_line_length": 80, "alphanum_fraction": 0.447246022, "num_tokens": 989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.42859351444915306}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2021,\n *  Max Planck Institute for Intelligent Systems (MPI-IS).\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the MPI-IS nor the names\n *     of its contributors may be used to endorse or promote products\n *     derived from this software without specific prior written\n *     permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n/* Author: Andreas Orthey */\n\n#include <ompl/base/spaces/special/MobiusStateSpace.h>\n#include <ompl/tools/config/MagicConstants.h>\n#include <cstring>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n\nusing namespace boost::math::double_constants;  // pi\nusing namespace ompl::base;\n\nMobiusStateSpace::MobiusStateSpace(double intervalMax, double radius) : radius_(radius)\n{\n    setName(\"Mobius\" + getName());\n    type_ = STATE_SPACE_MOBIUS;\n\n    StateSpacePtr SO2(std::make_shared<SO2StateSpace>());\n    StateSpacePtr R1(std::make_shared<RealVectorStateSpace>(1));\n    R1->as<RealVectorStateSpace>()->setBounds(-intervalMax, +intervalMax);\n\n    addSubspace(SO2, 1.0);\n    addSubspace(R1, 1.0);\n    lock();\n}\n\ndouble MobiusStateSpace::distance(const State *state1, const State *state2) const\n{\n    double theta1 = state1->as<MobiusStateSpace::StateType>()->getU();\n    double theta2 = state2->as<MobiusStateSpace::StateType>()->getU();\n\n    double diff = theta2 - theta1;\n\n    if (std::abs(diff) <= pi)\n    {\n        return CompoundStateSpace::distance(state1, state2);\n    }\n    else\n    {\n        // requires interpolation over the gluing strip\n        const auto *cstate1 = static_cast<const CompoundState *>(state1);\n        const auto *cstate2 = static_cast<const CompoundState *>(state2);\n\n        // distance on S1 as usual\n        double dist = 0.0;\n        dist += weights_[0] * components_[0]->distance(cstate1->components[0], cstate2->components[0]);\n\n        double r1 = state1->as<MobiusStateSpace::StateType>()->getV();\n        double r2 = state2->as<MobiusStateSpace::StateType>()->getV();\n\n        r2 = -r2;\n\n        dist += std::sqrt((r2 - r1) * (r2 - r1));\n        return dist;\n    }\n}\n\nvoid MobiusStateSpace::interpolate(const State *from, const State *to, double t, State *state) const\n{\n    double theta1 = from->as<MobiusStateSpace::StateType>()->getU();\n    double theta2 = to->as<MobiusStateSpace::StateType>()->getU();\n\n    double diff = theta2 - theta1;\n\n    if (std::abs(diff) <= pi)\n    {\n        // interpolate as it would be a cylinder\n        CompoundStateSpace::interpolate(from, to, t, state);\n    }\n    else\n    {\n        // requires interpolation over the gluing strip\n        const auto *cfrom = static_cast<const CompoundState *>(from);\n        const auto *cto = static_cast<const CompoundState *>(to);\n        auto *cstate = static_cast<CompoundState *>(state);\n\n        // interpolate S1 as usual\n        components_[0]->interpolate(cfrom->components[0], cto->components[0], t, cstate->components[0]);\n\n        double r1 = from->as<MobiusStateSpace::StateType>()->getV();\n        double r2 = to->as<MobiusStateSpace::StateType>()->getV();\n\n        // Need to mirror point for interpolation\n        r2 = -r2;\n\n        double r = r1 + (r2 - r1) * t;\n\n        // check again if we need to invert (only if we already crossed gluing\n        // line)\n        double thetaNew = state->as<MobiusStateSpace::StateType>()->getU();\n        double diff2 = theta2 - thetaNew;\n\n        if (std::abs(diff2) <= pi)\n        {\n            r = -r;\n        }\n\n        state->as<MobiusStateSpace::StateType>()->setV(r);\n    }\n}\n\nState *MobiusStateSpace::allocState() const\n{\n    auto *state = new StateType();\n    allocStateComponents(state);\n    return state;\n}\n\nEigen::Vector3f MobiusStateSpace::toVector(const State *state) const\n{\n    Eigen::Vector3f vec;\n\n    const auto *s = state->as<MobiusStateSpace::StateType>();\n    float u = s->getU();\n    float v = s->getV();\n\n    double R = radius_ + v * std::cos(0.5 * u);\n    vec[0] = R * std::cos(u);\n    vec[1] = R * std::sin(u);\n    vec[2] = v * std::sin(0.5 * u);\n    return vec;\n}\n", "meta": {"hexsha": "6ba82cbdb60319016af617da4bf9db2c12df00f4", "size": 5508, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/base/spaces/special/src/MobiusStateSpace.cpp", "max_stars_repo_name": "kopernikusauto/ompl", "max_stars_repo_head_hexsha": "528f02cdc5ac785ba24e1dbdf1cf621a17020b7b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 837.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T12:01:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:42:42.000Z", "max_issues_repo_path": "src/ompl/base/spaces/special/src/MobiusStateSpace.cpp", "max_issues_repo_name": "kopernikusauto/ompl", "max_issues_repo_head_hexsha": "528f02cdc5ac785ba24e1dbdf1cf621a17020b7b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 271.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T22:05:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:16:01.000Z", "max_forks_repo_path": "src/ompl/base/spaces/special/src/MobiusStateSpace.cpp", "max_forks_repo_name": "kopernikusauto/ompl", "max_forks_repo_head_hexsha": "528f02cdc5ac785ba24e1dbdf1cf621a17020b7b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 452.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T08:48:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T06:53:33.000Z", "avg_line_length": 34.8607594937, "max_line_length": 104, "alphanum_fraction": 0.6481481481, "num_tokens": 1382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4285935072603192}}
{"text": "#ifndef TRIAL_ONLINE_QUANTILE_PSQUARE_HPP\n#define TRIAL_ONLINE_QUANTILE_PSQUARE_HPP\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Copyright (C) 2016 Bjorn Reese <breese@users.sourceforge.net>\n//\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// Jain and Chlamtac, \"The [Piecewise-parabolic Prediction]-Square Algorithm\n//   for Dynamic Calculation of Percentiles and Histograms without Storing\n//   Observations\", Communications of the ACM, 28(10), pp. 1076-1086, 1985.\n//\n// Raatikainen, \"Sequential Procedure for Simultaneous Estimation of Several\n//   Percentiles\", Transactions of the Society for Computer Simulations, 7(1),\n//   pp. 21-44, 1990.\n\n#include <cstddef> // std::size_t\n#include <vector>\n#include <array>\n#include <ratio>\n#include <boost/mp11/list.hpp>\n#include <boost/mp11/algorithm.hpp>\n#include <trial/online/detail/type_traits.hpp>\n\nnamespace trial\n{\nnamespace online\n{\nnamespace quantile\n{\n\nusing minimum_ratio = std::ratio<0, 1>;\nusing maximum_ratio = std::ratio<1, 1>;\n\ntemplate <typename T, typename... Quantiles>\nclass psquare\n{\n    static_assert(std::is_floating_point<T>::value, \"T must be a floating-point type\");\n    static_assert((sizeof...(Quantiles) > 0), \"There must be at least one quantile\");\n\n    using QuantileList = boost::mp11::mp_sort<boost::mp11::mp_list<minimum_ratio, Quantiles..., maximum_ratio>, std::ratio_less>;\n    static_assert(boost::mp11::mp_all_of<QuantileList, detail::is_ratio>::value, \"Quantiles must be ratios\");\n\npublic:\n    using value_type = T;\n    using size_type = std::size_t;\n\n    psquare() noexcept;\n    psquare(const psquare&) noexcept = default;\n    psquare(psquare&&) noexcept = default;\n    psquare& operator= (const psquare&) noexcept = default;\n    psquare& operator= (psquare&&) noexcept = default;\n\n    void clear() noexcept;\n    bool empty() const noexcept;\n    size_type size() const noexcept;\n\n    void push(value_type) noexcept;\n\n    // Get value by type.\n    // Select middle quantile parameter by default.\n    template < typename Q = boost::mp11::mp_at_c<QuantileList, 1 + sizeof...(Quantiles) / 2> >\n    value_type value() const noexcept;\n\n    // Get value by index.\n    template <std::size_t Index = 1 + sizeof...(Quantiles) / 2>\n    value_type get() const noexcept;\n\n    struct parameter_type\n    {\n        parameter_type(size_type position,\n                       value_type height) noexcept;\n\n        bool operator== (const parameter_type& other) const noexcept\n        {\n            return ((position == other.position) &&\n                    (height == other.height));\n        }\n\n        size_type position;\n        value_type height;\n    };\n    std::vector<parameter_type> parameters() const;\n    void parameters(const std::vector<parameter_type>&) noexcept;\n\nprivate:\n    void initialize() noexcept;\n    value_type linear(size_type, int) const noexcept;\n    value_type parabolic(size_type, int) const noexcept;\n\nprivate:\n    static constexpr size_type quantile_length = sizeof...(Quantiles);\n    static constexpr size_type parameter_length = 2 * quantile_length + 3;\n    static constexpr value_type quantiles[quantile_length] = { (Quantiles::num / value_type(Quantiles::den))... };\n\n    size_type count {0};\n    std::array<size_type, parameter_length> positions;\n    std::array<value_type, parameter_length> heights;\n    std::array<value_type, parameter_length> desired_positions;\n    std::array<value_type, parameter_length> constant_deltas;\n};\n\n// Convenience types\nusing median_ratio = std::ratio<1, 2>;\nusing lower_quartile_ratio = std::ratio<1, 4>;\nusing upper_quartile_ratio = std::ratio<3, 4>;\n\ntemplate <typename T> using psquare_median = psquare<T, median_ratio>;\ntemplate <typename T> using psquare_quartile = psquare<T, lower_quartile_ratio, median_ratio, upper_quartile_ratio>;\n\n} // namespace quantile\n} // namespace online\n} // namespace trial\n\n#include <trial/online/quantile/detail/psquare.ipp>\n\n#endif // TRIAL_ONLINE_QUANTILE_PSQUARE_HPP\n", "meta": {"hexsha": "d34fdb83102ccc9223016ff07af339b1ba7d980f", "size": 4189, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/trial/online/quantile/psquare.hpp", "max_stars_repo_name": "breese/trial.online", "max_stars_repo_head_hexsha": "d28f8025082682ce10d9eb97c63ed0d4e62c7511", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T15:12:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T08:21:45.000Z", "max_issues_repo_path": "include/trial/online/quantile/psquare.hpp", "max_issues_repo_name": "breese/trial.online", "max_issues_repo_head_hexsha": "d28f8025082682ce10d9eb97c63ed0d4e62c7511", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-20T11:28:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-20T11:28:49.000Z", "max_forks_repo_path": "include/trial/online/quantile/psquare.hpp", "max_forks_repo_name": "breese/trial.online", "max_forks_repo_head_hexsha": "d28f8025082682ce10d9eb97c63ed0d4e62c7511", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-19T16:00:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-29T08:26:44.000Z", "avg_line_length": 34.0569105691, "max_line_length": 129, "alphanum_fraction": 0.6829792313, "num_tokens": 1013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.42859331460512695}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\n *    All rights reserved.\n *\n *    Redistribution and use in source and binary forms, with or without modification, are\n *    permitted provided that the following conditions are met:\n *      - Redistributions of source code must retain the above copyright notice, this list of\n *        conditions and the following disclaimer.\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\n *        conditions and the following disclaimer in the documentation and/or other materials\n *        provided with the distribution.\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\n *        may be used to endorse or promote products derived from this software without specific\n *        prior written permission.\n *\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *    Changelog\n *      YYMMDD    Author            Comment\n *      102511    D. Dirkx          First version of file.\n *      110120    D. Dirkx          Finalized for code check.\n *      110208    K. Kumar          Updated file header; corrected Doxygen comments; minor changes.\n *      110209    D. Dirkx          Minor changes.\n *      110209    K. Kumar          Minor changes.\n *      110905    S. Billemont      Reorganized includes.\n *                                  Moved (con/de)structors and getter/setters to header.\n *      120323    D. Dirkx          Removed set functions; moved functionality to constructor.\n *\n *    References\n *      E.H. Hirschel and C. Weiland, Selected Aerothermodynamic Design Problems of Hypersonic\n *          Flight Vehicles (chapter 5), Springer/AIAA, 2009.\n *      D. Dirkx, Continuous Shape Optimization of Entry Vehicles, MSc thesis, Delft University\n *          of Technology, 2011 (Unpublished).\n *\n *    Notes\n *\n */\n\n#include <cmath>\n#include <iostream>\n\n#include <boost/make_shared.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <Eigen/Core>\n\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/Mathematics/GeometricShapes/capsule.h\"\n#include \"Tudat/Mathematics/GeometricShapes/conicalFrustum.h\"\n#include \"Tudat/Mathematics/GeometricShapes/sphereSegment.h\"\n#include \"Tudat/Mathematics/GeometricShapes/torus.h\"\n\nnamespace tudat\n{\nnamespace geometric_shapes\n{\n\n//! Default constructor.\nCapsule::Capsule( const double noseRadius,\n                  const double middleRadius,\n                  const double rearLength,\n                  const double rearAngle,\n                  const double sideRadius )\n{\n    using std::sin;\n    using std::cos;\n    using mathematical_constants::PI;\n\n    // Call set functions for number of single and composite surface geometries\n    // with predetermined values.\n    setNumberOfCompositeSurfaceGeometries( 0 );\n    setNumberOfSingleSurfaceGeometries( 4 );\n\n    // Set member shape variables\n    noseRadius_ = noseRadius;\n    middleRadius_ = middleRadius;\n    rearLength_ = rearLength;\n    rearAngle_ = rearAngle;\n    sideRadius_ = sideRadius;\n\n    // Determine and set extent of spherical nose part.\n    double noseSphereAngle_ = asin( ( middleRadius_ - sideRadius_ )\n                                    / ( noseRadius_ - sideRadius_ ) );\n\n    // Create nose sphere.\n    boost::shared_ptr< SphereSegment > noseSphere_ = boost::make_shared< SphereSegment >(\n                noseRadius_, 0, 2 * PI, 0, noseSphereAngle_ );\n\n    // Declare translation vector.\n    Eigen::VectorXd translationVector_ = Eigen::VectorXd( 3 );\n    translationVector_( 2 ) = 0.0;\n    translationVector_( 1 ) = 0.0;\n    translationVector_( 0 ) = - noseRadius_ * cos( noseSphereAngle_ );\n\n    // Set nose translation vector.\n    noseSphere_->setOffset( translationVector_ );\n\n    // Set noseSphere_ in singleSurfaceList_.\n    setSingleSurfaceGeometry( noseSphere_, 0 );\n\n    // Create rear cone, fully revolved.\n    boost::shared_ptr< ConicalFrustum > cone_ = boost::make_shared< ConicalFrustum >(\n                rearAngle_, middleRadius_ - sideRadius_ * ( 1.0 - cos( rearAngle_ ) ),\n                rearLength_ );\n\n    // Set translation vector of cone.\n    translationVector_( 0 ) = -sideRadius_ * ( sin( PI / 2.0 - noseSphereAngle_ )\n                                               + sin ( -rearAngle_ ) );\n    cone_->setOffset( translationVector_ );\n\n    // Set cone in singleSurfaceList_.\n    setSingleSurfaceGeometry( cone_, 1 );\n\n    // Calculate end radius of cone.\n    double endRadius_ = cone_->getStartRadius( ) + rearLength_ * tan( rearAngle_ );\n\n    // Calculate rear sphere radius.\n    double rearNoseRadius_ = endRadius_ / cos( -rearAngle_ );\n\n    // Create rear sphere ( \"end cap\" ), fully revolved.\n    boost::shared_ptr< SphereSegment > rearSphere_ = boost::make_shared< SphereSegment >(\n                rearNoseRadius_, 0.0, 2.0 * PI, PI / 2.0 - rearAngle_, PI );\n\n    // Set translation vector of rear sphere.\n    translationVector_( 0 ) =  ( rearNoseRadius_ * sin( -rearAngle_ ) ) - rearLength_\n            - ( sideRadius_ * ( sin( PI / 2.0 - noseSphereAngle_ ) + sin ( -rearAngle_ ) ) );\n    rearSphere_->setOffset( translationVector_ );\n    setSingleSurfaceGeometry( rearSphere_, 2 );\n\n    // Create torus section of capsule.\n    double torusMajorRadius_ = ( noseRadius_ - sideRadius_ ) * sin( noseSphereAngle_ );\n    boost::shared_ptr< Torus > torus_ = boost::make_shared< Torus >(\n       torusMajorRadius_, sideRadius_, 0.0, 2.0 * PI, PI / 2.0 - noseSphereAngle_, rearAngle_ );\n\n    // Set translation vector of rear sphere.\n    translationVector_( 0 ) = -cos( noseSphereAngle_ ) * sideRadius_;\n    torus_->setOffset( translationVector_ );\n    setSingleSurfaceGeometry( torus_, 3 );\n\n    // Set rotation matrix fo each part to be compatible with flow direction in\n    // aerodynamic analysis.\n    Eigen::MatrixXd rotationMatrix = Eigen::MatrixXd( 3, 3 );\n    double angle_ = PI / 2.0;\n    rotationMatrix( 0, 0 ) = cos( angle_ );\n    rotationMatrix( 0, 1 ) = 0.0;\n    rotationMatrix( 0, 2 ) = sin( angle_ );\n    rotationMatrix( 1, 0 ) = 0.0;\n    rotationMatrix( 1, 1 ) = 1.0;\n    rotationMatrix( 1, 2 ) = 0.0;\n    rotationMatrix( 2, 0 ) = -sin( angle_ );\n    rotationMatrix( 2, 1 ) = 0.0;\n    rotationMatrix( 2, 2 ) = cos( angle_ );\n\n    // Set rotation matrix for single surface geometries.\n    for ( unsigned i = 0; i < numberOfSingleSurfaceGeometries_ ; i++ )\n    {\n        singleSurfaceGeometryList_[ i ]->setRotationMatrix( rotationMatrix );\n    }\n}\n\n//! Overload ostream to print class information.\nstd::ostream &operator<<( std::ostream &stream, Capsule& capsule )\n{\n    using std::endl;\n\n    stream << \"This is a capsule.\" << endl;\n    stream << \"The defining parameters are: \"<< endl\n           << \"Nose radius: \" << capsule.getNoseRadius( ) << endl\n           << \"Mid radius: \" << capsule.getMiddleRadius( ) << endl\n           << \"Rear length: \" << capsule.getRearLength( ) << endl\n           << \"Rear angle: \" << capsule.getRearAngle( ) << endl\n           << \"Side radius: \" << capsule.getSideRadius( )<< endl;\n\n    return stream;\n}\n\n} // namespace geometric_shapes\n} // namespace tudat\n", "meta": {"hexsha": "883dc5a1bf6dda1d1b22616aff1b7940e11b2703", "size": 7888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/GeometricShapes/capsule.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Mathematics/GeometricShapes/capsule.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Mathematics/GeometricShapes/capsule.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 42.1818181818, "max_line_length": 99, "alphanum_fraction": 0.6627789047, "num_tokens": 1960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4285933067533126}}
{"text": "/*\n * Copyright Nick Thompson, John Maddock 2020\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_MATH_SPECIAL_DAUBECHIES_SCALING_HPP\n#define BOOST_MATH_SPECIAL_DAUBECHIES_SCALING_HPP\n#include <vector>\n#include <array>\n#include <cmath>\n#include <thread>\n#include <future>\n#include <iostream>\n#include <boost/math/special_functions/detail/daubechies_scaling_integer_grid.hpp>\n#include <boost/math/filters/daubechies.hpp>\n#include <boost/math/interpolators/detail/cubic_hermite_detail.hpp>\n#include <boost/math/interpolators/detail/quintic_hermite_detail.hpp>\n#include <boost/math/interpolators/detail/septic_hermite_detail.hpp>\n\nnamespace boost::math {\n\ntemplate<class Real, int p, int order>\nstd::vector<Real> daubechies_scaling_dyadic_grid(int64_t j_max)\n{\n    using std::isnan;\n    using std::sqrt;\n    auto c = boost::math::filters::daubechies_scaling_filter<Real, p>();\n    Real scale = sqrt(static_cast<Real>(2))*(1 << order);\n    for (auto & x : c)\n    {\n        x *= scale;\n    }\n\n    auto phik = detail::daubechies_scaling_integer_grid<Real, p, order>();\n\n    // Maximum sensible j for 32 bit floats is j_max = 22:\n    if (std::is_same_v<Real, float>)\n    {\n        if (j_max > 23)\n        {\n            throw std::logic_error(\"Requested dyadic grid more dense than number of representables on the interval.\");\n        }\n    }\n    std::vector<Real> v(2*p + (2*p-1)*((1<<j_max) -1), std::numeric_limits<Real>::quiet_NaN());\n    v[0] = 0;\n    v[v.size()-1] = 0;\n    for (int64_t i = 0; i < static_cast<int64_t>(phik.size()); ++i) {\n        v[i*(1uLL<<j_max)] = phik[i];\n    }\n\n    for (int64_t j = 1; j <= j_max; ++j)\n    {\n        int64_t k_max = v.size()/(int64_t(1) << (j_max-j));\n        for (int64_t k = 1; k < k_max;  k += 2)\n        {\n            // Where this value will go:\n            int64_t delivery_idx = k*(1uLL << (j_max-j));\n            // This is a nice check, but we've tested this exhaustively, and it's an expensive check:\n            //if (delivery_idx >= static_cast<int64_t>(v.size())) {\n            //    std::cerr << \"Delivery index out of range!\\n\";\n            //    continue;\n            //}\n            Real term = 0;\n            for (int64_t l = 0; l < static_cast<int64_t>(c.size()); ++l)\n            {\n                int64_t idx = k*(int64_t(1) << (j_max - j + 1)) - l*(int64_t(1) << j_max);\n                if (idx < 0)\n                {\n                    break;\n                }\n                if (idx < static_cast<int64_t>(v.size()))\n                {\n                    term += c[l]*v[idx];\n                }\n            }\n            // Again, another nice check:\n            //if (!isnan(v[delivery_idx])) {\n            //    std::cerr << \"Delivery index already populated!, = \" << v[delivery_idx] << \"\\n\";\n            //    std::cerr << \"would overwrite with \" << term << \"\\n\";\n            //}\n            v[delivery_idx] = term;\n        }\n    }\n    return v;\n}\n\nnamespace detail {\n\ntemplate<class RandomAccessContainer>\nclass matched_holder {\npublic:\n    using Real = typename RandomAccessContainer::value_type;\n\n    matched_holder(RandomAccessContainer && y, RandomAccessContainer && dydx, int grid_refinements, Real x0) : x0_{x0}, y_{std::move(y)}, dy_{std::move(dydx)}\n    {\n        inv_h_ = (1 << grid_refinements);\n        Real h = 1/inv_h_;\n        for (auto & dy : dy_)\n        {\n            dy *= h;\n        }\n    }\n\n    inline Real operator()(Real x) const\n    {\n        using std::floor;\n        using std::sqrt;\n        // This is the exact Holder exponent, but it's pessimistic almost everywhere!\n        // It's only exactly right at dyadic rationals.\n        //Real const alpha = 2 - log(1+sqrt(Real(3)))/log(Real(2));\n        // We're gonna use alpha = 1/2, rather than 0.5500...\n        Real s = (x-x0_)*inv_h_;\n        Real ii = floor(s);\n        auto i = static_cast<decltype(y_.size())>(ii);\n        Real t = s - ii;\n        Real dphi = dy_[i+1];\n        Real diff = y_[i+1] - y_[i];\n        return y_[i] + (2*dphi - diff)*t + 2*sqrt(t)*(diff-dphi);\n    }\n\n    int64_t bytes() const\n    {\n        return 2*y_.size()*sizeof(Real) + sizeof(this);\n    }\n\nprivate:\n    Real x0_;\n    Real inv_h_;\n    RandomAccessContainer y_;\n    RandomAccessContainer dy_;\n};\n\ntemplate<class RandomAccessContainer>\nclass matched_holder_aos {\npublic:\n    using Point = typename RandomAccessContainer::value_type;\n    using Real = typename Point::value_type;\n\n    matched_holder_aos(RandomAccessContainer && data, int grid_refinements, Real x0) : x0_{x0}, data_{std::move(data)}\n    {\n        inv_h_ = Real(1uLL << grid_refinements);\n        Real h = 1/inv_h_;\n        for (auto & datum : data_)\n        {\n            datum[1] *= h;\n        }\n    }\n\n    inline Real operator()(Real x) const\n    {\n        using std::floor;\n        using std::sqrt;\n        Real s = (x-x0_)*inv_h_;\n        Real ii = floor(s);\n        auto i = static_cast<decltype(data_.size())>(ii);\n        Real t = s - ii;\n        Real y0 = data_[i][0];\n        Real y1 = data_[i+1][0];\n        Real dphi = data_[i+1][1];\n        Real diff = y1 - y0;\n        return y0 + (2*dphi - diff)*t + 2*sqrt(t)*(diff-dphi);\n    }\n\n    int64_t bytes() const\n    {\n        return data_.size()*data_[0].size()*sizeof(Real) + sizeof(this);\n    }\n\nprivate:\n    Real x0_;\n    Real inv_h_;\n    RandomAccessContainer data_;\n};\n\n\ntemplate<class RandomAccessContainer>\nclass linear_interpolation {\npublic:\n    using Real = typename RandomAccessContainer::value_type;\n\n    linear_interpolation(RandomAccessContainer && y, RandomAccessContainer && dydx, int grid_refinements) : y_{std::move(y)}, dydx_{std::move(dydx)}\n    {\n        s_ = (1 << grid_refinements);\n    }\n\n    inline Real operator()(Real x) const\n    {\n        using std::floor;\n        Real y = x*s_;\n        Real k = floor(y);\n\n        int64_t kk = static_cast<int64_t>(k);\n        Real t = y - k;\n        return (1-t)*y_[kk] + t*y_[kk+1];\n    }\n\n    inline Real prime(Real x) const\n    {\n        using std::floor;\n        Real y = x*s_;\n        Real k = floor(y);\n\n        int64_t kk = static_cast<int64_t>(k);\n        Real t = y - k;\n        return (1-t)*dydx_[kk] + t*dydx_[kk+1];\n    }\n\n    int64_t bytes() const\n    {\n        return (1 + y_.size() + dydx_.size())*sizeof(Real) + sizeof(y_) + sizeof(dydx_);\n    }\n\nprivate:\n    Real s_;\n    RandomAccessContainer y_;\n    RandomAccessContainer dydx_;\n};\n\ntemplate<class RandomAccessContainer>\nclass linear_interpolation_aos {\npublic:\n    using Point = typename RandomAccessContainer::value_type;\n    using Real = typename Point::value_type;\n\n    linear_interpolation_aos(RandomAccessContainer && data, int grid_refinements, Real x0) : x0_{x0}, data_{std::move(data)}\n    {\n        s_ = Real(1uLL << grid_refinements);\n    }\n\n    inline Real operator()(Real x) const\n    {\n        using std::floor;\n        Real y = (x-x0_)*s_;\n        Real k = floor(y);\n\n        int64_t kk = static_cast<int64_t>(k);\n        Real t = y - k;\n        return (t != 0) ? (1-t)*data_[kk][0] + t*data_[kk+1][0] : data_[kk][0];\n    }\n\n    inline Real prime(Real x) const\n    {\n        using std::floor;\n        Real y = (x-x0_)*s_;\n        Real k = floor(y);\n\n        int64_t kk = static_cast<int64_t>(k);\n        Real t = y - k;\n        return t != 0 ? (1-t)*data_[kk][1] + t*data_[kk+1][1] : data_[kk][1];\n    }\n\n    int64_t bytes() const\n    {\n        return sizeof(this) + data_.size()*data_[0].size()*sizeof(Real);\n    }\n\nprivate:\n    Real x0_;\n    Real s_;\n    RandomAccessContainer data_;\n};\n\n\ntemplate <class T>\nstruct daubechies_eval_type\n{\n   typedef T type;\n\n   static const std::vector<T>& vector_cast(const std::vector<T>& v) { return v; }\n\n};\ntemplate <>\nstruct daubechies_eval_type<float>\n{\n   typedef double type;\n\n   inline static std::vector<float> vector_cast(const std::vector<double>& v)\n   {\n      std::vector<float> result(v.size());\n      for (unsigned i = 0; i < v.size(); ++i)\n         result[i] = static_cast<float>(v[i]);\n      return result;\n   }\n};\ntemplate <>\nstruct daubechies_eval_type<double>\n{\n   typedef long double type;\n\n   inline static std::vector<double> vector_cast(const std::vector<long double>& v)\n   {\n      std::vector<double> result(v.size());\n      for (unsigned i = 0; i < v.size(); ++i)\n         result[i] = static_cast<double>(v[i]);\n      return result;\n   }\n};\n\nstruct null_interpolator\n{\n   template <class T>\n   T operator()(const T&)\n   {\n      return 1;\n   }\n};\n\n} // namespace detail\n\ntemplate<class Real, int p>\nclass daubechies_scaling {\n   //\n   // Some type manipulation so we know the type of the interpolator, and the vector type it requires:\n   //\n   typedef std::vector<std::array<Real, p < 6 ? 2 : p < 10 ? 3 : 4>> vector_type;\n   //\n   // List our interpolators:\n   //\n   typedef std::tuple<\n      detail::null_interpolator, detail::matched_holder_aos<vector_type>, detail::linear_interpolation_aos<vector_type>, \n      interpolators::detail::cardinal_cubic_hermite_detail_aos<vector_type>, interpolators::detail::cardinal_quintic_hermite_detail_aos<vector_type>,\n      interpolators::detail::cardinal_septic_hermite_detail_aos<vector_type> > interpolator_list;\n   //\n   // Select the one we need:\n   //\n   typedef std::tuple_element_t<\n      p == 1 ? 0 :\n      p == 2 ? 1 :\n      p == 3 ? 2 :\n      p <= 5 ? 3 :\n      p <= 9 ? 4 : 5, interpolator_list> interpolator_type;\n\npublic:\n   daubechies_scaling(int grid_refinements = -1)\n   {\n      static_assert(p < 20, \"Daubechies scaling functions are only implemented for p < 20.\");\n      static_assert(p > 0, \"Daubechies scaling functions must have at least 1 vanishing moment.\");\n      if constexpr (p == 1)\n      {\n         return;\n      }\n      else {\n         if (grid_refinements < 0)\n         {\n            if (std::is_same_v<Real, float>)\n            {\n               if (grid_refinements == -2)\n               {\n                  // Control absolute error:\n                  //                          p= 2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19\n                  std::array<int, 20> r{ -1, -1, 18, 19, 16, 11,  8,  7,  7,  7,  5,  5,  4,  4,  4,  4,  3,  3,  3,  3 };\n                  grid_refinements = r[p];\n               }\n               else\n               {\n                  // Control relative error:\n                  //                          p= 2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19\n                  std::array<int, 20> r{ -1, -1, 21, 21, 21, 17, 16, 15, 14, 13, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11 };\n                  grid_refinements = r[p];\n               }\n            }\n            else if (std::is_same_v<Real, double>)\n            {\n               //                          p= 2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19\n               std::array<int, 20> r{ -1, -1, 21, 21, 21, 21, 21, 21, 21, 21, 20, 20, 19, 19, 18, 18, 18, 18, 18, 18 };\n               grid_refinements = r[p];\n            }\n            else\n            {\n               grid_refinements = 21;\n            }\n         }\n\n         // Compute the refined grid:\n         // In fact for float precision I know the grid must be computed in double precision and then cast back down, or else parts of the support are systematically inaccurate.\n         std::future<std::vector<Real>> t0 = std::async(std::launch::async, [&grid_refinements]() {\n            // Computing in higher precision and downcasting is essential for 1ULP evaluation in float precision:\n            auto v = daubechies_scaling_dyadic_grid<typename detail::daubechies_eval_type<Real>::type, p, 0>(grid_refinements);\n            return detail::daubechies_eval_type<Real>::vector_cast(v);\n            });\n         // Compute the derivative of the refined grid:\n         std::future<std::vector<Real>> t1 = std::async(std::launch::async, [&grid_refinements]() {\n            auto v = daubechies_scaling_dyadic_grid<typename detail::daubechies_eval_type<Real>::type, p, 1>(grid_refinements);\n            return detail::daubechies_eval_type<Real>::vector_cast(v);\n            });\n\n         // if necessary, compute the second and third derivative:\n         std::vector<Real> d2ydx2;\n         std::vector<Real> d3ydx3;\n         if constexpr (p >= 6) {\n            std::future<std::vector<Real>> t3 = std::async(std::launch::async, [&grid_refinements]() {\n               auto v = daubechies_scaling_dyadic_grid<typename detail::daubechies_eval_type<Real>::type, p, 2>(grid_refinements);\n               return detail::daubechies_eval_type<Real>::vector_cast(v);\n               });\n\n            if constexpr (p >= 10) {\n               std::future<std::vector<Real>> t4 = std::async(std::launch::async, [&grid_refinements]() {\n                  auto v = daubechies_scaling_dyadic_grid<typename detail::daubechies_eval_type<Real>::type, p, 3>(grid_refinements);\n                  return detail::daubechies_eval_type<Real>::vector_cast(v);\n                  });\n               d3ydx3 = t4.get();\n            }\n            d2ydx2 = t3.get();\n         }\n\n\n         auto y = t0.get();\n         auto dydx = t1.get();\n\n         if constexpr (p >= 2)\n         {\n            vector_type data(y.size());\n            for (size_t i = 0; i < y.size(); ++i)\n            {\n               data[i][0] = y[i];\n               data[i][1] = dydx[i];\n               if constexpr (p >= 6)\n                  data[i][2] = d2ydx2[i];\n               if constexpr (p >= 10)\n                  data[i][3] = d3ydx3[i];\n            }\n            if constexpr (p <= 3)\n               m_interpolator = std::make_shared<interpolator_type>(std::move(data), grid_refinements, Real(0));\n            else\n               m_interpolator = std::make_shared<interpolator_type>(std::move(data), Real(0), Real(1) / (1 << grid_refinements));\n         }\n         else\n            m_interpolator = std::make_shared<detail::null_interpolator>();\n      }\n   }\n\n    inline Real operator()(Real x) const\n    {\n        if (x <= 0 || x >= 2*p-1)\n        {\n            return 0;\n        }\n        return (*m_interpolator)(x);\n    }\n\n    inline Real prime(Real x) const\n    {\n        static_assert(p > 2, \"The 3-vanishing moment Daubechies scaling function is the first which is continuously differentiable.\");\n        if (x <= 0 || x >= 2*p-1)\n        {\n            return 0;\n        }\n        return m_interpolator->prime(x);\n    }\n\n    inline Real double_prime(Real x) const\n    {\n        static_assert(p >= 6, \"Second derivatives require at least 6 vanishing moments.\");\n        if (x <= 0 || x >= 2*p - 1)\n        {\n            return Real(0);\n        }\n        return m_interpolator->double_prime(x);\n    }\n\n    std::pair<Real, Real> support() const\n    {\n        return {Real(0), Real(2*p-1)};\n    }\n\n    int64_t bytes() const\n    {\n       return m_interpolator->bytes() + sizeof(m_interpolator);\n    }\n\nprivate:\n   std::shared_ptr<interpolator_type> m_interpolator;\n};\n\n}\n#endif\n", "meta": {"hexsha": "9c10bc72cb649ab6aff34b6d66e90a32d4d5dcb5", "size": 15045, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/special_functions/daubechies_scaling.hpp", "max_stars_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_stars_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/special_functions/daubechies_scaling.hpp", "max_issues_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_issues_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/special_functions/daubechies_scaling.hpp", "max_forks_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_forks_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4091858038, "max_line_length": 177, "alphanum_fraction": 0.5549351944, "num_tokens": 4263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597974, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.428536359053805}}
{"text": "/* ----------------------------------------------------------------------------\r\n * Copyright 2018, Ross Hartley <m.ross.hartley@gmail.com>\r\n * All Rights Reserved\r\n * See LICENSE for the license information\r\n * -------------------------------------------------------------------------- */\r\n\r\n/**\r\n *  @file   landmarks.cpp\r\n *  @author Ross Hartley\r\n *  @brief  Example of invariant filtering for landmark-aided inertial navigation\r\n *  @date   September 25, 2018\r\n **/\r\n\r\n#include <iostream>\r\n#include <fstream>\r\n#include <string>\r\n#include <cstdlib>\r\n#include <Eigen/Dense>\r\n#include <boost/algorithm/string.hpp>\r\n#include \"inekf/inekf.hpp\"\r\n\r\n#define DT_MIN 1e-6\r\n#define DT_MAX 1\r\n\r\ndouble stod98(const std::string &s) {\r\n    return atof(s.c_str());\r\n}\r\n\r\nint stoi98(const std::string &s) {\r\n    return atoi(s.c_str());\r\n}\r\n\r\nusing namespace std;\r\nusing namespace inekf;\r\n\r\nint main() {\r\n    //  ---- Initialize invariant extended Kalman filter ----- //\r\n    RobotState initial_state; \r\n\r\n    // Initialize state mean\r\n    Eigen::Matrix3d R0;\r\n    Eigen::Vector3d v0, p0, bg0, ba0;\r\n    R0 << 1, 0, 0, // initial orientation\r\n          0, -1, 0, // IMU frame is rotated 90deg about the x-axis\r\n          0, 0, -1;\r\n    v0 << 0,0,0; // initial velocity\r\n    p0 << 0,0,0; // initial position\r\n    bg0 << 0,0,0; // initial gyroscope bias\r\n    ba0 << 0,0,0; // initial accelerometer bias\r\n    initial_state.setRotation(R0);\r\n    initial_state.setVelocity(v0);\r\n    initial_state.setPosition(p0);\r\n    initial_state.setGyroscopeBias(bg0);\r\n    initial_state.setAccelerometerBias(ba0);\r\n\r\n    // Initialize state covariance\r\n    NoiseParams noise_params;\r\n    noise_params.setGyroscopeNoise(0.01);\r\n    noise_params.setAccelerometerNoise(0.1);\r\n    noise_params.setGyroscopeBiasNoise(0.00001);\r\n    noise_params.setAccelerometerBiasNoise(0.0001);\r\n\r\n    // Initialize filter\r\n    InEKF filter(initial_state, noise_params);\r\n    cout << \"Noise parameters are initialized to: \\n\";\r\n    cout << filter.getNoiseParams() << endl;\r\n    cout << \"Robot's state is initialized to: \\n\";\r\n    cout << filter.getState() << endl;\r\n\r\n    // --- Optionally initialize prior landmarks --- //\r\n    mapIntVector3d prior_landmarks;\r\n    Eigen::Vector3d p_wl;\r\n    int id;\r\n\r\n    // // Landmark 1\r\n    // id = 1;\r\n    // p_wl << 0,-1,0;\r\n    // prior_landmarks.insert(pair<int,Eigen::Vector3d> (id, p_wl)); \r\n\r\n    // Landmark 2\r\n    // id = 2;\r\n    // p_wl << 1,1,-0.5;\r\n    // prior_landmarks.insert(pair<int,Eigen::Vector3d> (id, p_wl)); \r\n\r\n    // // Landmark 3\r\n    // id = 3;\r\n    // p_wl << 2,-1,0.5;\r\n    // prior_landmarks.insert(pair<int,Eigen::Vector3d> (id, p_wl)); \r\n\r\n    // Store landmarks for localization\r\n    filter.setPriorLandmarks(prior_landmarks); \r\n\r\n    // Open data file\r\n    ifstream infile(\"../data/imu_landmark_measurements.txt\");\r\n    string line;\r\n    Eigen::Matrix<double,6,1> imu_measurement = Eigen::Matrix<double,6,1>::Zero();\r\n    Eigen::Matrix<double,6,1> imu_measurement_prev = Eigen::Matrix<double,6,1>::Zero();\r\n    double t = 0;\r\n    double t_prev = 0;\r\n\r\n    // Loop through data file and read in measurements line by line\r\n    while (getline(infile, line)){\r\n        vector<string> measurement;\r\n        boost::split(measurement,line,boost::is_any_of(\" \"));\r\n        // Handle measurements\r\n        if (measurement[0].compare(\"IMU\")==0){\r\n            cout << \"Received IMU Data, propagating state\\n\";\r\n            assert((measurement.size()-2) == 6);\r\n            t = stod98(measurement[1]); \r\n            imu_measurement << stoi98(measurement[2]), \r\n                               stoi98(measurement[3]), \r\n                               stoi98(measurement[4]),\r\n                               stoi98(measurement[5]),\r\n                               stoi98(measurement[6]),\r\n                               stoi98(measurement[7]);\r\n\r\n            // Propagate using IMU data\r\n            double dt = t - t_prev;\r\n            if (dt > DT_MIN && dt < DT_MAX) {\r\n                filter.Propagate(imu_measurement_prev, dt);\r\n            }\r\n        }\r\n        else if (measurement[0].compare(\"LANDMARK\")==0){\r\n            cout << \"Received LANDMARK observation, correcting state\\n\";\r\n            assert((measurement.size()-2)%4 == 0);\r\n            t = stod98(measurement[1]); \r\n            vectorLandmarks measured_landmarks;\r\n            for (int i=2; i<measurement.size(); i+=4) {\r\n                int id = stoi98(measurement[i]);\r\n                Eigen::Vector3d p_bl;\r\n                p_bl << stoi98(measurement[i+1]), \r\n                        stoi98(measurement[i+2]), \r\n                        stoi98(measurement[i+3]);\r\n                Eigen::Matrix3d cov = 0.01*Eigen::Matrix3d::Identity();\r\n                Landmark landmark(id, p_bl, cov);\r\n                measured_landmarks.push_back(landmark); \r\n            }\r\n\r\n            // Correct state using landmark measurements\r\n            filter.CorrectLandmarks(measured_landmarks);\r\n        }\r\n\r\n        // Store previous timestamp\r\n        t_prev = t;\r\n        imu_measurement_prev = imu_measurement;\r\n    }\r\n\r\n    // Print final state\r\n    cout << filter.getState() << endl;\r\n\r\n    return 0;\r\n}\r\n", "meta": {"hexsha": "b6031a9bde2491b45fff0999ee0de5728dfb1235", "size": 5173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/landmarks.cpp", "max_stars_repo_name": "mayataka/invariant-ekf", "max_stars_repo_head_hexsha": "775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T12:38:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T12:38:09.000Z", "max_issues_repo_path": "examples/landmarks.cpp", "max_issues_repo_name": "mayataka/inekf", "max_issues_repo_head_hexsha": "775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/landmarks.cpp", "max_forks_repo_name": "mayataka/inekf", "max_forks_repo_head_hexsha": "775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8104575163, "max_line_length": 88, "alphanum_fraction": 0.5563502803, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4285363590538048}}
{"text": "/*\n * Copyright 2020-2021 Telecom Paris\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n */\n\n#include \"transport_channel.h\"\n\n#include <cmath>\n\n#include <algorithm>\n#include <boost/log/core.hpp>\n#include <boost/log/expressions.hpp>\n#include <boost/log/trivial.hpp>\n#include <boost/log/utility/setup/common_attributes.hpp>\n#include <boost/log/utility/setup/file.hpp>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <thread>\n#include <vector>\n\n#include \"../../asn1c/nr_rrc/BCCH-DL-SCH-Message.h\"\n#include \"../../utils/common_utils/common_utils.h\"\n#include \"../../utils/sequence_generator/sequence_generator.h\"\n#include \"../../variables/common_matrices/common_matrices.h\"\n#include \"../../variables/common_variables/common_variables.h\"\n#include \"../../variables/ldpc_matrices/ldpc_matrices.h\"\n#include \"../libphy/libphy.h\"\n\nusing namespace std;\n\nauto free5GRAN::phy::transport_channel::compute_N_polar_code(int E,\n                                                             int K,\n                                                             int nmax) -> int {\n  /**\n   * \\fn compute_N_polar_code\n   * \\brief Compute polar coding out sequence size\n   * \\standard TS 38.212 V15.2.0 Section 5.3.1\n   *\n   * \\param[in] E: Rate matching output sequence length\n   * \\param[in] K: Polar coding input sequence length (including CRC)\n   * \\param[in] nmax: Maximum value of n\n   *\n   * \\return Polar coding out sequence size\n   */\n  int n1, n2;\n  float rmin = 1.0 / 8.0;\n  if (E <= (9.0 / 8.0) * pow(2, ceil(log2(E)) - 1) &&\n      (float)K / (float)E < 9.0 / 16.0) {\n    n1 = ceil(log2(E)) - 1;\n  } else {\n    n1 = ceil(log2(E));\n  }\n  n2 = ceil(log2((float)K / rmin));\n  if (nmax < 5 && n1 < 5 && n2 < 5) {\n    return 5;\n  } else {\n    if (n1 < n2 && n1 < nmax) {\n      return n1;\n    } else if (n2 < n1 && n2 < nmax) {\n      return n2;\n    } else {\n      return nmax;\n    }\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::rate_recover(int* input_bits,\n                                                     int* output_bits,\n                                                     int i_bil,\n                                                     int E,\n                                                     int N,\n                                                     int K) {\n  /**\n   * \\fn rate_recover\n   * \\brief Rate recovering for polar coding.\n   * \\standard TS 38.212 V15.2.0 Section 5.4.1\n   *\n   * \\partial_imp Code block de-interleaving not implemented\n   * \\param[in] input_bits: Input bits sequence\n   * \\param[out] output_bits: Output bits sequence\n   * \\param[in] i_bil: Coded blocks interleaving indicator (0: No interleaving,\n   * 1: Interleaving) \\param[in] E: Rate matching output sequence length\n   * \\param[in] N: Rate matching input sequence length\n   */\n  int e[E], y[N];\n  /*\n   * Coded bit-interleaving/de-interleaving TS38.212 5.4.1.3\n   * No coded-bits interleaving\n   */\n  if (i_bil == 0) {\n    for (int n = 0; n < E; n++) {\n      e[n] = input_bits[n];\n    }\n  }\n  /*\n   * Bit de-selection TS38.212 5.4.1.2\n   */\n  if (E >= N) {\n    for (int n = 0; n < N; n++) {\n      y[n] = e[n];\n    }\n  } else {\n    if ((float)K / (float)E <= 7.0 / 16.0) {\n      for (int n = 0; n < N - E; n++) {\n        y[n] = 0;\n      }\n      for (int n = 0; n < E; n++) {\n        y[n + N - E] = e[n];\n      }\n    }\n  }\n\n  /*\n   * Sub-block de-interleaving TS38.212 5.4.1.1\n   */\n  for (int n = 0; n < N; n++) {\n    int i = floor(32 * (double)n / (double)N);\n    int j_n =\n        free5GRAN::SUB_BLOCK_INTERLEAVER_PATTERN[i] * N / 32 + n % (N / 32);\n    output_bits[j_n] = y[n];\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::polar_decode(int* input_bits,\n                                                     int* output_bits,\n                                                     int N,\n                                                     int K,\n                                                     int nmax,\n                                                     int i_il,\n                                                     int n_pc,\n                                                     int n_wm_pc,\n                                                     int E) {\n  /**\n   * \\fn polar_decode\n   * \\brief Polar decoding\n   * \\standard TS 38.212 V15.2.0 Section 5.3.1\n   *\n   * \\partial_imp Only n_wm_pc=0 is implemented\n   * \\details\n   * Details:\n   * - Polar decoding using Gn inverse matrix\n   * - Computing required sets\n   * - Recover c'\n   * - De-interleave c' to recover output\n   *\n   * \\param[in] input_bits: Input bits sequence\n   * \\param[out] output_bits: Output bits sequence\n   * \\param[in] N: Rate matching input sequence length\n   * \\param[in] K: Polar coding input sequence length (including CRC)\n   * \\param[in] nmax: Maximum value of n\n   * \\param[in] i_il: Interleaving indicator (0: No interleaving, 1:\n   * Interleaving) \\param[in] n_pc: Number of parity check bits \\param[in]\n   * n_wm_pc: Number of other parity check bits\n   */\n  int q_0_n_1[N], count_seq, q_i_n[K + n_pc], c_p[K], pi_seq[K], j_n, u[N];\n  int K_max = 164;\n  bool found;\n\n  /*\n   * polar decoding using Gn inverse matrix (TS38.212 5.3.1.2)\n   */\n  switch (N) {\n    case 32: {\n      for (int n = 0; n < N; n++) {\n        u[n] = 0;\n        for (int p = 0; p < N; p++) {\n          u[n] ^= (input_bits[p] * free5GRAN::G5_INV[p][n]);\n        }\n      }\n    };\n    case 64: {\n      for (int n = 0; n < N; n++) {\n        u[n] = 0;\n        for (int p = 0; p < N; p++) {\n          u[n] ^= (input_bits[p] * free5GRAN::G6_INV[p][n]);\n        }\n      }\n    };\n    case 128: {\n      for (int n = 0; n < N; n++) {\n        u[n] = 0;\n        for (int p = 0; p < N; p++) {\n          u[n] ^= (input_bits[p] * free5GRAN::G7_INV[p][n]);\n        }\n      }\n    };\n    case 256: {\n      for (int n = 0; n < N; n++) {\n        u[n] = 0;\n        for (int p = 0; p < N; p++) {\n          u[n] ^= (input_bits[p] * free5GRAN::G8_INV[p][n]);\n        }\n      }\n    };\n    case 512: {\n      for (int n = 0; n < N; n++) {\n        u[n] = 0;\n        for (int p = 0; p < N; p++) {\n          u[n] ^= (input_bits[p] * free5GRAN::G9_INV[p][n]);\n        }\n      }\n    };\n    case 1024: {\n      for (int n = 0; n < N; n++) {\n        u[n] = 0;\n        for (int p = 0; p < N; p++) {\n          u[n] ^= (input_bits[p] * free5GRAN::G10_INV[p][n]);\n        }\n      }\n    };\n  }\n\n  count_seq = 0;\n  vector<int> q_ftmp_n, q_itmp_n;\n\n  /*\n   * Computing q_0_n_1 (TS38.212 5.3.1.2)\n   */\n  for (int n : free5GRAN::POLAR_SEQUENCE_QNMAX_AND_RELIABILITY) {\n    if (n < N) {\n      q_0_n_1[count_seq] = n;\n      count_seq++;\n    }\n  }\n\n  if (E < N) {\n    if ((float)K / (float)E <= 7.0 / 16.0) {\n      for (int n = 0; n < N - E; n++) {\n        int i = floor(32 * (double)n / (double)N);\n        j_n =\n            free5GRAN::SUB_BLOCK_INTERLEAVER_PATTERN[i] * N / 32 + n % (N / 32);\n        q_ftmp_n.push_back(j_n);\n      }\n      if (E >= 3.0 * (float)N / 4.0) {\n        for (int n = 0; n < ceil(3.0 * (float)N / 4.0 - (float)E / 2.0); n++) {\n          q_ftmp_n.push_back(n);\n        }\n      } else {\n        for (int n = 0; n < ceil(9.0 * (float)N / 16.0 - (float)E / 4.0); n++) {\n          q_ftmp_n.push_back(n);\n        }\n      }\n    }\n  }\n\n  for (int n = 0; n < N; n++) {\n    found = false;\n    for (int x : q_ftmp_n) {\n      if (q_0_n_1[n] == x) {\n        found = true;\n        break;\n      }\n    }\n    if (!found) {\n      q_itmp_n.push_back(q_0_n_1[n]);\n    }\n  }\n  /*\n   * Computing q_i_n (TS38.212 5.3.1.2)\n   */\n  for (int n = 0; n < K + n_pc; n++) {\n    q_i_n[n] = q_itmp_n[q_itmp_n.size() - (K + n_pc) + n];\n  }\n  count_seq = 0;\n  /*\n   * Recovering c' from u_n (TS38.212 5.3.1.2)\n   */\n  for (int n = 0; n < N; n++) {\n    found = false;\n    for (int p = 0; p < K + n_pc; p++) {\n      if (q_i_n[p] == n) {\n        found = true;\n        break;\n      }\n    }\n    if (found) {\n      c_p[count_seq] = u[n];\n      count_seq++;\n    }\n  }\n  count_seq = 0;\n  /*\n   * generating pi sequence (TS38.212 5.3.1.1)\n   */\n  for (int m = 0; m < K_max; m++) {\n    if (free5GRAN::INTERLEAVING_PATTERN[m] >= K_max - K) {\n      pi_seq[count_seq] = free5GRAN::INTERLEAVING_PATTERN[m] - (K_max - K);\n      count_seq++;\n    }\n  }\n  /*\n   * de-interleaving c' to recover output sequence (TS38.212 5.3.1.1)\n   */\n  for (int k = 0; k < K; k++) {\n    output_bits[pi_seq[k]] = c_p[k];\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::crc_validate(int* input_bits,\n                                                     int* crc_polynom,\n                                                     int* remainder,\n                                                     int length_input,\n                                                     int length_crc) {\n  /**\n   * \\fn crc_validate\n   * \\brief CRC validation\n   * \\details\n   * Computes the remainder of the division of the input sequence by the\n   * polynom. If the remainder is equal to 0, CRC is validated\n   *\n   * \\param[in] input_bits: Input bits sequence\n   * \\param[in] crc_polynom: Polynom used for CRC computation\n   * \\param[out] remainder: Output remainder of the division\n   * \\param[in] length_input: Input size\n   * \\param[in] length_crc: Polynom size\n   */\n  int num_steps, seq1[length_crc];\n\n  /*\n   * Getting index of first 1 in input_bits\n   */\n  int index_0 = -1;\n  for (int i = 0; i < length_input; i++) {\n    if (input_bits[i] == 1) {\n      index_0 = i;\n      break;\n    }\n  }\n  /*\n   * Creating a new input called temp_input by removing all 0 from the beginning\n   * of input_bits\n   */\n  int temp_input[length_input - index_0];\n  for (int i = 0; i < length_input - index_0; i++) {\n    temp_input[i] = input_bits[index_0 + i];\n  }\n  length_input = length_input - index_0;\n  num_steps = length_input - length_crc + 1;\n\n  /*\n   * seq1 is the variable that will be XORed with crc_polynom step after step\n   * Initializing seq1 variable to the first bits of temp_input\n   */\n  for (int i = 0; i < length_crc; i++) {\n    seq1[i] = temp_input[i];\n  }\n\n  int i = 0;\n\n  /*\n   * Iterate until the polynom reaches the end of temp_input\n   */\n  while (i < num_steps) {\n    /*\n     * XORing seq1 and crc_polynom\n     */\n    for (int j = 0; j < length_crc; j++) {\n      remainder[j] = seq1[j] ^ crc_polynom[j];\n    }\n    /*\n     * Checing if the remainder is equal to 0. If true, algorithm ends\n     */\n    bool validated = true;\n    for (int j = 1; j < length_crc; j++) {\n      if (remainder[j] == 1) {\n        validated = false;\n        break;\n      }\n    }\n    if (validated) {\n      break;\n    }\n    /*\n     * Searching first 1 index in remainder\n     */\n    int index_1 = -1;\n    for (int j = 1; j < length_crc; j++) {\n      if (remainder[j] == 1) {\n        index_1 = j;\n        break;\n      }\n    }\n    /*\n     * seq1 is updated to be the remainder shifted until finding the first 1\n     */\n    for (int j = 0; j < length_crc - index_1; j++) {\n      seq1[j] = remainder[j + index_1];\n    }\n    /*\n     * Adding new entries from temp_input to fill seq1\n     */\n    for (int j = 0; j < index_1; j++) {\n      seq1[length_crc - index_1 + j] = temp_input[length_crc + i + j];\n    }\n    i += index_1;\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::compute_crc(int* input_bits,\n                                                    int* crc_polynom,\n                                                    int* remainder,\n                                                    int length_input,\n                                                    int length_crc) {\n  /**\n   * \\fn compute_crc\n   * \\brief CRC computation\n   * \\details\n   * Compute the CRC for a given input and polynom\n   *\n   * \\param[in] input_bits: Input bits sequence\n   * \\param[in] crc_polynom: Polynom used for CRC computation\n   * \\param[out] remainder: Output CRC\n   * \\param[in] length_input: Input size\n   * \\param[in] length_crc: Polynom size\n   */\n  int num_steps, *seq1;\n\n  /*\n   * Getting index of first 1 in input_bits\n   */\n  int index_0 = -1;\n  for (int i = 0; i < length_input; i++) {\n    if (input_bits[i] == 1) {\n      index_0 = i;\n      break;\n    }\n  }\n  /*\n   * Creating a new input called temp_input by removing all 0 from the beginning\n   * of input_bits Adding (length_crc - 1) zeros to complete temp_input\n   */\n  int temp_input[length_input - index_0 + length_crc - 1];\n  for (int i = 0; i < length_input - index_0; i++) {\n    temp_input[i] = input_bits[index_0 + i];\n  }\n  for (int i = 0; i < length_crc - 1; i++) {\n    temp_input[length_input - index_0 + i] = 0;\n  }\n  length_input = length_input - index_0;\n  num_steps = length_input;\n\n  /*\n   * Iterate until the polynom reaches the end of temp_input\n   */\n  int i = 0;\n  while (i < num_steps) {\n    /*\n     * XORing temp_input and crc_polynom\n     */\n    for (int j = 0; j < length_crc; j++) {\n      temp_input[i + j] ^= crc_polynom[j];\n    }\n    /*\n     * Checing if temp_input (for the first length_input bits) is equal to 0. If\n     * true, algorithm ends\n     */\n    bool finished = true;\n    for (int j = 0; j < length_input; j++) {\n      if (temp_input[j] == 1) {\n        finished = false;\n        break;\n      }\n    }\n    if (finished) {\n      break;\n    }\n    /*\n     * Shifting until finding a 1 (at least once)\n     */\n    i++;\n    while (temp_input[i] != 1) {\n      i++;\n    }\n  }\n  /*\n   * Remainder corresponds to the (length_crc - 1) last bits of temp_input\n   */\n  for (int j = 0; j < length_crc - 1; j++) {\n    remainder[j] = temp_input[length_input + j];\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::compute_ldpc_base_graph(int A,\n                                                                float R,\n                                                                int& graph) {\n  /**\n   * \\fn compute_ldpc_base_graph\n   * \\brief Choose LDPC base graph\n   * \\standard TS 38.212 V15.2.0 Section 7.2.2\n   *\n   * \\param[in] A: Transport block size\n   * \\param[in] R: Code rate\n   * \\param[out] graph: Output graph\n   */\n  if (A <= 292 || (A <= 3824 && R <= 0.67) || R <= 0.25) {\n    graph = 2;\n  } else {\n    graph = 1;\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::compute_transport_block_size(\n    int n_re,\n    float R,\n    int mod_order,\n    int num_layers,\n    int nrb,\n    int& tbs) {\n  /**\n   * \\fn compute_transport_block_size\n   * \\brief Transport block size computation\n   * \\standard TS 38.214 V15.2.0 Section 5.1.3.2\n   *\n   * \\partial_imp n_info > 3824 not implemented\n   *\n   * \\param[in] n_re: Number of PDSCH RE per RB\n   * \\param[in] R: Code rate\n   * \\param[in] mod_order: Modulation order\n   * \\param[in] num_layers: Number of transport layers\n   * \\param[in] nrb: Number of RB in PDSCH allocation\n   * \\param[out] tbs: Transport block size\n   */\n  long nre = (long)min(156, n_re) * nrb;\n  double n_info = (double)nre * R * mod_order * num_layers;\n  if (n_info <= 3824) {\n    long n = (int)max(3.0, floor(log2(n_info)) - 6);\n    long n_p_info = max(24.0, pow(2, n) * floor((double)n_info / pow(2, n)));\n    for (int i : free5GRAN::TS_38_214_TABLE_5_1_3_2_1) {\n      if (i >= n_p_info) {\n        tbs = i;\n        break;\n      }\n    }\n  } else {\n    cout << \"N INFO not supported !\" << endl;\n  }\n}\n\n/*\n * TS 38 212 5.2.2\n */\nvoid free5GRAN::phy::transport_channel::compute_Zc_dl_sch(int kb,\n                                                          float k_p,\n                                                          int& Zc,\n                                                          int& i_ls) {\n  /**\n   * \\fn compute_Zc_dl_sch\n   * \\brief Compute LDPC lifting size for DL-SCH encoding/decoding\n   * \\standard TS 38.212 V15.2.0 Section 5.2.2\n   *\n   * \\param[in] kb: Intermediate value for Zc computation\n   * \\param[in] k_p: K' value\n   * \\param[out] Zc: Returned value\n   * \\param[out] i_ls: Zc set index\n   */\n  Zc = 512;\n  for (int i = 0; i < 8; i++) {\n    for (int j = 0; j < 8; j++) {\n      if (TS_38_212_TABLE_5_3_2_1[i][j] < Zc &&\n          TS_38_212_TABLE_5_3_2_1[i][j] >= (k_p / (float)kb)) {\n        Zc = TS_38_212_TABLE_5_3_2_1[i][j];\n        i_ls = i;\n      }\n    }\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::\n    compute_code_block_segmentation_info_ldpc(int graph,\n                                              int B,\n                                              int& Zc,\n                                              int& K,\n                                              int& i_ls,\n                                              int& L,\n                                              int& C,\n                                              int& N,\n                                              int& K_p) {\n  /**\n   * \\fn compute_code_block_segmentation_info_ldpc\n   * \\brief Compute code block segmentation informations for LDPC\n   * \\standard TS 38.212 V15.2.0 Section 5.2.2\n   *\n   * \\param[in] graph: LDPC base graph\n   * \\param[in] B: Code block segmentation input size (inlcuding CRC)\n   * \\param[out] Zc: Returned LDPC lifting size\n   * \\param[out] K: Code block segmentation output size\n   * \\param[out] i_ls: Zc set index\n   * \\param[out] L: Code block CRC length\n   * \\param[out] C: Number of code blocks\n   * \\param[out] N: LDPC output sequence\n   * \\param[out] K_p: K' intermediate K value\n   */\n  int k_b, B_p;\n  int k_cb = (graph == 1) ? 8448 : 3840;\n  if (B <= k_cb) {\n    L = 0;\n    C = 1;\n    B_p = B;\n  } else {\n    L = 24;\n    C = ceil(B / (k_cb - L));\n    B_p = B + C * L;\n  }\n  float k_p = (float)B_p / (float)C;\n  if (graph == 1) {\n    k_b = 22;\n  } else {\n    if (B > 640) {\n      k_b = 10;\n    } else if (B > 560) {\n      k_b = 9;\n    } else if (B > 192) {\n      k_b = 8;\n    } else {\n      k_b = 6;\n    }\n  }\n  compute_Zc_dl_sch(k_b, k_p, Zc, i_ls);\n  K = (graph == 1) ? 22 * Zc : 10 * Zc;\n  N = (graph == 1) ? 66 * Zc : 50 * Zc;\n  K_p = (int)k_p;\n}\n\nvoid free5GRAN::phy::transport_channel::rate_recover_ldpc(\n    int* input_bits,\n    int N,\n    int i_lbrm,\n    int E,\n    int id_rv,\n    int mod_order,\n    int C,\n    int Zc,\n    int graph,\n    int K,\n    int K_p,\n    int* output_sequence) {\n  /**\n   * \\fn rate_recover_ldpc\n   * \\brief Rate recovering for LDPC (hard bits)\n   * \\standard TS 38.212 V15.2.0 Section 5.4.2\n   *\n   * \\param[in] input_bits: DL-SCH input bits\n   * \\param[in] N: Output sequence length\n   * \\param[in] i_lbrm: Indicator for N_cb computation\n   * \\param[in] E: DL-SCH input sequence length\n   * \\param[in] id_rv: Redundancy version\n   * \\param[in] mod_order: Modulation order\n   * \\param[in] C: Number of code blocks\n   * \\param[in] Zc: LDPC lifting size\n   * \\param[in] graph: LDPC base graph\n   * \\param[in] K: Code block length\n   * \\param[in] K_p: K' code block intermediate length\n   * \\param[out] output_sequence: Output bits\n   */\n  int N_cb = (i_lbrm == 0) ? N : min(N, 25344);\n  int e[E];\n  int E_Q = (int)((float)E / (float)mod_order);\n  /*\n   * Input de-interleaving\n   */\n  for (int j = 0; j < E_Q; j++) {\n    for (int i = 0; i < mod_order; i++) {\n      e[i * (E_Q) + j] = input_bits[i + j * mod_order];\n    }\n  }\n  /*\n   * Compute k0\n   */\n  int k0, k, j;\n  if (id_rv == 0) {\n    k0 = 0;\n  } else if (id_rv == 1) {\n    k0 = (graph == 1) ? floor((17.0 * N_cb) / (66.0 * Zc)) * Zc\n                      : floor((13.0 * N_cb) / (50.0 * Zc)) * Zc;\n  } else if (id_rv == 2) {\n    k0 = (graph == 1) ? floor((33.0 * N_cb) / (66.0 * Zc)) * Zc\n                      : floor((25.0 * N_cb) / (50.0 * Zc)) * Zc;\n  } else if (id_rv == 3) {\n    k0 = (graph == 1) ? floor((56.0 * N_cb) / (66.0 * Zc)) * Zc\n                      : floor((43.0 * N_cb) / (50.0 * Zc)) * Zc;\n  }\n\n  /*\n   * rate recovering\n   */\n  j = 0;\n  k = 0;\n  while (k < E) {\n    int index = (k0 + j) % N_cb;\n    if (index >= K_p - 2 * Zc && index < K - 2 * Zc) {\n      output_sequence[index] = -1;\n    } else {\n      output_sequence[index] = e[k];\n      k++;\n    }\n    j++;\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::rate_recover_ldpc(\n    double* input_bits,\n    int N,\n    int i_lbrm,\n    int E,\n    int id_rv,\n    int mod_order,\n    int C,\n    int Zc,\n    int graph,\n    int K,\n    int K_p,\n    double* output_sequence) {\n  /**\n   * \\fn rate_recover_ldpc\n   * \\brief Rate recovering for LDPC (soft bits)\n   * \\standard TS 38.212 V15.2.0 Section 5.4.2\n   *\n   * \\param[in] input_bits: DL-SCH input soft bits\n   * \\param[in] N: Output sequence length\n   * \\param[in] i_lbrm: Indicator for N_cb computation\n   * \\param[in] E: DL-SCH input sequence length\n   * \\param[in] id_rv: Redundancy version\n   * \\param[in] mod_order: Modulation order\n   * \\param[in] C: Number of code blocks\n   * \\param[in] Zc: LDPC lifting size\n   * \\param[in] graph: LDPC base graph\n   * \\param[in] K: Code block length\n   * \\param[in] K_p: K' code block intermediate length\n   * \\param[out] output_sequence: Output soft bits\n   */\n  int N_cb = (i_lbrm == 0) ? N : min(N, 25344);\n  double e[E];\n  int E_Q = (int)((float)E / (float)mod_order);\n  /*\n   * Input de-interleaving\n   */\n  for (int j = 0; j < E_Q; j++) {\n    for (int i = 0; i < mod_order; i++) {\n      e[i * (E_Q) + j] = input_bits[i + j * mod_order];\n    }\n  }\n\n  int k0, k, index, j;\n  if (id_rv == 0) {\n    k0 = 0;\n  } else if (id_rv == 1) {\n    k0 = (graph == 1) ? floor((17.0 * N_cb) / (66.0 * Zc)) * Zc\n                      : floor((13.0 * N_cb) / (50.0 * Zc)) * Zc;\n  } else if (id_rv == 2) {\n    k0 = (graph == 1) ? floor((33.0 * N_cb) / (66.0 * Zc)) * Zc\n                      : floor((25.0 * N_cb) / (50.0 * Zc)) * Zc;\n  } else if (id_rv == 3) {\n    k0 = (graph == 1) ? floor((56.0 * N_cb) / (66.0 * Zc)) * Zc\n                      : floor((43.0 * N_cb) / (50.0 * Zc)) * Zc;\n  }\n\n  vector<int> seen_indexes;\n  /*\n   * rate recovering\n   */\n  j = 0;\n  k = 0;\n  while (k < E) {\n    index = (k0 + j) % N_cb;\n    if (find(seen_indexes.begin(), seen_indexes.end(), index) ==\n        seen_indexes.end()) {\n      seen_indexes.push_back(index);\n      if (index >= K_p - 2 * Zc && index < K - 2 * Zc) {\n        output_sequence[index] = numeric_limits<double>::infinity();\n        ;\n      } else {\n        output_sequence[index] = e[k];\n        k++;\n      }\n    }\n    j++;\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::compute_circular_permutation_matrix(\n    int size,\n    int offset,\n    int** matrix) {\n  /**\n   * \\fn compute_circular_permutation_matrix\n   * \\brief Compute offset times right shifted identity matrix of size n\n   * \\param[in] size: Identity matrix size\n   * \\param[in] offset: Number of times to shift matrix\n   * \\param[out] matrix: Output matrix\n   */\n  for (int i = 0; i < size; i++) {\n    for (int j = 0; j < size; j++) {\n      matrix[i][j] = 0;\n    }\n    matrix[i][(i + offset) % size] = 1;\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::ldpc_decode_one_bit(\n    vector<vector<int>> R,\n    double* soft_bits,\n    int i,\n    double& new_bit) {\n  /**\n   * \\fn ldpc_decode_one_bit\n   * \\brief LDPC correct one bit value (using belief propagation algorithm)\n   * \\param[in] R: Input set of rows connected to bit i\n   * \\param[in] soft_bits: Input soft bits\n   * \\param[in] i: Bit index\n   * \\param[out] new_bit: New bit value\n   */\n  double r_p1[R.size()], r_prop, q_p1, q_m1, n_q_p1, n_q_m1;\n  /*\n   * Compute rj for each element in R\n   */\n  for (int j = 0; j < R.size(); j++) {\n    r_p1[j] = 1;\n    for (int i_p = 0; i_p < R[j].size(); i_p++) {\n      r_prop = 1 / (1 + exp(2 * soft_bits[R[j][i_p]]));\n      r_p1[j] *= 1 - 2 * r_prop;\n    }\n    r_p1[j] = 0.5 + 0.5 * r_p1[j];\n  }\n  /*\n   * Compute updated bit probabilities\n   */\n  q_m1 = 1;\n  q_p1 = 1;\n  for (int j = 0; j < R.size(); j++) {\n    q_p1 *= r_p1[j];\n    q_m1 *= (1 - r_p1[j]);\n  }\n  r_prop = 1 / (1 + exp(2 * soft_bits[i]));\n  q_m1 = r_prop * q_m1;\n  q_p1 = (1 - r_prop) * q_p1;\n  /*\n   * Normalization\n   */\n  n_q_p1 = q_p1 / (q_p1 + q_m1);\n  n_q_m1 = q_m1 / (q_p1 + q_m1);\n  /*\n   * Update bit value depending on max probability\n   */\n  if (n_q_p1 > n_q_m1) {\n    new_bit = -0.5 * log((1 / n_q_p1) - 1);\n  } else {\n    new_bit = 0.5 * log((1 / n_q_m1) - 1);\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::compute_H_matrix_ldpc(\n    int Zc,\n    int graph,\n    int i_ls,\n    vector<vector<int>>& matrix,\n    int& size_i,\n    int& size_j) {\n  /**\n   * \\fn compute_H_matrix_ldpc\n   * \\brief Compute Hbg matrix for LDPC\n   * \\standard TS 38.212 V15.2.0 Section 5.3.2\n   *\n   * \\param[in] Zc: LDPC lifting size\n   * \\param[in] graph: LDPC base graph\n   * \\param[in] i_ls: Zc set index\n   * \\param[out] matrix: H matrix\n   * \\param[out] size_i: H matrix number of rows\n   * \\param[out] size_i: H matrix number of columns\n   */\n  if (graph == 1) {\n    size_i = 46;\n    size_j = 68;\n  } else {\n    size_i = 42;\n    size_j = 52;\n  }\n\n  vector<int*> ldpc_table;\n  if (graph == 1) {\n    ldpc_table = free5GRAN::TS_38_212_TABLE_5_3_2_2;\n  } else {\n    ldpc_table = free5GRAN::TS_38_212_TABLE_5_3_2_3;\n  }\n  for (auto& p : ldpc_table) {\n    int index_i = p[0];\n    int index_j = p[1];\n    int v_ij = p[i_ls + 2];\n    matrix[index_i][index_j] = v_ij;\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::ldpc_decode(double* input_bits,\n                                                    int N,\n                                                    int Zc,\n                                                    int graph,\n                                                    int K,\n                                                    int i_ls,\n                                                    int* output_sequence) {\n  /**\n   * \\fn compute_H_matrix_ldpc\n   * \\brief Compute H matrix for LDPC using Belief propagation algorithm\n   * \\standard TS 38.212 V15.2.0 Section 5.3.2\n   *\n   * \\details\n   * Details:\n   * - Compute H matrix\n   * - Recover LDPC input bits from input sequence\n   * - Compute columns and row bit relations\n   * - Iterate 10 time:\n   * -# Try to correct each input bit value\n   * -# If H times corrected bits value equals 0, algorithm ends, otherwise it\n   * continues\n   *\n   * \\param[in] input_bits: Input soft bits sequence\n   * \\param[in] N: LDPC input bit sequence length\n   * \\param[in] Zc: LDPC lifting size\n   * \\param[in] graph: LDPC base graph\n   * \\param[in] K: Code block length\n   * \\param[in] i_ls: Zc set index\n   * \\param[out] output_sequence: Corrected output bits sequence\n   */\n  /*\n   * H matrix generation\n   */\n  int size_i, size_j;\n  size_i = 52;\n  size_j = 42;\n  vector<vector<int>> H(size_j, vector<int>(size_i, -1));\n  compute_H_matrix_ldpc(Zc, graph, i_ls, H, size_j, size_i);\n\n  double ldpc_input_bits[N + 2 * Zc];\n  for (int i = 0; i < 2 * Zc; i++) {\n    ldpc_input_bits[i] = 0;\n  }\n  for (int k = 2 * Zc; k < N + 2 * Zc; k++) {\n    ldpc_input_bits[k] = input_bits[k - 2 * Zc];\n  }\n  double new_bits[N + 2 * Zc];\n  vector<vector<int>> R[N + 2 * Zc], R_tot;\n  vector<int> new_vec, new_vec_tot;\n\n  /*\n   * Generate rows and columns matrices\n   */\n  for (int j = 0; j < size_j * Zc; j++) {\n    new_vec_tot.clear();\n    for (int i = 0; i < size_i; i++) {\n      if (H[j / Zc][i] != -1) {\n        new_vec_tot.push_back(((j % Zc + H[j / Zc][i]) % Zc) + i * Zc);\n      }\n    }\n    R_tot.push_back(new_vec_tot);\n  }\n  int index_l, inter_ind;\n  for (int i = 0; i < N + 2 * Zc; i++) {\n    for (int j = 0; j < size_j; j++) {\n      if (H[j][i / Zc] != -1) {\n        new_vec.clear();\n        inter_ind = ((i % Zc - H[j][i / Zc]) % Zc);\n        if (inter_ind < 0) {\n          inter_ind = Zc + inter_ind;\n        }\n        index_l = inter_ind + j * Zc;\n\n        for (int& p : R_tot[index_l]) {\n          if (p != i) {\n            new_vec.push_back(p);\n          }\n        }\n        R[i].push_back(new_vec);\n      }\n    }\n  }\n  int rest, final_bit[N + 2 * Zc];\n  /*\n   * Looping over iteration\n   */\n  for (int iter = 0; iter < 10; iter++) {\n    /*\n     * Decode bits\n     */\n    for (int i = 0; i < N + 2 * Zc; i++) {\n      ldpc_decode_one_bit(R[i], &ldpc_input_bits[0], i, ref(new_bits[i]));\n    }\n    for (int i = 0; i < N + 2 * Zc; i++) {\n      ldpc_input_bits[i] = new_bits[i];\n      final_bit[i] = (ldpc_input_bits[i] < 0) ? 1 : 0;\n      if (i < K) {\n        output_sequence[i] = final_bit[i];\n      }\n    }\n\n    bool validated = true;\n    for (int j = 0; j < size_j * Zc; j++) {\n      rest = 0;\n      for (int i : R_tot[j]) {\n        rest ^= final_bit[i];\n      }\n      if (rest == 1) {\n        validated = false;\n        break;\n      }\n    }\n    if (validated) {\n      BOOST_LOG_TRIVIAL(trace) << \"LDPC VALIDATED\";\n      break;\n    }\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::decode_bch(int* bch_bits,\n                                                   bool& crc_validated,\n                                                   int* mib_bits,\n                                                   int pci) {\n  /**\n   * \\fn decode_bch\n   * \\brief Decode broadcast channel\n   * \\standard TS 38.212 V15.2.0 Section 7.1\n   *\n   * \\details\n   * Details:\n   * - Rate recovering\n   * - Polar decoding\n   * - CRC validation\n   * - Scrambling\n   * - Payload de-interleaving\n   *\n   * \\param[in] bch_bits: Input bits sequence\n   * \\param[out] crc_validated: Indicator for CRC validation\n   * \\param[out] mib_bits: Output MIB bits\n   * \\param[in] pci: Cell PCI\n   */\n  int n = free5GRAN::phy::transport_channel::compute_N_polar_code(\n      free5GRAN::SIZE_SSB_PBCH_SAMPLES * 2, free5GRAN::SIZE_PBCH_POLAR_DECODED,\n      9);\n  int N = pow(2, n);\n  int rate_recovered_bits[N],\n      polar_decoded_bits[free5GRAN::SIZE_PBCH_POLAR_DECODED],\n      remainder[free5GRAN::BCH_CRC_LENGTH + 1],\n      bch_payload[free5GRAN::BCH_PAYLOAD_SIZE],\n      bch_crc_recomputed[free5GRAN::BCH_CRC_LENGTH],\n      bch_crc[free5GRAN::BCH_CRC_LENGTH], crc_masq[free5GRAN::BCH_CRC_LENGTH];\n  // Rate recover bch_bits to rate_recovered_bits\n  free5GRAN::phy::transport_channel::rate_recover(\n      bch_bits, rate_recovered_bits, 0, free5GRAN::SIZE_SSB_PBCH_SAMPLES * 2, N,\n      free5GRAN::SIZE_PBCH_POLAR_DECODED);\n  // Polar decode rate_recovered_bits to polar_decoded_bits\n  free5GRAN::phy::transport_channel::polar_decode(\n      rate_recovered_bits, polar_decoded_bits, N,\n      free5GRAN::SIZE_PBCH_POLAR_DECODED, 9, 1, 0, 0,\n      free5GRAN::SIZE_SSB_PBCH_SAMPLES * 2);\n  // Validate polar_decoded_bits CRC (compute the remainder and check that t is\n  // equal to 0)\n  free5GRAN::phy::transport_channel::crc_validate(\n      polar_decoded_bits, free5GRAN::G_CRC_24_C, remainder,\n      free5GRAN::SIZE_PBCH_POLAR_DECODED, free5GRAN::BCH_CRC_LENGTH + 1);\n  crc_validated = true;\n  for (int i = 1; i < free5GRAN::BCH_CRC_LENGTH + 1; i++) {\n    if (remainder[i] == 1) {\n      crc_validated = false;\n      break;\n    }\n  }\n  // Split polar_decoded_bits into bch_payload and bch_crc\n  for (int i = 0; i < free5GRAN::BCH_PAYLOAD_SIZE; i++) {\n    bch_payload[i] = polar_decoded_bits[i];\n  }\n  for (int i = 0; i < free5GRAN::BCH_CRC_LENGTH; i++) {\n    bch_crc[i] = polar_decoded_bits[free5GRAN::BCH_PAYLOAD_SIZE + i];\n  }\n  // Re-compute the bch_payload CRC\n  free5GRAN::phy::transport_channel::compute_crc(\n      bch_payload, free5GRAN::G_CRC_24_C, bch_crc_recomputed, 32, 25);\n\n  // XOR recomputed CRC with received CRC to determine CRC masq\n  for (int i = 0; i < free5GRAN::BCH_CRC_LENGTH; i++) {\n    crc_masq[i] = bch_crc[i] ^ bch_crc_recomputed[i];\n  }\n\n  /*\n   * PBCH payload recovering (TS38.212 7.1.1)\n   */\n  int A = free5GRAN::BCH_PAYLOAD_SIZE;\n  int A_bar = free5GRAN::BCH_PAYLOAD_SIZE - 8;\n  int M = A - 3;\n  int s_sequence[A], bch_descrambled[free5GRAN::BCH_PAYLOAD_SIZE];\n  int sfn_bits[4][2] = {{0, 0}, {0, 1}, {1, 0}, {1, 1}};\n  // Find the correct value of v\n  for (int v = 0; v < 4; v++) {\n    // Generate de-scrambling sequence\n    int c_seq[free5GRAN::BCH_PAYLOAD_SIZE + v * M];\n    free5GRAN::utils::sequence_generator::generate_c_sequence(\n        pci, free5GRAN::BCH_PAYLOAD_SIZE + v * M, c_seq, 0);\n    int j = 0;\n    // Generate s sequence\n    for (int i = 0; i < A; i++) {\n      if (i == 0 || i == 6 || i == 24) {\n        s_sequence[i] = 0;\n      } else {\n        s_sequence[i] = c_seq[j + v * M];\n        j++;\n      }\n    }\n    // De-scramble bch_payload to bch_descrambled\n    free5GRAN::utils::common_utils::scramble(bch_payload, s_sequence,\n                                             bch_descrambled,\n                                             free5GRAN::BCH_PAYLOAD_SIZE, 0);\n\n    // BCH payload de-interleaving\n    int j_sfn = 0;\n    int j_hrf = 10;\n    int j_ssb = 11;\n    int j_other = 14;\n    for (int i = 0; i < 32; i++) {\n      if (i == 24 || i == 25 || i == 26 || i == 27 || i == 1 || i == 2 ||\n          i == 3 || i == 4 || i == 5 || i == 6) {\n        mib_bits[i] =\n            bch_descrambled[free5GRAN::PBCH_PAYLOAD_INTERLEAVER[j_sfn]];\n        j_sfn++;\n      } else if (i == 28) {\n        mib_bits[i] =\n            bch_descrambled[free5GRAN::PBCH_PAYLOAD_INTERLEAVER[j_hrf]];\n      } else if (i >= A_bar + 5 && i <= A_bar + 7) {\n        mib_bits[i] =\n            bch_descrambled[free5GRAN::PBCH_PAYLOAD_INTERLEAVER[j_ssb]];\n        j_ssb++;\n      } else {\n        mib_bits[i] =\n            bch_descrambled[free5GRAN::PBCH_PAYLOAD_INTERLEAVER[j_other]];\n        j_other++;\n      }\n    }\n    // If final bits correspond to 3rd and 2nd LSB of SFN, correct v was found\n    if (sfn_bits[v][0] == mib_bits[25] && sfn_bits[v][1] == mib_bits[26]) {\n      break;\n    }\n  }\n}\n\nvoid free5GRAN::phy::transport_channel::decode_dci(\n    int* dci_bits,\n    int E,\n    int K,\n    int* rnti,\n    bool& validated,\n    vector<int>& decoded_dci_bits) {\n  /**\n   * \\fn decode_dci\n   * \\brief DCI decoding\n   * \\standard TS 38.212 V15.2.0 Section 7.3\n   *\n   * \\partial_imp Only DCI Format 1_0 has been tested\n   * \\details\n   * Details:\n   * - Rate recovering\n   * - Polar decoding\n   * - RNTI scrambling\n   * - CRC validation\n   *\n   * \\param[in] dci_bits: Input bits sequence\n   * \\param[in] E: PDCCH payload size\n   * \\param[in] K: DCI payload size (including CRC)\n   * \\param[in] rnti: RNTI for identifying DCI Format\n   * \\param[out] validated: Indicator for CRC validation\n   * \\param[out] decoded_dci_bits: Output bits sequence\n   */\n  int n = compute_N_polar_code(E, K, 9);\n  int N = pow(2, n);\n\n  BOOST_LOG_TRIVIAL(trace) << \"(n, N) = (\" + to_string(n) + \", \" +\n                                  to_string(N) + \")\";\n  BOOST_LOG_TRIVIAL(trace) << \"E = \" + to_string(E);\n  BOOST_LOG_TRIVIAL(trace) << \"K = \" + to_string(K);\n\n  int rate_recovered[N], polar_decoded[K], remainder[25], descrambled[K + 24];\n\n  int A = K - 24;\n  /*\n   * rate recovering\n   */\n  rate_recover(dci_bits, rate_recovered, 0, E, N, K);\n  /*\n   * Polar decoding\n   */\n  polar_decode(rate_recovered, polar_decoded, N, K, 9, 1, 0, 0, E);\n  /*\n   * RNTI de-masking and CRC validation\n   */\n  for (int i = 0; i < 24; i++) {\n    descrambled[i] = 1;\n  }\n  for (int i = 0; i < K; i++) {\n    if (i < A + 8) {\n      descrambled[i + 24] = polar_decoded[i];\n    } else {\n      descrambled[i + 24] = (polar_decoded[i] + rnti[i - A - 8]) % 2;\n    }\n  }\n  crc_validate(descrambled, free5GRAN::G_CRC_24_C, remainder, K + 24, 25);\n  validated = true;\n  for (int i : remainder) {\n    if (i == 1) {\n      validated = false;\n      break;\n    }\n  }\n  BOOST_LOG_TRIVIAL(trace) << \"## CRC \"\n                           << ((validated) ? \"validated\" : \"not validated\");\n\n  for (int i = 0; i < A; i++) {\n    decoded_dci_bits[i] = polar_decoded[i];\n  }\n}\n\nauto free5GRAN::phy::transport_channel::decode_dl_sch(\n    double* dl_sch_bits,\n    int n_re,\n    float R,\n    int nrb,\n    int E,\n    bool& validated,\n    free5GRAN::dci_1_0_si_rnti dci_1_0_si_rnti) -> vector<int> {\n  /**\n   * \\fn decode_dl_sch\n   * \\brief DL-SCH decoding\n   * \\standard TS 38.212 V15.2.0 Section 7.2\n   *\n   * \\partial_imp Implemented for one code block (C=1)\n   * \\details\n   * Details:\n   * - Rate recovering\n   * - LDPC decoding\n   * - CRC validation\n   *\n   * \\param[in] dl_sch_bits: Input soft bits sequence\n   * \\param[in] n_re: Number of RE per PDSCH RB\n   * \\param[in] R: Code Rate\n   * \\param[in] nrb: Number of PDSCH allocated RB\n   * \\param[in] E: PDSCH output sequence length\n   * \\param[out] validated: CRC validation indicator\n   * \\param[in] dci_1_0_si_rnti: Input DCI Format 1_0 object\n   */\n\n  /*\n   * Compute code block segmentation information\n   */\n  int graph, A, N, K, Zc, i_ls, L_cb, C, B, L, K_p;\n  compute_transport_block_size(n_re, R, 2, 1, nrb, A);\n  compute_ldpc_base_graph(A, R, graph);\n  L = (A > 3824) ? 24 : 16;\n  B = A + L;\n  compute_code_block_segmentation_info_ldpc(graph, B, Zc, K, i_ls, L_cb, C, N,\n                                            K_p);\n\n  BOOST_LOG_TRIVIAL(trace) << \"(TBS, graph) = \" << A << \", \" << graph;\n  BOOST_LOG_TRIVIAL(trace) << \"B = \" << B;\n  BOOST_LOG_TRIVIAL(trace) << \"Zc = \" << Zc;\n  BOOST_LOG_TRIVIAL(trace) << \"K = \" << K;\n  BOOST_LOG_TRIVIAL(trace) << \"i_ls = \" << i_ls;\n  BOOST_LOG_TRIVIAL(trace) << \"L = \" << L;\n  BOOST_LOG_TRIVIAL(trace) << \"C = \" << C;\n  BOOST_LOG_TRIVIAL(trace) << \"N = \" << N;\n  BOOST_LOG_TRIVIAL(trace) << \"L_cb = \" << L_cb;\n  BOOST_LOG_TRIVIAL(trace) << \"K_p = \" << K_p;\n  BOOST_LOG_TRIVIAL(trace) << \"E = \" << E;\n\n  /*\n   * Rate recovering\n   */\n  auto* rate_recovered = new double[N];\n  rate_recover_ldpc(dl_sch_bits, N, 1, E, dci_1_0_si_rnti.rv, 2, C, Zc, graph,\n                    K, K_p, rate_recovered);\n\n  /*\n   * LDPC decoding\n   */\n  int ldpc_decoded[K];\n  auto start = chrono::steady_clock::now();\n  ldpc_decode(rate_recovered, N, Zc, graph, K, i_ls, ldpc_decoded);\n  auto end = chrono::steady_clock::now();\n  auto diff = end - start;\n  BOOST_LOG_TRIVIAL(trace) << \"## LDPC execution time \"\n                           << chrono::duration<double, milli>(diff).count()\n                           << \"ms\";\n\n  int desegmented[B];\n  for (int i = 0; i < B; i++) {\n    desegmented[i] = ldpc_decoded[i];\n  }\n\n  /*\n   * CRC validation\n   */\n  int remainder[L];\n  if (L == 24) {\n    crc_validate(desegmented, free5GRAN::G_CRC_24_C, remainder, B, L + 1);\n  } else {\n    crc_validate(desegmented, free5GRAN::G_CRC_16, remainder, B, L + 1);\n  }\n\n  validated = true;\n  for (int i = 0; i < L + 1; i++) {\n    if (remainder[i] == 1) {\n      validated = false;\n      break;\n    }\n  }\n  vector<int> output_bits(A);\n\n  for (int i = 0; i < A; i++) {\n    output_bits[i] = desegmented[i];\n  }\n\n  BOOST_LOG_TRIVIAL(trace) << \"## CRC \"\n                           << ((validated) ? \"validated\" : \"not validated\");\n\n  return output_bits;\n}", "meta": {"hexsha": "d452455c499b41b155d0c20a14ec45589aaddbe8", "size": 38575, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/phy/transport_channel/transport_channel.cpp", "max_stars_repo_name": "Taclino/Newfree5GRAN", "max_stars_repo_head_hexsha": "24abe97f6c12a6b1b0885d5ee161901e6811952c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T06:58:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:43:19.000Z", "max_issues_repo_path": "lib/phy/transport_channel/transport_channel.cpp", "max_issues_repo_name": "GuillaumeC1A/free5GRAN", "max_issues_repo_head_hexsha": "f6624f22a301bfc354acfc46ec8b13457adf57f1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-01-15T10:48:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T16:20:05.000Z", "max_forks_repo_path": "lib/phy/transport_channel/transport_channel.cpp", "max_forks_repo_name": "GuillaumeC1A/free5GRAN", "max_forks_repo_head_hexsha": "f6624f22a301bfc354acfc46ec8b13457adf57f1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2021-01-08T12:09:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-26T13:41:17.000Z", "avg_line_length": 28.9819684448, "max_line_length": 80, "alphanum_fraction": 0.5322099806, "num_tokens": 12486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.42851231822973695}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SIMD_F_LOG_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_SIMD_F_LOG_HPP_INCLUDED\n\n\n#include <boost/simd/function/simd/multiplies.hpp>\n#include <boost/simd/function/simd/plus.hpp>\n#include <boost/simd/function/simd/fma.hpp>\n#include <boost/simd/function/simd/is_eqz.hpp>\n#include <boost/simd/function/simd/if_nan_else.hpp>\n#include <boost/simd/function/simd/if_else.hpp>\n#include <boost/simd/function/simd/if_else_zero.hpp>\n#include <boost/simd/function/simd/is_ltz.hpp>\n#include <boost/simd/arch/common/detail/generic/f_log_kernel.hpp>\n#include <boost/simd/arch/common/detail/tags.hpp>\n#include <boost/simd/constant/mhalf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/log_2hi.hpp>\n#include <boost/simd/constant/log_2lo.hpp>\n#include <boost/simd/constant/log2_em1.hpp>\n#include <boost/simd/constant/log10_ehi.hpp>\n#include <boost/simd/constant/log10_elo.hpp>\n#include <boost/simd/constant/log10_2hi.hpp>\n#include <boost/simd/constant/log10_2lo.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n#include <boost/dispatch/meta/scalar_of.hpp>\n\n#ifndef BOOST_SIMD_NO_NANS\n#include <boost/simd/function/simd/is_nan.hpp>\n#include <boost/simd/function/simd/logical_or.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/function/simd/is_equal.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_DENORMALS\n#include <boost/simd/function/simd/abs.hpp>\n#include <boost/simd/function/simd/is_less.hpp>\n#include <boost/simd/constant/smallestposval.hpp>\n#include <boost/simd/constant/twotonmb.hpp>\n#include <boost/simd/constant/mlogtwo2nmb.hpp>\n#include <boost/simd/constant/mlog2two2nmb.hpp>\n#include <boost/simd/constant/mlog10two2nmb.hpp>\n#endif\n\n  //////////////////////////////////////////////////////////////////////////////\n  // how to compute the various logarithms\n  //////////////////////////////////////////////////////////////////////////////\n  // The method is mainly taken from the cephes library:\n  // first reduce the the data\n  // a0 is supposed > 0\n  // the input a0 is split into a mantissa and an exponent\n  // the mantissa m is between sqrt(0.5) and sqrt(2) and the corresponding exponent is e\n  // a0 = m*2^e\n  // then the log? calculus is split in two parts (? being nothing: natural logarithm,  2: base 2 logarithm,\n  //10 base ten logarithm)\n  // as log?(a) = log?(2^e)+log?(m)\n  // 1) computing log?(m)\n  //   first put x = m-1 (so -0.29 <  x < 0.414)\n  //   write log(m)   = log(1+x)   = x + x*x/2 + x*x*x*g(x)\n  //   write log2(m)  = log2(1+x)  = C2*log(x),\n  //     C2 = log(2)  the multiplication have to be taken seriously as C2 is not exact\n  //   write log10(m) = log10(1+x) = C10*log(x),\n  //     C10= log(10) the multiplication have to be taken seriously as C10 is not exact\n  // then g(x) has to be approximated\n  // g is ((log(1+x)/x-1)/x-1/2)/x\n  // It is not a good idea to approximate directly log(1+x) instead of g,  because this will lead to bad precision around 1.\n  //\n  // in this approximation one can choose a best approximation rational function given by remez algorithm.\n  // there exist a classical solution which is a polynomial p8 one of degree 8 that gives 0.5ulps everywhere\n  // this is what is done in the kernel_t::log impl;\n  // Now,  it is possible to choose a rational fraction or a polynomial of lesser degree to approximate g\n  // providing faster but less accurate logs.\n  // 2) computing log?(2^e)\n  // see the explanations relative to each case\n  // 3) finalize\n  // This is simply treating invalid entries\n  // 4) For denormal we use the fact that log(x) =  log?(x*y)-log?(y) and that if y is\n  // the constant two2nmb if x is denormal x*y and y are not.\n  //////////////////////////////////////////////////////////////////////////////\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    namespace bd = boost::dispatch;\n    template < class A0 >\n    struct logarithm< A0, tag::simd_type, float>\n    {\n      using int_type = bd::as_integer_t<A0, signed>;\n      using sA0 = bd::scalar_of_t<A0>;\n      using  kernel_t = kernel<A0, tag::simd_type, float>;\n\n      static inline A0 log(const A0& a0) BOOST_NOEXCEPT\n      {\n        A0 z = a0;\n#ifndef BOOST_SIMD_NO_DENORMALS\n        A0 t = Zero<A0>();\n        auto denormal = is_less(bs::abs(z), Smallestposval<A0>());\n        z = if_else(denormal, z*Twotonmb<A0>(), z);\n        t = if_else_zero(denormal, Mlogtwo2nmb<A0>());\n#endif\n        //log(2.0) in double is 6.931471805599453e-01\n        //double(0.693359375f)+double(-0.00021219444f)  is  6.931471805600000e-01 at 1.0e-14 of log(2.0)\n        // let us call Log_2hi 0.693359375f anf Log_2lo -0.00021219444f\n        // We use thi to correct the sum where this could matter a lot\n        // log(a0) = fe*Log_2hi+ (0.5f*x*x +(fe*Log_2lo+y))\n        // These operations are order dependent: the parentheses do matter\n        A0 x, fe, x2, y;\n        kernel_t::log(z, fe, x, x2, y);\n        y = bs::fma(fe, Log_2lo<A0>(), y);\n        y = bs::fma(Mhalf<A0>(), x2, y);\n#ifdef BOOST_SIMD_NO_DENORMALS\n        return finalize(a0, bs::fma(Log_2hi<A0>(), fe, x+y));\n#else\n        return finalize(a0, bs::fma(Log_2hi<A0>(), fe, x+y+t));\n#endif\n      }\n\n      static inline A0 log2(const A0& a0) BOOST_NOEXCEPT\n      {\n        A0 z =  a0;\n#ifndef BOOST_SIMD_NO_DENORMALS\n        auto denormal = lt(bs::abs(z), Smallestposval<A0>());\n        z = if_else(denormal, z*Twotonmb<A0>(), z);\n        A0 t = if_else_zero(denormal, Mlog2two2nmb<A0>());\n#endif\n        //here let l2em1 = log2(e)-1, the computation is done as:\n        //log2(a0) = ((l2em1*x+(l2em1*(y+x*x/2)))+(y+x*x/2)))+x+fe for best results\n        // once again the order is very important.\n        A0 x, fe, x2, y;\n        kernel_t::log(z, fe, x, x2, y);\n        y = bs::fma(Mhalf<A0>(),x2, y);\n        z = bs::fma(x,Log2_em1<A0>(),y*Log2_em1<A0>());\n#ifdef BOOST_SIMD_NO_DENORMALS\n        return finalize(a0, ((z+y)+x)+fe);\n#else\n        return finalize(a0, ((z+y)+x)+fe+t);\n#endif\n      }\n\n      static inline A0 log10(const A0& a0) BOOST_NOEXCEPT\n      {\n        A0 z = a0;\n#ifndef BOOST_SIMD_NO_DENORMALS\n        auto denormal = lt(bs::abs(z), Smallestposval<A0>());\n        z = if_else(denormal, z*Twotonmb<A0>(), z);\n        A0 t = if_else_zero(denormal, Mlog10two2nmb<A0>());\n#endif\n        // here there are two multiplication: log of fraction by log10(e) and base 2 exponent by log10(2)\n        // and we have to split log10(e) and log10(2) in two parts to get extra precision when needed\n        A0 x, fe, x2, y;\n        kernel_t::log(z, fe, x, x2, y);\n        y = bs::fma(x2, Mhalf<A0>(), y);\n        z = (x+y* Log10_elo<A0>());\n        z = bs::fma(y, Log10_ehi<A0>(), z);\n        z = bs::fma( x, Log10_ehi<A0>(), z);\n        z = bs::fma(fe, Log10_2hi<A0>(), z);\n#ifdef BOOST_SIMD_NO_DENORMALS\n        return finalize(a0, bs::fma(fe, Log10_2lo<A0>(), z));\n#else\n        return finalize(a0, bs::fma(fe, Log10_2lo<A0>(), z+t));\n#endif\n      }\n    private:\n      static inline A0 finalize(const A0& a0, const A0& y) BOOST_NOEXCEPT\n      {\n#ifdef BOOST_SIMD_NO_NANS\n        auto test = bs::is_ltz(a0);\n#else\n        auto test = bs::logical_or(bs::is_ltz(a0), bs::is_nan(a0));\n#endif\n        A0 y1 = bs::if_nan_else(test, y);\n#ifndef BOOST_SIMD_NO_INFINITIES\n        y1 = if_else(bs::is_equal(a0, bs::Inf<A0>()), a0, y1);\n#endif\n        return if_else(is_eqz(a0), bs::Minf<A0>(), y1);\n      }\n    };\n  }\n} }\n\n#endif\n\n", "meta": {"hexsha": "0f88877195be61b4b65d62f45346dd1b30c29038", "size": 7945, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/detail/simd/f_log.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/detail/simd/f_log.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/detail/simd/f_log.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3802083333, "max_line_length": 124, "alphanum_fraction": 0.6219005664, "num_tokens": 2393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.42851231151640823}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// distribution::survival::response::right_truncated::mean_event.hpp   \t\t //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_RESPONSE_RIGHT_TRUNCATED_MEAN_EVENT_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_RESPONSE_RIGHT_TRUNCATED_MEAN_EVENT_HPP_ER_2009\n#include <stdexcept>\n#include <boost/type_traits.hpp>\n#include <boost/range.hpp>\n#include <boost/format.hpp>\n#include <boost/operators.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace distribution{\nnamespace survival{\nnamespace response{\n\n    // This class can be used to accumulate the proportion of failures and \n    // mean event time in a sequence of events.\n    //\n    // In the case of the exponential, a collection of mean_events can\n    // form a sufficient statistic,  assuming a discretized domain for\n    // the covariate: domain(x) = {x[k]:k=0,...,K-1}\n    //\n    // $\\log L_i(\\beta) = \\nu_i \\eta_i - t_i \\exp(\\eta_i)$\n    // where $\\eta_i = \\langle x_i,beta \\rangle$\n    // log L(D,\\beta) = sum{\n    //    <x[k],\\beta> sum{\\nu[i]:x[i]==x[k]}\n    //     -exp(<x[k],\\beta>) sum{t[i] : x[i]==x[k]}\n    //  :k=1,...,K\n    // }\n    // Sufficient statistic:\n    // {(sum{\\nu[i]:x[i]==x[k]},sum{t[i] : x[i]==x[k]}):k=0,...,K-1}\n    template<typename T,typename B = bool>\n    class mean_event : \n        public event<T,T>, \n        boost::addable<\n            mean_event<T,B>\n        >\n        // TODO equality_comparable<mean_event<T,B> >\n    {\n    public:\n        typedef event<T,B>  event_;\n        typedef event<T,T>  super_;\n        typedef typename super_::value_type value_type;\n        typedef std::size_t                 size_type;\n            \n        // Construction\n        mean_event();\n        mean_event(const event_&);\n        mean_event(const mean_event&);\n        mean_event& operator=(const mean_event&);\n            \n        // Access\n        size_type count()const;\n            \n        // Operators\n        mean_event& operator+=( const mean_event& e );\n        mean_event& operator()( const event_& e ); \n        \n        // I/O\n        template<class Archive> \n        void serialize(Archive & ar, const unsigned int version);\n        \n        private:\n        value_type impl(size_type n_a,value_type a,size_type n_b,value_type b);\n        size_type  count_;\n        static super_ convert(const event_&);\n    };\n\n    template<typename T,typename B>\n    std::ostream& operator<<(std::ostream& out,const mean_event<T,B>& e);\n\n    template<typename E>\n    struct meta_mean_event{\n        typedef typename E::value_type value_type;\n        typedef mean_event<value_type> type;\n    };\n    \n    // Implementation //\n    \n    // Constructor\n    template<typename T,typename B>\n    mean_event<T,B>::mean_event()\n    :super_(static_cast<T>(false),static_cast<T>(0)),\n    count_(0){\n        // Using super_() instead, would initialize time to inf.\n    }\n\n    template<typename T,typename B>\n    mean_event<T,B>::mean_event(const event_& e)\n    :super_(convert(e)),count_(1){\n        const char* msg = \"mean_event::mean_event(e), isinf(e.time())\";\n        if(boost::math::isinf(this->time())){\n            throw std::runtime_error(\n                msg\n            );\n        }\n    }\n\n    template<typename T,typename B>\n    mean_event<T,B>::mean_event(const mean_event& that)\n    :super_(that),count_(that.count_){}\n\n    template<typename T,typename B>\n    mean_event<T,B>& \n    mean_event<T,B>::operator=(const mean_event& that){\n        if(&that!=this){\n            super_::operator=( that );\n            count_ = that.count_;\n        }\n        return *this;\n    }\n    \n    // Access\n    template<typename T,typename B>\n    typename mean_event<T,B>::size_type \n    mean_event<T,B>::count()const{ return count_; }\n    \n    // Update\n    template<typename T,typename B>\n    mean_event<T,B>& \n    mean_event<T,B>::operator()(const event_& e){\n        mean_event other(e);\n        return ( (*this) += other );\n    }\n    \n    template<typename T,typename B>\n    mean_event<T,B>& \n    mean_event<T,B>::operator+=(const mean_event& other){\n        size_type n_a = this->count();\n        size_type n_b = other.count();\n        (this->failure_) \n            = (this->impl(n_a,this->failure(),n_b,other.failure()));\n        (this->time_) \n            = (this->impl(n_a,this->time(),n_b,other.time()));\n        (this->count_) += n_b;\n        return *this;\n    }\n    \n    //Private\n    template<typename T,typename B>\n    template<class Archive>\n    void mean_event<T,B>::serialize(Archive & ar, const unsigned int version)\n    {\n        ar & boost::serialization::base_object<super_>(*this);\n        ar & count_;\n    }\n\n    template<typename T,typename B>\n    typename mean_event<T,B>::value_type \n    mean_event<T,B>::impl(\n            size_type n_a,\n            value_type a,\n            size_type n_b,\n            value_type b\n    ){\n        return ( (n_a * a) + (n_b * b) ) / (n_a + n_b);\n    }\n    \n    template<typename T,typename B>\n    std::ostream& operator<<(std::ostream& out,const mean_event<T,B>& that){\n        typedef mean_event<T,B> that_;\n        typedef typename that_::super_ super_;\n        static const char* str = \"(%1%,%2%)\";\n        format f(str);\n        f % that.count() % static_cast<const super_&>(that) ;\n        out << f.str();\n        return out;\n    }\n\n    template<typename T,typename B>\n    typename mean_event<T,B>::super_ \n    mean_event<T,B>::convert(const event_& e){\n        static value_type zero = static_cast<value_type>(0);\n        static value_type one = static_cast<value_type>(1);\n        value_type t = e.time();\n        if(e.failure()){\n            return super_( one, t );\n        }else{\n            return super_( zero, t );\n        }\n    }\n\n}// response\n}// survival\n}// distribution\n}// detail\n}// statistics\n}// boost\n\n#endif", "meta": {"hexsha": "0bce71b3ab93186d5be3639a48680608618c908e", "size": 6414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "distribution_survival/boost/statistics/detail/distribution/survival/response/types/right_truncated/mean_event.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "distribution_survival/boost/statistics/detail/distribution/survival/response/types/right_truncated/mean_event.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "distribution_survival/boost/statistics/detail/distribution/survival/response/types/right_truncated/mean_event.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.07, "max_line_length": 101, "alphanum_fraction": 0.5710944808, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802471698041, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.42850865975259156}}
{"text": "/***************************************************************************\n * Copyright 1998-2020 by authors (see AUTHORS.txt)                        *\n *                                                                         *\n *   This file is part of LuxCoreRender.                                   *\n *                                                                         *\n * Licensed under the Apache License, Version 2.0 (the \"License\");         *\n * you may not use this file except in compliance with the License.        *\n * You may obtain a copy of the License at                                 *\n *                                                                         *\n *     http://www.apache.org/licenses/LICENSE-2.0                          *\n *                                                                         *\n * Unless required by applicable law or agreed to in writing, software     *\n * distributed under the License is distributed on an \"AS IS\" BASIS,       *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*\n * See the License for the specific language governing permissions and     *\n * limitations under the License.                                          *\n ***************************************************************************/\n\n#include <map>\n#include <vector>\n#include <string>\n#include <queue>\n#include <limits>\n\n#include <boost/format.hpp>\n\n#include \"luxrays/core/exttrianglemesh.h\"\n#include \"slg/shapes/simplify.h\"\n#include \"slg/scene/scene.h\"\n#include \"slg/utils/harlequincolors.h\"\n\nusing namespace std;\nusing namespace luxrays;\nusing namespace slg;\n\n//------------------------------------------------------------------------------\n//\n// The following code is based on Sven Forstmann's quadric mesh simplification\n// code (https://github.com/sp4cerat/Fast-Quadric-Mesh-Simplification)\n// and heavily modified for LuxCoreRender\n//\n// Papers at https://mgarland.org/research/quadrics.html\n\n/////////////////////////////////////////////\n//\n// Mesh Simplification Tutorial\n//\n// (C) by Sven Forstmann in 2014\n//\n// License : MIT\n// http://opensource.org/licenses/MIT\n//\n// https://github.com/sp4cerat/Fast-Quadric-Mesh-Simplification\n//\n// 5/2016: Chris Rorden created minimal version for OSX/Linux/Windows compile\n\nclass SymetricMatrix {\npublic:\n\t// Constructor\n\tSymetricMatrix(const float c = 0.f) {\n\t\tfor (u_int i = 0; i < 10; ++i)\n\t\t\tm[i] = c;\n\t}\n\n\tSymetricMatrix(\n\t\t\tconst float m11, const float m12, const float m13, const float m14,\n\t\t\tconst float m22, const float m23, const float m24,\n\t\t\tconst float m33, const float m34,\n\t\t\tconst float m44) {\n\t\tm[0] = m11;\n\t\tm[1] = m12;\n\t\tm[2] = m13;\n\t\tm[3] = m14;\n\t\tm[4] = m22;\n\t\tm[5] = m23;\n\t\tm[6] = m24;\n\t\tm[7] = m33;\n\t\tm[8] = m34;\n\t\tm[9] = m44;\n\t}\n\n\t// Make plane\n\tSymetricMatrix(const float a, const float b, const float c, const float d) {\n\t\tm[0] = a * a;\n\t\tm[1] = a * b;\n\t\tm[2] = a * c;\n\t\tm[3] = a * d;\n\t\tm[4] = b * b;\n\t\tm[5] = b * c;\n\t\tm[6] = b * d;\n\t\tm[7] = c * c;\n\t\tm[8] = c * d;\n\t\tm[9] = d * d;\n\t}\n\n\tfloat operator[](int c) const {\n\t\treturn m[c];\n\t}\n\n\t// Determinant\n\tfloat det(\n\t\t\tconst u_int a11, const u_int a12, const u_int a13,\n\t\t\tconst u_int a21, const u_int a22, const u_int a23,\n\t\t\tconst u_int a31, const u_int a32, const u_int a33) const {\n\t\tconst float det = m[a11] * m[a22] * m[a33] + m[a13] * m[a21] * m[a32] + m[a12] * m[a23] * m[a31]\n\t\t\t\t- m[a13] * m[a22] * m[a31] - m[a11] * m[a23] * m[a32] - m[a12] * m[a21] * m[a33];\n\t\treturn det;\n\t}\n\n\tconst SymetricMatrix operator+(const SymetricMatrix &n) const {\n\t\treturn SymetricMatrix(\n\t\t\t\tm[0] + n[0], m[1] + n[1], m[2] + n[2], m[3] + n[3],\n\t\t\t\tm[4] + n[4], m[5] + n[5], m[6] + n[6],\n\t\t\t\tm[7] + n[7], m[8] + n[8],\n\t\t\t\tm[9] + n[9]);\n\t}\n\n\tSymetricMatrix& operator+=(const SymetricMatrix& n) {\n\t\tm[0] += n[0];\n\t\tm[1] += n[1];\n\t\tm[2] += n[2];\n\t\tm[3] += n[3];\n\t\tm[4] += n[4];\n\t\tm[5] += n[5];\n\t\tm[6] += n[6];\n\t\tm[7] += n[7];\n\t\tm[8] += n[8];\n\t\tm[9] += n[9];\n\n\t\treturn *this;\n\t}\n\n\tfloat m[10];\n};\n\n\nclass Simplify {\npublic:\n\tSimplify(const ExtTriangleMesh &srcMesh) {\n\t\tconst u_int vertCount = srcMesh.GetTotalVertexCount();\n\t\tconst u_int triCount = srcMesh.GetTotalTriangleCount();\n\t\tconst Point *verts = srcMesh.GetVertices();\n\t\tconst Triangle *tris = srcMesh.GetTriangles();\n\n\t\tvertices.resize(vertCount);\n\t\tfor (u_int i = 0; i < vertCount; ++i)\n\t\t\tvertices[i].p = verts[i];\n\t\t\n\t\tif (srcMesh.HasNormals()) {\n\t\t\tconst Normal *norms = srcMesh.GetNormals();\n\t\t\tfor (u_int i = 0; i < vertCount; ++i)\n\t\t\t\tvertices[i].norm = norms[i];\n\n\t\t\thasNormals = true;\n\t\t} else\n\t\t\thasNormals = false;\n\t\t\n\t\tif (srcMesh.HasUVs(0)) {\n\t\t\tconst UV *uvs = srcMesh.GetUVs(0);\n\t\t\tfor (u_int i = 0; i < vertCount; ++i)\n\t\t\t\tvertices[i].uv = uvs[i];\n\n\t\t\thasUVs = true;\n\t\t} else\n\t\t\thasUVs = false;\n\t\t\n\t\tif (srcMesh.HasColors(0)) {\n\t\t\tconst Spectrum *cols = srcMesh.GetColors(0);\n\t\t\tfor (u_int i = 0; i < vertCount; ++i)\n\t\t\t\tvertices[i].col = cols[i];\n\n\t\t\thasColors = true;\n\t\t} else\n\t\t\thasColors = false;\n\n\t\tif (srcMesh.HasAlphas(0)) {\n\t\t\tconst float *alphas = srcMesh.GetAlphas(0);\n\t\t\tfor (u_int i = 0; i < vertCount; ++i)\n\t\t\t\tvertices[i].alpha = alphas[i];\n\n\t\t\thasAlphas = true;\n\t\t} else\n\t\t\thasAlphas = false;\n\n\t\ttriangles.resize(triCount);\n\t\tfor (u_int i = 0; i < triCount; ++i) {\n\t\t\ttriangles[i].v[0] = tris[i].v[0];\n\t\t\ttriangles[i].v[1] = tris[i].v[1];\n\t\t\ttriangles[i].v[2] = tris[i].v[2];\n\t\t}\n\t}\n\n\t~Simplify() {\n\t}\n\t\n\tExtTriangleMesh *GetExtMesh() const {\n\t\tconst u_int vertCount = vertices.size();\n\t\tconst u_int triCount = triangles.size();\n\n\t\tPoint *newVertices = ExtTriangleMesh::AllocVerticesBuffer(vertCount);\t\t\n\t\tfor (u_int i = 0; i < vertCount; ++i)\n\t\t\tnewVertices[i] = vertices[i].p;\n\t\t\n\t\tNormal *newNorms = nullptr;\n\t\tif (hasNormals) {\n\t\t\tnewNorms = new Normal[vertCount];\n\t\t\tfor (u_int i = 0; i < vertCount; ++i)\n\t\t\t\tnewNorms[i] = vertices[i].norm;\n\t\t}\n\t\t\n\t\tUV *newUVs = nullptr;\n\t\tif (hasUVs) {\n\t\t\tnewUVs = new UV[vertCount];\n\t\t\tfor (u_int i = 0; i < vertCount; ++i)\n\t\t\t\tnewUVs[i] = vertices[i].uv;\n\t\t}\n\n\t\tSpectrum *newCols = nullptr;\n\t\tif (hasColors) {\n\t\t\tnewCols = new Spectrum[vertCount];\n\t\t\tfor (u_int i = 0; i < vertCount; ++i)\n\t\t\t\tnewCols[i] = vertices[i].col;\n\t\t}\n\t\t\n\t\tfloat *newAlphas = nullptr;\n\t\tif (hasAlphas) {\n\t\t\tnewAlphas = new float[vertCount];\n\t\t\tfor (u_int i = 0; i < vertCount; ++i)\n\t\t\t\tnewAlphas[i] = vertices[i].alpha;\n\t\t}\n\t\t\n\t\tTriangle *newTris = ExtTriangleMesh::AllocTrianglesBuffer(triCount);\n\t\tfor (u_int i = 0; i < triCount; ++i) {\n\t\t\tassert (triangles[i].v[0] < vertCount);\n\t\t\tnewTris[i].v[0] = triangles[i].v[0];\n\n\t\t\tassert (triangles[i].v[1] < vertCount);\n\t\t\tnewTris[i].v[1] = triangles[i].v[1];\n\n\t\t\tassert (triangles[i].v[2] < vertCount);\n\t\t\tnewTris[i].v[2] = triangles[i].v[2];\n\t\t}\n\t\t\n\t\treturn new ExtTriangleMesh(vertCount, triCount, newVertices, newTris, newNorms,\n\t\t\t\tnewUVs, newCols, newAlphas);\n\t}\n\n\tvoid Decimate(const float targetTriangleCount, const Camera *scnCamera,\n\t\t\tconst float screenSize, const bool border) {\n\t\tpreserveBorder = border;\n\t\tcamera = scnCamera;\n\t\tedgeScreenSize = screenSize;\n\n\t\t// Work on 10% of all triangles for each iteration\n\t\tmaxCandidateQueueSize = Max(64u, Floor2UInt(triangles.size() * .1f));\n\n\t\t// Init\n\t\tfor (u_int i = 0; i < triangles.size(); ++i)\n\t\t\ttriangles[i].deleted = false;\n\n\t\t// Main iteration loop\n\t\tconst u_int startTriangleCount = triangles.size();\n\t\tdeletedTriangles = 0;\n\t\tvector<bool> deleted0, deleted1;\n\t\tfor (u_int iteration = 0; iteration < 64; ++iteration) {\n\t\t\tif (startTriangleCount - deletedTriangles <= targetTriangleCount)\n\t\t\t\tbreak;\n\n\t\t\tconst u_int initialdeletedTriangles = deletedTriangles;\n\n\t\t\t// Update mesh constantly\n\t\t\tUpdateMesh(iteration);\n\n\t\t\t// Remove vertices & mark deleted triangles\n\t\t\tfor (u_int i = 0; i < candidateList.size(); ++i)\n\t\t\t\tCollapseEdge(candidateList[i].tid, candidateList[i].tvertex, deleted0, deleted1);\n\n\t\t\tconst u_int iterationDeletedTriangles = deletedTriangles - initialdeletedTriangles;\n\t\t\tSDL_LOG(\"Simplify iteration \" << iteration << \" (\" << candidateList.size() << \" edge candidates, deleted \" << iterationDeletedTriangles << \"/\" << deletedTriangles << \" of \" << startTriangleCount << \" triangles)\");\n\t\t\tif (iterationDeletedTriangles == 0)\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// Clean up mesh\n\t\tCompactMesh();\n\t}\n\nprivate:\n\tstruct SimplifyTriangle {\n\t\tu_int v[3];\n\t\tNormal geometryN;\n\t\tfloat err[3];\n\t\tbool deleted, dirty;\n\t};\n\n\tstruct SimplifyVertex {\n\t\tPoint p;\n\t\tNormal norm;\n\t\tUV uv;\n\t\tSpectrum col;\n\t\tfloat alpha;\n\n\t\tu_int tstart, tcount;\n\t\tSymetricMatrix q;\n\n\t\tbool border;\n\t};\n\n\tstruct SimplifyRef {\n\t\tu_int tid, tvertex;\n\t};\n\t\n\tclass SimplifyRefErrCompare {\n\tpublic:\n\t\tSimplifyRefErrCompare(const Simplify &s) : simplify(s) { }\n\n\t\tbool operator()(const SimplifyRef &sr1, const SimplifyRef &sr2) const {\n\t\t\treturn simplify.triangles[sr1.tid].err[sr1.tvertex] < simplify.triangles[sr2.tid].err[sr2.tvertex];\n\t\t}\n\n\tprivate:\n\t\tconst Simplify &simplify;\n\t};\n\n\tvector<SimplifyTriangle> triangles;\n\tvector<SimplifyVertex> vertices;\n\tvector<SimplifyRef> refs;\n\n\tconst Camera *camera;\n\tfloat edgeScreenSize;\n\n\tu_int maxCandidateQueueSize;\n\tvector<SimplifyRef> candidateList;\n\n\tu_int deletedTriangles;\n\tbool hasNormals, hasUVs, hasColors, hasAlphas, preserveBorder;\n\n\tbool CollapseEdge(const u_int trinagleIndex, const u_int startVertexIndex,\n\t\t\tvector<bool> &deleted0, vector<bool> &deleted1) {\n\t\tSimplifyTriangle &t = triangles[trinagleIndex];\n\n\t\tif (t.deleted)\n\t\t\treturn false;\n\t\tif (t.dirty)\n\t\t\treturn false;\n\n\t\tconst u_int i0 = t.v[startVertexIndex];\n\t\tSimplifyVertex &v0 = vertices[i0];\n\n\t\tconst u_int i1 = t.v[(startVertexIndex + 1) % 3];\n\t\tSimplifyVertex &v1 = vertices[i1];\n\n\t\t// Border check\n\t\tif (v0.border != v1.border)\n\t\t\treturn false;\n\n\t\t// Compute vertex to collapse to\n\t\tPoint p;\n\t\tCalculateCollapseError(i0, i1, &p);\n\n\t\t// true/false if the triangles referencing the vertex are deleted\n\t\tdeleted0.resize(v0.tcount);\n\t\tdeleted1.resize(v1.tcount);\n\n\t\t// Don't remove if flipped\n\t\tif (Flipped(p, i0, i1, &deleted0))\n\t\t\treturn false;\n\t\tif (Flipped(p, i1, i0, &deleted1))\n\t\t\treturn false;\n\n\t\t// Save original vertex information\n\t\tconst Point triPoint0 = vertices[t.v[0]].p;\n\t\tconst Point triPoint1 = vertices[t.v[1]].p;\n\t\tconst Point triPoint2 = vertices[t.v[2]].p;\n\n\t\tconst Normal triNorm0 = vertices[t.v[0]].norm;\n\t\tconst Normal triNorm1 = vertices[t.v[1]].norm;\n\t\tconst Normal triNorm2 = vertices[t.v[2]].norm;\n\n\t\tconst UV triUV0 = vertices[t.v[0]].uv;\n\t\tconst UV triUV1 = vertices[t.v[1]].uv;\n\t\tconst UV triUV2 = vertices[t.v[2]].uv;\n\n\t\tconst Spectrum triCol0 = vertices[t.v[0]].col;\n\t\tconst Spectrum triCol1 = vertices[t.v[1]].col;\n\t\tconst Spectrum triCol2 = vertices[t.v[2]].col;\n\n\t\tconst float triAlpha0 = vertices[t.v[0]].alpha;\n\t\tconst float triAlpha1 = vertices[t.v[1]].alpha;\n\t\tconst float triAlpha2 = vertices[t.v[2]].alpha;\n\n\t\t// Not flipped, so remove edge\n\t\tv0.p = p;\t\t\n\t\tv0.q = v1.q + v0.q;\n\n\t\t// Interpolate other vertex attributes\n\t\tfloat b1, b2;\n\t\tif (Triangle::GetBaryCoords(\n\t\t\t\ttriPoint0,\n\t\t\t\ttriPoint1,\n\t\t\t\ttriPoint2,\n\t\t\t\tp, &b1, &b2)) {\n\t\t\tconst float b0 = 1.f - b1 - b2;\n\n\t\t\tif (hasNormals)\n\t\t\t\tv0.norm = Normalize(b0 * triNorm0 + b1 * triNorm1 + b2 * triNorm2);\n\t\t\tif (hasUVs)\n\t\t\t\tv0.uv = b0 * triUV0 + b1 * triUV1 + b2 * triUV2;\n\t\t\tif (hasColors)\n\t\t\t\tv0.col = b0 * triCol0 + b1 * triCol1 + b2 * triCol2;\n\t\t\tif (hasAlphas)\n\t\t\t\tv0.alpha = b0 * triAlpha0 + b1 * triAlpha1 + b2 * triAlpha2;\n\t\t} else {\n\t\t\t// Must be a malformed triangle\n\t\t\tif (hasNormals)\n\t\t\t\tv0.norm = triNorm0;\n\t\t\tif (hasUVs)\n\t\t\t\tv0.uv = triUV0;\n\t\t\tif (hasColors)\n\t\t\t\tv0.col = triCol0;\n\t\t\tif (hasAlphas)\n\t\t\t\tv0.alpha = triAlpha0;\t\t\t\n\t\t}\n\n\t\tconst u_int tstart = refs.size();\n\n\t\tUpdateTriangles(i0, v0, deleted0);\n\t\tUpdateTriangles(i0, v1, deleted1);\n\n\t\tconst u_int tcount = refs.size() - tstart;\n\n\t\tif (tcount <= v0.tcount) {\n\t\t\t// Save ram\n\t\t\tif (tcount)\n\t\t\t\tcopy(&refs[tstart], &refs[tstart] + tcount, &refs[v0.tstart]);\n\t\t} else\n\t\t\t// Append\n\t\t\tv0.tstart = tstart;\n\n\t\tv0.tcount = tcount;\n\n\t\treturn true;\n\t}\n\n\t// Check if a triangle flips when this edge is removed\n\tbool Flipped(const Point &p, const u_int i0, const u_int i1,\n\t\t\tvector<bool> *deleted = nullptr) const {\n\t\tconst SimplifyVertex &v0 = vertices[i0];\n\n\t\tfor (u_int k = 0; k < v0.tcount; ++k) {\n\t\t\tconst SimplifyTriangle &t = triangles[refs[v0.tstart + k].tid];\n\n\t\t\tif (t.deleted)\n\t\t\t\tcontinue;\n\n\t\t\tconst u_int s = refs[v0.tstart + k].tvertex;\n\t\t\tconst u_int id1 = t.v[(s + 1) % 3];\n\t\t\tconst u_int id2 = t.v[(s + 2) % 3];\n\n\t\t\t// Delete ?\n\t\t\tif (id1 == i1 || id2 == i1) {\n\t\t\t\tif (deleted)\n\t\t\t\t\t(*deleted)[k] = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Check if the triangle is too narrow\n\t\t\tconst Vector d1 = Normalize(vertices[id1].p - p);\n\t\t\tconst Vector d2 = Normalize(vertices[id2].p - p);\n\t\t\tif (AbsDot(d1, d2) > .999f)\n\t\t\t\treturn true;\n\n\t\t\t// Check if the Normal is changing side\n\t\t\tconst Normal geometryN(Normalize(Cross(d1, d2)));\n\t\t\tif (Dot(geometryN, t.geometryN) < .2f)\n\t\t\t\treturn true;\n\n\t\t\tif (deleted)\n\t\t\t\t(*deleted)[k] = false;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t// Update triangle connections and edge error after a edge is collapsed\n\tvoid UpdateTriangles(const u_int i0, const SimplifyVertex &v,\n\t\t\tconst  vector<bool> &deleted) {\n\t\tfor (u_int k = 0; k < v.tcount; ++k) {\n\t\t\tconst SimplifyRef &r = refs[v.tstart + k];\n\t\t\tSimplifyTriangle &t = triangles[r.tid];\n\n\t\t\tif (t.deleted)\n\t\t\t\tcontinue;\n\n\t\t\tif (deleted[k]) {\n\t\t\t\tt.deleted = true;\n\t\t\t\tdeletedTriangles++;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tt.v[r.tvertex] = i0;\n\t\t\tt.dirty = true;\n\t\t\tUpdateTriangleError(t);\n\n\t\t\trefs.push_back(r);\n\t\t}\n\t}\n\n\t// Compact triangles, compute edge error and build reference list\n\tvoid UpdateMesh(const u_int iteration) {\n\t\tif (iteration > 0) {\n\t\t\t// Compact triangles\n\t\t\tint dst = 0;\n\t\t\tfor (u_int i = 0; i < triangles.size(); ++i)\n\t\t\t\tif (!triangles[i].deleted)\n\t\t\t\t\ttriangles[dst++] = triangles[i];\n\n\t\t\ttriangles.resize(dst);\n\t\t}\n\n\t\t// Init Quadrics by Plane & Edge Errors\n\t\t//\n\t\t// Required at the beginning (iteration == 0)\n\t\t//\n\t\tif (iteration == 0) {\n\t\t\tfor (u_int i = 0; i < vertices.size(); ++i)\n\t\t\t\tvertices[i].q = SymetricMatrix(0.0);\n\n\t\t\tfor (u_int i = 0; i < triangles.size(); ++i) {\n\t\t\t\tSimplifyTriangle &t = triangles[i];\n\n\t\t\t\tSimplifyVertex &v0 = vertices[t.v[0]];\n\t\t\t\tSimplifyVertex &v1 = vertices[t.v[1]];\n\t\t\t\tSimplifyVertex &v2 = vertices[t.v[2]];\n\n\t\t\t\tconst Normal geometryN(Normalize(Cross(v1.p - v0.p, v2.p - v0.p)));\n\t\t\t\tt.geometryN = geometryN;\n\n\t\t\t\t// It doesn't matter what vertex I use here because the triangle\n\t\t\t\t// plane will pass for all 3\n\t\t\t\tconst SymetricMatrix sm(geometryN.x, geometryN.y, geometryN.z,\n\t\t\t\t\t\t-Dot(Vector(geometryN), Vector(v0.p)));\n\t\t\t\tv0.q += sm;\n\t\t\t\tv1.q += sm;\n\t\t\t\tv2.q += sm;\n\t\t\t}\n\n\t\t\tfor (u_int i = 0; i < triangles.size(); ++i) {\n\t\t\t\t// Calc Edge Error\n\t\t\t\tSimplifyTriangle &t = triangles[i];\n\n\t\t\t\tUpdateTriangleError(t);\n\t\t\t}\n\t\t}\n\n\t\t// Init Reference ID list\n\t\tfor (u_int i = 0; i < vertices.size(); ++i) {\n\t\t\tvertices[i].tstart = 0;\n\t\t\tvertices[i].tcount = 0;\n\t\t}\n\n\t\tfor (u_int i = 0; i < triangles.size(); ++i) {\n\t\t\tSimplifyTriangle &t = triangles[i];\n\n\t\t\tvertices[t.v[0]].tcount++;\n\t\t\tvertices[t.v[1]].tcount++;\n\t\t\tvertices[t.v[2]].tcount++;\n\t\t}\n\n\t\tu_int tstart = 0;\n\t\tfor (u_int i = 0; i < vertices.size(); ++i) {\n\t\t\tSimplifyVertex &v = vertices[i];\n\n\t\t\tv.tstart = tstart;\n\t\t\ttstart += v.tcount;\n\t\t\tv.tcount = 0;\n\t\t}\n\n\t\t// Write References\n\t\trefs.resize(triangles.size() * 3);\n\t\tfor (u_int i = 0; i < triangles.size(); ++i) {\n\t\t\tSimplifyTriangle &t = triangles[i];\n\n\t\t\tfor (u_int j = 0; j < 3; ++j) {\n\t\t\t\tSimplifyVertex &v = vertices[t.v[j]];\n\n\t\t\t\trefs[v.tstart + v.tcount].tid = i;\n\t\t\t\trefs[v.tstart + v.tcount].tvertex = j;\n\n\t\t\t\tv.tcount++;\n\t\t\t}\n\t\t}\n\n\t\t// Identify boundary : vertices[].border=0,1\n\t\t//\n\t\t// Required at the beginning (iteration == 0)\n\t\tif (iteration == 0) {\n\t\t\tfor (u_int i = 0; i < vertices.size(); ++i)\n\t\t\t\tvertices[i].border = false;\n\n\t\t\tvector<u_int> vcount, vids;\n\t\t\tfor (u_int i = 0; i < vertices.size(); ++i) {\n\t\t\t\tSimplifyVertex &v = vertices[i];\n\t\t\t\tvcount.clear();\n\t\t\t\tvids.clear();\n\n\t\t\t\tfor (u_int j = 0; j < v.tcount; ++j) {\n\t\t\t\t\tint k = refs[v.tstart + j].tid;\n\t\t\t\t\tSimplifyTriangle &t = triangles[k];\n\n\t\t\t\t\tfor (u_int k = 0; k < 3; ++k) {\n\t\t\t\t\t\tu_int ofs = 0;\n\t\t\t\t\t\tu_int id = t.v[k];\n\n\t\t\t\t\t\twhile (ofs < vcount.size()) {\n\t\t\t\t\t\t\tif (vids[ofs] == id)\n\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\tofs++;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (ofs == vcount.size()) {\n\t\t\t\t\t\t\tvcount.push_back(1);\n\t\t\t\t\t\t\tvids.push_back(id);\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tvcount[ofs]++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfor (u_int j = 0; j < vcount.size(); ++j) {\n\t\t\t\t\tif (vcount[j] == 1)\n\t\t\t\t\t\tvertices[vids[j]].border = true;\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t}\n\n\t\t// Build the edge candidate queue\n\t\tpriority_queue<SimplifyRef, vector<SimplifyRef>, SimplifyRefErrCompare>\n\t\t\tcandidateQueue{ SimplifyRefErrCompare(*this) };\n\t\tfor (u_int i = 0; i < triangles.size(); ++i) {\n\t\t\tconst SimplifyTriangle &t = triangles[i];\n\n\t\t\t// Look for the (valid) triangle vertex with the minimum error\n\t\t\tu_int minErrorIndex = NULL_INDEX;\n\t\t\tfloat minError = numeric_limits<float>::infinity();\n\t\t\tfor (u_int j = 0; j < 3; ++j) {\n\t\t\t\tconst u_int i0 = t.v[j];\n\t\t\t\tSimplifyVertex &v0 = vertices[i0];\n\n\t\t\t\tconst u_int i1 = t.v[(j + 1) % 3];\n\t\t\t\tSimplifyVertex &v1 = vertices[i1];\n\n\t\t\t\t// Border check\n\t\t\t\tif (preserveBorder) {\n\t\t\t\t\tif (v0.border && v1.border)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\tif (v0.border != v1.border)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Compute vertex to collapse to\n\t\t\t\tPoint p;\n\t\t\t\tCalculateCollapseError(i0, i1, &p);\n\n\t\t\t\t// Don't remove if flipped\n\t\t\t\tif (Flipped(p, i0, i1))\n\t\t\t\t\tcontinue;\n\t\t\t\tif (Flipped(p, i1, i0))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (t.err[j] < minError) {\n\t\t\t\t\tminErrorIndex = j;\n\t\t\t\t\tminError = t.err[j];\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (minErrorIndex == NULL_INDEX)\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tif (candidateQueue.size() < maxCandidateQueueSize) {\n\t\t\t\tcandidateQueue.push(SimplifyRef{i, minErrorIndex});\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst SimplifyRef &top = candidateQueue.top();\n\t\t\tif (t.err[minErrorIndex] < triangles[top.tid].err[top.tvertex]) {\n\t\t\t\tcandidateQueue.pop();\n\t\t\t\tcandidateQueue.push(SimplifyRef{i, minErrorIndex});\n\t\t\t}\n\t\t}\n\t\n\t\tif (candidateQueue.size() > 0) {\n\t\t\tcandidateList.resize(candidateQueue.size());\n\t\t\tfor (u_int i = candidateList.size() - 1;;) {\n\t\t\t\tcandidateList[i] = candidateQueue.top();\n\t\t\t\tcandidateQueue.pop();\n\n\t\t\t\tif (i == 0)\n\t\t\t\t\tbreak;\n\t\t\t\t--i;\n\t\t\t}\n\n\t\t\t/*for (u_int i = 0; i < Min<u_int>(candidateList.size(), 10u); ++i) {\n\t\t\t\tconst SimplifyTriangle &t = triangles[candidateList[i].tid];\n\n\t\t\t\tSDL_LOG(\"#\" << i << \" Min. error: \" << fixed << setprecision(10) << t.err[candidateList[i].tvertex] << \" (triangle \" << candidateList[i].tid << \")\");\n\n\t\t\t\tconst u_int i0 = t.v[candidateList[i].tvertex];\n\t\t\t\tSimplifyVertex &v0 = vertices[i0];\n\t\t\t\n\t\t\t\tconst u_int i1 = t.v[(candidateList[i].tvertex + 1) % 3];\n\t\t\t\tSimplifyVertex &v1 = vertices[i1];\n\n\t\t\t\tSDL_LOG(\"#\" << i << \" Collapse screen error scale: \" << fixed << setprecision(10) <<  CalculateCollapseScreenErrorScale(v0.p, v1.p));\n\t\t\t\tSDL_LOG(\"#\" << i << \" Triangle \" << candidateList[i].tid << \" border: \" <<\n\t\t\t\t\t\tvertices[t.v[candidateList[i].tvertex]].border << \" \" <<\n\t\t\t\t\t\tvertices[t.v[(candidateList[i].tvertex + 1) % 3]].border);\n\t\t\t}*/\n\t\t\t\n\t\t\t/*ExtTriangleMeshBuilder meshBuilder;\n\t\t\tfor (u_int i = 0; i < candidateList.size(); ++i) {\n\t\t\t\tconst SimplifyTriangle &t = triangles[candidateList[i].tid];\n\n\t\t\t\tconst u_int index = meshBuilder.vertices.size();\n\t\t\t\tmeshBuilder.AddVertex(vertices[t.v[candidateList[i].tvertex]].p);\n\t\t\t\tmeshBuilder.AddVertex(vertices[t.v[(candidateList[i].tvertex + 1) % 3]].p);\n\t\t\t\tmeshBuilder.AddVertex(vertices[t.v[(candidateList[i].tvertex + 2) % 3]].p);\n\n\t\t\t\tmeshBuilder.AddTriangle(Triangle(index, index + 1, index +2));\n\t\t\t}\n\t\t\tExtTriangleMesh *debugMesh = meshBuilder.GetExtTriangleMesh();\n\t\t\tdebugMesh->Save(\"debug-candidates.ply\");\n\t\t\tdelete debugMesh;*/\n\t\t}\n\n\t\t// Clear dirty flag\n\t\tfor (u_int i = 0; i < triangles.size(); ++i)\n\t\t\ttriangles[i].dirty = false;\n\t}\n\n\t// Finally compact mesh before exiting\n\tvoid CompactMesh() {\n\t\tu_int dst = 0;\n\n\t\tfor (u_int i = 0; i < vertices.size(); ++i)\n\t\t\tvertices[i].tcount = 0;\n\n\t\tfor (u_int i = 0; i < triangles.size(); ++i) {\n\t\t\tif (!triangles[i].deleted) {\n\t\t\t\tconst SimplifyTriangle &t = triangles[i];\n\t\t\t\ttriangles[dst++] = t;\n\n\t\t\t\tvertices[t.v[0]].tcount = 1;\n\t\t\t\tvertices[t.v[1]].tcount = 1;\n\t\t\t\tvertices[t.v[2]].tcount = 1;\n\t\t\t}\n\t\t}\n\t\ttriangles.resize(dst);\n\n\t\tdst = 0;\n\t\tfor (u_int i = 0; i < vertices.size(); ++i) {\n\t\t\tif (vertices[i].tcount) {\n\t\t\t\tvertices[i].tstart = dst;\n\t\t\t\tvertices[dst].p = vertices[i].p;\n\n\t\t\t\tvertices[dst].norm = vertices[i].norm;\n\t\t\t\tvertices[dst].uv = vertices[i].uv;\n\t\t\t\tvertices[dst].col = vertices[i].col;\n\t\t\t\tvertices[dst].alpha = vertices[i].alpha;\n\n\t\t\t\tdst++;\n\t\t\t}\n\t\t}\n\n\t\tfor (u_int i = 0; i < triangles.size(); ++i) {\n\t\t\tSimplifyTriangle &t = triangles[i];\n\n\t\t\tt.v[0] = vertices[t.v[0]].tstart;\n\t\t\tt.v[1] = vertices[t.v[1]].tstart;\n\t\t\tt.v[2] = vertices[t.v[2]].tstart;\n\t\t}\n\t\tvertices.resize(dst);\n\t}\n\n\t// Error between vertex and Quadric\n\tfloat VertexError(const SymetricMatrix &q, const float x, const float y, const float z) const {\n\t\treturn q[0] * x * x + 2.f * q[1] * x * y + 2.f * q[2] * x * z + 2.f * q[3] * x +\n\t\t\t\tq[4] * y * y + 2.f * q[5] * y * z + 2.f * q[6] * y +\n\t\t\t\tq[7] * z * z + 2.f * q[8] * z +\n\t\t\t\tq[9];\n\t}\n\n\t// Error for one edge\n\tfloat CalculateCollapseError(const u_int v1Index, const u_int v2Index,\n\t\t\tPoint *pResult = nullptr) const {\n\t\tconst SymetricMatrix q = vertices[v1Index].q + vertices[v2Index].q;\n\n\t\t// Compute interpolated vertex\n\t\tconst Point &p1 = vertices[v1Index].p;\n\t\tconst Point &p2 = vertices[v2Index].p;\n\t\tconst Point p3 = (p1 + p2) / 2;\n\n\t\t// Error can be negative, I add 1 to have screenErrorScale can than\n\t\t// work as expected\n\t\tconst float error1 = VertexError(q, p1.x, p1.y, p1.z) + 1.f;\n\t\tconst float error2 = VertexError(q, p2.x, p2.y, p2.z) + 1.f;\n\t\tconst float error3 = VertexError(q, p3.x, p3.y, p3.z) + 1.f;\n\n\t\tfloat error;\n\t\tif (preserveBorder && vertices[v1Index].border) {\n\t\t\terror = error1;\n\t\t\tif (pResult)\n\t\t\t\t*pResult = p1;\n\t\t} else if (preserveBorder && vertices[v2Index].border) {\n\t\t\terror = error2;\n\t\t\tif (pResult)\n\t\t\t\t*pResult = p2;\n\t\t} else {\n\t\t\terror = Min(error1, Min(error2, error3));\n\n\t\t\tif (pResult) {\n\t\t\t\tif (error1 == error)\n\t\t\t\t\t*pResult = p1;\n\t\t\t\tif (error2 == error)\n\t\t\t\t\t*pResult = p2;\n\t\t\t\tif (error3 == error)\n\t\t\t\t\t*pResult = p3;\n\t\t\t}\n\t\t}\n\n\t\t// Adding 1.0 because error have negative values\n\t\treturn Max(error + 1.f, 0.f);\n\t}\n\n\tfloat CalculateCollapseScreenErrorScale(const Point &v0, const Point &v1) const {\n\t\tif (edgeScreenSize > 0.f) {\n\t\t\tconst float notVisibleScale = .5f;\n\n\t\t\tfloat v0x, v0y;\n\t\t\tif (!camera->GetSamplePosition(v0, &v0x, &v0y) ||\n\t\t\t\t\t!IsValid(v0x) || !IsValid(v0y))\n\t\t\t\treturn notVisibleScale;\n\n\t\t\t// Normalize\n\t\t\tv0x /= camera->filmWidth;\n\t\t\tv0y /= camera->filmHeight;\n\n\t\t\tfloat v1x, v1y;\n\t\t\tif (!camera->GetSamplePosition(v1, &v1x, &v1y) ||\n\t\t\t\t\t!IsValid(v1x) || !IsValid(v1y))\n\t\t\t\treturn notVisibleScale;\n\n\t\t\t// Normalize\n\t\t\tv1x /= camera->filmWidth;\n\t\t\tv1y /= camera->filmHeight;\n\n\t\t\tconst float edge = sqrtf(Sqr(v0x - v1x) + Sqr(v0y - v1y));\n\t\t\tif (edge == 0.f)\n\t\t\t\treturn notVisibleScale;\n\n\t\t\treturn Max(edge / edgeScreenSize, notVisibleScale);\n\t\t} else\n\t\t\treturn 1.f;\n\t}\n\t\n\tvoid UpdateTriangleError(SimplifyTriangle &t) const {\n\t\tt.err[0] = CalculateCollapseError(t.v[0], t.v[1]) *\n\t\t\t\tCalculateCollapseScreenErrorScale(vertices[t.v[0]].p, vertices[t.v[1]].p);\n\n\t\tt.err[1] = CalculateCollapseError(t.v[1], t.v[2]) *\n\t\t\t\tCalculateCollapseScreenErrorScale(vertices[t.v[1]].p, vertices[t.v[2]].p);\n\n\t\tt.err[2] = CalculateCollapseError(t.v[2], t.v[0]) *\n\t\t\t\tCalculateCollapseScreenErrorScale(vertices[t.v[2]].p, vertices[t.v[0]].p);\n\t}\n};\n\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n//------------------------------------------------------------------------------\n\nSimplifyShape::SimplifyShape(const Camera *camera, ExtTriangleMesh *srcMesh,\n\t\tconst float target, const float edgeScreenSize, const bool preserveBorder) {\n\tSDL_LOG(\"Simplify shape \" << srcMesh->GetName() << \" with target \" << target);\n\n\tif ((edgeScreenSize > 0.f) && !camera)\n\t\tthrow runtime_error(\"The scene camera must be defined in order to enable simplify edgescreensize option\");\n\n\tconst float startTime = WallClockTime();\n\n\tconst u_int targetCount = Max(1u, Floor2UInt(srcMesh->GetTotalTriangleCount() * target));\n\n\t/*srcMesh->Save(\"debug-start.ply\");\n\tExtTriangleMesh *debugMeshStart = ScreenProjection(*camera, *srcMesh);\n\tdebugMeshStart->Save(\"debug-start-proj.ply\");\n\tdelete debugMeshStart;*/\n\n\tSimplify simplify(*srcMesh);\n\tsimplify.Decimate(targetCount, camera, edgeScreenSize, preserveBorder);\n\tmesh = simplify.GetExtMesh();\n\n\t/*srcMesh->Save(\"debug-end.ply\");\n\tExtTriangleMesh *debugMeshEnd = ScreenProjection(*camera, *mesh);\n\tdebugMeshEnd->Save(\"debug-end-proj.ply\");\n\tdelete debugMeshEnd;*/\n\n\tSDL_LOG(\"Subdivided shape from \" << srcMesh->GetTotalTriangleCount() << \" to \" << mesh->GetTotalTriangleCount() << \" faces\");\n\n\t// For some debugging\n\t//mesh->Save(\"debug.ply\");\n\t\n\tconst float endTime = WallClockTime();\n\tSDL_LOG(\"Simplify time: \" << (boost::format(\"%.3f\") % (endTime - startTime)) << \"secs\");\n}\n\nSimplifyShape::~SimplifyShape() {\n\tif (!refined)\n\t\tdelete mesh;\n}\n\nExtTriangleMesh *SimplifyShape::RefineImpl(const Scene *scene) {\n\treturn mesh;\n}\n", "meta": {"hexsha": "cd855d950301f579ffcbed3d9bb4f76022bb8cbe", "size": 25276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/slg/shapes/simplify.cpp", "max_stars_repo_name": "OmidGhotbi/LuxCore", "max_stars_repo_head_hexsha": "e83fb6bf2e2c0254e3c769ffc8e5546eb71f576a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/slg/shapes/simplify.cpp", "max_issues_repo_name": "OmidGhotbi/LuxCore", "max_issues_repo_head_hexsha": "e83fb6bf2e2c0254e3c769ffc8e5546eb71f576a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/slg/shapes/simplify.cpp", "max_forks_repo_name": "OmidGhotbi/LuxCore", "max_forks_repo_head_hexsha": "e83fb6bf2e2c0254e3c769ffc8e5546eb71f576a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3254054054, "max_line_length": 216, "alphanum_fraction": 0.6026665612, "num_tokens": 7918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4284490321354407}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_FUNCTION_GENERIC_COSH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_GENERIC_COSH_HPP_INCLUDED\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/constant/maxlog.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/simd/abs.hpp>\n#include <boost/simd/function/simd/average.hpp>\n#include <boost/simd/function/simd/exp.hpp>\n#include <boost/simd/function/simd/if_else.hpp>\n#include <boost/simd/function/simd/is_greater.hpp>\n#include <boost/simd/function/simd/rec.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( cosh_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_<bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      //////////////////////////////////////////////////////////////////////////////\n      // if x = abs(a0) according x < Threshold e =  exp(x) or exp(x/2) is\n      // respectively computed\n      // *  in the first case cosh (e+rec(e))/2\n      // *  in the second     cosh is (e/2)*e (avoiding undue overflow)\n      // Threshold is Maxlog - Log_2 defined in Maxshlog\n      //////////////////////////////////////////////////////////////////////////////\n      A0 x = bs::abs(a0);\n      auto test1 = (x > Maxlog<A0>()-Log_2<A0>());\n      A0 fac = if_else(test1, Half<A0>(), One<A0>());\n      A0 tmp = exp(x*fac);\n      A0 tmp1 = Half<A0>()*tmp;\n      return if_else(test1, tmp1*tmp, bs::average(tmp, rec(tmp)));\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "7dffbaba016680941fd3ec534f13eb5ca839f8d9", "size": 2211, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/cosh.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/generic/function/cosh.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/generic/function/cosh.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4745762712, "max_line_length": 100, "alphanum_fraction": 0.5427408412, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4284490321354407}}
{"text": "/** \n * This is a simple unoptimized code to evaluate some low-order dual diagrams in FK model\n * input : \n *  --order : order of the diagram\n *  --beta : order of the diagram\n *  --kpts : order of the diagram\n *  --U : order of the diagram\n * output:\n *  - dual self-energy \"sigma_wk.dat\"\n *  - cut of dual self-energy at first Matsubara freq\n *  - k-dependence of dual bubbles (summer over Matsubara freqs). \n */\n\n#include <boost/program_options.hpp>\n#include <gftools.hpp>\n#include <Eigen/Core>\n\nnamespace po = boost::program_options;\nusing namespace gftools;\n\nint main(int argc, char *argv[])\n{\n    // parse command line options - define beta, kpts and U\n    po::options_description desc(\"FK DF 2d\"); \n    desc.add_options()\n        (\"order,n\", po::value<int>()->default_value(2), \"order of diagrams\")\n        (\"beta\", po::value<double>()->default_value(1), \"inverse temperature\")\n        (\"kpts\", po::value<int>()->default_value(16), \"number of points in one dimension of k-space\")\n        (\"U\", po::value<double>()->default_value(8), \"interaction strength\")\n        (\"help\", \"produce help message\");\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    //po::notify(vm);\n    if (vm.count(\"help\")) { std::cout << desc << std::endl; exit(0); }\n    int diagram_order = vm[\"order\"].as<int>(); \n    int kpts = vm[\"kpts\"].as<int>();\n    // we will use diagram_order as amount of iterations in vertices. 1 iteration = 2nd order, etc. \n    diagram_order-=(diagram_order>0);\n    double beta = vm[\"beta\"].as<double>(); \n    double U = vm[\"U\"].as<double>(); \n    static constexpr int NDim = 2; // work in 2 dimensions\n\n    // Calc starts here\n    std::cout << \"Atomic limit of FK model in 2 dimensions using DF approximation\" << std::endl;\n    double T = 1.0/beta;\n    std::cout << \"beta = \" << beta << std::endl;\n    std::cout << \"T = \" << T << std::endl;\n    int totalkpts = std::pow(kpts, NDim);\n    std::cout << \"kmesh : \" << kpts << \" points \" << std::endl; \n    std::cout << \"total pts in BZ = \" << totalkpts << std::endl; \n\n    // typedef for F(w, w') type objects \n    typedef grid_object<std::complex<double>, fmatsubara_grid, fmatsubara_grid> vertex_type;\n    // G(w)\n    typedef grid_object<std::complex<double>, fmatsubara_grid> gw_type;\n    // G(w, kx, ky)\n    typedef grid_object<std::complex<double>, fmatsubara_grid, kmesh, kmesh> gk_type;\n    // e(kx, ky)\n    typedef grid_object<std::complex<double>, kmesh, kmesh> disp_type;\n    // typedef for matrices\n    typedef Eigen::MatrixXcd matrix_type; \n\n    // Prepare evaluation grids\n    fmatsubara_grid fgrid(-20,20,beta);\n    // Hybridization function (atomic limit)\n    gw_type delta(fgrid);\n    delta.fill([&](std::complex<double> w){return double(2*NDim) / w; });\n    // Local gf (atomic limit)\n    gw_type gw(fgrid);\n    gw.fill([&](std::complex<double> w){return 0.5/(w - U/2.0) + 0.5/(w + U/2.0);});\n    // Local vertex (atomic limit)\n    vertex_type gamma4(std::make_tuple(fgrid, fgrid));\n    typename gw_type::function_type Lambda = [U](std::complex<double> w){return 1. - U*U/4./w/w;};\n    gamma4.fill([&](std::complex<double> w1, std::complex<double> w2){ \n            return beta * U * U / 4.0 * double(1 - tools::is_float_equal(w1, w2) ) * (1. - U*U/4./w1/w1) * (1. - U*U/4./w2/w2); \n        });\n\n    // k-dependent input\n    // define a mesh in Brilloin zone (BZ)\n    kmesh kgrid(kpts);\n    // lattice dispersion\n    disp_type eps(std::forward_as_tuple(kgrid, kgrid));\n    eps.fill([&](double kx, double ky){return -2*(cos(kx) + cos(ky));});\n    // lattice gf in dmft\n    gk_type glat_dmft(std::forward_as_tuple(fgrid, kgrid, kgrid));\n    glat_dmft.fill([&](fmatsubara_grid::point w, kmesh::point kx, kmesh::point ky){return 1.0 / (1.0 / gw(w) + delta(w) - eps(kx, ky));});\n    // bare dual df\n    gk_type gd0(glat_dmft.grids());\n    gd0.fill([&](fmatsubara_grid::point w, kmesh::point kx, kmesh::point ky){return glat_dmft(w, kx, ky) - gw(w);});\n\n    double prec = 1e-5;\n    // check - local part of gd0 should be zero (check is approximate, as atomic limit is used)\n    for (auto w : fgrid.points()) { \n        double diff0 = std::abs(gd0[w].sum()) / double(totalkpts);\n        if (diff0 > prec) std::cerr << \"Problem encountered - w = \" << w << \": dual gd0 has a non-zero local part : \" <<  diff0 << \" > \" << prec << std::endl;\n        }\n    \n    // define full vertex (will be evaluated below)\n    vertex_type full_vertex(gamma4);\n    // make a matrix from the vertex\n    matrix_type gamma4_matrix = gamma4.data().as_matrix();\n    matrix_type full_vertex_matrix(gamma4_matrix);\n\n    // check that we are consistent - 2 frequency grids are the same\n    if (gd0.template grid<0>() != fgrid) throw std::logic_error(\"matsubara grid mismatch\");\n    \n    std::cout << \"kmesh : \" << kgrid << std::endl;\n    // Initalize dual self-energy on the same grids as gd0\n    gk_type sigma_dual(gd0.grids());\n    sigma_dual = 0.0;\n    disp_type bare_bubbles(kgrid,kgrid);\n\n    // now loop through the BZ (no irreducible part optimization)\n    for (kmesh::point q1 : kgrid.points()) { \n        for (kmesh::point q2 : kgrid.points()) { \n            std::cout << \"[\" << q1.index()*kpts + q2.index()+1 << \"/\" << totalkpts <<  \"]; q = {\" <<  q1.value() << \" \" << q2.value() << \"}\" << std::endl;\n            // Evaluate -T \\sum_k G_{w,k} G_{w,k+q}\n            // Shift dual g in k-space and make no frequency shift. \n            // note : this operation is typically optimized via an fft. \n            gk_type gd0_shift = gd0.shift(std::make_tuple(0.0,q1,q2)); \n            // obtain a bubble \n            gk_type bubble_wk = -T * gd0 * gd0_shift;\n            // perform sum over k    \n            gw_type dual_bubble(fgrid);\n            for (auto w : fgrid.points()) { dual_bubble[w] = bubble_wk[w].sum() / double(totalkpts); }\n            // save the bubble for output \n            bare_bubbles(q1, q2) = dual_bubble.sum();\n            // construct a diagonal matrix (in frequency space from the bubble)\n            matrix_type dual_bubble_matrix = dual_bubble.data().as_diagonal_matrix(); \n            // refresh vertex\n            full_vertex_matrix = gamma4_matrix;\n            // IMPORTANT : Evaluate dual diagram\n            for (int n=0; n<diagram_order; n++) \n                full_vertex_matrix= gamma4_matrix * dual_bubble_matrix * full_vertex_matrix; \n            // update self-energy\n            for (auto w : fgrid.points())\n                sigma_dual[w.index()] += T* full_vertex_matrix(w.index(), w.index()) * gd0_shift[w.index()] / double(totalkpts);\n        }\n    }\n    // output\n    // save bare bubbles\n    bare_bubbles.savetxt(\"db0.dat\");\n    // save sigma\n    sigma_dual.savetxt(\"sigma_wk.dat\");\n    // save sigma at first matsubara\n    auto w0 = fgrid.find_nearest(I*PI/beta);\n    disp_type sigma_w0(std::forward_as_tuple(kgrid,kgrid),sigma_dual[w0]);\n    sigma_w0.savetxt(\"sigma_w0.dat\");\n\n    // save lattice self-energy\n    gk_type sigma_lat(sigma_dual.grids());\n    for (fmatsubara_grid::point w : fgrid.points()) { \n        sigma_lat[w] = sigma_dual[w] / (sigma_dual[w] * gw[w] + 1.0);\n        }\n    sigma_lat.savetxt(\"sigma_lattice.dat\");\n    sigma_w0.data() = sigma_lat[w0];\n    sigma_w0.savetxt(\"sigma_lattice_w0.dat\");\n}\n\n", "meta": {"hexsha": "59a25040c5692a5080249fffd80a0103b283c724", "size": 7247, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/df_fk_2d.cpp", "max_stars_repo_name": "hmenke/gftools", "max_stars_repo_head_hexsha": "d79810dd705b8e2efa802321382ebb7658e5f452", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T01:30:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-18T14:29:32.000Z", "max_issues_repo_path": "example/df_fk_2d.cpp", "max_issues_repo_name": "hmenke/gftools", "max_issues_repo_head_hexsha": "d79810dd705b8e2efa802321382ebb7658e5f452", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-04-01T12:38:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T21:21:38.000Z", "max_forks_repo_path": "example/df_fk_2d.cpp", "max_forks_repo_name": "hmenke/gftools", "max_forks_repo_head_hexsha": "d79810dd705b8e2efa802321382ebb7658e5f452", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-05-11T16:45:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-11T04:44:44.000Z", "avg_line_length": 45.29375, "max_line_length": 158, "alphanum_fraction": 0.6129432869, "num_tokens": 2088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.428323253612575}}
{"text": "/**\n * Created by beck on 24/4/2018.\n * Extended Kalman Filter for 16 states, with quaternion for the orientation\n * Fused A3 flight controller IMU with UWB x and y position\n * With IMU raw reading comes in 400Hz and UWB raw reading in 50Hz\n */\n#include <iostream>\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <sensor_msgs/Imu.h>\n#include <std_msgs/String.h>\n#include <nav_msgs/Odometry.h>\n#include <uwb_msgs/uwb.h>\n#include <Eigen/Eigen>\n#include <queue>\n\n// #define INIT_Q_R_BY_MEASUREMENT\n\nusing namespace std;\nusing namespace Eigen;\nros::Publisher odom_pub;\nstring imu_topic, uwb_topic, publisher_topic;\ndouble uwb_weight, acc_angle_weight, mag_weight;\ndouble acc_weight, gyro_weight, acc_bias_weight, gyro_bias_weight;\n\n/**\n * Define states:\n *      x = [rotation_quaternion, position, velocity, bias_accel, bias_gyro]\n * Define inputs:\n *      u = [omg, accel], all imu measurement\n * Define noises:\n *      n = [n_gyro, n_acc, n_bias_acc, n_bias_gyro]\n */\nVectorXd x(16);                             // state\nMatrixXd P = MatrixXd::Zero(15, 15);        // covariance\nMatrixXd Q = MatrixXd::Identity(12, 12);    // prediction noise covariance\nMatrixXd R = MatrixXd::Identity(6, 6);      // observation noise covariance\n\n// buffers to save imu and uwb reading for time synchronization\nqueue <sensor_msgs::Imu::ConstPtr> imu_buf;\nqueue <nav_msgs::Odometry::ConstPtr> odom_buf;\nqueue <Matrix<double, 16, 1>> x_history;\nqueue <Matrix<double, 15, 15>> P_history;\n\n// previous propagated time\ndouble t_prev;\n\n// Initialization and covariance estimation\n// UWB wait until imu is initialized\nconst int IMU_INIT_COUNT = 40;\nint imu_count = 0;\nVector3d g_init = Vector3d::Zero();\nVector3d G = Vector3d::Zero();\nVector3d accl_init_buf[IMU_INIT_COUNT];\nVector3d gyro_init_buf[IMU_INIT_COUNT];\nqueue<double> uwb_init_buf_w;\nqueue<double> uwb_init_buf_x;\nqueue<double> uwb_init_buf_y;\ndouble theta_bias = 0;\nbool imu_initialized = false;\nbool odom_initialized = false;\n\n// TODO: Calibrate sensor position\n// imu frame to world frame rotation matrix, {[0, 0, -1], pi/2}\n//Matrix3d imu_R_world = Quaterniond(sqrt(1/2), 0, 0, -sqrt(1/2)).toRotationMatrix();\nMatrix3d imu_R_world;\n\n// Matrix3d init_robot_pose = Quaterniond(sqrt(1/2), 0, 0, -sqrt(1/2)).toRotationMatrix();\n// Matrix3d init_robot_pose = Quaterniond(0, 0, 0, 1).toRotationMatrix();\n\nvoid pub_odom_ekf(std_msgs::Header header) {\n    nav_msgs::Odometry odom;\n    odom.header.stamp = header.stamp;\n    odom.header.frame_id = \"world\";\n    odom.pose.pose.orientation.w = x(0);\n    odom.pose.pose.orientation.x = x(1);\n    odom.pose.pose.orientation.y = x(2);\n    odom.pose.pose.orientation.z = x(3);\n    odom.pose.pose.position.x = x(4);\n    odom.pose.pose.position.y = x(5);\n    odom.pose.pose.position.z = x(6);\n    odom.twist.twist.linear.x = x(7);\n    odom.twist.twist.linear.y = x(8);\n    odom.twist.twist.linear.z = x(9);\n\n    odom_pub.publish(odom);\n}\n\n// imu propagate in the world frame\nvoid propagate(const sensor_msgs::Imu::ConstPtr &imu_msg) {\n    double cur_t = imu_msg->header.stamp.toSec();\n    double dt = cur_t - t_prev;\n    Vector3d w_raw;\n    Vector3d a_raw;\n    a_raw(0) = imu_msg->linear_acceleration.x;\n    a_raw(1) = imu_msg->linear_acceleration.y;\n    a_raw(2) = imu_msg->linear_acceleration.z;\n    w_raw(0) = imu_msg->angular_velocity.x;\n    w_raw(1) = imu_msg->angular_velocity.y;\n    w_raw(2) = imu_msg->angular_velocity.z;\n\n    Vector3d a = a_raw - x.segment<3>(10);\n    Vector3d omg = w_raw - x.segment<3>(13);\n    Vector3d domg = 0.5 * dt * omg;\n\n    // propagate the state with quaternion calculus\n    Quaterniond dR(sqrt(1 - domg.squaredNorm()), domg(0), domg(1), domg(2));\n    Quaterniond Rt(x(0), x(1), x(2), x(3));\n    Quaterniond R_t = (Rt * dR).normalized();\n\n    x.segment<4>(0) << R_t.w(), R_t.x(), R_t.y(), R_t.z();\n    x.segment<3>(4) += x.segment<3>(7) * dt + (Rt * (a - G)) * 0.5 * dt * dt;\n    x.segment<3>(7) += (Rt * (a - G)) * dt;\n\n    // propagate the covariance with skew-symmetric matrix\n    MatrixXd I = MatrixXd::Identity(3, 3);\n    Matrix3d R_omg, R_a;\n    R_omg << 0, -omg(2), omg(1),\n            omg(2), 0, -omg(0),\n            -omg(1), omg(0), 0;\n    R_a << 0, -a(2), a(1),\n            a(2), 0, -a(0),\n            -a(1), a(0), 0;\n\n    MatrixXd A = MatrixXd::Zero(15, 15);\n    A.block<3, 3>(0, 0) = -R_omg;\n    A.block<3, 3>(0, 12)= -1 * I;\n    A.block<3, 3>(3, 6) = I;\n    A.block<3, 3>(6, 0) = (-1 * Rt.toRotationMatrix()) * R_a;\n    A.block<3, 3>(6, 9) = (-1 * Rt.toRotationMatrix());\n    // cout << \"DEBUG:: propagate A\" << endl << A << endl;\n\n    MatrixXd U = MatrixXd::Zero(15, 12);\n    U.block<3, 3>(0, 0) = -1 * I;\n    U.block<3, 3>(6, 3) = -1 * Rt.toRotationMatrix();\n    U.block<3, 3>(9, 6) = I;\n    U.block<3, 3>(12, 9)= I;\n    // cout << \"DEBUG:: propagate U\" << endl << U << endl;\n\n    MatrixXd F, V;\n    F = MatrixXd::Identity(15, 15) + dt * A;\n    V = dt * U;\n\n    P = F * P * F.transpose() + V * Q * V.transpose();\n    // cout << \"DEBUG:: P after propagate\" << endl << P << endl;\n\n    t_prev = cur_t;\n}\n\n// Loosely coupled update in world frame, fusing the global position of UWB and angle\nvoid update_loosely(const uwb_msgs::uwb &msg,\n                    const sensor_msgs::Imu::ConstPtr &imu_msg) {\n    Quaterniond q_g(1, 0, 0, 0);\n/*\n    if (imu_msg != nullptr && &imu_msg != NULL) {\n        Vector3d a_raw(imu_msg->linear_acceleration.x,\n                       imu_msg->linear_acceleration.y,\n                       imu_msg->linear_acceleration.z);\n        Vector3d a_norm = a_raw.normalized();\n        // cout << \"DEBUG:: raw accel\" << endl << a_norm << endl;\n        Vector3d q_vec(a_norm(1), -a_norm(0), 0);\n        Vector3d q_norm = q_vec.normalized();\n        q_g.w() = acos(a_norm(2));\n        q_g.x() = q_norm(0);\n        q_g.y() = q_norm(1);\n        q_g.z() = q_norm(2);\n    }\n*/\n\n    double theta_z = msg.pos_theta - theta_bias;\n    VectorXd T(3);\n    T(0) = msg.pos_x;\n    T(1) = msg.pos_y;\n    T(2) = 0;\n\n    MatrixXd C = MatrixXd::Zero(6, 15);\n    C.block<3, 3>(0, 0) = Matrix3d::Identity();\n//    C(2, 2) = 1;\n    C.block<3, 3>(3, 3) = Matrix3d::Identity();\n\n    MatrixXd K(15, 6);\n    K = P * C.transpose() * (C * P * C.transpose() + R).inverse();\n//    cout << \"DEBUG:: update K\" << endl << K << endl;\n\n    // Matrix3d uwb_R_world = AngleAxisd(theta_z, Vector3d::UnitZ()) * imu_R_world * q_g.toRotationMatrix();\n\tMatrix3d uwb_R_world = AngleAxisd(theta_z, Vector3d::UnitZ()) * q_g.toRotationMatrix();\n//    cout << \"DEBUG:: measured angle\" << endl << uwb_R_world << endl;\n\n    VectorXd r(6);\n    Quaterniond qm(uwb_R_world);\n    Quaterniond q = Quaterniond(x(0), x(1), x(2), x(3));\n    Quaterniond dq = q.conjugate() * qm; // Hamilton style\n    r.head(3) = 2 * dq.vec();\n    r.tail(3) = T - x.segment<3>(4);\n    VectorXd _r = K * r;\n    Vector3d dw(0.5 * _r(0), 0.5 * _r(1), 0.5 * _r(2));\n    Quaterniond _dq = Quaterniond(1, dw(0), dw(1), dw(2)).normalized();\n    q = q * _dq;\n\n    x(0) = q.w();\n    x(1) = q.x();\n    x(2) = q.y();\n    x(3) = q.z();\n    x.segment<12>(4) += _r.segment<12>(3);\n    P = P - K * C * P;\n//    cout << \"DEBUG:: P after update\" << endl << P << endl;\n}\n\n/**\n * Initialize, handle and save imu messages\n * @param imu_msg\n */\nvoid imu_callback(const sensor_msgs::Imu::ConstPtr &imu_msg) {\n    if (!imu_initialized && imu_count < IMU_INIT_COUNT) {\n        accl_init_buf[imu_count](0) = imu_msg->linear_acceleration.x;\n        accl_init_buf[imu_count](1) = imu_msg->linear_acceleration.y;\n        accl_init_buf[imu_count](2) = imu_msg->linear_acceleration.z;\n        gyro_init_buf[imu_count](0) = imu_msg->angular_velocity.x;\n        gyro_init_buf[imu_count](1) = imu_msg->angular_velocity.y;\n        gyro_init_buf[imu_count](2) = imu_msg->angular_velocity.z;\n        g_init(0) += accl_init_buf[imu_count](0);\n        g_init(1) += accl_init_buf[imu_count](1);\n        g_init(2) += accl_init_buf[imu_count](2);\n        imu_count++;\n    } else if (!imu_initialized && imu_count == IMU_INIT_COUNT) {\n#ifdef INIT_Q_R_BY_MEASUREMENT\n        double accl_mean[3] = {0};\n        double gyro_mean[3] = {0};\n        double accl_cova[3] = {0};\n        double gyro_cova[3] = {0};\n        for (int i = 0; i < IMU_INIT_COUNT; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                accl_mean[j] += accl_init_buf[i](j);\n                gyro_mean[j] += gyro_init_buf[i](j);\n                accl_cova[j] += pow(accl_init_buf[i](j), 2);\n                gyro_cova[j] += pow(gyro_init_buf[i](j), 2);\n            }\n        }\n        for (int j = 0; j < 3; ++j) {\n            accl_mean[j] /= IMU_INIT_COUNT;\n            gyro_mean[j] /= IMU_INIT_COUNT;\n            accl_cova[j] /= IMU_INIT_COUNT;\n            gyro_cova[j] /= IMU_INIT_COUNT;\n\n            // Q omg first, Q acceleration second\n            Q(j, j)         = gyro_cova[j] - pow(gyro_mean[j], 2);\n            Q(j + 3, j + 3) = accl_cova[j] - pow(accl_mean[j], 2);\n        }\n        // Add the ratio\n        Q.block<3, 3>(0, 0) = gyro_weight * Q.block<3, 3>(0, 0);\n        Q.block<3, 3>(3, 3) = acc_weight  * Q.block<3, 3>(3, 3);\n\n        // Hardcoded initial IMU bias_a, bias_g\n        Q.block<3, 3>(6, 6) = acc_bias_weight  * Q.block<3, 3>(6, 6);     // IMU bias_a, bias_g\n        Q.block<3, 3>(9, 9) = gyro_bias_weight * Q.block<3, 3>(9, 9);     // IMU bias_a, bias_g\n        cout << \"DEBUG: measured Q\" << endl << Q << endl;\n#else\n        // Initialize the covariance\n        Q.block<3, 3>(0, 0) = gyro_weight * Q.block<3, 3>(0, 0);     // IMU omg, accel\n        Q.block<3, 3>(3, 3) = acc_weight  * Q.block<3, 3>(3, 3);     // IMU omg, accel\n        Q.block<3, 3>(6, 6) = acc_bias_weight  * Q.block<3, 3>(6, 6);     // IMU bias_a, bias_g\n        Q.block<3, 3>(9, 9) = gyro_bias_weight * Q.block<3, 3>(9, 9);     // IMU bias_a, bias_g\n        cout << \"DEBUG: hardcoded Q\" << endl << Q << endl;\n#endif\n        g_init /= IMU_INIT_COUNT;\n\n        // Initialize the state and the gravity\n        x.setZero();\n        // Quaterniond init_pose(init_robot_pose);\n        Quaterniond init_pose(imu_R_world);\n        x(0) = init_pose.w();\n        x(1) = init_pose.x();\n        x(2) = init_pose.y();\n        x(3) = init_pose.z();\n\n        G = imu_R_world * g_init;\n        cout << \"DEBUG: init state x\" << x(0) << x(1) << x(2) << x(3) << endl;\n\t\tcout << \"DEBUG: measured G\" << endl << G << endl;\n        t_prev = imu_msg->header.stamp.toSec();\n        imu_initialized = true;\n    } else if (imu_initialized && odom_initialized) {\n        propagate(imu_msg);\n        pub_odom_ekf(imu_msg->header);\n\n        imu_buf.push(imu_msg);\n        x_history.push(x);\n        P_history.push(P);\n    }\n}\n\n/**\n * initialize, handle and save uwb messages\n * Also doing time synchronization\n * @param uwb msg\n */\nvoid odom_callback(const uwb_msgs::uwb &msg) {\n    if (!imu_initialized && !odom_initialized) {\n        uwb_init_buf_x.push(msg.pos_x);\n        uwb_init_buf_y.push(msg.pos_y);\n        uwb_init_buf_w.push(msg.pos_theta);\n    } else if (imu_initialized && !odom_initialized) {\n#ifdef INIT_Q_R_BY_MEASUREMENT\n        double uwb_mean[3] = {0, 0, 0};\n        double uwb_cova[3] = {0, 0, 0};\n        int uwb_count = (int) uwb_init_buf_x.size();\n        for (int i = 0; i < uwb_count; ++i) {\n            uwb_mean[0] += uwb_init_buf_x.front();\n            uwb_mean[1] += uwb_init_buf_y.front();\n            uwb_mean[2] += uwb_init_buf_w.front();\n            uwb_cova[0] += pow(uwb_init_buf_x.front(), 2);\n            uwb_cova[1] += pow(uwb_init_buf_y.front(), 2);\n            uwb_cova[2] += pow(uwb_init_buf_w.front(), 2);\n            uwb_init_buf_x.pop();\n            uwb_init_buf_y.pop();\n            uwb_init_buf_w.pop();\n        }\n        uwb_mean[0] /= uwb_count;\n        uwb_mean[1] /= uwb_count;\n        uwb_mean[2] /= uwb_count;\n        uwb_cova[0] /= uwb_count;\n        uwb_cova[1] /= uwb_count;\n        uwb_cova[2] /= uwb_count;\n\n        // Initialize the position and bias\n        x(4) = uwb_mean[0];\n        x(5) = uwb_mean[1];\n        x(6) = 0;\n        theta_bias = uwb_mean[2];\n\n        // Initialize the covariance R\n        R.topLeftCorner(2, 2) = acc_angle_weight * R.topLeftCorner(2, 2);\n        R(2, 2) = (uwb_cova[2] - pow(uwb_mean[2], 2)) * mag_weight;\n        R(3, 3) = (uwb_cova[0] - pow(uwb_mean[0], 2)) * uwb_weight;\n        R(4, 4) = (uwb_cova[1] - pow(uwb_mean[1], 2)) * uwb_weight;\n        R(5, 5) = 0.01 * R(5, 5) * uwb_weight;\n        cout << \"DEBUG: measured R\" << endl << R << endl;\n#else\n        x(4) = msg.pos_x;\n        x(5) = msg.pos_y;\n        x(6) = 0;\n\t\t\n\t\tx(0) = 1;\n\t\tx(1) = 0;\n\t\tx(2) = 0;\n\t\tx(3) = 0;\n\n        theta_bias = msg.pos_theta;\n        R.topLeftCorner(2, 2) = acc_angle_weight * R.topLeftCorner(2, 2);\n        R(2, 2) = mag_weight * R(2, 2);\n        R.bottomRightCorner(3, 3) = uwb_weight * R.bottomRightCorner(3, 3); // Measure x, y\n        cout << \"DEBUG: hardcoded R\" << endl << R << endl;\n#endif\n        t_prev = msg.header.stamp.toSec();\n        odom_initialized = true;\n    } else {\n        // throw the state and covariance history before the uwb time\n        while (!imu_buf.empty() && imu_buf.front()->header.stamp < msg.header.stamp) {\n            // trace the time backwards to imu time\n            t_prev = imu_buf.front()->header.stamp.toSec();\n//            ROS_INFO(\"throw state with time: %f\", t_prev);\n            imu_buf.pop();\n            x_history.pop();\n            P_history.pop();\n        }\n        // If x_history is empty then the uwb reading is the same as the last imu reading\n        // And the current estimated x could be used.\n        // If not, use the oldest time in the x_history\n        if (!x_history.empty()) {\n            x = x_history.front();\n            P = P_history.front();\n            t_prev = imu_buf.front()->header.stamp.toSec();\n            imu_buf.pop();\n            x_history.pop();\n            P_history.pop();\n        }\n\n//        ROS_INFO(\"update state with time: %f\", msg.header.stamp.toSec());\n        if (imu_buf.empty()){\n            update_loosely(msg, NULL);\n        } else {\n            update_loosely(msg, imu_buf.front());\n        }\n\n        // clean the x and P history since the new update corrects the previous propagate\n        while (!x_history.empty()) x_history.pop();\n        while (!P_history.empty()) P_history.pop();\n\n        queue <sensor_msgs::Imu::ConstPtr> temp_imu_buf;\n        while (!imu_buf.empty()) {\n//            ROS_INFO(\"propagate state with time: %f\", imu_buf.front()->header.stamp.toSec());\n            propagate(imu_buf.front());\n            temp_imu_buf.push(imu_buf.front());\n            x_history.push(x);\n            P_history.push(P);\n            imu_buf.pop();\n        }\n        std::swap(imu_buf, temp_imu_buf);\n    }\n}\n\nint main(int argc, char **argv) {\n    ros::init(argc, argv, \"ekf_quaternion_16states\");\n    ros::NodeHandle n(\"~\");\n\n    // sleep for 10 seconds in order to launch both sensors\n    ros::Duration(10).sleep();\n\n    n.param(\"imu_topic\", imu_topic, string(\"/dji_sdk/imu\"));\n    n.param(\"uwb_topic\", uwb_topic, string(\"/uwb_driver/info\"));\n    n.param(\"publisher_topic\", publisher_topic, string(\"/ekf_odom\"));\n    n.param(\"uwb_weight\", uwb_weight, 0.01);\n    n.param(\"acc_angle_weight\", acc_angle_weight, 0.01);\n    n.param(\"magnetometer_weight\" , mag_weight, 0.01);\n    n.param(\"accelerometer_weight\", acc_weight, 0.01);\n    n.param(\"gyroscope_weight\", gyro_weight, 0.01);\n    n.param(\"acc_bias_weight\" , acc_bias_weight, 0.01);\n    n.param(\"gyro_bias_weight\", gyro_bias_weight, 0.01);\n\n    ros::Subscriber s1 = n.subscribe(imu_topic, 100, imu_callback);\n    ros::Subscriber s2 = n.subscribe(uwb_topic, 10, odom_callback);\n    odom_pub = n.advertise<nav_msgs::Odometry>(publisher_topic, 100);\n\n    // Running the odometry in 400Hz as the IMU update\n    ros::Rate r(400);\n\n//    Rimu = Quaterniond(0.7071, 0, 0, -0.7071).toRotationMatrix();\n    imu_R_world << 1, 0, 0,\n            0, 1,  0,\n            0, 0,  1;\n\n    cout << \"imu_R_world\" << endl << imu_R_world << endl;\n\n    ros::spin();\n}\n\n/**\n *  0   q_w     body frame --> world frame\n *  1   q_x\n *  2   q_y\n *  3   q_z\n *  4   p_x     world frame\n *  5   p_y\n *  6   p_z\n *  7   v_x     world frame\n *  8   v_y\n *  9   v_z\n *  10  ba_x    accel_bias      body frame\n *  11  ba_y\n *  12  ba_z\n *  13  bw_x    gyro_bias       body frame\n *  14  bw_y\n *  15  bw_z\n */\n", "meta": {"hexsha": "c392f9e0ba29ab474adf329da2a6f95aa09e9263", "size": 16286, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3_estimator/history/ekf_uwb/src/ekf_uwb_node_quaternion.cpp", "max_stars_repo_name": "huying163/ros_environment", "max_stars_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-01-30T11:40:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T05:52:47.000Z", "max_issues_repo_path": "3_estimator/history/ekf_uwb/src/ekf_uwb_node_quaternion.cpp", "max_issues_repo_name": "huying163/ros_environment", "max_issues_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3_estimator/history/ekf_uwb/src/ekf_uwb_node_quaternion.cpp", "max_forks_repo_name": "huying163/ros_environment", "max_forks_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-23T08:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T08:14:57.000Z", "avg_line_length": 35.872246696, "max_line_length": 108, "alphanum_fraction": 0.5815424291, "num_tokens": 5208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.4283057240157963}}
{"text": "// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef NETKET_ADAMAX_HPP\n#define NETKET_ADAMAX_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iostream>\n#include \"abstract_optimizer.hpp\"\n\nnamespace netket {\n\nclass AdaMax : public AbstractOptimizer {\n  int npar_;\n\n  double alpha_;\n  double beta1_;\n  double beta2_;\n\n  Eigen::VectorXd ut_;\n  Eigen::VectorXd mt_;\n\n  double niter_;\n  double niter_reset_;\n\n  double epscut_;\n\n public:\n  explicit AdaMax(double alpha = 0.001, double beta1 = 0.9,\n                  double beta2 = 0.999, double epscut = 1.0e-7)\n      : alpha_(alpha), beta1_(beta1), beta2_(beta2), epscut_(epscut) {\n    npar_ = -1;\n    niter_ = 0;\n    niter_reset_ = -1;\n\n    PrintParameters();\n  }\n\n  void PrintParameters() {\n    InfoMessage() << \"Adamax optimizer initialized with these parameters :\"\n                  << std::endl;\n    InfoMessage() << \"Alpha = \" << alpha_ << std::endl;\n    InfoMessage() << \"Beta1 = \" << beta1_ << std::endl;\n    InfoMessage() << \"Beta2 = \" << beta2_ << std::endl;\n    InfoMessage() << \"Epscut = \" << epscut_ << std::endl;\n  }\n\n  void Init(int npar) override {\n    npar_ = npar;\n    ut_.setZero(npar_);\n    mt_.setZero(npar_);\n\n    niter_ = 0;\n  }\n\n  void Update(const Eigen::VectorXd &grad,\n              Eigen::Ref<Eigen::VectorXd> pars) override {\n    assert(npar_ > 0);\n\n    mt_ = beta1_ * mt_ + (1. - beta1_) * grad;\n\n    for (int i = 0; i < npar_; i++) {\n      ut_(i) = std::max(std::max(std::abs(grad(i)), beta2_ * ut_(i)), epscut_);\n    }\n    niter_ += 1.;\n    if (niter_reset_ > 0) {\n      if (niter_ > niter_reset_) {\n        niter_ = 1;\n      }\n    }\n\n    double eta = alpha_ / (1. - std::pow(beta1_, niter_));\n    for (int i = 0; i < npar_; i++) {\n      pars(i) -= eta * mt_(i) / ut_(i);\n    }\n  }\n\n  void Reset() override {\n    ut_ = Eigen::VectorXd::Zero(npar_);\n    mt_ = Eigen::VectorXd::Zero(npar_);\n    niter_ = 0;\n  }\n\n  void SetResetEvery(double niter_reset) { niter_reset_ = niter_reset; }\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "7c71fad70b318887fab3111d26e55fcfa02547c4", "size": 2642, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Sources/Optimizer/ada_max.hpp", "max_stars_repo_name": "tvieijra/netket", "max_stars_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-29T02:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T18:52:33.000Z", "max_issues_repo_path": "Sources/Optimizer/ada_max.hpp", "max_issues_repo_name": "tvieijra/netket", "max_issues_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T11:12:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T17:04:41.000Z", "max_forks_repo_path": "Sources/Optimizer/ada_max.hpp", "max_forks_repo_name": "tvieijra/netket", "max_forks_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-02T07:29:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-04T21:55:21.000Z", "avg_line_length": 25.1619047619, "max_line_length": 79, "alphanum_fraction": 0.6271763815, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.428199225613622}}
{"text": "// Copyright (C) 2015 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/bundle_adjustment/optimize_relative_position_with_known_rotation.h\"\n\n#include <ceres/rotation.h>\n#include <Eigen/Core>\n#include <glog/logging.h>\n#include <algorithm>\n#include <vector>\n\n#include \"theia/math/util.h\"\n#include \"theia/matching/feature_correspondence.h\"\n#include \"theia/sfm/triangulation/triangulation.h\"\n\nnamespace theia {\nnamespace {\n\n// Creates the constraint matrix such that ||A * t|| is minimized, where A is\n// R_i * f_i x R_j * f_j. Given known rotations, we can solve for the\n// relative translation from this constraint matrix.\nvoid CreateConstraintMatrix(\n    const std::vector<FeatureCorrespondence>& correspondences,\n    const Eigen::Vector3d& rotation1,\n    const Eigen::Vector3d& rotation2,\n    Eigen::MatrixXd* constraint_matrix) {\n  constraint_matrix->resize(3, correspondences.size());\n\n  Eigen::Matrix3d rotation_matrix1;\n  ceres::AngleAxisToRotationMatrix(\n      rotation1.data(), ceres::ColumnMajorAdapter3x3(rotation_matrix1.data()));\n  Eigen::Matrix3d rotation_matrix2;\n  ceres::AngleAxisToRotationMatrix(\n      rotation2.data(), ceres::ColumnMajorAdapter3x3(rotation_matrix2.data()));\n\n  for (int i = 0; i < correspondences.size(); i++) {\n    const Eigen::Vector3d rotated_feature1 =\n        rotation_matrix1.transpose() *\n        correspondences[i].feature1.point_.homogeneous();\n    const Eigen::Vector3d rotated_feature2 =\n        rotation_matrix2.transpose() *\n        correspondences[i].feature2.point_.homogeneous();\n\n    constraint_matrix->col(i) =\n        rotated_feature2.cross(rotated_feature1).transpose() *\n        rotation_matrix1.transpose();\n  }\n}\n\n// Determines if the majority of the points are in front of the cameras. This is\n// useful for determining the sign of the relative position. Returns true if\n// more than 50% of correspondences are in front of both cameras and false\n// otherwise.\nbool MajorityOfPointsInFrontOfCameras(\n    const std::vector<FeatureCorrespondence>& correspondences,\n    const Eigen::Vector3d& rotation1,\n    const Eigen::Vector3d& rotation2,\n    const Eigen::Vector3d& relative_position) {\n  // Compose the relative rotation.\n  Eigen::Matrix3d rotation_matrix1, rotation_matrix2;\n  ceres::AngleAxisToRotationMatrix(\n      rotation1.data(), ceres::ColumnMajorAdapter3x3(rotation_matrix1.data()));\n  ceres::AngleAxisToRotationMatrix(\n      rotation2.data(), ceres::ColumnMajorAdapter3x3(rotation_matrix2.data()));\n  const Eigen::Matrix3d relative_rotation_matrix =\n      rotation_matrix2 * rotation_matrix1.transpose();\n\n  // Tests all points for cheirality.\n  int num_points_in_front_of_cameras = 0;\n  for (const FeatureCorrespondence& match : correspondences) {\n    if (IsTriangulatedPointInFrontOfCameras(match,\n                                            relative_rotation_matrix,\n                                            relative_position)) {\n      ++num_points_in_front_of_cameras;\n    }\n  }\n\n  return num_points_in_front_of_cameras > (correspondences.size() / 2);\n}\n\n}  // namespace\n\n// Given known camera rotations and feature correspondences, this method solves\n// for the relative translation that optimizes the epipolar error\n// f_i * E * f_j^t = 0.\nbool OptimizeRelativePositionWithKnownRotation(\n    const std::vector<FeatureCorrespondence>& correspondences,\n    const Eigen::Vector3d& rotation1,\n    const Eigen::Vector3d& rotation2,\n    Eigen::Vector3d* relative_position) {\n  CHECK_NOTNULL(relative_position);\n\n  // Set the initial relative position to random. This helps avoid a bad local\n  // minima that is achieved from poor initialization.\n  relative_position->setRandom();\n\n  // Constants used for the IRLS solving.\n  const double eps = 1e-5;\n  const int kMaxIterations = 100;\n  const int kMaxInnerIterations = 10;\n  const double kMinWeight = 1e-7;\n\n  // Create the constraint matrix from the known correspondences and rotations.\n  Eigen::MatrixXd constraint_matrix;\n  CreateConstraintMatrix(correspondences,\n                         rotation1,\n                         rotation2,\n                         &constraint_matrix);\n\n  // Initialize the weighting terms for each correspondence.\n  Eigen::VectorXd weights(correspondences.size());\n  weights.setConstant(1.0);\n\n  // Solve for the relative positions using a robust IRLS.\n  double cost = 0;\n  int num_inner_iterations = 0;\n  for (int i = 0;\n       i < kMaxIterations && num_inner_iterations < kMaxInnerIterations;\n       i++) {\n    // Limit the minimum weight at kMinWeight.\n    weights = (weights.array() < kMinWeight).select(kMinWeight, weights);\n\n    // Apply the weights to the constraint matrix.\n    const Eigen::Matrix3d lhs = constraint_matrix *\n                                weights.asDiagonal().inverse() *\n                                constraint_matrix.transpose();\n\n    // Solve for the relative position which is the null vector of the weighted\n    // constraints.\n    const Eigen::Vector3d new_relative_position =\n        lhs.jacobiSvd(Eigen::ComputeFullU).matrixU().rightCols<1>();\n\n    // Update the weights based on the current errors.\n    weights =\n        (new_relative_position.transpose() * constraint_matrix).array().abs();\n\n    // Compute the new cost.\n    const double new_cost = weights.sum();\n\n    // Check for convergence.\n    const double delta = std::max(std::abs(cost - new_cost),\n                                  1 - new_relative_position.squaredNorm());\n\n    // If we have good convergence, attempt an inner iteration.\n    if (delta <= eps) {\n      ++num_inner_iterations;\n    } else {\n      num_inner_iterations = 0;\n    }\n\n    cost = new_cost;\n    *relative_position = new_relative_position;\n  }\n\n  // The position solver above does not consider the sign of the relative\n  // position. We can determine the sign by choosing the sign that puts the most\n  // points in front of the camera.\n  if (!MajorityOfPointsInFrontOfCameras(correspondences,\n                                        rotation1,\n                                        rotation2,\n                                        *relative_position)) {\n    *relative_position *= -1.0;\n  }\n\n  return true;\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "13ae23236abbdf0e2fc1e0716a131103e28b44d4", "size": 7906, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/bundle_adjustment/optimize_relative_position_with_known_rotation.cc", "max_stars_repo_name": "Sergej91/TheiaSfM", "max_stars_repo_head_hexsha": "e603e16888456c3e565a2c197fa9f8643c176175", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/theia/sfm/bundle_adjustment/optimize_relative_position_with_known_rotation.cc", "max_issues_repo_name": "Sergej91/TheiaSfM", "max_issues_repo_head_hexsha": "e603e16888456c3e565a2c197fa9f8643c176175", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/bundle_adjustment/optimize_relative_position_with_known_rotation.cc", "max_forks_repo_name": "Sergej91/TheiaSfM", "max_forks_repo_head_hexsha": "e603e16888456c3e565a2c197fa9f8643c176175", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.53, "max_line_length": 87, "alphanum_fraction": 0.7038957754, "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4281992181870154}}
{"text": "//\n// Created by philipp on 13.01.20.\n//\n\n#ifndef FUNNELS_CPP_EX1_HEU_HH\n#define FUNNELS_CPP_EX1_HEU_HH\n\n#include <Eigen/Core>\n#include <cmath>\n#include <sstream>\n#include <algorithm>\n\n\n#include <funnels/utils.hh>\n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795d\n#endif\n\n// Attention, in example 1, velocity coincides with the control\n// signal\n// Attention, assumes constant velocity/input\n\nconst double max_r_step = 0.1; // different funnel sizes in a family\nconst double min_r = 0.001; // Minimal radius\nconst double max_r = 0.5; // Minimal radius\nconst double max_alpha_step = max_r_step*max_r_step; // Minimal step for alpha\nconst double min_alpha = min_r*min_r; // Minimal alpha for ellipsoids\nconst double max_alpha = max_r*max_r; // Minimal alpha for ellipsoids\nconst double max_vel = 1.; // Norm of velocity\nconst double min_vel_diff = 0.1; // Norm difference in velocity\nconst double min_ang_diff = 20.*M_PI/180.;\nconst double gamma_conv = 3.; // exponential convergence rate\nconst double max_traj_length = 0.2; // Length of the new segment\nconst double dt_step = 0.05; //time step between two verification points\nconst double max_time = 10.;\nconst double min_englobe_fac = 1.1;\n\n\nEigen::Matrix2d getR(double alpha);\n\ntemplate<class DERIVED>\ndouble get_smallest_englobing(double r_src,\n    const Eigen::MatrixBase<DERIVED> &delta_vel){\n  return min_englobe_fac*(r_src + delta_vel.norm());\n}\n\ndouble get_smallest_englobing(double r_src, double d_v_norm);\n\ntemplate <class FUN_PTR_T>\nFUN_PTR_T get_this_funnel(const FUN_PTR_T &src, double radius,\n    const Eigen::Vector4d &x0, const Eigen::Vector2d u){\n  \n  using fun_t = typename FUN_PTR_T::element_type;\n  \n  // Get maximal time before the maximal length is attained\n  // or the playground is left\n  double n_u = u.norm()+1e-200;\n  double t_max = std::min(max_time, max_traj_length/n_u);\n  // distance to x/y-border\n  for (size_t i=0; i<2; i++){\n    if(x0(i)>=0. && u(i)>=0.){\n      t_max = std::min(t_max, (1.-x0(i))/(u(i)+1e-200));\n    }else if (x0(i)<=0. && u(i)<=0.){\n      t_max = std::min(t_max, (1.+x0(i))/(u(i)+1e-200));\n    }\n  }\n  if (t_max < 3.*dt_step){\n    // trajectory is too short\n    // initial is on the boundary and we are pointing outwards\n    return nullptr;\n  }\n  \n  // Convert to number of points\n  size_t this_n_verif = t_max/dt_step + 3;\n  \n  // todo check if this funnel already exists in the\n  // funnel system\n  // get the new name\n  std::stringstream sstream;\n  sstream.setf(std::ios::fixed);\n  sstream.precision(2);\n  \n  sstream << \"fun_\";\n  for(size_t i=0; i<4; i++){\n    sstream << (double) x0(i) << \"_\";\n  }\n  sstream << radius;\n  std::string name = sstream.str();\n  std::replace( name.begin(), name.end(), '.', 'p');\n  std::replace( name.begin(), name.end(), '-', 'm');\n  \n  // If exactly this funnel exists, the name will exist\n  if (utils_ext::loc_map.find(name)){\n    return nullptr;\n  }\n  \n  FUN_PTR_T new_fun = src->make_copy(name, this_n_verif);\n  \n  // set the new radius\n  new_fun->set_P(src->get_P()*(src->get_alpha()/(radius*radius)));\n  // and convergence\n  new_fun->set_gamma(gamma_conv);\n  \n  new_fun->compute(x0, 0., t_max, u);\n  \n  // He starts a family\n  new_fun->start_family(new_fun);\n  \n  return new_fun;\n}\n\ntemplate <class FUN_PTR_T>\nstd::vector<FUN_PTR_T> get_children(FUN_PTR_T &parent){\n  \n  using fun_t = typename FUN_PTR_T::element_type;\n  using matrix_t = typename fun_t::matrix_t;\n  \n  FUN_PTR_T this_child_fun;\n  FUN_PTR_T this_parent_fun = parent;\n  \n  \n  std::stringstream sstream;\n  std::string name;\n  \n  // Original unscaled matrix\n  matrix_t P_p = parent->get_P()*parent->get_alpha();\n  \n  sstream.setf(std::ios::fixed);\n  sstream.precision(2);\n  \n  std::vector<FUN_PTR_T> fun_vec_child;\n  \n  const double alpha_step = max_alpha_step;\n  const double r_step = max_r_step;\n  \n  // Radius of parent\n  double alpha = parent->get_alpha();\n  \n  if(std::sqrt(alpha) < min_r + r_step){\n    return fun_vec_child;\n  }\n  \n  alpha = std::max(min_alpha, (std::sqrt(alpha)-r_step)*(std::sqrt(alpha)-r_step));\n  \n  while(alpha>=min_alpha){\n    // Get the name\n    sstream.str(std::string());\n    sstream << \"fun_\";\n    for(size_t i=0; i<4; i++){\n      sstream << (double) parent->x0()(i) << \"_\";\n    }\n    sstream << std::sqrt(alpha);\n    name = sstream.str();\n    std::replace( name.begin(), name.end(), '.', 'p');\n    std::replace( name.begin(), name.end(), '-', 'm');\n    if (utils_ext::loc_map.find(name)){\n      // Already exists\n      return fun_vec_child;\n    }\n    \n    this_child_fun = this_parent_fun->make_copy(name, this_parent_fun->size());\n    // set the new radius\n    this_child_fun->set_P(P_p/alpha);\n    this_child_fun->set_cyclic(this_parent_fun->get_cyclic());\n    // And convergence\n    this_child_fun->set_gamma(gamma_conv);\n  \n    fun_t::set_parent(this_parent_fun, this_child_fun);\n    fun_vec_child.emplace_back(this_child_fun);\n    this_parent_fun = this_child_fun;\n    this_child_fun = nullptr;\n    // Update alpha\n    alpha = (std::sqrt(alpha)-r_step); // New alpha as r\n    if (alpha <= min_r){\n      break; // Necessary as negative radii become positive in next step\n    }\n    alpha *= alpha; // Convert to alpha\n  }\n  return fun_vec_child;\n}\n\n\ntemplate<class FUN_PTR_T, class FUN_SYS>\nvoid add_new_funnels(const FUN_PTR_T& src,\n    double t_src, FUN_SYS &fun_sys){\n  \n  using fun_t = typename FUN_PTR_T::element_type;\n  using vector_t = typename fun_t::vector_t;\n  using matrix_t = typename fun_t::matrix_t;\n  \n  // Return val\n  FUN_PTR_T fun_parent;\n  std::vector<FUN_PTR_T> fun_vec_child;\n  \n  // Radius of source\n  double r_src = std::sqrt(src->get_alpha());\n  if(r_src>=0.99*max_r){\n    return; // Quick exit\n  }\n  \n  Eigen::Vector2d v_src = src->x().block(2,0,2,1);\n  double n_v_src = v_src.norm();\n  Eigen::Vector2d v_src_n;\n  if (n_v_src<1e-10){\n    // The funnel is static -> any direction will do\n    n_v_src = 0.;\n    v_src_n(0) = 1.;\n    v_src_n(1) = 0.;\n  }else{\n    v_src_n = v_src/(n_v_src+1e-200); // Normalized\n  }\n  \n  \n  //Initial position\n  size_t idx_t = (src->t().array()-t_src).array().abs().minCoeff();\n  // Branching point of new funnels\n  Eigen::Vector2d pos_t = src->x().block(0,idx_t,2,1);\n  \n  // Create all possible successors with min_ang_diff\n  Eigen::Vector2d new_vel_n, new_vel;\n  Eigen::Vector4d x0;\n  double n_new_vel, tgt_radius;\n  double d_alpha = -M_PI;\n  while (d_alpha <= M_PI-min_ang_diff/2){\n    \n    // Desired new velocity direction\n    new_vel_n = getR(d_alpha)*v_src_n;\n    \n    // Loop over all allowed velocity norms\n    for (double delta_new_vel = -2.*max_vel; delta_new_vel<=2.*max_vel;\n        delta_new_vel+=min_vel_diff){\n      n_new_vel = n_v_src + delta_new_vel;\n      if(n_new_vel<-max_vel || n_new_vel > max_vel){\n        // New velocity norm is forbidden\n        continue;\n      }\n      if ((std::abs(n_new_vel)<1e-10) && (d_alpha != -M_PI/2) ){\n        // No need to add many static funnels with \"different\"\n        // directions\n        continue;\n      }\n      tgt_radius = get_smallest_englobing(r_src, std::abs(delta_new_vel));\n      if (tgt_radius>max_r){\n        // Minimal funnel size needed to englobe is larger then\n        // the maximal size\n        continue;\n      }\n      // Now we have a new parent funnel candidate\n      x0.block(0,0,2,1) = pos_t;\n      // todo refactor norm vs normalized\n      x0.block(2,0,2,1) = n_new_vel*new_vel_n;\n      // Parent\n      fun_parent = get_this_funnel(src, tgt_radius, x0, n_new_vel*new_vel_n);\n      if (fun_parent == nullptr){\n        continue;\n      }else{\n        // add\n        fun_sys.add_funnel(fun_parent, true);\n        // all_children\n        fun_vec_child = get_children(fun_parent);\n        for (auto a_f : fun_vec_child){\n          fun_sys.add_funnel(a_f);\n        }\n      }\n    } // Done velocity\n    d_alpha += min_ang_diff; // Update angles\n  }// Done angles\n  // All calculated\n  return;\n}\n\n#endif //FUNNELS_CPP_EX1_HEU_HH\n", "meta": {"hexsha": "4f6940c451dbf8ef32ea87f906707f9efc8a510b", "size": 7907, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/heuristics/ex1_heu.hh", "max_stars_repo_name": "schlepil/funnels_cpp_2", "max_stars_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/heuristics/ex1_heu.hh", "max_issues_repo_name": "schlepil/funnels_cpp_2", "max_issues_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/heuristics/ex1_heu.hh", "max_forks_repo_name": "schlepil/funnels_cpp_2", "max_forks_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8576642336, "max_line_length": 83, "alphanum_fraction": 0.6603009991, "num_tokens": 2297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.42819921818701534}}
{"text": "\n#include <NTL/vec_ZZ.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\n\nNTL_vector_impl(ZZ,vec_ZZ)\n\nNTL_eq_vector_impl(ZZ,vec_ZZ)\n\nNTL_io_vector_impl(ZZ,vec_ZZ)\n\nvoid InnerProduct(ZZ& xx, const vec_ZZ& a, const vec_ZZ& b)\n{\n   ZZ t1, x;\n\n   long n = min(a.length(), b.length());\n   long i;\n\n   clear(x);\n   for (i = 1; i <= n; i++) {\n      mul(t1, a(i), b(i));\n      add(x, x, t1);\n   }\n\n   xx = x;\n}\n\nvoid mul(vec_ZZ& x, const vec_ZZ& a, const ZZ& b_in)\n{\n   ZZ b = b_in;\n   long n = a.length();\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      mul(x[i], a[i], b);\n}\n\nvoid mul(vec_ZZ& x, const vec_ZZ& a, long b)\n{\n   long n = a.length();\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      mul(x[i], a[i], b);\n}\n\nvoid add(vec_ZZ& x, const vec_ZZ& a, const vec_ZZ& b)\n{\n   long n = a.length();\n   if (b.length() != n) Error(\"vector add: dimension mismatch\");\n\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      add(x[i], a[i], b[i]);\n}\n\nvoid sub(vec_ZZ& x, const vec_ZZ& a, const vec_ZZ& b)\n{\n   long n = a.length();\n   if (b.length() != n) Error(\"vector sub: dimension mismatch\");\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      sub(x[i], a[i], b[i]);\n}\n\nvoid clear(vec_ZZ& x)\n{\n   long n = x.length();\n   long i;\n   for (i = 0; i < n; i++)\n      clear(x[i]);\n}\n\nvoid negate(vec_ZZ& x, const vec_ZZ& a)\n{\n   long n = a.length();\n   x.SetLength(n);\n   long i;\n   for (i = 0; i < n; i++)\n      negate(x[i], a[i]);\n}\n\n\n\n\nlong IsZero(const vec_ZZ& a)\n{\n   long n = a.length();\n   long i;\n\n   for (i = 0; i < n; i++)\n      if (!IsZero(a[i]))\n         return 0;\n\n   return 1;\n}\n\nvec_ZZ operator+(const vec_ZZ& a, const vec_ZZ& b)\n{\n   vec_ZZ res;\n   add(res, a, b);\n   NTL_OPT_RETURN(vec_ZZ, res);\n}\n\nvec_ZZ operator-(const vec_ZZ& a, const vec_ZZ& b)\n{\n   vec_ZZ res;\n   sub(res, a, b);\n   NTL_OPT_RETURN(vec_ZZ, res);\n}\n\n\nvec_ZZ operator-(const vec_ZZ& a)\n{\n   vec_ZZ res;\n   negate(res, a);\n   NTL_OPT_RETURN(vec_ZZ, res);\n}\n\n\nZZ operator*(const vec_ZZ& a, const vec_ZZ& b)\n{\n   ZZ res;\n   InnerProduct(res, a, b);\n   NTL_OPT_RETURN(ZZ, res);\n}\n\nvoid VectorCopy(vec_ZZ& x, const vec_ZZ& a, long n)\n{\n   if (n < 0) Error(\"VectorCopy: negative length\");\n   if (NTL_OVERFLOW(n, 1, 0)) Error(\"overflow in VectorCopy\");\n\n   long m = min(n, a.length());\n\n   x.SetLength(n);\n\n   long i;\n\n   for (i = 0; i < m; i++)\n      x[i] = a[i];\n\n   for (i = m; i < n; i++)\n      clear(x[i]);\n}\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "43b8217f4dd41e6f236c325e694317f39862933b", "size": 2435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/vec_ZZ.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RUNETag/WinNTL/src/vec_ZZ.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/src/vec_ZZ.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 15.9150326797, "max_line_length": 64, "alphanum_fraction": 0.540862423, "num_tokens": 893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.4280755175522355}}
{"text": "#pragma once\n\n#include <boost/bimap.hpp>\n#include <boost/graph/adjacency_list.hpp>\n// #include <boost/graph/find_flow_cost.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n\nnamespace libMultiRobotPlanning {\n\n/*!\n  \\example assignment.cpp example that takes cost mappings from a file\n*/\n\n/*! \\brief Find optimal (lowest total cost) assignment\n\nThis class can find the lowest sum-of-cost assignment\nfor given agents and tasks. The costs must be integers, the agents and\ntasks can be of any user-specified type.\n\nThis method is based on maximum flow formulation.\n\n\\tparam Agent Type of the agent. Needs to be copy'able and comparable\n\\tparam Task Type of task. Needs to be copy'able and comparable\n*/\ntemplate <typename Agent, typename Task>\nclass Assignment {\n public:\n  Assignment()\n      : m_agents(), m_tasks(), m_graph(), m_sourceVertex(), m_sinkVertex() {\n    m_sourceVertex = boost::add_vertex(m_graph);\n    m_sinkVertex = boost::add_vertex(m_graph);\n  }\n\n  void clear() {\n    // std::cout << \"Asg: clear\" << std::endl;\n    std::set<edge_t> edgesToRemove;\n    for (const auto& agent : m_agents) {\n      auto es = boost::out_edges(agent.right, m_graph);\n      for (auto eit = es.first; eit != es.second; ++eit) {\n        if (!m_graph[*eit].isReverseEdge) {\n          edgesToRemove.insert(*eit);\n          edgesToRemove.insert(m_graph[*eit].reverseEdge);\n        }\n      }\n    }\n\n    for (const auto& e : edgesToRemove) {\n      boost::remove_edge(e, m_graph);\n    }\n  }\n\n  void setCost(const Agent& agent, const Task& task, long cost) {\n    // std::cout << \"setCost: \" << agent << \"->\" << task << \" cost: \" << cost <<\n    // std::endl;\n    // Lazily create vertex for agent\n    auto agentIter = m_agents.left.find(agent);\n    vertex_t agentVertex;\n    if (agentIter == m_agents.left.end()) {\n      agentVertex = boost::add_vertex(m_graph);\n      addOrUpdateEdge(m_sourceVertex, agentVertex, 0);\n      m_agents.insert(agentsMapEntry_t(agent, agentVertex));\n    } else {\n      agentVertex = agentIter->second;\n    }\n\n    // Lazily create vertex for task\n    auto taskIter = m_tasks.left.find(task);\n    vertex_t taskVertex;\n    if (taskIter == m_tasks.left.end()) {\n      taskVertex = boost::add_vertex(m_graph);\n      addOrUpdateEdge(taskVertex, m_sinkVertex, 0);\n      m_tasks.insert(tasksMapEntry_t(task, taskVertex));\n    } else {\n      taskVertex = taskIter->second;\n    }\n\n    addOrUpdateEdge(agentVertex, taskVertex, cost);\n  }\n\n  // find first (optimal) solution with minimal cost\n  long solve(std::map<Agent, Task>& solution) {\n    using namespace boost;\n\n    successive_shortest_path_nonnegative_weights(\n        m_graph, m_sourceVertex, m_sinkVertex,\n        boost::capacity_map(get(&Edge::capacity, m_graph))\n            .residual_capacity_map(get(&Edge::residualCapacity, m_graph))\n            .weight_map(get(&Edge::cost, m_graph))\n            .reverse_edge_map(get(&Edge::reverseEdge, m_graph)));\n\n    // long cost = find_flow_cost(\n    //   m_graph,\n    //   boost::capacity_map(get(&Edge::capacity, m_graph))\n    //   .residual_capacity_map(get(&Edge::residualCapacity, m_graph))\n    //   .weight_map(get(&Edge::cost, m_graph)));\n    long cost = 0;\n\n    // find solution\n    solution.clear();\n    auto es = out_edges(m_sourceVertex, m_graph);\n    for (auto eit = es.first; eit != es.second; ++eit) {\n      vertex_t agentVertex = target(*eit, m_graph);\n      auto es2 = out_edges(agentVertex, m_graph);\n      for (auto eit2 = es2.first; eit2 != es2.second; ++eit2) {\n        if (!m_graph[*eit2].isReverseEdge) {\n          vertex_t taskVertex = target(*eit2, m_graph);\n          if (m_graph[*eit2].residualCapacity == 0) {\n            solution[m_agents.right.at(agentVertex)] =\n                m_tasks.right.at(taskVertex);\n            cost += m_graph[edge(agentVertex, taskVertex, m_graph).first].cost;\n            break;\n          }\n        }\n      }\n    }\n\n    return cost;\n  }\n\n protected:\n  typedef boost::adjacency_list_traits<boost::vecS, boost::vecS,\n                                       boost::bidirectionalS>\n      graphTraits_t;\n  typedef graphTraits_t::vertex_descriptor vertex_t;\n  typedef graphTraits_t::edge_descriptor edge_t;\n\n  struct Vertex {\n    // boost::default_color_type color;\n    // edge_t predecessor;\n  };\n\n  struct Edge {\n    Edge()\n        : cost(0),\n          capacity(0),\n          residualCapacity(0),\n          reverseEdge(),\n          isReverseEdge(false) {}\n\n    long cost;\n    long capacity;\n    long residualCapacity;\n    edge_t reverseEdge;\n    bool isReverseEdge;\n  };\n\n  typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::bidirectionalS,\n                                Vertex, Edge>\n      graph_t;\n\n protected:\n  void addOrUpdateEdge(vertex_t from, vertex_t to, long cost) {\n    auto e = boost::edge(from, to, m_graph);\n    if (e.second) {\n      m_graph[e.first].cost = cost;\n      m_graph[m_graph[e.first].reverseEdge].cost = -cost;\n    } else {\n      auto e1 = boost::add_edge(from, to, m_graph);\n      m_graph[e1.first].cost = cost;\n      m_graph[e1.first].capacity = 1;\n      auto e2 = boost::add_edge(to, from, m_graph);\n      m_graph[e2.first].isReverseEdge = true;\n      m_graph[e2.first].cost = -cost;\n      m_graph[e2.first].capacity = 0;\n      m_graph[e1.first].reverseEdge = e2.first;\n      m_graph[e2.first].reverseEdge = e1.first;\n    }\n  }\n\n private:\n  typedef boost::bimap<Agent, vertex_t> agentsMap_t;\n  typedef typename agentsMap_t::value_type agentsMapEntry_t;\n  typedef boost::bimap<Task, vertex_t> tasksMap_t;\n  typedef typename tasksMap_t::value_type tasksMapEntry_t;\n\n  agentsMap_t m_agents;\n  tasksMap_t m_tasks;\n\n  graph_t m_graph;\n  vertex_t m_sourceVertex;\n  vertex_t m_sinkVertex;\n};\n\n}  // namespace libMultiRobotPlanning\n", "meta": {"hexsha": "54345c00ca2711551ec4fdb6669ca8b71cdb664e", "size": 5748, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/libMultiRobotPlanning/assignment.hpp", "max_stars_repo_name": "VSumanth99/libMultiRobotPlanning", "max_stars_repo_head_hexsha": "0720ac87711c5bace889be160087b86a2042cd14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 350.0, "max_stars_repo_stars_event_min_datetime": "2018-07-23T12:33:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:28:36.000Z", "max_issues_repo_path": "include/libMultiRobotPlanning/assignment.hpp", "max_issues_repo_name": "VSumanth99/libMultiRobotPlanning", "max_issues_repo_head_hexsha": "0720ac87711c5bace889be160087b86a2042cd14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2018-08-08T19:57:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-19T18:16:41.000Z", "max_forks_repo_path": "include/libMultiRobotPlanning/assignment.hpp", "max_forks_repo_name": "VSumanth99/libMultiRobotPlanning", "max_forks_repo_head_hexsha": "0720ac87711c5bace889be160087b86a2042cd14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 147.0, "max_forks_repo_forks_event_min_datetime": "2018-07-23T12:53:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:21:03.000Z", "avg_line_length": 31.0702702703, "max_line_length": 80, "alphanum_fraction": 0.648921364, "num_tokens": 1466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.42804382278324293}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>, Randi Cabezas <rcabezas@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.\n */\n\n#include <iostream>\n\n#include <boost/program_options.hpp>\n\n#include <dpMM/dirNaiveBayes.hpp>\n#include <dpMM/niwBaseMeasure.hpp>\n#include <dpMM/typedef.h>\n#include <dpMM/timer.hpp>\n\nnamespace po = boost::program_options;\n\nint main(int argc, char **argv){\n\n\t\n  // Declare the supported options.\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help,h\", \"produce help message\")\n\t(\"K,K\", po::value<int>(), \"number of initial clusters \")\n\t(\"T,T\", po::value<int>(), \"iterations\")\n\t(\"v,v\", po::value<bool>(), \"verbose output\")\n    (\"input,i\", po::value<string>(), \n      \"path to input dataset .csv file (rows: dimensions; cols: different \"\n      \"datapoints)\")\n    (\"output,o\", po::value<string>(), \n      \"path to output labels .csv file (rows: time; cols: different \"\n      \"datapoints)\")\n    ;\n\n    po::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm);    \n\n\tif (vm.count(\"help\")) {\n\t\tcout << desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tuint K=2;\n\tuint T=100;\n\tuint N=100;\n\tuint D=2;\n\tuint M=2;\n\tuint NumObs = 1; \n\tbool verbose = false; \n\tvector<uint> Mword; \n\tif (vm.count(\"K\")) \n\t\tK = vm[\"K\"].as<int>();\n\tif (vm.count(\"T\")) \n\t\tT = vm[\"T\"].as<int>();\n\tif (vm.count(\"v\"))\n\t\tverbose = vm[\"v\"].as<bool>();\n\n\tstring pathIn =\"\";\n\tstring pathOut =\"\";\n\tif(vm.count(\"input\")) \n\t\tpathIn = vm[\"input\"].as<string>();\n\tif(vm.count(\"output\")) \n\t\tpathOut= vm[\"output\"].as<string>();\n\t\n\tvector< Matrix<double, Dynamic, Dynamic> > x;\n\tx.reserve(N);\n\tif (!pathIn.compare(\"\"))\n\t{\n\t\tcout<<\"making some data up \" <<endl;\n\t\tuint Ndoc=M;\n\t\tuint Nword=int(N/M); \n\t\tfor(uint i=0; i<Ndoc; ++i) {\n\t\t\tMatrixXd  xdoc(D,Nword);  \n\t\t\tfor(uint w=0; w<Nword; ++w) {\n\t\t\t\tif(i<Ndoc/2)\n\t\t\t\t\txdoc.col(w) <<  VectorXd::Zero(D);\n\t\t\t\telse\n\t\t\t\t\txdoc.col(w) <<  2.0*VectorXd::Ones(D);\n\t\t\t}\n\n\t\t\tx.push_back(xdoc); \n\t\t}\n\t}else{\n\n\t\tcout<<\"loading data from \"<<pathIn<<endl;\n\t\tstd::ifstream fin(pathIn.data(),std::ifstream::in);\n\t\t\n\t\t//read parameters from file (tired of passing them in)\n\t\tfin>>NumObs; \n\t\tfin>>N;\n\t\tfin>>M;\n\t\tfin>>D; \n\n\t\tMatrixXd data(D,N);\n\t\tVectorXu words(M);\n\n\t\tfor (uint j=0; j<M; ++j) \n\t\t\tfin>>words(j); \n\t\t\n\t\tfor (uint j=1; j<(D+1); ++j) \n\t\t\tfor (uint i=0; i<N; ++i) \n\t\t\t\tfin>>data(j-1,i);\n\t\t\n\t\tuint count = 0;\n\t\tfor (uint j=0; j<M; ++j)\n\t\t{\n\t\t\tx.push_back(data.middleCols(count,words[j]));\n\t\t\tcount+=words[j];\n\t\t}\n\t\tfin.close();\n\t}\n\n\t\n\tdouble nu = D+1;\n\tdouble kappa = D+1;\n\tMatrixXd Delta = 0.1*MatrixXd::Identity(D,D);\n\tDelta *= nu;\n\tVectorXd theta = VectorXd::Zero(D);\n\tVectorXd alpha = 10.0*VectorXd::Ones(K);\n\n\tboost::mt19937 rndGen(9191);\n\tNIW<double> niw(Delta,theta,nu,kappa,&rndGen);\n\n\tDir<Catd,double> dir(alpha,&rndGen); \n\n  \n\t//cout<<\"------ marginalized ---- NIW \"<<endl;\n\t//DirNaiveBayes<double> naive_marg(dir,niwMargBase);\n\t//naive_marg.initialize(x);\n\t//cout<<naive_marg.labels().transpose()<<endl;\n\t//for(uint t=0; t<30; ++t)\n\t//{\n\t//naive_marg.sampleLabels();\n\t//naive_marg.sampleParameters();\n\t//cout<<naive_marg.labels().transpose()\n\t\t//<<\" logJoint=\"<<naive_marg.logJoint()<<endl;\n\t//}\n\tTimer tlocal;\n\ttlocal.tic();\n\n\tboost::shared_ptr<NiwSampled<double> > niwSampled( new NiwSampled<double>(niw));\n\tDirNaiveBayes<double> naive_samp(dir,niwSampled);\n  \n\tcout << \"naiveBayesian Clustering:\" << endl; \n\tcout << \"Ndocs=\" << M << endl; \n\tcout << \"Ndata=\" << N << endl; \n\tcout << \"dim=\" << D << endl;\n\tcout << \"Num Cluster = \" << K << \", (\" << T << \" iterations).\" << endl;\n\n\tnaive_samp.initialize( (const vector< Matrix<double, Dynamic, Dynamic> >) x );\n\tnaive_samp.inferAll(T,verbose);\n\n\n\tif (pathOut.compare(\"\"))\n\t{\n\t\tstd::ofstream fout(pathOut.data(),std::ofstream::out);\n\t\t\n\t\tstd::streambuf *coutbuf = std::cout.rdbuf(); //save old cout buffer\n\t\tcout.rdbuf(fout.rdbuf()); //redirect std::cout to fout1 buffer\n\n\t\t\tnaive_samp.dump(fout,fout);\n\n\t\tstd::cout.rdbuf(coutbuf); //reset to standard output again\n\n\t\tfout.close();\n\t}\n\n\ttlocal.displayElapsedTimeAuto();\n\treturn(0); \n\t\n};\n", "meta": {"hexsha": "eb75ddc4397cd36aaaee8445365a9e1e553810ad", "size": 4126, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/naiveBayes.cpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "test/naiveBayes.cpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/naiveBayes.cpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 23.988372093, "max_line_length": 120, "alphanum_fraction": 0.6114881241, "num_tokens": 1311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.42803624238782606}}
{"text": "/*ckwg +29\n * Copyright 2013-2015 by Kitware, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *  * Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n *  * Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and/or other materials provided with the distribution.\n *\n *  * Neither name of Kitware, Inc. nor the names of any contributors may be used\n *    to endorse or promote products derived from this software without specific\n *    prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * \\file\n * \\brief Implementation of \\link maptk::rotation_ rotation_<T> \\endlink\n *        for \\c T = { \\c float, \\c double }\n */\n\n#include \"rotation.h\"\n#include \"eigen_io.h\"\n\n#include <cmath>\n#include <limits>\n#include <boost/math/constants/constants.hpp>\n\n\nnamespace maptk\n{\n\n/// Constructor - from a Rodrigues vector\ntemplate <typename T>\nrotation_<T>\n::rotation_(const Eigen::Matrix<T,3,1>& rvec)\n{\n  T mag = rvec.norm();\n  if (mag == T(0))\n  {\n    // identity rotation is a special case\n    q_.setIdentity();\n  }\n  else\n  {\n    q_ = Eigen::Quaternion<T>(Eigen::AngleAxis<T>(mag, rvec/mag));\n  }\n}\n\n\n/// Constructor - from rotation angle and axis\ntemplate <typename T>\nrotation_<T>\n::rotation_(T angle, const Eigen::Matrix<T,3,1>& axis)\n  : q_(Eigen::Quaternion<T>(Eigen::AngleAxis<T>(angle, axis.normalized())))\n{\n}\n\n\n/// Constructor - from yaw, pitch, and roll\ntemplate <typename T>\nrotation_<T>\n::rotation_(const T& yaw, const T& pitch, const T& roll)\n{\n  using std::sin;\n  using std::cos;\n  // compute the rotation from North-East-Down (NED) coordinates to\n  // East-North-Up coordinates (ENU). It is a 180 degree rotation about\n  // the axis [1/sqrt(2), 1/sqrt(2), 0]\n  const double root_two = boost::math::constants::root_two<double>();\n  const T inv_root_two = static_cast<T>(1.0/root_two);\n  const rotation_<T> Rned2enu(Eigen::Quaternion<T>(0, inv_root_two, inv_root_two, 0));\n  const double half_x = 0.5 * static_cast<double>(-roll);\n  const double half_y = 0.5 * static_cast<double>(-pitch);\n  const double half_z = 0.5 * static_cast<double>(-yaw);\n  rotation_<T> Rx(Eigen::Quaternion<T>(T(cos(half_x)), T(sin(half_x)), 0, 0));\n  rotation_<T> Ry(Eigen::Quaternion<T>(T(cos(half_y)), 0, T(sin(half_y)), 0));\n  rotation_<T> Rz(Eigen::Quaternion<T>(T(cos(half_z)), 0, 0, T(sin(half_z))));\n  *this = Rx * Ry * Rz * Rned2enu;\n}\n\n\n/// Constructor - from a matrix\n/**\n * requires orthonormal matrix with +1 determinant\n */\ntemplate <typename T>\nrotation_<T>\n::rotation_(const Eigen::Matrix<T,3,3>& rot)\n{\n  q_ = Eigen::Quaternion<T>(rot);\n}\n\n\n/// Convert to a 3x3 matrix\ntemplate <typename T>\nrotation_<T>\n::operator Eigen::Matrix<T,3,3>() const\n{\n  return q_.toRotationMatrix();\n}\n\n\n\n/// Returns the axis of rotation\ntemplate <typename T>\nEigen::Matrix<T,3,1>\nrotation_<T>\n::axis() const\n{\n  Eigen::Matrix<T,3,1> dir(q_.x(), q_.y(), q_.z());\n  T mag = dir.norm();\n  if (mag == T(0))\n  {\n    return Eigen::Matrix<T,3,1>(0,0,1);\n  }\n  return dir / mag;\n}\n\n\n/// Returns the angle of the rotation in radians about the axis\ntemplate <typename T>\nT\nrotation_<T>\n::angle() const\n{\n  const double i = Eigen::Matrix<T,3,1>(q_.x(), q_.y(), q_.z()).norm();\n  const double r = q_.w();\n  T a = static_cast<T>(2.0 * std::atan2(i, r));\n  const T pi = boost::math::constants::pi<T>();\n  const T two_pi = static_cast<T>(2) * boost::math::constants::pi<T>();\n  // make sure computed angle lies within a sensible range,\n  // i.e. -pi/2 < a < pi/2\n  if (a >= pi)\n  {\n    a -= two_pi;\n  }\n  if (a <= -pi)\n  {\n    a += two_pi;\n  }\n  return a;\n}\n\n\n/// Return the rotation as a Rodrigues vector\ntemplate <typename T>\nEigen::Matrix<T,3,1>\nrotation_<T>\n::rodrigues() const\n{\n  T angle = this->angle();\n  if (angle == 0.0)\n  {\n    return Eigen::Matrix<T,3,1>(0,0,0);\n  }\n  return this->axis() * angle;\n}\n\n\n/// Convert to yaw, pitch, and roll\ntemplate <typename T>\nvoid\nrotation_<T>\n::get_yaw_pitch_roll(T& yaw, T& pitch, T& roll) const\n{\n  Eigen::Matrix<T,3,3> rotM(*this);\n  T cos_p = T(std::sqrt(double(rotM(1,2)*rotM(1,2)) + rotM(2,2)*rotM(2,2)));\n  yaw   = T(std::atan2(double(rotM(0,0)),double(rotM(0,1))));\n  pitch = T(std::atan2(double(rotM(0,2)),double(cos_p)));\n  roll  = T(std::atan2(double(-rotM(1,2)),double(-rotM(2,2))));\n}\n\n\n/// Compose two rotations\ntemplate <typename T>\nrotation_<T>\nrotation_<T>\n::operator*(const rotation_<T>& rhs) const\n{\n  return q_ * rhs.q_;\n}\n\n\n/// Rotate a vector\n/**\n * \\note for a large number of vectors, it is more efficient to\n * create a rotation matrix and use matrix multiplcation\n */\ntemplate <typename T>\nEigen::Matrix<T,3,1>\nrotation_<T>\n::operator*(const Eigen::Matrix<T,3,1>& rhs) const\n{\n  return q_ * rhs;\n}\n\n\n/// output stream operator for a rotation\ntemplate <typename T>\nstd::ostream&  operator<<(std::ostream& s, const rotation_<T>& r)\n{\n  s << r.quaternion().coeffs();\n  return s;\n}\n\n\n/// input stream operator for a rotation\ntemplate <typename T>\nstd::istream&  operator>>(std::istream& s, rotation_<T>& r)\n{\n  Eigen::Matrix<T,4,1> q;\n  s >> q;\n  r = rotation_<T>(q);\n  return s;\n}\n\n\n/// Generate a rotation vector that, when applied to A N times, produces B.\ntemplate <typename T>\nrotation_<T>\ninterpolate_rotation(rotation_<T> const& A, rotation_<T> const& B, T f)\n{\n  // rotation from A -> B\n  rotation_<T> C = A.inverse() * B;\n  // Reduce the angle of rotation by the fraction provided\n  return A * rotation_<T>(C.angle() * f, C.axis());\n}\n\n\n/// Generate N evenly interpolated rotations inbetween \\c A and \\c B.\ntemplate <typename T>\nvoid\ninterpolated_rotations(rotation_<T> const& A, rotation_<T> const& B, size_t n, std::vector< rotation_<T> > & interp_rots)\n{\n  interp_rots.reserve(interp_rots.capacity() + n);\n  size_t denom = n + 1;\n  for (size_t i=1; i<denom; ++i)\n  {\n    interp_rots.push_back(interpolate_rotation<T>(A, B, static_cast<T>(i) / denom));\n  }\n}\n\n\n/// \\cond DoxygenSuppress\n#define INSTANTIATE_ROTATION(T) \\\ntemplate class MAPTK_LIB_EXPORT rotation_<T>; \\\ntemplate MAPTK_LIB_EXPORT std::ostream&  operator<<(std::ostream& s, const rotation_<T>& r); \\\ntemplate MAPTK_LIB_EXPORT std::istream&  operator>>(std::istream& s, rotation_<T>& r); \\\ntemplate MAPTK_LIB_EXPORT rotation_<T> interpolate_rotation(rotation_<T> const& A, rotation_<T> const& B, T f); \\\ntemplate MAPTK_LIB_EXPORT void \\\ninterpolated_rotations(rotation_<T> const& A, rotation_<T> const& B, size_t n, std::vector< rotation_<T> > & interp_rots)\n\nINSTANTIATE_ROTATION(double);\nINSTANTIATE_ROTATION(float);\n\n#undef INSTANTIATE_ROTATION\n/// \\endcond\n\n} // end namespace maptk\n", "meta": {"hexsha": "9f43a1eea5a76e79b55b5c054f1378d74f920668", "size": 7584, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "maptk/rotation.cxx", "max_stars_repo_name": "efernandez/maptk", "max_stars_repo_head_hexsha": "c74546cf4056bffd1c3989055c7e60c5725eb3ab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "maptk/rotation.cxx", "max_issues_repo_name": "efernandez/maptk", "max_issues_repo_head_hexsha": "c74546cf4056bffd1c3989055c7e60c5725eb3ab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maptk/rotation.cxx", "max_forks_repo_name": "efernandez/maptk", "max_forks_repo_head_hexsha": "c74546cf4056bffd1c3989055c7e60c5725eb3ab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T09:29:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T09:29:55.000Z", "avg_line_length": 27.4782608696, "max_line_length": 121, "alphanum_fraction": 0.6811708861, "num_tokens": 2182, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.6334102567576901, "lm_q1q2_score": 0.42803623771143356}}
{"text": "#pragma once\n#include <Eigen/Sparse>\n\nnamespace edp\n{\nnamespace internal\n{\n    inline uint32_t ipow(uint32_t base, uint32_t exp)\n    {\n        uint32_t result = 1U;\n        while(exp != 0)\n        {\n            if((exp & 1U) != 0)\n            {\n                result *= base;\n            }\n            exp >>= 1U;\n            base *= base;\n        }\n\n        return result;\n    }\n}\n\ntemplate<typename T> struct TwoSiteTerm\n{\n    std::pair<uint32_t, uint32_t> sites;\n    Eigen::SparseMatrix<T> m;\n\n    TwoSiteTerm(std::pair<uint32_t, uint32_t> p1, const Eigen::SparseMatrix<T>& p2)\n        : sites(std::move(p1)), m(p2)\n    { }\n    TwoSiteTerm(std::pair<uint32_t, uint32_t>&& p1, Eigen::SparseMatrix<T>&& p2) : sites(p1), m(p2)\n    { }\n};\n\ntemplate<typename T> struct OneSiteTerm\n{\n    uint32_t site;\n    Eigen::SparseMatrix<T> m;\n\n    OneSiteTerm(uint32_t p1, const Eigen::SparseMatrix<T>& p2) : site(p1), m(p2) { }\n\n    OneSiteTerm(uint32_t p1, Eigen::SparseMatrix<T>&& p2) : site(p1), m(p2) { }\n};\n\ntemplate<typename T> class LocalHamiltonian\n{\nprivate:\n    uint32_t numSites_;\n    uint64_t d_; // local Hibert dimension\n\n    std::vector<TwoSiteTerm<T>> twoSiteTerms_;\n    std::vector<OneSiteTerm<T>> oneSiteTerms_;\n\n    [[nodiscard]] uint32_t swapBaseD(uint32_t idx, uint32_t pos, uint32_t val) const\n    {\n        uint32_t b = internal::ipow(d_, pos);\n        uint32_t upper = (idx / (b * d_)) * d_ + val;\n        return upper * b + (idx % b);\n    }\n\npublic:\n    LocalHamiltonian(uint32_t numSites, uint32_t d) : numSites_{numSites}, d_{d} { }\n\n    void clearTerms()\n    {\n        std::vector<TwoSiteTerm<T>>().swap(twoSiteTerms_);\n        std::vector<OneSiteTerm<T>>().swap(oneSiteTerms_);\n    }\n    [[nodiscard]] uint32_t getNumSites() const { return numSites_; }\n\n    [[nodiscard]] std::map<uint32_t, T> getCol(uint32_t n) const;\n    [[nodiscard]] inline std::map<uint32_t, T> operator()(uint32_t n) const { return getCol(n); }\n\n    void addTwoSiteTerm(const std::pair<int, int>& site, Eigen::SparseMatrix<T> m)\n    {\n        m.makeCompressed();\n        twoSiteTerms_.emplace_back(site, std::move(m));\n    }\n    void addOneSiteTerm(uint32_t site, Eigen::SparseMatrix<T> m)\n    {\n        m.makeCompressed();\n        oneSiteTerms_.emplace_back(site, std::move(m));\n    }\n};\n} // namespace edp\n\ntemplate<typename T> std::map<uint32_t, T> edp::LocalHamiltonian<T>::getCol(uint32_t n) const\n{\n    using Eigen::SparseMatrix;\n    using internal::ipow;\n\n    std::map<uint32_t, T> m;\n\n    for(auto& twoSiteTerm : twoSiteTerms_)\n    {\n        auto a = (n / ipow(d_, twoSiteTerm.sites.first)) % d_;\n        auto b = (n / ipow(d_, twoSiteTerm.sites.second)) % d_;\n        // auto col = twoSiteTerm.m.col(a*d_ + b);\n        auto col = b * d_ + a;\n        for(typename SparseMatrix<T>::InnerIterator it(twoSiteTerm.m, col); it; ++it)\n        {\n            uint32_t r = it.row();\n            uint32_t t = n;\n            t = swapBaseD(t, twoSiteTerm.sites.first, r % d_);\n            t = swapBaseD(t, twoSiteTerm.sites.second, r / d_);\n            m[t] += it.value();\n        }\n    }\n    for(auto& oneSiteTerm : oneSiteTerms_)\n    {\n        uint32_t a = (n / ipow(d_, oneSiteTerm.site)) % d_;\n        // auto col = oneSiteTerm.m.col(a);\n        auto col = a;\n\n        for(typename SparseMatrix<T>::InnerIterator it(oneSiteTerm.m, col); it; ++it)\n        {\n            uint32_t r = it.row();\n            uint32_t t = n;\n            t = swapBaseD(t, oneSiteTerm.site, r);\n            m[t] += it.value();\n        }\n    }\n    return m;\n}\n", "meta": {"hexsha": "b2b448081e570f152ecb5186ac7edce3b04d01ba", "size": 3526, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/edlib/EDP/LocalHamiltonian.hpp", "max_stars_repo_name": "cecri/ExactDiagonalization", "max_stars_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/edlib/EDP/LocalHamiltonian.hpp", "max_issues_repo_name": "cecri/ExactDiagonalization", "max_issues_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/edlib/EDP/LocalHamiltonian.hpp", "max_forks_repo_name": "cecri/ExactDiagonalization", "max_forks_repo_head_hexsha": "a168ed2f60149b1c3e5bd9ae46a5d169aea76773", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7637795276, "max_line_length": 99, "alphanum_fraction": 0.5777084515, "num_tokens": 1041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4279870344733885}}
{"text": "/**\n * \\file\n * \\author Thomas Fischer\n * \\date   2011-03-17\n * \\brief  Implementation of the AngleSkewMetric class.\n *\n * \\copyright\n * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include \"AngleSkewMetric.h\"\n\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n\n#include \"MeshLib/Node.h\"\n\n#include \"MathLib/MathTools.h\"\n\nusing namespace boost::math::double_constants;\n\nnamespace MeshLib\n{\nAngleSkewMetric::AngleSkewMetric(Mesh const& mesh) :\n    ElementQualityMetric(mesh)\n{}\n\nvoid AngleSkewMetric::calculateQuality ()\n{\n    const std::vector<MeshLib::Element*>& elements(_mesh.getElements());\n    const std::size_t nElements (_mesh.getNumberOfElements());\n\n    for (std::size_t k(0); k < nElements; k++)\n    {\n        Element const& elem (*elements[k]);\n        switch (elem.getGeomType())\n        {\n        case MeshElemType::LINE:\n            _element_quality_metric[k] = -1.0;\n            break;\n        case MeshElemType::TRIANGLE:\n            _element_quality_metric[k] = checkTriangle (elem);\n            break;\n        case MeshElemType::QUAD:\n            _element_quality_metric[k] = checkQuad (elem);\n            break;\n        case MeshElemType::TETRAHEDRON:\n            _element_quality_metric[k] = checkTetrahedron (elem);\n            break;\n        case MeshElemType::HEXAHEDRON:\n            _element_quality_metric[k] = checkHexahedron (elem);\n            break;\n        case MeshElemType::PRISM:\n            _element_quality_metric[k] = checkPrism (elem);\n            break;\n        default:\n            break;\n        }\n    }\n}\n\ndouble AngleSkewMetric::checkTriangle (Element const& elem) const\n{\n    double const* const node0 (elem.getNode(0)->getCoords());\n    double const* const node1 (elem.getNode(1)->getCoords());\n    double const* const node2 (elem.getNode(2)->getCoords());\n\n    double min_angle(two_pi);\n    double max_angle(0.0);\n    getMinMaxAngleFromTriangle (node0, node1, node2, min_angle, max_angle);\n\n    return 1.0 -\n           std::max((max_angle - third_pi) / two_thirds_pi,\n                    (third_pi - min_angle) / third_pi);\n}\n\ndouble AngleSkewMetric::checkQuad (Element const& elem) const\n{\n    double const* const node0 (elem.getNode(0)->getCoords());\n    double const* const node1 (elem.getNode(1)->getCoords());\n    double const* const node2 (elem.getNode(2)->getCoords());\n    double const* const node3 (elem.getNode(3)->getCoords());\n\n    double min_angle (two_pi);\n    double max_angle (0.0);\n\n    getMinMaxAngleFromQuad (node0, node1, node2, node3, min_angle, max_angle);\n\n    return 1.0 -\n           std::max((max_angle - two_pi) / (-pi), (two_pi - min_angle) / (two_pi));\n}\n\ndouble AngleSkewMetric::checkTetrahedron (Element const& elem) const\n{\n    double const* const node0 (elem.getNode(0)->getCoords());\n    double const* const node1 (elem.getNode(1)->getCoords());\n    double const* const node2 (elem.getNode(2)->getCoords());\n    double const* const node3 (elem.getNode(3)->getCoords());\n\n    double min_angle (two_pi);\n    double max_angle (0.0);\n\n    // first triangle (0,1,2)\n    getMinMaxAngleFromTriangle(node0, node1, node2, min_angle, max_angle);\n    // second triangle (0,1,3)\n    getMinMaxAngleFromTriangle(node0, node1, node3, min_angle, max_angle);\n    // third triangle (0,2,3)\n    getMinMaxAngleFromTriangle(node0, node2, node3, min_angle, max_angle);\n    // fourth triangle (1,2,3)\n    getMinMaxAngleFromTriangle(node1, node2, node3, min_angle, max_angle);\n\n    return 1.0 - std::max((max_angle - two_pi) / two_thirds_pi,\n                          (third_pi - min_angle) / third_pi);\n}\n\ndouble AngleSkewMetric::checkHexahedron (Element const& elem) const\n{\n    double const* const node0 (elem.getNode(0)->getCoords());\n    double const* const node1 (elem.getNode(1)->getCoords());\n    double const* const node2 (elem.getNode(2)->getCoords());\n    double const* const node3 (elem.getNode(3)->getCoords());\n    double const* const node4 (elem.getNode(4)->getCoords());\n    double const* const node5 (elem.getNode(5)->getCoords());\n    double const* const node6 (elem.getNode(6)->getCoords());\n    double const* const node7 (elem.getNode(7)->getCoords());\n\n    double min_angle (two_pi);\n    double max_angle (0.0);\n\n    // first surface (0,1,2,3)\n    getMinMaxAngleFromQuad (node0, node1, node2, node3, min_angle, max_angle);\n    // second surface (0,3,7,4)\n    getMinMaxAngleFromQuad (node0, node3, node7, node4, min_angle, max_angle);\n    // third surface (4,5,6,7)\n    getMinMaxAngleFromQuad (node4, node5, node6, node7, min_angle, max_angle);\n    // fourth surface (5,1,2,6)\n    getMinMaxAngleFromQuad (node5, node1, node2, node6, min_angle, max_angle);\n    // fifth surface (5,1,0,4)\n    getMinMaxAngleFromQuad (node5, node1, node0, node4, min_angle, max_angle);\n    // sixth surface (6,2,3,7)\n    getMinMaxAngleFromQuad (node6, node2, node3, node7, min_angle, max_angle);\n\n    return 1.0 -\n           std::max((max_angle - two_pi) / (-pi), (two_pi - min_angle) / two_pi);\n}\n\ndouble AngleSkewMetric::checkPrism (Element const& elem) const\n{\n    double const* const node0 (elem.getNode(0)->getCoords());\n    double const* const node1 (elem.getNode(1)->getCoords());\n    double const* const node2 (elem.getNode(2)->getCoords());\n    double const* const node3 (elem.getNode(3)->getCoords());\n    double const* const node4 (elem.getNode(4)->getCoords());\n    double const* const node5 (elem.getNode(5)->getCoords());\n\n    double min_angle_tri (two_pi);\n    double max_angle_tri (0.0);\n\n    // first triangle (0,1,2)\n    getMinMaxAngleFromTriangle (node0, node1, node2, min_angle_tri, max_angle_tri);\n    // second surface (3,4,5)\n    getMinMaxAngleFromTriangle (node3, node4, node5, min_angle_tri, max_angle_tri);\n\n    double tri_criterion (1.0 - std::max((max_angle_tri - two_pi) / two_thirds_pi,\n                                         (third_pi - min_angle_tri) / third_pi));\n\n    double min_angle_quad (two_pi);\n    double max_angle_quad (0.0);\n    // surface (0,3,4,1)\n    getMinMaxAngleFromQuad (node0, node3, node4, node1, min_angle_quad, max_angle_quad);\n    // surface (2,5,3,0)\n    getMinMaxAngleFromQuad (node2, node5, node3, node0, min_angle_quad, max_angle_quad);\n    // surface (1,2,5,4)\n    getMinMaxAngleFromQuad (node1, node2, node5, node4, min_angle_quad, max_angle_quad);\n\n    double quad_criterion (1.0 - std::max((max_angle_quad - two_pi) / (-pi),\n                                          (two_pi - min_angle_quad) / two_pi));\n\n    return std::min (tri_criterion, quad_criterion);\n}\n\nvoid AngleSkewMetric::getMinMaxAngleFromQuad (\n        double const* const n0, double const* const n1,\n        double const* const n2, double const* const n3,\n        double &min_angle, double &max_angle) const\n{\n    const double* nodes[4] = {n0, n1, n2, n3};\n    for (unsigned i=0; i<4; ++i)\n    {\n        const double angle (MathLib::getAngle (nodes[i], nodes[(i+1)%4], nodes[(i+2)%4]));\n        min_angle = std::min(angle, min_angle);\n        max_angle = std::max(angle, max_angle);\n    }\n}\n\nvoid AngleSkewMetric::getMinMaxAngleFromTriangle(double const* const n0,\n                                                          double const* const n1,\n                                                          double const* const n2,\n                                                          double &min_angle,\n                                                          double &max_angle) const\n{\n    const double* nodes[3] = {n0, n1, n2};\n    for (unsigned i=0; i<3; ++i)\n    {\n        const double angle (MathLib::getAngle (nodes[i], nodes[(i+1)%3], nodes[(i+2)%3]));\n        min_angle = std::min(angle, min_angle);\n        max_angle = std::max(angle, max_angle);\n    }\n}\n\n} // end namespace MeshLib\n", "meta": {"hexsha": "b1248b80447b133c19fe55dc33198cc7571adfb0", "size": 7896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MeshLib/MeshQuality/AngleSkewMetric.cpp", "max_stars_repo_name": "OlafKolditz/ogs", "max_stars_repo_head_hexsha": "e33400e1d9503d33ce80509a3441a873962ad675", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-09-02T11:49:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-02T11:49:52.000Z", "max_issues_repo_path": "MeshLib/MeshQuality/AngleSkewMetric.cpp", "max_issues_repo_name": "OlafKolditz/ogs", "max_issues_repo_head_hexsha": "e33400e1d9503d33ce80509a3441a873962ad675", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T13:08:57.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-25T12:56:17.000Z", "max_forks_repo_path": "MeshLib/MeshQuality/AngleSkewMetric.cpp", "max_forks_repo_name": "OlafKolditz/ogs", "max_forks_repo_head_hexsha": "e33400e1d9503d33ce80509a3441a873962ad675", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-08-13T13:37:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-01T10:19:03.000Z", "avg_line_length": 36.5555555556, "max_line_length": 90, "alphanum_fraction": 0.6331053698, "num_tokens": 2152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.42798702879230477}}
{"text": "// Copyright (c)  Mingcheng Zuo, Dietmar Wolz.\r\n//\r\n// This source code is licensed under the MIT license found in the\r\n// LICENSE file in the root directory.\r\n\r\n// Eigen based implementation of differential evolution (GCL-DE) derived from\r\n// \"A case learning-based differential evolution algorithm for global optimization of interplanetary trajectory design,\r\n//  Mingcheng Zuo, Guangming Dai, Lei Peng, Maocai Wang, Zhengquan Liu\", https://doi.org/10.1016/j.asoc.2020.106451\r\n\r\n#include <Eigen/Core>\r\n#include <iostream>\r\n#include <float.h>\r\n#include <ctime>\r\n#include <random>\r\n#include \"pcg_random.hpp\"\r\n#include \"call_java.hpp\"\r\n\r\nusing namespace std;\r\n\r\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1> vec;\r\ntypedef Eigen::Matrix<int, Eigen::Dynamic, 1> ivec;\r\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat;\r\n\r\ntypedef void (*callback_parallel)(int, int, double[], double[]);\r\n\r\nnamespace cl_differential_evolution {\r\n\r\nstatic uniform_real_distribution<> distr_01 = std::uniform_real_distribution<>(\r\n        0, 1);\r\nstatic normal_distribution<> gauss_01 = std::normal_distribution<>(0, 1);\r\n\r\nstatic double normreal(pcg64 *rs, double mu, double sdev) {\r\n    return gauss_01(*rs) * sdev + mu;\r\n}\r\n\r\nstatic vec zeros(int n) {\r\n    return Eigen::MatrixXd::Zero(n, 1);\r\n}\r\n\r\nstatic vec constant(int n, double val) {\r\n    return Eigen::MatrixXd::Constant(n, 1, val);\r\n}\r\n\r\nstatic Eigen::MatrixXd uniformVec(int dim, pcg64 &rs) {\r\n    return Eigen::MatrixXd::NullaryExpr(dim, 1, [&]() {\r\n        return distr_01(rs);\r\n    });\r\n}\r\n\r\nstatic Eigen::MatrixXd uniform(int dx, int dy, pcg64 &rs) {\r\n    return Eigen::MatrixXd::NullaryExpr(dx, dy, [&]() {\r\n        return distr_01(rs);\r\n    });\r\n}\r\n\r\nstruct IndexVal {\r\n    int index;\r\n    double val;\r\n};\r\n\r\nstatic bool compareIndexVal(IndexVal i1, IndexVal i2) {\r\n    return (i1.val < i2.val);\r\n}\r\n\r\nstatic ivec sort_index(const vec &x) {\r\n    int size = x.size();\r\n    IndexVal ivals[size];\r\n    for (int i = 0; i < size; i++) {\r\n        ivals[i].index = i;\r\n        ivals[i].val = x[i];\r\n    }\r\n    std::sort(ivals, ivals + size, compareIndexVal);\r\n    return Eigen::MatrixXi::NullaryExpr(size, 1, [&ivals](int i) {\r\n        return ivals[i].index;\r\n    });\r\n}\r\n\r\nstatic ivec sort_index(const vec &y, int *indices, int size) {\r\n    IndexVal ivals[size];\r\n    for (int i = 0; i < size; i++) {\r\n        ivals[i].index = indices[i];\r\n        ivals[i].val = y[indices[i]];\r\n    }\r\n    std::sort(ivals, ivals + size, compareIndexVal);\r\n    return Eigen::MatrixXi::NullaryExpr(size, 1, [&ivals](int i) {\r\n        return ivals[i].index;\r\n    });\r\n}\r\n\r\n// wrapper around the fitness function, scales according to boundaries\r\n\r\nclass Fitness {\r\n\r\npublic:\r\n\r\n    Fitness(CallJava *func_par_, const vec &lower_limit,\r\n            const vec &upper_limit) {\r\n        func_par = func_par_;\r\n        lower = lower_limit;\r\n        upper = upper_limit;\r\n        evaluationCounter = 0;\r\n        if (lower.size() > 0) // bounds defined\r\n            scale = (upper - lower);\r\n    }\r\n\r\n    vec norm(vec &X) {\r\n        return (X - lower).array() / scale.array();\r\n    }\r\n\r\n    vec getClosestFeasible(const vec &X) const {\r\n        if (lower.size() > 0) {\r\n            return X.cwiseMin(upper).cwiseMax(lower);\r\n        }\r\n        return X;\r\n    }\r\n\r\n    void values(const mat &popX, vec &ys) {\r\n        int popsize = popX.cols();\r\n        int n = popX.rows();\r\n        double pargs[popsize * n];\r\n        double res[popsize];\r\n        for (int p = 0; p < popX.cols(); p++) {\r\n            for (int i = 0; i < n; i++)\r\n                pargs[p * n + i] = popX(i, p);\r\n        }\r\n        func_par->evalJava(popsize, n, pargs, res);\r\n        for (int p = 0; p < popX.cols(); p++)\r\n            ys[p] = res[p];\r\n        evaluationCounter += popsize;\r\n    }\r\n\r\n    bool feasible(int i, double x) {\r\n        return x >= lower[i] && x <= upper[i];\r\n    }\r\n\r\n    vec uniformX(pcg64 &rs) {\r\n        vec rv = uniformVec(lower.size(), rs);\r\n        return (rv.array() * scale.array()).matrix() + lower;\r\n    }\r\n\r\n    double uniformXi(int i, pcg64 &rs) {\r\n        return lower[i] + scale[i] * distr_01(rs);\r\n    }\r\n\r\n    int getEvaluations() {\r\n        return evaluationCounter;\r\n    }\r\n\r\n    vec lower;\r\n    vec upper;\r\n\r\nprivate:\r\n    CallJava *func_par;\r\n    long evaluationCounter;\r\n    vec scale;\r\n};\r\n\r\nclass ClDeOptimizer {\r\n\r\npublic:\r\n\r\n    ClDeOptimizer(long runid_, Fitness *fitfun_, int dim_, int seed_,\r\n            int popsize_, int maxEvaluations_, double pbest_,\r\n            double stopfitness_, double K1_, double K2_) {\r\n        // runid used to identify a specific run\r\n        runid = runid_;\r\n        // fitness function to minimize\r\n        fitfun = fitfun_;\r\n        // Number of objective variables/problem dimension\r\n        dim = dim_;\r\n        // Population size\r\n        popsize0 = popsize_ > 0 ? popsize_ : int(dim * 8.5 + 150);\r\n        // maximal number of evaluations allowed.\r\n        maxEvaluations = maxEvaluations_;\r\n        // use low value 0 < pbest <= 1 to narrow search.\r\n        pbest0 = pbest_;\r\n        // Limit for fitness value.\r\n        stopfitness = stopfitness_;\r\n        K1 = K1_;\r\n        K2 = K2_;\r\n        // stop criteria\r\n        stop = 0;\r\n        rs = new pcg64(seed_);\r\n        init();\r\n    }\r\n\r\n    ~ClDeOptimizer() {\r\n        delete rs;\r\n    }\r\n\r\n    double rnd01() {\r\n        return distr_01(*rs);\r\n    }\r\n\r\n    int rndInt(int max) {\r\n        return (int) (max * distr_01(*rs));\r\n    }\r\n\r\n    void doOptimize() {\r\n\r\n        double CR, F;\r\n        vector<vec> sp;\r\n\r\n        double stage = 0.5;\r\n\r\n        int popsize = popsize0;\r\n        double pbest = pbest0;\r\n\r\n        // -------------------- Generation Loop --------------------------------\r\n\r\n        for (iterations = 1;; iterations++) {\r\n            // sort population\r\n            ivec sindex = sort_index(nextY);\r\n            popY = nextY(sindex, Eigen::all);\r\n            popX = nextX(Eigen::all, sindex);\r\n\r\n            bestX = popX.col(0);\r\n            bestY = popY[0];\r\n\r\n            if (isfinite(stopfitness) && bestY < stopfitness) {\r\n                stop = 1;\r\n                return;\r\n            }\r\n\r\n            if (fitfun->getEvaluations() >= maxEvaluations)\r\n                return;\r\n\r\n            double evals = float(fitfun->getEvaluations()) / maxEvaluations;\r\n            if (evals > stage)\r\n                pbest = pbest0;\r\n            else {\r\n                for (double per = 1.0; per >= 0; per = per - 0.05)\r\n                    if (evals * evals < per && evals * evals >= per - 0.05)\r\n                        pbest = 1 - per;\r\n            }\r\n            popsize = min(popsize0,\r\n                    max(7 * dim, int(popsize0 - (popsize0 - 50) * evals)));\r\n\r\n            mat local_upper(dim, popsize);\r\n            mat local_lower(dim, popsize);\r\n            double bound_info[popsize];\r\n            for (int p = 0; p < popsize; p++) {\r\n                vec X = popX.col(p);\r\n                local_upper.col(p) = fitfun->upper.cwiseMin(X);\r\n                local_lower.col(p) = fitfun->lower.cwiseMax(X);\r\n                vec norm = fitfun->norm(X);\r\n                double avnorm = norm.sum() / popsize;\r\n                bound_info[p] = 0;\r\n                for (int j = 0; j < dim; j++)\r\n                    bound_info[p] += abs(norm[j] - avnorm);\r\n                bound_info[p] /= popsize;\r\n            }\r\n\r\n            for (int p = 0; p < popsize; p++) {\r\n                int r1, r2, r3;\r\n                do {\r\n                    r1 = rndInt(popsize);\r\n                } while (r1 == p);\r\n                do {\r\n                    r2 = rndInt(int(popsize * pbest));\r\n                } while (r2 == p || r2 == r1);\r\n                do {\r\n                    r3 = rndInt(popsize + sp.size());\r\n                } while (r3 == p || r3 == r2 || r3 == r1);\r\n                int jr = rndInt(dim);\r\n\r\n                if (iterations % 2 == 1)\r\n//\t\t\t\t\tCR = 1;\r\n                    CR = normreal(rs, 0.95, 0.01);\r\n                else\r\n//\t\t\t\t\tCR = 0;\r\n                    CR = normreal(rs, 0.0, 0.01);\r\n\r\n                mat mutationX;\r\n                vec mutationY;\r\n                int mutationI[3];\r\n                if (evals > stage) {\r\n                    mutationI[0] = r1;\r\n                    mutationI[1] = r2;\r\n                    mutationI[2] = r3 < popsize ? r3 : r3 - popsize;\r\n                    ivec mindex = sort_index(nextY, mutationI, 3);\r\n                    mutationY = nextY(mindex, Eigen::all);\r\n                    mutationX = nextX(Eigen::all, mindex);\r\n                    F = 2 * (mutationY[1] - mutationY[0])\r\n                            / (mutationY[2] - mutationY[0]);\r\n                } else {\r\n                    if (rnd01() < 0.5)\r\n                        F = normreal(rs, 0.1, 0.04);\r\n                    else\r\n                        F = normreal(rs, 1.0, 1.0);\r\n                    if (F < 0 || F > 1)\r\n                        F = rnd01();\r\n                }\r\n                vec ui = popX.col(p);\r\n                vec ub = local_upper.col(p);\r\n                vec lb = local_lower.col(p);\r\n                for (int j = 0; j < dim; j++) {\r\n                    if (j == jr || rnd01() < CR) {\r\n                        if (bound_info[j] > 0.1 && evals < K1 && rnd01() > K2)\r\n                            ui[j] = ub[j] + lb[j] - popX(j, r1);\r\n                        else {\r\n                            if (evals > stage) {\r\n                                ui[j] = mutationX(j, 0)\r\n                                        + F\r\n                                                * (mutationX(j, 1)\r\n                                                        - mutationX(j, 2));\r\n                            } else {\r\n                                if (r3 < popsize)\r\n                                    ui[j] = popX(j, r1)\r\n                                            + F * (popX(j, r2) - popX(j, r3));\r\n                                else\r\n                                    ui[j] =\r\n                                            popX(j, r1)\r\n                                                    + F\r\n                                                            * ((popX)(j, r2)\r\n                                                                    - sp[r3\r\n                                                                            - popsize][j]);\r\n                            }\r\n                        }\r\n                        if (!fitfun->feasible(j, ui[j]))\r\n                            ui[j] = fitfun->uniformXi(j, *rs);\r\n                    }\r\n                }\r\n                nextX.col(p) = ui;\r\n            }\r\n            fitfun->values(nextX, nextY);\r\n            for (int p = 0; p < popsize; p++) {\r\n                if (nextY[p] < popY[p]) {\r\n                    if (sp.size() < popsize)\r\n                        sp.push_back(popX.col(p));\r\n                    else\r\n                        sp[rndInt(popsize)] = popX.col(p);\r\n                } else {    // no improvement, copy from parent\r\n                    nextX.col(p) = popX.col(p);\r\n                    nextY[p] = popY[p];\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    void init() {\r\n        popCR = zeros(popsize0);\r\n        popF = zeros(popsize0);\r\n        nextX = mat(dim, popsize0);\r\n        for (int p = 0; p < popsize0; p++)\r\n            nextX.col(p) = fitfun->uniformX(*rs);\r\n        nextY = vec(popsize0);\r\n        fitfun->values(nextX, nextY);\r\n    }\r\n\r\n    vec getBestX() {\r\n        return bestX;\r\n    }\r\n\r\n    double getBestValue() {\r\n        return bestY;\r\n    }\r\n\r\n    double getIterations() {\r\n        return iterations;\r\n    }\r\n\r\n    double getStop() {\r\n        return stop;\r\n    }\r\n\r\nprivate:\r\n    long runid;\r\n    Fitness *fitfun;\r\n    int popsize0; // population size\r\n    int dim;\r\n    int maxEvaluations;\r\n    double pbest0;\r\n    double stopfitness;\r\n    int iterations;\r\n    double bestY;\r\n    vec bestX;\r\n    int stop;\r\n    double K1;\r\n    double K2;\r\n    pcg64 *rs;\r\n    mat popX;\r\n    vec popY;\r\n    mat nextX;\r\n    vec nextY;\r\n    vec popCR;\r\n    vec popF;\r\n};\r\n}\r\n\r\nusing namespace cl_differential_evolution;\r\n\r\n/*\r\n * Class:     fcmaes_core_Jni\r\n * Method:    optimizeCLDE\r\n * Signature: (Lfcmaes/core/Fitness;[D[D[DIDIDDDJI)I\r\n */\r\nJNIEXPORT jint JNICALL Java_fcmaes_core_Jni_optimizeCLDE(JNIEnv *env,\r\n        jclass cls, jobject func, jdoubleArray jlower, jdoubleArray jupper,\r\n        jdoubleArray jinit, jint maxEvals, jdouble stopfitness, jint popsize,\r\n        jdouble pbest, jdouble K1, jdouble K2, jlong seed, jint runid) {\r\n    // init java function callback\r\n    double *init = env->GetDoubleArrayElements(jinit, JNI_FALSE);\r\n    double *lower = env->GetDoubleArrayElements(jlower, JNI_FALSE);\r\n    double *upper = env->GetDoubleArrayElements(jupper, JNI_FALSE);\r\n    int dim = env->GetArrayLength(jinit);\r\n\r\n    vec lower_limit(dim), upper_limit(dim);\r\n    bool useLimit = false;\r\n    for (int i = 0; i < dim; i++) {\r\n        lower_limit[i] = lower[i];\r\n        upper_limit[i] = upper[i];\r\n        useLimit |= (lower[i] != 0);\r\n        useLimit |= (upper[i] != 0);\r\n    }\r\n    if (useLimit == false) {\r\n        lower_limit.resize(0);\r\n        upper_limit.resize(0);\r\n    }\r\n    CallJava callJava(func, env);\r\n    Fitness fitfun(&callJava, lower_limit, upper_limit);\r\n    ClDeOptimizer opt(runid, &fitfun, dim, seed, popsize, maxEvals, pbest,\r\n            stopfitness, K1, K2);\r\n    try {\r\n        opt.doOptimize();\r\n        vec bestX = opt.getBestX();\r\n        double bestY = opt.getBestValue();\r\n\r\n        for (int i = 0; i < dim; i++)\r\n            init[i] = bestX[i];\r\n\r\n        env->SetDoubleArrayRegion(jinit, 0, dim, (jdouble*) init);\r\n        env->ReleaseDoubleArrayElements(jinit, init, 0);\r\n        env->ReleaseDoubleArrayElements(jupper, upper, 0);\r\n        env->ReleaseDoubleArrayElements(jlower, lower, 0);\r\n        return fitfun.getEvaluations();\r\n\r\n    } catch (std::exception &e) {\r\n        cout << e.what() << endl;\r\n        return fitfun.getEvaluations();\r\n    }\r\n    return 0;\r\n}\r\n\r\n", "meta": {"hexsha": "01a3ce12b064756a1ab8d968847a40f7f9e88f6b", "size": 14014, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppsrc/cldeoptimizer.cpp", "max_stars_repo_name": "dietmarwo/fcmaes-java", "max_stars_repo_head_hexsha": "ec1704199783e93628f6fde42295c9b79cb48dde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-11-08T14:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T12:41:38.000Z", "max_issues_repo_path": "cppsrc/cldeoptimizer.cpp", "max_issues_repo_name": "dietmarwo/fcmaes-java", "max_issues_repo_head_hexsha": "ec1704199783e93628f6fde42295c9b79cb48dde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppsrc/cldeoptimizer.cpp", "max_forks_repo_name": "dietmarwo/fcmaes-java", "max_forks_repo_head_hexsha": "ec1704199783e93628f6fde42295c9b79cb48dde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-08T14:27:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-08T14:27:15.000Z", "avg_line_length": 31.4921348315, "max_line_length": 120, "alphanum_fraction": 0.4696018267, "num_tokens": 3485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4279870287923047}}
{"text": "//==================================================================================================\n/**\n\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SINHC_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_SINHC_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/arch/common/detail/generic/sinhc_kernel.hpp>\n#include <boost/simd/meta/as_logical.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/detail/constant/maxlog.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/average.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/nbtrue.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/unary_minus.hpp>\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/constant/inf.hpp>\n#endif\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF( sinhc_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        //////////////////////////////////////////////////////////////////////////////\n        // if x = abs(a0) is less than 1 sinhc is computed using a polynomial(float)\n        // respectively rational(double) approx inspired from cephes sinh approx.\n        // else according x < Threshold e =  exp(x) or exp(x/2) is respectively\n        // computed\n        // * in the first case sinh is ((e-rec(e))/2)/x\n        // * in the second     sinh is (e/2/x)*e (avoiding undue overflow)\n        // Threshold is Maxlog - Log_2\n        //////////////////////////////////////////////////////////////////////////////\n        A0 x = bs::abs(a0);\n        auto lt1= is_less(x, One<A0>());\n        std::size_t nb = nbtrue(lt1);\n        A0 z = Zero<A0>();\n        if( nb > 0)\n        {\n          z = detail::sinhc_kernel<A0>::compute(sqr(x));\n          if(nb >=A0::static_size) return z;\n        }\n        auto test1 = is_greater(x, Maxlog<A0>()-Log_2<A0>());\n        A0 fac = if_else(test1, Half<A0>(), One<A0>());\n        A0 tmp = exp(x*fac);\n        A0 tmp1 = (Half<A0>()*tmp)/x;\n        A0 r =  if_else(test1, tmp1*tmp, average(tmp, -rec(tmp))/x);\n        #ifndef BOOST_SIMD_NO_INFINITIES\n        r = if_else(is_equal(x, Inf<A0>()), x, r);\n        #endif\n        return if_else(lt1, z, r);\n      }\n   };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "8760778108dbaa2299993c0cb462f846c4fba4db", "size": 3286, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/sinhc.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/simd/function/sinhc.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/simd/function/sinhc.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 38.6588235294, "max_line_length": 100, "alphanum_fraction": 0.5672550213, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4279593752364655}}
{"text": "#include <algorithm>\n#include <unordered_map>\n\n#include <Eigen/QR>\n#include <descriptor-projection/build-projection-matrix.h>\n#include <descriptor-projection/descriptor-projection.h>\n#include <descriptor-projection/flags.h>\n\n#include <vi-map/vertex.h>\n\nnamespace descriptor_projection {\n\n// Compute the covariance of the descriptors, rows are states, columns are\n// samples.\nvoid ComputeCovariance(\n    const Eigen::MatrixXf& data, Eigen::MatrixXf* covariance) {\n  CHECK_NOTNULL(covariance);\n  CHECK_GT(data.cols(), 0) << \"Data must not be empty!\";\n  VLOG(4) << \"Got \" << data.cols()\n          << \" samples to compute the covariance from.\";\n  covariance->setZero(data.rows(), data.rows());\n  constexpr int kBlockSize = 10000;\n  const int num_blocks = data.cols() / kBlockSize + 1;\n  for (int i = 0; i < num_blocks; ++i) {\n    const int block_start = i * kBlockSize;\n    const int block_size =\n        std::min<int>((i + 1) * kBlockSize, data.cols()) - block_start;\n    const Eigen::Block<const Eigen::MatrixXf>& data_block =\n        data.block(0, block_start, data.rows(), block_size);\n\n    const Eigen::MatrixXf centered =\n        data_block.colwise() - data_block.rowwise().mean();\n    double normalizer = std::max(static_cast<int>(data_block.cols() - 1), 1);\n    covariance->noalias() += (centered * centered.adjoint()) / normalizer;\n  }\n  (*covariance) /= num_blocks;\n}\n\nvoid BuildListOfMatchesAndNonMatches(\n    const Eigen::MatrixXf& all_descriptors, const std::vector<Track>& tracks,\n    std::vector<descriptor_projection::DescriptorMatch>* matches,\n    std::vector<descriptor_projection::DescriptorMatch>* non_matches) {\n  CHECK_NOTNULL(matches);\n  CHECK_NOTNULL(non_matches);\n  for (const Track& track : tracks) {\n    // Add pairs of matching descriptors to the list of matches.\n    // TODO(slynen): Consider taking random pairs to not under-estimate the\n    // variance.\n    for (size_t i = 1; i < track.size(); ++i) {\n      matches->emplace_back(track[i - 1], track[i]);\n    }\n  }\n\n  std::random_device device;\n  std::mt19937 generator(device());\n  std::uniform_int_distribution<> distribution(0, all_descriptors.cols() - 1);\n\n  for (size_t i = 1; i < static_cast<size_t>(all_descriptors.cols()) &&\n                     i < matches->size() * 2;\n       ++i) {\n    unsigned int index_a = distribution(generator);\n    unsigned int index_b = distribution(generator);\n    if (index_a == index_b) {\n      continue;\n    }\n    non_matches->emplace_back(index_a, index_b);\n  }\n}\n\nvoid BuildCovarianceMatricesOfMatchesAndNonMatches(\n    unsigned int descriptor_size, const Eigen::MatrixXf& all_descriptors,\n    const std::vector<Track>& tracks, unsigned int* sample_size_matches,\n    unsigned int* sample_size_non_matches, Eigen::MatrixXf* cov_matches,\n    Eigen::MatrixXf* cov_non_matches) {\n  CHECK_NOTNULL(sample_size_matches);\n  CHECK_NOTNULL(sample_size_non_matches);\n  CHECK_NOTNULL(cov_matches);\n  CHECK_NOTNULL(cov_non_matches);\n\n  {  // Scope to limit memory usage.\n    unsigned int too_short_tracks = 0;\n    unsigned int long_enough_tracks = 0;\n    constexpr size_t kMinTrackLength = 5;\n    size_t number_of_used_tracks = 0;\n    Eigen::MatrixXf sumMuMu;\n    sumMuMu.setZero(descriptor_size, descriptor_size);\n\n    std::vector<size_t> descriptors_from_tracks;\n    descriptors_from_tracks.reserve(500);\n\n    // Centering.\n    constexpr int kMaxNumSamples = 50000;\n    for (const Track& track : tracks) {\n      if (track.size() < kMinTrackLength) {\n        ++too_short_tracks;\n        continue;\n      }\n      if (number_of_used_tracks >= kMaxNumSamples) {\n        LOG(WARNING) << \"Truncated descriptors to \" << kMaxNumSamples << \".\";\n        break;\n      }\n      ++long_enough_tracks;\n\n      Eigen::Matrix<float, Eigen::Dynamic, 1> mean;\n      mean.resize(descriptor_size, Eigen::NoChange);\n      mean.setZero();\n\n      for (const size_t& descriptor_idx : track) {\n        descriptors_from_tracks.push_back(descriptor_idx);\n        mean += all_descriptors.block(0, descriptor_idx, descriptor_size, 1);\n      }\n\n      mean /= track.size();\n      CHECK_LE(mean.maxCoeff(), 1.0);\n      CHECK_GE(mean.minCoeff(), 0.0);\n\n      Eigen::MatrixXf mu_sq_current = (mean * mean.transpose()).eval();\n\n      sumMuMu += mu_sq_current * track.size();\n      ++number_of_used_tracks;\n    }\n\n    VLOG(3) << \"Got \" << long_enough_tracks << \" tracks out of \"\n            << tracks.size() << \" (dropped \" << too_short_tracks\n            << \" tracks because they were too short)\";\n\n    CHECK(!descriptors_from_tracks.empty());\n\n    VLOG(3) << \"Computing matches covariance from \"\n            << descriptors_from_tracks.size()\n            << \" matches (descriptor size: \" << descriptor_size << \")\";\n\n    *sample_size_matches = descriptors_from_tracks.size();\n\n    Eigen::MatrixXf matches;\n    matches.resize(descriptor_size, descriptors_from_tracks.size());\n    matches.setZero();\n\n    int matched_idx = 0;\n    for (const size_t& descriptor_idx : descriptors_from_tracks) {\n      matches.block(0, matched_idx, descriptor_size, 1) =\n          all_descriptors.block(0, descriptor_idx, descriptor_size, 1);\n      ++matched_idx;\n    }\n\n    CHECK_GT(descriptors_from_tracks.size(), number_of_used_tracks);\n\n    // Covariance computation for matches.\n    cov_matches->noalias() =\n        (matches * matches.transpose() - sumMuMu) * 2.0 /\n        static_cast<float>(\n            descriptors_from_tracks.size() - number_of_used_tracks);\n  }  // Scope to limit memory usage.\n\n  // Use all descriptors to estimate the non-matching covariance.\n  *sample_size_non_matches = all_descriptors.cols();\n  // Compute sample covariances non matched descriptors.\n  ComputeCovariance(all_descriptors, cov_non_matches);\n\n  *cov_non_matches *= 2.0f;\n}\n\nvoid ComputeProjectionMatrix(\n    const Eigen::MatrixXf& cov_matches, const Eigen::MatrixXf& cov_non_matches,\n    Eigen::MatrixXf* A) {\n  CHECK_NOTNULL(A);\n\n  const int dimensionality = cov_matches.cols();\n  A->resize(dimensionality, dimensionality);\n\n  Eigen::JacobiSVD<Eigen::MatrixXf> svd(cov_matches, Eigen::ComputeFullV);\n\n  CHECK_NE(svd.singularValues().minCoeff(), 0)\n      << \"Rank deficiency for matrix\"\n         \" of samples detected. Probably too little matches.\";\n\n  Eigen::MatrixXf Av =\n      svd.singularValues().cwiseSqrt().cwiseInverse().asDiagonal() *\n      svd.matrixV().transpose();\n\n  Eigen::JacobiSVD<Eigen::MatrixXf> svd_d(\n      Av * cov_non_matches * Av.transpose(), Eigen::ComputeFullV);\n\n  Eigen::MatrixXf singular_values_sqrt_inv =\n      svd_d.singularValues().cwiseSqrt().cwiseInverse().asDiagonal();\n\n  Eigen::MatrixXf eye;\n  eye.resize(dimensionality, dimensionality);\n  eye.setIdentity();\n\n  *A = (eye - singular_values_sqrt_inv) * svd_d.matrixV().transpose() *\n       svd.singularValues().cwiseInverse().asDiagonal() *\n       svd.matrixV().transpose();\n}\n}  // namespace descriptor_projection\n", "meta": {"hexsha": "2d34d324a032d31f7e351d7be0769cc425ecb818", "size": 6840, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithms/loopclosure/descriptor-projection/src/build-projection-matrix.cc", "max_stars_repo_name": "AdronTech/maplab", "max_stars_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1936.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T23:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:24:14.000Z", "max_issues_repo_path": "algorithms/loopclosure/descriptor-projection/src/build-projection-matrix.cc", "max_issues_repo_name": "AdronTech/maplab", "max_issues_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 353.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T18:40:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T15:53:46.000Z", "max_forks_repo_path": "algorithms/loopclosure/descriptor-projection/src/build-projection-matrix.cc", "max_forks_repo_name": "AdronTech/maplab", "max_forks_repo_head_hexsha": "1340e01466fc1c02994860723b8117daf9ad226d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 661.0, "max_forks_repo_forks_event_min_datetime": "2017-11-28T07:20:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:06:29.000Z", "avg_line_length": 34.8979591837, "max_line_length": 79, "alphanum_fraction": 0.6830409357, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.42791143737042575}}
{"text": "#include \"utils.h\"\n#include \"hard_clustering.h\"\n#include <boost/random/discrete_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\nusing namespace std;\n\nCUGMMLite::CUGMMLite(AdaHardCluster& mdl_,\n                     unsigned long int dim_)\n    : copt::BoundedProblem<double>(2),\n      mdl(mdl_),\n      dim(dim_),\n      k(mdl_.get_k()),\n      mu(mdl_.get_mu()),\n      m2(mdl_.get_m2()),\n      m4(mdl_.get_m4()){\n}\n\ndouble CUGMMLite::value(const copt::Vector<double>& x) {\n  // x = <alpha,kappa>\n  double obj = 0.0;\n  double alpha = x[0];\n  double kappa = x[1];\n  double var = 0.0;\n  for (size_t c = 0; c < k; ++c) {\n    var = mdl.variance(mu[c][dim],alpha,dim);\n    obj += (pow(m2[c][dim] - kappa*var,2)\n      )/(m4[c][dim] - 2*m2[c][dim]*kappa*var + pow(kappa*var,2));\n  }\n  return obj;\n}\n\nvoid CUGMMLite::gradient(const copt::Vector<double>& x,\n                         copt::Vector<double>& grad) {\n  double alpha = x[0];\n  double kappa = x[1];\n  double var = 0.0;\n  double diff_var = 0.0;\n  grad[0] = 0.0;\n  grad[1] = 0.0;\n  double coef = 0.0;\n  for (size_t c = 0; c < k; ++c){\n    var = mdl.variance(mu[c][dim],alpha,dim);\n    diff_var = mdl.diff_variance(mu[c][dim],alpha,dim);\n    coef = (2*(pow(m2[c][dim],2)-m4[c][dim])*(m2[c][dim] - kappa*var)\n      )/pow(m4[c][dim] - 2*m2[c][dim]*kappa*var + pow(kappa*var,2),2);\n    grad[0] += coef*kappa*diff_var;\n    grad[1] += coef*var;\n  }\n}\n\nAdaHardCluster::AdaHardCluster(const vector<vector<double>>& data_,\n                       const vector<unsigned long int>& label_,\n                       unsigned long int max_round_, unsigned long int k_)\n    : data(data_), label(label_) {\n  max_round = max_round_;\n  k = k_;\n  nmis.resize(max_round);\n  fill(nmis.begin(), nmis.end(), 0);\n  logliks.resize(max_round);\n  fill(logliks.begin(), logliks.end(), -numeric_limits<double>::max());\n  n_samples = data.size();\n  n_dims = data[0].size();\n  count.resize(k);\n  kappa.resize(n_dims);\n  kappa_a.resize(n_dims);\n  kappa_b.resize(n_dims);\n  mu.resize(k);\n  mu_a.resize(k);\n  mu_b.resize(k);\n  m2.resize(k);\n  m4.resize(k);\n  v.resize(k);\n  w_inv.resize(k);\n  for (size_t c = 0; c < k; ++c){\n    mu[c].resize(n_dims);\n    mu_a[c].resize(n_dims);\n    mu_b[c].resize(n_dims);\n    m2[c].resize(n_dims);\n    m4[c].resize(n_dims);\n    v[c].resize(n_dims);\n    w_inv[c].resize(n_dims);\n  }\n  asg.resize(n_samples);\n  attr_discrete.resize(n_dims);\n  attr_positive.resize(n_dims);\n  attr_nonnegative.resize(n_dims);\n\n  alpha.resize(n_dims);\n  lb.resize(n_dims);\n  ub.resize(n_dims);\n  for (unsigned long int j = 0; j < n_dims; ++j) {\n    attr_discrete[j] = is_discrete(data, j);\n    attr_positive[j] = is_positive(data, j);\n    attr_nonnegative[j] = attr_positive[j];\n    if (!attr_positive[j]) attr_nonnegative[j] = is_nonnegative(data, j);\n  }\n  for (unsigned long int j = 0; j < n_dims; ++j) {\n    if (attr_discrete[j]) {\n      if (attr_nonnegative[j]) {\n        alpha[j] = 1;\n        lb[j] = 0;\n        // ub[j] = numeric_limits<double>::max();\n        ub[j] = 10;\n      } else {\n        alpha[j] = 1;\n        lb[j] = 0;\n        // ub[j] = numeric_limits<double>::max();\n        ub[j] = 10;\n      }\n    } else {\n      if (attr_positive[j]) {\n        alpha[j] = 0;\n        // lb[j] = -numeric_limits<double>::max();\n        lb[j] = -10;\n        ub[j] = 2;\n      } else if (attr_nonnegative[j]) {\n        alpha[j] = 0.5;\n        lb[j] = 0;\n        ub[j] = 1;\n      } else {\n        alpha[j] = 1;\n        lb[j] = 0;\n        // ub[j] = numeric_limits<double>::max();\n        ub[j] = 10;\n      }\n    }\n  }\n}\n\ndouble AdaHardCluster::distance(const vector<double>& x,\n                                const unsigned long int c) {\n  double dist = 0.0;\n  for (unsigned long int j = 0; j < n_dims; ++j)\n    dist += pow(pow(x[j],2) - kappa[j]*v[c][j],2)*w_inv[c][j];\n  return dist;\n}\n\ndouble AdaHardCluster::variance(const double x,\n                                const double alpha,\n                                const unsigned long int dim){\n  // return nnc_variance(x, alpha);\n  if (attr_discrete[dim]){\n    if (attr_nonnegative[dim])\n      return nnd_variance(x, alpha);\n    else\n      return rc_variance(x, alpha);\n  } else {\n    if (attr_nonnegative[dim])\n      return nnc_variance(x, alpha);\n    else\n      return rc_variance(x, alpha);\n  }\n}\n\n\ndouble AdaHardCluster::diff_variance(const double x,\n                                 const double alpha,\n                                 const unsigned long int dim) {\n  // return nnc_diff_variance(x, alpha);\n  if (attr_discrete[dim]){\n    if (attr_nonnegative[dim])\n      return nnd_diff_variance(x, alpha);\n    else\n      return rc_diff_variance(x, alpha);\n  } else {\n    if (attr_nonnegative[dim])\n      return nnc_diff_variance(x, alpha);\n    else\n      return rc_diff_variance(x, alpha);\n  }\n}\n\nunsigned long int AdaHardCluster::get_k() { return k; }\n\nunsigned long int AdaHardCluster::get_max_round() { return max_round; }\n\nunsigned long int AdaHardCluster::get_n_dims() { return n_dims; }\n\nunsigned long int AdaHardCluster::get_n_samples() { return n_samples; }\n\nvector<double>& AdaHardCluster::get_kappa() { return kappa; }\n\nvector<double>& AdaHardCluster::get_logliks() { return logliks; }\n\nvector<double>& AdaHardCluster::get_nmis() { return nmis; }\n\ncopt::Vector<double>& AdaHardCluster::get_alpha() { return alpha; }\n\ncopt::Vector<double>& AdaHardCluster::get_lb() { return lb; }\n\ncopt::Vector<double>& AdaHardCluster::get_ub() { return ub; }\n\nconst vector<vector<double>>& AdaHardCluster::get_data() { return data; }\n\nvector<vector<double>>& AdaHardCluster::get_mu() { return mu; }\n\nvector<vector<double>>& AdaHardCluster::get_m2() { return m2; }\n\nvector<vector<double>>& AdaHardCluster::get_m4() { return m4; }\n\nvoid AdaHardCluster::initialize_random() {\n  unsigned long int ri;\n  for (size_t c = 0; c < k; ++c) {\n    ri = rand() % n_samples;\n    for (unsigned long int j = 0; j < n_dims; ++j){\n      mu[c][j] = data[ri][j];\n      mu_a[c][j] = 0;//mu[c][j];\n      mu_b[c][j] = 1.0;\n    }\n  }\n  for (unsigned long int j = 0; j < n_dims; ++j){\n    kappa[j] = 1.0;\n    kappa_a[j] = 1e-9;\n    kappa_b[j] = 1.0;\n  }\n}\n\nvoid AdaHardCluster::initialize_k_plus_plus() {\n  boost::mt19937 gen;\n  unsigned long int ri, k_eff;\n  ri = rand() % n_samples;\n  for (unsigned long int j = 0; j < n_dims; ++j) mu[0][j] = data[ri][j];\n  k_eff = 1;\n  vector<double> probs(n_samples, 0);\n  double dist = 0;\n  double best_dist = 0;\n  unsigned long int best_asg = -1;\n  unsigned long int cur_asg = -1;\n  do {\n    for (size_t i = 0; i < n_samples; ++i) {\n      best_dist = numeric_limits<double>::max();\n      for (size_t c = 0; c < k_eff; ++c) {\n        dist = 0;\n        for (unsigned long int j = 0; j < n_dims; ++j){\n          // dist += distance(data[i][j], mu[c][j], alpha[j], j);\n          dist += pow(data[i][j] - mu[c][j], 2);\n        }\n        if (dist < best_dist) best_dist = dist;\n      }\n      probs[i] = pow(best_dist, 2);\n    }\n    boost::random::discrete_distribution<> dist(probs.begin(), probs.end());\n    ri = dist(gen);\n    for (unsigned long int j = 0; j < n_dims; ++j) mu[k_eff][j] = data[ri][j];\n    k_eff += 1;\n  } while (k_eff != k);\n\n  for (unsigned long int j = 0; j < n_dims; ++j)\n    if (attr_nonnegative[j])\n      for (size_t c = 0; c < k_eff; ++c)\n        if (mu[c][j] == 0)\n          mu[c][j] = 1e-9;\n  for (unsigned long int j = 0; j < n_dims; ++j){\n    kappa[j] = 1.0;\n    kappa_a[j] = 1.0;\n    kappa_b[j] = 1.0;\n  }\n  for (size_t c = 0; c < k_eff; ++c)\n    for (unsigned long int j = 0; j < n_dims; ++j){\n      mu_a[c][j] = mu[c][j];\n      mu_b[c][j] = 1.0;\n    }\n  for (size_t i = 0; i < n_samples; ++i) {\n    best_dist = numeric_limits<double>::max();\n    best_asg = -1;\n    for (size_t c = 0; c < k; ++c) {\n      dist = 0.0;\n      for (size_t j = 0; j < n_dims; ++j)\n        dist += pow(data[i][j] - mu[c][j], 2);\n      if (dist < best_dist) {\n        best_dist = dist;\n        best_asg = c;\n      }\n    }\n    asg[i] = best_asg;\n  }\n  for (size_t c = 0; c < k; c++){\n    fill(mu[c].begin(), mu[c].end(), 1e-9);\n    fill(m2[c].begin(), m2[c].end(), 1e-9);\n    fill(m4[c].begin(), m4[c].end(), 1e-9);\n  }\n  fill(count.begin(), count.end(), 0);\n  for (size_t i = 0; i < n_samples; ++i) {\n    cur_asg = asg[i];\n    count[cur_asg] += 1;\n    for (size_t j = 0; j < n_dims; ++j){\n      mu[cur_asg][j] += data[i][j];\n      m2[cur_asg][j] += pow(data[i][j],2);\n      m4[cur_asg][j] += pow(data[i][j],4);\n    }\n  }\n  for (size_t c = 0; c < k; c++)\n    for (size_t j = 0; j < n_dims; ++j){\n      mu[c][j] = (kappa[j]*mu_a[c][j] + mu[c][j]\n                  )/(kappa[j]*mu_b[c][j] + count[c]);\n      m2[c][j] = (kappa[j]*pow(mu_a[c][j],2) + m2[c][j]\n                  )/(kappa[j]*mu_b[c][j] + count[c]);\n      m4[c][j] = (kappa[j]*pow(mu_a[c][j],4) + m4[c][j]\n                  )/(kappa[j]*mu_b[c][j] + count[c]);\n      v[c][j] = variance(mu[c][j],alpha[j],j);\n      w_inv[c][j] = (kappa[j]*mu_b[c][j] + count[c]\n        ) / (m4[c][j] - 2*m2[c][j]*kappa[j]*v[c][j] + pow(kappa[j]*v[c][j],2));\n    }\n}\n\nvoid AdaHardCluster::fit() {\n  bool updated = 0;\n  double inertia = 0;\n  double nmi = 0;\n  double dist = 0;\n  double best_dist = 0;\n  unsigned long int best_asg = -1;\n  unsigned long int cur_asg = -1;\n  for (size_t r = 0; r < max_round; r++) {\n    updated = 0;\n    inertia = 0.0;\n    for (size_t i = 0; i < n_samples; ++i) {\n      best_dist = numeric_limits<double>::max();\n      best_asg = -1;\n      for (size_t c = 0; c < k; ++c) {\n        dist = distance(data[i], c);\n        if (dist < best_dist) {\n          best_dist = dist;\n          best_asg = c;\n        }\n      }\n      if (asg[i] != best_asg) {\n        asg[i] = best_asg;\n        updated = 1;\n      }\n      inertia += best_dist;\n    }\n    nmi = calc_nmi(label, asg);\n    nmis[r] = nmi;\n    if (!updated) break;\n\n    for (size_t c = 0; c < k; c++){\n      fill(mu[c].begin(), mu[c].end(), 1e-9);\n      fill(m2[c].begin(), m2[c].end(), 1e-9);\n      fill(m4[c].begin(), m4[c].end(), 1e-9);\n    }\n    fill(count.begin(), count.end(), 0);\n    for (size_t i = 0; i < n_samples; ++i) {\n      cur_asg = asg[i];\n      count[cur_asg] += 1;\n      for (size_t j = 0; j < n_dims; ++j){\n        mu[cur_asg][j] += data[i][j];\n        m2[cur_asg][j] += pow(data[i][j],2);\n        m4[cur_asg][j] += pow(data[i][j],4);\n      }\n    }\n    for (size_t c = 0; c < k; c++)\n      for (size_t j = 0; j < n_dims; ++j){\n        mu[c][j] = (kappa[j]*mu_a[c][j] + mu[c][j]\n                    )/(kappa[j]*mu_b[c][j] + count[c]);\n        m2[c][j] = (kappa[j]*pow(mu_a[c][j],2) + m2[c][j]\n                    )/(kappa[j]*mu_b[c][j] + count[c]);\n        m4[c][j] = (kappa[j]*pow(mu_a[c][j],4) + m4[c][j]\n                    )/(kappa[j]*mu_b[c][j] + count[c]);\n        v[c][j] = variance(mu[c][j],alpha[j],j);\n        w_inv[c][j] = (kappa[j]*mu_b[c][j] + count[c]\n          ) / (m4[c][j] - 2*m2[c][j]*kappa[j]*v[c][j] + pow(kappa[j]*v[c][j],2));\n      }\n    double obj = 0;\n    for (size_t j = 0; j < n_dims; ++j){\n      CUGMMLite prblm(*this, j);\n      copt::Vector<double> lbj;\n      lbj.resize(2);\n      lbj[0] = lb[j];\n      lbj[1] = 1e-9;\n      prblm.setLowerBound(lbj);\n      copt::Vector<double> ubj;\n      ubj.resize(2);\n      ubj[0] = ub[j];\n      ubj[1] = numeric_limits<double>::max();\n      prblm.setUpperBound(ubj);\n      copt::Vector<double> xj;\n      xj.resize(2);\n      xj[0] = alpha[j];\n      xj[1] = kappa[j];\n      copt::LbfgsbSolver<CUGMMLite> solver;\n      solver.minimize(prblm, xj);\n      obj += prblm.value(xj);\n      if (!isnan(xj[0]))\n        alpha[j] = xj[0];\n      if (!isnan(xj[1]))\n        kappa[j] = xj[1];\n    }\n    cout << \"round=\" << r << \" nmi=\" << nmi << \" inertia=\" << inertia;\n    cout << \" obj=\" << obj << endl;\n  }\n  cout << \"Alpha=\";\n  for (unsigned long int j = 0; j < n_dims; ++j)\n      cout << alpha[j] << \" \";\n  cout << endl;\n  cout << \"Kappa=\";\n  for (unsigned long int j = 0; j < n_dims; ++j)\n      cout << kappa[j] << \" \";\n  cout << endl;\n  for (size_t c = 0; c < k; ++c){\n    cout << \"mu[\" << c << \"]=\";\n    for (unsigned long int j = 0; j < n_dims; ++j)\n        cout << mu[c][j] << \" \";\n    cout << endl;\n  }\n}\n", "meta": {"hexsha": "2e3639ff62369681b5178ef6c6c697de1adb6b09", "size": 12103, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/hard_clustering.cc", "max_stars_repo_name": "mehmetbasbug/adacluster", "max_stars_repo_head_hexsha": "7195a4476a8d8dfef37d43703af9b9bee3059fbe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-10-19T14:37:41.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-14T21:44:43.000Z", "max_issues_repo_path": "src/hard_clustering.cc", "max_issues_repo_name": "mehmetbasbug/adacluster", "max_issues_repo_head_hexsha": "7195a4476a8d8dfef37d43703af9b9bee3059fbe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hard_clustering.cc", "max_forks_repo_name": "mehmetbasbug/adacluster", "max_forks_repo_head_hexsha": "7195a4476a8d8dfef37d43703af9b9bee3059fbe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6642156863, "max_line_length": 81, "alphanum_fraction": 0.5268115343, "num_tokens": 4093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.42784242652248816}}
{"text": "// Copyright 2021 RoboJackets\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n// BEGIN STUDENT CODE\n\n#ifndef KALMAN_FILTER_HPP_\n#define KALMAN_FILTER_HPP_\n\n#include <Eigen/Dense>\n\nnamespace mineral_deposit_tracking\n{\n\ntemplate<int StateSize>\nclass KalmanFilter\n{\npublic:\n  using VectorType = Eigen::Matrix<double, StateSize, 1>;\n  using MatrixType = Eigen::Matrix<double, StateSize, StateSize>;\n\n  KalmanFilter(\n    const MatrixType & transition_matrix,\n    const MatrixType & process_covariance,\n    const MatrixType & observation_matrix)\n  : transition_matrix_(transition_matrix),\n    process_covariance_(process_covariance),\n    observation_matrix_(observation_matrix),\n    estimate_(VectorType::Zero()),\n    estimate_covariance_(MatrixType::Identity() * 500)\n  {\n  }\n\n  void Reset(const VectorType & initial_state, const MatrixType & initial_covariance)\n  {\n    estimate_ = initial_state;\n    estimate_covariance_ = initial_covariance;\n  }\n\n  void TimeUpdate()\n  {\n    estimate_ = transition_matrix_ * estimate_;\n    estimate_covariance_ = transition_matrix_ * estimate_covariance_ *\n      transition_matrix_.transpose() + process_covariance_;\n  }\n\n  void MeasurementUpdate(\n    const VectorType & measurement,\n    const MatrixType & measurement_covariance)\n  {\n    const MatrixType innovation_covariance =\n      (observation_matrix_ * estimate_covariance_ * observation_matrix_.transpose()) +\n      measurement_covariance;\n\n    const MatrixType gain = estimate_covariance_ * observation_matrix_.transpose() *\n      innovation_covariance.inverse();\n\n    estimate_ = estimate_ + (gain * (measurement - (observation_matrix_ * estimate_)));\n\n    const MatrixType tmp = MatrixType::Identity() - (gain * observation_matrix_);\n\n    estimate_covariance_ = (tmp * estimate_covariance_ * tmp.transpose()) +\n      (gain * measurement_covariance * gain.transpose());\n  }\n\n  const VectorType & GetEstimate() const\n  {\n    return estimate_;\n  }\n\n  const MatrixType & GetEstimateCovariance() const\n  {\n    return estimate_covariance_;\n  }\n\nprivate:\n  const MatrixType transition_matrix_;\n  const MatrixType process_covariance_;\n  const MatrixType observation_matrix_;\n  VectorType estimate_;\n  MatrixType estimate_covariance_;\n};\n\n}  // namespace mineral_deposit_tracking\n\n#endif  // KALMAN_FILTER_HPP_\n\n// END STUDENT CODE\n", "meta": {"hexsha": "675ef970fdd56001ca8216163dbc46245210b238", "size": 3342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "reference_solutions/mineral_deposit_tracking/src/kalman_filter.hpp", "max_stars_repo_name": "abhiramg2021/RoboJackets", "max_stars_repo_head_hexsha": "48c75c95528a01f67a08e979758b7963b7570c75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 177.0, "max_stars_repo_stars_event_min_datetime": "2015-09-28T20:31:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T23:20:56.000Z", "max_issues_repo_path": "reference_solutions/mineral_deposit_tracking/src/kalman_filter.hpp", "max_issues_repo_name": "robinzx117/software-training", "max_issues_repo_head_hexsha": "eda20e80a8a95bb46694325c5f3755909b883fd5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 89.0, "max_issues_repo_issues_event_min_datetime": "2016-09-24T21:52:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-21T03:36:31.000Z", "max_forks_repo_path": "reference_solutions/mineral_deposit_tracking/src/kalman_filter.hpp", "max_forks_repo_name": "robinzx117/software-training", "max_forks_repo_head_hexsha": "eda20e80a8a95bb46694325c5f3755909b883fd5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 252.0, "max_forks_repo_forks_event_min_datetime": "2015-09-21T20:58:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T09:31:35.000Z", "avg_line_length": 31.8285714286, "max_line_length": 87, "alphanum_fraction": 0.7552363854, "num_tokens": 720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.721743206297598, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4277530921163462}}
{"text": "/******************************************************************************\n * Copyright (c) 2015 - 2016 Philipp Schubert.                                *\n * All rights reserved. This program and the accompanying materials are made  *\n * available under the terms of LICENSE.txt.                                  *\n *                                                                            *\n * Contributors:                                                              *\n *     Philipp Schubert                                                       *\n *****************************************************************************/\n\n/**\n * @file pseudoinverse.cpp\n * @brief Enthält die Implementation der Datei pseudoinverse.hh.\n *\n * Hier wird der Prototyp zur Berechnung eines Pseudoinversen einer\n * Dreiecksmatrix implementiert.\n *\n * @author Philipp D. Schubert\n * @bug Keine Bugs bekannt.\n */\n\n#include <armadillo>\n#include <omp.h>\n#include <stdlib.h>\n#include <string.h>\n#include <typeinfo>\n\nextern \"C\" {\n#include \"m.h\"\n#include \"tm.h\"\n#include \"utils.h\"\n}\n\nextern \"C\" tm_t *pseudoinverse(const tm_t *t) {\n  m_t *m = initM(t->size, t->size);\n  unsigned int i, j;\n#pragma omp parallel for shared(t, m) private(i, j) schedule(dynamic)\n  for (i = 0; i < t->size; ++i) {\n    for (j = 0; j < t->size; ++j) {\n      m->elems[i * t->size + j] = (j <= i) ? t->elems[(i * (i + 1)) / 2 + j]\n                                           : t->elems[(j * (j + 1)) / 2 + i];\n    }\n  }\n  // check if we should use single or double precision and use adequate\n  // armadillo data structures\n  if (typeid(real_t).name() == typeid(float).name()) {\n    arma::fmat f_am =\n        arma::fmat((float *)m->elems, t->size, t->size, false, false);\n    arma::fmat f_inverse = arma::pinv(f_am);\n    // caution: override data memory of m\n    memcpy(m->elems, f_inverse.memptr(), t->size * t->size * sizeof(real_t));\n  } else {\n    arma::mat d_am =\n        arma::mat((double *)m->elems, t->size, t->size, false, false);\n    arma::mat d_inverse = arma::pinv(d_am);\n    // caution: override data memory of m\n    memcpy(m->elems, d_inverse.memptr(), t->size * t->size * sizeof(real_t));\n  }\n  tm_t *result = initTM(t->size);\n#pragma omp parallel for shared(result, m) private(i, j) schedule(dynamic)\n  for (i = 0; i < t->size; ++i) {\n    for (j = 0; j <= i; ++j) {\n      result->elems[(i * (i + 1)) / 2 + j] = m->elems[i * t->size + j];\n    }\n  }\n  free(m);\n  return result;\n}\n", "meta": {"hexsha": "2cf06548bf3d190d7e99aa8e88edbdf747c977a4", "size": 2456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pseudoinverse.cpp", "max_stars_repo_name": "pdschubert/mds_c", "max_stars_repo_head_hexsha": "bfc931ebbbfd101deac9e6e53a8f7af118b4d3ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-08-29T09:05:04.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-03T21:34:00.000Z", "max_issues_repo_path": "src/pseudoinverse.cpp", "max_issues_repo_name": "pdschubert/mds_c", "max_issues_repo_head_hexsha": "bfc931ebbbfd101deac9e6e53a8f7af118b4d3ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pseudoinverse.cpp", "max_forks_repo_name": "pdschubert/mds_c", "max_forks_repo_head_hexsha": "bfc931ebbbfd101deac9e6e53a8f7af118b4d3ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1176470588, "max_line_length": 79, "alphanum_fraction": 0.4930781759, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.427753085021891}}
{"text": "//  Created by jimmy on 2016-06-14.\n//  Copyright © 2016 jimmy. All rights reserved.\n//\n\n#ifndef __Kabsch__\n#define __Kabsch__\n\n// This code is modifed from released in public domain from\n// https://github.com/oleg-alexandrov/projects/blob/master/eigen/Kabsch.cpp\n\n#include <Eigen/Geometry>\n\n// This is general Kabsh algorithm,\n// The input 3D points are stored as columns.\nEigen::Affine3d Find3DAffineTransform(Eigen::Matrix3Xd input_pts, Eigen::Matrix3Xd output_pts);\n\n// This is Kabsh algorithm for camera pose estimation\n// Assume the points in camera coordiantes and world coordinates have same scale\n// The input 3D points are stored as columns. No scale effect\nEigen::Affine3d Find3DAffineTransformSameScale(Eigen::Matrix3Xd input_pts, Eigen::Matrix3Xd output_pts);\n\n\n\n\n#endif /* __Kabsch__ */\n", "meta": {"hexsha": "785c7fae1639e1d4daa37afbd2b17131fb7464ac", "size": 801, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pose_estimation/Kabsch.hpp", "max_stars_repo_name": "LiliMeng/btrf", "max_stars_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-28T15:24:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T13:51:05.000Z", "max_issues_repo_path": "src/pose_estimation/Kabsch.hpp", "max_issues_repo_name": "LiliMeng/btrf", "max_issues_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pose_estimation/Kabsch.hpp", "max_forks_repo_name": "LiliMeng/btrf", "max_forks_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-11-08T16:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-21T03:40:02.000Z", "avg_line_length": 30.8076923077, "max_line_length": 104, "alphanum_fraction": 0.7752808989, "num_tokens": 213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.427753085021891}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_UTIL_MATH_HPP\n#define BOOST_GEOMETRY_UTIL_MATH_HPP\n\n#include <cmath>\n#include <limits>\n\n#include <boost/math/constants/constants.hpp>\n\n#include <boost/geometry/util/select_most_precise.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace math\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\n\ntemplate <typename Type, bool IsFloatingPoint>\nstruct equals\n{\n    static inline bool apply(Type const& a, Type const& b)\n    {\n        return a == b;\n    }\n};\n\ntemplate <typename Type>\nstruct equals<Type, true>\n{\n    static inline bool apply(Type const& a, Type const& b)\n    {\n        // See http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.17,\n        // FUTURE: replace by some boost tool or boost::test::close_at_tolerance\n        return std::abs(a - b) <= std::numeric_limits<Type>::epsilon() * std::abs(a);\n    }\n};\n\n\ntemplate <typename Type, bool IsFloatingPoint> \nstruct equals_with_epsilon : public equals<Type, IsFloatingPoint> {};\n\n\n/*!\n\\brief Short construct to enable partial specialization for PI, currently not possible in Math.\n*/\ntemplate <typename T>\nstruct define_pi\n{\n    static inline T apply()\n    {\n        // Default calls Boost.Math\n        return boost::math::constants::pi<T>();\n    }\n};\n\n\n} // namespace detail\n#endif\n\n\ntemplate <typename T>\ninline T pi() { return detail::define_pi<T>::apply(); }\n\n\n// Maybe replace this by boost equals or boost ublas numeric equals or so\n\n/*!\n    \\brief returns true if both arguments are equal.\n    \\ingroup utility\n    \\param a first argument\n    \\param b second argument\n    \\return true if a == b\n    \\note If both a and b are of an integral type, comparison is done by ==.\n    If one of the types is floating point, comparison is done by abs and\n    comparing with epsilon. If one of the types is non-fundamental, it might\n    be a high-precision number and comparison is done using the == operator\n    of that class.\n*/\n\ntemplate <typename T1, typename T2>\ninline bool equals(T1 const& a, T2 const& b)\n{\n    typedef typename select_most_precise<T1, T2>::type select_type;\n    return detail::equals\n        <\n            select_type,\n            boost::is_floating_point<select_type>::type::value\n        >::apply(a, b);\n}\n\ntemplate <typename T1, typename T2>\ninline bool equals_with_epsilon(T1 const& a, T2 const& b)\n{\n    typedef typename select_most_precise<T1, T2>::type select_type;\n    return detail::equals_with_epsilon\n        <\n            select_type, \n            boost::is_floating_point<select_type>::type::value\n        >::apply(a, b);\n}\n\n\n\ndouble const d2r = geometry::math::pi<double>() / 180.0;\ndouble const r2d = 1.0 / d2r;\n\n/*!\n    \\brief Calculates the haversine of an angle\n    \\ingroup utility\n    \\note See http://en.wikipedia.org/wiki/Haversine_formula\n    haversin(alpha) = sin2(alpha/2)\n*/\ntemplate <typename T>\ninline T hav(T const& theta)\n{\n    T const half = T(0.5);\n    T const sn = sin(half * theta);\n    return sn * sn;\n}\n\n/*!\n\\brief Short utility to return the square\n\\ingroup utility\n\\param value Value to calculate the square from\n\\return The squared value\n*/\ntemplate <typename T>\ninline T sqr(T const& value)\n{\n    return value * value;\n}\n\n\n/*!\n\\brief Short utility to workaround gcc/clang problem that abs is converting to integer\n\\ingroup utility\n*/\ntemplate<typename T>\ninline T abs(const T& t)\n{\n    using std::abs;\n    return abs(t);\n}\n\n\n} // namespace math\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_UTIL_MATH_HPP\n", "meta": {"hexsha": "edd9ab0d3509620e98ca5c16c9dcdce5ff0f0630", "size": 4051, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/boost_1_47_0/boost/geometry/util/math.hpp", "max_stars_repo_name": "zigaosolin/Raytracer", "max_stars_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T14:37:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-25T07:38:07.000Z", "max_issues_repo_path": "external/boost_1_47_0/boost/geometry/util/math.hpp", "max_issues_repo_name": "zigaosolin/Raytracer", "max_issues_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2016-01-11T05:20:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T11:37:24.000Z", "max_forks_repo_path": "external/boost_1_47_0/boost/geometry/util/math.hpp", "max_forks_repo_name": "zigaosolin/Raytracer", "max_forks_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-01-05T15:10:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T04:59:16.000Z", "avg_line_length": 23.9704142012, "max_line_length": 95, "alphanum_fraction": 0.6921747717, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.42774322500338074}}
{"text": "#ifndef SKYLARK_WZT_HPP\n#define SKYLARK_WZT_HPP\n\n#ifndef SKYLARK_SKETCH_HPP\n#error \"Include top-level sketch.hpp instead of including individuals headers\"\n#endif\n\n#include <boost/random.hpp>\n\nnamespace skylark { namespace sketch {\n\n/**\n * Woodruff-Zhang Transform (data)\n *\n * Woodruff-Zhang Transform is very similar to the Clarkson-Woodruff Transform:\n * it replaces the +1/-1 diagonal with reciprocal exponentia random enteries. \n * It is sutiable for lp regression with 1 <= p <= 2.\n *\n * Reference:\n * D. Woodruff and Q. Zhang\n * Subspace Embeddings and L_p Regression Using Exponential Random\n * COLT 2013\n *\n * TODO current implementation is only one sketch index, when for 1 <= p <= 2\n *      you want more than one.\n */\n\ntemplate < typename InputMatrixType,\n           typename OutputMatrixType = InputMatrixType >\nstruct WZT_t :\n        public WZT_data_t,\n        virtual public sketch_transform_t<InputMatrixType, OutputMatrixType > {\n\npublic:\n\n    // We use composition to defer calls to hash_transform_t\n    typedef hash_transform_t< InputMatrixType, OutputMatrixType,\n                              boost::random::uniform_int_distribution,\n                              boost::random::exponential_distribution > transform_t;\n\n    typedef WZT_data_t data_type;\n    typedef data_type::params_t params_t;\n\n    WZT_t(int N, int S, double p, base::context_t& context)\n        : data_type(N, S, p, context), _transform(*this) {\n\n    }\n\n    WZT_t(int N, int S, const params_t& params, base::context_t& context)\n        : data_type(N, S, params, context),\n          _transform(*this) {\n\n    }\n\n    WZT_t(const boost::property_tree::ptree &pt)\n        : data_type(pt), _transform(*this) {\n\n    }\n\n    template< typename OtherInputMatrixType,\n              typename OtherOutputMatrixType >\n    WZT_t(const WZT_t<OtherInputMatrixType,OtherOutputMatrixType>& other)\n        : data_type(other), _transform(*this) {\n\n    }\n\n    WZT_t(const data_type& other)\n        : data_type(other), _transform(*this) {\n\n    }\n\n    /**\n     * Apply columnwise the sketching transform that is described by the\n     * the transform with output sketch_of_A.\n     */\n    void apply (const typename transform_t::matrix_type& A,\n                typename transform_t::output_matrix_type& sketch_of_A,\n                columnwise_tag dimension) const {\n        _transform.apply(A, sketch_of_A, dimension);\n    }\n\n    /**\n     * Apply rowwise the sketching transform that is described by the\n     * the transform with output sketch_of_A.\n     */\n    void apply (const typename transform_t::matrix_type& A,\n                typename transform_t::output_matrix_type& sketch_of_A,\n                rowwise_tag dimension) const {\n        _transform.apply(A, sketch_of_A, dimension);\n    }\n\n    int get_N() const { return this->_N; } /**< Get input dimesion. */\n    int get_S() const { return this->_S; } /**< Get output dimesion. */\n\n    const sketch_transform_data_t* get_data() const { return this; }\n\nprivate:\n    transform_t _transform;\n};\n\ntemplate<>\nclass WZT_t<boost::any, boost::any> :\n  public WZT_data_t,\n  virtual public sketch_transform_t<boost::any, boost::any > {\n\npublic:\n\n    typedef WZT_data_t data_type;\n    typedef data_type::params_t params_t;\n\n    WZT_t(int N, int S, double p, base::context_t& context)\n        : data_type(N, S, p, context) {\n\n    }\n\n    WZT_t(int N, int S, const params_t& params, base::context_t& context)\n        : data_type(N, S, params, context) {\n\n    }\n\n\n    WZT_t(const boost::property_tree::ptree &pt)\n        : data_type(pt) {\n\n    }\n\n    /**\n     * Copy constructor\n     */\n    template <typename OtherInputMatrixType,\n              typename OtherOutputMatrixType>\n    WZT_t (const WZT_t<OtherInputMatrixType, OtherOutputMatrixType>& other)\n        : data_type(other) {\n\n    }\n\n    /**\n     * Constructor from data\n     */\n    WZT_t (const data_type& other)\n        : data_type(other) {\n\n    }\n\n    /**\n     * Apply columnwise the sketching transform that is described by the\n     * the transform with output sketch_of_A.\n     */\n    void apply(const boost::any &A, const boost::any &sketch_of_A,\n                columnwise_tag dimension) const {\n\n#if     !(defined SKYLARK_NO_ANY) || (defined SKYLARK_WITH_WZT_ANY)\n\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::matrix_t, mdtypes::matrix_t,\n            WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::sparse_matrix_t,\n            mdtypes::matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::sparse_matrix_t,\n            mdtypes::sparse_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::shared_matrix_t,\n            mdtypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::root_matrix_t,\n            mdtypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n            mdtypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n            mdtypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n            mdtypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n            mdtypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n            mdtypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n            mdtypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n            mdtypes::dist_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n            mdtypes::dist_matrix_vc_star_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n            mdtypes::dist_matrix_vr_star_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_star_vc_t,\n            mdtypes::dist_matrix_star_vc_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_star_vr_t,\n            mdtypes::dist_matrix_star_vr_t, WZT_t);\n\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::matrix_t, mftypes::matrix_t,\n            WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::sparse_matrix_t,\n            mftypes::matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::sparse_matrix_t,\n            mftypes::sparse_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::shared_matrix_t,\n            mftypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::root_matrix_t,\n            mftypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_t,\n            mftypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_t,\n            mftypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n            mftypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n            mftypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n            mftypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n            mftypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_t,\n            mftypes::dist_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n            mftypes::dist_matrix_vc_star_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n            mftypes::dist_matrix_vr_star_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_star_vc_t,\n            mftypes::dist_matrix_star_vc_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_star_vr_t,\n            mftypes::dist_matrix_star_vr_t, WZT_t);\n\n#endif\n\n        SKYLARK_THROW_EXCEPTION (\n          base::sketch_exception()\n              << base::error_msg(\n                 \"This combination has not yet been implemented for WZT\"));\n\n    }\n\n    /**\n     * Apply rowwise the sketching transform that is described by the\n     * the transform with output sketch_of_A.\n     */\n    void apply (const boost::any &A, const boost::any &sketch_of_A,\n        rowwise_tag dimension) const {\n\n#if     !(defined SKYLARK_NO_ANY) || (defined SKYLARK_WITH_WZT_ANY)\n\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::matrix_t, mdtypes::matrix_t,\n            WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::sparse_matrix_t,\n            mdtypes::matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::sparse_matrix_t,\n            mdtypes::sparse_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::shared_matrix_t,\n            mdtypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::root_matrix_t,\n            mdtypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n            mdtypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n            mdtypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n            mdtypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n            mdtypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n            mdtypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n            mdtypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_t,\n            mdtypes::dist_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vc_star_t,\n            mdtypes::dist_matrix_vc_star_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_vr_star_t,\n            mdtypes::dist_matrix_vr_star_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_star_vc_t,\n            mdtypes::dist_matrix_star_vc_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mdtypes::dist_matrix_star_vr_t,\n            mdtypes::dist_matrix_star_vr_t, WZT_t);\n\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::matrix_t, mftypes::matrix_t,\n            WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::sparse_matrix_t,\n            mftypes::matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::sparse_matrix_t,\n            mftypes::sparse_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::shared_matrix_t,\n            mftypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::root_matrix_t,\n            mftypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_t,\n            mftypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_t,\n            mftypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n            mftypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n            mftypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n            mftypes::root_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n            mftypes::shared_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_t,\n            mftypes::dist_matrix_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vc_star_t,\n            mftypes::dist_matrix_vc_star_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_vr_star_t,\n            mftypes::dist_matrix_vr_star_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_star_vc_t,\n            mftypes::dist_matrix_star_vc_t, WZT_t);\n        SKYLARK_SKETCH_ANY_APPLY_DISPATCH(mftypes::dist_matrix_star_vr_t,\n            mftypes::dist_matrix_star_vr_t, WZT_t);\n\n#endif\n\n        SKYLARK_THROW_EXCEPTION (\n          base::sketch_exception()\n              << base::error_msg(\n                 \"This combination has not yet been implemented for WZT\"));\n\n    }\n\n    int get_N() const { return this->_N; } /**< Get input dimesion. */\n    int get_S() const { return this->_S; } /**< Get output dimesion. */\n\n    const sketch_transform_data_t* get_data() const { return this; }\n};\n\n} } /** namespace skylark::sketch */\n\n#endif // SKYLARK_WZT_HPP\n", "meta": {"hexsha": "c1d2b517cb2cf89eddeb53736384477b984c5424", "size": 12648, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sketch/WZT.hpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "sketch/WZT.hpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "sketch/WZT.hpp", "max_forks_repo_name": "xdata-skylark/libskylark", "max_forks_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 39.2795031056, "max_line_length": 84, "alphanum_fraction": 0.6928368121, "num_tokens": 3443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.42774321128979803}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb\n Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2012 Ferdinando Ametrano\n Copyright (C) 2006 Mark Joshi\n Copyright (C) 2006 StatPro Italia srl\n Copyright (C) 2007 Cristina Duminuco\n Copyright (C) 2007 Chiara Fornarola\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/math/solvers1d/newtonsafe.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <boost/math/special_functions/atanh.hpp>\n\nnamespace {\n    void checkParameters(QuantLib::Real strike,\n                         QuantLib::Real forward,\n                         QuantLib::Real displacement)\n    {\n        QL_REQUIRE(displacement >= 0.0, \"displacement (\"\n                                            << displacement\n                                            << \") must be non-negative\");\n        QL_REQUIRE(strike + displacement >= 0.0,\n                   \"strike + displacement (\" << strike << \" + \" << displacement\n                                             << \") must be non-negative\");\n        QL_REQUIRE(forward + displacement > 0.0, \"forward + displacement (\"\n                                                     << forward << \" + \"\n                                                     << displacement\n                                                     << \") must be positive\");\n    }\n}\n\nnamespace QuantLib {\n\n    Real blackFormula(Option::Type optionType,\n                      Real strike,\n                      Real forward,\n                      Real stdDev,\n                      Real discount,\n                      Real displacement)\n    {\n        checkParameters(strike, forward, displacement);\n        QL_REQUIRE(stdDev>=0.0,\n                   \"stdDev (\" << stdDev << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n\n        if (stdDev==0.0)\n            return std::max((forward-strike)*optionType, Real(0.0))*discount;\n\n        forward = forward + displacement;\n        strike = strike + displacement;\n\n        // since displacement is non-negative strike==0 iff displacement==0\n        // so returning forward*discount is OK\n        if (strike==0.0)\n            return (optionType==Option::Call ? forward*discount : 0.0);\n\n        Real d1 = std::log(forward/strike)/stdDev + 0.5*stdDev;\n        Real d2 = d1 - stdDev;\n        CumulativeNormalDistribution phi;\n        Real nd1 = phi(optionType*d1);\n        Real nd2 = phi(optionType*d2);\n        Real result = discount * optionType * (forward*nd1 - strike*nd2);\n        QL_ENSURE(result>=0.0,\n                  \"negative value (\" << result << \") for \" <<\n                  stdDev << \" stdDev, \" <<\n                  optionType << \" option, \" <<\n                  strike << \" strike , \" <<\n                  forward << \" forward\");\n        return result;\n    }\n\n    Real blackFormula(const boost::shared_ptr<PlainVanillaPayoff>& payoff,\n                      Real forward,\n                      Real stdDev,\n                      Real discount,\n                      Real displacement) {\n        return blackFormula(payoff->optionType(),\n            payoff->strike(), forward, stdDev, discount, displacement);\n    }\n\n    Real blackFormulaImpliedStdDevApproximation(Option::Type optionType,\n                                                Real strike,\n                                                Real forward,\n                                                Real blackPrice,\n                                                Real discount,\n                                                Real displacement)\n    {\n        checkParameters(strike, forward, displacement);\n        QL_REQUIRE(blackPrice>=0.0,\n                   \"blackPrice (\" << blackPrice << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n\n        Real stdDev;\n        forward = forward + displacement;\n        strike = strike + displacement;\n        if (strike==forward)\n            // Brenner-Subrahmanyan (1988) and Feinstein (1988) ATM approx.\n            stdDev = blackPrice/discount*std::sqrt(2.0 * M_PI)/forward;\n        else {\n            // Corrado and Miller extended moneyness approximation\n            Real moneynessDelta = optionType*(forward-strike);\n            Real moneynessDelta_2 = moneynessDelta/2.0;\n            Real temp = blackPrice/discount - moneynessDelta_2;\n            Real moneynessDelta_PI = moneynessDelta*moneynessDelta/M_PI;\n            Real temp2 = temp*temp-moneynessDelta_PI;\n            if (temp2<0.0) // approximation breaks down, 2 alternatives:\n                // 1. zero it\n                temp2=0.0;\n                // 2. Manaster-Koehler (1982) efficient Newton-Raphson seed\n                //return std::fabs(std::log(forward/strike))*std::sqrt(2.0);\n            temp2 = std::sqrt(temp2);\n            temp += temp2;\n            temp *= std::sqrt(2.0 * M_PI);\n            stdDev = temp/(forward+strike);\n        }\n        QL_ENSURE(stdDev>=0.0,\n                  \"stdDev (\" << stdDev << \") must be non-negative\");\n        return stdDev;\n    }\n\n    Real blackFormulaImpliedStdDevApproximation(\n                      const boost::shared_ptr<PlainVanillaPayoff>& payoff,\n                      Real forward,\n                      Real blackPrice,\n                      Real discount,\n                      Real displacement) {\n        return blackFormulaImpliedStdDevApproximation(payoff->optionType(),\n            payoff->strike(), forward, blackPrice, discount, displacement);\n    }\n\n\n    class BlackImpliedStdDevHelper {\n      public:\n        BlackImpliedStdDevHelper(Option::Type optionType,\n                                 Real strike,\n                                 Real forward,\n                                 Real undiscountedBlackPrice,\n                                 Real displacement = 0.0)\n        : halfOptionType_(0.5*optionType), signedStrike_(optionType*(strike+displacement)),\n          signedForward_(optionType*(forward+displacement)),\n          undiscountedBlackPrice_(undiscountedBlackPrice)\n        {\n            checkParameters(strike, forward, displacement);\n            QL_REQUIRE(undiscountedBlackPrice>=0.0,\n                       \"undiscounted Black price (\" <<\n                       undiscountedBlackPrice << \") must be non-negative\");\n            signedMoneyness_ = optionType*std::log((forward+displacement)/(strike+displacement));\n        }\n        Real operator()(Real stdDev) const {\n            #if defined(QL_EXTRA_SAFETY_CHECKS)\n            QL_REQUIRE(stdDev>=0.0,\n                       \"stdDev (\" << stdDev << \") must be non-negative\");\n            #endif\n            if (stdDev==0.0)\n                return std::max(signedForward_-signedStrike_, Real(0.0))\n                                                   - undiscountedBlackPrice_;\n            Real temp = halfOptionType_*stdDev;\n            Real d = signedMoneyness_/stdDev;\n            Real signedD1 = d + temp;\n            Real signedD2 = d - temp;\n            Real result = signedForward_ * N_(signedD1)\n                - signedStrike_ * N_(signedD2);\n            // numerical inaccuracies can yield a negative answer\n            return std::max(Real(0.0), result) - undiscountedBlackPrice_;\n        }\n        Real derivative(Real stdDev) const {\n            #if defined(QL_EXTRA_SAFETY_CHECKS)\n            QL_REQUIRE(stdDev>=0.0,\n                       \"stdDev (\" << stdDev << \") must be non-negative\");\n            #endif\n            Real signedD1 = signedMoneyness_/stdDev + halfOptionType_*stdDev;\n            return signedForward_*N_.derivative(signedD1);\n        }\n      private:\n        Real halfOptionType_;\n        Real signedStrike_, signedForward_;\n        Real undiscountedBlackPrice_, signedMoneyness_;\n        CumulativeNormalDistribution N_;\n    };\n\n\n    Real blackFormulaImpliedStdDev(Option::Type optionType,\n                                   Real strike,\n                                   Real forward,\n                                   Real blackPrice,\n                                   Real discount,\n                                   Real displacement,\n                                   Real guess,\n                                   Real accuracy,\n                                   Natural maxIterations)\n    {\n        checkParameters(strike, forward, displacement);\n\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n\n        QL_REQUIRE(blackPrice>=0.0,\n                   \"option price (\" << blackPrice << \") must be non-negative\");\n        // check the price of the \"other\" option implied by put-call paity\n        Real otherOptionPrice = blackPrice - optionType*(forward-strike)*discount;\n        QL_REQUIRE(otherOptionPrice>=0.0,\n                   \"negative \" << Option::Type(-1*optionType) <<\n                   \" price (\" << otherOptionPrice <<\n                   \") implied by put-call parity. No solution exists for \" <<\n                   optionType << \" strike \" << strike <<\n                   \", forward \" << forward <<\n                   \", price \" << blackPrice <<\n                   \", deflator \" << discount);\n\n        // solve for the out-of-the-money option which has\n        // greater vega/price ratio, i.e.\n        // it is numerically more robust for implied vol calculations\n        if (optionType==Option::Put && strike>forward) {\n            optionType = Option::Call;\n            blackPrice = otherOptionPrice;\n        }\n        if (optionType==Option::Call && strike<forward) {\n            optionType = Option::Put;\n            blackPrice = otherOptionPrice;\n        }\n\n        strike = strike + displacement;\n        forward = forward + displacement;\n\n        if (guess==Null<Real>())\n            guess = blackFormulaImpliedStdDevApproximation(\n                optionType, strike, forward, blackPrice, discount, displacement);\n        else\n            QL_REQUIRE(guess>=0.0,\n                       \"stdDev guess (\" << guess << \") must be non-negative\");\n        BlackImpliedStdDevHelper f(optionType, strike, forward,\n                                   blackPrice/discount);\n        NewtonSafe solver;\n        solver.setMaxEvaluations(maxIterations);\n        Real minSdtDev = 0.0, maxStdDev = 24.0; // 24 = 300% * sqrt(60)\n        Real stdDev = solver.solve(f, accuracy, guess, minSdtDev, maxStdDev);\n        QL_ENSURE(stdDev>=0.0,\n                  \"stdDev (\" << stdDev << \") must be non-negative\");\n        return stdDev;\n    }\n\n    Real blackFormulaImpliedStdDev(\n                        const boost::shared_ptr<PlainVanillaPayoff>& payoff,\n                        Real forward,\n                        Real blackPrice,\n                        Real discount,\n                        Real displacement,\n                        Real guess,\n                        Real accuracy,\n                        Natural maxIterations) {\n        return blackFormulaImpliedStdDev(payoff->optionType(), payoff->strike(),\n            forward, blackPrice, discount, displacement, guess, accuracy, maxIterations);\n    }\n\n    Real blackFormulaCashItmProbability(Option::Type optionType,\n                                        Real strike,\n                                        Real forward,\n                                        Real stdDev,\n                                        Real displacement) {\n        checkParameters(strike, forward, displacement);\n        if (stdDev==0.0)\n            return (forward*optionType > strike*optionType ? 1.0 : 0.0);\n\n        forward = forward + displacement;\n        strike = strike + displacement;\n        if (strike==0.0)\n            return (optionType==Option::Call ? 1.0 : 0.0);\n        Real d2 = std::log(forward/strike)/stdDev - 0.5*stdDev;\n        CumulativeNormalDistribution phi;\n        return phi(optionType*d2);\n    }\n\n\n    Real blackFormulaCashItmProbability(\n                        const boost::shared_ptr<PlainVanillaPayoff>& payoff,\n                        Real forward,\n                        Real stdDev,\n                        Real displacement) {\n        return blackFormulaCashItmProbability(payoff->optionType(),\n            payoff->strike(), forward, stdDev , displacement);\n    }\n\n\n    Real blackFormulaVolDerivative(Rate strike,\n                                      Rate forward,\n                                      Real stdDev,\n                                      Real expiry,\n                                      Real discount,\n                                      Real displacement)\n    {\n        return  blackFormulaStdDevDerivative(strike,\n                                     forward,\n                                     stdDev,\n                                     discount,\n                                     displacement)*std::sqrt(expiry);\n    }\n\n    Real blackFormulaStdDevDerivative(Rate strike,\n                                      Rate forward,\n                                      Real stdDev,\n                                      Real discount,\n                                      Real displacement)\n    {\n        checkParameters(strike, forward, displacement);\n        QL_REQUIRE(stdDev>=0.0,\n                   \"stdDev (\" << stdDev << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n\n        forward = forward + displacement;\n        strike = strike + displacement;\n\n        if (stdDev==0.0 || strike==0.0)\n            return 0.0;\n\n        Real d1 = std::log(forward/strike)/stdDev + .5*stdDev;\n        return discount * forward *\n            CumulativeNormalDistribution().derivative(d1);\n    }\n\n    Real blackFormulaStdDevDerivative(\n                        const boost::shared_ptr<PlainVanillaPayoff>& payoff,\n                        Real forward,\n                        Real stdDev,\n                        Real discount,\n                        Real displacement) {\n        return blackFormulaStdDevDerivative(payoff->strike(), forward,\n                                     stdDev, discount, displacement);\n    }\n\n\n    Real bachelierBlackFormula(Option::Type optionType,\n                               Real strike,\n                               Real forward,\n                               Real stdDev,\n                               Real discount)\n    {\n        QL_REQUIRE(stdDev>=0.0,\n                   \"stdDev (\" << stdDev << \") must be non-negative\");\n        QL_REQUIRE(discount>0.0,\n                   \"discount (\" << discount << \") must be positive\");\n        Real d = (forward-strike)*optionType, h = d/stdDev;\n        if (stdDev==0.0)\n            return discount*std::max(d, 0.0);\n        CumulativeNormalDistribution phi;\n        Real result = discount*(stdDev*phi.derivative(h) + d*phi(h));\n        QL_ENSURE(result>=0.0,\n                  \"negative value (\" << result << \") for \" <<\n                  stdDev << \" stdDev, \" <<\n                  optionType << \" option, \" <<\n                  strike << \" strike , \" <<\n                  forward << \" forward\");\n        return result;\n    }\n\n    Real bachelierBlackFormula(\n                        const boost::shared_ptr<PlainVanillaPayoff>& payoff,\n                        Real forward,\n                        Real stdDev,\n                        Real discount) {\n        return bachelierBlackFormula(payoff->optionType(),\n            payoff->strike(), forward, stdDev, discount);\n    }\n\n    static Real h(Real eta) {\n\n        const static Real  A0          = 3.994961687345134e-1;\n        const static Real  A1          = 2.100960795068497e+1;\n        const static Real  A2          = 4.980340217855084e+1;\n        const static Real  A3          = 5.988761102690991e+2;\n        const static Real  A4          = 1.848489695437094e+3;\n        const static Real  A5          = 6.106322407867059e+3;\n        const static Real  A6          = 2.493415285349361e+4;\n        const static Real  A7          = 1.266458051348246e+4;\n\n        const static Real  B0          = 1.000000000000000e+0;\n        const static Real  B1          = 4.990534153589422e+1;\n        const static Real  B2          = 3.093573936743112e+1;\n        const static Real  B3          = 1.495105008310999e+3;\n        const static Real  B4          = 1.323614537899738e+3;\n        const static Real  B5          = 1.598919697679745e+4;\n        const static Real  B6          = 2.392008891720782e+4;\n        const static Real  B7          = 3.608817108375034e+3;\n        const static Real  B8          = -2.067719486400926e+2;\n        const static Real  B9          = 1.174240599306013e+1;\n\n        QL_REQUIRE(eta>=0.0,\n                       \"eta (\" << eta << \") must be non-negative\");\n\n        const Real num = A0 + eta * (A1 + eta * (A2 + eta * (A3 + eta * (A4 + eta\n                    * (A5 + eta * (A6 + eta * A7))))));\n\n        const Real den = B0 + eta * (B1 + eta * (B2 + eta * (B3 + eta * (B4 + eta\n                    * (B5 + eta * (B6 + eta * (B7 + eta * (B8 + eta * B9))))))));\n\n        return std::sqrt(eta) * (num / den);\n\n    }\n\n    Real bachelierBlackFormulaImpliedVol(Option::Type optionType,\n                                   Real strike,\n                                   Real forward,\n                                   Real tte,\n                                   Real bachelierPrice,\n                                   Real discount) {\n\n        const static Real SQRT_QL_EPSILON = std::sqrt(QL_EPSILON);\n\n        QL_REQUIRE(tte>0.0,\n                   \"tte (\" << tte << \") must be positive\");\n\n        Real forwardPremium = bachelierPrice/discount;\n\n        Real straddlePremium;\n        if (optionType==Option::Call){\n            straddlePremium = 2.0 * forwardPremium - (forward - strike);\n        } else {\n            straddlePremium = 2.0 * forwardPremium + (forward - strike);\n        }\n\n        Real nu = (forward - strike) / straddlePremium;\n        QL_REQUIRE(nu<=1.0,\n                   \"nu (\" << nu << \") must be <= 1.0\");\n        QL_REQUIRE(nu>=-1.0,\n                     \"nu (\" << nu << \") must be >= -1.0\");\n\n        nu = std::max(-1.0 + QL_EPSILON, std::min(nu,1.0 - QL_EPSILON));\n\n        // nu / arctanh(nu) -> 1 as nu -> 0\n        Real eta = (std::fabs(nu) < SQRT_QL_EPSILON) ? 1.0 : nu / boost::math::atanh(nu);\n\n        Real heta = h(eta);\n\n        Real impliedBpvol = std::sqrt(M_PI / (2 * tte)) * straddlePremium * heta;\n\n        return impliedBpvol;\n    }\n}\n", "meta": {"hexsha": "ce5cbf54a121e360ddc5f4688a21074a56911211", "size": 19176, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/pricingengines/blackformula.cpp", "max_stars_repo_name": "quantosaurosProject/quantLib", "max_stars_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/pricingengines/blackformula.cpp", "max_issues_repo_name": "quantosaurosProject/quantLib", "max_issues_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/pricingengines/blackformula.cpp", "max_forks_repo_name": "quantosaurosProject/quantLib", "max_forks_repo_head_hexsha": "84b49913d3940cf80d6de8f70185867373f45e8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-29T05:44:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T05:44:27.000Z", "avg_line_length": 41.9606126915, "max_line_length": 97, "alphanum_fraction": 0.5103254068, "num_tokens": 4207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.42773891578073936}}
{"text": "/**\n * @author     : Zhao Chonyyao (cyzhao@zju.edu.cn)\n * @date       : 2021-04-30\n * @description: some basic energy function.\n * @version    : 1.0\n */\n#include <iostream>\n\n#include <Eigen/SparseCore>\n\n#include \"basic_energy.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace PhysIKA {\n/******************************************momentum*******************************/\n\ntemplate <typename T, size_t dim_>\nsize_t momentum<T, dim_>::Nx() const\n{\n    return dim_ * dof_;\n}\n\ntemplate <typename T, size_t dim_>\nmomentum<T, dim_>::momentum(const size_t dof, const Matrix<T, -1, 1>& mass_vec, const T& dt)\n    : dof_(dof), dispk_(Matrix<T, -1, 1>::Zero(dim_ * dof)), vk_(Matrix<T, -1, 1>::Zero(dim_ * dof)), dt_(dt), d1dt_(1 / dt), d1dtdt_(1 / dt / dt), mass_vec_(dim_ * dof)\n{\n\n#pragma omp parallel for\n    for (size_t i = 0; i < dof; ++i)\n    {\n        for (size_t j = 0; j < dim_; ++j)\n        {\n            mass_vec_(i * dim_ + j) = mass_vec(i);\n        }\n    }\n}\n\ntemplate <typename T, size_t dim_>\nmomentum<T, dim_>::momentum(const T* rest, const size_t dof, const Matrix<T, -1, 1>& mass_vec, const T& dt)\n    : dof_(dof), vk_(Matrix<T, -1, 1>::Zero(dim_ * dof)), dt_(dt), d1dt_(1 / dt), d1dtdt_(1 / dt / dt), mass_vec_(dim_ * dof)\n{\n\n    dispk_ = Eigen::Map<const Matrix<T, -1, 1>>(rest, dim_ * dof);\n#pragma omp parallel for\n    for (size_t i = 0; i < dof; ++i)\n    {\n        for (size_t j = 0; j < dim_; ++j)\n        {\n            mass_vec_(i * dim_ + j) = mass_vec(i);\n        }\n    }\n}\n\ntemplate <typename T, size_t dim_>\nint momentum<T, dim_>::Val(const T* x, data_ptr<T, dim_>& data) const\n{\n    Eigen::Map<const Matrix<T, -1, 1>> _x(x, dim_ * dof_);\n    const Matrix<T, -1, 1>             acce = (_x - dispk_) * d1dt_ - vk_;\n    data->save_val(0.5 * acce.dot(mass_vec_.cwiseProduct(acce)));\n\n    return 0;\n}\ntemplate <typename T, size_t dim_>\nint momentum<T, dim_>::Gra(const T* x, data_ptr<T, dim_>& data) const\n{\n    Eigen::Map<const Matrix<T, -1, 1>> _x(x, dim_ * dof_);\n\n    const Matrix<T, -1, 1> acce = (_x - dispk_) * d1dtdt_ - vk_ * d1dt_;\n    data->save_gra(mass_vec_.cwiseProduct(acce));\n\n    return 0;\n}\n\ntemplate <typename T, size_t dim_>\nint momentum<T, dim_>::Hes(const T* x, data_ptr<T, dim_>& data) const\n{\n#pragma omp parallel for\n    for (size_t i = 0; i < dim_ * dof_; ++i)\n        data->save_hes(i, i, d1dtdt_ * mass_vec_(i));\n\n    return 0;\n}\n\ntemplate <typename T, size_t dim_>\nint momentum<T, dim_>::update_location_and_velocity(const T* new_dispk_ptr, const T* new_velo_ptr)\n{\n    Eigen::Map<const Matrix<T, -1, 1>> new_dispk(new_dispk_ptr, dim_ * dof_);\n    if (new_velo_ptr == nullptr)\n        vk_ = (new_dispk - dispk_) * d1dt_;\n    else\n        vk_ = Map<const Matrix<T, -1, 1>>(new_velo_ptr, dim_ * dof_);\n\n    dispk_ = new_dispk;\n    return 0;\n}\n\ntemplate <typename T, size_t dim_>\nint momentum<T, dim_>::set_initial_velocity(const Matrix<T, dim_, 1>& velo)\n{\n    Eigen::Map<Matrix<T, -1, -1>> myvelo(vk_.data(), dim_, dof_);\n    for (size_t i = 0; i < dim_; ++i)\n    {\n        myvelo.row(i) = Matrix<T, 1, -1>::Ones(dof_) * velo(i);\n    }\n    return 0;\n}\n\n/******************************************momentum*******************************/\n/******************************************position_constraint*******************************/\ntemplate <typename T, size_t dim_>\nposition_constraint<T, dim_>::position_constraint(const size_t dof, const T& w, const vector<size_t>& cons)\n    : w_(w), cons_(cons), dof_(dof)\n{\n    rest_ = Matrix<T, -1, -1>::Zero(dim_, dof);\n}\n\ntemplate <typename T, size_t dim_>\nposition_constraint<T, dim_>::position_constraint(const T* rest, const size_t dof, const T& w, const std::vector<size_t>& cons)\n    : w_(w), cons_(cons), dof_(dof)\n{\n    rest_ = Eigen::Map<const Matrix<T, -1, -1>>(rest, dim_, dof_);\n}\n\n//TODO: simplify _x\ntemplate <typename T, size_t dim_>\nint position_constraint<T, dim_>::Val(const T* x, data_ptr<T, dim_>& data) const\n{\n    Eigen::Map<const Matrix<T, -1, -1>> deformed(x, dim_, dof_);\n    Matrix<T, -1, -1>                   _x = deformed - rest_;\n    for (auto iter_c = cons_.begin(); iter_c != cons_.end(); ++iter_c)\n    {\n        data->save_val(w_ * _x.col(*iter_c).dot(_x.col(*iter_c)));\n    }\n\n    return 0;\n}\n\ntemplate <typename T, size_t dim_>\nint position_constraint<T, dim_>::Gra(const T* x, data_ptr<T, dim_>& data) const\n{\n    Eigen::Map<const Matrix<T, -1, -1>> deformed(x, dim_, dof_);\n    Matrix<T, -1, -1>                   _x = deformed - rest_;\n\n    for (auto iter_c = cons_.begin(); iter_c != cons_.end(); ++iter_c)\n        data->save_gra(*iter_c, 2.0 * w_ * _x.col(*iter_c));\n    return 0;\n}\n\ntemplate <typename T, size_t dim_>\nint position_constraint<T, dim_>::Hes(const T* x, data_ptr<T, dim_>& data) const\n{\n    for (auto iter_c = cons_.begin(); iter_c != cons_.end(); ++iter_c)\n    {\n        for (size_t j = 0; j < dim_; ++j)\n        {\n            data->save_hes(*iter_c * dim_ + j, *iter_c * dim_ + j, 2 * w_);\n        }\n    }\n    return 0;\n}\n\ntemplate <typename T, size_t dim_>\nsize_t position_constraint<T, dim_>::Nx() const\n{\n    return dim_ * dof_;\n}\n/******************************************position_constraint*******************************/\n\n/******************************************gravity*******************************/\n//dof here is not about dim_\ntemplate <typename T, size_t dim_>\ngravity_energy<T, dim_>::gravity_energy(const size_t dof, const T& w_g, const T& gravity, const Matrix<T, -1, 1>& mass, const char& axis)\n    : w_g_(w_g), dof_(dof), gravity_(gravity), mass_(mass), axis_(axis)\n{\n}\n\ntemplate <typename T, size_t dim_>\nint gravity_energy<T, dim_>::Val(const T* x, data_ptr<T, dim_>& data) const\n{\n\n    Eigen::Map<const Matrix<T, -1, -1>> _x(x, dim_, dof_);\n    size_t                              which_axis = size_t(axis_ - 'x');\n    data->save_val((_x.row(which_axis).transpose().array() * mass_.array()).sum() * w_g_ * gravity_);\n    return 0;\n}\n\ntemplate <typename T, size_t dim_>\nint gravity_energy<T, dim_>::Gra(const T* x, data_ptr<T, dim_>& data) const\n{\n    size_t which_axis = size_t(axis_ - 'x');\n\n    Matrix<T, -1, -1> g(dim_, dof_);\n    g.setZero();\n    g.row(which_axis) = Matrix<T, -1, 1>::Constant(dof_, gravity_ * w_g_).cwiseProduct(mass_).transpose();\n    Eigen::Map<const Matrix<T, -1, 1>> g_(g.data(), dim_ * dof_);\n    data->save_gra(g_);\n    return 0;\n}\ntemplate <typename T, size_t dim_>\nint gravity_energy<T, dim_>::Hes(const T* x, data_ptr<T, dim_>& data) const\n{\n    return 0;\n}\n\ntemplate <typename T, size_t dim_>\nsize_t gravity_energy<T, dim_>::Nx() const\n{\n    return dim_ * dof_;\n}\n/******************************************gravity*******************************/\n\n/*************************************collision*********************************/\ntemplate <typename T, size_t dim_>\ncollision<T, dim_>::collision(const size_t dof_, const T& w_coll, const char& ground_axis, const T& ground_pos, const size_t& num_surf_point, const shared_ptr<Matrix<T, -1, -1>>& init_points_ptr)\n    : ground_axis_(ground_axis), ground_pos_(ground_pos), w_coll_(w_coll), num_surf_point_(num_surf_point), dof_(dof_), init_points_ptr_(init_points_ptr)\n{\n}\n\ntemplate <typename T, size_t dim_>\nint collision<T, dim_>::Val(const T* x, data_ptr<T, dim_>& data) const\n{\n    const size_t which_axis = size_t(ground_axis_ - 'x');\n\n    Eigen::Map<const Matrix<T, -1, -1>> _x(x, dim_, dof_);\n#pragma omp parallel for\n    for (size_t i = 0; i < dof_; ++i)\n    {\n        const T position_now = _x(which_axis, i) + (*init_points_ptr_)(which_axis, i);\n        if ((position_now - ground_pos_) < 0)\n        {\n\n            data->save_val(w_coll_ * pow((ground_pos_ - position_now), 2));\n        }\n    }\n    return 0;\n}\ntemplate <typename T, size_t dim_>\nint collision<T, dim_>::Gra(const T* x, data_ptr<T, dim_>& data) const\n{\n    const size_t which_axis = size_t(ground_axis_ - 'x');\n\n    Eigen::Map<const Matrix<T, -1, -1>> _x(x, dim_, dof_);\n#pragma omp parallel for\n    for (size_t i = 0; i < dof_; ++i)\n    {\n        const T position_now = _x(which_axis, i) + (*init_points_ptr_)(which_axis, i);\n        if ((position_now - ground_pos_) < 0)\n        {\n            data->save_gra(i * dim_ + which_axis, 2 * w_coll_ * (position_now - ground_pos_));\n        }\n    }\n    return 0;\n}\ntemplate <typename T, size_t dim_>\nint collision<T, dim_>::Hes(const T* x, data_ptr<T, dim_>& data) const\n{\n    const size_t                        which_axis = size_t(ground_axis_ - 'x');\n    Eigen::Map<const Matrix<T, -1, -1>> _x(x, dim_, dof_);\n#pragma omp parallel for\n    for (size_t i = 0; i < dof_; ++i)\n    {\n        const T position_now = _x(which_axis, i) + (*init_points_ptr_)(which_axis, i);\n        if ((position_now - ground_pos_) < 0)\n        {\n            for (size_t j = 0; j < dim_; ++j)\n            {\n                data->save_hes(i * dim_ + j, i * dim_ + j, 2 * w_coll_);\n            }\n        }\n    }\n\n    return 0;\n}\ntemplate <typename T, size_t dim_>\nsize_t collision<T, dim_>::Nx() const\n{\n    return dim_ * dof_;\n}\n\n/*************************************collision*********************************/\n\ntemplate class position_constraint<double, 3>;\ntemplate class position_constraint<float, 3>;\ntemplate class position_constraint<float, 1>;\ntemplate class position_constraint<double, 1>;\ntemplate class momentum<double, 3>;\ntemplate class momentum<float, 3>;\ntemplate class gravity_energy<double, 3>;\ntemplate class gravity_energy<float, 3>;\n// template class collision<FLOAT_TYPE, 3>;\n\n}  //namespace PhysIKA\n", "meta": {"hexsha": "4b3913401ba9eec75d0dfdbfba5760e026de95ce", "size": 9470, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Source/Dynamics/FiniteElementMethod/Source/Problem/energy/basic_energy.cc", "max_stars_repo_name": "weikm/sandcarSimulation2", "max_stars_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/Dynamics/FiniteElementMethod/Source/Problem/energy/basic_energy.cc", "max_issues_repo_name": "weikm/sandcarSimulation2", "max_issues_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Dynamics/FiniteElementMethod/Source/Problem/energy/basic_energy.cc", "max_forks_repo_name": "weikm/sandcarSimulation2", "max_forks_repo_head_hexsha": "fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1016949153, "max_line_length": 195, "alphanum_fraction": 0.5808870116, "num_tokens": 2864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.42773891578073936}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2021, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"math-precomp.h\"  // Precompiled headers\n//\n#include <mrpt/math/TLine3D.h>\n#include <mrpt/math/TSegment3D.h>\n#include <mrpt/math/geometry.h>\t // distance()\n#include <mrpt/serialization/CArchive.h>  // impl of << operator\n\n#include <Eigen/Dense>\n\nusing namespace mrpt::math;\n\nvoid TSegment3D::generate2DObject(TSegment2D& s) const\n{\n\ts = TSegment2D(*this);\n}\n\ndouble TSegment3D::length() const { return math::distance(point1, point2); }\ndouble TSegment3D::distance(const TPoint3D& point) const\n{\n\treturn std::min(\n\t\tstd::min(math::distance(point, point1), math::distance(point, point2)),\n\t\tTLine3D(*this).distance(point));\n}\ndouble TSegment3D::distance(const TSegment3D& segment) const\n{\n\tEigen::Vector3d u, v, w;\n\tTPoint3D diff_vect = point2 - point1;\n\tdiff_vect.asVector(u);\n\tdiff_vect = segment.point2 - segment.point1;\n\tdiff_vect.asVector(v);\n\tdiff_vect = point1 - segment.point1;\n\tdiff_vect.asVector(w);\n\tdouble a = u.dot(u);  // always >= 0\n\tdouble b = u.dot(v);\n\tdouble c = v.dot(v);  // always >= 0\n\tdouble d = u.dot(w);\n\tdouble e = v.dot(w);\n\tdouble D = a * c - b * b;  // always >= 0\n\tdouble sc, sN, sD = D;\t// sc = sN / sD, default sD = D >= 0\n\tdouble tc, tN, tD = D;\t// tc = tN / tD, default tD = D >= 0\n\n\t// compute the line parameters of the two closest points\n\tif (D < 0.00000001)\n\t{  // the lines are almost parallel\n\t\tsN = 0.0;  // force using point P0 on segment S1\n\t\tsD = 1.0;  // to prevent possible division by 0.0 later\n\t\ttN = e;\n\t\ttD = c;\n\t}\n\telse\n\t{  // get the closest points on the infinite lines\n\t\tsN = (b * e - c * d);\n\t\ttN = (a * e - b * d);\n\t\tif (sN < 0.0)\n\t\t{  // sc < 0 => the s=0 edge is visible\n\t\t\tsN = 0.0;\n\t\t\ttN = e;\n\t\t\ttD = c;\n\t\t}\n\t\telse if (sN > sD)\n\t\t{  // sc > 1 => the s=1 edge is visible\n\t\t\tsN = sD;\n\t\t\ttN = e + b;\n\t\t\ttD = c;\n\t\t}\n\t}\n\n\tif (tN < 0.0)\n\t{  // tc < 0 => the t=0 edge is visible\n\t\ttN = 0.0;\n\t\t// recompute sc for this edge\n\t\tif (-d < 0.0) sN = 0.0;\n\t\telse if (-d > a)\n\t\t\tsN = sD;\n\t\telse\n\t\t{\n\t\t\tsN = -d;\n\t\t\tsD = a;\n\t\t}\n\t}\n\telse if (tN > tD)\n\t{  // tc > 1 => the t=1 edge is visible\n\t\ttN = tD;\n\t\t// recompute sc for this edge\n\t\tif ((-d + b) < 0.0) sN = 0;\n\t\telse if ((-d + b) > a)\n\t\t\tsN = sD;\n\t\telse\n\t\t{\n\t\t\tsN = (-d + b);\n\t\t\tsD = a;\n\t\t}\n\t}\n\t// finally do the division to get sc and tc\n\tsc = (fabs(sN) < 0.00000001 ? 0.0 : sN / sD);\n\ttc = (fabs(tN) < 0.00000001 ? 0.0 : tN / tD);\n\n\t// get the difference of the two closest points\n\tconst auto dP = (w + (sc * u) - (tc * v)).eval();\n\treturn dP.norm();  // return the closest distance\n}\nbool TSegment3D::contains(const TPoint3D& point) const\n{\n\t// Not very intuitive, but very fast, method.\n\treturn std::abs(\n\t\t\t   math::distance(point1, point) + math::distance(point2, point) -\n\t\t\t   math::distance(point1, point2)) < getEpsilon();\n}\n\nbool TSegment3D::operator<(const TSegment3D& s) const\n{\n\tif (point1 < s.point1) return true;\n\telse if (s.point1 < point1)\n\t\treturn false;\n\telse\n\t\treturn point2 < s.point2;\n}\n\nmrpt::serialization::CArchive& mrpt::math::operator>>(\n\tmrpt::serialization::CArchive& in, mrpt::math::TSegment3D& s)\n{\n\treturn in >> s.point1 >> s.point2;\n}\nmrpt::serialization::CArchive& mrpt::math::operator<<(\n\tmrpt::serialization::CArchive& out, const mrpt::math::TSegment3D& s)\n{\n\treturn out << s.point1 << s.point2;\n}\n", "meta": {"hexsha": "a81bb334d5cace3f7aeb969ffd6381c1421de014", "size": 3868, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/src/TSegment3D.cpp", "max_stars_repo_name": "DavidLee999/mrpt", "max_stars_repo_head_hexsha": "9f7bcad718906245a7efa4c9760d4d35c43ceb61", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-01T15:43:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-01T15:43:00.000Z", "max_issues_repo_path": "libs/math/src/TSegment3D.cpp", "max_issues_repo_name": "jolting/mrpt", "max_issues_repo_head_hexsha": "2cfcd3a97aebd49290df5405976b15f8923c35cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-11-30T19:51:29.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-01T08:15:36.000Z", "max_forks_repo_path": "libs/math/src/TSegment3D.cpp", "max_forks_repo_name": "DavidLee999/mrpt", "max_forks_repo_head_hexsha": "9f7bcad718906245a7efa4c9760d4d35c43ceb61", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-01-12T02:08:10.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-14T23:05:10.000Z", "avg_line_length": 28.0289855072, "max_line_length": 80, "alphanum_fraction": 0.560237849, "num_tokens": 1287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.42772949863062326}}
{"text": "#ifndef SPARSEMATRIX_HPP_1BWMMLC8\n#define SPARSEMATRIX_HPP_1BWMMLC8\n\n#include <algorithm>\n#include <cassert>\n#include <fstream>\n#include <iterator>\n#include <map>\n#include <stdexcept>\n#include <tuple>\n#include <unordered_map>\n#include <vector>\n#include <vector>\n#include <iostream>\n\n#include <Eigen/Sparse>\n\nnamespace cask {\n  namespace sparse {\n\n    using EigenSparseMatrix = Eigen::SparseMatrix<double, Eigen::RowMajor, int32_t>;\n\n    template<typename value_type>\n  class SparkCooMatrix {\n\n        public:\n        using CoordType = std::tuple<int, int, value_type>;\n\n        int n, m;\n        std::vector<CoordType> data;\n\n        SparkCooMatrix(int _n, int _m) : n(_n), m(_m) {}\n      };\n  }\n\n// A dense vector representation\nclass Vector {\npublic:\n  std::vector<double> data;\n\n  Vector(int n) : data(n, 0) {}\n  Vector(std::initializer_list<double> l) : data(l) {}\n  Vector(const std::vector<double>& v) : data(v.begin(), v.end()) {}\n\n  Vector operator-(const Vector& other) const {\n    int n = size();\n    if (other.size() != data.size()) {\n      throw std::invalid_argument(\"Attempt to subtract vectors of different lengths: \" +\n                                  std::to_string(other.size()) + \" != \" + std::to_string(n));\n    }\n    Vector v(n);\n    for (int i = 0; i < n; i++) {\n      v[i] = data[i] - other[i];\n    }\n    return v;\n  }\n\n  int size() const {\n    return data.size();\n  }\n\n  bool operator==(const Vector& other) const {\n    return data == other.data;\n  }\n\n  const double& operator[](int i) const {\n    return data[i];\n  }\n\n  double& operator[](int i) {\n    return data[i];\n  }\n\n  void print(std::string label=\"\") const {\n    std::cout << label;\n    for (int i : data)\n      std::cout << i << \" \";\n    std::cout << std::endl;\n  }\n\n  double norm() const {\n    double residual;\n    for (double d : data)\n      residual += d * d;\n    return std::sqrt(residual);\n  }\n\n  double distance(const Vector& exp) const {\n    return (*this - exp).norm();\n  }\n\n  void writeToFile(std::string path) {\n    std::ofstream f{path};\n    if (!f)\n      throw std::invalid_argument(\"Could not open file for writing\");\n    for (auto v : data)\n      f << v << std::endl;\n  }\n};\n\n/**\n * Sparse matrix representations for some common storage formats:\n * - DoK (Dictionary of Keys) -- the de facto format for all/many construction tasks; random read/write access is\n * efficient, but memory footprint is large\n * - CSR -- an efficient format for when only row slicing operations are required; random read access is supported but inefficient,\n * random write access is only supported in update mode (cannot insert new nonzeros), memory footprint is minimal\n *\n * Some underlying assumptions that are respected by all matrix formats:\n *\n * - all storage is 0 indexed; it is incredibly awkward and error-prone to support 1-based indexing in a language like C++;\n * - for interfacing with certain codes that do not support 0 based indexing (e.g. if using BLAS from Fortran), some\n * formats provide a getIndexed() method to obtain the corresponding representation in 1 based indexing. Read the specific\n * of each method to understand the storage format and prevent bugs when interfacing with low-level C/Fortran APIs\n *\n * TODOs\n * - a consistent, safe mechanism for handling symmetric matrices?\n */\nclass DokMatrix {\n\n public:\n  int n, m;\n  int nnzs;\n\n  // use of std::map important: values are sorted by column index internaly\n  std::unordered_map<int, std::map<int, double>> dok;\n\n  DokMatrix() : n(0), m(0), nnzs(0) {}\n\n  DokMatrix(int _n, int m) : n(_n), m(m), nnzs(0) {}\n\n  DokMatrix(int _n, int m, int _nnzs) : n(_n), m(m), nnzs(_nnzs) {}\n\n  // Initialize the matrix as a dense matrix, with the given values, in order;\n  // matrix is assumed square with n = sqrt(pattern.size()); 0 entries must be\n  // entered explicitly\n  DokMatrix(const std::initializer_list<double>& pattern) :\n      DokMatrix(floor((sqrt(pattern.size()))), pattern) { }\n\n  // Initialize the matrix as a dense matrix, with the given values, in order;\n  // matrix is assumed of size n rows by pattern.size() / n columns;\n  // 0 entries must be entered explicitly\n  DokMatrix(int n, const std::initializer_list<double>& pattern) : n(n) {\n    nnzs = std::count_if(pattern.begin(), pattern.end(), [](double x){return x != 0;});\n    auto it = pattern.begin();\n    m = pattern.size() / n;\n    for (int i = 0; i < n; i++)\n      for (int j = 0; j < m; j++) {\n        double value = *it;\n        if (value != 0) {\n          dok[i][j] = value;\n        }\n        it++;\n      }\n  }\n\n  DokMatrix explicitSymmetric() {\n    int newNnzs = 0;\n    DokMatrix m(n, this->m);\n    for (auto &&s : dok) {\n      for (auto &&p : s.second) {\n        int i = s.first;\n        int j = p.first;\n        double value = p.second;\n        m.dok[i][j] = value;\n        newNnzs++;\n\n        // check the transpose entry does not exist\n        // TODO replace dok.find with dok.at\n        if (i == j)\n          continue;\n        if (dok.find(j) != dok.end()) {\n          if (dok[j].find(i) != dok[j].end()) {\n            if (dok[j][i] != p.second) {\n              throw std::invalid_argument(\"Matrix is not symmetric\");\n            } else {\n              std::cout << \"Warning! Matrix already contains transpose entry for \"\n                        << s.first << \" \" << p.first << std::endl;\n            }\n          }\n        }\n\n        // add the transpose entry\n        m.dok[j][i] = value;\n        newNnzs++;\n      }\n    }\n    m.nnzs = newNnzs;\n    return m;\n  }\n\n  bool operator==(const DokMatrix& other) const {\n    return n == other.n && m == other.m && nnzs == other.nnzs && dok == other.dok;\n  }\n\n  void pretty_print() const {\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < m; j++) {\n        std::cout << at(i, j) << \" \";\n      }\n      std::cout << \"\\n\";\n    }\n  }\n\n  double at(int i, int j) const {\n    assert(i < n && j < m);\n    if (dok.count(i) == 0)\n      return 0;\n    if (dok.at(i).count(j) == 0)\n      return 0;\n    return dok.at(i).at(j);\n  }\n\n  void set(int i, int j, double val) {\n    assert(i < n && j < m);\n    dok[i][j] = val;\n    nnzs++;\n  }\n\n  bool isNnz(int i, int j) const {\n    if (dok.count(i) == 0)\n      return false;\n    if (dok.at(i).count(j) == 0)\n        return false;\n    return dok.at(i).at(j) != 0;\n  }\n\n  DokMatrix getLowerTriangular() const {\n    DokMatrix lowerTriangular(n, m);\n    for (auto &e : dok) {\n      for (auto &ee : e.second) {\n        int i = e.first;\n        int j = ee.first;\n        double value = ee.second;\n        if (j <= i)\n          lowerTriangular.set(i, j, value);\n      }\n    }\n    return lowerTriangular;\n  }\n\n  DokMatrix getUpperTriangular() const {\n    DokMatrix lowerTriangular(n, m);\n    for (auto &e : dok) {\n      for (auto &ee : e.second) {\n        int i = e.first;\n        int j = ee.first;\n        double value = ee.second;\n        if (i <= j)\n          lowerTriangular.set(i, j, value);\n      }\n    }\n    return lowerTriangular;\n  }\n\n  Vector dot(const Vector& b) const {\n    Vector result(b.size());\n    for (auto &p : dok) {\n      int row = p.first;\n      for (auto &e : p.second) {\n        result[row] += b[e.first] * e.second;\n      }\n    }\n    return result;\n  }\n\n};\n\n// TODO verify preconditions:\n// with 1 based indexing\n// lower triangular\n// row entries in increasing column order\nclass CsrMatrix {\n  // TODO move to include/, make API\n public:\n  int n, m;\n  int nnzs;\n  std::vector<double> values;\n  std::vector<int> col_ind;\n  std::vector<int> row_ptr;\n\n  CsrMatrix() : n(0), m(0), nnzs(0) {}\n\n  CsrMatrix(std::initializer_list<double> mat) : CsrMatrix(DokMatrix(mat)){\n  }\n\n  CsrMatrix(int n, std::initializer_list<double> mat) : CsrMatrix(DokMatrix(n, mat)){\n  }\n\n  CsrMatrix(const DokMatrix &m) {\n    nnzs = m.nnzs;\n    this->n = m.n;\n    this->m = m.m;\n    int pos = 0;\n    for (int i = 0; i < n; i++) {\n      row_ptr.push_back(pos);\n      if (m.dok.count(i) != 0) {\n        for (auto &entries : m.dok.at(i)) {\n          col_ind.push_back(entries.first);\n          values.push_back(entries.second);\n          pos++;\n        }\n      }\n    }\n    row_ptr.push_back(nnzs);\n  }\n\n  CsrMatrix(int _n, int _m, int _nnzs, double *_values, int *_col_ind, int *_row_ptr) :\n      n(_n), m(_m),\n      nnzs(_nnzs) {\n    values.assign(_values, _values + _nnzs);\n    col_ind.assign(_col_ind, _col_ind + _nnzs);\n    row_ptr.assign(_row_ptr, _row_ptr + n + 1);\n  }\n\n  CsrMatrix(int n, int m, int nnzs,\n            const std::vector<double> &values,\n            const std::vector<int> &col_ind,\n            const std::vector<int> &row_ptr) :\n      n(n), m(m), nnzs(nnzs), values(values), col_ind(col_ind), row_ptr(row_ptr) {}\n\n  // Prints all matrix values\n  void pretty_print() const {\n    for (int i = 0; i < n; i++) {\n      int col_ptr = row_ptr[i];\n      for (int j = 0; j < n; j++) {\n        if (col_ptr < row_ptr[i + 1] && col_ind[col_ptr] == j) {\n          std::cout << values[col_ptr] << \" \";\n          col_ptr++;\n          continue;\n        }\n        std::cout << \"0 \";\n      }\n      std::cout << \"\\n\";\n    }\n  }\n\n  void print() {\n    std::cout << \"CSRMatrix( n= \" << n << \" nnzs= \" << nnzs << \")\" << std::endl;\n    std::cout << \"values = \";\n    std::copy(values.begin(), values.end(), std::ostream_iterator<double>{std::cout, \" \"});\n    std::cout << std::endl;\n    std::cout << \"col_ind = \";\n    std::copy(col_ind.begin(), col_ind.end(), std::ostream_iterator<double>{std::cout, \" \"});\n    std::cout << std::endl;\n    std::cout << \"row_ptr = \";\n    std::copy(row_ptr.begin(), row_ptr.end(), std::ostream_iterator<double>{std::cout, \" \"});\n    std::cout << std::endl;\n  }\n\n  double &get(int i, int j) {\n    for (int k = row_ptr[i]; k < row_ptr[i + 1]; k++) {\n      if (col_ind[k] == j) {\n        return values[k];\n      }\n    }\n\n    throw std::invalid_argument(\"No nonzero at row col:\"\n                                    + std::to_string(i) + \" \"\n                                    + std::to_string(j));\n  }\n\n  bool isNnz(int i, int j) {\n    // TODO efficiency could be improved\n    try {\n      get(i, j);\n    } catch (std::invalid_argument) {\n      return false;\n    }\n    return true;\n  }\n\n  bool isSymmetric() const {\n    return true;\n  }\n\n  DokMatrix toDok() const {\n    DokMatrix m(n, this->m, nnzs);\n    for (int i = 0; i < n; i++) {\n      for (int k = row_ptr[i]; k < row_ptr[i + 1]; k++) {\n        m.dok[i][col_ind[k]] = values[k];\n      }\n    }\n    return m;\n  }\n\n  bool operator==(const CsrMatrix& o) const {\n    return n == o.n &&\n        m == o.m &&\n        nnzs == o.nnzs &&\n        values == o.values &&\n        row_ptr == o.row_ptr &&\n        col_ind == o.col_ind;\n  }\n\n  std::vector<int> getRowPtrWithOneBasedIndex() const {\n    std::vector<int> rowIndexed;\n    std::transform(\n        row_ptr.begin(), row_ptr.end(), std::back_inserter(rowIndexed),\n        [](int x){return x + 1;}\n    );\n    return rowIndexed;\n  }\n\n  std::vector<int> getColIndWithOneBasedIndex() const {\n    std::vector<int> colIndexed;\n    std::transform(\n        col_ind.begin(), col_ind.end(), std::back_inserter(colIndexed),\n        [](int x){return x + 1;}\n    );\n    return colIndexed;\n\n  }\n\n  CsrMatrix getLowerTriangular() const {\n    return CsrMatrix(toDok().getLowerTriangular());\n  }\n\n  CsrMatrix getUpperTriangular() const {\n    return CsrMatrix(toDok().getUpperTriangular());\n  }\n\n  Vector dot(const Vector& b) const {\n    return toDok().dot(b);\n  }\n\n  CsrMatrix sliceRows(int startRow, int nRows) const {\n    //startPos = row_ptr[startRow];\n    std::vector<int> newRowPtr, newColInd;\n    std::vector<double> newValues;\n    int nnzs = 0;\n    int offset = row_ptr[startRow];\n    for (int i = startRow; i < startRow + nRows; i++) {\n      int r = row_ptr[i];\n      newRowPtr.push_back(r - offset);\n      for (int j = r; j < row_ptr[i + 1]; j++) {\n        newValues.push_back(values[j]);\n        newColInd.push_back(col_ind[j]);\n        nnzs++;\n      }\n    }\n    newRowPtr.push_back(newValues.size());\n    return CsrMatrix(nRows, this->m, nnzs, newValues, newColInd, newRowPtr);\n  }\n\n\n  /** Slices columns from this matrix into blocks. Each block has as\n      many rows as this matrix but at most blockSize columns.  All\n      blocks except the last one have exactly blockSize columns.\n\n      Example:\n\n      This matrix:\n      1 2 3 4\n      5 6 7 8\n      sliceColumns(3) returns:\n      1 2 3 | 4\n      5 6 7 | 8\n  */\n  std::vector<cask::CsrMatrix> sliceColumns(int blockSize) const {\n    // XXX constructing a CSR matrix this way is not safe because m and n are not updated\n    int nBlocks = m / blockSize + (m % blockSize == 0 ? 0 : 1);\n    std::vector<cask::CsrMatrix> partitions(nBlocks);\n    for (int i = 0; i < n; i++) {\n      for (int j = 0; j < nBlocks; j++) {\n        auto& p = partitions[j].row_ptr;\n        if (p.size() == 0)\n          p.push_back(0);\n        else\n          p.push_back(p.back());\n      }\n      //std::cout << \"i = \" << i << std::endl;\n      //std::cout << \"colptr\" << colptr[i] << std::endl;\n      for (int j = row_ptr[i]; j < row_ptr[i+1]; j++) {\n        auto& p = partitions[col_ind[j] / blockSize];\n        int idxInPartition = col_ind[j] - (col_ind[j] / blockSize ) * blockSize;\n        p.col_ind.push_back(idxInPartition);\n        p.values.push_back(values[j]);\n        p.row_ptr.back()++;\n      }\n    }\n    return partitions;\n  }\n\n};\n\n/** A symmetric matrix for which only the lower triangle is stored explicitly, in CSR format */\nclass SymCsrMatrix {\n public:\n  int n, m;\n  int nnzs;\n  CsrMatrix matrix;\n\n  // Construct a symmetric matrix from a lower triangular matrix in DoK format\n  explicit SymCsrMatrix(const DokMatrix& l) : n(l.n), m(l.m), matrix(l) {\n    int diagNnzs = 0;\n    for (int i = 0; i < l.n; i++)\n      if (l.at(i, i) != 0)\n        diagNnzs++;\n    nnzs = 2 * (l.nnzs - diagNnzs) + diagNnzs;\n  }\n\n  void print() {\n    // matrix.print();\n  }\n\n  void pretty_print() {\n    std::cout << \"Stored matrix: \" << std::endl;\n    matrix.pretty_print();\n    std::cout << \"Implicit values: \" << std::endl;\n    matrix.toDok().explicitSymmetric().pretty_print();\n  }\n\n  Vector dot(const Vector& b) const {\n    return matrix.toDok().explicitSymmetric().dot(b);\n  }\n\n};\n\n}\n\n#endif /* end of include guard: SPARSEMATRIX_HPP_1BWMMLC8 */\n", "meta": {"hexsha": "5346e28d565d175875feeb06342aea569eb2a058", "size": 14190, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/runtime/SparseMatrix.hpp", "max_stars_repo_name": "paul-g/spark", "max_stars_repo_head_hexsha": "9e561d7a575c6a984660ba4afc476a0a7aa5264d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2015-12-02T22:31:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:18:04.000Z", "max_issues_repo_path": "src/runtime/SparseMatrix.hpp", "max_issues_repo_name": "caskorg/cask", "max_issues_repo_head_hexsha": "9e561d7a575c6a984660ba4afc476a0a7aa5264d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2018-02-02T10:07:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-02T10:07:09.000Z", "max_forks_repo_path": "src/runtime/SparseMatrix.hpp", "max_forks_repo_name": "caskorg/cask", "max_forks_repo_head_hexsha": "9e561d7a575c6a984660ba4afc476a0a7aa5264d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T09:36:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-19T17:44:55.000Z", "avg_line_length": 27.183908046, "max_line_length": 131, "alphanum_fraction": 0.5705426357, "num_tokens": 4027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.6791786861878392, "lm_q1q2_score": 0.4277294904513917}}
{"text": "// Copyright (c) 2022, ETH Zurich and UNC Chapel Hill.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above copyright\n//       notice, this list of conditions and the following disclaimer in the\n//       documentation and/or other materials provided with the distribution.\n//\n//     * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of\n//       its contributors may be used to endorse or promote products derived\n//       from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de)\n\n#include \"estimators/fundamental_matrix.h\"\n\n#include <cfloat>\n#include <complex>\n#include <vector>\n\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\n#include \"base/polynomial.h\"\n#include \"estimators/utils.h\"\n#include \"util/logging.h\"\n\nnamespace colmap {\n\nstd::vector<FundamentalMatrixSevenPointEstimator::M_t>\nFundamentalMatrixSevenPointEstimator::Estimate(\n    const std::vector<X_t>& points1, const std::vector<Y_t>& points2) {\n  CHECK_EQ(points1.size(), 7);\n  CHECK_EQ(points2.size(), 7);\n\n  // Note that no normalization of the points is necessary here.\n\n  // Setup system of equations: [points2(i,:), 1]' * F * [points1(i,:), 1]'.\n  Eigen::Matrix<double, 7, 9> A;\n  for (size_t i = 0; i < 7; ++i) {\n    const double x0 = points1[i](0);\n    const double y0 = points1[i](1);\n    const double x1 = points2[i](0);\n    const double y1 = points2[i](1);\n    A(i, 0) = x1 * x0;\n    A(i, 1) = x1 * y0;\n    A(i, 2) = x1;\n    A(i, 3) = y1 * x0;\n    A(i, 4) = y1 * y0;\n    A(i, 5) = y1;\n    A(i, 6) = x0;\n    A(i, 7) = y0;\n    A(i, 8) = 1;\n  }\n\n  // 9 unknowns with 7 equations, so we have 2D null space.\n  Eigen::JacobiSVD<Eigen::Matrix<double, 7, 9>> svd(A, Eigen::ComputeFullV);\n  const Eigen::Matrix<double, 9, 9> f = svd.matrixV();\n  Eigen::Matrix<double, 1, 9> f1 = f.col(7);\n  Eigen::Matrix<double, 1, 9> f2 = f.col(8);\n\n  f1 -= f2;\n\n  // Normalize, such that lambda + mu = 1\n  // and add constraint det(F) = det(lambda * f1 + (1 - lambda) * f2).\n\n  const double t0 = f1(4) * f1(8) - f1(5) * f1(7);\n  const double t1 = f1(3) * f1(8) - f1(5) * f1(6);\n  const double t2 = f1(3) * f1(7) - f1(4) * f1(6);\n  const double t3 = f2(4) * f2(8) - f2(5) * f2(7);\n  const double t4 = f2(3) * f2(8) - f2(5) * f2(6);\n  const double t5 = f2(3) * f2(7) - f2(4) * f2(6);\n\n  Eigen::Vector4d coeffs;\n  coeffs(0) = f1(0) * t0 - f1(1) * t1 + f1(2) * t2;\n  coeffs(1) = f2(0) * t0 - f2(1) * t1 + f2(2) * t2 -\n              f2(3) * (f1(1) * f1(8) - f1(2) * f1(7)) +\n              f2(4) * (f1(0) * f1(8) - f1(2) * f1(6)) -\n              f2(5) * (f1(0) * f1(7) - f1(1) * f1(6)) +\n              f2(6) * (f1(1) * f1(5) - f1(2) * f1(4)) -\n              f2(7) * (f1(0) * f1(5) - f1(2) * f1(3)) +\n              f2(8) * (f1(0) * f1(4) - f1(1) * f1(3));\n  coeffs(2) = f1(0) * t3 - f1(1) * t4 + f1(2) * t5 -\n              f1(3) * (f2(1) * f2(8) - f2(2) * f2(7)) +\n              f1(4) * (f2(0) * f2(8) - f2(2) * f2(6)) -\n              f1(5) * (f2(0) * f2(7) - f2(1) * f2(6)) +\n              f1(6) * (f2(1) * f2(5) - f2(2) * f2(4)) -\n              f1(7) * (f2(0) * f2(5) - f2(2) * f2(3)) +\n              f1(8) * (f2(0) * f2(4) - f2(1) * f2(3));\n  coeffs(3) = f2(0) * t3 - f2(1) * t4 + f2(2) * t5;\n\n  Eigen::VectorXd roots_real;\n  Eigen::VectorXd roots_imag;\n  if (!FindPolynomialRootsCompanionMatrix(coeffs, &roots_real, &roots_imag)) {\n    return {};\n  }\n\n  std::vector<M_t> models;\n  models.reserve(roots_real.size());\n\n  for (Eigen::VectorXd::Index i = 0; i < roots_real.size(); ++i) {\n    const double kMaxRootImag = 1e-10;\n    if (std::abs(roots_imag(i)) > kMaxRootImag) {\n      continue;\n    }\n\n    const double lambda = roots_real(i);\n    const double mu = 1;\n\n    Eigen::MatrixXd F = lambda * f1 + mu * f2;\n\n    F.resize(3, 3);\n\n    const double kEps = 1e-10;\n    if (std::abs(F(2, 2)) < kEps) {\n      continue;\n    }\n\n    F /= F(2, 2);\n\n    models.push_back(F.transpose());\n  }\n\n  return models;\n}\n\nvoid FundamentalMatrixSevenPointEstimator::Residuals(\n    const std::vector<X_t>& points1, const std::vector<Y_t>& points2,\n    const M_t& F, std::vector<double>* residuals) {\n  ComputeSquaredSampsonError(points1, points2, F, residuals);\n}\n\nstd::vector<FundamentalMatrixEightPointEstimator::M_t>\nFundamentalMatrixEightPointEstimator::Estimate(\n    const std::vector<X_t>& points1, const std::vector<Y_t>& points2) {\n  CHECK_EQ(points1.size(), points2.size());\n\n  // Center and normalize image points for better numerical stability.\n  std::vector<X_t> normed_points1;\n  std::vector<Y_t> normed_points2;\n  Eigen::Matrix3d points1_norm_matrix;\n  Eigen::Matrix3d points2_norm_matrix;\n  CenterAndNormalizeImagePoints(points1, &normed_points1, &points1_norm_matrix);\n  CenterAndNormalizeImagePoints(points2, &normed_points2, &points2_norm_matrix);\n\n  // Setup homogeneous linear equation as x2' * F * x1 = 0.\n  Eigen::Matrix<double, Eigen::Dynamic, 9> cmatrix(points1.size(), 9);\n  for (size_t i = 0; i < points1.size(); ++i) {\n    cmatrix.block<1, 3>(i, 0) = normed_points1[i].homogeneous();\n    cmatrix.block<1, 3>(i, 0) *= normed_points2[i].x();\n    cmatrix.block<1, 3>(i, 3) = normed_points1[i].homogeneous();\n    cmatrix.block<1, 3>(i, 3) *= normed_points2[i].y();\n    cmatrix.block<1, 3>(i, 6) = normed_points1[i].homogeneous();\n  }\n\n  // Solve for the nullspace of the constraint matrix.\n  Eigen::JacobiSVD<Eigen::Matrix<double, Eigen::Dynamic, 9>> cmatrix_svd(\n      cmatrix, Eigen::ComputeFullV);\n  const Eigen::VectorXd cmatrix_nullspace = cmatrix_svd.matrixV().col(8);\n  const Eigen::Map<const Eigen::Matrix3d> ematrix_t(cmatrix_nullspace.data());\n\n  // Enforcing the internal constraint that two singular values must non-zero\n  // and one must be zero.\n  Eigen::JacobiSVD<Eigen::Matrix3d> fmatrix_svd(\n      ematrix_t.transpose(), Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Eigen::Vector3d singular_values = fmatrix_svd.singularValues();\n  singular_values(2) = 0.0;\n  const Eigen::Matrix3d F = fmatrix_svd.matrixU() *\n                            singular_values.asDiagonal() *\n                            fmatrix_svd.matrixV().transpose();\n\n  const std::vector<M_t> models = {points2_norm_matrix.transpose() * F *\n                                   points1_norm_matrix};\n  return models;\n}\n\nvoid FundamentalMatrixEightPointEstimator::Residuals(\n    const std::vector<X_t>& points1, const std::vector<Y_t>& points2,\n    const M_t& E, std::vector<double>* residuals) {\n  ComputeSquaredSampsonError(points1, points2, E, residuals);\n}\n\n}  // namespace colmap\n", "meta": {"hexsha": "3a29afbd7805f377afc3e0e058af434c0db98bdc", "size": 7649, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/estimators/fundamental_matrix.cc", "max_stars_repo_name": "ashishd/colmap", "max_stars_repo_head_hexsha": "30521f19de45c1cb2df8809728e780bf95fc8836", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-02-18T04:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T04:59:13.000Z", "max_issues_repo_path": "src/estimators/fundamental_matrix.cc", "max_issues_repo_name": "hyowonha/colmap", "max_issues_repo_head_hexsha": "d908cc37cbf97701b589a047274e3a7fbaf17c54", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/estimators/fundamental_matrix.cc", "max_forks_repo_name": "hyowonha/colmap", "max_forks_repo_head_hexsha": "d908cc37cbf97701b589a047274e3a7fbaf17c54", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8663366337, "max_line_length": 80, "alphanum_fraction": 0.6328931887, "num_tokens": 2514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4276199223186165}}
{"text": "// std includes\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <sstream>\n#include <cmath>\n#include <ctime>\n#include <memory>\n\n// Armadillo includes and preprocessors\n#include <armadillo>\n#include <viennacl/ocl/forwards.h>\n// ViennaCL includes\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/gmres.hpp\"\n#include \"viennacl/linalg/bicgstab.hpp\"\n#include \"viennacl/linalg/ilu.hpp\"\n//#include \"viennacl/linalg/ilu/chow_patel_ilu.hpp\"\n#include \"viennacl/linalg/lu.hpp\"\n#include \"viennacl/linalg/amg.hpp\"\n#include \"viennacl/linalg/sum.hpp\"\n#include \"viennacl/linalg/maxmin.hpp\"\n#include \"viennacl/tools/timer.hpp\"\n#include \"viennacl/forwards.h\"\n\n// Main CoMFi include\n#include \"comfi.hpp\"\n\nusing namespace std;\n\nint main(int argc, char** argv) {\n\n  // Create intermediate variable but use constant for safety\n\tcomfi::types::Settings __set;\n\tif (argc > 1) {\n\t\tcomfi::util::interpret_arguments(__set, argc, argv);\n\t}\n  const comfi::types::Settings settings = __set;\n\n  // Create context\n  comfi::types::Context ctx(1,\n                            400,\n                            comfi::types::NEUMANN,\n                            comfi::types::NEUMANN,\n                            comfi::types::NEUMANN,\n                            comfi::types::NEUMANN);\n  unique_ptr<vcl_mat> xn_vcl(new vcl_mat(comfi::util::shock_tube_ic(ctx)));\n  //unique_ptr<vcl_mat> xn_vcl(new vcl_mat(comfi::util::ot_vortex_ic(ctx)));\n  unique_ptr<vcl_mat> xn1_vcl(new vcl_mat(*xn_vcl));\n  comfi::util::save_solution(*xn_vcl, ctx);\n\n  // Initial std output\n  cout << \"Begin CoMFi Simulation\" << endl;\n  cout << \"======================\" << endl \n       << endl;\n  #ifdef VIENNACL_WITH_OPENCL\n    cout << \"Device Info:\" << endl \n         << \"------------\" << endl \n         << viennacl::ocl::current_device().info()\n         << endl;\n  #endif\n  #ifdef _OPENMP\n    cout << \"OpenMP Info:\" << endl\n         << \"------------\" << endl\n         << \"- OMP Max threads: \" << omp_get_max_threads() << endl\n         << \"- OMP Devices: \" << omp_get_default_device() << \"/\" << omp_get_num_devices() << endl\n         << endl;\n  #endif\n  cout << \"Parameters:\" << endl;\n  cout << \"-----------\" << endl;\n  cout << \"- Grid size: (\" << ctx.nz << \", \" << ctx.nx << \") \" << endl\n       << \"- Normalization constants:\" << endl\n       << \" - \" << \"n_0: \" << ctx.n_0 << \" m^-3\" << endl\n       << \" - \" << \"L_0: \" << ctx.l_0 << \" m\" << endl\n       << \" - \" << \"t_0: \" << ctx.t_0 << \" s\" << endl\n       << \" - \" << \"V_0: \" << ctx.V_0 << \" m/s\" << endl\n       << \" - \" << \"B_0: \" << ctx.B_0/0.1e-3 << \" G\" << endl\n       << \" - \" << \"e_0: \" << ctx.e_0 << \" C\" << endl\n       << \" - \" << \"T_0: \" << ctx.T_0 << \" K\" << endl\n       << \" - \" << \"p_0: \"<< ctx.p_0 << \" Pa\" << endl\n       << \" - \" << \"Width: \" << ctx.width << \" m\" << endl\n       << \" - \" << \"Height: \" << ctx.height << \" m\" << endl\n       << \" - \" << \"dx: \" << ctx.dx*ctx.l_0 << \" m | \" << \"dz: \" << ctx.dz*ctx.l_0 << \" m | \"\n                << \"ds: \" << ctx.ds*ctx.l_0 << \" m\" << endl\n       << endl;\n\n  //Initiate\n  viennacl::tools::timer vcl_timer[2]; // timers\n  //auto init = mhdsim::util::calcInitialCondition(op);\n  //auto init = mhdsim::util::calcReconnectionIC(op);\n  //auto init = comfi::util::calcShockTubeIC(op);\n  //auto init = comfi::util::calcSolerIC(op);\n  //arma::vec x0 = std::get<0>(init);\n  //const comfi::types::BgData bg;\n\n  cout << \"Compiling kernels ... \";\n  std::ifstream phi_file(\"kernels_ocl/phi.c\");\n  string phi_code((std::istreambuf_iterator<char>(phi_file)),\n                   std::istreambuf_iterator<char>()\n                 );\n  viennacl::ocl::program & phi_prog = viennacl::ocl::current_context().add_program(phi_code.c_str(), \"fluxl\"); // compile flux opencl kernel\n  std::ifstream eig_file(\"kernels_ocl/element_max.c\");\n  string eig_code((std::istreambuf_iterator<char>(eig_file)),\n                   std::istreambuf_iterator<char>()\n                 );\n  viennacl::ocl::program & eig_prog = viennacl::ocl::current_context().add_program(eig_code.c_str(), \"element_max\"); // compile eigenvalue opencl kernel\n  cout << \"built.\" << endl;\n\n  // Full execution timer\n  vcl_timer[0].start();\n  \n  // Begin solving/advancing\n  while (((ctx.time_step() < settings.max_time_steps) || (settings.max_time_steps < 0)) &&\n         ((ctx.time_elapsed() < settings.max_time) || (settings.max_time < 0.0))) {\n\n    double solve_time=0.0, build_time=0.0;\n\n    // Figure out time step\n    const double V = comfi::util::getmaxV(*xn_vcl, ctx);\n    cout << \"Char speed: \"  << V << \" V_0\" << endl;\n    const double ds = (ctx.dx>ctx.dz)*ctx.dz + (ctx.dz>=ctx.dx)*ctx.dx;\n    ctx.set_dt(0.8*0.5*ds/V);\n    cout << \"dt: \" << ctx.dt() << \" t_0\";\n    cout << \"\\t| Time: \" << ctx.time_elapsed() << \" t_0\" << endl;\n\n    /* //Update loop stuff */\n    /* t(ctx.time_step()) = ctx.time_elapsed(); */\n    /* dt_n(ctx.time_step()) = ctx.dt(); */\n\n    cout << ctx.time_step() << \": \" ;\n\n    vcl_timer[1].start();\n    //const arma::sp_mat Ri_cpu = mhdsim::routines::computeRi(*xn_vcl, op);\n    //static const arma::sp_mat one = arma::speye(num_of_elem, num_of_elem);\n    //const arma::sp_mat LHS_cpu = one + Ri_cpu*dt; // Euler\n    //vcl_sp_mat LHS;\n    //viennacl::copy(LHS_cpu, LHS);\n    build_time = vcl_timer[1].get();\n    \n    vcl_timer[1].start();\n    //GMRES\n    // solve (e.g. using GMRES solver)\n    // create and compute preconditioner:\n    //viennacl::linalg::ilu0_tag ilu0_config(true);\n    //viennacl::linalg::block_ilu_precond<vcl_sp_mat, viennacl::linalg::ilu0_tag> vcl_precond(LHS, ilu0_config);\n    //viennacl::linalg::ilu0_precond< vcl_sp_mat > vcl_precond(LHS, viennacl::linalg::ilu0_tag());\n    //viennacl::linalg::gmres_tag my_solver_tag(tolerance, 100, 20);\n    //viennacl::linalg::bicgstab_tag my_solver_tag(tolerance, 100, 20);\n    //unique_ptr<vcl_vec> x0_vcl(new vcl_vec(viennacl::linalg::solve(LHS, RHS, my_solver_tag, vcl_precond)));\n    /* unique_ptr<vcl_mat> x0_vcl(new vcl_mat(comfi::routines::computeRHS_Euler(*xn_vcl, ctx))); */\n    unique_ptr<vcl_mat> x0_vcl(new vcl_mat(comfi::routines::computeRHS_RK4(*xn_vcl, ctx)));\n    ctx.advance();\n    solve_time = vcl_timer[1].get();\n\n//    cout << \" GMRES(\" << my_solver_tag.iters();\n//    cout << \",\" << my_solver_tag.error();\n//    cout << \") | Build Time:\" << build_time;\n//    cout << \"s\\t| Sol Time:\" << solve_time << \"s\" << endl;\n//    const double sol_error = my_solver_tag.error();\n    /* double sol_error = 0; */\n\n    //mhdsim::util::save_solution(x0_vcl, -1, op);\n    //mhdsim::util::save_solution(xn_vcl, -2, op);\n    //mhdsim::util::save_solution(xn1_vcl, -3, op);\n\n    //Save solution every save_dt time\n    static double time_since_last_save = 0.0;\n    time_since_last_save += ctx.dt();\n    if ((time_since_last_save > settings.save_dt) && (settings.save_dt > 0.0)) {\n      comfi::util::save_solution(*x0_vcl, ctx);\n      time_since_last_save = 0.0;\n    }\n\n    //Save solution every save_dn steps\n    if ((ctx.time_step()%settings.save_dn == 0) && (settings.save_dn > 0)) {\n      comfi::util::save_solution(*x0_vcl, ctx);\n    }\n\n    // Move pointers before starting next step\n    xn1_vcl = std::move(xn_vcl);\n    xn_vcl = std::move(x0_vcl);\n\n  }\n\n  cout << \"Total exec time: \" << vcl_timer[0].get() << endl;\n\n  return 0;\n}\n\n/*\nvim: tabstop=2\nvim: shiftwidth=2\nvim: smarttab\nvim: expandtab\n*/\n", "meta": {"hexsha": "b617e3cb10b42635beee7f37f33bc2436be8cd6d", "size": 7420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "qalshidi/comfi", "max_stars_repo_head_hexsha": "59835f0ab4f54dea0ecb44405f583c9c06ad21bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-17T22:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T22:10:35.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "qalshidi/comfi", "max_issues_repo_head_hexsha": "59835f0ab4f54dea0ecb44405f583c9c06ad21bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "qalshidi/comfi", "max_forks_repo_head_hexsha": "59835f0ab4f54dea0ecb44405f583c9c06ad21bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2864321608, "max_line_length": 152, "alphanum_fraction": 0.5919137466, "num_tokens": 2319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.42761992231861645}}
{"text": "//sensor_msgs/Imu \n\n#include <opencv2/opencv.hpp>\n#include <cv_bridge/cv_bridge.h>\n#include <vector>\n#include <iostream>\n#include <boost/regex.hpp>\n#include <boost/filesystem.hpp>\n\n#include <message_filters/subscriber.h>\n#include <message_filters/synchronizer.h>\n#include <message_filters/sync_policies/approximate_time.h>\n#include \"sensor_msgs/Imu.h\"\n#include \"nav_msgs/Odometry.h\"\n#include \"std_msgs/Bool.h\"\n\n#include <Eigen/Eigen>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Eigen/Eigenvalues>\n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\nstatic void toEulerAngle(const Quaterniond& q, double& roll, double& pitch, double& yaw)\n{\n// roll (x-axis rotation)\ndouble sinr_cosp = +2.0 * (q.w() * q.x() + q.y() * q.z());\ndouble cosr_cosp = +1.0 - 2.0 * (q.x() * q.x() + q.y() * q.y());\nroll = atan2(sinr_cosp, cosr_cosp);\n\n// pitch (y-axis rotation)\ndouble sinp = +2.0 * (q.w() * q.y() - q.z() * q.x());\nif (fabs(sinp) >= 1)\npitch = copysign(M_PI / 2, sinp); // use 90 degrees if out of range\nelse\npitch = asin(sinp);\n\n// yaw (z-axis rotation)\ndouble siny_cosp = +2.0 * (q.w() * q.z() + q.x() * q.y());\ndouble cosy_cosp = +1.0 - 2.0 * (q.y() * q.y() + q.z() * q.z());\nyaw = atan2(siny_cosp, cosy_cosp);\n}\nstatic float toAngle(double& r)\n{\n    return 180 * r / M_PI;\n}\nclass message_sync_ros_node\n{\nprivate:\n    ros::NodeHandle node_;\n    ros::Subscriber init_sub,yt_sub,imu_sub;\n    typedef message_filters::sync_policies::ApproximateTime<nav_msgs::Odometry, sensor_msgs::Imu> slamSyncPolicy;\n    message_filters::Subscriber<nav_msgs::Odometry> *yt_sub_;\n    message_filters::Subscriber<sensor_msgs::Imu> *imu_sub_;\n    message_filters::Synchronizer<slamSyncPolicy> *sync_;\n    std::string yt_topic;\n    std::string imu_topic;\n    std::string root_path;\n    bool is_record,is_init;\n    ofstream map_points;\n    stringstream gss;\n    float init_yt_x,init_yt_y,init_yt_z,init_imu_x,init_imu_y,init_imu_z;\n\npublic:\n    message_sync_ros_node();\n    ~message_sync_ros_node();\n    void callback(const nav_msgs::Odometry::ConstPtr &yt_data,const sensor_msgs::Imu::ConstPtr &imu_data);\n    void update();\n    void initCB(const std_msgs::Bool::ConstPtr &msg);\n    void ytCB(const nav_msgs::Odometry::ConstPtr &yt_data);\n    void imuCB(const sensor_msgs::Imu::ConstPtr &imu_data);\n    void isDirectory(string path);\n};\n\nmessage_sync_ros_node::message_sync_ros_node()\n{\n    is_record = false;\n    is_init = false;\n    //map_points.open(\"/home/li/capture/0919/record.txt\", ios_base::app);\n    ros::param::get(\"/sync_imu/yt_topic\", yt_topic);\n    ros::param::get(\"/sync_imu/imu_topic\", imu_topic);\n    ros::param::get(\"/sync_imu/root_path\", root_path);\n    std::cout << \"yt_topic:\" << yt_topic << std::endl;\n    std::cout << \"imu_topic:\" << imu_topic << std::endl;\n    std::cout << \"root_path:\" << root_path << std::endl;\n\n    isDirectory(root_path);\n    string record_path = root_path + \"/record.txt\";\n    map_points.open(record_path, ios_base::app);\n    init_sub = node_.subscribe<std_msgs::Bool>(\"sync_imu/init\", 1, &message_sync_ros_node::initCB, this);\n    yt_sub_ = new message_filters::Subscriber<nav_msgs::Odometry>(node_, yt_topic, 1);\n    imu_sub_ = new message_filters::Subscriber<sensor_msgs::Imu>(node_, imu_topic, 1);\n    sync_ = new message_filters::Synchronizer<slamSyncPolicy>(slamSyncPolicy(20), *yt_sub_, *imu_sub_);\n    sync_->registerCallback(boost::bind(&message_sync_ros_node::callback, this, _1, _2));\n\n    //sub\n    yt_sub = node_.subscribe<nav_msgs::Odometry>(yt_topic, 1, &message_sync_ros_node::ytCB, this);\n    imu_sub = node_.subscribe<sensor_msgs::Imu>(imu_topic, 1, &message_sync_ros_node::imuCB, this);\n}\n\nvoid message_sync_ros_node::initCB(const std_msgs::Bool::ConstPtr &msg){\n    std::cout << \"initCB \" << std::endl;\n     is_init = true;\n}\n\nmessage_sync_ros_node::~message_sync_ros_node()\n{\n    map_points.close();\n}\n\nvoid message_sync_ros_node::update()\n{\n   std::cout << \"update \" << std::endl;\n}\n\nvoid message_sync_ros_node::isDirectory(string path)\n{\n    //判断根目录下是否存在子目录，不存在创建\n    if (!boost::filesystem::exists(path))\n    {\n        boost::filesystem::create_directory(path);\n    }\n}\n\nvoid message_sync_ros_node::callback(const nav_msgs::Odometry::ConstPtr &yt_data,const sensor_msgs::Imu::ConstPtr &imu_data)\n{\n    std::cout << \"sync message\" << std::endl;\n    // nav_msgs::Odometry current_pose;\n    // current_pose = *odom_data;\n    float angle_x = yt_data->pose.pose.position.x;\n    float angle_y = yt_data->pose.pose.position.y;\n    float angle_z = yt_data->pose.pose.position.z;\n    //std::cout << \"angle_x:\" << angle_x<< \" angle_y:\" << angle_y<< \" angle_z:\" << angle_z << std::endl;\n    //\n    //float imu_x = imu_data->orientation.x;\n    geometry_msgs::Quaternion qua = imu_data->orientation;\n    Eigen::Quaterniond q(qua.w, qua.x, qua.y, qua.z);\n    double roll,pitch,yaw;\n    toEulerAngle(q,roll,pitch,yaw);\n    //std::cout << \"roll:\" << roll<< \" pitch:\" << pitch<< \" yaw:\" << yaw << std::endl;\n    if(is_init){\n        std::cout << \"init:\" << std::endl;\n        init_yt_x = angle_x;\n        init_yt_y = angle_y;\n        init_yt_z = angle_z;\n        init_imu_x = toAngle(roll);\n        init_imu_y = toAngle(pitch);\n        init_imu_z = toAngle(yaw);\n        is_init = false;\n    }\n    float dx = abs(angle_x - init_yt_x)/100;\n    float dy = abs(angle_y - init_yt_y)/100;\n    float dz = abs(angle_z - init_yt_z)/100;\n    std::cout << \"ptz dx:\" << dx<< \" dy:\" << dy << \" dz:\" << dz << std::endl;\n    map_points << \"ptz dx:\" << dx<< \" dy:\" << dy << \" dz:\" << dz << std::endl;\n    dx = abs(toAngle(roll) - init_imu_x);\n    dy = abs(toAngle(pitch) - init_imu_y);\n    dz = abs(toAngle(yaw) - init_imu_z);\n    //std::cout << \"roll:\" << toAngle(roll)<< \" pitch:\" << toAngle(pitch) << \" yaw:\" << toAngle(yaw) << std::endl;\n    std::cout << \"imu dx:\" << dx<< \" dy:\" << dy << \" dz:\" << dz << std::endl;\n    map_points << \"imu dx:\" << dx<< \" dy:\" << dy << \" dz:\" << dz << std::endl;\n}\n\nvoid message_sync_ros_node::ytCB(const nav_msgs::Odometry::ConstPtr &yt_data)\n{\n    float angle_x = abs(yt_data->pose.pose.position.x)/100;\n    float angle_y = abs(yt_data->pose.pose.position.y)/100;\n    float angle_z = abs(yt_data->pose.pose.position.z)/100; \n    std::cout << \"PTZ data receive time:\" << yt_data->header.stamp << \" angle_x:\" << angle_x<< \" angle_y:\" << angle_y << \" angle_z:\" << angle_z << std::endl;\n    map_points << \"PTZ data receive time:\" << yt_data->header.stamp << \" angle_x:\" << angle_x<< \" angle_y:\" << angle_y << \" angle_z:\" << angle_z << std::endl;\n}\n\nvoid message_sync_ros_node::imuCB(const sensor_msgs::Imu::ConstPtr &imu_data)\n{\n    geometry_msgs::Quaternion qua = imu_data->orientation;\n    Eigen::Quaterniond q(qua.w, qua.x, qua.y, qua.z);\n    double roll,pitch,yaw;\n    toEulerAngle(q,roll,pitch,yaw);\n    if(is_init){\n        std::cout << \"init:\" << std::endl;\n        init_imu_x = toAngle(roll);\n        init_imu_y = toAngle(pitch);\n        init_imu_z = toAngle(yaw);\n        is_init = false;\n    }\n    float dx = abs(toAngle(roll) - init_imu_x);\n    float dy = abs(toAngle(pitch) - init_imu_y);\n    float dz = abs(toAngle(yaw) - init_imu_z);\n    std::cout << \"IMU data receive time:\" << imu_data->header.stamp << \" roll:\" << dx<< \" pitch:\" << dy << \" yaw:\" << dz << std::endl;\n    map_points << \"IMU data receive time:\" << imu_data->header.stamp << \" roll:\" << dx<< \" pitch:\" << dy << \" yaw:\" << dz << std::endl;\n}\n\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"message_sync_node\");\n    message_sync_ros_node node;\n\n    ROS_INFO(\"message_sync_node node started...\");\n    ros::Rate rate(10);\n\n    while (ros::ok())\n    {\n        ros::spinOnce();\n        rate.sleep();\n    }\n\n    return 0;\n}", "meta": {"hexsha": "ca95fd1d8f0e1bf22387397e1dd1872b7ffcac36", "size": 7687, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "message_sync/src/sync_imu.cpp", "max_stars_repo_name": "l756302098/ros_practice", "max_stars_repo_head_hexsha": "4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "message_sync/src/sync_imu.cpp", "max_issues_repo_name": "l756302098/ros_practice", "max_issues_repo_head_hexsha": "4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "message_sync/src/sync_imu.cpp", "max_forks_repo_name": "l756302098/ros_practice", "max_forks_repo_head_hexsha": "4da8b4ddb25ada2e6f1adb3c0f8b34576aedf6b7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4312796209, "max_line_length": 158, "alphanum_fraction": 0.6474567452, "num_tokens": 2276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255928, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.42761991621804823}}
{"text": "// Copyright (c) Dietmar Wolz.\r\n//\r\n// This source code is licensed under the MIT license found in the\r\n// LICENSE file in the root directory.\r\n\r\n// Eigen based implementation of differential evolution using on the DE/best/1 strategy.\r\n// Uses two deviations from the standard DE algorithm:\r\n// a) temporal locality introduced in \r\n// https://www.researchgate.net/publication/309179699_Differential_evolution_for_protein_folding_optimization_based_on_a_three-dimensional_AB_off-lattice_model\r\n// b) reinitialization of individuals based on their age. \r\n// requires https://github.com/imneme/pcg-cpp\r\n//\r\n// Supports parallel fitness function evaluation. \r\n// \r\n// You may keep parameters F and CR at their defaults since this implementation works well with the given settings for most problems,\r\n// since the algorithm oscillates between different F and CR settings.\r\n//\r\n// For expensive objective functions (e.g. machine learning parameter optimization) use the workers\r\n// parameter to parallelize objective function evaluation. The workers parameter is limited by the\r\n// population size.\r\n//\r\n// The ints parameter is a boolean array indicating which parameters are discrete integer values. This\r\n// parameter was introduced after observing non optimal DE-results for the ESP2 benchmark problem:\r\n// https://github.com/AlgTUDelft/ExpensiveOptimBenchmark/blob/master/expensiveoptimbenchmark/problems/DockerCFDBenchmark.py\r\n// If defined it causes a \"special treatment\" for discrete variables: They are rounded to the next integer value and\r\n// there is an additional mutation to avoid getting stuck at local minima.\r\n\r\n#include <Eigen/Core>\r\n#include <iostream>\r\n#include <float.h>\r\n#include <stdint.h>\r\n#include <ctime>\r\n#include <random>\r\n#include <queue>\r\n#include <tuple>\r\n#include \"pcg_random.hpp\"\r\n#include \"evaluator.h\"\r\n\r\nusing namespace std;\r\n\r\nnamespace differential_evolution {\r\n\r\nclass DeOptimizer {\r\n\r\npublic:\r\n\r\n    DeOptimizer(long runid_, Fitness *fitfun_, int dim_, int seed_,\r\n            int popsize_, int maxEvaluations_, double keep_,\r\n            double stopfitness_, double F_, double CR_, bool *isInt_) {\r\n        // runid used to identify a specific run\r\n        runid = runid_;\r\n        // fitness function to minimize\r\n        fitfun = fitfun_;\r\n        // Number of objective variables/problem dimension\r\n        dim = dim_;\r\n        // Population size\r\n        popsize = popsize_ > 0 ? popsize_ : 15 * dim;\r\n        // maximal number of evaluations allowed.\r\n        maxEvaluations = maxEvaluations_ > 0 ? maxEvaluations_ : 50000;\r\n        // keep best young after each iteration.\r\n        keep = keep_ > 0 ? keep_ : 30;\r\n        // Limit for fitness value.\r\n        stopfitness = stopfitness_;\r\n        F = F0 = F_ > 0 ? F_ : 0.5;\r\n        CR = CR0 = CR_ > 0 ? CR_ : 0.9;\r\n        // Number of iterations already performed.\r\n        iterations = 0;\r\n        bestY = DBL_MAX;\r\n        // stop criteria\r\n        stop = 0;\r\n        pos = 0;\r\n        //std::random_device rd;\r\n        rs = new pcg64(seed_);\r\n        // Indicating which parameters are discrete integer values. If defined these parameters will be\r\n        // rounded to the next integer and some additional mutation of discrete parameters are performed.\r\n        isInt = isInt_;\r\n        init();\r\n    }\r\n\r\n    ~DeOptimizer() {\r\n        delete rs;\r\n    }\r\n\r\n    double rnd01() {\r\n        return distr_01(*rs);\r\n    }\r\n\r\n    int rndInt(int max) {\r\n        return (int) (max * distr_01(*rs));\r\n    }\r\n\r\n    vec nextX(int p, const vec &xp, const vec &xb) {\r\n        if (p == 0) {\r\n            iterations++;\r\n            CR = iterations % 2 == 0 ? 0.5 * CR0 : CR0;\r\n            F = iterations % 2 == 0 ? 0.5 * F0 : F0;\r\n        }\r\n        int r1, r2;\r\n        do {\r\n            r1 = rndInt(popsize);\r\n        } while (r1 == p || r1 == bestI);\r\n        do {\r\n            r2 = rndInt(popsize);\r\n        } while (r2 == p || r2 == bestI || r2 == r1);\r\n        vec x1 = popX.col(r1);\r\n        vec x2 = popX.col(r2);\r\n        vec x = xb + (x1 - x2) * F;\r\n        int r = rndInt(dim);\r\n        for (int j = 0; j < dim; j++)\r\n            if (j != r && rnd01() > CR)\r\n                x[j] = xp[j];\r\n        vec nextx = fitfun->getClosestFeasible(x);\r\n        modify(nextx);\r\n        return nextx;\r\n    }\r\n\r\n    vec next_improve(const vec &xb, const vec &x, const vec &xi) {\r\n        vec nextx = fitfun->getClosestFeasible(xb + ((x - xi) * 0.5));\r\n        modify(nextx);\r\n        return nextx;\r\n    }\r\n\r\n    void modify(vec &x) {\r\n        if (isInt == NULL)\r\n            return;\r\n        double n_ints = 0;\r\n        for (int i = 0; i < dim; i++)\r\n            if (isInt[i]) n_ints++;\r\n        double min_mutate = 0.5;\r\n        double max_mutate = std::max(1.0, n_ints/20.0);\r\n        double to_mutate = min_mutate + rnd01()*(max_mutate - min_mutate);\r\n        for (int i = 0; i < dim; i++) {\r\n            if (isInt[i]) {\r\n                if (rnd01() < to_mutate/n_ints)\r\n                    x[i] = fitfun->sample_i(i, *rs); // resample\r\n                x[i] = std::round(x[i]);\r\n            }\r\n        }\r\n    }\r\n\r\n    vec ask(int &p) {\r\n        // ask for one new argument vector.\r\n        if (improvesX.empty()) {\r\n            p = pos;\r\n            vec x = nextX(p, popX.col(p), popX.col(bestI));\r\n            pos = (pos + 1) % popsize;\r\n            return x;\r\n        } else {\r\n            p = improvesP.front();\r\n            vec x = improvesX.front();\r\n            improvesP.pop();\r\n            improvesX.pop();\r\n            return x;\r\n        }\r\n    }\r\n\r\n    int tell(double y, const vec &x, int p) {\r\n        //tell function value for a argument list retrieved by ask_one().\r\n        if (isfinite(y) && y < popY[p]) {\r\n            if (iterations > 1) {\r\n                // temporal locality\r\n                improvesP.push(p);\r\n                improvesX.push(next_improve(popX.col(bestI), x, popX0.col(p)));\r\n            }\r\n            popX0.col(p) = popX.col(p);\r\n            popX.col(p) = x;\r\n            popY[p] = y;\r\n            popIter[p] = iterations;\r\n            if (y < popY[bestI]) {\r\n                bestI = p;\r\n                if (y < bestY) {\r\n                    bestY = y;\r\n                    bestX = x;\r\n                    if (isfinite(stopfitness) && bestY < stopfitness)\r\n                        stop = 1;\r\n                }\r\n            }\r\n        } else {\r\n            // reinitialize individual\r\n            if (keep * rnd01() < iterations - popIter[p]) {\r\n                popX.col(p) = fitfun->sample(*rs);\r\n                popY[p] = DBL_MAX;\r\n            }\r\n        }\r\n        return stop;\r\n    }\r\n\r\n    void doOptimize() {\r\n\r\n        // -------------------- Generation Loop --------------------------------\r\n        for (iterations = 1; fitfun->evaluations() < maxEvaluations\r\n        \t\t&& !fitfun->terminate(); iterations++) {\r\n\r\n            CR = iterations % 2 == 0 ? 0.5 * CR0 : CR0;\r\n            F = iterations % 2 == 0 ? 0.5 * F0 : F0;\r\n\r\n            for (int p = 0; p < popsize; p++) {\r\n                vec xp = popX.col(p);\r\n                vec xb = popX.col(bestI);\r\n                int r1, r2;\r\n                do {\r\n                    r1 = rndInt(popsize);\r\n                } while (r1 == p || r1 == bestI);\r\n                do {\r\n                    r2 = rndInt(popsize);\r\n                } while (r2 == p || r2 == bestI || r2 == r1);\r\n                vec x1 = popX.col(r1);\r\n                vec x2 = popX.col(r2);\r\n                int r = rndInt(dim);\r\n                vec x = vec(xp);\r\n                for (int j = 0; j < dim; j++) {\r\n                    if (j == r || rnd01() < CR) {\r\n                        x[j] = xb[j] + F * (x1[j] - x2[j]);\r\n                        if (!fitfun->feasible(j, x[j]))\r\n                            x[j] = fitfun->sample_i(j, *rs);\r\n                    }\r\n                }\r\n                modify(x);\r\n                double y = fitfun->eval(x)(0);\r\n                if (isfinite(y) && y < popY[p]) {\r\n                    // temporal locality\r\n                    vec x2 = next_improve(xb, x, xp);\r\n                    double y2 = fitfun->eval(x2)(0);\r\n                    if (isfinite(y2) && y2 < y) {\r\n                        y = y2;\r\n                        x = x2;\r\n                    }\r\n                    popX.col(p) = x;\r\n                    popY(p) = y;\r\n                    popIter[p] = iterations;\r\n                    if (y < popY[bestI]) {\r\n                        bestI = p;\r\n                        if (y < bestY) {\r\n                            bestY = y;\r\n                            bestX = x;\r\n                            if (isfinite(stopfitness) && bestY < stopfitness) {\r\n                                stop = 1;\r\n                                return;\r\n                            }\r\n                        }\r\n                    }\r\n                } else {\r\n                    // reinitialize individual\r\n                    if (keep * rnd01() < iterations - popIter[p]) {\r\n                        popX.col(p) = fitfun->sample(*rs);\r\n                        popY[p] = DBL_MAX;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    void do_optimize_delayed_update(int workers) {\r\n    \t iterations = 0;\r\n    \t fitfun->resetEvaluations();\r\n         workers = std::min(workers, popsize); // workers <= popsize\r\n    \t evaluator eval(fitfun, 1, workers);\r\n         int evals_size = popsize*10;\r\n    \t vec evals_x[evals_size];\r\n   \t     int evals_p[evals_size];\r\n         int cp = 0; \r\n         \r\n\t     // fill eval queue with initial population\r\n    \t for (int i = 0; i < workers; i++) {\r\n    \t\t int p;\r\n    \t\t vec x = ask(p);\r\n    \t\t eval.evaluate(x, cp);\r\n    \t\t evals_x[cp] = x;\r\n    \t\t evals_p[cp] = p;\r\n             cp = (cp + 1) % evals_size;             \r\n    \t }\r\n    \t while (fitfun->evaluations() < maxEvaluations && !fitfun->terminate()) {\r\n    \t\t vec_id* vid = eval.result();\r\n    \t\t vec y = vec(vid->_v);\r\n    \t\t int id = vid->_id;\r\n    \t\t delete vid;\r\n    \t\t vec x = evals_x[id];\r\n             int p = evals_p[id];\r\n    \t\t tell(y(0), x, p); // tell evaluated x\r\n    \t\t if (fitfun->evaluations() >= maxEvaluations)\r\n    \t\t\t break;\r\n    \t\t x = ask(p);\r\n    \t\t eval.evaluate(x, cp);\r\n    \t\t evals_x[cp] = x;\r\n    \t\t evals_p[cp] = p;\r\n             cp = (cp + 1) % evals_size; \r\n    \t }\r\n\t}\r\n\r\n    void init() {\r\n        popX = mat(dim, popsize);\r\n        popX0 = mat(dim, popsize);\r\n        popY = vec(popsize);\r\n        for (int p = 0; p < popsize; p++) {\r\n            popX0.col(p) = popX.col(p) = fitfun->sample(*rs);\r\n            popY[p] = DBL_MAX; // compute fitness\r\n        }\r\n        bestI = 0;\r\n        bestX = popX.col(bestI);\r\n        popIter = zeros(popsize);\r\n    }\r\n\r\n    vec getBestX() {\r\n        return bestX;\r\n    }\r\n\r\n    double getBestValue() {\r\n        return bestY;\r\n    }\r\n\r\n    double getIterations() {\r\n        return iterations;\r\n    }\r\n\r\n    double getStop() {\r\n        return stop;\r\n    }\r\n\r\n    Fitness* getFitfun() {\r\n        return fitfun;\r\n    }\r\n\r\n    int getDim() {\r\n        return dim;\r\n    }\r\n\r\nprivate:\r\n    long runid;\r\n    Fitness *fitfun;\r\n    int popsize; // population size\r\n    int dim;\r\n    int maxEvaluations;\r\n    double keep;\r\n    double stopfitness;\r\n    int iterations;\r\n    double bestY;\r\n    vec bestX;\r\n    int bestI;\r\n    int stop;\r\n    double F0;\r\n    double CR0;\r\n    double F;\r\n    double CR;\r\n    pcg64 *rs;\r\n    mat popX;\r\n    mat popX0;\r\n    vec popY;\r\n    vec popIter;\r\n    queue<vec> improvesX;\r\n    queue<int> improvesP;\r\n    int pos;\r\n    bool *isInt;\r\n};\r\n\r\n}\r\n\r\nusing namespace differential_evolution;\r\n\r\nextern \"C\" {\r\nvoid optimizeDE_C(long runid, callback_type func, int dim, int seed,\r\n        double *lower, double *upper, bool *ints,\r\n        int maxEvals, double keep,\r\n        double stopfitness, int popsize, double F, double CR, int workers, double* res) {\r\n    vec lower_limit(dim), upper_limit(dim);\r\n    bool isInt[dim];\r\n    bool useIsInt = false;\r\n    for (int i = 0; i < dim; i++) {\r\n        lower_limit[i] = lower[i];\r\n        upper_limit[i] = upper[i];\r\n        isInt[i] = ints[i];\r\n        useIsInt |= ints[i];\r\n        if (isInt[i]) {\r\n            // adjust bounds because ints are rounded\r\n            lower_limit[i] -= .499999999;\r\n            upper_limit[i] += .499999999;\r\n        }\r\n    }\r\n    Fitness fitfun(func, dim, 1, lower_limit, upper_limit);\r\n    DeOptimizer opt(runid, &fitfun, dim, seed, popsize, maxEvals, keep,\r\n            stopfitness, F, CR, useIsInt ? isInt : NULL);\r\n    try {\r\n        if (workers <= 1)\r\n            opt.doOptimize();\r\n        else\r\n            opt.do_optimize_delayed_update(workers);\r\n        vec bestX = opt.getBestX();\r\n        double bestY = opt.getBestValue();\r\n        for (int i = 0; i < dim; i++)\r\n            res[i] = bestX[i];\r\n        res[dim] = bestY;\r\n        res[dim + 1] = fitfun.evaluations();\r\n        res[dim + 2] = opt.getIterations();\r\n        res[dim + 3] = opt.getStop();\r\n    } catch (std::exception &e) {\r\n        cout << e.what() << endl;\r\n    }\r\n}\r\n}\r\n\r\n", "meta": {"hexsha": "520d29fbfae60235d18235792195665e30bff0a2", "size": 13019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_fcmaescpp/deoptimizer.cpp", "max_stars_repo_name": "Slamim8/fast-cma-es", "max_stars_repo_head_hexsha": "4e6f8e8929a08a2e5d5588f8d87abeb60752e41c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "_fcmaescpp/deoptimizer.cpp", "max_issues_repo_name": "Slamim8/fast-cma-es", "max_issues_repo_head_hexsha": "4e6f8e8929a08a2e5d5588f8d87abeb60752e41c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_fcmaescpp/deoptimizer.cpp", "max_forks_repo_name": "Slamim8/fast-cma-es", "max_forks_repo_head_hexsha": "4e6f8e8929a08a2e5d5588f8d87abeb60752e41c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5475, "max_line_length": 160, "alphanum_fraction": 0.4825255396, "num_tokens": 3258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4275115554450637}}
{"text": "/*\n * StokesM2L.cpp\n *\n *  Created on: Oct 12, 2016\n *      Author: wyan\n */\n\n#include \"SVD_pvfmm.hpp\"\n\n#include <Eigen/Dense>\n\n#include <iomanip>\n#include <iostream>\n\n#define DIRECTLAYER 2\n#define PI314 (static_cast<double>(3.1415926535897932384626433))\n\nnamespace Laplace1D3D {\n\nusing EVec3 = Eigen::Vector3d;\n\ninline double gKernel(const EVec3 &target, const EVec3 &source) {\n    EVec3 rst = target - source;\n    double rnorm = rst.norm();\n    return rnorm < 1e-14 ? 0 : 1 / rnorm;\n}\n\n/**\n * \\brief Returns the coordinates of points on the surface of a cube.\n * \\param[in] p Number of points on an edge of the cube is (n+1)\n * \\param[in] c Coordinates to the centre of the cube (3D array).\n * \\param[in] alpha Scaling factor for the size of the cube.\n * \\param[in] depth Depth of the cube in the octree.\n * \\return Vector with coordinates of points on the surface of the cube in the\n * format [x0 y0 z0 x1 y1 z1 .... ].\n */\n\ntemplate <class Real_t>\nstd::vector<Real_t> surface(int p, Real_t *c, Real_t alpha, int depth) {\n    size_t n_ = (6 * (p - 1) * (p - 1) + 2); // Total number of points.\n\n    std::vector<Real_t> coord(n_ * 3);\n    coord[0] = coord[1] = coord[2] = -1.0;\n    size_t cnt = 1;\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = -1.0;\n            coord[cnt * 3 + 1] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = (2.0 * j - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * i - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = -1.0;\n            coord[cnt * 3 + 2] = (2.0 * (j + 1) - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = (2.0 * j - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = -1.0;\n            cnt++;\n        }\n    for (size_t i = 0; i < (n_ / 2) * 3; i++)\n        coord[cnt * 3 + i] = -coord[i];\n\n    Real_t r = 0.5 * pow(0.5, depth);\n    Real_t b = alpha * r;\n    for (size_t i = 0; i < n_; i++) {\n        coord[i * 3 + 0] = (coord[i * 3 + 0] + 1.0) * b + c[0];\n        coord[i * 3 + 1] = (coord[i * 3 + 1] + 1.0) * b + c[1];\n        coord[i * 3 + 2] = (coord[i * 3 + 2] + 1.0) * b + c[2];\n    }\n    return coord;\n}\n\ndouble directSum(const EVec3 &target, const EVec3 &source, const int directTerm = 500000) {\n    // use asymptotic\n    const double L3 = 1.0;\n    double potentialDirect = 0;\n    for (int t = DIRECTLAYER + 1; t < directTerm; t++) {\n        potentialDirect +=\n            gKernel(target, source + EVec3(t * L3, 0, 0)) + gKernel(target, source - EVec3(t * L3, 0, 0));\n    }\n\n    return potentialDirect;\n}\n\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n    Eigen::setNbThreads(1);\n\n    const int pEquiv = atoi(argv[1]); // (8-1)^2*6 + 2 points\n    const int pCheck = atoi(argv[1]);\n    const double scaleEquiv = 1.05;\n    const double scaleCheck = 2.95;\n    const double pCenterEquiv[3] = {-(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2};\n    const double pCenterCheck[3] = {-(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2};\n\n    const double scaleLEquiv = 1.05;\n    const double scaleLCheck = 2.95;\n    const double pCenterLEquiv[3] = {-(scaleLEquiv - 1) / 2, -(scaleLEquiv - 1) / 2, -(scaleLEquiv - 1) / 2};\n    const double pCenterLCheck[3] = {-(scaleLCheck - 1) / 2, -(scaleLCheck - 1) / 2, -(scaleLCheck - 1) / 2};\n\n    auto pointMEquiv = surface(pEquiv, (double *)&(pCenterEquiv[0]), scaleEquiv,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointMCheck = surface(pCheck, (double *)&(pCenterCheck[0]), scaleCheck,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    auto pointLEquiv = surface(pEquiv, (double *)&(pCenterLCheck[0]), scaleLCheck,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointLCheck = surface(pCheck, (double *)&(pCenterLEquiv[0]), scaleLEquiv,\n                               0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    // calculate the operator M2L with least square\n    const int equivN = pointMEquiv.size() / 3;\n    const int checkN = pointLCheck.size() / 3;\n    Eigen::MatrixXd M2L(equivN, equivN); // Laplace, 1->1\n\n    Eigen::MatrixXd A(1 * checkN, 1 * equivN);\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1], pointLCheck[3 * k + 2]);\n        for (int l = 0; l < equivN; l++) {\n            const Eigen::Vector3d Lpoint(pointLEquiv[3 * l], pointLEquiv[3 * l + 1], pointLEquiv[3 * l + 2]);\n            A(k, l) = gKernel(Cpoint, Lpoint);\n        }\n    }\n    Eigen::MatrixXd ApinvU(A.cols(), A.rows());\n    Eigen::MatrixXd ApinvVT(A.cols(), A.rows());\n    pinv(A, ApinvU, ApinvVT);\n\n#pragma omp parallel for\n    for (int i = 0; i < equivN; i++) {\n        const Eigen::Vector3d Mpoint(pointMEquiv[3 * i], pointMEquiv[3 * i + 1], pointMEquiv[3 * i + 2]);\n        //\t\tstd::cout << \"debug:\" << Mpoint << std::endl;\n\n        // assemble linear system\n        Eigen::VectorXd f(checkN);\n        for (int k = 0; k < checkN; k++) {\n            Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1], pointLCheck[3 * k + 2]);\n            //\t\t\tstd::cout<<\"debug:\"<<k<<std::endl;\n            // sum the images\n            f(k) = directSum(Cpoint, Mpoint); // gKernelFF(Cpoint, Mpoint);\n        }\n        //\t\tstd::cout << \"debug:\" << f << std::endl;\n\n        M2L.col(i) = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n    }\n\n    // dump M2L\n    for (int i = 0; i < equivN; i++) {\n        for (int j = 0; j < equivN; j++) {\n            std::cout << i << \" \" << j << \" \" << std::scientific << std::setprecision(18) << M2L(i, j) << std::endl;\n        }\n    }\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> chargePoint(4);\n    std::vector<double> chargeValue(4);\n    chargePoint[0] = Eigen::Vector3d(0.125, 0.5, 0.5);\n    chargeValue[0] = 1;\n    chargePoint[1] = Eigen::Vector3d(0.375, 0.5, 0.5);\n    chargeValue[1] = -1;\n    chargePoint[2] = Eigen::Vector3d(0.625, 0.5, 0.5);\n    chargeValue[2] = 1;\n    chargePoint[3] = Eigen::Vector3d(0.875, 0.5, 0.5);\n    chargeValue[3] = -1;\n\n    // solve M\n    A.resize(checkN, equivN);\n    ApinvU.resize(A.cols(), A.rows());\n    ApinvVT.resize(A.cols(), A.rows());\n    Eigen::VectorXd f(checkN);\n    for (int k = 0; k < checkN; k++) {\n        double temp = 0;\n        Eigen::Vector3d Cpoint(pointMCheck[3 * k], pointMCheck[3 * k + 1], pointMCheck[3 * k + 2]);\n        for (size_t p = 0; p < chargePoint.size(); p++) {\n            temp = temp + gKernel(Cpoint, chargePoint[p]) * (chargeValue[p]);\n        }\n        f(k) = temp;\n        for (int l = 0; l < equivN; l++) {\n            Eigen::Vector3d Mpoint(pointMEquiv[3 * l], pointMEquiv[3 * l + 1], pointMEquiv[3 * l + 2]);\n            A(k, l) = gKernel(Mpoint, Cpoint);\n        }\n    }\n    pinv(A, ApinvU, ApinvVT);\n    Eigen::VectorXd Msource = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n\n    // impose zero sum\n    double fx = 0;\n    for (int i = 0; i < equivN; i++) {\n        fx += Msource[i];\n    }\n    fx /= equivN;\n    double test = 0;\n    for (int i = 0; i < equivN; i++) {\n        Msource[i] -= fx;\n        test += Msource[i];\n    }\n\n    std::cout << \"Msource net: \" << test << std::endl;\n    std::cout << \"Msource: \" << Msource << std::endl;\n\n    Eigen::VectorXd M2Lsource = M2L * (Msource);\n\n    Eigen::Vector3d samplePoint(0.125, 0.5, 0.5);\n    double Usample = 0;\n    double UsampleSP = 0;\n\n    for (int k = -DIRECTLAYER; k < 1 + DIRECTLAYER; k++) {\n        for (size_t p = 0; p < chargePoint.size(); p++) {\n            Usample += gKernel(samplePoint, chargePoint[p] + EVec3(k, 0, 0)) * chargeValue[p];\n        }\n    }\n\n    for (int p = 0; p < equivN; p++) {\n        Eigen::Vector3d Lpoint(pointLEquiv[3 * p], pointLEquiv[3 * p + 1], pointLEquiv[3 * p + 2]);\n        UsampleSP += gKernel(samplePoint, Lpoint) * M2Lsource[p];\n    }\n\n    std::cout << \"samplePoint:\" << samplePoint << std::endl;\n    std::cout << \"Usample NF:\" << Usample << std::endl;\n    std::cout << \"Usample FF:\" << UsampleSP << std::endl;\n    std::cout << \"Usample FF+NF total:\" << UsampleSP + Usample << std::endl;\n    std::cout << \"error:\" << UsampleSP + Usample + 8 * log(2) << std::endl;\n\n    samplePoint = EVec3(0.625, 0.5, 0.5);\n    Usample = 0;\n    UsampleSP = 0;\n\n    for (int k = -DIRECTLAYER; k < 1 + DIRECTLAYER; k++) {\n        for (size_t p = 0; p < chargePoint.size(); p++) {\n            Usample += gKernel(samplePoint, chargePoint[p] + EVec3(k, 0, 0)) * chargeValue[p];\n        }\n    }\n\n    for (int p = 0; p < equivN; p++) {\n        Eigen::Vector3d Lpoint(pointLEquiv[3 * p], pointLEquiv[3 * p + 1], pointLEquiv[3 * p + 2]);\n        UsampleSP += gKernel(samplePoint, Lpoint) * M2Lsource[p];\n    }\n\n    std::cout << \"samplePoint:\" << samplePoint << std::endl;\n    std::cout << \"Usample NF:\" << Usample << std::endl;\n    std::cout << \"Usample FF:\" << UsampleSP << std::endl;\n    std::cout << \"Usample FF+NF total:\" << UsampleSP + Usample << std::endl;\n    std::cout << \"error:\" << UsampleSP + Usample + 8 * log(2) << std::endl;\n\n    return 0;\n}\n\n} // namespace Laplace1D3D\n\n#undef DIRECTLAYER\n#undef PI314\n", "meta": {"hexsha": "2e30aeddc5cbaca69de3f295bfcb1cbfe939df11", "size": 9517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "M2L/Laplace/Laplace1D3D.cpp", "max_stars_repo_name": "lamsoa729/STKFMM", "max_stars_repo_head_hexsha": "26d7d971c198e3bed68eb8373e5590a6eb72f764", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "M2L/Laplace/Laplace1D3D.cpp", "max_issues_repo_name": "lamsoa729/STKFMM", "max_issues_repo_head_hexsha": "26d7d971c198e3bed68eb8373e5590a6eb72f764", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "M2L/Laplace/Laplace1D3D.cpp", "max_forks_repo_name": "lamsoa729/STKFMM", "max_forks_repo_head_hexsha": "26d7d971c198e3bed68eb8373e5590a6eb72f764", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.17578125, "max_line_length": 116, "alphanum_fraction": 0.5309446254, "num_tokens": 3401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4275115554450636}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Hidekazu Ikeno\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n/// \\file exponential_sum.hpp\n\n#ifndef MXPFIT_EXPONENTIAL_SUM_HPP\n#define MXPFIT_EXPONENTIAL_SUM_HPP\n\n#include <algorithm>\n#include <iosfwd>\n#include <random>\n\n#include <Eigen/Core>\n\nnamespace mxpfit\n{\n// --- Forward declarations\ntemplate <typename ExpScalarT, typename WScalarT = ExpScalarT>\nclass ExponentialSum;\n\ntemplate <typename ExponentsArrayT, typename WeightsArrayT>\nclass ExponentialSumWrapper;\n\nnamespace detail\n{\n\ntemplate <typename T>\nstruct ExponentialSumTraits;\n\n//\n// Generate random real number between [0,1]\n//\ntemplate <typename T>\nstruct random_real_scalar\n{\n    random_real_scalar() : distr_(T(), T(1))\n    {\n        std::random_device rd;\n        std::seed_seq seeds({rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd()});\n        engine_.seed(seeds);\n    }\n\n    T operator()()\n    {\n        return distr_(engine_);\n    }\n\n    std::mt19937 engine_;\n    std::uniform_real_distribution<T> distr_;\n};\n\ntemplate <typename T>\nstruct random_exponent_impl\n{\n    T operator()()\n    {\n        return m_rng(); // distributed on [0, 1]\n    }\n\nprivate:\n    random_real_scalar<T> m_rng;\n};\n\ntemplate <typename T>\nstruct random_exponent_impl<std::complex<T>>\n{\n    std::complex<T> operator()()\n    {\n        static const T pi = EIGEN_PI;\n        // zi distributed on unit disk\n        const auto zi = std::polar(m_rng(), pi * (m_rng() - T(0.5)));\n        return -Eigen::numext::log(zi);\n    }\n\nprivate:\n    random_real_scalar<T> m_rng;\n};\n\ntemplate <typename T>\nstruct random_weight_impl\n{\n    T operator()()\n    {\n        return m_rng(); // distributed on [0, 1]\n    }\n\nprivate:\n    random_real_scalar<T> m_rng;\n};\n\ntemplate <typename T>\nstruct random_weight_impl<std::complex<T>>\n{\n    std::complex<T> operator()()\n    {\n        // distributed on [-1, 1] + i[-1,1]\n        return std::complex<T>(T(2) * m_rng() - 1, T(2) * m_rng() - T(1));\n    }\n\nprivate:\n    random_real_scalar<T> m_rng;\n};\n\n} // namespace detail\n\n///\n/// ### ExponentialSumBase\n///\n/// Base class for expressions of exponential sum function\n///\ntemplate <typename Derived>\nclass ExponentialSumBase\n{\npublic:\n    using Index  = Eigen::Index;\n    using Traits = detail::ExponentialSumTraits<Derived>;\n\n    using ExponentsArray = typename Traits::ExponentsArray;\n    using WeightsArray   = typename Traits::WeightsArray;\n\n    using ExponentScalar = typename ExponentsArray::Scalar;\n    using WeightScalar   = typename WeightsArray::Scalar;\n\n    using ExponentsArrayNested =\n        typename Eigen::internal::ref_selector<ExponentsArray>::type;\n    using WeightsArrayNested =\n        typename Eigen::internal::ref_selector<WeightsArray>::type;\n\n    using PlainExponentsArray =\n        Eigen::Array<typename ExponentsArray::Scalar, Eigen::Dynamic, 1>;\n    using PlainWeightsArray =\n        Eigen::Array<typename WeightsArray::Scalar, Eigen::Dynamic, 1>;\n\n    /// \\return reference to the derived object\n    Derived& derived()\n    {\n        return *static_cast<Derived*>(this);\n    }\n    /// \\return const reference to the derived object\n    const Derived& derived() const\n    {\n        return *static_cast<const Derived*>(this);\n    }\n\n    /// \\return the number of exponential terms\n    Index size() const\n    {\n        assert(exponents().size() == weights().size());\n        return exponents().size();\n    }\n\n    /// \\return value of the multi-exponential function at given argument x\n    template <typename ArgT>\n    auto operator()(const ArgT& x) const\n        -> decltype(ExponentScalar() * WeightScalar())\n    {\n        // return derived().evalAt(x);\n        return ((-x * exponents()).exp() * weights()).sum();\n    }\n\n    /// \\return const reference to the array of exponents\n    ExponentsArrayNested exponents() const\n    {\n        return derived().exponents();\n    }\n\n    /// \\return reference to the array of weights\n    WeightsArrayNested weights() const\n    {\n        return derived().weights();\n    }\n\n    /// \\return value or reference of `i`-th exponents\n    typename ExponentsArray::CoeffReturnType exponent(Index i) const\n    {\n        assert(Index() <= i && i < size());\n        return exponents().coeff(i);\n    }\n\n    /// \\return value or reference of `i`-th weight\n    typename WeightsArray::CoeffReturnType weight(Index i) const\n    {\n        assert(Index() <= i && i < size());\n        return weights().coeff(i);\n    }\n};\n\n/// Output stream operator for `ExponentialSumBase`\ntemplate <typename Ch, typename Tr, typename Derived>\nstd::basic_ostream<Ch, Tr>&\noperator<<(std::basic_ostream<Ch, Tr>& os,\n           const ExponentialSumBase<Derived>& expsum)\n{\n    auto n = expsum.size();\n    os << n << '\\n';\n    for (decltype(n) i = 0; i < n; ++i)\n    {\n        os << expsum.exponent(i) << '\\t' << expsum.weight(i) << '\\n';\n    }\n\n    return os;\n}\n\n///\n/// Remove terms in exponential sum satisfying the specific criteria\n///\n/// \\param[in] esum original exponential sum,\n///   \\f$f(t)=\\sum_{j=1}^{n}c_{j}e^{-a_{j}t}.\\f$\n/// \\param[in] pred unary predicate which returns ​`true` if the term should\n///   be removed. The signature of the predicate function should be equivalent\n///   to the following:\n///   ``` c++\n///     bool pred(const Scalar& aj, const Scalar& cj);\n///   ```\n///   where `aj` and `cj` are j-th exponent, \\f$a_{j},\\$ and coefficient\n///   \\f$c_{j},\\f$ respectively, and `Scalar` is the scalar type of original\n///   exponential sum, `esum`. The signature does not need to have `const &`,\n///   but the function must not modify the objects passed to it.\n///\n/// \\return an object of ExponentialSum with same scalar types for `esum`.\n///\ntemplate <typename Derived, typename Predicate>\nExponentialSum<typename ExponentialSumBase<Derived>::ExponentScalar,\n               typename ExponentialSumBase<Derived>::WeightScalar>\nremoveIf(const ExponentialSumBase<Derived>& esum, Predicate pred)\n{\n    using Index      = Eigen::Index;\n    using IndexArray = Eigen::Array<Index, Eigen::Dynamic, 1>;\n    using ResultType =\n        ExponentialSum<typename ExponentialSumBase<Derived>::ExponentScalar,\n                       typename ExponentialSumBase<Derived>::WeightScalar>;\n    using Eigen::numext::abs;\n    using Eigen::numext::real;\n\n    if (esum.size() == Index())\n    {\n        return ResultType();\n    }\n\n    IndexArray index(IndexArray::LinSpaced(esum.size(), 0, esum.size() - 1));\n\n    auto* last =\n        std::remove_if(index.data(), index.data() + index.size(), [&](Index x) {\n            return pred(esum.exponent(x), esum.weight(x));\n        });\n\n    Index n = static_cast<Index>(last - index.data());\n    ResultType ret(n);\n    for (Index i = 0; i < n; ++i)\n    {\n        ret.exponent(i) = esum.exponent(index(i));\n        ret.weight(i)   = esum.weight(index(i));\n    }\n\n    return ret;\n}\n\n//==============================================================================\n// ExponentialSum class\n//==============================================================================\nnamespace detail\n{\n\ntemplate <typename ExpScalarT, typename WScalarT>\nstruct ExponentialSumTraits<ExponentialSum<ExpScalarT, WScalarT>>\n{\n    using ExponentsArray = Eigen::Array<ExpScalarT, Eigen::Dynamic, 1>;\n    using WeightsArray   = Eigen::Array<WScalarT, Eigen::Dynamic, 1>;\n};\n\n} // namespace detail\n\n///\n/// ### ExponentialSum\n///\n/// Representation of an exponential sum function with its storage.\n///\n/// \\tparam T  the scalar type for parameters\n/// \\tparam Size_ size of internal arrays to store exponents and weights. Set\n///     Eigen::Dynamic for changing the size dynamically. Default is\n///     Eigen::Dynamic.\n/// \\tparam MaxSize_ maximum size of internal arrays. Default is `Size_`.\n///\ntemplate <typename ExpScalarT, typename WScalarT>\nclass ExponentialSum\n    : public ExponentialSumBase<ExponentialSum<ExpScalarT, WScalarT>>\n{\n    using Base = ExponentialSumBase<ExponentialSum<ExpScalarT, WScalarT>>;\n\npublic:\n    using Index = Eigen::Index;\n\n    using ExponentsArray = typename Base::ExponentsArray;\n    using WeightsArray   = typename Base::WeightsArray;\n    using ExponentScalar = typename ExponentsArray::Scalar;\n    using WeightScalar   = typename WeightsArray::Scalar;\n\nprotected:\n    using IndexArray = Eigen::Array<Index, Eigen::Dynamic, 1>;\n\n    ExponentsArray m_exponents;\n    WeightsArray m_weights;\n\npublic:\n    /// Default constructor\n    ExponentialSum() = default;\n\n    /// Create an exponential sum function with number of terms\n    explicit ExponentialSum(Index n) : m_exponents(n), m_weights(n)\n    {\n    }\n\n    /// Create an exponential sum function from other expression\n    template <typename Derived>\n    explicit ExponentialSum(const ExponentialSumBase<Derived>& other)\n        : m_exponents(other.exponents()), m_weights(other.weights())\n    {\n    }\n\n    /// Copy constructor\n    ExponentialSum(const ExponentialSum&) = default;\n\n    /// Move constructor\n    ExponentialSum(ExponentialSum&&) = default;\n\n    /// Destuctor\n    ~ExponentialSum() = default;\n\n    /// Copy assignment operator\n    ExponentialSum& operator=(const ExponentialSum&) = default;\n\n    /// Move assignment operator\n    ExponentialSum& operator=(ExponentialSum&&) = default;\n\n    /// Create an exponential sum function from expressions of arrays\n    template <typename Derived1, typename Derived2>\n    explicit ExponentialSum(const Eigen::DenseBase<Derived1>& exponents_,\n                            const Eigen::DenseBase<Derived2>& weights_)\n        : m_exponents(exponents_), m_weights(weights_)\n    {\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived1);\n        EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived2);\n        eigen_assert(exponents_.size() == weights_.size() &&\n                     \"Size of exponents and weights array must be the same\");\n    }\n\n    /// \\return const reference to the array of exponents\n    const ExponentsArray& exponents() const\n    {\n        return m_exponents;\n    }\n\n    /// \\return  reference to the array of exponents\n    ExponentsArray& exponents()\n    {\n        return m_exponents;\n    }\n\n    /// \\return const reference to the array of exponents\n    const WeightsArray& weights() const\n    {\n        return m_weights;\n    }\n\n    /// \\return  reference to the array of exponents\n    WeightsArray& weights()\n    {\n        return m_weights;\n    }\n\n    /// Set the number of exponential terms\n    void resize(Index n)\n    {\n        m_exponents.resize(n);\n        m_weights.resize(n);\n    }\n\n    void swap(ExponentialSum& other)\n    {\n        m_exponents.swap(other.m_exponents);\n        m_weights.swap(other.m_weights);\n    }\n\n    using Base::size;\n    using Base::exponent;\n    using Base::weight;\n    using Base::operator();\n\n    ExponentScalar& exponent(Index i)\n    {\n        return m_exponents(i);\n    }\n\n    WeightScalar& weight(Index i)\n    {\n        return m_weights(i);\n    }\n\n    /// sort exponents \\f$ \\xi_i \\f$ and weights \\f$ w_i \\f$ by the ratio\n    /// \\f$|w_i| / |\\mathrm{Re}(\\xi)|\\f$\n    void sortByDominanceRatio()\n    {\n        using Eigen::numext::abs;\n        using Eigen::numext::real;\n        using std::swap;\n\n        if (size() <= Index(1))\n        {\n            return;\n        }\n\n        IndexArray order(IndexArray::LinSpaced(size(), 0, size() - 1));\n\n        std::sort(order.data(), order.data() + order.size(),\n                  [this](Index x, Index y) {\n                      return abs(m_weights(x)) / abs(real(m_exponents(x))) >\n                             abs(m_weights(y)) / abs(real(m_exponents(y)));\n                  });\n\n        ExponentsArray e_tmp(m_exponents);\n        WeightsArray w_tmp(m_weights);\n        for (Index i = 0; i < size(); ++i)\n        {\n            m_exponents(i) = e_tmp(order(i));\n            m_weights(i)   = w_tmp(order(i));\n        }\n    }\n\n    ///\n    /// Set exponents and weights to a random number.\n    ///\n    /// Exponents \\f$a_{i}\\f$ are distributed on the right half-plane, i.e.,\n    /// \\f$Re(a_{i})>0,\\f$ while weights are located at the region \\f$w_{i}\\in\n    /// [0,1] + i[-1,1].\\f$\n    ///\n    void setRandom()\n    {\n        static detail::random_exponent_impl<ExponentScalar> rnd_c;\n        static detail::random_weight_impl<WeightScalar> rnd_w;\n\n        for (Index i = 0; i < size(); ++i)\n        {\n            m_exponents(i) = rnd_c();\n            m_weights(i)   = rnd_w();\n        }\n    }\n\n    ///\n    /// Merge the terms with same exponents on an exponential sum.\n    ///\n    /// \\param[in] pred binary predicate which returns ​`true` if two\n    ///   exponents can be regarded as the same. The signature of the predicate\n    ///   function should be equivalent to the following:\n    ///\n    ///   ``` c++\n    ///     bool pred(const Scalar& AI, const Scalar& aj);\n    ///   ```\n    ///\n    ///   where `ai` and `aj` are the i-th and j-th exponentand `Scalar` is the\n    ///   scalar type of original exponential sum, `esum`. The signature does\n    ///   not need to have `const &`, but the function must not modify the\n    ///   objects passed to it.\n    ///\n    void\n    uniqueExponents(typename Eigen::NumTraits<ExponentScalar>::Real tolerance)\n    {\n        if (size() <= Index(1))\n        {\n            return;\n        }\n        IndexArray order(IndexArray::LinSpaced(size(), 0, size() - 1));\n        std::sort(order.data(), order.data() + order.size(),\n                  [this](Index x, Index y) {\n                      return std::make_tuple(std::abs(m_exponents(x)),\n                                             std::arg(m_exponents(x))) >\n                             std::make_tuple(std::abs(m_exponents(y)),\n                                             std::arg(m_exponents(y)));\n                  });\n\n        Index first = 0;\n        Index ret   = first;\n        Index last  = size();\n        while (++first != last)\n        {\n            const auto lhs = m_exponents(order(ret));\n            const auto rhs = m_exponents(order(first));\n            // if (pred(m_exponents(order(ret)), m_exponents(order(first))))\n            if (std::abs(rhs - lhs) <= tolerance * std::abs(rhs) ||\n                std::abs(rhs - lhs) <= tolerance * std::abs(lhs))\n            {\n                m_weights(order(first)) += m_weights(order(ret));\n            }\n            else if (++ret != first)\n            {\n                m_exponents(order(ret)) = m_exponents(order(first));\n                m_weights(order(ret))   = m_weights(order(first));\n            }\n        }\n        ++ret;\n\n        m_exponents.conservativeResize(ret);\n        m_weights.conservativeResize(ret);\n\n        return;\n    }\n};\n\n//==============================================================================\n// ExponentialSumWrapper class\n//==============================================================================\nnamespace detail\n{\n\ntemplate <typename ExpArrayT, typename WArrayT>\nstruct ExponentialSumTraits<ExponentialSumWrapper<ExpArrayT, WArrayT>>\n{\n    using ExponentsArray = ExpArrayT;\n    using WeightsArray   = WArrayT;\n};\n\n} // namespace: detail\n\n///\n/// ### ExponentialSumWrapper\n///\n/// Expression of an exponential sum function formed by wrapping existing array\n/// expressions.\n///\ntemplate <typename ExpArrayT, typename WArrayT>\nclass ExponentialSumWrapper\n    : public ExponentialSumBase<ExponentialSumWrapper<ExpArrayT, WArrayT>>\n{\n    EIGEN_STATIC_ASSERT_VECTOR_ONLY(ExpArrayT);\n    EIGEN_STATIC_ASSERT_VECTOR_ONLY(WArrayT);\n    using Base = ExponentialSumBase<ExponentialSumWrapper<ExpArrayT, WArrayT>>;\n\npublic:\n    using Index = typename Base::Index;\n\n    using ExponentsArray = typename Base::ExponentsArray;\n    using WeightsArray   = typename Base::WeightsArray;\n    using ExponentsArrayNested =\n        typename Eigen::internal::ref_selector<ExponentsArray>::type;\n    using WeightsArrayNested =\n        typename Eigen::internal::ref_selector<WeightsArray>::type;\n\nprotected:\n    ExponentsArrayNested m_exponents;\n    WeightsArrayNested m_weights;\n\npublic:\n    /// Create an exponential sum function from expressions of arrays\n    explicit ExponentialSumWrapper(const ExponentsArray& exponents_,\n                                   const WeightsArray& weights_)\n        : m_exponents(exponents_), m_weights(weights_)\n    {\n        eigen_assert(exponents_.size() == weights_.size() &&\n                     \"Size of exponents and weights array must be the same\");\n    }\n\n    /// \\return const reference to the array of exponents\n    const ExponentsArray& exponents() const\n    {\n        return m_exponents;\n    }\n\n    /// \\return const reference to the array of exponents\n    const WeightsArray& weights() const\n    {\n        return m_weights;\n    }\n\n    using Base::size;\n    using Base::exponent;\n    using Base::weight;\n    using Base::operator();\n};\n\n///\n/// Create an instance of `ExponentialSumWrapper` from given arrays.\n///\ntemplate <typename ExpArrayT, typename WArrayT>\nExponentialSumWrapper<ExpArrayT, WArrayT>\nmakeExponentialSum(const Eigen::ArrayBase<ExpArrayT>& exponents,\n                   const Eigen::ArrayBase<WArrayT>& weights)\n{\n    return ExponentialSumWrapper<ExpArrayT, WArrayT>(exponents.derived(),\n                                                     weights.derived());\n}\n\n} // namespace: mxpfit\n\n#endif /* MXPFIT_EXPONENTIAL_SUM_HPP */\n", "meta": {"hexsha": "f0a1978efe6b061fb57bafb936c603f3c10eab8f", "size": 18227, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/exponential_sum.hpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "include/mxpfit/exponential_sum.hpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "include/mxpfit/exponential_sum.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.637398374, "max_line_length": 80, "alphanum_fraction": 0.6203434465, "num_tokens": 4318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.427511547781563}}
{"text": "// graph-tool -- a general graph modification and manipulation thingy\n//\n// Copyright (C) 2006-2018 Tiago de Paula Peixoto <tiago@skewed.de>\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 3\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n#include \"graph.hh\"\n#include \"graph_filtering.hh\"\n#include \"graph_properties.hh\"\n#include \"graph_selectors.hh\"\n\n#include <boost/python.hpp>\n\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/graph/floyd_warshall_shortest.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace graph_tool;\n\nstruct do_all_pairs_search\n{\n    template <class Graph, class VertexIndexMap, class DistMap, class WeightMap>\n    void operator()(const Graph& g, VertexIndexMap vertex_index,\n                    DistMap dist_map, WeightMap weight, bool dense) const\n    {\n        typedef typename property_traits<DistMap>::value_type::value_type\n            dist_t;\n\n        parallel_vertex_loop\n            (g,\n             [&](auto& v)\n             {\n                 dist_map[v].clear();\n                 dist_map[v].resize(num_vertices(g), 0);\n             });\n\n        if (dense)\n        {\n            floyd_warshall_all_pairs_shortest_paths\n                (g, dist_map,\n                 weight_map(ConvertedPropertyMap<WeightMap,dist_t>(weight)).\n                 vertex_index_map(vertex_index));\n        }\n        else\n        {\n            johnson_all_pairs_shortest_paths\n                (g, dist_map,\n                 weight_map(ConvertedPropertyMap<WeightMap,dist_t>(weight)).\n                 vertex_index_map(vertex_index));\n        }\n    }\n};\n\nstruct do_all_pairs_search_unweighted\n{\n    template <class DistMap, class PredMap>\n    class bfs_visitor: public boost::bfs_visitor<null_visitor>\n    {\n    public:\n        bfs_visitor(DistMap& dist_map, PredMap& pred, size_t source)\n        : _dist_map(dist_map), _pred(pred), _source(source) {}\n\n        template <class Graph>\n        void initialize_vertex(typename graph_traits<Graph>::vertex_descriptor v,\n                               Graph&)\n        {\n            typedef typename DistMap::value_type dist_t;\n            dist_t inf = std::is_floating_point<dist_t>::value ?\n                numeric_limits<dist_t>::infinity() :\n                numeric_limits<dist_t>::max();\n            _dist_map[v] = (v == _source) ? 0 : inf;\n            _pred[v] = v;\n        }\n\n        template <class Graph>\n        void tree_edge(const typename graph_traits<Graph>::edge_descriptor& e,\n                       Graph& g)\n        {\n            _pred[target(e,g)] = source(e,g);\n        }\n\n        template <class Graph>\n        void discover_vertex(typename graph_traits<Graph>::vertex_descriptor v,\n                             Graph&)\n        {\n            if (size_t(_pred[v]) == v)\n                return;\n            _dist_map[v] = _dist_map[_pred[v]] + 1;\n        }\n\n    private:\n        DistMap& _dist_map;\n        PredMap& _pred;\n        size_t _source;\n    };\n\n    template <class Graph, class DistMap>\n    void operator()(const Graph& g, DistMap dist_map) const\n    {\n        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n        typedef typename property_traits<DistMap>::value_type dist_t;\n\n        vector<vertex_t> pred_map(num_vertices(g));\n        #pragma omp parallel if (num_vertices(g) > OPENMP_MIN_THRESH) \\\n            firstprivate(pred_map)\n        parallel_vertex_loop_no_spawn\n                (g,\n                 [&](auto v)\n                 {\n                     dist_map[v].resize(num_vertices(g), 0);\n                     bfs_visitor<dist_t,vector<size_t>>\n                         vis(dist_map[v], pred_map, v);\n                     breadth_first_search(g, v, visitor(vis));\n                 });\n    }\n};\n\n\nvoid get_all_dists(GraphInterface& gi, boost::any dist_map, boost::any weight,\n                   bool dense)\n{\n    if (weight.empty())\n    {\n        run_action<>()\n            (gi, std::bind(do_all_pairs_search_unweighted(),\n                           std::placeholders::_1, std::placeholders::_2),\n             vertex_scalar_vector_properties())\n            (dist_map);\n    }\n    else\n    {\n        run_action<>()\n            (gi, std::bind(do_all_pairs_search(), std::placeholders::_1,\n                           gi.get_vertex_index(), std::placeholders::_2,\n                           std::placeholders::_3, dense),\n             vertex_scalar_vector_properties(),\n             edge_scalar_properties())\n            (dist_map, weight);\n    }\n}\n\nvoid export_all_dists()\n{\n    python::def(\"get_all_dists\", &get_all_dists);\n};\n", "meta": {"hexsha": "7ed9c2c096eb06dc4cbde702b1268c06330d2e1a", "size": 5128, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/topology/graph_all_distances.cc", "max_stars_repo_name": "Znigneering/CSCI-3154", "max_stars_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graph-tool-2.27/src/graph/topology/graph_all_distances.cc", "max_issues_repo_name": "Znigneering/CSCI-3154", "max_issues_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graph-tool-2.27/src/graph/topology/graph_all_distances.cc", "max_forks_repo_name": "Znigneering/CSCI-3154", "max_forks_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4556962025, "max_line_length": 81, "alphanum_fraction": 0.5924336973, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.427511547781563}}
{"text": "/*!\n  @file   PCA.cpp\n  @author David Hirvonen\n  @brief  Internal PCA class implementation.\n\n  \\copyright Copyright 2014-2016 Elucideye, Inc. All rights reserved.\n  \\license{This project is released under the 3 Clause BSD License.}\n\n*/\n\n#include \"drishti/ml/PCA.h\"\n#include \"drishti/core/make_unique.h\"\n\n#include <Eigen/Dense>\n\nDRISHTI_ML_NAMESPACE_BEGIN\n\n// ########## Scaling params ############\n\nStandardizedPCA::Standardizer::Standardizer() = default;\nStandardizedPCA::Standardizer::~Standardizer() = default;\nStandardizedPCA::Standardizer::Standardizer(int size, int type)\n{\n    create(size, type);\n}\n\nvoid StandardizedPCA::Standardizer::create(int size, int type)\n{\n    mu.create(1, size, type);\n    sigma.create(1, size, type);\n}\n\nvoid StandardizedPCA::Standardizer::compute(const cv::Mat& src)\n{\n    create(src.cols, CV_32FC1);\n    float *pMu = mu.ptr<float>(), *pSigma = sigma.ptr<float>();\n    for (int i = 0; i < src.cols; i++, pMu++, pSigma++)\n    {\n        cv::Scalar mu, sigma;\n        cv::Mat x = src.col(i);\n        cv::meanStdDev(x, mu, sigma);\n        pMu[0] = mu[0];\n        pSigma[0] = sigma[0];\n    }\n}\n\ncv::Mat StandardizedPCA::Standardizer::standardize(const cv::Mat& data) const\n{\n    cv::Mat tmp_sigma = cv::repeat(sigma, data.rows / sigma.rows, data.cols / sigma.cols);\n    cv::Mat tmp_mean = cv::repeat(mu, data.rows / mu.rows, data.cols / mu.cols), tmp_data;\n    int ctype = mu.type();\n    if (data.type() != ctype || tmp_mean.data == mu.data)\n    {\n        data.convertTo(tmp_data, ctype);\n        cv::subtract(tmp_data, tmp_mean, tmp_data);\n        cv::divide(tmp_data, tmp_sigma, tmp_data);\n    }\n    else\n    {\n        cv::subtract(data, tmp_mean, tmp_mean);\n        cv::divide(tmp_mean, tmp_sigma, tmp_data);\n    }\n    return tmp_data;\n}\n\ncv::Mat StandardizedPCA::Standardizer::unstandardize(const cv::Mat& data) const\n{\n    cv::Mat tmp_sigma = cv::repeat(sigma, data.rows / sigma.rows, data.cols / sigma.cols);\n    cv::Mat tmp_mean = cv::repeat(mu, data.rows / mu.rows, data.cols / mu.cols), tmp_data;\n    int ctype = mu.type();\n    if (data.type() != ctype || tmp_mean.data == mu.data)\n    {\n        data.convertTo(tmp_data, ctype);\n        cv::multiply(tmp_data, tmp_sigma, tmp_data);\n        cv::add(tmp_data, tmp_mean, tmp_data);\n    }\n    else\n    {\n        cv::multiply(data, tmp_sigma, tmp_data);\n        cv::add(tmp_data, tmp_mean, tmp_data);\n    }\n    return tmp_data;\n}\n\n// ########### ScalePCA #############\n\nStandardizedPCA::StandardizedPCA() = default;\nStandardizedPCA::~StandardizedPCA() = default;\n\nsize_t StandardizedPCA::getNumComponents() const\n{\n    return m_transform.mu.cols;\n}\n\nvoid StandardizedPCA::compute(const cv::Mat& data, cv::Mat& projection, float retainedVariance)\n{\n    cv::Mat mu;\n    m_transform.compute(data);\n    cv::Mat data_ = m_transform.standardize(data);\n    m_pca = drishti::core::make_unique<cv::PCA>(data_, mu, cv::PCA::DATA_AS_ROW, retainedVariance);\n    m_pca->project(data_, projection);\n\n    init();\n}\n\nvoid StandardizedPCA::compute(const cv::Mat& data, cv::Mat& projection, int maxComponents)\n{\n    cv::Mat mu;\n    m_transform.compute(data);\n    cv::Mat data_ = m_transform.standardize(data);\n    m_pca = drishti::core::make_unique<cv::PCA>(data_, mu, cv::PCA::DATA_AS_ROW, maxComponents);\n    m_pca->project(data_, projection);\n\n    init();\n}\n\nvoid StandardizedPCA::init()\n{\n    // Cache transposed vectors for faster multiplication:\n    if (!m_pca->eigenvectors.empty())\n    {\n        m_eT = m_pca->eigenvectors.t();\n    }\n}\n\ncv::Mat StandardizedPCA::project(const cv::Mat& samples, int n) const\n{\n    cv::Mat samples_ = m_transform.standardize(samples), projection;\n    if (n > 0)\n    {\n        // Construct partial eigenvectors\n        cv::Mat eigenvectors = m_pca->eigenvectors({ 0, n }, cv::Range::all());\n        cv::Mat eigenvalues = m_pca->eigenvalues({ 0, n }, cv::Range::all());\n        cv::Mat mean = m_pca->mean;\n\n        cv::Mat data = samples_;\n        CV_Assert(!mean.empty() && !eigenvectors.empty() && ((mean.rows == 1 && mean.cols == data.cols) || (mean.cols == 1 && mean.rows == data.rows)));\n        cv::Mat tmp_data, tmp_mean = cv::repeat(mean, data.rows / mean.rows, data.cols / mean.cols);\n        int ctype = mean.type();\n        if (data.type() != ctype || tmp_mean.data == mean.data)\n        {\n            data.convertTo(tmp_data, ctype);\n            cv::subtract(tmp_data, tmp_mean, tmp_data);\n        }\n        else\n        {\n            cv::subtract(data, tmp_mean, tmp_mean);\n            tmp_data = tmp_mean;\n        }\n        if (mean.rows == 1)\n        {\n            cv::gemm(tmp_data, eigenvectors, 1, {}, 0, projection, cv::GEMM_2_T);\n        }\n        else\n        {\n            cv::gemm(eigenvectors, tmp_data, 1, {}, 0, projection, 0);\n        }\n    }\n    else\n    {\n        m_pca->project(samples_, projection);\n    }\n    return projection;\n}\n\nvoid StandardizedPCA::gemm_transpose(const cv::Mat& A, const cv::Mat& Bt, cv::Mat& result)\n{\n    assert(A.type() == CV_32F);\n    assert(A.isContinuous());\n    assert(A.cols == Bt.cols);\n    assert(Bt.type() == CV_32F);\n\n    using DynamicStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;\n    using MatrixRowMajor = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n    using MatrixColMajor = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;\n    using MapMatrixRowMajor = Eigen::Map<MatrixRowMajor, Eigen::Unaligned>;\n    using MapMatrixColMajor = Eigen::Map<MatrixColMajor, Eigen::Unaligned, DynamicStride>;\n\n    result.create(A.rows, Bt.rows, CV_32F);\n    MapMatrixRowMajor C1(result.ptr<float>(), result.rows, result.cols);\n    MapMatrixRowMajor A1(const_cast<float*>(A.ptr<float>()), A.rows, A.cols);\n    MapMatrixColMajor B1t(const_cast<float*>(Bt.ptr<float>()), /*n*/ Bt.cols, Bt.rows, DynamicStride(Bt.step1(), 1));\n    C1 = A1 * B1t;\n}\n\ncv::Mat StandardizedPCA::backProject(const cv::Mat& projection) const\n{\n    cv::Mat result;\n    int n = projection.cols;\n    if (n != m_pca->eigenvectors.cols)\n    {\n        // Construct partial eigenvectors\n        cv::Mat eigenvectors = m_pca->eigenvectors({ 0, n }, cv::Range::all());\n        cv::Mat eigenvalues = m_pca->eigenvalues({ 0, n }, cv::Range::all());\n        cv::Mat mean = m_pca->mean;\n\n        cv::Mat data = projection;\n        CV_Assert(!mean.empty() && !eigenvectors.empty() && ((mean.rows == 1 && eigenvectors.rows == data.cols) || (mean.cols == 1 && eigenvectors.rows == data.rows)));\n\n        cv::Mat tmp_data, tmp_mean;\n        if (data.type() != tmp_data.type())\n        {\n            data.convertTo(tmp_data, mean.type()); // 12%\n        }\n        else\n        {\n            tmp_data = data;\n        }\n        if (mean.rows == 1)\n        {\n            tmp_mean = cv::repeat(mean, data.rows, 1);\n\n            // Eigen multiplication ( no copy )\n            const cv::Mat& A = tmp_data;\n            const cv::Mat& Bt = m_eT;\n            gemm_transpose(A, Bt({ 0, Bt.rows }, { 0, n }), result);\n        }\n        else\n        {\n            tmp_mean = cv::repeat(mean, 1, data.cols);\n            cv::gemm(eigenvectors, tmp_data, 1, tmp_mean, 1, result, cv::GEMM_1_T);\n        }\n    }\n    else\n    {\n        result = m_pca->backProject(projection);\n    }\n\n    result = m_transform.unstandardize(result);\n\n    return result;\n}\n\nDRISHTI_ML_NAMESPACE_END\n", "meta": {"hexsha": "0abac7e2b619038d6273b640f42842e55a3bec5e", "size": 7331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": ".References/src/github.com/elucideye/drishti_real-time_eye_tracking/src/lib/drishti/ml/PCA.cpp", "max_stars_repo_name": "roscopecoltran/SniperKit-Core", "max_stars_repo_head_hexsha": "4600dffe1cddff438b948b6c22f586d052971e04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": ".References/src/github.com/elucideye/drishti_real-time_eye_tracking/src/lib/drishti/ml/PCA.cpp", "max_issues_repo_name": "roscopecoltran/SniperKit-Core", "max_issues_repo_head_hexsha": "4600dffe1cddff438b948b6c22f586d052971e04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": ".References/src/github.com/elucideye/drishti_real-time_eye_tracking/src/lib/drishti/ml/PCA.cpp", "max_forks_repo_name": "roscopecoltran/SniperKit-Core", "max_forks_repo_head_hexsha": "4600dffe1cddff438b948b6c22f586d052971e04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1957446809, "max_line_length": 168, "alphanum_fraction": 0.6082389851, "num_tokens": 2028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.427511547781563}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Piotr Smulewicz\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file k_cut.hpp\n * @brief\n * @author Piotr Smulewicz, Piotr Godlewski\n * @version 1.0\n * @date 2013-09-25\n */\n#ifndef PAAL_K_CUT_HPP\n#define PAAL_K_CUT_HPP\n\n#include \"paal/utils/functors.hpp\"\n#include \"paal/utils/type_functions.hpp\"\n#include \"paal/utils/irange.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/one_bit_color_map.hpp>\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n#include <boost/graph/subgraph.hpp>\n#include <boost/range/as_array.hpp>\n\n#include <queue>\n\nnamespace paal {\nnamespace greedy {\n\n/**\n * @brief this is solve k_cut problem\n * and return cut_cost\n * example:\n *  \\snippet k_cut_example.cpp K Cut Example\n *\n * example file is k_cut_example.cpp\n * @param graph\n * @param number_of_parts\n * @param result pairs of vertex_descriptor and number form (1,2,\n* ... ,k) id of part\n * @param index_map\n * @param weight_map\n * @tparam InGraph\n * @tparam OutputIterator\n * @tparam VertexIndexMap\n * @tparam EdgeWeightMap\n */\ntemplate<typename InGraph, class OutputIterator, typename VertexIndexMap, typename EdgeWeightMap>\nauto k_cut(const InGraph& graph, unsigned int number_of_parts,OutputIterator result,\n            VertexIndexMap index_map, EdgeWeightMap weight_map) ->\n            typename boost::property_traits<EdgeWeightMap>::value_type{\n    using cost_t = typename boost::property_traits<EdgeWeightMap>::value_type;\n    using Vertex = typename boost::graph_traits<InGraph>::vertex_descriptor;\n\n    using Graph = boost::adjacency_list<\n        boost::vecS, boost::vecS, boost::undirectedS, boost::no_property,\n        boost::property<boost::edge_weight_t, cost_t,\n                        boost::property<boost::edge_index_t, int>>>;\n\n    assert(num_vertices(graph) >= number_of_parts);\n\n    std::vector<int> vertex_to_part(num_vertices(graph));\n    using VertexIndexToVertex = typename std::vector<Vertex>;\n    using VertexIndexToVertexIndex = std::vector<int>;\n    VertexIndexToVertex vertex_in_subgraph_to_vertex(num_vertices(graph));\n    VertexIndexToVertexIndex vertex_to_vertex_in_subgraph(num_vertices(graph));\n    int vertex_in_part;\n    int parts = 1;\n    // cuts contain pair(x,y)\n    // x is the cost of the cut\n    // y and y+1 are index parts of graph after make a cut\n    std::priority_queue<\n            std::pair<cost_t,int>,\n            std::vector<std::pair<cost_t,int> >\n            ,utils::greater> cuts;\n\n    int id_part = 0;\n\n    //get part id and compute minimum cost of cut of that part and add it to queue\n    auto make_cut = [&](int id) {\n        vertex_in_part=0;\n        for (auto v: boost::as_array(vertices(graph))) {\n            if (vertex_to_part[get(index_map, v)] == id) {\n                vertex_in_subgraph_to_vertex[vertex_in_part] = v;\n                vertex_to_vertex_in_subgraph[get(index_map, v)] = vertex_in_part;\n                ++vertex_in_part;\n            }\n        }\n        Graph part(vertex_in_part);\n        for (auto edge : boost::as_array(edges(graph))) {\n            auto sour = get(index_map, source(edge,graph));\n            auto targ = get(index_map, target(edge,graph));\n            if (vertex_to_part[sour] == id &&\n                    vertex_to_part[targ] == id &&\n                    sour != targ) {\n                add_edge(vertex_to_vertex_in_subgraph[sour],\n                         vertex_to_vertex_in_subgraph[targ],\n                         get(weight_map, edge),\n                         part);\n            }\n        }\n        if (vertex_in_part < 2) {\n            ++id_part;\n            *result = std::make_pair(vertex_in_subgraph_to_vertex[0], id_part);\n            ++result;\n            return;\n        }\n        auto parities = boost::make_one_bit_color_map(num_vertices(part),\n                                            get(boost::vertex_index, part));\n        auto cut_cost = boost::stoer_wagner_min_cut(part,\n                                          get(boost::edge_weight, part),\n                                          boost::parity_map(parities));\n\n        for (auto i : irange(num_vertices(part))) {\n            vertex_to_part[get(index_map, vertex_in_subgraph_to_vertex[i])] =\n                    parts + get(parities, i); //return value convertable to 0/1\n        }\n        cuts.push(std::make_pair(cut_cost, parts));\n        parts += 2;\n    };\n\n    make_cut(0);\n    cost_t k_cut_cost = cost_t();\n    while (--number_of_parts) {\n        auto cut = cuts.top();\n        cuts.pop();\n        k_cut_cost += cut.first;\n        make_cut(cut.second);\n        make_cut(cut.second + 1);\n    }\n\n    while (!cuts.empty()) {\n        auto cut = cuts.top();\n        cuts.pop();\n        ++id_part;\n        for (auto v: boost::as_array(vertices(graph))) {\n            if (vertex_to_part[get(index_map, v)] == cut.second ||\n                    vertex_to_part[get(index_map, v)] == cut.second + 1) {\n                *result = std::make_pair(v, id_part);\n                ++result;\n            }\n        }\n    }\n    return k_cut_cost;\n}\n\n/**\n * @brief this is solve k_cut problem\n * and return cut_cost\n * example:\n *  \\snippet k_cut_example.cpp K Cut Example\n *\n * example file is k_cut_example.cpp\n * @param graph\n * @param number_of_parts\n * @param result pairs of vertex_descriptor and number form (1,2, ... ,k) id of part\n * @param params\n * @tparam InGraph\n * @tparam OutputIterator\n * @tparam T\n * @tparam P\n * @tparam R\n */\ntemplate<typename InGraph\n        ,class OutputIterator\n        ,typename T\n        ,typename P\n        ,typename R>\nauto k_cut(const InGraph& graph, unsigned int number_of_parts,\n    OutputIterator result, const boost::bgl_named_params<P, T, R>& params) ->\n        typename boost::property_traits<\n            puretype(boost::choose_const_pmap(get_param(params, boost::edge_weight), graph, boost::edge_weight))\n            >::value_type {\n    return k_cut(graph, number_of_parts, result,\n        boost::choose_const_pmap(get_param(params, boost::vertex_index), graph,boost::vertex_index),\n        boost::choose_const_pmap(get_param(params, boost::edge_weight), graph,boost::edge_weight)\n    );\n}\n\n/**\n * @brief this is solve k_cut problem\n * and return cut_cost\n * example:\n *  \\snippet k_cut_example.cpp K Cut Example\n *\n * example file is k_cut_example.cpp\n * @param graph\n * @param number_of_parts\n * @param result pairs of vertex_descriptor and number form (1,2, ... ,k) id of part\n * @tparam InGraph\n * @tparam OutputIterator\n */\ntemplate<typename InGraph, class OutputIterator>\nauto k_cut(const InGraph& graph, unsigned int number_of_parts, OutputIterator result) ->\n        typename boost::property_traits<puretype(get(boost::edge_weight,graph))>::value_type{\n    return k_cut(graph, number_of_parts, result, boost::no_named_parameters());\n}\n\n} //!greedy\n} //!paal\n\n#endif // PAAL_K_CUT_HPP\n", "meta": {"hexsha": "a37e7a28071d8648857d9721c0259e52d717b17a", "size": 7166, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/greedy/k_cut/k_cut.hpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/paal/greedy/k_cut/k_cut.hpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/paal/greedy/k_cut/k_cut.hpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 34.4519230769, "max_line_length": 112, "alphanum_fraction": 0.6246162434, "num_tokens": 1698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.427511547781563}}
{"text": "#include \"SchaeferNewtonParametrizer.h\"\n\n#include \"eigen_stl_utils.h\"\n#include <Eigen/SparseCholesky>\n#include <igl/cotmatrix_entries.h>\n#include <igl/doublearea.h>\n#include <iostream>\n\n#include \"../ScafData.h\"\n\n//#undef NDEBUG\n#include <assert.h>\n#include <igl/slice.h>\n#include <igl/slice_into.h>\n//#define NDEBUG\n\nDECLARE_DIFFSCALAR_BASE();\n\nusing namespace std;\nSchaeferNewtonParametrizer::SchaeferNewtonParametrizer(ScafData &_sd)\n\t\t: has_precomputed(false), d_(_sd) {\n\t// empty\n}\n\nvoid SchaeferNewtonParametrizer::newton_iteration(const Eigen::MatrixXi &F,\n\t\t\t\t\t\t\t\t\t\t\t\t  Eigen::MatrixXd &uv) {\n\t// flat uv (x1,y1,x2,y2,...)\n\tcout << \"computing grad and hessian\" << endl;\n\tEigen::VectorXd x; mat2_to_vec(uv,x);\n\t// compute energy for hessian grad calculation\n\t//DScalar Fx;// = 0;\n\tEigen::VectorXd grad; Eigen::SparseMatrix<double> hessian;\n\tdouble energy = compute_energy_gradient_hessian(F,\n\t\t\t\t\t\t\t\t\t\t\t\t\tuv,\n\t\t\t\t\t\t\t\t\t\t\t\t\tgrad,\n\t\t\t\t\t\t\t\t\t\t\t\t\thessian);\n\n\t// Grad and hessian finite-diff check (super slow, only perform on very small meshes)\n\t/*\n\tbool grad_ok = check_gradient(V,F,x,grad);\n\tcout << \"grad ok = \" << grad_ok << endl;\n\tassert(grad_ok);\n\tEigen::MatrixXd dense_hessian(hessian);\n\tbool hessian_ok = checkHessian(V,F,x,dense_hessian,0);\n\tcout << \"hessian ok = \" << hessian_ok << endl;\n\tassert(hessian_ok);\n\t*/\n\n\t// perform newton iteration\n\tcout << \"performing newton iteration\" << endl;\n\n\n// Modified by Zhongshi at May 11, 2017 to keep boundary\n\t// The flattening order is different from the rest!!!\n#define KEEP_BND\n#ifdef KEEP_BND\n\tconst auto& bnd_ids = d_.frame_ids;\n\tusing namespace Eigen;\n\n\tauto bnd_n = bnd_ids.size(); assert(bnd_n > 0);\n\tMatrixXd bnd_pos;\n\tint dim = 2;\n\tint v_n = d_.w_uv.rows();\n\tigl::slice(d_.w_uv, bnd_ids, 1, bnd_pos);\n\n\tVectorXi known_ids(bnd_n * dim);\n\tVectorXi unknown_ids((v_n - bnd_n) * dim);\n\n\t{ // get the complement of bnd_ids.\n\t\tint assign = 0, i = 0;\n\t\tfor (int get = 0; i < v_n && get < bnd_ids.size(); i++) {\n\t\t\tif (bnd_ids(get) == i) get++;\n\t\t\telse unknown_ids(2*(assign++)) = 2*i;\n\t\t}\n\t\twhile (i < v_n) unknown_ids(2*(assign++)) = 2*(i++);\n\t\tassert(assign + bnd_ids.size() == v_n);\n\t}\n\n\tVectorXd known_pos(bnd_n * dim);\n\t  for(int i=0; i<bnd_n; i++) {\n\t\t  known_ids(i * 2) = 2*bnd_ids(i);\n\t\t  known_ids(i * 2 + 1) = 2*bnd_ids(i) + 1;\n\t  }\n\tfor(int i=0; i<v_n - bnd_n; i++) {\n\t\tunknown_ids(i*2 + 1) = unknown_ids(i*2) + 1;\n\t}\n\n\tEigen::SparseMatrix<double> hessian_unknown;\n  \tigl::slice(hessian, unknown_ids, unknown_ids, hessian_unknown);\n\n\tEigen::VectorXd grad_unknown;\n\tigl::slice(grad, unknown_ids, 1, grad_unknown);\n\n\tEigen::SimplicialLDLT<Eigen::SparseMatrix<double> > solver;\n\tsolver.compute(hessian_unknown);\n\tif(solver.info()!=Eigen::Success) {\n\t\tcout << \"Eigen Failure!\" << endl;\n\t\texit(1);\n\t}\n\tEigen::VectorXd res = solver.solve(grad_unknown);\n\tVectorXd Uc = VectorXd::Zero(2* v_n);\n\tigl::slice_into(res, unknown_ids.matrix(), 1, Uc);\n\tx -= Uc;\n#else\n\n\tEigen::SparseLU<Eigen::SparseMatrix<double> > solver;\n  int n = hessian.rows();\n  Eigen::SparseMatrix<double> id(n,n); id.setIdentity();\n//\tsolver.compute(hessian + (1e-5) * id);\n  solver.compute(hessian);\n\tif(solver.info()!=Eigen::Success) {\n\t\tcout << \"Eigen Failure!\" << endl;\n        exit(1);\n\t}\n\tEigen::VectorXd res = solver.solve(grad);\n\tx -= res;\n#endif\n\t// unflatten uv\n\tvec_to_mat2(x,uv);\n}\n\ndouble SchaeferNewtonParametrizer::evaluate_energy(const Eigen::MatrixXi &F,\n\t\t\t\t\t\t\t\t\t\t\t\t   Eigen::MatrixXd &uv) {\n\tprecompute(F);\n\tdouble energy = 0;\n\n\tfor (int f_idx = 0; f_idx < F.rows(); f_idx++) {\n\t\tint v_1 = F(f_idx, 0);\n\t\tint v_2 = F(f_idx, 1);\n\t\tint v_3 = F(f_idx, 2);\n\n\t\t// compute current triangle squared area\n\t\tauto x1 = uv(v_1, 0);\n\t\tauto y1 = uv(v_1, 1);\n\t\tauto x2 = uv(v_2, 0);\n\t\tauto y2 = uv(v_2, 1); //DScalar x0(F(f,0),0); DScalar y0(F(f,0),1);\n\t\tauto x3 = uv(v_3, 0);\n\t\tauto y3 = uv(v_3, 1); //DScalar x0(F(f,0),0); DScalar y0(F(f,\n\t\t// 0),1);\n\n\t\tauto rx = x1 - x3;//uv(F(f,0),0)-uv(F(f,2),0);\n\t\tauto sx = x2 - x3;//uv(F(f,1),0)-uv(F(f,2),0);\n\t\tauto ry = y1 - y3;//uv(F(f,0),1)-uv(F(f,2),1);\n\t\tauto sy = y2 - y3;//uv(F(f,1),1)-uv(F(f,2),1);\n\t\tauto dblAd = rx * sy - ry * sx;\n\t\tauto uv_sqrt_dbl_area = dblAd * dblAd;\n\n\t\tauto l_part = (1 / (m_dblArea_orig(f_idx)) + (m_dblArea_orig(f_idx)\n\t\t\t\t/ uv_sqrt_dbl_area)) *\n\t\t\t\tm_dbl_area_weight(f_idx);\n\n\t\t//DScalar part_1 = (uv.row(v_3)-uv.row(v_1)).squaredNorm() * m_cached_edges_1[f_idx];\n\t\tauto part_1 =\n\t\t\t\t(pow(x3 - x1, 2) + pow(y3 - y1, 2)) * m_cached_edges_1[f_idx];\n\t\t//part_1 += (uv.row(v_2)-uv.row(v_1)).squaredNorm()* m_cached_edges_2[f_idx];\n\t\tpart_1 += (pow(x2 - x1, 2) + pow(y2 - y1, 2)) * m_cached_edges_2[f_idx];\n\t\tpart_1 /= (2 * m_dblArea_orig(f_idx));\n\n\t\t//DScalar part_2_1 = (uv.row(v_3)-uv.row(v_1)).dot(uv.row(v_2)-uv.row(v_1));\n\t\tauto part_2_1 = (x3 - x1) * (x2 - x1) + (y3 - y1) * (y2 - y1);\n\t\tdouble part_2_2 = m_cached_dot_prod[f_idx];\n\t\tauto part_2 = -(part_2_1 * part_2_2) / (m_dblArea_orig(f_idx));\n\n\t\tauto r_part = part_1 + part_2;\n\n\t\tenergy += l_part * r_part;\n\t}\n\treturn energy;\n}\n\ndouble SchaeferNewtonParametrizer::compute_energy_gradient_hessian(const Eigen::MatrixXi &F,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   Eigen::MatrixXd &uv,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   Eigen::VectorXd &grad,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   Eigen::SparseMatrix<double> &hessian) {\n\n\t// can save some computation time\n\thessian.resize(2*d_.v_num,2*d_.v_num);\n\thessian.reserve(10*2*d_.v_num);\n\tstd::vector<Eigen::Triplet<double> > IJV;//(10*2*6*d_.v_num);\n\tIJV.reserve(36*F.rows());\n\tgrad.resize(2*d_.v_num); grad.setZero();\n\n\tprecompute(F); // precompute if needed\n\t// uv is arranged by (x1,y1,x2,y2,...)\n\tdouble energy = 0;\n\tfor (int i = 0; i < F.rows(); i++) {\n\t\tDiffScalarBase::setVariableCount(6); // 3 vertices with 2 rows for each\n\t\tauto l_part = compute_face_energy_left_part(F, uv, i);\n\t\tauto r_part =\n\t\t\t\tcompute_face_energy_right_part(F, uv, i);\n\n\t\tauto temp = l_part * r_part;\n\t\tenergy += temp.getValue();\n\n\t\tEigen::VectorXd local_grad = temp.getGradient();\n\t\tfor (int v_i = 0; v_i < 3; v_i++) {\n\t\t\tint v_global = F(i,v_i);\n\n\t\t\tgrad(v_global*2) = grad(v_global*2) + local_grad(v_i*2); // x\n\t\t\tgrad(v_global*2+1) = grad(v_global*2+1) + local_grad(v_i*2+1); // y\n\t\t}\n\n\t\tEigen::MatrixXd local_hessian = temp.getHessian();\n//              Eigen::SelfAdjointEigenSolver<Eigen::Matrix<double, 6, 6>> es(local_hessian);\n//              Eigen::MatrixXd D = es.eigenvalues();\n//              Eigen::MatrixXd U = es.eigenvectors();\n//              for (int i = 0; i < 6; i++)\n//                      D(i) = (D(i) < 0) ? 0 : D(i);\n//              local_hessian = U * D.asDiagonal()* U.inverse();\n\t\tfor (int v1 = 0; v1 < 6; v1++) {\n\t\t\tfor (int v2 = 0; v2 < 6; v2++) {\n\t\t\t\tint v1_global = F(i,v1/2)*2 + v1%2;\n\t\t\t\tint v2_global = F(i,v2/2)*2 + v2%2;\n\n\t\t\t\tIJV.push_back(Eigen::Triplet<double>(v1_global,v2_global, local_hessian(v1,v2)));\n\t\t\t}\n\t\t}\n\t}\n\thessian.setFromTriplets(IJV.begin(),IJV.end());\n\treturn energy;\n}\n\nDScalar SchaeferNewtonParametrizer::compute_face_energy_left_part(const\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  Eigen::MatrixXi &F,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  const Eigen::MatrixXd &uv,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  int f_idx) {\n\n\tint v_1 = F(f_idx,0); int v_2 = F(f_idx,1); int v_3 = F(f_idx,2);\n\n\t// compute current triangle squared area\n\tDScalar x1(0*2,uv(v_1,0)); DScalar y1(0*2+1,uv(v_1,1)); //DScalar x0(F(f,0),0); DScalar y0(F(f,0),1);\n\tDScalar x2(1*2,uv(v_2,0)); DScalar y2(1*2+1,uv(v_2,1)); //DScalar x0(F(f,0),0); DScalar y0(F(f,0),1);\n\tDScalar x3(2*2,uv(v_3,0)); DScalar y3(2*2+1,uv(v_3,1)); //DScalar x0(F(f,0),0); DScalar y0(F(f,0),1);\n\n\t\n    auto rx = x1-x3;//uv(F(f,0),0)-uv(F(f,2),0);\n    auto sx = x2-x3;//uv(F(f,1),0)-uv(F(f,2),0);\n    auto ry = y1-y3;//uv(F(f,0),1)-uv(F(f,2),1);\n    auto sy = y2-y3;//uv(F(f,1),1)-uv(F(f,2),1);\n    auto dblAd = rx*sy - ry*sx;\n\tauto uv_sqrt_dbl_area = dblAd*dblAd;\n    \n\n    return (1/(m_dblArea_orig(f_idx)) + (m_dblArea_orig(f_idx)\n\t\t\t/uv_sqrt_dbl_area)) *\n\t\t\tm_dbl_area_weight(f_idx);\n}\n\nDScalar SchaeferNewtonParametrizer::compute_face_energy_right_part\n\t\t(const Eigen::MatrixXi &F, const Eigen::MatrixXd &uv, int f_idx) {\n\tint v_1 = F(f_idx,0); int v_2 = F(f_idx,1); int v_3 = F(f_idx,2);\n\n\tDScalar x1(0*2,uv(v_1,0)); DScalar y1(0*2+1,uv(v_1,1)); //DScalar x0(F(f,0),0); DScalar y0(F(f,0),1);\n\tDScalar x2(1*2,uv(v_2,0)); DScalar y2(1*2+1,uv(v_2,1)); //DScalar x0(F(f,0),0); DScalar y0(F(f,0),1);\n\tDScalar x3(2*2,uv(v_3,0)); DScalar y3(2*2+1,uv(v_3,1)); //DScalar x0(F(f,0),0); DScalar y0(F(f,0),1);\n\n\t//DScalar part_1 = (uv.row(v_3)-uv.row(v_1)).squaredNorm() * m_cached_edges_1[f_idx];\n\tauto part_1 =  ( pow(x3-x1,2) + pow(y3-y1,2) ) * m_cached_edges_1[f_idx];\n\t//part_1 += (uv.row(v_2)-uv.row(v_1)).squaredNorm()* m_cached_edges_2[f_idx];\n\tpart_1 += ( pow(x2-x1,2) + pow(y2-y1,2) ) * m_cached_edges_2[f_idx];\n\tpart_1 /= (2*m_dblArea_orig(f_idx));\n\n\t//DScalar part_2_1 = (uv.row(v_3)-uv.row(v_1)).dot(uv.row(v_2)-uv.row(v_1));\n\tauto part_2_1 = (x3-x1) * (x2-x1) + (y3-y1) * (y2-y1);\n\tdouble part_2_2 = m_cached_dot_prod[f_idx];\n\tauto part_2 = -(part_2_1 * part_2_2)/ (m_dblArea_orig(f_idx));\n\n\treturn part_1+part_2;\n}\n\nvoid SchaeferNewtonParametrizer::precompute(const Eigen::MatrixXi &F) {\n\tusing namespace Eigen;\n\tif (!has_precomputed) {\n\n//    \tigl::doublearea(V,F, m_dblArea_orig);\n\t\tm_dblArea_orig.resize(d_.f_num);\n\t\tm_dblArea_orig.head(d_.mf_num) = d_.m_M*2;\n\n\t\tVectorXd scaf_area;\n\t\tigl::doublearea(d_.w_uv, d_.s_T, scaf_area);\n\t\tm_dblArea_orig.tail(d_.sf_num) = scaf_area;\n\n\t\tm_dbl_area_weight = m_dblArea_orig;\n\t\tm_dbl_area_weight.tail(d_.sf_num) = d_.s_M*2;\n\n\t\t//m_cached_l_energy_per_face.resize(F.rows());\n\t\t//m_cached_r_energy_per_face.resize(F.rows());\n\t\tassert(F.rows() == d_.f_num);\n\n\t\tm_cached_edges_1.resize(F.rows());\n\t\tm_cached_edges_2.resize(F.rows());\n\t\tm_cached_dot_prod.resize(F.rows());\n\n      \tauto V = d_.m_V;\n\t\tfor (int f = 0; f < d_.mf_num; f++) {\n\t\t\tint v_1 = F(f, 0);\n\t\t\tint v_2 = F(f, 1);\n\t\t\tint v_3 = F(f, 2);\n\n\t\t\tm_cached_edges_1[f] = (V.row(v_2) - V.row(v_1)).squaredNorm();\n\t\t\tm_cached_edges_2[f] = (V.row(v_3) - V.row(v_1)).squaredNorm();\n\t\t\tm_cached_dot_prod[f] =\n\t\t\t\t\t(V.row(v_3) - V.row(v_1)).dot(V.row(v_2) - V.row(v_1));\n\t\t}\n\n\t\tV = d_.w_uv;\n\n      double min_bnd_edge_len = INFINITY;\n      int acc_bnd = 0;\n      for(int i=0; i<d_.bnd_sizes.size(); i++) {\n        int current_size = d_.bnd_sizes[i];\n\n        for(int e=acc_bnd; e<acc_bnd + current_size - 1; e++) {\n          min_bnd_edge_len = (std::min)(min_bnd_edge_len,\n                                      (d_.w_uv.row(d_.internal_bnd(e)) -\n                                          d_.w_uv.row(d_.internal_bnd(e+1)))\n                                          .squaredNorm());\n        }\n        min_bnd_edge_len = (std::min)(min_bnd_edge_len,\n                                    (d_.w_uv.row(d_.internal_bnd(acc_bnd)) -\n                                        d_.w_uv.row(d_.internal_bnd(acc_bnd +current_size -\n                                            1))).squaredNorm());\n        acc_bnd += current_size;\n      }\n\n      std::cout<<\"MinBndEdge\"<<min_bnd_edge_len<<std::endl;\n      double area_threshold = min_bnd_edge_len/4.0;\n\n\t\tfor(int f=d_.mf_num; f< d_.f_num; f++) {\n\t\t\tint v_1 = F(f, 0);\n\t\t\tint v_2 = F(f, 1);\n\t\t\tint v_3 = F(f, 2);\n\n\t\t\tif(m_dblArea_orig(f) <= area_threshold)\n\t\t\t{\n\t\t\t\tm_dblArea_orig(f) = area_threshold;\n\t\t\t\tauto dblA = m_dblArea_orig(f);\n\t\t\t\tdouble h = sqrt((dblA) / sin(\n\t\t\t\t\t\tM_PI / 3.0));\n\t\t\t\tEigen::Vector3d v1, v2, v3;\n\t\t\t\tv1 << 0, 0, 0;\n\t\t\t\tv2 << h, 0, 0;\n\t\t\t\tv3 << h / 2., (sqrt(3) / 2.) * h, 0;\n\n\t\t\t\tm_cached_edges_1[f] = (v2 - v1).squaredNorm();\n\t\t\t\tm_cached_edges_2[f] = (v3 - v1).squaredNorm();\n\t\t\t\tm_cached_dot_prod[f] =(v3 - v1).dot(v2-v1);\n\t\t\t} else {\n\t\t\t\tm_cached_edges_1[f] = (V.row(v_2) - V.row(v_1)).squaredNorm();\n\t\t\t\tm_cached_edges_2[f] = (V.row(v_3) - V.row(v_1)).squaredNorm();\n\t\t\t\tm_cached_dot_prod[f] =\n\t\t\t\t\t\t(V.row(v_3) - V.row(v_1)).dot(V.row(v_2) - V.row(v_1));\n\t\t\t}\n\t\t}\n\n\t\thas_precomputed = true;\n\t}\n}\n\ndouble energy_value(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, const Eigen::VectorXd& xx) {\n\tEigen::MatrixXd mat; vec_to_mat2(xx,mat);\n\tassert(false && \"Seems to be only used in finite verification\");\n\treturn 0;\n}\n\nvoid SchaeferNewtonParametrizer::finiteGradient(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F,\n\t\t\t\tconst Eigen::VectorXd &x, Eigen::VectorXd &grad, int accuracy) {\n    // accuracy can be 0, 1, 2, 3\n\n    const double eps = 2.2204e-8;\n    const size_t D = x.rows();\n    const int idx = (accuracy-3)/2;\n    const std::vector< std::vector <double>> coeff =\n    { {1, -1}, {1, -8, 8, -1}, {-1, 9, -45, 45, -9, 1}, {3, -32, 168, -672, 672, -168, 32, -3} };\n    const std::vector< std::vector <double>> coeff2 =\n    { {1, -1}, {-2, -1, 1, 2}, {-3, -2, -1, 1, 2, 3}, {-4, -3, -2, -1, 1, 2, 3, 4} };\n    const std::vector<double> dd = {2, 12, 60, 840};\n\n    Eigen::VectorXd finiteDiff(D);\n    for (size_t d = 0; d < D; d++) {\n      finiteDiff[d] = 0;\n      for (int s = 0; s < 2*(accuracy+1); ++s)\n      {\n        Eigen::VectorXd xx = x.eval();\n        xx[d] += coeff2[accuracy][s]*eps;\n        \n        finiteDiff[d] += coeff[accuracy][s]*energy_value(V,F,xx);\n      }\n      finiteDiff[d] /= (dd[accuracy]* eps);\n    }\n    grad = finiteDiff;\n  }\n\nbool SchaeferNewtonParametrizer::check_gradient(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F,\n\t\t\t\tconst Eigen::VectorXd& x, const Eigen::VectorXd& actual_grad, int accuracy) {\n   \tconst int D = x.rows();\n    Eigen::VectorXd expected_grad(D);\n    cout << \"computing finite gradient\" << endl;\n    finiteGradient(V,F,x, expected_grad, accuracy);\n    cout << \"done computing finite gradient\" << endl;\n\n    bool correct = true;\n\n    for (int d = 0; d < D; ++d) {\n      double scale = (std::max)((std::max)(fabs(actual_grad[d]), fabs(expected_grad[d])), 1.);\n      if(fabs(actual_grad[d]-expected_grad[d])>1e-2 * scale)\n        correct = false;\n    \tbreak;\n    }\n    return correct;\n}\n\n void SchaeferNewtonParametrizer::finiteHessian(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F,\n \t\t\tconst Eigen::VectorXd & x, Eigen::MatrixXd & hessian, int accuracy) {\n    const double eps = 2.2204e-08;\n    const size_t DIM = x.rows();\n\n    if(accuracy == 0) {\n      for (size_t i = 0; i < DIM; i++) {\n        for (size_t j = 0; j < DIM; j++) {\n          \n          Eigen::VectorXd xx = x;\n\n          xx[i] += eps; xx[j] += eps;\n          double f1 = energy_value(V,F,xx);\n          xx[i] -= eps; xx[j] -= eps;\n          \n          xx[i] += eps;\n          double f2 = energy_value(V,F,xx);\n          xx[i] -= eps;\n\n          xx[j] += eps;\n          double f3 = energy_value(V,F,xx);\n          xx[j] -= eps;\n\n          \n          double f4 = energy_value(V,F,xx);\n\n          hessian(i, j) = (f1 - f2 - f3 + f4) / (eps * eps);\n        }\n      }\n    } else {\n      Eigen::VectorXd xx;\n      for (size_t i = 0; i < DIM; i++) {\n        for (size_t j = 0; j < DIM; j++) {\n\n          double term_1 = 0;\n          xx = x.eval(); xx[i] += 1*eps;  xx[j] += -2*eps;  term_1 += energy_value(V,F,xx);\n          xx = x.eval(); xx[i] += 2*eps;  xx[j] += -1*eps;  term_1 += energy_value(V,F,xx);\n          xx = x.eval(); xx[i] += -2*eps; xx[j] += 1*eps;   term_1 += energy_value(V,F,xx);\n          xx = x.eval(); xx[i] += -1*eps; xx[j] += 2*eps;   term_1 += energy_value(V,F,xx);\n\n          double term_2 = 0;\n          xx = x.eval(); xx[i] += -1*eps; xx[j] += -2*eps;  term_2 += energy_value(V,F,xx);\n          xx = x.eval(); xx[i] += -2*eps; xx[j] += -1*eps;  term_2 += energy_value(V,F,xx);\n          xx = x.eval(); xx[i] += 1*eps;  xx[j] += 2*eps;   term_2 += energy_value(V,F,xx);\n          xx = x.eval(); xx[i] += 2*eps;  xx[j] += 1*eps;   term_2 += energy_value(V,F,xx);\n\n          double term_3 = 0;\n          xx = x.eval(); xx[i] += 2*eps;  xx[j] += -2*eps;  term_3 += energy_value(V,F,xx);\n          xx = x.eval(); xx[i] += -2*eps; xx[j] += 2*eps;   term_3 += energy_value(V,F,xx);\n          xx = x.eval(); xx[i] += -2*eps; xx[j] += -2*eps;  term_3 -= energy_value(V,F,xx);\n          xx = x.eval(); xx[i] += 2*eps;  xx[j] += 2*eps;   term_3 -= energy_value(V,F,xx);\n\n          double term_4 = 0;\n          xx = x.eval(); xx[i] += -1*eps; xx[j] += -1*eps;  term_4 += energy_value(V,F,xx);\n          xx = x.eval(); xx[i] += 1*eps;  xx[j] += 1*eps;   term_4 += energy_value(V,F,xx);\n          xx = x.eval(); xx[i] += 1*eps;  xx[j] += -1*eps;  term_4 -= energy_value(V,F,xx);\n          xx = x.eval(); xx[i] += -1*eps; xx[j] += 1*eps;   term_4 -= energy_value(V,F,xx);\n\n          hessian(i, j) = (-63 * term_1+63 * term_2+44 * term_3+74 * term_4)/(600.0 * eps * eps);\n\n        }\n      }\n    }\n\n  }\n\n  void SchaeferNewtonParametrizer::get_gradient(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F,\n                  Eigen::VectorXd& uv, Eigen::VectorXd& grad) {\n  \t Eigen::SparseMatrix<double> hessian;\n  \t Eigen::MatrixXd uv_mat; vec_to_mat2(uv,uv_mat);\n\t  compute_energy_gradient_hessian(F,\n\t\t\t\t\t\t\t\t\t  uv_mat,\n\t\t\t\t\t\t\t\t\t  grad,\n\t\t\t\t\t\t\t\t\t  hessian);\n  }\n\n  void SchaeferNewtonParametrizer::finiteHessian_with_grad(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F,\n  \t\t\t\t\tconst Eigen::VectorXd& x,\n \t\t\t\t\tEigen::MatrixXd & hessian, int accuracy) {\n  \tint var_num = V.rows()*2;\n  \tconst double eps = 2.2204e-08;\n  \thessian.resize(var_num,var_num);\n  \t\n  \tfor (int i = 0; i < var_num; i++) {\n  \t\tfor (int j = 0; j < var_num; j++) {\n  \t\t\tEigen::VectorXd new_x = x;\n  \t\t\t\n  \t\t\tEigen::VectorXd grad_cur; get_gradient(V,F,new_x, grad_cur);\n  \t\t\tdouble gi_x = grad_cur(i); double gj_x = grad_cur(j);\n\n  \t\t\tnew_x(j) = new_x(j) + eps;\n  \t\t\tEigen::VectorXd grad_i;  get_gradient(V,F,new_x, grad_i);\n  \t\t\tdouble gradj_plus_i = grad_i(i);\n  \t\t\tnew_x(j) = new_x(j) - eps;\n\n  \t\t\tnew_x(i) = new_x(i) + eps;\n  \t\t\tEigen::VectorXd grad_j;  get_gradient(V,F,new_x, grad_j);\n  \t\t\tdouble gradi_plus_j = grad_j(j);\n  \t\t\tnew_x(j) = new_x(j) - eps;\n\n  \t\t\thessian(i,j) =  (gradj_plus_i - gj_x)/(2*eps) + (gradi_plus_j - gi_x)/(2*eps);\n  \t\t}\n  \t}\n  }\n\n\nbool SchaeferNewtonParametrizer::checkHessian(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F,\n\t\t\t\t\tconst Eigen::VectorXd & x, const Eigen::MatrixXd& actual_hessian, int accuracy) {\n    // TODO: check if derived class exists:\n    // int(typeid(&Rosenbrock<double>::gradient) == typeid(&Problem<double>::gradient)) == 1 --> overwritten\n    const int D = x.rows();\n    bool correct = true;\n\n    Eigen::MatrixXd expected_hessian = Eigen::MatrixXd::Zero(D, D);\n    //finiteHessian(V,F,x, expected_hessian, accuracy);\n    finiteHessian_with_grad(V,F,x, expected_hessian, accuracy);\n\n    for (int d = 0; d < D; ++d) {\n      for (int e = 0; e < D; ++e) {\n        double scale = (std::max)((std::max)(fabs(actual_hessian(d, e)), fabs(expected_hessian(d, e))), 1.);\n        if(fabs(actual_hessian(d, e)- expected_hessian(d, e))>1e-1 * scale) {\n        \t\tcout << \"not correct for d = \" << d << \" and e = \" << e << endl;\n        \t\tcorrect = false;\n        \t}\n      }\n    }\n    return correct;\n\n  }\n", "meta": {"hexsha": "fb43286fc6f1c302a69af0ad337b42b752c87269", "size": 18798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Newton/SchaeferNewtonParametrizer.cpp", "max_stars_repo_name": "squarefk/Scaffold-Map", "max_stars_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2018-04-04T19:50:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T00:56:10.000Z", "max_issues_repo_path": "src/Newton/SchaeferNewtonParametrizer.cpp", "max_issues_repo_name": "squarefk/Scaffold-Map", "max_issues_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-04-27T05:01:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-21T19:07:28.000Z", "max_forks_repo_path": "src/Newton/SchaeferNewtonParametrizer.cpp", "max_forks_repo_name": "squarefk/Scaffold-Map", "max_forks_repo_head_hexsha": "6218cbc3ec5b83cb24c5bc65dd21e7b3a52dc76b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-04-05T10:50:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T14:26:09.000Z", "avg_line_length": 34.6826568266, "max_line_length": 110, "alphanum_fraction": 0.5882008724, "num_tokens": 6568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4274734660706856}}
{"text": "// Copyright (c) Facebook, Inc. and its affiliates.\n\n// This source code is licensed under the MIT license found in the\n// LICENSE file in the root directory of this source tree.\n#include <fstream>\n#include <iostream>\n#include <string>\n\n#include \"dtt.h\"\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include <torch/script.h>\n#include <torch/torch.h>\n\n#include \"pinocchio/algorithm/frames.hpp\"\n#include \"pinocchio/algorithm/jacobian.hpp\"\n#include \"pinocchio/algorithm/joint-configuration.hpp\"\n#include \"pinocchio/algorithm/kinematics.hpp\"\n#include \"pinocchio/algorithm/rnea.hpp\"\n#include \"pinocchio/parsers/urdf.hpp\"\n\ntorch::Tensor validTensor(torch::Tensor x) {\n  if (x.dim() < 2) {\n    x = x.unsqueeze(1);\n  }\n  return x.to(torch::kDouble);\n}\n\nEigen::VectorXd matrixToVector(Eigen::MatrixXd A) {\n  return Eigen::VectorXd(\n      Eigen::Map<Eigen::VectorXd>(A.data(), A.cols() * A.rows()));\n}\n\nstruct RobotModelPinocchio : torch::CustomClassHolder {\n  pinocchio::Model model_;\n  pinocchio::Data model_data_;\n  pinocchio::FrameIndex ee_idx_;\n\n  std::string xml_buffer_;\n  std::string ee_joint_name_;\n\n  RobotModelPinocchio(std::string urdf_filename, std::string ee_joint_name) {\n    ee_joint_name_ = ee_joint_name;\n\n    std::ifstream stream(urdf_filename);\n    xml_buffer_ = std::string((std::istreambuf_iterator<char>(stream)),\n                              std::istreambuf_iterator<char>());\n\n    initialize();\n  }\n\n  RobotModelPinocchio(std::vector<std::string> serialized_state) {\n    ee_joint_name_ = serialized_state[0];\n    xml_buffer_ = serialized_state[1];\n    initialize();\n  }\n\n  void initialize() {\n    pinocchio::urdf::buildModelFromXML(xml_buffer_, model_);\n    model_data_ = pinocchio::Data(model_);\n    ee_idx_ = model_.getFrameId(ee_joint_name_);\n  }\n\n  c10::List<torch::Tensor> get_joint_angle_limits(void) {\n    c10::List<torch::Tensor> result;\n    torch::Tensor l_result = torch::zeros(model_.nq, torch::kFloat32);\n    torch::Tensor u_result = torch::zeros(model_.nq, torch::kFloat32);\n\n    for (int i = 0; i < model_.nq; i++) {\n      l_result[i] = model_.lowerPositionLimit[i];\n      u_result[i] = model_.upperPositionLimit[i];\n    }\n    result.push_back(l_result);\n    result.push_back(u_result);\n\n    return result;\n  }\n\n  torch::Tensor get_joint_velocity_limits(void) {\n    torch::Tensor result = torch::zeros(model_.nq, torch::kFloat32);\n\n    for (int i = 0; i < model_.nq; i++) {\n      result[i] = model_.velocityLimit[i];\n    }\n\n    return result;\n  }\n\n  c10::List<torch::Tensor> forward_kinematics(torch::Tensor joint_positions) {\n    c10::List<torch::Tensor> result;\n    torch::Tensor pos_result = torch::zeros(3, torch::kFloat32);\n    torch::Tensor quat_result = torch::zeros(4, torch::kFloat32);\n\n    joint_positions = validTensor(joint_positions);\n    pinocchio::forwardKinematics(\n        model_, model_data_,\n        matrixToVector(dtt::libtorch2eigen<double>(joint_positions)));\n    pinocchio::updateFramePlacement(model_, model_data_, ee_idx_);\n\n    auto pos_data = model_data_.oMf[ee_idx_].translation().transpose();\n    auto quat_data = Eigen::Quaterniond(model_data_.oMf[ee_idx_].rotation());\n\n    for (int i = 0; i < 3; i++) {\n      pos_result[i] = pos_data[i];\n    }\n    quat_result[0] = quat_data.x();\n    quat_result[1] = quat_data.y();\n    quat_result[2] = quat_data.z();\n    quat_result[3] = quat_data.w();\n\n    result.push_back(pos_result);\n    result.push_back(quat_result);\n\n    return result;\n  }\n\n  torch::Tensor compute_jacobian(torch::Tensor joint_positions) {\n    joint_positions = validTensor(joint_positions);\n\n    torch::Tensor result = torch::zeros({6, model_.nq}, torch::kFloat64);\n    Eigen::Map<dtt::MatrixXrm<double>> J(result.data_ptr<double>(),\n                                         result.size(0), result.size(1));\n    pinocchio::computeFrameJacobian(\n        model_, model_data_,\n        matrixToVector(dtt::libtorch2eigen<double>(joint_positions)), ee_idx_,\n        pinocchio::LOCAL_WORLD_ALIGNED, J);\n\n    return result;\n  }\n\n  torch::Tensor inverse_dynamics(torch::Tensor joint_positions,\n                                 torch::Tensor joint_velocities,\n                                 torch::Tensor joint_accelerations) {\n    joint_positions = validTensor(joint_positions);\n    joint_velocities = validTensor(joint_velocities);\n    joint_accelerations = validTensor(joint_accelerations);\n    auto q = matrixToVector(dtt::libtorch2eigen<double>(joint_positions));\n    auto v = matrixToVector(dtt::libtorch2eigen<double>(joint_velocities));\n    auto a = matrixToVector(dtt::libtorch2eigen<double>(joint_accelerations));\n\n    Eigen::Matrix<double, Eigen::Dynamic, 1> tau =\n        pinocchio::rnea(model_, model_data_, q, v, a);\n    std::vector<int64_t> dims = {tau.rows()};\n    return torch::from_blob(tau.data(), dims, torch::kFloat64).clone();\n  }\n};\n\nTORCH_LIBRARY(torchscript_pinocchio, m) {\n  m.class_<RobotModelPinocchio>(\"RobotModelPinocchio\")\n      .def(torch::init<std::string, std::string>())\n      .def(\"get_joint_angle_limits\",\n           &RobotModelPinocchio::get_joint_angle_limits)\n      .def(\"get_joint_velocity_limits\",\n           &RobotModelPinocchio::get_joint_velocity_limits)\n      .def(\"forward_kinematics\", &RobotModelPinocchio::forward_kinematics)\n      .def(\"compute_jacobian\", &RobotModelPinocchio::compute_jacobian)\n      .def(\"inverse_dynamics\", &RobotModelPinocchio::inverse_dynamics)\n      .def_pickle(\n          // __getstate__\n          [](const c10::intrusive_ptr<RobotModelPinocchio> &self)\n              -> std::vector<std::string> {\n            return std::vector<std::string>{self->ee_joint_name_,\n                                            self->xml_buffer_};\n          },\n          // __setstate__\n          [](std::vector<std::string> state)\n              -> c10::intrusive_ptr<RobotModelPinocchio> {\n            return c10::make_intrusive<RobotModelPinocchio>(std::move(state));\n          });\n}", "meta": {"hexsha": "d84006c5e2f65577457238fef58acaf92b413fd7", "size": 5909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "polymetis/src/torchscript_operators/pinocchio.cpp", "max_stars_repo_name": "facebookresearch/polymetis", "max_stars_repo_head_hexsha": "1b2ea8528d4fb9ad72cec9c766be4cbdbdf76f18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2021-06-28T15:35:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T04:34:34.000Z", "max_issues_repo_path": "polymetis/src/torchscript_operators/pinocchio.cpp", "max_issues_repo_name": "facebookresearch/polymetis", "max_issues_repo_head_hexsha": "1b2ea8528d4fb9ad72cec9c766be4cbdbdf76f18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-28T20:16:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T21:25:44.000Z", "max_forks_repo_path": "polymetis/src/torchscript_operators/pinocchio.cpp", "max_forks_repo_name": "facebookresearch/polymetis", "max_forks_repo_head_hexsha": "1b2ea8528d4fb9ad72cec9c766be4cbdbdf76f18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-29T14:14:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T13:26:12.000Z", "avg_line_length": 34.5555555556, "max_line_length": 78, "alphanum_fraction": 0.6733795905, "num_tokens": 1520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.42747079991578185}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2013   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_LAPACK_GENERAL_GEBAL_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_LAPACK_GENERAL_GEBAL_HPP_INCLUDED\n\n#include <nt2/linalg/functions/gebal.hpp>\n#include <nt2/linalg/details/lapack/declare/gebal.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/functions/height.hpp>\n#include <nt2/include/functions/width.hpp>\n#include <nt2/include/functions/of_size.hpp>\n#include <nt2/linalg/details/utility/workspace.hpp>\n#include <nt2/linalg/details/utility/f77_wrapper.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace nt2 { namespace ext\n{\n\n//---------------------------------------------Real-double------------------------------------------------//\n\n  BOOST_DISPATCH_IMPLEMENT  ( gebal_, tag::cpu_\n                            , (A0)(S0)(A1)(S1)(A2)(A3)(C0)\n                            , ((container_<nt2::tag::table_,  double_<A0>, S0 >)) //a\n                              ((container_<nt2::tag::table_,  double_<A1>, S1 >)) //scale\n                              (scalar_< integer_<A2> >)                           //ilo\n                              (scalar_< integer_<A3> >)                           //ihi\n                              (scalar_< ints8_<C0> >)                             //job\n                            )\n  {\n    typedef nt2_la_int result_type;\n\n     BOOST_FORCEINLINE result_type operator()( A0& a, A1& scale\n                                             , A2& ilo, A3& ihi, C0 job) const\n     {\n        result_type info;\n        nt2_la_int  n   = nt2::width(a);\n        BOOST_ASSERT_MSG(n == nt2_la_int(nt2::height(a)), \"input must be square\");\n        nt2_la_int  lda = nt2::max(a.leading_size(), One<size_t>());\n        NT2_F77NAME(dgebal) (&job, &n\n                            , a.data(), &lda\n                            , &ilo, &ihi\n                            , scale.data(), &info);\n        return info;\n     }\n  };\n\n//---------------------------------------------Real-single------------------------------------------------//\n\n  BOOST_DISPATCH_IMPLEMENT  ( gebal_, tag::cpu_\n                            , (A0)(S0)(A1)(S1)(A2)(A3)(C0)\n                            , ((container_<nt2::tag::table_,  single_<A0>, S0 >)) //a\n                              ((container_<nt2::tag::table_,  single_<A1>, S1 >)) //scale\n                              (scalar_< integer_<A2> >)                           //ilo\n                              (scalar_< integer_<A3> >)                           //ihi\n                              (scalar_< ints8_<C0> >)                             //job\n                            )\n  {\n    typedef nt2_la_int result_type;\n\n     BOOST_FORCEINLINE result_type operator()( A0& a, A1& scale\n                                             , A2& ilo, A3& ihi, C0 job) const\n     {\n        result_type info;\n        nt2_la_int  n   = nt2::width(a);\n        BOOST_ASSERT_MSG(n == nt2_la_int(nt2::height(a)), \"input must be square\");\n        nt2_la_int  lda = nt2::max(a.leading_size(), One<size_t>());\n        NT2_F77NAME(sgebal) (&job, &n\n                            , a.data(), &lda\n                            , &ilo, &ihi\n                            , scale.data(), &info);\n        return info;\n     }\n  };\n\n//---------------------------------------------Complex-single------------------------------------------------//\n\n  BOOST_DISPATCH_IMPLEMENT  ( gebal_, tag::cpu_\n                            , (A0)(S0)(A1)(S1)(A2)(A3)(C0)\n                            , ((container_<nt2::tag::table_,  complex_<single_<A0> > , S0 >)) //a\n                              ((container_<nt2::tag::table_,  single_<A1>, S1 >)) //scale\n                              (scalar_< integer_<A2> >)                           //ilo\n                              (scalar_< integer_<A3> >)                           //ihi\n                              (scalar_< ints8_<C0> >)                             //job\n                            )\n  {\n    typedef nt2_la_int result_type;\n\n     BOOST_FORCEINLINE result_type operator()( A0& a, A1& scale\n                                             , A2& ilo, A3& ihi, C0 job) const\n     {\n        result_type info;\n        nt2_la_int  n   = nt2::width(a);\n        BOOST_ASSERT_MSG(n == nt2_la_int(nt2::height(a)), \"input must be square\");\n        nt2_la_int  lda = nt2::max(a.leading_size(), One<size_t>());\n        NT2_F77NAME(cgebal) (&job, &n\n                            , a.data(), &lda\n                            , &ilo, &ihi\n                            , scale.data(), &info);\n        return info;\n     }\n  };\n\n//---------------------------------------------Complex-double------------------------------------------------//\n\n  BOOST_DISPATCH_IMPLEMENT  ( gebal_, tag::cpu_\n                            , (A0)(S0)(A1)(S1)(A2)(A3)(C0)\n                            , ((container_<nt2::tag::table_,  complex_<double_<A0> > , S0 >)) //a\n                              ((container_<nt2::tag::table_,  double_<A1>, S1 >)) //scale\n                              (scalar_< integer_<A2> >)                           //ilo\n                              (scalar_< integer_<A3> >)                           //ihi\n                              (scalar_< ints8_<C0> >)                             //job\n                            )\n  {\n    typedef nt2_la_int result_type;\n\n     BOOST_FORCEINLINE result_type operator()( A0& a, A1& scale\n                                             , A2& ilo, A3& ihi, C0 job) const\n     {\n        result_type info = 0;\n        nt2_la_int  n   = nt2::width(a);\n        BOOST_ASSERT_MSG(n == nt2_la_int(nt2::height(a)), \"input must be square\");\n        nt2_la_int  lda = nt2::max(a.leading_size(), One<size_t>());\n        NT2_F77NAME(zgebal) (&job, &n\n                            , a.data(), &lda\n                            , &ilo, &ihi\n                            , scale.data(), &info);\n        return info;\n     }\n  };\n\n\n} }\n\n#endif\n", "meta": {"hexsha": "28a991eab6de357c4d3086659c5fea189d9899f7", "size": 6361, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/lapack/general/gebal.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/linalg/include/nt2/linalg/functions/lapack/general/gebal.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/linalg/include/nt2/linalg/functions/lapack/general/gebal.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 45.1134751773, "max_line_length": 111, "alphanum_fraction": 0.409369596, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.427447263506897}}
{"text": "#pragma once\n#include <pybind11/eigen.h>\n#include <pybind11/numpy.h>\n\n#include <Eigen/Core>\n#include <boost/geometry/algorithms/area.hpp>\n#include <boost/geometry/algorithms/covered_by.hpp>\n#include <boost/geometry/srs/spheroid.hpp>\n#if BOOST_VERSION >= 107500\n#include <boost/geometry/strategy/area.hpp>\n#include <boost/geometry/strategy/geographic/area.hpp>\n#else\n#include <boost/geometry/strategies/area.hpp>\n#include <boost/geometry/strategies/geographic/area.hpp>\n#endif\n#include <boost/geometry/strategies/geographic/distance_andoyer.hpp>\n#include <boost/geometry/strategies/geographic/distance_thomas.hpp>\n#include <boost/geometry/strategies/geographic/distance_vincenty.hpp>\n#include <optional>\n\n#include \"pyinterp/detail/broadcast.hpp\"\n#include \"pyinterp/detail/thread.hpp\"\n#include \"pyinterp/geodetic/system.hpp\"\n\nnamespace pyinterp::geodetic {\n\n/// Distance calculation strategy.\nenum DistanceStrategy { kAndoyer = 0x0, kThomas = 0x1, kVincenty = 0x2 };\n\nusing Andoyer = boost::geometry::strategy::distance::andoyer<\n    boost::geometry::srs::spheroid<double>>;\nusing Thomas = boost::geometry::strategy::distance::thomas<\n    boost::geometry::srs::spheroid<double>>;\nusing Vincenty = boost::geometry::strategy::distance::vincenty<\n    boost::geometry::srs::spheroid<double>>;\n\n/// Calculate the area\ntemplate <typename Geometry>\n[[nodiscard]] inline auto area(const Geometry &geometry,\n                               const std::optional<System> &wgs) -> double {\n  auto spheroid = wgs.has_value()\n                      ? boost::geometry::srs::spheroid(wgs->semi_major_axis(),\n                                                       wgs->semi_minor_axis())\n                      : boost::geometry::srs::spheroid<double>();\n  auto strategy = boost::geometry::strategy::area::geographic<\n      boost::geometry::strategy::vincenty, 5>(spheroid);\n  return boost::geometry::area(geometry, strategy);\n}\n\n/// Checks if the first geometry is inside or on border the second geometry\n/// using the specified strategy.\ntemplate <typename Geometry1, typename Geometry2>\n[[nodiscard]] inline auto covered_by(\n    const Geometry2 &geometry2, const Eigen::Ref<const Eigen::VectorXd> &lon,\n    const Eigen::Ref<const Eigen::VectorXd> &lat, const size_t num_threads)\n    -> pybind11::array_t<int8_t> {\n  detail::check_eigen_shape(\"lon\", lon, \"lat\", lat);\n  auto size = lon.size();\n  auto result =\n      pybind11::array_t<int8_t>(pybind11::array::ShapeContainer{{size}});\n  auto _result = result.template mutable_unchecked<1>();\n\n  {\n    pybind11::gil_scoped_release release;\n\n    // Captures the detected exceptions in the calculation function\n    // (only the last exception captured is kept)\n    auto except = std::exception_ptr(nullptr);\n\n    detail::dispatch(\n        [&](size_t start, size_t end) {\n          try {\n            for (auto ix = static_cast<int64_t>(start);\n                 ix < static_cast<int64_t>(end); ++ix) {\n              _result(ix) = static_cast<int8_t>(boost::geometry::covered_by(\n                  Geometry1(lon(ix), lat(ix)), geometry2));\n            }\n          } catch (...) {\n            except = std::current_exception();\n          }\n        },\n        size, num_threads);\n\n    if (except != nullptr) {\n      std::rethrow_exception(except);\n    }\n  }\n  return result;\n}\n\n/// Calculate the distance between two geometries.\ntemplate <typename Geometry1, typename Geometry2>\n[[nodiscard]] inline auto distance(const Geometry1 &geometry1,\n                                   const Geometry2 &geometry2,\n                                   const DistanceStrategy strategy,\n                                   const std::optional<System> &wgs) -> double {\n  auto spheroid = wgs.has_value()\n                      ? boost::geometry::srs::spheroid(wgs->semi_major_axis(),\n                                                       wgs->semi_minor_axis())\n                      : boost::geometry::srs::spheroid<double>();\n  switch (strategy) {\n    case kAndoyer:\n      return boost::geometry::distance(geometry1, geometry2, Andoyer(spheroid));\n      break;\n    case kThomas:\n      return boost::geometry::distance(geometry1, geometry2, Thomas(spheroid));\n      break;\n    case kVincenty:\n      return boost::geometry::distance(geometry1, geometry2,\n                                       Vincenty(spheroid));\n      break;\n  }\n  throw std::invalid_argument(\"unknown strategy: \" +\n                              std::to_string(static_cast<int>(strategy)));\n}\n\n/// Calculate the distance between two geometries.\ntemplate <typename Geometry1, typename Geometry2>\n[[nodiscard]] inline auto distance(const Geometry1 &geometry1,\n                                   const Geometry2 &geometry2) -> double {\n  return boost::geometry::distance(geometry1, geometry2);\n}\n\n/// Calculate the distance between coordinates.\ntemplate <typename Geometry, typename Strategy>\n[[nodiscard]] inline auto coordinate_distances(\n    const Eigen::Ref<const Eigen::VectorXd> &lon1,\n    const Eigen::Ref<const Eigen::VectorXd> &lat1,\n    const Eigen::Ref<const Eigen::VectorXd> &lon2,\n    const Eigen::Ref<const Eigen::VectorXd> &lat2, const Strategy &strategy,\n    const size_t num_threads) -> pybind11::array_t<double> {\n  auto size = lon1.size();\n  auto result =\n      pybind11::array_t<double>(pybind11::array::ShapeContainer{{size}});\n  auto _result = result.template mutable_unchecked<1>();\n\n  {\n    pybind11::gil_scoped_release release;\n\n    // Captures the detected exceptions in the calculation function\n    // (only the last exception captured is kept)\n    auto except = std::exception_ptr(nullptr);\n\n    detail::dispatch(\n        [&](size_t start, size_t end) {\n          try {\n            for (auto ix = static_cast<int64_t>(start);\n                 ix < static_cast<int64_t>(end); ++ix) {\n              _result(ix) = boost::geometry::distance(\n                  Geometry(lon1(ix), lat1(ix)), Geometry(lon2(ix), lat2(ix)),\n                  strategy);\n            }\n          } catch (...) {\n            except = std::current_exception();\n          }\n        },\n        size, num_threads);\n\n    if (except != nullptr) {\n      std::rethrow_exception(except);\n    }\n  }\n  return result;\n}\n\n/// Calculate the distance between coordinates.\ntemplate <typename Geometry>\n[[nodiscard]] inline auto coordinate_distances(\n    const Eigen::Ref<const Eigen::VectorXd> &lon1,\n    const Eigen::Ref<const Eigen::VectorXd> &lat1,\n    const Eigen::Ref<const Eigen::VectorXd> &lon2,\n    const Eigen::Ref<const Eigen::VectorXd> &lat2,\n    const DistanceStrategy strategy, const std::optional<System> &wgs,\n    const size_t num_threads) -> pybind11::array_t<double> {\n  detail::check_eigen_shape(\"lon1\", lon1, \"lat1\", lat1, \"lon2\", lon2, \"lat2\",\n                            lat2);\n  auto spheroid = wgs.has_value()\n                      ? boost::geometry::srs::spheroid(wgs->semi_major_axis(),\n                                                       wgs->semi_minor_axis())\n                      : boost::geometry::srs::spheroid<double>();\n  switch (strategy) {\n    case kAndoyer:\n      return coordinate_distances<Geometry, Andoyer>(\n          lon1, lat1, lon2, lat2, Andoyer(spheroid), num_threads);\n      break;\n    case kThomas:\n      return coordinate_distances<Geometry, Thomas>(\n          lon1, lat1, lon2, lat2, Thomas(spheroid), num_threads);\n      break;\n    case kVincenty:\n      return coordinate_distances<Geometry, Vincenty>(\n          lon1, lat1, lon2, lat2, Vincenty(spheroid), num_threads);\n      break;\n  }\n  throw std::invalid_argument(\"unknown strategy: \" +\n                              std::to_string(static_cast<int>(strategy)));\n}\n\n}  // namespace pyinterp::geodetic", "meta": {"hexsha": "963df4b4c63d412a45b4d62a93b1975af6ee614d", "size": 7661, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/geodetic/algorithm.hpp", "max_stars_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_stars_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/geodetic/algorithm.hpp", "max_issues_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_issues_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/geodetic/algorithm.hpp", "max_forks_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_forks_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4974874372, "max_line_length": 80, "alphanum_fraction": 0.6343819345, "num_tokens": 1765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.4274173628441904}}
{"text": "/*\n * BSD 3-Clause License\n * Copyright (c) 2020, Levente Kiss\n * All rights reserved.\n *\n * You may obtain a copy of the License at\n * https://opensource.org/licenses/BSD-3-Clause\n */\n\n#ifndef OLP_LOAMSLAMCALCULATOR_HPP\n#define OLP_LOAMSLAMCALCULATOR_HPP\n\n#include <thread>\n\n#include <boost/thread/barrier.hpp>\n\n#include <pcl/common/io.h>\n#include <pcl/common/transforms.h>\n#include <pcl/kdtree/kdtree_flann.h>\n\n#include \"../../helpers/ViewerHelper.h\"\n#include \"Calculator.h\"\n\nnamespace olp\n{\nnamespace compute\n{\ntemplate<typename PointType>\nclass LOAMSLAMCalculator : public Calculator<PointType>\n{\npublic:\n    LOAMSLAMCalculator(TransformData data) : Calculator<PointType>(data), BEAMCOUNT_(16), _barrier(BEAMCOUNT_ + 1)\n    {\n        _previousCloud = pcl::PointCloud<PointType>().makeShared();\n    }\n\n    TransformData calculate(typename pcl::PointCloud<PointType>::ConstPtr input) override;\n\n    const std::string stringId() const override\n    {\n        return \"LOAM\";\n    }\n\nprotected:\n    unsigned const BEAMCOUNT_;\n    const double SCAN_PERIOD_ = 0.1;\n    const float THRESHOLD_ = 0.1;\n    const double NEARBY_SCAN_ = 2.5;\nprivate:\n    boost::barrier _barrier;\n    typename pcl::PointCloud<PointType>::Ptr _previousCloud;\n\n    inline int _pointID(const PointType& point);\n\n    void _calculateDistortion(typename pcl::PointCloud<PointType>::Ptr points);\n\n    void _transformToStart(PointType const* const pi,\n                           PointType* const po,\n                           const Eigen::Vector3d& translation,\n                           const Eigen::Vector3d& rotation);\n\n\n    void _findPlanarAndEdgePoint(const typename pcl::PointCloud<PointType>::ConstPtr input,\n                                 std::vector<int>& planarPointIndexes,\n                                 std::vector<int>& edgePointIndexes,\n                                 int maxEdgePoints, int maxPlanarPoints,\n                                 float threshold);\n\n    void _findCorrespondances(const typename pcl::PointCloud<PointType>::ConstPtr previousCloud,\n                              const typename pcl::PointCloud<PointType>::ConstPtr currentCloud,\n                              const std::vector<int>& planarPointIndexes,\n                              const std::vector<int>& edgePointIndexes,\n                              Eigen::Vector3d& rotation,\n                              Eigen::Vector3d& translation,\n                              float threshold);\n};\n\ntemplate<typename PointType>\nTransformData LOAMSLAMCalculator<PointType>::calculate(typename pcl::PointCloud<PointType>::ConstPtr input)\n{\n    typename pcl::PointCloud<PointType>::Ptr correctedIn(new pcl::PointCloud<PointType>);\n    pcl::copyPointCloud(*input, *correctedIn);\n    std::vector<int> planarPoints;\n    std::vector<int> edgePoints;\n    std::shared_ptr<std::map<int, float>> cValues(new std::map<int, float>);\n\n    _calculateDistortion(correctedIn);\n    _findPlanarAndEdgePoint(correctedIn, planarPoints, edgePoints, 2, 4, THRESHOLD_);\n\n    if (_previousCloud->size() > 0)\n    {\n        Eigen::Vector3d rotation, translation;\n        _findCorrespondances(_previousCloud, correctedIn, planarPoints, edgePoints, rotation, translation, 25);\n        TransformData result = TransformData(70);\n        result.transform *= Eigen::AngleAxisd(rotation(2), Eigen::Vector3d::UnitZ());\n        result.transform.translation() = translation;\n        return result;\n    }\n    pcl::copyPointCloud(*input, *_previousCloud);\n    return TransformData();\n}\n\ntemplate<typename PointType>\ninline int LOAMSLAMCalculator<PointType>::_pointID(const PointType& point)\n{\n    float angle = atan(point.z / sqrt(point.x * point.x + point.y * point.y)) * 180 / M_PI;\n    int scanID = 0;\n    scanID = int((angle + 15) / 2 + 0.5);\n    if (scanID > (BEAMCOUNT_ - 1) || scanID < 0)\n    {\n        return -1;\n    }\n    return scanID;\n}\n\ntemplate<typename PointType>\nvoid LOAMSLAMCalculator<PointType>::_calculateDistortion(typename pcl::PointCloud<PointType>::Ptr points)\n{\n    bool halfPassed = false;\n    float startOri = -atan2(points->points[0].y, points->points[0].x);\n    float endOri = -atan2(points->points[points->points.size() - 1].y,\n                          points->points[points->points.size() - 1].x) +\n                   2 * M_PI;\n    if (endOri - startOri > 3 * M_PI)\n    {\n        endOri -= 2 * M_PI;\n    }\n    else if (endOri - startOri < M_PI)\n    {\n        endOri += 2 * M_PI;\n    }\n    int cloudSize = points->points.size();\n    for (int i = 0; i < cloudSize; i++)\n    {\n        int scanID = _pointID(points->points[i]);\n\n\n        float ori = -atan2(points->points[i].y, points->points[i].x);\n        if (!halfPassed)\n        {\n            if (ori < startOri - M_PI / 2)\n            {\n                ori += 2 * M_PI;\n            }\n            else if (ori > startOri + M_PI * 3 / 2)\n            {\n                ori -= 2 * M_PI;\n            }\n\n            if (ori - startOri > M_PI)\n            {\n                halfPassed = true;\n            }\n        }\n        else\n        {\n            ori += 2 * M_PI;\n            if (ori < endOri - M_PI * 3 / 2)\n            {\n                ori += 2 * M_PI;\n            }\n            else if (ori > endOri + M_PI / 2)\n            {\n                ori -= 2 * M_PI;\n            }\n        }\n\n        float relTime = (ori - startOri) / (endOri - startOri);\n        points->points[i].intensity = scanID + SCAN_PERIOD_ * relTime;\n    }\n}\n\ntemplate<typename PointType>\nvoid LOAMSLAMCalculator<PointType>::_transformToStart(\n    PointType const* const pi,\n    PointType* const po,\n    const Eigen::Vector3d& translation,\n    const Eigen::Vector3d& rotation)\n{\n    //interpolation ratio\n    double s = (pi->intensity - int(pi->intensity)) / SCAN_PERIOD_;\n\n    auto scaledT = translation * s;\n    auto scaledR = rotation * s;\n\n    float rx = s * scaledR[0];\n    float ry = s * scaledR[1];\n    float rz = s * scaledR[2];\n    float tx = s * scaledT[0];\n    float ty = s * scaledT[1];\n    float tz = s * scaledT[2];\n\n    float x1 = cos(rz) * (pi->x - tx) + sin(rz) * (pi->y - ty);\n    float y1 = -sin(rz) * (pi->x - tx) + cos(rz) * (pi->y - ty);\n    float z1 = (pi->z - tz);\n\n    float x2 = x1;\n    float y2 = cos(rx) * y1 + sin(rx) * z1;\n    float z2 = -sin(rx) * y1 + cos(rx) * z1;\n\n\n    po->x = cos(ry) * x2 - sin(ry) * z2;\n    po->y = y2;\n    po->z = sin(ry) * x2 + cos(ry) * z2;\n    po->intensity = pi->intensity;\n}\n\ntemplate<typename PointType>\nvoid LOAMSLAMCalculator<PointType>::_findPlanarAndEdgePoint(\n    const typename pcl::PointCloud<PointType>::ConstPtr input,\n    std::vector<int>& planarPointIndexes,\n    std::vector<int>& edgePointIndexes,\n    int maxEdgePoints, int maxPlanarPoints,\n    float threshold)\n{\n    const float MAXDISTANCE = 0.05;\n    std::vector<std::shared_ptr<std::vector<std::pair<int, Eigen::Vector3f>>>> pointsPerBeam;\n    for (auto i = 0; i < BEAMCOUNT_; ++i)\n    {\n        pointsPerBeam.push_back(std::shared_ptr<std::vector<std::pair<int, Eigen::Vector3f>>>(\n            new std::vector<std::pair<int, Eigen::Vector3f>>()));\n    }\n    for (auto i = 0; i < input->size(); ++i)\n    {\n        int beamIndex = _pointID(input->points[i]);\n        Eigen::Vector3f tmpPt(input->points[i].x, input->points[i].y, input->points[i].z);\n        pointsPerBeam[beamIndex]->push_back(std::pair<int, Eigen::Vector3f>(i, tmpPt));\n\n    }\n    std::vector<std::shared_ptr<std::vector<int>>> beamEdgesPoints;\n    std::vector<std::shared_ptr<std::vector<int>>> beamPlanarPoints;\n\n\n    auto f = [this, &threshold, &maxEdgePoints, &maxPlanarPoints, &MAXDISTANCE](\n        const std::vector<std::pair<int, Eigen::Vector3f>>& points,\n        std::shared_ptr<std::vector<int>> selectedEdgePoints,\n        std::shared_ptr<std::vector<int>> selectedPlanarPoints)\n    {\n        std::vector<float> cloudCurvature(points.size());\n        std::vector<int> cloudSortInd(points.size());\n        std::vector<int> cloudNeighborPicked(points.size());\n        std::vector<int> cloudLabel(points.size());\n        if (points.size() > 11)\n        {\n            for (int i = 5; i < points.size() - 6; i++)\n            {\n                float diffX =\n                    points.at(i - 5).second.x() + points.at(i - 4).second.x() + points.at(i - 3).second.x() +\n                    points.at(i - 2).second.x() + points.at(i - 1).second.x() - 10 * points.at(i).second.x() +\n                    points.at(i + 1).second.x() + points.at(i + 2).second.x() + points.at(i + 3).second.x() +\n                    points.at(i + 4).second.x() + points.at(i + 5).second.x();\n                float diffY =\n                    points.at(i - 5).second.y() + points.at(i - 4).second.y() + points.at(i - 3).second.y() +\n                    points.at(i - 2).second.y() + points.at(i - 1).second.y() - 10 * points.at(i).second.y() +\n                    points.at(i + 1).second.y() + points.at(i + 2).second.y() + points.at(i + 3).second.y() +\n                    points.at(i + 4).second.y() + points.at(i + 5).second.y();\n                float diffZ =\n                    points.at(i - 5).second.z() + points.at(i - 4).second.z() + points.at(i - 3).second.z() +\n                    points.at(i - 2).second.z() + points.at(i - 1).second.z() - 10 * points.at(i).second.z() +\n                    points.at(i + 1).second.z() + points.at(i + 2).second.z() + points.at(i + 3).second.z() +\n                    points.at(i + 4).second.z() + points.at(i + 5).second.z();\n                float c = diffX * diffX + diffY * diffY + diffZ * diffZ;\n                cloudCurvature[i] = c;\n                cloudSortInd[i] = i;\n                cloudNeighborPicked[i] = 0;\n                cloudLabel[i] = 0;\n            }\n\n            for (int i = 0; i < 6; ++i)\n            {\n                int startIndex = 5 + (points.size() - 10) * i / 6;\n                int endIndex = 5 + (points.size() - 10) * (i + 1) / 6 - 1;\n                std::sort(cloudSortInd.begin() + startIndex, cloudSortInd.begin() + endIndex + 1,\n                          [&cloudCurvature](int i, int j)\n                          {\n                              return cloudCurvature[i] < cloudCurvature[j];\n                          });\n                int largestPickedNum = 0;\n                for (int k = endIndex; k >= startIndex; k--)\n                {\n                    int ind = cloudSortInd[k];\n\n                    if (cloudNeighborPicked[ind] == 0 &&\n                        cloudCurvature[ind] > threshold)\n                    {\n\n                        largestPickedNum++;\n\n                        if (largestPickedNum <= maxEdgePoints)\n                        {\n                            cloudLabel[ind] = 1;\n                            selectedEdgePoints->push_back(points[ind].first);\n                        }\n                        else\n                        {\n                            break;\n                        }\n\n                        cloudNeighborPicked[ind] = 1;\n                        //not selecting close points\n                        for (int l = 1; l <= 5; l++)\n                        {\n                            float diffX = points.at(ind + l).second.x() - points.at(ind + l - 1).second.x();\n                            float diffY = points.at(ind + l).second.y() - points.at(ind + l - 1).second.y();\n                            float diffZ = points.at(ind + l).second.z() - points.at(ind + l - 1).second.z();\n                            if (diffX * diffX + diffY * diffY + diffZ * diffZ > MAXDISTANCE)\n                            {\n                                break;\n                            }\n\n                            cloudNeighborPicked[ind + l] = 1;\n                        }\n                        for (int l = -1; l >= -5; l--)\n                        {\n                            float diffX = points.at(ind + l).second.x() - points.at(ind + l + 1).second.x();\n                            float diffY = points.at(ind + l).second.y() - points.at(ind + l + 1).second.y();\n                            float diffZ = points.at(ind + l).second.z() - points.at(ind + l + 1).second.z();\n                            if (diffX * diffX + diffY * diffY + diffZ * diffZ > MAXDISTANCE)\n                            {\n                                break;\n                            }\n\n                            cloudNeighborPicked[ind + l] = 1;\n                        }\n                    }\n\n                }\n\n                int smallestPickedNum = 0;\n                for (int k = startIndex; k <= endIndex; k++)\n                {\n                    int ind = cloudSortInd[k];\n\n                    if (ind < 1)\n                    {\n                        continue;\n                    }\n\n                    if (cloudNeighborPicked[ind] == 0 &&\n                        cloudCurvature[ind] < threshold)\n                    {\n\n                        cloudLabel[ind] = -1;\n                        selectedPlanarPoints->push_back(points.at(ind).first);\n\n                        smallestPickedNum++;\n                        if (smallestPickedNum >= maxPlanarPoints)\n                        {\n                            break;\n                        }\n\n                        cloudNeighborPicked[ind] = 1;\n                        for (int l = 1; l <= 5; l++)\n                        {\n                            float diffX = points.at(ind + l).second.x() - points.at(ind + l - 1).second.x();\n                            float diffY = points.at(ind + l).second.y() - points.at(ind + l - 1).second.y();\n                            float diffZ = points.at(ind + l).second.z() - points.at(ind + l - 1).second.z();\n                            if (diffX * diffX + diffY * diffY + diffZ * diffZ > MAXDISTANCE)\n                            {\n                                break;\n                            }\n\n                            cloudNeighborPicked[ind + l] = 1;\n                        }\n                        for (int l = -1; l >= -5; l--)\n                        {\n                            float diffX = points.at(ind + l).second.x() - points.at(ind + l + 1).second.x();\n                            float diffY = points.at(ind + l).second.y() - points.at(ind + l + 1).second.y();\n                            float diffZ = points.at(ind + l).second.z() - points.at(ind + l + 1).second.z();\n                            if (diffX * diffX + diffY * diffY + diffZ * diffZ > MAXDISTANCE)\n                            {\n                                break;\n                            }\n\n                            cloudNeighborPicked[ind + l] = 1;\n                        }\n                    }\n                }\n            }\n        }\n        _barrier.wait();\n    };\n    int i = 0;\n    for (auto beamPoints : pointsPerBeam)\n    {\n        auto edgeTmp = std::shared_ptr<std::vector<int>>(new std::vector<int>);\n        beamEdgesPoints.push_back(edgeTmp);\n        auto planeTmp = std::shared_ptr<std::vector<int>>(new std::vector<int>);\n        beamPlanarPoints.push_back(planeTmp);\n        std::thread(f, *beamPoints, edgeTmp, planeTmp).detach();\n        ++i;\n    }\n    _barrier.wait();\n    for (auto edgePoints : beamEdgesPoints)\n    {\n        edgePointIndexes.insert(edgePointIndexes.end(), edgePoints->begin(), edgePoints->end());\n    }\n    for (auto planarPoints : beamPlanarPoints)\n    {\n        planarPointIndexes.insert(planarPointIndexes.end(), planarPoints->begin(), planarPoints->end());\n    }\n}\n\ntemplate<typename PointType>\nvoid LOAMSLAMCalculator<PointType>::_findCorrespondances(\n    const typename pcl::PointCloud<PointType>::ConstPtr previousCloud,\n    const typename pcl::PointCloud<PointType>::ConstPtr currentCloud,\n    const std::vector<int>& planarPointIndexes,\n    const std::vector<int>& edgePointIndexes,\n    Eigen::Vector3d& rotation,\n    Eigen::Vector3d& translation,\n    float threshold)\n{\n    Eigen::Vector3d tr = Eigen::Vector3d::Zero();\n    Eigen::Vector3d rt = Eigen::Vector3d::Zero();\n\n    typename pcl::KdTreeFLANN<PointType>::Ptr kdtreeCornerLast(new pcl::KdTreeFLANN<PointType>());\n    typename pcl::KdTreeFLANN<PointType>::Ptr kdtreeSurfLast(new pcl::KdTreeFLANN<PointType>());\n    kdtreeCornerLast->setInputCloud(previousCloud);\n    kdtreeSurfLast->setInputCloud(previousCloud);\n\n    int cornerPointsSharpNum = edgePointIndexes.size();\n    int surfPointsFlatNum = planarPointIndexes.size();\n\n    // neighbour edgePoint indices (J,K)\n    std::map<int, int> edgeJPointIndices;\n    std::map<int, int> edgeLPointIndices;\n\n    // neighbour planarPoint indices (J,K,L)\n    std::map<int, int> planarJPointIndices;\n    std::map<int, int> planarLPointIndices;\n    std::map<int, int> planarMPointIndices;\n\n\n    PointType coeff;\n    typename pcl::PointCloud<PointType>::Ptr coeffSel(new pcl::PointCloud<PointType>());\n    typename pcl::PointCloud<PointType>::Ptr laserCloudOri(new pcl::PointCloud<PointType>());\n\n    if (planarPointIndexes.size() > 100 && edgePointIndexes.size() > 10)\n    {\n        for (int iterationCount = 0; iterationCount < 25; ++iterationCount)\n        {\n            std::vector<int> pointSearchInd(1);\n            std::vector<float> pointSearchSqDis(1);\n\n            for (auto idx : planarPointIndexes)\n            {\n                PointType currentPt = currentCloud->points[idx];\n                _transformToStart(&currentCloud->points[idx], &currentPt, tr, rt);\n                if (iterationCount % 5 == 0)\n                {\n                    kdtreeSurfLast->nearestKSearch(currentPt, 1, pointSearchInd, pointSearchSqDis);\n                    int closestPointInd = -1, minPointInd2 = -1, minPointInd3 = -1;\n                    if (pointSearchSqDis[0] < threshold)\n                    {\n                        closestPointInd = pointSearchInd[0];\n                        int closestPointScan = _pointID(previousCloud->points[closestPointInd]);\n\n                        float pointSqDis, minPointSqDis2 = threshold, minPointSqDis3 = threshold;\n                        for (int j = closestPointInd + 1; j < surfPointsFlatNum; j++)\n                        {\n                            int currentPointID = _pointID(previousCloud->points[closestPointInd]);\n                            if (currentPointID > closestPointScan + NEARBY_SCAN_)\n                            {\n                                break;\n                            }\n                            pointSqDis = (previousCloud->points[j].x - currentPt.x) *\n                                         (previousCloud->points[j].x - currentPt.x) +\n                                         (previousCloud->points[j].y - currentPt.y) *\n                                         (previousCloud->points[j].y - currentPt.y) +\n                                         (previousCloud->points[j].z - currentPt.z) *\n                                         (previousCloud->points[j].z - currentPt.z);\n                            if (currentPointID <= closestPointScan && pointSqDis < minPointSqDis2)\n                            {\n                                minPointSqDis2 = pointSqDis;\n                                minPointInd2 = j;\n                            }\n                            else if (currentPointID > closestPointScan && pointSqDis < minPointSqDis3)\n                            {\n                                minPointSqDis3 = pointSqDis;\n                                minPointInd3 = j;\n                            }\n                        }\n                        for (int j = closestPointInd - 1; j >= 0; j--)\n                        {\n                            int currentPointID = _pointID(previousCloud->points[closestPointInd]);\n                            if (currentPointID < closestPointScan - NEARBY_SCAN_)\n                            {\n                                break;\n                            }\n                            pointSqDis = (previousCloud->points[j].x - currentPt.x) *\n                                         (previousCloud->points[j].x - currentPt.x) +\n                                         (previousCloud->points[j].y - currentPt.y) *\n                                         (previousCloud->points[j].y - currentPt.y) +\n                                         (previousCloud->points[j].z - currentPt.z) *\n                                         (previousCloud->points[j].z - currentPt.z);\n                            if (currentPointID >= closestPointScan && pointSqDis < minPointSqDis2)\n                            {\n                                minPointSqDis2 = pointSqDis;\n                                minPointInd2 = j;\n                            }\n                            else if (_pointID(previousCloud->points[j]) < closestPointScan &&\n                                     pointSqDis < minPointSqDis3)\n                            {\n                                minPointSqDis3 = pointSqDis;\n                                minPointInd3 = j;\n                            }\n                        }\n                    }\n\n                    planarJPointIndices[idx] = closestPointInd;\n                    planarLPointIndices[idx] = minPointInd2;\n                    planarMPointIndices[idx] = minPointInd3;\n                    pointSearchInd.clear();\n                    pointSearchSqDis.clear();\n                }\n\n                if (planarMPointIndices[idx] >= 0 && planarLPointIndices[idx] >= 0)\n                {\n                    Eigen::Vector3f J = previousCloud->points[planarJPointIndices[idx]].getVector3fMap();\n                    Eigen::Vector3f L = previousCloud->points[planarLPointIndices[idx]].getVector3fMap();\n                    Eigen::Vector3f M = previousCloud->points[planarMPointIndices[idx]].getVector3fMap();\n\n\n                    float pa = (L[1] - J[1]) * (M[2] - J[2])\n                               - (M[1] - J[1]) * (L[2] - L[2]);\n\n                    float pb = (L[2] - J[2]) * (M[0] - J[0])\n                               - (M[2] - J[2]) * (L[0] - J[0]);\n\n                    float pc = (L[0] - J[0]) * (M[1] - J[1])\n                               - (M[0] - J[0]) * (L[1] - J[1]);\n                    float pd = -(pa * J[0] + pb * J[1] + pc * J[2]);\n\n                    float ps = sqrt(pa * pa + pb * pb + pc * pc);\n\n                    pa /= ps;\n                    pb /= ps;\n                    pc /= ps;\n                    pd /= ps;\n\n                    float pd2 = pa * currentPt.x + pb * currentPt.y + pc * currentPt.z + pd;\n\n\n                    float s = 1;\n                    if (iterationCount >= 5)\n                    {\n                        s = 1 - 1.8 * fabs(pd2) / sqrt(sqrt(currentPt.x * currentPt.x\n                                                            + currentPt.y * currentPt.y +\n                                                            currentPt.z * currentPt.z));\n                    }\n\n                    coeff.x = s * pa;\n                    coeff.y = s * pb;\n                    coeff.z = s * pc;\n                    coeff.intensity = s * pd2;\n\n                    if (s > 0.1 && pd2 != 0)\n                    {\n\n                        laserCloudOri->push_back(currentCloud->points[idx]);\n                        coeffSel->push_back(coeff);\n                    }\n                }\n            }\n\n\n            for (auto idx : edgePointIndexes)\n            {\n                PointType currentPt = currentCloud->points[idx];\n                _transformToStart(&currentCloud->points[idx], &currentPt, tr, rt);\n                if (iterationCount % 5 == 0)\n                {\n                    kdtreeCornerLast->nearestKSearch(currentPt, 1, pointSearchInd, pointSearchSqDis);\n                    int closestPointInd = -1, minPointInd2 = -1;\n                    if (pointSearchSqDis[0] < threshold)\n                    {\n                        closestPointInd = pointSearchInd[0];\n                        int closestPointScan = _pointID(previousCloud->points[closestPointInd]);\n\n                        float pointSqDis, minPointSqDis2 = threshold;\n                        for (int j = closestPointInd + 1; j < cornerPointsSharpNum; j++)\n                        {\n                            int currentPointID = _pointID(previousCloud->points[j]);\n                            if (currentPointID > closestPointScan + NEARBY_SCAN_)\n                            {\n                                break;\n                            }\n\n                            if (currentPointID <= closestPointScan)\n                            {\n                                continue;\n                            }\n                            pointSqDis = (previousCloud->points[j].x - currentPt.x) *\n                                         (previousCloud->points[j].x - currentPt.x) +\n                                         (previousCloud->points[j].y - currentPt.y) *\n                                         (previousCloud->points[j].y - currentPt.y) +\n                                         (previousCloud->points[j].z - currentPt.z) *\n                                         (previousCloud->points[j].z - currentPt.z);\n\n                            if (pointSqDis < minPointSqDis2)\n                            {\n                                minPointSqDis2 = pointSqDis;\n                                minPointInd2 = j;\n                            }\n                        }\n\n                        for (int j = closestPointInd - 1; j >= 0; j--)\n                        {\n                            int currentPointID = _pointID(previousCloud->points[j]);\n                            if (currentPointID < closestPointScan - NEARBY_SCAN_)\n                            {\n                                break;\n                            }\n                            if (currentPointID >= closestPointScan)\n                            {\n                                continue;\n                            }\n\n                            pointSqDis = (previousCloud->points[j].x - currentPt.x) *\n                                         (previousCloud->points[j].x - currentPt.x) +\n                                         (previousCloud->points[j].y - currentPt.y) *\n                                         (previousCloud->points[j].y - currentPt.y) +\n                                         (previousCloud->points[j].z - currentPt.z) *\n                                         (previousCloud->points[j].z - currentPt.z);\n\n                            if (pointSqDis < minPointSqDis2)\n                            {\n                                minPointSqDis2 = pointSqDis;\n                                minPointInd2 = j;\n                            }\n                        }\n                    }\n                    /*********************************************/\n\n                    edgeJPointIndices[idx] = closestPointInd;\n                    edgeLPointIndices[idx] = minPointInd2;\n                    pointSearchInd.clear();\n                    pointSearchSqDis.clear();\n                }\n\n                if (edgeLPointIndices[idx] >= 0)\n                {\n                    Eigen::Vector3f I = currentPt.getVector3fMap();\n                    Eigen::Vector3f J = previousCloud->points[edgeJPointIndices[idx]].getVector3fMap();\n                    Eigen::Vector3f L = previousCloud->points[edgeLPointIndices[idx]].getVector3fMap();\n\n                    float num = (I - J).cross(I - L).norm();\n\n                    float deNum = (J - L).norm();\n\n\n                    float d = num / deNum;\n\n                    float la = ((J[1] - L[1]) * ((I[0] - J[0]) * (I[1] - L[1]) - (I[0] - L[0]) * (I[1] - J[1]))\n                                + (J[2] - L[2]) * ((I[0] - J[0]) * (I[2] - L[2]) - (I[0] - L[0]) * (I[2] - J[2]))) /\n                               num / deNum;\n\n                    float lb = -((J[0] - L[0]) * ((I[0] - J[0]) * (I[1] - L[1]) - (I[0] - L[0]) * (I[1] - J[1]))\n                                 -\n                                 (J[2] - L[2]) * ((I[1] - J[1]) * (I[2] - L[2]) - (I[1] - L[1]) * (I[2] - J[2]))) /\n                               num / deNum;\n\n                    float lc = -((J[0] - L[0]) * ((I[0] - J[0]) * (I[2] - L[2]) - (I[0] - L[0]) * (I[2] - J[2]))\n                                 +\n                                 (J[1] - L[1]) * ((I[1] - J[1]) * (I[2] - L[2]) - (I[1] - L[1]) * (I[2] - J[2]))) /\n                               num / deNum;\n\n                    float s = 1;\n                    if (iterationCount >= 5)\n                    {\n                        s = 1 - 1.8 * fabs(d);\n                    }\n\n                    coeff.x = s * la;\n                    coeff.y = s * lb;\n                    coeff.z = s * lc;\n                    coeff.intensity = s * d;\n\n                    if (s > 0.1 && d != 0)\n                    {\n                        laserCloudOri->push_back(currentCloud->points[idx]);\n                        coeffSel->push_back(coeff);\n                    }\n                }\n            }\n            int pointSelNum = laserCloudOri->points.size();\n\n            if (pointSelNum < 10)\n            {\n                continue;\n            }\n            Eigen::MatrixXf matA = Eigen::MatrixXf::Zero(pointSelNum, 6);\n            Eigen::MatrixXf matAt = Eigen::MatrixXf::Zero(6, pointSelNum);\n            Eigen::MatrixXf matAtA = Eigen::MatrixXf::Zero(6, 6);\n            Eigen::VectorXf matB = Eigen::VectorXf::Zero(pointSelNum);\n            Eigen::VectorXf matAtB = Eigen::VectorXf::Zero(6);\n            Eigen::VectorXf matX = Eigen::VectorXf::Zero(6);\n\n            Eigen::MatrixXf matP = Eigen::MatrixXf::Zero(6, 6);\n            bool isDegenerate = false;\n\n            for (int i = 0; i < pointSelNum; i++)\n            {\n                PointType pointOri = laserCloudOri->points[i];\n                coeff = coeffSel->points[i];\n\n                float s = 1;\n\n                float srx = sin(s * rt[0]);\n                float crx = cos(s * rt[0]);\n                float sry = sin(s * rt[1]);\n                float cry = cos(s * rt[1]);\n                float srz = sin(s * rt[2]);\n                float crz = cos(s * rt[2]);\n                float tx = s * tr[0];\n                float ty = s * tr[1];\n                float tz = s * tr[2];\n\n                float arx = (-s * crx * sry * srz * pointOri.x + s * crx * crz * sry * pointOri.y +\n                             s * srx * sry * pointOri.z\n                             + s * tx * crx * sry * srz - s * ty * crx * crz * sry - s * tz * srx * sry) * coeff.x\n                            + (s * srx * srz * pointOri.x - s * crz * srx * pointOri.y + s * crx * pointOri.z\n                               + s * ty * crz * srx - s * tz * crx - s * tx * srx * srz) * coeff.y\n                            + (s * crx * cry * srz * pointOri.x - s * crx * cry * crz * pointOri.y -\n                               s * cry * srx * pointOri.z\n                               + s * tz * cry * srx + s * ty * crx * cry * crz - s * tx * crx * cry * srz) *\n                              coeff.z;\n\n                float ary = ((-s * crz * sry - s * cry * srx * srz) * pointOri.x\n                             + (s * cry * crz * srx - s * sry * srz) * pointOri.y - s * crx * cry * pointOri.z\n                             + tx * (s * crz * sry + s * cry * srx * srz) +\n                             ty * (s * sry * srz - s * cry * crz * srx)\n                             + s * tz * crx * cry) * coeff.x\n                            + ((s * cry * crz - s * srx * sry * srz) * pointOri.x\n                               + (s * cry * srz + s * crz * srx * sry) * pointOri.y - s * crx * sry * pointOri.z\n                               + s * tz * crx * sry - ty * (s * cry * srz + s * crz * srx * sry)\n                               - tx * (s * cry * crz - s * srx * sry * srz)) * coeff.z;\n\n                float arz = ((-s * cry * srz - s * crz * srx * sry) * pointOri.x +\n                             (s * cry * crz - s * srx * sry * srz) * pointOri.y\n                             + tx * (s * cry * srz + s * crz * srx * sry) -\n                             ty * (s * cry * crz - s * srx * sry * srz)) * coeff.x\n                            + (-s * crx * crz * pointOri.x - s * crx * srz * pointOri.y\n                               + s * ty * crx * srz + s * tx * crx * crz) * coeff.y\n                            + ((s * cry * crz * srx - s * sry * srz) * pointOri.x +\n                               (s * crz * sry + s * cry * srx * srz) * pointOri.y\n                               + tx * (s * sry * srz - s * cry * crz * srx) -\n                               ty * (s * crz * sry + s * cry * srx * srz)) * coeff.z;\n\n                float atx = -s * (cry * crz - srx * sry * srz) * coeff.x + s * crx * srz * coeff.y\n                            - s * (crz * sry + cry * srx * srz) * coeff.z;\n\n                float aty = -s * (cry * srz + crz * srx * sry) * coeff.x - s * crx * crz * coeff.y\n                            - s * (sry * srz - cry * crz * srx) * coeff.z;\n\n                float atz = s * crx * sry * coeff.x - s * srx * coeff.y - s * crx * cry * coeff.z;\n\n                float d2 = coeff.intensity;\n\n                matA(i, 0) = arx;\n                matA(i, 1) = ary;\n                matA(i, 2) = arz;\n                matA(i, 3) = atx;\n                matA(i, 4) = aty;\n                matA(i, 5) = atz;\n                matB(i) = -0.05 * d2;\n            }\n            matAt = matA.transpose();\n\n            matAtA = matAt * matA;\n            matAtB = matAt * matB;\n            matX = matAtA.householderQr().solve(matAtB);\n\n            if (iterationCount == 0)\n            {\n\n                Eigen::VectorXf matE = Eigen::VectorXf::Zero(6);\n                Eigen::MatrixXf matV = Eigen::MatrixXf::Zero(6, 6);\n                Eigen::MatrixXf matV2 = Eigen::MatrixXf::Zero(6, 6);\n\n                Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> solver(matAtA);\n                matV = solver.eigenvectors();\n                matE = solver.eigenvalues();\n                matV2 = matV;\n\n                isDegenerate = false;\n                float eignThre[6] = {10, 10, 10, 10, 10, 10};\n                for (int i = 5; i >= 0; i--)\n                {\n                    if (matE.transpose()(i) < eignThre[i])\n                    {\n                        for (int j = 0; j < 6; j++)\n                        {\n                            matV2(i, j) = 0;\n                        }\n                        isDegenerate = true;\n                    }\n                    else\n                    {\n                        break;\n                    }\n                }\n\n                matP = matV.inverse() * matV2;\n            }\n\n            if (isDegenerate)\n            {\n                Eigen::VectorXf matX2(matX);\n                matX = matP * matX2;\n            }\n\n            rt[0] += matX[0];\n            rt[1] += matX[1];\n            rt[2] += matX[2];\n            tr[0] += matX[3];\n            tr[1] += matX[4];\n            tr[2] += matX[5];\n\n            for (int i = 0; i < 3; i++)\n            {\n                if (isnan(tr[i]))\n                    tr[i] = 0;\n                if (isnan(rt[i]))\n                    rt[i] = 0;\n            }\n\n            float deltaR = sqrt(\n                pow((matX[0] / M_PI * 180.0), 2) +\n                pow((matX[1] / M_PI * 180.0), 2) +\n                pow((matX[2] / M_PI * 180.0), 2));\n            float deltaT = sqrt(\n                pow(matX[3] * 100, 2) +\n                pow(matX[4] * 100, 2) +\n                pow(matX[5] * 100, 2));\n\n            //  std::cout << \"delta R: \" << deltaR << \" delta T: \" << deltaT << std::endl;\n\n            if (deltaR < 0.1 && deltaT < 0.1)\n            {\n                break;\n            }\n        }\n    }\n    else\n    {\n        std::cerr << \"Not enough features.\" << std::endl;\n    }\n\n    rotation = rt;\n    translation = tr;\n}\n\n} // compute\n} // olp\n\n#endif //OLP_LOAMSLAMCALCULATOR_HPP\n", "meta": {"hexsha": "cee0ec9d55bccf47e40cb2d4f2cb67dc77f71b30", "size": 35730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "compute/calculators/LOAMSLAMCalculator.hpp", "max_stars_repo_name": "mcserep/olp", "max_stars_repo_head_hexsha": "8d195f0ec858acc265eb24a447fc6408142a063c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-17T06:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T06:24:15.000Z", "max_issues_repo_path": "compute/calculators/LOAMSLAMCalculator.hpp", "max_issues_repo_name": "mcserep/olp", "max_issues_repo_head_hexsha": "8d195f0ec858acc265eb24a447fc6408142a063c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "compute/calculators/LOAMSLAMCalculator.hpp", "max_forks_repo_name": "mcserep/olp", "max_forks_repo_head_hexsha": "8d195f0ec858acc265eb24a447fc6408142a063c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-28T20:12:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T20:12:48.000Z", "avg_line_length": 41.5948777648, "max_line_length": 116, "alphanum_fraction": 0.4352644836, "num_tokens": 8712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4273789252203165}}
{"text": "#include <iostream>\n#include <vector>\n\n//#define NUMBER_DOUBLE 1\n#define NUMBER_DOUBLE_DOUBLE 1\n\n#include \"Nbodies/summation.h\"\n#include \"Integration/methods.h\"\n#include \"Writer/writer.h\"\n#include \"Nbodies/energy.h\"\n\n\n#include <boost/multiprecision/float128.hpp>\n\n\n#ifdef NUMBER_DOUBLE_DOUBLE\n#include <qd/dd_real.h>\n#include <qd/fpu.h>\n#endif\n\n#include <string>\n\nusing namespace std;\nusing namespace boost::multiprecision;\n\n\n#include <chrono>\nint main() {\n\n#ifdef NUMBER_DOUBLE_DOUBLE\n    unsigned int oldcw;\n    fpu_fix_start(&oldcw);\n#endif\n\n    using current_type = dd_real;\n\n\n\n    std::vector<Body<current_type>> bodies;\n\n    //make_universe(bodies, 40, current_type(0.0), current_type(0.0), current_type(0.0));\n/*\n    bodies.push_back(Body<current_type>({current_type(0),current_type(0),current_type(0)},{current_type(0),current_type(0),current_type(0)},current_type(2e14)));\n    bodies.push_back(Body<current_type>({ current_type(0), current_type(1.4e3), current_type(0) },{ current_type(3),current_type(0),current_type(0) },current_type(6)));\n    bodies.push_back(Body<current_type>({ current_type(0), current_type(1.3e3), current_type(0) },{ current_type(3),current_type(0),current_type(0) },current_type(6)));\n    bodies.push_back(Body<current_type>({ current_type(0), current_type(1.2e3), current_type(0) },{ current_type(3),current_type(0),current_type(0) },current_type(6)));\n    bodies.push_back(Body<current_type>({ current_type(0), current_type(1.1e3), current_type(0) },{ current_type(3),current_type(0),current_type(0) },current_type(6)));\n    bodies.push_back(Body<current_type>({ current_type(0), current_type(1.56e3), current_type(0) },{ current_type(3),current_type(0),current_type(0) },current_type(6)));\n    bodies.push_back(Body<current_type>({ current_type(0), current_type(1.5e3), current_type(0) },{ current_type(3),current_type(0),current_type(0) },current_type(6)));\n    bodies.push_back(Body<current_type>({ current_type(0), current_type(1.51e3), current_type(0) },{ current_type(3),current_type(0),current_type(0) },current_type(6)));\n*/\n\n\n    current_type a(\"0\");\n    current_type b(\"3\");\n    current_type c(\"6\");\n    current_type mm(\"2e14\");\n    current_type diss(\"1.3e3\");\n\n    bodies.push_back(Body<current_type>({a,a,a},{a,a,a},mm));\n    bodies.push_back(Body<current_type>({ current_type(\"0\"), current_type(\"1.3e3\"), current_type(\"0\") },{ current_type(\"3\"),current_type(\"0\"),current_type(\"0\") },current_type(\"6\")));\n    bodies.push_back(Body<current_type>({ current_type(\"0\"), current_type(\"1.2e3\"), current_type(\"0\") },{ current_type(\"3\"),current_type(\"0\"),current_type(\"0\") },current_type(\"6\")));\n    bodies.push_back(Body<current_type>({ current_type(\"0\"), current_type(\"1.1e3\"), current_type(\"0\") },{ current_type(\"3\"),current_type(\"0\"),current_type(\"0\") },current_type(\"6\")));\n    bodies.push_back(Body<current_type>({ current_type(\"0\"), current_type(\"1.56e3\"), current_type(\"0\") },{ current_type(\"3\"),current_type(\"0\"),current_type(\"0\") },current_type(\"6\")));\n    bodies.push_back(Body<current_type>({ current_type(\"0\"), current_type(\"1.5e3\"), current_type(\"0\") },{ current_type(\"3\"),current_type(\"0\"),current_type(\"0\") },current_type(\"6\")));\n    bodies.push_back(Body<current_type>({ current_type(\"0\"), current_type(\"1.51e3\"), current_type(\"0\") },{ current_type(\"3\"),current_type(\"0\"),current_type(\"0\") },current_type(\"6\")));\n    bodies.push_back(Body<current_type>({ current_type(\"0\"), current_type(\"1.4e3\"), current_type(\"0\") },{ current_type(\"3\"),current_type(\"0\"),current_type(\"0\") },current_type(\"6\")));\n\n\n    current_type init_energy = summation<current_type, kinetic_energy_proxy<current_type>>(kinetic_energy_proxy(bodies), bodies.size()) / current_type(2) +\n                         summation<current_type, potential_energy_proxy<current_type>>(potential_energy_proxy(bodies), bodies.size() * bodies.size()) / current_type(2) ;\n\n    vec<current_type> init_impulse_moment = summation<vec<current_type>, impulse_moment_proxy<vec<current_type>,current_type>>(impulse_moment_proxy<vec<current_type>,current_type>(bodies), bodies.size());\n\n    current_type total_mass = summation<current_type, total_mass_proxy<current_type>>(total_mass_proxy<current_type>(bodies), bodies.size());\n    vec<current_type> init_center_mass = summation<vec<current_type>, mass_center_proxy<vec<current_type>, current_type>>(mass_center_proxy<vec<current_type>, current_type>(bodies), bodies.size());\n    init_center_mass = init_center_mass / total_mass;\n    vec<current_type> init_vel_mass = summation<vec<current_type>, mass_vel_proxy<vec<current_type>, current_type>>(mass_vel_proxy<vec<current_type>, current_type>(bodies), bodies.size());\n    init_vel_mass = init_vel_mass / total_mass;\n\n    for( int i = 0; i < bodies.size(); i++){\n       // bodies[i].r -= init_center_mass;\n       // bodies[i].v -= init_vel_mass;\n    }\n\n\n    json data_energy, data_impulse_moment, data_center, data_bodies;\n    current_type h(\"0.1\");\n    int iterations = 100000;\n\n    std::vector<current_type> coefs = initDDCoef<current_type>();\n    auto start = std::chrono::high_resolution_clock::now();\n\n    for (int i = 0; i < iterations; i++) {\n         dormanPrince8(bodies, h, coefs);\n         //RungeKutta4(bodies, h);\n        if(true ) {\n            for(int j = 0; j < bodies.size(); j++){\n\n\n#ifdef NUMBER_DOUBLE_DOUBLE\n                    data_bodies[j][\"X\"][i] = bodies[j].r.X._hi();\n                    data_bodies[j][\"Y\"][i] = bodies[j].r.Y._hi();\n                    data_bodies[j][\"Z\"][i] = bodies[j].r.Z._hi();\n#endif\n#ifdef NUMBER_DOUBLE\n\n              data_bodies[j][\"X\"][i] = bodies[j].r.X;\n              data_bodies[j][\"Y\"][i] = bodies[j].r.Y;\n              data_bodies[j][\"Z\"][i] = bodies[j].r.Z;\n                    /*\n                    data_bodies[j][\"X\"][i] = bodies[j].r.X.str(32);\n                    data_bodies[j][\"Y\"][i] = bodies[j].r.Y.str(32);\n                    data_bodies[j][\"Z\"][i] = bodies[j].r.Z.str(32);\n                     */\n#endif\n            }\n\n            vec<current_type> center_mass = summation<vec<current_type>, mass_center_proxy<vec<current_type>, current_type>>(mass_center_proxy<vec<current_type>, current_type>(bodies), bodies.size());\n            center_mass = center_mass / total_mass;\n\n            current_type energy = summation<current_type, kinetic_energy_proxy<current_type>>(kinetic_energy_proxy(bodies), bodies.size()) / current_type(2) +\n                            summation<current_type, potential_energy_proxy<current_type>>(potential_energy_proxy(bodies),bodies.size() * bodies.size()) / current_type(2);\n\n            vec<current_type> impulse_moment = summation<vec<current_type>, impulse_moment_proxy<vec<current_type>,current_type>>(impulse_moment_proxy<vec<current_type>,current_type>(bodies), bodies.size());\n\n            data_energy[\"n\"].push_back(i);\n#ifdef NUMBER_DOUBLE_DOUBLE\n            data_energy[\"energy\"].push_back((abs((energy - init_energy)/init_energy)).to_string());\n#endif\n#ifdef NUMBER_DOUBLE\n            //data_energy[\"energy\"].push_back(abs((energy - init_energy)/init_energy).str(32));\n          data_energy[\"energy\"].push_back(abs((energy - init_energy)/init_energy));\n#endif\n\n            data_impulse_moment[\"n\"].push_back(i);\n#ifdef NUMBER_DOUBLE_DOUBLE\n            data_impulse_moment[\"moment\"].push_back(abs((impulse_moment - init_impulse_moment).Len() / init_impulse_moment.Len()).to_string());\n#endif\n#ifdef NUMBER_DOUBLE\n            //data_impulse_moment[\"moment\"].push_back(abs((impulse_moment - init_impulse_moment).Len() / init_impulse_moment.Len()).str(32));\n          data_impulse_moment[\"moment\"].push_back(abs((impulse_moment - init_impulse_moment).Len() / init_impulse_moment.Len()));\n#endif\n\n\n                data_center[\"n\"].push_back(i);\n#ifdef NUMBER_DOUBLE_DOUBLE\n                data_center[\"center\"].push_back(abs((init_center_mass - center_mass).Len()).to_string());\n#endif\n#ifdef NUMBER_DOUBLE\n                //data_center[\"center\"].push_back(abs((init_center_mass - center_mass).Len()).str(32));\n                data_center[\"center\"].push_back(abs((init_center_mass - center_mass).Len()));\n#endif\n\n\n\n        }\n    }\n    auto stop = std::chrono::high_resolution_clock::now();\n    auto duration = duration_cast<std::chrono::microseconds>(stop - start);\n    printf(\"time: %lld microseconds \\n\", duration.count());\n\n\n    writer<current_type> w;\n    w.writeRes(\"../log.json\", data_energy);\n    w.writeRes(\"../bodies.json\", data_bodies);\n    w.writeRes(\"../moment.json\", data_impulse_moment);\n    w.writeRes(\"../center.json\", data_center);\n\n#ifdef NUMBER_DOUBLE_DOUBLE\n    fpu_fix_end(&oldcw);\n#endif\n    return 0;\n}\n", "meta": {"hexsha": "4801906b4af1cd7dd4983dbf8f6bafc6d09d803b", "size": 8635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dd_NBodies/main.cpp", "max_stars_repo_name": "S1ckick/dd_landau", "max_stars_repo_head_hexsha": "9cf39225e074ebb99f37a605e9840cb3965a08ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dd_NBodies/main.cpp", "max_issues_repo_name": "S1ckick/dd_landau", "max_issues_repo_head_hexsha": "9cf39225e074ebb99f37a605e9840cb3965a08ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dd_NBodies/main.cpp", "max_forks_repo_name": "S1ckick/dd_landau", "max_forks_repo_head_hexsha": "9cf39225e074ebb99f37a605e9840cb3965a08ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.3428571429, "max_line_length": 207, "alphanum_fraction": 0.6809496236, "num_tokens": 2255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.42737892039250014}}
{"text": "/**\n * Copyright (C) 2016, Wu Tao. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include <string>\n#include <boost/functional/hash.hpp>\n#include \"FilterStrategy.h\"\n#include \"Slice.h\"\n\nnamespace lessdb {\n\nclass BloomFilterStrategy : public FilterStrategy {\n  //\n  // m: the total number of bits our bloom filter has.\n  // n: the number of elements.\n  // k: the number of hash functions.\n  // For a given m and n, the value of k that minimizes the false positive\n  // probability is ln2*(m/n).\n  //\n  // Use double-hashing to generate a sequence of hash values.\n  // See analysis in [Kirsch,Mitzenmacher 2006].\n  // The double-hashing functions is of the form gi(x) = h1(x) + i*h2(x).\n  //\n\n  const size_t kMinBloomFilterLength = 64;\n\n public:\n  BloomFilterStrategy(size_t bits_per_key) : bits_per_byte_(bits_per_key) {\n    k_ = static_cast<size_t>(bits_per_key * 0.69);  // ln2 ~= 0.69\n  }\n\n  inline void Put(const Slice &key, Slice &bits) override {\n    size_t h1 = boost::hash_range(key.RawData(), key.RawData() + key.Len());\n    size_t h2 = (h1 >> 17) | (h1 << 15);  // Rotate right 17 bits\n    for (size_t i = 0; i < k_; ++i) {\n      size_t g = (h1 + i * h2) % bits.Len();\n      bits[g / 8] |= (1 << (g % 8));\n    }\n  }\n\n  inline bool MightContain(const Slice &key, const Slice &bits) const override {\n    size_t h1 = boost::hash_range(key.RawData(), key.RawData() + key.Len());\n    size_t h2 = (h1 >> 17) | (h1 << 15);  // Rotate right 17 bits\n    for (size_t i = 0; i < k_; ++i) {\n      size_t g = (h1 + i * h2) % bits.Len();\n      if (!(bits[g / 8] & (1 << (g % 8))))\n        return false;\n    }\n    return true;\n  }\n\n private:\n  size_t bits_per_byte_;\n  size_t k_;\n};\n\nFilterStrategy *FilterStrategy::Default(size_t bits_per_bytes) {\n  return new BloomFilterStrategy(bits_per_bytes);\n}\n\n}  // namespace lessdb\n", "meta": {"hexsha": "76d4fc02be19b99005a745d0087fc256221003a8", "size": 2872, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/FilterStrategy.cc", "max_stars_repo_name": "neverchanje/lessdb", "max_stars_repo_head_hexsha": "187e8c7d9453bb048a6053a5d5610906b1586754", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2016-02-24T05:30:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-01T14:25:10.000Z", "max_issues_repo_path": "src/FilterStrategy.cc", "max_issues_repo_name": "neverchanje/lessdb", "max_issues_repo_head_hexsha": "187e8c7d9453bb048a6053a5d5610906b1586754", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/FilterStrategy.cc", "max_forks_repo_name": "neverchanje/lessdb", "max_forks_repo_head_hexsha": "187e8c7d9453bb048a6053a5d5610906b1586754", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-05-08T06:53:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-30T14:59:02.000Z", "avg_line_length": 35.9, "max_line_length": 80, "alphanum_fraction": 0.6786211699, "num_tokens": 771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.42737593546651276}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation>\n// Copyright (c) 2020-2021 Ilias Khairullin <ilias@nil.foundation>\n// Copyright (c) 2022 Ekaterina Chukavina <kate@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_ZK_COMMITMENTS_KZG_HPP\n#define CRYPTO3_ZK_COMMITMENTS_KZG_HPP\n\n#include <tuple>\n#include <vector>\n#include <type_traits>\n\n#include <boost/assert.hpp>\n#include <boost/iterator/zip_iterator.hpp>\n#include <boost/accumulators/accumulators.hpp>\n\n#include <nil/crypto3/math/polynomial/polynomial.hpp>\n#include <nil/crypto3/algebra/type_traits.hpp>\n#include <nil/crypto3/algebra/algorithms/pair.hpp>\n#include <nil/crypto3/algebra/pairing/pairing_policy.hpp>\n\nusing namespace nil::crypto3::math;\n\n#include <nil/crypto3/math/polynomial/polynomial.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace zk {\n            namespace commitments {\n                template<typename CurveType>\n                struct kzg {\n\n                    typedef CurveType curve_type;\n                    typedef algebra::pairing::pairing_policy<curve_type> pairing;\n                    typedef typename curve_type::gt_type::value_type gt_value_type;\n\n                    using base_field_value_type = typename curve_type::base_field_type::value_type;\n                    using commitment_key_type = std::vector<typename curve_type::template g1_type<>::value_type>;\n                    using verification_key_type = typename curve_type::template g2_type<>::value_type;\n                    using commitment_type = typename curve_type::template g1_type<>::value_type;\n                    using proof_type = commitment_type;\n\n                    struct params_type {\n                        std::size_t a;\n                    };\n\n                    static std::pair<commitment_key_type, verification_key_type> setup(const std::size_t n,\n                                                                                       params_type params) {\n\n                        size_t a_scaled = params.a;\n                        commitment_key_type commitment_key = {curve_type::template g1_type<>::value_type::one()};\n                        verification_key_type verification_key =\n                            curve_type::template g2_type<>::value_type::one() * params.a;\n\n                        for (std::size_t i = 0; i < n; i++) {\n                            commitment_key.emplace_back(a_scaled * (curve_type::template g1_type<>::value_type::one()));\n                            a_scaled = a_scaled * params.a;\n                        }\n\n                        return std::make_pair(commitment_key, verification_key);\n                    }\n\n                    static commitment_type commit(const commitment_key_type &commitment_key,\n                                                  const polynomial<base_field_value_type> &f) {\n\n                        commitment_type commitment = f[0] * commitment_key[0];\n\n                        for (std::size_t i = 0; i < f.size(); i++) {\n                            commitment = commitment + commitment_key[i] * f[i];\n                        }\n\n                        return commitment;\n                    }\n\n                    static proof_type proof_eval(commitment_key_type commitment_key,\n                                                 typename curve_type::base_field_type::value_type x,\n                                                 typename curve_type::base_field_type::value_type y,\n                                                 const polynomial<base_field_value_type> &f) {\n\n                        const polynomial<base_field_value_type> denominator_polynom = {-x, 1};\n\n                        const polynomial<base_field_value_type> q =\n                            (f + polynomial<base_field_value_type> {-y}) / denominator_polynom;\n\n                        proof_type p = kzg_commitment::commit(commitment_key, q);\n                        return p;\n                    }\n\n                    static bool verify_eval(verification_key_type verification_key,\n                                            commitment_type C_f,\n                                            base_field_value_type x,\n                                            base_field_value_type y,\n                                            proof_type p) {\n\n                        typename curve_type::gt_type::value_type gt1 =\n                            algebra::pair<curve_type>(C_f - curve_type::template g1_type<>::value_type::one() * y,\n                                                      curve_type::template g2_type<>::value_type::one());\n\n                        typename curve_type::gt_type::value_type gt2 = algebra::pair<curve_type>(\n                            p, verification_key - curve_type::template g2_type<>::value_type::one() * x);\n\n                        return gt1 == gt2;\n                    }\n                };\n            };    // namespace commitments \n        }         // namespace zk\n    }             // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_ZK_COMMITMENTS_KZG_HPP\n", "meta": {"hexsha": "e8102002b3cf199d6d20961a3aa05da6bed31172", "size": 6365, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/zk/commitments/polynomial/kzg.hpp", "max_stars_repo_name": "NilFoundation/zk", "max_stars_repo_head_hexsha": "60c63ba8e719620e9fe68d68621c84afded2a809", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nil/crypto3/zk/commitments/polynomial/kzg.hpp", "max_issues_repo_name": "NilFoundation/zk", "max_issues_repo_head_hexsha": "60c63ba8e719620e9fe68d68621c84afded2a809", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/nil/crypto3/zk/commitments/polynomial/kzg.hpp", "max_forks_repo_name": "NilFoundation/zk", "max_forks_repo_head_hexsha": "60c63ba8e719620e9fe68d68621c84afded2a809", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.8571428571, "max_line_length": 120, "alphanum_fraction": 0.5599371563, "num_tokens": 1180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4272958750643992}}
{"text": "#pragma once\n\n#include <Eigen/Dense>\n#include <vector>\n\n// quadrature rules\n#include \"quadrature/qhermite.hpp\"\n#include \"quadrature/qmaxwell.hpp\"\n#include \"spectral/lagrange_polynomial.hpp\"\n\n\nnamespace boltzmann {\nnamespace impl {\n\n/**\n * @brief stores integrals over Lagrange polynomials\n *        on the Hermite Quadrature nodes\n */\nclass outflow_helper\n{\n private:\n  typedef Eigen::VectorXd vec_t;\n\n public:\n  outflow_helper(int K);\n\n  /**\n   *\n   *\n   * @param hw  Hermite weights\n   * @param hx  Hermite nodes\n   *\n   * Note: both weights and nodes are wrt weight \\f$ e^{-x^2} \\f$\n   */\n  outflow_helper(const vec_t& hw, const vec_t& hx);\n\n  /**\n   * @brief returns \\f$ \\int_{\\mathbb{R}^+} y l_i(y) e^{-y^2/2} dy\\f$\n   *\n   * @param i the i-th lagrange polynomial\n   *\n   * @return\n   */\n  inline double get_y(unsigned int i) const\n  {\n    assert(i < ly_.size());\n    return ly_[i];\n  }\n\n  /**\n   * @brief returns \\f$ \\int_{\\mathbb{R}} l_i(x) e^{-x^2/2} dx\\f$\n   *\n   * @param i\n   *\n   * @return\n   */\n  inline double get_x(unsigned int i) const\n  {\n    assert(i < lx_.size());\n    return lx_[i];\n  }\n\n  inline const vec_t& lx() const { return lx_; }\n\n  inline const vec_t& ly() const { return ly_; }\n\n  template <typename DERIVED>\n  inline double compute(const Eigen::DenseBase<DERIVED>& src) const;\n\n private:\n  vec_t ly_;\n  vec_t lx_;\n};\n\ntemplate <typename DERIVED>\ninline double\noutflow_helper::compute(const Eigen::DenseBase<DERIVED>& src) const\n{\n  assert(src.rows() == ly_.size());\n  assert(src.cols() == lx_.size());\n\n  int K = ly_.size();\n\n  // compute outflow\n  double rho_p = 0;\n  for (int i = 0; i < K; ++i) {\n    for (int j = 0; j < K; ++j) {\n      rho_p += src(i, j) * get_x(j) * get_y(i);\n    }\n  }\n  return rho_p;\n}\n\n}  // end namespace impl\n}  // end namespace boltzmann\n", "meta": {"hexsha": "ff49976f8d19dc50e81c1dee4ee455f361b4b71c", "size": 1795, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/matrix/bc/impl/outflow_helper.hpp", "max_stars_repo_name": "simonpp/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/matrix/bc/impl/outflow_helper.hpp", "max_issues_repo_name": "simonpp/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/matrix/bc/impl/outflow_helper.hpp", "max_forks_repo_name": "simonpp/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.6979166667, "max_line_length": 69, "alphanum_fraction": 0.6122562674, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4272958750643992}}
{"text": "#include \"SLIC.hpp\"\n\n#include <iostream>\n#include <string>\n#include <filesystem>\n#include <chrono>\n#include <cmath>\n#include <boost/filesystem/convenience.hpp>\n\nSlic::Slic(std::string filename){\n  if_path = filename;\n  std::cout << \"Loading \" << filename << \" pixel data...\" << std::endl;\n  if(!image.loadFromFile(filename)){\n    std::cout << \"Problem loading filename: \" << filename << std::endl;\n    ready = false;\n  }\n  greyscale = false;\n  ready = true;\n  height = image.getSize().y;\n  width = image.getSize().x;\n  total_pixels = height * width;\n  num_cuts = 0;\n  std::cout << \"Loaded \" << width << \"x\" << height << \" file \" << filename << std::endl\n    << \"Total pixels: \" << total_pixels << std::endl;\n}\n\nSlic::~Slic(){\n\n}\n\n//O(1) constant\ndouble Slic::getColorDistance(HSV c1, HSV c2){\n  //Remember, these are coming in as\n  // Hue 0-360\n  // Saturation 0-100\n  // Value 0 - 100\n  double h1 = c1.hue * deg_to_rad;\n  double h2 = c2.hue * deg_to_rad;\n  double s1 = c1.saturation/100.0;\n  double s2 = c2.saturation/100.0;\n  double v1 = c1.value / 100.0;\n  double v2 = c2.value / 100.0;\n\n  //We're going to project the color value into the HSV color space and then measure the distance.\n  double p1 = std::pow(std::sin(h1)*s1*v1 - std::sin(h2)*s2*v2,2);\n  double p2 = std::pow(std::cos(h1)*s1*v1 - std::cos(h2)*s2*v2,2);\n  double p3 = std::pow(v1 - v2,2);\n  double dist2 = p1 + p2 + p3; //Our distance squared.\n  return sqrt(dist2);\n}\n\n//O(1) constant\nHSV Slic::rgb2hsv(RGBA rgb){\n\tfloat MAX = std::max(std::max(rgb.r,rgb.g), rgb.b);\n\tfloat MIN = std::min(std::min(rgb.r,rgb.g), rgb.b);\n\tfloat hue=0;\n\n  float eps = 0.00001;\n\tif(std::abs(MAX-MIN)<eps){\n\t\thue = 0;\n  }\n\telse if(std::abs(MAX-rgb.r)<eps){\n\t\thue = 60*((rgb.g - rgb.b)/(MAX-MIN));\n  }\n\telse if(std::abs(MAX-rgb.g)<eps){\n\t\thue = 60*(2 + (rgb.b - rgb.r)/(MAX-MIN));\n  }\n\telse if(std::abs(MAX-rgb.b)<eps){\n\t\thue = 60*(4 + (rgb.r - rgb.g)/(MAX-MIN));\n  }\n\tif(hue < 0)\n\t\thue+=360;\n\tint saturation = 0;\n\tif(MAX==0)\n\t\tsaturation = 0;\n\telse\n\t\tsaturation = (MAX-MIN)/MAX * 100;\n\tint value = (MAX + MIN)/2.0 * 100;\n\treturn HSV{hue,saturation,value};\n}\n\n// O(n) operation. Passes each pixel once.\nvoid Slic::convertToGreyscale(){\n  if(!ready)\n    return;\n  for(unsigned int i=0; i<height; i++){\n    for(unsigned int j=0; j<width; j++){\n      sf::Color pixel_color = image.getPixel(j,i);\n      float gs = (pixel_color.r + pixel_color.g + pixel_color.b)/3; // Averages the pixel color in rgb. Which converts it to grey.\n      image.setPixel(j,i, sf::Color(gs,gs,gs,255));\n    }\n  }\n  greyscale = true;\n}\n\nvoid Slic::loadToGraph(){\n  //Pixels are stored in a c style array in RGBA pixel format made of 8 bit integers.\n  const sf::Uint8 *pixel_data = image.getPixelsPtr();\n  for(unsigned int i=0; i<height; i++){\n    for(unsigned int j=0; j<width; j++){\n      //We're i units down height wise, and for each we have passed the width once. Then we're j units over on the current line.\n      // 0 0 0 1\n      // 1 0 2 0\n      // 2 0 X 0\n      // X is at spot (2,2), with a width of 4, and j of 2, we would have index = (2*4)+2 = 10. Which is correct.\n      unsigned int index = (i*width) + j;\n      //Extract our colors from the index\n      sf::Uint8 r = pixel_data[4*index];\n      sf::Uint8 g = pixel_data[4*index+1];\n      sf::Uint8 b = pixel_data[4*index+2];\n      sf::Uint8 a = pixel_data[4*index+3];\n      //Convert to HSV colorspace.\n      RGBA rgba = { int(r)/255.0, int(g)/255.0, int(b)/255.0, int(a)/255.0};\n      HSV hsv = rgb2hsv(rgba);\n      boost::add_vertex(vertex_data{rgba, hsv, std::vector<int>()}, graph);\n    }\n  }\n  graph_loaded = true;\n}\n#include <cstdlib>\n#include <ctime>\nsf::Color getComponentColor(int component_id){\n\tint some_prime = 31907;\n\tsrand(component_id * some_prime);\n\tint r = rand() % 256;\n\tint g = rand() % 256;\n\tint b = rand() % 256;\n\treturn sf::Color(r,g,b,255);\n}\n\nstruct rgb{\n  double r;\n  double g;\n  double b;\n};\n//I legit yoinked this one from online.\nRGBA hsv2rgb(HSV in)\n{\n    double      hh, p, q, t, ff;\n    long        i;\n    RGBA         out;\n    in.saturation /= 100.0;\n    in.value /= 100.0;\n    if(in.saturation <= 0.0) {       // < is bogus, just shuts up warnings\n        out.r = in.value;\n        out.g = in.value;\n        out.b = in.value;\n        return out;\n    }\n    hh = in.hue;\n    if(hh >= 360.0) hh = 0.0;\n    hh /= 60.0;\n    i = (long)hh;\n    ff = hh - i;\n    p = in.value * (1.0 - in.saturation);\n    q = in.value * (1.0 - (in.saturation * ff));\n    t = in.value * (1.0 - (in.saturation * (1.0 - ff)));\n\n    switch(i) {\n    case 0:\n        out.r = in.value;\n        out.g = t;\n        out.b = p;\n        break;\n    case 1:\n        out.r = q;\n        out.g = in.value;\n        out.b = p;\n        break;\n    case 2:\n        out.r = p;\n        out.g = in.value;\n        out.b = t;\n        break;\n\n    case 3:\n        out.r = p;\n        out.g = q;\n        out.b = in.value;\n        break;\n    case 4:\n        out.r = t;\n        out.g = p;\n        out.b = in.value;\n        break;\n    case 5:\n    default:\n        out.r = in.value;\n        out.g = p;\n        out.b = q;\n        break;\n    }\n    out.a = 255;\n    return out;\n}\n\nvoid Slic::writeToDisk(std::string out_dir){\n  if(!ready || !graph_loaded){\n    std::cout << \"Shit isn't ready:\" << std::endl;\n    return;\n  }\n  //Create a new pixel array.\n\tsf::Uint8 out_pixels[total_pixels*4];\n  // const sf::Uint8 *pixel_data = image.getPixelsPtr();\n\t//Filling our pixel array with new colors based on our connected components vector.\n\tauto vp = boost::vertices(graph);\n  std::cout << \"Writing to disk\" << std::endl;\n\tfor(auto iter = vp.first; iter!=vp.second; iter++){\n\t\tunsigned int index = *iter;\n    // std::cout << graph[index].cluster_ids[0] << std::endl;\n    sf::Color col = getComponentColor(graph[index].cluster_ids[0]);\n    // std::cout << graph[index].cluster_ids[0] << col.r << \" \" << col.g << std::endl;\n\n    out_pixels[4*index] = col.r;\n\t\tout_pixels[4*index+1] = col.g;\n\t\tout_pixels[4*index+2] = col.b;\n\t\tout_pixels[4*index+3] = 255;\n\t\t// out_pixels[4*index] = graph[index].rgba.r;\n\t\t// out_pixels[4*index+1] = graph[index].rgba.g;\n\t\t// out_pixels[4*index+2] = graph[index].rgba.b;\n\t\t// out_pixels[4*index+3] = graph[index].rgba.a;\n    // HSV hs = clusters[graph[index].cluster_ids[0]].color;\n    // RGBA col = hsv2rgb(hs);\n    // out_pixels[4*index] = col.r*255;\n    // out_pixels[4*index+1] = col.g*255;\n    // out_pixels[4*index+2] = col.b*255;\n    // out_pixels[4*index+3] = 255;\n\t}\n\n\n  //Strip path from input\n  std::filesystem::path input_path(if_path);\n  std::string no_path = input_path.filename();\n  //Strip extension from pathless input\n  std::filesystem::path pathless_path(no_path);\n  std::string base_path = pathless_path.stem();\n  std::string extension = \"\";\n  if(pathless_path.has_extension())\n    extension += pathless_path.extension().string();\n\n  //Create our output filename\n  base_path += \"_output\";\n  if(greyscale)\n    base_path += \"_greyscale\";\n  if(extension.size()>0)\n    base_path += extension;\n  std::string out_path = out_dir + base_path;\n\n  //Create our image to write and write it.\n  sf::Image out_image;\n  out_image.create(width, height, out_pixels);\n  out_image.saveToFile(out_path);\n}\n\nvoid Slic::cleanEdges(){\n  auto vp = boost::vertices(graph);\n  //For every vertex/pixel.\n  for(auto iter = vp.first; iter!=vp.second; iter++){\n    //Check it against all associated cluster ids.\n    edge_data best_fit = { -1 , -1 };\n    if(graph[*iter].cluster_ids.size()==0)\n      continue;\n    for(int id : graph[*iter].cluster_ids){\n      //It might be less costly to just remove each edge as we check it then add the last one. The other option is to loop twice.\n      //Convert cluster coordinates to an indice\n      int ci = clusters[id].cpos.y * width + clusters[id].cpos.x;\n\n      auto e = boost::edge(*iter, ci, graph).first;\n      //Find the best fitting edge and remove all of the rest.\n      if(best_fit.distance == -1){\n        best_fit = graph[e];\n        boost::remove_edge(e,graph);\n      }\n      else if(best_fit.distance > graph[e].distance){\n        best_fit = graph[e];\n        boost::remove_edge(e,graph);\n      }\n    }\n    graph[*iter].cluster_ids.clear();\n    //Reinsert the best edge. wasteful but fuck it.\n    int ci = clusters[best_fit.cluster_id].cpos.y * width + clusters[best_fit.cluster_id].cpos.x;\n    boost::add_edge(*iter, ci, best_fit, graph);\n    graph[*iter].cluster_ids.push_back(best_fit.cluster_id);\n  }\n}\n\n//O(n) - We hit every pixel or vertex in this algorithm.\nvoid Slic::updateClusterAverages(){\n  // 1. Generate connected component vector to find which\n  // 2.\n  if(!graph_loaded)\n    return;\n  auto vp = boost::vertices(graph);\n  //Containers to store shit in\n  std::vector<HSV> colors(clusters.size(),{0,0,0});\n  std::vector<int> color_count(clusters.size(),0);\n  //Loop through and add up all of the color values for each cluster.\n  for(auto iter = vp.first; iter!=vp.second; iter++){\n    auto v = graph[*iter];\n    if(v.cluster_ids.size()==0){\n      return;\n    }\n    colors[v.cluster_ids[0]].hue+= v.hsv.hue;\n    colors[v.cluster_ids[0]].saturation += v.hsv.saturation;\n    colors[v.cluster_ids[0]].value += v.hsv.value;\n    color_count[v.cluster_ids[0]]++;\n  }\n  //since we used the cluster id as the index, we can loop through just once to average it all and set it.\n  for(unsigned int i=0; i<clusters.size(); i++){\n    if(color_count[i]!=0){\n      clusters[i].color.hue = colors[i].hue / color_count[i];\n      clusters[i].color.saturation = colors[i].saturation / color_count[i];\n      clusters[i].color.value = colors[i].value / color_count[i];\n    }\n  }\n}\n\nbool Slic::inBounds(unsigned int x, unsigned int y){\n  //Can't be less than 0 since unsigned.\n  //If our width is 10, then index 9 is on the edge.\n//  std::cout << \"Checking if : \" << x << \" \" << y << \" - \" << width << \" \" << height << std::endl;\n  if(x >= width || y >= height)\n    return false;\n  return true;\n}\nbool Slic::isEdge(unsigned int x, unsigned int y){\n  if(x == width-1 || y == height-1)\n    return true;\n  if(x == 0 || y == 0)\n    return true;\n  return false;\n}\nvoid Slic::generateSuperpixels(unsigned int K, unsigned int error){\n  this->K = K;\n  unsigned int S = std::sqrt(total_pixels / K);\n  std::cout << \"S Value: \" << S << \" \" << width << \" \" << height << std::endl;\n  //Generate cluster centers.\n  for(unsigned int i=0; i*S < height; i++){\n    for(unsigned int j=0; j*S < width; j++){\n      int x = j*S; // We're just j*S units over.\n      int y = i*S; //We're i*S units down\n      int indice = y*width + x;\n      if(inBounds(x,y)){\n        //Get cluster center color.\n        HSV hsv = graph[indice].hsv;\n        clusters.push_back(Cluster{hsv,vec2<int>{x,y}, clusters.size()});\n        std::cout << \"Cluster center(\" << clusters.size() << \"): \" << x << \" \" << y << \" | Color: \" << hsv.hue << \" \" << hsv.saturation << \" \" << hsv.value <<  std::endl;\n      }\n    }\n  }\n  //todo - make these slightly more accurate and move off of edges.\n\n  //So every pass we're going to do the following\n  //Check every pixel around the cluster centers in a radius of 2S.\n  //Draw edges between detected pixels and the cluster centers.\n  //Clean edges\n  //Calculate cluster color\n\n  while(clusterPass(S*2,error)){\n    /*\n    How's it going today?\n    For me...I just wrote almost 10000 lines of code for a graphics project that probably won't get a B and now I'm cramming this on may 12th and it's 9pm.\n    Also it's my birthday yesterday and I think I spent it on caffeine and programming. Honestly not too bad. I got to learn a lot about opengl.\n    I just started getting into geometry shaders yesterday and water stuff too. My water is super ghetto, I have like 3 implementations lmao. the first one was a\n    mesh that I pulled the vertices on a sinfunction using elapsed time to simulate waves. I don't have much faith in this new algorithm, but I did do some research.\n    Hopefully it's sufficient. I kinda wish I found a way to do graph cuts using boost graph library. I think if I had like 2 more days I could do this projecvt so much better.\n    I'd probably do my own graph library and probably auto remove edges lmao.\n    */\n  }\n\n}\n\nbool Slic::clusterPass(int radius, unsigned int error){\n  //For each cluster\n  for(Cluster cluster : clusters){\n    //Check every pixel in a square radius around it.\n    for(int y=-radius; y<=radius; y++){\n      for(int x=-radius; x<=radius; x++){\n        int xpos = cluster.cpos.x + x;\n        int ypos = cluster.cpos.y + y;\n        if(inBounds(xpos,ypos)){\n          int indice1 = ypos*width + xpos;\n          int indice2 = cluster.cpos.y * width + cluster.cpos.x;\n          //Add edge\n          boost::add_edge(indice1,indice2, { getColorDistance(graph[indice1].hsv, graph[indice2].hsv), cluster.id},graph);\n          //Update our node cluster id list.\n          graph[indice1].cluster_ids.push_back(cluster.id);\n        }\n      }\n    }\n  }\n  cleanEdges();\n  updateClusterAverages();\n  return updateClusterPositions(error);\n}\n\n//Updates cluster positions and calculates the error threshhold for stopping our loop.\nbool Slic::updateClusterPositions(unsigned int error){\n  if(!graph_loaded)\n    return false;\n  auto vp = boost::vertices(graph);\n  //Containers to store shit in\n  std::vector<vec2<int>> pos(clusters.size(),{0,0});\n  std::vector<int> count(clusters.size(),0);\n  //Loop through all of the vertices\n  for(auto iter = vp.first; iter!=vp.second; iter++){\n    auto v = graph[*iter];\n    pos[v.cluster_ids[0]].x += clusters[v.cluster_ids[0]].cpos.x;\n    pos[v.cluster_ids[0]].y += clusters[v.cluster_ids[0]].cpos.y;\n    count[v.cluster_ids[0]]++;\n  }\n  for(unsigned int i = 0; i<count.size(); i++){\n    if(count[i]!=0){\n      //Compute error vector.\n      vec2<int> npos;\n      npos.x = pos[i].x / count[i];\n      npos.y = pos[i].y / count[i];\n      double l1 = std::sqrt(std::pow((npos.x),2) + std::pow(npos.y,2) + pow(clusters[i].color.hue,2) + pow(clusters[i].color.saturation,2) + pow(clusters[i].color.value,2));\n      double l2 = std::sqrt(std::pow((clusters[i].cpos.x),2) + std::pow(clusters[i].cpos.y,2)+ pow(clusters[i].color.hue,2) + pow(clusters[i].color.saturation,2) + pow(clusters[i].color.value,2));\n\n       std::cout << \"v1: \" << npos.x << \" \" << npos.y << \" v2 \" << clusters[i].cpos.x << \" \" << clusters[i].cpos.y << std::endl;\n       if((l1-l2) < error && (npos.x !=0 && npos.y!=0)){\n         std::cout << \"Error distance reached: \" << l1-l2 << std::endl;\n         return false;\n       }\n      clusters[i].cpos = npos;\n    }\n    else{\n      std::cout << \"Sir we've encountered a critical error. DIV/0. Somehow there's a pixel with no shit associated.\" << std::endl;\n    }\n  }\n  return true;\n}\n", "meta": {"hexsha": "6006dafc2900ecb77255b753e56b9aef73bce0f9", "size": 14665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unfinished/src/SLIC.cpp", "max_stars_repo_name": "wrathofrathma/image-segmentation", "max_stars_repo_head_hexsha": "a20562fa3e60c44d92d0d6ea571ac4004cf1b4ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "unfinished/src/SLIC.cpp", "max_issues_repo_name": "wrathofrathma/image-segmentation", "max_issues_repo_head_hexsha": "a20562fa3e60c44d92d0d6ea571ac4004cf1b4ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unfinished/src/SLIC.cpp", "max_forks_repo_name": "wrathofrathma/image-segmentation", "max_forks_repo_head_hexsha": "a20562fa3e60c44d92d0d6ea571ac4004cf1b4ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7903225806, "max_line_length": 196, "alphanum_fraction": 0.611660416, "num_tokens": 4362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4272958750643991}}
{"text": "#include <iostream>\r\n#include <cstdio>\r\n#include <string>\r\n#include <vector>\r\n#include <fstream>\r\n#include <Eigen/Eigenvalues>\r\n#include <opencv2/opencv.hpp>\r\n#include <algorithm> \r\n#include <math.h>\r\n\r\n\r\n#include \"information.h\"\r\n#include \"functionn.h\"\r\n#include \"read.h\"\r\n\r\nusing namespace std;\r\nusing Eigen::MatrixXd;\r\nusing Eigen::EigenSolver;\r\nusing Eigen::VectorXcd;\r\nusing Eigen::MatrixXcd;\r\n\r\n\r\nstring input,indicator1,indicator2 ;\r\nstring dataset = \"ATT/\";\r\nstring dash = \"_\";\r\nstring file_type = \".png\";\r\n\r\ndouble all_image_matrix[number_of_dataset][figure_height*figure_width] = { 0 };             //Create a vector*vector to store all image\r\nvector<double> average_face;\r\nvector<double> each_eigenvector(figure_height*figure_width,0);\r\nvector<vector<double>> eigenvectors(number_of_eigenvectors,each_eigenvector);\r\ndouble class_average_face[number_of_face_class][figure_height*figure_width] = { 0 };\r\ndouble class_w[number_of_face_class][number_of_eigenvectors] = { 0 };\r\nint test_index;\r\nint main() {\r\n\r\n\timage_content image;                                                   //Create a class call \"image_content\" to store the information of image\r\n\tdouble each[figure_height*figure_width] = {0};                       //Create a vector to store one image\r\n\r\n\r\n\r\n\t//Data all_data;\r\n\t\r\n\r\n\t//Read and store the data from figure and store it into to image_matrix\r\n\tfor (int i = 0, q = 1, w = 1; i < number_of_dataset && q < 41 && w < 11; i++) {\r\n\t\tindicator1 = to_string(q);\r\n\t\tindicator2 = to_string(w);\r\n\t\tinput = dataset + indicator1 + dash + indicator2 + file_type;      //Read the file by substituting the character.\r\n\t\timage = read::figure(input);                                       //Via opencv to read the image and acquire the data in class \"image_content\" form.\r\n\t\tfor (int j = 0; j < figure_height*figure_width; j++) {\r\n\t\t\teach[j] = (image.content[j]);                                  // Assign the data from class \"image_content\" to vector variable \"each\".\r\n\t\t}\r\n\r\n\r\n\t\t//This part is saving the image to a txt, in order to double check the matrix of input figure is correctly save into class \"image_content\" or not.\r\n\t\t//We save all data into a txt, then display it to check whether it is the original image or not.\r\n\t\t/*\r\n\t\tofstream file;\r\n\t\tfor (int i=0; i < image.height*image.width; i++) {\r\n\r\n\t\tfile.open(\"test1.txt\",fstream::app);\r\n\t\tfile << image.content[i];\r\n\t\tfile << \"\\n\";\r\n\t\tfile.close();\r\n\t\tcout << i << endl;\r\n\t\tcout << \"\\n\";\r\n\t\t}\r\n\t\tcout << endl;\r\n\t\t*/\r\n\r\n\t\t//Store information of each figure to the image_matrix\r\n\t\tfor (int k = 0; k < figure_height*figure_width; k++) {\r\n\t\t\tall_image_matrix[i][k] = each[k];\r\n\t\t}\r\n\r\n\t\t//This is just for the pointer.\r\n\t\tif (w < 11) { w++; }\r\n\t\tif (w == 11) { w = 1; q++; }\r\n\t}\r\n\r\n\r\n\r\n\r\n\taverage_face = functionn::averagee(all_image_matrix);    //Feed the image_matrix to the function and acquire the average face.\r\n\r\n\r\n\r\n\tfunctionn::save_one_face(average_face);                     //This part is saving the average face to a txt, in order to double check the average face is normal or not.\r\n\r\n\r\n\t//********\r\n\tvector<vector<double>> A_matrix = functionn::calculate_A(all_image_matrix, average_face);\r\n\t//We got A!  (A = A_matrix)\r\n\t//********\r\n\r\n\t///////////////////////////////////////////////////////////////////////////////\r\n\t// Let's calculate eigenvectors!\r\n\r\n\t//We have two ways to calculate eigenvectors, first is via Matlab, the other is eigen.\r\n\r\n\t//This part is reading the eigenvector and eigenvalue which are calculated from matlab.\r\n\t//Read 6 eigenvalues and its relevant eigenvetors.\r\n\tstring file_name = \"For_matlab/eigenvector\";\r\n\tstring file_type = \".txt\";\r\n\tifstream eigenvector_file;\r\n\tfor (int i = 1; i <= number_of_eigenvectors; i++) {\r\n\t\tint j = 0;\r\n\t\tcout << file_name + to_string(i) + file_type << endl;\r\n\t\teigenvector_file.open(file_name + to_string(i) + file_type, ios::in);\r\n\t\tstring line;\r\n\t\tdouble tem;\r\n\t\twhile (getline(eigenvector_file, line)) {\r\n\t\t\ttem = stod(line);\r\n\t\t\teigenvectors[i - 1][j] = tem;\r\n\t\t\tj++;\r\n\t\t}\r\n\t\teigenvector_file.close();\r\n\t}\r\n\r\n\r\n\t//********\r\n\t//This is the eigen way\r\n\t//vector<vector<complex<double>>> eigenvectors = functionn::calculate_eigenvalues_and_eigenvectors(A_matrix);\r\n\t//********\r\n\r\n\r\n\r\n\r\n\t//Now we have the eigenvector(eigenface)!\r\n\t//Let's display our eigenface !\r\n\r\n\r\n\t//////////////////////////////////////////////////////////////////////////////////\r\n\t/*\r\n\t//This part is reflecting the pixel value to (0,1), then reflect it to (0,255)\r\n\t\r\n\tcout << eigenvectors[0][100] << endl;\r\n\tdouble maximum = 0;\r\n\tdouble minimum = 1;\r\n\tfor (int count = 0; count < figure_height*figure_width; count++) {\r\n\t\tmaximum = max(maximum, eigenvectors[display_index][count]);\r\n\t\tminimum = min(minimum, eigenvectors[display_index][count]);\r\n\t}\r\n\r\n\tfor (int count = 0; count < figure_height*figure_width; count++) {\r\n\t\teigenvectors[display_index][count] = (eigenvectors[display_index][count] - minimum) / (maximum - minimum) * 255;\r\n\t}\r\n\r\n\t//Finish reflecting to (0,255)!\r\n\t//////////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\t//Assign the value in eigenface to file m (opencv Mat form) in order to display.\r\n\tif (eigenvectors[display_index].size() == figure_height*figure_width) // check that the rows and cols match the size of your vector\r\n\t{\r\n\t\tcv::Mat m(figure_height, figure_width, CV_8U); // initialize matrix of uchar of 1-channel where you will store vec data\r\n\r\n\t\tint p3 = 0;\r\n\t\tfor (int p1 = 0; p1 < figure_height; p1++) {\r\n\t\t\tfor (int p2 = 0; p2 < figure_width; p2++) {\r\n\t\t\t\tm.at<uchar>(p1, p2) = eigenvectors[display_index].at(p3);\r\n\t\t\t\tp3++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tcv::imwrite(\"Eigenface.jpg\", m);               //Save the eigenface!\r\n\t}\r\n\r\n\t*/\r\n\t//Now we have the essiential item to recognize face!\r\n\tcout << \"Please tell me which image do you want to test? (0~49)\" << endl;\r\n\tcin >> test_index;\r\n\tcout << endl;\r\n\tclass_information all;\r\n\t//First calculate the aveverge face of each class\r\n\tall.calculate_all_average_face();\r\n\r\n\t//Let's calculate each omega of all classes\r\n\tall.calculate_all_w();\r\n\r\n\r\n\t//Now we got 40 omega(each omega indicates the weights of each class and has 6 dimensions(number_of_eigenvectors))\r\n\t//Definition of Omega refers to equation(8) in \"Eigenfaces for Recognition\" 1991.\r\n\r\n\t//Let's classify our image from class A, B and C!\r\n\t//Use equation(8) in \"Eigenfaces for Recognition\" 1991.\r\n\r\n\tclassify result;\r\n\r\n\tresult.calculate_w(all_image_matrix[test_index]);\r\n\tresult.criteria_each();                          //Calculate the Euclidian distance\r\n\tresult.determine_result();\r\n\r\n\r\n\r\n\tint ans;\r\n\tif (test_index < 10) {\r\n\t\tans = 0;\r\n\t}\r\n\telse if (test_index < 20) {\r\n\t\tans = 1;\r\n\t}\r\n\telse if (test_index < 30) {\r\n\t\tans = 2;\r\n\t}\r\n\telse if (test_index < 40) {\r\n\t\tans = 3;\r\n\t}\r\n\telse if (test_index < 50) {\r\n\t\tans = 4;\r\n\t}\r\n\tcout << \"And the ground truth is \" << ans << \" !\" << endl;\r\n\r\n\r\n\r\n\tcout << endl;\r\n\tsystem(\"pause\");\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "ec785e16fd15c961f75a046f163bd1f21095ab6a", "size": 6924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Face_recognition/main.cpp", "max_stars_repo_name": "yoyotv/Face-detection", "max_stars_repo_head_hexsha": "df998e4ddca063fe2c0878177b8bb61aa7a9e301", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Face_recognition/main.cpp", "max_issues_repo_name": "yoyotv/Face-detection", "max_issues_repo_head_hexsha": "df998e4ddca063fe2c0878177b8bb61aa7a9e301", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Face_recognition/main.cpp", "max_forks_repo_name": "yoyotv/Face-detection", "max_forks_repo_head_hexsha": "df998e4ddca063fe2c0878177b8bb61aa7a9e301", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1891891892, "max_line_length": 170, "alphanum_fraction": 0.6226169844, "num_tokens": 1789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4272958750643991}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_FUNCTIONS_COMPLEX_GENERIC_SINCOS_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_FUNCTIONS_COMPLEX_GENERIC_SINCOS_HPP_INCLUDED\n#include <nt2/trigonometric/functions/sincos.hpp>\n#include <nt2/include/functions/sincos.hpp>\n#include <nt2/include/functions/sinhcosh.hpp>\n#include <nt2/include/functions/real.hpp>\n#include <nt2/include/functions/imag.hpp>\n#include <nt2/include/functions/is_imag.hpp>\n#include <nt2/include/functions/is_real.hpp>\n#include <nt2/include/functions/logical_and.hpp>\n#include <nt2/include/functions/is_invalid.hpp>\n#include <nt2/include/functions/is_inf.hpp>\n#include <nt2/sdk/complex/meta/as_complex.hpp>\n#include <nt2/sdk/complex/meta/as_real.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n#include <nt2/include/functions/logical_or.hpp>\n#include <nt2/include/functions/if_zero_else.hpp>\n#include <nt2/include/functions/if_else.hpp>\n#include <nt2/include/functions/any.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  (sincos_, tag::cpu_,\n                             (A0),\n                             (generic_ < complex_<floating_ < A0> > > )\n                             (generic_ < complex_<floating_ < A0> > > )\n                             (generic_ < complex_<floating_ < A0> > > )\n                            )\n  {\n    typedef void result_type;\n    inline void operator()(A0 const& a0,A0 & a1,A0 & a2) const\n    {\n      typedef typename meta::as_real<A0>::type rtype;\n      typedef typename meta::as_logical<A0>::type ltype;\n      rtype c, s, ch, sh;\n      sincos(nt2::real(a0), s, c);\n      sinhcosh(nt2::imag(a0), sh, ch);\n      rtype r1 = if_zero_else(is_imag(a0), s*ch);\n      rtype i1 = if_zero_else(is_real(a0), c*sh);\n      rtype r2 = c*ch;\n      rtype i2 = if_zero_else(logical_or(is_imag(a0), is_real(a0)), -s*sh);\n      a1 =  A0(r1, i1);\n      a2 =  A0(r2, i2);\n#ifndef BOOST_SIMD_NO_INVALIDS\n      ltype t = logical_and(is_invalid(real(a0)), is_inf(imag(a0)));\n      if (any(t))\n      {\n        A0 zs = A0(Nan<rtype>(),imag(a0));\n        A0 zc = A0(Inf<rtype>(),Nan<rtype>());\n        a1 = if_else(t, zs, a1);\n        a2 = if_else(t, zc, a2);\n      }\n#endif\n\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (sincos_, tag::cpu_,\n                             (A0),\n                             (generic_ < dry_<floating_ < A0> > > )\n                             (generic_ < dry_<floating_ < A0> > > )\n                             (generic_ < dry_<floating_ < A0> > > )\n                            )\n  {\n    typedef void result_type;\n    inline void operator()(A0 const& a0,A0 & a1,A0 & a2) const\n    {\n      typedef typename meta::as_real<A0>::type rtype;\n      rtype c, s;\n      sincos(nt2::real(a0), s, c);\n      a1 =  bitwise_cast<A0>(c);\n      a2 =  bitwise_cast<A0>(s);\n    }\n  };\n\n\n  BOOST_DISPATCH_IMPLEMENT  (sincos_, tag::cpu_,\n                             (A0),\n                             (generic_ < complex_<floating_ < A0> > > )\n                             (generic_ < complex_<floating_ < A0> > > )\n                            )\n  {\n    typedef A0 result_type;\n    inline A0 operator()(A0 const& a0,A0 & a2) const\n    {\n      result_type a1;\n      sincos(a0, a1, a2);\n      return a1;\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (sincos_, tag::cpu_,\n                             (A0),\n                             (generic_ < complex_<floating_<A0> > > )\n                            )\n  {\n    typedef std::pair<A0, A0>           result_type;\n    NT2_FUNCTOR_CALL(1)\n    {\n      A0 first, second;\n      sincos(a0, first, second);\n      return result_type(first, second);\n    }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "89816f2b4f3ad62ff702f9c57cd4e6b93e81227e", "size": 4204, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/type/complex/trigonometric/include/nt2/trigonometric/functions/complex/generic/sincos.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/type/complex/trigonometric/include/nt2/trigonometric/functions/complex/generic/sincos.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/type/complex/trigonometric/include/nt2/trigonometric/functions/complex/generic/sincos.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 35.0333333333, "max_line_length": 80, "alphanum_fraction": 0.5492388202, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.42729586882237325}}
{"text": "#include <vector>\n#include <random>\n#include <iostream>\n#include <chrono>\n#include <boost/geometry/extensions/triangulation/strategies/cartesian/detail/precise_math.hpp>\n#include \"dynamic_exact.h\"\n#include \"static_exact.h\"\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::Point_2 Point_2;\n\nconst int samples = 10'000'000;\n\nstruct problem { std::array<double, 2> a,b,c; };\n\nint main()\n{\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\tstd::uniform_real_distribution<> dis(0.0, 1.0);\n\tint mod = 1000;\n\tstd::cout << \"1 in \" << mod << \" is guaranteed to require higher precision.\\n\";\n\tstd::vector<problem> problems;\n\tproblems.reserve(samples);\n\tfor(int i=0; i < samples; ++i) {\n\t\tdouble bfac = 1.0, cfac = 1.0;\n\t\tif(i % mod == 0) {\n\t\t\tbfac = 1e20;\n\t\t\tcfac = 1e40;\n\t\t}\n\t\tproblems.emplace_back(problem{dis(gen), dis(gen), dis(gen) * bfac, dis(gen) * bfac, dis(gen) * cfac, dis(gen) * cfac});\n\t}\n\tauto start = std::chrono::system_clock::now();\n\tint sum1 = 0;\n\tfor(int i = 0; i < samples; ++i) {\n\t\tauto det = boost::geometry::detail::precise_math::orient2d<double>(problems[i].a, problems[i].b, problems[i].c);\n\t\tauto r = det > 0 ? 1 : (det < 0 ? -1 : 0);\n\t\tsum1 += r;\n\t}\n\tauto end = std::chrono::system_clock::now();\n\tauto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);\n\tstd::cout << \"Boost robust orient2:\\t\\t\" << sum1 << \"\\t\" << elapsed.count() << \"ms\\n\";\n\t\n\tstart = std::chrono::system_clock::now();\n\tint sum2 = 0;\n\tfor(int i = 0; i < samples; ++i) {\n\t        Point_2 p(problems[i].a[0], problems[i].a[1]), q(problems[i].b[0], problems[i].b[1]), r(problems[i].c[0], problems[i].c[1]);\n\t        auto det = CGAL::orientation(p, q, r);\n\t        sum2 += det > 0 ? 1 : (det < 0 ? -1 : 0);\n\t}\n\tend = std::chrono::system_clock::now();\n\telapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);\n\tstd::cout << \"CGAL exact predicate:\\t\\t\" << sum2 << \"\\t\" << elapsed.count() << \"ms\\n\";\n\n\tstart = std::chrono::system_clock::now();\n\tint sum3 = 0;\n\tfor(int i = 0; i < samples; ++i) {\n\t        auto det = (problems[i].a[0] - problems[i].c[0]) * (problems[i].b[1] - problems[i].c[1])\n\t\t\t- (problems[i].a[1] - problems[i].c[1]) * (problems[i].b[0] - problems[i].c[0]);\n\t        sum3 += det > 0 ? 1 : (det < 0 ? -1 : 0);\n\t}\n\tend = std::chrono::system_clock::now();\n\telapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);\n\tstd::cout << \"naive double computation:\\t\" << sum3 << \"\\t\" << elapsed.count() << \"ms\\n\";\n\n\tusing A = float_wrapper<double>;\n        start = std::chrono::system_clock::now();\n        int sum4 = 0;\n        for(int i = 0; i < samples; ++i) {\n                auto det = ((A(problems[i].a[0]) + A(-problems[i].c[0])) * (A(problems[i].b[1]) + A(-problems[i].c[1]))\n                        + (A(-problems[i].a[1]) + A(problems[i].c[1])) * (A(problems[i].b[0]) + A(-problems[i].c[0]))).sign();\n                sum4 += det > 0 ? 1 : (det < 0 ? -1 : 0);\n        }\n        end = std::chrono::system_clock::now();\n        elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);\n        std::cout << \"automatically generated exact:\\t\" << sum4 << \"\\t\" << elapsed.count() << \"ms\\n\";\n\treturn 0;\n}\n", "meta": {"hexsha": "9605e7b46c4d70b9b8715a171b407bb5476caac1", "size": 3277, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark.cpp", "max_stars_repo_name": "tinko92/expansion_math", "max_stars_repo_head_hexsha": "ef0a11f81de9838a7d3c9a3e413df672571a0302", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark.cpp", "max_issues_repo_name": "tinko92/expansion_math", "max_issues_repo_head_hexsha": "ef0a11f81de9838a7d3c9a3e413df672571a0302", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark.cpp", "max_forks_repo_name": "tinko92/expansion_math", "max_forks_repo_head_hexsha": "ef0a11f81de9838a7d3c9a3e413df672571a0302", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9625, "max_line_length": 133, "alphanum_fraction": 0.5932255111, "num_tokens": 1056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.42729586882237325}}
{"text": "#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/cycle_canceling.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\n// Graph Type with nested interior edge properties for Cost Flow Algorithms\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n                              boost::property<boost::edge_capacity_t, long,\n                                              boost::property<boost::edge_residual_capacity_t, long,\n                                                              boost::property<boost::edge_reverse_t, traits::edge_descriptor,\n                                                                              boost::property<boost::edge_weight_t, long>>>>>\n    graph; // new! weightmap corresponds to costs\ntypedef boost::graph_traits<graph>::edge_descriptor edge_desc;\ntypedef boost::graph_traits<graph>::out_edge_iterator out_edge_it; // Iterator\n\n// Custom edge adder class\nclass edge_adder\n{\n    graph &G;\n\npublic:\n    explicit edge_adder(graph &G) : G(G) {}\n    void add_edge(int from, int to, long capacity, long cost)\n    {\n        auto c_map = boost::get(boost::edge_capacity, G);\n        auto r_map = boost::get(boost::edge_reverse, G);\n        auto w_map = boost::get(boost::edge_weight, G); // new!\n        const edge_desc e = boost::add_edge(from, to, G).first;\n        const edge_desc rev_e = boost::add_edge(to, from, G).first;\n        c_map[e] = capacity;\n        c_map[rev_e] = 0; // reverse edge has no capacity!\n        r_map[e] = rev_e;\n        r_map[rev_e] = e;\n        w_map[e] = cost;      // new assign cost\n        w_map[rev_e] = -cost; // new negative cost\n    }\n};\n\nusing namespace std;\n\n\n// Idea:\n// Train has l seats. \n// Each seat can either be occupied by an agent or a regular passenger.\n// An agent on a mission brings reward q, a regular passenger 0.\n// l people board the train\n// At a given stop: \n// - either start mission to target-stop with value q\n// - or travel to next stop without reward\nvoid solve()\n{\n    int stops, missions, maxAgents;\n    cin >> stops >> missions >> maxAgents;\n\n    int maxValue = 128; // 2^7\n\n    graph G(stops);\n    edge_adder adder(G);\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    auto rc_map = boost::get(boost::edge_residual_capacity, G);\n\n    auto source = boost::add_vertex(G);\n    auto target = boost::add_vertex(G);\n\n    adder.add_edge(source, 0, maxAgents, 0);\n    adder.add_edge(stops - 1, target, maxAgents, 0);\n\n    for (int stop = 0; stop < stops - 1; ++stop) {\n        adder.add_edge(stop, stop + 1, maxAgents, maxValue);\n    }\n\n    int u, v, q;\n    for (int mission = 0; mission < missions; ++mission) {\n        cin >> u >> v >> q;\n        adder.add_edge(u, v, 1, maxValue * (v - u) - q);\n    }\n\n    boost::successive_shortest_path_nonnegative_weights(G, source, target);\n    auto cost = boost::find_flow_cost(G);\n    cost = maxAgents * maxValue * (stops - 1) - cost;\n    cout << cost << endl;\n}\n\nint main()\n{\n    int t; cin >> t;\n    for (int i = 0; i < t; ++i) {\n        solve();\n    }\n    return 0;\n}\n", "meta": {"hexsha": "2f65c43ae3e868380df3e4854d446ab69ffcd729", "size": 3349, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/casino.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/casino.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/casino.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 34.8854166667, "max_line_length": 125, "alphanum_fraction": 0.6189907435, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891479496521, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.42714479303746816}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Pavel Kharitonov <ipavrus@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_TIGER_FUNCTIONS_HPP\n#define CRYPTO3_TIGER_FUNCTIONS_HPP\n\n#include <boost/crypto3/hash/detail/tiger/basic_tiger_policy.hpp>\n#include <boost/crypto3/detail/make_uint_t.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace hashes {\n            namespace detail {\n                template<std::size_t DigestBits>\n                struct tiger_functions : public basic_tiger_policy<DigestBits> {\n                    typedef basic_tiger_policy<DigestBits> policy_type;\n\n                    typedef typename policy_type::byte_type byte_type;\n\n                    constexpr static const std::size_t word_bits = policy_type::word_bits;\n                    typedef typename policy_type::word_type word_type;\n\n                    constexpr static const std::size_t state_bits = basic_tiger_policy<DigestBits>::state_bits;\n                    constexpr static const std::size_t state_words = basic_tiger_policy<DigestBits>::state_words;\n                    typedef typename basic_tiger_policy<DigestBits>::state_type state_type;\n\n                    constexpr static const std::size_t block_bits = basic_tiger_policy<DigestBits>::block_bits;\n                    constexpr static const std::size_t block_words = basic_tiger_policy<DigestBits>::block_words;\n                    typedef typename basic_tiger_policy<DigestBits>::block_type block_type;\n\n                    inline static void mix(block_type &X) {\n                        X[0] -= X[7] ^ 0xA5A5A5A5A5A5A5A5;\n                        X[1] ^= X[0];\n                        X[2] += X[1];\n                        X[3] -= X[2] ^ ((~X[1]) << 19);\n                        X[4] ^= X[3];\n                        X[5] += X[4];\n                        X[6] -= X[5] ^ ((~X[4]) >> 23);\n                        X[7] ^= X[6];\n\n                        X[0] += X[7];\n                        X[1] -= X[0] ^ ((~X[7]) << 19);\n                        X[2] ^= X[1];\n                        X[3] += X[2];\n                        X[4] -= X[3] ^ ((~X[2]) >> 23);\n                        X[5] ^= X[4];\n                        X[6] += X[5];\n                        X[7] -= X[6] ^ 0x0123456789ABCDEF;\n                    }\n\n                    inline static void pass(word_type &A, word_type &B, word_type &C, block_type &X, byte_type mul) {\n                        C ^= X[0];\n                        A -= policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 7)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 5)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 3)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 1)];\n                        B += policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 0)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 2)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 4)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 6)];\n                        B *= mul;\n                        A ^= X[1];\n                        B -= policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 7)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 5)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 3)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 1)];\n                        C += policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 0)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 2)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 4)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 6)];\n                        C *= mul;\n                        B ^= X[2];\n                        C -= policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 7)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 5)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 3)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 1)];\n                        A += policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 0)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 2)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 4)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 6)];\n                        A *= mul;\n                        C ^= X[3];\n                        A -= policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 7)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 5)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 3)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 1)];\n                        B += policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 0)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 2)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 4)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 6)];\n                        B *= mul;\n                        A ^= X[4];\n                        B -= policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 7)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 5)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 3)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 1)];\n                        C += policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 0)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 2)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 4)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 6)];\n                        C *= mul;\n                        B ^= X[5];\n                        C -= policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 7)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 5)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 3)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 1)];\n                        A += policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 0)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 2)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 4)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(B, 6)];\n                        A *= mul;\n                        C ^= X[6];\n                        A -= policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 7)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 5)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 3)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 1)];\n                        B += policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 0)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 2)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 4)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(C, 6)];\n                        B *= mul;\n                        A ^= X[7];\n                        B -= policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 7)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 5)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 3)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 1)];\n                        C += policy_type::sbox1[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 0)] ^\n                             policy_type::sbox2[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 2)] ^\n                             policy_type::sbox3[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 4)] ^\n                             policy_type::sbox4[::boost::crypto3::detail::extract_uint_t<CHAR_BIT>(A, 6)];\n                        C *= mul;\n                    }\n                };\n            }   // namespace detail\n        }   // namespace hashes\n    }   // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_TIGER_FUNCTIONS_HPP\n", "meta": {"hexsha": "9777940b5f520575c630c8139fef770919199020", "size": 10386, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/hash/detail/tiger/tiger_functions.hpp", "max_stars_repo_name": "NilFoundation/boost-crypto", "max_stars_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-02T06:19:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T04:55:03.000Z", "max_issues_repo_path": "include/boost/crypto3/hash/detail/tiger/tiger_functions.hpp", "max_issues_repo_name": "NilFoundation/boost-crypto", "max_issues_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-04-06T21:49:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-18T04:54:51.000Z", "max_forks_repo_path": "include/boost/crypto3/hash/detail/tiger/tiger_functions.hpp", "max_forks_repo_name": "NilFoundation/boost-crypto", "max_forks_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:14:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:14:37.000Z", "avg_line_length": 71.1369863014, "max_line_length": 117, "alphanum_fraction": 0.5048141729, "num_tokens": 2639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.42710849565669995}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright 2014 Anton Bikineev\r\n//  Copyright 2014 Christopher Kormanyos\r\n//  Copyright 2014 John Maddock\r\n//  Copyright 2014 Paul Bristow\r\n//  Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n#ifndef BOOST_MATH_HYPERGEOMETRIC_ASYM_HPP\r\n#define BOOST_MATH_HYPERGEOMETRIC_ASYM_HPP\r\n\r\n#include <boost/math/special_functions/gamma.hpp>\r\n#include <boost/math/special_functions/hypergeometric_2F0.hpp>\r\n\r\n#ifdef BOOST_MSVC\r\n#pragma warning(push)\r\n#pragma warning(disable:4127)\r\n#endif\r\n\r\n  namespace boost { namespace math {\r\n\r\n  namespace detail {\r\n\r\n     //\r\n     // Asymptotic series based on https://dlmf.nist.gov/13.7#E1\r\n     //\r\n     // Note that a and b must not be negative integers, in addition\r\n     // we require z > 0 and so apply Kummer's relation for z < 0.\r\n     //\r\n     template <class T, class Policy>\r\n     inline T hypergeometric_1F1_asym_large_z_series(T a, const T& b, T z, const Policy& pol, int& log_scaling)\r\n     {\r\n        BOOST_MATH_STD_USING\r\n        static const char* function = \"boost::math::hypergeometric_1F1_asym_large_z_series<%1%>(%1%, %1%, %1%)\";\r\n        T prefix;\r\n        int e, s;\r\n        if (z < 0)\r\n        {\r\n           a = b - a;\r\n           z = -z;\r\n           prefix = 1;\r\n        }\r\n        else\r\n        {\r\n           e = z > INT_MAX ? INT_MAX : itrunc(z, pol);\r\n           log_scaling += e;\r\n           prefix = exp(z - e);\r\n        }\r\n        if ((fabs(a) < 10) && (fabs(b) < 10))\r\n        {\r\n           prefix *= pow(z, a) * pow(z, -b) * boost::math::tgamma(b, pol) / boost::math::tgamma(a, pol);\r\n        }\r\n        else\r\n        {\r\n           T t = log(z) * (a - b);\r\n           e = itrunc(t, pol);\r\n           log_scaling += e;\r\n           prefix *= exp(t - e);\r\n\r\n           t = boost::math::lgamma(b, &s, pol);\r\n           e = itrunc(t, pol);\r\n           log_scaling += e;\r\n           prefix *= s * exp(t - e);\r\n\r\n           t = boost::math::lgamma(a, &s, pol);\r\n           e = itrunc(t, pol);\r\n           log_scaling -= e;\r\n           prefix /= s * exp(t - e);\r\n        }\r\n        //\r\n        // Checked 2F0:\r\n        //\r\n        unsigned k = 0;\r\n        T a1_poch(1 - a);\r\n        T a2_poch(b - a);\r\n        T z_mult(1 / z);\r\n        T sum = 0;\r\n        T abs_sum = 0;\r\n        T term = 1;\r\n        T last_term = 0;\r\n        do\r\n        {\r\n           sum += term;\r\n           last_term = term;\r\n           abs_sum += fabs(sum);\r\n           term *= a1_poch * a2_poch * z_mult;\r\n           term /= ++k;\r\n           a1_poch += 1;\r\n           a2_poch += 1;\r\n           if (fabs(sum) * boost::math::policies::get_epsilon<T, Policy>() > fabs(term))\r\n              break;\r\n           if(fabs(sum) / abs_sum < boost::math::policies::get_epsilon<T, Policy>())\r\n              return boost::math::policies::raise_evaluation_error<T>(function, \"Large-z asymptotic approximation to 1F1 has destroyed all the digits in the result due to cancellation.  Current best guess is %1%\", \r\n                 prefix * sum, Policy());\r\n           if(k > boost::math::policies::get_max_series_iterations<Policy>())\r\n              return boost::math::policies::raise_evaluation_error<T>(function, \"1F1: Unable to locate solution in a reasonable time:\"\r\n                 \" large-z asymptotic approximation.  Current best guess is %1%\", prefix * sum, Policy());\r\n           if((k > 10) && (fabs(term) > fabs(last_term)))\r\n              return boost::math::policies::raise_evaluation_error<T>(function, \"Large-z asymptotic approximation to 1F1 is divergent.  Current best guess is %1%\", prefix * sum, Policy());\r\n        } while (true);\r\n\r\n        return prefix * sum;\r\n     }\r\n\r\n\r\n  // experimental range\r\n  template <class T, class Policy>\r\n  inline bool hypergeometric_1F1_asym_region(const T& a, const T& b, const T& z, const Policy&)\r\n  {\r\n    BOOST_MATH_STD_USING\r\n    int half_digits = policies::digits<T, Policy>() / 2;\r\n    bool in_region = false;\r\n\r\n    if (fabs(a) < 0.001f)\r\n       return false; // Haven't been able to make this work, why not?  TODO!\r\n\r\n    //\r\n    // We use the following heuristic, if after we have had half_digits terms\r\n    // of the 2F0 series, we require terms to be decreasing in size by a factor\r\n    // of at least 0.7.  Assuming the earlier terms were converging much faster\r\n    // than this, then this should be enough to achieve convergence before the\r\n    // series shoots off to infinity.\r\n    //\r\n    if (z > 0)\r\n    {\r\n       T one_minus_a = 1 - a;\r\n       T b_minus_a = b - a;\r\n       if (fabs((one_minus_a + half_digits) * (b_minus_a + half_digits) / (half_digits * z)) < 0.7)\r\n       {\r\n          in_region = true;\r\n          //\r\n          // double check that we are not divergent at the start if a,b < 0:\r\n          //\r\n          if ((one_minus_a < 0) || (b_minus_a < 0))\r\n          {\r\n             if (fabs(one_minus_a * b_minus_a / z) > 0.5)\r\n                in_region = false;\r\n          }\r\n       }\r\n    }\r\n    else if (fabs((1 - (b - a) + half_digits) * (a + half_digits) / (half_digits * z)) < 0.7)\r\n    {\r\n       if ((floor(b - a) == (b - a)) && (b - a < 0))\r\n          return false;  // Can't have a negative integer b-a.\r\n       in_region = true;\r\n       //\r\n       // double check that we are not divergent at the start if a,b < 0:\r\n       //\r\n       T a1 = 1 - (b - a);\r\n       if ((a1 < 0) || (a < 0))\r\n       {\r\n          if (fabs(a1 * a / z) > 0.5)\r\n             in_region = false;\r\n       }\r\n    }\r\n    //\r\n    // Check for a and b negative integers as these aren't supported by the approximation:\r\n    //\r\n    if (in_region)\r\n    {\r\n       if ((a < 0) && (floor(a) == a))\r\n          in_region = false;\r\n       if ((b < 0) && (floor(b) == b))\r\n          in_region = false;\r\n       if (fabs(z) < 40)\r\n          in_region = false;\r\n    }\r\n    return in_region;\r\n  }\r\n\r\n  } } } // namespaces\r\n\r\n#ifdef BOOST_MSVC\r\n#pragma warning(pop)\r\n#endif\r\n\r\n#endif // BOOST_MATH_HYPERGEOMETRIC_ASYM_HPP\r\n", "meta": {"hexsha": "0e5a29136b3eb24f2510a24bff82bdc3c24d7f68", "size": 6080, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/special_functions/detail/hypergeometric_asym.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/math/special_functions/detail/hypergeometric_asym.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/math/special_functions/detail/hypergeometric_asym.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T06:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:55:07.000Z", "avg_line_length": 33.9664804469, "max_line_length": 215, "alphanum_fraction": 0.5199013158, "num_tokens": 1643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.42710849565669995}}
{"text": "/*\n   For more information, please see: http://software.sci.utah.edu\n\n   The MIT License\n\n   Copyright (c) 2020 Scientific Computing and Imaging Institute,\n   University of Utah.\n\n   Permission is hereby granted, free of charge, to any person obtaining a\n   copy of this software and associated documentation files (the \"Software\"),\n   to deal in the Software without restriction, including without limitation\n   the rights to use, copy, modify, merge, publish, distribute, sublicense,\n   and/or sell copies of the Software, and to permit persons to whom the\n   Software is furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included\n   in all copies or substantial portions of the Software.\n\n   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n   DEALINGS IN THE SOFTWARE.\n*/\n\n\n#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Algorithms/Math/SolveLinearSystemWithEigen.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/DenseColumnMatrix.h>\n#include <Core/Datatypes/SparseRowMatrix.h>\n#include <Core/Datatypes/MatrixTypeConversions.h>\n#include <Eigen/Sparse>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Algorithms::Math;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core;\n\nnamespace\n{\n  using EigenComputationInfo = boost::error_info<struct tag_eigen_computation, Eigen::ComputationInfo>;\n\n  template <class ColumnMatrixType, template <typename> class SolverType>\n  class SolveLinearSystemAlgorithmEigenCGImpl\n  {\n  public:\n    SolveLinearSystemAlgorithmEigenCGImpl(SharedPointer<ColumnMatrixType> rhs, double tolerance, int maxIterations) :\n        tolerance_(tolerance), maxIterations_(maxIterations), rhs_(rhs) {}\n\n    using SolutionType = ColumnMatrixType;\n\n    template <class MatrixType>\n    typename ColumnMatrixType::EigenBase solveWithEigen(const MatrixType& lhs)\n    {\n      SolverType<typename MatrixType::EigenBase> solver;\n      solver.compute(lhs);\n\n      if (solver.info() != Eigen::Success)\n        BOOST_THROW_EXCEPTION(AlgorithmInputException()\n          << LinearAlgebraErrorMessage(\"Eigen solver initialization was unsuccessful\")\n          << EigenComputationInfo(solver.info()));\n\n      solver.setTolerance(tolerance_);\n      solver.setMaxIterations(maxIterations_);\n      auto solution = solver.solve(*rhs_).eval();\n      tolerance_ = solver.error();\n      maxIterations_ = solver.iterations();\n      return solution;\n    }\n\n    double tolerance_;\n    int maxIterations_;\n  private:\n    SharedPointer<ColumnMatrixType> rhs_;\n  };\n}\n\nSolveLinearSystemAlgorithm::Outputs SolveLinearSystemAlgorithm::run(const Inputs& input, const Parameters& params) const\n{\n  return runImpl<Inputs, Outputs>(input, params);\n}\n\nSolveLinearSystemAlgorithm::ComplexOutputs SolveLinearSystemAlgorithm::run(const ComplexInputs& input, const Parameters& params) const\n{\n  return runImpl<ComplexInputs, ComplexOutputs>(input, params);\n}\n\ntemplate <typename T>\nusing CG = Eigen::ConjugateGradient<T>;\n// Not available yet, need to upgrade Eigen\n// template <typename T>\n// using LSCG = Eigen::LeastSquaresConjugateGradient<T>;\ntemplate <typename T>\nusing BiCG = Eigen::BiCGSTAB<T>;\n\ntemplate <typename In, typename Out>\nOut SolveLinearSystemAlgorithm::runImpl(const In& input, const Parameters& params) const\n{\n  auto A = std::get<0>(input);\n  ENSURE_ALGORITHM_INPUT_NOT_NULL(A, \"Null input matrix\");\n\n  auto b = std::get<1>(input);\n  ENSURE_ALGORITHM_INPUT_NOT_NULL(b, \"Null rhs vector\");\n\n  double tolerance = std::get<0>(params);\n  ENSURE_POSITIVE_DOUBLE(tolerance, \"Tolerance out of range!\");\n\n  int maxIterations = std::get<1>(params);\n  ENSURE_POSITIVE_INT(maxIterations, \"Max iterations out of range!\");\n\n  auto method = std::get<2>(params);\n\n  using SolutionType = DenseColumnMatrixGeneric<typename std::tuple_element<0, In>::type::element_type::value_type>;\n  using AlgoTypeCG = SolveLinearSystemAlgorithmEigenCGImpl<SolutionType, CG>;\n  using AlgoTypeBiCG = SolveLinearSystemAlgorithmEigenCGImpl<SolutionType, BiCG>;\n\n  if (\"cg\" == method)\n    return solve<AlgoTypeCG, In, Out>(input, params);\n  else if (\"bicg\" == method)\n    return solve<AlgoTypeBiCG, In, Out>(input, params);\n  else\n  {\n    BOOST_THROW_EXCEPTION(AlgorithmProcessingException() << ErrorMessage(\"Need to upgrade Eigen for LSCG.\"));\n  }\n}\n\ntemplate <typename SolverType, typename In, typename Out>\nOut SolveLinearSystemAlgorithm::solve(const In& input, const Parameters& params) const\n{\n  auto A = std::get<0>(input);\n  auto b = std::get<1>(input);\n  double tolerance = std::get<0>(params);\n  int maxIterations = std::get<1>(params);\n\n  SolverType impl(b, tolerance, maxIterations);\n\n  typename SolverType::SolutionType x;\n  if (matrixIs::dense(A))\n  {\n    auto dense = castMatrix::toDense(A);\n    x = impl.solveWithEigen(*dense);\n  }\n  else if (matrixIs::sparse(A))\n  {\n    auto sparse = castMatrix::toSparse(A);\n    x = impl.solveWithEigen(*sparse);\n  }\n  else\n    BOOST_THROW_EXCEPTION(AlgorithmProcessingException() << ErrorMessage(\"solveWithEigen can only handle dense and sparse matrices.\"));\n\n  if (x.size() != 0)\n  {\n    auto solution(makeShared<typename SolverType::SolutionType>(x));\n    return Out(solution, impl.tolerance_, impl.maxIterations_);\n  }\n  else\n    BOOST_THROW_EXCEPTION(AlgorithmProcessingException() << ErrorMessage(\"solveWithEigen produced an empty solution.\"));\n}\n\nAlgorithmOutput SolveLinearSystemAlgorithm::run(const AlgorithmInput&) const\n{\n  throw 2;\n}\n", "meta": {"hexsha": "44162ac7b3a8f7f5eb2d94d59f7dcba27b2edc9b", "size": 5947, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/Math/SolveLinearSystemWithEigen.cc", "max_stars_repo_name": "kimjohn1/SCIRun", "max_stars_repo_head_hexsha": "62ae6cb632100371831530c755ef0b133fb5c978", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2015-02-09T22:42:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:14:50.000Z", "max_issues_repo_path": "src/Core/Algorithms/Math/SolveLinearSystemWithEigen.cc", "max_issues_repo_name": "kimjohn1/SCIRun", "max_issues_repo_head_hexsha": "62ae6cb632100371831530c755ef0b133fb5c978", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T19:39:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-27T20:28:45.000Z", "max_forks_repo_path": "src/Core/Algorithms/Math/SolveLinearSystemWithEigen.cc", "max_forks_repo_name": "kimjohn1/SCIRun", "max_forks_repo_head_hexsha": "62ae6cb632100371831530c755ef0b133fb5c978", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 64.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T17:51:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T07:08:08.000Z", "avg_line_length": 35.3988095238, "max_line_length": 135, "alphanum_fraction": 0.7484445939, "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186787341014, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4271084956566999}}
{"text": "/*\nProgram to translate text to DNA and vice versa\n*/\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <boost/random/mersenne_twister.hpp>\n//#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/program_options.hpp>\n#include \"../include/GF2M.hpp\"\n#include \"../include/DFT.hpp\"\n#include \"../include/helpers.hpp\"\n#include \"../include/encodedecode.hpp\"\n#include \"../include/ReedSolomon.hpp\"\n#include <string>\n#include <fstream>\n#include <streambuf>\n\nusing namespace std;\n\nnamespace po = boost::program_options;\n\nint main(int ac, char* av[])\n{\n\n\n// command line options\nint primer_length = 0;\nint numblocks = 1;\nbool rev = false;\nstring infile;\nstring fastq_infile;\nstring outfile;\nstring gtruthfile;\n\n\nunsigned N = 34;\nunsigned K = 32;\n\nunsigned n = 16383;\nunsigned k = 10977; // k = 0.67*n\n\nunsigned l = 4; // length of the index\nunsigned nuss = 12; // number of symbols of outer code per segment\n\nint opt;\n\npo::options_description desc(\"Allowed options\");\ndesc.add_options()\n    (\"help\", \"produce help message\")\n    (\"encode\", \"encode\")\n    (\"decode\", \"decode\")\n\t(\"singleseq\",\"singleseq\")\n\n    (\"disturb\", \"draw uniformly at random from the input lines, add errors to each line\")\n\t(\"input\",po::value<string>(&infile)->default_value(\"\"),\"inputfile\")\t\n\t(\"fastq_infile\",po::value<string>(&fastq_infile)->default_value(\"\"),\"fastq inputfile\")\t\n\t(\"output\",po::value<string>(&outfile)->default_value(\"\"),\"outputfile\")\t\n\t(\"groundtruth\",po::value<string>(&gtruthfile)->default_value(\"\"),\"groundtruthfile\")\t\n\t(\"reverse\", po::bool_switch(&rev), \"Fastq reverse sequences\")\n\t(\"primer_length\",po::value<int>(&primer_length)->default_value(0),\"primer_length\")\t\n\t\n\t(\"numblocks\",po::value<int>(&numblocks)->default_value(1),\"numblocks\")\t\n\t(\"n\",po::value<unsigned>(&n)->default_value(16383),\"n\")\t\n\t(\"k\",po::value<unsigned>(&k)->default_value(10977),\"k\")\t\n\t(\"N\",po::value<unsigned>(&N)->default_value(34),\"N\")\t\n\t(\"K\",po::value<unsigned>(&K)->default_value(32),\"K\")\t\n\t(\"l\",po::value<unsigned>(&l)->default_value(4),\"l\")\t\n\t(\"nuss\",po::value<unsigned>(&nuss)->default_value(12),\"nuss\")\n;\n\npo::variables_map vm;\npo::store(po::parse_command_line(ac, av, desc), vm);\npo::notify(vm);    \n\nif (vm.count(\"help\")) {\n    cout << desc << \"\\n\";\n    return 1;\n}\n\n\n///// parameters\n\ntypedef unsigned long long int uint;\n// inner code \nconst uint mi = 6;\nconst uint prim_poly = 91;\ntypedef GF2M<uint,mi,prim_poly> GFI; // GF(2^6) with primitive polynomail 91\nconst uint N_u = 63; // the underlying length of the shortened inner code\n\n\nGFI fai = GFI(2,0); // 64 + 2 = 1000010 = x + x^5\nDFT_FFT<GFI> dftgfi(N_u,fai,7,9); // 7*9 = 63\ntypedef RScode<GFI, DFT_FFT<GFI> > Innercode;\nInnercode innercode(N,K,fai,dftgfi,N_u);\n\n// list of primitive polynomials can be found here: https://www.partow.net/programming/polynomials/index.html\n\n//// parameter choices for outer code of length 16383\n///*\nconst unsigned Q = 127;\nconst unsigned P = 129;\nconst unsigned n_u = P*Q; // 16383 = 2^14 - 1, Q is prime and P = 3*43\nconst uint prim_poly_o = 16553; // primitive polynomial for 2^14\nconst unsigned mo = 14;\ntypedef GF2M<uint,mo,prim_poly_o> GFO;\nGFO fao = GFO(66,0); // 66 = 64 + 2 = 1000010 = x + x^5 // Element of order 16383\n//*/\n\n\n//// parameter choices for outer code of length 4095\n/*\nunsigned Q = 63;\nunsigned P = 65;\nunsigned n_u = 4095; // 2^12 - 1; // 2^12-1 = 5*3*3*7*13\nconst unsigned mo = 12;\nconst uint prim_poly_o = 4621; // primitive polynomial for GF(2^12), x^12 + x^9 + x^3 + x^2 + 1\ntypedef GF2M<uint,mo,prim_poly_o> GFO;\nGFO fao = GFO(10,0); // 9 = 64 + 2 = 1010 = x + x^3 // Element of order 4095; must have order 4095\n//cout << \"element has order:\" << fao.order() << endl; // check for order of element\n*/\n\n\nDFT_FFT<GFO> dftgfo(n_u,fao,P,Q); // Fourier transform for the outer code \n\ntypedef RScode<GFO,DFT_FFT<GFO> > Outercode;\nOutercode outercode(n,k,fao,dftgfo,n_u);\n\n\n\n// check all the parameter choices\n\nif (!vm.count(\"singleseq\")) {\nif (K*mi != nuss*mo+l*mi) {\n\tcerr << \"Must have: K*mi = nuss*mo + l*mi, where mi=6, mo=14, but got \" << K*mi << \", \" << nuss*mo+l*mi << endl;\t\n\treturn 1;\n}\n}\n\nif ( K > N) {\n\tcerr << \"Must have: K <= N\"  << endl;\t\n\treturn 1;\n}\n\nif ( k > n) {\n\tcerr << \"Must have: k <= n\"  << endl;\t\n\treturn 1;\n}\n\nif ( n > n_u) {\n\tcerr << \"Must have: n <= n_u\"  << endl;\t\n\treturn 1;\n}\n\nif ( N > N_u) {\n\tcerr << \"Must have: N <= N_u\"  << endl;\t\n\treturn 1;\n}\n\nif ( l*mi < log( numblocks*n )/log( 2 ) ) {\n\tcerr << \"Index has length \" << l*mi << \" bit, but require \" << log( numblocks*n )/log( 2 ) << \" bits\" << endl;\t\n\treturn 1;\n}\n\n\n\n// tell the user the parameter choices\n\ncout << \"--------------------------------\" << endl;\ncout << \"redundancy outer code: \" << float(n-k)/float(k)*100 << \"\\%\" << endl; // \" (= (n-k)/k)\" << endl;\ncout << \"redundancy inner code: \" << float(N-K)/float(K)*100 << \"\\%\" << endl; // \" (= (N-K)/K)\" << endl;\ncout << \"--------------------------------\" << endl;\n\n\n\n// encoder/decoder \nEnDecode< Innercode , Outercode > endecode(innercode,outercode,l,nuss);\nEnDecodeSingleSeq< Innercode > endecodesingleseq(innercode);\n\n/////////////////////// encode \nif (vm.count(\"encode\")) {\n\t\n\tcout << \"start encoding..\" << endl;\n\tif( infile == \"\" || outfile ==\"\"){\n\t\tcout << \"in/outfile not specified \" << endl; \n\t\treturn 0;\n\t}\n\tcout << \"infile:  \" << infile << endl;\n\tcout << \"outfile: \" << outfile << endl;\n\n\t// read data\n\tstd::ifstream t(infile.c_str());\n\tstd::string str((std::istreambuf_iterator<char>(t)),std::istreambuf_iterator<char>());\n\n\t// encode - determines the number of blocks required automatically\n\tvector<string> urn(n*numblocks);\n\t\n\tif( vm.count(\"singleseq\") ){\n\t\t// store only a signle sequence\n\t\tendecodesingleseq.encode(str, urn);\n\t\tnumblocks = 1;\n\t} else {\n\t\tendecode.encode(str, urn);\n\t\tnumblocks = endecode.numblocks; \n\t}\n\n\tif(numblocks*k*mo*nuss < str.size()*8){\n\t\tcerr << \"trying to store \" << str.size()*8 << \" bits, but can only store \" << numblocks*k*mo*nuss << \"many\" << endl;\t\n\t\treturn 1;\n\t}\n\n\tif( vm.count(\"singleseq\") ){\n\t\tcout << \"encoded \" << str.size() << \" Bytes to one DNA segment of length \" << urn[0].size() << endl;\n\t} else {\n\t\tcout << \"encoded \" << str.size() << \" Bytes to \" << numblocks << \" blocks, resulting in \"\n\t<< urn.size() << \" DNA segments of length \" << urn[0].size() << \" each.\" << endl;\n    }\n\n\tofstream out;\n\tout.open(outfile.c_str());\n\tfor(unsigned i=0;i<urn.size();++i) out << urn[i] << endl;\n\tout.close();\n\treturn 0;\n}\n\n\n/////////////////////// decode \nif (vm.count(\"decode\")) {\n\n\tif( (infile == \"\" && fastq_infile == \"\") ) {\t\n\t\tcout << \"infile not specified \" << endl; \n\t\treturn 0;\n\t}\n\t\n\tif( outfile ==\"\"){\n\t\tcout << \"outfile not specified \" << endl; \n\t\treturn 0;\n\t}\n\t\n\tif( numblocks==0 && !vm.count(\"singleseq\") ) {\n\t\tcout << \"numblocks not specified \" << endl; \n\t\treturn 0;\n\t}\n\t\n\t\n\tif(fastq_infile != \"\"){\n\t\tcout << \"fastq infile:  \" << fastq_infile << endl;\n\t} else {\n\t\tcout << \"infile:  \" << infile << endl;\n\t}\n\tcout << \"outfile: \" << outfile << endl;\n\tcout << \"numblocks: \"<<numblocks << endl; \n\n\tvector<string> drawnseg;\n\n\tif(infile != \"\"){\n\t\tcout << \"assume text file as input format\" << endl;\n\n\t\tstring sLine = \"\";\n\t\tifstream in;\n\t\tin.open(infile.c_str());\n\t\tif (in.fail()) {\n        \tcerr << \"Error when opening infile - does infile exist?\" << endl;\n\t\t\treturn 1;\n\t\t}\t\n\n\n\t\tunsigned ctr = 0;\t\n\t\twhile (!in.eof()){\n\t\t\tgetline(in, sLine);\n\t\t\t\n\t\t\tint seq_length = N*mi/2;\n\t\t\tif(sLine.size() >= seq_length + primer_length){\n\t\t\t\tsLine = sLine.substr(primer_length, seq_length);\n\t\t\t\tdrawnseg.push_back(sLine);\n\t\t\t\tctr++;\n\t\t\t}\n\t\t\tcout << \"\\rLines read: \" << ctr;\n\t\t}\n\t\tcout << endl;\n\t\t//drawnseg.resize(drawnseg.size()-1); // erase the last, empty line\n\t} else {\n\t\tcout << \"assume fastq file as input format\" << endl;\n\n\t\tint seq_length = N*mi/2;\n\t\tifstream in;\n\t\tin.open(fastq_infile.c_str());\n\t\tif(in.fail()){\n        \tcerr << \"Error when opening infile - does infile exist?\" << endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tstring sLine = \"\";\n\t\tvector<int> hist(400,0);\n\t\tunsigned totalctr = 0;\n\n\t\tint ctr = 0;\n\t\twhile (!in.eof()){\n\t\t\tgetline(in, sLine);\n\t\t\tctr++;\n\t\t\tif(ctr % 4 == 2){\n\t\t\t\thist[sLine.size()]++;\n\t\t\t\ttotalctr++;\n\t\t\t\tif(rev){\n\t\t\t\t\tflipvecdir(sLine);\n\t\t\t\t\tfliplett(sLine);\n\t\t\t\t}\n\n\t\t\t\tif(sLine.size() >= seq_length + primer_length){\n\t\t\t\t\tsLine = sLine.substr(primer_length, seq_length + primer_length );\n\t\t\t\t\tdrawnseg.push_back(sLine);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//if(ctr == 100000000) break;\n\t\t}\n\t\tin.close();\n\t}\n\t\n\t//\n\n\n\n\tstring recstr;\n\tcout << \"start decode..\" << endl;\t\n\t\n\tif( vm.count(\"singleseq\")){\n\t\t// store only a signle sequence\n\t\tendecodesingleseq.decode(recstr, drawnseg);\n\t} else {\n\t\tendecode.numblocks = numblocks;\n\t\tendecode.decode(recstr, drawnseg, gtruthfile);\n\t}\n\t\n\t\n\tofstream out;\n\tout.open(outfile.c_str());\n\tout << recstr;\n\tout.close();\n\tcout << \"Wrote file of length \" << recstr.size() << \" Bytes\" << endl;\n}\n\n////////////////////////// disturb\nif (vm.count(\"disturb\")) {\n\n\t// take M random draws uniformly at random and disturb those\n\n\tconst unsigned M = n*numblocks*6;\n\tconst float substprob = 0.0005; // substitution error probability\n\t//const unsigned M = n*numblocks*20;\n\t//const float substprob = 0.0005; // substitution error probability\n\tcout << \"disturb:\" << endl;\n\tcout << \"\\tDraw \" << M << \" many times\" << endl;\n\tcout << \"\\tsubstitution error probability \" << substprob << endl;\n\n\n\tif(infile == \"\" || outfile ==\"\") {\n\t\tcout << \"in/outfile not specified \" << endl; \n\t\treturn 0;\n\t}\n\tcout << \"infile:  \" << infile << endl;\n\tcout << \"outfile: \" << outfile << endl;\n\t\n\tvector<string> urn;\n\t\n\t\n\tstring sLine = \"\";\n\tifstream in;\n\tin.open(infile.c_str());\n\twhile (!in.eof()){\n\t\tgetline(in, sLine);\n\t\turn.push_back(sLine);\n\t}\n\turn.resize(urn.size()-1); // erase the last, empty line\n\t\n\tboost::mt19937 rng; \t\n\tboost::uniform_int<> unif(0,urn.size()-1); // distribution that maps to 0,..,urn.size()-1\n\tboost::uniform_int<> unif_N(0,N-1); // uniform distribution over {0,..,N-1}\n\tboost::uniform_int<> unif_4(0,4-1); // uniform distribution over {0,1,2,3}\n\tboost::bernoulli_distribution<> bern(substprob);\n\t//boost::bernoulli_distribution<> faircoin(0.5);\n\t\n\tchar nucl[] = \"ACGT\";\n\n\tvector<string> drawnseg(M);\n\t\n\tofstream out;\n\tout.open(outfile.c_str());\n\t\n\t// draw M times\n\tstring tmpstr;\n\tfor(unsigned i=0;i<M;++i){\n\t\tunsigned randind = unif(rng);\n\t\ttmpstr = urn[randind];\n\t\t\n\t\t// introduce errors\n\t\t// introduce on error per inner cw\n\t\tfor(unsigned j=0;j<1;++j){ \t\t\t\n\t\t\ttmpstr[unif_N(rng)] = nucl[unif_4(rng)];\n\t\t}\n\t\n\t\tunsigned ctr = 0;\n\t\tfor(unsigned j=0;j<tmpstr.size();++j)\n\t\t\tif(bern(rng)) {\n\t\t\t\ttmpstr[j] = nucl[unif_4(rng)];\n\t\t\t\tctr++;\n\t\t\t}\n\t\t\t//cout << ctr << endl;\n\t\t//if(faircoin(rng)) flipvecdir(tmpstr); // flip every second \n\n\t\t// write to file\n\t\tout << tmpstr;\n\t\tif(i!= M-1) out << endl;\n\t}\n\tout.close();\n\n}\n\n}\n", "meta": {"hexsha": "1458948cdcf60340c14a4741bad1789ad17eca84", "size": 10823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulate/texttodna.cpp", "max_stars_repo_name": "reinhardh/dna_rs_coding", "max_stars_repo_head_hexsha": "455e1a5182bf64281f54d434a4ed5ca456c2373e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2019-12-01T11:55:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T01:57:11.000Z", "max_issues_repo_path": "simulate/texttodna.cpp", "max_issues_repo_name": "reinhardh/dna_rs_coding", "max_issues_repo_head_hexsha": "455e1a5182bf64281f54d434a4ed5ca456c2373e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-26T09:13:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-26T15:19:01.000Z", "max_forks_repo_path": "simulate/texttodna.cpp", "max_forks_repo_name": "reinhardh/dna_rs_coding", "max_forks_repo_head_hexsha": "455e1a5182bf64281f54d434a4ed5ca456c2373e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-05T06:14:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T09:10:36.000Z", "avg_line_length": 25.6469194313, "max_line_length": 119, "alphanum_fraction": 0.615818165, "num_tokens": 3340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.42710849051900973}}
{"text": "//\n//  Copyright Toon Knapen and Kresimir Fresl 2003\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n\n#ifndef BOOST_BINDINGS_BLAS_BLAS2_HPP\n#define BOOST_BINDINGS_BLAS_BLAS2_HPP\n\n#include <boost/numeric/bindings/blas/blas2_overloads.hpp>\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/traits/transpose.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/type_traits.hpp>\n#include <cassert>\n\nnamespace boost { namespace numeric { namespace bindings { namespace blas {\n\n  // y <- alpha * op (A) * x + beta * y\n  // op (A) == A || A^T || A^H\n  // ! CAUTION this function assumes that all matrices involved are column-major matrices\n  template < typename matrix_type, typename vector_type_x, typename vector_type_y, typename value_type >\n  void gemv(const char TRANS,\n            const value_type& alpha,\n            const matrix_type &a,\n            const vector_type_x &x,\n            const value_type& beta,\n            vector_type_y &y\n            )\n  {\n    // precondition: matrix_type must be dense or dense_proxy\n    /* not all compilers can handle the traits\n    BOOST_STATIC_ASSERT( ( boost::is_same< typename mtraits::matrix_structure,\n                                           boost::numeric::bindings::traits::general_t\n                           >::value ) ) ;\n    */\n\n    const integer_t m = traits::matrix_size1( a ) ;\n    const integer_t n = traits::matrix_size2( a ) ;\n    assert ( traits::vector_size( x ) >= (TRANS == traits::NO_TRANSPOSE ? n : m) ) ;\n    assert ( traits::vector_size( y ) >= (TRANS == traits::NO_TRANSPOSE ? m : n) ) ;\n    const integer_t lda = traits::leading_dimension( a ) ;\n    const integer_t stride_x = traits::vector_stride( x ) ;\n    const integer_t stride_y = traits::vector_stride( y ) ;\n\n    const value_type *a_ptr = traits::matrix_storage( a ) ;\n    const value_type *x_ptr = traits::vector_storage( x ) ;\n    value_type *y_ptr = traits::vector_storage( y ) ;\n\n    detail::gemv( TRANS, m, n, alpha, a_ptr, lda, x_ptr, stride_x, beta, y_ptr, stride_y );\n  }\n\n  // A <- alpha * x * trans(y) ( outer product ), alpha, x and y are real-valued\n  // ! CAUTION this function assumes that all matrices involved are column-major matrices\n  template < typename vector_type_x, typename vector_type_y, typename value_type, typename matrix_type >\n  void ger( const value_type& alpha,\n            const vector_type_x &x,\n            const vector_type_y &y,\n            matrix_type &a\n            )\n  {\n    // precondition: matrix_type must be dense or dense_proxy\n    /* not all compilers can handle the traits\n    BOOST_STATIC_ASSERT( ( boost::is_same< typename mtraits::matrix_structure,\n                                           boost::numeric::bindings::traits::general_t\n                           >::value ) ) ;\n    */\n\n    const integer_t m = traits::matrix_size1( a ) ;\n    const integer_t n = traits::matrix_size2( a ) ;\n    assert ( traits::vector_size( x ) <= m ) ;\n    assert ( traits::vector_size( y ) <= n ) ;\n    const integer_t lda = traits::leading_dimension( a ) ;\n    const integer_t stride_x = traits::vector_stride( x ) ;\n    const integer_t stride_y = traits::vector_stride( y ) ;\n\n    const value_type *x_ptr = traits::vector_storage( x ) ;\n    const value_type *y_ptr = traits::vector_storage( y ) ;\n    value_type *a_ptr = traits::matrix_storage( a ) ;\n    \n    detail::ger( m, n, alpha, x_ptr, stride_x, y_ptr, stride_y, a_ptr, lda );\n  }\n/*\n  // A <- alpha * x * trans(y) ( outer product ), alpha, x and y are complex-valued \n  template < typename vector_type_x, typename vector_type_y, typename value_type, typename matrix_type >\n  void geru( const value_type& alpha,\n             const vector_type_x &x,\n             const vector_type_y &y,\n             matrix_type &a \n             )\n  {\n    // precondition: matrix_type must be dense or dense_proxy\n//    not all compilers can handle the traits\n//    BOOST_STATIC_ASSERT( ( boost::is_same< typename mtraits::matrix_structure,\n//                                           boost::numeric::bindings::traits::general_t\n//                           >::value ) ) ;\n\n\n//    BOOST_STATIC_ASSERT( ( boost::is_same< x.value_type(), FEMTown::Complex() >::value ) ) ;\n    const integer_t m = traits::matrix_size1( a ) ;\n    const integer_t n = traits::matrix_size2( a ) ;\n    assert ( traits::vector_size( x ) <= m ) ;\n    assert ( traits::vector_size( y ) <= n ) ;\n    const integer_t lda = traits::leading_dimension( a ) ;\n    const integer_t stride_x = traits::vector_stride( x ) ;\n    const integer_t stride_y = traits::vector_stride( y ) ;\n\n    const value_type *x_ptr = traits::vector_storage( x ) ;\n    const value_type *y_ptr = traits::vector_storage( y ) ;\n    value_type *a_ptr = traits::matrix_storage( a ) ;\n    \n    detail::geru( m, n, alpha, x_ptr, stride_x, y_ptr, stride_y, a_ptr, lda );\n  }\n*/\n  /*\n  // y <- alpha * A * x + beta * y \n  template < typename matrix_type, typename vector_type_x, typename vector_type_y >\n  void gemv(const typename traits::matrix_traits<matrix_type>::value_type &alpha,\n            const matrix_type &a, \n            const vector_type_x &x, \n            const typename traits::vector_traits<vector_type_y>::value_type &beta,\n            vector_type_y &y\n            )\n  {\n    gemv( traits::NO_TRANSPOSE, alpha, a, x, beta, y );\n  }\n\n\n  // y <- A * x\n  template < typename matrix_type, typename vector_type_x, typename vector_type_y >\n  void gemv(const matrix_type &a, const vector_type_x &x, vector_type_y &y)\n  {\n    typedef typename traits::matrix_traits<matrix_type>::value_type val_t;\n    gemv( traits::NO_TRANSPOSE, (val_t) 1, a, x, (val_t) 0, y );\n  }\n  */\n\n}}}}\n\n#endif // BOOST_BINDINGS_BLAS_BLAS2_HPP\n", "meta": {"hexsha": "cd315e6a279dbe7eb2014515252dcf3d468d2500", "size": 5817, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/blas/blas2.hpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/blas/blas2.hpp", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/blas/blas2.hpp", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6783216783, "max_line_length": 104, "alphanum_fraction": 0.6417397284, "num_tokens": 1473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.42697564699517804}}
{"text": "//\n// Created by yche on 12/17/17.\n//\n#include \"sling.h\"\n\n#include <boost/format.hpp>\n\n#include \"tbb/parallel_sort.h\"\n\n#include \"ground_truth/stat.h\"\n#include \"ground_truth/graph_yche.h\"\n#include \"ground_truth/yche_serialization.h\"\n#include \"util/log.h\"\n#include \"util/util.h\"\n\nconst double Sling::BACKEPS = 7.28e-4; //EPS / 23.;\nconst double Sling::K = 10.;\n\nint Sling::NUMTHREAD = std::thread::hardware_concurrency();\n//int Sling::NUMTHREAD = 1;\n\nusing namespace std::chrono;\n\nvoid Sling::init() {\n    first = new bool[g->n];\n    second = new bool[g->n];\n    memset(first, 0, sizeof(bool) * g->n);\n    memset(second, 0, sizeof(bool) * g->n);\n    for (int u = 0; u < g->n; ++u) {\n        if (!(first[u] = (g->inedge[u].size() <= K / BACKEPS))) {\n            second[u] = false;\n            continue;\n        }\n        int cnt = 0;\n        for (auto itr = g->inedge[u].begin(); itr != g->inedge[u].end(); ++itr) {\n            cnt += g->inedge[*itr].size();\n        }\n        second[u] = (cnt <= K / BACKEPS);\n    }\n    sqrtct[0] = 1.;\n    for (int i = 1; i < 20; ++i)\n        sqrtct[i] = sqrtc * sqrtct[i - 1];\n}\n\n//########################### indexing 1st: Diagonal Correction Matrix ####################################\ndouble Sling::calcDi(int i, double eps, bool &early, int &R, int tid) {\n    R = 0;\n    early = true;\n    if (g->inedge[i].size() == 0) return 1.;\n    if (g->inedge[i].size() == 1) {\n        if (g->inedge[i][0] == i) return 1.;\n        else return 1. - c;\n    }\n    return calcDi_1(i, eps, early, R, tid);\n}\n\ndouble Sling::calcDi_1(int i, double eps, bool &early, int &R, int tid) {\n    const auto &in_i = g->inedge[i];\n    const vector<int> *inedge = g->inedge;\n    const int isize = in_i.size();\n    eps = eps * (double) isize / (double) (isize - 1) / c;\n//    int Rs = 14. / 3. / eps * 2. * log(2 * g->n) / log(2.71828);\n//    constexpr double failure_probability = 0.01;\n\n    int Rs = 14. / 3. / eps * log(4.0 * g->n / failure_probability) / log(2.71828);\n    int X = 0;\n    double cc = c * (1l << 32);\n    for (; R < Rs; ++R) {\n        int rx = gen.rand(tid) % isize;\n        int ry = gen.rand(tid) % (isize - 1);\n        if (ry >= rx) ++ry;\n        int x = in_i[rx];\n        int y = in_i[ry];\n        do {\n            if (inedge[x].empty() || inedge[y].empty())\n                break;\n            x = inedge[x][gen.rand(tid) % inedge[x].size()];\n            y = inedge[y][gen.rand(tid) % inedge[y].size()];\n            if (x == y) {\n                ++X;\n                break;\n            }\n        } while (gen.rand(tid) < cc);\n    }\n    if (X / (double) R <= eps) {\n        return 1. - c * c * (X / (double) R) * (double) (isize - 1) / (double) isize - c / (double) isize;\n    }\n    double upp = X / (double) R + sqrt(eps * X / (double) R);\n//    int Rl = (2 * upp + 2. / 3. * eps) / (eps * eps) * log(2 * g->n) / log(2.71828);\n    int Rl = (2 * upp + 2. / 3. * eps) / (eps * eps) * log(4.0 * g->n / failure_probability) / log(2.71828);\n    for (; R < Rl; ++R) {\n        int rx = gen.rand(tid) % isize;\n        int ry = gen.rand(tid) % (isize - 1);\n        if (ry >= rx) ++ry;\n        int x = in_i[rx];\n        int y = in_i[ry];\n        do {\n            if (inedge[x].empty() || inedge[y].empty())\n                break;\n            x = inedge[x][gen.rand(tid) % inedge[x].size()];\n            y = inedge[y][gen.rand(tid) % inedge[y].size()];\n            if (x == y) {\n                ++X;\n                break;\n            }\n        } while (gen.rand(tid) < cc);\n    }\n    early = false;\n    return 1. - c * c * (X / (double) R) * (double) (isize - 1) / (double) isize - c / (double) isize;\n}\n\nvoid Sling::t_calcD(double eps, mutex *lock, int *cursor, int tid) {\n    int i, u;\n    while (true) {\n        lock->lock();\n        i = *cursor;\n        u = ((*cursor) += BLOCKSIZE);\n        lock->unlock();\n        if (i >= g->n)\n            return;\n        if (u > g->n) u = g->n;\n        for (; i < u; ++i) {\n            int RWCNT;\n            bool early;\n            double di = calcDi(i, eps / c, early, RWCNT, tid);\n            d[i] = di;\n        }\n    }\n}\n\nvoid __Sling_t_calcD(Sling *sim, double eps, mutex *lock, int *cursor, int tid) {\n    sim->t_calcD(eps, lock, cursor, tid);\n}\n\nvoid Sling::calcD(double eps) {\n    if (d != NULL) delete[] d;\n    d = new double[g->n];\n    int cursor = 0;\n    mutex lock;\n    vector<thread> threads;\n    for (int i = 0; i < NUMTHREAD - 1; ++i)\n        threads.emplace_back(__Sling_t_calcD, this, eps, &lock, &cursor, i);\n    t_calcD(eps, &lock, &cursor, NUMTHREAD - 1);\n    for (int t = 0; t < NUMTHREAD - 1; ++t)\n        threads[t].join();\n    d_bar = 0.;\n    for (int i = 0; i < g->n; ++i)\n        d_bar += d[i];\n    d_bar /= g->n;\n}\n\n//########################### indexing 2nd: Backward Propagation ####################################\nmap<pair<int, int>, double, PairCmp> Sling::pushback(int u, double eps, int tid) {\n    map<pair<int, int>, double, PairCmp> p;\n    gmap<int, double> pt;\n    gmap<int, double> ptt;\n    gset<int> s;\n    deque<int> q;\n    deque<int> qq;\n\n    int t = 0;\n    pt[u] = 1.;\n    q.push_back(u);\n\n    while (!q.empty()) {\n        int v = q.front();\n        double puvt = pt[v];;\n        p[make_pair(v, t)] = puvt;\n        for (unsigned i = 0; i < g->edge[v].size(); ++i) {\n            int vv = g->edge[v][i];\n            double x = ptt[vv] += puvt * sqrtc / (double) g->inedge[vv].size();\n            if (x > eps)// || (t < 2 && x > eps / K))\n            {\n                if (s.find(vv) == s.end()) {\n                    qq.push_back(vv);\n                    s.insert(vv);\n                }\n            }\n        }\n        q.pop_front();\n        if (q.empty()) {\n            s.clear();\n            pt.swap(ptt);\n            ptt.clear();\n            q.swap(qq);\n            qq.clear();\n            ++t;\n        }\n    }\n    p.erase(make_pair(u, 0));\n    return p;\n}\n\nvoid Sling::t_backward(double eps, mutex *tasklock, int *cursor, int tid, mutex *plock) {\n    int s, t;\n//    vector<tuple<int, int, int, double>> vec;\n    while (true) {\n//        vec.clear();\n        tasklock->lock();\n        s = *cursor;\n        t = ((*cursor) += BLOCKSIZE);\n        tasklock->unlock();\n\n        if (s >= g->n) return;\n        if (t > g->n) t = g->n;\n\n        for (int v = s; v < t; ++v) {\n            auto pv = pushback(v, eps, tid);\n            for (auto itr = pv.begin(); itr != pv.end(); ++itr) {\n                if (itr->second >= eps || (itr->first.second < 2 && itr->second >= eps / K)) {\n                    int u = itr->first.first;\n                    int t = itr->first.second;\n                    double value = itr->second;\n                    if (t == 1 && first[u]) continue;\n                    if (t == 2 && second[u]) continue;\n\n//                    p.push_back(make_tuple(u, t, v, value));\n                    con_vec_p.push_back(make_tuple(u, t, v, value));\n//                    con_vec_p.emplace_back(u, t, v, value);\n                }\n            }\n        }\n    }\n}\n\nvoid __Sling_t_backward(Sling *sim, double eps, mutex *tasklock, int *cursor, int tid, mutex *plock) {\n    sim->t_backward(eps, tasklock, cursor, tid, plock);\n}\n\nvoid Sling::backward(double eps) {\n//    Sling::NUMTHREAD = 1;\n    log_info(\"Backward Multi Threading: %d\", Sling::NUMTHREAD);\n    int plockNum = (g->n - 1) / BLOCKSIZE + 1;\n    auto *plock = new mutex[plockNum];\n    mutex tasklock;\n    int cursor = 0;\n//    if (!p.empty()) { p.clear(); }\n//    p.reserve(2339768660l);\n\n    if (!con_vec_p.empty()) { con_vec_p.clear(); }\n//    con_vec_p.reserve(2339768660l);\n    con_vec_p.reserve(233976866l);\n\n    vector<thread> threads;\n    for (int i = 0; i < NUMTHREAD - 1; ++i)\n        threads.emplace_back(__Sling_t_backward, this, eps, &tasklock, &cursor, i, plock);\n    t_backward(eps, &tasklock, &cursor, NUMTHREAD - 1, plock);\n    for (int t = 0; t < NUMTHREAD - 1; ++t)\n        threads[t].join();\n    delete[] plock;\n    cerr << \"sort\" << endl;\n//    sort(p.begin(), p.end(), cmpTuple);\n    tbb::parallel_sort(con_vec_p.begin(), con_vec_p.end(), cmpTuple);\n    cerr << \"sort finished\" << endl;\n    pstart.resize(g->n + 1);\n    pstart[0] = 0;\n    int x = 1;\n    for (long long i = 0; i < con_vec_p.size(); ++i) {\n        if (std::get<0>(con_vec_p[i]) >= x) {\n            for (; x <= std::get<0>(con_vec_p[i]); ++x)\n                pstart[x] = i;\n        }\n    }\n    for (; x <= g->n; ++x)\n        pstart[x] = con_vec_p.size();\n    p = vector<tuple<int, int, int, double>>{begin(con_vec_p), end(con_vec_p)};\n}\n\n///----------------------------- 1st: single pair\ndouble Sling::simrank(int u, int v) {\n    assert(!p.empty() && d != nullptr);\n    if (u == v) return 1.;\n    google::sparse_hash_map<pair<int, int>, double, PairHash> pu;\n    gmap<pair<int, int>, double, PairHash> pv;\n    gmap<pair<int, int>, double, PairHash> ppu;\n    gmap<pair<int, int>, double, PairHash> ppv;\n    for (long long i = pstart[u]; i < pstart[u + 1]; ++i) {\n        pu[make_pair(std::get<1>(p[i]), std::get<2>(p[i]))] = std::get<3>(p[i]);\n    }\n    for (long long i = pstart[v]; i < pstart[v + 1]; ++i) {\n        pv[make_pair(std::get<1>(p[i]), std::get<2>(p[i]))] = std::get<3>(p[i]);\n    }\n\n    int cnt = 0;\n    int thr = 1. / sqrt(BACKEPS);\n    for (long long i = pstart[u]; i < pstart[u + 1] && cnt < thr; ++i) {\n        int t = std::get<1>(p[i]);\n        int x = std::get<2>(p[i]);\n        if (g->inedge[x].size() > thr || g->inedge[x].empty()) continue;\n        ++cnt;\n        for (auto xitr = g->inedge[x].begin(); xitr != g->inedge[x].end(); ++xitr) {\n            if (pu.find(make_pair(t + 1, *xitr)) == pu.end())\n                ppu[make_pair(t + 1, *xitr)] += std::get<3>(p[i]) * c / g->inedge[x].size();\n        }\n    }\n    cnt = 0;\n    for (long long i = pstart[v]; i < pstart[v + 1] && cnt < thr; ++i) {\n        int t = std::get<1>(p[i]);\n        int x = std::get<2>(p[i]);\n        if (g->inedge[x].size() > thr || g->inedge[x].empty()) continue;\n        ++cnt;\n        for (auto xitr = g->inedge[x].begin(); xitr != g->inedge[x].end(); ++xitr) {\n            if (pv.find(make_pair(t + 1, *xitr)) == pv.end())\n                ppv[make_pair(t + 1, *xitr)] += std::get<3>(p[i]) * c / g->inedge[x].size();\n        }\n    }\n    for (auto itr = ppu.begin(); itr != ppu.end(); ++itr) {\n        pu[itr->first] = itr->second;\n    }\n    for (auto itr = ppv.begin(); itr != ppv.end(); ++itr) {\n        pv[itr->first] = itr->second;\n    }\n    if (first[u]) {\n        for (auto itr = g->inedge[u].begin(); itr != g->inedge[u].end(); ++itr) {\n            pu[make_pair(1, *itr)] = sqrtc / g->inedge[u].size();\n        }\n    }\n    if (second[u]) {\n        for (auto uitr = g->inedge[u].begin(); uitr != g->inedge[u].end(); ++uitr) {\n            int v = *uitr;\n            for (auto vitr = g->inedge[v].begin(); vitr != g->inedge[v].end(); ++vitr) {\n                pu[make_pair(2, *vitr)] += c / g->inedge[u].size() / g->inedge[v].size();\n            }\n        }\n    }\n    if (first[v]) {\n        for (auto itr = g->inedge[v].begin(); itr != g->inedge[v].end(); ++itr) {\n            pv[make_pair(1, *itr)] = sqrtc / g->inedge[v].size();\n        }\n    }\n    if (second[v]) {\n        for (auto vitr = g->inedge[v].begin(); vitr != g->inedge[v].end(); ++vitr) {\n            int vv = *vitr;\n            for (auto vitr = g->inedge[vv].begin(); vitr != g->inedge[vv].end(); ++vitr) {\n                pv[make_pair(2, *vitr)] += c / g->inedge[v].size() / g->inedge[vv].size();\n            }\n        }\n    }\n    double sim = 0.;\n    for (auto uitr = pu.begin(); uitr != pu.end(); ++uitr) {\n        auto vitr = pv.find(uitr->first);\n        if (vitr == pv.end())\n            continue;\n        sim += uitr->second * d[uitr->first.second] * vitr->second;\n    }\n    return sim;\n}\n\n// TODO\n///----------------------------- 2nd: single source\nvector<double> Sling::simrank(int u) {\n    assert(!p.empty() && d != NULL);\n    map<pair<int, int>, double, PairCmp> pu;\n    for (long long i = pstart[u]; i < pstart[u + 1]; ++i)\n        pu[make_pair(std::get<1>(p[i]), std::get<2>(p[i]))] = std::get<3>(p[i]);\n    gmap<pair<int, int>, double, PairHash> ppu;\n    int cnt = 0;\n    int thr = 1. / sqrt(BACKEPS);\n    for (long long i = pstart[u]; i < pstart[u + 1] && cnt < thr; ++i) {\n        int t = std::get<1>(p[i]);\n        int x = std::get<2>(p[i]);\n        if (g->inedge[x].size() > thr || g->inedge[x].empty()) continue;\n        ++cnt;\n        for (auto xitr = g->inedge[x].begin(); xitr != g->inedge[x].end(); ++xitr) {\n            if (pu.find(make_pair(t + 1, *xitr)) == pu.end())\n                ppu[make_pair(t + 1, *xitr)] += std::get<3>(p[i]) * c / g->inedge[x].size();\n        }\n    }\n    for (auto itr = ppu.begin(); itr != ppu.end(); ++itr) {\n        pu[itr->first] = itr->second;\n    }\n    if (second[u]) {\n        for (auto uitr = g->inedge[u].begin(); uitr != g->inedge[u].end(); ++uitr) {\n            int v = *uitr;\n            for (auto vitr = g->inedge[v].begin(); vitr != g->inedge[v].end(); ++vitr) {\n                pu[make_pair(2, *vitr)] += c / g->inedge[u].size() / g->inedge[v].size();\n            }\n        }\n    }\n    if (first[u]) {\n        for (auto itr = g->inedge[u].begin(); itr != g->inedge[u].end(); ++itr) {\n            pu[make_pair(1, *itr)] = sqrtc / g->inedge[u].size();\n        }\n    }\n    vector<double> sim(g->n, 0.);\n    vector<double> q;\n    vector<double> qq;\n    deque<int> s;\n    deque<int> ss;\n    for (int t = 1;; ++t) {\n        auto start = pu.lower_bound(make_pair(t, 0));\n        if (start == pu.end())\n            break;\n        auto end = pu.lower_bound(make_pair(t + 1, 0));\n        if (start == end) continue;\n        q.clear();\n        q.resize(g->n, 0.);\n        qq.clear();\n        qq.resize(g->n, 0.);\n        s.clear();\n        ss.clear();\n        int TTT = g->n / 10;\n        for (; start != end; ++start) {\n            q[start->first.second] = start->second * d[start->first.second];\n            s.push_back(start->first.second);\n        }\n        double eps = sqrtct[t] * BACKEPS;\n        for (int l = 1; l < t; ++l) {\n            if (s.size() > TTT) {\n                for (int u = 0; u < g->n; ++u) {\n                    if (q[u] <= eps) continue;\n                    for (auto vitr = g->edge[u].begin(); vitr != g->edge[u].end(); ++vitr) {\n                        int v = *vitr;\n                        qq[v] += sqrtc * q[u] / (double) g->inedge[v].size();\n                    }\n                }\n                q.swap(qq);\n                qq.clear();\n                qq.resize(g->n, 0.);\n            } else {\n                for (auto uitr = s.begin(); uitr != s.end(); ++uitr) {\n                    int u = *uitr;\n                    for (auto vitr = g->edge[u].begin(); vitr != g->edge[u].end(); ++vitr) {\n                        int v = *vitr;\n                        double inc = sqrtc * q[u] / (double) g->inedge[v].size();\n                        double x = qq[v] += inc;\n                        if (x > eps && x <= eps + inc) {\n                            ss.push_back(v);\n                        }\n                    }\n                }\n                q.swap(qq);\n                qq.clear();\n                qq.resize(g->n, 0.);\n                s.swap(ss);\n                ss.clear();\n            }\n        }\n        if (s.size() > TTT) {\n            for (int u = 0; u < g->n; ++u) {\n                if (q[u] <= eps) continue;\n                for (auto vitr = g->edge[u].begin(); vitr != g->edge[u].end(); ++vitr) {\n                    int v = *vitr;\n                    sim[v] += sqrtc * q[u] / (double) g->inedge[v].size();\n                }\n            }\n        } else {\n            for (auto uitr = s.begin(); uitr != s.end(); ++uitr) {\n                int u = *uitr;\n                for (auto vitr = g->edge[u].begin(); vitr != g->edge[u].end(); ++vitr) {\n                    int v = *vitr;\n                    sim[v] += sqrtc * q[u] / (double) g->inedge[v].size();\n                }\n            }\n        }\n    }\n\n    sim[u] = 1.;\n    return sim;\n}\n\nstring Sling::get_file_path_base() {\n    exec(string(\"mkdir -p \" + SLING_INDEX_DIR).c_str());\n    string file_path =\n            SLING_INDEX_DIR + \"/\" + boost::str(boost::format(\"RLP_%s-%.3f-%.6f-%.6f\") % g_name % c % eps_d % theta);\n    return file_path;\n}\n\nvoid Sling::build_or_load_index() {\n    string d_file_path = get_file_path_base() + \".d\";\n    string p_file_path = get_file_path_base() + \".p\";\n    string pstart_file_path = get_file_path_base() + \".pstart\";\n    if (file_exists(d_file_path) && file_exists(p_file_path) && file_exists(pstart_file_path)) {\n        log_info(\"indexing exists.......\");\n        YcheSerializer serializer;\n        log_info(\"d_file_path: %s\", d_file_path.c_str());\n        log_info(\"p_file_path: %s\", p_file_path.c_str());\n        FILE *pFile = fopen(d_file_path.c_str(), \"r\");\n        size_t tmp;\n        serializer.read_array_into_ref(pFile, d, tmp);\n        log_info(\"d size: %s\", to_string(tmp).c_str());\n        fclose(pFile);\n\n        FILE *pFile2 = fopen(p_file_path.c_str(), \"r\");\n        serializer.read_tuple_vec(pFile2, p);\n        fclose(pFile2);\n        log_info(\"p size: %s\", to_string(p.size()).c_str());\n\n        FILE *pFile3 = fopen(pstart_file_path.c_str(), \"r\");\n        serializer.read_vec(pFile3, pstart);\n        fclose(pFile3);\n    } else {\n        //  build the index\n        cout << \"indexing...\" << endl;\n\n        auto tmp_start = std::chrono::high_resolution_clock::now();\n        calcD(eps_d);\n        auto tmp_end = std::chrono::high_resolution_clock::now();\n\n        cout << \"finish calcD \" << float(duration_cast<microseconds>(tmp_end - tmp_start).count()) / (pow(10, 6))\n             << \" s\\n\";\n        tmp_start = std::chrono::high_resolution_clock::now();\n        backward(theta);\n        tmp_end = std::chrono::high_resolution_clock::now();\n\n        cout << \"finish backward \" << float(duration_cast<microseconds>(tmp_end - tmp_start).count()) / (pow(10, 6))\n             << \" s\\n\";\n        cout << \"mem size:\" << getValue() << endl;\n\n        cout << \"store index.......\" << endl;\n        // store indexing d\n        YcheSerializer serializer;\n        FILE *pFile = fopen(d_file_path.c_str(), \"wb\");\n        serializer.write_array(pFile, d, static_cast<size_t>(g->n));\n        fclose(pFile);\n        // store indexing p\n        FILE *pFile2 = fopen(p_file_path.c_str(), \"wb\");\n        serializer.write_tuple_vec(pFile2, p);\n        fclose(pFile2);\n        // store indexing pstart\n\n        FILE *pFile3 = fopen(pstart_file_path.c_str(), \"wb\");\n        serializer.write_vec(pFile3, pstart);\n        fclose(pFile2);\n    }\n}\n", "meta": {"hexsha": "9ef8b5aeac516950aa13bb9674f8145e2a5cfeeb", "size": 18559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SPS-Variants/sling/sling.cpp", "max_stars_repo_name": "RapidsAtHKUST/SimRank", "max_stars_repo_head_hexsha": "3a601b08f9a3c281e2b36b914e06aba3a3a36118", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-04-14T23:17:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T12:34:04.000Z", "max_issues_repo_path": "SPS-Variants/sling/sling.cpp", "max_issues_repo_name": "RapidsAtHKUST/SimRank", "max_issues_repo_head_hexsha": "3a601b08f9a3c281e2b36b914e06aba3a3a36118", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SPS-Variants/sling/sling.cpp", "max_forks_repo_name": "RapidsAtHKUST/SimRank", "max_forks_repo_head_hexsha": "3a601b08f9a3c281e2b36b914e06aba3a3a36118", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-17T16:26:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-17T16:26:50.000Z", "avg_line_length": 35.2163187856, "max_line_length": 116, "alphanum_fraction": 0.4675359664, "num_tokens": 5735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.42697563900267615}}
{"text": "#ifndef MATHLEXER_HPP\n#define MATHLEXER_HPP\n\n#include <iostream>\n#include <memory>\n#include <sstream>\n#include <vector>\n\n#include <boost/lexical_cast.hpp>\n\nnamespace simple_interpreter {\n\nstruct Token\n{\n   enum Type\n   {\n      integer,\n      plus,\n      minus,\n      lparen,\n      rparen\n   } type;\n\n   std::string text;\n\n   Token(const Type t, const std::string& str) : type(t), text(str)\n   {\n   }\n\n   friend std::ostream&\n   operator<<(std::ostream& os, const Token& token)\n   {\n      os << \"`\" << token.text << \"`\";\n      return os;\n   }\n};\n\n\nstd::vector< Token >\nlex(const std::string text)\n{\n   std::vector< Token > tokens;\n   for (size_t charIdx = 0; charIdx < text.size(); ++charIdx)\n   {\n      switch (text[charIdx])\n      {\n         case '+':\n            tokens.emplace_back(Token::plus, \"+\");\n            break;\n         case '-':\n            tokens.emplace_back(Token::minus, \"-\");\n            break;\n         case '(':\n            tokens.emplace_back(Token::lparen, \"(\");\n            break;\n         case ')':\n            tokens.emplace_back(Token::rparen, \")\");\n            break;\n         default:\n            if (std::isdigit(text[charIdx]))\n            {\n               std::ostringstream buffer;\n               buffer << text[charIdx];\n               for (size_t i = charIdx + 1; i < text.size(); ++i)\n               {\n                  if (std::isdigit(text[i]))\n                  {\n                     buffer << text[i];\n                     ++charIdx;\n                  }\n                  else\n                  {\n                     break;\n                  }\n               }\n\n               tokens.emplace_back(Token::integer, buffer.str());\n            }\n            else\n            {\n               throw std::runtime_error{std::string(\"error: Unexpected token: `\") + text[charIdx] + '`'};\n            }\n      }\n   }\n\n   return tokens;\n}\n\n\nstruct Element\n{\n   virtual int\n   eval() const = 0;\n};\n\n\nstruct Integer : Element\n{\n   int value;\n\n   Integer(const int newVal) : value(newVal)\n   {\n   }\n\n   int\n   eval() const override\n   {\n      return value;\n   }\n};\n\n\nstruct BinaryOperation : Element\n{\n   enum Type\n   {\n      addition,\n      subtraction\n   } type;\n\n   std::shared_ptr< Element > lhs, rhs;\n\n   int\n   eval() const override\n   {\n      switch (type)\n      {\n         case addition:\n            return lhs->eval() + rhs->eval();\n         case subtraction:\n            return lhs->eval() - rhs->eval();\n      }\n      return 0;\n   }\n};\n\n\nstd::shared_ptr< Element >\nparse(const std::vector< Token >& tokens)\n{\n   auto rootOp = std::make_shared< BinaryOperation >();\n\n   bool haveLhs{false};\n\n   for (size_t tokenIdx = 0; tokenIdx < tokens.size(); ++tokenIdx)\n   {\n      const auto& token = tokens[tokenIdx];\n      switch (token.type)\n      {\n         case Token::integer:\n         {\n            const int value = boost::lexical_cast< int >(token.text);\n            auto integer = std::make_shared< Integer >(value);\n            if (!haveLhs)\n            {\n               rootOp->lhs = integer;\n               haveLhs = true;\n            }\n            else\n            {\n               rootOp->rhs = integer;\n            }\n            break;\n         }\n         case Token::minus:\n         {\n            rootOp->type = BinaryOperation::subtraction;\n            break;\n         }\n         case Token::plus:\n         {\n            rootOp->type = BinaryOperation::addition;\n            break;\n         }\n         case Token::lparen:\n         {\n            bool rparenFound{false};\n            size_t rparenIdx = tokenIdx + 1;\n            for (; rparenIdx < tokens.size(); ++rparenIdx)\n            {\n               if (tokens[rparenIdx].type == Token::rparen)\n               {\n                  rparenFound = true;\n                  break;\n               }\n               else if (tokens[rparenIdx].type == Token::lparen)\n               {\n                  throw std::runtime_error{\"error: Nested parens not supported yet\"};\n               }\n            }\n            if (rparenFound)\n            {\n               std::vector< Token > subExpression{tokens.begin() + tokenIdx + 1, tokens.begin() + rparenIdx};\n               auto element = parse(subExpression);\n               if (!haveLhs)\n               {\n                  rootOp->lhs = element;\n                  haveLhs = true;\n               }\n               else\n               {\n                  rootOp->rhs = element;\n               }\n               tokenIdx = rparenIdx;\n            }\n            else\n            {\n               throw std::runtime_error{\"error: Missing `)`\"};\n            }\n            break;\n         }\n         case Token::rparen:\n         {\n            throw std::runtime_error{\"error: `)` should be ignored\"};\n            break;\n         }\n      }\n   }\n\n\n   return rootOp;\n}\n\n} // namespace simple_interpreter\n\n#endif // MATHLEXER_HPP\n", "meta": {"hexsha": "f3984a34568b0c9d8b6764fa99a9438bb40543b6", "size": 4849, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Interpreter/SimpleMathInterpreter.hpp", "max_stars_repo_name": "fawcio/design_patters_examples", "max_stars_repo_head_hexsha": "9393b53ca542255970bfdb7ce8e3978e55398cd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Interpreter/SimpleMathInterpreter.hpp", "max_issues_repo_name": "fawcio/design_patters_examples", "max_issues_repo_head_hexsha": "9393b53ca542255970bfdb7ce8e3978e55398cd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Interpreter/SimpleMathInterpreter.hpp", "max_forks_repo_name": "fawcio/design_patters_examples", "max_forks_repo_head_hexsha": "9393b53ca542255970bfdb7ce8e3978e55398cd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3612334802, "max_line_length": 109, "alphanum_fraction": 0.4499896886, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679928, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.4269756262060198}}
{"text": "#include <hdf5.h>\n#include <omp.h>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <Eigen/Sparse>\n#include <boost/filesystem.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/program_options.hpp>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <stdexcept>\n\n#include \"bte_config.h\"\n#include \"aux/filtered_range.hpp\"\n#include \"aux/message.hpp\"\n#include \"aux/timer.hpp\"\n#include \"base/numbers.hpp\"\n#include \"collision_tensor/assembly/gain.hpp\"\n#include \"collision_tensor/collision_tensor_factory.hpp\"\n#include \"collision_tensor/collision_tensor_galerkin.hpp\"\n#include \"collision_tensor/time_stepping/rk4.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n#include \"post_processing/energy.hpp\"\n#include \"post_processing/mass.hpp\"\n#include \"post_processing/momentum.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n#include \"spectral/utility/utility.hpp\"\n\nusing namespace std;\nusing namespace boltzmann;\nnamespace po = boost::program_options;\n\ntypedef SpectralBasisFactoryKS basis_factory_t;\n\nint main(int argc, char* argv[])\n{\n  boltzmann::Timer<> timer;\n  double beta, dt;\n  int nsteps;\n  string tensor_file;\n  bool adaptiveL, verbose;\n\n  po::options_description options(\"options\");\n  options.add_options()\n      (\"help\", \"produce help message\")\n      (\"beta,b\", po::value<double>(&beta)->default_value(2), \"beta\")\n      (\"dt,t\", po::value<double>(&dt)->default_value(0.001), \"delta t\")\n      (\"nsteps,n\", po::value<int>(&nsteps)->default_value(200), \"#timesteps\")\n      (\"adapt,a\", po::value<bool>(&adaptiveL)->default_value(false), \"use adaptive L-range\")\n      (\"ct,T\", po::value<string>(&tensor_file),\n      \"path to tensor file \\n the files `spectral_basis.desc` and \\n `spectral_basis_test.desc` \"\n      \"must reside in the same directory\")\n      (\"init,i\", po::value<string>()->required(), \"coefficients hdf5 in Polar Laguerre basis\")\n      (\"ifdata\", po::value<string>()->default_value(\"coeffs\"), \" path to data in HDF5 file `if`\")\n      (\"verbose,v\", po::value<bool>(&verbose)->default_value(false), \"verbose output\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    cout << options << \"\\n\";\n    return 0;\n  }\n\n  std::string version_id = GIT_SHA1;\n  cout << \"VersionID: \" << version_id << \"@\" << GIT_BNAME << std::endl;\n  cout << \"CMD:\\n\";\n  for (int i = 0; i < argc; ++i) {\n    cout << argv[i] << \"\\t\";\n  }\n  cout << \"\\n\\n\\n\";\n\n  cout << \"Command line parameters::\\n\"\n       << right << setw(15) << \"beta\" << setw(12) << beta << endl\n       << right << setw(15) << \"dt\" << setw(12) << dt << \"\\n\\n\\n\";\n\n  typedef typename basis_factory_t::basis_type basis_type;\n  typedef boost::filesystem::path path_t;\n\n  // load spectral basis\n  basis_type trial_basis;\n  path_t tensor_fpath(tensor_file.c_str());\n  string trial_basis_fname = (tensor_fpath.parent_path() / path_t(\"spectral_basis.desc\")).string();\n  basis_factory_t::create(trial_basis, trial_basis_fname);\n\n  // read tensor from file\n  timer.start();\n  CollisionTensorGalerkin ct(trial_basis);\n  ct.read_hdf5(tensor_file.c_str());\n  print_timer(timer.stop(), \"read collision tensor from file\");\n  cout << \"------------------------------\\n\";\n\n  const int N = trial_basis.n_dofs();\n  Eigen::VectorXd coeffs(N);\n  string fname = vm[\"init\"].as<string>();\n  hid_t h5_init = H5Fopen(fname.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT);\n  eigen2hdf::load(h5_init, vm[\"ifdata\"].as<string>(), coeffs);\n\n  cout << \"---------- MOMENTSs ----------\\n\";\n  Mass mass;\n  mass.init(trial_basis);\n  double m0 = mass.compute(coeffs.data());\n  cout << \"\\t mass = \" << m0 << endl;\n\n  Energy energy;\n  energy.init(trial_basis);\n  energy.compute(coeffs.data());\n\n  Momentum momentum;\n  momentum.init(trial_basis);\n  momentum.compute(coeffs.data());\n  cout << \"\\t energy = \" << energy.compute(coeffs.data()) << endl;\n\n  // ------------------------------------------------------------\n  // TIME STEPPING\n  typedef Eigen::VectorXd vec_t;\n  vec_t out(N);\n  hg::RK4<> rk4(N);\n  const double tol = 1e-10;\n  auto find_relevant_range = [&](const double* solution) {\n    const int L = spectral::get_max_l(trial_basis);\n    typedef typename basis_type::elem_t elem_t;\n    typedef typename basis_factory_t::fa_type angular_elem_t;\n    // start from l=Lmax until  coefficients are above threshold\n    const int llower_bound = 2;\n    int lupper_bound = 2;\n    typename elem_t::Acc::template get<angular_elem_t> get_xir;\n    for (int l = L; l > llower_bound; --l) {\n      std::function<bool(const elem_t&)> pred = [&](const elem_t& e) {\n        return (get_xir(e).get_id().l == l);\n      };\n      // get current l-range of spectral basis\n      auto range = filtered_range(trial_basis.begin(), trial_basis.end(), pred);\n      bool is_below_tre = true;\n      for (auto it = std::get<0>(range); it != std::get<1>(range); ++it) {\n        unsigned int idx = trial_basis.get_dof_index(it->get_id());\n        if (std::abs(solution[idx]) > tol) {\n          is_below_tre = false;\n          break;\n        }\n      }\n      if (!is_below_tre) {\n        lupper_bound = l;\n        break;\n      }\n    }\n    // look for the upper-bound iterator in trial_basis\n    std::function<bool(int, const elem_t& e)> comp = [&](int l, const elem_t& e) {\n      return l < get_xir(e).get_id().l;\n    };\n    auto it_max = std::upper_bound(trial_basis.begin(), trial_basis.end(), lupper_bound, comp);\n    if (verbose) cout << \"Adpative Basis: L_max = \" << lupper_bound << endl;\n    // returns nmax => relevant range is (0, nmax)\n    return (it_max - trial_basis.begin());\n  };\n\n  hid_t file, gdata;\n  file = H5Fcreate(\"coefficients.h5\", H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);\n  gdata = H5Gcreate1(file, \"data\", 0);\n  eigen2hdf::save(gdata, \"0\", coeffs);\n  H5Fflush(file, H5F_SCOPE_GLOBAL);\n\n  double t = 0;\n  for (int i = 0; i < nsteps; ++i) {\n    auto coeffsn = coeffs;\n    timer.start();\n    auto f = [&](double* dst, const double* src) {\n      if (adaptiveL) {\n        int nmax = find_relevant_range(coeffs.data());\n        if (verbose) cout << \"Adaptive nmax = \" << nmax << endl;\n        ct.apply_adaptive(dst, src, nmax);\n      } else {\n        ct.apply(dst, src);\n      }\n    };\n\n    rk4.apply(coeffsn.data(), coeffs.data(), f, dt);\n    ct.project(coeffsn.data(), coeffs.data());\n    print_timer(timer.stop(), \"RK4\");\n    t += dt;\n    timer.start();\n    coeffs = coeffsn;\n    double m = mass.compute(coeffs.data());\n    if(std::isnan(m)) {\n      H5Gclose(gdata);\n      H5Fclose(file);\n      throw std::runtime_error(\"blow up...\");\n    }\n    double e = energy.compute(coeffs.data());\n    auto mom = momentum.compute(coeffs.data());\n    print_timer(timer.stop(), \"compute moments\");\n\n    cout << \"::MOMENTS::\\t\" << setw(8) << i + 1 << setw(20) << setprecision(10) << t << setw(30)\n         << setprecision(20) << scientific << m << setw(30) << setprecision(20) << scientific << e\n         << setw(30) << setprecision(20) << scientific << mom[0] << setw(30) << setprecision(20)\n         << scientific << mom[1] << endl;\n\n    // save results to HDF5\n    eigen2hdf::save(gdata, boost::lexical_cast<string>(i + 1), coeffs);\n    H5Fflush(file, H5F_SCOPE_GLOBAL);\n  }\n\n  H5Gclose(gdata);\n  H5Fclose(file);\n\n  return 0;\n}\n", "meta": {"hexsha": "c7d83574eaa690e3bc1f52d1fa2dfb65290e2651", "size": 7241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/homogeneous/main_timestep_galerkin.cpp", "max_stars_repo_name": "simonpp/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/homogeneous/main_timestep_galerkin.cpp", "max_issues_repo_name": "simonpp/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/homogeneous/main_timestep_galerkin.cpp", "max_forks_repo_name": "simonpp/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6459330144, "max_line_length": 99, "alphanum_fraction": 0.6333379367, "num_tokens": 1971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.42690164914887174}}
{"text": "#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <chrono>\n#include <queue>\n\nusing namespace Eigen;\n\ntypedef struct {\n  long n;\n  long m;\n  unsigned int *rowOffsets;\n  unsigned int *adj;\n  long n_coarse;\n  long m_coarse;\n  unsigned int *rowOffsetsCoarse;\n  unsigned int *adjCoarse;\n  int *coarseID;\n  double *eweights;\n} graph_t;\n\ntemplate <typename T>\nstd::string to_string_with_precision(const T a_value, const int n = 8) {\n\n  std::ostringstream out;\n  out << std::setprecision(n) << a_value;\n  return out.str();\n}\n\nstatic int\nvu_cmpfn_inc(const void *a, const void *b) {\n\n  int *av = ((int *) a);\n  int *bv = ((int *) b);\n  if (*av > *bv)\n    return 1;\n  if (*av < *bv)\n    return -1;\n  if (*av == *bv) {\n    if (av[1] > bv[1])\n      return 1;\n    if (av[1] < bv[1])\n      return -1;\n  }\n  return 0;\n}\n\nstatic int\nsimpleCoarsening(graph_t *g, int coarseningType) {\n\n  if (coarseningType == 0)\n    return 0;\n\n  int num_coarsening_rounds_max = 100;\n  int coarse_graph_nmax = 1000;\n\n  int *cID = (int *) malloc((g->n)*sizeof(int));\n  assert(cID != NULL);\n  int *toMatch = (int *) malloc((g->n)*sizeof(int));\n  assert(toMatch != NULL);\n\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n  for (long i=0; i<g->n; i++) {\n    cID[i] = i;\n    toMatch[i] = 1;\n  }\n\n  int coarse_vert_count = g->n;\n  int num_rounds = 0;\n  while ((coarse_vert_count > coarse_graph_nmax) && \n         (num_rounds < num_coarsening_rounds_max)) {\n    num_rounds++;\n    int num_matched = 0;\n    for (int i=0; i<g->n; i++) {\n      int u = i;\n      while (cID[u] != u) {\n        cID[u] = cID[cID[u]];\n        u = cID[u];\n      }\n      if (toMatch[u] == 1) {\n        for (unsigned int j=g->rowOffsets[u]; \n                          j<g->rowOffsets[u+1]; j++) {\n          int v = g->adj[j];\n          while (v != cID[v]) {\n            cID[v] = cID[cID[v]];\n            v = cID[v];\n          }\n          if (v == u) {\n            continue;\n          }\n          if (toMatch[v] == 1) {\n            if (u < v) {\n              cID[u] = u;\n              cID[v] = u;\n            } else {\n              cID[u] = v;\n              cID[v] = v;\n            }\n            toMatch[u] = toMatch[v] = 0;\n            num_matched += 2;\n            break;\n          }\n        }\n      }\n    }\n\n    int num_unmatched = coarse_vert_count - num_matched;\n    int new_coarse_vert_count = num_matched/2 + num_unmatched;\n    fprintf(stderr, \"prev count: %d, matched: %d, new count: %d\\n\", \n             coarse_vert_count, num_matched, new_coarse_vert_count);\n             coarse_vert_count = new_coarse_vert_count;\n\n    for (int i=0; i<g->n; i++) {\n      toMatch[i] = 1;\n    }\n  }\n  fprintf(stderr, \"num rounds: %d\\n\", num_rounds);\n\n  int *coarse_edges = (int *) malloc(2 * g->m * sizeof(int));\n  assert(coarse_edges != NULL);  \n\n  /* set correct IDs */  \n  for (int i=0; i<g->n; i++) {\n    int u = cID[i];\n    while (u != cID[u]) {\n      u = cID[cID[u]];\n    }\n    cID[i] = u;\n  }\n\n  int *vertIDs = (int *) malloc(g->n * sizeof(int));\n  assert(vertIDs != NULL);  \n  for (int i=0; i<g->n; i++) {\n    vertIDs[i] = -1;\n  }\n  \n  int new_id = 0;\n  for (int i=0; i<g->n; i++) {\n    if (cID[i] == i) {\n      vertIDs[i] = new_id++;\n    }\n  }\n  assert(new_id == coarse_vert_count);\n  for (int i=0; i<g->n; i++) {\n    if (vertIDs[i] == -1) {\n      vertIDs[i] = vertIDs[cID[i]];\n    }\n  }\n\n  long ecount = 0;\n  for (int i=0; i<g->n; i++) {\n    int u = vertIDs[i];\n    for (unsigned int j=g->rowOffsets[i]; j<g->rowOffsets[i+1]; j++) {\n      int v = vertIDs[g->adj[j]];\n      coarse_edges[ecount++] = u;\n      coarse_edges[ecount++] = v;\n      // fprintf(stderr, \"%d %d\\n\", u, v);\n    }\n  }\n  ecount = ecount/2;\n  qsort(coarse_edges, g->m, 2*sizeof(int), vu_cmpfn_inc);\n\n  /* count the number of coarse edges */\n  int m_coarse = 1;\n  int prev_u = coarse_edges[0];\n  int prev_v = coarse_edges[1];\n    \n  for (int i=1; i<ecount; i++) {\n    int curr_u = coarse_edges[2*i];\n    int curr_v = coarse_edges[2*i+1];\n    if ((curr_u != prev_u) || (curr_v != prev_v)) {\n      m_coarse++;\n      prev_u = curr_u;\n      prev_v = curr_v;\n    }\n  }\n\n  fprintf(stderr, \"m_coarse %d\\n\", m_coarse);\n\n  /* Allocate coarse edge weights array */\n  double *eweights;\n  eweights = (double *) malloc(m_coarse * sizeof(double));\n  assert(eweights != NULL);\n  for (int i=0; i<m_coarse; i++) {\n    eweights[i] = 1.0;\n  }\n\n  unsigned int *rowOffsetsCoarse;\n  rowOffsetsCoarse = (unsigned int *)\n    malloc((coarse_vert_count+1)*sizeof(unsigned int));\n  assert(rowOffsetsCoarse != NULL);\n  for (int i=0; i<coarse_vert_count+1; i++) {\n    rowOffsetsCoarse[i] = 0;\n  }\n\n  unsigned int *adjCoarse;\n  adjCoarse = (unsigned int *) malloc(m_coarse*sizeof(unsigned int));\n  assert(adjCoarse != NULL);\n \n  /* update coarse edge weights */\n  m_coarse = 1;\n  // eweights[0] = 1.0;\n  prev_u = coarse_edges[0];\n  prev_v = coarse_edges[1];\n  adjCoarse[0] = prev_v;\n  rowOffsetsCoarse[prev_u+1]++;\n    \n  for (int i=1; i<ecount; i++) {\n    int curr_u = coarse_edges[2*i];\n    int curr_v = coarse_edges[2*i+1];\n    if ((curr_u != prev_u) || (curr_v != prev_v)) {\n      m_coarse++;\n      adjCoarse[m_coarse-1] = curr_v;\n      // eweights[m_coarse] = 1.0;\n      rowOffsetsCoarse[curr_u+1]++;\n      prev_u = curr_u;\n      prev_v = curr_v;\n    } else {\n      eweights[m_coarse-1] += 1.0; \n    }\n  }\n\n  for (int i=1; i<=coarse_vert_count; i++) {\n    rowOffsetsCoarse[i] += rowOffsetsCoarse[i-1];\n    // fprintf(stderr, \"%u \", rowOffsetsCoarse[i]);\n  }\n  \n  /*\n  fprintf(stderr, \"printing coarse graph:\\n\");\n  for (int i=0; i<coarse_vert_count; i++) {\n    for (int j=rowOffsetsCoarse[i]; j<rowOffsetsCoarse[i+1]; j++) {\n      fprintf(stderr, \"[%u %u %lf] \", i, adjCoarse[j], eweights[j]);\n    }\n  }\n  */\n\n  /*\n  for (int i=0; i<ecount/2; i++) {\n    fprintf(stderr, \"%d %d\\n\", coarse_edges[2*i], coarse_edges[2*i+1]);\n  }\n  */\n\n  free(cID);\n  free(toMatch);\n  free(coarse_edges);\n\n  g->coarseID = vertIDs;\n  g->n_coarse = coarse_vert_count;\n  g->m_coarse = m_coarse;\n  g->eweights = eweights;\n  g->adjCoarse = adjCoarse;\n  g->rowOffsetsCoarse = rowOffsetsCoarse;\n\n  if (coarseningType == 1)\n    return 0;\n\n  // Optionally write to CSR and MTX files\n  std::cout << \"Writing csr and mtx files to current directory\\n\"; \n  FILE *writeBinaryPtr = fopen( \"graph_coarse.csr\", \"wb\");\n  if (writeBinaryPtr == NULL) {\n    fprintf(stderr, \"could not open csr file for writing\\n\");\n    exit(1);\n  }\n  \n  FILE *outfp_mtx = fopen( \"graph_coarse.mtx\", \"w\");\n  if (outfp_mtx == NULL) {\n    fprintf(stderr, \"could not open mtx file for writing\\n\");\n    exit(1);\n  }\n\n  long N = g->n_coarse;\n  unsigned int *rowOffsetsCoarse_noloops = (unsigned int *)\n  malloc((N+1)*sizeof(unsigned int));\n  assert(rowOffsetsCoarse_noloops != NULL);\n  for (long i=0; i<N+1; i++) {\n    rowOffsetsCoarse_noloops[i] = 0;\n  }\n\n  long num_self_loops = 0;\n  for (long i=0; i<g->n_coarse; i++) {\n    for (unsigned int j=g->rowOffsetsCoarse[i]; \n                      j<g->rowOffsetsCoarse[i+1]; j++) {\n      unsigned int v = g->adjCoarse[j];\n      if (((unsigned int) i) == v) {\n        num_self_loops++;\n      } else {\n        rowOffsetsCoarse_noloops[i+1]++;\n      }\n    }\n  } \n \n  for (long i=1; i<N+1; i++) {\n    rowOffsetsCoarse_noloops[i] += rowOffsetsCoarse_noloops[i-1];\n  }\n   \n  long M = g->m_coarse - num_self_loops;\n  std::cout << \"edge count after loop removal: \" << M << std::endl;\n\n  fprintf(outfp_mtx, \"%%%%MatrixMarket matrix coordinate pattern symmetric\\n\");\n  fprintf(outfp_mtx, \"%ld %ld %ld\\n\", N, N, M);\n\n  unsigned int *adjCoarse_noloops = (unsigned int *)\n    malloc(M*sizeof(unsigned int));\n  assert(adjCoarse_noloops != NULL);\n \n  long ec = 0; \n  for (long i=0; i<g->n_coarse; i++) {\n    for (unsigned int j=g->rowOffsetsCoarse[i]; \n                      j<g->rowOffsetsCoarse[i+1]; j++) {\n      unsigned int v = g->adjCoarse[j];\n      if (((unsigned int) i) == v) {\n        num_self_loops++;\n      } else {\n        adjCoarse_noloops[ec++] = v;\n        fprintf(outfp_mtx, \"%ld %u\\n\", i+1, v+1);\n      }\n    }\n  } \n  assert(ec == M);\n  fclose(outfp_mtx);\n \n  long undirected = 1;\n  long graph_type = 0;\n  long one_indexed = 0;\n  long verification_graph = 0;\n\n  fwrite ( &N, sizeof(long), 1, writeBinaryPtr );\n  fwrite ( &M, sizeof(long), 1, writeBinaryPtr );\n  fwrite ( &undirected, sizeof(long), 1, writeBinaryPtr );\n  fwrite ( &graph_type , sizeof(long), 1, writeBinaryPtr );\n  fwrite ( &one_indexed , sizeof(long), 1, writeBinaryPtr );\n  fwrite ( &verification_graph , sizeof(long), 1, writeBinaryPtr );\n\n  fwrite ( rowOffsetsCoarse_noloops, sizeof(unsigned int), (N+1), writeBinaryPtr );\n  fwrite ( adjCoarse_noloops, sizeof(unsigned int), M, writeBinaryPtr );\n\n  fclose( writeBinaryPtr );\n\n  free(rowOffsetsCoarse_noloops);\n  free(adjCoarse_noloops);\n\n  return 0;\n}\n\nstatic int\nloadToMatrix(SparseMatrix<double,RowMajor>& M, VectorXd& degrees, \n    graph_t *g, int coarseningType) {\n\n  typedef Triplet<double> T;\n  std::vector<T> tripletList;\n  \n  if (coarseningType == 0) {\n    tripletList.reserve(g->m);\n \n    for (int i=0; i<g->n; i++) {\n      tripletList.push_back(T(i,i,0.5));\n      degrees(i) = g->rowOffsets[i+1]-g->rowOffsets[i];\n      double nzv = 1/(2.0*(g->rowOffsets[i+1]-g->rowOffsets[i]));\n      for (unsigned int j=g->rowOffsets[i]; j<g->rowOffsets[i+1]; j++) {\n        unsigned int v = g->adj[j];\n        tripletList.push_back(T(i, v, nzv));\n      }\n    }\n    M.setFromTriplets(tripletList.begin(), tripletList.end()); \n  } else {\n\n    for (int i=0; i<g->n_coarse; i++) {\n      double degree_i = 0;\n      for (unsigned int j=g->rowOffsetsCoarse[i]; j<g->rowOffsetsCoarse[i+1]; j++) {\n      degree_i += g->eweights[j];\n    }\n    degrees(i) = degree_i;\n    // std::cout << degrees(i) << \" \";\n    }\n   \n    tripletList.reserve(g->m_coarse);\n \n    for (long i=0; i<g->n_coarse; i++) {\n      double diag_val = 0;\n      double inv_2deg = 1/(2.0*degrees(i));\n      for (unsigned int j=g->rowOffsetsCoarse[i]; j<g->rowOffsetsCoarse[i+1]; j++) {\n        unsigned int v = g->adjCoarse[j];\n        if (v == ((unsigned int) i)) {\n          diag_val = g->eweights[j]*inv_2deg;\n        } else {\n          tripletList.push_back(T(i, v, g->eweights[j]*inv_2deg));\n        }\n      }\n      tripletList.push_back(T(i,i,diag_val+0.5));\n    }\n    M.setFromTriplets(tripletList.begin(), tripletList.end()); \n  }\n\n  return 0;\n}\n\nstatic VectorXd \nbfs(unsigned int *row, \n    unsigned int *col,\n    long N, long M,\n    unsigned int start) {\n  VectorXd columnOfMatrix(N);\n\n  unsigned int s = start;\n  int *visited = (int *) malloc (sizeof(int) * N);\n  memset(visited, 0, sizeof(unsigned int) * N);\n  std::queue<unsigned int> Q;\n  Q.push(s);\n  visited[s] = 1;\n  columnOfMatrix(s) = 0;\n\n  while(!Q.empty()) {\n    unsigned int h = Q.front();\n    Q.pop();\n    for (unsigned int j=row[h]; j<row[h+1]; j++) {\n      s = col[j];\n      if (!visited[s]) {\n        visited[s] = 1;\n        Q.push(s);\n        columnOfMatrix(s) = columnOfMatrix(h) + 1;\n      }\n    }\n  }\n  \n  free(visited);\n  return columnOfMatrix;\n}\n\n\nstatic int \nHDE(SparseMatrix<double,RowMajor>& M, graph_t *g,\n    VectorXd& degrees, \n    VectorXd& secondVec, VectorXd& thirdVec) {\n\n  auto startTimerPart = std::chrono::high_resolution_clock::now();  \n  \n  // Create Laplacian\n  long n = g->n;\n  long m = g->m;\n  typedef Triplet<double> T;\n  std::vector<T> LTripletList;\n  LTripletList.reserve(g->m);\n  for (int i=0; i<g->n; i++) {\n    LTripletList.push_back(T(i,i,degrees(i)));\n    for (unsigned int j=g->rowOffsets[i]; j<g->rowOffsets[i+1]; j++) {\n      unsigned int v = g->adj[j];\n      LTripletList.push_back(T(i,v, -1.0));\n    }\n  }\n  SparseMatrix<double,RowMajor> L(n,n);\n  L.setFromTriplets(LTripletList.begin(), LTripletList.end()); \n  auto endTimerPart = std::chrono::high_resolution_clock::now();\n  std::chrono::duration<double> elt = endTimerPart - startTimerPart;\n  std::cout << \"Laplacian load time: \" << elt.count() << \" s.\" << std::endl;\n\n  // HDE Initialize\n  startTimerPart = std::chrono::high_resolution_clock::now();  \n  VectorXi min_dist(g->n);\n  min_dist.setOnes();\n  min_dist = min_dist * INT_MAX;\n\n  int maxM = 50;\n  VectorXd tmp(n);\n  tmp.setOnes();\n  tmp.normalize();\n  MatrixXd dist(n,maxM+1);\n  MatrixXd dist_bak(n,maxM);\n  dist.col(0) = tmp;\n\n  int start_idx = 0;\n  for (int run_count=1; run_count<=maxM; run_count++) {\n    dist.col(run_count) = bfs(g->rowOffsets, g->adj, n, m, start_idx);\n    \n    int max = -1;\n    for (long i=0; i<n; i++) {\n      if (dist.col(run_count)(i) < min_dist[i]) {\n        min_dist[i] = dist.col(run_count)(i);\n      }\n      if (min_dist[i] > max) {\n        max = min_dist[i];\n        start_idx = i;\n      }\n    }\n    dist.col(run_count).normalize();\n  }\n\n  int j = 1;\n  for (int run_count=0; run_count<maxM; run_count++) {\n\n    for (int k=0; k<j; k++) {\n      // D-orthogonalize\n#if 1\n      VectorXd dnormvec(n);\n      dnormvec = dist.col(k).cwiseProduct(degrees);\n      double multplr_denom = dist.col(k).dot(dnormvec);\n      double multplr_num = dist.col(j).dot(dnormvec);\n      dist.col(j) = dist.col(j) - (multplr_num * dist.col(k))/multplr_denom;\n#endif\n#if 0\n      double multplr = dist.col(j).dot(dist.col(k));\n      dist.col(j) = dist.col(j) - multplr * dist.col(k);\n#endif\n    }\n\n    double normdist = dist.col(j).norm();\n    if (normdist < 0.001) {\n      std::cout << \"discarding vec \" << j << \", normdist \" << normdist << std::endl;\n      j--;\n    } else {\n      // std::cout << \"j \" << j << \", normdist \" << normdist << std::endl;\n      dist.col(j).normalize();\n    }\n\n    dist_bak.col(j-1) = dist.col(j); \n    j++;\n  }\n\n  MatrixXd LX(n, maxM);\n  LX = L * dist_bak;\n\n  MatrixXd XtLX(maxM, maxM);\n  XtLX = dist_bak.transpose() * LX;\n\n  SelfAdjointEigenSolver<MatrixXd> es(XtLX);\n  MatrixXd init_vecs(n, 2);\n  init_vecs = dist_bak * es.eigenvectors().leftCols(2).real();\n\n  endTimerPart = std::chrono::high_resolution_clock::now();\n  elt = endTimerPart - startTimerPart;\n  std::cout << \"HDE Initialization time \" << elt.count() << \" s.\" << std::endl;\n  secondVec = init_vecs.col(0);\n  thirdVec  = init_vecs.col(1);\n\n  return 0;\n}\n\nstatic int \npowerIterationKoren(SparseMatrix<double,RowMajor>& M, \n    VectorXd& degrees, double eps, VectorXd& firstVec, \n    VectorXd& secondVec, VectorXd& thirdVec, \n    int coarseningType, char *inputFilename) {\n\n  // double eps = 1e-9;\n  std::cout << \"Using eps \" << eps << \" for second eigenvector\" << std::endl;\n\n  if (coarseningType > 0) {\n    std::cout << \"Using coarsened graph\" << std::endl;\n  }\n\n  int n = M.rows();\n\n  VectorXd uk_hat(n);\n\n  // Intialized vectors are passed to function\n  uk_hat = secondVec;\n  // uk_hat.setRandom();\n  // uk_hat.normalize();\n\n  VectorXd uk(n);\n\n  // For D-orthonormalization\n  VectorXd firstVecD(n);\n  firstVecD = firstVec.cwiseProduct(degrees);\n  double mult1_denom = firstVec.dot(firstVecD);\n\n  VectorXd residual(n);\n\n  int num_iterations1 = 0;\n  \n  auto startTimerPart = std::chrono::high_resolution_clock::now();  \n  while (1) {\n\n    uk = uk_hat;\n    \n    // D-orthonormalize\n    double mult1_num = uk.dot(firstVecD);\n    uk = uk - (mult1_num/mult1_denom)*firstVec;\n\n    // Do matrix-vector product\n    uk_hat = M*uk;\n    uk_hat.normalize();\n\n    num_iterations1++;\n   \n    // double residual_norm1 =\n    //  residual.lpNorm<Infinity>()/(uk_hat.maxCoeff()-uk_hat.minCoeff());\n\n#if 0\n    double residual_dot = uk.dot(uk_hat);\n    if (residual_dot >= (1-eps)) {\n      break;\n    }\n#endif\n\n    residual = uk-uk_hat;\n    double residual_norm = residual.norm(); \n    // std::cout << residual_norm << std::endl;\n\n    if (residual_norm < eps) {\n      break;\n    }\n  }\n\n  std::cout << \"Num iterations for second eigenvector: \" <<\n    num_iterations1 << std::endl;\n\n  // Save this eigenvector\n  secondVec = uk_hat;\n  auto endTimerPart = std::chrono::high_resolution_clock::now();\n  std::chrono::duration<double> elt = endTimerPart - startTimerPart;\n  std::cout << \"Second eigenvector computation time: \" << elt.count() << \" s.\" << std::endl;\n\n  eps = 2.0*eps;\n  std::cout << \"Using eps \" << eps << \" for third eigenvector\" << std::endl;\n\n  // For D-orthonormalization\n  VectorXd secondVecD(n);\n  secondVecD = secondVec.cwiseProduct(degrees);\n  double mult2_denom = secondVec.dot(secondVecD);\n\n  // Initialized vectors are passed to function\n  uk_hat = thirdVec;\n  // uk_hat.setRandom();\n  // uk_hat.normalize();\n\n  startTimerPart = std::chrono::high_resolution_clock::now();  \n  int num_iterations2 = 0;\n  while (1) {\n\n    uk = uk_hat;\n    \n    // D-orthonormalize\n    double mult1_num = uk.dot(firstVecD);\n    uk = uk - (mult1_num/mult1_denom)*firstVec;\n    double mult2_num = uk.dot(secondVecD);\n    uk = uk - (mult2_num/mult2_denom)*secondVec;\n  \n\n    // Do matrix-vector product\n    uk_hat = M*uk;\n    uk_hat.normalize();\n\n    num_iterations2++;\n\n#if 0\n    double residual_dot = uk.dot(uk_hat);\n    if (residual_dot >= (1-eps)) {\n      break;\n    }\n#endif\n\n    residual = uk-uk_hat;\n    double residual_norm = residual.norm(); \n    // std::cout << \" \" << residual_norm << std::endl;\n\n    if (residual_norm < eps) {\n      break;\n    }\n\n  }\n  std::cout << \"Num iterations for third eigenvector: \" <<\n    num_iterations2 << std::endl;\n\n  // Save this eigenvector as well\n  thirdVec = uk_hat;\n  endTimerPart = std::chrono::high_resolution_clock::now();\n  elt = endTimerPart - startTimerPart;\n  std::cout << \"Third eigenvector computation time: \" << elt.count() << \" s.\" << std::endl;\n\n  std::cout << \"Dot products of eigenvectors: \" \n  << firstVec.dot(secondVec) << \" \"\n  << firstVec.dot(thirdVec) << \" \" << secondVec.dot(thirdVec) <<\n  std::endl;\n\n  return 0;\n\n}\n\nstatic int \nRefineTutte(SparseMatrix<double,RowMajor>& M, \n    VectorXd& secondVec, VectorXd& thirdVec,\n    int numSmoothing) {\n\n  std::cout << \"Number of smoothing rounds: \" << numSmoothing << std::endl; \n  auto startTimerPart = std::chrono::high_resolution_clock::now();\n  VectorXd unitVec(M.cols());;\n  unitVec.setOnes();\n\n  SparseMatrix<double,RowMajor> M2 = 2*M;\n  // M2.diagonal() -= unitVec;\n  M2.diagonal().setZero();\n  \n  for (int i=0; i<numSmoothing; i++) {\n    secondVec = M2*secondVec;\n    thirdVec = M2*thirdVec;\n  } \n  auto endTimerPart = std::chrono::high_resolution_clock::now();\n  std::chrono::duration<double> elt = endTimerPart - startTimerPart;\n  std::cout << \"RefineTutte Time: \" << elt.count() << \" s.\" << std::endl;\n\n  return 0; \n}\n\nstatic int \nwriteCoords(SparseMatrix<double,RowMajor>& M, \n    VectorXd& firstVec, VectorXd& secondVec, VectorXd& thirdVec, \n    int coarseningType, int doHDE, int refineType, \n    double eps, char *inputFilename) {\n\n  // Write coordinates to file\n  std::ofstream fout;\n  std::string coordFilename(inputFilename); \n  coordFilename += \"_c\" + std::to_string(coarseningType) \n      + \"_h\" + std::to_string(doHDE) \n      + \"_r\" + std::to_string(refineType) \n      + \"_eps\" + to_string_with_precision(eps) + \".nxyz\";\n  std::cout << \"Writing coordinates to file \" << coordFilename << std::endl;\n  fout.open(coordFilename);\n  int n = M.cols();\n  for (int i=0; i<n; i++) {\n    fout << secondVec(i) << \",\" << thirdVec(i) << std::endl;  \n  }\n  fout.close();\n\n  /* print eigenvalues */\n  double firstEigenVal = (M*firstVec).cwiseQuotient(firstVec).mean();\n  double firstEigenValMin =\n    (M*firstVec).cwiseQuotient(firstVec).minCoeff();\n  double firstEigenValMax =\n    (M*firstVec).cwiseQuotient(firstVec).maxCoeff();\n  double secondEigenVal = (M*secondVec).cwiseQuotient(secondVec).mean();\n  double secondEigenValMin =\n    (M*secondVec).cwiseQuotient(secondVec).minCoeff();\n  double secondEigenValMax =\n    (M*secondVec).cwiseQuotient(secondVec).maxCoeff();\n  double thirdEigenVal = (M*thirdVec).cwiseQuotient(thirdVec).mean();\n  double thirdEigenValMin =\n    (M*thirdVec).cwiseQuotient(thirdVec).minCoeff();\n  double thirdEigenValMax =\n    (M*thirdVec).cwiseQuotient(thirdVec).maxCoeff();\n\n  std::cout << \"First Eigenvalue  (mean, min, max): \" << firstEigenVal\n    << \" \" << firstEigenValMin << \" \" << firstEigenValMax << std::endl;\n  std::cout << \"Second Eigenvalue (mean, min, max): \" << secondEigenVal\n    << \" \" << secondEigenValMin << \" \" << secondEigenValMax << std::endl;\n  std::cout << \"Third Eigenvalue  (mean, min, max): \" << thirdEigenVal\n    << \" \" << thirdEigenValMin << \" \" << thirdEigenValMax << std::endl;\n\n  return 0;   \n}\n\n\nint main(int argc, char **argv) {\n\n  if (argc != 5) {\n    std::cout << \"Usage: \"<< argv[0] << \" <csr filename> \"\n    \"<0/1/2 (none,coarsen and continue,coarsen+stop)> <0/1 (HDE)> \" \n    \"<0/1/2/3 (none,Koren,Tutte,Koren+Tutte)> \"\n    << std::endl;\n  return 1;\n  }\n\n  char *inputFilename = argv[1];\n\n  int coarseningType = atoi(argv[2]);\n  if (coarseningType == 1) {\n    std::cout << \"Coarsening graph and continuing\" << std::endl;\n  } else if (coarseningType == 2) {\n    std::cout << \"Coarsening and stopping\" << std::endl;  \n  } else {\n    coarseningType = 0;\n  }\n\n  int doHDE = atoi(argv[3]);\n  if (doHDE) {\n    std::cout << \"Running High-dimensional embedding\" << std::endl;\n    coarseningType = 0;\n  } else {\n    doHDE = 0;\n  }\n\n  int refineType = atoi(argv[4]);\n  if (refineType == 0) {\n    std::cout << \"No eigenvector computation or refinement\" << std::endl;\n  } else if (refineType == 1) {\n    std::cout << \"Computing eigenvectors using Koren's algorithm\" << std::endl;\n  } else if (refineType == 2) {\n    std::cout << \"Refining coordinates using Tutte's algorithm\" << std::endl;\n  } else if (refineType == 3) {\n    std::cout << \"Eigenvectors followed by Tutte refinement\" << std::endl;\n  }\n\n  // Read CSR file\n  auto startTimer = std::chrono::high_resolution_clock::now();  \n  auto startTimerPart = std::chrono::high_resolution_clock::now();  \n  FILE *infp = fopen(inputFilename, \"rb\");\n  if (infp == NULL) {\n    std::cout << \"Error: Could not open input file. Exiting ...\" <<\n    std::endl; \n    return 1;   \n  }\n  long n, m;\n  long rest[4];\n  unsigned int *rowOffsets, *adj;\n  fread(&n, 1, sizeof(long), infp);\n  fread(&m, 1, sizeof(long), infp);\n  fread(rest, 4, sizeof(long), infp);\n  rowOffsets = (unsigned int *) malloc (sizeof(unsigned int) * (n+1));\n  assert(rowOffsets != NULL);\n  adj = (unsigned int *) malloc (sizeof(unsigned int) * m);\n  assert(adj != NULL);\n  fread(rowOffsets, n+1, sizeof(unsigned int), infp);\n  fread(adj, m, sizeof(unsigned int), infp);\n  fclose(infp);\n  auto endTimerPart = std::chrono::high_resolution_clock::now();\n  std::chrono::duration<double> elt = endTimerPart - startTimerPart;\n  std::cout << \"CSR read time: \" << elt.count() << \" s.\" << std::endl;\n  std::cout << \"Num edges: \" << m/2 << \", vertices: \" << n << std::endl;\n\n  graph_t g;\n  g.n = n; g.m = m;\n  g.rowOffsets = rowOffsets;\n  g.adj = adj;  \n\n  simpleCoarsening(&g, coarseningType);\n  \n  VectorXd secondVecc;\n  VectorXd thirdVecc;\n \n  if (coarseningType > 0) {\n    long n_coarse = g.n_coarse;\n    SparseMatrix<double,RowMajor> Mc(n_coarse,n_coarse);\n    VectorXd degreesc(n_coarse);\n    loadToMatrix(Mc, degreesc, &g, coarseningType);\n    VectorXd firstVecc(n_coarse);\n    firstVecc.setOnes();\n    firstVecc.normalize();\n    secondVecc.resize(n_coarse);\n    thirdVecc.resize(n_coarse);\n    secondVecc.setRandom();\n    if (secondVecc(0) < 0) {\n      secondVecc = -secondVecc;\n    }\n    secondVecc.normalize();\n    thirdVecc.setRandom();\n    if (thirdVecc(0) < 0) {\n      thirdVecc = -thirdVecc;\n    }\n    thirdVecc.normalize();\n    double epsc = 1e-9;\n    powerIterationKoren(Mc, degreesc, epsc, \n      firstVecc, secondVecc, thirdVecc, coarseningType,\n        inputFilename);\n    if (coarseningType == 2) {\n      writeCoords(Mc, firstVecc, secondVecc, thirdVecc, \n        coarseningType, doHDE, refineType, epsc, inputFilename);\n    }\n  }\n\n  // Load to matrix\n  startTimerPart = std::chrono::high_resolution_clock::now();  \n  SparseMatrix<double,RowMajor> M(n,n);\n  VectorXd degrees(n);\n  // load the full graph/matrix now\n  loadToMatrix(M, degrees, &g, 0);\n  endTimerPart = std::chrono::high_resolution_clock::now();\n  elt = endTimerPart - startTimerPart;\n  std::cout << \"Matrix load time: \" << elt.count() << \" s.\" << std::endl;\n\n  // Compute second and third eigenvectors using\n  // Koren's power iteration algorithm\n  VectorXd firstVec(n);\n  firstVec.setOnes();\n  firstVec.normalize();\n\n  VectorXd secondVec(n);\n  VectorXd thirdVec(n);\n\n  // Initialize with previously-found coarse vectors\n  if (coarseningType == 1) {\n    for (long i=0; i<g.n; i++) {  \n      secondVec(i) = secondVecc(g.coarseID[i]);\n      thirdVec(i)  = thirdVecc(g.coarseID[i]);\n    }\n    secondVec.normalize();\n    thirdVec.normalize();\n  \n  // initialize with HDE vectors  \n  } else if (doHDE == 1) {\n    HDE(M, &g, degrees, secondVec, thirdVec); \n  \n  // Random vectors   \n  } else if (doHDE == 0) {\n     secondVec.setRandom();\n     if (secondVec(0) < 0) {\n       secondVec = -secondVec;\n     }\n     secondVec.normalize();\n     thirdVec.setRandom();\n     if (thirdVec(0) < 0) {\n       thirdVec = -thirdVec;\n     }\n     thirdVec.normalize();\n  }\n\n  if (coarseningType != 2) {\n    int numTutteSmoothing = 500;\n    double eps = 1e-5;\n    if (refineType == 0) {\n      secondVec.normalize();\n      thirdVec.normalize();\n    } else if (refineType == 1) {   \n      powerIterationKoren(M, degrees, eps, firstVec, secondVec, thirdVec, \n      0, inputFilename);\n    } else if (refineType == 2) {\n      RefineTutte(M, secondVec, thirdVec, numTutteSmoothing);\n    } else if (refineType == 3) {\n      RefineTutte(M, secondVec, thirdVec, numTutteSmoothing);\n      powerIterationKoren(M, degrees, eps, firstVec, secondVec, thirdVec, \n      0, inputFilename);\n    }\n    writeCoords(M, firstVec, secondVec, thirdVec, \n          coarseningType, doHDE, refineType, 0, inputFilename);  \n  }\n\n  free(g.rowOffsets);\n  free(g.adj);\n\n  if (coarseningType > 0) {\n    free(g.rowOffsetsCoarse);\n    free(g.adjCoarse);\n    free(g.coarseID);\n    free(g.eweights);\n  }\n  endTimerPart = std::chrono::high_resolution_clock::now();\n  elt = endTimerPart - startTimer;\n  std::cout << \"Overall time: \" << elt.count() << \" s.\" << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "04842eee899cc25a2b83c19f1afc1d66dbb9ae48", "size": 26044, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "spectralDrawing.cpp", "max_stars_repo_name": "MadduriGroup/SpectralGraphDrawing", "max_stars_repo_head_hexsha": "d2d9702fcc320261c89cf54c08ca21f663793e68", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spectralDrawing.cpp", "max_issues_repo_name": "MadduriGroup/SpectralGraphDrawing", "max_issues_repo_head_hexsha": "d2d9702fcc320261c89cf54c08ca21f663793e68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spectralDrawing.cpp", "max_forks_repo_name": "MadduriGroup/SpectralGraphDrawing", "max_forks_repo_head_hexsha": "d2d9702fcc320261c89cf54c08ca21f663793e68", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4725738397, "max_line_length": 92, "alphanum_fraction": 0.6040162801, "num_tokens": 8198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4269016415796538}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_ELLIPTIC_FUNCTIONS_GENERIC_ELLIPKE_HPP_INCLUDED\n#define NT2_ELLIPTIC_FUNCTIONS_GENERIC_ELLIPKE_HPP_INCLUDED\n\n#include <nt2/elliptic/functions/ellipke.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n#include <nt2/include/constants/eps.hpp>\n#include <nt2/sdk/meta/scalar_of.hpp>\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  (ellipke_, tag::cpu_,\n                             (A0),\n                             (generic_<floating_<A0> >)\n\n                            )\n  {\n    typedef std::pair<A0, A0> result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      typedef typename nt2::meta::scalar_of<A0>::type sA0;\n      A0 first, second;\n      nt2::ellipke(a0, nt2::Eps<sA0>(), first, second);\n      return result_type(first, second);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (ellipke_, tag::cpu_,\n                             (A0)(A1),\n                             (generic_<floating_<A0> >)\n                             (scalar_<floating_<A1> >)\n\n                            )\n  {\n    typedef std::pair<A0, A0> result_type;\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      A0 first, second;\n      nt2::ellipke(a0, a1, first, second);\n      return result_type(first, second);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  (  ellipke_, tag::cpu_,\n                               (A0)(A1),\n                               (generic_<floating_<A0> >)\n                               (scalar_<floating_<A1> >)\n                               (generic_<floating_<A0> >)\n                            )\n  {\n    typedef A0 result_type;\n    inline result_type operator()(A0 const& a0,A1 const & a1,A0 & a3) const\n    {\n      A0 a2;\n      nt2::ellipke(a0,a1,a2,a3);\n      return a2;\n    }\n  };\n\n} }\n#endif\n", "meta": {"hexsha": "1bbdd89cd542ff690b1b6bc27e5555d84fb56d45", "size": 2195, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/elliptic/include/nt2/elliptic/functions/generic/ellipke.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/elliptic/include/nt2/elliptic/functions/generic/ellipke.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/elliptic/include/nt2/elliptic/functions/generic/ellipke.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 30.9154929577, "max_line_length": 80, "alphanum_fraction": 0.4993166287, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4269016340104355}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_EULER_FUNCTIONS_SIMD_COMMON_GAMMA_HPP_INCLUDED\n#define NT2_EULER_FUNCTIONS_SIMD_COMMON_GAMMA_HPP_INCLUDED\n\n#include <nt2/euler/functions/gamma.hpp>\n#include <nt2/euler/functions/details/gamma_kernel.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/pi.hpp>\n#include <nt2/include/constants/three.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/any.hpp>\n#include <nt2/include/functions/simd/divides.hpp>\n#include <nt2/include/functions/simd/floor.hpp>\n#include <nt2/include/functions/simd/if_allbits_else.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/inbtrue.hpp>\n#include <nt2/include/functions/simd/is_even.hpp>\n#include <nt2/include/functions/simd/is_flint.hpp>\n#include <nt2/include/functions/simd/is_greater_equal.hpp>\n#include <nt2/include/functions/simd/is_less.hpp>\n#include <nt2/include/functions/simd/is_ltz.hpp>\n#include <nt2/include/functions/simd/logical_and.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/negif.hpp>\n#include <nt2/include/functions/simd/seladd.hpp>\n#include <nt2/include/functions/simd/selsub.hpp>\n#include <nt2/include/functions/simd/sinpi.hpp>\n#include <nt2/include/functions/simd/splat.hpp>\n#include <nt2/include/functions/simd/stirling.hpp>\n#include <nt2/include/functions/simd/unary_minus.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n#include <nt2/sdk/meta/cardinal_of.hpp>\n\n#include <boost/simd/sdk/config.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <nt2/include/functions/simd/is_nan.hpp>\n#include <nt2/include/functions/simd/logical_or.hpp>\n#endif\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/functions/simd/is_equal.hpp>\n#endif\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  (gamma_, tag::cpu_,\n                             (A0)(X),\n                             ((simd_<floating_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    typedef typename meta::as_logical<A0>::type bA0;\n    NT2_FUNCTOR_CALL(1)\n    {\n      bA0 nan_result = logical_and(is_ltz(a0), is_flint(a0));\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      nan_result = logical_or(nt2::is_nan(a0), nan_result);\n      #endif\n      A0 q = nt2::abs(a0);\n      bA0 test = lt(a0, nt2::splat<A0>(-33.0));\n      std::size_t nb = nt2::inbtrue(test);\n      A0 r =  Nan<A0>();\n      if(nb > 0)\n      {\n        //treat negative large with reflection\n        r = large_negative(q);\n        if (nb >= meta::cardinal_of<A0>::value)\n          return nt2::if_nan_else(nan_result, r);\n      }\n      A0 r1 = other(a0, test);\n      A0 r2 = if_else(test, r, r1);\n      return nt2::if_nan_else(nan_result, r2);\n    }\n\n  private :\n    static inline A0 large_negative(const A0& q)\n    {\n      A0 st =  nt2::stirling(q);\n      A0 p = nt2::floor(q);\n      A0 sgngam = nt2::negif(nt2::is_even(p), One<A0>());\n      A0 z = q - p;\n      bA0 test2 = lt(z, nt2::Half<A0>() );\n      z = nt2::selsub(test2, z, nt2::One<A0>());\n      z = q*nt2::sinpi(z);\n      z =  nt2::abs(z);\n      return sgngam*nt2::Pi<A0>()/(z*st);\n    }\n\n    static inline A0 other(const A0& q, const bA0& test)\n    {\n      A0 x =  nt2::if_else(test, Two<A0>(), q);\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      bA0 inf_result = eq(q, Inf<A0>());\n      x = if_else(inf_result, Two<A0>(), x);\n      #endif\n      A0 z = nt2::One<A0>();\n      bA0 test1 = ge(x,Three<A0>());\n      while( nt2::any(test1) )\n      {\n        x = nt2::seladd(test1, x, nt2::Mone<A0>());\n        z = nt2::if_else(   test1, z*x, z);\n        test1 = ge(x,Three<A0>());\n      }\n      //all x are less than 3\n      test1 = nt2::is_ltz(x);\n      while( nt2::any(test1) )\n      {\n        z = nt2::if_else(test1, z/x, z);\n        x = nt2::seladd(test1, x, nt2::One<A0>());\n        test1 = nt2::is_ltz(x);\n      }\n      //all x are greater than 0 and less than 3\n      bA0 test2 = lt(x,nt2::Two<A0>());\n      while( nt2::any(test2))\n      {\n        z = nt2::if_else(test2, z/x, z);\n        x = nt2::seladd(test2, x, nt2::One<A0>());\n        test2 = lt(x,nt2::Two<A0>());\n      }\n      //all x are greater equal 2 and less than 3\n      x = z*details::gamma_kernel<A0>::gamma1(x-nt2::Two<A0>());\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      return if_else(inf_result, q, x);\n      #else\n      return x;\n      #endif\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "c429d98f11b93804fcf50b1ba41fc6fb46b52941", "size": 5120, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/gamma.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/gamma.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/euler/include/nt2/euler/functions/simd/common/gamma.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 35.0684931507, "max_line_length": 80, "alphanum_fraction": 0.6162109375, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.426869328149796}}
{"text": "#include <CGAL/internal/Surface_mesh_segmentation/Disk_samplers.h>\n\n#include <boost/tuple/tuple.hpp>\n#include <vector>\n\ntypedef boost::tuple<double, double, double> boost_tuple;\n\nvoid print(const std::vector<boost_tuple>& samples)\n{\n  const std::size_t map_size = 31;\n  const std::size_t map_size_2 = 45;\n  std::vector<std::vector<bool> > sample_map(map_size, std::vector<bool>(map_size_2, false));\n\n  for(std::vector<boost_tuple>::const_iterator sample_it = samples.begin();\n    sample_it != samples.end(); ++sample_it)\n  {\n    double x = (sample_it->get<0>() +1)/2;\n    double y = (sample_it->get<1>() +1)/2;\n    x *= (map_size-1);\n    y *= (map_size_2-1);\n    std::size_t x_c  = static_cast<std::size_t>(x + 0.49);\n    std::size_t y_c  = static_cast<std::size_t>(y + 0.49);\n    sample_map[x_c][y_c] = true;\n  }\n  for(std::size_t i = 0; i < map_size; ++i)\n  {\n    for(std::size_t j = 0; j < map_size_2; ++j)\n    {\n      if(sample_map[i][j]){ std::cout << \"*\"; }\n      else                { std::cout << \" \"; }\n    }\n    std::cout << std::endl;\n  }\n  std::cout << std::endl;\n}\n/**\n * Uses disk sampling functors to sample points from unit-disk.\n * It also prints sampled points for visual debugging.\n *\n * Note that it always return EXIT_SUCCESS\n */\nint main(void)\n{\n  CGAL::internal::Vogel_disk_sampling<boost_tuple> sampling_1;\n  CGAL::internal::Vogel_disk_sampling<boost_tuple, true> sampling_2;\n  CGAL::internal::Polar_disk_sampling<boost_tuple> sampling_3;\n  CGAL::internal::Concentric_disk_sampling<boost_tuple> sampling_4;\n\n  std::vector<boost_tuple> samples_1;\n  std::vector<boost_tuple> samples_2;\n  std::vector<boost_tuple> samples_3;\n  std::vector<boost_tuple> samples_4;\n\n  sampling_1(64, std::back_inserter(samples_1));\n  sampling_2(64, std::back_inserter(samples_2));\n  sampling_3(64, std::back_inserter(samples_3));\n  sampling_4(64, std::back_inserter(samples_4));\n\n  print(samples_1);\n  print(samples_2);\n  print(samples_3);\n  print(samples_4);\n}\n", "meta": {"hexsha": "4bd02aaf6026b92660998c8e506fec13cfc2d288", "size": 1964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh_segmentation/test/Surface_mesh_segmentation/Disk_samplers_test.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T09:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T05:00:23.000Z", "max_issues_repo_path": "Surface_mesh_segmentation/test/Surface_mesh_segmentation/Disk_samplers_test.cpp", "max_issues_repo_name": "antoniospg/cgal", "max_issues_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-10T13:32:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T12:23:20.000Z", "max_forks_repo_path": "Surface_mesh_segmentation/test/Surface_mesh_segmentation/Disk_samplers_test.cpp", "max_forks_repo_name": "antoniospg/cgal", "max_forks_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T15:26:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-21T15:26:25.000Z", "avg_line_length": 30.6875, "max_line_length": 93, "alphanum_fraction": 0.6771894094, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4268682338574247}}
{"text": "/*\n* Copyright (c) 2019, Intel Corporation\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions are met:\n*     * Redistributions of source code must retain the above copyright\n*       notice, this list of conditions and the following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright\n*       notice, this list of conditions and the following disclaimer in the\n*       documentation and/or other materials provided with the distribution.\n*     * Neither the name of the Intel Corporation nor the\n*       names of its contributors may be used to endorse or promote products\n*       derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n\n#pragma once\n\n#include \"Teisko/Algorithm/Bit.hpp\"\n#include \"Teisko/Algorithm/Functors.hpp\"\n#include \"Teisko/Algorithm/NelderMead.hpp\"\n#include \"Teisko/Color.hpp\"\n#include <Eigen/Dense>\n#include <array>\n#include <exception>\n#include <numeric>\n#include <vector>\n\nnamespace Teisko\n{\n    template <int N>\n    int operator-(const cyclical_index<N>& a, const cyclical_index<N>& b)\n    {\n        return a.idx < b.idx ? N - (b.idx - a.idx) : b.idx - a.idx;\n    }\n\n    struct color_correction_matrix : Eigen::Matrix3d\n    {\n        color_correction_matrix()\n        {\n            setIdentity();\n        }\n\n        color_correction_matrix(const Eigen::Matrix3d& v) : Eigen::Matrix3d(v) {}\n\n        // Apply color correction matrix\n        template <rgb_cs CS = rgb_cs::sRGB, wp WP = wp::D65>\n        rgb<double, CS, WP> apply(const rgb<double, rgb_cs::Sensor, wp::None>& pt) const\n        {\n            return rgb<double, CS, WP> (\n                (*this)(0, 0) * pt.r + (*this)(0, 1) * pt.g + (*this)(0, 2) * pt.b,\n                (*this)(1, 0) * pt.r + (*this)(1, 1) * pt.g + (*this)(1, 2) * pt.b,\n                (*this)(2, 0) * pt.r + (*this)(2, 1) * pt.g + (*this)(2, 2) * pt.b);\n        }\n    };\n\n    // Calculate color correction matrix from input and output matrices\n    // Either calculate ccm by\n    // 1. matrix inverse if matrix is invertible\n    // 2. least square method using svd decomposition (high accuracy but slow)\n    inline color_correction_matrix calculate_ccm(const Eigen::Matrix3d& in, const Eigen::Matrix3d& out)\n    {\n        using namespace Eigen;\n\n        const double THRESHOLD = 1e-8;\n        if (std::abs(in.determinant()) > THRESHOLD)\n        {\n            // CCM = M(out) / M(in) = M(out)*inverse(M(in))\n            //\n            // M(in)  = [RGB(1, in) ^ T, RGB(2, in) ^ T, RGB(grey) ^ T]\n            // M(out) = [RGB(1, out) ^ T, RGB(2, out) ^ T, RGB(grey) ^ T]\n            return color_correction_matrix(out * in.inverse());\n        }\n        JacobiSVD<Matrix3d> svd(in.transpose(), ComputeFullU | ComputeFullV);\n        return color_correction_matrix(svd.solve(out.transpose()).transpose());\n    }\n\n    template <rgb_cs CS, wp WP = wp::D65>\n    struct patch\n    {\n        rgb<double, rgb_cs::Sensor, wp::None> input;\n        rgb<double, CS, WP> target;\n        double weight;\n        bool achromatic;\n    };\n\n    template <rgb_cs CS, wp WP = wp::D65>\n    struct ccm_input_params\n    {\n        std::array<patch<CS, WP>, 24> color_checker_classic;\n        //std::vector<patch<CS, WP>> munsell; // TODO: Implementation for Munsell\n\n        void white_balance()\n        {\n            average_f<double> r_per_g;\n            average_f<double> b_per_g;\n\n            // Loop over achromatic patches (bottom row), dimmest and brightest omitted\n            for (size_t i = 19; i < 23; ++i)\n            {\n                r_per_g += color_checker_classic[i].input.r / color_checker_classic[i].input.g;\n                b_per_g += color_checker_classic[i].input.b / color_checker_classic[i].input.g;\n            }\n\n            auto max_gain = std::max({ (double)r_per_g, (double)b_per_g, 1.0 });\n            auto gain_r = max_gain / r_per_g;\n            auto gain_g = max_gain;\n            auto gain_b = max_gain / b_per_g;\n\n            for (auto& patch : color_checker_classic)\n            {\n                patch.input.r *= gain_r;\n                patch.input.g *= gain_g;\n                patch.input.b *= gain_b;\n            }\n        }\n\n        void normalize()\n        {\n            average_f<double> ratio;\n            for (size_t i = 19; i < 23; ++i)\n            {\n                ratio += color_checker_classic[i].target.mean() / color_checker_classic[i].input.mean();\n            }\n\n            for (auto& patch : color_checker_classic)\n            {\n                patch.input *= ratio;\n            }\n        }\n    };\n\n    template <rgb_cs CS, wp WP = wp::D65>\n    struct ccm_optimization_params\n    {\n        ccm_input_params<CS, WP> input_params;\n\n        ccm_optimization_params() = default;\n        ccm_optimization_params(const ccm_input_params<CS, WP>& input) : input_params(input) { }\n\n        void prepare()\n        {\n            input_params.white_balance();\n            input_params.normalize();\n        }\n    };\n\n    template <rgb_cs CS, wp WP = wp::D65>\n    struct ccm_func_optimizer\n    {\n        ccm_optimization_params<CS, WP> params;\n\n        ccm_func_optimizer(ccm_optimization_params<CS, WP>& p) : params(p) { }\n\n        double operator()(double *p)\n        {\n            auto sum = 0.0;\n\n            // Create CCM from optimization set. Middle column is constructed from\n            // border columns (each row sum up to 1)\n            auto ccm = color_correction_matrix();\n            ccm <<\n                p[0], 1 - p[0] - p[1], p[1],\n                p[2], 1 - p[2] - p[3], p[3],\n                p[4], 1 - p[4] - p[5], p[5];\n\n            for (const auto& patch : params.input_params.color_checker_classic)\n            {\n                if (patch.weight > 0)\n                {\n                    lab<double, WP> pt1(ccm.apply<CS, WP>(patch.input));\n                    lab<double, WP> pt2(patch.target); // TODO: Pre calculate\n\n                    sum += color_diff<color_diff_type::DeltaE2000>::calculate(pt1, pt2) * patch.weight;\n                }\n            }\n            return sum;\n        }\n    };\n\n    template <rgb_cs CS, wp WP = wp::D65>\n    class ccm_optimization\n    {\n    public:\n        ccm_optimization(ccm_input_params<CS, WP>& input) : options(input) { }\n\n        color_correction_matrix characterize()\n        {\n            // Do white balance and adjust input intensity\n            options.prepare();\n\n            // Get initial point for nelder mead optimization by using least square CCM\n            auto initial_ccm = ls_ccm().data();\n\n            // RinR, BinR, RinG, BinG, RinB, BinB indices\n            std::vector<double> initial_pt =\n            {\n                initial_ccm[0], initial_ccm[2], initial_ccm[3], initial_ccm[5], initial_ccm[6], initial_ccm[8]\n            };\n\n            // 1. coarse optimization\n            auto solver = ccm_func_optimizer<CS, WP>(options);\n            auto result = nelder_mead_simplex(initial_pt, solver, {200, 1e-4, 1e-4});\n\n            // 2. fine optimization\n            result = nelder_mead_simplex(result.second, solver, {4000, 1e-12, 1e-4});\n\n            // Create CCM from optimization set. Middle column is constructed from\n            // border columns (each row should sum up to 1)\n            color_correction_matrix ccm;\n            ccm <<\n                result.second[0], 1 - result.second[0] - result.second[1], result.second[1],\n                result.second[2], 1 - result.second[2] - result.second[3], result.second[3],\n                result.second[4], 1 - result.second[4] - result.second[5], result.second[5];\n            return ccm;\n        }\n\n    private:\n        ccm_optimization_params<CS, WP> options;\n\n        // Solve a linear system Ax=b for initial CCM optimization\n        // Where A is CCC input matrix and B is CCC target matrix\n        // This method does not preserve greys nor does it minimize error in de2000.\n        color_correction_matrix ls_ccm()\n        {\n            Eigen::Matrix<double, 24, 3> A;\n            Eigen::Matrix<double, 24, 3> b;\n            Eigen::Matrix3d x;\n\n            // Initialize matrices\n            size_t n = options.input_params.color_checker_classic.size();\n            for (size_t i = 0; i < n; ++i)\n            {\n                const patch<CS, WP>& patch = options.input_params.color_checker_classic[i];\n                A.row(i) << patch.input.r, patch.input.g, patch.input.b;\n                b.row(i) << patch.target.r, patch.target.g, patch.target.b;\n            }\n\n            // Use HouseholderQR decomposition to solve the linear equation.\n            // Prefer speed over accuracy for the decomposition method.\n            return color_correction_matrix(A.householderQr().solve(b));\n        }\n    };\n}", "meta": {"hexsha": "e12539a3825104bb98996a5d7492a670dbafa026", "size": 9551, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Teisko/ColorCorrection.hpp", "max_stars_repo_name": "intel/image-quality-and-characterization-utilities", "max_stars_repo_head_hexsha": "ef58f9aea906e6453b8cec4a891104d16dd44f93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-04-10T14:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-13T06:26:22.000Z", "max_issues_repo_path": "include/Teisko/ColorCorrection.hpp", "max_issues_repo_name": "intel/image-quality-and-characterization-utilities", "max_issues_repo_head_hexsha": "ef58f9aea906e6453b8cec4a891104d16dd44f93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Teisko/ColorCorrection.hpp", "max_forks_repo_name": "intel/image-quality-and-characterization-utilities", "max_forks_repo_head_hexsha": "ef58f9aea906e6453b8cec4a891104d16dd44f93", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T11:39:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-17T11:38:29.000Z", "avg_line_length": 37.30859375, "max_line_length": 110, "alphanum_fraction": 0.5849649251, "num_tokens": 2353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4268682268572087}}
{"text": "/* Author: Guido Kanschat, University of Heidelberg, 2003  */\n/*         Baerbel Janssen, University of Heidelberg, 2010 */\n/*         Wolfgang Bangerth, Texas A&M University, 2010   */\n\n/*    $Id: step-16.cc 28506 2013-02-21 02:47:24Z bangerth $       */\n/*                                                                */\n/*    Copyright (C) 2003-2004, 2006-2013 by the deal.II authors                   */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n// As discussed in the introduction, most of this program is copied almost\n// verbatim from step-6, which itself is only a slight modification of\n// step-5. Consequently, a significant part of this program is not new if\n// you've read all the material up to step-6, and we won't comment on that\n// part of the functionality that is unchanged. Rather, we will focus on those\n// aspects of the program that have to do with the multigrid functionality\n// which forms the new aspect of this tutorial program.\n\n// @sect3{Include files}\n\n// Again, the first few include files are already known, so we won't comment\n// on them:\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/utilities.h>\n\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n\n// These, now, are the include necessary for the multi-level methods. The\n// first two declare classes that allow us to enumerate degrees of freedom not\n// only on the finest mesh level, but also on intermediate levels (that's what\n// the MGDoFHandler class does) as well as allow to access this information\n// (iterators and accessors over these cells).\n//\n// The rest of the include files deals with the mechanics of multigrid as a\n// linear operator (solver or preconditioner).\n#include <deal.II/multigrid/mg_dof_handler.h>\n#include <deal.II/multigrid/mg_constrained_dofs.h>\n#include <deal.II/multigrid/multigrid.h>\n#include <deal.II/multigrid/mg_transfer.h>\n#include <deal.II/multigrid/mg_tools.h>\n#include <deal.II/multigrid/mg_coarse.h>\n#include <deal.II/multigrid/mg_smoother.h>\n#include <deal.II/multigrid/mg_matrix.h>\n\n// This is C++:\n#include <fstream>\n#include <sstream>\n\n// The last step is as in all previous programs:\nnamespace Step16\n{\n  using namespace dealii;\n\n\n  // @sect3{The <code>LaplaceProblem</code> class template}\n\n  // This main class is basically the same class as in step-6. As far as\n  // member functions is concerned, the only addition is the\n  // <code>assemble_multigrid</code> function that assembles the matrices that\n  // correspond to the discrete operators on intermediate levels:\n  template <int dim>\n  class LaplaceProblem\n  {\n  public:\n    LaplaceProblem (const unsigned int deg);\n    void run ();\n\n  private:\n    void setup_system ();\n    void assemble_system ();\n    void assemble_multigrid ();\n    void solve ();\n    void refine_grid ();\n    void output_results (const unsigned int cycle) const;\n\n    Triangulation<dim>   triangulation;\n    FE_Q<dim>            fe;\n    MGDoFHandler<dim>    mg_dof_handler;\n\n    SparsityPattern      sparsity_pattern;\n    SparseMatrix<double> system_matrix;\n\n    // We need an additional object for the hanging nodes constraints. They\n    // are handed to the transfer object in the multigrid. Since we call a\n    // compress inside the multigrid these constraints are not allowed to be\n    // inhomogeneous so we store them in different ConstraintMatrix objects.\n    ConstraintMatrix     hanging_node_constraints;\n    ConstraintMatrix     constraints;\n\n    Vector<double>       solution;\n    Vector<double>       system_rhs;\n\n    const unsigned int degree;\n\n    // The following four objects are the only additional member variables,\n    // compared to step-6. They first three represent the operators that act\n    // on individual levels of the multilevel hierarchy, rather than on the\n    // finest mesh as do the objects above while the last object stores\n    // information about the boundary indices on each level and information\n    // about indices lying on a refinement edge between two different\n    // refinement levels.\n    //\n    // To facilitate having objects on each level of a multilevel hierarchy,\n    // deal.II has the MGLevelObject class template that provides storage for\n    // objects on each level. What we need here are matrices on each level,\n    // which implies that we also need sparsity patterns on each level. As\n    // outlined in the @ref mg_paper, the operators (matrices) that we need\n    // are actually twofold: one on the interior of each level, and one at the\n    // interface between each level and that part of the domain where the mesh\n    // is coarser. In fact, we will need the latter in two versions: for the\n    // direction from coarse to fine mesh and from fine to\n    // coarse. Fortunately, however, we here have a self-adjoint problem for\n    // which one of these is the transpose of the other, and so we only have\n    // to build one; we choose the one from coarse to fine.\n    MGLevelObject<SparsityPattern>       mg_sparsity_patterns;\n    MGLevelObject<SparseMatrix<double> > mg_matrices;\n    MGLevelObject<SparseMatrix<double> > mg_interface_matrices;\n    MGConstrainedDoFs                    mg_constrained_dofs;\n  };\n\n\n\n  // @sect3{Nonconstant coefficients}\n\n  // The implementation of nonconstant coefficients is copied verbatim from\n  // step-5 and step-6:\n\n  template <int dim>\n  class Coefficient : public Function<dim>\n  {\n  public:\n    Coefficient () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n\n    virtual void value_list (const std::vector<Point<dim> > &points,\n                             std::vector<double>            &values,\n                             const unsigned int              component = 0) const;\n  };\n\n\n\n  template <int dim>\n  double Coefficient<dim>::value (const Point<dim> &p,\n                                  const unsigned int) const\n  {\n    if (p.square() < 0.5*0.5)\n      return 20;\n    else\n      return 1;\n  }\n\n\n\n  template <int dim>\n  void Coefficient<dim>::value_list (const std::vector<Point<dim> > &points,\n                                     std::vector<double>            &values,\n                                     const unsigned int              component) const\n  {\n    const unsigned int n_points = points.size();\n\n    Assert (values.size() == n_points,\n            ExcDimensionMismatch (values.size(), n_points));\n\n    Assert (component == 0,\n            ExcIndexRange (component, 0, 1));\n\n    for (unsigned int i=0; i<n_points; ++i)\n      values[i] = Coefficient<dim>::value (points[i]);\n  }\n\n\n  // @sect3{The <code>LaplaceProblem</code> class implementation}\n\n  // @sect4{LaplaceProblem::LaplaceProblem}\n\n  // The constructor is left mostly unchanged. We take the polynomial degree\n  // of the finite elements to be used as a constructor argument and store it\n  // in a member variable.\n  //\n  // By convention, all adaptively refined triangulations in deal.II never\n  // change by more than one level across a face between cells. For our\n  // multigrid algorithms, however, we need a slightly stricter guarantee,\n  // namely that the mesh also does not change by more than refinement level\n  // across vertices that might connect two cells. In other words, we must\n  // prevent the following situation:\n  //\n  // @image html limit_level_difference_at_vertices.png \"\"\n  //\n  // This is achieved by passing the\n  // Triangulation::limit_level_difference_at_vertices flag to the constructor\n  // of the triangulation class.\n  template <int dim>\n  LaplaceProblem<dim>::LaplaceProblem (const unsigned int degree)\n    :\n    triangulation (Triangulation<dim>::\n                   limit_level_difference_at_vertices),\n    fe (degree),\n    mg_dof_handler (triangulation),\n    degree(degree)\n  {}\n\n\n\n  // @sect4{LaplaceProblem::setup_system}\n\n  // The following function extends what the corresponding one in step-6\n  // did. The top part, apart from the additional output, does the same:\n  template <int dim>\n  void LaplaceProblem<dim>::setup_system ()\n  {\n    mg_dof_handler.distribute_dofs (fe);\n\n    // Here we output not only the degrees of freedom on the finest level, but\n    // also in the multilevel structure\n    deallog << \"Number of degrees of freedom: \"\n            << mg_dof_handler.n_dofs();\n\n    for (unsigned int l=0; l<triangulation.n_levels(); ++l)\n      deallog << \"   \" << 'L' << l << \": \"\n              << mg_dof_handler.n_dofs(l);\n    deallog  << std::endl;\n\n    sparsity_pattern.reinit (mg_dof_handler.n_dofs(),\n                             mg_dof_handler.n_dofs(),\n                             mg_dof_handler.max_couplings_between_dofs());\n    DoFTools::make_sparsity_pattern (mg_dof_handler, sparsity_pattern);\n\n    solution.reinit (mg_dof_handler.n_dofs());\n    system_rhs.reinit (mg_dof_handler.n_dofs());\n\n    // But it starts to be a wee bit different here, although this still\n    // doesn't have anything to do with multigrid methods. step-6 took care of\n    // boundary values and hanging nodes in a separate step after assembling\n    // the global matrix from local contributions. This works, but the same\n    // can be done in a slightly simpler way if we already take care of these\n    // constraints at the time of copying local contributions into the global\n    // matrix. To this end, we here do not just compute the constraints do to\n    // hanging nodes, but also due to zero boundary conditions. We will use\n    // this set of constraints later on to help us copy local contributions\n    // correctly into the global linear system right away, without the need\n    // for a later clean-up stage:\n    constraints.clear ();\n    hanging_node_constraints.clear ();\n    DoFTools::make_hanging_node_constraints (mg_dof_handler, hanging_node_constraints);\n    DoFTools::make_hanging_node_constraints (mg_dof_handler, constraints);\n\n    typename FunctionMap<dim>::type      dirichlet_boundary;\n    ZeroFunction<dim>                    homogeneous_dirichlet_bc (1);\n    dirichlet_boundary[0] = &homogeneous_dirichlet_bc;\n    VectorTools::interpolate_boundary_values (static_cast<const DoFHandler<dim>&>(mg_dof_handler),\n                                              dirichlet_boundary,\n                                              constraints);\n    constraints.close ();\n    hanging_node_constraints.close ();\n    constraints.condense (sparsity_pattern);\n    sparsity_pattern.compress();\n    system_matrix.reinit (sparsity_pattern);\n\n    // The multigrid constraints have to be initialized. They need to know\n    // about the boundary values as well, so we pass the\n    // <code>dirichlet_boundary</code> here as well.\n    mg_constrained_dofs.clear();\n    mg_constrained_dofs.initialize(mg_dof_handler, dirichlet_boundary);\n\n\n    // Now for the things that concern the multigrid data structures. First,\n    // we resize the multi-level objects to hold matrices and sparsity\n    // patterns for every level. The coarse level is zero (this is mandatory\n    // right now but may change in a future revision). Note that these\n    // functions take a complete, inclusive range here (not a starting index\n    // and size), so the finest level is <code>n_levels-1</code>.  We first\n    // have to resize the container holding the SparseMatrix classes, since\n    // they have to release their SparsityPattern before the can be destroyed\n    // upon resizing.\n    const unsigned int n_levels = triangulation.n_levels();\n\n    mg_interface_matrices.resize(0, n_levels-1);\n    mg_interface_matrices.clear ();\n    mg_matrices.resize(0, n_levels-1);\n    mg_matrices.clear ();\n    mg_sparsity_patterns.resize(0, n_levels-1);\n\n    // Now, we have to provide a matrix on each level. To this end, we first\n    // use the MGTools::make_sparsity_pattern function to first generate a\n    // preliminary compressed sparsity pattern on each level (see the @ref\n    // Sparsity module for more information on this topic) and then copy it\n    // over to the one we really want. The next step is to initialize both\n    // kinds of level matrices with these sparsity patterns.\n    //\n    // It may be worth pointing out that the interface matrices only have\n    // entries for degrees of freedom that sit at or next to the interface\n    // between coarser and finer levels of the mesh. They are therefore even\n    // sparser than the matrices on the individual levels of our multigrid\n    // hierarchy. If we were more concerned about memory usage (and possibly\n    // the speed with which we can multiply with these matrices), we should\n    // use separate and different sparsity patterns for these two kinds of\n    // matrices.\n    for (unsigned int level=0; level<n_levels; ++level)\n      {\n        CompressedSparsityPattern csp;\n        csp.reinit(mg_dof_handler.n_dofs(level),\n                   mg_dof_handler.n_dofs(level));\n        MGTools::make_sparsity_pattern(mg_dof_handler, csp, level);\n\n        mg_sparsity_patterns[level].copy_from (csp);\n\n        mg_matrices[level].reinit(mg_sparsity_patterns[level]);\n        mg_interface_matrices[level].reinit(mg_sparsity_patterns[level]);\n      }\n  }\n\n\n  // @sect4{LaplaceProblem::assemble_system}\n\n  // The following function assembles the linear system on the finesh level of\n  // the mesh. It is almost exactly the same as in step-6, with the exception\n  // that we don't eliminate hanging nodes and boundary values after\n  // assembling, but while copying local contributions into the global\n  // matrix. This is not only simpler but also more efficient for large\n  // problems.\n  //\n  // This latter trick is something that only found its way into deal.II over\n  // time and wasn't used in the initial version of this tutorial\n  // program. There is, however, a discussion of this function in the\n  // introduction of step-27.\n  template <int dim>\n  void LaplaceProblem<dim>::assemble_system ()\n  {\n    const QGauss<dim>  quadrature_formula(degree+1);\n\n    FEValues<dim> fe_values (fe, quadrature_formula,\n                             update_values    |  update_gradients |\n                             update_quadrature_points  |  update_JxW_values);\n\n    const unsigned int   dofs_per_cell = fe.dofs_per_cell;\n    const unsigned int   n_q_points    = quadrature_formula.size();\n\n    FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n    Vector<double>       cell_rhs (dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    const Coefficient<dim> coefficient;\n    std::vector<double>    coefficient_values (n_q_points);\n\n    typename MGDoFHandler<dim>::active_cell_iterator\n    cell = mg_dof_handler.begin_active(),\n    endc = mg_dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        cell_matrix = 0;\n        cell_rhs = 0;\n\n        fe_values.reinit (cell);\n\n        coefficient.value_list (fe_values.get_quadrature_points(),\n                                coefficient_values);\n\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            {\n              for (unsigned int j=0; j<dofs_per_cell; ++j)\n                cell_matrix(i,j) += (coefficient_values[q_point] *\n                                     fe_values.shape_grad(i,q_point) *\n                                     fe_values.shape_grad(j,q_point) *\n                                     fe_values.JxW(q_point));\n\n              cell_rhs(i) += (fe_values.shape_value(i,q_point) *\n                              1.0 *\n                              fe_values.JxW(q_point));\n            }\n\n        cell->get_dof_indices (local_dof_indices);\n        constraints.distribute_local_to_global (cell_matrix, cell_rhs,\n                                                local_dof_indices,\n                                                system_matrix, system_rhs);\n      }\n  }\n\n\n  // @sect4{LaplaceProblem::assemble_multigrid}\n\n  // The next function is the one that builds the linear operators (matrices)\n  // that define the multigrid method on each level of the mesh. The\n  // integration core is the same as above, but the loop below will go over\n  // all existing cells instead of just the active ones, and the results must\n  // be entered into the correct matrix. Note also that since we only do\n  // multi-level preconditioning, no right-hand side needs to be assembled\n  // here.\n  //\n  // Before we go there, however, we have to take care of a significant amount\n  // of book keeping:\n  template <int dim>\n  void LaplaceProblem<dim>::assemble_multigrid ()\n  {\n    QGauss<dim>  quadrature_formula(1+degree);\n\n    FEValues<dim> fe_values (fe, quadrature_formula,\n                             update_values   | update_gradients |\n                             update_quadrature_points | update_JxW_values);\n\n    const unsigned int   dofs_per_cell   = fe.dofs_per_cell;\n    const unsigned int   n_q_points      = quadrature_formula.size();\n\n    FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    const Coefficient<dim> coefficient;\n    std::vector<double>    coefficient_values (n_q_points);\n\n    // Next a few things that are specific to building the multigrid data\n    // structures (since we only need them in the current function, rather\n    // than also elsewhere, we build them here instead of the\n    // <code>setup_system</code> function). Some of the following may be a bit\n    // obscure if you're not familiar with the algorithm actually implemented\n    // in deal.II to support multilevel algorithms on adaptive meshes; if some\n    // of the things below seem strange, take a look at the @ref mg_paper.\n    //\n    // Our first job is to identify those degrees of freedom on each level\n    // that are located on interfaces between adaptively refined levels, and\n    // those that lie on the interface but also on the exterior boundary of\n    // the domain. As in many other parts of the library, we do this by using\n    // boolean masks, i.e. vectors of booleans each element of which indicates\n    // whether the corresponding degree of freedom index is an interface DoF\n    // or not. The <code>MGConstraints</code> already computed the information\n    // for us when we called initialize in <code>setup_system()</code>.\n    std::vector<std::vector<bool> > interface_dofs\n      = mg_constrained_dofs.get_refinement_edge_indices ();\n    std::vector<std::vector<bool> > boundary_interface_dofs\n      = mg_constrained_dofs.get_refinement_edge_boundary_indices ();\n\n    // The indices just identified will later be used to decide where the\n    // assembled value has to be added into on each level.  On the other hand,\n    // we also have to impose zero boundary conditions on the external\n    // boundary of each level. But this the <code>MGConstraints</code> knows\n    // it. So we simply ask for them by calling <code>get_boundary_indices\n    // ()</code>.  The third step is to construct constraints on all those\n    // degrees of freedom: their value should be zero after each application\n    // of the level operators. To this end, we construct ConstraintMatrix\n    // objects for each level, and add to each of these constraints for each\n    // degree of freedom. Due to the way the ConstraintMatrix stores its data,\n    // the function to add a constraint on a single degree of freedom and\n    // force it to be zero is called Constraintmatrix::add_line(); doing so\n    // for several degrees of freedom at once can be done using\n    // Constraintmatrix::add_lines():\n    std::vector<ConstraintMatrix> boundary_constraints (triangulation.n_levels());\n    std::vector<ConstraintMatrix> boundary_interface_constraints (triangulation.n_levels());\n    for (unsigned int level=0; level<triangulation.n_levels(); ++level)\n      {\n        boundary_constraints[level].add_lines (interface_dofs[level]);\n        boundary_constraints[level].add_lines (mg_constrained_dofs.get_boundary_indices()[level]);\n        boundary_constraints[level].close ();\n\n        boundary_interface_constraints[level]\n        .add_lines (boundary_interface_dofs[level]);\n        boundary_interface_constraints[level].close ();\n      }\n\n    // Now that we're done with most of our preliminaries, let's start the\n    // integration loop. It looks mostly like the loop in\n    // <code>assemble_system</code>, with two exceptions: (i) we don't need a\n    // right hand side, and more significantly (ii) we don't just loop over\n    // all active cells, but in fact all cells, active or not. Consequently,\n    // the correct iterator to use is MGDoFHandler::cell_iterator rather than\n    // MGDoFHandler::active_cell_iterator. Let's go about it:\n    typename MGDoFHandler<dim>::cell_iterator cell = mg_dof_handler.begin(),\n                                              endc = mg_dof_handler.end();\n\n    for (; cell!=endc; ++cell)\n      {\n        cell_matrix = 0;\n        fe_values.reinit (cell);\n\n        coefficient.value_list (fe_values.get_quadrature_points(),\n                                coefficient_values);\n\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            for (unsigned int j=0; j<dofs_per_cell; ++j)\n              cell_matrix(i,j) += (coefficient_values[q_point] *\n                                   fe_values.shape_grad(i,q_point) *\n                                   fe_values.shape_grad(j,q_point) *\n                                   fe_values.JxW(q_point));\n\n        // The rest of the assembly is again slightly different. This starts\n        // with a gotcha that is easily forgotten: The indices of global\n        // degrees of freedom we want here are the ones for current level, not\n        // for the global matrix. We therefore need the function\n        // MGDoFAccessorLLget_mg_dof_indices, not\n        // MGDoFAccessor::get_dof_indices as used in the assembly of the\n        // global system:\n        cell->get_mg_dof_indices (local_dof_indices);\n\n        // Next, we need to copy local contributions into the level\n        // objects. We can do this in the same way as in the global assembly,\n        // using a constraint object that takes care of constrained degrees\n        // (which here are only boundary nodes, as the individual levels have\n        // no hanging node constraints). Note that the\n        // <code>boundary_constraints</code> object makes sure that the level\n        // matrices contains no contributions from degrees of freedom at the\n        // interface between cells of different refinement level.\n        boundary_constraints[cell->level()]\n        .distribute_local_to_global (cell_matrix,\n                                     local_dof_indices,\n                                     mg_matrices[cell->level()]);\n\n        // The next step is again slightly more obscure (but explained in the\n        // @ref mg_paper): We need the remainder of the operator that we just\n        // copied into the <code>mg_matrices</code> object, namely the part on\n        // the interface between cells at the current level and cells one\n        // level coarser. This matrix exists in two directions: for interior\n        // DoFs (index $i$) of the current level to those sitting on the\n        // interface (index $j$), and the other way around. Of course, since\n        // we have a symmetric operator, one of these matrices is the\n        // transpose of the other.\n        //\n        // The way we assemble these matrices is as follows: since the are\n        // formed from parts of the local contributions, we first delete all\n        // those parts of the local contributions that we are not interested\n        // in, namely all those elements of the local matrix for which not $i$\n        // is an interface DoF and $j$ is not. The result is one of the two\n        // matrices that we are interested in, and we then copy it into the\n        // <code>mg_interface_matrices</code> object. The\n        // <code>boundary_interface_constraints</code> object at the same time\n        // makes sure that we delete contributions from all degrees of freedom\n        // that are not only on the interface but also on the external\n        // boundary of the domain.\n        //\n        // The last part to remember is how to get the other matrix. Since it\n        // is only the transpose, we will later (in the <code>solve()</code>\n        // function) be able to just pass the transpose matrix where\n        // necessary.\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          for (unsigned int j=0; j<dofs_per_cell; ++j)\n            if ( !(interface_dofs[cell->level()][local_dof_indices[i]]==true &&\n                   interface_dofs[cell->level()][local_dof_indices[j]]==false))\n              cell_matrix(i,j) = 0;\n\n        boundary_interface_constraints[cell->level()]\n        .distribute_local_to_global (cell_matrix,\n                                     local_dof_indices,\n                                     mg_interface_matrices[cell->level()]);\n      }\n  }\n\n\n\n  // @sect4{LaplaceProblem::solve}\n\n  // This is the other function that is significantly different in support of\n  // the multigrid solver (or, in fact, the preconditioner for which we use\n  // the multigrid method).\n  //\n  // Let us start out by setting up two of the components of multilevel\n  // methods: transfer operators between levels, and a solver on the coarsest\n  // level. In finite element methods, the transfer operators are derived from\n  // the finite element function spaces involved and can often be computed in\n  // a generic way independent of the problem under consideration. In that\n  // case, we can use the MGTransferPrebuilt class that, given the constraints\n  // on the global level and an MGDoFHandler object computes the matrices\n  // corresponding to these transfer operators.\n  //\n  // The second part of the following lines deals with the coarse grid\n  // solver. Since our coarse grid is very coarse indeed, we decide for a\n  // direct solver (a Householder decomposition of the coarsest level matrix),\n  // even if its implementation is not particularly sophisticated. If our\n  // coarse mesh had many more cells than the five we have here, something\n  // better suited would obviously be necessary here.\n  template <int dim>\n  void LaplaceProblem<dim>::solve ()\n  {\n\n    // Create the object that deals with the transfer between different\n    // refinement levels. We need to pass it the hanging node constraints.\n    MGTransferPrebuilt<Vector<double> > mg_transfer(hanging_node_constraints, mg_constrained_dofs);\n    // Now the prolongation matrix has to be built.  This matrix needs to take\n    // the boundary values on each level into account and needs to know about\n    // the indices at the refinement egdes. The <code>MGConstraints</code>\n    // knows about that so pass it as an argument.\n    mg_transfer.build_matrices(mg_dof_handler);\n\n    FullMatrix<double> coarse_matrix;\n    coarse_matrix.copy_from (mg_matrices[0]);\n    MGCoarseGridHouseholder<> coarse_grid_solver;\n    coarse_grid_solver.initialize (coarse_matrix);\n\n    // The next component of a multilevel solver or preconditioner is that we\n    // need a smoother on each level. A common choice for this is to use the\n    // application of a relaxation method (such as the SOR, Jacobi or\n    // Richardson method) or a small number of iterations of a solver method\n    // (such as CG or GMRES). The mg::SmootherRelaxation and\n    // MGSmootherPrecondition classes provide support for these two kinds of\n    // smoothers. Here, we opt for the application of a single SOR\n    // iteration. To this end, we define an appropriate <code>typedef</code>\n    // and then setup a smoother object.\n    //\n    // Since this smoother needs temporary vectors to store intermediate\n    // results, we need to provide a VectorMemory object. Since these vectors\n    // will be reused over and over, the GrowingVectorMemory is more time\n    // efficient than the PrimitiveVectorMemory class in the current case.\n    //\n    // The last step is to initialize the smoother object with our level\n    // matrices and to set some smoothing parameters.  The\n    // <code>initialize()</code> function can optionally take additional\n    // arguments that will be passed to the smoother object on each level. In\n    // the current case for the SOR smoother, this could, for example, include\n    // a relaxation parameter. However, we here leave these at their default\n    // values. The call to <code>set_steps()</code> indicates that we will use\n    // two pre- and two post-smoothing steps on each level; to use a variable\n    // number of smoother steps on different levels, more options can be set\n    // in the constructor call to the <code>mg_smoother</code> object.\n    //\n    // The last step results from the fact that we use the SOR method as a\n    // smoother - which is not symmetric - but we use the conjugate gradient\n    // iteration (which requires a symmetric preconditioner) below, we need to\n    // let the multilevel preconditioner make sure that we get a symmetric\n    // operator even for nonsymmetric smoothers:\n    typedef PreconditionSOR<SparseMatrix<double> > Smoother;\n    mg::SmootherRelaxation<Smoother, Vector<double> > mg_smoother;\n    mg_smoother.initialize(mg_matrices);\n    mg_smoother.set_steps(2);\n    mg_smoother.set_symmetric(true);\n\n    // The next preparatory step is that we must wrap our level and interface\n    // matrices in an object having the required multiplication functions. We\n    // will create two objects for the interface objects going from coarse to\n    // fine and the other way around; the multigrid algorithm will later use\n    // the transpose operator for the latter operation, allowing us to\n    // initialize both up and down versions of the operator with the matrices\n    // we already built:\n    MGMatrix<> mg_matrix(&mg_matrices);\n    MGMatrix<> mg_interface_up(&mg_interface_matrices);\n    MGMatrix<> mg_interface_down(&mg_interface_matrices);\n\n    // Now, we are ready to set up the V-cycle operator and the multilevel\n    // preconditioner.\n    Multigrid<Vector<double> > mg(mg_dof_handler,\n                                  mg_matrix,\n                                  coarse_grid_solver,\n                                  mg_transfer,\n                                  mg_smoother,\n                                  mg_smoother);\n    mg.set_edge_matrices(mg_interface_down, mg_interface_up);\n\n    PreconditionMG<dim, Vector<double>, MGTransferPrebuilt<Vector<double> > >\n    preconditioner(mg_dof_handler, mg, mg_transfer);\n\n    // With all this together, we can finally get about solving the linear\n    // system in the usual way:\n    SolverControl solver_control (1000, 1e-12);\n    SolverCG<>    cg (solver_control);\n\n    solution = 0;\n\n    cg.solve (system_matrix, solution, system_rhs,\n              preconditioner);\n    constraints.distribute (solution);\n\n    std::cout << \"   \" << solver_control.last_step()\n              << \" CG iterations needed to obtain convergence.\"\n              << std::endl;\n  }\n\n\n\n  // @sect4{Postprocessing}\n\n  // The following two functions postprocess a solution once it is\n  // computed. In particular, the first one refines the mesh at the beginning\n  // of each cycle while the second one outputs results at the end of each\n  // such cycle. The functions are almost unchanged from those in step-6, with\n  // the exception of two minor differences: The KellyErrorEstimator::estimate\n  // function wants an argument of type DoFHandler, not MGDoFHandler, and so\n  // we have to cast from derived to base class; and we generate output in VTK\n  // format, to use the more modern visualization programs available today\n  // compared to those that were available when step-6 was written.\n  template <int dim>\n  void LaplaceProblem<dim>::refine_grid ()\n  {\n    Vector<float> estimated_error_per_cell (triangulation.n_active_cells());\n\n    KellyErrorEstimator<dim>::estimate (static_cast<DoFHandler<dim>&>(mg_dof_handler),\n                                        QGauss<dim-1>(3),\n                                        typename FunctionMap<dim>::type(),\n                                        solution,\n                                        estimated_error_per_cell);\n    GridRefinement::refine_and_coarsen_fixed_number (triangulation,\n                                                     estimated_error_per_cell,\n                                                     0.3, 0.03);\n    triangulation.execute_coarsening_and_refinement ();\n  }\n\n\n\n  template <int dim>\n  void LaplaceProblem<dim>::output_results (const unsigned int cycle) const\n  {\n    DataOut<dim> data_out;\n\n    data_out.attach_dof_handler (mg_dof_handler);\n    data_out.add_data_vector (solution, \"solution\");\n    data_out.build_patches ();\n\n    std::ostringstream filename;\n    filename << \"solution-\"\n             << cycle\n             << \".vtk\";\n\n    std::ofstream output (filename.str().c_str());\n    data_out.write_vtk (output);\n  }\n\n\n  // @sect4{LaplaceProblem::run}\n\n  // Like several of the functions above, this is almost exactly a copy of of\n  // the corresponding function in step-6. The only difference is the call to\n  // <code>assemble_multigrid</code> that takes care of forming the matrices\n  // on every level that we need in the multigrid method.\n  template <int dim>\n  void LaplaceProblem<dim>::run ()\n  {\n    for (unsigned int cycle=0; cycle<8; ++cycle)\n      {\n        std::cout << \"Cycle \" << cycle << ':' << std::endl;\n\n        if (cycle == 0)\n          {\n            GridGenerator::hyper_ball (triangulation);\n\n            static const HyperBallBoundary<dim> boundary;\n            triangulation.set_boundary (0, boundary);\n\n            triangulation.refine_global (1);\n          }\n        else\n          refine_grid ();\n\n\n        std::cout << \"   Number of active cells:       \"\n                  << triangulation.n_active_cells()\n                  << std::endl;\n\n        setup_system ();\n\n        std::cout << \"   Number of degrees of freedom: \"\n                  << mg_dof_handler.n_dofs()\n                  << \" (by level: \";\n        for (unsigned int level=0; level<triangulation.n_levels(); ++level)\n          std::cout << mg_dof_handler.n_dofs(level)\n                    << (level == triangulation.n_levels()-1\n                        ? \")\" : \", \");\n        std::cout << std::endl;\n\n        assemble_system ();\n        assemble_multigrid ();\n\n        solve ();\n        output_results (cycle);\n      }\n  }\n}\n\n\n// @sect3{The main() function}\n//\n// This is again the same function as in step-6:\nint main ()\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step16;\n\n      deallog.depth_console (0);\n\n      LaplaceProblem<2> laplace_problem(1);\n      laplace_problem.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "a7e1eafceefcbb1b4c1777c10e76dfc66389f923", "size": 36677, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-16/step-16.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/step-16/step-16.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/step-16/step-16.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 43.8195937873, "max_line_length": 99, "alphanum_fraction": 0.6597049922, "num_tokens": 8302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4268682268572087}}
{"text": "﻿/*\r\nCopyright(c) 2014 Akihiro Nishimura\r\n\r\nThis software is released under the MIT License.\r\nhttp://opensource.org/licenses/mit-license.php\r\n*/\r\n\r\n#include \"ctr.h\"\r\n#include \"SigUtil/lib/calculation/binary_operation.hpp\"\r\n#include \"SigUtil/lib/tools/convergence.hpp\"\r\n#include \"SigUtil/lib/functional/filter.hpp\"\r\n#include \"SigUtil/lib/functional/list_deal.hpp\"\r\n#include <Eigen/Dense>\r\n\r\n#include \"SigUtil/lib/tools/time_watch.hpp\"\r\n\r\nnamespace sigtm\r\n{\r\n//using namespace boost::numeric;\r\n\r\nconst double projection_z = 1.0;\r\n\r\nstatic double safe_log(double x)\r\n{\r\n\treturn x > 0 ? std::log(x) : log_lower_limit;\r\n};\r\n\r\n\r\ntemplate <class C>\r\nstatic auto row_(C&& src, uint i) ->decltype(ublas::row(src, i))\r\n{\r\n\treturn ublas::row(src, i);\r\n}\r\nstatic auto row_(EigenMatrix& src, uint i) ->decltype(src.row(i))\r\n{\r\n\treturn src.row(i);\r\n}\r\nstatic auto row_(EigenMatrix const& src, uint i) ->decltype(src.row(i))\r\n{\r\n\treturn src.row(i);\r\n}\r\n\r\ntemplate <class C>\r\nstatic auto at_(C&& src, uint row, uint col) ->decltype(src(row, col))\r\n{\r\n\treturn src(row, col);\r\n}\r\nstatic auto at_(EigenMatrix& src, uint row, uint col) ->decltype(src.coeffRef(col, row))\r\n{\r\n\treturn src.coeffRef(col, row);\r\n}\r\nstatic auto at_(EigenMatrix const& src, uint row, uint col) ->decltype(src.coeffRef(col, row))\r\n{\r\n\treturn src.coeffRef(col, row);\r\n}\r\n\r\ntemplate <class V>\r\nvoid normalize_dist_v(V&& vec)\r\n{\r\n\tdouble sum = vec.sum();\r\n\tvec /= sum;\r\n}\r\ntemplate <class F, class V>\r\nauto map_v(F&& func, V&& vec)\r\n{\r\n\tusing RT = decltype(sig::impl::eval(std::forward<F>(func), std::forward<V>(vec)(0)));\r\n\r\n\tEigenVector result(vec.size());\r\n\r\n\tfor (uint i = 0, size = vec.size(); i < size; ++i){\r\n\t\tresult[i] = std::forward<F>(func)(std::forward<V>(vec)(i));\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\ntemplate <class F, class M>\r\nauto map_m(F&& func, M&& mat)\r\n{\r\n\tusing RT = decltype(sig::impl::eval(std::forward<F>(func), std::forward<M>(mat)(0, 0)));\r\n\r\n\tconst uint col_size = mat.cols();\r\n\tconst uint row_size = mat.rows();\r\n\r\n\tEigenMatrix result(col_size, row_size);\r\n\r\n\tfor (uint i = 0; i < col_size; ++i){\r\n\t\tfor (uint j = 0; j < row_size; ++j){\r\n\t\t\tresult(i, j) = std::forward<F>(func)(std::forward<M>(mat)(i, j));\r\n\t\t}\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\n\r\ntemplate <class V>\r\nbool is_feasible(V const& x)\r\n{\r\n\tdouble val;\r\n\tdouble sum = 0;\r\n\tfor (uint i = 0, size = x.size()-1; i < size; ++i) {\r\n\t\tval = x[i];\r\n\t\tif (val < 0 || val >1) return false;\r\n\t\tsum += val;\r\n\t\tif (sum > 1) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\n// project x on to simplex (using // http://www.cs.berkeley.edu/~jduchi/projects/DuchiShSiCh08.pdf)\r\ntemplate <class V1, class V2>\r\nvoid simplex_projection(\r\n\tV1 const& x,\r\n\tV2& x_proj,\r\n\tdouble z)\r\n{\r\n\tx_proj = x;\r\n\tstd::sort(x_proj.data(), x_proj.data() + x_proj.size());\r\n\tdouble cumsum = -z, u;\r\n\tint j = 0;\r\n\t\r\n\tfor (int i = x.size() - 1; i >= 0; --i) {\r\n\t\tu = x_proj[i];\r\n\t\tcumsum += u;\r\n\t\tif (u > cumsum / (j + 1)) j++;\r\n\t\telse break;\r\n\t}\r\n\tdouble theta = cumsum / j;\r\n\tfor (int i = 0, size = x.size(); i < size; ++i) {\r\n\t\tu = x[i] - theta;\r\n\t\tif (u <= 0) u = 0.0;\r\n\t\tx_proj[i] = u;\r\n\t}\r\n\tnormalize_dist_v(x_proj); // fix the normaliztion issue due to numerical errors\r\n}\r\n\r\ntemplate <class V1, class V2, class V3>\r\nauto df_simplex(\r\n\tV1 const&gamma,\r\n\tV2 const& v,\r\n\tdouble lambda,\r\n\tV3 const& opt_x)\r\n{\r\n\tEigenVector g = -lambda * (opt_x - v);\r\n\tEigenVector y = gamma;\r\n\r\n\t//sig::for_each_v([](double& v1, double v2){ v1 /= v2; }, y, opt_x);\r\n\tfor(uint i = 0, size = y.size(); i < size; ++i){\r\n\t\ty[i] /= opt_x[i];\r\n\t}\r\n\r\n\tg += y;\r\n\t\r\n\t//sig::for_each_v([](double& v1){ v1 *= -1; }, g);\r\n\tg.array() *= -1;\r\n\r\n\treturn g;\r\n}\r\n\r\ntemplate <class V1, class V2, class V3>\r\ndouble f_simplex(\r\n\tV1 const& gamma,\r\n\tV2 const& v,\r\n\tdouble lambda,\r\n\tV3 const& opt_x)\r\n{\r\n\tauto y = map_v([&](double x){ return safe_log(x); }, opt_x);\r\n\tauto z = v - opt_x;\r\n\t\r\n\t//double f = ublas::inner_prod(y, gamma);\r\n\tdouble f = y.dot(gamma);\r\n\t\r\n\t//double val = ublas::inner_prod(z, z);\r\n\tdouble val = z.dot(z);\r\n\r\n\tf -= 0.5 * lambda * val;\r\n\r\n\treturn -f;\r\n}\r\n\r\n// projection gradient algorithm\r\ntemplate <class V1, class V2, class V3>\r\nvoid optimize_simplex(\r\n\tV1 const& gamma, \r\n\tV2 const& v, \r\n\tdouble lambda,\r\n\tV3& opt_x)\r\n{\r\n\tsize_t size = sig::min(gamma.size(), v.size());\r\n\tEigenVector x_bar(size);\r\n\tEigenVector opt_x_old = opt_x;\r\n\r\n\tdouble f_old = f_simplex(gamma, v, lambda, opt_x);\r\n\r\n\tauto g = df_simplex(gamma, v, lambda, opt_x);\r\n\r\n\tnormalize_dist_v(g);\r\n\t//double ab_sum = sig::sum(g);\r\n\t//if (ab_sum > 1.0) g *= (1.0 / ab_sum); // rescale the gradient\r\n\r\n\topt_x -= g;\r\n\r\n\tsimplex_projection(opt_x, x_bar, projection_z);\r\n\r\n\tx_bar -= opt_x_old;\r\n\t\r\n\t//double r = 0.5 * ublas::inner_prod(g, x_bar);\r\n\tdouble r = 0.5 * g.dot(x_bar);\r\n\r\n\tconst double beta = 0.5;\r\n\tdouble t = beta;\r\n\tfor (uint iter = 0; iter < 100; ++iter) {\r\n\t\topt_x = opt_x_old;\r\n\t\topt_x += t * x_bar;\r\n\r\n\t\tdouble f_new = f_simplex(gamma, v, lambda, opt_x);\r\n\r\n\t\tif (f_new > f_old + r * t) t = t * beta;\r\n\t\telse break;\r\n\t}\r\n\r\n\tif (!is_feasible(opt_x))  printf(\"sth is wrong, not feasible. you've got to check it ...\\n\");\r\n}\r\n\r\n\r\nvoid CTR::init()\r\n{\r\n\tsig::SimpleRandom<double> randf(0, 1, FixedRandom);\r\n\r\n\tbeta_ = MatrixKV_(V_, K_); //SIG_INIT_MATRIX(double, K, V, 0);\r\n\r\n\tif (hparam_->beta_.empty()){\r\n\t\tfor(TopicId k = 0; k < K_; ++k){\r\n\t\t\tauto& beta_v = row_(beta_, k);\t\t\t\r\n\t\t\tfor (uint v = 0; v < V_; ++v) beta_v[v] = randf() + hparam_->beta_smooth_;\r\n\t\t\tnormalize_dist_v(beta_v);\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tstd::cout << \"beta loading\" << std::endl;\r\n\t\t//beta_ = sig::to_matrix_ublas(hparam_->beta_);\r\n\t\tfor (uint k = 0; k < K_; ++k){\r\n\t\t\tfor (uint v = 0; v < V_; ++v) beta_(v, k) = hparam_->beta_[k][v];\r\n\t\t}\r\n\t}\r\n\r\n\r\n\ttheta_ = MatrixIK_::Zero(K_, I_); // SIG_INIT_MATRIX(double, I, K, 0);\r\n\r\n\tif (hparam_->theta_opt_){\r\n\t\tif (hparam_->theta_.empty()){\r\n\t\t\tfor (ItemId i = 0; i < I_; ++i){\r\n\t\t\t\tauto& theta_v = row_(theta_, i);\r\n\t\t\t\tfor (uint k = 0; k < K_; ++k) theta_v[k] = randf() + hparam_->alpha_smooth_;\r\n\t\t\t\tnormalize_dist_v(theta_v);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse{\r\n\t\t\tstd::cout << \"theta loading\" << std::endl;\r\n\t\t\t//theta_ = sig::to_matrix_ublas(hparam_->theta_);\r\n\t\t\tfor (uint i = 0; i < I_; ++i){\r\n\t\t\t\tfor (uint k = 0; k < K_; ++k) beta_(k, i) = hparam_->beta_[i][k];\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tuser_factor_ = MatrixUK_::Zero(U_, K_);\r\n\titem_factor_ = MatrixIK_::Zero(I_, K_);\r\n\r\n\tif (hparam_->theta_opt_){\r\n\t\tfor (ItemId i = 0; i < I_; ++i){\r\n\t\t\tauto& if_v = row_(item_factor_, i);\r\n\t\t\tfor (uint k = 0; k < K_; ++k) if_v[k] = randf();\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\titem_factor_ = theta_;\r\n\t}\r\n}\r\n\r\n\r\nvoid CTR::printUFactor() const\r\n{\r\n\tstd::cout << \"user_factor\" << std::endl;\r\n\tfor (uint u = 0; u<U_; ++u){\r\n\t\tfor (uint k = 0; k<K_; ++k) std::cout << user_factor_(u, k) << \", \";\r\n\t\tstd::cout << std::endl;\r\n\t}\r\n}\r\nvoid CTR::printIFactor() const\r\n{\r\n\tstd::cout << \"item_factor\" << std::endl;\r\n\tfor (uint i = 0; i<I_; ++i){\r\n\t\tfor (uint k = 0; k<K_; ++k) std::cout << item_factor_(i, k) << \", \";\r\n\t\tstd::cout << std::endl;\r\n\t}\r\n}\r\n\r\n/*\r\n\tstd::cout << \"estimate rating\" << std::endl;\r\n\tfor (uint u = 0; u<ratings_->userSize(); ++u){\r\n\t\tfor (uint i = 0; i<ratings_->itemSize(); ++i) std::cout << estimate(u, i) << \", \";\r\n\t\tstd::cout << std::endl;\r\n\t}\r\n\tstd::cout << std::endl;\r\n*/\r\n\r\nvoid CTR::saveTmp() const\r\n{\r\n\t/*\r\n\tsprintf(name, \"%s/%04d-U.dat\", directory, iter);\r\n      FILE * file_U = fopen(name, \"w\");\r\n      mtx_fprintf(file_U, user_factor_);\r\n      fclose(file_U);\r\n\r\n      sprintf(name, \"%s/%04d-V.dat\", directory, iter);\r\n      FILE * file_V = fopen(name, \"w\");\r\n      mtx_fprintf(file_V, item_factor_);\r\n      fclose(file_V);\r\n\r\n      if (hparam_->ctr_run) { \r\n        sprintf(name, \"%s/%04d-theta.dat\", directory, iter);\r\n        FILE * file_theta = fopen(name, \"w\");\r\n        mtx_fprintf(file_theta, m_theta);\r\n        fclose(file_theta);\r\n\r\n        sprintf(name, \"%s/%04d-beta.dat\", directory, iter);\r\n        FILE * file_beta = fopen(name, \"w\");\r\n        mtx_fprintf(file_beta, m_beta);\r\n        fclose(file_beta);\r\n\t}\r\n\t*/\r\n}\r\n\r\nvoid CTR::save() const\r\n{\r\n}\r\n\r\nvoid CTR::load()\r\n{\r\n\r\n}\r\n\r\ndouble CTR::docInference(ItemId id,\tbool update_word_ss)\r\n{\r\n\tdouble pseudo_count = 1.0;\r\n\tdouble likelihood = 0;\r\n\tauto const& theta_v = row_(theta_, id);\r\n\tauto log_theta_v = map_v([&](double x){ return safe_log(x); }, theta_v);\r\n\t\r\n\tfor (auto tid : item_tokens_[id]){\r\n\t\tWordId w = tokens_[tid].word_id;\r\n\t\tauto& phi_v = row_(phi_, tid);\r\n\r\n\t\tfor (TopicId k = 0; k < K_; ++k){\r\n\t\t\tphi_v[k] = theta_v[k] * at_(beta_, k, w);\r\n\t\t}\r\n\t\tnormalize_dist_v(phi_v);\r\n\r\n\t\tfor (TopicId k = 0; k < K_; ++k){\r\n\t\t\tdouble const& p = phi_v[k];\r\n\t\t\tif (p > 0){\r\n\t\t\t\tlikelihood += p * (log_theta_v[k] + log_beta_(k, w) - std::log(p));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (pseudo_count > 0) {\r\n\t\t//likelihood += pseudo_count * std::accumulate(std::begin(log_theta_v), std::end(log_theta_v), 0.0);\r\n\t\tlikelihood += pseudo_count * log_theta_v.sum();\r\n\t}\r\n\r\n\t// smoothing with small pseudo counts\r\n\t//sig::for_each_v([&](double& v){ v = pseudo_count; }, gamma_);\r\n\tgamma_.array() += pseudo_count;\r\n\t\r\n\tfor (auto tid : item_tokens_[id]){\r\n\t\tfor (TopicId k = 0; k < K_; ++k) {\r\n\t\t\t//double x = doc->m_counts[tid] * phi_(tid, k);\t// doc_word_ct only\r\n\t\t\tdouble const& x = at_(phi_, tid, k);\r\n\t\t\tgamma_[k] += x;\r\n\t\t\t\r\n\t\t\tif (update_word_ss){\r\n\t\t\t\tat_(word_ss_, k, tokens_[tid].word_id) -= x;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn likelihood;\r\n}\r\n\r\nvoid CTR::updateU()\r\n{ \r\n\tdouble delta_ab = hparam_->a_ - hparam_->b_;\r\n\tMatrixKK_ XX = MatrixKK_::Zero(K_, K_);\r\n\r\n\t// calculate VCV^T in equation(8)\r\n\tfor (uint i = 0; i < I_; i ++){\r\n\t\tif (std::begin(item_ratings_[i]) != std::end(item_ratings_[i])){\r\n\t\t\tauto const& vec_v = row_(item_factor_, i);\r\n\r\n\t\t\t//XX += outer_prod(vec_v, vec_v);\r\n\t\t\tXX += vec_v.transpose() * vec_v;\r\n\t\t}\r\n    }\r\n\t\r\n\t// negative item weight\r\n\tXX *= hparam_->b_;\r\n\r\n\t//sig::for_diagonal([&](double& v){ v += hparam_->lambda_u_; }, XX);\r\n\tXX.diagonal().array() += hparam_->lambda_u_;\r\n\t\t\r\n\tfor (uint j = 0; j < U_; ++j){\r\n\t\tauto const& ratings = user_ratings_[j];\r\n\r\n\t\tif (std::begin(ratings) != std::end(ratings)){\r\n\t\t\tEigenMatrix A = XX;\r\n\t\t\tVectorK_ x(K_, 0);\r\n\r\n\t\t\tfor (auto rating : ratings){\r\n\t\t\t\tauto const& vec_v = row_(item_factor_, rating->item_id_);\r\n\r\n\t\t\t\tA += delta_ab * vec_v.transpose() * vec_v;\r\n\t\t\t\tx += hparam_->a_ * vec_v;\r\n\t\t\t}\r\n\r\n\t\t\tauto vec_u = row_(user_factor_, j);\r\n\t\t\t//vec_u = *sig::matrix_vector_solve(std::move(A), std::move(x));\t// update vector u\r\n\t\t\tauto slv = A.fullPivLu().solve(x);\r\n\t\t\tfor (uint k = 0; k < K_; ++k) vec_u.coeffRef(k) = slv.coeff(k);\r\n\r\n\t\t\t// update the likelihood\r\n\t\t\t//auto result = inner_prod(vec_u, vec_u);\r\n\t\t\tauto result = vec_u.dot(vec_u);\r\n\t\t\tlikelihood_ += -0.5 * hparam_->lambda_u_ * result;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid CTR::updateV()\r\n{\r\n\tdouble delta_ab = hparam_->a_ - hparam_->b_;\r\n\tMatrixKK_ XX = MatrixKK_::Zero(K_, K_);\r\n\t\r\n\tfor (uint j = 0; j < U_; ++j){\r\n\t\tif (std::begin(user_ratings_[j]) != std::end(user_ratings_[j])){\r\n\t\t\tauto const& vec_u = row_(user_factor_, j);\r\n\t\t\t//XX += outer_prod(vec_u, vec_u);\r\n\t\t\tXX += vec_u.transpose() * vec_u;\r\n\t\t}\r\n\t}\r\n\tXX.array() *= hparam_->b_;\r\n\t\t\r\n\tfor (uint i = 0; i < I_; ++i){\r\n\t\tauto& vec_v = row_(item_factor_, i);\r\n\t\tauto const& theta_v = row_(theta_, i);\r\n\t\tauto const& ratings = item_ratings_[i];\r\n\r\n\t\tif (std::begin(ratings) != std::end(ratings)){\r\n\t\t\tEigenMatrix A = XX;\r\n\t\t\tVectorK_ x(K_, 0);\r\n\r\n\t\t\tfor (auto rating : ratings){\r\n\t\t\t\tauto const& vec_u = row_(user_factor_, rating->user_id_);\r\n\r\n\t\t\t\t//A += delta_ab * outer_prod(vec_u, vec_u);\r\n\t\t\t\tA += delta_ab * vec_u.transpose() * vec_u;\r\n\t\t\t\tx += hparam_->a_ * vec_u;\r\n\t\t\t}\r\n\r\n\t\t\t//sig::for_each_v([&](double& x, double t){ x += hparam_->lambda_v_ * t; }, xx, theta_v);\r\n\t\t\tx += hparam_->lambda_v_ * theta_v;\t// adding the topic vector\r\n\r\n\t\t\r\n\t\t\tEigenMatrix B = A;\t\t// save for computing likelihood \r\n\r\n\t\t\t//sig::for_diagonal([&](double& v){ v += hparam_->lambda_v_; }, A);\r\n\t\t\tA.diagonal().array() += hparam_->lambda_v_;\r\n\r\n\t\t\t//vec_v = *sig::matrix_vector_solve(A, std::move(x));\t// update vector v\r\n\t\t\tvec_v = A.colPivHouseholderQr().solve(x);\r\n\r\n\t\t\t// update the likelihood for the relevant part\r\n\t\t\tlikelihood_ += -0.5 * item_ratings_[i].size() * hparam_->a_;\r\n\r\n\r\n\t\t\tfor (auto rating : ratings){\r\n\t\t\t\tauto const& vec_u = row_(user_factor_, rating->user_id_);\r\n\t\t\t\t//auto result = inner_prod(vec_u, vec_v);\r\n\t\t\t\tauto result = vec_u.dot(vec_u);\r\n\r\n\t\t\t\tlikelihood_ += hparam_->a_ * result;\r\n\t\t\t}\r\n\t\t\t//likelihood_ += -0.5 * ublas::inner_prod(vec_v, ublas::prod(B, vec_v));\r\n\t\t\tlikelihood_ += -0.5 * vec_v.dot(B * vec_v.transpose());\r\n\r\n\t\t\t// likelihood part of theta, even when theta=0, which is a special case\r\n\t\t\tEigenVector x2 = vec_v;\r\n\t\t\t\r\n\t\t\t//sig::for_each_v([](double& v1, double v2){ v1 -= v2; }, x2, theta_v);\r\n\t\t\tx2 -= theta_v;\r\n\r\n\t\t\t//auto result = inner_prod(x2, x2);\r\n\t\t\tauto result = x2.dot(x2);\r\n\t\t\tlikelihood_ += -0.5 * hparam_->lambda_v_ * result;\r\n\r\n\t\t\tif (hparam_->theta_opt_){\r\n\t\t\t\tlikelihood_ += docInference(i, true);\r\n\t\t\t\toptimize_simplex(gamma_, vec_v, hparam_->lambda_v_, row_(theta_, i));\r\n\t\t\t}\r\n\t\t}\r\n\t\telse{\r\n\t\t\t// m=0, this article has never been rated\r\n\t\t\tif (hparam_->theta_opt_) {\r\n\t\t\t\tdocInference(i, false);\r\n\t\t\t\tnormalize_dist_v(gamma_);\r\n\t\t\t\trow_(theta_, i) = gamma_;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid CTR::updateBeta()\r\n{\r\n\tbeta_ = word_ss_;\r\n\r\n\tfor (TopicId k = 0; k < K_; ++k){\r\n\t\tauto& beta_v = row_(beta_, k);\r\n\r\n\t\tnormalize_dist_v(beta_v);\r\n\t\trow_(log_beta_, k) = map_v([&](double x){ return safe_log(x); }, beta_v);\r\n\t}\r\n}\r\n\r\nauto CTR::recommend_impl(Id id, bool for_user) const->std::vector<EstValueType>\r\n{\r\n\tstd::vector<EstValueType> result;\r\n\r\n\tif (for_user){\r\n\t\tuint i = 0;\r\n\t\tfor (auto e : user_ratings_[id]){\r\n\t\t\tfor (uint ed = e->item_id_; i < ed; ++i){\r\n\t\t\t\tresult.push_back(std::make_pair(i, estimate(id, i)));\r\n\t\t\t}\r\n\t\t\ti = e->item_id_ + 1;\r\n\t\t}\r\n\t\tfor (; i < I_; ++i){\r\n\t\t\tresult.push_back(std::make_pair(i, estimate(id, i)));\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tuint u = 0;\r\n\t\tfor (auto e : item_ratings_[id]){\r\n\t\t\tfor (uint ed = e->item_id_; u < ed; ++u){\r\n\t\t\t\tresult.push_back(std::make_pair(u, estimate(u, id)));\r\n\t\t\t}\r\n\t\t\tu = e->user_id_ + 1;\r\n\t\t}\r\n\t\tfor (; u < U_; ++u){\r\n\t\t\tresult.push_back(std::make_pair(u, estimate(u, id)));\r\n\t\t}\r\n\t}\r\n\r\n\tsig::sort(result, [](std::pair<Id, double> const& v1, std::pair<Id, double> const& v2){ return v1.second > v2.second; });\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid CTR::train(uint max_iter, uint min_iter, uint save_lag)\r\n{\r\n\tuint iter = 0;\r\n\tdouble likelihood_old;\r\n\tsig::ManageConvergenceSimple conv(conv_epsilon_);\r\n\t\r\n\tauto info_print = [](uint iter, double likelihood, double converge){\r\n\t\tstd::cout << \"iter=\" << iter << \", likelihood=\" << likelihood << \", converge=\" << converge << std::endl;\r\n\t\treturn true;\r\n\t};\r\n\r\n\tif (max_iter < min_iter) std::swap(max_iter, min_iter);\r\n\r\n\tif (hparam_->theta_opt_){\r\n\t\tgamma_ = VectorK_::Zero(K_);\r\n\t\tlog_beta_ = map_m([&](double x){ return safe_log(x); }, beta_);\r\n\t\tword_ss_ = MatrixKV_(V_, K_); // SIG_INIT_MATRIX(double, K, V, 0);\r\n\t\tphi_ = MatrixKV_(K_, T_);  //SIG_INIT_MATRIX(double, T, K, 0);\r\n\t}\r\n\r\n\t while ((!conv.is_convergence() && iter < max_iter) || iter < min_iter)\r\n\t {\r\n\t\tlikelihood_old = likelihood_;\r\n\t\tlikelihood_ = 0.0;\r\n\r\n\t\t//printUFactor();\r\n\t\t//printIFactor();\r\n\r\n\t\t//sig::TimeWatch tw;\r\n\t\tupdateU();\r\n\t\t//tw.save();\r\n\t\t//std::cout << tw.get_total_time() << std::endl;\r\n\r\n\t\t//if (hparam_->lda_regression_) break; // one iteration is enough for lda-regression\r\n\r\n\t\tupdateV();\r\n\t\t\r\n\t\t// update beta if needed\r\n\t\tif (hparam_->theta_opt_) updateBeta();\r\n\r\n\t\tif(likelihood_ < likelihood_old) std::cout << \"likelihood is decreasing!\" << std::endl;\r\n\t\t\r\n\t\t// save intermediate results\r\n\t\tif (iter % save_lag == 0) {\r\n\t\t\tsaveTmp();\r\n\t\t}\r\n\r\n\t\t++iter;\r\n\t\tconv.update( sig::abs_delta(likelihood_, likelihood_old) / likelihood_old);\r\n\r\n\t\tinfo_print(iter, likelihood_, conv.get_value());\r\n\t }\r\n\r\n\t std::cout << \"train finished\" << std::endl;\r\n}\r\n\r\nauto CTR::recommend(Id id, bool for_user, sig::Maybe<uint> top_n, sig::Maybe<double> threshold) const->std::vector<EstValueType>\r\n{\r\n\tauto result = recommend_impl(id, for_user);\r\n\r\n\tif (top_n) result = sig::take(*top_n, std::move(result));\r\n\tif (threshold) sig::filter([&](std::pair<Id, double> const& e){ return e.second > *threshold; }, std::move(result));\r\n\r\n\treturn result;\r\n}\r\n\r\ninline double CTR::estimate(UserId u_id, ItemId i_id) const\r\n{\r\n\t//return inner_prod(row_(user_factor_, u_id), row_(item_factor_, i_id));\r\n\treturn row_(user_factor_, u_id).dot(row_(item_factor_, i_id));\r\n}\r\n\r\n/*\r\nvoid c_ctr::learn_map_estimate(\r\n\tconst c_data* users,\r\n\tconst c_data* items,\r\n\tconst c_corpus* c,\r\n\tconst ctr_hyperparameter* param,\r\n\tconst char* directory)\r\n{\r\n  // init model parameters\r\n  printf(\"\\ninitializing the model ...\\n\");\r\n  init_model(hparam_->ctr_run);\r\n\r\n  // filename\r\n  char name[500];\r\n\r\n  // start time\r\n  time_t start, current;\r\n  time(&start);\r\n  int elapsed = 0;\r\n\r\n  int iter = 0;\r\n  double likelihood = -exp(50), likelihood_old;\r\n  double converge = 1.0;\r\n\r\n  /// create the state log file \r\n  sprintf(name, \"%s/state.log\", directory);\r\n  FILE* file = fopen(name, \"w\");\r\n  fprintf(file, \"iter time likelihood converge\\n\");\r\n\r\n  int i, j, m, n, l, k;\r\n  int* item_ids; \r\n  int* user_ids;\r\n\r\n  double result;\r\n\r\n  /// confidence parameters\r\n  double a_minus_b = hparam_->a - hparam_->b;\r\n\r\n  \r\n  update();  \r\n \r\n  save();\r\n\r\n  // free memory\r\n  gsl_matrix_free(XX);\r\n  gsl_matrix_free(A);\r\n  gsl_matrix_free(B);\r\n  gsl_vector_free(x);\r\n\r\n  if (hparam_->ctr_run && hparam_->theta_opt) {\r\n    gsl_matrix_free(phi);\r\n    gsl_matrix_free(log_beta);\r\n    gsl_matrix_free(word_ss);\r\n    gsl_vector_free(gamma);\r\n  }\r\n}\r\n*/\r\n\r\n}\t// sigtm", "meta": {"hexsha": "5c91f4173a37aecd60a77d10f6606e956401bcbd", "size": 17601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SigTM/lib/model/ctr.cpp", "max_stars_repo_name": "regenschauer490/TopicModel", "max_stars_repo_head_hexsha": "d9a2be5801d7e4da7429bca828039accf1b30033", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SigTM/lib/model/ctr.cpp", "max_issues_repo_name": "regenschauer490/TopicModel", "max_issues_repo_head_hexsha": "d9a2be5801d7e4da7429bca828039accf1b30033", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SigTM/lib/model/ctr.cpp", "max_forks_repo_name": "regenschauer490/TopicModel", "max_forks_repo_head_hexsha": "d9a2be5801d7e4da7429bca828039accf1b30033", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1084165478, "max_line_length": 129, "alphanum_fraction": 0.5936594512, "num_tokens": 5509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4268682268572087}}
{"text": "/*\n * Copyright (c) 2008, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the Willow Garage, Inc. nor the names of its\n *       contributors may be used to endorse or promote products derived from\n *       this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n/*\n * Author: Stuart Glaser\n */\n\n#include <boost/shared_ptr.hpp>\n\n#include \"robot_mechanism_controllers/joint_spline_trajectory_controller.h\"\n#include <sstream>\n#include \"angles/angles.h\"\n#include \"pluginlib/class_list_macros.h\"\n\nPLUGINLIB_EXPORT_CLASS( controller::JointSplineTrajectoryController, pr2_controller_interface::Controller)\n\nnamespace controller {\n\n// These functions are pulled from the spline_smoother package.\n// They've been moved here to avoid depending on packages that aren't\n// mature yet.\n\n\nstatic inline void generatePowers(int n, double x, double* powers)\n{\n  powers[0] = 1.0;\n  for (int i=1; i<=n; i++)\n  {\n    powers[i] = powers[i-1]*x;\n  }\n}\n\nstatic void getQuinticSplineCoefficients(double start_pos, double start_vel, double start_acc,\n    double end_pos, double end_vel, double end_acc, double time, std::vector<double>& coefficients)\n{\n  coefficients.resize(6);\n\n  if (time == 0.0)\n  {\n    coefficients[0] = end_pos;\n    coefficients[1] = end_vel;\n    coefficients[2] = 0.5*end_acc;\n    coefficients[3] = 0.0;\n    coefficients[4] = 0.0;\n    coefficients[5] = 0.0;\n  }\n  else\n  {\n    double T[6];\n    generatePowers(5, time, T);\n\n    coefficients[0] = start_pos;\n    coefficients[1] = start_vel;\n    coefficients[2] = 0.5*start_acc;\n    coefficients[3] = (-20.0*start_pos + 20.0*end_pos - 3.0*start_acc*T[2] + end_acc*T[2] -\n                       12.0*start_vel*T[1] - 8.0*end_vel*T[1]) / (2.0*T[3]);\n    coefficients[4] = (30.0*start_pos - 30.0*end_pos + 3.0*start_acc*T[2] - 2.0*end_acc*T[2] +\n                       16.0*start_vel*T[1] + 14.0*end_vel*T[1]) / (2.0*T[4]);\n    coefficients[5] = (-12.0*start_pos + 12.0*end_pos - start_acc*T[2] + end_acc*T[2] -\n                       6.0*start_vel*T[1] - 6.0*end_vel*T[1]) / (2.0*T[5]);\n  }\n}\n\n/**\n * \\brief Samples a quintic spline segment at a particular time\n */\nstatic void sampleQuinticSpline(const std::vector<double>& coefficients, double time,\n    double& position, double& velocity, double& acceleration)\n{\n  // create powers of time:\n  double t[6];\n  generatePowers(5, time, t);\n\n  position = t[0]*coefficients[0] +\n      t[1]*coefficients[1] +\n      t[2]*coefficients[2] +\n      t[3]*coefficients[3] +\n      t[4]*coefficients[4] +\n      t[5]*coefficients[5];\n\n  velocity = t[0]*coefficients[1] +\n      2.0*t[1]*coefficients[2] +\n      3.0*t[2]*coefficients[3] +\n      4.0*t[3]*coefficients[4] +\n      5.0*t[4]*coefficients[5];\n\n  acceleration = 2.0*t[0]*coefficients[2] +\n      6.0*t[1]*coefficients[3] +\n      12.0*t[2]*coefficients[4] +\n      20.0*t[3]*coefficients[5];\n}\n\nstatic void getCubicSplineCoefficients(double start_pos, double start_vel,\n    double end_pos, double end_vel, double time, std::vector<double>& coefficients)\n{\n  coefficients.resize(4);\n\n  if (time == 0.0)\n  {\n    coefficients[0] = end_pos;\n    coefficients[1] = end_vel;\n    coefficients[2] = 0.0;\n    coefficients[3] = 0.0;\n  }\n  else\n  {\n    double T[4];\n    generatePowers(3, time, T);\n\n    coefficients[0] = start_pos;\n    coefficients[1] = start_vel;\n    coefficients[2] = (-3.0*start_pos + 3.0*end_pos - 2.0*start_vel*T[1] - end_vel*T[1]) / T[2];\n    coefficients[3] = (2.0*start_pos - 2.0*end_pos + start_vel*T[1] + end_vel*T[1]) / T[3];\n  }\n}\n\n\nJointSplineTrajectoryController::JointSplineTrajectoryController()\n  : loop_count_(0), robot_(NULL)\n{\n}\n\nJointSplineTrajectoryController::~JointSplineTrajectoryController()\n{\n  sub_command_.shutdown();\n  serve_query_state_.shutdown();\n}\n\nbool JointSplineTrajectoryController::init(pr2_mechanism_model::RobotState *robot, ros::NodeHandle &n)\n{\n  using namespace XmlRpc;\n  node_ = n;\n  robot_ = robot;\n\n  // Gets all of the joints\n  XmlRpc::XmlRpcValue joint_names;\n  if (!node_.getParam(\"joints\", joint_names))\n  {\n    ROS_ERROR(\"No joints given. (namespace: %s)\", node_.getNamespace().c_str());\n    return false;\n  }\n  if (joint_names.getType() != XmlRpc::XmlRpcValue::TypeArray)\n  {\n    ROS_ERROR(\"Malformed joint specification.  (namespace: %s)\", node_.getNamespace().c_str());\n    return false;\n  }\n  for (int i = 0; i < joint_names.size(); ++i)\n  {\n    XmlRpcValue &name_value = joint_names[i];\n    if (name_value.getType() != XmlRpcValue::TypeString)\n    {\n      ROS_ERROR(\"Array of joint names should contain all strings.  (namespace: %s)\",\n                node_.getNamespace().c_str());\n      return false;\n    }\n\n    pr2_mechanism_model::JointState *j = robot->getJointState((std::string)name_value);\n    if (!j) {\n      ROS_ERROR(\"Joint not found: %s. (namespace: %s)\",\n                ((std::string)name_value).c_str(), node_.getNamespace().c_str());\n      return false;\n    }\n    joints_.push_back(j);\n  }\n\n  // Ensures that all the joints are calibrated.\n  for (size_t i = 0; i < joints_.size(); ++i)\n  {\n    if (!joints_[i]->calibrated_)\n    {\n      ROS_ERROR(\"Joint %s was not calibrated (namespace: %s)\",\n                joints_[i]->joint_->name.c_str(), node_.getNamespace().c_str());\n      return false;\n    }\n  }\n\n  // Sets up pid controllers for all of the joints\n  std::string gains_ns;\n  if (!node_.getParam(\"gains\", gains_ns))\n    gains_ns = node_.getNamespace() + \"/gains\";\n  pids_.resize(joints_.size());\n  for (size_t i = 0; i < joints_.size(); ++i)\n    if (!pids_[i].init(ros::NodeHandle(gains_ns + \"/\" + joints_[i]->joint_->name)))\n      return false;\n\n  // Creates a dummy trajectory\n  boost::shared_ptr<SpecifiedTrajectory> traj_ptr(new SpecifiedTrajectory(1));\n  SpecifiedTrajectory &traj = *traj_ptr;\n  traj[0].start_time = robot_->getTime().toSec();\n  traj[0].duration = 0.0;\n  traj[0].splines.resize(joints_.size());\n  for (size_t j = 0; j < joints_.size(); ++j)\n    traj[0].splines[j].coef[0] = 0.0;\n  current_trajectory_box_.set(traj_ptr);\n\n  sub_command_ = node_.subscribe(\"command\", 1, &JointSplineTrajectoryController::commandCB, this);\n  serve_query_state_ = node_.advertiseService(\n    \"query_state\", &JointSplineTrajectoryController::queryStateService, this);\n\n  q.resize(joints_.size());\n  qd.resize(joints_.size());\n  qdd.resize(joints_.size());\n\n  controller_state_publisher_.reset(\n    new realtime_tools::RealtimePublisher<pr2_controllers_msgs::JointTrajectoryControllerState>\n    (node_, \"state\", 1));\n  controller_state_publisher_->lock();\n  for (size_t j = 0; j < joints_.size(); ++j)\n    controller_state_publisher_->msg_.joint_names.push_back(joints_[j]->joint_->name);\n  controller_state_publisher_->msg_.desired.positions.resize(joints_.size());\n  controller_state_publisher_->msg_.desired.velocities.resize(joints_.size());\n  controller_state_publisher_->msg_.desired.accelerations.resize(joints_.size());\n  controller_state_publisher_->msg_.actual.positions.resize(joints_.size());\n  controller_state_publisher_->msg_.actual.velocities.resize(joints_.size());\n  controller_state_publisher_->msg_.error.positions.resize(joints_.size());\n  controller_state_publisher_->msg_.error.velocities.resize(joints_.size());\n  controller_state_publisher_->unlock();\n\n\n  return true;\n}\n\nvoid JointSplineTrajectoryController::starting()\n{\n  last_time_ = robot_->getTime();\n\n  for (size_t i = 0; i < pids_.size(); ++i)\n    pids_[i].reset();\n\n  // Creates a \"hold current position\" trajectory.\n  boost::shared_ptr<SpecifiedTrajectory> hold_ptr(new SpecifiedTrajectory(1));\n  SpecifiedTrajectory &hold = *hold_ptr;\n  hold[0].start_time = last_time_.toSec() - 0.001;\n  hold[0].duration = 0.0;\n  hold[0].splines.resize(joints_.size());\n  for (size_t j = 0; j < joints_.size(); ++j)\n    hold[0].splines[j].coef[0] = joints_[j]->position_;\n\n  current_trajectory_box_.set(hold_ptr);\n}\n\nvoid JointSplineTrajectoryController::update()\n{\n  // Checks if all the joints are calibrated.\n\n  ros::Time time = robot_->getTime();\n  ros::Duration dt = time - last_time_;\n  last_time_ = time;\n\n  boost::shared_ptr<const SpecifiedTrajectory> traj_ptr;\n  current_trajectory_box_.get(traj_ptr);\n  if (!traj_ptr)\n    ROS_FATAL(\"The current trajectory can never be null\");\n\n  // Only because this is what the code originally looked like.\n  const SpecifiedTrajectory &traj = *traj_ptr;\n\n  // Determines which segment of the trajectory to use.  (Not particularly realtime friendly).\n  int seg = -1;\n  while (seg + 1 < (int)traj.size() &&\n         traj[seg+1].start_time < time.toSec())\n  {\n    ++seg;\n  }\n\n  if (seg == -1)\n  {\n    if (traj.size() == 0)\n      ROS_ERROR(\"No segments in the trajectory\");\n    else\n      ROS_ERROR(\"No earlier segments.  First segment starts at %.3lf (now = %.3lf)\", traj[0].start_time, time.toSec());\n    return;\n  }\n\n  // ------ Trajectory Sampling\n\n  for (size_t i = 0; i < q.size(); ++i)\n  {\n    sampleSplineWithTimeBounds(traj[seg].splines[i].coef, traj[seg].duration,\n                               time.toSec() - traj[seg].start_time,\n                               q[i], qd[i], qdd[i]);\n  }\n\n  // ------ Trajectory Following\n\n  std::vector<double> error(joints_.size());\n  for (size_t i = 0; i < joints_.size(); ++i)\n  {\n    error[i] = q[i] - joints_[i]->position_;\n    joints_[i]->commanded_effort_ += pids_[i].computeCommand(error[i],\n          joints_[i]->velocity_ - qd[i], dt);\n  }\n\n  // ------ State publishing\n\n  if (loop_count_ % 10 == 0)\n  {\n    if (controller_state_publisher_ && controller_state_publisher_->trylock())\n    {\n      controller_state_publisher_->msg_.header.stamp = time;\n      for (size_t j = 0; j < joints_.size(); ++j)\n      {\n        controller_state_publisher_->msg_.desired.positions[j] = q[j];\n        controller_state_publisher_->msg_.desired.velocities[j] = qd[j];\n        controller_state_publisher_->msg_.desired.accelerations[j] = qdd[j];\n        controller_state_publisher_->msg_.actual.positions[j] = joints_[j]->position_;\n        controller_state_publisher_->msg_.actual.velocities[j] = joints_[j]->velocity_;\n        controller_state_publisher_->msg_.error.positions[j] = error[j];\n        controller_state_publisher_->msg_.error.velocities[j] = joints_[j]->velocity_ - qd[j];\n      }\n      controller_state_publisher_->unlockAndPublish();\n    }\n  }\n\n  ++loop_count_;\n}\n\nvoid JointSplineTrajectoryController::commandCB(const trajectory_msgs::JointTrajectoryConstPtr &msg)\n{\n  ros::Time time = last_time_;\n  ROS_DEBUG(\"Figuring out new trajectory at %.3lf, with data from %.3lf\",\n            time.toSec(), msg->header.stamp.toSec());\n\n  boost::shared_ptr<SpecifiedTrajectory> new_traj_ptr(new SpecifiedTrajectory);\n  SpecifiedTrajectory &new_traj = *new_traj_ptr;\n\n  // ------ If requested, performs a stop\n\n  if (msg->points.empty())\n  {\n    starting();\n    return;\n  }\n\n  // ------ Correlates the joints we're commanding to the joints in the message\n\n  std::vector<int> lookup(joints_.size(), -1);  // Maps from an index in joints_ to an index in the msg\n  for (size_t j = 0; j < joints_.size(); ++j)\n  {\n    for (size_t k = 0; k < msg->joint_names.size(); ++k)\n    {\n      if (msg->joint_names[k] == joints_[j]->joint_->name)\n      {\n        lookup[j] = k;\n        break;\n      }\n    }\n\n    if (lookup[j] == -1)\n    {\n      ROS_ERROR(\"Unable to locate joint %s in the commanded trajectory.\", joints_[j]->joint_->name.c_str());\n      return;\n    }\n  }\n\n  // ------ Grabs the trajectory that we're currently following.\n\n  boost::shared_ptr<const SpecifiedTrajectory> prev_traj_ptr;\n  current_trajectory_box_.get(prev_traj_ptr);\n  if (!prev_traj_ptr)\n  {\n    ROS_FATAL(\"The current trajectory can never be null\");\n    return;\n  }\n  const SpecifiedTrajectory &prev_traj = *prev_traj_ptr;\n\n  // ------ Copies over the segments from the previous trajectory that are still useful.\n\n  // Useful segments are still relevant after the current time.\n  int first_useful = -1;\n  while (first_useful + 1 < (int)prev_traj.size() &&\n         prev_traj[first_useful + 1].start_time <= time.toSec())\n  {\n    ++first_useful;\n  }\n\n  // Useful segments are not going to be completely overwritten by the message's splines.\n  int last_useful = -1;\n  double msg_start_time;\n  if (msg->points.size() > 0)\n    msg_start_time = (msg->header.stamp + msg->points[0].time_from_start).toSec();\n  else\n    msg_start_time = std::max(time.toSec(), msg->header.stamp.toSec());\n\n  while (last_useful + 1 < (int)prev_traj.size() &&\n         prev_traj[last_useful + 1].start_time < msg_start_time)\n  {\n    ++last_useful;\n  }\n\n  if (last_useful < first_useful)\n    first_useful = last_useful;\n\n  // Copies over the old segments that were determined to be useful.\n  for (int i = std::max(first_useful,0); i <= last_useful; ++i)\n  {\n    new_traj.push_back(prev_traj[i]);\n  }\n\n  // We always save the last segment so that we know where to stop if\n  // there are no new segments.\n  if (new_traj.size() == 0)\n    new_traj.push_back(prev_traj[prev_traj.size() - 1]);\n\n  // ------ Determines when and where the new segments start\n\n  // Finds the end conditions of the final segment\n  Segment &last = new_traj[new_traj.size() - 1];\n  std::vector<double> prev_positions(joints_.size());\n  std::vector<double> prev_velocities(joints_.size());\n  std::vector<double> prev_accelerations(joints_.size());\n\n  ROS_DEBUG(\"Initial conditions for new set of splines:\");\n  for (size_t i = 0; i < joints_.size(); ++i)\n  {\n    sampleSplineWithTimeBounds(last.splines[i].coef, last.duration,\n                               msg->header.stamp.toSec() - last.start_time,\n                               prev_positions[i], prev_velocities[i], prev_accelerations[i]);\n    ROS_DEBUG(\"    %.2lf, %.2lf, %.2lf  (%s)\", prev_positions[i], prev_velocities[i],\n              prev_accelerations[i], joints_[i]->joint_->name.c_str());\n  }\n\n  // ------ Tacks on the new segments\n\n  std::vector<double> positions;\n  std::vector<double> velocities;\n  std::vector<double> accelerations;\n\n  std::vector<double> durations(msg->points.size());\n  durations[0] = msg->points[0].time_from_start.toSec();\n  for (size_t i = 1; i < msg->points.size(); ++i)\n    durations[i] = (msg->points[i].time_from_start - msg->points[i-1].time_from_start).toSec();\n\n  // Checks if we should wrap\n  std::vector<double> wrap(joints_.size(), 0.0);\n  assert(!msg->points[0].positions.empty());\n  for (size_t j = 0; j < joints_.size(); ++j)\n  {\n    if (joints_[j]->joint_->type == urdf::Joint::CONTINUOUS)\n    {\n      double dist = angles::shortest_angular_distance(prev_positions[j], msg->points[0].positions[j]);\n      wrap[j] = (prev_positions[j] + dist) - msg->points[0].positions[j];\n    }\n  }\n\n  for (size_t i = 0; i < msg->points.size(); ++i)\n  {\n    Segment seg;\n\n    seg.start_time = (msg->header.stamp + msg->points[i].time_from_start).toSec() - durations[i];\n    seg.duration = durations[i];\n    seg.splines.resize(joints_.size());\n\n    // Checks that the incoming segment has the right number of elements.\n\n    if (msg->points[i].accelerations.size() != 0 && msg->points[i].accelerations.size() != joints_.size())\n    {\n      ROS_ERROR(\"Command point %d has %d elements for the accelerations\", (int)i, (int)msg->points[i].accelerations.size());\n      return;\n    }\n    if (msg->points[i].velocities.size() != 0 && msg->points[i].velocities.size() != joints_.size())\n    {\n      ROS_ERROR(\"Command point %d has %d elements for the velocities\", (int)i, (int)msg->points[i].velocities.size());\n      return;\n    }\n    if (msg->points[i].positions.size() != joints_.size())\n    {\n      ROS_ERROR(\"Command point %d has %d elements for the positions\", (int)i, (int)msg->points[i].positions.size());\n      return;\n    }\n\n    // Re-orders the joints in the command to match the interal joint order.\n\n    accelerations.resize(msg->points[i].accelerations.size());\n    velocities.resize(msg->points[i].velocities.size());\n    positions.resize(msg->points[i].positions.size());\n    for (size_t j = 0; j < joints_.size(); ++j)\n    {\n      if (!accelerations.empty()) accelerations[j] = msg->points[i].accelerations[lookup[j]];\n      if (!velocities.empty()) velocities[j] = msg->points[i].velocities[lookup[j]];\n      if (!positions.empty()) positions[j] = msg->points[i].positions[lookup[j]] + wrap[j];\n    }\n\n    // Converts the boundary conditions to splines.\n\n    for (size_t j = 0; j < joints_.size(); ++j)\n    {\n      if (prev_accelerations.size() > 0 && accelerations.size() > 0)\n      {\n        getQuinticSplineCoefficients(\n          prev_positions[j], prev_velocities[j], prev_accelerations[j],\n          positions[j], velocities[j], accelerations[j],\n          durations[i],\n          seg.splines[j].coef);\n      }\n      else if (prev_velocities.size() > 0 && velocities.size() > 0)\n      {\n        getCubicSplineCoefficients(\n          prev_positions[j], prev_velocities[j],\n          positions[j], velocities[j],\n          durations[i],\n          seg.splines[j].coef);\n        seg.splines[j].coef.resize(6, 0.0);\n      }\n      else\n      {\n        seg.splines[j].coef[0] = prev_positions[j];\n        if (durations[i] == 0.0)\n          seg.splines[j].coef[1] = 0.0;\n        else\n          seg.splines[j].coef[1] = (positions[j] - prev_positions[j]) / durations[i];\n        seg.splines[j].coef[2] = 0.0;\n        seg.splines[j].coef[3] = 0.0;\n        seg.splines[j].coef[4] = 0.0;\n        seg.splines[j].coef[5] = 0.0;\n      }\n    }\n\n    // Pushes the splines onto the end of the new trajectory.\n\n    new_traj.push_back(seg);\n\n    // Computes the starting conditions for the next segment\n\n    prev_positions = positions;\n    prev_velocities = velocities;\n    prev_accelerations = accelerations;\n  }\n\n  // ------ Commits the new trajectory\n\n  if (!new_traj_ptr)\n  {\n    ROS_ERROR(\"The new trajectory was null!\");\n    return;\n  }\n\n  current_trajectory_box_.set(new_traj_ptr);\n  ROS_DEBUG(\"The new trajectory has %d segments\", (int)new_traj.size());\n#if 0\n  for (size_t i = 0; i < std::min((size_t)20,new_traj.size()); ++i)\n  {\n    ROS_DEBUG(\"Segment %2d: %.3lf for %.3lf\", i, new_traj[i].start_time, new_traj[i].duration);\n    for (size_t j = 0; j < new_traj[i].splines.size(); ++j)\n    {\n      ROS_DEBUG(\"    %.2lf  %.2lf  %.2lf  %.2lf , %.2lf  %.2lf(%s)\",\n                new_traj[i].splines[j].coef[0],\n                new_traj[i].splines[j].coef[1],\n                new_traj[i].splines[j].coef[2],\n                new_traj[i].splines[j].coef[3],\n                new_traj[i].splines[j].coef[4],\n                new_traj[i].splines[j].coef[5],\n                joints_[j]->joint_->name_.c_str());\n    }\n  }\n#endif\n}\n\nbool JointSplineTrajectoryController::queryStateService(\n  pr2_controllers_msgs::QueryTrajectoryState::Request &req,\n  pr2_controllers_msgs::QueryTrajectoryState::Response &resp)\n{\n  boost::shared_ptr<const SpecifiedTrajectory> traj_ptr;\n  current_trajectory_box_.get(traj_ptr);\n  if (!traj_ptr)\n  {\n    ROS_FATAL(\"The current trajectory can never be null\");\n    return false;\n  }\n  const SpecifiedTrajectory &traj = *traj_ptr;\n\n  // Determines which segment of the trajectory to use\n  int seg = -1;\n  while (seg + 1 < (int)traj.size() &&\n         traj[seg+1].start_time < req.time.toSec())\n  {\n    ++seg;\n  }\n  if (seg == -1)\n    return false;\n\n  for (size_t i = 0; i < q.size(); ++i)\n  {\n  }\n\n\n  resp.name.resize(joints_.size());\n  resp.position.resize(joints_.size());\n  resp.velocity.resize(joints_.size());\n  resp.acceleration.resize(joints_.size());\n  for (size_t j = 0; j < joints_.size(); ++j)\n  {\n    resp.name[j] = joints_[j]->joint_->name;\n    sampleSplineWithTimeBounds(traj[seg].splines[j].coef, traj[seg].duration,\n                               req.time.toSec() - traj[seg].start_time,\n                               resp.position[j], resp.velocity[j], resp.acceleration[j]);\n  }\n\n  return true;\n}\n\nvoid JointSplineTrajectoryController::sampleSplineWithTimeBounds(\n  const std::vector<double>& coefficients, double duration, double time,\n  double& position, double& velocity, double& acceleration)\n{\n  if (time < 0)\n  {\n    double _;\n    sampleQuinticSpline(coefficients, 0.0, position, _, _);\n    velocity = 0;\n    acceleration = 0;\n  }\n  else if (time > duration)\n  {\n    double _;\n    sampleQuinticSpline(coefficients, duration, position, _, _);\n    velocity = 0;\n    acceleration = 0;\n  }\n  else\n  {\n    sampleQuinticSpline(coefficients, time,\n                        position, velocity, acceleration);\n  }\n}\n\n}\n", "meta": {"hexsha": "ced6a0cd899c0c15f5e57dcae06afcc88654dde4", "size": 21681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/pr2_controllers/robot_mechanism_controllers/src/joint_spline_trajectory_controller.cpp", "max_stars_repo_name": "Camixxx/-noetic-pr2", "max_stars_repo_head_hexsha": "9a2263bdb4a1b76c39ab5d62e7701baa2a117b7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-15T06:54:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T01:41:13.000Z", "max_issues_repo_path": "catkin_ws/src/pr2_controllers/robot_mechanism_controllers/src/joint_spline_trajectory_controller.cpp", "max_issues_repo_name": "Camixxx/-noetic-pr2", "max_issues_repo_head_hexsha": "9a2263bdb4a1b76c39ab5d62e7701baa2a117b7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "catkin_ws/src/pr2_controllers/robot_mechanism_controllers/src/joint_spline_trajectory_controller.cpp", "max_forks_repo_name": "Camixxx/-noetic-pr2", "max_forks_repo_head_hexsha": "9a2263bdb4a1b76c39ab5d62e7701baa2a117b7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T03:54:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-23T09:47:27.000Z", "avg_line_length": 33.1513761468, "max_line_length": 124, "alphanum_fraction": 0.6514920898, "num_tokens": 5996, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4268682268572087}}
{"text": "/**\n * @file fusion.hpp\n * @brief The main header file for the Code Base\n * \n */\n\n#ifndef _FUSION_HPP_\n#define _FUSION_HPP_\n\n\n//INITIAL STATE ENTER BEFORE FLIGHT\n///////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////\n\n#define x_x_0 0 //initial position in x direction\n#define x_y_0 0 //initial position in y direction\n#define x_z_0 0 //initial position in z direction\n#define v_x_0 0 // initial velocity in the x direction\n#define v_y_0 0 // initial velocity in the y direction\n#define v_z_0 0 // initial velocity in the z direction\n#define a_x_0 0 // initial acceleration in x direction\n#define a_y_0 0 // initial acceleration in y direction\n#define a_z_0 0 // initial acceleration in z direction\n#define theta_x_0 0 // initial attitude in the x direction\n#define theta_y_0 0 // initial attitude in the y direction\n#define theta_z_0 0 // initial attitude in the z direction\n#define omega_x_0 0 // initial angular velocity in the x direction\n#define omega_y_0 0 // initial angular velocity in the y direction\n#define omega_z_0 0 // initial angular velocity in the z direction\n#define alpha_x_0 0 // initial angular acceleration in the x direction\n#define alpha_y_0 0 // initial angular acceleration in the y direction\n#define alpha_z_0 0 // initial angular acceleration in the z direction\n#define mag_x_0 0 //  nitial expected magnetic field reading in the x direction\n#define mag_y_0 0 // initial expected magnetic field reading in the y direction\n#define mag_z_0 0 // initial expected magnetic field reading in the z direction\n\n\n#define p_x_x_0 0.1 //initial position variance in x direction\n#define p_x_y_0 0.1 //initial position variance in y direction\n#define p_x_z_0 0.1 //initial position variance in z direction\n#define p_v_x_0 0.1 // initial velocity variance in the x direction\n#define p_v_y_0 0.1 // initial velocity variance in the y direction\n#define p_v_z_0 0.1 // initial velocity variance in the z direction\n#define p_a_x_0 0.01 // initial acceleration variance in x direction\n#define p_a_y_0 0.01 // initial acceleration variance in y direction\n#define p_a_z_0 0.01 // initial acceleration variance in z direction\n#define p_theta_x_0 0.1 // initial attitude variance in the x direction\n#define p_theta_y_0 0.1 // initial attitude variance in the y direction\n#define p_theta_z_0 0.1 // initial attitude variance in the z direction\n#define p_omega_x_0 0.1 // initial angular velocity variance in the x direction\n#define p_omega_y_0 0.1 // initial angular velocity variance in the y direction\n#define p_omega_z_0 0.1 // initial angular velocity variance in the z direction\n#define p_alpha_x_0 0.01 // initial angular acceleration variance in the x direction\n#define p_alpha_y_0 0.01 // initial angular acceleration variance in the y direction\n#define p_alpha_z_0 0.01 // initial angular acceleration variance in the z direction\n#define p_mag_x_0 0 // initial expected magnetic field reading variance in the x direction\n#define p_mag_y_0 0 // initial expected magnetic field reading variance in the y direction\n#define p_mag_z_0 0 // initial expected magnetic field reading variance in the z direction\n\n\n///////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////\n\n\n\n#include \"Arduino.h\"\n#include \"Eigen.h\"\n#include <Eigen/Eigen>\n#include <Adafruit_BNO055.h>\n#include \"Thread.h\"\n#include <ThreadController.h>\n\n//! IMU Struct\n/*!\n*   This structs holds the BNO055 sample at a point in time to be stored and processed.\n*/\nstruct IMUdata {\n    float GYRO[3] = {0,0,0};             // Gyro in [DPS]\n    float LINEAR_ACCEL[3] = {0,0,0};     // Accelerometer in [m/s^2]\n    float GRAVITY_ACCEL[3] = {0,0,0};    // Accelerometer in [mg]\n    float MAG[3] = {0,0,0};              // Magnetometer in [uT]\n    float Quat[4] = {0,0,0,0};           // {w, x, y, z}\n    float Temp = 0;\n    uint32_t t = 0;\n\n    float phi, theta, psi;                // Roll or phi (X), pitch or theta (Y), and yaw or psi (Z)\n    float q_w, q_x, q_y, q_z;             // Quaternion\n};\n\n//! Main State Estimation Class\n/*!\n*\n*/\nclass State\n{\n    private:\n        float accel_error = 0.0;\n\n        float gyro_error = 0.0;\n        IMUdata *data;\n\n    public:\n        State(IMUdata*);\n        ~State();\n\n        void dataAq(IMUdata *data);\n\n        void predict();\n        void processCovarianceMatrix();\n        void calculateKalmanGain();\n        void stateDetermination();\n        void updatePreviousState();\n        void updateProcessCovarianceMatrix();\n        void updateDynamics();\n        // Eigen::MatrixXd dcmBodyToEarth(double theta, double phi, double psi);\n\n        template<typename T>\n        void print_mtxd(const T& X); \n\n        float calcAccelSystematicError();\n        float calcGyroSystematicError();\n\n        float eulerAngle(float GYRO, float gyro_sen, float gyro_samp); // Function to compute Euler angle\n        void quaternion(float phi, float theta, float psi, float &q_w, float &q_x, float &q_y, float &q_z); // Function to computer Quaternion\n\n    protected:\n};\n\n//! BNO055 IMU Class\n/*!\n*   Class to manage the Adafruit BNO055 Absolute Orientation IMU Fusion breakout board\n*/\nclass DigitalIMU {\n    private:\n        Adafruit_BNO055 board;\n        sensors_event_t event;\n        imu::Quaternion quat;\n        imu::Vector<3> accel;\n    public:\n        DigitalIMU();\n        DigitalIMU(int32_t sensorID, uint8_t address);\n        bool begin();\n        void sample(IMUdata* data, State* ptr);\n};\n\nnamespace constants\n{\n    extern int interval_IMU;\n    extern double dt;\n    extern double baseAccel_error;\n    extern double baseGyro_error;\n    extern float gyro_sen;           // = 900 rad/sec\n};\n\n/* All lower case variables are vectors || all uppercase are Matrices*/\nnamespace matrices\n{\n    // BOTH DISCARDED AFTER FIRST RUN\n    extern Eigen::VectorXd x_0; // Initial State Vector \n    extern Eigen::MatrixXd P_0; // Initial Process Covariance Matrix\n\n    // VECTORS\n    extern Eigen::VectorXd y; /* Observation Vector */\n    extern Eigen::VectorXd x_m; /* Direct Observation Vector */\n    extern Eigen::VectorXd x_k; /* Final State Vector */\n    extern Eigen::VectorXd x_kp; /* State Prediction */\n    extern Eigen::VectorXd x_k_1; /* Previous State Vector (K-1) */\n    extern Eigen::VectorXd w_k; /* Predicted State Noise */\n    extern Eigen::VectorXd z_k; /* Measurement Noise */\n\n    // MATRICES\n    extern Eigen::MatrixXd C; /* Observation Transition Matrix*/\n    extern Eigen::MatrixXd A; /* State Transition Matrix */\n    extern Eigen::MatrixXd P_kp; /* Predicted Process Covariance */\n    extern Eigen::MatrixXd P_k_1; /* Previous Predicted Process Covariance */\n    extern Eigen::MatrixXd R; /* Sensor Covariance Matrix */\n    extern Eigen::MatrixXd H; /* Observation model mapping matrix*/\n    extern Eigen::MatrixXd K; /* Kalman Gain */\n\n    // Identity Matrix\n    extern Eigen::MatrixXd I; /* 21x21 Identity Matrix */\n };\n\n#endif\n", "meta": {"hexsha": "f8177e81256d727fe71529ae0a3c476e48e510b6", "size": 6974, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/src/fusion.hpp", "max_stars_repo_name": "CU-SRL/sensorFusion", "max_stars_repo_head_hexsha": "03aacf669185f0cae05308e7596eabaabd6e34ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/src/fusion.hpp", "max_issues_repo_name": "CU-SRL/sensorFusion", "max_issues_repo_head_hexsha": "03aacf669185f0cae05308e7596eabaabd6e34ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/src/fusion.hpp", "max_forks_repo_name": "CU-SRL/sensorFusion", "max_forks_repo_head_hexsha": "03aacf669185f0cae05308e7596eabaabd6e34ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6972972973, "max_line_length": 142, "alphanum_fraction": 0.6799541153, "num_tokens": 1722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.42686822685720865}}
{"text": "/* boost random/binomial_distribution.hpp header file\n *\n * Copyright Steven Watanabe 2010\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * See http://www.boost.org for most recent version including documentation.\n *\n * $Id$\n */\n\n#ifndef BOOST_RANDOM_BINOMIAL_DISTRIBUTION_HPP_INCLUDED\n#define BOOST_RANDOM_BINOMIAL_DISTRIBUTION_HPP_INCLUDED\n\n#include <boost/config/no_tr1/cmath.hpp>\n#include <cstdlib>\n#include <iosfwd>\n\n#include <boost/random/detail/config.hpp>\n#include <boost/random/uniform_01.hpp>\n\n#include <boost/random/detail/disable_warnings.hpp>\n\nnamespace boost {\nnamespace random {\n\nnamespace detail {\n\ntemplate<class RealType>\nstruct binomial_table {\n    static const RealType table[10];\n};\n\ntemplate<class RealType>\nconst RealType binomial_table<RealType>::table[10] = {\n    0.08106146679532726,\n    0.04134069595540929,\n    0.02767792568499834,\n    0.02079067210376509,\n    0.01664469118982119,\n    0.01387612882307075,\n    0.01189670994589177,\n    0.01041126526197209,\n    0.009255462182712733,\n    0.008330563433362871\n};\n\n}\n\n/**\n * The binomial distribution is an integer valued distribution with\n * two parameters, @c t and @c p.  The values of the distribution\n * are within the range [0,t].\n *\n * The distribution function is\n * \\f$\\displaystyle P(k) = {t \\choose k}p^k(1-p)^{t-k}\\f$.\n *\n * The algorithm used is the BTRD algorithm described in\n *\n *  @blockquote\n *  \"The generation of binomial random variates\", Wolfgang Hormann,\n *  Journal of Statistical Computation and Simulation, Volume 46,\n *  Issue 1 & 2 April 1993 , pages 101 - 110\n *  @endblockquote\n */\ntemplate<class IntType = int, class RealType = double>\nclass binomial_distribution {\npublic:\n    typedef IntType result_type;\n    typedef RealType input_type;\n\n    class param_type {\n    public:\n        typedef binomial_distribution distribution_type;\n        /**\n         * Construct a param_type object.  @c t and @c p\n         * are the parameters of the distribution.\n         *\n         * Requires: t >=0 && 0 <= p <= 1\n         */\n        explicit param_type(IntType t_arg = 1, RealType p_arg = RealType (0.5))\n          : _t(t_arg), _p(p_arg)\n        {}\n        /** Returns the @c t parameter of the distribution. */\n        IntType t() const { return _t; }\n        /** Returns the @c p parameter of the distribution. */\n        RealType p() const { return _p; }\n#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS\n        /** Writes the parameters of the distribution to a @c std::ostream. */\n        template<class CharT, class Traits>\n        friend std::basic_ostream<CharT,Traits>&\n        operator<<(std::basic_ostream<CharT,Traits>& os,\n                   const param_type& parm)\n        {\n            os << parm._p << \" \" << parm._t;\n            return os;\n        }\n    \n        /** Reads the parameters of the distribution from a @c std::istream. */\n        template<class CharT, class Traits>\n        friend std::basic_istream<CharT,Traits>&\n        operator>>(std::basic_istream<CharT,Traits>& is, param_type& parm)\n        {\n            is >> parm._p >> std::ws >> parm._t;\n            return is;\n        }\n#endif\n        /** Returns true if the parameters have the same values. */\n        friend bool operator==(const param_type& lhs, const param_type& rhs)\n        {\n            return lhs._t == rhs._t && lhs._p == rhs._p;\n        }\n        /** Returns true if the parameters have different values. */\n        friend bool operator!=(const param_type& lhs, const param_type& rhs)\n        {\n            return !(lhs == rhs);\n        }\n    private:\n        IntType _t;\n        RealType _p;\n    };\n    \n    /**\n     * Construct a @c binomial_distribution object. @c t and @c p\n     * are the parameters of the distribution.\n     *\n     * Requires: t >=0 && 0 <= p <= 1\n     */\n    explicit binomial_distribution(IntType t_arg = 1,\n                                   RealType p_arg = RealType(0.5))\n      : _t(t_arg), _p(p_arg)\n    {\n        init();\n    }\n    \n    /**\n     * Construct an @c binomial_distribution object from the\n     * parameters.\n     */\n    explicit binomial_distribution(const param_type& parm)\n      : _t(parm.t()), _p(parm.p())\n    {\n        init();\n    }\n    \n    /**\n     * Returns a random variate distributed according to the\n     * binomial distribution.\n     */\n    template<class URNG>\n    IntType operator()(URNG& urng) const\n    {\n        if(use_inversion()) {\n            if(0.5 < _p) {\n                return _t - invert(_t, 1-_p, urng);\n            } else {\n                return invert(_t, _p, urng);\n            }\n        } else if(0.5 < _p) {\n            return _t - generate(urng);\n        } else {\n            return generate(urng);\n        }\n    }\n    \n    /**\n     * Returns a random variate distributed according to the\n     * binomial distribution with parameters specified by @c param.\n     */\n    template<class URNG>\n    IntType operator()(URNG& urng, const param_type& parm) const\n    {\n        return binomial_distribution(parm)(urng);\n    }\n\n    /** Returns the @c t parameter of the distribution. */\n    IntType t() const { return _t; }\n    /** Returns the @c p parameter of the distribution. */\n    RealType p() const { return _p; }\n\n    /** Returns the smallest value that the distribution can produce. */\n    IntType min BOOST_PREVENT_MACRO_SUBSTITUTION() const { return 0; }\n    /** Returns the largest value that the distribution can produce. */\n    IntType max BOOST_PREVENT_MACRO_SUBSTITUTION() const { return _t; }\n\n    /** Returns the parameters of the distribution. */\n    param_type param() const { return param_type(_t, _p); }\n    /** Sets parameters of the distribution. */\n    void param(const param_type& parm)\n    {\n        _t = parm.t();\n        _p = parm.p();\n        init();\n    }\n\n    /**\n     * Effects: Subsequent uses of the distribution do not depend\n     * on values produced by any engine prior to invoking reset.\n     */\n    void reset() { }\n\n#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS\n    /** Writes the parameters of the distribution to a @c std::ostream. */\n    template<class CharT, class Traits>\n    friend std::basic_ostream<CharT,Traits>&\n    operator<<(std::basic_ostream<CharT,Traits>& os,\n               const binomial_distribution& bd)\n    {\n        os << bd.param();\n        return os;\n    }\n    \n    /** Reads the parameters of the distribution from a @c std::istream. */\n    template<class CharT, class Traits>\n    friend std::basic_istream<CharT,Traits>&\n    operator>>(std::basic_istream<CharT,Traits>& is, binomial_distribution& bd)\n    {\n        bd.read(is);\n        return is;\n    }\n#endif\n\n    /** Returns true if the two distributions will produce the same\n        sequence of values, given equal generators. */\n    friend bool operator==(const binomial_distribution& lhs,\n                           const binomial_distribution& rhs)\n    {\n        return lhs._t == rhs._t && lhs._p == rhs._p;\n    }\n    /** Returns true if the two distributions could produce different\n        sequences of values, given equal generators. */\n    friend bool operator!=(const binomial_distribution& lhs,\n                           const binomial_distribution& rhs)\n    {\n        return !(lhs == rhs);\n    }\n\nprivate:\n\n    /// @cond show_private\n\n    template<class CharT, class Traits>\n    void read(std::basic_istream<CharT, Traits>& is) {\n        param_type parm;\n        if(is >> parm) {\n            param(parm);\n        }\n    }\n\n    bool use_inversion() const\n    {\n        // BTRD is safe when np >= 10\n        return m < 11;\n    }\n\n    // computes the correction factor for the Stirling approximation\n    // for log(k!)\n    static RealType fc(IntType k)\n    {\n        if(k < 10) return detail::binomial_table<RealType>::table[k];\n        else {\n            RealType ikp1 = RealType(1) / (k + 1);\n            return (RealType(1)/12\n                 - (RealType(1)/360\n                 - (RealType(1)/1260)*(ikp1*ikp1))*(ikp1*ikp1))*ikp1;\n        }\n    }\n\n    void init()\n    {\n        using std::sqrt;\n        using std::pow;\n\n        RealType p = (0.5 < _p)? (1 - _p) : _p;\n        IntType t = _t;\n        \n        m = static_cast<IntType>((t+1)*p);\n\n        if(use_inversion()) {\n            _u.q_n = pow((1 - p), static_cast<RealType>(t));\n        } else {\n            _u.btrd.r = p/(1-p);\n            _u.btrd.nr = (t+1)*_u.btrd.r;\n            _u.btrd.npq = t*p*(1-p);\n            RealType sqrt_npq = sqrt(_u.btrd.npq);\n            _u.btrd.b = 1.15 + 2.53 * sqrt_npq;\n            _u.btrd.a = -0.0873 + 0.0248*_u.btrd.b + 0.01*p;\n            _u.btrd.c = t*p + 0.5;\n            _u.btrd.alpha = (2.83 + 5.1/_u.btrd.b) * sqrt_npq;\n            _u.btrd.v_r = 0.92 - 4.2/_u.btrd.b;\n            _u.btrd.u_rv_r = 0.86*_u.btrd.v_r;\n        }\n    }\n\n    template<class URNG>\n    result_type generate(URNG& urng) const\n    {\n        using std::floor;\n        using std::abs;\n        using std::log;\n\n        while(true) {\n            RealType u;\n            RealType v = uniform_01<RealType>()(urng);\n            if(v <= _u.btrd.u_rv_r) {\n                u = v/_u.btrd.v_r - 0.43;\n                return static_cast<IntType>(floor(\n                    (2*_u.btrd.a/(0.5 - abs(u)) + _u.btrd.b)*u + _u.btrd.c));\n            }\n\n            if(v >= _u.btrd.v_r) {\n                u = uniform_01<RealType>()(urng) - 0.5;\n            } else {\n                u = v/_u.btrd.v_r - 0.93;\n                u = ((u < 0)? -0.5 : 0.5) - u;\n                v = uniform_01<RealType>()(urng) * _u.btrd.v_r;\n            }\n\n            RealType us = 0.5 - abs(u);\n            IntType k = static_cast<IntType>(floor((2*_u.btrd.a/us + _u.btrd.b)*u + _u.btrd.c));\n            if(k < 0 || k > _t) continue;\n            v = v*_u.btrd.alpha/(_u.btrd.a/(us*us) + _u.btrd.b);\n            RealType km = abs(k - m);\n            if(km <= 15) {\n                RealType f = 1;\n                if(m < k) {\n                    IntType i = m;\n                    do {\n                        ++i;\n                        f = f*(_u.btrd.nr/i - _u.btrd.r);\n                    } while(i != k);\n                } else if(m > k) {\n                    IntType i = k;\n                    do {\n                        ++i;\n                        v = v*(_u.btrd.nr/i - _u.btrd.r);\n                    } while(i != m);\n                }\n                if(v <= f) return k;\n                else continue;\n            } else {\n                // final acceptance/rejection\n                v = log(v);\n                RealType rho =\n                    (km/_u.btrd.npq)*(((km/3. + 0.625)*km + 1./6)/_u.btrd.npq + 0.5);\n                RealType t = -km*km/(2*_u.btrd.npq);\n                if(v < t - rho) return k;\n                if(v > t + rho) continue;\n\n                IntType nm = _t - m + 1;\n                RealType h = (m + 0.5)*log((m + 1)/(_u.btrd.r*nm))\n                           + fc(m) + fc(_t - m);\n\n                IntType nk = _t - k + 1;\n                if(v <= h + (_t+1)*log(static_cast<RealType>(nm)/nk)\n                          + (k + 0.5)*log(nk*_u.btrd.r/(k+1))\n                          - fc(k)\n                          - fc(_t - k))\n                {\n                    return k;\n                } else {\n                    continue;\n                }\n            }\n        }\n    }\n\n    template<class URNG>\n    IntType invert(IntType t, RealType p, URNG& urng) const\n    {\n        RealType q = 1 - p;\n        RealType s = p / q;\n        RealType a = (t + 1) * s;\n        RealType r = _u.q_n;\n        RealType u = uniform_01<RealType>()(urng);\n        IntType x = 0;\n        while(u > r) {\n            u = u - r;\n            ++x;\n            RealType r1 = ((a/x) - s) * r;\n            // If r gets too small then the round-off error\n            // becomes a problem.  At this point, p(i) is\n            // decreasing exponentially, so if we just call\n            // it 0, it's close enough.  Note that the\n            // minimum value of q_n is about 1e-7, so we\n            // may need to be a little careful to make sure that\n            // we don't terminate the first time through the loop\n            // for float.  (Hence the test that r is decreasing)\n            if(r1 < std::numeric_limits<RealType>::epsilon() && r1 < r) {\n                break;\n            }\n            r = r1;\n        }\n        return x;\n    }\n\n    // parameters\n    IntType _t;\n    RealType _p;\n\n    // common data\n    IntType m;\n\n    union {\n        // for btrd\n        struct {\n            RealType r;\n            RealType nr;\n            RealType npq;\n            RealType b;\n            RealType a;\n            RealType c;\n            RealType alpha;\n            RealType v_r;\n            RealType u_rv_r;\n        } btrd;\n        // for inversion\n        RealType q_n;\n    } _u;\n\n    /// @endcond\n};\n\n}\n\n// backwards compatibility\nusing random::binomial_distribution;\n\n}\n\n#include <boost/random/detail/enable_warnings.hpp>\n\n#endif\n", "meta": {"hexsha": "78d1a123a47a6ffddaa4bafb7c429d7441055a2a", "size": 12985, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/random/binomial_distribution.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/random/binomial_distribution.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/random/binomial_distribution.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 29.8505747126, "max_line_length": 96, "alphanum_fraction": 0.5286099345, "num_tokens": 3476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.42686822685720865}}
{"text": "// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef NETKET_ADADELTA_HPP\n#define NETKET_ADADELTA_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <cassert>\n#include <cmath>\n#include <complex>\n#include <iostream>\n#include \"abstract_optimizer.hpp\"\n\nnamespace netket {\n\nclass AdaDelta : public AbstractOptimizer {\n  int npar_;\n\n  double rho_;\n  double epscut_;\n\n  Eigen::VectorXd Eg2_;\n  Eigen::VectorXd Edx2_;\n\n  const Complex I_;\n\n public:\n  // Json constructor\n  explicit AdaDelta(double rho = 0.95, double epscut = 1.0e-7)\n      : rho_(rho), epscut_(epscut), I_(0, 1) {\n    npar_ = -1;\n\n    PrintParameters();\n  }\n\n  // Json constructor\n  explicit AdaDelta(const json &pars) : I_(0, 1) {\n    npar_ = -1;\n\n    from_json(pars);\n    PrintParameters();\n  }\n\n  void PrintParameters() {\n    InfoMessage() << \"Adadelta optimizer initialized with these parameters :\"\n                  << std::endl;\n    InfoMessage() << \"Rho = \" << rho_ << std::endl;\n    InfoMessage() << \"Epscut = \" << epscut_ << std::endl;\n  }\n\n  void Init(const Eigen::VectorXd &pars) override {\n    npar_ = pars.size();\n    Eg2_.setZero(npar_);\n    Edx2_.setZero(npar_);\n  }\n\n  void Init(const Eigen::VectorXcd &pars) override {\n    npar_ = 2 * pars.size();\n    Eg2_.setZero(npar_);\n    Edx2_.setZero(npar_);\n  }\n\n  void Update(const Eigen::VectorXd &grad, Eigen::VectorXd &pars) override {\n    assert(npar_ > 0);\n\n    Eg2_ = rho_ * Eg2_ + (1. - rho_) * grad.cwiseAbs2();\n\n    Eigen::VectorXd Dx(npar_);\n\n    for (int i = 0; i < npar_; i++) {\n      Dx(i) = -std::sqrt(Edx2_(i) + epscut_) * grad(i);\n      Dx(i) /= std::sqrt(Eg2_(i) + epscut_);\n      pars(i) += Dx(i);\n    }\n\n    Edx2_ = rho_ * Edx2_ + (1. - rho_) * Dx.cwiseAbs2();\n  }\n\n  void Update(const Eigen::VectorXcd &grad, Eigen::VectorXd &pars) override {\n    Update(Eigen::VectorXd(grad.real()), pars);\n  }\n\n  void Update(const Eigen::VectorXcd &grad, Eigen::VectorXcd &pars) override {\n    assert(npar_ == 2 * pars.size());\n\n    Eigen::VectorXd Dx(npar_);\n\n    for (int i = 0; i < pars.size(); i++) {\n      Eg2_(2 * i) =\n          rho_ * Eg2_(2 * i) + (1. - rho_) * std::pow(grad(i).real(), 2);\n      Eg2_(2 * i + 1) =\n          rho_ * Eg2_(2 * i + 1) + (1. - rho_) * std::pow(grad(i).imag(), 2);\n\n      Dx(2 * i) = -std::sqrt(Edx2_(2 * i) + epscut_) * grad(i).real();\n      Dx(2 * i + 1) = -std::sqrt(Edx2_(2 * i + 1) + epscut_) * grad(i).imag();\n      Dx(2 * i) /= std::sqrt(Eg2_(2 * i) + epscut_);\n      Dx(2 * i + 1) /= std::sqrt(Eg2_(2 * i + 1) + epscut_);\n\n      pars(i) += Dx(2 * i);\n      pars(i) += I_ * Dx(2 * i + 1);\n\n      Edx2_(2 * i) = rho_ * Edx2_(2 * i) + (1. - rho_) * std::pow(Dx(2 * i), 2);\n      Edx2_(2 * i + 1) =\n          rho_ * Edx2_(2 * i + 1) + (1. - rho_) * std::pow(Dx(2 * i + 1), 2);\n    }\n  }\n\n  void Reset() override {\n    Eg2_ = Eigen::VectorXd::Zero(npar_);\n    Edx2_ = Eigen::VectorXd::Zero(npar_);\n  }\n\n  void from_json(const json &pars) {\n    // DEPRECATED (to remove for v2.0.0)\n    std::string section = \"Optimizer\";\n    if (!FieldExists(pars, section)) {\n      section = \"Learning\";\n    }\n    rho_ = FieldOrDefaultVal(pars[section], \"Rho\", 0.95);\n    epscut_ = FieldOrDefaultVal(pars[section], \"Epscut\", 1.0e-7);\n  }\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "5dc77995d16f07073c0135f1837601ab5cecd9f2", "size": 3808, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Optimizer/ada_delta.hpp", "max_stars_repo_name": "flatironinstitute/netket", "max_stars_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T19:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T01:03:15.000Z", "max_issues_repo_path": "NetKet/Optimizer/ada_delta.hpp", "max_issues_repo_name": "flatironinstitute/netket", "max_issues_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetKet/Optimizer/ada_delta.hpp", "max_forks_repo_name": "flatironinstitute/netket", "max_forks_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-23T01:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T01:04:00.000Z", "avg_line_length": 27.3956834532, "max_line_length": 80, "alphanum_fraction": 0.5963760504, "num_tokens": 1225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342972, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.42674595665236403}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file flatextrapolation.hpp\n    \\brief flat interpolation decorator\n    \\ingroup math\n*/\n\n#ifndef quantext_flat_extrapolation_hpp\n#define quantext_flat_extrapolation_hpp\n\n#include <ql/math/interpolation.hpp>\n#include <ql/math/interpolations/cubicinterpolation.hpp>\n#include <ql/math/interpolations/linearinterpolation.hpp>\n#include <ql/math/interpolations/loginterpolation.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantExt {\nusing namespace QuantLib;\n\n//! Flat extrapolation given a base interpolation\n/*! \\ingroup math\n */\nclass FlatExtrapolation : public Interpolation {\nprivate:\n    class FlatExtrapolationImpl : public Interpolation::Impl {\n\n    public:\n        FlatExtrapolationImpl(const boost::shared_ptr<Interpolation>& i) : i_(i) {}\n        void update() { i_->update(); }\n        Real xMin() const { return i_->xMin(); }\n        Real xMax() const { return i_->xMax(); }\n        std::vector<Real> xValues() const { QL_FAIL(\"not implemented\"); }\n        std::vector<Real> yValues() const { QL_FAIL(\"not implemented\"); }\n        bool isInRange(Real x) const { return i_->isInRange(x); }\n        Real value(Real x) const {\n            Real tmp = std::max(std::min(x, i_->xMax()), i_->xMin());\n            return i_->operator()(tmp);\n        }\n        Real primitive(Real x) const {\n            if (x >= i_->xMin() && x <= i_->xMax()) {\n                return i_->primitive(x);\n            }\n            if (x < i_->xMin()) {\n                return i_->primitive(i_->xMin()) - (i_->xMin() - x);\n            } else {\n                return i_->primitive(i_->xMax()) + (x - i_->xMax());\n            }\n        }\n        Real derivative(Real x) const {\n            if (x > i_->xMin() && x < i_->xMax()) {\n                return i_->derivative(x);\n            } else {\n                // that is the left derivative for xmin and\n                // the right derivative for xmax\n                return 0.0;\n            }\n        }\n        Real secondDerivative(Real x) const {\n            if (x > i_->xMin() && x < i_->xMax()) {\n                return i_->secondDerivative(x);\n            } else {\n                // that is the left derivative for xmin and\n                // the right derivative for xmax\n                return 0.0;\n            }\n        }\n\n    private:\n        const boost::shared_ptr<Interpolation> i_;\n    };\n\npublic:\n    FlatExtrapolation(const boost::shared_ptr<Interpolation>& i) {\n        impl_ = boost::make_shared<FlatExtrapolationImpl>(i);\n        impl_->update();\n    }\n};\n\n//! %Linear-interpolation and flat extrapolation factory and traits\nclass LinearFlat {\npublic:\n    template <class I1, class I2> Interpolation interpolate(const I1& xBegin, const I1& xEnd, const I2& yBegin) const {\n        return FlatExtrapolation(boost::make_shared<LinearInterpolation>(xBegin, xEnd, yBegin));\n    }\n    static const bool global = false;\n    static const Size requiredPoints = 2;\n};\n\n//! %Linear-interpolation and flat extrapolation factory and traits\nclass LogLinearFlat {\npublic:\n    template <class I1, class I2> Interpolation interpolate(const I1& xBegin, const I1& xEnd, const I2& yBegin) const {\n        return FlatExtrapolation(boost::make_shared<LogLinearInterpolation>(xBegin, xEnd, yBegin));\n    }\n    static const bool global = false;\n    static const Size requiredPoints = 2;\n};\n\n//! Hermite interpolation and flat extrapolation factory and traits\nclass HermiteFlat {\npublic:\n     template <class I1, class I2> Interpolation interpolate(const I1& xBegin, const I1& xEnd, const I2& yBegin) const {\n         return FlatExtrapolation(boost::make_shared<Parabolic>(xBegin, xEnd, yBegin));\n     }\n     static const bool global = false;\n     static const Size requiredPoints = 2;\n};\n\n//! Cubic interpolation and flat extrapolation factory and traits\nclass CubicFlat {\npublic:\n    CubicFlat(\n        QuantLib::CubicInterpolation::DerivativeApprox da = QuantLib::CubicInterpolation::Kruger,\n        bool monotonic = false,\n        QuantLib::CubicInterpolation::BoundaryCondition leftCondition = QuantLib::CubicInterpolation::SecondDerivative,\n        QuantLib::Real leftConditionValue = 0.0,\n        QuantLib::CubicInterpolation::BoundaryCondition rightCondition = QuantLib::CubicInterpolation::SecondDerivative,\n        QuantLib::Real rightConditionValue = 0.0)\n        : da_(da), monotonic_(monotonic), leftType_(leftCondition), rightType_(rightCondition),\n          leftValue_(leftConditionValue), rightValue_(rightConditionValue) {}\n\n    template <class I1, class I2> Interpolation interpolate(const I1& xBegin, const I1& xEnd, const I2& yBegin) const {\n        return FlatExtrapolation(boost::make_shared<CubicInterpolation>(\n            xBegin, xEnd, yBegin, da_, monotonic_, leftType_, leftValue_, rightType_, rightValue_));\n    }\n\n    static const bool global = true;\n    static const Size requiredPoints = 2;\n\nprivate:\n    QuantLib::CubicInterpolation::DerivativeApprox da_;\n    bool monotonic_;\n    QuantLib::CubicInterpolation::BoundaryCondition leftType_;\n    QuantLib::CubicInterpolation::BoundaryCondition rightType_;\n    QuantLib::Real leftValue_;\n    QuantLib::Real rightValue_;\n};\n\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "a9d7c47b9dbaed234a375e30f2b63ec0eb6110f2", "size": 5919, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/math/flatextrapolation.hpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/math/flatextrapolation.hpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/math/flatextrapolation.hpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 37.2264150943, "max_line_length": 120, "alphanum_fraction": 0.6686940362, "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.426745956652364}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation>\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//---------------------------------------------------------------------------//\n\n\n#define PROVING_KEY_FILE \"provkey.bin\"\n#define VERIFICATION_KEY_FILE \"verifkey.bin\"\n#define BIG_PROOF_FILE \"big_proof.bin\"\n#define PROOF_FILE \"proof.bin\"\n#define PRIMARY_INPUT_FILE \"primary_input.bin\"\n\n#include <iostream>\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include \"detail/r1cs_examples.hpp\"\n#include \"detail/sha256_component.hpp\"\n\n#include <nil/crypto3/algebra/curves/bls12.hpp>\n#include <nil/crypto3/algebra/fields/bls12/base_field.hpp>\n#include <nil/crypto3/algebra/fields/bls12/scalar_field.hpp>\n#include <nil/crypto3/algebra/fields/arithmetic_params/bls12.hpp>\n#include <nil/crypto3/algebra/curves/params/multiexp/bls12.hpp>\n#include <nil/crypto3/algebra/curves/params/wnaf/bls12.hpp>\n\n#include <nil/crypto3/zk/components/blueprint.hpp>\n#include <nil/crypto3/zk/components/blueprint_variable.hpp>\n\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/marshalling.hpp>\n\n#include <nil/crypto3/zk/snark/algorithms/generate.hpp>\n#include <nil/crypto3/zk/snark/algorithms/verify.hpp>\n#include <nil/crypto3/zk/snark/algorithms/prove.hpp>\n\n#include <nil/crypto3/zk/components/component.hpp>\n\n#include <nil/crypto3/zk/components/blueprint.hpp>\n#include <nil/crypto3/zk/components/blueprint_variable.hpp>\n// #include <nil/crypto3/zk/snark/components/basic_components.hpp>\n\n// #include <nil/crypto3/zk/snark/relations/constraint_satisfaction_problems/r1cs.hpp>\n\nusing namespace nil::crypto3;\nusing namespace nil::crypto3::zk;\nusing namespace nil::crypto3::zk::components;\nusing namespace nil::crypto3::algebra;\n\n#include <iostream>\n#include <string>\n#include \"picosha2.hpp\"\n\nusing namespace std;\n\ntypedef algebra::curves::bls12<381> curve_type;\ntypedef typename curve_type::scalar_field_type field_type;\ntypedef zk::snark::r1cs_gg_ppzksnark<curve_type> scheme_type;\n\nusing std::string;\nusing std::cout;\nusing std::endl;\n\n\n\nusing curve_type = curves::bls12<381>;\nusing field_type = typename curve_type::scalar_field_type;\n\n\n// must be done here, after definition of curve_type and field_type\n#include \"utils.hpp\"\n\n\n\nvoid build_circuit ( blueprint<field_type> &bp, std::vector<uint32_t> &passphrase32 ){\n\n  blueprint_variable<field_type> public_pubkey0;\n  public_pubkey0.allocate( bp );\n\n  blueprint_variable<field_type> public_pubkey1;\n  public_pubkey1.allocate( bp );\n\n  blueprint_variable<field_type> public_pubkey2;\n  public_pubkey2.allocate( bp );\n\n  blueprint_variable<field_type> public_pubkey3;\n  public_pubkey3.allocate( bp );\n\n  blueprint_variable<field_type> secret_pubkey0;\n  secret_pubkey0.allocate( bp );\n\n  blueprint_variable<field_type> secret_pubkey1;\n  secret_pubkey1.allocate( bp );\n\n  blueprint_variable<field_type> secret_pubkey2;\n  secret_pubkey2.allocate( bp );\n\n  blueprint_variable<field_type> secret_pubkey3;\n  secret_pubkey3.allocate( bp );\n\n  blueprint_variable<field_type> secret_hash0;\n  secret_hash0.allocate( bp );\n\n  blueprint_variable<field_type> secret_hash1;\n  secret_hash1.allocate( bp );\n\n  blueprint_variable<field_type> secret_hash2;\n  secret_hash2.allocate( bp );\n\n  blueprint_variable<field_type> secret_hash3;\n  secret_hash3.allocate( bp );\n\n  bp.set_input_sizes(4);\n\n  // This sets up the blueprint variables\n  // so that the first one (out) represents the public\n  // input and the rest is private input\n\n\n  bp.add_r1cs_constraint(r1cs_constraint<field_type>( secret_pubkey0 , 1, public_pubkey0));\n  bp.add_r1cs_constraint(r1cs_constraint<field_type>( secret_pubkey1 , 1, public_pubkey1));\n  bp.add_r1cs_constraint(r1cs_constraint<field_type>( secret_pubkey2 , 1, public_pubkey2));\n  bp.add_r1cs_constraint(r1cs_constraint<field_type>( secret_pubkey3 , 1, public_pubkey3));\n  bp.add_r1cs_constraint(r1cs_constraint<field_type>( passphrase32[0] , 1, secret_hash0));\n  bp.add_r1cs_constraint(r1cs_constraint<field_type>( passphrase32[1] , 1, secret_hash1));\n  bp.add_r1cs_constraint(r1cs_constraint<field_type>( passphrase32[2] , 1, secret_hash2));\n  bp.add_r1cs_constraint(r1cs_constraint<field_type>( passphrase32[3] , 1, secret_hash3));\n}\n\n\n\n\n\nvoid prepare_circuit ( std::string passphrase ){\n\n  using curve_type = curves::bls12<381>;\n  using field_type = typename curve_type::scalar_field_type;\n\n  std::vector<uint32_t> passphrase32(4);\n  uint32s_of_passphrase( passphrase32, passphrase );\n\n  blueprint<field_type> bp;\n  build_circuit( bp, passphrase32 );\n\n  const r1cs_constraint_system<field_type> constraint_system =\n    bp.get_constraint_system();\n  const typename r1cs_gg_ppzksnark<curve_type>::keypair_type keypair =\n    generate<r1cs_gg_ppzksnark<curve_type>>(constraint_system);\n\n  save_proving_key( PROVING_KEY_FILE, keypair.first ) ;\n  save_verification_key( VERIFICATION_KEY_FILE , keypair.second );\n\n}\n\nvoid use_circuit( std::string passphrase, std::string pubkey ){\n\n  std::vector<uint32_t> passphrase32(4);\n  std::vector<uint32_t> pubkey32(4);\n\n  if( pubkey.size() != 64 ){\n    cerr << \"Wrong size for pubkey, should be 64 hexa chars\" << endl ;\n    exit(2) ;\n  }\n\n  uint32s_of_passphrase( passphrase32, passphrase );\n  uint32s_of_pubkey( pubkey32, pubkey );\n\n  // public\n  snark::r1cs_variable_assignment<field_type> primary_assignment;\n  for( int i = 0; i < 4; i++){\n    primary_assignment.push_back( pubkey32 [i] );\n  }\n  typename scheme_type::primary_input_type primary_input\n    ( primary_assignment.begin(), primary_assignment.begin() + 4 );\n\n  // private\n  snark::r1cs_variable_assignment<field_type> auxiliary_assignment;\n  for( int i = 0; i < 4; i++){\n    auxiliary_assignment.push_back( pubkey32 [i] );\n  }\n  for( int i = 0; i < 4; i++){\n    auxiliary_assignment.push_back( passphrase32 [i] );\n  }\n\n  typename scheme_type::auxiliary_input_type auxiliary_input\n    ( auxiliary_assignment.begin(), auxiliary_assignment.begin() + 8 );\n\n\n  typename scheme_type::proving_key_type pk =\n    load_proving_key( PROVING_KEY_FILE );\n\n\n  const typename r1cs_gg_ppzksnark<curve_type>::proof_type proof =\n    prove<r1cs_gg_ppzksnark<curve_type>>( pk,  primary_input, auxiliary_input );\n\n  const typename r1cs_gg_ppzksnark<curve_type>::verification_key_type vk =\n    load_verification_key( VERIFICATION_KEY_FILE );\n\n  bool verified =\n    verify<r1cs_gg_ppzksnark<curve_type>>(vk, primary_input, proof);\n\n  if( !verified ){\n    cerr << \"Invalid proof\" << endl;\n    exit(2) ;\n  }\n\n  save_primary_input( PRIMARY_INPUT_FILE, primary_input );\n  save_big_proof( BIG_PROOF_FILE, proof, primary_input, vk );\n  save_proof( PROOF_FILE, proof );\n\n}\n\nvoid print_usage(std::ostream &cout, std::string command )\n{\n    cout << command << \" SUBCOMMAND [ARGUMENTS]\" << endl ;\n    cout << \"Available subcommands:\" << endl ;\n    cout << \"  * prepare PASSPHRASE : output circuit for PASSPHRASE to 'provkey.bin' and 'verifkey.bin'\" << endl ;\n    cout << \"  * prove PASSPHRASE PUBKEY : generate 'proof.bin', 'verifkey.bin', 'variables.bin' and 'big_proof.bin'\" << endl ;\n    cout << \"Arguments:\" << endl ;\n    cout << \"  PASSPHRASE: an ASCII string that you have to memorize\" << endl ;\n    cout << \"  PUBKEY: the Hexadecimal representation of your pubkey (without 0x)\" << endl ;\n\n}\n\nint main(int argc, char *argv[]) {\n\n  if( argc == 1 ){\n    print_usage ( cout, argv[0] ) ;\n    return 0 ;\n  }\n\n  std::string subcommand = argv[1] ;\n  if( subcommand == \"prepare\" ){\n    cerr << \"prepare\" << endl ;\n    if( argc != 3 ){\n      cerr << \"Bad number of arguments:\" << endl ;\n      print_usage ( cerr, argv[0] ) ;\n      return 1;\n    }\n\n    prepare_circuit( argv[2] );\n    return 0 ;\n  } else\n  if( subcommand == \"prove\" ){\n    cerr << \"prove\" << endl ;\n    if( argc != 4 ){\n      cerr << \"Bad number of arguments:\" << endl ;\n      print_usage ( cerr, argv[0] ) ;\n      return 1;\n    }\n    use_circuit( argv[2], argv[3] );\n    return 0 ;\n  } else {\n    cerr << \"Unknown subcommand: \" << subcommand << endl;\n    return 2 ;\n  }\n\n}\n\n\n/*\n*/\n", "meta": {"hexsha": "e955b1fc1f65c18f36f965e4e5928c4b6f480f0e", "size": 8662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "proposal-18/submission-18/devex-18-zk-contest/03_pincode/cpp/main.cpp", "max_stars_repo_name": "Tonium-io/devex", "max_stars_repo_head_hexsha": "e031f74b0d08958a3c6e56d9c2b8c386acc96f8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-09T14:40:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-09T14:40:45.000Z", "max_issues_repo_path": "proposal-18/submission-18/devex-18-zk-contest/03_pincode/cpp/main.cpp", "max_issues_repo_name": "Tonium-io/devex", "max_issues_repo_head_hexsha": "e031f74b0d08958a3c6e56d9c2b8c386acc96f8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-09T04:33:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T04:35:09.000Z", "max_forks_repo_path": "proposal-18/submission-18/devex-18-zk-contest/03_pincode/cpp/main.cpp", "max_forks_repo_name": "Tonium-io/devex", "max_forks_repo_head_hexsha": "e031f74b0d08958a3c6e56d9c2b8c386acc96f8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2021-05-05T20:58:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-17T08:18:07.000Z", "avg_line_length": 31.4981818182, "max_line_length": 127, "alphanum_fraction": 0.7216578157, "num_tokens": 2300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8670357529306639, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.42674471083821974}}
{"text": "#ifndef GRAPHS_UTILS_HPP\n#define GRAPHS_UTILS_HPP\n\n#include <utility>\n#include <vector>\n#include <fstream>\n#include <filesystem>\n#include <numeric>\n\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n\n#include <osmium/osm/node_ref.hpp>\n#include <osmium/osm/way.hpp>\n\nnamespace graphs {\nusing Distance = double;\nusing Angle = long double;\nusing Location = std::pair<Angle, Angle>;\nusing Locations = std::vector<Location>;\n\ntemplate<typename T>\nbool serialize(const std::string& filename, T&& data) {\n    std::ofstream binary { filename, std::ios::out | std::ios::binary | std::ios::app };\n    boost::archive::binary_oarchive archive { binary, boost::archive::no_header };\n    archive << data;\n    binary.close();\n    return true;\n}\n\ntemplate<typename T>\nbool deserialize(const std::string& filename, T&& data) {\n    if (!std::filesystem::exists(filename)) { return false; }\n    std::ifstream binary { filename, std::ios::binary };\n    boost::archive::binary_iarchive archive { binary, boost::archive::no_header };\n    archive >> data;\n    binary.close();\n    return true;\n}\n\n/**\n * Factory method for Position.\n */\ninline auto make_pos(const osmium::NodeRef& node) -> Location {\n    return { node.lat(), node.lon() };\n}\n\n/**\n * Determines the great-circle distance between two points given their longitudes and latitudes.\n *\n * @param x, y OSM nodes with corresponding coordinates.\n * @return Distance between nodes.\n */\ninline auto haversine(const Location& x, const Location& y) -> Distance {\n    const auto[lat_1, lon_1] = x;\n    const auto[lat_2, lon_2] = y;\n    constexpr long double R = 6'371'000;\n\n    // Convert to radians\n    const auto phi1 = lat_1 * M_PI / 180;\n    const auto phi2 = lat_2 * M_PI / 180;\n    const auto d_phi = (lat_2 - lat_1) * M_PI / 180;\n    const auto d_lambda = (lon_2 - lon_1) * M_PI / 180;\n\n    // Square of half the chord length between the objects\n    const auto a = std::pow(std::sin(d_phi / 2), 2) +\n                   std::cos(phi1) * std::cos(phi2) * std::pow(std::sin(d_lambda / 2), 2);\n    // Angular distance in radians\n    const auto c = 2 * std::atan2(std::sqrt(a), std::sqrt(1 - a));\n    return R * c;\n}\n\n/**\n * Determines the geographical center of a building consisting of ambient nodes.\n *\n * @param nodes List of nodes of an OSM way.\n * @return Geocenter described by a pair of latitude and longitude respectively.\n */\ninline auto barycenter(const osmium::WayNodeList& nodes) -> Location {\n    const auto lat = std::accumulate(nodes.cbegin(), nodes.cend(), static_cast<long double>(0),\n                                     [](auto lhs, const auto& node) { return lhs + node.lat(); });\n    const auto lon = std::accumulate(nodes.cbegin(), nodes.cend(), static_cast<long double>(0),\n                                     [](auto lhs, const auto& node) { return lhs + node.lon(); });\n    const auto num = nodes.size();\n\n    return { lat / num, lon / num };\n}\n\ninline auto barycenter(const Locations& locations) -> Location {\n    const auto\n        lat = std::accumulate(locations.cbegin(), locations.cend(), static_cast<long double>(0),\n                              [](auto lhs, const auto& node) { return lhs + node.first; });\n    const auto\n        lon = std::accumulate(locations.cbegin(), locations.cend(), static_cast<long double>(0),\n                              [](auto lhs, const auto& node) { return lhs + node.second; });\n    const auto num = locations.size();\n\n    return { lat / num, lon / num };\n}\n} // namespace graph\n\n\n#endif // GRAPHS_UTILS_HPP\n", "meta": {"hexsha": "7c9726041a098db5b1c61958a217c2032001caf3", "size": 3547, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/utils.hpp", "max_stars_repo_name": "team-cringe/graphs", "max_stars_repo_head_hexsha": "f84e2a4c3cae3b5c2493926c84536b9f81b1ed22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/utils.hpp", "max_issues_repo_name": "team-cringe/graphs", "max_issues_repo_head_hexsha": "f84e2a4c3cae3b5c2493926c84536b9f81b1ed22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/utils.hpp", "max_forks_repo_name": "team-cringe/graphs", "max_forks_repo_head_hexsha": "f84e2a4c3cae3b5c2493926c84536b9f81b1ed22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1057692308, "max_line_length": 98, "alphanum_fraction": 0.6433605864, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4267025919560983}}
{"text": "// chapter 3\n\n#include <iostream>\n#include <boost/type_traits/is_reference.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/type_traits/is_pointer.hpp>\n#include <boost/type_traits/is_float.hpp>\n#include <boost/type_traits/alignment_of.hpp>\n#include <boost/type_traits/remove_reference.hpp>\n#include <boost/type_traits/remove_pointer.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/minus.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/vector_c.hpp>\n#include <boost/mpl/transform.hpp>\n#include <boost/mpl/equal.hpp>\nusing namespace boost::mpl::placeholders;\n#include <iterator>\n#include <utility>\n#include <list>\n#include <vector>\n#include <string>\n#include <assert.h>\n\nnamespace mpl = boost::mpl;\n\ntypedef mpl::vector_c<int, 1, 0, 0, 0> mass;\ntypedef mpl::vector_c<int, 0, 1, 0, 0> length;\ntypedef mpl::vector_c<int, 0, 0, 1, 0> time;\ntypedef mpl::vector_c<int, 0, 1, -2, 0> accel;\ntypedef mpl::vector_c<int, 1, 1, -2, 0> force;\ntypedef mpl::vector_c<int, 0, 0, 0, 0> scalar;\n\n\ntemplate <class T, class Dimension>\nstruct Quantity\n{\n\tQuantity(T x) : m_value(x) {}\n\ttemplate <class OtherDimension>\n\tQuantity( Quantity<T, OtherDimension> &rhs) : m_value(rhs.value()) \n\t{\n\t\tBOOST_STATIC_ASSERT((\n\t\t\tmpl::equal< Dimension, OtherDimension >::type::value\n\t\t\t));\t\n\t}\n\n\tT m_value;\n\tT value() const { return m_value; }\n\n\ttemplate<class OtherDimension>\n\tQuantity<T, Dimension>& operator=(Quantity<T, OtherDimension> &rhs)\n\t{\n\t\tBOOST_STATIC_ASSERT((\n\t\t\tmpl::equal< Dimension, OtherDimension >::type::value\n\t\t\t));\n\n\t\tif (this != &rhs)\n\t\t{\n\t\t\tm_value = rhs.value();\n\t\t}\n\t\treturn *this;\n\t}\n\n\tQuantity<T, Dimension> operator+(const Quantity<T, Dimension> &rhs)\n\t{\n\t\treturn Quantity<T, Dimension>(value() + rhs.value());\n\t}\n\tQuantity<T, Dimension> operator-(const Quantity<T, Dimension> &rhs)\n\t{\n\t\treturn Quantity<T, Dimension>(value() - rhs.value());\n\t}\n\n\tstruct minus_f\n\t{\n\t\ttemplate <class T1, class T2>\n\t\tstruct apply : mpl::minus<T1,T2> {};\n\t};\n\n\ttemplate <class OtherDimension>\n\tQuantity<\n\t\tT, \n\t\ttypename mpl::transform<Dimension, OtherDimension, mpl::plus<_1,_2> >::type \n\t> \n\t\toperator*(const Quantity<T, OtherDimension> &rhs)\n\t{\n\t\ttypedef typename mpl::transform<Dimension, OtherDimension, mpl::plus<_1,_2> >::type dim;\n\t\treturn Quantity<T, dim>(value() * rhs.value());\n\t}\n\n\ttemplate <class OtherDimension>\n\tQuantity<T, typename mpl::transform<Dimension, OtherDimension, minus_f>::type > \n\t\toperator/(const Quantity<T, OtherDimension> &rhs)\n\t{\n\t\ttypedef typename mpl::transform<Dimension, OtherDimension, minus_f>::type dim;\n\t\treturn Quantity<T, dim>(value() / rhs.value());\n\t}\n\n};\n\nvoid main()\n{\n\tQuantity<float, mass> m(3.f);\n\tQuantity<float, mass> m2(4.f);\n\tQuantity<float, length> l(5.f);\n\tQuantity<float, accel> a(5.f);\n\tQuantity<float, mass> m3 = m + m2;\n\tQuantity<float, mass> m4 = m - m2;\n\tQuantity<float, force> f = m * a;\n\n\tm4 = f/a;\n\n\n\n\tBOOST_STATIC_ASSERT((\n\t\tmpl::plus<\n\t\tmpl::int_<2>\n\t\t,mpl::int_<3>\n\t\t,mpl::int_<4>\n\t\t>::type::value == 9\n\t\t));\n\n}\n", "meta": {"hexsha": "5b49bc02cbbd3ef4252799d23fd4cfb808636b27", "size": 3024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ex3/ex3/main.cpp", "max_stars_repo_name": "jjuiddong/TemplateMetaProgramming", "max_stars_repo_head_hexsha": "ccfa4b21205c8cd3da1906f64cdbeb200902812a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-31T05:50:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-31T05:50:22.000Z", "max_issues_repo_path": "ex3/ex3/main.cpp", "max_issues_repo_name": "jjuiddong/TemplateMetaProgramming", "max_issues_repo_head_hexsha": "ccfa4b21205c8cd3da1906f64cdbeb200902812a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ex3/ex3/main.cpp", "max_forks_repo_name": "jjuiddong/TemplateMetaProgramming", "max_forks_repo_head_hexsha": "ccfa4b21205c8cd3da1906f64cdbeb200902812a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-31T05:50:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-31T05:50:41.000Z", "avg_line_length": 24.3870967742, "max_line_length": 90, "alphanum_fraction": 0.6908068783, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185318, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4267025919560983}}
{"text": "/**\n * @file  CableTensionFactor.cpp\n * @brief Cable tension factor: relates cable tension, two mounting points, and\n * resultant forces\n * @author Frank Dellaert\n * @author Gerry Chen\n */\n\n#include \"CableTensionFactor.h\"\n\n#include <gtdynamics/utils/DynamicsSymbol.h>\n\n#include <gtsam/base/Matrix.h>\n#include <gtsam/base/Vector.h>\n#include <gtsam/geometry/Pose3.h>\n#include <gtsam/nonlinear/NonlinearFactor.h>\n\n#include <boost/optional.hpp>\n#include <iostream>\n#include <string>\n\nusing namespace gtsam;\n\nnamespace gtdynamics {\n\n/******************************************************************************/\nVector6 CableTensionFactor::computeWrench(\n    double t, const Pose3 &wTx, boost::optional<Matrix &> H_t,\n    boost::optional<Matrix &> H_wTx) const {\n  // Jacobians: cable direction\n  Matrix33 dir_H_wPb;\n  Matrix36 wPb_H_wTx;\n  // Jacobians: force to wrench conversion\n  Matrix31 wf_H_t;\n  Matrix33 wf_H_dir;\n  Matrix33 xf_H_wf;\n  Matrix33 xf_H_wRx;\n  Matrix63 H_xf;\n  Matrix33 xm_H_xf;  // = H_xf.topRows<3>(); TODO(gerry): pointer?\n\n  // cable direction\n  Point3 wPb = wTx.transformFrom(xPb_, H_wTx ? &wPb_H_wTx : 0);\n  Vector3 dir = normalize(wPb - wPa_, H_wTx ? &dir_H_wPb : 0);\n  // force->wrench\n  Vector3 wf = -t * dir;\n  if (H_t) wf_H_t = -dir;\n  if (H_wTx) wf_H_dir = -t * I_3x3;\n  Vector3 xf = wTx.rotation().unrotate(wf,  // force in the EE frame\n                                       H_wTx ? &xf_H_wRx : 0,\n                                       (H_t || H_wTx) ? &xf_H_wf : 0);\n  Vector3 xm = cross(xPb_, xf,     // moment in the EE frame\n                     boost::none,  //\n                     (H_t || H_wTx) ? &xm_H_xf : 0);\n\n  Vector6 F = (Vector6() << xm, xf).finished();\n  if (H_t || H_wTx) H_xf << xm_H_xf, I_3x3;\n  if (H_t) *H_t = H_xf * xf_H_wf * wf_H_t;\n  if (H_wTx) {\n    *(H_wTx) = H_xf * xf_H_wf * wf_H_dir * dir_H_wPb * wPb_H_wTx;\n    H_wTx->leftCols<3>() += H_xf * xf_H_wRx;\n  }\n  return F;\n}\n\n/******************************************************************************/\nVector6 CableTensionFactor::computeWrenchUsingAdjoint(\n    double t, const Pose3 &wTx, boost::optional<Matrix &> H_t,\n    boost::optional<Matrix &> H_wTx) const {\n  // Jacobians: cable direction\n  Matrix33 dir_H_wPb;\n  Matrix36 wPb_H_wTx;\n  // Jacobians: force to wrench conversion\n  Matrix61 wF_H_t;\n  Matrix63 wF_H_dir;\n\n  // cable direction\n  Point3 wPb = wTx.transformFrom(xPb_, H_wTx ? &wPb_H_wTx : 0);\n  Vector3 dir = normalize(wPb - wPa_, H_wTx ? &dir_H_wPb : 0);\n  // force->wrench\n  Pose3 bTx = Pose3(wTx.rotation().inverse(), xPb_).inverse();\n  Vector6 wF = (Vector6() << 0, 0, 0, -t * dir).finished();\n  if (H_t) wF_H_t = (Matrix61() << 0, 0, 0, -dir).finished();\n  if (H_wTx) wF_H_dir = (Matrix63() << Z_3x3, -t * I_3x3).finished();\n  Vector6 F = bTx.AdjointMap().transpose() * wF;\n  // TODO(gerry): find jacobian of adjoint map\n  return F;\n}\n\n}  // namespace gtdynamics\n", "meta": {"hexsha": "2ea2d1ef9b9dd9f1ebf212aa6972bd92cb04e68a", "size": 2898, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtdynamics/cablerobot/factors/CableTensionFactor.cpp", "max_stars_repo_name": "danbarla/GTDynamics", "max_stars_repo_head_hexsha": "0448b359aff9e0e784832666e4048ee01c8b082d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-08-09T23:43:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-11T16:16:37.000Z", "max_issues_repo_path": "gtdynamics/cablerobot/factors/CableTensionFactor.cpp", "max_issues_repo_name": "danbarla/GTDynamics", "max_issues_repo_head_hexsha": "0448b359aff9e0e784832666e4048ee01c8b082d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 104.0, "max_issues_repo_issues_event_min_datetime": "2021-08-03T14:15:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T08:18:09.000Z", "max_forks_repo_path": "gtdynamics/cablerobot/factors/CableTensionFactor.cpp", "max_forks_repo_name": "danbarla/GTDynamics", "max_forks_repo_head_hexsha": "0448b359aff9e0e784832666e4048ee01c8b082d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-08-02T17:42:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-24T00:43:17.000Z", "avg_line_length": 32.2, "max_line_length": 80, "alphanum_fraction": 0.6066252588, "num_tokens": 953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.42670258471834704}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      Battin, R.H. An Introduction to the Mathematics and Methods of Astrodynamics,\n *          AIAA Education Series, 1999.\n *      Izzo, D. lambert_problem.h, keptoolbox.\n *\n *    Notes\n *      This code is an implementation of the method developed by Dario Izzo from ESA/ACT and\n *      publicly available at: http://keptoolbox.sourceforge.net/.\n *      After verification and validation, it was proven that this algorithm is faster and more\n *      robust than the implemented Lancaster & Blanchard and Gooding method. Notably, this method\n *      does not suffer from the near-pi singularity (pi-transfers are by nature singular).\n *\n */\n\n#include \"Tudat/Astrodynamics/MissionSegments/lambertTargeterIzzo.h\"\n#include \"Tudat/Astrodynamics/MissionSegments/lambertRoutines.h\"\n\n#include <Eigen/Geometry>\n\nnamespace tudat\n{\nnamespace mission_segments\n{\n\n//! Execute Lambert targeting solver.\nvoid LambertTargeterIzzo::execute( )\n{\n    // Call Izzo's Lambert targeting routine.\n    solveLambertProblemIzzo( cartesianPositionAtDeparture, cartesianPositionAtArrival,\n                             timeOfFlight, gravitationalParameter, cartesianVelocityAtDeparture,\n                             cartesianVelocityAtArrival, isRetrograde_, convergenceTolerance_,\n                             maximumNumberOfIterations_ );\n}\n\n//! Get radial velocity at departure.\ndouble LambertTargeterIzzo::getRadialVelocityAtDeparture( )\n{\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtDeparture\n            = cartesianPositionAtDeparture.normalized( );\n\n    // Compute radial velocity at departure.\n    return cartesianVelocityAtDeparture.dot( radialUnitVectorAtDeparture );\n}\n\n//! Get radial velocity at arrival.\ndouble LambertTargeterIzzo::getRadialVelocityAtArrival( )\n{\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtArrival = cartesianPositionAtArrival.normalized( );\n\n    // Compute radial velocity at arrival.\n    return cartesianVelocityAtArrival.dot( radialUnitVectorAtArrival );\n}\n\n//! Get transverse velocity at departure.\ndouble LambertTargeterIzzo::getTransverseVelocityAtDeparture( )\n{\n    // Compute angular momemtum vector.\n    const Eigen::Vector3d angularMomentumVector =\n            cartesianPositionAtDeparture.cross( cartesianVelocityAtDeparture );\n\n    // Compute normalized angular momentum vector.\n    const Eigen::Vector3d angularMomentumUnitVector = angularMomentumVector.normalized( );\n\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtDeparture\n            = cartesianPositionAtDeparture.normalized( );\n\n    // Compute tangential unit vector.\n    Eigen::Vector3d tangentialUnitVectorAtDeparture =\n                angularMomentumUnitVector.cross( radialUnitVectorAtDeparture );\n\n    // Compute tangential velocity at departure.\n    return cartesianVelocityAtDeparture.dot( tangentialUnitVectorAtDeparture );\n}\n\n//! Get transverse velocity at arrival.\ndouble LambertTargeterIzzo::getTransverseVelocityAtArrival( )\n{\n    // Compute angular momemtum vector.\n    const Eigen::Vector3d angularMomentumVector =\n            cartesianPositionAtArrival.cross( cartesianVelocityAtArrival );\n\n    // Compute normalized angular momentum vector.\n    const Eigen::Vector3d angularMomentumUnitVector = angularMomentumVector.normalized( );\n\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtArrival = cartesianPositionAtArrival.normalized( );\n\n    // Compute tangential unit vector.\n    Eigen::Vector3d tangentialUnitVectorAtArrival\n            = angularMomentumUnitVector.cross( radialUnitVectorAtArrival );\n\n    // Compute tangential velocity at departure.\n    return cartesianVelocityAtArrival.dot( tangentialUnitVectorAtArrival );\n}\n\n//! Get semi-major axis.\ndouble LambertTargeterIzzo::getSemiMajorAxis( )\n{\n    // Compute specific orbital energy: eps = v^2/ - mu/r.\n    const double specificOrbitalEnergy = cartesianVelocityAtDeparture.squaredNorm( ) / 2.0\n            - gravitationalParameter / cartesianPositionAtDeparture.norm( );\n\n    // Compute semi-major axis: a = -mu / 2*eps.\n    return -gravitationalParameter / ( 2.0 * specificOrbitalEnergy );\n}\n\n} // namespace mission_segments\n} // namespace tudat\n", "meta": {"hexsha": "590a3879efe060d4644680caf4661e7a17897a91", "size": 4791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/MissionSegments/lambertTargeterIzzo.cpp", "max_stars_repo_name": "ViktorJordanov/tudat", "max_stars_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/MissionSegments/lambertTargeterIzzo.cpp", "max_issues_repo_name": "ViktorJordanov/tudat", "max_issues_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/MissionSegments/lambertTargeterIzzo.cpp", "max_forks_repo_name": "ViktorJordanov/tudat", "max_forks_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.328, "max_line_length": 98, "alphanum_fraction": 0.7372156126, "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569014, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.42665344907297054}}
{"text": "// This file is part of snark, a generic and flexible library for robotics research\n// Copyright (c) 2011 The University of Sydney\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n// 1. Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the University of Sydney nor the\n//    names of its contributors may be used to endorse or promote products\n//    derived from this software without specific prior written permission.\n//\n// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE\n// GRANTED BY THIS LICENSE.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT\n// HOLDERS AND CONTRIBUTORS \\\"AS IS\\\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n// IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n/// @author vsevolod vlaskine\n\n#include <algorithm>\n#include <cmath>\n#include <deque>\n#include <functional>\n#include <iostream>\n#include <vector>\n#include <boost/scoped_ptr.hpp>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <comma/application/command_line_options.h>\n#include <comma/base/types.h>\n#include <comma/csv/stream.h>\n#include <comma/string/string.h>\n#include \"../../visiting/traits.h\"\n#include \"../rotation_matrix.h\"\n\nvoid usage( bool verbose )\n{\n    std::cerr << std::endl;\n    std::cerr << \"simple wrapper for eigen library operations\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"usage: cat sample.csv | math-eigen <operation> [<options>]\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"<operation>: eigen, rotation\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"operations\" << std::endl;\n    std::cerr << \"    eigen (default): calculate eigen vector and eigen values on a sample\" << std::endl;\n    std::cerr << \"        fields\" << std::endl;\n    std::cerr << \"            block: block number; output eigen vectors and eigen values for each\" << std::endl;\n    std::cerr << \"                   contiguous block of samples with the same block id\" << std::endl;\n    std::cerr << \"            data: sample data\" << std::endl;\n    std::cerr << \"            default: data\" << std::endl;\n    std::cerr << \"        output\" << std::endl;\n    std::cerr << \"            default output fields\" << std::endl;\n    std::cerr << \"                one eigen vector per line; if block field present: vector,value,block\" << std::endl;\n    std::cerr << \"                                           if no block field present: vector,value\" << std::endl;\n    std::cerr << \"            binary format: 32-bit unsigned integer for block, doubles for other output fields\" << std::endl;\n    std::cerr << \"        options\" << std::endl;\n    std::cerr << \"            --normalize,-n: output normalized eigen values\" << std::endl;\n    std::cerr << \"            --rsort,--descending: output eigen vectors and values in descending order of eigen values\" << std::endl;\n    std::cerr << \"            --sort,-s,--ascending: output eigen vectors and values in ascending order of eigen values\" << std::endl;\n    std::cerr << \"            --single-line-output,--single-line,--single: output eigen vectors and eigen values all as one line:\" << std::endl;\n    std::cerr << \"                                                         vector[0],vector[1],...,value[0],value[1],...,block\" << std::endl;\n    std::cerr << \"            --size: a hint of number of elements in the data vector, ignored, if data indices\" << std::endl;\n    std::cerr << \"                    specified, e.g. data[0],data[1],data[2]\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"    fit plane: fit plane to dataset, output its mean and normal\" << std::endl;\n    std::cerr << \"        fields\" << std::endl;\n    std::cerr << \"            block: block number; output eigen vectors and eigen values for each\" << std::endl;\n    std::cerr << \"                   contiguous block of samples with the same block id\" << std::endl;\n    std::cerr << \"            data: sample data\" << std::endl;\n    std::cerr << \"            default: data\" << std::endl;\n    std::cerr << \"        output\" << std::endl;\n    std::cerr << \"            output fields: mean,normal[,block]\" << std::endl;\n    std::cerr << \"            binary format: 32-bit unsigned integer for block, doubles for other output fields\" << std::endl;\n    std::cerr << \"        options\" << std::endl;\n    std::cerr << \"            --size: a hint of number of elements in the data vector, ignored, if data indices\" << std::endl;\n    std::cerr << \"                    specified, e.g. data[0],data[1],data[2]\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"    rotation: convert rotation from representation to another, append the result to stdin data, output to stdout\" << std::endl;\n    std::cerr << \"        options\" << std::endl;\n    std::cerr << \"            --from=<what>: input representation; default euler\" << std::endl;\n    std::cerr << \"            --to=<what>: output representation; default euler\" << std::endl;\n    std::cerr << \"                <what>\" << std::endl;\n    std::cerr << \"                    euler;rpy;roll,pitch,yaw: euler angles, i.e. roll, pitch, yaw\" << std::endl;\n    std::cerr << \"                    axis-angle,angle-axis: angle-axis\" << std::endl;\n    std::cerr << \"                    axis-angle-scaled: rotation axis with the norm equal to rotation angle\" << std::endl;\n    std::cerr << \"                    quaternion: quaternion\" << std::endl;\n    std::cerr << \"                    rotation-matrix,matrix: rotation matrix\" << std::endl;\n    std::cerr << \"            --input-fields: print input fields to stdout and exit\" << std::endl;\n    std::cerr << \"            --output-fields: print output fields to stdout and exit\" << std::endl;\n    std::cerr << \"            --output-format: print binary output format to stdout and exit\" << std::endl;\n    std::cerr << std::endl;\n    std::cerr << \"options\" << std::endl;\n    std::cerr << \"    --help,-h: show this help; --help --verbose: more help\" << std::endl;\n    if( verbose ) { std::cerr << std::endl << \"csv options\" << std::endl << comma::csv::options::usage() << std::endl; }\n    std::cerr << std::endl;\n    std::cerr << \"examples\" << std::endl;\n    std::cerr << \"    eigen\" << std::endl;\n    std::cerr << \"        cat sample.csv | math-eigen\" << std::endl;\n    std::cerr << \"        cat sample.csv | math-eigen --fields=block,data\" << std::endl;\n    std::cerr << \"        cat sample.csv | math-eigen --fields=block,,,data --size=4\" << std::endl;\n    std::cerr << \"        cat sample.csv | math-eigen --fields=block,,data[0],,data[1],,data[2],,data[3]\" << std::endl;\n    std::cerr << \"        cat sample.bin | math-eigen --fields=block,data --binary=ui,6d\" << std::endl;\n    std::cerr << std::endl;\n    exit( 0 );\n}\n\nstatic boost::optional< unsigned int > size;\n\nnamespace snark { namespace eigen {\n\nstruct input_t\n{\n    std::vector< double > data;\n    comma::uint32 block;\n    \n    input_t() : data( *size ), block( 0 ) {}\n};\n\nstruct output_t\n{\n    std::vector< double > vector;\n    double value;\n    comma::uint32 block;\n    \n    output_t() : vector( *size ), value( 0 ), block( 0 ) {}\n};\n\nstruct single_line_output_t\n{\n    std::vector< double > vectors; // quick and dirty\n    std::vector< double > values;\n    comma::uint32 block;\n    \n    single_line_output_t(): vectors( *size * *size ), values( *size ), block( 0 ) {}\n};\n\nstruct fit_plane_output_t\n{\n    std::vector< double > mean;\n    std::vector< double > normal;\n    comma::uint32 block;\n    \n    fit_plane_output_t(): mean( *size ), normal( *size ), block( 0 ) {}\n};\n\n} } // namespace snark { namespace eigen {\n\nnamespace comma { namespace visiting {\n\ntemplate <> struct traits< snark::eigen::input_t >\n{\n    template < typename K, typename V > static void visit( const K&, snark::eigen::input_t& p, V& v )\n    {\n        v.apply( \"data\", p.data );\n        v.apply( \"block\", p.block );\n    }\n\n    template < typename K, typename V > static void visit( const K&, const snark::eigen::input_t& p, V& v )\n    {\n        v.apply( \"data\", p.data );\n        v.apply( \"block\", p.block );\n    }\n};\n\ntemplate <> struct traits< snark::eigen::output_t >\n{\n    template < typename K, typename V > static void visit( const K&, const snark::eigen::output_t& p, V& v )\n    {\n        v.apply( \"vector\", p.vector );\n        v.apply( \"value\", p.value );\n        v.apply( \"block\", p.block );\n    }\n};\n\ntemplate <> struct traits< snark::eigen::single_line_output_t >\n{\n    template < typename K, typename V > static void visit( const K&, const snark::eigen::single_line_output_t& p, V& v )\n    {\n        v.apply( \"vectors\", p.vectors );\n        v.apply( \"values\", p.values );\n        v.apply( \"block\", p.block );\n    }\n};\n\ntemplate <> struct traits< snark::eigen::fit_plane_output_t >\n{\n    template < typename K, typename V > static void visit( const K&, const snark::eigen::fit_plane_output_t& p, V& v )\n    {\n        v.apply( \"mean\", p.mean );\n        v.apply( \"normal\", p.normal );\n        v.apply( \"block\", p.block );\n    }\n};\n\n} } // namespace comma { namespace visiting {\n\nnamespace rotation {\n\ntemplate < typename T > struct traits;\n\ntemplate <> struct traits< snark::roll_pitch_yaw >\n{\n    static snark::roll_pitch_yaw zero() { return snark::roll_pitch_yaw(); }\n    static snark::roll_pitch_yaw get( const snark::rotation_matrix& m ) { return m.roll_pitch_yaw(); }\n};\n\ntemplate < typename T > struct traits< Eigen::AngleAxis< T > >\n{\n    static Eigen::AngleAxis< T > zero() { Eigen::AngleAxis< T > a( 0, Eigen::Matrix< T, 3, 1 >::Zero() ); return a; }\n    static Eigen::AngleAxis< T > get( const snark::rotation_matrix& m ) { return Eigen::AngleAxis< T >( m.rotation() ); }\n};\n\ntemplate <> struct traits< Eigen::Vector3d >\n{\n    static Eigen::Vector3d zero() { return Eigen::Vector3d::Zero(); }\n    static Eigen::Vector3d get( const snark::rotation_matrix& m ) { const Eigen::AngleAxis< double > a( m.rotation() ); return a.axis() * a.angle(); }\n};\n\ntemplate < typename T > struct traits< Eigen::Quaternion< T > >\n{\n    static Eigen::Quaternion< T > zero() { Eigen::Quaternion< T > q( 0, 0, 0, 0 ); return q; }\n    static Eigen::Quaternion< T > get( const snark::rotation_matrix& m ) { return m.quaternion(); }\n};\n\ntemplate <> struct traits< Eigen::Matrix< double, 3, 3 > >\n{\n    static Eigen::Matrix< double, 3, 3 > zero() { return Eigen::Matrix< double, 3, 3 >::Zero(); }\n    static Eigen::Matrix< double, 3, 3 > get( const snark::rotation_matrix& m ) { return Eigen::Matrix< double, 3, 3 >( m.rotation() ); }\n};\n    \ntemplate < typename From, typename To >\nstatic int run( const comma::command_line_options& options )\n{\n    if( options.exists( \"--input-fields\" ) ) { std::cout << comma::join( comma::csv::names< From >( false ), ',' ) << std::endl; return 0; }\n    if( options.exists( \"--output-fields\" ) ) { std::cout << comma::join( comma::csv::names< To >( false ), ',' ) << std::endl; return 0; }\n    if( options.exists( \"--output-format\" ) ) { std::cout << comma::csv::format::value< To >() << std::endl; return 0; }\n    comma::csv::options csv( options );\n    csv.full_xpath = true;\n    comma::csv::input_stream< From > istream( std::cin, csv, rotation::traits< From >::zero() );\n    comma::csv::options output_csv;\n    if( csv.binary() ) { output_csv.format( comma::csv::format::value< To >() ); }\n    output_csv.full_xpath = true;\n    comma::csv::output_stream< To > ostream( std::cout, output_csv );\n    while( istream.ready() || std::cin.good() )\n    {\n        const From* p = istream.read();\n        if( !p ) { break; }\n        comma::csv::append( istream, ostream, rotation::traits< To >::get( snark::rotation_matrix( *p ) ) );\n        if( csv.flush ) { ostream.flush(); }\n    }\n    return 0;\n}\n    \ntemplate < typename From >\nstatic int run( const comma::command_line_options& options, const std::string& to )\n{\n    if( to == \"euler\" || to == \"rpy\" || to == \"roll,pitch,yaw\" ) { return rotation::run< From, snark::roll_pitch_yaw >( options ); }\n    if( to == \"angle-axis\" || to == \"axis-angle\" ) { return rotation::run< From, Eigen::AngleAxis< double > >( options ); }\n    if( to == \"axis-angle-scaled\" ) { return rotation::run< From, Eigen::Vector3d >( options ); }\n    if( to == \"quaternion\" ) { return rotation::run< From, Eigen::Quaternion< double > >( options ); }\n    if( to == \"rotation-matrix\" || to == \"matrix\" ) { return rotation::run< From, Eigen::Matrix< double, 3, 3 > >( options ); }\n    std::cerr << \"math-eigen: rotation: expected valid value for --to; got --to=\\\"\" << to << \"\\\"\" << std::endl;\n    return 1;\n}\n\n} // namespace rotation {\n\nint main( int ac, char** av )\n{\n    try\n    {\n        comma::command_line_options options( ac, av, usage );\n        const std::vector< std::string >& unnamed = options.unnamed( \"--flush,--normalize,-n,--sort,-s,--ascending,--rsort,--descending,--single-line-output,--single-line,--single,--verbose,-v\" );\n        std::string operation = unnamed.empty() ? std::string( \"eigen\" ) : unnamed[0];\n        if( operation == \"eigen\" || operation == \"fit-plane\" )\n        {\n            comma::csv::options csv( options );\n            size = options.optional< unsigned int >( \"--size\" );\n            if( csv.fields.empty() ) { csv.fields = \"data\"; }\n            std::string first;\n            if( !size )\n            {\n                const std::vector< std::string >& fields = comma::split( csv.fields, ',' );\n                if( csv.has_field( \"data\" ) )\n                {\n                    unsigned int count;\n                    if( csv.binary() )\n                    {\n                        count = csv.format().count();\n                    }\n                    else\n                    {\n                        while( std::cin.good() && first.empty() ) { std::getline( std::cin, first ); }\n                        count = comma::split( first, csv.delimiter ).size(); // quick and dirty, wasteful\n                    }\n                    size = count - fields.size() + 1;\n                }\n                else\n                {\n                    unsigned int max = 0;\n                    for( unsigned int i = 0; i < fields.size(); ++i )\n                    {\n                        if( fields[i].substr( 0, 5 ) == \"data[\" && *fields[i].rbegin() == ']' ) { unsigned int k = boost::lexical_cast< unsigned int >( fields[i].substr( 5, fields[i].size() - 6 ) ) + 1; if( k > max ) { max = k; } }\n                    }\n                    if( max == 0 ) { std::cerr << \"math-eigen: please specify valid data fields\" << std::endl; return 1; }\n                    size = max;\n                }\n            }\n            \n            bool has_block = csv.has_field( \"block\" );\n            std::deque< snark::eigen::input_t > buffer;\n            if( !first.empty() ) { buffer.push_back( comma::csv::ascii< snark::eigen::input_t >( csv ).get( first ) ); }\n            comma::csv::input_stream< snark::eigen::input_t > istream( std::cin, csv );\n            std::vector< unsigned int > indices( *size ); // quick and dirty\n            for( unsigned int i = 0; i < indices.size(); indices[i] = i, ++i );\n            if( operation == \"eigen\" )\n            {\n                bool single_line_output = options.exists( \"--single-line-output,--single-line,--single\" );\n                bool normalize = options.exists( \"--normalize,-n\" );\n                bool sort = options.exists( \"--sort,--ascending,-s,--descending,--rsort\" );\n                bool ascending = sort && !options.exists( \"--descending,--rsort\" );\n                comma::csv::options output_csv;\n                output_csv.fields = single_line_output ? has_block ? \"vectors,values,block\" : \"vectors,values\"\n                                                       : has_block ? \"vector,value,block\" : \"vector,value\";\n                if( csv.binary() )\n                {\n                    std::string s = boost::lexical_cast< std::string >( single_line_output ? *size * ( *size + 1 ) : ( *size + 1 ) );\n                    output_csv.format( has_block ? s + \"d,ui\" : s + \"d\" );\n                }\n                boost::scoped_ptr< comma::csv::output_stream< snark::eigen::output_t > > ostream;\n                boost::scoped_ptr< comma::csv::output_stream< snark::eigen::single_line_output_t > > single_line_ostream;\n                if( single_line_output ) { single_line_ostream.reset( new comma::csv::output_stream< snark::eigen::single_line_output_t >( std::cout, output_csv ) ); }\n                else { ostream.reset( new comma::csv::output_stream< snark::eigen::output_t >( std::cout, output_csv ) ); }\n                while( true )\n                {\n                    const snark::eigen::input_t* p = istream.read();\n                    if( !p || ( !buffer.empty() && buffer.front().block != p->block ) )\n                    {\n                        typedef Eigen::Matrix< double, -1, -1, Eigen::RowMajor > matrix_t;\n                        matrix_t sample( buffer.size(), *size );\n                        for( std::size_t i = 0; i < buffer.size(); ++i ) { ::memcpy( &sample( i, 0 ), &buffer[i].data[0], *size * sizeof( double ) ); } // dodgy?\n                        //if( buffer.size() == 1 ) { std::cerr << \"math-eigen: on block \" << buffer.front().block << \": expected block with at least two entries, got only one\" << std::endl; return 1; }\n                        matrix_t covariance = sample.adjoint() * sample;\n                        covariance = covariance / ( sample.rows() - 1 );                    \n                        Eigen::SelfAdjointEigenSolver< matrix_t > solver( covariance );\n                        Eigen::VectorXd values = solver.eigenvalues();\n                        if( normalize ) { values = values / solver.eigenvalues().sum(); }\n                        const matrix_t& vectors = solver.eigenvectors().transpose();\n                        if( sort )\n                        {\n                            std::map< double, unsigned int > m; // quick and dirty, watch performance\n                            for( unsigned int i = 0; i < indices.size(); m[ ascending ? values[i] : -values[i] ] = i, ++i );\n                            unsigned int i = 0;\n                            for( std::map< double, unsigned int >::const_iterator it = m.begin(); it != m.end(); indices[i] = it->second, ++it, ++i );\n                        }\n                        if( single_line_output )\n                        {\n                            snark::eigen::single_line_output_t output;\n                            output.block = buffer.front().block;\n                            if( sort )\n                            {\n                                for( unsigned int i = 0; i < indices.size(); ++i )\n                                {\n                                    output.values[i] = values[ indices[i] ];\n                                    ::memcpy( &output.vectors[ i * *size ], &vectors( indices[i], 0 ), *size * sizeof( double ) ); // quick and dirty\n                                }\n                            }\n                            else\n                            {\n                                ::memcpy( &output.vectors[0], &vectors( 0, 0 ), *size * *size * sizeof( double ) ); // quick and dirty\n                                ::memcpy( &output.values[0], &values[0], *size * sizeof( double ) );\n                            }\n                            single_line_ostream->write( output );\n                            if( csv.flush ) { single_line_ostream->flush(); }\n                        }\n                        else\n                        {\n                            for( std::size_t i = 0; i < *size; ++i )\n                            {\n                                snark::eigen::output_t output;\n                                output.block = buffer.front().block;\n                                ::memcpy( &output.vector[0], &vectors( indices[i], 0 ), *size * sizeof( double ) );\n                                output.value = values[ indices[i] ];\n                                ostream->write( output );\n                                if( csv.flush ) { ostream->flush(); }\n                            }\n                        }\n                        buffer.clear();\n                    }\n                    if( !p ) { break; }\n                    buffer.push_back( *p );\n                }\n                return 0;\n            }\n            if( operation == \"fit-plane\" ) // see http://math.stackexchange.com/questions/99299/best-fitting-plane-given-a-set-of-points\n            {\n                comma::csv::options output_csv;\n                output_csv.fields = has_block ? \"mean,normal,block\" : \"mean,normal\";\n                if( csv.binary() )\n                {\n                    std::string s = boost::lexical_cast< std::string >( *size );\n                    output_csv.format( has_block ? s + \"d,\" + s + \"d,ui\" : s + \"d,\" + s + \"d\" );\n                }\n                comma::csv::output_stream< snark::eigen::fit_plane_output_t > ostream( std::cout, output_csv );\n                while( true )\n                {\n                    const snark::eigen::input_t* p = istream.read();\n                    if( !p || ( !buffer.empty() && buffer.front().block != p->block ) )\n                    {\n                        typedef Eigen::Matrix< double, -1, -1 > matrix_t;\n                        matrix_t sample( *size, buffer.size() );\n                        for( std::size_t i = 0; i < buffer.size(); ++i ) // todo: watch performance, cache misses; use tbb::parallel_for?\n                        {\n                            for( std::size_t j = 0; j < *size; ++j ) { sample.row( j )[i] = buffer[i].data[j]; }\n                        }\n                        Eigen::VectorXd mean( *size );\n                        for( std::size_t i = 0; i < *size; ++i )\n                        {\n                            mean( i ) = sample.row( i ).mean();\n                            sample.row( i ).array() -= mean( i );\n                        }\n                        Eigen::VectorXd normal = sample.jacobiSvd( Eigen::ComputeThinU | Eigen::ComputeThinV ).matrixU().rightCols< 1 >();\n                        snark::eigen::fit_plane_output_t output;\n                        ::memcpy( &output.mean[0], &mean[0], *size * sizeof( double ) ); // quick and dirty\n                        ::memcpy( &output.normal[0], &normal[0], *size * sizeof( double ) ); // quick and dirty\n                        output.block = buffer.front().block;\n                        ostream.write( output );\n                        buffer.clear();\n                    }\n                    if( !p ) { break; }\n                    buffer.push_back( *p );\n                }\n                return 0;\n            }\n                \n        }\n        if( operation == \"rotation\" )\n        {\n            std::string from = options.value< std::string >( \"--from\", \"euler\" );\n            std::string to = options.value< std::string >( \"--to\", \"euler\" );\n            if( from == \"euler\" || from == \"rpy\" || from == \"roll,pitch,yaw\" ) { return rotation::run< snark::roll_pitch_yaw >( options, to ); }\n            if( from == \"angle-axis\" || from == \"axis-angle\" ) { return rotation::run< Eigen::AngleAxis< double > >( options, to ); }\n            if( from == \"axis-angle-scaled\" ) { return rotation::run< Eigen::Vector3d >( options, to ); }\n            if( from == \"quaternion\" ) { return rotation::run< Eigen::Quaternion< double > >( options, to ); }\n            if( from == \"rotation-matrix\" || from == \"matrix\" ) { return rotation::run< Eigen::Matrix< double, 3, 3 > >( options, to ); }\n            std::cerr << \"math-eigen: rotation: expected valid value for --from; got --from=\\\"\" << from << \"\\\"\" << std::endl;\n            return 1;\n        }\n        std::cerr << \"math-eigen: expected operation, got \\\"\" << operation << \"\\\"\" << std::endl;\n    }\n    catch( std::exception& ex ) { std::cerr << \"math-eigen: \" << ex.what() << std::endl; }\n    catch( ... ) { std::cerr << \"math-eigen: unknown exception\" << std::endl; }\n    return 1;\n}\n", "meta": {"hexsha": "bce27ff39fcafe5272847247ba08d12bc864f243", "size": 24978, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/applications/math-eigen.cpp", "max_stars_repo_name": "nightfox0909/snark", "max_stars_repo_head_hexsha": "6a6ddc79af9086f13ba0c1287a555c2740fe4e70", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2015-01-14T14:38:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T09:56:03.000Z", "max_issues_repo_path": "math/applications/math-eigen.cpp", "max_issues_repo_name": "nightfox0909/snark", "max_issues_repo_head_hexsha": "6a6ddc79af9086f13ba0c1287a555c2740fe4e70", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2015-01-21T00:57:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-22T04:22:35.000Z", "max_forks_repo_path": "math/applications/math-eigen.cpp", "max_forks_repo_name": "nightfox0909/snark", "max_forks_repo_head_hexsha": "6a6ddc79af9086f13ba0c1287a555c2740fe4e70", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:17:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T17:13:35.000Z", "avg_line_length": 53.3717948718, "max_line_length": 231, "alphanum_fraction": 0.5269837457, "num_tokens": 6089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4265288285365704}}
{"text": "/*\n *  Authors: Lana Mineh and John Scott\n *  Copyright 2021 Phasecraft Ltd. and John Scott\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n */\n \n/**\n * \\file test-utils.hpp\n * \\brief Utilities for the test function\n *\n */\n\n#include <armadillo>\n#include <qsl/concepts.hpp>\n\n/// Gets the bit in the nth position of val\nunsigned getBit(unsigned val, unsigned n);\n\n/// Set the nth bit of val to b\nunsigned setBit(unsigned val, unsigned n, unsigned b);\n\n/**\n * \\brief Construct an armadillo matrix to apply an arbitrary gate\n */\ntemplate<std::floating_point Fp>\narma::SpMat<std::complex<Fp>>\nmakeMatrix(const arma::Mat<std::complex<Fp>> & gate, unsigned nqubits,\n\t   const std::vector<unsigned> & indices)\n{\n    // Check that the gate size matches the length of the indices\n    if ((1ULL << indices.size()) != gate.n_rows) {\n\tthrow std::logic_error(\"Length of indices vector does not \"\n\t\t\t       \"match the size of the gate in call \"\n\t\t\t       \"to makeMatrix()\");\n    }\n\n    const std::size_t dim{ 1ULL << nqubits };\n    arma::SpMat<std::complex<Fp>> mat(dim,dim);    \n\t\n    // Write columns of mat. The columns of the matrix\n    // correspond to the images of the basis states under\n    // the action of the unitary matrix. \n    for (std::size_t col = 0; col < dim; col++) {\n\n\t// Get column bitstring and find the value of the ctrl and targ bits.\n\t// The values of the bits of col in the ctrl and targ positions\n\t// fix which column of the small matrix is used in populating\n\t// values of the big matrix at column col.\n\t//\n\t// Generalised for standard vector of qubit positions. \n\tstd::vector<unsigned> vals;\n\tfor (std::size_t k = 0; k < indices.size(); k++) {\n\t    vals.push_back(getBit(col, indices[k]));\n\t}\n\t\n\t// Write rows of mat. For each row index, \n\tfor (std::size_t n = 0; n < gate.n_rows; n++) {\n\n\t    // Make the row index. The rows that are non-zero in a\n\t    // particular column are the ones whose bits agree with\n\t    // the bits in the col, apart from at the ctrl and targ\n\t    // positions. There, they take every possible ctrl and\n\t    // targ value.\n\t    std::size_t row = col;\n\t    for (std::size_t k = 0; k < indices.size(); k++) {\n\t\trow = setBit(row, indices[k], getBit(n,k));\n\t    }\n\n\t    // Make the column index for the small matrix\n\t    std::size_t m = 0;\n\t    for (std::size_t k = 0; k < vals.size(); k++) {\n\t\tm = setBit(m, k, vals[k]);\n\t    }\n\n\t    mat(row,col) = gate(n,m);\n\t}\n    }\n    return mat;\n}\n\n/**\n * \\brief Convert a standard vector state to an armadillo vector\n */\ntemplate<std::floating_point Fp>\narma::Col<std::complex<Fp>> toArmaState(const std::vector<qsl::complex<Fp>> & res)\n{\n    arma::Col<std::complex<Fp>> qubit_v(res.size());\n    for (std::size_t i = 0; i < res.size(); i++) {\n\tqubit_v(i) = std::complex<Fp>{res[i].real, res[i].imag};\n    }\n    return qubit_v;\n}\n\n/**\n * \\brief Convert a Simulator state to an armadillo vector\n */\ntemplate<qsl::Simulator Sim>\narma::Col<std::complex<typename Sim::Fp_type>> toArmaState(const Sim & sim)\n{\n    using Fp = Sim::Fp_type;\n    // Read qubit state into armadillo to check the state hasn't changed\n    std::vector<qsl::complex<Fp>> res = sim.getState();\n    return toArmaState<Fp>(res);\n}\n\n/**\n * \\brief Make the projector onto a particular outcome of the target qubit\n *\n */\ntemplate<std::floating_point Fp>\narma::SpMat<std::complex<Fp>>\nprojector(unsigned num_qubits, unsigned targ, unsigned outcome)\n{\n    // Calculate the projector for the outcome, which is\n    // the observable that has eigenvalue 0 for |~outcome) and eigenvalue\n    // 1 for |outcome). The expectation value of this observable in a\n    // state is the probability of getting 1 on measurement.\n    arma::Mat<std::complex<Fp>> projector(2,2,arma::fill::zeros);\n    if (outcome == 0) {\n\tprojector(0,0) = 1;\n    } else if (outcome == 1) {\n\tprojector(1,1) = 1;\n    } else {\n\tthrow std::out_of_range(\"outcome must be 0 or 1 in projector() function\");\n    }\n    arma::SpMat<std::complex<Fp>> M = makeMatrix(projector, num_qubits, {targ});\n    return M;\n}\n\n/**\n * \\brief Calculate the probability of measuring a projector outcome\n *\n * Uses the formula prob = (v|P|v), where v is the state and P is \n * the projector\n */\ntemplate<std::floating_point Fp>\nFp probability(const arma::SpMat<std::complex<Fp>> & P,\n\t       const arma::Col<std::complex<Fp>> & v)\n{\n    // Calculate the probability of the projector outcome\n    Fp prob = arma::cdot(v, P*v).real();\n    return prob;\n}\n\n/**\n * \\brief Collapse a state v using a projector P\n *\n * The output is the state Pv/|Pv| (i.e. the normalised projected state)\n *\n */\ntemplate<std::floating_point Fp>\narma::Col<std::complex<Fp>>\napplyProjector(const arma::SpMat<std::complex<Fp>> & P,\n\t       const arma::Col<std::complex<Fp>> & v)\n{\n    arma::Col<std::complex<Fp>> state = (P * v)/arma::norm(P * v);\n    return state;\n}\n", "meta": {"hexsha": "aba6365b3928511f96f1ca9056a23bc0ddf37f95", "size": 5342, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gtest/test-utils.hpp", "max_stars_repo_name": "lanamineh/qsl", "max_stars_repo_head_hexsha": "7e339d2345297709ef817d78ae3a52a33b1c8614", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gtest/test-utils.hpp", "max_issues_repo_name": "lanamineh/qsl", "max_issues_repo_head_hexsha": "7e339d2345297709ef817d78ae3a52a33b1c8614", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gtest/test-utils.hpp", "max_forks_repo_name": "lanamineh/qsl", "max_forks_repo_head_hexsha": "7e339d2345297709ef817d78ae3a52a33b1c8614", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2397660819, "max_line_length": 82, "alphanum_fraction": 0.6591164358, "num_tokens": 1463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.658417487156366, "lm_q1q2_score": 0.4265216748484004}}
{"text": "// Copyright 2020 LMNT, Inc. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// ==============================================================================\n\n#include <Eigen/Dense>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <ctime>\n#include <cuda.h>\n#include <cuda_runtime_api.h>\n#include <iostream>\n#include <string>\n#include <unsupported/Eigen/CXX11/Tensor>\n#include <vector>\n\n#include \"device_ptr.h\"\n#include \"haste.h\"\n\nusing haste::v0::lstm::BackwardPass;\nusing haste::v0::lstm::ForwardPass;\nusing std::string;\n\nusing Tensor1 = Eigen::Tensor<float, 1>;\nusing Tensor2 = Eigen::Tensor<float, 2>;\nusing Tensor3 = Eigen::Tensor<float, 3>;\n\nconstexpr int BATCH_SIZE = 64;\nconstexpr int SEQUENCE_LEN = 1000;\nconstexpr int HIDDEN_DIMS = 512;\nconstexpr int INPUT_DIMS = 512;\n\nstatic cublasHandle_t g_blas_handle;\n\nclass ScopeTimer {\n  public:\n    ScopeTimer(const string& msg) : msg_(msg) {\n      cudaEventCreate(&start_);\n      cudaEventCreate(&stop_);\n      cudaDeviceSynchronize();\n      cudaEventRecord(start_);\n    }\n\n    ~ScopeTimer() {\n      float elapsed_ms;\n      cudaEventRecord(stop_);\n      cudaEventSynchronize(stop_);\n      cudaEventElapsedTime(&elapsed_ms, start_, stop_);\n      printf(\"%s %.1fms\\n\", msg_.c_str(), elapsed_ms);\n      cudaEventDestroy(start_);\n      cudaEventDestroy(stop_);\n    }\n\n  private:\n    string msg_;\n    cudaEvent_t start_, stop_;\n};\n\nvoid LstmInference(const Tensor2& W, const Tensor2& R, const Tensor1& b, const Tensor3& x) {\n  const int time_steps = x.dimension(2);\n  const int batch_size = x.dimension(1);\n  const int input_size = x.dimension(0);\n  const int hidden_size = R.dimension(1);\n\n  // Copy weights over to GPU.\n  device_ptr<Tensor2> W_dev(W);\n  device_ptr<Tensor2> R_dev(R);\n  device_ptr<Tensor1> b_dev(b);\n  device_ptr<Tensor3> x_dev(x);\n\n  device_ptr<Tensor2> h_dev((time_steps + 1) * batch_size * hidden_size);\n  device_ptr<Tensor2> c_dev((time_steps + 1) * batch_size * hidden_size);\n  device_ptr<Tensor3> v_dev(time_steps * batch_size * hidden_size * 4);\n  device_ptr<Tensor2> tmp_Rh_dev(batch_size * hidden_size * 4);\n\n  h_dev.zero();\n  c_dev.zero();\n\n  ScopeTimer t(\"Inference:\");\n\n  ForwardPass<float> forward(\n      false,  // training\n      batch_size,\n      input_size,\n      hidden_size,\n      g_blas_handle);\n\n  forward.Run(\n      time_steps,\n      W_dev.data,\n      R_dev.data,\n      b_dev.data,\n      x_dev.data,\n      h_dev.data,\n      c_dev.data,\n      v_dev.data,\n      tmp_Rh_dev.data,\n      0.0f,      // zoneout prob\n      nullptr);  // zoneout mask\n}\n\nvoid LstmTrain(const Tensor2& W, const Tensor2& R, const Tensor1& b, const Tensor3& x,\n               const Tensor3& dh, const Tensor3& dc) {\n  const int time_steps = x.dimension(2);\n  const int batch_size = x.dimension(1);\n  const int input_size = x.dimension(0);\n  const int hidden_size = R.dimension(1);\n\n  // Copy weights over to GPU.\n  device_ptr<Tensor2> W_dev(W);\n  device_ptr<Tensor2> R_dev(R);\n  device_ptr<Tensor1> b_dev(b);\n  device_ptr<Tensor3> x_dev(x);\n\n  // This is nearly the same as the inference code except we have an extra dimension\n  // for h and c. We'll store those outputs of the cell for all time steps and use\n  // them during the backward pass below.\n  device_ptr<Tensor3> h_dev((time_steps + 1) * batch_size * hidden_size);\n  device_ptr<Tensor3> c_dev((time_steps + 1) * batch_size * hidden_size);\n  device_ptr<Tensor3> v_dev(batch_size * hidden_size * 4 * time_steps);\n  device_ptr<Tensor2> tmp_Rh_dev(batch_size * hidden_size * 4);\n\n  h_dev.zero();\n  c_dev.zero();\n\n  {\n    ScopeTimer t(\"Train forward:\");\n    ForwardPass<float> forward(\n        true,  // training\n        batch_size,\n        input_size,\n        hidden_size,\n        g_blas_handle);\n\n    forward.Run(\n        time_steps,\n        W_dev.data,\n        R_dev.data,\n        b_dev.data,\n        x_dev.data,\n        h_dev.data,\n        c_dev.data,\n        v_dev.data,\n        tmp_Rh_dev.data,\n        0.0f,      // zoneout prob\n        nullptr);  // zoneout mask\n  }\n\n  Eigen::array<int, 3> transpose_x({ 1, 2, 0 });\n  Tensor3 x_t = x.shuffle(transpose_x);\n\n  Eigen::array<int, 2> transpose({ 1, 0 });\n  Tensor2 W_t = W.shuffle(transpose);\n  Tensor2 R_t = R.shuffle(transpose);\n\n  device_ptr<Tensor3> x_t_dev(x_t);\n  device_ptr<Tensor2> W_t_dev(W_t);\n  device_ptr<Tensor2> R_t_dev(R_t);\n\n  // These gradients should actually come \"from above\" but we're just allocating\n  // a bunch of uninitialized memory and passing it in.\n  device_ptr<Tensor3> dh_new_dev(dh);\n  device_ptr<Tensor3> dc_new_dev(dc);\n\n  device_ptr<Tensor3> dx_dev(time_steps * batch_size * input_size);\n  device_ptr<Tensor2> dW_dev(input_size * hidden_size * 4);\n  device_ptr<Tensor2> dR_dev(hidden_size * hidden_size * 4);\n  device_ptr<Tensor2> db_dev(hidden_size * 4);\n  device_ptr<Tensor2> dh_dev(batch_size * hidden_size);\n  device_ptr<Tensor2> dc_dev(batch_size * hidden_size);\n\n  dW_dev.zero();\n  dR_dev.zero();\n  db_dev.zero();\n  dh_dev.zero();\n  dc_dev.zero();\n\n  {\n    ScopeTimer t(\"Train backward:\");\n    BackwardPass<float> backward(\n        batch_size,\n        input_size,\n        hidden_size,\n        g_blas_handle);\n\n    backward.Run(\n        time_steps,\n        W_t_dev.data,\n        R_t_dev.data,\n        b_dev.data,\n        x_t_dev.data,\n        h_dev.data,\n        c_dev.data,\n        dh_new_dev.data,\n        dc_new_dev.data,\n        dx_dev.data,\n        dW_dev.data,\n        dR_dev.data,\n        db_dev.data,\n        dh_dev.data,\n        dc_dev.data,\n        v_dev.data,\n        nullptr);\n  }\n}\n\nvoid LstmTrainIterative(const Tensor2& W, const Tensor2& R, const Tensor1& b, const Tensor3& x,\n                        const Tensor3& dh, const Tensor3& dc) {\n  const int time_steps = x.dimension(2);\n  const int batch_size = x.dimension(1);\n  const int input_size = x.dimension(0);\n  const int hidden_size = R.dimension(1);\n\n  // Copy weights over to GPU.\n  device_ptr<Tensor2> W_dev(W);\n  device_ptr<Tensor2> R_dev(R);\n  device_ptr<Tensor1> b_dev(b);\n  device_ptr<Tensor3> x_dev(x);\n\n  device_ptr<Tensor3> h_dev((time_steps + 1) * batch_size * hidden_size);\n  device_ptr<Tensor3> c_dev((time_steps + 1) * batch_size * hidden_size);\n  device_ptr<Tensor3> v_dev(time_steps * batch_size * hidden_size * 4);\n  device_ptr<Tensor2> tmp_Rh_dev(batch_size * hidden_size * 4);\n\n  h_dev.zero();\n  c_dev.zero();\n\n  {\n    ScopeTimer t(\"Train forward (iterative):\");\n    ForwardPass<float> forward(\n        true,  // training\n        batch_size,\n        input_size,\n        hidden_size,\n        g_blas_handle);\n\n    const int NC = batch_size * input_size;\n    const int NH = batch_size * hidden_size;\n    for (int t = 0; t < time_steps; ++t) {\n      forward.Iterate(\n          0,\n          W_dev.data,\n          R_dev.data,\n          b_dev.data,\n          x_dev.data + t * NC,\n          h_dev.data + t * NH,\n          c_dev.data + t * NH,\n          h_dev.data + (t + 1) * NH,\n          c_dev.data + (t + 1) * NH,\n          v_dev.data + t * NH * 4,\n          tmp_Rh_dev.data,\n          0.0f,      // zoneout prob\n          nullptr);  // zoneout mask\n    }\n  }\n\n  Eigen::array<int, 3> transpose_x({ 1, 2, 0 });\n  Tensor3 x_t = x.shuffle(transpose_x);\n\n  Eigen::array<int, 2> transpose({ 1, 0 });\n  Tensor2 W_t = W.shuffle(transpose);\n  Tensor2 R_t = R.shuffle(transpose);\n\n  device_ptr<Tensor3> x_t_dev(x_t);\n  device_ptr<Tensor2> W_t_dev(W_t);\n  device_ptr<Tensor2> R_t_dev(R_t);\n\n  // These gradients should actually come \"from above\" but we're just allocating\n  // a bunch of uninitialized memory and passing it in.\n  device_ptr<Tensor3> dh_new_dev(dh);\n  device_ptr<Tensor3> dc_new_dev(dc);\n\n  device_ptr<Tensor3> dx_dev(time_steps * batch_size * input_size);\n  device_ptr<Tensor2> dW_dev(input_size * hidden_size * 4);\n  device_ptr<Tensor2> dR_dev(hidden_size * hidden_size * 4);\n  device_ptr<Tensor2> db_dev(hidden_size * 4);\n  device_ptr<Tensor2> dh_dev(batch_size * hidden_size);\n  device_ptr<Tensor2> dc_dev(batch_size * hidden_size);\n\n  dW_dev.zero();\n  dR_dev.zero();\n  db_dev.zero();\n  dh_dev.zero();\n  dc_dev.zero();\n\n  {\n    ScopeTimer t(\"Train backward (iterative):\");\n    BackwardPass<float> backward(\n        batch_size,\n        input_size,\n        hidden_size,\n        g_blas_handle);\n\n    const int NC = batch_size * input_size;\n    const int NH = batch_size * hidden_size;\n    for (int t = time_steps - 1; t >= 0; --t) {\n      backward.Iterate(\n          0,\n          W_t_dev.data,\n          R_t_dev.data,\n          b_dev.data,\n          x_t_dev.data + t * NC,\n          h_dev.data + t * NH,\n          c_dev.data + t * NH,\n          c_dev.data + (t + 1) * NH,\n          dh_new_dev.data + t * NH,\n          dc_new_dev.data + t * NH,\n          dx_dev.data + t * NC,\n          dW_dev.data,\n          dR_dev.data,\n          db_dev.data,\n          dh_dev.data,\n          dc_dev.data,\n          v_dev.data + t * NH * 4,\n          nullptr);\n    }\n  }\n}\n\nint main() {\n  srand(time(0));\n\n  cublasCreate(&g_blas_handle);\n\n  // Weights.\n  // W: input weight matrix\n  // R: recurrent weight matrix\n  // b: bias\n  Tensor2 W(HIDDEN_DIMS * 4, INPUT_DIMS);\n  Tensor2 R(HIDDEN_DIMS * 4, HIDDEN_DIMS);\n  Tensor1 b(HIDDEN_DIMS * 4);\n\n  // Input.\n  Tensor3 x(INPUT_DIMS, BATCH_SIZE, SEQUENCE_LEN);\n\n  // Gradients from upstream layers.\n  Tensor3 dh(HIDDEN_DIMS, BATCH_SIZE, SEQUENCE_LEN + 1);\n  Tensor3 dc(HIDDEN_DIMS, BATCH_SIZE, SEQUENCE_LEN + 1);\n\n  W.setRandom();\n  R.setRandom();\n  b.setRandom();\n  x.setRandom();\n  dh.setRandom();\n  dc.setRandom();\n\n  LstmInference(W, R, b, x);\n  LstmTrain(W, R, b, x, dh, dc);\n  LstmTrainIterative(W, R, b, x, dh, dc);\n\n  cublasDestroy(g_blas_handle);\n\n  return 0;\n}\n", "meta": {"hexsha": "1ccf64abdd800122a2c56c09e373a570f595b0de", "size": 10164, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/lstm.cc", "max_stars_repo_name": "nammingi/haste", "max_stars_repo_head_hexsha": "459608cfdb4de4d28d2213df8e71f005be8d0f35", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 291.0, "max_stars_repo_stars_event_min_datetime": "2020-01-29T19:46:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T22:41:27.000Z", "max_issues_repo_path": "examples/lstm.cc", "max_issues_repo_name": "nammingi/haste", "max_issues_repo_head_hexsha": "459608cfdb4de4d28d2213df8e71f005be8d0f35", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2020-02-24T22:25:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T20:08:43.000Z", "max_forks_repo_path": "examples/lstm.cc", "max_forks_repo_name": "nammingi/haste", "max_forks_repo_head_hexsha": "459608cfdb4de4d28d2213df8e71f005be8d0f35", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2020-02-07T02:51:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T08:44:15.000Z", "avg_line_length": 27.6948228883, "max_line_length": 95, "alphanum_fraction": 0.6385281385, "num_tokens": 2834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.42649132227270425}}
{"text": "\n#include <functional>\n#include <cmath>\n\n#include <boost/math/tools/roots.hpp>\n\n#include \"PROPOSAL/Constants.h\"\n#include \"PROPOSAL/decay/LeptonicDecayChannel.h\"\n#include \"PROPOSAL/math/RandomGenerator.h\"\n#include \"PROPOSAL/particle/Particle.h\"\n\n\nusing namespace PROPOSAL;\n\n/******************************************************************************\n*                         LeptonicDecayChannelApprox                         *\n******************************************************************************/\n\n\nconst std::string LeptonicDecayChannelApprox::name_ = \"LeptonicDecayChannelApprox\";\n\n// ------------------------------------------------------------------------- //\nLeptonicDecayChannelApprox::LeptonicDecayChannelApprox(const ParticleDef& lepton,\n                                           const ParticleDef& neutrino,\n                                           const ParticleDef& anti_neutrino)\n    : DecayChannel()\n    , massive_lepton_(lepton)\n    , neutrino_(neutrino)\n    , anti_neutrino_(anti_neutrino)\n{\n}\n\n// ------------------------------------------------------------------------- //\nLeptonicDecayChannelApprox::~LeptonicDecayChannelApprox() {}\n\n// ------------------------------------------------------------------------- //\nLeptonicDecayChannelApprox::LeptonicDecayChannelApprox(const LeptonicDecayChannelApprox& mode)\n    : DecayChannel(mode)\n    , massive_lepton_(mode.massive_lepton_)\n    , neutrino_(mode.neutrino_)\n    , anti_neutrino_(mode.anti_neutrino_)\n{\n}\n\n// ------------------------------------------------------------------------- //\nbool LeptonicDecayChannelApprox::compare(const DecayChannel& channel) const\n{\n    const LeptonicDecayChannelApprox* leptonic = dynamic_cast<const LeptonicDecayChannelApprox*>(&channel);\n\n    if (!leptonic)\n        return false;\n    else if (massive_lepton_ != leptonic->massive_lepton_)\n        return false;\n    else if (neutrino_ != leptonic->neutrino_)\n        return false;\n    else if (anti_neutrino_ != leptonic->anti_neutrino_)\n        return false;\n    else\n        return true;\n}\n\n// ------------------------------------------------------------------------- //\ndouble LeptonicDecayChannelApprox::DecayRate(double x, double parent_mass, double E_max, double right_side)\n{\n    (void)parent_mass;\n    (void)E_max;\n\n    return x * x * x * (1. - 0.5 * x) - right_side;\n}\n\n// ------------------------------------------------------------------------- //\ndouble LeptonicDecayChannelApprox::DifferentialDecayRate(double x, double parent_mass, double E_max)\n{\n    (void)parent_mass;\n    (void)E_max;\n\n    return (3 - 2 * x) * x * x;\n}\n\n// ------------------------------------------------------------------------- //\nstd::pair<double, double> LeptonicDecayChannelApprox::function_and_derivative(double x,\n                                                                        double parent_mass,\n                                                                        double E_max,\n                                                                        double right_side)\n{\n    return std::make_pair(DecayRate(x, parent_mass, E_max, right_side), DifferentialDecayRate(x, parent_mass, E_max));\n}\n\n// ------------------------------------------------------------------------- //\ndouble LeptonicDecayChannelApprox::FindRootBoost(double min, double parent_mass, double E_max, double right_side)\n{\n    double max        = 1;\n    double x_start    = 0.5;\n    int binary_digits = 6;\n    // in older versions a max_step was set to 40, which were the max number of int steps\n    // int max_steps = 40;\n\n    return boost::math::tools::newton_raphson_iterate(\n        std::bind(&LeptonicDecayChannelApprox::function_and_derivative, this, std::placeholders::_1, parent_mass, E_max, right_side),\n        x_start,\n        min,\n        max,\n        binary_digits);\n}\n\n// ------------------------------------------------------------------------- //\nDecayChannel::DecayProducts LeptonicDecayChannelApprox::Decay(const Particle& particle)\n{\n    double parent_mass = particle.GetMass();\n\n    DecayProducts products;\n    products.push_back(new Particle(massive_lepton_));\n    products.push_back(new Particle(neutrino_));\n    products.push_back(new Particle(anti_neutrino_));\n\n    // Sample energy from decay rate\n    double emax       = (parent_mass * parent_mass + massive_lepton_.mass * massive_lepton_.mass) / (2 * parent_mass);\n    double x_min      = massive_lepton_.mass / emax;\n    // double f_min      = x_min * x_min * x_min * (1 - 0.5 * x_min);\n    // double right_side = f_min + (0.5 - f_min) * RandomGenerator::Get().RandomDouble();\n\n    double f_min      = DecayRate(x_min, parent_mass, emax, 0.0);\n    double f_max      = DecayRate(1.0, parent_mass, emax, 0.0);\n    double right_side = f_min + (f_max - f_min) * RandomGenerator::Get().RandomDouble();\n\n    double find_root = FindRootBoost(x_min, parent_mass, emax, right_side);\n\n    double lepton_energy   = std::max(find_root * emax, massive_lepton_.mass);\n    double lepton_momentum = std::sqrt((lepton_energy - massive_lepton_.mass) * (lepton_energy + massive_lepton_.mass));\n\n    // Sample directions For the massive letpon\n    products[0]->SetDirection(GenerateRandomDirection());\n    products[0]->SetMomentum(lepton_momentum);\n\n    // Sample directions For the massless letpon\n    double energy_neutrinos   = parent_mass - lepton_energy;\n    double virtual_mass       = std::sqrt((energy_neutrinos - lepton_momentum) * (energy_neutrinos + lepton_momentum));\n    double momentum_neutrinos = 0.5 * virtual_mass;\n    Vector3D direction        = GenerateRandomDirection();\n\n    products[1]->SetDirection(direction);\n    products[1]->SetMomentum(momentum_neutrinos);\n\n    Vector3D opposite_direction = -direction;\n    opposite_direction.CalculateSphericalCoordinates();\n    products[2]->SetDirection(opposite_direction);\n    products[2]->SetMomentum(momentum_neutrinos);\n\n    // Boost neutrinos to lepton frame\n    // double beta = lepton_momentum / energy_neutrinos;\n    double gamma = energy_neutrinos / virtual_mass;\n    double betagamma = lepton_momentum / virtual_mass;\n    Boost(*products[1], products[0]->GetDirection(), gamma, betagamma);\n    Boost(*products[2], products[0]->GetDirection(), gamma, betagamma);\n\n    // Boost all products in Lab frame (the reason, why the boosting goes in the negative direction of the particle)\n    Boost(products, -particle.GetDirection(), particle.GetEnergy()/particle.GetMass(), particle.GetMomentum()/particle.GetMass());\n\n    CopyParticleProperties(products, particle);\n\n    return products;\n}\n\n// ------------------------------------------------------------------------- //\n// Print\n// ------------------------------------------------------------------------- //\n\n// ------------------------------------------------------------------------- //\nvoid LeptonicDecayChannelApprox::print(std::ostream& os) const\n{\n    os << \"Massive lepton:\\n\" << massive_lepton_ << '\\n';\n    os << \"Neutrino:\\n\" << neutrino_ << '\\n';\n    os << \"Anti neutrino:\\n\" << anti_neutrino_ << '\\n';\n}\n\n/******************************************************************************\n *                          LeptonicDecayChannel                              *\n ******************************************************************************/\n\nconst std::string LeptonicDecayChannel::name_ = \"LeptonicDecayChannel\";\n\n// ------------------------------------------------------------------------- //\nLeptonicDecayChannel::LeptonicDecayChannel(const ParticleDef& lepton,\n                                                 const ParticleDef& neutrino,\n                                                 const ParticleDef& anti_neutrino)\n    : LeptonicDecayChannelApprox(lepton, neutrino, anti_neutrino)\n{\n}\n\n// ------------------------------------------------------------------------- //\nLeptonicDecayChannel::~LeptonicDecayChannel() {}\n\n// ------------------------------------------------------------------------- //\nLeptonicDecayChannel::LeptonicDecayChannel(const LeptonicDecayChannel& mode)\n    : LeptonicDecayChannelApprox(mode)\n{\n}\n\n// ------------------------------------------------------------------------- //\ndouble LeptonicDecayChannel::DecayRate(double x, double M, double E_max, double right_side)\n{\n    double M2 = M * M;\n    double m  = massive_lepton_.mass;\n    double m2 = m * m;\n\n    double E_l     = E_max * x;\n    double sqrt_EM = std::sqrt(E_l * E_l - m2);\n\n    return 1.5 * m2 * m2 * M * std::log(sqrt_EM + E_l) +\n           sqrt_EM * ((M2 + m2 - M * E_l) * (E_l * E_l - m2) - 1.5 * M * E_l * m2) - right_side;\n}\n\n// ------------------------------------------------------------------------- //\ndouble LeptonicDecayChannel::DifferentialDecayRate(double x, double M, double E_max)\n{\n    double m   = massive_lepton_.mass;\n    double E_l = E_max * x;\n\n    return E_max * std::sqrt(E_l * E_l - m * m) * (M * E_l * (3.0 * M - 4.0 * E_l) + m * m * (3.0 * E_l - 2 * M));\n}\n", "meta": {"hexsha": "a28fc7ede82f248af816ca2b88874d3d5cdec320", "size": 8914, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "PROPOSAL/private/PROPOSAL/decay/LeptonicDecayChannel.cxx", "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_issues_repo_path": "PROPOSAL/private/PROPOSAL/decay/LeptonicDecayChannel.cxx", "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROPOSAL/private/PROPOSAL/decay/LeptonicDecayChannel.cxx", "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "avg_line_length": 40.334841629, "max_line_length": 133, "alphanum_fraction": 0.5373569666, "num_tokens": 1947, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8596637397236823, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.42647387669681336}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <sstream>\n#include <filesystem>\n#include <string>\n#include <utility>\n\nusing namespace std::string_literals;\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"miMaS/field.h\"\n#include \"miMaS/complex_field.h\"\n#include \"miMaS/weno.h\"\n#include \"miMaS/fft.h\"\n#include \"miMaS/array_view.h\"\n#include \"miMaS/poisson.h\"\n#include \"miMaS/rk.h\"\n#include \"miMaS/config.h\"\n#include \"miMaS/signal_handler.h\"\n#include \"miMaS/iteration.h\"\n\n\n\nnamespace o2 {\n  template < typename _T , std::size_t NumDimsV >\n  auto\n  trp_v ( field<_T,NumDimsV> const & u , ublas::vector<_T> const& E )\n  {\n    field<_T,NumDimsV> trp(tools::array_view<const std::size_t>(u.shape(),NumDimsV+1));\n\n    { auto k=0, km1=trp.size(0)-1;\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[k+1][i]-u[km1][i])/(2.*u.step.dv) );\n      }\n    }\n    for ( auto k=1 ; k<trp.size(0)-1 ; ++k ) {\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[k+1][i]-u[k-1][i])/(2.*u.step.dv) );\n      }\n    }\n    { auto k=trp.size(0)-1, kp1=0;\n      for ( auto i=0 ; i<trp.size(1) ; ++i ) {\n        trp[k][i] = ( E(i)*(u[kp1][i]-u[k-1][i])/(2.*u.step.dv) );\n      }\n    }\n\n    return trp;\n  }\n}\n\nnamespace math = boost::math::constants;\nconst std::complex<double> & I = std::complex<double>(0.,1.);\n\n#define SQ(X) ((X)*(X))\n#define Xi(i) (i*f.step.dx+f.range.x_min)\n#define Vk(k) (k*f.step.dv+f.range.v_min)\n\nstruct surimi {\n  ublas::vector<double> E;\n\n  surimi ( std::size_t nx , double )\n    : E(nx,1.)\n  { ; }\n\n  ~surimi ()\n  { ; }\n\n  ublas::vector<double>\n  operator () ( ublas::vector<double> const& )\n  {\n    return E;\n  }\n};\n\nauto\ndisque ( double x0 , double v0 , double R ) {\n  return [=](double x,double v){ return ( SQ( x-x0 ) + SQ(v-v0) < R*R ) ? 1. : 0.; };\n}\n\nauto\ntest2 ( double vmin , double vmax , double kx ) {\n  return [=](double x,double v){ return ( vmin < v && v < vmax ) ? std::cos(2.*math::pi<double>()*kx*x) : 0.; };\n}\n\nauto\nmaxwellian ( double rho , double u , double T ) {\n  return [=](double x,double v){ return rho/(std::sqrt(2.*math::pi<double>()*T))*std::exp( -0.5*SQ(v-u)/T ); };\n}\n\nint\nmain ( int argc , char const * argv[] )\n{\n  std::filesystem::path p(\"config.init\");\n  if ( argc > 1 )\n    { p = argv[1]; }\n  auto c = config(p);\n  c.name = \"cm_e10m3\";\n\n  c.create_output_directory();\n  std::ofstream ofconfig( c.output_dir / \"config.init\" );\n  ofconfig << c << \"\\n\";\n  ofconfig.close();\n\n/* ------------------------------------------------------------------------- */\n  field<double,1> f(boost::extents[c.Nv][c.Nx]);\n  field<double,1> f_sol(boost::extents[c.Nv][c.Nx]);\n\n  complex_field<double,1> hf(boost::extents[c.Nv][c.Nx]);\n  fft::spectrum_ d(c.Nx);\n\n  std::vector<double> mass;\n\n  const double Kx = 0.5;\n  f.range.v_min = -3.; f.range.v_max = 3.;\n  f.range.x_min = -3.; f.range.x_max = 3.;\n  f.compute_steps();\n\n  f_sol.range = f.range;\n  f_sol.compute_steps();\n\n  ublas::vector<double> v (c.Nv,1.); // velocity in x direction, transport at speed 1\n\n  ublas::vector<double> kx(c.Nx);\n  {\n    double l = f.range.len_x();\n    for ( auto i=0 ; i<c.Nx/2 ; ++i ) { kx[i]      = 2.*math::pi<double>()*i/l; }\n    for ( int i=-c.Nx/2 ; i<0 ; ++i ) { kx[c.Nx+i] = 2.*math::pi<double>()*i/l; }\n  }\n\n  auto c0 = disque(0.,0.,1.);\n  auto d0 = test2(-1.,1.,1./f.range.len_x());\n\n  double m=0;\n  for (field<double,2>::size_type k=0 ; k<f.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<f.size(1) ; ++i ) {\n      f[k][i] = c0(Xi(i),Vk(k));\n      f_sol[k][i] = c0(Xi(i)-c.Tf,Vk(k)-c.Tf);\n\n      m += f[k][i]*f.step.dx*f.step.dv;\n      //f[k][i] = d0(Xi(i),Vk(k));\n      //f_sol[k][i] = d0(Xi(i)-c.Tf,Vk(k)-c.Tf);\n    }\n  }\n  std::cout << m << std::endl;\n  //d.fft(f[int(c.Nv/2.)].begin());\n  //std::copy( d.begin() , d.end() , std::ostream_iterator<std::complex<double>>(std::cout,\" \"));\n\n  f.write( c.output_dir / (\"init_\"+c.name+\".dat\") );\n  f_sol.write( c.output_dir / (\"sol_\"+c.name+\".dat\") );\n\n  iteration::iteration<double> iter;\n  iter.iter = 0;\n  iter.current_time = 0.;\n  //iter.dt = 0.050*f.step.dv;\n  //iter.dt = 2.*std::sqrt(2.)*f.step.dv;\n  iter.dt = 0.150*f.step.dv;\n\n  std::vector<double> normL2; normL2.reserve(100);\n  auto L2 = [&]( field<double,1>const& f )->double {\n    return std::pow(\n            std::accumulate( f.origin() , f.origin()+f.num_elements() , 0. ,\n              []( double s , double fik )->double { return s + fik*fik; }\n          ),2)*f.step.dx*f.step.dv;\n  };\n\n  // space scheme\n  auto wenol = [&](field<double,1>const& f , ublas::vector<double> const& E )->field<double,1> { return wenolin::trp_v(f,E); };\n  auto weno  = [&](field<double,1>const& f , ublas::vector<double> const& E )->field<double,1> { return weno::trp_v(f,E); };\n  auto cd2   = [&](field<double,1>const& f , ublas::vector<double> const& E )->field<double,1> { return o2::trp_v(f,E); };\n\n  // time scheme init\n  //expRK::HochbruckOstermann<surimi> rk(c.Nx,c.Nv,f.range.len_x(),f.shape(),v,kx,cd2); // 0.250 , 0.501 , 1.702\n  expRK::CoxMatthews<surimi> rk(c.Nx,c.Nv,f.range.len_x(),f.shape(),v,kx,cd2); // 0.150 , 0.450 , 1.351\n  //expRK::RK22<surimi> rk(c.Nx,c.Nv,f.range.len_x(),f.shape(),v,kx,cd2);\n  //lawson::RK33<surimi> rk(c.Nx,c.Nv,f.range.len_x(),f.shape(),v,kx,weno);\n\n  //while (  iter.current_time < c.Tf ) {\n  while ( iter.iter < 101 ) {\n    std::cout << \"\\r\" << iteration::time(iter) << std::flush;\n\n    normL2.push_back(L2(f));\n    f = rk(f,iter.dt);\n\n\n    ++iter.iter;\n    //if ( iter.current_time + iter.dt > c.Tf ) { iter.dt = c.Tf-iter.current_time; }\n    iter.current_time += iter.dt;\n  }\n  std::cout << \"\\r\" << time(iter) << std::endl;\n\n  f.write( c.output_dir / (\"vp_\"+c.name+\".dat\") );\n\n  /*\n  field<double,1> f_diff(boost::extents[c.Nv][c.Nx]);\n  f_diff.range = f.range;\n  for (field<double,2>::size_type k=0 ; k<f.size(0) ; ++k ) {\n    for (field<double,2>::size_type i=0 ; i<f.size(1) ; ++i ) {\n      f_diff[k][i] = f[k][i]-d0(Xi(i)-c.Tf,Vk(k)-c.Tf);\n    }\n  }\n  f_diff.write( c.output_dir / (\"diff_\"+c.name+\".dat\") );\n  */\n\n  std::ofstream of( c.output_dir / (\"normL2\"+c.name+\".dat\") );\n  std::transform(\n    normL2.begin() , normL2.end() ,\n    std::ostream_iterator<std::string>(of,\"\\n\") ,\n    [&,count=0](double x) mutable {\n      std::stringstream ss; ss << count << \" \" << iter.dt*(count++) << \" \" << x;\n      return ss.str();\n    }\n  );\n  of.close();\n\n  return 0;\n}\n", "meta": {"hexsha": "79ef8d6cc9475edbbfb55c2c7ea0d991c425e589", "size": 6544, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/lintrp.cc", "max_stars_repo_name": "Kivvix/miMaS", "max_stars_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-01-03T22:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-29T06:12:07.000Z", "max_issues_repo_path": "code/lintrp.cc", "max_issues_repo_name": "Kivvix/miMaS", "max_issues_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/lintrp.cc", "max_forks_repo_name": "Kivvix/miMaS", "max_forks_repo_head_hexsha": "ad3894522e64f21827ba3b8f8d1a48c3dc9216e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-20T12:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-29T06:17:16.000Z", "avg_line_length": 29.2142857143, "max_line_length": 127, "alphanum_fraction": 0.5611246944, "num_tokens": 2318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.42645188243830273}}
{"text": "#pragma once\n\n#include <math.h>\n#include <boost/serialization/version.hpp>\n#include \"types/Point.hpp\"\n\nstruct RANSACLine\n{\n   Point p1, p2;\n   /**\n    * Line defined in terms of\n    * t1 * x + t2 * y + t3 = 0\n    */\n   int t1, t2, t3;\n   float var;\n\n   RANSACLine(Point p1, Point p2, float var = 0) : p1(p1), p2(p2), var(var)\n   {\n      t1 = p2.y() - p1.y();\n      t2 = p1.x() - p2.x();\n      t3 = p1.y() * (p2.x() - p1.x()) - p1.x() * (p2.y() - p1.y());\n   }\n\n   RANSACLine() {};\n   \n   RANSACLine(const RANSACLine &other) {\n      this->t1 = other.t1;\n      this->t2 = other.t2;\n      this->t3 = other.t3;\n      this->var = other.var;\n      \n      this->p1(0, 0) = other.p1(0, 0);\n      this->p1(1, 0) = other.p1(1, 0);\n      this->p2(0, 0) = other.p2(0, 0);\n      this->p2(1, 0) = other.p2(1, 0);\n   }\n\n   template<class Archive>\n   void serialize(Archive &ar, const unsigned int file_version)\n   {\n      ar & t1 & t2 & t3;\n      ar & var;\n      if (file_version >= 1) {\n        ar & p1 & p2;\n      } else {\n        p1 = Point (0, 0);\n        p2 = Point (0, 0);\n      }\n   }\n};\n\ninline std::ostream& operator<<(std::ostream& os, const RANSACLine& line) {\n   os << line.p1;\n   os << line.p2;\n   os.write((char*) &(line.t1), sizeof(int));\n   os.write((char*) &(line.t2), sizeof(int));\n   os.write((char*) &(line.t3), sizeof(int));\n   os.write((char*) &(line.var), sizeof(float));\n   \n   return os;\n}\n\ninline std::istream& operator>>(std::istream& is, RANSACLine& line) {\n   is >> line.p1;\n   is >> line.p2;\n   is.read((char*) &(line.t1), sizeof(int));\n   is.read((char*) &(line.t2), sizeof(int));\n   is.read((char*) &(line.t3), sizeof(int));\n   is.read((char*) &(line.var), sizeof(float));\n   \n   return is;\n}\n\nBOOST_CLASS_VERSION(RANSACLine, 1);\n\nstruct RANSACCircle\n{\n   PointF centre;\n   float radius;\n   float var;\n\n   RANSACCircle(PointF centre, float radius, float var = 0)\n      : centre(centre), radius(radius), var(var)\n   {\n   }\n\n   RANSACCircle(const Point p1, const Point p2, const Point p3, float var = 0)\n      : var(var)\n   {\n      float bx = p1.x(); float by = p1.y();\n      float cx = p2.x(); float cy = p2.y();\n      float dx = p3.x(); float dy = p3.y();\n\n      float temp = cx*cx+cy*cy;\n      float bc   = (bx*bx + by*by - temp)/2.0;\n      float cd   = (temp - dx*dx - dy*dy)/2.0;\n      float det  = (bx-cx)*(cy-dy)-(cx-dx)*(by-cy);\n\n      centre = PointF();\n      radius = 0;\n\n      if (fabs(det) < 1.0e-6) {\n         this->radius = std::numeric_limits<float>::quiet_NaN();\n         return;\n      }\n\n      det = 1 / det;\n      centre.x() = (bc*(cy-dy)-cd*(by-cy))*det;\n      centre.y() = ((bx-cx)*cd-(cx-dx)*bc)*det;\n      cx = centre.x(); cy = centre.y();\n      radius = sqrt((cx-bx)*(cx-bx)+(cy-by)*(cy-by));\n   }\n\n   RANSACCircle(const Point p1, const Point p2, float radius, float var = 0)\n      : radius(radius), var(var)\n   {\n\t\t/* TODO(carl) Find a faster way to do this */\n/*\n      PointF v = (p2 - p1).cast<float>();\n      PointF n = PointF(v.y(), -v.x()).normalized();\n      PointF m = (p2 + p1).cast<float>() / 2;\n      float dist2 = ((p1.x()- p2.x()) * (p1.x()- p2.x())) +\n         ((p1.y()- p2.y()) * (p1.y()- p2.y()));\n      float d = sqrt(radius*radius - (dist2 / 4));\n      PointF newN = PointF(n.x() * d, n.y() *d);\n      centre = (m + (newN));\n*/\n\n      centre = PointF();\n      if (p1 == p2) {\n         this->radius = std::numeric_limits<float>::quiet_NaN();\n         return;\n      };\n\n      const float x1 = p1.x(), x2 = p2.x(), y1 = p1.y(), y2 = p2.y();\n      if (y1 != y2) {\n         const float k1 = (x2 - x1) / (y1 - y2);\n         const float k2 = (x1*x1 + y1*y1 - x2*x2 - y2*y2) / (2*(y1 - y2));\n\n         const float a = 1 + k1*k1;\n         const float b = -2*x1 + 2*(k1*(k2 - y1));\n         const float c = x1*x1 + (k2 - y1)*(k2 - y1) - radius*radius;\n         const float d = b*b - 4*a*c;\n\n         if (d < 0) {\n            this->radius = std::numeric_limits<float>::quiet_NaN();\n            return;\n         }\n\n         const float x = (-b + (y1 > y2 ? sqrtf(d) : -sqrtf(d))) / (2*a);\n         const float y = k1*x + k2;\n         centre.x() = x;\n         centre.y() = y;\n\n      } else {\n         const float k1 = (y2 - y1) / (x1 - x2);\n         const float k2 = (y1*y1 + x1*x1 - y2*y2 - x2*x2) / (2*(x1 - x2));\n\n         const float a = 1 + k1*k1;\n         const float b = -2*y1 + 2*(k1*(k2 - x1));\n         const float c = y1*y1 + (k2 - x1)*(k2 - x1) - radius*radius;\n         const float d = b*b - 4*a*c;\n\n         if (d < 0) {\n            this->radius = std::numeric_limits<float>::quiet_NaN();\n            return;\n         }\n\n         const float x = (-b + (x1 > x2 ? sqrtf(d) : -sqrtf(d))) / (2*a);\n         const float y = k1*x + k2;\n         centre.x() = x;\n         centre.y() = y;\n      }\n   }\n\n   RANSACCircle() {};\n\n   template<class Archive>\n   void serialize(Archive &ar, const unsigned int file_version)\n   {\n      ar & centre;\n      ar & radius;\n      ar & var;\n   }\n\n};\n\nBOOST_CLASS_VERSION(RANSACCircle, 0);\n", "meta": {"hexsha": "c32d9bd4a149a47098f3bc509aff72a897c1e066", "size": 4973, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/External/unsw/unsw/types/RansacTypes.hpp", "max_stars_repo_name": "pedrohsreis/boulos", "max_stars_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T18:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T17:47:07.000Z", "max_issues_repo_path": "src/Core/External/unsw/unsw/types/RansacTypes.hpp", "max_issues_repo_name": "pedrohsreis/boulos", "max_issues_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-08T18:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-19T21:41:16.000Z", "max_forks_repo_path": "src/Core/External/unsw/unsw/types/RansacTypes.hpp", "max_forks_repo_name": "pedrohsreis/boulos", "max_forks_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-09-11T17:19:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-30T16:43:56.000Z", "avg_line_length": 26.3121693122, "max_line_length": 78, "alphanum_fraction": 0.4886386487, "num_tokens": 1716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4264518768460496}}
{"text": "#include <algorithm>\n#include <array>\n#include <cassert>\n#include <exception>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <stdexcept>\n#include <vector>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/astar_search.hpp>\n#include <boost/operators.hpp>\n\n\ntemplate<typename ForwardIt>\nauto is_element_unique(ForwardIt first, ForwardIt last) -> bool {\n    for (; first != last; ++first) {\n        if (last != std::find(first + 1, last, *first)) {\n            return false;\n        }\n    }\n    return true;\n}\n\n\ntemplate<typename ForwardIt>\nauto permutation_parity(ForwardIt first1, ForwardIt last1, ForwardIt first2, ForwardIt last2) -> int {\n    assert(std::distance(first1, last1) == std::distance(first2, last2));\n\n    std::vector<bool> mark(std::distance(first1, last1));\n    int counter = 0;\n    bool done = false;\n    do {\n        // find next unmark pos\n        auto unmark = std::find(mark.begin(), mark.end(), false);\n        if (unmark == mark.end()) {\n            done = true;\n        }\n        else {\n            auto pos1 = std::next(first1, std::distance(mark.begin(), unmark));\n            auto f = pos1;\n            bool end_cycle = false;\n            do {\n                // find next pos in the cycle\n                // only accept if it is not marked\n                bool found = false;\n                auto pos2 = first2;\n                long long dis = 0;\n                do {\n                    pos2 = std::find(pos2, last2, *pos1);\n                    if (pos2 == last2) return -1;\n                    dis = std::distance(first2, pos2);\n                    found = (mark[dis] == false);\n                    ++pos2;\n                } while (!found);\n\n                pos1 = std::next(first1, dis);\n                mark[dis] = true;\n                if (*f == *pos1) {\n                    end_cycle = true;\n                }\n                else {\n                    ++counter;\n                }\n            } while (!end_cycle);\n        }\n    } while (!done);\n\n    return counter;\n}\n\n\nnamespace puzzle {\n\n    struct direction {\n        enum type {\n            begin = 0,\n            left = begin,\n            top,\n            right,\n            bottom,\n            end\n        };\n    };\n\n\n    namespace board {\n\n        // contains size * size numbers\n        // 1 special number called blank square\n        template<typename Derived>\n        class base_board {\n            using mytype = base_board;\n            using derived_type = Derived;\n\n\n        protected:\n            base_board() = default;\n            ~base_board() = default;\n\n\n        public:\n            // slide blank square\n            auto slide(direction::type d) -> bool {\n                auto&& buffer = this->buffer();\n                auto bpos = blankpos();\n                auto& row = bpos.first;\n                auto& col = bpos.second;\n\n                using std::swap;\n                switch (d) {\n                case direction::left:\n                    if (col == 0)\n                        return false;\n                    swap(buffer[row][col], buffer[row][col - 1]);\n                    --col;\n                    blankpos(bpos);\n                    break;\n\n                case direction::top:\n                    if (row == 0)\n                        return false;\n                    swap(buffer[row][col], buffer[row - 1][col]);\n                    --row;\n                    blankpos(bpos);\n                    break;\n\n                case direction::right:\n                    if (col == size() - 1)\n                        return false;\n                    swap(buffer[row][col], buffer[row][col + 1]);\n                    ++col;\n                    blankpos(bpos);\n                    break;\n\n                case direction::bottom:\n                    if (row == size() - 1)\n                        return false;\n                    swap(buffer[row][col], buffer[row + 1][col]);\n                    ++row;\n                    blankpos(bpos);\n                    break;\n\n                default:\n                    throw std::invalid_argument{ \"invalid slide direction\" };\n                    break;\n                }\n\n                return true;\n            }\n\n\n            // find position of a number in board\n            // return (-1, -1) if cannot find\n            auto find(int num) const noexcept -> std::pair<int, int> {\n                auto&& buffer = this->buffer();\n                for (auto row = 0; row < size(); ++row) {\n                    for (auto col = 0; col < size(); ++col) {\n                        if (buffer[row][col] == num) {\n                            return std::make_pair(row, col);\n                        }\n                    }\n                }\n                return std::make_pair(-1, -1);\n            }\n\n\n            // get & set blank square position\n            auto blankpos() const noexcept -> decltype(auto) {\n                return static_cast<derived_type const *>(this)->blankpos();\n            }\n\n\n            void blankpos(std::pair<int, int> const& bpos) noexcept {\n                static_cast<derived_type*>(this)->blankpos(bpos);\n            }\n\n\n            auto size() const noexcept -> decltype(auto) {\n                return static_cast<derived_type const *>(this)->size();\n            }\n\n\n            // read only\n            auto operator[](int index) const noexcept -> decltype(auto) {\n                return buffer()[index];\n            }\n\n\n            // used by std::map\n            auto operator<(mytype const& other) const noexcept -> bool {\n                return buffer() < other.buffer();\n            }\n\n\n            auto operator==(mytype const& other) const noexcept -> bool {\n                return buffer() == other.buffer();\n            }\n\n            auto operator!=(mytype const& other) const noexcept -> bool {\n                return !(*this == other);\n            }\n\n\n            // output mytype to ostream\n            friend std::ostream& operator<<(std::ostream& os, mytype const& board) {\n                auto width = os.width();\n                for (auto r = 0; r < board.size(); ++r) {\n                    for (auto c = 0; c < board.size(); ++c) {\n                        os << std::setw(width) << board.buffer()[r][c];\n                    }\n                    os << \"\\n\";\n                }\n                return os;\n            }\n\n\n        private:\n            auto buffer() noexcept -> decltype(auto) {\n                return static_cast<derived_type *>(this)->buffer();\n            }\n\n            auto buffer() const noexcept -> decltype(auto) {\n                return static_cast<derived_type const *>(this)->buffer();\n            }\n        };\n\n\n        template<int N>\n        class aa_board : public base_board<aa_board<N>>\n        {\n            static_assert(N > 0, \"invalid size\");\n\n            using mybase = base_board<aa_board<N>>;\n            using buffer_type = std::array<std::array<int, N>, N>;\n\n            friend mybase;\n\n        public:\n            aa_board() = default;\n            aa_board(buffer_type const& buffer, std::pair<int, int> const& blankpos) :\n                mybase{},\n                m_buffer{ buffer },\n                m_brow{ blankpos.first },\n                m_bcol{ blankpos.second }\n            {\n                // check blank square position\n                if ((0 <= m_brow && m_brow <= size() - 1) && (0 <= m_brow && m_brow <= size() - 1)) {\n                    // then it's OK\n                }\n                else {\n                    throw std::invalid_argument{ \"invalid blank position\" };\n                }\n            }\n\n\n        public: // required by base_board\n            auto size() const noexcept -> int {\n                return N;\n            }\n\n\n            auto blankpos() const noexcept {\n                assert(m_brow != -1 && m_bcol != -1);\n                return std::make_pair(m_brow, m_bcol);\n            }\n\n\n            void blankpos(std::pair<int, int> const& bpos) noexcept {\n                m_brow = bpos.first;\n                m_bcol = bpos.second;\n            }\n\n\n        private: // required by base_board\n            auto buffer() noexcept -> buffer_type& {\n                return m_buffer;\n            }\n\n\n            auto buffer() const noexcept -> buffer_type const& {\n                return m_buffer;\n            }\n\n\n        private:\n            buffer_type m_buffer{};\n            int m_brow = -1;\n            int m_bcol = -1;\n        };\n\n\n        class vv_board : public base_board<vv_board>\n        {\n            using mybase = base_board<vv_board>;\n            using buffer_type = std::vector<std::vector<int>>;\n\n            friend mybase;\n\n        public:\n            vv_board() = default;\n            vv_board(buffer_type const& buffer, std::pair<int, int> const& blankpos) :\n                mybase{},\n                m_buffer{ buffer },\n                m_brow{ blankpos.first },\n                m_bcol{ blankpos.second }\n            {\n                // check buffer, number of cols must be equal to number of rows\n                for (auto& row : m_buffer) {\n                    if (static_cast<int>(row.size()) != size()) {\n                        throw std::invalid_argument{ \"invalid board\" };\n                    }\n                }\n\n                // check blank square position\n                if ((0 <= m_brow && m_brow <= size() - 1) && (0 <= m_brow && m_brow <= size() - 1)) {\n                    // then it's OK\n                }\n                else {\n                    throw std::invalid_argument{ \"invalid blank position\" };\n                }\n            }\n\n\n        public: // required by base_board\n            auto size() const noexcept -> int {\n                return static_cast<int>(m_buffer.size());\n            }\n\n\n            auto blankpos() const noexcept {\n                assert(m_brow != -1 && m_bcol != -1);\n                return std::make_pair(m_brow, m_bcol);\n            }\n\n\n            void blankpos(std::pair<int, int> const& bpos) noexcept {\n                m_brow = bpos.first;\n                m_bcol = bpos.second;\n            }\n\n\n        private: // required by base_board\n            auto buffer() noexcept -> buffer_type& {\n                return m_buffer;\n            }\n\n\n            auto buffer() const noexcept -> buffer_type const& {\n                return m_buffer;\n            }\n\n\n        private:\n            buffer_type m_buffer{};\n            int m_brow = -1;\n            int m_bcol = -1;\n        };\n\n\n        template<typename Board>\n        auto num_of_neighbors(Board const& board) noexcept -> int {\n            auto bpos = board.blankpos();\n            auto row = bpos.first;\n            auto col = bpos.second;\n\n            int non = 0;\n\n            int r1 = row - 1;\n            int r2 = row + 1;\n            int c1 = col - 1;\n            int c2 = col + 1;\n\n            auto is_valid_pos = [&board](int r, int c) -> bool {\n                return (0 <= r && r <= board.size() - 1) && (0 <= c && c <= board.size() - 1);\n            };\n\n            if (is_valid_pos(r1, c1)) ++non;\n            if (is_valid_pos(r1, c2)) ++non;\n            if (is_valid_pos(r2, c1)) ++non;\n            if (is_valid_pos(r2, c2)) ++non;\n\n            assert(non >= 2);\n\n            return non;\n        }\n\n\n        template<typename Board, typename T>\n        auto make_board(T&& buffer, int size, int blank_num = 0) {\n            int row = -1;\n            int col = -1;\n            for (auto r = 0; r < size; ++r) {\n                for (auto c = 0; c < size; ++c) {\n                    if (buffer[r][c] == blank_num) {\n                        row = r;\n                        col = c;\n                    }\n                }\n            }\n\n            if (row == -1 || col == -1)\n                throw std::invalid_argument{ \"cannot find blank square\" };\n\n            return Board{ buffer, std::make_pair(row, col) };\n        }\n\n    } // namespace board\n\n\n    namespace graph {\n\n        template<typename Board>\n        class neighbor_iterator : public boost::forward_iterator_helper<neighbor_iterator<Board>, Board>\n        {\n        public:\n            neighbor_iterator() = default;\n            neighbor_iterator(Board const& board, direction::type d) :\n                m_board{ board },\n                m_direction{ d }\n            {}\n\n\n            auto operator==(neighbor_iterator const& other) const noexcept -> bool {\n                if (m_direction == direction::end && other.m_direction == direction::end) {\n                    return true;\n                }\n                return m_direction == other.m_direction && m_board == other.m_board;\n            }\n\n\n            auto operator++() -> neighbor_iterator& {\n                m_direction = static_cast<direction::type>(m_direction + 1);\n                return *this;\n            }\n\n\n            auto operator*() const noexcept -> std::pair<Board, Board> {\n                auto temp = m_board;\n                temp.slide(m_direction);\n                return std::make_pair(m_board, temp);\n            }\n\n\n        private:\n            Board m_board;\n            direction::type m_direction = direction::end;\n        };\n\n\n        /*\n        model of\n            Graph\n            IncidenceGraph\n        */\n        template<typename Board>\n        struct board_graph {\n            // Graph concept requirements\n            using vertex_descriptor         = Board;\n            using edge_descriptor           = std::pair<Board, Board>;\n            using directed_category         = boost::undirected_tag;\n            using edge_parallel_category    = boost::disallow_parallel_edge_tag;\n            using traversal_category        = boost::incidence_graph_tag;\n\n            // IncidenceGraph concept requirements\n            using out_edge_iterator         = neighbor_iterator<Board>;\n            using degree_size_type          = int;\n        };\n\n\n\n        // IncidenceGraph concept requirements\n        template<typename Board,\n            typename Graph = board_graph<Board> // just make the name shorter\n        >\n        auto out_edges(typename Graph::vertex_descriptor const& board, board_graph<Board> const&)\n            -> std::pair<typename Graph::out_edge_iterator, typename Graph::out_edge_iterator>\n        {\n            return std::make_pair(\n                typename Graph::out_edge_iterator{ board, direction::begin },\n                typename Graph::out_edge_iterator{ board, direction::end }\n            );\n        }\n\n\n        template<typename Board,\n            typename Graph = board_graph<Board>\n        >\n        auto out_degree(typename Graph::vertex_descriptor const& board, board_graph<Board> const&)\n            -> typename Graph::degree_size_type\n        {\n            return num_of_neighbors(board);\n        }\n\n\n        /* boost graph already provides two below functions\n\n        template<typename Board,\n            typename Graph = board_graph<Board>\n        >\n        auto source(typename Graph::edge_descriptor const& e, board_graph<Board> const&)\n            -> typename Graph::vertex_descriptor\n        {\n            return e.first;\n        }\n\n\n        template<typename Board,\n            typename Graph = board_graph<Board>\n        >\n        auto target(typename Graph::edge_descriptor const& e, board_graph<Board> const&)\n            -> typename Graph::vertex_descriptor\n        {\n            return e.second;\n        }\n        */\n\n\n        // found exception\n        struct found : public std::exception\n        {};\n\n        struct exceed_limit : public std::exception\n        {};\n\n\n        template<typename Board>\n        class visitor : public boost::default_astar_visitor\n        {\n        public:\n            visitor(Board const& goal, int *counter = nullptr, int vertices_limit = -1) noexcept :\n                m_goal{ goal },\n                m_counter{ counter },\n                m_limit{ vertices_limit }\n            {}\n\n\n            void examine_vertex(Board const& board, board_graph<Board> const&) {\n                if (m_limit > 0) --m_limit;\n                if (m_counter) ++*m_counter;\n\n                if (board == m_goal)\n                    throw found{};\n\n                if (m_limit == 0)\n                    throw exceed_limit{};\n            }\n\n\n        private:\n            Board const& m_goal;\n            int *m_counter = nullptr;\n            int m_limit = -1;\n        };\n\n\n        template<typename Board>\n        class manhattan_heuristic : public boost::astar_heuristic<board_graph<Board>, int>\n        {\n        public:\n            manhattan_heuristic(Board const& goal) :\n                m_goal{ goal }\n            {}\n\n\n            auto operator()(Board const& board) -> int {\n                int sum = 0;\n                for (auto row = 0; row < board.size(); ++row) {\n                    for (auto m_col = 0; m_col < board.size(); ++m_col) {\n                        auto pos = m_goal.find(board[row][m_col]);\n                        sum += (std::abs(row - pos.first) + std::abs(m_col - pos.second)) << 1;\n                    }\n                }\n                return sum;\n            }\n\n\n        private:\n            Board const& m_goal;\n        };\n\n    } // namespace graph\n\n\n    // a map with default value\n    template <typename Key, typename Value>\n    class default_map {\n    public:\n        using key_type = Key;\n        using data_type = Value;\n        using value_type = std::pair<Key, Value>;\n\n\n        default_map(Value const& defaultValue)\n            : defaultValue(defaultValue)\n        {}\n\n\n        auto operator[](Key const& k) -> Value& {\n            if (m.find(k) == m.end()) {\n                m[k] = defaultValue;\n            }\n            return m[k];\n        }\n\n\n    private:\n        std::map<Key, Value> m;\n        Value const defaultValue;\n    };\n\n}\n\n\n// graph_traits partial specialization for board_graph\nnamespace boost {\n\n    template<typename Board>\n    struct graph_traits<puzzle::graph::board_graph<Board>> {\n        using G                         = puzzle::graph::board_graph<Board>;\n\n        using vertex_descriptor         = typename G::vertex_descriptor;\n        using edge_descriptor           = typename G::edge_descriptor;\n        using out_edge_iterator         = typename G::out_edge_iterator;\n\n        using directed_category         = typename G::directed_category;\n        using edge_parallel_category    = typename G::edge_parallel_category;\n        using traversal_category        = typename G::traversal_category;\n\n        using degree_size_type          = typename G::degree_size_type;\n\n        using in_edge_iterator          = void;\n        using vertex_iterator           = void;\n        using vertices_size_type        = void;\n        using edge_iterator             = void;\n        using edges_size_type           = void;\n    };\n\n}\n\n\nnamespace puzzle {\n\n    template<typename Board>\n    auto check_board(Board const& start, Board const& goal) -> bool {\n        // must have same size\n        if (start.size() != goal.size()) {\n            return false;\n        }\n        auto const size = start.size();\n\n        // must have same blank number\n        auto sbpos = start.blankpos();\n        auto gbpos = goal.blankpos();\n        if (start[sbpos.first][sbpos.second] != goal[gbpos.first][gbpos.second]) {\n            return false;\n        }\n\n        std::vector<int> vstart;\n        std::vector<int> vgoal;\n        vstart.reserve(size * size);\n        vgoal.reserve(size * size);\n        for (auto r = 0; r < size; ++r) {\n            for (auto c = 0; c < size; ++c) {\n                vstart.push_back(start[r][c]);\n                vgoal.push_back(goal[r][c]);\n            }\n        }\n\n        // each number can appear only once\n        if (!is_element_unique(vstart.begin(), vstart.end()) || !is_element_unique(vgoal.begin(), vgoal.end())) {\n            return false;\n        }\n\n        // both boards have same set of numbers\n        if (!std::is_permutation(vstart.begin(), vstart.end(), vgoal.begin(), vgoal.end())) {\n            return false;\n        }\n\n        return true;\n    }\n\n\n    template<typename Board>\n    auto solvable(Board const& start, Board const& goal) -> bool {\n        if (!check_board(start, goal)) {\n            throw std::invalid_argument{ \"invalid boards, cannot check solvability\" };\n        }\n\n        auto const size = start.size();\n\n        std::vector<int> vstart;\n        std::vector<int> vgoal;\n        vstart.reserve(size * size);\n        vgoal.reserve(size * size);\n        for (auto r = 0; r < size; ++r) {\n            for (auto c = 0; c < size; ++c) {\n                vstart.push_back(start[r][c]);\n                vgoal.push_back(goal[r][c]);\n            }\n        }\n\n        // compute parity of permutation\n        auto parity = permutation_parity(vstart.begin(), vstart.end(), vgoal.begin(), vgoal.end());\n        if (parity == -1) {\n            return false;\n        }\n\n        // compute taxicab distance\n        auto sbpos = start.blankpos();\n        auto gbpos = goal.blankpos();\n        auto tabdis = std::abs(sbpos.first - gbpos.first) + std::abs(sbpos.second - gbpos.second);\n\n        return (parity + tabdis) % 2 == 0;\n    }\n\n\n    template<typename Board>\n    auto solve(Board const& start, Board const& goal, int *counter = nullptr, int limit = -1) -> std::vector<Board> {\n        using PredecessorMap = boost::associative_property_map<std::map<Board, Board>>;\n        using DistanceMap = boost::associative_property_map<puzzle::default_map<Board, int>>;\n        using WeightMap = boost::associative_property_map<puzzle::default_map<std::pair<Board, Board>, int>>;\n        using VertexIndexMap = boost::associative_property_map<std::map<Board, int>>;\n        using RankMap = boost::associative_property_map<std::map<Board, int>>;\n        using ColorMap = boost::associative_property_map<std::map<Board, boost::default_color_type>>;\n\n\n        if (!check_board(start, goal)) {\n            throw std::invalid_argument{ \"invalid boards\" };\n        }\n\n        if (!solvable(start, goal)) {\n            throw std::runtime_error{ \"unsolvable\" };\n        }\n\n        puzzle::graph::board_graph<Board> graph;\n\n        std::map<Board, Board> pmx{};\n        puzzle::default_map<Board, int> dmx{ std::numeric_limits<int>::max() };\n        puzzle::default_map<std::pair<Board, Board>, int> wmx{ 1 };\n        std::map<Board, int> vimx{};\n        std::map<Board, int> rmx{};\n        std::map<Board, boost::default_color_type> cmx{};\n\n        PredecessorMap pm{ pmx };\n\n        try {\n            boost::astar_search_no_init(\n                graph,\n                start,\n                puzzle::graph::manhattan_heuristic<Board>{ goal },\n                boost::visitor(puzzle::graph::visitor<Board>{ goal, counter, limit })\n                    .weight_map(WeightMap{ wmx })\n                    .vertex_index_map(VertexIndexMap{ vimx })\n                    .predecessor_map(pm)\n                    .distance_map(DistanceMap{ dmx })\n                    .rank_map(RankMap{ rmx })\n                    .color_map(ColorMap{ cmx })\n                    .distance_compare(std::less<void>{})\n                    .distance_combine(std::plus<void>{})\n            );\n        }\n        catch (puzzle::graph::found const&) {\n            std::vector<Board> path;\n\n            auto current = goal;\n            bool done = false;\n            do {\n                path.push_back(current);\n                if (current == start) {\n                    done = true;\n                }\n                else {\n                    current = pm[current];\n                }\n            } while (!done);\n\n            return path;\n        }\n        catch (puzzle::graph::exceed_limit const&) {\n            // ignore\n        }\n\n        return std::vector<Board>{};\n    }\n\n} // namespace puzzle\n\n\nint main() {\n    try {\n        std::array<std::array<int, 4>, 4> g{ {\n            { 1,  2,  3,  4 },\n            { 5,  6,  7,  8 },\n            { 9, 10, 11, 12 },\n            { 13, 14, 15, 0 }\n        } };\n\n        std::array<std::array<int, 4>, 4> s{ {\n            { 7, 15,  2, 10 },\n            { 3,  0,  8,  5 },\n            { 6, 11, 13,  1 },\n            { 14, 12, 4,  9 }\n        } };\n\n        auto goal = puzzle::board::make_board<puzzle::board::aa_board<4>>(g, 4);\n        auto start = puzzle::board::make_board<puzzle::board::aa_board<4>>(s, 4);\n\n        int counter = 0;\n        auto path = puzzle::solve(start, goal, &counter);\n\n        std::cout\n            << \"number of tests: \" << counter << \"\\n\"\n            << \"number of steps: \" << path.size() - 1 << \"\\n\\n\";\n\n        std::cout\n            << \"start puzzle:\\n\" << std::setw(3) << start << \"\\n\\n\"\n            << \"goal puzzle:\\n\" << std::setw(3) << goal << \"\\n\\n\";\n\n        // print all intermediate blank square positions\n        for (auto it = path.rbegin(), eit = path.rend(); it != eit; ++it) {\n            auto pos = it->blankpos();\n            std::cout << \"(\" << pos.first << \",\" << pos.second << \") -> \";\n        }\n        std::cout << \"done\\n\";\n    }\n    catch (std::exception const& e) {\n        std::cout << e.what();\n    }\n}\n", "meta": {"hexsha": "1548370581b9d81a3f3362227f02d762ebf2949b", "size": 25027, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/15Puzzle.cpp", "max_stars_repo_name": "so61pi/examples", "max_stars_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-01T07:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T00:05:06.000Z", "max_issues_repo_path": "cpp/15Puzzle.cpp", "max_issues_repo_name": "so61pi/examples", "max_issues_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2020-02-24T13:04:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T10:19:48.000Z", "max_forks_repo_path": "cpp/15Puzzle.cpp", "max_forks_repo_name": "so61pi/examples", "max_forks_repo_head_hexsha": "38e2831cd6517864fc05f499f72fbb4ff6ae27c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-30T07:29:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-30T07:29:58.000Z", "avg_line_length": 30.0805288462, "max_line_length": 117, "alphanum_fraction": 0.4788428497, "num_tokens": 5413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.42643227664048233}}
{"text": "//\n// Copyright 2013 Christian Henning\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n#ifndef BOOST_GIL_IO_TEST_MANDEL_HPP\n#define BOOST_GIL_IO_TEST_MANDEL_HPP\n\n#include <boost/gil.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace gil;\n\n// Models a Unary Function\ntemplate <typename P>   // Models PixelValueConcept\nstruct mandelbrot_fn\n{\n    using point_t = boost::gil::point_t;\n    using const_t = mandelbrot_fn;\n    using value_type = P;\n    using reference = value_type;\n    using const_reference = value_type;\n    using argument_type = point_t;\n    using result_type = reference;\n    static constexpr bool is_mutable = false;\n\n    value_type                    _in_color,_out_color;\n    point_t                       _img_size;\n    static const int MAX_ITER=100;        // max number of iterations\n\n    mandelbrot_fn() {}\n    mandelbrot_fn(const point_t& sz, const value_type& in_color, const value_type& out_color) : _in_color(in_color), _out_color(out_color), _img_size(sz) {}\n\n    std::ptrdiff_t width()  { return _img_size.x; }\n    std::ptrdiff_t height() { return _img_size.y; }\n\n    result_type operator()(const point_t& p) const {\n        // normalize the coords to (-2..1, -1.5..1.5)\n        // (actually make y -1.0..2 so it is asymmetric, so we can verify some view factory methods)\n        double t=get_num_iter(point<double>(p.x/(double)_img_size.x*3-2, p.y/(double)_img_size.y*3-1.0f));//1.5f));\n        t=pow(t,0.2);\n\n        value_type ret;\n        for (int k=0; k<num_channels<P>::value; ++k)\n            ret[k]=(typename channel_type<P>::type)(_in_color[k]*t + _out_color[k]*(1-t));\n        return ret;\n    }\n\nprivate:\n    double get_num_iter(const point<double>& p) const {\n        point<double> Z(0,0);\n        for (int i=0; i<MAX_ITER; ++i) {\n            Z = point<double>(Z.x*Z.x - Z.y*Z.y + p.x, 2*Z.x*Z.y + p.y);\n            if (Z.x*Z.x + Z.y*Z.y > 4)\n                return i/(double)MAX_ITER;\n        }\n        return 0;\n    }\n};\n\ntemplate< typename Pixel >\nstruct mandel_view\n{\n    using deref_t = mandelbrot_fn<Pixel>;\n    using locator_t= virtual_2d_locator<deref_t, false>;\n    using my_virt_view_t = image_view<locator_t>;\n    using type = my_virt_view_t;\n};\n\ntemplate< typename Pixel >\ntypename mandel_view< Pixel >::type create_mandel_view( unsigned int width\n                                                      , unsigned int height\n                                                      , const Pixel& in\n                                                      , const Pixel& out\n                                                      )\n{\n    using view_t = typename mandel_view<Pixel>::type;\n    using deref_t = typename mandel_view<Pixel>::deref_t;\n    using locator_t = typename mandel_view<Pixel>::locator_t;\n\n    point_t dims( width, height );\n    return view_t( dims\n                 , locator_t( point_t( 0, 0 )\n                            , point_t( 1, 1 )\n                            , deref_t( dims\n                                     , in\n                                     , out\n                                     )\n                            )\n                 );\n}\n\n#endif // BOOST_GIL_IO_TEST_MANDEL_HPP\n", "meta": {"hexsha": "4c7b89216f4defb4f90b4872dfa4754efd62209d", "size": 3290, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/gil/io/test/mandel_view.hpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/gil/io/test/mandel_view.hpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/gil/io/test/mandel_view.hpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 33.9175257732, "max_line_length": 156, "alphanum_fraction": 0.5671732523, "num_tokens": 818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4264322766404823}}
{"text": "#include \"ackermann_ekf/ackermann_ekf.h\"\n\n#include <boost/algorithm/clamp.hpp>\n#include <math.h>\n#include <vector>\n\nnamespace ackermann_ekf {\n\nAckermannEkf::AckermannEkf(const Eigen::VectorXd x_min,\n                           const Eigen::VectorXd x_max, double wheelbase,\n                           double control_acceleration_gain,\n                           double max_control_acceleration,\n                           double control_angle_speed_gain,\n                           double max_control_angle_speed)\n    : x(STATE_SIZE),\n      P(STATE_SIZE, STATE_SIZE),\n      Q(STATE_SIZE, STATE_SIZE),\n      x_min_(x_min),\n      x_max_(x_max),\n      wheelbase_(wheelbase),\n      control_acceleration_gain_(control_acceleration_gain),\n      max_control_acceleration_(max_control_acceleration),\n      control_angle_speed_gain_(control_angle_speed_gain),\n      max_control_angle_speed_(max_control_angle_speed) {\n    // Initialize the state to zeros, this is compensated for with a high\n    // initial state covariance (P), see below\n    // \\todo Read initial state vector from a parameter\n    x.setZero();\n\n    // Set the initial state covariance to a constant matrix\n    // \\todo Read the initial state covariance matrix from a parameter\n    P.setIdentity();\n    P *= 1e1;\n\n    // Set the process noise covariance to a constant matrix\n    // \\todo Read the process noise covariance matrix from a parameter\n    Q.setZero();\n    Q(State::X, State::X) = 1e-3;\n    Q(State::Y, State::Y) = 1e-3;\n    Q(State::Z, State::Z) = 1e-4;\n    Q(State::speed, State::speed) = 1e-0;\n    Q(State::accel, State::accel) = 1e+1;\n    Q(State::Roll, State::Roll) = 1e-4;\n    Q(State::Pitch, State::Pitch) = 1e-4;\n    Q(State::Yaw, State::Yaw) = 1e-3;\n    Q(State::droll_dx, State::droll_dx) = 1e-6;\n    Q(State::dpitch_dx, State::dpitch_dx) = 1e-6;\n    Q(State::dyaw_dx, State::dyaw_dx) = 1e+0;\n}\n\nvoid AckermannEkf::process_measurement(const Measurement &measurement) {\n    bring_time_forward_to(measurement.time);\n\n    correct(measurement);\n}\n\nvoid AckermannEkf::process_control_signal(const ControlSignal &control_signal) {\n    bring_time_forward_to(control_signal.time);\n\n    // Enable control signals for prediction step as soon as one is recieved\n    control_signal_enabled_ = true;\n    control_signal_ = control_signal;\n}\n\nvoid AckermannEkf::bring_time_forward_to(double time) {\n    if (time > this->time) {\n        // Only predict if the filter time has been initialized, otherwise dt\n        // may be VERY large\n        if (this->time >= 0) {\n            predict(time - this->time);\n        }\n        this->time = time;\n    }\n}\n\nvoid AckermannEkf::predict(double dt) {\n    if (control_signal_enabled_) {\n        // Accelration is linear gain on velocity error\n        x(State::accel) = boost::algorithm::clamp(\n            (control_signal_.u(ControlSignal::speed) - x(State::speed)) *\n                control_acceleration_gain_,\n            -max_control_acceleration_, max_control_acceleration_);\n\n        double steering_angle = atan(wheelbase_ * x(State::dyaw_dx));\n        // Add (steering angle speed) * dt to steering angle, where steering\n        // angle speed is linear gain on steering angle error\n        steering_angle +=\n            boost::algorithm::clamp(\n                (control_signal_.u(ControlSignal::angle) - steering_angle) *\n                    control_angle_speed_gain_,\n                -max_control_angle_speed_, max_control_angle_speed_) *\n            dt;\n        steering_angle = boost::algorithm::clamp(steering_angle, -M_PI * 0.499,\n                                                 M_PI * 0.499);\n\n        x(State::dyaw_dx) = tan(steering_angle) / wheelbase_;\n\n        constrain_state();\n    }\n\n    Eigen::VectorXd f(STATE_SIZE);\n    Eigen::MatrixXd F(STATE_SIZE, STATE_SIZE);\n    f.setZero();\n    F.setZero();\n\n    // clang-format off\n\n    // The code here has been autogenerated by matlab and manually pasted in.\n    // Do not edit directly!\n\n    f(State::X) = x(State::X)-((dt*dt)*(x(State::speed)*(x(State::dpitch_dx)*x(State::speed)*(sin(x(State::Roll))*sin(x(State::Yaw))+cos(x(State::Roll))*cos(x(State::Yaw))*sin(x(State::Pitch)))+x(State::dyaw_dx)*x(State::speed)*(cos(x(State::Roll))*sin(x(State::Yaw))-cos(x(State::Yaw))*sin(x(State::Pitch))*sin(x(State::Roll))))-x(State::accel)*cos(x(State::Pitch))*cos(x(State::Yaw))))/2.0+dt*x(State::speed)*cos(x(State::Pitch))*cos(x(State::Yaw));\n    f(State::Y) = x(State::Y)+((dt*dt)*(x(State::speed)*(x(State::dpitch_dx)*x(State::speed)*(cos(x(State::Yaw))*sin(x(State::Roll))-cos(x(State::Roll))*sin(x(State::Pitch))*sin(x(State::Yaw)))+x(State::dyaw_dx)*x(State::speed)*(cos(x(State::Roll))*cos(x(State::Yaw))+sin(x(State::Pitch))*sin(x(State::Roll))*sin(x(State::Yaw))))+x(State::accel)*cos(x(State::Pitch))*sin(x(State::Yaw))))/2.0+dt*x(State::speed)*cos(x(State::Pitch))*sin(x(State::Yaw));\n    f(State::Z) = x(State::Z)-((dt*dt)*(x(State::speed)*(x(State::dpitch_dx)*x(State::speed)*cos(x(State::Pitch))*cos(x(State::Roll))-x(State::dyaw_dx)*x(State::speed)*cos(x(State::Pitch))*sin(x(State::Roll)))+x(State::accel)*sin(x(State::Pitch))))/2.0-dt*x(State::speed)*sin(x(State::Pitch));\n    f(State::speed) = x(State::speed)+x(State::accel)*dt;\n    f(State::accel) = x(State::accel);\n    f(State::Roll) = (x(State::Roll)*cos(x(State::Pitch))+x(State::droll_dx)*dt*x(State::speed)*cos(x(State::Pitch))+dt*x(State::dyaw_dx)*x(State::speed)*cos(x(State::Roll))*sin(x(State::Pitch))+x(State::dpitch_dx)*dt*x(State::speed)*sin(x(State::Pitch))*sin(x(State::Roll)))/cos(x(State::Pitch));\n    f(State::Pitch) = x(State::Pitch)+dt*x(State::speed)*(x(State::dpitch_dx)*cos(x(State::Roll))-x(State::dyaw_dx)*sin(x(State::Roll)));\n    f(State::Yaw) = (x(State::Yaw)*cos(x(State::Pitch))+dt*x(State::dyaw_dx)*x(State::speed)*cos(x(State::Roll))+x(State::dpitch_dx)*dt*x(State::speed)*sin(x(State::Roll)))/cos(x(State::Pitch));\n    f(State::droll_dx) = x(State::droll_dx);\n    f(State::dpitch_dx) = x(State::dpitch_dx);\n    f(State::dyaw_dx) = x(State::dyaw_dx);\n\n    F(State::X, State::X) = 1.0;\n    F(State::X, State::speed) = -dt*(-cos(x(State::Pitch))*cos(x(State::Yaw))+dt*x(State::dyaw_dx)*x(State::speed)*cos(x(State::Roll))*sin(x(State::Yaw))+x(State::dpitch_dx)*dt*x(State::speed)*sin(x(State::Roll))*sin(x(State::Yaw))+x(State::dpitch_dx)*dt*x(State::speed)*cos(x(State::Roll))*cos(x(State::Yaw))*sin(x(State::Pitch))-dt*x(State::dyaw_dx)*x(State::speed)*cos(x(State::Yaw))*sin(x(State::Pitch))*sin(x(State::Roll)));\n    F(State::X, State::accel) = ((dt*dt)*cos(x(State::Pitch))*cos(x(State::Yaw)))/2.0;\n    F(State::X, State::Roll) = (dt*dt)*x(State::speed)*(x(State::dpitch_dx)*x(State::speed)*(cos(x(State::Roll))*sin(x(State::Yaw))-cos(x(State::Yaw))*sin(x(State::Pitch))*sin(x(State::Roll)))-x(State::dyaw_dx)*x(State::speed)*(sin(x(State::Roll))*sin(x(State::Yaw))+cos(x(State::Roll))*cos(x(State::Yaw))*sin(x(State::Pitch))))*(-1.0/2.0);\n    F(State::X, State::Pitch) = dt*cos(x(State::Yaw))*(x(State::speed)*sin(x(State::Pitch))*2.0+x(State::accel)*dt*sin(x(State::Pitch))+x(State::dpitch_dx)*dt*(x(State::speed)*x(State::speed))*cos(x(State::Pitch))*cos(x(State::Roll))-dt*x(State::dyaw_dx)*(x(State::speed)*x(State::speed))*cos(x(State::Pitch))*sin(x(State::Roll)))*(-1.0/2.0);\n    F(State::X, State::Yaw) = (dt*dt)*(x(State::speed)*(x(State::dpitch_dx)*x(State::speed)*(cos(x(State::Yaw))*sin(x(State::Roll))-cos(x(State::Roll))*sin(x(State::Pitch))*sin(x(State::Yaw)))+x(State::dyaw_dx)*x(State::speed)*(cos(x(State::Roll))*cos(x(State::Yaw))+sin(x(State::Pitch))*sin(x(State::Roll))*sin(x(State::Yaw))))+x(State::accel)*cos(x(State::Pitch))*sin(x(State::Yaw)))*(-1.0/2.0)-dt*x(State::speed)*cos(x(State::Pitch))*sin(x(State::Yaw));\n    F(State::X, State::dpitch_dx) = (dt*dt)*(x(State::speed)*x(State::speed))*(sin(x(State::Roll))*sin(x(State::Yaw))+cos(x(State::Roll))*cos(x(State::Yaw))*sin(x(State::Pitch)))*(-1.0/2.0);\n    F(State::X, State::dyaw_dx) = (dt*dt)*(x(State::speed)*x(State::speed))*(cos(x(State::Roll))*sin(x(State::Yaw))-cos(x(State::Yaw))*sin(x(State::Pitch))*sin(x(State::Roll)))*(-1.0/2.0);\n    F(State::Y, State::Y) = 1.0;\n    F(State::Y, State::speed) = dt*(cos(x(State::Pitch))*sin(x(State::Yaw))+dt*x(State::dyaw_dx)*x(State::speed)*cos(x(State::Roll))*cos(x(State::Yaw))+x(State::dpitch_dx)*dt*x(State::speed)*cos(x(State::Yaw))*sin(x(State::Roll))-x(State::dpitch_dx)*dt*x(State::speed)*cos(x(State::Roll))*sin(x(State::Pitch))*sin(x(State::Yaw))+dt*x(State::dyaw_dx)*x(State::speed)*sin(x(State::Pitch))*sin(x(State::Roll))*sin(x(State::Yaw)));\n    F(State::Y, State::accel) = ((dt*dt)*cos(x(State::Pitch))*sin(x(State::Yaw)))/2.0;\n    F(State::Y, State::Roll) = ((dt*dt)*x(State::speed)*(x(State::dpitch_dx)*x(State::speed)*(cos(x(State::Roll))*cos(x(State::Yaw))+sin(x(State::Pitch))*sin(x(State::Roll))*sin(x(State::Yaw)))-x(State::dyaw_dx)*x(State::speed)*(cos(x(State::Yaw))*sin(x(State::Roll))-cos(x(State::Roll))*sin(x(State::Pitch))*sin(x(State::Yaw)))))/2.0;\n    F(State::Y, State::Pitch) = dt*sin(x(State::Yaw))*(x(State::speed)*sin(x(State::Pitch))*2.0+x(State::accel)*dt*sin(x(State::Pitch))+x(State::dpitch_dx)*dt*(x(State::speed)*x(State::speed))*cos(x(State::Pitch))*cos(x(State::Roll))-dt*x(State::dyaw_dx)*(x(State::speed)*x(State::speed))*cos(x(State::Pitch))*sin(x(State::Roll)))*(-1.0/2.0);\n    F(State::Y, State::Yaw) = (dt*dt)*(x(State::speed)*(x(State::dpitch_dx)*x(State::speed)*(sin(x(State::Roll))*sin(x(State::Yaw))+cos(x(State::Roll))*cos(x(State::Yaw))*sin(x(State::Pitch)))+x(State::dyaw_dx)*x(State::speed)*(cos(x(State::Roll))*sin(x(State::Yaw))-cos(x(State::Yaw))*sin(x(State::Pitch))*sin(x(State::Roll))))-x(State::accel)*cos(x(State::Pitch))*cos(x(State::Yaw)))*(-1.0/2.0)+dt*x(State::speed)*cos(x(State::Pitch))*cos(x(State::Yaw));\n    F(State::Y, State::dpitch_dx) = ((dt*dt)*(x(State::speed)*x(State::speed))*(cos(x(State::Yaw))*sin(x(State::Roll))-cos(x(State::Roll))*sin(x(State::Pitch))*sin(x(State::Yaw))))/2.0;\n    F(State::Y, State::dyaw_dx) = ((dt*dt)*(x(State::speed)*x(State::speed))*(cos(x(State::Roll))*cos(x(State::Yaw))+sin(x(State::Pitch))*sin(x(State::Roll))*sin(x(State::Yaw))))/2.0;\n    F(State::Z, State::Z) = 1.0;\n    F(State::Z, State::speed) = -dt*(sin(x(State::Pitch))+x(State::dpitch_dx)*dt*x(State::speed)*cos(x(State::Pitch))*cos(x(State::Roll))-dt*x(State::dyaw_dx)*x(State::speed)*cos(x(State::Pitch))*sin(x(State::Roll)));\n    F(State::Z, State::accel) = (dt*dt)*sin(x(State::Pitch))*(-1.0/2.0);\n    F(State::Z, State::Roll) = ((dt*dt)*(x(State::speed)*x(State::speed))*cos(x(State::Pitch))*(x(State::dyaw_dx)*cos(x(State::Roll))+x(State::dpitch_dx)*sin(x(State::Roll))))/2.0;\n    F(State::Z, State::Pitch) = (dt*dt)*(x(State::accel)*cos(x(State::Pitch))-x(State::speed)*(x(State::dpitch_dx)*x(State::speed)*cos(x(State::Roll))*sin(x(State::Pitch))-x(State::dyaw_dx)*x(State::speed)*sin(x(State::Pitch))*sin(x(State::Roll))))*(-1.0/2.0)-dt*x(State::speed)*cos(x(State::Pitch));\n    F(State::Z, State::dpitch_dx) = (dt*dt)*(x(State::speed)*x(State::speed))*cos(x(State::Pitch))*cos(x(State::Roll))*(-1.0/2.0);\n    F(State::Z, State::dyaw_dx) = ((dt*dt)*(x(State::speed)*x(State::speed))*cos(x(State::Pitch))*sin(x(State::Roll)))/2.0;\n    F(State::speed, State::speed) = 1.0;\n    F(State::speed, State::accel) = dt;\n    F(State::accel, State::accel) = 1.0;\n    F(State::Roll, State::speed) = (dt*(x(State::droll_dx)*cos(x(State::Pitch))+x(State::dyaw_dx)*cos(x(State::Roll))*sin(x(State::Pitch))+x(State::dpitch_dx)*sin(x(State::Pitch))*sin(x(State::Roll))))/cos(x(State::Pitch));\n    F(State::Roll, State::Roll) = (cos(x(State::Pitch))+x(State::dpitch_dx)*dt*x(State::speed)*cos(x(State::Roll))*sin(x(State::Pitch))-dt*x(State::dyaw_dx)*x(State::speed)*sin(x(State::Pitch))*sin(x(State::Roll)))/cos(x(State::Pitch));\n    F(State::Roll, State::Pitch) = dt*x(State::speed)*1.0/pow(cos(x(State::Pitch)),2.0)*(x(State::dyaw_dx)*cos(x(State::Roll))+x(State::dpitch_dx)*sin(x(State::Roll)));\n    F(State::Roll, State::droll_dx) = dt*x(State::speed);\n    F(State::Roll, State::dpitch_dx) = (dt*x(State::speed)*sin(x(State::Pitch))*sin(x(State::Roll)))/cos(x(State::Pitch));\n    F(State::Roll, State::dyaw_dx) = (dt*x(State::speed)*cos(x(State::Roll))*sin(x(State::Pitch)))/cos(x(State::Pitch));\n    F(State::Pitch, State::speed) = dt*(x(State::dpitch_dx)*cos(x(State::Roll))-x(State::dyaw_dx)*sin(x(State::Roll)));\n    F(State::Pitch, State::Roll) = -dt*x(State::speed)*(x(State::dyaw_dx)*cos(x(State::Roll))+x(State::dpitch_dx)*sin(x(State::Roll)));\n    F(State::Pitch, State::Pitch) = 1.0;\n    F(State::Pitch, State::dpitch_dx) = dt*x(State::speed)*cos(x(State::Roll));\n    F(State::Pitch, State::dyaw_dx) = -dt*x(State::speed)*sin(x(State::Roll));\n    F(State::Yaw, State::speed) = (dt*(x(State::dyaw_dx)*cos(x(State::Roll))+x(State::dpitch_dx)*sin(x(State::Roll))))/cos(x(State::Pitch));\n    F(State::Yaw, State::Roll) = (dt*x(State::speed)*(x(State::dpitch_dx)*cos(x(State::Roll))-x(State::dyaw_dx)*sin(x(State::Roll))))/cos(x(State::Pitch));\n    F(State::Yaw, State::Pitch) = dt*x(State::speed)*1.0/pow(cos(x(State::Pitch)),2.0)*sin(x(State::Pitch))*(x(State::dyaw_dx)*cos(x(State::Roll))+x(State::dpitch_dx)*sin(x(State::Roll)));\n    F(State::Yaw, State::Yaw) = 1.0;\n    F(State::Yaw, State::dpitch_dx) = (dt*x(State::speed)*sin(x(State::Roll)))/cos(x(State::Pitch));\n    F(State::Yaw, State::dyaw_dx) = (dt*x(State::speed)*cos(x(State::Roll)))/cos(x(State::Pitch));\n    F(State::droll_dx, State::droll_dx) = 1.0;\n    F(State::dpitch_dx, State::dpitch_dx) = 1.0;\n    F(State::dyaw_dx, State::dyaw_dx) = 1.0;\n\n    // clang-format on\n\n    // Kalman prediction equations according to wikipeadia on EKF\n    x = f;\n    constrain_state();\n    P = F * P * F.transpose() + dt * Q;\n}\n\nvoid AckermannEkf::correct(const Measurement &measurement) {\n    Eigen::VectorXd h(MEASUREMENT_SIZE);\n    Eigen::MatrixXd H(MEASUREMENT_SIZE, STATE_SIZE);\n    h.setZero();\n    H.setZero();\n\n    // clang-format off\n\n    // The code here has been autogenerated by matlab and manually pasted in.\n    // Do not edit directly!\n\n    h(Measurement::X) = x(State::X)-measurement.sensor_position(1)*(cos(x(State::Roll))*sin(x(State::Yaw))-cos(x(State::Yaw))*sin(x(State::Pitch))*sin(x(State::Roll)))+measurement.sensor_position(2)*(sin(x(State::Roll))*sin(x(State::Yaw))+cos(x(State::Roll))*cos(x(State::Yaw))*sin(x(State::Pitch)))+measurement.sensor_position(0)*cos(x(State::Pitch))*cos(x(State::Yaw));\n    h(Measurement::Y) = x(State::Y)+measurement.sensor_position(1)*(cos(x(State::Roll))*cos(x(State::Yaw))+sin(x(State::Pitch))*sin(x(State::Roll))*sin(x(State::Yaw)))-measurement.sensor_position(2)*(cos(x(State::Yaw))*sin(x(State::Roll))-cos(x(State::Roll))*sin(x(State::Pitch))*sin(x(State::Yaw)))+measurement.sensor_position(0)*cos(x(State::Pitch))*sin(x(State::Yaw));\n    h(Measurement::Z) = x(State::Z)-measurement.sensor_position(0)*sin(x(State::Pitch))+measurement.sensor_position(2)*cos(x(State::Pitch))*cos(x(State::Roll))+measurement.sensor_position(1)*cos(x(State::Pitch))*sin(x(State::Roll));\n    h(Measurement::dx_dt) = x(State::speed)*(x(State::dpitch_dx)*measurement.sensor_position(2)-x(State::dyaw_dx)*measurement.sensor_position(1)+1.0);\n    h(Measurement::dy_dt) = -x(State::speed)*(x(State::droll_dx)*measurement.sensor_position(2)-x(State::dyaw_dx)*measurement.sensor_position(0));\n    h(Measurement::dz_dt) = -x(State::speed)*(x(State::dpitch_dx)*measurement.sensor_position(0)-x(State::droll_dx)*measurement.sensor_position(1));\n    h(Measurement::d2x_dt2) = x(State::accel)-measurement.gravity*sin(x(State::Pitch))+x(State::accel)*x(State::dpitch_dx)*measurement.sensor_position(2)-x(State::accel)*x(State::dyaw_dx)*measurement.sensor_position(1)-x(State::dpitch_dx)*x(State::speed)*(x(State::dpitch_dx)*measurement.sensor_position(0)*x(State::speed)-x(State::droll_dx)*measurement.sensor_position(1)*x(State::speed))+x(State::dyaw_dx)*x(State::speed)*(x(State::droll_dx)*measurement.sensor_position(2)*x(State::speed)-x(State::dyaw_dx)*measurement.sensor_position(0)*x(State::speed));\n    h(Measurement::d2y_dt2) = x(State::dyaw_dx)*(x(State::speed)*x(State::speed))+measurement.gravity*cos(x(State::Pitch))*sin(x(State::Roll))-x(State::accel)*x(State::droll_dx)*measurement.sensor_position(2)+x(State::accel)*x(State::dyaw_dx)*measurement.sensor_position(0)+x(State::droll_dx)*x(State::speed)*(x(State::dpitch_dx)*measurement.sensor_position(0)*x(State::speed)-x(State::droll_dx)*measurement.sensor_position(1)*x(State::speed))+x(State::dyaw_dx)*x(State::speed)*(x(State::dpitch_dx)*measurement.sensor_position(2)*x(State::speed)-x(State::dyaw_dx)*measurement.sensor_position(1)*x(State::speed));\n    h(Measurement::d2z_dt2) = -x(State::dpitch_dx)*(x(State::speed)*x(State::speed))+measurement.gravity*cos(x(State::Pitch))*cos(x(State::Roll))-x(State::accel)*x(State::dpitch_dx)*measurement.sensor_position(0)+x(State::accel)*x(State::droll_dx)*measurement.sensor_position(1)-x(State::dpitch_dx)*x(State::speed)*(x(State::dpitch_dx)*measurement.sensor_position(2)*x(State::speed)-x(State::dyaw_dx)*measurement.sensor_position(1)*x(State::speed))-x(State::droll_dx)*x(State::speed)*(x(State::droll_dx)*measurement.sensor_position(2)*x(State::speed)-x(State::dyaw_dx)*measurement.sensor_position(0)*x(State::speed));\n    h(Measurement::Roll) = x(State::Roll);\n    h(Measurement::Pitch) = x(State::Pitch);\n    h(Measurement::Yaw) = x(State::Yaw);\n    h(Measurement::droll_dt) = x(State::droll_dx)*x(State::speed);\n    h(Measurement::dpitch_dt) = x(State::dpitch_dx)*x(State::speed);\n    h(Measurement::dyaw_dt) = x(State::dyaw_dx)*x(State::speed);\n\n    H(Measurement::X, State::X) = 1.0;\n    H(Measurement::X, State::Roll) = measurement.sensor_position(1)*(sin(x(State::Roll))*sin(x(State::Yaw))+cos(x(State::Roll))*cos(x(State::Yaw))*sin(x(State::Pitch)))+measurement.sensor_position(2)*(cos(x(State::Roll))*sin(x(State::Yaw))-cos(x(State::Yaw))*sin(x(State::Pitch))*sin(x(State::Roll)));\n    H(Measurement::X, State::Pitch) = cos(x(State::Yaw))*(-measurement.sensor_position(0)*sin(x(State::Pitch))+measurement.sensor_position(2)*cos(x(State::Pitch))*cos(x(State::Roll))+measurement.sensor_position(1)*cos(x(State::Pitch))*sin(x(State::Roll)));\n    H(Measurement::X, State::Yaw) = -measurement.sensor_position(1)*(cos(x(State::Roll))*cos(x(State::Yaw))+sin(x(State::Pitch))*sin(x(State::Roll))*sin(x(State::Yaw)))+measurement.sensor_position(2)*(cos(x(State::Yaw))*sin(x(State::Roll))-cos(x(State::Roll))*sin(x(State::Pitch))*sin(x(State::Yaw)))-measurement.sensor_position(0)*cos(x(State::Pitch))*sin(x(State::Yaw));\n    H(Measurement::Y, State::Y) = 1.0;\n    H(Measurement::Y, State::Roll) = -measurement.sensor_position(1)*(cos(x(State::Yaw))*sin(x(State::Roll))-cos(x(State::Roll))*sin(x(State::Pitch))*sin(x(State::Yaw)))-measurement.sensor_position(2)*(cos(x(State::Roll))*cos(x(State::Yaw))+sin(x(State::Pitch))*sin(x(State::Roll))*sin(x(State::Yaw)));\n    H(Measurement::Y, State::Pitch) = sin(x(State::Yaw))*(-measurement.sensor_position(0)*sin(x(State::Pitch))+measurement.sensor_position(2)*cos(x(State::Pitch))*cos(x(State::Roll))+measurement.sensor_position(1)*cos(x(State::Pitch))*sin(x(State::Roll)));\n    H(Measurement::Y, State::Yaw) = -measurement.sensor_position(1)*(cos(x(State::Roll))*sin(x(State::Yaw))-cos(x(State::Yaw))*sin(x(State::Pitch))*sin(x(State::Roll)))+measurement.sensor_position(2)*(sin(x(State::Roll))*sin(x(State::Yaw))+cos(x(State::Roll))*cos(x(State::Yaw))*sin(x(State::Pitch)))+measurement.sensor_position(0)*cos(x(State::Pitch))*cos(x(State::Yaw));\n    H(Measurement::Z, State::Z) = 1.0;\n    H(Measurement::Z, State::Roll) = cos(x(State::Pitch))*(measurement.sensor_position(1)*cos(x(State::Roll))-measurement.sensor_position(2)*sin(x(State::Roll)));\n    H(Measurement::Z, State::Pitch) = -measurement.sensor_position(0)*cos(x(State::Pitch))-measurement.sensor_position(2)*cos(x(State::Roll))*sin(x(State::Pitch))-measurement.sensor_position(1)*sin(x(State::Pitch))*sin(x(State::Roll));\n    H(Measurement::dx_dt, State::speed) = x(State::dpitch_dx)*measurement.sensor_position(2)-x(State::dyaw_dx)*measurement.sensor_position(1)+1.0;\n    H(Measurement::dx_dt, State::dpitch_dx) = measurement.sensor_position(2)*x(State::speed);\n    H(Measurement::dx_dt, State::dyaw_dx) = -measurement.sensor_position(1)*x(State::speed);\n    H(Measurement::dy_dt, State::speed) = -x(State::droll_dx)*measurement.sensor_position(2)+x(State::dyaw_dx)*measurement.sensor_position(0);\n    H(Measurement::dy_dt, State::droll_dx) = -measurement.sensor_position(2)*x(State::speed);\n    H(Measurement::dy_dt, State::dyaw_dx) = measurement.sensor_position(0)*x(State::speed);\n    H(Measurement::dz_dt, State::speed) = -x(State::dpitch_dx)*measurement.sensor_position(0)+x(State::droll_dx)*measurement.sensor_position(1);\n    H(Measurement::dz_dt, State::droll_dx) = measurement.sensor_position(1)*x(State::speed);\n    H(Measurement::dz_dt, State::dpitch_dx) = -measurement.sensor_position(0)*x(State::speed);\n    H(Measurement::d2x_dt2, State::speed) = x(State::speed)*((x(State::dpitch_dx)*x(State::dpitch_dx))*measurement.sensor_position(0)+(x(State::dyaw_dx)*x(State::dyaw_dx))*measurement.sensor_position(0)-x(State::dpitch_dx)*x(State::droll_dx)*measurement.sensor_position(1)-x(State::droll_dx)*x(State::dyaw_dx)*measurement.sensor_position(2))*-2.0;\n    H(Measurement::d2x_dt2, State::accel) = x(State::dpitch_dx)*measurement.sensor_position(2)-x(State::dyaw_dx)*measurement.sensor_position(1)+1.0;\n    H(Measurement::d2x_dt2, State::Pitch) = -measurement.gravity*cos(x(State::Pitch));\n    H(Measurement::d2x_dt2, State::droll_dx) = (x(State::speed)*x(State::speed))*(x(State::dpitch_dx)*measurement.sensor_position(1)+x(State::dyaw_dx)*measurement.sensor_position(2));\n    H(Measurement::d2x_dt2, State::dpitch_dx) = x(State::accel)*measurement.sensor_position(2)-x(State::dpitch_dx)*measurement.sensor_position(0)*(x(State::speed)*x(State::speed))*2.0+x(State::droll_dx)*measurement.sensor_position(1)*(x(State::speed)*x(State::speed));\n    H(Measurement::d2x_dt2, State::dyaw_dx) = -x(State::accel)*measurement.sensor_position(1)+x(State::droll_dx)*measurement.sensor_position(2)*(x(State::speed)*x(State::speed))-x(State::dyaw_dx)*measurement.sensor_position(0)*(x(State::speed)*x(State::speed))*2.0;\n    H(Measurement::d2y_dt2, State::speed) = x(State::speed)*(x(State::dyaw_dx)-(x(State::droll_dx)*x(State::droll_dx))*measurement.sensor_position(1)-(x(State::dyaw_dx)*x(State::dyaw_dx))*measurement.sensor_position(1)+x(State::dpitch_dx)*x(State::droll_dx)*measurement.sensor_position(0)+x(State::dpitch_dx)*x(State::dyaw_dx)*measurement.sensor_position(2))*2.0;\n    H(Measurement::d2y_dt2, State::accel) = -x(State::droll_dx)*measurement.sensor_position(2)+x(State::dyaw_dx)*measurement.sensor_position(0);\n    H(Measurement::d2y_dt2, State::Roll) = measurement.gravity*cos(x(State::Pitch))*cos(x(State::Roll));\n    H(Measurement::d2y_dt2, State::Pitch) = -measurement.gravity*sin(x(State::Pitch))*sin(x(State::Roll));\n    H(Measurement::d2y_dt2, State::droll_dx) = -x(State::accel)*measurement.sensor_position(2)+x(State::dpitch_dx)*measurement.sensor_position(0)*(x(State::speed)*x(State::speed))-x(State::droll_dx)*measurement.sensor_position(1)*(x(State::speed)*x(State::speed))*2.0;\n    H(Measurement::d2y_dt2, State::dpitch_dx) = (x(State::speed)*x(State::speed))*(x(State::droll_dx)*measurement.sensor_position(0)+x(State::dyaw_dx)*measurement.sensor_position(2));\n    H(Measurement::d2y_dt2, State::dyaw_dx) = x(State::accel)*measurement.sensor_position(0)+x(State::speed)*x(State::speed)+x(State::dpitch_dx)*measurement.sensor_position(2)*(x(State::speed)*x(State::speed))-x(State::dyaw_dx)*measurement.sensor_position(1)*(x(State::speed)*x(State::speed))*2.0;\n    H(Measurement::d2z_dt2, State::speed) = x(State::speed)*(x(State::dpitch_dx)+(x(State::dpitch_dx)*x(State::dpitch_dx))*measurement.sensor_position(2)+(x(State::droll_dx)*x(State::droll_dx))*measurement.sensor_position(2)-x(State::dpitch_dx)*x(State::dyaw_dx)*measurement.sensor_position(1)-x(State::droll_dx)*x(State::dyaw_dx)*measurement.sensor_position(0))*-2.0;\n    H(Measurement::d2z_dt2, State::accel) = -x(State::dpitch_dx)*measurement.sensor_position(0)+x(State::droll_dx)*measurement.sensor_position(1);\n    H(Measurement::d2z_dt2, State::Roll) = -measurement.gravity*cos(x(State::Pitch))*sin(x(State::Roll));\n    H(Measurement::d2z_dt2, State::Pitch) = -measurement.gravity*cos(x(State::Roll))*sin(x(State::Pitch));\n    H(Measurement::d2z_dt2, State::droll_dx) = x(State::accel)*measurement.sensor_position(1)-x(State::droll_dx)*measurement.sensor_position(2)*(x(State::speed)*x(State::speed))*2.0+x(State::dyaw_dx)*measurement.sensor_position(0)*(x(State::speed)*x(State::speed));\n    H(Measurement::d2z_dt2, State::dpitch_dx) = -x(State::accel)*measurement.sensor_position(0)-x(State::speed)*x(State::speed)-x(State::dpitch_dx)*measurement.sensor_position(2)*(x(State::speed)*x(State::speed))*2.0+x(State::dyaw_dx)*measurement.sensor_position(1)*(x(State::speed)*x(State::speed));\n    H(Measurement::d2z_dt2, State::dyaw_dx) = (x(State::speed)*x(State::speed))*(x(State::dpitch_dx)*measurement.sensor_position(1)+x(State::droll_dx)*measurement.sensor_position(0));\n    H(Measurement::Roll, State::Roll) = 1.0;\n    H(Measurement::Pitch, State::Pitch) = 1.0;\n    H(Measurement::Yaw, State::Yaw) = 1.0;\n    H(Measurement::droll_dt, State::speed) = x(State::droll_dx);\n    H(Measurement::droll_dt, State::droll_dx) = x(State::speed);\n    H(Measurement::dpitch_dt, State::speed) = x(State::dpitch_dx);\n    H(Measurement::dpitch_dt, State::dpitch_dx) = x(State::speed);\n    H(Measurement::dyaw_dt, State::speed) = x(State::dyaw_dx);\n    H(Measurement::dyaw_dt, State::dyaw_dx) = x(State::speed);\n\n    // clang-format on\n\n    // Find the indicies of values to include in correction step\n    std::vector<int> measurement_indices;\n    for (int i = 0; i < MEASUREMENT_SIZE; i++) {\n        if (measurement.mask[i]) {\n            measurement_indices.push_back(i);\n        }\n    }\n\n    // Create subsets of z, R, h and H from the indicies of given by the\n    // measurement mask. There is no need to work with e.g. the full h vector\n    // if only two out of MEASUREMENT_SIZE components are actually used\n    // By creating this subset we e.g. in this example only have to invert a 2x2\n    // matrix as opposed to a MEASUREMENT_SIZExMEASUREMENT_SIZE one\n    Eigen::MatrixXd R(measurement_indices.size(), measurement_indices.size());\n    Eigen::VectorXd y(measurement_indices.size());\n    Eigen::MatrixXd H_subset(measurement_indices.size(), STATE_SIZE);\n    for (int i_ = 0; i_ < measurement_indices.size(); i_++) {\n        int i = measurement_indices[i_];\n\n        // Subset h and z (and y)\n        y(i_) = measurement.z(i) - h(i);\n\n        // Wrap Yaw error (a == 2*pi*n + a)\n        if (i_ == Measurement::Yaw) {\n            y(i_) -= round(y(i_) / (2 * M_PI)) * 2 * M_PI;\n        }\n\n        // Subset R\n        for (int j_ = 0; j_ < measurement_indices.size(); j_++) {\n            int j = measurement_indices[j_];\n\n            R(i_, j_) = measurement.R(i, j);\n        }\n\n        // Subset H\n        for (int j = 0; j < STATE_SIZE; j++) { H_subset(i_, j) = H(i, j); }\n    }\n\n    // Kalman correction equations according to wikipeadia on EKF\n    Eigen::MatrixXd K = P * H_subset.transpose() *\n                        (H_subset * P * H_subset.transpose() + R).inverse();\n    x.noalias() += K * y;\n    constrain_state();\n    P = (Eigen::MatrixXd::Identity(STATE_SIZE, STATE_SIZE) - K * H_subset) * P;\n}\n\nvoid AckermannEkf::constrain_state() {\n    x.noalias() = x.cwiseMax(x_min_).cwiseMin(x_max_);\n}\n\n} // namespace ackermann_ekf", "meta": {"hexsha": "4728e251ba9c2b5eb2cf9393d442cc5f9d9bc860", "size": 27697, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ackermann_ekf/src/ackermann_ekf.cpp", "max_stars_repo_name": "OssianEriksson/autonomous-twizy", "max_stars_repo_head_hexsha": "d78e352c37dd4b2dcdd588b89e2bedb665e7175e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T21:49:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T20:23:16.000Z", "max_issues_repo_path": "ackermann_ekf/src/ackermann_ekf.cpp", "max_issues_repo_name": "OssianEriksson/autonomous-twizy", "max_issues_repo_head_hexsha": "d78e352c37dd4b2dcdd588b89e2bedb665e7175e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-04T20:25:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-04T20:31:07.000Z", "max_forks_repo_path": "ackermann_ekf/src/ackermann_ekf.cpp", "max_forks_repo_name": "OssianEriksson/autonomous-twizy", "max_forks_repo_head_hexsha": "d78e352c37dd4b2dcdd588b89e2bedb665e7175e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 90.2182410423, "max_line_length": 617, "alphanum_fraction": 0.6674008015, "num_tokens": 8241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339516289534, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.4264268634752421}}
{"text": "/*====================================================================\n * Simple pendulum example\n * Copyright (c) 2015 Matthew Millard \n * <matthew.millard@iwr.uni-heidelberg.de>\n *\n *///=================================================================\n\n\n#include <string>\n#include <iostream>\n#include <iomanip>\n#include <stdio.h> \n#include <rbdl/rbdl.h>\n#include \"csvtools.h\"\n\n#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp>\n#include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n#include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>\n#include <boost/numeric/odeint/stepper/generation/make_controlled.hpp>\n//using namespace std;\nusing namespace boost::numeric::odeint;\n\n\n#ifndef RBDL_BUILD_ADDON_LUAMODEL\n    #error \"Error: RBDL addon LuaModel not enabled.\"\n#endif\n\n#include <rbdl/addons/luamodel/luamodel.h>\n#include <rbdl/addons/luamodel/luatables.h>\n\n\nusing namespace std;\nusing namespace RigidBodyDynamics;\nusing namespace RigidBodyDynamics::Math;\n\n\n//====================================================================\n// Boost stuff\n//====================================================================\n\ntypedef std::vector< double > state_type;\n\ntypedef runge_kutta_cash_karp54< state_type > error_stepper_type;\ntypedef controlled_runge_kutta< error_stepper_type > controlled_stepper_type;\n\n\nclass rbdlToBoost {\n    public:\n        rbdlToBoost(Model& model,std::vector<ConstraintSet>& cs\n                        ) : model(model),cs(cs) {\n            q = VectorNd::Zero(model.dof_count);\n            qd = VectorNd::Zero(model.dof_count);\n            qdd = VectorNd::Zero(model.dof_count);\n            tau = VectorNd::Zero(model.dof_count);\n\n        }\n\n        void operator() (const state_type &x, \n                         state_type &dxdt, \n                         const double t){\n\n            //q\n            int j = 0;\n            for(unsigned int i=0; i<model.dof_count; i++){\n                q[i] = (double)x[j];\n                j++;\n            }\n\n            //qd\n            for(unsigned int i=0; i<model.dof_count; i++){\n                qd[i] = (double)x[j];\n                j++;\n            }\n            //tau = for now. This could call a control\n            //               function.\n            for(unsigned int i=0; i<model.dof_count; i++){\n                tau[i] = 0;\n            }\n\n            //2c. A special forward dynamics function needs to be called in\n            //    order to compute qdd which simultaneously satisfies the \n            //    constraint set and the equations of motion.\n            ForwardDynamicsConstraintsDirect (model, q, qd, tau, cs[0], qdd);\n\n\n            //populate dxdt\n            j = 0;\n            for(unsigned int i = 0; i < model.dof_count; i++){\n                dxdt[j] = (double)qd[i];\n                j++;\n            }\n            for(unsigned int i = 0; i < model.dof_count; i++){\n                dxdt[j] = (double)qdd[i];\n                j++;\n            }\n\n        }\n\n    private:\n        Model& model;\n        std::vector< RigidBodyDynamics::ConstraintSet >& cs;\n        VectorNd q, qd, qdd, tau;\n};\n\nstruct pushBackStateAndTime\n{\n    std::vector< state_type >& states;\n    std::vector< double >& times;\n\n    pushBackStateAndTime( std::vector< state_type > &states , \n                              std::vector< double > &times )\n    : states( states ) , times( times ) { }\n\n    void operator()( const state_type &x , double t )\n    {\n        states.push_back( x );\n        times.push_back( t );\n    }\n};\n\nvoid f(const state_type &x, state_type &dxdt, const double t);\n\n/* Problem Constants */\nint main (int argc, char* argv[]) {\n    rbdl_check_api_version (RBDL_API_VERSION);\n\n\n    //problem specific constants\n    int     nPts    = 100;\n    double  t0      = 0;\n    double  t1      = 3;\n\n\n    //Integration settings\n    double absTolVal   = 1e-6;\n    double relTolVal   = 1e-6;\n\n    VectorNd q, qd, qdd, tau;\n\n    RigidBodyDynamics::Model model;\n    string modelFile = \"./../model/constrainedDoublePendulum.lua\";\n\n    //2a. Some extra work is needed to load in the model, and the \n    //    constraint sets\n    std::vector<std::string> constraintSetNames = \n        Addons::LuaModelGetConstraintSetNames(modelFile.c_str());\n    std::vector<RigidBodyDynamics::ConstraintSet> constraintSets;\n\n    constraintSets.resize(constraintSetNames.size());\n    \n    if (! Addons::LuaModelReadFromFileWithConstraints(\n                                      modelFile.c_str(),\n                                      &model,\n                                      constraintSets,\n                                      constraintSetNames,\n                                      false)            ){\n        std::cerr     << \"Error loading model\" << std::endl;\n        abort();\n    }\n\n\n    q       = VectorNd::Zero (model.dof_count);\n    qd      = VectorNd::Zero (model.dof_count);\n    qdd     = VectorNd::Zero (model.dof_count);\n    tau     = VectorNd::Zero (model.dof_count);\n\n    printf(\"DoF: %i\\n\",model.dof_count);\n\n\n    printf(\"==============================\\n\");\n    printf(\"1. Forward Dynamics \\n\");\n    printf(\"==============================\\n\");    \n\n    // rx0 x1,y1,z1,rx1,ry1,rz1\n    //  0,  1, 2, 3,  4,  5,  6,\n    q[2] = 1.0;\n\n    rbdlToBoost rbdlModel(model,constraintSets);\n    state_type xState(model.dof_count*2);\n\n    int j = 0;\n    for(unsigned int i = 0; i< (model.dof_count); ++i){\n        xState[j++] = q(i);\n    }\n    for(unsigned int i = 0; i< (model.dof_count); ++i){\n        xState[j++] = qd(i);\n    }\n\n    double dt   = (t1-t0)/((double)nPts);    \n\n\n    double ke, pe = 0;\n\n\n    std::vector<std::vector< double > > matrixData;\n    std::vector<std::vector< double > > matrixPlotData;\n    std::vector< double > rowData(model.dof_count+1);\n    std::vector< double > rowPlotData(4);\n\n    double a_x = 1.0 , a_dxdt = 1.0;\n    controlled_stepper_type  \n    controlled_stepper(\n        default_error_checker< double , \n                               range_algebra , \n                               default_operations >\n        ( absTolVal , relTolVal , a_x , a_dxdt ) );\n    \n\n    double tp = 0;\n    rowData[0] = 0;\n    for(unsigned int z=0; z < model.dof_count; z++){\n        rowData[z+1] = xState[model.dof_count + z];\n    }\n    matrixData.push_back(rowData);\n    double t = 0;\n\n    VectorNd constraintPosError = VectorNd::Zero(5);\n    VectorNd constraintVelError = VectorNd::Zero(5);\n\n    double constraintPosNorm, constraintVelNorm;\n\n    printf(\"Columns\\n\");\n    printf(\"      t,        ke,       pe,    ke+pe ,norm(cons_pos), norm(cons_vel)\\n\");\n    for(int i = 0; i <= nPts; i++){\n       \n\n        t = t0 + dt*i;\n\n\n        integrate_adaptive( \n            controlled_stepper ,\n            rbdlModel , xState , tp , t , (t-tp)/10000 );\n        tp = t;\n\n        j = 0;\n        for(unsigned int k = 0; k < model.dof_count; ++k){\n            q[k] = xState[j++];\n        }\n        for(unsigned int k = 0; k < model.dof_count; ++k){\n            qd[k] = xState[j++];\n        }\n\n        //Ensure that the constraint set quantites are up to date\n        ForwardDynamicsConstraintsDirect (model, q, qd, tau,\n          constraintSets[0], qdd);\n\n\n        //2d. The position-level and velocity level constraint set errors\n        //    can be fished out of the vectors in the ConstraintSet struct\n        //\n        //    Note: In the coming months there will be some functions added so that you\n        //          can easily access this information.\n        //\n        //    Homework: After reading Featherstone & Orin Sec. 3.4, go and have a look\n        //              at the fields in the ConstraintSet struct in \n        //              rbdl-orb/include/rbdl/Constraints.h\n        //\n        //              At the same time, open the doxygen for RBDL and read the sections\n        //              on Constraints and ConstraintSets        \n        ConstraintSet &ci = constraintSets[0];        \n        constraintPosNorm = 0;\n        constraintVelNorm = 0;\n        for(int k=0; k<5;++k){\n          constraintPosError(k) = ci.err(k);\n          constraintVelError(k) = ci.errd(k);\n\n          constraintPosNorm += ci.err(k)*ci.err(k);\n          constraintVelNorm += ci.errd(k)*ci.errd(k);\n        }\n        constraintPosNorm = sqrt(constraintPosNorm);\n        constraintVelNorm = sqrt(constraintVelNorm);\n\n        pe = Utils::CalcPotentialEnergy(model, q, true);\n        ke = Utils::CalcKineticEnergy(model, q, qd, true);\n\n\n        printf(\"%f, %f, %f, %f, %f, %f\\n\",\n                    t, ke,pe, ke+pe, constraintPosNorm, constraintVelNorm);\n\n        rowData[0] = t;\n        for(unsigned int z=0; z < model.dof_count; z++){\n            rowData[z+1] = xState[z];\n        }\n        matrixData.push_back(rowData);\n\n\n        rowPlotData[0] = t;\n        rowPlotData[1] = constraintPosNorm;\n        rowPlotData[2] = constraintVelNorm;\n        rowPlotData[3] =(ke+pe);\n\n        matrixPlotData.push_back(rowPlotData);\n    }\n    printf(\"Columns\\n\");\n    printf(\"      t,        ke,       pe,    ke+pe ,norm(cons_pos), norm(cons_vel)\\n\");\n\n\n    std::string header = \"\";\n    std::string fname   = \"../output/meshup.csv\";\n    printMatrixToFile(matrixData, header, fname);\n    printf(\"Wrote: ../output/meshup.csv (meshup animation file)\\n\");\n\n    fname   = \"../output/simulationData.csv\";\n    header = \"time,constraintPositionNorm,constraintVelocityNorm,systemEnergy,\";\n    printMatrixToFile(matrixPlotData, header, fname);\n    printf(\"Wrote: ../output/simulationData.csv (error data)\\n\");\n\n\n    return 0;\n        \n}\n\n", "meta": {"hexsha": "8eaab2458d684e1107747cdd33c542bf468319b5", "size": 9524, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/constrainedDoublePendulum/src/constrainedDoublePendulumForwardDynamics.cc", "max_stars_repo_name": "ju6ge/rbdl-orb", "max_stars_repo_head_hexsha": "321e20e80e2859a3a2ab43629c7c26c1020cb6f6", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-04-30T19:32:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T11:30:23.000Z", "max_issues_repo_path": "examples/constrainedDoublePendulum/src/constrainedDoublePendulumForwardDynamics.cc", "max_issues_repo_name": "ju6ge/rbdl-orb", "max_issues_repo_head_hexsha": "321e20e80e2859a3a2ab43629c7c26c1020cb6f6", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-04T23:16:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T23:37:28.000Z", "max_forks_repo_path": "examples/constrainedDoublePendulum/src/constrainedDoublePendulumForwardDynamics.cc", "max_forks_repo_name": "ju6ge/rbdl-orb", "max_forks_repo_head_hexsha": "321e20e80e2859a3a2ab43629c7c26c1020cb6f6", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2020-02-01T20:38:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T22:28:24.000Z", "avg_line_length": 30.428115016, "max_line_length": 89, "alphanum_fraction": 0.5404241915, "num_tokens": 2411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4263394396504611}}
{"text": "#include <GL/freeglut.h>\n#include <iostream>\n#include <vector>\n#include <Eigen/Eigen>\n\n#include \"m_estimators.h\"\n#include \"example_func_ax_plus_b_eq_y_jacobian.h\"\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = 0.0, rotate_y = 0.0;\nfloat translate_z = -10.0;\nfloat translate_x, translate_y = 0.0;\n\nbool initGL(int *argc, char **argv);\nvoid display();\nvoid keyboard(unsigned char key, int x, int y);\nvoid mouse(int button, int state, int x, int y);\nvoid motion(int x, int y);\nvoid reshape(int w, int h);\nvoid printHelp();\n\ndouble a = 0.3;\ndouble b = 1.0;\n\ndouble a_barron = 0.3;\ndouble b_barron = 1.0;\n\ndouble a_cauchy = 0.3;\ndouble b_cauchy = 1.0;\n\ndouble a_huber = 0.3;\ndouble b_huber = 1.0;\n\ndouble barron_c = 0.25;\ndouble barron_alpha = 1;\n\nstd::vector<std::pair<double, double>> input_data;\n\nint main(int argc, char *argv[]){\n\tdouble y;\n\tfor(double x = -10; x <= 10; x+= 0.01){\n\t\texample_func_ax_plus_b(y,  x,  a,  b);\n\t\ty += ((double(rand()%1000000)/1000000.0) - 0.5) * 2.0 * 0.1;\n\t\tinput_data.emplace_back(x,y);\n\t}\n\n\t//outliers\n\tfor(double x = -10; x <= 0; x+= 0.02){\n\t\texample_func_ax_plus_b(y,  x,  a,  b);\n\t\ty += ((double(rand()%1000000)/1000000.0) - 0.5) * 2.0 + 5;\n\t\tinput_data.emplace_back(x,y);\n\t}\n\tfor(double x = 0; x <= 10; x+= 0.02){\n\t\texample_func_ax_plus_b(y,  x,  a,  b);\n\t\ty += ((double(rand()%1000000)/1000000.0) - 0.5) * 2.0 - 5;\n\t\tinput_data.emplace_back(x,y);\n\t}\n\n\ta = 0.5;\n\ta_barron = 0.5;\n\ta_cauchy = 0.5;\n\ta_huber = 0.5;\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"adaptive_robust_loss_function_demo\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01,\n\t\t\t10000.0);\n\tglutReshapeFunc(reshape);\n\n\treturn true;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tglPointSize(4);\n\tglLineWidth(5);\n\tglColor3f(1,0,0);\n\tglBegin(GL_LINE_STRIP);\n\tdouble y;\n\tfor(double x = -10; x < 10; x+=0.01){\n\t\texample_func_ax_plus_b(y,  x,  a_barron,  b_barron);\n\t\tglVertex3f(x, y, 0);\n\t}\n\tglEnd();\n\n\tglColor3f(0,1,0);\n\tglBegin(GL_LINE_STRIP);\n\tfor(double x = -10; x < 10; x+=0.01){\n\t\texample_func_ax_plus_b(y,  x,  a_cauchy,  b_cauchy);\n\t\tglVertex3f(x, y, 0);\n\t}\n\tglEnd();\n\n\tglColor3f(0,0,1);\n\tglBegin(GL_LINE_STRIP);\n\tfor(double x = -10; x < 10; x+=0.01){\n\t\texample_func_ax_plus_b(y,  x,  a_huber,  b_huber);\n\t\tglVertex3f(x, y, 0);\n\t}\n\tglEnd();\n\n\tglColor3f(0,0,0);\n\tglBegin(GL_LINE_STRIP);\n\tfor(double x = -10; x < 10; x+=0.01){\n\t\texample_func_ax_plus_b(y,  x,  a,  b);\n\t\tglVertex3f(x, y, 0);\n\t}\n\tglEnd();\n\n\n\tglColor3f(0.5,0.5,0.9);\n\tglBegin(GL_POINTS);\n\tfor(const auto &d:input_data){\n\t\tglVertex3f(d.first, d.second, 0);\n\t}\n\tglEnd();\n\n\tglutSwapBuffers();\n}\n\nvoid keyboard(unsigned char key, int /*x*/, int /*y*/) {\n\tswitch (key) {\n\t\tcase (27): {\n\t\t\tglutDestroyWindow(glutGetWindow());\n\t\t\treturn;\n\t\t}\n\t\tcase 'o':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0; i < input_data.size() ; i++){\n\t\t\t\tdouble delta;\n\t\t\t\tobservation_equation_example_func_ax_plus_b_eq_y(delta, input_data[i].first, input_data[i].second, a, b);\n\n\t\t\t\tEigen::Matrix<double, 1, 2> jacobian;\n\t\t\t\tobservation_equation_example_func_ax_plus_b_eq_y_jacobian(jacobian, input_data[i].first, input_data[i].second, a, b);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\ttripletListA.emplace_back(ir, 0, -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, 1, -jacobian(0,1));\n\t\t\t\ttripletListP.emplace_back(ir, ir,  1);\n\t\t\t\ttripletListB.emplace_back(ir, 0,  delta);\n\n\t\t\t}\n\n\t\t\tint number_of_columns = 2;\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), number_of_columns);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(number_of_columns, number_of_columns);\n\t\t\tEigen::SparseMatrix<double> AtPB(number_of_columns, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == number_of_columns){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\ta += h_x[0];\n\t\t\t\tb += h_x[1];\n\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'b':{\n\t\t\tdouble min_sum = 1000000000.0;\n\t\t\tfor(double alpha = -10; alpha <=2; alpha += 0.1){\n\t\t\t\tdouble Z_tilde = get_approximate_partition_function(-10, 10, alpha, 1, 100);\n\t\t\t\tdouble sum = 0;\n\t\t\t\tfor(size_t i = 0; i < input_data.size() ; i++){\n\t\t\t\t\tdouble delta;\n\t\t\t\t\tobservation_equation_example_func_ax_plus_b_eq_y(delta, input_data[i].first, input_data[i].second, a, b);\n\t\t\t\t\tsum += get_truncated_robust_kernel(delta, alpha, barron_c, Z_tilde);\n\t\t\t\t}\n\t\t\t\tif(sum < min_sum){\n\t\t\t\t\tmin_sum = sum;\n\t\t\t\t\tbarron_alpha = alpha;\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << \"barron_alpha: \" << barron_alpha << std::endl;\n\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0; i < input_data.size() ; i++){\n\t\t\t\tdouble delta;\n\t\t\t\tobservation_equation_example_func_ax_plus_b_eq_y(delta, input_data[i].first, input_data[i].second, a_barron, b_barron);\n\n\t\t\t\tEigen::Matrix<double, 1, 2> jacobian;\n\t\t\t\tobservation_equation_example_func_ax_plus_b_eq_y_jacobian(jacobian, input_data[i].first, input_data[i].second, a_barron, b_barron);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\ttripletListA.emplace_back(ir, 0, -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, 1, -jacobian(0,1));\n\t\t\t\ttripletListP.emplace_back(ir, ir, get_barron_w(delta, barron_alpha, barron_c));\n\t\t\t\ttripletListB.emplace_back(ir, 0,  delta);\n\t\t\t}\n\n\t\t\tint number_of_columns = 2;\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), number_of_columns);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(number_of_columns, number_of_columns);\n\t\t\tEigen::SparseMatrix<double> AtPB(number_of_columns, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == number_of_columns){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\ta_barron += h_x[0];\n\t\t\t\tb_barron += h_x[1];\n\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'c':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0; i < input_data.size() ; i++){\n\t\t\t\tdouble delta;\n\t\t\t\tobservation_equation_example_func_ax_plus_b_eq_y(delta, input_data[i].first, input_data[i].second, a_cauchy, b_cauchy);\n\n\t\t\t\tEigen::Matrix<double, 1, 2> jacobian;\n\t\t\t\tobservation_equation_example_func_ax_plus_b_eq_y_jacobian(jacobian, input_data[i].first, input_data[i].second, a_cauchy, b_cauchy);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\ttripletListA.emplace_back(ir, 0, -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, 1, -jacobian(0,1));\n\t\t\t\ttripletListP.emplace_back(ir, ir, get_barron_w(delta, 0, barron_c));\n\t\t\t\ttripletListB.emplace_back(ir, 0,  delta);\n\t\t\t}\n\n\t\t\tint number_of_columns = 2;\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), number_of_columns);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(number_of_columns, number_of_columns);\n\t\t\tEigen::SparseMatrix<double> AtPB(number_of_columns, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == number_of_columns){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\ta_cauchy += h_x[0];\n\t\t\t\tb_cauchy += h_x[1];\n\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'l':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0; i < input_data.size() ; i++){\n\t\t\t\tdouble delta;\n\t\t\t\tobservation_equation_example_func_ax_plus_b_eq_y(delta, input_data[i].first, input_data[i].second, a_huber, b_huber);\n\n\t\t\t\tEigen::Matrix<double, 1, 2> jacobian;\n\t\t\t\tobservation_equation_example_func_ax_plus_b_eq_y_jacobian(jacobian, input_data[i].first, input_data[i].second, a_huber, b_huber);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\ttripletListA.emplace_back(ir, 0, -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, 1, -jacobian(0,1));\n\t\t\t\ttripletListP.emplace_back(ir, ir, get_barron_w(delta, 1, barron_c));\n\t\t\t\ttripletListB.emplace_back(ir, 0,  delta);\n\t\t\t}\n\n\t\t\tint number_of_columns = 2;\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), number_of_columns);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(number_of_columns, number_of_columns);\n\t\t\tEigen::SparseMatrix<double> AtPB(number_of_columns, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == number_of_columns){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\ta_huber += h_x[0];\n\t\t\t\tb_huber += h_x[1];\n\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase '-':{\n\t\t\tbarron_alpha -= 0.1;\n\t\t\tstd::cout << \"barron_alpha \" << barron_alpha << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\tcase '=':{\n\t\t\tbarron_alpha += 0.1;\n\t\t\tstd::cout << \"barron_alpha \" << barron_alpha << std::endl;\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"'o': optimize\" << std::endl;\n\tstd::cout << \"'b': optimize robust Barron\" << std::endl;\n\tstd::cout << \"'c': optimize robust Cauchy\" << std::endl;\n\tstd::cout << \"'l': optimize robust L1L2\" << std::endl;\n\tstd::cout << \"'-': barron_alpha -= 0.1\" << std::endl;\n\tstd::cout << \"'=': barron_alpha += 0.1\" << std::endl;\n}\n\n\n\n\n", "meta": {"hexsha": "8e332633ec30d92bc9e5de71fb724032323b2ba2", "size": 15375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/adaptive_robust_loss_function_demo.cpp", "max_stars_repo_name": "JanuszBedkowski/observation_equations", "max_stars_repo_head_hexsha": "ab241f571a655aebc89870f54e01cb7347382aa9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-11T13:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T22:04:00.000Z", "max_issues_repo_path": "codes/c++Examples/src/adaptive_robust_loss_function_demo.cpp", "max_issues_repo_name": "JanuszBedkowski/observation_equations", "max_issues_repo_head_hexsha": "ab241f571a655aebc89870f54e01cb7347382aa9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/c++Examples/src/adaptive_robust_loss_function_demo.cpp", "max_forks_repo_name": "JanuszBedkowski/observation_equations", "max_forks_repo_head_hexsha": "ab241f571a655aebc89870f54e01cb7347382aa9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-30T22:33:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T18:21:21.000Z", "avg_line_length": 28.6847014925, "max_line_length": 135, "alphanum_fraction": 0.6524227642, "num_tokens": 5093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.4262858575567863}}
{"text": "/* H0 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */\n/* H0 X                                                                            */\n/* H0 X   libAtoms+QUIP: atomistic simulation library                              */\n/* H0 X                                                                            */\n/* H0 X   Portions of this code were written by                                    */\n/* H0 X     Albert Bartok-Partay, Silvia Cereda, Gabor Csanyi, James Kermode,      */\n/* H0 X     Ivan Solt, Wojciech Szlachta, Csilla Varnai, Steven Winfield.          */\n/* H0 X                                                                            */\n/* H0 X   Copyright 2006-2010.                                                     */\n/* H0 X                                                                            */\n/* H0 X   These portions of the source code are released under the GNU General     */\n/* H0 X   Public License, version 2, http://www.gnu.org/copyleft/gpl.html          */\n/* H0 X                                                                            */\n/* H0 X   If you would like to license the source code under different terms,      */\n/* H0 X   please contact Gabor Csanyi, gabor@csanyi.net                            */\n/* H0 X                                                                            */\n/* H0 X   Portions of this code were written by Noam Bernstein as part of          */\n/* H0 X   his employment for the U.S. Government, and are not subject              */\n/* H0 X   to copyright in the USA.                                                 */\n/* H0 X                                                                            */\n/* H0 X                                                                            */\n/* H0 X   When using this software, please cite the following reference:           */\n/* H0 X                                                                            */\n/* H0 X   http://www.libatoms.org                                                  */\n/* H0 X                                                                            */\n/* H0 X  Additional contributions by                                               */\n/* H0 X    Alessio Comisso, Chiara Gattinoni, and Gianpietro Moras                 */\n/* H0 X                                                                            */\n/* H0 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */\n\n/* This file contains routines which use the Computational Geometry\n   Algorithms Library (CGAL, http://www.cgal.org) to compute alpha\n   shapes. It is used to determine a crack front given the set of\n   crack surface atoms. */\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n#include <CGAL/algorithm.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Alpha_shape_2.h>\n#include <CGAL/Arr_segment_traits_2.h>\n#include <CGAL/Arrangement_2.h>\n#include <CGAL/bounding_box.h>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <list>\n\n#include <boost/iterator/transform_iterator.hpp>\n\nextern \"C\" {\n#include \"libatoms.h\"\n}\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel K;\n\ntypedef K::FT FT;\n\ntypedef K::Point_2  Point;\ntypedef K::Segment_2  Segment;\n\ntypedef CGAL::Alpha_shape_vertex_base_2<K> Vb;\ntypedef CGAL::Alpha_shape_face_base_2<K>  Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb,Fb> Tds;\ntypedef CGAL::Delaunay_triangulation_2<K,Tds> Triangulation_2;\n\ntypedef CGAL::Alpha_shape_2<Triangulation_2>  Alpha_shape_2;\n\ntypedef Alpha_shape_2::Face  Face;\ntypedef Alpha_shape_2::Vertex Vertex;\ntypedef Alpha_shape_2::Edge Edge;\ntypedef Alpha_shape_2::Face_handle  Face_handle;\ntypedef Alpha_shape_2::Vertex_handle Vertex_handle;\n\ntypedef Alpha_shape_2::Face_circulator  Face_circulator;\ntypedef Alpha_shape_2::Vertex_circulator  Vertex_circulator;\n\ntypedef Alpha_shape_2::Locate_type Locate_type;\n\ntypedef Alpha_shape_2::Face_iterator  Face_iterator;\ntypedef Alpha_shape_2::Vertex_iterator  Vertex_iterator;\ntypedef Alpha_shape_2::Edge_iterator  Edge_iterator;\ntypedef Alpha_shape_2::Edge_circulator  Edge_circulator;\n\ntypedef Alpha_shape_2::Alpha_iterator Alpha_iterator;\ntypedef Alpha_shape_2::Alpha_shape_edges_iterator Alpha_shape_edges_iterator;\ntypedef Alpha_shape_2::Alpha_shape_vertices_iterator Alpha_shape_vertices_iterator;\n\ntypedef CGAL::Arr_segment_traits_2<K> Traits_2;\ntypedef CGAL::Arrangement_2<Traits_2> Arrangement_2;\ntypedef CGAL::Arr_walk_along_line_point_location<Arrangement_2> Walk_pl;\n\nstd::map<Point,int>::key_type get_key(std::map<Point,int>::value_type aPair) {\n  return aPair.first;\n}\n\ntypedef std::map<Point,int>::key_type (*get_key_t)(std::map<Point,int>::value_type);\ntypedef std::map<Point,int>::iterator map_iterator;\ntypedef boost::transform_iterator<get_key_t, map_iterator> mapkey_iterator;\n\n\nextern \"C\" void c_alpha_shape_2(int *n, double x[], double y[],\n                                double *alpha, int *shape_n, int shape_list[],\n                                int *error)\n{\n  INIT_ERROR;\n\n  // Map from points to original indices in input data\n  std::map<Point,int> point_map;\n\n  for (int i=0; i<*n; i++) {\n    point_map[Point(x[i],y[i])] = i;\n  }\n\n  mapkey_iterator points_begin(point_map.begin(), get_key);\n  mapkey_iterator points_end(point_map.end(), get_key);\n\n  Alpha_shape_2 A(points_begin, points_end, FT(*alpha), Alpha_shape_2::GENERAL);\n\n  Arrangement_2 arr;\n\n  // Traverse alpha shape edges and add to arrangement\n  for(Alpha_shape_edges_iterator it =  A.alpha_shape_edges_begin();\n      it != A.alpha_shape_edges_end();\n      ++it){\n    CGAL::insert(arr, A.segment(*it));\n  }\n\n  // Check we have one bounded face\n  if (arr.number_of_faces() != 2) {\n    RAISE_ERROR(\"c_alpha_shape_2: number of bounded faces != 1, try increasing alpha\");\n  }\n\n  Arrangement_2::Face_const_iterator fi = arr.faces_begin();\n  ++fi; // skip over the unbounded face which all arrangements have\n\n  Arrangement_2::Ccb_halfedge_const_circulator ccb = fi->outer_ccb();\n\n  // Check shape_list is big enough to store alpha shape\n  int tmp_shape_length = 0;\n  do {\n    tmp_shape_length++;\n    ++ccb;\n  } while (ccb != fi->outer_ccb());\n  if (tmp_shape_length > *shape_n) {\n    RAISE_ERROR(\"c_alpha_shape_2: size of alpha shape exceeds length of shape_list\");\n  }\n\n  // traverse outer CCB again, adding results to shape_list\n  ccb = fi->outer_ccb();\n  *shape_n = 0;\n  do {\n    shape_list[(*shape_n)++] = point_map[ccb->source()->point()];\n    ++ccb;\n  } while (ccb != fi->outer_ccb());\n}\n\nextern \"C\" void c_crack_front_alpha_shape(int *n, double x[], double y[],\n                                          double *alpha, double *angle_threshold,\n                                          int *front_n, int front_list[], int *error)\n{\n  INIT_ERROR;\n\n  // Map from points to original indices in input data\n  std::map<Point,int> point_map;\n\n  for (int i=0; i<*n; i++) {\n    point_map[Point(x[i],y[i])] = i;\n  }\n\n  mapkey_iterator points_begin(point_map.begin(), get_key);\n  mapkey_iterator points_end(point_map.end(), get_key);\n\n  Alpha_shape_2 A(points_begin, points_end, FT(*alpha), Alpha_shape_2::GENERAL);\n\n  Arrangement_2 arr;\n\n  // Traverse alpha shape edges and add to arrangement\n  for(Alpha_shape_edges_iterator it =  A.alpha_shape_edges_begin();\n      it != A.alpha_shape_edges_end();\n      ++it){\n    CGAL::insert(arr, A.segment(*it));\n  }\n\n  // Check we have one bounded face\n  if (arr.number_of_faces() != 2) {\n    RAISE_ERROR(\"c_crack_front_alpha_shape: number of bounded faces != 1, try increasing alpha\");\n  }\n\n  // Compute bounding box of original point set and use it\n  // to perform a vertical ray shooting query\n  K::Iso_rectangle_2 bbox = bounding_box(points_begin, points_end);\n  Point p = Point(bbox.xmax(), bbox.ymin());\n  Walk_pl walk_pl(arr);\n  CGAL::Object    obj = walk_pl.ray_shoot_up (p);\n  Arrangement_2::Vertex_const_handle xmax_vertex;\n  if (!CGAL::assign (xmax_vertex, obj)) {\n    RAISE_ERROR(\"c_crack_front_alpha_shape: vertical line search did not hit a vertex\");\n  }\n\n  Arrangement_2::Face_const_iterator fi = arr.faces_begin();\n  ++fi; // skip over the unbounded face which all arrangements have\n\n  // find half-line with source at xmax_vertex\n  Arrangement_2::Ccb_halfedge_const_circulator curr, xmax_edge;\n  for(xmax_edge = fi->outer_ccb(); xmax_edge->source() != xmax_vertex; ++xmax_edge);\n\n  double bearing;\n  Point p1, p2;\n  std::list<int> front;\n\n  // start at xmax_edge and traverse outer CCB until angle along line\n  // exceeds angle_threshold\n  curr = xmax_edge;\n  do {\n    p1 = curr->source()->point();\n    p2 = curr->target()->point();\n\n    bearing = 180./M_PI*std::atan2(CGAL::to_double(p2.y())-CGAL::to_double(p1.y()),\n                                   CGAL::to_double(p2.x())-CGAL::to_double(p1.x()));\n\n    front.push_back(point_map[curr->source()->point()]);\n  } while (++curr != xmax_edge && bearing < *angle_threshold);\n\n  // now go back to xmax_edge, and go around backwards until\n  // angle is less than -angle_theshold\n  curr = xmax_edge;\n  --curr; // don't want xmax_edge vertex to appear twice in output list\n  do {\n    p1 = curr->twin()->source()->point();\n    p2 = curr->twin()->target()->point();\n\n    bearing = 180./M_PI*std::atan2(CGAL::to_double(p2.y())-CGAL::to_double(p1.y()),\n                                   CGAL::to_double(p2.x())-CGAL::to_double(p1.x()));\n\n    front.push_front(point_map[curr->source()->point()]);\n  } while (--curr != xmax_edge && bearing > -*angle_threshold);\n\n  // Copy output into array front_list\n  if (front.size() > *front_n) {\n    RAISE_ERROR(\"c_crack_front_alpha_shape: Not enough space in front_list\");\n  }\n  *front_n=0;\n  for (std::list<int>::iterator it = front.begin(); it != front.end(); ++it) {\n    front_list[(*front_n)++] = *it;\n  }\n}\n\n#ifdef MAIN_PROGRAM\nint main()\n{\n  FILE *stream = fopen(\"pos_xz\",\"r\");\n  char buffer[256];\n  int i,n;\n\n  fgets(buffer,256,stream);\n  sscanf(buffer,\"%d\",&n);\n\n  double *x = new double[n];\n  double *y = new double[n];\n\n  for (i=0; i<n; i++) {\n    fgets(buffer,256,stream);\n    sscanf(buffer,\"%lf %lf\",&(x[i]),&(y[i]));\n  }\n  fclose(stream);\n\n  double alpha = 100.0;\n  double angle_threshold = 160.0;\n\n  int front_n = 100;\n  int *front_list = new int[front_n];\n\n  int error = 0;\n  crack_front_alpha_shape(&n, x, y, &alpha, &angle_threshold, &front_n, front_list, &error);\n\n  if (error == 0) {\n    for (i = 0; i < front_n; i++)\n      std::cout << front_list[i] << std::endl;\n  }\n}\n#endif\n", "meta": {"hexsha": "3b52bdfe2507f440a212eb438f87434fbfbb3a03", "size": 10545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/libAtoms/alphashape.cpp", "max_stars_repo_name": "Sideboard/QUIP", "max_stars_repo_head_hexsha": "f41372609e4a92fcda9f33b695a666de3886822b", "max_stars_repo_licenses": ["NRL"], "max_stars_count": 229.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T16:35:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T10:44:32.000Z", "max_issues_repo_path": "src/libAtoms/alphashape.cpp", "max_issues_repo_name": "Sideboard/QUIP", "max_issues_repo_head_hexsha": "f41372609e4a92fcda9f33b695a666de3886822b", "max_issues_repo_licenses": ["NRL"], "max_issues_count": 356.0, "max_issues_repo_issues_event_min_datetime": "2015-05-29T08:28:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:55:34.000Z", "max_forks_repo_path": "src/libAtoms/alphashape.cpp", "max_forks_repo_name": "Sideboard/QUIP", "max_forks_repo_head_hexsha": "f41372609e4a92fcda9f33b695a666de3886822b", "max_forks_repo_licenses": ["NRL"], "max_forks_count": 106.0, "max_forks_repo_forks_event_min_datetime": "2015-01-21T12:56:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T08:39:24.000Z", "avg_line_length": 36.8706293706, "max_line_length": 97, "alphanum_fraction": 0.6144144144, "num_tokens": 2596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.4262756101578747}}
{"text": "/* Copyright (c) 2017, United States Government, as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * \n * All rights reserved.\n * \n * The Astrobee platform is licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with the\n * License. You may obtain a copy of the License at\n * \n *     http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n#include <Eigen/Dense>\n\n#include <iostream>\n\nusing namespace Eigen;\n\nvoid rotate_quat(Quaternionf & q, Vector3f & gibbs_vector, Quaternionf* ret) {\n  Quaternionf t(2, gibbs_vector.x(), gibbs_vector.y(), gibbs_vector.z());\n  // Eigen's multiply doesn't work the same as simulink...\n  // let's keep this to be safe\n  ret->x() = q.x() * t.w() + q.w() * t.x() - q.z() * t.y() + q.y() * t.z();\n  ret->y() = q.y() * t.w() + q.z() * t.x() + q.w() * t.y() - q.x() * t.z();\n  ret->z() = q.z() * t.w() - q.y() * t.x() + q.x() * t.y() + q.w() * t.z();\n  ret->w() = q.w() * t.w() - q.x() * t.x() - q.y() * t.y() - q.z() * t.z();\n  if (ret->w() < 0) {\n    ret->w() = -ret->w(); ret->x() = -ret->x(); ret->y() = -ret->y(); ret->z() = -ret->z();\n  }\n  // Eigen normalize function doesn't work here, I don't understand why\n  if (ret->w() != 0) {\n    float mag = sqrt(ret->x() * ret->x() + ret->y() * ret->y() + ret->z() * ret->z() + ret->w() * ret->w());\n    ret->x() /= mag; ret->y() /= mag; ret->z() /= mag; ret->w() /= mag;\n  }\n}\n\nvoid apply_delta_state(\n    float* delta_state, int delta_state_length, unsigned short update_flag,\n    float* quat_ISS2B_in, float* gyro_bias_in,\n    float* V_B_ISS_ISS_in, float* accel_bias_in, float* P_B_ISS_ISS_in,\n    float* ml_quat_ISS2cam_in, float* ml_P_cam_ISS_ISS_in, unsigned short kfl_status_in,\n    float* of_quat_ISS2cam_in, float* of_P_cam_ISS_ISS_in,\n    float* quat_ISS2B_out, float* gyro_bias_out,\n    float* V_B_ISS_ISS_out, float* accel_bias_out, float* P_B_ISS_ISS_out,\n    float* ml_quat_ISS2cam_out, float* ml_P_cam_ISS_ISS_out, unsigned short* kfl_status_out,\n    float* of_quat_ISS2cam_out, float* of_P_cam_ISS_ISS_out) {\n  int num_augs = (delta_state_length - 21) / 6;\n  Map<VectorXf> ds(delta_state, delta_state_length);\n  Map<Quaternionf> quat(quat_ISS2B_in);\n  Map<Quaternionf> out_quat(quat_ISS2B_out);\n  Map<Vector3f> gyro_bias(gyro_bias_in);\n  Map<Vector3f> out_gyro_bias(gyro_bias_out);\n  Map<Vector3f> vel(V_B_ISS_ISS_in);\n  Map<Vector3f> out_vel(V_B_ISS_ISS_out);\n  Map<Vector3f> accel_bias(accel_bias_in);\n  Map<Vector3f> out_accel_bias(accel_bias_out);\n  Map<Vector3f> pos(P_B_ISS_ISS_in);\n  Map<Vector3f> out_pos(P_B_ISS_ISS_out);\n  Map<Quaternionf> ml_quat(ml_quat_ISS2cam_in);\n  Map<Quaternionf> out_ml_quat(ml_quat_ISS2cam_out);\n  Map<Vector3f> ml_pos(ml_P_cam_ISS_ISS_in);\n  Map<Vector3f> out_ml_pos(ml_P_cam_ISS_ISS_out);\n\n  Quaternionf temp_quat1, temp_quat2;\n  Vector3f temp_vector = ds.segment<3>(0);\n  temp_quat1 = quat;\n  rotate_quat(temp_quat1, temp_vector, &temp_quat2);\n  out_quat = temp_quat2;\n  out_gyro_bias = gyro_bias + ds.segment<3>(3);\n  out_vel = vel + ds.segment<3>(6);\n  out_accel_bias = accel_bias + ds.segment<3>(9);\n  out_pos = pos + ds.segment<3>(12);\n\n  temp_quat1 = ml_quat;\n  temp_vector = ds.segment<3>(15);\n  rotate_quat(temp_quat1, temp_vector, &temp_quat2);\n  out_ml_quat = temp_quat2;\n  out_ml_pos = ml_pos + ds.segment<3>(18);\n\n  *kfl_status_out = (kfl_status_in & ~3) | update_flag;\n\n  Map<MatrixXf> of_quat(of_quat_ISS2cam_in, num_augs, 4);\n  Map<MatrixXf> out_of_quat(of_quat_ISS2cam_out, num_augs, 4);\n  Map<MatrixXf> of_pos(of_P_cam_ISS_ISS_in, num_augs, 3);\n  Map<MatrixXf> out_of_pos(of_P_cam_ISS_ISS_out, num_augs, 3);\n\n  for (int i = 0; i < num_augs; i++) {\n    Quaternionf t_quat(of_quat(i, 3), of_quat(i, 0), of_quat(i, 1), of_quat(i, 2));\n    Quaternionf r;\n    temp_vector = ds.segment<3>(21 + 6 * i);\n    rotate_quat(t_quat, temp_vector, &r);\n    out_of_quat(i, 0) = r.x();\n    out_of_quat(i, 1) = r.y();\n    out_of_quat(i, 2) = r.z();\n    out_of_quat(i, 3) = r.w();\n    out_of_pos.row(i) = of_pos.row(i) + ds.segment<3>(24 + 6 * i).transpose();\n  }\n}\n\n", "meta": {"hexsha": "22a45fdcee3bad2ff532e0853ccc3bee85eb62c0", "size": 4420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gnc/matlab/cxx_functions/src/apply_delta_state.cpp", "max_stars_repo_name": "Robo0603179/astrobee", "max_stars_repo_head_hexsha": "19e58806c63cddd9046342c7fa2ac7808f40ad3c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 629.0, "max_stars_repo_stars_event_min_datetime": "2017-08-31T23:09:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:55:40.000Z", "max_issues_repo_path": "gnc/matlab/cxx_functions/src/apply_delta_state.cpp", "max_issues_repo_name": "Robo0603179/astrobee", "max_issues_repo_head_hexsha": "19e58806c63cddd9046342c7fa2ac7808f40ad3c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 269.0, "max_issues_repo_issues_event_min_datetime": "2018-05-05T12:31:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:04:11.000Z", "max_forks_repo_path": "gnc/matlab/cxx_functions/src/apply_delta_state.cpp", "max_forks_repo_name": "Robo0603179/astrobee", "max_forks_repo_head_hexsha": "19e58806c63cddd9046342c7fa2ac7808f40ad3c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 248.0, "max_forks_repo_forks_event_min_datetime": "2017-08-31T23:20:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T22:29:16.000Z", "avg_line_length": 41.6981132075, "max_line_length": 108, "alphanum_fraction": 0.6726244344, "num_tokens": 1473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.42627359492912786}}
{"text": "// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"paddle/phi/kernels/matrix_rank_tol_kernel.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n#include \"paddle/phi/core/kernel_registry.h\"\n#include \"paddle/phi/kernels/elementwise_multiply_kernel.h\"\n#include \"paddle/phi/kernels/full_kernel.h\"\n#include \"paddle/phi/kernels/funcs/compare_functors.h\"\n#include \"paddle/phi/kernels/funcs/eigen/common.h\"\n#include \"paddle/phi/kernels/funcs/elementwise_base.h\"\n#include \"paddle/phi/kernels/impl/matrix_rank_kernel_impl.h\"\n#include \"paddle/phi/kernels/reduce_max_kernel.h\"\n#include \"paddle/phi/kernels/reduce_sum_kernel.h\"\n\nnamespace phi {\n\ntemplate <typename T>\nvoid BatchEigenvalues(const T* x_data,\n                      T* eigenvalues_data,\n                      int batches,\n                      int rows,\n                      int cols,\n                      int k) {\n  // Eigen::Matrix API need non-const pointer.\n  T* input = const_cast<T*>(x_data);\n  int stride = rows * cols;\n  for (int i = 0; i < batches; i++) {\n    auto m = Eigen::Map<\n        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(\n        input + i * stride, rows, rows);\n    Eigen::SelfAdjointEigenSolver<\n        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>\n        eigen_solver(m);\n    auto eigenvalues = eigen_solver.eigenvalues().cwiseAbs();\n    for (int j = 0; j < k; j++) {\n      *(eigenvalues_data + i * k + j) = eigenvalues[j];\n    }\n  }\n}\n\ntemplate <typename T>\nvoid BatchSVD(const T* x_data,\n              T* eigenvalues_data,\n              int batches,\n              int rows,\n              int cols,\n              int k) {\n  // Eigen::Matrix API need non-const pointer.\n  T* input = const_cast<T*>(x_data);\n  int stride = rows * cols;\n  Eigen::BDCSVD<\n      Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>\n      svd;\n  for (int i = 0; i < batches; i++) {\n    auto m = Eigen::Map<\n        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(\n        input + i * stride, rows, cols);\n    svd.compute(m);\n    auto res_s = svd.singularValues();\n    for (int j = 0; j < k; j++) {\n      eigenvalues_data[i * k + j] = res_s[j];\n    }\n  }\n}\n\ntemplate <typename T, typename Context>\nvoid MatrixRankTolKernel(const Context& dev_ctx,\n                         const DenseTensor& x,\n                         const DenseTensor& atol_tensor,\n                         bool use_default_tol,\n                         bool hermitian,\n                         DenseTensor* out) {\n  auto* x_data = x.data<T>();\n  dev_ctx.template Alloc<int64_t>(out);\n  auto dim_x = x.dims();\n  auto dim_out = out->dims();\n  int rows = dim_x[dim_x.size() - 2];\n  int cols = dim_x[dim_x.size() - 1];\n  int k = std::min(rows, cols);\n  auto numel = x.numel();\n  int batches = numel / (rows * cols);\n\n  T rtol_T = 0;\n\n  if (use_default_tol) {\n    rtol_T = std::numeric_limits<T>::epsilon() * std::max(rows, cols);\n  }\n\n  DenseTensor eigenvalue_tensor;\n  eigenvalue_tensor.Resize(detail::GetEigenvalueDim(dim_x, k));\n  auto* eigenvalue_data = dev_ctx.template Alloc<T>(&eigenvalue_tensor);\n\n  if (hermitian) {\n    BatchEigenvalues<T>(x_data, eigenvalue_data, batches, rows, cols, k);\n  } else {\n    BatchSVD<T>(x_data, eigenvalue_data, batches, rows, cols, k);\n  }\n\n  DenseTensor max_eigenvalue_tensor;\n  max_eigenvalue_tensor.Resize(detail::RemoveLastDim(eigenvalue_tensor.dims()));\n  dev_ctx.template Alloc<T>(&max_eigenvalue_tensor);\n  phi::MaxKernel<T, Context>(dev_ctx,\n                             eigenvalue_tensor,\n                             std::vector<int64_t>{-1},\n                             false,\n                             &max_eigenvalue_tensor);\n\n  DenseTensor temp_rtol_tensor;\n  temp_rtol_tensor =\n      phi::Full<T, Context>(dev_ctx, {1}, static_cast<T>(rtol_T));\n\n  DenseTensor rtol_tensor =\n      phi::Multiply<T>(dev_ctx, temp_rtol_tensor, max_eigenvalue_tensor);\n\n  DenseTensor tol_tensor;\n  tol_tensor.Resize(dim_out);\n  dev_ctx.template Alloc<T>(&tol_tensor);\n  funcs::ElementwiseCompute<GreaterElementFunctor<T>, T, T>(\n      dev_ctx,\n      atol_tensor,\n      rtol_tensor,\n      -1,\n      GreaterElementFunctor<T>(),\n      &tol_tensor);\n\n  tol_tensor.Resize(detail::NewAxisDim(tol_tensor.dims(), 1));\n\n  DenseTensor compare_result;\n  compare_result.Resize(detail::NewAxisDim(dim_out, k));\n  dev_ctx.template Alloc<int64_t>(&compare_result);\n  int axis = -1;\n  if (eigenvalue_tensor.dims().size() >= tol_tensor.dims().size()) {\n    funcs::ElementwiseCompute<funcs::GreaterThanFunctor<T, int64_t>, T, int>(\n        dev_ctx,\n        eigenvalue_tensor,\n        tol_tensor,\n        axis,\n        funcs::GreaterThanFunctor<T, int64_t>(),\n        &compare_result);\n  } else {\n    funcs::ElementwiseCompute<funcs::LessThanFunctor<T, int64_t>, T, int>(\n        dev_ctx,\n        eigenvalue_tensor,\n        tol_tensor,\n        axis,\n        funcs::LessThanFunctor<T, int64_t>(),\n        &compare_result);\n  }\n\n  phi::SumKernel<int64_t>(dev_ctx,\n                          compare_result,\n                          std::vector<int64_t>{-1},\n                          compare_result.dtype(),\n                          false,\n                          out);\n}\n}  // namespace phi\n\nPD_REGISTER_KERNEL(\n    matrix_rank_tol, CPU, ALL_LAYOUT, phi::MatrixRankTolKernel, float, double) {\n}\n", "meta": {"hexsha": "3bfc07319e98dac12fcec00a6172ea113f654b29", "size": 5894, "ext": "cc", "lang": "C++", "max_stars_repo_path": "paddle/phi/kernels/cpu/matrix_rank_tol_kernel.cc", "max_stars_repo_name": "RangeKing/Paddle", "max_stars_repo_head_hexsha": "2d87300809ae75d76f5b0b457d8112cb88dc3e27", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-08-15T07:02:27.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-24T09:34:00.000Z", "max_issues_repo_path": "paddle/phi/kernels/cpu/matrix_rank_tol_kernel.cc", "max_issues_repo_name": "RangeKing/Paddle", "max_issues_repo_head_hexsha": "2d87300809ae75d76f5b0b457d8112cb88dc3e27", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-28T07:23:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T07:23:22.000Z", "max_forks_repo_path": "paddle/phi/kernels/cpu/matrix_rank_tol_kernel.cc", "max_forks_repo_name": "RangeKing/Paddle", "max_forks_repo_head_hexsha": "2d87300809ae75d76f5b0b457d8112cb88dc3e27", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4886363636, "max_line_length": 80, "alphanum_fraction": 0.6243637598, "num_tokens": 1487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911057, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4262735889197501}}
{"text": "/**\n * \\file TimeVaryingSecondOrderFilter.cpp\n * @see http://abvolt.com/research/publications2.htm\n * @see http://www.music.mcgill.ca/~ich/classes/FiltersChap2.pdf for the allpass filter\n */\n\n#include <ATK/EQ/TimeVaryingSecondOrderFilter.h>\n#include <ATK/EQ/TimeVaryingIIRFilter.h>\n\n#include <cassert>\n#include <cmath>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace ATK\n{\n  /// Time varying coefficient base class. Two input ports, the first is the data, the second one is the central frequency\n  template <typename DataType>\n  TimeVaryingBaseSecondOrderCoefficients<DataType>::TimeVaryingBaseSecondOrderCoefficients()\n    :Parent(2, 1)\n  {\n  }\n\n  template <typename DataType>\n  void TimeVaryingBaseSecondOrderCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    coefficients_in.clear();\n    coefficients_in.reserve((in_order+1) * number_of_steps);\n    coefficients_out.clear();\n    coefficients_out.reserve(out_order * number_of_steps);\n  }\n\n  template <typename DataType>\n  void TimeVaryingBaseSecondOrderCoefficients<DataType>::set_min_frequency(double min_frequency)\n  {\n    if(min_frequency <= 0)\n    {\n      throw std::out_of_range(\"Min frequency must be positive\");\n    }\n    this->min_frequency = min_frequency;\n    setup();\n  }\n\n  template <typename DataType>\n  double TimeVaryingBaseSecondOrderCoefficients<DataType>::get_min_frequency() const\n  {\n    return min_frequency;\n  }\n\n  template <typename DataType>\n  void TimeVaryingBaseSecondOrderCoefficients<DataType>::set_max_frequency(double max_frequency)\n  {\n    if(max_frequency <= min_frequency)\n    {\n      throw std::out_of_range(\"Max frequency must be greater than min frequency\");\n    }\n    this->max_frequency = max_frequency;\n    setup();\n  }\n\n  template <typename DataType>\n  double TimeVaryingBaseSecondOrderCoefficients<DataType>::get_max_frequency() const\n  {\n    return max_frequency;\n  }\n\n  template <typename DataType>\n  void TimeVaryingBaseSecondOrderCoefficients<DataType>::set_number_of_steps(int number_of_steps)\n  {\n    if(number_of_steps <= 0)\n    {\n      throw std::out_of_range(\"Number of steps must be strictly positive\");\n    }\n    this->number_of_steps = number_of_steps;\n    setup();\n  }\n\n  template <typename DataType>\n  int TimeVaryingBaseSecondOrderCoefficients<DataType>::get_number_of_steps() const\n  {\n    return number_of_steps;\n  }\n\n  template <typename DataType>\n  void TimeVaryingBaseSecondOrderCoefficients<DataType>::set_memory(double memory)\n  {\n    if(memory < 0 || memory >= 1)\n    {\n      throw std::out_of_range(\"Memory for time varying EQ had to be in the range [0, 1[\");\n    }\n    this->memory = memory;\n  }\n\n  template <typename DataType>\n  double TimeVaryingBaseSecondOrderCoefficients<DataType>::get_memory() const\n  {\n    return memory;\n  }\n\n  template<typename DataType>\n  TimeVaryingBandPassCoefficients<DataType>::TimeVaryingBandPassCoefficients()\n    :Parent()\n  {\n  }\n\n  template <typename DataType>\n  void TimeVaryingBandPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n    \n    for(gsl::index i = 0; i < number_of_steps; ++i)\n    {\n      DataType cut_frequency = static_cast<DataType>((max_frequency - min_frequency) * i / (number_of_steps - 1) + min_frequency);\n      DataType c = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n      DataType d = (1 + std::sqrt(static_cast<DataType>(2.)) * c + c * c);\n      DataType Q_inv = 1 / Q;\n\n      coefficients_in.push_back(-Q_inv * c / d);\n      coefficients_in.push_back(0);\n      coefficients_in.push_back(Q_inv * c / d);\n      coefficients_out.push_back(- (1 - std::sqrt(static_cast<DataType>(2.)) * c + c * c) / d);\n      coefficients_out.push_back(- 2 * (c * c - 1) / d);\n    }\n  }\n  \n  template <typename DataType_>\n  void TimeVaryingBandPassCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if(Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be strictly positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ TimeVaryingBandPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType>\n  TimeVaryingLowPassCoefficients<DataType>::TimeVaryingLowPassCoefficients()\n    :Parent()\n  {\n  }\n\n  template <typename DataType>\n  void TimeVaryingLowPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    for(gsl::index i = 0; i < number_of_steps; ++i)\n    {\n      DataType cut_frequency = static_cast<DataType>((max_frequency - min_frequency) * i / (number_of_steps - 1) + min_frequency);\n      DataType c = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n      DataType d = (1 + std::sqrt(static_cast<DataType>(2.)) * c + c * c);\n    \n      coefficients_in.push_back(c * c / d);\n      coefficients_in.push_back(2 * c * c / d);\n      coefficients_in.push_back(c * c / d);\n      coefficients_out.push_back(- (1 - std::sqrt(static_cast<DataType>(2.)) * c + c * c) / d);\n      coefficients_out.push_back(- 2 * (c * c - 1) / d);\n    }\n  }\n\n  template<typename DataType>\n  TimeVaryingHighPassCoefficients<DataType>::TimeVaryingHighPassCoefficients()\n    :Parent()\n  {\n  }\n\n  template <typename DataType>\n  void TimeVaryingHighPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    for(gsl::index i = 0; i < number_of_steps; ++i)\n    {\n      DataType cut_frequency = static_cast<DataType>((max_frequency - min_frequency) * i / (number_of_steps - 1) + min_frequency);\n      DataType c = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n      DataType d = (1 + std::sqrt(static_cast<DataType>(2.)) * c + c * c);\n\n      coefficients_in.push_back(1);\n      coefficients_in.push_back(-2);\n      coefficients_in.push_back(1);\n      coefficients_out.push_back(- (1 - std::sqrt(static_cast<DataType>(2.)) * c + c * c) / d);\n      coefficients_out.push_back(- 2 * (c * c - 1) / d);\n    }\n  }\n\n  template<typename DataType>\n  TimeVaryingBandPassPeakCoefficients<DataType>::TimeVaryingBandPassPeakCoefficients()\n    :Parent()\n  {\n  }\n\n  template <typename DataType>\n  void TimeVaryingBandPassPeakCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    for(gsl::index i = 0; i < number_of_steps; ++i)\n    {\n      DataType cut_frequency = static_cast<DataType>((max_frequency - min_frequency) * i / (number_of_steps - 1) + min_frequency);\n      DataType c = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n      DataType Q_inv = 1 / Q;\n      if(gain <= 1)\n      {\n        DataType V0 = 1 / gain;\n        DataType d = 1 + V0 * Q_inv * c + c * c;\n\n        coefficients_in.push_back((1 - Q_inv * c + c * c) / d);\n        coefficients_in.push_back(2 * (c * c - 1) / d);\n        coefficients_in.push_back((1 + Q_inv * c + c * c) / d);\n        coefficients_out.push_back(-(1 - V0 * Q_inv * c + c * c) / d);\n        coefficients_out.push_back(-2 * (c * c - 1) / d);\n      }\n      else\n      {\n        DataType V0 = gain;\n        DataType d = 1 + Q_inv * c + c * c;\n\n        coefficients_in.push_back((1 - V0 * Q_inv * c + c * c) / d);\n        coefficients_in.push_back(2 * (c * c - 1) / d);\n        coefficients_in.push_back((1 + V0 * Q_inv * c + c * c) / d);\n        coefficients_out.push_back(-(1 - Q_inv * c + c * c) / d);\n        coefficients_out.push_back(-2 * (c * c - 1) / d);\n      }\n    }\n  }\n\n  template <typename DataType_>\n  void TimeVaryingBandPassPeakCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if(Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be strictly positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ TimeVaryingBandPassPeakCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template <typename DataType_>\n  void TimeVaryingBandPassPeakCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    if(gain <= 0)\n    {\n      throw std::out_of_range(\"Gain must be strictly positive\");\n    }\n    this->gain = gain;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ TimeVaryingBandPassPeakCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  TimeVaryingAllPassCoefficients<DataType>::TimeVaryingAllPassCoefficients()\n    :Parent()\n  {\n  }\n\n  template <typename DataType>\n  void TimeVaryingAllPassCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    for(gsl::index i = 0; i < number_of_steps; ++i)\n    {\n      DataType cut_frequency = static_cast<DataType>((max_frequency - min_frequency) * i / (number_of_steps - 1) + min_frequency);\n      DataType c = std::tan(boost::math::constants::pi<DataType>() * Q);\n      DataType d = -std::cos(2 * boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n\n      coefficients_in.push_back(1);\n      coefficients_in.push_back(d * (1 - c));\n      coefficients_in.push_back(-c);\n      coefficients_out.push_back(c);\n      coefficients_out.push_back(-d * (1 - c));\n    }\n  }\n\n  template <typename DataType_>\n  void TimeVaryingAllPassCoefficients<DataType_>::set_Q(DataType_ Q)\n  {\n    if(Q <= 0)\n    {\n      throw std::out_of_range(\"Q must be strictly positive\");\n    }\n    this->Q = Q;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ TimeVaryingAllPassCoefficients<DataType_>::get_Q() const\n  {\n    return Q;\n  }\n\n  template<typename DataType>\n  TimeVaryingLowShelvingCoefficients<DataType>::TimeVaryingLowShelvingCoefficients()\n    :Parent()\n  {\n  }\n\n  template <typename DataType>\n  void TimeVaryingLowShelvingCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    for(gsl::index i = 0; i < number_of_steps; ++i)\n    {\n      DataType cut_frequency = static_cast<DataType>((max_frequency - min_frequency) * i / (number_of_steps - 1) + min_frequency);\n      DataType c = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n      if(gain <= 1)\n      {\n        DataType V0 = 1 / gain;\n        DataType d = (1 + std::sqrt(static_cast<DataType>(2.) * V0) * c + V0 * c * c);\n\n        coefficients_in.push_back((1 - std::sqrt(static_cast<DataType>(2.)) * c + c * c) / d);\n        coefficients_in.push_back(2 * (c * c - 1) / d);\n        coefficients_in.push_back((1 + std::sqrt(static_cast<DataType>(2.)) * c + c * c) / d);\n        coefficients_out.push_back(- (1 - std::sqrt(static_cast<DataType>(2.) * V0) * c + V0 * c * c) / d);\n        coefficients_out.push_back(- 2 * (V0 * c * c - 1) / d);\n      }\n      else\n      {\n        DataType d = (1 + std::sqrt(static_cast<DataType>(2.)) * c + c * c);\n\n        coefficients_in.push_back((1 - std::sqrt(static_cast<DataType>(2.) * gain) * c + gain * c * c) / d);\n        coefficients_in.push_back(2 * (gain * c * c - 1) / d);\n        coefficients_in.push_back((1 + std::sqrt(static_cast<DataType>(2.) * gain) * c + gain * c * c) / d);\n        coefficients_out.push_back(- (1 - std::sqrt(static_cast<DataType>(2.)) * c + c * c) / d);\n        coefficients_out.push_back(- 2 * (c * c - 1) / d);\n      }\n    }\n  }\n\n  template <typename DataType_>\n  void TimeVaryingLowShelvingCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    if(gain <= 0)\n    {\n      throw std::out_of_range(\"Gain must be strictly positive\");\n    }\n    this->gain = gain;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ TimeVaryingLowShelvingCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n\n  template<typename DataType>\n  TimeVaryingHighShelvingCoefficients<DataType>::TimeVaryingHighShelvingCoefficients()\n    :Parent()\n  {\n  }\n\n  template <typename DataType>\n  void TimeVaryingHighShelvingCoefficients<DataType>::setup()\n  {\n    Parent::setup();\n\n    for(gsl::index i = 0; i < number_of_steps; ++i)\n    {\n      DataType cut_frequency = static_cast<DataType>((max_frequency - min_frequency) * i / (number_of_steps - 1) + min_frequency);\n      DataType c = std::tan(boost::math::constants::pi<DataType>() * cut_frequency / input_sampling_rate);\n      if(gain <= 1)\n      {\n        DataType V0 = 1 / gain;\n        DataType d = (V0 + std::sqrt(static_cast<DataType>(2.) * V0) * c + c * c);\n\n        coefficients_in.push_back(-(1 - std::sqrt(static_cast<DataType>(2.0)) * c + c * c) / d);\n        coefficients_in.push_back(-2 * (c * c - 1) / d);\n        coefficients_in.push_back(-(1 + std::sqrt(static_cast<DataType>(2.0)) * c + c * c) / d);\n        coefficients_out.push_back(- (V0 - std::sqrt(static_cast<DataType>(2.0) * V0) * c + c * c) / d);\n        coefficients_out.push_back(- 2 * (c * c - V0) / d);\n      }\n      else\n      {\n        DataType d = (1 + std::sqrt(static_cast<DataType>(2.)) * c + c * c);\n\n        coefficients_in.push_back(-(gain - std::sqrt(static_cast<DataType>(2.0) * gain) * c + c * c) / d);\n        coefficients_in.push_back(-2 * (c * c - gain) / d);\n        coefficients_in.push_back(-(gain + std::sqrt(static_cast<DataType>(2.0) * gain) * c + c * c) / d);\n        coefficients_out.push_back(- (1 - std::sqrt(static_cast<DataType>(2.0)) * c + c * c) / d);\n        coefficients_out.push_back(- 2 * (c * c - 1) / d);\n      }\n    }\n  }\n  \n  template<typename DataType_>\n  void TimeVaryingHighShelvingCoefficients<DataType_>::set_gain(DataType_ gain)\n  {\n    if(gain <= 0)\n    {\n      throw std::out_of_range(\"Gain must be strictly positive\");\n    }\n    this->gain = gain;\n    setup();\n  }\n\n  template <typename DataType_>\n  DataType_ TimeVaryingHighShelvingCoefficients<DataType_>::get_gain() const\n  {\n    return gain;\n  }\n\n#if ATK_ENABLE_INSTANTIATION\n  template class TimeVaryingBaseSecondOrderCoefficients<float>;\n  \n  template class ATK_EQ_EXPORT TimeVaryingBandPassCoefficients<float>;\n  template class ATK_EQ_EXPORT TimeVaryingLowPassCoefficients<float>;\n  template class ATK_EQ_EXPORT TimeVaryingHighPassCoefficients<float>;\n  template class ATK_EQ_EXPORT TimeVaryingBandPassPeakCoefficients<float>;\n  template class ATK_EQ_EXPORT TimeVaryingAllPassCoefficients<float>;\n  template class ATK_EQ_EXPORT TimeVaryingLowShelvingCoefficients<float>;\n  template class ATK_EQ_EXPORT TimeVaryingHighShelvingCoefficients<float>;\n#endif\n  template class TimeVaryingBaseSecondOrderCoefficients<double>;\n\n  template class ATK_EQ_EXPORT TimeVaryingBandPassCoefficients<double>;\n  template class ATK_EQ_EXPORT TimeVaryingLowPassCoefficients<double>;\n  template class ATK_EQ_EXPORT TimeVaryingHighPassCoefficients<double>;\n  template class ATK_EQ_EXPORT TimeVaryingBandPassPeakCoefficients<double>;\n  template class ATK_EQ_EXPORT TimeVaryingAllPassCoefficients<double>;\n  template class ATK_EQ_EXPORT TimeVaryingLowShelvingCoefficients<double>;\n  template class ATK_EQ_EXPORT TimeVaryingHighShelvingCoefficients<double>;\n}\n", "meta": {"hexsha": "cd3a1ac21d42c603340fb4339e00de20f0ddabd2", "size": 14589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/TimeVaryingSecondOrderFilter.cpp", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/EQ/TimeVaryingSecondOrderFilter.cpp", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/EQ/TimeVaryingSecondOrderFilter.cpp", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 32.7842696629, "max_line_length": 130, "alphanum_fraction": 0.6652957708, "num_tokens": 3994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4261071937076573}}
{"text": "﻿///\\file IsingModel-Visual.cpp\n///\\author Ethan Knox\n///\\date 7/19/2020.\n\n#include <boost/filesystem/fstream.hpp>\n#include <boost/program_options.hpp>\n#include \"../include/Ising.h\"\n#include \"../include/run_simulation.h\"\n#include <iostream>\n\nnamespace opt = boost::program_options;\n\nint main(int argc, const char* argv[])\n{\n    long nrows, ncols, stopiter, framestep;\n    double J, h, T;\n    char method, geometry;\n\n    opt::options_description params(\"Simulation Parameters\");\n\n    params.add_options()\n            (\"help\", \"Show usage\")\n            (\"nrows,r\", opt::value<long>(&nrows)->default_value(500), \"Number of rows\")\n            (\"ncols,c\", opt::value<long>(&ncols)->default_value(500), \"Number of columns\")\n            (\"stopiter,s\", opt::value<long>(&stopiter)->default_value(250000), \"Number of iterations\")\n            (\"framestep,f\", opt::value<long>(&framestep)->default_value(2500), \"Number of iterations between frames\")\n            (\"J,j\", opt::value<double>(&J)->default_value(1.0), \"Ferromagnetic Coupling Constant\")\n            (\"h,h\", opt::value<double>(&h)->default_value(0.0), \"Magnetic Field Strength\")\n            (\"T,t\", opt::value<double>(&T)->default_value(1.8), \"Temperature\")\n            (\"method,m\", opt::value<char>(&method)->default_value('M'), \"Solution Method\")\n            (\"geometry,g\", opt::value<char>(&geometry)->default_value('S'), \"Grid Geometry\")\n            ;\n\n    opt::variables_map vm;\n    opt::store(opt::parse_command_line(argc, argv, params), vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << params << std::endl;\n        return 1;\n    }\n    else {\n        opt::notify(vm);\n\n        std::cout << \"\\n2D ISING MODEL - VISUAL SIMULATION\" << std::endl;\n        std::cout << \"----------------------------------\" << std::endl;\n\n        Ising p = Ising(nrows, ncols, stopiter, framestep, J, h, T, method, geometry);\n\n        std::cout << \"Using the \" << (p.method == 'M' ? \"Metropolis-Hastings\" : \"Wolff\") << \" Algorithm \";\n        std::cout << \"with \" << (p.geometry == 'S' ? \"Standard Square\" : \"Hexagonal\") << \" Geometry\" << std::endl;\n        std::cout << p.nrows << \"x\" << p.ncols << \" Grid, \";\n        std::cout << p.stopiter << \" Iterations, \" << p.framestep << \" Steps Between Frames\" << std::endl;\n        std::cout << \"J = \" << p.J << \", h = \" << p.h << \", T = \" << p.T << std::endl;\n        std::cout << \"\\nRunning...\" << std::endl;\n\n        p.randomize();\n        run_simulation(p); // Go baby go\n\n        std::cout << \"Done!\" << std::endl;\n        std::cout << \"----------------------------------\" << std::endl;\n\n        return 0;\n    }\n}", "meta": {"hexsha": "1bab5132e7ba16723bdb29ed23bff0ee98a3fa92", "size": 2600, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "legacy/src/IsingModel-Visual.cpp", "max_stars_repo_name": "ethank5149/Ising-Model-Visual", "max_stars_repo_head_hexsha": "1c83634504467cf4ee4347419f9adbf328773c11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "legacy/src/IsingModel-Visual.cpp", "max_issues_repo_name": "ethank5149/Ising-Model-Visual", "max_issues_repo_head_hexsha": "1c83634504467cf4ee4347419f9adbf328773c11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "legacy/src/IsingModel-Visual.cpp", "max_forks_repo_name": "ethank5149/Ising-Model-Visual", "max_forks_repo_head_hexsha": "1c83634504467cf4ee4347419f9adbf328773c11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-08T13:22:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T13:22:29.000Z", "avg_line_length": 40.625, "max_line_length": 117, "alphanum_fraction": 0.5503846154, "num_tokens": 693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.42609732448528176}}
{"text": "/*  \n * Copyright (c) 2009 Carnegie Mellon University. \n *     All rights reserved.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http://www.graphlab.ml.cmu.edu\n *\n */\n\n\n#include <boost/unordered_set.hpp>\n#include <graphlab.hpp>\n#include <graphlab/ui/metrics_server.hpp>\n#include <graphlab/macros_def.hpp>\n/**\n *  \n * In this program we implement the \"hash-table\" version of the\n * \"edge-iterator\" algorithm described in\n * \n *    T. Schank. Algorithmic Aspects of Triangle-Based Network Analysis.\n *    Phd in computer science, University Karlsruhe, 2007.\n *\n * The procedure is quite straightforward:\n *   - each vertex maintains a list of all of its neighbors in a hash table.\n *   - For each edge (u,v) in the graph, count the number of intersections\n *     of the neighbor set on u and the neighbor set on v.\n *   - We store the size of the intersection on the edge.\n * \n * This will count every triangle exactly 3 times. Summing across all the\n * edges and dividing by 3 gives the desired result.\n *\n * The preprocessing stage take O(|E|) time, and it has been shown that this\n * algorithm takes $O(|E|^(3/2))$ time.\n *\n * If we only require total counts, we can introduce a optimization that is\n * similar to the \"forward\" algorithm\n * described in thesis above. Instead of maintaining a complete list of all\n * neighbors, each vertex only maintains a list of all neighbors with\n * ID greater than itself. This implicitly generates a topological sort\n * of the graph.\n *\n * Then you can see that each triangle\n *\n * \\verbatim\n  \n     A----->C\n     |     ^\n     |   /\n     v /\n     B\n   \n * \\endverbatim\n * Must be counted only once. (Only when processing edge AB, can one\n * observe that A and B have intersecting out-neighbor sets).\n *\n *\n * \\note The implementation here is built to be easy to understand\n * and not necessarily optimal. In particular the unordered_set is slow\n * for small number of entries. There is a much more efficient\n * (and substantially more complicated) version in undirected_triangle_count.cpp\n */\n\n/*\n * Each vertex maintains a list of all its neighbors.\n * and a final count for the number of triangles it is involved in\n */\nstruct vertex_data_type {\n  vertex_data_type():num_triangles(0) { }\n  // A list of all its neighbors\n  boost::unordered_set<graphlab::vertex_id_type> vid_set;\n  // The number of triangles this vertex is involved it.\n  // only used if \"per vertex counting\" is used\n  size_t num_triangles;\n  \n  void save(graphlab::oarchive &oarc) const {\n    oarc << vid_set << num_triangles;\n  }\n  void load(graphlab::iarchive &iarc) {\n    iarc >> vid_set >> num_triangles;\n  }\n};\n\n\n/*\n * Each edge is simply a counter of triangles\n */\ntypedef size_t edge_data_type;\n\n// To collect the set of neighbors, we need a message type which is\n// basically a set of vertex IDs\n\nbool PER_VERTEX_COUNT = false;\n\n\n/*\n * This is the gathering type which accumulates an (unordered) set of\n * all neighboring vertices.\n * It is a simple wrapper around a boost::unordered_set with\n * an operator+= which simply performs a set union.\n *\n * This struct can be significantly accelerated for small sets.\n * Small collections of vertex IDs should not require the overhead\n * of the unordered_set.\n */\nstruct set_union_gather {\n  boost::unordered_set<graphlab::vertex_id_type> vid_set;\n\n  /*\n   * Combining with another collection of vertices.\n   * Union it into the current set.\n   */\n  set_union_gather& operator+=(const set_union_gather& other) {\n    foreach(graphlab::vertex_id_type othervid, other.vid_set) {\n      vid_set.insert(othervid);\n    }\n    return *this;\n  }\n  \n  // serialize\n  void save(graphlab::oarchive& oarc) const {\n    oarc << vid_set;\n  }\n\n  // deserialize\n  void load(graphlab::iarchive& iarc) {\n    iarc >> vid_set;\n  }\n};\n\n/*\n * Define the type of the graph\n */\ntypedef graphlab::distributed_graph<vertex_data_type,\n                                    edge_data_type> graph_type;\n\n\n/*\n * This class implements the triangle counting algorithm as described in\n * the header. On gather, we accumulate a set of all adjacent vertices.\n * If per_vertex output is not necessary, we can use the optimization\n * where each vertex only accumulates neighbors with greater vertex IDs.\n */\nclass triangle_count :\n      public graphlab::ivertex_program<graph_type,\n                                      set_union_gather>,\n      /* I have no data. Just force it to POD */\n      public graphlab::IS_POD_TYPE  {\npublic:\n  // Gather on all edges\n  edge_dir_type gather_edges(icontext_type& context,\n                             const vertex_type& vertex) const {\n    return graphlab::ALL_EDGES;\n  } \n\n  /*\n   * For each edge, figure out the ID of the \"other\" vertex\n   * and accumulate a set of the neighborhood vertex IDs.\n   */\n  gather_type gather(icontext_type& context,\n                     const vertex_type& vertex,\n                     edge_type& edge) const {\n    set_union_gather gather;\n    // Insert the opposite end of the edge IF the opposite end has\n    // ID greater than the current vertex\n    // If we are getting per vertex counts, we need the entire neighborhood\n    vertex_id_type otherid = edge.source().id() == vertex.id() ?\n                             edge.target().id() : edge.source().id();\n    if (PER_VERTEX_COUNT ||\n        otherid > vertex.id()) gather.vid_set.insert(otherid);\n    return gather;\n  }\n\n  /*\n   * the gather result now contains the vertex IDs in the neighborhood.\n   * store it on the vertex. \n   */\n  void apply(icontext_type& context, vertex_type& vertex,\n             const gather_type& neighborhood) {\n    vertex.data().vid_set = neighborhood.vid_set;\n  } // end of apply\n\n  /*\n   * Scatter over all edges to compute the intersection.\n   * I only need to touch each edge once, so if I scatter just on the\n   * out edges, that is sufficient.\n   */\n  edge_dir_type scatter_edges(icontext_type& context,\n                              const vertex_type& vertex) const {\n    return graphlab::OUT_EDGES;\n  }\n\n\n  /*\n   * Computes the size of the intersection of two unordered sets\n   */\n  static size_t count_set_intersect(\n               const boost::unordered_set<vertex_id_type>& smaller_set,\n               const boost::unordered_set<vertex_id_type>& larger_set) {\n    size_t count = 0;\n    foreach(vertex_id_type vid, smaller_set) {\n      count += larger_set.count(vid);\n    }\n    return count;\n  }\n\n  /*\n   * For each edge, count the intersection of the neighborhood of the\n   * adjacent vertices. This is the number of triangles this edge is involved\n   * in.\n   */\n  void scatter(icontext_type& context,\n              const vertex_type& vertex,\n              edge_type& edge) const {\n    const vertex_data_type& srclist = edge.source().data();\n    const vertex_data_type& targetlist = edge.target().data();\n    if (srclist.vid_set.size() >= targetlist.vid_set.size()) {\n      edge.data() = count_set_intersect(targetlist.vid_set, srclist.vid_set);\n    }\n    else {\n      edge.data() = count_set_intersect(srclist.vid_set, targetlist.vid_set);\n    }\n  }\n};\n\n\n\n/*\n * This class is used in a second engine call if per vertex counts are needed.\n * The number of triangles a vertex is involved in can be computed easily\n * by summing over the number of triangles each adjacent edge is involved in\n * and dividing by 2. \n */\nclass get_per_vertex_count :\n      public graphlab::ivertex_program<graph_type, size_t>,\n      /* I have no data. Just force it to POD */\n      public graphlab::IS_POD_TYPE  {\npublic:\n  // Gather on all edges\n  edge_dir_type gather_edges(icontext_type& context,\n                             const vertex_type& vertex) const {\n    return graphlab::ALL_EDGES;\n  }\n  // We gather the number of triangles each edge is involved in\n  size_t gather(icontext_type& context,\n                     const vertex_type& vertex,\n                     edge_type& edge) const {\n    return edge.data();\n  }\n\n  /* the gather result is the total sum of the number of triangles\n   * each adjacent edge is involved in . Dividing by 2 gives the\n   * desired result.\n   */\n  void apply(icontext_type& context, vertex_type& vertex,\n             const gather_type& num_triangles) {\n    vertex.data().num_triangles = num_triangles / 2;\n  }\n\n  // No scatter\n  edge_dir_type scatter_edges(icontext_type& context,\n                             const vertex_type& vertex) const {\n    return graphlab::NO_EDGES;\n  }\n\n\n};\n\n\n/* Used to sum over all the edges in the graph in a\n * map_reduce_edges call\n * to get the total number of triangles\n */\nsize_t get_edge_data(const graph_type::edge_type& e) {\n  return e.data();\n}\n\n\n\n/*\n * A saver which saves a file where each line is a vid / # triangles pair\n */\nstruct save_triangle_count{\n  std::string save_vertex(graph_type::vertex_type v) { \n    return graphlab::tostr(v.id()) + \"\\t\" +\n           graphlab::tostr(v.data().num_triangles) + \"\\n\";\n  }\n  std::string save_edge(graph_type::edge_type e) {\n    return \"\";\n  }\n};\n\n\nint main(int argc, char** argv) {\n  std::cout << \"This program counts the exact number of triangles in the \"\n            \"provided graph.\\n\\n\";\n\n  graphlab::command_line_options clopts(\"Exact Triangle Counting. \"\n    \"Given a graph, this program computes the total number of triangles \"\n    \"in the graph. An option (per_vertex) is also provided which \"\n    \"computes for each vertex, the number of triangles it is involved in.\"\n    \"The algorithm assumes that each undirected edge appears exactly once \"\n    \"in the graph input. If edges may appear more than once, this procedure \"\n    \"will over count.\");\n  std::string prefix, format;\n  std::string per_vertex;\n  clopts.attach_option(\"graph\", prefix,\n                       \"Graph input. reads all graphs matching prefix*\");\n  clopts.attach_option(\"format\", format,\n                       \"The graph format\");\n  clopts.attach_option(\"per_vertex\", per_vertex,\n                       \"If not empty, will count the number of \"\n                       \"triangles each vertex belongs to and \"\n                       \"save to file with prefix \\\"[per_vertex]\\\". \"\n                       \"The algorithm used is slightly different \"\n                       \"and thus will be a little slower\");\n  \n  if(!clopts.parse(argc, argv)) return EXIT_FAILURE;\n  if (prefix == \"\") {\n    std::cout << \"--graph is not optional\\n\";\n    clopts.print_description();\n    return EXIT_FAILURE;\n  }\n  else if (format == \"\") {\n    std::cout << \"--format is not optional\\n\";\n    clopts.print_description();\n    return EXIT_FAILURE;\n  }\n\n\n  if (per_vertex != \"\") PER_VERTEX_COUNT = true;\n  // Initialize control plane using mpi\n  graphlab::mpi_tools::init(argc, argv);\n  graphlab::distributed_control dc;\n\n  graphlab::launch_metric_server();\n  // load graph\n  graph_type graph(dc, clopts);\n  graph.load_format(prefix, format);\n  graph.finalize();\n  dc.cout() << \"Number of vertices: \" << graph.num_vertices() << std::endl\n            << \"Number of edges:    \" << graph.num_edges() << std::endl;\n\n  graphlab::timer ti;\n  \n  // create engine to count the number of triangles\n  dc.cout() << \"Counting Triangles...\" << std::endl;\n  graphlab::synchronous_engine<triangle_count> engine(dc, graph, clopts);\n  engine.signal_all();\n  engine.start();\n\n  dc.cout() << \"Counted in \" << ti.current_time() << \" seconds\" << std::endl;\n\n  if (PER_VERTEX_COUNT == false) {\n    size_t count = graph.map_reduce_edges<size_t>(get_edge_data);\n    dc.cout() << count << \" Triangles\"  << std::endl;\n  }\n  else {\n    graphlab::synchronous_engine<get_per_vertex_count> engine(dc, graph, clopts);\n    engine.signal_all();\n    engine.start();\n    graph.save(per_vertex,\n            save_triangle_count(),\n            false, /* no compression */\n            true, /* save vertex */\n            false, /* do not save edge */\n            1); /* one file per machine */\n\n  }\n  \n  graphlab::stop_metric_server();\n\n  graphlab::mpi_tools::finalize();\n  return EXIT_SUCCESS;\n} // End of main\n\n", "meta": {"hexsha": "d2754449b44a1d9479481c2b18afab4cc396fc23", "size": 12492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/graph_analytics/simple_undirected_triangle_count.cpp", "max_stars_repo_name": "coreyp1/graphlab", "max_stars_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 333.0, "max_stars_repo_stars_event_min_datetime": "2016-07-29T19:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:40:34.000Z", "max_issues_repo_path": "toolkits/graph_analytics/simple_undirected_triangle_count.cpp", "max_issues_repo_name": "HybridGraph/GraphLab-PowerGraph", "max_issues_repo_head_hexsha": "ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2016-09-15T00:31:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T07:51:07.000Z", "max_forks_repo_path": "toolkits/graph_analytics/simple_undirected_triangle_count.cpp", "max_forks_repo_name": "HybridGraph/GraphLab-PowerGraph", "max_forks_repo_head_hexsha": "ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 163.0, "max_forks_repo_forks_event_min_datetime": "2016-07-29T19:22:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:15:24.000Z", "avg_line_length": 32.1131105398, "max_line_length": 81, "alphanum_fraction": 0.6652257445, "num_tokens": 2952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.6688802603710086, "lm_q1q2_score": 0.42609732367638914}}
{"text": "/* Copyright 2020 Oinam Romesh Meitei\n  \n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n */\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <cmath>\n#include <vector>\n#include <typeinfo>\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <iomanip>\n\n#include \"getham.h\"\n#include \"agradc.h\"\n\ngradc grad_ana(\n\t       std::vector<double> &tlist,\n\t       std::vector<std::complex<double> > &ini_vec,\n\t       pulsec pobj,\n\t       std::vector< std::vector< Eigen::SparseMatrix\n\t       <double,0,ptrdiff_t> > > hdrive,\n\t       std::vector< std::complex<double> > dsham,\n\t       std::vector< int> &states,\n\t       Eigen::MatrixXcd &cHam){\n\n  Eigen::SparseMatrix<std::complex<double> > hamdr;\n  Eigen::SparseMatrix<std::complex<double> > hamdR;\n  std::complex<double> hcoef; //, hcoefc;\n  \n  int i,j;\n  int dsham_len = dsham.size();\n  int tlen = tlist.size();\n  int nstate = states.size();\n  int &nqubit = pobj.nqubit;\n  double energy;\n  \n  std::complex<double> psit_g;\n  \n  Eigen::SparseMatrix<std::complex<double> >\n    matexp_(dsham_len, dsham_len);\n\n  Eigen::SparseMatrix<std::complex<double> > hD, Hd_;\n  Eigen::MatrixXcd H1_, P_;\n  Eigen::VectorXcd psi_;\n  Eigen::VectorXcd states_(nstate);\n  \n  std::vector< Eigen::VectorXcd > O_(nqubit,\n\t\t\t\t     Eigen::VectorXcd (dsham_len));\n  \n  std::vector< Eigen::VectorXcd > g1__(nqubit,\n\t\t\t\t       Eigen::VectorXcd (dsham_len));\n  \n  std::vector< Eigen::VectorXcd > g1_(nqubit,\n\t\t\t\t       Eigen::VectorXcd (nstate));\n  \n  Eigen::Map<Eigen::VectorXcd> ket_(ini_vec.data(), ini_vec.size());\n  std::vector< Eigen::SparseMatrix<std::complex<double> > > hamd(nqubit);\n  std::vector<std::vector<double> > t_grad(nqubit,\n\t\t\t\t\t   std::vector<double> (tlen));\n    \n  double tau = tlist[tlen-1] / tlen;\n  std::complex<double> im(0.0,-tau);\n  std::complex<double> imp(0.0,tau);\n    \n  for (int t=0; t<tlen; t++){\n  \n    hD = getham2(tlist[t], t, pobj, hdrive, dsham, dsham_len, matexp_, hamd, hamdr, hamdR, hcoef);\n    H1_ = im * Eigen::MatrixXcd(hD);\n    ket_ = H1_.exp() * ket_;    \n  }\n\n  for (i=0; i<nqubit; i++){\n    g1__[i] = hamd[i] * ket_;\n  }\n\n  for (i=0; i<nstate; i++){\n    states_[i] = ket_[states[i]];\n  }\n  double nrm =  states_.norm();\n    \n  for (int i = 0; i<nqubit; i++){\n    for (int j=0; j<nstate; j++){\n      g1_[i][j] = g1__[i][states[j]];\n    }\n  }  \n\n  psi_ = cHam * states_;\n\n  std::complex<double> energy_ = states_.conjugate().transpose() * psi_;\n  energy = energy_.real();\n\n  psi_ = psi_.conjugate();\n  Eigen::Transpose<Eigen::VectorXcd> psi1_ = psi_.transpose();\n  P_ = Eigen::MatrixXcd::Identity(dsham_len, dsham_len);\n\n  double tau1 = 2.0 * tau;\n\n  for (i=0; i<nqubit; i++){\n    \n    psit_g = psi1_ * g1_[i];\n    t_grad[i][tlen-1] = tau1 * psit_g.imag();\n  }\n        \n  for (int idx=tlen-1; idx > 0; idx--){\n    Hd_ = getham3( tlist[idx], idx, pobj, hdrive, dsham, dsham_len, matexp_, hamdr, hamdR, hcoef);\n    hD = getham2(tlist[idx-1], idx-1, pobj, hdrive, dsham, dsham_len,\n\t\t matexp_, hamd, hamdr, hamdR, hcoef);\n\n\n    H1_ = (imp*Eigen::MatrixXcd(Hd_)).exp();\n    ket_ = H1_ * ket_;\n    P_ = P_ * H1_.conjugate().transpose();\n\n    for (i=0; i<nqubit; i++){\n      O_[i] = P_ * hamd[i] * ket_;\n    }\n    \n    for (i=0; i<nqubit; i++){\n      for (j=0; j<nstate; j++){\n\tg1_[i][j] = O_[i][states[j]];\n      }\n    }\n\n    for (i=0; i<nqubit; i++){\n      psit_g = psi1_ * g1_[i];\n      t_grad[i][idx-1] = tau1 * psit_g.imag();\n    }    \n  }  \n  gradc g1(energy, nrm, t_grad);\n    \n  return g1;\n}\n\n\ngradc grad_ana_normalized(\n                               std::vector<double> &tlist,\n                               std::vector<std::complex<double> > &ini_vec,\n                               pulsec pobj,\n                               std::vector< std::vector< Eigen::SparseMatrix\n\t\t\t       <double,0,ptrdiff_t> > > hdrive,\n                               std::vector< std::complex<double> > dsham,\n\t\t\t       std::vector< int> &states,\n\t\t\t       Eigen::MatrixXcd &cHam){\n\n  Eigen::SparseMatrix<std::complex<double> > hamdr;\n  Eigen::SparseMatrix<std::complex<double> > hamdR;\n  std::complex<double> hcoef; \n  \n  int i,j;\n  int dsham_len = dsham.size();\n  int tlen = tlist.size();\n  int nstate = states.size();\n  int &nqubit = pobj.nqubit;\n  double energy,nrm2, nrm4;\n  \n  std::complex<double> psit_g,psit_gN;\n  \n  Eigen::SparseMatrix<std::complex<double> >\n    matexp_(dsham_len, dsham_len);\n\n  Eigen::SparseMatrix<std::complex<double> > hD, Hd_;\n  Eigen::MatrixXcd H1_, P_;\n  Eigen::VectorXcd psi_,psi_N;\n  Eigen::VectorXcd states_(nstate);\n\n  std::vector< Eigen::VectorXcd > O_(nqubit,\n\t\t\t\t     Eigen::VectorXcd (dsham_len));\n  \n  std::vector< Eigen::VectorXcd > g1__(nqubit,\n\t\t\t\t       Eigen::VectorXcd (dsham_len));\n  \n  std::vector< Eigen::VectorXcd > g1_(nqubit,\n\t\t\t\t       Eigen::VectorXcd (nstate));\n  \n  Eigen::Map<Eigen::VectorXcd> ket_(ini_vec.data(), ini_vec.size());\n  std::vector< Eigen::SparseMatrix<std::complex<double> > > hamd(nqubit);\n  std::vector<std::vector<double> > t_grad(nqubit,\n\t\t\t\t\t   std::vector<double> (tlen));\n    \n  double tau = tlist[tlen-1] / tlen;\n  std::complex<double> im(0.0,-tau);\n  std::complex<double> imp(0.0,tau);\n    \n  for (int t=0; t<tlen; t++){\n  \n    hD = getham2(tlist[t], t, pobj, hdrive, dsham, dsham_len, matexp_, hamd, hamdr, hamdR, hcoef);\n    H1_ = im * Eigen::MatrixXcd(hD);\n    ket_ = H1_.exp() * ket_;    \n  }\n\n  for (i=0; i<nqubit; i++){\n    g1__[i] = hamd[i] * ket_;\n  }\n\n  for (i=0; i<nstate; i++){\n    states_[i] = ket_[states[i]];\n  }\n  double nrm =  states_.norm();\n  nrm2 = nrm*nrm;\n  nrm4 = nrm2*nrm2;\n    \n  for (int i = 0; i<nqubit; i++){\n    for (int j=0; j<nstate; j++){\n      g1_[i][j] = g1__[i][states[j]];\n    }\n  }  \n\n  psi_ = cHam * states_;\n  psi_N = states_;\n\n  std::complex<double> energy_ = states_.conjugate().transpose() * psi_;\n  energy = energy_.real();\n\n  psi_ = psi_.conjugate();\n  Eigen::Transpose<Eigen::VectorXcd> psi1_ = psi_.transpose();\n  psi_N = psi_N.conjugate();\n  Eigen::Transpose<Eigen::VectorXcd> psi1_N = psi_N.transpose();\n  P_ = Eigen::MatrixXcd::Identity(dsham_len, dsham_len);\n  double tau1 = 2.0 * tau;\n  nrm4 = tau1/nrm4;\n\n  for (i=0; i<nqubit; i++){\n    \n    psit_g = psi1_ * g1_[i];\n    psit_gN = psi1_N * g1_[i];  \n    t_grad[i][tlen-1] = (psit_g.imag()*nrm2 - energy*psit_gN.imag())*nrm4;    \n  }\n        \n  for (int idx=tlen-1; idx > 0; idx--){\n    Hd_ = getham3( tlist[idx], idx, pobj, hdrive, dsham, dsham_len, matexp_, hamdr, hamdR, hcoef);\n    hD = getham2(tlist[idx-1], idx-1, pobj, hdrive, dsham, dsham_len,\n\t\t matexp_, hamd, hamdr, hamdR, hcoef);\n\n    H1_ = (imp*Eigen::MatrixXcd(Hd_)).exp();\n    ket_ = H1_ * ket_;\n    P_ = P_ * H1_.conjugate().transpose();\n\n    for (i=0; i<nqubit; i++){\n      O_[i] = P_ * hamd[i] * ket_;\n    }\n    \n    for (i=0; i<nqubit; i++){\n      for (j=0; j<nstate; j++){\n\tg1_[i][j] = O_[i][states[j]];\n      }\n    }\n\n    for (i=0; i<nqubit; i++){\n      psit_g = psi1_ * g1_[i];\n      psit_gN = psi1_N * g1_[i];\n      t_grad[i][idx-1] = (psit_g.imag()*nrm2 - energy*psit_gN.imag())*nrm4;\n    }    \n  }\n  energy = energy/nrm2;\n  gradc g1(energy, nrm, t_grad);\n    \n  return g1;\n}\n", "meta": {"hexsha": "d9016ab7c660e32e3fb664b7e95a5941c7623a79", "size": 7671, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ctrlq/lib/grad_ana.cc", "max_stars_repo_name": "asthanaa/ctrlq", "max_stars_repo_head_hexsha": "4af7721ed679a1ac2d4147a9406fa794f2af64d8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-09-25T14:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T17:36:53.000Z", "max_issues_repo_path": "ctrlq/lib/grad_ana.cc", "max_issues_repo_name": "asthanaa/ctrlq", "max_issues_repo_head_hexsha": "4af7721ed679a1ac2d4147a9406fa794f2af64d8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-21T18:54:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-21T18:54:38.000Z", "max_forks_repo_path": "ctrlq/lib/grad_ana.cc", "max_forks_repo_name": "asthanaa/ctrlq", "max_forks_repo_head_hexsha": "4af7721ed679a1ac2d4147a9406fa794f2af64d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-18T18:19:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-26T13:48:44.000Z", "avg_line_length": 27.996350365, "max_line_length": 98, "alphanum_fraction": 0.5945769782, "num_tokens": 2637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397349, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.42608258252763936}}
{"text": "#include \"RefElement.h\"\n#include \"basis/Functions.h\"\n#include \"basis/Nodal.h\"\n#include \"quadrules/AutoRule.h\"\n#include \"tensor/EigenMap.h\"\n#include \"tensor/Reshape.h\"\n#include \"tensor/TensorBase.h\"\n#include \"util/Combinatorics.h\"\n#include \"util/Enumerate.h\"\n#include \"util/MultiIndex.h\"\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n\n#include <cassert>\n#include <cstddef>\n\nnamespace tndm {\n\ntemplate <std::size_t D> Managed<Matrix<double>> ModalRefElement<D>::massMatrix() const {\n    auto rule = simplexQuadratureRule<D>(2 * this->degree());\n    std::ptrdiff_t nbf = this->numBasisFunctions();\n    Managed<Matrix<double>> M({nbf, nbf}, this->alignment());\n    auto E = evaluateBasisAt(rule.points(), {0, 1});\n    for (std::ptrdiff_t i = 0; i < M.shape(0); ++i) {\n        for (std::ptrdiff_t j = 0; j < M.shape(1); ++j) {\n            M(i, j) = 0.0;\n            // The basis is orthogonal, therefore we only need to compute the diagonal\n            if (i == j) {\n                for (std::size_t q = 0; q < rule.size(); ++q) {\n                    M(i, j) += rule.weights()[q] * E(i, q) * E(j, q);\n                }\n            }\n        }\n    }\n\n    return M;\n}\n\ntemplate <std::size_t D> Managed<Matrix<double>> ModalRefElement<D>::inverseMassMatrix() const {\n    auto Minv = massMatrix();\n    for (std::ptrdiff_t i = 0; i < Minv.shape(0); ++i) {\n        Minv(i, i) = 1.0 / Minv(i, i);\n    }\n    return Minv;\n}\n\ntemplate <std::size_t D>\nManaged<Matrix<double>>\nModalRefElement<D>::evaluateBasisAt(std::vector<std::array<double, D>> const& points,\n                                    std::array<unsigned, 2> const& permutation) const {\n    using index_t = Matrix<double>::index_t;\n    auto shape =\n        permute(permutation, make_index<index_t>(this->numBasisFunctions(), points.size()));\n    Managed<Matrix<double>> E(shape, this->alignment());\n    for (std::size_t p = 0; p < points.size(); ++p) {\n        for (auto&& [bf, j] : enumerate(AllIntegerSums<D>(this->degree()))) {\n            auto index = permute(permutation, make_index<index_t>(bf, p));\n            E(index) = DubinerP(j, points[p]);\n        }\n    }\n    return E;\n}\n\ntemplate <std::size_t D>\nManaged<Tensor<double, 3u>>\nModalRefElement<D>::evaluateGradientAt(std::vector<std::array<double, D>> const& points,\n                                       std::array<unsigned, 3> const& permutation) const {\n    using index_t = Matrix<double>::index_t;\n    auto shape =\n        permute(permutation, make_index<index_t>(this->numBasisFunctions(), D, points.size()));\n    Managed<Tensor<double, 3u>> grad(shape, this->alignment());\n    for (std::size_t p = 0; p < points.size(); ++p) {\n        for (auto&& [bf, j] : enumerate(AllIntegerSums<D>(this->degree()))) {\n            auto dphi = gradDubinerP(j, points[p]);\n            for (std::size_t d = 0; d < D; ++d) {\n                auto index = permute(permutation, make_index<index_t>(bf, d, p));\n                grad(index) = dphi[d];\n            }\n        }\n    }\n    return grad;\n}\n\ntemplate <std::size_t D>\nNodalRefElement<D>::NodalRefElement(unsigned degree, NodesFactory<D> const& nodesFactory,\n                                    std::size_t alignment)\n    : RefElement<D>(degree, alignment), refNodes_(nodesFactory(degree)) {\n    assert(this->numBasisFunctions() == refNodes_.size());\n    vandermonde_ = Vandermonde(this->degree(), refNodes_);\n    vandermondeInv_ = vandermonde_.inverse();\n}\n\ntemplate <std::size_t D> Managed<Matrix<double>> NodalRefElement<D>::massMatrix() const {\n    std::ptrdiff_t nbf = this->numBasisFunctions();\n    Managed<Matrix<double>> M({nbf, nbf}, this->alignment());\n\n    Managed<Matrix<double>> modalM =\n        ModalRefElement<D>(this->degree(), this->alignment()).massMatrix();\n    EigenMap(M) = vandermondeInv_.transpose() * EigenMap(modalM) * vandermondeInv_;\n\n    return M;\n}\n\ntemplate <std::size_t D> Managed<Matrix<double>> NodalRefElement<D>::inverseMassMatrix() const {\n    std::ptrdiff_t nbf = this->numBasisFunctions();\n    Managed<Matrix<double>> Minv({nbf, nbf}, this->alignment());\n\n    Managed<Matrix<double>> modalMinv =\n        ModalRefElement<D>(this->degree(), this->alignment()).inverseMassMatrix();\n    EigenMap(Minv) = vandermonde_ * EigenMap(modalMinv) * vandermonde_.transpose();\n\n    return Minv;\n}\n\ntemplate <std::size_t D>\nManaged<Matrix<double>>\nNodalRefElement<D>::evaluateBasisAt(std::vector<std::array<double, D>> const& points,\n                                    std::array<unsigned, 2> const& permutation) const {\n    Managed<Matrix<double>> E =\n        ModalRefElement<D>(this->degree(), this->alignment()).evaluateBasisAt(points, permutation);\n    auto Emap = EigenMap(E);\n    if (permutation[0] == 0 && permutation[1] == 1) {\n        Emap = vandermondeInv_.transpose() * Emap;\n    } else if (permutation[0] == 1 && permutation[1] == 0) {\n        Emap = Emap * vandermondeInv_;\n    } else {\n        assert(false);\n    }\n    return E;\n}\n\ntemplate <std::size_t D>\nManaged<Tensor<double, 3u>>\nNodalRefElement<D>::evaluateGradientAt(std::vector<std::array<double, D>> const& points,\n                                       std::array<unsigned, 3> const& permutation) const {\n    Managed<Tensor<double, 3u>> gradE = ModalRefElement<D>(this->degree(), this->alignment())\n                                            .evaluateGradientAt(points, permutation);\n\n    assert(vandermondeInv_.cols() == vandermondeInv_.rows());\n    // 0,1,2 F_idq = V_ji E_jdq => F_i(dq) = V^T E_j(dq)\n    // 0,2,1 F_iqd = V_ji E_jqd => F_i(qd) = V^T E_j(qd)\n    if (permutation[0] == 0) {\n        assert((permutation[1] == 1 && permutation[2] == 2) ||\n               (permutation[1] == 2 && permutation[2] == 1));\n        auto mat = reshape(gradE, vandermondeInv_.rows(), D * points.size());\n        EigenMap(mat) = vandermondeInv_.transpose() * EigenMap(mat);\n    }\n    // 1,2,0 F_dqi = V_ji E_dqj => F_(dq)i = E_(dq)j V\n    // 2,1,0 F_qdi = V_ji E_qdj => F_(qd)i = E_(qd)j V\n    else if (permutation[2] == 0) {\n        assert((permutation[0] == 1 && permutation[1] == 2) ||\n               (permutation[0] == 2 && permutation[1] == 1));\n        auto mat = reshape(gradE, D * points.size(), vandermondeInv_.rows());\n        EigenMap(mat) = EigenMap(mat) * vandermondeInv_;\n    }\n    // 1,0,2 F_diq = V_ji E_djq => F_di[q] = E_dj[q] V\n    // 2,0,1 F_qid = V_ji E_qjd => F_qi[d] = E_qj[d] V\n    else {\n        assert((permutation[0] == 1 && permutation[2] == 2) ||\n               (permutation[0] == 2 && permutation[2] == 1));\n        for (decltype(gradE)::index_t i = 0; i < gradE.shape(2); ++i) {\n            auto mat = gradE.subtensor(slice{}, slice{}, i);\n            EigenMap(mat) = EigenMap(mat) * vandermondeInv_;\n        }\n    }\n\n    return gradE;\n}\n\ntemplate class ModalRefElement<1ul>;\ntemplate class ModalRefElement<2ul>;\ntemplate class ModalRefElement<3ul>;\ntemplate class NodalRefElement<1ul>;\ntemplate class NodalRefElement<2ul>;\ntemplate class NodalRefElement<3ul>;\n\n} // namespace tndm\n", "meta": {"hexsha": "dbbcaf9c24c3359c2aaae6596aac23b7ef33389d", "size": 6948, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/form/RefElement.cpp", "max_stars_repo_name": "NicoSchlw/tandem", "max_stars_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T17:11:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:51:01.000Z", "max_issues_repo_path": "src/form/RefElement.cpp", "max_issues_repo_name": "NicoSchlw/tandem", "max_issues_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-05-18T14:51:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T12:56:31.000Z", "max_forks_repo_path": "src/form/RefElement.cpp", "max_forks_repo_name": "NicoSchlw/tandem", "max_forks_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-23T08:04:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T12:23:59.000Z", "avg_line_length": 38.8156424581, "max_line_length": 99, "alphanum_fraction": 0.599884859, "num_tokens": 2019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.42608257720784254}}
{"text": "#include \"mex.h\"\n#include <math.h>\n#include <Eigen/Dense>\n\nusing namespace std;\n\nvoid constraints(mxArray* c_out, mxArray* ceq_out, mxArray* dc_out, mxArray* dceq_out, const Eigen::MatrixXd& x, size_t nc, size_t nceq, size_t nv, size_t nsteps)\n{\n  Eigen::MatrixXd steps = x.block(0, 0, 6, nsteps);\n  Eigen::MatrixXd rel_steps = x.block(6, 0, 6, nsteps);\n\n  Eigen::MatrixXd c(nc, 1);\n  c = Eigen::MatrixXd::Zero(nc, 1);\n  Eigen::VectorXd ceq(nceq);\n  ceq = Eigen::VectorXd::Zero(nceq);\n  Eigen::MatrixXd dc(nv, nsteps);\n  dc = Eigen::MatrixXd::Zero(nv, nc);\n  Eigen::MatrixXd dceq(nv, nceq);\n  dceq = Eigen::MatrixXd::Zero(nv, nceq);\n  Eigen::Matrix2d R;\n  Eigen::Vector2d dxy;\n  Eigen::Vector2d proj;\n  Eigen::Vector2d u;\n  Eigen::Vector2d al;\n\n  // ceq.segment(0,2) = steps.block(0,0,2,1) - rel_steps.block(0,0,2,1);\n  // dceq.block(0,0,2,2) << 1, 0, 0, 1;\n  // dceq.block(6,0,2,2) << -1, 0, 0, -1;\n\n  int j;\n  int x1_ndx;\n  int dx_ndx;\n  int x2_ndx;\n  int con_ndx;\n  int con_dndx;\n  double dx, dy, si, co;\n\n  for (j = 2; j <= nsteps; j++) {\n    con_ndx = (j-1)*2;\n    con_dndx = 2;\n    si = sin(steps(5,j-2));\n    co = cos(steps(5,j-2));\n    R << co, -si, si, co;\n    dxy = R * rel_steps.block(0,j-1,2,1);\n    proj = steps.block(0,j-2,2,1) + dxy;\n    ceq.segment(con_ndx, con_dndx) = steps.block(0,j-1,2,1) - proj;\n    x1_ndx = (j-2)*12;\n    dx_ndx = (j-1)*12+6;\n    x2_ndx = (j-1)*12;\n    dceq.block(x2_ndx,con_ndx,2,con_dndx) << 1, 0, 0, 1;\n    dceq.block(x1_ndx,con_ndx,2,con_dndx) << -1, 0, 0, -1;\n    dx = rel_steps(0,j-1);\n    dy = rel_steps(1,j-1);\n    dceq.block(x1_ndx+5,con_ndx,1,con_dndx) << dx*si + dy*co, -dx*co + dy*si;\n    dceq.block(dx_ndx,con_ndx,1,con_dndx) << -co, -si;\n    dceq.block(dx_ndx+1,con_ndx,1,con_dndx) << si, -co;\n  }\n\n  memcpy(mxGetPr(c_out), c.data(), sizeof(double)*c.rows()*c.cols());\n  memcpy(mxGetPr(dc_out), dc.data(), sizeof(double)*dc.rows()*dc.cols());\n  memcpy(mxGetPr(ceq_out), ceq.data(), sizeof(double)*ceq.rows()*ceq.cols());\n  memcpy(mxGetPr(dceq_out), dceq.data(), sizeof(double)*dceq.rows()*dceq.cols());\n\n  return;\n}\n\nvoid mexFunction( int nlhs, mxArray *plhs[],\n                  int nrhs, const mxArray *prhs[] )\n{\n  // [c_mex, ceq_mex, dc_mex, dceq_mex] = stepCollocationConstraintsMex(x);\n\n  size_t nv = mxGetM(prhs[0]);\n  size_t nsteps = nv / 12;\n  size_t nceq = 2 * nsteps;\n  size_t nc = 0;\n\n  Eigen::MatrixXd x = Eigen::Map<Eigen::MatrixXd>(mxGetPr(prhs[0]), 12, nsteps);\n\n  /* Create matrices for the return arguments. */\n  plhs[0] = mxCreateDoubleMatrix((mwSize)nc, (mwSize)1, mxREAL); // c\n  plhs[1] = mxCreateDoubleMatrix((mwSize)nceq, (mwSize)1, mxREAL); // ceq\n  plhs[2] = mxCreateDoubleMatrix((mwSize)nv, (mwSize)nc, mxREAL); // dc\n  plhs[3] = mxCreateDoubleMatrix((mwSize)nv, (mwSize)nceq, mxREAL); // dceq\n\n  /* Assign pointers to each output. */\n  mxArray* c = plhs[0];\n  mxArray* ceq = plhs[1];\n  mxArray* dc = plhs[2];\n  mxArray* dceq = plhs[3];\n\n  constraints(c, ceq, dc, dceq, x, nc, nceq, nv, nsteps);\n}", "meta": {"hexsha": "c14185b1f98295bc12222c4f201ee5b6f85218a4", "size": 2977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "systems/robotInterfaces/footstepCollocationConstraintsMex.cpp", "max_stars_repo_name": "jacob-izr/drake", "max_stars_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T09:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T21:59:27.000Z", "max_issues_repo_path": "systems/robotInterfaces/footstepCollocationConstraintsMex.cpp", "max_issues_repo_name": "jacob-izr/drake", "max_issues_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "systems/robotInterfaces/footstepCollocationConstraintsMex.cpp", "max_forks_repo_name": "jacob-izr/drake", "max_forks_repo_head_hexsha": "d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T19:37:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-29T19:37:28.000Z", "avg_line_length": 32.3586956522, "max_line_length": 162, "alphanum_fraction": 0.6207591535, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.42608257720784243}}
{"text": "/*\nCopyright (c) 2015 - 2016, Tianwei Shen\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of libvot nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n/** \\file svt.cpp\n *\t\\brief singular value threshold (immature)\n */\n#include <iostream>\n#include <vector>\n#include <sstream>\n#include <Eigen/Dense>\n#include <random>\n\n#include \"utils/io_utils.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nfloat Fnorm(Eigen::MatrixXf &f)\n{\n\tfloat norm = 0;\n\tfor (int i = 0; i < f.rows(); i++) {\n\t\tfor (int j = 0; j < f.cols(); j++) {\n\t\t\tnorm += f(i, j) * f(i, j);\n\t\t}\n\t}\n\treturn sqrt(norm);\n}\n\ndouble Fnorm(Eigen::MatrixXd &d)\n{\n\tdouble norm = 0;\n\tfor (int i = 0; i < d.rows(); i++) {\n\t\tfor (int j = 0; j < d.cols(); j++) {\n\t\t\tnorm += d(i, j) * d(i, j);\n\t\t}\n\t}\n\treturn sqrt(norm);\n}\n\n// sample_set.size() = d.rows();\nEigen::MatrixXd MatrixProjection(Eigen::MatrixXd &d, std::vector<std::vector<int> > sample_set)\n{\n\tEigen::MatrixXd pd = Eigen::MatrixXd::Constant(d.rows(), d.cols(), 0);\n\tfor (int i = 0; i < d.rows(); i++) {\n\t\tfor (int j = 0; j < sample_set[i].size(); j++) {\n\t\t\tpd(i, sample_set[i][j]) = d(i, sample_set[i][j]);\n\t\t}\n\t}\n\treturn pd;\n}\n\nint main(int argc, char ** argv)\n{\n\tif (argc != 2) {\n\t\tcout << \"Usage: \" << argv[0] << \" <mat_file>\\n\";\n\t\texit(-1);\n\t}\n\tconst char *mat_file = argv[1];\n\n\t// here we assume that the input matrix is a square matrix\n\tvector<string> mat_string;\n\ttw::IO::ExtractLines(mat_file, mat_string);\n\tint mat_size = mat_string.size();\n\tMatrixXd input_mat = MatrixXd::Constant(mat_size, mat_size, 0);\n\tfor (int i = 0; i < mat_size; i++) {\n\t\tstringstream ss;\n\t\tss << mat_string[i];\n\t\tfloat temp;\n\t\tfor (int j = 0; j < mat_size; j++) {\n\t\t\tss >> temp;\n\t\t\tinput_mat(i, j) = temp;\n\t\t}\n\t}\n\n\tMatrixXd sample_mat = MatrixXd::Constant(mat_size, mat_size, 0);\n\tconst float sample_ratio = 0.4;\n\tconst int sample_size = mat_size * sample_ratio;\n\tvector<vector<int> > sample_set;\n\tsample_set.resize(mat_size);\n\n\t// sample without replacement\n\tdefault_random_engine e(0);\n\tuniform_int_distribution<int> uni_rand(0, mat_size-1);\n\tfor (int i = 0; i < mat_size; i++) {\n\t\tfor (int j = 0; j < sample_size; j++) {\n\t\t\tint curr_sample = uni_rand(e);\n\t\t\tint k;\n\t\t\tfor (k = 0; k < j; k++) {\n\t\t\t\tif (curr_sample == sample_set[i][k]) {\n\t\t\t\t\tj--; k = -1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (k != -1) {\n\t\t\t\tsample_set[i].push_back(curr_sample);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (int i = 0; i < mat_size; i++) {\n\t\tfor (int j = 0; j < sample_set[i].size(); j++) {\n\t\t\tsample_mat(i, sample_set[i][j]) = input_mat(i, sample_set[i][j]);\n\t\t}\n\t}\n\n\tcout << sample_mat << endl;\n\n\t// singular value thresholding\n\tfloat step_size = 1.5;//1.2 * mat_size / sample_ratio;\n\tfloat tau = 5 * mat_size;\n\tint k0 = tau / (step_size * Fnorm(sample_mat)) + 1;\n\tint max_iter = 200;\n\tMatrixXd Y = k0 * step_size * sample_mat;\n\tMatrixXd X;\n\tdouble stop_threshold = 1e-4;\n\tfor (int i = 0; i < max_iter; i++) {\n\t\tJacobiSVD<MatrixXd> svd(Y, ComputeThinU | ComputeThinV);\n\t\tMatrixXd U = svd.matrixU();\n\t\tMatrixXd V = svd.matrixV();\n\t\tVectorXd singular_vector = svd.singularValues();\n\t\tMatrixXd S = MatrixXd::Constant(mat_size, mat_size, 0);\n\t\tfor (int i = 0; i < mat_size; i++) {\n\t\t\tif (singular_vector[i] > tau) {\n\t\t\t\tS(i, i) = singular_vector[i] - tau;\n\t\t\t}\n\t\t}\n\t\tX = U * S * V.transpose();\n\n\t\t// compute error\n\t\tMatrixXd residual_mat = X - sample_mat;\n\t\tMatrixXd residual_proj = MatrixProjection(residual_mat, sample_set);\n\t\tdouble error = Fnorm(residual_proj);\n\t\tdouble sample_mat_norm = Fnorm(sample_mat);\n\t\tif (error / sample_mat_norm < stop_threshold) {\n\t\t\tcout << \"break at iter \" << i << endl;\n\t\t\tbreak;\n\t\t}\n\n\t\t// refresh Y\n\t\tfor (int i = 0; i < sample_mat.rows(); i++) {\n\t\t\tfor (int j = 0; j < sample_set[i].size(); j++) {\n\t\t\t\tY(i, sample_set[i][j]) = Y(i, sample_set[i][j]) + step_size * (sample_mat(i, sample_set[i][j]) - X(i, sample_set[i][j]));\n\t\t\t}\n\t\t}\n\t}\n\n\t// compute completion error\n\tfloat completion_error = 0;\n\tfloat max_error = 0;\n\tfloat error_bound = 10;\n\tint within_bound_count = 0;\n\tfor (int i = 0; i < mat_size; i++) {\n\t\tfor (int j = 0; j < mat_size; j++) {\n\t\t\tcompletion_error += (X(i, j) - input_mat(i, j)) * (X(i, j) - input_mat(i, j));\n\t\t\tif (max_error < abs(X(i, j) - input_mat(i, j)) ) {\n\t\t\t\tmax_error = abs(X(i, j) - input_mat(i, j));\n\t\t\t}\n\t\t\tif (abs(X(i, j) - input_mat(i, j)) < error_bound) {\n\t\t\t\twithin_bound_count++;\n\t\t\t}\n\t\t}\n\t}\n\tMatrixXd error_mat = X - input_mat;\n\tfloat relative_error = Fnorm(error_mat) / Fnorm(input_mat);\n\tcout << \"completion_error \" << completion_error << endl;\n\tcout << \"max_error \" << max_error << endl;\n\tcout << \"within_bound_count \" << within_bound_count << endl;\n\tcout << \"relative_error \" << relative_error << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "58ac0e110708b5a73f6fa6764c5c29eca83c8af2", "size": 5978, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "software/libvot/src/examples/svt.cpp", "max_stars_repo_name": "zyxrrr/GraphSfM", "max_stars_repo_head_hexsha": "1af22ec17950ffc8a5c737a6a46f4465c40aa470", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 181.0, "max_stars_repo_stars_event_min_datetime": "2015-09-18T13:46:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T06:14:11.000Z", "max_issues_repo_path": "software/libvot/src/examples/svt.cpp", "max_issues_repo_name": "zyxrrr/GraphSfM", "max_issues_repo_head_hexsha": "1af22ec17950ffc8a5c737a6a46f4465c40aa470", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 23.0, "max_issues_repo_issues_event_min_datetime": "2015-12-29T21:39:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-31T10:44:36.000Z", "max_forks_repo_path": "software/libvot/src/examples/svt.cpp", "max_forks_repo_name": "zyxrrr/GraphSfM", "max_forks_repo_head_hexsha": "1af22ec17950ffc8a5c737a6a46f4465c40aa470", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 60.0, "max_forks_repo_forks_event_min_datetime": "2015-09-18T13:46:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T03:26:07.000Z", "avg_line_length": 29.89, "max_line_length": 125, "alphanum_fraction": 0.6580796253, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.6150878696277513, "lm_q1q2_score": 0.4260356740161267}}
{"text": "#include <set>\nusing namespace std;\n\n#include \"Denoising.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <Eigen/IterativeLinearSolvers>\n\ntypedef Eigen::MatrixXd Matrix;\ntypedef Eigen::SparseMatrix<double> SpMat;\ntypedef Eigen::Triplet<double> Triplet;\n\nbool operator<(const Vector3d& v1, const Vector3d& v2) {\n    if(v1[0] != v2[0]) return v1[0] < v2[0];\n    if(v1[1] != v2[1]) return v1[1] < v2[1];\n    return v1[2] < v1[2];\n}\n\nbool operator>(const Vector3d& v1, const Vector3d& v2) {\n    if(v1[0] != v2[0]) return v1[0] > v2[0];\n    if(v1[1] != v2[1]) return v1[1] > v2[1];\n    return v1[2] > v1[2];\n}\n\ndouble genrand_gauss(double mu, double sigma) {\n    double z = sqrt(-2.0 * log(genrand_real2())) * sin(2.0 * M_PI * genrand_real2());\n    return mu + sigma * z;\n}\n\nvoid addNoise(Mesh& mesh) {\n    init_genrand((unsigned long)time(NULL));\n    OpenMesh::VPropHandleT<Mesh::Point> vprop;\n    mesh.add_property(vprop);\n\n    Mesh::VertexIter v_it;\n    for(v_it = mesh.vertices_begin(); v_it != mesh.vertices_end(); ++v_it) {\n        double vx = genrand_gauss(0.0, 0.001);\n        double vy = genrand_gauss(0.0, 0.001);\n        double vz = genrand_gauss(0.0, 0.001);\n        mesh.property(vprop, *v_it) = mesh.point(*v_it) + Mesh::Point(vx, vy, vz);\n        mesh.set_point(*v_it, mesh.property(vprop, *v_it));\n    }\n    mesh.remove_property(vprop);\n}\n\nvoid denoise(Mesh& mesh) {\n    // Prepare coefficient matrices R and D.\n    Mesh::EdgeIter e_it;\n    Mesh::FaceVertexIter fv_it;\n\n    const int nVert = static_cast<int>(mesh.n_vertices());\n    const int nEdge = static_cast<int>(mesh.n_edges());\n\n    vector<Triplet> tripR;\n    vector<Triplet> tripD;\n\n    int ie = 0;\n    for(e_it = mesh.edges_begin(); e_it != mesh.edges_end(); ++e_it) {\n        Mesh::HalfedgeHandle heh = mesh.halfedge_handle(*e_it, 0);\n\n        Mesh::VertexHandle vh1 = mesh.to_vertex_handle(heh);\n        Mesh::VertexHandle vh3 = mesh.from_vertex_handle(heh);\n        Mesh::VertexHandle vh2 = mesh.opposite_vh(heh);\n        Mesh::VertexHandle vh4 = mesh.opposite_he_opposite_vh(heh);\n\n        int i1 = vh1.idx();\n        int i2 = vh2.idx();\n        int i3 = vh3.idx();\n        int i4 = vh4.idx();\n        if(i1 == -1 || i2 == -1 || i3 == -1 || i4 == -1) {\n            continue;\n        }\n\n        OpenMesh::Vec3f p1 = mesh.point(vh1);\n        OpenMesh::Vec3f p2 = mesh.point(vh2);\n        OpenMesh::Vec3f p3 = mesh.point(vh3);\n        OpenMesh::Vec3f p4 = mesh.point(vh4);\n\n        double S123 = 0.5 * OpenMesh::cross(p2 - p1, p2 - p3).norm();\n        double S134 = 0.5 * OpenMesh::cross(p4 - p1, p4 - p3).norm();\n        double l13  = (p1 - p3).norm();\n\n        double coef1 = (S123 * OpenMesh::dot(p4 - p3, p3 - p1) + S134 * OpenMesh::dot(p1 - p3, p3 - p2)) / (l13 * l13 * (S123 + S134));\n        double coef2 = S134 / (S123 + S134);\n        double coef3 = (S123 * OpenMesh::dot(p3 - p1, p1 - p4) + S134 * OpenMesh::dot(p2 - p1, p1 - p3)) / (l13 * l13 * (S123 + S134));\n        double coef4 = S123 / (S123 + S134);\n\n        tripR.push_back(Triplet(ie, i1, coef1));\n        tripR.push_back(Triplet(ie, i2, coef2));\n        tripR.push_back(Triplet(ie, i3, coef3));\n        tripR.push_back(Triplet(ie, i4, coef4));\n\n        tripD.push_back(Triplet(ie, i1, 1.0));\n        tripD.push_back(Triplet(ie, i2, -1.0));\n        tripD.push_back(Triplet(ie, i3, 1.0));\n        tripD.push_back(Triplet(ie, i4, -1.0));\n        ie++;\n    }\n\n    SpMat R(nEdge, nVert);\n    SpMat D(nEdge, nVert);\n    R.setFromTriplets(tripR.begin(), tripR.end());\n    D.setFromTriplets(tripD.begin(), tripD.end());\n\n    // Store vertex positions in the Eigen::Vector\n    Matrix pInit(nVert, 3);\n    Matrix pVec(nVert, 3);\n    Mesh::VertexIter v_it;\n    int ip = 0;\n    for(v_it = mesh.vertices_begin(); v_it != mesh.vertices_end(); ++v_it) {\n        Mesh::Point p = mesh.point(*v_it);\n        pInit(ip, 0) = p[0];\n        pInit(ip, 1) = p[1];\n        pInit(ip, 2) = p[2];\n\n        pVec(ip, 0) = p[0];\n        pVec(ip, 1) = p[1];\n        pVec(ip, 2) = p[2];\n        ip++;\n    }\n\n    // Prepare sparse matrix.\n    vector<Triplet> tripI(nVert);\n    for(int i=0; i<nVert; i++) {\n        tripI[i] = Triplet(i, i, 1.0);\n    }\n    SpMat I(nVert, nVert);\n    I.setFromTriplets(tripI.begin(), tripI.end());\n\n    // Solve linear problem.\n    double lambda = 1.0e-2;\n    double alpha  = 0.1;\n    double beta   = 1.0e-3;\n    double bmax   = 1.0;\n    double mu     = 2.0;\n\n    // Matrix pVec = pInit;\n    Matrix dlt(nEdge, 3);\n    while(beta < bmax) {\n        // solve sub-problem for delta (shrinkage operator)\n        Matrix y = D * pVec;\n        for(int i=0; i<nEdge; i++) {\n            dlt(i, 0) = 0.0;\n            for(int d=0; d<3; d++) {\n                dlt(i, 0) += y(i, d) * y(i, d);\n            }\n            \n            if(dlt(i, 0) < lambda / beta) {\n                dlt(i, 0) = 0.0;\n            }\n\n            dlt(i, 1) = dlt(i, 0);\n            dlt(i, 2) = dlt(i, 0);\n        }\n\n        // solve sub-problem for points (linear system)\n        SpMat  A = I + alpha * R.transpose() * R + beta * D.transpose() * D;\n        Matrix b = pInit + beta * D.transpose() * dlt;\n\n        Eigen::ConjugateGradient<SpMat> solver;\n        solver.compute(A);\n        pVec = solver.solve(b);\n        if(solver.info() != Eigen::Success) {\n            printf(\"Solve linear system failed.\\n\");\n        }\n        \n        // update parameters\n        printf(\".\");\n        beta  *= mu;\n        alpha *= 0.5;\n    }\n    printf(\"\\n\");\n\n    // Update vertex information_OBJMESH_H_\n    OpenMesh::VPropHandleT<Mesh::Point> vprop;\n    mesh.add_property(vprop);\n    ip = 0;\n    for(v_it = mesh.vertices_begin(); v_it != mesh.vertices_end(); ++v_it) {\n        mesh.property(vprop, *v_it) = Mesh::Point(pVec(ip, 0), pVec(ip, 1), pVec(ip, 2));\n        mesh.set_point(*v_it, mesh.property(vprop, *v_it));\n        ip++;\n    }\n    mesh.remove_property(vprop);\n}\n", "meta": {"hexsha": "90f756644d34f670ac295bb4a1108844b0e5f9ce", "size": 5874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/denoising.cpp", "max_stars_repo_name": "tatsy/L0Denoising", "max_stars_repo_head_hexsha": "3a881bce8993162b9283e4ff94ab9146267c1008", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-02-25T10:27:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-10T10:40:59.000Z", "max_issues_repo_path": "sources/denoising.cpp", "max_issues_repo_name": "tatsy/L0Denoising", "max_issues_repo_head_hexsha": "3a881bce8993162b9283e4ff94ab9146267c1008", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-24T07:33:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-31T00:57:03.000Z", "max_forks_repo_path": "sources/denoising.cpp", "max_forks_repo_name": "tatsy/L0Denoising", "max_forks_repo_head_hexsha": "3a881bce8993162b9283e4ff94ab9146267c1008", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-02-28T02:18:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T17:33:34.000Z", "avg_line_length": 31.5806451613, "max_line_length": 135, "alphanum_fraction": 0.5527749404, "num_tokens": 1949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4260141818839427}}
{"text": "#ifndef URASTER_HPP\n#define URASTER_HPP\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/LU>\t//for .inverse().  Probably not needed\n#include <vector>\n#include <array>\n#include <memory>\n#include <functional>\n\nnamespace uraster {\n\n\tclass Pixel {\n\t\tpublic:\n\t\t\tEigen::Vector4f color;\n\t\t\tfloat& depth() {\n\t\t\t\treturn color[3];\n\t\t\t}\n\t\t\tPixel():color(0.0f,0.0f,0.0f,-1e10f) {\n\t\t\t}\n\t};\n\n\tbool _wireframe = false;\n\n\n\t//This is the framebuffer class.  It's a part of namespace uraster because the uraster needs to have a well-defined image class to render to.\n\t//It is templated because the output type need not be only colors, could contain anything (like a stencil buffer or depth buffer or gbuffer for deferred rendering)\n\ttemplate<class PixelType>\n\t\tclass Framebuffer {\n\t\t\tprotected:\n\t\t\t\tstd::vector<PixelType> data;\n\t\t\tpublic:\n\t\t\t\tconst std::size_t width;\n\t\t\t\tconst std::size_t height;\n\t\t\t\t//constructor initializes the array\n\t\t\t\tFramebuffer(std::size_t w,std::size_t h):\n\t\t\t\t\tdata(w*h),\n\t\t\t\t\twidth(w),height(h) {\n\t\t\t\t\t}\n\t\t\t\t//2D pixel access\n\t\t\t\tPixelType& operator()(std::size_t x,std::size_t y) {\n\t\t\t\t\treturn data[y*width+x];\n\t\t\t\t}\n\t\t\t\t//const version\n\t\t\t\tconst PixelType& operator()(std::size_t x,std::size_t y) const {\n\t\t\t\t\treturn data[y*width+x];\n\t\t\t\t}\n\t\t\t\tvoid clear(const PixelType& pt=PixelType()) {\n\t\t\t\t\tstd::fill(data.begin(),data.end(),pt);\n\t\t\t\t}\n\t\t};\n\n\t//This function runs the vertex shader on all the vertices, producing the varyings that will be interpolated by the rasterizer.\n\t//VertexVsIn can be anything, VertexVsOut MUST have a position() method that returns a 4D vector, and it must have an overloaded *= and += operator for the interpolation\n\t//The right way to think of VertexVsOut is that it is the class you write containing the varying outputs from the vertex shader.\n\ttemplate<class VertexVsIn,class VertexVsOut,class VertShader>\n\t\tvoid run_vertex_shader(const VertexVsIn* b,const VertexVsIn* e,VertexVsOut* o,\n\t\t\t\tVertShader vertex_shader) {\n\t\t\tstd::size_t n=e-b;\n#pragma omp parallel for\n\t\t\tfor(std::size_t i=0; i<n; i++) {\n\t\t\t\to[i]=vertex_shader(b[i]);\n\t\t\t}\n\t\t}\n\tstruct BarycentricTransform {\n\t\tprivate:\n\t\t\tEigen::Vector2f offset;\n\t\t\tEigen::Matrix2f Ti;\n\t\tpublic:\n\t\t\tBarycentricTransform(const Eigen::Vector2f& s1,const Eigen::Vector2f& s2,const Eigen::Vector2f& s3):\n\t\t\t\toffset(s3) {\n\t\t\t\t\tEigen::Matrix2f T;\n\t\t\t\t\tT << (s1-s3),(s2-s3);\n\t\t\t\t\tTi=T.inverse();\n\t\t\t\t}\n\t\t\tEigen::Vector3f operator()(const Eigen::Vector2f& v) const {\n\t\t\t\tEigen::Vector2f b;\n\t\t\t\tb=Ti*(v-offset);\n\t\t\t\treturn Eigen::Vector3f(b[0],b[1],1.0f-b[0]-b[1]);\n\t\t\t}\n\t};\n\n\tvoid line(int x0, int y0, int x1, int y1, uraster::Framebuffer<uraster::Pixel>& fp, Eigen::Array2i ul, Eigen::Array2i lr)\n\t{\n\t\tint dx =  abs(x1-x0), sx = x0<x1 ? 1 : -1;\n\t\tint dy = -abs(y1-y0), sy = y0<y1 ? 1 : -1;\n\t\tint err = dx+dy, e2; /* error value e_xy */\n\t\turaster::Pixel p;\n\t\tp.color = Eigen::Vector4f(1, 1, 1, 1);\n\n\t\twhile(1) {\n\t\t\tif (x0 < ul[0]) x0 = ul[0];\n\t\t\tif (x0 >= lr[0]) x0 = lr[0]-1;\n\t\t\tif (y0 < ul[1]) y0 = ul[1];\n\t\t\tif (y0 >= lr[1]) y0 = lr[1]-1;\n\t\t\tfp(x0, y0) = p;\n\t\t\t//fp(x0+1, y0) = p;\n\t\t\t//fp(x0, y0+1) = p;\n\t\t\t//fp(x0+1, y0+1) = p;\n\t\t\t//fp(x0-1, y0) = p;\n\t\t\t//fp(x0, y0-1) = p;\n\t\t\t//fp(x0-1, y0-1) = p;\n\t\t\tif (x0==x1 && y0==y1) break;\n\t\t\te2 = 2*err;\n\t\t\tif (e2 > dy) { err += dy; x0 += sx; } /* e_xy+e_x > 0 */\n\t\t\tif (e2 < dx) { err += dx; y0 += sy; } /* e_xy+e_y < 0 */\n\t\t}\n\t}\n\n\t//This function takes in 3 varyings vertices from the vertex shader that make up a triangle,\n\t//rasterizes the triangle and runs the fragment shader on each resulting pixel.\n\ttemplate<class PixelOut,class VertexVsOut,class FragShader>\n\t\tvoid rasterize_triangle(Framebuffer<PixelOut>& fb,const std::array<VertexVsOut,3>& verts,FragShader fragment_shader) {\n\t\t\tstd::array<Eigen::Vector4f,3> points {{verts[0].position(),verts[1].position(),verts[2].position()}};\n\t\t\t//Do the perspective divide by w to get screen space coordinates.\n\t\t\tstd::array<Eigen::Vector4f,3> epoints {{points[0]/points[0][3],points[1]/points[1][3],points[2]/points[2][3]}};\n\t\t\tauto ss1=epoints[0].head<2>().array(),ss2=epoints[1].head<2>().array(),ss3=epoints[2].head<2>().array();\n\n\t\t\t//calculate the bounding box of the triangle in screen space floating point.\n\t\t\tEigen::Array2f bb_ul=ss1.min(ss2).min(ss3);\n\t\t\tEigen::Array2f bb_lr=ss1.max(ss2).max(ss3);\n\t\t\tEigen::Array2i isz(fb.width,fb.height);\n\n\t\t\t//convert bounding box to fixed point.\n\t\t\t//move bounding box from (-1.0,1.0)->(0,imgdim)\n\t\t\tEigen::Array2i ibb_ul=((bb_ul*0.5f+0.5f)*isz.cast<float>()).cast<int>();\n\t\t\tEigen::Array2i ibb_lr=((bb_lr*0.5f+0.5f)*isz.cast<float>()).cast<int>();\n\t\t\tibb_lr+=1;\t//add one pixel of coverage\n\n\t\t\t//clamp the bounding box to the framebuffer size if necessary\n\t\t\tibb_ul=ibb_ul.max(Eigen::Array2i(0,0));\n\t\t\tibb_lr=ibb_lr.min(isz);\n\n\n\t\t\tBarycentricTransform bt(ss1.matrix(),ss2.matrix(),ss3.matrix());\n\n\t\t\t\tstatic uraster::Framebuffer<uraster::Pixel> tp(fb.width, fb.height); // mask pixels to draw\n\t\t\tif (_wireframe) {\n\n\t\t\tint x001 = 0, x010 = 0, x100 = 0;\n\t\t\tint y001 = 0, y010 = 0, y100 = 0;\n\t\t\tEigen::Vector2f ex_001(1.0, -1.0), ex_010(1.0, -1.0), ex_100(1.0, -1.0);\n\t\t\t// find the extremities in barycentric coordinates of each corner of the\n\t\t\t// vertex in viewport coordinates\n\n\t\t\tbool visible = false, set_1 = false, set_2 = false, set_3 = false;\n\t\t\t// tell the fragment shader to only draw these in $color\n\t\t\tfor(int y=ibb_ul[1]; y<ibb_lr[1]; y++) {\n\t\t\t\tfor(int x=ibb_ul[0]; x<ibb_lr[0]; x++) {\n\t\t\t\t\tEigen::Vector2f ssc(x, y);\n\t\t\t\t\tssc.array()/=isz.cast<float>();\t//move pixel to relative coordinates\n\t\t\t\t\tssc.array()-=0.5f;\n\t\t\t\t\tssc.array()*=2.0f;\n\n\t\t\t\t\t//Compute barycentric coordinates of the pixel center\n\t\t\t\t\tEigen::Vector3f bary=bt(ssc);\n\n\t\t\t\t\t//if the pixel has valid barycentric coordinates, the pixel is in the triangle\n\t\t\t\t\tif(!((bary.array() <= 1.0f).all() && (bary.array() >= 0.0f).all())) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tvisible = true;\n\n\t\t\t\t\tif (bary[0] + bary[1] < ex_001[0] || bary[2] > ex_001[1]) {\n\t\t\t\t\t//if (bary[2] > ex_001[1]) {\n\t\t\t\t\t\tex_001[0] = bary[0] + bary[1];\n\t\t\t\t\t\tex_001[1] = bary[2];\n\t\t\t\t\t\tx001 = x;\n\t\t\t\t\t\ty001 = y;\n\t\t\t\t\t\tset_1 = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (bary[0] + bary[2] < ex_010[0] || (bary[1] > ex_010[1])) {\n\t\t\t\t\t//if (bary[1] > ex_010[1]) {\n\t\t\t\t\t\tex_010[0] = bary[0] + bary[2];\n\t\t\t\t\t\tex_010[1] = bary[1];\n\t\t\t\t\t\tx010 = x;\n\t\t\t\t\t\ty010 = y;\n\t\t\t\t\t\tset_2 = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (bary[1] + bary[2] < ex_100[0] || (bary[0] > ex_100[1])) {\n\t\t\t\t\t//if (bary[0] > ex_100[1]) {\n\t\t\t\t\t\tex_100[0] = bary[1] + bary[2];\n\t\t\t\t\t\tex_100[1] = bary[0];\n\t\t\t\t\t\tx100 = x;\n\t\t\t\t\t\ty100 = y;\n\t\t\t\t\t\tset_3 = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\t\ttp.clear();\n\t\t\t\tif (visible && set_1 && set_2 && set_3) {\n\t\t\t\t\tline(x001, y001, x010, y010, tp, ibb_ul, ibb_lr);\n\t\t\t\t\tline(x010, y010, x100, y100, tp, ibb_ul, ibb_lr);\n\t\t\t\t\tline(x100, y100, x001, y001, tp, ibb_ul, ibb_lr);\n\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t//\n\n\t\t\t\t//std::cout << coords.size() << \" \";\n\n\t\t\t\t// calculate all display coordinates of projected edges of the triangle\n\n\n\t\t\t\t//std::cout << ex_001 << std::endl << ex_010 << std::endl << ex_100 << std::endl;\n\t\t\t\t//exit(1);\n\t\t\t\tauto a = verts[2].p - verts[1].p;\n\t\t\t\tauto b = verts[1].p - verts[0].p;\n\t\t\t\tEigen::Vector3f c(a[0], a[1], a[2]);\n\t\t\t\tEigen::Vector3f d(b[0], b[1], b[2]);\n\t\t\t\tauto normal = c.cross(d).normalized();\n\n\t\t\t\t//for all the pixels in the bounding box\n\t\t\t\tfor(int y=ibb_ul[1]; y<ibb_lr[1]; y++) {\n\t\t\t\t\tfor(int x=ibb_ul[0]; x<ibb_lr[0]; x++) {\n\t\t\t\t\t\tEigen::Vector2f ssc(x,y);\n\t\t\t\t\t\tssc.array()/=isz.cast<float>();\t//move pixel to relative coordinates\n\t\t\t\t\t\tssc.array()-=0.5f;\n\t\t\t\t\t\tssc.array()*=2.0f;\n\n\t\t\t\t\t\t//Compute barycentric coordinates of the pixel center\n\t\t\t\t\t\tEigen::Vector3f bary=bt(ssc);\n\n\t\t\t\t\t\t//if the pixel has valid barycentric coordinates, the pixel is in the triangle\n\t\t\t\t\t\tif(!((bary.array() < 1.0f).all() && (bary.array() > 0.0f).all())) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfloat d=bary[0]*epoints[0][2]+bary[1]*epoints[1][2]+bary[2]*epoints[2][2];\n\t\t\t\t\t\t//Reference the current pixel at that coordinate\n\t\t\t\t\t\tPixelOut& po=fb(x,y);\n\t\t\t\t\t\t// if the interpolated depth passes the depth test\n\t\t\t\t\t\tif(po.depth() >= d || d > 1.0) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//interpolate varying parameters\n\t\t\t\t\t\tVertexVsOut v;\n\t\t\t\t\t\tfor(int i=0; i<3; i++) {\n\t\t\t\t\t\t\tVertexVsOut vt=verts[i];\n\t\t\t\t\t\t\tvt*=bary[i];\n\t\t\t\t\t\t\tv+=vt;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (_wireframe) {\n\t\t\t\t\t\tif (tp(x, y).color[0] == 1) {\n\t\t\t\t\t\t\tv.p[3] = 0.0;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tv.p[3] = 0.5;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tv.p[0] = normal[0];\n\t\t\t\t\t\tv.p[1] = normal[1];\n\t\t\t\t\t\tv.p[2] = normal[2];\n\t\t\t\t\t\t//call the fragment shader\n\t\t\t\t\t\tpo=fragment_shader(v);\n\t\t\t\t\t\tpo.depth()=d; //write the depth buffer\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t//This function rasterizes a set of triangles determined by an index buffer and a buffer of output verts.\n\t\t\t\t\ttemplate<class PixelOut,class VertexVsOut,class FragShader>\n\t\t\t\t\t\tvoid rasterize(Framebuffer<PixelOut>& fb,const std::size_t* ib,const std::size_t* ie,const VertexVsOut* verts,\n\t\t\t\t\t\t\t\tFragShader fragment_shader) {\n\t\t\t\t\t\t\tstd::size_t n=ie-ib;\n#pragma omp parallel for\n\t\t\t\t\t\t\tfor(std::size_t i=0; i<n; i+=3) {\n\t\t\t\t\t\t\t\tconst std::size_t* ti=ib+i;\n\t\t\t\t\t\t\t\tstd::array<VertexVsOut,3> tri {{verts[ti[0]],verts[ti[1]],verts[ti[2]]}};\n\t\t\t\t\t\t\t\trasterize_triangle(fb,tri,fragment_shader);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t//This function does a draw call from an indexed buffer\n\t\t\t\t\ttemplate<class PixelOut,class VertexVsOut,class VertexVsIn,class VertShader, class FragShader>\n\t\t\t\t\t\tvoid draw(Framebuffer<PixelOut>& fb,\n\t\t\t\t\t\t\t\tconst VertexVsIn* vertexbuffer_b,const VertexVsIn* vertexbuffer_e,\n\t\t\t\t\t\t\t\tconst std::size_t* indexbuffer_b,const std::size_t* indexbuffer_e,\n\t\t\t\t\t\t\t\tVertexVsOut* vcache_b,VertexVsOut* vcache_e,\n\t\t\t\t\t\t\t\tVertShader vertex_shader,\n\t\t\t\t\t\t\t\tFragShader fragment_shader, bool wireframe = false) {\n\t\t\t\t\t\t\tstd::unique_ptr<VertexVsOut[]> vc;\n\t\t\t\t\t\t\t_wireframe = wireframe;\n\t\t\t\t\t\t\tif(vcache_b==NULL || (vcache_e-vcache_b) != (vertexbuffer_e-vertexbuffer_b)) {\n\t\t\t\t\t\t\t\tvcache_b=new VertexVsOut[(vertexbuffer_e-vertexbuffer_b)];\n\t\t\t\t\t\t\t\tvc.reset(vcache_b);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trun_vertex_shader(vertexbuffer_b,vertexbuffer_e,vcache_b,vertex_shader);\n\t\t\t\t\t\t\trasterize(fb,indexbuffer_b,indexbuffer_e,vcache_b,fragment_shader);\n\t\t\t\t\t\t}\n\n\t\t\t\t\tstruct VertVsOut {\n\t\t\t\t\t\tEigen::Vector4f p;\n\t\t\t\t\t\tEigen::Vector3f color;\n\n\t\t\t\t\t\tVertVsOut():\n\t\t\t\t\t\t\tp(0.0f,0.0f,0.0f,0.0f),color(0.0f,0.0f,0.0f) {\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tconst Eigen::Vector4f& position() const {\n\t\t\t\t\t\t\treturn p;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tVertVsOut& operator+=(const VertVsOut& tp) {\n\t\t\t\t\t\t\tp+=tp.p;\n\t\t\t\t\t\t\tcolor+=tp.color;\n\t\t\t\t\t\t\treturn *this;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tVertVsOut& operator*=(const float& f) {\n\t\t\t\t\t\t\tp*=f;\n\t\t\t\t\t\t\tcolor*=f;\n\t\t\t\t\t\t\treturn *this;\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\t//VertVsOut example_vertex_shader(const Eigen::Vector3f& vin,const Eigen::Matrix4f& mvp,float t) {\n\t\t\t\t\t//\tVertVsOut vout;\n\t\t\t\t\t//\tvout.p=mvp*Eigen::Vector4f(vin[0],vin[1],vin[2],1.0f);\n\t\t\t\t\t//\t//vout.p[3]=1.0f;\n\t\t\t\t\t//\tvout.color=Eigen::Vector3f(1.0f,static_cast <float> (rand()) / static_cast <float> (RAND_MAX),0.0f);\n\t\t\t\t\t//\treturn vout;\n\t\t\t\t\t//}\n\n\t\t\t\t\t//Pixel example_fragment_shader(const VertVsOut& fsin) {\n\t\t\t\t\t//\tPixel p;\n\t\t\t\t\t//\tp.color.head<3>()=fsin.color;\n\t\t\t\t\t//\treturn p;\n\t\t\t\t\t//}\n\t\t\t\t\t// example end\n\n\t\t\t\t}\n\n#endif\n", "meta": {"hexsha": "b20def565391ac4e627919b60c45c10966567b1d", "size": 11161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "uraster.hpp", "max_stars_repo_name": "psychoticbeef/3dfromintensity", "max_stars_repo_head_hexsha": "ae63a1fb2e3de9c92d7b1fa6cd09ba59f5d60554", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "uraster.hpp", "max_issues_repo_name": "psychoticbeef/3dfromintensity", "max_issues_repo_head_hexsha": "ae63a1fb2e3de9c92d7b1fa6cd09ba59f5d60554", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "uraster.hpp", "max_forks_repo_name": "psychoticbeef/3dfromintensity", "max_forks_repo_head_hexsha": "ae63a1fb2e3de9c92d7b1fa6cd09ba59f5d60554", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6174698795, "max_line_length": 170, "alphanum_fraction": 0.6077412418, "num_tokens": 3818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4260141818839425}}
{"text": "#include \"rotation.h\"\n#include \"himan_common.h\"\n#include <Eigen/Geometry>\n\nusing namespace Eigen;\n\ntemplate <typename T>\nvoid himan::geoutil::rotate(himan::geoutil::position<T>& p, const himan::geoutil::rotation<T>& r)\n{\n\t// Map data structures to Eigen library objects\n\tMap<Matrix<T, 3, 1>> P(p.Data());\n\tMap<const Quaternion<T>> QR(r.Data());\n\n\t// Create a corresponding quaternion of the input position vector\n\tQuaternion<T> QP;\n\tQP.w() = 0;\n\tQP.vec() = P;\n\n\t// Apply spatial rotation through quaternion products\n\tQuaternion<T> rotatedP = QR * QP * QR.inverse();\n\tP = rotatedP.vec();\n}\ntemplate void himan::geoutil::rotate<float>(himan::geoutil::position<float>&, const himan::geoutil::rotation<float>&);\ntemplate void himan::geoutil::rotate<double>(himan::geoutil::position<double>&,\n                                             const himan::geoutil::rotation<double>&);\n\ntemplate <typename T>\nhiman::geoutil::position<T> himan::geoutil::rotate(const himan::geoutil::position<T>& p,\n                                                   const himan::geoutil::rotation<T>& r)\n{\n\tposition<T> ret(p);\n\trotate(ret, r);\n\treturn ret;\n}\ntemplate himan::geoutil::position<float> himan::geoutil::rotate<float>(const himan::geoutil::position<float>&,\n                                                                       const himan::geoutil::rotation<float>&);\ntemplate himan::geoutil::position<double> himan::geoutil::rotate<double>(const himan::geoutil::position<double>&,\n                                                                         const himan::geoutil::rotation<double>&);\n\ntemplate <typename T>\nhiman::geoutil::rotation<T> himan::geoutil::rotation<T>::FromRotLatLon(const T& latOfSouthPole, const T& lonOfSouthPole,\n                                                                       const T& angleOfRot)\n{\n\thiman::geoutil::rotation<T> ret;\n\n\t// Map data structures to Eigen library objects\n\tMap<Quaternion<T>> QRot(ret.Data());\n\n\t// Create a rotation quaternion from product of a series of rotations about principle axis\n\tQRot = AngleAxis<T>(lonOfSouthPole, Matrix<T, 3, 1>::UnitZ()) *\n\t       AngleAxis<T>(-(T(M_PI / 2.0) + latOfSouthPole), Matrix<T, 3, 1>::UnitY()) *\n\t       AngleAxis<T>(-angleOfRot, Matrix<T, 3, 1>::UnitZ());\n\n\treturn ret;\n}\ntemplate himan::geoutil::rotation<float> himan::geoutil::rotation<float>::FromRotLatLon(const float& latOfSouthPole,\n                                                                                        const float& lonOfSouthPole,\n                                                                                        const float& angleOfRot);\ntemplate himan::geoutil::rotation<double> himan::geoutil::rotation<double>::FromRotLatLon(const double& latOfSouthPole,\n                                                                                          const double& lonOfSouthPole,\n                                                                                          const double& angleOfRot);\n\ntemplate <typename T>\nhiman::geoutil::rotation<T> himan::geoutil::rotation<T>::ToRotLatLon(const T& latOfSouthPole, const T& lonOfSouthPole,\n                                                                     const T& angleOfRot)\n{\n\thiman::geoutil::rotation<T> ret;\n\t// Map data structures to Eigen library objects\n\tMap<Quaternion<T>> QRot(ret.Data());\n\n\t// Create a rotation quaternion from product of a series of rotations about principle axis\n\tQRot = AngleAxis<T>(angleOfRot, Matrix<T, 3, 1>::UnitZ()) *\n\t       AngleAxis<T>(T(M_PI / 2.0) + latOfSouthPole, Matrix<T, 3, 1>::UnitY()) *\n\t       AngleAxis<T>(-lonOfSouthPole, Matrix<T, 3, 1>::UnitZ());\n\n\treturn ret;\n}\ntemplate himan::geoutil::rotation<float> himan::geoutil::rotation<float>::ToRotLatLon(const float& latOfSouthPole,\n                                                                                      const float& lonOfSouthPole,\n                                                                                      const float& angleOfRot);\ntemplate himan::geoutil::rotation<double> himan::geoutil::rotation<double>::ToRotLatLon(const double& latOfSouthPole,\n                                                                                        const double& lonOfSouthPole,\n                                                                                        const double& angleOfRot);\n", "meta": {"hexsha": "be174d641f33634657deb856aaf02cde35afea5c", "size": 4331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "himan-lib/source/rotation.cpp", "max_stars_repo_name": "fox91/himan", "max_stars_repo_head_hexsha": "4bb0ba4b034675edb21a1b468c0104f00f78784b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2017-04-20T18:51:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T21:12:49.000Z", "max_issues_repo_path": "himan-lib/source/rotation.cpp", "max_issues_repo_name": "fox91/himan", "max_issues_repo_head_hexsha": "4bb0ba4b034675edb21a1b468c0104f00f78784b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-07-05T02:15:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T09:36:51.000Z", "max_forks_repo_path": "himan-lib/source/rotation.cpp", "max_forks_repo_name": "fox91/himan", "max_forks_repo_head_hexsha": "4bb0ba4b034675edb21a1b468c0104f00f78784b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-18T06:32:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-29T15:17:09.000Z", "avg_line_length": 51.5595238095, "max_line_length": 120, "alphanum_fraction": 0.5472177326, "num_tokens": 951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.42595206973351163}}
{"text": "#ifndef _BAYES_FILTER__MODELS\n#define _BAYES_FILTER__MODELS\n\n/*\n * Bayes++ the Bayesian Filtering Library\n * Copyright (c) 2002 Michael Stevens\n * See accompanying Bayes++.htm for terms and conditions of use.\n *\n * $Id: models.hpp 634 2010-08-15 16:39:44Z mistevens $\n */\n\n/*\n * Predict and Observe models\n *  These models extend, adapt and simplify the fundamental Bayesian filter models\n *  Simple : Simplify model construction and use\n *  General: Generalise a model so it include properties of more then one model\n *  Adapted: Adapt one model type into another\n */\n#include <boost/function.hpp>\n\n/* Filter namespace */\nnamespace Bayesian_filter\n{\n\ntypedef boost::function1<const FM::Vec&, const FM::Vec&> State_function;\n// A generalised function of state. Compatible with predict and observe models\n\n\nclass Simple_additive_predict_model : public Additive_predict_model\n// Additive predict model initialised from function and model matricies\n{\n\tState_function ff;\npublic:\n\tSimple_additive_predict_model (State_function f_init, const FM::Matrix& G_init, const FM::Vec& q_init);\n\t// Precondition: G, q are conformantly dimensioned (not checked)\n\n\t// No default assignment operator\n\n\tvirtual const FM::Vec& f(const FM::Vec& x) const\n\t{\treturn ff(x);\n\t}\n};\n\nclass Simple_linrz_predict_model : public Linrz_predict_model\n// Linrz predict model initialised from function and model matrices\n{\n\tState_function ff;\npublic:\n\tSimple_linrz_predict_model (State_function f_init, const FM::Matrix& Fx_init, const FM::Matrix& G_init, const FM::Vec& q_init);\n\t// Precondition: Fx, G, q are conformantly dimensioned (not checked)\n\n\t// No default assignment operator\n\n\tvirtual const FM::Vec& f(const FM::Vec& x) const\n\t{\treturn ff(x);\n\t}\n};\n\nclass Simple_linear_predict_model : public Linear_predict_model\n// Linear predict model initialised from model matricies\n{\npublic:\n\tSimple_linear_predict_model (const FM::Matrix& Fx_init, const FM::Matrix& G_init, const FM::Vec& q_init);\n\t// Precondition: Fx, q and G are conformantly dimensioned (not checked)\n};\n\n\nclass Simple_linrz_correlated_observe_model : public Linrz_correlated_observe_model\n// Linrz observe model initialised from function and model matrices\n{\n\tState_function ff;\npublic:\n\tSimple_linrz_correlated_observe_model (State_function f_init, const FM::Matrix& Hx_init, const FM::SymMatrix& Z_init);\n\t// Precondition: Hx, Z are conformantly dimensioned (not checked)\n\t// No default assignment operator\n\n\tvirtual const FM::Vec& h(const FM::Vec& x) const\n\t{\treturn ff(x);\n\t}\n};\n\nclass Simple_linrz_uncorrelated_observe_model : public Linrz_uncorrelated_observe_model\n// Linrz observe model initialised from function and model matrices\n{\n\tState_function ff;\npublic:\n\tSimple_linrz_uncorrelated_observe_model (State_function f_init, const FM::Matrix& Hx_init, const FM::Vec& Zv_init);\n\t// Precondition: Hx, Zv are conformantly dimensioned (not checked)\n\t// No default assignment operator\n\n\tvirtual const FM::Vec& h(const FM::Vec& x) const\n\t{\treturn ff(x);\n\t}\n};\n\nclass Simple_linear_correlated_observe_model : public Linear_correlated_observe_model\n// Linear observe model initialised from model matrices\n{\npublic:\n\tSimple_linear_correlated_observe_model (const FM::Matrix& Hx_init, const FM::SymMatrix& Z_init);\n\t// Precondition: Hx, Z are conformantly dimensioned (not checked)\n};\n\nclass Simple_linear_uncorrelated_observe_model : public Linear_uncorrelated_observe_model\n// Linear observe model initialised from model matrices\n{\npublic:\n\tSimple_linear_uncorrelated_observe_model (const FM::Matrix& Hx_init, const FM::Vec& Zv_init);\n\t// Precondition: Hx, Zv are conformantly dimensioned (not checked)\n};\n\n\n\n/*\n * Model Adaptors: Constructed with a reference to another model\n */\n\n\nclass Adapted_Correlated_additive_observe_model : public Correlated_additive_observe_model\n/*\n * Adapt Uncorrelated_additive_observe_model to an equivalent\n * Correlated_additive_observe_model_adaptor\n */\n{\npublic:\n\tAdapted_Correlated_additive_observe_model (Uncorrelated_additive_observe_model& adapt);\n\tconst FM::Vec& h(const FM::Vec& x) const\n\t{\n\t\treturn unc.h(x);\n\t}\n\tinline void normalise (FM::Vec& z_denorm, const FM::Vec& z_from) const\n\t{\n\t\tunc.normalise (z_denorm, z_from);\n\t};\nprivate:\n\tUncorrelated_additive_observe_model& unc;\n};\n\nclass Adapted_Linrz_correlated_observe_model : public Linrz_correlated_observe_model\n/*\n * Adapt Linrz_uncorrelated_observe_model to an equivalent\n * Linrz_correlated_observe_model\n */\n{\npublic:\n\tAdapted_Linrz_correlated_observe_model (Linrz_uncorrelated_observe_model& adapt);\n\tconst FM::Vec& h(const FM::Vec& x) const\n\t{\n\t\treturn unc.h(x);\n\t}\n\tinline void normalise (FM::Vec& z_denorm, const FM::Vec& z_from) const\n\t{\n\t\tunc.normalise (z_denorm, z_from);\n\t};\nprotected:\n\tLinrz_uncorrelated_observe_model& unc;\n};\n\n\n/*\n * Generalised Models: generalise a model so it include properties of more then one model.\n */\n\n// General Linearised Uncorrelated Additive and Likelihood observe model\nclass General_LzUnAd_observe_model : public Linrz_uncorrelated_observe_model, public Likelihood_observe_model\n{\npublic:\n\tGeneral_LzUnAd_observe_model (std::size_t x_size, std::size_t z_size) :\n\t\tLinrz_uncorrelated_observe_model(x_size, z_size),\n\t\tLikelihood_observe_model(z_size),\n\t\tli(z_size)\n\t{}\n\tvirtual Float L(const FM::Vec& x) const\n\t// Definition of likelihood for additive noise model given zz\n\t{\treturn li.L(*this, z, h(x));\n\t}\n\tvirtual void Lz (const FM::Vec& zz)\n\t// Fix the observation zz about which to evaluate the Likelihood function\n\t// Zv is also fixed\n\t{\tLikelihood_observe_model::z = zz;\n\t\tli.Lz(*this);\n\t}\nprivate:\n\tfriend class General_LiUnAd_observe_model;\n\tstruct Likelihood_uncorrelated\n\t{\n\t\tLikelihood_uncorrelated(std::size_t z_size) :\n\t\t\tzInnov(z_size), Zv_inv(z_size)\n\t\t{\tzset = false;\n\t\t}\n\t\tmutable FM::Vec zInnov;\t// Normailised innovation, temporary for L(x)\n\t\tFM::Vec Zv_inv;\t\t\t// Inverse Noise Covariance given zz\n\t\tFloat logdetZ;\t\t\t// log(det(Z))\n\t\tbool zset;\n\t\tFloat L(const Uncorrelated_additive_observe_model& model, const FM::Vec& z, const FM::Vec& zp) const;\n\t\t// Definition of likelihood for additive noise model given zz\n\t\tvoid Lz(const Uncorrelated_additive_observe_model& model);\n\t};\n\tLikelihood_uncorrelated li;\n};\n\n// General Linear Uncorrelated Additive and Likelihood observe model\nclass General_LiUnAd_observe_model : public Linear_uncorrelated_observe_model, public Likelihood_observe_model\n{\npublic:\n\tGeneral_LiUnAd_observe_model (std::size_t x_size, std::size_t z_size) :\n\t\tLinear_uncorrelated_observe_model(x_size, z_size),\n\t\tLikelihood_observe_model(z_size),\n\t\tli(z_size)\n\t{}\n\tvirtual Float L(const FM::Vec& x) const\n\t// Definition of likelihood for additive noise model given zz\n\t{\treturn li.L(*this, z, h(x));\n\t}\n\tvirtual void Lz (const FM::Vec& zz)\n\t// Fix the observation zz about which to evaluate the Likelihood function\n\t// Zv is also fixed\n\t{\tLikelihood_observe_model::z = zz;\n\t\tli.Lz(*this);\n\t}\n\nprivate:\n\tGeneral_LzUnAd_observe_model::Likelihood_uncorrelated li;\n};\n\n// General Linearised Correlated Additive and Likelihood observe model\nclass General_LzCoAd_observe_model : public Linrz_correlated_observe_model, public Likelihood_observe_model\n{\npublic:\n\tGeneral_LzCoAd_observe_model (std::size_t x_size, std::size_t z_size) :\n\t\tLinrz_correlated_observe_model(x_size, z_size),\n\t\tLikelihood_observe_model(z_size),\n\t\tli(z_size)\n\t{}\n\tvirtual Float L(const FM::Vec& x) const\n\t// Definition of likelihood for additive noise model given zz\n\t{\treturn li.L(*this, z, h(x));\n\t}\n\tvirtual void Lz (const FM::Vec& zz)\n\t// Fix the observation zz about which to evaluate the Likelihood function\n\t// Zv is also fixed\n\t{\tLikelihood_observe_model::z = zz;\n\t\tli.Lz(*this);\n\t}\n\nprivate:\n\tfriend class General_LiCoAd_observe_model;\n\tstruct Likelihood_correlated\n\t{\n\t\tLikelihood_correlated(std::size_t z_size) :\n\t\t\tzInnov(z_size), Z_inv(z_size,z_size)\n\t\t{\tzset = false;\n\t\t}\n\t\tmutable FM::Vec zInnov;\t// Normalised innovation, temporary for L(x)\n\t\tFM::SymMatrix Z_inv;\t// Inverse Noise Covariance\n\t\tFloat logdetZ;\t\t\t// log(det(Z)\n\t\tbool zset;\t\n\t\tstatic Float scaled_vector_square(const FM::Vec& v, const FM::SymMatrix& V);\n\t\tFloat L(const Correlated_additive_observe_model& model, const FM::Vec& z, const FM::Vec& zp) const;\n\t\t// Definition of likelihood for additive noise model given zz\n\t\tvoid Lz(const Correlated_additive_observe_model& model);\n\t};\n\tLikelihood_correlated li;\n};\n\n// General Linear Correlated Additive and Likelihood observe model\nclass General_LiCoAd_observe_model : public Linear_correlated_observe_model, public Likelihood_observe_model\n{\npublic:\n\tGeneral_LiCoAd_observe_model (std::size_t x_size, std::size_t z_size) :\n\t\tLinear_correlated_observe_model(x_size, z_size),\n\t\tLikelihood_observe_model(z_size),\n\t\tli(z_size)\n\t{}\n\tvirtual Float L(const FM::Vec& x) const\n\t// Definition of likelihood for additive noise model given zz\n\t{\treturn li.L(*this, z, h(x));\n\t}\n\tvirtual void Lz (const FM::Vec& zz)\n\t// Fix the observation zz about which to evaluate the Likelihood function\n\t// Zv is also fixed\n\t{\tLikelihood_observe_model::z = zz;\n\t\tli.Lz(*this);\n\t}\n\nprivate:\n\tGeneral_LzCoAd_observe_model::Likelihood_correlated li;\n};\n\n\n}// namespace\n\n#endif\n", "meta": {"hexsha": "40fd1651b2b94b50d455a7d9289b44a0786f46f3", "size": 9165, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bayes/include/open_ptrack/bayes/models.hpp", "max_stars_repo_name": "wangqiang1588/open_ptrack", "max_stars_repo_head_hexsha": "cf8aa4b30926abcceb3de686cd8ea4b48c2baaeb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 327.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T07:34:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T02:01:30.000Z", "max_issues_repo_path": "bayes/include/open_ptrack/bayes/models.hpp", "max_issues_repo_name": "wangqiang1588/open_ptrack", "max_issues_repo_head_hexsha": "cf8aa4b30926abcceb3de686cd8ea4b48c2baaeb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 145.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T20:43:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-16T23:16:33.000Z", "max_forks_repo_path": "bayes/include/open_ptrack/bayes/models.hpp", "max_forks_repo_name": "wangqiang1588/open_ptrack", "max_forks_repo_head_hexsha": "cf8aa4b30926abcceb3de686cd8ea4b48c2baaeb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 120.0, "max_forks_repo_forks_event_min_datetime": "2015-03-11T14:16:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T08:39:04.000Z", "avg_line_length": 31.1734693878, "max_line_length": 128, "alphanum_fraction": 0.7695581015, "num_tokens": 2484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4259392753865028}}
{"text": "#include <k52/optimization/hleborodov_rosenbrock_method.h>\n\n#ifdef BUILD_WITH_MPI\n\n#include <boost/mpi.hpp>\n#include <k52/parallel/mpi/constants.h>\n\n#endif\n\n#include <cmath>\n#include <stdexcept>\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n\n#include <k52/optimization/params/i_continuous_parameters.h>\n\nusing ::std::vector;\n\nnamespace\n{\nconst double kArgumentsIncreaseValue = 1.5;\nconst double kArgumentsDecreaseValue = -0.5;\n}\n\nnamespace k52\n{\nnamespace optimization\n{\n\nHleborodovRosenbrockMethod::HleborodovRosenbrockMethod(double precision, size_t max_iteration_number,\n    double first_step, double max_step)\n    : precision_(precision)\n    , arguments_increase_(kArgumentsIncreaseValue)\n    , arguments_decrease_(kArgumentsDecreaseValue)\n    , first_step_(first_step)\n    , max_step_(max_step)\n    , max_iteration_number_(max_iteration_number)\n{\n}\n\nHleborodovRosenbrockMethod* HleborodovRosenbrockMethod::Clone() const\n{\n    return new HleborodovRosenbrockMethod(precision_, max_iteration_number_, first_step_, max_step_);\n}\n\nstd::string HleborodovRosenbrockMethod::get_name() const\n{\n    return \"Hleborodov Rosenbrock Method\";\n}\n\n#ifdef BUILD_WITH_MPI\nvoid HleborodovRosenbrockMethod::Send(boost::mpi::communicator* communicator, int target) const\n{\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, precision_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, first_step_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, max_step_);\n    communicator->send(target, k52::parallel::mpi::constants::kCommonTag, max_iteration_number_);\n}\n\nvoid HleborodovRosenbrockMethod::Receive(boost::mpi::communicator* communicator, int source)\n{\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, precision_);\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, first_step_);\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, max_step_);\n    communicator->recv(source, k52::parallel::mpi::constants::kCommonTag, max_iteration_number_);\n}\n#endif\n\nvector<double> HleborodovRosenbrockMethod::FindOptimalParameters(const vector<double>& initial_parameters)\n{\n    vector<double> arguments = initial_parameters;\n    dimension_ = arguments.size();\n    vector<double> next_step_arguments(arguments);\n\n    InitializeBasisAndSteps();\n\n    for (size_t i = 1; i <= max_iteration_number_; i++)\n    {\n        // Research of next arguments, that minimize function\n        MakeStep(next_step_arguments);\n\n        if (IsExitCriteriaFulfilled(next_step_arguments, arguments))\n        {\n            break;\n        }\n\n        // Check number of iterations\n        if (i == max_iteration_number_)\n        {\n            std::cout << \" Minimun has not found\";\n        }\n\n        // Make new basis by Gramm-Shmidt method\n        CreateNewBasis();\n        arguments = next_step_arguments;\n    }\n\n    return next_step_arguments;\n}\n\nvoid HleborodovRosenbrockMethod::InitializeBasisAndSteps()\n{\n    steps_array_ = vector<double> (dimension_,first_step_);\n\n    basis_ = vector< vector<double> > (dimension_, vector<double> (dimension_, 0));\n\n    // Initialize basis is Decart coordinate system\n    for(size_t i = 0; i<dimension_; i++)\n    {\n        basis_[i][i] = 1;\n    }\n}\n\nbool HleborodovRosenbrockMethod::IsExitCriteriaFulfilled(\n    const vector<double>& arguments,\n    const vector<double>& previous_step_arguments)\n{\n    bool escape = true;\n    // check arguments increases to escape\n    for(size_t j = 0; j<dimension_; j++)\n    {\n        if(std::abs(arguments[j] - previous_step_arguments[j]) > precision_)\n        {\n            escape = false;\n        }\n    }\n    return escape;\n}\n\nvoid HleborodovRosenbrockMethod::MakeStep(vector<double> &arguments)\n{\n    double start_function_value = CountObjectiveFunctionValueToMinimize(arguments);\n\n    vector<double> tested_arguments(arguments);\n    vector<double> tested_arguments2(arguments);\n\n    /// Sort steps_array_ by descending for beter method speed\n    std::sort(steps_array_.begin(), steps_array_.end(), std::greater<double>());\n\n    for(size_t i = 0; i<dimension_; i++)\n    {\n        // make test step to minimize function in current direction\n        // make it by each of coordinates\n        MakeStepPerCoordinate(i, &tested_arguments);\n\n        double counted_value = CountObjectiveFunctionValueToMinimize(tested_arguments);\n\n        if(start_function_value > counted_value)\n        {\n            steps_array_[i] *= arguments_increase_;\n        }\n        else\n        {\n            steps_array_[i] *= arguments_decrease_;\n        }\n\n        CorrectStep(i);\n\n        MakeStepPerCoordinate(i, &tested_arguments2);\n\n        tested_arguments = arguments;\n    }\n\n    arguments = tested_arguments2;\n}\n\nvoid HleborodovRosenbrockMethod::MakeStepPerCoordinate(int basis_index, vector<double>* arguments)\n{\n    for(size_t j = 0; j<dimension_; j++)\n    {\n        (*arguments)[j] += steps_array_[basis_index]*basis_[basis_index][j];\n    }\n}\n\nvoid HleborodovRosenbrockMethod::CreateNewBasis()\n{\n    vector< vector<double> > matrix_of_coeff(dimension_, vector<double> (dimension_, 0));\n    vector< vector<double> > unnormalized_basis(dimension_, vector<double> (dimension_, 0));\n\n    for(size_t j = 0; j<dimension_; j++)\n    {\n        for(size_t i = j; i<dimension_; i++)\n        {\n            for(size_t k = 0; k<dimension_; k++)\n            {\n                matrix_of_coeff[j][k] += steps_array_[i]*basis_[i][k];\n            }\n        }\n    }\n\n    for(size_t i = 0; i<dimension_; i++)\n    {\n        for(size_t j = 0; j<dimension_; j++)\n        {\n            unnormalized_basis[i][j] = matrix_of_coeff[i][j];\n        }\n        basis_[0][i] = matrix_of_coeff[0][i];\n    }\n\n    NormalizeVector(basis_[0]);\n    double temp;\n\n    for(size_t j = 1; j<dimension_; j++)\n    {\n        for(size_t i = 0; i<j; i++)\n        {\n            temp = ScalarComposition(matrix_of_coeff[j],basis_[i]);\n            for(size_t k = 0; k<dimension_; k++)\n            {\n                unnormalized_basis[j][k] -= temp*basis_[i][k];\n            }\n        }\n\n        for(size_t k = 0; k<dimension_; k++)\n        {\n            basis_[j][k] = unnormalized_basis[j][k];\n        }\n        NormalizeVector(basis_[j]);\n    }\n}\n\nvoid HleborodovRosenbrockMethod::NormalizeVector(vector<double> &target_vector)\n{\n    double temp = 0;\n    for(size_t i = 0; i<dimension_; i++)\n    {\n        temp += target_vector[i]*target_vector[i];\n    }\n    temp = sqrt(temp);\n    for(size_t i = 0; i<dimension_; i++)\n    {\n        if(temp != 0)\n        {\n            target_vector[i] /= temp;\n        }\n    }\n}\n\ndouble HleborodovRosenbrockMethod::ScalarComposition(\n    const vector<double>& first_vector,\n    const vector<double>& second_vector)\n{\n    double scalar_composition = 0;\n    for(size_t i = 0; i<dimension_; i++)\n    {\n        scalar_composition += first_vector[i]*second_vector[i];\n    }\n    return scalar_composition;\n}\n\nvoid HleborodovRosenbrockMethod::CorrectStep(size_t step_index)\n{\n    if( std::abs(steps_array_[step_index]) > max_step_)\n    {\n        steps_array_[step_index] =\n            max_step_*steps_array_[step_index]/std::abs(steps_array_[step_index]);\n    }\n}\n\n}/* namespace optimization */\n}/* namespace k52 */\n", "meta": {"hexsha": "a6390f18e1efa2b8a7dab9228dc43d2416a0c874", "size": 7266, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimization/hleborodov_rosenbrock_method.cpp", "max_stars_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_stars_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/optimization/hleborodov_rosenbrock_method.cpp", "max_issues_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_issues_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimization/hleborodov_rosenbrock_method.cpp", "max_forks_repo_name": "wfoperihnofiksnfvopjdf/k52", "max_forks_repo_head_hexsha": "2bbbfe018db6d73ec9773f29e571269f898a9bc0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6273764259, "max_line_length": 106, "alphanum_fraction": 0.6630883567, "num_tokens": 1827, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4259392753865028}}
{"text": "#include <iostream>\n#include <cmath>\n#include <boost/make_shared.hpp>\n#include <problem/solver.h>\n#include <communicators/mpicom.h>\n#include <communicators/localcom.h>\n#include <problem/subtasks.h>\n#include <fstream>\n#include <getopt.h>\n#include <cstring>\n#include <omp.h>\n\nSolver::Solver(int& argc, char**& argv)\n    : xSplit_(0)\n    , ySplit_(0)\n    , normOfDifference_(0)\n    , maxDifference_(0)\n    , iterations_(0)\n    , elapsedTime_(0)\n    , dump_(false)\n{\n    int opt;\n    while (-1 != (opt = getopt(argc, argv, \"m:n:d\")))\n    {\n        switch (opt)\n        {\n        case 'm':\n            xSplit_ = std::atoi(optarg);\n            break;\n        case 'n':\n            ySplit_ = std::atoi(optarg);\n            break;\n        case 'd':\n            dump_ = true;\n            break;\n        default:\n            throw std::runtime_error(\"invalid arg\");\n            break;\n        }\n    }\n    if (xSplit_ < 3 || ySplit_ < 3)\n    {\n        throw std::runtime_error(\"set nonzero splits\");\n    }\n\n#ifdef CMC_OPENMPI\n    mpi_.reset(new MpiHolder(&argc, &argv));\n    com_ = boost::make_shared<MpiCommunicator>(xSplit_, ySplit_);\n#else\n    com_ = boost::make_shared<LocalCommunicator>();\n#endif\n}\n\nvoid \nSolver::SetProblem(Problem p, double eps)\n{\n    SetSubtask(\n        p.domain, \n        xSplit_, ySplit_, \n        com_->CountSubtask(Vertical), com_->CountSubtask(Horizontal),\n        com_->GetSubtask(Vertical),   com_->GetSubtask(Horizontal)\n    );\n    m_ = boost::make_shared<FiniteElementMethod>(com_, p, xSplit_, ySplit_);\n    eps_ = eps;\n}\n\nvoid \nSolver::Solve()\n{\n    double startTime = MPI_Wtime();\n\n    Matrix w = m_->FirstApproximation();\n    do\n    {\n        Matrix next = m_->EvaluateNext(w);\n        normOfDifference_ = m_->NormOfDifference(w, next);\n        w = next;\n        iterations_++;\n    } while (normOfDifference_ > eps_);\n\n    double endTime = MPI_Wtime();\n\n    elapsedTime_ = endTime - startTime;\n\n    Matrix etalon = m_->Etalon();\n    double localError = 0;\n    for (int i = 0; i < w.GetRows(); i++)\n    {\n        for (int j = 0; j < w.GetCols(); j++)\n        {\n            double diff = std::fabs(w(i, j) - etalon(i, j));\n            if (diff > localError)\n            {\n                localError = diff;\n            }\n        }\n    }\n    maxDifference_ = com_->UpdateError(localError);\n    solution_ = w.Unwrapped();\n}\n\nvoid \nSolver::PrintReport()\n{\n    if (dump_)\n    {\n        int row = com_->GetSubtask(Vertical);\n        int col = com_->GetSubtask(Horizontal);\n        DumpSolution(row, col);\n        DumpEtalon(row, col);\n    }\n\n    if (!com_->IsMaster())\n    {\n        return;\n    }\n\n    std::cout << \"Max difference: \" << maxDifference_ << std::endl;\n    std::cout << \"Norm:           \" << normOfDifference_ << std::endl;\n    std::cout << \"Iterations:     \" << iterations_ << std::endl;\n    std::cout << \"Elapsed time:   \" << elapsedTime_ << std::endl;\n}\n\nvoid\nSolver::DumpSolution(int row, int col) const\n{\n    char filename[32];\n    std::sprintf(filename, \"solution_%d-%d\", row, col);\n    std::ofstream f(filename);\n    for (int i = 0; i < solution_.GetRows(); i++)\n    {\n        for (int j = 0; j < solution_.GetCols(); j++)\n        {\n            f << i << ',' << j << ',' << solution_(i, j) << std::endl;\n        }\n    }\n}\n\nvoid\nSolver::DumpEtalon(int row, int col) const\n{\n    char filename[32];\n    std::sprintf(filename, \"etalon_%d-%d\", row, col);\n    std::ofstream f(filename);\n\n    const Matrix etalon = m_->Etalon().Unwrapped();\n    for (int i = 0; i < etalon.GetRows(); i++)\n    {\n        for (int j = 0; j < etalon.GetCols(); j++)\n        {\n            f << i << ',' << j << ',' << etalon(i, j) << std::endl;\n        }\n    }\n}", "meta": {"hexsha": "b0966dc6de89d0890017217f351bca57da4e4e5f", "size": 3672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/problem/solver.cpp", "max_stars_repo_name": "KoSeAn97/skm2019", "max_stars_repo_head_hexsha": "18f2ea92e9683aead02fe62f4bae3d606ab8bdde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/problem/solver.cpp", "max_issues_repo_name": "KoSeAn97/skm2019", "max_issues_repo_head_hexsha": "18f2ea92e9683aead02fe62f4bae3d606ab8bdde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/problem/solver.cpp", "max_forks_repo_name": "KoSeAn97/skm2019", "max_forks_repo_head_hexsha": "18f2ea92e9683aead02fe62f4bae3d606ab8bdde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8441558442, "max_line_length": 76, "alphanum_fraction": 0.5411220044, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4258868953910294}}
{"text": "#ifndef itkLaplaceEquationSolverImageFilter_hxx_included\n#define itkLaplaceEquationSolverImageFilter_hxx_included\n\n#include \"itkLaplaceEquationSolverImageFilter.h\"\n\n#include \"itkImageRegionConstIteratorWithIndex.h\"\n\n#include <algorithm>\n#include <ctime>\n#include <limits>\n\n#include <Eigen/SparseCholesky>\n\nnamespace itk\n{\n\ntemplate< typename TInputImage, typename TOutputImage >\ninline void\nLaplaceEquationSolverImageFilter< TInputImage, TOutputImage >\n::UpdateAB( size_t i, InputIndexType voxelIndex, OutputPixelType invDxDx,\n            TripletListType & tripletList, VectorType & b,\n            OffsetValueType solutionIndex )\n{\n  bool labelFound = false;\n  InputPixelType label = this->GetInput()->GetPixel( voxelIndex );\n  if ( label == m_SolutionLabel )\n    {\n    Eigen::Triplet< OutputPixelType > triplet( i, solutionIndex, invDxDx );\n    tripletList.push_back( triplet );\n    labelFound = true;\n    }\n  else if ( label == m_NeumannBoundaryConditionLabel )\n    {\n    Eigen::Triplet< OutputPixelType > triplet( i, i, invDxDx );\n    tripletList.push_back( triplet );\n    labelFound = true;\n    }\n  else\n    {\n    typename DirichletMapType::iterator iter =\n      m_DirichletBoundaryConditionMap.find( label );\n    if ( iter != m_DirichletBoundaryConditionMap.end() )\n      {\n      b[i] -= iter->second * invDxDx;\n      labelFound = true;\n      }\n    }\n  if ( !labelFound )\n    {\n    itkExceptionMacro( << \"Unknown label value \"\n                       << label << \" at index \" << voxelIndex );\n    }\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nLaplaceEquationSolverImageFilter< TInputImage, TOutputImage >\n::LaplaceEquationSolverImageFilter()\n{\n  m_SolutionLabel = 11;\n  m_NeumannBoundaryConditionLabel = 6;\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nLaplaceEquationSolverImageFilter< TInputImage, TOutputImage >\n::ResetDirichletBoundaryConditions()\n{\n  m_DirichletBoundaryConditionMap.reset();\n\n  this->Modified();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nLaplaceEquationSolverImageFilter< TInputImage, TOutputImage >\n::AddDirichletBoundaryCondition( InputPixelType boundaryConditionLabel,\n                                 OutputPixelType boundaryConditionValue )\n{\n  m_DirichletBoundaryConditionMap[ boundaryConditionLabel ] =\n    boundaryConditionValue;\n\n  this->Modified();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nsize_t\nLaplaceEquationSolverImageFilter< TInputImage, TOutputImage >\n::GetNumberOfDirichletBoundaryConditions() const\n{\n  return m_DirichletBoundaryConditionMap.size();\n}\n\ntemplate< typename TInputImage, typename TOutputImage >\nvoid\nLaplaceEquationSolverImageFilter< TInputImage, TOutputImage >\n::GenerateData()\n{\n  typename TInputImage::ConstPointer input = this->GetInput();\n  typename TOutputImage::Pointer output = this->GetOutput();\n\n  // Allocate the output and initialize to NaN\n  this->AllocateOutputs();\n  output->FillBuffer( std::numeric_limits< OutputPixelType >::quiet_NaN() );\n\n  // Do Laplace solution by iterative solver using 6 neighborhood\n  InputIndexType minIndex = input->GetBufferedRegion().GetIndex();\n  InputIndexType maxIndex = input->GetBufferedRegion().GetUpperIndex();\n\n  // First get all the solution domain indices. We do this, otherwise\n  // the matrices to solve will be far too large to fit into memory.\n  std::vector< InputIndexType > solutionIndices;\n\n  typedef typename TInputImage::OffsetValueType OffsetValueType;\n  std::vector< OffsetValueType > linearIndex2UnknownIndex(\n    input->GetPixelContainer()->Size(), 0 );\n\n  long counter = 0;\n  typedef ImageRegionConstIteratorWithIndex< TInputImage > IteratorWithIndexType;\n  IteratorWithIndexType fullRegionIter( input.GetPointer(), input->GetBufferedRegion() );\n  for ( fullRegionIter.GoToBegin(); !fullRegionIter.IsAtEnd(); ++fullRegionIter )\n    {\n    InputPixelType pixelValue = fullRegionIter.Get();\n    InputIndexType index = fullRegionIter.GetIndex();\n    if ( pixelValue == m_SolutionLabel )\n      {\n      solutionIndices.push_back( index );\n      linearIndex2UnknownIndex[ input->ComputeOffset( fullRegionIter.GetIndex() ) ] = counter;\n      ++counter;\n      }\n    }\n\n  itkDebugMacro( << \"Done with noting indices\" );\n\n  size_t numberOfUnknowns = solutionIndices.size();\n\n  itkDebugMacro( << \"Number of unknowns: \" << numberOfUnknowns );\n\n  // Set up the linear system by going through all the indices of the\n  // solution domain and creating the sparse matrix A and the right\n  // vector b\n  typedef Eigen::SparseMatrix< OutputPixelType, Eigen::ColMajor > MatrixType;\n  MatrixType A( numberOfUnknowns, numberOfUnknowns );\n\n  // Set up the b vector\n  typedef Eigen::Matrix< OutputPixelType, Eigen::Dynamic, 1 > VectorType;\n  VectorType b( numberOfUnknowns );\n  b.fill( 0.0 );\n\n  // Set the diagonal elements\n  OutputPixelType dx = input->GetSpacing()[0];\n  OutputPixelType dy = input->GetSpacing()[1];\n  OutputPixelType dz = input->GetSpacing()[2];\n\n  OutputPixelType invDxDx = 1.0 / (dx * dx);\n  OutputPixelType invDyDy = 1.0 / (dy * dy);\n  OutputPixelType invDzDz = 1.0 / (dz * dz);\n\n  itkDebugMacro( << \"Done setting diagonal elements of A\" );\n\n  // Triplets to feed into A via\n  // Eigen::SparseMatrix<>::setFromTriplets.  Note that triplets with\n  // the same i, j indices will be summed in the sparse matrix.\n  typedef Eigen::Triplet< OutputPixelType > Triplet;\n  std::vector< Triplet > tripletList;\n  tripletList.reserve( 7 * numberOfUnknowns );\n\n  // This is somewhat of a goofy way to set up A. It is nearly a\n  // direct translation from MATLAB code. Setting the elements based\n  // on a traditional stencil approach might be faster and use less\n  // memory.\n  for ( size_t i = 0; i < numberOfUnknowns; ++i )\n    {\n    tripletList.push_back( Triplet( i, i, -2.0 * ( invDxDx + invDyDy + invDzDz ) ) );\n    }\n\n  for ( size_t i = 0; i < numberOfUnknowns; ++i )\n    {\n    InputIndexType index = solutionIndices[i];\n\n    // +x, -x\n    InputIndexType indexXP = index;\n    indexXP[0] = std::min( maxIndex[0], index[0] + 1 );\n    InputIndexType indexXM = index;\n    indexXM[0] = std::max( minIndex[0], index[0] - 1 );\n\n    // +y, -y\n    InputIndexType indexYP = index;\n    indexYP[1] = std::min( maxIndex[1], index[1] + 1 );\n    InputIndexType indexYM = index;\n    indexYM[1] = std::max( minIndex[1], index[1] - 1 );\n\n    // +z, -z\n    InputIndexType indexZP = index;\n    indexZP[2] = std::min( maxIndex[2], index[2] + 1 );\n    InputIndexType indexZM = index;\n    indexZM[2] = std::max( minIndex[2], index[2] - 1 );\n\n    OffsetValueType linearIndex;\n    linearIndex = input->ComputeOffset( indexXP );\n    this->UpdateAB( i, indexXP, invDxDx, tripletList, b,\n                    linearIndex2UnknownIndex[ linearIndex ] );\n    linearIndex = input->ComputeOffset( indexXM );\n    this->UpdateAB( i, indexXM, invDxDx, tripletList, b,\n                    linearIndex2UnknownIndex[ linearIndex ] );\n    linearIndex = input->ComputeOffset( indexYP );\n    this->UpdateAB( i, indexYP, invDyDy, tripletList, b,\n                    linearIndex2UnknownIndex[ linearIndex ] );\n    linearIndex = input->ComputeOffset( indexYM );\n    this->UpdateAB( i, indexYM, invDyDy, tripletList, b,\n                    linearIndex2UnknownIndex[ linearIndex ] );\n    linearIndex = input->ComputeOffset( indexZP );\n    this->UpdateAB( i, indexZP, invDzDz, tripletList, b,\n                    linearIndex2UnknownIndex[ linearIndex ] );\n    linearIndex = input->ComputeOffset( indexZM );\n    this->UpdateAB( i, indexZM, invDzDz, tripletList, b,\n                    linearIndex2UnknownIndex[ linearIndex ] );\n    }\n\n  itkDebugMacro( << \"Done building linear systems\" );\n\n  // Fill A\n  A.setFromTriplets( tripletList.begin(), tripletList.end() );\n  tripletList.clear();\n\n  // Compress the matrix before handing it off to the solver\n  A.makeCompressed();\n\n  itkDebugMacro( << \"Done compressing\" );\n\n  std::time_t startTime;\n  std::time( &startTime );\n\n  // Tried several solvers on one large image to find the fastest:\n  // ConjugateGradient  - 111 seconds\n  // SimplicialCholesky - 204 seconds\n  // SimplicialLDLT     - 203 seconds\n  // SimplicalLLT       - error\n  Eigen::ConjugateGradient< MatrixType > solver;\n  solver.compute( A );\n  VectorType x = solver.solve( b );\n\n  itkDebugMacro( << \"Done solving\" );\n\n  std::time_t endTime;\n  std::time( &endTime );\n\n  double elapsedSeconds = std::difftime( endTime, startTime );\n  (void) elapsedSeconds; // To avoid warning when compiled in release mode\n  itkDebugMacro( << \"Execution took \" << elapsedSeconds << \" seconds.\" );\n\n  if ( solver.info() != Eigen::Success )\n    {\n    itkExceptionMacro( << \"Failed to solve linear system.\" );\n    }\n\n  // Now copy the output vector to the output image\n  for ( size_t i = 0; i < solutionIndices.size(); ++i )\n    {\n    output->SetPixel( solutionIndices[i], x[i] );\n    }\n\n  // Now set the values for the Dirichlet boundary conditions\n  // in the output image.\n  ImageRegionConstIterator< TInputImage > iterIn( input.GetPointer(),\n                                                     input->GetBufferedRegion() );\n  ImageRegionIterator< TOutputImage > iterOut( output.GetPointer(),\n                                                  output->GetBufferedRegion() );\n\n  while ( !iterIn.IsAtEnd() && !iterOut.IsAtEnd() )\n    {\n    typename DirichletMapType::iterator iter = m_DirichletBoundaryConditionMap.find( iterIn.Get() );\n    if ( iter != m_DirichletBoundaryConditionMap.end() )\n      {\n      iterOut.Set( iter->second );\n      }\n    ++iterIn;\n    ++iterOut;\n    }\n}\n\n} // end namespace itk\n\n#endif\n", "meta": {"hexsha": "aa0fcdad8bacb19e0148a8eced7b3b5b6534ee77", "size": 9549, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ITK/itkLaplaceEquationSolverImageFilter.hxx", "max_stars_repo_name": "PediatricAirways/CrossSectionMeasurementTools", "max_stars_repo_head_hexsha": "059909d16f0b3033b7b604a2174c7c239dc63dcb", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-11-11T16:57:59.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-13T09:28:10.000Z", "max_issues_repo_path": "ITK/itkLaplaceEquationSolverImageFilter.hxx", "max_issues_repo_name": "PediatricAirways/CrossSectionMeasurementTools", "max_issues_repo_head_hexsha": "059909d16f0b3033b7b604a2174c7c239dc63dcb", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ITK/itkLaplaceEquationSolverImageFilter.hxx", "max_forks_repo_name": "PediatricAirways/CrossSectionMeasurementTools", "max_forks_repo_head_hexsha": "059909d16f0b3033b7b604a2174c7c239dc63dcb", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6232394366, "max_line_length": 100, "alphanum_fraction": 0.6885537753, "num_tokens": 2534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.425755399067829}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/math/quaternion.hpp>\n#include <cmath>\n#include <limits>\n#include <pup.h>\n#include <string>\n#include <vector>\n\n#include \"DataStructures/DataVector.hpp\"\n#include \"Domain/FunctionsOfTime/FunctionOfTime.hpp\"\n#include \"Domain/FunctionsOfTime/FunctionOfTimeHelpers.hpp\"\n#include \"Domain/FunctionsOfTime/PiecewisePolynomial.hpp\"\n#include \"Parallel/CharmPupable.hpp\"\n#include \"Utilities/Gsl.hpp\"\n\nnamespace domain::FunctionsOfTime {\n/// \\ingroup ComputationalDomainGroup\n/// \\brief A FunctionOfTime that stores quaternions for the rotation map\n///\n/// \\details This FunctionOfTime stores quaternions that will be used in the\n/// time-dependent rotation map as well as the orbital angular velocity that\n/// will be controlled by the rotation control sytem. To get the quaternion, an\n/// ODE is solved of the form \\f$ \\dot{q} = \\frac{1}{2} q \\times \\omega \\f$\n/// where \\f$ \\omega \\f$ is the orbital angular velocity which is stored\n/// internally as the derivative of an angle `PiecewisePolynomial`, and\n/// \\f$ \\times \\f$ here is quaternion multiplication.\n///\n/// Different from a `PiecewisePolynomial`, only the quaternion\n/// itself is stored, not any of the derivatives because the derivatives must be\n/// calculated from the solved ODE at every function call. Because\n/// derivatives of the quaternion are not stored, the template parameter\n/// `MaxDeriv` refers to both the max derivative of the stored angle\n/// PiecewisePolynomial and the max derivative returned by the\n/// QuaternionFunctionOfTime. The `update` function is then just a wrapper\n/// around the internal `PiecewisePolynomial::update` function with the addition\n/// that it then updates the stored quaternions as well.\n///\n/// The angle PiecewisePolynomial is accessible through the `angle_func`,\n/// `angle_func_and_deriv`, and `angle_func_and_2_derivs` functions which\n/// correspond to the function calls of a normal PiecewisePolynomial except\n/// without the `angle_` prefix.\n///\n/// It is encouraged to use `quat_func` and `angle_func` when you want the\n/// specific values of the functions to avoid ambiguity in what you are\n/// calling. However, the original three `func` functions inherited from the\n/// FunctionOfTime base class are necessary because the maps use the generic\n/// `func` functions, thus they return the quaternion and its derivatives (which\n/// are needed for the map). This is all to keep the symmetry of naming\n/// `angle_func` and `quat_func` so that function calls won't be ambiguous.\ntemplate <size_t MaxDeriv>\nclass QuaternionFunctionOfTime : public FunctionOfTime {\n public:\n  QuaternionFunctionOfTime() = default;\n  QuaternionFunctionOfTime(\n      double t, std::array<DataVector, 1> initial_quat_func,\n      std::array<DataVector, MaxDeriv + 1> initial_angle_func,\n      double expiration_time);\n\n  ~QuaternionFunctionOfTime() override = default;\n  QuaternionFunctionOfTime(QuaternionFunctionOfTime&&) = default;\n  QuaternionFunctionOfTime& operator=(QuaternionFunctionOfTime&&) = default;\n  QuaternionFunctionOfTime(const QuaternionFunctionOfTime&) = default;\n  QuaternionFunctionOfTime& operator=(const QuaternionFunctionOfTime&) =\n      default;\n\n  // LCOV_EXCL_START\n  explicit QuaternionFunctionOfTime(CkMigrateMessage* /*unused*/) {}\n  // LCOV_EXCL_STOP\n\n  auto get_clone() const -> std::unique_ptr<FunctionOfTime> override;\n\n  // clang-tidy: google-runtime-references\n  // clang-tidy: cppcoreguidelines-owning-memory,-warnings-as-errors\n  WRAPPED_PUPable_decl_template(QuaternionFunctionOfTime<MaxDeriv>);  // NOLINT\n\n  void reset_expiration_time(const double next_expiration_time) override {\n    angle_f_of_t_.reset_expiration_time(next_expiration_time);\n  }\n\n  /// Returns domain of validity for the function of time\n  std::array<double, 2> time_bounds() const override {\n    return angle_f_of_t_.time_bounds();\n  }\n\n  /// Updates the `MaxDeriv`th derivative of the angle piecewisepolynomial at\n  /// the given time, then updates the stored quaternions.\n  ///\n  /// `updated_max_deriv` is a datavector of the `MaxDeriv`s for each component.\n  /// `next_expiration_time` is the next expiration time.\n  void update(double time_of_update, DataVector updated_max_deriv,\n              double next_expiration_time) override;\n\n  // NOLINTNEXTLINE(google-runtime-references)\n  void pup(PUP::er& p) override;\n\n  /// Returns the quaternion at an arbitrary time `t`.\n  std::array<DataVector, 1> func(const double t) const override {\n    return quat_func(t);\n  }\n\n  /// Returns the quaternion and its first derivative at an arbitrary time `t`.\n  std::array<DataVector, 2> func_and_deriv(const double t) const override {\n    return quat_func_and_deriv(t);\n  }\n\n  /// Returns the quaternion and the first two derivatives at an arbitrary\n  /// time `t`.\n  std::array<DataVector, 3> func_and_2_derivs(const double t) const override {\n    return quat_func_and_2_derivs(t);\n  }\n\n  /// Returns the quaternion at an arbitrary time `t`.\n  std::array<DataVector, 1> quat_func(double t) const;\n\n  /// Returns the quaternion and its first derivative at an arbitrary time `t`.\n  std::array<DataVector, 2> quat_func_and_deriv(double t) const;\n\n  /// Returns the quaternion and the first two derivatives at an arbitrary\n  /// time `t`.\n  std::array<DataVector, 3> quat_func_and_2_derivs(double t) const;\n\n  /// Returns stored angle at an arbitrary time `t`.\n  std::array<DataVector, 1> angle_func(const double t) const {\n    return angle_f_of_t_.func(t);\n  }\n\n  /// Returns stored angle and its first derivative (omega) at an arbitrary time\n  /// `t`.\n  std::array<DataVector, 2> angle_func_and_deriv(const double t) const {\n    return angle_f_of_t_.func_and_deriv(t);\n  }\n\n  /// Returns stored angle and the first two derivatives at an arbitrary\n  /// time `t`.\n  std::array<DataVector, 3> angle_func_and_2_derivs(const double t) const {\n    return angle_f_of_t_.func_and_2_derivs(t);\n  }\n\n private:\n  template <size_t LocalMaxDeriv>\n  friend bool operator==(  // NOLINT(readability-redundant-declaration)\n      const QuaternionFunctionOfTime<LocalMaxDeriv>& lhs,\n      const QuaternionFunctionOfTime<LocalMaxDeriv>& rhs);\n\n  template <size_t LocalMaxDeriv>\n  friend std::ostream& operator<<(  // NOLINT(readability-redundant-declaration)\n      std::ostream& os,\n      const QuaternionFunctionOfTime<LocalMaxDeriv>& quaternion_f_of_t);\n\n  std::vector<FunctionOfTimeHelpers::StoredInfo<1, false>>\n      stored_quaternions_and_times_;\n\n  domain::FunctionsOfTime::PiecewisePolynomial<MaxDeriv> angle_f_of_t_;\n\n  /// Integrates the ODE \\f$ \\dot{q} = \\frac{1}{2} q \\times \\omega \\f$ from time\n  /// `t0` to time `t`. On input, `quaternion_to_integrate` is the initial\n  /// quaternion at time `t0` and on output, it stores the result at time `t`\n  void solve_quaternion_ode(\n      gsl::not_null<boost::math::quaternion<double>*> quaternion_to_integrate,\n      double t0, double t) const;\n\n  /// Updates the `std::vector<StoredInfo>` to have the same number of stored\n  /// quaternions as the `angle_f_of_t_ptr` has stored angles. This is necessary\n  /// to ensure we can solve the ODE at any time `t`\n  void update_stored_info();\n\n  /// Does common operations to all the `func` functions such as updating stored\n  /// info, solving the ODE, and returning the normalized quaternion as a boost\n  /// quaternion for easy calculations\n  boost::math::quaternion<double> setup_func(double t) const;\n};\n\ntemplate <size_t MaxDeriv>\nbool operator!=(const QuaternionFunctionOfTime<MaxDeriv>& lhs,\n                const QuaternionFunctionOfTime<MaxDeriv>& rhs);\n\n/// \\cond\ntemplate <size_t MaxDeriv>\nPUP::able::PUP_ID QuaternionFunctionOfTime<MaxDeriv>::my_PUP_ID = 0;  // NOLINT\n/// \\endcond\n}  // namespace domain::FunctionsOfTime\n", "meta": {"hexsha": "064c3ad5b635e0884cc42b513635b74a9b927c23", "size": 7816, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Domain/FunctionsOfTime/QuaternionFunctionOfTime.hpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 117.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T22:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:23:36.000Z", "max_issues_repo_path": "src/Domain/FunctionsOfTime/QuaternionFunctionOfTime.hpp", "max_issues_repo_name": "nilsvu/spectre", "max_issues_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3177.0, "max_issues_repo_issues_event_min_datetime": "2017-04-07T21:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:59.000Z", "max_forks_repo_path": "src/Domain/FunctionsOfTime/QuaternionFunctionOfTime.hpp", "max_forks_repo_name": "nilsvu/spectre", "max_forks_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2017-04-07T19:36:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T10:21:00.000Z", "avg_line_length": 41.7967914439, "max_line_length": 80, "alphanum_fraction": 0.747185261, "num_tokens": 1948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4257054289963076}}
{"text": "#include <iostream>\n#include <string>\n\n#include <boost/program_options.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/preprocessor/seq/for_each.hpp>\n\n#include <amgcl/backend/builtin.hpp>\n#include <amgcl/value_type/static_matrix.hpp>\n#include <amgcl/make_solver.hpp>\n#include <amgcl/amg.hpp>\n#include <amgcl/solver/runtime.hpp>\n#include <amgcl/coarsening/runtime.hpp>\n#include <amgcl/relaxation/runtime.hpp>\n#include <amgcl/relaxation/as_preconditioner.hpp>\n#include <amgcl/preconditioner/cpr.hpp>\n#include <amgcl/adapter/crs_tuple.hpp>\n#include <amgcl/adapter/block_matrix.hpp>\n#include <amgcl/io/mm.hpp>\n#include <amgcl/io/binary.hpp>\n#include <amgcl/profiler.hpp>\n\nnamespace amgcl { profiler<> prof; }\nusing amgcl::prof;\nusing amgcl::precondition;\n\n//---------------------------------------------------------------------------\ntemplate <class Matrix>\nvoid solve_cpr(const Matrix &K, const std::vector<double> &rhs, boost::property_tree::ptree &prm)\n{\n    auto t1 = prof.scoped_tic(\"CPR\");\n\n    typedef amgcl::backend::builtin<double> Backend;\n\n    typedef\n        amgcl::amg<Backend, amgcl::runtime::coarsening::wrapper, amgcl::runtime::relaxation::wrapper>\n        PPrecond;\n\n    typedef\n        amgcl::relaxation::as_preconditioner<Backend, amgcl::runtime::relaxation::wrapper>\n        SPrecond;\n\n    prof.tic(\"setup\");\n    amgcl::make_solver<\n        amgcl::preconditioner::cpr<PPrecond, SPrecond>,\n        amgcl::runtime::solver::wrapper<Backend>\n        > solve(K, prm);\n    prof.toc(\"setup\");\n\n    std::cout << solve.precond() << std::endl;\n\n    std::vector<double> x(rhs.size(), 0.0);\n\n    size_t iters;\n    double error;\n\n    prof.tic(\"setup\");\n    std::tie(iters, error) = solve(rhs, x);\n    prof.toc(\"setup\");\n\n    std::cout << \"Iterations: \" << iters << std::endl\n              << \"Error:      \" << error << std::endl;\n}\n\n//---------------------------------------------------------------------------\ntemplate <int B, class Matrix>\nvoid solve_block_cpr(const Matrix &K, const std::vector<double> &rhs, boost::property_tree::ptree &prm)\n{\n    auto t1 = prof.scoped_tic(\"CPR\");\n\n    typedef amgcl::static_matrix<double, B, B> val_type;\n    typedef amgcl::static_matrix<double, B, 1> rhs_type;\n    typedef amgcl::backend::builtin<val_type>  SBackend;\n    typedef amgcl::backend::builtin<double>    PBackend;\n\n    typedef\n        amgcl::amg<\n            PBackend,\n            amgcl::runtime::coarsening::wrapper,\n            amgcl::runtime::relaxation::wrapper>\n        PPrecond;\n\n    typedef\n        amgcl::relaxation::as_preconditioner<\n            SBackend,\n            amgcl::runtime::relaxation::wrapper\n            >\n        SPrecond;\n\n    prof.tic(\"setup\");\n    amgcl::make_solver<\n        amgcl::preconditioner::cpr<PPrecond, SPrecond>,\n        amgcl::runtime::solver::wrapper<SBackend>\n        > solve(amgcl::adapter::block_matrix<val_type>(K), prm);\n    prof.toc(\"setup\");\n\n    std::cout << solve.precond() << std::endl;\n\n    std::vector<rhs_type> x(rhs.size(), amgcl::math::zero<rhs_type>());\n\n    auto rhs_ptr = reinterpret_cast<const rhs_type*>(rhs.data());\n    size_t n = amgcl::backend::rows(K) / B;\n\n    size_t iters;\n    double error;\n\n    prof.tic(\"solve\");\n    std::tie(iters, error) = solve(amgcl::make_iterator_range(rhs_ptr, rhs_ptr + n), x);\n    prof.toc(\"solve\");\n\n    std::cout << \"Iterations: \" << iters << std::endl\n              << \"Error:      \" << error << std::endl;\n}\n\n//---------------------------------------------------------------------------\nint main(int argc, char *argv[]) {\n    using std::string;\n    using std::vector;\n    using amgcl::prof;\n    using amgcl::precondition;\n\n    namespace po = boost::program_options;\n    namespace io = amgcl::io;\n\n    po::options_description desc(\"Options\");\n\n    desc.add_options()\n        (\"help,h\", \"show help\")\n        (\n         \"binary,B\",\n         po::bool_switch()->default_value(false),\n         \"When specified, treat input files as binary instead of as MatrixMarket. \"\n         \"It is assumed the files were converted to binary format with mm2bin utility. \"\n        )\n        (\n         \"matrix,A\",\n         po::value<string>()->required(),\n         \"The system matrix in MatrixMarket format\"\n        )\n        (\n         \"rhs,f\",\n         po::value<string>(),\n         \"The right-hand side in MatrixMarket format\"\n        )\n        (\n         \"runtime-block-size,b\",\n         po::value<int>(),\n         \"The block size of the system matrix set at runtime\"\n        )\n        (\n         \"static-block-size,c\",\n         po::value<int>()->default_value(1),\n         \"The block size of the system matrix set at compiletime\"\n        )\n        (\n         \"params,P\",\n         po::value<string>(),\n         \"parameter file in json format\"\n        )\n        (\n         \"prm,p\",\n         po::value< vector<string> >()->multitoken(),\n         \"Parameters specified as name=value pairs. \"\n         \"May be provided multiple times. Examples:\\n\"\n         \"  -p solver.tol=1e-3\\n\"\n         \"  -p precond.coarse_enough=300\"\n        )\n        ;\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n\n    if (vm.count(\"help\")) {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n\n    po::notify(vm);\n\n    boost::property_tree::ptree prm;\n    if (vm.count(\"params\")) read_json(vm[\"params\"].as<string>(), prm);\n\n    if (vm.count(\"prm\")) {\n        for(const string &v : vm[\"prm\"].as<vector<string> >()) {\n            amgcl::put(prm, v);\n        }\n    }\n\n    int cb = vm[\"static-block-size\"].as<int>();\n\n    if (vm.count(\"runtime-block-size\"))\n        prm.put(\"precond.block_size\", vm[\"runtime-block-size\"].as<int>());\n    else\n        prm.put(\"precond.block_size\", cb);\n\n    size_t rows;\n    vector<ptrdiff_t> ptr, col;\n    vector<double> val, rhs;\n    std::vector<char> pm;\n\n    {\n        auto t = prof.scoped_tic(\"reading\");\n\n        string Afile  = vm[\"matrix\"].as<string>();\n        bool   binary = vm[\"binary\"].as<bool>();\n\n        if (binary) {\n            io::read_crs(Afile, rows, ptr, col, val);\n        } else {\n            size_t cols;\n            std::tie(rows, cols) = io::mm_reader(Afile)(ptr, col, val);\n            precondition(rows == cols, \"Non-square system matrix\");\n        }\n\n        if (vm.count(\"rhs\")) {\n            string bfile = vm[\"rhs\"].as<string>();\n\n            size_t n, m;\n\n            if (binary) {\n                io::read_dense(bfile, n, m, rhs);\n            } else {\n                std::tie(n, m) = io::mm_reader(bfile)(rhs);\n            }\n\n            precondition(n == rows && m == 1, \"The RHS vector has wrong size\");\n        } else {\n            rhs.resize(rows, 1.0);\n        }\n    }\n\n#define CALL_BLOCK_SOLVER(z, data, B)                                          \\\n    case B:                                                                    \\\n        solve_block_cpr<B>(std::tie(rows, ptr, col, val), rhs, prm);           \\\n        break;\n\n    switch(cb) {\n        case 1:\n            solve_cpr(std::tie(rows, ptr, col, val), rhs, prm);\n            break;\n\n        BOOST_PP_SEQ_FOR_EACH(CALL_BLOCK_SOLVER, ~, AMGCL_BLOCK_SIZES)\n\n        default:\n            precondition(false, \"Unsupported block size\");\n            break;\n    }\n\n    std::cout << prof << std::endl;\n}\n", "meta": {"hexsha": "b1822d2510ad7a37139e39ee6331ac6201bd7cfc", "size": 7300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/cpr.cpp", "max_stars_repo_name": "tenglongcong/amgcl", "max_stars_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 504.0, "max_stars_repo_stars_event_min_datetime": "2015-03-11T13:50:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:08:55.000Z", "max_issues_repo_path": "examples/cpr.cpp", "max_issues_repo_name": "tenglongcong/amgcl", "max_issues_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 209.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T19:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T06:44:12.000Z", "max_forks_repo_path": "examples/cpr.cpp", "max_forks_repo_name": "tenglongcong/amgcl", "max_forks_repo_head_hexsha": "61948e1a49c1cbc9fdb68c92d532c8b70e021516", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 92.0, "max_forks_repo_forks_event_min_datetime": "2015-01-04T06:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T09:49:12.000Z", "avg_line_length": 28.9682539683, "max_line_length": 103, "alphanum_fraction": 0.5512328767, "num_tokens": 1874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4257054223269536}}
{"text": "/*\n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; either version 2 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n   Product name: redemption, a FLOSS RDP proxy\n   Copyright (C) Wallix 2016\n   Author(s): Christophe Grosjean\n\n*/\n\n#include \"utils/crypto/ssl_mod_exp_direct.hpp\"\n\n#include <cassert>\n#include <cstddef>\n\n#include \"cxx/diagnostic.hpp\"\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n/**\n * \\pre  \\a out_len >= \\a modulus_size\n * \\return  the length of the big-endian number placed at out. ~size_t{} if error\n */\nwritable_bytes_view mod_exp_direct(\n    writable_bytes_view out,\n    bytes_view inr,\n    bytes_view modulus,\n    bytes_view exponent\n) {\n    assert(out.size() >= modulus.size());\n\n    using int_type = boost::multiprecision::cpp_int;\n\n    auto b256_to_bigint = [](bytes_view s) {\n        int_type i;\n        boost::multiprecision::import_bits(i, s.begin(), s.end());\n        return i;\n    };\n\n    int_type base = b256_to_bigint(inr);\n    int_type exp = b256_to_bigint(exponent);\n    int_type m = b256_to_bigint(modulus);\n\n    REDEMPTION_DIAGNOSTIC_PUSH()\n    REDEMPTION_DIAGNOSTIC_GCC_IGNORE(\"-Wzero-as-null-pointer-constant\")\n    int_type r = boost::multiprecision::powm(base, exp, m);\n    REDEMPTION_DIAGNOSTIC_POP()\n\n    auto it = boost::multiprecision::export_bits(r, out.data(), 8);\n    auto r_len = static_cast<size_t>(it - out.data());\n    *it = 0;\n    if (r_len == 1 && out[0] == 0) {\n        r_len = 0;\n    }\n    return out.first(r_len);\n}\n", "meta": {"hexsha": "5039da95b116c57c08a83d7ba3fe70c5730f7e08", "size": 2051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "redemption/src/utils/crypto/ssl_mod_exp_direct.cpp", "max_stars_repo_name": "DianaAssistant/DIANA", "max_stars_repo_head_hexsha": "6a4c51c1861f6a936941b21c2c905fc291c229d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "redemption/src/utils/crypto/ssl_mod_exp_direct.cpp", "max_issues_repo_name": "DianaAssistant/DIANA", "max_issues_repo_head_hexsha": "6a4c51c1861f6a936941b21c2c905fc291c229d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "redemption/src/utils/crypto/ssl_mod_exp_direct.cpp", "max_forks_repo_name": "DianaAssistant/DIANA", "max_forks_repo_head_hexsha": "6a4c51c1861f6a936941b21c2c905fc291c229d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1617647059, "max_line_length": 81, "alphanum_fraction": 0.6967333008, "num_tokens": 533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5660185351961016, "lm_q1q2_score": 0.42565305544857074}}
{"text": "﻿/*! \\file freefallsolveeom.cpp\n    \\brief 空気抵抗のある自由落下系に対して運動方程式を解くクラスの実装\n\n    Copyright © 2018 @dc1394 All Rights Reserved.\n    This software is released under the BSD 2-Clause License.\n*/\n#include \"freefallsolveeom.h\"\n#include <cmath>                                // for std::cos, std::floor, std::log10\n#include <cstdio>                               // for std::fclose, std::fflush, std::fopen, std::fwrite\n#include <optional>                             // for std::make_optional\n#include <queue>                                // for std::queue\n#include <string>                               // for std::to_string\n#include <tuple>                                // for std::get, std::make_tuple\n#include <utility>                              // for std::make_pair  \n#include <boost/assert.hpp>                     // for BOOST_ASSERT\n#include <boost/math/constants/constants.hpp>   // for boost::math::constants::pi\n#include <boost/math/tools/minima.hpp>          // for boost::math::tools::brent_find_minima\n#include <boost/math/tools/roots.hpp>           // for boost::math::tools::bisect\n\nnamespace freefallsolveeom {\n    // #region コンストラクタ・デストラクタ\n\n    FreefallSolveEom::FreefallSolveEom(double dt, double tintervalgraphplot, double eps, double m, double r, double h0, double v0, Ode_Solver_type ode_solver_type) :\n        acc_(gsl_interp_accel_alloc(), gsl_interp_accel_deleter),\n        dt_(dt),\n        eps_(eps),\n        fp_(nullptr, std::fclose),\n        h0_(h0),\n        imax_(static_cast<std::int32_t>(tintervalgraphplot / dt)),\n        l2divm2northlatitude45_(sqr(sqr(FreefallSolveEom::R0 + h0) * 2.0 * pi<double>() / (24.0 * 60.0 * 60.0)) * std::cos(pi<double>() * 0.25)),\n        m_(m),\n        ode_solver_type_(ode_solver_type),\n        r_(r),\n        spherevolume_(4.0 / 3.0 * boost::math::constants::pi<double>() * r * r * r),\n        spline_pressure_(nullptr, gsl_spline_deleter),\n        spline_temperature_(nullptr, gsl_spline_deleter),\n        tintervalgraphplot_(tintervalgraphplot),\n        tintervaloutputcsv_(std::nullopt),\n        islargertintervaloutputcsv_(std::nullopt),\n        v0_(v0),\n\t\tx_({ R0 + h0, v0 })\n    {\n        initialize();\n    }\n\n    FreefallSolveEom::FreefallSolveEom(double dt, double tintervalgraphplot, double tintervaloutputcsv, std::string const & csvfilename, double eps, double m, double r, double h0, double v0, Ode_Solver_type ode_solver_type) :\n        acc_(gsl_interp_accel_alloc(), gsl_interp_accel_deleter),\n        dt_(dt),\n        eps_(eps),\n        fp_(std::unique_ptr< FILE, decltype(&std::fclose) >(std::fopen(csvfilename.c_str(), \"w\"), std::fclose)),\n        h0_(h0),\n        imax_(static_cast<std::int32_t>(tintervalgraphplot / dt)),\n        l2divm2northlatitude45_(sqr(sqr(FreefallSolveEom::R0 + h0) * 2.0 * pi<double>() / (24.0 * 60.0 * 60.0)) * std::cos(pi<double>() * 0.25)),\n        m_(m),\n        ode_solver_type_(ode_solver_type),\n        outputtocsvdigits_(std::to_string(tintervaloutputcsv > 0.1 ? 1 : static_cast<std::int32_t>(std::ceil(-std::log10(tintervaloutputcsv))))),\n        r_(r),\n        spherevolume_(4.0 / 3.0 * boost::math::constants::pi<double>() * r * r * r),\n        spline_pressure_(nullptr, gsl_spline_deleter),\n        spline_temperature_(nullptr, gsl_spline_deleter),\n        tintervalgraphplot_(tintervalgraphplot),\n        tintervaloutputcsv_(std::make_optional(tintervaloutputcsv)),\n        islargertintervaloutputcsv_(std::make_optional(tintervalgraphplot <= tintervaloutputcsv)),\n        v0_(v0),\n        x_({ R0 + h0, v0 })\n    {\n        initialize();\n    }\n\n    // #endregion コンストラクタ・デストラクタ\n\n    // #region publicメンバ関数\n\n    std::tuple< double, double, double, FreefallSolveEom::hmaxtype, FreefallSolveEom::vmaxtype, FreefallSolveEom::tandvtype, FreefallSolveEom::tandvandbooltype > FreefallSolveEom::operator()()\n    {\n        FreefallSolveEom::state_type result{};\n        switch (ode_solver_type_) {\n        case Ode_Solver_type::ADAMS_BASHFORTH_MOULTON:\n            result = solveeom_run(adams_bashforth_moulton< 2, FreefallSolveEom::state_type >());\n            break;\n\n        case Ode_Solver_type::BULIRSCH_STOER:\n            result = solveeom_run(bulirsch_stoer< FreefallSolveEom::state_type >(eps_, eps_));\n            break;\n\n        case Ode_Solver_type::CONTROLLED_RUNGE_KUTTA:\n            result = solveeom_run(make_controlled(eps_, eps_, error_stepper_type()));\n            break;\n\n        default:\n            BOOST_ASSERT(!\"Ode_Solver_typeがあり得ない値になっている！\");\n            break;\n        }\n\n        auto const t = iscalculationfinished_ ? tend_ : t_;\n        auto const h = result[0] - FreefallSolveEom::R0;\n        auto const v = result[1];\n\n        FreefallSolveEom::hmaxtype stateofhmax = std::nullopt;\n        if (hmaxoftandh_)\n        {\n            stateofhmax = hmaxoftandh_;\n        }\n        else if (v0_ <= 0.0)\n        {\n            stateofhmax = std::make_optional(std::make_pair(0.0, h0_));\n        }\n        \n        FreefallSolveEom::vmaxtype stateofvmax = std::nullopt;\n        if (vmaxoftandhandv_ && std::fabs(std::get<2>(*vmaxoftandhandv_)) >= std::fabs(v0_))\n        {\n            stateofvmax = vmaxoftandhandv_;\n        }\n        else if (vmaxoftandhandv_ || (iscalculationfinished_ && std::fabs(v) < std::fabs(v0_)))\n        {\n            stateofvmax = std::make_optional(std::make_tuple(0.0, h0_, v0_));    \n        }\n        else if (iscalculationfinished_ && std::fabs(v) >= std::fabs(v0_))\n        {\n            stateofvmax = std::make_optional(std::make_tuple(t, h, v));\n        }\n\n        return std::make_tuple(t, h, v, stateofhmax, stateofvmax, stateescapeofkarmanline_, stateescapeofexosphere_);\n    }\n\n    // #endregion publicメンバ関数\n\n    // #region privateメンバ関数\n\n    double FreefallSolveEom::get_P(double r) const\n    {\n        // ジオポテンシャル高度を取得\n        auto const H = getGeopotentialFromAltitude(r);\n\n        // 「標準大気 ー 各高度における空気の温度・圧力・密度・音速・粘性係数・動粘性係数の計算式」\n        // https://pigeon-poppo.com/standard-atmosphere/ より\n        if (H <= 11000.0)\n        {\n            return 101325.0 * std::pow(288.15 / FreefallSolveEom::get_T(r), -5.256);\n        }\n        else if (H <= 20000.0)\n        {\n            return 22632.064 * std::exp(-0.1577 * (FreefallSolveEom::MTOKM * H - 11.0));\n        }\n        else if (H <= 32000.0)\n        {\n            return 5474.889 * std::pow(216.65 / FreefallSolveEom::get_T(r), 34.163);\n        }\n        else if (H <= 47000.0)\n        {\n            return 868.019 * std::pow(228.65 / FreefallSolveEom::get_T(r), 12.201);\n        }\n        else if (H <= 51000.0)\n        {\n            return 110.906 * std::exp(-0.1262 * (FreefallSolveEom::MTOKM * H - 47.0));\n        }\n        else if (H <= 71000.0)\n        {\n            return 66.939 * std::pow(270.65 / FreefallSolveEom::get_T(r), -12.201);\n        }\n        else if (H <= 84852.0)\n        {\n            return 3.956 * std::pow(214.65 / FreefallSolveEom::get_T(r), -17.082);\n        }\n        else if (r - FreefallSolveEom::R0 <= 1000000.0)\n        {   \n            return gsl_spline_eval(spline_pressure_.get(), r - FreefallSolveEom::R0, acc_.get());\n        }\n        else\n        {\n            return 0.0;\n        }\n    }\n\n    double FreefallSolveEom::get_T(double r) const\n    {\n        // ジオポテンシャル高度を取得\n        auto const H = getGeopotentialFromAltitude(r);\n        \n        // 「標準大気 ー 各高度における空気の温度・圧力・密度・音速・粘性係数・動粘性係数の計算式」\n        // https://pigeon-poppo.com/standard-atmosphere/ より\n        if (H <= 11000.0)\n        {\n            return FreefallSolveEom::CELSIUSTOABSOLUTETEMPERATURE + 15.0 - 6.5 * FreefallSolveEom::MTOKM * H;\n        }\n        else if (H <= 20000.0)\n        {\n            return FreefallSolveEom::CELSIUSTOABSOLUTETEMPERATURE - 56.5;\n        }\n        else if (H <= 32000.0)\n        {\n            return FreefallSolveEom::CELSIUSTOABSOLUTETEMPERATURE - 76.5 + FreefallSolveEom::MTOKM * H;\n        }\n        else if (H <= 47000.0)\n        {\n            return FreefallSolveEom::CELSIUSTOABSOLUTETEMPERATURE - 134.1 + 2.8 * FreefallSolveEom::MTOKM * H;\n        }\n        else if (H <= 51000.0)\n        {\n            return FreefallSolveEom::CELSIUSTOABSOLUTETEMPERATURE - 2.5;\n        }\n        else if (H <= 71000.0)\n        {\n            return FreefallSolveEom::CELSIUSTOABSOLUTETEMPERATURE + 140.3 - 2.8 * FreefallSolveEom::MTOKM * H;\n        }\n        else if (H <= 84852.0)\n        {\n            return FreefallSolveEom::CELSIUSTOABSOLUTETEMPERATURE + 83.5 - 2.0 * FreefallSolveEom::MTOKM * H;\n        }\n        else if (r - FreefallSolveEom::R0 <= 1000000.0)\n        {\n            return gsl_spline_eval(spline_temperature_.get(), r - FreefallSolveEom::R0, acc_.get());\n        }\n        else\n        {\n            return 1000.0;\n        }\n    }\n\n    void FreefallSolveEom::initialize()\n    {\n        // 高度80km以上での気圧と温度のデータ\n        // 国立天文台編『理科年表』丸善出版（2012）p.331より引用\n        p_data_ = { 1.0524,    0.37338,   0.18359,   0.15381,   3.2011E-2, 7.1042E-3,\n                    2.5382E-3, 1.2505E-3, 7.2028E-4, 3.0395E-4, 1.5271E-4, 8.4736E-5,\n                    2.4767E-5, 8.7704E-6, 3.4498E-6, 1.4518E-6, 6.4468E-7, 3.0236E-7,\n                    1.5137E-7, 8.2130E-8, 4.8865E-8, 3.1908E-8, 2.2599E-8, 1.7036E-8,\n                    1.3415E-8, 1.0873E-8, 7.5138E-9 };\n\n        t_data_ = { 198.639, 186.87, 186.87, 186.87, 195.08, 240.00, 360.00, 469.27,\n                    559.63,  696.29, 790.07, 854.56, 941.33, 976.01, 990.06, 995.83,\n                    998.22,  999.24, 999.67, 999.85, 999.93, 999.97, 999.99, 999.99,\n                    1000.0,  1000.0, 1000.0 };\n\n        z_mesh_ = { 80000.0,  86000.0,  90000.0,  91000.0,  100000.0, 110000.0,\n                    120000.0, 130000.0, 140000.0, 160000.0, 180000.0, 200000.0,\n                    250000.0, 300000.0, 350000.0, 400000.0, 450000.0, 500000.0,\n                    550000.0, 600000.0, 650000.0, 700000.0, 750000.0, 800000.0,\n                    850000.0, 900000.0, 1000000.0 };\n\n        BOOST_ASSERT(p_data_.size() == z_mesh_.size());\n        BOOST_ASSERT(t_data_.size() == z_mesh_.size());\n\n        spline_pressure_.reset(gsl_spline_alloc(gsl_interp_cspline, z_mesh_.size()));\n        spline_temperature_.reset(gsl_spline_alloc(gsl_interp_cspline, z_mesh_.size()));\n\n        gsl_spline_init(spline_pressure_.get(), z_mesh_.data(), p_data_.data(), z_mesh_.size());\n        gsl_spline_init(spline_temperature_.get(), z_mesh_.data(), t_data_.data(), z_mesh_.size());\n    }\n    \n    template <typename Stepper>\n    FreefallSolveEom::state_type FreefallSolveEom::solveeom_run(Stepper const & stepper)\n    {\n        using namespace boost::math::tools;\n\n        if (isfirststep_)\n        {\n            if (fp_)\n            {\n                outputresulttocsv(0.0, x_);\n            }\n\n            // 0秒目ですでにカーマン・ラインを突破しているかどうか\n            if (x_[0] >= FreefallSolveEom::KARMANLINE)\n            {\n                stateescapeofkarmanline_ = std::make_optional(std::make_pair(0.0, v0_));\n            }\n\n            // 0秒目ですでに外気圏を脱出しているかどうか\n            if (x_[0] >= FreefallSolveEom::ALTITUDEOFEXOSPHERE)\n            {\n                // 外気圏を脱出した際に速度が第二宇宙速度以上だったかどうか\n                if (x_[1] >= FreefallSolveEom::SECONDESCAPEVELOCITYOFEXOSPHERE)\n                {\n                    stateescapeofexosphere_ = std::make_optional(std::make_tuple(0.0, v0_, true));\n\n                    // 計算打ち切り\n                    iscalculationfinished_ = true;\n                    tend_ = 0.0;\n                }\n                else\n                {\n                    stateescapeofexosphere_ = std::make_optional(std::make_tuple(0.0, v0_, false));\n                }\n            }\n\n            isfirststep_ = false;\n            return x_;\n        }\n\n        std::queue<FreefallSolveEom::state_type> history{};\n\n        for (auto i = 1; i <= imax_; i++) {\n            auto const ttmp = static_cast<double>(i) * dt_;\n\n            if (history.size() < 2)\n            {\n                history.push(x_);\n            }\n            else\n            {\n                history.pop();\n                history.push(x_);\n            }\n\n            integrate_eom(stepper, dt_, x_);\n\n            if (vmaxoftandhandv_ && x_[1] < 0.0)\n            {\n                BOOST_ASSERT(std::get<2>(*vmaxoftandhandv_) < x_[1]);\n            }\n\n            auto const statebefore = history.back();\n\n            // カーマン・ラインを突破した際の時間を探索\n            if (!stateescapeofkarmanline_ && x_[0] >= FreefallSolveEom::KARMANLINE)\n            {\n                auto maxit = MAXITER;\n                auto res = bisect(\n                    [&stepper, &statebefore, this](double t)\n                {\n                    auto x = statebefore;\n                    integrate_eom(stepper, t, x);\n                    return x[0] - FreefallSolveEom::KARMANLINE;\n                },\n                    0.0,\n                    dt_,\n                    eps_tolerance<double>(FreefallSolveEom::DIGITS),\n                    maxit);\n\n                auto const tescapeofkarmanline = (res.first + res.second) * 0.5;\n                auto xtmp(statebefore);\n                integrate_eom(stepper, tescapeofkarmanline, xtmp);\n\n                stateescapeofkarmanline_ = std::make_optional(std::make_pair(t_ + static_cast<double>(i - 1) * dt_ + tescapeofkarmanline, xtmp[1]));\n            }\n\n            // 外気圏を脱出した際の時間を探索\n            if (!stateescapeofexosphere_ && x_[0] >= FreefallSolveEom::ALTITUDEOFEXOSPHERE)\n            {\n                auto maxit = MAXITER;\n                auto res = bisect(\n                    [&stepper, &statebefore, this](double t)\n                {\n                    auto x = statebefore;\n                    integrate_eom(stepper, t, x);\n                    return x[0] - FreefallSolveEom::ALTITUDEOFEXOSPHERE;\n                },\n                    0.0,\n                    dt_,\n                    eps_tolerance<double>(FreefallSolveEom::DIGITS),\n                    maxit);\n\n                auto const tescapeofexosphere = (res.first + res.second) * 0.5;\n                auto xtmp(statebefore);\n                integrate_eom(stepper, tescapeofexosphere, xtmp);\n\n                // 外気圏を脱出した際に速度が第二宇宙速度以上だったかどうか\n                if (xtmp[1] >= FreefallSolveEom::SECONDESCAPEVELOCITYOFEXOSPHERE)\n                {\n                    stateescapeofexosphere_ = std::make_optional(std::make_tuple(t_ + static_cast<double>(i - 1) * dt_ + tescapeofexosphere, xtmp[1], true));\n\n                    // 計算打ち切り\n                    iscalculationfinished_ = true;\n                    tend_ = t_ + static_cast<double>(i - 1) * dt_ + tescapeofexosphere;\n\n                    return xtmp;\n                }\n                else\n                {\n                    stateescapeofexosphere_ = std::make_optional(std::make_tuple(t_ + static_cast<double>(i - 1) * dt_ + tescapeofexosphere, xtmp[1], false));\n                }\n            }\n            \n            // 地面に衝突する時の速度とその際の時間を探索\n            if (x_[0] < FreefallSolveEom::R0)\n            {\n                auto maxit = MAXITER;\n                auto res = bisect(\n                    [&stepper, &statebefore, this](double t)\n                {\n                    auto x = statebefore;\n                    integrate_eom(stepper, t, x);\n                    return x[0] - FreefallSolveEom::R0;\n                },\n                    0.0,\n                    dt_,\n                    eps_tolerance<double>(FreefallSolveEom::DIGITS),\n                    maxit);\n\n                auto const tendtmp = (res.first + res.second) * 0.5;\n                auto xtmp(statebefore);\n                integrate_eom(stepper, tendtmp, xtmp);\n\n                tend_ = t_ + static_cast<double>(i - 1) * dt_ + tendtmp;\n                                \n                if (fp_)\n                {\n                    outputresulttocsv(tend_, xtmp);\n                    std::fflush(fp_.get());\n                    fp_.reset();\n                }\n                \n                iscalculationfinished_ = true;\n\n                return xtmp;\n            }\n\n            // 最高到達高度とその際の時間の探索\n            if (statebefore[1] * x_[1] <= 0.0)\n            {\n                auto maxit = MAXITER;\n                auto const res = bisect(\n                    [&stepper, &statebefore, this](double t)\n                {\n                    auto x = statebefore;\n                    integrate_eom(stepper, t, x);\n                    return x[1];\n                },\n                    0.0,\n                    dt_,\n                    eps_tolerance<double>(FreefallSolveEom::DIGITS),\n                    maxit);\n\n                auto const thmaxtmp = (res.first + res.second) * 0.5;\n                auto xtmp(statebefore);\n                integrate_eom(stepper, thmaxtmp, xtmp);\n\n                hmaxoftandh_ = std::make_optional(std::make_pair(t_ + static_cast<double>(i - 1) * dt_ + thmaxtmp, xtmp[0] - FreefallSolveEom::R0));\n            }\n\n            // 最高速度とその際の時間と高度の探索\n            if (!vmaxoftandhandv_ && x_[1] < 0.0 && x_[1] > statebefore[1])\n            {\n                auto maxit = MAXITER;\n                auto state2before = history.front();\n                auto const res = brent_find_minima(\n                    [&stepper, &state2before, this](double t)\n                {\n                    auto x = state2before;\n                    integrate_eom(stepper, t, x);\n                    return x[1];\n                },\n                    0.0,\n                    2.0 * dt_,\n                    FreefallSolveEom::DIGITS,\n                    maxit);\n\n                auto xtmp(state2before);\n                integrate_eom(stepper, res.first, xtmp);\n\n                BOOST_ASSERT(xtmp[1] < state2before[1]);\n                BOOST_ASSERT(xtmp[1] < statebefore[1]);\n                BOOST_ASSERT(xtmp[1] < x_[1]);\n\n                vmaxoftandhandv_ = std::make_optional(std::make_tuple(t_ + static_cast<double>(i - 2) * dt_ + res.first, xtmp[0] - FreefallSolveEom::R0, xtmp[1]));\n            }\n\n            if (tintervaloutputcsv_ &&\n                !(*islargertintervaloutputcsv_) &&\n                (std::fabs(ttmp / *tintervaloutputcsv_ - std::floor(ttmp / *tintervaloutputcsv_)) <= FreefallSolveEom::ZERODECISIONTOCSV || std::fabs(ttmp / *tintervaloutputcsv_ - std::ceil(ttmp / *tintervaloutputcsv_)) <= FreefallSolveEom::ZERODECISIONTOCSV))\n            {\n                outputresulttocsv(t_ + ttmp, x_);\n            }\n        }\n\n        cnt_++;\n        t_ = static_cast<double>(cnt_) * tintervalgraphplot_;\n\n        if (tintervaloutputcsv_ &&\n            *islargertintervaloutputcsv_ &&\n            (std::fabs(t_ / *tintervaloutputcsv_ - std::floor(t_ / *tintervaloutputcsv_)) <= FreefallSolveEom::ZERODECISIONTOCSV || std::fabs(t_ / *tintervaloutputcsv_ - std::ceil(t_ / *tintervaloutputcsv_)) <= FreefallSolveEom::ZERODECISIONTOCSV))\n        {\n            outputresulttocsv(t_, x_);\n        }\n                \n        return x_;\n    }\n\n    // #endregion privateメンバ関数\n\n    // #region templateメンバ関数の実体化\n\n    template FreefallSolveEom::state_type FreefallSolveEom::solveeom_run<adams_bashforth_moulton< 2, FreefallSolveEom::state_type > >(adams_bashforth_moulton< 2, state_type > const & stepper);\n    template FreefallSolveEom::state_type FreefallSolveEom::solveeom_run<bulirsch_stoer < FreefallSolveEom::state_type > >(bulirsch_stoer < state_type > const & stepper);\n    template FreefallSolveEom::state_type FreefallSolveEom::solveeom_run<FreefallSolveEom::error_stepper_type>(error_stepper_type const & stepper);\n\n    // #endregion templateメンバ関数の実体化\n\n    // #region staticメンバ変数\n\n    const double FreefallSolveEom::SECONDESCAPEVELOCITYOFEXOSPHERE = std::sqrt(2.0 * FreefallSolveEom::G * FreefallSolveEom::M / FreefallSolveEom::ALTITUDEOFEXOSPHERE);\n\n    // #endregion staticメンバ変数\n}\n", "meta": {"hexsha": "fe1f25e9e45fb66367c28bda25250b9ada54de02", "size": 19683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Freefall/freefallsolveeom/freefallsolveeom.cpp", "max_stars_repo_name": "dc1394/Freefall", "max_stars_repo_head_hexsha": "a44993c1f2c08bedac84af158c75933e89cc6318", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Freefall/freefallsolveeom/freefallsolveeom.cpp", "max_issues_repo_name": "dc1394/Freefall", "max_issues_repo_head_hexsha": "a44993c1f2c08bedac84af158c75933e89cc6318", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Freefall/freefallsolveeom/freefallsolveeom.cpp", "max_forks_repo_name": "dc1394/Freefall", "max_forks_repo_head_hexsha": "a44993c1f2c08bedac84af158c75933e89cc6318", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6834677419, "max_line_length": 260, "alphanum_fraction": 0.5403647818, "num_tokens": 6073, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.42549638180041555}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// Fields.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//  Classes implementing vector/scalar/tensor fields. Each class also specifies\n//  how the quantities are flattened into a single 1D array. Field samples are\n//  stored as columns of a dim x |D| 2D array that is then flattened in column\n//  major format. Here |D| is the size of the discrete domain.\n//\n//  This means, for symmetric tensor fields, there are two flattenings: first\n//  each sample is flattened into a 6-vector (in 3D) using Voigt notation, then\n//  each 6-vector is stored as a column in a 6 x |D| array, which is flattened\n//  into a 6 |D| vector.\n//\n//  For vector fields, the resulting flattened vector looks like:\n//      [v_0x, v_0y, v_0z, v_1x, ..., v_|D|z]\n//  This vector can be obtained with the getFlattened() method.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Company:  New York University\n//  Created:  02/13/2013 16:27:14\n////////////////////////////////////////////////////////////////////////////////\n#ifndef FIELDS_HH\n#define FIELDS_HH\n#include <Eigen/Dense>\n#include <vector>\n#include <string>\n#include <cassert>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <stdexcept>\n#include <cmath>\n#include <limits>\n\n#include \"Flattening.hh\"\n#include \"SymmetricMatrix.hh\"\n\n#include \"Algebra.hh\"\n\ntypedef enum { FIELD_SCALAR, FIELD_VECTOR, FIELD_MATRIX} FieldType;\nenum class DomainType { PER_ELEMENT = 0, PER_NODE = 1, ANY = 3, GUESS = 3, UNKNOWN = -1};\n\ntemplate<typename Real, size_t t_dim>\nclass VectorField : public VectorSpace<Real, VectorField<Real, t_dim>> {\npublic:\n    typedef Eigen::Matrix<Real, Eigen::Dynamic, 1> FlattenedType;\n    typedef Eigen::Matrix<Real, t_dim, Eigen::Dynamic> ArrayType;\n    typedef typename ArrayType::ColXpr         ValueType;\n    typedef typename ArrayType::ConstColXpr    ConstValueType;\n\n    // Copy and move constructors/assignment\n    VectorField(const VectorField  &b) = default;\n    VectorField(      VectorField &&b) = default;\n    VectorField &operator=(const VectorField  &b) = default;\n    VectorField &operator=(      VectorField &&b) = default;\n\n    // Flattened data constructor\n    // Note: copies data\n    VectorField(const FlattenedType &values) {\n        size_t domainSize = values.rows() / t_dim;\n        assert(t_dim * domainSize == (size_t) values.rows());\n        m_values = Eigen::Map<const ArrayType>(values.data(), t_dim,\n                                               domainSize);\n    }\n\n    // Flattened data constructor (std::vector version)\n    template<typename Real2>\n    VectorField(const std::vector<Real2> &values) {\n        size_t domainSize = values.size() / t_dim;\n        if (t_dim * domainSize != values.size())\n            throw std::runtime_error(\"Invalid flattened field size (not an \" + std::to_string(t_dim) + \"D field)\");\n        m_values = Eigen::Map<const Eigen::Matrix<Real2, t_dim, Eigen::Dynamic> >\n            (&values[0], t_dim, domainSize);\n    }\n\n    // Uninitialized allocation constructor\n    explicit VectorField(size_t domainSize = 0)\n        : m_values(t_dim, domainSize) { }\n\n    ConstValueType operator()(size_t i) const {\n        assert(i < (size_t) m_values.cols());\n        return m_values.col(i);\n    }\n\n    ValueType operator()(size_t i) {\n        assert(i < (size_t) m_values.cols());\n        return m_values.col(i);\n    }\n\n    void clear() { m_values = ArrayType::Zero(dim(), domainSize()); }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // VectorSpace requirements\n    ////////////////////////////////////////////////////////////////////////////\n    void Add(const VectorField &b) { m_values += b.m_values; }\n    void Scale(Real scalar)        { m_values *= scalar; }\n\n    // Normalize data so that the maximum column magnitude is 1.\n    void maxColumnNormalize() { m_values /= maxMag(); }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Non-VectorSpace operations.\n    ////////////////////////////////////////////////////////////////////////////\n    Real maxMag() const {\n        Real maxNorm = 0;\n        for (size_t i = 0; i < domainSize(); ++i)\n            maxNorm = std::max(maxNorm, m_values.col(i).norm());\n        return maxNorm;\n    }\n\n    Real minMag() const {\n        Real minNorm = std::numeric_limits<Real>::max();\n        for (size_t i = 0; i < domainSize(); ++i)\n            minNorm = std::min(minNorm, m_values.col(i).norm());\n        return minNorm;\n    }\n\n    // Component wise abs.\n    VectorField cwiseAbs() const { auto r = VectorField(*this); r.m_values = r.m_values.cwiseAbs(); return r; }\n\n    // Set all coefficients to a constant\n    void setConstant(Real val) { m_values.setConstant(val); }\n\n    // Sum of squared norms of each vector.\n    Real frobeniusNormSq() const {\n        Real normSq = 0;\n        for (size_t i = 0; i < domainSize(); ++i)\n            normSq += m_values.col(i).squaredNorm();\n        return normSq;\n    }\n\n    // Scalar-valued inner product between vector field: apply dot product\n    // pointwise and sum.\n    Real innerProduct(const VectorField &b) const {\n        assert(domainSize() == b.domainSize());\n        Real result = 0;\n        for (size_t i = 0; i < domainSize(); ++i)\n            result += m_values.col(i).dot(b.m_values.col(i));\n        return result;\n    }\n\n    // Unweighted mean vector.\n    Eigen::Matrix<Real, t_dim, 1> mean() const {\n        Eigen::Matrix<Real, t_dim, 1> result;\n        result.setZero();\n        for (size_t i = 0; i < domainSize(); ++i)\n            result += m_values.col(i);\n        result *= (1.0 / domainSize());\n        return result;\n    }\n\n    const ArrayType &data() const { return m_values; }\n          ArrayType &data()       { return m_values; }\n\n    size_t dim() const { return t_dim; }\n    size_t N()   const { return dim(); }\n    size_t domainSize() const { return m_values.cols(); }\n    FieldType fieldType() const { return FIELD_VECTOR; }\n\n    void resizeDomain(size_t dSize) {\n        m_values.resize(Eigen::NoChange, dSize);\n        clear();\n    }\n\n    // Flattened access\n    size_t size() const { return dim() * domainSize(); }\n    void resize(size_t i) { assert(i % dim() == 0); resizeDomain(i / dim()); }\n          Real &operator[](size_t i)       { assert(i < size()); return m_values.data()[i]; }\n    const Real &operator[](size_t i) const { assert(i < size()); return m_values.data()[i]; }\n\n    template<typename Real2>\n    void getFlattened(std::vector<Real2> &v) const {\n        v.resize(size());\n        for (size_t i = 0; i < size(); ++i)\n            v[i] = operator[](i);\n    }\n\n    void print(std::ostream &os, const std::string &componentSeparator = \"\\t\",\n               const std::string &elementPrefix = \"\",\n               const std::string &elementSuffix = \"\\n\",\n               const std::string &elementSeparator = \"\") const {\n        for (size_t i = 0; i < domainSize(); ++i) {\n            if (i) os << elementSeparator;\n            ConstValueType v = (*this)(i);\n            os << elementPrefix << v[0];\n            for (size_t j = 1; j < t_dim; ++j) {\n                os << componentSeparator << v[j];\n            }\n            os << elementSuffix;\n        }\n    }\n\n    void dump(const std::string &path) const {\n        std::ofstream of(path);\n        if (!of.is_open())\n            throw std::runtime_error(std::string(\"Couldn't open '\") +\n                        path + \"' for writing.\");\n        of << std::scientific << std::setprecision(16);\n        print(of);\n    }\n\nprotected:\n    /** Data storage */\n    ArrayType m_values;\n};\n\ntemplate<typename Real>\nclass ScalarField : public VectorField<Real, 1> {\npublic:\n    using typename VectorField<Real, 1>::FlattenedType;\n    typedef Real value_type;\n\n    // ScalarField's value type should act both like a vector (to mimic\n    // base class VectorField<Real, 1>) and like a scalar (via typecasts)\n    class ValueType {\n    public:\n        ValueType(Real &val) : m_val(val) { }\n              Real &operator[](size_t i)       { (void) (i); assert(i == 0); return m_val; }\n        const Real &operator[](size_t i) const { (void) (i); assert(i == 0); return m_val; }\n        operator Real&()      { return m_val; }\n        operator Real() const { return m_val; }\n        ValueType &operator=(Real val) { m_val = val; return *this; }\n    private:\n        Real &m_val;\n    };\n    class ConstValueType {\n    public:\n        ConstValueType(const Real &val) : m_val(val) { }\n        Real  operator[](size_t i) const { (void) i; assert(i == 0); return m_val; }\n        operator Real() const { return m_val; }\n    private:\n        const Real &m_val;\n    };\n\n    ScalarField(const FlattenedType &values)\n        : VectorField<Real, 1>(values) { }\n    explicit ScalarField(size_t domainSize = 0)\n        : VectorField<Real, 1>(domainSize) { }\n    template<typename Real2>\n    ScalarField(const std::vector<Real2> &values)\n        : VectorField<Real, 1>(values) { }\n    // Allow construction from 1-dim vector.\n    template<typename Real2>\n    ScalarField(const VectorField<Real2, 1> &values)\n        : VectorField<Real, 1>(values) { }\n\n    FieldType fieldType() const { return FIELD_SCALAR; }\n\n    Real squaredNorm() const { return m_values.squaredNorm(); }\n    Real norm() const { return m_values.norm(); }\n    Real  sum() const { return m_values.sum(); }\n    Real  min() const { return m_values.minCoeff(); }\n    Real  max() const { return m_values.maxCoeff(); }\n\n    // Return the entry with maximum/minimum magnitude\n    Real minMag() const { Real m = min(), M = max(); return (std::abs(m) < M) ? m : M; }\n    Real maxMag() const { Real m = min(), M = max(); return (std::abs(m) > M) ? m : M; }\n\n    // Component wise abs.\n    ScalarField cwiseAbs() const { auto r = ScalarField(*this); r.m_values = r.m_values.cwiseAbs(); return r; }\n\n    // operator() should return numbers rather than column vectors...\n    ConstValueType operator()(size_t i) const {\n        assert(i < (size_t) m_values.cols());\n        return ConstValueType(m_values(0, i));\n    }\n    ValueType operator()(size_t i) {\n        assert(i < (size_t) m_values.cols());\n        return ValueType(m_values(0, i));\n    }\n\n    const Real *data() const { return m_values.data(); }\n          Real *data()       { return m_values.data(); }\n    template<size_t dim>\n    VectorField<Real, dim> unflatten() const {\n        return VectorField<Real, dim>(m_values);\n    }\n\n    const typename VectorField<Real, 1>::ArrayType &values() const { return m_values; }\n\n    void minRelax(const ScalarField<Real> &b) { m_values = m_values.cwiseMin(b.m_values); }\n    void maxRelax(const ScalarField<Real> &b) { m_values = m_values.cwiseMax(b.m_values); }\n    void minRelax(Real b) { m_values = m_values.cwiseMin(b); }\n    void maxRelax(Real b) { m_values = m_values.cwiseMax(b); }\n\nprivate:\n    using VectorField<Real, 1>::m_values;\n};\n\n// Handles both VectorField and ScalarField output.\ntemplate<typename Real, size_t N>\nstd::ostream &operator<<(std::ostream &os, const VectorField<Real, N> &vf) {\n    for (size_t i = 0; i < vf.domainSize(); ++i) {\n        for (size_t c = 0; c < N; ++c) {\n            os << (c ? \"\\t\" : \"\") << vf(i)[c];\n        }\n        os << std::endl;\n    }\n\n    return os;\n}\n\n// Symmetric matrix NxN fields need only store the upper triangle of the NxN\n// matrix. This triangle is flattened into a 1D vector following Voigt notation.\n//  [ 0 2 ]   [ 0 5 4 ]  ...  [ 0  N*(N+1)/2 -1  ]\n//  [   1 ]   [   1 3 ]       [    1             ]\n//            [     2 ]       [        2     ... ]\n//                            [         ..   N+1 ]\n//                            [           .. N   ]\n//                            [              N-1 ]\n// This is the typical stress/strain flattening that\n// collects the diagonal xx, yy, ... entries at the beginning\n// The total number of entries is sum_{i=1}^N i = (N * (N + 1)) / 2\n// (because there are i entries in the ith column).\ntemplate<typename Real, size_t t_N>\nclass SymmetricMatrixField : public VectorSpace<Real, SymmetricMatrixField<Real, t_N>> {\npublic:\n    typedef Eigen::Matrix<Real, Eigen::Dynamic, 1> FlattenedType;\n    typedef Eigen::Matrix<Real, flatLen(t_N), Eigen::Dynamic> ArrayType;\n\n    typedef SymmetricMatrixRef<t_N, typename ArrayType::ColXpr,\n            const typename ArrayType::ColXpr> ValueType;\n    typedef ConstSymmetricMatrixRef<t_N,\n            typename ArrayType::ConstColXpr> ConstValueType;\n\n    SymmetricMatrixField(const SymmetricMatrixField &b) : m_values(b.m_values) { }\n\n    SymmetricMatrixField(size_t domainSize, const FlattenedType &values) {\n        assert(dim() * domainSize == values.rows());\n        m_values = Eigen::Map<const ArrayType>(values.data(), dim(),\n                                               domainSize);\n    }\n\n    // Eigen ArrayType constructor\n    SymmetricMatrixField(const ArrayType values) : m_values(values) { }\n\n    SymmetricMatrixField(size_t domainSize = 0)\n        : m_values(dim(), domainSize) { }\n\n    constexpr size_t dim() const { return flatLen(t_N); }\n    size_t N()   const { return t_N; }\n    size_t domainSize() const { return m_values.cols(); }\n    FieldType fieldType() const { return FIELD_MATRIX; }\n\n    void clear() { m_values = ArrayType::Zero(dim(), domainSize()); }\n    void resizeDomain(size_t dSize) {\n        m_values.resize(Eigen::NoChange, dSize);\n        clear();\n    }\n\n    ConstValueType operator()(size_t i) const {\n        return ConstValueType(m_values.col(i));\n    }\n\n    ValueType operator()(size_t i) {\n        return ValueType(m_values.col(i));\n    }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // VectorSpace requirements\n    ////////////////////////////////////////////////////////////////////////////\n    void Add(const SymmetricMatrixField &b) { m_values += b.m_values; }\n    void Scale(Real scalar)                 { m_values *= scalar; }\n\n    ////////////////////////////////////////////////////////////////////////////\n    // Non-VectorSpace operations.\n    ////////////////////////////////////////////////////////////////////////////\n    // MHS on Nov 3 3015\n    SymmetricMatrixField &operator/=(const ScalarField<Real> &scalars) {\n        assert(scalars.domainSize() == size_t(m_values.cols()));\n        for (size_t i = 0; i < scalars.domainSize(); ++i)\n            m_values.col(i) /= scalars(i);\n        return *this;\n    }\n\n    // Component wise abs.\n    SymmetricMatrixField cwiseAbs() const { return SymmetricMatrixField(m_values.cwiseAbs()); }\n    // Set all coefficients to a constant\n    void setConstant(Real val) { m_values.setConstant(val); }\n\n    SymmetricMatrixField &operator=(const SymmetricMatrixField &b) {\n        if (this == &b) return *this;\n        m_values = b.m_values;\n        return *this;\n    }\n\n    const ArrayType &data() const { return m_values; }\n          ArrayType &data()       { return m_values; }\n\n    void dump(const std::string &path) const {\n        std::ofstream of(path);\n        if (!of.is_open())\n            throw std::runtime_error(std::string(\"Couldn't open '\") +\n                        path + \"' for writing.\");\n        of << std::scientific << std::setprecision(16);\n        for (size_t i = 0; i < domainSize(); ++i) {\n            ConstValueType v = (*this)(i);\n            of << v[0];\n            for (size_t j = 1; j < dim(); ++j) {\n                of << '\\t' << v[j];\n            }\n            of << std::endl;\n        }\n    }\n\n    void load(const std::string &path) {\n        std::ifstream is(path);\n        if (!is.is_open())\n            throw std::runtime_error(std::string(\"Couldn't open '\") + path);\n\n        std::string line;\n        std::vector<Real> data;\n        while (std::getline(is >> std::ws, line)) {\n            std::vector<Real> v;\n            std::istringstream iss(line);\n            Real c;\n            size_t i = 0;\n            while (iss >> c) { data.push_back(c); ++i; }\n            if (i != dim()) throw std::runtime_error(\"Read wrong number of components.\");\n        }\n        assert(data.size() % dim() == 0);\n        int domSize = data.size() / dim();\n        m_values = Eigen::Map<const ArrayType>(&data[0], dim(), domSize);\n    }\n\nprivate:\n    /** Data storage */\n    ArrayType m_values;\n};\n\ntemplate<typename Real, size_t N>\nstd::ostream &operator<<(std::ostream &os, const SymmetricMatrixField<Real, N> &smf)\n{\n    for (size_t i = 0; i < smf.domainSize(); ++i) {\n        for (size_t c = 0; c < smf.dim(); ++c) {\n            os << (c ? \"\\t\" : \"\") << smf(i)[c];\n        }\n        os << std::endl;\n    }\n    return os;\n}\n\n// Simple field class that can change dimension but is less efficient/statically\n// checked.\n// Stores in flattened x0 y0 x1 y1 ... format\ntemplate<typename _Real>\nclass DynamicField {\npublic:\n    DynamicField(size_t dimensions, size_t domSize) {\n        resize(dimensions, domSize);\n    }\n\n    DynamicField(const DynamicField &b) {\n        m_dim = b.m_dim;\n        m_storage = b.m_storage;\n    }\n\n    template<size_t _N>\n    DynamicField(const VectorField<_Real, _N> &vf) {\n        resize(vf.dim(), vf.domainSize());\n        for (size_t i = 0; i < vf.dim(); ++i)\n            for (size_t j = 0; j < vf.domainSize(); ++j)\n                (*this)(i, j) = vf(j)[i];\n    }\n\n    void resize(size_t domSize) { m_storage.resize(domSize * m_dim); }\n    void resize(size_t dim, size_t domSize) { m_dim = dim; resize(domSize); }\n\n    size_t domainSize() const {\n        assert(m_storage.size() % m_dim == 0);\n        return m_storage.size() / m_dim;\n    }\n\n    size_t dim() const { return m_dim; }\n\n    // Flattened access\n          _Real &operator[](size_t i)       { return m_storage.at(i); }\n    const _Real &operator[](size_t i) const { return m_storage.at(i); }\n\n    _Real &operator()(size_t i, size_t j) {\n        if (i >= dim() || j >= domainSize()) throw std::runtime_error(\"out of bounds access\");\n        return m_storage.at(j * dim() + i);\n    }\n\n    _Real  operator()(size_t i, size_t j) const {\n        if (i >= dim() || j >= domainSize()) throw std::runtime_error(\"out of bounds access\");\n        return m_storage.at(j * dim() + i);\n    }\n\n    // Casts to Field types.\n    operator ScalarField<_Real>() const {\n        if (m_dim != 1) throw std::runtime_error(\"Illegal cast of vector field to scalar field.\");\n        return ScalarField<_Real>(m_storage);\n    }\n    template<size_t _dim>\n    operator VectorField<_Real, _dim>() const {\n        if (m_dim != _dim) throw std::runtime_error(\"Vector field cast dimension mismatch.\");\n        return VectorField<_Real, _dim>(m_storage);\n    }\n    template<size_t _dim>\n    operator SymmetricMatrixField<_Real, _dim>() const {\n        if (m_dim != _dim) throw std::runtime_error(\"Vector field cast dimension mismatch.\");\n        return SymmetricMatrixField<_Real, _dim>(m_storage);\n    }\n\n    friend std::ostream &operator<<(std::ostream &os, const DynamicField &f) {\n        for (size_t j = 0; j < f.domainSize(); ++j) {\n            for (size_t i = 0; i < f.dim(); ++i)\n                os << (i ? \"\\t\" : \"\") << f(i, j);\n            os << std::endl;\n        }\n        return os;\n    }\n\nprivate:\n    size_t m_dim;\n    std::vector<_Real> m_storage;\n};\n\n#endif // FIELDS_HH\n", "meta": {"hexsha": "333f351ab2f150c46439120c851da717f47de0d8", "size": 19329, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/lib/MeshFEM/Fields.hh", "max_stars_repo_name": "pbedenbaugh/MeshFEM", "max_stars_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "src/lib/MeshFEM/Fields.hh", "max_issues_repo_name": "pbedenbaugh/MeshFEM", "max_issues_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "src/lib/MeshFEM/Fields.hh", "max_forks_repo_name": "pbedenbaugh/MeshFEM", "max_forks_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 36.9579349904, "max_line_length": 115, "alphanum_fraction": 0.5657302499, "num_tokens": 4849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.42549638180041555}}
{"text": "#include <assert.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <NTL/GF2X.h>\n#include <NTL/GF2XFactoring.h>\n#include <NTL/GF2E.h>\n#include <NTL/GF2EX.h>\n#include <NTL/GF2EXFactoring.h>\n\n#include \"gcm.h\"\n\nusing namespace std;\nusing namespace NTL;\n\nint main(int argc, char **argv)\n{\n    struct slice a1, c1, t1, a2, c2, t2;\n    struct slice *sp[] = {&a1, &c1, &t1, &a2, &c2, &t2};\n    int i;\n    GF2EX p, p1, p2;\n    vec_pair_GF2EX_long factors;\n    char out[33];\n\n    argc -= 1;\n    argv += 1;\n\n    assert(argc == 6);\n\n    for (i = 0; i < argc; i += 1) {\n        hex2bytes(sp[i], argv[i]);\n    }\n\n    initfield();\n    buildpoly(p1, &a1, &c1, &t1);\n    buildpoly(p2, &a2, &c2, &t2);\n    p = p1 + p2;\n    MakeMonic(p);\n    CanZass(factors, p);\n\n    for (i = 0; i < factors.length(); i += 1) {\n        if (deg(factors[i].a) == 1) {\n            felem2hex(out, factors[i].a[0]);\n            printf(\"%s\\n\", out);\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "0ecc8a9ddae6f74a9a356edf77ba43d2c870abcb", "size": 984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool/recover.cpp", "max_stars_repo_name": "nonce-disrespect/nonce-disrespect", "max_stars_repo_head_hexsha": "425524519779c27dd74c2b51d436f5d3de8d364d", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 119.0, "max_stars_repo_stars_event_min_datetime": "2016-05-19T15:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T23:01:02.000Z", "max_issues_repo_path": "tool/recover.cpp", "max_issues_repo_name": "nonce-disrespect/nonce-disrespect", "max_issues_repo_head_hexsha": "425524519779c27dd74c2b51d436f5d3de8d364d", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tool/recover.cpp", "max_forks_repo_name": "nonce-disrespect/nonce-disrespect", "max_forks_repo_head_hexsha": "425524519779c27dd74c2b51d436f5d3de8d364d", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2016-05-20T09:26:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-30T08:49:31.000Z", "avg_line_length": 18.9230769231, "max_line_length": 56, "alphanum_fraction": 0.5355691057, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.42547129514147647}}
{"text": "\n#include <iostream>\n#include <vector>\n#include <math.h>\n\n#include <boost/timer.hpp>\n\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\n\n#include \"TwoChQS.hpp\"\n\n\n\nvoid TwoChQS_DiagHN(vector<double> Params,\n\t\t     CNRGbasisarray* pAbasis,CNRGbasisarray* pSingleSite,\n\t\t     CNRGmatrix* Qm1fNQ, CNRGarray* pAeig){\n\n\n  CNRGmatrix HN(*pAbasis);\n  double OldEl[2];\n\n  double chi_N[2]={Params[0],Params[1]};\n  double Lambda=Params[2];\n  double auxEl;\n\n  // Check time\n  boost::timer t;\n\n  // New approach\n  HN.UpperTriangular=true;\n\n  int icount=0;\n  for (int ibl=0;ibl<pAbasis->NumBlocks();ibl++)\n    {\n      // HN is block diagonal (ibl,ibl) so we are setting the blocks\n      HN.MatBlockMap.push_back(ibl);\n      HN.MatBlockMap.push_back(ibl);\n\n      // Each MatBlock is Nbl x Nbl in lenght\n      HN.MatBlockBegEnd.push_back(icount);\n      //icount+=pAbasis->GetBlockSize(ibl)*pAbasis->GetBlockSize(ibl);\n      // New\n      int sizebl=pAbasis->GetBlockSize(ibl);\n      if (HN.UpperTriangular)\n \ticount+=(sizebl*(sizebl+1))/2;\n      else\n\ticount+=sizebl*sizebl;\n\n      HN.MatBlockBegEnd.push_back(icount-1);\n\n      cout << \"  Setting up H_(N = \" << pAbasis->Nshell << \") Block : \" << ibl ;\n      cout << \" of \" << pAbasis->NumBlocks();\n      cout << \"  size: \" << pAbasis->GetBlockSize(ibl) << endl;\n      t.restart();\n\n      double Q1i=pAbasis->GetQNumber(ibl,0);\n      double Si=pAbasis->GetQNumber(ibl,1);\n\n\n      // Calculate matrix elements\n      for (int ist=pAbasis->GetBlockLimit(ibl,0);\n\t   ist<=pAbasis->GetBlockLimit(ibl,1);ist++)\n\t{\n\t  int type_i=pAbasis->iType[ist];\n\n\n// \t  for (int jst=pAbasis->GetBlockLimit(ibl,0);\n//  \t       jst<=pAbasis->GetBlockLimit(ibl,1);jst++)\n//       NEW: calculate only half of the matrix elements\n//\n\t  int j0;\n\t  // NEW THING! only calculates half of matrix els!\n\t  if (HN.UpperTriangular) j0=ist; \n\t  else j0=pAbasis->GetBlockLimit(ibl,0);\n\t  for (int jst=j0;\n\t           jst<=pAbasis->GetBlockLimit(ibl,1);jst++)\n\t    {\n\t      int type_j=pAbasis->iType[jst];\n\n\t      if (ist==jst)   // Diagonal terms\n\t\t{\n\t\t  auxEl=sqrt(Lambda)*(pAbasis->dEn[ist]);\n\t\t  HN.MatEl.push_back(auxEl);\n\t\t}\n\t      else \t\t  //Off-diagonal terms\n\t\t{\n\t\t  // Loop in channels\n\t\t  auxEl=0.0;\n\t\t  for (int ich=1;ich<=2;ich++)\n\t\t    {\n\t\t      OldEl[ich-1]=Qm1fNQ[ich-1].GetMatEl(pAbasis->StCameFrom[ist],pAbasis->StCameFrom[jst]);\n\t\t      int typep=type_i;\n\t\t      int type=type_j;\n\n\t\t      // if zero, try the h.c term\n\t\t      if (dEqual(fabs(OldEl[ich-1]),0.0))\n\t\t\t{\n\t\t\t  OldEl[ich-1]=Qm1fNQ[ich-1].GetMatEl(pAbasis->StCameFrom[jst],\n\t\t\t\t\t\t       pAbasis->StCameFrom[ist]);\n\t\t\t  typep=type_j;\n\t\t\t  type=type_i;\n\t\t\t}\n\n\t\t      // Will this work?\n\t\t      // if still zero, next.\n\t\t      //if (dEqual(fabs(OldEl[ich-1]),0.0)) break;\n\t\t      \n\n\t\t      // Get SingleSite QNumbers\n\t\t      int pos=0;\n\t\t      int iblssp=pSingleSite->GetBlockFromSt(typep,pos);\n\t\t      int iblss=pSingleSite->GetBlockFromSt(type,pos);\n\n\t\t      double Qtildep=pSingleSite->GetQNumber(iblssp,0);\n\t\t      double Stildep=pSingleSite->GetQNumber(iblssp,1);\n\t\t      double Sztildep=pSingleSite->GetQNumber(iblssp,2);\n\n\n\t\t      double Qtilde=pSingleSite->GetQNumber(iblss,0);\n\t\t      double Stilde=pSingleSite->GetQNumber(iblss,1);\n\t\t      double Sztilde=pSingleSite->GetQNumber(iblss,2);\n\n\t\t      double Soldp=Si-Sztildep;\n\t\t      double Sold=Si-Sztilde;\n\n\n\t\t      // Check Fermi Sign\n\t\t      double FermiSign=1.0;\n\t\t      // will be -1 if only one of them is zero (A XOR B)\n\t\t      // Check this one. \n\t\t      // Fermi sign now depends on which type the thing is!!!\n                      // In other words, it will be -1 if the state has only one \n\t\t      // electron in only one of the channels\n\t\t      // Single site states +-1,+-1/2!!\n                      // \n\t\t      if ( (dEqual(Sztilde,0.5)||dEqual(Sztilde,-0.5)) ) FermiSign=-1.0;\n\n\t\t      double siteqnumsp[]={Qtildep,Stildep,Sztildep};\n\t\t      double siteqnums[]={Qtilde,Stilde,Sztilde};\n\n\t\t      //Loop in spins\n\t\t      for (int sigma=-1;sigma<=1;sigma+=2)\n\t\t\t{\n\t\t\t  double dSigma=0.5*(double)sigma;\n\t\t\t  double FullMatEl=0.0;\n\t\t\t  double auxCG[]={0.0,0.0,0.0,0.0};\n\n\t\t\t  // Loop in Szold\n\t\t\t  for (double Szold=Sold;Szold>=-Sold;Szold-=1.0)\n\t\t\t    {\n\t\t\t      double Szoldp=Szold-dSigma;\n\t\t\t      Sztilde=Si-Szold;\n\t\t\t      Sztildep=Sztilde+dSigma;\n\t\t\t      // Changing dSigma changes Sztildep\n\t\t\t      // Need an extra loop in the \"p\" block\n\n\t\t\t      // Site matrix element: finds the block\n\t\t\t      siteqnums[2]=Sztilde;\n\t\t\t      siteqnumsp[2]=Sztildep;\n\t\t\t      int siteblock=pSingleSite->GetBlockFromQNumbers(siteqnums);\n\t\t\t      int siteblockp=pSingleSite->GetBlockFromQNumbers(siteqnumsp);\n\t\t\t      \n// \t\t\t      if ((ist==302)&&( (jst==304)||(jst==305) ))\n// \t\t\t\tcout << \" ist = \" << ist\n// \t\t\t\t     << \" jst = \" << jst\n// \t\t\t\t     << \" ich = \" << ich\n// \t\t\t\t     << \" sigma = \" << sigma\n// \t\t\t\t     << \" Szold = \" << Szold\n// \t\t\t\t     << \" Sztildep = \" << Sztildep\n// \t\t\t\t     << \" Sztilde = \" << Sztilde\n// \t\t\t\t     << endl;\n\n\n\n\t\t\t      if ( (dLEqual(fabs(Sztildep),Stildep))&&\n\t\t\t\t   (dLEqual(fabs(Szold),Sold))&&\n\t\t\t\t   (dLEqual(fabs(Szoldp),Soldp)) )\n\t\t\t\t{\n\t\t\t\t  // CG coefs\n\t\t\t\t  auxCG[0]=CGordan(Sold,Szold,\n\t\t\t\t\t\t   Stilde,Sztilde,\n\t\t\t\t\t\t   Si,Si);\t\t\t\t \n\n\t\t\t\t  auxCG[1]=CGordan(Soldp,Szoldp,\n\t\t\t\t\t\t   Stildep,Sztildep,\n\t\t\t\t\t\t   Si,Si);\n\n\t\t\t\t  auxCG[2]=CGordan(Soldp,Szoldp,\n\t\t\t\t\t\t   0.5,dSigma,\n\t\t\t\t\t\t   Sold,Szold);\n\t\t\t\t  \n\t\t\t\t  //Loop in site blocks!! Necessary!\n\t\t\t\t  for (int sitestatep=pSingleSite->GetBlockLimit(siteblockp,0);sitestatep<=pSingleSite->GetBlockLimit(siteblockp,1);sitestatep++)\n\t\t\t\t    {\n\t\t\t\t      for (int sitestate=pSingleSite->GetBlockLimit(siteblock,0);sitestate<=pSingleSite->GetBlockLimit(siteblock,1);sitestate++)\n\t\t\t\t\t{\n\t\t\t\t\t  double SpSm[2]={0.0,0.0};\n\t\t\t\t\t  SpSm[0]=TwoChQS_SpSm_table(sitestate,type);\n\t\t\t\t\t  SpSm[1]=TwoChQS_SpSm_table(sitestatep,typep);\n\t\t\t\t\t  auxCG[3]=TwoChQS_fd_table(ich,sigma,\n\t\t\t\t\t\t\t\t    sitestatep,sitestate);\n//  \t\t\t\t\t  if ((ist==302)&&( (jst==304)||(jst==305) ))\n// \t\t\t\t\t    cout << \" ist = \" << ist\n// \t\t\t\t\t\t << \" jst = \" << jst\n// \t\t\t\t\t\t << \" ich = \" << ich\n// \t\t\t\t\t\t << \" sigma = \" << sigma\n// \t\t\t\t\t\t << \" fd_table(\" \n// \t\t\t\t\t\t << sitestatep << \",\" \n// \t\t\t\t\t\t << sitestate << \") = \" \n// \t\t\t\t\t\t << auxCG[3] << endl\n// \t\t\t\t\t\t << \" SpSm1(\" \n// \t\t\t\t\t\t << sitestate << \",\" << type \n// \t\t\t\t\t\t << \") = \" << SpSm[0] \n// \t\t\t\t\t\t << endl\n// \t\t\t\t\t\t << \" SpSm2(\" \n// \t\t\t\t\t\t << sitestatep << \",\" << typep \n// \t\t\t\t\t\t << \") = \" << SpSm[1] \n// \t\t\t\t\t\t << endl;\n\t\t\t\t  \n\t\t\t\t\t  FullMatEl+=auxCG[0]*auxCG[1]*auxCG[2]*auxCG[3]*FermiSign*SpSm[0]*SpSm[1];\n\n\t\t\t\t\t}\n\t\t\t\t      // end loop in site block\n\t\t\t\t    }\n\t\t\t\t  // end loop in site blockp\n\t\t\t\t}\n\t\t\t      // END Calc coefs safeguard\n\t\t\t    }\n\t\t\t  // End loop in Szold\n\n\t\t\tauxEl+=chi_N[ich-1]*OldEl[ich-1]*FullMatEl;\n\n// \t\t\tif ((ist==302)&&( (jst==304)||(jst==305) ))\n// \t\t\t  cout << \" ich = \" << ich\n// \t\t\t       << \" OldEl = \" << OldEl[ich-1]\n// \t\t\t       << \" FullMatEl = \" << FullMatEl\n// \t\t\t       << \" auxEl = \" << auxEl\n// \t\t\t       << endl;\n\n\t\t\t}\n\t\t      // end loop in sigma\n\t\t    }\n\t\t  //end loop in channels\n\n\t\t  HN.MatEl.push_back(auxEl);\n\t\t  // NEW: add jst,ist as well\n\t\t  //HN.MatEl.push_back(auxEl);\n\n\t\t}\n\t      // END if ist=jst\n\t    }\n\t  //END loop in jst\n\t}\n      // END loop in ist\n\n      cout << \" ...Done. Set-up Time: \" << t.elapsed() << endl;\n    }\n  // END Loop in blocks (ibl)\n\n\n  cout << \"Updating Aeig \" << endl;\n  pAeig->ClearAll();\n\n  // Syncronize with HN\n  *pAeig=HN;\n\n  // Set dEn,dEigVec\n  pAeig->dEn.clear();\n  pAeig->dEigVec.clear();\n\n  for (int ibl=0;ibl<HN.NumBlocks();ibl++){\n      //// NEW\n    //       cout << \" Regularizing block \" << ibl << \" of \" << HN.NumBlocks()-1 << endl;\n    //       HN.PutInRegularForm(ibl);\n    //pAbasis->PrintBlockBasis(ibl);\n    //HN.PrintMatBlock(ibl,ibl);\n    cout << \" Diagonalizing block \" << ibl << \" of \" << HN.NumBlocks()-1 << endl;\n    HN.DiagBlock(ibl,pAeig->dEn,pAeig->dEigVec);\n    //pAeig->PrintBlockEn(ibl);\n  }\n\n \n  //uset this later\n  pAeig->SetE0zero();\n\n\n\n}\n// end subroutine\n////////////////////////\n////////////////////////\n////////////////////////\n\n// Scrap code\n\t\t\t  // Sum in Sztilde\n// \t\t\t  for (Sztilde=-Stilde;Sztilde<=Stilde;Sztilde+=1.0)\n// \t\t\t    {\n// \t\t\t      double Sztildep=Sztilde+dSigma;\n// \t\t\t      double Szold=Si-Sztilde;\n// \t\t\t      double Szoldp=Si-Sztildep;\n\n// \t\t\t      // CG coefs\n// \t\t\t      auxCG[0]=CGordan(Sold,Szold,\n// \t\t\t\t\t       Stilde,Sztilde,Si,Si);\n// \t\t\t      auxCG[1]=CGordan(Soldp,Szoldp,\n// \t\t\t\t\t       Stildep,Sztildep,Si,Si);\n// \t\t\t      auxCG[2]=CGordan(Soldp,Szoldp,\n// \t\t\t\t\t       0.5,dSigma,Sold,Szold);\n// \t\t\t      // Site matrix element\n// \t\t\t      siteqnums[2]=Sztilde;\n// \t\t\t      siteqnumsp[2]=Sztildep;\n// \t\t\t      int sitestate=pSingleSite->GetBlockFromQNumbers(siteqnums);\n// \t\t\t      int sitestatep=pSingleSite->GetBlockFromQNumbers(siteqnumsp);\n// \t\t\t      auxCG[3]=TwoChQS_fd_table(ich,sigma,\n// \t\t\t\t\t\t\tsitestatep,sitestate);\n\n// \t\t\t      FullMatEl+=auxCG[0]*auxCG[1]*auxCG[2]*OldEl[ich-1]*auxCG[3]*FermiSign;\n\t\t\t      \n// \t\t\t    }\n// \t\t\t  // END Loop in Sztilde\n", "meta": {"hexsha": "5000a691aeae128e577913c3e1efd77b6ad85f19", "size": 9059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/TwoChQS/TwoChQS_DiagHN.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/TwoChQS/TwoChQS_DiagHN.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TwoChQS/TwoChQS_DiagHN.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1335403727, "max_line_length": 133, "alphanum_fraction": 0.5460867645, "num_tokens": 3032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673133042217, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.4254712927686279}}
{"text": "\n/*!\n * @file \n * @brief \n * @copyright alphya 2020-2021\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef NYARUGA_UTIL_CARTESIAN_PRODUCT_HPP\n#define NYARUGA_UTIL_CARTESIAN_PRODUCT_HPP\n\n#pragma once\n\n// this code almost from\n// https://stackoverflow.com/questions/16686942/how-to-iterate-over-two-stl-like-containers-cartesian-product\n\n// ネストした for 文が書きやすくなります\n// 速度はブレ幅が大きいですが、for 文をネストした場合より 2 倍以上遅くなることはないと思います\n// パソコンの調子によって、1.5 倍くらいだったり、同じくらいだったりしました\n\n// 例\n\n/*\n    array b = { false, true };\n    array i = { 0, 1 };\n    array s = { \"Hello\", \"World\" };\n\n    // i, j, k は、それぞれの添え字に関してネストした for 文と\n    // 同じような添え字を走る(直積)\n    // 引数はイテレータが使える型や組み込みの配列なら OK\n    // (使用する操作：std::end(), std::begin(), it++) \n    for (auto&& [i,j,k]: cartesian_product(b,i,s)) \n    {\n        std::cout << std::boolalpha << i << \", \";\n        std::cout << j << \", \";\n        std::cout << k << \"\\n\";\n    } \n\n    //   for (int i = 0; i != 2; ++i)\n    //   for (int j = 1; j != 3; ++j) \n    //   for (int k = 2; k != 4; ++k) \n   for (auto&& [i,j,k]: cartesian_product({0,2},{1,3},{2,4})) \n    {\n        std::cout << i << \", \";\n        std::cout << j << \", \";\n        std::cout << k << \"\\n\";\n    }\n\n*/\n\n#include <tuple>                        // make_tuple, tuple\n#include <utility>                      // pair\n#include <vector>                       // vector\n#include <boost/coroutine2/coroutine.hpp>\n\nnamespace nyaruga {\n\nnamespace util {\n\n/*\n\nnamespace impl1 { // コルーチン実装\n\nnamespace detail {\n\n// the lambda is fully bound with one element from each of the ranges\ntemplate<class Op>\nvoid insert_tuples(Op&& op) noexcept\n{\n    // evaluating the lambda will insert the currently bound tuple\n    op();\n}\n\n// \"peal off\" the first range from the remaining tuple of ranges\ntemplate<class Op, class InputIterator1, class... InputIterator2>\nvoid insert_tuples(Op&& op, std::pair<InputIterator1, InputIterator1> head, std::pair<InputIterator2, InputIterator2>... tail)\n{\n    // \"peal off\" the elements from the first of the remaining ranges\n    // NOTE: the recursion will effectively generate the multiple nested for-loops\n    for (auto it = head.first; it != head.second; ++it) {\n        // bind the first free variable in the lambda, and\n        // keep one free variable for each of the remaining ranges\n        detail::insert_tuples(\n            [&op,&it](InputIterator2... elems) { op(it, elems...); },\n            tail...\n        );\n    }\n}\n\n}   // namespace detail\n\n// convert a tuple of ranges to the range of tuples representing the Cartesian product\ntemplate<class... InputIterator>\nvoid cartesian_product_impl(auto & sink, std::pair<InputIterator, InputIterator>&&... dimensions)\n{\n    detail::insert_tuples(\n         [&sink](InputIterator... elems) { sink(std::make_tuple(*elems...)); },\n         std::forward<decltype(dimensions)>(dimensions)...\n    );\n}\n    \ntemplate<class...Args>\ndecltype(auto) cartesian_product(Args&&... args)\n{\n    using coro_type = boost::coroutines2::coroutine<\n        typename std::tuple<std::remove_reference_t<decltype(*std::begin(std::declval<Args&>()))>...> \n    >;\n    \n    return typename coro_type::pull_type(\n    [...args=std::forward<Args>(args)](typename coro_type::push_type & sink)\n    {\n        cartesian_product_impl(sink, std::make_pair(std::begin(args), std::end(args))...);   \n    });\n};\n} //namespace impl1\n\n*/\n\n// from: https://stackoverflow.com/questions/16686942/how-to-iterate-over-two-stl-like-containers-cartesian-product\nnamespace impl2 { // ほぼ stack overflow から \n\nnamespace detail {\n\n// the lambda is fully bound with one element from each of the ranges\ntemplate<class Op>\nvoid insert_tuples(Op&& op)\n{\n        // evaluating the lambda will insert the currently bound tuple\n        op();\n}\n\n// \"peal off\" the first range from the remaining tuple of ranges\ntemplate<class Op, class InputIterator1, class... InputIterator2>\nvoid insert_tuples(Op&& op, std::pair<InputIterator1, InputIterator1> head, std::pair<InputIterator2, InputIterator2>... tail)\n{\n        // \"peal off\" the elements from the first of the remaining ranges\n        // NOTE: the recursion will effectively generate the multiple nested for-loops\n        for (auto it = head.first; it != head.second; ++it) {\n                // bind the first free variable in the lambda, and\n                // keep one free variable for each of the remaining ranges\n                detail::insert_tuples(\n                        [&op,&it](InputIterator2... elems) mutable { op(it, elems...); },\n                        tail...\n                );\n        }\n}\n\n// convert a tuple of ranges to the range of tuples representing the Cartesian product\ntemplate<class OutputIterator, class... InputIterator>\nvoid cartesian_product_impl(OutputIterator result, std::pair<InputIterator, InputIterator>... dimensions)\n{\n        insert_tuples(\n                 [=](InputIterator... elems) mutable { *result++ = std::make_tuple(*elems...); },\n                 dimensions...\n        );\n}\n\n}       // namespace detail\n\n\n\ntemplate <typename...Args>\nauto cartesian_product(Args&&...args)\n{\n    std::vector< typename std::tuple<std::remove_reference_t<decltype(*std::begin(std::declval<Args&>()))>...>  > result;\n    detail::cartesian_product_impl(\n            std::back_inserter(result),\n            std::make_pair(std::begin(args), std::end(args))...\n    );\n    return result;\n}\n\n} // namespace impl2 (almost original)\n\nusing namespace impl2; // impl1 より倍速い場合があった 速度はパソコンの調子によって大きく左右される\n\n} // namespace nyaruga::util\n\n/* how to use\n\n#include <string>\n#include <iostream>\n#include <array>\n#include <stdio.h>\n#include <chrono>\n\nusing std::array;\n\nint main() \n{\n    array b = { false, true };\n    array i = { 0, 1 };\n    array s = { \"Hello\", \"World\" };\n    \n    \n    using namespace std;\n    chrono::system_clock::time_point start, end;\n\n    start = chrono::system_clock::now();\n\n    for (int f = 0; f < 1000; ++f)\n    // now use a single flat loop over result to do your own thing\n    for (auto&& [i,j,k]: cartesian_product(b,i,s)) {\n        std::cout << std::boolalpha << i << \", \";\n        std::cout << j << \", \";\n        std::cout << k << \"\\n\";\n    }\n    \n        // 何かの処理\n\n    end = chrono::system_clock::now();\n\n    double time = static_cast<double>(chrono::duration_cast<chrono::microseconds>(end - start).count() / 1000.0);\n    printf(\"time %lf[ms]\\n\", time);\n    \n}   \n\n*/\n\n#include <initializer_list>\n\nnamespace nyaruga::util {\n\nnamespace detail_index {\n\ntemplate<class Op>\nvoid insert_tuples(Op&& op)\n{\n        op();\n}\n\nvoid insert_tuples(auto&& op,auto head, auto... tail)\n{\n    for (auto i = *head.begin(); i < *(head.begin()+1); ++i) {\n        insert_tuples(\n            [&op,&i](typename decltype(tail)::value_type... elems) mutable { op(i, elems...); },\n            tail...\n        );\n    }\n}\n\nvoid cartesian_product_impl(auto&& result, auto&&... dimensions)\n{\n    insert_tuples(\n         [=](auto... elems) mutable { *result++ = std::make_tuple(elems...); },\n         std::forward<decltype(dimensions)>(dimensions)...\n    );\n}\n\n}       // namespace detail\n\ntemplate<typename... T>\nauto cartesian_product(std::initializer_list<T>...args)\n{\n    std::vector<typename std::tuple<T...>> result;\n    detail_index::cartesian_product_impl(std::back_inserter(result), args...);\n    return result;\n}\n\n}\n\n/* how to use\n#include <string>\n#include <iostream>\n#include <array>\n#include <stdio.h>\n#include <chrono>\n\nusing std::array;\n\nint main() \n{\n    \n    using namespace std;\n    chrono::system_clock::time_point start, end;\n\n    start = chrono::system_clock::now();\n\n    for (int f = 0; f < 1000; ++f)\n    \n   for (auto&& [i,j,k]: cartesian_product({0,2},{1,3},{2,4})) \n//   equal to\n//   for (int i = 0; i != 2; ++i)\n//   for (int j = 1; j != 3; ++j) \n//   for (int k = 2; k != 4; ++k) \n    {\n        std::cout << i << \", \";\n        std::cout << j << \", \";\n        std::cout << k << \"\\n\";\n    }\n    \n    end = chrono::system_clock::now();\n\n    double time = static_cast<double>(chrono::duration_cast<chrono::microseconds>(end - start).count() / 1000.0);\n    printf(\"time %lf[ms]\\n\", time);\n\n}  \n*/\n\n#endif // NYARUGA_UTPL_CARTESIAN_PRODUCT_HPP", "meta": {"hexsha": "473d5f60ebeef62053f1a27720e6229ce40e3f11", "size": 8224, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nyaruga_util/cartesian_product.hpp", "max_stars_repo_name": "alphya/nyaruga_util", "max_stars_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nyaruga_util/cartesian_product.hpp", "max_issues_repo_name": "alphya/nyaruga_util", "max_issues_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nyaruga_util/cartesian_product.hpp", "max_forks_repo_name": "alphya/nyaruga_util", "max_forks_repo_head_hexsha": "a75d388b2fe80100760f9b5fc7e959e4846b590f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3222591362, "max_line_length": 126, "alphanum_fraction": 0.6090710117, "num_tokens": 2293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241911813151, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.42525022182059213}}
{"text": "\n#pragma once\n\n#include <Eigen/Dense>\n\n#include \"perceive/foundation.hpp\"\n#include \"perceive/utils/sdbm-hash.hpp\"\n#include \"vector-2.hpp\"\n#include \"vector-3.hpp\"\n\nnamespace perceive\n{\n// An \"axis-aligned\" bounding box\n#pragma pack(push, 1)\ntemplate<typename T> class AABBT\n{\n public:\n   CUSTOM_NEW_DELETE(AABBT)\n\n   using value_type = T;\n\n   T left{T(0.0)}, top{T(0.0)}, right{T(0.0)}, bottom{T(0.0)};\n\n   AABBT() noexcept             = default;\n   AABBT(const AABBT&) noexcept = default;\n   AABBT(AABBT&&) noexcept      = default;\n   ~AABBT()                     = default;\n   AABBT& operator=(const AABBT&) noexcept = default;\n   AABBT& operator=(AABBT&&) noexcept = default;\n\n   AABBT(T in_left, T in_top, T in_right, T in_bottom)\n   noexcept\n       : left(in_left)\n       , top(in_top)\n       , right(in_right)\n       , bottom(in_bottom)\n   {}\n   AABBT(Vector2T<T> lefttop, Vector2T<T> rightbottom)\n   noexcept\n       : left(lefttop.x)\n       , top(lefttop.y)\n       , right(rightbottom.x)\n       , bottom(rightbottom.y)\n   {}\n\n   template<class Iterator> AABBT(Iterator first, Iterator last) noexcept\n   {\n      *this = minmax();\n      union_with(first, last);\n   }\n\n   static AABBT nan() noexcept { return AABBT(T(NAN), T(NAN), T(NAN), T(NAN)); }\n   static AABBT minmax() noexcept\n   {\n      auto mmax = std::numeric_limits<T>::max();\n      auto mmin = std::numeric_limits<T>::lowest();\n      return AABBT<T>(mmax, mmax, mmin, mmin);\n   }\n\n   bool is_finite() const noexcept\n   {\n      return true && std::isfinite(left) && std::isfinite(top)\n             && std::isfinite(right) && std::isfinite(bottom);\n   }\n\n   // Union a point with the AABB\n   void union_point(T x, T y) noexcept\n   {\n      if(std::isfinite(x)) {\n         if(x < left) left = x;\n         if(x > right) right = x;\n      }\n      if(std::isfinite(y)) {\n         if(y < top) top = y;\n         if(y > bottom) bottom = y;\n      }\n   }\n\n   void union_point(const Vector2T<T>& p) noexcept { union_point(p.x, p.y); }\n   void union_point(const T p[2]) noexcept { union_point(p[0], p[1]); }\n\n   bool contains(T x, T y) const noexcept\n   {\n      if constexpr(std::is_floating_point<T>::value) {\n         return is_close_between(x, left, right)\n                and is_close_between(y, top, bottom);\n      }\n      return (x >= left) && (x <= right) && (y >= top) && (y <= bottom);\n   }\n   bool contains(const Vector2T<T>& p) const noexcept\n   {\n      return contains(p.x, p.y);\n   }\n   bool contains(const T p[2]) const noexcept { return contains(p[0], p[1]); }\n\n   template<class Iterator>\n   void union_with(Iterator first, Iterator last) noexcept\n   {\n      while(first != last) union_point(*first++);\n   }\n\n   T w() const noexcept\n   {\n      return right - left;\n      if constexpr(std::is_integral_v<T>)\n         return abs(right - left);\n      else\n         return fabs(right - left);\n   }\n   T h() const noexcept\n   {\n      return bottom - top;\n      if constexpr(std::is_integral_v<T>)\n         return abs(bottom - top);\n      else\n         return fabs(bottom - top);\n   }\n   T width() const noexcept { return w(); }\n   T height() const noexcept { return h(); }\n\n   T area() const noexcept { return w() * h(); }\n\n   AABBT& grow(T inc) noexcept\n   {\n      left -= inc;\n      top -= inc;\n      right += inc;\n      bottom += inc;\n      return *this;\n   }\n\n   static AABBT intersection(const AABBT& a, const AABBT& b) noexcept\n   {\n      AABBT<T> c = a;\n\n      c.left   = std::max(a.left, b.left);\n      c.right  = std::min(a.right, b.right);\n      c.top    = std::max(a.top, b.top);\n      c.bottom = std::min(a.bottom, b.bottom);\n\n      if(c.w() < 0) {\n         c.left  = T(0.5 * double(c.left + c.right));\n         c.right = c.left;\n      }\n\n      if(c.h() < 0) {\n         c.top    = T(0.5 * double(c.top + c.bottom));\n         c.bottom = c.top;\n      }\n\n      return c;\n   }\n\n   static T intersection_area(const AABBT& a, const AABBT& b) noexcept\n   {\n      AABBT<T> c = a;\n\n      c.left   = std::max(a.left, b.left);\n      c.right  = std::min(a.right, b.right);\n      c.top    = std::max(a.top, b.top);\n      c.bottom = std::min(a.bottom, b.bottom);\n\n      T w = c.w();\n      T h = c.h();\n\n      return (w > 0.0 && h > 0.0) ? (w * h) : T(0.0);\n   }\n\n   // Raster order in images has a \"flipped\" y-axis\n   AABBT reflect_raster() const noexcept\n   {\n      AABBT o = *this;\n      std::swap(o.top, o.bottom);\n      return o;\n   }\n\n   T intersection_area(const AABBT& o) const noexcept\n   {\n      return intersection_area(*this, o);\n   }\n\n   static T union_area(const AABBT& a, const AABBT& b) noexcept\n   {\n      return a.area() + b.area() - intersection_area(a, b);\n   }\n   T union_area(const AABBT& o) const noexcept { return union_area(*this, o); }\n\n   Vector2T<T> centre() const noexcept\n   {\n      return Vector2T<T>(T(left + 0.5 * (right - left)),\n                         T(top + 0.5 * (bottom - top)));\n   }\n   Vector2T<T> center() const noexcept { return centre(); }\n\n   real aspect_ratio() const noexcept { return real(width()) / real(height()); }\n\n   // Scale the AABB by some size\n   AABBT& operator*=(T scalar) noexcept\n   {\n      Vector2T<T> c = centre();\n      T w           = this->w() * scalar * 0.5;\n      T h           = this->h() * scalar * 0.5;\n      left          = c.x - w;\n      right         = c.x + w;\n      top           = c.y - h;\n      bottom        = c.y + h;\n      return *this;\n   }\n\n   AABBT& operator/=(T scalar) noexcept { return *this *= (1.0 / scalar); }\n   AABBT operator*(T scalar) const noexcept\n   {\n      AABBT res(*this);\n      res *= scalar;\n      return res;\n   }\n   AABBT operator/(T scalar) const noexcept\n   {\n      AABBT res(*this);\n      res /= scalar;\n      return res;\n   }\n\n   Vector2T<T> left_top() const noexcept { return Vector2T<T>(left, top); }\n   Vector2T<T> top_left() const noexcept { return Vector2T<T>(left, top); }\n   Vector2T<T> right_bottom() const noexcept\n   {\n      return Vector2T<T>(right, bottom);\n   }\n   Vector2T<T> bottom_right() const noexcept\n   {\n      return Vector2T<T>(right, bottom);\n   }\n\n   Vector2T<T> corner(int index) const noexcept\n   {\n      switch(index) {\n      case 0: return Vector2T<T>(left, bottom);\n      case 1: return Vector2T<T>(left, top);\n      case 2: return Vector2T<T>(right, top);\n      case 3: return Vector2T<T>(right, bottom);\n      }\n      FATAL(\"kBAM!\");\n      return {};\n   }\n\n   std::array<Vector2T<T>, 4> to_array_polygon() const noexcept\n   {\n      std::array<Vector2T<T>, 4> X;\n      X[0] = Vector2T<T>(left, top);\n      X[1] = Vector2T<T>(right, top);\n      X[2] = Vector2T<T>(right, bottom);\n      X[3] = Vector2T<T>(left, bottom);\n      return X;\n   }\n\n   vector<Vector2T<T>> to_polygon() const noexcept(false)\n   {\n      vector<Vector2T<T>> X(4);\n      X[0] = Vector2T<T>(left, top);\n      X[1] = Vector2T<T>(right, top);\n      X[2] = Vector2T<T>(right, bottom);\n      X[3] = Vector2T<T>(left, bottom);\n      return X;\n   }\n\n   Vector3T<T> left_line() const noexcept\n   {\n      T l = this->left, t = this->top, r = this->right, b = this->bottom;\n      return to_homgen_line(Vector3T<T>(l, t, 1), Vector3T<T>(l, b, 1));\n   }\n\n   Vector3T<T> right_line() const noexcept\n   {\n      T l = this->left, t = this->top, r = this->right, b = this->bottom;\n      return to_homgen_line(Vector3T<T>(r, t, 1), Vector3T<T>(r, b, 1));\n   }\n\n   Vector3T<T> top_line() const noexcept\n   {\n      T l = this->left, t = this->top, r = this->right, b = this->bottom;\n      return to_homgen_line(Vector3T<T>(l, t, 1), Vector3T<T>(r, t, 1));\n   }\n\n   Vector3T<T> bottom_line() const noexcept\n   {\n      T l = this->left, t = this->top, r = this->right, b = this->bottom;\n      return to_homgen_line(Vector3T<T>(l, b, 1), Vector3T<T>(r, b, 1));\n   }\n\n   Vector3T<T> line(int ind) const noexcept\n   {\n      switch(ind) {\n      case 0: return left_line();\n      case 1: return top_line();\n      case 2: return right_line();\n      case 3: return bottom_line();\n      }\n      return left_line();\n   }\n\n   bool operator!=(const AABBT<T>& rhs) const noexcept\n   {\n      return !(*this == rhs);\n   }\n   bool operator==(const AABBT<T>& rhs) const noexcept\n   {\n      return is_close(left, rhs.left) and is_close(top, rhs.top)\n             and is_close(right, rhs.right) and is_close(bottom, rhs.bottom);\n   }\n\n   AABBT& set_to(const T& l, const T& t, const T& r, const T& b) noexcept\n   {\n      left   = l;\n      top    = t;\n      right  = r;\n      bottom = b;\n      return *this;\n   }\n   AABBT& set_to(T a[4]) noexcept\n   {\n      set_to(a[0], a[1], a[2], a[3]);\n      return *this;\n   }\n\n   T* copy_to(T a[4]) const noexcept\n   {\n      a[0] = left;\n      a[1] = top;\n      a[2] = right;\n      a[3] = bottom;\n      return a;\n   }\n\n   T* ptr() noexcept { return &left; }\n   const T* ptr() const noexcept { return &left; }\n   T& operator[](int idx) noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 4);\n#endif\n      return ptr()[idx];\n   }\n\n   const T& operator[](int idx) const noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 4);\n#endif\n      return ptr()[idx];\n   }\n\n   T& operator()(int idx) noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 4);\n#endif\n      return ptr()[idx];\n   }\n   const T& operator()(int idx) const noexcept\n   {\n#ifdef DEBUG_BUILD\n      assert(idx >= 0 && idx < 4);\n#endif\n      return ptr()[idx];\n   }\n\n   unsigned size() const noexcept { return 4; }\n\n   std::string to_string(const char* fmt = \"[{} {} {} {}]\") const\n   {\n      return format(fmt, left, top, right, bottom);\n   }\n\n   std::string to_str() const { return to_string(); }\n\n   size_t hash() const noexcept { return sdbm_hash(ptr(), sizeof(T) * size()); }\n\n   friend std::string str(const AABBT<T>& aabb) { return aabb.to_string(); }\n};\n#pragma pack(pop)\n\ntemplate<typename T>\nAABBT<T> intersection(const AABBT<T>& a, const AABBT<T>& b) noexcept\n{\n   return AABBT<T>::intersection(a, b);\n}\n\ntemplate<typename T>\nT intersection_area(const AABBT<T>& a, const AABBT<T>& b) noexcept\n{\n   return AABBT<T>::intersection_area(a, b);\n}\n\ntemplate<typename T> T union_area(const AABBT<T>& a, const AABBT<T>& b) noexcept\n{\n   return AABBT<T>::union_area(a, b);\n}\n\n// Scalar multiples\ntemplate<typename T> AABBT<T> operator*(float a, const AABBT<T>& v) noexcept\n{\n   return v * a;\n}\ntemplate<typename T> AABBT<T> operator/(float a, const AABBT<T>& v) noexcept\n{\n   return v / a;\n}\ntemplate<typename T> AABBT<T> operator*(double a, const AABBT<T>& v) noexcept\n{\n   return v * a;\n}\ntemplate<typename T> AABBT<T> operator/(double a, const AABBT<T>& v) noexcept\n{\n   return v / a;\n}\n\n// Intersection of homogeneous line ('line') with AABB\ntemplate<typename T>\nstd::pair<Vector2T<T>, Vector2T<T>>\nintersect(const AABBT<T>& aabb, const Vector3T<T>& in_line) noexcept\n{\n   array<Vector3T<T>, 4> lines;\n   array<Vector3T<T>, 4> isects;\n   array<bool, 4> bounded;\n   std::pair<Vector2T<T>, Vector2T<T>> ret\n       = {Vector2T<T>::nan(), Vector2T<T>::nan()};\n\n   const auto line = in_line.normalised_line();\n\n   { // What are the lines of the AABB?, the order is [left, top, right, bot]\n      int counter = 0;\n      std::generate(\n          begin(lines), end(lines), [&]() { return aabb.line(counter++); });\n   }\n\n   { // Where does 'line' intersect with each line of the AABB?\n      std::transform(\n          cbegin(lines), cend(lines), begin(isects), [&](const auto& ll) {\n             return cross(line, ll).normalise_point();\n          });\n   }\n\n   { // Are inserections on the border of the AABB?\n     // Point 'X' is between lines 'l1' and 'l2'\n      auto is_between = [&](const Vector3T<T>& X,\n                            const Vector3T<T>& l1,\n                            const Vector3T<T>& l2) -> bool {\n         return X.is_finite() && (dot(X, l1) < 0.0) == (dot(X, l2) < 0.0);\n      };\n\n      bounded[0] = is_close_between(isects[0].y, aabb.top, aabb.bottom);\n      bounded[1] = is_close_between(isects[1].x, aabb.left, aabb.right);\n      bounded[2] = is_close_between(isects[2].y, aabb.top, aabb.bottom);\n      bounded[3] = is_close_between(isects[3].x, aabb.left, aabb.right);\n   }\n\n   unsigned pos     = 0;\n   auto push_result = [&](const Vector3T<T>& X) {\n      if(pos < 2) {\n         auto& p = (pos++ == 0) ? ret.first : ret.second;\n         p(0)    = X(0);\n         p(1)    = X(1);\n      } else {\n         const auto v  = Vector2T<T>(X(0), X(1));\n         const auto q0 = (ret.first - ret.second).quadrance();\n         const auto q1 = (ret.first - v).quadrance();\n         if(q1 > q0) ret.second = v;\n      }\n   };\n\n   for(size_t i = 0; i < 4; ++i)\n      if(bounded[i]) push_result(isects[i]);\n\n   if(false) {\n      INFO(\"FEEDBACK\");\n      cout << format(\"AABB  = {}\", str(aabb)) << endl;\n      cout << format(\"line  = {}\", str(line)) << endl;\n      for(auto i = 0; i < 4; ++i) {\n         cout << format(\" {:c} ll = {}, isect = {{}, {}}\",\n                        (bounded[size_t(i)] ? '*' : ' '),\n                        str(lines[size_t(i)]),\n                        isects[size_t(i)].x,\n                        isects[size_t(i)].y)\n              << endl;\n      }\n      cout << format(\"out   = {{}, {}} -> {{}, {}}\",\n                     ret.first.x,\n                     ret.first.y,\n                     ret.second.x,\n                     ret.second.y)\n           << endl\n           << endl;\n   }\n\n   return ret;\n}\n\ntemplate<typename T>\nstd::pair<Vector2T<T>, Vector2T<T>> intersect(const AABBT<T>& aabb,\n                                              const Vector2T<T>& A,\n                                              const Vector2T<T>& B) noexcept\n{\n   const bool A_in = aabb.contains(A);\n   const bool B_in = aabb.contains(B);\n\n   if(A_in and B_in) return {A, B};\n\n   const auto ll     = to_homgen_line(A, B);\n   const auto [U, V] = intersect(aabb, ll);\n\n   auto orthogonal_line_at = [&](const auto& U) -> auto\n   {\n      return Vector3T<T>(-ll.y, ll.x, ll.y * U.x - ll.x * U.y);\n   };\n\n   auto is_between_A_B = [&](const auto& U) -> bool {\n      const auto tt = orthogonal_line_at(U);\n      const auto da = tt.x * A.x + tt.y * A.y + tt.z;\n      const auto db = tt.x * B.x + tt.y * B.y + tt.z;\n      return std::signbit(da) != std::signbit(db);\n   };\n\n   auto subline\n       = [&](const auto& X, const auto& Y, const auto& U, const auto& V) {\n            return is_between_A_B(U) ? U : V;\n         };\n\n   if(A_in)\n      return {A, subline(A, B, U, V)};\n   else if(B_in)\n      return {subline(B, A, U, V), B};\n   if(is_between_A_B(U) and is_between_A_B(V)) return {U, V};\n   return {Vector2T<T>::nan(), Vector2T<T>::nan()};\n}\n\n// The returned homography maps points in the 'src' AABB to the 'dst' AABB\ntemplate<typename T>\ninline Eigen::Matrix3d rescale_homography(const AABBT<T>& src,\n                                          const AABBT<T>& dst) noexcept\n{\n   Eigen::Matrix3d H = Eigen::Matrix3d::Identity();\n   H(0, 0)           = dst.width() / src.width();\n   H(1, 1)           = dst.height() / src.height();\n   H(0, 2)           = dst.left - H(0, 0) * src.left;\n   H(1, 2)           = dst.top - H(1, 1) * src.top;\n\n   // auto tryit = [&] (Vector2 s, Vector2 d) {\n   //     Vector3r x = H * Vector3r(s.x, s.y, 1.0);\n   //     x /= x(2);\n   //     cout << format(\"{} => {} ({}, {})\",\n   //                    s.to_string(), d.to_string(), x(0), x(1))\n   //     << endl;\n   // };\n\n   // tryit(src.top_left(), dst.top_left());\n   // tryit(src.right_bottom(), dst.right_bottom());\n\n   return H;\n}\n\ntemplate<typename T>\ninline bool in_bounding_box(const Vector3T<T>& X,\n                            const Vector3T<T>& A,\n                            const Vector3T<T>& B)\n{\n   for(auto i = 0; i < 3; ++i)\n      if(X(i) < A(i)) return false;\n   for(auto i = 0; i < 3; ++i)\n      if(X(i) > B(i)) return false;\n   return true;\n};\n\n} // namespace perceive\n", "meta": {"hexsha": "3ffe8c91e95004c9fef2c9839e9a0c0e28c27552", "size": 15735, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/geometry/aabb.hpp", "max_stars_repo_name": "prcvlabs/multiview", "max_stars_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T23:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:43:32.000Z", "max_issues_repo_path": "multiview/multiview_cpp/src/perceive/geometry/aabb.hpp", "max_issues_repo_name": "prcvlabs/multiview", "max_issues_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:33:02.000Z", "max_forks_repo_path": "multiview/multiview_cpp/src/perceive/geometry/aabb.hpp", "max_forks_repo_name": "prcvlabs/multiview", "max_forks_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-26T03:14:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T06:42:52.000Z", "avg_line_length": 27.3652173913, "max_line_length": 80, "alphanum_fraction": 0.5403241182, "num_tokens": 4732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4252502042121823}}
{"text": "#include <fstream>\n#include <string>\n\n#include <polycrypto/PolyCrypto.h>\n\n#include <xutils/Utils.h>\n#include <xutils/Log.h>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace boost::multiprecision;\nusing namespace std;\nusing namespace libpolycrypto;\n\n/**\n * How do we reason about bandwidth in (t, n) DKG? (i.e., need t shares to reconstruct)\n *  - c   = the size of a poly commitment\n *  - s   = the size of a share\n *  - p   = the size of a proof for a share\n *  - f0c = the size of a Feldman commitment g^f(0) to f(0)\n *  - f0p = the size of the proof for g^f(0) (includes NIZKPoK for Kate et al)\n */\n\n/**\n *  DOWNLOAD\n *  --------\n *  Each player i\\in [n] needs to obtain from every other player j \\ne i: a poly commitment + share + proof + f(0) comm + f(0) proof\n *   - per-player: (n-1)*(c + s + p + f0c + f0p) commitments + shares + proofs need to be downloaded\n *   - total: n * per-player\n */\ntemplate<class T>\nT calcDownload(T n, T c, T s, T p, T f0c, T f0p) {\n    T perPlayer = (n-1)*(c + s + p + f0c + f0p);\n\n    return perPlayer;\n}\n\n/**\n *  UPLOAD\n *  ------\n *  Each player i needs to broadcast their poly commitment + f(0) comm + f(0) proof (same in eJF-DKG and in AMT DKG)\n *  Each player i sends n-1 shares to the n-1 other players (same in eJF-DKG and in AMT DKG)\n *  Each player i publishes the AMT (O(n) best case) or sends proofs individually (O(n log t) worst case)\n *  Assume n = 2^k for some k\n *\n *   - Best case per-player:  (c + f0c + f0p) + (n-1)*s + (2n-1)*c (for the AMT quotient commitments)\n *      - In eJF-DKG, last sum term would have been (n-1)*c (so we are only a bit more expensive)\n *\n *   - Worst case per-player: (c + f0c + f0p) + (n-1)*(s + (log(t-1) + 1)c)\n */\ntemplate<class T>\nT calcUpload_WorstCase(T n, T c, T s, T p, T f0c, T f0p) {\n    T perPlayer = c + f0c + f0p + (n-1)*(s + p);\n\n    return perPlayer;\n}\n\ntemplate<class T>\nT calcUpload(T n, T c, T s, T p, T f0c, T f0p) {\n    return calcUpload_WorstCase(n, c, s, p, f0c, f0p);\n}\n\n// NOTE: t is the reconstruction threshold so the poly degrees are t-1\ntemplate<class T>\nstd::tuple<T,T> feldman(T n, T t) {\n    const T polyDeg = (t - 1);\n    const T commSize = 32 * (polyDeg + 1); // need to send a group element for each coeff of the poly\n    const T shareSize = 32;        // share is just a field element\n    const T proofSize = 0;         // can verify share against commitment directly (not true for Pedersen though: needs 32-byte r(i))\n    const T f0commSize = 0;        // g^f(0) is already part of the Feldman commitment to the first coeff c_0 = f(0)\n    const T f0proofSize = 0;       // can verify f(0) directly against comm\n\n    return std::make_tuple(\n        calcDownload(n, commSize, shareSize, proofSize, f0commSize, f0proofSize),\n        calcUpload(n, commSize, shareSize, proofSize, f0commSize, f0proofSize));\n}\n\ntemplate<class T>\nstd::tuple<T,T> kate(T n) {\n    const T commSize = 32;          // g^p(s) is one group element\n    const T shareSize = 32;         // share is a field element\n    const T proofSize = 32;         // proof is g^{p(s) - p(i) / (x - i)}: one group element\n    const T f0commSize = 32;        // one group element\n    // a Schnorr signature (e = H(g || g^k || g^x || proverID || bla), s = k + ex)\n    // Reference: https://tools.ietf.org/html/rfc8235#page-8\n    const T nizkPok = 64;           // basically a Schnorr signature\n    const T f0proofSize = 32 + nizkPok; // g^f(0) proof: normal Kate proof + a NIZKPoK of f(0) w.r.t. g\n\n    return std::make_tuple(\n        calcDownload(n, commSize, shareSize, proofSize, f0commSize, f0proofSize),\n        calcUpload(n, commSize, shareSize, proofSize, f0commSize, f0proofSize));\n}\n\n/**\n * This is the bandwidth if we send a constant-sized proof for g^f(0) and a log n-sized proof for f(i)\n */\ntemplate<class T>\nstd::tuple<T,T> amt(T n, T t) {\n    // a tree of n = 2^i nodes has i + 1 nodes along any path and that's how many quotient commitments will be in our proof\n    // when n is not a power of two, we round up using log2ceil\n    const T commSize = 32;\n    const T shareSize = 32;\n    // we are only evaluating at n points this time, and proving g^f(0) using a normal Kate proof\n    //const T numLevels = Utils::log2ceil(n) + 1;\n    const T proofSize = (Utils::log2floor(t-1) + 1) * 32;\n    const T f0commSize = 32;\n    const T nizkPok = 64;           // see kate() description\n    const T f0proofSize = 32 + nizkPok;    // proof for g^f(0) is now a normal constant-sized Kate proof (+ NIZKPoK)\n\n    //loginfo << \" * numLevels = \" << numLevels << \" (for n = \" << n << \")\" << endl;\n\n    return std::make_tuple(\n        calcDownload(n, commSize, shareSize, proofSize, f0commSize, f0proofSize),\n        calcUpload(n, commSize, shareSize, proofSize, f0commSize, f0proofSize));\n}\n\nint main(int argc, char *argv[]) {\n    libpolycrypto::initialize(nullptr, 0);\n    \n    if(argc < 3) {\n        cout << \"Usage: \" << argv[0] << \" <out-file> <max-f>\" << endl;\n        cout << endl;\n        cout << \"Estimates bandwidth for Feldman, Kate and AMT DKGs\" << endl;\n        cout << endl;\n        cout << \" <out-file>     writes numbers in this file\" << endl;\n        cout << \" <max-f>        computes numbers for (k=f+1, n=2f+1) thresholds for f up to <max-f>\" << endl;\n        cout << endl;\n        return 1;\n    }\n\n    string outFile(argv[1]);\n    size_t max_f = static_cast<size_t>(std::stoi(argv[2]));\n\n    ofstream fout(outFile);\n\n    if(fout.fail()) {\n        throw std::runtime_error(\"Could not write to output file\");\n    }\n\n    using NumBytesType = int128_t;\n    loginfo << \"sizeof(NumBytesType): \" << sizeof(NumBytesType) << endl;\n\n    fout << \"t,n,dkg,download_bw_bytes,download_bw_hum,upload_bw_bytes,upload_bw_hum,comm_bw_bytes,comm_bw_hum,total_bw_bytes,total_bw_hum\" << endl;\n\n    for(size_t p = 2; p <= max_f + 1; p *= 2) {\n        size_t f = p - 1;\n        size_t t = f + 1;\n        size_t n = 2*f + 1;\n        loginfo << t << \" out of \" << n  << \" DKG\" << endl;\n\n        auto writeRow = [&fout, &n, &t](std::tuple<NumBytesType, NumBytesType> bytes, const char * scheme) {\n            NumBytesType perPlayerDown = std::get<0>(bytes);\n            NumBytesType perPlayerUp = std::get<1>(bytes);\n            fout\n                 << t << \",\"\n                 << n << \",\"\n                 << scheme << \",\"\n                 << perPlayerDown << \",\"\n                 << Utils::humanizeBytes(perPlayerDown) << \",\"\n                 << perPlayerUp << \",\"\n                 << Utils::humanizeBytes(perPlayerUp) << \",\"\n                 << perPlayerDown + perPlayerUp << \",\"\n                 << Utils::humanizeBytes(perPlayerDown + perPlayerUp) << \",\"\n                 << n*(perPlayerDown + perPlayerUp) << \",\"\n                 << Utils::humanizeBytes(n*(perPlayerDown + perPlayerUp))\n                 << endl;\n        };\n\n        writeRow(feldman(n, t), \"JF-DKG\");\n        writeRow(kate(n), \"eJF-DKG\");\n        writeRow(amt(n, t), \"AMT DKG\");\n    }\n    \n    loginfo << \"All done!\" << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "0962469c3e555b3ca2d9c17e02b1636ee477c6dd", "size": 6996, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libpolycrypto/app/BandwidthCalc.cpp", "max_stars_repo_name": "ibalajiarun/libpolycrypto", "max_stars_repo_head_hexsha": "89a69ed90ee4e9287222cc5781ff11562286f454", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2020-01-29T19:33:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T16:45:51.000Z", "max_issues_repo_path": "libpolycrypto/app/BandwidthCalc.cpp", "max_issues_repo_name": "ibalajiarun/libpolycrypto", "max_issues_repo_head_hexsha": "89a69ed90ee4e9287222cc5781ff11562286f454", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-18T12:33:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T18:30:55.000Z", "max_forks_repo_path": "libpolycrypto/app/BandwidthCalc.cpp", "max_forks_repo_name": "ibalajiarun/libpolycrypto", "max_forks_repo_head_hexsha": "89a69ed90ee4e9287222cc5781ff11562286f454", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-07-09T01:35:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-20T04:54:47.000Z", "avg_line_length": 39.3033707865, "max_line_length": 148, "alphanum_fraction": 0.5913379074, "num_tokens": 2178, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.679178692681616, "lm_q1q2_score": 0.4252502001462715}}
{"text": "// -----------------------------------------------------------------------\n//\n// Copyright (C) 2020  - David Fernández Castellanos\n//\n// This file is part of the MEPLS software. You can use it, redistribute\n// it, and/or modify it under the terms of the Creative Commons Attribution\n// 4.0 International Public License. The full text of the license can be\n// found in the file LICENSE at the top level of the MEPLS distribution.\n//\n// -----------------------------------------------------------------------\n\n#include <example.h>\n#include <mepls/utils.h>\n#include <mepls/solver.h>\n#include <mepls/system.h>\n#include <mepls/event.h>\n#include <mepls/history.h>\n#include <mepls/dynamics.h>\n#include <cmdparser.hpp>\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/base/path_search.h>\n#include <boost/property_tree/json_parser.hpp>\n\n// new headers\n#include <omp.h>\n#include <deal.II/base/conditional_ostream.h>\n\n\nstruct Parameters\n{\n   unsigned int seed = 1234567;\n   unsigned int n_rep = 1;\n   unsigned int Nx = 32;\n   unsigned int Ny = 32;\n   double G = 30.;\n   double nu = 0.3;\n   double gamma = 0.05;\n   double k = 6.;\n   double strain_limit_aqs = 0.05;\n   double time_limit_creep = 1e5;\n   double ext_stress_creep = 0.;\n   double lambda = 1.;\n   double temperature = 1.;\n   bool verbose = true;\n\n   void declare_entries(dealii::ParameterHandler &prm)\n   {\n      prm.enter_subsection(\"Section1\");\n\n      prm.declare_entry(\"seed\", mepls::utils::str::to_string(seed), dealii::Patterns::Integer(0), \"\");\n      prm.declare_entry(\"n_rep\", mepls::utils::str::to_string(n_rep), dealii::Patterns::Integer(0), \"\");\n      prm.declare_entry(\"Nx\", mepls::utils::str::to_string(Nx), dealii::Patterns::Integer(0), \"\");\n      prm.declare_entry(\"Ny\", mepls::utils::str::to_string(Ny), dealii::Patterns::Integer(0), \"\");\n      prm.declare_entry(\"G\", mepls::utils::str::to_string(G), dealii::Patterns::Double(0.0), \"\");\n      prm.declare_entry(\"nu\", mepls::utils::str::to_string(nu), dealii::Patterns::Double(0.0), \"\");\n      prm.declare_entry(\"gamma\", mepls::utils::str::to_string(gamma), dealii::Patterns::Double(0.0), \"\");\n      prm.declare_entry(\"strain_limit_aqs\", mepls::utils::str::to_string(strain_limit_aqs), dealii::Patterns::Double(0.0), \"\");\n      prm.declare_entry(\"time_limit_creep\", mepls::utils::str::to_string(time_limit_creep), dealii::Patterns::Double(0.0), \"\");\n      prm.declare_entry(\"ext_stress_creep\", mepls::utils::str::to_string(ext_stress_creep), dealii::Patterns::Double(0.0), \"\");\n      prm.declare_entry(\"temperature\", mepls::utils::str::to_string(temperature), dealii::Patterns::Double(0.0), \"\");\n      prm.declare_entry(\"lambda\", mepls::utils::str::to_string(lambda), dealii::Patterns::Double(0.0), \"\");\n      prm.declare_entry(\"k\", mepls::utils::str::to_string(k), dealii::Patterns::Double(0.0), \"\");\n\t  prm.declare_entry(\"verbose\", mepls::utils::str::to_string(verbose), dealii::Patterns::Bool(), \"\");\n\n      prm.leave_subsection();\n   }\n\n   void load_entries(dealii::ParameterHandler &prm)\n   {\n      prm.enter_subsection(\"Section1\");\n\n      seed = prm.get_integer(\"seed\");\n      n_rep = prm.get_integer(\"n_rep\");\n      Nx = prm.get_integer(\"Nx\");\n      Ny = prm.get_integer(\"Ny\");\n      G = prm.get_double(\"G\");\n      nu = prm.get_double(\"nu\");\n      gamma = prm.get_double(\"gamma\");\n      k = prm.get_double(\"k\");\n      strain_limit_aqs = prm.get_double(\"strain_limit_aqs\");\n      time_limit_creep = prm.get_double(\"time_limit_creep\");\n      ext_stress_creep = prm.get_double(\"ext_stress_creep\");\n      temperature = prm.get_double(\"temperature\");\n      lambda = prm.get_double(\"lambda\");\n      verbose = prm.get_bool(\"verbose\");\n\n      prm.leave_subsection();\n   }\n\n   void load_file(const std::string &filename)\n   {\n      dealii::ParameterHandler prm;\n      declare_entries(prm);\n      prm.parse_input(filename);\n      load_entries(prm);\n   }\n\n   void generate_file(const std::string &filename)\n   {\n      std::ofstream outfile(filename);\n      dealii::ParameterHandler prm;\n      declare_entries(prm);\n      prm.print_parameters(outfile, dealii::ParameterHandler::OutputStyle::Text);\n   }\n\n};\n\n\ntemplate<int dim>\nvoid write_data(const mepls::history::History<dim> &creep_history,\n                const mepls::history::History<dim> &aqs_history,\n                const Parameters &p)\n{\n   boost::property_tree::ptree data_tree;\n\n   data_tree.put(\"Name\", \"Step5\");\n   data_tree.put(\"Description\", \"System undergoing creep deformation, and then driven in \"\n\t\t\t\t\t\t\t\t\"athermal quasistatic shear\");\n\n   data_tree.put(\"Parameters.dim\", 2);\n   data_tree.put(\"Parameters.seed\", p.seed);\n   data_tree.put(\"Parameters.Nx\", p.Nx);\n   data_tree.put(\"Parameters.Ny\", p.Ny);\n   data_tree.put(\"Parameters.G\", p.G);\n   data_tree.put(\"Parameters.nu\", p.nu);\n   data_tree.put(\"Parameters.gamma\", p.gamma);\n   data_tree.put(\"Parameters.lambda\", p.lambda);\n   data_tree.put(\"Parameters.temperature\", p.temperature);\n   data_tree.put(\"Parameters.k\", p.k);\n   data_tree.put(\"Parameters.ext_stress_creep\", p.ext_stress_creep);\n   data_tree.put(\"Parameters.time_limit_creep\", p.time_limit_creep);\n   data_tree.put(\"Parameters.strain_limit_aqs\", p.strain_limit_aqs);\n\n   \t// -------- creep history ----------\n\t{\n\t   std::ostringstream plastic_events_csv;\n\t   plastic_events_csv << \"index,element,eigenstrain_00,eigenstrain_11,eigenstrain_01\\n\";\n\t   for(auto &row : creep_history.plastic)\n\t\t  plastic_events_csv << row.index << \",\" << row.element << \",\" << row.eigenstrain_00 << \",\"\n\t\t\t\t\t\t\t << row.eigenstrain_11 << \",\" << row.eigenstrain_01 << \"\\n\";\n\n\t   data_tree.put(\"Data.creep.plastic_events\", plastic_events_csv.str());\n\n\n\t   std::ostringstream driving_events_csv;\n\t   driving_events_csv << \"index,dtime,dext_stress,dtotal_strain\\n\";\n\t   for(auto &row : creep_history.driving)\n\t\t  driving_events_csv << row.index << \",\" << row.dtime << \",\"\n\t\t\t\t\t\t\t << row.dext_stress << \",\" << row.dtotal_strain << \"\\n\";\n\n\t   data_tree.put(\"Data.creep.driving_events\", driving_events_csv.str());\n\n\n\t   std::ostringstream macro_evolution_csv;\n\t   macro_evolution_csv << \"index,ext_stress,total_strain,time,av_vm_stress,av_vm_plastic_strain\\n\";\n\t   for(auto &row : creep_history.macro_evolution)\n\t\t  macro_evolution_csv << row.index << \",\" << row.ext_stress << \",\"\n\t\t\t\t\t\t\t << row.total_strain << \",\" << row.time << \",\"\n\t\t\t\t\t\t\t << row.av_vm_stress << \",\" << row.av_vm_plastic_strain << \"\\n\";\n\n\t   data_tree.put(\"Data.creep.macro_evolution\", macro_evolution_csv.str());\n\t}\n\n\t// -------- aqs history ----------\n\t{\n\t   std::ostringstream plastic_events_csv;\n\t   plastic_events_csv << \"index,element,eigenstrain_00,eigenstrain_11,eigenstrain_01\\n\";\n\t   for(auto &row : aqs_history.plastic)\n\t\t  plastic_events_csv << row.index << \",\" << row.element << \",\" << row.eigenstrain_00 << \",\"\n\t\t\t\t\t\t\t << row.eigenstrain_11 << \",\" << row.eigenstrain_01 << \"\\n\";\n\n\t   data_tree.put(\"Data.AQS.plastic_events\", plastic_events_csv.str());\n\n\n\t   std::ostringstream driving_events_csv;\n\t   driving_events_csv << \"index,dtime,dext_stress,dtotal_strain\\n\";\n\t   for(auto &row : aqs_history.driving)\n\t\t  driving_events_csv << row.index << \",\" << row.dtime << \",\"\n\t\t\t\t\t\t\t << row.dext_stress << \",\" << row.dtotal_strain << \"\\n\";\n\n\t   data_tree.put(\"Data.AQS.driving_events\", driving_events_csv.str());\n\n\n\t   std::ostringstream macro_evolution_csv;\n\t   macro_evolution_csv << \"index,ext_stress,total_strain,time,av_vm_stress,av_vm_plastic_strain\\n\";\n\t   for(auto &row : aqs_history.macro_evolution)\n\t\t  macro_evolution_csv << row.index << \",\" << row.ext_stress << \",\"\n\t\t\t\t\t\t\t << row.total_strain << \",\" << row.time << \",\"\n\t\t\t\t\t\t\t << row.av_vm_stress << \",\" << row.av_vm_plastic_strain << \"\\n\";\n\n\t   data_tree.put(\"Data.AQS.macro_evolution\", macro_evolution_csv.str());\n\t}\n\n\n\t// create a descriptive filename\n   \tstd::ostringstream filename;\n\n\tfilename << \"Nx_\" << p.Nx\n\t         << \"+gamma_\" << std::fixed << std::setprecision(2) << p.gamma\n\t         << \"+lambda_\" << p.lambda\n\t         << \"+k_\" << p.k\n\t\t     << \"+G_\" << p.G\n\t\t     << \"+T_\" << p.temperature\n\t\t     << \"+ext_stress_\" << p.ext_stress_creep\n\t\t\t << \"+seed_\" << p.seed\n\t\t\t << \".json\";\n\n   std::ofstream output_file( filename.str() );\n   boost::property_tree::json_parser::write_json(output_file, data_tree);\n   output_file.close();\n}\n\n\nvoid run(const Parameters &p, dealii::ConditionalOStream & cout)\n{\n   //----- SET UP ------\n\n   constexpr unsigned dim = 2;\n   std::mt19937 generator(p.seed);\n\n   dealii::SymmetricTensor<4, dim> C = mepls::utils::tensor::make_isotropic_stiffness<dim>(p.G, p.nu);\n\n   mepls::element::Vector<dim> elements;\n\n   for(double n = 0; n < p.Nx * p.Ny; ++n)\n   {\n      example::element::Scalar<dim>::Config conf;\n      conf.number = n;\n      conf.gamma = p.gamma;\n      conf.lambda = p.lambda;\n      conf.k = p.k;\n      conf.temperature = p.temperature;\n\n      auto element = new example::element::Scalar<dim>(conf, generator);\n      element->C(C);\n\n      elements.push_back(element);\n   }\n\n   mepls::elasticity_solver::LeesEdwards<dim> solver(p.Nx, p.Ny, mepls::elasticity_solver::ControlMode::stress);\n   for(auto &element : elements)\n      solver.set_elastic_properties(element->number(), element->C());\n   solver.setup_and_assembly();\n\n   mepls::element::calculate_local_stress_coefficients_central(elements, solver);\n   mepls::element::calculate_ext_stress_coefficients(elements, solver);\n\n   mepls::system::Standard<dim> system(elements, solver, generator);\n\n\n   //----- CREEP DEFORMATION ------\n\n   mepls::history::History<dim> creep_history(\"creep_history\");\n   system.set_history(creep_history);\n   creep_history.add_macro(system);\n\n   // apply an external (stress) load of amplitude p.ext_stress_creep\n   mepls::dynamics::fixed_load_increment(p.ext_stress_creep, system);\n   creep_history.add_macro(system);\n\n   mepls::dynamics::KMC<dim> kmc;\n\n   mepls::utils::ContinueSimulation continue_creep;\n\n\twhile( continue_creep() )\n\t{\n\t\tcout << system.macrostate[\"time\"] << \" \" << system.macrostate[\"total_strain\"] <<\" \"\n\t\t\t  << system.macrostate[\"ext_stress\"] << std::endl;\n\n\t\tkmc(system);\n\t\tcreep_history.add_macro(system);\n\n\t\tmepls::dynamics::relaxation(system, continue_creep);\n\t\tcreep_history.add_macro(system);\n\n\t  continue_creep(system.macrostate[\"time\"] < p.time_limit_creep, \"creep time limit reached\");\n\t}\n\n\t cout << continue_creep << std::endl;\n\n\n   //----- TRANSITION TO AQS ------\n\n\t// remove the external load\n    mepls::dynamics::fixed_load_increment(-p.ext_stress_creep, system);\n\tcreep_history.add_macro(system);\n\n\t// relax possible unstable slip system after the load change\n\tmepls::dynamics::relaxation(system, continue_creep);\n\tcreep_history.add_macro(system);\n\n    // in the AQS, we start measuring the macroscale strain from zero\n\tsystem.macrostate.clear();\n\n\tfor(auto & element : elements)\n\t\telement->state_to_prestress();\n\n\t// we switch the driving mode to strain-controlled during AQS\n    solver.set_control_mode(mepls::elasticity_solver::ControlMode::strain);\n\n    // since the type of driving conditions have changed, the local stress change induced by a unit\n    // load increment is different. We need to re-compute the ext_stress_coefficients\n    mepls::element::calculate_ext_stress_coefficients(elements, solver);\n\n\n    //----- ATHERMAL QUASISTATIC SHEAR ------\n\n   \tmepls::history::History<dim> aqs_history(\"aqs_history\");\n  \tsystem.set_history(aqs_history);\n   \taqs_history.add_macro(system);\n\n   mepls::utils::ContinueSimulation continue_AQS_simulation;\n   while(continue_AQS_simulation())\n   {\n\t\tcout << system.macrostate[\"total_strain\"] << \" \" << system.macrostate[\"ext_stress\"] << std::endl;\n\n      mepls::dynamics::extremal_dynamics_step(system);\n      aqs_history.add_macro(system);\n\n      mepls::dynamics::relaxation(system, continue_AQS_simulation);\n      aqs_history.add_macro(system);\n\n      continue_AQS_simulation(system.macrostate[\"total_strain\"] < p.strain_limit_aqs, \"AQS strain limit reached\");\n   }\n\n\t   cout << continue_AQS_simulation << std::endl;\n\n   for(auto &element : elements)\n      delete element;\n\n\t// write the simulation data, using its own dedicated function\n\twrite_data(creep_history, aqs_history, p);\n}\n\n\nint main(int argc, char *argv[])\n{\n   // Read the command line arguments. We define the -f 'filename' to pass the\n   // path to the parameters file\n   cli::Parser parser(argc, argv);\n   parser.set_optional<std::string>(\"f\", \"file\", \"./default.prm\", \"Name of the input configuration file\");\n   parser.run_and_exit_if_error();\n   // you can check https://github.com/FlorianRappl/CmdParser for a further documentation of cli::Parser\n\n\n\n   // Create the parameters object\n   Parameters p;\n\n   // We try to load the parameters file, but if it doesn't exist, we generate a new one with the name\n   // default.prm and default values\n   try\n   {\n      p.load_file(parser.get<std::string>(\"f\"));\n   }\n   catch(dealii::PathSearch::ExcFileNotFound &)\n   {\n      p.generate_file(parser.get<std::string>(\"f\"));\n      std::cout << \"Configuration file \" << parser.get<std::string>(\"f\") << \" created\" << std::endl;\n      return 1;\n   }\n\n\n\n\tunsigned int n_rep = p.n_rep;\n\tif(n_rep < omp_get_max_threads())\n\t\tn_rep = omp_get_max_threads();\n\n\t// initialize the master engine with the master seed\n\tstd::srand(p.seed);\n\n\t#pragma omp parallel\n\t{\n\t\tunsigned int n_threads = omp_get_max_threads();\n\t\tunsigned int id = omp_get_thread_num();\n\t\tunsigned int rep_per_thread = int( n_rep / n_threads );\n\n\t\tdealii::ConditionalOStream cout(std::cout, id==0 and p.verbose);\n\n\t\tfor(unsigned int n = 0; n < rep_per_thread; ++n)\n\t\t{\n\t\t\tParameters p_thread = p;\n\t\t\t#pragma critical\n\t\t\t{\n\t\t\t\t// generate a seed for a simulation run\n\t\t\t\tp_thread.seed = std::rand();\n\t\t\t};\n\n\t\t\trun(p_thread, cout);\n\t\t}\n\n\t}\n\n   return 0;\n}\n", "meta": {"hexsha": "f7453092988cd6a2636ddbf556270cae2d7e2e57", "size": 13711, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tutorial/step5/step_5.cc", "max_stars_repo_name": "kastellane/MEPLS", "max_stars_repo_head_hexsha": "9d7e4a7b9de73e65e3d4e4aba9b90a6fd563e186", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorial/step5/step_5.cc", "max_issues_repo_name": "kastellane/MEPLS", "max_issues_repo_head_hexsha": "9d7e4a7b9de73e65e3d4e4aba9b90a6fd563e186", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial/step5/step_5.cc", "max_forks_repo_name": "kastellane/MEPLS", "max_forks_repo_head_hexsha": "9d7e4a7b9de73e65e3d4e4aba9b90a6fd563e186", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6237373737, "max_line_length": 127, "alphanum_fraction": 0.6680037926, "num_tokens": 3552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.42525019473559383}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n// Copyright (c) 2013 Adam Wulkiewicz, Lodz, Poland.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_GEOMETRIES_MATRIX_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_GEOMETRIES_MATRIX_HPP\n\n#include <cstddef>\n\n#include <boost/geometry/extensions/algebra/core/tags.hpp>\n#include <boost/geometry/extensions/algebra/geometries/concepts/matrix_concept.hpp>\n\nnamespace boost { namespace geometry {\n\nnamespace model {\n\ntemplate <typename T, std::size_t Rows, std::size_t Cols>\nclass matrix\n{\n    BOOST_CONCEPT_ASSERT( (concept::Matrix<matrix>) );\n\npublic:\n\n    /// @brief Default constructor, no initialization\n    inline matrix()\n    {}\n\n    /// @brief Get a coordinate\n    /// @tparam I row index\n    /// @tparam J col index\n    /// @return the cell value\n    template <std::size_t I, std::size_t J>\n    inline T const& get() const\n    {\n        BOOST_STATIC_ASSERT(I < Rows);\n        BOOST_STATIC_ASSERT(J < Cols);\n        return m_values[I + Rows * J];\n    }\n\n    /// @brief Set a coordinate\n    /// @tparam I row index\n    /// @tparam J col index\n    /// @param value value to set\n    template <std::size_t I, std::size_t J>\n    inline void set(T const& value)\n    {\n        BOOST_STATIC_ASSERT(I < Rows);\n        BOOST_STATIC_ASSERT(J < Cols);\n        m_values[I + Rows * J] = value;\n    }\n\nprivate:\n\n    T m_values[Rows * Cols];\n};\n\n} // namespace model\n\n#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS\nnamespace traits\n{\n\ntemplate <typename CoordinateType, std::size_t Rows, std::size_t Cols>\nstruct tag<model::matrix<CoordinateType, Rows, Cols> >\n{\n    typedef matrix_tag type;\n};\n\ntemplate <typename CoordinateType, std::size_t Rows, std::size_t Cols>\nstruct coordinate_type<model::matrix<CoordinateType, Rows, Cols> >\n{\n    typedef CoordinateType type;\n};\n\n//template <typename CoordinateType, std::size_t Rows, std::size_t Cols>\n//struct coordinate_system<model::matrix<CoordinateType, Rows, Cols> >\n//{\n//    typedef cs::cartesian type;\n//};\n\n// TODO - move this class to traits.hpp\ntemplate <typename Geometry, std::size_t Index>\nstruct indexed_dimension\n{\n     BOOST_MPL_ASSERT_MSG(false,\n                          NOT_IMPLEMENTED_FOR_THIS_GEOMETRY_OR_INDEX,\n                          (Geometry, boost::integral_constant<std::size_t, Index>));\n};\n\ntemplate <typename CoordinateType, std::size_t Rows, std::size_t Cols>\nstruct indexed_dimension<model::matrix<CoordinateType, Rows, Cols>, 0>\n    : boost::integral_constant<std::size_t, Rows>\n{};\n\ntemplate <typename CoordinateType, std::size_t Rows, std::size_t Cols>\nstruct indexed_dimension<model::matrix<CoordinateType, Rows, Cols>, 1>\n    : boost::integral_constant<std::size_t, Cols>\n{};\n\ntemplate <typename CoordinateType, std::size_t Rows, std::size_t Cols, std::size_t I, std::size_t J>\nstruct indexed_access<model::matrix<CoordinateType, Dimension>, I, J>\n{\n    typedef CoordinateType coordinate_type;\n\n    static inline coordinate_type get(model::matrix<CoordinateType, Rows, Cols> const& m)\n    {\n        return m.template get<I, J>();\n    }\n\n    static inline void set(model::matrix<CoordinateType, Rows, Cols> & m, coordinate_type const& value)\n    {\n        m.template set<I, J>(value);\n    }\n};\n\n} // namespace traits\n#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_GEOMETRIES_MATRIX_HPP\n", "meta": {"hexsha": "61b988403d94f83f31925f6182482044070540af", "size": 3900, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/algebra/geometries/matrix.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "3party/boost/boost/geometry/extensions/algebra/geometries/matrix.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "3party/boost/boost/geometry/extensions/algebra/geometries/matrix.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-04T10:55:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T18:52:06.000Z", "avg_line_length": 29.5454545455, "max_line_length": 103, "alphanum_fraction": 0.7076923077, "num_tokens": 999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4252501866037726}}
{"text": "//Bsplines file\n#include <Eigen/Sparse>\n#include <Eigen/Eigenvalues>\n#include <Eigen/StdVector>\n#include <cstdlib>\n#include <iostream>\n#include <mpi.h>\n#include <fstream>\n#include <iterator>\n#include <vector>\n#include <algorithm>\n#include <complex>\n#include <sstream>\n#include <math.h>\n#include <omp.h>\n#include <numeric>\n#include <chrono>\n#include <ctime>\n#include <limits>\n#include \"bsplines.h\"\n\n\n#define bp(x) cout << \"breakpoint\" << (#x) << endl\n\nusing namespace Eigen;\nusing namespace std::complex_literals;\nusing namespace std::chrono;\nusing std::cout;\nusing std::endl;\n\n \nvoid generateBsplines(InputParameter Inp, double dX,ArrayXd x,ArrayXXd &BB,ArrayXXd &d_BB, ArrayXXd &diff_BB){\n    std::vector<Array<double,Dynamic,Dynamic>\n        ,aligned_allocator<Array<double,Dynamic,Dynamic> > > B(Inp.n+1);\n    for(int i = 0 ; i < Inp.n+1; i++){\n        B[i].setZero(x.size(),Inp.N_b-1+2*Inp.n);\n    }\n     \n    ArrayXd t = ArrayXd::Zero(Inp.N_b+2*Inp.n);\n    \n    for(int i = Inp.n+1; i< Inp.N_b +Inp.n;i++){\n        B[0].col(i-1).segment((i-Inp.n-1) * Inp.n,Inp.n) = 1;\n        t(i-1) = (i-Inp.n-1) * dX;\n\n    }\n    t.segment(Inp.N_b + Inp.n - 1,Inp.n+1) = Inp.b;\n    for( int k = 1; k < Inp.n+1;k++){\n        for(int i = 1; i < Inp.N_b-1+2*Inp.n-k+1; i++){\n            double tmp1 = t(i+k-1) - t(i-1);\n            double tmp2 = t(i+k+0) - t(i-0);\n\n            if(tmp1 == 0)\n                tmp1 =1;\n            if(tmp2 == 0)\n                tmp2 =1;       \n        \n            B[k].col(i-1) = ((x - t(i-1))/tmp1) * B[k-1].col(i-1) \n                           + (t(i+k) - x)/tmp2 * B[k-1].col(i); \n       }\n    }\n    bp(\"first order derivaitve of bsplines\");\n    //d_B is the first derivative \n    std::vector<Array<double,Dynamic,Dynamic>\n        ,aligned_allocator<Array<double,Dynamic,Dynamic> > > d_B(Inp.n+1);\n    for(int i = 0 ; i < Inp.n+1; i++){\n        d_B[i].setZero(x.size(),Inp.N_b-1+2*Inp.n);\n    }\n\n    for( int k = 2; k < Inp.n+1; k++){\n        for(int i = 1; i < Inp.N_b-1+2*Inp.n-k+1; i++){\n            double tmp1 = t(i+k-1) - t(i-1);\n            double tmp2 = t(i+k+0) - t(i+0);\n\n            if(tmp1 == 0)\n                tmp1 =1;\n            if(tmp2 == 0)\n                tmp2 =1;       \n        \n            d_B[k].col(i-1) = k * (B[k-1].col(i-1)/tmp1 - B[k-1].col(i)/tmp2);\n\n        }\n    }\n    bp(\"scond order derivative of bsplines \");\n    //diff of B is the second derivative \n    std::vector<Array<double,Dynamic,Dynamic>\n        ,aligned_allocator<Array<double,Dynamic,Dynamic> > > diff_B(Inp.n+1);\n    for(int i = 0 ; i < Inp.n+1; i++){\n        diff_B[i].setZero(x.size(),Inp.N_b-1+2*Inp.n);\n    }\n\n    for( int k = 2; k < Inp.n+1; k++){\n        for(int i = 1; i < Inp.N_b-1+2*Inp.n-k+1; i++){\n            double tmp1 = t(i+k-1) - t(i-1);\n            double tmp2 = t(i+k+0) - t(i+0);\n            double tmp3 = t(i+k-2) - t(i-1);\n            double tmp4 = t(i+k-1) - t(i+0);\n            double tmp5 = t(i+k+0) - t(i+1);\n\n            if(tmp1 == 0)\n                tmp1 =1;\n            if(tmp2 == 0)\n                tmp2 =1;       \n            if(tmp3 == 0)\n                tmp3 =1;       \n            if(tmp4 == 0)\n                tmp4 =1;       \n            if(tmp5 == 0)\n                tmp5 =1;       \n            \n        diff_B[k].col(i-1) = k * (k-1)/tmp1 * (B[k-2].col(i-1)/tmp3 - B[k-2].col(i)/tmp4)\n                           - k * (k-1)/tmp2 * (B[k-2].col(i)/tmp4 - B[k-2].col(i+1)/tmp5);\n        }\n    }\n    BB=B[Inp.n];\n    d_BB=d_B[Inp.n];\n    diff_BB=diff_B[Inp.n];\n\n    cout <<\"Bsplines generated\"<<endl;\n   \n}\n\nvoid gausLegendreSetup(int k, int nmbr_breakpoints,\n        ArrayXd x_break, ArrayXd &x, ArrayXd &weights){\n    //Return evenly spaced values within a given interval.\n    std::vector<int> I(k);\n    std::iota(I.begin(),I.end(),1);\n    \n    MatrixXd J = MatrixXd::Zero(k,k);\n    for(int i = 0; i < k-1; i++){\n        J(i,i+1) = 0.5 / sqrt(1-pow(2*I[i],-2));\n        J(i+1,i) = 0.5 / sqrt(1-pow(2*I[i],-2));\n    }\n    //get the eigenvalues and eigenvectors \n\n    SelfAdjointEigenSolver<MatrixXd> es;\n    es.compute(J);\n    VectorXd eigval = es.eigenvalues();\n    MatrixXd eigvect = es.eigenvectors();\n    for(int i = 2; i < nmbr_breakpoints+1;i++){\n        x.segment((i-2)*k,k) = (x_break(i-1)-x_break(i-2))*0.5*  eigval.array()\n            +(x_break[i-1]+x_break[i-2])*0.5;\n        weights.segment((i-2)*k,k) = 2*eigvect.row(0).array().square();\n        \n    }\n\n}\n\n\n", "meta": {"hexsha": "23ea5e018059e09c647e6d9f8b50d88a229f151c", "size": 4422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bsplines.cpp", "max_stars_repo_name": "krygol/GPU-Accelerated-Propagator", "max_stars_repo_head_hexsha": "4d0af7e1739e39813bab6dac760b8d1589116c20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/bsplines.cpp", "max_issues_repo_name": "krygol/GPU-Accelerated-Propagator", "max_issues_repo_head_hexsha": "4d0af7e1739e39813bab6dac760b8d1589116c20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/bsplines.cpp", "max_forks_repo_name": "krygol/GPU-Accelerated-Propagator", "max_forks_repo_head_hexsha": "4d0af7e1739e39813bab6dac760b8d1589116c20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.677852349, "max_line_length": 110, "alphanum_fraction": 0.4968340118, "num_tokens": 1523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4250267293941805}}
{"text": "#ifndef SKYLARK_BLOCKADMM_HPP\n#define SKYLARK_BLOCKADMM_HPP\n\n#include <elemental.hpp>\n#include <skylark.hpp>\n#include <cmath>\n#include <boost/mpi.hpp>\n\n#ifdef SKYLARK_HAVE_OPENMP\n#include <omp.h>\n#endif\n\n#include \"../utility/timer.hpp\"\n#include \"hilbert.hpp\"\n\n// Columns are examples, rows are features\ntypedef elem::DistMatrix<double, elem::STAR, elem::VC> DistInputMatrixType;\n\n// Rows are examples, columns are target values\ntypedef elem::DistMatrix<double, elem::VC, elem::STAR> DistTargetMatrixType;\n\ntypedef elem::Matrix<double> LocalMatrixType;\ntypedef skylark::base::sparse_matrix_t<double> sparse_matrix_t;\n\ntemplate <class T>\nclass BlockADMMSolver\n{\npublic:\n\n    typedef skylark::sketch::sketch_transform_t<T, LocalMatrixType>\n    feature_transform_t;\n    typedef std::vector<const feature_transform_t *> feature_transform_array_t;\n\n\n    // No feature transdeforms (aka just linear regression).\n    BlockADMMSolver(const lossfunction* loss,\n        const regularization* regularizer,\n        double lambda, // regularization parameter\n        int NumFeatures,\n        int NumFeaturePartitions = 1);\n\n    // Easy interface, aka kernel based.\n    template<typename Kernel, typename MapTypeTag>\n    BlockADMMSolver<T>(skylark::base::context_t& context,\n        const lossfunction* loss,\n        const regularization* regularizer,\n        double lambda, // regularization parameter\n        int NumFeatures,\n        Kernel kernel,\n        MapTypeTag tag,\n        int NumFeaturePartitions = 1);\n\n    // Easy interface, aka kernel based, with quasi-random features.\n    template<typename Kernel>\n    BlockADMMSolver<T>(skylark::base::context_t& context,\n        const lossfunction* loss,\n        const regularization* regularizer,\n        double lambda, // regularization parameter\n        int NumFeatures,\n        Kernel kernel,\n        skylark::ml::quasi_feature_transform_tag tag,\n        int NumFeaturePartitions);\n\n    // Guru interface.\n    BlockADMMSolver<T>(const lossfunction* loss,\n        const regularization* regularizer,\n        const feature_transform_array_t& featureMaps,\n        double lambda, // regularization parameter\n        bool ScaleFeatureMaps = true);\n\n    void set_nthreads(int NumThreads) { this->NumThreads = NumThreads; }\n    void set_rho(double RHO) { this->RHO = RHO; }\n    void set_maxiter(double MAXITER) { this->MAXITER = MAXITER; }\n    void set_tol(double TOL) { this->TOL = TOL; }\n    void set_cache_transform(bool CacheTransforms) {this->CacheTransforms = CacheTransforms;}\n\n    ~BlockADMMSolver();\n\n    void InitializeFactorizationCache();\n    void InitializeTransformCache(int n);\n\n    skylark::ml::model_t<T, LocalMatrixType>* train(T& X,\n        LocalMatrixType& Y, T& Xv, LocalMatrixType& Yv,\n        const boost::mpi::communicator& comm);\n\n    int get_numfeatures() {return NumFeatures;}\n\n    feature_transform_array_t& get_feature_maps() {return featureMaps;}\n\nprivate:\n\n    feature_transform_array_t featureMaps;\n    int NumFeatures;\n    int NumFeaturePartitions;\n    lossfunction* loss;\n    regularization* regularizer;\n    std::vector<int> starts, finishes;\n    bool ScaleFeatureMaps;\n    bool OwnFeatureMaps;\n    LocalMatrixType **Cache;\n    LocalMatrixType **TransformCache;\n    int NumThreads;\n\n    double lambda;\n    double RHO;\n    int MAXITER;\n    double TOL;\n\n    bool CacheTransforms;\n};\n\ntemplate <class T>\nvoid BlockADMMSolver<T>::InitializeFactorizationCache() {\n    Cache = new LocalMatrixType* [NumFeaturePartitions];\n    for(int j=0; j<NumFeaturePartitions; j++) {\n        int start = starts[j];\n        int finish = finishes[j];\n        int sj = finish - start  + 1;\n        Cache[j]  = new elem::Matrix<double>(sj, sj);\n    }\n}\n\ntemplate <class T>\nvoid BlockADMMSolver<T>::InitializeTransformCache(int n) {\n    TransformCache = new LocalMatrixType* [NumFeaturePartitions];\n    for(int j=0; j<NumFeaturePartitions; j++) {\n        int start = starts[j];\n        int finish = finishes[j];\n        int sj = finish - start  + 1;\n        TransformCache[j]  = new elem::Matrix<double>(sj, n);\n    }\n}\n\n\n// No feature transforms (aka just linear regression).\ntemplate <class T>\nBlockADMMSolver<T>::BlockADMMSolver(\n        const lossfunction* loss,\n        const regularization* regularizer,\n        double lambda, // regularization parameter\n        int NumFeatures,\n        int NumFeaturePartitions) :\n        NumFeatures(NumFeatures),\n            NumFeaturePartitions(NumFeaturePartitions),\n            starts(NumFeaturePartitions), finishes(NumFeaturePartitions),\n            NumThreads(1), RHO(1.0), MAXITER(1000), TOL(0.1) {\n\n    this->loss = const_cast<lossfunction *> (loss);\n    this->regularizer = const_cast<regularization *> (regularizer);\n    this->lambda = lambda;\n    this->NumFeaturePartitions = NumFeaturePartitions;\n    int blksize = int(ceil(double(NumFeatures) / NumFeaturePartitions));\n    for(int i = 0; i < NumFeaturePartitions; i++) {\n        starts[i] = i * blksize;\n        finishes[i] = std::min((i + 1) * blksize, NumFeatures) - 1;\n    }\n    this->ScaleFeatureMaps = false;\n    OwnFeatureMaps = false;\n    InitializeFactorizationCache();\n    CacheTransforms = false;\n}\n\n// Easy interface, aka kernel based.\ntemplate<class T>\ntemplate<typename Kernel, typename MapTypeTag>\nBlockADMMSolver<T>::BlockADMMSolver(skylark::base::context_t& context,\n    const lossfunction* loss,\n    const regularization* regularizer,\n    double lambda, // regularization parameter\n    int NumFeatures,\n    Kernel kernel,\n    MapTypeTag tag,\n    int NumFeaturePartitions) :\n    featureMaps(NumFeaturePartitions),\n    NumFeatures(NumFeatures), NumFeaturePartitions(NumFeaturePartitions),\n    starts(NumFeaturePartitions), finishes(NumFeaturePartitions),\n    NumThreads(1), RHO(1.0), MAXITER(1000), TOL(0.1) {\n\n    this->loss = const_cast<lossfunction *> (loss);\n    this->regularizer = const_cast<regularization *> (regularizer);\n    this->lambda = lambda;\n    int blksize = int(ceil(double(NumFeatures) / NumFeaturePartitions));\n    for(int i = 0; i < NumFeaturePartitions; i++) {\n        starts[i] = i * blksize;\n        finishes[i] = std::min((i + 1) * blksize, NumFeatures) - 1;\n        int sj = finishes[i] - starts[i] + 1;\n        featureMaps[i] =\n            kernel.template create_rft< T, LocalMatrixType >(sj, tag, context);\n    }\n    this->ScaleFeatureMaps = true;\n    OwnFeatureMaps = true;\n    InitializeFactorizationCache();\n    CacheTransforms = false;\n}\n\n// Easy interface, aka kernel based, with quasi-random features.\ntemplate<class T>\ntemplate<typename Kernel>\nBlockADMMSolver<T>::BlockADMMSolver(skylark::base::context_t& context,\n    const lossfunction* loss,\n    const regularization* regularizer,\n    double lambda, // regularization parameter\n    int NumFeatures,\n    Kernel kernel,\n    skylark::ml::quasi_feature_transform_tag tag,\n    int NumFeaturePartitions) :\n    featureMaps(NumFeaturePartitions),\n    NumFeatures(NumFeatures), NumFeaturePartitions(NumFeaturePartitions),\n    starts(NumFeaturePartitions), finishes(NumFeaturePartitions),\n    NumThreads(1), RHO(1.0), MAXITER(1000), TOL(0.1) {\n\n    this->loss = const_cast<lossfunction *> (loss);\n    this->regularizer = const_cast<regularization *> (regularizer);\n    this->lambda = lambda;\n    int blksize = int(ceil(double(NumFeatures) / NumFeaturePartitions));\n    skylark::utility::leaped_halton_sequence_t<double>\n        qmcseq(kernel.qrft_sequence_dim()); // TODO size\n    for(int i = 0; i < NumFeaturePartitions; i++) {\n        starts[i] = i * blksize;\n        finishes[i] = std::min((i + 1) * blksize, NumFeatures) - 1;\n        int sj = finishes[i] - starts[i] + 1;\n        featureMaps[i] =\n            kernel.template create_qrft< T, LocalMatrixType,\n              skylark::utility::leaped_halton_sequence_t>(sj, qmcseq,\n                  starts[i], context);\n    }\n    this->ScaleFeatureMaps = true;\n    OwnFeatureMaps = true;\n    InitializeFactorizationCache();\n    CacheTransforms = false;\n}\n\n// Guru interface\ntemplate <class T>\nBlockADMMSolver<T>::BlockADMMSolver(const lossfunction* loss,\n    const regularization* regularizer,\n    const feature_transform_array_t &featureMaps,\n    double lambda,\n    bool ScaleFeatureMaps) :\n    featureMaps(featureMaps),\n    NumFeaturePartitions(featureMaps.size()),\n    starts(NumFeaturePartitions), finishes(NumFeaturePartitions),\n    NumThreads(1), RHO(1.0), MAXITER(1000), TOL(0.1)  {\n\n    this->loss = const_cast<lossfunction *> (loss);\n    this->regularizer = const_cast<regularization *> (regularizer);\n    this->lambda = lambda;\n    NumFeaturePartitions = featureMaps.size();\n    NumFeatures = 0;\n    for(int i = 0; i < NumFeaturePartitions; i++) {\n        starts[i] = NumFeatures;\n        finishes[i] = NumFeatures + featureMaps[i]->get_S() - 1;\n        NumFeatures += featureMaps[i]->get_S();\n    }\n    this->ScaleFeatureMaps = ScaleFeatureMaps;\n    OwnFeatureMaps = false;\n    InitializeFactorizationCache();\n    CacheTransforms = false;\n}\n\ntemplate <class T>\nBlockADMMSolver<T>::~BlockADMMSolver() {\n    for(int i=0; i  < NumFeaturePartitions; i++) {\n        delete Cache[i];\n        if (OwnFeatureMaps)\n            delete featureMaps[i];\n    }\n    delete[] Cache;\n}\n\n\ntemplate <class T>\nskylark::ml::model_t<T, LocalMatrixType>* BlockADMMSolver<T>::train(T& X, LocalMatrixType& Y, T& Xv, LocalMatrixType& Yv,\n    const boost::mpi::communicator& comm) {\n\n       int rank = comm.rank();\n       int size = comm.size();\n\n       int P = size;\n\n       int ni = skylark::base::Width(X);\n       int d = skylark::base::Height(X);\n       int targets = GetNumTargets(comm, Y);\n\n       skylark::ml::model_t<T, LocalMatrixType>* model =\n           new skylark::ml::model_t<T, LocalMatrixType>(featureMaps,\n               ScaleFeatureMaps, NumFeatures, targets);\n\n       elem::Matrix<double> Wbar;\n       elem::View(Wbar, model->get_coef());\n\n\n       int k = Wbar.Width();\n\n       // number of classes, targets - to generalize\n\n       int D = NumFeatures;\n\n       // exception: check if D = Wbar.Height();\n\n       LocalMatrixType O(k, ni); //uses default Grid\n       elem::MakeZeros(O);\n\n       LocalMatrixType Obar(k, ni); //uses default Grid\n       elem::MakeZeros(Obar);\n\n       LocalMatrixType nu(k, ni); //uses default Grid\n       elem::MakeZeros(nu);\n\n       LocalMatrixType W, mu, Wi, mu_ij, ZtObar_ij;\n\n       if(rank==0) {\n           elem::Zeros(W,  D, k);\n           elem::Zeros(mu, D, k);\n       }\n       elem::Zeros(Wi, D, k);\n       elem::Zeros(mu_ij, D, k);\n       elem::Zeros(ZtObar_ij, D, k);\n\n       int iter = 0;\n\n       // int ni = O.LocalWidth();\n\n       //elem::Matrix<double> x = X.Matrix();\n       //elem::Matrix<double> y = Y.Matrix();\n\n\n       double localloss = loss->evaluate(O, Y);\n       double totalloss, accuracy, obj;\n\n       int Dk = D*k;\n       int nik  = ni*k;\n       int start, finish, sj;\n\n       boost::mpi::timer timer;\n\n       LocalMatrixType sum_o, del_o, wbar_output;\n       elem::Zeros(del_o, k, ni);\n       LocalMatrixType Yp(Yv.Height(), k);\n       LocalMatrixType Yp_labels(Yv.Height(), 1);\n\n       /*LocalMatrixType wbar_tmp;\n       //if (NumThreads > 1)\n\n       elem::Zeros(wbar_tmp, k, ni);*/\n\n       if (CacheTransforms)\n                   InitializeTransformCache(ni);\n\n       SKYLARK_TIMER_INITIALIZE(ITERATIONS_PROFILE);\n       SKYLARK_TIMER_INITIALIZE(COMMUNICATION_PROFILE);\n       SKYLARK_TIMER_INITIALIZE(TRANSFORM_PROFILE);\n       SKYLARK_TIMER_INITIALIZE(ZTRANSFORM_PROFILE);\n       SKYLARK_TIMER_INITIALIZE(ZMULT_PROFILE);\n       SKYLARK_TIMER_INITIALIZE(PROXLOSS_PROFILE);\n       SKYLARK_TIMER_INITIALIZE(BARRIER_PROFILE);\n       SKYLARK_TIMER_INITIALIZE(PREDICTION_PROFILE);\n\n       while(iter<MAXITER) {\n\n           SKYLARK_TIMER_RESTART(ITERATIONS_PROFILE);\n\n           iter++;\n\n           SKYLARK_TIMER_RESTART(COMMUNICATION_PROFILE);\n           broadcast(comm, Wbar.Buffer(), Dk, 0);\n\n           SKYLARK_TIMER_ACCUMULATE(COMMUNICATION_PROFILE)\n\n           // mu_ij = mu_ij - Wbar\n           elem::Axpy(-1.0, Wbar, mu_ij);\n\n           // Obar = Obar - nu\n           elem::Axpy(-1.0, nu, Obar);\n\n           SKYLARK_TIMER_RESTART(PROXLOSS_PROFILE);\n           loss->proxoperator(Obar, 1.0/RHO, Y, O);\n           SKYLARK_TIMER_ACCUMULATE(PROXLOSS_PROFILE);\n\n           if(rank==0) {\n               regularizer->proxoperator(Wbar, lambda/RHO, mu, W);\n           }\n\n           elem::Zeros(sum_o, k, ni);\n           elem::Zeros(wbar_output, k, ni);\n\n           int j;\n           const feature_transform_t* featureMap;\n\n           SKYLARK_TIMER_RESTART(TRANSFORM_PROFILE);\n\n   #       ifdef SKYLARK_HAVE_OPENMP\n   #       pragma omp parallel for if(NumThreads > 1) private(j, start, finish, sj, featureMap) num_threads(NumThreads)\n   #       endif\n           for(j = 0; j < NumFeaturePartitions; j++) {\n               start = starts[j];\n               finish = finishes[j];\n               sj = finish - start  + 1;\n\n               elem::Matrix<double> z(sj, ni);\n\n               if (CacheTransforms && (iter > 1))\n               {\n                    elem::View(z,  *TransformCache[j], 0, 0, sj, ni);\n               }\n               else {\n                   if (featureMaps.size() > 0) {\n                       featureMap = featureMaps[j];\n\n                       SKYLARK_TIMER_RESTART(ZTRANSFORM_PROFILE);\n                       featureMap->apply(X, z, skylark::sketch::columnwise_tag());\n                       SKYLARK_TIMER_ACCUMULATE(ZTRANSFORM_PROFILE)\n\n                       if (ScaleFeatureMaps)\n                           elem::Scal(sqrt(double(sj) / d), z);\n                       } else {\n                          // for linear case just use Z = X no slicing business.\n                          // skylark::base::ColumnView<double>(z, x, );\n                          // ;// VIEWS on SPARSE MATRICES: elem::View(z, x, start, 0, sj, ni);\n                       }\n               }\n\n               elem::Matrix<double> tmp(sj, k);\n               elem::Matrix<double> rhs(sj, k);\n               elem::Matrix<double> o(k, ni);\n\n               if(iter==1) {\n\n                   elem::Matrix<double> Ones;\n                   elem::Ones(Ones, sj, 1);\n                   elem::Gemm(elem::NORMAL, elem::TRANSPOSE, 1.0, z, z, 0.0, *Cache[j]);\n                   Cache[j]->UpdateDiagonal(Ones);\n                   elem::Inverse(*Cache[j]);\n\n\n                   if (CacheTransforms) {\n                       *TransformCache[j] = z;\n                       //DEBUG\n                        std::cout << \"CACHING TRANSFORMS...\" << std::endl;\n                        elem::Write(*TransformCache[0], \"FeatureMatrix.asc\", elem::ASCII, \"\");\n                   }\n               }\n\n               elem::View(tmp, Wbar, start, 0, sj, k); //tmp = Wbar[J,:]\n\n               LocalMatrixType wbar_tmp;\n               elem::Zeros(wbar_tmp, k, ni);\n\n               if (NumThreads > 1) {\n                   elem::Gemm(elem::TRANSPOSE, elem::NORMAL, 1.0, tmp, z, 0.0, wbar_tmp);\n\n   #               ifdef SKYLARK_HAVE_OPENMP\n   #               pragma omp critical\n   #               endif\n                   elem::Axpy(1.0, wbar_tmp, wbar_output);\n               } else\n                   elem::Gemm(elem::TRANSPOSE, elem::NORMAL, 1.0, tmp, z, 1.0, wbar_output);\n\n               rhs = tmp; //rhs = Wbar[J,:]\n               elem::View(tmp, mu_ij, start, 0, sj, k); //tmp = mu_ij[J,:]\n               elem::Axpy(-1.0, tmp, rhs); // rhs = rhs - mu_ij[J,:] = Wbar[J,:] - mu_ij[J,:]\n               elem::View(tmp, ZtObar_ij, start, 0, sj, k);\n               elem::Axpy(+1.0, tmp, rhs); // rhs = rhs + ZtObar_ij[J,:]\n\n               SKYLARK_TIMER_RESTART(ZMULT_PROFILE);\n               elem::Matrix<double> dsum = del_o;\n               elem::Axpy(NumFeaturePartitions + 1.0, nu, dsum);\n               elem::Gemm(elem::NORMAL, elem::TRANSPOSE, 1.0/(NumFeaturePartitions + 1.0), z, dsum, 1.0, rhs); // rhs = rhs + z'*(1/(n+1) * del_o + nu)\n               SKYLARK_TIMER_ACCUMULATE(ZMULT_PROFILE);\n\n               elem::View(tmp, Wi, start, 0, sj, k);\n               elem::Gemm(elem::NORMAL, elem::NORMAL, 1.0, *Cache[j], rhs, 0.0, tmp); // ]tmp = Wi[J,:] = Cache[j]*rhs\n\n               SKYLARK_TIMER_RESTART(ZMULT_PROFILE);\n               elem::Gemm(elem::TRANSPOSE, elem::NORMAL, 1.0, tmp, z, 0.0, o); // o = (z*tmp)' = (z*Wi[J,:])'\n               SKYLARK_TIMER_ACCUMULATE(ZMULT_PROFILE);\n\n               // mu_ij[JJ,:] = mu_ij[JJ,:] + Wi[JJ,:];\n               elem::View(tmp, mu_ij, start, 0, sj, k); //tmp = mu_ij[J,:]\n               elem::View(rhs, Wi, start, 0, sj, k);\n               elem::Axpy(+1.0, rhs, tmp);\n\n               //ZtObar_ij[JJ,:] = numpy.dot(Z.T, o);\n               elem::View(tmp, ZtObar_ij, start, 0, sj, k);\n               elem::Gemm(elem::NORMAL, elem::TRANSPOSE, 1.0, z, o, 0.0, tmp);\n\n               //  sum_o += o\n               if (NumThreads > 1) {\n   #               ifdef SKYLARK_HAVE_OPENMP\n   #               pragma omp critical\n   #               endif\n                   elem::Axpy(1.0, o, sum_o);\n               } else\n                   elem::Axpy(1.0, o, sum_o);\n\n               z.Empty();\n           }\n\n           SKYLARK_TIMER_ACCUMULATE(TRANSFORM_PROFILE);\n\n           localloss = 0.0 ;\n           //  elem::Zeros(o, ni, k);\n           elem::Matrix<double> o(k, ni);\n           elem::MakeZeros(o);\n           elem::Scal(-1.0, sum_o);\n           elem::Axpy(+1.0, O, sum_o); // sum_o = O.Matrix - sum_o\n           del_o = sum_o;\n\n           SKYLARK_TIMER_RESTART(PREDICTION_PROFILE);\n           if (skylark::base::Width(Xv) > 0) {\n               elem::MakeZeros(Yp);\n               elem::MakeZeros(Yp_labels);\n               model->predict(Xv, Yp_labels, Yp, NumThreads);\n               accuracy = model->evaluate(Yv, Yp, comm);\n           }\n           SKYLARK_TIMER_ACCUMULATE(PREDICTION_PROFILE);\n\n           localloss += loss->evaluate(wbar_output, Y);\n\n           SKYLARK_TIMER_RESTART(COMMUNICATION_PROFILE);\n           reduce(comm, localloss, totalloss, std::plus<double>(), 0);\n           SKYLARK_TIMER_ACCUMULATE(COMMUNICATION_PROFILE);\n\n           if(rank == 0) {\n               obj = totalloss + lambda*regularizer->evaluate(Wbar);\n               if (skylark::base::Width(Xv) <=0) {\n                   std::cout << \"iteration \" << iter << \" objective \" << obj << \" time \" << timer.elapsed() << \" seconds\" << std::endl;\n               }\n               else {\n                   std::cout << \"iteration \" << iter << \" objective \" << obj << \" accuracy \" << accuracy << \" time \" << timer.elapsed() << \" seconds\" << std::endl;\n               }\n           }\n\n           elem::Copy(O, Obar);\n           elem::Scal(1.0/(NumFeaturePartitions+1.0), sum_o);\n           elem::Axpy(-1.0, sum_o, Obar);\n\n           elem::Axpy(+1.0, O, nu);\n           elem::Axpy(-1.0, Obar, nu);\n\n\n\n           //Wbar = comm.reduce(Wi)\n           SKYLARK_TIMER_RESTART(COMMUNICATION_PROFILE);\n           boost::mpi::reduce (comm,\n                                   Wi.LockedBuffer(),\n                                   Wi.MemorySize(),\n                                   Wbar.Buffer(),\n                                   std::plus<double>(),\n                                   0);\n           SKYLARK_TIMER_ACCUMULATE(COMMUNICATION_PROFILE);\n\n           if(rank==0) {\n               //Wbar = (Wisum + W)/(P+1)\n               elem::Axpy(1.0, W, Wbar);\n               elem::Scal(1.0/(P+1), Wbar);\n\n               // mu = mu + W - Wbar;\n               elem::Axpy(+1.0, W, mu);\n               elem::Axpy(-1.0, Wbar, mu);\n           }\n\n           SKYLARK_TIMER_RESTART(BARRIER_PROFILE);\n           comm.barrier();\n           SKYLARK_TIMER_ACCUMULATE(BARRIER_PROFILE);\n\n           SKYLARK_TIMER_ACCUMULATE(ITERATIONS_PROFILE);\n       }\n\n       SKYLARK_TIMER_PRINT(ITERATIONS_PROFILE, comm);\n       SKYLARK_TIMER_PRINT(COMMUNICATION_PROFILE, comm);\n       SKYLARK_TIMER_PRINT(TRANSFORM_PROFILE, comm);\n       SKYLARK_TIMER_PRINT(ZTRANSFORM_PROFILE, comm);\n       SKYLARK_TIMER_PRINT(ZMULT_PROFILE, comm);\n       SKYLARK_TIMER_PRINT(PROXLOSS_PROFILE, comm);\n       SKYLARK_TIMER_PRINT(BARRIER_PROFILE, comm);\n       SKYLARK_TIMER_PRINT(PREDICTION_PROFILE, comm);\n\n       return model;\n}\n\n\n#endif /* SKYLARK_BLOCKADDM_HPP */\n", "meta": {"hexsha": "6751dc0b95fb525224d3b2c3f355a1d34c42f2f9", "size": 20155, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ml/BlockADMM.hpp", "max_stars_repo_name": "wangg12/libskylark", "max_stars_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-12T07:26:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-12T07:26:47.000Z", "max_issues_repo_path": "ml/BlockADMM.hpp", "max_issues_repo_name": "cjiyer/libskylark", "max_issues_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ml/BlockADMM.hpp", "max_forks_repo_name": "cjiyer/libskylark", "max_forks_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5119863014, "max_line_length": 163, "alphanum_fraction": 0.5879434384, "num_tokens": 5211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.42497948963654747}}
{"text": "#include \"surface_flow.h\"\n#include \"fractional_laplacian.h\"\n#include \"helpers.h\"\n\n#include \"sobolev/h1.h\"\n#include \"sobolev/h1_lbfgs.h\"\n#include \"sobolev/h2.h\"\n#include \"sobolev/l2_lbfgs.h\"\n#include \"sobolev/bqn_lbfgs.h\"\n#include \"sobolev/hs.h\"\n#include \"sobolev/hs_schur.h\"\n#include \"sobolev/hs_iterative.h\"\n#include \"sobolev/constraints.h\"\n#include \"spatial/convolution.h\"\n\n#include <Eigen/SparseCholesky>\n\nnamespace rsurfaces\n{\n\n    SurfaceFlow::SurfaceFlow(SurfaceEnergy *energy_)\n    {\n        energies.push_back(energy_);\n\n        mesh = energy_->GetMesh();\n        geom = energy_->GetGeom();\n        stepCount = 0;\n\n        origBarycenter = meshBarycenter(geom, mesh);\n        std::cout << \"Original barycenter = \" << origBarycenter << std::endl;\n        RecenterMesh();\n        secretBarycenter = 0;\n        obstacleEnergy = 0;\n\n        verticesMutated = false;\n        lbfgs = 0;\n        bqn_B = 0;\n    }\n\n    void SurfaceFlow::AddAdditionalEnergy(SurfaceEnergy *extraEnergy)\n    {\n        energies.push_back(extraEnergy);\n    }\n\n    void SurfaceFlow::AddObstacleEnergy(SurfaceEnergy *obsEnergy)\n    {\n        obstacleEnergy = obsEnergy;\n        AddAdditionalEnergy(obstacleEnergy);\n    }\n\n\n    void SurfaceFlow::UpdateEnergies()\n    {\n        for (SurfaceEnergy *energy : energies)\n        {\n            energy->Update();\n        }\n    }\n\n    inline double guessStepSize(double gProjNorm)\n    {\n        // double initGuess = (gProjNorm < 1) ? 1.0 / sqrt(gProjNorm) : 1.0 / gProjNorm;\n        double initGuess = 1.0 / gProjNorm;\n        initGuess *= 2;\n        return initGuess;\n    }\n\n    void SurfaceFlow::StepL2Unconstrained()\n    {\n        stepCount++;\n        UpdateEnergies();\n\n        Eigen::MatrixXd l2diff;\n        l2diff.setZero(mesh->nVertices(), 3);\n        AssembleGradients(l2diff);\n\n        double initGuess = guessStepSize(l2diff.norm());\n        LineSearch search(mesh, geom, energies, maxStepSize);\n        search.BacktrackingLineSearch(l2diff, initGuess, 1);\n    }\n\n    void SurfaceFlow::StepL2Projected()\n    {\n        stepCount++;\n        UpdateEnergies();\n\n        Eigen::MatrixXd l2diff;\n        l2diff.setZero(mesh->nVertices(), 3);\n        AssembleGradients(l2diff);\n\n        // Make a saddle matrix with just the identity in the corner\n        std::vector<Triplet> triplets;\n        for (size_t i = 0; i < mesh->nVertices(); i++)\n        {\n            size_t i3 = 3 * i;\n            triplets.push_back(Triplet(i3, i3, 1));\n            triplets.push_back(Triplet(i3 + 1, i3 + 1, 1));\n            triplets.push_back(Triplet(i3 + 2, i3 + 2, 1));\n        }\n\n        size_t nConstraintRows = addConstraintTriplets(triplets, true);\n        size_t dims = 3 * mesh->nVertices() + nConstraintRows;\n\n        Eigen::SparseMatrix<double> A(dims, dims);\n        A.setFromTriplets(triplets.begin(), triplets.end());\n\n        Eigen::VectorXd l2col;\n        l2col.setZero(dims);\n        MatrixUtils::MatrixIntoColumn(l2diff, l2col);\n\n        SparseFactorization factorizedA;\n        factorizedA.Compute(A);\n\n        l2col = factorizedA.Solve(l2col);\n        MatrixUtils::ColumnIntoMatrix(l2col, l2diff);\n\n        double initGuess = guessStepSize(l2diff.norm());\n        LineSearch search(mesh, geom, energies, maxStepSize);\n        search.BacktrackingLineSearch(l2diff, initGuess, 1);\n        \n        // Constraint projection\n        l2col.setZero();\n        size_t curRow = 3 * mesh->nVertices();\n\n        for (Constraints::SimpleProjectorConstraint* spc : simpleConstraints)\n        {\n            spc->addErrorValues(l2col, mesh, geom, curRow);\n            curRow += spc->nRows();\n        }\n\n        for (ConstraintPack pack : schurConstraints)\n        {\n            pack.constraint->addErrorValues(l2col, mesh, geom, curRow);\n            curRow += pack.constraint->nRows();\n        }\n\n        l2col = factorizedA.Solve(l2col);\n\n        VertexIndices inds = mesh->getVertexIndices();\n        for (GCVertex v : mesh->vertices())\n        {\n            size_t base = inds[v] * 3;\n            Vector3 corr{l2col(base), l2col(base + 1), l2col(base + 2)};\n            geom->inputVertexPositions[v] -= corr;\n        }\n\n        geom->refreshQuantities();\n    }\n\n\n    double SurfaceFlow::evaluateEnergy()\n    {\n        return GetEnergyValue(energies);\n    }\n\n    void SurfaceFlow::AssembleGradients(Eigen::MatrixXd &dest)\n    {\n        AddGradientsToMatrix(energies, dest);\n    }\n\n    std::unique_ptr<Hs::HsMetric> SurfaceFlow::GetHsMetric()\n    {\n        std::unique_ptr<Hs::HsMetric> hs(new Hs::HsMetric(energies, obstacleEnergy, simpleConstraints, schurConstraints));\n        hs->disableNearField = disableNearField;\n        return hs;\n    }\n\n    void SurfaceFlow::StepProjectedGradientExact()\n    {\n        long timeStart = currentTimeMilliseconds();\n        stepCount++;\n        std::cout << \"=== Iteration \" << stepCount << \" ===\" << std::endl;\n        std::cout << \"Using Hs projected gradient method...\" << std::endl;\n        UpdateEnergies();\n\n        // Assemble sum of L2 differentials of all energies involved\n        // (including tangent-point energy)\n        Eigen::MatrixXd l2diff, gradientProj;\n        l2diff.setZero(mesh->nVertices(), 3);\n        gradientProj.setZero(mesh->nVertices(), 3);\n\n        AssembleGradients(l2diff);\n        double gNorm = l2diff.norm();\n\n        std::unique_ptr<Hs::HsMetric> hs = GetHsMetric();\n\n        Eigen::MatrixXd M = hs->GetHsMatrixConstrained();\n\n        // Flatten the gradient into a single column\n        Eigen::VectorXd gradientCol;\n        gradientCol.setZero(M.rows());\n\n        // Solve the dense system\n        MatrixUtils::MatrixIntoColumn(l2diff, gradientCol);\n        Eigen::PartialPivLU<Eigen::MatrixXd> solver = M.partialPivLu();\n        gradientCol = solver.solve(gradientCol);\n        MatrixUtils::ColumnIntoMatrix(gradientCol, gradientProj);\n\n        VertexIndices inds = mesh->getVertexIndices();\n\n        double gProjNorm = gradientProj.norm();\n        // Measure dot product of search direction with original gradient direction\n        double gradDot = (l2diff.transpose() * gradientProj).trace() / (gNorm * gProjNorm);\n\n        // Guess a step size\n        // double initGuess = prevStep * 1.25;\n        double initGuess = guessStepSize(gProjNorm);\n\n        std::cout << \"  * Initial step size guess = \" << initGuess << std::endl;\n\n        // Take the step using line search\n        LineSearch search(mesh, geom, energies, maxStepSize);\n        search.BacktrackingLineSearch(gradientProj, initGuess, gradDot);\n        geom->refreshQuantities();\n\n        // Reuse factorized matrix for constraint projection\n        gradientCol.setZero();\n        size_t curRow = 3 * mesh->nVertices();\n\n        for (Constraints::SimpleProjectorConstraint *cons : simpleConstraints)\n        {\n            cons->addErrorValues(gradientCol, mesh, geom, curRow);\n            curRow += cons->nRows();\n        }\n\n        for (const ConstraintPack &c : schurConstraints)\n        {\n            c.constraint->addErrorValues(gradientCol, mesh, geom, curRow);\n            curRow += c.constraint->nRows();\n        }\n\n        gradientCol = solver.solve(gradientCol);\n\n        VertexIndices verts = mesh->getVertexIndices();\n        for (GCVertex v : mesh->vertices())\n        {\n            int base = 3 * verts[v];\n            Vector3 vertCorr{gradientCol(base), gradientCol(base + 1), gradientCol(base + 2)};\n            geom->inputVertexPositions[v] -= vertCorr;\n        }\n\n        long timeEnd = currentTimeMilliseconds();\n        std::cout << \"  Total time for gradient step = \" << (timeEnd - timeStart) << \" ms\" << std::endl;\n    }\n\n    inline void printSolveInfo(size_t numNewton)\n    {\n        if (numNewton > 0)\n        {\n            std::cout << \"  * With \" << numNewton << \" Newton constraint(s), Hs projection will require \"\n                      << (numNewton + 1) << \" linear solves\" << std::endl;\n        }\n        else\n        {\n            std::cout << \"  * With no Newton constraints, Hs projection will require 1 linear solve\" << std::endl;\n        }\n    }\n\n    void SurfaceFlow::StepProjectedGradient()\n    {\n        ptic(\"SurfaceFlow::StepProjectedGradient\");\n        \n        long timeStart = currentTimeMilliseconds();\n        stepCount++;\n        std::cout << \"=== Iteration \" << stepCount << \" ===\" << std::endl;\n        std::cout << \"Using Hs projected gradient method...\" << std::endl;\n        UpdateEnergies();\n\n        // Assemble sum of L2 differentials of all energies involved\n        // (including tangent-point energy)\n        Eigen::MatrixXd l2diff, gradientProj;\n        l2diff.setZero(mesh->nVertices(), 3);\n        gradientProj.setZero(mesh->nVertices(), 3);\n\n        AssembleGradients(l2diff);\n        double gNorm = l2diff.norm();\n\n        std::unique_ptr<Hs::HsMetric> hs = GetHsMetric();\n        hs->allowBarycenterShift = allowBarycenterShift;\n        printSolveInfo(hs->newtonConstraints.size());\n\n        Vector3 shift{0, 0, 0};\n        if (allowBarycenterShift)\n        {\n            shift = averageOfMatrixRows(geom, mesh, l2diff);\n            std::cout << \"Average shift of L2 diff = \" << shift << std::endl;\n        }\n\n        Hs::ProjectViaSchur<Hs::SparseInverse>(*hs, l2diff, gradientProj);\n\n        if (allowBarycenterShift)\n        {\n            addShiftToMatrixRows(gradientProj, mesh->nVertices(), shift);\n        }\n\n        VertexIndices inds = mesh->getVertexIndices();\n\n        double gProjNorm = gradientProj.norm();\n        // Measure dot product of search direction with original gradient direction\n        double gradDot = (l2diff.transpose() * gradientProj).trace() / (gNorm * gProjNorm);\n\n        // Guess a step size\n        // double initGuess = prevStep * 1.25;\n        double initGuess = guessStepSize(gProjNorm);\n\n        std::cout << \"  * Initial step size guess = \" << initGuess << std::endl;\n\n        // Take the step using line search\n        LineSearch search(mesh, geom, energies, maxStepSize);\n        double delta = search.BacktrackingLineSearch(gradientProj, initGuess, gradDot);\n\n        if (schurConstraints.size() > 0)\n        {\n            Hs::ProjectSchurConstraints<Hs::SparseInverse>(*hs, 1);\n        }\n\n        if (allowBarycenterShift)\n        {\n            // The barycenter goes wherever it wants.\n            // Assumes no pin constraints; free barycenter isn't meant to be used with pins.\n        }\n        else\n        {\n            hs->ProjectSimpleConstraints();\n        }\n\n        incrementSchurConstraints();\n        geom->refreshQuantities();\n\n        long timeEnd = currentTimeMilliseconds();\n        std::cout << \"  Total time for gradient step = \" << (timeEnd - timeStart) << \" ms\" << std::endl;\n        \n        ptoc(\"SurfaceFlow::StepProjectedGradient\");\n    }\n\n    void SurfaceFlow::StepProjectedGradientIterative()\n    {\n        ptic(\"SurfaceFlow::StepProjectedGradientIterative\");\n        \n        long timeStart = currentTimeMilliseconds();\n        stepCount++;\n        std::cout << \"=== Iteration \" << stepCount << \" ===\" << std::endl;\n        std::cout << \"Using iterative Hs projected gradient method...\" << std::endl;\n        UpdateEnergies();\n\n        // Assemble sum of L2 differentials of all energies involved\n        // (including tangent-point energy)\n        Eigen::MatrixXd l2diff, gradientProj;\n        l2diff.setZero(mesh->nVertices(), 3);\n        gradientProj.setZero(mesh->nVertices(), 3);\n        AssembleGradients(l2diff);\n        double gNorm = l2diff.norm();\n\n        std::unique_ptr<Hs::HsMetric> hs = GetHsMetric();\n        printSolveInfo(hs->newtonConstraints.size());\n\n        Vector3 shift{0, 0, 0};\n        if (allowBarycenterShift)\n        {\n            shift = averageOfMatrixRows(geom, mesh, l2diff);\n            std::cout << \"Average shift of L2 diff = \" << shift << std::endl;\n        }\n\n        Hs::ProjectConstrainedHsIterativeMat(*hs, l2diff, gradientProj);\n\n        if (allowBarycenterShift)\n        {\n            addShiftToMatrixRows(gradientProj, mesh->nVertices(), shift);\n        }\n\n        VertexIndices inds = mesh->getVertexIndices();\n\n        double gProjNorm = gradientProj.norm();\n        // Measure dot product of search direction with original gradient direction\n        double gradDot = (l2diff.transpose() * gradientProj).trace() / (gNorm * gProjNorm);\n\n        // Guess a step size\n        // double initGuess = prevStep * 1.25;\n        double initGuess = guessStepSize(gProjNorm);\n\n        std::cout << \"  * Initial step size guess = \" << initGuess << std::endl;\n\n        // Take the step using line search\n        LineSearch search(mesh, geom, energies, maxStepSize);\n        double delta = search.BacktrackingLineSearch(gradientProj, initGuess, gradDot);\n\n        // Constraint projection\n        if (schurConstraints.size() > 0)\n        {\n            // hs->ResetSchurComplement();\n            std::cout << \"  Projecting Newton constraints...\" << std::endl;\n            Hs::ProjectSchurConstraints<Hs::IterativeInverse>(*hs, 1);\n        }\n        if (allowBarycenterShift)\n        {\n            // The barycenter goes wherever it wants.\n            // Assumes no pin constraints; free barycenter isn't meant to be used with pins.\n        }\n        else\n        {\n            hs->ProjectSimpleConstraints();\n        }\n\n        incrementSchurConstraints();\n        geom->refreshQuantities();\n\n        long timeEnd = currentTimeMilliseconds();\n        std::cout << \"  Total time for gradient step = \" << (timeEnd - timeStart) << \" ms\" << std::endl;\n        \n        ptoc(\"SurfaceFlow::StepProjectedGradientIterative\");\n    }\n\n    size_t SurfaceFlow::addConstraintTriplets(std::vector<Triplet> &triplets, bool includeSchur)\n    {\n        size_t curRow = 3 * mesh->nVertices();\n        size_t nConstraintRows = 0;\n        for (Constraints::SimpleProjectorConstraint *spc : simpleConstraints)\n        {\n            Constraints::addTripletsToSymmetric(*spc, triplets, mesh, geom, curRow);\n            size_t nr = spc->nRows();\n            curRow += nr;\n            nConstraintRows += nr;\n        }\n\n        if (includeSchur)\n        {\n            for (ConstraintPack &c : schurConstraints)\n            {\n                Constraints::addTripletsToSymmetric(*c.constraint, triplets, mesh, geom, curRow);\n                size_t nr = c.constraint->nRows();\n                curRow += nr;\n                nConstraintRows += nr;\n            }\n        }\n        return nConstraintRows;\n    }\n\n    void SurfaceFlow::prefactorConstrainedLaplacian(SparseFactorization &factored, bool includeSchur)\n    {\n        Eigen::SparseMatrix<double> L;\n        prefactorConstrainedLaplacian(L, factored, includeSchur);\n    }\n\n    void SurfaceFlow::prefactorConstrainedLaplacian(Eigen::SparseMatrix<double> &L, SparseFactorization &factored, bool includeSchur)\n    {\n        // Assemble triplets for the Laplacian\n        std::vector<Triplet> h1Triplets, h1Triplets3x;\n        H1::getTriplets(h1Triplets, mesh, geom, 1e-10);\n        MatrixUtils::TripleTriplets(h1Triplets, h1Triplets3x);\n        // Add constraint rows at bottom\n        size_t nConstraintRows = addConstraintTriplets(h1Triplets3x, includeSchur);\n        size_t dims = 3 * mesh->nVertices() + nConstraintRows;\n\n        // Builds and factorize the Laplacian\n        L.resize(dims, dims);\n        L.setFromTriplets(h1Triplets3x.begin(), h1Triplets3x.end());\n        factored.Compute(L);\n    }\n\n    void SurfaceFlow::StepH1ProjGrad()\n    {\n        long timeStart = currentTimeMilliseconds();\n        stepCount++;\n        std::cout << \"=== Iteration \" << stepCount << \" ===\" << std::endl;\n        std::cout << \"Using H1 projected gradient method...\" << std::endl;\n        UpdateEnergies();\n\n        // Assemble sum of L2 differentials of all energies involved\n        // (including tangent-point energy)\n        Eigen::MatrixXd l2diff;\n        l2diff.setZero(mesh->nVertices(), 3);\n        AssembleGradients(l2diff);\n        double gNorm = l2diff.norm();\n\n        Vector3 shift{0, 0, 0};\n        if (allowBarycenterShift)\n        {\n            shift = averageOfMatrixRows(geom, mesh, l2diff);\n            std::cout << \"Average shift of L2 diff = \" << shift << std::endl;\n        }\n\n        SparseFactorization factorizedL;\n        prefactorConstrainedLaplacian(factorizedL, true);\n        size_t dims = factorizedL.nRows;\n        std::cout << \"Prefactorized\" << std::endl;\n\n        // Project the H1 gradient\n        Eigen::VectorXd gradientVec;\n        gradientVec.setZero(dims);\n        MatrixUtils::MatrixIntoColumn(l2diff, gradientVec);\n\n        gradientVec = factorizedL.Solve(gradientVec);\n        Eigen::MatrixXd gradientProj;\n        gradientProj.setZero(l2diff.rows(), l2diff.cols());\n        MatrixUtils::ColumnIntoMatrix(gradientVec, gradientProj);\n\n        if (allowBarycenterShift)\n        {\n            addShiftToMatrixRows(gradientProj, mesh->nVertices(), shift);\n        }\n\n        double gProjNorm = gradientProj.norm();\n        // Measure dot product of search direction with original gradient direction\n        double gradDot = (l2diff.transpose() * gradientProj).trace() / (gNorm * gProjNorm);\n        // Guess a step size\n        double initGuess = guessStepSize(gProjNorm);\n        std::cout << \"  * Initial step size guess = \" << initGuess << std::endl;\n        // Take the step using line search\n        LineSearch search(mesh, geom, energies, maxStepSize);\n        double delta = search.BacktrackingLineSearch(gradientProj, initGuess, gradDot);\n\n        // Do corrective constraint projection by reusing the H1 metric\n        H1::ProjectConstraints(mesh, geom, simpleConstraints, schurConstraints, factorizedL, 1);\n\n        incrementSchurConstraints();\n        geom->refreshQuantities();\n\n        long timeEnd = currentTimeMilliseconds();\n        std::cout << \"  Total time for gradient step = \" << (timeEnd - timeStart) << \" ms\" << std::endl;\n    }\n\n    void savePositions(MeshPtr &mesh, GeomPtr &geom, Eigen::MatrixXd &positions)\n    {\n        positions.setZero(mesh->nVertices(), 3);\n\n        VertexIndices inds = mesh->getVertexIndices();\n\n        for (GCVertex v : mesh->vertices())\n        {\n            Vector3 pos = geom->inputVertexPositions[v];\n            size_t i = inds[v];\n            positions(i, 0) = pos.x;\n            positions(i, 1) = pos.y;\n            positions(i, 2) = pos.z;\n        }\n    }\n\n    void SurfaceFlow::StepAQP(double invKappa)\n    {\n        long timeStart = currentTimeMilliseconds();\n        if (stepCount == 0 || verticesMutated)\n        {\n            // Reset Nesterov memory of previous step\n            savePositions(mesh, geom, prevPositions1);\n            savePositions(mesh, geom, prevPositions2);\n        }\n        else\n        {\n            double theta = (1 - sqrt(invKappa)) / (1 + sqrt(invKappa));\n            // 1. Nesterov step\n            Eigen::MatrixXd y_n = (1 + theta) * prevPositions1 - theta * prevPositions2;\n            for (GCVertex v : mesh->vertices())\n            {\n                Vector3 pos = MatrixUtils::GetRowAsVector3(y_n, v.getIndex());\n                geom->inputVertexPositions[v] = pos;\n            }\n            geom->refreshQuantities();\n        }\n        stepCount++;\n\n        // 2. H1 gradient step following the Nesterov step\n        std::cout << \"=== Iteration \" << stepCount << \" ===\" << std::endl;\n        std::cout << \"Using AQP...\" << std::endl;\n        UpdateEnergies();\n\n        // Assemble sum of L2 differentials of all energies involved\n        // (including tangent-point energy)\n        Eigen::MatrixXd l2diff;\n        l2diff.setZero(mesh->nVertices(), 3);\n        AssembleGradients(l2diff);\n        double gNorm = l2diff.norm();\n\n        Vector3 shift{0, 0, 0};\n        if (allowBarycenterShift)\n        {\n            shift = averageOfMatrixRows(geom, mesh, l2diff);\n            std::cout << \"Average shift of L2 diff = \" << shift << std::endl;\n        }\n\n        SparseFactorization factorizedL;\n        // Only use \"simple\" positional constraints (Nesterov would break hard constraints anyway)\n        prefactorConstrainedLaplacian(factorizedL, false);\n        size_t dims = factorizedL.nRows;\n\n        // Project the H1 gradient\n        Eigen::VectorXd gradientVec;\n        gradientVec.setZero(dims);\n        MatrixUtils::MatrixIntoColumn(l2diff, gradientVec);\n\n        gradientVec = factorizedL.Solve(gradientVec);\n        Eigen::MatrixXd gradientProj;\n        gradientProj.setZero(l2diff.rows(), l2diff.cols());\n        MatrixUtils::ColumnIntoMatrix(gradientVec, gradientProj);\n\n        if (allowBarycenterShift)\n        {\n            addShiftToMatrixRows(gradientProj, mesh->nVertices(), shift);\n        }\n\n        double gProjNorm = gradientProj.norm();\n        // Measure dot product of search direction with original gradient direction\n        double gradDot = (l2diff.transpose() * gradientProj).trace() / (gNorm * gProjNorm);\n        // Guess a step size\n        double initGuess = guessStepSize(gProjNorm);\n        std::cout << \"  * Initial step size guess = \" << initGuess << std::endl;\n        // Take the step using line search\n        LineSearch search(mesh, geom, energies, maxStepSize);\n        double delta = search.BacktrackingLineSearch(gradientProj, initGuess, gradDot);\n\n        // Make sure pins don't drift\n        for (Constraints::SimpleProjectorConstraint *spc : simpleConstraints)\n        {\n            spc->ProjectConstraint(mesh, geom);\n        }\n        // Save previous positions\n        prevPositions2 = prevPositions1;\n        savePositions(mesh, geom, prevPositions1);\n        geom->refreshQuantities();\n\n        long timeEnd = currentTimeMilliseconds();\n        std::cout << \"  Total time for gradient step = \" << (timeEnd - timeStart) << \" ms\" << std::endl;\n    }\n\n    void SurfaceFlow::StepH1LBFGS()\n    {\n        long timeStart = currentTimeMilliseconds();\n\n        stepCount++;\n        std::cout << \"=== Iteration \" << stepCount << \" ===\" << std::endl;\n        std::cout << \"Using H1 L-BFGS...\" << std::endl;\n\n        if (!lbfgs)\n        {\n            lbfgs = new H1_LBFGS(20, simpleConstraints);\n        }\n\n        if (verticesMutated)\n        {\n            std::cout << \"  * Vertices were mutated; resetting memory\" << std::endl;\n            lbfgs->ResetMemory();\n        }\n\n        UpdateEnergies();\n        // Assemble sum of L2 differentials of all energies involved\n        // (including tangent-point energy)\n        Eigen::MatrixXd l2diff, projected, positions;\n        l2diff.setZero(mesh->nVertices(), 3);\n        positions.setZero(mesh->nVertices(), 3);\n        projected.setZero(mesh->nVertices(), 3);\n        AssembleGradients(l2diff);\n        double gNorm = l2diff.norm();\n\n        Eigen::VectorXd l2diffvec(3 * mesh->nVertices());\n        MatrixUtils::MatrixIntoColumn(l2diff, l2diffvec);\n\n        savePositions(mesh, geom, positions);\n        Eigen::VectorXd posvec(3 * mesh->nVertices());\n        MatrixUtils::MatrixIntoColumn(positions, posvec);\n\n        // Do the L-BFGS update with current position and gradient\n        lbfgs->SetUpInnerProduct(mesh, geom);\n        lbfgs->UpdateDirection(posvec, l2diffvec);\n        double gProjNorm = lbfgs->direction().norm();\n\n        MatrixUtils::ColumnIntoMatrix(lbfgs->direction(), projected);\n        double gradDot = (l2diffvec.dot(lbfgs->direction())) / (gNorm * gProjNorm);\n        std::cout << \"  * Dot product = \" << gradDot << std::endl;\n\n        LineSearch search(mesh, geom, energies, maxStepSize);\n        // Take the step using line search\n        double initGuess = guessStepSize(gProjNorm);\n        double delta = search.BacktrackingLineSearch(projected, initGuess, fmax(0, gradDot));\n\n        if (gradDot < 0)\n        {\n            std::cout << \"  * Negative dot product; resetting memory\" << std::endl;\n            lbfgs->ResetMemory();\n        }\n\n        // Make sure pins don't drift\n        for (Constraints::SimpleProjectorConstraint *spc : simpleConstraints)\n        {\n            spc->ProjectConstraint(mesh, geom);\n        }\n        geom->refreshQuantities();\n\n        long timeEnd = currentTimeMilliseconds();\n        std::cout << \"  Total time for gradient step = \" << (timeEnd - timeStart) << \" ms\" << std::endl;\n    }\n\n    void SurfaceFlow::StepBQN()\n    {\n        long timeStart = currentTimeMilliseconds();\n\n        stepCount++;\n        std::cout << \"=== Iteration \" << stepCount << \" ===\" << std::endl;\n        std::cout << \"Using blended L-BFGS (BQN)...\" << std::endl;\n\n        if (!lbfgs)\n        {\n            // B = (total area) ^ (2(d-1) / d) for d = 3\n            // (equation 13 of BCQN / Zhu et al.)\n            double b = pow(totalArea(geom, mesh), 4.0 / 3.0);\n            lbfgs = new BQN_LBFGS(20, simpleConstraints, b);\n        }\n\n        if (verticesMutated)\n        {\n            std::cout << \"  * Vertices were mutated; resetting memory\" << std::endl;\n            lbfgs->ResetMemory();\n        }\n\n        UpdateEnergies();\n        // Assemble sum of L2 differentials of all energies involved\n        // (including tangent-point energy)\n        Eigen::MatrixXd l2diff, projected, positions;\n        l2diff.setZero(mesh->nVertices(), 3);\n        positions.setZero(mesh->nVertices(), 3);\n        projected.setZero(mesh->nVertices(), 3);\n        AssembleGradients(l2diff);\n        double gNorm = l2diff.norm();\n\n        Eigen::VectorXd l2diffvec(3 * mesh->nVertices());\n        MatrixUtils::MatrixIntoColumn(l2diff, l2diffvec);\n\n        savePositions(mesh, geom, positions);\n        Eigen::VectorXd posvec(3 * mesh->nVertices());\n        MatrixUtils::MatrixIntoColumn(positions, posvec);\n\n        // Do the L-BFGS update with current position and gradient\n        lbfgs->SetUpInnerProduct(mesh, geom);\n        lbfgs->UpdateDirection(posvec, l2diffvec);\n        double gProjNorm = lbfgs->direction().norm();\n\n        MatrixUtils::ColumnIntoMatrix(lbfgs->direction(), projected);\n        double gradDot = (l2diffvec.dot(lbfgs->direction())) / (gNorm * gProjNorm);\n        std::cout << \"  * Dot product = \" << gradDot << std::endl;\n\n        LineSearch search(mesh, geom, energies, maxStepSize);\n        // Take the step using line search\n        double initGuess = guessStepSize(gProjNorm);\n        double delta = search.BacktrackingLineSearch(projected, initGuess, fmax(0, gradDot));\n\n        if (gradDot < 0)\n        {\n            std::cout << \"  * Negative dot product; resetting memory\" << std::endl;\n            lbfgs->ResetMemory();\n        }\n\n        // Make sure pins don't drift\n        for (Constraints::SimpleProjectorConstraint *spc : simpleConstraints)\n        {\n            spc->ProjectConstraint(mesh, geom);\n        }\n        geom->refreshQuantities();\n\n        long timeEnd = currentTimeMilliseconds();\n        std::cout << \"  Total time for gradient step = \" << (timeEnd - timeStart) << \" ms\" << std::endl;\n    }\n\n    void SurfaceFlow::StepH2Projected()\n    {\n        long timeStart = currentTimeMilliseconds();\n        stepCount++;\n        std::cout << \"=== Iteration \" << stepCount << \" ===\" << std::endl;\n        std::cout << \"Using H2 projected gradient...\" << std::endl;\n        UpdateEnergies();\n\n        // Assemble sum of L2 differentials of all energies involved\n        // (including tangent-point energy)\n        Eigen::MatrixXd l2diff;\n        l2diff.setZero(mesh->nVertices(), 3);\n        AssembleGradients(l2diff);\n        double gNorm = l2diff.norm();\n\n        // Get bi-Laplacian triplets\n        std::vector<Triplet> biTriplets, biTriplets3x;\n        H2::getTriplets(biTriplets, mesh, geom, 0);\n        MatrixUtils::TripleTriplets(biTriplets, biTriplets3x);\n        size_t nConstraintRows = addConstraintTriplets(biTriplets3x, true);\n\n        // Build tripled matrix\n        size_t dims = 3 * mesh->nVertices() + nConstraintRows;\n        Eigen::SparseMatrix<double> biLaplacian(dims, dims);\n        biLaplacian.setFromTriplets(biTriplets3x.begin(), biTriplets3x.end()); \n\n        // Pre-factorize it\n        SparseFactorization factorizedL;\n        factorizedL.Compute(biLaplacian);\n\n        // Reshape the gradient into a column\n        Eigen::VectorXd gradientVec;\n        gradientVec.setZero(dims);\n        MatrixUtils::MatrixIntoColumn(l2diff, gradientVec);\n\n        // Solve for the H2 gradient\n        gradientVec = factorizedL.Solve(gradientVec);\n        Eigen::MatrixXd gradientProj;\n        gradientProj.setZero(l2diff.rows(), l2diff.cols());\n        MatrixUtils::ColumnIntoMatrix(gradientVec, gradientProj);\n\n        // Take the step using line search\n        double gProjNorm = gradientProj.norm();\n        double gradDot = (l2diff.transpose() * gradientProj).trace() / (gNorm * gProjNorm);\n        double initGuess = guessStepSize(gProjNorm);\n        std::cout << \"  * Initial step size guess = \" << initGuess << std::endl;\n        LineSearch search(mesh, geom, energies, maxStepSize);\n        double delta = search.BacktrackingLineSearch(gradientProj, initGuess, gradDot);\n\n        // Do corrective constraint projection by reusing the metric\n        H1::ProjectConstraints(mesh, geom, simpleConstraints, schurConstraints, factorizedL, 1);\n\n        incrementSchurConstraints();\n        geom->refreshQuantities();\n\n        long timeEnd = currentTimeMilliseconds();\n        std::cout << \"  Total time for gradient step = \" << (timeEnd - timeStart) << \" ms\" << std::endl;\n    }\n\n\n    void SurfaceFlow::RecenterMesh()\n    {\n        Vector3 center = meshBarycenter(geom, mesh);\n        translateMesh(geom, mesh, origBarycenter - center);\n    }\n\n    void SurfaceFlow::ResetAllConstraints()\n    {\n        for (ConstraintPack &p : schurConstraints)\n        {\n            p.constraint->ResetFunction(mesh, geom);\n        }\n        for (Constraints::SimpleProjectorConstraint *c : simpleConstraints)\n        {\n            c->ResetFunction(mesh, geom);\n        }\n    }\n\n    void SurfaceFlow::ResetAllPotentials()\n    {\n        for (SurfaceEnergy *energy : energies)\n        {\n            energy->ResetTargets();\n        }\n    }\n\n    SurfaceEnergy *SurfaceFlow::BaseEnergy()\n    {\n        return energies[0];\n    }\n\n} // namespace rsurfaces\n", "meta": {"hexsha": "a82832a5e9bc5fb2db13fefd10b9c5b0e63d1fc3", "size": 29983, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/surface_flow.cpp", "max_stars_repo_name": "Conrekatsu/repulsive-surfaces", "max_stars_repo_head_hexsha": "74d6a16e6ca55c8296fa5a49757c2318bea62a84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2021-12-13T09:58:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:03:01.000Z", "max_issues_repo_path": "src/surface_flow.cpp", "max_issues_repo_name": "Conrekatsu/repulsive-surfaces", "max_issues_repo_head_hexsha": "74d6a16e6ca55c8296fa5a49757c2318bea62a84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/surface_flow.cpp", "max_forks_repo_name": "Conrekatsu/repulsive-surfaces", "max_forks_repo_head_hexsha": "74d6a16e6ca55c8296fa5a49757c2318bea62a84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-02-25T06:46:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T05:46:53.000Z", "avg_line_length": 35.1500586166, "max_line_length": 133, "alphanum_fraction": 0.6032751893, "num_tokens": 7352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.42488718665941977}}
{"text": "// Std includes\n#include <iostream> // cout, endl\n#include <vector>\n#include <memory> // shared_ptr\n#include <map>\n// Thirdparties includes\n#include <Eigen/Dense>\n// Lib includes\n#include \"v0l/bin/file_data.h\"\n#include \"m0sh/uniform.h\"\n#include \"m0sh/structured_sub.h\"\n#include \"fl0p/unstationary.h\"\n\nconst unsigned int DIM = 3;\n\nusing TypeScalar = double;\nusing TypeVectorScalar = Eigen::Matrix<TypeScalar, 1, 1>;\nusing TypeVector = Eigen::Matrix<TypeScalar, DIM, 1>;\nusing TypeMatrix = Eigen::Matrix<TypeScalar, DIM, DIM>;\ntemplate<typename... Args>\nusing TypeRef = Eigen::Ref<Args...>;\n\ntemplate<typename ...Args>\nusing TypeContainer = std::vector<Args...>;\nusing TypeMesh = m0sh::Uniform<TypeVector, TypeRef, TypeContainer>;\nusing TypeMeshSub = m0sh::StructuredSub<TypeVector, TypeRef, TypeContainer>;\nusing TypeTimeMesh = m0sh::Uniform<TypeVectorScalar, TypeRef, TypeContainer>;\nusing TypeTimeMeshSub = m0sh::StructuredSub<TypeVectorScalar, TypeRef, TypeContainer>;\nusing TypeFlow = fl0w::fl0p::Unstationary<TypeVector, TypeMatrix, TypeRef, TypeMesh, TypeContainer, TypeMeshSub, TypeTimeMesh, TypeTimeMeshSub, TypeVectorScalar, v0l::FileData>;\n\nvoid print(const TypeFlow& flow, const TypeVector& x, const TypeScalar& t) {\n    std::cout << std::endl;\n    std::cout << \"flow.getVelocity(\" << x.transpose() << \", \" << t << \") = \\n\" << flow.getVelocity(x, t).transpose() << std::endl;\n    //std::cout << \"flow.getJacobian(\" << x.transpose() << \", \" << t << \") = \\n\" << flow.getJacobian(x, t) << std::endl;\n    //std::cout << \"flow.getVorticity(\" << x.transpose() << \", \" << t << \") = \\n\" << flow.getVorticity(x, t).transpose() << std::endl;\n    //std::cout << \"flow.getAcceleration(\" << x.transpose() << \", \" << t << \") = \\n\" << flow.getAcceleration(x, t).transpose() << std::endl;\n    std::cout << std::endl;\n}\n\nint main () {\n    std::vector<std::vector<v0l::FileData<float>>> velocity(2);\n    for(std::size_t i = 0; i < velocity.size(); i++) {\n        std::string fileName = std::string(\"../data/v050\") + std::to_string(i) + \".vtk\";\n        velocity[i].emplace_back(fileName, 0);\n        velocity[i].emplace_back(fileName, 1);\n        velocity[i].emplace_back(fileName, 2);\n    }\n    // mesh data\n    // // create lengths\n    TypeVector origin;\n    std::vector<double> lengths;\n    for(std::size_t i = 0; i < velocity[0][0].meta.dimensions.size(); i++) {\n        lengths.push_back(velocity[0][0].meta.dimensions[i] * velocity[0][0].meta.spacing[i]);\n        origin[i] = velocity[0][0].meta.origin[i];\n    }\n    // // flow\n    std::cout << \"building flow...\" << std::endl;\n    TypeFlow flow(std::make_shared<TypeMesh>(velocity[0][0].meta.dimensions, lengths, origin, TypeContainer<bool>(DIM, true)), velocity, 1, std::make_shared<TypeTimeMesh>(std::vector<std::size_t>(1, 1), std::vector<double>(1, 0.02), TypeVectorScalar(0.0), std::vector<bool>(1, false)), 1);\n    std::cout << \"flow built !\" << std::endl;\n    // print\n    print(flow, TypeVector({-0.5, -0.5, -0.5}), 0.0);\n    print(flow, TypeVector({0.0, 0.0, 0.0}), 0.0);\n    print(flow, TypeVector({0.5, 0.5, 0.5}), 0.0);\n    print(flow, TypeVector({-0.5, -0.5, -0.5}), 0.01);\n    print(flow, TypeVector({0.0, 0.0, 0.0}), 0.01);\n    print(flow, TypeVector({0.5, 0.5, 0.5}), 0.01);\n}\n", "meta": {"hexsha": "c30dca495c942d2bb52ded2ce64caaceec538e79", "size": 3241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/v0l/unstationary/main.cpp", "max_stars_repo_name": "C0PEP0D/fl0p", "max_stars_repo_head_hexsha": "d65b1babfaec8b996474e42362f6819580ad3538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/v0l/unstationary/main.cpp", "max_issues_repo_name": "C0PEP0D/fl0p", "max_issues_repo_head_hexsha": "d65b1babfaec8b996474e42362f6819580ad3538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/v0l/unstationary/main.cpp", "max_forks_repo_name": "C0PEP0D/fl0p", "max_forks_repo_head_hexsha": "d65b1babfaec8b996474e42362f6819580ad3538", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6617647059, "max_line_length": 289, "alphanum_fraction": 0.6414686825, "num_tokens": 998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.42487871743630595}}
{"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 1999 - 2021 by the deal.II authors\n *\n * This file is part of the deal.II library.\n *\n * The deal.II library is free software; you can use it, redistribute\n * it, and/or modify it under the terms of the GNU Lesser General\n * Public License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * The full text of the license can be found in the file LICENSE.md at\n * the top level directory of deal.II.\n *\n * ---------------------------------------------------------------------\n *\n * <br>\n *\n * <i>\n * This program was contributed by Peter Munch. This work and the required\n * generalizations of the internal data structures of deal.II form part of the\n * project \"Virtual Materials Design\" funded by the Helmholtz Association of\n * German Research Centres.\n * </i>\n *\n *\n * <a name=\"Intro\"></a>\n * <h1>Introduction</h1>\n *\n * <h3>Motivation</h3>\n *\n * The motivation for using simplex meshes (as done in step-3simplex) is\n * straightforward: many freely available mesh-generation tools are very good in\n * creating good-quality meshes in such a format, while they struggle with\n * hex-only meshes. Hex-only meshes, on the other hand, are characterized with\n * better numerical properties (e.g., less degrees of freedom for the same\n * degree of accuracy and possibly better performance since the tensor-product\n * structure can be exploited) and are, as a consequence, the natural choice for\n * rather simple geometries and for meshes described by a coarse mesh with a few\n * cells (like a hyperball) and obtained in their final form through iterative\n * local refinement.\n *\n * Mixed meshes try to combine the best of both worlds by partitioning the\n * geometry in parts that can be easily meshed by hypercube cells\n * (quadrilaterals in 2D, hexahedrons in 3D) and in parts that can not be meshed\n * easily, requiring simplices (triangles in 2D, tetrahedrons in 3D). Since one\n * assumes that the region requiring simplices is rather small compared to the\n * rest of the domain where more efficient and accurate methods can be applied,\n * one can expect that the overall efficiency is hardly impacted by such an\n * approach.\n *\n * One should note that in 3D, one also needs a transition region between\n * hypercube and simplex regions. Here, one can use wedges/prisms and/or\n * pyramids.\n *\n *\n * <h3>Working with mixed meshes</h3>\n *\n * <i>\n * In the following, we concentrate, for the sake of simplicity, on 2D meshes:\n * they can only contain triangles and quadrilaterals. However, as detailed in\n * the outlook, an extension of the presented approach to the 3D case is\n * straightforward.\n * </i>\n *\n * The complexity of working with mixed meshes in 2D results from the fact\n * that it contains of two\n * types of geometrical objects: quadrilaterals and triangles. How to deal with\n * quadrilaterals, we have discussed in step-3: we selected an appropriate\n * finite element, quadrature rule and mapping object, e.g., FE_Q, QGauss, and\n * MappingFE (initialized with FE_Q). For simplex meshes, we selected in\n * step-3simplex FE_SimplexP, QGaussSimplex, and MappingFE (intialized with\n * FE_SimplexP).\n *\n * For mixed meshes, we need multiple finite elements, quadrature rules, and\n * mapping objects (one set for triangles and one set for quadrilaterals) in the\n * same program. To ease the work with the multitude of objects (in particular\n * in 3D, we need at least four of each), you can collect the objects and group\n * them together in hp::FECollection, hp::QCollection, and\n * hp::MappingCollection.\n *\n * Just like in the context of finite elements, quadrature rules, and mapping\n * objects, we need multiple FEValues objects: the collection of FEValues is\n * called hp::FEValues. It returns the FEValues object needed for the current\n * cell via the method hp::FEValues::get_present_fe_values().\n *\n * For hp::FEValues, to be able to select the right finite element/quadrature\n * rule/ mapping object set, it queries the active_fe_index of the given cell\n * during hp::FEValues::reinit(). The indices have to be set - as shown below -\n * before calling DoFHandler::distribute_dofs() by the user.\n *\n * <i>\n * The namespace name of hp::FECollection, hp::QCollection,\n * hp::MappingCollection, and hp::FEValues indicates that these classes have not\n * been written for mixed meshes in the first place, but for problems where each\n * (hypercube) cell could have a different type of finite element assigned - in\n * the simplest case, all cells have the same element type but different\n * polynomial degrees p (the reason for the letter \"p\" in \"hp\"). An extension of\n * this infrastructure to work not only on different element types but also on\n * different geometrical objects was a natural choice. For further details on\n * hp-methods, see step-27.\n * </i>\n *\n * <h3>Mesh generation</h3>\n *\n * Just like in step-3simplex, we read an externally generated mesh. For this\n * tutorial, we have created the mesh (square with width and height of one;\n * quadrilaterals on the left half and triangles on the right half) with Gmsh\n * with the following journal file \"box_2D_mixed.geo\":\n *\n * @code\n * Rectangle(1) = {0.0, 0, 0, 0.5, 1, 0};\n * Rectangle(2) = {0.5, 0, 0, 0.5, 1, 0};\n * Recombine Surface{1};\n * Physical Surface(\"All\") = {1, 2};\n * Mesh 2;\n * Coherence Mesh;\n * Save \"box_2D_mixed.msh\";\n * @endcode\n *\n * The journal file can be processed by Gmsh generating the actual mesh with the\n * ending \".msh\":\n *\n * @code\n * gmsh box_2D_mixed.geo\n * @endcode\n *\n * We have included in the tutorial folder both the journal file and the mesh\n * file in the event that one does not have access to Gmsh.\n *\n */\n\n\n// @sect3{Include files}\n\n// Include files, as used in step-3:\n#include <deal.II/base/function.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n\n#include <deal.II/grid/tria.h>\n\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/vector.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <fstream>\n#include <iostream>\n\n// Include files, as added in step-3simplex:\n#include <deal.II/base/quadrature_lib.h>\n\n#include <deal.II/fe/fe_simplex_p.h>\n#include <deal.II/fe/mapping_fe.h>\n\n#include <deal.II/grid/grid_in.h>\n\n// Include files that we need in this tutorial to be able to deal with\n// collections of finite elements, quadrature rules, mapping objects, and\n// FEValues.\n#include <deal.II/hp/fe_collection.h>\n#include <deal.II/hp/fe_values.h>\n#include <deal.II/hp/mapping_collection.h>\n#include <deal.II/hp/q_collection.h>\n\nusing namespace dealii;\n\n// @sect3{The <code>Step3</code> class}\n//\n// This is the main class of the tutorial. Since it is very similar to the\n// version from step-3 and step-3simplex, we will only point out and explain\n// the relevant differences that allow to perform simulations on mixed meshes.\n\nclass Step3\n{\npublic:\n  Step3();\n\n  void run();\n\nprivate:\n  void make_grid();\n  void setup_system();\n  void assemble_system();\n  void solve();\n  void output_results() const;\n\n  Triangulation<2> triangulation;\n\n  // As already explained, we are not working with mapping objects, finite\n  // elements, and quadrature rules directly but with collections of them.\n  const hp::MappingCollection<2> mapping;\n  const hp::FECollection<2>      fe;\n  const hp::QCollection<2>       quadrature_formula;\n\n  DoFHandler<2> dof_handler;\n\n  SparsityPattern      sparsity_pattern;\n  SparseMatrix<double> system_matrix;\n\n  Vector<double> solution;\n  Vector<double> system_rhs;\n};\n\n\n// @sect4{Step3::Step3}\n//\n// In the constructor of the Step3 class, we fill the collections. Here, we\n// position the objects related to triangles in the first place (index 0) and\n// the ones related to quadrilaterals in the second place (index 1).\nStep3::Step3()\n  : mapping(MappingFE<2>(FE_SimplexP<2>(1)), MappingFE<2>(FE_Q<2>(1)))\n  , fe(FE_SimplexP<2>(2), FE_Q<2>(2))\n  , quadrature_formula(QGaussSimplex<2>(3), QGauss<2>(3))\n  , dof_handler(triangulation)\n{}\n\n\n// @sect4{Step3::make_grid}\n//\n// Read the external mesh file \"box_2D_mixed.msh\" as in step-3simplex.\nvoid Step3::make_grid()\n{\n  GridIn<2>(triangulation).read(\"box_2D_mixed.msh\");\n\n  std::cout << \"Number of active cells: \" << triangulation.n_active_cells()\n            << std::endl;\n}\n\n\n// @sect4{Step3::setup_system}\n//\n// In contrast to step-3 and step-3simplex, we need here a preprocessing step\n// that assigns an active_fe_index to each cell consistently according to the\n// indices in the collections and the cell type.\nvoid Step3::setup_system()\n{\n  for (const auto &cell : dof_handler.active_cell_iterators())\n    {\n      if (cell->reference_cell() == ReferenceCells::Triangle)\n        cell->set_active_fe_index(0);\n      else if (cell->reference_cell() == ReferenceCells::Quadrilateral)\n        cell->set_active_fe_index(1);\n      else\n        Assert(false, ExcNotImplemented());\n    }\n\n  dof_handler.distribute_dofs(fe);\n  std::cout << \"Number of degrees of freedom: \" << dof_handler.n_dofs()\n            << std::endl;\n  DynamicSparsityPattern dsp(dof_handler.n_dofs());\n  DoFTools::make_sparsity_pattern(dof_handler, dsp);\n  sparsity_pattern.copy_from(dsp);\n\n  system_matrix.reinit(sparsity_pattern);\n\n  solution.reinit(dof_handler.n_dofs());\n  system_rhs.reinit(dof_handler.n_dofs());\n}\n\n\n// @sect4{Step3::assemble_system}\n//\n// The following function looks similar to the version in step-3 and\n// step-3simplex with the following two differences:\n//  - We do not work with FEValues directly but with the collection class\n//    hp::FEValues. It gives us - after it has been initialized with the current\n//    cell - a reference to the right FEValues object (constructed\n//    with the correct mapping object, finite element, and quadrature rule),\n//    which can be used as usual to compute the cell integrals.\n//  - The cell-local stiffness matrix and the right-hand-side vector have\n//    different sizes depending on the cell type (6 DoFs vs. 9 DoFs) so that\n//    they might need to be resized for each cell.\n//\n// Apart from these two changes, the code has not changed. Not even, the\n// cell integrals have been changed depending on whether one operates on\n// hypercube, simplex, or mixed meshes.\nvoid Step3::assemble_system()\n{\n  hp::FEValues<2> hp_fe_values(mapping,\n                               fe,\n                               quadrature_formula,\n                               update_values | update_gradients |\n                                 update_JxW_values);\n\n  FullMatrix<double>                   cell_matrix;\n  Vector<double>                       cell_rhs;\n  std::vector<types::global_dof_index> local_dof_indices;\n\n  for (const auto &cell : dof_handler.active_cell_iterators())\n    {\n      hp_fe_values.reinit(cell);\n\n      const auto &fe_values = hp_fe_values.get_present_fe_values();\n\n      const unsigned int dofs_per_cell = cell->get_fe().n_dofs_per_cell();\n      cell_matrix.reinit(dofs_per_cell, dofs_per_cell);\n      cell_rhs.reinit(dofs_per_cell);\n      local_dof_indices.resize(dofs_per_cell);\n\n      cell_matrix = 0;\n      cell_rhs    = 0;\n\n      for (const unsigned int q_index : fe_values.quadrature_point_indices())\n        {\n          for (const unsigned int i : fe_values.dof_indices())\n            for (const unsigned int j : fe_values.dof_indices())\n              cell_matrix(i, j) +=\n                (fe_values.shape_grad(i, q_index) * // grad phi_i(x_q)\n                 fe_values.shape_grad(j, q_index) * // grad phi_j(x_q)\n                 fe_values.JxW(q_index));           // dx\n\n          for (const unsigned int i : fe_values.dof_indices())\n            cell_rhs(i) += (fe_values.shape_value(i, q_index) * // phi_i(x_q)\n                            1. *                                // f(x_q)\n                            fe_values.JxW(q_index));            // dx\n        }\n      cell->get_dof_indices(local_dof_indices);\n\n      for (const unsigned int i : fe_values.dof_indices())\n        for (const unsigned int j : fe_values.dof_indices())\n          system_matrix.add(local_dof_indices[i],\n                            local_dof_indices[j],\n                            cell_matrix(i, j));\n\n      for (const unsigned int i : fe_values.dof_indices())\n        system_rhs(local_dof_indices[i]) += cell_rhs(i);\n    }\n\n\n  std::map<types::global_dof_index, double> boundary_values;\n  VectorTools::interpolate_boundary_values(\n    mapping, dof_handler, 0, Functions::ZeroFunction<2>(), boundary_values);\n  MatrixTools::apply_boundary_values(boundary_values,\n                                     system_matrix,\n                                     solution,\n                                     system_rhs);\n}\n\n\n// @sect4{Step3::solve}\n//\n// Nothing has changed here.\nvoid Step3::solve()\n{\n  SolverControl            solver_control(1000, 1e-12);\n  SolverCG<Vector<double>> solver(solver_control);\n  solver.solve(system_matrix, solution, system_rhs, PreconditionIdentity());\n}\n\n\n// @sect4{Step3::output_results}\n//\n// Nothing has changed here.\nvoid Step3::output_results() const\n{\n  DataOut<2> data_out;\n\n  DataOutBase::VtkFlags flags;\n  flags.write_higher_order_cells = true;\n  data_out.set_flags(flags);\n\n  data_out.attach_dof_handler(dof_handler);\n  data_out.add_data_vector(solution, \"solution\");\n  data_out.build_patches(mapping, 2);\n  std::ofstream output(\"solution.vtk\");\n  data_out.write_vtk(output);\n}\n\n\n// @sect4{Step3::run}\n//\n// Nothing has changed here.\nvoid Step3::run()\n{\n  make_grid();\n  setup_system();\n  assemble_system();\n  solve();\n  output_results();\n}\n\n\n// @sect3{The <code>main</code> function}\n//\n// Nothing has changed here.\nint main()\n{\n  deallog.depth_console(2);\n\n  Step3 laplace_problem;\n  laplace_problem.run();\n\n  return 0;\n}\n\n/**\n * <h1>Results</h1>\n *\n * The following figures show the mesh and the result obtained by executing this\n * program:\n *\n * <table align=\"center\" class=\"doxtable\" style=\"width:65%\">\n *   <tr>\n *     <td>\n *         @image html step_3_mixed_0.png\n *     </td>\n *     <td>\n *         @image html step_3_mixed_1.png\n *     </td>\n *   </tr>\n * </table>\n *\n * Not surprisingly, the result looks as expected.\n *\n *\n * <h3>Possibilities for extensions</h3>\n *\n * In this tutorial, we presented how to use the deal.II simplex infrastructure\n * to solve a simple Poisson problem on a mixed mesh in 2D. In this scope, we\n * could only present a small section of the capabilities. In the following, we\n * point out further capabilities briefly.\n *\n *\n * <h4>Pure hypercube and simplex meshes</h4>\n *\n * In this tutorial, we worked on a mesh consisting both of quadrilaterals and\n * triangles. However, the program and the underlying concepts also work if the\n * mesh only contains either quadrilaterals or triangles. Interested users can\n * try this out: we have provided appropriate journal files and meshes for such\n * cases.\n *\n *\n * <h4>3D meshes</h4>\n *\n * In 3D, meshes might also consist of wedges/prisms and pyramids. Therefore,\n * the above introduced collections might consist of four components.\n *\n * For wedge/prism and pyramid cell types, following finite-element and\n * quadrature-rule classes are available:\n *  - wedge: FE_WedgeP, FE_WedgeDGP, QGaussWedge, MappingFE\n *  - pyramid: FE_PyramidP, FE_PyramidDGP, QGaussPyramid, MappingFE\n *\n * <h4>Parallelization, face integrals, discontinuous Galerkin methods, and\n * matrix-free operator evaluation</h4>\n *\n * Regarding these aspects, the same comments are valid that are described in\n * step-3simplex for pure simplex meshes.\n *\n */\n", "meta": {"hexsha": "0d61428d757cbc2923dbc25f4f32cc62c24a2ab0", "size": 15894, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/doxygen/step_3_mixed.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/doxygen/step_3_mixed.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/doxygen/step_3_mixed.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4772234273, "max_line_length": 80, "alphanum_fraction": 0.6918333963, "num_tokens": 4015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4248743982569049}}
{"text": "/**\n * io.cpp\n *\n * 2021 Gabriel Moreira\n *\n * https://github.com/gabmoreira/maks\n *\n * This software and the related documents  are provided as  is,  with no express\n * or implied  warranties,  other  than those  that are  expressly stated  in the\n * License.\n *\n * Copyright © 2021 Gabriel Moreira. All rights reserved.\n */\n\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <fstream>\n\n#include <Eigen/Geometry>\n\n#include \"io.hpp\"\n\nusing std::vector;\nusing std::string;\nusing std::stod;\nusing std::stoi;\n\nusing Eigen::Quaterniond;\nusing Eigen::Vector3d;\nusing Eigen::VectorXi;\nusing Eigen::Matrix3d;\nusing Eigen::MatrixXd;\nusing Eigen::Ref;\n\n#define G2O_PRECISION 15\n\n/**\n * Splits a string based on a delimiter.\n *\n * @param str Input string to be split.\n * @param delim Input string delimiter.\n * @return vector of tokens.\n */\nvector<string> strSplit(const string& str, const string& delim) {\n    vector<string> tokens;\n    size_t prev = 0, pos = 0;\n    do {\n        pos = str.find(delim, prev);\n        if (pos == string::npos)\n            pos = str.length();\n        string token = str.substr(prev, pos-prev);\n        if (!token.empty())\n            tokens.push_back(token);\n        prev = pos + delim.length();\n    } while (pos < str.length() && prev < str.length());\n\n    return tokens;\n};\n\n\n/**\n * Reads g2o file.\n *\n * @param path (input) char*  - g2o file name.\n * @param node_i (output) Eigen::VectorXi - node indices.\n * @param node_r (output) Eigen::MatrixXd - SO(3) node rotations.\n * @param node_t (output) Eigen::MatrixXd - node translations.\n * @param edge_i (output) Eigen::VectorXi - edge indices (from).\n * @param edge_j (output) Eigen::VectorXi - edge indices (to).\n * @param edge_r (output) Eigen::MatrixXd - SO(3) edge rotations.\n * @param edge_t (output) Eigen::MatrixXd - edge translations.\n * @param num_nodes (output) int - number of nodes loaded.\n * @param num_edges (output) int - number of edges loaded.\n */\nvoid readG2O(const char*   path,\n             Ref<VectorXi> node_i,\n             Ref<MatrixXd> node_r,\n             Ref<MatrixXd> node_t,\n             Ref<VectorXi> edge_i,\n             Ref<VectorXi> edge_j,\n             Ref<MatrixXd> edge_r,\n             Ref<MatrixXd> edge_t,\n             int&          num_nodes,\n             int&          num_edges) {\n    \n    std::ifstream infile(path);\n    if(!infile)\n        return;\n\n    string edge_tag = \"EDGE_SE3:QUAT\";\n    string node_tag = \"VERTEX_SE3:QUAT\";\n\n    num_nodes = 0;\n    num_edges = 0;\n    \n    string line;\n    while (std::getline(infile, line)) {\n        vector<string> tokens = strSplit(line, \" \");\n        string tag = tokens[0];\n\n        if (0 == tag.compare(edge_tag)) {\n            int edge_i_id = stoi(tokens[1]);\n            int edge_j_id = stoi(tokens[2]);\n            \n            // Edge translation\n            Vector3d t( stod(tokens[3]), stod(tokens[4]), stod(tokens[5]) );\n            \n            // Edge quaternion\n            Quaterniond q( stod(tokens[9]), stod(tokens[6]), stod(tokens[7]), stod(tokens[8]) );\n\n            edge_i(num_edges) += edge_i_id;\n            edge_j(num_edges) += edge_j_id;\n            edge_r.block<3,3>(0,num_edges*3) += q.normalized().toRotationMatrix();\n            edge_t.block<3,1>(0,num_edges) += t;\n            num_edges++;\n                        \n        } else if (0 == tag.compare(node_tag)) {\n            int node_id = stoi(tokens[1]);\n            \n            // Node translation\n            Vector3d t( stod(tokens[2]), stod(tokens[3]), stod(tokens[4]) );\n\n            // Node quaternion\n            Quaterniond q( stod(tokens[8]), stod(tokens[5]), stod(tokens[6]), stod(tokens[7]) );\n\n            node_i(num_nodes) += node_id;\n            node_r.block<3,3>(0,num_nodes*3) += q.normalized().toRotationMatrix();\n            node_t.block<3,1>(0,num_nodes) += t;\n            num_nodes++;\n        };\n    };\n};\n\n\n/**\n * Reads edge rotations from g2o file.\n *\n * @param path (input) char*  - g2o file name.\n * @param edge_i (output) Eigen::VectorXi - edge id (from).\n * @param edge_j (output) Eigen::VectorXi - edge id (to).\n * @param edge_r (output) Eigen::MatrixXd - Row block matrix containing SO(3) rotations.\n * @param num_edges (output) int - number of edges.\n */\nvoid readG2O(const char*          path,\n             Eigen::Ref<VectorXi> edge_i,\n             Eigen::Ref<VectorXi> edge_j,\n             Eigen::Ref<MatrixXd> edge_r,\n             int&                 num_edges) {\n    \n    std::ifstream infile(path);\n    if(!infile)\n        return;\n\n    string edge_tag = \"EDGE_SE3:QUAT\";\n\n    num_edges = 0;\n    \n    string line;\n    while (std::getline(infile, line)) {\n        vector<string> tokens = strSplit(line, \" \");\n        string tag = tokens[0];\n\n        if (0 == tag.compare(edge_tag)) {\n            int edge_i_id = stoi(tokens[1]);\n            int edge_j_id = stoi(tokens[2]);\n            \n            /* Edge quaternion */\n            Quaterniond q( stod(tokens[9]), stod(tokens[6]), stod(tokens[7]), stod(tokens[8]) );\n\n            edge_i(num_edges) += edge_i_id;\n            edge_j(num_edges) += edge_j_id;\n            edge_r.block<3,3>(0,num_edges*3) += q.normalized().toRotationMatrix();\n            num_edges++;\n        };\n    };\n};\n\n\n\n\nvoid writeG2O(const char* filename,\n              const vector<int>&         node_i,\n              const vector<Quaterniond>& node_q,\n              const vector<Vector3d>&    node_t,\n              const vector<int>&         edge_i,\n              const vector<int>&         edge_j,\n              const vector<Quaterniond>& edge_q,\n              const vector<Vector3d>&    edge_t) {\n\n    int num_nodes = (int) node_i.size();\n    int num_edges = (int) edge_i.size();\n    \n    string filepath = string(filename) + \".g2o\";\n\n    std::ostringstream buffer;\n    buffer.clear();\n\n    /* Write node data */\n    for (int i = 0; i < num_nodes; ++i) {\n        /* Write tag */\n        buffer << \"VERTEX_SE3:QUAT\";\n        \n        /* Write node id */\n        buffer << \" \" << std::to_string(node_i[i]);\n        \n        /* Write node translation */\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << node_t[i](0); // x\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << node_t[i](1); // y\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << node_t[i](2); // z\n\n        /* Write node quaternion */\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << node_q[i].x();           // qx\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << node_q[i].y();           // qy\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << node_q[i].z();           // qz\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << node_q[i].w() << \"\\n\";   // qw\n    };\n    \n    /* Write edge data */\n    for (int i = 0; i < num_edges; ++i) {\n        /* Write tag */\n        buffer << \"EDGE_SE3:QUAT\";\n        \n        /* Write edge ids */\n        buffer << \" \" << std::to_string(edge_i[i]);\n        buffer << \" \" << std::to_string(edge_j[i]);\n\n        /* Write node translation */\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << edge_t[i](0); // x\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << edge_t[i](1); // y\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << edge_t[i](2); // z\n\n        /* Write node quaternion */\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << edge_q[i].x();           // qx\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << edge_q[i].y();           // qy\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << edge_q[i].z();           // qz\n        buffer << \" \" << std::fixed << std::setprecision(G2O_PRECISION) << edge_q[i].w() << \"\\n\";   // qw\n    };\n\n    std::ofstream outfile;\n    outfile.open(filepath);\n    if(!outfile) {\n        return;\n    };\n\n    outfile << buffer.str();\n    outfile.close();\n    printf(\"Pose graph saved to %s\\n\", filepath.c_str());\n};\n", "meta": {"hexsha": "e9067bb369f140941b41e1a898591f79e7895e63", "size": 8083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/io.cpp", "max_stars_repo_name": "rjanvier/maks", "max_stars_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2020-12-15T10:15:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:19:07.000Z", "max_issues_repo_path": "src/io.cpp", "max_issues_repo_name": "rjanvier/maks", "max_issues_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T12:24:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:47:43.000Z", "max_forks_repo_path": "src/io.cpp", "max_forks_repo_name": "rjanvier/maks", "max_forks_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-06T07:22:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T09:31:30.000Z", "avg_line_length": 32.203187251, "max_line_length": 105, "alphanum_fraction": 0.548434987, "num_tokens": 2125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4248743982569049}}
{"text": "/*\n * rosenbrock4.cpp\n *\n * Copyright 2010-2012 Mario Mulansky\n * Copyright 2011-2012 Karsten Ahnert\n * Copyright 2012 Andreas Angelopoulos\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <iostream>\n#include <fstream>\n#include <utility>\n\n#include <boost/numeric/odeint.hpp>\n\n#include <boost/phoenix/core.hpp>\n\n#include <boost/phoenix/core.hpp>\n#include <boost/phoenix/operator.hpp>\n\nusing namespace std;\nusing namespace boost::numeric::odeint;\nnamespace phoenix = boost::phoenix;\n\n\n\n//[ stiff_system_definition\ntypedef boost::numeric::ublas::vector< double > vector_type;\ntypedef boost::numeric::ublas::matrix< double > matrix_type;\n\nstruct stiff_system\n{\n    void operator()( const vector_type &x , vector_type &dxdt , double /* t */ )\n    {\n        dxdt[ 0 ] = -101.0 * x[ 0 ] - 100.0 * x[ 1 ];\n        dxdt[ 1 ] = x[ 0 ];\n    }\n};\n\nstruct stiff_system_jacobi\n{\n    void operator()( const vector_type & /* x */ , matrix_type &J , const double & /* t */ , vector_type &dfdt )\n    {\n        J( 0 , 0 ) = -101.0;\n        J( 0 , 1 ) = -100.0;\n        J( 1 , 0 ) = 1.0;\n        J( 1 , 1 ) = 0.0;\n        dfdt[0] = 0.0;\n        dfdt[1] = 0.0;\n    }\n};\n//]\n\n\n\n/*\n//[ stiff_system_alternative_definition\ntypedef boost::numeric::ublas::vector< double > vector_type;\ntypedef boost::numeric::ublas::matrix< double > matrix_type;\n\nstruct stiff_system\n{\n    template< class State >\n    void operator()( const State &x , State &dxdt , double t )\n    {\n        ...\n    }\n};\n\nstruct stiff_system_jacobi\n{\n    template< class State , class Matrix >\n    void operator()( const State &x , Matrix &J , const double &t , State &dfdt )\n    {\n        ...\n    }\n};\n//]\n */\n\n\n\nint main( int argc , char **argv )\n{\n//    typedef rosenbrock4< double > stepper_type;\n//    typedef rosenbrock4_controller< stepper_type > controlled_stepper_type;\n//    typedef rosenbrock4_dense_output< controlled_stepper_type > dense_output_type;\n    //[ integrate_stiff_system\n    vector_type x( 2 , 1.0 );\n\n    size_t num_of_steps = integrate_const( make_dense_output< rosenbrock4< double > >( 1.0e-6 , 1.0e-6 ) ,\n            make_pair( stiff_system() , stiff_system_jacobi() ) ,\n            x , 0.0 , 50.0 , 0.01 ,\n            cout << phoenix::arg_names::arg2 << \" \" << phoenix::arg_names::arg1[0] << \"\\n\" );\n    //]\n    clog << num_of_steps << endl;\n\n\n\n//    typedef runge_kutta_dopri5< vector_type > dopri5_type;\n//    typedef controlled_runge_kutta< dopri5_type > controlled_dopri5_type;\n//    typedef dense_output_runge_kutta< controlled_dopri5_type > dense_output_dopri5_type;\n    //[ integrate_stiff_system_alternative\n\n    vector_type x2( 2 , 1.0 );\n\n    size_t num_of_steps2 = integrate_const( make_dense_output< runge_kutta_dopri5< vector_type > >( 1.0e-6 , 1.0e-6 ) ,\n            stiff_system() , x2 , 0.0 , 50.0 , 0.01 ,\n            cout << phoenix::arg_names::arg2 << \" \" << phoenix::arg_names::arg1[0] << \"\\n\" );\n    //]\n    clog << num_of_steps2 << endl;\n\n\n    return 0;\n}\n", "meta": {"hexsha": "ca71f660016ab3a1405e46967c47014be4b7f7cd", "size": 3072, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/stiff_system.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/odeint/examples/stiff_system.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/odeint/examples/stiff_system.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 25.8151260504, "max_line_length": 119, "alphanum_fraction": 0.6328125, "num_tokens": 922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.622459324198198, "lm_q1q2_score": 0.4248743854377356}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n// Copyright (c) 2013 Adam Wulkiewicz, Lodz, Poland.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_ALGORITHMS_CONVERT_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_ALGORITHMS_CONVERT_HPP\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/algorithms/convert.hpp>\n\n#include <boost/geometry/extensions/algebra/core/tags.hpp>\n\n#include <boost/geometry/extensions/algebra/algorithms/detail.hpp>\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate <typename RQuaternion, typename RMatrix>\nstruct convert<RQuaternion, RMatrix, rotation_quaternion_tag, rotation_matrix_tag, 3, false>\n{\n    static inline void apply(RQuaternion const& q, RMatrix& m)\n    {\n        typedef typename coordinate_type<RQuaternion>::type T;\n\n        // quaternion should be normalized\n\n        T xx2 = get<1>(q) * get<1>(q) * 2;\n        T yy2 = get<2>(q) * get<2>(q) * 2;\n        T zz2 = get<3>(q) * get<3>(q) * 2;\n        T xy2 = get<1>(q) * get<2>(q) * 2;\n        T yz2 = get<2>(q) * get<3>(q) * 2;\n        T xz2 = get<1>(q) * get<3>(q) * 2;\n        T wx2 = get<0>(q) * get<1>(q) * 2;\n        T wy2 = get<0>(q) * get<2>(q) * 2;\n        T wz2 = get<0>(q) * get<3>(q) * 2;\n\n        // WARNING!\n        // Quaternion (0, 0, 0, 0) is converted to identity matrix!\n\n        set<0, 0>(m, 1-yy2-zz2); set<0, 1>(m, xy2-wz2);   set<0, 2>(m, xz2+wy2);\n        set<1, 0>(m, xy2+wz2);   set<1, 1>(m, 1-xx2-zz2); set<1, 2>(m, yz2-wx2);\n        set<2, 0>(m, xz2-wy2);   set<2, 1>(m, yz2+wx2);   set<2, 2>(m, 1-xx2-yy2);\n    }\n};\n\ntemplate <typename RMatrix, typename RQuaternion>\nstruct convert<RMatrix, RQuaternion, rotation_matrix_tag, rotation_quaternion_tag, 3, false>\n{\n    static inline void apply(RMatrix const& m, RQuaternion & q)\n    {\n        typedef typename coordinate_type<RMatrix>::type T;\n\n        // WARNING!\n        // Zero matrix is converted to quaternion(0.5, 0, 0, 0)!\n\n        T w = math::sqrt(1 + get<0, 0>(m) + get<1, 1>(m) + get<2, 2>(m)) / 2;\n        T iw4 = 0.25 / w;\n        set<0>(q, w);\n        set<1>(q, (get<2, 1>(m) - get<1, 2>(m)) * iw4);\n        set<2>(q, (get<0, 2>(m) - get<2, 0>(m)) * iw4);\n        set<3>(q, (get<1, 0>(m) - get<0, 1>(m)) * iw4);\n    }\n};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_ALGEBRA_ALGORITHMS_ASSIGN_HPP\n", "meta": {"hexsha": "593c050282cf8b09beede4c24a89b36c56d27d6a", "size": 2948, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/algebra/algorithms/convert.hpp", "max_stars_repo_name": "yumetodo/OpenSiv3D", "max_stars_repo_head_hexsha": "ea191438ecbc64185f5df3d9f79dffc6757e4192", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 709.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T07:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:02:22.000Z", "max_issues_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/algebra/algorithms/convert.hpp", "max_issues_repo_name": "yumetodo/OpenSiv3D", "max_issues_repo_head_hexsha": "ea191438ecbc64185f5df3d9f79dffc6757e4192", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/algebra/algorithms/convert.hpp", "max_forks_repo_name": "yumetodo/OpenSiv3D", "max_forks_repo_head_hexsha": "ea191438ecbc64185f5df3d9f79dffc6757e4192", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 33.5, "max_line_length": 92, "alphanum_fraction": 0.631275441, "num_tokens": 1012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.42482316993793756}}
{"text": "#include <iostream>\n#include <cassert>\n#include <vector>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> GraphTraits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n                              boost::property<boost::edge_capacity_t, long,\n                                              boost::property<boost::edge_residual_capacity_t, long,\n                                                              boost::property<boost::edge_reverse_t, GraphTraits::edge_descriptor>>>>\n    Graph;\n\nconst int debug_level = 0;\n\n#define DEBUG(min_level, x)      \\\n  if (debug_level >= min_level)  \\\n  {                              \\\n    std::cerr << x << std::endl; \\\n  }\n\nconst std::vector<std::pair<int, int>> attack_offsets{\n    {-1, -2},\n    {-1, 2},\n    {1, -2},\n    {1, 2},\n    {-2, -1},\n    {-2, 1},\n    {2, -1},\n    {2, 1},\n};\n\nclass EdgeAdder\n{\n  Graph &G;\n\npublic:\n  explicit EdgeAdder(Graph &G) : G(G) {}\n  void add_edge(int from, int to, long capacity)\n  {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    const Graph::edge_descriptor e = boost::add_edge(from, to, G).first;\n    const Graph::edge_descriptor rev_e = boost::add_edge(to, from, G).first;\n    c_map[e] = capacity;\n    c_map[rev_e] = 0; // reverse edge has no capacity!\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n  }\n};\n\nvoid testcase()\n{\n  int n;\n  std::cin >> n;\n  assert(n >= 1 && n <= (1 << 6));\n\n  const auto square_is_in_range = [n](int i, int j) { return i >= 0 && i < n && j >= 0 && j < n; };\n  const auto square_is_white = [](int i, int j) { return (i + j) % 2 == 0; };\n\n  std::vector<std::vector<bool>> is_present_by_field(n, std::vector<bool>(n));\n  for (int i = 0; i < n; i++)\n  {\n    for (int j = 0; j < n; j++)\n    {\n      int raw;\n      std::cin >> raw;\n      assert(raw == 0 || raw == 1);\n      is_present_by_field.at(i).at(j) = bool(raw);\n    }\n  }\n\n  int next_free_node = 0;\n  const int node_source = next_free_node++;\n  const int node_sink = next_free_node++;\n  const auto get_node_for_square = [next_free_node, n, square_is_in_range](int i, int j) {\n    assert(square_is_in_range(i, j));\n    return next_free_node + i * n + j;\n  };\n  next_free_node += n * n;\n  const int num_nodes = next_free_node;\n\n  Graph G(num_nodes);\n  EdgeAdder adder(G);\n  auto rc_map = boost::get(boost::edge_residual_capacity, G);\n\n  for (int i = 0; i < n; i++)\n  {\n    for (int j = 0; j < n; j++)\n    {\n      if (!is_present_by_field.at(i).at(j))\n      {\n        continue;\n      }\n\n      if (square_is_white(i, j))\n      {\n        adder.add_edge(node_source, get_node_for_square(i, j), 1);\n      }\n      else\n      {\n        adder.add_edge(get_node_for_square(i, j), node_sink, 1);\n        continue;\n      }\n\n      for (const auto offset : attack_offsets)\n      {\n        const int attack_i = i + offset.first;\n        const int attack_j = j + offset.second;\n        if (!square_is_in_range(attack_i, attack_j) || !is_present_by_field.at(attack_i).at(attack_j))\n        {\n          continue;\n        }\n        assert(!square_is_white(attack_i, attack_j));\n        adder.add_edge(get_node_for_square(i, j), get_node_for_square(attack_i, attack_j), 1);\n      }\n    }\n  }\n\n  boost::push_relabel_max_flow(G, node_source, node_sink);\n\n  std::vector<bool> visited_by_node(num_nodes, false);\n  visited_by_node.at(node_source) = true;\n  std::deque<int> queue{node_source};\n  while (!queue.empty())\n  {\n    const int node = queue.front();\n    queue.pop_front();\n    for (auto it = boost::out_edges(node, G); it.first != it.second; it.first++)\n    {\n      const int next_node = boost::target(*it.first, G);\n      if (rc_map[*it.first] > 0 && !visited_by_node.at(next_node))\n      {\n        visited_by_node.at(next_node) = true;\n        queue.push_back(next_node);\n      }\n    }\n  }\n\n  int max_knights = 0;\n  for (int i = 0; i < n; i++)\n  {\n    for (int j = 0; j < n; j++)\n    {\n      if (is_present_by_field.at(i).at(j) && square_is_white(i, j) == visited_by_node.at(get_node_for_square(i, j)))\n      {\n        max_knights++;\n      }\n    }\n  }\n\n  std::cout << max_knights << \"\\n\";\n}\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n\n  int t;\n  std::cin >> t;\n  for (int i = 0; i < t; i++)\n  {\n    testcase();\n  }\n\n  return 0;\n}", "meta": {"hexsha": "be5dcbe36374299ecf1617b21da73afc1428745f", "size": 4416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-09/placing-knights/src/main.cpp", "max_stars_repo_name": "tehwalris/algolab", "max_stars_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T08:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T08:21:32.000Z", "max_issues_repo_path": "week-09/placing-knights/src/main.cpp", "max_issues_repo_name": "tehwalris/algolab", "max_issues_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-09/placing-knights/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4431137725, "max_line_length": 133, "alphanum_fraction": 0.5733695652, "num_tokens": 1287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225279, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4247988752302842}}
{"text": "#include <assert.h>\n#include <limits>\n\n#include <Eigen/Core>\n\n#include \"MultiviewGeometry.h\"\n#include \"Math.h\"\n#include \"Stl.h\"\n#include \"Conversion.h\"\n#include \"Log.h\"\n\nnamespace VISFS {\n\nbool isFinite(const cv::Point3f & _point) {\n    return uIsFinite(_point.x) && uIsFinite(_point.y) && uIsFinite(_point.z);\n}\n\ncv::Point3f transformPoint(const cv::Point3f & _points, const GeometricCamera & _model) {\n    Eigen::Vector4d tempPoint = _model.getTansformImageToRobot() * Eigen::Vector4d(_points.x, _points.y, _points.z, 1.f);\n    return cv::Point3f(tempPoint[0], tempPoint[1], tempPoint[2]);\n}\n\ncv::Point3f transformPoint(const cv::Point3f & _points, const Eigen::Isometry3d & _transform) {\n    Eigen::Vector4d tempPoint = _transform * Eigen::Vector4d(_points.x, _points.y, _points.z, 1.f);\n    return cv::Point3f(tempPoint[0], tempPoint[1], tempPoint[2]);\n}\n\nstd::vector<float> computeReprojErrors(\n\tconst std::vector<cv::Point3f> & _objectPoints,\n\tconst std::vector<cv::Point2f> & _imagePoints,\n\tconst cv::Mat & _cameraModel,\n\tconst cv::Mat & _distCoeffs,\n\tconst cv::Mat & _rvec,\n\tconst cv::Mat & _tvec,\n\tconst float _reProjErrorThreshold,\n\tstd::vector<std::size_t> & _inliers) {\n    assert(_objectPoints.size() == _imagePoints.size());\n    std::size_t cnt = _objectPoints.size();\n    std::vector<cv::Point2f> projPoints;\n    cv::projectPoints(_objectPoints, _rvec, _tvec, _cameraModel, _distCoeffs, projPoints);\n\n    _inliers.resize(cnt, 0);\n    std::vector<float> error(cnt);\n    std::size_t oi = 0;\n    for (std::size_t i = 0; i < cnt; ++i) {\n        float e = static_cast<float>(cv::norm(_imagePoints[i] - projPoints[i]));\n        if (e <= _reProjErrorThreshold) {\n            _inliers[oi] = i;\n            error[oi++] = e;\n        }\n    }\n    _inliers.resize(oi);\n    error.resize(oi);\n    return error;\n}\n\nstd::vector<cv::Point3f> generateKeyPoints3DStereo(const std::vector<cv::KeyPoint> & _kptsLeft, const std::vector<cv::KeyPoint> & _kptsRight_, const GeometricCamera & _cameraLeft, const GeometricCamera & _cameraRight, float _minDepth, float _maxDepth) {\n    assert(_kptsLeft.size() == _kptsRight_.size());\n\n    std::vector<cv::Point3f> kpts3D;\n    kpts3D.resize(_kptsLeft.size());\n    const float badPoint = std::numeric_limits<float>::quiet_NaN();\n    for (std::size_t i = 0; i < _kptsLeft.size(); ++i) {\n        cv::Point3f point(badPoint, badPoint, badPoint);\n        float disparity = _kptsLeft[i].pt.x - _kptsRight_[i].pt.x;\n        if (disparity != 0.f) {\n            cv::Point3f tempPoint = projectDisparityTo3D(_kptsLeft[i].pt, disparity, _cameraLeft, _cameraRight);\n            if (isFinite(tempPoint) && (_minDepth < 0.f || tempPoint.z > _minDepth) && (_maxDepth <= 0.f || tempPoint.z <= _maxDepth)) {\n                point = tempPoint;  // point in camera coordinate system.\n                point = transformPoint(point, _cameraLeft);\n            }\n        }\n        kpts3D.at(i) = point;\n    }\n    return kpts3D;\n}\n\ncv::Point3f projectDisparityTo3D(const cv::Point2f & _corner, float _disparity, const GeometricCamera & _cameraLeft, const GeometricCamera & _cameraRight) {\n    cv::Mat leftK = _cameraLeft.cvKfloat();\n    cv::Mat rightK = _cameraRight.cvKfloat();\n    float baseLine = _cameraLeft.getBaseLine();\n    if (_disparity > 0.f && baseLine > 0.f && leftK.at<float>(0, 0) > 0.f) {\n        float c = 0.f;\n        if (leftK.at<float>(0, 2) > 0.f && rightK.at<float>(0, 2) > 0.f) {\n            c = rightK.at<float>(0, 2) - leftK.at<float>(0, 2);\n        }\n        float W = baseLine/(_disparity + c);\n        return cv::Point3f((_corner.x - leftK.at<float>(0, 2))*W, (_corner.y - leftK.at<float>(1, 2))*W, leftK.at<float>(0, 0)*W);\n    }\n    const float badPoint = std::numeric_limits<float>::quiet_NaN();\n    return cv::Point3f(badPoint, badPoint, badPoint);\n}\n\nEigen::Isometry3d estimateMotion3DTo2D(\n    const std::map<std::size_t, cv::Point3f> & _words3dFrom,\n    const std::map<std::size_t, cv::KeyPoint> & _words2dTo,\n    const GeometricCamera & _cameraModel,\n    int _minInliers,\n    int _iterations,\n    double _reProjError,\n    int _flagPnP,\n    int _refineIterations,\n    const std::map<std::size_t, cv::Point3f> & _words3dTo,\n    cv::Mat & _covariance,\n    std::vector<std::size_t> & _matchesOut,\n    std::vector<std::size_t> & _inliersOut,\n\tconst Eigen::Isometry3d & _guess) {\n    Eigen::Isometry3d transform(Eigen::Matrix4d::Zero());\n    std::vector<std::size_t> matches, inliers;\n    _covariance = cv::Mat::eye(6, 6, CV_64FC1);\n\n    // find correspondences\n    std::vector<size_t> ids = uKeys(_words2dTo);\n    std::vector<cv::Point3f> objectPoints(ids.size());\n    std::vector<cv::Point2f> imagePoints(ids.size());\n    std::size_t oi = 0;\n    matches.resize(ids.size());\n    for (std::size_t i = 0; i < ids.size(); ++i) {\n        std::map<std::size_t, cv::Point3f>::const_iterator iter = _words3dFrom.find(ids[i]);\n        if (iter != _words3dFrom.end() && isFinite(iter->second)) {\n            const cv::Point3f & pt = iter->second;\n            objectPoints[oi] = pt;\n            imagePoints[oi] = _words2dTo.find(ids[i])->second.pt;\n            matches[oi++] = ids[i];\n        }\n    }\n    objectPoints.resize(oi);\n    imagePoints.resize(oi);\n    matches.resize(oi);\n\n    if (static_cast<int>(matches.size()) >= _minInliers) {\n        cv::Mat K = _cameraModel.cvKdouble();\n        cv::Mat D = _cameraModel.cvDdouble();\n        Eigen::Isometry3d guessCameraFrame = (_guess * _cameraModel.getTansformImageToRobot()).inverse();\n\t\tcv::Mat R = (cv::Mat_<double>(3,3) <<\n\t\t\t\tguessCameraFrame(0, 0), guessCameraFrame(0, 1), guessCameraFrame(0, 2),\n\t\t\t\tguessCameraFrame(1, 0), guessCameraFrame(1, 1), guessCameraFrame(1, 2),\n\t\t\t\tguessCameraFrame(2, 0), guessCameraFrame(2, 1), guessCameraFrame(2, 2));\n\t\tcv::Mat rvec(1,3, CV_64FC1);\n\t\tcv::Rodrigues(R, rvec);\n        Eigen::Vector3d eigent = guessCameraFrame.translation();\n        cv::Mat tvec = (cv::Mat_<double>(1,3) << eigent.x(), eigent.y(), eigent.z());\n\n        // Calculate\n        VISFS::solvePnPRansac(objectPoints, imagePoints, K, D, rvec, tvec, false, _iterations, _reProjError, _minInliers, inliers, _flagPnP, _refineIterations);\n\n        if (static_cast<int>(inliers.size()) >= _minInliers) {\n            cv::Rodrigues(rvec, R);\n            Eigen::Matrix3d rotation;\n            rotation << R.at<double>(0,0), R.at<double>(0,1), R.at<double>(0,2),\n\t\t\t\t\t\tR.at<double>(1,0), R.at<double>(1,1), R.at<double>(1,2),\n\t\t\t\t\t\tR.at<double>(2,0), R.at<double>(2,1), R.at<double>(2,2);\n            Eigen::Vector3d translate(tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2));\n            Eigen::Isometry3d pnp = Eigen::Isometry3d::Identity();\n            pnp.prerotate(rotation);\n            pnp.pretranslate(translate);\n            transform = (_cameraModel.getTansformImageToRobot() * pnp).inverse();\n\n            // compute variance (like in PCL computeVariance() method of sac_model.h)\n            if (_words3dTo.size()) {\n                std::vector<float> errSqrdDists(inliers.size());\n                std::vector<float> errSqrdAngles(inliers.size());\n                oi = 0;\n                for (std::size_t i = 0; i < inliers.size(); ++i) {\n                    std::map<std::size_t, cv::Point3f>::const_iterator iter = _words3dTo.find(matches[inliers[i]]);\n                    if (iter != _words3dTo.end() && isFinite(iter->second)) {\n                        const cv::Point3f & objPoint = objectPoints[inliers[i]];\n                        cv::Point3f newPoint = transformPoint(iter->second, transform);\n                        errSqrdDists[oi] = uNormSquared(objPoint.x-newPoint.x, objPoint.y-newPoint.y, objPoint.z-newPoint.z);\n\n                        Eigen::Vector4f v1(objPoint.x-transform.translation().x(), objPoint.y-transform.translation().y(), objPoint.z-transform.translation().z(), 0);\n                        Eigen::Vector4f v2(newPoint.x-transform.translation().x(), newPoint.y-transform.translation().y(), newPoint.z-transform.translation().z(), 0);\n                        errSqrdAngles[oi++] = getAngle3D(v1, v2);\n                    }\n                }\n                errSqrdDists.resize(oi);\n                errSqrdAngles.resize(oi);\n\n                if (errSqrdDists.size()) {\n                    std::sort(errSqrdDists.begin(), errSqrdDists.end());\n                    double medianErrSqr = 2.1981 * static_cast<double>(errSqrdDists[errSqrdDists.size() >> 1]);\n                    assert(uIsFinite(medianErrSqr));\n                    _covariance(cv::Range(0, 3), cv::Range(0, 3)) *= medianErrSqr;\n                    std::sort(errSqrdAngles.begin(), errSqrdAngles.end());\n                    medianErrSqr = 2.1981 * static_cast<double>(errSqrdAngles[errSqrdAngles.size() >> 1]);\n                    assert(uIsFinite(medianErrSqr));\n                    _covariance(cv::Range(3, 6), cv::Range(3, 6)) *= medianErrSqr;\n                } else {\n                    LOG_ERROR << \"Not enough close points to compute covariance!\";\n                }\n\n                if (static_cast<float>(oi) / static_cast<float>(inliers.size()) < 0.2f) {\n                    LOG_WARN << \"A very low number of inliers have valid depth \" << oi << \" / \" << inliers.size() << \" , the transform returned may be wrong!\";\n                }\n            } else {\n                // compute variance, which is the rms of reprojection errors\n                std::vector<cv::Point2f> imagePointsReproj;\n                cv::projectPoints(objectPoints, rvec, tvec, K, cv::Mat(), imagePointsReproj);\n                float err = 0.f;\n                for (std::size_t i = 0; i < inliers.size(); ++i) {\n                    err += uNormSquared(imagePoints.at(inliers[i]).x-imagePointsReproj.at(inliers[i]).x, imagePoints.at(inliers[i]).y-imagePointsReproj.at(inliers[i]).y);\n                }\n                assert(uIsFinite(err));\n                _covariance *= std::sqrt(err/static_cast<float>(inliers.size()));\n            }\n        }\n    }\n\n    _matchesOut = matches;\n    _inliersOut.resize(inliers.size());\n    for (std::size_t i = 0; i < inliers.size(); ++i) {\n        _inliersOut.at(i) = matches[inliers[i]];\n    }\n\n    return transform;\n}\n\n\nvoid solvePnPRansac(\n\tconst std::vector<cv::Point3f> & _objectPoints,\n\tconst std::vector<cv::Point2f> & _imagePoints,\n\tconst cv::Mat & _cameraMatrix,\n\tconst cv::Mat & _distCoeffs,\n\tcv::Mat & _rvec,\n\tcv::Mat & _tvec,\n\tbool _useExtrinsicGuess,\n\tint _iterationsCount,\n\tfloat _reprojectionError,\n\tint _minInliersCount,\n\tstd::vector<std::size_t> & _inliers,\n\tint _flags,\n\tint _refineIterations,\n\tfloat _refineSigma) {\n    if (_minInliersCount < 4) {\n        _minInliersCount = 4;\n    }\n    std::vector<int> inliersInt;\n    cv::solvePnPRansac(_objectPoints, _imagePoints, _cameraMatrix, _distCoeffs, _rvec, _tvec,\n                        _useExtrinsicGuess, _iterationsCount, _reprojectionError, 0.99, inliersInt, _flags);\n    float inlierThreshold = _reprojectionError;\n    if (static_cast<int>(inliersInt.size()) >= _minInliersCount && _refineIterations > 0) {\n        float errorThreshold = inlierThreshold;\n        int refineIterations = 0;\n        bool inlierChanged = false, oscillating = false;\n        _inliers = uIntVector2Ul(inliersInt);\n        std::vector<std::size_t> newInliers, prevInliers = _inliers, inliersSizes;\n        cv::Mat newModelRvec = _rvec;\n        cv::Mat newModelTvec = _tvec;\n\n        do {\n            // Get inliers from current model.\n            std::vector<cv::Point3f> oPointsInliers(prevInliers.size());\n            std::vector<cv::Point2f> iPointsInliers(prevInliers.size());\n            for (std::size_t i = 0; i < prevInliers.size(); ++i) {\n                oPointsInliers[i] = _objectPoints[prevInliers[i]];\n                iPointsInliers[i] = _imagePoints[prevInliers[i]];\n            }\n            // Optimize the model coefficients.\n            cv::solvePnP(oPointsInliers, iPointsInliers, _cameraMatrix, _distCoeffs, newModelRvec, newModelTvec, true, _flags);\n            inliersSizes.push_back(prevInliers.size());\n\n            // Select the new inliers based on the optimized coefficients and new threshold.\n            std::vector<float> error = computeReprojErrors(_objectPoints, _imagePoints, _cameraMatrix, _distCoeffs, newModelRvec, newModelTvec, errorThreshold, newInliers);\n            if (static_cast<int>(newInliers.size()) < _minInliersCount) {\n                ++refineIterations;\n                if (refineIterations >= _refineIterations) {\n                    break;\n                }\n                continue;\n            }\n\n            // Estimate the variance and the new threshold.\n            float mean = uMean(error);\n            float variance = uVariance(error, mean);\n            errorThreshold = std::min(inlierThreshold, _refineSigma*sqrt(variance));\n\n            inlierChanged = false;\n            std::swap(prevInliers, newInliers);\n            // If the number of inliers changed, then we are still optimizing.\n            if (newInliers.size() != prevInliers.size()) {\n                // Check if the number of inliers is oscillating in between two values\n                if (static_cast<int>(inliersSizes.size()) >= _minInliersCount) {\n                    if (inliersSizes[inliersSizes.size()-1] == inliersSizes[inliersSizes.size()-3] &&\n                        inliersSizes[inliersSizes.size()-2] == inliersSizes[inliersSizes.size()-4]) {\n                        oscillating = true;\n                        break;\n                    }\n                }\n                inlierChanged = true;\n                continue;\n            }\n            // Check the value of the inlier set.\n            for (std::size_t i = 0; i < prevInliers.size(); ++i) {\n                // If the value of the inliers changed, then we are still optimizing\n                if (prevInliers[i] != newInliers[i]) {\n                    inlierChanged = true;\n                    break;\n                }\n            }\n        } while (inlierChanged && ++refineIterations < _refineIterations);\n\n        // If the new set of inliers is empty, we didn't do a good job refineing.\n        if (static_cast<int>(prevInliers.size()) < _minInliersCount) {\n            LOG_ERROR << \"RANSAC refineModel: Refinement failed: got very low inliers \" << prevInliers.size() << \".\";\n        }\n        if (oscillating) {\n            LOG_WARN << \"RANSAC refineModel: Detected oscillations in the model refinement.\";\n        }\n\n        std::swap(_inliers, newInliers);\n        _rvec = newModelRvec;\n        _tvec = newModelTvec;\n    }\n\n}\n\ncv::Mat computeCovariance(\n\tconst std::map<std::size_t, cv::Point3f> & _pointsInCoor1,\n\tconst std::map<std::size_t, cv::Point3f> & _pointsInCoor2,\n\tconst Eigen::Isometry3d & _transformCoor2ToCoor1,\n\tconst std::vector<std::size_t> & _inliers) {\n        cv::Mat covariance = cv::Mat::eye(6, 6, CV_64FC1);\n    if (_inliers.empty()) {\n        LOG_ERROR << \"The corresponding index is empty. return huge covariance.\";\n        covariance *= 9999.0;\n        return covariance;\n    } else if (_pointsInCoor1.empty() || _pointsInCoor2.empty()) {\n        LOG_ERROR << \"The input points are empty. return huge covariance.\";\n        covariance *= 9999.0;\n        return covariance;\n    } else {\n        std::vector<float> errSqrdDists(_inliers.size());\n        std::vector<float> errSqrdAngles(_inliers.size());\n        std::size_t oi = 0;\n        for (std::size_t i = 0; i < _inliers.size(); ++i) {\n            std::map<std::size_t, cv::Point3f>::const_iterator iter1 = _pointsInCoor1.find(_inliers[i]);\n            std::map<std::size_t, cv::Point3f>::const_iterator iter2 = _pointsInCoor2.find(_inliers[i]);\n            if (iter1 != _pointsInCoor1.end() && isFinite(iter1->second) && iter2 != _pointsInCoor2.end() && isFinite(iter2->second)) {\n                const cv::Point3f & ptCoor1 = iter1->second;\n                const cv::Point3f & ptCoor2Proj = transformPoint(iter2->second, _transformCoor2ToCoor1);\n                errSqrdDists[oi] = uNormSquared(ptCoor1.x - ptCoor2Proj.x, ptCoor1.y - ptCoor2Proj.y, ptCoor1.z- ptCoor2Proj.z);\n\n                auto translationCoor2TtoCoor1 = _transformCoor2ToCoor1.translation();\n                Eigen::Vector4f v1(ptCoor1.x- translationCoor2TtoCoor1.x(), ptCoor1.y - translationCoor2TtoCoor1.y(), ptCoor1.z - translationCoor2TtoCoor1.z(), 0);\n                Eigen::Vector4f v2(ptCoor2Proj.x - translationCoor2TtoCoor1.x(), ptCoor2Proj.y - translationCoor2TtoCoor1.y(), ptCoor2Proj.z - translationCoor2TtoCoor1.z(), 0);\n                errSqrdAngles[oi++] = getAngle3D(v1, v2);\n            }\n        }\n        errSqrdDists.resize(oi);\n        errSqrdAngles.resize(oi);\n\n        if (errSqrdDists.size()) {\n            std::sort(errSqrdDists.begin(), errSqrdDists.end());\n            double medianErrSqr = 2.1981 * static_cast<double>(errSqrdDists[errSqrdDists.size() >> 1]);\n            assert(uIsFinite(medianErrSqr));\n            covariance(cv::Range(0, 3), cv::Range(0, 3)) *= medianErrSqr;\n            std::sort(errSqrdAngles.begin(), errSqrdAngles.end());\n            medianErrSqr = 2.1981 * static_cast<double>(errSqrdAngles[errSqrdAngles.size() >> 1]);\n            assert(uIsFinite(medianErrSqr));\n            covariance(cv::Range(3, 6), cv::Range(3, 6)) *= medianErrSqr;\n        } else {\n            LOG_WARN << \"Not enough close points to compute covariance!\";\n        }\n\n        if (static_cast<float>(oi) / static_cast<float>(_inliers.size()) < 0.2f) {\n            LOG_WARN << \"A very low number of inliers have valid depth \" << oi << \" / \" << _inliers.size() << \" , the transform returned may be wrong!\";\n        }\n    }\n}\n\n}   // namespace", "meta": {"hexsha": "ba15acbbbdd45133e155a848d26fb7d21790a440", "size": 17584, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "corelib/src/MultiviewGeometry.cpp", "max_stars_repo_name": "supersaiyajinggod/VISFS", "max_stars_repo_head_hexsha": "6567df9b064437a32dc96d6f03ef6cd4ea1b24ce", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T13:20:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T13:31:11.000Z", "max_issues_repo_path": "corelib/src/MultiviewGeometry.cpp", "max_issues_repo_name": "supersaiyajinggod/VISFS", "max_issues_repo_head_hexsha": "6567df9b064437a32dc96d6f03ef6cd4ea1b24ce", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "corelib/src/MultiviewGeometry.cpp", "max_forks_repo_name": "supersaiyajinggod/VISFS", "max_forks_repo_head_hexsha": "6567df9b064437a32dc96d6f03ef6cd4ea1b24ce", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.3962264151, "max_line_length": 253, "alphanum_fraction": 0.6058348499, "num_tokens": 4949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4246917926485513}}
{"text": "#include \"CartographicMapping.hpp\"\n#include <proj_api.h>\n#include <boost/assign/list_of.hpp>\n#include <boost/algorithm/string.hpp>\n#include <base-logging/Logging.hpp>\n\nnamespace templ {\nnamespace utils {\n\nconst double CartographicMapping::RADIUS_MOON_IN_M = 1737.1E03;\nconst double CartographicMapping::RADIUS_EARTH_IN_M = 6371E03;\n\nstd::map<CartographicMapping::Type, std::string> CartographicMapping::TypeTxt = boost::assign::map_list_of\n    (UNKNOWN, \"UNKNOWN\")\n    (EARTH, \"EARTH\")\n    (MOON, \"MOON\")\n    ;\n\nCartographicMapping::CartographicMapping(const std::string& radiusTypeName)\n{\n    mType = getTypeByName(radiusTypeName);\n}\n\nCartographicMapping::CartographicMapping(Type type)\n    : mType(type)\n{\n}\n\nbase::Point CartographicMapping::latitudeLongitudeToMetric(const base::Point& point) const\n{\n    projPJ pj_merc, pj_latlong;\n\n    switch(mType)\n    {\n        case MOON:\n        {\n            {\n                std::stringstream ss;\n                ss << \"+proj=merc +ellps=sphere\";\n                ss << \" +a=\" << RADIUS_MOON_IN_M;\n                ss << \" +b=\" << RADIUS_MOON_IN_M;\n                ss << \" +units=m\";\n                ss << \" +lat_ts=\" << point.x();\n                if (!(pj_merc = pj_init_plus(ss.str().c_str())) )\n                {\n                    throw std::runtime_error(\"templ::utils::CartographMapping::latitudeLongitudeToMetric: \"\n                            \" could not init mercator projection for moon\");\n                }\n            }\n            {\n                std::stringstream ss;\n                ss << \"+proj=latlong +ellps=sphere\";\n                ss << \" +a=\" << RADIUS_MOON_IN_M;\n                ss << \" +b=\" << RADIUS_MOON_IN_M;\n                ss << \" +units=m\";\n                if (!(pj_latlong = pj_init_plus(ss.str().c_str())) )\n                {\n                    throw std::runtime_error(\"templ::utils::CartographMapping::latitudeLongitudeToMetric: \"\n                            \" could not init latitude/longitude projection for moon\");\n                }\n            }\n            break;\n        }\n        case EARTH:\n        case UNKNOWN:\n        {\n            if (!(pj_merc = pj_init_plus(\"+proj=merc +ellps=clrk66 +lat_ts=33\")) )\n            {\n                throw std::runtime_error(\"templ::utils::CartographMapping::latitudeLongitudeToMetric: \"\n                        \" could not init mercator projection\");\n            }\n            if (!(pj_latlong = pj_init_plus(\"+proj=latlong +ellps=clrk66\")) )\n            {\n                throw std::runtime_error(\"templ::utils::CartographMapping::latitudeLongitudeToMetric: \"\n                        \" could not init latitude/longitude projection\");\n            }\n        }\n        break;\n    }\n\n    double x = point.x();\n    double y = point.y();\n\n    x *= DEG_TO_RAD;\n    y *= DEG_TO_RAD;\n\n    pj_transform(pj_latlong, pj_merc, 1, 1, &x, &y, NULL);\n    return base::Point(x,y,0.0);\n}\n\nCartographicMapping::Type CartographicMapping::getTypeByName(const std::string& _name)\n{\n    std::string name = _name;\n    boost::to_upper(name);\n\n    std::map<CartographicMapping::Type, std::string>::const_iterator cit = CartographicMapping::TypeTxt.begin();\n    for(; cit != CartographicMapping::TypeTxt.end(); ++cit)\n    {\n        if(cit->second == name)\n        {\n            return cit->first;\n        }\n    }\n\n    throw std::invalid_argument(\"templ::utils::CartographMapping::getTypeByName: could not find radius type named: '\" + _name + \"'\");\n}\n\n\n} // end namespace utils\n} // end namespace templ\n", "meta": {"hexsha": "1b83c3e46c7b55a2783f21a003b14e9d0781b5f9", "size": 3501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/CartographicMapping.cpp", "max_stars_repo_name": "tomcreutz/planning-templ", "max_stars_repo_head_hexsha": "55e35ede362444df9a7def6046f6df06851fe318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-31T12:15:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T12:15:15.000Z", "max_issues_repo_path": "src/utils/CartographicMapping.cpp", "max_issues_repo_name": "tomcreutz/planning-templ", "max_issues_repo_head_hexsha": "55e35ede362444df9a7def6046f6df06851fe318", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/CartographicMapping.cpp", "max_forks_repo_name": "tomcreutz/planning-templ", "max_forks_repo_head_hexsha": "55e35ede362444df9a7def6046f6df06851fe318", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-29T10:38:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T10:38:07.000Z", "avg_line_length": 31.5405405405, "max_line_length": 133, "alphanum_fraction": 0.5629820051, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4246917926485513}}
{"text": "\n#define OFDIS_INTERNAL\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Dense>\n#include \"litiv/3rdparty/ofdis/fdf/image.h\"\n#include \"litiv/3rdparty/ofdis/patch.hpp\"\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nofdis::PatClass<eInput,eOutput>::PatClass(const camparam* cpt_in,\n                                          const camparam* cpo_in,\n                                          const optparam* op_in,\n                                          const int patchid_in) :\n        cpt(cpt_in),\n        cpo(cpo_in),\n        op(op_in),\n        patchid(patchid_in) {\n    pc = new patchstate<eOutput>();\n    CreateStatusStruct(pc);\n    tmp.resize(op->novals,1);\n    dxx_tmp.resize(op->novals,1);\n    dyy_tmp.resize(op->novals,1);\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatClass<eInput,eOutput>::CreateStatusStruct(patchstate<eOutput>* psin) {\n    // get reference / template patch\n    psin->pdiff.resize(op->novals,1);\n    psin->pweight.resize(op->novals,1);\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nofdis::PatClass<eInput,eOutput>::~PatClass() {\n    delete pc;\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatClass<eInput,eOutput>::InitializePatch(Eigen::Map<const Eigen::MatrixXf>* im_ao_in,\n                                                      Eigen::Map<const Eigen::MatrixXf>* im_ao_dx_in,\n                                                      Eigen::Map<const Eigen::MatrixXf>* im_ao_dy_in,\n                                                      const Eigen::Vector2f pt_ref_in) {\n    im_ao = im_ao_in;\n    im_ao_dx = im_ao_dx_in;\n    im_ao_dy = im_ao_dy_in;\n    pt_ref = pt_ref_in;\n    ResetPatch();\n    getPatchStaticNNGrad(im_ao->data(), im_ao_dx->data(), im_ao_dy->data(), &pt_ref, &tmp, &dxx_tmp, &dyy_tmp);\n    ComputeHessian();\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatClass<eInput,eOutput>::ComputeHessian() {\n    if(eOutput==ofdis::FlowOutput_OpticalFlow) {\n        pc->Hes(0,0) = (dxx_tmp.array()*dxx_tmp.array()).sum();\n        pc->Hes(0,1) = (dxx_tmp.array()*dyy_tmp.array()).sum();\n        pc->Hes(1,1) = (dyy_tmp.array()*dyy_tmp.array()).sum();\n        pc->Hes(1,0) = pc->Hes(0,1);\n        if(pc->Hes.determinant()==0) {\n            pc->Hes(0,0) += 1e-10;\n            pc->Hes(1,1) += 1e-10;\n        }\n    }\n    else {\n        pc->Hes(0,0) = (dxx_tmp.array()*dxx_tmp.array()).sum();\n        if(pc->Hes.sum()==0)\n            pc->Hes(0,0) += 1e-10;\n    }\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatClass<eInput,eOutput>::SetTargetImage(Eigen::Map<const Eigen::MatrixXf>* im_bo_in,\n                                                     Eigen::Map<const Eigen::MatrixXf>* im_bo_dx_in,\n                                                     Eigen::Map<const Eigen::MatrixXf>* im_bo_dy_in) {\n    im_bo = im_bo_in;\n    im_bo_dx = im_bo_dx_in;\n    im_bo_dy = im_bo_dy_in;\n    ResetPatch();\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatClass<eInput,eOutput>::ResetPatch() {\n    pc->hasconverged=0;\n    pc->hasoptstarted=0;\n    pc->pt_st = pt_ref;\n    pc->pt_iter = pt_ref;\n    pc->p_in.setZero();\n    pc->p_iter.setZero();\n    pc->delta_p.setZero();\n    pc->delta_p_sqnorm = 1e-10;\n    pc->delta_p_sqnorm_init = 1e-10;\n    pc->mares = 1e20;\n    pc->mares_old = 1e20;\n    pc->cnt=0;\n    pc->invalid = false;\n}\n\ninline void paramtopt(Eigen::Vector2f& pt_iter, const Eigen::Vector2f& pt_ref, const Eigen::Vector2f& p_iter) {\n    pt_iter = pt_ref + p_iter; // for optical flow the point displacement and the parameter vector are equivalent\n}\n\ninline void paramtopt(Eigen::Vector2f& pt_iter, const Eigen::Vector2f& pt_ref, const Eigen::Matrix<float,1,1>& p_iter) {\n    pt_iter[0] = pt_ref[0] + p_iter[0];\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatClass<eInput,eOutput>::OptimizeStart(const point_type& p_in_arg) {\n    pc->p_in   = p_in_arg;\n    pc->p_iter = p_in_arg;\n\n    // convert from input parameters to 2D query location(s) for patches\n    paramtopt(pc->pt_iter,pt_ref,pc->p_iter);\n\n    // save starting location, only needed for outlier check\n    pc->pt_st = pc->pt_iter;\n\n    //Check if initial position is already invalid\n    if(pc->pt_iter[0] < cpt->tmp_lb  || pc->pt_iter[1] < cpt->tmp_lb || // check if patch left valid image region\n       pc->pt_iter[0] > cpt->tmp_ubw || pc->pt_iter[1] > cpt->tmp_ubh) {\n        pc->hasconverged=1;\n        pc->pdiff = tmp;\n        pc->hasoptstarted=1;\n    }\n    else {\n        pc->cnt=0; // reset iteration counter\n        pc->delta_p_sqnorm = 1e-10;\n        pc->delta_p_sqnorm_init = 1e-10;  // set to arbitrary low value, s.t. that loop condition is definitely true on first iteration\n        pc->mares = 1e5;          // mean absolute residual\n        pc->mares_old = 1e20; // for rate of change, keep mares from last iteration in here. Set high so that loop condition is definitely true on first iteration\n        pc->hasconverged=0;\n\n        OptimizeComputeErrImg();\n\n        pc->hasoptstarted=1;\n        pc->invalid = false;\n    }\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatClass<eInput,eOutput>::OptimizeIter(const point_type& p_in_arg, const bool untilconv) {\n    if(!pc->hasoptstarted) {\n        ResetPatch();\n        OptimizeStart(p_in_arg);\n    }\n    int oldcnt=pc->cnt;\n    // optimize patch until convergence, or do only one iteration if DIS visualization is used\n    while(!(pc->hasconverged || (untilconv == false && (pc->cnt > oldcnt)))) {\n        pc->cnt++;\n        // projection onto sd_images\n        if(eOutput==ofdis::FlowOutput_OpticalFlow) {\n            pc->delta_p[0] = (dxx_tmp.array()*pc->pdiff.array()).sum();\n            pc->delta_p[1] = (dyy_tmp.array()*pc->pdiff.array()).sum();\n        }\n        else\n            pc->delta_p[0] = (dxx_tmp.array()*pc->pdiff.array()).sum();\n        pc->delta_p = pc->Hes.llt().solve(pc->delta_p); // solve linear system\n        pc->p_iter -= pc->delta_p; // update flow vector\n        if(eOutput==ofdis::FlowOutput_StereoDepth) {\n            if(cpt->camlr==0)\n                pc->p_iter[0] = std::min(pc->p_iter[0],0.0f); // disparity in t can only be negative (in right image)\n            else\n                pc->p_iter[0] = std::max(pc->p_iter[0],0.0f); // ... positive (in left image)\n        }\n        // compute patch locations based on new parameter vector\n        paramtopt(pc->pt_iter,pt_ref,pc->p_iter);\n        // check if patch(es) moved too far from starting location, if yes, stop iteration and reset to starting location\n        if((pc->pt_st - pc->pt_iter).norm() > op->outlierthresh || // check if query patch moved more than >padval from starting location -> most likely outlier\n            pc->pt_iter[0] < cpt->tmp_lb  || pc->pt_iter[1] < cpt->tmp_lb || // check patch left valid image region\n            pc->pt_iter[0] > cpt->tmp_ubw || pc->pt_iter[1] > cpt->tmp_ubh) {\n            pc->p_iter = pc->p_in; // reset\n            paramtopt(pc->pt_iter,pt_ref,pc->p_iter);\n            pc->hasconverged=1;\n            pc->hasoptstarted=1;\n        }\n        OptimizeComputeErrImg();\n    }\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatClass<eInput,eOutput>::LossComputeErrorImage(Eigen::Matrix<float,Eigen::Dynamic,1>* patdest,\n                                            Eigen::Matrix<float,Eigen::Dynamic,1>* wdest,\n                                            const Eigen::Matrix<float,Eigen::Dynamic,1>* patin,\n                                            const Eigen::Matrix<float,Eigen::Dynamic,1>* tmpin) {\n    v4sf * pd = (v4sf*) patdest->data(),\n         * pa = (v4sf*) patin->data(),\n         * te = (v4sf*) tmpin->data(),\n         * pw = (v4sf*) wdest->data();\n\n    if(op->costfct==0) { // L2 cost function\n        for(int i=op->novals/4; i--; ++pd, ++pa, ++te, ++pw) {\n          (*pd) = (*pa)-(*te);  // difference image\n          (*pw) = __builtin_ia32_andnps(op->negzero,(*pd));\n        }\n    }\n    else if(op->costfct==1) { // L1 cost function\n        for(int i=op->novals/4; i--; ++pd, ++pa, ++te, ++pw) {\n            (*pd) = (*pa)-(*te);   // difference image\n            (*pd) = __builtin_ia32_orps( __builtin_ia32_andps(op->negzero,  (*pd) )  , __builtin_ia32_sqrtps (__builtin_ia32_andnps(op->negzero,  (*pd) )) );  // sign(pdiff) * sqrt(abs(pdiff))\n            (*pw) = __builtin_ia32_andnps(op->negzero,  (*pd) );\n        }\n    }\n    else if(op->costfct==2) { // Pseudo Huber cost function\n        for (int i=op->novals/4; i--; ++pd, ++pa, ++te, ++pw) {\n            (*pd) = (*pa)-(*te); // difference image\n            (*pd) = __builtin_ia32_orps(\n                        __builtin_ia32_andps(op->negzero,(*pd)),\n                        __builtin_ia32_sqrtps(\n                            // PSEUDO HUBER NORM\n                            __builtin_ia32_mulps(\n                                __builtin_ia32_sqrtps(\n                                    op->ones+__builtin_ia32_divps(__builtin_ia32_mulps((*pd),(*pd)),\n                                    op->normoutlier_tmpbsq)\n                                )-op->ones,\n                                op->normoutlier_tmp2bsq\n                            )\n                        )\n                    ); // sign(pdiff) * sqrt( 2*b^2*( sqrt(1+abs(pdiff)^2/b^2)+1)  )) // <- looks like this without SSE instruction\n            (*pw) = __builtin_ia32_andnps(op->negzero,(*pd));\n        }\n    }\n}\n\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatClass<eInput,eOutput>::OptimizeComputeErrImg() {\n    getPatchStaticBil(im_bo->data(), &(pc->pt_iter), &(pc->pdiff));\n    // Get photometric patch error\n    LossComputeErrorImage(&pc->pdiff, &pc->pweight, &pc->pdiff, &tmp);\n    // Compute step norm\n    pc->delta_p_sqnorm = pc->delta_p.squaredNorm();\n    if(pc->cnt==1)\n        pc->delta_p_sqnorm_init = pc->delta_p_sqnorm;\n    // Check early termination criterions\n    pc->mares_old = pc->mares;\n    pc->mares = pc->pweight.template lpNorm<1>() / (op->novals);\n    if( ! ((pc->cnt < op->max_iter) & (pc->mares  > op->res_thresh) &\n          ((pc->cnt < op->min_iter) | (pc->delta_p_sqnorm / pc->delta_p_sqnorm_init >= op->dp_thresh)) &\n          ((pc->cnt < op->min_iter) | (pc->mares / pc->mares_old <= op->dr_thresh))) )\n        pc->hasconverged=1;\n}\n\n// Extract patch on integer position, and gradients, No Bilinear interpolation\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatClass<eInput,eOutput>::getPatchStaticNNGrad(const float* img,\n                                           const float* img_dx,\n                                           const float* img_dy,\n                                           const Eigen::Vector2f* mid_in,\n                                           Eigen::Matrix<float,Eigen::Dynamic,1>* tmp_in_e,\n                                           Eigen::Matrix<float,Eigen::Dynamic,1>* tmp_dx_in_e,\n                                           Eigen::Matrix<float,Eigen::Dynamic,1>* tmp_dy_in_e) {\n    float* tmp_in = tmp_in_e->data();\n    float* tmp_dx_in = tmp_dx_in_e->data();\n    float* tmp_dy_in = tmp_dy_in_e->data();\n    Eigen::Vector2i pos;\n    Eigen::Vector2i pos_it;\n    pos[0] = round((*mid_in)[0])+cpt->imgpadding;\n    pos[1] = round((*mid_in)[1])+cpt->imgpadding;\n    int posxx = 0;\n    int lb = -op->p_samp_s/2;\n    int ub = op->p_samp_s/2-1;\n    for(int j = lb; j<=ub; ++j) {\n        for(int i = lb; i<=ub; ++i,++posxx) {\n            pos_it[0] = pos[0]+i;\n            pos_it[1] = pos[1]+j;\n            int idx = pos_it[0]+pos_it[1]*cpt->tmp_w;\n            if(eInput==ofdis::FlowInput_RGB) {\n                idx *= 3;\n                tmp_in[posxx] = img[idx];\n                tmp_dx_in[posxx] = img_dx[idx];\n                tmp_dy_in[posxx] = img_dy[idx];\n                ++posxx;\n                ++idx;\n                tmp_in[posxx] = img[idx];\n                tmp_dx_in[posxx] = img_dx[idx];\n                tmp_dy_in[posxx] = img_dy[idx];\n                ++posxx;\n                ++idx;\n                tmp_in[posxx] = img[idx];\n                tmp_dx_in[posxx] = img_dx[idx];\n                tmp_dy_in[posxx] = img_dy[idx];\n            }\n            else {\n                tmp_in[posxx] = img[idx];\n                tmp_dx_in[posxx] = img_dx[idx];\n                tmp_dy_in[posxx] = img_dy[idx];\n            }\n        }\n    }\n    // PATCH NORMALIZATION\n    if(op->patnorm>0)\n        tmp_in_e->array() -= (tmp_in_e->sum()/op->novals);\n}\n\n// Extract patch on float position with bilinear interpolation, no gradients.\ntemplate<ofdis::FlowInputType eInput, ofdis::FlowOutputType eOutput>\nvoid ofdis::PatClass<eInput,eOutput>::getPatchStaticBil(const float* img, const Eigen::Vector2f* mid_in, Eigen::Matrix<float,Eigen::Dynamic,1>* tmp_in_e) {\n    float* tmp_in = tmp_in_e->data();\n    Eigen::Vector2f resid;\n    Eigen::Vector4f we; // bilinear weight vector\n    Eigen::Vector4i pos;\n    Eigen::Vector2i pos_it;\n    // Compute the bilinear weight vector, for patch without orientation/scale change -> weight vector is constant for all pixels\n    pos[0] = ceil((*mid_in)[0]+.00001f); // ensure rounding up to natural numbers\n    pos[1] = ceil((*mid_in)[1]+.00001f);\n    pos[2] = floor((*mid_in)[0]);\n    pos[3] = floor((*mid_in)[1]);\n    resid[0] = (*mid_in)[0]-(float)pos[2];\n    resid[1] = (*mid_in)[1]-(float)pos[3];\n    we[0] = resid[0]*resid[1];\n    we[1] = (1-resid[0])*resid[1];\n    we[2] = resid[0]*(1-resid[1]);\n    we[3] = (1-resid[0])*(1-resid[1]);\n    pos[0] += cpt->imgpadding;\n    pos[1] += cpt->imgpadding;\n    float* tmp_it = tmp_in;\n    const float* img_a,* img_b,* img_c,* img_d,* img_e;\n    if(eInput==ofdis::FlowInput_RGB)\n        img_e = img+(pos[0]-op->p_samp_s/2)*3;\n    else\n        img_e = img+pos[0]-op->p_samp_s/2;\n    int lb = -op->p_samp_s/2;\n    int ub = op->p_samp_s/2-1;\n    for(pos_it[1] = pos[1]+lb; pos_it[1]<=pos[1]+ub; ++pos_it[1]) {\n        if(eInput==ofdis::FlowInput_RGB) {\n            img_a = img_e+pos_it[1]*cpt->tmp_w*3;\n            img_c = img_e+(pos_it[1]-1)*cpt->tmp_w*3;\n            img_b = img_a-3;\n            img_d = img_c-3;\n        }\n        else {\n            img_a = img_e+pos_it[1]*cpt->tmp_w;\n            img_c = img_e+(pos_it[1]-1)*cpt->tmp_w;\n            img_b = img_a-1;\n            img_d = img_c-1;\n        }\n        for(pos_it[0] = pos[0]+lb; pos_it[0]<=pos[0]+ub; ++pos_it[0],++tmp_it,++img_a,++img_b,++img_c,++img_d) {\n            if(eInput==ofdis::FlowInput_RGB) {\n                (*tmp_it) = we[0]*(*img_a)+we[1]*(*img_b)+we[2]*(*img_c)+we[3]*(*img_d);\n                ++tmp_it;\n                ++img_a;\n                ++img_b;\n                ++img_c;\n                ++img_d;\n                (*tmp_it) = we[0]*(*img_a)+we[1]*(*img_b)+we[2]*(*img_c)+we[3]*(*img_d);\n                ++tmp_it;\n                ++img_a;\n                ++img_b;\n                ++img_c;\n                ++img_d;\n                (*tmp_it) = we[0]*(*img_a)+we[1]*(*img_b)+we[2]*(*img_c)+we[3]*(*img_d);\n            }\n            else {\n                (*tmp_it) = we[0]*(*img_a)+we[1]*(*img_b)+we[2]*(*img_c)+we[3]*(*img_d);\n            }\n        }\n    }\n    // PATCH NORMALIZATION\n    if(op->patnorm>0) // Subtract Mean\n        tmp_in_e->array() -= (tmp_in_e->sum()/op->novals);\n}\n\ntemplate class ofdis::PatClass<ofdis::FlowInput_Grayscale,ofdis::FlowOutput_OpticalFlow>;\ntemplate class ofdis::PatClass<ofdis::FlowInput_Gradient,ofdis::FlowOutput_OpticalFlow>;\ntemplate class ofdis::PatClass<ofdis::FlowInput_RGB,ofdis::FlowOutput_OpticalFlow>;\ntemplate class ofdis::PatClass<ofdis::FlowInput_Grayscale,ofdis::FlowOutput_StereoDepth>;\ntemplate class ofdis::PatClass<ofdis::FlowInput_Gradient,ofdis::FlowOutput_StereoDepth>;\ntemplate class ofdis::PatClass<ofdis::FlowInput_RGB,ofdis::FlowOutput_StereoDepth>;", "meta": {"hexsha": "e38c1ebf374b5da390c80737a7d2119532eeea09", "size": 15964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdparty/ofdis/src/patch.cpp", "max_stars_repo_name": "jpjodoin/litiv", "max_stars_repo_head_hexsha": "435556bea20d60816aff492f50587b1a2d748b21", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 97.0, "max_stars_repo_stars_event_min_datetime": "2015-10-16T04:32:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:04:02.000Z", "max_issues_repo_path": "3rdparty/ofdis/src/patch.cpp", "max_issues_repo_name": "jpjodoin/litiv", "max_issues_repo_head_hexsha": "435556bea20d60816aff492f50587b1a2d748b21", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-07-01T16:37:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-10T06:09:39.000Z", "max_forks_repo_path": "3rdparty/ofdis/src/patch.cpp", "max_forks_repo_name": "jpjodoin/litiv", "max_forks_repo_head_hexsha": "435556bea20d60816aff492f50587b1a2d748b21", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-11-17T05:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T09:30:28.000Z", "avg_line_length": 43.7369863014, "max_line_length": 192, "alphanum_fraction": 0.5641443247, "num_tokens": 4745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.42458246930807875}}
{"text": "//\n// Created by Gonzalo Lera Romero.\n// Grupo de Optimizacion Combinatoria (GOC).\n// Departamento de Computacion - Universidad de Buenos Aires.\n//\n\n#include \"goc/graph/maxflow_mincut.h\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_selectors.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n\nusing namespace std;\n\nnamespace goc\n{\nnamespace\n{\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property, boost::property<boost::edge_index_t, std::size_t>> BoostDigraph;\ntypedef boost::graph_traits<BoostDigraph>::vertex_descriptor BoostVertex;\ntypedef BoostDigraph::edge_descriptor BoostArc;\n}\n\npair<double, STCut> maxflow_mincut(const Digraph& D, const function<double(int i, int j)>& c, int s, int t)\n{\n\t// n = number of vertices.\n\tint n = D.VertexCount();\n\t\n\t// Build boost network B to work with.\n\tBoostDigraph B;\n\tvector<BoostArc> reverse_arcs;\n\tvector<float> capacities;\n\t\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tfor (int j: D.Successors(i))\n\t\t{\n\t\t\tboost::add_edge(i, j, boost::num_edges(B), B);\n\t\t\tcapacities.push_back(c(i,j));\n\t\t}\n\t}\n\t\n\t// Add boost reverse arcs.\n\tvector<BoostArc> reverse_reverses; // reverse arcs of the reverse arcs.\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tfor (int j: D.Successors(i))\n\t\t{\n\t\t\tauto reverse_arc = boost::edge(j,i,B);\n\t\t\tif (!reverse_arc.second) // If the arc was not in the network.\n\t\t\t{\n\t\t\t\treverse_arc = boost::add_edge(j, i, boost::num_edges(B), B);\n\t\t\t\tcapacities.push_back(0.0);\n\t\t\t\treverse_reverses.push_back(boost::edge(i,j,B).first);\n\t\t\t}\n\t\t\treverse_arcs.push_back(reverse_arc.first);\n\t\t}\n\t}\n\tfor (auto e: reverse_reverses) reverse_arcs.push_back(e);\n\t\n\tvector<int> color(n);\n\tvector<float> residual_capacity(num_edges(B), 0);\n\t\n\tauto capacity_map = boost::make_iterator_property_map(&capacities[0], boost::get(boost::edge_index, B));\n\tauto residual_capacity_map = boost::make_iterator_property_map(&residual_capacity[0], boost::get(boost::edge_index, B));\n\tauto reverse_arc_map = boost::make_iterator_property_map(&reverse_arcs[0], boost::get(boost::edge_index, B));\n\tauto color_map = boost::make_iterator_property_map(&color[0], boost::get(boost::vertex_index, B));\n\t\n\t// Solve max-flow with boykov_kolmogorov algorithm.\n\tBoostVertex source = s;\n\tBoostVertex sink = t;\n\tdouble max_flow = boost::boykov_kolmogorov_max_flow(B, capacity_map, residual_capacity_map, reverse_arc_map,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolor_map, boost::get(boost::vertex_index, B), source, sink);\n\t\n\t// Get min-cut.\n\tSTCut min_cut;\n\tfor (int i = 0; i < n; ++i)\n\t{\n\t\tif (color[i] == boost::black_color) min_cut.S.push_back(i);\n\t\telse min_cut.T.push_back(i);\n\t}\n\t\n\treturn {max_flow, min_cut};\n}\n} // namespace goc.", "meta": {"hexsha": "372b59d245cb067562c24a8685eea2cd01e1e1e1", "size": 2756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/src/graph/maxflow_mincut.cpp", "max_stars_repo_name": "mblufstein/pruebasOR", "max_stars_repo_head_hexsha": "b43e63596643fe762f49fefffcc763c6a293a9cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-12-31T09:21:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-01T02:37:07.000Z", "max_issues_repo_path": "code/src/graph/maxflow_mincut.cpp", "max_issues_repo_name": "mblufstein/pruebasOR", "max_issues_repo_head_hexsha": "b43e63596643fe762f49fefffcc763c6a293a9cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/src/graph/maxflow_mincut.cpp", "max_forks_repo_name": "mblufstein/pruebasOR", "max_forks_repo_head_hexsha": "b43e63596643fe762f49fefffcc763c6a293a9cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-21T14:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-01T02:37:06.000Z", "avg_line_length": 31.6781609195, "max_line_length": 158, "alphanum_fraction": 0.7162554427, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.42445210924159105}}
{"text": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n#ifndef ITL_PC_MASSLUMPING_INCLUDE\n#define ITL_PC_MASSLUMPING_INCLUDE\n\n#include <boost/numeric/linear_algebra/inverse.hpp>\n\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/detail/base_cursor.hpp>\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n#include <boost/numeric/itl/pc/solver.hpp>\n\nnamespace itl\n{\n  namespace pc\n  {\n\n    /// Diagonal Preconditioner\n    template <typename Matrix, typename Value= typename mtl::Collection<Matrix>::value_type>\n    class masslumping\n    {\n    public:\n      typedef Value                                         value_type;\n      typedef typename mtl::Collection<Matrix>::size_type   size_type;\n      typedef masslumping                                   self;\n\n      /// Constructor takes matrix reference\n      explicit masslumping(const Matrix& A) : inv_diag(num_rows(A))\n      {\n        // \tmtl::vampir_trace<5050> tracer;\n        MTL_THROW_IF(num_rows(A) != num_cols(A), mtl::matrix_not_square());\n        using namespace mtl;\n        using namespace mtl::tag;\n        using mtl::traits::range_generator;\n        using math::reciprocal;\n\n        typedef typename range_generator<tag::row, Matrix>::type c_type;\n        typedef typename range_generator<tag::nz, c_type>::type  ic_type;\n\n        typename mtl::traits::row<Matrix>::type row(A);\n        typename mtl::traits::const_value<Matrix>::type value(A);\n\n        value_type row_sum;\n        c_type cursor(begin<tag::row>(A));\n        for (c_type cend(end<tag::row>(A)); cursor != cend; ++cursor)\n        {\n          row_sum = math::zero(value_type());\n          ic_type icursor(begin<tag::nz>(cursor));\n          size_type r = row(icursor);\n\n          for (ic_type icend(end<tag::nz>(cursor)); icursor != icend; ++icursor)\n            row_sum += value(*icursor);\n\n          inv_diag[r]= reciprocal(row_sum);\n        }\n      }\n\n      /// Member function solve, better use free function solve\n      template <typename Vector>\n      Vector solve(const Vector& x) const\n      {\n        Vector y(resource(x));\n        solve(x, y);\n        return y;\n      }\n\n      template <typename VectorIn, typename VectorOut>\n      void solve(const VectorIn& x, VectorOut& y) const\n      {\n        mtl::vampir_trace<5051> tracer;\n        y.checked_change_resource(x);\n        MTL_THROW_IF(size(x) != size(inv_diag), mtl::incompatible_size());\n        for (size_type i= 0; i < size(inv_diag); ++i)\n          y[i]= inv_diag[i] * x[i];\n      }\n\n      /// Member function for solving adjoint problem, better use free function adjoint_solve\n      template <typename Vector>\n      Vector adjoint_solve(const Vector& x) const\n      {\n        Vector y(resource(x));\n        adjoint_solve(x, y);\n        return y;\n      }\n\n      template <typename VectorIn, typename VectorOut>\n      void adjoint_solve(const VectorIn& x, VectorOut& y) const\n      {\n        using mtl::conj;\n        y.checked_change_resource(x);\n        MTL_THROW_IF(size(x) != size(inv_diag), mtl::incompatible_size());\n        for (size_type i= 0; i < size(inv_diag); ++i)\n          y[i]= conj(inv_diag[i]) * x[i];\n      }\n\n    protected:\n      mtl::vector::dense_vector<value_type>    inv_diag;\n    };\n\n    /// Solve approximately a sparse system in terms of inverse lumped diagonal\n    template <typename Matrix, typename Vector>\n    solver<masslumping<Matrix>, Vector, false>\n    inline solve(const masslumping<Matrix>& P, const Vector& x)\n    {\n      return solver<masslumping<Matrix>, Vector, false>(P, x);\n    }\n\n    /// Solve approximately the adjoint of a sparse system in terms of inverse lumped diagonal\n    template <typename Matrix, typename Vector>\n    solver<masslumping<Matrix>, Vector, true>\n    inline adjoint_solve(const masslumping<Matrix>& P, const Vector& x)\n    {\n      return solver<masslumping<Matrix>, Vector, true>(P, x);\n    }\n\n\n  }\n} // namespace itl::pc\n\n#endif // ITL_PC_MASSLUMPING_INCLUDE\n", "meta": {"hexsha": "6e860a74e83405f1d9a8a1edeb2ed6cff6be29bf", "size": 4532, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver/itl/masslumping.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "src/solver/itl/masslumping.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver/itl/masslumping.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5703703704, "max_line_length": 94, "alphanum_fraction": 0.6436451898, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.42445209335106265}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2000 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n \n * Author: Wolfgang Bangerth, University of Texas at Austin, 2000, 2004 \n *         Wolfgang Bangerth, Texas A&M University, 2016 \n */ \n\n\n// @sect3{Include files}  \n\n// 首先是我们在以前的例子程序中已经使用过的常见的各种头文件。\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/logstream.h> \n#include <deal.II/base/multithread_info.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/sparsity_tools.h> \n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n#include <deal.II/grid/grid_refinement.h> \n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n#include <deal.II/fe/fe_values.h> \n#include <deal.II/fe/fe_system.h> \n#include <deal.II/fe/fe_q.h> \n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/matrix_tools.h> \n#include <deal.II/numerics/data_out.h> \n#include <deal.II/numerics/error_estimator.h> \n\n// 这里是我们对这个例子程序特别需要的东西，而这些东西并不在  step-8  中。首先，我们替换掉标准输出 <code>std::cout</code> by a new stream <code>pcout</code> ，它在并行计算中只用于在其中一个MPI进程中生成输出。\n\n#include <deal.II/base/conditional_ostream.h> \n\n// 我们将通过调用  Utilities::MPI  名称空间中的相应函数来查询进程的数量和当前进程的数量。\n\n#include <deal.II/base/mpi.h> \n\n// 然后，我们要把所有涉及（全局）线性系统的线性代数组件替换成类，这些类围绕PETSc提供的接口与我们自己的线性代数类相似（PETSc是一个用C语言编写的库，而deal.II附带的包装类提供的PETSc功能的接口与我们自己的线性代数类已经有的接口相似）。特别是，我们需要在MPI程序中分布在几个 @ref GlossMPIProcess \"进程 \"中的向量和矩阵（如果只有一个进程，也就是说，如果你只在一台机器上运行，并且没有MPI支持，则简单映射为顺序的、本地的向量和矩阵）。\n\n#include <deal.II/lac/petsc_vector.h> \n#include <deal.II/lac/petsc_sparse_matrix.h> \n\n// 然后，我们还需要PETSc提供的求解器和预处理器的接口。\n\n#include <deal.II/lac/petsc_solver.h> \n#include <deal.II/lac/petsc_precondition.h> \n\n// 此外，我们还需要一些划分网格的算法，以便在MPI网络上有效地分布这些网格。分区算法在 <code>GridTools</code> 命名空间中实现，我们需要一个额外的包含文件，用于 <code>DoFRenumbering</code> 中的一个函数，该函数允许对与自由度相关的索引进行排序，以便根据它们所关联的子域进行编号。\n\n#include <deal.II/grid/grid_tools.h> \n#include <deal.II/dofs/dof_renumbering.h> \n\n// 而这又是简单的C++。\n\n#include <fstream> \n#include <iostream> \n\n// 最后一步和以前所有的程序一样。\n\nnamespace Step17 \n{ \n  using namespace dealii; \n// @sect3{The <code>ElasticProblem</code> class template}  \n\n// 该程序的第一个真正的部分是主类的声明。 正如在介绍中提到的，几乎所有的内容都是从 step-8 中逐字复制过来的，所以我们只对这两个教程之间的少数差异进行评论。 有一个（表面上的）变化是，我们让 <code>solve</code> 返回一个值，即收敛所需的迭代次数，这样我们就可以在适当的地方将其输出到屏幕上。\n\n  template <int dim> \n  class ElasticProblem \n  { \n  public: \n    ElasticProblem(); \n    void run(); \n\n  private: \n    void         setup_system(); \n    void         assemble_system(); \n    unsigned int solve(); \n    void         refine_grid(); \n    void         output_results(const unsigned int cycle) const; \n\n// 第一个变化是，我们必须声明一个变量，表明我们应该通过它来分配我们的计算的 @ref GlossMPICommunicator \"MPI通信器\"。\n\n    MPI_Comm mpi_communicator; \n\n// 然后我们有两个变量，告诉我们在并行世界中的位置。下面的第一个变量， <code>n_mpi_processes</code>  ，告诉我们总共有多少个MPI进程，而第二个变量， <code>this_mpi_process</code>  ，表示在这个进程空间中，目前进程的编号（在MPI语言中，这相当于进程的 @ref GlossMPIRank  \"等级\"）。后者对每个进程都有一个唯一的值，介于0和（小于） <code>n_mpi_processes</code>  之间。如果这个程序运行在没有MPI支持的单机上，那么它们的值分别为 <code>1</code> and <code>0</code>  ，。\n\n    const unsigned int n_mpi_processes; \n    const unsigned int this_mpi_process; \n\n// 接下来是一个类似流的变量  <code>pcout</code>  。从本质上讲，它只是我们为了方便而使用的东西：在一个并行程序中，如果每个进程都输出状态信息，那么很快就会有很多杂乱的信息。相反，我们希望只让一个 @ref GlossMPIProcess \"进程 \"输出一次所有的信息，例如， @ref GlossMPIRank \"等级 \"为零的那个。同时，在我们创建输出的<i>every</i>地方加上 <code>if (my_rank==0)</code> 条件的前缀似乎很傻。\n\n// 为了使这个问题更简单，ConditionalOStream类正是这样做的：它就像一个流一样，但只有在一个标志被设置后才转发到一个真正的、底层的流。通过将这个条件设置为 <code>this_mpi_process==0</code> （其中 <code>this_mpi_process</code> 对应于MPI进程的等级），我们确保输出只从第一个进程中产生，并且我们不会在每个进程中重复得到同样的输出行。因此，我们可以在每一个地方和每一个进程中使用 <code>pcout</code> ，但是除了一个进程之外，所有的进程都不会发生通过 <code>operator&lt;&lt;</code> 输送到对象中的信息。\n\n    ConditionalOStream pcout; \n\n// 成员变量列表的其余部分与  step-8  中的内容基本相同。然而，我们改变了矩阵和矢量类型的声明，以使用并行的PETSc对象代替。请注意，我们没有使用单独的稀疏模式，因为PETSc将其作为矩阵数据结构的一部分进行内部管理。\n\n    Triangulation<dim> triangulation; \n    FESystem<dim>      fe; \n    DoFHandler<dim>    dof_handler; \n\n    AffineConstraints<double> hanging_node_constraints; \n\n    PETScWrappers::MPI::SparseMatrix system_matrix; \n\n    PETScWrappers::MPI::Vector solution; \n    PETScWrappers::MPI::Vector system_rhs; \n  }; \n// @sect3{Right hand side values}  \n\n// 以下内容取自 step-8 ，未作改动。\n\n  template <int dim> \n  class RightHandSide : public Function<dim> \n  { \n  public: \n    virtual void vector_value(const Point<dim> &p, \n                              Vector<double> &  values) const override \n    { \n      Assert(values.size() == dim, ExcDimensionMismatch(values.size(), dim)); \n      Assert(dim >= 2, ExcInternalError()); \n\n      Point<dim> point_1, point_2; \n      point_1(0) = 0.5; \n      point_2(0) = -0.5; \n\n      if (((p - point_1).norm_square() < 0.2 * 0.2) || \n          ((p - point_2).norm_square() < 0.2 * 0.2)) \n        values(0) = 1; \n      else \n        values(0) = 0; \n\n      if (p.square() < 0.2 * 0.2) \n        values(1) = 1; \n      else \n        values(1) = 0; \n    } \n\n    virtual void \n    vector_value_list(const std::vector<Point<dim>> &points, \n                      std::vector<Vector<double>> &  value_list) const override \n    { \n      const unsigned int n_points = points.size(); \n\n      Assert(value_list.size() == n_points, \n             ExcDimensionMismatch(value_list.size(), n_points)); \n\n      for (unsigned int p = 0; p < n_points; ++p) \n        RightHandSide<dim>::vector_value(points[p], value_list[p]); \n    } \n  }; \n\n//  @sect3{The <code>ElasticProblem</code> class implementation}  \n// @sect4{ElasticProblem::ElasticProblem}  \n\n// 实际实现的第一步是主类的构造函数。除了初始化我们在 step-8 中已经有的相同成员变量外，我们在这里用连接所有进程的全局MPI通信器来初始化我们将使用的MPI通信器变量（在更复杂的应用中，可以在这里使用只连接所有进程的一个子集的通信器对象），并调用 Utilities::MPI 辅助函数来确定进程的数量以及当前进程在这个画面中的地位。此外，我们确保输出只由（全局）第一个进程产生。我们通过将我们想要输出的流传给 (<code>std::cout</code>) 和一个真/假标志作为参数，后者是通过测试当前执行构造函数调用的进程是否是MPI宇宙中的第一个来确定的。\n\n  template <int dim> \n  ElasticProblem<dim>::ElasticProblem() \n    : mpi_communicator(MPI_COMM_WORLD) \n    , n_mpi_processes(Utilities::MPI::n_mpi_processes(mpi_communicator)) \n    , this_mpi_process(Utilities::MPI::this_mpi_process(mpi_communicator)) \n    , pcout(std::cout, (this_mpi_process == 0)) \n    , fe(FE_Q<dim>(1), dim) \n    , dof_handler(triangulation) \n  {} \n\n//  @sect4{ElasticProblem::setup_system}  \n\n// 接下来，我们需要实现为要解决的全局线性系统设置各种变量的函数。\n\n// 然而，在我们进行这项工作之前，对于一个并行程序来说，有一件事要做：我们需要确定哪个MPI进程负责每个单元。在进程之间分割单元，通常称为 \"划分网格\"，是通过给每个单元分配一个 @ref GlossSubdomainId \"子域id \"来完成的。我们通过调用METIS库来完成这一工作，METIS库以一种非常有效的方式完成这一工作，试图将子域之间接口上的节点数量降到最低。我们没有尝试直接调用METIS，而是通过调用 GridTools::partition_triangulation() 函数来实现，该函数在更高的编程水平上实现了这一点。\n\n//  @note  正如在介绍中提到的，如果我们使用 parallel::shared::Triangulation 类来代替三角形对象，我们就可以避免这个手动划分的步骤（正如我们在 step-18 中所做的）。  该类实质上做了所有常规三角形的工作，但它也在每次创建或细化网格操作后自动划分网格。\n\n// 在分割之后，我们需要像往常一样列举所有的自由度。 然而，我们希望列举自由度的方式是：所有与子域0（位于进程0）的单元相关的自由度都在与子域1的单元相关的自由度之前，在进程2的单元之前，以此类推。我们需要这样做，因为我们必须将全局向量的右手边和解决方案，以及矩阵分割成连续的行块，住在每个处理器上，而且我们希望以一种需要最小通信的方式来做。这个特殊的列举可以通过使用 DoFRenumbering::subdomain_wise(). 对自由度指数重新排序来获得。\n\n// 这个初始设置的最后一步是，我们为自己得到一个IndexSet，表示这个过程所负责的全局未知数的子集。(注意，一个自由度不一定是由拥有一个单元的进程所拥有，只是因为这个自由度生活在这个单元上：有些自由度生活在子域之间的接口上，因此只由这个接口附近的一个进程所拥有。)\n\n// 在我们继续之前，让我们回顾一下在介绍中已经讨论过的一个事实。我们在这里使用的三角形是在所有进程中复制的，每个进程都有整个三角形的完整副本，包括所有单元。分区只提供了一种方法来确定每个进程 \"拥有 \"哪些单元，但它知道所有单元的一切。同样，DoFHandler对象知道每个单元的一切，特别是每个单元上的自由度，无论它是否是当前进程拥有的单元。这不能扩展到大型问题，因为如果问题足够大，最终只是在每个进程中存储整个网格以及与之相关的所有内容将变得不可行。另一方面，如果我们将三角形分割成若干部分，使每个进程只存储它 \"拥有 \"的单元格，而不存储其他的单元格（或者，至少是其他单元格的一小部分），那么，只要我们将足够多的MPI进程扔给它们，我们就可以解决大问题。这就是我们在 step-40 中要做的，例如，使用 parallel::distributed::Triangulation 类。 另一方面，我们在当前程序中演示的其余大部分内容实际上将继续工作，无论我们有整个三角形的可用，还是只有其中的一部分。\n\n  template <int dim> \n  void ElasticProblem<dim>::setup_system() \n  { \n    GridTools::partition_triangulation(n_mpi_processes, triangulation); \n\n    dof_handler.distribute_dofs(fe); \n    DoFRenumbering::subdomain_wise(dof_handler); \n\n// 我们需要初始化表示当前网格的悬挂节点约束的对象。与三角形和DoFHandler对象一样，我们将简单地在每个进程上存储<i>all</i>约束；同样，这不会有规模，但我们在 step-40 中展示了如何通过在每个MPI进程上只存储对这个特定进程实际重要的自由度约束来解决这个问题。\n\n    hanging_node_constraints.clear(); \n    DoFTools::make_hanging_node_constraints(dof_handler, \n                                            hanging_node_constraints); \n    hanging_node_constraints.close(); \n\n// 现在我们为系统矩阵创建稀疏性模式。请注意，我们再次计算并存储所有条目，而不仅仅是与此相关的条目（参见 step-18 或 step-40 ，以获得更有效的处理方式）。\n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, \n                                    dsp, \n                                    hanging_node_constraints, \n                                    false); \n\n// 现在我们确定本地拥有的DoF的集合，并使用它来初始化并行向量和矩阵。由于矩阵和向量需要并行工作，我们必须向它们传递一个MPI通信对象，以及IndexSet  @p locally_owned_dofs. 中包含的分区信息。IndexSet包含关于全局大小（<i>total</i>自由度数）的信息，也包含要在本地存储哪些行的子集。 注意，系统矩阵需要该行和列的分区信息。对于正方形矩阵，就像这里的情况一样，列的划分方式应该与行的划分方式相同，但是对于矩形矩阵，我们必须按照与矩阵相乘的向量的划分方式来划分列，而行的划分方式必须与矩阵-向量乘法的目的向量相同。\n\n    const std::vector<IndexSet> locally_owned_dofs_per_proc = \n      DoFTools::locally_owned_dofs_per_subdomain(dof_handler); \n    const IndexSet locally_owned_dofs = \n      locally_owned_dofs_per_proc[this_mpi_process]; \n\n    system_matrix.reinit(locally_owned_dofs, \n                         locally_owned_dofs, \n                         dsp, \n                         mpi_communicator); \n\n    solution.reinit(locally_owned_dofs, mpi_communicator); \n    system_rhs.reinit(locally_owned_dofs, mpi_communicator); \n  } \n\n//  @sect4{ElasticProblem::assemble_system}  \n\n// 我们现在组装矩阵和问题的右手边。在我们进行详细讨论之前，有一些事情值得一提。首先，我们将并行组装系统，也就是说，每个进程将负责在属于这个特定进程的单元上进行组装。请注意，自由度的分割方式是，单元内部和属于同一子域的单元之间的所有自由度都属于 <code>owns</code> 该单元的过程。然而，即使如此，我们有时也需要在一个单元上与属于不同过程的邻居集合，在这些情况下，当我们将局部贡献加到全局矩阵或右手向量中时，我们必须将这些条目转移到拥有这些元素的过程中。幸运的是，我们不需要用手去做这件事。PETSc为我们做了这一切，它在本地缓存了这些元素，当我们在这个函数的末尾对矩阵和向量调用 <code>compress()</code> 函数时，根据需要将它们发送给其他进程。\n\n// 第二点是，一旦我们把矩阵和向量的贡献交给了PETSc，那么，a）很难，b）要把它们拿回来进行修改，效率非常低。这不仅是PETSc的错，也是这个程序的分布式性质的结果：如果一个条目驻留在另一个处理器上，那么要得到它必然是很昂贵的。这样做的后果是，我们不应该试图首先组装矩阵和右手边，就像没有悬挂的节点约束和边界值一样，然后在第二步中消除这些约束（例如使用 AffineConstraints::condense()). ），相反，我们应该在将这些条目交给PETSc之前尝试消除悬挂的节点约束。这很容易：我们不需要手工复制元素到全局矩阵中（就像我们在 step-4 中做的那样），而是使用 AffineConstraints::distribute_local_to_global() 函数来同时处理悬空节点的问题。我们在  step-6  中也已经这样做了。第二步，消除边界节点，也可以这样做，把边界值放到与悬挂节点相同的AffineConstraints对象中（例如，见 step-6 中的方法）；但是，严格来说，在这里没有必要这样做，因为消除边界值可以只用每个进程本身存储的数据来完成，因此，我们使用之前在 step-4 中使用的方法，即通过 MatrixTools::apply_boundary_values().  \n\n// 说了这么多，下面是实际的实现，从辅助变量的一般设置开始。 请注意，我们仍然使用deal.II的全矩阵和向量类型的本地系统，因为这些类型很小，不需要在不同进程中共享）。\n\n  template <int dim> \n  void ElasticProblem<dim>::assemble_system() \n  { \n    QGauss<dim>   quadrature_formula(fe.degree + 1); \n    FEValues<dim> fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     cell_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    std::vector<double> lambda_values(n_q_points); \n    std::vector<double> mu_values(n_q_points); \n\n    Functions::ConstantFunction<dim> lambda(1.), mu(1.); \n\n    RightHandSide<dim>          right_hand_side; \n    std::vector<Vector<double>> rhs_values(n_q_points, Vector<double>(dim)); \n\n// 接下来是对所有元素的循环。请注意，我们不需要在每个进程上做<i>all</i>的工作：我们在这里的工作只是在实际属于这个MPI进程的单元上组装系统，所有其他的单元将由其他进程来处理。这就是紧随for-loop之后的if-clause所要处理的：它查询每个单元的子域标识符，这是一个与每个单元相关的数字，告诉我们所有者进程的情况。在更大的范围内，子域标识被用来将一个域分成几个部分（我们在上面 <code>setup_system()</code> 的开头就这样做了），并允许识别一个单元生活在哪个子域。在这个应用中，我们让每个进程恰好处理一个子域，所以我们确定了  <code>subdomain</code> and <code>MPI process</code>  的条款。\n\n// 除此以外，如果你已经了解了  step-8  中的组装方式，那么组装本地系统就相对不容易了。如上所述，将本地贡献分配到全局矩阵和右手边，也是以与  step-6  中相同的方式来处理悬挂节点约束。\n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      if (cell->subdomain_id() == this_mpi_process) \n        { \n          cell_matrix = 0; \n          cell_rhs    = 0; \n\n          fe_values.reinit(cell); \n\n          lambda.value_list(fe_values.get_quadrature_points(), lambda_values); \n          mu.value_list(fe_values.get_quadrature_points(), mu_values); \n\n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            { \n              const unsigned int component_i = \n                fe.system_to_component_index(i).first; \n\n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                { \n                  const unsigned int component_j = \n                    fe.system_to_component_index(j).first; \n\n                  for (unsigned int q_point = 0; q_point < n_q_points; \n                       ++q_point) \n                    { \n                      cell_matrix(i, j) += \n                        ((fe_values.shape_grad(i, q_point)[component_i] * \n                          fe_values.shape_grad(j, q_point)[component_j] * \n                          lambda_values[q_point]) + \n                         (fe_values.shape_grad(i, q_point)[component_j] * \n                          fe_values.shape_grad(j, q_point)[component_i] * \n                          mu_values[q_point]) + \n                         ((component_i == component_j) ? \n                            (fe_values.shape_grad(i, q_point) * \n                             fe_values.shape_grad(j, q_point) * \n                             mu_values[q_point]) : \n                            0)) * \n                        fe_values.JxW(q_point); \n                    } \n                } \n            } \n\n          right_hand_side.vector_value_list(fe_values.get_quadrature_points(), \n                                            rhs_values); \n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            { \n              const unsigned int component_i = \n                fe.system_to_component_index(i).first; \n\n              for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n                cell_rhs(i) += fe_values.shape_value(i, q_point) * \n                               rhs_values[q_point](component_i) * \n                               fe_values.JxW(q_point); \n            } \n\n          cell->get_dof_indices(local_dof_indices); \n          hanging_node_constraints.distribute_local_to_global(cell_matrix, \n                                                              cell_rhs, \n                                                              local_dof_indices, \n                                                              system_matrix, \n                                                              system_rhs); \n        } \n\n// 下一步是对向量和系统矩阵进行 \"压缩\"。这意味着每个进程将对矩阵和向量中那些自己不拥有的条目所做的添加发送给拥有这些条目的进程。在收到其他进程的这些加法后，每个进程再把它们加到它已经拥有的值上。这些加法是将生活在几个单元上的形状函数的积分贡献结合起来，就像在串行计算中一样，不同的是这些单元被分配给不同的进程。\n\n    system_matrix.compress(VectorOperation::add); \n    system_rhs.compress(VectorOperation::add); \n\n// 全局矩阵和右边的向量现在已经形成。我们仍然要应用边界值，方法与我们在 step-3 ,  step-4 , 和其他一些程序中的方法相同。\n\n// 下面调用 MatrixTools::apply_boundary_values() 的最后一个参数允许进行一些优化。它控制我们是否应该删除对应于边界节点的矩阵列中的条目（即，将其设置为零），或者保留它们（通过 <code>true</code> 意味着：是的，消除这些列）。如果我们消除了列，那么结果矩阵将再次成为对称的，如果我们不这样做，那么它将不会。不过，结果系统的解应该是一样的。我们想让系统重新成为对称的唯一原因是我们想使用CG方法，该方法只对对称矩阵有效。我们可能<i>not</i>想让矩阵对称的原因是，这将要求我们写进实际存在于其他进程中的列项，即涉及到数据的交流。这总是很昂贵的。\n\n// 经验告诉我们，如果我们不删除与边界节点相关的列，CG也可以工作（而且工作得几乎一样好），这可以用这种特殊的非对称性结构来解释。为了避免通信的费用，我们因此不消除受影响列中的条目。\n\n    std::map<types::global_dof_index, double> boundary_values; \n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             Functions::ZeroFunction<dim>(dim), \n                                             boundary_values); \n    MatrixTools::apply_boundary_values( \n      boundary_values, system_matrix, solution, system_rhs, false); \n  } \n\n//  @sect4{ElasticProblem::solve}  \n\n// 组建了线性系统后，我们接下来需要解决它。PETSc提供了各种顺序和并行求解器，我们为这些求解器编写了包装器，其接口与之前所有示例程序中使用的deal.II求解器几乎相同。因此，下面的代码看起来应该相当熟悉。\n\n// 在该函数的顶部，我们设置了一个收敛监视器，并指定了我们希望解决线性系统的精度。接下来，我们使用PETSc的CG求解器创建一个实际的求解器对象，该求解器也可用于并行（分布式）矢量和矩阵。最后是一个预处理程序；我们选择使用一个块状雅可比预处理程序，它通过计算矩阵的每个对角线块的不完全LU分解来工作。 换句话说，每个MPI进程从其存储的行中计算出一个ILU，丢掉与本地未存储的行指数相对应的列；这就产生了一个方形的矩阵块，我们可以从中计算出一个ILU。这意味着如果你只用一个进程来运行程序，那么你将使用一个ILU(0)作为预处理程序，而如果它在许多进程上运行，那么我们将在对角线上有许多块，预处理程序是这些块中每个块的ILU(0)。在每个处理器只有一个自由度的极端情况下，这个预处理程序只是一个雅可比预处理程序，因为对角线矩阵块只由一个条目组成。这样的预处理程序相对容易计算，因为它不需要在处理器之间进行任何形式的通信，但一般来说，对于大量的处理器来说，它的效率并不高)。\n\n// 按照这样的设置，我们就可以解决这个线性系统。\n\n  template <int dim> \n  unsigned int ElasticProblem<dim>::solve() \n  { \n    SolverControl solver_control(solution.size(), 1e-8 * system_rhs.l2_norm()); \n    PETScWrappers::SolverCG cg(solver_control, mpi_communicator); \n\n    PETScWrappers::PreconditionBlockJacobi preconditioner(system_matrix); \n\n    cg.solve(system_matrix, solution, system_rhs, preconditioner); \n\n// 下一步是分配悬挂的节点约束。这有点麻烦，因为要填入一个约束节点的值，你需要访问它所约束的节点的值（例如，对于2d中的Q1元素，我们需要访问悬挂节点面的大边上的两个节点，以计算中间的约束节点的值）。\n\n// 问题是，我们已经建立了我们的向量（在 <code>setup_system()</code> 中），使每个进程只负责存储解向量中与该进程 \"拥有 \"的自由度相对应的那些元素。然而，在有些情况下，为了计算一个进程中受限自由度的向量项的值，我们需要访问存储在其他进程中的向量项。 PETSc（以及它所基于的MPI模型）不允许简单地查询存储在其他进程上的向量条目，所以我们在这里所做的是获得一个 \"分布式 \"向量的副本，我们将所有元素存储在本地。这很简单，因为deal.II包装器有一个针对deal.II Vector类的转换构造函数。这种转换当然需要通信，但实质上每个进程只需要将其数据批量发送给其他每个进程一次，而不需要对单个元素的查询做出回应）。\n\n    Vector<double> localized_solution(solution); \n\n// 当然，和以前的讨论一样，如果你想在大量进程上解决大问题，这样的步骤显然不能扩展得很远，因为现在每个进程都存储了<i>all elements</i>的解向量。(我们将在 step-40 中展示如何更好地做到这一点。) 另一方面，在这个本地副本上分配悬挂节点约束很简单，使用通常的函数 AffineConstraints::distributed().  特别是，我们可以计算<i>all</i>约束自由度的值，无论当前进程是否拥有它们。\n\n    hanging_node_constraints.distribute(localized_solution); \n\n// 然后把所有的东西都转回全局向量中。下面的操作是复制我们在分布式解决方案中本地存储的那些本地化解决方案的元素，而不碰其他的。由于我们在所有处理器上做同样的操作，我们最终得到一个分布式向量（即在每个进程上只存储与该进程拥有的自由度相对应的向量项），该向量的所有受限节点都被固定。\n\n// 我们通过返回收敛所需的迭代次数来结束这个函数，以允许一些输出。\n\n    solution = localized_solution; \n\n    return solver_control.last_step(); \n  } \n// @sect4{ElasticProblem::refine_grid}  \n\n// 使用某种细化指标，可以对网格进行细化。这个问题与分布悬挂节点约束基本相同：为了计算误差指标（即使我们只是对当前进程拥有的单元上的指标感兴趣），我们需要访问解向量的更多元素，而不仅仅是当前处理器存储的那些元素。为了实现这一点，我们基本上做了我们在 <code>solve()</code> 中已经做过的事情，即获取<i>complete</i>解向量的副本到每个进程中，并使用它来计算。如上所述，这本身就很昂贵，尤其是没有必要，因为我们刚刚在 <code>solve()</code> 中创建并销毁了这样一个向量，但效率并不是这个程序的重点，所以让我们选择一种设计，即每个函数都尽可能地独立。\n\n// 一旦我们有了这样一个包含<i>all</i>解向量元素的 \"本地化 \"向量，我们就可以计算属于当前过程的单元的指标。事实上，我们当然可以计算<i>all</i>细化指标，因为我们的Triangulation和DoFHandler对象存储了所有单元的信息，而且我们有一个完整的解向量副本。但是为了展示如何进行%并行操作，让我们演示一下，如果只计算<i>some</i>错误指标，然后与其他进程交换剩余的指标，会如何操作。(最终，每个进程都需要一套完整的细化指标，因为每个进程都需要细化他们的网格，并且需要以与其他进程完全相同的方式细化它。)\n\n// 所以，为了做到这一切，我们需要。\n\n// - 首先，获得分布式求解向量的本地拷贝。\n\n// - 第二，创建一个向量来存储细化指标。\n\n// - 第三，让KellyErrorEstimator计算属于当前子域/过程的所有单元的细化指标。调用的最后一个参数表明我们对哪个子域感兴趣。在它之前的三个参数是其他各种默认参数，通常不需要（也不说明数值，而是使用默认值），但我们必须在这里明确说明，因为我们要修改下面一个参数的值（即表示子域的参数）。\n\n  template <int dim> \n  void ElasticProblem<dim>::refine_grid() \n  { \n    const Vector<double> localized_solution(solution); \n\n    Vector<float> local_error_per_cell(triangulation.n_active_cells()); \n    KellyErrorEstimator<dim>::estimate(dof_handler, \n                                       QGauss<dim - 1>(fe.degree + 1), \n                                       {}, \n                                       localized_solution, \n                                       local_error_per_cell, \n                                       ComponentMask(), \n                                       nullptr, \n                                       MultithreadInfo::n_threads(), \n                                       this_mpi_process); \n\n// 现在所有进程都计算了自己单元格的错误指标，并将其存储在 <code>local_error_per_cell</code> 向量的相应元素中。这个向量中不属于本进程的单元格的元素为零。然而，由于所有进程都有整个三角形的副本，并需要保持这些副本的同步，他们需要三角形的所有单元的细化指标值。因此，我们需要分配我们的结果。我们通过创建一个分布式向量来做到这一点，每个进程都有自己的份额，并设置它所计算的元素。因此，当你把这个向量看作是一个存在于所有进程中的向量时，那么这个向量的每个元素都被设置过一次。然后，我们可以将这个并行向量分配给每个进程上的一个本地非并行向量，使<i>all</i>错误指示器在每个进程上都可用。\n//因此，\n//在第一步，我们需要设置一个并行向量。为了简单起见，每个进程都将拥有一个元素块，其数量与该进程拥有的单元格一样多，因此第一个元素块存储在进程0，下一个元素块存储在进程1，以此类推。然而，需要注意的是，这些元素不一定是我们要写入的元素。这是单元格排列顺序的结果，也就是说，向量中的元素对应单元格的顺序并不是根据这些单元格所属的子域来排序的。换句话说，如果在这个过程中，我们计算某个子域的单元的指标，我们可能会把结果写到分布式向量的或多或少的随机元素中；特别是，它们不一定位于我们在这个过程中拥有的向量块中。它们随后将不得不被复制到另一个进程的内存空间中，当我们调用 <code>compress()</code> 函数时，PETSc为我们做了这项操作。这种低效率可以通过更多的代码来避免，但我们不这样做，因为它不是程序总运行时间的一个主要因素。\n\n// 所以我们是这样做的：计算有多少个单元属于这个过程，建立一个有这么多元素的分布式向量存储在本地，将我们在本地计算的元素复制过去，最后将结果压缩。事实上，我们实际上只复制了非零的元素，所以我们可能会错过一些我们计算为零的元素，但这不会有什么影响，因为无论如何，向量的原始值是零。\n\n    const unsigned int n_local_cells = \n      GridTools::count_cells_with_subdomain_association(triangulation, \n                                                        this_mpi_process); \n    PETScWrappers::MPI::Vector distributed_all_errors( \n      mpi_communicator, triangulation.n_active_cells(), n_local_cells); \n\n    for (unsigned int i = 0; i < local_error_per_cell.size(); ++i) \n      if (local_error_per_cell(i) != 0) \n        distributed_all_errors(i) = local_error_per_cell(i); \n    distributed_all_errors.compress(VectorOperation::insert); \n\n// 所以现在我们有了这个分布式向量，它包含了所有单元的细化指标。为了使用它，我们需要获得一个本地副本，然后用它来标记要细化或粗化的单元，并实际进行细化和粗化。重要的是要认识到，<i>every</i>过程对它自己的三角形副本做了这个工作，并且以完全相同的方式进行。\n\n    const Vector<float> localized_all_errors(distributed_all_errors); \n\n    GridRefinement::refine_and_coarsen_fixed_number(triangulation, \n                                                    localized_all_errors, \n                                                    0.3, \n                                                    0.03); \n    triangulation.execute_coarsening_and_refinement(); \n  } \n// @sect4{ElasticProblem::output_results}  \n\n// 最后一个有意义的函数是创建图形输出的函数。它的工作方式与 step-8 中的相同，但有两个小的区别。在讨论这些之前，让我们说明这个函数的一般工作原理：我们打算让所有的数据都在一个进程中产生，然后写入一个文件中。正如本程序的许多其他部分已经讨论过的那样，这不是一个可以扩展的东西。之前，我们认为我们会在三角计算、DoFHandlers和解决方案向量的副本方面遇到麻烦，每个进程都必须存储所有的数据，而且会出现一个点，即每个进程根本没有足够的内存来存储这么多数据。在这里，情况是不同的：不仅是内存，而且运行时间也是一个问题。如果一个进程负责处理<i>all</i>的数据，而其他所有的进程什么都不做，那么这一个函数最终会在程序的整个运行时间中占主导地位。 特别是，这个函数花费的时间将与问题的整体大小（以单元数或自由度数计算）成正比，与我们扔给它的进程数量无关。\n\n// 这种情况需要避免，我们将在 step-18 和 step-40 中展示如何解决这个问题。对于目前的问题，解决方案是让每个进程只为自己的本地单元产生输出数据，并将它们写入单独的文件，每个进程一个文件。这就是 step-18 的操作方式。另外，我们可以简单地把所有的东西放在一组独立的文件中，让可视化软件读取所有的文件（可能也使用多个处理器），并从所有的文件中创建一个单一的可视化；这就是 step-40 、 step-32 以及后来开发的所有其他并行程序的路径。\n\n// 更具体地说，对于当前的函数，所有的进程都调用这个函数，但不是所有的进程都需要做与生成输出相关的工作。事实上，它们不应该这样做，因为我们会试图一次多次地写到同一个文件。所以我们只让第一个进程做这件事，而其他所有的进程在这段时间内闲置（或者为下一次迭代开始工作，或者干脆把它们的CPU让给碰巧在同一时间运行的其他作业）。第二件事是，我们不仅要输出解决方案的向量，还要输出一个向量，表明每个单元属于哪个子域。这将使一些分区域的图片变得很好。\n\n// 为了实现这一点，过程0需要一个完整的本地向量中的解决方案组件。就像前面的函数一样，有效的方法是重新使用在 <code>solve()</code> 函数中已经创建的向量，但是为了使事情更加自洽，我们在这里简单地从分布式解决方案向量中重新创建一个向量。\n\n// 需要认识到的一个重要问题是，我们在所有的进程中都做了这个定位操作，而不是只有那个实际需要数据的进程。然而，这一点是无法避免的，在本教程程序中，我们对向量使用的MPI简化通信模型。MPI没有办法查询另一个进程的数据，双方必须在同一时间启动通信。因此，即使大多数进程不需要本地化的解决方案，我们也必须把将分布式转换为本地化向量的语句放在那里，以便所有进程都执行它。\n\n// （这项工作的一部分实际上可以避免。我们所做的是将所有进程的本地部分发送给所有其他进程。我们真正需要做的是在所有进程上发起一个操作，每个进程只需将其本地的数据块发送给进程0，因为只有这个进程才真正需要它，也就是说，我们需要类似于收集操作的东西。PETSc可以做到这一点，但是为了简单起见，我们在这里并不试图利用这一点。我们没有这样做，因为我们所做的事情在整个计划中并不昂贵：它是所有进程之间的一个矢量通信，这必须与我们在求解线性系统、为预处理程序设置块状ILU以及其他操作时必须进行的通信数量相比较。)\n\n  template <int dim> \n  void ElasticProblem<dim>::output_results(const unsigned int cycle) const \n  { \n    const Vector<double> localized_solution(solution); \n\n// 这样做后，零进程继续设置输出文件，如  step-8  ，并将（本地化的）解决方案矢量附加到输出对象上。\n\n    if (this_mpi_process == 0) \n      { \n        std::ofstream output(\"solution-\" + std::to_string(cycle) + \".vtk\"); \n\n        DataOut<dim> data_out; \n        data_out.attach_dof_handler(dof_handler); \n\n        std::vector<std::string> solution_names; \n        switch (dim) \n          { \n            case 1: \n              solution_names.emplace_back(\"displacement\"); \n              break; \n            case 2: \n              solution_names.emplace_back(\"x_displacement\"); \n              solution_names.emplace_back(\"y_displacement\"); \n              break; \n            case 3: \n              solution_names.emplace_back(\"x_displacement\"); \n              solution_names.emplace_back(\"y_displacement\"); \n              solution_names.emplace_back(\"z_displacement\"); \n              break; \n            default: \n              Assert(false, ExcInternalError()); \n          } \n\n        data_out.add_data_vector(localized_solution, solution_names); \n\n// 我们在这里做的唯一其他事情是，我们也为每个单元格输出一个值，表明它属于哪个子域（即MPI进程）。这需要一些转换工作，因为库提供给我们的数据不是输出类所期望的数据，但这并不困难。首先，设置一个整数向量，每个单元格一个，然后由每个单元格的子域id填充。\n\n// 这个向量的元素在第二步中被转换为浮点向量，这个向量被添加到DataOut对象中，然后它去创建VTK格式的输出。\n\n        std::vector<unsigned int> partition_int(triangulation.n_active_cells()); \n        GridTools::get_subdomain_association(triangulation, partition_int); \n\n        const Vector<double> partitioning(partition_int.begin(), \n                                          partition_int.end()); \n\n        data_out.add_data_vector(partitioning, \"partitioning\"); \n\n        data_out.build_patches(); \n        data_out.write_vtk(output); \n      } \n  } \n// @sect4{ElasticProblem::run}  \n\n// 最后，这里是驱动程序的功能。它与 step-8 几乎完全没有变化，只是我们替换了 <code>std::cout</code> by the <code>pcout</code> 流。除此以外，唯一的表面变化是我们输出了每个进程有多少个自由度，以及线性求解器花了多少次收敛。\n\n  template <int dim> \n  void ElasticProblem<dim>::run() \n  { \n    for (unsigned int cycle = 0; cycle < 10; ++cycle) \n      { \n        pcout << \"Cycle \" << cycle << ':' << std::endl; \n\n        if (cycle == 0) \n          { \n            GridGenerator::hyper_cube(triangulation, -1, 1); \n            triangulation.refine_global(3); \n          } \n        else \n          refine_grid(); \n\n        pcout << \"   Number of active cells:       \" \n              << triangulation.n_active_cells() << std::endl; \n\n        setup_system(); \n\n        pcout << \"   Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << \" (by partition:\"; \n        for (unsigned int p = 0; p < n_mpi_processes; ++p) \n          pcout << (p == 0 ? ' ' : '+') \n                << (DoFTools::count_dofs_with_subdomain_association(dof_handler, \n                                                                    p)); \n        pcout << \")\" << std::endl; \n\n        assemble_system(); \n        const unsigned int n_iterations = solve(); \n\n        pcout << \"   Solver converged in \" << n_iterations << \" iterations.\" \n              << std::endl; \n\n        output_results(cycle); \n      } \n  } \n} // namespace Step17 \n// @sect3{The <code>main</code> function}  \n\n//  <code>main()</code> 的工作方式与其他示例程序中的大多数主函数相同，即它将工作委托给管理对象的 <code>run</code> 函数，并且只将所有内容包装成一些代码来捕获异常。\n\nint main(int argc, char **argv) \n{ \n  try \n    { \n      using namespace dealii; \n      using namespace Step17; \n\n// 这里是唯一真正的区别。MPI和PETSc都要求我们在程序开始时初始化这些库，并在结束时解除初始化。MPI_InitFinalize类处理了所有这些。后面的参数`1`意味着我们确实想让每个MPI进程以单线程运行，这是PETSc并行线性代数的前提条件。\n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); \n\n      ElasticProblem<2> elastic_problem; \n      elastic_problem.run(); \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n\n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "10c9276db61c2fae684e1786796ba26d14b0fd8b", "size": 27921, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-17/step-17.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-17/step-17.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-17/step-17.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.9226973684, "max_line_length": 565, "alphanum_fraction": 0.6762651767, "num_tokens": 13413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.6859494421679929, "lm_q1q2_score": 0.42445209335106265}}
{"text": "/**\n * ****************************************************************************\n * Copyright (c) 2016, Robert Lukierski.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n * ****************************************************************************\n * Blob Detector.\n * ****************************************************************************\n */\n\n#include <VisionCore/Image/ConnectedComponents.hpp>\n\n#include <VisionCore/LaunchUtils.hpp>\n#include <VisionCore/Image/ImagePatch.hpp>\n#include <Eigen/SVD>\n\ntemplate<typename T>\nvoid vc::image::computeGradient(const vc::Buffer2DView<T,vc::TargetHost>& img_in, vc::Buffer2DView<Eigen::Matrix<T,2,1>, vc::TargetHost>& grad_img)\n{\n    tbb::parallel_for(tbb::blocked_range2d<std::size_t>(1, img_in.height() - 1, 1, img_in.width() - 1), [&](const tbb::blocked_range2d<std::size_t>& r)\n    {\n        for(std::size_t y = r.rows().begin() ; y != r.rows().end() ; ++y )\n        {\n            for(std::size_t x = r.cols().begin() ; x != r.cols().end() ; ++x ) \n            {\n                Eigen::Matrix<T,2,1>& grad = grad_img(x,y);\n                grad(0) = img_in(x+1,y) - img_in(x-1,y); // dX\n                grad(1) = img_in(x,y+1) - img_in(x,y-1); // dY\n            }\n        }\n    });\n}\n\ntemplate<typename T>\nvc::image::Conic<T> vc::image::estimateConic(const vc::Buffer2DView<Eigen::Matrix<T,2,1>,vc::TargetHost>& grad_img, const vc::image::Blob<T>& component)\n{\n    vc::image::Conic<T> conic;\n    \n    const vc::types::Rectangle<int> region = component.BoundingBox;\n    \n    // Form system Ax = b to solve\n    Eigen::Matrix<T,5,5> A = Eigen::Matrix<T,5,5>::Zero();\n    Eigen::Matrix<T,5,1> b = Eigen::Matrix<T,5,1>::Zero();\n    \n    for(int v = region.y1() ; v <= region.y2() ; ++v)\n    {\n        const Eigen::Matrix<T,2,1>* dIv = grad_img.rowPtr(v);\n        \n        for(int u = region.x1() ; u <= region.x2() ; ++u)\n        {\n            // li = (ai,bi,ci)' = (I_ui,I_vi, -dI' x_i)'\n            const Eigen::Matrix<T,3,1> d = Eigen::Matrix<T,3,1>(dIv[u](0), dIv[u](1), -(dIv[u](0) * u + dIv[u](1) * v) );\n            const Eigen::Matrix<T,3,1> li = d;\n            Eigen::Matrix<T,5,1> Ki;\n            Ki << li(0) * li(0), li(0) * li(1), li(1) * li(1), li(0) * li(2), li(1) * li(2);\n            A += Ki * Ki.transpose();\n            b += -Ki * li(2) * li(2);\n        }\n    }\n    \n    const Eigen::Matrix<T,5,1> x = A.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV).solve(b);\n    \n    Eigen::Matrix<T,3,3> C_star_norm;\n    C_star_norm <<  x(0)        , x(1)/T(2.0)   , x(3)/T(2.0),  \n                    x(1)/T(2.0) , x(2)          , x(4)/T(2.0),  \n                    x(3)/T(2.0) , x(4)/T(2.0)   ,   T(1.0);\n    \n    conic.C = C_star_norm.inverse();\n\n    conic.BoundingBox = region;\n    conic.Dual = conic.C.inverse();\n    conic.Dual /= conic.Dual(2,2);\n    conic.Center = Eigen::Matrix<T,2,1>(conic.Dual(0,2),conic.Dual(1,2));\n    \n    return conic;\n}\n\ntemplate<typename T>\nstatic inline int tracer(vc::ImagePatch<T,vc::TargetHost>& inpk, vc::ImagePatch<vc::image::BlobID,vc::TargetHost>& outpk, int start, T valid_val)\n{\n    int ret = 8;\n    \n    int nidx = 0;\n    // FIXME const max_ways = 7\n    for(int i = 0 ; i <= 7 ; ++i) // visit all around\n    {\n        nidx = (start + i) % 8;\n        \n        if(inpk(nidx) == valid_val) // black\n        {\n            if(ret == 8) // first found\n            {\n                ret = nidx;\n            }\n        }\n        else // white\n        {\n            // mark it\n            outpk(nidx) = -1;\n        }\n    }\n    \n    return ret; // new direction\n}\n\ntemplate<typename T>\nstatic inline int first_look(vc::ImagePatch<T,vc::TargetHost>& inpk, vc::ImagePatch<vc::image::BlobID,vc::TargetHost>& outpk, bool internal, T valid_val)\n{\n    if(internal == false)\n    {\n        // external contour start direction\n        return tracer<T>(inpk, outpk, 7, valid_val);\n    }\n    else\n    {\n        // internal contour start direction\n        return tracer<T>(inpk, outpk, 3, valid_val);\n    }\n}\n\ntemplate<typename T,typename T2>\nstatic void contour_tracing(vc::Buffer2DView<T,vc::TargetHost>& input, vc::image::BlobImageT& output, int x, int y, bool internal, vc::image::BlobMapT<T2>& bmap, T valid_val, bool do_contour)\n{\n    vc::ImagePatch<T,vc::TargetHost> krn_input(input, x, y);\n    vc::ImagePatch<vc::image::BlobID,vc::TargetHost> krn_output(output, x, y);\n    \n    vc::image::BlobID label = krn_output(0,0);\n    \n    // first step from the beginning of the contour\n    int start = first_look<T>(krn_input, krn_output, internal, valid_val);\n    \n    if(internal == false)\n    {\n        bmap[label].Perimeter = 0.0;\n        \n        if(do_contour)\n        {\n            bmap[label].ContourOuter.clear();\n            bmap[label].ContourOuter.push_back(Eigen::Matrix<T2,2,1>((T2)x,(T2)y));\n        }\n    }\n    else\n    {\n        if(do_contour)\n        {\n            bmap[label].ContourInner.clear();\n            bmap[label].ContourInner.push_back(Eigen::Matrix<T2,2,1>((T2)x,(T2)y));\n        }\n    }\n    \n    if(start == 8) // isolated point, done\n    {\n        return;\n    }\n    \n    int curr = start;\n    while(1)\n    {\n        // label the point\n        vc::image::Blob<T2>& bb = bmap[label];\n        bb.SumX += krn_output.getX();\n        bb.SumY += krn_output.getY();\n        bb.Area += 1.0;\n        bb.BoundingBox.insert(krn_output.getX(), krn_output.getY());\n        \n        if(internal == false)\n        {\n            bb.Perimeter += 1.0;\n            if(do_contour)\n            {\n                bmap[label].ContourOuter.push_back(Eigen::Matrix<T2,2,1>((T2)krn_output.getX(),(T2)krn_output.getY()));\n            }\n        }\n        else\n        {\n            if(do_contour)\n            {\n                bmap[label].ContourInner.push_back(Eigen::Matrix<T2,2,1>((T2)krn_output.getX(),(T2)krn_output.getY()));\n            }\n        }\n        \n        if(krn_output(0,0) != label)\n        {\n            krn_output(0,0) = label;\n        }\n        \n        // switch tracer to the next point\n        krn_input.move(curr);\n        krn_output.move(curr);\n        \n        // get next direction\n        curr = tracer<T>(krn_input, krn_output, (curr + 5) % 8, valid_val);\n        \n        // check exit conditions\n        // isolated point\n        if(curr == 8) \n        {\n            break;\n        }\n        // came back to the same place\n        if((krn_input.getX() == x) && (krn_input.getY() == y) && (curr == start)) \n        {\n            break;\n        }\n    }\n}\n\n\n\ntemplate<typename T,typename T2>\nvc::image::BlobID vc::image::blobDetector(vc::Buffer2DView<T,vc::TargetHost>& img_thr, vc::image::BlobImageT& output, BlobMapT<T2>& bmap, T valid_val, bool do_contour)\n{\n    BlobID cur_label = 1;\n    \n    // clear output\n    for(std::size_t y = 1 ; y < output.height() ; ++y)\n    {\n        for(std::size_t x = 1 ; x < output.width() ; ++x)\n        {\n            output(x,y) = 0;\n        }\n    }\n    bmap.clear();\n    \n    vc::ImagePatch<T,vc::TargetHost> krn_input(img_thr);\n    vc::ImagePatch<BlobID,vc::TargetHost> krn_output(output);\n    \n    // go over the image, unfortunately not parallel (FIXME maybe?)\n    for(int j = 0 ; j < (int)img_thr.height() ; ++j)\n    {\n        for(int i = 0 ; i < (int)img_thr.width() ; ++i)\n        {\n            // move kernels\n            krn_input.set(i,j);\n            krn_output.set(i,j);\n            \n            if(krn_input(0,0) == valid_val) // P is black\n            {\n                // step 1\n                if((krn_input(0,-1) != valid_val) && (krn_output(0,0) == 0)) // pixel above is white and P is unlabelled\n                {\n                    // label and add to the map\n                    krn_output(0,0) = cur_label;\n                    \n                    contour_tracing<T,T2>(img_thr, output, i, j, false, bmap, valid_val, do_contour); // trace external contour\n                    \n                    cur_label++;\n                }\n                else // step 2\n                {\n                    if((krn_input(0,1) != valid_val) && (krn_output(0,1) == 0)) // pixel below white & unmarked\n                    {\n                        if(krn_output(0,0) == 0) // is not labelled\n                        {\n                            krn_output(0,0) = krn_output(-1,0); // set the same label as the previous pixel\n                        }\n                        \n                        contour_tracing<T,T2>(img_thr, output, i, j, true, bmap, valid_val, do_contour); // trace internal contour\n                    }\n                    else // step 3\n                    {\n                        if(krn_output(0,0) == 0) // not yet labelled\n                        {\n                            krn_output(0,0) = krn_output(-1,0); // set the same label as the previous pixel\n                        }\n                    }\n                    \n                    Blob<T2>& bb = bmap[krn_output(0,0)];\n                    bb.SumX += krn_output.getX();\n                    bb.SumY += krn_output.getY();\n                    bb.Area += 1.0;\n                    bb.BoundingBox.insert(krn_output.getX(), krn_output.getY());\n                }\n            }\n        }\n    }\n    \n    // calculate blob parameters\n    for(typename BlobMapT<T2>::iterator it = bmap.begin() ; it != bmap.end() ; ++it)\n    {\n        it->second.Center << it->second.SumX / it->second.Area , it->second.SumY / it->second.Area;\n        it->second.Compactness = (it->second.Perimeter * it->second.Perimeter) / (T(4.0 * M_PI) * it->second.Area);\n        it->second.Roundness = 1.0 / it->second.Compactness;\n    }\n    \n    return cur_label - 1; // number of blobs found\n}\n\n// instantiate\ntemplate vc::image::BlobID vc::image::blobDetector<uint8_t,float>(vc::Buffer2DView<uint8_t,vc::TargetHost>& img_thr, vc::image::BlobImageT& output, BlobMapT<float>& bmap, uint8_t valid_val, bool do_contour);\ntemplate vc::image::Conic<float> vc::image::estimateConic<float>(const vc::Buffer2DView<Eigen::Matrix<float,2,1>,vc::TargetHost>& grad_img, const vc::image::Blob<float>& component);\ntemplate void vc::image::computeGradient<float>(const vc::Buffer2DView<float,vc::TargetHost>& img_in, vc::Buffer2DView<Eigen::Matrix<float,2,1>, vc::TargetHost>& grad_img);\n", "meta": {"hexsha": "f8199e12824ba97c0c86ce7c35978da899b0f01b", "size": 11666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sources/Image/ConnectedComponents.cpp", "max_stars_repo_name": "lukier/vision_core", "max_stars_repo_head_hexsha": "45cb1bf7b74e1e1d5aa1078494a328b317d5a368", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2016-10-30T23:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T12:27:40.000Z", "max_issues_repo_path": "sources/Image/ConnectedComponents.cpp", "max_issues_repo_name": "jczarnowski/vision_core", "max_issues_repo_head_hexsha": "924c53339b1d99ebb3b1e358edfaa1a4e8d3703b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T04:45:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T01:32:22.000Z", "max_forks_repo_path": "sources/Image/ConnectedComponents.cpp", "max_forks_repo_name": "lukier/vision_core", "max_forks_repo_head_hexsha": "45cb1bf7b74e1e1d5aa1078494a328b317d5a368", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-14T00:46:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T08:55:11.000Z", "avg_line_length": 36.6855345912, "max_line_length": 207, "alphanum_fraction": 0.537287845, "num_tokens": 3187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4243954719831474}}
{"text": "//\n// Created by Arnie on 2016-11-15.\n//\n\n#include \"dtm.h\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <sstream>\n#include <fstream>\n#include <utility>\n#include <functional>\n#include <algorithm>\n#include <cmath>\nusing namespace std;\n\nVectorXf get_mvn_samples(VectorXf mean, MatrixXf cov) {\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> eigenSolver(cov);\n  normal_distribution<float> dist(0, 1);\n  default_random_engine gen;\n  auto std_norm = [&] (float) {return dist(gen);};\n  return mean + eigenSolver.eigenvectors() * eigenSolver\n      .eigenvalues().cwiseSqrt().asDiagonal() *\n      VectorXf::NullaryExpr(mean.size(), std_norm);\n}\n\nstatic float gaussianVar(float mean, float std_dev) {\n  default_random_engine generator;\n  normal_distribution<float> distribution(mean, std_dev);\n  return distribution(generator);\n}\n\nstatic VectorXf softmax(VectorXf weights) {\n  size_t K = weights.size();\n  VectorXf soft(K);\n  float MAX = weights[0];\n  float norm = 0.0;\n  for (size_t i = 0; i < K; i++) {\n    if (weights(i) > MAX)\n      MAX = weights(i);\n  }\n\n  for (size_t i = 0; i < K; i++)   {\n    norm += exp(weights(i) - MAX);\n  }\n\n  for (size_t i = 0; i < K; i++) {\n    soft(i) = exp(weights(i) - MAX) / (norm + 0.00001);\n    if (soft(i) < 1e-30) {\n      soft(i) = 0.0;\n    }\n  }\n\n  return soft;\n}\n\nvoid DTM::build_alias_table(size_t t, size_t w) {\n  AliasSamples term(phi[t].row(w));\n  term_alias_samples[t][w] = term.get_samples(K);\n}\n\nDTM::DTM(const vector<vector<vector<size_t>>> &data, const vector<string> &\ndictionary,\n         size_t num_topics, float sgld_a, float sgld_b, float sgld_c,\n         float dtm_phi_var, float dtm_eta_var, float dtm_alpha_var) : W(data),\n         vocabulary(dictionary), K(num_topics), sgld_a(sgld_a), sgld_b(sgld_b),\n         sgld_c(sgld_c), dtm_phi_var(dtm_phi_var), dtm_eta_var(dtm_eta_var),\n         dtm_alpha_var(dtm_alpha_var) {\n  V = vocabulary.size();\n  T = W.size();\n  D = vector<size_t>(T);\n  Z = vector<vector<vector<size_t>>>(T);\n  term_alias_samples =\n      vector<vector<vector<size_t>>>\n          (T, vector<vector<size_t>> (V, vector<size_t>(K)));\n  sample_indices = vector<vector<size_t>>(T, vector<size_t>(V));\n\n\n  CDK = vector<MatrixXf> (T);\n  CWK = vector<MatrixXf> (T, MatrixXf::Zero(V, K));\n  CK = MatrixXf::Zero(T, K);\n  phi = vector<MatrixXf>(T, MatrixXf::Zero(V, K));\n  eta = vector<MatrixXf>(T);\n  alpha = MatrixXf::Zero(T, K);\n\n  for (size_t t = 0; t < T; ++t) {\n    D[t] = W[t].size();\n    Z[t] = vector<vector<size_t>>(D[t]);\n    eta[t] = MatrixXf::Zero(D[t], K);\n    CDK[t] = MatrixXf::Zero(D[t], K);\n    for (size_t d = 0; d < D[t]; ++d) {\n      Z[t][d] = vector<size_t>(W[t][d].size());\n    }\n  }\n}\n\nvoid DTM::initialize(bool init_with_lda) {\n  default_random_engine generator;\n  uniform_int_distribution<size_t> uniform_topic(0, K - 1);\n  u01 = uniform_real_distribution<float>(0, 1);\n  float init_alpha = 50.0 / K;\n  float init_beta = 0.01;\n  for (size_t t = 0; t < T; ++t) {\n    for (size_t d = 0; d < D[t]; ++d) {\n      size_t N = W[t][d].size();\n      for (size_t n = 0; n < N; ++n) {\n        size_t w = W[t][d][n];\n        size_t k = uniform_topic(generator);\n        Z[t][d][n] = k;\n        CDK[t](d, k)++;\n        CWK[t](w, k)++;\n        CK(t, k)++;\n        eta[t](d, k) += (1 + init_alpha) / (N + K * init_alpha);\n      }\n    }\n  }\n\n  if (init_with_lda) {\n    size_t t = 0;\n    for (size_t iter = 0; iter < 50; iter++) {\n      cout << \"LDA Iter: \" << iter << endl;\n      for (size_t d = 0; d < D[t]; ++d) {\n        for (size_t n = 0; n < W[t][d].size(); n++) {\n          size_t k = Z[t][d][n];\n          size_t w = W[t][d][n];\n          CDK[t](d, k)--;\n          CWK[t](w, k)--;\n          CK(t, k)--;\n\n          vector<float> prob(K);\n          for (k = 0; k < K; k++) {\n            prob[k] = (CDK[t](d, k) + init_alpha) * ((CWK[t](w, k) + init_beta)\n                / (CK(t, k) + V * init_beta));\n          }\n          discrete_distribution<size_t> mult(prob.begin(), prob.end());\n          k = mult(generator);\n          Z[t][d][n] = k;\n          CDK[t](d, k)++;\n          CWK[t](w, k)++;\n          CK(t, k)++;\n        }\n      }\n    }\n  }\n  for (size_t t = 0; t < T; t++) {\n    for (size_t w = 0; w < V; w++) {\n      for (size_t k = 0; k < K; k++) {\n        phi[t](w, k) = (CWK[0](w, k) + init_beta) / (CK(0, k) + V * init_beta);\n      }\n      build_alias_table(t, w);\n    }\n  }\n}\n\nvoid DTM::estimate(size_t num_iters) {\n  default_random_engine generator;\n  for (size_t iter = 0; iter < num_iters; iter++) {\n    cout << \"Iteration \" << iter << endl;\n    float eps = sgld_a * (pow(sgld_b + iter, -sgld_c));\n    float xi = gaussianVar(0.0, pow(eps, 2));\n    VectorXf xi_vec;\n    VectorXf mean(K);\n    for (size_t t = 0; t < T; t++) {\n      xi_vec = VectorXf::Constant(K, xi);\n      for (size_t d = 0; d < D[t]; d++) {\n        size_t N = W[t][d].size();\n        uniform_int_distribution<size_t> doc_dist(0, N - 1);\n\n        // estimate eta\n        VectorXf soft_eta = softmax(eta[t].row(d));\n        VectorXf prior_eta = (alpha.row(t) - eta[t].row(d)) / dtm_eta_var;\n        VectorXf denom_eta = N * soft_eta;\n        VectorXf grad_eta = CDK[t].row(d).transpose() - denom_eta;\n        eta[t].row(d) += ((eps / 2) * (grad_eta + prior_eta)) + xi_vec;\n\n\n        for (size_t n = 0; n < N; n++) {\n          for (size_t mh = 0; mh < 4; mh++) {\n            size_t k = Z[t][d][n];\n            size_t w = W[t][d][n];\n            CDK[t](d, k)--;\n            CWK[t](w, k)--;\n            CK(t, k)--;\n\n            size_t proposal;\n            float acceptance_prob = 0.0;\n            if (mh % 2 == 0) {\n              // Z-proposal\n              size_t index = doc_dist(generator);\n              proposal = Z[t][d][index];\n\n              acceptance_prob =\n                  exp(phi[t](w, proposal)) / exp(phi[t](w, k));\n            } else {\n              if (sample_indices[t][w] >= K) {\n                build_alias_table(t, w);\n                sample_indices[t][w] = 0;\n              }\n              proposal = term_alias_samples[t][w][sample_indices[t][w]];\n              sample_indices[t][w]++;\n              acceptance_prob = exp(eta[t](d, proposal)) / exp(eta[t](d, k));\n            }\n            acceptance_prob = acceptance_prob > 1.0 ? 1.0 : acceptance_prob;\n            if (u01(generator) >= acceptance_prob) {\n              // reject proposal\n              proposal = k;\n            }\n            Z[t][d][n] = proposal;\n            CDK[t](d, proposal)++;\n            CWK[t](w, proposal)++;\n            CK(t, proposal)++;\n          }\n        }\n      }\n\n      xi_vec = VectorXf::Constant(V, xi);\n      for (unsigned k = 0; k < K; ++k) {\n        // sample phi\n        VectorXf soft_phi = softmax(phi[t].col(k));\n        VectorXf prior_phi(V);\n        if (t == 0) {\n          float phi_sigma = 1.0 / ((1.0 / 100) + (1 / dtm_phi_var));\n          prior_phi = phi[t + 1].col(k) * (phi_sigma / dtm_phi_var);\n          prior_phi = ((2 * prior_phi) - 2 * phi[t].col(k)) / dtm_phi_var;\n        } else if (t == T - 1) {\n          prior_phi = (phi[t - 1].col(k) - phi[t].col(k)) / dtm_phi_var;\n        } else {\n          prior_phi = (phi[t + 1].col(k) + phi[t - 1].col(k) - 2 * phi[t].col\n              (k)) / dtm_phi_var;\n        }\n\n        VectorXf denom_phi = CK(t, k) * soft_phi;\n        VectorXf grad_phi = CWK[t].col(k) - denom_phi;\n\n        phi[t].col(k) += ((eps / 2) * (grad_phi + prior_phi)) + xi_vec;\n      }\n\n      // sample alpha\n      VectorXf alpha_bar(K);\n      float alpha_precision = 0.0;  // designed to be a diagonal matrix\n      MatrixXf cov = MatrixXf::Identity(K, K);\n      if (t == 0) {\n        alpha_precision = (1.0 / 100) + (1 / dtm_alpha_var);\n        float alpha_sigma = 1.0 / alpha_precision;\n        alpha_bar = alpha.row(t+1) * (alpha_sigma / dtm_alpha_var);\n      } else if (t == T-1) {\n        alpha_bar = (alpha.row(t-1) - alpha.row(t)) / dtm_alpha_var;\n        alpha_precision = 1.0 / dtm_alpha_var;\n      } else {\n        alpha_precision = (2 / dtm_alpha_var);\n        alpha_bar = (alpha.row(t+1) - alpha.row(t-1)) / 2;\n      }\n      VectorXf eta_bar = eta[t].colwise().sum();\n      float sigma = 1.0 / (1.0 / alpha_precision + (D[t] / dtm_eta_var));\n      cov *= sigma;\n      mean = (alpha_bar / alpha_precision + (eta_bar / dtm_eta_var)) * sigma;\n      alpha.row(t) = get_mvn_samples(mean, cov);\n      if (iter % 5 == 0) {\n        diagnosis(t);\n      }\n    }\n  }\n}\n\nvoid DTM::diagnosis(size_t t) {\n  float perp = 0.0;\n  unsigned N = 0;\n  float total_log_likelihood = 0.0;\n  vector<VectorXf> softmax_phi(K);\n  vector<VectorXf> softmax_eta(D[t]);\n  for (size_t k = 0; k < K; ++k) {\n    softmax_phi[k] = softmax(phi[t].col(k));\n  }\n  for (size_t d = 0; d < D[t]; d++) {\n    N += W[t][d].size();\n    softmax_eta[d] = softmax(eta[t].row(d));\n    for (size_t n = 0; n < W[t][d].size(); n++) {\n      float likelihood = 0.0;\n      size_t w = W[t][d][n];\n      for (size_t k = 0; k < K; k++) {\n        likelihood += ((softmax_eta[d](k) * (softmax_phi[k](w))));\n        if (likelihood < 0)\n          std::cout << \"Likelihood less than 0, error\" << std::endl;\n      }\n      total_log_likelihood += log(likelihood);\n    }\n  }\n  cout << \"Perplexity: \" <<  t << \"  \"\n       << exp(-total_log_likelihood / N) << endl;\n}\n\nvoid DTM::save_data(string dir) {\n  for (size_t t = 0; t < T; ++t) {\n    stringstream sstm;\n    sstm << dir << \"/time_slice_\" << t << \".txt\";\n    string fname = sstm.str();\n    ofstream myfile;\n\n    myfile.open(fname.c_str());\n    for (size_t k = 0; k < K; ++k) {\n      vector<pair<float, size_t>> ranking;\n      for (size_t v = 0; v < V; v++) {\n        ranking.push_back(make_pair(phi[t](v, k), v));\n      }\n      sort(ranking.begin(), ranking.end(),\n           std::greater<pair<float, size_t>>());\n      myfile << \"Topic \" << k << \"\\n\";\n      for (size_t v = 0; v < 10; v++) {\n        size_t w = ranking[v].second;\n        myfile << \"(\" << vocabulary[w] << \", \" << phi[t](w, k) << \")\" << endl;\n      }\n      myfile << endl;\n    }\n    myfile.close();\n  }\n}", "meta": {"hexsha": "9a6201ccbe9cb5ec61f93dcac369e27d94e60cb1", "size": 9969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dtm.cpp", "max_stars_repo_name": "alexismailov2/FastDFM", "max_stars_repo_head_hexsha": "2628d0296f35264655d1245f3648e84589b99148", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dtm.cpp", "max_issues_repo_name": "alexismailov2/FastDFM", "max_issues_repo_head_hexsha": "2628d0296f35264655d1245f3648e84589b99148", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dtm.cpp", "max_forks_repo_name": "alexismailov2/FastDFM", "max_forks_repo_head_hexsha": "2628d0296f35264655d1245f3648e84589b99148", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6476190476, "max_line_length": 79, "alphanum_fraction": 0.5189086167, "num_tokens": 3170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4243954719831474}}
{"text": "/*\r\n *  Copyright 2011-2015 Maxim Milakov\r\n *\r\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  you may not use this file except in compliance with the License.\r\n *  You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n *  Unless required by applicable law or agreed to in writing, software\r\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  See the License for the specific language governing permissions and\r\n *  limitations under the License.\r\n */\r\n\r\n#include \"roc_result.h\"\r\n\r\n#include <boost/format.hpp>\r\n#include <algorithm>\r\n#include <numeric>\r\n\r\nnamespace nnforge\r\n{\r\n\troc_result::roc_result(\r\n\t\tconst output_neuron_value_set& predicted_value_set,\r\n\t\tconst output_neuron_value_set& actual_value_set,\r\n\t\tfloat threshold,\r\n\t\tfloat beta,\r\n\t\tunsigned int segment_count,\r\n\t\tfloat min_val,\r\n\t\tfloat max_val)\r\n\t\t: segment_count(segment_count)\r\n\t\t, min_val(min_val)\r\n\t\t, max_val(max_val)\r\n\t\t, threshold(threshold)\r\n\t\t, beta(beta)\r\n\t\t, actual_positive_elem_count(0)\r\n\t\t, actual_negative_elem_count(0)\r\n\t\t, values_for_positive_elems(segment_count)\r\n\t\t, values_for_negative_elems(segment_count)\r\n\t{\r\n\t\tfloat mult = 1.0F / (max_val - min_val);\r\n\t\tfloat segment_count_f = static_cast<float>(segment_count);\r\n\t\tstd::vector<std::vector<float> >::const_iterator predicted_it = predicted_value_set.neuron_value_list.begin();\r\n\t\tfor(std::vector<std::vector<float> >::const_iterator actual_it = actual_value_set.neuron_value_list.begin();\r\n\t\t\tactual_it != actual_value_set.neuron_value_list.end();\r\n\t\t\tactual_it++, predicted_it++)\r\n\t\t{\r\n\t\t\tconst std::vector<float>& actual_value_list = *actual_it;\r\n\t\t\tconst std::vector<float>& predicted_value_list = *predicted_it;\r\n\r\n\t\t\tstd::vector<float>::const_iterator predicted_value_it = predicted_value_list.begin();\r\n\t\t\tfor(std::vector<float>::const_iterator actual_value_it = actual_value_list.begin();\r\n\t\t\t\tactual_value_it != actual_value_list.end();\r\n\t\t\t\tactual_value_it++, predicted_value_it++)\r\n\t\t\t{\r\n\t\t\t\tfloat actual_value = *actual_value_it;\r\n\t\t\t\tfloat predicted_value = *predicted_value_it;\r\n\r\n\t\t\t\tunsigned int bucket_id = std::min<unsigned int>(static_cast<unsigned int>(std::max<float>(std::min<float>((predicted_value - min_val) * mult, 1.0F), 0.0F) * segment_count_f), (segment_count - 1));\r\n\r\n\t\t\t\tif (actual_value > 0.0F)\r\n\t\t\t\t{\r\n\t\t\t\t\tvalues_for_positive_elems[bucket_id]++;\r\n\t\t\t\t\tactual_positive_elem_count++;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvalues_for_negative_elems[bucket_id]++;\r\n\t\t\t\t\tactual_negative_elem_count++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tfloat roc_result::get_accuracy() const\r\n\t{\r\n\t\tunsigned int starting_segment_id = static_cast<unsigned int>(std::max(std::min((threshold - min_val) / (max_val - min_val), 1.0F), 0.0F) * static_cast<float>(segment_count));\r\n\r\n\t\tunsigned int true_positive = std::accumulate(values_for_positive_elems.begin() + starting_segment_id, values_for_positive_elems.end(), 0);\r\n\t\tunsigned int true_negative = std::accumulate(values_for_negative_elems.begin(), values_for_negative_elems.begin() + starting_segment_id, 0);\r\n\r\n\t\treturn static_cast<float>(true_positive + true_negative) / static_cast<float>(actual_positive_elem_count + actual_negative_elem_count);\r\n\t}\r\n\r\n\tfloat roc_result::get_f_score() const\r\n\t{\r\n\t\tunsigned int starting_segment_id = static_cast<unsigned int>(std::max(std::min((threshold - min_val) / (max_val - min_val), 1.0F), 0.0F) * static_cast<float>(segment_count));\r\n\r\n\t\tunsigned int true_positive = std::accumulate(values_for_positive_elems.begin() + starting_segment_id, values_for_positive_elems.end(), 0);\r\n\t\tunsigned int false_positive = std::accumulate(values_for_negative_elems.begin() + starting_segment_id, values_for_negative_elems.end(), 0);\r\n\t\t// unsigned int true_negative = std::accumulate(values_for_negative_elems.begin(), values_for_negative_elems.begin() + starting_segment_id, 0);\r\n\t\tunsigned int false_negative = std::accumulate(values_for_positive_elems.begin(), values_for_positive_elems.begin() + starting_segment_id, 0);\r\n\r\n\t\treturn (1.0F + beta * beta) * static_cast<float>(true_positive) /\r\n\t\t\t((1.0F + beta * beta) * static_cast<float>(true_positive) + (beta * beta) * static_cast<float>(false_negative) + static_cast<float>(false_positive));\r\n\t}\r\n\r\n\tfloat roc_result::get_precision() const\r\n\t{\r\n\t\tunsigned int starting_segment_id = static_cast<unsigned int>(std::max(std::min((threshold - min_val) / (max_val - min_val), 1.0F), 0.0F) * static_cast<float>(segment_count));\r\n\r\n\t\tunsigned int true_positive = std::accumulate(values_for_positive_elems.begin() + starting_segment_id, values_for_positive_elems.end(), 0);\r\n\t\tunsigned int false_positive = std::accumulate(values_for_negative_elems.begin() + starting_segment_id, values_for_negative_elems.end(), 0);\r\n\r\n\t\treturn static_cast<float>(true_positive) / (static_cast<float>(true_positive) + static_cast<float>(false_positive));\r\n\t}\r\n\r\n\tfloat roc_result::get_recall() const\r\n\t{\r\n\t\tunsigned int starting_segment_id = static_cast<unsigned int>(std::max(std::min((threshold - min_val) / (max_val - min_val), 1.0F), 0.0F) * static_cast<float>(segment_count));\r\n\r\n\t\tunsigned int true_positive = std::accumulate(values_for_positive_elems.begin() + starting_segment_id, values_for_positive_elems.end(), 0);\r\n\t\tunsigned int false_negative = std::accumulate(values_for_positive_elems.begin(), values_for_positive_elems.begin() + starting_segment_id, 0);\r\n\r\n\t\treturn static_cast<float>(true_positive) / (static_cast<float>(true_positive) + static_cast<float>(false_negative));\r\n\t}\r\n\r\n\tfloat roc_result::get_auc() const\r\n\t{\r\n\t\tstd::vector<float> true_positive_rates;\r\n\t\t{\r\n\t\t\tunsigned int current_positive_elems_count = 0;\r\n\t\t\tfloat mult = 1.0F / static_cast<float>(actual_positive_elem_count);\r\n\t\t\tfor(std::vector<unsigned int>::const_reverse_iterator it = values_for_positive_elems.rbegin(); it != values_for_positive_elems.rend(); ++it)\r\n\t\t\t{\r\n\t\t\t\tcurrent_positive_elems_count += *it;\r\n\t\t\t\ttrue_positive_rates.push_back(mult * static_cast<float>(current_positive_elems_count));\r\n\t\t\t}\r\n\t\t}\r\n\t\ttrue_positive_rates.push_back(1.0F);\r\n\r\n\t\tstd::vector<float> false_positive_rates;\r\n\t\t{\r\n\t\t\tunsigned int current_negative_elems_count = 0;\r\n\t\t\tfloat mult = 1.0F / static_cast<float>(actual_negative_elem_count);\r\n\t\t\tfor(std::vector<unsigned int>::const_reverse_iterator it = values_for_negative_elems.rbegin(); it != values_for_negative_elems.rend(); ++it)\r\n\t\t\t{\r\n\t\t\t\tcurrent_negative_elems_count += *it;\r\n\t\t\t\tfalse_positive_rates.push_back(mult * static_cast<float>(current_negative_elems_count));\r\n\t\t\t}\r\n\t\t}\r\n\t\tfalse_positive_rates.push_back(1.0F);\r\n\r\n\t\tfloat sum = 0.0F;\r\n\t\tfloat previous_fpr = 0.0F;\r\n\t\tfloat previous_tpr = 0.0F;\r\n\t\tstd::vector<float>::const_iterator tpr_it = true_positive_rates.begin();\r\n\t\tfor(std::vector<float>::const_iterator fpr_it = false_positive_rates.begin(); fpr_it != false_positive_rates.end(); ++fpr_it, ++tpr_it)\r\n\t\t{\r\n\t\t\tfloat current_fpr = *fpr_it;\r\n\t\t\tfloat current_tpr = *tpr_it;\r\n\r\n\t\t\tif (current_fpr != previous_fpr)\r\n\t\t\t\tsum += (current_fpr - previous_fpr) * (previous_tpr + current_tpr) * 0.5F;\r\n\r\n\t\t\tprevious_fpr = current_fpr;\r\n\t\t\tprevious_tpr = current_tpr;\r\n\t\t}\r\n\r\n\t\treturn sum;\r\n\t}\r\n\r\n\tstd::ostream& operator<< (std::ostream& out, const roc_result& val)\r\n\t{\r\n\t\tout << (boost::format(\"AUC %|1$.5f|, (using threshold %|2$.3f|) Accuracy %|3$.5f|, Precision %|4$.5f|, Recall %|5$.5f|, F-score %|6$.5f| (beta %|7$.3f|)\") % val.get_auc() % val.threshold % val.get_accuracy() % val.get_precision() % val.get_recall() % val.get_f_score() % val.beta).str();\r\n\r\n\t\treturn out;\r\n\t}\r\n}\r\n", "meta": {"hexsha": "2ab0b9cd078459cf736837641e775c6e3e8d5f03", "size": 7660, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nnforge/roc_result.cpp", "max_stars_repo_name": "anshumang/nnForgeINST", "max_stars_repo_head_hexsha": "1e9ea1b539cadbb03daa39f5d81025c1b17c21d8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-08-19T08:02:59.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-18T21:10:36.000Z", "max_issues_repo_path": "nnforge/roc_result.cpp", "max_issues_repo_name": "anshumang/nnForgeINST", "max_issues_repo_head_hexsha": "1e9ea1b539cadbb03daa39f5d81025c1b17c21d8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nnforge/roc_result.cpp", "max_forks_repo_name": "anshumang/nnForgeINST", "max_forks_repo_head_hexsha": "1e9ea1b539cadbb03daa39f5d81025c1b17c21d8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5348837209, "max_line_length": 290, "alphanum_fraction": 0.7257180157, "num_tokens": 1911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4243954657834915}}
{"text": "#include \"hoCuNDArray_utils.h\"\n#include \"cuNDArray_fileio.h\"\n#include \"cuNDArray_math.h\"\n#include \"imageOperator.h\"\n#include \"hoPartialDerivativeOperator.h\"\n#include \"hoCuConebeamProjectionOperator.h\"\n#include \"cgSolver.h\"\n#include \"hoCuGPBBSolver.h\"\n#include \"hoCuNCGSolver.h\"\n#include \"hoCuPartialDerivativeOperator.h\"\n#include \"CBSubsetOperator.h\"\n#include \"osSPSSolver.h\"\n#include \"osMOMSolverF.h\"\n#include <boost/program_options.hpp>\n#include \"osPDsolver.h\"\n#include \"hdf5_utils.h\"\n#include \"cuEdgeATrousOperator.h\"\n#include \"cuDCTOperator.h\"\n#include \"cuNCGSolver.h\"\n#include \"subselectionOperator.h\"\n#include \"solver_utils.h\"\n#include \"cuSolverUtils.h\"\n#include \"osMOMSolverDual.h\"\nusing namespace std;\nusing namespace Gadgetron;\n\nnamespace po = boost::program_options;\n\n\nboost::shared_ptr<cuNDArray<float> > calculate_prior(boost::shared_ptr<CBCT_binning>  binning,boost::shared_ptr<CBCT_acquisition> ps, hoCuNDArray<float>& projections, std::vector<size_t> is_dims, floatd3 imageDimensions){\n\tstd::cout << \"Calculating FDK prior\" << std::endl;\n\tboost::shared_ptr<CBCT_binning> binning_pics=binning->get_3d_binning();\n\tstd::vector<size_t> is_dims3d = is_dims;\n\tis_dims3d.pop_back();\n\tboost::shared_ptr< hoCuConebeamProjectionOperator >\n\tEp( new hoCuConebeamProjectionOperator() );\n\tEp->setup(ps,binning_pics,imageDimensions);\n\tEp->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\tEp->set_domain_dimensions(&is_dims3d);\n\tEp->set_use_filtered_backprojection(true);\n\tboost::shared_ptr<hoCuNDArray<float> > prior3d(new hoCuNDArray<float>(&is_dims3d));\n\tEp->mult_MH(&projections,prior3d.get());\n\n\thoCuNDArray<float> tmp_proj(*ps->get_projections());\n\tEp->mult_M(prior3d.get(),&tmp_proj);\n\tfloat s = dot(ps->get_projections().get(),&tmp_proj)/dot(&tmp_proj,&tmp_proj);\n\t*prior3d *= s;\n\tboost::shared_ptr<cuNDArray<float> > prior(new cuNDArray<float>(*expand( prior3d.get(), is_dims.back() )));\n\tstd::cout << \"Prior complete\" << std::endl;\n\treturn prior;\n}\n\n\nboost::shared_ptr<cuNDArray<float>> calculate_weightImage(boost::shared_ptr<CBCT_binning>  binning,boost::shared_ptr<CBCT_acquisition> ps, hoCuNDArray<float>& ho_projections, std::vector<size_t> is_dims, floatd3 imageDimensions){\n\n\tcuNDArray<float> projections(ho_projections);\n\tboost::shared_ptr<CBCT_binning> binning_pics=binning->get_3d_binning();\n\tstd::vector<size_t> is_dims3d = is_dims;\n\tis_dims3d.pop_back();\n\tauto Ep = boost::make_shared<cuConebeamProjectionOperator>();\n\tauto ps2 = boost::make_shared<CBCT_acquisition>(boost::shared_ptr<hoCuNDArray<float>>(),ps->get_geometry());\n\tEp->setup(ps2,binning_pics,imageDimensions);\n\tEp->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\tEp->set_domain_dimensions(&is_dims3d);\n\t//Ep->set_use_filtered_backprojection(true);\n\tEp->offset_correct(&projections);\n\t//Ep->mult_MH(&projections,prior3d.get());\n\t//cgSolver<hoCuNDArray<float>> solv;\n\tcuNCGSolver<float> solv;\n\tsolv.set_non_negativity_constraint(true);\n\tsolv.set_encoding_operator(Ep);\n\tsolv.set_max_iterations(10);\n\tauto prior3d = solv.solve(&projections);\n\t//auto prior3d = boost::make_shared<cuNDArray<float>>(is_dims3d);\n\twrite_nd_array(prior3d.get(),\"fdk.real\");\n\tcuNDArray<float> tmp_proj(projections);\n\tclear(&tmp_proj);\n\tEp->mult_M(prior3d.get(),&tmp_proj);\n\t//float s = dot(ps->get_projections().get(),&tmp_proj)/dot(&tmp_proj,&tmp_proj);\n\t//std::cout << \"Scaling \" << s << std::endl;\n\t/*\n\t //Ep->offset_correct(&tmp_proj);\n\t//tmp_proj *= s;\n\twrite_nd_array(&tmp_proj,\"projtmp.real\");\n\ttmp_proj -= projections;\n\ttmp_proj *= float(-1);\n\tabs_inplace(&tmp_proj);\n\n\twrite_nd_array(ps->get_projections().get(),\"proj.real\");\n\twrite_nd_array(&tmp_proj,\"projdiff.real\");\n\tstd::cout << \"Proj size \";\n\tauto pdims = *tmp_proj.get_dimensions();\n\tfor (auto p : pdims ) std::cout << p << \" \";\n\tstd::cout << std::endl;\n\t//Ep->set_use_filtered_backprojection(false);\n\t//Ep->mult_MH(&tmp_proj,prior3d.get());\n\t//solv.set_non_negativity_constraint(false);\n\tprior3d = solv.solve(&tmp_proj);\n\t//abs_inplace(prior.get());\n\tstd::cout << \"Prior complete\" << std::endl;\n\t */\n\treturn prior3d;\n}\n\n\nint main(int argc, char** argv)\n{\n\tstring acquisition_filename;\n\tstring outputFile;\n\tuintd3 imageSize;\n\tfloatd3 voxelSize;\n\tint device;\n\tunsigned int iterations;\n\tfloatd2 scale_factor;\n\tunsigned int subsets;\n\tfloat rho;\n\tfloat tv_weight,pics_weight, wavelet_weight,huber,sigma,dct_weight;\n\n\tpo::options_description desc(\"Allowed options\");\n\n\tdesc.add_options()\n    \t\t\t\t\t\t(\"help\", \"produce help message\")\n    \t\t\t\t\t\t(\"acquisition,a\", po::value<string>(&acquisition_filename)->default_value(\"acquisition.hdf5\"), \"Acquisition data\")\n    \t\t\t\t\t\t(\"samples,n\",po::value<unsigned int>(),\"Number of samples per ray\")\n    \t\t\t\t\t\t(\"output,f\", po::value<string>(&outputFile)->default_value(\"reconstruction.hdf5\"), \"Output filename\")\n    \t\t\t\t\t\t(\"size,s\",po::value<uintd3>(&imageSize)->default_value(uintd3(512,512,1)),\"Image size in pixels\")\n    \t\t\t\t\t\t(\"binning,b\",po::value<string>(),\"Binning file for 4d reconstruction\")\n    \t\t\t\t\t\t(\"SAG\",\"Use exact SAG correction if present\")\n    \t\t\t\t\t\t(\"voxelSize,v\",po::value<floatd3>(&voxelSize)->default_value(floatd3(0.488f,0.488f,1.0f)),\"Voxel size in mm\")\n    \t\t\t\t\t\t(\"dimensions,d\",po::value<floatd3>(),\"Image dimensions in mm. Overwrites voxelSize.\")\n    \t\t\t\t\t\t(\"iterations,i\",po::value<unsigned int>(&iterations)->default_value(10),\"Number of iterations\")\n    \t\t\t\t\t\t(\"device\",po::value<int>(&device)->default_value(0),\"Number of the device to use (0 indexed)\")\n\t     \t\t\t\t\t (\"downsample,D\",po::value<floatd2>(&scale_factor)->default_value(floatd2(1,1)),\"Downsample projections this factor\")\n    \t\t\t\t\t\t(\"subsets,u\",po::value<unsigned int>(&subsets)->default_value(10),\"Number of subsets to use\")\n    \t\t\t\t\t\t(\"TV\",po::value<float>(&tv_weight)->default_value(0),\"Total variation weight\")\n    \t\t\t\t\t\t(\"PICS\",po::value<float>(&pics_weight)->default_value(0),\"PICS weight\")\n    \t\t\t\t\t\t(\"Wavelet,W\",po::value<float>(&wavelet_weight)->default_value(0),\"Weight of the wavelet operator\")\n    \t\t\t\t\t\t(\"Huber\",po::value<float>(&huber)->default_value(0),\"Huber weight\")\n    \t\t\t\t\t\t(\"use_prior\",\"Use an FDK prior\")\n    \t\t\t\t\t\t(\"sigma\",po::value<float>(&sigma)->default_value(0.001),\"Sigma for billateral filter\")\n    \t\t\t\t\t\t(\"DCT\",po::value<float>(&dct_weight)->default_value(0),\"DCT regularization\")\n    \t\t\t\t\t\t(\"3D\",\"Only use binning for selecting valid projections\")\n    \t\t\t\t\t\t;\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t\tcout << desc << \"\\n\";\n\t\treturn 1;\n\t}\n\n\tstd::stringstream command_line_string;\n\tstd::cout << \"Command line options:\" << std::endl;\n\tfor (po::variables_map::iterator it = vm.begin(); it != vm.end(); ++it){\n\t\tboost::any a = it->second.value();\n\t\tcommand_line_string << it->first << \": \";\n\t\tif (a.type() == typeid(std::string)) command_line_string << it->second.as<std::string>();\n\t\telse if (a.type() == typeid(int)) command_line_string << it->second.as<int>();\n\t\telse if (a.type() == typeid(unsigned int)) command_line_string << it->second.as<unsigned int>();\n\t\telse if (a.type() == typeid(float)) command_line_string << it->second.as<float>();\n\t\telse if (a.type() == typeid(vector_td<float,3>)) command_line_string << it->second.as<vector_td<float,3> >();\n\t\telse if (a.type() == typeid(vector_td<int,3>)) command_line_string << it->second.as<vector_td<int,3> >();\n\t\telse if (a.type() == typeid(vector_td<unsigned int,3>)) command_line_string << it->second.as<vector_td<unsigned int,3> >();\n\t\telse command_line_string << \"Unknown type\" << std::endl;\n\t\tcommand_line_string << std::endl;\n\t}\n\tstd::cout << command_line_string.str();\n\n\tcudaSetDevice(device);\n\n\t//Really weird stuff. Needed to initialize the device?? Should find real bug.\n\tcudaDeviceManager::Instance()->lockHandle();\n\tcudaDeviceManager::Instance()->unlockHandle();\n\n\tboost::shared_ptr<CBCT_acquisition> ps(new CBCT_acquisition());\n\tps->load(acquisition_filename);\n\tps->get_geometry()->print(std::cout);\n    if (scale_factor[0] != 1 || scale_factor[1] != 1)\n        ps->downsample(scale_factor[0],scale_factor[1]);\n\n\tfloat SDD = ps->get_geometry()->get_SDD();\n\tfloat SAD = ps->get_geometry()->get_SAD();\n\n\tboost::shared_ptr<CBCT_binning> binning(new CBCT_binning());\n\tif (vm.count(\"binning\")){\n\t\tstd::cout << \"Loading binning data\" << std::endl;\n\t\tbinning->load(vm[\"binning\"].as<string>());\n\t\tif (vm.count(\"3D\"))\n\t\t\tbinning = binning->get_3d_binning();\n\t} else binning->set_as_default_3d_bin(ps->get_projections()->get_size(2));\n\tbinning->print(std::cout);\n\n\tfloatd3 imageDimensions;\n\tif (vm.count(\"dimensions\")){\n\t\timageDimensions = vm[\"dimensions\"].as<floatd3>();\n\t\tvoxelSize = imageDimensions/imageSize;\n\t}\n\telse imageDimensions = voxelSize*imageSize;\n\n\tfloat lengthOfRay_in_mm = norm(imageDimensions);\n\tunsigned int numSamplesPerPixel = 3;\n\tfloat minSpacing = min(voxelSize)/numSamplesPerPixel;\n\n\tunsigned int numSamplesPerRay;\n\tif (vm.count(\"samples\")) numSamplesPerRay = vm[\"samples\"].as<unsigned int>();\n\telse numSamplesPerRay = ceil( lengthOfRay_in_mm / minSpacing );\n\n\tfloat step_size_in_mm = lengthOfRay_in_mm / numSamplesPerRay;\n\tsize_t numProjs = ps->get_projections()->get_size(2);\n\tsize_t needed_bytes = 2 * prod(imageSize) * sizeof(float);\n\tstd::vector<size_t> is_dims = to_std_vector((uint64d3)imageSize);\n\n\tstd::cout << \"IS dimensions \" << is_dims[0] << \" \" << is_dims[1] << \" \" << is_dims[2] << std::endl;\n\tstd::cout << \"Image size \" << imageDimensions << std::endl;\n\n\tis_dims.push_back(binning->get_number_of_bins());\n\n\tstd::vector<size_t> double_dims = is_dims;\n\tdouble_dims.push_back(2);\n\n\t//osLALMSolver<cuNDArray<float>> solver;\n\tosMOMSolverDual<cuNDArray<float>> solver;\n\t//osAHZCSolver<cuNDArray<float>> solver;\n\t//osMOMSolverF<cuNDArray<float>> solver;\n\t//ADMMSolver<cuNDArray<float>> solver;\n\tsolver.set_dump(false);\n\n\n\tboost::shared_ptr<cuNDArray<float>> prior;\n\tif (vm.count(\"use_prior\") || pics_weight > 0) {\n\t\tauto projections = *ps->get_projections();\n\t\tprior = calculate_prior(binning,ps,projections,is_dims,imageDimensions);\n\t\t//prior = calculate_weightImage(binning,ps,projections,is_dims,imageDimensions);\n\t\tsolver.set_x0(prior);\n\t}\n\t//osPDSolver<cuNDArray<float>> solver;\n\t/*\n  {\n  hoCuConebeamProjectionOperator op;\n  \tauto bin3D = boost::make_shared<CBCT_binning>(binning->get_3d_binning());\n  \top.setup(ps,bin3D,imageDimensions);\n  \thoCuNDArray<float> proj(*ps->get_projections());\n  \top.offset_correct(&proj);\n  \top.set_use_filtered_backprojection(true);\n\n  \tstd::vector<size_t> is_dims3D = to_std_vector((uint64d3)imageSize);\n\n  \thoCuNDArray<float> image(is_dims3D);\n\n  \top.mult_MH(&proj,&image,false);\n\n  \tauto cuimage = boost::make_shared<cuNDArray<float>>(image);\n  \tsolver.set_x0(expand(cuimage.get(),is_dims.back()));\n  }\n\t */\n\t//solver.set_regularization_iterations(1);\n\t//osSPSSolver<cuNDArray<float>> solver;\n\t/*\n  if (pics_weight > 0){\n  \tstd::cout << \"Calculating PICS prior\" << std::endl;\n  \thoCuConebeamProjectionOperator op;\n  \tauto bin3D = boost::make_shared<CBCT_binning>(binning->get_3d_binning());\n  \top.setup(ps,bin3D,imageDimensions);\n  \thoCuNDArray<float> proj(*ps->get_projections());\n  \top.offset_correct(&proj);\n  \top.set_use_filtered_backprojection(true);\n\n  \tstd::vector<size_t> is_dims3D = to_std_vector((uint64d3)imageSize);\n\n  \thoCuNDArray<float> image(is_dims3D);\n\n  \top.mult_MH(&proj,&image,false);\n  \tauto prior = boost::make_shared<cuNDArray<float>>(image);\n  \tauto PICS = boost::make_shared<cuTvPicsOperator<float,3>>();\n  \tPICS->set_prior(prior);\n  \tPICS->set_weight(pics_weight);\n  \tsolver.add_nonlinear_operator(PICS);\n\n  \twrite_nd_array(prior.get(),\"fdk_prior.real\");\n  }\n\n\n\n\n\t */\n\n\t// Define encoding matrix\n\n\n\t/*auto weight_array = boost::make_shared<cuNDArray<float>>(is_dims);\n  {\n  \tboost::shared_ptr<linearOperator<cuNDArray<float>>> E2(E);\n  \tcuNDArray<float> tmp_proj(*ps->get_projections()->get_dimensions());\n  \tfill(&tmp_proj,1.0f);\n  \tE2->mult_MH(&tmp_proj,weight_array.get(),false);\n  \tclamp_min(weight_array.get(),1.0f);\n  \treciprocal_inplace(weight_array.get());\n  \t//*weight_array *= *weight_array;\n  }\n  write_nd_array(weight_array.get(),\"weights.real\");\n\t */\n\n\n\t//hoCuCgDescentSolver<float> solver;\n\n\t//osSPSSolver<hoNDArray<float>> solver;\n\t//hoCuNCGSolver<float> solver;\n\t//solver.set_domain_dimensions(&is_dims);\n\tsolver.set_max_iterations(iterations);\n\tsolver.set_output_mode(osSPSSolver<cuNDArray<float>>::OUTPUT_VERBOSE);\n\tsolver.set_tau(5e-5);\n\tsolver.set_non_negativity_constraint(true);\n\tsolver.set_huber(huber);\n\n\tsolver.set_reg_steps(4);\n\t//solver.set_rho(rho);\n\n\tif (tv_weight > 0){\n\n\t\tauto Dx = boost::make_shared<cuPartialDerivativeOperator<float,4>>(0);\n\t\tDx->set_weight(tv_weight);\n\n\t\tDx->set_domain_dimensions(&is_dims);\n\t\tDx->set_codomain_dimensions(&is_dims);\n\t\t/*\n  \tDx->set_domain_dimensions(&double_dims);\n  \tDx->set_codomain_dimensions(&double_dims);\n\t\t */\n\t\tauto Dy = boost::make_shared<cuPartialDerivativeOperator<float,4>>(1);\n\t\tDy->set_weight(tv_weight);\n\t\tDy->set_domain_dimensions(&is_dims);\n\t\tDy->set_codomain_dimensions(&is_dims);\n\t\t/*\n  \tDy->set_domain_dimensions(&double_dims);\n  \tDy->set_codomain_dimensions(&double_dims);\n\t\t */\n\n\n\t\tauto Dz = boost::make_shared<cuPartialDerivativeOperator<float,4>>(2);\n\t\tDz->set_weight(tv_weight);\n\t\tDz->set_domain_dimensions(&is_dims);\n\t\tDz->set_codomain_dimensions(&is_dims);\n\t\t/*\n  \tDz->set_domain_dimensions(&double_dims);\n  \tDz->set_codomain_dimensions(&double_dims);\n\t\t */\n\n\t\tauto Dt = boost::make_shared<cuPartialDerivativeOperator<float,4>>(3);\n\t\tDt->set_weight(tv_weight);\n\t\tDt->set_domain_dimensions(&is_dims);\n\t\tDt->set_codomain_dimensions(&is_dims);\n\n\t\tauto Dx1 = boost::make_shared<subselectionOperator<cuNDArray<float>>>(Dx,0);\n\t\tDx1->set_domain_dimensions(&double_dims);\n\t\tDx1->set_codomain_dimensions(&is_dims);\n\t\tauto Dy1 = boost::make_shared<subselectionOperator<cuNDArray<float>>>(Dy,0);\n\t\tDy1->set_domain_dimensions(&double_dims);\n\t\tDy1->set_codomain_dimensions(&is_dims);\n\t\tauto Dz1 = boost::make_shared<subselectionOperator<cuNDArray<float>>>(Dz,0);\n\t\tDz1->set_domain_dimensions(&double_dims);\n\t\tDz1->set_codomain_dimensions(&is_dims);\n\n\t\tauto Dt1 = boost::make_shared<subselectionOperator<cuNDArray<float>>>(Dt,0);\n\t\tDt1->set_domain_dimensions(&double_dims);\n\t\tDt1->set_codomain_dimensions(&is_dims);\n\n\n\t\tDx1->set_weight(tv_weight);\n\t\tDy1->set_weight(tv_weight);\n\t\tDz1->set_weight(tv_weight);\n\t\tDt1->set_weight(tv_weight*2);\n\n\t\t//solver.add_regularization_group({Dx,Dy,Dz});\n\t\tsolver.add_regularization_group({Dx1,Dy1,Dz1});\n//        solver.add_regularization_operator(Dt1);\n\t\t/*\nauto Dt = boost::make_shared<cuPartialDerivativeOperator<float,4>>(3);\n\tDt->set_weight(tv_weight);\n\tDt->set_domain_dimensions(&is_dims);\n\tDt->set_codomain_dimensions(&is_dims);\n\tsolver.add_regularization_operator(Dt);\n\t\t */\n\t\t/*\n\tauto projections = *ps->get_projections();\n  \tauto prior_weight = calculate_weightImage(binning,ps,projections,is_dims,imageDimensions);\n  \t//sqrt_inplace(prior_weight.get());\n  \tstd::cout << \"Prior min \" << min(prior_weight.get()) << std::endl;\n  \t//*prior_weight -= min(prior_weight.get());\n\t\t *prior_weight /= asum(prior_weight.get())/prior_weight->get_number_of_elements();\n\t\t *prior_weight -= max(prior_weight.get());\n\t\t *prior_weight *= float(-1);\n  \t//clamp_min(prior_weight.get(),float(1e-2));\n  \t//reciprocal_inplace(prior_weight.get());\n\n\n  \twrite_nd_array(prior_weight.get(),\"prior.real\");\n  \t//cudaDeviceReset();\n  \tauto Wt = boost::make_shared<weightingOperator<cuNDArray<float>>>(prior_weight,Dt);\n\tWt->set_weight(tv_weight);\n  \tWt->set_domain_dimensions(&is_dims);\n  \tWt->set_codomain_dimensions(&is_dims);\n\t\t */\n\t\t//lver.add_regularization_operator(Dt);\n\n\n\n\n\t}\n\t/*\n  if (pics_weight > 0){\n\n  \tauto Dx = boost::make_shared<cuPartialDerivativeOperator<float,4>>(0);\n  \tDx->set_weight(pics_weight);\n  \tDx->set_domain_dimensions(&is_dims);\n  \tDx->set_codomain_dimensions(&is_dims);\n\n  \tauto Dy = boost::make_shared<cuPartialDerivativeOperator<float,4>>(1);\n  \tDy->set_weight(pics_weight);\n  \tDy->set_domain_dimensions(&is_dims);\n  \tDy->set_codomain_dimensions(&is_dims);\n\n\n  \tauto Dz = boost::make_shared<cuPartialDerivativeOperator<float,4>>(2);\n  \tDz->set_weight(pics_weight);\n  \tDz->set_domain_dimensions(&is_dims);\n  \tDz->set_codomain_dimensions(&is_dims);\n\n  \tsolver.add_regularization_group({Dx,Dy,Dz},prior);\n\n\n  }*/\n\n\t/*\n\tif (tv_weight > 0){\n\n\t\tauto Dx = boost::make_shared<cuDCTDerivativeOperator<float>>(0);\n\t\tDx->set_weight(tv_weight);\n\t\tDx->set_domain_dimensions(&is_dims);\n\t\tDx->set_codomain_dimensions(&is_dims);\n\n\t\tauto Dy = boost::make_shared<cuDCTDerivativeOperator<float>>(1);\n\t\tDy->set_weight(tv_weight);\n\t\tDy->set_domain_dimensions(&is_dims);\n\t\tDy->set_codomain_dimensions(&is_dims);\n\n\n\t\tauto Dz = boost::make_shared<cuDCTDerivativeOperator<float>>(2);\n\t\tDz->set_weight(tv_weight);\n\t\tDz->set_domain_dimensions(&is_dims);\n\t\tDz->set_codomain_dimensions(&is_dims);\n\n\n\n\t\tsolver.add_regularization_group({Dx,Dy,Dz});\n\n\n\t}\n\n\t */\n\n\tif (dct_weight > 0){\n\t\t//auto dctOp = boost::make_shared<identityOperator<cuNDArray<float>>>();\n\t\tauto dctOp = boost::make_shared<cuDCTOperator<float>>();\n\t\tdctOp->set_domain_dimensions(&is_dims);\n\t\t//dctOp->set_codomain_dimensions(&is_dims);\n\t\tdctOp->set_weight(dct_weight);\n\n\t\tauto dctOp1 = boost::make_shared<subselectionOperator<cuNDArray<float>>>(dctOp,1);\n\t\tdctOp1->set_domain_dimensions(&double_dims);\n\t\tdctOp1->set_codomain_dimensions(dctOp->get_codomain_dimensions().get());\n\t\tdctOp1->set_weight(dct_weight);\n\t\tsolver.add_regularization_operator(dctOp1);\n\t\t/*\n\t\tauto Dt = boost::make_shared<cuPartialDerivativeOperator<float,4>>(3);\n\t\tDt->set_weight(dct_weight);\n\t\tDt->set_domain_dimensions(&is_dims);\n\t\tDt->set_codomain_dimensions(&is_dims);\n\t\tauto Dt1 = boost::make_shared<subselectionOperator<cuNDArray<float>>>(Dt,1);\n\t\tDt1->set_domain_dimensions(&double_dims);\n\t\tDt1->set_codomain_dimensions(&is_dims);\n\n\t\tsolver.add_regularization_operator(Dt1);\n\t\t */\n/*\n\t\tauto Dt = boost::make_shared<cuPartialDerivativeOperator<float,4>>(3);\n\t\tDt->set_weight(tv_weight);\n\t\tDt->set_domain_dimensions(&double_dims);\n\t\tDt->set_codomain_dimensions(&double_dims);\n\t\tsolver.add_regularization_operator(Dt);\n\t\tauto Dx = boost::make_shared<cuPartialDerivativeOperator<float,4>>(0);\n\t\tDx->set_weight(tv_weight);\n\n\t\tDx->set_domain_dimensions(&is_dims);\n\t\tDx->set_codomain_dimensions(&is_dims);\n\t\t/*\n  \tDx->set_domain_dimensions(&double_dims);\n  \tDx->set_codomain_dimensions(&double_dims);\n\t\t */\n\t\t/*\n\t\tauto Dy = boost::make_shared<cuPartialDerivativeOperator<float,4>>(1);\n\t\tDy->set_weight(tv_weight);\n\t\tDy->set_domain_dimensions(&is_dims);\n\t\tDy->set_codomain_dimensions(&is_dims);\n\t\t*/\n\t\t/*\n  \tDy->set_domain_dimensions(&double_dims);\n  \tDy->set_codomain_dimensions(&double_dims);\n\t\t */\n/*\n\n\t\tauto Dz = boost::make_shared<cuPartialDerivativeOperator<float,4>>(2);\n\t\tDz->set_weight(tv_weight);\n\t\tDz->set_domain_dimensions(&is_dims);\n\t\tDz->set_codomain_dimensions(&is_dims);\n\t\t*/\n\t\t/*\n  \tDz->set_domain_dimensions(&double_dims);\n  \tDz->set_codomain_dimensions(&double_dims);\n\t\t */\n\n/*\n\t\tauto Dx1 = boost::make_shared<subselectionOperator<cuNDArray<float>>>(Dx,1);\n\t\tDx1->set_domain_dimensions(&double_dims);\n\t\tDx1->set_codomain_dimensions(&is_dims);\n\t\tauto Dy1 = boost::make_shared<subselectionOperator<cuNDArray<float>>>(Dy,1);\n\t\tDy1->set_domain_dimensions(&double_dims);\n\t\tDy1->set_codomain_dimensions(&is_dims);\n\t\tauto Dz1 = boost::make_shared<subselectionOperator<cuNDArray<float>>>(Dz,1);\n\t\tDz1->set_domain_dimensions(&double_dims);\n\t\tDz1->set_codomain_dimensions(&is_dims);\n\n\t\tDx1->set_weight(tv_weight*0.1);\n\t\tDy1->set_weight(tv_weight*0.1);\n\t\tDz1->set_weight(tv_weight*0.1);\n\n*/\n\t}\n\n\tauto E = boost::make_shared<CBSubsetOperator<cuNDArray> >(subsets);\n\n\n\t//E->setup(ps,binning,imageDimensions);\n\tE->setup(ps,binning,imageDimensions);\n\tE->set_domain_dimensions(&is_dims);\n\tE->set_codomain_dimensions(ps->get_projections()->get_dimensions().get());\n\n\tsolver.set_encoding_operator(E);\n\n\n\n\tauto projections = boost::make_shared<cuNDArray<float>>(*ps->get_projections());\n\tstd::cout << \"Projection norm:\" << nrm2(projections.get()) << std::endl;\n\t//E->set_use_offset_correction(false);\n\n\t//boost::shared_ptr<cuNDArray<bool>> mask;\n\t//mask = E->calculate_mask(projections,0.03f);\n\t//ps->set_projections(boost::shared_ptr<hoCuNDArray<float>>()); //Clear projections from host memory.\n\n//\tE->offset_correct(projections.get());\n\t//E->set_mask(mask);\n\tstd::cout << \"Projection norm:\" << nrm2(projections.get()) << std::endl;\n\n\n\t//solver.set_damping(1e-6);\n\n\t/*\n    boost::shared_ptr<hoCuNDArray<float> > prior;\n\n  if (vm.count(\"use_prior\")) {\n  \tprior = calculate_prior(binning,ps,projections,is_dims,imageDimensions);\n  \tsolver.set_x0(prior);\n  }\n\t */\n\n\tauto result = solver.solve(projections.get());\n\tstd::cout << \"Penguin\" << nrm2(result.get()) << std::endl;\n\n\tstd::cout << \"Result sum \" << asum(result.get()) << std::endl;\n\n\t//apply_mask(result.get(),mask.get());\n\n\tstd::cout << \"Result sum \" << asum(result.get()) << std::endl;\n\t//saveNDArray2HDF5(result.get(),outputFile,imageDimensions,vector_td<float,3>(0),command_line_string.str(),iterations);\n\n\n\tif (wavelet_weight > 0){\n\t\tosMOMSolverF<cuNDArray<float>> solverF;\n\t\tsolverF.set_max_iterations(iterations);\n\t\tsolverF.set_x0(result);\n\t\tsolverF.set_encoding_operator(E);\n\n\t\tauto wave = boost::make_shared<cuEdgeATrousOperator<float>>();\n\n\t\twave->set_sigma(sigma);\n\t\twave->set_domain_dimensions(&is_dims);\n\t\tif (binning->get_number_of_bins() == 1)\n\t\t\twave->set_levels({2,2,2});\n\t\telse\n\t\t\twave->set_levels({2,2,2,2});\n\t\twave->set_weight(wavelet_weight);\n\t\tsolverF.add_regularization_operator(wave);\n\n\t\tresult = solverF.solve(projections.get());\n\n\t}\n\n\tauto result2 = sum(result.get(),4);\n\tsaveNDArray2HDF5(result.get(),\"seperate.hdf5\",imageDimensions,floatd3(0,0,0),command_line_string.str(),iterations);\n\tsaveNDArray2HDF5(result2.get(),outputFile,imageDimensions,floatd3(0,0,0),command_line_string.str(),iterations);\n\t//write_dicom(result.get(),command_line_string.str(),imageDimensions);\n\t/*\n  cuNDArray<float> tmp(W->get_codomain_dimensions());\n\n  W->mult_M(result.get(),&tmp);\n\n  write_nd_array(&tmp,\"test.real\");\n\t */\n\t//E->set_use_offset_correction(false);\n\t/*\n  linearOperator<cuNDArray<float>> * E_all = E.get();\n  auto tmp_proj = projections;\n  clear(&tmp_proj);\n\n  E_all->mult_M(result.get(),&tmp_proj);\n  tmp_proj -= projections;\n  write_nd_array(&tmp_proj,\"projection_diffs.real\");\n\n  std::cout <<\"Projection dimensions \";\n  auto pdims = *projections.get_dimensions();\n  for (auto d : pdims)\n  \tstd::cout << d << \" \";\n  std::cout << std::endl;\n\n\t */\n\n}\n", "meta": {"hexsha": "a89bc6be656677d4d36c6731ae5203b53552da64", "size": 22536, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xray/cuCBOS2_reconstruct.cpp", "max_stars_repo_name": "ahsanjav/gt-tomography", "max_stars_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-06-26T13:41:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-10T11:06:27.000Z", "max_issues_repo_path": "xray/cuCBOS2_reconstruct.cpp", "max_issues_repo_name": "ahsanjav/gt-tomography", "max_issues_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xray/cuCBOS2_reconstruct.cpp", "max_forks_repo_name": "ahsanjav/gt-tomography", "max_forks_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T14:37:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T14:37:29.000Z", "avg_line_length": 35.2676056338, "max_line_length": 229, "alphanum_fraction": 0.7212016329, "num_tokens": 6372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.42439546578349147}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#include \"CubicSplineFactory.hpp\"\n\n#include <rw/core/Ptr.hpp>\n#include <rw/math/EAA.hpp>\n#include <rw/math/Q.hpp>\n#include <rw/math/Quaternion.hpp>\n#include <rw/math/Transform3D.hpp>\n#include <rw/math/Vector2D.hpp>\n#include <rw/math/Vector3D.hpp>\n#include <rw/math/VectorND.hpp>\n#include <rw/trajectory/CubicSplineInterpolator.hpp>\n#include <rw/trajectory/SQUADInterpolator.hpp>\n\n#include <Eigen/Sparse>\n#include <math.h>\n\n#if EIGEN_VERSION_AT_LEAST(3, 1, 0)\n#include <Eigen/SparseCholesky>\n#endif\n\nusing namespace rw::trajectory;\n\nusing namespace rw::math;\nusing namespace rw::core;\n\n// ###########################################################################\n// #                                Q Functions                              #\n// ###########################################################################\n\nInterpolatorTrajectory< Q >::Ptr CubicSplineFactory::makeNaturalSpline (QPath::Ptr qpath,\n                                                                        double timeStep)\n{\n    std::vector< double > times;\n    for (size_t i = 0; i < qpath->size (); i++) {\n        times.push_back (i * timeStep);\n    }\n    return makeNaturalSpline (*qpath, times);\n}\n\nInterpolatorTrajectory< rw::math::Q >::Ptr\nCubicSplineFactory::makeNaturalSpline (TimedQPath::Ptr tqpath)\n{\n    QPath path;\n    std::vector< double > times;\n    for (const TimedQ& tq : *tqpath) {\n        path.push_back (tq.getValue ());\n        times.push_back (tq.getTime ());\n    }\n\n    return makeNaturalSpline (path, times);\n}\n\nInterpolatorTrajectory< rw::math::Q >::Ptr\nCubicSplineFactory::makeNaturalSpline (const QPath& qpath, const std::vector< double >& times)\n{\n    typedef float T;\n\n    if (qpath.size () < 2)\n        RW_THROW (\"Path must be longer than 1!\");\n    if (qpath.size () != times.size ())\n        RW_THROW (\"Length of path and times need to be equal\");\n\n    size_t dim = (qpath)[0].size ();    // the number of dimensions of the points\n    size_t N   = qpath.size () - 1;     // we have N+1 points, which yields N splines\n\n    typedef Eigen::Matrix< T, Eigen::Dynamic, 1 > Vector;\n    // typedef Eigen::Matrix<T, Eigen::Dynamic, 1, 1> Matrix;\n\n    Vector B (N + 1);    // make room for boundary conditions\n\n    Vector Y (N + 1);    // the points that the spline should intersect\n\n    Vector a (dim * (N + 1)), b (dim * N), c (dim * N), d (dim * N);\n\n    Vector H (N);    // duration from point i to i+1\n    for (size_t i = 0; i < N; i++) {\n        // T timeI0 = (T)((*tqpath)[i]).getTime();\n        // T timeI1 = (T)((*tqpath)[i+1]).getTime();\n        // H[i] = timeI1-timeI0;\n        H[i] = (float) (times[i + 1] - times[i]);\n    }\n\n#if EIGEN_VERSION_AT_LEAST(3, 1, 0)\n    Eigen::SparseMatrix< T > A ((int) N + 1, (int) N + 1);\n    // D[0] = 2*H[0];\n    A.insert (0, 0) = 2 * H[0];\n    A.insert (0, 1) = H[0];\n    A.insert (1, 0) = H[0];\n    for (size_t i = 1; i < N; i++) {\n        // D[i] = 2*(H[i-1]+H[i]);\n        int ei                = (int) i;\n        A.insert (ei, ei)     = 2 * (H[i - 1] + H[i]);\n        A.insert (ei, ei + 1) = H[i];\n        A.insert (ei + 1, ei) = H[i];\n    }\n    // D[N] = 2*H[N-1];\n    A.insert ((int) N, (int) N) = 2 * H[N - 1];\n\n    Eigen::SimplicialLLT< Eigen::SparseMatrix< T > > solver;\n    solver.compute (A);\n\n#else\n    Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > A =\n        Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic >::Zero ((int) N + 1, (int) N + 1);\n    A (0, 0) = 2 * H[0];\n    A (0, 1) = H[0];\n    A (1, 0) = H[0];\n    for (size_t i = 1; i < N; i++) {\n        // D[i] = 2*(H[i-1]+H[i]);\n        int ei         = (int) i;\n        A (ei, ei)     = 2 * (H[i - 1] + H[i]);\n        A (ei, ei + 1) = H[i];\n        A (ei + 1, ei) = H[i];\n    }\n    // D[N] = 2*H[N-1];\n    A ((int) N, (int) N) = 2 * H[N - 1];\n    Eigen::LLT< Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > > solver;\n    solver.compute (A);\n\n#endif\n    for (size_t j = 0; j < (size_t) dim; j++) {\n        for (size_t i = 0; i < (size_t) N + 1; i++) {\n            Y[i] = (T) (qpath[i])[j];\n        }\n\n        B[0] = (T) (3.0 * (Y[1] - Y[0]) / H[0]);\n        for (size_t i = 1; i < N; i++) {\n            B[i] = (T) (3.0 * ((Y[i + 1] - Y[i]) / H[i] - (Y[i] - Y[i - 1]) / H[i - 1]));\n        }\n        B[N] = (T) (-3.0 * (Y[N] - Y[N - 1]) / H[N - 1]);\n\n        B = solver.solve (B);\n\n        for (size_t i = 0; i < (size_t) N + 1; i++) {\n            a[i * dim + j] = Y[i];\n        }\n\n        for (size_t i = 0; i < (size_t) N; i++) {\n            c[j + i * dim] = B[i];\n            b[j + i * dim] = (Y[i + 1] - Y[i]) / H[i] - H[i] * (B[i + 1] + 2 * B[i]) / (T) 3.0;\n            d[j + i * dim] = (B[i + 1] - B[i]) / ((T) 3.0 * H[i]);    //   +B[i]+B[i+1];\n        }\n    }\n\n    // ************** now create the actual trajectory from the calcualted parameters\n    InterpolatorTrajectory< Q >::Ptr traj = ownedPtr (new InterpolatorTrajectory< Q > (times[0]));\n\n    Q ba (dim), bb (dim), bc (dim), bd (dim);\n    for (size_t i = 0; i < N; i++) {\n        for (size_t j = 0; j < dim; j++) {\n            ba[j] = a[j + i * dim];\n            bb[j] = b[j + i * dim];\n            bc[j] = c[j + i * dim];\n            bd[j] = d[j + i * dim];\n        }\n        Interpolator< Q >* iptr = new CubicSplineInterpolator< Q > (ba, bb, bc, bd, H[i]);\n        traj->add (ownedPtr (iptr));\n    }\n\n    return traj;\n}\n\nInterpolatorTrajectory< Q >::Ptr CubicSplineFactory::makeClampedSpline (QPath::Ptr qpath,\n                                                                        const rw::math::Q& dqStart,\n                                                                        const rw::math::Q& dqEnd,\n                                                                        double timeStep)\n{\n    std::vector< double > times;\n    for (size_t i = 0; i < qpath->size (); i++) {\n        times.push_back (i * timeStep);\n    }\n    return makeClampedSpline (*qpath, times, dqStart, dqEnd);\n}\n\nInterpolatorTrajectory< rw::math::Q >::Ptr\nCubicSplineFactory::makeClampedSpline (TimedQPath::Ptr tqpath, const rw::math::Q& dqStart,\n                                       const rw::math::Q& dqEnd)\n\n{\n    QPath path;\n    std::vector< double > times;\n    for (const TimedQ& tq : *tqpath) {\n        path.push_back (tq.getValue ());\n        times.push_back (tq.getTime ());\n    }\n\n    return makeClampedSpline (path, times, dqStart, dqEnd);\n}\n\n// ###########################################################################\n// #                             Template Functions                          #\n// ###########################################################################\n\ntemplate< typename T >\ntypename InterpolatorTrajectory< T >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< T >& path, double timeStep)\n{\n    std::vector< double > times;\n    for (size_t i = 0; i < path.size (); i++) {\n        times.push_back (i * timeStep);\n    }\n    return makeNaturalSpline (path, times);\n}\n\n// ### explicit template specifications\ntemplate InterpolatorTrajectory< Vector3D<> >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Vector3D<> >& path, double timeStep);\n\ntemplate InterpolatorTrajectory< Transform3DVector<> >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Transform3DVector<> >& path, double timeStep);\n\ntemplate InterpolatorTrajectory< Q >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Q >& path, double timeStep);\n\ntemplate InterpolatorTrajectory< Quaternion< double > >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Quaternion< double > >& path, double timeStep);\n\n// ########### NEXT FUNCTION ###############\n\ntemplate< typename T >\ntypename InterpolatorTrajectory< T >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Timed< T > >& path)\n{\n    Path< T > pathN;\n    std::vector< double > times;\n    for (const Timed< T >& tq : path) {\n        pathN.push_back (tq.getValue ());\n        times.push_back (tq.getTime ());\n    }\n\n    return makeNaturalSpline (pathN, times);\n}\n\n// ### explicit template specifications\ntemplate InterpolatorTrajectory< Vector3D<> >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Timed< Vector3D<> > >& path);\n\ntemplate InterpolatorTrajectory< Transform3DVector<> >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Timed< Transform3DVector<> > >& path);\n\ntemplate InterpolatorTrajectory< Q >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Timed< Q > >& path);\n\ntemplate InterpolatorTrajectory< Quaternion< double > >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Timed< Quaternion< double > > >& path);\n\n// ########### NEXT FUNCTION ###############\n\ntemplate< typename T >\ntypename InterpolatorTrajectory< T >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< T >& path, const std::vector< double >& times)\n{\n    if (path.size () < 2) {\n        RW_THROW (\"Path must be longer than 1!\");\n    }\n    if (path.size () != times.size ()) {\n        RW_THROW (\"Length of path and times need to be equal\");\n    }\n\n    size_t dim = path[0].size ();     // the number of dimensions of the points\n    size_t N   = path.size () - 1;    // we have N+1 points, which yields N splines\n    Eigen::VectorXd B (N + 1);        // make room for boundary conditions\n\n    Eigen::VectorXd Y (N + 1);    // the points that the spline should intersect\n\n    Eigen::VectorXd a (dim * (N + 1));\n    Eigen::VectorXd b (dim * N);\n    Eigen::VectorXd c (dim * N);\n    Eigen::VectorXd d (dim * N);\n\n    Eigen::VectorXd H (N);    // duration from point i to i+1\n    for (size_t i = 0; i < N; i++) {\n        H[i] = (double) (times[i + 1] - times[i]);\n    }\n#if EIGEN_VERSION_AT_LEAST(3, 1, 0)\n    Eigen::SparseMatrix< double > A ((int) N + 1, (int) N + 1);\n    A.insert (0, 0) = 2 * H[0];\n    A.insert (0, 1) = H[0];\n    A.insert (1, 0) = H[0];\n    for (size_t i = 1; i < N; i++) {\n        int ei                = (int) i;\n        A.insert (ei, ei)     = 2 * (H[i - 1] + H[i]);\n        A.insert (ei, ei + 1) = H[i];\n        A.insert (ei + 1, ei) = H[i];\n    }\n    // D[N] = 2*H[N-1];\n    A.insert ((int) N, (int) N) = 2 * H[N - 1];\n\n    Eigen::SimplicialLLT< Eigen::SparseMatrix< double > > solver;\n    solver.compute (A);\n\n#else\n    Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > A =\n        Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic >::Zero ((int) N + 1, (int) N + 1);\n    A (0, 0) = 2 * H[0];\n    A (0, 1) = H[0];\n    A (1, 0) = H[0];\n    for (size_t i = 1; i < N; i++) {\n        int ei         = (int) i;\n        A (ei, ei)     = 2 * (H[i - 1] + H[i]);\n        A (ei, ei + 1) = H[i];\n        A (ei + 1, ei) = H[i];\n    }\n    A ((int) N, (int) N) = 2 * H[N - 1];\n    Eigen::LLT< Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > > solver;\n    solver.compute (A);\n#endif\n    for (size_t j = 0; j < (size_t) dim; j++) {\n        for (size_t i = 0; i < (size_t) N + 1; i++) {\n            Y[i] = (double) (path[i])[j];\n        }\n\n        B[0] = (double) (3.0 * (Y[1] - Y[0]) / H[0]);\n        for (size_t i = 1; i < N; i++) {\n            B[i] = (double) (3.0 * ((Y[i + 1] - Y[i]) / H[i] - (Y[i] - Y[i - 1]) / H[i - 1]));\n        }\n        B[N] = (double) (-3.0 * (Y[N] - Y[N - 1]) / H[N - 1]);\n\n        B = solver.solve (B);\n\n        for (size_t i = 0; i < (size_t) N + 1; i++) {\n            a[i * dim + j] = Y[i];\n        }\n\n        for (size_t i = 0; i < (size_t) N; i++) {\n            c[j + i * dim] = B[i];\n            b[j + i * dim] = (Y[i + 1] - Y[i]) / H[i] - H[i] * (B[i + 1] + 2 * B[i]) / (double) 3.0;\n            d[j + i * dim] = (B[i + 1] - B[i]) / ((double) 3.0 * H[i]);    //   +B[i]+B[i+1];\n        }\n    }\n    // ************** now create the actual trajectory from the calcualted parameters\n    typename InterpolatorTrajectory< T >::Ptr traj =\n        ownedPtr (new InterpolatorTrajectory< T > (times[0]));\n\n    T ba, bb, bc, bd;\n    for (size_t i = 0; i < N; i++) {\n        for (size_t j = 0; j < dim; j++) {\n            ba[j] = a[j + i * dim];\n            bb[j] = b[j + i * dim];\n            bc[j] = c[j + i * dim];\n            bd[j] = d[j + i * dim];\n        }\n        Interpolator< T >* iptr = new CubicSplineInterpolator< T > (ba, bb, bc, bd, H[i]);\n        traj->add (ownedPtr (iptr));\n    }\n    return traj;\n}\n\n// ### explicit template specifications\ntemplate InterpolatorTrajectory< Vector3D<> >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Vector3D<> >& path,\n                                       const std::vector< double >& times);\n\ntemplate InterpolatorTrajectory< Transform3DVector<> >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Transform3DVector<> >& path,\n                                       const std::vector< double >& times);\n\ntemplate InterpolatorTrajectory< Quaternion<> >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Quaternion<> >& path,\n                                       const std::vector< double >& times);\n\n// ########### NEXT FUNCTION ###############\ntemplate< typename T >\ntypename InterpolatorTrajectory< T >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< T >& path, const T& dStart, const T& dEnd,\n                                       double timeStep)\n{\n    std::vector< double > times;\n    for (size_t i = 0; i < path.size (); i++) {\n        times.push_back (i * timeStep);\n    }\n    return makeClampedSpline (path, times, dStart, dEnd);\n}\nnamespace rw { namespace trajectory {\ntemplate<>\ntypename InterpolatorTrajectory< Transform3D<> >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Transform3D<> >& path,\n                                       const Transform3D<>& dStart, const Transform3D<>& dEnd,\n                                       double timeStep)\n{\n    RW_THROW (\"Clamped Cubic Spline not yet implemented for Transform3D\");\n    return NULL;\n}\n}}\ntemplate InterpolatorTrajectory< Vector3D<> >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Vector3D<> >& path, const Vector3D<>& dStart,\n                                       const Vector3D<>& dEnd, double timeStep);\n\ntemplate InterpolatorTrajectory< Q >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Q >& path, const Q& dStart, const Q& dEnd,\n                                       double timeStep);\n\ntemplate InterpolatorTrajectory< Transform3DVector<> >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Transform3DVector<> >& path,\n                                       const Transform3DVector<>& dStart,\n                                       const Transform3DVector<>& dEnd, double timeStep);\n\ntemplate InterpolatorTrajectory< Quaternion<> >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Quaternion<> >& path, const Quaternion<>& dStart,\n                                       const Quaternion<>& dEnd, double timeStep);\n\n// ########### NEXT FUNCTION ###############\n\ntemplate< typename T >\ntypename InterpolatorTrajectory< T >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Timed< T > >& tpath, const T& dStart,\n                                       const T& dEnd)\n{\n    Path< T > path;\n    std::vector< double > times;\n    for (const Timed< T >& tq : tpath) {\n        path.push_back (tq.getValue ());\n        times.push_back (tq.getTime ());\n    }\n\n    return makeClampedSpline (path, times, dStart, dEnd);\n}\n\ntemplate InterpolatorTrajectory< Vector3D<> >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Timed< Vector3D<> > >& tpath,\n                                       const Vector3D<>& dStart, const Vector3D<>& dEnd);\n\ntemplate InterpolatorTrajectory< Q >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Timed< Q > >& path, const Q& dStart,\n                                       const Q& dEnd);\n\ntemplate InterpolatorTrajectory< Transform3DVector<> >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Timed< Transform3DVector<> > >& tpath,\n                                       const Transform3DVector<>& dStart,\n                                       const Transform3DVector<>& dEnd);\n\ntemplate InterpolatorTrajectory< Quaternion<> >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Timed< Quaternion<> > >& tpath,\n                                       const Quaternion<>& dStart, const Quaternion<>& dEnd);\n\n// ########### NEXT FUNCTION ###############\ntemplate< typename T >\ntypename InterpolatorTrajectory< T >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< T >& path, const std::vector< double >& times,\n                                       const T& dStart, const T& dEnd)\n{\n    if (path.size () < 2)\n        RW_THROW (\"Path must be longer than 1!\");\n\n    if (path.size () != times.size ())\n        RW_THROW (\"Length of path and times need to match\");\n\n    size_t dim = path[0].size ();     // the number of dimensions of the points\n    size_t N   = path.size () - 1;    // we have N+1 points, which yields N splines\n    Eigen::VectorXd B (N + 1);        // make room for boundary conditions\n\n    Eigen::VectorXd Y (N + 1);    // the points that the spline should intersect\n\n    Eigen::VectorXd a (dim * (N + 1));\n    Eigen::VectorXd b (dim * N);\n    Eigen::VectorXd c (dim * N);\n    Eigen::VectorXd d (dim * N);\n    Eigen::VectorXd H (N);    // duration from point i to i+1\n\n    for (size_t i = 0; i < N; i++) {\n        H[i] = (float) (times[i + 1] - times[i]);\n    }\n#if EIGEN_VERSION_AT_LEAST(3, 1, 0)\n    Eigen::SparseMatrix< double > A ((int) N + 1, (int) N + 1);\n\n    A.insert (0, 0) = 2 * H[0];\n    A.insert (0, 1) = H[0];\n    A.insert (1, 0) = H[0];\n    for (size_t i = 1; i < N; i++) {\n        int ei                = (int) i;\n        A.insert (ei, ei)     = 2 * (H[i - 1] + H[i]);\n        A.insert (ei + 1, ei) = H[i];\n        A.insert (ei, ei + 1) = H[i];\n    }\n    A.insert ((int) N, (int) N) = 2 * H[N - 1];\n\n    Eigen::SimplicialLLT< Eigen::SparseMatrix< double > > solver;\n    solver.compute (A);\n\n#else\n    Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > A =\n        Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic >::Zero ((int) N + 1, (int) N + 1);\n\n    A (0, 0) = 2 * H[0];\n    A (0, 1) = H[0];\n    A (1, 0) = H[0];\n    for (size_t i = 1; i < N; i++) {\n        int ei         = (int) i;\n        A (ei, ei)     = 2 * (H[i - 1] + H[i]);\n        A (ei + 1, ei) = H[i];\n        A (ei, ei + 1) = H[i];\n    }\n    A ((int) N, (int) N) = 2 * H[N - 1];\n\n    Eigen::LLT< Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > > solver;\n    solver.compute (A);\n\n#endif\n\n    for (size_t j = 0; j < (size_t) dim; j++) {\n        for (size_t i = 0; i < (size_t) N + 1; i++) {\n            Y[i] = (double) (path[i])[j];\n        }\n\n        B[0] = (double) (3.0 * (Y[1] - Y[0]) / H[0] - 3 * dStart[j]);\n        for (size_t i = 1; i < (std::size_t) B.size () - 1; i++) {\n            B[i] = (double) (3.0 * ((Y[i + 1] - Y[i]) / H[i] - (Y[i] - Y[i - 1]) / H[i - 1]));\n        }\n        B[N] = (double) (3.0 * dEnd[j] - 3.0 * (Y[N] - Y[N - 1]) / H[N - 1]);\n\n        B = solver.solve (B);\n\n        for (size_t i = 0; i < N + 1; i++) {\n            a[i * dim + j] = Y[i];\n        }\n\n        for (size_t i = 0; i < (size_t) N; i++) {\n            c[j + i * dim] = B[i];\n            b[j + i * dim] =\n                (double) ((Y[i + 1] - Y[i]) / H[i] - H[i] * (B[i + 1] + 2 * B[i]) / 3.0);\n            d[j + i * dim] = (double) ((B[i + 1] - B[i]) / (3.0 * H[i]));    //   +B[i]+B[i+1];\n        }\n    }\n\n    // ************** now create the actual trajectory from the calcualted parameters\n    typename InterpolatorTrajectory< T >::Ptr traj =\n        ownedPtr (new InterpolatorTrajectory< T > (times[0]));\n\n    T ba=path[0], bb=path[0], bc=path[0], bd=path[0];\n    for (size_t i = 0; i < N; i++) {\n\n        for (size_t j = 0; j < dim; j++) {\n            ba[j] = a[j + i * dim];\n            bb[j] = b[j + i * dim];\n            bc[j] = c[j + i * dim];\n            bd[j] = d[j + i * dim];\n        }\n        Interpolator< T >* iptr = new CubicSplineInterpolator< T > (ba, bb, bc, bd, H[i]);\n        traj->add (ownedPtr (iptr));\n    }\n\n    return traj;\n}\n\ntemplate InterpolatorTrajectory< Vector3D<> >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Vector3D<> >& path,\n                                       const std::vector< double >& times, const Vector3D<>& dStart,\n                                       const Vector3D<>& dEnd);\n\ntemplate InterpolatorTrajectory< Q >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Q >& path,\n                                       const std::vector< double >& times, const Q& dStart,\n                                       const Q& dEnd);\n\ntemplate InterpolatorTrajectory< Transform3DVector<> >::Ptr CubicSplineFactory::makeClampedSpline (\n    const Path< Transform3DVector<> >& path, const std::vector< double >& times,\n    const Transform3DVector<>& dStart, const Transform3DVector<>& dEnd);\n\ntemplate InterpolatorTrajectory< Quaternion<> >::Ptr\nCubicSplineFactory::makeClampedSpline (const Path< Quaternion<> >& path,\n                                       const std::vector< double >& times,\n                                       const Quaternion<>& dStart, const Quaternion<>& dEnd);\n\n// ###########################################################################\n// #                          Transform3D Functions                          #\n// ###########################################################################\n\nInterpolatorTrajectory< rw::math::Transform3DVector<> >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Transform3D<> >& path, double timeStep)\n{\n    std::vector< double > times;\n    for (size_t i = 0; i < path.size (); i++) {\n        times.push_back (i * timeStep);\n    }\n    return makeNaturalSpline (path, times);\n}\n\nInterpolatorTrajectory< rw::math::Transform3DVector<> >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< Timed< Transform3D<> > >& path)\n{\n    Path< Transform3D<> > pathN;\n    std::vector< double > times;\n    for (const Timed< Transform3D<> >& tq : path) {\n        pathN.push_back (tq.getValue ());\n        times.push_back (tq.getTime ());\n    }\n\n    return makeNaturalSpline (pathN, times);\n}\n\nInterpolatorTrajectory< rw::math::Transform3DVector<> >::Ptr\nCubicSplineFactory::makeNaturalSpline (const Path< rw::math::Transform3D<> >& path,\n                                       const std::vector< double >& times)\n{\n    Path< Transform3DVector<> > NPath;\n    for (const Transform3D<>& trans : path) {\n        NPath.push_back (Transform3DVector<> (trans));\n    }\n    return makeNaturalSpline (NPath, times);\n}\n\n// ###########################################################################\n// #                             SQUAD Functions                             #\n// ###########################################################################\n\nInterpolatorTrajectory< rw::math::Quaternion<> >::Ptr\nCubicSplineFactory::makeSQUAD (const Path< rw::math::Quaternion<> >& path, double timeStep)\n{\n    std::vector< double > times;\n    for (size_t i = 0; i < path.size (); i++) {\n        times.push_back (i * timeStep);\n    }\n    return makeSQUAD (path, times);\n}\nInterpolatorTrajectory< rw::math::Quaternion<> >::Ptr\nCubicSplineFactory::makeSQUAD (const Path< Timed< rw::math::Quaternion<> > >& tpath)\n{\n    Path< rw::math::Quaternion<> > pathN;\n    std::vector< double > times;\n    for (const Timed< rw::math::Quaternion<> >& tq : tpath) {\n        pathN.push_back (tq.getValue ());\n        times.push_back (tq.getTime ());\n    }\n    return makeSQUAD (pathN, times);\n}\n\nInterpolatorTrajectory< rw::math::Quaternion<> >::Ptr\nCubicSplineFactory::makeSQUAD (const Path< rw::math::Quaternion<> >& path,\n                               const std::vector< double >& times)\n{\n    InterpolatorTrajectory< Quaternion<> >::Ptr traj =\n        ownedPtr (new InterpolatorTrajectory< Quaternion<> > (times[0]));\n    size_t N = path.size () - 1;\n    std::vector< Quaternion<> > s (path.size ());\n    s[0] = path[0];\n    for (size_t i = 1; i < s.size () - 1; i++) {\n        const Quaternion<>& qn1 = path[i - 1];\n        const Quaternion<>& q0  = path[i];\n        const Quaternion<>& q1  = path[i + 1];\n\n        s[i] = q0 * exp (-1 * (ln (q0.inverse () * q1) + ln (q0.inverse () * qn1)) * (1.0 / 4.0));\n    }\n    s.back () = path.back ();\n\n    for (size_t i = 0; i < N - 1; i++) {\n        double duration = times[i + 1] - times[i];\n        Interpolator< Quaternion<> >* iptr =\n            new SQUADInterpolator< double > (path[i], path[i + 1], s[i], s[i + 1], duration);\n        traj->add (ownedPtr (iptr));\n    }\n    return traj;\n}", "meta": {"hexsha": "ad136a366961b3f54850074458a7e1da9ec43c5b", "size": 25181, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/trajectory/CubicSplineFactory.cpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/trajectory/CubicSplineFactory.cpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/trajectory/CubicSplineFactory.cpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6397608371, "max_line_length": 100, "alphanum_fraction": 0.5198363846, "num_tokens": 7374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.42439545958383534}}
{"text": "#ifndef QST_RBM_HPP\n#define QST_RBM_HPP\n#include <iostream>\n#include <Eigen/Dense>\n#include <random>\n#include <fstream>\n\nnamespace qst{\n\n// RBM class\nclass Rbm{\n\n    int nv_;                        // Number of visible units\n    int nh_;                        // Number of hidden units\n    int npar_;                      // Number of parameters\n    int nchains_;                   // Number of sampling chains\n    \n    Eigen::MatrixXd v_;             // Visible states\n    Eigen::MatrixXd h_;             // Hidden states\n    Eigen::MatrixXd probv_given_h_; // Visible probabilities\n    Eigen::MatrixXd probh_given_v_; // Hidden probabilities\n\n    Eigen::MatrixXd W_;             // Weights\n    Eigen::VectorXd b_;             // Visible fields\n    Eigen::VectorXd c_;             // Hidden fields\n    \n    Eigen::VectorXd gamma_;         // Container for hidden contribution to quantities \n    \n    std::mt19937 rgen_;             // Random number generator\n    \npublic:\n    // Contructor\n    Rbm(Parameters &par):nv_(par.nv_),nh_(par.nh_){\n        npar_=nv_+nh_+nv_*nh_;\n        nchains_ = par.nc_;\n        v_.setZero(nchains_,nv_);\n        h_.setZero(nchains_,nh_);\n        probv_given_h_.resize(nchains_,nv_);\n        probh_given_v_.resize(nchains_,nh_);\n        W_.resize(nh_,nv_);\n        b_.resize(nv_);\n        c_.resize(nh_);\n        gamma_.resize(nh_);\n        rgen_.seed(13579);\n        //std::random_device rd;\n        //rgen_.seed(rd());\n    }\n\n    // Private members access functions\n    inline int Nvisible()const{\n        return nv_;\n    }\n    inline int Nhidden()const{\n        return nh_;\n    }\n    inline int Npar()const{\n        return npar_;\n    }\n    inline int Nchains(){\n        return nchains_;\n    }\n    inline Eigen::VectorXd VisibleStateRow(int s){\n        return v_.row(s);\n    }\n    \n    // Set the visible layer state\n    inline void SetVisibleLayer(Eigen::MatrixXd v){\n        v_=v;\n    }\n   \n    // Initialize the network parameters\n    void InitRandomPars(int seed,double sigma){\n        std::default_random_engine generator(seed);\n        std::normal_distribution<double> distribution(0,sigma);\n        for(int i=0;i<nh_;i++){\n            for(int j=0;j<nv_;j++){\n                W_(i,j)=distribution(generator);\n            }\n        }\n        //b_.setZero();\n        //c_.setZero();\n        for(int j=0;j<nv_;j++){\n            b_(j)=distribution(generator);\n        }\n        for(int i=0;i<nh_;i++){\n            c_(i)=distribution(generator);\n        }\n    }\n\n    // Compute derivative of the effective visible energy\n    Eigen::VectorXd VisEnergyGrad(const Eigen::VectorXd & v){\n        Eigen::VectorXd der(npar_);\n        int p=0;\n        logistic(W_*v+c_,gamma_);\n        for(int i=0;i<nh_;i++){\n            for(int j=0;j<nv_;j++){\n                der(p)=gamma_(i)*v(j);\n                p++;\n            }\n        }\n        for(int j=0;j<nv_;j++){\n            der(p)=v(j);\n            p++;\n        }\n        for(int i=0;i<nh_;i++){\n            der(p)=gamma_(i);\n            p++;\n        } \n        return -der;\n    }\n   \n    // Return the probability for state v\n    inline double prob(const Eigen::VectorXd & v){\n        ln1pexp(W_*v+c_,gamma_);\n        return std::exp(v.dot(b_)+gamma_.sum());\n    }\n    \n    // Conditional Probabilities \n    void ProbHiddenGivenVisible(const Eigen::MatrixXd &v,Eigen::MatrixXd &probs){\n        logistic((v*W_.transpose()).rowwise() + c_.transpose(),probs);\n    }\n    void ProbVisibleGivenHidden(const Eigen::MatrixXd &h,Eigen::MatrixXd &probs){\n        logistic((h*W_).rowwise() + b_.transpose(),probs);\n    }\n\n    // Sample one layer \n    void SampleLayer(Eigen::MatrixXd & hv,const Eigen::MatrixXd & probs){\n        std::uniform_real_distribution<double> distribution(0,1);\n        for(int s=0;s<hv.rows();s++){\n            for(int i=0;i<hv.cols();i++){\n                hv(s,i)=distribution(rgen_)<probs(s,i);\n            }\n        }\n    }\n    \n    // Perform k steps of Gibbs sampling\n    void Sample(int steps){\n        for(int k=0;k<steps;k++){\n            ProbHiddenGivenVisible(v_,probh_given_v_);\n            SampleLayer(h_,probh_given_v_);\n            ProbVisibleGivenHidden(h_,probv_given_h_);\n            SampleLayer(v_,probv_given_h_);\n        }\n    }\n   \n    // Get RBM parameters\n    Eigen::VectorXd GetParameters(){\n        Eigen::VectorXd pars(npar_);\n        int p=0;\n        for(int i=0;i<nh_;i++){\n            for(int j=0;j<nv_;j++){\n                pars(p)=W_(i,j);\n                p++;\n            }\n        }\n        for(int j=0;j<nv_;j++){\n            pars(p)=b_(j);\n            p++;\n        }\n        for(int i=0;i<nh_;i++){\n            pars(p)=c_(i);\n            p++;\n        }\n        return pars;\n    }\n    \n    // Set RBM parameters\n    void SetParameters(const Eigen::VectorXd & pars){\n        int p=0;\n        for(int i=0;i<nh_;i++){\n            for(int j=0;j<nv_;j++){\n                W_(i,j)=pars(p);\n                p++;\n            }\n        }\n        for(int j=0;j<nv_;j++){\n            b_(j)=pars(p);\n            p++;\n        }\n        for(int i=0;i<nh_;i++){\n            c_(i)=pars(p);\n            p++;\n        }\n    }\n\n    // Read weights from file \n    void LoadWeights(std::ifstream &fin){\n        for(int i=0;i<nh_;i++){\n            for(int j=0;j<nv_;j++){\n                fin >> W_(i,j);\n            }\n        }\n        for(int j=0;j<nv_;j++){\n            fin >> b_(j);\n        }\n        for(int i=0;i<nh_;i++){\n            fin >> c_(i);\n        }\n    }\n\n    // Read weights from file \n    void SaveWeights(std::ofstream &fout){\n        for(int i=0;i<nh_;i++){\n            for(int j=0;j<nv_;j++){\n                fout << W_(i,j) << \" \";\n            }\n            fout << std::endl;\n        }\n        fout << std::endl;\n        for(int j=0;j<nv_;j++){\n            fout <<  b_(j) << \" \";\n        }\n        fout << std::endl <<std::endl;\n        for(int i=0;i<nh_;i++){\n            fout << c_(i) << \" \";\n        }\n        fout << std::endl <<std::endl;\n    }\n \n    // Functions \n    inline void logistic(const Eigen::VectorXd & x,Eigen::VectorXd & y){\n        for(int i=0;i<x.size();i++){\n            y(i)=1./(1.+std::exp(-x(i)));;\n        }\n    }\n    inline void logistic(const Eigen::MatrixXd & x,Eigen::MatrixXd & y){\n        for(int i=0;i<x.rows();i++){\n            for(int j=0;j<x.cols();j++){\n                //y(i,j)=logistic(x(i,j));\n                y(i,j)=1./(1.+std::exp(-x(i,j)));\n            }\n        }\n    }\n    inline double ln1pexp(double x){\n        if(x>30){\n            return x;\n        }\n        return std::log1p(std::exp(x));\n    }\n    void ln1pexp(const Eigen::VectorXd & x,Eigen::VectorXd & y){\n        for(int i=0;i<x.size();i++){\n            y(i)=ln1pexp(x(i));\n        }\n    }\n\n };\n\n}\n\n#endif\n", "meta": {"hexsha": "847b835bbae6bd2681192e617dfb64d397f19cd6", "size": 6738, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qucumber/cpp/rbm.hpp", "max_stars_repo_name": "PatrickHuembeli/QuCumber", "max_stars_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-02T10:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-02T10:03:45.000Z", "max_issues_repo_path": "qucumber/cpp/rbm.hpp", "max_issues_repo_name": "PatrickHuembeli/QuCumber", "max_issues_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qucumber/cpp/rbm.hpp", "max_forks_repo_name": "PatrickHuembeli/QuCumber", "max_forks_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8446215139, "max_line_length": 87, "alphanum_fraction": 0.481596913, "num_tokens": 1744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4243897534465414}}
{"text": "//[ TArray\n///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2008 Eric Niebler. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// This example constructs a mini-library for linear algebra, using\n// expression templates to eliminate the need for temporaries when\n// adding arrays of numbers. It duplicates the TArray example from\n// PETE (http://www.codesourcery.com/pooma/download.html)\n\n#include <iostream>\n#include <boost/mpl/int.hpp>\n#include <boost/proto/core.hpp>\n#include <boost/proto/context.hpp>\nnamespace mpl = boost::mpl;\nnamespace proto = boost::proto;\nusing proto::_;\n\n// This grammar describes which TArray expressions\n// are allowed; namely, int and array terminals\n// plus, minus, multiplies and divides of TArray expressions.\nstruct TArrayGrammar\n  : proto::or_<\n        proto::terminal< int >\n      , proto::terminal< int[3] >\n      , proto::plus< TArrayGrammar, TArrayGrammar >\n      , proto::minus< TArrayGrammar, TArrayGrammar >\n      , proto::multiplies< TArrayGrammar, TArrayGrammar >\n      , proto::divides< TArrayGrammar, TArrayGrammar >\n    >\n{};\n\ntemplate<typename Expr>\nstruct TArrayExpr;\n\n// Tell proto that in the TArrayDomain, all\n// expressions should be wrapped in TArrayExpr<> and\n// must conform to the TArrayGrammar\nstruct TArrayDomain\n  : proto::domain<proto::generator<TArrayExpr>, TArrayGrammar>\n{};\n\n// Here is an evaluation context that indexes into a TArray\n// expression, and combines the result.\nstruct TArraySubscriptCtx\n  : proto::callable_context< TArraySubscriptCtx const >\n{\n    typedef int result_type;\n\n    TArraySubscriptCtx(std::ptrdiff_t i)\n      : i_(i)\n    {}\n\n    // Index array terminals with our subscript. Everything\n    // else will be handled by the default evaluation context.\n    int operator ()(proto::tag::terminal, int const (&data)[3]) const\n    {\n        return data[this->i_];\n    }\n\n    std::ptrdiff_t i_;\n};\n\n// Here is an evaluation context that prints a TArray expression.\nstruct TArrayPrintCtx\n  : proto::callable_context< TArrayPrintCtx const >\n{\n    typedef std::ostream &result_type;\n\n    TArrayPrintCtx() {}\n\n    std::ostream &operator ()(proto::tag::terminal, int i) const\n    {\n        return std::cout << i;\n    }\n\n    std::ostream &operator ()(proto::tag::terminal, int const (&arr)[3]) const\n    {\n        return std::cout << '{' << arr[0] << \", \" << arr[1] << \", \" << arr[2] << '}';\n    }\n\n    template<typename L, typename R>\n    std::ostream &operator ()(proto::tag::plus, L const &l, R const &r) const\n    {\n        return std::cout << '(' << l << \" + \" << r << ')';\n    }\n\n    template<typename L, typename R>\n    std::ostream &operator ()(proto::tag::minus, L const &l, R const &r) const\n    {\n        return std::cout << '(' << l << \" - \" << r << ')';\n    }\n\n    template<typename L, typename R>\n    std::ostream &operator ()(proto::tag::multiplies, L const &l, R const &r) const\n    {\n        return std::cout << l << \" * \" << r;\n    }\n\n    template<typename L, typename R>\n    std::ostream &operator ()(proto::tag::divides, L const &l, R const &r) const\n    {\n        return std::cout << l << \" / \" << r;\n    }\n};\n\n// Here is the domain-specific expression wrapper, which overrides\n// operator [] to evaluate the expression using the TArraySubscriptCtx.\ntemplate<typename Expr>\nstruct TArrayExpr\n  : proto::extends<Expr, TArrayExpr<Expr>, TArrayDomain>\n{\n    typedef proto::extends<Expr, TArrayExpr<Expr>, TArrayDomain> base_type;\n\n    TArrayExpr( Expr const & expr = Expr() )\n      : base_type( expr )\n    {}\n\n    // Use the TArraySubscriptCtx to implement subscripting\n    // of a TArray expression tree.\n    int operator []( std::ptrdiff_t i ) const\n    {\n        TArraySubscriptCtx const ctx(i);\n        return proto::eval(*this, ctx);\n    }\n\n    // Use the TArrayPrintCtx to display a TArray expression tree.\n    friend std::ostream &operator <<(std::ostream &sout, TArrayExpr<Expr> const &expr)\n    {\n        TArrayPrintCtx const ctx;\n        return proto::eval(expr, ctx);\n    }\n};\n\n// Here is our TArray terminal, implemented in terms of TArrayExpr\n// It is basically just an array of 3 integers.\nstruct TArray\n  : TArrayExpr< proto::terminal< int[3] >::type >\n{\n    explicit TArray( int i = 0, int j = 0, int k = 0 )\n    {\n        (*this)[0] = i;\n        (*this)[1] = j;\n        (*this)[2] = k;\n    }\n\n    // Here we override operator [] to give read/write access to\n    // the elements of the array. (We could use the TArrayExpr\n    // operator [] if we made the subscript context smarter about\n    // returning non-const reference when appropriate.)\n    int &operator [](std::ptrdiff_t i)\n    {\n        return proto::value(*this)[i];\n    }\n\n    int const &operator [](std::ptrdiff_t i) const\n    {\n        return proto::value(*this)[i];\n    }\n\n    // Here we define a operator = for TArray terminals that\n    // takes a TArray expression.\n    template< typename Expr >\n    TArray &operator =(Expr const & expr)\n    {\n        // proto::as_expr<TArrayDomain>(expr) is the same as\n        // expr unless expr is an integer, in which case it\n        // is made into a TArrayExpr terminal first.\n        return this->assign(proto::as_expr<TArrayDomain>(expr));\n    }\n\n    template< typename Expr >\n    TArray &printAssign(Expr const & expr)\n    {\n        *this = expr;\n        std::cout << *this << \" = \" << expr << std::endl;\n        return *this;\n    }\n\nprivate:\n    template< typename Expr >\n    TArray &assign(Expr const & expr)\n    {\n        // expr[i] here uses TArraySubscriptCtx under the covers.\n        (*this)[0] = expr[0];\n        (*this)[1] = expr[1];\n        (*this)[2] = expr[2];\n        return *this;\n    }\n};\n\nint main()\n{\n    TArray a(3,1,2);\n\n    TArray b;\n\n    std::cout << a << std::endl;\n    std::cout << b << std::endl;\n\n    b[0] = 7; b[1] = 33; b[2] = -99;\n\n    TArray c(a);\n\n    std::cout << c << std::endl;\n\n    a = 0;\n\n    std::cout << a << std::endl;\n    std::cout << b << std::endl;\n    std::cout << c << std::endl;\n\n    a = b + c;\n\n    std::cout << a << std::endl;\n\n    a.printAssign(b+c*(b + 3*c));\n\n    return 0;\n}\n//]\n", "meta": {"hexsha": "338f69b1e930261a9e5afbdf5c4fe49d019760dc", "size": 6204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/proto/example/tarray.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/proto/example/tarray.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/proto/example/tarray.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 27.8206278027, "max_line_length": 86, "alphanum_fraction": 0.608478401, "num_tokens": 1606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.42426315972413353}}
{"text": "/*!\n * @file demo.cpp\n * @author  (Aleksander Rybin)\n * @brief Threadpool example demo program for parallel matrix x vector multiply\n * @date 2021-09-15\n */\n\n// ---------------------\n// includes: STL\n#include <algorithm>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <random>\n#include <vector>\n\n// ---------------------\n// includes: boost\n#include <boost/program_options.hpp>\n\n// ---------------------\n// includes: local\n#include \"threadpool_example/threadpool.hpp\"\n\nstd::vector<int> generate(std::size_t size, std::function<int()> gen);\n\nvoid printMatrix(const std::vector<int>& matrix, std::size_t matrixRows, std::size_t matrixCols);\nvoid printVector(const std::vector<int>& vector);\n\nint main(int argc, char* argv[]) {\n    namespace po = boost::program_options;\n\n    po::options_description options(\"Allowed programm options\");\n\n    std::size_t threadsNum;\n    bool        verboseOutput;\n\n    std::size_t matrixRows;\n    std::size_t matrixCols;\n\n    // clang-format off\n    options.add_options()\n        (\"help,h\", \"produce help message\")\n        (\"threads_num,t\", po::value<std::size_t>(&threadsNum)->default_value(std::thread::hardware_concurrency() - 1), \"number of threads to run\")\n        (\"verbose,v\", po::value<bool>(&verboseOutput)->default_value(false), \"verbose output\")\n        (\"matrix_rows\", po::value<std::size_t>(&matrixRows)->default_value(10000), \"number of rows in multiplied matrix\")\n        (\"matrix_cols\", po::value<std::size_t>(&matrixCols)->default_value(10000), \"number of cols in multiplied matrix\");\n    // clang-format on\n\n    po::variables_map vm;\n\n    try {\n        po::store(po::parse_command_line(argc, argv, options), vm);\n        po::notify(vm);\n    } catch (const po::error& e) {\n        std::cerr << e.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n\n    if (vm.count(\"help\")) {\n        std::cout << options << std::endl;\n        return EXIT_SUCCESS;\n    }\n\n    try {\n        std::random_device                 randomDevice;\n        std::mt19937                       mersenneEngine{randomDevice()};\n        std::uniform_int_distribution<int> distribution{-9, 9};\n        auto gen = [&distribution, &mersenneEngine] { return distribution(mersenneEngine); };\n\n        std::vector<int> matrix = generate(matrixRows * matrixCols, gen);\n        std::vector<int> vector = generate(matrixCols, gen);\n\n        std::vector<int> result(matrixRows);\n\n        if (verboseOutput) {\n            printMatrix(matrix, matrixRows, matrixCols);\n            printVector(vector);\n        }\n\n        try {\n            threadpool_example::ThreadPool thp(threadsNum);\n\n            std::size_t rowsPerThread = matrixRows / threadsNum;\n            for (std::size_t i = 0; i < threadsNum; ++i) {\n                thp.enqueue([=, &matrix, &vector, &result] {\n                    for (std::size_t j = i * rowsPerThread; j < (i + 1) * rowsPerThread; ++j) {\n                        int currentResult = 0;\n                        for (std::size_t k = 0; k < matrixCols; ++k) {\n                            currentResult += matrix[j * matrixCols + k] * vector[k];\n                        }\n                        result[j] = currentResult;\n                    }\n                });\n            }\n        } catch (const std::system_error& e) {\n            std::cerr << \"thread error\" << std::endl;\n            return EXIT_FAILURE;\n        }\n\n        if (verboseOutput) {\n            printVector(result);\n        }\n    } catch (const std::bad_alloc& e) {\n        std::cerr << \"bad alock\" << std::endl;\n        return EXIT_FAILURE;\n    } catch (const std::exception& e) {\n        std::cerr << e.what() << std::endl;\n        return EXIT_FAILURE;\n    } catch (...) {\n        std::cerr << \"unknown error\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    return EXIT_SUCCESS;\n}\n\nstd::vector<int> generate(std::size_t size, std::function<int()> gen) {\n    std::vector<int> result(size);\n    std::generate(result.begin(), result.end(), gen);\n    return result;\n}\n\nvoid printMatrix(const std::vector<int>& matrix, std::size_t matrixRows, std::size_t matrixCols) {\n    std::cout << \"\\n\";\n    for (std::size_t i = 0; i < matrixRows; ++i) {\n        for (std::size_t j = 0; j < matrixCols; ++j) {\n            std::cout << std::setw(2) << matrix[i * matrixCols + j] << ' ';\n        }\n        std::cout << \"\\n\";\n    }\n    std::cout << std::endl;\n}\n\nvoid printVector(const std::vector<int>& vector) {\n    std::cout << \"\\n\";\n    for (std::size_t i = 0; i < vector.size(); ++i) {\n        std::cout << std::setw(2) << vector[i] << ' ';\n    }\n    std::cout << std::endl;\n}\n", "meta": {"hexsha": "4333341fcdc9dcb14ddf4282729f1b5871e9a442", "size": 4590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/threadpool_example/demo.cpp", "max_stars_repo_name": "AleksandrRybin/threadpool-example", "max_stars_repo_head_hexsha": "68f6b21e5682df46f97c5c021d6001d3a4df3d31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/threadpool_example/demo.cpp", "max_issues_repo_name": "AleksandrRybin/threadpool-example", "max_issues_repo_head_hexsha": "68f6b21e5682df46f97c5c021d6001d3a4df3d31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/threadpool_example/demo.cpp", "max_forks_repo_name": "AleksandrRybin/threadpool-example", "max_forks_repo_head_hexsha": "68f6b21e5682df46f97c5c021d6001d3a4df3d31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.323943662, "max_line_length": 146, "alphanum_fraction": 0.5607843137, "num_tokens": 1133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.6477982247516796, "lm_q1q2_score": 0.4242396341461651}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 2011 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n * \n * Authors: Joerg Frohne, Texas A&M University and \n *                        University of Siegen, 2011, 2012 \n *          Wolfgang Bangerth, Texas A&M University, 2012 \n */ \n\n\n// @sect3{Include files}  \n\n// 像往常一样，在开始的时候，我们把所有我们需要的头文件都包含在这里。除了为Trilinos库提供接口的各种文件外，没有什么意外。\n\n#include <deal.II/base/quadrature_lib.h> \n#include <deal.II/base/function.h> \n#include <deal.II/base/index_set.h> \n\n#include <deal.II/lac/affine_constraints.h> \n#include <deal.II/lac/vector.h> \n#include <deal.II/lac/full_matrix.h> \n#include <deal.II/lac/dynamic_sparsity_pattern.h> \n#include <deal.II/lac/solver_cg.h> \n#include <deal.II/lac/trilinos_sparse_matrix.h> \n#include <deal.II/lac/trilinos_vector.h> \n#include <deal.II/lac/trilinos_precondition.h> \n\n#include <deal.II/grid/tria.h> \n#include <deal.II/grid/grid_generator.h> \n\n#include <deal.II/fe/fe_q.h> \n#include <deal.II/fe/fe_values.h> \n\n#include <deal.II/dofs/dof_handler.h> \n#include <deal.II/dofs/dof_tools.h> \n\n#include <deal.II/numerics/vector_tools.h> \n#include <deal.II/numerics/data_out.h> \n\n#include <fstream> \n#include <iostream> \n\nnamespace Step41 \n{ \n  using namespace dealii; \n// @sect3{The <code>ObstacleProblem</code> class template}  \n\n// 该类提供了描述障碍问题所需的所有函数和变量。它与我们在 step-4 中要做的事情很接近，所以相对简单。唯一真正的新组件是计算主动集合的update_solution_and_constraints函数和一些描述线性系统原始（无约束）形式所需的变量（ <code>complete_system_matrix</code> 和 <code>complete_system_rhs</code> ），以及主动集合本身和主动集合公式中用于缩放拉格朗日乘数的质量矩阵 $B$ 的对角线。其余的内容与 step-4 相同。\n\n  template <int dim> \n  class ObstacleProblem \n  { \n  public: \n    ObstacleProblem(); \n    void run(); \n\n  private: \n    void make_grid(); \n    void setup_system(); \n    void assemble_system(); \n    void \n         assemble_mass_matrix_diagonal(TrilinosWrappers::SparseMatrix &mass_matrix); \n    void update_solution_and_constraints(); \n    void solve(); \n    void output_results(const unsigned int iteration) const; \n\n    Triangulation<dim>        triangulation; \n    FE_Q<dim>                 fe; \n    DoFHandler<dim>           dof_handler; \n    AffineConstraints<double> constraints; \n    IndexSet                  active_set; \n\n    TrilinosWrappers::SparseMatrix system_matrix; \n    TrilinosWrappers::SparseMatrix complete_system_matrix; \n\n    TrilinosWrappers::MPI::Vector solution; \n    TrilinosWrappers::MPI::Vector system_rhs; \n    TrilinosWrappers::MPI::Vector complete_system_rhs; \n    TrilinosWrappers::MPI::Vector diagonal_of_mass_matrix; \n    TrilinosWrappers::MPI::Vector contact_force; \n  }; \n// @sect3{Right hand side, boundary values, and the obstacle}  \n\n// 在下文中，我们定义了描述右侧函数、Dirichlet边界值以及作为 $\\mathbf x$ 函数的障碍物高度的类。在这三种情况下，我们都从函数 @<dim@>, 派生出这些类，尽管在 <code>RightHandSide</code> 和 <code>Obstacle</code> 的情况下，这更多的是出于惯例而非必要，因为我们从未将此类对象传递给库。在任何情况下，鉴于我们选择了 $f=-10$  ,  $u|_{\\partial\\Omega}=0$  ...，右手和边界值类的定义是显而易见的。\n\n  template <int dim> \n  class RightHandSide : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & /*p*/, \n                         const unsigned int component = 0) const override \n    { \n      (void)component; \n      AssertIndexRange(component, 1); \n\n      return -10; \n    } \n  }; \n\n  template <int dim> \n  class BoundaryValues : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & /*p*/, \n                         const unsigned int component = 0) const override \n    { \n      (void)component; \n      AssertIndexRange(component, 1); \n\n      return 0; \n    } \n  }; \n\n// 我们用一个级联的障碍物来描述障碍物的功能（想想看：楼梯的阶梯）。\n\n  template <int dim> \n  class Obstacle : public Function<dim> \n  { \n  public: \n    virtual double value(const Point<dim> & p, \n                         const unsigned int component = 0) const override \n    { \n      (void)component; \n      Assert(component == 0, ExcIndexRange(component, 0, 1)); \n\n      if (p(0) < -0.5) \n        return -0.2; \n      else if (p(0) >= -0.5 && p(0) < 0.0) \n        return -0.4; \n      else if (p(0) >= 0.0 && p(0) < 0.5) \n        return -0.6; \n      else \n        return -0.8; \n    } \n  }; \n\n//  @sect3{Implementation of the <code>ObstacleProblem</code> class}  \n// @sect4{ObstacleProblem::ObstacleProblem}  \n\n// 对每个看过前几个教程程序的人来说，构造函数是完全显而易见的。\n\n  template <int dim> \n  ObstacleProblem<dim>::ObstacleProblem() \n    : fe(1) \n    , dof_handler(triangulation) \n  {} \n// @sect4{ObstacleProblem::make_grid}  \n\n// 我们在二维的正方形 $[-1,1]\\times [-1,1]$ 上解决我们的障碍物问题。因此这个函数只是设置了一个最简单的网格。\n\n  template <int dim> \n  void ObstacleProblem<dim>::make_grid() \n  { \n    GridGenerator::hyper_cube(triangulation, -1, 1); \n    triangulation.refine_global(7); \n\n    std::cout << \"Number of active cells: \" << triangulation.n_active_cells() \n              << std::endl \n              << \"Total number of cells: \" << triangulation.n_cells() \n              << std::endl; \n  } \n// @sect4{ObstacleProblem::setup_system}  \n\n// 在这个值得注意的第一个函数中，我们设置了自由度处理程序，调整了向量和矩阵的大小，并处理了约束。最初，约束条件当然只是由边界值给出的，所以我们在函数的顶部对它们进行插值。\n\n  template <int dim> \n  void ObstacleProblem<dim>::setup_system() \n  { \n    dof_handler.distribute_dofs(fe); \n    active_set.set_size(dof_handler.n_dofs()); \n\n    std::cout << \"Number of degrees of freedom: \" << dof_handler.n_dofs() \n              << std::endl \n              << std::endl; \n\n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             BoundaryValues<dim>(), \n                                             constraints); \n    constraints.close(); \n\n    DynamicSparsityPattern dsp(dof_handler.n_dofs()); \n    DoFTools::make_sparsity_pattern(dof_handler, dsp, constraints, false); \n\n    system_matrix.reinit(dsp); \n    complete_system_matrix.reinit(dsp); \n\n    IndexSet solution_index_set = dof_handler.locally_owned_dofs(); \n    solution.reinit(solution_index_set, MPI_COMM_WORLD); \n    system_rhs.reinit(solution_index_set, MPI_COMM_WORLD); \n    complete_system_rhs.reinit(solution_index_set, MPI_COMM_WORLD); \n    contact_force.reinit(solution_index_set, MPI_COMM_WORLD); \n\n// 这里唯一要做的事情是计算 $B$ 矩阵中的因子，该矩阵用于缩放残差。正如在介绍中所讨论的，我们将使用一个小技巧来使这个质量矩阵成为对角线，在下文中，首先将所有这些计算成一个矩阵，然后提取对角线元素供以后使用。\n\n    TrilinosWrappers::SparseMatrix mass_matrix; \n    mass_matrix.reinit(dsp); \n    assemble_mass_matrix_diagonal(mass_matrix); \n    diagonal_of_mass_matrix.reinit(solution_index_set); \n    for (unsigned int j = 0; j < solution.size(); j++) \n      diagonal_of_mass_matrix(j) = mass_matrix.diag_element(j); \n  } \n// @sect4{ObstacleProblem::assemble_system}  \n\n// 这个函数一次就把系统矩阵和右手边集合起来，并把约束条件（由于活动集以及来自边界值）应用到我们的系统中。否则，它在功能上等同于例如  step-4  中的相应函数。\n\n  template <int dim> \n  void ObstacleProblem<dim>::assemble_system() \n  { \n    std::cout << \"   Assembling system...\" << std::endl; \n\n    system_matrix = 0; \n    system_rhs    = 0; \n\n    const QGauss<dim>  quadrature_formula(fe.degree + 1); \n    RightHandSide<dim> right_hand_side; \n\n    FEValues<dim> fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_gradients | \n                              update_quadrature_points | update_JxW_values); \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n    Vector<double>     cell_rhs(dofs_per_cell); \n\n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      { \n        fe_values.reinit(cell); \n        cell_matrix = 0; \n        cell_rhs    = 0; \n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            { \n              for (unsigned int j = 0; j < dofs_per_cell; ++j) \n                cell_matrix(i, j) += \n                  (fe_values.shape_grad(i, q_point) * \n                   fe_values.shape_grad(j, q_point) * fe_values.JxW(q_point)); \n\n              cell_rhs(i) += \n                (fe_values.shape_value(i, q_point) * \n                 right_hand_side.value(fe_values.quadrature_point(q_point)) * \n                 fe_values.JxW(q_point)); \n            } \n\n        cell->get_dof_indices(local_dof_indices); \n\n        constraints.distribute_local_to_global(cell_matrix, \n                                               cell_rhs, \n                                               local_dof_indices, \n                                               system_matrix, \n                                               system_rhs, \n                                               true); \n      } \n  } \n\n//  @sect4{ObstacleProblem::assemble_mass_matrix_diagonal}  \n\n// 下一个函数用于计算对角线质量矩阵 $B$ ，用于在主动集方法中缩放变量。正如介绍中所讨论的，我们通过选择正交的梯形规则来获得质量矩阵的对角线。这样一来，我们就不再需要在正交点、指数 $i$ 和指数 $j$ 上进行三重循环，而是可以直接使用双重循环。考虑到我们在以前的许多教程程序中讨论过的内容，该函数的其余部分是显而易见的。\n\n// 注意在调用这个函数的时候，约束对象只包含边界值约束；因此我们在最后的复制-本地-全局步骤中不必注意保留矩阵项的值，这些项以后可能会受到活动集的约束。\n\n// 还需要注意的是，只有在我们拥有 $Q_1$ 元素的情况下，使用梯形规则的技巧才有效。对于更高阶的元素，我们需要使用一个正交公式，在有限元的所有支持点都有正交点。构建这样一个正交公式其实并不难，但不是这里的重点，所以我们只是在函数的顶部断言我们对有限元的隐含假设实际上得到了满足。\n\n  template <int dim> \n  void ObstacleProblem<dim>::assemble_mass_matrix_diagonal( \n    TrilinosWrappers::SparseMatrix &mass_matrix) \n  { \n    Assert(fe.degree == 1, ExcNotImplemented()); \n\n    const QTrapezoid<dim> quadrature_formula; \n    FEValues<dim>         fe_values(fe, \n                            quadrature_formula, \n                            update_values | update_JxW_values); \n\n    const unsigned int dofs_per_cell = fe.n_dofs_per_cell(); \n    const unsigned int n_q_points    = quadrature_formula.size(); \n\n    FullMatrix<double> cell_matrix(dofs_per_cell, dofs_per_cell); \n    std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell); \n\n \n      { \n        fe_values.reinit(cell); \n        cell_matrix = 0; \n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) \n          for (unsigned int i = 0; i < dofs_per_cell; ++i) \n            cell_matrix(i, i) += \n              (fe_values.shape_value(i, q_point) * \n               fe_values.shape_value(i, q_point) * fe_values.JxW(q_point)); \n\n        cell->get_dof_indices(local_dof_indices); \n\n        constraints.distribute_local_to_global(cell_matrix, \n                                               local_dof_indices, \n                                               mass_matrix); \n      } \n  } \n// @sect4{ObstacleProblem::update_solution_and_constraints}  \n\n// 在某种意义上，这是本程序的核心功能。 它更新了介绍中所讨论的受限自由度的活动集，并从中计算出一个AffineConstraints对象，然后可以用来在下一次迭代的解中消除受限自由度。同时，我们将解决方案的受限自由度设置为正确的值，即障碍物的高度。\n\n// 从根本上说，这个函数是相当简单的。我们必须在所有自由度上循环，并检查函数 $\\Lambda^k_i + c([BU^k]_i - G_i) = \\Lambda^k_i + cB_i(U^k_i - [g_h]_i)$ 的符号，因为在我们的例子中 $G_i = B_i[g_h]_i$  。为此，我们使用介绍中给出的公式，通过该公式我们可以计算出拉格朗日乘数，作为原始线性系统的残差（通过变量 <code>complete_system_matrix</code> and <code>complete_system_rhs</code> 给出。在这个函数的顶部，我们使用一个属于矩阵类的函数来计算这个残差。\n\n  template <int dim> \n  void ObstacleProblem<dim>::update_solution_and_constraints() \n  { \n    std::cout << \"   Updating active set...\" << std::endl; \n\n    const double penalty_parameter = 100.0; \n\n    TrilinosWrappers::MPI::Vector lambda( \n      complete_index_set(dof_handler.n_dofs())); \n    complete_system_matrix.residual(lambda, solution, complete_system_rhs); \n\n// 计算 contact_force[i] =\n\n// - lambda[i] * diagonal_of_mass_matrix[i]。\n\n    contact_force = lambda; \n    contact_force.scale(diagonal_of_mass_matrix); \n    contact_force *= -1; \n\n// 下一步是重置活动集和约束对象，并在所有自由度上开始循环。由于我们不能只是在解向量的所有元素上循环，所以这变得稍微复杂了一些，因为我们没有办法找出一个自由度与哪个位置相关；但是，我们需要这个位置来测试一个自由度的位移是大于还是小于这个位置的障碍物高度。\n\n// 我们通过在所有单元和定义在每个单元上的DoF上循环来解决这个问题。我们在这里使用一个 $Q_1$ 函数来描述位移，对于该函数，自由度总是位于单元格的顶点上；因此，我们可以通过询问顶点来获得每个自由度的索引及其位置。另一方面，这显然对高阶元素不起作用，因此我们添加了一个断言，确保我们只处理所有自由度都位于顶点的元素，以避免万一有人想玩增加解的多项式程度时用非功能性代码绊倒自己。\n\n// 循环单元格而不是自由度的代价是我们可能会多次遇到一些自由度，即每次我们访问与给定顶点相邻的一个单元格时。因此，我们必须跟踪我们已经接触过的顶点和尚未接触的顶点。我们通过使用一个标志数组来做到这一点  <code>dof_touched</code>  。\n\n    constraints.clear(); \n    active_set.clear(); \n\n    const Obstacle<dim> obstacle; \n    std::vector<bool>   dof_touched(dof_handler.n_dofs(), false); \n\n    for (const auto &cell : dof_handler.active_cell_iterators()) \n      for (const auto v : cell->vertex_indices()) \n        { \n          Assert(dof_handler.get_fe().n_dofs_per_cell() == cell->n_vertices(), \n                 ExcNotImplemented()); \n\n          const unsigned int dof_index = cell->vertex_dof_index(v, 0); \n\n          if (dof_touched[dof_index] == false) \n            dof_touched[dof_index] = true; \n          else \n            continue; \n\n// 现在我们知道我们还没有触及这个DoF，让我们得到那里的位移函数的值以及障碍函数的值，并使用这个来决定当前DoF是否属于活动集。为此，我们使用上面和介绍中给出的函数。\n\n// 如果我们决定该DoF应该是活动集的一部分，我们将其索引添加到活动集中，在AffineConstraints对象中引入一个不均匀的平等约束，并将解的值重置为障碍物的高度。最后，系统的非接触部分的残差作为一个额外的控制（残差等于剩余的、未计算的力，在接触区之外应该为零），所以我们把残差向量的分量（即拉格朗日乘数lambda）清零，这些分量对应于身体接触的区域；在所有单元的循环结束时，残差将因此只包括非接触区的残差。我们在循环结束后输出这个残差的准则和活动集的大小。\n\n          const double obstacle_value = obstacle.value(cell->vertex(v)); \n          const double solution_value = solution(dof_index); \n\n          if (lambda(dof_index) + penalty_parameter * \n                                    diagonal_of_mass_matrix(dof_index) * \n                                    (solution_value - obstacle_value) < \n              0) \n            { \n              active_set.add_index(dof_index); \n              constraints.add_line(dof_index); \n              constraints.set_inhomogeneity(dof_index, obstacle_value); \n\n              solution(dof_index) = obstacle_value; \n\n              lambda(dof_index) = 0; \n            } \n        } \n    std::cout << \"      Size of active set: \" << active_set.n_elements() \n              << std::endl; \n\n    std::cout << \"   Residual of the non-contact part of the system: \" \n              << lambda.l2_norm() << std::endl; \n\n// 在最后一步中，我们将迄今为止从活动集合中得到的对DoF的约束加入到那些由Dirichlet边界值产生的约束中，并关闭约束对象。\n\n    VectorTools::interpolate_boundary_values(dof_handler, \n                                             0, \n                                             BoundaryValues<dim>(), \n                                             constraints); \n    constraints.close(); \n  } \n// @sect4{ObstacleProblem::solve}  \n\n// 关于求解函数，其实没有什么可说的。在牛顿方法的背景下，我们通常对非常高的精度不感兴趣（为什么要求一个高度精确的线性问题的解，而我们知道它只能给我们一个非线性问题的近似解），所以我们使用ReductionControl类，当达到一个绝对公差（为此我们选择 $10^{-12}$ ）或者当残差减少一定的系数（这里是 $10^{-3}$ ）时停止反复运算。\n\n  template <int dim> \n  void ObstacleProblem<dim>::solve() \n  { \n    std::cout << \"   Solving system...\" << std::endl; \n\n    ReductionControl                        reduction_control(100, 1e-12, 1e-3); \n    SolverCG<TrilinosWrappers::MPI::Vector> solver(reduction_control); \n    TrilinosWrappers::PreconditionAMG       precondition; \n    precondition.initialize(system_matrix); \n\n    solver.solve(system_matrix, solution, system_rhs, precondition); \n    constraints.distribute(solution); \n\n    std::cout << \"      Error: \" << reduction_control.initial_value() << \" -> \" \n              << reduction_control.last_value() << \" in \" \n              << reduction_control.last_step() << \" CG iterations.\" \n              << std::endl; \n  } \n// @sect4{ObstacleProblem::output_results}  \n\n// 我们使用vtk-format进行输出。 该文件包含位移和活动集的数字表示。\n\n  template <int dim> \n  void ObstacleProblem<dim>::output_results(const unsigned int iteration) const \n  { \n    std::cout << \"   Writing graphical output...\" << std::endl; \n\n    TrilinosWrappers::MPI::Vector active_set_vector( \n      dof_handler.locally_owned_dofs(), MPI_COMM_WORLD); \n    for (const auto index : active_set) \n      active_set_vector[index] = 1.; \n\n    DataOut<dim> data_out; \n\n    data_out.attach_dof_handler(dof_handler); \n    data_out.add_data_vector(solution, \"displacement\"); \n    data_out.add_data_vector(active_set_vector, \"active_set\"); \n    data_out.add_data_vector(contact_force, \"lambda\"); \n\n    data_out.build_patches(); \n\n    std::ofstream output_vtk(\"output_\" + \n                             Utilities::int_to_string(iteration, 3) + \".vtk\"); \n    data_out.write_vtk(output_vtk); \n  } \n\n//  @sect4{ObstacleProblem::run}  \n\n// 这是一个对所有事情都有最高级别控制的函数。 它并不长，而且事实上相当直接：在主动集方法的每一次迭代中，我们都要组装线性系统，求解它，更新主动集并将解投射回可行集，然后输出结果。只要主动集在前一次迭代中没有变化，迭代就会终止。\n\n// 唯一比较棘手的部分是，我们必须在第一次迭代组装好线性系统（即矩阵和右手边）后保存它。原因是这是唯一一个我们可以在没有任何接触约束的情况下访问线性系统的步骤。我们需要这个来计算其他迭代中解决方案的残差，但是在其他迭代中，我们形成的线性系统中对应于约束自由度的行和列都被消除了，因此我们不能再访问原始方程的全部残差。\n\n  template <int dim> \n  void ObstacleProblem<dim>::run() \n  { \n    make_grid(); \n    setup_system(); \n\n    IndexSet active_set_old(active_set); \n    for (unsigned int iteration = 0; iteration <= solution.size(); ++iteration) \n      { \n        std::cout << \"Newton iteration \" << iteration << std::endl; \n\n        assemble_system(); \n\n        if (iteration == 0) \n          { \n            complete_system_matrix.copy_from(system_matrix); \n            complete_system_rhs = system_rhs; \n          } \n\n        solve(); \n        update_solution_and_constraints(); \n        output_results(iteration); \n\n        if (active_set == active_set_old) \n          break; \n\n        active_set_old = active_set; \n\n        std::cout << std::endl; \n      } \n  } \n} // namespace Step41 \n// @sect3{The <code>main</code> function}  \n\n// 这就是主函数。它遵循所有其他主函数的模式。调用初始化MPI是因为我们在这个程序中建立线性求解器的Trilinos库需要它。\n\nint main(int argc, char *argv[]) \n{ \n  try \n    { \n      using namespace dealii; \n      using namespace Step41; \n\n      Utilities::MPI::MPI_InitFinalize mpi_initialization( \n        argc, argv, numbers::invalid_unsigned_int); \n\n// 这个程序只能在串行中运行。否则，将抛出一个异常。\n\n      AssertThrow(Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD) == 1, \n                  ExcMessage( \n                    \"This program can only be run in serial, use ./step-41\")); \n\n      ObstacleProblem<2> obstacle_problem; \n      obstacle_problem.run(); \n    } \n  catch (std::exception &exc) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Exception on processing: \" << std::endl \n                << exc.what() << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n\n      return 1; \n    } \n  catch (...) \n    { \n      std::cerr << std::endl \n                << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      std::cerr << \"Unknown exception!\" << std::endl \n                << \"Aborting!\" << std::endl \n                << \"----------------------------------------------------\" \n                << std::endl; \n      return 1; \n    } \n\n  return 0; \n} \n\n\n", "meta": {"hexsha": "d38e355177ccc81d6d1c6a4cd4f552cd754a2340", "size": 19077, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-41/step-41.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-41/step-41.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-41/step-41.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0036697248, "max_line_length": 306, "alphanum_fraction": 0.6216910416, "num_tokens": 6708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.4242396295137161}}
{"text": "#include \"lum_retinex.h\"\n\n#include <Eigen/SparseCore>\n#include <Eigen/SparseCholesky>\n#include <chrono>\n\nnamespace lum {\n\n    // timing helper\n\tdouble get_s() {\n\t\tusing namespace std::chrono;\n\t\tauto now = system_clock::now();\n\t\tsystem_clock::duration tse = now.time_since_epoch();\n\t\treturn duration_cast<nanoseconds>(tse).count() / 1e9;\n\t}\n\n    // Helper image processing routines\n\tvoid log(const float* inimg, float* outimg, int sz) {\n#ifdef USE_MKL\n\t\tvsLn(sz, inimg, outimg);\n#else\n\t\tfor (int i = 0; i < sz; ++i) {\n\t\t\tfloat in = inimg[i];\n\t\t\toutimg[i] = std::logf(inimg[i] + 0.00001);\n\t\t}\n#endif\n\t}\n\n\tvoid exp(const float* inimg, float* outimg, int sz) {\n#ifdef USE_MKL\n\t\tvsExp(sz, inimg, outimg);\n#else\n\t\tfor (int i = 0; i < sz; ++i) {\n\t\t\toutimg[i] = std::expf(inimg[i]);\n\t\t}\n#endif\n\t}\n\tvoid mean(const float* inimg, float* outimg, int outsz) {\n\t\tfor (int i = 0; i < outsz; ++i) {\n\t\t\toutimg[i] = (inimg[i * 3] + inimg[i * 3 + 1] + inimg[i * 3 + 2]) / 3;\n\t\t}\n\t}\n\n\n\t// helpers for image indices\n\tclass reflshadidx {\n\tpublic:\n\t\treflshadidx(int w, int h)\n\t\t:m_w(w), m_h(h){}\n\t\tint reflidx(int x, int y) const {\n\t\t\treturn m_w * y + x;\n\t\t}\n\t\tint shadidx(int x, int y) const {\n\t\t\treturn m_w * m_h + reflidx(x, y);\n\t\t}\n\tprivate:\n\t\tint m_w;\n\t\tint m_h;\n\t};\n\tclass imwrap {\n\tpublic:\n\t\timwrap(const float* img, int w, int h)\n\t\t:m_w(w), m_h(h), m_img(img){ }\n\n\t\tfloat operator()(int x, int y) const {\n\t\t\tassert(x >= 0);\n\t\t\tassert(y >= 0);\n\t\t\tassert(x < m_w);\n\t\t\tassert(y < m_h);\n\t\t\treturn m_img[m_w * y + x];\n\t\t}\n\tprivate:\n\t\tconst float* m_img;\n\t\tint m_w;\n\t\tint m_h;\n\t};\n\n\t// forward declaration of internal functions\n\tvoid reflect_clamp(int w, int h, float* refl_in, float* shading_in);\n\tvoid preprocess(int w, int h, const float* img, float* logimg);\n\tvoid postprocess(int w, int h, float* refl_in, float* shading_in, float* refl_out, float* shading_out);\n\tEigen::VectorXf makeB(float threshold, const float* im, int w, int h);\n\n\tusing Triplet = Eigen::Triplet<float>;\n\tint nconstraints(int w, int h) {\n\t\treturn w*h + 2 * w*(h - 1) + 2 * (w - 1) * h;\n\t}\n\tint nentries(int w, int h) {\n\t\treturn 2 * (w*h + 2 * w*(h - 1) + 2 * (w - 1) * h);\n\t}\n\tstd::vector<Triplet> makeTriplets(int w, int h) {\n\t\treflshadidx I(w, h);\n\t\tprintf(\"Assemble matrix.\\n\");\n\t\tdouble assemble_start = get_s();\n\t\tstd::vector <Triplet> entries;\n\t\tint cit = 0;\n\t\tfor (int y = 0; y < h; ++y) {\n\t\t\tfor (int x = 0; x < w; ++x) {\n\t\t\t\tif (x < w - 1) {\n\t\t\t\t\t// dxR(r, c) = -lR(r, c) + lR(r, c + 1)\n\t\t\t\t\tentries.push_back(Triplet(cit, I.reflidx(x, y), -1));\n\t\t\t\t\tentries.push_back(Triplet(cit, I.reflidx(x + 1, y), +1));\n\t\t\t\t\tcit++;\n\n\t\t\t\t\t// dxS(r, c) = -lS(r, c) + lS(r, c + 1)\n\t\t\t\t\tentries.push_back(Triplet(cit, I.shadidx(x, y), -1));\n\t\t\t\t\tentries.push_back(Triplet(cit, I.shadidx(x + 1, y), +1));\n\t\t\t\t\tcit++;\n\t\t\t\t}\n\t\t\t\tif (y < h - 1) {\n\t\t\t\t\tentries.push_back(Triplet(cit, I.reflidx(x, y), -1));\n\t\t\t\t\tentries.push_back(Triplet(cit, I.reflidx(x, y + 1), +1));\n\t\t\t\t\tcit++;\n\n\t\t\t\t\tentries.push_back(Triplet(cit, I.shadidx(x, y), -1));\n\t\t\t\t\tentries.push_back(Triplet(cit, I.shadidx(x, y + 1), +1));\n\t\t\t\t\tcit++;\n\t\t\t\t\t// dyR(r, c) = -lR(r, c) + lR(r + 1)\n\t\t\t\t\t// dyS(r, c) = -lS(r, c) + lS(r + 1)\n\t\t\t\t}\n\n\t\t\t\t// reflectance plus shading (log space) == final image\n\t\t\t\tentries.push_back(Triplet(cit, I.reflidx(x, y), 1));\n\t\t\t\tentries.push_back(Triplet(cit, I.shadidx(x, y), 1));\n\t\t\t\tcit++;\n\t\t\t}\n\t\t}\n\t\tassert(entries.size() == nentries(w, h));\n\t\tdouble assemble_end = get_s();\n\t\tprintf(\"Makemtx took %.1fms\\n\", (assemble_end- assemble_start) * 1000);\n\t\treturn entries;\n\t}\n\n\t// to log domain\n\tvoid preprocess(int w, int h, const float* img, float* logimg) {\n\t\tprintf(\"Start Preprocessing.\\n\");\n\t\tdouble preprocess_start = get_s();\n\t\tlog(img, logimg, w*h);\n\t\tdouble preprocess_b_end = get_s();\n\t\tprintf(\"Preprocess took %.1fms\\n\", (preprocess_b_end - preprocess_start) * 1000);\n\t}\n\n\t// back to linear\n\tvoid postprocess(int w, int h, float* refl_in, float* shading_in, float* refl_out, float* shading_out) {\n\t\tprintf(\"Post process start.\\n\");\n\t\tdouble postprocess_start = get_s();\n\t\treflect_clamp(w, h, refl_in, shading_in);\n\t\texp(refl_in, refl_out, w*h);\n\t\texp(shading_in, shading_out, w*h);\n\t\tdouble postprocess_end = get_s();\n\t\tprintf(\"Postprocess took %.1fms\\n\", (postprocess_end - postprocess_start)*1000 );\n\t}\n\n\tEigen::VectorXf makeB(float threshold, const float* im, int w, int h) {\n\t\tEigen::VectorXf b(nconstraints(w, h));\n\t\tdouble assemble_b_start = get_s();\n\t\timwrap I(im, w, h);\n\t\tint cit = 0;\n\t\tfor (int y = 0; y < h; ++y) {\n\t\t\tfor (int x = 0; x < w; ++x) {\n\t\t\t\tif (x < w - 1) {\n\t\t\t\t\tfloat dx = -I(x, y) + I(x + 1, y);\n\t\t\t\t\tfloat dxR;\n\t\t\t\t\tfloat dxS;\n\t\t\t\t\tif (std::abs(dx) > threshold) {\n\t\t\t\t\t\tdxR = dx;\n\t\t\t\t\t\tdxS = 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdxR = 0;\n\t\t\t\t\t\tdxS = dx;\n\t\t\t\t\t}\n\t\t\t\t\t// dxR(r, c) = -lR(r, c) + lR(r, c + 1)\n\t\t\t\t\tb(cit++) = dxR;\n\n\t\t\t\t\t// dxS(r, c) = -lS(r, c) + lS(r, c + 1)\n\t\t\t\t\tb(cit++) = dxS;\n\t\t\t\t}\n\t\t\t\tif (y < h - 1) {\n\t\t\t\t\tfloat dy = -I(x, y) + I(x, y + 1);\n\t\t\t\t\tfloat dyR;\n\t\t\t\t\tfloat dyS;\n\t\t\t\t\tif (std::abs(dy) > threshold) {\n\t\t\t\t\t\tdyR = dy;\n\t\t\t\t\t\tdyS = 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdyR = 0;\n\t\t\t\t\t\tdyS = dy;\n\t\t\t\t\t}\n\t\t\t\t\tb(cit++) = dyR;\n\t\t\t\t\tb(cit++) = dyS;\n\t\t\t\t\t// dyR(r, c) = -lR(r, c) + lR(r + 1)\n\t\t\t\t\t// dyS(r, c) = -lS(r, c) + lS(r + 1)\n\t\t\t\t}\n\t\t\t\t// reflectance plus shading (log space) == final image\n\t\t\t\tb(cit++) = I(x, y);\n\t\t\t}\n\t\t}\n\t\treturn b;\n\t}\n\n\t// operates on log-reflectance\n\t// makes sure that log-reflectane is less than 0\n\tvoid reflect_clamp(int w, int h, float* refl_in, float* shading_in) {\n\n\t\tfloat max_reflectance = -FLT_MIN;\n\t\tfloat min_reflectance = FLT_MAX;\n\t\tint nancount = 0;\n\t\tint infcount = 0;\n\t\tfor (int i = 0; i < w * h; ++i) {\n\t\t\tif (refl_in[i] > max_reflectance) {\n\t\t\t\tmax_reflectance = refl_in[i];\n\t\t\t}\n\t\t\tif (refl_in[i] < min_reflectance) {\n\t\t\t\tmin_reflectance = refl_in[i];\n\t\t\t}\n\t\t}\n\n\t\tif (max_reflectance > 0) {\n\t\t\tfor (int i = 0; i < w * h; ++i) {\n\t\t\t\trefl_in[i] -= max_reflectance;\n\t\t\t}\n\t\t\tfor (int i = 0; i < w * h; ++i) {\n\t\t\t\tshading_in[i] += max_reflectance;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid retinex(float threshold, const float* im, int w, int h, float* reflectance, float* shading) {\n\t\tassert(reflectance);\n\t\tassert(shading);\n\t\tassert(im);\n\t\tretinex_decomp rdec(w, h);\n\t\trdec.solve(threshold, im, reflectance, shading);\n\t}\n\t/* I would prefer solving direction Ax = b.\n\t  However, this doesn't work with Eigen's QR decomp (why?).\n\t  I solve A'Ax = A'b, using Cholesky, instead.\n\t*/\n\tretinex_decomp::retinex_decomp(int w, int h): m_w(w), m_h(h) {\n\t\tstd::vector <Triplet> entries = makeTriplets(w, h);\n\t\tSpMat A(nconstraints(w, h), w * h * 2);\n\t\tA.setFromTriplets(entries.begin(), entries.end());\n\t\tm_At = A.transpose();\n\t\t{\n\t\t\tprintf(\"factorize %d-by-%d matrix\\n\", A.cols(), A.cols());\n\t\t\tdouble decompose_start = get_s();\n\t\t\tm_solver.compute(m_At * A);\n\t\t\tdouble decompose_end = get_s();\n\t\t\tprintf(\"factorize took %.1fms\\n\", (decompose_end - decompose_start) * 1000);\n\t\t}\n\t}\n\tvoid retinex_decomp::solve(float threshold, const float* im, float* reflectance, float* shading) {\n\t\tassert(reflectance);\n\t\tassert(shading);\n\t\tassert(im);\n\n\t\tstd::vector<float> logimg(m_w*m_h);\n\t\tpreprocess(m_w, m_h, im, logimg.data());\n\t\tEigen::VectorXf b = makeB(threshold, logimg.data(), m_w, m_h);\n\t\tdouble solve_start = get_s();\n\t\tEigen::VectorXf x = m_solver.solve(m_At * b);\n\t\tdouble solve_end = get_s();\n\t\tprintf(\"solve took %.1fms\\n\", (solve_end - solve_start) * 1000);\n\t\tpostprocess(m_w, m_h, x.data(), x.data() + m_w * m_h, reflectance, shading);\n\t}\n\n\t// does greyscale retinex with post processing.\n\tvoid retinex_decomp::solve_rgb(float threshold, const float* im, float* reflectance, float* shading) {\n\t\tassert(reflectance);\n\t\tassert(shading);\n\t\tassert(im);\n\t\tconst int sz = m_w * m_h;\n\n\t\tstd::vector<float> grayimg(sz);\n\t\tmean(im, grayimg.data(), grayimg.size());\n\t\tstd::vector<float> graylog(sz);\n\t\tdouble before = get_s();\n\t\tlog(grayimg.data(), graylog.data(), sz);\n\t\tdouble after = get_s();\n\n\t\tEigen::VectorXf b = makeB(threshold, graylog.data(), m_w, m_h);\n\t\tdouble solve_start = get_s();\n\t\tEigen::VectorXf x = m_solver.solve(m_At * b);\n\t\tdouble solve_end = get_s();\n\n\t\tfloat* log_shading = x.data() + sz;\n\t\treflect_clamp(m_w, m_h, x.data(), log_shading);\n\n\t\tstd::vector<float> rgb_logimg(3*sz);\n\t\tlog(im, rgb_logimg.data(), rgb_logimg.size());\n\n\t\t// do gray to rgb conversion\n\t\t// log R = log I - log S\n\t\tfor (int i = 0; i < sz; ++i) {\n\t\t\trgb_logimg[i * 3 + 0] = rgb_logimg[i * 3 + 0] - log_shading[i];\n\t\t\trgb_logimg[i * 3 + 1] = rgb_logimg[i * 3 + 1] - log_shading[i];\n\t\t\trgb_logimg[i * 3 + 2] = rgb_logimg[i * 3 + 2] - log_shading[i];\n\t\t}\n\n\t\texp(rgb_logimg.data(), reflectance, 3 * sz);\n\t\texp(log_shading, shading, sz);\n\t}\n}", "meta": {"hexsha": "3743782336a4e4329ba40b888c2ab831e61f7f86", "size": 8611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lum_retinex.cpp", "max_stars_repo_name": "lmurmann/retinex", "max_stars_repo_head_hexsha": "b66f32e64d3752de97b222b928b3d869f16457e4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-11-11T13:23:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-30T01:48:55.000Z", "max_issues_repo_path": "lum_retinex.cpp", "max_issues_repo_name": "lmurmann/retinex", "max_issues_repo_head_hexsha": "b66f32e64d3752de97b222b928b3d869f16457e4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-07T14:03:56.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-30T09:34:46.000Z", "max_forks_repo_path": "lum_retinex.cpp", "max_forks_repo_name": "lmurmann/retinex", "max_forks_repo_head_hexsha": "b66f32e64d3752de97b222b928b3d869f16457e4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-03-15T13:28:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T22:16:49.000Z", "avg_line_length": 28.4191419142, "max_line_length": 105, "alphanum_fraction": 0.5964464058, "num_tokens": 3080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789178257654, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4242211579738964}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Jose Aparicio\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/quantlib.hpp>\n\n#include <boost/timer.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/function.hpp>\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\nusing namespace QuantLib;\n\n#ifdef BOOST_MSVC\n#  ifdef QL_ENABLE_THREAD_SAFE_OBSERVER_PATTERN\n#    include <ql/auto_link.hpp>\n#    define BOOST_LIB_NAME boost_system\n#    include <boost/config/auto_link.hpp>\n#    undef BOOST_LIB_NAME\n#    define BOOST_LIB_NAME boost_thread\n#    include <boost/config/auto_link.hpp>\n#    undef BOOST_LIB_NAME\n#  endif\n#endif\n\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib {\n\n    Integer sessionId() { return 0; }\n\n}\n#endif\n\n\n/* This sample code shows basic usage of a Latent variable model.\n   The data and correlation problem presented is the same as in:\n     'Modelling Dependent Defaults: Asset Correlations Are Not Enough!'\n     Frey R., A. J. McNeil and M. A. Nyfeler RiskLab publications March 2001\n*/\nint main(int, char* []) {\n\n    try {\n\n        boost::timer timer;\n        std::cout << std::endl;\n\n        Calendar calendar = TARGET();\n        Date todaysDate(19, March, 2014);\n        // must be a business day\n        todaysDate = calendar.adjust(todaysDate);\n\n        Settings::instance().evaluationDate() = todaysDate;\n\n\n        /* --------------------------------------------------------------\n                        SET UP BASKET PORTFOLIO\n        -------------------------------------------------------------- */\n        // build curves and issuers into a basket of three names\n        std::vector<Real> hazardRates(3, -std::log(1.-0.01));\n        std::vector<std::string> names;\n        for(Size i=0; i<hazardRates.size(); i++)\n            names.push_back(std::string(\"Acme\") + \n                boost::lexical_cast<std::string>(i));\n        std::vector<Handle<DefaultProbabilityTermStructure> > defTS;\n        for(Size i=0; i<hazardRates.size(); i++)\n            defTS.push_back(Handle<DefaultProbabilityTermStructure>(\n                boost::make_shared<FlatHazardRate>(0, TARGET(), hazardRates[i], \n                    Actual365Fixed())));\n        std::vector<Issuer> issuers;\n        for(Size i=0; i<hazardRates.size(); i++) {\n            std::vector<QuantLib::Issuer::key_curve_pair> curves(1, \n                std::make_pair(NorthAmericaCorpDefaultKey(\n                    EURCurrency(), QuantLib::SeniorSec,\n                    Period(), 1. // amount threshold\n                    ), defTS[i]));\n            issuers.push_back(Issuer(curves));\n        }\n\n        boost::shared_ptr<Pool> thePool = boost::make_shared<Pool>();\n        for(Size i=0; i<hazardRates.size(); i++)\n            thePool->add(names[i], issuers[i], NorthAmericaCorpDefaultKey(\n                    EURCurrency(), QuantLib::SeniorSec, Period(), 1.));\n\n        std::vector<DefaultProbKey> defaultKeys(hazardRates.size(), \n            NorthAmericaCorpDefaultKey(EURCurrency(), SeniorSec, Period(), 1.));\n        // Recoveries are irrelevant in this example but must be given as the \n        //   lib stands.\n        std::vector<boost::shared_ptr<RecoveryRateModel> > rrModels(\n            hazardRates.size(), boost::make_shared<ConstantRecoveryModel>(\n            ConstantRecoveryModel(0.5, SeniorSec)));\n        boost::shared_ptr<Basket> theBskt = boost::make_shared<Basket>(\n            todaysDate, names, std::vector<Real>(hazardRates.size(), 100.), \n            thePool);\n        /* --------------------------------------------------------------\n                        SET UP JOINT DEFAULT EVENT LATENT MODELS\n        -------------------------------------------------------------- */\n        // Latent model factors, corresponds to the first entry in Table1 of the\n        //   publication mentioned. It is a single factor model\n        std::vector<std::vector<Real> > fctrsWeights(hazardRates.size(), \n            std::vector<Real>(1, std::sqrt(0.1)));\n        // --- Default Latent models -------------------------------------\n        // Gaussian integrable joint default model:\n        boost::shared_ptr<GaussianDefProbLM> lmG(new \n            GaussianDefProbLM(fctrsWeights, \n            LatentModelIntegrationType::GaussianQuadrature,\n\t\t\tGaussianCopulaPolicy::initTraits() // otherwise gcc screams\n\t\t\t));\n        // Define StudentT copula\n        // this is as far as we can be from the Gaussian, 2 T_3 factors:\n        std::vector<Integer> ordersT(2, 3);\n        TCopulaPolicy::initTraits iniT;\n        iniT.tOrders = ordersT;\n        // StudentT integrable joint default model:\n        boost::shared_ptr<TDefProbLM> lmT(new TDefProbLM(fctrsWeights, \n            // LatentModelIntegrationType::GaussianQuadrature,\n            LatentModelIntegrationType::Trapezoid,\n            iniT));\n\n        // --- Default Loss models ----------------------------------------\n        // Gaussian random joint default model:\n        Size numSimulations = 100000;\n        // Size numCoresUsed = 4;\n        // Sobol, many cores\n        boost::shared_ptr<DefaultLossModel> rdlmG(\n            boost::make_shared<RandomDefaultLM<GaussianCopulaPolicy> >(lmG, \n                std::vector<Real>(), numSimulations, 1.e-6, 2863311530));\n        // StudentT random joint default model:\n        boost::shared_ptr<DefaultLossModel> rdlmT(\n            boost::make_shared<RandomDefaultLM<TCopulaPolicy> >(lmT, \n            std::vector<Real>(), numSimulations, 1.e-6, 2863311530));\n\n        /* --------------------------------------------------------------\n                        DUMP SOME RESULTS\n        -------------------------------------------------------------- */\n        /* Default correlations in a T copula should be below those of the \n        gaussian for the same factors.\n        The calculations on the MC show dispersion on both copulas (thats\n        ok) and too large values with very large dispersions on the T case.\n        Computations are ok, within the dispersion, for the gaussian; compare\n        with the direct integration in both cases.\n        However the T does converge to the gaussian value for large value of\n        the parameters.\n        */\n        Date calcDate(TARGET().advance(Settings::instance().evaluationDate(), \n            Period(120, Months)));\n        std::vector<Probability> probEventsTLatent, probEventsGLatent, \n            probEventsTRandLoss, probEventsGRandLoss;\n        //\n        lmT->resetBasket(theBskt);\n        for(Size numEvts=0; numEvts <=theBskt->size(); numEvts++) {\n            probEventsTLatent.push_back(lmT->probAtLeastNEvents(numEvts, \n                calcDate));\n         }\n        //\n        lmG->resetBasket(theBskt);\n        for(Size numEvts=0; numEvts <=theBskt->size(); numEvts++) {\n            probEventsGLatent.push_back(lmG->probAtLeastNEvents(numEvts, \n                calcDate));\n         }\n        //\n        theBskt->setLossModel(rdlmT);\n        for(Size numEvts=0; numEvts <=theBskt->size(); numEvts++) {\n            probEventsTRandLoss.push_back(theBskt->probAtLeastNEvents(numEvts, \n                calcDate));\n         }\n        //\n        theBskt->setLossModel(rdlmG);\n        for(Size numEvts=0; numEvts <=theBskt->size(); numEvts++) {\n            probEventsGRandLoss.push_back(theBskt->probAtLeastNEvents(numEvts, \n                calcDate));\n         }\n\n        Date correlDate = TARGET().advance(\n            Settings::instance().evaluationDate(), Period(12, Months));\n        std::vector<std::vector<Real> > correlsGlm, correlsTlm, correlsGrand, \n            correlsTrand;\n        //\n        lmG->resetBasket(theBskt);\n        for(Size iName1=0; iName1 <theBskt->size(); iName1++) {\n            std::vector<Real> tmp;\n            for(Size iName2=0; iName2 <theBskt->size(); iName2++)\n                tmp.push_back(lmG->defaultCorrelation(correlDate, \n                    iName1, iName2));\n            correlsGlm.push_back(tmp);\n        }\n        //\n        lmT->resetBasket(theBskt);\n        for(Size iName1=0; iName1 <theBskt->size(); iName1++) {\n            std::vector<Real> tmp;\n            for(Size iName2=0; iName2 <theBskt->size(); iName2++)\n                tmp.push_back(lmT->defaultCorrelation(correlDate, \n                    iName1, iName2));\n            correlsTlm.push_back(tmp);\n        }\n        //\n        theBskt->setLossModel(rdlmG);\n        for(Size iName1=0; iName1 <theBskt->size(); iName1++) {\n            std::vector<Real> tmp;\n            for(Size iName2=0; iName2 <theBskt->size(); iName2++)\n                tmp.push_back(theBskt->defaultCorrelation(correlDate, \n                    iName1, iName2));\n            correlsGrand.push_back(tmp);\n        }\n        //\n        theBskt->setLossModel(rdlmT);\n        for(Size iName1=0; iName1 <theBskt->size(); iName1++) {\n            std::vector<Real> tmp;\n            for(Size iName2=0; iName2 <theBskt->size(); iName2++)\n                tmp.push_back(theBskt->defaultCorrelation(correlDate, \n                    iName1, iName2));\n            correlsTrand.push_back(tmp);\n        }\n\n\n\n        std::cout << \n            \" Gaussian versus T prob of extreme event (random and integrable)-\" \n            << std::endl;\n        for(Size numEvts=0; numEvts <=theBskt->size(); numEvts++) {\n            std::cout << \"-Prob of \" << numEvts << \" events... \" <<\n                probEventsGLatent[numEvts] << \" ** \" << \n                probEventsTLatent[numEvts] << \" ** \" << \n                probEventsGRandLoss[numEvts]<< \" ** \" << \n                probEventsTRandLoss[numEvts] \n            << std::endl;\n        }\n\n        cout << endl;\n        cout << \"-- Default correlations G,T,GRand,TRand--\" << endl;\n        cout << \"-----------------------------------------\" << endl;\n        for(Size iName1=0; iName1 <theBskt->size(); iName1++) {\n            for(Size iName2=0; iName2 <theBskt->size(); iName2++)\n                cout << \n                    correlsGlm[iName1][iName2] << \" , \";\n            ;\n                cout << endl;\n        }\n        cout << endl;\n        for(Size iName1=0; iName1 <theBskt->size(); iName1++) {\n            for(Size iName2=0; iName2 <theBskt->size(); iName2++)\n                cout << \n                    correlsTlm[iName1][iName2] << \" , \";\n            ;\n                cout << endl;\n        }\n        cout << endl;\n        for(Size iName1=0; iName1 <theBskt->size(); iName1++) {\n            for(Size iName2=0; iName2 <theBskt->size(); iName2++)\n                cout << \n                    correlsGrand[iName1][iName2] << \" , \";\n            ;\n                cout << endl;\n        }\n        cout << endl;\n        for(Size iName1=0; iName1 <theBskt->size(); iName1++) {\n            for(Size iName2=0; iName2 <theBskt->size(); iName2++)\n                cout << \n                    correlsTrand[iName1][iName2] << \" , \";\n            ;\n                cout << endl;\n        }\n\n\n\n        Real seconds  = timer.elapsed();\n        Integer hours = Integer(seconds/3600);\n        seconds -= hours * 3600;\n        Integer minutes = Integer(seconds/60);\n        seconds -= minutes * 60;\n        cout << \"Run completed in \";\n        if (hours > 0)\n            cout << hours << \" h \";\n        if (hours > 0 || minutes > 0)\n            cout << minutes << \" m \";\n        cout << fixed << setprecision(0)\n             << seconds << \" s\" << endl;\n\n        return 0;\n    } catch (exception& e) {\n        cerr << e.what() << endl;\n        return 1;\n    } catch (...) {\n        cerr << \"unknown error\" << endl;\n        return 1;\n    }\n}\n\n", "meta": {"hexsha": "66f994dc952829c52f515068bb72ddd5ecb457e8", "size": 12198, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/LatentModel/LatentModel.cpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "Examples/LatentModel/LatentModel.cpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "Examples/LatentModel/LatentModel.cpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 39.7328990228, "max_line_length": 80, "alphanum_fraction": 0.552139695, "num_tokens": 3018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.42412244219386286}}
{"text": "//==================================================================================================\n/*\n  Copyright 2017 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n//! [inverse_hyperbolic]\n#include <boost/simd/hyperbolic.hpp>\n#include <boost/simd/pack.hpp>\n#include <boost/simd/function/enumerate.hpp>\n#include <iostream>\n\nnamespace bs =  boost::simd;\nusing pack_ft =  bs::pack <float, 8>;\n\nint main()\n{\n  pack_ft p = bs::enumerate<pack_ft>(-2.0f, 0.5f);\n  std::cout << \" p =  \" << p << std::endl\n            <<  \" -> bs::acosh(p) =  \" << bs::acosh(p) << std::endl\n            <<  \" -> bs::asinh(p) =  \" << bs::asinh(p) << std::endl\n            <<  \" -> bs::atanh(p) =  \" << bs::atanh(p) << std::endl\n            <<  \" -> bs::asech(p) =  \" << bs::asech(p) << std::endl\n            <<  \" -> bs::acsch(p) =  \" << bs::acsch(p) << std::endl;\n  return 0;\n}\n//! [inverse_hyperbolic]\n", "meta": {"hexsha": "734b9c034c532826ffa8ff708ee27276b6b202ec", "size": 1094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/doc/hyperbolic/inverse_hyperbolic.cpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "test/doc/hyperbolic/inverse_hyperbolic.cpp", "max_issues_repo_name": "remymuller/boost.simd", "max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/doc/hyperbolic/inverse_hyperbolic.cpp", "max_forks_repo_name": "remymuller/boost.simd", "max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 36.4666666667, "max_line_length": 100, "alphanum_fraction": 0.4515539305, "num_tokens": 304, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.42412244219386286}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <boost/program_options.hpp>\n\n#include <omp.h>\n\n#include \"dpSubclustersSphereMM.hpp\"\n\nusing namespace Eigen;\nusing std:string;\nusing std::ofstream; \nusing std::ifstream; \nnamespace po = boost::program_options;\n\n{\n\n  // Declare the supported options.\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help,h\", \"produce help message\")\n    (\"N,N\", po::value<int>(), \"number of input datapoints\")\n    (\"D,D\", po::value<int>(), \"number of dimensions of the data\")\n    (\"T,T\", po::value<int>(), \"iterations\")\n    (\"alpha,a\", po::value<double>(), \"alpha parameter of the DP\")\n    (\"base,b\", po::value<string>(), \n      \"which base measure to use (only NIW right now)\")\n    (\"params,p\", po::value< vector<double> >()->multitoken(), \n      \"parameters of the base measure\")\n    (\"input,i\", po::value<string>(), \n      \"path to input dataset .csv file (rows: dimensions; cols: different datapoints)\")\n    (\"output,o\", po::value<string>(), \n      \"path to output labels .csv file (rows: time; cols: different datapoints)\")\n    ;\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);    \n\n  if (vm.count(\"help\")) {\n    cout << desc << \"\\n\";\n    return 1;\n  }\n  \n#ifndef NDEBUG\n  uint32_t nThreads = 1;\n#else\n  uint32_t nThreads = omp_get_max_threads(); // has to match number of threads on computer\n#endif\n  // number of iterations\n  uint32_t T=1000;\n  if (vm.count(\"T\")) T = vm[\"T\"].as<int>();\n  uint32_t N=100;\n  if (vm.count(\"N\")) N = vm[\"N\"].as<int>();\n  uint32_t D=2;\n  if (vm.count(\"D\")) D = vm[\"D\"].as<int>();\n  cout << \"T=\"<<T<<endl;\n  // DP alpha parameter\n  double alpha = 0.1;\n  if (vm.count(\"alpha\")) alpha = vm[\"alpha\"].as<double>();\n  cout << \"alpha=\"<<alpha<<endl;\n  // which base distribution\n  string base = \"NIW\";\n  if(vm.count(\"base\")) base = vm[\"base\"].as<string>();\n  \n//  DpMM *dpmm;\n//  if(!base.compare(\"NIW\"))\n//  {\n    MatrixXd Delta(D-1,D-1);\n    VectorXd theta(D);\n    double nu = D+3.0;\n    double kappa = D+3.0;\n//    Delta << nu,0.0,0.0,nu;\n//    theta << 0.0,0.0;\n    if(vm.count(\"params\"))\n    {\n      vector<double> params = vm[\"params\"].as< vector<double> >();\n      cout<<\"params length=\"<<params.size()<<\" D=\"<<D<<endl;\n      nu = params[0];\n      kappa = params[1];\n      for(uint32_t i=0; i<D; ++i)\n        theta(i) = params[2+i];\n      for(uint32_t i=0; i<D-1; ++i)\n        for(uint32_t j=0; j<D-1; ++j)\n          Delta(i,j) = params[2+D-1+i+(D-1)*j];\n      cout <<\"nu=\"<<nu<<endl;\n      cout <<\"kappa=\"<<kappa<<endl;\n      cout <<\"theta=\"<<theta<<endl;\n      cout <<\"Delta=\"<<Delta<<endl;\n    }\n    niwSphere_sampled niw(D-1,kappa,nu, theta.data(),Delta.data());\n//    \n//  }else{\n//    cout<<\"base \"<<base<<\" not supported\"<<endl;\n//    return 1;\n//  }\n  \n  MatrixXd x(D,N);\n  string pathIn =\"\";\n  if(vm.count(\"input\")) pathIn = vm[\"input\"].as<string>();\n  if (!pathIn.compare(\"\"))\n  {\n    for(uint32_t i=0; i<N; ++i)\n      if(i<N/2)\n      {\n        x.col(i) << VectorXd::Zero(D);\n      }else{\n        x.col(i) << 2.0*VectorXd::Ones(D);\n      }\n  }else{\n    cout<<\"loading data from \"<<pathIn<<endl;\n    ifstream fin(pathIn.data(),ifstream::in);\n    for (uint32_t j=0; j<D; ++j)\n      for (uint32_t i=0; i<N; ++i)\n      {\n        fin>>x(j,i);\n      }\n    //cout<<x<<endl;\n  }\n  string pathOut =\"./labels.csv\";\n  if(vm.count(\"output\")) \n    pathOut = vm[\"output\"].as<string>();\n  cout<<\"output to \"<<pathOut<<endl;\n\n  VectorXd z(N);\n  z.setZero();\n  cout<<\"z.shape=\"<<z.size()<<endl;\n  DpSubclustersSphereMM *dpmm = new DpSubclustersSphereMM(N,D,x.data(), \n      z.data(), alpha, niw, nThreads,true,true);\n  cout<<\"-- init\"<<endl;\n  dpmm->initialize();\n\n  ofstream fout(pathOut.data(),ofstream::out);\n  for (uint32_t t=0; t<T; ++t)\n  {\n    cout<<\"------------ t=\"<<t<<\" -------------\"<<endl;\n    cout<<\"-- sampling params\"<<endl;\n    dpmm->sample_params();\n    cout<<\"-- sampling superclusters\"<<endl;\n    dpmm->sample_superclusters();\n    cout<<\"-- sampling labels\"<<endl;\n    dpmm->sample_labels();\n\n    if(t%50 == 0)\n    {\n      cout<<\"-- random splits\"<<endl;\n      dpmm->propose_random_splits();\n    }\n    cout<<\"-- random merges\"<<endl;\n    dpmm->propose_random_merges();\n    cout<<\"-- splits\"<<endl;\n    dpmm->propose_splits();\n\n    cout<<\"   logLike=\\t\"<<dpmm->joint_loglikelihood()<<endl;\n    cout<<\"   K=\\t\"<<dpmm->getK()<<endl;\n    cout<<\"   Nk=\\t\"<<dpmm->getNK()<<endl;\n\n\n//    const VectorXi& z = dpmm->getLabels().transpose();\n//    //cout<< \"z_\"<<t<<\"= \"<<z.transpose()<<endl;\n    for (uint32_t i=0; i<z.size()-1; ++i) \n      fout<<int(floor(z(i)))<<\" \";\n    fout<<int(floor(z(z.size()-1)))<<endl;\n  }\n  fout.close();\n}\n", "meta": {"hexsha": "b1ae463cb11d7895bf40fd82d36295bb7b47a786", "size": 4836, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/deprecated/dpSubclusterSphereGMM.cpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "src/deprecated/dpSubclusterSphereGMM.cpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/deprecated/dpSubclusterSphereGMM.cpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 28.2807017544, "max_line_length": 90, "alphanum_fraction": 0.5647229115, "num_tokens": 1472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.585101154203231, "lm_q1q2_score": 0.42412243523867504}}
{"text": "#ifndef VEC2D_HPP_INCLUDED\n#define VEC2D_HPP_INCLUDED\n\n/*! \\file vector.hpp\n    \\ingroup common\n    \\brief vector data types\n    \\details this file imports the vector data types from boost.ublas for use under less verbose\n            type names.\n*/\n\n#include <cassert>\n#include <numeric>\n#include <boost/numeric/ublas/vector.hpp>\n\n//! \\addtogroup common\n//! \\{\n\n//! vector of doubles with constant maximum length \\p N\ntemplate<int N>\nusing c_vector = boost::numeric::ublas::c_vector<double, N>;\n\n/*! normal generic vector type with at most three entries.\n    uses c_vector, i.e. preallocated space so it does not\n    require any dynamic memory management to create these\n    objects.\n*/\nusing gen_vect = c_vector<3>;\n\n/// integer vector of at most three dimension.\nusing int_vect = boost::numeric::ublas::c_vector<int, 3>;\n\n/// cross product function, very ugly, not generic or easy to use.\n/// \\todo should be removed or significantly improved.\ntemplate<class Result, class Vector>\nvoid crossProduct( Result& target, const Vector& v1, const Vector& v2)\n{\n    assert( target.size() == 3 );\n    assert( v1.size() == 3);\n    assert( v2.size() == 3 );\n    target[0] =  v1[1]*v2[2] - v1[2]*v2[1];\n    target[1] = -v1[0]*v2[2] + v1[2]*v2[0];\n    target[2] = v1[0]*v2[1] - v1[1]*v2[0];\n}\n\n\ntemplate<class Vec1, class Vec2>\ndouble dotProduct(Vec1&& v1, Vec2&& v2) {\n    using std::begin;\n    using std::end;\n    return std::inner_product(begin(v1), end(v1), begin(v2), 0.0);\n}\n\n//! \\}\n\n#endif // VEC2D_HPP_INCLUDED\n", "meta": {"hexsha": "f28e2ba14504d38c06bb772243f56f7636cbfa7e", "size": 1508, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/vector.hpp", "max_stars_repo_name": "ngc92/branchedflowsim", "max_stars_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/vector.hpp", "max_issues_repo_name": "ngc92/branchedflowsim", "max_issues_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/vector.hpp", "max_forks_repo_name": "ngc92/branchedflowsim", "max_forks_repo_head_hexsha": "d38c0e7f892d07d0abd9b63d30570c41b3b83b34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9285714286, "max_line_length": 96, "alphanum_fraction": 0.6717506631, "num_tokens": 439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.4240515319497883}}
{"text": "/**\n * $Id$\n *\n * Software License Agreement (GNU General Public License)\n *\n *  Copyright (C) 2015:\n *\n *    Johann Prankl, prankl@acin.tuwien.ac.at\n *    Aitor Aldoma, aldoma@acin.tuwien.ac.at\n *\n *      Automation and Control Institute\n *      Vienna University of Technology\n *      Gusshausstraße 25-29\n *      1170 Vienn, Austria\n *\n *  This program is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * @author Johann Prankl, Aitor Aldoma\n *\n */\n\n#ifndef KP_INV_POSE_HPP\n#define KP_INV_POSE_HPP\n\n#include <v4r/common/rotation.h>\n#include <Eigen/Dense>\n\nnamespace v4r {\n\ninline void invPose(const Eigen::Matrix4f &pose, Eigen::Matrix4f &inv_pose) {\n  inv_pose.setIdentity();\n  inv_pose.topLeftCorner<3, 3>() = pose.topLeftCorner<3, 3>().transpose();\n  inv_pose.block<3, 1>(0, 3) = -1 * (inv_pose.topLeftCorner<3, 3>() * pose.block<3, 1>(0, 3));\n}\n\ninline void invPose(const Eigen::Matrix4d &pose, Eigen::Matrix4d &inv_pose) {\n  inv_pose.setIdentity();\n  inv_pose.topLeftCorner<3, 3>() = pose.topLeftCorner<3, 3>().transpose();\n  inv_pose.block<3, 1>(0, 3) = -1 * (inv_pose.topLeftCorner<3, 3>() * pose.block<3, 1>(0, 3));\n}\n\n/**\n * invPose6\n */\ntemplate <typename T1, typename T2, typename T3, typename T4>\ninline void invPose6(const T1 r[3], const T2 t[3], T3 inv_r[3], T4 inv_t[3]) {\n  inv_r[0] = T1(-1) * r[0];\n  inv_r[1] = T1(-1) * r[1];\n  inv_r[2] = T1(-1) * r[2];\n\n  v4r::AngleAxisRotatePoint(inv_r, t, inv_t);\n\n  inv_t[0] = T4(-1) * inv_t[0];\n  inv_t[1] = T4(-1) * inv_t[1];\n  inv_t[2] = T4(-1) * inv_t[2];\n}\n\n}  // namespace v4r\n\n#endif\n", "meta": {"hexsha": "ae576daaa76ba8355b40afe4e02d5a88b390d5c9", "size": 2142, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/keypoints/include/v4r/keypoints/impl/invPose.hpp", "max_stars_repo_name": "v4r-tuwien/v4r", "max_stars_repo_head_hexsha": "ff3fbd6d2b298b83268ba4737868bab258262a40", "max_stars_repo_licenses": ["BSD-1-Clause", "BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-22T11:36:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-20T11:31:08.000Z", "max_issues_repo_path": "modules/keypoints/include/v4r/keypoints/impl/invPose.hpp", "max_issues_repo_name": "v4r-tuwien/v4r", "max_issues_repo_head_hexsha": "ff3fbd6d2b298b83268ba4737868bab258262a40", "max_issues_repo_licenses": ["BSD-1-Clause", "BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/keypoints/include/v4r/keypoints/impl/invPose.hpp", "max_forks_repo_name": "v4r-tuwien/v4r", "max_forks_repo_head_hexsha": "ff3fbd6d2b298b83268ba4737868bab258262a40", "max_forks_repo_licenses": ["BSD-1-Clause", "BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-10-19T10:39:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T13:39:03.000Z", "avg_line_length": 29.75, "max_line_length": 94, "alphanum_fraction": 0.6690009337, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.42405152740824475}}
{"text": "#include <iostream>\n#include <armadillo>\nusing namespace std;\nusing namespace arma;\n\nint main() {\n    vec a = {1, 2};\n    a.print();\n    // mat a = {{1}, {2}}; \n    rowvec b = {2, 3};\n    b.print();\n    mat res = a * b ;\n    \n    res.print();\n    (b * a).print();\n\n    std::vector<double> v = {1, 2, 3};\n    vec c = vec({1, 2, 3});\n    c.print();\n    cout << c(2) << endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "dfe003f1f6d016263104e0bc5d320ab62219058c", "size": 390, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/arma_test.cc", "max_stars_repo_name": "codestorm04/Machine_Learning_CPP", "max_stars_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-06-05T09:31:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-13T13:37:44.000Z", "max_issues_repo_path": "examples/arma_test.cc", "max_issues_repo_name": "codestorm04/Machine_Learning_CPP", "max_issues_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/arma_test.cc", "max_forks_repo_name": "codestorm04/Machine_Learning_CPP", "max_forks_repo_head_hexsha": "50bbe9c7b8c387cd9690b9c338639ae62fda1cf5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-11-15T04:43:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T15:59:30.000Z", "avg_line_length": 16.25, "max_line_length": 38, "alphanum_fraction": 0.4641025641, "num_tokens": 136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.6619228825191871, "lm_q1q2_score": 0.42405152259768153}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2015 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <iostream>\n\n//#define BOOST_DISABLE_ASSERTS\n\n#include <boost/timer/timer.hpp>\n\n#include \"dune/grid/config.h\"\n#include \"dune/grid/uggrid.hh\"\n\n#include \"fem/assemble.hh\"\n#include \"fem/lagrangespace.hh\"\n#include \"linalg/trivialpreconditioner.hh\"\n#include \"linalg/jacobiPreconditioner.hh\"\n#include \"linalg/uzawa.hh\"\n#include \"linalg/direct.hh\"\n#include \"linalg/cg.hh\"\n#include \"io/vtk.hh\"\n#include \"utilities/kaskopt.hh\" // property_tree\n#include \"utilities/gridGeneration.hh\"\n\nusing namespace Kaskade;\n#include \"stokes.hh\"\n\nint main(int argc, char *argv[])\n{\n  using namespace boost::fusion;\n\n\n  int verbosity = 1;  // print to console if arguments are changed\n  bool dump = false; // do not write properties into file\n  std::unique_ptr<boost::property_tree::ptree> pt = getKaskadeOptions(argc, argv, verbosity, dump);\n\n  std::cout << \"Start stokes tutorial programm.\" << std::endl;\n\n  boost::timer::cpu_timer totalTimer;\n\n  constexpr int dim = 2;\n  constexpr int uIdx = 0;\n  constexpr int pIdx = 1;\n\n  // command line parameters\n  int refinements = getParameter(pt, \"refinements\", 5);\n  int order = getParameter(pt, \"order\", 2); // order for velocity space, order for pressure space is (order-1)\n  std::string empty;\n\n  std::string s(\"names.type.\");\n  s += getParameter(pt, \"solver.type\", empty);\n  bool direct = getParameter(pt, s, 0);\n    \n  s = \"names.direct.\" + getParameter(pt, \"solver.direct\", empty);\n  DirectType directType = static_cast<DirectType>(getParameter(pt, s, 4));  // 4: DirectType::UMFPACK3264\n\n  std::cout << \"original mesh shall be refined : \" << refinements << \" times\" << std::endl;\n  std::cout << \"discretization order           : \" << order << std::endl;\n  std::cout << \"direct solver                  : \" << directType << std::endl;\n\n  boost::timer::cpu_timer gridTimer;\n  // grid generation\n  using Grid = Dune::UGGrid<dim>;\n  using H1Space = FEFunctionSpace<ContinuousLagrangeMapper<double,Grid::LeafGridView> >;\n  using Spaces = vector<H1Space const*,H1Space const*>;\n  using VariableDescriptions = vector<Variable<SpaceIndex<1>,Components<2>,VariableId<uIdx> >,\n                                      Variable<SpaceIndex<0>,Components<1>,VariableId<pIdx> > >;\n  using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;\n  using CoefficientVectors = VariableSet::CoefficientVectorRepresentation<>::type;\n  using Functional = StokesFunctional<double,VariableSet>;\n  using Assembler = VariationalFunctionalAssembler<LinearizationAt<Functional> >;\n\n  Dune::FieldVector<double,dim> x0(0.0), length(1.0);\n  GridManager<Grid> gridManager( createRectangle<Grid>(x0,length,1.0));\n  gridManager.globalRefine(refinements);\n  std::cout << \"computing time for generation of initial mesh: \" << boost::timer::format(gridTimer.elapsed());\n\n\n  // construct involved spaces.\n  H1Space pressureSpace(gridManager,gridManager.grid().leafGridView(),order-1);\n  H1Space velocitySpace(gridManager,gridManager.grid().leafGridView(),order);\n\n  Spaces spaces(&pressureSpace,&velocitySpace);\n\n  // construct variable list.\n  std::string varNames[2] = { \"u\", \"p\" };\n\n  VariableSet variableSet(spaces,varNames);\n\n  // construct variational functional.\n  Functional F;\n\n  // construct Galerkin representation\n  Assembler assembler(spaces);\n  VariableSet::VariableSet x(variableSet);\n  VariableSet::VariableSet dx(variableSet);\n\n  size_t nnz = assembler.nnz(0,2,0,2,false);\n  size_t dof = variableSet.degreesOfFreedom(0,2);\n  std::cout << \"overall degrees of freedom: \" << dof << std::endl;\n  std::cout << \"(structurally) nonzero elements: \" << nnz << std::endl;\n\n  boost::timer::cpu_timer assembleTimer;\n  assembler.assemble(linearization(F,x));\n  std::cout << \"computing time for assemble: \" << boost::timer::format(assembleTimer.elapsed());\n\n  if(direct)\n  {\n    CoefficientVectors solution(VariableSet::CoefficientVectorRepresentation<>::init(spaces));\n    CoefficientVectors rhs(assembler.rhs());\n\n    boost::timer::cpu_timer directTimer;\n    // solve performing one Newton step\n    directInverseOperator(AssembledGalerkinOperator<Assembler>(assembler),directType).applyscaleadd(-1.0,rhs,solution);\n    std::cout << \"computing time for directsolve: \" << boost::timer::format(directTimer.elapsed());\n    x.data = solution.data;\n  }\n  else // Uzawa Solver\n  {\n    using VectorOfU = VariableSet::CoefficientVectorRepresentation<uIdx,uIdx+1>::type;\n    using VectorOfP = VariableSet::CoefficientVectorRepresentation<pIdx,pIdx+1>::type;\n    using Assembler_UU = AssembledGalerkinOperator<Assembler,uIdx,uIdx+1,uIdx,uIdx+1>;\n    using Assembler_PU = AssembledGalerkinOperator<Assembler,pIdx,pIdx+1,uIdx,uIdx+1>;\n    using Assembler_UP = AssembledGalerkinOperator<Assembler,uIdx,uIdx+1,pIdx,pIdx+1>;\n    using PreconAdapt = MatrixRepresentedOperator<MatrixAsTriplet<double>, VectorOfP, VectorOfP>;\n    using UzSo = UzawaSolver<VectorOfU,VectorOfP>;\n\n    Assembler_UU A(assembler);\n    Assembler_PU B(assembler);\n    Assembler_UP Bt(assembler);\n\n    boost::timer::cpu_timer iterativeTimer;\n    Dune::InverseOperatorResult res;\n    const DefaultDualPairing<VectorOfU,VectorOfU> defaultScalarProduct{};\n    StrakosTichyPTerminationCriterion<double> termination(1e-14,300);\n    int lookAhead = getParameter(pt, \"solver.lookAhead\", 3);\n    termination.setLookAhead(lookAhead);\n\n    JacobiPreconditioner<Assembler_UU> jacobiPreconditioner(A);\n    // inexact inner solver for upper left block\n    //Dune::CGSolver<VectorOfU> cg(A,jacobiPreconditioner,1e-14,300,0);\n    CG<VectorOfU,VectorOfU> cg(A,jacobiPreconditioner,defaultScalarProduct,termination,verbosity);\n    TrivialPreconditioner<PreconAdapt> trivialPreconditioner;\n\n    VectorOfU f(assembler.rhs<uIdx,uIdx+1>());\n    VectorOfP g(assembler.rhs<pIdx,pIdx+1>());\n    VectorOfU u(VariableSet::CoefficientVectorRepresentation<uIdx,uIdx+1>::init(spaces));\n    VectorOfP p(VariableSet::CoefficientVectorRepresentation<pIdx,pIdx+1>::init(spaces));\n\n    UzSo uzawa(A,cg,B,Bt,trivialPreconditioner,1e-4,100,2);\n\n    UzSo::Domain solution(vector<VectorOfU,VectorOfP>(u,p));\n    UzSo::Range rhs(vector<VectorOfU,VectorOfP>(f,g));\n    rhs *= -1.0; // change sign as rhs is -'F while the assembler returns F'\n    uzawa.apply(solution,rhs,res);\n\n    std::cout << \"computing time for iterative solve: \" << boost::timer::format(iterativeTimer.elapsed());\n\n    at_c<uIdx>(x.data).coefficients() = at_c<0>(at_c<uIdx>(solution.data).data);\n    at_c<pIdx>(x.data).coefficients() = at_c<0>(at_c<pIdx>(solution.data).data);\n  }\n\n  boost::timer::cpu_timer outputTimer;\n  writeVTKFile(x,\"stokes\", IoOptions().setOrder(order));\n  std::cout << \"graphical output finished, data in VTK format is written into file stokes.vtu \\n\";\n  std::cout << \"computing time for output: \" << boost::timer::format(outputTimer.elapsed()) << \"\\n\";\n\n  std::cout << \"total computing time: \" << boost::timer::format(totalTimer.elapsed()) << \"\\n\";\n  std::cout << \"End stokes tutorial program\" << std::endl;\n}\n", "meta": {"hexsha": "b241ba7e1c72be3e87aa91f138fe88106ab8c42e", "size": 7812, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/stokes/stokes.cpp", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/tutorial/stokes/stokes.cpp", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/tutorial/stokes/stokes.cpp", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 43.6424581006, "max_line_length": 119, "alphanum_fraction": 0.6661546339, "num_tokens": 2056, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.6619228625116081, "lm_q1q2_score": 0.42405151886319636}}
{"text": "/*\n    MIT License\n\n    Copyright (c) 2021 Zhepei Wang (wangzhepei@live.com)\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n*/\n\n#ifndef FLATNESS_HPP\n#define FLATNESS_HPP\n\n#include <Eigen/Eigen>\n\n#include <cmath>\n\nnamespace flatness\n{\n    class FlatnessMap\n    {\n    public:\n        inline void reset(const double &vehicle_mass,\n                          const double &gravitational_acceleration,\n                          const double &horitonral_drag_coeff,\n                          const double &vertical_drag_coeff,\n                          const double &parasitic_drag_coeff,\n                          const double &speed_smooth_factor)\n        {\n            mass = vehicle_mass;\n            grav = gravitational_acceleration;\n            dh = horitonral_drag_coeff;\n            dv = vertical_drag_coeff;\n            cp = parasitic_drag_coeff;\n            veps = speed_smooth_factor;\n\n            return;\n        }\n        //通过速度加速度和机动度计算角速度和旋转\n        inline void forward(const Eigen::Vector3d &vel,\n                            const Eigen::Vector3d &acc,\n                            const Eigen::Vector3d &jer,\n                            const double &psi,\n                            const double &dpsi,\n                            double &thr,\n                            Eigen::Vector4d &quat,\n                            Eigen::Vector3d &omg)\n        {\n            double w0, w1, w2, dw0, dw1, dw2;\n\n            v0 = vel(0);\n            v1 = vel(1);\n            v2 = vel(2);\n            a0 = acc(0);\n            a1 = acc(1);\n            a2 = acc(2);\n            cp_term = sqrt(v0 * v0 + v1 * v1 + v2 * v2 + veps);\n            w_term = 1.0 + cp * cp_term;\n            w0 = w_term * v0;\n            w1 = w_term * v1;\n            w2 = w_term * v2;\n            dh_over_m = dh / mass;\n            zu0 = a0 + dh_over_m * w0;\n            zu1 = a1 + dh_over_m * w1;\n            zu2 = a2 + dh_over_m * w2 + grav;\n            zu_sqr0 = zu0 * zu0;\n            zu_sqr1 = zu1 * zu1;\n            zu_sqr2 = zu2 * zu2;\n            zu01 = zu0 * zu1;\n            zu12 = zu1 * zu2;\n            zu02 = zu0 * zu2;\n            zu_sqr_norm = zu_sqr0 + zu_sqr1 + zu_sqr2;\n            zu_norm = sqrt(zu_sqr_norm);\n            z0 = zu0 / zu_norm;\n            z1 = zu1 / zu_norm;\n            z2 = zu2 / zu_norm;\n            ng_den = zu_sqr_norm * zu_norm;\n            ng00 = (zu_sqr1 + zu_sqr2) / ng_den;\n            ng01 = -zu01 / ng_den;\n            ng02 = -zu02 / ng_den;\n            ng11 = (zu_sqr0 + zu_sqr2) / ng_den;\n            ng12 = -zu12 / ng_den;\n            ng22 = (zu_sqr0 + zu_sqr1) / ng_den;\n            v_dot_a = v0 * a0 + v1 * a1 + v2 * a2;\n            dw_term = cp * v_dot_a / cp_term;\n            dw0 = w_term * a0 + dw_term * v0;\n            dw1 = w_term * a1 + dw_term * v1;\n            dw2 = w_term * a2 + dw_term * v2;\n            dz_term0 = jer(0) + dh_over_m * dw0;\n            dz_term1 = jer(1) + dh_over_m * dw1;\n            dz_term2 = jer(2) + dh_over_m * dw2;\n            dz0 = ng00 * dz_term0 + ng01 * dz_term1 + ng02 * dz_term2;\n            dz1 = ng01 * dz_term0 + ng11 * dz_term1 + ng12 * dz_term2;\n            dz2 = ng02 * dz_term0 + ng12 * dz_term1 + ng22 * dz_term2;\n            f_term0 = mass * a0 + dv * w0;\n            f_term1 = mass * a1 + dv * w1;\n            f_term2 = mass * (a2 + grav) + dv * w2;\n            thr = z0 * f_term0 + z1 * f_term1 + z2 * f_term2;\n            tilt_den = sqrt(2.0 * (1.0 + z2));\n            tilt0 = 0.5 * tilt_den;\n            tilt1 = -z1 / tilt_den;\n            tilt2 = z0 / tilt_den;\n            c_half_psi = cos(0.5 * psi);\n            s_half_psi = sin(0.5 * psi);\n            quat(0) = tilt0 * c_half_psi;\n            quat(1) = tilt1 * c_half_psi + tilt2 * s_half_psi;\n            quat(2) = tilt2 * c_half_psi - tilt1 * s_half_psi;\n            quat(3) = tilt0 * s_half_psi;\n            c_psi = cos(psi);\n            s_psi = sin(psi);\n            omg_den = z2 + 1.0;\n            omg_term = dz2 / omg_den;\n            omg(0) = dz0 * s_psi - dz1 * c_psi -\n                     (z0 * s_psi - z1 * c_psi) * omg_term;\n            omg(1) = dz0 * c_psi + dz1 * s_psi -\n                     (z0 * c_psi + z1 * s_psi) * omg_term;\n            omg(2) = (z1 * dz0 - z0 * dz1) / omg_den + dpsi;\n\n            return;\n        }\n\n        inline void backward(const Eigen::Vector3d &pos_grad,\n                             const Eigen::Vector3d &vel_grad,\n                             const double &thr_grad,\n                             const Eigen::Vector4d &quat_grad,\n                             const Eigen::Vector3d &omg_grad,\n                             Eigen::Vector3d &pos_total_grad,\n                             Eigen::Vector3d &vel_total_grad,\n                             Eigen::Vector3d &acc_total_grad,\n                             Eigen::Vector3d &jer_total_grad,\n                             double &psi_total_grad,\n                             double &dpsi_total_grad) const\n        {\n            double w0b, w1b, w2b, dw0b, dw1b, dw2b;\n            double z0b, z1b, z2b, dz0b, dz1b, dz2b;\n            double v_sqr_normb, cp_termb, w_termb;\n            double zu_sqr_normb, zu_normb, zu0b, zu1b, zu2b;\n            double zu_sqr0b, zu_sqr1b, zu_sqr2b, zu01b, zu12b, zu02b;\n            double ng00b, ng01b, ng02b, ng11b, ng12b, ng22b, ng_denb;\n            double dz_term0b, dz_term1b, dz_term2b, f_term0b, f_term1b, f_term2b;\n            double tilt_denb, tilt0b, tilt1b, tilt2b, head0b, head3b;\n            double cpsib, spsib, omg_denb, omg_termb;\n            double tempb, tilt_den_sqr;\n\n            tilt0b = s_half_psi * (quat_grad(3)) + c_half_psi * (quat_grad(0));\n            head3b = tilt0 * (quat_grad(3)) + tilt2 * (quat_grad(1)) - tilt1 * (quat_grad(2));\n            tilt2b = c_half_psi * (quat_grad(2)) + s_half_psi * (quat_grad(1));\n            head0b = tilt2 * (quat_grad(2)) + tilt1 * (quat_grad(1)) + tilt0 * (quat_grad(0));\n            tilt1b = c_half_psi * (quat_grad(1)) - s_half_psi * (quat_grad(2));\n            tilt_den_sqr = tilt_den * tilt_den;\n            tilt_denb = (z1 * tilt1b - z0 * tilt2b) / tilt_den_sqr + 0.5 * tilt0b;\n            omg_termb = -((z0 * c_psi + z1 * s_psi) * (omg_grad(1))) -\n                        (z0 * s_psi - z1 * c_psi) * (omg_grad(0));\n            tempb = omg_grad(2) / omg_den;\n            dpsi_total_grad = omg_grad(2);\n            z1b = dz0 * tempb;\n            dz0b = z1 * tempb + c_psi * (omg_grad(1)) + s_psi * (omg_grad(0));\n            z0b = -(dz1 * tempb);\n            dz1b = s_psi * (omg_grad(1)) - z0 * tempb - c_psi * (omg_grad(0));\n            omg_denb = -((z1 * dz0 - z0 * dz1) * tempb / omg_den) -\n                       dz2 * omg_termb / (omg_den * omg_den);\n            tempb = -(omg_term * (omg_grad(1)));\n            cpsib = dz0 * (omg_grad(1)) + z0 * tempb;\n            spsib = dz1 * (omg_grad(1)) + z1 * tempb;\n            z0b += c_psi * tempb;\n            z1b += s_psi * tempb;\n            tempb = -(omg_term * (omg_grad(0)));\n            spsib += dz0 * (omg_grad(0)) + z0 * tempb;\n            cpsib += -dz1 * (omg_grad(0)) - z1 * tempb;\n            z0b += s_psi * tempb + tilt2b / tilt_den + f_term0 * (thr_grad);\n            z1b += -c_psi * tempb - tilt1b / tilt_den + f_term1 * (thr_grad);\n            dz2b = omg_termb / omg_den;\n            z2b = omg_denb + tilt_denb / tilt_den + f_term2 * (thr_grad);\n            psi_total_grad = c_psi * spsib + 0.5 * c_half_psi * head3b -\n                             s_psi * cpsib - 0.5 * s_half_psi * head0b;\n            f_term0b = z0 * (thr_grad);\n            f_term1b = z1 * (thr_grad);\n            f_term2b = z2 * (thr_grad);\n            ng02b = dz_term0 * dz2b + dz_term2 * dz0b;\n            dz_term0b = ng02 * dz2b + ng01 * dz1b + ng00 * dz0b;\n            ng12b = dz_term1 * dz2b + dz_term2 * dz1b;\n            dz_term1b = ng12 * dz2b + ng11 * dz1b + ng01 * dz0b;\n            ng22b = dz_term2 * dz2b;\n            dz_term2b = ng22 * dz2b + ng12 * dz1b + ng02 * dz0b;\n            ng01b = dz_term0 * dz1b + dz_term1 * dz0b;\n            ng11b = dz_term1 * dz1b;\n            ng00b = dz_term0 * dz0b;\n            jer_total_grad(2) = dz_term2b;\n            dw2b = dh_over_m * dz_term2b;\n            jer_total_grad(1) = dz_term1b;\n            dw1b = dh_over_m * dz_term1b;\n            jer_total_grad(0) = dz_term0b;\n            dw0b = dh_over_m * dz_term0b;\n            tempb = cp * (v2 * dw2b + v1 * dw1b + v0 * dw0b) / cp_term;\n            acc_total_grad(2) = mass * f_term2b + w_term * dw2b + v2 * tempb;\n            acc_total_grad(1) = mass * f_term1b + w_term * dw1b + v1 * tempb;\n            acc_total_grad(0) = mass * f_term0b + w_term * dw0b + v0 * tempb;\n            vel_total_grad(2) = dw_term * dw2b + a2 * tempb;\n            vel_total_grad(1) = dw_term * dw1b + a1 * tempb;\n            vel_total_grad(0) = dw_term * dw0b + a0 * tempb;\n            cp_termb = -(v_dot_a * tempb / cp_term);\n            tempb = ng22b / ng_den;\n            zu_sqr0b = tempb;\n            zu_sqr1b = tempb;\n            ng_denb = -((zu_sqr0 + zu_sqr1) * tempb / ng_den);\n            zu12b = -(ng12b / ng_den);\n            tempb = ng11b / ng_den;\n            ng_denb += zu12 * ng12b / (ng_den * ng_den) -\n                       (zu_sqr0 + zu_sqr2) * tempb / ng_den;\n            zu_sqr0b += tempb;\n            zu_sqr2b = tempb;\n            zu02b = -(ng02b / ng_den);\n            zu01b = -(ng01b / ng_den);\n            tempb = ng00b / ng_den;\n            ng_denb += zu02 * ng02b / (ng_den * ng_den) +\n                       zu01 * ng01b / (ng_den * ng_den) -\n                       (zu_sqr1 + zu_sqr2) * tempb / ng_den;\n            zu_normb = zu_sqr_norm * ng_denb -\n                       (zu2 * z2b + zu1 * z1b + zu0 * z0b) / zu_sqr_norm;\n            zu_sqr_normb = zu_norm * ng_denb + zu_normb / (2.0 * zu_norm);\n            tempb += zu_sqr_normb;\n            zu_sqr1b += tempb;\n            zu_sqr2b += tempb;\n            zu2b = z2b / zu_norm + zu0 * zu02b + zu1 * zu12b + 2 * zu2 * zu_sqr2b;\n            w2b = dv * f_term2b + dh_over_m * zu2b;\n            zu1b = z1b / zu_norm + zu2 * zu12b + zu0 * zu01b + 2 * zu1 * zu_sqr1b;\n            w1b = dv * f_term1b + dh_over_m * zu1b;\n            zu_sqr0b += zu_sqr_normb;\n            zu0b = z0b / zu_norm + zu2 * zu02b + zu1 * zu01b + 2 * zu0 * zu_sqr0b;\n            w0b = dv * f_term0b + dh_over_m * zu0b;\n            w_termb = a2 * dw2b + a1 * dw1b + a0 * dw0b +\n                      v2 * w2b + v1 * w1b + v0 * w0b;\n            acc_total_grad(2) += zu2b;\n            acc_total_grad(1) += zu1b;\n            acc_total_grad(0) += zu0b;\n            cp_termb += cp * w_termb;\n            v_sqr_normb = cp_termb / (2.0 * cp_term);\n            vel_total_grad(2) += w_term * w2b + 2 * v2 * v_sqr_normb + vel_grad(2);\n            vel_total_grad(1) += w_term * w1b + 2 * v1 * v_sqr_normb + vel_grad(1);\n            vel_total_grad(0) += w_term * w0b + 2 * v0 * v_sqr_normb + vel_grad(0);\n            pos_total_grad(2) = pos_grad(2);\n            pos_total_grad(1) = pos_grad(1);\n            pos_total_grad(0) = pos_grad(0);\n\n            return;\n        }\n\n    private:\n        double mass, grav, dh, dv, cp, veps;\n\n        double v0, v1, v2, a0, a1, a2, v_dot_a;\n        double z0, z1, z2, dz0, dz1, dz2;\n        double cp_term, w_term/*segma*||v||*/, dh_over_m;\n        double zu_sqr_norm, zu_norm, zu0, zu1, zu2;\n        double zu_sqr0, zu_sqr1, zu_sqr2, zu01, zu12, zu02;\n        double ng00, ng01, ng02, ng11, ng12, ng22, ng_den;\n        double dw_term, dz_term0, dz_term1, dz_term2, f_term0, f_term1, f_term2;\n        double tilt_den, tilt0, tilt1, tilt2, c_half_psi, s_half_psi;\n        double c_psi, s_psi, omg_den, omg_term;\n    };\n}\n\n#endif", "meta": {"hexsha": "c1326842362eea1a05958a02b25d827b3822eb34", "size": 12686, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gcopter/include/gcopter/flatness.hpp", "max_stars_repo_name": "valeriangcz/GCOPTER", "max_stars_repo_head_hexsha": "badce6a8ef9decc359fe826820baad1097d928a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T11:17:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T11:17:51.000Z", "max_issues_repo_path": "gcopter/include/gcopter/flatness.hpp", "max_issues_repo_name": "valeriangcz/GCOPTER", "max_issues_repo_head_hexsha": "badce6a8ef9decc359fe826820baad1097d928a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gcopter/include/gcopter/flatness.hpp", "max_forks_repo_name": "valeriangcz/GCOPTER", "max_forks_repo_head_hexsha": "badce6a8ef9decc359fe826820baad1097d928a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.797833935, "max_line_length": 94, "alphanum_fraction": 0.5098533817, "num_tokens": 4054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4240043031386318}}
{"text": "// -*- mode: c++; indent-tabs-mode: nil; -*-\n//\n// Paragraph\n// Copyright (c) 2016-2019 Illumina, Inc.\n// All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// You may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//\t\thttp://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied\n// See the License for the specific language governing permissions and limitations\n//\n//\n\n/**\n * Population statistics for genotype sets\n *\n * \\author Sai Chen & Egor Dolzhenko & Peter Krusche\n * \\email schen6@illumina.com & pkrusche@illumina.com & edolzhenko@illumina.com\n *\n */\n\n#include \"genotyping/PopulationStatistics.hh\"\n\n#include <algorithm>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <numeric>\n\nusing std::vector;\n\nnamespace genotyping\n{\nPopulationStatistics::PopulationStatistics(GenotypeSet const& genotypes)\n{\n    num_valid_samples = 0;\n    num_total_samples = static_cast<int>(genotypes.size());\n\n    for (auto const& genotype : genotypes)\n    {\n        if (genotype.gt.empty())\n        {\n            continue;\n        }\n        num_valid_samples++;\n        if (genotype_counts.find(genotype.gt) == genotype_counts.end())\n        {\n            genotype_counts[genotype.gt] = 1;\n        }\n        else\n        {\n            genotype_counts[genotype.gt]++;\n        }\n\n        for (auto const& gt : genotype.gt)\n        {\n            if (allele_counts.size() <= gt)\n            {\n                allele_counts.resize(gt + 1, 0);\n            }\n            allele_counts[gt]++;\n        }\n    }\n}\n\nJson::Value PopulationStatistics::toJson() const\n{\n    double hwe_p_chisq = getChisqPvalue();\n    double hwe_p_fisher = -1;\n    if (needFisherExactHWE())\n    {\n        hwe_p_fisher = getFisherExactPvalue();\n    }\n    double call_rate = getCallrate();\n\n    Json::Value json_result;\n    json_result[\"hwe\"] = hwe_p_chisq;\n    if (hwe_p_fisher == -1)\n    {\n        json_result[\"hwe_fisher\"] = \"\";\n    }\n    else\n    {\n        json_result[\"hwe_fisher\"] = hwe_p_fisher;\n    }\n    json_result[\"call_rate\"] = call_rate;\n\n    auto allele_frequencies = getAlleleFrequencies();\n    json_result[\"allele_frequencies\"] = Json::arrayValue;\n    for (auto& a : allele_frequencies)\n    {\n        json_result[\"allele_frequencies\"].append(a);\n    }\n\n    return json_result;\n}\n\ndouble PopulationStatistics::getChisqPvalue() const\n{\n    double chisq_val = 0;\n    for (auto& gv : genotype_counts)\n    {\n        if (gv.first.size() != 2)\n        {\n            continue;\n        }\n        uint64_t h1 = gv.first[0];\n        uint64_t h2 = gv.first[1];\n        if (allele_counts[h1] == 0 || allele_counts[h2] == 0) // skip unobserved alleles\n        {\n            continue;\n        }\n        double e_count;\n        if (h1 == h2)\n        {\n            e_count = ((double)allele_counts[h1] / num_valid_samples / 2)\n                * ((double)allele_counts[h1] / num_valid_samples / 2) * num_valid_samples;\n        }\n        else\n        {\n            e_count = 2 * ((double)allele_counts[h1] / num_valid_samples / 2)\n                * ((double)allele_counts[h2] / num_valid_samples / 2) * num_valid_samples;\n        }\n\n        double diff = e_count - gv.second;\n        double norm_diff_square = (double)(diff * diff) / e_count;\n        chisq_val += norm_diff_square;\n    }\n    boost::math::chi_squared chisq_distribution(1);\n    double hwe_pval = 1 - boost::math::cdf(chisq_distribution, chisq_val);\n    return hwe_pval;\n}\n\n/**\n * @return True if need to use Fisher's exact test for HWE P\n * For multi-alleles, always use chisq\n * For bi-allelic:\n *      if\n *          N<=30, or count of the rarest genotype <= 20, or rarest expected count <= 20, use fisher's exact\n *      else\n *          use chisq\n */\nbool PopulationStatistics::needFisherExactHWE() const\n{\n    int num_observed_alleles = 0;\n    for (auto a : allele_counts)\n    {\n        if (a > 0)\n        {\n            num_observed_alleles++;\n        }\n    }\n    if (num_observed_alleles <= 1)\n    {\n        return false;\n    }\n    if (num_observed_alleles > 2)\n    {\n        return false;\n    }\n\n    if (num_valid_samples <= 30)\n    {\n        return true;\n    }\n\n    for (auto& g : genotype_counts)\n    {\n        if (g.second > 0 && g.second <= 20)\n        {\n            return true;\n        }\n    }\n\n    auto minor_allele_index = minNonZeroAlleleIndex();\n    double minor_allele_freq = (double)allele_counts[minor_allele_index] / 2 / num_valid_samples;\n    if (minor_allele_freq * minor_allele_freq * num_valid_samples <= 20)\n    {\n        return true;\n    }\n    return false;\n}\n\n/**\n * from JE Wigginton 2005 AJHG\n */\ndouble PopulationStatistics::getFisherExactPvalue() const\n{\n    auto minor_allele_index = minNonZeroAlleleIndex();\n    auto p_major = std::max_element(allele_counts.begin(), allele_counts.end());\n    int minor_allele_count = allele_counts[minor_allele_index];\n    int major_allele_count = *p_major;\n\n    GenotypeVector het_gv;\n    het_gv.push_back(static_cast<uint64_t>(p_major - allele_counts.begin()));\n    het_gv.push_back(static_cast<uint64_t>(minor_allele_index));\n    std::sort(het_gv.begin(), het_gv.end());\n    int observed_num_het = 0;\n    for (auto& g : genotype_counts)\n    {\n        if (g.first.size() != 2)\n        {\n            continue;\n        }\n        if (g.first[0] == het_gv[0] && g.first[1] == het_gv[1])\n        {\n            observed_num_het = g.second;\n            break;\n        }\n    }\n\n    int num_expect_het = std::round(\n        2 * ((double)minor_allele_count / num_valid_samples / 2) * ((double)major_allele_count / num_valid_samples / 2)\n        * num_valid_samples);\n\n    std::vector<double> scaled_pvals;\n    double observe_scaled_pval = -1;\n\n    // for num_het > expected het\n    int prev_num_ref_hom = (minor_allele_count - num_expect_het) / 2;\n    int prev_num_alt_hom = num_valid_samples - prev_num_ref_hom - num_expect_het;\n    double prev_scaled_pval = 1;\n    for (int num_het = num_expect_het; num_het <= minor_allele_count; num_het += 2)\n    {\n        if (num_het == num_expect_het)\n        {\n            scaled_pvals.push_back(1);\n            continue;\n        }\n        int prev_num_het = num_het - 2;\n        double iscale\n            = prev_scaled_pval * (4 * prev_num_ref_hom * prev_num_alt_hom) / ((prev_num_het + 2) * (prev_num_het + 1));\n        scaled_pvals.push_back(iscale);\n        prev_scaled_pval = iscale;\n        prev_num_ref_hom--;\n        prev_num_alt_hom--;\n        if (observe_scaled_pval == -1 && num_het == observed_num_het)\n        {\n            observe_scaled_pval = iscale;\n        }\n    }\n\n    // for num_het < expected het\n    prev_num_ref_hom = (minor_allele_count - num_expect_het) / 2;\n    prev_num_alt_hom = num_valid_samples - prev_num_ref_hom - num_expect_het;\n    prev_scaled_pval = 1;\n    for (int num_het = num_expect_het; num_het >= 0; num_het -= 2)\n    {\n        if (num_het == num_expect_het)\n        {\n            continue;\n        }\n        int prev_num_het = num_het + 2;\n        double iscale = prev_scaled_pval / 4 * prev_num_het / (prev_num_ref_hom + 1) * (prev_num_het - 1)\n            / (prev_num_alt_hom + 1);\n        scaled_pvals.push_back(iscale);\n        prev_scaled_pval = iscale;\n        prev_num_ref_hom++;\n        prev_num_alt_hom++;\n        if (observe_scaled_pval == -1 && num_het == observed_num_het)\n        {\n            observe_scaled_pval = iscale;\n        }\n    }\n\n    // calculate HWE\n    double hwe_scale_sum = 0;\n    for (auto s : scaled_pvals)\n    {\n        if (s <= observe_scaled_pval)\n        {\n            hwe_scale_sum += s;\n        }\n    }\n    double pval = hwe_scale_sum / std::accumulate(scaled_pvals.begin(), scaled_pvals.end(), (double)0);\n    return pval;\n}\n\n/**\n * @return allele frequencies\n */\nstd::vector<double> PopulationStatistics::getAlleleFrequencies() const\n{\n    std::vector<double> result;\n    const uint32_t sum = std::accumulate(allele_counts.begin(), allele_counts.end(), (uint32_t)0);\n    result.reserve(allele_counts.size());\n    for (auto ac : allele_counts)\n    {\n        if (sum > 0)\n        {\n            result.push_back(((double)ac) / sum);\n        }\n        else\n        {\n            result.push_back(0);\n        }\n    }\n    return result;\n}\n\n/**\n * @return iterator to the lowest allele non-zero minor allele count\n */\nsize_t PopulationStatistics::minNonZeroAlleleIndex() const\n{\n    auto p_minor = std::min_element(allele_counts.begin(), allele_counts.end());\n    if (*p_minor > 0)\n    {\n        return static_cast<size_t>(p_minor - allele_counts.begin());\n    }\n    p_minor = std::max_element(allele_counts.begin(), allele_counts.end());\n    if (*p_minor == 0)\n    {\n        return static_cast<size_t>(0);\n    }\n    for (auto it = allele_counts.begin(); it != allele_counts.end(); it++)\n    {\n        if (*it < *p_minor)\n        {\n            p_minor = it;\n        }\n    }\n    return static_cast<size_t>(p_minor - allele_counts.begin());\n}\n}", "meta": {"hexsha": "eb6efba17a5df38049175843b2f03547b2ccb060", "size": 9138, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/c++/lib/genotyping/PopulationStatistics.cpp", "max_stars_repo_name": "vb-wayne/paragraph", "max_stars_repo_head_hexsha": "3f6f6f7a2a3ac209c7dbb21487ca4d9eaed5c14c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 111.0, "max_stars_repo_stars_event_min_datetime": "2017-11-24T18:22:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T07:55:31.000Z", "max_issues_repo_path": "src/c++/lib/genotyping/PopulationStatistics.cpp", "max_issues_repo_name": "vb-wayne/paragraph", "max_issues_repo_head_hexsha": "3f6f6f7a2a3ac209c7dbb21487ca4d9eaed5c14c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2018-01-01T19:58:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T12:01:17.000Z", "max_forks_repo_path": "src/c++/lib/genotyping/PopulationStatistics.cpp", "max_forks_repo_name": "vb-wayne/paragraph", "max_forks_repo_head_hexsha": "3f6f6f7a2a3ac209c7dbb21487ca4d9eaed5c14c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2018-03-01T04:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T14:52:03.000Z", "avg_line_length": 27.7750759878, "max_line_length": 119, "alphanum_fraction": 0.6038520464, "num_tokens": 2428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4240042929379318}}
{"text": "/* ============================================================================\n * Copyright (c) 2009-2016 BlueQuartz Software, LLC\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice, this\n * list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n *\n * Neither the name of BlueQuartz Software, the US Air Force, nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The code contained herein was partially funded by the followig contracts:\n *    United States Air Force Prime Contract FA8650-07-D-5800\n *    United States Air Force Prime Contract FA8650-10-D-5210\n *    United States Prime Contract Navy N00173-07-C-2068\n *\n * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n#include \"PrincipalComponentAnalysis.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Eigen>\n\n#include <QtCore/QTextStream>\n\n#include \"SIMPLib/Common/Constants.h\"\n#include \"SIMPLib/Common/TemplateHelpers.h\"\n#include \"SIMPLib/DataArrays/IDataArray.h\"\n#include \"SIMPLib/DataContainers/DataContainer.h\"\n#include \"SIMPLib/DataContainers/DataContainerArray.h\"\n#include \"SIMPLib/FilterParameters/AbstractFilterParametersReader.h\"\n#include \"SIMPLib/FilterParameters/BooleanFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/ChoiceFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/DataArrayCreationFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/IntFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/LinkedBooleanFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/LinkedPathCreationFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/MultiDataArraySelectionFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/SeparatorFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/StringFilterParameter.h\"\n\n#include \"DREAM3DReview/DREAM3DReviewConstants.h\"\n#include \"DREAM3DReview/DREAM3DReviewVersion.h\"\n\n/* Create Enumerations to allow the created Attribute Arrays to take part in renaming */\nenum createdPathID : RenameDataPath::DataID_t\n{\n  AttributeMatrixID21 = 21,\n\n  DataArrayID30 = 30,\n  DataArrayID31 = 31,\n  DataArrayID32 = 32,\n  DataArrayID33 = 33,\n};\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nPrincipalComponentAnalysis::PrincipalComponentAnalysis() = default;\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nPrincipalComponentAnalysis::~PrincipalComponentAnalysis() = default;\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::setupFilterParameters()\n{\n  FilterParameterVectorType parameters;\n  MultiDataArraySelectionFilterParameter::RequirementType mdaReq =\n      MultiDataArraySelectionFilterParameter::CreateRequirement(SIMPL::Defaults::AnyPrimitive, 1, AttributeMatrix::Type::Any, IGeometry::Type::Any);\n  parameters.push_back(\n      SIMPL_NEW_MDA_SELECTION_FP(\"Attribute Arrays for Computing Principal Components\", SelectedDataArrayPaths, FilterParameter::Category::RequiredArray, PrincipalComponentAnalysis, mdaReq));\n  {\n    ChoiceFilterParameter::Pointer choices = ChoiceFilterParameter::New();\n    choices->setHumanLabel(\"Matrix Approach\");\n    choices->setPropertyName(\"MatrixApproach\");\n    choices->setSetterCallback(SIMPL_BIND_SETTER(PrincipalComponentAnalysis, this, MatrixApproach));\n    choices->setGetterCallback(SIMPL_BIND_GETTER(PrincipalComponentAnalysis, this, MatrixApproach));\n    QVector<QString> approaches = {\"Correlation\", \"Covariance\"};\n    choices->setChoices(approaches);\n    choices->setCategory(FilterParameter::Category::Parameter);\n    parameters.push_back(choices);\n  }\n  QStringList linkedProps = {\"NumberOfDimensionsForProjection\", \"ProjectedDataSpaceArrayPath\"};\n  parameters.push_back(SIMPL_NEW_LINKED_BOOL_FP(\"Project Data Space\", ProjectDataSpace, FilterParameter::Category::Parameter, PrincipalComponentAnalysis, linkedProps));\n  parameters.push_back(SIMPL_NEW_INTEGER_FP(\"Number of Dimensions for Projection\", NumberOfDimensionsForProjection, FilterParameter::Category::Parameter, PrincipalComponentAnalysis));\n  DataArrayCreationFilterParameter::RequirementType dacReq = DataArrayCreationFilterParameter::CreateRequirement(AttributeMatrix::Type::Any, IGeometry::Type::Any);\n  parameters.push_back(SIMPL_NEW_DA_CREATION_FP(\"Projected Data Space\", ProjectedDataSpaceArrayPath, FilterParameter::Category::CreatedArray, PrincipalComponentAnalysis, dacReq));\n  parameters.push_back(SeparatorFilterParameter::Create(\"Principal Component Data\", FilterParameter::Category::CreatedArray));\n  parameters.push_back(SIMPL_NEW_STRING_FP(\"Principal Component Attribute Matrix\", PCAttributeMatrixName, FilterParameter::Category::CreatedArray, PrincipalComponentAnalysis));\n  parameters.push_back(SIMPL_NEW_STRING_FP(\"Principal Component Eigenvalues\", PCEigenvaluesName, FilterParameter::Category::CreatedArray, PrincipalComponentAnalysis));\n  parameters.push_back(SIMPL_NEW_STRING_FP(\"Principal Component Eigenvectors\", PCEigenvectorsName, FilterParameter::Category::CreatedArray, PrincipalComponentAnalysis));\n  setFilterParameters(parameters);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::readFilterParameters(AbstractFilterParametersReader* reader, int index)\n{\n  reader->openFilterGroup(this, index);\n  setSelectedDataArrayPaths(reader->readDataArrayPathVector(\"SelectedDataArrayPaths\", getSelectedDataArrayPaths()));\n  setPCAttributeMatrixName(reader->readString(\"PCAttributeMatrixName\", getPCAttributeMatrixName()));\n  setPCEigenvaluesName(reader->readString(\"PCEigenvaluesName\", getPCEigenvaluesName()));\n  setPCEigenvectorsName(reader->readString(\"PCEigenvectorsName\", getPCEigenvectorsName()));\n  setMatrixApproach(reader->readValue(\"MatrixApproach\", getMatrixApproach()));\n  setProjectDataSpace(reader->readValue(\"ProjectDataSpace\", getProjectDataSpace()));\n  setNumberOfDimensionsForProjection(reader->readValue(\"NumberOfDimensionsForProjection\", getNumberOfDimensionsForProjection()));\n  setProjectedDataSpaceArrayPath(reader->readDataArrayPath(\"ProjectedDataSpaceArrayPath\", getProjectedDataSpaceArrayPath()));\n  reader->closeFilterGroup();\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::initialize()\n{\n  m_SelectedWeakPtrVector.clear();\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::dataCheck()\n{\n  clearErrorCode();\n  clearWarningCode();\n  initialize();\n\n  if(getSelectedDataArrayPaths().size() < 2)\n  {\n    QString ss = QObject::tr(\"At least two Attribute Array must be selected\");\n    setErrorCondition(-11001, ss);\n    return;\n  }\n\n  QVector<DataArrayPath> paths = getSelectedDataArrayPaths();\n\n  if(!DataArrayPath::ValidateVector(paths))\n  {\n    QString ss = QObject::tr(\"There are Attribute Arrays selected that are not contained in the same Attribute Matrix; all selected Attribute Arrays must belong to the same Attribute Matrix\");\n    setErrorCondition(-11002, ss);\n  }\n\n  for(auto&& path : paths)\n  {\n    IDataArray::WeakPointer ptr = getDataContainerArray()->getPrereqIDataArrayFromPath(this, path);\n    if(ptr.lock())\n    {\n      m_SelectedWeakPtrVector.push_back(ptr);\n      int32_t numComps = ptr.lock()->getNumberOfComponents();\n      if(numComps != 1)\n      {\n        QString ss = QObject::tr(\"Attribute Arrays must be scalar arrays, but %1 has %2 total components\").arg(ptr.lock()->getName()).arg(numComps);\n        setErrorCondition(-11003, ss);\n      }\n    }\n  }\n\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  std::vector<size_t> tDims(1, paths.size());\n\n  DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getSelectedDataArrayPaths().at(0).getDataContainerName());\n  m->createNonPrereqAttributeMatrix(this, getPCAttributeMatrixName(), tDims, AttributeMatrix::Type::Generic, AttributeMatrixID21);\n\n  DataArrayPath tempPath;\n  std::vector<size_t> cDims(1, 1);\n\n  tempPath.update(getSelectedDataArrayPaths().at(0).getDataContainerName(), getPCAttributeMatrixName(), getPCEigenvaluesName());\n  m_PCEigenvaluesPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<double>>(this, tempPath, 0, cDims, \"\", DataArrayID31);\n  if(m_PCEigenvaluesPtr.lock())\n  {\n    m_PCEigenvalues = m_PCEigenvaluesPtr.lock()->getPointer(0);\n  }\n\n  cDims[0] = paths.size();\n\n  tempPath.update(getSelectedDataArrayPaths().at(0).getDataContainerName(), getPCAttributeMatrixName(), getPCEigenvectorsName());\n  m_PCEigenvectorsPtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<double>>(this, tempPath, 0, cDims, \"\", DataArrayID32);\n  if(m_PCEigenvectorsPtr.lock())\n  {\n    m_PCEigenvectors = m_PCEigenvectorsPtr.lock()->getPointer(0);\n  }\n\n  if(getProjectDataSpace())\n  {\n    if(getNumberOfDimensionsForProjection() <= 0)\n    {\n      QString ss = QObject::tr(\"Number of dimensions for the projected space (%1) must be greater than 0\").arg(getNumberOfDimensionsForProjection());\n      setErrorCondition(-11004, ss);\n    }\n\n    if(getNumberOfDimensionsForProjection() > paths.size())\n    {\n      QString ss = QObject::tr(\"Number of dimensions for the projected space (%1) must be less than or equal to the number of selected Attribute Arrays (%2)\")\n                       .arg(getNumberOfDimensionsForProjection())\n                       .arg(paths.size());\n      setErrorCondition(-11005, ss);\n    }\n\n    cDims[0] = getNumberOfDimensionsForProjection();\n\n    m_ProjectedDataSpacePtr = getDataContainerArray()->createNonPrereqArrayFromPath<DataArray<double>>(this, getProjectedDataSpaceArrayPath(), 0, cDims, \"\", DataArrayID33);\n    if(m_ProjectedDataSpacePtr.lock())\n    {\n      m_ProjectedDataSpace = m_ProjectedDataSpacePtr.lock()->getPointer(0);\n    }\n    if(getErrorCode() >= 0)\n    {\n      paths.push_back(getProjectedDataSpaceArrayPath());\n    }\n  }\n\n  getDataContainerArray()->validateNumberOfTuples(this, paths);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\ntemplate <typename T>\nvoid copyDataArrays(IDataArray::Pointer dataPtr, std::vector<double>& copy, int32_t arrayIndex)\n{\n  typename DataArray<T>::Pointer inDataPtr = std::dynamic_pointer_cast<DataArray<T>>(dataPtr);\n  T* dPtr = inDataPtr->getPointer(0);\n  size_t numTuples = inDataPtr->getNumberOfTuples();\n\n  for(size_t i = 0; i < numTuples; i++)\n  {\n    copy[numTuples * arrayIndex + i] = static_cast<double>(dPtr[i]);\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::execute()\n{\n  dataCheck();\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  if(m_SelectedDataArrayPaths.size() != m_SelectedWeakPtrVector.size())\n  {\n    QString ss = QObject::tr(\"The number of selected Attribute Arrays does not equal the number of internal weak pointers\");\n    setErrorCondition(-11008, ss);\n    return;\n  }\n\n  // Set up our Eigen variables ; we use a dynamic double matrix since we don't know\n  // the number of arrays or their tuples at compile time ; could have just used the\n  // MatrixXd typedef instead of our own, but this is explicit about the ordering\n  // being column major\n  auto numArrays = m_SelectedWeakPtrVector.size();\n  size_t numTuples = m_SelectedWeakPtrVector[0].lock()->getNumberOfTuples();\n\n  typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> CovarianceMatrix;\n\n  // Copy the incoming data into a contiguous chunk of memory, casting everything to doubles\n  std::vector<double> inDataVector(numTuples * numArrays, 0);\n\n  for(auto i = 0; i < numArrays; i++)\n  {\n    EXECUTE_FUNCTION_TEMPLATE(this, copyDataArrays, m_SelectedWeakPtrVector[i].lock(), m_SelectedWeakPtrVector[i].lock(), inDataVector, i);\n  }\n\n  // Interface our CovarianceMatrix typedef with our contiguous array in memory\n  // Using a colum major matrix, so each array is a column, so the arrays should\n  // be layed out end-to-end in memory ; initialization for sizes in Eigen is:\n  // numRows x numColumns\n  Eigen::Map<CovarianceMatrix> dataMat(inDataVector.data(), numTuples, numArrays);\n\n  // If the correlation approach is being used, the data must be standardize to have\n  // mean 0 and unit variance\n  if(m_MatrixApproach == 0)\n  {\n    // Standardize data to have mean 0 and unit variance\n    dataMat = (dataMat.rowwise() - dataMat.colwise().mean());\n    Eigen::RowVectorXd stdDev = dataMat.colwise().squaredNorm();\n    for(auto i = 0; i < stdDev.cols(); i++)\n    {\n      stdDev(i) /= dataMat.rows();\n      stdDev(i) = sqrt(stdDev(i));\n    }\n    dataMat = dataMat.array().rowwise() / stdDev.array();\n  }\n\n  // Calculate the covariance matrix using the matrix formulation, checking if\n  // tuples are 1 to avoid division by zero\n  // If correlation was chosen, then this is technically the correlation matrix,\n  // but since the means are zero in that case the centering operation is trivial\n  Eigen::MatrixXd centeredMat = dataMat.rowwise() - dataMat.colwise().mean();\n  Eigen::MatrixXd covMat;\n\n  if(numTuples == 1)\n  {\n    covMat = (centeredMat.adjoint() * centeredMat) / (1.0);\n  }\n  else\n  {\n    covMat = (centeredMat.adjoint() * centeredMat) / (double(numTuples - 1.0));\n  }\n\n  // Perform the eigen decomposition to get the eigenvectors and eigenvalues\n  // of the covariance matrix, then copy those values into the primary\n  // DataArray pointers\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> pca(covMat);\n\n  for(auto i = 0; i < pca.eigenvalues().size(); i++)\n  {\n    m_PCEigenvalues[i] = pca.eigenvalues()(i);\n  }\n\n  for(auto i = 0; i < pca.eigenvectors().cols(); i++)\n  {\n    for(auto j = 0; j < pca.eigenvectors().rows(); j++)\n    {\n      m_PCEigenvectors[pca.eigenvectors().rows() * i + j] = pca.eigenvectors()(j, i);\n    }\n  }\n\n  if(m_ProjectDataSpace)\n  {\n    // Extract the projective transform\n    // Eigen orders the eigenvalues/eigenvectors in ascending order, so just grab\n    // the rightmost columns equal to the number of projective dimensions\n    Eigen::MatrixXd transform = pca.eigenvectors().rightCols(m_NumberOfDimensionsForProjection);\n\n    // Multiply each row in the centered data matrix by transform and copy the projected\n    // points into the DataArray pointer\n    for(auto i = 0; i < centeredMat.rows(); i++)\n    {\n      Eigen::VectorXd tmp = centeredMat.row(i) * transform;\n      for(int32_t j = 0; j < m_NumberOfDimensionsForProjection; j++)\n      {\n        m_ProjectedDataSpace[m_NumberOfDimensionsForProjection * i + j] = tmp(j);\n      }\n    }\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nAbstractFilter::Pointer PrincipalComponentAnalysis::newFilterInstance(bool copyFilterParameters) const\n{\n  PrincipalComponentAnalysis::Pointer filter = PrincipalComponentAnalysis::New();\n  if(copyFilterParameters)\n  {\n    copyFilterParameterInstanceVariables(filter.get());\n  }\n  return filter;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString PrincipalComponentAnalysis::getCompiledLibraryName() const\n{\n  return DREAM3DReviewConstants::DREAM3DReviewBaseName;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString PrincipalComponentAnalysis::getBrandingString() const\n{\n  return \"DREAM3DReview\";\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString PrincipalComponentAnalysis::getFilterVersion() const\n{\n  QString version;\n  QTextStream vStream(&version);\n  vStream << DREAM3DReview::Version::Major() << \".\" << DREAM3DReview::Version::Minor() << \".\" << DREAM3DReview::Version::Patch();\n  return version;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString PrincipalComponentAnalysis::getGroupName() const\n{\n  return DREAM3DReviewConstants::FilterGroups::DREAM3DReviewFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQUuid PrincipalComponentAnalysis::getUuid() const\n{\n  return QUuid(\"{ec163736-39c8-5c69-9a56-61940a337c07}\");\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString PrincipalComponentAnalysis::getSubGroupName() const\n{\n  return DREAM3DReviewConstants::FilterSubGroups::DimensionalityReductionFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString PrincipalComponentAnalysis::getHumanLabel() const\n{\n  return \"Principal Component Analysis\";\n}\n\n// -----------------------------------------------------------------------------\nPrincipalComponentAnalysis::Pointer PrincipalComponentAnalysis::NullPointer()\n{\n  return Pointer(static_cast<Self*>(nullptr));\n}\n\n// -----------------------------------------------------------------------------\nstd::shared_ptr<PrincipalComponentAnalysis> PrincipalComponentAnalysis::New()\n{\n  struct make_shared_enabler : public PrincipalComponentAnalysis\n  {\n  };\n  std::shared_ptr<make_shared_enabler> val = std::make_shared<make_shared_enabler>();\n  val->setupFilterParameters();\n  return val;\n}\n\n// -----------------------------------------------------------------------------\nQString PrincipalComponentAnalysis::getNameOfClass() const\n{\n  return QString(\"PrincipalComponentAnalysis\");\n}\n\n// -----------------------------------------------------------------------------\nQString PrincipalComponentAnalysis::ClassName()\n{\n  return QString(\"PrincipalComponentAnalysis\");\n}\n\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::setSelectedDataArrayPaths(const QVector<DataArrayPath>& value)\n{\n  m_SelectedDataArrayPaths = value;\n}\n\n// -----------------------------------------------------------------------------\nQVector<DataArrayPath> PrincipalComponentAnalysis::getSelectedDataArrayPaths() const\n{\n  return m_SelectedDataArrayPaths;\n}\n\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::setPCAttributeMatrixName(const QString& value)\n{\n  m_PCAttributeMatrixName = value;\n}\n\n// -----------------------------------------------------------------------------\nQString PrincipalComponentAnalysis::getPCAttributeMatrixName() const\n{\n  return m_PCAttributeMatrixName;\n}\n\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::setPCEigenvaluesName(const QString& value)\n{\n  m_PCEigenvaluesName = value;\n}\n\n// -----------------------------------------------------------------------------\nQString PrincipalComponentAnalysis::getPCEigenvaluesName() const\n{\n  return m_PCEigenvaluesName;\n}\n\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::setPCEigenvectorsName(const QString& value)\n{\n  m_PCEigenvectorsName = value;\n}\n\n// -----------------------------------------------------------------------------\nQString PrincipalComponentAnalysis::getPCEigenvectorsName() const\n{\n  return m_PCEigenvectorsName;\n}\n\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::setMatrixApproach(int value)\n{\n  m_MatrixApproach = value;\n}\n\n// -----------------------------------------------------------------------------\nint PrincipalComponentAnalysis::getMatrixApproach() const\n{\n  return m_MatrixApproach;\n}\n\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::setProjectDataSpace(bool value)\n{\n  m_ProjectDataSpace = value;\n}\n\n// -----------------------------------------------------------------------------\nbool PrincipalComponentAnalysis::getProjectDataSpace() const\n{\n  return m_ProjectDataSpace;\n}\n\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::setNumberOfDimensionsForProjection(int value)\n{\n  m_NumberOfDimensionsForProjection = value;\n}\n\n// -----------------------------------------------------------------------------\nint PrincipalComponentAnalysis::getNumberOfDimensionsForProjection() const\n{\n  return m_NumberOfDimensionsForProjection;\n}\n\n// -----------------------------------------------------------------------------\nvoid PrincipalComponentAnalysis::setProjectedDataSpaceArrayPath(const DataArrayPath& value)\n{\n  m_ProjectedDataSpaceArrayPath = value;\n}\n\n// -----------------------------------------------------------------------------\nDataArrayPath PrincipalComponentAnalysis::getProjectedDataSpaceArrayPath() const\n{\n  return m_ProjectedDataSpaceArrayPath;\n}\n", "meta": {"hexsha": "b1a4eed7e34ef23e2ecbac02cdcf419ac81479c9", "size": 23050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DREAM3DReviewFilters/PrincipalComponentAnalysis.cpp", "max_stars_repo_name": "JDuffeyBQ/DREAM3DReview", "max_stars_repo_head_hexsha": "098ddc60d1c53764e09e21e08d4636233071be31", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DREAM3DReviewFilters/PrincipalComponentAnalysis.cpp", "max_issues_repo_name": "JDuffeyBQ/DREAM3DReview", "max_issues_repo_head_hexsha": "098ddc60d1c53764e09e21e08d4636233071be31", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DREAM3DReviewFilters/PrincipalComponentAnalysis.cpp", "max_forks_repo_name": "JDuffeyBQ/DREAM3DReview", "max_forks_repo_head_hexsha": "098ddc60d1c53764e09e21e08d4636233071be31", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0142348754, "max_line_length": 192, "alphanum_fraction": 0.62, "num_tokens": 4514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4239972471013279}}
{"text": "#include <cstdlib>\n#include <list>\n#include <Eigen/Core>\n#include <moihgp/moihgp_regression.h>\n#include <moihgp/matern32ss.h>\n#include <iostream>\n#include <time.h>\n\n\n\nint main()\n{\n\n    double dt = 0.1;\n    size_t num_output = 2;\n    size_t num_latent = 1;\n    bool threading = true;\n    Eigen::MatrixXd H(2, 2);\n    H << 0.7, 0.3, -0.3, 0.7;\n    std::vector<Eigen::VectorXd> data;\n    double t = 0.0;\n    while (t < 2 * M_PI)\n    {\n        Eigen::VectorXd x(num_latent);\n        x << sin(t), sin(4*t);\n        data.push_back(H * x + 0.1 * Eigen::VectorXd(num_output).setRandom());\n        t += dt;\n    }\n    data.shrink_to_fit();\n    size_t num_data = data.size();\n\n    moihgp::MOIHGPRegression<moihgp::Matern32StateSpace> gp(dt, num_output, num_latent, num_data, threading);\n    clock_t tic = clock();\n    int niter = gp.fit(data);\n    clock_t toc = clock();\n\n    std::cout << \"Iteration count: \" << niter << std::endl;\n    std::cout << \"Elapsed time: \" << double(toc - tic) / 1000.0 << \"ms\" << std::endl;\n\n    return 0;\n\n}", "meta": {"hexsha": "f916834b0b1132ad70a48e0be94485f1cb3a26ed", "size": 1024, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moihgp/cpp_examples/example_regression.cpp", "max_stars_repo_name": "MLCS-Yonsei/MultiOutputIHGP", "max_stars_repo_head_hexsha": "3767325f57c5cd34655013fd9c7a0d87e97fc74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "moihgp/cpp_examples/example_regression.cpp", "max_issues_repo_name": "MLCS-Yonsei/MultiOutputIHGP", "max_issues_repo_head_hexsha": "3767325f57c5cd34655013fd9c7a0d87e97fc74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moihgp/cpp_examples/example_regression.cpp", "max_forks_repo_name": "MLCS-Yonsei/MultiOutputIHGP", "max_forks_repo_head_hexsha": "3767325f57c5cd34655013fd9c7a0d87e97fc74f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-10T16:44:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T16:44:42.000Z", "avg_line_length": 24.380952381, "max_line_length": 109, "alphanum_fraction": 0.5908203125, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8479677506936878, "lm_q2_score": 0.5, "lm_q1q2_score": 0.4239838753468439}}
{"text": "/*\nCopyright (C) 2012 Mathias Eitz and Ronald Richter.\nAll rights reserved.\n\nThis file is part of the imdb library and is made available under\nthe terms of the BSD license (see the LICENSE file).\n*/\n\n#ifndef KMEANS_INIT_HPP\n#define KMEANS_INIT_HPP\n\n#include <vector>\n#include <boost/random.hpp>\n\n#include \"distance.hpp\"\n\ntemplate <class index_t, class collection_t>\nvoid kmeans_init_random(std::vector<index_t>& centers, const collection_t& collection, std::size_t numclusters)\n{\n    assert(collection.size() >= numclusters);\n\n    centers.resize(collection.size());\n    for (std::size_t i = 0; i < centers.size(); i++) centers[i] = i;\n    std::random_shuffle(centers.begin(), centers.end());\n    centers.resize(numclusters);\n}\n\ntemplate <class index_t, class collection_t, class dist_fn>\nvoid kmeans_init_plusplus(std::vector<index_t>& result, const collection_t& collection, std::size_t numclusters, const dist_fn& distfn)\n{\n    assert(numclusters > 0);\n    assert(collection.size() >= numclusters);\n\n    typedef typename collection_t::value_type item_t;\n    typedef boost::mt19937                    rng_t;\n    typedef boost::uniform_real<double>       unirand_t;\n\n    rng_t rng;\n\n    boost::variate_generator<rng_t&, unirand_t> unirand(rng, unirand_t(0.0, 1.0));\n\n    std::size_t numtrials = 2 + std::log(numclusters);\n\n    // add first cluster, randomly chosen\n    std::set<index_t> centers;\n    index_t first = unirand() * collection.size();\n    centers.insert(first);\n\n    // compute distance between first cluster center and all others\n    // and accumulate the distances that gives the current potential\n    std::vector<double> dists(collection.size());\n    double potential = 0.0;\n    for (std::size_t i = 0; i < collection.size(); i++)\n    {\n        double d = distfn(collection[first], collection[i]);\n        dists[i] = d*d;\n        potential += dists[i];\n    }\n    std::cout << \"kmeans++ init: numclusters=\" << numclusters << \" numtrials=\" << numtrials << \" collection.size=\" << collection.size() << \" init pot=\" << potential << std::endl;\n\n    // iteratively add centers\n    for (std::size_t c = 1; c < numclusters; c++)\n    {\n        double min_potential = std::numeric_limits<double>::max();\n        std::size_t best_index = 0;\n\n        for (std::size_t i = 0; i < numtrials; i++)\n        {\n            std::size_t index;\n\n            // get new center\n            double r = unirand() * potential;\n            for (index = 0; index < collection.size()-1 && r > dists[index]; index++)\n            {\n                r -= dists[index];\n            }\n\n            while (centers.count(index) > 0) index = (index + 1) % collection.size();\n\n            // recompute potential\n            double p = 0.0;\n            for (std::size_t k = 0; k < collection.size(); k++)\n            {\n                double d = distfn(collection[index], collection[k]);\n                p += std::min(dists[k], d*d);\n            }\n\n            if (p < min_potential)\n            {\n                min_potential = p;\n                best_index = index;\n            }\n        }\n\n        for (std::size_t i = 0; i < collection.size(); i++)\n        {\n            double d = distfn(collection[best_index], collection[i]);\n            dists[i] = d*d;\n        }\n\n        potential = min_potential;\n\n        centers.insert(best_index);\n\n        std::cout << \"new center \" << c << \": potential=\" << potential << \" index=\" << best_index << std::endl;\n    }\n\n    std::copy(centers.begin(), centers.end(), std::back_inserter(result));\n}\n\nenum KmeansInitAlgorithm\n{\n    KmeansInitRandom,\n    KmeansInitPlusPlus\n};\n\n#endif // KMEANS_INIT_HPP\n", "meta": {"hexsha": "d87cbbba3eb748bd71a5c20f848325d99ddc9369", "size": 3619, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "imdb/image_search/kmeans_init.hpp", "max_stars_repo_name": "jjkislele/imdb_framework_msvs", "max_stars_repo_head_hexsha": "e283499ec6b7095d471671e963815aced45c38fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-16T11:25:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T11:25:01.000Z", "max_issues_repo_path": "imdb/image_search_featureExtracted/kmeans_init.hpp", "max_issues_repo_name": "jjkislele/imdb_framework_msvs", "max_issues_repo_head_hexsha": "e283499ec6b7095d471671e963815aced45c38fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imdb/image_search_featureExtracted/kmeans_init.hpp", "max_forks_repo_name": "jjkislele/imdb_framework_msvs", "max_forks_repo_head_hexsha": "e283499ec6b7095d471671e963815aced45c38fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6694915254, "max_line_length": 178, "alphanum_fraction": 0.5979552363, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4239835136237395}}
{"text": "#include <opencv2/opencv.hpp>\r\n#include <Eigen/SparseCholesky>\r\n#include <opencv2/core/eigen.hpp>\r\n#include \"Consts.h\"\r\nusing namespace std;\r\nusing namespace cv;\r\nusing namespace Eigen;\r\n\r\n\r\nMat Get_Pixel_Indices_Mat(int rows, int cols) {//Fill the Pixels mat as indices of image pixels - by rows\r\n\tMat Pixel_idx(rows, cols, DataType<int>::type, Scalar(0));\r\n\tint i, j, k = 0;\r\n\tfor (i = 0; i < rows; i++) {\r\n\t\tfor (j = 0; j < cols; j++) {\r\n\t\t\tPixel_idx.at<int>(i,j) = k;\r\n\t\t\tk++;\r\n\t\t}\r\n\t}\r\n\treturn Pixel_idx;\r\n}\r\n\r\n\r\nvoid Calc_Mean(Mat values, Mat * mean) {\r\n\tdouble result = 0;\r\n\tint i, j;\r\n\tfor (i = 0; i < CHANNELS_NUM; i++) {\r\n\t\tfor (j = 0; j < values.rows; j++) {\r\n\t\t\tresult += values.at<double>(j, i);\r\n\t\t}\r\n\t\t(*mean).at<double>(0,i) = result/(double)values.rows;\r\n\t\tresult = 0;\r\n\t}\r\n\treturn;\r\n}\r\n\r\n\r\nRect Get_Frame(int x, int y, int frame_size, int rows, int cols) {\r\n\tint width = frame_size, height = frame_size;\r\n\tint m = x - frame_size/2, n = y - frame_size/2;\r\n\tif (x > frame_size / 2 && x < cols - frame_size / 2 && y > frame_size / 2 && y < rows - frame_size / 2) {\r\n\t\tRect R(m, n, width, height);\r\n\t\treturn R;\r\n\t}\r\n\telse {\r\n\t\tif (m < 0) {\r\n\t\t\twidth = frame_size + m;\r\n\t\t\tm = 0;\r\n\t\t}\r\n\t\telse if (cols - m - frame_size < 0) {\r\n\t\t\twidth = cols - m;\r\n\t\t}\r\n\t\tif (n < 0) {\r\n\t\t\theight = frame_size + n;\r\n\t\t\tn = 0;\r\n\t\t}\r\n\t\telse if (rows - n - frame_size < 0) {\r\n\t\t\theight = rows - n;\r\n\t\t}\r\n\t\tRect R(m, n, width, height);\r\n\t\treturn R;\r\n\t}\r\n}\r\n\r\n\r\nMat Laplacian_In_Patch(Mat Values, Mat Mean, Mat Covar, double regularization_parameter) {\r\n\tint i, j;\r\n\tMat Image_Part_Mat_T(CHANNELS_NUM, Values.cols, DataType<double>::type);\r\n\tMat Image_Part_Mat(Values.rows, CHANNELS_NUM, DataType<double>::type);\r\n\tMat Covar_Part_Mat(CHANNELS_NUM, CHANNELS_NUM, DataType<double>::type);\r\n\tMat Identity(CHANNELS_NUM, CHANNELS_NUM, DataType<double>::type);\r\n\tMat Result;\r\n\tsetIdentity(Identity, Scalar(1));\r\n\tCovar_Part_Mat = (regularization_parameter / (double)Values.rows)*Identity;\r\n\tCovar_Part_Mat = Covar + Covar_Part_Mat;\r\n\tCovar_Part_Mat = Covar_Part_Mat.inv();\r\n\tfor (i = 0; i < CHANNELS_NUM; i++) {\r\n\t\tfor (j = 0; j < Values.rows; j++) {\r\n\t\t\tImage_Part_Mat.at<double>(j, i) = Values.at<double>(j, i) - Mean.at<double>(0, i);\r\n\t\t}\r\n\t}\r\n\ttranspose(Image_Part_Mat, Image_Part_Mat_T);\r\n\tResult = Image_Part_Mat*Covar_Part_Mat*Image_Part_Mat_T;\r\n\tfor (i = 0; i < Result.rows; i++) {\r\n\t\tfor (j = 0; j < Result.cols; j++) {\r\n\t\t\tResult.at<double>(i, j) = -Result.at<double>(i, j) - 1;\r\n\t\t}\r\n\t}\r\n\tResult = Result / Values.rows;\r\n\treturn Result;\r\n}\r\n\r\n\r\nMat Reshape_To_Channels_And_Normalize(Mat source){\r\n\tint i, j, k , Patch_reshaped_iterator = 0;\r\n\tMat Patch_reshaped(source.rows*source.cols, CHANNELS_NUM, DataType<double>::type);\r\n\tfor (j = 0; j < source.rows; j++) {\r\n\t\tfor (i = 0; i < source.cols; i++) {\r\n\t\t\tfor (k = 0; k < CHANNELS_NUM; k++) {\r\n\t\t\t\tPatch_reshaped.at<double>(Patch_reshaped_iterator, k) = (double)source.at<Vec3b>(j, i)[CHANNELS_NUM - k - 1] / (double)255;\r\n\t\t\t}\r\n\t\t\tPatch_reshaped_iterator++;\r\n\t\t}\r\n\t}\r\n\treturn Patch_reshaped;\r\n}\r\n\r\n\r\nvoid Calc_Covar(Mat patch, Mat patch_idx, int patch_size, Mat Mean, Mat * Covar) {\r\n\tMat Mean_Mul_Mean_T(CHANNELS_NUM, CHANNELS_NUM, DataType<double>::type);\r\n\tMat Mean_T(CHANNELS_NUM, 1, DataType<double>::type);\r\n\tMat Patch_T(CHANNELS_NUM, patch_size, DataType<double>::type);\r\n\ttranspose(Mean, Mean_T);\r\n\tMean_Mul_Mean_T = Mean_T*(Mean);\r\n\ttranspose(patch, Patch_T);\r\n\t*Covar = Patch_T*patch / patch_size;\r\n\t*Covar = *Covar - Mean_Mul_Mean_T;\r\n\treturn;\r\n}\r\n\r\n\r\nMat Normalize_Mat(Mat Transmission) {\r\n\tint i, j;\r\n\tMat normalized(Transmission.rows, Transmission.cols, DataType<double>::type);\r\n\tfor (i = 0; i < Transmission.rows; i++) {\r\n\t\tfor (j = 0; j < Transmission.cols; j++) {\r\n\t\t\tnormalized.at<double>(i, j) = (double)Transmission.at<uchar>(i, j) / 255;\r\n\t\t}\r\n\t}\r\n\treturn normalized;\r\n}\r\n\r\n\r\nvoid Assign_Lap_Values_To_Correct_Indices(Mat Values, Mat indices, vector<Triplet<double>> * tripletList) {\r\n\tint i, j, lap_index_x, lap_index_y;\r\n\tdouble res_value = 0;\r\n\tfor (i = 0; i < Values.rows; i++) {\r\n\t\tfor (j = 0; j < Values.cols; j++) {\r\n\t\t\tlap_index_x = indices.at<int>(0, i);\r\n\t\t\tlap_index_y = indices.at<int>(0, j); \r\n\t\t\tif (lap_index_y > lap_index_x) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tres_value = Values.at<double>(i, j);\r\n\t\t\tif (i == j) {\r\n\t\t\t\tres_value += 1;\r\n\t\t\t}\r\n\t\t\t(*tripletList).push_back(Triplet<double>(lap_index_x, lap_index_y, res_value));\r\n\t\t}\r\n\t}\r\n\treturn;\r\n}\r\n\r\n\r\nSparseMatrix<double> GetLaplacian(Mat image, int frame_size, double regularization_parameter) { //frame_size is supposably 3\r\n\tint rows = image.rows;\r\n\tint cols = image.cols;\r\n\tint size = rows*cols;\r\n\tint i, area, j = 0;\r\n\tint num_of_frames_for_single_pixel = frame_size*frame_size;\r\n\tint entries_per_column_estimation = frame_size * 2 - 1;\r\n\tint estimation_of_entries = size*entries_per_column_estimation;\r\n\tMat mean(1, CHANNELS_NUM, DataType<double>::type, Scalar(0));\r\n\tMat covar(CHANNELS_NUM, CHANNELS_NUM, DataType<double>::type, Scalar(0));\r\n\tMat Patch, Patch_idx, Patch_Reshaped, Lap_In_Patch;\r\n\tMat Pixel_idx = Get_Pixel_Indices_Mat(rows, cols);\r\n\tMat Mean(1, CHANNELS_NUM, DataType<double>::type, Scalar(0));\r\n\tMat Covar(CHANNELS_NUM, CHANNELS_NUM, DataType<double>::type, Scalar(0));\r\n\tvector<Triplet<double>> tripletList;\r\n\tSparseMatrix<double> result_LowerTriangle(size, size);\r\n\ttripletList.reserve(estimation_of_entries);\r\n\tresult_LowerTriangle.reserve(VectorXi::Constant(size, entries_per_column_estimation));//CORRECT RESERVE FOR LOWER TRIANGLEVIEW\r\n\tfor (i = 0; i < rows; i++) {\r\n\t\tfor (j = 0; j < cols; j++) {\r\n\t\t\tRect R = Get_Frame(j, i, frame_size, rows, cols);\r\n\t\t\tarea = R.area();\r\n\t\t\tPatch = image(R);\r\n\t\t\tPatch_Reshaped = Reshape_To_Channels_And_Normalize(Patch);\r\n\t\t\tCalc_Mean(Patch_Reshaped, &Mean);\r\n\t\t\tCalc_Covar(Patch_Reshaped, Patch_idx, area, Mean, &Covar);\r\n\t\t\tLap_In_Patch = Laplacian_In_Patch(Patch_Reshaped, Mean, Covar, regularization_parameter);\r\n\t\t\tPatch_idx = Pixel_idx(R);\r\n\t\t\tif (!Patch_idx.isContinuous())\r\n\t\t\t{\r\n\t\t\t\tPatch_idx = Patch_idx.clone();\r\n\t\t\t}\r\n\t\t\tPatch_idx = Patch_idx.reshape(0, 1);\r\n\t\t\tAssign_Lap_Values_To_Correct_Indices(Lap_In_Patch, Patch_idx, &tripletList);\r\n\t\t}\r\n\t}\r\n\tresult_LowerTriangle.setFromTriplets(tripletList.begin(), tripletList.end());\r\n\tSparseMatrix<double> result = result_LowerTriangle.selfadjointView<Lower>();\r\n\treturn result;\r\n}\r\n\r\n\r\nMat SoftMatting(Mat Transmission, Mat image, int frame_size, double regularization_parameter, double lambda) {\r\n\tint i, j;\r\n\tint Laplacian_Size = image.rows*image.cols;\r\n\tMat t;\r\n\tMat normalized_Transmission = Normalize_Mat(Transmission);\r\n\tMat b = normalized_Transmission.reshape(0, Laplacian_Size);\r\n\tMat Transmission_new(Transmission.rows, Transmission.cols, DataType<uchar>::type);\r\n\tMatrix<double, Dynamic, Dynamic, ColMajor> b_Eigen(b.rows, b.cols);\r\n\tMap<VectorXd> b_Vector(b_Eigen.data(), b_Eigen.size());\r\n\tSparseMatrix<double> Laplacian = GetLaplacian(image, frame_size, regularization_parameter);\r\n\tSparseMatrix<double> Identity_Mat(Laplacian_Size, Laplacian_Size);\r\n\tSparseMatrix<double> A(Laplacian_Size, Laplacian_Size);\r\n\tSimplicialLLT<SparseMatrix<double>> solver;\r\n\tVectorXd x;\r\n\tb = lambda*b;\r\n\tcv2eigen(b, b_Eigen);\r\n\tIdentity_Mat.setIdentity();\r\n\tA = lambda*Identity_Mat;\r\n\tA += Laplacian;\r\n\tx = solver.compute(A).solve(b_Vector);//Solve Ax = b for x\r\n\tb_Eigen.col(0) = x;\r\n\teigen2cv(b_Eigen, t);\r\n\tt = t.reshape(0, Transmission.rows);\r\n\tfor (i = 0; i < Transmission.rows; i++) {\r\n\t\tfor (j = 0; j < Transmission.cols; j++) {\r\n\t\t\tTransmission_new.at<uchar>(i, j) = (uchar)min(255, (int)(t.at<double>(i, j) * 255));\r\n\t\t}\r\n\t}\r\n\treturn Transmission_new;\r\n}", "meta": {"hexsha": "c51f8a08963b30f60cfcbcd715e20c3d3f2202b9", "size": 7615, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Soft_Matting.cpp", "max_stars_repo_name": "yanchevskyroman/DCP", "max_stars_repo_head_hexsha": "1037b330613ab9be30cd043e3e3272b5480717fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-07T08:17:37.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-07T08:17:37.000Z", "max_issues_repo_path": "Soft_Matting.cpp", "max_issues_repo_name": "yanchevskyroman/DCP", "max_issues_repo_head_hexsha": "1037b330613ab9be30cd043e3e3272b5480717fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Soft_Matting.cpp", "max_forks_repo_name": "yanchevskyroman/DCP", "max_forks_repo_head_hexsha": "1037b330613ab9be30cd043e3e3272b5480717fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8444444444, "max_line_length": 128, "alphanum_fraction": 0.6719632305, "num_tokens": 2282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.42395062427725666}}
{"text": "#include <algorithm>\n#include <boost/optional.hpp>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)\n#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)\n#define EACH(e, a) for(auto&& e : a)\n#define ALL(a) std::begin(a), std::end(a)\n#define RALL(a) std::rbegin(a), std::rend(a)\n#define FILL(a, n) memset((a), n, sizeof(a))\n#define FILLZ(a) FILL(a, 0)\n#define INT(x) (static_cast<int>(x))\n\nusing namespace std;\n\nusing ll = long long;\nusing VI = vector<int>;\nusing VI2D = vector<vector<int>>;\n\nconstexpr int INF = 2e9;\nconstexpr double EPS = 1e-10;\nconstexpr double PI = acos(-1.0);\n\nconstexpr int dx[] = {-1, 0, 1, 0};\nconstexpr int dy[] = {0, -1, 0, 1};\n\ntemplate <typename T>\nconstexpr int sign(T x) {\n\treturn x < 0 ? -1 : x > 0 ? 1 : 0;\n}\n\ntemplate <>\nconstexpr int sign(double x) {\n\treturn x < -EPS ? -1 : x > EPS ? 1 : 0;\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmax(T& m, U x) {\n\tm = max(m, x);\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmin(T& m, U x) {\n\tm = min(m, x);\n}\n\ntemplate <typename T>\nconstexpr T square(T x) {\n\treturn x * x;\n}\n\nconstexpr double deg_to_rad(double deg) {\n\treturn PI * deg / 180.0;\n}\n\nconstexpr double rad_to_deg(double rad) {\n\treturn rad * 180 / PI;\n}\n\n// 二次元ベクトルクラス\nclass Vec2d {\n\tdouble _x;\n\tdouble _y;\n\n\tpublic:\n\t// 原点の位置ベクトル\n\tstatic constexpr Vec2d origin() { return Vec2d(0.0, 0.0); }\n\n\t// ゼロベクトル\n\tstatic constexpr Vec2d zero() { return Vec2d::origin(); }\n\n\tconstexpr Vec2d(double a, double b) : _x(a), _y(b) {}\n\n\tconstexpr double x() const { return this->_x; }\n\tconstexpr double y() const { return this->_y; }\n\n\t// 外積\n\tconstexpr double det(const Vec2d& rhs) const {\n\t\treturn this->x() * rhs.y() - this->y() * rhs.x();\n\t}\n\n\t// 内積\n\tconstexpr double dot(const Vec2d& rhs) const {\n\t\treturn this->x() * rhs.x() + this->y() * rhs.y();\n\t}\n\n\t// 長さ\n\tconstexpr double length() const { return this->distance(Vec2d::origin()); }\n\n\t// 2つの位置ベクトル間のユークリッド距離\n\tconstexpr double distance(const Vec2d& rhs) const {\n\t\treturn std::sqrt(square(this->x() - rhs.x()) +\n\t\t\t\t\t\t square(this->y() - rhs.y()));\n\t}\n\n\t// 2つの位置ベクトル間のマンハッタン距離\n\tconstexpr double manhattan_distance(const Vec2d& rhs) const {\n\t\treturn std::abs(this->x() - rhs.x()) + std::abs(this->y() - rhs.y());\n\t}\n\n\t// ベクトルとx軸のなす角\n\tconstexpr double argument() const {\n\t\treturn std::atan2(this->y(), this->x());\n\t}\n\n\t// 反時計回りに回転したベクトル\n\tconstexpr Vec2d rotate(double rad) const {\n\t\tdouble xx = this->x();\n\t\tdouble yy = this->y();\n\t\treturn Vec2d(xx * cos(rad) - yy * sin(rad),\n\t\t\t\t\t xx * sin(rad) + yy * cos(rad));\n\t}\n\n\t// 単位ベクトル\n\tconstexpr Vec2d unit() const {\n\t\tdouble len = this->length();\n\t\treturn Vec2d(this->x() / len, this->y() / len);\n\t}\n\n\t// 法線ベクトル\n\tconstexpr Vec2d normal() const {\n\t\tdouble len = this->length();\n\t\treturn Vec2d(this->y() / len, -this->x() / len);\n\t}\n\n\t// 平行判定\n\tconstexpr bool is_parallel(const Vec2d& rhs) const { return false; }\n\n\t// ベクトル和\n\tconstexpr Vec2d operator+() const { return *this; }\n\tconstexpr Vec2d operator+(const Vec2d& rhs) const {\n\t\treturn Vec2d(this->x() + rhs.x(), this->y() + rhs.y());\n\t}\n\n\t// ベクトル差\n\tconstexpr Vec2d operator-() const { return Vec2d(-this->x(), -this->y()); }\n\tconstexpr Vec2d operator-(const Vec2d& rhs) const {\n\t\treturn Vec2d(this->x() - rhs.x(), this->y() - rhs.y());\n\t}\n\n\t// スカラー積\n\tconstexpr Vec2d operator*(const double rhs) const {\n\t\treturn Vec2d(this->x() * rhs, this->y() * rhs);\n\t}\n\tconstexpr Vec2d operator/(const double rhs) const {\n\t\treturn Vec2d(this->x() / rhs, this->y() / rhs);\n\t}\n\n\tconstexpr bool operator<(const Vec2d& rhs) const {\n\t\treturn sign(this->x()) ? this->y() < rhs.y() : this->x() < rhs.x();\n\t}\n\n\tprivate:\n};\n\n// 点の進行方向\nconstexpr int ccw(Vec2d a, Vec2d b, Vec2d c) {\n\tVec2d ab = b - a;\n\tVec2d ac = c - a;\n\tint det = ab.det(ac);\n\tif(det > 0) {\n\t\treturn 1; // 反時計回り\n\t}\n\tif(det < 0) {\n\t\treturn -1; // 時計回り\n\t}\n\tif(ab.dot(ac) < 0) {\n\t\treturn 2; // c-a-b\n\t}\n\tif(ab.normal() < ac.normal()) {\n\t\treturn -2; // a-b-c\n\t}\n\treturn 0; // a-c-b\n}\n\nint main() {\n\tdouble a, b, h, m;\n\tcin >> a >> b >> h >> m;\n\tVec2d hvec(0, a);\n\tVec2d mvec(0, b);\n\tdouble harg = -deg_to_rad(h * 30 + (m / 2));\n\tdouble marg = -deg_to_rad(m * 6);\n\tVec2d moved_hour_vec = hvec.rotate(harg);\n\tVec2d moved_min_vec = mvec.rotate(marg);\n\tdouble dist = moved_min_vec.distance(moved_hour_vec);\n\tcout << setprecision(16) << dist << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "9ace2eda427338f4e4044d20b3cabe04af6cbd4d", "size": 4733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC168/C.cpp", "max_stars_repo_name": "arlechann/atcoder", "max_stars_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AtCoder/ABC168/C.cpp", "max_issues_repo_name": "arlechann/atcoder", "max_issues_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AtCoder/ABC168/C.cpp", "max_forks_repo_name": "arlechann/atcoder", "max_forks_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6459330144, "max_line_length": 76, "alphanum_fraction": 0.62074794, "num_tokens": 1651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.42395061755860936}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <sstream>\n#include <string>\n#include <list>\n#include <vector>\n#include <tuple>\n#include <functional>\n#include <utility>\n#include <iomanip>\n\nusing namespace std::string_literals;\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"vlasovpp/field.h\"\n#include \"vlasovpp/complex_field.h\"\n#include \"vlasovpp/weno.h\"\n#include \"vlasovpp/fft.h\"\n#include \"vlasovpp/array_view.h\"\n#include \"vlasovpp/poisson.h\"\n#include \"vlasovpp/rk.h\"\n#include \"vlasovpp/config.h\"\n#include \"vlasovpp/signal_handler.h\"\n#include \"vlasovpp/iteration.h\"\n#include \"vlasovpp/physic.h\"\n#include \"vlasovpp/tool.h\"\n\n\nnamespace math = boost::math::constants;\nconst std::complex<double> & I = std::complex<double>(0.,1.);\n\n#define SQ(X) ((X)*(X))\n#define Zi(i) (i*f.step.dz+f.range.z_min)\n#define Vkx(k) (k*f.step.dvx+f.range.vx_min)\n#define Vky(k) (k*f.step.dvy+f.range.vy_min)\n#define Vkz(k) (k*f.step.dvz+f.range.vz_min)\n\n{% for i in range(0,expLt_mat|count) %}\n  {% for j in range(0,expLt_mat[i]|count) %}\nstd::complex<double>\nmatrixExpr{{ i }}{{ j }} ( double t , double k ) {\n  return {{ expLt_mat[i][j] }};\n}\n  {% endfor %}\n{% endfor %}\n\nint\nmain ( int argc , char const * argv[] )\n{\n  // load configuration\n  auto c = config(argc,argv,\"{{ simu_name }}\");\n  c.create_output_directory();\n  save_config(c);\n\n/* ---------------------------------------------------------------- */\n  // physics variables initilization\n\n  field3d<double> f(boost::extents[c.Nvx][c.Nvy][c.Nvz][c.Nz]);\n  complex_field<double,3> hf(boost::extents[c.Nvx][c.Nvy][c.Nvz][c.Nz]);\n\n  ublas::vector<double> jcx(c.Nz,0.) , jcy(c.Nz,0.);\n  ublas::vector<double> Ex(c.Nz,0.)  , Ey(c.Nz,0.);\n  ublas::vector<double> Bx(c.Nz,0.)  , By(c.Nz,0.);\n\n  // range in velocity are done by jinja parameter\n  f.range.vx_min = {{ frange.vx_min }}; f.range.vx_max = {{ frange.vx_max }};\n  f.range.vy_min = {{ frange.vy_min }}; f.range.vy_max = {{ frange.vy_max }};\n  f.range.vz_min = {{ frange.vz_min }}; f.range.vz_max = {{ frange.vz_max }};\n  // range in space are done from config (K parameter)\n  f.range.z_min =  0.;  f.range.z_max = 2.*math::pi<double>()/c.K;\n\n  f.compute_steps();\n\n  const double v_par  = c.v_par;\n  const double v_perp = c.v_perp;\n  const double nh = c.nh;\n  const double B0 = c.B0;\n\n  ublas::vector<double> Kz(c.Nz);\n  {\n    const double L = f.range.len_z();\n    for ( auto i=0u ; i<c.Nz/2 ; ++i ) { Kz[i]      = 2.*math::pi<double>()*i/L; }\n    for ( auto i=-c.Nz/2 ; i<0 ; ++i ) { Kz[c.Nz+i] = 2.*math::pi<double>()*i/L; }\n  }\n\n  // initial condition\n  auto M1 = maxwellian(nh,{0.,0.,0.},{v_perp,v_perp,v_par});\n  for ( auto k_x=0u ; k_x<c.Nvx ; ++k_x ) {\n    for ( auto k_y=0u ; k_y<c.Nvy ; ++k_y ) {\n      for ( auto k_z=0u ; k_z<c.Nvz ; ++k_z ) {\n        for (std::size_t i=0u ; i<f.size_x() ; ++i ) {\n          const double vx = k_x*f.step.dvx + f.range.vx_min;\n          const double vy = k_y*f.step.dvy + f.range.vy_min;\n          const double vz = k_z*f.step.dvz + f.range.vz_min;\n          const double z  = i*f.step.dz + f.range.z_min;\n          f[k_x][k_y][k_z][i] = M1( z,vx,vy,vz );\n        }\n        fft::fft(f[k_x][k_y][k_z].begin(),f[k_x][k_y][k_z].end(),hf[k_x][k_y][k_z].begin());\n      }\n    }\n  }\n  for ( auto i=0u ; i<c.Nz ; ++i ) {\n    double z = f.range.z_min + f.step.dz*i;\n    Bx[i] = c.alpha * std::sin(c.K*z);\n  }\n\n  // end physics variables initialization\n/* ---------------------------------------------------------------- */\n  // monitorring initialization\n\n  std::vector<double> times;           times.reserve(100);\n  std::vector<double> electric_energy; electric_energy.reserve(100);\n  std::vector<double> kinetic_energy;  kinetic_energy.reserve(100);\n  std::vector<double> magnetic_energy; magnetic_energy.reserve(100);\n  std::vector<double> cold_energy;     cold_energy.reserve(100);\n  std::vector<double> mass;            mass.reserve(100);\n  std::vector<double> Bxmax;           Bxmax.reserve(100);\n  std::vector<double> Bymax;           Bymax.reserve(100);\n  std::vector<double> Exmax;           Exmax.reserve(100);\n  std::vector<double> Eymax;           Eymax.reserve(100);\n\n  ublas::vector<double> fdvxdvydz(c.Nvz,0.);\n  ublas::vector<double> vxfdv(c.Nz,0.), vyfdv(c.Nz,0.), vzfdv(c.Nz,0.);\n  ublas::vector<double> ec_perp(c.Nz,0.), ec_vz(c.Nz,0.);\n  ublas::vector<double> rho_h(c.Nz,0.);\n  field<double,1> fdvxdvy(boost::extents[c.Nvz][c.Nz]);\n\n  // init all computer functor for each monitoring value\n  auto compute_vperp_integral       = computer::vperp_integral<double>( f );\n  auto compute_z_vperp_integral     = computer::z_vperp_integral<double>( f );\n  auto compute_z_vz_integral        = computer::z_vz_integral<double>( f );\n  auto compute_local_kinetic_energy = computer::local_kinetic_energy<double>( f );\n  auto compute_electric_energy      = computer::space_energy( f.step.dz );\n  auto compute_magnetic_energy      = computer::space_energy( f.step.dz );\n  auto compute_cold_energy          = computer::space_energy( f.step.dz );\n  auto compute_hot_mass_energy      = computer::hot_mass_energy<double>( f );\n\n  auto printer_z_data  = factory::printer__x_data( f.range.z_min  , f.step.dz  );\n  auto printer_vz_data = factory::printer__x_data( f.range.vz_min , f.step.dvz );\n\n  electric_energy.push_back( compute_electric_energy(Ex,Ey) );\n  magnetic_energy.push_back( compute_magnetic_energy(Bx,By) );\n  cold_energy.push_back( compute_cold_energy(jcx,jcy) );\n  compute_hot_mass_energy(hf);\n  kinetic_energy.push_back( compute_hot_mass_energy.he );\n  mass.push_back( compute_hot_mass_energy.mass );\n  Bxmax.push_back( max_abs(Bx) );\n  Bymax.push_back( max_abs(By) );\n  Exmax.push_back( max_abs(Ex) );\n  Eymax.push_back( max_abs(Ey) );\n\n  monitoring::reactive_monitoring<std::vector<double>> moni(\n    c.output_dir/(\"energy_\"s + c.name + \".dat\"s) ,\n    times ,\n    {&electric_energy,&magnetic_energy,&cold_energy,&kinetic_energy,&mass,&Exmax,&Eymax,&Bxmax,&Bymax}\n  );\n\n  // end monitorring initialization\n/* ---------------------------------------------------------------- */\n  // substage initialization\n\n  //{# declaration of each substage variables #}\n  ublas::vector<std::complex<double>> {%- for (lhs,_) in schemes %} {{ lhs.jcx }}(c.Nz,0.) {{ \",\" if not loop.last else \"\" }}{% endfor %};\n  ublas::vector<std::complex<double>> {%- for (lhs,_) in schemes %} {{ lhs.jcy }}(c.Nz,0.) {{ \",\" if not loop.last else \"\" }}{% endfor %};\n  ublas::vector<std::complex<double>> {%- for (lhs,_) in schemes %} {{ lhs.Bx  }}(c.Nz,0.) {{ \",\" if not loop.last else \"\" }}{% endfor %};\n  ublas::vector<std::complex<double>> {%- for (lhs,_) in schemes %} {{ lhs.By  }}(c.Nz,0.) {{ \",\" if not loop.last else \"\" }}{% endfor %};\n  ublas::vector<std::complex<double>> {%- for (lhs,_) in schemes %} {{ lhs.Ex  }}(c.Nz,0.) {{ \",\" if not loop.last else \"\" }}{% endfor %};\n  ublas::vector<std::complex<double>> {%- for (lhs,_) in schemes %} {{ lhs.Ey  }}(c.Nz,0.) {{ \",\" if not loop.last else \"\" }}{% endfor %};\n\n  complex_field<double,3> {%- for (lhs,_) in schemes[:-1] %} {{ lhs.fh }}(boost::extents[c.Nvx][c.Nvy][c.Nvz][c.Nz]) {{ \", \" if not loop.last else \"\" }}{% endfor %};\n  field3d<double> dvf(boost::extents[c.Nvx][c.Nvy][c.Nvz][c.Nz]);\n\n  // init Fourier variables (just for first loop and first stage)\n  fft::fft( jcx.begin() , jcx.end() , {{ schemes[-1][0].jcx }}.begin() );\n  fft::fft( jcy.begin() , jcy.end() , {{ schemes[-1][0].jcy }}.begin() );\n  fft::fft(  Ex.begin() ,  Ex.end() , {{ schemes[-1][0].Ex  }}.begin() );\n  fft::fft(  Ey.begin() ,  Ey.end() , {{ schemes[-1][0].Ey  }}.begin() );\n  fft::fft(  Bx.begin() ,  Bx.end() , {{ schemes[-1][0].Bx  }}.begin() );\n  fft::fft(  By.begin() ,  By.end() , {{ schemes[-1][0].By  }}.begin() );\n\n  {% macro compute_hjfx( hf ) -%}\n    ( w_1*c_ - w_2*s_ )*{{ hf }}[k_x][k_y][k_z][i]*f.volumeV()\n  {%- endmacro %}\n  {% macro compute_hjfy( hf ) -%}\n    ( w_1*s_ + w_2*c_ )*{{ hf }}[k_x][k_y][k_z][i]*f.volumeV()\n  {%- endmacro %}\n\n  {% macro compute_velocity_vx( Ex , Ey , Bx , By ) -%}\n    -( {{ Ex }}[i]*c_ + {{ Ey }}[i]*s_ + v_z*{{ Bx }}[i]*s_ - v_z*{{ By }}[i]*c_)\n  {%- endmacro %}\n  {% macro compute_velocity_vy( Ex , Ey , Bx , By ) -%}\n    -(-{{ Ex }}[i]*s_ + {{ Ey }}[i]*c_ + v_z*{{ Bx }}[i]*c_ + v_z*{{ By }}[i]*s_)\n  {%- endmacro %}\n  {% macro compute_velocity_vz( Ex , Ey , Bx , By ) -%}\n    -(-{{ Bx }}[i]*( w_1*s_ + w_2*c_ ) + {{ By }}[i]*( w_1*c_ - w_2*s_ ))\n  {%- endmacro %}\n\n  auto next_snapshot = c.snaptimes.begin();\n\n  iteration_4d::iteration<double> iter;\n  iter.dt = c.dt0;\n  times.push_back(iter.current_time);\n  const double dt_cfl_maxwell = 2.0*std::sqrt(2.0)/c.Nz;\n  \n  while ( iter.current_time<c.Tf )\n  {\n    const double current_t = iter.current_time;\n    const double dt = iter.dt;\n    std::cout << \"\\r\" << iteration_4d::time(iter) << std::flush;\n\n    // {# write here only one stage and loop with jinja2 #}\n    {% for (lhs,rhs) in schemes %}\n    //////////////////////////////////////////////////////////////////\n    { // begin stage {{ loop.index }}\n      double c_ = std::cos(B0*( current_t + {{ lhs.dt }}*dt )) ,\n             s_ = std::sin(B0*( current_t + {{ lhs.dt }}*dt )) ;\n\n      // compute $\\int v_x {{ schemes[loop.index0-1][0].fh }}\\,\\mathrm{d}v$ and $\\int v_y {{ schemes[loop.index0-1][0].fh }}\\,\\mathrm{d}v$\n      ublas::vector<std::complex<double>> hjhx(c.Nz,0.) , hjhy(c.Nz,0.);\n      for ( auto k_x=0u ; k_x<c.Nvx ; ++k_x ) {\n        const double w_1 = k_x*f.step.dvx + f.range.vx_min;\n        for ( auto k_y=0u ; k_y<c.Nvy ; ++k_y ) {\n          const double w_2 = k_y*f.step.dvy + f.range.vy_min;\n          for ( auto k_z=0u ; k_z<c.Nvz ; ++k_z ) {\n            for ( auto i=1u ; i<c.Nz ; ++i ) {\n              hjhx[i] += {{ compute_hjfx(schemes[loop.index0-1][0].fh) }};\n              hjhy[i] += {{ compute_hjfy(schemes[loop.index0-1][0].fh) }};\n            }\n          }\n        }\n      }\n      // keep zero mean\n      hjhx[0] = 0.0;\n      hjhy[0] = 0.0;\n\n      // --> compute {{ lhs.jcx }}, {{ lhs.jcy }}, {{ lhs.Bx }}, {{ lhs.By }}, {{ lhs.Ex }}, {{ lhs.Ey }} (all spatial values)\n      for ( auto i=1u ; i<c.Nz ; ++i ) {\n        {% if not loop.last %}\n          {{ lhs.jcx }}[i] = {{ rhs.jcx }};\n          // ---\n          {{ lhs.jcy }}[i] = {{ rhs.jcy }};\n          // ---\n          {{ lhs.Bx  }}[i] = {{ rhs.Bx  }};\n          // ---\n          {{ lhs.By  }}[i] = {{ rhs.By  }};\n          // ---\n          {{ lhs.Ex  }}[i] = {{ rhs.Ex  }};\n          // ---\n          {{ lhs.Ey  }}[i] = {{ rhs.Ey  }};\n        {% else %}\n          auto {{ lhs.jcx }}_tmp = {{ rhs.jcx }};\n          // ---\n          auto {{ lhs.jcy }}_tmp = {{ rhs.jcy }};\n          // ---\n          auto {{ lhs.Bx  }}_tmp = {{ rhs.Bx  }};\n          // ---\n          auto {{ lhs.By  }}_tmp = {{ rhs.By  }};\n          // ---\n          auto {{ lhs.Ex  }}_tmp = {{ rhs.Ex  }};\n          // ---\n          auto {{ lhs.Ey  }}_tmp = {{ rhs.Ey  }};\n\n          {{ lhs.jcx }}[i] = {{ lhs.jcx }}_tmp;\n          {{ lhs.jcy }}[i] = {{ lhs.jcy }}_tmp;\n          {{ lhs.Bx  }}[i] = {{ lhs.Bx  }}_tmp;\n          {{ lhs.By  }}[i] = {{ lhs.By  }}_tmp;\n          {{ lhs.Ex  }}[i] = {{ lhs.Ex  }}_tmp;\n          {{ lhs.Ey  }}[i] = {{ lhs.Ey  }}_tmp;\n        {% endif %}\n      }\n      // keep zero mean\n      {{ lhs.jcx }}[0] = 0.0;\n      {{ lhs.jcy }}[0] = 0.0;\n      {{ lhs.Bx  }}[0] = 0.0;\n      {{ lhs.By  }}[0] = 0.0;\n      {{ lhs.Ex  }}[0] = 0.0;\n      {{ lhs.Ey  }}[0] = 0.0;\n\n      // --> compute {{ lhs.fh }}\n      // iFFT of hf\n      for ( auto k_x=0u ; k_x<c.Nvx ; ++k_x ) {\n        for ( auto k_y=0u ; k_y<c.Nvy ; ++k_y ) {\n          for ( auto k_z=0u ; k_z<c.Nvz ; ++k_z ) {\n            fft::ifft( {{ schemes[loop.index0-1][0].fh }}[k_x][k_y][k_z].begin() ,\n                       {{ schemes[loop.index0-1][0].fh }}[k_x][k_y][k_z].end()   ,\n                       f[k_x][k_y][k_z].begin()\n                    );\n          }\n        }\n      }\n      // iFFT of hEx, hEy, hBx and hBy\n      fft::ifft({{ schemes[loop.index0-1][0].Ex }}.begin(),{{ schemes[loop.index0-1][0].Ex }}.end(),Ex.begin());\n      fft::ifft({{ schemes[loop.index0-1][0].Ey }}.begin(),{{ schemes[loop.index0-1][0].Ey }}.end(),Ey.begin());\n      fft::ifft({{ schemes[loop.index0-1][0].Bx }}.begin(),{{ schemes[loop.index0-1][0].Bx }}.end(),Bx.begin());\n      fft::ifft({{ schemes[loop.index0-1][0].By }}.begin(),{{ schemes[loop.index0-1][0].By }}.end(),By.begin());\n\n      // compute approximation of (E×vB)∂ᵥf\n      for ( auto k_x=0u ; k_x<c.Nvx ; ++k_x ) {\n        for ( auto k_y=0u ; k_y<c.Nvy ; ++k_y ) {\n          for ( auto k_z=0u ; k_z<c.Nvz ; ++k_z ) {\n            for ( auto i=0u ; i<c.Nz ; ++i ) {\n              const double w_1 = k_x*f.step.dvx + f.range.vx_min;\n              const double w_2 = k_y*f.step.dvy + f.range.vy_min;\n              const double v_z = k_z*f.step.dvz + f.range.vz_min;\n\n              const double velocity_vx = {{ compute_velocity_vx('Ex','Ey','Bx','By') }};\n              const double velocity_vy = {{ compute_velocity_vy('Ex','Ey','Bx','By') }};\n              const double velocity_vz = {{ compute_velocity_vz('Ex','Ey','Bx','By') }};\n\n              dvf[k_x][k_y][k_z][i] = + weno3d::d_vx(velocity_vx,f,k_x,k_y,k_z,i)\n                                      + weno3d::d_vy(velocity_vy,f,k_x,k_y,k_z,i)\n                                      + weno3d::d_vz(velocity_vz,f,k_x,k_y,k_z,i);\n            }\n          }\n        }\n      }\n\n      // update hf\n      for ( auto k_x=0u ; k_x<c.Nvx ; ++k_x ) {\n        for ( auto k_y=0u ; k_y<c.Nvy ; ++k_y ) {\n          for ( auto k_z=0u ; k_z<c.Nvz ; ++k_z ) {\n            const double v_z = k_z*f.step.dvz + f.range.vz_min;\n            fft::spectrum_ hfvxvyvz(c.Nz);\n            hfvxvyvz.fft(dvf[k_x][k_y][k_z].begin());\n            for ( auto i=0u ; i<c.Nz ; ++i ) {\n              {{ lhs.fh }}[k_x][k_y][k_z][i] = {{ rhs.fh }};\n            }\n          }\n        }\n      }\n\n    } // end stage {{ loop.index }}\n    //////////////////////////////////////////////////////////////////\n    {% endfor %}\n\n    fft::ifft(hEx.begin(),hEx.end(),Ex.begin());\n    fft::ifft(hEy.begin(),hEy.end(),Ey.begin());\n    fft::ifft(hBx.begin(),hBx.end(),Bx.begin());\n    fft::ifft(hBy.begin(),hBy.end(),By.begin());\n    fft::ifft(hjcx.begin(),hjcx.end(),jcx.begin());\n    fft::ifft(hjcy.begin(),hjcy.end(),jcy.begin());\n\n    electric_energy.push_back(compute_electric_energy(Ex,Ey));\n    magnetic_energy.push_back(compute_magnetic_energy(Bx,By));\n    cold_energy.push_back(compute_cold_energy(jcx,jcy));\n    compute_hot_mass_energy(hf);\n    kinetic_energy.push_back(compute_hot_mass_energy.he);\n    mass.push_back(compute_hot_mass_energy.mass);\n    Exmax.push_back( max_abs(Ex) );\n    Eymax.push_back( max_abs(Ey) );\n    Bxmax.push_back( max_abs(Bx) );\n    Bymax.push_back( max_abs(By) );\n\n    ++iter.iter;\n    iter.current_time += iter.dt;\n    times.push_back(current_t);\n    moni.push();\n\n    if ( iter.iter % 1000 == 0 ) {\n      std::stringstream filename;\n      \n      filename.str(\"\");\n      compute_vperp_integral( hf );\n      filename << \"fdvxdvy_\" << c.name << \"_\" << iter.iter << \".dat\";\n      compute_vperp_integral.fdvxdvy.write( c.output_dir / filename.str() );\n      \n      filename.str(\"\");\n      compute_z_vz_integral( hf );\n      filename << \"fdzdvz_\" << c.name << \"_\" << iter.iter << \".dat\";\n      compute_z_vz_integral.fdzdvz.write( c.output_dir / filename.str() );\n      \n      filename.str(\"\");\n      compute_z_vperp_integral( hf );\n      filename << \"fdvxdvydz_\" << c.name << \"_\" << iter.iter << \".dat\";\n      c << monitoring::make_data( filename.str() , compute_z_vperp_integral.fdvxdvydz , printer_vz_data );\n    } // end monitoring %1000\n\n  } // end time loop\n  std::cout << \"\\r\" << iteration_4d::time(iter) << std::endl;\n\n  auto writer_t_y = [&,count=0] (auto const& y) mutable {\n    std::stringstream ss; ss<<times[count++]<<\" \"<<y;\n    return ss.str();\n  };\n\n  // this data are already in energy_XXX.dat\n  c << monitoring::make_data( \"ee\"s + c.name + \".dat\"s , electric_energy , writer_t_y );\n  c << monitoring::make_data( \"eb\"s + c.name + \".dat\"s , magnetic_energy , writer_t_y );\n  c << monitoring::make_data( \"ec\"s + c.name + \".dat\"s , cold_energy     , writer_t_y );\n  c << monitoring::make_data( \"ek\"s + c.name + \".dat\"s , kinetic_energy  , writer_t_y );\n  c << monitoring::make_data( \"m\"s  + c.name + \".dat\"s , mass            , writer_t_y );\n\n  {\n    std::stringstream filename;\n    \n    filename.str(\"\");\n    compute_vperp_integral( hf );\n    filename << \"fdvxdvy_\" << c.name << \"_Tf.dat\";\n    compute_vperp_integral.fdvxdvy.write( c.output_dir / filename.str() );\n    \n    filename.str(\"\");\n    compute_z_vz_integral( hf );\n    filename << \"fdzdvz_\" << c.name << \"_Tf.dat\";\n    compute_z_vz_integral.fdzdvz.write( c.output_dir / filename.str() );\n    \n    filename.str(\"\");\n    compute_z_vperp_integral( hf );\n    filename << \"fdvxdvydz_\" << c.name << \"_Tf.dat\";\n    c << monitoring::make_data( filename.str() , compute_z_vperp_integral.fdvxdvydz , printer_vz_data );\n  }\n\nreturn 0;\n}\n", "meta": {"hexsha": "026be62ff9aabb9c2ce1a2247606316f4f5430c9", "size": 17094, "ext": "cc", "lang": "C++", "max_stars_repo_path": "script/hybrid_stalfos.jinja.cc", "max_stars_repo_name": "kivvix/vlasovpp", "max_stars_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "script/hybrid_stalfos.jinja.cc", "max_issues_repo_name": "kivvix/vlasovpp", "max_issues_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "script/hybrid_stalfos.jinja.cc", "max_forks_repo_name": "kivvix/vlasovpp", "max_forks_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6033254157, "max_line_length": 165, "alphanum_fraction": 0.5473850474, "num_tokens": 5496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.4239370812020368}}
{"text": "#include \"solarsystem.h\"\n#include \"planet.h\"\n#include <iostream>\n#include <armadillo>\n#include <stdio.h>\n#include <iomanip>\nusing namespace arma;\nusing namespace std;\n\n\nsolarsystem::solarsystem()\n{\n}\nvoid solarsystem::add(planet n){\n     number_planets++;\n     all_planets.push_back(n);\n }\nvoid solarsystem::print_position(ofstream &output, ofstream &output2, vector<planet> vec){\n    print_position(output, output2, vec, 3);\n}\n\nvoid solarsystem::print_position(ofstream &output, ofstream &output2, vector<planet> vec, int n){\n    if(n>3 || n<=0) n=3;\n    for(int i=0; i<vec.size(); i++){\n        planet &this = vec[i];\n        std::cout << std::scientific;\n        for(int j=0; j<n;j++){\n        std::cout << this.position[j] << \"   \";\n        output << std::scientific << this.position[j] << \"   \";\n        output2 << std::scientific << this.velocity[j] << \"   \";\n        }\n        std::cout << \"         \";\n        output  << \"         \";\n        output2  << \"         \";\n       }\n    std::cout << std::endl;\n    output << endl;\n    output2 << endl;\n}\n\nvoid solarsystem::insert_data(vector<planet> vec, mat &ma){\n    for(int i=0; i<vec.size(); i++){\n        planet &this = vec[i];\n        ma(i,6)=this.mass;\n\n        for(int k=0; k<3;k++){\n            ma(i,k)=this.position[k];\n            ma(i,k+3)=this.velocity[k];\n        }\n    }\n}\n\nvoid solarsystem::synctroniz(vector<planet> vec, mat &ma){\n    int n = vec.size();\n\n    for(int j=0; j<n;j++){\n        planet &this = vec[j];\n    for (int i = 0; i < 3; ++i){\n       this.position[i] =  ma(j,i);\n       this.velocity[i] = ma(j,i+3);\n}\n}\n\n}\n\nvoid solarsystem::solverRK4(vector<planet> vec, double h, double tmax){\n\n    mat y_i(number_planets,7);\n    mat y_i_temp(number_planets,7);\n    mat k1(number_planets,7);\n    mat k2(number_planets,7);\n    mat k3(number_planets,7);\n    mat k4(number_planets,7);\n\n    insert_data(vec , y_i);\n    double t=0;\n\n    //for print file_________\n    char *filename = new char[1000];\n    char *filename2 = new char[1000];\n        sprintf(filename, \"Planet_position_RK4_%f.dat\", h);\n        sprintf(filename2, \"Planet_velocity_RK4_%f.dat\", h);\n\n        ofstream output (filename);\n        ofstream output2 (filename2);\n\n        if (output.is_open()){\n            output.precision(5);\n            output2.precision(5);\n    while(t<tmax){\n\n        derivative(y_i, k1, number_planets);\n\n        sum_matrix(y_i_temp, 1, y_i, 0.5*h, k1, number_planets);\n        derivative(y_i_temp, k2, number_planets);\n\n        sum_matrix( y_i_temp, 1,  y_i, 0.5*h,  k2, number_planets);\n\n        derivative( y_i_temp,  k3, number_planets);\n\n        sum_matrix( y_i_temp, 1,  y_i, h,  k3, number_planets);\n\n        derivative( y_i_temp,  k4, number_planets);\n\n        for(int j=1; j<number_planets; j++){\n\n             for(int i=0; i<6; i++){\n                 y_i(j,i) = y_i(j,i) + h*(k1(j,i) + 2*k2(j,i) + 2*k3(j,i) + k4(j,i))/6;\n             }\n\n             //Syncroniz position and velocity with the classes\n             planet &this = vec[j];\n             for(int i=0; i<3; i++){\n             this.position[i] = y_i(j,i);\n             this.velocity[i] = y_i(j,i+3);\n             }\n\n        }\n\nprint_position(output, output2, vec, 3);\n\nt+=h;\n\n}\n\noutput.close();\n}\n}\n\nvoid solarsystem::solverVERLET(vector<planet> vec, double h, double tmax){\n\n    mat y_i(number_planets,7);\n    mat r_i_dt(number_planets,7);\n    mat a_dt(number_planets,7);\n    mat v_dt(number_planets,7);\n    mat v_dt_2(number_planets,7);\n\n    insert_data(vec , y_i);\n\n    double t=0,zz =1;\n\n    //print file___________________\n    char *filename = new char[1000];\n    char *filename2 = new char[1000];\n        sprintf(filename, \"Planet_position_Verlet_%f.dat\", h);\n        sprintf(filename2, \"Planet_velocity_Verlet_%f.dat\", h);\n\n            ofstream output (filename);\n            ofstream output2 (filename2);\n\n            if (output.is_open()){\n            output.precision(5);\n            output2.precision(5);\n    // end for print\n\n\n    while(t<tmax){\n\n        derivative(y_i, a_dt, number_planets);\n\n        for(int j=0; j<number_planets; j++){\n\n             for(int i=0; i<3; i++){\n                 y_i(j,i) = y_i(j,i) + h*y_i(j,i+3) + 0.5*h*h*a_dt(j,i+3);\n                 v_dt_2(j,i+3) = y_i(j,i+3) + 0.5*h*a_dt(j,i+3);\n             }\n        }\n\n        derivative(y_i, a_dt, number_planets);\n\n        for(int j=0; j<number_planets; j++){\n\n             for(int i=3; i<6; i++){\n\n                 y_i(j,i) = v_dt_2(j,i) + 0.5*h*a_dt(j,i);\n\n             }\n\n             planet &this = vec[j];\n             for(int i=0; i<3; i++){\n             this.position[i] = y_i(j,i);\n             this.velocity[i] = y_i(j,i+3);\n             }\n        }\nprint_position(output, output2, vec,3);\n\nt+=h;\n\n}\noutput.close();\n}\n\n\n}\nvoid solarsystem::sum_matrix(mat &result, double coeff_one, mat &first,double coeff_two, mat &second, int n){\n    for(int j=0; j<n; j++){\n         for(int i=0; i<6; i++){\n            result(j,i) = coeff_one*first(j,i) + coeff_two*second(j,i);\n         }\n         result(j,6) = first(j,6);\n\n    }\n}\nvoid solarsystem::printmat(mat &ma, int n){\n    cout << endl;\n    for(int i=0; i<7; i++){\n\n        for(int k=0; k<n;k++){\n            cout <<  ma(k,i)<<\" \" ;\n        } cout << endl;}\n}\ndouble solarsystem::force(double x, double y, double z, double Mothers){\n    double G=  4*M_PI*M_PI;\n    double force=0;\n    double distance=0;\n\n    distance = x*x + y*y + z*z;\n\n    force = G*Mothers/pow(distance, 1.5);\n\n    return force;\n}\nvoid solarsystem::derivative(mat &dat, mat &de, int n){\n\n    double accelleration_x=0,accelleration_y=0,accelleration_z=0, mod_force;\n    for(int i=0; i<n; i++){\n\n        accelleration_x=0,accelleration_y=0,accelleration_z=0;\n        for(int j=0; j<n; j++){\n            if(i!=j){\n\nmod_force = force(dat(j,0)-dat(i,0),dat(j,1)-dat(i,1) ,dat(j,2)-dat(i,2),  dat(j,6));\n\n\naccelleration_x += mod_force*(dat(j,0)-dat(i,0));\naccelleration_y += mod_force*(dat(j,1)-dat(i,1));\naccelleration_z += mod_force*(dat(j,2)-dat(i,2));\n}\n}\n        de(i,3) = accelleration_x;\n        de(i,4) = accelleration_y;\n        de(i,5) = accelleration_z;\n\n    }\n\n\n    for(int i=0; i<n; i++){\n        de(i,0) = dat(i,3); //velx\n        de(i,1) = dat(i,4); //vely\n        de(i,2) = dat(i,5); //velz\n    }\n}\n", "meta": {"hexsha": "28407856449be5dd567e42f14c615889ca474f55", "size": 6256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Programs/OOExamples/solarsystem.cpp", "max_stars_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_stars_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 87.0, "max_stars_repo_stars_event_min_datetime": "2015-01-21T08:29:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T07:11:53.000Z", "max_issues_repo_path": "doc/Programs/OOExamples/solarsystem.cpp", "max_issues_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_issues_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-01-18T10:43:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-08T13:15:42.000Z", "max_forks_repo_path": "doc/Programs/OOExamples/solarsystem.cpp", "max_forks_repo_name": "GabrielSCabrera/ComputationalPhysics2", "max_forks_repo_head_hexsha": "a840b97b651085090f99bf6a11abab57100c2e85", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2015-02-09T10:02:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T10:44:14.000Z", "avg_line_length": 24.7272727273, "max_line_length": 109, "alphanum_fraction": 0.5439578005, "num_tokens": 1914, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.42388702534773326}}
{"text": "/*\n * StokesM2L.cpp\n *\n *  Created on: Oct 12, 2016\n *      Author: wyan\n */\n\n#include \"SVD_pvfmm.hpp\"\n\n#include <Eigen/Dense>\n\n#include <iomanip>\n#include <iostream>\n\n#define DIRECTLAYER 2\n\nnamespace Stokes1D3D {\n\n/**\n * \\brief Returns the coordinates of points on the surface of a cube.\n * \\param[in] p Number of points on an edge of the cube is (n+1)\n * \\param[in] c Coordinates to the centre of the cube (3D array).\n * \\param[in] alpha Scaling factor for the size of the cube.\n * \\param[in] depth Depth of the cube in the octree.\n * \\return Vector with coordinates of points on the surface of the cube in the\n * format [x0 y0 z0 x1 y1 z1 .... ].\n */\ntemplate <class Real_t>\nstd::vector<Real_t> surface(int p, Real_t *c, Real_t alpha, int depth) {\n    size_t n_ = (6 * (p - 1) * (p - 1) + 2); // Total number of points.\n\n    std::vector<Real_t> coord(n_ * 3);\n    coord[0] = coord[1] = coord[2] = -1.0;\n    size_t cnt = 1;\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = -1.0;\n            coord[cnt * 3 + 1] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = (2.0 * j - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * i - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = -1.0;\n            coord[cnt * 3 + 2] = (2.0 * (j + 1) - p + 1) / (p - 1);\n            cnt++;\n        }\n    for (int i = 0; i < p - 1; i++)\n        for (int j = 0; j < p - 1; j++) {\n            coord[cnt * 3] = (2.0 * (i + 1) - p + 1) / (p - 1);\n            coord[cnt * 3 + 1] = (2.0 * j - p + 1) / (p - 1);\n            coord[cnt * 3 + 2] = -1.0;\n            cnt++;\n        }\n    for (size_t i = 0; i < (n_ / 2) * 3; i++)\n        coord[cnt * 3 + i] = -coord[i];\n\n    Real_t r = 0.5 * pow(0.5, depth);\n    Real_t b = alpha * r;\n    for (size_t i = 0; i < n_; i++) {\n        coord[i * 3 + 0] = (coord[i * 3 + 0] + 1.0) * b + c[0];\n        coord[i * 3 + 1] = (coord[i * 3 + 1] + 1.0) * b + c[1];\n        coord[i * 3 + 2] = (coord[i * 3 + 2] + 1.0) * b + c[2];\n    }\n    return coord;\n}\n\ninline void Gkernel(const Eigen::Vector3d &target,\n                    const Eigen::Vector3d &source, Eigen::Matrix3d &answer) {\n    auto rst = target - source;\n    double rnorm = rst.norm();\n    if (rnorm < 1e-13) {\n        answer.setZero();\n        return;\n    }\n\n    auto part2 = rst * rst.transpose() / (rnorm * rnorm * rnorm);\n    auto part1 = Eigen::Matrix3d::Identity() / rnorm;\n    answer = part1 + part2;\n}\n\n// calculate the M2L matrix of images from 2 to 1000\nint main(int argc, char **argv) {\n    Eigen::initParallel();\n    Eigen::setNbThreads(1);\n\n    const int pEquiv = atoi(argv[1]); // (8-1)^2*6 + 2 points\n    const int pCheck = atoi(argv[1]);\n    const double scaleEquiv = 1.05;\n    const double scaleCheck = 2.95;\n    const double pCenterEquiv[3] = {\n        -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2};\n    const double pCenterCheck[3] = {\n        -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2};\n    auto pointMEquiv = surface(\n        pEquiv, (double *)&(pCenterEquiv[0]), scaleEquiv,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointMCheck = surface(\n        pCheck, (double *)&(pCenterCheck[0]), scaleCheck,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    auto pointLEquiv = surface(\n        pEquiv, (double *)&(pCenterCheck[0]), scaleCheck,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n    auto pointLCheck = surface(\n        pCheck, (double *)&(pCenterEquiv[0]), scaleEquiv,\n        0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n    //\tfor (int i = 0; i < pointLEquiv.size() / 3; i++) {\n    //\t\tstd::cout << pointLEquiv[3 * i] << \" \" << pointLEquiv[3 * i + 1]\n    //<< \" \" << pointLEquiv[3 * i + 2] << \" \"\n    //\t\t\t\t<< std::endl;\n    //\t}\n    //\n    //\tfor (int i = 0; i < pointLCheck.size() / 3; i++) {\n    //\t\tstd::cout << pointLCheck[3 * i] << \" \" << pointLCheck[3 * i + 1]\n    //<< \" \" << pointLCheck[3 * i + 2] << \" \"\n    //\t\t\t\t<< std::endl;\n    //\t}\n\n    const int imageN = 500000; // images to sum\n    // calculate the operator M2L with least square\n    const int equivN = pointMEquiv.size() / 3;\n    const int checkN = pointLCheck.size() / 3;\n    Eigen::MatrixXd A(3 * checkN, 3 * equivN);\n#pragma omp parallel for\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Matrix3d G = Eigen::Matrix3d::Zero();\n        Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1],\n                               pointLCheck[3 * k + 2]);\n        for (int l = 0; l < equivN; l++) {\n            const Eigen::Vector3d Lpoint(pointLEquiv[3 * l],\n                                         pointLEquiv[3 * l + 1],\n                                         pointLEquiv[3 * l + 2]);\n            Gkernel(Cpoint, Lpoint, G);\n            A.block<3, 3>(3 * k, 3 * l) = G;\n        }\n    }\n    Eigen::MatrixXd ApinvU(A.cols(), A.rows());\n    Eigen::MatrixXd ApinvVT(A.cols(), A.rows());\n    pinv(A, ApinvU, ApinvVT);\n\n    Eigen::MatrixXd M2L(3 * equivN, 3 * equivN);\n#pragma omp parallel for\n    for (int i = 0; i < equivN; i++) {\n        const Eigen::Vector3d Mpoint(pointMEquiv[3 * i], pointMEquiv[3 * i + 1],\n                                     pointMEquiv[3 * i + 2]);\n        Eigen::MatrixXd f(3 * checkN, 3);\n        //\t\tstd::cout<<\"debug:\"<<Mpoint<<std::endl;\n        for (int k = 0; k < checkN; k++) {\n            Eigen::Matrix3d temp = Eigen::Matrix3d::Zero();\n            Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1],\n                                   pointLCheck[3 * k + 2]);\n            //\t\t\tstd::cout<<\"debug:\"<<k<<std::endl;\n            // sum the images\n            for (int per = DIRECTLAYER + 1; per < imageN; per++) {\n                Eigen::Vector3d perVec(1.0 * per, 0, 0);\n                Eigen::Matrix3d G1 = Eigen::Matrix3d::Zero();\n                Eigen::Matrix3d G2 = Eigen::Matrix3d::Zero();\n                Gkernel(Cpoint, Mpoint + perVec, G1);\n                Gkernel(Cpoint, Mpoint - perVec, G2);\n                temp = temp + (G1 + G2);\n            }\n            //\t\t\tstd::cout << temp << std::endl;\n            f.block<3, 3>(3 * k, 0) = temp;\n        }\n        M2L.block(0, 3 * i, 3 * equivN, 3) =\n            (ApinvU.transpose() * (ApinvVT.transpose() * f));\n    }\n\n    // dump M2L\n    for (int i = 0; i < 3 * equivN; i++) {\n        for (int j = 0; j < 3 * equivN; j++) {\n            std::cout << i << \" \" << j << \" \" << std::scientific\n                      << std::setprecision(18) << M2L(i, j) << std::endl;\n        }\n    }\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>\n        forcePoint(3);\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>\n        forceValue(3);\n    forcePoint[0] = Eigen::Vector3d(0.5, 0.55, 0.2);\n    forceValue[0] = Eigen::Vector3d(-0.2, 0, 0);\n    forcePoint[1] = Eigen::Vector3d(0.5, 0.5, 0.5);\n    forceValue[1] = Eigen::Vector3d(1, 0, 0);\n    forcePoint[2] = Eigen::Vector3d(0.7, 0.7, 0.7);\n    forceValue[2] = Eigen::Vector3d(-0.8, 0, 0);\n\n    // solve M\n    A.resize(3 * checkN, 3 * equivN);\n    ApinvU.resize(A.cols(), A.rows());\n    ApinvVT.resize(A.cols(), A.rows());\n    Eigen::VectorXd f(3 * checkN);\n#pragma omp parallel for\n    for (int k = 0; k < checkN; k++) {\n        Eigen::Vector3d temp = Eigen::Vector3d::Zero();\n        Eigen::Matrix3d G = Eigen::Matrix3d::Zero();\n        Eigen::Vector3d Cpoint(pointMCheck[3 * k], pointMCheck[3 * k + 1],\n                               pointMCheck[3 * k + 2]);\n        for (int p = 0; p < 3; p++) {\n            Gkernel(Cpoint, forcePoint[p], G);\n            temp = temp + G * (forceValue[p]);\n        }\n        f.block<3, 1>(3 * k, 0) = temp;\n        for (int l = 0; l < equivN; l++) {\n            Eigen::Vector3d Mpoint(pointMEquiv[3 * l], pointMEquiv[3 * l + 1],\n                                   pointMEquiv[3 * l + 2]);\n            Gkernel(Cpoint, Mpoint, G);\n            A.block<3, 3>(3 * k, 3 * l) = G;\n        }\n    }\n    pinv(A, ApinvU, ApinvVT);\n    Eigen::VectorXd Msource = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n    // impose zero sum\n    double fx = 0, fy = 0, fz = 0;\n    for (int i = 0; i < equivN; i++) {\n        fx += Msource[3 * i];\n        fy += Msource[3 * i + 1];\n        fz += Msource[3 * i + 2];\n    }\n    std::cout << \"fx svd before correction: \" << fx << std::endl;\n    std::cout << \"fy svd before correction: \" << fy << std::endl;\n    std::cout << \"fz svd before correction: \" << fz << std::endl;\n\n    fx /= equivN;\n    fy /= equivN;\n    fz /= equivN;\n    for (int i = 0; i < equivN; i++) {\n        Msource[3 * i] -= fx;\n        Msource[3 * i + 1] -= fy;\n        Msource[3 * i + 2] -= fz;\n    }\n\n    std::cout << \"Msource: \" << Msource << std::endl;\n\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>\n        forcePointExt(0);\n    std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>>\n        forceValueExt(0);\n    for (size_t p = 0; p < forcePoint.size(); p++) {\n        for (int k = -DIRECTLAYER; k < DIRECTLAYER + 1; k++) {\n            forcePointExt.push_back(Eigen::Vector3d(k, 0, 0) + forcePoint[p]);\n            forceValueExt.push_back(forceValue[p]);\n        }\n    }\n\n    Eigen::VectorXd M2Lsource = M2L * (Msource);\n    Eigen::Vector3d samplePoint(0.6, 0.5, 0.5);\n    Eigen::Vector3d Usample(0, 0, 0);\n    Eigen::Vector3d UsampleSP(0, 0, 0);\n    Eigen::Matrix3d G;\n    for (size_t p = 0; p < forcePointExt.size(); p++) {\n        Gkernel(samplePoint, forcePointExt[p], G);\n        Usample += G * (forceValueExt[p]);\n    }\n    std::cout << \"Usample Direct:\" << Usample << std::endl;\n\n    for (int p = 0; p < equivN; p++) {\n        Eigen::Vector3d Lpoint(pointLEquiv[3 * p], pointLEquiv[3 * p + 1],\n                               pointLEquiv[3 * p + 2]);\n        Eigen::Vector3d Fpoint(M2Lsource[3 * p], M2Lsource[3 * p + 1],\n                               M2Lsource[3 * p + 2]);\n        Gkernel(samplePoint, Lpoint, G);\n        UsampleSP = UsampleSP + G * (Fpoint);\n    }\n\n    std::cout << \"Usample M2L:\" << UsampleSP << std::endl;\n    std::cout << \"Usample M2L total:\" << UsampleSP + Usample << std::endl;\n\n    Eigen::Vector3d UsampleN(0, 0, 0);\n    for (size_t p = 0; p < forcePoint.size(); p++) {\n        Eigen::Matrix3d G1 = Eigen::Matrix3d::Zero();\n        Eigen::Matrix3d G2 = Eigen::Matrix3d::Zero();\n        for (int per = DIRECTLAYER + 1; per < imageN; per++) {\n            Eigen::Vector3d perVec(1.0 * per, 0, 0);\n            Gkernel(samplePoint, forcePoint[p] + perVec, G1);\n            Gkernel(samplePoint, forcePoint[p] - perVec, G2);\n            UsampleN += (G1 + G2) * (forceValue[p]);\n        }\n        Gkernel(samplePoint, forcePoint[p], G2);\n    }\n\n    std::cout << \"Usample N Images:\" << UsampleN + Usample << std::endl;\n    std::cout << \"error\" << UsampleSP - UsampleN << std::endl;\n\n    return 0;\n}\n\n} // namespace Stokes1D3D\n\n#undef DIRECTLAYER\n", "meta": {"hexsha": "d2107811e021d945fc2b6e761f15de44ef6513c5", "size": 11104, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "M2LStokes/src/Stokes1D3D.cpp", "max_stars_repo_name": "blackwer/PeriodicFMM", "max_stars_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-06-14T02:07:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-18T04:41:34.000Z", "max_issues_repo_path": "M2LStokes/src/Stokes1D3D.cpp", "max_issues_repo_name": "blackwer/PeriodicFMM", "max_issues_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "M2LStokes/src/Stokes1D3D.cpp", "max_forks_repo_name": "blackwer/PeriodicFMM", "max_forks_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T16:30:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T20:26:36.000Z", "avg_line_length": 37.768707483, "max_line_length": 80, "alphanum_fraction": 0.5018912104, "num_tokens": 3855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4236039578479139}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\n\nusing int_type = boost::multiprecision::cpp_int;\n\n#include <iostream>\n#include <vector>\n\n#include \"structured.h\"\n#include \"config.h\"\n#include \"gadget.h\"\n#include \"optimizer.h\"\n#include \"orbit.h\"\n#include \"rational.h\"\n\nint main() {\n  std::cout << \"Analyzing orbits of the symmetry group...\" << std::endl;\n  OrbitInfo orbitInfo;\n\n  std::cout << \"Finding all structured sets\" << std::endl;\n  std::vector<bool> structuredSets = getAllStructuredSets();\n  long long i = 0;\n  for (long long ind = 0; ind < n_nodes; ++ind)\n    i += structuredSets[ind];\n  std::cout << \"Found \" << i << \" nodes to consider\" << std::endl;\n\n  EdgeOrbitInfo edgeOrbitInfo(orbitInfo, structuredSets);\n  Optimizer<int_type> optimizer;\n  Evaluator<int_type> evaluator(orbitInfo, edgeOrbitInfo);\n\n  std::cout << \"Optimizing gadget...\" << std::endl;\n\n  auto gadget = optimizer.gadgetSearch(orbitInfo, edgeOrbitInfo);\n\n  std::cout << \"Finished optimizing gadget\" << std::endl;\n  \n  std::cout << gadget;\n\n  auto randomCost = evaluator.relaxedRandomCost(gadget);\n \n  int_type totalWeight = 0;\n  for (auto edgeOrbit : edgeOrbitInfo.edgeOrbits)\n    totalWeight += edgeOrbit.size() * gadget.getWeight(edgeOrbit[0]);\n  auto dictCost = Rational<int_type>(totalWeight, dimension);\n\n  auto inapproximabilityFactor = randomCost / dictCost;\n  \n  std::cout << \"The found gadget has inapproximability factor \"\n            << inapproximabilityFactor.a << \"/\" << inapproximabilityFactor.b\n            << std::endl;\n}\n", "meta": {"hexsha": "4b4a78e665a27d14dfbaf610fb40f24087bf46cb", "size": 1512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "bjorn-martinsson/MaxCutInapproximability", "max_stars_repo_head_hexsha": "a907289e3a491cd52bddf511e4a14be20904095b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "bjorn-martinsson/MaxCutInapproximability", "max_issues_repo_head_hexsha": "a907289e3a491cd52bddf511e4a14be20904095b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "bjorn-martinsson/MaxCutInapproximability", "max_forks_repo_head_hexsha": "a907289e3a491cd52bddf511e4a14be20904095b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6470588235, "max_line_length": 76, "alphanum_fraction": 0.6937830688, "num_tokens": 398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324983301568, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.4235306652307904}}
{"text": "// Petter Strandmark 2012.\n\n#include <cstdio>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n\n#include <Eigen/Dense>\n\n#include <spii/spii.h>\n#include <spii/solver.h>\n\nnamespace spii {\n\nvoid LBFGSSolver::solve(const Function& function,\n                        SolverResults* results) const\n{\n\tdouble global_start_time = wall_time();\n\n\t// Dimension of problem.\n\tsize_t n = function.get_number_of_scalars();\n\n\tif (n == 0) {\n\t\tresults->exit_condition = SolverResults::FUNCTION_TOLERANCE;\n\t\treturn;\n\t}\n\n\t// Current point, gradient and Hessian.\n\tdouble fval   = std::numeric_limits<double>::quiet_NaN();\n\tdouble fprev  = std::numeric_limits<double>::quiet_NaN();\n\tdouble normg0 = std::numeric_limits<double>::quiet_NaN();\n\tdouble normg  = std::numeric_limits<double>::quiet_NaN();\n\tdouble normdx = std::numeric_limits<double>::quiet_NaN();\n\n\tEigen::VectorXd x, g;\n\n\t// Copy the user state to the current point.\n\tfunction.copy_user_to_global(&x);\n\tEigen::VectorXd x2(n);\n\n\t// L-BFGS history.\n\tstd::vector<Eigen::VectorXd>  s_data(this->lbfgs_history_size),\n\t                              y_data(this->lbfgs_history_size);\n\tstd::vector<Eigen::VectorXd*> s(this->lbfgs_history_size),\n\t                              y(this->lbfgs_history_size);\n\tfor (int h = 0; h < this->lbfgs_history_size; ++h) {\n\t\ts_data[h].resize(function.get_number_of_scalars());\n\t\ts_data[h].setZero();\n\t\ty_data[h].resize(function.get_number_of_scalars());\n\t\ty_data[h].setZero();\n\t\ts[h] = &s_data[h];\n\t\ty[h] = &y_data[h];\n\t}\n\n\tEigen::VectorXd rho(this->lbfgs_history_size);\n\trho.setZero();\n\n\tEigen::VectorXd alpha(this->lbfgs_history_size);\n\talpha.setZero();\n\tEigen::VectorXd q(n);\n\tEigen::VectorXd r(n);\n\n\t// Needed from the previous iteration.\n\tEigen::VectorXd x_prev(n), s_tmp(n), y_tmp(n);\n\n\tCheckExitConditionsCache exit_condition_cache;\n\n\t//\n\t// START MAIN ITERATION\n\t//\n\tresults->startup_time   += wall_time() - global_start_time;\n\tresults->exit_condition = SolverResults::INTERNAL_ERROR;\n\tint iter = 0;\n\tbool last_iteration_successful = true;\n\tint number_of_line_search_failures = 0;\n\tint number_of_restarts = 0;\n\twhile (true) {\n\n\t\t//\n\t\t// Evaluate function and derivatives.\n\t\t//\n\t\tdouble start_time = wall_time();\n\t\t// y[0] should contain the difference between the gradient\n\t\t// in this iteration and the gradient from the previous.\n\t\t// Therefore, update y before and after evaluating the\n\t\t// function.\n\t\tif (iter > 0) {\n\t\t\ty_tmp = -g;\n\t\t}\n\t\tfval = function.evaluate(x, &g);\n\n\t\tnormg = std::max(g.maxCoeff(), -g.minCoeff());\n\t\tif (iter == 0) {\n\t\t\tnormg0 = normg;\n\t\t}\n\t\tresults->function_evaluation_time += wall_time() - start_time;\n\n\t\t//\n\t\t// Update history\n\t\t//\n\t\tstart_time = wall_time();\n\n\t\tif (iter > 0 && last_iteration_successful) {\n\t\t\ts_tmp = x - x_prev;\n\t\t\ty_tmp += g;\n\n\t\t\tdouble sTy = s_tmp.dot(y_tmp);\n\t\t\tif (sTy > 1e-16) {\n\t\t\t\t// Shift all pointers one step back, discarding the oldest one.\n\t\t\t\tEigen::VectorXd* sh = s[this->lbfgs_history_size - 1];\n\t\t\t\tEigen::VectorXd* yh = y[this->lbfgs_history_size - 1];\n\t\t\t\tfor (int h = this->lbfgs_history_size - 1; h >= 1; --h) {\n\t\t\t\t\ts[h]   = s[h - 1];\n\t\t\t\t\ty[h]   = y[h - 1];\n\t\t\t\t\trho[h] = rho[h - 1];\n\t\t\t\t}\n\t\t\t\t// Reuse the storage of the discarded data for the new data.\n\t\t\t\ts[0] = sh;\n\t\t\t\ty[0] = yh;\n\n\t\t\t\t*y[0] = y_tmp;\n\t\t\t\t*s[0] = s_tmp;\n\t\t\t\trho[0] = 1.0 / sTy;\n\t\t\t}\n\t\t}\n\n\t\tresults->lbfgs_update_time += wall_time() - start_time;\n\n\t\t//\n\t\t// Test stopping criteriea\n\t\t//\n\t\tstart_time = wall_time();\n\t\tif (iter > 1 && this->check_exit_conditions(fval, fprev, normg,\n\t\t                                            normg0, x.norm(), normdx,\n\t\t                                            last_iteration_successful, \n\t\t                                            &exit_condition_cache, results)) {\n\t\t\tbreak;\n\t\t}\n\t\tif (iter >= this->maximum_iterations) {\n\t\t\tresults->exit_condition = SolverResults::NO_CONVERGENCE;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (this->callback_function) {\n\t\t\tCallbackInformation information;\n\t\t\tinformation.objective_value = fval;\n\t\t\tinformation.x = &x;\n\t\t\tinformation.g = &g;\n\n\t\t\tif (!callback_function(information)) {\n\t\t\t\tresults->exit_condition = SolverResults::USER_ABORT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tresults->stopping_criteria_time += wall_time() - start_time;\n\n\t\t//\n\t\t// Compute search direction via L-BGFS two-loop recursion.\n\t\t//\n\t\tstart_time = wall_time();\n\t\tbool should_restart = false;\n\n\t\tdouble H0 = 1.0;\n\t\tif (iter > 0) {\n\t\t\t// If the gradient is identical two iterations in a row,\n\t\t\t// y will be the zero vector and H0 will be NaN. In this\n\t\t\t// case the line search will fail and L-BFGS will be restarted\n\t\t\t// with a steepest descent step.\n\t\t\tH0 = s[0]->dot(*y[0]) / y[0]->dot(*y[0]);\n\n\t\t\t// If isinf(H0) || isnan(H0)\n\t\t\tif (H0 ==  std::numeric_limits<double>::infinity() ||\n\t\t\t    H0 == -std::numeric_limits<double>::infinity() ||\n\t\t\t    H0 != H0) {\n\t\t\t\tshould_restart = true;\n\t\t\t}\n\t\t}\n\n\t\tq = -g;\n\n\t\tfor (int h = 0; h < this->lbfgs_history_size; ++h) {\n\t\t\talpha[h] = rho[h] * s[h]->dot(q);\n\t\t\tq = q - alpha[h] * (*y[h]);\n\t\t}\n\n\t\tr = H0 * q;\n\n\t\tfor (int h = this->lbfgs_history_size - 1; h >= 0; --h) {\n\t\t\tdouble beta = rho[h] * y[h]->dot(r);\n\t\t\tr = r + (*s[h]) * (alpha[h] - beta);\n\t\t}\n\n\t\t// If the function improves very little, the approximated Hessian\n\t\t// might be very bad. If this is the case, it is better to discard\n\t\t// the history once in a while. This allows the solver to correctly\n\t\t// solve some badly scaled problems.\n\t\tdouble restart_test = std::fabs(fval - fprev) /\n\t\t                      (std::fabs(fval) + std::fabs(fprev));\n\t\tif (iter > 0 && iter % 100 == 0 && restart_test\n\t\t                                   < this->lbfgs_restart_tolerance) {\n\t\t\tshould_restart = true;\n\t\t}\n\t\tif (! last_iteration_successful) {\n\t\t\tshould_restart = true;\n\t\t}\n\n\t\tif (should_restart) {\n\t\t\tif (this->log_function) {\n\t\t\t\tchar str[1024];\n\t\t\t\tif (number_of_restarts <= 10) {\n\t\t\t\t\tstd::sprintf(str, \"Restarting: fval = %.3e, deltaf = %.3e, max|g_i| = %.3e, test = %.3e\",\n\t\t\t\t\t\t\t\t fval, std::fabs(fval - fprev), normg, restart_test);\n\t\t\t\t\tthis->log_function(str);\n\t\t\t\t}\n\t\t\t\tif (number_of_restarts == 10) {\n\t\t\t\t\tthis->log_function(\"NOTE: No more restarts will be reported.\");\n\t\t\t\t}\n\t\t\t\tnumber_of_restarts++;\n\t\t\t}\n\t\t\tr = -g;\n\t\t\tfor (int h = 0; h < this->lbfgs_history_size; ++h) {\n\t\t\t\t(*s[h]).setZero();\n\t\t\t\t(*y[h]).setZero();\n\t\t\t}\n\t\t\trho.setZero();\n\t\t\talpha.setZero();\n\t\t\t// H0 is not used, but its value will be printed.\n\t\t\tH0 = std::numeric_limits<double>::quiet_NaN();\n\t\t}\n\n\t\tresults->lbfgs_update_time += wall_time() - start_time;\n\n\t\t//\n\t\t// Perform line search.\n\t\t//\n\t\tstart_time = wall_time();\n\t\tdouble start_alpha = 1.0;\n\t\t// In the first iteration, start with a much smaller step\n\t\t// length. (heuristic used by e.g. minFunc)\n\t\tif (iter == 0) {\n\t\t\tdouble sumabsg = 0.0;\n\t\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\t\tsumabsg += std::fabs(g[i]);\n\t\t\t}\n\t\t\tstart_alpha = std::min(1.0, 1.0 / sumabsg);\n\t\t}\n\t\tdouble alpha_step = this->perform_linesearch(function, x, fval, g,\n\t\t                                             r, &x2, start_alpha);\n\n\t\tif (alpha_step <= 0) {\n\t\t\tif (this->log_function) {\n\t\t\t\tthis->log_function(\"Line search failed.\");\n\t\t\t\tchar str[1024];\n\t\t\t\tstd::sprintf(str, \"%4d %+.3e %9.3e %.3e %.3e %.3e %.3e\",\n\t\t\t\t\titer, fval, std::fabs(fval - fprev), normg, alpha_step, H0, rho[0]);\n\t\t\t\tthis->log_function(str);\n\t\t\t}\n\t\t\tif (! last_iteration_successful || number_of_line_search_failures++ > 10) {\n\t\t\t\t// This happens quite seldom. Every time it has happened, the function\n\t\t\t\t// was actually converged to a solution.\n\t\t\t\tresults->exit_condition = SolverResults::GRADIENT_TOLERANCE;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tlast_iteration_successful = false;\n\t\t}\n\t\telse {\n\t\t\t// Record length of this step.\n\t\t\tnormdx = alpha_step * r.norm();\n\t\t\t// Compute new point.\n\t\t\tx_prev = x;\n\t\t\tx = x + alpha_step * r;\n\n\t\t\tlast_iteration_successful = true;\n\t\t}\n\n\t\tresults->backtracking_time += wall_time() - start_time;\n\n\t\t//\n\t\t// Log the results of this iteration.\n\t\t//\n\t\tstart_time = wall_time();\n\n\t\tint log_interval = 1;\n\t\tif (iter > 30) {\n\t\t\tlog_interval = 10;\n\t\t}\n\t\tif (iter > 200) {\n\t\t\tlog_interval = 100;\n\t\t}\n\t\tif (iter > 2000) {\n\t\t\tlog_interval = 1000;\n\t\t}\n\t\tif (this->log_function && iter % log_interval == 0) {\n\t\t\tif (iter == 0) {\n\t\t\t\tthis->log_function(\"Itr       f       deltaf   max|g_i|   alpha      H0       rho\");\n\t\t\t}\n\n\t\t\tthis->log_function(\n\t\t\t\tto_string(\n\t\t\t\t\tstd::setw(4), iter, \" \",\n\t\t\t\t\tstd::setw(10), std::setprecision(3), std::scientific, std::showpos, fval, std::noshowpos, \" \",\n\t\t\t\t\tstd::setw(9),  std::setprecision(3), std::scientific, std::fabs(fval - fprev), \" \",\n\t\t\t\t\tstd::setw(9),  std::setprecision(3), std::setprecision(3), std::scientific, normg, \" \",\n\t\t\t\t\tstd::setw(9),  std::setprecision(3), std::scientific, alpha_step, \" \",\n\t\t\t\t\tstd::setw(9),  std::setprecision(3), std::scientific, H0, \" \",\n\t\t\t\t\tstd::setw(9),  std::setprecision(3), std::scientific, rho[0]\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\t\tresults->log_time += wall_time() - start_time;\n\n\t\tfprev = fval;\n\t\titer++;\n\t}\n\n\tfunction.copy_global_to_user(x);\n\tresults->total_time += wall_time() - global_start_time;\n\n\tif (this->log_function) {\n\t\tchar str[1024];\n\t\tstd::sprintf(str, \" end %+.3e           %.3e\", fval, normg);\n\t\tthis->log_function(str);\n\t}\n}\n\n}  // namespace spii", "meta": {"hexsha": "ae68707695514aeeea9ed016d9d786a9d2c2c74d", "size": 9196, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/solver_lbfgs.cpp", "max_stars_repo_name": "PetterS/spii", "max_stars_repo_head_hexsha": "98c5847223d7c3febea5a1aac6f4978dfef207ec", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2015-03-03T16:21:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-16T08:02:12.000Z", "max_issues_repo_path": "source/solver_lbfgs.cpp", "max_issues_repo_name": "nashdingsheng/spii", "max_issues_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-07-16T14:41:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-09T19:27:22.000Z", "max_forks_repo_path": "source/solver_lbfgs.cpp", "max_forks_repo_name": "nashdingsheng/spii", "max_forks_repo_head_hexsha": "3130d0dc43af8ae79d1fdf315a8b5fc05fe00321", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-09-21T23:09:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-24T20:20:30.000Z", "avg_line_length": 27.9513677812, "max_line_length": 99, "alphanum_fraction": 0.6096128752, "num_tokens": 2787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.423496266637043}}
{"text": "//=====================================================\n// File   :  hand_vec_interface.hh\n// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n//=====================================================\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 2\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n// You should have received a copy of the GNU General Public License\n// along with this program; if not, write to the Free Software\n// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n//\n#ifndef HAND_VEC_INTERFACE_HH\n#define HAND_VEC_INTERFACE_HH\n\n#include <Eigen/Core>\n#include \"f77_interface.hh\"\n\nusing namespace Eigen;\n\ntemplate<class real>\nclass hand_vec_interface : public f77_interface_base<real> {\n\npublic :\n\n  typedef typename ei_packet_traits<real>::type Packet;\n  static const int PacketSize = ei_packet_traits<real>::size;\n\n  typedef typename f77_interface_base<real>::stl_matrix stl_matrix;\n  typedef typename f77_interface_base<real>::stl_vector stl_vector;\n  typedef typename f77_interface_base<real>::gene_matrix gene_matrix;\n  typedef typename f77_interface_base<real>::gene_vector gene_vector;\n\n  static void free_matrix(gene_matrix & A, int N){\n    ei_aligned_free(A);\n  }\n\n  static void free_vector(gene_vector & B){\n    ei_aligned_free(B);\n  }\n\n  static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){\n    int N = A_stl.size();\n    A = (real*)ei_aligned_malloc(N*N*sizeof(real));\n    for (int j=0;j<N;j++)\n      for (int i=0;i<N;i++)\n        A[i+N*j] = A_stl[j][i];\n  }\n\n  static inline void vector_from_stl(gene_vector & B, stl_vector & B_stl){\n    int N = B_stl.size();\n    B = (real*)ei_aligned_malloc(N*sizeof(real));\n    for (int i=0;i<N;i++)\n      B[i] = B_stl[i];\n  }\n\n  static inline std::string name() {\n    #ifdef PEELING\n    return \"hand_vectorized_peeling\";\n    #else\n    return \"hand_vectorized\";\n    #endif\n  }\n\n  static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n  {\n    asm(\"#begin matrix_vector_product\");\n    int AN = (N/PacketSize)*PacketSize;\n    int ANP = (AN/(2*PacketSize))*2*PacketSize;\n    int bound = (N/4)*4;\n    for (int i=0;i<N;i++)\n      X[i] = 0;\n\n    for (int i=0;i<bound;i+=4)\n    {\n      register real* __restrict__ A0 = A + i*N;\n      register real* __restrict__ A1 = A + (i+1)*N;\n      register real* __restrict__ A2 = A + (i+2)*N;\n      register real* __restrict__ A3 = A + (i+3)*N;\n\n      Packet ptmp0 = ei_pset1(B[i]);\n      Packet ptmp1 = ei_pset1(B[i+1]);\n      Packet ptmp2 = ei_pset1(B[i+2]);\n      Packet ptmp3 = ei_pset1(B[i+3]);\n//       register Packet ptmp0, ptmp1, ptmp2, ptmp3;\n//       asm(\n//\n//           \"movss     (%[B],%[j],4), %[ptmp0]  \\n\\t\"\n//           \"shufps   $0,%[ptmp0],%[ptmp0] \\n\\t\"\n//           \"movss    4(%[B],%[j],4), %[ptmp1]  \\n\\t\"\n//           \"shufps   $0,%[ptmp1],%[ptmp1] \\n\\t\"\n//           \"movss    8(%[B],%[j],4), %[ptmp2]  \\n\\t\"\n//           \"shufps   $0,%[ptmp2],%[ptmp2] \\n\\t\"\n//           \"movss   12(%[B],%[j],4), %[ptmp3]  \\n\\t\"\n//           \"shufps   $0,%[ptmp3],%[ptmp3] \\n\\t\"\n//           : [ptmp0] \"=x\" (ptmp0),\n//             [ptmp1] \"=x\" (ptmp1),\n//             [ptmp2] \"=x\" (ptmp2),\n//             [ptmp3] \"=x\" (ptmp3)\n//           : [B] \"r\" (B),\n//             [j] \"r\" (size_t(i))\n//           : );\n\n      if (AN>0)\n      {\n//         for (size_t j = 0;j<ANP;j+=8)\n//         {\n//           asm(\n//\n//           \"movaps     (%[A0],%[j],4), %%xmm8  \\n\\t\"\n//           \"movaps   16(%[A0],%[j],4), %%xmm12 \\n\\t\"\n//           \"movups     (%[A3],%[j],4), %%xmm11 \\n\\t\"\n//           \"movups   16(%[A3],%[j],4), %%xmm15 \\n\\t\"\n//           \"movups     (%[A2],%[j],4), %%xmm10 \\n\\t\"\n//           \"movups   16(%[A2],%[j],4), %%xmm14 \\n\\t\"\n//           \"movups     (%[A1],%[j],4), %%xmm9  \\n\\t\"\n//           \"movups   16(%[A1],%[j],4), %%xmm13 \\n\\t\"\n//\n//           \"mulps %[ptmp0], %%xmm8  \\n\\t\"\n//           \"addps (%[res0],%[j],4), %%xmm8  \\n\\t\"\n//           \"mulps %[ptmp3], %%xmm11 \\n\\t\"\n//           \"addps %%xmm11, %%xmm8  \\n\\t\"\n//           \"mulps %[ptmp2], %%xmm10 \\n\\t\"\n//           \"addps %%xmm10, %%xmm8  \\n\\t\"\n//           \"mulps %[ptmp1], %%xmm9  \\n\\t\"\n//           \"addps %%xmm9, %%xmm8   \\n\\t\"\n//           \"movaps %%xmm8, (%[res0],%[j],4)  \\n\\t\"\n//\n//           \"mulps %[ptmp0], %%xmm12 \\n\\t\"\n//           \"addps 16(%[res0],%[j],4), %%xmm12  \\n\\t\"\n//           \"mulps %[ptmp3], %%xmm15 \\n\\t\"\n//           \"addps %%xmm15, %%xmm12  \\n\\t\"\n//           \"mulps %[ptmp2], %%xmm14 \\n\\t\"\n//           \"addps %%xmm14, %%xmm12  \\n\\t\"\n//           \"mulps %[ptmp1], %%xmm13 \\n\\t\"\n//           \"addps %%xmm13, %%xmm12  \\n\\t\"\n//           \"movaps %%xmm12, 16(%[res0],%[j],4) \\n\\t\"\n//           :\n//           : [res0] \"r\" (X), [j] \"r\" (j),[A0] \"r\" (A0),\n//             [A1] \"r\" (A1),\n//             [A2] \"r\" (A2),\n//             [A3] \"r\" (A3),\n//             [ptmp0] \"x\" (ptmp0),\n//             [ptmp1] \"x\" (ptmp1),\n//             [ptmp2] \"x\" (ptmp2),\n//             [ptmp3] \"x\" (ptmp3)\n//           : \"%xmm8\", \"%xmm9\", \"%xmm10\", \"%xmm11\", \"%xmm12\", \"%xmm13\", \"%xmm14\", \"%xmm15\", \"%r14\");\n//         }\n          register Packet A00;\n          register Packet A01;\n          register Packet A02;\n          register Packet A03;\n          register Packet A10;\n          register Packet A11;\n          register Packet A12;\n          register Packet A13;\n          for (int j = 0;j<ANP;j+=2*PacketSize)\n          {\n//             A00 = ei_pload(&A0[j]);\n//             A01 = ei_ploadu(&A1[j]);\n//             A02 = ei_ploadu(&A2[j]);\n//             A03 = ei_ploadu(&A3[j]);\n//             A10 = ei_pload(&A0[j+PacketSize]);\n//             A11 = ei_ploadu(&A1[j+PacketSize]);\n//             A12 = ei_ploadu(&A2[j+PacketSize]);\n//             A13 = ei_ploadu(&A3[j+PacketSize]);\n//\n//             A00 = ei_pmul(ptmp0, A00);\n//             A01 = ei_pmul(ptmp1, A01);\n//             A02 = ei_pmul(ptmp2, A02);\n//             A03 = ei_pmul(ptmp3, A03);\n//             A10 = ei_pmul(ptmp0, A10);\n//             A11 = ei_pmul(ptmp1, A11);\n//             A12 = ei_pmul(ptmp2, A12);\n//             A13 = ei_pmul(ptmp3, A13);\n//\n//             A00 = ei_padd(A00,A01);\n//             A02 = ei_padd(A02,A03);\n//             A00 = ei_padd(A00,ei_pload(&X[j]));\n//             A00 = ei_padd(A00,A02);\n//             ei_pstore(&X[j],A00);\n//\n//             A10 = ei_padd(A10,A11);\n//             A12 = ei_padd(A12,A13);\n//             A10 = ei_padd(A10,ei_pload(&X[j+PacketSize]));\n//             A10 = ei_padd(A10,A12);\n//             ei_pstore(&X[j+PacketSize],A10);\n\n            ei_pstore(&X[j],\n              ei_padd(ei_pload(&X[j]),\n                ei_padd(\n                  ei_padd(ei_pmul(ptmp0,ei_pload(&A0[j])),ei_pmul(ptmp1,ei_ploadu(&A1[j]))),\n                  ei_padd(ei_pmul(ptmp2,ei_ploadu(&A2[j])),ei_pmul(ptmp3,ei_ploadu(&A3[j]))) )));\n\n            ei_pstore(&X[j+PacketSize],\n              ei_padd(ei_pload(&X[j+PacketSize]),\n                ei_padd(\n                  ei_padd(ei_pmul(ptmp0,ei_pload(&A0[j+PacketSize])),ei_pmul(ptmp1,ei_ploadu(&A1[j+PacketSize]))),\n                  ei_padd(ei_pmul(ptmp2,ei_ploadu(&A2[j+PacketSize])),ei_pmul(ptmp3,ei_ploadu(&A3[j+PacketSize]))) )));\n          }\n          for (int j = ANP;j<AN;j+=PacketSize)\n            ei_pstore(&X[j],\n              ei_padd(ei_pload(&X[j]),\n                ei_padd(\n                  ei_padd(ei_pmul(ptmp0,ei_pload(&A0[j])),ei_pmul(ptmp1,ei_ploadu(&A1[j]))),\n                  ei_padd(ei_pmul(ptmp2,ei_ploadu(&A2[j])),ei_pmul(ptmp3,ei_ploadu(&A3[j]))) )));\n      }\n      // process remaining scalars\n      for (int j=AN;j<N;j++)\n        X[j] += ei_pfirst(ptmp0) * A0[j] + ei_pfirst(ptmp1) * A1[j] + ei_pfirst(ptmp2) * A2[j] + ei_pfirst(ptmp3) * A3[j];\n    }\n    for (int i=bound;i<N;i++)\n    {\n      real tmp0 = B[i];\n      Packet ptmp0 = ei_pset1(tmp0);\n      int iN0 = i*N;\n      if (AN>0)\n      {\n        bool aligned0 = (iN0 % PacketSize) == 0;\n        if (aligned0)\n          for (int j = 0;j<AN;j+=PacketSize)\n            ei_pstore(&X[j], ei_padd(ei_pmul(ptmp0,ei_pload(&A[j+iN0])),ei_pload(&X[j])));\n        else\n          for (int j = 0;j<AN;j+=PacketSize)\n            ei_pstore(&X[j], ei_padd(ei_pmul(ptmp0,ei_ploadu(&A[j+iN0])),ei_pload(&X[j])));\n      }\n      // process remaining scalars\n      for (int j=AN;j<N;j++)\n        X[j] += tmp0 * A[j+iN0];\n    }\n    asm(\"#end matrix_vector_product\");\n  }\n  \n  static inline void symv(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n  {\n    \n//     int AN = (N/PacketSize)*PacketSize;\n//     int ANP = (AN/(2*PacketSize))*2*PacketSize;\n//     int bound = (N/4)*4;\n    for (int i=0;i<N;i++)\n      X[i] = 0;\n    \n    int bound = std::max(0,N-8) & 0xfffffffE;\n\n    for (int j=0;j<bound;j+=2)\n    {\n      register real* __restrict__ A0 = A + j*N;\n      register real* __restrict__ A1 = A + (j+1)*N;\n      \n      real t0 = B[j];\n      Packet ptmp0 = ei_pset1(t0);\n      real t1 = B[j+1];\n      Packet ptmp1 = ei_pset1(t1);\n      \n      real t2 = 0;\n      Packet ptmp2 = ei_pset1(t2);\n      real t3 = 0;\n      Packet ptmp3 = ei_pset1(t3);\n      \n      int starti = j+2;\n      int alignedEnd = starti;\n      int alignedStart = (starti) + ei_first_aligned(&X[starti], N-starti);\n      alignedEnd = alignedStart + ((N-alignedStart)/(PacketSize))*(PacketSize);\n\n      X[j]   += t0 * A0[j];\n      X[j+1] += t1 * A1[j];\n      \n      X[j+1] += t0 * A0[j+1];\n      t2 += A0[j+1] * B[j+1];\n      \n//       alignedStart = alignedEnd;\n      for (int i=starti; i<alignedStart; ++i) {\n        X[i] += t0 * A0[i] + t1 * A1[i];\n        t2 += A0[i] * B[i];\n        t3 += A1[i] * B[i];\n      }\n      asm(\"#begin symv\");\n      for (size_t i=alignedStart; i<alignedEnd; i+=PacketSize) {\n        Packet A0i = ei_ploadu(&A0[i]);\n        Packet A1i = ei_ploadu(&A1[i]);\n//         Packet A0i1 = ei_ploadu(&A0[i+PacketSize]);\n        Packet Xi = ei_pload(&X[i]);\n        Packet Bi = ei_pload/*u*/(&B[i]);\n//         Packet Xi1 = ei_pload(&X[i+PacketSize]);\n//         Packet Bi1 = ei_pload/*u*/(&B[i+PacketSize]);\n        Xi = ei_padd(ei_padd(Xi, ei_pmul(ptmp0, A0i)), ei_pmul(ptmp1, A1i));\n        ptmp2 = ei_padd(ptmp2, ei_pmul(A0i, Bi));\n        ptmp3 = ei_padd(ptmp3, ei_pmul(A1i, Bi));\n//         Xi1 = ei_padd(Xi1, ei_pmul(ptmp1, A0i1));\n//         ptmp2 = ei_padd(ptmp2, ei_pmul(A0i1, Bi1));\n//         \n        ei_pstore(&X[i],Xi);\n//         ei_pstore(&X[i+PacketSize],Xi1);\n//         asm(\n//           \"prefetchnta   64(%[A0],%[i],4)   \\n\\t\"\n//           //\"movups     (%[A0],%[i],4), %%xmm8  \\n\\t\"\n//           \"movsd       (%[A0],%[i],4), %%xmm8  \\n\\t\"\n//           \"movhps     8(%[A0],%[i],4), %%xmm8  \\n\\t\"\n// //           \"movups   16(%[A0],%[i],4), %%xmm9  \\n\\t\"\n// //           \"movups   64(%[A0],%[i],4), %%xmm15  \\n\\t\"\n//           \"movaps     (%[B], %[i],4), %%xmm12 \\n\\t\"\n// //           \"movaps   16(%[B], %[i],4), %%xmm13 \\n\\t\"\n//           \"movaps     (%[X], %[i],4), %%xmm10 \\n\\t\"\n// //           \"movaps   16(%[X], %[i],4), %%xmm11 \\n\\t\"\n//           \n//           \"mulps %%xmm8, %%xmm12  \\n\\t\"\n// //           \"mulps %%xmm9, %%xmm13  \\n\\t\"\n//           \n//           \"mulps %[ptmp1], %%xmm8  \\n\\t\"\n//           \"addps %%xmm12, %[ptmp2]  \\n\\t\"\n//           \"addps %%xmm8, %%xmm10  \\n\\t\"\n//           \n//           \n//           \n//           \n// //           \"mulps %[ptmp1], %%xmm9  \\n\\t\"\n//           \n// //           \"addps %%xmm9, %%xmm11  \\n\\t\"\n// //           \"addps %%xmm13, %[ptmp2]  \\n\\t\"\n//           \n//           \"movaps %%xmm10,   (%[X],%[i],4) \\n\\t\"\n// //           \"movaps %%xmm11, 16(%[X],%[i],4) \\n\\t\"\n//           : \n//           : [X] \"r\" (X), [i] \"r\" (i), [A0] \"r\" (A0),\n//             [B] \"r\" (B),\n//             [ptmp1] \"x\" (ptmp1),\n//             [ptmp2] \"x\" (ptmp2)\n//           : \"%xmm8\", \"%xmm9\", \"%xmm10\", \"%xmm11\", \"%xmm12\", \"%xmm13\", \"%xmm15\");\n      }\n      asm(\"#end symv\");\n      for (int i=alignedEnd; i<N; i++) {\n        X[i] += t0 * A0[i] + t1 * A1[i];\n        t2 += A0[i] * B[i];\n        t3 += A1[i] * B[i];\n      }\n      \n      \n      X[j]   += t2 + ei_predux(ptmp2);\n      X[j+1] += t3 + ei_predux(ptmp3);\n    }\n    for (int j=bound;j<N;j++)\n    {\n      register real* __restrict__ A0 = A + j*N;\n      \n      real t1 = B[j];\n      real t2 = 0;\n      X[j] += t1 * A0[j];\n      for (int i=j+1; i<N; i+=PacketSize) {\n        X[i] += t1 * A0[i];\n        t2 += A0[i] * B[i];\n      }\n      X[j] += t2;\n    }\n    \n  }\n\n//   static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n//   {\n//     asm(\"#begin matrix_vector_product\");\n//     int AN = (N/PacketSize)*PacketSize;\n//     int ANP = (AN/(2*PacketSize))*2*PacketSize;\n//     int bound = (N/4)*4;\n//     for (int i=0;i<N;i++)\n//       X[i] = 0;\n//\n//     for (int i=0;i<bound;i+=4)\n//     {\n//       real tmp0 = B[i];\n//       Packet ptmp0 = ei_pset1(tmp0);\n//       real tmp1 = B[i+1];\n//       Packet ptmp1 = ei_pset1(tmp1);\n//       real tmp2 = B[i+2];\n//       Packet ptmp2 = ei_pset1(tmp2);\n//       real tmp3 = B[i+3];\n//       Packet ptmp3 = ei_pset1(tmp3);\n//       int iN0 = i*N;\n//       int iN1 = (i+1)*N;\n//       int iN2 = (i+2)*N;\n//       int iN3 = (i+3)*N;\n//       if (AN>0)\n//       {\n// //         int aligned0 = (iN0 % PacketSize);\n//         int aligned1 = (iN1 % PacketSize);\n//\n//         if (aligned1==0)\n//         {\n//           for (int j = 0;j<AN;j+=PacketSize)\n//           {\n//             ei_pstore(&X[j],\n//               ei_padd(ei_pload(&X[j]),\n//                 ei_padd(\n//                   ei_padd(ei_pmul(ptmp0,ei_pload(&A[j+iN0])),ei_pmul(ptmp1,ei_pload(&A[j+iN1]))),\n//                   ei_padd(ei_pmul(ptmp2,ei_pload(&A[j+iN2])),ei_pmul(ptmp3,ei_pload(&A[j+iN3]))) )));\n//           }\n//         }\n//         else if (aligned1==2)\n//         {\n//           for (int j = 0;j<AN;j+=PacketSize)\n//           {\n//             ei_pstore(&X[j],\n//               ei_padd(ei_pload(&X[j]),\n//                 ei_padd(\n//                   ei_padd(ei_pmul(ptmp0,ei_pload(&A[j+iN0])),ei_pmul(ptmp1,ei_ploadu(&A[j+iN1]))),\n//                   ei_padd(ei_pmul(ptmp2,ei_pload(&A[j+iN2])),ei_pmul(ptmp3,ei_ploadu(&A[j+iN3]))) )));\n//           }\n//         }\n//         else\n//         {\n//           for (int j = 0;j<ANP;j+=2*PacketSize)\n//           {\n//             ei_pstore(&X[j],\n//               ei_padd(ei_pload(&X[j]),\n//                 ei_padd(\n//                   ei_padd(ei_pmul(ptmp0,ei_pload(&A[j+iN0])),ei_pmul(ptmp1,ei_ploadu(&A[j+iN1]))),\n//                   ei_padd(ei_pmul(ptmp2,ei_ploadu(&A[j+iN2])),ei_pmul(ptmp3,ei_ploadu(&A[j+iN3]))) )));\n//\n//             ei_pstore(&X[j+PacketSize],\n//               ei_padd(ei_pload(&X[j+PacketSize]),\n//                 ei_padd(\n//                   ei_padd(ei_pmul(ptmp0,ei_pload(&A[j+PacketSize+iN0])),ei_pmul(ptmp1,ei_ploadu(&A[j+PacketSize+iN1]))),\n//                   ei_padd(ei_pmul(ptmp2,ei_ploadu(&A[j+PacketSize+iN2])),ei_pmul(ptmp3,ei_ploadu(&A[j+PacketSize+iN3]))) )));\n//\n// //             ei_pstore(&X[j+2*PacketSize],\n// //               ei_padd(ei_pload(&X[j+2*PacketSize]),\n// //                 ei_padd(\n// //                   ei_padd(ei_pmul(ptmp0,ei_pload(&A[j+2*PacketSize+iN0])),ei_pmul(ptmp1,ei_ploadu(&A[j+2*PacketSize+iN1]))),\n// //                   ei_padd(ei_pmul(ptmp2,ei_ploadu(&A[j+2*PacketSize+iN2])),ei_pmul(ptmp3,ei_ploadu(&A[j+2*PacketSize+iN3]))) )));\n// //\n// //             ei_pstore(&X[j+3*PacketSize],\n// //               ei_padd(ei_pload(&X[j+3*PacketSize]),\n// //                 ei_padd(\n// //                   ei_padd(ei_pmul(ptmp0,ei_pload(&A[j+3*PacketSize+iN0])),ei_pmul(ptmp1,ei_ploadu(&A[j+3*PacketSize+iN1]))),\n// //                   ei_padd(ei_pmul(ptmp2,ei_ploadu(&A[j+3*PacketSize+iN2])),ei_pmul(ptmp3,ei_ploadu(&A[j+3*PacketSize+iN3]))) )));\n//\n//           }\n//           for (int j = ANP;j<AN;j+=PacketSize)\n//             ei_pstore(&X[j],\n//               ei_padd(ei_pload(&X[j]),\n//                 ei_padd(\n//                   ei_padd(ei_pmul(ptmp0,ei_ploadu(&A[j+iN0])),ei_pmul(ptmp1,ei_ploadu(&A[j+iN1]))),\n//                   ei_padd(ei_pmul(ptmp2,ei_ploadu(&A[j+iN2])),ei_pmul(ptmp3,ei_ploadu(&A[j+iN3]))) )));\n//         }\n//       }\n//       // process remaining scalars\n//       for (int j=AN;j<N;j++)\n//         X[j] += tmp0 * A[j+iN0] + tmp1 * A[j+iN1] + tmp2 * A[j+iN2] + tmp3 * A[j+iN3];\n//     }\n//     for (int i=bound;i<N;i++)\n//     {\n//       real tmp0 = B[i];\n//       Packet ptmp0 = ei_pset1(tmp0);\n//       int iN0 = i*N;\n//       if (AN>0)\n//       {\n//         bool aligned0 = (iN0 % PacketSize) == 0;\n//         if (aligned0)\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             ei_pstore(&X[j], ei_padd(ei_pmul(ptmp0,ei_pload(&A[j+iN0])),ei_pload(&X[j])));\n//         else\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             ei_pstore(&X[j], ei_padd(ei_pmul(ptmp0,ei_ploadu(&A[j+iN0])),ei_pload(&X[j])));\n//       }\n//       // process remaining scalars\n//       for (int j=AN;j<N;j++)\n//         X[j] += tmp0 * A[j+iN0];\n//     }\n//     asm(\"#end matrix_vector_product\");\n//   }\n\n//   static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n//   {\n//     asm(\"#begin matrix_vector_product\");\n//     int AN = (N/PacketSize)*PacketSize;\n//     for (int i=0;i<N;i++)\n//       X[i] = 0;\n//\n//     for (int i=0;i<N;i+=2)\n//     {\n//       real tmp0 = B[i];\n//       Packet ptmp0 = ei_pset1(tmp0);\n//       real tmp1 = B[i+1];\n//       Packet ptmp1 = ei_pset1(tmp1);\n//       int iN0 = i*N;\n//       int iN1 = (i+1)*N;\n//       if (AN>0)\n//       {\n//         bool aligned0 = (iN0 % PacketSize) == 0;\n//         bool aligned1 = (iN1 % PacketSize) == 0;\n//\n//         if (aligned0 && aligned1)\n//         {\n//           for (int j = 0;j<AN;j+=PacketSize)\n//           {\n//             ei_pstore(&X[j],\n//               ei_padd(ei_pmul(ptmp0,ei_pload(&A[j+iN0])),\n//               ei_padd(ei_pmul(ptmp1,ei_pload(&A[j+iN1])),ei_pload(&X[j]))));\n//           }\n//         }\n//         else if (aligned0)\n//         {\n//           for (int j = 0;j<AN;j+=PacketSize)\n//           {\n//             ei_pstore(&X[j],\n//               ei_padd(ei_pmul(ptmp0,ei_pload(&A[j+iN0])),\n//               ei_padd(ei_pmul(ptmp1,ei_ploadu(&A[j+iN1])),ei_pload(&X[j]))));\n//           }\n//         }\n//         else if (aligned1)\n//         {\n//           for (int j = 0;j<AN;j+=PacketSize)\n//           {\n//             ei_pstore(&X[j],\n//               ei_padd(ei_pmul(ptmp0,ei_ploadu(&A[j+iN0])),\n//               ei_padd(ei_pmul(ptmp1,ei_pload(&A[j+iN1])),ei_pload(&X[j]))));\n//           }\n//         }\n//         else\n//         {\n//           int ANP = (AN/(4*PacketSize))*4*PacketSize;\n//           for (int j = 0;j<ANP;j+=4*PacketSize)\n//           {\n//             ei_pstore(&X[j],\n//               ei_padd(ei_pmul(ptmp0,ei_ploadu(&A[j+iN0])),\n//               ei_padd(ei_pmul(ptmp1,ei_ploadu(&A[j+iN1])),ei_pload(&X[j]))));\n//\n//             ei_pstore(&X[j+PacketSize],\n//               ei_padd(ei_pmul(ptmp0,ei_ploadu(&A[j+PacketSize+iN0])),\n//               ei_padd(ei_pmul(ptmp1,ei_ploadu(&A[j+PacketSize+iN1])),ei_pload(&X[j+PacketSize]))));\n//\n//             ei_pstore(&X[j+2*PacketSize],\n//               ei_padd(ei_pmul(ptmp0,ei_ploadu(&A[j+2*PacketSize+iN0])),\n//               ei_padd(ei_pmul(ptmp1,ei_ploadu(&A[j+2*PacketSize+iN1])),ei_pload(&X[j+2*PacketSize]))));\n//\n//             ei_pstore(&X[j+3*PacketSize],\n//               ei_padd(ei_pmul(ptmp0,ei_ploadu(&A[j+3*PacketSize+iN0])),\n//               ei_padd(ei_pmul(ptmp1,ei_ploadu(&A[j+3*PacketSize+iN1])),ei_pload(&X[j+3*PacketSize]))));\n//           }\n//           for (int j = ANP;j<AN;j+=PacketSize)\n//             ei_pstore(&X[j],\n//               ei_padd(ei_pmul(ptmp0,ei_ploadu(&A[j+iN0])),\n//               ei_padd(ei_pmul(ptmp1,ei_ploadu(&A[j+iN1])),ei_pload(&X[j]))));\n//         }\n//       }\n//       // process remaining scalars\n//       for (int j=AN;j<N;j++)\n//         X[j] += tmp0 * A[j+iN0] + tmp1 * A[j+iN1];\n//     }\n//     int remaining = (N/2)*2;\n//     for (int i=remaining;i<N;i++)\n//     {\n//       real tmp0 = B[i];\n//       Packet ptmp0 = ei_pset1(tmp0);\n//       int iN0 = i*N;\n//       if (AN>0)\n//       {\n//         bool aligned0 = (iN0 % PacketSize) == 0;\n//         if (aligned0)\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             ei_pstore(&X[j], ei_padd(ei_pmul(ptmp0,ei_pload(&A[j+iN0])),ei_pload(&X[j])));\n//         else\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             ei_pstore(&X[j], ei_padd(ei_pmul(ptmp0,ei_ploadu(&A[j+iN0])),ei_pload(&X[j])));\n//       }\n//       // process remaining scalars\n//       for (int j=AN;j<N;j++)\n//         X[j] += tmp0 * A[j+iN0];\n//     }\n//     asm(\"#end matrix_vector_product\");\n//   }\n\n//   static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n//   {\n//     asm(\"#begin matrix_vector_product\");\n//     int AN = (N/PacketSize)*PacketSize;\n//     for (int i=0;i<N;i++)\n//       X[i] = 0;\n//     for (int i=0;i<N;i++)\n//     {\n//       real tmp = B[i];\n//       Packet ptmp = ei_pset1(tmp);\n//       int iN = i*N;\n//       if (AN>0)\n//       {\n//         bool aligned = (iN % PacketSize) == 0;\n//         if (aligned)\n//         {\n//           #ifdef PEELING\n//           Packet A0, A1, A2, X0, X1, X2;\n//           int ANP = (AN/(8*PacketSize))*8*PacketSize;\n//           for (int j = 0;j<ANP;j+=PacketSize*8)\n//           {\n//             A0 = ei_pload(&A[j+iN]);\n//             X0 = ei_pload(&X[j]);\n//             A1 = ei_pload(&A[j+PacketSize+iN]);\n//             X1 = ei_pload(&X[j+PacketSize]);\n//             A2 = ei_pload(&A[j+2*PacketSize+iN]);\n//             X2 = ei_pload(&X[j+2*PacketSize]);\n//             ei_pstore(&X[j], ei_padd(X0, ei_pmul(ptmp,A0)));\n//             A0 = ei_pload(&A[j+3*PacketSize+iN]);\n//             X0 = ei_pload(&X[j+3*PacketSize]);\n//             ei_pstore(&X[j+PacketSize], ei_padd(ei_pload(&X1), ei_pmul(ptmp,A1)));\n//             A1 = ei_pload(&A[j+4*PacketSize+iN]);\n//             X1 = ei_pload(&X[j+4*PacketSize]);\n//             ei_pstore(&X[j+2*PacketSize], ei_padd(ei_pload(&X2), ei_pmul(ptmp,A2)));\n//             A2 = ei_pload(&A[j+5*PacketSize+iN]);\n//             X2 = ei_pload(&X[j+5*PacketSize]);\n//             ei_pstore(&X[j+3*PacketSize], ei_padd(ei_pload(&X0), ei_pmul(ptmp,A0)));\n//             A0 = ei_pload(&A[j+6*PacketSize+iN]);\n//             X0 = ei_pload(&X[j+6*PacketSize]);\n//             ei_pstore(&X[j+4*PacketSize], ei_padd(ei_pload(&X1), ei_pmul(ptmp,A1)));\n//             A1 = ei_pload(&A[j+7*PacketSize+iN]);\n//             X1 = ei_pload(&X[j+7*PacketSize]);\n//             ei_pstore(&X[j+5*PacketSize], ei_padd(ei_pload(&X2), ei_pmul(ptmp,A2)));\n//             ei_pstore(&X[j+6*PacketSize], ei_padd(ei_pload(&X0), ei_pmul(ptmp,A0)));\n//             ei_pstore(&X[j+7*PacketSize], ei_padd(ei_pload(&X1), ei_pmul(ptmp,A1)));\n// //\n// //             ei_pstore(&X[j], ei_padd(ei_pload(&X[j]), ei_pmul(ptmp,ei_pload(&A[j+iN]))));\n// //             ei_pstore(&X[j+PacketSize], ei_padd(ei_pload(&X[j+PacketSize]), ei_pmul(ptmp,ei_pload(&A[j+PacketSize+iN]))));\n// //             ei_pstore(&X[j+2*PacketSize], ei_padd(ei_pload(&X[j+2*PacketSize]), ei_pmul(ptmp,ei_pload(&A[j+2*PacketSize+iN]))));\n// //             ei_pstore(&X[j+3*PacketSize], ei_padd(ei_pload(&X[j+3*PacketSize]), ei_pmul(ptmp,ei_pload(&A[j+3*PacketSize+iN]))));\n// //             ei_pstore(&X[j+4*PacketSize], ei_padd(ei_pload(&X[j+4*PacketSize]), ei_pmul(ptmp,ei_pload(&A[j+4*PacketSize+iN]))));\n// //             ei_pstore(&X[j+5*PacketSize], ei_padd(ei_pload(&X[j+5*PacketSize]), ei_pmul(ptmp,ei_pload(&A[j+5*PacketSize+iN]))));\n// //             ei_pstore(&X[j+6*PacketSize], ei_padd(ei_pload(&X[j+6*PacketSize]), ei_pmul(ptmp,ei_pload(&A[j+6*PacketSize+iN]))));\n// //             ei_pstore(&X[j+7*PacketSize], ei_padd(ei_pload(&X[j+7*PacketSize]), ei_pmul(ptmp,ei_pload(&A[j+7*PacketSize+iN]))));\n//           }\n//           for (int j = ANP;j<AN;j+=PacketSize)\n//             ei_pstore(&X[j], ei_padd(ei_pload(&X[j]), ei_pmul(ptmp,ei_pload(&A[j+iN]))));\n//           #else\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             ei_pstore(&X[j], ei_padd(ei_pload(&X[j]), ei_pmul(ptmp,ei_pload(&A[j+iN]))));\n//           #endif\n//         }\n//         else\n//         {\n//           #ifdef PEELING\n//           int ANP = (AN/(8*PacketSize))*8*PacketSize;\n//           for (int j = 0;j<ANP;j+=PacketSize*8)\n//           {\n//             ei_pstore(&X[j], ei_padd(ei_pload(&X[j]), ei_pmul(ptmp,ei_ploadu(&A[j+iN]))));\n//             ei_pstore(&X[j+PacketSize], ei_padd(ei_pload(&X[j+PacketSize]), ei_pmul(ptmp,ei_ploadu(&A[j+PacketSize+iN]))));\n//             ei_pstore(&X[j+2*PacketSize], ei_padd(ei_pload(&X[j+2*PacketSize]), ei_pmul(ptmp,ei_ploadu(&A[j+2*PacketSize+iN]))));\n//             ei_pstore(&X[j+3*PacketSize], ei_padd(ei_pload(&X[j+3*PacketSize]), ei_pmul(ptmp,ei_ploadu(&A[j+3*PacketSize+iN]))));\n//             ei_pstore(&X[j+4*PacketSize], ei_padd(ei_pload(&X[j+4*PacketSize]), ei_pmul(ptmp,ei_ploadu(&A[j+4*PacketSize+iN]))));\n//             ei_pstore(&X[j+5*PacketSize], ei_padd(ei_pload(&X[j+5*PacketSize]), ei_pmul(ptmp,ei_ploadu(&A[j+5*PacketSize+iN]))));\n//             ei_pstore(&X[j+6*PacketSize], ei_padd(ei_pload(&X[j+6*PacketSize]), ei_pmul(ptmp,ei_ploadu(&A[j+6*PacketSize+iN]))));\n//             ei_pstore(&X[j+7*PacketSize], ei_padd(ei_pload(&X[j+7*PacketSize]), ei_pmul(ptmp,ei_ploadu(&A[j+7*PacketSize+iN]))));\n//           }\n//           for (int j = ANP;j<AN;j+=PacketSize)\n//             ei_pstore(&X[j], ei_padd(ei_pload(&X[j]), ei_pmul(ptmp,ei_ploadu(&A[j+iN]))));\n//           #else\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             ei_pstore(&X[j], ei_padd(ei_pload(&X[j]), ei_pmul(ptmp,ei_ploadu(&A[j+iN]))));\n//           #endif\n//         }\n//       }\n//       // process remaining scalars\n//       for (int j=AN;j<N;j++)\n//         X[j] += tmp * A[j+iN];\n//     }\n//     asm(\"#end matrix_vector_product\");\n//   }\n\n    static inline void atv_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n  {\n    int AN = (N/PacketSize)*PacketSize;\n    int bound = (N/4)*4;\n    for (int i=0;i<bound;i+=4)\n    {\n      real tmp0 = 0;\n      Packet ptmp0 = ei_pset1(real(0));\n      real tmp1 = 0;\n      Packet ptmp1 = ei_pset1(real(0));\n      real tmp2 = 0;\n      Packet ptmp2 = ei_pset1(real(0));\n      real tmp3 = 0;\n      Packet ptmp3 = ei_pset1(real(0));\n      int iN0 = i*N;\n      int iN1 = (i+1)*N;\n      int iN2 = (i+2)*N;\n      int iN3 = (i+3)*N;\n      if (AN>0)\n      {\n        int align1 = (iN1 % PacketSize);\n        if (align1==0)\n        {\n          for (int j = 0;j<AN;j+=PacketSize)\n          {\n            Packet b = ei_pload(&B[j]);\n            ptmp0 = ei_padd(ptmp0, ei_pmul(b, ei_pload(&A[j+iN0])));\n            ptmp1 = ei_padd(ptmp1, ei_pmul(b, ei_pload(&A[j+iN1])));\n            ptmp2 = ei_padd(ptmp2, ei_pmul(b, ei_pload(&A[j+iN2])));\n            ptmp3 = ei_padd(ptmp3, ei_pmul(b, ei_pload(&A[j+iN3])));\n          }\n        }\n        else if (align1==2)\n        {\n          for (int j = 0;j<AN;j+=PacketSize)\n          {\n            Packet b = ei_pload(&B[j]);\n            ptmp0 = ei_padd(ptmp0, ei_pmul(b, ei_pload(&A[j+iN0])));\n            ptmp1 = ei_padd(ptmp1, ei_pmul(b, ei_ploadu(&A[j+iN1])));\n            ptmp2 = ei_padd(ptmp2, ei_pmul(b, ei_pload(&A[j+iN2])));\n            ptmp3 = ei_padd(ptmp3, ei_pmul(b, ei_ploadu(&A[j+iN3])));\n          }\n        }\n        else\n        {\n          for (int j = 0;j<AN;j+=PacketSize)\n          {\n            Packet b = ei_pload(&B[j]);\n            ptmp0 = ei_padd(ptmp0, ei_pmul(b, ei_pload(&A[j+iN0])));\n            ptmp1 = ei_padd(ptmp1, ei_pmul(b, ei_ploadu(&A[j+iN1])));\n            ptmp2 = ei_padd(ptmp2, ei_pmul(b, ei_ploadu(&A[j+iN2])));\n            ptmp3 = ei_padd(ptmp3, ei_pmul(b, ei_ploadu(&A[j+iN3])));\n          }\n        }\n        tmp0 = ei_predux(ptmp0);\n        tmp1 = ei_predux(ptmp1);\n        tmp2 = ei_predux(ptmp2);\n        tmp3 = ei_predux(ptmp3);\n      }\n      // process remaining scalars\n      for (int j=AN;j<N;j++)\n      {\n        tmp0 += B[j] * A[j+iN0];\n        tmp1 += B[j] * A[j+iN1];\n        tmp2 += B[j] * A[j+iN2];\n        tmp3 += B[j] * A[j+iN3];\n      }\n      X[i+0] = tmp0;\n      X[i+1] = tmp1;\n      X[i+2] = tmp2;\n      X[i+3] = tmp3;\n    }\n\n    for (int i=bound;i<N;i++)\n    {\n      real tmp0 = 0;\n      Packet ptmp0 = ei_pset1(real(0));\n      int iN0 = i*N;\n      if (AN>0)\n      {\n        if (iN0 % PacketSize==0)\n          for (int j = 0;j<AN;j+=PacketSize)\n            ptmp0 = ei_padd(ptmp0, ei_pmul(ei_pload(&B[j]), ei_pload(&A[j+iN0])));\n        else\n          for (int j = 0;j<AN;j+=PacketSize)\n            ptmp0 = ei_padd(ptmp0, ei_pmul(ei_pload(&B[j]), ei_ploadu(&A[j+iN0])));\n        tmp0 = ei_predux(ptmp0);\n      }\n      // process remaining scalars\n      for (int j=AN;j<N;j++)\n        tmp0 += B[j] * A[j+iN0];\n      X[i+0] = tmp0;\n    }\n  }\n\n//   static inline void atv_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n//   {\n//     int AN = (N/PacketSize)*PacketSize;\n//     for (int i=0;i<N;i++)\n//       X[i] = 0;\n//     for (int i=0;i<N;i++)\n//     {\n//       real tmp = 0;\n//       Packet ptmp = ei_pset1(real(0));\n//       int iN = i*N;\n//       if (AN>0)\n//       {\n//         bool aligned = (iN % PacketSize) == 0;\n//         if (aligned)\n//         {\n//           #ifdef PEELING\n//           int ANP = (AN/(8*PacketSize))*8*PacketSize;\n//           for (int j = 0;j<ANP;j+=PacketSize*8)\n//           {\n//             ptmp =\n//               ei_padd(ei_pmul(ei_pload(&B[j]), ei_pload(&A[j+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+PacketSize]), ei_pload(&A[j+PacketSize+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+2*PacketSize]), ei_pload(&A[j+2*PacketSize+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+3*PacketSize]), ei_pload(&A[j+3*PacketSize+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+4*PacketSize]), ei_pload(&A[j+4*PacketSize+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+5*PacketSize]), ei_pload(&A[j+5*PacketSize+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+6*PacketSize]), ei_pload(&A[j+6*PacketSize+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+7*PacketSize]), ei_pload(&A[j+7*PacketSize+iN])),\n//               ptmp))))))));\n//           }\n//           for (int j = ANP;j<AN;j+=PacketSize)\n//             ptmp = ei_padd(ptmp, ei_pmul(ei_pload(&B[j]), ei_pload(&A[j+iN])));\n//           #else\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             ptmp = ei_padd(ptmp, ei_pmul(ei_pload(&B[j]), ei_pload(&A[j+iN])));\n//           #endif\n//         }\n//         else\n//         {\n//           #ifdef PEELING\n//           int ANP = (AN/(8*PacketSize))*8*PacketSize;\n//           for (int j = 0;j<ANP;j+=PacketSize*8)\n//           {\n//             ptmp =\n//               ei_padd(ei_pmul(ei_pload(&B[j]), ei_ploadu(&A[j+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+PacketSize]), ei_ploadu(&A[j+PacketSize+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+2*PacketSize]), ei_ploadu(&A[j+2*PacketSize+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+3*PacketSize]), ei_ploadu(&A[j+3*PacketSize+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+4*PacketSize]), ei_ploadu(&A[j+4*PacketSize+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+5*PacketSize]), ei_ploadu(&A[j+5*PacketSize+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+6*PacketSize]), ei_ploadu(&A[j+6*PacketSize+iN])),\n//               ei_padd(ei_pmul(ei_pload(&B[j+7*PacketSize]), ei_ploadu(&A[j+7*PacketSize+iN])),\n//               ptmp))))))));\n//           }\n//           for (int j = ANP;j<AN;j+=PacketSize)\n//             ptmp = ei_padd(ptmp, ei_pmul(ei_pload(&B[j]), ei_ploadu(&A[j+iN])));\n//           #else\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             ptmp = ei_padd(ptmp, ei_pmul(ei_pload(&B[j]), ei_ploadu(&A[j+iN])));\n//           #endif\n//         }\n//         tmp = ei_predux(ptmp);\n//       }\n//       // process remaining scalars\n//       for (int j=AN;j<N;j++)\n//         tmp += B[j] * A[j+iN];\n//       X[i] = tmp;\n//     }\n//   }\n\n  static inline void axpy(real coef, const gene_vector & X, gene_vector & Y, int N){\n    int AN = (N/PacketSize)*PacketSize;\n    if (AN>0)\n    {\n      Packet pcoef = ei_pset1(coef);\n      #ifdef PEELING\n      const int peelSize = 3;\n      int ANP = (AN/(peelSize*PacketSize))*peelSize*PacketSize;\n      float* X1 = X + PacketSize;\n      float* Y1 = Y + PacketSize;\n      float* X2 = X + 2*PacketSize;\n      float* Y2 = Y + 2*PacketSize;\n      Packet x0,x1,x2,y0,y1,y2;\n      for (int j = 0;j<ANP;j+=PacketSize*peelSize)\n      {\n        x0 = ei_pload(X+j);\n        x1 = ei_pload(X1+j);\n        x2 = ei_pload(X2+j);\n\n        y0 = ei_pload(Y+j);\n        y1 = ei_pload(Y1+j);\n        y2 = ei_pload(Y2+j);\n\n        y0 = ei_pmadd(pcoef, x0, y0);\n        y1 = ei_pmadd(pcoef, x1, y1);\n        y2 = ei_pmadd(pcoef, x2, y2);\n\n        ei_pstore(Y+j,  y0);\n        ei_pstore(Y1+j, y1);\n        ei_pstore(Y2+j, y2);\n//         ei_pstore(&Y[j+2*PacketSize], ei_padd(ei_pload(&Y[j+2*PacketSize]), ei_pmul(pcoef,ei_pload(&X[j+2*PacketSize]))));\n//         ei_pstore(&Y[j+3*PacketSize], ei_padd(ei_pload(&Y[j+3*PacketSize]), ei_pmul(pcoef,ei_pload(&X[j+3*PacketSize]))));\n//         ei_pstore(&Y[j+4*PacketSize], ei_padd(ei_pload(&Y[j+4*PacketSize]), ei_pmul(pcoef,ei_pload(&X[j+4*PacketSize]))));\n//         ei_pstore(&Y[j+5*PacketSize], ei_padd(ei_pload(&Y[j+5*PacketSize]), ei_pmul(pcoef,ei_pload(&X[j+5*PacketSize]))));\n//         ei_pstore(&Y[j+6*PacketSize], ei_padd(ei_pload(&Y[j+6*PacketSize]), ei_pmul(pcoef,ei_pload(&X[j+6*PacketSize]))));\n//         ei_pstore(&Y[j+7*PacketSize], ei_padd(ei_pload(&Y[j+7*PacketSize]), ei_pmul(pcoef,ei_pload(&X[j+7*PacketSize]))));\n      }\n      for (int j = ANP;j<AN;j+=PacketSize)\n        ei_pstore(&Y[j], ei_padd(ei_pload(&Y[j]), ei_pmul(pcoef,ei_pload(&X[j]))));\n      #else\n      for (int j = 0;j<AN;j+=PacketSize)\n        ei_pstore(&Y[j], ei_padd(ei_pload(&Y[j]), ei_pmul(pcoef,ei_pload(&X[j]))));\n      #endif\n    }\n    // process remaining scalars\n    for (int i=AN;i<N;i++)\n      Y[i] += coef * X[i];\n  }\n\n\n};\n\n#endif\n", "meta": {"hexsha": "be5d5e6b6a4204737e71cfc58af68215304efee6", "size": 34744, "ext": "hh", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/bench/btl/libs/hand_vec/hand_vec_interface.hh", "max_stars_repo_name": "dailysoap/CSMM.104x", "max_stars_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "t1m1/include/eigen/bench/btl/libs/hand_vec/hand_vec_interface.hh", "max_issues_repo_name": "dailysoap/CSMM.104x", "max_issues_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "t1m1/include/eigen/bench/btl/libs/hand_vec/hand_vec_interface.hh", "max_forks_repo_name": "dailysoap/CSMM.104x", "max_forks_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T01:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T14:55:38.000Z", "avg_line_length": 39.1702367531, "max_line_length": 135, "alphanum_fraction": 0.4892355515, "num_tokens": 12331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4234962601540015}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"grad.h\"\n#include <Eigen/Geometry>\n#include <vector>\n\n#include \"PI.h\"\n#include \"per_face_normals.h\"\n#include \"volume.h\"\n#include \"doublearea.h\"\n\nnamespace igl {\n\nnamespace {\n\ntemplate <typename DerivedV, typename DerivedF>\nIGL_INLINE void grad_tet(\n  const Eigen::MatrixBase<DerivedV>&V,\n  const Eigen::MatrixBase<DerivedF>&T,\n  Eigen::SparseMatrix<typename DerivedV::Scalar> &G,\n  bool uniform)\n{\n  using namespace Eigen;\n  assert(T.cols() == 4);\n  const int n = V.rows(); int m = T.rows();\n\n  /*\n      F = [ ...\n      T(:,1) T(:,2) T(:,3); ...\n      T(:,1) T(:,3) T(:,4); ...\n      T(:,1) T(:,4) T(:,2); ...\n      T(:,2) T(:,4) T(:,3)]; */\n  MatrixXi F(4*m,3);\n  for (int i = 0; i < m; i++) {\n    F.row(0*m + i) << T(i,0), T(i,1), T(i,2);\n    F.row(1*m + i) << T(i,0), T(i,2), T(i,3);\n    F.row(2*m + i) << T(i,0), T(i,3), T(i,1);\n    F.row(3*m + i) << T(i,1), T(i,3), T(i,2);\n  }\n  // compute volume of each tet\n  Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> vol;\n  igl::volume(V,T,vol);\n\n  Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> A(F.rows());\n  Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, Eigen::Dynamic> N(F.rows(),3);\n  if (!uniform) {\n    // compute tetrahedron face normals\n    igl::per_face_normals(V,F,N); int norm_rows = N.rows();\n    for (int i = 0; i < norm_rows; i++)\n      N.row(i) /= N.row(i).norm();\n    igl::doublearea(V,F,A); A/=2.;\n  } else {\n    // Use a uniform tetrahedra as a reference, with the same volume as the original one:\n    //\n    // Use normals of the uniform tet (V = h*[0,0,0;1,0,0;0.5,sqrt(3)/2.,0;0.5,sqrt(3)/6.,sqrt(2)/sqrt(3)])\n    //         0         0    1.0000\n    //         0.8165   -0.4714   -0.3333\n    //         0          0.9428   -0.3333\n    //         -0.8165   -0.4714   -0.3333\n    for (int i = 0; i < m; i++) {\n      N.row(0*m+i) << 0,0,1;\n      double a = sqrt(2)*std::cbrt(3*vol(i)); // area of a face in a uniform tet with volume = vol(i)\n      A(0*m+i) = (pow(a,2)*sqrt(3))/4.;\n    }\n    for (int i = 0; i < m; i++) {\n      N.row(1*m+i) << 0.8165,-0.4714,-0.3333;\n      double a = sqrt(2)*std::cbrt(3*vol(i));\n      A(1*m+i) = (pow(a,2)*sqrt(3))/4.;\n    }\n    for (int i = 0; i < m; i++) {\n      N.row(2*m+i) << 0,0.9428,-0.3333;\n      double a = sqrt(2)*std::cbrt(3*vol(i));\n      A(2*m+i) = (pow(a,2)*sqrt(3))/4.;\n    }\n    for (int i = 0; i < m; i++) {\n      N.row(3*m+i) << -0.8165,-0.4714,-0.3333;\n      double a = sqrt(2)*std::cbrt(3*vol(i));\n      A(3*m+i) = (pow(a,2)*sqrt(3))/4.;\n    }\n\n  }\n\n  /*  G = sparse( ...\n      [0*m + repmat(1:m,1,4) ...\n       1*m + repmat(1:m,1,4) ...\n       2*m + repmat(1:m,1,4)], ...\n      repmat([T(:,4);T(:,2);T(:,3);T(:,1)],3,1), ...\n      repmat(A./(3*repmat(vol,4,1)),3,1).*N(:), ...\n      3*m,n);*/\n  std::vector<Triplet<double> > G_t;\n  for (int i = 0; i < 4*m; i++) {\n    int T_j; // j indexes : repmat([T(:,4);T(:,2);T(:,3);T(:,1)],3,1)\n    switch (i/m) {\n      case 0:\n        T_j = 3;\n        break;\n      case 1:\n        T_j = 1;\n        break;\n      case 2:\n        T_j = 2;\n        break;\n      case 3:\n        T_j = 0;\n        break;\n    }\n    int i_idx = i%m;\n    int j_idx = T(i_idx,T_j);\n\n    double val_before_n = A(i)/(3*vol(i_idx));\n    G_t.push_back(Triplet<double>(0*m+i_idx, j_idx, val_before_n * N(i,0)));\n    G_t.push_back(Triplet<double>(1*m+i_idx, j_idx, val_before_n * N(i,1)));\n    G_t.push_back(Triplet<double>(2*m+i_idx, j_idx, val_before_n * N(i,2)));\n  }\n  G.resize(3*m,n);\n  G.setFromTriplets(G_t.begin(), G_t.end());\n}\n\ntemplate <typename DerivedV, typename DerivedF>\nIGL_INLINE void grad_tri(\n  const Eigen::MatrixBase<DerivedV>&V,\n  const Eigen::MatrixBase<DerivedF>&F,\n  Eigen::SparseMatrix<typename DerivedV::Scalar> &G,\n  bool uniform)\n{\n  // Number of faces\n  const int m = F.rows();\n  // Number of vertices\n  const int nv = V.rows();\n  // Number of dimensions\n  const int dims = V.cols();\n  Eigen::Matrix<typename DerivedV::Scalar,Eigen::Dynamic,3>\n    eperp21(m,3), eperp13(m,3);\n\n  for (int i=0;i<m;++i)\n  {\n    // renaming indices of vertices of triangles for convenience\n    int i1 = F(i,0);\n    int i2 = F(i,1);\n    int i3 = F(i,2);\n\n    // #F x 3 matrices of triangle edge vectors, named after opposite vertices\n    typedef Eigen::Matrix<typename DerivedV::Scalar, 1, 3> RowVector3S;\n    RowVector3S v32 = RowVector3S::Zero(1,3);\n    RowVector3S v13 = RowVector3S::Zero(1,3);\n    RowVector3S v21 = RowVector3S::Zero(1,3);\n    v32.head(V.cols()) = V.row(i3) - V.row(i2);\n    v13.head(V.cols()) = V.row(i1) - V.row(i3);\n    v21.head(V.cols()) = V.row(i2) - V.row(i1);\n    RowVector3S n = v32.cross(v13);\n    // area of parallelogram is twice area of triangle\n    // area of parallelogram is || v1 x v2 ||\n    // This does correct l2 norm of rows, so that it contains #F list of twice\n    // triangle areas\n    double dblA = std::sqrt(n.dot(n));\n    Eigen::Matrix<typename DerivedV::Scalar, 1, 3> u(0,0,1);\n    if (!uniform) {\n      // now normalize normals to get unit normals\n      u = n / dblA;\n    } else {\n      // Abstract equilateral triangle v1=(0,0), v2=(h,0), v3=(h/2, (sqrt(3)/2)*h)\n\n      // get h (by the area of the triangle)\n      double h = sqrt( (dblA)/sin(igl::PI / 3.0)); // (h^2*sin(60))/2. = Area => h = sqrt(2*Area/sin_60)\n\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 1> v1,v2,v3;\n      v1 << 0,0,0;\n      v2 << h,0,0;\n      v3 << h/2.,(sqrt(3)/2.)*h,0;\n\n      // now fix v32,v13,v21 and the normal\n      v32 = v3-v2;\n      v13 = v1-v3;\n      v21 = v2-v1;\n      n = v32.cross(v13);\n    }\n\n    // rotate each vector 90 degrees around normal\n    double norm21 = std::sqrt(v21.dot(v21));\n    double norm13 = std::sqrt(v13.dot(v13));\n    eperp21.row(i) = u.cross(v21);\n    eperp21.row(i) = eperp21.row(i) / std::sqrt(eperp21.row(i).dot(eperp21.row(i)));\n    eperp21.row(i) *= norm21 / dblA;\n    eperp13.row(i) = u.cross(v13);\n    eperp13.row(i) = eperp13.row(i) / std::sqrt(eperp13.row(i).dot(eperp13.row(i)));\n    eperp13.row(i) *= norm13 / dblA;\n  }\n\n  // create sparse gradient operator matrix\n  G.resize(dims*m,nv);\n  std::vector<Eigen::Triplet<typename DerivedV::Scalar> > Gijv;\n  Gijv.reserve(4*dims*m);\n  for(int f = 0;f<F.rows();f++)\n  {\n    for(int d = 0;d<dims;d++)\n    {\n      Gijv.emplace_back(f+d*m,F(f,1), eperp13(f,d));\n      Gijv.emplace_back(f+d*m,F(f,0),-eperp13(f,d));\n      Gijv.emplace_back(f+d*m,F(f,2), eperp21(f,d));\n      Gijv.emplace_back(f+d*m,F(f,0),-eperp21(f,d));\n    }\n  }\n  G.setFromTriplets(Gijv.begin(), Gijv.end());\n}\n\n} // anonymous namespace\n\n} // namespace igl\n\ntemplate <typename DerivedV, typename DerivedF>\nIGL_INLINE void igl::grad(\n  const Eigen::MatrixBase<DerivedV>&V,\n  const Eigen::MatrixBase<DerivedF>&F,\n  Eigen::SparseMatrix<typename DerivedV::Scalar> &G,\n  bool uniform)\n{\n  assert(F.cols() == 3 || F.cols() == 4);\n  switch(F.cols())\n  {\n    case 3:\n      return grad_tri(V,F,G,uniform);\n    case 4:\n      return grad_tet(V,F,G,uniform);\n    default:\n      assert(false);\n  }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\n// generated by autoexplicit.sh\ntemplate void igl::grad<Eigen::Matrix<double, -1, 2, 0, -1, 2>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 2, 0, -1, 2> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::SparseMatrix<Eigen::Matrix<double, -1, 2, 0, -1, 2>::Scalar, 0, int>&, bool);\ntemplate void igl::grad<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::SparseMatrix<Eigen::Matrix<double, -1, -1, 0, -1, -1>::Scalar, 0, int>&, bool);\ntemplate void igl::grad<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::SparseMatrix<Eigen::Matrix<double, -1, 3, 0, -1, 3>::Scalar, 0, int>&, bool);\n#endif\n", "meta": {"hexsha": "ab1a52fa0fab3a5173456d0e45cbe481aab77785", "size": 8367, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/grad.cpp", "max_stars_repo_name": "danatzmi/Animation-Assignment2", "max_stars_repo_head_hexsha": "7461b57ad51d61814cd1f467863a431c7c08d84f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "igl/grad.cpp", "max_issues_repo_name": "danatzmi/Animation-Assignment2", "max_issues_repo_head_hexsha": "7461b57ad51d61814cd1f467863a431c7c08d84f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "igl/grad.cpp", "max_forks_repo_name": "danatzmi/Animation-Assignment2", "max_forks_repo_head_hexsha": "7461b57ad51d61814cd1f467863a431c7c08d84f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 34.7178423237, "max_line_length": 327, "alphanum_fraction": 0.5685430859, "num_tokens": 3055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.42346883019322323}}
{"text": "/*=============================================================================\nCopyright 2020 Syed Ali Hasan <alihasan9922@gmail.com>\n\nDistributed under the Boost Software License, Version 1.0. (See accompanying\nfile License.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n\n#ifndef BOOST_ASTRONOMY_EQUATORIAL_HA_COORD_HPP\n#define BOOST_ASTRONOMY_EQUATORIAL_HA_COORD_HPP\n\n#include <iostream>\n#include <boost/static_assert.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/units/get_dimension.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/units/systems/si/plane_angle.hpp>\n#include <boost/units/systems/si/dimensionless.hpp>\n#include <boost/units/physical_dimensions/plane_angle.hpp>\n#include <boost/astronomy/coordinate/coord_sys/coord_sys.hpp>\n\n/**\n * The Equatorial Coordinates, are referred to the plane of the Earth’s equator\n *\n * Declination\n * Declination is analogous to latitude and indicates how far away an object is\n * from the celestial equator. Declination is int the range ±90◦ with positive\n * angles indicating locations north of the celestial equator and negative angles\n * indicating locations south of the celestial equator. Because declination is\n * measured with respect to the celestial equator, and the celestial equator’s\n * location does not vary with time of day or an observer’s location, declination\n * for an object is fixed and does not vary with the time of day or an\n * observer’s location.\n *\n * Hour Angle\n * If we use an observer’s meridian instead of the celestial prime meridian as a reference point,\n * we have another way to measure “celestial longitude\" called “hour angle” (H). While right ascension\n * is an angular measurement (although expressed in HMS format) of an object’s distance from the First\n * Point of Aries, hour angle is very much a time measurement. The hour angle for an object is a measure\n * of how long it has been since the object crossed an observer’s meridian.\n * Because of the way that an hour angle is defined (i.e., relative to an observer’s local celestial meridian),\n * it varies both with time of day and an observer’s location.\n *\n**/\n\nnamespace boost { namespace astronomy { namespace coordinate {\n\nnamespace bu = boost::units;\nnamespace bg = boost::geometry;\n\ntemplate\n<\n    typename CoordinateType = double,\n    typename HourAngleQuantity = bu::quantity<bu::si::plane_angle, CoordinateType>,\n    typename Declination = bu::quantity<bu::si::plane_angle, CoordinateType>\n>\nstruct equatorial_ha_coord : public coord_sys\n       <2, bg::cs::spherical<bg::radian>, CoordinateType>\n{\n  ///@cond INTERNAL\n  BOOST_STATIC_ASSERT_MSG(\n      ((std::is_same<typename bu::get_dimension<HourAngleQuantity>::type,\n          bu::plane_angle_dimension>::value) &&\n       (std::is_same<typename bu::get_dimension<Declination>::type,\n           bu::plane_angle_dimension>::value)),\n      \"Hour Angle and Declination must be of plane angle type\");\n  BOOST_STATIC_ASSERT_MSG((std::is_floating_point<CoordinateType>::value),\n                          \"CoordinateType must be a floating-point type\");\n  ///@endcond\npublic:\n    typedef HourAngleQuantity quantity1;\n    typedef Declination quantity2;\n\n    //Default constructor\n    equatorial_ha_coord() {}\n\n    equatorial_ha_coord\n        (\n            HourAngleQuantity const &Ha,\n            Declination const &Dec\n        )\n    {\n      this->set_ha_dec(Ha, Dec);\n    }\n\n    //Create tuple of Hour Angle and Declination\n    std::tuple<HourAngleQuantity, Declination> get_ha_dec() const\n    {\n      return std::make_tuple(this->get_ha(), this->get_dec());\n    }\n\n    //Get Hour Angle\n    HourAngleQuantity get_ha() const\n    {\n      return static_cast<HourAngleQuantity>\n      (\n          bu::quantity<bu::si::plane_angle, CoordinateType>::from_value\n              (bg::get<0>(this->point))\n      );\n    }\n\n    //Get Declination\n    Declination get_dec() const\n    {\n      return static_cast<Declination>\n      (\n          bu::quantity<bu::si::plane_angle, CoordinateType>::from_value\n              (bg::get<1>(this->point))\n      );\n    }\n\n    //Set value of Hour Angle and Declination\n    void set_ha_dec\n        (\n            HourAngleQuantity const &Ha,\n            Declination const &Dec\n        )\n    {\n      this->set_ha(Ha);\n      this->set_dec(Dec);\n    }\n\n    //Set Hour Angle\n    void set_ha(HourAngleQuantity const &Ha)\n    {\n      bg::set<0>\n          (\n              this->point,\n              static_cast<bu::quantity<bu::si::plane_angle, CoordinateType>>(Ha).value()\n          );\n    }\n\n    //Set Declination\n    void set_dec(Declination const &Dec)\n    {\n      bg::set<1>\n          (\n              this->point,\n              static_cast<bu::quantity<bu::si::plane_angle, CoordinateType>>(Dec).value()\n          );\n    }\n\n}; //equatorial_ha_coord\n\n//Make Equatorial Coordinate\ntemplate\n<\n    typename CoordinateType,\n    template<typename Unit2, typename CoordinateType_> class HourAngleQuantity,\n    template<typename Unit1, typename CoordinateType_> class Declination,\n    typename Unit1,\n    typename Unit2\n>\nequatorial_ha_coord\n<\n    CoordinateType,\n    Declination<Unit1, CoordinateType>,\n    HourAngleQuantity<Unit2, CoordinateType>\n> make_equatorial_ha_coord\n(\n    HourAngleQuantity<Unit2, CoordinateType> const &Ha,\n    Declination<Unit1, CoordinateType> const &Dec\n)\n{\n  return equatorial_ha_coord\n      <\n          CoordinateType,\n          HourAngleQuantity<Unit2, CoordinateType>,\n          Declination<Unit1, CoordinateType>\n      > (Ha, Dec);\n}\n\n//Print Equatorial Hour Angle Coordinates\ntemplate\n<\n    typename CoordinateType,\n    class HourAngleQuantity,\n    class Declination\n>\nstd::ostream &operator << (std::ostream &out, equatorial_ha_coord\n                          <CoordinateType, HourAngleQuantity, Declination> const &point) {\n  out << \"Equatorial Coordinate (Hour Angle: \"\n      << point.get_ha() << \", Declination: \"\n      << point.get_dec() << \")\";\n\n  return out;\n}\n\n}}}\n\n#endif  // BOOST_ASTRONOMY_EQUATORIAL_HA_COORD_HPP\n", "meta": {"hexsha": "131bd5f5d7c79d431475271ee1ea9884aba79f23", "size": 6086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/coordinate/coord_sys/equatorial_ha_coord.hpp", "max_stars_repo_name": "lpranam/Astronomy", "max_stars_repo_head_hexsha": "63aa055a3ce849210680451d81db4cc1ddc8d402", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-14T08:23:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-23T05:26:19.000Z", "max_issues_repo_path": "include/boost/astronomy/coordinate/coord_sys/equatorial_ha_coord.hpp", "max_issues_repo_name": "Zyro9922/astronomy", "max_issues_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/astronomy/coordinate/coord_sys/equatorial_ha_coord.hpp", "max_forks_repo_name": "Zyro9922/astronomy", "max_forks_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8638743455, "max_line_length": 111, "alphanum_fraction": 0.6713769307, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.42346882243528905}}
{"text": "// Ben Martin\n// October 11, 2005\n\n// This currently works only on undirected graphs...\n// Graph must model Adjacency Graph, Incidence Graph, VertexListGraph\n\n\n\n#ifndef BOOST_GRAPH_SPECTRAL_EMBEDDING_LAYOUT_HPP\n#define BOOST_GRAPH_SPECTRAL_EMBEDDING_LAYOUT_HPP\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/properties.hpp>\n#include <vecLib/clapack.h>\n//#include \"f2c.h\"\n//#include \"cblas.h\"\n//#include \"clapack.h\"\n#include <utility> // for pair\n//#include <boost/graph/point2d.hpp>\n//#include <boost/graph/point3d.hpp>\n#include <iostream.h>\n\ntypedef long int integer;\ntypedef double doublereal;\n\nnamespace boost {\n\n  template <typename Graph, typename PositionMap>\n  void spectral_embedding_layout(Graph& g, PositionMap pos_map) {\n\n    typedef typename property_map<Graph, vertex_index_t>::const_type IndexMap;\n    typedef typename Graph::vertex_iterator VertexIterator;\n    typedef typename boost::graph_traits<Graph>::adjacency_iterator AdjacencyIterator;\n    \n    IndexMap index_map = get(vertex_index, g);\n\n    VertexIterator v, vs, ve;\n    using std::pair;\n    std::pair<VertexIterator, VertexIterator> p;\n    p = vertices(g);\n    vs = p.first;\n    ve = p.second;\n    \n    integer N = num_vertices(g);\n\n    doublereal *A;\n    //    A = (doublereal*)malloc( N*N*sizeof(double) );\n    A = new double[N * N];\n    \n    int i;\n    \n    AdjacencyIterator a, as, ae;\n    std::pair<AdjacencyIterator, AdjacencyIterator> ap;\n    \n    for (i = 0; i < N * N; i++)\n      A[i] = 0;\n    i = 0;\n    for (v = vs; v != ve; ++v) {\n      A[(index_map[*v] * N) + index_map[*v]] = (doublereal)out_degree(*v, g);\n      ap = adjacent_vertices(*v, g);\n      as = ap.first;\n      ae = ap.second;\n      for (a = as; a != ae; ++a) {\n\tA[index_map[*v] + index_map[*a]*N] = (doublereal)(-1);\n\tA[index_map[*v]*N + index_map[*a]] = (doublereal)(-1);\n      }\n\n      pos_map[*v][0] = i;\n      pos_map[*v][1] = i;\n      \n      i++;\n    }\n    \n\n    /*\n    cout << \"index_map = \" << endl;\n    for (v = vs; v != ve; ++v) {\n      cout << index_map[*v] << \" \";\n    }\n    cout << endl;\n    cout << \"A = \" << endl;\n    for (i = 0; i < N; i++)\n    {\n      for (int j = 0; j < N; j++)\n      {\n        cout << A[i*N + j] << \" \";\n      }\n        cout << endl;\n    }\n    */\n\n    // Set up the 8 billion parameters for CLAPACK\n    char   JOBZ   = 'v';\n    char   RANGE  = 'i';\n    char   UPLO   = 'l'; // arbitrary at the moment...\n    // N is defined\n    // A is defined\n    integer    LDA    = N;\n    doublereal VL     = 0; // not needed\n    doublereal VU     = 0; // not needed\n    integer    IL     = 2;// 1; // first NON-ZERO eigenvalue\n    integer    IU     = 3;// N; // 4 for the 3d case\n    //    char   dlamch_cmach = 's';\n\n    doublereal ABSTOL = 0.01;// dlamch_(&dlamch_cmach); // most likely SEVERE OVERKILL\n    integer    M = (IU - IL + 1); // N; // should come back 2 or 3 (for 2d, 3d respectively)\n    doublereal *W = new double[N]; // the eigenvalues\n    doublereal *Z = new double[N*M]; // the eigenvectors\n    integer    LDZ = N;\n    integer    *ISUPPZ = new integer[2*M];// (integer*)0; // = new int[2*(IU-IL+1)]; ??? Not needed?\n    doublereal *WORK = new double[26*N]; // should this be allocated?\n    integer    LWORK  = 26*N; // -1\n    integer    *IWORK = new integer[10*N];\n    integer    LIWORK = 10*N; // -1\n    integer    INFO;\n\n    //    dstegr_()\n    dsyevr_(&JOBZ, &RANGE, &UPLO, &N, A, &LDA, &VL, &VU, &IL, &IU, &ABSTOL,\n            &M, W, Z, &LDZ, ISUPPZ, WORK, &LWORK, IWORK, &LIWORK, &INFO);\n\n    /*\n    cout << \"N = \" << N << endl; \n    cout << \"IL = \" << INFO << endl; \n    cout << \"IU = \" << INFO << endl; \n\n    cout << \"INFO = \" << INFO << endl; \n    cout << \"M = \" << M << endl; \n    \n    cout << \"W = \";\n    for (i = 0; i < M; i++)\n      cout << W[i] << \" \";\n    cout << endl;\n    for (i = 0; i < M; i++)\n      for (int j = 0; j < N; j++)\n      {\n        cout << Z[i*N + j] << \"\";\n        cout << endl;\n      }\n    */\n\n    // Set position based on eigenvectors\n    i = 0;\n    for (v = vs; v != ve; ++v)\n    {\n      pos_map[*v][0] = Z[0*LDZ + i];\n      i++;\n    }\n    i = 0;\n    for (v = vs; v != ve; ++v)\n    {\n      pos_map[*v][1] = Z[1*LDZ + i];\n      i++;\n    }\n    \n  } // end spectral_embedding_layout()\n  \n} // end namespace boost\n\n#endif // BOOST_GRAPH_SPECTRAL_EMBEDDING_LAYOUT_HPP\n\n", "meta": {"hexsha": "7d73ab1ccdac1900e5b887af6f97989764992b0f", "size": 4354, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/spectral_embedding_layout.hpp", "max_stars_repo_name": "erwinvaneijk/bgl-python", "max_stars_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-06-19T08:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T11:09:05.000Z", "max_issues_repo_path": "boost/graph/spectral_embedding_layout.hpp", "max_issues_repo_name": "erwinvaneijk/bgl-python", "max_issues_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/graph/spectral_embedding_layout.hpp", "max_forks_repo_name": "erwinvaneijk/bgl-python", "max_forks_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-07-13T07:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T15:08:03.000Z", "avg_line_length": 26.8765432099, "max_line_length": 100, "alphanum_fraction": 0.5411116215, "num_tokens": 1414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4234295066831888}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2011 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef TRACKINGCONTROLIPOPT_HH\n#define TRACKINGCONTROLIPOPT_HH\n\n#include <memory>\n#include <algorithm>\n#include <cstdlib>\n\n#include <boost/timer.hpp>\n\n#include \"IpTNLP.hpp\"\n#include \"variationalproblemutil.hh\"\n\nstruct FirstLess \n{\n  template <class T>\n  bool operator()(std::pair<T,T> const& p) const { return p.first < p.second; }\n};\n\n\n\n/**\n * Ipopt interface implementation for optimal control problems. This\n * adapts Galerkin operator representations from variational\n * functionals to Ipopt.  Since Ipopt requires not only value and\n * derivatives of the Lagrange functional, the primal variables are\n * split into two quasi-identical groups: those that enter the cost\n * functional (u,y) and those that enter the constraints (v,z).\n */\ntemplate <class GOP>\nclass TrackingControlInterface: public Ipopt::TNLP \n{\n  typedef GOP Gop;\n  typedef typename Gop::RT RT;\n  typedef typename Gop::VariableSet VarSet;\n  typedef typename VarSet::Grid Grid;\n  typedef typename Gop::Functional Functional;\n  \n  typedef Ipopt::Index Index;\n  typedef Ipopt::TNLP::IndexStyleEnum IndexStyleEnum;\n  typedef Ipopt::SolverReturn SolverReturn;\n  typedef Ipopt::Number Number;\n  \n\n  enum { U=0, Y, V, Z, LAMBDA, END};\n  typedef int AssemblyParts;\n  \n  \n  \npublic:\n  TrackingControlInterface(VarSet const& varSet_,\n                           Functional& f_):\n    varSet(varSet_),\n    gop(varSet),\n    f(f_),\n    nu(varSet.dimension(U,U+1)),\n    ny(varSet.dimension(Y,Y+1)),\n    nl(varSet.dimension(LAMBDA,LAMBDA+1)),\n    n(nu+ny)\n  {}\n  \n  \n  /** overload this method to return the number of variables\n   *  and constraints, and the number of non-zeros in the jacobian and\n   *  the hessian. The index_style parameter lets you specify C or Fortran\n   *  style indexing for the sparse matrix iRow and jCol parameters.\n   *  C_STYLE is 0-based, and FORTRAN_STYLE is 1-based.\n   */\n  virtual bool get_nlp_info(Index& n, Index& m, Index& nnz_jac_g,\n                            Index& nnz_h_lag, IndexStyleEnum& index_style) \n  {\n    std::cout << \"nu=\" << nu << \" ny=\" << ny << \" nl=\" << nl << '\\n';\n\n    n = this->n;\n    m = nl;\n\n    nnz_jac_g = gop.nnz(LAMBDA,LAMBDA+1,V,Z+1,false);\n    \n    int nnz1 = gop.nnz(U,Y+1,U,Y+1,true);\n    int nnz2 = gop.nnz(V,Z+1,V,Z+1,true);\n    int nnzMax = std::max(nnz1,nnz2);\n    \n    std::vector<int> rows(nnzMax), cols(nnzMax);\n    std::vector<RT> data(nnzMax);\n    std::vector<std::pair<int,int> > entries(nnz1+nnz2);\n    \n    gop.toTriplet(U,Y+1,U,Y+1,rows.begin(),cols.begin(),data.begin(),true);\n    for (int i=0; i<nnz1; ++i)\n      entries[i] = std::make_pair(rows[i],cols[i]);\n    gop.toTriplet(V,Z+1,V,Z+1,rows.begin(),cols.begin(),data.begin(),true);\n    for (int i=0; i<nnz2; ++i)\n      entries[i+nnz1] = std::make_pair(rows[i],cols[i]);\n\n    // remove upper diagonal entries\n    entries.erase(std::remove_if(entries.begin(),entries.end(),FirstLess()),entries.end());\n    // remove duplicate entries\n    std::sort(entries.begin(),entries.end());\n    entries.erase(std::unique(entries.begin(),entries.end()),entries.end());\n    \n\n    nnz_h_lag = entries.size();\n\n    index_style = C_STYLE;\n\n    return true;\n  }\n  \n  /** overload this method to return the information about the bound\n   *  on the variables and constraints. The value that indicates\n   *  that a bound does not exist is specified in the parameters\n   *  nlp_lower_bound_inf and nlp_upper_bound_inf.  By default,\n   *  nlp_lower_bound_inf is -1e19 and nlp_upper_bound_inf is\n   *  1e19. (see TNLPAdapter) */\n  virtual bool get_bounds_info(Index n, Number* x_l, Number* x_u,\n                               Index m, Number* g_l, Number* g_u) \n  {\n    assert(n == ny+nu);\n    assert(m == nl);\n\n    f.boxConstraints(x_l+nu,x_u+nu,x_l,x_u);\n    \n    std::fill_n(g_l,nl,0);\n    std::fill_n(g_u,nl,0);\n    \n    return true;\n  }\n  \n  /** overload this method to return the starting point. The bools\n   *  init_x and init_lambda are both inputs and outputs. As inputs,\n   *  they indicate whether or not the algorithm wants you to\n   *  initialize x and lambda respectively. If, for some reason, the\n   *  algorithm wants you to initialize these and you cannot, set\n   *  the respective bool to false.\n   */\n  virtual bool get_starting_point(Index n, bool init_x, Number* x,\n                                  bool init_z, Number* z_L, Number* z_U,\n                                  Index m, bool init_lambda,\n                                  Number* lambda) \n  {\n    if (init_x) {\n      std::fill_n(x,n,0);\n      for (size_t i=0; i<nu; ++i)\n        x[i] = static_cast<Number>(std::rand())/RAND_MAX;\n    }\n    if (init_z) {\n      std::fill_n(z_L,n,1);\n      std::fill_n(z_U,n,1);\n    }\n    if (init_lambda) {\n      std::fill_n(lambda,m,1);\n    }\n    \n\n    return true;\n  }\n  \n\n  /** overload this method to return the value of the objective function */\n  virtual bool eval_f(Index n, const Number* x, bool new_x,\n                      Number& obj_value) \n  {\n    std::vector<Number> lambda(nl,0);\n    assemble(new_x,x,true,&lambda[0],GOP::VALUE);\n\n    obj_value = gop.functional();\n    \n    return true;\n  }\n  \n\n  /** overload this method to return the vector of the gradient of\n   *  the objective w.r.t. x */\n  virtual bool eval_grad_f(Index n, const Number* x, bool new_x,\n                           Number* grad_f) \n  {\n    std::vector<Number> lambda(nl,0);\n    assemble(new_x,x,true,&lambda[0],GOP::RHS);\n\n    ToSequence<U,LAMBDA>::call(gop,grad_f);\n\n    return true;\n  }\n  \n\n  /** overload this method to return the vector of constraint values */\n  virtual bool eval_g(Index n, const Number* x, bool new_x,\n                      Index m, Number* g) \n  {\n    assemble(new_x,x,false,0,GOP::RHS);\n\n    ToSequence<LAMBDA,END>::call(gop,g);\n\n    return true;\n  }\n  \n    \n  /** overload this method to return the jacobian of the\n   *  constraints. The vectors iRow and jCol only need to be set\n   *  once. The first call is used to set the structure only (iRow\n   *  and jCol will be non-NULL, and values will be NULL) For\n   *  subsequent calls, iRow and jCol will be NULL. */\n  virtual bool eval_jac_g(Index n, const Number* x, bool new_x,\n                          Index m, Index nele_jac, Index* iRow,\n                          Index *jCol, Number* values) \n  {\n    if (iRow != 0) {\n      // provide sparsity structure\n      std::vector<RT> data(nele_jac);\n      typename std::vector<RT>::iterator v = data.begin();\n      gop.toTriplet(LAMBDA,END,U,LAMBDA,iRow,jCol,v,false);\n    } else {\n      assert(x);\n      assert(values);\n      \n      assemble(new_x,x,false,0,GOP::MATRIX);\n\n      std::vector<Index> idx(nele_jac);\n      typename std::vector<Index>::iterator i = idx.begin(), j = idx.begin();\n      gop.toTriplet(LAMBDA,END,U,LAMBDA,i,j,values,false);\n    }\n    \n\n    return true;\n  }\n  \n    \n\n  /** overload this method to return the hessian of the\n   *  lagrangian. The vectors iRow and jCol only need to be set once\n   *  (during the first call). The first call is used to set the\n   *  structure only (iRow and jCol will be non-NULL, and values\n   *  will be NULL) For subsequent calls, iRow and jCol will be\n   *  NULL. This matrix is symmetric - specify the lower diagonal\n   *  only.  A default implementation is provided, in case the user\n   *  wants to se quasi-Newton approximations to estimate the second\n   *  derivatives and doesn't not neet to implement this method. */\n  virtual bool eval_h(Index n, const Number* x, bool new_x,\n                      Number obj_factor, Index m, const Number* lambda,\n                      bool new_lambda, Index nele_hess,\n                      Index* iRow, Index* jCol, Number* values) \n  {\n    int nnz = gop.nnz(U,LAMBDA,U,LAMBDA,true);\n    assert(nnz==nele_hess);\n\n    if (values) {\n      if (x || lambda) {\n        // if (lambda) {\n        //   std::cerr << \"set lambda: \";\n        //   std::copy(lambda,lambda+m,std::ostream_iterator<Number>(std::cerr,\" \"));\n        //   std::cerr << '\\n';\n        // }\n        \n        assemble(new_x,x,new_lambda,lambda,GOP::MATRIX,obj_factor);\n      } else\n        std::cerr << \"eval_h called without x or lambda\\n\";\n      \n      std::vector<int> unused(nnz);\n      std::vector<int>::iterator ri = unused.begin(), ci = unused.begin();\n      gop.toTriplet(U,LAMBDA,U,LAMBDA,ri,ci,values,true);\n    } else {\n      std::vector<RT> unused(nnz);\n      gop.toTriplet(U,LAMBDA,U,LAMBDA,iRow,jCol,unused.begin(),true);\n    }\n\n    return true;\n  }\n  \n    \n\n  /** This method is called when the algorithm is complete so the TNLP can store/write the solution */\n  virtual void finalize_solution(SolverReturn status,\n                                 Index n, const Number* x, const Number* z_L, const Number* z_U,\n                                 Index m, const Number* g, const Number* lambda,\n                                 Number obj_value) \n  {\n    int nnz = gop.nnz(U,END,U,END,false);\n    std::vector<size_t> ri(nnz), ci(nnz);\n    std::vector<double> di(nnz);\n    gop.toTriplet(U,END,U,END,ri.begin(),ci.begin(),di.begin(),false);\n    \n    std::ofstream out(\"result.m\");\n    out << \"function [A] = result()\\n\"\n        << \"ri = [\\n\";\n    std::copy(ri.begin(),ri.end(),std::ostream_iterator<size_t>(out,\"\\n\"));\n    out << \"];\\nci = [\\n\";\n    std::copy(ci.begin(),ci.end(),std::ostream_iterator<size_t>(out,\"\\n\"));\n    out << \"];\\ndi = [\\n\";\n    std::copy(di.begin(),di.end(),std::ostream_iterator<double>(out,\"\\n\"));\n    out << \"];\\n\"\n        << \"A = spconvert([ri+1 ci+1 di]);\\n\";\n    \n\n\n    std::vector<RT> data(n+nl,0);\n    std::copy(x,x+n,data.begin());\n    if (lambda)\n      std::copy(lambda,lambda+nl,data.begin()+n);\n    f.vars.read(data.begin());\n    writeVTKFile(varSet,f.vars,\"solution\");\n  }\n  \n    \n\n  // /** Intermediate Callback method for the user.  Providing dummy\n  //  *  default implementation.  For details see IntermediateCallBack\n  //  *  in IpNLP.hpp. */\n  // virtual bool intermediate_callback(AlgorithmMode mode,\n  //                                    Index iter, Number obj_value,\n  //                                    Number inf_pr, Number inf_du,\n  //                                    Number mu, Number d_norm,\n  //                                    Number regularization_size,\n  //                                    Number alpha_du, Number alpha_pr,\n  //                                    Index ls_trials,\n  //                                    const IpoptData* ip_data,\n  //                                    IpoptCalculatedQuantities* ip_cq);\n\nprivate:\n  void assemble(bool new_x, Number const* x, bool new_lambda, Number const* lambda, AssemblyParts ap, double sigma = 1.0) \n  {\n    if (new_x || new_lambda || (sigma!=f.ipoptSigma)) {\n      \n      std::vector<RT> data(n+nl);\n      f.vars.write(data.begin());\n      \n      if (new_x) {\n        assert(x);\n        std::copy(x,x+n,data.begin());\n        // std::cout << \"u = \" << x[0] << '\\n';\n        \n      }\n      \n      if (new_lambda) {\n        assert(lambda);\n        std::copy(lambda,lambda+nl,data.begin()+n);\n      }\n      \n      f.vars.read(data.begin());\n      f.ipoptSigma = sigma;\n      \n      // it's more efficient to simultaneously assemble functional/rhs/matrix\n      boost::timer timer;\n      gop.assemble(f);\n\n      // std::cout << \"\\nAssembled (sigma=\" << sigma << \"):\\nu=\";\n      // std::copy(data.begin(),data.begin()+nu,std::ostream_iterator<RT>(std::cout,\" \")); \n      // std::cout << \"\\ny=\"; std::copy(data.begin()+nu,data.begin()+n,std::ostream_iterator<RT>(std::cout,\" \")); \n      // std::cout << \"\\nl=\"; std::copy(data.begin()+n,data.begin()+n+nl,std::ostream_iterator<RT>(std::cout,\" \"));\n      // toSequence<0,3>(gop,data.begin());\n      // std::cout << \"\\nLagrange gradient:\\ndu=\"; std::copy(data.begin(),data.begin()+nu,std::ostream_iterator<RT>(std::cout,\" \")); \n      // std::cout << \"\\ndy=\"; std::copy(data.begin()+nu,data.begin()+n,std::ostream_iterator<RT>(std::cout,\" \")); \n      // std::cout << \"\\ndl=\"; std::copy(data.begin()+n,data.begin()+n+nl,std::ostream_iterator<RT>(std::cout,\" \"));\n      // std::cout << \"\\n\";      \n\n      //std::cout << \"assembly time: \" << timer.elapsed() << \"s\\n\";\n      // std::cout << \"As. u=[\";\n      // std::cout.precision(2);\n      // std::copy(x+ny,x+ny+nu,std::ostream_iterator<Number>(std::cout,\",\"));\n      // std::cout << \"]\\n\";\n    }\n  }\n  \n\n    \n  VarSet const& varSet;\n  Gop gop;\n  Functional& f;\n  int nu, ny, nl, n;\n};\n\n\n\n#endif\n", "meta": {"hexsha": "c55e41fc0474c7c589079c4f13ace95c6569682c", "size": 13256, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/ipopt/ocipopt.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/ipopt/ocipopt.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/ipopt/ocipopt.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 34.5208333333, "max_line_length": 133, "alphanum_fraction": 0.5654797827, "num_tokens": 3561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.42342950668318874}}
{"text": "/*\n * \n * Copyright (c) Kresimir Fresl 2002 \n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * Author acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n#ifndef BOOST_NUMERIC_BINDINGS_CBLAS_LEVEL_3_HPP\n#define BOOST_NUMERIC_BINDINGS_CBLAS_LEVEL_3_HPP\n\n#include <cassert>\n\n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/traits/type_traits.hpp>\n#include <boost/numeric/bindings/atlas/cblas3_overloads.hpp>\n#include <boost/numeric/bindings/atlas/cblas_enum.hpp>\n#include <boost/type_traits/same_traits.hpp>\n#include <boost/mpl/if.hpp>\n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n#  include <boost/static_assert.hpp>\n#endif\n\nnamespace boost { namespace numeric { namespace bindings { \n\n  namespace atlas {\n\n    // C <- alpha * op (A) * op (B) + beta * C \n    // op (A) == A || A^T || A^H\n    template <typename T, typename MatrA, typename MatrB, typename MatrC>\n    inline\n    void gemm (CBLAS_TRANSPOSE const TransA, CBLAS_TRANSPOSE const TransB, \n               T const& alpha, MatrA const& a, MatrB const& b, \n               T const& beta, MatrC& c\n               )\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrB>::matrix_structure, \n        traits::general_t\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrC>::matrix_structure, \n        traits::general_t\n      >::value)); \n\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::ordering_type,\n        typename traits::matrix_traits<MatrB>::ordering_type\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::ordering_type,\n        typename traits::matrix_traits<MatrC>::ordering_type\n      >::value)); \n#endif \n\n      assert (TransA == CblasNoTrans \n              || TransA == CblasTrans \n              || TransA == CblasConjTrans); \n      assert (TransB == CblasNoTrans \n              || TransB == CblasTrans \n              || TransB == CblasConjTrans); \n\n      int const m = TransA == CblasNoTrans\n        ? traits::matrix_size1 (a)\n        : traits::matrix_size2 (a);\n      int const n = TransB == CblasNoTrans\n        ? traits::matrix_size2 (b)\n        : traits::matrix_size1 (b);\n      int const k = TransA == CblasNoTrans\n        ? traits::matrix_size2 (a)\n        : traits::matrix_size1 (a); \n      assert (m == traits::matrix_size1 (c)); \n      assert (n == traits::matrix_size2 (c)); \n#ifndef NDEBUG\n      int const k1 = TransB == CblasNoTrans\n        ? traits::matrix_size1 (b)\n        : traits::matrix_size2 (b);\n      assert (k == k1); \n#endif\n      // .. what about AtlasConj? \n\n      CBLAS_ORDER const stor_ord\n        = enum_cast<CBLAS_ORDER const>\n        (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n           typename traits::matrix_traits<MatrA>::ordering_type\n#else\n           typename MatrA::orientation_category \n#endif \n         >::value); \n\n      detail::gemm (stor_ord, TransA, TransB, m, n, k, alpha, \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                    traits::matrix_storage (a), \n#else\n                    traits::matrix_storage_const (a), \n#endif\n                    traits::leading_dimension (a),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n                    traits::matrix_storage (b), \n#else\n                    traits::matrix_storage_const (b), \n#endif\n                    traits::leading_dimension (b),\n                    beta, \n                    traits::matrix_storage (c), \n                    traits::leading_dimension (c)); \n    }\n\n\n    // C <- alpha * A * B + beta * C \n    template <typename T, typename MatrA, typename MatrB, typename MatrC>\n    inline\n    void gemm (T const& alpha, MatrA const& a, MatrB const& b, \n               T const& beta, MatrC& c) \n    {\n      gemm (CblasNoTrans, CblasNoTrans, alpha, a, b, beta, c) ;\n    }\n    \n\n    // C <- A * B \n    template <typename MatrA, typename MatrB, typename MatrC>\n    inline\n    void gemm (MatrA const& a, MatrB const& b, MatrC& c) {\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<MatrC>::value_type val_t; \n#else\n      typedef typename MatrC::value_type val_t; \n#endif \n      gemm (CblasNoTrans, CblasNoTrans, (val_t) 1, a, b, (val_t) 0, c);\n    }\n\n\n\n    // C <- alpha * A * B + beta * C \n    // C <- alpha * B * A + beta * C \n    // A == A^T\n\n    namespace detail {\n\n      template <typename T, typename SymmA, typename MatrB, typename MatrC>\n      inline\n      void symm (CBLAS_SIDE const side, CBLAS_UPLO const uplo, \n                 T const& alpha, SymmA const& a, MatrB const& b, \n                 T const& beta, MatrC& c)\n      {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrB>::matrix_structure, \n          traits::general_t\n        >::value));\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrC>::matrix_structure, \n          traits::general_t\n        >::value)); \n\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<SymmA>::ordering_type,\n          typename traits::matrix_traits<MatrB>::ordering_type\n        >::value)); \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<SymmA>::ordering_type,\n          typename traits::matrix_traits<MatrC>::ordering_type\n        >::value)); \n#endif \n\n        assert (side == CblasLeft || side == CblasRight);\n        assert (uplo == CblasUpper || uplo == CblasLower); \n\n        int const m = traits::matrix_size1 (c);\n        int const n = traits::matrix_size2 (c);\n\n        assert (side == CblasLeft \n                ? m == traits::matrix_size1 (a) \n                  && m == traits::matrix_size2 (a)\n                : n == traits::matrix_size1 (a) \n                  && n == traits::matrix_size2 (a)); \n        assert (m == traits::matrix_size1 (b) \n                && n == traits::matrix_size2 (b)); \n\n        CBLAS_ORDER const stor_ord\n          = enum_cast<CBLAS_ORDER const>\n          (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n            typename traits::matrix_traits<SymmA>::ordering_type\n#else\n            typename SymmA::orientation_category \n#endif \n           >::value); \n\n        symm (stor_ord, side, uplo,  \n              m, n, alpha, \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n              traits::matrix_storage (a), \n#else\n              traits::matrix_storage_const (a), \n#endif\n              traits::leading_dimension (a),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n              traits::matrix_storage (b), \n#else\n              traits::matrix_storage_const (b), \n#endif\n              traits::leading_dimension (b),\n              beta, \n              traits::matrix_storage (c), \n              traits::leading_dimension (c)); \n      }\n\n    } // detail \n \n    // C <- alpha * A * B + beta * C \n    // C <- alpha * B * A + beta * C \n    // A == A^T\n    template <typename T, typename SymmA, typename MatrB, typename MatrC>\n    inline\n    void symm (CBLAS_SIDE const side, CBLAS_UPLO const uplo, \n               T const& alpha, SymmA const& a, MatrB const& b, \n               T const& beta, MatrC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      detail::symm (side, uplo, alpha, a, b, beta, c); \n    }\n\n    template <typename T, typename SymmA, typename MatrB, typename MatrC>\n    inline\n    void symm (CBLAS_SIDE const side, \n               T const& alpha, SymmA const& a, MatrB const& b, \n               T const& beta, MatrC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmA>::matrix_structure, \n        traits::symmetric_t\n      >::value)); \n#endif \n\n      CBLAS_UPLO const uplo\n        = enum_cast<CBLAS_UPLO const>\n        (uplo_triang<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n          typename traits::matrix_traits<SymmA>::uplo_type\n#else\n          typename SymmA::packed_category \n#endif \n         >::value); \n\n      detail::symm (side, uplo, alpha, a, b, beta, c); \n    }\n\n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n\n    namespace detail {\n\n      // C <- alpha * A * B + beta * C ;  A == A^T\n      struct symm_left {\n        template <typename T, typename SymmA, typename MatrB, typename MatrC>\n        static void f (T const& alpha, SymmA const& a, MatrB const& b, \n                       T const& beta, MatrC& c) \n        {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n          BOOST_STATIC_ASSERT((boost::is_same<\n            typename traits::matrix_traits<SymmA>::matrix_structure, \n            traits::symmetric_t\n          >::value)); \n          BOOST_STATIC_ASSERT((boost::is_same<\n            typename traits::matrix_traits<MatrB>::matrix_structure, \n            traits::general_t\n          >::value));\n#endif \n\n          int const m = traits::matrix_size1 (c);\n          int const n = traits::matrix_size2 (c);\n\n          assert (m == traits::matrix_size1 (a) \n                  && m == traits::matrix_size2 (a)); \n          assert (m == traits::matrix_size1 (b) \n                  && n == traits::matrix_size2 (b)); \n\n          CBLAS_ORDER const stor_ord\n            = enum_cast<CBLAS_ORDER const>\n            (storage_order<\n              typename traits::matrix_traits<SymmA>::ordering_type\n             >::value); \n\n          CBLAS_UPLO const uplo\n            = enum_cast<CBLAS_UPLO const>\n            (uplo_triang<\n              typename traits::matrix_traits<SymmA>::uplo_type\n             >::value); \n\n          symm (stor_ord, CblasLeft, uplo,  \n                m, n, alpha, \n                traits::matrix_storage (a), traits::leading_dimension (a),\n                traits::matrix_storage (b), traits::leading_dimension (b),\n                beta, \n                traits::matrix_storage (c), traits::leading_dimension (c)); \n        }\n      }; \n\n      // C <- alpha * A * B + beta * C ;  B == B^T\n      struct symm_right {\n        template <typename T, typename MatrA, typename SymmB, typename MatrC>\n        static void f (T const& alpha, MatrA const& a, SymmB const& b, \n                       T const& beta, MatrC& c) \n        {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n          BOOST_STATIC_ASSERT((boost::is_same<\n            typename traits::matrix_traits<MatrA>::matrix_structure, \n            traits::general_t\n          >::value));\n          BOOST_STATIC_ASSERT((boost::is_same<\n            typename traits::matrix_traits<SymmB>::matrix_structure, \n            traits::symmetric_t\n          >::value));\n#endif \n\n          int const m = traits::matrix_size1 (c);\n          int const n = traits::matrix_size2 (c);\n\n          assert (n == traits::matrix_size1 (b) \n                  && n == traits::matrix_size2 (b)); \n          assert (m == traits::matrix_size1 (a) \n                  && n == traits::matrix_size2 (a)); \n\n          CBLAS_ORDER const stor_ord\n            = enum_cast<CBLAS_ORDER const>\n            (storage_order<\n              typename traits::matrix_traits<SymmB>::ordering_type\n             >::value); \n \n          CBLAS_UPLO const uplo\n            = enum_cast<CBLAS_UPLO const>\n            (uplo_triang<\n              typename traits::matrix_traits<SymmB>::uplo_type\n             >::value); \n\n          symm (stor_ord, CblasRight, uplo,  \n                m, n, alpha, \n                traits::matrix_storage (b), traits::leading_dimension (b),\n                traits::matrix_storage (a), traits::leading_dimension (a),\n                beta, \n                traits::matrix_storage (c), traits::leading_dimension (c)); \n        }\n      }; \n\n    } // detail \n    \n    // C <- alpha * A * B + beta * C \n    // C <- alpha * B * A + beta * C \n    // A == A^T\n    template <typename T, typename MatrA, typename MatrB, typename MatrC>\n    inline\n    void symm (T const& alpha, MatrA const& a, MatrB const& b, \n               T const& beta, MatrC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrC>::matrix_structure, \n        traits::general_t\n      >::value)); \n\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::ordering_type,\n        typename traits::matrix_traits<MatrB>::ordering_type\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::ordering_type,\n        typename traits::matrix_traits<MatrC>::ordering_type\n      >::value)); \n#endif \n\n      typedef typename\n        boost::mpl::if_c<\n          boost::is_same<\n            typename traits::matrix_traits<MatrA>::matrix_structure, \n            traits::symmetric_t\n          >::value,\n          detail::symm_left, \n          detail::symm_right\n        >::type functor; \n\n      functor::f (alpha, a, b, beta, c); \n    }\n\n    // C <- A * B  \n    // C <- B * A  \n    template <typename MatrA, typename MatrB, typename MatrC>\n    inline\n    void symm (MatrA const& a, MatrB const& b, MatrC& c) {\n      typedef typename traits::matrix_traits<MatrC>::value_type val_t; \n      symm ((val_t) 1, a, b, (val_t) 0, c);\n    }\n\n#endif // BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n\n\n\n    // C <- alpha * A * B + beta * C \n    // C <- alpha * B * A + beta * C \n    // A == A^H\n\n    namespace detail {\n\n      template <typename T, typename HermA, typename MatrB, typename MatrC>\n      inline\n      void hemm (CBLAS_SIDE const side, CBLAS_UPLO const uplo, \n                 T const& alpha, HermA const& a, MatrB const& b, \n                 T const& beta, MatrC& c)\n      {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrB>::matrix_structure, \n          traits::general_t\n        >::value));\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrC>::matrix_structure, \n          traits::general_t\n        >::value)); \n\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<HermA>::ordering_type,\n          typename traits::matrix_traits<MatrB>::ordering_type\n        >::value)); \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<HermA>::ordering_type,\n          typename traits::matrix_traits<MatrC>::ordering_type\n        >::value)); \n#endif \n\n        assert (side == CblasLeft || side == CblasRight);\n        assert (uplo == CblasUpper || uplo == CblasLower); \n\n        int const m = traits::matrix_size1 (c);\n        int const n = traits::matrix_size2 (c);\n\n        assert (side == CblasLeft \n                ? m == traits::matrix_size1 (a) \n                  && m == traits::matrix_size2 (a)\n                : n == traits::matrix_size1 (a) \n                  && n == traits::matrix_size2 (a)); \n        assert (m == traits::matrix_size1 (b) \n                && n == traits::matrix_size2 (b)); \n\n        CBLAS_ORDER const stor_ord\n          = enum_cast<CBLAS_ORDER const>\n          (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n            typename traits::matrix_traits<HermA>::ordering_type\n#else\n            typename HermA::orientation_category \n#endif \n           >::value); \n\n        hemm (stor_ord, side, uplo,  \n              m, n, alpha, \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n              traits::matrix_storage (a), \n#else\n              traits::matrix_storage_const (a), \n#endif\n              traits::leading_dimension (a),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n              traits::matrix_storage (b), \n#else\n              traits::matrix_storage_const (b), \n#endif\n              traits::leading_dimension (b),\n              beta, \n              traits::matrix_storage (c), \n              traits::leading_dimension (c)); \n      }\n\n    } // detail \n \n    // C <- alpha * A * B + beta * C \n    // C <- alpha * B * A + beta * C \n    // A == A^H\n    template <typename T, typename HermA, typename MatrB, typename MatrC>\n    inline\n    void hemm (CBLAS_SIDE const side, CBLAS_UPLO const uplo, \n               T const& alpha, HermA const& a, MatrB const& b, \n               T const& beta, MatrC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      detail::hemm (side, uplo, alpha, a, b, beta, c); \n    }\n\n    template <typename T, typename HermA, typename MatrB, typename MatrC>\n    inline\n    void hemm (CBLAS_SIDE const side, \n               T const& alpha, HermA const& a, MatrB const& b, \n               T const& beta, MatrC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermA>::matrix_structure, \n        traits::hermitian_t\n      >::value)); \n#endif \n\n      CBLAS_UPLO const uplo\n        = enum_cast<CBLAS_UPLO const>\n        (uplo_triang<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n          typename traits::matrix_traits<HermA>::uplo_type\n#else\n          typename HermA::packed_category \n#endif \n         >::value); \n\n      detail::hemm (side, uplo, alpha, a, b, beta, c); \n    }\n\n\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n\n    namespace detail {\n\n      // C <- alpha * A * B + beta * C ;  A == A^H\n      struct hemm_left {\n        template <typename T, typename HermA, typename MatrB, typename MatrC>\n        static void f (T const& alpha, HermA const& a, MatrB const& b, \n                       T const& beta, MatrC& c) \n        {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n          BOOST_STATIC_ASSERT((boost::is_same<\n            typename traits::matrix_traits<HermA>::matrix_structure, \n            traits::hermitian_t\n          >::value)); \n          BOOST_STATIC_ASSERT((boost::is_same<\n            typename traits::matrix_traits<MatrB>::matrix_structure, \n            traits::general_t\n          >::value));\n#endif \n\n          int const m = traits::matrix_size1 (c);\n          int const n = traits::matrix_size2 (c);\n\n          assert (m == traits::matrix_size1 (a) \n                  && m == traits::matrix_size2 (a)); \n          assert (m == traits::matrix_size1 (b) \n                  && n == traits::matrix_size2 (b)); \n\n          CBLAS_ORDER const stor_ord\n            = enum_cast<CBLAS_ORDER const>\n            (storage_order<\n              typename traits::matrix_traits<HermA>::ordering_type\n             >::value); \n\n          CBLAS_UPLO const uplo\n            = enum_cast<CBLAS_UPLO const>\n            (uplo_triang<\n              typename traits::matrix_traits<HermA>::uplo_type\n             >::value); \n\n          hemm (stor_ord, CblasLeft, uplo,  \n                m, n, alpha, \n                traits::matrix_storage (a), traits::leading_dimension (a),\n                traits::matrix_storage (b), traits::leading_dimension (b),\n                beta, \n                traits::matrix_storage (c), traits::leading_dimension (c)); \n        }\n      }; \n\n      // C <- alpha * A * B + beta * C ;  B == B^H\n      struct hemm_right {\n        template <typename T, typename MatrA, typename HermB, typename MatrC>\n        static void f (T const& alpha, MatrA const& a, HermB const& b, \n                       T const& beta, MatrC& c) \n        {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n          BOOST_STATIC_ASSERT((boost::is_same<\n            typename traits::matrix_traits<MatrA>::matrix_structure, \n            traits::general_t\n          >::value));\n          BOOST_STATIC_ASSERT((boost::is_same<\n            typename traits::matrix_traits<HermB>::matrix_structure, \n            traits::hermitian_t\n          >::value));\n#endif \n\n          int const m = traits::matrix_size1 (c);\n          int const n = traits::matrix_size2 (c);\n\n          assert (n == traits::matrix_size1 (b) \n                  && n == traits::matrix_size2 (b)); \n          assert (m == traits::matrix_size1 (a) \n                  && n == traits::matrix_size2 (a)); \n\n          CBLAS_ORDER const stor_ord\n            = enum_cast<CBLAS_ORDER const>\n            (storage_order<\n              typename traits::matrix_traits<HermB>::ordering_type\n             >::value); \n \n          CBLAS_UPLO const uplo\n            = enum_cast<CBLAS_UPLO const>\n            (uplo_triang<\n              typename traits::matrix_traits<HermB>::uplo_type\n             >::value); \n\n          hemm (stor_ord, CblasRight, uplo,  \n                m, n, alpha, \n                traits::matrix_storage (b), traits::leading_dimension (b),\n                traits::matrix_storage (a), traits::leading_dimension (a),\n                beta, \n                traits::matrix_storage (c), traits::leading_dimension (c)); \n        }\n      }; \n\n    } \n    \n    template <typename T, typename MatrA, typename MatrB, typename MatrC>\n    inline\n    void hemm (T const& alpha, MatrA const& a, MatrB const& b, \n               T const& beta, MatrC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrC>::matrix_structure, \n        traits::general_t\n      >::value)); \n\n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::ordering_type,\n        typename traits::matrix_traits<MatrB>::ordering_type\n      >::value)); \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<MatrA>::ordering_type,\n        typename traits::matrix_traits<MatrC>::ordering_type\n      >::value)); \n#endif \n\n      typedef typename\n        boost::mpl::if_c<\n          boost::is_same<\n            typename traits::matrix_traits<MatrA>::matrix_structure, \n            traits::hermitian_t\n          >::value,\n          detail::hemm_left, \n          detail::hemm_right\n        >::type functor; \n\n      functor::f (alpha, a, b, beta, c); \n    }\n\n    // C <- A * B  \n    // C <- B * A  \n    template <typename MatrA, typename MatrB, typename MatrC>\n    inline\n    void hemm (MatrA const& a, MatrB const& b, MatrC& c) {\n      typedef typename traits::matrix_traits<MatrC>::value_type val_t; \n      hemm ((val_t) 1, a, b, (val_t) 0, c);\n    }\n\n#endif // BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n\n    \n    // C <- alpha * A * A^T + beta * C\n    // C <- alpha * A^T * A + beta * C\n    // C == C^T\n\n    namespace detail {\n\n      template <typename T, typename MatrA, typename SymmC>\n      inline\n      void syrk (CBLAS_UPLO const uplo, CBLAS_TRANSPOSE trans, \n                 T const& alpha, MatrA const& a, \n                 T const& beta, SymmC& c)\n      {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrA>::matrix_structure, \n          traits::general_t\n        >::value));\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrA>::ordering_type,\n          typename traits::matrix_traits<SymmC>::ordering_type\n        >::value)); \n#endif \n\n        assert (uplo == CblasUpper || uplo == CblasLower); \n        assert (trans == CblasNoTrans \n                || trans == CblasTrans \n                || trans == CblasConjTrans); \n\n        int const n = traits::matrix_size1 (c);\n        assert (n == traits::matrix_size2 (c)); \n        \n        int const k = trans == CblasNoTrans\n          ? traits::matrix_size2 (a)\n          : traits::matrix_size1 (a); \n        assert (n == (trans == CblasNoTrans\n                      ? traits::matrix_size1 (a)\n                      : traits::matrix_size2 (a))); \n\n        CBLAS_ORDER const stor_ord\n          = enum_cast<CBLAS_ORDER const>\n          (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n            typename traits::matrix_traits<SymmC>::ordering_type\n#else\n            typename SymmC::orientation_category \n#endif \n           >::value); \n\n        syrk (stor_ord, uplo, trans, \n              n, k, alpha, \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n              traits::matrix_storage (a), \n#else\n              traits::matrix_storage_const (a), \n#endif\n              traits::leading_dimension (a),\n              beta, \n              traits::matrix_storage (c), \n              traits::leading_dimension (c)); \n      }\n\n    } // detail \n \n    // C <- alpha * A * A^T + beta * C\n    // C <- alpha * A^T * A + beta * C\n    // C == C^T\n    template <typename T, typename MatrA, typename SymmC>\n    inline\n    void syrk (CBLAS_UPLO const uplo, CBLAS_TRANSPOSE trans, \n               T const& alpha, MatrA const& a, \n               T const& beta, SymmC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmC>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      detail::syrk (uplo, trans, alpha, a, beta, c); \n    }\n\n    template <typename T, typename MatrA, typename SymmC>\n    inline\n    void syrk (CBLAS_TRANSPOSE trans, \n               T const& alpha, MatrA const& a, \n               T const& beta, SymmC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmC>::matrix_structure, \n        traits::symmetric_t\n      >::value)); \n#endif \n\n      CBLAS_UPLO const uplo\n        = enum_cast<CBLAS_UPLO const>\n        (uplo_triang<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n          typename traits::matrix_traits<SymmC>::uplo_type\n#else\n          typename SymmC::packed_category \n#endif \n         >::value); \n\n      detail::syrk (uplo, trans, alpha, a, beta, c); \n    }\n\n    // C <- A * A^T + C\n    // C <- A^T * A + C\n    template <typename MatrA, typename SymmC>\n    inline\n    void syrk (CBLAS_TRANSPOSE trans, MatrA const& a, SymmC& c) {\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<SymmC>::value_type val_t; \n#else\n      typedef typename SymmC::value_type val_t; \n#endif \n      syrk (trans, (val_t) 1, a, (val_t) 0, c);\n    }\n\n    \n    // C <- alpha * A * B^T + conj(alpha) * B * A^T + beta * C\n    // C <- alpha * A^T * B + conj(alpha) * B^T * A + beta * C\n    // C == C^T\n\n    namespace detail {\n\n      template <typename T, typename MatrA, typename MatrB, typename SymmC>\n      inline\n      void syr2k (CBLAS_UPLO const uplo, CBLAS_TRANSPOSE trans, \n                  T const& alpha, MatrA const& a, MatrB const& b, \n                  T const& beta, SymmC& c)\n      {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrA>::matrix_structure, \n          traits::general_t\n        >::value));\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrB>::matrix_structure, \n          traits::general_t\n        >::value));\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrA>::ordering_type,\n          typename traits::matrix_traits<SymmC>::ordering_type\n        >::value)); \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrB>::ordering_type,\n          typename traits::matrix_traits<SymmC>::ordering_type\n        >::value)); \n#endif \n\n        assert (uplo == CblasUpper || uplo == CblasLower); \n        assert (trans == CblasNoTrans \n                || trans == CblasTrans \n                || trans == CblasConjTrans); \n\n        int const n = traits::matrix_size1 (c);\n        assert (n == traits::matrix_size2 (c)); \n        \n        int const k = trans == CblasNoTrans\n          ? traits::matrix_size2 (a)\n          : traits::matrix_size1 (a); \n        assert (k == (trans == CblasNoTrans\n                      ? traits::matrix_size2 (b)\n                      : traits::matrix_size1 (b))); \n        assert (n == (trans == CblasNoTrans\n                      ? traits::matrix_size1 (a)\n                      : traits::matrix_size2 (a))); \n        assert (n == (trans == CblasNoTrans\n                      ? traits::matrix_size1 (b)\n                      : traits::matrix_size2 (b))); \n\n        CBLAS_ORDER const stor_ord\n          = enum_cast<CBLAS_ORDER const>\n          (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n            typename traits::matrix_traits<SymmC>::ordering_type\n#else\n            typename SymmC::orientation_category \n#endif \n           >::value); \n\n        syr2k (stor_ord, uplo, trans, \n               n, k, alpha, \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n               traits::matrix_storage (a), \n#else\n               traits::matrix_storage_const (a), \n#endif\n               traits::leading_dimension (a),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n               traits::matrix_storage (b), \n#else\n               traits::matrix_storage_const (b), \n#endif\n               traits::leading_dimension (b),\n               beta, \n               traits::matrix_storage (c), \n               traits::leading_dimension (c)); \n      }\n\n    } // detail \n \n    // C <- alpha * A * B^T + conj(alpha) * B * A^T + beta * C\n    // C <- alpha * A^T * B + conj(alpha) * B^T * A + beta * C\n    // C == C^T\n    template <typename T, typename MatrA, typename MatrB, typename SymmC>\n    inline\n    void syr2k (CBLAS_UPLO const uplo, CBLAS_TRANSPOSE trans, \n               T const& alpha, MatrA const& a, MatrB const& b, \n               T const& beta, SymmC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmC>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      detail::syr2k (uplo, trans, alpha, a, b, beta, c); \n    }\n\n    template <typename T, typename MatrA, typename MatrB, typename SymmC>\n    inline\n    void syr2k (CBLAS_TRANSPOSE trans, \n               T const& alpha, MatrA const& a, MatrB const& b,  \n               T const& beta, SymmC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<SymmC>::matrix_structure, \n        traits::symmetric_t\n      >::value)); \n#endif \n\n      CBLAS_UPLO const uplo\n        = enum_cast<CBLAS_UPLO const>\n        (uplo_triang<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n          typename traits::matrix_traits<SymmC>::uplo_type\n#else\n          typename SymmC::packed_category \n#endif \n         >::value); \n\n      detail::syr2k (uplo, trans, alpha, a, b, beta, c); \n    }\n\n    // C <- A * B^T + B * A^T + C\n    // C <- A^T * B + B^T * A + C\n    template <typename MatrA, typename MatrB, typename SymmC>\n    inline\n    void syr2k (CBLAS_TRANSPOSE trans, \n                MatrA const& a, MatrB const& b, SymmC& c) \n    {\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<SymmC>::value_type val_t; \n#else\n      typedef typename SymmC::value_type val_t; \n#endif \n      syr2k (trans, (val_t) 1, a, b, (val_t) 0, c);\n    }\n\n    \n    // C <- alpha * A * A^H + beta * C\n    // C <- alpha * A^H * A + beta * C\n    // C == C^H\n\n    namespace detail {\n\n      template <typename T, typename MatrA, typename HermC>\n      inline\n      void herk (CBLAS_UPLO const uplo, CBLAS_TRANSPOSE trans, \n                 T const& alpha, MatrA const& a, \n                 T const& beta, HermC& c)\n      {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrA>::matrix_structure, \n          traits::general_t\n        >::value));\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrA>::ordering_type,\n          typename traits::matrix_traits<HermC>::ordering_type\n        >::value)); \n#endif \n\n        assert (uplo == CblasUpper || uplo == CblasLower); \n        assert (trans == CblasNoTrans || trans == CblasConjTrans); \n\n        int const n = traits::matrix_size1 (c);\n        assert (n == traits::matrix_size2 (c)); \n        \n        int const k = trans == CblasNoTrans\n          ? traits::matrix_size2 (a)\n          : traits::matrix_size1 (a); \n        assert (n == (trans == CblasNoTrans\n                      ? traits::matrix_size1 (a)\n                      : traits::matrix_size2 (a))); \n\n        CBLAS_ORDER const stor_ord\n          = enum_cast<CBLAS_ORDER const>\n          (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n            typename traits::matrix_traits<HermC>::ordering_type\n#else\n            typename HermC::orientation_category \n#endif \n           >::value); \n\n        herk (stor_ord, uplo, trans, \n              n, k, alpha, \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n              traits::matrix_storage (a), \n#else\n              traits::matrix_storage_const (a), \n#endif\n              traits::leading_dimension (a),\n              beta, \n              traits::matrix_storage (c), \n              traits::leading_dimension (c)); \n      }\n\n    } // detail \n \n    // C <- alpha * A * A^H + beta * C\n    // C <- alpha * A^H * A + beta * C\n    // C == C^H\n    template <typename T, typename MatrA, typename HermC>\n    inline\n    void herk (CBLAS_UPLO const uplo, CBLAS_TRANSPOSE trans, \n               T const& alpha, MatrA const& a, \n               T const& beta, HermC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermC>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      detail::herk (uplo, trans, alpha, a, beta, c); \n    }\n\n    template <typename T, typename MatrA, typename HermC>\n    inline\n    void herk (CBLAS_TRANSPOSE trans, \n               T const& alpha, MatrA const& a, \n               T const& beta, HermC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermC>::matrix_structure, \n        traits::hermitian_t\n      >::value)); \n#endif \n\n      CBLAS_UPLO const uplo\n        = enum_cast<CBLAS_UPLO const>\n        (uplo_triang<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n          typename traits::matrix_traits<HermC>::uplo_type\n#else\n          typename HermC::packed_category \n#endif \n         >::value); \n\n      detail::herk (uplo, trans, alpha, a, beta, c); \n    }\n\n    // C <- A * A^H + C\n    // C <- A^H * A + C\n    template <typename MatrA, typename HermC>\n    inline\n    void herk (CBLAS_TRANSPOSE trans, MatrA const& a, HermC& c) {\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<HermC>::value_type val_t; \n#else\n      typedef typename HermC::value_type val_t; \n#endif \n      typedef typename traits::type_traits<val_t>::real_type real_t; \n      herk (trans, (real_t) 1, a, (real_t) 0, c);\n    }\n\n\n    // C <- alpha * A * B^H + conj(alpha) * B * A^H + beta * C\n    // C <- alpha * A^H * B + conj(alpha) * B^H * A + beta * C\n    // C == C^H\n\n    namespace detail {\n\n      template <typename T1, typename T2, \n                typename MatrA, typename MatrB, typename HermC>\n      inline\n      void her2k (CBLAS_UPLO const uplo, CBLAS_TRANSPOSE trans, \n                  T1 const& alpha, MatrA const& a, MatrB const& b, \n                  T2 const& beta, HermC& c)\n      {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrA>::matrix_structure, \n          traits::general_t\n        >::value));\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrB>::matrix_structure, \n          traits::general_t\n        >::value));\n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrA>::ordering_type,\n          typename traits::matrix_traits<HermC>::ordering_type\n        >::value)); \n        BOOST_STATIC_ASSERT((boost::is_same<\n          typename traits::matrix_traits<MatrB>::ordering_type,\n          typename traits::matrix_traits<HermC>::ordering_type\n        >::value)); \n#endif \n\n        assert (uplo == CblasUpper || uplo == CblasLower); \n        assert (trans == CblasNoTrans || trans == CblasConjTrans); \n\n        int const n = traits::matrix_size1 (c);\n        assert (n == traits::matrix_size2 (c)); \n        \n        int const k = trans == CblasNoTrans\n          ? traits::matrix_size2 (a)\n          : traits::matrix_size1 (a); \n        assert (k == (trans == CblasNoTrans\n                      ? traits::matrix_size2 (b)\n                      : traits::matrix_size1 (b))); \n        assert (n == (trans == CblasNoTrans\n                      ? traits::matrix_size1 (a)\n                      : traits::matrix_size2 (a))); \n        assert (n == (trans == CblasNoTrans\n                      ? traits::matrix_size1 (b)\n                      : traits::matrix_size2 (b))); \n\n        CBLAS_ORDER const stor_ord\n          = enum_cast<CBLAS_ORDER const>\n          (storage_order<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n            typename traits::matrix_traits<HermC>::ordering_type\n#else\n            typename HermC::orientation_category \n#endif \n           >::value); \n\n        her2k (stor_ord, uplo, trans, \n               n, k, alpha, \n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n               traits::matrix_storage (a), \n#else\n               traits::matrix_storage_const (a), \n#endif\n               traits::leading_dimension (a),\n#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING\n               traits::matrix_storage (b), \n#else\n               traits::matrix_storage_const (b), \n#endif\n               traits::leading_dimension (b),\n               beta, \n               traits::matrix_storage (c), \n               traits::leading_dimension (c)); \n      }\n\n    } // detail \n \n    // C <- alpha * A * B^H + conj(alpha) * B * A^H + beta * C\n    // C <- alpha * A^H * B + conj(alpha) * B^H * A + beta * C\n    // C == C^H\n    template <typename T1, typename T2, \n              typename MatrA, typename MatrB, typename HermC>\n    inline\n    void her2k (CBLAS_UPLO const uplo, CBLAS_TRANSPOSE trans, \n               T1 const& alpha, MatrA const& a, MatrB const& b, \n               T2 const& beta, HermC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermC>::matrix_structure, \n        traits::general_t\n      >::value)); \n#endif \n\n      detail::her2k (uplo, trans, alpha, a, b, beta, c); \n    }\n\n    template <typename T1, typename T2, \n              typename MatrA, typename MatrB, typename HermC>\n    inline\n    void her2k (CBLAS_TRANSPOSE trans, \n               T1 const& alpha, MatrA const& a, MatrB const& b,  \n               T2 const& beta, HermC& c)\n    {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n      BOOST_STATIC_ASSERT((boost::is_same<\n        typename traits::matrix_traits<HermC>::matrix_structure, \n        traits::hermitian_t\n      >::value)); \n#endif \n\n      CBLAS_UPLO const uplo\n        = enum_cast<CBLAS_UPLO const>\n        (uplo_triang<\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n          typename traits::matrix_traits<HermC>::uplo_type\n#else\n          typename HermC::packed_category \n#endif \n         >::value); \n\n      detail::her2k (uplo, trans, alpha, a, b, beta, c); \n    }\n\n    // C <- A * B^H + B * A^H + C\n    // C <- A^H * B + B^H * A + C\n    template <typename MatrA, typename MatrB, typename HermC>\n    inline\n    void her2k (CBLAS_TRANSPOSE trans, \n                MatrA const& a, MatrB const& b, HermC& c) \n    {\n#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS\n      typedef typename traits::matrix_traits<HermC>::value_type val_t; \n#else\n      typedef typename HermC::value_type val_t; \n#endif \n      typedef typename traits::type_traits<val_t>::real_type real_t; \n      her2k (trans, (val_t) 1, a, b, (real_t) 0, c);\n    }\n\n    \n  } // namespace atlas\n\n}}} \n\n#endif // BOOST_NUMERIC_BINDINGS_CBLAS_LEVEL_3_HPP\n", "meta": {"hexsha": "c84652cf6838f96aa8edfa268eccba495b6f4259", "size": 40501, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/boost/numeric/bindings/atlas/cblas3.hpp", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-11-13T16:40:57.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T15:37:19.000Z", "max_issues_repo_path": "openrave/plugins/include/boost/numeric/bindings/atlas/cblas3.hpp", "max_issues_repo_name": "jdsika/holy", "max_issues_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-06-13T01:29:51.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-14T00:38:27.000Z", "max_forks_repo_path": "openrave/plugins/include/boost/numeric/bindings/atlas/cblas3.hpp", "max_forks_repo_name": "jdsika/holy", "max_forks_repo_head_hexsha": "a2ac55fa1751a3a8038cf61d29b95005f36d6264", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-05T20:18:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T20:18:25.000Z", "avg_line_length": 33.143207856, "max_line_length": 77, "alphanum_fraction": 0.5853435718, "num_tokens": 10533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.4234174495093709}}
{"text": "#pragma once\n\n// Switching to Blitz Based Arrays\n#include <blitz/array.h>\n#include <fftw3.h>\n#include <omp.h>\n#include <string.h>\n#include <algorithm>\n#include <cmath>\n#include <complex>\n#include <fstream>\n#include <iostream>\n#include <vector>\n\n// It should be ok at populate namespace with complex\nusing std::complex;\n\nnamespace NDarray {\n\nusing namespace blitz;\n\n// FFT Libraries complex Float\nvoid fftshift(Array<complex<float>, 3> &temp);\nvoid fftshift(Array<complex<float>, 4> &temp);\nvoid fft(Array<complex<float>, 3> &temp);\nvoid fft(Array<complex<float>, 4> &temp);\nvoid ifft(Array<complex<float>, 3> &temp);\nvoid ifft(Array<complex<float>, 4> &temp);\n\nvoid fft(Array<complex<float>, 3> &temp, int);\nvoid ifft(Array<complex<float>, 3> &temp, int);\nvoid fft3(Array<complex<float>, 3> &temp, int, int, bool);\n\nvoid gaussian_filter(Array<float, 2> &, int);\nvoid gaussian_filter(Array<complex<float>, 2> &, int);\ncomplex<float> conj_sum(Array<complex<float>, 3> P, Array<complex<float>, 3> R);\nvoid gaussian_blur(Array<complex<float>, 3> &In, float sigX, float sigY, float sigZ);\nvoid gaussian_blur(Array<float, 3> &In, float sigX, float sigY, float sigZ);\n\ninline void endian_swap(int &x) {\n  x = (x << 24 & 0xFF000000) | (x << 8 & 0x00FF0000) | (x >> 8 & 0x0000FF00) |\n      (x >> 24 & 0x000000FF);\n}\n\ntemplate <typename T, int N>\nvoid ArrayRead(blitz::Array<T, N> &temp, const char *name) {\n  FILE *fid;\n  if ((fid = fopen(name, \"r\")) == NULL) {\n    cout << \"Array:Can't Open \" << name << endl;\n    cout << \"Exiting\" << endl;\n    exit(1);\n  } else {\n    int j;\n    if ((j = fread(temp.data(), sizeof(T), temp.numElements(), fid)) !=\n        (int)(temp.numElements())) {\n      cout << \"Array3:Not enough data: only read \" << j << \"points of\"\n           << temp.numElements() << endl;\n      exit(1);\n    }\n    fclose(fid);\n  }\n}\n\ntemplate <typename T, const int N_rank>\nvoid ArrayWriteMagAppend(Array<complex<T>, N_rank> &temp, const char *name) {\n  ofstream ofs(name, ios_base::binary | ios_base::app);\n\n  for (typename Array<complex<T>, N_rank>::iterator miter = temp.begin();\n       miter != temp.end(); miter++) {\n    T val = abs(*miter);\n    ofs.write((char *)&val, sizeof(T));\n  }\n}\n\ntemplate <typename T, const int N_rank>\nvoid ArrayWriteAppend(Array<T, N_rank> &temp, const char *name) {\n  ofstream ofs(name, ios_base::binary | ios_base::app);\n\n  for (typename Array<T, N_rank>::iterator miter = temp.begin();\n       miter != temp.end(); miter++) {\n    T val = *miter;\n    ofs.write((char *)&val, sizeof(T));\n  }\n}\n\ntemplate <typename T, const int N_rank>\nvoid ArrayWriteAppendAsComplexFloat(Array<T, N_rank> &temp, const char *name) {\n  ofstream ofs(name, ios_base::binary | ios_base::app);\n\n  for (typename Array<T, N_rank>::iterator miter = temp.begin();\n       miter != temp.end(); miter++) {\n    complex<float> val = *miter;\n    ofs.write((char *)&val, sizeof(complex<float>));\n  }\n}\n\ntemplate <typename T>\nvoid ArrayWriteAppendZeros(int number, const char *name) {\n  ofstream ofs(name, ios_base::binary | ios_base::app);\n\n  for (int i = 0; i < number; i++) {\n    T val = (T)0.0;  // Zero is zero for all types!\n    ofs.write((char *)&val, sizeof(T));\n  }\n}\n\ntemplate <typename T, const int N_rank>\nvoid ArrayWrite(Array<T, N_rank> &temp, const char *name) {\n  remove(name);  // This speeds things up considerably\n  ofstream ofs(name, ios_base::binary);\n\n  for (typename Array<T, N_rank>::iterator miter = temp.begin();\n       miter != temp.end(); miter++) {\n    T val = *miter;\n    ofs.write((char *)&val, sizeof(T));\n  }\n}\n\ntemplate <typename T, const int N_rank>\nvoid ArrayWriteMag(Array<complex<T>, N_rank> &temp, const char *name) {\n  remove(name);  // This speeds things up considerably\n  ofstream ofs(name, ios_base::binary);\n  for (typename Array<complex<T>, N_rank>::iterator miter = temp.begin();\n       miter != temp.end(); miter++) {\n    T val = abs(*miter);\n    ofs.write((char *)&val, sizeof(T));\n  }\n}\n\ntemplate <typename T, const int N_rank>\ndouble ArrayEnergy(Array<complex<T>, N_rank> &temp) {\n  double EE = 0;\n  for (typename Array<complex<T>, N_rank>::iterator miter = temp.begin();\n       miter != temp.end(); miter++) {\n    EE += (double)(norm(*miter));\n  }\n  return (EE);\n}\n\ntemplate <typename T, const int N_rank, const int M_rank>\ndouble ArrayEnergy(Array<Array<complex<T>, N_rank>, M_rank> &temp) {\n  double EE = 0;\n  for (typename Array<Array<complex<T>, N_rank>, M_rank>::iterator miter =\n           temp.begin();\n       miter != temp.end(); miter++) {\n    EE += ArrayEnergy(*miter);\n  }\n  return (EE);\n}\n\ntemplate <typename T, const int N_rank>\nvoid ArrayWritePhase(Array<complex<T>, N_rank> &temp, const char *name) {\n  ofstream ofs(name, ios_base::binary);\n\n  for (typename Array<complex<T>, N_rank>::iterator miter = temp.begin();\n       miter != temp.end(); miter++) {\n    T val = arg(*miter);\n    ofs.write((char *)&val, sizeof(T));\n  }\n}\n\ntemplate <typename T, const int N_rank>\nvoid ArrayWritePhaseAppend(Array<complex<T>, N_rank> &temp, const char *name) {\n  ofstream ofs(name, ios_base::binary | ios_base::app);\n\n  for (typename Array<complex<T>, N_rank>::iterator miter = temp.begin();\n       miter != temp.end(); miter++) {\n    T val = arg(*miter);\n    ofs.write((char *)&val, sizeof(T));\n  }\n}\n\ntemplate <typename T, const int N_rank, const int M_rank>\nvoid WriteCFL(Array<Array<T, N_rank>, M_rank> &temp, const char *name,\n              int pad_dim1 = 0) {\n  // Create names for header and binary\n  char name_hdr[2048];\n  char name_bin[2048];\n\n  sprintf(name_hdr, \"%s.hdr\", name);\n  sprintf(name_bin, \"%s.cfl\", name);\n\n  // Now determine the size of the ND array\n  TinyVector<int, M_rank> Dim1 = temp.shape();\n\n  // Loop over all sub-arrays to get the max\n  typename Array<Array<T, N_rank>, M_rank>::iterator miter = temp.begin();\n\n  TinyVector<int, N_rank> Dim2 = (*miter).shape();\n  for (; miter != temp.end(); miter++) {\n    TinyVector<int, N_rank> Dim2_temp = (*miter).shape();\n    for (int i = 0; i < N_rank; i++) {\n      Dim2(i) = max(Dim2(i), Dim2_temp(i));\n    }\n  }\n\n  // Combine the Size to get the total size\n  Array<int, 1> Dim(N_rank + M_rank + pad_dim1);\n  int count = 0;\n  for (int i = 0; i < pad_dim1; i++) {\n    Dim(count) = 1;\n    count++;\n  }\n  for (int i = 0; i < N_rank; i++) {\n    Dim(count) = Dim2(i);\n    count++;\n  }\n  for (int i = 0; i < M_rank; i++) {\n    Dim(count) = Dim1(i);\n    count++;\n  }\n\n  // Debug info (temp)\n  cout << \"File Name = \" << name_bin << endl;\n  cout << \"Header Name = \" << name_hdr << endl;\n  cout << \"Output Size = \" << Dim << endl;\n\n  // Write the header\n  FILE *fid;\n  fid = fopen(name_hdr, \"w\");\n  fprintf(fid, \"# Dimensions\\n\");\n  for (int i = 0; i < M_rank + N_rank; i++) {\n    fprintf(fid, \"%d \", Dim(i));\n  }\n  if ((N_rank + M_rank) < 5) {\n    for (int i = 0; i < (5 - (M_rank + N_rank)); i++) {\n      fprintf(fid, \"%d \", 1);\n    }\n  }\n  fclose(fid);\n\n  // Write the binary data\n  remove(name_bin);\n  int inner_size = product(Dim2);\n  for (typename Array<Array<T, N_rank>, M_rank>::iterator miter = temp.begin();\n       miter != temp.end(); miter++) {\n    ArrayWriteAppendAsComplexFloat((*miter), name_bin);\n\n    // Bart doesn't support container sizes. Just pad with zeros\n    if ((*miter).numElements() < inner_size) {\n      ArrayWriteAppendZeros<complex<float> >(\n          inner_size - (*miter).numElements(), name_bin);\n    }\n  }\n}\n\ntemplate <typename T, const int N_rank>\nvoid WriteCFL(Array<T, N_rank> &temp, const char *name) {\n  // Create names for header and binary\n  char name_hdr[2048];\n  char name_bin[2048];\n\n  sprintf(name_hdr, \"%s.hdr\", name);\n  sprintf(name_bin, \"%s.cfl\", name);\n\n  // Now determine the size of the ND array\n  TinyVector<int, N_rank> Dim = temp.shape();\n\n  // Debug info (temp)\n  cout << \"File Name = \" << name_bin << endl;\n  cout << \"Header Name = \" << name_hdr << endl;\n  cout << \"Output Size = \" << Dim << endl;\n\n  // Write the header\n  FILE *fid;\n  fid = fopen(name_hdr, \"w\");\n  fprintf(fid, \"# Dimensions\\n\");\n  for (int i = 0; i < N_rank; i++) {\n    fprintf(fid, \"%d \", Dim(i));\n  }\n  if ((N_rank) < 5) {\n    for (int i = 0; i < (5 - (N_rank)); i++) {\n      fprintf(fid, \"%d \", 1);\n    }\n  }\n  fclose(fid);\n\n  // Write the binary data\n  remove(name_bin);\n  ArrayWriteAppendAsComplexFloat(temp, name_bin);\n}\n\ntemplate <typename T, const int N_rank, const int M_rank>\nvoid WriteCFL_triplet(Array<Array<T, N_rank>, M_rank> &temp,\n                      Array<Array<T, N_rank>, M_rank> &temp2,\n                      Array<Array<T, N_rank>, M_rank> &temp3,\n                      const char *name) {\n  // Create names for header and binary\n  char name_hdr[2048];\n  char name_bin[2048];\n\n  sprintf(name_hdr, \"%s.hdr\", name);\n  sprintf(name_bin, \"%s.cfl\", name);\n\n  // Now determine the size of the ND array\n  TinyVector<int, M_rank> Dim1 = temp.shape();\n\n  // Loop over all sub-arrays to get the max\n  typename Array<Array<T, N_rank>, M_rank>::iterator miter = temp.begin();\n\n  TinyVector<int, N_rank> Dim2 = (*miter).shape();\n  for (; miter != temp.end(); miter++) {\n    TinyVector<int, N_rank> Dim2_temp = (*miter).shape();\n    for (int i = 0; i < N_rank; i++) {\n      Dim2(i) = max(Dim2(i), Dim2_temp(i));\n    }\n  }\n\n  // Combine the Size to get the total size\n  TinyVector<int, N_rank + M_rank> Dim;\n  for (int i = 0; i < N_rank; i++) {\n    Dim(i) = Dim2(i);\n  }\n  for (int i = 0; i < M_rank; i++) {\n    Dim(i + N_rank) = Dim1(i);\n  }\n\n  TinyVector<int, N_rank + M_rank + 1> DimTriple;\n  DimTriple(0) = 3;\n  for (int i = 0; i < (N_rank + M_rank); i++) {\n    DimTriple(i + 1) = Dim(i);\n  }\n\n  // Debug info (temp)\n  cout << \"File Name = \" << name_bin << endl;\n  cout << \"Header Name = \" << name_hdr << endl;\n  cout << \"Output Size = \" << Dim << endl;\n\n  // Write the header\n  FILE *fid;\n  fid = fopen(name_hdr, \"w\");\n  fprintf(fid, \"# Dimensions\\n\");\n  for (int i = 0; i < M_rank + N_rank + 1; i++) {\n    fprintf(fid, \"%d \", DimTriple(i));\n  }\n  if ((N_rank + M_rank + 1) < 5) {\n    for (int i = 0; i < (5 - (M_rank + N_rank + 1)); i++) {\n      fprintf(fid, \"%d \", 1);\n    }\n  }\n  fclose(fid);\n\n  // Write the binary data\n  remove(name_bin);\n  int inner_size = product(Dim2);\n  ofstream ofs(name_bin, ios_base::binary | ios_base::app);\n\n  // Three input arrays\n  typename Array<Array<T, N_rank>, M_rank>::iterator miter1 = temp.begin();\n  typename Array<Array<T, N_rank>, M_rank>::iterator miter2 = temp2.begin();\n  typename Array<Array<T, N_rank>, M_rank>::iterator miter3 = temp3.begin();\n  for (; (miter1 != temp.end()); miter1++, miter2++, miter3++) {\n    // Pointers to the the inner array\n    typename Array<T, N_rank>::iterator niter1 = (*miter1).begin();\n    typename Array<T, N_rank>::iterator niter2 = (*miter2).begin();\n    typename Array<T, N_rank>::iterator niter3 = (*miter3).begin();\n\n    for (; (niter1 != (*miter1).end()); niter1++, niter2++, niter3++) {\n      {\n        complex<float> val = *niter1;\n        ofs.write((char *)&val, sizeof(complex<float>));\n      }\n      {\n        complex<float> val = *niter2;\n        ofs.write((char *)&val, sizeof(complex<float>));\n      }\n      {\n        complex<float> val = *niter3;\n        ofs.write((char *)&val, sizeof(complex<float>));\n      }\n    }\n\n    // Bart doesn't support container sizes. Just pad with zeros\n    if ((*miter1).numElements() < inner_size) {\n      ArrayWriteAppendZeros<complex<float> >(\n          3 * (inner_size - (*miter1).numElements()), name_bin);\n    }\n  }\n}\n\ntemplate <typename T>\nArray<Array<T, 3>, 1> Alloc4DContainer(int x, int y, int z, int t) {\n  Array<Array<T, 3>, 1> temp;\n  temp.setStorage(ColumnMajorArray<1>());\n  temp.resize(t);\n\n  for (typename Array<Array<T, 3>, 1>::iterator miter = temp.begin();\n       miter != temp.end(); miter++) {\n    (*miter).setStorage(ColumnMajorArray<3>());\n    (*miter).resize(x, y, z);\n    (*miter) = (T)0;\n  }\n  return (temp);\n}\n\ntemplate <typename T>\nArray<Array<T, 3>, 3> Alloc6DContainer(int x, int y, int z, int d1, int d2,\n                                       int d3) {\n  Array<Array<T, 3>, 3> temp;\n  temp.setStorage(ColumnMajorArray<3>());\n  temp.resize(d1, d2, d3);\n\n  for (typename Array<Array<T, 3>, 3>::iterator miter = temp.begin();\n       miter != temp.end(); miter++) {\n    (*miter).setStorage(ColumnMajorArray<3>());\n    (*miter).resize(x, y, z);\n    (*miter) = (T)0;\n  }\n  return (temp);\n}\n\ntemplate <typename T>\nArray<Array<T, 3>, 2> Alloc5DContainer(int x, int y, int z, int d1, int d2) {\n  Array<Array<T, 3>, 2> temp;\n  temp.setStorage(ColumnMajorArray<2>());\n  temp.resize(d1, d2);\n\n  for (int i = 0; i < d1; i++) {\n    for (int j = 0; j < d2; j++) {\n      temp(i, j).setStorage(ColumnMajorArray<3>());\n      temp(i, j).resize(x, y, z);\n      temp(i, j) = (T)0;\n    }\n  }\n\n  /* This leads to errors for no real reason\n  for( typename Array< Array<T,3>,2>::iterator miter=temp.begin();   miter\n  !=temp.end(); miter++){\n          (*miter).setStorage(ColumnMajorArray<3>());\n          (*miter).resize(x,y,z);\n          (*miter)= (T )0;\n  }\n  */\n  return (temp);\n}\n\ndouble Dmax(const Array<Array<double, 2>, 1> &A);\ndouble Dmin(const Array<Array<double, 2>, 1> &A);\n\nvoid nested_workaround(long index, int *N, int *idx, int total);\n\n}  // namespace NDarray\n", "meta": {"hexsha": "e98ad62e43f7d5d68ff7d786330cf8335f7063c7", "size": 13161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ArrayTemplates.hpp", "max_stars_repo_name": "uwmri/mri_recon", "max_stars_repo_head_hexsha": "c74780d56c87603fb935744bf312e8c59d415997", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ArrayTemplates.hpp", "max_issues_repo_name": "uwmri/mri_recon", "max_issues_repo_head_hexsha": "c74780d56c87603fb935744bf312e8c59d415997", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-06T19:45:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-07T03:22:25.000Z", "max_forks_repo_path": "src/ArrayTemplates.hpp", "max_forks_repo_name": "uwmri/mri_recon", "max_forks_repo_head_hexsha": "c74780d56c87603fb935744bf312e8c59d415997", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7088036117, "max_line_length": 85, "alphanum_fraction": 0.6043613707, "num_tokens": 3994, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.6297745935070806, "lm_q1q2_score": 0.42341743082213595}}
{"text": "// Vector production via a one-loop box diagram\n//\n// Author:       Daniel Winney (2021)\n// Affiliation:  Joint Physics Analysis Center (JPAC)\n// Email:        dwinney@iu.edu\n// ---------------------------------------------------------------------------\n\n#ifndef _BOX_AMP_\n#define _BOX_AMP_\n\n#include \"constants.hpp\"\n#include \"amplitudes/amplitude.hpp\"\n#include \"amplitudes/reaction_kinematics.hpp\"\n#include \"box/box_discontinuity.hpp\"\n\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n\n#include \"Math/GSLIntegrator.h\"\n#include \"Math/GaussLegendreIntegrator.h\"\n#include \"Math/IntegrationTypes.h\"\n#include \"Math/Functor.h\"\n\nnamespace jpacPhoto\n{\n    class box_amplitude : public amplitude\n    {\n        public: \n        // Constructor.\n        // Need the parent reaction kinematics and pre-set sub-amplitudes\n        box_amplitude(reaction_kinematics * xkinem, box_discontinuity * disc, std::string id = \"Box Amplitude\")\n        : amplitude(xkinem, id), _disc(disc)\n        {};\n\n        box_amplitude(reaction_kinematics * xkinem, amplitude * left, amplitude * right, std::string id = \"Box Amplitude\")\n        : amplitude(xkinem, id)\n        {\n            _disc = new box_discontinuity(left, right);\n            _needDelete = true;\n        };\n\n        // Destructor\n        ~box_amplitude()\n        {\n            if (_needDelete) delete _disc;\n        };\n\n        // Setter for max cutoff in dispersion relation\n        inline void set_cutoff(double s_cut)\n        {\n            _s_cut = s_cut;\n        };\n\n        // only vector available\n        inline std::vector<std::array<int,2>> allowedJP()\n        {\n            return { {1, -1} };\n        };\n\n        // Evaluate the helicity amplitude by dispersing\n        std::complex<double> helicity_amplitude(std::array<int, 4> helicities, double s, double t);\n\n        // Override the jpacPhoto::amplitude::integrated_xsection\n        double integrated_xsection(double s);\n\n        private:        \n\n        // Discontinutity given in terms of the two tree amplitudes\n        box_discontinuity * _disc;\n        bool _needDelete = false;\n\n        // Integration momentum cutoff. Defaults to 2 GeV (an arbitrary but sensible value)\n        double _s_cut = 2.;\n    };\n};\n\n#endif", "meta": {"hexsha": "951515853852372de5d649ce3a7ad6c6638ffa2f", "size": 2226, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/box/box_amplitude.hpp", "max_stars_repo_name": "dwinney/vector-photoproduction", "max_stars_repo_head_hexsha": "a524c12f10c33c296b1b7cab20ae8a34d36adb12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/box/box_amplitude.hpp", "max_issues_repo_name": "dwinney/vector-photoproduction", "max_issues_repo_head_hexsha": "a524c12f10c33c296b1b7cab20ae8a34d36adb12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-08T17:48:26.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-08T17:48:26.000Z", "max_forks_repo_path": "include/box/box_amplitude.hpp", "max_forks_repo_name": "dwinney/vector-photoproduction", "max_forks_repo_head_hexsha": "a524c12f10c33c296b1b7cab20ae8a34d36adb12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T21:42:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-23T20:19:59.000Z", "avg_line_length": 29.2894736842, "max_line_length": 122, "alphanum_fraction": 0.6096136568, "num_tokens": 523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174789, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.42332920333555446}}
{"text": "#include \"util/coordinate.hpp\"\n#include \"util/coordinate_calculation.hpp\"\n#include \"util/trigonometry_table.hpp\"\n#include \"util/web_mercator.hpp\"\n\n#include <boost/assert.hpp>\n\n#include <cmath>\n\n#include <limits>\n#include <utility>\n\nnamespace osrm\n{\nnamespace util\n{\n\nnamespace coordinate_calculation\n{\n\n// Does not project the coordinates!\nstd::uint64_t squaredEuclideanDistance(const Coordinate lhs, const Coordinate rhs)\n{\n    const std::uint64_t dx = static_cast<std::int32_t>(lhs.lon - rhs.lon);\n    const std::uint64_t dy = static_cast<std::int32_t>(lhs.lat - rhs.lat);\n\n    return dx * dx + dy * dy;\n}\n\ndouble haversineDistance(const Coordinate coordinate_1, const Coordinate coordinate_2)\n{\n    auto lon1 = static_cast<int>(coordinate_1.lon);\n    auto lat1 = static_cast<int>(coordinate_1.lat);\n    auto lon2 = static_cast<int>(coordinate_2.lon);\n    auto lat2 = static_cast<int>(coordinate_2.lat);\n    BOOST_ASSERT(lon1 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lat1 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lon2 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lat2 != std::numeric_limits<int>::min());\n    const double lt1 = lat1 / COORDINATE_PRECISION;\n    const double ln1 = lon1 / COORDINATE_PRECISION;\n    const double lt2 = lat2 / COORDINATE_PRECISION;\n    const double ln2 = lon2 / COORDINATE_PRECISION;\n\n    const double dlat1 = lt1 * detail::DEGREE_TO_RAD;\n    const double dlong1 = ln1 * detail::DEGREE_TO_RAD;\n    const double dlat2 = lt2 * detail::DEGREE_TO_RAD;\n    const double dlong2 = ln2 * detail::DEGREE_TO_RAD;\n\n    const double dlong = dlong1 - dlong2;\n    const double dlat = dlat1 - dlat2;\n\n    const double aharv = std::pow(std::sin(dlat / 2.0), 2.0) +\n                         std::cos(dlat1) * std::cos(dlat2) * std::pow(std::sin(dlong / 2.), 2);\n    const double charv = 2. * std::atan2(std::sqrt(aharv), std::sqrt(1.0 - aharv));\n    return detail::EARTH_RADIUS * charv;\n}\n\ndouble greatCircleDistance(const Coordinate coordinate_1, const Coordinate coordinate_2)\n{\n    auto lon1 = static_cast<int>(coordinate_1.lon);\n    auto lat1 = static_cast<int>(coordinate_1.lat);\n    auto lon2 = static_cast<int>(coordinate_2.lon);\n    auto lat2 = static_cast<int>(coordinate_2.lat);\n    BOOST_ASSERT(lat1 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lon1 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lat2 != std::numeric_limits<int>::min());\n    BOOST_ASSERT(lon2 != std::numeric_limits<int>::min());\n\n    const double float_lat1 = (lat1 / COORDINATE_PRECISION) * detail::DEGREE_TO_RAD;\n    const double float_lon1 = (lon1 / COORDINATE_PRECISION) * detail::DEGREE_TO_RAD;\n    const double float_lat2 = (lat2 / COORDINATE_PRECISION) * detail::DEGREE_TO_RAD;\n    const double float_lon2 = (lon2 / COORDINATE_PRECISION) * detail::DEGREE_TO_RAD;\n\n    const double x_value = (float_lon2 - float_lon1) * std::cos((float_lat1 + float_lat2) / 2.0);\n    const double y_value = float_lat2 - float_lat1;\n    return std::hypot(x_value, y_value) * detail::EARTH_RADIUS;\n}\n\ndouble perpendicularDistance(const Coordinate segment_source,\n                             const Coordinate segment_target,\n                             const Coordinate query_location,\n                             Coordinate &nearest_location,\n                             double &ratio)\n{\n    using namespace coordinate_calculation;\n\n    BOOST_ASSERT(query_location.IsValid());\n\n    FloatCoordinate projected_nearest;\n    std::tie(ratio, projected_nearest) =\n        projectPointOnSegment(web_mercator::fromWGS84(segment_source),\n                              web_mercator::fromWGS84(segment_target),\n                              web_mercator::fromWGS84(query_location));\n    nearest_location = web_mercator::toWGS84(projected_nearest);\n\n    const double approximate_distance = greatCircleDistance(query_location, nearest_location);\n    BOOST_ASSERT(0.0 <= approximate_distance);\n    return approximate_distance;\n}\n\ndouble perpendicularDistance(const Coordinate source_coordinate,\n                             const Coordinate target_coordinate,\n                             const Coordinate query_location)\n{\n    double ratio;\n    Coordinate nearest_location;\n\n    return perpendicularDistance(\n        source_coordinate, target_coordinate, query_location, nearest_location, ratio);\n}\n\nCoordinate centroid(const Coordinate lhs, const Coordinate rhs)\n{\n    Coordinate centroid;\n    // The coordinates of the midpoints are given by:\n    // x = (x1 + x2) /2 and y = (y1 + y2) /2.\n    centroid.lon = (lhs.lon + rhs.lon) / FixedLongitude{2};\n    centroid.lat = (lhs.lat + rhs.lat) / FixedLatitude{2};\n    return centroid;\n}\n\ndouble degToRad(const double degree)\n{\n    using namespace boost::math::constants;\n    return degree * (pi<double>() / 180.0);\n}\n\ndouble radToDeg(const double radian)\n{\n    using namespace boost::math::constants;\n    return radian * (180.0 * (1. / pi<double>()));\n}\n\ndouble bearing(const Coordinate first_coordinate, const Coordinate second_coordinate)\n{\n    const double lon_diff =\n        static_cast<double>(toFloating(second_coordinate.lon - first_coordinate.lon));\n    const double lon_delta = degToRad(lon_diff);\n    const double lat1 = degToRad(static_cast<double>(toFloating(first_coordinate.lat)));\n    const double lat2 = degToRad(static_cast<double>(toFloating(second_coordinate.lat)));\n    const double y = std::sin(lon_delta) * std::cos(lat2);\n    const double x =\n        std::cos(lat1) * std::sin(lat2) - std::sin(lat1) * std::cos(lat2) * std::cos(lon_delta);\n    double result = radToDeg(std::atan2(y, x));\n    while (result < 0.0)\n    {\n        result += 360.0;\n    }\n\n    while (result >= 360.0)\n    {\n        result -= 360.0;\n    }\n    return result;\n}\n\ndouble computeAngle(const Coordinate first, const Coordinate second, const Coordinate third)\n{\n    using namespace boost::math::constants;\n    using namespace coordinate_calculation;\n\n    if (first == second || second == third)\n        return 180;\n\n    BOOST_ASSERT(first.IsValid());\n    BOOST_ASSERT(second.IsValid());\n    BOOST_ASSERT(third.IsValid());\n\n    const double v1x = static_cast<double>(toFloating(first.lon - second.lon));\n    const double v1y =\n        web_mercator::latToY(toFloating(first.lat)) - web_mercator::latToY(toFloating(second.lat));\n    const double v2x = static_cast<double>(toFloating(third.lon - second.lon));\n    const double v2y =\n        web_mercator::latToY(toFloating(third.lat)) - web_mercator::latToY(toFloating(second.lat));\n\n    double angle = (atan2_lookup(v2y, v2x) - atan2_lookup(v1y, v1x)) * 180. / pi<double>();\n\n    while (angle < 0.)\n    {\n        angle += 360.;\n    }\n\n    BOOST_ASSERT(angle >= 0);\n    return angle;\n}\n\nboost::optional<Coordinate>\ncircleCenter(const Coordinate C1, const Coordinate C2, const Coordinate C3)\n{\n    // free after http://paulbourke.net/geometry/circlesphere/\n    // require three distinct points\n    if (C1 == C2 || C2 == C3 || C1 == C3)\n    {\n        return boost::none;\n    }\n\n    // define line through c1, c2 and c2,c3\n    const double C2C1_lat = static_cast<double>(toFloating(C2.lat - C1.lat)); // yDelta_a\n    const double C2C1_lon = static_cast<double>(toFloating(C2.lon - C1.lon)); // xDelta_a\n    const double C3C2_lat = static_cast<double>(toFloating(C3.lat - C2.lat)); // yDelta_b\n    const double C3C2_lon = static_cast<double>(toFloating(C3.lon - C2.lon)); // xDelta_b\n\n    // check for collinear points in X-Direction / Y-Direction\n    if ((std::abs(C2C1_lon) < std::numeric_limits<double>::epsilon() &&\n         std::abs(C3C2_lon) < std::numeric_limits<double>::epsilon()) ||\n        (std::abs(C2C1_lat) < std::numeric_limits<double>::epsilon() &&\n         std::abs(C3C2_lat) < std::numeric_limits<double>::epsilon()))\n    {\n        return boost::none;\n    }\n    else if (std::abs(C2C1_lon) < std::numeric_limits<double>::epsilon())\n    {\n        // vertical line C2C1\n        // due to c1.lon == c2.lon && c1.lon != c3.lon we can rearrange this way\n        BOOST_ASSERT(std::abs(static_cast<double>(toFloating(C3.lon - C1.lon))) >=\n                         std::numeric_limits<double>::epsilon() &&\n                     std::abs(static_cast<double>(toFloating(C2.lon - C3.lon))) >=\n                         std::numeric_limits<double>::epsilon());\n        return circleCenter(C1, C3, C2);\n    }\n    else if (std::abs(C3C2_lon) < std::numeric_limits<double>::epsilon())\n    {\n        // vertical line C3C2\n        // due to c2.lon == c3.lon && c1.lon != c3.lon we can rearrange this way\n        // after rearrangement both deltas will be zero\n        BOOST_ASSERT(std::abs(static_cast<double>(toFloating(C1.lon - C2.lon))) >=\n                         std::numeric_limits<double>::epsilon() &&\n                     std::abs(static_cast<double>(toFloating(C3.lon - C1.lon))) >=\n                         std::numeric_limits<double>::epsilon());\n        return circleCenter(C2, C1, C3);\n    }\n    else\n    {\n        const double C2C1_slope = C2C1_lat / C2C1_lon;\n        const double C3C2_slope = C3C2_lat / C3C2_lon;\n\n        if (std::abs(C2C1_slope) < std::numeric_limits<double>::epsilon())\n        {\n            // Three non-collinear points with C2,C1 on same latitude.\n            // Due to the x-values correct, we can swap C3 and C1 to obtain the correct slope value\n            return circleCenter(C3, C2, C1);\n        }\n        // valid slope values for both lines, calculate the center as intersection of the lines\n\n        // can this ever happen?\n        if (std::abs(C2C1_slope - C3C2_slope) < std::numeric_limits<double>::epsilon())\n            return boost::none;\n\n        const double C1_y = static_cast<double>(toFloating(C1.lat));\n        const double C1_x = static_cast<double>(toFloating(C1.lon));\n        const double C2_y = static_cast<double>(toFloating(C2.lat));\n        const double C2_x = static_cast<double>(toFloating(C2.lon));\n        const double C3_y = static_cast<double>(toFloating(C3.lat));\n        const double C3_x = static_cast<double>(toFloating(C3.lon));\n\n        const double lon = (C2C1_slope * C3C2_slope * (C1_y - C3_y) + C3C2_slope * (C1_x + C2_x) -\n                            C2C1_slope * (C2_x + C3_x)) /\n                           (2 * (C3C2_slope - C2C1_slope));\n        const double lat = (0.5 * (C1_x + C2_x) - lon) / C2C1_slope + 0.5 * (C1_y + C2_y);\n        if (lon < -180.0 || lon > 180.0 || lat < -90.0 || lat > 90.0)\n            return boost::none;\n        else\n            return Coordinate(FloatLongitude{lon}, FloatLatitude{lat});\n    }\n}\n\ndouble circleRadius(const Coordinate C1, const Coordinate C2, const Coordinate C3)\n{\n    // a circle by three points requires thee distinct points\n    auto center = circleCenter(C1, C2, C3);\n    if (center)\n        return haversineDistance(C1, *center);\n    else\n        return std::numeric_limits<double>::infinity();\n}\n\nCoordinate interpolateLinear(double factor, const Coordinate from, const Coordinate to)\n{\n    BOOST_ASSERT(0 <= factor && factor <= 1.0);\n\n    const auto from_lon = static_cast<std::int32_t>(from.lon);\n    const auto from_lat = static_cast<std::int32_t>(from.lat);\n    const auto to_lon = static_cast<std::int32_t>(to.lon);\n    const auto to_lat = static_cast<std::int32_t>(to.lat);\n\n    FixedLongitude interpolated_lon{\n        static_cast<std::int32_t>(from_lon + factor * (to_lon - from_lon))};\n    FixedLatitude interpolated_lat{\n        static_cast<std::int32_t>(from_lat + factor * (to_lat - from_lat))};\n\n    return {std::move(interpolated_lon), std::move(interpolated_lat)};\n}\n\n// compute the signed area of a triangle\ndouble signedArea(const Coordinate first_coordinate,\n                  const Coordinate second_coordinate,\n                  const Coordinate third_coordinate)\n{\n    const auto lat_1 = static_cast<double>(toFloating(first_coordinate.lat));\n    const auto lon_1 = static_cast<double>(toFloating(first_coordinate.lon));\n    const auto lat_2 = static_cast<double>(toFloating(second_coordinate.lat));\n    const auto lon_2 = static_cast<double>(toFloating(second_coordinate.lon));\n    const auto lat_3 = static_cast<double>(toFloating(third_coordinate.lat));\n    const auto lon_3 = static_cast<double>(toFloating(third_coordinate.lon));\n    return 0.5 * (-lon_2 * lat_1 + lon_3 * lat_1 + lon_1 * lat_2 - lon_3 * lat_2 - lon_1 * lat_3 +\n                  lon_2 * lat_3);\n}\n\n// check if a set of three coordinates is given in CCW order\nbool isCCW(const Coordinate first_coordinate,\n           const Coordinate second_coordinate,\n           const Coordinate third_coordinate)\n{\n    return signedArea(first_coordinate, second_coordinate, third_coordinate) > 0;\n}\n\nstd::pair<util::Coordinate, util::Coordinate>\nleastSquareRegression(const std::vector<util::Coordinate> &coordinates)\n{\n    BOOST_ASSERT(coordinates.size() >= 2);\n    double sum_lon = 0, sum_lat = 0, sum_lon_lat = 0, sum_lon_lon = 0;\n    double min_lon = static_cast<double>(toFloating(coordinates.front().lon));\n    double max_lon = static_cast<double>(toFloating(coordinates.front().lon));\n    for (const auto coord : coordinates)\n    {\n        min_lon = std::min(min_lon, static_cast<double>(toFloating(coord.lon)));\n        max_lon = std::max(max_lon, static_cast<double>(toFloating(coord.lon)));\n        sum_lon += static_cast<double>(toFloating(coord.lon));\n        sum_lon_lon +=\n            static_cast<double>(toFloating(coord.lon)) * static_cast<double>(toFloating(coord.lon));\n        sum_lat += static_cast<double>(toFloating(coord.lat));\n        sum_lon_lat +=\n            static_cast<double>(toFloating(coord.lon)) * static_cast<double>(toFloating(coord.lat));\n    }\n\n    const auto dividend = coordinates.size() * sum_lon_lat - sum_lon * sum_lat;\n    const auto divisor = coordinates.size() * sum_lon_lon - sum_lon * sum_lon;\n    if (std::abs(divisor) < std::numeric_limits<double>::epsilon())\n        return std::make_pair(coordinates.front(), coordinates.back());\n\n    // slope of the regression line\n    const auto slope = dividend / divisor;\n    const auto intercept = (sum_lat - slope * sum_lon) / coordinates.size();\n\n    const auto GetLatAtLon = [intercept,\n                              slope](const util::FloatLongitude longitude) -> util::FloatLatitude {\n        return {intercept + slope * static_cast<double>((longitude))};\n    };\n\n    const util::Coordinate regression_first = {\n        toFixed(util::FloatLongitude{min_lon - 1}),\n        toFixed(util::FloatLatitude(GetLatAtLon(util::FloatLongitude{min_lon - 1})))};\n    const util::Coordinate regression_end = {\n        toFixed(util::FloatLongitude{max_lon + 1}),\n        toFixed(util::FloatLatitude(GetLatAtLon(util::FloatLongitude{max_lon + 1})))};\n\n    return {regression_first, regression_end};\n}\n\n} // ns coordinate_calculation\n} // ns util\n} // ns osrm\n", "meta": {"hexsha": "3ba1f22a39af73bed16eecb5c68c8c73cb0ad161", "size": 14761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/coordinate_calculation.cpp", "max_stars_repo_name": "rudazhan/osrm-backend", "max_stars_repo_head_hexsha": "1ba5ff44cccbef2dd98ca91f3b7aa4cf9ca984c6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util/coordinate_calculation.cpp", "max_issues_repo_name": "rudazhan/osrm-backend", "max_issues_repo_head_hexsha": "1ba5ff44cccbef2dd98ca91f3b7aa4cf9ca984c6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util/coordinate_calculation.cpp", "max_forks_repo_name": "rudazhan/osrm-backend", "max_forks_repo_head_hexsha": "1ba5ff44cccbef2dd98ca91f3b7aa4cf9ca984c6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5521978022, "max_line_length": 100, "alphanum_fraction": 0.6616760382, "num_tokens": 3720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.42326814816055847}}
{"text": "#include <stdlib.h>\n#include <assert.h>\n#include <time.h>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <set>\n#include <boost/numeric/ublas/matrix.hpp>\n\n#include \"../Point.h\"\n#include \"../ANN.h\"\n#include \"../RMSUtils.h\"\n#include \"../IOUtil.h\"\n\nusing namespace std;\n\nvector<Point> validDirs;\nvector<double> validResults;\n\nbool validate_coreset(const vector<Point> &fatP, vector<size_t> &idxs, double epsilon) {\n    assert(idxs.size() <= fatP.size());\n\n    if (fatP.empty())\n        return true;\n\n    if (idxs.empty())\n        return false;\n\n    assert(idxs[0] >= 0 && idxs[idxs.size() - 1] < fatP.size());\n\n    for (size_t i = 0; i < validDirs.size(); i++) {\n        double cor_max = fatP[idxs[0]].dotP(validDirs[i]);\n        for (size_t j = 1; j < idxs.size(); j++) {\n            double corval = fatP[idxs[j]].dotP(validDirs[i]);\n            if (corval > cor_max)\n                cor_max = corval;\n        }\n\n        double ptval = validResults[i];\n        if (cor_max < (1 - epsilon) * ptval)\n            return false;\n    }\n    return true;\n}\n\nvoid loss_distribution(const vector<Point> &coreset, const vector<Point> &queries,\n                       const vector<double> &results, vector<double> &regret_dist) {\n    int n = min(queries.size(), results.size());\n    regret_dist.reserve(1000);\n\n    vector<double> regret_ratios(n);\n    for (int i = 0; i < n; i++) {\n        assert(results[i] > 0);\n        double dot_max = 0;\n        for (int j = 0; j < coreset.size(); ++j) {\n            double dotp = coreset[j].dotP(queries[i]);\n            if (dotp > dot_max)\n                dot_max = dotp;\n        }\n\n        double regret_ratio_i = (results[i] - dot_max) / results[i];\n        regret_ratios[i] = regret_ratio_i;\n    }\n\n    sort (regret_ratios.begin(), regret_ratios.end());\n\n    for (int i = 1; i < 1000; ++i) {\n        regret_dist[i - 1] = regret_ratios[n * i / 1000];\n    }\n    regret_dist[999] = regret_ratios[n - 1];\n}\n\nbool validate_eps_kernel(const vector<Point> &fatP, vector<size_t> &idxs, double epsilon) {\n    assert(idxs.size() <= fatP.size());\n\n    if (fatP.empty())\n        return true;\n\n    if (idxs.empty())\n        return false;\n\n    assert(idxs[0] >= 0 && idxs[idxs.size() - 1] < fatP.size());\n\n    size_t m = validDirs.size() / 2;\n    for (size_t i = 0; i < m; i++) {\n        double cor_max = fatP[idxs[0]].dotP(validDirs[2 * i]);\n        double cor_min = fatP[idxs[0]].dotP(validDirs[2 * i + 1]);\n        for (size_t j = 1; j < idxs.size(); j++) {\n            double cor_val1 = fatP[idxs[j]].dotP(validDirs[2 * i]);\n            double cor_val2 = fatP[idxs[j]].dotP(validDirs[2 * i + 1]);\n            if (cor_val1 > cor_max)\n                cor_max = cor_val1;\n            if (cor_val2 > cor_min)\n                cor_min = cor_val2;\n        }\n\n        if ((cor_max + cor_min) < (1 - epsilon) * (validResults[2 * i] + validResults[2 * i + 1]))\n            return false;\n    }\n    return true;\n}\n\nvoid coreset_by_sample(ANN *ann_ds, size_t dim, double outer_rad, double delta, size_t deltam, vector<size_t> &idxs) {\n    vector<Point> randomP;\n    RMSUtils::get_random_sphere_points(outer_rad, dim, deltam, randomP, false);\n\n    vector<size_t> new_idxs;\n    ann_ds->getANNs(randomP, delta, new_idxs);\n\n    //figure out all the distinct indices\n    set<size_t> unique_idxs;\n    for (size_t i = 0; i < idxs.size(); i++)\n        unique_idxs.insert(idxs[i]);\n    for (size_t i = 0; i < new_idxs.size(); i++)\n        unique_idxs.insert(new_idxs[i]);\n\n    idxs.clear();\n\n    set<size_t>::iterator it;\n    for (it = unique_idxs.begin(); it != unique_idxs.end(); ++it)\n        idxs.push_back((*it));\n}\n\nvector<size_t> get_coreset(const vector<Point> &fatP, const int r, const double epsilon, bool &isValid) {\n    size_t dim = fatP[0].get_dimension();\n\n    double outer_rad;\n    outer_rad = 1 + sqrt(dim);\n    double delta = epsilon / (2 * outer_rad);\n\n    vector<size_t> idxs;\n    ANN *ann_ds = new ANN();\n    ann_ds->insertPts(fatP);\n\n    size_t m = r;\n    bool b = false;\n    while (!b) {\n        coreset_by_sample(ann_ds, dim, outer_rad, delta, m, idxs);\n        b = validate_coreset(fatP, idxs, epsilon);\n        m += 5;\n\n        if (b && idxs.size() <= r) {\n            isValid = true;\n            break;\n        }\n\n        if (idxs.size() > r) {\n            isValid = false;\n            break;\n        }\n    }\n\n    delete ann_ds;\n    return idxs;\n}\n\nint main(int argc, char **argv) {\n    if (argc < 7) {\n        cerr << \"coreset: Usage \" << argv[0] << \"<r> <dim> <data_path> <query_path> <valid_path> <output_path>\\n\";\n        exit(1);\n    }\n\n    int r = atoi(argv[1]);\n    size_t dim = atoi(argv[2]);\n\n    vector<Point> fatP;\n\n    IOUtil::read_input_points(argv[3], dim, fatP);\n    IOUtil::read_validate_dirs(argv[4], dim, validDirs);\n    IOUtil::read_validate_results(argv[5], validResults);\n\n    ofstream result_file;\n    result_file.open(argv[6], ofstream::out | ofstream::app);\n\n    cout << \"ann \" << argv[3] << \" \" << fatP.size() << \" \" << dim << endl;\n\n    result_file << \"dataset=\" << argv[3] << \" r=\" << r << \"\\n\" << flush;\n\n    double eps = 0.2;\n\n    vector<size_t> idxs;\n    bool isValid;\n    while (true) {\n        cout << eps << endl;\n        idxs = get_coreset(fatP, r, eps, isValid);\n        if (isValid) {\n            break;\n        } else {\n            eps += 0.01;\n        }\n    }\n\n    vector<Point> coreset;\n    vector<double> regretDist;\n    coreset.reserve(idxs.size());\n    for (int i = 0; i < idxs.size(); ++i)\n        coreset.push_back(fatP[idxs[i]]);\n    loss_distribution(coreset, validDirs, validResults, regretDist);\n\n    cout << regretDist[999] << endl;\n\n    for (int i = 0; i < 1000; ++i)\n        result_file << regretDist[i] << \"\\n\";\n    result_file.flush();\n    result_file.close();\n}\n", "meta": {"hexsha": "dc64b57ebdd817193eaf33759aff7e1c4156b584", "size": 5778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ANN/coreset_r/coreset_r.cpp", "max_stars_repo_name": "yhwang1990/minimum-coresets", "max_stars_repo_head_hexsha": "8a81d6cb7260cc9de82d5d9160440296732d2620", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-19T13:01:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-19T13:01:43.000Z", "max_issues_repo_path": "ANN/coreset_r/coreset_r.cpp", "max_issues_repo_name": "yhwang1990/minimum-coresets", "max_issues_repo_head_hexsha": "8a81d6cb7260cc9de82d5d9160440296732d2620", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ANN/coreset_r/coreset_r.cpp", "max_forks_repo_name": "yhwang1990/minimum-coresets", "max_forks_repo_head_hexsha": "8a81d6cb7260cc9de82d5d9160440296732d2620", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7788461538, "max_line_length": 118, "alphanum_fraction": 0.5607476636, "num_tokens": 1668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4231743852235444}}
{"text": "#ifndef ASLAM_BACKEND_EUCLIDEAN_EXPRESSION_NODE_HPP\n#define ASLAM_BACKEND_EUCLIDEAN_EXPRESSION_NODE_HPP\n\n#include <aslam/backend/JacobianContainer.hpp>\n#include \"RotationExpressionNode.hpp\"\n#include \"ScalarExpressionNode.hpp\"\n#include \"TransformationExpressionNode.hpp\"\n#include \"MatrixExpressionNode.hpp\"\n#include <boost/shared_ptr.hpp>\n#include <Eigen/Core>\n#include <sm/kinematics/RotationalKinematics.hpp>\n#include <aslam/backend/VectorExpressionNode.hpp>\n\nnamespace aslam {\n  namespace backend {\n    template <int D> class VectorExpression;\n    class HomogeneousExpressionNode;\n    /**\n     * \\class EuclideanExpressionNode\n     * \\brief The superclass of all classes representing euclidean points.\n     */\n    typedef VectorExpressionNode<3>  EuclideanExpressionNode;\n\n    /**\n     * \\class EuclideanExpressionNodeMultiply\n     *\n     * \\brief A class representing the multiplication of two euclidean matrices.\n     * \n     */\n    class EuclideanExpressionNodeMultiply : public EuclideanExpressionNode\n    {\n    public:\n      EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n      EuclideanExpressionNodeMultiply(boost::shared_ptr<RotationExpressionNode> lhs, \n                                      boost::shared_ptr<EuclideanExpressionNode> rhs);\n      ~EuclideanExpressionNodeMultiply() override;\n\n      void accept(ExpressionNodeVisitor& visitor) override;\n    private:\n      Eigen::Vector3d evaluateImplementation() const override;\n      void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override;\n      void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override;\n\n      boost::shared_ptr<RotationExpressionNode> _lhs;\n      mutable Eigen::Matrix3d _C_lhs;\n      boost::shared_ptr<EuclideanExpressionNode> _rhs;\n      mutable Eigen::Vector3d _p_rhs;\n    };\n\n    // ## New Class for Multiplication with a MatrixExpression\n    /**\n      * \\class EuclideanExpressionNodeMatrixMultiply\n      *\n      * \\brief A class representing the multiplication of a Matrix with a euclidean Vector.\n      *\n      */\n     class EuclideanExpressionNodeMatrixMultiply : public EuclideanExpressionNode\n     {\n     public:\n       EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n       EuclideanExpressionNodeMatrixMultiply(boost::shared_ptr<MatrixExpressionNode> lhs, boost::shared_ptr<EuclideanExpressionNode> rhs);\n       ~EuclideanExpressionNodeMatrixMultiply() override;\n\n     private:\n       Eigen::Vector3d evaluateImplementation() const override;\n       void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override;\n       void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override;\n\n       boost::shared_ptr<MatrixExpressionNode> _lhs;\n       mutable Eigen::Matrix3d _A_lhs;\n       boost::shared_ptr<EuclideanExpressionNode> _rhs;\n       mutable Eigen::Vector3d _p_rhs;\n\n     };\n\n\n\n    /**\n      * \\class EuclideanExpressionNodeCrossEuclidean\n      *\n      * \\brief A class representing the cross product of two euclidean expressions.\n      *\n      */\n     class EuclideanExpressionNodeCrossEuclidean : public EuclideanExpressionNode\n     {\n     public:\n       EuclideanExpressionNodeCrossEuclidean(boost::shared_ptr<EuclideanExpressionNode> lhs,\n           boost::shared_ptr<EuclideanExpressionNode> rhs);\n       ~EuclideanExpressionNodeCrossEuclidean() override;\n\n       void accept(ExpressionNodeVisitor& visitor) override;\n     private:\n       Eigen::Vector3d evaluateImplementation() const override;\n       void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override;\n       void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override;\n\n       boost::shared_ptr<EuclideanExpressionNode> _lhs;\n       boost::shared_ptr<EuclideanExpressionNode> _rhs;\n     };\n\n\n     /**\n       * \\class EuclideanExpressionNodeAddEuclidean\n       *\n       * \\brief A class representing the addition of two euclidean expressions.\n       *\n       */\n      class EuclideanExpressionNodeAddEuclidean : public EuclideanExpressionNode\n      {\n      public:\n        EuclideanExpressionNodeAddEuclidean(boost::shared_ptr<EuclideanExpressionNode> lhs,\n            boost::shared_ptr<EuclideanExpressionNode> rhs);\n        ~EuclideanExpressionNodeAddEuclidean() override;\n\n        void accept(ExpressionNodeVisitor& visitor) override;\n      private:\n        Eigen::Vector3d evaluateImplementation() const override;\n        void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override;\n        void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override;\n\n        boost::shared_ptr<EuclideanExpressionNode> _lhs;\n        boost::shared_ptr<EuclideanExpressionNode> _rhs;\n      };\n\n\n      /**\n      * \\class EuclideanExpressionNodeSubtractEuclidean\n      *\n      * \\brief A class representing the subtraction of two Euclidean expressions.\n      *\n      */\n     class EuclideanExpressionNodeSubtractEuclidean : public EuclideanExpressionNode\n     {\n     public:\n       EuclideanExpressionNodeSubtractEuclidean(boost::shared_ptr<EuclideanExpressionNode> lhs,\n           boost::shared_ptr<EuclideanExpressionNode> rhs);\n       ~EuclideanExpressionNodeSubtractEuclidean() override;\n\n     private:\n       Eigen::Vector3d evaluateImplementation() const override;\n       void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override;\n       void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override;\n\n       boost::shared_ptr<EuclideanExpressionNode> _lhs;\n       boost::shared_ptr<EuclideanExpressionNode> _rhs;\n     };\n\n    /**\n      * \\class EuclideanExpressionNodeSubtractVector\n      *\n      * \\brief A class representing the subtraction of a vector from an Euclidean expression.\n      *\n      */\n     class EuclideanExpressionNodeSubtractVector : public EuclideanExpressionNode\n     {\n     public:\n       EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n       EuclideanExpressionNodeSubtractVector(boost::shared_ptr<EuclideanExpressionNode> lhs,\n              const Eigen::Vector3d & rhs);\n       ~EuclideanExpressionNodeSubtractVector() override;\n\n     private:\n       Eigen::Vector3d evaluateImplementation() const override;\n       void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override;\n       void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override;\n\n       boost::shared_ptr<EuclideanExpressionNode> _lhs;\n       Eigen::Vector3d _rhs;\n     };\n\n\n     /**\n       * \\class EuclideanExpressionNodeSubtractVector\n       *\n       * \\brief A class representing the negated Euclidean expression.\n       *\n       */\n      class EuclideanExpressionNodeNegated : public EuclideanExpressionNode\n      {\n      public:\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        EuclideanExpressionNodeNegated(boost::shared_ptr<EuclideanExpressionNode> operand);\n        ~EuclideanExpressionNodeNegated() override;\n\n      private:\n        Eigen::Vector3d evaluateImplementation() const override;\n        void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override;\n        void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override;\n\n        boost::shared_ptr<EuclideanExpressionNode> _operand;\n      };\n\n     /**\n       * \\class EuclideanExpressionNodeScalarMultiply\n       *\n       * \\brief A class representing the multiplication of a ScalarExpression with an Euclidean expression.\n       *\n       */\n      class EuclideanExpressionNodeScalarMultiply : public EuclideanExpressionNode\n      {\n      public:\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        EuclideanExpressionNodeScalarMultiply(boost::shared_ptr<EuclideanExpressionNode> p, boost::shared_ptr<ScalarExpressionNode> s);\n        ~EuclideanExpressionNodeScalarMultiply() override;\n\n      private:\n        Eigen::Vector3d evaluateImplementation() const override;\n        void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override;\n        void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override;\n\n        boost::shared_ptr<EuclideanExpressionNode> _p;\n        boost::shared_ptr<ScalarExpressionNode> _s;\n      };\n\n      class EuclideanExpressionNodeTranslation : public EuclideanExpressionNode\n      {\n      public:\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        EuclideanExpressionNodeTranslation(boost::shared_ptr<TransformationExpressionNode> operand);\n        ~EuclideanExpressionNodeTranslation() override;\n\n      private:\n        Eigen::Vector3d evaluateImplementation() const override;\n        void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override;\n        void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override;\n\n        boost::shared_ptr<TransformationExpressionNode> _operand;\n      };\n\n\n  class EuclideanExpressionNodeRotationParameters : public EuclideanExpressionNode\n      {\n      public:\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        EuclideanExpressionNodeRotationParameters(boost::shared_ptr<RotationExpressionNode> operand, sm::kinematics::RotationalKinematics::Ptr rk);\n        ~EuclideanExpressionNodeRotationParameters() override;\n\n      private:\n        Eigen::Vector3d evaluateImplementation() const override;\n        void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override;\n        void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override;\n\n        boost::shared_ptr<RotationExpressionNode> _operand;\n        sm::kinematics::RotationalKinematics::Ptr _rk;\n      };\n\n\n  class EuclideanExpressionNodeFromHomogeneous : public EuclideanExpressionNode\n      {\n      public:\n        EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n        EuclideanExpressionNodeFromHomogeneous(boost::shared_ptr<HomogeneousExpressionNode> root);\n        ~EuclideanExpressionNodeFromHomogeneous() override;\n\n      private:\n        Eigen::Vector3d evaluateImplementation() const override;\n        void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override;\n        void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override;\n\n        boost::shared_ptr<HomogeneousExpressionNode> _root;\n      };\n\n    /**\n      * \\class EuclideanExpressionNodeElementwiseMultiplyEuclidean\n      *\n      * \\brief A class representing the elementwise product of two euclidean expressions.\n      *\n      */\n     class EuclideanExpressionNodeElementwiseMultiplyEuclidean : public EuclideanExpressionNode\n     {\n     public:\n       EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n       EuclideanExpressionNodeElementwiseMultiplyEuclidean(boost::shared_ptr<EuclideanExpressionNode> lhs,\n           boost::shared_ptr<EuclideanExpressionNode> rhs);\n       ~EuclideanExpressionNodeElementwiseMultiplyEuclidean() override;\n\n     private:\n       Eigen::Vector3d evaluateImplementation() const override;\n       void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override;\n       void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override;\n\n       boost::shared_ptr<EuclideanExpressionNode> _lhs;\n       boost::shared_ptr<EuclideanExpressionNode> _rhs;\n     };\n\n  \n  \n  } // namespace backend\n} // namespace aslam\n\n#endif /* ASLAM_BACKEND_EUCLIDEAN_EXPRESSION_NODE_HPP */\n", "meta": {"hexsha": "8c5871d30c7838f407ce9f617524ff7f23f1f61c", "size": 11437, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "aslam_backend_expressions/include/aslam/backend/EuclideanExpressionNode.hpp", "max_stars_repo_name": "ethz-asl/aslam_optimizer", "max_stars_repo_head_hexsha": "8e9dd18f9f0d8af461e88e108a3beda2003daf11", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2017-04-26T13:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T01:52:22.000Z", "max_issues_repo_path": "aslam_backend_expressions/include/aslam/backend/EuclideanExpressionNode.hpp", "max_issues_repo_name": "ethz-asl/aslam_optimizer", "max_issues_repo_head_hexsha": "8e9dd18f9f0d8af461e88e108a3beda2003daf11", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:02:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-12T06:07:22.000Z", "max_forks_repo_path": "aslam_backend_expressions/include/aslam/backend/EuclideanExpressionNode.hpp", "max_forks_repo_name": "ethz-asl/aslam_optimizer", "max_forks_repo_head_hexsha": "8e9dd18f9f0d8af461e88e108a3beda2003daf11", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-06-28T04:17:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T04:58:36.000Z", "avg_line_length": 37.9966777409, "max_line_length": 147, "alphanum_fraction": 0.7388301128, "num_tokens": 2352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4231743852235444}}
{"text": "#include \"../../include/waveO1/observer.hpp\"\n#include \"../../include/waveO1/utilities.hpp\"\n#include \"../../include/mymfem/utilities.hpp\"\n\n#include <fstream>\n#include <iostream>\n#include <Eigen/Core>\n\n\ndouble WaveO1Observer\n:: eval_dgpFtimeError (std::shared_ptr<GridFunction>& p,\n                      std::shared_ptr<GridFunction>& v,\n                      double t) const\n{\n    double errp=0;\n    double errv=0;\n\n    // assumes that all elements have the same geometry\n    auto faceElGeomType = p->FESpace()->GetMesh()\n                ->GetFaceGeometryType(0);\n\n    // L2 error in pressure\n    // set integration rules\n    IntegrationRules rule1{};\n    const IntegrationRule *ir1;\n    int order1 = 2*p->FESpace()->GetFE(0)->GetOrder()+2;\n    ir1 = &rule1.Get(faceElGeomType, order1);\n    m_pE_coeff->SetTime(t);\n    m_assembleDgpSmoothError->SetIntegrationRule(ir1);\n    errp = m_assembleDgpSmoothError->Ftime(p.get(), m_pE_coeff.get());\n\n    // L2 error in velocity\n    // set integration rules\n    IntegrationRules rule2{};\n    const IntegrationRule *ir2;\n    int order2 = 2*v->FESpace()->GetFE(0)->GetOrder()+2;\n    ir2 = &rule2.Get(faceElGeomType, order2);\n    m_vE_coeff->SetTime(t);\n    m_assembleDgpSmoothError->SetIntegrationRule(ir2);\n    errv = m_assembleDgpSmoothError->Ftime(v.get(), m_vE_coeff.get());\n\n    return (errp + errv);\n}\n\n//! Computes DG error for a space-like face\n//! at a specified time\ndouble WaveO1Observer\n:: eval_dgpFspaceError\n(std::shared_ptr<GridFunction>& p,\n std::shared_ptr<GridFunction>& v,\n double t,\n std::shared_ptr<WaveO1InvSqMediumCoeff>&) const\n{\n    double errp=0;\n    double errv=0;\n\n    // assumes that all elements have the same geometry\n    auto elGeomType = p->FESpace()\n                ->GetFE(0)->GetGeomType();\n\n    IntegrationRules rule1{}, rule2{};\n    const IntegrationRule *ir1, *ir2;\n\n    m_pE_coeff->SetTime(t);\n    m_vE_coeff->SetTime(t);\n\n    // pressure\n    int order1 = 2*p->FESpace()->GetFE(0)->GetOrder()+2;\n    ir1 = &rule1.Get(elGeomType, order1);\n    m_assembleDgpSmoothError->SetIntegrationRule(ir1);\n    errp = m_assembleDgpSmoothError->Fspace\n            (p.get(), m_pE_coeff.get());\n            //(p.get(), m_pE_coeff.get(), invSqMed.get());\n\n    // velocity\n    int order2 = 2*v->FESpace()->GetFE(0)->GetOrder()+2;\n    ir2 = &rule2.Get(elGeomType, order2);\n    m_assembleDgpSmoothError->SetIntegrationRule(ir2);\n    m_vE->ProjectCoefficient(*m_vE_coeff);\n    errv = m_assembleDgpSmoothError->Fspace(v.get(), m_vE_coeff.get());\n\n    return (errp + errv);\n}\n\n//! Computes DG^{+} error\nstd::tuple <double, double> WaveO1Observer\n:: eval_xtDgpError (BlockVector& W) const\n{\n    double errDgFtime=0;\n    double errDgFspace=0;\n\n    int Nt = m_tWspace->GetNE();\n    int xdimW1 = m_xW1space->GetTrueVSize();\n    int xdimW2 = m_xW2space->GetTrueVSize();\n\n    Vector& p = W.GetBlock(0);\n    Vector& v = W.GetBlock(1);\n\n    Vector pSol(xdimW1);\n    std::shared_ptr<GridFunction> pGSol\n            = std::make_shared<GridFunction>\n            (m_xW1space, pSol);\n\n    Vector vSol(xdimW2);\n    std::shared_ptr<GridFunction> vGSol\n            = std::make_shared<GridFunction>\n            (m_xW2space, vSol);\n\n    // medium\n    auto invSqMed = std::make_shared<WaveO1InvSqMediumCoeff>\n            (m_testCase);\n\n    ElementTransformation *tTrans = nullptr;\n    const FiniteElement *tFe = nullptr;\n    Vector tShape;\n    Array<int> tVdofs;\n\n    // DG^{+} error for time-like faces\n    Eigen::VectorXd bufErrFtime(Nt);\n    bufErrFtime.setZero();\n\n    double errFtime;\n    for (int n=0; n<Nt; n++)\n    {\n        m_tWspace->GetElementVDofs(n, tVdofs);\n        tTrans = m_tWspace->GetElementTransformation(n);\n\n        tFe = m_tWspace->GetFE(n);\n        int tNdofs = tFe->GetDof();\n        tShape.SetSize(tNdofs);\n\n        int order = 2*tFe->GetOrder()+2;\n        const IntegrationRule *ir\n                = &IntRules.Get(tFe->GetGeomType(), order);\n\n        for (int i = 0; i < ir->GetNPoints(); i++)\n        {\n            const IntegrationPoint &ip = ir->IntPoint(i);\n            tTrans->SetIntPoint(&ip);\n            tFe->CalcShape(ip, tShape);\n\n            // build solution at time t\n            Vector t;\n            tTrans->Transform(ip, t);\n            build_xSol_FG(p, tShape, tVdofs, pSol);\n            build_xSol_FG(v, tShape, tVdofs, vSol);\n\n            errFtime = eval_dgpFtimeError(pGSol, vGSol, t(0));\n\n            double w = ip.weight*tTrans->Weight();\n            bufErrFtime(n) += w*errFtime;\n        }\n    }\n    errDgFtime = std::sqrt(bufErrFtime.sum());\n\n    // DG^{+} error for space-like faces\n    Eigen::VectorXd bufErrFspace(Nt);\n    bufErrFspace.setZero();\n\n    Vector t;\n    IntegrationPoint ip0;\n    ip0.Set1w(0, 1);\n\n    for (int n=0; n<Nt; n++)\n    {\n        int np = n;\n\n        // build solution at tn^{+}\n        m_tWspace->GetElementVDofs(np, tVdofs);\n        tTrans = m_tWspace->GetElementTransformation(np);\n        tFe = m_tWspace->GetFE(np);\n        int tNdofs = tFe->GetDof();\n        tShape.SetSize(tNdofs);\n\n        tTrans->SetIntPoint(&ip0);\n        tFe->CalcShape(ip0, tShape);\n        tTrans->Transform(ip0, t);\n        build_xSol_FG(p, tShape, tVdofs, pSol);\n        build_xSol_FG(v, tShape, tVdofs, vSol);\n\n        // compute error\n        bufErrFspace(n) = eval_dgpFspaceError\n                (pGSol, vGSol, t(0), invSqMed);\n    }\n    errDgFspace = std::sqrt(2*bufErrFspace.sum());\n\n    return {errDgFtime, errDgFspace};\n}\n\n// End of file\n", "meta": {"hexsha": "3797205c5443510c68ebcf60d0bc222618e93119", "size": 5439, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/waveO1/dgp_error.cpp", "max_stars_repo_name": "pratyuksh/FEMWave", "max_stars_repo_head_hexsha": "9ed0fbe0981d712ce3e531500381589b034fb9f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T13:06:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T13:06:38.000Z", "max_issues_repo_path": "src/waveO1/dgp_error.cpp", "max_issues_repo_name": "pratyuksh/FEMWave", "max_issues_repo_head_hexsha": "9ed0fbe0981d712ce3e531500381589b034fb9f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/waveO1/dgp_error.cpp", "max_forks_repo_name": "pratyuksh/FEMWave", "max_forks_repo_head_hexsha": "9ed0fbe0981d712ce3e531500381589b034fb9f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-05T13:06:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T13:06:39.000Z", "avg_line_length": 28.4764397906, "max_line_length": 71, "alphanum_fraction": 0.6162897591, "num_tokens": 1652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.42317437836222604}}
{"text": "//Backend for the instanton finder in the AdS/Flat spacetime case.\r\n#define DLL_EXPORT\r\n#define INSTANTON_SOLVER_DLL_API //Comment this out if we wish to import these\r\n//from a DLL instead.\r\n\r\n#include \"project_specific.h\"\r\n\r\n#include \"multi_precision_definitions.h\"\r\n#include <boost/array.hpp>//For boost arrays (needed for ode_types)\r\n#include \"AdS.h\"\r\n#include <initializer_list>//Allow us to use initialiser lists for vector.\r\n    //This simplifies the code somewhat.\r\n\r\n\r\n//------------------------------------------------------------------------------\r\n//Main function to export:\r\ntemplate< class value_type , class time_type >\r\nvoid odeSolveAdSFlat(value_type false_vacuum , value_type true_vacuum ,\r\n                     value_type barrier , potential< value_type >& V ,\r\n                     time_type chimax , int odeSolverToUse,\r\n                     value_type RelTol, value_type AbsTol, value_type stepError,\r\n                     value_type xi,\r\n                     value_type lowerBound , value_type upperBound ,\r\n                     solution_grid< time_type , std::vector< value_type > ,\r\n                     value_type >& solOut,value_type& DSout,\r\n                     value_type precision,std::ostream& outStream,\r\n                     bool track_scale_factor,bool compute_H0_linearisation)\r\n{\r\n//INPUTS:\r\n    //Ok. we proceed by bisecting until we have a solution which overshoots\r\n    //beyond\r\n    //chimax, which stands in for infinity.\r\n\r\n    //Overshoots occur when the solution crosses zero before chimax.\r\n    //Undershoots when\r\n    //its derivative crosses zero before then.\r\n\r\n    //Instantiate the events function, state-type, dynamic BCs etc...\r\n    typedef std::vector< value_type > AdSFlatSolType;//solution without action,\r\n        //for speed.\r\n    typedef std::vector< value_type > AdSFlatSolTypeAction;\r\n    //typedef odeAdSFlat< AdSFlatSolType , time_type , value_type>odeRHSAdSFlat;\r\n    typedef odeAdSFlat_delta_a< AdSFlatSolType , time_type , value_type>\r\n            odeRHSAdSFlat;\r\n    typedef eventsAdSFlat< AdSFlatSolType , time_type , value_type > evAdSFlat;\r\n    /*typedef dynamicBCsAdSFlat_taylor< value_type , AdSFlatSolType , time_type>\r\n            dynBCAdSFlat;*/\r\n    typedef dynamicBCs_flatfv_delta< value_type , AdSFlatSolType , time_type>\r\n            dynBCAdSFlat;\r\n    /*typedef odeAdSFlatAction<AdSFlatSolTypeAction,time_type,value_type>\r\n            odeRHSAdSFlatAction;*/\r\n    typedef odeAdSFlatAction_delta_a<AdSFlatSolTypeAction,time_type,value_type>\r\n            odeRHSAdSFlatAction;\r\n    typedef eventsAdSFlat< AdSFlatSolTypeAction , time_type , value_type >\r\n            evAdSFlatAction;\r\n    typedef dynamicBCsAdSFlat_taylor< value_type , AdSFlatSolTypeAction ,\r\n                                      time_type > dynBCAdSFlatAction;\r\n    typedef eventsGravFriction<AdSFlatSolType,time_type,value_type> eventsGrav;\r\n    typedef odeGravFriction< AdSFlatSolType , time_type , value_type > odeGrav;\r\n    typedef dynamicBCsGravFriction_taylor< value_type , AdSFlatSolType ,\r\n                                      time_type > dynBCGrav;\r\n    typedef odeGravFrictionAction<AdSFlatSolType,time_type,value_type>\r\n                                    odeGravAction;\r\n\r\n    //Instantiation for overshoot/undershoot:\r\n\r\n    const value_type _1p0 = value_type(1.0);\r\n    const value_type _0p0 = value_type(0.0);\r\n    const value_type _2p0 = value_type(2.0);\r\n    const value_type _6p0 = value_type(6.0);\r\n    std::cout.precision(50);\r\n\r\n    //Potential\r\n    value_type W0 = value_type(0.0);\r\n    value_type h;\r\n    if(xi >= _0p0 && xi < _1p0/_6p0)\r\n    {\r\n        h = _1p0;//h = phi_scale/M_p so h = 1 is Planck units.\r\n    }\r\n    else\r\n    {\r\n        h = _1p0/sqrt(abs(xi));\r\n        //h = value_type(1.0);//h = phi_scale/M_p so h = 1 is Planck units.\r\n    }\r\n\tvalue_type V0 = _0p0;//V at phi = 0.\r\n    odeRHSAdSFlat odeToSolveTrack(V,xi, h, V0); //ode to solve (gravitational\r\n                                                           //instanton equation)\r\n    odeGrav odeToSolveNoTrack(V,xi, h, V0);\r\n    odeRHS<std::vector<value_type>,time_type,value_type>* odeToSolve;\r\n    if(track_scale_factor)\r\n    {\r\n        odeToSolve = &odeToSolveTrack;\r\n    }\r\n    else\r\n    {\r\n        odeToSolve = &odeToSolveNoTrack;\r\n    }\r\n\r\n    evAdSFlat eventsTrack(false_vacuum,true_vacuum,false_vacuum,outStream);\r\n    //events function.\r\n    eventsGrav eventsNoTrack(false_vacuum,true_vacuum);\r\n    events_function< std::vector<value_type> , time_type, value_type >* events;\r\n    if(track_scale_factor)\r\n    {\r\n        events = &eventsTrack;\r\n    }\r\n    else\r\n    {\r\n        events = &eventsNoTrack;\r\n    }\r\n        //Checks for events labelled IE:\r\n        //IE = 1 -> y crosses zero (terminal event, => overshoot)\r\n        //IE = 2 -> y' crosses zero (terminal event, => undershoot)\r\n        //IE = 3 -> a crosses zero (non-terminal event, for reference only)\r\n        //IE = 4 -> y crosses lowerBound (usually 0, but could be different -\r\n                                            //terminal event)\r\n        //IE = 5 -> y crosses upperBound (terminal event, indicates bad initial\r\n                                          //condition or perhaps a->0)\r\n    dynBCAdSFlat bcAdjusterTrack(xi,h,V0,V,stepError,1);\r\n    dynBCGrav bcAdjusterNoTrack(xi,h,V0,V,stepError,1);\r\n    //Performs analytic\r\n    // first\r\n    //step using a taylor series approximation.\r\n        //stepError - determines size of initial step.\r\n        //version (last argument) - specifies which version of the ode we are\r\n            //using.\r\n            //version = 0 -> normal ode, no action.\r\n            //version = 1 -> ode with action\r\n            //version = 2 -> linearised ode.\r\n    dynamicBCs< value_type , std::vector<value_type> , time_type >* bcAdjuster;\r\n    if(track_scale_factor)\r\n    {\r\n        bcAdjuster = &bcAdjusterTrack;\r\n    }\r\n    else\r\n    {\r\n        bcAdjuster = &bcAdjusterNoTrack;\r\n    }\r\n\r\n\r\n\r\n\r\n\r\n\r\n    //Search loop:\r\n    int nMax = 200;\r\n    int counter = 0;\r\n    //Current bounds on location of bounce:\r\n    value_type lower = lowerBound;//Barrier\r\n    value_type upper = upperBound;//True vacuum\r\n    outStream << \"Lower initial = \" << lower << std::endl;\r\n    outStream << \"Upper initial = \" << upper << std::endl;\r\n    value_type guess;\r\n    multi diff = abs(upper - lower);\r\n    outStream << \"diff = \" << diff << std::endl;\r\n    while(diff > precision)\r\n    {\r\n        //outStream << \"Loop stage 1\" <<std::endl;\r\n        //Bisect to get initial guess:\r\n        guess = (lower + upper)/_2p0;\r\n        outStream << \"\\nn = \" << counter << \", guess = \" << guess << \"\\n\";\r\n        outStream << \"\\ndiff = \" << upper - lower;\r\n        //outStream << \"Loop stage 2\" <<std::endl;\r\n\r\n        //Search for FWHMif(track_scale_factor)\r\n        if(track_scale_factor)\r\n        {\r\n            eventsTrack.value_to_check = (guess + false_vacuum)/_2p0;\r\n        }\r\n\r\n\r\n\r\n        //Formulate initial conditions vector:\r\n        AdSFlatSolType y0;\r\n        //value_type y0List[] = { guess , _0p0 , _0p0 , _1p0 };\r\n        value_type y0List[] = { guess , _0p0 , _0p0 , _1p0 , _0p0, _0p0 };\r\n\r\n        y0.assign(y0List,y0List + 6);\r\n        //AdSFlatSolType y0NoTrack;\r\n        //value_type y0NoTrackList[] = { guess , _0p0 , _0p0 , _1p0};\r\n        //y0NoTrack.assign(y0TrackList,y0TrackList + 4);\r\n\r\n        //AdSFlatSolType y0 = track_scale_factor ? y0Track : y0NoTrack;\r\n        //Step away to avoid co-ordinate singularity at chi = 0:\r\n        //outStream << \"Loop stage 3\" <<std::endl;\r\n        AdSFlatSolType y01step = y0;\r\n        time_type epsilon = (*bcAdjuster)(y0,y01step);//Copies solution after\r\n            //step of epsilon into y01step. Last argument tells us whether\r\n            //we step forwards (0) or backwards (1) in time.\r\n        //Set up time range:\r\n        //outStream << \"Loop stage 4\" <<std::endl;\r\n        //time_type tspanArray[2] = { epsilon , chimax };\r\n        std::vector< time_type > tspan;\r\n        time_type tspan_list[] = { epsilon , chimax };\r\n        tspan.assign(tspan_list,tspan_list + 2);\r\n        //tspan.assign(tspanArray,tspanArray + 2);\r\n        //Solve the ode:\r\n        //outStream << \"Loop stage 5\" <<std::endl;\r\n        solution_grid< time_type , AdSFlatSolType , value_type > solTemp;\r\n        time_type initStepMax = time_type(0.01)/time_type(chimax);\r\n        //outStream << \"Integrating...\" <<std::endl;\r\n        int nSuccess = ode_solve<time_type,AdSFlatSolType,value_type>\r\n            (*odeToSolve,y01step,tspan,(*events),odeSolverToUse,solTemp,RelTol,\r\n             AbsTol,initStepMax);\r\n        if(nSuccess != 1)\r\n        {\r\n            outStream << \"nSuccess = \" << nSuccess\r\n                      << \" when solving for AdS-Flat instantons.\" << std::endl;\r\n            throw \"Integration failure.\";\r\n        }\r\n        //Now check whether we found an overshoot or an undershoot:\r\n        bool overshoots = false;\r\n        bool undershoots = false;\r\n        for(int j = 0; j < int(solTemp.IE.size());j++)\r\n        {\r\n            switch(solTemp.IE[j])\r\n            {\r\n            case 1:\r\n                //overshoot.\r\n                //outStream << \"Overshoot.\" << std::endl;\r\n                //reportToCaller(\"Overshoot.\\n\");\r\n                if(track_scale_factor)\r\n                {\r\n                    overshoots = true;\r\n                    upper = guess;\r\n                }\r\n                //else we just found a' = 0, so not terminal.\r\n                break;\r\n            case 2:\r\n                //undershoot, IF it occurs on the opposite side of the barrier\r\n                //to the true vacuum (theoretically impossible to occur on the\r\n                //other side, so must be a numerical artefact if it does).\r\n                if((true_vacuum - barrier)*(solTemp.YE[j][0] - barrier)\r\n                   < value_type(0.0))\r\n                {\r\n                    //outStream << \"Undershoot.\" << std::endl;\r\n                    //reportToCaller(\"Undershoot.\\n\");\r\n                    undershoots = true;\r\n                    lower = guess;\r\n                }\r\n                break;\r\n            case 3:\r\n                //Found a = 0 point.\r\n                outStream << \"Found a = 0. Error, or possibly background is \"\r\n                          << \"de-Sitter like.\" << std::endl;\r\n                //reportToCaller(\"Found a = 0. Error, or possibly background is\r\n                                 //de-Sitter like.\");\r\n                throw \"Unexpected ode-event encountered during integration.\";\r\n            case 4:\r\n                //crossed upper bound, so overshoot for tracking a'/a version,\r\n                //FWHM for the a',a separately tracked version.\r\n                if(!track_scale_factor)\r\n                {\r\n                    overshoots = true;\r\n                    upper = guess;\r\n                    eventsNoTrack.y0upperBound = upper;\r\n                }\r\n                break;\r\n            case 5:\r\n                //Crossed lower bound (in both cases).\r\n                //Usually indicates an overshoot:\r\n                //outStream << \"Overshoot.\" << std::endl;\r\n                //reportToCaller(\"Overshoot.\\n\");\r\n                overshoots = true;\r\n                upper = guess;\r\n                if(!track_scale_factor)\r\n                {\r\n                    eventsNoTrack.y0upperBound = upper;\r\n                }\r\n                break;\r\n            case 6:\r\n                //Crossed upper bound. Only\r\n                //occurs for the a'/a version.\r\n                //Indicates a bad initial condition.\r\n                outStream << \"Upper bound crossed during ode integration. \"\r\n                          << \"Possibly a bad initial condition (wrong side of \"\r\n                          << \"true vacuum) or solution undershot and event \"\r\n                          << \"detection failed to detect this.\" << std::endl;\r\n                //reportToCaller(\"Upper bound crossed during ode integration.\r\n                    //Possibly a bad initial condition (wrong side\r\n                    //of true vacuum) or solution undershot and event detection\r\n                    //failed to detect this.\\n\");\r\n                throw \"Unexpected ode-event encountered during integration.\";\r\n            default:\r\n                outStream << \"Unrecognised ode-event.\" << std::endl;\r\n                //reportToCaller(\"Unrecognised ode-event.\\n\");\r\n                throw \"Unexpected ode-event encountered during integration.\";\r\n            }\r\n            if(overshoots || undershoots)\r\n            {\r\n                break;\r\n            }\r\n        }\r\n        counter++;\r\n        diff = abs(lower - upper);\r\n        //outStream << \"y0Upper - y0lower = \" << diff << std::endl;\r\n        if(overshoots)\r\n        {\r\n            outStream << \"Overshoot.\\n\" << std::endl;\r\n        }\r\n        else if(undershoots)\r\n        {\r\n            outStream << \"Undershoot.\\n\" << std::endl;\r\n        }\r\n\r\n        //Dump all available data if we get neither an overshoot nor an\r\n        //undershoot, as this is\r\n        //theoretically impossible so we want to understand what went wrong:\r\n        else if(!(overshoots||undershoots))\r\n        {\r\n            outStream << \"Neither undershoot nor overshoot detected. \"\r\n                      << \"(Perhaps integration range should be extended?) \"\r\n                      << \"Relevant data:\\n\";\r\n            outStream << \"no. of events = \" << int(solTemp.IE.size())\r\n                      << std::endl;\r\n            for(int i = 0; i < int(solTemp.IE.size());i++)\r\n            {\r\n                outStream << \"IE[\" << i << \"] = \" << solTemp.IE[i] << std::endl;\r\n                outStream << \"YE[\" << i << \"] = \" << std::endl;\r\n                for(int j = 0;j < y01step.size();j++)\r\n                {\r\n                    outStream << solTemp.YE[i][j] << std::endl;\r\n                }\r\n                outStream << \"TE[\" << i << \"] = \" << solTemp.TE[i] << std::endl;\r\n            }\r\n            outStream << \"y0 = \\n\";\r\n            for(int i = 0;i < y01step.size();i++)\r\n            {\r\n                outStream << y01step[i] << std::endl;\r\n            }\r\n            outStream << \"yend = \\n\";\r\n            for(int i = 0;i < y01step.size();i++)\r\n            {\r\n                outStream << solTemp.Y[int(solTemp.Y.size() - 1)][i]\r\n                          << std::endl;\r\n            }\r\n            outStream << \"Tend = \" << solTemp.T[int(solTemp.T.size()) - 1]\r\n                      << std::endl;\r\n            //Now exit, throwing an error:\r\n            throw \"Error - Neither overshoot nor undershoot detected.\\n\";\r\n        }\r\n\r\n    }\r\n    //We found the bounce. Are we within precision?\r\n    if(diff > precision)\r\n    {\r\n        outStream << \"Loop exited before finding bounce.\" << std::endl;\r\n        //reportToCaller(\"Loop exited before finding bounce.\\n\");\r\n    }\r\n\r\n    //Compute action:\r\n    odeRHSAdSFlatAction odeToSolveActionTrack(V,xi,h,V0);\r\n    evAdSFlatAction eventsActionTrack(false_vacuum,true_vacuum,false_vacuum,\r\n                                 outStream);\r\n    dynBCAdSFlatAction bcAdjusterActionTrack(xi,h,V0,V,stepError,2);\r\n    odeGravAction odeToSolveActionNoTrack(V,xi,h,V0);\r\n    dynBCGrav bcAdjusterActionNoTrack(xi,h,V0,V,stepError,2);\r\n    odeRHS<std::vector<value_type>,time_type,value_type>* odeToSolveAction;\r\n    dynamicBCs< value_type , std::vector<value_type> , time_type >*\r\n        bcAdjusterAction;\r\n    eventsGrav eventsActionNoTrack(false_vacuum,true_vacuum);\r\n    events_function< std::vector<value_type> , time_type, value_type >*\r\n        eventsAction;\r\n    if(track_scale_factor)\r\n    {\r\n        odeToSolveAction = &odeToSolveActionTrack;\r\n        bcAdjusterAction = &bcAdjusterActionTrack;\r\n        eventsAction = &eventsActionTrack;\r\n    }\r\n    else\r\n    {\r\n        odeToSolveAction = &odeToSolveActionNoTrack;\r\n        bcAdjusterAction = &bcAdjusterActionNoTrack;\r\n        eventsAction = &eventsActionNoTrack;\r\n    }\r\n    //outStream << \"Computing final bounce solution... \" << std::endl;\r\n\r\n    //Check for when the solution passes through its FWHM:\r\n    //This feature isn't yet implemented for the NoTrack version, so we don't\r\n    //use it in that case.\r\n    if(track_scale_factor)\r\n    {\r\n        eventsActionTrack.value_to_check = (guess + false_vacuum)/_2p0;\r\n    }\r\n\r\n    //Boundary conditions at x = 0\r\n    AdSFlatSolTypeAction y0Action;\r\n    //value_type y0ActionList[] = {guess,_0p0,_0p0,_1p0,_0p0};\r\n    value_type y0ActionList[] = {guess,_0p0,_0p0,_1p0,_0p0,_0p0,_0p0};\r\n    //y0Action.assign(y0ActionList,y0ActionList + 5);\r\n    y0Action.assign(y0ActionList,y0ActionList + 7);\r\n    AdSFlatSolTypeAction y0Action1step = y0Action;\r\n    //Same BCs work for NoTrack, where we use theta = log(a + 1)\r\n\r\n    //Step to boundary conditions slightly offset from x = 0:\r\n    time_type epsAction = (*bcAdjusterAction)(y0Action,y0Action1step);\r\n\r\n    //Integration range:\r\n    time_type tspanArray[2] = { epsAction , chimax };\r\n    std::vector< time_type > tspan;\r\n    tspan.assign(tspanArray,tspanArray + 2);\r\n    time_type initStepMax = time_type(0.01)/time_type(chimax);\r\n\r\n    //Integrate:\r\n    int nSuccess = ode_solve<time_type,AdSFlatSolTypeAction,value_type>\r\n    (*odeToSolveAction,y0Action1step,tspan,*eventsAction,odeSolverToUse,solOut,\r\n     RelTol,AbsTol,initStepMax);\r\n    if(nSuccess != 1)\r\n    {\r\n        outStream << \"nSuccess = \" << nSuccess << \" when solving for AdS-Flat\"\r\n                  << \"instantons.\" << std::endl;\r\n        throw \"Integration failure.\";\r\n    }\r\n    DSout = solOut.Y[int(solOut.T.size()) - 1][4];\r\n    outStream << \"Done.\" << std::endl;\r\n    //Done.\r\n}\r\n//------------------------------------------------------------------------------\r\ntemplate< class value_type , class time_type >\r\nvoid odeSolveAdSFlatSingle(value_type y0, value_type false_vacuum ,\r\n                           value_type true_vacuum , value_type barrier ,\r\n                           potential< value_type >& V , time_type chimax ,\r\n                           int odeSolverToUse,\r\n                           value_type RelTol, value_type AbsTol,\r\n                           value_type stepError, value_type xi,\r\n                           value_type lowerBound , value_type upperBound ,\r\n                           solution_grid< time_type , std::vector< value_type >,\r\n                           value_type >& solOut,value_type& DSout,\r\n                           value_type precision,std::ostream& outStream,\r\n                           bool track_scale_factor)\r\n{\r\n//INPUTS:\r\n\r\n     outStream << \"Starting Integration for y0 = \\n\" << y0 << std::endl;\r\n     outStream << \"\\nV(y0) = \" << V(y0) << std::endl;\r\n\r\n     const value_type _1p0 = value_type(1.0);\r\n     const value_type _0p0 = value_type(0.0);\r\n     const value_type _2p0 = value_type(2.0);\r\n     const value_type _6p0 = value_type(6.0);\r\n\r\n    //Ok. we proceed by bisecting until we have a solution which overshoots\r\n    //beyond\r\n    //chimax, which stands in for infinity.\r\n\r\n    //Overshoots occur when the solution crosses zero before chimax.\r\n    //Undershoots when\r\n    //its derivative crosses zero before then.\r\n\r\n    //Instantiate the events function, state-type, dynamic BCs etc...\r\n    typedef std::vector< value_type > AdSFlatSolType;//solution without action,\r\n        //for speed.\r\n    typedef std::vector< value_type > AdSFlatSolTypeAction;\r\n    typedef odeAdSFlat< AdSFlatSolType , time_type , value_type > odeRHSAdSFlat;\r\n    typedef eventsAdSFlat< AdSFlatSolType , time_type , value_type > evAdSFlat;\r\n    typedef dynamicBCsAdSFlat_taylor< value_type , AdSFlatSolType , time_type >\r\n            dynBCAdSFlat;\r\n    typedef odeAdSFlatAction< AdSFlatSolTypeAction , time_type , value_type >\r\n            odeRHSAdSFlatAction;\r\n    typedef eventsAdSFlat< AdSFlatSolTypeAction , time_type , value_type >\r\n            evAdSFlatAction;\r\n    typedef dynamicBCsAdSFlat_taylor< value_type , AdSFlatSolTypeAction ,\r\n                                      time_type > dynBCAdSFlatAction;\r\n    typedef eventsGravFriction<AdSFlatSolType,time_type,value_type> eventsGrav;\r\n    typedef odeGravFriction< AdSFlatSolType , time_type , value_type > odeGrav;\r\n    typedef dynamicBCsGravFriction_taylor< value_type , AdSFlatSolType ,\r\n                                      time_type > dynBCGrav;\r\n    typedef odeGravFrictionAction<AdSFlatSolType,time_type,value_type>\r\n                                    odeGravAction;\r\n\r\n    //Instantiation for overshoot/undershoot:\r\n\r\n    //Compute action:\r\n    value_type W0 = _0p0;\r\n    value_type h;\r\n    if(xi >= _0p0 && xi < _1p0/_6p0)\r\n    {\r\n        h = _1p0;//h = phi_scale/M_p so h = 1 is Planck units.\r\n    }\r\n    else\r\n    {\r\n        h = _1p0/sqrt(abs(xi));\r\n        //h = value_type(1.0);//h = phi_scale/M_p so h = 1 is Planck units.\r\n    }\r\n    //Setup odeRHS, event-detector, and dynamicBC objects needed:\r\n    odeRHSAdSFlatAction odeToSolveActionTrack(V,xi,h,W0);\r\n    evAdSFlatAction eventsActionTrack(false_vacuum,true_vacuum,false_vacuum,\r\n                                 outStream);\r\n    dynBCAdSFlatAction bcAdjusterActionTrack(xi,h,W0,V,stepError,2);\r\n    odeGravAction odeToSolveActionNoTrack(V,xi,h,W0);\r\n    dynBCGrav bcAdjusterActionNoTrack(xi,h,W0,V,stepError,2);\r\n    odeRHS<std::vector<value_type>,time_type,value_type>* odeToSolveAction;\r\n    dynamicBCs< value_type , std::vector<value_type> , time_type >*\r\n        bcAdjusterAction;\r\n    eventsGrav eventsActionNoTrack(false_vacuum,true_vacuum);\r\n    events_function< std::vector<value_type> , time_type, value_type >*\r\n        eventsAction;\r\n    if(track_scale_factor)\r\n    {\r\n        odeToSolveAction = &odeToSolveActionTrack;\r\n        bcAdjusterAction = &bcAdjusterActionTrack;\r\n        eventsAction = &eventsActionTrack;\r\n    }\r\n    else\r\n    {\r\n        odeToSolveAction = &odeToSolveActionNoTrack;\r\n        bcAdjusterAction = &bcAdjusterActionNoTrack;\r\n        eventsAction = &eventsActionNoTrack;\r\n    }\r\n\r\n\r\n    AdSFlatSolTypeAction y0Action;\r\n    value_type y0ActionList[] = { y0 , _0p0 , _0p0 , _1p0 , _0p0 };\r\n    y0Action.assign(y0ActionList,y0ActionList + 5);\r\n    AdSFlatSolTypeAction y0Action1step = y0Action;\r\n    outStream << \"Compute boundary conditions.\\n\";\r\n    time_type epsAction = (*bcAdjusterAction)(y0Action,y0Action1step);\r\n    outStream << \"Done.\";\r\n    outStream << \"\\ny0 = \" << y0Action1step[0];\r\n    outStream << \"\\ny0p = \" << y0Action1step[1];\r\n    outStream << \"\\na0 = \" << y0Action1step[2];\r\n    outStream << \"\\na0p = \" << y0Action1step[3];\r\n    outStream << \"\\nS = \" << y0Action1step[4];\r\n    time_type tspanArray[2] = { epsAction , chimax };\r\n    std::vector< time_type > tspan;\r\n    tspan.assign(tspanArray,tspanArray + 2);\r\n    time_type initStepMax = time_type(0.01)/time_type(chimax);\r\n    outStream << \"Starting integration.\";\r\n    int nSuccess = ode_solve<time_type,AdSFlatSolTypeAction,value_type>\r\n    (*odeToSolveAction,y0Action1step,tspan,*eventsAction,odeSolverToUse,solOut,\r\n     RelTol,AbsTol,initStepMax);\r\n    if(nSuccess != 1)\r\n    {\r\n        outStream << \"nSuccess = \" << nSuccess << \" when solving for AdS-Flat\"\r\n                  << \" instantons.\" << std::endl;\r\n        throw \"Integration failure.\";\r\n    }\r\n    DSout = solOut.Y[int(solOut.T.size()) - 1][4];\r\n    //Done.\r\n}\r\n//------------------------------------------------------------------------------\r\n\r\n//------------------------------------------------------------------------------\r\n//Explicit instantiation and export of this function:\r\ntemplate DLL_EXPORT void odeSolveAdSFlat\r\n    < multi , multi >\r\n    (multi , multi , multi , potential< multi >& , multi , int,multi, multi ,\r\n     multi, multi, multi , multi ,\r\n     solution_grid< multi , std::vector< multi > , multi >&,\r\n     multi&, multi, std::ostream&,bool,bool);\r\n//------------------------------------------------------------------------------\r\ntemplate DLL_EXPORT void odeSolveAdSFlatSingle\r\n    < multi , multi >\r\n    (multi , multi , multi , multi , potential< multi >& , multi , int, multi,\r\n     multi , multi, multi, multi , multi ,\r\n     solution_grid< multi , std::vector< multi > , multi >&,\r\n     multi&, multi, std::ostream&,bool);\r\n//------------------------------------------------------------------------------\r\n", "meta": {"hexsha": "a511cb75247d4c54e4f141fe87105066555a3613", "size": 24195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AdS.cpp", "max_stars_repo_name": "svstopyra/dS_instanton_solver", "max_stars_repo_head_hexsha": "9517036c03ec9129989ed7f1e3eeecabf4119bfe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AdS.cpp", "max_issues_repo_name": "svstopyra/dS_instanton_solver", "max_issues_repo_head_hexsha": "9517036c03ec9129989ed7f1e3eeecabf4119bfe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AdS.cpp", "max_forks_repo_name": "svstopyra/dS_instanton_solver", "max_forks_repo_head_hexsha": "9517036c03ec9129989ed7f1e3eeecabf4119bfe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.282647585, "max_line_length": 81, "alphanum_fraction": 0.5677206034, "num_tokens": 6014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026368, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.42317437150090775}}
{"text": "//\r\n// Created by KH on 3/7/2020.\r\n//\r\n\r\n#include \"CNode.h\"\r\n#include \"CTree.h\"\r\n\r\n#include <klib/math.h>\r\n#include <klib/random.h>\r\n#include <klib/vecutils.h>\r\n\r\n#include <memory>\r\n#include <boost/container/small_vector.hpp>\r\n#include <boost/container/flat_set.hpp>\r\n#include <boost/iterator/counting_iterator.hpp>\r\n\r\n#include <tsl/robin_set.h>\r\n\r\nnamespace igen {\r\n\r\n\r\nstatic const double Epsilon = 1E-4;\r\n\r\nstatic const int V_LOG_BUILD = 100;\r\n\r\nCNode::CNode(CTree *tree, CNode *parent, int id, std::array<boost::sub_range<vec<PConfig>>, 2> configs) :\r\n        tree(tree), parent(parent), id_(id), configs_(std::move(configs)) {\r\n    depth_ = (parent ? parent->depth() + 1 : 0);\r\n    if (parent) {\r\n        tested_vars_ = parent->tested_vars_;\r\n    } else {\r\n        tested_vars_ = dom()->create_vec_vars<bool>();\r\n    }\r\n}\r\n\r\nconst PDomain &CNode::dom() const {\r\n    return tree->ctx()->dom();\r\n}\r\n\r\nconst PVarDomain &CNode::dom(int var_id) const {\r\n    return dom()->vars()[var_id];\r\n}\r\n\r\nvoid CNode::calc_freq() {\r\n    int n_vars = (int) dom()->n_vars();\r\n    auto &freq = tree->t_freq;\r\n    for (auto &a : freq) for (auto &b : a) for (auto &c : b) c = 0;\r\n    for (const auto &c : configs_[0]) {\r\n        const auto &vals = c->values();\r\n        for (int var_id = 0; var_id < n_vars; ++var_id) {\r\n            freq[0][var_id][vals[var_id]]++;\r\n        }\r\n    }\r\n    for (const auto &c : configs_[1]) {\r\n        const auto &vals = c->values();\r\n        for (int var_id = 0; var_id < n_vars; ++var_id) {\r\n            freq[1][var_id][vals[var_id]]++;\r\n        }\r\n    }\r\n}\r\n\r\nvoid CNode::calc_inf_gain() {\r\n    splitvar = -1;\r\n    double log2ntotal = log2(n_total());\r\n    auto &freq = tree->t_freq;\r\n    auto &info = tree->t_info, &gain = tree->t_gain;\r\n\r\n    // Calc info\r\n    for (int var_id = 0; var_id < dom()->n_vars(); ++var_id) {\r\n        if (tested_vars_[var_id]) continue;\r\n        double sum = 0;\r\n        for (int val = 0; val < dom()->n_values(var_id); ++val) {\r\n            int n = freq[0][var_id][val] + freq[1][var_id][val];\r\n            sum += n * log2(n);\r\n        }\r\n        info[var_id] = log2ntotal - sum / n_total();\r\n    }\r\n\r\n    // Calc base_info\r\n    double base_info = 0;\r\n    for (int hit = 0; hit <= 1; ++hit) {\r\n        int n = int(configs_[hit].size());\r\n        base_info += n * log2(n);\r\n    }\r\n    base_info = log2ntotal - base_info / n_total();\r\n\r\n    // Calc gain\r\n    double total_gain = 0;\r\n    for (int var_id = 0; var_id < dom()->n_vars(); ++var_id) {\r\n        if (tested_vars_[var_id]) continue;\r\n        double &g = (gain[var_id] = 0);\r\n        for (int val = 0; val < dom()->n_values(var_id); ++val) {\r\n            double sum = 0;\r\n            int total = 0;\r\n            for (int hit = 0; hit <= 1; ++hit) {\r\n                int n = freq[hit][var_id][val];\r\n                sum += n * log2(n);\r\n                total += n;\r\n            }\r\n            sum = total * log2(total) - sum;\r\n            g += sum;\r\n        }\r\n        g = base_info - g / n_total();\r\n        total_gain += g;\r\n    }\r\n\r\n    // Calc avgain & mdl\r\n    avgain = 0;\r\n    possible = 0;\r\n    for (int var = 0; var < dom()->n_vars(); ++var) {\r\n        if (tested_vars_[var]) continue;\r\n        if (gain[var] >= Epsilon &&\r\n            (tree->multi_val_ || dom(var)->n_values() < 0.3 * (tree->n_cases_ + 1))) {\r\n            possible++;\r\n            avgain += gain[var];\r\n        } else {\r\n            //Gain[Att] = None;\r\n        }\r\n    }\r\n\r\n    avgain /= possible;\r\n    mdl = log2(possible) / int(hit_configs().size() + miss_configs().size());\r\n    mingain = avgain * tree->avgain_wt_ + mdl * tree->mdl_wt_;\r\n}\r\n\r\nint CNode::select_best_var(bool first_pass) {\r\n    auto &info = tree->t_info, &gain = tree->t_gain;\r\n    splitvar = -1;\r\n    find_pass = first_pass ? 1 : 2;\r\n    double bestratio = -1000;\r\n    int bestnbr = dom()->n_all_values();\r\n\r\n    for (int var = 0; var < dom()->n_vars(); ++var) {\r\n        if (tested_vars_[var]) continue;\r\n\r\n        double inf = info[var];\r\n\r\n        if (first_pass) {\r\n            if (gain[var] < 0.999 * mingain || inf <= 0) continue;\r\n        } else {\r\n            if (inf <= 0) inf = Epsilon;\r\n        }\r\n\r\n        double val = gain[var] / inf;\r\n        int nbr = dom()->n_values(var);\r\n\r\n        if (val > bestratio\r\n            || (val > 0.999 * bestratio && (nbr < bestnbr || (nbr == bestnbr && gain[var] > gain[var])))) {\r\n            splitvar = var;\r\n            bestratio = val;\r\n            bestnbr = nbr;\r\n        }\r\n    }\r\n\r\n    return splitvar;\r\n}\r\n\r\nvoid CNode::create_childs() {\r\n    CHECK(0 <= splitvar && splitvar < dom()->n_vars());\r\n    int nvalues = dom()->n_values(splitvar);\r\n\r\n    tested_vars_[splitvar] = true;\r\n    childs.resize(nvalues);\r\n\r\n    for (int hit = 0; hit <= 1; ++hit) {\r\n        auto &c = configs_[hit];\r\n        const auto &freq = tree->t_freq[hit][splitvar];\r\n        auto &tmp_conf = tree->t_conf;\r\n        tmp_conf.assign(std::make_move_iterator(c.begin()), std::make_move_iterator(c.end()));\r\n        auto &curpos = tree->t_curpos[hit];\r\n        curpos.resize(nvalues);\r\n        curpos[0] = c.begin();\r\n        for (int i = 1; i < nvalues; ++i) {\r\n            curpos[i] = curpos[i - 1] + freq[i - 1];\r\n        }\r\n        for (auto &x : tmp_conf) {\r\n            int v = x->values()[splitvar];\r\n            *curpos[v]++ = move(x);\r\n        }\r\n        CHECK(curpos[nvalues - 1] == c.end());\r\n        //DCHECK(std::is_sorted(c.begin(), c.end(), [splitvar = splitvar](const auto &a, const auto &b) {\r\n        //    return a->get(splitvar) < b->get(splitvar);\r\n        //}));\r\n        //std::stable_sort(c.begin(), c.end(), [splitvar = splitvar](const auto &a, const auto &b) {\r\n        //    return a->get(splitvar) < b->get(splitvar);\r\n        //});\r\n    }\r\n\r\n    for (int i = 0; i < nvalues; ++i) {\r\n        auto &pos = tree->t_curpos;\r\n        auto &c = configs_;\r\n        boost::sub_range<vec<PConfig>> miss_conf = {i == 0 ? c[0].begin() : pos[0][i - 1], pos[0][i]};\r\n        boost::sub_range<vec<PConfig>> hit_conf = {i == 0 ? c[1].begin() : pos[1][i - 1], pos[1][i]};\r\n        childs[i] = new CNode(tree, this, i, {miss_conf, hit_conf});\r\n    }\r\n}\r\n\r\nbool CNode::evaluate_split() {\r\n    if (is_leaf()) {\r\n        CHECK(n_hits() == 0 || n_misses() == 0); // Same config lead to 2 different result?\r\n        GVLOG(V_LOG_BUILD) << \"\\n<\" << depth() << \">: \" << n_total() << \" cases\\n    \"\r\n                           << (leaf_value() ? \"HIT\" : \"MISS\");\r\n        min_cases_in_one_leaf_ = n_total();\r\n        return false;\r\n    }\r\n\r\n    calc_freq();\r\n    calc_inf_gain();\r\n    if (select_best_var(true) == -1) select_best_var(false);\r\n    CHECK_NE(splitvar, -1);\r\n    VLOG_BLOCK(V_LOG_BUILD, print_tmp_state(log << \"\\n<\" << depth() << \">: \" << n_total() << \" cases\\n\"));\r\n\r\n    split_by = dom()->vars().at(splitvar);\r\n    create_childs();\r\n\r\n    min_cases_in_one_leaf_ = std::numeric_limits<int>::max();\r\n    for (auto &c : childs) {\r\n        c->evaluate_split();\r\n        min_cases_in_one_leaf_ = std::min(min_cases_in_one_leaf_, c->min_cases_in_one_leaf_);\r\n    }\r\n\r\n    return split_by != nullptr;\r\n}\r\n\r\nstd::ostream &CNode::print_tmp_state(std::ostream &output, const str &indent) const {\r\n    auto &freq = tree->t_freq;\r\n    auto &info = tree->t_info, &gain = tree->t_gain;\r\n    for (const auto &var : dom()->vars()) {\r\n        // if (info[var->id()] < 0 || gain[var->id()] < 0)\r\n        //     continue;\r\n        if (tested_vars_[var->id()]) continue;\r\n        output << indent << \"Var \" << var->name() << \": \\n\";\r\n        fmt::print(output, \"{}{}[{:>4}{:>8}{:>8}]\\n\", indent, indent, \"Val\", \"MISS\", \"HIT\");\r\n        for (int i = 0; i < var->n_values(); ++i) {\r\n            fmt::print(output, \"{}{}[{:>4}{:>8}{:>8}]\\n\", indent, indent,\r\n                       i, freq[0][var->id()][i], freq[1][var->id()][i]);\r\n        }\r\n        fmt::print(output, \"{}{}info {:.3f}, gain {:.3f}, val {:.3f}\\n\", indent, indent,\r\n                   info[var->id()], gain[var->id()], gain[var->id()] / info[var->id()]);\r\n    }\r\n    fmt::print(output, \"{}av gain={:.3f}, MDL ({}) = {:.3f}, min={:.3f}\\n\",\r\n               indent, avgain, possible, mdl, mingain);\r\n    fmt::print(output, \"{}best var \", indent);\r\n    if (splitvar == -1) {\r\n        output << \"N/A\\n\";\r\n    } else {\r\n        fmt::print(output, \"{}: info {:.3f}, gain {:.3f}, val {:.3f}{}\",\r\n                   dom()->name(splitvar), info[splitvar], gain[splitvar], gain[splitvar] / info[splitvar],\r\n                   find_pass == 1 ? \"\\n\" : \", second-pass\\n\");\r\n    }\r\n    return output;\r\n}\r\n\r\nbool CNode::leaf_value() const {\r\n    CHECK(is_leaf());\r\n    if (hit_configs().empty() && miss_configs().empty())\r\n        return tree->default_hit_;\r\n    return !hit_configs().empty();\r\n}\r\n\r\n\r\nz3::expr CNode::build_zexpr_mixed() const {\r\n    if (is_leaf()) {\r\n        return tree->ctx()->zbool(leaf_value());\r\n    }\r\n    CHECK(splitvar != -1 && int(childs.size()) == dom(splitvar)->n_values());\r\n\r\n    z3::expr res(tree->ctx_mut()->zctx()), e = res;\r\n    bool empty_res = true;\r\n\r\n    for (int val = 0; val < int(childs.size()); ++val) {\r\n        bool need_or = false;\r\n        if (childs[val]->is_leaf()) {\r\n            if (childs[val]->leaf_value()) {\r\n                e = dom(splitvar)->eq(val);\r\n                need_or = true;\r\n            }\r\n        } else {\r\n            e = dom(splitvar)->eq(val) && childs[val]->build_zexpr_mixed();\r\n            need_or = true;\r\n        }\r\n        if (need_or) {\r\n            if (empty_res) res = e, empty_res = false;\r\n            else res = res || e;\r\n        }\r\n    }\r\n    CHECK(!empty_res);\r\n    return res;\r\n}\r\n\r\nvoid CNode::build_zexpr_disj_conj(z3::expr_vector &vec_res, const expr &cur_expr) const {\r\n    if (is_leaf() && leaf_value()) {\r\n        vec_res.push_back(cur_expr);\r\n        return;\r\n    }\r\n    for (int val = 0; val < int(childs.size()); ++val) {\r\n        expr next_expr = depth_ == 0 ?\r\n                         dom(splitvar)->eq(val) :\r\n                         cur_expr && dom(splitvar)->eq(val);\r\n        childs[val]->build_zexpr_disj_conj(vec_res, next_expr);\r\n    }\r\n}\r\n\r\nvoid CNode::print_node(std::ostream &output, str &prefix) const {\r\n    if (is_leaf()) {\r\n        output << (leaf_value() ? \"HIT\" : \"MISS\") << \" (\" << n_total() << \")\\n\";\r\n        return;\r\n    }\r\n    CHECK_NE(splitvar, -1);\r\n    CHECK_GE(n_childs(), 2);\r\n    const str &var_name = dom(splitvar)->name();\r\n\r\n    prefix.append(\":   \");\r\n    for (int v = 0; v < n_childs(); ++v) {\r\n        if (v == n_childs() - 1) prefix.at(prefix.size() - 4) = ' ';\r\n\r\n        const PMutCNode n = childs[v];\r\n        if (v == 0) {\r\n            if (prefix.size() >= 8)\r\n                output << std::string_view(prefix.data(), prefix.size() - 8) << \":...\";\r\n        } else {\r\n            output << std::string_view(prefix.data(), prefix.size() - 4);\r\n        }\r\n        output << var_name << \" = \" << dom(splitvar)->label(v) << (n->is_leaf() ? \": \" : \":\\n\");\r\n        n->print_node(output, prefix);\r\n    }\r\n    prefix.resize(prefix.size() - 4);\r\n}\r\n\r\nstd::pair<bool, int> CNode::test_config(const PConfig &conf) const {\r\n    if (is_leaf()) return {leaf_value(), n_total()};\r\n    CHECK_NE(splitvar, -1);\r\n    return childs.at(size_t(conf->get(splitvar)))->test_config(conf);\r\n}\r\n\r\nstd::pair<bool, int> CNode::test_add_config(const PConfig &conf, bool val) {\r\n    if (is_leaf()) {\r\n        bool leaf_val = leaf_value();\r\n        if (leaf_val == val) {\r\n            min_cases_in_one_leaf_++;\r\n            new_configs_.push_back(conf);\r\n            CHECK_EQ(min_cases_in_one_leaf_, n_total() + new_configs_.size());\r\n        }\r\n        return {leaf_val, n_total()};\r\n    }\r\n    CHECK_NE(splitvar, -1);\r\n    auto res = childs.at(size_t(conf->get(splitvar)))->test_add_config(conf, val);\r\n    min_cases_in_one_leaf_ = std::numeric_limits<int>::max();\r\n    for (auto &c : childs) {\r\n        min_cases_in_one_leaf_ = std::min(min_cases_in_one_leaf_, c->min_cases_in_one_leaf_);\r\n    }\r\n    return res;\r\n}\r\n\r\n// =====================================================================================================================\r\n\r\nvoid CNode::gather_small_leaves(vec<PConfig> &res, int min_confs, int max_confs, const PMutConfig &curtpl) const {\r\n    if (is_leaf()) {\r\n        if (min_confs <= min_cases_in_one_leaf_ && min_cases_in_one_leaf_ <= max_confs)\r\n            res.emplace_back(new Config(curtpl));\r\n        return;\r\n    }\r\n    CHECK_NE(splitvar, -1);\r\n    for (int v = 0; v < n_childs(); ++v) {\r\n        CHECK(curtpl->get(splitvar) == -1);\r\n        curtpl->set(splitvar, v);\r\n        childs[v]->gather_small_leaves(res, min_confs, max_confs, curtpl);\r\n        curtpl->set(splitvar, -1);\r\n    }\r\n}\r\n\r\nvoid CNode::gather_leaves_nodes(vec<ptr<const CNode>> &res, int min_confs, int max_confs) const {\r\n    if (is_leaf()) {\r\n        if (min_confs <= min_cases_in_one_leaf_ && min_cases_in_one_leaf_ <= max_confs)\r\n            res.emplace_back(this);\r\n        return;\r\n    }\r\n    CHECK_NE(splitvar, -1);\r\n    for (int v = 0; v < n_childs(); ++v) {\r\n        childs[v]->gather_leaves_nodes(res, min_confs, max_confs);\r\n    }\r\n}\r\n\r\nvoid CNode::gen_tpl(Config &conf) const {\r\n    if (is_leaf()) {\r\n        CHECK_EQ(splitvar, -1);\r\n    }\r\n    if (parent != nullptr) {\r\n        CHECK_NE(parent->splitvar, -1);\r\n        conf.set(parent->splitvar, id_);\r\n        parent->gen_tpl(conf);\r\n    }\r\n}\r\n\r\nvec<ptr<Config>> CNode::gen_one_convering_configs(int lim) const {\r\n    const PMutContext ctx = tree->ctx();\r\n    const PDomain dom = tree->ctx()->dom();\r\n    //====\r\n    Config templ(ctx);\r\n    templ.set_all(-1);\r\n    gen_tpl(templ);\r\n    //====\r\n    tsl::robin_set<hash_t> shash;\r\n    shash.reserve((size_t) n_total());\r\n    // Note: either hit_configs() or miss_configs() is empty\r\n    CHECK(hit_configs().empty() || miss_configs().empty());\r\n    bool use_solver = ((n_total() + sz(new_configs_)) <= 1000);\r\n    if (use_solver) {\r\n        for (const auto &c : hit_configs()) shash.insert(c->hash());\r\n        for (const auto &c : miss_configs()) shash.insert(c->hash());\r\n        for (const auto &c : new_configs_) shash.insert(c->hash());\r\n    }\r\n    //====\r\n    vec<sm_vec<int>> SetVAL;\r\n    SetVAL.reserve((size_t) dom->n_vars());\r\n    int n_finished = 0;\r\n    for (int i = 0; i < dom->n_vars(); i++) {\r\n        if (templ.get(i) == -1) {\r\n            SetVAL.emplace_back(boost::counting_iterator<int>(0), boost::counting_iterator<int>(dom->n_values(i)));\r\n        } else {\r\n            SetVAL.emplace_back();\r\n            n_finished++;\r\n        }\r\n    }\r\n\r\n    VLOG(100, \"Tpl: \\n\") << templ;\r\n\r\n    vec<PMutConfig> ret;\r\n    std::unique_ptr<Z3Scope> z3;\r\n    while (n_finished < dom->n_vars() && int(ret.size()) < lim) {\r\n        PMutConfig conf = new Config(ctx);\r\n        sm_vec<int, 128> vrand;\r\n        for (int i = 0; i < dom->n_vars(); i++) {\r\n            sm_vec<int> &st = SetVAL[i];\r\n            int tmplval = templ.values()[i];\r\n            if (tmplval != -1) {\r\n                conf->set(i, tmplval);\r\n            } else if (!st.empty()) {\r\n                auto it = Rand.get(st);\r\n                conf->set(i, *it);\r\n                unordered_erase(st, it);\r\n                if (st.empty())\r\n                    n_finished++;\r\n            } else {\r\n                conf->set(i, Rand.get(dom->n_values(i)));\r\n                vrand.push_back(i);\r\n            }\r\n        }\r\n        if (shash.insert(conf->hash()).second) {\r\n            if (z3 != nullptr) (*z3)->add(!conf->to_expr());\r\n            ret.emplace_back(move(conf));\r\n        } else if (use_solver) {\r\n            for (int id : vrand) conf->set(id, -1);\r\n\r\n            if (z3 == nullptr) {\r\n                z3 = std::make_unique<Z3Scope>(ctx->zscope());\r\n                for (const auto &c : hit_configs()) (*z3)->add(!c->to_expr());\r\n                for (const auto &c : miss_configs()) (*z3)->add(!c->to_expr());\r\n                for (const auto &c : new_configs_) (*z3)->add(!c->to_expr());\r\n                for (const auto &c : ret) (*z3)->add(!c->to_expr());\r\n                //(*z3)->set(\"timeout\", 600u * 1000u); // 600s\r\n            }\r\n\r\n            expr e = conf->to_expr();\r\n            if ((*z3)->check(1, &e) == z3::sat) {\r\n                z3::model m = (*z3)->get_model();\r\n                for (int id : vrand)\r\n                    conf->set(id, dom->var(id)->val_id_of(m.get_const_interp(dom->var(id)->zvar().decl())));\r\n\r\n                VLOG(100, \"Found cex for tpl using solver ({} conds): \\n\", shash.size()) << templ << '\\n' << *conf;\r\n                bool insert_res = shash.insert(conf->hash(true /*recalc hash*/)).second;\r\n                CHECK(insert_res) << *conf;\r\n                (*z3)->add(!conf->to_expr());\r\n                ret.emplace_back(move(conf));\r\n            } else {\r\n                VLOG(100, \"Can't find cex for tpl: \") << templ;\r\n            }\r\n        }\r\n    }\r\n\r\n    VLOG_BLOCK(100, {\r\n        log << \"CEX:\\n\";\r\n        for (const auto &c : ret) log << *c << '\\n';\r\n    });\r\n\r\n    return ret;\r\n}\r\n\r\nstd::ostream &CNode::serialize(std::ostream &out, bool &last_is_char) const {\r\n    if (is_leaf()) {\r\n        out << \"MH\"[leaf_value()];\r\n        last_is_char = true;\r\n    } else {\r\n        if (last_is_char) out << ' ', last_is_char = false;\r\n        out << splitvar << ' ';\r\n        for (const auto &c : childs) c->serialize(out, last_is_char);\r\n    }\r\n    return out;\r\n}\r\n\r\nstd::istream &CNode::deserialize(std::istream &inp) {\r\n    if (inp >> splitvar) {\r\n        CHECK(0 <= splitvar && splitvar < dom()->n_vars());\r\n        childs.resize(dom()->n_values(splitvar));\r\n        for (int i = 0; i < sz(childs); ++i) {\r\n            childs[i] = new CNode(tree, this, i, {hit_configs(), miss_configs()});\r\n            childs[i]->deserialize(inp);\r\n        }\r\n    } else if (char c; inp.clear(), inp >> c) {\r\n        CHECK(c == 'H' || c == 'M');\r\n        boost::sub_range<vec<PConfig>> empty = {tree->configs_[0].begin(), tree->configs_[0].begin()};\r\n        configs_[0] = configs_[1] = empty;\r\n        configs_[c == 'H'] = tree->configs_[0];\r\n    } else {\r\n        CHECK(0);\r\n    }\r\n    return inp;\r\n}\r\n\r\nvoid CNode::build_interpreter(vec<int> &dat) const {\r\n    if (is_leaf()) {\r\n        dat.push_back(leaf_value() ? CTree::kInterpretHit : CTree::kInterpretMiss);\r\n    } else {\r\n        dat.push_back(splitvar);\r\n        CHECK_EQ(childs.size(), dom(splitvar)->n_values());\r\n        int beg = sz(dat), nchilds = sz(childs);\r\n        dat.resize(beg + nchilds - 1);\r\n        for (int i = 0; i < nchilds; ++i) {\r\n            childs[i]->build_interpreter(dat);\r\n            if (i < nchilds - 1)\r\n                dat[beg + i] = sz(dat);\r\n        }\r\n    }\r\n}\r\n\r\n}", "meta": {"hexsha": "5b0a3e6a0d234ebb1e1b92da66ce0e1b13456b99", "size": 18613, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igen/c50/CNode.cpp", "max_stars_repo_name": "unsat/gentree", "max_stars_repo_head_hexsha": "694ad9f26ef693c6870935de3988f31130587afc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-07T01:07:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-07T01:07:48.000Z", "max_issues_repo_path": "igen/c50/CNode.cpp", "max_issues_repo_name": "dynaroars/gentree", "max_issues_repo_head_hexsha": "694ad9f26ef693c6870935de3988f31130587afc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-14T21:27:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-14T21:29:49.000Z", "max_forks_repo_path": "igen/c50/CNode.cpp", "max_forks_repo_name": "dynaroars/gentree", "max_forks_repo_head_hexsha": "694ad9f26ef693c6870935de3988f31130587afc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T15:23:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-12T15:23:53.000Z", "avg_line_length": 34.7257462687, "max_line_length": 121, "alphanum_fraction": 0.5019072691, "num_tokens": 5184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.42317243431359514}}
{"text": "\n\n/* --------------------------------------------------------------------- \n * \n * Copyright (C) 1999 - 2021 by the deal.II authors \n * \n * This file is part of the deal.II library. \n * \n * The deal.II library is free software; you can use it, redistribute \n * it, and/or modify it under the terms of the GNU Lesser General \n * Public License as published by the Free Software Foundation; either \n * version 2.1 of the License, or (at your option) any later version. \n * The full text of the license can be found in the file LICENSE.md at \n * the top level directory of deal.II. \n * \n * --------------------------------------------------------------------- \n */ \n\n\n// @sect3{Include files}  \n\n// 库中最基本的类是Triangulation类，它在这里声明。\n\n#include <deal.II/grid/tria.h> \n\n// 这里有一些生成标准网格的函数。\n\n#include <deal.II/grid/grid_generator.h> \n\n// 输出各种图形格式的网格。\n\n#include <deal.II/grid/grid_out.h> \n\n// 这对于C++输出来说是需要的。\n\n#include <iostream> \n#include <fstream> \n\n// 这是对 `std::sqrt` 和 `std::fabs` 函数声明的说明。\n\n#include <cmath> \n\n//导入deal.II的最后一步是这样的。所有deal.II的函数和类都在一个命名空间 <code>dealii</code> 中，以确保它们不会与你可能想和deal.II一起使用的其他库的符号发生冲突。我们可以在使用这些函数和类时，在每个名字前加上 <code>dealii::</code> 的前缀，但这很快就会变得繁琐和令人厌烦。相反，我们只是简单地导入整个deal.II的名字空间，以供一般使用。\n\nusing namespace dealii; \n// @sect3{Creating the first mesh}  \n\n// 在下面的第一个函数中，我们简单地使用单位方格作为域，并从中产生一个全局细化网格。\n\nvoid first_grid() \n{ \n\n// 首先要做的是为二维域的三角化定义一个对象。\n\n  Triangulation<2> triangulation; \n\n// 在这里和下面的许多情况下，类名后面的字符串\"<2>\"表示这是一个在两个空间维度上工作的对象。同样，也有一些三角形类的版本是在一个（\"<1>\"）和三个（\"<3>\"）空间维度上工作的。这种工作方式是通过一些模板魔法实现的，我们将在后面的示例程序中详细研究；在那里，我们也将看到如何以一种基本独立于维度的方式编写程序。\n\n// 接下来，我们要用一个正方形领域的单个单元来填充三角结构。三角形被细化了四次，总共得到 $4^4=256$ 个单元。\n\n  GridGenerator::hyper_cube(triangulation); \n  triangulation.refine_global(4); \n\n// 现在我们要将网格的图形表示写到输出文件中。deal.II的GridOut类可以用多种不同的输出格式来实现；在这里，我们选择可扩展矢量图（SVG）格式，你可以用你选择的网络浏览器来进行可视化。\n\n  std::ofstream out(\"grid-1.svg\"); \n  GridOut       grid_out; \n  grid_out.write_svg(triangulation, out); \n  std::cout << \"Grid written to grid-1.svg\" << std::endl; \n} \n\n//  @sect3{Creating the second mesh}  \n\n// 下面第二个函数中的网格略微复杂一些，因为我们使用了一个环形域，并对结果进行了一次全局细化。\n\nvoid second_grid() \n{ \n\n// 我们再次开始定义一个二维域的三角化对象。\n\n  Triangulation<2> triangulation; \n\n// 然后我们用一个环形域来填充它。环的中心应是点(1,0)，内半径和外半径应是0.5和1。圆周单元的数量可以由这个函数自动调整，但我们选择在最后一个参数中明确设置为10。\n\n  const Point<2> center(1, 0); \n  const double   inner_radius = 0.5, outer_radius = 1.0; \n  GridGenerator::hyper_shell( \n    triangulation, center, inner_radius, outer_radius, 10); \n\n// 默认情况下，三角测量假定所有边界都是直线，所有单元都是双线性四边形或三线性六边形，并且它们是由粗略网格（我们刚刚创建的）的单元定义的。除非我们做一些特别的事情，否则当需要引入新的点时，域被假定为由粗网格的直线划定，而新的点将简单地位于周围的中间。然而，在这里，我们知道领域是弯曲的，我们想让三角法根据底层的几何形状来放置新的点。幸运的是，一些优秀的灵魂实现了一个描述球状域的对象，而环是球状域的一个部分；它只需要环的中心，并自动计算出如何指示三角计算在哪里放置新的点。这在deal.II中的工作方式是，你用一个通常被称为 \"流形指标 \"的数字来标记你想要弯曲的三角形部分，然后告诉三角形在所有有这个流形指标的地方使用一个特定的 \"流形对象\"。具体如何操作在此并不重要（你可以在 step-53 和 @ref manifold 中阅读）。GridGenerator中的函数在大多数情况下为我们处理这个问题：它们将正确的流形附加到一个域上，这样当三角形被细化时，新的单元就会被放置在正确的位置上。在目前的情况下， GridGenerator::hyper_shell 为所有的单元格附加了一个球形流形：这将导致单元格在球面坐标的计算下被细化（因此新的单元格的边缘要么是径向的，要么是位于原点周围的同心圆）。\n\n// 默认情况下（即对于手工创建的三角图或未调用GridGenerator函数（如 GridGenerator::hyper_shell 或 GridGenerator::hyper_ball), ），三角图的所有单元格和面都将其manifold_id设置为 numbers::flat_manifold_id, ，如果您想要一个产生直线边缘的流形，这是默认的，但您可以为个别单元格和面改变这个数字。在这种情况下，因此与数字0相关的曲面流形将不适用于那些流形指标为非零的部分，但其他流形描述对象可以与这些非零指标相关联。如果没有流形描述与特定的流形指标相关联，则暗示产生直角边缘的流形。(流形指标是一个略微复杂的话题；如果你对这里到底发生了什么感到困惑，你可能想看看 @ref GlossManifoldIndicator \"关于这个话题的词汇表条目\")。既然 GridGenerator::hyper_shell 选择的默认值是合理的，我们就不去管它。\n\n// 为了演示如何在所有单元格上写一个循环，我们将分五个步骤向域的内圈细化网格。\n\n  for (unsigned int step = 0; step < 5; ++step) \n    { \n\n// 接下来，我们需要对三角形的活动单元进行循环。你可以把三角形看作一个单元格的集合。如果它是一个数组，你只需要得到一个指针，用操作符`++`从一个元素递增到下一个元素。三角形的单元不是作为一个简单的数组来存储的，但是<i>iterator</i>的概念将指针的工作方式概括为任意的对象集合（更多信息见<a href= \"http:en.wikipedia.org/wiki/Iterator#C.2B.2B\">wikipedia</a>）。通常情况下，C++中的任何容器类型都会返回一个迭代器，指向集合的开始，方法称为`begin'，而迭代器则指向集合结束后的1，方法称为`end'。我们可以用操作符`++it`来增加一个迭代器`it`，用`*it`来解除引用以获得底层数据，并通过比较`it != collection.end()`来检查我们是否完成。\n\n// 第二个重要的部分是我们只需要活动单元。活动单元是那些没有被进一步细化的单元，也是唯一可以被标记为进一步细化的单元。deal.II提供了迭代器类别，允许我们在<i>all</i>单元（包括活动单元的父单元）或只在活动单元上迭代。因为我们要的是后者，所以我们需要调用方法 Triangulation::active_cell_iterators().  。\n\n//把所有这些放在一起，我们可以用\n// @code{.cpp}\n//      for (auto it = triangulation.active_cell_iterators().begin();\n//           it != triangulation.active_cell_iterators().end();\n//           ++it)\n//        {\n//          auto cell = *it;\n//  //Then a miracle occurs...\n//        }\n//  @endcode\n//  在一个三角形的所有活动单元上循环。 在这个循环的初始化器中，我们使用了`auto`关键字作为迭代器`it`的类型。`auto`关键字意味着被声明的对象的类型将从上下文中推断出来。当实际的类型名称很长，甚至可能是多余的时候，这个关键字很有用。如果你不确定类型是什么，想查一下结果支持什么操作，你可以去看方法的文档  Triangulation::active_cell_iterators().  在这个例子中，`it`的类型是  `Triangulation::active_cell_iterator`.  \n\n// 虽然`auto`关键字可以让我们不用输入长长的数据类型名称，但我们仍然要输入大量冗余的关于开始和结束迭代器以及如何递增的声明。与其这样，我们不如使用<a href=\"http:en.cppreference.com/w/cpp/language/range-for\">range-based for loops</a>，它将上面显示的所有语法包成一个更短的形式。\n\n      for (auto &cell : triangulation.active_cell_iterators()) \n        { \n// @note  关于deal.II中使用的迭代器类的更多信息，见 @ref Iterators ，关于基于范围的for循环和`auto`关键字的更多信息，见 @ref CPP11 。\n\n// 接下来，我们在单元格的所有顶点上循环。为此，我们查询一个顶点索引的迭代器（在2D中，这是一个包含元素`{0,1,2,3}`的数组，但是由于`cell->vertex_indices()`知道单元格所处的维度，因此返回的数组在所有维度上都是正确的，这使得无论我们在2D还是3D中运行这段代码都是正确的，也就是说，它实现了 \"维度无关的编程\" - 我们将在  step-4  中讨论一个重要部分）。\n\n          for (const auto v : cell->vertex_indices()) \n            { \n\n// 如果这个单元格位于内边界，那么它至少有一个顶点必须位于内环上，因此与中心的径向距离正好是0.5，达到浮点精度。所以我们计算这个距离，如果我们发现一个顶点具有这个属性，我们就标记这个单元，以便以后进行细化。然后我们也可以打破所有顶点的循环，转到下一个单元。        因为离中心的距离是以浮点数计算的，所以我们必须期望我们所计算的东西只能精确到[round-off](https:en.wikipedia.org/wiki/Round-off_error)以内。因此，我们永远不能指望通过平等的方式来比较距离和内半径。诸如 \"if (distance_from_center == inner_radius) \"这样的语句将会失败，除非我们运气特别好。相反，我们需要以一定的容忍度进行比较，通常的方法是写成`if  (std::abs(distance_from_center  。\n\n// - inner_radius) <= tolerance)`，其中`tolerance'是比四舍五入大的某个小数字。问题是如何选择它。我们可以直接选择，比如说，`1e-10'，但这只适合于我们比较的对象是大小为1的情况。如果我们创建了一个单元大小为`1e+10'的网格，那么`1e-10'将远远低于四舍五入，就像以前一样，只有在我们特别幸运的情况下，比较才会成功。相反，使公差*相对于被比较对象的典型 \"比例 \"几乎总是有用的。在这里，\"尺度 \"是指内半径，或者是细胞的直径。我们选择前者，并将公差设置为 $10^{-6}$ 倍环形物的内半径。\n\n              const double distance_from_center = \n                center.distance(cell->vertex(v)); \n\n              if (std::fabs(distance_from_center - inner_radius) <= \n                  1e-6 * inner_radius) \n                { \n                  cell->set_refine_flag(); \n                  break; \n                } \n            } \n        } \n\n// 现在我们已经标记了所有我们想要细化的单元格，我们让三角化实际做这个细化。这样做的函数的名字很长，因为我们也可以标记单元格进行粗化，该函数一次完成粗化和细化。\n\n      triangulation.execute_coarsening_and_refinement(); \n    } \n\n// 最后，在这五次细化迭代之后，我们要再次将得到的网格写入文件，同样是SVG格式。这和上面的工作一样。\n\n  std::ofstream out(\"grid-2.svg\"); \n  GridOut       grid_out; \n  grid_out.write_svg(triangulation, out); \n\n  std::cout << \"Grid written to grid-2.svg\" << std::endl; \n} \n\n//  @sect3{The main function}  \n\n// 最后是主函数。这里没有什么可做的，只是调用两个子函数，产生两个网格。\n\nint main() \n{ \n  first_grid(); \n  second_grid(); \n} \n\n\n\n", "meta": {"hexsha": "42c35f69bbd44986e02734cb19a719f656785b03", "size": 6758, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Translator_file/examples/step-1/step-1.cc", "max_stars_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_stars_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Translator_file/examples/step-1/step-1.cc", "max_issues_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_issues_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Translator_file/examples/step-1/step-1.cc", "max_forks_repo_name": "jiaqiwang969/deal.ii-course-practice", "max_forks_repo_head_hexsha": "0da5ad1537d8152549d8a0e4de5872efe7619c8a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2261904762, "max_line_length": 554, "alphanum_fraction": 0.7278780704, "num_tokens": 3934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.7185943865443352, "lm_q1q2_score": 0.4231724132972702}}
{"text": "#include \"PhysicsTools/Utilities/interface/Parameter.h\"\n#include \"PhysicsTools/Utilities/interface/ZLineShape.h\"\n#include \"PhysicsTools/Utilities/interface/Gaussian.h\"\n#include \"PhysicsTools/Utilities/interface/Numerical.h\"\n#include \"PhysicsTools/Utilities/interface/Exponential.h\"\n#include \"PhysicsTools/Utilities/interface/Polynomial.h\"\n#include \"PhysicsTools/Utilities/interface/Constant.h\"\n#include \"PhysicsTools/Utilities/interface/Convolution.h\"\n#include \"PhysicsTools/Utilities/interface/Operations.h\"\n#include \"PhysicsTools/Utilities/interface/Integral.h\"\n#include \"PhysicsTools/Utilities/interface/MultiHistoChiSquare.h\"\n#include \"PhysicsTools/Utilities/interface/RootMinuit.h\"\n#include \"PhysicsTools/Utilities/interface/RootMinuitCommands.h\"\n#include \"PhysicsTools/Utilities/interface/FunctClone.h\"\n#include \"PhysicsTools/Utilities/interface/rootPlot.h\"\n#include \"TROOT.h\"\n#include \"TH1.h\"\n#include \"TFile.h\"\n#include <boost/program_options.hpp>\nusing namespace boost;\nnamespace po = boost::program_options;\n\n#include <iostream>\n#include <algorithm> \n#include <exception>\n#include <iterator>\n#include <string>\n#include <vector>\nusing namespace std;\n\n// A helper function to simplify the main part.\ntemplate<class T>\nostream& operator<<(ostream& os, const vector<T>& v) {\n  copy(v.begin(), v.end(), ostream_iterator<T>(cout, \" \")); \n  return os;\n}\n\n//A function that sets istogram contents to 0 \n//if they are too small\nvoid fix(TH1* histo) {\n  for(int i = 1; i <= histo->GetNbinsX(); ++i) {\n    if(histo->GetBinContent(i) < 0.1) {\n      histo->SetBinContent(i, 0.0);\n      histo->SetBinError(i, 0.0);\n    }\n  }\n}\n\ntypedef funct::GaussIntegrator IntegratorConv;\ntypedef funct::GaussIntegrator IntegratorNorm;\n//typedef funct::TrapezoidIntegrator IntegratorConv;\n//typedef funct::TrapezoidIntegrator IntegratorNorm;\n\ntypedef funct::Product<funct::Exponential, \n\t\t       funct::Convolution<funct::ZLineShape, funct::Gaussian, IntegratorConv>::type>::type ZPeakNoNorm;\n\nNUMERICAL_FUNCT_INTEGRAL(ZPeakNoNorm, IntegratorNorm);\n\ntypedef funct::DefIntegral<ZPeakNoNorm, funct::Constant, funct::Constant, IntegratorNorm> ZPeakNormFactor;\ntypedef funct::Ratio<ZPeakNoNorm, ZPeakNormFactor>::type ZPeak;\n\nint main(int ac, char *av[]) {\n  gROOT->SetStyle(\"Plain\");\n  try {\n    typedef funct::Power<funct::Parameter, funct::Numerical<2> >::type IsoefficiencytermSQ;\n    typedef funct::Master<funct::Product<funct::Parameter, ZPeak>::type> ZMuMuFun;\n    typedef funct::Slave<funct::Product<funct::Parameter, ZPeak>::type> ZMuMuFunClone;\n    typedef funct::Product<funct::Product<funct::Power<funct::Parameter, funct::Numerical<2> >::type, \n                                          funct::Power<funct::Parameter, funct::Numerical<2> >::type >::type, \n                           IsoefficiencytermSQ >::type  ZMuMuEfficiencyTerm;\n    typedef funct::Product<ZMuMuEfficiencyTerm, ZMuMuFun>::type ZMuMuSig;\n\n\n    typedef funct::Product<funct::Product<funct::Power<funct::Parameter, funct::Numerical<2> >::type, \n                                          funct::Power<funct::Parameter, funct::Numerical<2> >::type >::type, \n                          funct::Difference<funct::Numerical<1>, IsoefficiencytermSQ >::type>::type  ZMuMuNoIsoEfficiencyTerm;\n\n    typedef funct::Product<ZMuMuNoIsoEfficiencyTerm, ZMuMuFunClone>::type ZMuMuNoIsoSig;\n    \n    typedef funct::Product<funct::Product<funct::Numerical<2>, \n                                          funct::Product<funct::Power<funct::Parameter, funct::Numerical<2> >::type, \n                                                         funct::Product<funct::Parameter, \n                                                                        funct::Difference<funct::Numerical<1>, funct::Parameter>::type \n                                                                       >::type \n                                                        >::type \n                           >::type,  IsoefficiencytermSQ >::type  ZMuTkEfficiencyTerm;\n\n\n\n    typedef funct::Product<ZMuTkEfficiencyTerm, ZMuMuFunClone>::type ZMuTkSig;\n    typedef funct::Product<funct::Parameter, \n                           funct::Product<funct::Exponential, funct::Polynomial<2> >::type >::type ZMuTkBkg;\n    typedef funct::Product<funct::Constant,ZMuTkBkg>::type ZMuTkBkgScaled;//bgtrack rescaled\n    typedef ZMuTkBkg ZMuMuNoIsoBkg;\n    typedef ZMuTkBkgScaled  ZMuMuNoIsoBkgScaled ;//bgZmmNotIso rescaled\n    typedef ZMuTkEfficiencyTerm ZMuSaEfficiencyTerm;\n    typedef funct::Product<ZMuSaEfficiencyTerm, \n                           funct::Product<funct::Parameter, funct::Gaussian>::type>::type ZMuSaSig;\n    typedef funct::Product<funct::Parameter, funct::Exponential>::type ZMuSaBkg;\n \n    // typedef ZMuTkBkg ZMuMuNoIsoBkg;\n    typedef funct::Product<funct::Constant, funct::Sum<ZMuMuNoIsoSig, ZMuMuNoIsoBkg>::type>::type ZMuMuNoIso;//3\n    typedef funct::Product<funct::Constant, ZMuMuSig>::type ZMuMu;\n    typedef funct::Product<funct::Constant, funct::Sum<ZMuTkSig, ZMuTkBkg>::type>::type ZMuTk;\n    typedef funct::Product<funct::Constant, funct::Sum<ZMuSaSig, ZMuSaBkg>::type>::type ZMuSa;\n    typedef fit::MultiHistoChiSquare<ZMuMu, ZMuTk, ZMuSa, ZMuMuNoIso> ChiSquared;\n\n    double fMin, fMax;\n    string ext;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n      (\"help,h\", \"produce help message\")\n      (\"input-file,i\", po::value< vector<string> >(), \"input file\")\n      (\"min,m\", po::value<double>(&fMin)->default_value(60), \"minimum value for fit range\")\n      (\"max,M\", po::value<double>(&fMax)->default_value(120), \"maximum value for fit range\")\n      (\"plot-format,p\", po::value<string>(&ext)->default_value(\"ps\"), \n       \"output plot format\")\n      ;\n    \n    po::positional_options_description p;\n    p.add(\"input-file\", -1);\n    \n    po::variables_map vm;\n    po::store(po::command_line_parser(ac, av).\n\t    options(desc).positional(p).run(), vm);\n    po::notify(vm);\n    \n    if (vm.count(\"help\")) {\n      cout << \"Usage: options_description [options]\\n\";\n      cout << desc;\n      return 0;\n      }\n    \n    fit::RootMinuitCommands<ChiSquared> commands(\"csa08ZFit.txt\");\n\n    const int rebinMuMuNoIso = 2,rebinMuMu = 1, rebinMuTk = 2, rebinMuSa = 8;\n    // assume that the bin size is 1 GeV!!!\n    funct::Constant rebinMuMuNoIsoConst(rebinMuMuNoIso),rebinMuMuConst(rebinMuMu), rebinMuTkConst(rebinMuTk), rebinMuSaConst(rebinMuSa);\n\n    if (vm.count(\"input-file\")) {\n      cout << \"Input files are: \" \n\t   << vm[\"input-file\"].as< vector<string> >() << \"\\n\";\n      vector<string> v_file = vm[\"input-file\"].as< vector<string> >();\n      for(vector<string>::const_iterator it = v_file.begin(); \n\t  it != v_file.end(); ++it) {\n\tTFile * root_file = new TFile(it->c_str(),\"read\");\n\n\tTH1D * histoZMuMuNoIso = (TH1D*) root_file->Get(\"nonIsolatedZToMuMuPlots/zMass\");\n\thistoZMuMuNoIso->Rebin(rebinMuMuNoIso);\n\tfix(histoZMuMuNoIso);\n\n\tTH1D * histoZMuMu = (TH1D*) root_file->Get(\"goodZToMuMuPlots/zMass\");\n\thistoZMuMu->Rebin(rebinMuMu);\n\tfix(histoZMuMu);\n\n\tTH1D * histoZMuTk = (TH1D*) root_file->Get(\"goodZToMuMuOneTrackPlots/zMass\");\n\thistoZMuTk->Rebin(rebinMuTk);\n\tfix(histoZMuTk);\n\n\tTH1D * histoZMuSa = (TH1D*) root_file->Get(\"goodZToMuMuOneStandAloneMuonPlots/zMass\");\n\thistoZMuSa->Rebin(rebinMuSa);\n\tfix(histoZMuSa);\n\n\tcout << \">>> histogram loaded\\n\";\n\tstring f_string = *it;\n\treplace(f_string.begin(), f_string.end(), '.', '_');\n\treplace(f_string.begin(), f_string.end(), '/', '_');\n\tstring plot_string = f_string + \".\" + ext;\n\tcout << \">>> Input files loaded\\n\";\n\t\n\tconst char * kYieldZMuMu = \"YieldZMuMu\";\n\tconst char * kEfficiencyTk = \"EfficiencyTk\";\n\tconst char * kEfficiencySa = \"EfficiencySa\";\n\tconst char * kEfficiencyIso = \"EfficiencyIso\";\n\tconst char * kYieldBkgZMuTk = \"YieldBkgZMuTk\"; \n\tconst char * kYieldBkgZMuSa = \"YieldBkgZMuSa\"; \n\tconst char * kYieldBkgZMuMuNotIso = \"YieldBkgZMuMuNotIso\"; \n\tconst char * kLambdaZMuMu = \"LambdaZMuMu\";\n\tconst char * kMass = \"Mass\";\n\tconst char * kGamma = \"Gamma\";\n\tconst char * kPhotonFactorZMuMu = \"PhotonFactorZMuMu\";\n\tconst char * kInterferenceFactorZMuMu = \"InterferenceFactorZMuMu\";\n\tconst char * kMeanZMuMu = \"MeanZMuMu\";\n\tconst char * kSigmaZMuMu = \"SigmaZMuMu\";\n\tconst char * kAlpha = \"Alpha\";\n\tconst char * kB0 = \"B0\"; \n\tconst char * kB1 = \"B1\"; \n\tconst char * kB2 = \"B2\"; \n\tconst char * kLambda = \"Lambda\";\n\tconst char * kA0 = \"A0\"; \n\tconst char * kA1 = \"A1\"; \n\tconst char * kA2 = \"A2\"; \n\tconst char * kBeta = \"Beta\";\n\tconst char * kSigmaZMuSa = \"SigmaZMuSa\";\n\t\n\tfunct::Parameter lambdaZMuMu(kLambdaZMuMu, commands.par(kLambdaZMuMu));\n\tfunct::Parameter mass(kMass, commands.par(kMass));\n\tfunct::Parameter gamma(kGamma, commands.par(kGamma));\n\tfunct::Parameter photonFactorZMuMu(kPhotonFactorZMuMu, commands.par(kPhotonFactorZMuMu)); \n\tfunct::Parameter interferenceFactorZMuMu(kInterferenceFactorZMuMu, commands.par(kInterferenceFactorZMuMu)); \n\tfunct::Parameter yieldZMuMu(kYieldZMuMu, commands.par(kYieldZMuMu));\n\tfunct::Parameter efficiencyTk(kEfficiencyTk, commands.par(kEfficiencyTk)); \n\tfunct::Parameter efficiencySa(kEfficiencySa, commands.par(kEfficiencySa)); \n\tfunct::Parameter efficiencyIso(kEfficiencyIso, commands.par(kEfficiencyIso)); \n\tfunct::Parameter yieldBkgZMuTk(kYieldBkgZMuTk, commands.par(kYieldBkgZMuTk));\n\tfunct::Parameter yieldBkgZMuSa(kYieldBkgZMuSa, commands.par(kYieldBkgZMuSa));\n\tfunct::Parameter yieldBkgZMuMuNotIso(kYieldBkgZMuMuNotIso, commands.par(kYieldBkgZMuMuNotIso));\n\tfunct::Parameter meanZMuMu(kMeanZMuMu, commands.par(kMeanZMuMu));\n\tfunct::Parameter sigmaZMuMu(kSigmaZMuMu, commands.par(kSigmaZMuMu)); \n\tfunct::Parameter sigmaZMuSa(kSigmaZMuSa, commands.par(kSigmaZMuSa)); \n\tfunct::Parameter lambda(kLambda, commands.par(kLambda));\n\tfunct::Parameter alpha(kAlpha, commands.par(kAlpha));\n\tfunct::Parameter beta(kBeta, commands.par(kBeta));\n\tfunct::Parameter b0(kB0, commands.par(kB0));\n\tfunct::Parameter b1(kB1, commands.par(kB1));\n\tfunct::Parameter b2(kB2, commands.par(kB2));\n\tfunct::Parameter a0(kA0, commands.par(kA0));\n\tfunct::Parameter a1(kA1, commands.par(kA1));\n\tfunct::Parameter a2(kA2, commands.par(kA2));\n\tfunct::Constant cFMin(fMin), cFMax(fMax);\n\n\t//IntegratorConv integratorConv(20);\n\t//IntegratorNorm integratorNorm(20);\n\tIntegratorConv integratorConv(1.e-4);\n\tIntegratorNorm integratorNorm(1.e-4);\n\n\tZPeakNoNorm zPeakNN = funct::Exponential(lambdaZMuMu) * \n\t  funct::conv(funct::ZLineShape(mass, gamma, photonFactorZMuMu, interferenceFactorZMuMu), \n\t\t      funct::Gaussian(meanZMuMu, sigmaZMuMu), \n\t\t      -3*sigmaZMuMu.value(), 3*sigmaZMuMu.value(), integratorConv);\n\tZPeak zPeak = zPeakNN / ZPeakNormFactor(zPeakNN, cFMin, cFMax, integratorNorm);\n\tZMuMuFun zMuMuFun = funct::master(yieldZMuMu * zPeak);\n\tZMuMuFunClone zMuMuFunClone = funct::slave(zMuMuFun);\n\tIsoefficiencytermSQ efficiencyIsoSquare = (efficiencyIso ^ funct::Numerical<2>(2)); //efficienza Isolamento al quadrato\n\tZMuMuEfficiencyTerm zMuMuEfficiencyTerm = ((efficiencyTk ^ funct::Numerical<2>(2)) * \n\t  (efficiencySa ^ funct::Numerical<2>(2))) * efficiencyIsoSquare; \n\tZMuMuNoIsoEfficiencyTerm zMuMuNoIsoEfficiencyTerm = ((efficiencyTk ^ funct::Numerical<2>(2)) * \n\t  (efficiencySa ^ funct::Numerical<2>(2))) * (funct::Numerical<1>(1) - efficiencyIsoSquare);\n\tZMuMu zMuMu = rebinMuMuConst * (zMuMuEfficiencyTerm * zMuMuFun);\n\n\tZMuTkBkg zMuTkBkg = yieldBkgZMuTk * (funct::Exponential(lambda) * funct::Polynomial<2>(a0, a1, a2));\n\tZMuTkBkgScaled zMuTkBkgScaled = rebinMuTkConst * zMuTkBkg;\n\tZMuTkEfficiencyTerm zMuTkEfficiencyTerm = funct::Numerical<2>(2) * \n\t  ((efficiencyTk ^ funct::Numerical<2>(2)) * (efficiencySa * (funct::Numerical<1>(1) - efficiencySa))) * efficiencyIsoSquare;\n\tZMuTk zMuTk = rebinMuTkConst*(zMuTkEfficiencyTerm * zMuMuFunClone + zMuTkBkg);\n\n\tZMuMuNoIsoBkg zMuMuNoIsoBkg = yieldBkgZMuMuNotIso * (funct::Exponential(alpha) * funct::Polynomial<2>(b0, b1, b2));\n\tZMuMuNoIsoBkgScaled  zMuMuNoIsoBkgScaled = rebinMuMuNoIsoConst * zMuMuNoIsoBkg;\n\tZMuMuNoIso zMuMuNoIso = rebinMuMuNoIsoConst * ((zMuMuNoIsoEfficiencyTerm * zMuMuFunClone) +  zMuMuNoIsoBkg);\n\n\tZMuSaEfficiencyTerm zMuSaEfficiencyTerm = funct::Numerical<2>(2) * \n\t  ((efficiencySa ^ funct::Numerical<2>()) * (efficiencyTk * (funct::Numerical<1>() - efficiencyTk)))* efficiencyIsoSquare ;\n\tZMuSa zMuSa = rebinMuSaConst *(zMuSaEfficiencyTerm * (yieldZMuMu * funct::Gaussian(mass, sigmaZMuSa)) \n\t\t\t\t       + (yieldBkgZMuSa * funct::Exponential(beta)));\n\n\tChiSquared chi2(zMuMu, histoZMuMu, \n\t\t\tzMuTk, histoZMuTk, \n\t\t\tzMuSa, histoZMuSa, \n\t\t\tzMuMuNoIso,histoZMuMuNoIso,\n\t\t\tfMin, fMax);//WARNING attento all'ordine in cui hai definito il ch2\n\tcout << \"N. deg. of freedom: \" << chi2.numberOfBins() << endl;\n\tfit::RootMinuit<ChiSquared> minuit(chi2, true);\n\tcommands.add(minuit, yieldZMuMu);\n\tcommands.add(minuit, efficiencyTk);\n\tcommands.add(minuit, efficiencySa);\n\tcommands.add(minuit, efficiencyIso);\n\tcommands.add(minuit, yieldBkgZMuTk);\n\tcommands.add(minuit, yieldBkgZMuSa);\n\tcommands.add(minuit, yieldBkgZMuMuNotIso);\n\tcommands.add(minuit, lambdaZMuMu);\n\tcommands.add(minuit, mass);\n\tcommands.add(minuit, gamma);\n\tcommands.add(minuit, photonFactorZMuMu);\n\tcommands.add(minuit, interferenceFactorZMuMu);\n\tcommands.add(minuit, meanZMuMu);\n\tcommands.add(minuit, sigmaZMuMu);\n\tcommands.add(minuit, sigmaZMuSa);\n\tcommands.add(minuit, lambda);\n\tcommands.add(minuit, alpha);\n\tcommands.add(minuit, beta);\n\tcommands.add(minuit, a0);\n\tcommands.add(minuit, a1);\n\tcommands.add(minuit, a2);\n\tcommands.add(minuit, b0);\n\tcommands.add(minuit, b1);\n\tcommands.add(minuit, b2);\n\tcommands.run(minuit);\n\tconst unsigned int nPar = 24;//WARNIG: this must be updated manually for now\n\tROOT::Math::SMatrix<double, nPar, nPar, ROOT::Math::MatRepSym<double, nPar> > err;\n\tminuit.getErrorMatrix(err);\n\tstd::cout << \"error matrix:\" << std::endl;\n\tfor(unsigned int i = 0; i < nPar; ++i) {\n\t  for(unsigned int j = 0; j < nPar; ++j) {\n\t    std::cout << err(i, j) << \"\\t\";\n\t  }\n\t  std::cout << std::endl;\n\t} \n\tminuit.printFitResults();\n\n\tdouble s;\n\ts = 0;\n\tfor(int i = 1; i <= histoZMuMuNoIso->GetNbinsX(); ++i)\n\t  s += histoZMuMuNoIso->GetBinContent(i);\n\thistoZMuMuNoIso->SetEntries(s);\n\tfor(int i = 1; i <= histoZMuMu->GetNbinsX(); ++i)\n\t  s += histoZMuMu->GetBinContent(i);\n\thistoZMuMu->SetEntries(s);\n\ts = 0;\n\tfor(int i = 1; i <= histoZMuTk->GetNbinsX(); ++i)\n\t  s += histoZMuTk->GetBinContent(i);\n\thistoZMuTk->SetEntries(s);\n\ts = 0;\n\tfor(int i = 1; i <= histoZMuSa->GetNbinsX(); ++i)\n\t  s += histoZMuSa->GetBinContent(i);\n\thistoZMuSa->SetEntries(s);\n\tstring ZMuMuPlot = \"ZMuMuFit_\" + plot_string;\n\troot::plot<ZMuMu>(ZMuMuPlot.c_str(), *histoZMuMu, zMuMu, fMin, fMax, \n\t\t\t  efficiencyTk, efficiencySa, efficiencyIso,\n\t\t\t  yieldZMuMu, lambdaZMuMu, mass, gamma, photonFactorZMuMu, interferenceFactorZMuMu, \n\t\t\t  meanZMuMu, sigmaZMuMu, \n\t\t\t  kRed, 2, kDashed, 100, \n\t\t\t  \"Z -> #mu #mu mass\", \"#mu #mu invariant mass (GeV/c^{2})\", \n\t\t\t  \"Events\");\n\t\n\tstring ZMuMuNoIsoPlot = \"ZMuMuNoIsoFit_\" + plot_string;\n\troot::plot<ZMuMuNoIso>(ZMuMuNoIsoPlot.c_str(), *histoZMuMuNoIso, zMuMuNoIso, fMin, fMax, \n\t\t\t       efficiencyTk, efficiencySa, efficiencyIso, \n\t\t\t       yieldZMuMu, lambdaZMuMu, mass, gamma, photonFactorZMuMu, interferenceFactorZMuMu, \n\t\t\t       meanZMuMu, sigmaZMuMu, \n\t\t\t       kRed, 2, kDashed, 100, \n\t\t\t       \"Z -> #mu #mu Not Iso mass\", \"#mu #mu invariant mass (GeV/c^{2})\", \n\t\t\t       \"Events\");\t\n\t\n\tstring ZMuTkPlot = \"ZMuTkFit_\" + plot_string;\n\tTF1 funZMuTk = root::tf1<ZMuTk>(\"ZMuTkFunction\", zMuTk, fMin, fMax, \n\t\t\t\t\tefficiencyTk, efficiencySa,efficiencyIso,\n\t\t\t\t\tyieldZMuMu, lambdaZMuMu, mass, gamma, photonFactorZMuMu, interferenceFactorZMuMu, \n\t\t\t\t\tmeanZMuMu, sigmaZMuMu, \n\t\t\t\t\tyieldBkgZMuTk, lambda, a0, a1, a2);\n\tfunZMuTk.SetLineColor(kRed);\n\tfunZMuTk.SetLineWidth(2);\n\tfunZMuTk.SetLineStyle(kDashed);\n\tfunZMuTk.SetNpx(10000);\n\tTF1 funZMuTkBkg = root::tf1<ZMuTkBkgScaled>(\"ZMuTkBack\", zMuTkBkgScaled, fMin, fMax, \n\t\t\t\t\t      yieldBkgZMuTk, lambda, a0, a1, a2);\n\tfunZMuTkBkg.SetLineColor(kGreen);\n\tfunZMuTkBkg.SetLineWidth(2);\n\tfunZMuTkBkg.SetLineStyle(kDashed);\n\tfunZMuTkBkg.SetNpx(10000);\n\thistoZMuTk->SetTitle(\"Z -> #mu + (unmatched) track mass\");\n\thistoZMuTk->SetXTitle(\"#mu + (unmatched) track invariant mass (GeV/c^{2})\");\n\thistoZMuTk->SetYTitle(\"Events\");\n\tTCanvas *canvas = new TCanvas(\"canvas\");\n\thistoZMuTk->Draw(\"e\");\n\tfunZMuTk.Draw(\"same\");\n\tfunZMuTkBkg.Draw(\"same\");\n\tcanvas->SaveAs(ZMuTkPlot.c_str());\n\tcanvas->SetLogy();\n\tstring logZMuTkPlot = \"log_\" + ZMuTkPlot;\n\tcanvas->SaveAs(logZMuTkPlot.c_str());\n\tstring ZMuSaPlot = \"ZMuSaFit_\" + plot_string;\n\troot::plot<ZMuSa>(ZMuSaPlot.c_str(), *histoZMuSa, zMuSa, fMin, fMax, \n\t\t\t  efficiencySa, efficiencyTk, efficiencyIso,\n\t\t\t  yieldZMuMu, mass, sigmaZMuSa, yieldBkgZMuSa, \n\t\t\t  kRed, 2, kDashed, 10000, \n\t\t\t  \"Z -> #mu + (unmatched) standalone mass\", \n\t\t\t  \"#mu + (unmatched) standalone invariant mass (GeV/c^{2})\", \n\t\t\t  \"Events\");\n      }\n    }\n    \n  }\n  catch(std::exception& e) {\n    cerr << \"error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n  catch(...) {\n    cerr << \"Exception of unknown type!\\n\";\n  }\n  return 0;\n}\n\n\n\n", "meta": {"hexsha": "7ae7f022131337dd923f8a1f987a0698f5246f90", "size": 16994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/csa08ZFit.cpp", "max_stars_repo_name": "SWuchterl/cmssw", "max_stars_repo_head_hexsha": "769b4a7ef81796579af7d626da6039dfa0347b8e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-09-08T14:12:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T23:57:01.000Z", "max_issues_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/csa08ZFit.cpp", "max_issues_repo_name": "SWuchterl/cmssw", "max_issues_repo_head_hexsha": "769b4a7ef81796579af7d626da6039dfa0347b8e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 545.0, "max_issues_repo_issues_event_min_datetime": "2017-09-19T17:10:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T16:55:27.000Z", "max_forks_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/csa08ZFit.cpp", "max_forks_repo_name": "SWuchterl/cmssw", "max_forks_repo_head_hexsha": "769b4a7ef81796579af7d626da6039dfa0347b8e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2017-10-04T09:47:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-23T18:04:45.000Z", "avg_line_length": 44.1402597403, "max_line_length": 136, "alphanum_fraction": 0.6965399553, "num_tokens": 5301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245953120233, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.42317211629511214}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_WRENCH6D_HPP\n#define RW_MATH_WRENCH6D_HPP\n\n/**\n * @file Wrench6D.hpp\n */\n\n#if !defined(SWIG)\n#include \"EAA.hpp\"\n#include \"Math.hpp\"\n#include \"Transform3D.hpp\"\n#include \"Vector3D.hpp\"\n\n#include <rw/common/Serializable.hpp>\n\n#include <Eigen/Core>\n#endif\n\nnamespace rw { namespace math {\n\n    /** @addtogroup math */\n    /*@{*/\n\n    /**\n     * @brief Class for representing 6 degrees of freedom wrenches.\n     *\n     * \\f[\n     * \\mathbf{\\nu} =\n     * \\left[\n     *  \\begin{array}{c}\n     *  f_x\\\\\n     *  f_y\\\\\n     *  f_z\\\\\n     *  \\tau_x\\\\\n     *  \\tau_y\\\\\n     *  \\tau_z\n     *  \\end{array}\n     * \\right]\n     * \\f]\n     *\n     * A Wrench is the description of a frames linear force and rotational torque\n     * with respect to some reference frame.\n     *\n     */\n    template< class T = double > class Wrench6D\n    {\n      private:\n        T _wrench[6];\n\n      public:\n        /**\n         * @brief Constructs a 6 degrees of freedom velocity screw\n         *\n         * @param fx [in] @f$ f_x @f$\n         * @param fy [in] @f$ f_y @f$\n         * @param fz [in] @f$ f_z @f$\n         * @param tx [in] @f$ \\tau_x @f$\n         * @param ty [in] @f$ \\tau_y @f$\n         * @param tz [in] @f$ \\tau_z @f$\n         */\n        Wrench6D (T fx, T fy, T fz, T tx, T ty, T tz);\n\n        /**\n         * @brief Constructs based on Eigen data type\n         */\n        template< class R > Wrench6D (const Eigen::MatrixBase< R >& v)\n        {\n            if (v.cols () != 1 || v.rows () != 6)\n                RW_THROW (\"Unable to initialize VectorND with \" << v.rows () << \" x \" << v.cols ()\n                                                                << \" matrix\");\n            for (size_t i = 0; i < 6; i++)\n                _wrench[i] = v.row (i) (0);\n        }\n\n        /**\n         * @brief Default Constructor. Initialized the wrench to 0\n         */\n        Wrench6D ()\n        {\n            _wrench[0] = _wrench[1] = _wrench[2] = _wrench[3] = _wrench[4] = _wrench[5] = 0;\n        }\n\n        /**\n         * @brief Constructs a wrench from a force and torque\n         *\n         * @param force [in] linear force\n         * @param torque [in] angular torque\n         */\n        Wrench6D (const rw::math::Vector3D< T >& force, const rw::math::Vector3D< T >& torque);\n\n        /**\n         * @brief Sets the force component\n         *\n         * @param force [in] linear force\n         */\n        void setForce (const rw::math::Vector3D< T >& force)\n        {\n            _wrench[0] = force (0);\n            _wrench[1] = force (1);\n            _wrench[2] = force (2);\n        }\n\n        /**\n         * @brief Sets the torque component\n         *\n         * @param torque [in] angular torque\n         */\n        void setTorque (const rw::math::Vector3D< T >& torque)\n        {\n            _wrench[3] = torque (0);\n            _wrench[4] = torque (1);\n            _wrench[5] = torque (2);\n        }\n\n        /**\n         * @brief Extracts the force\n         *\n         * @return the force\n         */\n        const rw::math::Vector3D< T > force () const\n        {\n            return rw::math::Vector3D< T > (_wrench[0], _wrench[1], _wrench[2]);\n        }\n\n        /**\n         * @brief Extracts the torque and represents it using an Vector3D<T>\n         *\n         * @return the torque\n         */\n        const rw::math::Vector3D< T > torque () const\n        {\n            return rw::math::Vector3D< T > (_wrench[3], _wrench[4], _wrench[5]);\n        }\n#if !defined(SWIG)\n        /**\n         * @brief Returns reference to wrench element\n         *\n         * @param index [in] index in the wrench, index must be @f$ < 6 @f$.\n         *\n         * @return reference to wrench element\n         */\n        T& operator() (std::size_t index)\n        {\n            assert (index < 6);\n            return _wrench[index];\n        }\n\n        /**\n         * @brief Returns const reference to wrench element\n         *\n         * @param index [in] index in the wrench, index must be @f$ < 6 @f$.\n         *\n         * @return const reference to wrench element\n         */\n        const T& operator() (std::size_t index) const\n        {\n            assert (index < 6);\n            return _wrench[index];\n        }\n\n        /**\n         * @brief Returns const reference to velocity screw element\n         *\n         * @param i [in] index in the screw, index must be @f$ < 6 @f$.\n         *\n         * @return const reference to velocity screw element\n         */\n        const T& operator[] (size_t i) const { return (*this) (i); }\n\n        /**\n         * @brief Returns const reference to velocity screw element\n         *\n         * @param i [in] index in the screw, index must be @f$ < 6 @f$.\n         *\n         * @return const reference to velocity screw element\n         */\n        T& operator[] (size_t i) { return (*this) (i); }\n#else\n        ARRAYOPERATOR (T);\n#endif\n        /**\n         * @brief Adds the wrench given as a parameter to the wrench.\n         *\n         * Assumes the wrenches are represented in the same coordinate system.\n         *\n         * @param wrench [in] Wrench to add\n         *\n         * @return reference to the Wrench6D to support additional assignments.\n         */\n        Wrench6D< T >& operator+= (const Wrench6D< T >& wrench)\n        {\n            for (size_t i = 0; i < 6; i++)\n                _wrench[i] += wrench (i);\n            return *this;\n        }\n\n        /**\n         * @brief Subtracts the wrench given as a parameter from the wrench.\n         *\n         * Assumes the wrenches are represented in the same coordinate system.\n         *\n         * @param wrench [in] Velocity screw to subtract\n         *\n         * @return reference to the Wrench6D to support additional\n         * assignments.\n         */\n        Wrench6D< T >& operator-= (const Wrench6D< T >& wrench)\n        {\n            for (size_t i = 0; i < 6; i++)\n                _wrench[i] -= wrench (i);\n            return *this;\n        }\n\n        /**\n         * @brief Scales wrench with s\n         *\n         * @param s [in] scaling value\n         *\n         * @return reference to the Wrench6D to support additional\n         * assigments\n         */\n        Wrench6D< T >& operator*= (T s)\n        {\n            for (size_t i = 0; i < 6; i++)\n                _wrench[i] *= s;\n\n            return *this;\n        }\n\n        /**\n         * @brief Scales wrench and returns scaled version\n         * @param s [in] scaling value\n         * @return Scaled wrench\n         */\n        const Wrench6D< T > operator* (T s) const\n        {\n            Wrench6D result = *this;\n            result *= s;\n            return result;\n        }\n#if !defined(SWIG)\n        /**\n         * @brief Changes frame of reference and referencepoint of\n         * wrench: @f$ \\robabx{b}{b}{\\mathbf{w}}\\to\n         * \\robabx{a}{a}{\\mathbf{w}} @f$\n         *\n         * The frames @f$ \\mathcal{F}_a @f$ and @f$ \\mathcal{F}_b @f$ are\n         * rigidly connected.\n         *\n         * @param aTb [in] the location of frame @f$ \\mathcal{F}_b @f$ wrt.\n         * frame @f$ \\mathcal{F}_a @f$: @f$ \\robabx{a}{b}{\\mathbf{T}} @f$\n         *\n         * @param bV [in] wrench wrt. frame @f$ \\mathcal{F}_b @f$: @f$\n         * \\robabx{b}{b}{\\mathbf{\\nu}} @f$\n         *\n         * @return the wrench wrt. frame @f$ \\mathcal{F}_a @f$: @f$\n         * \\robabx{a}{a}{\\mathbf{\\nu}} @f$\n         *\n         * Transformation of both the wrench reference point and of the base to\n         * which the wrench is expressed\n         *\n         * \\f[\n         * \\robabx{a}{a}{\\mathbf{w}} =\n         * \\left[\n         *  \\begin{array}{c}\n         *  \\robabx{a}{a}{\\mathbf{force}} \\\\\n         *  \\robabx{a}{a}{\\mathbf{torque}}\n         *  \\end{array}\n         * \\right] =\n         * \\left[\n         *  \\begin{array}{cc}\n         *    \\robabx{a}{b}{\\mathbf{R}} & S(\\robabx{a}{b}{\\mathbf{p}})\n         *    \\robabx{a}{b}{\\mathbf{R}} \\\\\n         *    \\mathbf{0}^{3x3} & \\robabx{a}{b}{\\mathbf{R}}\n         *  \\end{array}\n         * \\right]\n         * \\robabx{b}{b}{\\mathbf{\\nu}} =\n         * \\left[\n         *  \\begin{array}{c}\n         *    \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{b}{\\mathbf{v}} +\n         *    \\robabx{a}{b}{\\mathbf{p}} \\times \\robabx{a}{b}{\\mathbf{R}}\n         *    \\robabx{b}{b}{\\mathbf{\\omega}}\\\\\n         *    \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{b}{\\mathbf{\\omega}}\n         *  \\end{array}\n         * \\right]\n         * \\f]\n         *\n         */\n        friend const Wrench6D< T > operator* (const Transform3D< T >& aTb, const Wrench6D< T >& bV)\n        {\n            const rw::math::Vector3D< T >& bv = bV.force ();\n            const rw::math::Vector3D< T >& bw = bV.torque ();\n            const rw::math::Vector3D< T >& aw = aTb.R () * bw;\n            const rw::math::Vector3D< T >& av = aTb.R () * bv + cross (aTb.P (), aw);\n            return Wrench6D< T > (av, aw);\n        }\n#endif\n#if !defined(SWIG)\n        /**\n         * @brief Changes wrench referencepoint of\n         * wrench: @f$ \\robabx{b}{b}{\\mathbf{w}}\\to\n         * \\robabx{a}{a}{\\mathbf{w}} @f$\n         *\n         * The frames @f$ \\mathcal{F}_a @f$ and @f$ \\mathcal{F}_b @f$ are\n         * rigidly connected.\n         *\n         * @param aPb [in] the location of frame @f$ \\mathcal{F}_b @f$ wrt.\n         * frame @f$ \\mathcal{F}_a @f$: @f$ \\robabx{a}{b}{\\mathbf{T}} @f$\n         *\n         * @param bV [in] wrench wrt. frame @f$ \\mathcal{F}_b @f$: @f$\n         * \\robabx{b}{b}{\\mathbf{\\nu}} @f$\n         *\n         * @return the wrench wrt. frame @f$ \\mathcal{F}_a @f$: @f$\n         * \\robabx{a}{a}{\\mathbf{\\nu}} @f$\n         *\n         * Transformation of both the velocity reference point and of the base to\n         * which the wrench is expressed\n         *\n         * \\f[\n         * \\robabx{a}{a}{\\mathbf{w}} =\n         * \\left[\n         *  \\begin{array}{c}\n         *  \\robabx{a}{a}{\\mathbf{force}} \\\\\n         *  \\robabx{a}{a}{\\mathbf{torque}}\n         *  \\end{array}\n         * \\right] =\n         * \\left[\n         *  \\begin{array}{cc}\n         *    \\robabx{a}{b}{\\mathbf{R}} & S(\\robabx{a}{b}{\\mathbf{p}})\n         *    \\robabx{a}{b}{\\mathbf{R}} \\\\\n         *    \\mathbf{0}^{3x3} & \\robabx{a}{b}{\\mathbf{R}}\n         *  \\end{array}\n         * \\right]\n         * \\robabx{b}{b}{\\mathbf{\\nu}} =\n         * \\left[\n         *  \\begin{array}{c}\n         *    \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{b}{\\mathbf{v}} +\n         *    \\robabx{a}{b}{\\mathbf{p}} \\times \\robabx{a}{b}{\\mathbf{R}}\n         *    \\robabx{b}{b}{\\mathbf{\\omega}}\\\\\n         *    \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{b}{\\mathbf{\\omega}}\n         *  \\end{array}\n         * \\right]\n         * \\f]\n         *\n         */\n        friend const Wrench6D< T > operator* (const rw::math::Vector3D< T >& aPb, const Wrench6D< T >& bV)\n        {\n            const rw::math::Vector3D< T >& bv = bV.force ();\n            const rw::math::Vector3D< T >& bw = bV.torque ();\n            const rw::math::Vector3D< T >& av = bv + cross (aPb, bw);\n            return Wrench6D< T > (av, bw);\n        }\n#endif\n#if !defined(SWIG)\n        /**\n         * @brief Changes frame of reference for wrench: @f$\n         * \\robabx{b}{i}{\\mathbf{w}}\\to \\robabx{a}{i}{\\mathbf{w}}\n         * @f$\n         *\n         * @param aRb [in] the change in orientation between frame\n         * @f$ \\mathcal{F}_a @f$ and frame\n         * @f$ \\mathcal{F}_b @f$: @f$ \\robabx{a}{b}{\\mathbf{R}} @f$\n         *\n         * @param bV [in] velocity screw wrt. frame\n         * @f$ \\mathcal{F}_b @f$: @f$ \\robabx{b}{i}{\\mathbf{\\nu}} @f$\n         *\n         * @return the wrench wrt. frame @f$ \\mathcal{F}_a @f$:\n         * @f$ \\robabx{a}{i}{\\mathbf{w}} @f$\n         *\n         * Transformation of the base to which the wrench is expressed. The wrench\n         * reference point is left intact\n         *\n         * \\f[\n         * \\robabx{a}{i}{\\mathbf{w}} =\n         * \\left[\n         *  \\begin{array}{c}\n         *  \\robabx{a}{i}{\\mathbf{force}} \\\\\n         *  \\robabx{a}{i}{\\mathbf{torque}}\n         *  \\end{array}\n         * \\right] =\n         * \\left[\n         *  \\begin{array}{cc}\n         *    \\robabx{a}{b}{\\mathbf{R}} & \\mathbf{0}^{3x3} \\\\\n         *    \\mathbf{0}^{3x3} & \\robabx{a}{b}{\\mathbf{R}}\n         *  \\end{array}\n         * \\right]\n         * \\robabx{b}{i}{\\mathbf{\\nu}} =\n         * \\left[\n         *  \\begin{array}{c}\n         *    \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{i}{\\mathbf{v}} \\\\\n         *    \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{i}{\\mathbf{\\omega}}\n         *  \\end{array}\n         * \\right]\n         * \\f]\n         */\n        friend const Wrench6D< T > operator* (const Rotation3D< T >& aRb, const Wrench6D< T >& bV)\n        {\n            rw::math::Vector3D< T > bv = bV.force ();\n            rw::math::Vector3D< T > bw = bV.torque ();\n\n            return Wrench6D< T > (aRb * bv, aRb * bw);\n        }\n#endif\n\n        /**\n         * @brief Adds two wrenches together @f$\n         * \\mathbf{w}_{12}=\\mathbf{w}_1+\\mathbf{w}_2 @f$\n         *\n         * @param rhs [in] @f$ \\mathbf{\\nu}_1 @f$\n         *\n         * @return the wrench @f$ \\mathbf{w}_{12} @f$\n         */\n        const Wrench6D< T > operator+ (const Wrench6D< T >& rhs) const\n        {\n            return Wrench6D< T > (_wrench[0] + rhs (0),\n                                  _wrench[1] + rhs (1),\n                                  _wrench[2] + rhs (2),\n                                  _wrench[3] + rhs (3),\n                                  _wrench[4] + rhs (4),\n                                  _wrench[5] + rhs (5));\n        }\n\n        /**\n         * @brief Subtracts two velocity screws\n         * \\f$\\mathbf{\\nu}_{12}=\\mathbf{\\nu}_1-\\mathbf{\\nu}_2\\f$\n         *\n         * \\param rhs [in] \\f$\\mathbf{w}_1\\f$\n         * \\return the wrench \\f$\\mathbf{w}_{12} \\f$\n         */\n        const Wrench6D< T > operator- (const Wrench6D< T >& rhs) const\n        {\n            return Wrench6D< T > (_wrench[0] - rhs (0),\n                                  _wrench[1] - rhs (1),\n                                  _wrench[2] - rhs (2),\n                                  _wrench[3] - rhs (3),\n                                  _wrench[4] - rhs (4),\n                                  _wrench[5] - rhs (5));\n        }\n#if !defined(SWIG)\n        /**\n         * @brief Ouputs wrench to stream\n         *\n         * @param os [in/out] stream to use\n         * @param wrench [in] the wrench\n         * @return the resulting stream\n         */\n        friend std::ostream& operator<< (std::ostream& os, const Wrench6D< T >& wrench)\n        {\n            return os << \"{{\" << wrench (0) << \",\" << wrench (1) << \",\" << wrench (2) << \"},{\"\n                      << wrench (3) << \",\" << wrench (4) << \",\" << wrench (5) << \"}}\";\n            // return os << wrench.e();\n        }\n#else\n        TOSTRING (rw::math::Wrench6D< T >);\n#endif\n\n        /**\n         * @brief Takes the 1-norm of the wrench. All elements both\n         * force and torque are given the same weight.\n         * @return the 1-norm\n         */\n        T norm1 () const\n        {\n            return fabs (_wrench[0]) + fabs (_wrench[1]) + fabs (_wrench[2]) + fabs (_wrench[3]) +\n                   fabs (_wrench[4]) + fabs (_wrench[5]);\n            // return _wrench.template lpNorm<1>();\n        }\n\n        /**\n         * @brief Takes the 2-norm of the wrench. All elements both\n         * force and torque are given the same weight\n         * @return the 2-norm\n         */\n        T norm2 () const\n        {\n            return std::sqrt (Math::sqr (_wrench[0]) + Math::sqr (_wrench[1]) +\n                              Math::sqr (_wrench[2]) + Math::sqr (_wrench[3]) +\n                              Math::sqr (_wrench[4]) + Math::sqr (_wrench[5]));\n        }\n\n        /**\n         * @brief Takes the infinite norm of the wrench. All elements\n         * both force and torque are given the same weight.\n         *\n         * @return the infinite norm\n         */\n        T normInf () const\n        {\n            return std::max (\n                fabs (_wrench[0]),\n                std::max (fabs (_wrench[1]),\n                          std::max (fabs (_wrench[2]),\n                                    std::max (fabs (_wrench[3]),\n                                              std::max (fabs (_wrench[4]), fabs (_wrench[5]))))));\n        }\n\n        /**\n           @brief Converter to Eigen data type\n         */\n        Eigen::Matrix< T, 6, 1 > e () const\n        {\n            Eigen::Matrix< T, 6, 1 > res;\n            for (size_t i = 0; i < 6; i++)\n                res (i) = _wrench[i];\n            return res;\n        }\n\n        /**\n         * @brief Compares \\b a and \\b b for equality.\n         * @param b [in] other wrench to compare with.\n         * @return True if a equals b, false otherwise.\n         */\n        bool operator== (const Wrench6D< T >& b) const\n        {\n            return _wrench[0] == b[0] && _wrench[1] == b[1] && _wrench[2] == b[2] &&\n                   _wrench[3] == b[3] && _wrench[4] == b[4] && _wrench[5] == b[5];\n        }\n\n        /**\n         * @brief Compares \\b a and \\b b for inequality.\n         * @param b [in] other wrench to compare with.\n         * @return True if a and b are different, false otherwise.\n         */\n        bool operator!= (const Wrench6D< T >& b) const { return !(*this == b); }\n    };\n\n    /**\n     * @brief Takes the 1-norm of the wrench. All elements both\n     * force and torque are given the same weight.\n     *\n     * @param wrench [in] the wrench\n     * @return the 1-norm\n     */\n    template< class T > T norm1 (const Wrench6D< T >& wrench) { return wrench.norm1 (); }\n\n    /**\n     * @brief Takes the 2-norm of the wrench. All elements both\n     * force and tporque are given the same weight\n     *\n     * @param wrench [in] the wrench\n     * @return the 2-norm\n     */\n    template< class T > T norm2 (const Wrench6D< T >& wrench) { return wrench.norm2 (); }\n\n    /**\n     * @brief Takes the infinite norm of the wrench. All elements\n     * both force and torque are given the same weight.\n     *\n     * @param wrench [in] the wrench\n     *\n     * @return the infinite norm\n     */\n    template< class T > T normInf (const Wrench6D< T >& wrench) { return wrench.normInf (); }\n\n    /**\n     * @brief Casts Wrench6D<T> to Wrench6D<Q>\n     *\n     * @param vs [in] Wrench6D with type T\n     *\n     * @return Wrench6D with type Q\n     */\n    template< class Q, class T > const Wrench6D< Q > cast (const Wrench6D< T >& vs)\n    {\n        return Wrench6D< Q > (static_cast< Q > (vs (0)),\n                              static_cast< Q > (vs (1)),\n                              static_cast< Q > (vs (2)),\n                              static_cast< Q > (vs (3)),\n                              static_cast< Q > (vs (4)),\n                              static_cast< Q > (vs (5)));\n    }\n#if !defined(SWIG)\n    extern template class rw::math::Wrench6D< double >;\n    extern template class rw::math::Wrench6D< float >;\n#else\n    SWIG_DECLARE_TEMPLATE (Wrench6Dd, rw::math::Wrench6D< double >);\n    SWIG_DECLARE_TEMPLATE (Wrench6Df, rw::math::Wrench6D< float >);\n#endif\n\n    using Wrench6Dd = Wrench6D< double >;\n    using Wrench6Df = Wrench6D< float >;\n\n    /*@}*/\n}}    // namespace rw::math\n\nnamespace rw { namespace common {\n    class OutputArchive;\n    class InputArchive;\n    namespace serialization {\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::Wrench6D\n         */\n        template<>\n        void write (const rw::math::Wrench6D< double >& sobject,\n                    rw::common::OutputArchive& oarchive, const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::Wrench6D\n         */\n        template<>\n        void write (const rw::math::Wrench6D< float >& sobject, rw::common::OutputArchive& oarchive,\n                    const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Wrench6D\n         */\n        template<>\n        void read (rw::math::Wrench6D< double >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Wrench6D\n         */\n        template<>\n        void read (rw::math::Wrench6D< float >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n    }    // namespace serialization\n}}       // namespace rw::common\n\n#endif    // end include guard\n", "meta": {"hexsha": "e7c8d31e96895012edcd6d463a76fb8ebce9cf89", "size": 21351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/Wrench6D.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/Wrench6D.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/math/Wrench6D.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3088923557, "max_line_length": 106, "alphanum_fraction": 0.4670507236, "num_tokens": 6303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.42311256299010985}}
{"text": "#ifndef SKYLARK_ML_MODEL_HPP\n#define SKYLARK_ML_MODEL_HPP\n\n#include <El.hpp>\n#include <El/core/types.h>\n#include <skylark.hpp>\n#include <cmath>\n#include <boost/mpi.hpp>\n#include <sstream>\n#include <fstream>\n#include <iostream>\n#include <cstdlib>\n#include <string>\n#include <vector>\n#include \"kernels.hpp\"\n#include \"options.hpp\"\n\n#ifdef SKYLARK_HAVE_OPENMP\n#include <omp.h>\n#endif\n\nnamespace skylark { namespace ml {\n\nint classification_accuracy(El::Matrix<double>& Yt, El::Matrix<double>& Yp) {\n    int correct = 0;\n    double o, o1;\n    int pred;\n\n\n    for(int i=0; i < Yp.Height(); i++) {\n        o = Yp.Get(i,0);\n        pred = 0;\n        if (Yp.Width()==1)\n            pred = (o >= 0)? +1:-1;\n\n        for(int j=1; j < Yp.Width(); j++) {\n            o1 = Yp.Get(i,j);\n            if ( o1 > o) {\n                o = o1;\n                pred = j;\n            }\n        }\n\n        if(pred == (int) Yt.Get(i,0))\n            correct++;\n    }\n    return correct;\n}\n\nstruct hilbert_model_t {\n    // TODO the following two should depend on the input type\n    // TODO explicit doubles is not desired.\n    typedef El::Matrix<double> intermediate_type;\n    typedef El::Matrix<double> coef_type;\n\n    typedef sketch::sketch_transform_t<boost::any, boost::any>\n    feature_transform_type;\n\n    template<typename SketchTransformType>\n    hilbert_model_t(std::vector<const SketchTransformType *>& maps, bool scale_maps,\n        int num_features, int num_outputs, bool regression) :\n        _coef(num_features, num_outputs), _maps(maps.size()), _scale_maps(scale_maps),\n        _regression(regression), _starts(maps.size()), _finishes(maps.size()) {\n\n        // TODO verify all N dimension of the maps match\n\n        El::Zero(_coef);\n\n        int nf = 0;\n        for(int i = 0; i < maps.size(); i++) {\n            _maps[i] = maps[i]->type_erased();\n            _starts[i] = nf;\n            _finishes[i] = nf + _maps[i]->get_S() - 1;\n            nf += _maps[i]->get_S();\n        }\n\n        _input_size = (_maps.size() == 0) ?\n            num_features : _maps[0]->get_N();\n    }\n\n    hilbert_model_t(const boost::property_tree::ptree &pt) {\n        build_from_ptree(pt);\n    }\n\n    hilbert_model_t(const std::string& fname) {\n        std::ifstream is(fname);\n\n        // Skip all lines begining with \"#\"\n        while(is.peek() == '#')\n            is.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n\n        boost::property_tree::ptree pt;\n        boost::property_tree::read_json(is, pt);\n        is.close();\n        build_from_ptree(pt);\n    }\n\n    ~hilbert_model_t() {\n        for (auto it = _maps.begin(); it != _maps.end(); it++)\n            delete *it;\n    }\n\n    boost::property_tree::ptree to_ptree() const {\n        boost::property_tree::ptree pt;\n        pt.put(\"skylark_object_type\", \"model:linear-on-features\");\n        pt.put(\"skylark_version\", VERSION);\n\n        pt.put(\"num_features\", _coef.Height());\n        pt.put(\"num_outputs\", _coef.Width());\n        pt.put(\"input_size\", _input_size);\n        pt.put(\"regression\", _regression);\n\n        boost::property_tree::ptree ptfmap;\n        ptfmap.put(\"number_maps\", _maps.size());\n        ptfmap.put(\"scale_maps\", _scale_maps);\n\n\n        boost::property_tree::ptree ptmaps;\n        for(int i = 0; i < _maps.size(); i++)\n            ptmaps.push_back(std::make_pair(std::to_string(i),\n                    _maps[i]->to_ptree()));\n        ptfmap.add_child(\"maps\", ptmaps);\n\n        pt.add_child(\"feature_mapping\", ptfmap);\n\n        std::stringstream scoef;\n        El::Print(_coef, \"\", scoef);\n        pt.put(\"coef_matrix\", scoef.str());\n\n        return pt;\n    }\n\n    /**\n     * Saves the model to a file named fname. You may want to use this method\n     * from only a single rank.\n     */\n    void save(const std::string& fname, const std::string& header) const {\n        boost::property_tree::ptree pt = to_ptree();\n        std::ofstream of(fname);\n        of << header;\n        boost::property_tree::write_json(of, pt);\n        of.close();\n    }\n\n    template<typename InputType, typename LabelType, typename DecisionType>\n    void predict(const InputType& X, LabelType& PV, DecisionType& DV,\n        int num_threads = 1) const {\n\n        int d = base::Height(X);\n        int k = base::Width(_coef);\n        int n = base::Width(X);\n\n        if (_maps.size() == 0)  {\n            // No maps (linear case)\n\n            DV.Resize(n, k);\n            base::Gemm(El::TRANSPOSE,El::NORMAL,1.0, X, _coef, 0.0, DV);\n        } else {\n            // Non-linear case\n            coef_type Wslice;\n            int j, start, finish, sj;\n\n            El::Zeros(DV, n, k);\n#           ifdef SKYLARK_HAVE_OPENMP\n#           pragma omp parallel for if(num_threads > 1) private(j, start, finish, sj) num_threads(num_threads)\n#           endif\n            for(j = 0; j < _maps.size(); j++) {\n                start = _starts[j];\n                finish = _finishes[j];\n                sj = finish - start  + 1;\n\n                intermediate_type z(sj, n);\n                _maps[j]->apply(&X, &z, sketch::columnwise_tag());\n\n                if (_scale_maps)\n                    // TODO shouldn't it be s instead of d?\n                    El::Scale(sqrt(double(sj) / d), z);\n\n                DecisionType o(n, k);\n\n                El::LockedView(Wslice, _coef, start, 0, sj, k);\n                base::Gemm(El::TRANSPOSE, El::NORMAL, 1.0, z, Wslice, o);\n\n#               ifdef SKYLARK_HAVE_OPENMP\n#               pragma omp critical\n#               endif\n                base::Axpy(+1.0, o, DV);\n            }\n        }\n\n        if (!_regression) {\n            double o, o1, pred;\n            PV.Resize(n, 1);\n            for(int i=0; i < DV.Height(); i++) {\n                o = DV.Get(i,0);\n                pred = 0;\n                if (DV.Width()==1)\n                    pred = (o >= 0)? +1:-1;\n\n                for(int j=1; j < DV.Width(); j++) {\n                    o1 = DV.Get(i,j);\n                    if ( o1 > o) {\n                        o = o1;\n                        pred = j;\n                    }\n                }\n                PV.Set(i,0, pred);\n            }\n        }\n    }\n\n    coef_type& get_coef() { return _coef; }\n\n    int get_output_size() const { return _coef.Width(); }\n    int get_input_size() const { return _input_size; }\n\n    bool is_regression() const { return _regression; }\n\nprotected:\n\n    void build_from_ptree(const boost::property_tree::ptree &pt) {\n        int num_features = pt.get<int>(\"num_features\");\n        int num_outputs = pt.get<int>(\"num_outputs\");\n        _coef.Resize(num_features, num_outputs);\n\n        _input_size = pt.get<int>(\"input_size\");\n        _regression = pt.get<bool>(\"regression\");\n\n        int num_maps = pt.get<int>(\"feature_mapping.number_maps\");\n        _maps.resize(num_maps);\n        const boost::property_tree::ptree &ptmaps =\n            pt.get_child(\"feature_mapping.maps\");\n        for(int i = 0; i < num_maps; i++)\n            _maps[i] =\n                feature_transform_type::from_ptree(\n                   ptmaps.get_child(std::to_string(i)));\n\n        int nf = 0;\n        _starts.resize(num_maps);\n        _finishes.resize(num_maps);\n        for(int i = 0; i < _maps.size(); i++) {\n            _starts[i] = nf;\n            _finishes[i] = nf + _maps[i]->get_S() - 1;\n            nf += _maps[i]->get_S();\n        }\n\n        _scale_maps = pt.get<bool>(\"feature_mapping.scale_maps\");\n\n        std::istringstream coef_str(pt.get<std::string>(\"coef_matrix\"));\n        double *buffer = _coef.Buffer();\n        int ldim = _coef.LDim();\n        for(int i = 0; i < num_features; i++) {\n            std::string line;\n            std::getline(coef_str, line);\n            std::istringstream coefstream(line);\n            for(int j = 0; j < num_outputs; j++) {\n                std::string token;\n                coefstream >> token;\n                buffer[i + j * ldim] = atof(token.c_str());\n            }\n        }\n    }\n\nprivate:\n    coef_type _coef;\n    El::Int _input_size;\n    std::vector<const feature_transform_type *> _maps; // TODO use shared_ptr\n    bool _scale_maps;\n    bool _regression;\n\n    std::vector<int> _starts, _finishes;\n};\n\n//////////////////////////////////////////////////////////////////////////\n\n\ntemplate<typename OutType, typename ComputeType, typename dummy = OutType>\nstruct model_t;\n\n/**\n * Generic (abstract) model for continous output - regression\n */\ntemplate<typename OutType, typename ComputeType>\nstruct model_t<OutType, ComputeType,\n typename std::enable_if<std::is_floating_point<OutType>::value, OutType>::type>\n{\n\n    virtual void predict(base::direction_t direction_XT,\n        const El::DistMatrix<ComputeType> &XT, El::DistMatrix<OutType> &YP)\n        const = 0;\n\n    virtual boost::property_tree::ptree to_ptree() const = 0;\n\n    virtual void save(const std::string& fname, const std::string& header)\n        const = 0;\n\n    virtual El::Int get_input_size() const = 0;\n\n    virtual ~model_t() {\n\n    }\n};\n\n/**\n * Generic (abstract) model for discrete (all other) output - classification\n */\ntemplate<typename OutType, typename ComputeType>\nstruct model_t<OutType, ComputeType,\n typename std::enable_if<!std::is_floating_point<OutType>::value, OutType>::type>\n{\n\n    virtual void predict(base::direction_t direction_XT,\n        const El::DistMatrix<ComputeType> &XT, El::DistMatrix<OutType> &LP,\n        El::DistMatrix<ComputeType> &DV)\n        const = 0;\n\n    virtual boost::property_tree::ptree to_ptree() const = 0;\n\n    virtual void save(const std::string& fname, const std::string& header)\n        const = 0;\n\n    virtual El::Int get_input_size() const = 0;\n\n    virtual void get_column_coding(std::vector<OutType> &rcoding) const = 0;\n\n    virtual ~model_t() {\n\n    }\n};\n\n/******************************************************************************/\n\n/**\n * Kernel model.\n */\ntemplate<typename KernelType, typename OutType, typename ComputeType = OutType,\n         typename dummy = OutType>\nstruct kernel_model_t;\n\n/**\n * Kernel model for continuous output - regression model\n */\ntemplate<typename KernelType, typename OutType, typename ComputeType>\nstruct kernel_model_t<KernelType, OutType, ComputeType,\n  typename std::enable_if<std::is_floating_point<OutType>::value, OutType>::type > :\npublic model_t<OutType, ComputeType>\n\n{\n    typedef KernelType kernel_type;\n    typedef ComputeType compute_type;\n    typedef OutType out_type;\n\n    kernel_model_t(const kernel_type &k,\n        base::direction_t direction, const El::DistMatrix<compute_type> &X,\n        const std::string &dataloc, El::Int partial,\n        const utility::io::fileformat_t fileformat,\n        sketch::generic_sketch_container_t pretransform,\n        const El::DistMatrix<compute_type> &A) :\n        _X(), _direction(direction),\n        _A(), _dataloc(dataloc), _partial(partial),\n        _fileformat(fileformat), _pretransform(pretransform), _k(k),\n        _input_size(k.get_dim()), _output_size(A.Width()) {\n\n        El::LockedView(_X, X);\n        El::LockedView(_A, A);\n    }\n\n    kernel_model_t(const boost::property_tree::ptree &pt) {\n        build_from_ptree(pt);\n    }\n\n    void predict(base::direction_t direction_XT,\n        const El::DistMatrix<compute_type> &XT, El::DistMatrix<out_type> &YP) const {\n\n        El::DistMatrix<compute_type> KT;\n        Gram(_direction, direction_XT, _k, _X, XT, KT);\n        YP.Resize(_A.Height(), KT.Width());\n        El::Gemm(El::ADJOINT, El::NORMAL, out_type(1.0), _A, KT, YP);\n    }\n\n    boost::property_tree::ptree to_ptree() const {\n        boost::property_tree::ptree pt;\n\n        pt.put(\"skylark_object_type\", \"model:kernel\");\n        pt.put(\"skylark_version\", VERSION);\n\n        pt.put(\"data_location\", _dataloc);\n        pt.put(\"partial\", _partial);\n        pt.put(\"fileformat\", _fileformat);\n        if (!_pretransform.empty())\n            pt.add_child(\"pre_transform\", _pretransform.to_ptree());\n        pt.put(\"num_outputs\", _output_size);\n        pt.put(\"input_size\", _input_size);\n        pt.put(\"regression\", true);\n\n        pt.add_child(\"kernel\", _k.to_ptree());\n\n        std::stringstream sA;\n        El::Print(_A, \"\", sA);\n        pt.put(\"alpha\", sA.str());\n\n        return pt;\n    }\n\n    void save(const std::string& fname, const std::string& header) const {\n        boost::property_tree::ptree pt = to_ptree();\n        std::ofstream of(fname);\n        of << header;\n        boost::property_tree::write_json(of, pt);\n        of.close();\n    }\n\n    virtual ~kernel_model_t() {\n\n    }\n\n    El::Int get_input_size() const {\n        return _input_size;\n    }\n\nprotected:\n    void build_from_ptree(const boost::property_tree::ptree &pt) {\n\n        _input_size = pt.get<El::Int>(\"input_size\");\n        _output_size = pt.get<El::Int>(\"num_outputs\");\n\n        _k = kernel_container_t(pt.get_child(\"kernel\"));\n        _dataloc = pt.get<std::string>(\"data_location\");\n        _fileformat = (utility::io::fileformat_t)pt.get<int>(\"fileformat\");\n        _partial = pt.get<El::Int>(\"partial\");\n\n        // TODO handle \"partial\" and \"sampling\"\n        El::DistMatrix<OutType> dummyY;\n\n        switch (_fileformat) {\n        case utility::io::FORMAT_LIBSVM:\n            utility::io::ReadLIBSVM(_dataloc, _X0, dummyY, base::COLUMNS,\n                _input_size, _partial);\n            break;\n\n#ifdef SKYLARK_HAVE_HDF5\n        case utility::io::FORMAT_HDF5: {\n            H5::H5File in(_dataloc, H5F_ACC_RDONLY);\n            utility::io::ReadHDF5(in, \"X\", _X0, -1, _partial);\n            in.close();\n        }\n            break;\n#endif\n\n        default:\n            // TODO\n            return;\n        }\n\n       if (pt.count(\"pre_transform\") > 0) {\n            _pretransform =\n                sketch::generic_sketch_container_t::from_ptree(pt.\n                    get_child(\"pre_transform\"));\n\n            _X.Resize(_X0.Height(), _pretransform.get_S());\n            _pretransform.apply(&_X0, &_X, sketch::rowwise_tag());\n            _X0.Empty();\n        } else\n            El::View(_X, _X0);\n\n        _direction = base::COLUMNS;\n\n        std::istringstream A_str(pt.get<std::string>(\"alpha\"));\n        if (_A.Grid().Size() == 1) {\n            _A.Resize(_X.Width(), _output_size);\n            compute_type *buffer = _A.Buffer();\n            int ldim = _A.LDim();\n            for(int i = 0; i < _X.Width(); i++) {\n                std::string line;\n                std::getline(A_str, line);\n                std::istringstream Astream(line);\n                for(int j = 0; j < _output_size; j++) {\n                    std::string token;\n                    Astream >> token;\n                    buffer[i + j * ldim] = atof(token.c_str());\n                }\n            }\n        } else {\n            // TODO: can do more memory efficient\n            El::DistMatrix<compute_type, El::CIRC, El::CIRC> A0(_X.Width(),\n                _output_size);\n            if (A0.Grid().Rank() == 0) {\n                compute_type *buffer = A0.Buffer();\n                int ldim = A0.LDim();\n                for(int i = 0; i < _X.Width(); i++) {\n                    std::string line;\n                    std::getline(A_str, line);\n                    std::istringstream Astream(line);\n                    for(int j = 0; j < _output_size; j++) {\n                        std::string token;\n                        Astream >> token;\n                        buffer[i + j * ldim] = atof(token.c_str());\n                    }\n                }\n            }\n\n            _A = A0;\n        }\n    }\n\nprivate:\n    El::DistMatrix<compute_type> _X, _X0;  // X0 is only for load.\n    base::direction_t _direction;\n    El::DistMatrix<compute_type> _A;\n    std::string _dataloc;\n    El::Int _partial;\n    utility::io::fileformat_t _fileformat;\n    sketch::generic_sketch_container_t _pretransform;\n    kernel_type _k;\n    El::Int _input_size, _output_size;\n};\n\n/**\n * Kernel model for discrete (all other) outputs - classification\n */\ntemplate<typename KernelType, typename OutType, typename ComputeType>\nstruct kernel_model_t<KernelType, OutType, ComputeType,\n  typename std::enable_if<!std::is_floating_point<OutType>::value, OutType>::type > :\npublic model_t<OutType, ComputeType> {\n\n    typedef KernelType kernel_type;\n    typedef ComputeType compute_type;\n    typedef OutType out_type;\n\n    kernel_model_t(const kernel_type &k,\n        base::direction_t direction, const El::DistMatrix<compute_type> &X,\n        const std::string &dataloc, El::Int partial,\n        const utility::io::fileformat_t fileformat,\n        const skylark::sketch::generic_sketch_container_t pretransform,\n        const El::DistMatrix<compute_type> &A,\n        const std::vector<OutType> &rcoding) :\n        _X(), _direction(direction),\n        _A(), _rcoding(rcoding), _dataloc(dataloc), _partial(partial),\n        _fileformat(fileformat), _pretransform(pretransform),\n        _k(k), _input_size(k.get_dim()), _output_size(A.Width()) {\n\n        El::LockedView(_X, X);\n        El::LockedView(_A, A);\n    }\n\n    kernel_model_t(const boost::property_tree::ptree &pt) {\n        build_from_ptree(pt);\n    }\n\n    void predict(base::direction_t direction_XT,\n        const El::DistMatrix<compute_type> &XT, El::DistMatrix<out_type> &LP,\n        El::DistMatrix<compute_type> &DV) const {\n\n        El::DistMatrix<compute_type> KT;\n        Gram(_direction, direction_XT, _k, _X, XT, KT);\n        El::Gemm(El::ADJOINT, El::NORMAL, compute_type(1.0), _A, KT, DV);\n        DummyDecode(El::ADJOINT, DV, LP, _rcoding);\n    }\n\n    boost::property_tree::ptree to_ptree() const {\n        boost::property_tree::ptree pt;\n\n        pt.put(\"skylark_object_type\", \"model:kernel\");\n        pt.put(\"skylark_version\", VERSION);\n\n        pt.put(\"data_location\", _dataloc);\n        pt.put(\"partial\", _partial);\n        pt.put(\"fileformat\", _fileformat);\n        if (!_pretransform.empty())\n            pt.add_child(\"pre_transform\", _pretransform.to_ptree());\n        pt.put(\"num_outputs\", _output_size);\n        pt.put(\"input_size\", _input_size);\n        pt.put(\"regression\", false);\n\n        boost::property_tree::ptree rcoding;\n        for(int i = 0; i < _rcoding.size(); i++)\n            rcoding.put(std::to_string(i), _rcoding[i]);\n        pt.add_child(\"rcoding\", rcoding);\n\n        pt.add_child(\"kernel\", _k.to_ptree());\n\n        std::stringstream sA;\n        El::Print(_A, \"\", sA);\n        pt.put(\"alpha\", sA.str());\n\n        return pt;\n    }\n\n    void save(const std::string& fname, const std::string& header) const {\n        boost::property_tree::ptree pt = to_ptree();\n        std::ofstream of(fname);\n        of << header;\n        boost::property_tree::write_json(of, pt);\n        of.close();\n    }\n\n    virtual ~kernel_model_t() {\n\n    }\n\n    El::Int get_input_size() const {\n        return _input_size;\n    }\n\n    void get_column_coding(std::vector<OutType> &rcoding) const {\n        rcoding.resize(_rcoding.size());\n        for(int i = 0; i < _rcoding.size(); i++)\n            rcoding[i] = _rcoding[i];\n    }\n\nprotected:\n\n    void build_from_ptree(const boost::property_tree::ptree &pt) {\n\n        _input_size = pt.get<El::Int>(\"input_size\");\n        _output_size = pt.get<El::Int>(\"num_outputs\");\n        _rcoding.resize(_output_size);\n        const boost::property_tree::ptree &ptrcoding =\n            pt.get_child(\"rcoding\");\n        for(El::Int i = 0; i < _output_size; i++)\n            _rcoding[i] = ptrcoding.get<OutType>(std::to_string(i));\n        _k = kernel_container_t(pt.get_child(\"kernel\"));\n\n        _dataloc = pt.get<std::string>(\"data_location\");\n        _fileformat = (utility::io::fileformat_t)pt.get<int>(\"fileformat\");\n        _partial = pt.get<int>(\"partial\");\n\n        El::DistMatrix<OutType> dummyL;\n\n        switch (_fileformat) {\n        case utility::io::FORMAT_LIBSVM:\n            utility::io::ReadLIBSVM(_dataloc, _X0, dummyL, base::COLUMNS,\n                _input_size, _partial);\n            break;\n\n#ifdef SKYLARK_HAVE_HDF5\n        case utility::io::FORMAT_HDF5: {\n            H5::H5File in(_dataloc, H5F_ACC_RDONLY);\n            utility::io::ReadHDF5(in, \"X\", _X0, -1, _partial);\n            in.close();\n        }\n            break;\n#endif\n\n        default:\n            // TODO\n            return;\n        }\n\n        if (pt.count(\"pre_transform\") > 0) {\n            _pretransform =\n                sketch::generic_sketch_container_t::from_ptree(pt.\n                    get_child(\"pre_transform\"));\n\n            _X.Resize(_X0.Height(), _pretransform.get_S());\n            _pretransform.apply(&_X0, &_X, sketch::rowwise_tag());\n            _X0.Empty();\n        } else\n            El::View(_X, _X0);\n\n        _direction = base::COLUMNS;\n\n        std::istringstream A_str(pt.get<std::string>(\"alpha\"));\n        if (_A.Grid().Size() == 1) {\n            _A.Resize(_X.Width(), _output_size);\n            compute_type *buffer = _A.Buffer();\n            int ldim = _A.LDim();\n            for(int i = 0; i < _X.Width(); i++) {\n                std::string line;\n                std::getline(A_str, line);\n                std::istringstream Astream(line);\n                for(int j = 0; j < _output_size; j++) {\n                    std::string token;\n                    Astream >> token;\n                    buffer[i + j * ldim] = atof(token.c_str());\n                }\n            }\n        } else {\n            // TODO: can do more memory efficient\n            El::DistMatrix<compute_type, El::CIRC, El::CIRC> A0(_X.Width(),\n                _output_size);\n            if (A0.Grid().Rank() == 0) {\n                compute_type *buffer = A0.Buffer();\n                int ldim = A0.LDim();\n                for(int i = 0; i < _X.Width(); i++) {\n                    std::string line;\n                    std::getline(A_str, line);\n                    std::istringstream Astream(line);\n                    for(int j = 0; j < _output_size; j++) {\n                        std::string token;\n                        Astream >> token;\n                        buffer[i + j * ldim] = atof(token.c_str());\n                    }\n                }\n            }\n\n            _A = A0;\n        }\n    }\n\nprivate:\n    El::DistMatrix<compute_type> _X, _X0; // X0 is only for model load.\n    base::direction_t _direction;\n    El::DistMatrix<compute_type> _A;\n    std::vector<OutType> _rcoding;\n    std::string _dataloc;\n    El::Int _partial;\n    utility::io::fileformat_t _fileformat;\n    sketch::generic_sketch_container_t _pretransform;\n    kernel_type _k;\n    El::Int _input_size, _output_size;\n};\n\n/******************************************************************************/\n\n/**\n * Feature expansion model - expands feature expansion and then uses\n * linear combination.\n */\ntemplate<template <typename, typename> class SketchType,\n         typename OutType, typename ComputeType = OutType,\n         typename dummy = OutType>\nstruct feature_expansion_model_t;\n\n/**\n * Feature expansion model for continuous output - regression model\n */\ntemplate<template <typename, typename> class SketchType,\n         typename OutType, typename ComputeType>\nstruct feature_expansion_model_t<SketchType, OutType, ComputeType,\n  typename std::enable_if<std::is_floating_point<OutType>::value, OutType>::type > :\npublic model_t<OutType, ComputeType>\n\n{\n    typedef ComputeType compute_type;\n    typedef OutType out_type;\n\n    typedef SketchType<El::DistMatrix<compute_type>,\n                       El::DistMatrix<compute_type> > sketch_type;\n\n    feature_expansion_model_t(const sketch_type &S,\n        const El::DistMatrix<compute_type> &W) :\n        _W(),  _scale_maps(false), _feature_transforms(1),\n        _input_size(S.get_N()), _output_size(W.Width()),\n        _feature_size(S.get_S()) {\n\n       _feature_transforms[0] = S;\n        El::LockedView(_W, W);\n    }\n\n    feature_expansion_model_t(bool scale_maps,\n        const std::vector<sketch_type> &transforms,\n        const El::DistMatrix<compute_type> &W) :\n        _W(), _scale_maps(scale_maps),\n        _feature_transforms(transforms),\n        _input_size(_feature_transforms[0].get_N()), _output_size(W.Width()),\n        _feature_size(0) {\n\n        for(auto it = _feature_transforms.begin();\n            it != _feature_transforms.end(); it++)\n            _feature_size += it->get_S();\n        El::LockedView(_W, W);\n    }\n\n    feature_expansion_model_t(const boost::property_tree::ptree &pt) {\n        build_from_ptree(pt);\n    }\n\n    void predict(base::direction_t direction_XT,\n        const El::DistMatrix<compute_type> &XT, El::DistMatrix<out_type> &YP) const {\n\n        if (direction_XT == base::COLUMNS) {\n            El::Zeros(YP, _output_size, XT.Width());\n            El::DistMatrix<compute_type> ZT, VW;\n            El::Int starts = 0;\n            for(int i = 0; i < _feature_transforms.size(); i++) {\n                const sketch_type &S = _feature_transforms[i];\n                ZT.Resize(S.get_S(), XT.Width());\n                S.apply(XT, ZT, sketch::columnwise_tag());\n                if (_scale_maps)\n                    El::Scale<compute_type, compute_type>\n                        (sqrt(double(S.get_S()) / _feature_size), ZT);\n                base::RowView(VW, _W, starts, S.get_S());\n                starts += S.get_S();\n                El::Gemm(El::ADJOINT, El::NORMAL, compute_type(1.0), VW, ZT,\n                    compute_type(1.0), YP);\n            }\n\n        } else {\n            El::Zeros(YP, XT.Height(), _output_size);\n            El::DistMatrix<compute_type> ZT, VW;\n            El::Int starts = 0;\n            for(int i = 0; i < _feature_transforms.size(); i++) {\n                const sketch_type &S = _feature_transforms[i];\n                S.apply(XT, ZT, sketch::rowwise_tag());\n                if (_scale_maps)\n                    El::Scale<compute_type, compute_type>\n                        (sqrt(double(S.get_S()) / _feature_size), ZT);\n                base::RowView(VW, _W, starts, S.get_S());\n                starts += S.get_S();\n                El::Gemm(El::NORMAL, El::NORMAL, compute_type(1.0), ZT, VW,\n                    compute_type(1.0), YP);\n            }\n        }\n    }\n\n    boost::property_tree::ptree to_ptree() const {\n        boost::property_tree::ptree pt;\n\n        pt.put(\"skylark_object_type\", \"model:feature_expansion\");\n        pt.put(\"skylark_version\", VERSION);\n\n        pt.put(\"num_outputs\", _output_size);\n        pt.put(\"input_size\", _input_size);\n        pt.put(\"regression\", true);\n\n        boost::property_tree::ptree ptfmap;\n        ptfmap.put(\"number_transforms\", _feature_transforms.size());\n        ptfmap.put(\"scale_maps\", _scale_maps);\n\n        boost::property_tree::ptree ptmaps;\n        for(El::Int i = 0; i < _feature_transforms.size(); i++)\n            ptmaps.push_back(std::make_pair(std::to_string(i),\n                    _feature_transforms[i].to_ptree()));\n        ptfmap.add_child(\"transforms\", ptmaps);\n\n        pt.add_child(\"feature_mapping\", ptfmap);\n\n        std::stringstream sW;\n        El::Print(_W, \"\", sW);\n        pt.put(\"weights\", sW.str());\n\n        return pt;\n    }\n\n    void save(const std::string& fname, const std::string& header) const {\n        boost::property_tree::ptree pt = to_ptree();\n        std::ofstream of(fname);\n        of << header;\n        boost::property_tree::write_json(of, pt);\n        of.close();\n    }\n\n    virtual ~feature_expansion_model_t() {\n\n    }\n\n    El::Int get_input_size() const {\n        return _input_size;\n    }\n\nprotected:\n    void build_from_ptree(const boost::property_tree::ptree &pt) {\n\n        _input_size = pt.get<El::Int>(\"input_size\");\n        _output_size = pt.get<El::Int>(\"num_outputs\");\n\n        int num_transforms = pt.get<int>(\"feature_mapping.number_transforms\");\n        _scale_maps = pt.get<bool>(\"feature_mapping.scale_maps\");\n\n        El::Int s = 0;\n        _feature_transforms.resize(num_transforms);\n        const boost::property_tree::ptree &ptmaps =\n            pt.get_child(\"feature_mapping.transforms\");\n        for(int i = 0; i < num_transforms; i++) {\n            _feature_transforms[i] =\n                sketch_type(sketch_type::from_ptree(ptmaps.get_child(std::to_string(i))));\n            s += _feature_transforms[i].get_S();\n        }\n\n        std::istringstream W_str(pt.get<std::string>(\"weights\"));\n        if (_W.Grid().Size() == 1) {\n            _W.Resize(s, _output_size);\n            compute_type *buffer = _W.Buffer();\n            int ldim = _W.LDim();\n            for(int i = 0; i < s; i++) {\n                std::string line;\n                std::getline(W_str, line);\n                std::istringstream Wstream(line);\n                for(int j = 0; j < _output_size; j++) {\n                    std::string token;\n                    Wstream >> token;\n                    buffer[i + j * ldim] = atof(token.c_str());\n                }\n            }\n        } else {\n            // TODO: can do more memory efficient\n            El::DistMatrix<compute_type, El::CIRC, El::CIRC> W0(s, _output_size);\n            if (W0.Grid().Rank() == 0) {\n                compute_type *buffer = W0.Buffer();\n                int ldim = W0.LDim();\n                for(int i = 0; i < s; i++) {\n                    std::string line;\n                    std::getline(W_str, line);\n                    std::istringstream Wstream(line);\n                    for(int j = 0; j < _output_size; j++) {\n                        std::string token;\n                        Wstream >> token;\n                        buffer[i + j * ldim] = atof(token.c_str());\n                    }\n                }\n            }\n\n            _W = W0;\n        }\n    }\n\nprivate:\n    El::DistMatrix<compute_type> _W;\n    bool _scale_maps;\n    std::vector<sketch_type> _feature_transforms;\n    El::Int _input_size, _output_size;\n    El::Int _feature_size;\n};\n\n/**\n * Approximate kernel model for discrete (all other) outputs - classification\n */\ntemplate<template <typename, typename> class SketchType,\n         typename OutType, typename ComputeType>\nstruct feature_expansion_model_t<SketchType, OutType, ComputeType,\n  typename std::enable_if<!std::is_floating_point<OutType>::value, OutType>::type > :\npublic model_t<OutType, ComputeType> {\n\n    typedef ComputeType compute_type;\n    typedef OutType out_type;\n\n    typedef SketchType<El::DistMatrix<compute_type>,\n                       El::DistMatrix<compute_type> > sketch_type;\n\n    feature_expansion_model_t(const sketch_type &S,\n        const El::DistMatrix<compute_type> &W,\n        const std::vector<OutType> &rcoding) :\n        _W(), _rcoding(rcoding), _scale_maps(false), _feature_transforms(1),\n        _input_size(S.get_N()), _output_size(W.Width()),\n        _feature_size(S.get_S()) {\n\n        _feature_transforms[0] = S;\n        El::LockedView(_W, W);\n    }\n\n    feature_expansion_model_t(bool scale_maps,\n        const std::vector<sketch_type> &transforms,\n        const El::DistMatrix<compute_type> &W,\n        const std::vector<OutType> &rcoding) :\n        _W(), _rcoding(rcoding), _scale_maps(scale_maps),\n        _feature_transforms(transforms),\n        _input_size(_feature_transforms[0].get_N()), _output_size(W.Width()),\n        _feature_size(0) {\n\n        for(auto it = _feature_transforms.begin();\n            it != _feature_transforms.end(); it++)\n            _feature_size += it->get_S();\n        El::LockedView(_W, W);\n    }\n\n    feature_expansion_model_t(const boost::property_tree::ptree &pt) {\n        build_from_ptree(pt);\n    }\n\n    void predict(base::direction_t direction_XT,\n        const El::DistMatrix<compute_type> &XT, El::DistMatrix<out_type> &LP,\n        El::DistMatrix<compute_type> &DV) const {\n\n        if (direction_XT == base::COLUMNS) {\n\n            El::DistMatrix<compute_type> ZT, VW;\n            El::Zeros(DV, _output_size, XT.Width());\n            El::Int starts = 0;\n            for(int i = 0; i < _feature_transforms.size(); i++) {\n                const sketch_type &S = _feature_transforms[i];\n                ZT.Resize(S.get_S(), XT.Width());\n                S.apply(XT, ZT, sketch::columnwise_tag());\n                if (_scale_maps)\n                    El::Scale<compute_type, compute_type>\n                        (sqrt(double(S.get_S()) / _feature_size), ZT);\n                base::RowView(VW, _W, starts, S.get_S());\n                starts += S.get_S();\n                El::Gemm(El::ADJOINT, El::NORMAL, compute_type(1.0), VW, ZT,\n                    compute_type(1.0), DV);\n            }\n            DummyDecode(El::ADJOINT, DV, LP, _rcoding);\n\n        } else {\n\n            El::DistMatrix<compute_type> ZT, VW;\n            El::Zeros(DV, XT.Height(), _output_size);\n            El::Int starts = 0;\n            for(int i = 0; i < _feature_transforms.size(); i++) {\n                const sketch_type &S = _feature_transforms[i];\n                S.apply(XT, ZT, sketch::rowwise_tag());\n                if (_scale_maps)\n                    El::Scale<compute_type, compute_type>\n                        (sqrt(double(S.get_S()) / _feature_size), ZT);\n                base::RowView(VW, _W, starts, S.get_S());\n                starts += S.get_S();\n                El::Gemm(El::NORMAL, El::NORMAL, compute_type(1.0), ZT, VW,\n                    compute_type(1.0), DV);\n            }\n            DummyDecode(El::NORMAL, DV, LP, _rcoding);\n\n        }\n    }\n\n    boost::property_tree::ptree to_ptree() const {\n        boost::property_tree::ptree pt;\n\n        pt.put(\"skylark_object_type\", \"model:feature_expansion\");\n        pt.put(\"skylark_version\", VERSION);\n\n        pt.put(\"input_size\", _input_size);\n        pt.put(\"num_outputs\", _output_size);\n        pt.put(\"regression\", false);\n\n        boost::property_tree::ptree rcoding;\n        for(int i = 0; i < _rcoding.size(); i++)\n            rcoding.put(std::to_string(i), _rcoding[i]);\n        pt.add_child(\"rcoding\", rcoding);\n\n        boost::property_tree::ptree ptfmap;\n        ptfmap.put(\"number_transforms\", _feature_transforms.size());\n        ptfmap.put(\"scale_maps\", _scale_maps);\n\n        boost::property_tree::ptree ptmaps;\n        for(El::Int i = 0; i < _feature_transforms.size(); i++)\n            ptmaps.push_back(std::make_pair(std::to_string(i),\n                    _feature_transforms[i].to_ptree()));\n        ptfmap.add_child(\"transforms\", ptmaps);\n        pt.add_child(\"feature_mapping\", ptfmap);\n\n        std::stringstream sW;\n        El::Print(_W, \"\", sW);\n        pt.put(\"weights\", sW.str());\n\n        return pt;\n    }\n\n    void save(const std::string& fname, const std::string& header) const {\n        boost::property_tree::ptree pt = to_ptree();\n        std::ofstream of(fname);\n        of << header;\n        boost::property_tree::write_json(of, pt);\n        of.close();\n    }\n\n    virtual ~feature_expansion_model_t() {\n\n    }\n\n    El::Int get_input_size() const {\n        return _input_size;\n    }\n\n    void get_column_coding(std::vector<OutType> &rcoding) const {\n        rcoding.resize(_rcoding.size());\n        for(int i = 0; i < _rcoding.size(); i++)\n            rcoding[i] = _rcoding[i];\n    }\n\nprotected:\n    void build_from_ptree(const boost::property_tree::ptree &pt) {\n\n        _input_size = pt.get<El::Int>(\"input_size\");\n        _output_size = pt.get<El::Int>(\"num_outputs\");\n        _rcoding.resize(_output_size);\n        const boost::property_tree::ptree &ptrcoding =\n            pt.get_child(\"rcoding\");\n        for(El::Int i = 0; i < _output_size; i++)\n            _rcoding[i] = ptrcoding.get<OutType>(std::to_string(i));\n\n        int num_transforms = pt.get<int>(\"feature_mapping.number_transforms\");\n        _scale_maps = pt.get<bool>(\"feature_mapping.scale_maps\");\n\n        El::Int s = 0;\n        _feature_transforms.resize(num_transforms);\n        const boost::property_tree::ptree &ptmaps =\n            pt.get_child(\"feature_mapping.transforms\");\n        for(int i = 0; i < num_transforms; i++) {\n            _feature_transforms[i] =\n                sketch_type(sketch_type::from_ptree(ptmaps.get_child(std::to_string(i))));\n            s += _feature_transforms[i].get_S();\n        }\n\n        std::istringstream W_str(pt.get<std::string>(\"weights\"));\n        if (_W.Grid().Size() == 1) {\n            _W.Resize(s, _output_size);\n            compute_type *buffer = _W.Buffer();\n            int ldim = _W.LDim();\n            for(int i = 0; i < s; i++) {\n                std::string line;\n                std::getline(W_str, line);\n                std::istringstream Wstream(line);\n                for(int j = 0; j < _output_size; j++) {\n                    std::string token;\n                    Wstream >> token;\n                    buffer[i + j * ldim] = atof(token.c_str());\n                }\n            }\n        } else {\n            // TODO: can do more memory efficient\n            El::DistMatrix<compute_type, El::CIRC, El::CIRC> W0(s, _output_size);\n            if (W0.Grid().Rank() == 0) {\n                compute_type *buffer = W0.Buffer();\n                int ldim = W0.LDim();\n                for(int i = 0; i < s; i++) {\n                    std::string line;\n                    std::getline(W_str, line);\n                    std::istringstream Wstream(line);\n                    for(int j = 0; j < _output_size; j++) {\n                        std::string token;\n                        Wstream >> token;\n                        buffer[i + j * ldim] = atof(token.c_str());\n                    }\n                }\n            }\n\n            _W = W0;\n        }\n    }\n\nprivate:\n    El::DistMatrix<compute_type> _W;\n    std::vector<OutType> _rcoding;\n    bool _scale_maps;\n    std::vector<sketch_type> _feature_transforms;\n    El::Int _input_size, _output_size;\n    El::Int _feature_size;\n};\n\n/******************************************************************************/\n\n/**\n * Container -\n * Generic (abstract) model.\n */\ntemplate<typename OutType, typename ComputeType = OutType,\n         typename dummy = OutType>\nstruct model_container_t;\n\n/**\n * Container -\n * Generic (abstract) model for continious output - regression\n */\ntemplate<typename OutType, typename ComputeType>\nstruct model_container_t<OutType, ComputeType,\n  typename std::enable_if<std::is_floating_point<OutType>::value, OutType>::type> :\npublic model_t<OutType, ComputeType>\n{\n    typedef model_t<OutType, ComputeType> model_type;\n\n    model_container_t(const std::shared_ptr<model_type> m) :\n        _m(m) {\n    }\n\n    model_container_t(const boost::property_tree::ptree &pt) {\n        std::string type = pt.get<std::string>(\"skylark_object_type\");\n\n        if (type == \"model:kernel\")\n            _m.reset(new kernel_model_t<skylark::ml::kernel_container_t,\n                OutType, ComputeType>(pt));\n\n        if (type == \"model:feature_expansion\")\n            _m.reset(new feature_expansion_model_t<\n                sketch::sketch_transform_container_t,\n                OutType, ComputeType>(pt));\n    }\n\n    virtual void predict(base::direction_t direction_XT,\n        const El::DistMatrix<ComputeType> &XT, El::DistMatrix<OutType> &YP) const {\n        _m->predict(direction_XT, XT, YP);\n    }\n\n    virtual boost::property_tree::ptree to_ptree() const {\n        return _m->to_ptree();\n    }\n\n    virtual void save(const std::string& fname, const std::string& header)\n        const {\n        _m->save(fname, header);\n    }\n\n    virtual El::Int get_input_size() const {\n        return _m->get_input_size();\n    }\n\n    virtual ~model_container_t() {\n\n    }\n\nprivate:\n    std::shared_ptr<model_type> _m;\n};\n\n/**\n * Container -\n * Generic (abstract) model for discrete (all other) output - classification\n */\ntemplate<typename OutType, typename ComputeType>\nstruct model_container_t<OutType, ComputeType,\n  typename std::enable_if<!std::is_floating_point<OutType>::value, OutType>::type> :\npublic model_t<OutType, ComputeType>\n{\n    typedef model_t<OutType, ComputeType> model_type;\n\n    model_container_t(const std::shared_ptr<model_type> m) :\n        _m(m) {\n    }\n\n    model_container_t(const boost::property_tree::ptree &pt) {\n        std::string type = pt.get<std::string>(\"skylark_object_type\");\n\n        if (type == \"model:kernel\")\n            _m.reset(new kernel_model_t<skylark::ml::kernel_container_t,\n                OutType, ComputeType>(pt));\n\n        if (type == \"model:feature_expansion\")\n            _m.reset(new feature_expansion_model_t<\n                sketch::sketch_transform_container_t,\n                OutType, ComputeType>(pt));\n    }\n\n    virtual void predict(base::direction_t direction_XT,\n        const El::DistMatrix<ComputeType> &XT, El::DistMatrix<OutType> &LP,\n        El::DistMatrix<ComputeType> &DV) const {\n        _m->predict(direction_XT, XT, LP, DV);\n    }\n\n    virtual boost::property_tree::ptree to_ptree() const {\n        return _m->to_ptree();\n    }\n\n    virtual void save(const std::string& fname, const std::string& header)\n        const {\n        _m->save(fname, header);\n    }\n\n    virtual El::Int get_input_size() const {\n        return _m->get_input_size();\n    }\n\n    virtual void get_column_coding(std::vector<OutType> &rcoding) const {\n        return _m->get_column_coding(rcoding);\n    }\n\n    virtual ~model_container_t() {\n\n    }\n\nprivate:\n    std::shared_ptr<model_type> _m;\n};\n\n} }\n\n#endif /* SKYLARK_ML_MODEL_HPP */\n", "meta": {"hexsha": "efaa413d9e6cd68ed568f5650062c4de636b68cf", "size": 41036, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ml/model.hpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "ml/model.hpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "ml/model.hpp", "max_forks_repo_name": "xdata-skylark/libskylark", "max_forks_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 32.6719745223, "max_line_length": 110, "alphanum_fraction": 0.5605565845, "num_tokens": 10241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4231125560649689}}
{"text": "/**\n * \\file src/gps.cc\n * Measurements using GPS.\n */\n\n#include <shg/gps.h>\n#include <cmath>\n#include <cstring>\n#include <cstdlib>\n#include <cstdio>\n#include <iostream>\n#ifdef HAVE_PUGIXML\n#include <exception>\n#include <fstream>\n#include <sstream>\n#include <boost/iostreams/filtering_streambuf.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n#endif\n#include <shg/utils.h>\n#include <shg/geometry.h>\n\nnamespace SHG::GPS {\n\nnamespace {\n\nconstexpr double eccentricity_squared =\n     (sqr(semi_major_axis) - sqr(semi_minor_axis)) /\n     sqr(semi_major_axis);\nconstexpr double one_minus_eccentricity_squared =\n     1.0 - eccentricity_squared;\n\n}  // anonymous namespace\n\nvoid convert(const Geogr_coord& g, Cart_coord& p) {\n     const double phi = degrees_to_radians(g.phi);\n     const double lambda = degrees_to_radians(g.lambda);\n     const double sin_phi = std::sin(phi);\n     const double cos_phi = std::cos(phi);\n     const double c =\n          semi_major_axis /\n          std::sqrt(1.0 - eccentricity_squared * sin_phi * sin_phi);\n     const double d = c + g.h;\n     p.x = d * cos_phi * std::cos(lambda);\n     p.y = d * cos_phi * std::sin(lambda);\n     p.z = (one_minus_eccentricity_squared * c + g.h) * sin_phi;\n}\n\ndouble distance(const Cart_coord& p, const Cart_coord& q) {\n     return std::hypot(p.x - q.x, p.y - q.y, p.z - q.z);\n}\n\n#ifdef HAVE_PUGIXML\n\nvoid GPX_data::parse(std::istream& f) {\n     using std::runtime_error;\n\n     state_ = State::error;\n\n     pugi::xml_document doc;\n     pugi::xml_parse_result const result = doc.load(f);\n     if (!result)\n          throw runtime_error(result.description());\n     parse(doc);\n}\n\nvoid GPX_data::parse(char const* fname) {\n     using std::runtime_error;\n\n     state_ = State::error;\n\n     pugi::xml_document doc;\n     pugi::xml_parse_result const result = doc.load_file(fname);\n     if (!result)\n          throw runtime_error(result.description());\n     parse(doc);\n}\n\ndouble GPX_data::distance() const {\n     check_state();\n     return distance_;\n}\n\ndouble GPX_data::distance_on_ellipsoid() const {\n     check_state();\n     return distance_on_ellipsoid_;\n}\n\ndouble GPX_data::uphill() const {\n     check_state();\n     return uphill_;\n}\n\ndouble GPX_data::downhill() const {\n     check_state();\n     return downhill_;\n}\n\nstd::string GPX_data::start_time() const {\n     check_state();\n     return boost::posix_time::to_iso_extended_string(start_time_);\n}\n\nstd::string GPX_data::end_time() const {\n     check_state();\n     return boost::posix_time::to_iso_extended_string(end_time_);\n}\n\nstd::string GPX_data::elapsed_time() const {\n     check_state();\n     boost::posix_time::time_duration td = end_time_ - start_time_;\n     return boost::posix_time::to_simple_string(td);\n}\n\nboost::int64_t GPX_data::elapsed_seconds() const {\n     check_state();\n     boost::posix_time::time_duration td = end_time_ - start_time_;\n     return td.total_seconds();\n}\n\ndouble GPX_data::speedms() const {\n     check_state();\n     return distance_ / (end_time_ - start_time_).total_seconds();\n}\n\ndouble GPX_data::speedkmh() const {\n     return speedms() * 3.6;\n}\n\nvoid GPX_data::parse(pugi::xml_document const& doc) {\n     using std::runtime_error;\n     using boost::posix_time::ptime;\n     using boost::posix_time::from_iso_extended_string;\n\n     distance_ = 0.0;\n     distance_on_ellipsoid_ = 0.0;\n     uphill_ = 0.0;\n     downhill_ = 0.0;\n     bool first = true;\n     Geogr_coord gcp;   // previous\n     Geogr_coord gcc;   // current\n     Geogr_coord gcep;  // previous on ellipsoid\n     Geogr_coord gcec;  // current on ellipsoid\n     Cart_coord ccp;    // previous\n     Cart_coord ccc;    // current\n     Cart_coord ccep;   // previous on ellipsoid\n     Cart_coord ccec;   // current on ellipsoid\n     char* str_end;\n     char tmp[20];\n     boost::posix_time::ptime ctime;\n     unsigned ntrkpts = 0;  // number of track points\n\n     gcp = {0.0, 0.0, 0.0};  // to shut up warnings\n     gcec.h = 0.0;\n     pugi::xml_node ns =\n          doc.child(\"gpx\").child(\"trk\").child(\"trkseg\");\n     for (pugi::xml_node p = ns.first_child(); p;\n          p = p.next_sibling()) {\n          char const* v = p.attribute(\"lat\").value();\n          if (!*v)\n               throw runtime_error(\"missing latitude\");\n          gcec.phi = gcc.phi = std::strtod(v, &str_end);\n          if (*str_end != '\\0' || !std::isfinite(gcc.phi))\n               throw runtime_error(\"invalid latitude\");\n          if (gcc.phi < -90.0 || gcc.phi > 90.0)\n               throw runtime_error(\"latitude out of range\");\n\n          v = p.attribute(\"lon\").value();\n          if (!*v)\n               throw runtime_error(\"missing longitude\");\n          gcec.lambda = gcc.lambda = std::strtod(v, &str_end);\n          if (*str_end != '\\0' || !std::isfinite(gcc.lambda))\n               throw runtime_error(\"invalid longitude\");\n          if (gcc.lambda < -180.0 || gcc.lambda >= 180.0)\n               throw runtime_error(\"longitude out of range\");\n\n          v = p.child_value(\"ele\");\n          if (!*v)\n               throw runtime_error(\"missing elevation\");\n          gcc.h = std::strtod(v, &str_end);\n          if (*str_end != '\\0' || !std::isfinite(gcc.h))\n               throw runtime_error(\"invalid elevation\");\n\n          // \"2021-06-11T16:01:53Z\" --> \"2021-06-11T16:01:53\"\n          strncpy(tmp, p.child_value(\"time\"), 19);\n          tmp[19] = '\\0';\n          if (!*tmp)\n               throw runtime_error(\"missing timestamp\");\n          try {\n               ctime = ptime(from_iso_extended_string(tmp));\n          } catch (std::exception const&) {\n               throw runtime_error(\"invalid timestamp\");\n          }\n\n          convert(gcc, ccc);\n          convert(gcec, ccec);\n\n          if (first) {\n               start_time_ = end_time_ = ctime;\n               first = false;\n          } else {\n               distance_ += SHG::GPS::distance(ccp, ccc);\n               distance_on_ellipsoid_ +=\n                    SHG::GPS::distance(ccep, ccec);\n               if (gcc.h > gcp.h)\n                    uphill_ += gcc.h - gcp.h;\n               else if (gcc.h < gcp.h)\n                    downhill_ += gcp.h - gcc.h;\n               if (ctime < end_time_)\n                    throw runtime_error(\"timestamp mismatch\");\n               end_time_ = ctime;\n          }\n          gcp = gcc;\n          ccp = ccc;\n          gcep = gcec;\n          ccep = ccec;\n          ntrkpts++;\n     }\n     ns = ns.next_sibling();\n     if (ns)\n          throw runtime_error(\"more then one track segment found\");\n     if (ntrkpts <= 1)\n          throw runtime_error(\"not enough track points\");\n     if ((end_time_ - start_time_).total_seconds() < 1)\n          throw runtime_error(\"elapsed time is zero seconds\");\n     state_ = State::ok;\n}\n\nvoid GPX_data::check_state() const {\n     if (state_ != State::ok)\n          throw std::logic_error(\n               \"successfully call the method parse() first\");\n}\n\nvoid Activity_statistics::run(std::filesystem::path const& dir) {\n     namespace fs = std::filesystem;\n     namespace io = boost::iostreams;\n     using std::ios_base;\n     GPX_data d;\n\n     for (auto const& p : fs::directory_iterator(dir)) {\n          if (!fs::is_regular_file(p.path()))\n               continue;\n          io::filtering_streambuf<io::input> inbuf;\n\n          if (p.path().extension() == \".gz\" &&\n              p.path().stem().extension() == \".gpx\") {\n               inbuf.push(io::gzip_decompressor());\n          } else if (p.path().extension() != \".gpx\") {\n               continue;\n          }\n          Result r;\n          r.fname = p.path().filename().generic_string();\n          r.status = \"failed\";\n\n          try {\n               std::ifstream f(p.path(),\n                               ios_base::in | ios_base::binary);\n               inbuf.push(f);\n               std::istream instream(&inbuf);\n               // When not using buf and calling\n               // d.parse(instream), on Windows an exception \"no\n               // random access: iostream stream error\" is\n               // thrown.\n               std::stringstream buf(ios_base::in | ios_base::out |\n                                     ios_base::binary);\n               buf << instream.rdbuf();\n               d.parse(buf);\n               if (d.state() == GPX_data::State::ok) {\n                    r.status = \"ok\";\n                    r.distance = d.distance();\n                    r.distance_on_ellipsoid =\n                         d.distance_on_ellipsoid();\n                    r.uphill = d.uphill();\n                    r.downhill = d.downhill();\n                    r.start_time = d.start_time();\n                    r.end_time = d.end_time();\n                    r.elapsed_time = d.elapsed_time();\n                    r.elapsed_seconds = d.elapsed_seconds();\n                    r.speedms = d.speedms();\n                    r.speedkmh = d.speedkmh();\n               }\n          } catch (std::exception const& e) {\n               r.status += \": \";\n               r.status += e.what();\n          }\n          results_.push_back(r);\n     }\n}\n\n#endif\n\n}  // namespace SHG::GPS\n", "meta": {"hexsha": "410c629bba408b5a0c478c418dbf0b4fffcb8576", "size": 9042, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/gps.cc", "max_stars_repo_name": "shgalus/shg", "max_stars_repo_head_hexsha": "0318d0126cf12c3236183447d130969c468a02fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-05-21T04:14:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-31T17:15:15.000Z", "max_issues_repo_path": "src/gps.cc", "max_issues_repo_name": "shgalus/shg", "max_issues_repo_head_hexsha": "0318d0126cf12c3236183447d130969c468a02fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-05-21T05:31:04.000Z", "max_issues_repo_issues_event_max_datetime": "2015-05-21T05:31:04.000Z", "max_forks_repo_path": "src/gps.cc", "max_forks_repo_name": "shgalus/shg", "max_forks_repo_head_hexsha": "0318d0126cf12c3236183447d130969c468a02fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-05-21T04:14:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-18T12:35:22.000Z", "avg_line_length": 30.8600682594, "max_line_length": 68, "alphanum_fraction": 0.5576199956, "num_tokens": 2217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4230115313018374}}
{"text": "#pragma once\n\n#include <array>\n#include <random>\n\n#include <Eigen/Geometry>\n#include <unsupported/Eigen/EulerAngles>\n\n\nnamespace affx {\n\nclass Affine {\n  using Vector6d = Eigen::Matrix<double, 6, 1>;\n  using Vector7d = Eigen::Matrix<double, 7, 1>;\n\n  using Euler = Eigen::EulerAngles<double, Eigen::EulerSystemZYX>;\n  typedef Eigen::Affine3d Type;\n\npublic:\n  Type data;\n\n  explicit Affine() {\n    this->data = Type::Identity();\n  }\n\n  explicit Affine(const Type& data) {\n    this->data = data;\n  }\n\n  explicit Affine(double x, double y, double z, double a = 0.0, double b = 0.0, double c = 0.0) {\n    data.translation() = Eigen::Vector3d(x, y, z);\n    data.linear() = Euler(a, b, c).toRotationMatrix();\n  }\n\n  explicit Affine(double x, double y, double z, double q_w, double q_x, double q_y, double q_z) {\n    data.translation() = Eigen::Vector3d(x, y, z);\n    data.linear() = Eigen::Quaterniond(q_w, q_x, q_y, q_z).toRotationMatrix();\n  }\n\n  explicit Affine(const std::array<double, 6>& v): Affine(v[0], v[1], v[2], v[3], v[4], v[5]) { }\n\n  explicit Affine(const std::array<double, 7>& v): Affine(v[0], v[1], v[2], v[3], v[4], v[5]) { }\n\n  explicit Affine(const Vector6d& v): Affine(v[0], v[1], v[2], v[3], v[4], v[5]) { }\n\n  explicit Affine(const Vector7d& v): Affine(v[0], v[1], v[2], v[3], v[4], v[5]) { }\n\n  explicit Affine(const std::array<double, 16>& array) {\n    Type affine(Eigen::Matrix4d::Map(array.data()));\n    data = affine;\n  }\n\n  Affine operator *(const Affine &a) const {\n    Type result;\n    result = data * a.data;\n    return Affine(result);\n  }\n\n  Affine inverse() const {\n    return Affine(data.inverse());\n  }\n\n  bool isApprox(const Affine &a) const {\n    return data.isApprox(a.data);\n  }\n\n  Eigen::Ref<Affine::Type::MatrixType> matrix() {\n    return data.matrix();\n  }\n\n  std::array<double, 16> array() const {\n    std::array<double, 16> array;\n    std::copy(data.data(), data.data() + array.size(), array.begin());\n    return array;\n  }\n\n  Vector6d vector() const {\n    Vector6d result;\n    result << data.translation(), angles();\n    return result;\n  }\n\n  Vector7d vector_with_elbow(double elbow) const {\n    Vector7d result;\n    result << data.translation(), angles(), elbow;\n    return result;\n  }\n\n  Eigen::Vector3d translation() const {\n    Eigen::Vector3d v;\n    v << data.translation();\n    return v;\n  }\n\n  Eigen::Vector3d angles() const {\n    Eigen::Vector3d angles = Euler::FromRotation<false, false, false>(data.rotation()).angles();\n    Eigen::Vector3d angles_equal;\n    angles_equal << angles[0] - M_PI, M_PI - angles[1], angles[2] - M_PI;\n\n    if (angles_equal[1] > M_PI) {\n      angles_equal[1] -= 2 * M_PI;\n    }\n    if (angles_equal[2] < -M_PI) {\n      angles_equal[2] += 2 * M_PI;\n    }\n\n    if (angles.norm() < angles_equal.norm()) {\n      return angles;\n    }\n    return angles_equal;\n  }\n\n  Type::LinearMatrixType rotation() const {\n    Type::LinearMatrixType result;\n    result << data.rotation();\n    return result;\n  }\n\n  Eigen::Quaterniond quaternion() const {\n    Eigen::Quaterniond q(data.rotation());\n    return q;\n  }\n\n  std::array<double, 4> py_quaternion() const {\n    auto q = quaternion();\n    return {q.w(), q.x(), q.y(), q.z()};\n  }\n\n  double x() const {\n    return data.translation().x();\n  }\n\n  double y() const {\n    return data.translation().y();\n  }\n\n  double z() const {\n    return data.translation().z();\n  }\n\n  double a() const {\n    return angles()(0);\n  }\n\n  double b() const {\n    return angles()(1);\n  }\n\n  double c() const {\n    return angles()(2);\n  }\n\n  double qW() const {\n    return quaternion().w();\n  }\n\n  double qX() const {\n    return quaternion().x();\n  }\n\n  double qY() const {\n    return quaternion().y();\n  }\n\n  double qZ() const {\n    return quaternion().z();\n  }\n\n  void translate(const Eigen::Vector3d &v) {\n    data.translate(v);\n  }\n\n  void pretranslate(const Eigen::Vector3d &v) {\n    data.pretranslate(v);\n  }\n\n  void rotate(const Type::LinearMatrixType &r) {\n    data.rotate(r);\n  }\n\n  void prerotate(const Type::LinearMatrixType &r) {\n    data.prerotate(r);\n  }\n\n  void setQuaternion(double w, double x, double y, double z) {\n    data.linear() = Eigen::Quaterniond(w, x, y, z).toRotationMatrix();\n  }\n\n  void setX(double x) {\n    data.translation().x() = x;\n  }\n\n  void setY(double y) {\n    data.translation().y() = y;\n  }\n\n  void setZ(double z) {\n    data.translation().z() = z;\n  }\n\n  void setA(double a) {\n    Eigen::Vector3d euler = angles();\n    data.linear() = Euler(a, euler(1), euler(2)).toRotationMatrix();\n  }\n\n  void setB(double b) {\n    Eigen::Vector3d euler = angles();\n    data.linear() = Euler(euler(0), b, euler(2)).toRotationMatrix();\n  }\n\n  void setC(double c) {\n    Eigen::Vector3d euler = angles();\n    data.linear() = Euler(euler(0), euler(1), c).toRotationMatrix();\n  }\n\n  Affine slerp(const Affine& affine, double t) const {\n    Type result;\n    Eigen::Quaterniond q_start(data.rotation());\n    Eigen::Quaterniond q_end(affine.rotation());\n    result.translation() = data.translation() + t * (affine.translation() - data.translation());\n    result.linear() = q_start.slerp(t, q_end).toRotationMatrix();\n    return Affine(result);\n  }\n\n  Affine getInnerRandom() const {\n    std::random_device r;\n    std::default_random_engine engine(r());\n\n    Eigen::Matrix<double, 6, 1> max, random;\n    max << data.translation(), angles();\n\n    for (int i = 0; i < 6; i++) {\n      std::uniform_real_distribution<double> distribution(-max(i), max(i));\n      random(i) = distribution(engine);\n    }\n\n    return Affine(random(0), random(1), random(2), random(3), random(4), random(5));\n  }\n\n  std::string toString() const {\n    Eigen::Matrix<double, 6, 1> v;\n    v << data.translation(), angles();\n\n    return \"[\" + std::to_string(v(0)) + \", \" + std::to_string(v(1)) + \", \" + std::to_string(v(2))\n      + \", \" + std::to_string(v(3)) + \", \" + std::to_string(v(4)) + \", \" + std::to_string(v(5)) + \"]\";\n  }\n};\n\n} // namespace affx\n", "meta": {"hexsha": "77d16deb3e9ddc2bfb102d524d751bbfca364fa9", "size": 5929, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/affx/affine.hpp", "max_stars_repo_name": "smart-cuhk/affx", "max_stars_repo_head_hexsha": "83b2df308e102b10616327f421e2582e003fcc4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/affx/affine.hpp", "max_issues_repo_name": "smart-cuhk/affx", "max_issues_repo_head_hexsha": "83b2df308e102b10616327f421e2582e003fcc4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-09T11:04:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-23T08:14:17.000Z", "max_forks_repo_path": "include/affx/affine.hpp", "max_forks_repo_name": "smart-cuhk/affx", "max_forks_repo_head_hexsha": "83b2df308e102b10616327f421e2582e003fcc4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-07T02:05:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T02:05:25.000Z", "avg_line_length": 23.716, "max_line_length": 102, "alphanum_fraction": 0.6051610727, "num_tokens": 1737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.42295882288179043}}
{"text": "// -----------------------------------------------------------------------\n//\n// Copyright (C) 2020  - David Fernández Castellanos\n//\n// This file is part of the MEPLS software. You can use it, redistribute\n// it, and/or modify it under the terms of the Creative Commons Attribution\n// 4.0 International Public License. The full text of the license can be\n// found in the file LICENSE at the top level of the MEPLS distribution.\n//\n// -----------------------------------------------------------------------\n\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/path_search.h>\n\n#include \"espci.h\"\n\n#if defined(OPENMP)\n#include <omp.h>\n\n#endif\n\n#include <cmdparser.hpp>\n#include <random>\n\n\nnamespace espci\n{\n\nusing namespace mepls;\n\n\nvoid run(const parameters::Parameters &p, dealii::ConditionalOStream & cout)\n{\n\t// TODO here, dim=2 at least for how we set the average pressure\n\n\t/////////////////////////////\n\t//////  setup system ///////\n\t///////////////////////////\n\n\tconstexpr unsigned int dim = 2;\n\n\tutils::ContinueSimulation continue_simulation;\n\n\tauto timer = utils::TimerSingleton::getInstance();\n\ttimer->enter_subsection(\"Setting up\");\n\n\tstd::mt19937 generator(p.sim.seed);\n\n\tstd::vector<espci::element::Anisotropic<dim> *> elements_espci = create_elements<dim>(p,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  generator);\n\n\tmepls::element::Vector<dim> elements;\n\tfor(auto &element : elements_espci)\n\t\telements.push_back(element);\n\n\tsnapshot::Check<dim> snapshot_check(p.out.snapshots_min, p.out.snapshots_max,\n\t\t\t\t\t\t\t\t\t\tp.out.snapshots_interval, p.out.snapshots_sensitivity);\n\tstd::vector<snapshot::Threshold<dim> > threshold_snapshots;\n\tstd::vector<snapshot::Stress<dim> > stress_snapshots;\n\tstd::vector<snapshot::DefGrad<dim> > def_grad_snapshots;\n\tstd::vector<patches::PatchPropertiesSnapshot<dim> > patch_prop_snapshots;\n\tstd::vector<GlobalPropertiesSnapshot<dim>> global_properties_snapshots;\n\tauto patch_to_element_map = patches::make_patch_to_element_map(elements, p.sim.N_patch_list,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   p.sim.Nx, p.sim.Ny);\n\tbool parent_liquid = p.sim.parent_liquid;\n\tbool thermal_relaxation = p.sim.thermal_relaxation;\n\tbool reload = p.sim.reload;\n\tbool het_elasticity = p.sim.het_elasticity;\n\tbool precalculate = not het_elasticity; // precalculate stress factors when doing patch tests;\n\t// only valid for homogeneous elasticity\n\tbool do_ee = p.sim.do_ee; // relax from oi state to ee when doing patch tests\n\n\tstd::vector<double> theta_list;\n\tif(p.sim.n_theta == 4)\n\t{\n\t\ttheta_list.push_back(0 * M_PI / 180.);\n\t\ttheta_list.push_back(90 * M_PI / 180.);\n\t\ttheta_list.push_back(50 * M_PI / 180.);\n\t\ttheta_list.push_back(140 * M_PI / 180.);\n\t}\n\telse if(p.sim.n_theta == 2)\n\t{\n\t\ttheta_list.push_back(0 * M_PI / 180.);\n\t\ttheta_list.push_back(90 * M_PI / 180.);\n\t}\n\telse\n\t{\n\t\tfor(double z = 0.; z < M_PI; z += M_PI / double(p.sim.n_theta))\n\t\t\ttheta_list.push_back(z);\n\t}\n\n\telasticity_solver::LeesEdwards<dim> solver(p.sim.Nx, p.sim.Ny);\n\tM_Assert(elements.size() == solver.get_n_elements(), \"Numbers of mesoscale and finite \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t  \"elements do not match\");\n\n\t// initial (default) assembly using the quench elastic properties.\n\tfor(auto &element : elements)\n\t\tsolver.set_elastic_properties(element->number(), element->C());\n\tsolver.setup_and_assembly();\n\n\tif(het_elasticity)\n\t\tmepls::element::calculate_local_stress_coefficients(elements, solver);\n\telse\n\t\tmepls::element::calculate_local_stress_coefficients_central(elements, solver);\n\n\tmepls::element::calculate_ext_stress_coefficients(elements, solver);\n\n\tsystem::Standard<dim> system(elements, solver, generator);\n\tsystem::MacroState<dim> &macrostate = system.macrostate;\n\n\tif(p.mat.init_eigenstrain)\n\t\tapply_initial_eigenstrain<dim>(system, p);\n\n\ttimer->leave_subsection(\"Setting up\");\n\n\t///////////////////////////////////////////\n\t///////  simulate parent liquid //////////\n\t/////////////////////////////////////////\n\n\ttimer->enter_subsection(\"Simulate parent liquid\");\n\n\thistory::History<dim> liquid_history(\"parent_liquid\");\n\tsystem.set_history(liquid_history);\n\tif(parent_liquid)\n\t{\n\n\t\tfor(auto &element : elements_espci)\n\t\t{\n\t\t\tauto conf = element->config();\n\t\t\tconf.temperature = p.mat.temperature_liquid;\n\t\t\telement->config(conf);\n\t\t}\n\n\t\tsimulate_parent_liquid_KMC(system, liquid_history, p, continue_simulation);\n//\t\tsimulate_parent_liquid_MH(system, liquid_history, p, continue_simulation);\n\t}\n\n\t// apply instantaneous quench\n\tfor(auto &element : elements_espci)\n\t{\n\t\tauto conf = element->config();\n\t\tconf.temperature = 0;\n\t\telement->config(conf);\n\t}\n\n\tdynamics::relaxation(system, continue_simulation, 1e10);\n\tif(not continue_simulation())\n\t{\n\t\tcout << continue_simulation << std::endl;\n\t\tabort();\n\t}\n\n\tliquid_history.add_macro(system);\n\tsystem.macrostate.clear();\n\n\n\ttimer->leave_subsection(\"Simulate parent liquid\");\n\n\t////////////////////////////\n\t//////      AQS     ///////\n\t//////////////////////////\n\n\thistory::History<dim> aqs_history(\"AQS\");\n\tsystem.set_history(aqs_history);\n\n\n\t/* ----- snapshots ----- */\n\ttimer->enter_subsection(\"Taking snapshots\");\n\n\tif(p.out.snapshots.find(\"slip_thresholds\") != std::string::npos)\n\t\tthreshold_snapshots.push_back(\n\t\t\tsnapshot::Threshold(system, p.sim.monitor_name, 0.,\n\t\t\t\t\t\t\t\tmacrostate[p.sim.monitor_name]));\n\tif(p.out.snapshots.find(\"stress\") != std::string::npos)\n\t\tstress_snapshots.push_back(\n\t\t\tsnapshot::Stress(system, p.sim.monitor_name, 0.,\n\t\t\t\t\t\t\t macrostate[p.sim.monitor_name]));\n\tif(p.out.snapshots.find(\"def_grad\") != std::string::npos)\n\t\tdef_grad_snapshots.push_back(\n\t\t\tsnapshot::DefGrad(system, p.sim.monitor_name, 0.,\n\t\t\t\t\t\t\t  macrostate[p.sim.monitor_name]));\n\n\tif(p.out.snapshots.find(\"patches\") != std::string::npos)\n\t\tfor(auto n_patch : p.sim.N_patch_list)\n\t\t{\n\t\t\tcout << \">>> \" << n_patch << std::endl;\n\t\t\tpatch_prop_snapshots.push_back(\n\t\t\t\tpatches::PatchPropertiesSnapshot<dim>(system,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  p.sim.monitor_name, 0.,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  macrostate[p.sim.monitor_name],\n\t\t\t\t\t\t\t\t\t\t\t\t\t  n_patch, theta_list, precalculate,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  do_ee));\n\t\t}\n\n\tif(p.out.snapshots.find(\"global_properties\") != std::string::npos)\n\t\tglobal_properties_snapshots.push_back(\n\t\t\tGlobalPropertiesSnapshot<dim>(system, solver, aqs_history.index(), p.sim.monitor_name,\n\t\t\t\t\t\t\t\t\t\t  0., macrostate[p.sim.monitor_name]));\n\ttimer->leave_subsection(\"Taking snapshots\");\n\n\t/* ----- save struct. properties ----- */\n\tstd::vector<event::RenewSlip<dim>> renewal_vector;\n\tfor(auto &element : elements)\n\t\telement->record_structural_properties(renewal_vector);\n\taqs_history.add(renewal_vector);\n\n\n\t/* ---- simulation loop ----- */\n\ttimer->enter_subsection(\"Running AQS\");\n\n\tcontinue_simulation(system.macrostate[p.sim.monitor_name] < p.sim.monitor_limit,\n\t\t\t\t\t\tp.sim.monitor_name + \" limit reached\");\n\n\n\t// adding an (empty) driving event will record the average prestress\n\t// (which can be slightly non-zero due to numerical accuray) as the\n\t// first event in the history\n\tevent::Driving<dim> prestress_event;\n\tprestress_event.activation_protocol = mepls::dynamics::Protocol::prestress;\n\tsystem.add(prestress_event);\n\n\taqs_history.add_macro(system);\n\n\tassert( macrostate[\"av_vm_plastic_strain\"]==0. );\n\n\tdouble G_old = 0.;\n\tdouble G_stat = p.mat.G;\n\twhile(continue_simulation())\n\t{\n\t\t// reassemble the elastic properties if the change in the shear\n\t\t// modulus is big enough and if it's different enough from the stationary\n\t\t// value\n\t\tdealii::SymmetricTensor<4,dim> av_C;\n\t\tfor(auto &element : elements)\n\t\t\tav_C += element->C();\n\t\tav_C /= double(elements.size());\n\n\t\tdouble G_new = av_C[0][1][0][1];\n\n\t\tif(std::abs(G_new/G_old-1)>0.001 and std::abs(G_old/G_stat-1)>0.005)\n\t\t{\n\t\t\ttimer->leave_subsection(\"Running AQS\");\n\t\t\ttimer->enter_subsection(\"Reassembling with new stiffness\");\n\n\t\t\tG_old = G_new;\n\n\t\t\tsolver.reassemble_with_new_stiffness(av_C);\n\n\t\t\t// we call add which will inform the macrostate and the elements\n\t\t\t// about the change in external stress due to the change in global\n\t\t\t// stiffness and will also record that change in the history\n\t\t\tconst std::vector<event::Plastic<dim>> added_yielding;\n\t\t\tevent::Driving<dim> driving_event_variation_stiffness;\n\t\t\tdriving_event_variation_stiffness.activation_protocol = mepls::dynamics::Protocol::variation_stiffness;\n\t\t\tsystem.add(driving_event_variation_stiffness);\n\n\t\t\tauto state = solver.get_state();\n\t\t\tmepls::element::calculate_local_stress_coefficients_central(elements, solver);\n\t\t\tmepls::element::calculate_ext_stress_coefficients(elements, solver);\n\t\t\tsolver.set_state(state);\n\n\t\t\t// relax to ensure there are no unstable elements after the change\n\t\t\t// in the elastic properties (if the shear modulus rises with strain,\n\t\t\t// that will lead to stress rises that can unstabilise elements)\n\t\t\tdynamics::relaxation(system, continue_simulation);\n\n\t\t\ttimer->leave_subsection(\"Reassembling with new stiffness\");\n\t\t\ttimer->enter_subsection(\"Running AQS\");\n\t\t}\n\n\t\tcout << aqs_history.index() << \" | \" << std::fixed << macrostate[\"total_strain\"]\n\t\t\t\t  << \" \" << macrostate[\"ext_stress\"] << std::endl;\n\n\t\tif(snapshot_check(macrostate[p.sim.monitor_name]))\n\t\t{\n\t\t\ttimer->leave_subsection(\"Running AQS\");\n\t\t\ttimer->enter_subsection(\"Taking snapshots\");\n\n\t\t\tif(p.out.snapshots.find(\"slip_thresholds\") != std::string::npos)\n\t\t\t\tthreshold_snapshots.push_back(\n\t\t\t\t\tsnapshot::Threshold(system, p.sim.monitor_name,\n\t\t\t\t\t\t\t\t\t\tsnapshot_check.desired_value,\n\t\t\t\t\t\t\t\t\t\tmacrostate[p.sim.monitor_name]));\n\t\t\tif(p.out.snapshots.find(\"stress\") != std::string::npos)\n\t\t\t\tstress_snapshots.push_back(\n\t\t\t\t\tsnapshot::Stress(system, p.sim.monitor_name,\n\t\t\t\t\t\t\t\t\t snapshot_check.desired_value, macrostate[p.sim.monitor_name]));\n\t\t\tif(p.out.snapshots.find(\"def_grad\") != std::string::npos)\n\t\t\t\tdef_grad_snapshots.push_back(\n\t\t\t\t\tsnapshot::DefGrad(system, p.sim.monitor_name,\n\t\t\t\t\t\t\t\t\t  snapshot_check.desired_value,\n\t\t\t\t\t\t\t\t\t  macrostate[p.sim.monitor_name]));\n\t\t\tif(p.out.snapshots.find(\"patches\") != std::string::npos)\n\t\t\t\tfor(auto n_patch : p.sim.N_patch_list)\n\t\t\t\t{\n\t\t\t\t\tcout << \">>> \" << n_patch << std::endl;\n\t\t\t\t\tpatch_prop_snapshots.push_back(\n\t\t\t\t\t\tpatches::PatchPropertiesSnapshot<dim>(system,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  p.sim.monitor_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  snapshot_check.desired_value,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  macrostate[p.sim.monitor_name],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  n_patch,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  theta_list, precalculate, do_ee));\n\t\t\t\t}\n\n\t\t\ttimer->leave_subsection(\"Taking snapshots\");\n\t\t\ttimer->enter_subsection(\"Running AQS\");\n\t\t}\n\n\n\t\t/* ---- dyanmics ----- */\n\t\tdynamics::finite_extremal_dynamics_step(1e-4 * 0.5, system);\n\t\taqs_history.add_macro(system);\n\n\t\tdynamics::relaxation(system, continue_simulation);\n\t\taqs_history.add_macro(system);\n\n\n\t\tcontinue_simulation(system.macrostate[p.sim.monitor_name] < p.sim.monitor_limit,\n\t\t\t\t\t\t\tp.sim.monitor_name + \" limit reached\");\n\t}\n\n\tauto solver_state_end_AQS = solver.get_state();\n\tauto macrostate_end_AQS = system.macrostate;\n\n\tcout << continue_simulation << std::endl;\n\n\ttimer->leave_subsection(\"Running AQS\");\n\n\n\t//////////////////////////////////\n\t//////  thermal relaxation //////\n\t////////////////////////////////\n\n\ttimer->enter_subsection(\"Thermal relaxation\");\n\n\thistory::History<dim> thermal_relaxation_hist(\"thermal_relaxation\");\n\n\tif(thermal_relaxation)\n\t{\n\t\tmepls::element::Vector<dim> elements_replica;\n\t\tfor(auto &element : elements_espci)\n\t\t{\n\t\t\tauto element_copy = element->make_copy();\n\n\t\t\tauto conf = element_copy->config();\n\t\t\tconf.temperature = p.mat.temperature_relaxation;\n\t\t\telement_copy->config(conf);\n\n\t\t\telements_replica.push_back( element_copy );\n\t\t}\n\n\t\t// the solver state is copied, so it contains the eigenstrain and the load\n\t\t// in this case the elements elastic field need not be converted into a\n\t\t// prestress before\n\t\tsolver.set_state(solver_state_end_AQS);\n\n\t\tauto system_replica = system.get_new_instance(elements_replica, solver,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  system.generator);\n\t\tsystem_replica->macrostate = macrostate_end_AQS;\n\t\tsystem_replica->set_history(thermal_relaxation_hist);\n\n\t\t// initiate dynamics using copied system\n\t\tmepls::dynamics::KMC<dim> kmc;\n\t\tmepls::utils::ContinueSimulation continue_relaxing;\n\t\tauto &macrostate = system_replica->macrostate;\n\t\tthermal_relaxation_hist.add_macro( *system_replica );\n\n\t\twhile(continue_relaxing())\n\t\t{\n\n\t\t\tcout << thermal_relaxation_hist.index() << \" | \" << std::fixed\n\t\t\t\t\t  << macrostate[\"total_strain\"]\n\t\t\t\t\t  << \" \" << macrostate[\"ext_stress\"]\n\t\t\t\t\t  << \" \" << macrostate[\"pressure\"]\n\t\t\t\t\t  << \" \" << macrostate[\"time\"]\n\t\t\t\t\t  << std::endl;\n\n\t\t\tkmc(*system_replica);\n\t\t\tthermal_relaxation_hist.add_macro( *system_replica );\n\n\t\t\tmepls::dynamics::relaxation(*system_replica, continue_relaxing);\n\t\t\tthermal_relaxation_hist.add_macro( *system_replica );\n\n\t\t\tcontinue_relaxing(macrostate[\"ext_stress\"] > 0, \"System relaxed\");\n\t\t}\n\n\t\tdelete system_replica;\n\n\t\tcout << continue_relaxing << std::endl;\n\t\tcout << \"Relaxing finished\" << std::endl;\n\t}\n\n\ttimer->leave_subsection(\"Thermal relaxation\");\n\n\t///////////////////////////////\n\t//////  reloading step ///////\n\t/////////////////////////////\n\n\thistory::History<dim> aqs_unloading(\"AQS_unloading\");\n\thistory::History<dim> aqs_reload_forward(\"AQS_reload_forward\");\n\thistory::History<dim> aqs_reload_backward(\"AQS_reload_backward\");\n\n\tif(reload)\n\t{\n\t\ttimer->enter_subsection(\"Reloading\");\n\n\t\t// the solver state is copied, so it contains the eigenstrain and the load\n\t\t// in this case the elements elastic field need not be converted into a\n\t\t// prestress before\n\t\tsolver.set_state(solver_state_end_AQS);\n\n\t\tsystem.macrostate = macrostate_end_AQS;\n\n\t\tsystem.set_history(aqs_unloading);\n\n\t\tutils::ContinueSimulation continue_unloading;\n\t\tauto &macrosate = system.macrostate;\n\t\taqs_unloading.add_macro(system);\n\n\t\twhile(continue_unloading())\n\t\t{\n\t\t\tcout << aqs_unloading.index() << \" | \" << std::fixed\n\t\t\t\t\t  << macrostate[\"total_strain\"] << \" \" << macrostate[\"ext_stress\"] << \" \"\n\t\t\t\t\t  << macrostate[\"pressure\"] << std::endl;\n\n\t\t\tdynamics::finite_extremal_dynamics_step(1e-4 * 0.5, system, false);\n\t\t\taqs_unloading.add_macro(system);\n\n\t\t\tdynamics::relaxation(system, continue_unloading);\n\t\t\taqs_unloading.add_macro(system);\n\n\t\t\tcontinue_unloading(macrostate[\"ext_stress\"] > 0, \"System unloaded\");\n\t\t}\n\n\t\tcout << continue_unloading << std::endl;\n\n\t\tperform_reloading(system, aqs_reload_forward, true, p);\n\t\tperform_reloading(system, aqs_reload_backward, false, p);\n\n\t\ttimer->leave_subsection(\"Reloading\");\n\t}\n\n\n\t/////////////////////////////////////\n\t//////  post-simultaion step ///////\n\t///////////////////////////////////\n\n\tstd::string filename = p.out.filename + \"_\" + write::make_filename(p) + \".h5\";\n\tH5::H5File file(p.out.path + \"/\" + filename, H5F_ACC_TRUNC);\n\twrite::file_attrs(file, p);\n\n\tif(parent_liquid)\n\t\twrite::evolution_history(file, liquid_history);\n\tif(thermal_relaxation)\n\t\twrite::evolution_history(file, thermal_relaxation_hist);\n\twrite::evolution_history(file, aqs_history);\n\tif(reload)\n\t{\n\t\twrite::evolution_history(file, aqs_unloading);\n\t\twrite::evolution_history(file, aqs_reload_forward);\n\t\twrite::evolution_history(file, aqs_reload_backward);\n\t}\n\n\twrite::patch_info<dim>(file, \"/patch_info\", patch_to_element_map);\n\twrite::element_info(file, \"/element_info\", elements);\n\twrite::snapshots(file, \"/snapshots\", threshold_snapshots, stress_snapshots, def_grad_snapshots,\n\t\t\t\t\t patch_prop_snapshots, global_properties_snapshots);\n\tfile.close();\n\n\n\t/* ---- delete dynamically-allocated objects ----- */\n\tfor(auto &element : elements)\n\t\tdelete element;\n\n\tif(p.out.verbosity and omp_get_thread_num() == 0)\n\t\ttimer->print_summary();\n} // run\n\n\n} // espci\n\n\nint main(int argc, char *argv[])\n{\n\tcli::Parser parser(argc, argv);\n\tparser.set_optional<std::string>(\"f\", \"file\", \"./default.cfg\",\n\t\t\t\t\t\t\t\t\t \"Name of the input configuration file\");\n\tparser.run_and_exit_if_error();\n\n\tdealii::deallog.depth_console(0);\n\n\n\tespci::parameters::Parameters p;\n\n\ttry\n\t{\n\t\tp.load_file(parser.get<std::string>(\"f\"));\n\t}\n\tcatch(dealii::PathSearch::ExcFileNotFound &)\n\t{\n\t\tp.generate_file(parser.get<std::string>(\"f\"));\n\t\tstd::cout << \"Configuration file \" << parser.get<std::string>(\"f\") << \" created\" << std::endl;\n\t}\n\n\n\tunsigned int n_rep = p.sim.n_rep;\n\tif(n_rep < omp_get_max_threads())\n\t\tn_rep = omp_get_max_threads();\n\n\t// initialize the master engine with the master seed\n\tstd::srand(p.sim.seed);\n\n\t#pragma omp parallel\n\t{\n\t\tunsigned int n_threads = omp_get_max_threads();\n\t\tunsigned int id = omp_get_thread_num();\n\t\tunsigned int rep_per_thread = int( n_rep / n_threads );\n\n\t\tdealii::ConditionalOStream cout(std::cout, id==0 and p.out.verbosity);\n\n\t\tfor(unsigned int n = 0; n < rep_per_thread; ++n)\n\t\t{\n\t\t\tespci::parameters::Parameters p_thread = p;\n\t\t\t#pragma critical\n\t\t\t{\n\t\t\t\t// generate a seed for a simulation run\n\t\t\t\tp_thread.sim.seed = std::rand();\n\t\t\t};\n\n\t\t\tespci::run(p_thread, cout);\n\t\t}\n\n\t}\n\n}", "meta": {"hexsha": "750fcaf6c5a7f5735b37f6147954842f8f335ba0", "size": 16718, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gallery/espci/main.cc", "max_stars_repo_name": "kastellane/MEPLS", "max_stars_repo_head_hexsha": "9d7e4a7b9de73e65e3d4e4aba9b90a6fd563e186", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gallery/espci/main.cc", "max_issues_repo_name": "kastellane/MEPLS", "max_issues_repo_head_hexsha": "9d7e4a7b9de73e65e3d4e4aba9b90a6fd563e186", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gallery/espci/main.cc", "max_forks_repo_name": "kastellane/MEPLS", "max_forks_repo_head_hexsha": "9d7e4a7b9de73e65e3d4e4aba9b90a6fd563e186", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1902985075, "max_line_length": 106, "alphanum_fraction": 0.6847110898, "num_tokens": 4172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.808067204308405, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4229588180431052}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"poses-precomp.h\"\t// Precompiled headers\n//\n#include <mrpt/math/ops_containers.h>  // maximum()\n#include <mrpt/poses/CPoint3D.h>\n#include <mrpt/poses/CPointPDFParticles.h>\n#include <mrpt/poses/CPose3D.h>\n#include <mrpt/serialization/CArchive.h>\n#include <mrpt/system/os.h>\n\n#include <Eigen/Dense>\n\nusing namespace mrpt;\nusing namespace mrpt::poses;\nusing namespace mrpt::math;\nusing namespace mrpt::system;\n\nIMPLEMENTS_SERIALIZABLE(CPointPDFParticles, CPointPDF, mrpt::poses)\n\nCPointPDFParticles::CPointPDFParticles(size_t numParticles)\n{\n\tsetSize(numParticles);\n}\n\n/** Clear all the particles (free memory) */\nvoid CPointPDFParticles::clear() { setSize(0); }\n/*---------------------------------------------------------------\n\t\tsetSize\n  ---------------------------------------------------------------*/\nvoid CPointPDFParticles::setSize(\n\tsize_t numberParticles, const mrpt::math::TPoint3Df& defaultValue)\n{\n\t// Free old particles: automatic via smart ptr\n\tm_particles.resize(numberParticles);\n\tfor (auto& it : m_particles)\n\t{\n\t\tit.log_w = 0;\n\t\tit.d.reset(new TPoint3Df(defaultValue));\n\t}\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tgetMean\n  Returns an estimate of the pose, (the mean, or mathematical expectation of the\n PDF)\n ---------------------------------------------------------------*/\nvoid CPointPDFParticles::getMean(CPoint3D& p) const\n{\n\tMRPT_START\n\tif (m_particles.empty())\n\t\tTHROW_EXCEPTION(\"Cannot compute mean since there are zero particles.\");\n\n\tCParticleList::const_iterator it;\n\tdouble sumW = 0;\n\tdouble x = 0, y = 0, z = 0;\n\tfor (it = m_particles.begin(); it != m_particles.end(); it++)\n\t{\n\t\tconst double w = exp(it->log_w);\n\t\tx += it->d->x * w;\n\t\ty += it->d->y * w;\n\t\tz += it->d->z * w;\n\t\tsumW += w;\n\t}\n\n\tASSERT_(sumW != 0);\n\n\tsumW = 1.0 / sumW;\n\n\tp.x(x * sumW);\n\tp.y(y * sumW);\n\tp.z(z * sumW);\n\n\tMRPT_END\n}\n\nstd::tuple<CMatrixDouble33, CPoint3D> CPointPDFParticles::getCovarianceAndMean()\n\tconst\n{\n\tMRPT_START\n\n\tCPoint3D mean;\n\tCMatrixDouble33 cov;\n\n\tgetMean(mean);\n\tcov.setZero();\n\n\tsize_t i, n = m_particles.size();\n\tdouble var_x = 0, var_y = 0, var_p = 0, var_xy = 0, var_xp = 0, var_yp = 0;\n\n\tdouble lin_w_sum = 0;\n\n\tfor (i = 0; i < n; i++)\n\t\tlin_w_sum += exp(m_particles[i].log_w);\n\tif (lin_w_sum == 0) lin_w_sum = 1;\n\n\tfor (i = 0; i < n; i++)\n\t{\n\t\tdouble w = exp(m_particles[i].log_w) / lin_w_sum;\n\n\t\tdouble err_x = m_particles[i].d->x - mean.x();\n\t\tdouble err_y = m_particles[i].d->y - mean.y();\n\t\tdouble err_phi = m_particles[i].d->z - mean.z();\n\n\t\tvar_x += square(err_x) * w;\n\t\tvar_y += square(err_y) * w;\n\t\tvar_p += square(err_phi) * w;\n\t\tvar_xy += err_x * err_y * w;\n\t\tvar_xp += err_x * err_phi * w;\n\t\tvar_yp += err_y * err_phi * w;\n\t}\n\n\tif (n >= 2)\n\t{\n\t\t// Unbiased estimation of variance:\n\t\tcov(0, 0) = var_x;\n\t\tcov(1, 1) = var_y;\n\t\tcov(2, 2) = var_p;\n\n\t\tcov(1, 0) = cov(0, 1) = var_xy;\n\t\tcov(2, 0) = cov(0, 2) = var_xp;\n\t\tcov(1, 2) = cov(2, 1) = var_yp;\n\t}\n\n\treturn {cov, mean};\n\tMRPT_END\n}\n\nuint8_t CPointPDFParticles::serializeGetVersion() const { return 0; }\nvoid CPointPDFParticles::serializeTo(mrpt::serialization::CArchive& out) const\n{\n\tuint32_t N = size();\n\tout << N;\n\n\tfor (const auto& m_particle : m_particles)\n\t\tout << m_particle.log_w << m_particle.d->x << m_particle.d->y\n\t\t\t<< m_particle.d->z;\n}\n\nvoid CPointPDFParticles::serializeFrom(\n\tmrpt::serialization::CArchive& in, uint8_t version)\n{\n\tswitch (version)\n\t{\n\t\tcase 0:\n\t\t{\n\t\t\tuint32_t N;\n\t\t\tin >> N;\n\t\t\tsetSize(N);\n\n\t\t\tfor (auto& m_particle : m_particles)\n\t\t\t\tin >> m_particle.log_w >> m_particle.d->x >> m_particle.d->y >>\n\t\t\t\t\tm_particle.d->z;\n\t\t}\n\t\tbreak;\n\t\tdefault: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version);\n\t};\n}\n\nvoid CPointPDFParticles::copyFrom(const CPointPDF& o)\n{\n\tif (this == &o) return;\t // It may be used sometimes\n\n\t// Convert to samples:\n\tTHROW_EXCEPTION(\"NO\");\n}\n\n/*---------------------------------------------------------------\n\n  ---------------------------------------------------------------*/\nbool CPointPDFParticles::saveToTextFile(const std::string& file) const\n{\n\tMRPT_START\n\n\tFILE* f = os::fopen(file.c_str(), \"wt\");\n\tif (!f) return false;\n\n\tsize_t i, N = m_particles.size();\n\tfor (i = 0; i < N; i++)\n\t\tos::fprintf(\n\t\t\tf, \"%f %f %f %e\\n\", m_particles[i].d->x, m_particles[i].d->y,\n\t\t\tm_particles[i].d->z, m_particles[i].log_w);\n\n\tos::fclose(f);\n\treturn true;\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tchangeCoordinatesReference\n ---------------------------------------------------------------*/\nvoid CPointPDFParticles::changeCoordinatesReference(\n\tconst CPose3D& newReferenceBase)\n{\n\tTPoint3D pt;\n\tfor (auto& m_particle : m_particles)\n\t{\n\t\tnewReferenceBase.composePoint(\n\t\t\tm_particle.d->x, m_particle.d->y, m_particle.d->z,\t// In\n\t\t\tpt.x, pt.y, pt.z  // Out\n\t\t);\n\t\tm_particle.d->x = d2f(pt.x);\n\t\tm_particle.d->y = d2f(pt.y);\n\t\tm_particle.d->z = d2f(pt.z);\n\t}\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tcomputeKurtosis\n ---------------------------------------------------------------*/\ndouble CPointPDFParticles::computeKurtosis()\n{\n\tMRPT_START\n\n\t// kurtosis = \\mu^4 / (\\sigma^2) -3\n\tEigen::Vector3d kurts, mu4, m, var;\n\tkurts.fill(0);\n\tmu4.fill(0);\n\tm.fill(0);\n\tvar.fill(0);\n\n\t// Means:\n\tfor (auto& m_particle : m_particles)\n\t{\n\t\tm[0] += m_particle.d->x;\n\t\tm[1] += m_particle.d->y;\n\t\tm[2] += m_particle.d->z;\n\t}\n\tm *= 1.0 / m_particles.size();\n\n\t// variances:\n\tfor (auto& m_particle : m_particles)\n\t{\n\t\tvar[0] += square(m_particle.d->x - m[0]);\n\t\tvar[1] += square(m_particle.d->y - m[1]);\n\t\tvar[2] += square(m_particle.d->z - m[2]);\n\t}\n\tvar *= 1.0 / m_particles.size();\n\tvar[0] = square(var[0]);\n\tvar[1] = square(var[1]);\n\tvar[2] = square(var[2]);\n\n\t// Moment:\n\tfor (auto& m_particle : m_particles)\n\t{\n\t\tmu4[0] += pow(m_particle.d->x - m[0], 4.0);\n\t\tmu4[1] += pow(m_particle.d->y - m[1], 4.0);\n\t\tmu4[2] += pow(m_particle.d->z - m[2], 4.0);\n\t}\n\tmu4 *= 1.0 / m_particles.size();\n\n\t// Kurtosis's\n\tkurts.array() = mu4.array() / var.array();\n\n\treturn math::maximum(kurts);\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\tdrawSingleSample\n  ---------------------------------------------------------------*/\nvoid CPointPDFParticles::drawSingleSample([\n\t[maybe_unused]] CPoint3D& outSample) const\n{\n\tTHROW_EXCEPTION(\"TO DO!\");\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\tbayesianFusion\n ---------------------------------------------------------------*/\nvoid CPointPDFParticles::bayesianFusion(\n\t[[maybe_unused]] const CPointPDF& p1_,\n\t[[maybe_unused]] const CPointPDF& p2_,\n\t[[maybe_unused]] const double minMahalanobisDistToDrop)\n{\n\tMRPT_START\n\n\tTHROW_EXCEPTION(\"TODO!!!\");\n\n\tMRPT_END\n}\n", "meta": {"hexsha": "baa26536136a30e7222e9cbc908f302a9630b519", "size": 7332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/poses/src/CPointPDFParticles.cpp", "max_stars_repo_name": "wstnturner/mrpt", "max_stars_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T05:24:26.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-17T00:30:02.000Z", "max_issues_repo_path": "libs/poses/src/CPointPDFParticles.cpp", "max_issues_repo_name": "wstnturner/mrpt", "max_issues_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T22:43:00.000Z", "max_issues_repo_issues_event_max_datetime": "2015-07-17T18:52:59.000Z", "max_forks_repo_path": "libs/poses/src/CPointPDFParticles.cpp", "max_forks_repo_name": "wstnturner/mrpt", "max_forks_repo_head_hexsha": "b0be3557a4cded6bafff03feb28f7fa1f75762a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T12:32:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-30T15:50:13.000Z", "avg_line_length": 25.2827586207, "max_line_length": 80, "alphanum_fraction": 0.5396890344, "num_tokens": 2103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4229082418614177}}
{"text": "// Copyright (C) 2013 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/transformation/gdls_similarity_transform.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <cmath>\n#include <glog/logging.h>\n#include <vector>\n\n#include \"theia/alignment/alignment.h\"\n#include \"theia/sfm/pose/dls_impl.h\"\n#include \"theia/util/random.h\"\n\nnamespace theia {\n\nusing dls_impl::CreateMacaulayMatrix;\nusing dls_impl::ExtractJacobianCoefficients;\nusing dls_impl::LeftMultiplyMatrix;\nusing Eigen::Matrix;\nusing Eigen::Matrix3d;\nusing Eigen::Matrix4d;\nusing Eigen::MatrixXd;\nusing Eigen::Quaterniond;\nusing Eigen::Vector3d;\n\n// This implementation is based off of the DLS PnP implementation. The general\n// approach is to first rewrite the reprojection constraint (i.e., cost\n// function) such that all unknowns appear linearly in terms of the rotation\n// parameters (which are 3 parameters in the Cayley-Gibss-Rodriguez\n// formulation). Then we create a system of equations from the jacobian of the\n// cost function, and solve these equations via a Macaulay matrix to obtain the\n// roots (i.e., the 3 parameters of rotation). The translation and scale can\n// then be obtained through back-substitution.\nvoid GdlsSimilarityTransform(const std::vector<Vector3d>& ray_origin,\n                             const std::vector<Vector3d>& ray_direction,\n                             const std::vector<Vector3d>& world_point,\n                             std::vector<Quaterniond>* solution_rotation,\n                             std::vector<Vector3d>* solution_translation,\n                             std::vector<double>* solution_scale) {\n  CHECK_GE(ray_direction.size(), 4);\n\n  const int num_correspondences = ray_direction.size();\n  // The bottom-right symmetric block matrix of inverse(A^T * A). This is the\n  // generalized version of Matrix H from Eq. 17 in the Appendix of the gDLS\n  // paper (note that term appears exactly in the bottom right 3x3 of this\n  // matrix).\n  Matrix4d h_inverse = Matrix4d::Zero();\n  for (int i = 0; i < num_correspondences; i++) {\n    h_inverse(0, 0) = h_inverse(0, 0) + ray_origin[i].squaredNorm() -\n                      ray_origin[i].dot(ray_direction[i]) *\n                          ray_origin[i].dot(ray_direction[i]);\n    Vector3d temp_term =\n        -ray_origin[i] + ray_origin[i].dot(ray_direction[i]) * ray_direction[i];\n    h_inverse.block<3, 1>(1, 0) = h_inverse.block<3, 1>(1, 0) + temp_term;\n    h_inverse.block<1, 3>(0, 1) =\n        h_inverse.block<1, 3>(0, 1) + temp_term.transpose();\n    h_inverse.block<3, 3>(1, 1) =\n        h_inverse.block<3, 3>(1, 1) + Matrix3d::Identity() -\n        (ray_direction[i] * ray_direction[i].transpose());\n  }\n  const Matrix4d h_matrix = h_inverse.inverse();\n\n  // This is the translation and scale parameterized by the 9 entries of the\n  // rotation matrix. The first row is the scale and rows 2 - 4 are the\n  // translation.\n  Matrix<double, 4, 9> sv_helper = Matrix<double, 4, 9>::Zero();\n  for (int i = 0; i < num_correspondences; i++) {\n    // Scale factor.\n    sv_helper.row(0) =\n        sv_helper.row(0) +\n        (ray_origin[i].transpose() -\n         ray_origin[i].dot(ray_direction[i]) * ray_direction[i].transpose()) *\n            LeftMultiplyMatrix(world_point[i]);\n\n    // Translation factor.\n    sv_helper.block<3, 9>(1, 0) =\n        sv_helper.block<3, 9>(1, 0) +\n        (ray_direction[i] * ray_direction[i].transpose() -\n         Matrix3d::Identity()) *\n            LeftMultiplyMatrix(world_point[i]);\n  }\n\n  sv_helper = h_matrix * sv_helper;\n  const Matrix<double, 1, 9>& scale_factor = sv_helper.row(0);\n  const Matrix<double, 3, 9>& translation_factor = sv_helper.block<3, 9>(1, 0);\n\n  // Compute the cost function C' of Eq. 15 in gDLS paper. This is a factorized\n  // version where the rotation matrix parameters have been pulled out. The\n  // entries to this equation are the coefficients to the cost function which is\n  // a quartic in the rotation parameters.\n  Matrix<double, 9, 9> ls_cost_coefficients = Matrix<double, 9, 9>::Zero();\n  for (int i = 0; i < num_correspondences; i++) {\n    const Matrix<double, 3, 9> cost_coeff_term =\n        (ray_direction[i] * ray_direction[i].transpose() -\n         Matrix3d::Identity()) *\n        (LeftMultiplyMatrix(world_point[i]) - ray_origin[i] * scale_factor +\n         translation_factor);\n    ls_cost_coefficients =\n        ls_cost_coefficients + cost_coeff_term.transpose() * cost_coeff_term;\n  }\n\n  // Extract the coefficients of the jacobian (Eq. 16) from the\n  // ls_cost_coefficients matrix. The jacobian represent 3 monomials in the\n  // rotation parameters. Each entry of the jacobian will be 0 at the roots of\n  // the polynomial, so we can arrange a system of polynomials from these\n  // equations.\n  double f1_coeff[20];\n  double f2_coeff[20];\n  double f3_coeff[20];\n  ExtractJacobianCoefficients(\n      ls_cost_coefficients, f1_coeff, f2_coeff, f3_coeff);\n\n  // We create one equation with random terms that is generally non-zero at the\n  // roots of our system.\n  const Eigen::Vector4d rand_vec = 100.0 * Eigen::Vector4d::Random();\n  const double macaulay_term[4] = {\n      rand_vec(0), rand_vec(1), rand_vec(2), rand_vec(3)};\n\n  // Create Macaulay matrix that will be used to solve our polynonomial system.\n  const MatrixXd& macaulay_matrix =\n      CreateMacaulayMatrix(f1_coeff, f2_coeff, f3_coeff, macaulay_term);\n\n  // Via the Schur complement trick, the top-left of the Macaulay matrix\n  // contains a multiplication matrix whose eigenvectors correspond to solutions\n  // to our system of equations.\n  const MatrixXd solution_polynomial =\n      macaulay_matrix.block<27, 27>(0, 0) -\n      (macaulay_matrix.block<27, 93>(0, 27) *\n       macaulay_matrix.block<93, 93>(27, 27).partialPivLu().solve(\n           macaulay_matrix.block<93, 27>(27, 0)));\n\n  // Extract eigenvectors of the solution polynomial to obtain the roots which\n  // are contained in the entries of the eigenvectors.\n  const Eigen::EigenSolver<MatrixXd> eigen_solver(solution_polynomial);\n\n  // Many of the eigenvectors will contain complex solutions so we must filter\n  // them to find the real solutions.\n  const auto eigen_vectors = eigen_solver.eigenvectors();\n  for (int i = 0; i < 27; i++) {\n    // The first entry of the eigenvector should equal 1 according to our\n    // polynomial, so we must divide each solution by the first entry.\n    std::complex<double> s1 = eigen_vectors(9, i) / eigen_vectors(0, i);\n    std::complex<double> s2 = eigen_vectors(3, i) / eigen_vectors(0, i);\n    std::complex<double> s3 = eigen_vectors(1, i) / eigen_vectors(0, i);\n\n    // If the rotation solutions are real, treat this as a valid candidate\n    // rotation.\n    const double kEpsilon = 1e-6;\n    if (fabs(s1.imag()) < kEpsilon && fabs(s2.imag()) < kEpsilon &&\n        fabs(s3.imag()) < kEpsilon) {\n      // Compute the rotation (which is the transpose rotation of our solution)\n      // and translation.\n      Quaterniond soln_rotation(1.0, s1.real(), s2.real(), s3.real());\n      soln_rotation = soln_rotation.inverse().normalized();\n\n      const Matrix3d rot_mat = soln_rotation.inverse().toRotationMatrix();\n      const Eigen::Map<const Matrix<double, 9, 1> > rot_vec(rot_mat.data());\n      const Vector3d soln_translation = translation_factor * rot_vec;\n      const double soln_scale = scale_factor * rot_vec;\n\n      // TODO(cmsweeney): evaluate cost function and return it as an output\n      // variable.\n\n      // Check that all points are in front of the camera. Discard the solution\n      // if this is not the case.\n      bool all_points_in_front_of_camera = true;\n\n      for (int j = 0; j < num_correspondences; j++) {\n        const Vector3d transformed_point = soln_rotation * world_point[j] +\n                                           soln_translation -\n                                           soln_scale * ray_origin[j];\n\n        // Find the rotation that puts the image ray at [0, 0, 1] i.e. looking\n        // straightforward from the camera.\n        const Quaterniond unrot =\n            Quaterniond::FromTwoVectors(ray_direction[j], Vector3d(0, 0, 1));\n\n        // Rotate the transformed point and check if the z coordinate is\n        // negative. This will indicate if the point is projected behind the\n        // camera.\n        const Vector3d rotated_projection = unrot * transformed_point;\n        if (rotated_projection.z() < 0) {\n          all_points_in_front_of_camera = false;\n          break;\n        }\n      }\n\n      if (all_points_in_front_of_camera) {\n        solution_rotation->push_back(soln_rotation);\n        solution_translation->push_back(soln_translation);\n        solution_scale->push_back(soln_scale);\n      }\n    }\n  }\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "0f1ad6c8fad734dce498d216ba05fdc9b8a38570", "size": 10477, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/transformation/gdls_similarity_transform.cc", "max_stars_repo_name": "urbste/pyTheiaSfM", "max_stars_repo_head_hexsha": "814034c96b602fef1dc76ae6692278d61179ebcc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-10T19:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T08:16:54.000Z", "max_issues_repo_path": "src/theia/sfm/transformation/gdls_similarity_transform.cc", "max_issues_repo_name": "urbste/TheiaSfM", "max_issues_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/transformation/gdls_similarity_transform.cc", "max_forks_repo_name": "urbste/TheiaSfM", "max_forks_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-20T03:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T08:08:52.000Z", "avg_line_length": 45.1594827586, "max_line_length": 80, "alphanum_fraction": 0.6858833636, "num_tokens": 2601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4229082418614177}}
{"text": "// Copyright 2015-2018 Hans Dembinski\n//\n// Distributed under the Boost Software License, version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_HISTOGRAM_ACCUMULATORS_MEAN_HPP\n#define BOOST_HISTOGRAM_ACCUMULATORS_MEAN_HPP\n\n#include <boost/histogram/fwd.hpp>\n#include <cstddef>\n#include <type_traits>\n\nnamespace boost {\nnamespace histogram {\nnamespace accumulators {\n\n/** Calculates mean and variance of sample.\n\n  Uses Welfords's incremental algorithm to improve the numerical\n  stability of mean and variance computation.\n*/\ntemplate <class RealType>\nclass mean {\npublic:\n  mean() = default;\n  mean(const std::size_t n, const RealType& mean, const RealType& variance)\n      : sum_(n), mean_(mean), sum_of_deltas_squared_(variance * (sum_ - 1)) {}\n\n  void operator()(const RealType& x) {\n    sum_ += 1;\n    const auto delta = x - mean_;\n    mean_ += delta / sum_;\n    sum_of_deltas_squared_ += delta * (x - mean_);\n  }\n\n  template <class T>\n  mean& operator+=(const mean<T>& rhs) {\n    const auto tmp = mean_ * sum_ + static_cast<RealType>(rhs.mean_ * rhs.sum_);\n    sum_ += rhs.sum_;\n    mean_ = tmp / sum_;\n    sum_of_deltas_squared_ += static_cast<RealType>(rhs.sum_of_deltas_squared_);\n    return *this;\n  }\n\n  mean& operator*=(const RealType& s) {\n    mean_ *= s;\n    sum_of_deltas_squared_ *= s * s;\n    return *this;\n  }\n\n  template <class T>\n  bool operator==(const mean<T>& rhs) const noexcept {\n    return sum_ == rhs.sum_ && mean_ == rhs.mean_ &&\n           sum_of_deltas_squared_ == rhs.sum_of_deltas_squared_;\n  }\n\n  template <class T>\n  bool operator!=(const mean<T>& rhs) const noexcept {\n    return !operator==(rhs);\n  }\n\n  std::size_t count() const noexcept { return sum_; }\n  const RealType& value() const noexcept { return mean_; }\n  RealType variance() const { return sum_of_deltas_squared_ / (sum_ - 1); }\n\n  template <class Archive>\n  void serialize(Archive&, unsigned /* version */);\n\nprivate:\n  std::size_t sum_ = 0;\n  RealType mean_ = 0, sum_of_deltas_squared_ = 0;\n};\n\n} // namespace accumulators\n} // namespace histogram\n} // namespace boost\n\n#ifndef BOOST_HISTOGRAM_DOXYGEN_INVOKED\nnamespace std {\ntemplate <class T, class U>\n/// Specialization for boost::histogram::accumulators::mean.\nstruct common_type<boost::histogram::accumulators::mean<T>,\n                   boost::histogram::accumulators::mean<U>> {\n  using type = boost::histogram::accumulators::mean<common_type_t<T, U>>;\n};\n} // namespace std\n#endif\n\n#endif\n", "meta": {"hexsha": "5bb8d840a2582ce2e7b03d40f3afcfef32cbfa45", "size": 2516, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/histogram/accumulators/mean.hpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/boost/histogram/accumulators/mean.hpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/boost/histogram/accumulators/mean.hpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 27.6483516484, "max_line_length": 80, "alphanum_fraction": 0.6947535771, "num_tokens": 674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.4229082281396332}}
{"text": "//  Copyright Paul A. Bristow 2007.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_STATS_rayleigh_HPP\n#define BOOST_STATS_rayleigh_HPP\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/math/special_functions/expm1.hpp>\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n#include <boost/config/no_tr1/cmath.hpp>\n\n#ifdef BOOST_MSVC\n# pragma warning(push)\n# pragma warning(disable: 4702) // unreachable code (return after domain_error throw).\n#endif\n\n#include <utility>\n\nnamespace boost{ namespace math{\n\nnamespace detail\n{ // Error checks:\n  template <class RealType, class Policy>\n  inline bool verify_sigma(const char* function, RealType sigma, RealType* presult, const Policy& pol)\n  {\n     if(sigma <= 0)\n     {\n        *presult = policies::raise_domain_error<RealType>(\n           function,\n           \"The scale parameter \\\"sigma\\\" must be > 0, but was: %1%.\", sigma, pol);\n        return false;\n     }\n     return true;\n  } // bool verify_sigma\n\n  template <class RealType, class Policy>\n  inline bool verify_rayleigh_x(const char* function, RealType x, RealType* presult, const Policy& pol)\n  {\n     if(x < 0)\n     {\n        *presult = policies::raise_domain_error<RealType>(\n           function,\n           \"The random variable must be >= 0, but was: %1%.\", x, pol);\n        return false;\n     }\n     return true;\n  } // bool verify_rayleigh_x\n} // namespace detail\n\ntemplate <class RealType = double, class Policy = policies::policy<> >\nclass rayleigh_distribution\n{\npublic:\n   typedef RealType value_type;\n   typedef Policy policy_type;\n\n   rayleigh_distribution(RealType sigma = 1)\n      : m_sigma(sigma)\n   {\n      RealType err;\n      detail::verify_sigma(\"boost::math::rayleigh_distribution<%1%>::rayleigh_distribution\", sigma, &err, Policy());\n   } // rayleigh_distribution\n\n   RealType sigma()const\n   { // Accessor.\n     return m_sigma;\n   }\n\nprivate:\n   RealType m_sigma;\n}; // class rayleigh_distribution\n\ntypedef rayleigh_distribution<double> rayleigh;\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> range(const rayleigh_distribution<RealType, Policy>& /*dist*/)\n{ // Range of permissible values for random variable x.\n   using boost::math::tools::max_value;\n   return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>());\n}\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> support(const rayleigh_distribution<RealType, Policy>& /*dist*/)\n{ // Range of supported values for random variable x.\n   // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\n   using boost::math::tools::max_value;\n   return std::pair<RealType, RealType>((0),  max_value<RealType>());\n}\n\ntemplate <class RealType, class Policy>\ninline RealType pdf(const rayleigh_distribution<RealType, Policy>& dist, const RealType& x)\n{\n   BOOST_MATH_STD_USING // for ADL of std function exp.\n\n   RealType sigma = dist.sigma();\n   RealType result;\n   static const char* function = \"boost::math::pdf(const rayleigh_distribution<%1%>&, %1%)\";\n   if(false == detail::verify_sigma(function, sigma, &result, Policy()))\n   {\n      return result;\n   }\n   if(false == detail::verify_rayleigh_x(function, x, &result, Policy()))\n   {\n      return result;\n   }\n   RealType sigmasqr = sigma * sigma;\n   result = x * (exp(-(x * x) / ( 2 * sigmasqr))) / sigmasqr; \n   return result;\n} // pdf\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const rayleigh_distribution<RealType, Policy>& dist, const RealType& x)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   RealType result;\n   RealType sigma = dist.sigma();\n   static const char* function = \"boost::math::cdf(const rayleigh_distribution<%1%>&, %1%)\";\n   if(false == detail::verify_sigma(function, sigma, &result, Policy()))\n   {\n      return result;\n   }\n   if(false == detail::verify_rayleigh_x(function, x, &result, Policy()))\n   {\n      return result;\n   }\n   result = -boost::math::expm1(-x * x / ( 2 * sigma * sigma), Policy());\n   return result;\n} // cdf\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const rayleigh_distribution<RealType, Policy>& dist, const RealType& p)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   RealType result;\n   RealType sigma = dist.sigma();\n   static const char* function = \"boost::math::quantile(const rayleigh_distribution<%1%>&, %1%)\";\n   if(false == detail::verify_sigma(function, sigma, &result, Policy()))\n      return result;\n   if(false == detail::check_probability(function, p, &result, Policy()))\n      return result;\n\n   if(p == 0)\n   {\n      return 0;\n   }\n   if(p == 1)\n   {\n     return policies::raise_overflow_error<RealType>(function, 0, Policy());\n   }\n   result = sqrt(-2 * sigma * sigma * boost::math::log1p(-p, Policy()));\n   return result;\n} // quantile\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const complemented2_type<rayleigh_distribution<RealType, Policy>, RealType>& c)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   RealType result;\n   RealType sigma = c.dist.sigma();\n   static const char* function = \"boost::math::cdf(const rayleigh_distribution<%1%>&, %1%)\";\n   if(false == detail::verify_sigma(function, sigma, &result, Policy()))\n   {\n      return result;\n   }\n   RealType x = c.param;\n   if(false == detail::verify_rayleigh_x(function, x, &result, Policy()))\n   {\n      return result;\n   }\n   result =  exp(-x * x / ( 2 * sigma * sigma));\n   return result;\n} // cdf complement\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const complemented2_type<rayleigh_distribution<RealType, Policy>, RealType>& c)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions, log & sqrt.\n\n   RealType result;\n   RealType sigma = c.dist.sigma();\n   static const char* function = \"boost::math::quantile(const rayleigh_distribution<%1%>&, %1%)\";\n   if(false == detail::verify_sigma(function, sigma, &result, Policy()))\n   {\n      return result;\n   }\n   RealType q = c.param;\n   if(false == detail::check_probability(function, q, &result, Policy()))\n   {\n      return result;\n   }\n   if(q == 1)\n   {\n      return 0;\n   }\n   if(q == 0)\n   {\n     return policies::raise_overflow_error<RealType>(function, 0, Policy());\n   }\n   result = sqrt(-2 * sigma * sigma * log(q));\n   return result;\n} // quantile complement\n\ntemplate <class RealType, class Policy>\ninline RealType mean(const rayleigh_distribution<RealType, Policy>& dist)\n{\n   RealType result;\n   RealType sigma = dist.sigma();\n   static const char* function = \"boost::math::mean(const rayleigh_distribution<%1%>&, %1%)\";\n   if(false == detail::verify_sigma(function, sigma, &result, Policy()))\n   {\n      return result;\n   }\n   using boost::math::constants::root_half_pi;\n   return sigma * root_half_pi<RealType>();\n} // mean\n\ntemplate <class RealType, class Policy>\ninline RealType variance(const rayleigh_distribution<RealType, Policy>& dist)\n{\n   RealType result;\n   RealType sigma = dist.sigma();\n   static const char* function = \"boost::math::variance(const rayleigh_distribution<%1%>&, %1%)\";\n   if(false == detail::verify_sigma(function, sigma, &result, Policy()))\n   {\n      return result;\n   }\n   using boost::math::constants::four_minus_pi;\n   return four_minus_pi<RealType>() * sigma * sigma / 2;\n} // variance\n\ntemplate <class RealType, class Policy>\ninline RealType mode(const rayleigh_distribution<RealType, Policy>& dist)\n{\n   return dist.sigma();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType median(const rayleigh_distribution<RealType, Policy>& dist)\n{\n   using boost::math::constants::root_ln_four;\n   return root_ln_four<RealType>() * dist.sigma();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType skewness(const rayleigh_distribution<RealType, Policy>& /*dist*/)\n{\n  // using namespace boost::math::constants;\n  return static_cast<RealType>(0.63111065781893713819189935154422777984404221106391L);\n  // Computed using NTL at 150 bit, about 50 decimal digits.\n  // return 2 * root_pi<RealType>() * pi_minus_three<RealType>() / pow23_four_minus_pi<RealType>();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis(const rayleigh_distribution<RealType, Policy>& /*dist*/)\n{\n  // using namespace boost::math::constants;\n  return static_cast<RealType>(3.2450893006876380628486604106197544154170667057995L);\n  // Computed using NTL at 150 bit, about 50 decimal digits.\n  // return 3 - (6 * pi<RealType>() * pi<RealType>() - 24 * pi<RealType>() + 16) /\n  // (four_minus_pi<RealType>() * four_minus_pi<RealType>());\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis_excess(const rayleigh_distribution<RealType, Policy>& /*dist*/)\n{\n  //using namespace boost::math::constants;\n  // Computed using NTL at 150 bit, about 50 decimal digits.\n  return static_cast<RealType>(0.2450893006876380628486604106197544154170667057995L);\n  // return -(6 * pi<RealType>() * pi<RealType>() - 24 * pi<RealType>() + 16) /\n  //   (four_minus_pi<RealType>() * four_minus_pi<RealType>());\n} // kurtosis\n\n} // namespace math\n} // namespace boost\n\n#ifdef BOOST_MSVC\n# pragma warning(pop)\n#endif\n\n// This include must be at the end, *after* the accessors\n// for this distribution have been defined, in order to\n// keep compilers that support two-phase lookup happy.\n#include <boost/math/distributions/detail/derived_accessors.hpp>\n\n#endif // BOOST_STATS_rayleigh_HPP\n", "meta": {"hexsha": "66d3d507a32cc06aa70f483849993f4b8e383fea", "size": 9693, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/boost_1_44_0/boost/math/distributions/rayleigh.hpp", "max_stars_repo_name": "RaptDept/slimtune", "max_stars_repo_head_hexsha": "a9a248a342a51d95b7c833bce5bb91bf3db987f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-07-01T03:26:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-06T06:00:38.000Z", "max_issues_repo_path": "external/boost_1_44_0/boost/math/distributions/rayleigh.hpp", "max_issues_repo_name": "RaptDept/slimtune", "max_issues_repo_head_hexsha": "a9a248a342a51d95b7c833bce5bb91bf3db987f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-02T17:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-02T17:31:28.000Z", "max_forks_repo_path": "external/boost_1_44_0/boost/math/distributions/rayleigh.hpp", "max_forks_repo_name": "RaptDept/slimtune", "max_forks_repo_head_hexsha": "a9a248a342a51d95b7c833bce5bb91bf3db987f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-02-05T19:34:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T08:46:34.000Z", "avg_line_length": 32.9693877551, "max_line_length": 116, "alphanum_fraction": 0.6966883318, "num_tokens": 2479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.422882520059657}}
{"text": "//| Copyright Inria May 2015\n//| This project has received funding from the European Research Council (ERC) under\n//| the European Union's Horizon 2020 research and innovation programme (grant\n//| agreement No 637972) - see http://www.resibots.eu\n//|\n//| Contributor(s):\n//|   - Jean-Baptiste Mouret (jean-baptiste.mouret@inria.fr)\n//|   - Antoine Cully (antoinecully@gmail.com)\n//|   - Konstantinos Chatzilygeroudis (konstantinos.chatzilygeroudis@inria.fr)\n//|   - Federico Allocati (fede.allocati@gmail.com)\n//|   - Vaios Papaspyros (b.papaspyros@gmail.com)\n//|   - Roberto Rama (bertoski@gmail.com)\n//|\n//| This software is a computer library whose purpose is to optimize continuous,\n//| black-box functions. It mainly implements Gaussian processes and Bayesian\n//| optimization.\n//| Main repository: http://github.com/resibots/limbo\n//| Documentation: http://www.resibots.eu/limbo\n//|\n//| This software is governed by the CeCILL-C license under French law and\n//| abiding by the rules of distribution of free software.  You can  use,\n//| modify and/ or redistribute the software under the terms of the CeCILL-C\n//| license as circulated by CEA, CNRS and INRIA at the following URL\n//| \"http://www.cecill.info\".\n//|\n//| As a counterpart to the access to the source code and  rights to copy,\n//| modify and redistribute granted by the license, users are provided only\n//| with a limited warranty  and the software's author,  the holder of the\n//| economic rights,  and the successive licensors  have only  limited\n//| liability.\n//|\n//| In this respect, the user's attention is drawn to the risks associated\n//| with loading,  using,  modifying and/or developing or reproducing the\n//| software by the user in light of its specific status of free software,\n//| that may mean  that it is complicated to manipulate,  and  that  also\n//| therefore means  that it is reserved for developers  and  experienced\n//| professionals having in-depth computer knowledge. Users are therefore\n//| encouraged to load and test the software's suitability as regards their\n//| requirements in conditions enabling the security of their systems and/or\n//| data to be ensured and,  more generally, to use and operate it in the\n//| same conditions as regards security.\n//|\n//| The fact that you are presently reading this means that you have had\n//| knowledge of the CeCILL-C license and that you accept its terms.\n//|\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <Eigen/Core>\n\n#ifdef USE_TBB\n#include <tbb/concurrent_hash_map.h>\n#include <tbb/parallel_for.h>\n#include <tbb/task_scheduler_init.h>\n#else\n#include <map>\n#endif\n\n#include <limbo/experimental/acqui/ucb_imgpo.hpp>\n#include <limbo/experimental/bayes_opt/imgpo.hpp>\n#include <limbo/init/no_init.hpp>\n#include <limbo/mean/constant.hpp>\n#include <limbo/tools/macros.hpp>\n#include <limbo/tools/parallel.hpp>\n\nusing namespace limbo;\n\nstatic constexpr int nb_replicates = 4;\n\nnamespace colors {\n    static const char* red = \"\\33[31m\";\n    static const char* green = \"\\33[32m\";\n    static const char* yellow = \"\\33[33m\";\n    static const char* reset = \"\\33[0m\";\n    static const char* bold = \"\\33[1m\";\n}\n\n// support functions\ninline double sign(double x)\n{\n    if (x < 0)\n        return -1;\n    if (x > 0)\n        return 1;\n    return 0;\n}\n\ninline double hat(double x)\n{\n    if (x != 0)\n        return log(fabs(x));\n    return 0;\n}\n\ninline double c1(double x)\n{\n    if (x > 0)\n        return 10;\n    return 5.5;\n}\n\ninline double c2(double x)\n{\n    if (x > 0)\n        return 7.9;\n    return 3.1;\n}\n\ninline Eigen::VectorXd t_osz(const Eigen::VectorXd& x)\n{\n    Eigen::VectorXd r = x;\n    for (int i = 0; i < x.size(); i++)\n        r(i) = sign(x(i)) * exp(hat(x(i)) + 0.049 * sin(c1(x(i)) * hat(x(i))) + sin(c2(x(i)) * hat(x(i))));\n    return r;\n}\n\nstruct Sphere {\n    BO_PARAM(size_t, dim_in, 2);\n    BO_PARAM(size_t, dim_out, 1);\n\n    Eigen::VectorXd operator()(const Eigen::VectorXd& x) const\n    {\n        Eigen::Vector2d opt(0.5, 0.5);\n        return tools::make_vector(-(x - opt).squaredNorm());\n    }\n};\n\nstruct Ellipsoid {\n    BO_PARAM(size_t, dim_in, 2);\n    BO_PARAM(size_t, dim_out, 1);\n\n    Eigen::VectorXd operator()(const Eigen::VectorXd& x) const\n    {\n        Eigen::Vector2d opt(0.5, 0.5);\n        Eigen::Vector2d z = t_osz(x - opt);\n        double r = 0;\n        for (size_t i = 0; i < dim_in(); ++i)\n            r += std::pow(10, ((double)i) / (dim_in() - 1.0)) * z(i) * z(i) + 1;\n        return tools::make_vector(-r);\n    }\n};\n\nstruct Rastrigin {\n    BO_PARAM(size_t, dim_in, 4);\n    BO_PARAM(size_t, dim_out, 1);\n\n    Eigen::VectorXd operator()(const Eigen::VectorXd& x) const\n    {\n        double f = 10 * x.size();\n        for (int i = 0; i < x.size(); ++i)\n            f += x(i) * x(i) - 10 * cos(2 * M_PI * x(i));\n        return tools::make_vector(-f);\n    }\n};\n\n// see : http://www.sfu.ca/~ssurjano/hart3.html\nstruct Hartman3 {\n    BO_PARAM(size_t, dim_in, 3);\n    BO_PARAM(size_t, dim_out, 1);\n\n    Eigen::VectorXd operator()(const Eigen::VectorXd& x) const\n    {\n        Eigen::Matrix<double, 4, 3> a, p;\n        a << 3.0, 10, 30, 0.1, 10, 35, 3.0, 10, 30, 0.1, 10, 36;\n        p << 0.3689, 0.1170, 0.2673, 0.4699, 0.4387, 0.7470, 0.1091, 0.8732, 0.5547,\n            0.0382, 0.5743, 0.8828;\n        Eigen::Vector4d alpha;\n        alpha << 1.0, 1.2, 3.0, 3.2;\n\n        double res = 0;\n        for (int i = 0; i < 4; i++) {\n            double s = 0.0f;\n            for (size_t j = 0; j < 3; j++) {\n                s += a(i, j) * (x(j) - p(i, j)) * (x(j) - p(i, j));\n            }\n            res += alpha(i) * exp(-s);\n        }\n        return tools::make_vector(res);\n    }\n};\n\n// see : http://www.sfu.ca/~ssurjano/hart6.html\nstruct Hartman6 {\n    BO_PARAM(size_t, dim_in, 6);\n    BO_PARAM(size_t, dim_out, 1);\n\n    Eigen::VectorXd operator()(const Eigen::VectorXd& x) const\n    {\n        Eigen::Matrix<double, 4, 6> a, p;\n        a << 10, 3, 17, 3.5, 1.7, 8, 0.05, 10, 17, 0.1, 8, 14, 3, 3.5, 1.7, 10, 17,\n            8, 17, 8, 0.05, 10, 0.1, 14;\n        p << 0.1312, 0.1696, 0.5569, 0.0124, 0.8283, 0.5886, 0.2329, 0.4135, 0.8307,\n            0.3736, 0.1004, 0.9991, 0.2348, 0.1451, 0.3522, 0.2883, 0.3047, 0.665,\n            0.4047, 0.8828, 0.8732, 0.5743, 0.1091, 0.0381;\n\n        Eigen::Vector4d alpha;\n        alpha << 1.0, 1.2, 3.0, 3.2;\n\n        double res = 0;\n        for (int i = 0; i < 4; i++) {\n            double s = 0.0f;\n            for (size_t j = 0; j < 6; j++) {\n                s += a(i, j) * (x(j) - p(i, j)) * (x(j) - p(i, j));\n            }\n            res += alpha(i) * exp(-s);\n        }\n        return tools::make_vector(res);\n    }\n};\n\n// see : http://www.sfu.ca/~ssurjano/goldpr.html\n// (with ln, as suggested in Jones et al.)\nstruct GoldenPrice {\n    BO_PARAM(size_t, dim_in, 2);\n    BO_PARAM(size_t, dim_out, 1);\n\n    Eigen::VectorXd operator()(const Eigen::VectorXd& xx) const\n    {\n        Eigen::VectorXd x = (4.0 * xx).array() - 2.0;\n        double r = (1 + (x(0) + x(1) + 1) * (x(0) + x(1) + 1) * (19 - 14 * x(0) + 3 * x(0) * x(0) - 14 * x(1) + 6 * x(0) * x(1) + 3 * x(1) * x(1))) * (30 + (2 * x(0) - 3 * x(1)) * (2 * x(0) - 3 * x(1)) * (18 - 32 * x(0) + 12 * x(0) * x(0) + 48 * x(1) - 36 * x(0) * x(1) + 27 * x(1) * x(1)));\n\n        return tools::make_vector(-log(r) + 5);\n    }\n};\n\nstruct Params {\n    struct bayes_opt_bobase : public defaults::bayes_opt_bobase {\n        BO_PARAM(bool, stats_enabled, false);\n    };\n\n    struct bayes_opt_imgpo : public defaults::bayes_opt_imgpo {\n    };\n\n    struct kernel : public defaults::kernel {\n        BO_PARAM(double, noise, 1e-10);\n    };\n\n    struct kernel_exp : public defaults::kernel_exp {\n    };\n\n    struct stop_maxiterations {\n        BO_PARAM(int, iterations, 100);\n    };\n\n    struct acqui_ucb_imgpo : public defaults::acqui_ucb_imgpo {\n    };\n\n    struct mean_constant {\n        BO_PARAM(double, constant, 0);\n    };\n};\n\ntemplate <typename T>\nvoid print_res(const T& r)\n{\n    std::cout << \"====== RESULTS ======\" << std::endl;\n    for (auto x : r) {\n        for (auto y : x.second) {\n            std::cout << x.first << \"\\t =>\"\n                      << \" found :\" << y.second << \" expected \" << y.first\n                      << std::endl;\n        }\n        std::vector<std::pair<double, double>>& v = x.second;\n        std::sort(v.begin(), v.end(),\n            [](const std::pair<double, double>& x1,\n                      const std::pair<double, double>& x2) {\n                // clang-format off\n                return x1.second < x2.second;\n                // clang-format on\n            });\n        double med = v[v.size() / 2].second;\n        if (fabs(v[0].first - med) < 0.05)\n            std::cout << \"[\" << colors::green << \"OK\" << colors::reset << \"] \";\n        else\n            std::cout << \"[\" << colors::red << \"ERROR\" << colors::reset << \"] \";\n        std::cout << colors::yellow << colors::bold << \" -- \" << x.first\n                  << colors::reset << \" \";\n        std::cout << \"Median: \" << med << \" error :\" << fabs(v[0].first - med)\n                  << std::endl;\n    }\n}\n\nbool is_in_argv(int argc, char** argv, const char* needle)\n{\n    auto it = std::find_if(argv, argv + argc,\n        [=](const char* s) {\n            // clang-format off\n            return strcmp(needle, s) == 0;\n            // clang-format on\n        });\n    return !(it == argv + argc);\n}\n\ntemplate <typename T1, typename T2>\nvoid add_to_results(const char* key, T1& map, const T2& p)\n{\n#ifdef USE_TBB\n    typename T1::accessor a;\n    if (!map.find(a, key))\n        map.insert(a, key);\n#else\n    typename T1::iterator a;\n    a = map.find(key);\n    if (a == map.end())\n        map[key] = std::vector<std::pair<double, double>>();\n#endif\n    a->second.push_back(p);\n}\n\nint main(int argc, char** argv)\n{\n    tools::par::init();\n\n#ifdef USE_TBB\n    using res_t = tbb::concurrent_hash_map<std::string, std::vector<std::pair<double, double>>>;\n#else\n    using res_t = std::map<std::string, std::vector<std::pair<double, double>>>;\n#endif\n    res_t results;\n\n    using kf_t = kernel::Exp<Params>;\n    using mean_t = mean::Constant<Params>;\n    using model_t = model::GP<Params, kf_t, mean_t>;\n    using init_t = init::NoInit<Params>;\n    using acqui_t = acqui::experimental::UCB_IMGPO<Params, model_t>;\n\n    using Opt_t = bayes_opt::experimental::IMGPO<Params, modelfun<model_t>, initfun<init_t>, acquifun<acqui_t>>;\n\n    if (!is_in_argv(argc, argv, \"--only\") || is_in_argv(argc, argv, \"sphere\"))\n        tools::par::replicate(nb_replicates, [&]() {\n            // clang-format off\n                Opt_t opt;\n                opt.optimize(Sphere());\n                Eigen::Vector2d s_val(0.5, 0.5);\n                double x_opt = FirstElem()(Sphere()(s_val));\n                add_to_results(\"Sphere\", results, std::make_pair(x_opt, opt.best_observation()(0)));\n            // clang-format on\n        });\n\n    if (!is_in_argv(argc, argv, \"--only\") || is_in_argv(argc, argv, \"ellipsoid\"))\n        tools::par::replicate(nb_replicates, [&]() {\n            // clang-format off\n                Opt_t opt;\n                opt.optimize(Ellipsoid());\n                Eigen::Vector2d s_val(0.5, 0.5);\n                double x_opt = FirstElem()(Ellipsoid()(s_val));\n                add_to_results(\"Ellipsoid\", results, std::make_pair(x_opt, opt.best_observation()(0)));\n            // clang-format on\n        });\n\n    if (!is_in_argv(argc, argv, \"--only\") || is_in_argv(argc, argv, \"rastrigin\"))\n        tools::par::replicate(nb_replicates, [&]() {\n            // clang-format off\n                Opt_t opt;\n                opt.optimize(Rastrigin());\n                Eigen::Vector4d s_val(0, 0, 0, 0);\n                double x_opt = FirstElem()(Rastrigin()(s_val));\n                add_to_results(\"Rastrigin\", results, std::make_pair(x_opt, opt.best_observation()(0)));\n            // clang-format on\n        });\n\n    if (!is_in_argv(argc, argv, \"--only\") || is_in_argv(argc, argv, \"hartman3\"))\n        tools::par::replicate(nb_replicates, [&]() {\n            // clang-format off\n                Opt_t opt;\n                opt.optimize(Hartman3());\n                // double s_max = 3.86278;\n                Eigen::Vector3d s_val(0.114614, 0.555549, 0.852547);\n                double x_opt = FirstElem()(Hartman3()(s_val));\n                add_to_results(\"Hartman 3\", results, std::make_pair(x_opt, opt.best_observation()(0)));\n            // clang-format on\n        });\n\n    if (!is_in_argv(argc, argv, \"--only\") || is_in_argv(argc, argv, \"hartman6\"))\n        tools::par::replicate(nb_replicates, [&]() {\n            // clang-format off\n                Opt_t opt;\n                opt.optimize(Hartman6());\n                Eigen::Matrix<double, 6, 1> s_val;\n                s_val << 0.20169, 0.150011, 0.476874, 0.275332, 0.311652, 0.6573;\n                //double s_max = 3.32237;\n                double x_opt = FirstElem()(Hartman6()(s_val));\n                add_to_results(\"Hartman 6\", results, std::make_pair(x_opt, opt.best_observation()(0)));\n            // clang-format on\n        });\n\n    if (!is_in_argv(argc, argv, \"--only\") || is_in_argv(argc, argv, \"golden_price\"))\n        tools::par::replicate(nb_replicates, [&]() {\n            // clang-format off\n                Opt_t opt;\n                opt.optimize(GoldenPrice());\n                //    double s_max = -log(3);\n                Eigen::Vector2d s_val(0.5, 0.25);\n                double x_opt = FirstElem()(GoldenPrice()(s_val));\n                add_to_results(\"Golden Price\", results, std::make_pair(x_opt, opt.best_observation()(0)));\n            // clang-format on\n        });\n\n    std::cout << \"Benchmark finished.\" << std::endl;\n\n    print_res(results);\n    return 0;\n}\n", "meta": {"hexsha": "1d81d1c87b9393dbe168abea406f03c0d51b2294", "size": 13744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "limbo/src/examples/experimental/imgpo.cpp", "max_stars_repo_name": "yjjuan/automl_cplusplus", "max_stars_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-08T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T17:52:18.000Z", "max_issues_repo_path": "limbo/src/examples/experimental/imgpo.cpp", "max_issues_repo_name": "yjjuan/automl_cplusplus", "max_issues_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "limbo/src/examples/experimental/imgpo.cpp", "max_forks_repo_name": "yjjuan/automl_cplusplus", "max_forks_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6862745098, "max_line_length": 291, "alphanum_fraction": 0.5633003492, "num_tokens": 4171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4228825127252626}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_OFFSET_MULTIPLIER_FREE_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_OFFSET_MULTIPLIER_FREE_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/scal/fun/identity_free.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <cmath>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the unconstrained scalar that transforms to the\n * specified offset and multiplier constrained scalar given the specified\n * offset and multiplier.\n *\n * <p>The transfrom in <code>locmultiplier_constrain(T, double, double)</code>,\n * is reversed by the reverse affine transformation,\n *\n * <p>\\f$f^{-1}(y) = \\frac{y - L}{S}\\f$\n *\n * where \\f$L\\f$ and \\f$S\\f$ are the offset and multiplier.\n *\n * <p>If the offset is zero and multiplier is one,\n * this function reduces to  <code>identity_free(y)</code>.\n *\n * @tparam T type of scalar\n * @tparam L type of offset\n * @tparam S type of multiplier\n * @param y constrained value\n * @param[in] mu offset of constrained output\n * @param[in] sigma multiplier of constrained output\n * @return the free scalar that transforms to the input scalar\n *   given the offset and multiplier\n * @throw std::domain_error if sigma <= 0\n * @throw std::domain_error if mu is not finite\n */\ntemplate <typename T, typename L, typename S>\ninline return_type_t<T, L, S> offset_multiplier_free(const T& y, const L& mu,\n                                                     const S& sigma) {\n  check_finite(\"offset_multiplier_free\", \"offset\", mu);\n  if (sigma == 1) {\n    if (mu == 0)\n      return identity_free(y);\n    return y - mu;\n  }\n  check_positive_finite(\"offset_multiplier_free\", \"multiplier\", sigma);\n  return (y - mu) / sigma;\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "1167ad3473bb0c90dfc49419bff18b613e8a134b", "size": 1858, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/math/prim/scal/fun/offset_multiplier_free.hpp", "max_stars_repo_name": "alashworth/stan-monorepo", "max_stars_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-06T15:53:17.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-06T15:53:17.000Z", "max_issues_repo_path": "src/stan/math/prim/scal/fun/offset_multiplier_free.hpp", "max_issues_repo_name": "alashworth/stan-monorepo", "max_issues_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-01-17T18:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-17T18:51:39.000Z", "max_forks_repo_path": "src/stan/math/prim/scal/fun/offset_multiplier_free.hpp", "max_forks_repo_name": "alashworth/stan-monorepo", "max_forks_repo_head_hexsha": "75596bc1f860ededd7b3e9ae9002aea97ee1cd46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5964912281, "max_line_length": 79, "alphanum_fraction": 0.7018299247, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.42288251272526256}}
{"text": "/*\nCopyright 2017. All rights reserved.\nComputer Vision Group, Visual Computing Institute\nRWTH Aachen University, Germany\n\nThis file is part of the rwth_mot framework.\nAuthors: Aljosa Osep (osep -at- vision.rwth-aachen.de)\n\nrwth_mot framework is free software; you can redistribute it and/or modify it under the\nterms of the GNU General Public License as published by the Free Software\nFoundation; either version 3 of the License, or any later version.\n\nrwth_mot framework is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\nPARTICULAR PURPOSE. See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with\nrwth_mot framework; if not, write to the Free Software Foundation, Inc., 51 Franklin\nStreet, Fifth Floor, Boston, MA 02110-1301, USA\n*/\n\n#include \"utils_bounding_box.h\"\n\n// eigen\n#include <Eigen/Core>\n\n// utils\n#include \"utils_filtering.h\"\n#include \"camera.h\"\n#include \"utils_common.h\"\n\n\nnamespace SUN {\n    namespace utils {\n        namespace bbox {\n\n            Eigen::Vector4d Intersection2d(const Eigen::Vector4d &rect1, const Eigen::Vector4d &rect2) {\n                const double rect1_x = rect1[0];\n                const double rect1_y = rect1[1];\n                const double rect1_w = rect1[2];\n                const double rect1_h = rect1[3];\n\n                const double rect2_x = rect2[0];\n                const double rect2_y = rect2[1];\n                const double rect2_w = rect2[2];\n                const double rect2_h = rect2[3];\n\n                const double left = rect1_x > rect2_x ? rect1_x : rect2_x;\n                const double top = rect1_y > rect2_y ? rect1_y : rect2_y;\n                double lhs = rect1_x + rect1_w;\n                double rhs = rect2_x + rect2_w;\n                const double right = lhs < rhs ? lhs : rhs;\n                lhs = rect1_y + rect1_h;\n                rhs = rect2_y + rect2_h;\n                const double bottom = lhs < rhs ? lhs : rhs;\n\n                Eigen::Vector4d rect_intersection;\n                rect_intersection[0] = right < left ? 0 : left;\n                rect_intersection[1] = bottom < top ? 0 : top;\n                rect_intersection[2] = right < left ? 0 : right - left;\n                rect_intersection[3] = bottom < top ? 0 : bottom - top;\n\n                return rect_intersection;\n            }\n\n            double IntersectionOverUnion2d(const Eigen::Vector4d &rect1, const Eigen::Vector4d &rect2) {\n                Eigen::Vector4d rect_intersection = Intersection2d(rect1, rect2);\n                const double intersection_area = rect_intersection[2] * rect_intersection[3]; // Surface of the intersection of the rects\n                const double union_of_rects = rect1[2] * rect1[3] + rect2[2] * rect2[3] - intersection_area; // Union of the area of the rects\n                return intersection_area / union_of_rects; // Intersection over union\n            }\n\n            Eigen::Vector4d BoundingBox2d(pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr scene_cloud,\n                                          const std::vector<int> &indices, double percentage) {\n\n                pcl::PointIndices filtered_indices = SUN::utils::filter::FilterPointCloudBasedOnRadius(scene_cloud, indices, percentage);\n\n                int bbx_min = static_cast<int>(1e10);\n                int bbx_max = static_cast<int>(-1e10);\n                int bby_min = static_cast<int>(1e10);\n                int bby_max = static_cast<int>(-1e10);\n\n                for (auto ind:filtered_indices.indices) {\n                    int x = -1, y = -1;\n                    UnravelIndex(ind, scene_cloud->width, &x, &y);\n                    if (x < bbx_min)\n                        bbx_min = x;\n                    if (x > bbx_max)\n                        bbx_max = x;\n                    if (y < bby_min)\n                        bby_min = y;\n                    if (y > bby_max)\n                        bby_max = y;\n                }\n\n                // [min_x min_y w h]\n                Eigen::Vector4d bb2d_out;\n                bb2d_out[0] = static_cast<double>(bbx_min);\n                bb2d_out[1] = static_cast<double>(bby_min);\n                bb2d_out[2] = static_cast<double>(bbx_max - bbx_min);\n                bb2d_out[3] = static_cast<double>(bby_max - bby_min);\n\n                return bb2d_out;\n            }\n\n            Eigen::Vector4d BoundingBox2d(pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr object_cloud, const SUN::utils::Camera &cam, double percentage) {\n                auto filtered_cloud = SUN::utils::filter::FilterPointCloudBasedOnRadius(object_cloud,  percentage);\n\n                int bbx_min = static_cast<int>(1e10);\n                int bbx_max = static_cast<int>(-1e10);\n                int bby_min = static_cast<int>(1e10);\n                int bby_max = static_cast<int>(-1e10);\n\n                for (const auto &pt:filtered_cloud->points) {\n                    int x, y;\n\n                    auto proj_pt = cam.CameraToImage(pt.getVector4fMap().cast<double>());\n                    x = proj_pt[0];\n                    y = proj_pt[1];\n\n                    if (x < bbx_min)\n                        bbx_min = x;\n                    if (x > bbx_max)\n                        bbx_max = x;\n                    if (y < bby_min)\n                        bby_min = y;\n                    if (y > bby_max)\n                        bby_max = y;\n                }\n\n                // [min_x min_y w h]\n                Eigen::Vector4d bb2d_out;\n                bb2d_out[0] = static_cast<double>(bbx_min);\n                bb2d_out[1] = static_cast<double>(bby_min);\n                bb2d_out[2] = static_cast<double>(bbx_max - bbx_min);\n                bb2d_out[3] = static_cast<double>(bby_max - bby_min);\n\n                return bb2d_out;\n            }\n\n            Eigen::VectorXd BoundingBox3d(pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr cloud_in, double percentage) {\n                // Remove some points (radius-based cleaning)\n                auto cloud_to_process = SUN::utils::filter::FilterPointCloudBasedOnRadius(cloud_in, percentage);\n\n                // Compute mean, covariance matrix 3d\n                Eigen::Matrix3d cov_mat3d;\n                Eigen::Vector4d mean3d;\n                pcl::computeMeanAndCovarianceMatrix(*cloud_to_process, cov_mat3d, mean3d);\n\n                // Let's restrict ourselves to 2D ground-plane projection. More robust.\n                Eigen::Matrix2d cov_mat2d;\n                cov_mat2d(0, 0) = cov_mat3d(0, 0);\n                cov_mat2d(1, 1) = cov_mat3d(2, 2);\n                cov_mat2d(0, 1) = cov_mat3d(0, 2);\n                cov_mat2d(1, 0) = cov_mat3d(2, 0);\n\n                // Compute Eigen vectors, values.\n                // Here, we get 2 eigenvectors, corresponding to dominant axes of 2D proj. of object (to the ground plane).\n                Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> eigen_solver(cov_mat2d, Eigen::ComputeEigenvectors);\n                Eigen::Matrix2d eigen_vectors = eigen_solver.eigenvectors();\n\n                // Def. local coord. sys.\n                Eigen::Matrix3d p2w(Eigen::Matrix3d::Identity());\n                p2w.block<2, 2>(0, 0) = eigen_vectors.transpose();\n                Eigen::Vector2d c_2d(mean3d[0], mean3d[2]); // Mean on gp. proj.\n                p2w.block<2, 1>(0, 2) = -1.f * (p2w.block<2, 2>(0, 0) * c_2d); //centroid.head<2>());\n\n                // Find bbox extent (width, depth)\n                float bbx_min = static_cast<float>(1e4);\n                float bbx_max = static_cast<float>(-1e4);\n                float bbz_min = static_cast<float>(1e4);\n                float bbz_max = static_cast<float>(-1e4);\n\n                for (int i = 0; i <cloud_to_process->size(); i++) {\n\n                    const auto &p_ref = cloud_to_process->at(i);\n                    Eigen::Vector3d p_eig(p_ref.x, p_ref.z, 1.0);\n\n                    if (std::isnan(p_ref.x))\n                        continue;\n\n                    p_eig = p2w * p_eig;\n\n                    const float tmp_x = p_eig[0];\n                    const float tmp_z = p_eig[1];\n\n                    if (tmp_x < bbx_min)\n                        bbx_min = tmp_x;\n                    if (tmp_x > bbx_max)\n                        bbx_max = tmp_x;\n                    if (tmp_z < bbz_min)\n                        bbz_min = tmp_z;\n                    if (tmp_z > bbz_max)\n                        bbz_max = tmp_z;\n                }\n\n                // Find out orientation\n                Eigen::Matrix3d R_mat;\n                R_mat.setIdentity();\n                R_mat(0, 0) = eigen_vectors(0, 0);\n                R_mat(0, 2) = eigen_vectors(0, 1);\n                R_mat(2, 0) = eigen_vectors(1, 0);\n                R_mat(2, 2) = eigen_vectors(1, 1);\n                const Eigen::Vector2d mean_diag = 0.5f * (Eigen::Vector2d(bbx_min + bbx_max, bbz_min + bbz_max));\n                const Eigen::Vector2d tfinal = eigen_vectors * mean_diag + Eigen::Vector2d(mean3d[0], mean3d[2]);\n\n                // Final transform\n                Eigen::Quaterniond qfinal(R_mat);\n                double bb1 = bbx_max - bbx_min;\n                double bb3 = bbz_max - bbz_min;\n\n                // Get height\n                Eigen::Vector4f cloud_min, cloud_max;\n                pcl::getMinMax3D(*cloud_to_process, cloud_min, cloud_max);\n                double min_y = cloud_min[1];\n                double max_y = cloud_max[1];\n                double cloud_height = std::abs(max_y - min_y); // Difference between Y-coords.\n\n                // Resulting data structure\n                Eigen::VectorXd bb3d_out;\n                bb3d_out.setZero(10, 1); // center_x, center_y, center_z, width, height, depth, quaternion\n\n                // X-Z center from 2d-gp-PCA, Y compute from 3D points\n                bb3d_out(0) = tfinal[0];\n                bb3d_out(1) = min_y + (max_y - min_y) / 2.0;\n                bb3d_out(2) = tfinal[1];\n\n                // Width, height, depth\n                bb3d_out(3) = std::abs(bb1);\n                bb3d_out(4) = std::abs(cloud_height);\n                bb3d_out(5) = std::abs(bb3);\n\n                // Quaternion, representing orientation\n                //qfinal.setIdentity();\n                bb3d_out(6) = qfinal.w();\n                bb3d_out(7) = qfinal.x();\n                bb3d_out(8) = qfinal.y();\n                bb3d_out(9) = qfinal.z();\n\n                return bb3d_out;\n            }\n\n            Eigen::VectorXd BoundingBox3d(pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr scene_cloud,\n                                          const std::vector<int> &indices, double percentage) {\n                // Remove some points (radius-based cleaning)\n                auto filtered_indices = SUN::utils::filter::FilterPointCloudBasedOnRadius(scene_cloud, indices, percentage);\n\n                // Compute mean, covariance matrix 3d\n                Eigen::Matrix3d cov_mat3d;\n                Eigen::Vector4d mean3d;\n                pcl::computeMeanAndCovarianceMatrix(*scene_cloud, indices, cov_mat3d, mean3d);\n\n                // Let's restrict ourselves to 2D ground-plane projection. More robust.\n                Eigen::Matrix2d cov_mat2d;\n                cov_mat2d(0, 0) = cov_mat3d(0, 0);\n                cov_mat2d(1, 1) = cov_mat3d(2, 2);\n                cov_mat2d(0, 1) = cov_mat2d(1, 0) = cov_mat3d(0, 2);\n\n                // Compute Eigen vectors, values..\n                // Here, we get 2 eigenvectors, corresponding to dominant axes of 2D proj. of object (to the ground plane).\n                Eigen::SelfAdjointEigenSolver<Eigen::Matrix2d> eigen_solver(cov_mat2d, Eigen::ComputeEigenvectors);\n                Eigen::Matrix2d eigen_vectors = eigen_solver.eigenvectors();\n\n                // Def. local coord. sys.\n                Eigen::Matrix3d p2w(Eigen::Matrix3d::Identity());\n                p2w.block<2, 2>(0, 0) = eigen_vectors.transpose();\n                Eigen::Vector2d c_2d(mean3d[0], mean3d[2]); // Mean on gp. proj.\n                p2w.block<2, 1>(0, 2) = -1.f * (p2w.block<2, 2>(0, 0) * c_2d); //centroid.head<2>());\n\n                // Find bbox extent (width, depth)\n                float bbx_min = 1e10;\n                float bbx_max = -1e10;\n                float bbz_min = 1e10;\n                float bbz_max = -1e10;\n\n                for (int i = 0; i < filtered_indices.indices.size(); i++) {\n                    int ind = filtered_indices.indices.at(i);\n                    const auto &p_ref = scene_cloud->at(ind);\n\n                    if (std::isnan(p_ref.x))\n                        continue;\n\n                    Eigen::Vector3d p_eig(p_ref.x, p_ref.z, 1.0);\n                    p_eig = p2w * p_eig;\n\n                    const double tmp_x = p_eig[0];\n                    const double tmp_z = p_eig[1];\n\n                    if (tmp_x < bbx_min)\n                        bbx_min = tmp_x;\n                    if (tmp_x > bbx_max)\n                        bbx_max = tmp_x;\n                    if (tmp_z < bbz_min)\n                        bbz_min = tmp_z;\n                    if (tmp_z > bbz_max)\n                        bbz_max = tmp_z;\n                }\n\n                // Find out orientation\n                Eigen::Matrix3d R_mat;\n                R_mat.setIdentity();\n                R_mat(0, 0) = eigen_vectors(0, 0);\n                R_mat(0, 2) = eigen_vectors(0, 1);\n                R_mat(2, 0) = eigen_vectors(1, 0);\n                R_mat(2, 2) = eigen_vectors(1, 1);\n                const Eigen::Vector2d mean_diag = 0.5f * (Eigen::Vector2d(bbx_min + bbx_max, bbz_min + bbz_max));\n                const Eigen::Vector2d tfinal = eigen_vectors * mean_diag + Eigen::Vector2d(mean3d[0], mean3d[2]);\n\n                // Final transform\n                const Eigen::Quaterniond qfinal(R_mat);\n                double bb1 = bbx_max - bbx_min;\n                double bb3 = bbz_max - bbz_min;\n\n                // Get height\n                Eigen::Vector4f cloud_min, cloud_max;\n                pcl::getMinMax3D(*scene_cloud, filtered_indices, cloud_min, cloud_max);\n                double min_y = cloud_min[1];\n                double max_y = cloud_max[1];\n                double cloud_height = std::abs(max_y - min_y); // Difference between Y-coords.\n\n                // Resulting data structure\n                Eigen::VectorXd bb3d_out;\n                bb3d_out.setZero(10, 1); // center_x, center_y, center_z, width, height, depth, quaternion\n\n                // X-Z center from 2d-gp-PCA, Y compute from 3D points\n                bb3d_out(0) = tfinal[0];\n                bb3d_out(1) = min_y + (max_y - min_y) / 2.0;\n                bb3d_out(2) = tfinal[1];\n\n                // Width, height, depth\n                bb3d_out(3) = std::abs(bb1);\n                bb3d_out(4) = std::abs(cloud_height);\n                bb3d_out(5) = std::abs(bb3);\n\n                // Quaternion, representing orientation\n                bb3d_out(6) = qfinal.w();\n                bb3d_out(7) = qfinal.x();\n                bb3d_out(8) = qfinal.y();\n                bb3d_out(9) = qfinal.z();\n\n                return bb3d_out;\n            }\n\n            Eigen::Vector4d ReparametrizeBoundingBoxCenterMidToLeftTopPoint(const Eigen::Vector4d &bounding_box_2d) {\n                auto cx = bounding_box_2d[0];\n                auto cy = bounding_box_2d[1];\n                auto w = bounding_box_2d[2];\n                auto h = bounding_box_2d[3];\n                return Eigen::Vector4d(cx - (w / 2.0), cy - (h / 2.0), w, h);\n            }\n\n            Eigen::Vector4d ReparametrizeBoundingBoxCenterTopToLeftTopPoint(const Eigen::Vector4d &bounding_box_2d) {\n                auto cx = bounding_box_2d[0];\n                auto cy = bounding_box_2d[1];\n                auto w = bounding_box_2d[2];\n                auto h = bounding_box_2d[3];\n                return Eigen::Vector4d(cx - (w / 2.0), cy, w, h);\n            }\n        }\n    }\n}", "meta": {"hexsha": "523ebf1c633e5a8712b5f5aed1d3ad0932e37b04", "size": 15958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sun_utils/utils_bounding_box.cpp", "max_stars_repo_name": "glc12125/ciwt", "max_stars_repo_head_hexsha": "fb56e43cdfb0856c4609c33cd12905185d42a6e4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 88.0, "max_stars_repo_stars_event_min_datetime": "2017-05-30T08:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T04:11:25.000Z", "max_issues_repo_path": "src/sun_utils/utils_bounding_box.cpp", "max_issues_repo_name": "glc12125/ciwt", "max_issues_repo_head_hexsha": "fb56e43cdfb0856c4609c33cd12905185d42a6e4", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-07-28T02:43:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-12T03:35:54.000Z", "max_forks_repo_path": "src/sun_utils/utils_bounding_box.cpp", "max_forks_repo_name": "glc12125/ciwt", "max_forks_repo_head_hexsha": "fb56e43cdfb0856c4609c33cd12905185d42a6e4", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2017-07-23T06:58:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T13:59:17.000Z", "avg_line_length": 44.2049861496, "max_line_length": 152, "alphanum_fraction": 0.521807244, "num_tokens": 4045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4227638035873632}}
{"text": "/*\n * WaveEquationAdjoint.cpp\n *\n *  Created on: 17.07.2017\n *      Author: thies\n */\n\n/*\n * based on WaveEquation.cpp\n */\n\n#include <deal.II/base/exceptions.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/thread_management.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/base/types.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/identity_matrix.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/solver_control.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <forward/WaveEquationAdjoint.h>\n#include <forward/WaveEquation.h>\n\n#include <stddef.h>\n#include <iostream>\n#include <map>\n#include <string>\n\nnamespace wavepi {\nnamespace forward {\nusing namespace dealii;\nusing namespace wavepi::base;\n\ntemplate<int dim>\nWaveEquationAdjoint<dim>::WaveEquationAdjoint(std::shared_ptr<SpaceTimeMesh<dim>> mesh)\n      : AbstractEquationAdjoint<dim>(mesh), zero(std::make_shared<Functions::ZeroFunction<dim>>(1)) {\n}\n\ntemplate<int dim>\nWaveEquationAdjoint<dim>::WaveEquationAdjoint(const WaveEquation<dim> &wave)\n      : AbstractEquationAdjoint<dim>(wave.get_mesh()), zero(std::make_shared<Functions::ZeroFunction<dim>>(1)) {\n\n   this->set_param_c(wave.get_param_c());\n   this->set_param_nu(wave.get_param_nu());\n   this->set_param_rho(wave.get_param_rho());\n   this->set_param_q(wave.get_param_q());\n   this->set_rho_time_dependent(wave.is_rho_time_dependent());\n\n   this->set_theta(wave.get_theta());\n   this->set_solver_tolerance(wave.get_solver_tolerance());\n   this->set_solver_max_iter(wave.get_solver_max_iter());\n}\n\ntemplate<int dim>\nvoid WaveEquationAdjoint<dim>::assemble_matrices(size_t time_idx) {\n   LogStream::Prefix p(\"assemble_matrices\");\n\n   this->fill_matrices(mesh, time_idx, matrix_A, matrix_B, matrix_C);\n}\n\ntemplate<int dim>\nvoid WaveEquationAdjoint<dim>::apply_boundary_conditions_u(double time __attribute ((unused))) {\n   std::map<types::global_dof_index, double> boundary_values;\n   VectorTools::interpolate_boundary_values(*dof_handler, 0, *this->zero, boundary_values);\n   MatrixTools::apply_boundary_values(boundary_values, system_matrix, solution_u, system_rhs_u);\n}\n\ntemplate<int dim>\nvoid WaveEquationAdjoint<dim>::apply_boundary_conditions_v(double time __attribute ((unused))) {\n   std::map<types::global_dof_index, double> boundary_values;\n   VectorTools::interpolate_boundary_values(*dof_handler, 0, *this->zero, boundary_values);\n   MatrixTools::apply_boundary_values(boundary_values, system_matrix, solution_v, system_rhs_v);\n}\n\ntemplate class WaveEquationAdjoint<1> ;\ntemplate class WaveEquationAdjoint<2> ;\ntemplate class WaveEquationAdjoint<3> ;\n\n} /* namespace forward */\n} /* namespace wavepi */\n", "meta": {"hexsha": "3166ce884716152524507e74925127b9e6179886", "size": 2844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/forward/WaveEquationAdjoint.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/forward/WaveEquationAdjoint.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/forward/WaveEquationAdjoint.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6896551724, "max_line_length": 112, "alphanum_fraction": 0.7651195499, "num_tokens": 733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754471, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4227638035873631}}
{"text": "#include \"Formatings.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <datas/sensor_data.hpp>\n#include <vector>\n#include <cmath>\n#include \"Geometrie.h\"\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n\nfloat compute_value(laser_4m_record m1, int i, double limit){\n  if(0.02<m1.data[i].dist<limit){\n    return m1.data[i].dist;\n  }\n  if (0.02<m1.data[i-1].dist<limit && 0.02<m1.data[i+1].dist<limit){\n    return (m1.data[i-1].dist+m1.data[i+1].dist)/2;\n  }\n  //si on arrive ici (m1[1] >= limite && (m1[i+1]>=limite || m1[i-1]>=limite)\n  //Sois les trois mesures sont a la limite sois une seul ne l'est pas (elle deviendra la \"mesure reel\")\n  if(m1.data[i-1].dist<m1.data[i+1].dist && m1.data[i-1].dist>0.02){\n    return m1.data[i-1].dist;\n  }\n  return m1.data[i+1].dist>0.02?m1.data[i+1].dist:m1.data[i].dist;\n}\n\nstd::vector<struct polar_coordinate> format_Telemetre(polar_coordinate Values[], int length, float offsetX, float offsetY, float offsetTheta){\n  double Xstart,Xend,Ystart,Yend;\n  polar_coordinate tmpres={{0,0,0},0};\n  std::vector<struct polar_coordinate> Res;\n  for(int i=0;i<length;i++){\n    Xstart=Values[i].dist*cos(Values[i].dir.theta);\n    Ystart=Values[i].dist*sin(Values[i].dir.theta);\n    Xend=cos(offsetTheta)*Xstart+sin(offsetTheta)*Ystart+offsetX;\n    Yend=-1*sin(offsetTheta)*Xstart+cos(offsetTheta)*Ystart+offsetY;\n    tmpres.dist=sqrt(Xend*Xend+Yend*Yend);\n    tmpres.dir.theta=atan2(Yend,Xend);\n    Res.push_back(tmpres);\n  }\n  return Res;\n}\n\nstd::vector<struct polar_coordinate> format_US(double US[]){\n  std::vector<struct polar_coordinate> Res;\n  double Xstart,Xend,Ystart,Yend;\n  eucclid_coordinate Relevee={0,0,0};\n  polar_coordinate tmpres={{0,0,0},0};\n  double Pas=(20*2*M_PI)/360;\n  double Tright=-1*M_PI;\n  double Tleft=M_PI;\n  double Thetas_Deg_US[]={90,50,30,10,-10,-30,-50,-90,-90,-130,-150,-170,170,150,130,90};\n//  double Thetas_US[16]={Tright,Tright+Pas,Tright+2*Pas,Tright+3*Pas,Tright+4*Pas,Tright+5*Pas,Tright+6*Pas,Tleft,Tleft,Tleft+Pas,Tleft+2*Pas,Tleft+3*Pas,Tleft+4*Pas,Tleft+5*Pas,Tleft+6*Pas,Tleft+7*Pas,Tright};\n  for(int i=0;i<16;i++){\n    tmpres.dist=US[i]+0.1;//Aproximation\n    tmpres.dir.theta=(Thetas_Deg_US[i]/180)*M_PI;\n    Relevee=ConvPolToEuclide(tmpres);\n    if(i<8){//US Front\n      //LES US se \"rejoignes\" environ 8CM en avant des roues.\n      Relevee.x=Relevee.x+0.08;\n    }else{//US rear\n      //LES US se \"rejoignes\" environ 16CM en arrière des roues.\n      Relevee.x=Relevee.x-0.16;\n    }\n    tmpres=ConvEuclideToPol(Relevee);\n    Res.push_back(tmpres);\n  }\n  return Res;\n}\n\n\nstd::vector<pfoa::waypoint> format_Path(std::vector<struct eucclid_coordinate> Points){\n  double dist=0;\n  std::vector<pfoa::waypoint> Path;\n  eucclid_coordinate lastPoint=Points[0];\n  for(int i=0;i<Points.size();i++){\n    dist=dist+sqrt(pow(lastPoint.x-Points[i].x,2)+pow(lastPoint.y-Points[i].y,2));\n    Path.push_back({Points[i].x,Points[i].y,dist});\n    lastPoint=Points[i];\n  }\n}\n\nvoid Recomput_Weeldist(euclid_position Oldstate,euclid_position R_state, double &ssg, double &ssd){\n  double L=ENTRE_ROUE;\n  float dx=R_state.pos.x-Oldstate.pos.x;\n  float dy=R_state.pos.y-Oldstate.pos.y;\n  float dt=R_state.dir.theta-Oldstate.dir.theta;\n  float ds=sqrt(pow(dx,2)+pow(dy,2));\n  ssg=(ds-(dt*L)/2);\n  ssd=(dt*L)+ssg;\n}\n\nvoid SimuOdo(euclid_position Oldstate,euclid_position &R_state, double DistRG, double DistRD){\n  double L=ENTRE_ROUE;\n  float ds = (DistRG + DistRD)/2;\n  float dt = (DistRD-DistRG)/L;\n  R_state.pos.x=Oldstate.pos.x+ds*cos(Oldstate.dir.theta+dt/2);\n  R_state.pos.y=Oldstate.pos.y+ds*sin(Oldstate.dir.theta+dt/2);\n  R_state.dir.theta=Oldstate.dir.theta+dt;\n}\n\nvoid compute_Fenetre_Error_Odo(euclid_position R_state, double distLeft, double distRight, Eigen::MatrixXd &P, double &x1, double &x2, double &y1, double &y2, double &t1, double &t2){\n  Eigen::MatrixXd OdoCov(2,2);\n  OdoCov<< 0.001780754260856,0,0,0.001691065861758;\n  Eigen::MatrixXd OdoCovtmp(2,2);\n  Eigen::MatrixXd Dist(2,2);\n  Dist<< 1.0,0.0,0.0,1.0;\n  Eigen::MatrixXd Jacobrob(3,3);\n  Jacobrob << 1,0,0,0,1,0,0,0,1;\n  Eigen::MatrixXd Jacobdist(3,2);\n  Eigen::MatrixXd Pstart(3,3);\n  Pstart=P;\n\n  double Lodo=ENTRE_ROUE;\n  double ds,dt;\n  double demicos,demisin;\n  int iex, iey, iet;\n  double Ex, Ey, OrientEy, ExSim, EySim, OrientEySim;\n  double ext1, ext2, eyt1, eyt2;\n  euclid_position OdoEstime;\n\n  //Compute odometries errors.\n  Dist(0,0)=distRight;\n  Dist(1,1)=distLeft;\n  OdoCovtmp = OdoCov*Dist;\n  ds=(distRight+distLeft)/2;\n  dt=(distRight-distLeft)/Lodo;\n  Jacobrob(0,2)=-1*ds*sin(R_state.dir.theta+dt/2);\n  Jacobrob(1,2)=ds*cos(R_state.dir.theta+dt/2);\n\n  demicos=(cos(R_state.dir.theta+dt/2))/2;\n  demisin=(sin(R_state.dir.theta+dt/2))/2;\n\n  Jacobdist(0,0)=demicos-(ds/Lodo)*demisin;\n  Jacobdist(0,1)=demicos+(ds/Lodo)*demisin;\n  Jacobdist(1,0)=demisin+(ds/Lodo)*demicos;\n  Jacobdist(1,1)=demisin-(ds/Lodo)*demicos;\n  Jacobdist(2,0)=1/Lodo;\n  Jacobdist(2,1)=-1/Lodo;\n\n  P=Jacobrob*Pstart*Jacobrob.transpose()+Jacobdist*OdoCovtmp*Jacobdist.transpose();\n\n  Eigen::EigenSolver<Eigen::MatrixXd> VecpropSolvP(P);\n  Eigen::MatrixXd ValsProps=VecpropSolvP.pseudoEigenvalueMatrix();\n  Eigen::MatrixXd VecsProps=VecpropSolvP.pseudoEigenvectors();\n  //Ey = val prop la plus grande puis Ex puis Et\n\n  if(ValsProps(0,0)>ValsProps(1,1)){//0 sup a 1\n    if(ValsProps(2,2)>ValsProps(0,0)){//2-0-1\n      iex = 0;\n      iey = 2;\n      iet = 1;\n    }\n    else if(ValsProps(2,2)>ValsProps(1,1)){//0-2-1\n      iex = 2;\n      iey = 0;\n      iet = 1;\n    }else{//0-1-2\n      iex = 1;\n      iey = 0;\n      iet = 2;\n    }\n  }else{//1 sup a 0\n    if(ValsProps(2,2)>ValsProps(1,1)){//2-1-0\n      iex = 1;\n      iey = 2;\n      iet = 0;\n    }\n    else if(ValsProps(2,2)>ValsProps(0,0)){//1-2-0\n      iex = 2;\n      iey = 1;\n      iet = 0;\n    }else{//1-0-2\n      iex = 0;\n      iey = 1;\n      iet = 2;\n    }\n  }\n  Ex = pow(ValsProps(iex,iex),(1/3.0));\n  Ey = pow(ValsProps(iey,iey),(1/3.0));\n  OrientEy = atan2(VecsProps(1,iey),VecsProps(2,iey));\n  SimuOdo(R_state,OdoEstime,distLeft,distRight);\n  ext1=abs(Ex*cos(R_state.dir.theta+OrientEy-M_PI/2));\n  eyt1=abs(Ex*sin(R_state.dir.theta+OrientEy-M_PI/2));\n  ext2=abs(Ey*cos(R_state.dir.theta+OrientEy));\n  eyt2=abs(Ey*sin(R_state.dir.theta+OrientEy));\n//  ext1=max(ext1,ext2);\n  if(ext2>ext1){\n    ext1=ext2;\n  }\n//  eyt1=max(eyt1,eyt2);\n  if(eyt2>eyt1){\n    eyt1=eyt2;\n  }\n  x1=OdoEstime.pos.x+ext1;\n  x2=OdoEstime.pos.x-ext1;\n  y1=OdoEstime.pos.y+eyt1;\n  y2=OdoEstime.pos.y-eyt1;\n  t2=R_state.dir.theta+dt-pow(fabs(ValsProps(iet,iet)),(1/3.0));\n  t1=R_state.dir.theta+dt+pow(fabs(ValsProps(iet,iet)),(1/3.0));\n\n}\n\n\nvoid compute_Fenetre_Error_Odo_Rob(euclid_position R_state, double distLeft, double distRight, Eigen::MatrixXd &P, eucclid_coordinate &PEShort,eucclid_coordinate &PELong){\n  /*Renvois les coordonees des points des axes representant l'elipse d'incertitude.*/\n  Eigen::MatrixXd OdoCov(2,2);\n  OdoCov<< 0.001780754260856,0,0,0.001691065861758;\n  Eigen::MatrixXd OdoCovtmp(2,2);\n  Eigen::MatrixXd Dist(2,2);\n  Dist<< 1.0,0.0,0.0,1.0;\n  Eigen::MatrixXd Jacobrob(3,3);\n  Jacobrob << 1,0,0,0,1,0,0,0,1;\n  Eigen::MatrixXd Jacobdist(3,2);\n  Eigen::MatrixXd Pstart(3,3);\n  Pstart=P;\n\n  double Lodo=ENTRE_ROUE;\n  double ds,dt;\n  double demicos,demisin;\n  int iex, iey, iet;\n  double Ex, Ey, OrientEy, ExSim, EySim, OrientEySim;\n  double ext1, ext2, eyt1, eyt2;\n  euclid_position OdoEstime;\n\n  //Compute odometries errors.\n  Dist(0,0)=distRight;\n  Dist(1,1)=distLeft;\n  OdoCovtmp = OdoCov*Dist;\n  ds=(distRight+distLeft)/2;\n  dt=(distRight-distLeft)/Lodo;\n  Jacobrob(0,2)=-1*ds*sin(R_state.dir.theta+dt/2);\n  Jacobrob(1,2)=ds*cos(R_state.dir.theta+dt/2);\n\n  demicos=(cos(R_state.dir.theta+dt/2))/2;\n  demisin=(sin(R_state.dir.theta+dt/2))/2;\n\n  Jacobdist(0,0)=demicos-(ds/Lodo)*demisin;\n  Jacobdist(0,1)=demicos+(ds/Lodo)*demisin;\n  Jacobdist(1,0)=demisin+(ds/Lodo)*demicos;\n  Jacobdist(1,1)=demisin-(ds/Lodo)*demicos;\n  Jacobdist(2,0)=1/Lodo;\n  Jacobdist(2,1)=-1/Lodo;\n\n  P=Jacobrob*Pstart*Jacobrob.transpose()+Jacobdist*OdoCovtmp*Jacobdist.transpose();\n\n  Eigen::EigenSolver<Eigen::MatrixXd> VecpropSolvP(P);\n  Eigen::MatrixXd ValsProps=VecpropSolvP.pseudoEigenvalueMatrix();\n  Eigen::MatrixXd VecsProps=VecpropSolvP.pseudoEigenvectors();\n  //Ey = val prop la plus grande puis Ex puis Et\n\n  if(ValsProps(0,0)>ValsProps(1,1)){//0 sup a 1\n    if(ValsProps(2,2)>ValsProps(0,0)){//2-0-1\n      iex = 0;\n      iey = 2;\n      iet = 1;\n    }\n    else if(ValsProps(2,2)>ValsProps(1,1)){//0-2-1\n      iex = 2;\n      iey = 0;\n      iet = 1;\n    }else{//0-1-2\n      iex = 1;\n      iey = 0;\n      iet = 2;\n    }\n  }else{//1 sup a 0\n    if(ValsProps(2,2)>ValsProps(1,1)){//2-1-0\n      iex = 1;\n      iey = 2;\n      iet = 0;\n    }\n    else if(ValsProps(2,2)>ValsProps(0,0)){//1-2-0\n      iex = 2;\n      iey = 1;\n      iet = 0;\n    }else{//1-0-2\n      iex = 0;\n      iey = 1;\n      iet = 2;\n    }\n  }\n  Ex = pow(ValsProps(iex,iex),(1/3.0));\n  Ey = pow(ValsProps(iey,iey),(1/3.0));\n  OrientEy = atan2(VecsProps(1,iey),VecsProps(2,iey));\n//  SimuOdo(R_state,OdoEstime,distLeft,distRight);\n  ext1=abs(Ex*cos(OrientEy-M_PI/2));\n  eyt1=abs(Ex*sin(OrientEy-M_PI/2));\n  ext2=abs(Ey*cos(OrientEy));\n  eyt2=abs(Ey*sin(OrientEy));\n\n  PEShort.x=ext1;\n  PEShort.y=ext1;\n//  PEShort.theta=R_state.dir.theta+dt-pow(ValsProps(iet,iet),(1/3.0));\n  PELong.x=ext2;\n  PELong.y=ext2;\n//  PELong.theta=R_state.dir.theta+dt+pow(ValsProps(iet,iet),(1/3.0));\n\n}\n\n\ndouble Compute_ThetaCompas(std::vector<polar_coordinate> Telemetrie, euclid_position Odom){\n  std::vector<polar_coordinate> Tmp_telemetries;\n  std::vector<int> iRans;\n  std::vector<double> As, difAs;\n  std::vector<double> WAs, WdifAs;\n\n  double Coridor_orient[][5]={{4.88,26.38,-1,2.5,0},{23,30,2.88,50.88,M_PI/2}};\n  int Coridor_Num=2;\n  int RoboDir, PresentCoridor;\n  int ifind;\n  double awall, bwall, Angletmp;\n  double Angle_Compas;\n  struct polar_coordinate P1,P2;\n  iRans.clear();\n  As.clear();\n  WAs.clear();\n  awall=2000;\n  Angle_Compas=999;\n\n  //Retrais des points pouvant être trop eloignee\n  for(int i=0; i<Telemetrie.size(); i++){\n    if(Telemetrie[i].dist<3.5 && Telemetrie[i].dist>0.05){\n      Tmp_telemetries.push_back(Telemetrie[i]);\n    }\n  }\n  //Recuperation de l'orientation principale a cet endroit dans le reper monde.\n  PresentCoridor=-1;\n  RoboDir=-1;\n  for(int i=0; i<Coridor_Num; i++){\n    //Si l'odometrie se pense dans une zone d'un couloir\n    if(Odom.pos.x>Coridor_orient[i][0] && Odom.pos.x<Coridor_orient[i][1] && Odom.pos.y>Coridor_orient[i][2] && Odom.pos.y<Coridor_orient[i][3]){\n      PresentCoridor=i;\n      break;\n    }\n  }\n/*\n  std::cout << \"Present Coridor = \"<< PresentCoridor  << '\\n';\n  std::cout << \"Info Coridor = \"<< Coridor_orient[PresentCoridor][4] << \" - Odo theta = \"<< Odom.dir.theta << '\\n';\n  std::cout << \" - Fabs observe => \"<< fabs(Coridor_orient[PresentCoridor][4]-Odom.dir.theta) << '\\n';/**/\n  //On determine le sens de deplacement du robot.\n  if(PresentCoridor!=-1){\n    if(fabs(Coridor_orient[PresentCoridor][4]-Odom.dir.theta)<4*M_PI/12){//Retour\n      RoboDir=1;\n    }\n    if(fabs(Coridor_orient[PresentCoridor][4]-Odom.dir.theta)>8*M_PI/12){//Aller\n      RoboDir=2;\n    }\n  }\n//  std::cout << \"ROBODIR = \"<< RoboDir << '\\n';\n  if(Telemetrie.size()!=0 && RoboDir!=-1){\n    while(As.size()<5 && Tmp_telemetries.size()>Telemetrie.size()*0.1){\n      for(int i=0; i<iRans.size(); i++){\n        ifind=iRans.size()-1-i;\n        Tmp_telemetries.erase(Tmp_telemetries.begin()+iRans[ifind]);\n      }\n      iRans=ransaclignefrompole(Tmp_telemetries, awall, bwall, 0.01, P1, P2);\n      As.push_back(awall);\n      WAs.push_back(iRans.size());\n//      std::cout << \"New A = \"<< awall << \" - Poid = \"<< iRans.size() << '\\n';\n    }\n    difAs.clear();\n    WdifAs.clear();\n    //On met la plus grosse ligne en premier parmis les possibilités.\n    difAs.push_back(As[0]);\n    WdifAs.push_back(WAs[0]);\n    for(int i=1; i<As.size(); i++){\n      awall=0;\n      for(int j=0; i<difAs.size(); j++){\n        Angletmp=fabs(atan2(difAs[j],1)-atan2(As[i],1));\n        while(Angletmp>=M_PI){\n          Angletmp=Angletmp-M_PI;\n        }\n        if(Angletmp<M_PI/6 && Angletmp>5*M_PI/6){//Le mur est paralèle a +/-pi/4\n          WdifAs[j]=WdifAs[j]+WAs[i];\n          awall=1;\n          break;\n        }\n      }\n      if(awall!=1){//Pas de droite \"paralèle\" trouvé. on cré un nouveau groupe. avec la droite ayant le plus de \"membres\"\n        difAs.push_back(As[i]);\n        WdifAs.push_back(WAs[i]);\n      }\n    }\n    //Recuperation de l'orientation dont le poid des paralèle est le plus important\n    bwall=0;\n    for(int i=0; i<WdifAs.size(); i++){\n      if(WdifAs[i]>bwall){\n        bwall=WdifAs[i];\n        awall=difAs[i];\n      }\n    }\n//    std::cout << \"awall = \"<< awall<< \" - Atan awall = \"<< atan2(awall,1) << '\\n';\n    if(RoboDir==1){ //retour\n      Angle_Compas=-1*(atan2(awall,1))+Coridor_orient[PresentCoridor][4];\n    }\n    if(RoboDir==2){ //aller\n      Angle_Compas=-1*(atan2(awall,1))+(Coridor_orient[PresentCoridor][4]-M_PI);\n    }\n  }\n  return Angle_Compas;\n}\n\nstd::vector<double> Iadd(std::vector<double> ia, std::vector<double>ib){\n  std::vector<double> res;\n  if (IisEmpty(ia)){\n    return res;\n  }\n  if (IisEmpty(ib)){\n    return res;\n  }\n  double mina, maxa, minb, maxb;\n  mina=*min_element(ia.begin(), ia.end());\n  maxa=*max_element(ia.begin(), ia.end());\n  minb=*min_element(ib.begin(), ib.end());\n  maxb=*max_element(ib.begin(), ib.end());\n  res.reserve(2);\n  res.push_back(mina+minb);\n  res.push_back(maxa+maxb);\n  return res;\n}\nstd::vector<double> Isub(std::vector<double> ia, std::vector<double>ib){\n    std::vector<double> res;\n    if (IisEmpty(ia)){\n      return res;\n    }\n    if (IisEmpty(ib)){\n      return res;\n    }\n    double mina, maxa, minb, maxb;\n    mina=*min_element(ia.begin(), ia.end());\n    maxa=*max_element(ia.begin(), ia.end());\n    minb=*min_element(ib.begin(), ib.end());\n    maxb=*max_element(ib.begin(), ib.end());\n    res.reserve(2);\n    res.push_back(mina-maxb);\n    res.push_back(maxa-minb);\n    return res;\n}\nstd::vector<double> Imul(std::vector<double> ia, std::vector<double>ib){\n  std::vector<double> res;\n  if (IisEmpty(ia)){\n    return res;\n  }\n  if (IisEmpty(ib)){\n    return res;\n  }\n  std::vector<double> tmp(4);\n  double mina, maxa, minb, maxb;\n  mina=*min_element(ia.begin(), ia.end());\n  maxa=*max_element(ia.begin(), ia.end());\n  minb=*min_element(ib.begin(), ib.end());\n  maxb=*max_element(ib.begin(), ib.end());\n  tmp[0]=mina*minb;\n  tmp[1]=mina*maxb;\n  tmp[2]=maxa*minb;\n  tmp[3]=maxa*maxb;\n  res.reserve(2);\n  res.push_back(*min_element(tmp.begin(), tmp.end()));\n  res.push_back(*max_element(tmp.begin(), tmp.end()));\n  return res;\n}\nstd::vector<double> Icos(std::vector<double> ia){\n  std::vector<double> res, tmp(2);\n  if (IisEmpty(ia)){\n    return res;\n  }\n  double mina, maxa, minb, maxb;\n  tmp[0]=*min_element(ia.begin(), ia.end())+M_PI/2;\n  tmp[1]=*max_element(ia.begin(), ia.end())+M_PI/2;\n  res=Isin(tmp);\n  return res;\n}\nstd::vector<double> Isin(std::vector<double> ia){\n  std::vector<double> res,tmp(2),rtmp,Snum(1);\n  if (IisEmpty(ia)){\n    return res;\n  }\n  double mina, maxa, minb, maxb;\n  tmp[0]=*min_element(ia.begin(), ia.end());\n  tmp[1]=*max_element(ia.begin(), ia.end());\n  if(Ilength(tmp)>2*M_PI){\n    res.reserve(2);\n    res.push_back(-1);\n    res.push_back(1);\n    return res;\n  }\n  while(tmp[1]>2*M_PI){\n    tmp[0]=tmp[0]-2*M_PI;\n    tmp[1]=tmp[1]-2*M_PI;\n  }\n  while(tmp[0]<0){\n    tmp[0]=tmp[0]+2*M_PI;\n    tmp[1]=tmp[1]+2*M_PI;\n  }\n  rtmp.push_back(sin(tmp[0]));\n  rtmp.push_back(sin(tmp[1]));\n  Snum[0]=M_PI/2;\n  if(Iin(Snum,tmp)==true){\n    rtmp.push_back(1);\n  }\n  Snum[0]=3*M_PI/2;\n  if(Iin(Snum,tmp)==true){\n    rtmp.push_back(-1);\n  }\n  res.reserve(2);\n  res.push_back(*min_element(rtmp.begin(), rtmp.end()));\n  res.push_back(*max_element(rtmp.begin(), rtmp.end()));\n  return res;\n}\n\ndouble Imid(std::vector<double> ia){\n    double res;\n    double mina, maxa;\n    mina=*min_element(ia.begin(), ia.end());\n    maxa=*max_element(ia.begin(), ia.end());\n    res=mina+(maxa-mina)/2;\n    return res;\n}\n\ndouble Ilength(std::vector<double> ia){\n  double res;\n  double mina, maxa;\n  if (IisEmpty(ia)){\n    return -1;\n  }\n  mina=*min_element(ia.begin(), ia.end());\n  maxa=*max_element(ia.begin(), ia.end());\n  res=maxa-mina;\n  return res;\n}\n\nbool Iin(std::vector<double> ia,std::vector<double> ib){\n  if (IisEmpty(ia)||IisEmpty(ib)){\n    return false;\n  }\n  double mina, maxa, minb, maxb;\n  mina=*min_element(ia.begin(), ia.end());\n  maxa=*max_element(ia.begin(), ia.end());\n  minb=*min_element(ib.begin(), ib.end());\n  maxb=*max_element(ib.begin(), ib.end());\n  return ((mina>=minb)&&(maxa<=maxb));\n}\n\nvoid IVals(std::vector<double> ia,double &min, double &max){\n  if (IisEmpty(ia)){\n    return;\n  }\n  min=*min_element(ia.begin(), ia.end());\n  max=*max_element(ia.begin(), ia.end());\n  return;\n}\n\nstd::vector<double> initInterval(double a,double b){\n  std::vector<double> res={a,b};\n  return res;\n}\n\n\nstd::vector<double> Icentering(std::vector<double> ia){\n  std::vector<double> res;\n  if (IisEmpty(ia)){\n    return res;\n  }\n//  double mina, maxa, minb, maxb;\n  res.reserve(2);\n  res.push_back(*min_element(ia.begin(), ia.end())-Imid(ia));\n  res.push_back(*max_element(ia.begin(), ia.end())-Imid(ia));\n  return res;\n}\n\nstd::vector<double> Iintersec(std::vector<double> ia, std::vector<double>ib){\n  std::vector<double> res;\n  if (IisEmpty(ia)){\n    return res;\n  }\n  if (IisEmpty(ib)){\n    return res;\n  }\n  double mina, maxa, minb, maxb;\n  mina=*min_element(ia.begin(), ia.end());\n  maxa=*max_element(ia.begin(), ia.end());\n  minb=*min_element(ib.begin(), ib.end());\n  maxb=*max_element(ib.begin(), ib.end());\n  if(!(maxa < minb || mina > maxb)){\n    res.reserve(2);\n    res.push_back(mina*(mina>minb)+minb*!(mina>minb));\n    res.push_back(maxa*(maxa<maxb)+maxb*!(maxa<maxb));\n  }\n  return res;\n}\nstd::vector<double> Iunion(std::vector<double> ia, std::vector<double>ib){\n  std::vector<double> res;\n  double mina, maxa, minb, maxb;\n  if (IisEmpty(ia)){\n    return ib;\n  }\n  if (IisEmpty(ib)){\n    return ia;\n  }\n  mina=*min_element(ia.begin(), ia.end());\n  maxa=*max_element(ia.begin(), ia.end());\n  minb=*min_element(ib.begin(), ib.end());\n  maxb=*max_element(ib.begin(), ib.end());\n  res.reserve(2);\n  res.push_back(mina*(mina<minb)+minb*!(mina<minb));\n  res.push_back(maxa*(maxa>maxb)+maxb*!(maxa>maxb));\n  return res;\n}\n\nbool IisEmpty(std::vector<double> ia){\n  return ia.size()==0;\n}\n", "meta": {"hexsha": "924aa45373eccab29c558199fea35bcd89b0d15f", "size": 18415, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codeCpp/Formatings.cpp", "max_stars_repo_name": "benaliabderrahmane/-Localization-by-particle-filter--Off-line-and-Online-localization-performance-evaluation", "max_stars_repo_head_hexsha": "a5814359e3796b7f98be47e8ab22121131579ee0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-12T07:33:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T21:06:32.000Z", "max_issues_repo_path": "codeCpp/Formatings.cpp", "max_issues_repo_name": "benaliabderrahmane/-Localization-by-particle-filter--Off-line-and-Online-localization-performance-evaluation", "max_issues_repo_head_hexsha": "a5814359e3796b7f98be47e8ab22121131579ee0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codeCpp/Formatings.cpp", "max_forks_repo_name": "benaliabderrahmane/-Localization-by-particle-filter--Off-line-and-Online-localization-performance-evaluation", "max_forks_repo_head_hexsha": "a5814359e3796b7f98be47e8ab22121131579ee0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9918566775, "max_line_length": 211, "alphanum_fraction": 0.6389356503, "num_tokens": 6666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.422763797338406}}
{"text": "// Compile with:\n// emcc -I${BOOST} -I${QUANTLIB} -s BINARYEN_TRAP_MODE=clamp -o billiontrader-bootstrapping.js billiontrader-bootstrapping.cpp ${QUANTLIB}/ql/.libs/libQuantLib.a\n\n#include <ql/quantlib.hpp>\n\n#ifdef BOOST_MSVC\n/* Uncomment the following lines to unmask floating-point\nexceptions. Warning: unpredictable results can arise...\n\nSee http://www.wilmott.com/messageview.cfm?catid=10&threadid=9481\nIs there anyone with a definitive word about this?\n*/\n// #include <float.h>\n// namespace { unsigned int u = _controlfp(_EM_INEXACT, _MCW_EM); }\n#endif\n\n#include <ql/quantlib.hpp>\n//#include <boost/timer.hpp>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n\nusing namespace std;\nusing namespace QuantLib;\n\n#if defined(QL_ENABLE_SESSIONS)\nnamespace QuantLib\n{\n\nInteger sessionId() { return 0; }\n\n} // namespace QuantLib\n#endif\n\nusing namespace QuantLib;\n\nint main(int argc, char *argv[])\n{\n    Calendar calendar = JointCalendar(UnitedKingdom(UnitedKingdom::Exchange), UnitedStates(UnitedStates::Settlement), JoinHolidays);\n\n    Date settlementDate(18, February, 2015);\n    settlementDate = calendar.adjust(settlementDate);\n    // Due to Release 1.20 - October 26th, 2020: Improved calculation of spot date for vanilla swap around holidays (thanks to Paul Giltinan), \n    // the example no longer works with 2 spot days\n    Integer fixingDays = 0;\n    Date todaysDate = calendar.advance(settlementDate, -fixingDays, Days);\n    Settings::instance().evaluationDate() = todaysDate;\n    DayCounter depositDayCounter = Actual360();\n\n    Rate d1wQuote = 0.001375;\n    Rate d1mQuote = 0.001717;\n    Rate d2mQuote = 0.002112;\n    Rate d3mQuote = 0.002581;\n    boost::shared_ptr<Quote> d1wRate(new SimpleQuote(d1wQuote));\n    boost::shared_ptr<Quote> d1mRate(new SimpleQuote(d1mQuote));\n    boost::shared_ptr<Quote> d2mRate(new SimpleQuote(d2mQuote));\n    boost::shared_ptr<Quote> d3mRate(new SimpleQuote(d3mQuote));\n    boost::shared_ptr<RateHelper> d1w(new DepositRateHelper(Handle<Quote>(d1wRate), 7 * Days, fixingDays, calendar, ModifiedFollowing, true, depositDayCounter));\n    boost::shared_ptr<RateHelper> d1m(new DepositRateHelper(Handle<Quote>(d1mRate), 4 * Weeks, fixingDays, calendar, ModifiedFollowing, true, depositDayCounter));\n    boost::shared_ptr<RateHelper> d2m(new DepositRateHelper(Handle<Quote>(d2mRate), 2 * Months, fixingDays, calendar, ModifiedFollowing, true, depositDayCounter));\n    boost::shared_ptr<RateHelper> d3m(new DepositRateHelper(Handle<Quote>(d3mRate), 3 * Months, fixingDays, calendar, ModifiedFollowing, true, depositDayCounter));\n\n    DayCounter FutDayCounter = Actual360();\n    Real fut1Quote = 99.725; // 0.2750\n    Real fut2Quote = 99.585; // 0.4150\n    Real fut3Quote = 99.385; //0.6150\n    Real fut4Quote = 99.16;  // 0.84\n    Real fut5Quote = 98.93;  // 1.07\n    Real fut6Quote = 98.715; // 1.285\n    boost::shared_ptr<Quote> fut1Price(new SimpleQuote(fut1Quote));\n    boost::shared_ptr<Quote> fut2Price(new SimpleQuote(fut2Quote));\n    boost::shared_ptr<Quote> fut3Price(new SimpleQuote(fut3Quote));\n    boost::shared_ptr<Quote> fut4Price(new SimpleQuote(fut4Quote));\n    boost::shared_ptr<Quote> fut5Price(new SimpleQuote(fut5Quote));\n    boost::shared_ptr<Quote> fut6Price(new SimpleQuote(fut6Quote));\n    Integer futMonths = 3;\n\n    Date imm = IMM::nextDate(settlementDate);\n    boost::shared_ptr<RateHelper> fut1(new FuturesRateHelper(Handle<Quote>(fut1Price), imm, futMonths, calendar, ModifiedFollowing, true, depositDayCounter));\n    imm = IMM::nextDate(imm + 1);\n    boost::shared_ptr<RateHelper> fut2(new FuturesRateHelper(Handle<Quote>(fut2Price), imm, futMonths, calendar, ModifiedFollowing, true, depositDayCounter));\n    imm = IMM::nextDate(imm + 1);\n    boost::shared_ptr<RateHelper> fut3(new FuturesRateHelper(Handle<Quote>(fut3Price), imm, futMonths, calendar, ModifiedFollowing, true, depositDayCounter));\n    imm = IMM::nextDate(imm + 1);\n    boost::shared_ptr<RateHelper> fut4(new FuturesRateHelper(Handle<Quote>(fut4Price), imm, futMonths, calendar, ModifiedFollowing, true, depositDayCounter));\n\n    imm = IMM::nextDate(imm + 1);\n    boost::shared_ptr<RateHelper> fut5(new FuturesRateHelper(Handle<Quote>(fut5Price), imm, futMonths, calendar, ModifiedFollowing, true, depositDayCounter));\n    imm = IMM::nextDate(imm + 1);\n    boost::shared_ptr<RateHelper> fut6(new FuturesRateHelper(Handle<Quote>(fut6Price), imm, futMonths, calendar, ModifiedFollowing, true, depositDayCounter));\n\n    Rate s2yQuote = 0.0089268;\n    Rate s3yQuote = 0.0123343;\n    Rate s4yQuote = 0.0147985;\n    Rate s5yQuote = 0.0165843;\n    Rate s6yQuote = 0.0179191;\n    boost::shared_ptr<Quote> s2yRate(new SimpleQuote(s2yQuote));\n    boost::shared_ptr<Quote> s3yRate(new SimpleQuote(s3yQuote));\n    boost::shared_ptr<Quote> s4yRate(new SimpleQuote(s4yQuote));\n    boost::shared_ptr<Quote> s5yRate(new SimpleQuote(s5yQuote));\n    boost::shared_ptr<Quote> s6yRate(new SimpleQuote(s6yQuote));\n\n    Frequency swFixedLegFrequency = Annual;\n    BusinessDayConvention swFixedLegConvention = Unadjusted;\n    DayCounter swFixedLegDayCounter = Actual360();\n    boost::shared_ptr<IborIndex> swFloatingLegIndex(new USDLibor(Period(3, Months)));\n\n    boost::shared_ptr<RateHelper> s2y(new SwapRateHelper(\n        Handle<Quote>(s2yRate), 2 * Years,\n        calendar, swFixedLegFrequency,\n        swFixedLegConvention, swFixedLegDayCounter,\n        swFloatingLegIndex));\n    boost::shared_ptr<RateHelper> s3y(new SwapRateHelper(\n        Handle<Quote>(s3yRate), 3 * Years,\n        calendar, swFixedLegFrequency,\n        swFixedLegConvention, swFixedLegDayCounter,\n        swFloatingLegIndex));\n    boost::shared_ptr<RateHelper> s4y(new SwapRateHelper(\n        Handle<Quote>(s4yRate), 4 * Years,\n        calendar, swFixedLegFrequency,\n        swFixedLegConvention, swFixedLegDayCounter,\n        swFloatingLegIndex));\n    boost::shared_ptr<RateHelper> s5y(new SwapRateHelper(\n        Handle<Quote>(s5yRate), 5 * Years,\n        calendar, swFixedLegFrequency,\n        swFixedLegConvention, swFixedLegDayCounter,\n        swFloatingLegIndex));\n    boost::shared_ptr<RateHelper> s6y(new SwapRateHelper(\n        Handle<Quote>(s6yRate), 6 * Years,\n        calendar, swFixedLegFrequency,\n        swFixedLegConvention, swFixedLegDayCounter,\n        swFloatingLegIndex));\n\n    typedef boost::shared_ptr<RateHelper> SharedPtrRateHelper;\n    vector<SharedPtrRateHelper> depoFutSwapInstruments;\n    depoFutSwapInstruments.push_back(d1w);\n    depoFutSwapInstruments.push_back(d1m);\n    depoFutSwapInstruments.push_back(d2m);\n    depoFutSwapInstruments.push_back(d3m);\n    depoFutSwapInstruments.push_back(fut1);\n    depoFutSwapInstruments.push_back(fut2);\n    depoFutSwapInstruments.push_back(fut3);\n    depoFutSwapInstruments.push_back(fut4);\n    depoFutSwapInstruments.push_back(fut5);\n    depoFutSwapInstruments.push_back(fut6);\n    depoFutSwapInstruments.push_back(s2y);\n    depoFutSwapInstruments.push_back(s3y);\n    depoFutSwapInstruments.push_back(s4y);\n    depoFutSwapInstruments.push_back(s5y);\n    depoFutSwapInstruments.push_back(s6y);\n\n    DayCounter termStructureDayCounter = Actual360();\n    boost::shared_ptr<YieldTermStructure> depoFutSwapTermStructure(new PiecewiseYieldCurve<Discount,\n                                                                                           Linear>(settlementDate, depoFutSwapInstruments, termStructureDayCounter));\n    Date matDate1(25, February, 2015);\n    Date matDate2(18, March, 2015);\n    Date matDate3(20, April, 2015);\n    Date matDate4(18, May, 2015);\n\n    Date matDate5(17, June, 2015);\n    Date matDate6(16, September, 2015);\n    Date matDate7(16, December, 2015);\n    Date matDate8(16, March, 2016);\n    Date matDate9(15, June, 2016);\n\n    Date matDate10(21, September, 2016);\n    Date matDate11(21, February, 2017);\n    Date matDate12(20, February, 2018);\n    Date matDate13(19, February, 2019);\n    Date matDate14(18, February, 2020);\n\n    // Round output to 4 decimals\n    std::cout.precision(4);\n\n    std::cout << \"0.1375: \" << depoFutSwapTermStructure->zeroRate(matDate1, depositDayCounter, Simple) << std::endl;\n    std::cout << \"0.1717: \" << depoFutSwapTermStructure->zeroRate(matDate2, depositDayCounter, Simple) << std::endl;\n    std::cout << \"0.2112: \" << depoFutSwapTermStructure->zeroRate(matDate3, depositDayCounter, Simple) << std::endl;\n    std::cout << \"0.2581: \" << depoFutSwapTermStructure->zeroRate(matDate4, depositDayCounter, Simple) << std::endl;\n\n    std::cout << \"0.2511: \" << depoFutSwapTermStructure->zeroRate(matDate5, FutDayCounter, Simple) << std::endl;\n    std::cout << \"0.3223: \" << depoFutSwapTermStructure->zeroRate(matDate6, FutDayCounter, Simple) << std::endl;\n    std::cout << \"0.4111: \" << depoFutSwapTermStructure->zeroRate(matDate7, FutDayCounter, Simple) << std::endl;\n    std::cout << \"0.5113: \" << depoFutSwapTermStructure->zeroRate(matDate8, FutDayCounter, Simple) << std::endl;\n    std::cout << \"0.6177: \" << depoFutSwapTermStructure->zeroRate(matDate9, FutDayCounter, Simple) << std::endl;\n\n    std::cout << \"0.7325: \" << depoFutSwapTermStructure->zeroRate(matDate10, FutDayCounter, Compounded, Annual) << std::endl;\n    std::cout << \"0.8911: \" << depoFutSwapTermStructure->zeroRate(matDate11, FutDayCounter, Compounded, Annual) << std::endl;\n    std::cout << \"1.2373: \" << depoFutSwapTermStructure->zeroRate(matDate12, FutDayCounter, Compounded, Annual) << std::endl;\n    std::cout << \"1.4884: \" << depoFutSwapTermStructure->zeroRate(matDate13, FutDayCounter, Compounded, Annual) << std::endl;\n    std::cout << \"1.6719: \" << depoFutSwapTermStructure->zeroRate(matDate14, FutDayCounter, Compounded, Annual) << std::endl;\n    std::cout << \"Discount Rate : \" << depoFutSwapTermStructure->discount(matDate14) << std::endl;\n    std::cout << \"Forward Rate : \" << depoFutSwapTermStructure->forwardRate(matDate13, matDate14, FutDayCounter, Simple) << std::endl;\n\n    return 0;\n}", "meta": {"hexsha": "33f283c587170b3ad5c4bdb41907b338b3b5ee28", "size": 9895, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/billiontrader-bootstrapping.cpp", "max_stars_repo_name": "CaptorAB/quantlib-wasm", "max_stars_repo_head_hexsha": "30fd0831f19fea2cedc176649237ea2f78237354", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-08-05T09:29:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T15:17:33.000Z", "max_issues_repo_path": "examples/billiontrader-bootstrapping.cpp", "max_issues_repo_name": "CaptorAB/node-quantlib", "max_issues_repo_head_hexsha": "b341c89fba0e13a4db6545d8c4b42dfdfc2868db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-10T08:15:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-10T14:41:53.000Z", "max_forks_repo_path": "examples/billiontrader-bootstrapping.cpp", "max_forks_repo_name": "CaptorAB/node-quantlib", "max_forks_repo_head_hexsha": "b341c89fba0e13a4db6545d8c4b42dfdfc2868db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-14T20:37:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-18T16:45:21.000Z", "avg_line_length": 50.7435897436, "max_line_length": 165, "alphanum_fraction": 0.7229914098, "num_tokens": 2905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.679178699175393, "lm_q1q2_score": 0.4227611188552607}}
{"text": "#include \"electromagnet_calibration.h\"\r\n\r\n#include <iomanip>\r\n#include <Eigen/Jacobi>\r\n\r\nElectromagnetCalibration::MagneticWorkSpace::MagneticWorkSpace()\r\n{\r\n    xMin = xMax = yMin = yMax = zMin = zMax = 0;\r\n}\r\n\r\nElectromagnetCalibration::MagneticWorkSpace::MagneticWorkSpace(double size)\r\n{\r\n    xMin = -size;\r\n    xMax = size;\r\n    yMin = -size;\r\n    yMax = size;\r\n    zMin = -size;\r\n    zMax = size;\r\n}\r\n\r\n\r\nElectromagnetCalibration::MagneticWorkSpace::MagneticWorkSpace(double xMin_, double xMax_, double yMin_, double yMax_, double zMin_, double zMax_ )\r\n{\r\n    xMin = xMin_;\r\n    xMax = xMax_;\r\n    yMin = yMin_;\r\n    yMax = yMax_;\r\n    zMin = zMin_;\r\n    zMax = zMax_;\r\n}\r\n\r\nMagneticMeasurement::MagneticMeasurement()\r\n{\r\n    Field.setZero(3,1);\r\n    Position.setZero(3,1);\r\n    AppliedCurrentVector.setZero(0,1);\r\n\r\n}\r\n\r\nMagneticMeasurement::MagneticMeasurement(const Eigen::Vector3d &F, const Eigen::Vector3d &P, const Eigen::VectorXd &C)\r\n{\r\n    Field = F;\r\n    Position = P;\r\n    AppliedCurrentVector = C;\r\n}\r\n\r\n\r\nElectromagnetCalibration::ElectromagnetCalibration( std::string calibrationFileName )\r\n{\r\n    bool calibrationFileLoadSucessful = loadCalibration(calibrationFileName);\r\n\r\n    assert( calibrationFileLoadSucessful );\r\n\r\n    checkSourcePositions();\r\n}\r\n\r\nElectromagnetCalibration::ElectromagnetCalibration()\r\n{\r\n    /*< Default Constructor only available to inheriting classes **/\r\n    this->name = \"NONE\";\r\n    this->coilList.clear();\r\n    this->use_offset = false;\r\n\r\n    checkSourcePositions();\r\n}\r\n\r\n//\r\n// \\brief the constructor from a coil list.\r\n// \\param coilList The list of coils and their respective sources.\r\n// \\param dc_field_offset The dc offset field, if any.\r\n//\r\nElectromagnetCalibration::ElectromagnetCalibration(std::string systemName_, const MagneticWorkSpace& workSpace_, const std::vector<ScalorPotential>& coilList_, const ScalorPotential& dc_field_offset_ )\r\n{\r\n    /*< Default Constructor only available to inheriting classes **/\r\n    this->coilList = coilList_;\r\n    this->name = systemName_ ;\r\n    this->offset = dc_field_offset_;\r\n    this->use_offset = ( 0 != offset.getNumberOfSources());\r\n    this->workSpace = workSpace_;\r\n\r\n    checkSourcePositions();\r\n}\r\n\r\n// The following functions return the field and/or gradient given a current vector and a position.\r\n//   If no position is provided, it is assumed to be at the workspace origin. For the combined vector,\r\n//   the gradient matrix has been repacked into a 5 element vetor form (because it is symetric and has zero trace).\r\n//   The order of the gradient terms is: [dBx/dx, dBx/dy, dBx/dz, dBy/dy, dBy/dz].\r\nEigen::Vector3d ElectromagnetCalibration::fieldAtPoint(    const Eigen::VectorXd& currentVector, const Eigen::Vector3d& position ) const\r\n{\r\n    assert( currentVector.size() == coilList.size() );\r\n    Eigen::Vector3d field(0,0,0);\r\n    std::vector<ScalorPotential>::const_iterator coilIT = coilList.begin();\r\n    int coilNum = 0;\r\n    for( ; coilIT != coilList.end(); coilIT++, coilNum ++ )\r\n    {\r\n        field += coilIT->getGradient(position)*currentVector(coilNum);\r\n    }\r\n    if( use_offset )\r\n    {\r\n        field += offset.getGradient(position);\r\n    }\r\n\r\n\r\n    return field;\r\n}\r\n\r\nEigen::Matrix3d ElectromagnetCalibration::gradientAtPoint( const Eigen::VectorXd& currentVector, const Eigen::Vector3d& position ) const\r\n{\r\n\r\n    assert( currentVector.size() == coilList.size() ); // make sure there are as many currents as coils\r\n    Eigen::MatrixXd actuationMatrix = gradientCurrentJacobian( position );\r\n\r\n    return remapGradientVector(actuationMatrix*currentVector + offsetFieldAndGradientAtPoint(position).tail<5>());\r\n\r\n}\r\n\r\nVector8d ElectromagnetCalibration::fieldAndGradientAtPoint( const Eigen::VectorXd& currentVector, const Eigen::Vector3d& position ) const\r\n{\r\n    assert( currentVector.size() == coilList.size() ); // make sure there are as many currents as coils\r\n    Eigen::MatrixXd actuationMatrix = fieldAndGradientCurrentJacobian( position );\r\n\r\n    return actuationMatrix*currentVector + offsetFieldAndGradientAtPoint(position);\r\n}\r\n\r\nVector8d ElectromagnetCalibration::offsetFieldAndGradientAtPoint( const Eigen::Vector3d& position ) const\r\n{\r\n    Vector8d offsetFieldAndGradient = Vector8d::Zero();\r\n\r\n    if( use_offset )\r\n    {\r\n\r\n        ScalorPotentialState fieldInfo = offset.getState(position);\r\n\r\n\r\n        offsetFieldAndGradient.head<3>() = fieldInfo.firstSpatialDerivative;\r\n        offsetFieldAndGradient.tail<5>() = remapGradientMatrix(fieldInfo.secondSpatialDerivative);\r\n    }\r\n\r\n    return offsetFieldAndGradient;\r\n}\r\n\r\n\r\n// The following functions return the Current Jacobian of the field and/or gradient.  This matrix can be inverted to determine the\r\n//   currents necessary to achieve a desired field and gradient.  The gradient portion of the matrix has been vectorized into 5 elements.\r\n//   They are [dBx/dx, dBx/dy, dBx/dz, dBy/dy, dBy/dz].\r\nEigen::MatrixXd ElectromagnetCalibration::fieldCurrentJacobian( const Eigen::Vector3d& position ) const\r\n{\r\n    Eigen::MatrixXd actuationMatrix = Eigen::MatrixXd::Zero(3,coilList.size());\r\n\r\n\r\n\r\n    if( !pointInWorkspace(position) )\r\n    {\r\n        cout << \"Warning: Requesting point out side of magnetic workspace. \" << position.transpose() << \" (Xmin,Xmax): (\" << this->workSpace.xMin << \", \" << this->workSpace.xMax << \") \" <<\r\n                \" (Ymin,Ymax): (\" << this->workSpace.yMin << \", \" << this->workSpace.yMax << \") \" <<\r\n                \" (Zmin,Zmax): (\" << this->workSpace.zMin << \", \" << this->workSpace.zMax << \") \" << endl;\r\n    }\r\n\r\n    std::vector<ScalorPotential>::const_iterator coilIT = coilList.begin();\r\n    int coilNum = 0;\r\n    for( ; coilIT != coilList.end(); coilIT++, coilNum ++ )\r\n    {\r\n        ScalorPotentialState fieldInfo = coilIT->getState(position);\r\n        actuationMatrix.block<3,1>(0,coilNum) = fieldInfo.firstSpatialDerivative;\r\n\r\n    }\r\n\r\n    return actuationMatrix;\r\n}\r\n\r\nEigen::MatrixXd ElectromagnetCalibration::gradientCurrentJacobian( const Eigen::Vector3d& position ) const\r\n{\r\n\r\n    Eigen::MatrixXd actuationMatrix = Eigen::MatrixXd::Zero(5,coilList.size());\r\n\r\n\r\n    if( !pointInWorkspace(position) )\r\n    {\r\n        cout << \"Warning: Requesting point out side of magnetic workspace. \" << position.transpose() << \" (Xmin,Xmax): (\" << this->workSpace.xMin << \", \" << this->workSpace.xMax << \") \" <<\r\n                \" (Ymin,Ymax): (\" << this->workSpace.yMin << \", \" << this->workSpace.yMax << \") \" <<\r\n                \" (Zmin,Zmax): (\" << this->workSpace.zMin << \", \" << this->workSpace.zMax << \") \" << endl;\r\n    }\r\n\r\n    std::vector<ScalorPotential>::const_iterator coilIT = coilList.begin();\r\n    int coilNum = 0;\r\n    for( ; coilIT != coilList.end(); coilIT++, coilNum ++ )\r\n    {\r\n        ScalorPotentialState fieldInfo = coilIT->getState(position);\r\n        actuationMatrix.block<5,1>(0,coilNum) = remapGradientMatrix(fieldInfo.secondSpatialDerivative);\r\n\r\n    }\r\n\r\n    return actuationMatrix;\r\n}\r\n\r\nEigen::MatrixXd ElectromagnetCalibration::fieldAndGradientCurrentJacobian( const Eigen::Vector3d& position ) const\r\n{\r\n\r\n    Eigen::MatrixXd actuationMatrix = Eigen::MatrixXd::Zero(8,coilList.size());\r\n\r\n\r\n    if( !pointInWorkspace(position) )\r\n    {\r\n        cout << \"Warning: Requesting point out side of magnetic workspace. \" << position.transpose() << \" (Xmin,Xmax): (\" << this->workSpace.xMin << \", \" << this->workSpace.xMax << \") \" <<\r\n                \" (Ymin,Ymax): (\" << this->workSpace.yMin << \", \" << this->workSpace.yMax << \") \" <<\r\n                \" (Zmin,Zmax): (\" << this->workSpace.zMin << \", \" << this->workSpace.zMax << \") \" << endl;\r\n    }\r\n\r\n    std::vector<ScalorPotential>::const_iterator coilIT = coilList.begin();\r\n    int coilNum = 0;\r\n    for( ; coilIT != coilList.end(); coilIT++, coilNum ++ )\r\n    {\r\n        ScalorPotentialState fieldInfo = coilIT->getState(position);\r\n        actuationMatrix.block<3,1>(0,coilNum) = fieldInfo.firstSpatialDerivative;\r\n        actuationMatrix.block<5,1>(3,coilNum) = remapGradientMatrix(fieldInfo.secondSpatialDerivative);\r\n\r\n    }\r\n\r\n    return actuationMatrix;\r\n}\r\n\r\n// This function returns the 5x3 Jacobian describing how gradient changes with position.  The gradient change is a 5x3 packing of a 3x3x3 tensor.\r\n//  The first column is how the gradient vector packing [dBx/dx, dBx/dy, dBx/dz, dBy/dy, dBy/dz] changes with x, the second is how it changes with y, and third is\r\n//  how it changes with z.\r\nEigen::Matrix<double,5,3> ElectromagnetCalibration::gradientPositionJacobian( const Eigen::VectorXd& currentVector, const Eigen::Vector3d& position ) const\r\n{\r\n\r\n    assert( currentVector.size() == coilList.size() );// make sure there are as many currents as coils\r\n\r\n    Eigen::Matrix<double,5,3> gradJacobian = Eigen::MatrixXd::Zero(5,3);\r\n\r\n    if( currentVector.norm() == 0 && !useOffset() )\r\n    {\r\n        // NOthing to do!\r\n        return gradJacobian;\r\n    }\r\n\r\n    if( !pointInWorkspace(position) )\r\n    {\r\n        cout << \"Warning: Requesting point out side of magnetic workspace. \" << position.transpose() << \" (Xmin,Xmax): (\" << this->workSpace.xMin << \", \" << this->workSpace.xMax << \") \" <<\r\n                \" (Ymin,Ymax): (\" << this->workSpace.yMin << \", \" << this->workSpace.yMax << \") \" <<\r\n                \" (Zmin,Zmax): (\" << this->workSpace.zMin << \", \" << this->workSpace.zMax << \") \" << endl;\r\n    }\r\n\r\n    std::vector<ScalorPotential>::const_iterator coilIT = coilList.begin();\r\n    int coilNum = 0;\r\n    for( ; coilIT != coilList.end(); coilIT++, coilNum ++ )\r\n    {\r\n        ScalorPotentialState fieldInfo = coilIT->getState(position);\r\n        gradJacobian += fieldInfo.thirdSpatialDerivative*currentVector(coilNum);\r\n\r\n    }\r\n\r\n    if( use_offset )\r\n    {\r\n        ScalorPotentialState fieldInfo = offset.getState(position);\r\n        gradJacobian += fieldInfo.thirdSpatialDerivative;\r\n    }\r\n\r\n    return gradJacobian;\r\n}\r\n\r\n\r\n// This function returns the field, gradient, gradientJacobian, and field/gradient current jacobain.  It is more efficient than requesting them seporately\r\nvoid ElectromagnetCalibration::fullMagneticState( Eigen::Vector3d& fieldAtPoint, Eigen::Matrix<double,8,3>& fieldGradientPositionJacobian, Eigen::MatrixXd& fieldGradientCurrentJacobian, const Eigen::VectorXd& currentVector, const Eigen::Vector3d& position ) const\r\n{\r\n    assert( currentVector.size() == coilList.size() );// make sure there are as many currents as coils\r\n\r\n    fieldAtPoint.setZero();\r\n    fieldGradientPositionJacobian.setZero();\r\n    fieldGradientCurrentJacobian.setZero(8,coilList.size());\r\n\r\n    Vector5d gradAtPt;\r\n    gradAtPt.setZero();\r\n\r\n\r\n    if( currentVector.norm() == 0 && !this->useOffset() )\r\n    {\r\n        // NOthing to do!\r\n        return ;\r\n    }\r\n\r\n    if( !pointInWorkspace(position) )\r\n    {\r\n        cout << \"Warning: Requesting point out side of magnetic workspace. \" << position.transpose() << \" (Xmin,Xmax): (\" << this->workSpace.xMin << \", \" << this->workSpace.xMax << \") \" <<\r\n                \" (Ymin,Ymax): (\" << this->workSpace.yMin << \", \" << this->workSpace.yMax << \") \" <<\r\n                \" (Zmin,Zmax): (\" << this->workSpace.zMin << \", \" << this->workSpace.zMax << \") \" << endl;\r\n    }\r\n\r\n    std::vector<ScalorPotential>::const_iterator coilIT = coilList.begin();\r\n    int coilNum = 0;\r\n    for( ; coilIT != coilList.end(); coilIT++, coilNum ++ )\r\n    {\r\n        ScalorPotentialState fieldInfo = coilIT->getState(position);\r\n\r\n        fieldGradientCurrentJacobian.block<3,1>(0,coilNum) = fieldInfo.firstSpatialDerivative;\r\n        fieldGradientCurrentJacobian.block<5,1>(3,coilNum) = remapGradientMatrix(fieldInfo.secondSpatialDerivative);\r\n\r\n        fieldGradientPositionJacobian.block<5,3>(3,0) += fieldInfo.thirdSpatialDerivative*currentVector(coilNum);\r\n        fieldGradientPositionJacobian.block<3,3>(0,0) += fieldInfo.secondSpatialDerivative*currentVector(coilNum);\r\n        fieldAtPoint += fieldInfo.firstSpatialDerivative*currentVector(coilNum);\r\n    }\r\n\r\n    if( use_offset )\r\n    {\r\n        ScalorPotentialState fieldInfo = offset.getState(position);\r\n\r\n        fieldGradientPositionJacobian.block<5,3>(3,0) += fieldInfo.thirdSpatialDerivative;\r\n        fieldGradientPositionJacobian.block<3,3>(0,0) += fieldInfo.secondSpatialDerivative;\r\n        fieldAtPoint += fieldInfo.firstSpatialDerivative;\r\n\r\n    }\r\n\r\n}\r\n\r\nMagneticState ElectromagnetCalibration::fullMagneticState(const Eigen::VectorXd& currentVector, const Eigen::Vector3d& position ) const\r\n{\r\n    assert( currentVector.size() == coilList.size() );// make sure there are as many currents as coils\r\n\r\n    MagneticState returnState;\r\n    returnState.FieldGradientActuationMatrix.setZero(8,coilList.size());\r\n\r\n\r\n    if( !pointInWorkspace(position) )\r\n    {\r\n        cout << \"Warning: Requesting point out side of magnetic workspace. \" << position.transpose() << \" (Xmin,Xmax): (\" << this->workSpace.xMin << \", \" << this->workSpace.xMax << \") \" <<\r\n                \" (Ymin,Ymax): (\" << this->workSpace.yMin << \", \" << this->workSpace.yMax << \") \" <<\r\n                \" (Zmin,Zmax): (\" << this->workSpace.zMin << \", \" << this->workSpace.zMax << \") \" << endl;\r\n    }\r\n\r\n    std::vector<ScalorPotential>::const_iterator coilIT;\r\n    int coilNum;\r\n    for( coilIT = coilList.begin(), coilNum = 0;\r\n         coilIT != coilList.end();\r\n         coilIT++, coilNum ++ )\r\n    {\r\n        ScalorPotentialState fieldInfo = coilIT->getState(position);\r\n\r\n        returnState.FieldGradientActuationMatrix.block<3,1>(0,coilNum) = fieldInfo.firstSpatialDerivative;\r\n        returnState.FieldGradientActuationMatrix.block<5,1>(3,coilNum) =  remapGradientMatrix(fieldInfo.secondSpatialDerivative);\r\n\r\n        returnState.Field += fieldInfo.firstSpatialDerivative * currentVector(coilNum);\r\n        returnState.GradientPositionJacobian += fieldInfo.thirdSpatialDerivative*currentVector(coilNum);\r\n        returnState.Gradient += fieldInfo.secondSpatialDerivative*currentVector(coilNum);\r\n\r\n    }\r\n\r\n    if( use_offset )\r\n    {\r\n        ScalorPotentialState fieldInfo = offset.getState(position);\r\n\r\n        returnState.Field += fieldInfo.firstSpatialDerivative;\r\n        returnState.GradientPositionJacobian += fieldInfo.thirdSpatialDerivative;\r\n        returnState.Gradient += fieldInfo.secondSpatialDerivative;\r\n    }\r\n\r\n    return returnState;\r\n}\r\n\r\n\r\n\r\n// These two functions convert a vector packing of the gradient to a matrix packing and vice versa.\r\nEigen::Matrix3d ElectromagnetCalibration::remapGradientVector(const Vector5d& gradVector )\r\n{\r\n    Eigen::Matrix3d gradientMatrix;\r\n    // repack vector gradient into matrix gradient\r\n    gradientMatrix.leftCols<1>() = gradVector.topRows<3>();\r\n    gradientMatrix.block<2,1>(1,1) = gradVector.bottomRows<2>();\r\n    gradientMatrix(0,1) = gradientMatrix(1,0);\r\n    gradientMatrix(0,2) = gradientMatrix(2,0);\r\n    gradientMatrix(1,2) = gradientMatrix(2,1);\r\n    gradientMatrix(2,2) = -1.0*(gradientMatrix(0,0)+gradientMatrix(1,1));\r\n\r\n    return gradientMatrix;\r\n}\r\n\r\nVector5d ElectromagnetCalibration::remapGradientMatrix( const Eigen::Matrix3d& gradMatrix)\r\n{\r\n    Vector5d gradVec;\r\n    gradVec.topRows<3>() = gradMatrix.leftCols<1>();\r\n    gradVec(3) = gradMatrix(1,1);\r\n    gradVec(4) = gradMatrix(2,1);\r\n    return gradVec;\r\n}\r\n\r\nEigen::MatrixXd ElectromagnetCalibration::packForceMatrix(const Eigen::Vector3d& moment)\r\n{\r\n    Eigen::MatrixXd ForceMatrix(3,5);\r\n    ForceMatrix <<  moment(0),  moment(1), moment(2),  0,         0,\r\n            0,          moment(0), 0,          moment(1), moment(2),\r\n            -moment(2), 0,         moment(0), -moment(2), moment(1);\r\n    return ForceMatrix;\r\n}\r\n\r\nbool ElectromagnetCalibration::loadCalibration(std::string fileName)\r\n{\r\n    coilList.clear();\r\n\r\n    // reinitialize offset\r\n    offset = ScalorPotential();\r\n\r\n    YAML::Node systemDefinition = YAML::LoadFile(fileName);\r\n    this->name = systemDefinition[\"System_Name\"].as<std::string>();\r\n    int numCoils = systemDefinition[\"Coil_List\"].size();\r\n    this->workSpace.xMin = systemDefinition[\"Workspace_Dimensions\"][0][0].as<double>();\r\n    this->workSpace.xMax = systemDefinition[\"Workspace_Dimensions\"][0][1].as<double>();\r\n    this->workSpace.yMin = systemDefinition[\"Workspace_Dimensions\"][1][0].as<double>();\r\n    this->workSpace.yMax = systemDefinition[\"Workspace_Dimensions\"][1][1].as<double>();\r\n    this->workSpace.zMin = systemDefinition[\"Workspace_Dimensions\"][2][0].as<double>();\r\n    this->workSpace.zMax = systemDefinition[\"Workspace_Dimensions\"][2][1].as<double>();\r\n\r\n    for( unsigned int coil = 0; coil<numCoils; coil++ )\r\n    {\r\n        std::string coilTag = systemDefinition[\"Coil_List\"][coil].as<std::string>();\r\n\r\n        ScalorPotential newCoil;\r\n\r\n        int numSources = systemDefinition[coilTag][\"Source_List\"].size();\r\n\r\n        for( unsigned int src = 0; src < numSources; src ++ )\r\n        {\r\n            ScalorPotential::srcStruct newSrc;\r\n            std::string srcTag = systemDefinition[coilTag][\"Source_List\"][src].as<std::string>();\r\n\r\n            std::vector<double> coeff = systemDefinition[coilTag][srcTag][\"A_Coeff\"].as< std::vector<double> >();\r\n            for( unsigned int i=0; i<coeff.size(); i++ )\r\n                newSrc.A_Coeff.push_back(ScalorPotential::srcCoeff(coeff[i],i+1));\r\n\r\n            coeff = systemDefinition[coilTag][srcTag][\"B_Coeff\"].as< std::vector<double> >();\r\n            for( unsigned int i=0; i<coeff.size(); i++ )\r\n                newSrc.B_Coeff.push_back(ScalorPotential::srcCoeff(coeff[i],i+1));\r\n\r\n            newSrc.srcDirection = systemDefinition[coilTag][srcTag][\"Source_Direction\"].as< Eigen::Vector3d >();\r\n            newSrc.srcDirection.normalize(); // normalize in place\r\n            newSrc.srcPosition = systemDefinition[coilTag][srcTag][\"Source_Position\"].as< Eigen::Vector3d >();\r\n\r\n            newCoil.setSourceStruct(src,newSrc); // add to coil's source list\r\n        }\r\n\r\n        if( coilTag.find(\"Offset\") == std::string::npos )\r\n        {\r\n            // \"Offset\" not found\r\n            this->coilList.push_back(newCoil); // add to coil List\r\n        } else\r\n        {\r\n            // Offset tag is found\r\n            offset = newCoil;\r\n        }\r\n    }\r\n\r\n    use_offset = offset.getNumberOfSources();\r\n    return coilList.size() > 0 || use_offset;\r\n}\r\n\r\n///@brief  writes a new calibration file\r\n/// @param a string pointing to the location for the yaml formated calbiration file\r\nbool ElectromagnetCalibration::writeCalibration(std::string fileName) const\r\n{\r\n    YAML::Node systemDefinition;\r\n    systemDefinition[\"System_Name\"] = this->name;\r\n\r\n    std::vector<ScalorPotential>::const_iterator coilIT = coilList.begin();\r\n    unsigned int coilNum =0;\r\n    for( ; coilIT != coilList.end(); coilIT ++, coilNum ++ )\r\n    {\r\n        stringstream coilName;\r\n        coilName << \"Coil_\" << coilNum;\r\n        systemDefinition[\"Coil_List\"].push_back(coilName.str());\r\n\r\n        for( unsigned int srcNum = 0; srcNum < coilIT->getNumberOfSources(); srcNum ++ )\r\n        {\r\n            ScalorPotential::srcStruct src = coilIT->getSourceStruct(srcNum);\r\n            stringstream srcName;\r\n            srcName << \"Src_\" << srcNum;\r\n            systemDefinition[coilName.str()][\"Source_List\"].push_back(srcName.str());\r\n            std::vector<double> coeff;\r\n            for( unsigned int i=0; i<src.A_Coeff.size(); i++ )\r\n                coeff.push_back(src.A_Coeff[i].coeff);\r\n            systemDefinition[coilName.str()][srcName.str()][\"A_Coeff\"] = coeff;\r\n\r\n            coeff.clear();\r\n            for( unsigned int i=0; i<src.B_Coeff.size(); i++ )\r\n                coeff.push_back(src.B_Coeff[i].coeff);\r\n            systemDefinition[coilName.str()][srcName.str()][\"B_Coeff\"] = coeff;\r\n            systemDefinition[coilName.str()][srcName.str()][\"Source_Direction\"] = src.srcDirection;\r\n            systemDefinition[coilName.str()][srcName.str()][\"Source_Position\"] = src.srcPosition;\r\n        }\r\n    }\r\n\r\n    if( this->hasOffset() )\r\n    {\r\n        stringstream coilName;\r\n        coilName << \"Offset\";\r\n        systemDefinition[\"Coil_List\"].push_back(coilName.str());\r\n\r\n        for( unsigned int srcNum = 0; srcNum < offset.getNumberOfSources(); srcNum ++ )\r\n        {\r\n            ScalorPotential::srcStruct src = offset.getSourceStruct(coilNum);\r\n            stringstream srcName;\r\n            srcName << \"Src_\" << srcNum;\r\n            systemDefinition[coilName.str()][\"Source_List\"].push_back(srcName.str());\r\n            std::vector<double> coeff;\r\n            for( unsigned int i=0; i<src.A_Coeff.size(); i++ )\r\n                coeff.push_back(src.A_Coeff[i].coeff);\r\n            systemDefinition[coilName.str()][srcName.str()][\"A_Coeff\"] = coeff;\r\n\r\n            coeff.clear();\r\n            for( unsigned int i=0; i<src.A_Coeff.size(); i++ )\r\n                coeff.push_back(src.B_Coeff[i].coeff);\r\n            systemDefinition[coilName.str()][srcName.str()][\"B_Coeff\"] = coeff;\r\n            systemDefinition[coilName.str()][srcName.str()][\"Source_Direction\"] = src.srcDirection;\r\n            systemDefinition[coilName.str()][srcName.str()][\"Source_Position\"] = src.srcPosition;\r\n        }\r\n    }\r\n\r\n    systemDefinition[\"Workspace_Dimensions\"][0][0] = this->workSpace.xMin;\r\n    systemDefinition[\"Workspace_Dimensions\"][0][1] = this->workSpace.xMax;\r\n    systemDefinition[\"Workspace_Dimensions\"][1][0] = this->workSpace.yMin;\r\n    systemDefinition[\"Workspace_Dimensions\"][1][1] = this->workSpace.yMax;\r\n    systemDefinition[\"Workspace_Dimensions\"][2][0] = this->workSpace.zMin;\r\n    systemDefinition[\"Workspace_Dimensions\"][2][1] = this->workSpace.zMax;\r\n\r\n\r\n    std::ofstream fout;\r\n    fout.open(fileName.c_str(),std::ofstream::out|std::ofstream::trunc);\r\n    fout << systemDefinition;\r\n    fout.close();\r\n\r\n    return fout.good();\r\n}\r\n\r\nint ElectromagnetCalibration::getNumberOfCoils() const\r\n{\r\n    return coilList.size();\r\n}\r\n\r\n///@brief returns the number of sources for the given coil\r\nint ElectromagnetCalibration::getNumberOfSources( unsigned int coilNum ) const\r\n{\r\n    if( coilNum >= (coilList.size() + useOffset()) )\r\n        return 0;\r\n    else if( coilNum == coilList.size() )\r\n        return offset.getNumberOfSources();\r\n    else\r\n        return coilList[coilNum].getNumberOfSources();\r\n}\r\n\r\n///@brief returns the number of coefficients for the given source\r\nint ElectromagnetCalibration::getNumberOfCoeffients( unsigned int coilNum, unsigned int srcNum ) const\r\n{\r\n    if( coilNum >= (coilList.size() + useOffset()) )\r\n        return 0;\r\n    else if( coilNum == coilList.size() )\r\n    {\r\n        if( srcNum < offset.getNumberOfSources() )\r\n            return offset.getSourceStruct(srcNum).A_Coeff.size() + offset.getSourceStruct(srcNum).B_Coeff.size();\r\n    }\r\n    else if( srcNum < coilList[coilNum].getNumberOfSources() )\r\n        return coilList[coilNum].getSourceStruct(srcNum).A_Coeff.size() + coilList[coilNum].getSourceStruct(srcNum).B_Coeff.size();\r\n\r\n    return 0;\r\n\r\n}\r\n\r\nbool ElectromagnetCalibration::hasOffset() const\r\n{\r\n    return offset.getNumberOfSources();\r\n}\r\n\r\nstd::string ElectromagnetCalibration::getName() const\r\n{\r\n    return name;\r\n}\r\n\r\nbool ElectromagnetCalibration::pointInWorkspace( const Eigen::Vector3d& position ) const\r\n{\r\n    return workSpace.xMin <= position(0) && workSpace.xMax >= position(0)\r\n            && workSpace.yMin <= position(1) && workSpace.yMax >= position(1)\r\n            && workSpace.zMin <= position(2) && workSpace.zMax >= position(2);\r\n}\r\n\r\nvoid ElectromagnetCalibration::setWorkSpace(const ElectromagnetCalibration::MagneticWorkSpace& ws)\r\n{\r\n    workSpace = ws;\r\n    return;\r\n}\r\n\r\nElectromagnetCalibration::MagneticWorkSpace ElectromagnetCalibration::getWorkSpace() const\r\n{\r\n    return workSpace;\r\n}\r\n\r\nvoid ElectromagnetCalibration::useOffset(bool offsetOn)\r\n{\r\n    use_offset = offsetOn;\r\n}\r\n\r\nvoid ElectromagnetCalibration::useOffset(const ScalorPotential& newOffset )\r\n{\r\n    offset = newOffset;\r\n    use_offset = true;\r\n    return;\r\n}\r\n\r\nbool ElectromagnetCalibration::useOffset() const\r\n{\r\n    return use_offset;\r\n}\r\n\r\nbool ElectromagnetCalibration::checkSourcePositions(bool printWarning) const\r\n{\r\n    std::vector<ScalorPotential>::const_iterator coilIterator;\r\n    std::vector<ScalorPotential::srcStruct>::const_iterator srcIterator;\r\n    int numTooClose = 0;\r\n    int numTooFar = 0;\r\n    // normalize directions, check positions relative to workspace, and source counts\r\n    for( coilIterator  = coilList.begin();\r\n         coilIterator != coilList.end();\r\n         coilIterator ++)\r\n    {\r\n        for(srcIterator  = coilIterator->srcList.begin();\r\n            srcIterator != coilIterator->srcList.end();\r\n            srcIterator ++ )\r\n        {\r\n\r\n            double distanceSq = (srcIterator->srcPosition - pCenter).squaredNorm();\r\n\r\n            if( distanceSq < rMinSq)\r\n            {\r\n                numTooClose ++;\r\n            }else if( distanceSq > rMaxSq )\r\n            {\r\n                numTooFar ++;\r\n            }\r\n        }\r\n    }\r\n\r\n    if(printWarning && (numTooClose+numTooFar) )\r\n    {\r\n        cout << \"There are \" << numTooClose << \" sources too close to the workspace center and \" << numTooFar << \" too far from the workspace center.\" << endl;\r\n    }\r\n\r\n\r\n\r\n    return (numTooClose+numTooFar == 0);\r\n}\r\n\r\n\r\n\r\nvoid ElectromagnetCalibration::calibrate(std::string calibrationName, const std::vector<MagneticMeasurement>& dataList, bool printProgress, bool printStats_, calibration_constraints constraint,double minimumSourceToCenterDistance, double maximumSourceToCenterDistance, double converganceTolerance, int maxAttempts, int numberOfConvergedIterations)\r\n{\r\n    name = calibrationName;\r\n\r\n    if( constraint == HEADING_AND_POSITION )\r\n        minRadIsActive = true;\r\n    else\r\n        minRadIsActive = false;\r\n    nConst = 2;\r\n\r\n    posWeight = 1;\r\n\r\n    double sqrtEpsilon = std::sqrt(std::numeric_limits<double>::epsilon());\r\n    double rmsError_this, rmsError_last;\r\n    int iteration = 0;\r\n    bool converged;\r\n    int convergedIterations = 0;\r\n\r\n\r\n    do{\r\n        numberOfMeasurements = dataList.size();\r\n        numberOfParameters = 0;\r\n        numberOfConstraints = 0;\r\n        numberOfSources = 0;\r\n\r\n        std::vector<ScalorPotential>::iterator coilIT = coilList.begin();\r\n        std::vector<MagneticMeasurement>::const_iterator measIT;\r\n\r\n        // count problem size\r\n        int coilNum = 0;\r\n        for( ; coilIT != coilList.end(); coilIT ++, coilNum ++ )\r\n        {\r\n            numberOfSources += coilIT->getNumberOfSources();\r\n            numberOfConstraints += nConst*coilIT->getNumberOfSources();\r\n            numberOfParameters += coilIT->getNumCalibrationParameters();\r\n        }\r\n        if( useOffset() )\r\n        {\r\n            numberOfSources += offset.getNumberOfSources();\r\n            numberOfConstraints += nConst*offset.getNumberOfSources();\r\n            numberOfParameters += offset.getNumCalibrationParameters();\r\n        }\r\n\r\n        // Define Workspace Size off of DATA\r\n        workSpace.xMax = -std::numeric_limits<double>::max();\r\n        workSpace.yMax = -std::numeric_limits<double>::max();\r\n        workSpace.zMax = -std::numeric_limits<double>::max();\r\n        workSpace.xMin = std::numeric_limits<double>::max();\r\n        workSpace.yMin = std::numeric_limits<double>::max();\r\n        workSpace.zMin = std::numeric_limits<double>::max();\r\n        for( measIT = dataList.begin(); measIT != dataList.end(); measIT ++)\r\n        {\r\n            workSpace.xMax = std::max(workSpace.xMax, measIT->Position.x());\r\n            workSpace.xMin = std::min(workSpace.xMin, measIT->Position.x());\r\n\r\n            workSpace.yMax = std::max(workSpace.yMax, measIT->Position.y());\r\n            workSpace.yMin = std::min(workSpace.yMin, measIT->Position.y());\r\n\r\n            workSpace.zMax = std::max(workSpace.zMax, measIT->Position.z());\r\n            workSpace.zMin = std::min(workSpace.zMin, measIT->Position.z());\r\n        }\r\n\r\n        // Calculate Workspace Info\r\n        pCenter = Eigen::Vector3d(workSpace.xMax+workSpace.xMin,workSpace.yMax+workSpace.yMin,workSpace.zMax+workSpace.zMin)/2.0;\r\n\r\n        if( minimumSourceToCenterDistance < 0)\r\n        {\r\n            rMinSq = 0;\r\n            for( measIT = dataList.begin(); measIT != dataList.end(); measIT ++)\r\n            {\r\n                rMinSq = std::max(rMinSq, 1.001*(measIT->Position-pCenter).squaredNorm()); // limit it to no closer than 5% bigger than the wkspace size\r\n            }\r\n        } else\r\n        {\r\n            rMinSq = 1.001 * std::pow(minimumSourceToCenterDistance,2);\r\n        }\r\n\r\n\r\n        if( maximumSourceToCenterDistance < 0  || (constraint != HEADING_AND_POSITION ))\r\n        {\r\n            rMaxSq = rMinSq;\r\n\r\n            if( maximumSourceToCenterDistance > 0 )\r\n                rMaxSq = std::max(std::pow(maximumSourceToCenterDistance,2),rMaxSq);\r\n\r\n\r\n            int srcNum;\r\n            for(coilIT = coilList.begin(); coilIT != coilList.end(); coilIT ++ )\r\n            {\r\n                ScalorPotential::srcStruct src;\r\n                for( srcNum = 0; srcNum < coilIT->getNumberOfSources(); srcNum ++ )\r\n                {\r\n                    src = coilIT->getSourceStruct(srcNum);\r\n                    rMaxSq = std::max(rMaxSq, 100*(src.srcPosition-pCenter).squaredNorm()); // limit it to 30x the farthest initial guess\r\n\r\n                    if( rMaxSq == 0 )\r\n                        rMaxSq = 1;\r\n                }\r\n            }\r\n\r\n        } else\r\n        {\r\n            rMaxSq = 0.999 * std::pow(maximumSourceToCenterDistance,2);\r\n        }\r\n\r\n        assert(('Electromagnet_Calibration::calibrate: The minimum source to center distance is greator than the maximum allowable source to center distance.', rMaxSq >= rMinSq || constraint == UNIT_HEADING_ONLY ));\r\n\r\n        // initialize coefficients with linear least squares\r\n        linearLeastSquareCoeffFit(dataList);\r\n\r\n\r\n        // preallocate vectors and matricies for solution\r\n        Eigen::MatrixXd J;\r\n        Eigen::MatrixXd JtJ;\r\n        Eigen::VectorXd E;\r\n\r\n        // ************ OPTIMIZE WITH NONLINEAR LEAST SQUARES ***************** //\r\n\r\n\r\n        JtJ.setZero(0,0);\r\n        J.setZero(3*numberOfMeasurements+numberOfConstraints,numberOfParameters);\r\n        E.setZero(0);\r\n\r\n\r\n\r\n\r\n        // initialize PHI leave all Lambda's Initialized to Zero\r\n        Eigen::VectorXd states(numberOfParameters), states_last(numberOfParameters), delta_States(numberOfParameters), delta_States_last(numberOfParameters), error_this(numberOfMeasurements*3+numberOfConstraints), delta_error(numberOfMeasurements*3+numberOfConstraints);\r\n        Eigen::VectorXd deltaErrExp(numberOfMeasurements*3+numberOfConstraints);\r\n        Eigen::VectorXd ds_tmp;\r\n        Eigen::VectorXd error_last = error_this;\r\n        Eigen::VectorXd delta_error_last = delta_error;\r\n        Eigen::VectorXd error_last_last = error_last;\r\n\r\n        obtainPHI(states);\r\n        applyPHI(states);\r\n        obtainPHI(states);\r\n        states_last = states;\r\n\r\n        delta_States.setZero(numberOfParameters);\r\n        delta_States_last.setZero(numberOfParameters);\r\n\r\n        packError(error_this, dataList);\r\n        delta_error.setZero(error_this.rows(),error_this.cols());\r\n        error_last = error_this;\r\n\r\n        rmsError_this = std::sqrt(error_this.squaredNorm()/error_this.rows());\r\n        rmsError_last = rmsError_this;\r\n\r\n\r\n        double Lambda = 1;\r\n        double LambdaChangeRange = 1 + sqrtEpsilon;\r\n        double lambdaRangeCount = 0;\r\n\r\n        double deltaRmsError = rmsError_this = rmsError_last;\r\n\r\n        double predictionFactor = 1.0;\r\n        double percentStateChange = 0.0;\r\n        double percentErrorChange = 0.0;\r\n        int errorIncreaseCounter = 0;\r\n\r\n\r\n\r\n        if( printProgress )\r\n        {\r\n            std::cout << std::setprecision(3) << \"Iteration: \" << iteration << \"   RMS Error: \" << rmsError_this << std::endl;// << \"   Delta RMS Error: \" <<  deltaRmsError  << \"\\tError Change: \" << percentErrorChange << \"%\" << \"\\tState Change: \" << percentStateChange << \"%\";\r\n        }\r\n\r\n        do {\r\n            converged = true;\r\n\r\n            // get updated jacobian\r\n            packErrorJacobian(J, dataList);\r\n\r\n            // Remove Zero columns and rescale\r\n            std::vector<int> HtoJ_index;\r\n            std::vector<double> H_col_scale;\r\n            Eigen::MatrixXd H(J.rows(),J.cols());\r\n            unsigned int count = 0;\r\n            for( unsigned int i=0; i<J.cols(); i++ )\r\n            {\r\n                double J_col_norm = J.col(i).norm();\r\n                //cout << \"Col: \" << i << \" Norm: \" << J_col_norm << (J_col_norm > std::numeric_limits<double>::epsilon()*10.0?\"\\tKeep\":\"\\tLoose\")<< endl;\r\n                if( J_col_norm > std::numeric_limits<double>::epsilon()*10.0 /*!=0*/ )\r\n                {\r\n                    H.col(count) = J.col(i)/J_col_norm;\r\n                    H_col_scale.push_back(J_col_norm);\r\n                    HtoJ_index.push_back(i);\r\n                    count ++;\r\n                }\r\n            }\r\n\r\n\r\n            delta_States_last = delta_States;\r\n\r\n            int H_rows = H.rows();\r\n            int H_cols = HtoJ_index.size();\r\n\r\n            assert( H_rows > 0 && H_cols > 0 );\r\n\r\n            JtJ = H.block(0,0,H_rows,H_cols).transpose()*H.block(0,0,H_rows,H_cols);\r\n            JtJ += Lambda*Eigen::MatrixXd::Identity(H_cols,H_cols);\r\n\r\n            ds_tmp = -JtJ.fullPivLu().solve(H.block(0,0,H_rows,H_cols).transpose()*error_this);\r\n\r\n            //ds_tmp = -JtJ.ldlt().solve(H.block(0,0,H_rows,H_cols).transpose()*error_this);\r\n\r\n            delta_States.setZero(delta_States.rows());\r\n            for( unsigned int i=0; i<H_cols; i++ )\r\n            {\r\n                delta_States(HtoJ_index[i]) = ds_tmp(i)/H_col_scale[i];\r\n            }\r\n\r\n\r\n            states += delta_States;\r\n\r\n            delta_error_last = delta_error;\r\n            error_last_last = error_last;\r\n            error_last = error_this;\r\n\r\n\r\n            applyPHI(states);\r\n            packError(error_this, dataList);\r\n\r\n\r\n            double rmsError_last_last = rmsError_last;\r\n            rmsError_last = rmsError_this;\r\n            rmsError_this = std::sqrt(error_this.squaredNorm()/error_this.rows());\r\n\r\n            delta_error = error_this-error_last;\r\n\r\n            deltaRmsError = rmsError_this-rmsError_last;\r\n\r\n            deltaErrExp =  J*delta_States + error_last;\r\n\r\n            double delta_error_prediction = std::sqrt(deltaErrExp.squaredNorm()/error_this.rows())-rmsError_last;\r\n            predictionFactor = deltaRmsError/( delta_error_prediction );\r\n\r\n            delta_States = states-states_last; // just incase BC/Constraint inforcement changed something\r\n\r\n            percentErrorChange = deltaRmsError / rmsError_this * 100.0;\r\n            if( std::isnan(percentErrorChange) )\r\n                percentErrorChange = deltaRmsError;\r\n\r\n            double normStates = states.norm();\r\n            percentStateChange = delta_States.norm()/normStates * 100.0;\r\n            if( std::isnan(percentStateChange) )\r\n                percentStateChange = sqrt(delta_States.squaredNorm()/delta_States.rows());\r\n\r\n\r\n            if( deltaRmsError <= 0  )\r\n            {\r\n                errorIncreaseCounter = 1;\r\n\r\n\r\n\r\n                // UPDATE Lambda based on convergance criteria\r\n\r\n                // handel boundry conditions that occure at initialization\r\n                if( std::isinf(predictionFactor) || std::isnan(predictionFactor)  )\r\n                {\r\n                    predictionFactor = 1.0-3.0/4.0*LambdaChangeRange;\r\n                }\r\n\r\n                if( predictionFactor > 1+LambdaChangeRange/4.0 )\r\n                {\r\n                    double e_this_sqNorm = error_this.squaredNorm();\r\n                    double deltaError = e_this_sqNorm-error_last.squaredNorm();\r\n\r\n                    std::vector<double> e,ac,bc,cc;\r\n                    e.push_back(e_this_sqNorm-deltaError);\r\n                    e.push_back(e_this_sqNorm);\r\n                    ac.push_back(0);\r\n                    ac.push_back(1);\r\n                    bc.push_back(0);\r\n                    bc.push_back(1);\r\n                    cc.push_back(1);\r\n                    cc.push_back(1);\r\n\r\n                    double factor = 1.0;\r\n                    while (  deltaError < 0 )\r\n                    {\r\n                        factor *= 3.0;\r\n                        states = states_last + factor*delta_States;\r\n\r\n                        // update error\r\n                        error_last = error_this;\r\n                        applyPHI(states);\r\n                        packError(error_this, dataList);\r\n\r\n                        double e_this_sqNorm2 = error_this.squaredNorm();\r\n\r\n                        e.push_back(e_this_sqNorm2);\r\n                        ac.push_back(factor*factor);\r\n                        bc.push_back(factor);\r\n                        cc.push_back(1.0);\r\n\r\n                        deltaError = e_this_sqNorm2-e_this_sqNorm;\r\n                        e_this_sqNorm = e_this_sqNorm2;\r\n                    }\r\n\r\n                    Eigen::MatrixXd A(e.size(),3);\r\n                    Eigen::VectorXd E(e.size(),1);\r\n                    for( int i=0; i< e.size(); i++ )\r\n                    {\r\n                        A.block(i,0,1,3) << ac[i], bc[i], cc[i];\r\n                        E(i) = e[i];\r\n                    }\r\n                    Eigen::Vector3d coeff = A.householderQr().solve(E);\r\n\r\n                    factor = -coeff(1)/(2.0*coeff(0));\r\n\r\n                    delta_States *= factor;\r\n                    states = states_last + delta_States;\r\n\r\n                    // update error\r\n                    error_last = error_this;\r\n                    applyPHI(states);\r\n                    packError(error_this, dataList);\r\n\r\n\r\n                    delta_States = states-states_last; // just incase BC/Constraint inforcement changed something\r\n\r\n                    error_last = error_last_last;\r\n                    rmsError_this = std::sqrt(error_this.squaredNorm()/error_this.rows());//solutionRMSError();\r\n\r\n                    delta_error = error_this-error_last;\r\n\r\n                    deltaRmsError = rmsError_this-rmsError_last;\r\n\r\n                    lambdaRangeCount ++;\r\n\r\n                    percentErrorChange = deltaRmsError / rmsError_this * 100.0;\r\n                    if( std::isnan(percentErrorChange) )\r\n                        percentErrorChange = deltaRmsError;\r\n\r\n                    double normStates = states.norm();\r\n                    percentStateChange = delta_States.norm()/normStates * 100.0;\r\n                    if( std::isnan(percentStateChange) )\r\n                        percentStateChange = sqrt(delta_States.squaredNorm()/delta_States.rows());\r\n\r\n                }\r\n                else if( std::abs(1.0-predictionFactor) > LambdaChangeRange )\r\n                {\r\n                    // Error change was too small compared to a linear change. Getting close to an over-step.  Be more gradient decent.\r\n                    double factor =  2;\r\n                    Lambda = std::max( Lambda*factor, std::numeric_limits<double>::epsilon() );\r\n\r\n                }\r\n                else if( std::abs(1.0-predictionFactor) < LambdaChangeRange/2.0 )\r\n                {\r\n                    // Error change was too close to linear.  Get more aggresive!\r\n                    double factor  =  1/2.0;\r\n                    Lambda = std::max( Lambda*factor, std::numeric_limits<double>::epsilon() );\r\n\r\n                    lambdaRangeCount ++;\r\n\r\n                }\r\n\r\n                if( lambdaRangeCount > 3 )\r\n                {\r\n                    LambdaChangeRange = std::min(1.0, LambdaChangeRange*2);\r\n                    lambdaRangeCount = 0;\r\n                }\r\n\r\n\r\n\r\n                states_last = states;\r\n            }\r\n            else\r\n            {\r\n                errorIncreaseCounter ++;\r\n                // change made things worse!\r\n\r\n\r\n                Lambda *= 2.0*errorIncreaseCounter;\r\n                //Lambda *= std::abs(deltaRmsError-delta_error_prediction)/Lambda+2.0;//2.0;\r\n                LambdaChangeRange = std::max(LambdaChangeRange*0.75, sqrtEpsilon);\r\n\r\n\r\n                states = states_last;\r\n                delta_States = delta_States_last;\r\n\r\n                error_this = error_last;\r\n                error_last = error_last_last;\r\n                delta_error = delta_error_last;\r\n\r\n                rmsError_this = rmsError_last;\r\n                rmsError_last = rmsError_last_last;\r\n\r\n                deltaRmsError = rmsError_this-rmsError_last;\r\n\r\n                delta_States_last.setZero(delta_States_last.rows(),delta_States_last.cols());\r\n                lambdaRangeCount = 0;\r\n\r\n                converged = false;\r\n            }\r\n\r\n            iteration ++;\r\n\r\n            assert( !std::isinf(Lambda) && !std::isnan(Lambda));\r\n            assert( !std::isinf(rmsError_this) && !std::isnan(rmsError_this));\r\n\r\n\r\n\r\n            converged = converged && (\r\n                        iteration >= maxAttempts ||\r\n                        rmsError_this <converganceTolerance ||\r\n                        (std::abs(deltaRmsError)*(1+Lambda) < converganceTolerance && delta_error.norm()!=0) ||\r\n                        (std::abs(percentErrorChange)*(1+Lambda)/100.0 < converganceTolerance && percentErrorChange >= std::numeric_limits<double>::epsilon()*rmsError_this ) ||\r\n                        (std::abs(percentStateChange)*(1+Lambda)/100.0 < converganceTolerance && percentStateChange >= std::numeric_limits<double>::epsilon()*normStates ) );\r\n\r\n\r\n            // make sure we have multiple converged runs before declaring done\r\n            if( deltaRmsError < 0 )\r\n            {\r\n                convergedIterations = converged*(convergedIterations+1);\r\n                converged = converged && (convergedIterations >= numberOfConvergedIterations);\r\n            }\r\n\r\n            if( iteration == 1 && maxAttempts > 1 )\r\n                converged = false;\r\n\r\n            if( Lambda > 10000 )\r\n                converged = true;\r\n\r\n\r\n            if( printProgress && iteration%100 == 1)\r\n            {\r\n                std::cout <</* \"Conv: \" << (converged?\"YES   \":\"NO   \") << */std::setprecision(3) << \"Iteration: \" << iteration << \"\\tRMS Error: \" << 1000*std::sqrt(error_this.head(3*numberOfMeasurements).squaredNorm()/(3*numberOfMeasurements)) << \" mT\\tDelta RMS Error: \" <<  deltaRmsError*1000  << \" mT\\t  Error Change: \" << percentErrorChange << \"%\" << \"\\tState Change: \" << percentStateChange << \"%\";\r\n                std::cout << std::endl;\r\n            }\r\n\r\n\r\n        }while( !converged );\r\n\r\n        if( printProgress )\r\n        {\r\n            std::cout << std::setprecision(3) << \"Iteration: \" << iteration << \"\\tRMS Error: \" << 1000*std::sqrt(error_this.head(3*numberOfMeasurements).squaredNorm()/(3*numberOfMeasurements)) << \" mT\\tDelta RMS Error: \" <<  deltaRmsError*1000  << \" mT\\tPercent Error Change: \" << percentErrorChange << \"%\" << \"\\tPercent State Change: \" << percentStateChange << \"%\\tTolerance: \" << converganceTolerance << \"\\tDONE!\"<<std::endl<<std::endl;\r\n        }\r\n\r\n\r\n        applyPHI(states);\r\n\r\n        if( constraint != UNIT_HEADING_ONLY && ! checkSourcePositions( printProgress ) )\r\n        {\r\n            if( maximumSourceToCenterDistance > 0 )\r\n                rMaxSq = std::max(rMinSq*1.001, std::pow(maximumSourceToCenterDistance,2));\r\n\r\n            minRadIsActive = true;\r\n            nConst = 2;\r\n            posWeight *= 2;\r\n            converged = false;\r\n\r\n            if( printProgress )\r\n                cout << \"Resolving to move sources out of workspace\" << endl;\r\n        }\r\n\r\n    }while(!converged);\r\n\r\n\r\n    // remove any residual errors\r\n    // initialize coefficients with linear least squares\r\n    linearLeastSquareCoeffFit(dataList);\r\n\r\n\r\n    if( printStats_ )\r\n        printStats( dataList);\r\n\r\n    return;\r\n}\r\n\r\nvoid ElectromagnetCalibration::linearLeastSquareCoeffFit(const std::vector<MagneticMeasurement> &dataList)\r\n{\r\n    // ************ INITIALIZE COEFFICIENTS WITH LINEAR LEAST SQUARES ***************** //\r\n    Eigen::VectorXd E(numberOfMeasurements*3);\r\n    Eigen::MatrixXd JtJ(numberOfParameters - numberOfSources*6, numberOfParameters-numberOfSources*6);\r\n    Eigen::MatrixXd J(3*numberOfMeasurements, numberOfParameters - numberOfSources*6);\r\n\r\n    // Pack Error\r\n    unsigned int phiRowNum = 0;\r\n    unsigned int coilNum;\r\n    std::vector<ScalorPotential>::iterator coilIT;\r\n    std::vector<MagneticMeasurement>::const_iterator measIT;\r\n    for( coilIT = coilList.begin(), coilNum = 0;\r\n         coilIT != coilList.end();\r\n         coilIT ++, coilNum ++ )\r\n    {\r\n        // for each source\r\n        int srcNum;\r\n        std::vector<ScalorPotential::srcStruct>::iterator srcIT;\r\n        for( srcIT = coilIT->srcList.begin(), srcNum = 0;\r\n             srcIT != coilIT->srcList.end();\r\n             srcIT ++, srcNum++ )\r\n        {\r\n            int numParam = coilIT->getNumCalibrationParameters( srcNum );\r\n\r\n            int measColInd;\r\n            for( measIT = dataList.begin(), measColInd = 0;\r\n                 measIT != dataList.end();\r\n                 measIT ++, measColInd+=3)\r\n            {\r\n                Eigen::MatrixXd Ft,Hessian;\r\n                Ft.setZero(numParam,3);\r\n                Hessian.setZero(numParam,numParam);\r\n                coilIT->packJacobians(srcNum, measIT->AppliedCurrentVector(coilNum), measIT->Position, -measIT->Field, Ft, Hessian);\r\n\r\n\r\n                J.block(measColInd, phiRowNum, 3, numParam-6 ) = Ft.topRows(numParam-6).transpose();\r\n\r\n                E.segment(measColInd,3) = -measIT->Field;\r\n            }\r\n            phiRowNum += numParam-6;\r\n        }\r\n    }\r\n\r\n    if( useOffset() )\r\n    {\r\n        // for each offset source\r\n        int srcNum;\r\n        std::vector<ScalorPotential::srcStruct>::iterator srcIT;\r\n        for( srcIT = offset.srcList.begin(), srcNum = 0;\r\n             srcIT != offset.srcList.end();\r\n             srcIT ++, srcNum++ )\r\n        {\r\n            int numParam = offset.getNumCalibrationParameters( srcNum );\r\n\r\n            int measColInd;\r\n            for( measIT = dataList.begin(), measColInd = 0;\r\n                 measIT != dataList.end();\r\n                 measIT ++,  measColInd+=3)\r\n            {\r\n                Eigen::MatrixXd Ft,Hessian;\r\n                Ft.setZero(numParam,3);\r\n                Hessian.setZero(numParam,numParam);\r\n                offset.packJacobians(srcNum, 1.0, measIT->Position, -measIT->Field, Ft, Hessian);\r\n\r\n\r\n                J.block(measColInd, phiRowNum, 3, numParam-6) = Ft.topRows(numParam-6).transpose();\r\n\r\n                E.segment(measColInd, 3) = (-measIT->Field);\r\n            }\r\n            phiRowNum += numParam-6;\r\n        }\r\n    }\r\n\r\n    JtJ = J.transpose()*J;\r\n    Eigen::VectorXd PHI = -JtJ.fullPivLu().solve(J.transpose()*E);\r\n\r\n    // apply initial coefficient fit to parameters\r\n    phiRowNum = 0;\r\n    for( coilIT = coilList.begin(), coilNum = 0;\r\n         coilIT != coilList.end();\r\n         coilIT ++, coilNum ++ )\r\n    {\r\n        // for each source\r\n        int srcNum;\r\n        std::vector<ScalorPotential::srcStruct>::iterator srcIT;\r\n        for( srcIT = coilIT->srcList.begin(), srcNum = 0;\r\n             srcIT != coilIT->srcList.end();\r\n             srcIT ++, srcNum++ )\r\n        {\r\n\r\n            std::vector<ScalorPotential::srcCoeff>::iterator coeffIT;\r\n            for( coeffIT = srcIT->A_Coeff.begin(); coeffIT != srcIT->A_Coeff.end(); coeffIT ++, phiRowNum++ )\r\n            {\r\n                coeffIT->coeff = PHI(phiRowNum);\r\n            }\r\n            for( coeffIT = srcIT->B_Coeff.begin(); coeffIT != srcIT->B_Coeff.end(); coeffIT ++, phiRowNum++ )\r\n            {\r\n                coeffIT->coeff = PHI(phiRowNum);\r\n            }\r\n\r\n        }\r\n    }\r\n\r\n    if( useOffset() )\r\n    {\r\n        // for each offset source\r\n        int srcNum;\r\n        std::vector<ScalorPotential::srcStruct>::iterator srcIT;\r\n        for( srcIT = offset.srcList.begin(), srcNum = 0;\r\n             srcIT != offset.srcList.end();\r\n             srcIT ++, srcNum++ )\r\n        {\r\n            std::vector<ScalorPotential::srcCoeff>::iterator coeffIT;\r\n            for( coeffIT = srcIT->A_Coeff.begin(); coeffIT != srcIT->A_Coeff.end(); coeffIT ++, phiRowNum++ )\r\n            {\r\n                coeffIT->coeff = PHI(phiRowNum);\r\n            }\r\n            for( coeffIT = srcIT->B_Coeff.begin(); coeffIT != srcIT->B_Coeff.end(); coeffIT ++, phiRowNum++ )\r\n            {\r\n                coeffIT->coeff = PHI(phiRowNum);\r\n            }\r\n        }\r\n    }\r\n\r\n}\r\n\r\nvoid ElectromagnetCalibration::applyPHI(const Eigen::VectorXd& PHI )\r\n{\r\n    // initialize PHI leave all Lambda's Initialized to Zero\r\n    unsigned int paramCount = 0;\r\n    for( std::vector<ScalorPotential>::iterator coilIT = coilList.begin(); coilIT != coilList.end(); coilIT ++)\r\n    {\r\n        int numParam = coilIT->getNumCalibrationParameters();\r\n        coilIT->unpackCalibrationState( PHI.segment(paramCount,numParam) );\r\n        paramCount += numParam;\r\n    }\r\n    if( useOffset() )\r\n    {\r\n        int numParam = offset.getNumCalibrationParameters();\r\n        offset.unpackCalibrationState( PHI.segment(paramCount,numParam) );\r\n        paramCount += numParam;\r\n    }\r\n}\r\n\r\nvoid ElectromagnetCalibration::obtainPHI( Eigen::VectorXd& PHI )\r\n{\r\n    // initialize PHI leave all Lambda's Initialized to Zero\r\n    unsigned int paramCount = 0;\r\n    for( std::vector<ScalorPotential>::iterator coilIT = coilList.begin(); coilIT != coilList.end(); coilIT ++)\r\n    {\r\n        int numParam = coilIT->getNumCalibrationParameters();\r\n        coilIT->packCalibrationState( PHI.segment(paramCount,numParam) );\r\n        paramCount += numParam;\r\n    }\r\n    if( useOffset() )\r\n    {\r\n        int numParam = offset.getNumCalibrationParameters();\r\n        offset.packCalibrationState( PHI.segment(paramCount,numParam) );\r\n        paramCount += numParam;\r\n    }\r\n}\r\n\r\nvoid ElectromagnetCalibration::packError( Eigen::VectorXd& error, const std::vector<MagneticMeasurement> & dataList )\r\n{\r\n    // update measurement error\r\n    assert(('Error Vector is the Wrong Size', error.rows() == 3*numberOfMeasurements + numberOfConstraints));\r\n\r\n    int measInd;\r\n    std::vector<MagneticMeasurement>::const_iterator measIT;\r\n    for( measIT = dataList.begin(), measInd = 0;\r\n         measIT != dataList.end();\r\n         measIT ++, measInd += 3 )\r\n    {\r\n        assert( ('ElectromagnetCalibration::packError:  Measurement Index Out of Bounds', measInd+2 < 3*dataList.size()) );\r\n        error.segment(measInd,3) = fieldAtPoint(measIT->AppliedCurrentVector,measIT->Position)-measIT->Field;\r\n    }\r\n\r\n    if( nConst > 0 )\r\n    {\r\n        // update Constraint Error\r\n        std::vector<ScalorPotential>::iterator coilIT;\r\n        for( coilIT = coilList.begin(); coilIT != coilList.end(); coilIT ++ )\r\n        {\r\n            // for each source\r\n            std::vector<ScalorPotential::srcStruct>::iterator srcIT;\r\n            for( srcIT = coilIT->srcList.begin();\r\n                 srcIT != coilIT->srcList.end();\r\n                 srcIT ++, measInd+=nConst)\r\n            {\r\n\r\n                assert( ('ElectromagnetCalibration::packError:  Measurement Index Out of Bounds', measInd < error.rows()) );\r\n                error(measInd) = srcIT->srcDirection.squaredNorm()-1;\r\n\r\n                if( nConst == 2 )\r\n                {\r\n                    // srcPosition Constraint Addition\r\n                    double rSqSrc = (srcIT->srcPosition - pCenter).squaredNorm();\r\n                    double rSqRatio = 1;\r\n                    double rSqW = 1;\r\n\r\n                    if( minRadIsActive && rSqSrc <= rMinSq && srcIT->A_Coeff.size() == 0 )\r\n                    {\r\n                        rSqRatio = rSqSrc/rMinSq;\r\n                        rSqW = 1.001*rMinSq;\r\n                    }\r\n                    else if(rSqSrc >= rMaxSq )\r\n                    {\r\n                        rSqRatio = rSqSrc/rMaxSq;\r\n                        rSqW = 0.999*rMaxSq;\r\n                    }\r\n\r\n                    error(measInd+1) = posWeight*(rSqRatio - 1);\r\n\r\n                }\r\n            }\r\n        }\r\n\r\n        if( useOffset() )\r\n        {\r\n            // for each offset source\r\n            std::vector<ScalorPotential::srcStruct>::iterator srcIT;\r\n            for( srcIT = offset.srcList.begin(); srcIT != offset.srcList.end(); srcIT ++, measInd += nConst)\r\n            {\r\n\r\n                assert( ('ElectromagnetCalibration::packError:  Measurement Index Out of Bounds', measInd < error.rows()) );\r\n                error(measInd) = srcIT->srcDirection.squaredNorm()-1;\r\n\r\n\r\n                if( nConst == 2)\r\n                {\r\n                    // srcPosition Constraint Addition\r\n                    double rSqSrc = (srcIT->srcPosition - pCenter).squaredNorm();\r\n                    double rSqRatio = 1;\r\n                    double rSqW = 1;\r\n\r\n                    if( minRadIsActive && rSqSrc <= rMinSq && srcIT->A_Coeff.size() == 0 )\r\n                    {\r\n                        rSqRatio = rSqSrc/rMinSq;\r\n                        rSqW = 1.001*rMinSq;\r\n                    }\r\n                    else if(rSqSrc >= rMaxSq )\r\n                    {\r\n                        rSqRatio = rSqSrc/rMaxSq;\r\n                        rSqW = 0.999*rMaxSq;\r\n                    }\r\n\r\n                    error(measInd+1) = posWeight*(rSqRatio - 1);\r\n\r\n\r\n                }\r\n            }\r\n\r\n        }\r\n    }\r\n}\r\n\r\nvoid ElectromagnetCalibration::packErrorJacobian( Eigen::MatrixXd& J, const std::vector<MagneticMeasurement> & dataList  )\r\n{  \r\n    // Pack Jacobian\r\n    unsigned int phiRowNum = 0;\r\n    unsigned int coilNum;\r\n    std::vector<ScalorPotential>::iterator coilIT;\r\n    for( coilIT = coilList.begin(), coilNum = 0;\r\n         coilIT != coilList.end();\r\n         coilIT ++, coilNum ++ )\r\n    {\r\n        // for each source\r\n        int srcNum;\r\n        std::vector<ScalorPotential::srcStruct>::iterator srcIT;\r\n        for( srcIT = coilIT->srcList.begin(), srcNum = 0;\r\n             srcIT != coilIT->srcList.end();\r\n             srcIT ++, srcNum++ )\r\n        {\r\n            int numParam = coilIT->getNumCalibrationParameters( srcNum );\r\n\r\n            int measColInd;\r\n            std::vector<MagneticMeasurement>::const_iterator measIT;\r\n            for(measIT = dataList.begin(), measColInd = 0;\r\n                measIT != dataList.end();\r\n                measIT ++, measColInd+=3)\r\n            {\r\n                Eigen::MatrixXd Ft,Hessian;\r\n                Ft.setZero(numParam,3);\r\n                Hessian.setZero(numParam,numParam);\r\n                coilIT->packJacobians(srcNum, measIT->AppliedCurrentVector(coilNum), measIT->Position, Eigen::Vector3d(0,0,0), Ft, Hessian);\r\n\r\n\r\n                J.block(measColInd, phiRowNum, 3, numParam ) = Ft.transpose();\r\n            }\r\n            phiRowNum += numParam;\r\n        }\r\n    }\r\n\r\n    if( useOffset() )\r\n    {\r\n        // for each offset source\r\n        int srcNum;\r\n        std::vector<ScalorPotential::srcStruct>::iterator srcIT;\r\n        for( srcIT = offset.srcList.begin(), srcNum = 0;\r\n             srcIT != offset.srcList.end();\r\n             srcIT ++, srcNum++ )\r\n        {\r\n            int numParam = offset.getNumCalibrationParameters( srcNum );\r\n\r\n            int measColInd;\r\n            std::vector<MagneticMeasurement>::const_iterator measIT;\r\n            for(measIT = dataList.begin(), measColInd = 0;\r\n                measIT != dataList.end();\r\n                measIT ++, measColInd+=3)\r\n            {\r\n                Eigen::MatrixXd Ft,Hessian;\r\n                Ft.setZero(numParam,3);\r\n                Hessian.setZero(numParam,numParam);\r\n                offset.packJacobians(srcNum, 1.0, measIT->Position, Eigen::Vector3d(0,0,0), Ft, Hessian);\r\n\r\n                J.block(measColInd, phiRowNum, 3, numParam ) = Ft.transpose();;\r\n            }\r\n            phiRowNum += numParam;\r\n        }\r\n    }\r\n\r\n\r\n    if( nConst > 0 )\r\n    {\r\n        // Add In Constraint Terms\r\n        int constraintNum = 0;\r\n        phiRowNum = 0;\r\n        int measColInd = numberOfMeasurements*3;\r\n        for( coilIT = coilList.begin(); coilIT != coilList.end(); coilIT ++ )\r\n        {\r\n            // for each source\r\n            int srcNum;\r\n            std::vector<ScalorPotential::srcStruct>::iterator srcIT;\r\n            for( srcIT = coilIT->srcList.begin(), srcNum = 0; srcIT != coilIT->srcList.end();\r\n                 srcIT ++, srcNum++, measColInd+=nConst)\r\n            {\r\n                int numParam = coilIT->getNumCalibrationParameters( srcNum );\r\n                J.block(measColInd, phiRowNum+numParam-6, 1, 3) = 2*srcIT->srcDirection.transpose();\r\n\r\n                if( nConst ==2 )\r\n                {\r\n                    // srcPosition Constraint Addition\r\n                    double rSqSrc = (srcIT->srcPosition - pCenter).squaredNorm();\r\n                    double rSqRatio = 1;\r\n                    double rSqW = 1;\r\n\r\n                    if( minRadIsActive && rSqSrc <= rMinSq && srcIT->A_Coeff.size() == 0 )\r\n                    {\r\n                        rSqRatio = rSqSrc/rMinSq;\r\n                        rSqW = 1.001*rMinSq;\r\n                    }\r\n                    else if(rSqSrc >= rMaxSq )\r\n                    {\r\n                        rSqRatio = rSqSrc/rMaxSq;\r\n                        rSqW = 0.999*rMaxSq;\r\n                    }\r\n\r\n                    J.block(measColInd+1, phiRowNum+numParam-3, 1, 3) = 2.0*posWeight*(srcIT->srcPosition - pCenter).transpose()/rSqW;\r\n\r\n                }\r\n\r\n                phiRowNum += numParam;\r\n            }\r\n        }\r\n\r\n        if( useOffset() )\r\n        {\r\n            // for each offset source\r\n            int srcNum;\r\n            std::vector<ScalorPotential::srcStruct>::iterator srcIT;\r\n            for( srcIT = offset.srcList.begin(), srcNum = 0; srcIT != offset.srcList.end();\r\n                 srcIT ++, srcNum++, measColInd += nConst)\r\n            {\r\n                int numParam = offset.getNumCalibrationParameters( srcNum );\r\n\r\n                J.block(measColInd, phiRowNum+numParam-6, 1, 3) = 2*srcIT->srcDirection.transpose();\r\n\r\n                if( nConst == 2)\r\n                {\r\n                    // srcPosition Constraint Addition\r\n                    double rSqSrc = (srcIT->srcPosition - pCenter).squaredNorm();\r\n                    double rSqRatio = 1;\r\n                    double rSqW = 1;\r\n\r\n                    if( minRadIsActive && rSqSrc <= rMinSq && srcIT->A_Coeff.size() == 0 )\r\n                    {\r\n                        rSqRatio = rSqSrc/rMinSq;\r\n                        rSqW = 1.001*rMinSq;\r\n                    }\r\n                    else if(rSqSrc >= rMaxSq )\r\n                    {\r\n                        rSqRatio = rSqSrc/rMaxSq;\r\n                        rSqW = 0.999*rMaxSq;\r\n                    }\r\n\r\n                    J.block(measColInd+1, phiRowNum+numParam-3, 1, 3) = 2.0*posWeight*(srcIT->srcPosition - pCenter).transpose()/rSqW;\r\n\r\n                }\r\n\r\n                phiRowNum += numParam;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n\r\nvoid ElectromagnetCalibration::printStats( const std::vector< MagneticMeasurement >& dataList) const\r\n{\r\n\r\n\r\n    double percentError = 0;\r\n    double SS_res = 0;\r\n    double SS_total = 0;\r\n    double SS_field = 0;\r\n\r\n    Eigen::Vector3d avgFieldError(0,0,0);\r\n    Eigen::Vector3d fieldTmp;\r\n    Eigen::Vector3d avgField(Eigen::Vector3d::Zero());\r\n\r\n    std::vector<MagneticMeasurement>::const_iterator dataIT;\r\n\r\n    for( dataIT  = dataList.begin();\r\n         dataIT != dataList.end();\r\n         dataIT++ )\r\n    {\r\n        SS_field += dataIT->Field.squaredNorm();\r\n\r\n    }\r\n    double rmsField = std::sqrt(SS_field/(double)dataList.size()/3.0);\r\n\r\n    double averageFielddMag = 0;\r\n    for( dataIT  = dataList.begin();\r\n         dataIT != dataList.end();\r\n         dataIT++ )\r\n    {\r\n        avgField += dataIT->Field;\r\n        averageFielddMag += dataIT->Field.norm();\r\n        fieldTmp = fieldAtPoint(dataIT->AppliedCurrentVector, dataIT->Position );\r\n        avgFieldError += (dataIT->Field - fieldTmp);\r\n        percentError += sqrt((dataIT->Field - fieldTmp).squaredNorm()/3.0)/rmsField;//dataIT->Field.norm();\r\n        SS_res += (dataIT->Field - fieldTmp).squaredNorm();\r\n        SS_total += dataIT->Field.squaredNorm();\r\n    }\r\n\r\n    avgField /= (double) dataList.size();\r\n    averageFielddMag /= (double) dataList.size();\r\n    avgFieldError /= (double) dataList.size();\r\n    Eigen::Matrix3d errorVariance; errorVariance.setZero(3,3);\r\n\r\n\r\n    Eigen::Matrix3d fieldVar(Eigen::Matrix3d::Zero());\r\n    for( dataIT  = dataList.begin();\r\n         dataIT != dataList.end();\r\n         dataIT++ )\r\n    {\r\n\r\n\r\n        fieldTmp = fieldAtPoint(dataIT->AppliedCurrentVector, dataIT->Position );\r\n        Eigen::Vector3d fieldError = (dataIT->Field - fieldTmp);\r\n        Eigen::Vector3d errorDiff = fieldError-avgFieldError;\r\n        errorVariance += errorDiff*errorDiff.transpose();\r\n\r\n        errorDiff = dataIT->Field-avgField;\r\n        fieldVar += errorDiff*errorDiff.transpose();\r\n    }\r\n\r\n    fieldVar /= ((double) dataList.size()-1);\r\n    errorVariance /= ((double) dataList.size()-1);\r\n\r\n    percentError /= (double) dataList.size()/100.0;\r\n    double rmsError_out = std::sqrt(SS_res/(double)dataList.size()/3.0);\r\n    double rmsError_normalized = rmsError_out/std::sqrt(SS_field/(double)dataList.size()/3.0);\r\n    double R_squared_out = 1- SS_res/SS_total;\r\n\r\n\r\n\r\n    Eigen::JacobiSVD<Eigen::Matrix3d> varSVD(errorVariance,Eigen::ComputeFullU|Eigen::ComputeFullV);\r\n    Eigen::Matrix3d S = varSVD.singularValues().asDiagonal();\r\n    for( int i=0;i<3;i++ )\r\n        S(i,i) = sqrt(S(i,i));\r\n    Eigen::Matrix3d stdFieldErr = varSVD.matrixU()*S*varSVD.matrixV().transpose();\r\n\r\n    cout << getName() << endl\r\n         << \"  Percent Error:\\t\" << setprecision(4) << percentError << \"%\" << endl\r\n         << \"  RMS Error:\\t\" << setprecision(4) << rmsError_out << endl\r\n         << \"  RMS Error/RMS Field: \" << setprecision(4) << rmsError_normalized*100 <<\"%\"<< endl\r\n         << \"  R^2:\\t\\t\" << setprecision(9) << R_squared_out << endl\r\n         << \"  Average Field Magnitude: \" << setprecision(4) << averageFielddMag*1000 << \" mT\" << endl\r\n         << \"  Average Field Error:\\t(\" << setprecision(4) << (avgFieldError.transpose()*1000) << \") mT\" << endl\r\n         << \"  Average Field Error:\\t(\" << setprecision(4) << (avgFieldError.transpose()/averageFielddMag)*100 << \") %\" << endl\r\n         << \"  \\nField Error Variance:\\n\" << \"---------------\\n\" << setprecision(4) << avgFieldError << endl << \"---------------\" << endl\r\n         << \"  \\nField Error stdev [mT]:\\n\" << \"---------------\\n\" << setprecision(4) << stdFieldErr*1000 << endl << \"---------------\" << endl\r\n         << \"  \\nField Error stdev [%]:\\n\" << \"---------------\\n\" << setprecision(4) << stdFieldErr/averageFielddMag*100 << endl << \"---------------\" << endl;\r\n\r\n    cout << endl;\r\n\r\n    return;\r\n}\r\n", "meta": {"hexsha": "12c0610527a7483106431203060c5a716512140e", "size": 62828, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "electromagnet_calibration.cpp", "max_stars_repo_name": "M3R-CSM/electromagnet-calibration", "max_stars_repo_head_hexsha": "92082e7babce97ae896eaacc7b2bdda671deb6e7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T04:08:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T00:48:33.000Z", "max_issues_repo_path": "electromagnet_calibration.cpp", "max_issues_repo_name": "M3R-CSM/electromagnet-calibration", "max_issues_repo_head_hexsha": "92082e7babce97ae896eaacc7b2bdda671deb6e7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "electromagnet_calibration.cpp", "max_forks_repo_name": "M3R-CSM/electromagnet-calibration", "max_forks_repo_head_hexsha": "92082e7babce97ae896eaacc7b2bdda671deb6e7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7587908698, "max_line_length": 439, "alphanum_fraction": 0.5791207742, "num_tokens": 14969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8519528132451417, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.42264853365130545}}
{"text": "\r\n#include <boost/random/mersenne_twister.hpp>\r\n#include <boost/numeric/ublas/matrix.hpp>\r\n#include <boost/random/uniform_real_distribution.hpp>\r\n\r\n\r\n\r\n#include <include/grassmann_pca.hpp>\r\n#include <include/private/boost_ublas_row_iterator.hpp>\r\n\r\n\r\n\r\n// generating a matrix of random numbers, each row will contain\r\n// a data vector.\r\ntemplate <class matrix_t>\r\nvoid generate_matrix(const int nb_elements, const int dimension, matrix_t& mat_data)\r\n{\r\n  static boost::random::mt19937 rng;\r\n  boost::random::uniform_real_distribution<double> dist(-1000, 1000);\r\n  \r\n  mat_data.resize(nb_elements, dimension);\r\n  for(int i = 0; i < nb_elements; i++)\r\n  {\r\n    for(int j = 0; j < dimension; j++)\r\n    {\r\n      mat_data(i, j) = dist(rng);\r\n    }\r\n  }\r\n}\r\n\r\nvoid example_grassmann_pca_impl()\r\n{\r\n  using namespace grassmann_averages_pca;\r\n  using namespace grassmann_averages_pca::details::ublas_helpers;\r\n  namespace ub = boost::numeric::ublas;\r\n\r\n  \r\n  typedef ub::vector<double> data_t;                         // type of the vectors \r\n  typedef ub::matrix<double> matrix_t;                       // type of the structure holding the data\r\n\r\n  typedef grassmann_pca< data_t > grassmann_pca_t;           // the type of the structure for the computation of the grassmann averages pca\r\n                                                             // data_t tells which kind of structure will be used for internal computations\r\n                                                             // and will be received from the data iterators.\r\n  \r\n  typedef row_iter<const matrix_t> const_row_iter_t;         // iterator on the data, deferencing one\r\n                                                             // of these iterator should yield a structure\r\n                                                             // convertible to data_t. This iterator iterates \r\n                                                             // over the rows of a given matrix.\r\n\r\n  \r\n  const int dimensions = 5;                   // each vector is of dimension 5\r\n  const int max_dimension_to_compute = 3;     // we want only the first 3 basis-vectors\r\n  const int max_iterations = 1000;            // at most 1000 iterations before giving up for the current dimension\r\n  \r\n  // generating the data points\r\n  matrix_t mat_data;\r\n  generate_matrix(10000, dimensions, mat_data);\r\n\r\n\r\n  // configure the first points\r\n  const double initial_point[] = {0.2097, 0.3959, 0.5626, 0.2334, 0.6545}; // some dummy initial point\r\n  data_t vec_initial_point(dimensions);\r\n  std::copy(initial_point, initial_point + dimensions, vec_initial_point.begin());\r\n  std::vector< data_t > v_init_points(max_dimension_to_compute, vec_initial_point);\r\n\r\n  // allocate the output\r\n  std::vector<data_t> basis_vectors(max_dimension_to_compute);\r\n  \r\n  // the instance\r\n  grassmann_pca_t instance;\r\n  \r\n  // some configuration\r\n  if(!instance.set_nb_processors(4))              // using 4 processors\r\n  {\r\n    std::cerr << \"Error while setting the number of threads\" << std::endl;\r\n    return;\r\n  }\r\n  \r\n  if(!instance.set_max_chunk_size(1000))          // using max chunk size of 1000\r\n  {\r\n    std::cerr << \"Error while setting the chunk size\" << std::endl;\r\n    return;\r\n  }\r\n  \r\n  if(!instance.set_nb_steps_pca(3))               // using 3 PCA steps\r\n  {\r\n    std::cerr << \"Error while setting the number of PCA steps\" << std::endl;\r\n    return;\r\n  }\r\n  \r\n  \r\n  bool return_calue = instance.batch_process(\r\n    max_iterations,\r\n    max_dimension_to_compute,\r\n    const_row_iter_t(mat_data, 0),\r\n    const_row_iter_t(mat_data, mat_data.size1()),\r\n    basis_vectors.begin(),\r\n    &v_init_points);\r\n\r\n  if(!return_calue)\r\n  {\r\n    std::cerr << \"Error during the computation of the GrassmannAveragesPCA\" << std::endl;  \r\n  }\r\n}\r\n", "meta": {"hexsha": "9eec7fc3cebd5e13f422fbd8380314e6bf1bedd7", "size": 3784, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/example_grassmannpca.cpp", "max_stars_repo_name": "MPI-Intelligent-Systems-Tuebingen/-Grassmann-Averages-PCA", "max_stars_repo_head_hexsha": "247ed7c8125057b55fc7ef3f26e8c106e09b8ad0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-07-15T11:14:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-08T01:47:55.000Z", "max_issues_repo_path": "test/example_grassmannpca.cpp", "max_issues_repo_name": "MPI-Intelligent-Systems-Tuebingen/-Grassmann-Averages-PCA", "max_issues_repo_head_hexsha": "247ed7c8125057b55fc7ef3f26e8c106e09b8ad0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-24T17:28:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-24T17:28:19.000Z", "max_forks_repo_path": "test/example_grassmannpca.cpp", "max_forks_repo_name": "MPI-Intelligent-Systems-Tuebingen/-Grassmann-Averages-PCA", "max_forks_repo_head_hexsha": "247ed7c8125057b55fc7ef3f26e8c106e09b8ad0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-11T12:33:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T12:51:49.000Z", "avg_line_length": 36.0380952381, "max_line_length": 140, "alphanum_fraction": 0.6197145877, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4223284998879599}}
{"text": "// Copyright 2002 Rensselaer Polytechnic Institute\r\n\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  Authors: Lauren Foutz\r\n//           Scott Hill\r\n\r\n/*\r\n  This file implements the functions\r\n\r\n  template <class VertexListGraph, class DistanceMatrix, \r\n    class P, class T, class R>\r\n  bool floyd_warshall_initialized_all_pairs_shortest_paths(\r\n    const VertexListGraph& g, DistanceMatrix& d, \r\n    const bgl_named_params<P, T, R>& params)\r\n\r\n  AND\r\n\r\n  template <class VertexAndEdgeListGraph, class DistanceMatrix, \r\n    class P, class T, class R>\r\n  bool floyd_warshall_all_pairs_shortest_paths(\r\n    const VertexAndEdgeListGraph& g, DistanceMatrix& d, \r\n    const bgl_named_params<P, T, R>& params)\r\n*/\r\n\r\n\r\n#ifndef BOOST_GRAPH_FLOYD_WARSHALL_HPP\r\n#define BOOST_GRAPH_FLOYD_WARSHALL_HPP\r\n\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/named_function_params.hpp>\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/graph/relax.hpp>\r\n#include <boost/concept/assert.hpp>\r\n\r\nnamespace boost\r\n{\r\n  namespace detail {\r\n    template<typename T, typename BinaryPredicate>\r\n    T min_with_compare(const T& x, const T& y, const BinaryPredicate& compare)\r\n    {\r\n      if (compare(x, y)) return x; \r\n      else return y;\r\n    }\r\n\r\n    template<typename VertexListGraph, typename DistanceMatrix, \r\n      typename BinaryPredicate, typename BinaryFunction,\r\n      typename Infinity, typename Zero>\r\n    bool floyd_warshall_dispatch(const VertexListGraph& g, \r\n      DistanceMatrix& d, const BinaryPredicate &compare, \r\n      const BinaryFunction &combine, const Infinity& inf, \r\n      const Zero& zero)\r\n    {\r\n      typename graph_traits<VertexListGraph>::vertex_iterator \r\n        i, lasti, j, lastj, k, lastk;\r\n    \r\n      \r\n      for (boost::tie(k, lastk) = vertices(g); k != lastk; k++)\r\n        for (boost::tie(i, lasti) = vertices(g); i != lasti; i++)\r\n          if(d[*i][*k] != inf)\r\n            for (boost::tie(j, lastj) = vertices(g); j != lastj; j++)\r\n              if(d[*k][*j] != inf)\r\n                d[*i][*j] = \r\n                  detail::min_with_compare(d[*i][*j], \r\n                                           combine(d[*i][*k], d[*k][*j]),\r\n                                           compare);\r\n      \r\n      \r\n      for (boost::tie(i, lasti) = vertices(g); i != lasti; i++)\r\n        if (compare(d[*i][*i], zero))\r\n          return false;\r\n      return true;\r\n    }\r\n  }\r\n\r\n  template <typename VertexListGraph, typename DistanceMatrix, \r\n    typename BinaryPredicate, typename BinaryFunction,\r\n    typename Infinity, typename Zero>\r\n  bool floyd_warshall_initialized_all_pairs_shortest_paths(\r\n    const VertexListGraph& g, DistanceMatrix& d, \r\n    const BinaryPredicate& compare, \r\n    const BinaryFunction& combine, const Infinity& inf, \r\n    const Zero& zero)\r\n  {\r\n    BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<VertexListGraph> ));\r\n  \r\n    return detail::floyd_warshall_dispatch(g, d, compare, combine, \r\n    inf, zero);\r\n  }\r\n  \r\n\r\n  \r\n  template <typename VertexAndEdgeListGraph, typename DistanceMatrix, \r\n    typename WeightMap, typename BinaryPredicate, \r\n    typename BinaryFunction, typename Infinity, typename Zero>\r\n  bool floyd_warshall_all_pairs_shortest_paths(\r\n    const VertexAndEdgeListGraph& g, \r\n    DistanceMatrix& d, const WeightMap& w, \r\n    const BinaryPredicate& compare, const BinaryFunction& combine, \r\n    const Infinity& inf, const Zero& zero)\r\n  {\r\n    BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<VertexAndEdgeListGraph> ));\r\n    BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<VertexAndEdgeListGraph> ));\r\n    BOOST_CONCEPT_ASSERT(( IncidenceGraphConcept<VertexAndEdgeListGraph> ));\r\n  \r\n    typename graph_traits<VertexAndEdgeListGraph>::vertex_iterator \r\n      firstv, lastv, firstv2, lastv2;\r\n    typename graph_traits<VertexAndEdgeListGraph>::edge_iterator first, last;\r\n  \r\n    \r\n    for(boost::tie(firstv, lastv) = vertices(g); firstv != lastv; firstv++)\r\n      for(boost::tie(firstv2, lastv2) = vertices(g); firstv2 != lastv2; firstv2++)\r\n        d[*firstv][*firstv2] = inf;\r\n    \r\n    \r\n    for(boost::tie(firstv, lastv) = vertices(g); firstv != lastv; firstv++)\r\n      d[*firstv][*firstv] = zero;\r\n    \r\n    \r\n    for(boost::tie(first, last) = edges(g); first != last; first++)\r\n    {\r\n      if (d[source(*first, g)][target(*first, g)] != inf) {\r\n        d[source(*first, g)][target(*first, g)] = \r\n          detail::min_with_compare(\r\n            get(w, *first), \r\n            d[source(*first, g)][target(*first, g)],\r\n            compare);\r\n      } else \r\n        d[source(*first, g)][target(*first, g)] = get(w, *first);\r\n    }\r\n    \r\n    bool is_undirected = is_same<typename \r\n      graph_traits<VertexAndEdgeListGraph>::directed_category, \r\n      undirected_tag>::value;\r\n    if (is_undirected)\r\n    {\r\n      for(boost::tie(first, last) = edges(g); first != last; first++)\r\n      {\r\n        if (d[target(*first, g)][source(*first, g)] != inf)\r\n          d[target(*first, g)][source(*first, g)] = \r\n            detail::min_with_compare(\r\n              get(w, *first), \r\n              d[target(*first, g)][source(*first, g)],\r\n              compare);\r\n        else \r\n          d[target(*first, g)][source(*first, g)] = get(w, *first);\r\n      }\r\n    }\r\n    \r\n  \r\n    return detail::floyd_warshall_dispatch(g, d, compare, combine, \r\n      inf, zero);\r\n  }\r\n  \r\n\r\n  namespace detail {        \r\n    template <class VertexListGraph, class DistanceMatrix, \r\n      class WeightMap, class P, class T, class R>\r\n    bool floyd_warshall_init_dispatch(const VertexListGraph& g, \r\n      DistanceMatrix& d, WeightMap /*w*/, \r\n      const bgl_named_params<P, T, R>& params)\r\n    {\r\n      typedef typename property_traits<WeightMap>::value_type WM;\r\n      WM inf =\r\n        choose_param(get_param(params, distance_inf_t()), \r\n          std::numeric_limits<WM>::max BOOST_PREVENT_MACRO_SUBSTITUTION());\r\n    \r\n      return floyd_warshall_initialized_all_pairs_shortest_paths(g, d,\r\n        choose_param(get_param(params, distance_compare_t()), \r\n          std::less<WM>()),\r\n        choose_param(get_param(params, distance_combine_t()), \r\n          closed_plus<WM>(inf)),\r\n        inf,\r\n        choose_param(get_param(params, distance_zero_t()), \r\n          WM()));\r\n    }\r\n    \r\n\r\n    \r\n    template <class VertexAndEdgeListGraph, class DistanceMatrix, \r\n      class WeightMap, class P, class T, class R>\r\n    bool floyd_warshall_noninit_dispatch(const VertexAndEdgeListGraph& g, \r\n      DistanceMatrix& d, WeightMap w, \r\n      const bgl_named_params<P, T, R>& params)\r\n    {\r\n      typedef typename property_traits<WeightMap>::value_type WM;\r\n    \r\n      WM inf =\r\n        choose_param(get_param(params, distance_inf_t()), \r\n          std::numeric_limits<WM>::max BOOST_PREVENT_MACRO_SUBSTITUTION());\r\n      return floyd_warshall_all_pairs_shortest_paths(g, d, w,\r\n        choose_param(get_param(params, distance_compare_t()), \r\n          std::less<WM>()),\r\n        choose_param(get_param(params, distance_combine_t()), \r\n          closed_plus<WM>(inf)),\r\n        inf,\r\n        choose_param(get_param(params, distance_zero_t()), \r\n          WM()));\r\n    }\r\n    \r\n\r\n  }   // namespace detail\r\n\r\n  \r\n  \r\n  template <class VertexListGraph, class DistanceMatrix, class P, \r\n    class T, class R>\r\n  bool floyd_warshall_initialized_all_pairs_shortest_paths(\r\n    const VertexListGraph& g, DistanceMatrix& d, \r\n    const bgl_named_params<P, T, R>& params)\r\n  {\r\n    return detail::floyd_warshall_init_dispatch(g, d, \r\n      choose_const_pmap(get_param(params, edge_weight), g, edge_weight), \r\n      params);\r\n  }\r\n  \r\n  template <class VertexListGraph, class DistanceMatrix>\r\n  bool floyd_warshall_initialized_all_pairs_shortest_paths(\r\n    const VertexListGraph& g, DistanceMatrix& d)\r\n  {\r\n    bgl_named_params<int,int> params(0);\r\n    return detail::floyd_warshall_init_dispatch(g, d,\r\n      get(edge_weight, g), params);\r\n  }\r\n  \r\n\r\n  \r\n  \r\n  template <class VertexAndEdgeListGraph, class DistanceMatrix, \r\n    class P, class T, class R>\r\n  bool floyd_warshall_all_pairs_shortest_paths(\r\n    const VertexAndEdgeListGraph& g, DistanceMatrix& d, \r\n    const bgl_named_params<P, T, R>& params)\r\n  {\r\n    return detail::floyd_warshall_noninit_dispatch(g, d, \r\n      choose_const_pmap(get_param(params, edge_weight), g, edge_weight), \r\n      params);\r\n  }\r\n  \r\n  template <class VertexAndEdgeListGraph, class DistanceMatrix>\r\n  bool floyd_warshall_all_pairs_shortest_paths(\r\n    const VertexAndEdgeListGraph& g, DistanceMatrix& d)\r\n  {\r\n    bgl_named_params<int,int> params(0);\r\n    return detail::floyd_warshall_noninit_dispatch(g, d,\r\n      get(edge_weight, g), params);\r\n  }\r\n  \r\n\r\n} // namespace boost\r\n\r\n#endif\r\n\r\n", "meta": {"hexsha": "dc8ca259ba946b9728e9a7c54dc9a7a452f6f85c", "size": 8850, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/graph/floyd_warshall_shortest.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/graph/floyd_warshall_shortest.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/graph/floyd_warshall_shortest.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 34.4357976654, "max_line_length": 83, "alphanum_fraction": 0.6379661017, "num_tokens": 2171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.42232849988795984}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#define _USE_MATH_DEFINES\n#include \"mesh.h\"\n#include \"transforms.h\"\n\n#include <Eigen/Geometry>\n#include <cmath>\n\nnamespace\n{\n  const float PI = static_cast<float>(M_PI);\n}\n\nnamespace scenepic\n{\n  Vector interpolate(const Vector& p0, const Vector& p1, float alpha)\n  {\n    return alpha * p0 + (1. - alpha) * p1;\n  }\n\n  void Mesh::add_cube(\n    const Color& color,\n    const Transform& transform,\n    bool fill_triangles,\n    bool add_wireframe)\n  {\n    this->check_instances();\n    this->check_color(color);\n    Vector p0(-0.5, -0.5, -0.5);\n    Vector p1(+0.5, -0.5, -0.5);\n    Vector p2(-0.5, +0.5, -0.5);\n    Vector p3(+0.5, +0.5, -0.5);\n    Vector p4(-0.5, -0.5, +0.5);\n    Vector p5(+0.5, -0.5, +0.5);\n    Vector p6(-0.5, +0.5, +0.5);\n    Vector p7(+0.5, +0.5, +0.5);\n\n    Mesh m = Mesh(\"\").shared_color(m_shared_color).texture_id(m_texture_id);\n    m.add_quad(\n      color, p0, p2, p3, p1, VectorNone(), fill_triangles, add_wireframe);\n    m.add_quad(\n      color, p1, p3, p7, p5, VectorNone(), fill_triangles, add_wireframe);\n    m.add_quad(\n      color, p5, p7, p6, p4, VectorNone(), fill_triangles, add_wireframe);\n    m.add_quad(\n      color, p4, p6, p2, p0, VectorNone(), fill_triangles, add_wireframe);\n    m.add_quad(\n      color, p2, p6, p7, p3, VectorNone(), fill_triangles, add_wireframe);\n    m.add_quad(\n      color, p4, p0, p1, p5, VectorNone(), fill_triangles, add_wireframe);\n\n    if (!transform.isIdentity())\n    {\n      m.apply_transform(transform);\n    }\n\n    this->append_mesh(m);\n  }\n\n  void Mesh::add_thickline(\n    const Color& color,\n    const Vector& start_point,\n    const Vector& end_point,\n    float start_thickness,\n    float end_thickness,\n    const Transform& transform_init,\n    bool fill_triangles,\n    bool add_wireframe)\n  {\n    this->check_instances();\n    this->check_color(color);\n\n    // For convenience\n    float length = (end_point - start_point).norm() * 0.5f;\n    start_thickness *= 0.5f;\n    end_thickness *= 0.5f;\n\n    // Create points\n    Vector p0(-length, -start_thickness, -start_thickness);\n    Vector p1(+length, -end_thickness, -end_thickness);\n    Vector p2(-length, +start_thickness, -start_thickness);\n    Vector p3(+length, +end_thickness, -end_thickness);\n    Vector p4(-length, -start_thickness, +start_thickness);\n    Vector p5(+length, -end_thickness, +end_thickness);\n    Vector p6(-length, +start_thickness, +start_thickness);\n    Vector p7(+length, +end_thickness, +end_thickness);\n\n    // Add quads to new mesh\n    Mesh m = Mesh(\"\").shared_color(m_shared_color).texture_id(m_texture_id);\n    m.add_quad(\n      color, p0, p2, p3, p1, VectorNone(), fill_triangles, add_wireframe);\n    m.add_quad(\n      color, p1, p3, p7, p5, VectorNone(), fill_triangles, add_wireframe);\n    m.add_quad(\n      color, p4, p5, p7, p6, VectorNone(), fill_triangles, add_wireframe);\n    m.add_quad(\n      color, p4, p6, p2, p0, VectorNone(), fill_triangles, add_wireframe);\n    m.add_quad(\n      color, p2, p6, p7, p3, VectorNone(), fill_triangles, add_wireframe);\n    m.add_quad(\n      color, p4, p0, p1, p5, VectorNone(), fill_triangles, add_wireframe);\n\n    // Transform if not unit thickline\n    Transform transform = transform_init;\n    if (start_point != VectorNone())\n    {\n      assert(end_point != VectorNone());\n      Vector center = 0.5 * (start_point + end_point);\n      Vector axis = end_point - start_point;\n      length = axis.norm();\n      Transform rotation = Transforms::rotation_to_align_x_to_axis(axis);\n      Transform translation = Transforms::translate(center);\n      Transform tx = translation * rotation;\n      if (transform.isIdentity())\n      {\n        transform = tx;\n      }\n      else\n      {\n        transform *= tx;\n      }\n    }\n\n    if (!transform.isIdentity())\n    {\n      m.apply_transform(transform);\n    }\n\n    this->append_mesh(m);\n  }\n\n  void Mesh::add_cone(\n    const Color& color,\n    const Transform& transform,\n    float truncation_height,\n    std::uint32_t lat_count,\n    std::uint32_t long_count,\n    bool fill_triangles,\n    bool add_wireframe)\n  {\n    this->check_instances();\n    this->check_color(color);\n\n    const float radius = 0.5f;\n    Vector apex(-0.5f, 0., 0.);\n    bool add_apex = std::abs(truncation_height - 1.) < 1e-6;\n    const float base_center_x = 0.5f;\n    Mesh m = Mesh(\"\").shared_color(m_shared_color);\n    for (std::uint32_t lat_index = 0; lat_index < lat_count; ++lat_index)\n    {\n      float alpha = static_cast<float>(lat_index) / lat_count;\n      alpha = alpha * truncation_height;\n\n      for (std::uint32_t long_index = 0; long_index < long_count; ++long_index)\n      {\n        float phi = long_index * 2.0f * PI / long_count;\n        float cosPhi = std::cos(phi);\n        float sinPhi = std::sin(phi);\n\n        Vector base_point(base_center_x, cosPhi * radius, sinPhi * radius);\n        Vector xyz = interpolate(apex, base_point, alpha);\n        Vector normal = (base_point - apex).cross(xyz - Vector(xyz(0), 0, 0));\n        normal = normal.cross(base_point - apex);\n        normal.normalize();\n        m.append_vertex(xyz, normal, color);\n      }\n    }\n\n    if (add_apex)\n    {\n      m.append_vertex(apex, Vector(-1, 0, 0), color);\n    }\n\n    for (std::uint32_t lat_index = 0; lat_index < lat_count - 1; ++lat_index)\n    {\n      for (std::uint32_t long_index = 0; long_index < long_count; ++long_index)\n      {\n        auto base_index = lat_index * long_count;\n        auto a = base_index + long_index;\n        auto b = base_index + (long_index + 1) % long_count;\n        auto c = base_index + long_index + long_count;\n        auto d = base_index + (long_index + 1) % long_count + long_count;\n        if (fill_triangles)\n        {\n          m.append_triangle(b, a, c);\n          m.append_triangle(b, c, d);\n        }\n\n        if (add_wireframe)\n        {\n          m.append_line(a, b);\n          m.append_line(b, d);\n          m.append_line(d, c);\n          m.append_line(c, a);\n        }\n      }\n    }\n\n    if (add_apex)\n    {\n      std::uint32_t lat_index = lat_count - 1;\n      auto a = lat_count * long_count;\n      for (std::uint32_t long_index = 0; long_index < long_count; ++long_index)\n      {\n        auto base_index = lat_index * long_count;\n        auto b = base_index + long_index;\n        auto c = base_index + (long_index + 1) % long_count;\n\n        if (fill_triangles)\n        {\n          m.append_triangle(b, a, c);\n        }\n\n        if (add_wireframe)\n        {\n          m.append_line(a, b);\n          m.append_line(a, c);\n        }\n      }\n    }\n\n    if (!transform.isIdentity())\n    {\n      m.apply_transform(transform);\n    }\n\n    this->append_mesh(m);\n  }\n\n  void Mesh::add_coordinate_axes(\n    float length, float thickness, const Transform& transform)\n  {\n    this->check_instances();\n    if (this->m_vertices.cols() == 6)\n    {\n      // shared color mesh\n      std::cerr << \"Converting shared color mesh to use vertex color \"\n                << \"to accommodate coordinate axes.\";\n      VertexBuffer vertices = VertexBuffer::Zero(this->count_vertices(), 9);\n      if (this->count_vertices())\n      {\n        vertices.leftCols(6) = this->m_vertices;\n        vertices.col(6).fill(this->m_shared_color.r());\n        vertices.col(7).fill(this->m_shared_color.g());\n        vertices.col(8).fill(this->m_shared_color.b());\n        this->m_shared_color = Color::None();\n      }\n\n      this->m_vertices = vertices;\n    }\n    else if (this->m_vertices.cols() == 8)\n    {\n      // image/texture mesh\n      throw std::invalid_argument(\"Cannot add coordinate axes to a UV mesh\");\n    }\n\n    Mesh m = Mesh(\"\");\n    m.add_thickline(\n      {1, 0, 0}, {0, 0, 0}, {length, 0, 0}, thickness, 0.5f * thickness);\n    m.add_thickline(\n      {0, 1, 0}, {0, 0, 0}, {0, length, 0}, thickness, 0.5f * thickness);\n    m.add_thickline(\n      {0, 0, 1}, {0, 0, 0}, {0, 0, length}, thickness, 0.5f * thickness);\n    m.add_sphere({1, 1, 1}, Transforms::scale(thickness * 1.1f));\n    if (!transform.isIdentity())\n    {\n      m.apply_transform(transform);\n    }\n\n    this->append_mesh(m);\n  }\n\n  void Mesh::add_camera_frustum(\n    const Color& color,\n    float fov_y_degrees,\n    float aspect_ratio,\n    float depth,\n    float thickness,\n    const Transform& transform)\n  {\n    this->check_instances();\n    this->check_color(color);\n    Mesh m = Mesh(\"\").shared_color(m_shared_color);\n    const float fov_y_half_radians = fov_y_degrees / 2.0f * PI / 180.0f;\n    const float height = depth * std::sin(fov_y_half_radians);\n    const float width = height * aspect_ratio;\n\n    m.add_thickline(\n      color, {0, 0, 0}, {+width, +height, depth}, 0.4f * thickness, thickness);\n    m.add_thickline(\n      color, {0, 0, 0}, {+width, -height, depth}, 0.4f * thickness, thickness);\n    m.add_thickline(\n      color, {0, 0, 0}, {-width, -height, depth}, 0.4f * thickness, thickness);\n    m.add_thickline(\n      color,\n      {0.0, 0.0, 0.0},\n      {-width, +height, depth},\n      0.4f * thickness,\n      thickness);\n    m.add_thickline(\n      color,\n      {+width, +height, depth},\n      {-width, +height, depth},\n      thickness,\n      thickness);\n    m.add_thickline(\n      color,\n      {-width, +height, depth},\n      {-width, -height, depth},\n      thickness,\n      thickness);\n    m.add_thickline(\n      color,\n      {-width, -height, depth},\n      {+width, -height, depth},\n      thickness,\n      thickness);\n    m.add_thickline(\n      color,\n      {+width, -height, depth},\n      {+width, +height, depth},\n      thickness,\n      thickness);\n    m.add_coordinate_axes(depth * 0.075f, thickness);\n\n    if (!transform.isIdentity())\n    {\n      m.apply_transform(transform);\n    }\n\n    this->append_mesh(m);\n  }\n\n  void Mesh::add_camera_frustum(\n    const Camera& camera, const Color& color, float thickness, float depth)\n  {\n    this->check_instances();\n    this->check_color(color);\n    Mesh m = Mesh(\"\").shared_color(m_shared_color);\n    Vector eye(0, 0, 0);\n    Eigen::Vector3f top_left(-1, -1, 1);\n    Eigen::Vector3f top_right(1, -1, 1);\n    Eigen::Vector3f bottom_left(-1, 1, 1);\n    Eigen::Vector3f bottom_right(1, 1, 1);\n\n    Transform unprojection = camera.projection().inverse();\n    top_left =\n      (unprojection * top_left.homogeneous()).hnormalized().normalized() *\n      depth;\n    top_right =\n      (unprojection * top_right.homogeneous()).hnormalized().normalized() *\n      depth;\n    bottom_left =\n      (unprojection * bottom_left.homogeneous()).hnormalized().normalized() *\n      depth;\n    bottom_right =\n      (unprojection * bottom_right.homogeneous()).hnormalized().normalized() *\n      depth;\n\n    m.add_thickline(color, eye, bottom_right, 0.4f * thickness, thickness);\n    m.add_thickline(color, eye, top_right, 0.4f * thickness, thickness);\n    m.add_thickline(color, eye, top_left, 0.4f * thickness, thickness);\n    m.add_thickline(color, eye, bottom_left, 0.4f * thickness, thickness);\n    m.add_thickline(color, bottom_right, bottom_left, thickness, thickness);\n    m.add_thickline(color, bottom_left, top_left, thickness, thickness);\n    m.add_thickline(color, top_left, top_right, thickness, thickness);\n    m.add_thickline(color, top_right, bottom_right, thickness, thickness);\n    m.add_coordinate_axes(-0.075f, thickness);\n\n    if (!camera.camera_to_world().isIdentity())\n    {\n      m.apply_transform(camera.camera_to_world());\n    }\n\n    this->append_mesh(m);\n  }\n\n  void Mesh::add_camera_image(const Camera& camera, float depth)\n  {\n    this->check_instances();\n    Mesh m = Mesh(\"\").shared_color(m_shared_color).texture_id(m_texture_id);\n    Vector eye(0, 0, 0);\n    Eigen::Vector3f top_left(-1, -1, 1);\n    Eigen::Vector3f top_right(1, -1, 1);\n    Eigen::Vector3f bottom_left(-1, 1, 1);\n    Eigen::Vector3f bottom_right(1, 1, 1);\n\n    Transform unprojection = camera.projection().inverse();\n    top_left =\n      (unprojection * top_left.homogeneous()).hnormalized().normalized() *\n      depth;\n    top_right =\n      (unprojection * top_right.homogeneous()).hnormalized().normalized() *\n      depth;\n    bottom_left =\n      (unprojection * bottom_left.homogeneous()).hnormalized().normalized() *\n      depth;\n    bottom_right =\n      (unprojection * bottom_right.homogeneous()).hnormalized().normalized() *\n      depth;\n\n    m.add_quad(Color::None(), top_left, top_right, bottom_right, bottom_left);\n    if (!camera.camera_to_world().isIdentity())\n    {\n      m.apply_transform(camera.camera_to_world());\n    }\n\n    this->append_mesh(m);\n  }\n\n  void Mesh::add_disc(\n    const Color& color,\n    const Transform& transform,\n    std::uint32_t segment_count,\n    bool fill_triangles,\n    bool add_wireframe)\n  {\n    this->check_instances();\n    this->check_color(color);\n\n    float radius = 0.5f;\n\n    VectorBuffer vertices =\n      VectorBuffer::Zero(static_cast<Eigen::Index>(segment_count) + 1, 3);\n    auto thetas = Eigen::ArrayXf::LinSpaced(segment_count, 0, 2.0f * PI);\n    auto ys = radius * thetas.cos();\n    auto zs = radius * thetas.sin();\n    vertices.block(1, 1, segment_count, 1) = ys;\n    vertices.bottomRightCorner(segment_count, 1) = zs;\n\n    TriangleBuffer triangles(segment_count, 3);\n    triangles.col(0).fill(0);\n    triangles.col(2) = arange(0, segment_count) + 1;\n    triangles.col(1) = roll(triangles.col(2).array(), 1);\n\n    ColorBuffer colors = ColorBufferNone();\n    if (!color.is_none())\n    {\n      colors = ColorBuffer(segment_count + 1, 3);\n      colors.col(0).fill(color(0));\n      colors.col(1).fill(color(1));\n      colors.col(2).fill(color(2));\n    }\n\n    VectorBuffer normals =\n      VectorBuffer::Zero(static_cast<Eigen::Index>(segment_count) + 1, 3);\n    normals.col(0).fill(1.0f);\n\n    this->add_mesh_with_normals(\n      vertices,\n      normals,\n      triangles,\n      colors,\n      UVBufferNone(),\n      transform,\n      false,\n      fill_triangles,\n      add_wireframe);\n  }\n\n  void Mesh::add_cylinder(\n    const Color& color,\n    const Transform& transform,\n    std::uint32_t segment_count,\n    bool fill_triangles,\n    bool add_wireframe)\n  {\n    this->check_instances();\n    this->check_color(color);\n\n    // Unit diameter for consistency with other primitives\n    float radius = 0.5f;\n\n    auto N = segment_count;\n\n    // Add discs at each end of the cylinder\n    // Note, we do not re-use disc vertices for the barrel, as this gives bad\n    // normals\n    std::array<float, 2> x_vals = {-0.5f, +0.5f};\n    for (auto& x : x_vals)\n    {\n      auto disc_transform = Transforms::rotation_about_y(x == 0.5f ? 0 : PI);\n      disc_transform = Transforms::translate({x, 0, 0}) * disc_transform;\n      if (!transform.isIdentity())\n      {\n        disc_transform = transform * disc_transform;\n      }\n\n      this->add_disc(color, disc_transform, N, fill_triangles, add_wireframe);\n    }\n\n    auto thetas = Eigen::ArrayXf::LinSpaced(N, 0, 2.0f * PI);\n    auto ys = radius * thetas.cos();\n    auto zs = radius * thetas.sin();\n\n    VectorBuffer vertices(2 * N, 3);\n    vertices.topLeftCorner(N, 1).fill(-0.5f);\n    vertices.bottomLeftCorner(N, 1).fill(+0.5f);\n    vertices.block(0, 1, N, 1) = ys;\n    vertices.block(N, 1, N, 1) = ys;\n    vertices.topRightCorner(N, 1) = zs;\n    vertices.bottomRightCorner(N, 1) = zs;\n\n    VectorBuffer normals = vertices;\n    normals.col(0).fill(0.0f);\n\n    TriangleBuffer triangles(2 * N, 3);\n    auto range = arange(0, N);\n    triangles.topLeftCorner(N, 1) = roll(range, 1);\n    triangles.block(0, 1, N, 1) = range;\n    triangles.topRightCorner(N, 1) = range + N;\n    triangles.bottomLeftCorner(N, 1) = roll(range, 1);\n    triangles.block(N, 1, N, 1) = range + N;\n    triangles.bottomRightCorner(N, 1) = roll(range, 1) + N;\n\n    ColorBuffer colors = ColorBufferNone();\n    if (!color.is_none())\n    {\n      colors = ColorBuffer(2 * N, 3);\n      colors.col(0).fill(color(0));\n      colors.col(1).fill(color(1));\n      colors.col(2).fill(color(2));\n    }\n\n    this->add_mesh_with_normals(\n      vertices,\n      normals,\n      triangles,\n      colors,\n      UVBufferNone(),\n      transform,\n      false,\n      fill_triangles,\n      add_wireframe);\n  }\n\n  void Mesh::add_sphere(\n    const Color& color,\n    const Transform& transform,\n    bool fill_triangles,\n    bool add_wireframe)\n  {\n    this->add_icosphere(color, transform, 2, fill_triangles, add_wireframe);\n  }\n\n  void Mesh::add_icosphere(\n    const Color& color,\n    const Transform& transform,\n    std::uint32_t steps,\n    bool fill_triangles,\n    bool add_wireframe)\n  {\n    this->check_instances();\n    this->check_color(color);\n\n    // Create a basic icosohedron primitive\n\n    // Leads to unit diameter for consistency with other primitives\n    const float radius = 0.5f;\n    const float t = 0.5f * (1.0f + std::sqrt(5.0f));\n    VectorBuffer vertex_positions(12, 3);\n    vertex_positions << -1.0, +t, 0.0, +1.0, +t, 0.0, -1.0, -t, 0.0, +1.0, -t,\n      0.0, 0.0, -1.0, +t, 0.0, +1.0, +t, 0.0, -1.0, -t, 0.0, +1.0, -t, +t, 0.0,\n      -1.0, +t, 0.0, +1.0, -t, 0.0, -1.0, -t, 0.0, +1.0;\n    vertex_positions.rowwise().normalize();\n    vertex_positions *= radius;\n\n    TriangleBuffer triangles(20, 3);\n    triangles << 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5,\n      11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8,\n      3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1;\n\n    typedef std::pair<std::uint32_t, std::uint32_t> Edge;\n    // Apply subdivision\n    for (std::uint32_t iter = 0; iter < steps; ++iter)\n    {\n      std::map<Edge, std::uint32_t> new_e_vs;\n      TriangleBuffer new_triangles;\n\n      // For each triangle we will make up to 3 new e-verts\n      // (some will have less when shared with neighbouring triangles)\n      for (auto triangle = 0; triangle < triangles.rows(); ++triangle)\n      {\n        auto a = triangles(triangle, 0);\n        auto b = triangles(triangle, 1);\n        auto c = triangles(triangle, 2);\n        std::map<Edge, std::uint32_t> v_idx;\n\n        // Loop over triangle edges\n        std::array<Edge, 3> edges = {Edge(a, b), Edge(a, c), Edge(b, c)};\n        for (const auto& edge : edges)\n        {\n          Edge back_edge(edge.second, edge.first);\n          // Check this edge does not already have a new edge-vertex\n          if (new_e_vs.count(edge))\n          {\n            v_idx[edge] = new_e_vs[edge];\n          }\n          else if (new_e_vs.count(back_edge))\n          {\n            v_idx[edge] = new_e_vs[back_edge];\n          }\n          else\n          {\n            Vector v = vertex_positions.row(edge.first) +\n              vertex_positions.row(edge.second);\n            v.normalize();\n            v *= radius;\n            v_idx[edge] = new_e_vs[edge] =\n              static_cast<std::uint32_t>(vertex_positions.rows());\n            append_row(vertex_positions, v);\n          }\n        }\n\n        // Append new triangles\n        append_row(\n          new_triangles, Triangle(a, v_idx[Edge(a, b)], v_idx[Edge(a, c)]));\n        append_row(\n          new_triangles,\n          Triangle(v_idx[Edge(a, b)], v_idx[Edge(b, c)], v_idx[Edge(a, c)]));\n        append_row(\n          new_triangles, Triangle(v_idx[Edge(a, c)], v_idx[Edge(b, c)], c));\n        append_row(\n          new_triangles, Triangle(v_idx[Edge(a, b)], b, v_idx[Edge(b, c)]));\n      }\n\n      // Replace existing triangles with new triangles\n      triangles = new_triangles;\n    }\n\n    // Set up per-vertex colors if required\n    ColorBuffer colors;\n    if (!color.is_none())\n    {\n      colors = ColorBuffer(vertex_positions.rows(), 3);\n      colors.col(0).fill(color.r());\n      colors.col(1).fill(color.g());\n      colors.col(2).fill(color.b());\n    }\n\n    // Set up per-vertex uvs if required\n    UVBuffer uvs;\n    if (!m_texture_id.empty())\n    {\n      // Compute azimuth and inclination values into the uv buffer\n      uvs.resize(vertex_positions.rows(), Eigen::NoChange);\n      for (auto v_idx = 0; v_idx < vertex_positions.rows(); ++v_idx)\n      {\n        uvs(v_idx, 0) = static_cast<float>(\n          0.5f -\n          0.5f *\n            std::atan2(vertex_positions(v_idx, 2), vertex_positions(v_idx, 0)) /\n            PI); // Azimuth\n        uvs(v_idx, 1) = static_cast<float>(\n          1.0f -\n          std::acos(vertex_positions(v_idx, 1) * 2.0f) / PI); // Inclination\n      }\n\n      // Duplicate vertices across the longitude seam - not particularly\n      // efficient and bit of a hack but works ok.  Results in non watertight\n      // mesh. Loop over triangles\n      TriangleBuffer new_triangles;\n      for (auto triangle = 0; triangle < triangles.rows(); ++triangle)\n      {\n        auto a = triangles(triangle, 0);\n        auto b = triangles(triangle, 1);\n        auto c = triangles(triangle, 2);\n\n        // Rotate triangle indices to ensure a is east most vertex, preserving\n        // triangle winding order\n        for (std::size_t attempt = 0; attempt < 2; ++attempt)\n        {\n          if (uvs(a, 0) < uvs(b, 0) || uvs(a, 0) < uvs(c, 0))\n          {\n            std::tie(a, b, c) = std::make_tuple(b, c, a);\n          }\n        }\n\n        // Identify hemisphere for a, b, c\n        // Hack - doesn't look great at poles for small number of subdiv steps\n        bool a_isEast = uvs(a, 0) > 0.66f;\n        bool b_isWest = uvs(b, 0) < 0.33f;\n        bool c_isWest = uvs(c, 0) < 0.33f;\n\n        // Duplicate vertices if necessary\n        if (a_isEast && c_isWest) // Duplicate c vertex\n        {\n          Vertex new_vertex = vertex_positions.row(c);\n          append_row(vertex_positions, new_vertex); // Concatenate a copy of c\n          append_row(uvs, Eigen::Vector2f(1.0f + uvs(c, 0), uvs(c, 1)));\n          c = static_cast<uint32_t>(\n            vertex_positions.rows() - 1); // Will overwrite c in triangle\n        }\n        if (a_isEast && b_isWest) // Duplicate b vertex\n        {\n          Vertex new_vertex = vertex_positions.row(b);\n          append_row(vertex_positions, new_vertex); // Concatenate a copy of b\n          append_row(uvs, Eigen::Vector2f(1.0f + uvs(b, 0), uvs(b, 1)));\n          b = static_cast<uint32_t>(\n            vertex_positions.rows() - 1); // Will overwrite b in triangle\n        }\n\n        // Save the new triangle\n        append_row(new_triangles, Triangle(a, b, c));\n      }\n\n      // Replace existing triangles with new triangles\n      triangles = new_triangles;\n    }\n\n    // Populate mesh\n\n    // vertices double as normals given they lie on unit sphere\n    this->add_mesh_with_normals(\n      std::move(vertex_positions),\n      std::move(vertex_positions),\n      std::move(triangles),\n      std::move(colors),\n      std::move(uvs),\n      transform,\n      false,\n      fill_triangles,\n      add_wireframe);\n  }\n\n  void Mesh::add_uv_sphere(\n    const Color& color,\n    const Transform& transform,\n    std::uint32_t lat_count,\n    std::uint32_t long_count,\n    bool fill_triangles,\n    bool add_wireframe)\n  {\n    this->check_instances();\n    this->check_color(color);\n\n    // Add vertices\n\n    // Leads to unit diameter for consistency with other primitives\n    const double radius = 0.5;\n    Mesh m = Mesh(\"\").shared_color(m_shared_color);\n    for (std::uint32_t lat_index = 0; lat_index < lat_count + 1; ++lat_index)\n    {\n      double theta = lat_index * M_PI / lat_count;\n      double cosTheta = std::cos(theta);\n      double sinTheta = std::sin(theta);\n      for (std::uint32_t long_index = 0; long_index < long_count; ++long_index)\n      {\n        double phi = long_index * 2.0 * M_PI / long_count;\n        double cosPhi = std::cos(phi);\n        double sinPhi = std::sin(phi);\n\n        double dx = radius * cosPhi * sinTheta;\n        double dy = radius * cosTheta;\n        double dz = radius * sinPhi * sinTheta;\n        Vector pos = Eigen::Vector3d(dx, dy, dz).cast<float>();\n        m.append_vertex(pos, pos, color);\n      }\n    }\n\n    // Add triangles\n    for (std::uint32_t lat_index = 0; lat_index < lat_count; ++lat_index)\n    {\n      for (std::uint32_t long_index = 0; long_index < long_count; ++long_index)\n      {\n        auto base_index = lat_index * long_count;\n        auto a = base_index + long_index;\n        auto b = base_index + (long_index + 1) % long_count;\n        auto c = base_index + long_index + long_count;\n        auto d = base_index + (long_index + 1) % long_count + long_count;\n        if (fill_triangles)\n        {\n          if (lat_index > 0)\n          {\n            m.append_triangle(a, b, c);\n          }\n          m.append_triangle(c, b, d);\n        }\n        if (add_wireframe)\n        {\n          m.append_line(a, b);\n          m.append_line(b, d);\n          m.append_line(d, c);\n          m.append_line(c, a);\n        }\n      }\n    }\n\n    if (!transform.isIdentity())\n    {\n      m.apply_transform(transform);\n    }\n\n    this->append_mesh(m);\n  }\n\n} // namespace scenepic", "meta": {"hexsha": "8b29ee58719657dc165791a6ce83c9b428737207", "size": 24666, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/scenepic/mesh_primitives.cpp", "max_stars_repo_name": "microsoft/scenepic", "max_stars_repo_head_hexsha": "e3fd2c6312fa670a92b7888962b6812c262c6759", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T08:51:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T11:19:23.000Z", "max_issues_repo_path": "src/scenepic/mesh_primitives.cpp", "max_issues_repo_name": "microsoft/scenepic", "max_issues_repo_head_hexsha": "e3fd2c6312fa670a92b7888962b6812c262c6759", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2021-10-05T11:36:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T13:33:43.000Z", "max_forks_repo_path": "src/scenepic/mesh_primitives.cpp", "max_forks_repo_name": "microsoft/scenepic", "max_forks_repo_head_hexsha": "e3fd2c6312fa670a92b7888962b6812c262c6759", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-12-12T16:42:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T11:50:14.000Z", "avg_line_length": 30.8710888611, "max_line_length": 80, "alphanum_fraction": 0.6006648828, "num_tokens": 7017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.42232849988795984}}
{"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/diag.hpp\n *\n * \\brief The \\c diag operation.\n *\n * The \\c diag operation takes inspiration from the \\e diag MATLAB's function\n * and the \\e DiagonalMatrix Mathematica's function.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright (c) 2009, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_UBLAS_DIAG_HPP\n#define BOOST_NUMERIC_UBLAS_DIAG_HPP\n\n#include <boost/numeric/ublasx/container/generalized_diagonal_matrix.hpp>\n#include <boost/numeric/ublas/fwd.hpp>\n#include <boost/numeric/ublasx/proxy/matrix_diagonal.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n/**\n * \\brief A traits class for vector-to-diagonal-matrix transformation.\n * \\tparam VectorT A model of VectorExpression.\n * \\tparam Layout A matrix layout type.\n */\ntemplate <typename VectorT, typename LayoutT>\nstruct vector_matrix_diag_traits\n{\n    typedef typename vector_traits<VectorT>::value_type value_type;\n    typedef typename vector_traits<VectorT>::difference_type difference_type;\n    typedef typename vector_traits<VectorT>::size_type size_type;\n    typedef LayoutT layout_type;\n    typedef typename VectorT::array_type array_type; //FIXME: not in vector_traits\n    typedef generalized_diagonal_matrix<value_type, layout_type, array_type> result_type;\n};\n\n\n/**\n * \\brief A traits class for vector-to-diagonal-matrix transformation.\n * \\tparam VectorExprT A model of VectorExpression.\n * \\tparam Layout A matrix layout type.\n */\ntemplate <typename VectorExprT, typename LayoutT>\nstruct vector_matrix_diag_traits<vector_expression<VectorExprT>, LayoutT>\n{\n    typedef typename vector_traits<VectorExprT>::value_type value_type;\n    typedef typename vector_traits<VectorExprT>::difference_type difference_type;\n    typedef typename vector_traits<VectorExprT>::size_type size_type;\n    typedef LayoutT layout_type;\n    typedef typename VectorExprT::array_type array_type; //FIXME: not in vector_traits\n    typedef generalized_diagonal_matrix<value_type, layout_type, array_type> result_type;\n};\n\n\n/**\n * \\brief Create a square matrix of order \\f$n+abs(k)\\f$, with the elements of\n *  \\a v on the \\a k-th diagonal.\n * \\tparam VectorT A model of VectorExpression.\n * \\tparam LayoutT The layout type of the resulting matrix (e.g., row_major).\n * \\param v A vector expression.\n * \\param k The offset from the main diagonal:\n *  - \\a k = 0 represents the main diagonal,\n *  - \\a k > 0 is the offset above the main diagonal,\n *  - \\a k < 0 is the offset below the main diagonal.\n *  .\n *  Default to zero.\n * \\param l The matrix layout.\n * \\return A square diagonal matrix with the elements of \\a v on the \\a k-th\n *  diagonal.\n */\ntemplate <typename VectorT, typename LayoutT>\nBOOST_UBLAS_INLINE\ntypename vector_matrix_diag_traits<VectorT,LayoutT>::result_type diag(vector_expression<VectorT>& v, typename vector_matrix_diag_traits<VectorT,LayoutT>::difference_type k=0, LayoutT /*l*/=LayoutT())\n{\n    typedef vector_matrix_diag_traits<VectorT,LayoutT> traits;\n    typedef typename traits::size_type size_type;\n    typedef typename traits::array_type array_type;\n    typedef typename traits::result_type result_type;\n\n    size_type d(k > 0 ? k : -k);\n\n    return result_type(\n            v().size() + d,\n            k,\n            array_type(v().data())\n    );\n}\n\n\n/**\n * \\brief Create a square matrix of order \\f$n+abs(k)\\f$, with the elements of\n *  \\a v on the \\a k-th diagonal.\n * \\tparam VectorT A model of VectorExpression.\n * \\tparam LayoutT The layout type of the resulting matrix (e.g., row_major).\n * \\param v A vector expression.\n * \\param k The offset from the main diagonal:\n *  - \\a k = 0 represents the main diagonal,\n *  - \\a k > 0 is the offset above the main diagonal,\n *  - \\a k < 0 is the offset below the main diagonal.\n *  .\n *  Default to zero.\n * \\param l The matrix layout.\n * \\return A square diagonal matrix with the elements of \\a v on the \\a k-th\n *  diagonal.\n *\n * Variant for const reference to vectors.\n */\ntemplate <typename VectorT, typename LayoutT>\nBOOST_UBLAS_INLINE\ntypename vector_matrix_diag_traits<VectorT const,LayoutT>::result_type diag(vector_expression<VectorT> const& v, typename vector_matrix_diag_traits<VectorT,LayoutT>::difference_type k=0, LayoutT /*l*/=LayoutT())\n{\n    typedef vector_matrix_diag_traits<VectorT const,LayoutT> traits;\n    typedef typename traits::size_type size_type;\n    typedef typename traits::array_type array_type;\n    typedef typename traits::result_type result_type;\n\n    size_type d(k > 0 ? k : -k);\n\n    return result_type(\n            v().size() + d,\n            k,\n            array_type(v().data())\n    );\n}\n\n\n/**\n * \\brief create a square matrix of order \\f$n+abs(k)\\f$, with the elements of\n *  \\a v on the \\a k-th diagonal.\n * \\tparam vectort a model of vectorexpression.\n * \\param v a vector expression.\n * \\param k the offset from the main diagonal:\n *  - \\a k = 0 represents the main diagonal,\n *  - \\a k > 0 is the offset above the main diagonal,\n *  - \\a k < 0 is the offset below the main diagonal.\n *  .\n *  Default to zero.\n * \\return a square diagonal matrix with the elements of \\a v on the \\a k-th\n *  diagonal and with a row-major layout.\n */\ntemplate <typename VectorT>\nBOOST_UBLAS_INLINE\ntypename vector_matrix_diag_traits<VectorT,row_major>::result_type diag(vector_expression<VectorT>& v, typename vector_matrix_diag_traits<VectorT,row_major>::difference_type k=0)\n{\n    typedef vector_matrix_diag_traits<VectorT,row_major> traits;\n    typedef typename traits::size_type size_type;\n    typedef typename traits::array_type array_type;\n    typedef typename traits::result_type result_type;\n\n    size_type d(k > 0 ? k : -k);\n\n    return result_type(\n            v().size() + d,\n            k,\n            array_type(v().data())\n    );\n}\n\n\n/**\n * \\brief create a square matrix of order \\f$n+abs(k)\\f$, with the elements of\n *  \\a v on the \\a k-th diagonal.\n * \\tparam vectort a model of vectorexpression.\n * \\param v a vector expression.\n * \\param k the offset from the main diagonal:\n *  - \\a k = 0 represents the main diagonal,\n *  - \\a k > 0 is the offset above the main diagonal,\n *  - \\a k < 0 is the offset below the main diagonal.\n *  .\n *  Default to zero.\n * \\return a square diagonal matrix with the elements of \\a v on the \\a k-th\n *  diagonal and with a row-major layout.\n *\n * Variant for const reference to vectors.\n */\ntemplate <typename VectorT>\nBOOST_UBLAS_INLINE\ntypename vector_matrix_diag_traits<VectorT const,row_major>::result_type diag(vector_expression<VectorT> const& v, typename vector_matrix_diag_traits<VectorT,row_major>::difference_type k=0)\n{\n    typedef vector_matrix_diag_traits<VectorT const,row_major> traits;\n    typedef typename traits::size_type size_type;\n    typedef typename traits::array_type array_type;\n    typedef typename traits::result_type result_type;\n\n    size_type d(k > 0 ? k : -k);\n\n    return result_type(\n            v().size() + d,\n            k,\n            array_type(v().data())\n    );\n}\n\n\n/**\n * \\brief Create a \\a size1 by \\a size2 matrix with the elements of\n *  \\a v on the \\a k-th diagonal.\n * \\tparam VectorT A model of VectorExpression.\n * \\tparam LayoutT The layout type of the resulting matrix (e.g., row_major).\n * \\param v A vector expression. If too long it will be truncated.\n * \\param size1 The number of rows of the resulting matrix.\n * \\param size2 The number of columns of the resulting matrix.\n * \\param k The offset from the main diagonal:\n *  - \\a k = 0 represents the main diagonal,\n *  - \\a k > 0 is the offset above the main diagonal,\n *  - \\a k < 0 is the offset below the main diagonal.\n *  .\n *  Default to zero.\n * \\param l The matrix layout.\n * \\return A rectangular diagonal matrix with the elements of \\a v on the\n *  \\a k-th diagonal.\n */\ntemplate <typename VectorT, typename LayoutT>\nBOOST_UBLAS_INLINE\ntypename vector_matrix_diag_traits<VectorT,LayoutT>::result_type diag(vector_expression<VectorT>& v, typename vector_matrix_diag_traits<VectorT,LayoutT>::size_type size1, typename vector_matrix_diag_traits<VectorT,LayoutT>::size_type size2, typename vector_matrix_diag_traits<VectorT,LayoutT>::difference_type k=0, LayoutT /*l*/=LayoutT())\n{\n    typedef vector_matrix_diag_traits<VectorT,row_major> traits;\n    typedef typename traits::array_type array_type;\n    typedef typename traits::result_type result_type;\n\n    return result_type(\n            size1,\n            size2,\n            k,\n            array_type(v().data())\n    );\n}\n\n\n/**\n * \\brief Create a \\a size1 by \\a size2 matrix with the elements of\n *  \\a v on the \\a k-th diagonal.\n * \\tparam VectorT A model of VectorExpression.\n * \\tparam LayoutT The layout type of the resulting matrix (e.g., row_major).\n * \\param v A vector expression. If too long it will be truncated.\n * \\param size1 The number of rows of the resulting matrix.\n * \\param size2 The number of columns of the resulting matrix.\n * \\param k The offset from the main diagonal:\n *  - \\a k = 0 represents the main diagonal,\n *  - \\a k > 0 is the offset above the main diagonal,\n *  - \\a k < 0 is the offset below the main diagonal.\n *  .\n *  Default to zero.\n * \\param l The matrix layout.\n * \\return A rectangular diagonal matrix with the elements of \\a v on the\n *  \\a k-th diagonal.\n *\n * Variant for const reference to vectors.\n */\ntemplate <typename VectorT, typename LayoutT>\nBOOST_UBLAS_INLINE\ntypename vector_matrix_diag_traits<VectorT const,LayoutT>::result_type diag(vector_expression<VectorT> const& v, typename vector_matrix_diag_traits<VectorT,LayoutT>::size_type size1, typename vector_matrix_diag_traits<VectorT,LayoutT>::size_type size2, typename vector_matrix_diag_traits<VectorT,LayoutT>::difference_type k=0, LayoutT /*l*/=LayoutT())\n{\n    typedef vector_matrix_diag_traits<VectorT const,row_major> traits;\n    typedef typename traits::array_type array_type;\n    typedef typename traits::result_type result_type;\n\n    return result_type(\n            size1,\n            size2,\n            k,\n            array_type(v().data())\n    );\n}\n\n\n/**\n * \\brief Create a \\a size1 by \\a size2 matrix with the elements of\n *  \\a v on the \\a k-th diagonal.\n * \\tparam VectorT A model of VectorExpression.\n * \\param v A vector expression. If too long it will be truncated.\n * \\param size1 The number of rows of the resulting matrix.\n * \\param size2 The number of columns of the resulting matrix.\n * \\param k The offset from the main diagonal:\n *  - \\a k = 0 represents the main diagonal,\n *  - \\a k > 0 is the offset above the main diagonal,\n *  - \\a k < 0 is the offset below the main diagonal.\n *  .\n *  Default to zero.\n * \\return A rectangular diagonal matrix with the elements of \\a v on the\n *  \\a k-th diagonal and with a row-major layout.\n */\ntemplate <typename VectorT>\nBOOST_UBLAS_INLINE\ntypename vector_matrix_diag_traits<VectorT,row_major>::result_type diag(vector_expression<VectorT>& v, typename vector_matrix_diag_traits<VectorT,row_major>::size_type size1, typename vector_matrix_diag_traits<VectorT,row_major>::size_type size2, typename vector_matrix_diag_traits<VectorT,row_major>::difference_type k=0)\n{\n    typedef vector_matrix_diag_traits<VectorT,row_major> traits;\n    typedef typename traits::array_type array_type;\n    typedef typename traits::result_type result_type;\n\n    return result_type(\n            size1,\n            size2,\n            k,\n            array_type(v().data())\n    );\n}\n\n\n/**\n * \\brief Create a \\a size1 by \\a size2 matrix with the elements of\n *  \\a v on the \\a k-th diagonal.\n * \\tparam VectorT A model of VectorExpression.\n * \\param v A vector expression. If too long it will be truncated.\n * \\param size1 The number of rows of the resulting matrix.\n * \\param size2 The number of columns of the resulting matrix.\n * \\param k The offset from the main diagonal:\n *  - \\a k = 0 represents the main diagonal,\n *  - \\a k > 0 is the offset above the main diagonal,\n *  - \\a k < 0 is the offset below the main diagonal.\n *  .\n *  Default to zero.\n * \\return A rectangular diagonal matrix with the elements of \\a v on the\n *  \\a k-th diagonal and with a row-major layout.\n *\n * Variant for const reference to vectors.\n */\ntemplate <typename VectorT>\nBOOST_UBLAS_INLINE\ntypename vector_matrix_diag_traits<VectorT const,row_major>::result_type diag(vector_expression<VectorT> const& v, typename vector_matrix_diag_traits<VectorT,row_major>::size_type size1, typename vector_matrix_diag_traits<VectorT,row_major>::size_type size2, typename vector_matrix_diag_traits<VectorT,row_major>::difference_type k=0)\n{\n    typedef vector_matrix_diag_traits<VectorT const,row_major> traits;\n    typedef typename traits::array_type array_type;\n    typedef typename traits::result_type result_type;\n\n    return result_type(\n            size1,\n            size2,\n            k,\n            array_type(v().data())\n    );\n}\n\n\n//[FIXME]: The two functions below are commented for problems on overloading:\n// the ambiguity is caused by difference_type, size_type and LayoutT.\n///**\n// * \\brief Create a square matrix of order \\f$n+abs(k)\\f$, with the elements of\n// *  \\a v on the \\a k-th diagonal.\n// * \\tparam VectorT A model of VectorExpression.\n// * \\tparam LayoutT The layout type of the resulting matrix (e.g., row_major).\n// * \\param v A vector expression. If longer than \\a size it will be truncated.\n// * \\param size The size of the resulting matrix.\n// * \\param k The offset from the main diagonal:\n// *  - \\a k = 0 represents the main diagonal,\n// *  - \\a k > 0 is the offset above the main diagonal,\n// *  - \\a k < 0 is the offset below the main diagonal.\n// * \\param l The matrix layout.\n// *  .\n// * \\return A square diagonal matrix with the elements of \\a v on the \\a k-th\n// *  diagonal.\n// */\n//template <typename VectorT, typename LayoutT>\n//BOOST_UBLAS_INLINE\n//typename vector_matrix_diag_traits<VectorT,LayoutT>::result_type diag(vector_expression<VectorT>& v, typename vector_matrix_diag_traits<VectorT,LayoutT>::size_type size, typename vector_matrix_diag_traits<VectorT,LayoutT>::difference_type k, LayoutT /*l*//*=LayoutT()*/)\n//{\n//  typedef vector_matrix_diag_traits<VectorT,LayoutT> traits;\n//  typedef typename traits::size_type size_type;\n//  typedef typename traits::array_type array_type;\n//  typedef typename traits::result_type result_type;\n//\n//  return result_type(\n//          size,\n//          k,\n//          array_type(v().data())\n//  );\n//}\n\n\n///**\n// * \\brief Create a square matrix of order \\f$n+abs(k)\\f$, with the elements of\n// *  \\a v on the \\a k-th diagonal.\n// * \\tparam VectorT A model of VectorExpression.\n// * \\param v A vector expression. If longer than \\a size it will be truncated.\n// * \\param size The size of the resulting matrix.\n// * \\param k The offset from the main diagonal:\n// *  - \\a k = 0 represents the main diagonal,\n// *  - \\a k > 0 is the offset above the main diagonal,\n// *  - \\a k < 0 is the offset below the main diagonal.\n// *  .\n// * \\return A square diagonal matrix with the elements of \\a v on the \\a k-th\n// *  diagonal and with a row-major layout.\n// */\n//template <typename VectorT>\n//BOOST_UBLAS_INLINE\n//typename vector_matrix_diag_traits<VectorT,row_major>::result_type diag(vector_expression<VectorT>& v, typename vector_matrix_diag_traits<VectorT,row_major>::size_type size, typename vector_matrix_diag_traits<VectorT,row_major>::difference_type k)\n//{\n//  typedef vector_matrix_diag_traits<VectorT,row_major> traits;\n//  typedef typename traits::size_type size_type;\n//  typedef typename traits::array_type array_type;\n//  typedef typename traits::result_type result_type;\n//\n//  return result_type(\n//          size,\n//          k,\n//          array_type(v().data())\n//  );\n//}\n//[/FIXME]\n\n\n/**\n * \\brief Create a view of the \\a k-th diagonal of a matrix.\n * \\tparam MatrixT A model of MatrixExpression.\n * \\param me A matrix expression from which taking the \\a k-th diagonal.\n * \\param k The offset from the main diagonal:\n *  - \\a k = 0 represents the main diagonal,\n *  - \\a k > 0 is the offset above the main diagonal,\n *  - \\a k < 0 is the offset below the main diagonal.\n *  .\n *  Default to zero.\n * \\return A view of the \\a k-th diagonal of matrix \\a me.\n */\ntemplate<typename MatrixT>\nBOOST_UBLAS_INLINE\nmatrix_diagonal<MatrixT> diag(matrix_expression<MatrixT>& me, typename MatrixT::difference_type k=0)\n{\n    return matrix_diagonal<MatrixT>(me(), k);\n}\n\n\n/**\n * \\brief Create an unmutable view of the \\a k-th diagonal of a matrix.\n * \\tparam MatrixT A model of MatrixExpression.\n * \\param me A matrix expression from which taking the \\a k-th diagonal.\n * \\param k The offset from the main diagonal:\n *  - \\a k = 0 represents the main diagonal,\n *  - \\a k > 0 is the offset above the main diagonal,\n *  - \\a k < 0 is the offset below the main diagonal.\n *  .\n *  Default to zero.\n * \\return An unmutable view of the \\a k-th diagonal of matrix \\a me.\n */\ntemplate<typename MatrixT>\nBOOST_UBLAS_INLINE\nmatrix_diagonal<MatrixT const> const diag(matrix_expression<MatrixT> const& me, typename MatrixT::difference_type k=0)\n{\n    return matrix_diagonal<MatrixT const>(me(), k);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_DIAG_HPP\n", "meta": {"hexsha": "d0f317abc5f9d7344e3df0adb6c98957f7587e38", "size": 17461, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/diag.hpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "boost/numeric/ublasx/operation/diag.hpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "boost/numeric/ublasx/operation/diag.hpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 38.0413943355, "max_line_length": 351, "alphanum_fraction": 0.7134184755, "num_tokens": 4345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4223020123211147}}
{"text": "#include <iostream>\r\n#include <cmath>\r\n#include <vector>\r\n#include <math.h>\r\n#include <fstream>\r\n#include \"GeneralizedHeat.hpp\"\r\n#include \"APDE.hpp\"\r\n#include \"PDE_Q2.hpp\"\r\n#include \"originalPDE.hpp\"\r\n#include \"EllipticPDE_Q1.hpp\"\r\n#include \"EllipticPDE2.hpp\"\r\n#include \"Nonanalytic_1.hpp\"\r\n#include <string>\r\n#include <boost/math/quadrature/gauss.hpp>\r\nusing namespace std;\r\nusing namespace boost::math::quadrature;\r\n//const double M_PI = 2*acos(0);\r\n\r\nvoid printTime(SpaceMesh a_smesh, TimeMesh a_tmesh);\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\r\nSpaceMesh smesh;\r\nsmesh.GenerateDefaultSpaceMesh();\r\nsmesh.GloballyBisectSpaceMesh();\r\nsmesh.GloballyBisectSpaceMesh();\r\n//smesh.GloballyBisectSpaceMesh();\r\n//smesh.GloballyBisectSpaceMesh();\r\n\r\nTimeMesh tmesh;\r\ntmesh.GenerateUniformTimeMesh(pow(smesh.meshsize(), 1), 1.0);\r\n\r\nPDE_Q2 anotherpde;\r\noriginalPDE firstpde;\r\nEllipticPDE_Q1 Q1;\r\nEllipticPDE2 elliptic2;\r\nNonanalytic NA_1;\r\n\r\nGeneralHeat genheat;\r\nsmesh.PrintSpaceNodes();\r\ngenheat.SetSpaceTimeMesh(smesh, tmesh, NA_1);\r\n//genheat.StationaryHeatEquation();\r\ngenheat.SolveWithBCs();\r\nprintTime(smesh, tmesh);\r\ngenheat.PrintSolution();\r\n\r\n\r\n//genheat.GlobalSpaceError();\r\n\r\n//for (int i=0; i<6; i++)\r\n//{\r\n//    genheat.SetSpaceTimeMesh(smesh, tmesh, elliptic2);\r\n//    genheat.StationaryHeatEquation();\r\n//    std::cout<< smesh.meshsize() + 1 <<\"\\n\";\r\n//    genheat.UnitTest1();\r\n//    smesh.GloballyBisectSpaceMesh();\r\n//    tmesh.GenerateUniformTimeMesh(pow(smesh.meshsize()+1, 2), 1.0);\r\n//}\r\n\r\n\r\n}\r\n\r\nvoid printTime(SpaceMesh a_smesh, TimeMesh a_tmesh)\r\n{\r\n    ofstream myfile2;\r\n    myfile2.open (\"Y.csv\");\r\n    for(int j=0;j<a_tmesh.NumberOfTimeSteps()+1;j++ )\r\n    {\r\n    for(int i = 0; i<a_smesh.meshsize()+1; i++)\r\n    {\r\n        myfile2 << a_tmesh.ReadTimeStep(j) << \", \";\r\n    }\r\n    myfile2 << \"\\n\";\r\n    }\r\n    myfile2.close();\r\n}\r\n", "meta": {"hexsha": "39c5983c261fa993d4af01de4c367265bff17e62", "size": 1853, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solver class generalised for all boundary conditions/driver.cpp", "max_stars_repo_name": "thabomiles/FEMHeatEquation", "max_stars_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Solver class generalised for all boundary conditions/driver.cpp", "max_issues_repo_name": "thabomiles/FEMHeatEquation", "max_issues_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solver class generalised for all boundary conditions/driver.cpp", "max_forks_repo_name": "thabomiles/FEMHeatEquation", "max_forks_repo_head_hexsha": "b60eb04358e6c408923073cb52eeaadeee9fa0d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7564102564, "max_line_length": 70, "alphanum_fraction": 0.6799784134, "num_tokens": 552, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934765, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4223020123211146}}
{"text": "//\n// Created by mmath on 5/28/17.\n//\n\n#ifndef PYSCAN_POINT_HPP\n#define PYSCAN_POINT_HPP\n#include <string>\n#include <cstring>\n#include <cmath>\n#include <vector>\n#include <iostream>\n#include <array>\n#include <cassert>\n#include <sstream>\n#include <functional>\n#include <unordered_map>\n#include <queue>\n#include <optional>\n\n#include \"Utilities.hpp\"\n\n//#include <boost/math/special_functions/next.hpp>\n\nnamespace pyscan {\n\n    template<typename tuple_t>\n    constexpr auto get_array_from_tuple(tuple_t&& tuple) {\n        constexpr auto get_array = [](auto&& ... x){\n            return std::array{std::forward<decltype(x)>(x) ... , 1.0};\n        };\n        return std::apply(get_array, std::forward<tuple_t>(tuple));\n    }\n\n    // Coordiates in homgenous space.\n    template<int dim = 2>\n    class Point {\n    public:\n\n\n        template <class ...Coords, std::enable_if_t<(sizeof...(Coords) == dim + 1)>* = nullptr>\n        explicit Point(Coords... rest) : coords{rest...} {\n            static_assert(sizeof...(rest) == dim + 1, \"Wrong number of arguments for the point type.\");\n        }\n\n        template <class ...Coords, std::enable_if_t<(sizeof...(Coords) == dim)>* = nullptr>\n        explicit Point(std::tuple<Coords...> c) : coords(get_array_from_tuple(c)) {}\n\n       /* Point<dim>& operator=(Point<dim> const& pt) {\n            std::copy(coords.begin(), coords.end(), pt.coords.begin());\n            return *this;\n        }*/\n\n        Point() {\n            coords.fill(0.0);\n        }\n        virtual ~Point() = default;\n\n        friend std::ostream &operator<<(std::ostream &os, Point const &pt) {\n            os << \"pyscan::Point<\" << dim << \">(\";\n            for (size_t d = 0; d < dim; d++ ) {\n                os << pt.coords[d] << \", \";\n            }\n            os << pt.coords[dim];\n            os << \")\";\n            return os;\n        }\n\n        friend Point<dim> operator*(Point<dim> pt, double val) {\n            Point<dim> res;\n            for (size_t i = 0; i < dim; ++i) {\n                res.coords[i] = pt.coords[i] * val;\n            }\n            res.coords[dim] = pt.coords[dim];\n            return res;\n        }\n\n        friend Point<dim> operator*(double val, Point<dim> pt) {\n            return operator*(pt, val);\n        }\n\n        Point<dim> flip_orientation() const {\n            //Flips the orientation\n            Point<dim> p_out;\n            for (size_t j = 0; j < dim + 1; j++) {\n                p_out.coords[j] = -coords[j];\n            }\n            return p_out;\n        }\n\n        Point<dim> orient_up(int i) const {\n            // Always orient these down by the second to last coordinate.\n            // In 2d this ensures that y is oriented down.\n            // In 3d this ensures that z is oriented down.\n            Point<dim> p_out;\n            assert(i < dim + 1);\n            double orientation = std::copysign(1.0, coords[i]);\n            for (size_t j = 0; j < dim + 1; j++) {\n                p_out.coords[j] = orientation * coords[j];\n            }\n            return p_out;\n        }\n\n        Point<dim> orient_down(int i) const {\n            // Always orient these down by the second to last coordinate.\n            // In 2d this ensures that y is oriented down.\n            // In 3d this ensures that z is oriented down.\n            Point<dim> p_out;\n            assert(i < dim + 1);\n            double orientation = std::copysign(1.0, coords[i]);\n            for (size_t j = 0; j < dim + 1; j++) {\n                p_out.coords[j] = -orientation * coords[j];\n            }\n            return p_out;\n        }\n\n        inline double& operator[](size_t i) {\n            assert(i < dim + 1);\n            return coords[i];\n        }\n\n        inline double get_coord(size_t i) const {\n            return coords[i];\n        }\n\n        inline double operator[](size_t i) const {\n            assert(i < dim + 1);\n            return coords[i];\n        }\n\n        inline double operator()(size_t i) const {\n            assert(i < dim);\n            return coords[i] / coords[dim];\n        }\n\n        virtual std::string str() const {\n            std::stringstream ss;\n            ss << *this;\n            return ss.str();\n        }\n\n        bool operator==(const Point<dim> &pt) const {\n            for (size_t i = 0; i < dim + 1; ++i) {\n                if (coords[i] != pt.coords[i])\n                    return false;\n            }\n            return true;\n        }\n\n        inline double evaluate(const Point<dim> &other) const {\n            double res = 0.0;\n            for (size_t i = 0; i < dim + 1; ++i) {\n                res += coords[i] * other.coords[i];\n            }\n            return res; //* std::copysign(1.0, other[dim]);\n        }\n\n        inline Point<dim> direction(const Point<dim> & other) const {\n            auto pt = other.operator-(*this);\n            return pt.normalize();\n        }\n\n        inline double square_dist(const Point<dim> &p) const {\n            double res = 0.0;\n            for (size_t i = 0; i < dim; ++i) {\n                double tmp = (p[i] / p[dim] - coords[i] / coords[dim]);\n                res += tmp * tmp;\n            }\n            return res;\n        }\n\n        inline Point<dim> on_segment(Point<dim> const& p2, double alpha) {\n            /*\n             * Returns a point between this point and the second point that is alpha this + (1 - alpha) p2;\n             */\n            return alpha * (*this) + (1 - alpha) * p2;\n        }\n\n        inline double dist(const Point<dim> &p) const {\n            return sqrt(square_dist(p));\n        }\n\n\n        Point<dim> normalize() const {\n            Point<dim> res;\n            double magnitude = sqrt(pdot(*this)) / coords[dim];\n            for (size_t i = 0; i < dim; ++i) {\n                res.coords[i] = coords[i] / magnitude;\n            }\n            res.coords[dim] = 1.0;\n            return res;\n        }\n\n        Point<dim> operator-(const Point<dim>& other) const {\n            Point<dim> res;\n            for (size_t i = 0; i < dim; ++i) {\n                res.coords[i] = coords[i] * other[dim] - other[i] * coords[dim];\n            }\n            res.coords[dim] = other[dim] * coords[dim];\n            return res;\n        }\n\n        Point<dim> operator+(const Point<dim>& other) const {\n            Point<dim> res;\n            for (size_t i = 0; i < dim; ++i) {\n                res.coords[i] = coords[i] * other[dim] + other[i] * coords[dim];\n            }\n            res.coords[dim] = other[dim] * coords[dim];\n            return res;\n        }\n\n\n        inline double square_dist(const Point<dim>& begin, const Point<dim>& end) const {\n            auto v = end - begin;\n            auto w = *this - begin;\n            double c1 = w.pdot(v);\n            if (util::alte(c1, 0.0)) return square_dist(begin);\n            double c2 = v.pdot(v);\n            if (util::alte(c2, c1)) return square_dist(end);\n            double b = c1 / c2;\n            auto pb = begin + v * b;\n            return square_dist(pb);\n        }\n\n        inline double pdot(const Point<dim>& other) const {\n            /*\n             * Takes the dot product between these points as if they are vectors\n             */\n            double res = 0.0;\n            for (size_t i = 0; i < dim; ++i) {\n                res += coords[i] * other.coords[i];\n            }\n            //If this is approximately 0 then the points exist at infinity and this operation doesn't make sense.\n            assert(!util::aeq(coords[dim] * other[dim], 0.0));\n            return res / (coords[dim] * other[dim]);\n        }\n\n        inline bool approx_eq(Point<dim> const& p) const {\n\n            double res = 0.0;\n            for (size_t i = 0; i < dim; ++i) {\n                double tmp = (p[i] * coords[dim] - coords[i] * p[dim]);\n                res += std::abs(tmp);\n            }\n            return util::aeq(res, 0.0);\n        }\n\n        inline bool above_closed(const Point<dim> &p) const {\n            return util::alte(0.0, evaluate(p));\n        }\n\n        inline bool below_closed(const Point<dim> &p) const {\n            return util::alte(evaluate(p), 0.0);\n        }\n\n        inline bool above(const Point<dim> &p) const {\n            return util::alt(0.0, evaluate(p));\n        }\n\n        inline bool below(const Point<dim> &p) const {\n            return util::alt(evaluate(p), 0.0);\n        }\n\n\n        inline bool crosses( const Point<dim>& p1, const Point<dim>& p2) const {\n            /*\n             * Checks if this line is crossed by this line segment between p1\n             */\n            auto or1 = p1.orient_up(dim);\n            auto or2 = p2.orient_up(dim);\n            return (above(or1) && below(or2)) || (below(or1) && above(or2));\n        }\n\n        inline bool parallel_lte( const Point<dim>& l1) const {\n            /*\n             * Checks to see if this line is less than or equal to the line l1 assuming that l1 is parallel to\n             * this.\n             */\n            double norm = 1.0;\n            for (size_t i = 0; i < dim; ++i) {\n                if (!util::aeq(l1[i], 0)) {\n                    norm = coords[i] / l1[i];\n                    break;\n                }\n            }\n            return util::alte(l1[dim] * norm, coords[dim]);\n        }\n\n        inline bool parallel_lt( const Point<dim>& l1) const {\n            /*\n             * Checks to see if this line is less than or equal to the line l1 assuming that l1 is parallel to\n             * this.\n             */\n            double norm = 1.0;\n            for (size_t i = 0; i < dim; ++i) {\n                if (!util::aeq(l1[i], 0)) {\n                    norm = coords[i] / l1[i];\n                    break;\n                }\n            }\n            return util::alt(l1[dim] * norm, coords[dim]);\n        }\n\n    protected:\n        std::array<double, dim + 1> coords;\n    };\n\n\n    template<int dim = 2>\n    class WPoint : public Point<dim> {\n    public:\n        template<typename ...Coords>\n        explicit WPoint(double weight, Coords... rest)\n                : Point<dim>(rest...), weight(weight) {\n                }\n\n        WPoint()\n                : Point<dim>(), weight(0.0) {}\n        virtual ~WPoint() = default;\n\n        friend std::ostream &operator<<(std::ostream &os, WPoint const &pt) {\n            os << \"WPoint(\" << pt.get_weight() << \", \";\n            for (auto &el: pt.coords) {\n                os << el << \", \";\n            }\n            os << \")\";\n            return os;\n        }\n\n        inline double get_weight() const {\n            return weight;\n        }\n\n        virtual void set_weight(double w) {\n            weight = w;\n        }\n\n    protected:\n        double weight;\n    };\n\n\n    template<int dim = 2>\n    class LPoint : public WPoint<dim> {\n    public:\n        template<typename ...Coords>\n        LPoint(size_t label, double weight, Coords... rest)\n                : WPoint<dim>(weight, rest...), label(label) {}\n\n        LPoint()\n                : WPoint<dim>(), label(0) {}\n\n\n        virtual ~LPoint() = default;\n\n        inline size_t get_label() const {\n            return label;\n        }\n\n        friend std::ostream &operator<<(std::ostream &os, LPoint const &pt) {\n            os << \"LPoint(\" << pt.label << \", \" << pt.get_weight() << \", \";\n            for (auto &el: pt.coords) {\n                os << el << \", \";\n            }\n            os << \")\";\n            return os;\n        }\n\n        virtual void set_label(size_t l) {\n            label = l;\n        }\n\n    protected:\n        size_t label;\n    };\n\n\n    Point<2> correct_orientation(const Point<2>& pivot, const Point<2>& p);\n\n    Point<2> intersection(const Point<2> &p1, const Point<2> &p2);\n\n    std::tuple<double, double, double> normal(const Point<3> &p1, const Point<3> &p2, const Point<3> &p3);\n\n    bool is_parallel(const Point<2> &l1, const Point<2> &l2);\n\n    Point<3> cross_product(const Point<3>& p1, const Point<3>& p2);\n\n    bool crosses_segment(const Point<2> &p1, const Point<2> &p2, const Point<2> &q1, const Point<2> &q2);\n\n    //Return the two points on the line that are equidistance to some other point.\n//    std::tuple<Point<2>, Point<2>> chord_pts(const Point<2> &line, const Point<2> &origin, double dist);\n\n\n    using pt2_t = Point<2>;\n    using wpt2_t = WPoint<2>;\n    using lpt2_t = LPoint<2>;\n    using point_list_t = std::vector<pt2_t>;\n    using point_it_t = point_list_t::iterator;\n    using cpoint_it_t = point_list_t::const_iterator;\n\n    using weight_list_t = std::vector<double>;\n    using weight_it_t = weight_list_t::iterator;\n    using pt3_t = Point<3>;\n    using wpt3_t = WPoint<3>;\n    using lpt3_t = LPoint<3>;\n    using point3_list_t = std::vector<pt3_t>;\n    using point3_it_t = point3_list_t::iterator;\n    using label_list_t = std::vector<size_t>;\n    using wpoint_list_t = std::vector<WPoint<2>>;\n    using wpoint_it_t = wpoint_list_t::iterator;\n    using cwpoint_it_t = wpoint_list_t::const_iterator;\n\n    using lpoint_list_t = std::vector<LPoint<2>>;\n    using lpoint_it_t = lpoint_list_t::iterator;\n    using clpoint_it_t = lpoint_list_t::const_iterator;\n\n    using wpoint3_list_t = std::vector<WPoint<3>>;\n    using lpoint3_list_t = std::vector<LPoint<3>>;\n    using lpoint3_it_t = lpoint3_list_t::iterator;\n\n    using discrepancy_func_t = std::function<double(double, double, double, double)>;\n\n\n\n    template <typename T>\n    void remove_duplicates(std::vector<T>& pts) {\n\n        auto pts_end = std::remove_if(pts.begin(), pts.end(), [] (T const& pt){\n            return util::aeq(pt[2], 0.0) || std::isnan(pt(0)) || std::isnan(pt(1)) || std::isinf(pt(0)) || std::isinf(pt(1));\n        });\n        std::sort(pts.begin(), pts_end, [](T const& p1, T const& p2){\n            return p1(0) < p2(0);\n        });\n\n        //This is a version of unique that should be defined for non transitive relationships.\n        auto new_end = pts.end() - 1;\n        if (pts.size() <= 1) {\n            return;\n        }\n        for (auto pt_b = pts.end() - 2; ;pt_b--) {\n            if ((pt_b + 1)->approx_eq(*pt_b)) {\n                std::swap(*(pt_b + 1), *pt_b);\n                std::swap(*(pt_b + 1), *new_end);\n                new_end--;\n            }\n            if (pt_b == pts.begin()) {\n                break;\n            }\n        }\n        pts.erase(new_end + 1, pts.end());\n    }\n\n    inline bool cmpX(Point<2> const& p1, Point<2> const& p2) {\n        return p1(0) < p2(0);\n    }\n\n    inline bool cmpY(Point<2> const& p1, Point<2> const& p2) {\n        return p1(1) < p2(1);\n    }\n\n    using bbox_t = std::tuple<double, double, double, double>;\n\n    template<typename Pt>\n    std::optional<bbox_t> bbox(std::vector<Pt> const& pts) {\n        if (pts.empty()) {\n            return std::nullopt;\n        }\n        auto [mnx, mxx] = std::minmax_element(pts.begin(), pts.end(), cmpX);\n        auto [mny, mxy] = std::minmax_element(pts.begin(), pts.end(), cmpY);\n        return std::make_tuple((*mnx)(0), (*mny)(1), (*mxx)(0), (*mxy)(1));\n    }\n\n    template<typename Pt, typename ...Args>\n    std::optional<bbox_t> bbox(std::vector<Pt> const& pts, Args ...rest) {\n        if (!pts.empty()) {\n            auto opt_bbox = bbox(rest...);\n            auto opt_bbox2 = bbox(pts);\n            if (opt_bbox.has_value() && opt_bbox2.has_value()) {\n                auto[mnx1, mny1, mxx1, mxy1] = opt_bbox.value();\n                auto[mnx2, mny2, mxx2, mxy2] = opt_bbox2.value();\n                return std::make_tuple(std::min(mnx1, mnx2), std::min(mny1, mny2), std::max(mxx1, mxx2),\n                                       std::max(mxy1, mxy2));\n            } else if (opt_bbox.has_value()) {\n                return opt_bbox;\n            } else {\n                return opt_bbox2;\n            }\n        } else {\n            return bbox(rest...);\n        }\n    }\n\n\n//    template <int dim, class URNG>\n//    wpoint_list_t weighted_random_sample_wor(wpoint_list_t& arr, URNG&& g, size_t sample_size) {\n//        std::priority_queue<double, WPoint<dim>> queue_els;\n//\n//        sample_size = std::min(arr.size(), sample_size);\n//        for (size_t i = 0; i < sample_size; ++i) {\n//            std::uniform_int_distribution<decltype(i)> d(i, arr.size() - 1);\n//            std::swap (arr[i], arr[d(g)]);\n//        }\n//        return Vec(arr.begin(), arr.begin() + sample_size);\n//    }\n\n}\n\n\n#endif //PYSCAN_POINT_HPP\n", "meta": {"hexsha": "c5f01ce89bd96536cab9f532910b1abcc70bce8f", "size": 16265, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Point.hpp", "max_stars_repo_name": "michaelmathen/pyscan", "max_stars_repo_head_hexsha": "f0eb78d3e9a6a2048a5c8166f3be5f453b2bea22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-03-22T20:50:37.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T21:13:50.000Z", "max_issues_repo_path": "include/Point.hpp", "max_issues_repo_name": "AprilXiaoyanLiu/pyscan", "max_issues_repo_head_hexsha": "f0eb78d3e9a6a2048a5c8166f3be5f453b2bea22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Point.hpp", "max_forks_repo_name": "AprilXiaoyanLiu/pyscan", "max_forks_repo_head_hexsha": "f0eb78d3e9a6a2048a5c8166f3be5f453b2bea22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-06-26T21:13:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-26T22:03:46.000Z", "avg_line_length": 31.9548133595, "max_line_length": 125, "alphanum_fraction": 0.5019366738, "num_tokens": 4154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4223020047509993}}
{"text": "#pragma once\n#include <vector>\n#include <memory>\n#include <Eigen/Sparse>\n#include \"../DerivedPtrHolder.hh\"\n\nnamespace kt84 {\n\ntemplate <int N>\nstruct LaplaceDirect_VertexTraits {\n    struct Data {\n        bool is_fixed;\n        Eigen::Matrix<double, N, 1> value;\n        Eigen::Matrix<double, N, 1> laplacian;\n        \n        Data()\n            : is_fixed()\n            , value    (Eigen::Matrix<double, N, 1>::Zero())\n            , laplacian(Eigen::Matrix<double, N, 1>::Zero())\n        {}\n    } laplaceDirect;\n};\n\nstruct LaplaceDirect_HalfedgeTraits {\n    double laplaceDirect_weight;\n    LaplaceDirect_HalfedgeTraits()\n        : laplaceDirect_weight(1)\n    {}\n};\n\ntemplate <class TMeshBase, class TMesh, int N>\nstruct LaplaceDirect : public DerivedPtrHolder<TMesh, LaplaceDirect<TMeshBase, TMesh, N>> {\n    typedef Eigen::Matrix<double,  N, 1> Value ;\n    typedef Eigen::Matrix<double, -1, N> Vector;\n    typedef Eigen::SparseMatrix <double> Matrix;\n    \n    double laplaceDirect_constraintWeight;\n    Matrix L;\n    std::shared_ptr<Eigen::SimplicialCholesky<Matrix>> solver;\n    \n    LaplaceDirect()\n        : laplaceDirect_constraintWeight(1000.0)            // better to set large value as default? not really sure...\n    {}\n    \n    void laplaceDirect_factorize() {\n        TMesh* mesh = get_mesh();\n        \n        int nv = mesh->n_vertices();\n        \n        typedef Eigen::Triplet<double> Triplet;\n        std::vector<Triplet> triplets;\n        for (int i = 0; i < nv; ++i) {\n            auto v = mesh->vertex_handle(i);\n            \n            triplets.push_back(Triplet(i, i, 1));\n            \n            double weight_sum = 0;\n            for (auto h = mesh->voh_iter(v); h.is_valid(); ++h)\n                weight_sum += mesh->data(*h).laplaceDirect_weight;\n            \n            for (auto h = mesh->voh_iter(v); h.is_valid(); ++h) {\n                auto w = mesh->to_vertex_handle(*h);\n                double weight = mesh->data(*h).laplaceDirect_weight / weight_sum;\n                \n                triplets.push_back(Triplet(i, w.idx(), -weight));\n            }\n            \n            if (mesh->data(v).laplaceDirect.is_fixed)\n                triplets.push_back(Triplet(i, i, laplaceDirect_constraintWeight));\n        }\n        \n        L.resize(nv, nv);\n        L.setFromTriplets(triplets.begin(), triplets.end());\n        \n        solver.reset(new Eigen::SimplicialCholesky<Matrix>(L.transpose() * L));\n    }\n    \n    void laplaceDirect_solve() {\n        TMesh* mesh = get_mesh();\n        \n        int nv = mesh->n_vertices();\n        \n        if (!solver || L.rows() != nv)\n            laplaceDirect_factorize();\n        \n        // set right hand side\n        Vector b(nv, N);\n        for (int i = 0; i < nv; ++i) {\n            auto& vdata = mesh->data(mesh->vertex_handle(i)).laplaceDirect;\n            \n            b.row(i) = vdata.laplacian.transpose();\n            \n            if (vdata.is_fixed)\n                b.row(i) += laplaceDirect_constraintWeight * vdata.value.transpose();\n        }\n        \n        // solve!\n        Vector x = solver->solve(L.transpose() * b);\n        \n        // copy result to Data::value\n        for (int i = 0; i < nv; ++i) {\n            auto& vdata = mesh->data(mesh->vertex_handle(i)).laplaceDirect;\n            \n            if (!vdata.is_fixed)\n                vdata.value = x.row(i).transpose();\n        }\n    }\n    \n    void laplaceDirect_set_laplacian_from_value() {\n        TMesh* mesh = get_mesh();\n        \n        for (auto v : mesh->vertices()) {\n            auto& vdata = mesh->data(v).laplaceDirect;\n            \n            vdata.laplacian = vdata.value;\n            \n            double weight_sum = 0;\n            for (auto h = mesh->voh_iter(v); h.is_valid(); ++h)\n                weight_sum += mesh->data(*h).laplaceDirect_weight;\n            \n            for (auto h = mesh->voh_iter(v); h.is_valid(); ++h) {\n                auto w = mesh->to_vertex_handle(*h);\n                auto& wdata = mesh->data(w).laplaceDirect;\n                double weight = mesh->data(*h).laplaceDirect_weight / weight_sum;\n                \n                vdata.laplacian -= weight * wdata.value;\n            }\n        }\n    }\nprivate:\n    TMesh* get_mesh() const { return DerivedPtrHolder<TMesh, LaplaceDirect<TMeshBase, TMesh, N>>::derived_ptr; }\n};\n\n}\n", "meta": {"hexsha": "e30451e95b515c8727d1f0f36ccabf88d31ab6d4", "size": 4321, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/openmesh/base/LaplaceDirect.hh", "max_stars_repo_name": "honoriocassiano/skbar", "max_stars_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kt84/openmesh/base/LaplaceDirect.hh", "max_issues_repo_name": "honoriocassiano/skbar", "max_issues_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T12:16:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T12:21:41.000Z", "max_forks_repo_path": "src/kt84/openmesh/base/LaplaceDirect.hh", "max_forks_repo_name": "honoriocassiano/skbar", "max_forks_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0074074074, "max_line_length": 119, "alphanum_fraction": 0.5355241842, "num_tokens": 1071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.42221811782724644}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/optional.hpp>\n#include <cstddef>\n#include <limits>\n\n#include \"DataStructures/Tensor/TypeAliases.hpp\"\n#include \"Domain/OrientationMap.hpp\"\n#include \"Utilities/TypeTraits.hpp\"\n\nnamespace PUP {\nclass er;\n}  // namespace PUP\n\nnamespace CoordinateMaps {\n\n/*!\n * \\ingroup CoordinateMapsGroup\n *\n * \\brief Three dimensional map from the cube to a wedge.\n * \\image html Shell.png \"A shell can be constructed out of six wedges.\"\n *\n * \\details The mapping that goes from a reference cube to a three-dimensional\n *  wedge centered on a coordinate axis covering a volume between an inner\n *  surface and outer surface. Each surface can be given a curvature\n *  between flat (a sphericity of 0) or spherical (a sphericity of 1).\n *\n *  The first two logical coordinates correspond to the two angular coordinates,\n *  and the third to the radial coordinate.\n *\n *  The Wedge3D map is constructed by linearly interpolating between a bulged\n *  face of radius `radius_of_inner_surface` to a bulged face of\n *  radius `radius_of_outer_surface`, where the radius of each bulged face\n *  is defined to be the radius of the sphere circumscribing the bulge.\n *\n *  We make a choice here as to whether we wish to use the logical coordinates\n *  parameterizing these surface as they are, in which case we have the\n *  equidistant choice of coordinates, or whether to apply a tangent map to them\n *  which leads us to the equiangular choice of coordinates. In terms of the\n *  logical coordinates, the equiangular coordinates are:\n *\n *  \\f[\\textrm{equiangular xi} : \\Xi(\\xi) = \\textrm{tan}(\\xi\\pi/4)\\f]\n *\n *  \\f[\\textrm{equiangular eta}  : \\mathrm{H}(\\eta) = \\textrm{tan}(\\eta\\pi/4)\\f]\n *\n *  With derivatives:\n *\n *  \\f[\\Xi'(\\xi) = \\frac{\\pi}{4}(1+\\Xi^2)\\f]\n *\n *  \\f[\\mathrm{H}'(\\eta) = \\frac{\\pi}{4}(1+\\mathrm{H}^2)\\f]\n *\n *  The equidistant coordinates are:\n *\n *  \\f[ \\textrm{equidistant xi}  : \\Xi = \\xi\\f]\n *\n *  \\f[ \\textrm{equidistant eta}  : \\mathrm{H} = \\eta\\f]\n *\n *  with derivatives:\n *\n *  <center>\\f$\\Xi'(\\xi) = 1\\f$, and \\f$\\mathrm{H}'(\\eta) = 1\\f$</center>\n *\n *  We also define the variable \\f$\\rho\\f$, given by:\n *\n *  \\f[\\textrm{rho} : \\rho = \\sqrt{1+\\Xi^2+\\mathrm{H}^2}\\f]\n *\n *  ### The Spherical Face Map\n *  The surface map for the spherical face of radius \\f$R\\f$ lying in the\n * \\f$+z\\f$\n *  direction in either choice of coordinates is then given by:\n *\n *  \\f[\\vec{\\sigma}_{spherical}: \\vec{\\xi} \\rightarrow \\vec{x}(\\vec{\\xi})\\f]\n *  Where\n *  \\f[\n *  \\vec{x}(\\xi,\\eta) =\n *  \\begin{bmatrix}\n *  x(\\xi,\\eta)\\\\\n *  y(\\xi,\\eta)\\\\\n *  z(\\xi,\\eta)\\\\\n *  \\end{bmatrix}  = \\frac{R}{\\rho}\n *  \\begin{bmatrix}\n *  \\Xi\\\\\n *  \\mathrm{H}\\\\\n *  1\\\\\n *  \\end{bmatrix}\\f]\n *\n *  ### The Bulged Face Map\n *  The bulged surface is itself constructed by linearly interpolating between\n *  a cubical face and a spherical face. The surface map for the cubical face\n *  of side length \\f$2L\\f$ lying in the \\f$+z\\f$ direction is given by:\n *\n *  \\f[\\vec{\\sigma}_{cubical}: \\vec{\\xi} \\rightarrow \\vec{x}(\\vec{\\xi})\\f]\n *  Where\n *  \\f[\n *  \\vec{x}(\\xi,\\eta) =\n *  \\begin{bmatrix}\n *  x(\\xi,\\eta)\\\\\n *  y(\\xi,\\eta)\\\\\n *  L\\\\\n *  \\end{bmatrix}  = L\n *  \\begin{bmatrix}\n *  \\Xi\\\\\n *  \\mathrm{H}\\\\\n *  1\\\\\n *  \\end{bmatrix}\\f]\n *\n *  To construct the bulged map we interpolate between this cubical face map\n *  and a spherical face map of radius \\f$R\\f$, with the\n *  interpolation parameter being \\f$s\\f$. The surface map for the bulged face\n *  lying in the \\f$+z\\f$ direction is then given by:\n *\n *  \\f[\\vec{\\sigma}_{bulged}(\\xi,\\eta) = {(1-s)L + \\frac{sR}{\\rho}}\n *  \\begin{bmatrix}\n *  \\Xi\\\\\n *  \\mathrm{H}\\\\\n *  1\\\\\n *  \\end{bmatrix}\\f]\n *\n *  We constrain L by demanding that the spherical face circumscribe the cube.\n *  With this condition, we have \\f$L = R/\\sqrt3\\f$.\n *  \\note This differs from the choice in SpEC where it is demanded that the\n *  surfaces touch at the center, which leads to \\f$L = R\\f$.\n *\n *  ### The Full Volume Map\n *  The final map for the wedge which lies along the \\f$+z\\f$ is obtained by\n *  interpolating between the two surfaces with the\n *  interpolation parameter being the logical coordinate \\f$\\zeta\\f$. This\n *  results in:\n *\n *  \\f[\\vec{x}(\\xi,\\eta,\\zeta) =\n *  \\frac{1}{2}\\left\\{(1-\\zeta)\\Big[(1-s_{inner})\\frac{R_{inner}}{\\sqrt 3}\n *   + s_{inner}\\frac{R_{inner}}{\\rho}\\Big] +\n *  (1+\\zeta)\\Big[(1-s_{outer})\\frac{R_{outer}}{\\sqrt 3} +s_{outer}\n *  \\frac{R_{outer}}{\\rho}\\Big] \\right\\}\\begin{bmatrix}\n *  \\Xi\\\\\n *  \\mathrm{H}\\\\\n *  1\\\\\n *  \\end{bmatrix}\\f]\n *\n *  We will define the variables \\f$F(\\zeta)\\f$ and \\f$S(\\zeta)\\f$, the frustum\n * and sphere factors: \\f[F(\\zeta) = F_0 + F_1\\zeta\\f] \\f[S(\\zeta) = S_0 +\n * S_1\\zeta\\f]\n *  Where \\f{align*}F_0 &= \\frac{1}{2} \\big\\{ (1-s_{outer})R_{outer} +\n * (1-s_{inner})R_{inner}\\big\\}\\\\\n *  F_1 &= \\partial_{\\zeta} F = \\frac{1}{2} \\big\\{ (1-s_{outer})R_{outer} -\n * (1-s_{inner})R_{inner}\\big\\}\\\\\n *  S_0 &= \\frac{1}{2} \\big\\{ s_{outer}R_{outer} + s_{inner}R_{inner}\\big\\}\\\\\n *  S_1 &= \\partial_{\\zeta} S = \\frac{1}{2} \\big\\{ s_{outer}R_{outer} -\n * s_{inner}R_{inner}\\big\\}\\f}\n *\n *  The map can then be rewritten as:\n * \\f[\\vec{x}(\\xi,\\eta,\\zeta) = \\left\\{\\frac{F(\\zeta)}{\\sqrt 3} +\n * \\frac{S(\\zeta)}{\\rho}\\right\\}\\begin{bmatrix}\n *  \\Xi\\\\\n *  \\mathrm{H}\\\\\n *  1\\\\\n *  \\end{bmatrix}\\f]\n *\n *  We provide some common derivatives:\n *  \\f[\\partial_{\\xi}z = \\frac{-S(\\zeta)\\Xi\\Xi'}{\\rho^3}\\f]\n *  \\f[\\partial_{\\eta}z = \\frac{-S(\\zeta)\\mathrm{H}\\mathrm{H}'}{\\rho^3}\\f]\n * \\f[\\partial_{\\zeta}z = \\frac{F'}{\\sqrt 3} + \\frac{S'}{\\rho}\\f]\n *  The Jacobian then is: \\f[J =\n *  \\begin{bmatrix}\n *  \\Xi'z + \\Xi\\partial_{\\xi}z & \\Xi\\partial_{\\eta}z & \\Xi\\partial_{\\zeta}z \\\\\n *  \\mathrm{H}\\partial_{\\xi}z & \\mathrm{H}'z +\n *  \\mathrm{H}\\partial_{\\eta}z & \\mathrm{H}\\partial_{\\zeta}z\\\\\n *   \\partial_{\\xi}z&\\partial_{\\eta}z &\\partial_{\\zeta}z \\\\\n *  \\end{bmatrix}\n *  \\f]\n *\n *  A common factor that shows up in the inverse jacobian is:\n *  \\f[ T:= \\frac{S(\\zeta)}{(\\partial_{\\zeta}z)\\rho^3}\\f]\n *\n *  The inverse Jacobian then is: \\f[J^{-1} =\n *  \\frac{1}{z}\\begin{bmatrix}\n *  \\Xi'^{-1} & 0 & -\\Xi\\Xi'^{-1}\\\\\n *  0 & \\mathrm{H}'^{-1} & -\\mathrm{H}\\mathrm{H}'^{-1}\\\\\n *  T\\Xi &\n *  T\\mathrm{H} &\n *  T + F(\\partial_{\\zeta}z)^{-1}/\\sqrt 3\\\\\n *  \\end{bmatrix}\n *  \\f]\n *\n *  ### Changing the radial distribution of the gridpoints\n *  By default, Wedge3D linearly distributes its gridpoints in the radial\n *  direction. An exponential distribution of gridpoints can be obtained by\n *  linearly interpolating in the logarithm of the radius, in order to obtain\n *  a relatively higher resolution at smaller radii. Since this is a radial\n *  rescaling of Wedge3D, this option is only supported for fully spherical\n *  wedges with `sphericity_inner` = `sphericity_outer` = 1.\n *\n *  The linear interpolation done is:\n *  \\f[\n *  \\log r = \\frac{1-\\zeta}{2}\\log R_{inner} +\n *  \\frac{1+\\zeta}{2}\\log R_{outer}\n *  \\f]\n *\n *  The map then is:\n *  \\f[\\vec{x}(\\xi,\\eta,\\zeta) =\n *  \\frac{\\sqrt{R_{inner}^{1-\\zeta}R_{outer}^{1+\\zeta}}}{\\rho}\\begin{bmatrix}\n *  \\Xi\\\\\n *  \\mathrm{H}\\\\\n *  1\\\\\n *  \\end{bmatrix}\\f]\n *\n *  The jacobian simplifies similarly.\n *\n */\nclass Wedge3D {\n public:\n  static constexpr size_t dim = 3;\n  enum class WedgeHalves {\n    /// Use the entire wedge\n    Both,\n    /// Use only the upper logical half\n    UpperOnly,\n    /// Use only the lower logical half\n    LowerOnly\n  };\n\n  /*!\n   * Constructs a 3D wedge.\n   * \\param radius_inner Distance from the origin to one of the\n   * corners which lie on the inner surface.\n   * \\param radius_outer Distance from the origin to one of the\n   * corners which lie on the outer surface.\n   * \\param orientation_of_wedge The orientation of the desired wedge relative\n   * to the orientation of the default wedge which is a wedge that has its\n   * curved surfaces pierced by the upper-z axis. The logical xi and eta\n   * coordinates point in the cartesian x and y directions, respectively.\n   * \\param sphericity_inner Value between 0 and 1 which determines\n   * whether the inner surface is flat (value of 0), spherical (value of 1) or\n   * somewhere in between\n   * \\param sphericity_outer Value between 0 and 1 which determines\n   * whether the outer surface is flat (value of 0), spherical (value of 1) or\n   * somewhere in between\n   * \\param with_equiangular_map Determines whether to apply a tangent function\n   * mapping to the logical coordinates (for `true`) or not (for `false`).\n   * \\param halves_to_use Determines whether to use the logical xi\n   * coordinates in the [0,1] interval (value of `UpperOnly`) of the full wedge,\n   * the coordinates in the [-1,0] interval (value of `LowerOnly`) of the\n   * full wedge, or the full wedge entirely (value of `Both`). Half wedges are\n   * currently only useful in constructing domains for binary systems.\n   * \\param with_logarithmic_map Determines whether to apply an exponential\n   * function mapping to the \"sphere factor\", the effect of which is to\n   * distribute the radial gridpoints logarithmically in physical space.\n   */\n  Wedge3D(double radius_inner, double radius_outer,\n          OrientationMap<3> orientation_of_wedge, double sphericity_inner,\n          double sphericity_outer, bool with_equiangular_map,\n          WedgeHalves halves_to_use = WedgeHalves::Both,\n          bool with_logarithmic_map = false) noexcept;\n\n  Wedge3D() = default;\n  ~Wedge3D() = default;\n  Wedge3D(Wedge3D&&) = default;\n  Wedge3D(const Wedge3D&) = default;\n  Wedge3D& operator=(const Wedge3D&) = default;\n  Wedge3D& operator=(Wedge3D&&) = default;\n\n  template <typename T>\n  std::array<tt::remove_cvref_wrap_t<T>, 3> operator()(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  /// For a \\f$+z\\f$-oriented `Wedge3D`, returns invalid if \\f$z<=0\\f$\n  /// or if \\f$(x,y,z)\\f$ is on or outside the cone defined\n  /// by \\f$(x^2/z^2 + y^2/z^2+1)^{1/2} = -S/F\\f$, where\n  /// \\f$S = \\frac{1}{2}(s_1 r_1 - s_0 r_0)\\f$ and\n  /// \\f$F = \\frac{1}{2\\sqrt{3}}((1-s_1) r_1 - (1-s_0) r_0)\\f$.\n  /// Here \\f$s_0,s_1\\f$ and \\f$r_0,r_1\\f$ are the specified sphericities\n  /// and radii of the inner and outer \\f$z\\f$ surfaces.  The map is singular on\n  /// the cone and on the xy plane.\n  boost::optional<std::array<double, 3>> inverse(\n      const std::array<double, 3>& target_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> jacobian(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  template <typename T>\n  tnsr::Ij<tt::remove_cvref_wrap_t<T>, 3, Frame::NoFrame> inv_jacobian(\n      const std::array<T, 3>& source_coords) const noexcept;\n\n  // clang-tidy: google runtime references\n  void pup(PUP::er& p) noexcept;  // NOLINT\n\n private:\n  // factors out calculation of z needed for mapping and jacobian\n  template <typename T>\n  tt::remove_cvref_wrap_t<T> default_physical_z(const T& zeta,\n                                                const T& one_over_rho) const\n      noexcept;\n  friend bool operator==(const Wedge3D& lhs, const Wedge3D& rhs) noexcept;\n\n  double radius_inner_{std::numeric_limits<double>::signaling_NaN()};\n  double radius_outer_{std::numeric_limits<double>::signaling_NaN()};\n  OrientationMap<3> orientation_of_wedge_{};\n  double sphericity_inner_{std::numeric_limits<double>::signaling_NaN()};\n  double sphericity_outer_{std::numeric_limits<double>::signaling_NaN()};\n  bool with_equiangular_map_ = false;\n  WedgeHalves halves_to_use_ = WedgeHalves::Both;\n  bool with_logarithmic_map_ = false;\n  double scaled_frustum_zero_{std::numeric_limits<double>::signaling_NaN()};\n  double sphere_zero_{std::numeric_limits<double>::signaling_NaN()};\n  double scaled_frustum_rate_{std::numeric_limits<double>::signaling_NaN()};\n  double sphere_rate_{std::numeric_limits<double>::signaling_NaN()};\n};\nbool operator!=(const Wedge3D& lhs, const Wedge3D& rhs) noexcept;\n}  // namespace CoordinateMaps\n", "meta": {"hexsha": "811e31d9385b2cc91475fb307c973ca8c5d0b285", "size": 11977, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Domain/CoordinateMaps/Wedge3D.hpp", "max_stars_repo_name": "marissawalker/spectre", "max_stars_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Domain/CoordinateMaps/Wedge3D.hpp", "max_issues_repo_name": "marissawalker/spectre", "max_issues_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Domain/CoordinateMaps/Wedge3D.hpp", "max_forks_repo_name": "marissawalker/spectre", "max_forks_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1433121019, "max_line_length": 80, "alphanum_fraction": 0.6536695333, "num_tokens": 3950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.42218294083815516}}
{"text": "/*\n * Copyright 2019 Xilinx, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n *  @brief Kernel implementation file\n *\n *  $DateTime: 2019/04/09 12:00:00 $\n */\n\n#ifndef _HLS_FD_SOLVER_H_\n#define _HLS_FD_SOLVER_H_\n#include \"ap_int.h\"\n#include \"xf_fintech/spmv.hpp\"\n#include \"xf_fintech/dimv.hpp\"\n#include \"xf_fintech/trsv.hpp\"\n#ifndef __SYNTHESIS__\n#include <assert.h>\n#include <boost/algorithm/string.hpp>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#endif\n\n#define PRAGMA_SUB(x) _Pragma(#x)\n#define DO_PRAGMA(x) PRAGMA_SUB(x)\n\nnamespace xf {\nnamespace fintech {\nnamespace internal {\n\n/// @brief Get V-inner index from an S ordered vector\ninline unsigned int V2S(const unsigned int index, const unsigned int m1, const unsigned int m2) {\n    unsigned int row = index % m2;\n    unsigned int col = index / m2;\n    return row * m1 + col;\n}\n\n/// @brief Get S-inner index from an V ordered vector\ninline unsigned int S2V(const unsigned int index, const unsigned int m1, const unsigned int m2) {\n    unsigned int row = index % m1;\n    unsigned int col = index / m1;\n    return row * m2 + col;\n}\n\n/// @brief Class to encapsulate the Finite Difference engine components\ntemplate <typename DT,\n          unsigned int M_SIZE,\n          unsigned int LOG2_M_SIZE,\n          unsigned int A_SIZE,\n          unsigned int MEM_WIDTH,\n          unsigned int DIM2_SIZE1 = 3,\n          unsigned int DIM2_SIZE2 = 5>\nclass Solver {\n   public:\n    /// @brief default constructor\n    Solver() {\n#pragma HLS inline\n    }\n    /// @brief Copy and reorder S ordered vector into V inner form\n    /// @param[in]  v_in  Vector representing array of size m1 x m2 flattened in S\n    /// inner form\n    /// @param[in]  m1   Size of array [0..m1-1] in S direction\n    /// @param[in]  m2   Size of array [0..m2-1] in V direction\n    /// @param[out] v_out Vector representing array of size m1 x m2 flattened in V\n    /// inner form\n    void reorderS2V(const DT v_in[M_SIZE], DT v_out[M_SIZE], const unsigned int m1, const unsigned int m2) {\n#pragma HLS ARRAY_PARTITION variable = v_out cyclic factor = MEM_WIDTH dim = 1\n\n        for (unsigned int i = 0; i < M_SIZE; ++i) {\n#pragma HLS UNROLL factor = MEM_WIDTH\n            v_out[S2V(i, m1, m2)] = v_in[i];\n        }\n    }\n\n    /// @brief Copy and reorder V ordered vector into S inner form\n    /// @param[in]  v_in  Vector representing array of size m1 x m2 flattened in V\n    /// inner form\n    /// @param[in]  m1   Size of array [0..m1] in S direction\n    /// @param[in]  m2   Size of array [0..m2] in V direction\n    /// @param[out] v_out Vector representing array of size m1 x m2 flattened in S\n    /// inner form\n    void reorderV2S(const DT v_in[M_SIZE], DT v_out[M_SIZE], const unsigned int m1, const unsigned int m2) {\n#pragma HLS ARRAY_PARTITION variable = v_out cyclic factor = MEM_WIDTH dim = 1\n\n        for (unsigned int i = 0; i < M_SIZE; ++i) {\n#pragma HLS UNROLL factor = MEM_WIDTH\n            v_out[V2S(i, m1, m2)] = v_in[i];\n        }\n    }\n\n    /// @brief Utility function to copy a vector\n    void CopyVector(const DT v_in[M_SIZE], DT v_out[M_SIZE]) {\n        for (unsigned int i = 0; i < M_SIZE; ++i) {\n            v_out[i] = v_in[i];\n        }\n    }\n\n    /// @brief Utility function to add two vectors\n    void vectorAdd(const DT v_in0[M_SIZE], const DT v_in1[M_SIZE], DT v_out[M_SIZE]) {\n#pragma HLS ARRAY_PARTITION variable = v_out cyclic factor = MEM_WIDTH dim = 1\n\n        for (int i = 0; i < M_SIZE; ++i) {\n#pragma HLS UNROLL factor = MEM_WIDTH\n            v_out[i] = v_in0[i] + v_in1[i];\n        }\n    }\n\n    /// @brief Utility function to subtract two vectors\n    void vectorSub(const DT v_in0[M_SIZE], const DT v_in1[M_SIZE], DT v_out[M_SIZE]) {\n#pragma HLS ARRAY_PARTITION variable = v_out cyclic factor = MEM_WIDTH dim = 1\n\n        for (int i = 0; i < M_SIZE; ++i) {\n#pragma HLS UNROLL factor = MEM_WIDTH\n            v_out[i] = v_in0[i] - v_in1[i];\n        }\n    }\n\n    /// @brief Wrapper to PCR tridiagonal solver\n    /// @details Solves tridiagonal linear system\n    /// @param[in]  X1    M x 3 array holding lower/main/upper diagonals of X1\n    /// tridiagonal matrix\n    /// @param[in]  rhs   Right hand side of linear system to be solved\n    /// @param[in]  m1    Size of array [0..m1-1] in S direction\n    /// @param[in]  m2    Size of array [0..m2-1] in V direction\n    /// @param[out] v_out  Solution vector representing array of size m1 x m2\n    /// flattened in V inner form\n    void triDiagSovlerPCR(\n        DT X1[M_SIZE][DIM2_SIZE1], DT rhs[M_SIZE], DT v_out[M_SIZE], const unsigned int m1, const unsigned int m2) {\n        DT r[M_SIZE];\n        DT a[M_SIZE];\n        DT b[M_SIZE];\n        DT c[M_SIZE];\n#pragma HLS RESOURCE variable = r core = RAM_2P_BRAM\n#pragma HLS RESOURCE variable = a core = RAM_2P_BRAM\n#pragma HLS RESOURCE variable = b core = RAM_2P_BRAM\n#pragma HLS RESOURCE variable = c core = RAM_2P_BRAM\n        DO_PRAGMA(HLS array_partition variable = r cyclic factor = FD_NUM_PCR)\n        DO_PRAGMA(HLS array_partition variable = a cyclic factor = FD_NUM_PCR)\n        DO_PRAGMA(HLS array_partition variable = b cyclic factor = FD_NUM_PCR)\n        DO_PRAGMA(HLS array_partition variable = c cyclic factor = FD_NUM_PCR)\n\n        // Working copies of diagonals as solver will overwrite them\n        for (int i = 0; i < M_SIZE; i++) {\n            //#pragma HLS pipeline\n            r[i] = rhs[i];\n            a[i] = X1[i][0];\n            b[i] = X1[i][1];\n            c[i] = X1[i][2];\n        }\n\n        // Call the PCR tridiagonal solver\n        xf::fintech::trsvCore<DT, M_SIZE, LOG2_M_SIZE, FD_NUM_PCR>(a, b, c, r);\n\n        // Final division for result\n        for (int k = 0; k < M_SIZE; k++) {\n            // Note that v_out is written in V inner order using the S2V function\n            v_out[S2V(k, m1, m2)] = r[k] / b[k];\n        }\n    }\n\n    /// @brief Solve pentadiagonal form linear system\n    /// @details This is a highly serial algorithm and is the bottleneck in this\n    /// solver\n    /// Unfortunately due to the formulation used by In 'T Hout & Foulon, the\n    /// pentadiagonal array contains diagonals\n    /// which are not fully populated.  This causes the common parallel\n    /// pentadiagonal systems to fail due to\n    /// divide-by-zero errors or similar.\n    /// @param[in]  A          M x 5 array holding lower/lower/main/upper/upper\n    /// diagonals of X1 tridiagonal matrix\n    /// @param[in]  rhs        Right hand side of linear system to be solved\n    /// @param[in]  precompute Flag to indicate the scaling factors should be\n    /// computed\n    /// @param[out] v_out       Solution vector representing array of size m1 x m2\n    /// flattened in V inner form\n    void pendaDiagSovler(DT A[M_SIZE][DIM2_SIZE2], DT rhs[M_SIZE], DT v_out[M_SIZE], bool precompute) {\n        // These are preprocessed versions of the diagonals.\n        // For a given array these are constant so they are calculated once and\n        // cached (by marking as static) and using precompute variable.\n        static DT d[M_SIZE];\n        static DT a[M_SIZE];\n        static DT e[M_SIZE];\n        static DT c[M_SIZE];\n        static DT f[M_SIZE];\n\n        static DT xmult0[M_SIZE];\n        static DT xmult1[M_SIZE];\n\n        static DT xmult_r;\n\n        static DT d_inv[M_SIZE];\n\n        // Not static as this changes each time\n        DT r[M_SIZE];\n\n        // Working variable\n        DT xmult = 0.0;\n\n        // One time precomputation of the vectors\n        if (precompute) {\n            // Main diagonal\n            for (unsigned int i = 0; i < M_SIZE; ++i) {\n                d[i] = A[i][2];\n            }\n\n            // First upper/lower, dropping padded zeros\n            for (unsigned int i = 0; i < M_SIZE - 1; ++i) {\n                a[i] = A[i + 1][1];\n                c[i] = A[i][3];\n            }\n\n            // Second upper/lower, dropping padded zeros\n            for (unsigned int i = 0; i < M_SIZE - 2; ++i) {\n                e[i] = A[i + 2][0];\n                f[i] = A[i][4];\n            }\n\n            // Scaling factors\n            for (unsigned int i = 1; i < (M_SIZE - 1); ++i) {\n                xmult = a[i - 1] / d[i - 1];\n                d[i] = d[i] - xmult * c[i - 1];\n                c[i] = c[i] - xmult * f[i - 1];\n                xmult0[i] = xmult;\n                xmult = e[i - 1] / d[i - 1];\n                a[i] = a[i] - xmult * c[i - 1];\n                d[i + 1] = d[i + 1] - xmult * f[i - 1];\n                xmult1[i] = xmult;\n            }\n\n            // d manipulation\n            xmult_r = a[M_SIZE - 2] / d[M_SIZE - 2];\n            d[M_SIZE - 1] = d[M_SIZE - 1] - xmult_r * c[M_SIZE - 2];\n\n            // Invert d (one time operation and allows multiplies to be used later on)\n            for (unsigned int i = 0; i < M_SIZE; ++i) {\n                d_inv[i] = 1.0 / d[i];\n            }\n        }\n\n        // Input vector changes each time\n        for (unsigned int i = 0; i < M_SIZE; ++i) {\n            r[i] = rhs[i];\n        }\n\n        // Apply the scaling factors\n        for (unsigned int i = 1; i < (M_SIZE - 1); ++i) {\n            r[i] = r[i] - xmult0[i] * r[i - 1];\n            r[i + 1] = r[i + 1] - xmult1[i] * r[i - 1];\n        }\n\n        // Back solve\n        v_out[M_SIZE - 1] = (r[M_SIZE - 1] - xmult_r * r[M_SIZE - 2]) * d_inv[M_SIZE - 1];\n        v_out[M_SIZE - 2] = (r[M_SIZE - 2] - c[M_SIZE - 2] * v_out[M_SIZE - 1]) * d_inv[M_SIZE - 2];\n        unsigned int i = M_SIZE - 3;\n        do {\n            v_out[i] = (r[i] - f[i] * v_out[i + 2] - c[i] * v_out[i + 1]) * d_inv[i];\n        } while (i-- > 0);\n    }\n};\n\n/// @brief Utility class to encapsulate the multiplier elements\ntemplate <typename DT,\n          unsigned int MEM_WIDTH,\n          unsigned int INDEX_WIDTH,\n          unsigned int A_SIZE,\n          unsigned int M_SIZE,\n          unsigned int LOG2_M_SIZE,\n          unsigned int DIM2_SIZE1 = 3,\n          unsigned int DIM2_SIZE2 = 5>\nclass StreamWrapper {\n   private:\n    static const unsigned int M_SIZE_BLOCKS = M_SIZE / MEM_WIDTH;\n\n   public:\n    typedef xf::fintech::blas::WideType<DT, MEM_WIDTH> WideDataType;\n    typedef hls::stream<WideDataType> WideStreamType;\n\n   public:\n    /// @brief default constructor\n    StreamWrapper() {\n#pragma HLS inline\n    }\n    /// @brief Computes multiplication of tridiagonal matrix by a vector\n    /// @param[in]  A1         M x 3 array holding lower/main/upper diagonals of\n    /// A1 tridiagonal matrix\n    /// @param[in]  u          Vector to be multiplied\n    /// @param[out] rhs1_tmp0 Multiplication result\n    /// @param[out] u_out     Stream form of U to pass to pentadiagonal multiplier\n    void streamDimv3(DT A1[M_SIZE][DIM2_SIZE1], DT u[M_SIZE], DT rhs1_tmp0[M_SIZE], WideStreamType& u_out) {\n        for (unsigned int i = 0; i < M_SIZE_BLOCKS; ++i) {\n#pragma HLS PIPELINE\n            WideDataType val;\n#pragma HLS ARRAY_PARTITION variable = val complete\n            for (unsigned int j = 0; j < MEM_WIDTH; ++j) {\n                val[j] = u[i * MEM_WIDTH + j];\n            }\n            u_out.write(val);\n        }\n        xf::fintech::blas::dimv<DT, M_SIZE, DIM2_SIZE1, MEM_WIDTH>(A1, u, M_SIZE, rhs1_tmp0);\n    }\n\n    /// @brief Computes multiplication of pentadiagonal matrix by a vector\n    /// @param[in]  A2         M x 5 array holding lower/main/upper diagonals of\n    /// A2 tridiagonal matrix\n    /// @param[in]  u_in      Vector to be multiplied [stream format]\n    /// @param[in]  m1         Size of array [0..m1-1] in S direction\n    /// @param[in]  m2         Size of array [0..m2-1] in V direction\n    /// @param[out] rhs2_tmp0 Multiplication result\n    /// @param[out] u_out     Vector output [stream format]\n    void streamDimv5(DT A2[M_SIZE][DIM2_SIZE2],\n                     WideStreamType& u_in,\n                     unsigned int m1,\n                     unsigned int m2,\n                     DT rhs2_tmp0[M_SIZE],\n                     WideStreamType& u_out) {\n        DT u_r0[M_SIZE]; // S-inner\n        DT u_r1[M_SIZE]; // V-inner\n#pragma HLS ARRAY_PARTITION variable = u_r0 cyclic factor = MEM_WIDTH dim = 1\n#pragma HLS ARRAY_PARTITION variable = u_r1 cyclic factor = MEM_WIDTH dim = 1\n\n        for (unsigned int i = 0; i < M_SIZE_BLOCKS; ++i) {\n#pragma HLS PIPELINE\n            WideDataType val;\n#pragma HLS ARRAY_PARTITION variable = val complete\n            val = u_in.read();\n            u_out.write(val);\n            for (unsigned int j = 0; j < MEM_WIDTH; ++j) {\n                u_r0[i * MEM_WIDTH + j] = val[j];\n            }\n        }\n        // S2V conversion\n        Solver<DT, M_SIZE, LOG2_M_SIZE, A_SIZE, MEM_WIDTH> solver;\n        solver.reorderS2V(u_r0, u_r1, m1, m2);\n        xf::fintech::blas::dimv<DT, M_SIZE, DIM2_SIZE2, MEM_WIDTH>(A2, u_r1, M_SIZE, rhs2_tmp0);\n    }\n\n    /// @brief Computes multiplication of sparse matrix by vector plus a constant\n    /// @param[in]  A          Sparse matrix value\n    /// @param[in]  Ar         Sparse matrix row\n    /// @param[in]  Ac         Sparse matrix column\n    /// @param[in]  u_in      Vector to be multiplied [stream format]\n    /// @param[in]  b          Vector to be added after sparse-mult stage\n    /// @param[in]  Annz       Number of non-zeros in sparse matrix (how many\n    /// elements of A/Ar/Ac are valid)\n    /// @param[in]  M          Matrix M-size === (m1+1) x (m2+1)\n    /// @param[out] y0         Result of mult-add in flattened S-inner form\n    void streamSparseMultAdd(DT A[A_SIZE],\n                             unsigned int Ar[A_SIZE],\n                             unsigned int Ac[A_SIZE],\n                             WideStreamType& u_in,\n                             DT b[M_SIZE],\n                             unsigned int Annz,\n                             unsigned int M,\n                             DT y0[M_SIZE]) {\n#pragma HLS ARRAY_PARTITION variable = y0 cyclic factor = MEM_WIDTH dim = 1\n        DT u[M_SIZE];\n#pragma HLS ARRAY_PARTITION variable = u cyclic factor = MEM_WIDTH dim = 1\n        DT y0_tmp1[M_SIZE];\n#pragma HLS ARRAY_PARTITION variable = y0_tmp1 cyclic factor = MEM_WIDTH dim = 1\n\n        for (unsigned int i = 0; i < M_SIZE_BLOCKS; ++i) {\n#pragma HLS PIPELINE\n            WideDataType val = u_in.read();\n#pragma HLS ARRAY_PARTITION variable = val complete\n            for (unsigned int j = 0; j < MEM_WIDTH; ++j) {\n                u[i * MEM_WIDTH + j] = val[j];\n            }\n        }\n        xf::fintech::blas::Spmv<DT, MEM_WIDTH, INDEX_WIDTH, M_SIZE, M_SIZE, A_SIZE> spmv;\n        spmv.sparseMultAdd(A, Ar, Ac, u, b, y0_tmp1, Annz, M);\n        unsigned int vec_blocks = M / MEM_WIDTH;\n        for (unsigned int i = 0; i < vec_blocks; ++i) {\n#pragma HLS PIPELINE\n            for (unsigned int j = 0; j < MEM_WIDTH; ++j) {\n                y0[i * MEM_WIDTH + j] = u[i * MEM_WIDTH + j] + y0_tmp1[i * MEM_WIDTH + j];\n            }\n        }\n    }\n\n    /// @brief Wrapper function to combine multipliers into a dataflow region and\n    /// allow parallelization\n    void parallelBlocks(DT A[A_SIZE],\n                        unsigned int Ar[A_SIZE],\n                        unsigned int Ac[A_SIZE],\n                        DT u[M_SIZE],\n                        DT b[M_SIZE],\n                        unsigned int Annz,\n                        unsigned int M,\n                        DT A1[M_SIZE][DIM2_SIZE1],\n                        DT A2[M_SIZE][DIM2_SIZE2],\n                        unsigned int m1,\n                        unsigned int m2,\n                        DT y0[M_SIZE],\n                        DT rhs1_tmp0[M_SIZE],\n                        DT rhs2_tmp0[M_SIZE]) {\n        WideStreamType u0;\n        WideStreamType u1;\n#pragma HLS DATAFLOW\n        streamDimv3(A1, u, rhs1_tmp0, u0);\n        streamDimv5(A2, u0, m1, m2, rhs2_tmp0, u1);\n        streamSparseMultAdd(A, Ar, Ac, u1, b, Annz, M, y0);\n    }\n};\n\n} // end of internal namespace block\n\n/// @brief Top level callable function to perform the Douglas ADI method\n/// @details This function creates the solver/stream wrapper objects and connects\n/// them up\n/// It also provides the extra connectivity for the non-streaming blocks\n/// @param[in]  A          Sparse matrix value\n/// @param[in]  Ar         Sparse matrix row\n/// @param[in]  Ac         Sparse matrix column\n/// @param[in]  Annz       Number of non-zeros in sparse matrix (how many\n/// elements of A/Ar/Ac are valid)\n/// @param[in]  A1         Tridiagonal matrix stored as three vectors\n/// lower/main/upper\n/// @param[in]  A2         Pentadiagonal matrix stored as five vectors\n/// lower/lower/main/upper/upper\n/// @param[in]  X1         Tridiagonal matrix stored as three vectors\n/// lower/main/upper\n/// @param[in]  X2         Pentadiagonal matrix stored as five vectors\n/// lower/lower/main/upper/upper\n/// @param[in]  b          Boundary condition vector\n/// @param[in]  u0         Initial condition (payoff condition for a call\n/// option)\n/// @param[in]  M1         Size of array [0..M1] in S direction\n/// @param[in]  M2         Size of array [0..M2] in V direction\n/// @param[in]  N          Iteration count\n/// @param[out] u          Calculated price grid\ntemplate <typename DT,\n          unsigned int MEM_WIDTH,\n          unsigned int INDEX_WIDTH,\n          unsigned int A_SIZE,\n          unsigned int M_SIZE,\n          unsigned int LOG2_M_SIZE,\n          unsigned int DIM2_SIZE1,\n          unsigned int DIM2_SIZE2>\nvoid FdDouglas(DT A[A_SIZE],\n               unsigned int Ar[A_SIZE],\n               unsigned int Ac[A_SIZE],\n               unsigned int Annz,\n               DT A1[M_SIZE][DIM2_SIZE1],\n               DT A2[M_SIZE][DIM2_SIZE2],\n               DT X1[M_SIZE][DIM2_SIZE1],\n               DT X2[M_SIZE][DIM2_SIZE2],\n               DT b[M_SIZE],\n               DT u0[M_SIZE],\n               unsigned int M1,\n               unsigned int M2,\n               unsigned int N,\n               DT u[M_SIZE]) {\n    DT y0[M_SIZE];\n#pragma HLS ARRAY_PARTITION variable = y0 cyclic factor = MEM_WIDTH dim = 1\n    DT rhs1[M_SIZE];\n    DT y1[M_SIZE];\n    DT rhs2[M_SIZE];\n    DT y2[M_SIZE];\n\n    DT rhs1_tmp0[M_SIZE];\n    DT rhs2_tmp0[M_SIZE];\n\n    internal::Solver<DT, M_SIZE, LOG2_M_SIZE, A_SIZE, MEM_WIDTH, DIM2_SIZE1, DIM2_SIZE2> solver;\n    internal::StreamWrapper<DT, MEM_WIDTH, INDEX_WIDTH, A_SIZE, M_SIZE, LOG2_M_SIZE> stream_wrapper;\n\n    solver.CopyVector(u0, u);\n\n    // Perform the Douglas iteration\n    // After N iterations the u vector will hold the output\n    for (int i = 0; i < N; ++i) {\n        // These operations are performed in parallel with a stream passing vector\n        // data between them\n        stream_wrapper.parallelBlocks(A, Ar, Ac, u, b, Annz, M_SIZE, A1, A2, M1, M2, y0, rhs1_tmp0, rhs2_tmp0);\n\n        // These operations depending on the previous one completing and run\n        // sequentially\n        solver.vectorSub(y0, rhs1_tmp0, rhs1);\n        solver.triDiagSovlerPCR(X1, rhs1, y1, M1, M2);\n        solver.vectorSub(y1, rhs2_tmp0, rhs2);\n        solver.pendaDiagSovler(X2, rhs2, y2, i == 0);\n\n        // Vector u has to be reordered back to S-inner form\n        solver.reorderV2S(y2, u, M1, M2);\n    }\n}\n}\n} // End of namespace xf::fintech\n\n#endif\n", "meta": {"hexsha": "729a2348f3593f1207636fee2f3e193c7fb6a8dd", "size": 19596, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "quantitative_finance/L2/include/xf_fintech/fd_solver.hpp", "max_stars_repo_name": "vmayoral/Vitis_Libraries", "max_stars_repo_head_hexsha": "2323dc5036041e18242718287aee4ce66ba071ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T06:37:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T06:37:15.000Z", "max_issues_repo_path": "quantitative_finance/L2/include/xf_fintech/fd_solver.hpp", "max_issues_repo_name": "vmayoral/Vitis_Libraries", "max_issues_repo_head_hexsha": "2323dc5036041e18242718287aee4ce66ba071ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quantitative_finance/L2/include/xf_fintech/fd_solver.hpp", "max_forks_repo_name": "vmayoral/Vitis_Libraries", "max_forks_repo_head_hexsha": "2323dc5036041e18242718287aee4ce66ba071ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-28T05:58:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T05:58:38.000Z", "avg_line_length": 38.880952381, "max_line_length": 116, "alphanum_fraction": 0.5820575628, "num_tokens": 5355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.42218294083815516}}
{"text": "//\n// Copyright (c) 2002--2010\n// Toon Knapen, Karl Meerbergen, Kresimir Fresl,\n// Thomas Klimpel and Rutger ter Borg\n//\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n// THIS FILE IS AUTOMATICALLY GENERATED\n// PLEASE DO NOT EDIT!\n//\n\n#ifndef BOOST_NUMERIC_BINDINGS_LAPACK_DRIVER_GEEVX_HPP\n#define BOOST_NUMERIC_BINDINGS_LAPACK_DRIVER_GEEVX_HPP\n\n#include <boost/assert.hpp>\n#include <boost/numeric/bindings/begin.hpp>\n#include <boost/numeric/bindings/detail/array.hpp>\n#include <boost/numeric/bindings/is_column_major.hpp>\n#include <boost/numeric/bindings/is_complex.hpp>\n#include <boost/numeric/bindings/is_mutable.hpp>\n#include <boost/numeric/bindings/is_real.hpp>\n#include <boost/numeric/bindings/lapack/workspace.hpp>\n#include <boost/numeric/bindings/remove_imaginary.hpp>\n#include <boost/numeric/bindings/size.hpp>\n#include <boost/numeric/bindings/stride.hpp>\n#include <boost/numeric/bindings/traits/detail/utils.hpp>\n#include <boost/numeric/bindings/value_type.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/type_traits/remove_const.hpp>\n#include <boost/utility/enable_if.hpp>\n\n//\n// The LAPACK-backend for geevx is the netlib-compatible backend.\n//\n#include <boost/numeric/bindings/lapack/detail/lapack.h>\n#include <boost/numeric/bindings/lapack/detail/lapack_option.hpp>\n\nnamespace boost {\nnamespace numeric {\nnamespace bindings {\nnamespace lapack {\n\n//\n// The detail namespace contains value-type-overloaded functions that\n// dispatch to the appropriate back-end LAPACK-routine.\n//\nnamespace detail {\n\n//\n// Overloaded function for dispatching to\n// * netlib-compatible LAPACK backend (the default), and\n// * float value-type.\n//\ninline std::ptrdiff_t geevx( const char balanc, const char jobvl,\n        const char jobvr, const char sense, const fortran_int_t n, float* a,\n        const fortran_int_t lda, float* wr, float* wi, float* vl,\n        const fortran_int_t ldvl, float* vr, const fortran_int_t ldvr,\n        fortran_int_t& ilo, fortran_int_t& ihi, float* scale, float& abnrm,\n        float* rconde, float* rcondv, float* work, const fortran_int_t lwork,\n        fortran_int_t* iwork ) {\n    fortran_int_t info(0);\n    LAPACK_SGEEVX( &balanc, &jobvl, &jobvr, &sense, &n, a, &lda, wr, wi, vl,\n            &ldvl, vr, &ldvr, &ilo, &ihi, scale, &abnrm, rconde, rcondv, work,\n            &lwork, iwork, &info );\n    return info;\n}\n\n//\n// Overloaded function for dispatching to\n// * netlib-compatible LAPACK backend (the default), and\n// * double value-type.\n//\ninline std::ptrdiff_t geevx( const char balanc, const char jobvl,\n        const char jobvr, const char sense, const fortran_int_t n, double* a,\n        const fortran_int_t lda, double* wr, double* wi, double* vl,\n        const fortran_int_t ldvl, double* vr, const fortran_int_t ldvr,\n        fortran_int_t& ilo, fortran_int_t& ihi, double* scale, double& abnrm,\n        double* rconde, double* rcondv, double* work,\n        const fortran_int_t lwork, fortran_int_t* iwork ) {\n    fortran_int_t info(0);\n    LAPACK_DGEEVX( &balanc, &jobvl, &jobvr, &sense, &n, a, &lda, wr, wi, vl,\n            &ldvl, vr, &ldvr, &ilo, &ihi, scale, &abnrm, rconde, rcondv, work,\n            &lwork, iwork, &info );\n    return info;\n}\n\n//\n// Overloaded function for dispatching to\n// * netlib-compatible LAPACK backend (the default), and\n// * complex<float> value-type.\n//\ninline std::ptrdiff_t geevx( const char balanc, const char jobvl,\n        const char jobvr, const char sense, const fortran_int_t n,\n        std::complex<float>* a, const fortran_int_t lda,\n        std::complex<float>* w, std::complex<float>* vl,\n        const fortran_int_t ldvl, std::complex<float>* vr,\n        const fortran_int_t ldvr, fortran_int_t& ilo, fortran_int_t& ihi,\n        float* scale, float& abnrm, float* rconde, float* rcondv,\n        std::complex<float>* work, const fortran_int_t lwork, float* rwork ) {\n    fortran_int_t info(0);\n    LAPACK_CGEEVX( &balanc, &jobvl, &jobvr, &sense, &n, a, &lda, w, vl, &ldvl,\n            vr, &ldvr, &ilo, &ihi, scale, &abnrm, rconde, rcondv, work,\n            &lwork, rwork, &info );\n    return info;\n}\n\n//\n// Overloaded function for dispatching to\n// * netlib-compatible LAPACK backend (the default), and\n// * complex<double> value-type.\n//\ninline std::ptrdiff_t geevx( const char balanc, const char jobvl,\n        const char jobvr, const char sense, const fortran_int_t n,\n        std::complex<double>* a, const fortran_int_t lda,\n        std::complex<double>* w, std::complex<double>* vl,\n        const fortran_int_t ldvl, std::complex<double>* vr,\n        const fortran_int_t ldvr, fortran_int_t& ilo, fortran_int_t& ihi,\n        double* scale, double& abnrm, double* rconde, double* rcondv,\n        std::complex<double>* work, const fortran_int_t lwork,\n        double* rwork ) {\n    fortran_int_t info(0);\n    LAPACK_ZGEEVX( &balanc, &jobvl, &jobvr, &sense, &n, a, &lda, w, vl, &ldvl,\n            vr, &ldvr, &ilo, &ihi, scale, &abnrm, rconde, rcondv, work,\n            &lwork, rwork, &info );\n    return info;\n}\n\n} // namespace detail\n\n//\n// Value-type based template class. Use this class if you need a type\n// for dispatching to geevx.\n//\ntemplate< typename Value, typename Enable = void >\nstruct geevx_impl {};\n\n//\n// This implementation is enabled if Value is a real type.\n//\ntemplate< typename Value >\nstruct geevx_impl< Value, typename boost::enable_if< is_real< Value > >::type > {\n\n    typedef Value value_type;\n    typedef typename remove_imaginary< Value >::type real_type;\n\n    //\n    // Static member function for user-defined workspaces, that\n    // * Deduces the required arguments for dispatching to LAPACK, and\n    // * Asserts that most arguments make sense.\n    //\n    template< typename MatrixA, typename VectorWR, typename VectorWI,\n            typename MatrixVL, typename MatrixVR, typename VectorSCALE,\n            typename VectorRCONDE, typename VectorRCONDV, typename WORK,\n            typename IWORK >\n    static std::ptrdiff_t invoke( const char balanc, const char jobvl,\n            const char jobvr, const char sense, MatrixA& a, VectorWR& wr,\n            VectorWI& wi, MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n            fortran_int_t& ihi, VectorSCALE& scale, real_type& abnrm,\n            VectorRCONDE& rconde, VectorRCONDV& rcondv, detail::workspace2<\n            WORK, IWORK > work ) {\n        namespace bindings = ::boost::numeric::bindings;\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixVL >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixVR >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                VectorWR >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                VectorWI >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                MatrixVL >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                MatrixVR >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                VectorSCALE >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                VectorRCONDE >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                VectorRCONDV >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorWR >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorWI >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixVL >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixVR >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorSCALE >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorRCONDE >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorRCONDV >::value) );\n        BOOST_ASSERT( bindings::size(rconde) >= bindings::size_column(a) );\n        BOOST_ASSERT( bindings::size(rcondv) >= bindings::size_column(a) );\n        BOOST_ASSERT( bindings::size(wi) >= bindings::size_column(a) );\n        BOOST_ASSERT( bindings::size(work.select(fortran_int_t())) >=\n                min_size_iwork( sense, bindings::size_column(a) ));\n        BOOST_ASSERT( bindings::size(work.select(real_type())) >=\n                min_size_work( sense, jobvl, jobvr,\n                bindings::size_column(a) ));\n        BOOST_ASSERT( bindings::size(wr) >= bindings::size_column(a) );\n        BOOST_ASSERT( bindings::size_column(a) >= 0 );\n        BOOST_ASSERT( bindings::size_minor(a) == 1 ||\n                bindings::stride_minor(a) == 1 );\n        BOOST_ASSERT( bindings::size_minor(vl) == 1 ||\n                bindings::stride_minor(vl) == 1 );\n        BOOST_ASSERT( bindings::size_minor(vr) == 1 ||\n                bindings::stride_minor(vr) == 1 );\n        BOOST_ASSERT( bindings::stride_major(a) >= std::max< std::ptrdiff_t >(1,\n                bindings::size_column(a)) );\n        BOOST_ASSERT( balanc == 'N' || balanc == 'P' || balanc == 'S' ||\n                balanc == 'B' );\n        BOOST_ASSERT( jobvl == 'N' || jobvl == 'V' || jobvl == 'E' ||\n                jobvl == 'B' );\n        BOOST_ASSERT( jobvr == 'N' || jobvr == 'V' || jobvr == 'E' ||\n                jobvr == 'B' );\n        BOOST_ASSERT( sense == 'N' || sense == 'E' || sense == 'V' ||\n                sense == 'B' );\n        return detail::geevx( balanc, jobvl, jobvr, sense,\n                bindings::size_column(a), bindings::begin_value(a),\n                bindings::stride_major(a), bindings::begin_value(wr),\n                bindings::begin_value(wi), bindings::begin_value(vl),\n                bindings::stride_major(vl), bindings::begin_value(vr),\n                bindings::stride_major(vr), ilo, ihi,\n                bindings::begin_value(scale), abnrm,\n                bindings::begin_value(rconde), bindings::begin_value(rcondv),\n                bindings::begin_value(work.select(real_type())),\n                bindings::size(work.select(real_type())),\n                bindings::begin_value(work.select(fortran_int_t())) );\n    }\n\n    //\n    // Static member function that\n    // * Figures out the minimal workspace requirements, and passes\n    //   the results to the user-defined workspace overload of the \n    //   invoke static member function\n    // * Enables the unblocked algorithm (BLAS level 2)\n    //\n    template< typename MatrixA, typename VectorWR, typename VectorWI,\n            typename MatrixVL, typename MatrixVR, typename VectorSCALE,\n            typename VectorRCONDE, typename VectorRCONDV >\n    static std::ptrdiff_t invoke( const char balanc, const char jobvl,\n            const char jobvr, const char sense, MatrixA& a, VectorWR& wr,\n            VectorWI& wi, MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n            fortran_int_t& ihi, VectorSCALE& scale, real_type& abnrm,\n            VectorRCONDE& rconde, VectorRCONDV& rcondv, minimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        bindings::detail::array< real_type > tmp_work( min_size_work( sense,\n                jobvl, jobvr, bindings::size_column(a) ) );\n        bindings::detail::array< fortran_int_t > tmp_iwork(\n                min_size_iwork( sense, bindings::size_column(a) ) );\n        return invoke( balanc, jobvl, jobvr, sense, a, wr, wi, vl, vr, ilo,\n                ihi, scale, abnrm, rconde, rcondv, workspace( tmp_work,\n                tmp_iwork ) );\n    }\n\n    //\n    // Static member function that\n    // * Figures out the optimal workspace requirements, and passes\n    //   the results to the user-defined workspace overload of the \n    //   invoke static member\n    // * Enables the blocked algorithm (BLAS level 3)\n    //\n    template< typename MatrixA, typename VectorWR, typename VectorWI,\n            typename MatrixVL, typename MatrixVR, typename VectorSCALE,\n            typename VectorRCONDE, typename VectorRCONDV >\n    static std::ptrdiff_t invoke( const char balanc, const char jobvl,\n            const char jobvr, const char sense, MatrixA& a, VectorWR& wr,\n            VectorWI& wi, MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n            fortran_int_t& ihi, VectorSCALE& scale, real_type& abnrm,\n            VectorRCONDE& rconde, VectorRCONDV& rcondv, optimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        real_type opt_size_work;\n        bindings::detail::array< fortran_int_t > tmp_iwork(\n                min_size_iwork( sense, bindings::size_column(a) ) );\n        detail::geevx( balanc, jobvl, jobvr, sense,\n                bindings::size_column(a), bindings::begin_value(a),\n                bindings::stride_major(a), bindings::begin_value(wr),\n                bindings::begin_value(wi), bindings::begin_value(vl),\n                bindings::stride_major(vl), bindings::begin_value(vr),\n                bindings::stride_major(vr), ilo, ihi,\n                bindings::begin_value(scale), abnrm,\n                bindings::begin_value(rconde), bindings::begin_value(rcondv),\n                &opt_size_work, -1, bindings::begin_value(tmp_iwork) );\n        bindings::detail::array< real_type > tmp_work(\n                traits::detail::to_int( opt_size_work ) );\n        return invoke( balanc, jobvl, jobvr, sense, a, wr, wi, vl, vr, ilo,\n                ihi, scale, abnrm, rconde, rcondv, workspace( tmp_work,\n                tmp_iwork ) );\n    }\n\n    //\n    // Static member function that returns the minimum size of\n    // workspace-array work.\n    //\n    static std::ptrdiff_t min_size_work( const char sense, const char jobvl,\n            const char jobvr, const std::ptrdiff_t n ) {\n        if ( sense == 'N' || sense == 'E' ) {\n            if ( jobvl =='V' || jobvr == 'V' )\n                return std::max< std::ptrdiff_t >( 1, 3*n );\n            else\n                return std::max< std::ptrdiff_t >( 1, 2*n );\n        } else\n            return std::max< std::ptrdiff_t >( 1, n*(n+6) );\n    }\n\n    //\n    // Static member function that returns the minimum size of\n    // workspace-array iwork.\n    //\n    static std::ptrdiff_t min_size_iwork( const char sense,\n            const std::ptrdiff_t n ) {\n        if ( sense == 'N' || sense == 'E' )\n            return 0;\n        else\n            return 2*n-2;\n    }\n};\n\n//\n// This implementation is enabled if Value is a complex type.\n//\ntemplate< typename Value >\nstruct geevx_impl< Value, typename boost::enable_if< is_complex< Value > >::type > {\n\n    typedef Value value_type;\n    typedef typename remove_imaginary< Value >::type real_type;\n\n    //\n    // Static member function for user-defined workspaces, that\n    // * Deduces the required arguments for dispatching to LAPACK, and\n    // * Asserts that most arguments make sense.\n    //\n    template< typename MatrixA, typename VectorW, typename MatrixVL,\n            typename MatrixVR, typename VectorSCALE, typename VectorRCONDE,\n            typename VectorRCONDV, typename WORK, typename RWORK >\n    static std::ptrdiff_t invoke( const char balanc, const char jobvl,\n            const char jobvr, const char sense, MatrixA& a, VectorW& w,\n            MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n            fortran_int_t& ihi, VectorSCALE& scale, real_type& abnrm,\n            VectorRCONDE& rconde, VectorRCONDV& rcondv, detail::workspace2<\n            WORK, RWORK > work ) {\n        namespace bindings = ::boost::numeric::bindings;\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixVL >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_column_major< MatrixVR >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< VectorSCALE >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                VectorRCONDE >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< VectorSCALE >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                VectorRCONDV >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                VectorW >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                MatrixVL >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (boost::is_same< typename remove_const<\n                typename bindings::value_type< MatrixA >::type >::type,\n                typename remove_const< typename bindings::value_type<\n                MatrixVR >::type >::type >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixA >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorW >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixVL >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< MatrixVR >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorSCALE >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorRCONDE >::value) );\n        BOOST_STATIC_ASSERT( (bindings::is_mutable< VectorRCONDV >::value) );\n        BOOST_ASSERT( bindings::size(rconde) >= bindings::size_column(a) );\n        BOOST_ASSERT( bindings::size(rcondv) >= bindings::size_column(a) );\n        BOOST_ASSERT( bindings::size(w) >= bindings::size_column(a) );\n        BOOST_ASSERT( bindings::size(work.select(real_type())) >=\n                min_size_rwork( bindings::size_column(a) ));\n        BOOST_ASSERT( bindings::size(work.select(value_type())) >=\n                min_size_work( sense, bindings::size_column(a) ));\n        BOOST_ASSERT( bindings::size_column(a) >= 0 );\n        BOOST_ASSERT( bindings::size_minor(a) == 1 ||\n                bindings::stride_minor(a) == 1 );\n        BOOST_ASSERT( bindings::size_minor(vl) == 1 ||\n                bindings::stride_minor(vl) == 1 );\n        BOOST_ASSERT( bindings::size_minor(vr) == 1 ||\n                bindings::stride_minor(vr) == 1 );\n        BOOST_ASSERT( bindings::stride_major(a) >= std::max< std::ptrdiff_t >(1,\n                bindings::size_column(a)) );\n        BOOST_ASSERT( balanc == 'N' || balanc == 'P' || balanc == 'S' ||\n                balanc == 'B' );\n        BOOST_ASSERT( jobvl == 'N' || jobvl == 'V' || jobvl == 'E' ||\n                jobvl == 'B' );\n        BOOST_ASSERT( jobvr == 'N' || jobvr == 'V' || jobvr == 'E' ||\n                jobvr == 'B' );\n        BOOST_ASSERT( sense == 'N' || sense == 'E' || sense == 'V' ||\n                sense == 'B' );\n        return detail::geevx( balanc, jobvl, jobvr, sense,\n                bindings::size_column(a), bindings::begin_value(a),\n                bindings::stride_major(a), bindings::begin_value(w),\n                bindings::begin_value(vl), bindings::stride_major(vl),\n                bindings::begin_value(vr), bindings::stride_major(vr), ilo,\n                ihi, bindings::begin_value(scale), abnrm,\n                bindings::begin_value(rconde), bindings::begin_value(rcondv),\n                bindings::begin_value(work.select(value_type())),\n                bindings::size(work.select(value_type())),\n                bindings::begin_value(work.select(real_type())) );\n    }\n\n    //\n    // Static member function that\n    // * Figures out the minimal workspace requirements, and passes\n    //   the results to the user-defined workspace overload of the \n    //   invoke static member function\n    // * Enables the unblocked algorithm (BLAS level 2)\n    //\n    template< typename MatrixA, typename VectorW, typename MatrixVL,\n            typename MatrixVR, typename VectorSCALE, typename VectorRCONDE,\n            typename VectorRCONDV >\n    static std::ptrdiff_t invoke( const char balanc, const char jobvl,\n            const char jobvr, const char sense, MatrixA& a, VectorW& w,\n            MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n            fortran_int_t& ihi, VectorSCALE& scale, real_type& abnrm,\n            VectorRCONDE& rconde, VectorRCONDV& rcondv, minimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        bindings::detail::array< value_type > tmp_work( min_size_work( sense,\n                bindings::size_column(a) ) );\n        bindings::detail::array< real_type > tmp_rwork( min_size_rwork(\n                bindings::size_column(a) ) );\n        return invoke( balanc, jobvl, jobvr, sense, a, w, vl, vr, ilo, ihi,\n                scale, abnrm, rconde, rcondv, workspace( tmp_work,\n                tmp_rwork ) );\n    }\n\n    //\n    // Static member function that\n    // * Figures out the optimal workspace requirements, and passes\n    //   the results to the user-defined workspace overload of the \n    //   invoke static member\n    // * Enables the blocked algorithm (BLAS level 3)\n    //\n    template< typename MatrixA, typename VectorW, typename MatrixVL,\n            typename MatrixVR, typename VectorSCALE, typename VectorRCONDE,\n            typename VectorRCONDV >\n    static std::ptrdiff_t invoke( const char balanc, const char jobvl,\n            const char jobvr, const char sense, MatrixA& a, VectorW& w,\n            MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n            fortran_int_t& ihi, VectorSCALE& scale, real_type& abnrm,\n            VectorRCONDE& rconde, VectorRCONDV& rcondv, optimal_workspace ) {\n        namespace bindings = ::boost::numeric::bindings;\n        value_type opt_size_work;\n        bindings::detail::array< real_type > tmp_rwork( min_size_rwork(\n                bindings::size_column(a) ) );\n        detail::geevx( balanc, jobvl, jobvr, sense,\n                bindings::size_column(a), bindings::begin_value(a),\n                bindings::stride_major(a), bindings::begin_value(w),\n                bindings::begin_value(vl), bindings::stride_major(vl),\n                bindings::begin_value(vr), bindings::stride_major(vr), ilo,\n                ihi, bindings::begin_value(scale), abnrm,\n                bindings::begin_value(rconde), bindings::begin_value(rcondv),\n                &opt_size_work, -1, bindings::begin_value(tmp_rwork) );\n        bindings::detail::array< value_type > tmp_work(\n                traits::detail::to_int( opt_size_work ) );\n        return invoke( balanc, jobvl, jobvr, sense, a, w, vl, vr, ilo, ihi,\n                scale, abnrm, rconde, rcondv, workspace( tmp_work,\n                tmp_rwork ) );\n    }\n\n    //\n    // Static member function that returns the minimum size of\n    // workspace-array work.\n    //\n    static std::ptrdiff_t min_size_work( const char sense,\n            const std::ptrdiff_t n ) {\n        if ( sense == 'N' || sense == 'E' )\n            return std::max< std::ptrdiff_t >( 1, 2*n );\n        else\n            return std::max< std::ptrdiff_t >( 1, n*n + 2*n );\n    }\n\n    //\n    // Static member function that returns the minimum size of\n    // workspace-array rwork.\n    //\n    static std::ptrdiff_t min_size_rwork( const std::ptrdiff_t n ) {\n        return 2*n;\n    }\n};\n\n\n//\n// Functions for direct use. These functions are overloaded for temporaries,\n// so that wrapped types can still be passed and used for write-access. In\n// addition, if applicable, they are overloaded for user-defined workspaces.\n// Calls to these functions are passed to the geevx_impl classes. In the \n// documentation, most overloads are collapsed to avoid a large number of\n// prototypes which are very similar.\n//\n\n//\n// Overloaded function for geevx. Its overload differs for\n// * User-defined workspace\n//\ntemplate< typename MatrixA, typename VectorWR, typename VectorWI,\n        typename MatrixVL, typename MatrixVR, typename VectorSCALE,\n        typename VectorRCONDE, typename VectorRCONDV, typename Workspace >\ninline typename boost::enable_if< detail::is_workspace< Workspace >,\n        std::ptrdiff_t >::type\ngeevx( const char balanc, const char jobvl, const char jobvr,\n        const char sense, MatrixA& a, VectorWR& wr, VectorWI& wi,\n        MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n        fortran_int_t& ihi, VectorSCALE& scale, typename remove_imaginary<\n        typename bindings::value_type< MatrixA >::type >::type& abnrm,\n        VectorRCONDE& rconde, VectorRCONDV& rcondv, Workspace work ) {\n    return geevx_impl< typename bindings::value_type<\n            MatrixA >::type >::invoke( balanc, jobvl, jobvr, sense, a, wr, wi,\n            vl, vr, ilo, ihi, scale, abnrm, rconde, rcondv, work );\n}\n\n//\n// Overloaded function for geevx. Its overload differs for\n// * Default workspace-type (optimal)\n//\ntemplate< typename MatrixA, typename VectorWR, typename VectorWI,\n        typename MatrixVL, typename MatrixVR, typename VectorSCALE,\n        typename VectorRCONDE, typename VectorRCONDV >\ninline typename boost::disable_if< detail::is_workspace< VectorRCONDV >,\n        std::ptrdiff_t >::type\ngeevx( const char balanc, const char jobvl, const char jobvr,\n        const char sense, MatrixA& a, VectorWR& wr, VectorWI& wi,\n        MatrixVL& vl, MatrixVR& vr, fortran_int_t& ilo,\n        fortran_int_t& ihi, VectorSCALE& scale, typename remove_imaginary<\n        typename bindings::value_type< MatrixA >::type >::type& abnrm,\n        VectorRCONDE& rconde, VectorRCONDV& rcondv ) {\n    return geevx_impl< typename bindings::value_type<\n            MatrixA >::type >::invoke( balanc, jobvl, jobvr, sense, a, wr, wi,\n            vl, vr, ilo, ihi, scale, abnrm, rconde, rcondv,\n            optimal_workspace() );\n}\n\n//\n// Overloaded function for geevx. Its overload differs for\n// * User-defined workspace\n//\ntemplate< typename MatrixA, typename VectorW, typename MatrixVL,\n        typename MatrixVR, typename VectorSCALE, typename VectorRCONDE,\n        typename VectorRCONDV, typename Workspace >\ninline typename boost::enable_if< detail::is_workspace< Workspace >,\n        std::ptrdiff_t >::type\ngeevx( const char balanc, const char jobvl, const char jobvr,\n        const char sense, MatrixA& a, VectorW& w, MatrixVL& vl, MatrixVR& vr,\n        fortran_int_t& ilo, fortran_int_t& ihi, VectorSCALE& scale,\n        typename remove_imaginary< typename bindings::value_type<\n        MatrixA >::type >::type& abnrm, VectorRCONDE& rconde,\n        VectorRCONDV& rcondv, Workspace work ) {\n    return geevx_impl< typename bindings::value_type<\n            MatrixA >::type >::invoke( balanc, jobvl, jobvr, sense, a, w, vl,\n            vr, ilo, ihi, scale, abnrm, rconde, rcondv, work );\n}\n\n//\n// Overloaded function for geevx. Its overload differs for\n// * Default workspace-type (optimal)\n//\ntemplate< typename MatrixA, typename VectorW, typename MatrixVL,\n        typename MatrixVR, typename VectorSCALE, typename VectorRCONDE,\n        typename VectorRCONDV >\ninline typename boost::disable_if< detail::is_workspace< VectorRCONDV >,\n        std::ptrdiff_t >::type\ngeevx( const char balanc, const char jobvl, const char jobvr,\n        const char sense, MatrixA& a, VectorW& w, MatrixVL& vl, MatrixVR& vr,\n        fortran_int_t& ilo, fortran_int_t& ihi, VectorSCALE& scale,\n        typename remove_imaginary< typename bindings::value_type<\n        MatrixA >::type >::type& abnrm, VectorRCONDE& rconde,\n        VectorRCONDV& rcondv ) {\n    return geevx_impl< typename bindings::value_type<\n            MatrixA >::type >::invoke( balanc, jobvl, jobvr, sense, a, w, vl,\n            vr, ilo, ihi, scale, abnrm, rconde, rcondv, optimal_workspace() );\n}\n\n} // namespace lapack\n} // namespace bindings\n} // namespace numeric\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "5eec32dc2f8641d6ced5eaa38d6f29b6e8750fd5", "size": 29147, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/boost/numeric/bindings/lapack/driver/geevx.hpp", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/boost/numeric/bindings/lapack/driver/geevx.hpp", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/boost/numeric/bindings/lapack/driver/geevx.hpp", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 48.7408026756, "max_line_length": 84, "alphanum_fraction": 0.6380759598, "num_tokens": 7282, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.42218294083815516}}
{"text": "#ifndef PHYSYCOM_UTILS_VORONOI_HPP\n#define PHYSYCOM_UTILS_VORONOI_HPP\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstdio>\n#include <vector>\n\n#include <boost/polygon/voronoi.hpp>\n\nusing boost::polygon::voronoi_builder;\nusing boost::polygon::voronoi_diagram;\nusing boost::polygon::x;\nusing boost::polygon::y;\nusing boost::polygon::low;\nusing boost::polygon::high;\n\n\nnamespace physycom\n{\n  constexpr double PI = 3.1415926535;\n  inline double atan2_2pi(const double &y, const double &x)\n  {\n    double th = std::atan2(y,x);\n    return (th >= 0) ? th : 2*PI + th;\n  }\n\n  struct Point\n  {\n    int x, y;\n    Point() : x(0), y(0) {}\n    Point(int x, int y) : x(x), y(y) {}\n    bool operator==(const Point &p)\n    {\n      return x == p.x && y == p.y;\n    }\n    bool operator!=(const Point &p)\n    {\n      return ! (*this == p);\n    }\n    friend std::ostream &operator<<(std::ostream &stream, const Point &p)\n    {\n      stream << \"[\" << p.x << \",\" << p.y << \"]\";\n      return stream;\n    }\n  };\n\n  struct Segment\n  {\n    Point p0, p1;\n    Segment(int x1, int y1, int x2, int y2) : p0(x1, y1), p1(x2, y2) {}\n  };\n\n  struct Box\n  {\n    int xmin, xmax, ymin, ymax;\n    Box() : xmin(0), xmax(0), ymin(0), ymax(0) {}\n    Box(const int &xmin, const int &xmax, const int &ymin, const int &ymax) : xmin(xmin), xmax(xmax), ymin(ymin), ymax(ymax) {}\n    bool contains(const Point &p)\n    {\n      return p.x > xmin && p.x < xmax && p.y > ymin && p.y < ymax;\n    }\n    void encompass(const Point &p)\n    {\n      if (xmin > p.x)\n        xmin = (p.x > 0) ? 0.9*p.x : 1.1*p.x;\n      if (xmax < p.x)\n        xmax = (p.x > 0) ? 1.1*p.x : 0.9*p.x;\n      if (ymin > p.y)\n        ymin = (p.y > 0) ? 0.9*p.y : 1.1*p.y;\n      if (xmax < p.x)\n        ymax = (p.y > 0) ? 1.1*p.y : 0.9*p.y;\n    }\n    friend std::ostream &operator<<(std::ostream &stream, const Box &b)\n    {\n      stream << \"[\" << b.xmin << \",\" << b.xmax << \"]x[\" << b.ymin << \",\" << b.ymax << \"]\";\n      return stream;\n    }\n  };\n\n  struct Polygon\n  {\n    std::vector<Point> points;\n    Polygon() {}\n    Polygon(std::vector<Point> &points) : points(points) {}\n  };\n\n} // physycom\n\nnamespace boost\n{\n  namespace polygon\n  {\n    using namespace physycom;\n\n    template <>\n    struct geometry_concept<Point>\n    {\n      typedef point_concept type;\n    };\n\n    template <>\n    struct point_traits<Point>\n    {\n      typedef int coordinate_type;\n\n      static inline coordinate_type get(const Point& point, orientation_2d orient)\n      {\n        return (orient == HORIZONTAL) ? point.x : point.y;\n      }\n    };\n\n    template <>\n    struct geometry_concept<Segment>\n    {\n      typedef segment_concept type;\n    };\n\n    template <>\n    struct segment_traits<Segment>\n    {\n      typedef int coordinate_type;\n      typedef Point point_type;\n\n      static inline point_type get(const Segment& segment, direction_1d dir)\n      {\n        return dir.to_int() ? segment.p1 : segment.p0;\n      }\n    };\n  }  // polygon\n}  // boost\n\nnamespace physycom\n{\n  struct voronoi\n  {\n    std::vector<Point> points, points_voro;\n    Box bounds;\n    std::vector<Polygon> cells;\n    voronoi_diagram<double> vd;\n\n    voronoi() {}\n    voronoi(const std::vector<Point> &points, const Box &bounds) : points(points), bounds(bounds)\n    {\n      construct_voronoi(this->points.begin(), this->points.end(), &(this->vd));\n      int cell_index = 0;\n      for (auto cell = vd.cells().begin(); cell != vd.cells().end(); ++cell)\n      {\n        Polygon pg;\n        if (cell->contains_point())\n        {\n          if (cell->source_category() == boost::polygon::SOURCE_CATEGORY_SINGLE_POINT)\n          {\n            // retrieve point in cell\n            std::size_t index = cell->source_index();\n            Point p = this->points[index];\n            points_voro.push_back(p);\n            std::cout << \"cell #\" << cell_index << std::endl;\n\n            // loop over cell edges\n            auto *edge = cell->incident_edge();\n            int edge_cnt = 0;\n            do\n            {\n              edge = edge->next();\n              if (edge->is_finite())\n              {\n                Point p0 = Point(edge->vertex0()->x(), edge->vertex0()->y());\n                Point p1 = Point(edge->vertex1()->x(), edge->vertex1()->y());\n                std::cout << \"FINITE \" << p0 << \" \" << p1 << std::endl;\n                if (!pg.points.size())\n                  pg.points.push_back(p0);\n                pg.points.push_back(p1);\n              }\n              else if (edge->is_infinite())\n              {\n                auto cell1 = edge->cell();\n                auto cell2 = edge->twin()->cell();\n                Point origin, direction;\n                std::vector<Point> clipped_edge;\n                if (cell1->contains_point() && cell2->contains_point())\n                {\n                  Point p1 = points[edge->cell()->source_index()];\n                  Point p2 = points[edge->twin()->cell()->source_index()];\n                  origin.x = (p1.x + p2.x) * 0.5;\n                  origin.y = (p1.y + p2.y) * 0.5;\n                  direction.x = p1.y - p2.y;\n                  direction.y = p2.x - p1.x;\n                }\n\n                double theta1 = physycom::atan2_2pi(bounds.ymax - origin.y, bounds.xmax - origin.x);\n                double theta2 = physycom::atan2_2pi(bounds.ymax - origin.y, bounds.xmin - origin.x);\n                double theta3 = physycom::atan2_2pi(bounds.ymin - origin.y, bounds.xmin - origin.x);\n                double theta4 = physycom::atan2_2pi(bounds.ymin - origin.y, bounds.xmax - origin.x);\n\n/*\n                std::cout << \"t1 \" << theta1 * 180 / PI << \" \" << bounds.ymax - origin.y << \" \" << bounds.xmax - origin.x << std::endl\n                          << \"t2 \" << theta2 * 180 / PI << \" \" << bounds.ymax - origin.y << \" \" << bounds.xmin - origin.x << std::endl\n                          << \"t3 \" << theta3 * 180 / PI << \" \" << bounds.ymin - origin.y << \" \" << bounds.xmin - origin.x << std::endl\n                          << \"t4 \" << theta4 * 180 / PI << \" \" << bounds.ymin - origin.y << \" \" << bounds.xmax - origin.x << std::endl;\n*/\n\n                if (edge->vertex0() == NULL)\n                {\n                  direction.x *= -1;\n                  direction.y *= -1;\n                }\n                double thetad = physycom::atan2_2pi(direction.y, direction.x);\n\n                Point clipped;\n                if ( thetad <= theta1 || thetad > theta4 )\n                  clipped = Point(bounds.xmax, origin.y + ( direction.y * ( bounds.xmax - origin.x) ) / direction.x );\n                else if ( thetad <= theta2 )\n                  clipped = Point(origin.x + ( direction.x * ( bounds.ymax - origin.y) ) / direction.y, bounds.ymax );\n                else if ( thetad <= theta3 )\n                  clipped = Point(bounds.xmin, origin.y - ( direction.y * ( bounds.xmin - origin.x) ) / direction.x );\n                else if ( thetad <= theta4 )\n                  clipped = Point(origin.x - ( direction.x * ( bounds.ymin - origin.y) ) / direction.y, bounds.ymin );\n                std::cout << \"clip \" << origin << \" \" << direction << \" \" << clipped << std::endl;\n                std::cout << \"INFINITE \" << origin << \" \" << clipped <<  std::endl;\n\n                if (edge->vertex0() != NULL)\n                {\n                  if (pg.points.size() == 0)\n                    pg.points.push_back(origin);\n                  if (pg.points.back() != origin)\n                    pg.points.push_back(origin);\n                  pg.points.push_back(clipped);\n                }\n                else\n                {\n                  pg.points.push_back(clipped);\n                  pg.points.push_back(origin);\n                }\n\n              }\n              edge_cnt++;\n            } while (edge != cell->incident_edge());\n          }\n        }\n        ++cell_index;\n        this->cells.push_back(pg);\n      }\n    }\n  };\n\n} // end of namespace physycom\n\n#endif // PHYSYCOM_UTILS_VORONOI_HPP\n", "meta": {"hexsha": "86f46e2dccb5960fca23faf865e13049510d894c", "size": 7953, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "physycom/voronoi.hpp", "max_stars_repo_name": "physycom/utils", "max_stars_repo_head_hexsha": "f5144e434f6e4b2804802c84188c72b833fa03d2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-18T11:00:49.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-18T11:00:49.000Z", "max_issues_repo_path": "physycom/voronoi.hpp", "max_issues_repo_name": "physycom/utils", "max_issues_repo_head_hexsha": "f5144e434f6e4b2804802c84188c72b833fa03d2", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "physycom/voronoi.hpp", "max_forks_repo_name": "physycom/utils", "max_forks_repo_head_hexsha": "f5144e434f6e4b2804802c84188c72b833fa03d2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6852589641, "max_line_length": 135, "alphanum_fraction": 0.4983025273, "num_tokens": 2088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.42218293407049584}}
{"text": "/** \\file kernel_functors.hpp \\brief Kernel (covariance) functions */\n/*\n-------------------------------------------------------------------------\n   This file is part of BayesOpt, an efficient C++ library for \n   Bayesian optimization.\n\n   Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n   BayesOpt is free software: you can redistribute it and/or modify it \n   under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   BayesOpt is distributed in the hope that it will be useful, but \n   WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with BayesOpt.  If not, see <http://www.gnu.org/licenses/>.\n------------------------------------------------------------------------\n*/\n\n#ifndef  _KERNEL_FUNCTORS_HPP_\n#define  _KERNEL_FUNCTORS_HPP_\n\n#include <map>\n#include <boost/scoped_ptr.hpp>\n#include <boost/math/distributions/normal.hpp> \n#include \"bayesopt/parameters.hpp\"\n#include \"specialtypes.hpp\"\n\nnamespace bayesopt\n{\n  \n  /**\\addtogroup KernelFunctions\n   * \\brief Set of kernel or covariance functions for the nonparametric\n   * processes.\n   */\n  //@{\n\n  /** \\brief Interface for kernel functors */\n  class Kernel\n  {\n  public:\n    virtual ~Kernel(){};\n    virtual void init(size_t input_dim) {};\n    virtual void init(size_t input_dim, Kernel* left, Kernel* right) {};\n\n    virtual void setHyperParameters(const vectord &theta) = 0;\n    virtual vectord getHyperParameters() = 0;\n    virtual size_t nHyperParameters() = 0;\n\n    virtual double operator()( const vectord &x1, const vectord &x2 ) = 0;\n    virtual double gradient( const vectord &x1, const vectord &x2,\n\t\t\t     size_t component ) = 0;\n\n  protected:\n    size_t n_inputs;\n  };\n\n\n\n  template <typename KernelType> Kernel * create_func()\n  {\n    return new KernelType();\n  }\n\n  /** \n   * \\brief Factory model for kernel functions\n   * This factory is based on the libgp library by Manuel Blum\n   *      https://bitbucket.org/mblum/libgp\n   * which follows the squeme of GPML by Rasmussen and Nickisch\n   *     http://www.gaussianprocess.org/gpml/code/matlab/doc/\n   */\n  class KernelFactory\n  {\n  public:\n    KernelFactory ();\n    virtual ~KernelFactory () {};\n  \n    Kernel* create(std::string name, size_t input_dim);\n    \n  private:\n    typedef Kernel* (*create_func_definition)();\n    std::map<std::string , KernelFactory::create_func_definition> registry;\n  };\n\n\n  class KernelModel\n  {\n  public:\n    KernelModel(size_t dim, Parameters parameters);\n    virtual ~KernelModel() {};\n\n    Kernel* getKernel();\n    \n    void setHyperParameters(const vectord &theta);\n    vectord getHyperParameters();\n    size_t nHyperParameters();\n\n\n    /** \n     * \\brief Select kernel (covariance function) for the surrogate process.\n     * @param thetav kernel parameters (mean)\n     * @param stheta kernel parameters (std)\n     * @param k_name kernel name\n     */\n    void setKernel (const vectord &thetav, const vectord &stheta, \n\t\t   std::string k_name, size_t dim);\n\n    /** Wrapper of setKernel for C++ kernel structure */\n    void setKernel (KernelParameters kernel, size_t dim);\n\n    void computeCorrMatrix(const vecOfvec& XX, matrixd& corrMatrix, double nugget);\n    void computeDerivativeCorrMatrix(const vecOfvec& XX, matrixd& corrMatrix, \n\t\t\t\t    int dth_index);\n    vectord computeCrossCorrelation(const vecOfvec& XX, const vectord &query);\n    void computeCrossCorrelation(const vecOfvec& XX, const vectord &query,\n\t\t\t\t vectord& knx);\n    double computeSelfCorrelation(const vectord& query);\n    double kernelLogPrior();\n\n  private:\n    /** Set prior (Gaussian) for kernel hyperparameters */\n    void setKernelPrior (const vectord &theta, const vectord &s_theta);\n\n    boost::scoped_ptr<Kernel> mKernel;            ///< Pointer to kernel function\n    std::vector<boost::math::normal> priorKernel; ///< Prior of kernel parameters\n  };\n\n  inline Kernel* KernelModel::getKernel()\n  { return mKernel.get();  }\n\n  inline void KernelModel::setHyperParameters(const vectord &theta)\n  { mKernel->setHyperParameters(theta); };\n    \n  inline vectord KernelModel::getHyperParameters()\n  {return mKernel->getHyperParameters();};\n  \n  inline size_t KernelModel::nHyperParameters()\n  {return mKernel->nHyperParameters();};\n\n  inline vectord KernelModel::computeCrossCorrelation(const vecOfvec& XX, \n\t\t\t\t\t\t      const vectord &query)\n  {\n    vectord knx(XX.size());\n    computeCrossCorrelation(XX,query,knx);\n    return knx;\n  }\n\n  inline void KernelModel::computeCrossCorrelation(const vecOfvec& XX, \n\t\t\t\t\t\t   const vectord &query,\n\t\t\t\t\t\t   vectord& knx)\n  {\n    std::vector<vectord>::const_iterator x_it  = XX.begin();\n    vectord::iterator k_it = knx.begin();\n    while(x_it != XX.end())\n      {\t*k_it++ = (*mKernel)(*x_it++, query); }\n  }\n\n\n  inline double KernelModel::computeSelfCorrelation(const vectord& query)\n  { return (*mKernel)(query,query); }\n\n  inline void KernelModel::setKernelPrior (const vectord &theta, \n\t\t\t\t\t   const vectord &s_theta)\n  {\n    for (size_t i = 0; i<theta.size(); ++i)\n      {\n\tboost::math::normal n(theta(i),s_theta(i));\n\tpriorKernel.push_back(n);\n      }\n  };\n\n\n  //@}\n\n} //namespace bayesopt\n\n\n#endif\n", "meta": {"hexsha": "4492e2926afe317cb03b5f48210e03c2e3ead351", "size": 5451, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/bayesopt/include/kernel_functors.hpp", "max_stars_repo_name": "pchrapka/brain-modelling", "max_stars_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T19:37:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-13T19:37:52.000Z", "max_issues_repo_path": "external/bayesopt/include/kernel_functors.hpp", "max_issues_repo_name": "pchrapka/brain-modelling", "max_issues_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/bayesopt/include/kernel_functors.hpp", "max_forks_repo_name": "pchrapka/brain-modelling", "max_forks_repo_head_hexsha": "f232b5a858e45f10b0b0735269010454129ab017", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T12:22:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T12:22:05.000Z", "avg_line_length": 29.7868852459, "max_line_length": 83, "alphanum_fraction": 0.6732709595, "num_tokens": 1345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4221162342510207}}
{"text": "/* ---------------------------------------------------------------------\n**\n** Copyright (C) 2017 Xiaoyu Wei\n**\n** Permission is hereby granted, free of charge, to any person obtaining a copy\n** of this software and associated documentation files (the \"Software\"), to deal\n** in the Software without restriction, including without limitation the rights\n** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n** copies of the Software, and to permit persons to whom the Software is\n** furnished to do so, subject to the following conditions:\n**\n** The above copyright notice and this permission notice shall be included in\n** all copies or substantial portions of the Software.\n**\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n** THE SOFTWARE.\n**\n** -------------------------------------------------------------------*/\n\n#include <array>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <string>\n\n#include <pybind11/numpy.h>\n#include <pybind11/pybind11.h>\n\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/lac/vector.h>\n\nnamespace py = pybind11;\nnamespace d = dealii;\n\nconstexpr double a = -1;\nconstexpr double b = 1;\nconst d::UpdateFlags update_flags =\n    d::update_quadrature_points | d::update_JxW_values;\n\nvoid greet() { std::cout << \"Hello from meshgen11_dealii.\" << std::endl; }\n\n// {{{ utils\n\n// make a copy of py::array to dealii::Vector\ntemplate <class Number>\nd::Vector<Number> pyarr_to_dvec(py::array_t<Number> arr) {\n\n  py::buffer_info info = arr.request();\n  if (info.ndim != 1) {\n    throw std::runtime_error(\"Number of dimensions must be one\");\n  }\n\n  // pointer to the data buffer\n  Number *iter = (Number *)info.ptr;\n\n  d::Vector<Number> dvec;\n  dvec.reinit(info.shape[0]);\n  Number *ptc = iter;\n  for (unsigned int c = 0; c < info.shape[0]; ++c) {\n    dvec[c] = *ptc;\n    ++ptc;\n  }\n\n  return dvec;\n}\n\ntemplate <int dim>\ndouble l_infty_distance(d::Point<dim> &p1, d::Point<dim> &p2) {\n  double dist = std::numeric_limits<double>::max();\n  for (unsigned int d = 0; d < dim; ++d) {\n    double tmp = std::abs(p1[d] - p2[d]);\n    dist = tmp > dist ? dist : tmp;\n  }\n  return dist;\n}\n\ntemplate <int dim>\ndouble compute_q_point_radii(\n    d::Point<dim> q_point,\n    std::array<d::Point<dim>, d::GeometryInfo<dim>::vertices_per_cell>\n        &vertices) {\n  double rad = std::numeric_limits<double>::max();\n  for (auto &&v : vertices) {\n    double tmp = l_infty_distance(q_point, v);\n    rad = tmp > rad ? rad : tmp;\n  }\n  return rad;\n}\n\ntemplate <int dimension, int n_vertices>\nd::Point<dimension>\ncompute_barycenter(std::array<d::Point<dimension>, n_vertices> &vertices) {\n\n  d::Point<dimension> bc;\n  for (unsigned int d = 0; d < dimension; ++d) {\n    bc[d] = 0;\n  }\n\n  for (auto &&v : vertices) {\n    bc += v;\n  }\n  bc /= n_vertices;\n  return bc;\n}\n\n// }}}\n\n// {{{ MeshGenerator class\n\ntemplate <int dimension> class MeshGenerator {\npublic:\n  d::Triangulation<dimension> triangulation;\n  d::FE_Q<dimension> fe;\n  d::DoFHandler<dimension> dof_handler;\n  d::QGauss<dimension> quadrature_formula;\n\n  double box_a, box_b;\n\n  unsigned int max_n_cells;\n  unsigned int min_grid_level, max_grid_level;\n\n  // q: quad order\n  // level: initial (uniform) level\n  // bounding box: [aa, bb]^dim\n  MeshGenerator(\n      int q, int level, double aa, double bb,\n      py::args args, py::kwargs kwargs,\n      unsigned int max_n_cells = std::numeric_limits<unsigned int>::max(),\n      unsigned int min_grid_level = std::numeric_limits<unsigned int>::min(),\n      unsigned int max_grid_level = std::numeric_limits<unsigned int>::max())\n      : triangulation(d::Triangulation<dimension>::limit_level_difference_at_vertices), fe(q),\n        dof_handler(triangulation), quadrature_formula(q), box_a(aa), box_b(bb),\n        max_n_cells(max_n_cells), min_grid_level(min_grid_level),\n        max_grid_level(max_grid_level) {\n    d::GridGenerator::hyper_cube(triangulation, box_a, box_b);\n\n    // initial number of levels must be compatible\n    assert(level > min_grid_level);\n    assert(level <= max_grid_level + 1);\n    assert(std::pow(std::pow(2, dimension), level - 1) <= max_n_cells);\n\n    if (level > 1) {\n      triangulation.refine_global(level - 1);\n    }\n    this->dof_handler.distribute_dofs(fe);\n  }\n\n  // NOTE: Copy constructor is not supported since dealii::DoFHandler is not\n  // copy constructable, but a dummy copy constructor is required by\n  // boost.python to build the code.\n  MeshGenerator(const MeshGenerator<dimension> &) : MeshGenerator(1, 1){};\n\n  std::string greet() { return \"Hello from MeshGen.\"; }\n\n  void generate_gmsh(const std::string fn) {\n    std::string filename = fn;\n    std::ofstream output_file(filename);\n    d::GridOut().write_msh(this->triangulation, output_file);\n    std::cout << \"Mesh written in \" << filename << std::endl;\n  }\n\n  void write_vtu(const std::string fn) {\n    std::string filename = fn;\n    std::ofstream output_file(filename);\n    d::GridOut().write_vtu(this->triangulation, output_file);\n    std::cout << \"Mesh written in \" << filename << std::endl;\n  }\n\n  py::array get_q_points() {\n    py::dtype dtype = py::dtype::of<double>();\n\n    const size_t n_q_points = this->quadrature_formula.size();\n    const size_t total_n_q_points = triangulation.n_active_cells() * n_q_points;\n\n    std::array<size_t, 2> pt_shape = {total_n_q_points, dimension};\n    std::array<size_t, 2> pt_strides = {dimension * sizeof(double),\n                                        sizeof(double)};\n\n    d::FEValues<dimension> fe_values(this->fe, this->quadrature_formula,\n                                     d::update_quadrature_points);\n    std::vector<double> points(pt_shape[0] * pt_shape[1], 0);\n    auto ptp = points.data();\n\n    auto cell = dof_handler.begin_active();\n    auto endc = dof_handler.end();\n    for (; cell != endc; ++cell) {\n      fe_values.reinit(cell);\n      std::vector<d::Point<dimension>> q_points =\n          fe_values.get_quadrature_points();\n\n      for (auto &&point : q_points) {\n        for (unsigned int d = 0; d < dimension; ++d) {\n          // For a preferred ordering of quad points\n          // This does not change anything but the ordering due to the symmetry\n          // in each direction (as long as the subdivided boxes are cubes), not\n          // even weights are changed.\n          *ptp = point[dimension - 1 - d];\n          ++ptp;\n        }\n      }\n    }\n\n    return py::array(py::buffer_info(points.data(), sizeof(double),\n                                     py::format_descriptor<double>::value, 2,\n                                     pt_shape, pt_strides));\n  }\n\n  py::array get_q_weights() {\n    py::dtype dtype = py::dtype::of<double>();\n\n    const size_t n_q_points = this->quadrature_formula.size();\n    const size_t total_n_q_points =\n        this->triangulation.n_active_cells() * n_q_points;\n\n    std::array<size_t, 1> w_shape = {total_n_q_points};\n    std::array<size_t, 1> w_strides = {sizeof(double)};\n\n    d::FEValues<dimension> fe_values(this->fe, this->quadrature_formula,\n                                     d::update_JxW_values);\n\n    std::vector<double> weights(w_shape[0], 0);\n    auto ptw = weights.data();\n\n    auto cell = this->dof_handler.begin_active();\n    auto endc = this->dof_handler.end();\n    for (; cell != endc; ++cell) {\n      fe_values.reinit(cell);\n      std::vector<double> q_weights;\n\n      for (unsigned int q_index = 0; q_index < n_q_points; ++q_index) {\n        q_weights.push_back(fe_values.JxW(q_index));\n      }\n\n      for (auto &&weight : q_weights) {\n        *ptw = weight;\n        ++ptw;\n      }\n    }\n\n    return py::array(py::buffer_info(weights.data(), sizeof(double),\n                                     py::format_descriptor<double>::value, 1,\n                                     w_shape, w_strides));\n  }\n\n  py::array get_cell_measures() {\n    py::dtype dtype = py::dtype::of<double>();\n    std::array<size_t, 1> m_shape = {this->triangulation.n_active_cells()};\n    std::array<size_t, 1> m_strides = {sizeof(double)};\n    std::vector<double> measures(m_shape[0], 0);\n    auto ptm = measures.data();\n\n    auto cell = this->dof_handler.begin_active();\n    auto endc = this->dof_handler.end();\n    for (; cell != endc; ++cell) {\n      *ptm = cell->measure();\n      ++ptm;\n    }\n\n    return py::array(py::buffer_info(measures.data(), sizeof(double),\n                                     py::format_descriptor<double>::value, 1,\n                                     m_shape, m_strides));\n  }\n\n  py::array get_cell_extents() {\n    py::dtype dtype = py::dtype::of<double>();\n    std::array<size_t, 1> m_shape = {this->triangulation.n_active_cells()};\n    std::array<size_t, 1> m_strides = {sizeof(double)};\n    std::vector<double> extents(m_shape[0], 0);\n    auto ptm = extents.data();\n\n    auto cell = this->dof_handler.begin_active();\n    auto endc = this->dof_handler.end();\n    for (; cell != endc; ++cell) {\n      auto v0 = cell->vertex(0);\n      auto v1 = cell->vertex(1);\n      *ptm = l_infty_distance<dimension>(v0, v1);\n      ++ptm;\n    }\n\n    return py::array(py::buffer_info(extents.data(), sizeof(double),\n                                     py::format_descriptor<double>::value, 1,\n                                     m_shape, m_strides));\n  }\n\n  py::array get_cell_centers() {\n    py::dtype dtype = py::dtype::of<double>();\n    std::array<size_t, 2> c_shape = {this->triangulation.n_active_cells(),\n                                     dimension};\n    std::array<size_t, 2> c_strides = {dimension * sizeof(double),\n                                       sizeof(double)};\n    std::vector<double> centers(c_shape[0] * c_shape[1], 0);\n    auto ptc = centers.data();\n\n    auto cell = this->dof_handler.begin_active();\n    auto endc = this->dof_handler.end();\n    for (; cell != endc; ++cell) {\n      std::array<d::Point<dimension>,\n                 d::GeometryInfo<dimension>::vertices_per_cell>\n          vertices;\n      for (unsigned int v = 0;\n           v < d::GeometryInfo<dimension>::vertices_per_cell; ++v) {\n        vertices[v] = cell->vertex(v);\n      }\n      auto barycenter = compute_barycenter<\n          dimension, d::GeometryInfo<dimension>::vertices_per_cell>(vertices);\n      for (unsigned int d = 0; d < dimension; ++d) {\n        *ptc = barycenter[dimension - 1 - d];\n        ++ptc;\n      }\n    }\n\n    return py::array(py::buffer_info(centers.data(), sizeof(double),\n                                     py::format_descriptor<double>::value, 2,\n                                     c_shape, c_strides));\n  }\n\n  int n_active_cells() { return this->triangulation.n_active_cells(); }\n\n  // Do both preparation for refinement and coarsening as well as mesh\n  // smoothing. The function returns whether some cells' flagging has been\n  // changed in the process.\n  bool prepare_coarsening_and_refinement() {\n\n    bool flagging_changed = false;\n\n    if (this->triangulation.n_levels() > this->max_grid_level) {\n      flagging_changed = true;\n      for (const auto &cell :\n           this->triangulation.active_cell_iterators_on_level(max_grid_level))\n        cell->clear_refine_flag();\n    }\n\n    for (const auto &cell :\n         triangulation.active_cell_iterators_on_level(min_grid_level))\n      if (cell->coarsen_flag_set()) {\n        flagging_changed = true;\n        cell->clear_coarsen_flag();\n      }\n\n    return (flagging_changed &&\n            this->triangulation.prepare_coarsening_and_refinement());\n  }\n\n  void execute_coarsening_and_refinement() {\n    this->triangulation.execute_coarsening_and_refinement();\n    this->dof_handler.distribute_dofs(fe);\n  }\n\n  // {{{ adaptive mesh refinement\n\n  // (Legacy) driver function for mesh adaptivity\n  int update_mesh(py::array_t<double> &criteria,\n                  const double top_fraction_of_cells,\n                  const double bottom_fraction_of_cells) {\n\n    // calls refine_and_coarsen_fixed_number\n    int n_active_cells = this->refine_and_coarsen_fixed_number(\n        criteria, top_fraction_of_cells, bottom_fraction_of_cells);\n\n    return n_active_cells;\n  }\n\n  // Interface for dealii::GridRefinement::refine_and_coarsen_fixed_number\n  int refine_and_coarsen_fixed_number(py::array_t<double> &criteria,\n                                      const double top_fraction_of_cells,\n                                      const double bottom_fraction_of_cells) {\n\n    auto ctr = pyarr_to_dvec<double>(criteria);\n\n    d::GridRefinement::refine_and_coarsen_fixed_number(\n        this->triangulation, ctr, top_fraction_of_cells,\n        bottom_fraction_of_cells, this->max_n_cells);\n\n    this->prepare_coarsening_and_refinement();\n    this->execute_coarsening_and_refinement();\n\n    return this->n_active_cells();\n  }\n\n  // Interface for dealii::GridRefinement::refine_and_coarsen_fixed_fraction\n  int refine_and_coarsen_fixed_fraction(\n      py::array_t<double> &criteria, const double top_fraction_of_errors,\n      const double bottom_fraction_of_errors) {\n\n    auto ctr = pyarr_to_dvec<double>(criteria);\n\n    d::GridRefinement::refine_and_coarsen_fixed_fraction(\n        this->triangulation, ctr, top_fraction_of_errors,\n        bottom_fraction_of_errors, this->max_n_cells);\n\n    this->prepare_coarsening_and_refinement();\n    this->execute_coarsening_and_refinement();\n\n    return this->n_active_cells();\n  }\n\n  // Interface for dealii::GridRefinement::refine_and_coarsen_optimize\n  // NOTE: this function does not repsect max_n_cells!\n  int refine_and_coarsen_optimize(py::array_t<double> &criteria,\n                                  const unsigned int order) {\n\n    auto ctr = pyarr_to_dvec<double>(criteria);\n\n    d::GridRefinement::refine_and_coarsen_optimize(this->triangulation, ctr,\n                                                   order);\n\n    this->prepare_coarsening_and_refinement();\n    this->execute_coarsening_and_refinement();\n\n    if (this->n_active_cells() > this->max_n_cells) {\n      std::cout << \"Warning: max_n_cells has been exceeded!\" << std::endl;\n    }\n\n    return this->n_active_cells();\n  }\n\n  // Interface for dealii::GridRefinement::refine\n  // NOTE: this function does not repsect max_n_cells!\n  int refine(py::array_t<double> &criteria, const double threshold,\n             const unsigned int max_to_mark =\n                 std::numeric_limits<unsigned int>::max()) {\n\n    auto ctr = pyarr_to_dvec<double>(criteria);\n\n    d::GridRefinement::refine(this->triangulation, ctr, threshold, max_to_mark);\n\n    this->prepare_coarsening_and_refinement();\n    this->execute_coarsening_and_refinement();\n\n    if (this->n_active_cells() > this->max_n_cells) {\n      std::cout << \"Warning: max_n_cells has been exceeded!\" << std::endl;\n    }\n\n    return this->n_active_cells();\n  }\n\n  // Interface for dealii::GridRefinement::coarsen\n  int coarsen(py::array_t<double> &criteria, const double threshold) {\n\n    auto ctr = pyarr_to_dvec<double>(criteria);\n\n    d::GridRefinement::coarsen(this->triangulation, ctr, threshold);\n\n    this->prepare_coarsening_and_refinement();\n    this->execute_coarsening_and_refinement();\n\n    return this->n_active_cells();\n  }\n\n  // }}}\n\n  // Show some info about the mesh\n  void print_info() {\n\n    std::cout << \"Number of cells: \" << this->triangulation.n_cells()\n              << std::endl;\n\n    std::cout << \"Number of active cells: \"\n              << this->triangulation.n_active_cells() << std::endl;\n\n    d::FEValues<dimension> fe_values(fe, quadrature_formula,\n                                     d::update_quadrature_points);\n    const unsigned int n_q_points = quadrature_formula.size();\n    std::cout << \"Number of quad points per cell: \" << n_q_points << std::endl;\n  }\n};\ntypedef MeshGenerator<1> MeshGen1D;\ntypedef MeshGenerator<2> MeshGen2D;\ntypedef MeshGenerator<3> MeshGen3D;\n\n// }}}\n\n// {{{ (Legacy) make uniform mesh\n// A legacy one-stop mesh generation function, returns quad points, weights\n// and some spacing info within a tuple.\ntemplate <int dim> py::tuple make_uniform_cubic_grid_details(int q, int level) {\n  py::dtype dtype = py::dtype::of<double>();\n\n  d::Triangulation<dim> triangulation;\n  d::FE_Q<dim> fe(q);\n  d::DoFHandler<dim> dof_handler(triangulation);\n  d::QGauss<dim> quadrature_formula(q);\n\n  d::GridGenerator::hyper_cube(triangulation, a, b);\n  if (level > 1) {\n    triangulation.refine_global(level - 1);\n  }\n  dof_handler.distribute_dofs(fe);\n  // std::cout << \"Number of active cells: \" << triangulation.n_active_cells()\n  //<< std::endl;\n\n  d::FEValues<dim> fe_values(fe, quadrature_formula, update_flags);\n  const size_t n_q_points = quadrature_formula.size();\n  // std::cout << \"Number of quad points per cell: \" << n_q_points << std::endl;\n\n  const size_t total_n_q_points = triangulation.n_active_cells() * n_q_points;\n\n  std::array<size_t, 2> pt_shape = {total_n_q_points, dim};\n  std::array<size_t, 2> pt_strides = {dim * sizeof(double), sizeof(double)};\n  std::array<size_t, 1> w_shape = {total_n_q_points};\n  std::array<size_t, 1> w_strides = {sizeof(double)};\n\n  // Quad points\n  std::vector<double> points(pt_shape[0] * pt_shape[1], 0);\n  // Quad weights\n  std::vector<double> weights(w_shape[0], 0);\n  // Distance (l_infty) to the closest cell vertex\n  // (used for reconstructing the mesh in boxtree)\n  std::vector<double> radii(w_shape[0], 0);\n  auto ptp = points.data();\n  auto ptw = weights.data();\n  auto ptr = radii.data();\n\n  // For margins\n  std::array<double, dim * 2> margins;\n  std::array<double *, dim * 2> mpts;\n  margins.fill(std::numeric_limits<double>::max());\n\n  auto cell = dof_handler.begin_active();\n  auto endc = dof_handler.end();\n  for (; cell != endc; ++cell) {\n    fe_values.reinit(cell);\n    std::vector<d::Point<dim>> q_points = fe_values.get_quadrature_points();\n    std::vector<double> q_weights;\n    std::array<d::Point<dim>, d::GeometryInfo<dim>::vertices_per_cell> vertices;\n\n    for (unsigned int q_index = 0; q_index < n_q_points; ++q_index) {\n      q_weights.push_back(fe_values.JxW(q_index));\n    }\n\n    for (unsigned int v = 0; v < d::GeometryInfo<dim>::vertices_per_cell; ++v) {\n      vertices[v] = cell->vertex(v);\n    }\n\n    for (auto &&point : q_points) {\n      for (unsigned int d = 0; d < dim; ++d) {\n        // For a preferred ordering of quad points\n        // This does not change anything but the ordering due to the symmetry\n        // in each direction (as long as the subdivided boxes are cubes), not\n        // even weights are changed.\n        *ptp = point[dim - 1 - d];\n        ++ptp;\n      }\n\n      // gather some info about margins\n      for (unsigned int d = 0; d < dim; ++d) {\n        auto margin_a_id = d * 2;\n        auto margin_b_id = d * 2 + 1;\n        if (std::abs(point[d] - a) < margins[margin_a_id]) {\n          margins[margin_a_id] = std::abs(point[d] - a);\n          mpts[margin_a_id] = ptr;\n        }\n        if (std::abs(point[d] - b) < margins[margin_b_id]) {\n          margins[margin_b_id] = std::abs(point[d] - b);\n          mpts[margin_b_id] = ptr;\n        }\n      }\n\n      ++ptr;\n    }\n\n    for (auto &&weight : q_weights) {\n      *ptw = weight;\n      ++ptw;\n    }\n  }\n\n  for (unsigned int i = 0; i < dim * 2; ++i) {\n    *(mpts[i]) = margins[i];\n  }\n\n  py::tuple result = py::make_tuple(\n      py::array(py::buffer_info(points.data(), sizeof(double),\n                                py::format_descriptor<double>::value, 2,\n                                pt_shape, pt_strides)),\n      py::array(py::buffer_info(weights.data(), sizeof(double),\n                                py::format_descriptor<double>::value, 1,\n                                w_shape, w_strides)),\n      py::array(py::buffer_info(radii.data(), sizeof(double),\n                                py::format_descriptor<double>::value, 1,\n                                w_shape, w_strides)));\n\n  return result;\n}\n\npy::tuple make_uniform_cubic_grid(int q, int level, int dim,\n                                  py::args args, py::kwargs kwargs) {\n  if (dim == 1) {\n    return make_uniform_cubic_grid_details<1>(q, level);\n  } else if (dim == 2) {\n    return make_uniform_cubic_grid_details<2>(q, level);\n  } else if (dim == 3) {\n    return make_uniform_cubic_grid_details<3>(q, level);\n  } else {\n    std::cout << \"Dimension must be 1,2 or 3.\" << std::endl;\n  }\n}\n\n// }}}\n\nPYBIND11_MODULE(meshgen_dealii, m) {\n  m.doc() = \"A mesh generator for volumential.\";\n\n  m.def(\"greet\", &greet, \"Greetings! This is meshgen11.\");\n\n  m.def(\"make_uniform_cubic_grid\", &make_uniform_cubic_grid,\n        \"Make a simple grid\", py::arg(\"degree\"), py::arg(\"level\") = 1,\n        py::arg(\"dim\") = 2);\n\n  py::class_<MeshGen1D>(m, \"MeshGen1D\")\n      .def(py::init<int, int, double, double, py::args, py::kwargs>(), py::arg(\"degree\"),\n           py::arg(\"level\"), py::arg(\"a\"), py::arg(\"b\"))\n      .def(\"greet\", &MeshGen1D::greet)\n      .def(\"get_q_points\", &MeshGen1D::get_q_points)\n      .def(\"get_q_weights\", &MeshGen1D::get_q_weights)\n      .def(\"get_cell_centers\", &MeshGen1D::get_cell_centers)\n      .def(\"get_cell_extents\", &MeshGen1D::get_cell_extents)\n      .def(\"get_cell_measures\", &MeshGen1D::get_cell_measures)\n      .def(\"n_active_cells\", &MeshGen1D::n_active_cells)\n      .def(\"prepare_coarsening_and_refinement\",\n           &MeshGen1D::prepare_coarsening_and_refinement)\n      .def(\"execute_coarsening_and_refinement\",\n           &MeshGen1D::execute_coarsening_and_refinement)\n      .def(\"update_mesh\", &MeshGen1D::update_mesh)\n      .def(\"refine_and_coarsen_fixed_number\",\n           &MeshGen1D::refine_and_coarsen_fixed_number)\n      .def(\"refine_and_coarsen_fixed_fraction\",\n           &MeshGen1D::refine_and_coarsen_fixed_fraction)\n      .def(\"refine_and_coarsen_optimize\",\n           &MeshGen1D::refine_and_coarsen_optimize)\n      .def(\"refine\", &MeshGen1D::refine)\n      .def(\"coarsen\", &MeshGen1D::coarsen)\n      .def(\"print_info\", &MeshGen1D::print_info)\n      .def(\"generate_gmsh\", &MeshGen1D::generate_gmsh)\n      .def(\"write_vtu\", &MeshGen1D::write_vtu);\n\n  py::class_<MeshGen2D>(m, \"MeshGen2D\")\n      .def(py::init<int, int, double, double, py::args, py::kwargs>(), py::arg(\"degree\"),\n           py::arg(\"level\"), py::arg(\"a\"), py::arg(\"b\"))\n      .def(\"greet\", &MeshGen2D::greet)\n      .def(\"get_q_points\", &MeshGen2D::get_q_points)\n      .def(\"get_q_weights\", &MeshGen2D::get_q_weights)\n      .def(\"get_cell_centers\", &MeshGen2D::get_cell_centers)\n      .def(\"get_cell_extents\", &MeshGen2D::get_cell_extents)\n      .def(\"get_cell_measures\", &MeshGen2D::get_cell_measures)\n      .def(\"n_active_cells\", &MeshGen2D::n_active_cells)\n      .def(\"prepare_coarsening_and_refinement\",\n           &MeshGen2D::prepare_coarsening_and_refinement)\n      .def(\"execute_coarsening_and_refinement\",\n           &MeshGen2D::execute_coarsening_and_refinement)\n      .def(\"update_mesh\", &MeshGen2D::update_mesh)\n      .def(\"refine_and_coarsen_fixed_number\",\n           &MeshGen2D::refine_and_coarsen_fixed_number)\n      .def(\"refine_and_coarsen_fixed_fraction\",\n           &MeshGen2D::refine_and_coarsen_fixed_fraction)\n      .def(\"refine_and_coarsen_optimize\",\n           &MeshGen2D::refine_and_coarsen_optimize)\n      .def(\"refine\", &MeshGen2D::refine)\n      .def(\"coarsen\", &MeshGen2D::coarsen)\n      .def(\"print_info\", &MeshGen2D::print_info)\n      .def(\"generate_gmsh\", &MeshGen2D::generate_gmsh)\n      .def(\"write_vtu\", &MeshGen2D::write_vtu);\n\n  py::class_<MeshGen3D>(m, \"MeshGen3D\")\n      .def(py::init<int, int, double, double, py::args, py::kwargs>(), py::arg(\"degree\"),\n           py::arg(\"level\"), py::arg(\"a\"), py::arg(\"b\"))\n      .def(\"greet\", &MeshGen3D::greet)\n      .def(\"get_q_points\", &MeshGen3D::get_q_points)\n      .def(\"get_q_weights\", &MeshGen3D::get_q_weights)\n      .def(\"get_cell_centers\", &MeshGen3D::get_cell_centers)\n      .def(\"get_cell_extents\", &MeshGen3D::get_cell_extents)\n      .def(\"get_cell_measures\", &MeshGen3D::get_cell_measures)\n      .def(\"n_active_cells\", &MeshGen3D::n_active_cells)\n      .def(\"prepare_coarsening_and_refinement\",\n           &MeshGen3D::prepare_coarsening_and_refinement)\n      .def(\"execute_coarsening_and_refinement\",\n           &MeshGen3D::execute_coarsening_and_refinement)\n      .def(\"update_mesh\", &MeshGen3D::update_mesh)\n      .def(\"refine_and_coarsen_fixed_number\",\n           &MeshGen3D::refine_and_coarsen_fixed_number)\n      .def(\"refine_and_coarsen_fixed_fraction\",\n           &MeshGen3D::refine_and_coarsen_fixed_fraction)\n      .def(\"refine_and_coarsen_optimize\",\n           &MeshGen3D::refine_and_coarsen_optimize)\n      .def(\"refine\", &MeshGen3D::refine)\n      .def(\"coarsen\", &MeshGen3D::coarsen)\n      .def(\"print_info\", &MeshGen3D::print_info)\n      .def(\"generate_gmsh\", &MeshGen3D::generate_gmsh)\n      .def(\"write_vtu\", &MeshGen3D::write_vtu);\n}\n", "meta": {"hexsha": "6f3d15dfef97778bc1f9327e5b09603697887aff", "size": 25268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contrib/meshgen11_dealii/meshgen.cpp", "max_stars_repo_name": "xywei/volumential", "max_stars_repo_head_hexsha": "07c6ca8c623acf24fb8deddf93baa1035234db58", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-21T23:57:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T22:02:50.000Z", "max_issues_repo_path": "contrib/meshgen11_dealii/meshgen.cpp", "max_issues_repo_name": "inducer/volumential", "max_issues_repo_head_hexsha": "290a5943d3f47958dcab6736bc2b758525471570", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:41:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-26T15:42:21.000Z", "max_forks_repo_path": "contrib/meshgen11_dealii/meshgen.cpp", "max_forks_repo_name": "inducer/volumential", "max_forks_repo_head_hexsha": "290a5943d3f47958dcab6736bc2b758525471570", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-21T21:23:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-21T21:23:39.000Z", "avg_line_length": 35.9431009957, "max_line_length": 94, "alphanum_fraction": 0.6383568149, "num_tokens": 6750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4221162342510207}}
{"text": "#include \"math.hpp\"\n\n#include <boost/integer.hpp>\n\n#include <cstring>\n#include <limits>\n\nnamespace base\n{\n\ntemplate <typename Float>\nbool AlmostEqualULPs(Float x, Float y, uint32_t maxULPs)\n{\n  static_assert(std::is_floating_point<Float>::value, \"\");\n  static_assert(std::numeric_limits<Float>::is_iec559, \"\");\n\n  // Make sure maxUlps is non-negative and small enough that the\n  // default NaN won't compare as equal to anything.\n  ASSERT_LESS(maxULPs, 4 * 1024 * 1024, ());\n\n  int constexpr bits = CHAR_BIT * sizeof(Float);\n  typedef typename boost::int_t<bits>::exact IntType;\n  typedef typename boost::uint_t<bits>::exact UIntType;\n\n  // Same as *reinterpret_cast<IntType const *>(&x), but without warnings.\n  IntType xInt, yInt;\n  static_assert(sizeof(xInt) == sizeof(x), \"bit_cast impossible\");\n  std::memcpy(&xInt, &x, sizeof(x));\n  std::memcpy(&yInt, &y, sizeof(y));\n\n  // Make xInt and yInt lexicographically ordered as a twos-complement int.\n  IntType const highestBit = IntType(1) << (bits - 1);\n  if (xInt < 0)\n    xInt = highestBit - xInt;\n  if (yInt < 0)\n    yInt = highestBit - yInt;\n\n  // Calculate diff with special case to avoid IntType overflow.\n  UIntType diff;\n  if ((xInt >= 0) == (yInt >= 0))\n    diff = Abs(xInt - yInt);\n  else\n    diff = UIntType(Abs(xInt)) + UIntType(Abs(yInt));\n\n  return diff <= maxULPs;\n}\n\ntemplate bool AlmostEqualULPs<float>(float x, float y, uint32_t maxULPs);\ntemplate bool AlmostEqualULPs<double>(double x, double y, uint32_t maxULPs);\n\n} // namespace base\n", "meta": {"hexsha": "c3f875d35ca5a5220a50cc1b8f990988c4a37931", "size": 1507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "base/math.cpp", "max_stars_repo_name": "sthirvela/organicmaps", "max_stars_repo_head_hexsha": "14885ba070ac9d1b7241ebb89eeefa46c9fdc1e4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3062.0, "max_stars_repo_stars_event_min_datetime": "2021-04-09T16:51:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:02:51.000Z", "max_issues_repo_path": "base/math.cpp", "max_issues_repo_name": "MAPSWorks/organicmaps", "max_issues_repo_head_hexsha": "b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1396.0, "max_issues_repo_issues_event_min_datetime": "2021-04-08T07:26:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:27:46.000Z", "max_forks_repo_path": "base/math.cpp", "max_forks_repo_name": "MAPSWorks/organicmaps", "max_forks_repo_head_hexsha": "b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 242.0, "max_forks_repo_forks_event_min_datetime": "2021-04-10T17:10:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T13:41:07.000Z", "avg_line_length": 28.9807692308, "max_line_length": 76, "alphanum_fraction": 0.6921035169, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4221162197704937}}
{"text": "// Copyright 2004 The Trustees of Indiana University.\n\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Jeremiah Willcock\n//           Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_GURSOY_ATUN_LAYOUT_HPP\n#define BOOST_GRAPH_GURSOY_ATUN_LAYOUT_HPP\n\n// Gursoy-Atun graph layout, based on:\n// \"Neighbourhood Preserving Load Balancing: A Self-Organizing Approach\"\n// in EuroPar 2000, p. 234 of LNCS 1900\n// http://springerlink.metapress.com/link.asp?id=pcu07ew5rhexp9yt\n\n#include <cmath>\n#include <vector>\n#include <exception>\n#include <algorithm>\n\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/named_function_params.hpp>\n\nnamespace boost { \n\nnamespace detail {\n\nstruct over_distance_limit : public std::exception {};\n\ntemplate <typename PositionMap, typename NodeDistanceMap,  typename Topology,\n          typename Graph>\nstruct update_position_visitor {\n  typedef typename Topology::point_type Point;\n  PositionMap position_map;\n  NodeDistanceMap node_distance;\n  const Topology& space;\n  Point input_vector;\n  double distance_limit;\n  double learning_constant;\n  double falloff_ratio;\n\n  typedef boost::on_examine_vertex event_filter;\n\n  typedef typename graph_traits<Graph>::vertex_descriptor\n    vertex_descriptor;\n\n  update_position_visitor(PositionMap position_map,\n                          NodeDistanceMap node_distance,\n                          const Topology& space,\n                          const Point& input_vector,\n                          double distance_limit,\n                          double learning_constant,\n                          double falloff_ratio):\n    position_map(position_map), node_distance(node_distance), \n    space(space),\n    input_vector(input_vector), distance_limit(distance_limit),\n    learning_constant(learning_constant), falloff_ratio(falloff_ratio) {}\n\n  void operator()(vertex_descriptor v, const Graph&) const \n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::pow;\n#endif\n\n    if (get(node_distance, v) > distance_limit)\n      throw over_distance_limit();\n    Point old_position = get(position_map, v);\n    double distance = get(node_distance, v);\n    double fraction = \n      learning_constant * pow(falloff_ratio, distance * distance);\n    put(position_map, v,\n        space.move_position_toward(old_position, fraction, input_vector));\n  }\n};\n\ntemplate<typename EdgeWeightMap>\nstruct gursoy_shortest\n{\n  template<typename Graph, typename NodeDistanceMap, typename UpdatePosition>\n  static inline void \n  run(const Graph& g, typename graph_traits<Graph>::vertex_descriptor s,\n      NodeDistanceMap node_distance,  UpdatePosition& update_position,\n      EdgeWeightMap weight)\n  {\n    boost::dijkstra_shortest_paths(g, s, weight_map(weight).\n      visitor(boost::make_dijkstra_visitor(std::make_pair(\n       boost::record_distances(node_distance, boost::on_edge_relaxed()),\n        update_position))));\n  }\n};\n\ntemplate<>\nstruct gursoy_shortest<dummy_property_map>\n{\n  template<typename Graph, typename NodeDistanceMap, typename UpdatePosition>\n  static inline void \n  run(const Graph& g, typename graph_traits<Graph>::vertex_descriptor s,\n      NodeDistanceMap node_distance,  UpdatePosition& update_position,\n      dummy_property_map)\n  {\n    boost::breadth_first_search(g, s,\n      visitor(boost::make_bfs_visitor(std::make_pair(\n        boost::record_distances(node_distance, boost::on_tree_edge()),\n        update_position))));\n  }\n};\n\n} // namespace detail\n\ntemplate <typename VertexListAndIncidenceGraph,  typename Topology,\n          typename PositionMap, typename Diameter, typename VertexIndexMap, \n          typename EdgeWeightMap>\nvoid \ngursoy_atun_step\n  (const VertexListAndIncidenceGraph& graph,  \n   const Topology& space,\n   PositionMap position,\n   Diameter diameter,\n   double learning_constant,\n   VertexIndexMap vertex_index_map,\n   EdgeWeightMap weight)\n{\n#ifndef BOOST_NO_STDC_NAMESPACE\n  using std::pow;\n  using std::exp;\n#endif\n\n  typedef typename graph_traits<VertexListAndIncidenceGraph>::vertex_iterator\n    vertex_iterator;\n  typedef typename graph_traits<VertexListAndIncidenceGraph>::vertex_descriptor\n    vertex_descriptor;\n  typedef typename Topology::point_type point_type;\n  vertex_iterator i, iend;\n  std::vector<double> distance_from_input_vector(num_vertices(graph));\n  typedef boost::iterator_property_map<std::vector<double>::iterator, \n                                       VertexIndexMap,\n                                       double, double&>\n    DistanceFromInputMap;\n  DistanceFromInputMap distance_from_input(distance_from_input_vector.begin(),\n                                           vertex_index_map);\n  std::vector<double> node_distance_map_vector(num_vertices(graph));\n  typedef boost::iterator_property_map<std::vector<double>::iterator, \n                                       VertexIndexMap,\n                                       double, double&>\n    NodeDistanceMap;\n  NodeDistanceMap node_distance(node_distance_map_vector.begin(),\n                                vertex_index_map);\n  point_type input_vector = space.random_point();\n  vertex_descriptor min_distance_loc \n    = graph_traits<VertexListAndIncidenceGraph>::null_vertex();\n  double min_distance = 0.0;\n  bool min_distance_unset = true;\n  for (boost::tie(i, iend) = vertices(graph); i != iend; ++i) {\n    double this_distance = space.distance(get(position, *i), input_vector);\n    put(distance_from_input, *i, this_distance);\n    if (min_distance_unset || this_distance < min_distance) {\n      min_distance = this_distance;\n      min_distance_loc = *i;\n    }\n    min_distance_unset = false;\n  }\n  assert (!min_distance_unset); // Graph must have at least one vertex\n  boost::detail::update_position_visitor<\n      PositionMap, NodeDistanceMap, Topology,\n      VertexListAndIncidenceGraph> \n    update_position(position, node_distance, space,\n                    input_vector, diameter, learning_constant, \n                    exp(-1. / (2 * diameter * diameter)));\n  std::fill(node_distance_map_vector.begin(), node_distance_map_vector.end(), 0);\n  try {\n    typedef detail::gursoy_shortest<EdgeWeightMap> shortest;\n    shortest::run(graph, min_distance_loc, node_distance, update_position,\n                  weight);    \n  } catch (detail::over_distance_limit) { \n    /* Thrown to break out of BFS or Dijkstra early */ \n  }\n}\n\ntemplate <typename VertexListAndIncidenceGraph,  typename Topology,\n          typename PositionMap, typename VertexIndexMap, \n          typename EdgeWeightMap>\nvoid gursoy_atun_refine(const VertexListAndIncidenceGraph& graph,  \n                        const Topology& space,\n                        PositionMap position,\n                        int nsteps,\n                        double diameter_initial,\n                        double diameter_final,\n                        double learning_constant_initial,\n                        double learning_constant_final,\n                        VertexIndexMap vertex_index_map,\n                        EdgeWeightMap weight) \n{\n#ifndef BOOST_NO_STDC_NAMESPACE\n  using std::pow;\n  using std::exp;\n#endif\n\n  typedef typename graph_traits<VertexListAndIncidenceGraph>::vertex_iterator\n    vertex_iterator;\n  typedef typename graph_traits<VertexListAndIncidenceGraph>::vertex_descriptor\n    vertex_descriptor;\n  typedef typename Topology::point_type point_type;\n  vertex_iterator i, iend;\n  double diameter_ratio = (double)diameter_final / diameter_initial;\n  double learning_constant_ratio = \n    learning_constant_final / learning_constant_initial;\n  std::vector<double> distance_from_input_vector(num_vertices(graph));\n  typedef boost::iterator_property_map<std::vector<double>::iterator, \n                                       VertexIndexMap,\n                                       double, double&>\n    DistanceFromInputMap;\n  DistanceFromInputMap distance_from_input(distance_from_input_vector.begin(),\n                                           vertex_index_map);\n  std::vector<int> node_distance_map_vector(num_vertices(graph));\n  typedef boost::iterator_property_map<std::vector<int>::iterator, \n                                       VertexIndexMap, double, double&>\n    NodeDistanceMap;\n  NodeDistanceMap node_distance(node_distance_map_vector.begin(),\n                                vertex_index_map);\n  for (int round = 0; round < nsteps; ++round) {\n    double part_done = (double)round / (nsteps - 1);\n    int diameter = (int)(diameter_initial * pow(diameter_ratio, part_done));\n    double learning_constant = \n      learning_constant_initial * pow(learning_constant_ratio, part_done);\n    gursoy_atun_step(graph, space, position, diameter, learning_constant, \n                     vertex_index_map, weight);\n  }\n}\n\ntemplate <typename VertexListAndIncidenceGraph,  typename Topology,\n          typename PositionMap, typename VertexIndexMap, \n          typename EdgeWeightMap>\nvoid gursoy_atun_layout(const VertexListAndIncidenceGraph& graph,  \n                        const Topology& space,\n                        PositionMap position,\n                        int nsteps,\n                        double diameter_initial,\n                        double diameter_final,\n                        double learning_constant_initial,\n                        double learning_constant_final,\n                        VertexIndexMap vertex_index_map,\n                        EdgeWeightMap weight)\n{\n  typedef typename graph_traits<VertexListAndIncidenceGraph>::vertex_iterator\n    vertex_iterator;\n  vertex_iterator i, iend;\n  for (boost::tie(i, iend) = vertices(graph); i != iend; ++i) {\n    put(position, *i, space.random_point());\n  }\n  gursoy_atun_refine(graph, space,\n                     position, nsteps,\n                     diameter_initial, diameter_final, \n                     learning_constant_initial, learning_constant_final,\n                     vertex_index_map, weight);\n}\n\ntemplate <typename VertexListAndIncidenceGraph,  typename Topology,\n          typename PositionMap, typename VertexIndexMap>\nvoid gursoy_atun_layout(const VertexListAndIncidenceGraph& graph,  \n                        const Topology& space,\n                        PositionMap position,\n                        int nsteps,\n                        double diameter_initial,\n                        double diameter_final,\n                        double learning_constant_initial,\n                        double learning_constant_final,\n                        VertexIndexMap vertex_index_map)\n{\n  gursoy_atun_layout(graph, space, position, nsteps, \n                     diameter_initial, diameter_final, \n                     learning_constant_initial, learning_constant_final, \n                     vertex_index_map, dummy_property_map());\n}\n\ntemplate <typename VertexListAndIncidenceGraph, typename Topology,\n          typename PositionMap>\nvoid gursoy_atun_layout(const VertexListAndIncidenceGraph& graph,  \n                        const Topology& space,\n                        PositionMap position,\n                        int nsteps,\n                        double diameter_initial,\n                        double diameter_final = 1.0,\n                        double learning_constant_initial = 0.8,\n                        double learning_constant_final = 0.2)\n{ \n  gursoy_atun_layout(graph, space, position, nsteps, diameter_initial,\n                     diameter_final, learning_constant_initial,\n                     learning_constant_final, get(vertex_index, graph)); \n}\n\ntemplate <typename VertexListAndIncidenceGraph, typename Topology,\n          typename PositionMap>\nvoid gursoy_atun_layout(const VertexListAndIncidenceGraph& graph,  \n                        const Topology& space,\n                        PositionMap position,\n                        int nsteps)\n{\n#ifndef BOOST_NO_STDC_NAMESPACE\n  using std::sqrt;\n#endif\n\n  gursoy_atun_layout(graph, space, position, nsteps, \n                     sqrt((double)num_vertices(graph)));\n}\n\ntemplate <typename VertexListAndIncidenceGraph, typename Topology,\n          typename PositionMap>\nvoid gursoy_atun_layout(const VertexListAndIncidenceGraph& graph,  \n                        const Topology& space,\n                        PositionMap position)\n{\n  gursoy_atun_layout(graph, space, position, num_vertices(graph));\n}\n\ntemplate<typename VertexListAndIncidenceGraph, typename Topology,\n         typename PositionMap, typename P, typename T, typename R>\nvoid \ngursoy_atun_layout(const VertexListAndIncidenceGraph& graph,  \n                   const Topology& space,\n                   PositionMap position,\n                   const bgl_named_params<P,T,R>& params)\n{\n#ifndef BOOST_NO_STDC_NAMESPACE\n  using std::sqrt;\n#endif\n\n  std::pair<double, double> diam(sqrt(double(num_vertices(graph))), 1.0);\n  std::pair<double, double> learn(0.8, 0.2);\n  gursoy_atun_layout(graph, space, position,\n                     choose_param(get_param(params, iterations_t()),\n                                  num_vertices(graph)),\n                     choose_param(get_param(params, diameter_range_t()), \n                                  diam).first,\n                     choose_param(get_param(params, diameter_range_t()), \n                                  diam).second,\n                     choose_param(get_param(params, learning_constant_range_t()), \n                                  learn).first,\n                     choose_param(get_param(params, learning_constant_range_t()), \n                                  learn).second,\n                     choose_const_pmap(get_param(params, vertex_index), graph,\n                                       vertex_index),\n                     choose_param(get_param(params, edge_weight), \n                                  dummy_property_map()));\n}\n\n/***********************************************************\n * Topologies                                              *\n ***********************************************************/\ntemplate<std::size_t Dims>\nclass convex_topology \n{\n  struct point \n  {\n    point() { }\n    double& operator[](std::size_t i) {return values[i];}\n    const double& operator[](std::size_t i) const {return values[i];}\n\n  private:\n    double values[Dims];\n  };\n\n public:\n  typedef point point_type;\n\n  double distance(point a, point b) const \n  {\n    double dist = 0;\n    for (std::size_t i = 0; i < Dims; ++i) {\n      double diff = b[i] - a[i];\n      dist += diff * diff;\n    }\n    // Exact properties of the distance are not important, as long as\n    // < on what this returns matches real distances\n    return dist;\n  }\n\n  point move_position_toward(point a, double fraction, point b) const \n  {\n    point result;\n    for (std::size_t i = 0; i < Dims; ++i)\n      result[i] = a[i] + (b[i] - a[i]) * fraction;\n    return result;\n  }\n};\n\ntemplate<std::size_t Dims,\n         typename RandomNumberGenerator = minstd_rand>\nclass hypercube_topology : public convex_topology<Dims>\n{\n  typedef uniform_01<RandomNumberGenerator, double> rand_t;\n\n public:\n  typedef typename convex_topology<Dims>::point_type point_type;\n\n  explicit hypercube_topology(double scaling = 1.0) \n    : gen_ptr(new RandomNumberGenerator), rand(new rand_t(*gen_ptr)), \n      scaling(scaling) \n  { }\n\n  hypercube_topology(RandomNumberGenerator& gen, double scaling = 1.0) \n    : gen_ptr(), rand(new rand_t(gen)), scaling(scaling) { }\n                     \n  point_type random_point() const \n  {\n    point_type p;\n    for (std::size_t i = 0; i < Dims; ++i)\n      p[i] = (*rand)() * scaling;\n    return p;\n  }\n\n private:\n  shared_ptr<RandomNumberGenerator> gen_ptr;\n  shared_ptr<rand_t> rand;\n  double scaling;\n};\n\ntemplate<typename RandomNumberGenerator = minstd_rand>\nclass square_topology : public hypercube_topology<2, RandomNumberGenerator>\n{\n  typedef hypercube_topology<2, RandomNumberGenerator> inherited;\n\n public:\n  explicit square_topology(double scaling = 1.0) : inherited(scaling) { }\n  \n  square_topology(RandomNumberGenerator& gen, double scaling = 1.0) \n    : inherited(gen, scaling) { }\n};\n\ntemplate<typename RandomNumberGenerator = minstd_rand>\nclass cube_topology : public hypercube_topology<3, RandomNumberGenerator>\n{\n  typedef hypercube_topology<3, RandomNumberGenerator> inherited;\n\n public:\n  explicit cube_topology(double scaling = 1.0) : inherited(scaling) { }\n  \n  cube_topology(RandomNumberGenerator& gen, double scaling = 1.0) \n    : inherited(gen, scaling) { }\n};\n\ntemplate<std::size_t Dims,\n         typename RandomNumberGenerator = minstd_rand>\nclass ball_topology : public convex_topology<Dims>\n{\n  typedef uniform_01<RandomNumberGenerator, double> rand_t;\n\n public:\n  typedef typename convex_topology<Dims>::point_type point_type;\n\n  explicit ball_topology(double radius = 1.0) \n    : gen_ptr(new RandomNumberGenerator), rand(new rand_t(*gen_ptr)), \n      radius(radius) \n  { }\n\n  ball_topology(RandomNumberGenerator& gen, double radius = 1.0) \n    : gen_ptr(), rand(new rand_t(gen)), radius(radius) { }\n                     \n  point_type random_point() const \n  {\n    point_type p;\n    double dist_sum;\n    do {\n      dist_sum = 0.0;\n      for (std::size_t i = 0; i < Dims; ++i) {\n        double x = (*rand)() * 2*radius - radius;\n        p[i] = x;\n        dist_sum += x * x;\n      }\n    } while (dist_sum > radius*radius);\n    return p;\n  }\n\n private:\n  shared_ptr<RandomNumberGenerator> gen_ptr;\n  shared_ptr<rand_t> rand;\n  double radius;\n};\n\ntemplate<typename RandomNumberGenerator = minstd_rand>\nclass circle_topology : public ball_topology<2, RandomNumberGenerator>\n{\n  typedef ball_topology<2, RandomNumberGenerator> inherited;\n\n public:\n  explicit circle_topology(double radius = 1.0) : inherited(radius) { }\n  \n  circle_topology(RandomNumberGenerator& gen, double radius = 1.0) \n    : inherited(gen, radius) { }\n};\n\ntemplate<typename RandomNumberGenerator = minstd_rand>\nclass sphere_topology : public ball_topology<3, RandomNumberGenerator>\n{\n  typedef ball_topology<3, RandomNumberGenerator> inherited;\n\n public:\n  explicit sphere_topology(double radius = 1.0) : inherited(radius) { }\n  \n  sphere_topology(RandomNumberGenerator& gen, double radius = 1.0) \n    : inherited(gen, radius) { }\n};\n\ntemplate<typename RandomNumberGenerator = minstd_rand>\nclass heart_topology \n{\n  // Heart is defined as the union of three shapes:\n  // Square w/ corners (+-1000, -1000), (0, 0), (0, -2000)\n  // Circle centered at (-500, -500) radius 500*sqrt(2)\n  // Circle centered at (500, -500) radius 500*sqrt(2)\n  // Bounding box (-1000, -2000) - (1000, 500*(sqrt(2) - 1))\n\n  struct point \n  {\n    point() { values[0] = 0.0; values[1] = 0.0; }\n    point(double x, double y) { values[0] = x; values[1] = y; }\n\n    double& operator[](std::size_t i)       { return values[i]; }\n    double  operator[](std::size_t i) const { return values[i]; }\n\n  private:\n    double values[2];\n  };\n\n  bool in_heart(point p) const \n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::abs;\n    using std::pow;\n#endif\n\n    if (p[1] < abs(p[0]) - 2000) return false; // Bottom\n    if (p[1] <= -1000) return true; // Diagonal of square\n    if (pow(p[0] - -500, 2) + pow(p[1] - -500, 2) <= 500000)\n      return true; // Left circle\n    if (pow(p[0] - 500, 2) + pow(p[1] - -500, 2) <= 500000)\n      return true; // Right circle\n    return false;\n  }\n\n  bool segment_within_heart(point p1, point p2) const \n  {\n    // Assumes that p1 and p2 are within the heart\n    if ((p1[0] < 0) == (p2[0] < 0)) return true; // Same side of symmetry line\n    if (p1[0] == p2[0]) return true; // Vertical\n    double slope = (p2[1] - p1[1]) / (p2[0] - p1[0]);\n    double intercept = p1[1] - p1[0] * slope;\n    if (intercept > 0) return false; // Crosses between circles\n    return true;\n  }\n\n  typedef uniform_01<RandomNumberGenerator, double> rand_t;\n\n public:\n  typedef point point_type;\n\n  heart_topology() \n    : gen_ptr(new RandomNumberGenerator), rand(new rand_t(*gen_ptr)) { }\n\n  heart_topology(RandomNumberGenerator& gen) \n    : gen_ptr(), rand(new rand_t(gen)) { }\n\n  point random_point() const \n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif\n\n    point result;\n    double sqrt2 = sqrt(2.);\n    do {\n      result[0] = (*rand)() * (1000 + 1000 * sqrt2) - (500 + 500 * sqrt2);\n      result[1] = (*rand)() * (2000 + 500 * (sqrt2 - 1)) - 2000;\n    } while (!in_heart(result));\n    return result;\n  }\n\n  double distance(point a, point b) const \n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif\n    if (segment_within_heart(a, b)) {\n      // Straight line\n      return sqrt((b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]));\n    } else {\n      // Straight line bending around (0, 0)\n      return sqrt(a[0] * a[0] + a[1] * a[1]) + sqrt(b[0] * b[0] + b[1] * b[1]);\n    }\n  }\n\n  point move_position_toward(point a, double fraction, point b) const \n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif\n\n    if (segment_within_heart(a, b)) {\n      // Straight line\n      return point(a[0] + (b[0] - a[0]) * fraction,\n                   a[1] + (b[1] - a[1]) * fraction);\n    } else {\n      double distance_to_point_a = sqrt(a[0] * a[0] + a[1] * a[1]);\n      double distance_to_point_b = sqrt(b[0] * b[0] + b[1] * b[1]);\n      double location_of_point = distance_to_point_a / \n                                   (distance_to_point_a + distance_to_point_b);\n      if (fraction < location_of_point)\n        return point(a[0] * (1 - fraction / location_of_point), \n                     a[1] * (1 - fraction / location_of_point));\n      else\n        return point(\n          b[0] * ((fraction - location_of_point) / (1 - location_of_point)),\n          b[1] * ((fraction - location_of_point) / (1 - location_of_point)));\n    }\n  }\n\n private:\n  shared_ptr<RandomNumberGenerator> gen_ptr;\n  shared_ptr<rand_t> rand;\n};\n\n} // namespace boost\n\n#endif // BOOST_GRAPH_GURSOY_ATUN_LAYOUT_HPP\n", "meta": {"hexsha": "3b6ccc5ed9acf280fd70dbc37ed194fe07158bc8", "size": 22148, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost-1_34_1/boost/graph/gursoy_atun_layout.hpp", "max_stars_repo_name": "memoryboxes/bitcoin_satoshi", "max_stars_repo_head_hexsha": "efbe7e393c1ae3ee9f26a3040c423f176b1e48cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-04-23T04:55:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T10:26:27.000Z", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/miniBoost/boost/graph/gursoy_atun_layout.hpp", "max_issues_repo_name": "skair39/structured", "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-26T21:49:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-11T04:03:44.000Z", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/miniBoost/boost/graph/gursoy_atun_layout.hpp", "max_forks_repo_name": "skair39/structured", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T13:16:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:13:14.000Z", "avg_line_length": 35.0443037975, "max_line_length": 82, "alphanum_fraction": 0.6453404371, "num_tokens": 5082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4219962933686824}}
{"text": "// Copyright 2019, Collabora, Ltd.\n// SPDX-License-Identifier: BSL-1.0\n/*!\n * @file\n * @brief  Base implementations for math library.\n * @author Jakob Bornecrantz <jakob@collabora.com>\n * @author Ryan Pavlik <ryan.pavlik@collabora.com>\n * @author Moses Turner <mosesturner@protonmail.com>\n * @ingroup aux_math\n */\n\n#include \"math/m_api.h\"\n#include \"math/m_eigen_interop.hpp\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <assert.h>\n\nusing namespace xrt::auxiliary::math;\n\n/*\n *\n * Copy helpers.\n *\n */\n\nstatic inline Eigen::Quaternionf\ncopy(const struct xrt_quat &q)\n{\n\t// Eigen constructor order is different from XRT, OpenHMD and OpenXR!\n\t//  Eigen: `float w, x, y, z`.\n\t// OpenXR: `float x, y, z, w`.\n\treturn Eigen::Quaternionf(q.w, q.x, q.y, q.z);\n}\n\nstatic inline Eigen::Quaternionf\ncopy(const struct xrt_quat *q)\n{\n\treturn copy(*q);\n}\n\nXRT_MAYBE_UNUSED static inline Eigen::Quaterniond\ncopyd(const struct xrt_quat &q)\n{\n\t// Eigen constructor order is different from XRT, OpenHMD and OpenXR!\n\t//  Eigen: `float w, x, y, z`.\n\t// OpenXR: `float x, y, z, w`.\n\treturn Eigen::Quaterniond(q.w, q.x, q.y, q.z);\n}\n\nXRT_MAYBE_UNUSED static inline Eigen::Quaterniond\ncopyd(const struct xrt_quat *q)\n{\n\treturn copyd(*q);\n}\n\nstatic inline Eigen::Vector3f\ncopy(const struct xrt_vec3 &v)\n{\n\treturn Eigen::Vector3f(v.x, v.y, v.z);\n}\n\nstatic inline Eigen::Vector3f\ncopy(const struct xrt_vec3 *v)\n{\n\treturn copy(*v);\n}\n\nXRT_MAYBE_UNUSED static inline Eigen::Vector3d\ncopyd(const struct xrt_vec3 &v)\n{\n\treturn Eigen::Vector3d(v.x, v.y, v.z);\n}\n\nXRT_MAYBE_UNUSED static inline Eigen::Vector3d\ncopyd(const struct xrt_vec3 *v)\n{\n\treturn copyd(*v);\n}\n\nstatic inline Eigen::Matrix3f\ncopy(const struct xrt_matrix_3x3 *m)\n{\n\tEigen::Matrix3f res;\n\t// clang-format off\n\tres << m->v[0], m->v[3], m->v[6],\n\t       m->v[1], m->v[4], m->v[7],\n\t       m->v[2], m->v[5], m->v[8];\n\t// clang-format on\n\treturn res;\n}\n\nstatic inline Eigen::Matrix4f\ncopy(const struct xrt_matrix_4x4 *m)\n{\n\tEigen::Matrix4f res;\n\t// clang-format off\n\tres << m->v[0], m->v[4], m->v[8],  m->v[12],\n\t       m->v[1], m->v[5], m->v[9],  m->v[13],\n\t       m->v[2], m->v[6], m->v[10], m->v[14],\n\t       m->v[3], m->v[7], m->v[11], m->v[15];\n\t// clang-format on\n\treturn res;\n}\n\n\n/*\n *\n * Exported vector functions.\n *\n */\n\nextern \"C\" bool\nmath_vec3_validate(const struct xrt_vec3 *vec3)\n{\n\tassert(vec3 != NULL);\n\n\treturn map_vec3(*vec3).allFinite();\n}\n\nextern \"C\" void\nmath_vec3_accum(const struct xrt_vec3 *additional, struct xrt_vec3 *inAndOut)\n{\n\tassert(additional != NULL);\n\tassert(inAndOut != NULL);\n\n\tmap_vec3(*inAndOut) += map_vec3(*additional);\n}\n\nextern \"C\" void\nmath_vec3_subtract(const struct xrt_vec3 *subtrahend, struct xrt_vec3 *inAndOut)\n{\n\tassert(subtrahend != NULL);\n\tassert(inAndOut != NULL);\n\n\tmap_vec3(*inAndOut) -= map_vec3(*subtrahend);\n}\n\nextern \"C\" void\nmath_vec3_scalar_mul(float scalar, struct xrt_vec3 *inAndOut)\n{\n\tassert(inAndOut != NULL);\n\n\tmap_vec3(*inAndOut) *= scalar;\n}\n\nextern \"C\" void\nmath_vec3_cross(const struct xrt_vec3 *l, const struct xrt_vec3 *r, struct xrt_vec3 *result)\n{\n\tmap_vec3(*result) = map_vec3(*l).cross(map_vec3(*r));\n}\n\nextern \"C\" void\nmath_vec3_normalize(struct xrt_vec3 *in)\n{\n\tmap_vec3(*in) = map_vec3(*in).normalized();\n}\n\n/*\n *\n * Exported quaternion functions.\n *\n */\n\nextern \"C\" void\nmath_quat_from_angle_vector(float angle_rads, const struct xrt_vec3 *vector, struct xrt_quat *result)\n{\n\tmap_quat(*result) = Eigen::AngleAxisf(angle_rads, copy(vector));\n}\n\nextern \"C\" void\nmath_quat_from_matrix_3x3(const struct xrt_matrix_3x3 *mat, struct xrt_quat *result)\n{\n\tEigen::Matrix3f m;\n\tm << mat->v[0], mat->v[1], mat->v[2], mat->v[3], mat->v[4], mat->v[5], mat->v[6], mat->v[7], mat->v[8];\n\n\tEigen::Quaternionf q(m);\n\tmap_quat(*result) = q;\n}\n\nextern \"C\" void\nmath_quat_from_plus_x_z(const struct xrt_vec3 *plus_x, const struct xrt_vec3 *plus_z, struct xrt_quat *result)\n{\n\txrt_vec3 plus_y;\n\tmath_vec3_cross(plus_z, plus_x, &plus_y);\n\n\txrt_matrix_3x3 m = {{\n\t    plus_x->x,\n\t    plus_y.x,\n\t    plus_z->x,\n\t    plus_x->y,\n\t    plus_y.y,\n\t    plus_z->y,\n\t    plus_x->z,\n\t    plus_y.z,\n\t    plus_z->z,\n\t}};\n\n\tmath_quat_from_matrix_3x3(&m, result);\n}\n\nstatic bool\nquat_validate(const float precision, const struct xrt_quat *quat)\n{\n\tassert(quat != NULL);\n\tauto rot = copy(*quat);\n\n\n\t/*\n\t * This was originally squaredNorm, but that could result in a norm\n\t * value that was further from 1.0f then FLOAT_EPSILON (two).\n\t *\n\t * Our tracking system would produce such orientations and looping those\n\t * back into say a quad layer would cause this to fail. And even\n\t * normalizing the quat would not fix this as normalizations uses\n\t * non-squared \"length\" which does fall into the range and doesn't\n\t * change the elements of the quat.\n\t */\n\tauto norm = rot.norm();\n\tif (norm > 1.0f + precision || norm < 1.0f - precision) {\n\t\treturn false;\n\t}\n\n\t// Technically not yet a required check, but easier to stop problems\n\t// now than once denormalized numbers pollute the rest of our state.\n\t// see https://gitlab.khronos.org/openxr/openxr/issues/922\n\tif (!rot.coeffs().allFinite()) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nextern \"C\" bool\nmath_quat_validate(const struct xrt_quat *quat)\n{\n\tconst float FLOAT_EPSILON = Eigen::NumTraits<float>::epsilon();\n\treturn quat_validate(FLOAT_EPSILON, quat);\n}\n\nextern \"C\" bool\nmath_quat_validate_within_1_percent(const struct xrt_quat *quat)\n{\n\treturn quat_validate(0.01, quat);\n}\n\nextern \"C\" void\nmath_quat_invert(const struct xrt_quat *quat, struct xrt_quat *out_quat)\n{\n\tmap_quat(*out_quat) = map_quat(*quat).conjugate();\n}\n\nextern \"C\" void\nmath_quat_normalize(struct xrt_quat *inout)\n{\n\tassert(inout != NULL);\n\tmap_quat(*inout).normalize();\n}\n\nextern \"C\" bool\nmath_quat_ensure_normalized(struct xrt_quat *inout)\n{\n\tassert(inout != NULL);\n\n\tif (math_quat_validate(inout))\n\t\treturn true;\n\n\tconst float FLOAT_EPSILON = Eigen::NumTraits<float>::epsilon();\n\tconst float TOLERANCE = FLOAT_EPSILON * 5;\n\n\tauto rot = copy(*inout);\n\tauto norm = rot.norm();\n\tif (norm > 1.0f + TOLERANCE || norm < 1.0f - TOLERANCE) {\n\t\treturn false;\n\t}\n\n\tmap_quat(*inout).normalize();\n\treturn true;\n}\n\n\nextern \"C\" void\nmath_quat_rotate(const struct xrt_quat *left, const struct xrt_quat *right, struct xrt_quat *result)\n{\n\tassert(left != NULL);\n\tassert(right != NULL);\n\tassert(result != NULL);\n\n\tauto l = copy(left);\n\tauto r = copy(right);\n\n\tauto q = l * r;\n\n\tmap_quat(*result) = q;\n}\n\nextern \"C\" void\nmath_quat_rotate_vec3(const struct xrt_quat *left, const struct xrt_vec3 *right, struct xrt_vec3 *result)\n{\n\tassert(left != NULL);\n\tassert(right != NULL);\n\tassert(result != NULL);\n\n\tauto l = copy(left);\n\tauto r = copy(right);\n\n\tauto v = l * r;\n\n\tmap_vec3(*result) = v;\n}\n\nextern \"C\" void\nmath_quat_rotate_derivative(const struct xrt_quat *quat, const struct xrt_vec3 *deriv, struct xrt_vec3 *result)\n{\n\tassert(quat != NULL);\n\tassert(deriv != NULL);\n\tassert(result != NULL);\n\n\tauto l = copy(quat);\n\tauto m = Eigen::Quaternionf(0.0f, deriv->x, deriv->y, deriv->z);\n\tauto r = l.conjugate();\n\n\tauto v = l * m * r;\n\n\tstruct xrt_vec3 ret = {v.x(), v.y(), v.z()};\n\t*result = ret;\n}\n\nextern \"C\" void\nmath_quat_slerp(const struct xrt_quat *left, const struct xrt_quat *right, float t, struct xrt_quat *result)\n{\n\tassert(left != NULL);\n\tassert(right != NULL);\n\tassert(result != NULL);\n\n\tauto l = copy(left);\n\tauto r = copy(right);\n\n\tmap_quat(*result) = l.slerp(t, r);\n}\n\n/*\n *\n * Exported matrix functions.\n *\n */\n\nvoid\nmath_matrix_2x2_multiply(const struct xrt_matrix_2x2 *left,\n                         const struct xrt_matrix_2x2 *right,\n                         struct xrt_matrix_2x2 *result)\n{\n\tresult->v[0] = left->v[0] * right->v[0] + left->v[1] * right->v[2];\n\tresult->v[1] = left->v[0] * right->v[1] + left->v[1] * right->v[3];\n\tresult->v[2] = left->v[2] * right->v[0] + left->v[3] * right->v[2];\n\tresult->v[3] = left->v[2] * right->v[1] + left->v[3] * right->v[3];\n}\n\nextern \"C\" void\nmath_matrix_3x3_transform_vec3(const struct xrt_matrix_3x3 *left, const struct xrt_vec3 *right, struct xrt_vec3 *result)\n{\n\tEigen::Matrix3f m;\n\tm << left->v[0], left->v[1], left->v[2], // 1\n\t    left->v[3], left->v[4], left->v[5],  // 2\n\t    left->v[6], left->v[7], left->v[8];  // 3\n\n\tmap_vec3(*result) = m * copy(right);\n}\n\nextern \"C\" void\nmath_matrix_3x3_multiply(const struct xrt_matrix_3x3 *left,\n                         const struct xrt_matrix_3x3 *right,\n                         struct xrt_matrix_3x3 *result)\n{\n\tresult->v[0] = left->v[0] * right->v[0] + left->v[1] * right->v[3] + left->v[2] * right->v[6];\n\tresult->v[1] = left->v[0] * right->v[1] + left->v[1] * right->v[4] + left->v[2] * right->v[7];\n\tresult->v[2] = left->v[0] * right->v[2] + left->v[1] * right->v[5] + left->v[2] * right->v[8];\n\n\tresult->v[3] = left->v[3] * right->v[0] + left->v[4] * right->v[3] + left->v[5] * right->v[6];\n\tresult->v[4] = left->v[3] * right->v[1] + left->v[4] * right->v[4] + left->v[5] * right->v[7];\n\tresult->v[5] = left->v[3] * right->v[2] + left->v[4] * right->v[5] + left->v[5] * right->v[8];\n\n\tresult->v[6] = left->v[6] * right->v[0] + left->v[7] * right->v[3] + left->v[8] * right->v[6];\n\tresult->v[7] = left->v[6] * right->v[1] + left->v[7] * right->v[4] + left->v[8] * right->v[7];\n\tresult->v[8] = left->v[6] * right->v[2] + left->v[7] * right->v[5] + left->v[8] * right->v[8];\n}\n\nextern \"C\" void\nmath_matrix_3x3_inverse(const struct xrt_matrix_3x3 *in, struct xrt_matrix_3x3 *result)\n{\n\tEigen::Matrix3f m = copy(in);\n\tmap_matrix_3x3(*result) = m.inverse();\n}\n\nvoid\nmath_matrix_4x4_identity(struct xrt_matrix_4x4 *result)\n{\n\tmap_matrix_4x4(*result) = Eigen::Matrix4f::Identity();\n}\n\nvoid\nmath_matrix_4x4_multiply(const struct xrt_matrix_4x4 *left,\n                         const struct xrt_matrix_4x4 *right,\n                         struct xrt_matrix_4x4 *result)\n{\n\tmap_matrix_4x4(*result) = copy(left) * copy(right);\n}\n\nvoid\nmath_matrix_4x4_view_from_pose(const struct xrt_pose *pose, struct xrt_matrix_4x4 *result)\n{\n\tEigen::Vector3f position = copy(&pose->position);\n\tEigen::Quaternionf orientation = copy(&pose->orientation);\n\n\tEigen::Translation3f translation(position);\n\tEigen::Affine3f transformation = translation * orientation;\n\n\tmap_matrix_4x4(*result) = transformation.matrix().inverse();\n}\n\nvoid\nmath_matrix_4x4_model(const struct xrt_pose *pose, const struct xrt_vec3 *size, struct xrt_matrix_4x4 *result)\n{\n\tEigen::Vector3f position = copy(&pose->position);\n\tEigen::Quaternionf orientation = copy(&pose->orientation);\n\n\tauto scale = Eigen::Scaling(size->x, size->y, size->z);\n\n\tEigen::Translation3f translation(position);\n\tEigen::Affine3f transformation = translation * orientation * scale;\n\n\tmap_matrix_4x4(*result) = transformation.matrix();\n}\n\nvoid\nmath_matrix_4x4_inverse_view_projection(const struct xrt_matrix_4x4 *view,\n                                        const struct xrt_matrix_4x4 *projection,\n                                        struct xrt_matrix_4x4 *result)\n{\n\tEigen::Matrix4f v = copy(view);\n\tEigen::Matrix4f v3 = Eigen::Matrix4f::Identity();\n\tv3.block<3, 3>(0, 0) = v.block<3, 3>(0, 0);\n\tEigen::Matrix4f vp = copy(projection) * v3;\n\tmap_matrix_4x4(*result) = vp.inverse();\n}\n\n\n/*\n *\n * Exported Matrix 4x4 functions.\n *\n */\n\nextern \"C\" void\nm_mat4_f64_identity(struct xrt_matrix_4x4_f64 *result)\n{\n\tmap_matrix_4x4_f64(*result) = Eigen::Matrix4d::Identity();\n}\n\nextern \"C\" void\nm_mat4_f64_invert(const struct xrt_matrix_4x4_f64 *matrix, struct xrt_matrix_4x4_f64 *result)\n{\n\tEigen::Matrix4d m = map_matrix_4x4_f64(*matrix);\n\tmap_matrix_4x4_f64(*result) = m.inverse();\n}\n\nextern \"C\" void\nm_mat4_f64_multiply(const struct xrt_matrix_4x4_f64 *left,\n                    const struct xrt_matrix_4x4_f64 *right,\n                    struct xrt_matrix_4x4_f64 *result)\n{\n\tEigen::Matrix4d l = map_matrix_4x4_f64(*left);\n\tEigen::Matrix4d r = map_matrix_4x4_f64(*right);\n\n\tmap_matrix_4x4_f64(*result) = l * r;\n}\n\nextern \"C\" void\nm_mat4_f64_orientation(const struct xrt_quat *quat, struct xrt_matrix_4x4_f64 *result)\n{\n\tmap_matrix_4x4_f64(*result) = Eigen::Affine3d(copyd(*quat)).matrix();\n}\n\nextern \"C\" void\nm_mat4_f64_model(const struct xrt_pose *pose, const struct xrt_vec3 *size, struct xrt_matrix_4x4_f64 *result)\n{\n\tEigen::Vector3d position = copyd(pose->position);\n\tEigen::Quaterniond orientation = copyd(pose->orientation);\n\n\tauto scale = Eigen::Scaling(copyd(size));\n\n\tEigen::Translation3d translation(position);\n\tEigen::Affine3d transformation = translation * orientation * scale;\n\n\tmap_matrix_4x4_f64(*result) = transformation.matrix();\n}\n\nextern \"C\" void\nm_mat4_f64_view(const struct xrt_pose *pose, struct xrt_matrix_4x4_f64 *result)\n{\n\tEigen::Vector3d position = copyd(pose->position);\n\tEigen::Quaterniond orientation = copyd(pose->orientation);\n\n\tEigen::Translation3d translation(position);\n\tEigen::Affine3d transformation = translation * orientation;\n\n\tmap_matrix_4x4_f64(*result) = transformation.matrix().inverse();\n}\n\n\n/*\n *\n * Exported pose functions.\n *\n */\n\nextern \"C\" bool\nmath_pose_validate(const struct xrt_pose *pose)\n{\n\tassert(pose != NULL);\n\n\treturn math_vec3_validate(&pose->position) && math_quat_validate(&pose->orientation);\n}\n\nextern \"C\" void\nmath_pose_invert(const struct xrt_pose *pose, struct xrt_pose *outPose)\n{\n\tassert(pose != NULL);\n\tassert(outPose != NULL);\n\n\t// Store results to temporary locals so we can do this \"in-place\"\n\t// (pose == outPose) if desired. Pure copies here.\n\tEigen::Vector3f newPosition = position(*pose);\n\tEigen::Quaternionf newOrientation = orientation(*pose);\n\n\t// Conjugate legal here since pose must be normalized/unit length.\n\tnewOrientation = newOrientation.conjugate();\n\t// Use the newly inverted rotation, to rotate position.\n\tnewPosition = -(newOrientation * newPosition);\n\n\tposition(*outPose) = newPosition;\n\torientation(*outPose) = newOrientation;\n}\n\nextern \"C\" void\nmath_pose_identity(struct xrt_pose *pose)\n{\n\tpose->position.x = 0.0;\n\tpose->position.y = 0.0;\n\tpose->position.z = 0.0;\n\tpose->orientation.x = 0.0;\n\tpose->orientation.y = 0.0;\n\tpose->orientation.z = 0.0;\n\tpose->orientation.w = 1.0;\n}\n\n/*!\n * Return the result of transforming a point by a pose/transform.\n */\nstatic inline Eigen::Vector3f\ntransform_point(const xrt_pose &transform, const xrt_vec3 &point)\n{\n\treturn orientation(transform) * map_vec3(point) + position(transform);\n}\n\n/*!\n * Return the result of transforming a pose by a pose/transform.\n */\nstatic inline xrt_pose\ntransform_pose(const xrt_pose &transform, const xrt_pose &pose)\n{\n\txrt_pose ret;\n\tposition(ret) = transform_point(transform, pose.position);\n\torientation(ret) = orientation(transform) * orientation(pose);\n\treturn ret;\n}\n\nextern \"C\" void\nmath_pose_transform(const struct xrt_pose *transform, const struct xrt_pose *pose, struct xrt_pose *outPose)\n{\n\tassert(pose != NULL);\n\tassert(transform != NULL);\n\tassert(outPose != NULL);\n\n\txrt_pose newPose = transform_pose(*transform, *pose);\n\tmemcpy(outPose, &newPose, sizeof(xrt_pose));\n}\n\nextern \"C\" void\nmath_pose_transform_point(const struct xrt_pose *transform, const struct xrt_vec3 *point, struct xrt_vec3 *out_point)\n{\n\tassert(transform != NULL);\n\tassert(point != NULL);\n\tassert(out_point != NULL);\n\n\tmap_vec3(*out_point) = transform_point(*transform, *point);\n}\n", "meta": {"hexsha": "3c5ea6948d50b9b8e434e8c355f779dd2e6db05f", "size": 15163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/xrt/auxiliary/math/m_base.cpp", "max_stars_repo_name": "SimulaVR/monado", "max_stars_repo_head_hexsha": "b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21", "max_stars_repo_licenses": ["Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-08T05:17:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T12:50:59.000Z", "max_issues_repo_path": "src/xrt/auxiliary/math/m_base.cpp", "max_issues_repo_name": "SimulaVR/monado", "max_issues_repo_head_hexsha": "b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21", "max_issues_repo_licenses": ["Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/xrt/auxiliary/math/m_base.cpp", "max_forks_repo_name": "SimulaVR/monado", "max_forks_repo_head_hexsha": "b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21", "max_forks_repo_licenses": ["Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3138564274, "max_line_length": 120, "alphanum_fraction": 0.6823188023, "num_tokens": 4784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.42199628762987595}}
{"text": "/**\n *****************************************************************************\n * @author     This file is part of libsnark, developed by SCIPR Lab\n *             and contributors (see AUTHORS).\n * @copyright  MIT license (see LICENSE file)\n *****************************************************************************/\n#include <boost/program_options.hpp>\n#include <libff/common/profiling.hpp>\n\n#include <libsnark/common/default_types/ram_zksnark_pp.hpp>\n#include <libsnark/relations/ram_computations/memory/examples/memory_contents_examples.hpp>\n#include <libsnark/relations/ram_computations/rams/examples/ram_examples.hpp>\n#include <libsnark/relations/ram_computations/rams/tinyram/tinyram_params.hpp>\n#include <libsnark/zk_proof_systems/zksnark/ram_zksnark/examples/run_ram_zksnark.hpp>\n#include <libsnark/zk_proof_systems/zksnark/ram_zksnark/ram_zksnark.hpp>\n\nusing namespace libsnark;\n\ntemplate<typename FieldT>\nvoid simulate_random_memory_contents(const tinyram_architecture_params &ap, const size_t input_size, const size_t program_size)\n{\n    const size_t num_addresses = 1ul<<ap.dwaddr_len();\n    const size_t value_size = 2 * ap.w;\n    memory_contents init_random = random_memory_contents(num_addresses, value_size, program_size + (input_size + 1)/2);\n\n    libff::enter_block(\"Initialize random delegated memory\");\n    delegated_ra_memory<FieldT> dm_random(num_addresses, value_size, init_random);\n    libff::leave_block(\"Initialize random delegated memory\");\n}\n\ntemplate<typename ppT>\nvoid profile_ram_zksnark_verifier(const tinyram_architecture_params &ap, const size_t input_size, const size_t program_size)\n{\n    typedef ram_zksnark_machine_pp<ppT> ramT;\n    const size_t time_bound  = 10;\n\n    const size_t boot_trace_size_bound = program_size + input_size;\n    const ram_example<ramT> example = gen_ram_example_complex<ramT>(ap, boot_trace_size_bound, time_bound, true);\n\n    ram_zksnark_proof<ppT> pi;\n    ram_zksnark_verification_key<ppT> vk = ram_zksnark_verification_key<ppT>::dummy_verification_key(ap);\n\n    libff::enter_block(\"Verify fake proof\");\n    ram_zksnark_verifier<ppT>(vk, example.boot_trace, time_bound, pi);\n    libff::leave_block(\"Verify fake proof\");\n}\n\ntemplate<typename ppT>\nvoid print_ram_zksnark_verifier_profiling()\n{\n    libff::inhibit_profiling_info = true;\n    for (size_t w : { 16, 32 })\n    {\n        const size_t k = 16;\n\n        for (size_t input_size : { 0, 10, 100 })\n        {\n            for (size_t program_size = 10; program_size <= 10000; program_size *= 10)\n            {\n                const tinyram_architecture_params ap(w, k);\n\n                profile_ram_zksnark_verifier<ppT>(ap, input_size, program_size);\n\n                const double input_map = libff::last_times[\"Call to ram_zksnark_verifier_input_map\"];\n                const double preprocessing = libff::last_times[\"Call to r1cs_ppzksnark_verifier_process_vk\"];\n                const double accumulate = libff::last_times[\"Call to r1cs_ppzksnark_IC_query::accumulate\"];\n                const double pairings = libff::last_times[\"Online pairing computations\"];\n                const double total = libff::last_times[\"Call to ram_zksnark_verifier\"];\n                const double rest = total - (input_map + preprocessing + accumulate + pairings);\n\n                const double delegated_ra_memory_init = libff::last_times[\"Construct delegated_ra_memory from memory map\"];\n                simulate_random_memory_contents<libff::Fr<typename ppT::curve_A_pp> >(ap, input_size, program_size);\n                const double delegated_ra_memory_init_random = libff::last_times[\"Initialize random delegated memory\"];\n                const double input_map_random = input_map - delegated_ra_memory_init + delegated_ra_memory_init_random;\n                const double total_random = total - delegated_ra_memory_init + delegated_ra_memory_init_random;\n\n                printf(\"w = %zu, k = %zu, program_size = %zu, input_size = %zu, input_map = %0.2fms, preprocessing = %0.2fms, accumulate = %0.2fms, pairings = %0.2fms, rest = %0.2fms, total = %0.2fms (input_map_random = %0.2fms, total_random = %0.2fms)\\n\",\n                       w, k, program_size, input_size, input_map * 1e-6, preprocessing * 1e-6, accumulate * 1e-6, pairings * 1e-6, rest * 1e-6, total * 1e-6, input_map_random * 1e-6, total_random * 1e-6);\n            }\n        }\n    }\n}\n\ntemplate<typename ppT>\nvoid profile_ram_zksnark(const tinyram_architecture_params &ap, const size_t program_size, const size_t input_size, const size_t time_bound)\n{\n    typedef ram_zksnark_machine_pp<ppT> ramT;\n\n    const size_t boot_trace_size_bound = program_size + input_size;\n    const ram_example<ramT> example = gen_ram_example_complex<ramT>(ap, boot_trace_size_bound, time_bound, true);\n    const bool test_serialization = true;\n    const bool bit = run_ram_zksnark<ppT>(example, test_serialization);\n    assert(bit);\n}\n\nnamespace po = boost::program_options;\n\nbool process_command_line(const int argc, const char** argv,\n                          bool &profile_gp,\n                          size_t &w,\n                          size_t &k,\n                          bool &profile_v,\n                          size_t &l)\n{\n    try\n    {\n        po::options_description desc(\"Usage\");\n        desc.add_options()\n            (\"help\", \"print this help message\")\n            (\"profile_gp\", \"profile generator and prover\")\n            (\"w\", po::value<size_t>(&w)->default_value(16), \"word size\")\n            (\"k\", po::value<size_t>(&k)->default_value(16), \"register count\")\n            (\"profile_v\", \"profile verifier\")\n            (\"v\", \"print version info\")\n            (\"l\", po::value<size_t>(&l)->default_value(10), \"program length\");\n\n        po::variables_map vm;\n        po::store(po::parse_command_line(argc, argv, desc), vm);\n\n        if (vm.count(\"v\"))\n        {\n            libff::print_compilation_info();\n            exit(0);\n        }\n\n        if (vm.count(\"help\"))\n        {\n            std::cout << desc << \"\\n\";\n            return false;\n        }\n\n        profile_gp = vm.count(\"profile_gp\");\n        profile_v = vm.count(\"profile_v\");\n\n        if (!(vm.count(\"profile_gp\") ^ vm.count(\"profile_v\")))\n        {\n            std::cout << \"Must choose between profiling generator/prover and profiling verifier (see --help)\\n\";\n            return false;\n        }\n\n        po::notify(vm);\n    }\n    catch(std::exception& e)\n    {\n        std::cerr << \"Error: \" << e.what() << \"\\n\";\n        return false;\n    }\n\n    return true;\n}\n\nint main(int argc, const char* argv[])\n{\n    libff::start_profiling();\n    ram_zksnark_PCD_pp<default_ram_zksnark_pp>::init_public_params();\n\n    bool profile_gp;\n    size_t w;\n    size_t k;\n    bool profile_v;\n    size_t l;\n\n    if (!process_command_line(argc, argv, profile_gp, w, k, profile_v, l))\n    {\n        return 1;\n    }\n\n    tinyram_architecture_params ap(w, k);\n\n    if (profile_gp)\n    {\n        profile_ram_zksnark<default_ram_zksnark_pp>(ap, 100, 100, 10); // w, k, l, n, T\n    }\n\n    if (profile_v)\n    {\n        profile_ram_zksnark_verifier<default_ram_zksnark_pp>(ap, l/2, l/2);\n    }\n}\n", "meta": {"hexsha": "914a2d597d73434dae4fccd998d4eb9672cba5ea", "size": 7113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/camlsnark_c/libsnark-caml/libsnark/zk_proof_systems/zksnark/ram_zksnark/profiling/profile_ram_zksnark.cpp", "max_stars_repo_name": "Pratyush/snarky", "max_stars_repo_head_hexsha": "4776e98ba72d4c8706c689fd747462ef87db8799", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1459.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T02:58:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:11:17.000Z", "max_issues_repo_path": "src/camlsnark_c/libsnark-caml/libsnark/zk_proof_systems/zksnark/ram_zksnark/profiling/profile_ram_zksnark.cpp", "max_issues_repo_name": "Pratyush/snarky", "max_issues_repo_head_hexsha": "4776e98ba72d4c8706c689fd747462ef87db8799", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 152.0, "max_issues_repo_issues_event_min_datetime": "2015-03-20T18:55:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T23:51:23.000Z", "max_forks_repo_path": "src/camlsnark_c/libsnark-caml/libsnark/zk_proof_systems/zksnark/ram_zksnark/profiling/profile_ram_zksnark.cpp", "max_forks_repo_name": "Pratyush/snarky", "max_forks_repo_head_hexsha": "4776e98ba72d4c8706c689fd747462ef87db8799", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 464.0, "max_forks_repo_forks_event_min_datetime": "2015-01-10T03:02:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:08:30.000Z", "avg_line_length": 39.5166666667, "max_line_length": 256, "alphanum_fraction": 0.6448755799, "num_tokens": 1788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.42196754904564365}}
{"text": "/*******************************************************************************\n * Copyright (c) 2014, 2016  IBM Corporation and others\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *******************************************************************************/\n#include \"LatLngUtil.hpp\"\n\n#include <boost/geometry/algorithms/detail/vincenty_direct.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/core/srs.hpp>\n#include <boost/geometry/strategies/strategies.hpp>\n#include <boost/geometry/algorithms/assign.hpp>\n#include <boost/geometry/geometries/point.hpp>\n\nnamespace bg = boost::geometry;\n\nnamespace loc {\n    const double d2r = M_PI / 180.0;\n    const double r2d = 180.0 / M_PI;\n    \n    const double gda_a = 6378.1370;\n    const double gda_f = 1.0 / 298.25722210;\n    const double gda_b = gda_a * ( 1.0 - gda_f );\n\n\n    template <typename P>\n    bool LatLngUtil::non_precise_ct()\n    {\n        typedef typename bg::coordinate_type<P>::type ct;\n        return boost::is_integral<ct>::value || boost::is_float<ct>::value;\n    }\n    \n    template <typename P, typename Spheroid>\n     Point2D LatLngUtil::transform(LatLng latlng, Anchor anchor, Spheroid spheroid) {\n        typedef typename bg::promote_floating_point\n        <typename bg::select_calculation_type<P, P, void>::type>::type calc_t;\n        \n        typedef bg::detail::vincenty_inverse<calc_t, true, true> inverse_formula;\n        typename inverse_formula::result_type\n        result_i = inverse_formula::apply(anchor.latlng.lng * d2r,\n                                          anchor.latlng.lat * d2r,\n                                          latlng.lng * d2r,\n                                          latlng.lat * d2r,\n                                          spheroid);\n        calc_t dist = result_i.distance;\n        calc_t azimuth = ((result_i.azimuth * r2d) - anchor.rotate) * d2r;\n        \n        Point2D p;\n        p.x = sin(azimuth) * dist;\n        p.y = cos(azimuth) * dist;\n        return p;\n    }\n    \n    template <typename P, typename Spheroid>\n     LatLng LatLngUtil::transform(LatLng latlng, double dist, double angle, Spheroid spheroid){\n        typedef typename bg::promote_floating_point\n        <typename bg::select_calculation_type<P, P, void>::type>::type calc_t;\n        \n        typedef bg::detail::vincenty_direct<calc_t> direct_formula;\n        typename direct_formula::result_type\n        result = direct_formula::apply(latlng.lng * d2r,\n                                       latlng.lat * d2r,\n                                       dist,\n                                       angle * d2r,\n                                       spheroid);\n        \n        double lat = result.lat2 * r2d;\n        double lng = result.lon2 * r2d;\n        LatLng ll;\n        ll.lat = lat;\n        ll.lng = lng;\n        \n        return ll;\n    }\n    \n\n     LatLng LatLngUtil::localToGlobal(const Point2D p, const Anchor anchor) {\n        bg::srs::spheroid<double> const gda_spheroid(gda_a, gda_b);\n        // usually atan2 takes (y, x) order but rotation is opposite in spherical coordinate\n        double r = (atan2(p.x, p.y) * r2d)+anchor.rotate;\n        double d = sqrt(pow(p.x,2)+pow(p.y,2)) / 1000; // in kilometer\n        \n        typedef typename bg::model::point<double, 2, bg::cs::geographic<bg::degree>> point_t;\n        return transform<point_t>(anchor.latlng, d, r, gda_spheroid);\n    }\n    \n    Point2D LatLngUtil::globalToLocal(const LatLng latlng, const Anchor anchor) {\n        bg::srs::spheroid<double> const gda_spheroid(gda_a, gda_b);\n        typedef typename bg::model::point<double, 2, bg::cs::geographic<bg::degree>> point_t;\n        Point2D p = transform<point_t>(latlng, anchor, gda_spheroid);\n        p.x *= 1000;\n        p.y *= 1000;\n        return p;\n    }\n    \n};\n", "meta": {"hexsha": "cac826782d4fa5ae7700ad5cf932e0d94f35de38", "size": 4901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ble-cpp/src/core/LatLngUtil.cpp", "max_stars_repo_name": "harsh-agarwal/blelocpp", "max_stars_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-06-13T20:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T17:29:32.000Z", "max_issues_repo_path": "ble-cpp/src/core/LatLngUtil.cpp", "max_issues_repo_name": "harsh-agarwal/blelocpp", "max_issues_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-03-14T07:00:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-07T18:20:15.000Z", "max_forks_repo_path": "ble-cpp/src/core/LatLngUtil.cpp", "max_forks_repo_name": "harsh-agarwal/blelocpp", "max_forks_repo_head_hexsha": "eaba46c6239981c7b8e69bef2ab33bb08ecb15b4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-02-03T07:41:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T10:03:48.000Z", "avg_line_length": 42.9912280702, "max_line_length": 95, "alphanum_fraction": 0.6125280555, "num_tokens": 1161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.42196754904564365}}
{"text": "/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*/\n\n#include <mitkGIFVolumetricDensityStatistics.h>\n\n// MITK\n#include <mitkITKImageImport.h>\n#include <mitkImageCast.h>\n#include <mitkImageAccessByItk.h>\n#include <mitkPixelTypeMultiplex.h>\n#include <mitkImagePixelReadAccessor.h>\n\n// ITK\n#include <itkLabelStatisticsImageFilter.h>\n#include <itkNeighborhoodIterator.h>\n#include <itkImageRegionConstIteratorWithIndex.h>\n#include <itkLabelGeometryImageFilter.h>\n\n// VTK\n#include <vtkSmartPointer.h>\n#include <vtkImageMarchingCubes.h>\n#include <vtkMassProperties.h>\n#include <vtkDelaunay3D.h>\n#include <vtkGeometryFilter.h>\n#include <vtkDoubleArray.h>\n#include <vtkPCAStatistics.h>\n#include <vtkTable.h>\n\n// STL\n#include <limits>\n#include <vnl/vnl_math.h>\n\n// Eigen\n#include <Eigen/Dense>\n\nstruct GIFVolumetricDensityStatisticsParameters\n{\n  double volume;\n  std::string prefix;\n};\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid\nCalculateVolumeDensityStatistic(itk::Image<TPixel, VImageDimension>* itkImage, mitk::Image::Pointer mask, GIFVolumetricDensityStatisticsParameters params, mitk::GIFVolumetricDensityStatistics::FeatureListType & featureList)\n{\n  typedef itk::Image<TPixel, VImageDimension> ImageType;\n  typedef itk::Image<unsigned short, VImageDimension> MaskType;\n\n  double volume = params.volume;\n  std::string prefix = params.prefix;\n\n  typename MaskType::Pointer maskImage = MaskType::New();\n  mitk::CastToItkImage(mask, maskImage);\n\n  itk::ImageRegionConstIteratorWithIndex<ImageType> imgA(itkImage, itkImage->GetLargestPossibleRegion());\n  itk::ImageRegionConstIteratorWithIndex<ImageType> imgB(itkImage, itkImage->GetLargestPossibleRegion());\n  itk::ImageRegionConstIteratorWithIndex<MaskType> maskA(maskImage, maskImage->GetLargestPossibleRegion());\n  itk::ImageRegionConstIteratorWithIndex<MaskType> maskB(maskImage, maskImage->GetLargestPossibleRegion());\n\n  double moranA = 0;\n  double moranB = 0;\n  double geary = 0;\n  double Nv = 0;\n  double w_ij = 0;\n  double mean = 0;\n\n  typename ImageType::PointType pointA;\n  typename ImageType::PointType pointB;\n\n  while (!imgA.IsAtEnd())\n  {\n    if (maskA.Get() > 0)\n    {\n      Nv += 1;\n      mean += imgA.Get();\n    }\n    ++imgA;\n    ++maskA;\n  }\n  mean /= Nv;\n  imgA.GoToBegin();\n  maskA.GoToBegin();\n\n  while (!imgA.IsAtEnd())\n  {\n    if (maskA.Get() > 0)\n    {\n      imgB.GoToBegin();\n      maskB.GoToBegin();\n      while (!imgB.IsAtEnd())\n      {\n        if ((imgA.GetIndex() == imgB.GetIndex()) ||\n          (maskB.Get() < 1))\n        {\n          ++imgB;\n          ++maskB;\n          continue;\n        }\n        itkImage->TransformIndexToPhysicalPoint(maskA.GetIndex(), pointA);\n        itkImage->TransformIndexToPhysicalPoint(maskB.GetIndex(), pointB);\n\n        double w = 1 / pointA.EuclideanDistanceTo(pointB);\n        moranA += w*(imgA.Get() - mean)* (imgB.Get() - mean);\n        geary += w * (imgA.Get() - imgB.Get()) * (imgA.Get() - imgB.Get());\n\n        w_ij += w;\n\n        ++imgB;\n        ++maskB;\n      }\n      moranB += (imgA.Get() - mean)* (imgA.Get() - mean);\n    }\n    ++imgA;\n    ++maskA;\n  }\n\n  MITK_INFO << \"Volume: \" << volume;\n  MITK_INFO << \" Mean: \" << mean;\n  featureList.push_back(std::make_pair(prefix + \"Volume integrated intensity\", volume* mean));\n  featureList.push_back(std::make_pair(prefix + \"Volume Moran's I index\", Nv / w_ij * moranA / moranB));\n  featureList.push_back(std::make_pair(prefix + \"Volume Geary's C measure\", ( Nv -1 ) / 2 / w_ij * geary/ moranB));\n}\n\nvoid calculateMOBB(vtkPointSet *pointset, double &volume, double &surface)\n{\n  volume = std::numeric_limits<double>::max();\n\n  for (int cellID = 0; cellID < pointset->GetNumberOfCells(); ++cellID)\n  {\n    auto cell = pointset->GetCell(cellID);\n\n    for (int edgeID = 0; edgeID < 3; ++edgeID)\n    {\n      auto edge = cell->GetEdge(edgeID);\n\n      double pA[3], pB[3];\n      double pAA[3], pBB[3];\n\n      vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();\n      transform->PostMultiply();\n      pointset->GetPoint(edge->GetPointId(0), pA);\n      pointset->GetPoint(edge->GetPointId(1), pB);\n\n      double angleZ = std::atan2((- pA[2] + pB[2]) ,(pA[1] - pB[1]));\n      angleZ *= 180 / vnl_math::pi;\n      if (pA[2] == pB[2])\n        angleZ = 0;\n\n      transform->RotateX(angleZ);\n      transform->TransformPoint(pA, pAA);\n      transform->TransformPoint(pB, pBB);\n\n      double angleY = std::atan2((pAA[1] -pBB[1]) ,-(pAA[0] - pBB[0]));\n      angleY *= 180 / vnl_math::pi;\n      if (pAA[1] == pBB[1])\n        angleY = 0;\n      transform->RotateZ(angleY);\n\n      double p0[3];\n      pointset->GetPoint(edge->GetPointId(0), p0);\n\n      double curMinX = std::numeric_limits<double>::max();\n      double curMaxX = std::numeric_limits<double>::lowest();\n      double curMinY = std::numeric_limits<double>::max();\n      double curMaxY = std::numeric_limits<double>::lowest();\n      double curMinZ = std::numeric_limits<double>::max();\n      double curMaxZ = std::numeric_limits<double>::lowest();\n      for (int pointID = 0; pointID < pointset->GetNumberOfPoints(); ++pointID)\n      {\n        double p[3];\n        double p2[3];\n        pointset->GetPoint(pointID, p);\n        p[0] -= p0[0]; p[1] -= p0[1]; p[2] -= p0[2];\n        transform->TransformPoint(p, p2);\n\n        curMinX = std::min<double>(p2[0], curMinX);\n        curMaxX = std::max<double>(p2[0], curMaxX);\n        curMinY = std::min<double>(p2[1], curMinY);\n        curMaxY = std::max<double>(p2[1], curMaxY);\n        curMinZ = std::min<double>(p2[2], curMinZ);\n        curMaxZ = std::max<double>(p2[2], curMaxZ);\n      }\n\n      if ((curMaxX - curMinX)*(curMaxY - curMinY)*(curMaxZ - curMinZ) < volume)\n      {\n        volume = (curMaxX - curMinX)*(curMaxY - curMinY)*(curMaxZ - curMinZ);\n        surface = (curMaxX - curMinX)*(curMaxX - curMinX) + (curMaxY - curMinY)*(curMaxY - curMinY) + (curMaxZ - curMinZ)*(curMaxZ - curMinZ);\n        surface *= 2;\n      }\n\n\n    }\n  }\n}\n\nvoid calculateMEE(vtkPointSet *pointset, double &vol, double &surf, double tolerance=0.0001)\n{\n  // Inspired by https://github.com/smdabdoub/ProkaryMetrics/blob/master/calc/fitting.py\n\n  int numberOfPoints = pointset->GetNumberOfPoints();\n  int dimension = 3;\n  Eigen::MatrixXd points(3, numberOfPoints);\n  Eigen::MatrixXd Q(3+1, numberOfPoints);\n  double p[3];\n\n  std::cout << \"Initialize Q \" << std::endl;\n  for (int i = 0; i < numberOfPoints; ++i)\n  {\n    pointset->GetPoint(i, p);\n    points(0, i) = p[0];\n    points(1, i) = p[1];\n    points(2, i) = p[2];\n    Q(0, i) = p[0];\n    Q(1, i) = p[1];\n    Q(2, i) = p[2];\n    Q(3, i) = 1.0;\n  }\n\n  int count = 1;\n  double error = 1;\n  Eigen::VectorXd u_vector(numberOfPoints);\n  u_vector.fill(1.0 / numberOfPoints);\n  Eigen::DiagonalMatrix<double, Eigen::Dynamic> u = u_vector.asDiagonal();\n  Eigen::VectorXd ones(dimension + 1);\n  ones.fill(1);\n  Eigen::MatrixXd Ones = ones.asDiagonal();\n\n  // Khachiyan Algorithm\n  while (error > tolerance)\n  {\n    auto Qt = Q.transpose();\n    Eigen::MatrixXd X = Q*u*Qt;\n    Eigen::FullPivHouseholderQR<Eigen::MatrixXd> qr(X);\n    Eigen::MatrixXd Xi = qr.solve(Ones);\n\n    Eigen::MatrixXd M = Qt * Xi * Q;\n\n    double maximumValue = M(0, 0);\n    int maximumPosition = 0;\n    for (int i = 0; i < numberOfPoints; ++i)\n    {\n      if (maximumValue < M(i, i))\n      {\n        maximumValue = M(i, i);\n        maximumPosition = i;\n      }\n    }\n    double stepsize = (maximumValue - dimension - 1) / ((dimension + 1) * (maximumValue - 1));\n    Eigen::DiagonalMatrix<double, Eigen::Dynamic> new_u = (1.0 - stepsize) * u;\n    new_u.diagonal()[maximumPosition] = (new_u.diagonal())(maximumPosition) + stepsize;\n    ++count;\n    error = (new_u.diagonal() - u.diagonal()).norm();\n    u.diagonal() = new_u.diagonal();\n  }\n\n   // U = u\n\n  Eigen::MatrixXd Ai = points * u * points.transpose() - points * u *(points * u).transpose();\n  Eigen::FullPivHouseholderQR<Eigen::MatrixXd> qr(Ai);\n  Eigen::VectorXd ones2(dimension);\n  ones2.fill(1);\n  Eigen::MatrixXd Ones2 = ones2.asDiagonal();\n  Eigen::MatrixXd A = qr.solve(Ones2)*1.0/dimension;\n\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(A);\n  double c = 1 / sqrt(svd.singularValues()[0]);\n  double b = 1 / sqrt(svd.singularValues()[1]);\n  double a = 1 / sqrt(svd.singularValues()[2]);\n  double V = 4 * vnl_math::pi*a*b*c / 3;\n\n  double ad_mvee= 0;\n  double alpha = std::sqrt(1 - b*b / a / a);\n  double beta = std::sqrt(1 - c*c / a / a);\n  for (int i = 0; i < 20; ++i)\n  {\n    ad_mvee += 4 * vnl_math::pi*a*b*(alpha*alpha + beta*beta) / (2 * alpha*beta) * (std::pow(alpha*beta, i)) / (1 - 4 * i*i);\n  }\n  vol = V;\n  surf = ad_mvee;\n}\n\nmitk::GIFVolumetricDensityStatistics::FeatureListType mitk::GIFVolumetricDensityStatistics::CalculateFeatures(const Image::Pointer & image, const Image::Pointer &mask)\n{\n  FeatureListType featureList;\n  if (image->GetDimension() < 3)\n  {\n    return featureList;\n  }\n\n  std::string prefix = FeatureDescriptionPrefix();\n\n  vtkSmartPointer<vtkImageMarchingCubes> mesher = vtkSmartPointer<vtkImageMarchingCubes>::New();\n  vtkSmartPointer<vtkMassProperties> stats = vtkSmartPointer<vtkMassProperties>::New();\n  vtkSmartPointer<vtkMassProperties> stats2 = vtkSmartPointer<vtkMassProperties>::New();\n  mesher->SetInputData(mask->GetVtkImageData());\n  mesher->SetValue(0, 0.5);\n  stats->SetInputConnection(mesher->GetOutputPort());\n  stats->Update();\n\n  vtkSmartPointer<vtkDelaunay3D> delaunay =\n    vtkSmartPointer< vtkDelaunay3D >::New();\n  delaunay->SetInputConnection(mesher->GetOutputPort());\n  delaunay->SetAlpha(0);\n  delaunay->Update();\n  vtkSmartPointer<vtkGeometryFilter> geometryFilter =\n    vtkSmartPointer<vtkGeometryFilter>::New();\n  geometryFilter->SetInputConnection(delaunay->GetOutputPort());\n  geometryFilter->Update();\n  stats2->SetInputConnection(geometryFilter->GetOutputPort());\n  stats2->Update();\n\n  double vol_mvee;\n  double surf_mvee;\n  calculateMEE(mesher->GetOutput(), vol_mvee, surf_mvee);\n\n  double vol_mobb;\n  double surf_mobb;\n  calculateMOBB(geometryFilter->GetOutput(), vol_mobb, surf_mobb);\n\n  double pi = vnl_math::pi;\n\n  double meshVolume = stats->GetVolume();\n  double meshSurf = stats->GetSurfaceArea();\n\n  GIFVolumetricDensityStatisticsParameters params;\n  params.volume = meshVolume;\n  params.prefix = prefix;\n  AccessByItk_3(image, CalculateVolumeDensityStatistic, mask, params, featureList);\n\n  //Calculate center of mass shift\n  int xx = mask->GetDimensions()[0];\n  int yy = mask->GetDimensions()[1];\n  int zz = mask->GetDimensions()[2];\n\n  double xd = mask->GetGeometry()->GetSpacing()[0];\n  double yd = mask->GetGeometry()->GetSpacing()[1];\n  double zd = mask->GetGeometry()->GetSpacing()[2];\n\n  int minimumX=xx;\n  int maximumX=0;\n  int minimumY=yy;\n  int maximumY=0;\n  int minimumZ=zz;\n  int maximumZ=0;\n\n  vtkSmartPointer<vtkDoubleArray> dataset1Arr = vtkSmartPointer<vtkDoubleArray>::New();\n  vtkSmartPointer<vtkDoubleArray> dataset2Arr = vtkSmartPointer<vtkDoubleArray>::New();\n  vtkSmartPointer<vtkDoubleArray> dataset3Arr = vtkSmartPointer<vtkDoubleArray>::New();\n  dataset1Arr->SetNumberOfComponents(1);\n  dataset2Arr->SetNumberOfComponents(1);\n  dataset3Arr->SetNumberOfComponents(1);\n  dataset1Arr->SetName(\"M1\");\n  dataset2Arr->SetName(\"M2\");\n  dataset3Arr->SetName(\"M3\");\n\n  vtkSmartPointer<vtkDoubleArray> dataset1ArrU = vtkSmartPointer<vtkDoubleArray>::New();\n  vtkSmartPointer<vtkDoubleArray> dataset2ArrU = vtkSmartPointer<vtkDoubleArray>::New();\n  vtkSmartPointer<vtkDoubleArray> dataset3ArrU = vtkSmartPointer<vtkDoubleArray>::New();\n  dataset1ArrU->SetNumberOfComponents(1);\n  dataset2ArrU->SetNumberOfComponents(1);\n  dataset3ArrU->SetNumberOfComponents(1);\n  dataset1ArrU->SetName(\"M1\");\n  dataset2ArrU->SetName(\"M2\");\n  dataset3ArrU->SetName(\"M3\");\n\n  vtkSmartPointer<vtkPoints> points =\n    vtkSmartPointer< vtkPoints >::New();\n\n  for (int x = 0; x < xx; x++)\n  {\n    for (int y = 0; y < yy; y++)\n    {\n      for (int z = 0; z < zz; z++)\n      {\n        itk::Image<int,3>::IndexType index;\n\n        index[0] = x;\n        index[1] = y;\n        index[2] = z;\n\n        mitk::ScalarType pxImage;\n        mitk::ScalarType pxMask;\n\n        mitkPixelTypeMultiplex5(\n              mitk::FastSinglePixelAccess,\n              image->GetChannelDescriptor().GetPixelType(),\n              image,\n              image->GetVolumeData(),\n              index,\n              pxImage,\n              0);\n\n        mitkPixelTypeMultiplex5(\n              mitk::FastSinglePixelAccess,\n              mask->GetChannelDescriptor().GetPixelType(),\n              mask,\n              mask->GetVolumeData(),\n              index,\n              pxMask,\n              0);\n\n        //Check if voxel is contained in segmentation\n        if (pxMask > 0)\n        {\n          minimumX = std::min<int>(x, minimumX);\n          minimumY = std::min<int>(y, minimumY);\n          minimumZ = std::min<int>(z, minimumZ);\n          maximumX = std::max<int>(x, maximumX);\n          maximumY = std::max<int>(y, maximumY);\n          maximumZ = std::max<int>(z, maximumZ);\n          points->InsertNextPoint(x*xd, y*yd, z*zd);\n\n          if (pxImage == pxImage)\n          {\n            dataset1Arr->InsertNextValue(x*xd);\n            dataset2Arr->InsertNextValue(y*yd);\n            dataset3Arr->InsertNextValue(z*zd);\n          }\n        }\n      }\n    }\n  }\n\n  vtkSmartPointer<vtkTable> datasetTable = vtkSmartPointer<vtkTable>::New();\n  datasetTable->AddColumn(dataset1Arr);\n  datasetTable->AddColumn(dataset2Arr);\n  datasetTable->AddColumn(dataset3Arr);\n\n  vtkSmartPointer<vtkPCAStatistics> pcaStatistics = vtkSmartPointer<vtkPCAStatistics>::New();\n  pcaStatistics->SetInputData(vtkStatisticsAlgorithm::INPUT_DATA, datasetTable);\n  pcaStatistics->SetColumnStatus(\"M1\", 1);\n  pcaStatistics->SetColumnStatus(\"M2\", 1);\n  pcaStatistics->SetColumnStatus(\"M3\", 1);\n  pcaStatistics->RequestSelectedColumns();\n  pcaStatistics->SetDeriveOption(true);\n  pcaStatistics->Update();\n\n  vtkSmartPointer<vtkDoubleArray> eigenvalues = vtkSmartPointer<vtkDoubleArray>::New();\n  pcaStatistics->GetEigenvalues(eigenvalues);\n\n  std::vector<double> eigen_val(3);\n  eigen_val[2] = eigenvalues->GetValue(0);\n  eigen_val[1] = eigenvalues->GetValue(1);\n  eigen_val[0] = eigenvalues->GetValue(2);\n\n  double major = 2*sqrt(eigen_val[2]);\n  double minor = 2*sqrt(eigen_val[1]);\n  double least = 2*sqrt(eigen_val[0]);\n\n  double alpha = std::sqrt(1 - minor*minor / major / major);\n  double beta = std::sqrt(1 - least*least / major / major);\n\n  double a = (maximumX - minimumX+1) * xd;\n  double b = (maximumY - minimumY+1) * yd;\n  double c = (maximumZ - minimumZ+1) * zd;\n\n  double vd_aabb = meshVolume / (a*b*c);\n  double ad_aabb = meshSurf / (2 * a*b + 2 * a*c + 2 * b*c);\n\n  double vd_aee = 3 * meshVolume / (4.0*pi*major*minor*least);\n  double ad_aee = 0;\n  for (int i = 0; i < 20; ++i)\n  {\n    ad_aee += 4 * pi*major*minor*(alpha*alpha + beta*beta) / (2 * alpha*beta) * (std::pow(alpha*beta, i)) / (1 - 4 * i*i);\n  }\n  ad_aee = meshSurf / ad_aee;\n\n  double vd_ch = meshVolume / stats2->GetVolume();\n  double ad_ch = meshSurf / stats2->GetSurfaceArea();\n\n  featureList.push_back(std::make_pair(prefix + \"Volume density axis-aligned bounding box\", vd_aabb));\n  featureList.push_back(std::make_pair(prefix + \"Surface density axis-aligned bounding box\", ad_aabb));\n  featureList.push_back(std::make_pair(prefix + \"Volume density oriented minimum bounding box\", meshVolume / vol_mobb));\n  featureList.push_back(std::make_pair(prefix + \"Surface density oriented minimum bounding box\", meshSurf / surf_mobb));\n  featureList.push_back(std::make_pair(prefix + \"Volume density approx. enclosing ellipsoid\", vd_aee));\n  featureList.push_back(std::make_pair(prefix + \"Surface density approx. enclosing ellipsoid\", ad_aee));\n  featureList.push_back(std::make_pair(prefix + \"Volume density approx. minimum volume enclosing ellipsoid\", meshVolume / vol_mvee));\n  featureList.push_back(std::make_pair(prefix + \"Surface density approx. minimum volume enclosing ellipsoid\", meshSurf / surf_mvee));\n  featureList.push_back(std::make_pair(prefix + \"Volume density convex hull\", vd_ch));\n  featureList.push_back(std::make_pair(prefix + \"Surface density convex hull\", ad_ch));\n\n  return featureList;\n}\n\nmitk::GIFVolumetricDensityStatistics::GIFVolumetricDensityStatistics()\n{\n  SetLongName(\"volume-density\");\n  SetShortName(\"volden\");\n  SetFeatureClassName(\"Morphological Density\");\n}\n\nmitk::GIFVolumetricDensityStatistics::FeatureNameListType mitk::GIFVolumetricDensityStatistics::GetFeatureNames()\n{\n  FeatureNameListType featureList;\n  return featureList;\n}\n\n\nvoid mitk::GIFVolumetricDensityStatistics::AddArguments(mitkCommandLineParser &parser)\n{\n  std::string name = GetOptionPrefix();\n\n  parser.addArgument(GetLongName(), name, mitkCommandLineParser::Bool, \"Use Volume-Density Statistic\", \"calculates volume density based features\", us::Any());\n}\n\nvoid\nmitk::GIFVolumetricDensityStatistics::CalculateFeaturesUsingParameters(const Image::Pointer & feature, const Image::Pointer &mask, const Image::Pointer &, FeatureListType &featureList)\n{\n  auto parsedArgs = GetParameter();\n  if (parsedArgs.count(GetLongName()))\n  {\n    MITK_INFO << \"Start calculating volumetric density features ....\";\n    auto localResults = this->CalculateFeatures(feature, mask);\n    featureList.insert(featureList.end(), localResults.begin(), localResults.end());\n    MITK_INFO << \"Finished calculating volumetric density features....\";\n  }\n}\n\n", "meta": {"hexsha": "82523f06bb6133212023cde48c0b2ba578265329", "size": 17705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/Classification/CLUtilities/src/GlobalImageFeatures/mitkGIFVolumetricDensityStatistics.cpp", "max_stars_repo_name": "SVRTK/MITK", "max_stars_repo_head_hexsha": "52252d60e42702e292d188e30f6717fe50c23962", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Modules/Classification/CLUtilities/src/GlobalImageFeatures/mitkGIFVolumetricDensityStatistics.cpp", "max_issues_repo_name": "SVRTK/MITK", "max_issues_repo_head_hexsha": "52252d60e42702e292d188e30f6717fe50c23962", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/Classification/CLUtilities/src/GlobalImageFeatures/mitkGIFVolumetricDensityStatistics.cpp", "max_forks_repo_name": "SVRTK/MITK", "max_forks_repo_head_hexsha": "52252d60e42702e292d188e30f6717fe50c23962", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5321969697, "max_line_length": 223, "alphanum_fraction": 0.6620163796, "num_tokens": 5054, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.42192692404596205}}
{"text": "\n#include <NTL/ZZX.h>\n\n#include <NTL/new.h>\n\nNTL_START_IMPL\n\n\n\nconst ZZX& ZZX::zero()\n{\n   static ZZX z;\n   return z;\n}\n\n\n\nvoid conv(ZZ_pX& x, const ZZX& a)\n{\n   conv(x.rep, a.rep);\n   x.normalize();\n}\n\nvoid conv(ZZX& x, const ZZ_pX& a)\n{\n   conv(x.rep, a.rep);\n   x.normalize();\n}\n\n\nistream& operator>>(istream& s, ZZX& x)\n{\n   s >> x.rep;\n   x.normalize();\n   return s;\n}\n\nostream& operator<<(ostream& s, const ZZX& a)\n{\n   return s << a.rep;\n}\n\n\nvoid ZZX::normalize()\n{\n   long n;\n   const ZZ* p;\n\n   n = rep.length();\n   if (n == 0) return;\n   p = rep.elts() + n;\n   while (n > 0 && IsZero(*--p)) {\n      n--;\n   }\n   rep.SetLength(n);\n}\n\n\nlong IsZero(const ZZX& a)\n{\n   return a.rep.length() == 0;\n}\n\n\nlong IsOne(const ZZX& a)\n{\n    return a.rep.length() == 1 && IsOne(a.rep[0]);\n}\n\nlong operator==(const ZZX& a, const ZZX& b)\n{\n   long i, n;\n   const ZZ *ap, *bp;\n\n   n = a.rep.length();\n   if (n != b.rep.length()) return 0;\n\n   ap = a.rep.elts();\n   bp = b.rep.elts();\n\n   for (i = 0; i < n; i++)\n      if (ap[i] != bp[i]) return 0;\n\n   return 1;\n}\n\n\nlong operator==(const ZZX& a, long b)\n{\n   if (b == 0)\n      return IsZero(a);\n\n   if (deg(a) != 0)\n      return 0;\n\n   return a.rep[0] == b;\n}\n\nlong operator==(const ZZX& a, const ZZ& b)\n{\n   if (IsZero(b))\n      return IsZero(a);\n\n   if (deg(a) != 0)\n      return 0;\n\n   return a.rep[0] == b;\n}\n\n\nvoid GetCoeff(ZZ& x, const ZZX& a, long i)\n{\n   if (i < 0 || i > deg(a))\n      clear(x);\n   else\n      x = a.rep[i];\n}\n\nvoid SetCoeff(ZZX& x, long i, const ZZ& a)\n{\n   long j, m;\n\n   if (i < 0) \n      Error(\"SetCoeff: negative index\");\n\n   if (NTL_OVERFLOW(i, 1, 0))\n      Error(\"overflow in SetCoeff\");\n\n   m = deg(x);\n\n   if (i > m && IsZero(a)) return; \n\n   if (i > m) {\n      /* careful: a may alias a coefficient of x */\n\n      long alloc = x.rep.allocated();\n\n      if (alloc > 0 && i >= alloc) {\n         ZZ aa = a;\n         x.rep.SetLength(i+1);\n         x.rep[i] = aa;\n      }\n      else {\n         x.rep.SetLength(i+1);\n         x.rep[i] = a;\n      }\n         \n      for (j = m+1; j < i; j++)\n         clear(x.rep[j]);\n   }\n   else\n      x.rep[i] = a;\n\n   x.normalize();\n}\n\n\nvoid SetCoeff(ZZX& x, long i)\n{\n   long j, m;\n\n   if (i < 0) \n      Error(\"coefficient index out of range\");\n\n   if (NTL_OVERFLOW(i, 1, 0))\n      Error(\"overflow in SetCoeff\");\n\n   m = deg(x);\n\n   if (i > m) {\n      x.rep.SetLength(i+1);\n      for (j = m+1; j < i; j++)\n         clear(x.rep[j]);\n   }\n   set(x.rep[i]);\n   x.normalize();\n}\n\n\nvoid SetX(ZZX& x)\n{\n   clear(x);\n   SetCoeff(x, 1);\n}\n\n\nlong IsX(const ZZX& a)\n{\n   return deg(a) == 1 && IsOne(LeadCoeff(a)) && IsZero(ConstTerm(a));\n}\n      \n      \n\nconst ZZ& coeff(const ZZX& a, long i)\n{\n   if (i < 0 || i > deg(a))\n      return ZZ::zero();\n   else\n      return a.rep[i];\n}\n\n\nconst ZZ& LeadCoeff(const ZZX& a)\n{\n   if (IsZero(a))\n      return ZZ::zero();\n   else\n      return a.rep[deg(a)];\n}\n\nconst ZZ& ConstTerm(const ZZX& a)\n{\n   if (IsZero(a))\n      return ZZ::zero();\n   else\n      return a.rep[0];\n}\n\n\n\nvoid conv(ZZX& x, const ZZ& a)\n{\n   if (IsZero(a))\n      x.rep.SetLength(0);\n   else {\n      x.rep.SetLength(1);\n      x.rep[0] = a;\n   }\n}\n\n\nvoid conv(ZZX& x, long a)\n{\n   if (a == 0) \n      x.rep.SetLength(0);\n   else {\n      x.rep.SetLength(1);\n      conv(x.rep[0], a);\n   }\n}\n\n\nvoid conv(ZZX& x, const vec_ZZ& a)\n{\n   x.rep = a;\n   x.normalize();\n}\n\n\nvoid add(ZZX& x, const ZZX& a, const ZZX& b)\n{\n   long da = deg(a);\n   long db = deg(b);\n   long minab = min(da, db);\n   long maxab = max(da, db);\n   x.rep.SetLength(maxab+1);\n\n   long i;\n   const ZZ *ap, *bp; \n   ZZ* xp;\n\n   for (i = minab+1, ap = a.rep.elts(), bp = b.rep.elts(), xp = x.rep.elts();\n        i; i--, ap++, bp++, xp++)\n      add(*xp, (*ap), (*bp));\n\n   if (da > minab && &x != &a)\n      for (i = da-minab; i; i--, xp++, ap++)\n         *xp = *ap;\n   else if (db > minab && &x != &b)\n      for (i = db-minab; i; i--, xp++, bp++)\n         *xp = *bp;\n   else\n      x.normalize();\n}\n\nvoid add(ZZX& x, const ZZX& a, const ZZ& b)\n{\n   long n = a.rep.length();\n   if (n == 0) {\n      conv(x, b);\n   }\n   else if (&x == &a) {\n      add(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else if (x.rep.MaxLength() == 0) {\n      x = a;\n      add(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else {\n      // ugly...b could alias a coeff of x\n\n      ZZ *xp = x.rep.elts(); \n      add(xp[0], a.rep[0], b);\n      x.rep.SetLength(n);\n      xp = x.rep.elts();\n      const ZZ *ap = a.rep.elts();\n      long i;\n      for (i = 1; i < n; i++)\n         xp[i] = ap[i];\n      x.normalize();\n   }\n}\n\n\nvoid add(ZZX& x, const ZZX& a, long b)\n{\n   if (a.rep.length() == 0) {\n      conv(x, b);\n   }\n   else {\n      if (&x != &a) x = a;\n      add(x.rep[0], x.rep[0], b);\n      x.normalize();\n   }\n}\n\n\nvoid sub(ZZX& x, const ZZX& a, const ZZX& b)\n{\n   long da = deg(a);\n   long db = deg(b);\n   long minab = min(da, db);\n   long maxab = max(da, db);\n   x.rep.SetLength(maxab+1);\n\n   long i;\n   const ZZ *ap, *bp; \n   ZZ* xp;\n\n   for (i = minab+1, ap = a.rep.elts(), bp = b.rep.elts(), xp = x.rep.elts();\n        i; i--, ap++, bp++, xp++)\n      sub(*xp, (*ap), (*bp));\n\n   if (da > minab && &x != &a)\n      for (i = da-minab; i; i--, xp++, ap++)\n         *xp = *ap;\n   else if (db > minab)\n      for (i = db-minab; i; i--, xp++, bp++)\n         negate(*xp, *bp);\n   else\n      x.normalize();\n\n}\n\nvoid sub(ZZX& x, const ZZX& a, const ZZ& b)\n{\n   long n = a.rep.length();\n   if (n == 0) {\n      conv(x, b);\n      negate(x, x);\n   }\n   else if (&x == &a) {\n      sub(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else if (x.rep.MaxLength() == 0) {\n      x = a;\n      sub(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else {\n      // ugly...b could alias a coeff of x\n\n      ZZ *xp = x.rep.elts();\n      sub(xp[0], a.rep[0], b);\n      x.rep.SetLength(n);\n      xp = x.rep.elts();\n      const ZZ *ap = a.rep.elts();\n      long i;\n      for (i = 1; i < n; i++)\n         xp[i] = ap[i];\n      x.normalize();\n   }\n}\n\nvoid sub(ZZX& x, const ZZX& a, long b)\n{\n   if (b == 0) {\n      x = a;\n      return;\n   }\n\n   if (a.rep.length() == 0) {\n      x.rep.SetLength(1);\n      conv(x.rep[0], b);\n      negate(x.rep[0], x.rep[0]);\n   }\n   else {\n      if (&x != &a) x = a;\n      sub(x.rep[0], x.rep[0], b);\n   }\n   x.normalize();\n}\n\nvoid sub(ZZX& x, long a, const ZZX& b)\n{\n   negate(x, b);\n   add(x, x, a);\n}\n\n\nvoid sub(ZZX& x, const ZZ& b, const ZZX& a)\n{\n   long n = a.rep.length();\n   if (n == 0) {\n      conv(x, b);\n   }\n   else if (x.rep.MaxLength() == 0) {\n      negate(x, a);\n      add(x.rep[0], a.rep[0], b);\n      x.normalize();\n   }\n   else {\n      // ugly...b could alias a coeff of x\n\n      ZZ *xp = x.rep.elts();\n      sub(xp[0], b, a.rep[0]);\n      x.rep.SetLength(n);\n      xp = x.rep.elts();\n      const ZZ *ap = a.rep.elts();\n      long i;\n      for (i = 1; i < n; i++)\n         negate(xp[i], ap[i]);\n      x.normalize();\n   }\n}\n\n\n\nvoid negate(ZZX& x, const ZZX& a)\n{\n   long n = a.rep.length();\n   x.rep.SetLength(n);\n\n   const ZZ* ap = a.rep.elts();\n   ZZ* xp = x.rep.elts();\n   long i;\n\n   for (i = n; i; i--, ap++, xp++)\n      negate((*xp), (*ap));\n\n}\n\nlong MaxBits(const ZZX& f)\n{\n   long i, m;\n   m = 0;\n\n   for (i = 0; i <= deg(f); i++) {\n      m = max(m, NumBits(f.rep[i]));\n   }\n\n   return m;\n}\n\n\nvoid PlainMul(ZZX& x, const ZZX& a, const ZZX& b)\n{\n   if (&a == &b) {\n      PlainSqr(x, a);\n      return;\n   }\n\n   long da = deg(a);\n   long db = deg(b);\n\n   if (da < 0 || db < 0) {\n      clear(x);\n      return;\n   }\n\n   long d = da+db;\n\n\n\n   const ZZ *ap, *bp;\n   ZZ *xp;\n   \n   ZZX la, lb;\n\n   if (&x == &a) {\n      la = a;\n      ap = la.rep.elts();\n   }\n   else\n      ap = a.rep.elts();\n\n   if (&x == &b) {\n      lb = b;\n      bp = lb.rep.elts();\n   }\n   else\n      bp = b.rep.elts();\n\n   x.rep.SetLength(d+1);\n\n   xp = x.rep.elts();\n\n   long i, j, jmin, jmax;\n   ZZ t, accum;\n\n   for (i = 0; i <= d; i++) {\n      jmin = max(0, i-db);\n      jmax = min(da, i);\n      clear(accum);\n      for (j = jmin; j <= jmax; j++) {\n\t mul(t, ap[j], bp[i-j]);\n\t add(accum, accum, t);\n      }\n      xp[i] = accum;\n   }\n   x.normalize();\n}\n\nvoid PlainSqr(ZZX& x, const ZZX& a)\n{\n   long da = deg(a);\n\n   if (da < 0) {\n      clear(x);\n      return;\n   }\n\n   long d = 2*da;\n\n   const ZZ *ap;\n   ZZ *xp;\n\n   ZZX la;\n\n   if (&x == &a) {\n      la = a;\n      ap = la.rep.elts();\n   }\n   else\n      ap = a.rep.elts();\n\n\n   x.rep.SetLength(d+1);\n\n   xp = x.rep.elts();\n\n   long i, j, jmin, jmax;\n   long m, m2;\n   ZZ t, accum;\n\n   for (i = 0; i <= d; i++) {\n      jmin = max(0, i-da);\n      jmax = min(da, i);\n      m = jmax - jmin + 1;\n      m2 = m >> 1;\n      jmax = jmin + m2 - 1;\n      clear(accum);\n      for (j = jmin; j <= jmax; j++) {\n\t mul(t, ap[j], ap[i-j]);\n\t add(accum, accum, t);\n      }\n      add(accum, accum, accum);\n      if (m & 1) {\n\t sqr(t, ap[jmax + 1]);\n\t add(accum, accum, t);\n      }\n\n      xp[i] = accum;\n   }\n\n   x.normalize();\n}\n\n\n\nstatic\nvoid PlainMul(ZZ *xp, const ZZ *ap, long sa, const ZZ *bp, long sb)\n{\n   if (sa == 0 || sb == 0) return;\n\n   long sx = sa+sb-1;\n\n   long i, j, jmin, jmax;\n   static ZZ t, accum;\n\n   for (i = 0; i < sx; i++) {\n      jmin = max(0, i-sb+1);\n      jmax = min(sa-1, i);\n      clear(accum);\n      for (j = jmin; j <= jmax; j++) {\n         mul(t, ap[j], bp[i-j]);\n         add(accum, accum, t);\n      }\n      xp[i] = accum;\n   }\n}\n\n\n\nstatic\nvoid KarFold(ZZ *T, const ZZ *b, long sb, long hsa)\n{\n   long m = sb - hsa;\n   long i;\n\n   for (i = 0; i < m; i++)\n      add(T[i], b[i], b[hsa+i]);\n\n   for (i = m; i < hsa; i++)\n      T[i] = b[i];\n}\n\nstatic\nvoid KarSub(ZZ *T, const ZZ *b, long sb)\n{\n   long i;\n\n   for (i = 0; i < sb; i++)\n      sub(T[i], T[i], b[i]);\n}\n\nstatic\nvoid KarAdd(ZZ *T, const ZZ *b, long sb)\n{\n   long i;\n\n   for (i = 0; i < sb; i++)\n      add(T[i], T[i], b[i]);\n}\n\nstatic\nvoid KarFix(ZZ *c, const ZZ *b, long sb, long hsa)\n{\n   long i;\n\n   for (i = 0; i < hsa; i++)\n      c[i] = b[i];\n\n   for (i = hsa; i < sb; i++)\n      add(c[i], c[i], b[i]);\n}\n\nstatic void PlainMul1(ZZ *xp, const ZZ *ap, long sa, const ZZ& b)\n{\n   long i;\n\n   for (i = 0; i < sa; i++)\n      mul(xp[i], ap[i], b);\n}\n\n\n\nstatic\nvoid KarMul(ZZ *c, const ZZ *a, \n            long sa, const ZZ *b, long sb, ZZ *stk)\n{\n   if (sa < sb) {\n      { long t = sa; sa = sb; sb = t; }\n      { const ZZ *t = a; a = b; b = t; }\n   }\n\n   if (sb == 1) {\n      if (sa == 1)\n         mul(*c, *a, *b);\n      else\n         PlainMul1(c, a, sa, *b);\n\n      return;\n   }\n\n   if (sb == 2 && sa == 2) {\n      mul(c[0], a[0], b[0]);\n      mul(c[2], a[1], b[1]);\n      add(stk[0], a[0], a[1]);\n      add(stk[1], b[0], b[1]);\n      mul(c[1], stk[0], stk[1]);\n      sub(c[1], c[1], c[0]);\n      sub(c[1], c[1], c[2]);\n\n      return;\n\n   }\n\n   long hsa = (sa + 1) >> 1;\n\n   if (hsa < sb) {\n      /* normal case */\n\n      long hsa2 = hsa << 1;\n\n      ZZ *T1, *T2, *T3;\n\n      T1 = stk; stk += hsa;\n      T2 = stk; stk += hsa;\n      T3 = stk; stk += hsa2 - 1;\n\n      /* compute T1 = a_lo + a_hi */\n\n      KarFold(T1, a, sa, hsa);\n\n      /* compute T2 = b_lo + b_hi */\n\n      KarFold(T2, b, sb, hsa);\n\n      /* recursively compute T3 = T1 * T2 */\n\n      KarMul(T3, T1, hsa, T2, hsa, stk);\n\n      /* recursively compute a_hi * b_hi into high part of c */\n      /* and subtract from T3 */\n\n      KarMul(c + hsa2, a+hsa, sa-hsa, b+hsa, sb-hsa, stk);\n      KarSub(T3, c + hsa2, sa + sb - hsa2 - 1);\n\n\n      /* recursively compute a_lo*b_lo into low part of c */\n      /* and subtract from T3 */\n\n      KarMul(c, a, hsa, b, hsa, stk);\n      KarSub(T3, c, hsa2 - 1);\n\n      clear(c[hsa2 - 1]);\n\n      /* finally, add T3 * X^{hsa} to c */\n\n      KarAdd(c+hsa, T3, hsa2-1);\n   }\n   else {\n      /* degenerate case */\n\n      ZZ *T;\n\n      T = stk; stk += hsa + sb - 1;\n\n      /* recursively compute b*a_hi into high part of c */\n\n      KarMul(c + hsa, a + hsa, sa - hsa, b, sb, stk);\n\n      /* recursively compute b*a_lo into T */\n\n      KarMul(T, a, hsa, b, sb, stk);\n\n      KarFix(c, T, hsa + sb - 1, hsa);\n   }\n}\n\nvoid KarMul(ZZX& c, const ZZX& a, const ZZX& b)\n{\n   if (IsZero(a) || IsZero(b)) {\n      clear(c);\n      return;\n   }\n\n   if (&a == &b) {\n      KarSqr(c, a);\n      return;\n   }\n\n   vec_ZZ mem;\n\n   const ZZ *ap, *bp;\n   ZZ *cp;\n\n   long sa = a.rep.length();\n   long sb = b.rep.length();\n\n   if (&a == &c) {\n      mem = a.rep;\n      ap = mem.elts();\n   }\n   else\n      ap = a.rep.elts();\n\n   if (&b == &c) {\n      mem = b.rep;\n      bp = mem.elts();\n   }\n   else\n      bp = b.rep.elts();\n\n   c.rep.SetLength(sa+sb-1);\n   cp = c.rep.elts();\n\n   long maxa, maxb, xover;\n\n   maxa = MaxBits(a);\n   maxb = MaxBits(b);\n   xover = 2;\n\n   if (sa < xover || sb < xover)\n      PlainMul(cp, ap, sa, bp, sb);\n   else {\n      /* karatsuba */\n\n      long n, hn, sp, depth;\n\n      n = max(sa, sb);\n      sp = 0;\n      depth = 0;\n      do {\n         hn = (n+1) >> 1;\n         sp += (hn << 2) - 1;\n         n = hn;\n         depth++;\n      } while (n >= xover);\n\n      ZZVec stk;\n      stk.SetSize(sp, \n         ((maxa + maxb + NumBits(min(sa, sb)) + 2*depth + 10) \n          + NTL_ZZ_NBITS-1)/NTL_ZZ_NBITS);\n\n      KarMul(cp, ap, sa, bp, sb, stk.elts());\n   }\n\n   c.normalize();\n}\n\n\n\n\n\n\nvoid PlainSqr(ZZ* xp, const ZZ* ap, long sa)\n{\n   if (sa == 0) return;\n\n   long da = sa-1;\n   long d = 2*da;\n\n   long i, j, jmin, jmax;\n   long m, m2;\n   static ZZ t, accum;\n\n   for (i = 0; i <= d; i++) {\n      jmin = max(0, i-da);\n      jmax = min(da, i);\n      m = jmax - jmin + 1;\n      m2 = m >> 1;\n      jmax = jmin + m2 - 1;\n      clear(accum);\n      for (j = jmin; j <= jmax; j++) {\n\t mul(t, ap[j], ap[i-j]);\n\t add(accum, accum, t);\n      }\n      add(accum, accum, accum);\n      if (m & 1) {\n\t sqr(t, ap[jmax + 1]);\n\t add(accum, accum, t);\n      }\n\n      xp[i] = accum;\n   }\n}\n\n\nstatic\nvoid KarSqr(ZZ *c, const ZZ *a, long sa, ZZ *stk)\n{\n   if (sa == 1) {\n      sqr(*c, *a);\n      return;\n   }\n\n   if (sa == 2) {\n      sqr(c[0], a[0]);\n      sqr(c[2], a[1]);\n      mul(c[1], a[0], a[1]);\n      add(c[1], c[1], c[1]);\n\n      return;\n   }\n\n   if (sa == 3) {\n      sqr(c[0], a[0]);\n      mul(c[1], a[0], a[1]);\n      add(c[1], c[1], c[1]);\n      sqr(stk[0], a[1]);\n      mul(c[2], a[0], a[2]);\n      add(c[2], c[2], c[2]);\n      add(c[2], c[2], stk[0]);\n      mul(c[3], a[1], a[2]);\n      add(c[3], c[3], c[3]);\n      sqr(c[4], a[2]);\n\n      return;\n \n   }\n\n   long hsa = (sa + 1) >> 1;\n   long hsa2 = hsa << 1;\n\n   ZZ *T1, *T2;\n\n   T1 = stk; stk += hsa;\n   T2 = stk; stk += hsa2-1;\n\n   KarFold(T1, a, sa, hsa);\n   KarSqr(T2, T1, hsa, stk);\n\n\n   KarSqr(c + hsa2, a+hsa, sa-hsa, stk);\n   KarSub(T2, c + hsa2, sa + sa - hsa2 - 1);\n\n\n   KarSqr(c, a, hsa, stk);\n   KarSub(T2, c, hsa2 - 1);\n\n   clear(c[hsa2 - 1]);\n\n   KarAdd(c+hsa, T2, hsa2-1);\n}\n\n      \nvoid KarSqr(ZZX& c, const ZZX& a)\n{\n   if (IsZero(a)) {\n      clear(c);\n      return;\n   }\n\n   vec_ZZ mem;\n\n   const ZZ *ap;\n   ZZ *cp;\n\n   long sa = a.rep.length();\n\n   if (&a == &c) {\n      mem = a.rep;\n      ap = mem.elts();\n   }\n   else\n      ap = a.rep.elts();\n\n   c.rep.SetLength(sa+sa-1);\n   cp = c.rep.elts();\n\n   long maxa, xover;\n\n   maxa = MaxBits(a);\n\n   xover = 2;\n\n   if (sa < xover)\n      PlainSqr(cp, ap, sa);\n   else {\n      /* karatsuba */\n\n      long n, hn, sp, depth;\n\n      n = sa;\n      sp = 0;\n      depth = 0;\n      do {\n         hn = (n+1) >> 1;\n         sp += hn+hn+hn - 1;\n         n = hn;\n         depth++;\n      } while (n >= xover);\n\n      ZZVec stk;\n      stk.SetSize(sp, \n         ((2*maxa + NumBits(sa) + 2*depth + 10) \n          + NTL_ZZ_NBITS-1)/NTL_ZZ_NBITS);\n\n      KarSqr(cp, ap, sa, stk.elts());\n   }\n\n   c.normalize();\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "021145cf2a7a54d4900a5b958d07781cd2ae9e86", "size": 15581, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/ZZX.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-17T20:30:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-24T19:52:14.000Z", "max_issues_repo_path": "RUNETag/WinNTL/src/ZZX.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/src/ZZX.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 16.0463439753, "max_line_length": 77, "alphanum_fraction": 0.4397022014, "num_tokens": 5760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.6859494678483918, "lm_q1q2_score": 0.42191918717125443}}
{"text": "#pragma once\n#include \"sico/types/orientations.hpp\"\n\n#ifdef SICO_USE_EIGEN\n#pragma warning(push)\n#pragma warning(disable : 4365)\n#pragma warning(disable : 4464)\n#pragma warning(disable : 4514)\n#pragma warning(disable : 4710)\n#pragma warning(disable : 4625)\n#pragma warning(disable : 4626)\n#pragma warning(disable : 4820)\n#pragma warning(disable : 5026)\n#pragma warning(disable : 5027)\n#pragma warning(disable : 5045)\n#define EIGEN_PERMANENTLY_DISABLE_STUPID_WARNINGS\n#include <Eigen/Dense>\n#pragma warning(pop)\n\nnamespace sico {\n\nusing vector3d   = Eigen::Vector3d;\nusing matrix3d   = Eigen::Matrix3d;\nusing quaternion = Eigen::Quaterniond;\n\n} // namespace sico\n\n#else\n#include \"sico/types/angles.hpp\"\n\n#include <array>\n#include <type_traits>\n\n#pragma warning(push)\n#pragma warning(disable : 5045) // spectre\nnamespace sico {\n\nusing scalar_t = double;\n\ntemplate<size_t S>\nusing arrayd = std::array<scalar_t, S>;\n\n// Basic linear algebra based on arrays of doubles\nusing vector3d   = arrayd<3>;\nusing matrix3d   = arrayd<9>;\nusing quaternion = arrayd<4>;\n\n// Beneric operations\ntemplate<size_t S>\narrayd<S> operator+(arrayd<S> const& s1, arrayd<S> const& s2)\n{\n    arrayd<S> s;\n    for (size_t i = 0; i < S; i++)\n        s[i] = s1[i] + s2[i];\n    return s;\n}\ntemplate<size_t S>\narrayd<S>& operator+=(arrayd<S>& s1, arrayd<S> const& s2)\n{\n    for (size_t i = 0; i < S; i++)\n        s1[i] += s2[i];\n    return s1;\n}\ntemplate<size_t S>\narrayd<S>& operator+=(arrayd<S>& s1, scalar_t const v)\n{\n    for (size_t i = 0; i < S; i++)\n        s1[i] += v;\n    return s1;\n}\ntemplate<size_t S>\narrayd<S> operator-(arrayd<S> const& s1)\n{\n    arrayd<S> s;\n    for (size_t i = 0; i < S; i++)\n        s[i] = -s1[i];\n    return s;\n}\ntemplate<size_t S>\narrayd<S> operator*(arrayd<S> const& s1, scalar_t const t)\n{\n    arrayd<S> s;\n    for (size_t i = 0; i < S; i++)\n        s[i] = s1[i] * t;\n    return s;\n}\ntemplate<size_t S>\narrayd<S>& operator*=(arrayd<S>& s, scalar_t const t)\n{\n    for (size_t i = 0; i < S; i++)\n        s[i] *= t;\n    return s;\n}\ntemplate<size_t S>\nbool operator==(arrayd<S> const& s1, arrayd<S> const& s2)\n{\n    bool r = true;\n    for (size_t i = 0; i < S; i++)\n        r = r && s1[i] == s2[i];\n    return r;\n}\ntemplate<size_t S>\nscalar_t dot(arrayd<S> const& s1, arrayd<S> const& s2)\n{\n    scalar_t d = 0;\n    for (size_t i = 0; i < S; i++) {\n        d += s1[i] * s2[i];\n    }\n    return d;\n}\n\n// generic operations, based on previously defined ones\ntemplate<size_t S>\narrayd<S> operator-(arrayd<S> const& s1, arrayd<S> const& s2)\n{\n    return s1 + -s2;\n}\ntemplate<size_t S>\narrayd<S>& operator-=(arrayd<S>& s1, arrayd<S> const& s2)\n{\n    s1 += -s2;\n    return s1;\n}\ntemplate<size_t S>\narrayd<S>& operator-=(arrayd<S>& s1, scalar_t const v)\n{\n    s1 += -v;\n    return s1;\n}\ntemplate<size_t S>\narrayd<S> operator/(arrayd<S> const& s1, scalar_t const d)\n{\n    return s1 * (1.0 / d);\n}\ntemplate<size_t S>\narrayd<S>& operator/=(arrayd<S>& s1, scalar_t const d)\n{\n    s1 *= 1.0 / d;\n    return s1;\n}\ntemplate<size_t S>\nbool operator!=(arrayd<S> const& s1, arrayd<S> const& s2)\n{\n    return !(s1 == s2);\n}\ntemplate<size_t S>\nscalar_t length_squared(arrayd<S> const& s)\n{\n    return dot(s, s);\n}\ntemplate<size_t S>\nscalar_t length(arrayd<S> const& s)\n{\n    return sqrt(length_squared(s));\n}\ntemplate<size_t S>\narrayd<S>& normalize(arrayd<S>& s)\n{\n    auto const l = length(s);\n    if (l < 0.0001)\n        return s;\n    s /= l;\n    return s;\n}\ntemplate<size_t S>\narrayd<S> normalized(arrayd<S> s)\n{\n    normalize(s);\n    return s;\n}\n\n// quaternion operations\ninline quaternion operator*(quaternion const& q1, quaternion const& q2)\n{\n    return { q1[3] * q2[0] + q1[0] * q2[3] + q1[1] * q2[2] - q1[2] * q2[1],\n             q1[3] * q2[1] + q1[1] * q2[3] + q1[2] * q2[0] - q1[0] * q2[2],\n             q1[3] * q2[2] + q1[2] * q2[3] + q1[0] * q2[1] - q1[1] * q2[0],\n             q1[3] * q2[3] - q1[0] * q2[0] - q1[1] * q2[1] - q1[2] * q2[2] };\n}\ninline quaternion conj(quaternion const& q)\n{\n    return { -q[0], -q[1], -q[2], q[3] };\n}\ninline vector3d operator*(quaternion const& rot, vector3d const& v)\n{\n    quaternion const pure { v[0], v[1], v[2], 0.0 };\n    quaternion const rot_conj = conj(rot);\n    quaternion const temp { pure[3] * rot_conj[0] + pure[0] * rot_conj[3] + pure[1] * rot_conj[2]\n                                - pure[2] * rot_conj[1],\n                            pure[3] * rot_conj[1] + pure[1] * rot_conj[3] + pure[2] * rot_conj[0]\n                                - pure[0] * rot_conj[2],\n                            pure[3] * rot_conj[2] + pure[2] * rot_conj[3] + pure[0] * rot_conj[1]\n                                - pure[1] * rot_conj[0],\n                            pure[3] * rot_conj[3] - pure[0] * rot_conj[0] - pure[1] * rot_conj[1]\n                                - pure[2] * rot_conj[2] };\n\n    return { rot[3] * temp[0] + rot[0] * temp[3] + rot[1] * temp[2] - rot[2] * temp[1],\n             rot[3] * temp[1] + rot[1] * temp[3] + rot[2] * temp[0] - rot[0] * temp[2],\n             rot[3] * temp[2] + rot[2] * temp[3] + rot[0] * temp[1] - rot[1] * temp[0] };\n}\ninline quaternion from_euler(scalar_t xRot, scalar_t yRot, scalar_t zRot)\n{\n    using std::cos;\n    using std::sin;\n    auto const       hX = xRot * 0.5;\n    auto const       hY = yRot * 0.5;\n    auto const       hZ = zRot * 0.5;\n    quaternion const qx { sin(hX), 0.0, 0.0, cos(hX) };\n    quaternion const qy { 0.0, sin(hY), 0.0, cos(hY) };\n    quaternion const qz { 0.0, 0.0, sin(hZ), cos(hZ) };\n    quaternion       result = qx * qy * qz;\n    normalize(result);\n    return result;\n}\n\n// matrix operations\ninline double& mat(matrix3d& m, size_t row, size_t column)\n{\n    return m[row * 3 + column];\n}\ninline double mat(matrix3d const& m, size_t row, size_t column)\n{\n    return m[row * 3 + column];\n}\ninline vector3d operator*(matrix3d const& m, vector3d const& v)\n{\n    vector3d res;\n    res.fill(0);\n    for (unsigned r = 0; r < 3; ++r)\n        for (unsigned c = 0; c < 3; ++c)\n            res[r] += mat(m, r, c) * v[c];\n\n    return res;\n}\ninline matrix3d rot_mat(quaternion const& q)\n{\n    auto const xs = q[0] + q[0];\n    auto const ys = q[1] + q[1];\n    auto const zs = q[2] + q[2];\n    auto const xx = q[0] * xs;\n    auto const xy = q[0] * ys;\n    auto const xz = q[0] * zs;\n    auto const yy = q[1] * ys;\n    auto const yz = q[1] * zs;\n    auto const zz = q[2] * zs;\n    auto const wx = q[3] * xs;\n    auto const wy = q[3] * ys;\n    auto const wz = q[3] * zs;\n\n    matrix3d m;\n    mat(m, 0, 0) = double(1.0) - (yy + zz);\n    mat(m, 1, 0) = xy + wz;\n    mat(m, 2, 0) = xz - wy;\n    mat(m, 0, 1) = xy - wz;\n    mat(m, 1, 1) = double(1.0) - (xx + zz);\n    mat(m, 2, 1) = yz + wx;\n    mat(m, 0, 2) = xz + wy;\n    mat(m, 1, 2) = yz - wx;\n    mat(m, 2, 2) = double(1.0) - (xx + yy);\n    return m;\n}\ninline void to_euler(matrix3d const& m, scalar_t& x, scalar_t& y, scalar_t& z)\n{\n    y = asin(mat(m, 0, 2));\n    if (y < SICO_PI2) {\n        if (y > -SICO_PI2) {\n            x = atan2(-mat(m, 1, 2), mat(m, 2, 2));\n            z = atan2(-mat(m, 0, 1), mat(m, 0, 0));\n        }\n        else {\n            x = -atan2(mat(m, 1, 0), mat(m, 1, 1));\n            z = 0;\n        }\n    }\n    else {\n        x = atan2(mat(m, 1, 0), mat(m, 1, 1));\n        z = 0;\n    }\n}\n\n} // namespace sico\n#pragma warning(pop)\n#endif\n\nnamespace sico {\ntemplate<typename Ref>\ninline quaternion make_quat(quat<Ref> const& q)\n{\n#ifdef SICO_USE_EIGEN\n    return quaternion(q.w, q.x, q.y, q.z);\n#else\n    return quaternion { q.x, q.y, q.z, q.w };\n#endif\n}\n\ntemplate<typename Ref>\ninline quat<Ref> make_quat(quaternion const& q)\n{\n#ifdef SICO_USE_EIGEN\n    return quat<Ref> { q.x(), q.y(), q.z(), q.w() };\n#else\n    return quat<Ref> { q[0], q[1], q[2], q[3] };\n#endif\n}\n} // namespace sico\n\n//\n// Simulation-Coordinates library\n// Author F.Jacomme\n// MIT Licensed\n//", "meta": {"hexsha": "0035a17a34e84d341eaa6f0314a4cd0e6bf51206", "size": 7821, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sico/types/linear_algebra.hpp", "max_stars_repo_name": "fjacomme/sico", "max_stars_repo_head_hexsha": "501b8f08313e4394ac8585167b74374e2ae3da09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sico/types/linear_algebra.hpp", "max_issues_repo_name": "fjacomme/sico", "max_issues_repo_head_hexsha": "501b8f08313e4394ac8585167b74374e2ae3da09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/sico/types/linear_algebra.hpp", "max_forks_repo_name": "fjacomme/sico", "max_forks_repo_head_hexsha": "501b8f08313e4394ac8585167b74374e2ae3da09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1479099678, "max_line_length": 97, "alphanum_fraction": 0.5547883902, "num_tokens": 2831, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4219191792734037}}
{"text": "#ifndef MATHTOOLBOX_KERNEL_FUNCTIONS_HPP\n#define MATHTOOLBOX_KERNEL_FUNCTIONS_HPP\n\n#include <Eigen/Core>\n#include <functional>\n\nnamespace mathtoolbox\n{\n    using Kernel = std::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&, const Eigen::VectorXd&)>;\n    using KernelThetaDerivative =\n        std::function<Eigen::VectorXd(const Eigen::VectorXd&, const Eigen::VectorXd&, const Eigen::VectorXd&)>;\n    using KernelThetaIDerivative =\n        std::function<double(const Eigen::VectorXd&, const Eigen::VectorXd&, const Eigen::VectorXd&, const int)>;\n    using KernelFirstArgDerivative =\n        std::function<Eigen::VectorXd(const Eigen::VectorXd&, const Eigen::VectorXd&, const Eigen::VectorXd&)>;\n\n    double GetArdSquaredExpKernel(const Eigen::VectorXd& x_a, const Eigen::VectorXd& x_b, const Eigen::VectorXd& theta);\n\n    Eigen::VectorXd GetArdSquaredExpKernelThetaDerivative(const Eigen::VectorXd& x_a,\n                                                          const Eigen::VectorXd& x_b,\n                                                          const Eigen::VectorXd& theta);\n\n    double GetArdSquaredExpKernelThetaIDerivative(const Eigen::VectorXd& x_a,\n                                                  const Eigen::VectorXd& x_b,\n                                                  const Eigen::VectorXd& theta,\n                                                  const int              index);\n\n    Eigen::VectorXd GetArdSquaredExpKernelFirstArgDerivative(const Eigen::VectorXd& x_a,\n                                                             const Eigen::VectorXd& x_b,\n                                                             const Eigen::VectorXd& theta);\n\n    double GetArdMatern52Kernel(const Eigen::VectorXd& x_a, const Eigen::VectorXd& x_b, const Eigen::VectorXd& theta);\n\n    Eigen::VectorXd GetArdMatern52KernelThetaDerivative(const Eigen::VectorXd& x_a,\n                                                        const Eigen::VectorXd& x_b,\n                                                        const Eigen::VectorXd& theta);\n\n    double GetArdMatern52KernelThetaIDerivative(const Eigen::VectorXd& x_a,\n                                                const Eigen::VectorXd& x_b,\n                                                const Eigen::VectorXd& theta,\n                                                const int              index);\n\n    Eigen::VectorXd GetArdMatern52KernelFirstArgDerivative(const Eigen::VectorXd& x_a,\n                                                           const Eigen::VectorXd& x_b,\n                                                           const Eigen::VectorXd& theta);\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_KERNEL_FUNCTIONS_HPP\n", "meta": {"hexsha": "4d38dab8aad026ad9cc9e37473aa2b0bba530cc3", "size": 2705, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/kernel-functions.hpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "include/mathtoolbox/kernel-functions.hpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "include/mathtoolbox/kernel-functions.hpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 55.2040816327, "max_line_length": 120, "alphanum_fraction": 0.5445471349, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.4218996308937385}}
{"text": "// ======================================================================\n/*!\n * \\file NFmiAzimuthalArea.cpp\n * \\brief Implementation of class NFmiAzimuthalArea\n */\n// ======================================================================\n/*!\n * \\class NFmiAzimuthalArea\n *\n * Abstract class for azimuthal projections.\n * Partially based on masterpiece \"npolster.cpp\" (Originaali 1.  3. 1996/Persa ja Kari)\n *\n * Azimuthal projections are based on refs.\n *\n *\t-# Peter Richardus, Ron K.Adler: \"Map Projections\", North-Holland, 2nd printing 1974.\n *\t-# \"Navigation Facility Reference Manual\" rev. 2.0 3/93\n *\t-# \"An Album of Map Projections\" USGS Paper 1453\n *\n * SOME BASIC AZIMUTHAL PROJECTION CONCEPTS\n *\n * POLAR or NORMAL CASE means the central latitude is 90 degrees North,\n * that is the North Pole\n *\n * TANGENTIAL CASE means the true latitude is 90 degrees North, otherwise we talk\n * about NON-TANGENTIAL or SECANT CASE\n *\n *\n * NOTE:\n * Applying non-polar case (central latitude other than 90 degrees North) is\n * possible but not tested in this program. Applying both non-tangential projection\n * plane AND non-polar case together is NOT ALLOWED in this program! FMI defaults to\n * following values: central latitude 90 deg North, true latitude 60 deg North\n *\n *\n * The y axis lies along the central meridian (lon0), y increasing north;\n * The x axis is perpendicular to the y axis at (lon0,lat0), x increasing east.\n *\n * RECTANGULAR LOCAL COORDINATES are relative unitless cartesian XY-coordinates.\n * The range for these coordinates will be derived directly from the size of the\n * local rectangle used. The upper left corner XY-point and the opposite lower right\n * corner XY-point will define the LOCAL RECTANGLE.\n *\n * RECTANGULAR WORLD COORDINATES are cartesian XY-coordinates measured in meters\n * on \"true world\" map plane. The upper left corner XY-point and the opposite lower\n * right corner XY-point (in meters) will define the WORLD RECTANGLE.\n *\n * GEODETIC COORDINATES are latitude-longitude coordinates in degrees.\n *\n *\n * \\see NFmiStereographicArea, NFmiGnomonicArea and NFmiEquidistArea\n *\n * INPUT PARAMETERS/ARGUMENT LISTS\n *\n * theBottomLeftLatLon = lower left corner point of the rectangle in GEODETIC\n *\t\t\t\t\t\t\t\t latitude-longitude coordinates\n *\n * theTopRightLatLon =\t upper right corner point of the rectangle in GEODETIC\n *\t\t\t\t\t\t\t\t latitude-longitude coordinates for\n *the\n *rectangle\n *\n * theCentralLongitude = central longitude (also called central meridian)\n *\n * theTopLeftXY = upper left corner of the rectangle in rectangular LOCAL coordinates\n *\n * theBottomRightXY = lower right corner of the rectangle in rectangular LOCAL coordinates\n *\n *\n * theCenterLatitude = See definition in ref [1]. For example, center latitude\n *\t\t\t\t\t for the north POLAR stereographic projection is always 90\n *degrees.\n *\t\t\t\t\t This is also called a \"normal\" projection case.\n *                   If the central latitude is other than 90 degrees the projection is NOT\n *\t\t\t\t\t a polar (or normal case of) projection.\n *\n * theTrueLatitude = latitude, where the Earth globe intersects the rectangular world\n *\t\t\t\t\t XY plane. For true angle 90 degrees North the intersecting\n *XY\n *plane\n *gently\n *\t\t\t\t\t touches the north pole. For details, see ref [2].\n *\n * theRadialRange = radius of the circle bounded by corner points forming a square.\n *                  Radius is assumed to be given in meters\n *\n */\n// ======================================================================\n\n#include \"NFmiAzimuthalArea.h\"\n#include <boost/functional/hash.hpp>\n#include <macgyver/Exception.h>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n\nusing namespace std;\n\n#include \"NFmiVersion.h\"\n\n// ----------------------------------------------------------------------\n/*!\n * Void constructor\n */\n// ----------------------------------------------------------------------\n\nNFmiAzimuthalArea::NFmiAzimuthalArea()\n    : itsTopRightLatLon(),\n      itsBottomLeftLatLon(),\n      itsBottomLeftWorldXY(),\n      itsXScaleFactor(),\n      itsYScaleFactor(),\n      itsWorldRect(),\n      itsRadialRange(),\n      itsCentralLongitude(),\n      itsCentralLatitude(),\n      itsTrueLatitude(),\n      itsTrueLatScaleFactor()\n{\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Copy constructor\n *\n * \\param theAzimuthalArea The other area being copied\n */\n// ----------------------------------------------------------------------\n\nNFmiAzimuthalArea::NFmiAzimuthalArea(const NFmiAzimuthalArea &theAzimuthalArea)\n\n    = default;\n\n/*!\n * Constructor\n *\n * \\param theCenterLatLon Undocumented\n * \\param theRadialRangeInMeters Undocumented\n * \\param theTopLeftXY Undocumented\n * \\param theBottomRightXY Undocumented\n */\nNFmiAzimuthalArea::NFmiAzimuthalArea(double theRadialRangeInMeters,\n                                     const NFmiPoint &theCenterLatLon,\n                                     const NFmiPoint &theTopLeftXY,\n                                     const NFmiPoint &theBottomRightXY,\n                                     bool usePacificView)\n    : NFmiArea(theTopLeftXY, theBottomRightXY, usePacificView),\n      itsTopRightLatLon(),\n      itsBottomLeftLatLon(),\n      itsBottomLeftWorldXY(),\n      itsXScaleFactor(),\n      itsYScaleFactor(),\n      itsWorldRect(),\n      itsRadialRange(theRadialRangeInMeters),\n      itsCentralLongitude(theCenterLatLon.X(), usePacificView),\n      itsCentralLatitude(theCenterLatLon.Y()),\n      itsTrueLatitude(90.),\n      itsTrueLatScaleFactor(1.0)\n{\n}\n\n// ----------------------------------------------------------------------\n/*!\n * This constructor creates a XY world rectangle based on the given bottom\n * left and top right latlons.\n *\n * \\param theBottomLeftLatLon The bottom left corner coordinates\n * \\param theTopRightLatLon The top right corner coordinates\n * \\param theCentralLongitude The central longitude of the projection\n * \\param theTopLeftXY The top left view coordinates\n * \\param theBottomRightXY The bottom right view coordinates\n * \\param theCentralLatitude The projection center latitude\n * \\param theTrueLatitude The tangential plane latitude\n */\n// ----------------------------------------------------------------------\n\nNFmiAzimuthalArea::NFmiAzimuthalArea(const NFmiPoint &theBottomLeftLatLon,\n                                     const NFmiPoint &theTopRightLatLon,\n                                     const double theCentralLongitude,\n                                     const NFmiPoint &theTopLeftXY,\n                                     const NFmiPoint &theBottomRightXY,\n                                     const double theCentralLatitude,\n                                     const double theTrueLatitude,\n                                     bool usePacificView)\n    : NFmiArea(theTopLeftXY, theBottomRightXY, usePacificView),\n      itsTopRightLatLon(theTopRightLatLon),\n      itsBottomLeftLatLon(theBottomLeftLatLon),\n      itsBottomLeftWorldXY(),\n      itsXScaleFactor(),\n      itsYScaleFactor(),\n      itsWorldRect(),\n      itsRadialRange(0.),\n      itsCentralLongitude(theCentralLongitude, usePacificView),\n      itsCentralLatitude(theCentralLatitude),\n      itsTrueLatitude(theTrueLatitude),\n      itsTrueLatScaleFactor(0.0)\n{\n}\n\n// ----------------------------------------------------------------------\n/*!\n * This constructor creates a XY world rectangle based on the given bottom\n * left latlon and the given width and height of the world rectangle\n * in X and Y directions, respectively.\n *\n * \\param theBottomLeftLatLon The bottom left corner coordinates\n * \\param theCentralLongitude The central longitude of the projection\n * \\param theTopLeftXY The top left view coordinates\n * \\param theBottomRightXY The bottom right view coordinates\n * \\param theCentralLatitude The projection center latitude\n * \\param theTrueLatitude The tangential plane latitude\n */\n// ----------------------------------------------------------------------\n\nNFmiAzimuthalArea::NFmiAzimuthalArea(const NFmiPoint &theBottomLeftLatLon,\n                                     const double theCentralLongitude,\n                                     const NFmiPoint &theTopLeftXY,\n                                     const NFmiPoint &theBottomRightXY,\n                                     const double theCentralLatitude,\n                                     const double theTrueLatitude,\n                                     bool usePacificView)\n    : NFmiArea(theTopLeftXY, theBottomRightXY, usePacificView),\n      itsTopRightLatLon(),\n      itsBottomLeftLatLon(theBottomLeftLatLon),\n      itsBottomLeftWorldXY(),\n      itsXScaleFactor(),\n      itsYScaleFactor(),\n      itsWorldRect(),\n      itsRadialRange(0.),\n      itsCentralLongitude(theCentralLongitude, usePacificView),\n      itsCentralLatitude(theCentralLatitude),\n      itsTrueLatitude(theTrueLatitude),\n      itsTrueLatScaleFactor(0.0)\n{\n}\n\n// ----------------------------------------------------------------------\n/*!\n * This constructor creates a XY world square based on the radial range.\n * This range can be taken as the radius of the circle bounded by corner\n * points forming the square. Radius is assumed to be given in meters\n *\n * \\param theRadialRange The redius of the view area in meters.\n * \\param theCentralLongitude The central longitude of the projection\n * \\param theTopLeftXY The top left view coordinates\n * \\param theBottomRightXY The bottom right view coordinates\n * \\param theCentralLatitude The projection center latitude\n * \\param theTrueLatitude The tangential plane latitude\n */\n// ----------------------------------------------------------------------\n\nNFmiAzimuthalArea::NFmiAzimuthalArea(const double theRadialRange,\n                                     const double theCentralLongitude,\n                                     const NFmiPoint &theTopLeftXY,\n                                     const NFmiPoint &theBottomRightXY,\n                                     const double theCentralLatitude,\n                                     const double theTrueLatitude,\n                                     bool usePacificView)\n    : NFmiArea(theTopLeftXY, theBottomRightXY, usePacificView),\n      itsTopRightLatLon(),\n      itsBottomLeftLatLon(),\n      itsBottomLeftWorldXY(),\n      itsXScaleFactor(),\n      itsYScaleFactor(),\n      itsWorldRect(),\n      itsRadialRange(theRadialRange),\n      itsCentralLongitude(theCentralLongitude, usePacificView),\n      itsCentralLatitude(theCentralLatitude),\n      itsTrueLatitude(theTrueLatitude),\n      itsTrueLatScaleFactor(0.0)\n{\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param fKeepWorldRect Undocumented, unused\n */\n// ----------------------------------------------------------------------\n\nvoid NFmiAzimuthalArea::Init(bool /* fKeepWorldRect */)\n{\n  try\n  {\n    itsXScaleFactor = Width() / itsWorldRect.Width();\n    itsYScaleFactor = Height() / itsWorldRect.Height();\n\n    itsTrueLatScaleFactor =\n        (DistanceFromPerspectivePointToCenterOfEarth() + kRearth * itsTrueLatitude.Sin()) /\n        (DistanceFromPerspectivePointToCenterOfEarth() + kRearth);\n\n    itsTopRightLatLon = TopRightLatLon();\n    itsBottomLeftLatLon = BottomLeftLatLon();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Returns the geodetic latitude-longitude point corresponding the\n * rectangular LOCAL point theXYPoint. Point will be returned in degrees.\n *\n * \\param theXYPoint The local xy-coordinates to be converted\n * \\return The respective geodetic coordinates\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiAzimuthalArea::ToLatLon(const NFmiPoint &theXYPoint) const\n{\n  try\n  {\n    double xWorld, yWorld;\n\n    // Transform local xy-coordinates into world xy-coordinates (meters).\n\n    xWorld = itsWorldRect.Left() + (theXYPoint.X() - Left()) / itsXScaleFactor;\n    yWorld = itsWorldRect.Bottom() - (theXYPoint.Y() - Top()) / itsYScaleFactor;\n\n    // Transform world xy-coordinates into geodetic coordinates.\n\n    return WorldXYToLatLon(NFmiPoint(xWorld, yWorld));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Returns the world XY coordinates corresponding the\n * rectangular LOCAL point theXYPoint.\n *\n * \\param theXYPoint The local xy-coordinates to be converted\n * \\return The respective world coordinates\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiAzimuthalArea::XYToWorldXY(const NFmiPoint &theXYPoint) const\n{\n  try\n  {\n    double xWorld = itsWorldRect.Left() + (theXYPoint.X() - Left()) / itsXScaleFactor;\n    double yWorld = itsWorldRect.Bottom() - (theXYPoint.Y() - Top()) / itsYScaleFactor;\n\n    return NFmiPoint(xWorld, yWorld);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Returns the XY coordinates corresponding the\n * rectangular LOCAL point theWorldXYPoint.\n *\n * \\param theWorldXYPoint The local world xy-coordinates to be converted\n * \\return The respective XY coordinates\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiAzimuthalArea::WorldXYToXY(const NFmiPoint &theWorldXYPoint) const\n{\n  try\n  {\n    double x = itsXScaleFactor * (theWorldXYPoint.X() - itsWorldRect.Left()) + Left();\n    double y = Top() - itsYScaleFactor * (theWorldXYPoint.Y() - itsWorldRect.Bottom());\n    return NFmiPoint(x, y);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Transforms input world xy-coordinates into geodetic coordinates\n * (longitude,latitude) on globe. This proceeds in two steps:\n *\n *  -# transform world xy-coordinates into tangential world xy coordinates\n *  -# transform tangential world xy-coordinates into geodetic coordinates\n *\n * Some basic projection concepts:\n *\n *  - POLAR or NORMAL CASE means the central latitude is 90 degrees North,\n *    that is the North Pole\n *  - TANGENTIAL CASE means the true latitude is 90 degrees North,\n *    otherwise we talk about NON-TANGENTIAL or SECANT CASE\n *\n * \\note\n * Applying non-polar case (central latitude other than 90 degrees North)\n * is possible but not tested in this program. Applying both non-tangential\n * projection plane -AND- non-polar case together is NOT ALLOWED in this program!\n * FMI defaults to following values: central latitude 90 deg North,\n * true latitude 60 deg North.\n *\n * \\param theXYPoint The world xy-coordinates to be converted\n * \\return The geodetic coordinates.\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiAzimuthalArea::WorldXYToLatLon(const NFmiPoint &theXYPoint) const\n{\n  try\n  {\n    double lat0, lat, dlon, sinlat0, coslat0, coslat, delta;\n    double sinDelta, cosDelta, B, cosB, xWorld, yWorld, xWorldTangential, yWorldTangential, xyDist;\n    double dlonDeg, lonDeg, latDeg, trueLat, centralLat, centralLon;\n\n    trueLat = itsTrueLatitude.Value();\n    centralLat = itsCentralLatitude.Value();\n    centralLon = itsCentralLongitude.Value();\n\n    // See the second NOTE above\n    if ((trueLat != 90.) && (centralLat != 90.))\n      return NFmiPoint(kFloatMissing, kFloatMissing);\n\n    // ----------------------------------------------------------------------------------------\n    // STEP 1.\n    // Transform world xy-coordinates (defined by itsTrueLatitude) onto the tangential xy-plane\n    // ----------------------------------------------------------------------------------------\n\n    DistanceFromPerspectivePointToCenterOfEarth();\n\n    xWorld = theXYPoint.X();\n    yWorld = theXYPoint.Y();\n\n    xWorldTangential = 0.0;\n    yWorldTangential = 0.0;\n\n    if (trueLat == 90.)\n    {\n      // TANGENTIAL case\n\n      xWorldTangential = xWorld;\n      yWorldTangential = yWorld;\n    }\n    else\n    {\n      // NON-TANGENTIAL \"secant\" case\n\n      // (D + kRearth)*xWorld/(D + kRearth*itsTrueLatitude.Sin());\n      if (xWorld != 0.0)\n        xWorldTangential = xWorld / itsTrueLatScaleFactor;\n\n      // (D + kRearth)*yWorld/(D + kRearth*itsTrueLatitude.Sin());\n      if (yWorld != 0.0)\n        yWorldTangential = yWorld / itsTrueLatScaleFactor;\n    }\n\n    // ----------------------------------------------------------------------\n    // STEP 2.\n    // Transform tangential xy world coordinates into geodetic coordinates\n    // ----------------------------------------------------------------------\n\n    // XY distance measured between current point and the map center\n    xyDist = sqrt(xWorldTangential * xWorldTangential + yWorldTangential * yWorldTangential);\n\n    lat0 = FmiRad(centralLat);  // = Reference latitude = central latitude\n\n    if (xyDist == 0.0)\n      return NFmiPoint(centralLon, lat0);\n\n    // Delta angle for the tangential plane depends on the tangential XY distance\n    delta = CalcDelta(xyDist);\n\n    if (centralLat == 90.)\n    {\n      // POLAR (=NORMAL) case\n\n      // Compute absolute latitude\n\n      // Fakta: lat = asin(cosdelta) = FmiRad(90) - delta\n      lat = FmiRad(90) - delta;  // = asin(cosDelta);\n      latDeg = FmiDeg(lat);\n\n      // Compute longitude difference relative to central longitude\n\n      if (yWorldTangential == 0.)\n        dlonDeg = Sign(xWorldTangential) * 90.;\n      else\n      {\n        // Fakta: dlon = asin((sinDelta*cosB)/cos(lat)) = atan(xWorldTangential/yWorldTangential)\n\n        Sign(yWorldTangential) < 0\n            ? dlonDeg =\n                  Sign(xWorldTangential) * FmiDeg(atan(fabs(xWorldTangential / yWorldTangential)))\n            : dlonDeg = Sign(xWorldTangential) *\n                        (FmiDeg(atan(fabs(yWorldTangential / xWorldTangential))) + 90.);\n      }\n\n      lonDeg = NFmiLongitude(centralLon + dlonDeg, PacificView()).Value();\n    }\n    else\n    {\n      // HUOM! HUOM! Tätä \"ei-polaaria\" tapausta ei ole testattu!\n\n      // NON-POLAR case\n\n      // Azimuthal angle for the XY point ON THE TANGENTIAL MAP PLANE\n      B = asin(yWorldTangential / xyDist);\n      cosB = cos(B);\n\n      sinlat0 = sin(lat0);\n      coslat0 = cos(lat0);\n      cosDelta = cos(delta);\n      sinDelta = sin(delta);\n\n      // Compute absolute latitude\n      lat = asin(coslat0 * sinDelta * sin(B) + sinlat0 * cosDelta);\n      coslat = cos(lat);\n      latDeg = FmiDeg(lat);\n\n      // Compute longitude difference relative to CentralLongitude\n      dlon = asin((sinDelta * cosB) / coslat);\n      dlonDeg = FmiDeg(dlon);\n\n      // Quadrant check\n      // VOI OLLA ETTEI TÄMÄ TARKASTELU OLE RIITTÄVÄ!\n      if (xWorld > 0.0)\n        lonDeg = NFmiLongitude(centralLon + dlonDeg, PacificView()).Value();\n      else\n        lonDeg = NFmiLongitude(centralLon - dlonDeg, PacificView()).Value();\n    }\n\n    return NFmiPoint(lonDeg, latDeg);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Transforms input geodetic coordinates (longitude,latitude) into world coordinates\n * (meters) on xy-plane cutting the Earth globe. This proceeds in two steps:\n *\n *  -# transform geodetic coordinates into TANGENTIAL world xy-coordinates\n *  -# transform tangential world xy-coordinates into final world xy coordinates\n *\n *\n * Some basic projection concepts:\n *\n *  - POLAR or NORMAL CASE means the central latitude is 90 degrees North, that\n *    is the North Pole\n *  - TANGENTIAL CASE means the true latitude is 90 degrees North, otherwise we talk\n *    about NON-TANGENTIAL or SECANT CASE\n *\n * \\note\n * Aapplying non-polar case (central latitude other than 90 degrees North) is possible\n * but not tested in this program. Applying both non-tangential projection plane\n * -AND- non-polar case together is NOT ALLOWED in this program!\n *  FMI defaults to following values: central latitude 90 deg North, true\n * latitude 60 deg North.\n *\n * \\param theLatLonPoint The geodetic coordinates to be converted\n * \\return the world xy-coordinates\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiAzimuthalArea::LatLonToWorldXY(const NFmiPoint &theLatLonPoint) const\n{\n  try\n  {\n    double k, lat0, lat, dlon, sinlat0, sinlat, coslat0, coslat, delta;\n    double xWorldTangential, yWorldTangential;\n    double xWorld, yWorld, trueLat, centralLat, centralLon;\n\n    trueLat = itsTrueLatitude.Value();\n    centralLat = itsCentralLatitude.Value();\n    centralLon = itsCentralLongitude.Value();\n\n    if ((trueLat != 90.) && (centralLat != 90.))\n    {\n      // Jos tullaan t�h�n, projektion parametrit eiv�t ole sallittuja, muuta centralLat arvoon\n      // 90!!!!!!!\n      assert(!((trueLat != 90.) && (centralLat != 90.)));\n      return NFmiPoint::gMissingLatlon;\n    }\n\n    lat0 = FmiRad(centralLat);\n    lat = FmiRad(theLatLonPoint.Y());\n    dlon = FmiRad(theLatLonPoint.X() - centralLon);\n    sinlat = sin(lat);\n    coslat = cos(lat);\n\n    DistanceFromPerspectivePointToCenterOfEarth();\n\n    // ----------------------------------------------------------------------\n    // STEP 1.\n    // Transform geodetic coordinates into world coordinates on a xy-plane tangential to\n    // the surface of Earth globe.\n    // ----------------------------------------------------------------------\n\n    if (centralLat == 90.)\n    {\n      // Polar (=normal) case, that is, lat0 = FmiRad(90 deg).\n      // NOTE! This polar case COULD be computed just the way non-polar case is computed\n      // by just assigning lat0 = FmiRad(90).\n      // Howewer, since sin(lat0) == 1 and cos(lat0) == 0,\n      // this is the reduced and somewhat faster way of computing the normal case:\n\n      delta = sinlat;\n      k = K(delta);\n      if (k == kFloatMissing)\n        return NFmiPoint::gMissingLatlon;\n\n      // Fakta:  k*coslat*sin(dlon) = 2*kRearth*tan(0.5*(kPii/2 - lat))*sin(dlon)\n      xWorldTangential = k * coslat * sin(dlon);\n      // Fakta:  k*(-coslat*cos(dlon)) = -2*kRearth*tan(0.5*(kPii/2 - lat))*cos(dlon)\n      yWorldTangential = k * (-coslat * cos(dlon));\n    }\n    else\n    {\n      // Non-polar case\n\n      sinlat0 = sin(lat0);\n      coslat0 = cos(lat0);\n\n      delta = sinlat0 * sinlat + coslat0 * coslat * cos(dlon);\n      k = K(delta);\n      if (k == kFloatMissing)\n        return NFmiPoint::gMissingLatlon;\n\n      xWorldTangential = k * coslat * sin(dlon);\n      yWorldTangential = k * (coslat0 * sinlat - sinlat0 * coslat * cos(dlon));\n    }\n\n    // ----------------------------------------------------------------------\n    // STEP 2.\n    // Transform tangential world xy-coordinates onto the xy-plane cutting Earth\n    // globe. This cutting xy-plane is parallel to tangential xy-plane and is\n    // defined by itsTrueLatitude\n    // ----------------------------------------------------------------------\n\n    xWorld = 0.0;\n    yWorld = 0.0;\n\n    if (trueLat == 90.)\n    {\n      // Cutting plane is already tangential to north pole - nothing to do.\n      if (xWorldTangential != 0.0)\n        xWorld = xWorldTangential;\n\n      if (yWorldTangential != 0.0)\n        yWorld = yWorldTangential;\n    }\n    else\n    {\n      // xWorldTangential*(D + kRearth*itsTrueLatitude.Sin())/(D + kRearth)\n      if (xWorldTangential != 0.0)\n        xWorld = xWorldTangential * itsTrueLatScaleFactor;\n\n      // yWorldTangential*(D + kRearth*itsTrueLatitude.Sin())/(D + kRearth)\n      if (yWorldTangential != 0.0)\n        yWorld = yWorldTangential * itsTrueLatScaleFactor;\n    }\n\n    return NFmiPoint(xWorld, yWorld);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Transforms input geodetic coordinates (longitude,latitude) into local\n * (relative) coordinates on xy-plane.\n *\n * \\param theLatLonPoint The geodetic coordinates to be converted.\n * \\return The converted local xy-coordinates\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiAzimuthalArea::ToXY(const NFmiPoint &theLatLonPoint) const\n{\n  try\n  {\n    double xLocal, yLocal;\n\n    // Transform input geodetic coordinates into world coordinates (meters) on xy-plane.\n    NFmiPoint latlon(FixLongitude(theLatLonPoint.X()), theLatLonPoint.Y());\n    NFmiPoint xyWorld(LatLonToWorldXY(latlon));\n\n    if (xyWorld == NFmiPoint::gMissingLatlon)\n      return xyWorld;\n\n    // Finally, transform world xy-coordinates into local xy-coordinates\n    xLocal = Left() + itsXScaleFactor * (xyWorld.X() - itsWorldRect.Left());\n    yLocal = Top() + itsYScaleFactor * (itsWorldRect.Bottom() - xyWorld.Y());\n\n    return NFmiPoint(xLocal, yLocal);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Turns the input azimuth angle (in degrees) and radius (in meters)\n * into corresponding RELATIVE XY coordinates.\n *\n * \\param theAzimuth The azimuth angle in degrees\n * \\param theRadius The radius in meters\n * \\return The respective relative xy-coordinates.\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiAzimuthalArea::RadialXYPoint(double theAzimuth, double theRadius) const\n{\n  try\n  {\n    double startAngle;\n    double radianAngle;\n\n    // Start angle defaults to 0 deg. = North\n    startAngle = 0.5 * kPii;\n\n    radianAngle = startAngle - kPii * theAzimuth / 180.;\n\n    return NFmiPoint(theRadius * cos(radianAngle), theRadius * sin(radianAngle));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Transforms input azimuth angle and radius into world coordinates on xy-plane.\n *\n * \\param theAzimuth The azimuth angle\n * \\param theRadius The radius\n * \\return The respective world coordinates\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiAzimuthalArea::LatLonToWorldXY(double theAzimuth, double theRadius) const\n{\n  try\n  {\n    return RadialXYPoint(theAzimuth, theRadius);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Transforms input azimuth angle and radius from world coordinates into\n * local (relative) coordinates on xy-plane.\n *\n * \\param theAzimuth The azimuth angle\n * \\param theRadius The radius\n * \\return The respective local relative xy-coordinates\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiAzimuthalArea::ToXY(double theAzimuth, double theRadius) const\n{\n  try\n  {\n    double xLocal, yLocal;\n\n    // First, transform azimuth and radius into world coordinates (meters) on xy-plane.\n    NFmiPoint xyWorld(LatLonToWorldXY(theAzimuth, theRadius));\n\n    // Finally, transform world xy-coordinates into local xy-coordinates\n    xLocal = Left() + itsXScaleFactor * (xyWorld.X() - itsWorldRect.Left());\n    yLocal = Top() + itsYScaleFactor * (itsWorldRect.Bottom() - xyWorld.Y());\n\n    return NFmiPoint(xLocal, yLocal);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Transforms input azimuth angle (in degrees) and radius (in meters)\n * from world coordinates into geodetic (latitude-longitude) coordinates.\n *\n * \\param theAzimuth The azimuth angle in degrees\n * \\param theRadius The radius in meters\n * \\return The respective geodetic coordinates\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiAzimuthalArea::ToLatLon(double theAzimuth, double theRadius) const\n{\n  try\n  {\n    return WorldXYToLatLon(RadialXYPoint(theAzimuth, theRadius));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n *  Returns the geodetic center point\n *\n * \\return The geodetic center point\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiAzimuthalArea::CurrentCenter() const\n{\n  try\n  {\n    return NFmiPoint(itsCentralLongitude.Value(), itsCentralLatitude.Value());\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Assignment operator\n *\n * \\param theArea The other area being copied\n * \\return Referencee to the assigned value.\n * \\todo Should protect from self assignment, since NFmiArea::operator=\n *       cannot be trusted here.\n */\n// ----------------------------------------------------------------------\n\nNFmiAzimuthalArea &NFmiAzimuthalArea::operator=(const NFmiAzimuthalArea &theArea)\n{\n  try\n  {\n    NFmiArea::operator=(theArea);\n\n    itsBottomLeftLatLon = theArea.itsBottomLeftLatLon;\n    itsTopRightLatLon = theArea.itsTopRightLatLon;\n    itsCentralLongitude.SetValue(theArea.itsCentralLongitude.Value());\n    itsCentralLatitude.SetValue(theArea.itsCentralLatitude.Value());\n    itsTrueLatitude.SetValue(theArea.itsTrueLatitude.Value());\n    itsXScaleFactor = theArea.itsXScaleFactor;\n    itsYScaleFactor = theArea.itsYScaleFactor;\n    itsBottomLeftWorldXY = theArea.itsBottomLeftWorldXY;\n    itsWorldRect = theArea.itsWorldRect;\n    itsRadialRange = theArea.itsRadialRange;\n    itsTrueLatScaleFactor = theArea.itsTrueLatScaleFactor;\n\n    return *this;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Equality comparison\n *\n * \\param theArea The other area being compared to\n * \\return True, if the areas are equivalent\n * \\todo Investigate whether NFmiArea::operator== should also be called.\n */\n// ----------------------------------------------------------------------\n\nbool NFmiAzimuthalArea::operator==(const NFmiAzimuthalArea &theArea) const\n{\n  try\n  {\n    if ((itsBottomLeftLatLon == theArea.itsBottomLeftLatLon) &&\n        (itsTopRightLatLon == theArea.itsTopRightLatLon) &&\n        (itsCentralLongitude.Value() == theArea.itsCentralLongitude.Value()) &&\n        (itsCentralLatitude.Value() == theArea.itsCentralLatitude.Value()) &&\n        (itsTrueLatitude.Value() == theArea.itsTrueLatitude.Value()) &&\n        (itsXScaleFactor == theArea.itsXScaleFactor) &&\n        (itsYScaleFactor == theArea.itsYScaleFactor) &&\n        (itsBottomLeftWorldXY == theArea.itsBottomLeftWorldXY) &&\n        (itsWorldRect == theArea.itsWorldRect) && (itsRadialRange == theArea.itsRadialRange))\n      return true;\n\n    return false;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Inequality comparison\n *\n * \\param theArea The other area being compared to\n * \\return True, if the areas are not equivalent\n */\n// ----------------------------------------------------------------------\n\nbool NFmiAzimuthalArea::operator!=(const NFmiAzimuthalArea &theArea) const\n{\n  try\n  {\n    return (!(*this == theArea));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Equality comparison with an area derived from NFmiAzimuthalArea.\n *\n * \\param theArea The other area being compared to\n * \\return True, if the NFmiAzimuthalArea parts are equivalent\n * \\todo Use static_cast instead of C-style cast\n */\n// ----------------------------------------------------------------------\n\nbool NFmiAzimuthalArea::operator==(const NFmiArea &theArea) const\n{\n  try\n  {\n    return *this == static_cast<const NFmiAzimuthalArea &>(theArea);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Inequality comparison with an area derived from NFmiAzimuthalArea.\n *\n * \\param theArea The other area being compared to\n * \\return True, if the NFmiAzimuthalArea parts are not equivalent\n */\n// ----------------------------------------------------------------------\n\nbool NFmiAzimuthalArea::operator!=(const NFmiArea &theArea) const\n{\n  try\n  {\n    return !(*this == theArea);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Write the projection to the given stream\n *\n * \\param file The output stream to write to.\n * \\return The output stream written to.\n */\n// ----------------------------------------------------------------------\n\nstd::ostream &NFmiAzimuthalArea::Write(std::ostream &file) const\n{\n  try\n  {\n    NFmiArea::Write(file);\n\n    file << itsBottomLeftLatLon << itsTopRightLatLon << itsCentralLongitude.Value() << endl\n         << itsCentralLatitude.Value() << endl\n         << itsTrueLatitude.Value() << endl;\n    int oldPrec = file.precision();\n    file.precision(15);\n\n    // We trust everything to be at least version 6 by now\n    if (DefaultFmiInfoVersion >= 5)\n    {\n      file << itsRadialRange << \" 0\"\n           << \" 0\" << endl;\n      file << itsWorldRect << ' ';\n    }\n    else\n      file << itsWorldRect << endl;\n\n    file.precision(oldPrec);\n\n    return file;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Replace the projection with the one in the given input stream.\n *\n * \\param file The input stream to read from\n * \\return The input stream read from\n */\n// ----------------------------------------------------------------------\n\nstd::istream &NFmiAzimuthalArea::Read(std::istream &file)\n{\n  try\n  {\n    double centralLatitude, trueLatitude, centralLongitude;\n\n    NFmiArea::Read(file);\n\n    file >> itsBottomLeftLatLon;\n    file >> itsTopRightLatLon;\n    PacificView(NFmiArea::IsPacificView(itsBottomLeftLatLon, itsTopRightLatLon));\n    file >> centralLongitude;\n    file >> centralLatitude;\n    file >> trueLatitude;\n    // We trust everything to be at least version 6 by now\n    if (DefaultFmiInfoVersion >= 5)\n    {\n      unsigned long dummy;\n      file >> itsRadialRange >> dummy >> dummy;\n    }\n\n    itsCentralLongitude.SetValue(centralLongitude);\n    itsCentralLatitude.SetValue(centralLatitude);\n    itsTrueLatitude.SetValue(trueLatitude);\n\n    file >> itsWorldRect;\n\n    Init();\n\n    return file;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Hash value\n */\n// ----------------------------------------------------------------------\n\nstd::size_t NFmiAzimuthalArea::HashValue() const\n{\n  try\n  {\n    std::size_t hash = NFmiArea::HashValue();\n    boost::hash_combine(hash, itsTopRightLatLon.HashValue());\n    boost::hash_combine(hash, itsBottomLeftLatLon.HashValue());\n    boost::hash_combine(hash, itsBottomLeftWorldXY.HashValue());\n    boost::hash_combine(hash, boost::hash_value(itsXScaleFactor));\n    boost::hash_combine(hash, boost::hash_value(itsYScaleFactor));\n    boost::hash_combine(hash, itsWorldRect.HashValue());\n    boost::hash_combine(hash, boost::hash_value(itsRadialRange));\n    boost::hash_combine(hash, itsCentralLongitude.HashValue());\n    boost::hash_combine(hash, itsCentralLatitude.HashValue());\n    boost::hash_combine(hash, itsTrueLatitude.HashValue());\n    boost::hash_combine(hash, boost::hash_value(itsTrueLatScaleFactor));\n\n    return hash;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ======================================================================\n", "meta": {"hexsha": "c86839edf8ee04e30bd1e75d3a470accd31e17db", "size": 36088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "newbase/NFmiAzimuthalArea.cpp", "max_stars_repo_name": "fmidev/smartmet-library-newbase", "max_stars_repo_head_hexsha": "12d93660c06e3c66a039ea75530bd9ca5daf7ab8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "newbase/NFmiAzimuthalArea.cpp", "max_issues_repo_name": "fmidev/smartmet-library-newbase", "max_issues_repo_head_hexsha": "12d93660c06e3c66a039ea75530bd9ca5daf7ab8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-01-17T10:46:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-21T07:50:17.000Z", "max_forks_repo_path": "newbase/NFmiAzimuthalArea.cpp", "max_forks_repo_name": "fmidev/smartmet-library-newbase", "max_forks_repo_head_hexsha": "12d93660c06e3c66a039ea75530bd9ca5daf7ab8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-01-17T07:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-26T07:10:23.000Z", "avg_line_length": 33.1691176471, "max_line_length": 99, "alphanum_fraction": 0.5921913101, "num_tokens": 8291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.42184194908213896}}
{"text": "//==================================================================================================\n/**\n  Copyright 201 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ERF_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_ERF_HPP_INCLUDED\n\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/sign.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/arch/common/detail/generic/erf_kernel.hpp>\n\n#ifndef BOOST_SIMD_NO_INVALIDS\n#include <boost/simd/function/is_nan.hpp>\n#endif\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/function/is_inf.hpp>\n#include <boost/simd/function/signnz.hpp>\n#endif\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( erf_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::double_<A0> >\n                          )\n  {\n    inline A0 operator() (A0 x) const\n    {\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if(is_nan(x)) return x;\n      #endif\n      A0 y =  bs::abs(x);\n      if (y <= Ratio<A0, 15, 32>()) // 0.46875\n      {\n        return detail::erf_kernel1<A0>::erf1(x, y);\n      }\n      else if (y <= 4)\n      {\n        A0 res = detail::erf_kernel1<A0>::erf2(x, y);\n        res =    detail::erf_kernel1<A0>::finalize2(res, y);\n        res = (Half<A0>() - res) + Half<A0>();\n        if (is_ltz(x)) res = -res;\n        return res;\n      }\n      else if  (y <= 26.543)\n      {\n        A0 res = detail::erf_kernel1<A0>::erf3(x, y);\n        res =    detail::erf_kernel1<A0>::finalize2(res, y);\n        res = (Half<A0>() - res) + Half<A0>();\n        if (is_ltz(x)) res = -res;\n        return res;\n      }\n      else return sign(x);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( erf_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::single_<A0> >\n                          )\n  {\n    inline A0 operator()(A0 a0) const\n    {\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if(is_nan(a0)) return a0;\n      #endif\n\n      #ifndef BOOST_SIMD_NO_INFINITIES\n      if (bs::is_inf(a0)) return signnz(a0);\n      #endif\n\n      A0 x =  bs::abs(a0);\n      if (x < Ratio<A0, 2, 3>())\n      {\n        return a0*detail::erf_kernel<A0>::erf1(sqr(x));\n      }\n      else\n      {\n        A0 z = x/inc(x)-Ratio<A0, 2, 5>();\n        A0 r2 =   oneminus(exp(-sqr(x))*detail::erf_kernel<A0>::erfc2(z));\n        if (is_ltz(a0)) r2 = -r2;\n        return r2;\n      }\n   }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( erf_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const std_tag &, A0 a0) const BOOST_NOEXCEPT\n    {\n      return std::erf(a0);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "3e8241eb5da4257370cfad98cc62338ef96c2c89", "size": 3620, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/erf.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/scalar/function/erf.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/scalar/function/erf.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 29.6721311475, "max_line_length": 100, "alphanum_fraction": 0.5309392265, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4218419490821389}}
{"text": "#include <gentl/inference/mcmc.h>\n#include <gentl/util/randutils.h>\n#include <gentl/types.h>\n\n#include <utility>\n#include <vector>\n#include <stdexcept>\n#include <memory>\n#include <array>\n#include <iostream>\n\n#include <Eigen/Dense>\n\n\n// TODO support parameters\n// TODO support subset of addresses\n\nusing gentl::SimulateOptions;\nusing gentl::GenerateOptions;\nusing gentl::UpdateOptions;\n\n// ****************************\n// *** Model implementation ***\n// ****************************\n\nconstexpr size_t latent_dimension = 2;\ntypedef Eigen::Vector<double,latent_dimension> mean_t;\ntypedef Eigen::Matrix<double,latent_dimension,latent_dimension> cov_t;\n\n// Selection types\n\nclass LatentsSelection {};\n\n// Choice buffer types\n\nclass EmptyChoiceBuffer {};\n\ntypedef Eigen::Array<double,latent_dimension,1> latent_choices_t;\n\n// model change types\n\nstruct ModelChange {\n    mean_t new_mean;\n    cov_t new_cov;\n};\n\n// return value change types\n\nclass RetvalChange {};\n\n// learnable parameters\n\nclass Parameters { };\nclass GradientAccumulator { };\n\n\n\nclass Trace;\n\nclass Model {\n    typedef int return_type;\n    friend class Trace;\n\nprivate:\n    typedef Eigen::LLT<Eigen::Matrix<double,latent_dimension,latent_dimension>> Chol;\n    mean_t mean_;\n    cov_t cov_;\n    cov_t precision_;\n    Chol chol_;\n\npublic:\n    template <typename RNGType>\n    void exact_sample(latent_choices_t& latents, RNGType& rng) const {\n        static std::normal_distribution<double> standard_normal_dist(0.0, 1.0);\n        for (auto& x : latents)\n            x = standard_normal_dist(rng);\n        latents = (mean_ + (chol_.matrixL() * latents.matrix())).array();\n    }\n\n    [[nodiscard]] double logpdf(const latent_choices_t& latents) const {\n        static double logSqrt2Pi = 0.5*std::log(2*M_PI);\n        double quadform = chol_.matrixL().solve(latents.matrix() - mean_).squaredNorm();\n        return std::exp(-static_cast<double>(latent_dimension)*logSqrt2Pi - 0.5*quadform) / chol_.matrixL().determinant();\n    }\n\n    template <typename RNGType>\n    [[nodiscard]] std::pair<double,double> importance_sample(latent_choices_t& latents, RNGType& rng) const {\n        exact_sample(latents, rng);\n        double log_weight = 0.0;\n        return {logpdf(latents), log_weight};\n    }\n\n    void logpdf_grad(latent_choices_t& latent_gradient, const latent_choices_t& latents) const {\n        // gradient wrt value x is -x\n        latent_gradient = (-precision_ * (latents.matrix() - mean_)).array();\n    }\n\n\npublic:\n    Model(mean_t mean, cov_t cov) :\n            mean_{std::move(mean)}, cov_{std::move(cov)}, chol_{cov}, precision_{cov.inverse()} {\n        if (chol_.info() != Eigen::Success)\n            throw std::logic_error(\"decomposition failed!\");\n    }\n\n    // simulate into a new trace object\n    template <typename RNGType>\n    std::unique_ptr<Trace> simulate(RNGType& rng, Parameters& parameters, const SimulateOptions&) const;\n\n    // simulate into an existing trace object (overwriting existing contents)\n    template <typename RNGType>\n    void simulate(RNGType& rng, Parameters& parameters, const SimulateOptions&, Trace& trace) const;\n\n    // generate into a new trace object\n    template <typename RNGType>\n    std::pair<std::unique_ptr<Trace>,double> generate(const EmptyChoiceBuffer& constraints, RNGType& rng,\n                                                      Parameters& parameters, const GenerateOptions&) const;\n\n    // generate into an existing trace object (overwriting existing contents)\n    template <typename RNGType>\n    double generate(Trace& trace, const EmptyChoiceBuffer& constraints,\n                    RNGType& rng, Parameters& parameters, const GenerateOptions&) const;\n\n    // equivalent to generate but without returning a trace\n\n    template <typename RNG>\n    std::pair<int, double> assess(RNG&, Parameters&, const latent_choices_t& constraints) const;\n\n    template <typename RNG>\n    std::pair<int, double> assess(RNG&, Parameters&, const EmptyChoiceBuffer& constraints) const;\n\n};\n\nclass Trace {\n    friend class Model;\nprivate:\n    Model model_;\n    double score_;\n    latent_choices_t latents_;\n    latent_choices_t alternate_latents_;\n    latent_choices_t latent_gradient_;\n    bool can_be_reverted_;\n    bool gradients_computed_;\n    RetvalChange diff_;\nprivate:\n    // initialize trace without precomputed gradient\n    Trace(Model model, double score, latent_choices_t&& latents) :\n        model_{std::move(model)}, score_{score}, latents_{latents},\n        can_be_reverted_{false}, gradients_computed_{false} {}\n    // initialize trace with gradient precomputed\n    Trace(Model model, double score, latent_choices_t&& latents, latent_choices_t&& latent_gradient) :\n    model_{std::move(model)}, score_{score}, latents_{latents}, latent_gradient_{latent_gradient},\n        can_be_reverted_{false}, gradients_computed_{true} {}\npublic:\n    Trace() = delete;\n    Trace(const Trace& other) = delete;\n    Trace(Trace&& other) = delete;\n    Trace& operator=(const Trace& other) = delete;\n    Trace& operator=(Trace&& other) noexcept = delete;\n\n    [[nodiscard]] double score() const;\n    [[nodiscard]] const latent_choices_t& choices() const;\n    [[nodiscard]] const latent_choices_t& choices(const LatentsSelection& selection) const;\n    const latent_choices_t& choice_gradient(const LatentsSelection& selection);\n    template <typename RNG>\n    double update(RNG&, const gentl::change::NoChange&, const latent_choices_t& constraints, const UpdateOptions& options);\n    const latent_choices_t& backward_constraints();\n\n    void revert();\n};\n\n\n// ****************************\n// *** Model implementation ***\n// ****************************\n\ntemplate <typename RNGType>\nstd::unique_ptr<Trace> Model::simulate(RNGType& rng, Parameters& parameters, const SimulateOptions& options) const {\n    latent_choices_t latents;\n    exact_sample(latents, rng);\n    auto log_density = logpdf(latents);\n    if (options.precompute_gradient()) {\n        latent_choices_t latent_gradient;\n        logpdf_grad(latent_gradient, latents);\n        // note: this copies the model\n        return std::unique_ptr<Trace>(new Trace(*this, log_density, std::move(latents), std::move(latent_gradient)));\n    } else {\n        // note: this copies the model\n        return std::unique_ptr<Trace>(new Trace(*this, log_density, std::move(latents)));\n    }\n}\n\ntemplate <typename RNGType>\nvoid Model::simulate(RNGType& rng, Parameters& parameters, const SimulateOptions& options, Trace& trace) const {\n    exact_sample(trace.latents_, rng);\n    trace.score_ = logpdf(trace.latents_);\n    if (options.precompute_gradient()) {\n        logpdf_grad(trace.latent_gradient_, trace.latents_);\n    }\n    trace.gradients_computed_ = options.precompute_gradient();\n    trace.can_be_reverted_ = false;\n}\n\ntemplate <typename RNGType>\nstd::pair<std::unique_ptr<Trace>,double> Model::generate(const EmptyChoiceBuffer& constraints, RNGType& rng,\n                                                         Parameters& parameters, const GenerateOptions& options) const {\n    latent_choices_t latents;\n    auto [log_density, log_weight] = importance_sample(latents, rng);\n    std::unique_ptr<Trace> trace = nullptr;\n    if (options.precompute_gradient()) {\n        latent_choices_t latent_gradient;\n        logpdf_grad(latent_gradient, latents);\n        trace = std::unique_ptr<Trace>(new Trace(*this, log_density, std::move(latents), std::move(latent_gradient)));\n    } else {\n        trace = std::unique_ptr<Trace>(new Trace(*this, log_density, std::move(latents)));\n    }\n    return {std::move(trace), log_weight};\n}\n\ntemplate <typename RNGType>\ndouble Model::generate(Trace& trace, const EmptyChoiceBuffer& constraints, RNGType& rng, Parameters& parameters,\n                       const GenerateOptions& options) const {\n    trace.model_ = *this;\n    auto [log_density, log_weight] = importance_sample(trace.latents_, rng);\n    trace.score_ = log_density;\n    double score = logpdf(trace.latents_);\n    if (options.precompute_gradient()) {\n        logpdf_grad(trace.latent_gradient_, trace.latents_);\n    }\n    trace.gradients_computed_ = options.precompute_gradient();\n    trace.can_be_reverted_ = false;\n    return log_weight;\n}\n\ntemplate <typename RNG>\nstd::pair<int, double> Model::assess(RNG&, Parameters& parameters, const latent_choices_t& constraints) const {\n    return {-1, logpdf(constraints)};\n}\n\ntemplate <typename RNG>\nstd::pair<int, double> Model::assess(RNG&, Parameters& parameters, const EmptyChoiceBuffer& constraints) const {\n    return {-1, 0.0};\n}\n\n// ****************************\n// *** Trace implementation ***\n// ****************************\n\ndouble Trace::score() const {\n    return score_;\n}\n\nconst latent_choices_t& Trace::choices(const LatentsSelection& selection) const {\n    return latents_;\n}\n\nconst latent_choices_t& Trace::choices() const {\n    return latents_;\n}\n\nvoid Trace::revert() {\n    if (!can_be_reverted_)\n        throw std::logic_error(\"log_weight is only available between calls to update and revert\");\n    can_be_reverted_ = false;\n    std::swap(latents_, alternate_latents_);\n    gradients_computed_ = false;\n}\n\n\nconst latent_choices_t& Trace::backward_constraints() {\n    return alternate_latents_;\n}\n\nconst latent_choices_t& Trace::choice_gradient(const LatentsSelection& selection) {\n    if (!gradients_computed_) {\n        model_.logpdf_grad(latent_gradient_, latents_);\n    }\n    gradients_computed_ = true;\n    return  latent_gradient_;\n}\n\ntemplate <typename RNG>\ndouble Trace::update(RNG&, const gentl::change::NoChange&, const latent_choices_t& latents, const UpdateOptions& options) {\n    if (options.save()) {\n        std::swap(latents_, alternate_latents_);\n        latents_ = latents; // copy assignment\n        can_be_reverted_ = true;\n    } else {\n        latents_ = latents; // copy assignment\n        // can_be_reverted_ keeps its previous value\n    };\n    double new_log_density = model_.logpdf(latents_);\n    double log_weight = new_log_density - score_;\n    score_ = new_log_density;\n    if (options.precompute_gradient()) {\n        model_.logpdf_grad(latent_gradient_, latents_);\n    }\n    gradients_computed_ = options.precompute_gradient();\n    return log_weight;\n}\n\n// TODO add implementation of update that accepts a change to the model\n\n\n// *********************\n// *** Example usage ***\n// *********************\n\n\nint main(int argc, char* argv[]) {\n    using std::cout;\n    using std::endl;\n    using std::cerr;\n\n    // TODO test multiple threads\n\n    // parse arguments\n\n    static const std::string usage = \"Usage: ./mcmc\"\n                                     \"<hmc_cycles_per_iter>\"\n                                     \"<mala_cycles_per_iter>\"\n                                     \"<mh_cycles_per_iter>\"\n                                     \"<hmc_leapfrog_steps>\"\n                                     \"<hmc_eps>\"\n                                     \"<mala_tau>\"\n                                     \"<num_threads>\"\n                                     \"<num_iters>\"\n                                     \"<seed>\";\n    if (argc != 10) {\n        throw std::invalid_argument(usage);\n    }\n    size_t hmc_cycles_per_iter;\n    size_t mala_cycles_per_iter;\n    size_t mh_cycles_per_iter;\n    size_t hmc_leapfrog_steps;\n    double hmc_eps;\n    double mala_tau;\n    size_t num_threads;\n    size_t num_iters;\n    uint32_t seed;\n    try {\n        hmc_cycles_per_iter = std::atoi(argv[1]);\n        mala_cycles_per_iter = std::atoi(argv[2]);\n        mh_cycles_per_iter = std::atoi(argv[3]);\n        hmc_leapfrog_steps = std::atoi(argv[4]);\n        hmc_eps = std::atof(argv[5]);\n        mala_tau = std::atof(argv[6]);\n        num_threads = std::atoi(argv[7]);\n        num_iters = std::atoi(argv[8]);\n        seed = std::atoi(argv[9]);\n    } catch (const std::invalid_argument& e) {\n        throw std::invalid_argument(usage);\n    }\n    cerr << \"hmc_cycles_per_iter: \" << hmc_cycles_per_iter << endl;\n    cerr << \"mala_cycles_per_iter: \" << mala_cycles_per_iter << endl;\n    cerr << \"mh_cycles_per_iter: \" << mh_cycles_per_iter << endl;\n    cerr << \"hmc_leapfrog_steps: \" << hmc_leapfrog_steps << endl;\n    cerr << \"hmc_eps: \" << hmc_eps << endl;\n    cerr << \"mala_tau: \" << mala_tau << endl;\n    cerr << \"num_threads: \" << num_threads << endl;\n    cerr << \"num_iters: \" << num_iters << endl;\n    cerr << \"seed: \" << seed << endl;\n\n    // initialize RNG\n\n    gentl::randutils::seed_seq_fe128 seed_seq {seed};\n    std::mt19937 rng(seed_seq);\n\n    // define the model and proposal\n    mean_t mean {0.0, 0.0};\n\n    cov_t target_covariance {{1.0, 0.95},\n                             {0.95, 1.0}};\n    Model model {mean, target_covariance};\n\n    cov_t proposal_covariance {{1.0, 0.0},\n                               {0.0, 1.0}};\n    Model proposal {mean, proposal_covariance};\n\n    auto make_proposal = [&proposal](const Trace& trace) {\n        return proposal;\n    };\n\n    // generate initial trace and choice buffers\n    Parameters unused {};\n    auto [trace, log_weight] = model.generate(EmptyChoiceBuffer{}, rng, unused, GenerateOptions().precompute_gradient(true));\n    LatentsSelection hmc_selection;\n    LatentsSelection mala_selection;\n    auto proposal_trace = make_proposal(*trace).simulate(rng, unused, SimulateOptions().precompute_gradient(false));\n\n    latent_choices_t hmc_momenta_buffer {trace->choices(hmc_selection)}; // copy constructor\n    latent_choices_t hmc_values_buffer {trace->choices(hmc_selection)}; // copy constructor\n    latent_choices_t mala_buffer_1 {trace->choices(mala_selection)}; // copy constructor\n    latent_choices_t mala_buffer_2 {trace->choices(mala_selection)}; // copy constructor\n\n    // do some MALA and HMC on the latent variables (without allocating any memory inside the loop)\n    std::vector<mean_t> history(num_iters);\n    size_t hmc_num_accepted = 0;\n    size_t mala_num_accepted = 0;\n    size_t mh_num_accepted = 0;\n    for (size_t iter = 0; iter < num_iters; iter++) {\n        history[iter] = trace->choices(LatentsSelection{}).matrix();\n        for (size_t cycle = 0; cycle < hmc_cycles_per_iter; cycle++) {\n            hmc_num_accepted += gentl::mcmc::hmc(\n                    *trace, hmc_selection, hmc_leapfrog_steps, hmc_eps,\n                    hmc_momenta_buffer, hmc_values_buffer, rng);\n        }\n        for (size_t cycle = 0; cycle < mala_cycles_per_iter; cycle++) {\n            mala_num_accepted += gentl::mcmc::mala(\n                    *trace, mala_selection, mala_tau, mala_buffer_1, mala_buffer_2, rng);\n        }\n        for (size_t cycle = 0; cycle < mh_cycles_per_iter; cycle++) {\n            mh_num_accepted += gentl::mcmc::mh(\n                    rng, *trace, make_proposal, unused, *proposal_trace, true);\n        }\n    }\n\n    cerr << \"hmc acceptance rate: \" << static_cast<double>(hmc_num_accepted) / static_cast<double>(num_iters * hmc_cycles_per_iter) << endl;\n    cerr << \"mala acceptance rate: \" << static_cast<double>(mala_num_accepted) / static_cast<double>(num_iters * mala_cycles_per_iter) << endl;\n    cerr << \"mh acceptance rate: \" << static_cast<double>(mh_num_accepted) / static_cast<double>(num_iters * mh_cycles_per_iter) << endl;\n\n    for (const auto& x : history)\n        cout << x(0) << \",\" << x(1) << endl;\n\n}\n", "meta": {"hexsha": "e72238d9664880ba9b79a7d2c2599c011bbcd648", "size": 15223, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/mcmc.cpp", "max_stars_repo_name": "OpenGen/GenTL", "max_stars_repo_head_hexsha": "ee29ac4a954d3951ae6d9ad5ae0ab8285d30d3a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-19T06:16:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T06:16:09.000Z", "max_issues_repo_path": "examples/mcmc.cpp", "max_issues_repo_name": "OpenGen/GenTL", "max_issues_repo_head_hexsha": "ee29ac4a954d3951ae6d9ad5ae0ab8285d30d3a5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/mcmc.cpp", "max_forks_repo_name": "OpenGen/GenTL", "max_forks_repo_head_hexsha": "ee29ac4a954d3951ae6d9ad5ae0ab8285d30d3a5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.734741784, "max_line_length": 143, "alphanum_fraction": 0.6568350522, "num_tokens": 3599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.421841943617461}}
{"text": "#include <boost/config.hpp>\n#include <boost/version.hpp>\n\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include <iostream>\n#include <fstream>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Polyline_simplification_2/simplify.h>\n#include <CGAL/IO/WKT.h>\n#include <list>\n#include <deque>\n\nnamespace PS = CGAL::Polyline_simplification_2;\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point_2;\ntypedef std::deque<Point_2> Polyline_2;\ntypedef PS::Stop_above_cost_threshold Stop;\ntypedef PS::Squared_distance_cost Cost;\n#endif\nint main(int argc, char* argv[])\n{\n  #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n  Polyline_2 polyline;\n  std::ifstream ifs( (argc==1)?\"data/polyline.wkt\":argv[1]);\n  CGAL::read_linestring_WKT(ifs, polyline);\n  Cost cost;\n  std::deque<Point_2> result;\n  PS::simplify(polyline.begin(), polyline.end(), cost, Stop(0.5), std::back_inserter(result));\n  \n  std::cout.precision(12);\n  for(std::size_t i=0; i < result.size(); ++i){\n    std::cout << result[i] << std::endl;\n  }\n#endif\n  return 0;\n}\n", "meta": {"hexsha": "17fdf1dfec4882c4bf21233488d9d8cc55c53c7c", "size": 1143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/Polyline_simplification_2/simplify_polyline.cpp", "max_stars_repo_name": "josuehfa/DAASystem", "max_stars_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T01:13:02.000Z", "max_issues_repo_path": "CoreSystem/lib/CGAL/examples/Polyline_simplification_2/simplify_polyline.cpp", "max_issues_repo_name": "josuehfa/DAASystem", "max_issues_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoreSystem/lib/CGAL/examples/Polyline_simplification_2/simplify_polyline.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 30.0789473684, "max_line_length": 94, "alphanum_fraction": 0.7252843395, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4217903227167157}}
{"text": "#include <iostream>\n#include <vector>\n#include <set>\n#include <iterator>\n#include <math.h>\n#include <cmath>\n#include <stdexcept>\n#include <chrono>\n#include <exception>\n#include <queue>\n#include <cstdlib>\n#include <rapidcsv.h>\n#include <boost/math/distributions/normal.hpp>\n#include <sys/time.h>\n#include <ecotools/roi_hooks.h>\n#include <nlopt.hpp>\n#include <algorithm>\n#include \"ptss_dse.hpp\"\n#include \"ptss_config.hpp\"\n#include \"ptss_nlopt.hpp\"\n\nusing namespace std;\n\n// AET \nstatic double AET[] = {\\\n0.0052912772458832795,\\\n0.004254273510905619,\\\n0.005266330309541947,\\\n0.003688517486111831,\\\n0.003959440926636103,\\\n0.009683975849832148,\\\n0.0024794976904501873,\\\n2.153404950919569e-05,\\\n0.0021638291897166048,\\\n0.003533669349872262,\\\n0.0002555000090127519};\n\nstatic double BET[] = {\\\n0.002118298041182201,\\\n-0.0008304322052644017,\\\n0.0021923143697295602,\\\n0.0011143885733635485,\\\n0.001000559321893281,\\\n-0.002893833328927599,\\\n-0.0007496878381248601,\\\n0.0001677868522003634,\\\n-0.001202365402456029,\\\n-0.0027172901605883966,\\\n-7.198705194815577e-05};\n\nstatic double AP[] = {\\\n2.9905877034358053,\\\n2.0279769439421345,\\\n3.3427689873417723,\\\n2.947167721518987,\\\n3.176307692307692,\\\n1.5027499999999998,\\\n2.299642857142857,\\\n0.6275357142857142,\\\n2.130357142857143,\\\n1.7288351648351648,\\\n0.8776666666666665};\n\nstatic double BP[] = {\\\n1.9919258589511664,\\\n0.3829859855334483,\\\n2.140996835443037,\\\n1.758180379746836,\\\n1.7091208791208778,\\\n4.669250000000002,\\\n3.7145476190476217,\\\n1.810845238095241,\\\n0.834642857142855,\\\n3.2989230769230744,\\\n3.5970000000000013};\n\n/* Lower Limit of core allocation for different phases */\nunsigned int LLIM[] = {\\\n1,\\\n1,\\\n1,\\\n1,\\\n1,\\\n2,\\\n2,\\\n2,\\\n2,\\\n3,\\\n2};\n\nbool phase_t::operator ==(const phase_t &b) const {\n    return ((this->bench_id == b.bench_id) && (this->alloc == b.alloc));\n}\n\nbool phase_t::operator !=(const phase_t &b) const {\n    return !((this->bench_id == b.bench_id) && (this->alloc == b.alloc));\n}\n\nbool phase_t::operator <(const phase_t &b) const {\n    return (this->alloc < b.alloc);\n}\n\nbool phase_t::operator >(const phase_t &b) const {\n    return (this->alloc > b.alloc);\n}\n\nbool phase_t::operator <=(const phase_t &b) const {\n    return (this->alloc <= b.alloc);\n}\n\nbool phase_t::operator >=(const phase_t &b) const {\n    return (this->alloc >= b.alloc);\n}\n\nostream& operator<<(ostream& os, const phase_t& pht) {\n    os << \"{bench_id:\" << pht.bench_id <<\",alloc:\" << pht.alloc << \"}\";\n    return os;\n}\n\nphase_t::phase_t(unsigned int bench_id,unsigned int alloc) : bench_id{bench_id}, alloc{alloc} {}\nphase_t::phase_t() : bench_id{0}, alloc{0} {}\n\ndouble estimate_exec_time(const int x, const int bench) {\n    if (bench > BENCH_PRSC_DEDUP || bench < BENCH_LACE_DFS) {\n        throw invalid_argument( \"Unrecognized Benchmark\" );\n    }\n    double a = AET[bench];\n    double b = BET[bench];\n    double y;\n    if (bench <= BENCH_LACE_QUEENS)\n        y = 1/(a*x + b);\n    else\n        y = 1/(a*log(x) + b);\n    return y;\n}\n\ndouble estimate_power(const int x, const int bench) {\n    if (bench > BENCH_PRSC_DEDUP || bench < BENCH_LACE_DFS) {\n        throw invalid_argument( \"Unrecognized Benchmark\" );\n    }\n    double a = AP[bench];\n    double b = BP[bench];\n    double y;\n    y = a*x + b;\n    return y;\n}\n\nint inv_estimate_power(const double y, const int bench) {\n    if (bench > BENCH_PRSC_DEDUP || bench < BENCH_LACE_DFS) {\n        throw invalid_argument( \"Unrecognized Benchmark\" );\n    }\n    double a = AP[bench];\n    double b = BP[bench];\n    double x;\n    x = (1/a)*(y-b);\n\n    /* The number of cores must be within [LLIM,ULIM] */\n    if (x < LLIM[bench])\n        x = LLIM[bench];\n    if (x > ULIM)\n        x = ULIM;\n    return x;\n}\n\n/* \n * Extrapolation of et can make the values often negative \n * These need to be discarded\n */\ndouble compute_execution_time(const alloc2_t &x) {\n    double sum = 0.0;\n    double et  = 0.0;\n    for(auto jt = x.begin(); jt != x.end(); jt++) {\n        et = estimate_exec_time(jt->alloc,jt->bench_id);\n        if (et >= 0.0)\n            sum += et;\n        else\n            return -HUGE_VAL;\n        \n    }\n    return sum;\n}\n\n\n/* Compute the Peak Power */\ndouble compute_pkpower(const alloc2_t &x) {\n    double pkp = 0.0;\n    for(auto jt = x.begin(); jt != x.end(); jt++)\n        pkp = max(pkp,estimate_power(jt->alloc,jt->bench_id));\n    return pkp;\n}\n\n/* Returns all the bottleneck phases (Those with highest power consumption) */\nset<unsigned int> compute_bottleneck(const alloc2_t &x) {\n    set<unsigned int> phs;\n    double etp[NPH];\n\n    /* Estimate the power of all phases */\n    for (unsigned int i = 0; i < x.size();i++)\n        etp[i] = estimate_power(x[i].alloc,x[i].bench_id);\n    const int N = sizeof(etp) / sizeof(double);\n    unsigned int least_idx = distance(etp, max_element(etp, etp + N));\n    double maxp = etp[least_idx];\n\n    /* Find all indices with maximum power consumption */\n    for(unsigned int i = 0; i < x.size();i++) {\n        // cout << \"maxp : \"<<maxp<<\",power estimate : \"<<estimate_power(x[i].alloc,x[i].bench_id)<<endl;\n        if (maxp == etp[i]) {\n            phs.insert(i);\n        }\n    }\n    return phs;\n}\n\n/* Compute the nbd allocation with maximum decrease in et */\nset<unsigned int> compute_maxgrad(const alloc2_t &x) {\n    set<unsigned int> phs;\n    double etp[NPH];\n    // cout << \"compute_maxgrad input size = \"<<x.size()<<endl;\n    /* Estimate the execution time of all phases */\n    for (unsigned int i = 0; i < x.size();i++) {\n        alloc2_t tmp = x;\n        tmp[i].alloc += 1;\n        etp[i] = compute_execution_time(x) - compute_execution_time(tmp);\n\n        // if (etp[i]) {\n        //     throw invalid_argument(\"Negative diff in et unexpected\\n\");\n        // }\n        // cout << \"ph(\"<<i<<\")-diff:\"<<etp[i]<<endl;\n    }\n    const int N = sizeof(etp) / sizeof(double);\n    unsigned int least_idx = distance(etp, max_element(etp, etp + N));\n    double maxp = etp[least_idx];\n\n    /* Find all indices with max decline in execution time */\n    for(unsigned int i = 0; i < x.size();i++) {\n        // cout << \"maxp : \"<<maxp<<\",power estimate : \"<<estimate_power(x[i].alloc,x[i].bench_id)<<endl;\n        if (maxp == etp[i]) {\n            phs.insert(i);\n        }\n    }\n    // int i = 0;\n    // for (set<unsigned int>::iterator it = phs.begin(); it != phs.end(); it++) {\n    //     cout << \"phs(\"<<i++<<\")-diff:\"<<*it<<endl;\n    // }\n    return phs;\n}\n\n\n/* Try to balance out all the power consumption in all the phases*/\nvoid balance_out(alloc2_t &x) {\n    double pkp = compute_pkpower(x);\n    for(auto jt = x.begin(); jt != x.end(); jt++) {\n        jt->alloc = inv_estimate_power(pkp,jt->bench_id);\n    }\n}\n\n\n// /* Display Routines */\nstd::ostream& operator<<(std::ostream& os, const alloc2_t& vi) {\n    unsigned int i;\n    os << \"<\";\n    for (i = 0; i < vi.size(); i++) {\n        os << vi[i] ;\n        os << \",\";\n    }\n    os << \">\";\n    return os;\n}\n\n/* Display for vector */\nostream& operator<<(ostream& os, const std::vector<double> pht) {\n    os << \"Vector<\" ;\n    for (unsigned int i = 0; i < pht.size(); i++)\n        os << pht[i] << \"|\";\n    os << \">\";\n    return os;\n}\n\nstd::ostream& operator<<(std::ostream& os, const all_alloc2_t& vvi) { \n  os << \"{\\n\";\n  for(auto it = vvi.begin();\n      it != vvi.end();\n      it++) {\n      os << \"  \" << *it << \"\\n\";\n  }\n  os << \"}\";\n  return os;\n}\n\n\n/* An non-recursive version of the above */\nstatic inline long long calculate_time_diff_spec(struct timespec t2, struct timespec t1) {\n    long long elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000000000LL + t2.tv_nsec - t1.tv_nsec;\n    return elapsedTime;                                                         \n} \n\nvoid ptss_DSE_hrt::construct_alloc2() {\n    alloc2_t vi2;\n    double et, pkp;\n    ptss_int_t r = M, j = 0, dec, cnt;\n    ptss_int_t TOT = (ptss_int_t)pow(M,NPH);\n\n    /* Temporary \"Global Varirbles \"*/\n    double deadline = this->deadline;\n    // unsigned int bench[] = {10,9,10,10,7};\n    double opt_pkp_power = HUGE_VALF;\n    double opt_exec_time = HUGE_VALF;\n    //struct timespec t1, t2;\n\n    for (cnt = 0; cnt < TOT; cnt++) {\n        //clock_gettime(CLOCK_REALTIME,&t1);\n        dec = cnt;\n\n        /* Create the point */\n        for (j = 0; j < NPH; j++) {\n            phase_t phinfo;\n            phinfo.alloc = dec%r + 1;\n            phinfo.bench_id = this->bench[j];\n            vi2.push_back(phinfo);\n            dec = dec/r;\n        }\n        \n        /* Find optimal pkp point */\n        et = compute_execution_time(vi2);\n        if (et <= deadline && et >= 0) {\n            pkp = compute_pkpower(vi2);\n            if (pkp <= opt_pkp_power) {\n                this->opt_point     = vi2;\n                opt_pkp_power       = pkp;\n            }\n        }\n        // vi2.clear();\n\n        /* Find optimal et point */\n        pkp = compute_pkpower(vi2);\n        if (pkp <= this->pkp_cap && pkp >= 0) {\n            et = compute_execution_time(vi2);\n            if (et >= 0 && et <= opt_exec_time) {\n                this->opt_point2    = vi2;\n                opt_exec_time       = et;\n            }\n        }\n        vi2.clear();\n    }\n\n    // cout << \"Optimal Point : \"<<opt_point<<endl;\n}\n\nunsigned int gen_bench_id() {\n    unsigned int a = BENCH_PRSC_BLACKSCHOLES + (rand() % 6);\n    return a;\n}\n\n\ndouble ptss_DSE_hrt::compute_cvx() {\n    nlopt::opt opt(nlopt::LD_MMA, NPH+1);\n    // nlopt::opt opt(nlopt::LN_SBPLX, NPH+1);\n\n    /* Set the Box Constraints */\n    std::vector<double> lb(NPH+1);\n    std::vector<double> ub(NPH+1);\n    for (int i = 0; i < NPH; i++) {\n        lb[i] = LLIM[this->bench[i]];\n        ub[i] = ULIM;\n    }\n    lb[NPH] = 0.0;\n    ub[NPH] = HUGE_VAL;\n    opt.set_lower_bounds(lb);\n    opt.set_upper_bounds(ub);\n\n    /* Set the Parameters for inequality constraints */\n    // cout << \"CVX Deadline \" << this->deadline << endl;\n    vector<ptss_constraint_param> param;\n    param.push_back(ptss_constraint_param(this->a_et,this->b_et,this->deadline,-1));\n    for (int i = 0; i < NPH; i++) {\n        param.push_back(ptss_constraint_param(this->a_p,this->b_p,this->deadline,i));\n    }\n    opt.add_inequality_constraint(ptss_constraint_exectime, &param[0], 1e-8);\n    for (int i = 1; i <= NPH; i++) {\n        opt.add_inequality_constraint(ptss_constraint_power, &param[i], 1e-8);\n    }\n\n    /* Set the objective function */\n    opt.set_min_objective(ptss_func_pkp, NULL);\n\n    /* Stopping Criteria and Initial Point*/\n    opt.set_ftol_rel(1e-4);\n    vector<double> x(NPH+1);\n    vector<phase_t> c(NPH);\n    for (int i = 0; i < NPH; i++) {\n        c[i].alloc    = M;\n        c[i].bench_id = this->bench[i];\n        x[i] = M;\n    }\n    x[NPH] = compute_pkpower(c);\n    double minf = 0.0;\n    \n    try{\n        //nlopt::result result = \n        opt.optimize(x, minf);\n        // cout << \"CVX-Opt f(\" << x << \") = \"<< std::setprecision(10) << minf << std::endl;\n        // std::cout << \"found minimum after \" << count <<\" evaluations\\n\";\n\n        /* Update the cvx point */\n        this->cvx_point.clear();\n        for (int i = 0; i < NPH; i++) {\n            phase_t tmp;\n            tmp.alloc    = ceil(x[i]);\n            tmp.bench_id = this->bench[i];\n            this->cvx_point.push_back(tmp);\n        }\n\n        /* Display the continuous domain point */\n        // cout <<\"CVX-Opt continuous point x = <\";\n        // for (int i = 0; i < NPH+1; i++)\n        //     cout <<x[i]<<\",\";\n        // cout<<\">\"<<endl;\n        // cout << \"CVX-Opt minf = \" << minf << endl;\n        // cout << \"CVX-Opt Relaxed Point = \"<<this->cvx_point<<\"\\n\";\n        // cout << \"CVX-Opt Power Consumption = \"<<compute_pkpower(this->cvx_point)<<\"\\n\";\n        // cout << \"CVX-Opt Execution Time = \"<<compute_execution_time(this->cvx_point)<<\"\\n\\n\";\n        \n        return minf;\n    }\n    catch(std::exception &e) {\n        std::cout << \"nlopt failed: \" << e.what() << std::endl;\n    }\n    return minf;\n}\n\ndouble ptss_DSE_hrt::bench_create() {\n    /* Create a mix of benchmarks */\n    int a;\n    // unsigned int benchid[] = {10,9,10,10,7};\n    for (int i = 0; i < NPH; i++) {\n        a = gen_bench_id();\n        // a = benchid[i];\n        // cout << \"Bench id Generated \"<<a<<endl;\n        this->bench.push_back(a);\n        a_et.push_back(AET[a]);\n        b_et.push_back(BET[a]);\n        a_p.push_back(AP[a]);\n        b_p.push_back(BP[a]);\n    }\n    \n    double minf = this->compute_cvx();\n    this->cvx_pkp_min = minf;\n    return minf;\n}\n\n/* Benchid is given */\ndouble ptss_DSE_hrt::bench_create2(const vector<int> &benchid) {\n    /* Create a mix of benchmarks */\n    int a;\n    if (benchid.size() != NPH) {\n        throw runtime_error(\"NPH and benchid size must match\");\n    }\n    for (int i = 0; i < NPH; i++) {\n        a = benchid[i];\n        a_et.push_back(AET[a]);\n        b_et.push_back(BET[a]);\n        a_p.push_back(AP[a]);\n        b_p.push_back(BP[a]);\n    }\n    this->bench = benchid;\n    \n    double minf = this->compute_cvx();\n    this->cvx_pkp_min = minf;\n    return minf;\n}\n\nbool ptss_DSE_hrt::contains_point(const alloc2_t& a) {\n    bool ret = this->search_space.find(a) != this->search_space.end();\n    if (ret) {\n        cout << \"point:\"<<a<<\",pkp:\"<<compute_pkpower(a)<<\",et:\"<<compute_execution_time(a)<<endl;\n    } else {\n        cout << \"point not found : \" << a << endl;\n    }\n    return ret;\n}\n\n\nptss_DSE_hrt::ptss_DSE_hrt(double deadline,double pkp_cap) {\n    this->deadline = deadline;\n    this->pkp_cap  = pkp_cap;\n    this->bench_create();\n    /* Create an extreme point */\n    for (int i = 0; i < NPH; i++) {\n        phase_t p(this->bench[i],ULIM);\n        this->ext_point.push_back(p);\n\n        phase_t p2(this->bench[i],LLIM[this->bench[i]]);\n        this->ext_point2.push_back(p2);\n    }\n#ifndef SHUTDOWN_ORACLE\n    this->construct_alloc2();\n#else\n    /* Do not compute the Oracle*/\n    this->opt_point     = ext_point;\n#endif\n\n    /* Use a DGGD Algorithm */\n    this->ptss_pkmin();\n    this->ptss_etmin();\n}\n\n/* Read the workload from a File, compute and write the results to another CSV file */\nptss_DSE_hrt::ptss_DSE_hrt(rapidcsv::Document &inDoc,ostream &os,double pkp_cap, unsigned int idx, bool &done) {\n    vector<int> benchid;\n    double deadline;\n\n    /* Continuously Read the CSV Files */\n    int i = 1, j = 0;\n    try {\n        std::vector<double> wkld = inDoc.GetRow<double>(idx);\n        this->deadline = wkld[0];\n        this->pkp_cap  = pkp_cap;\n        for (i = 1; i < wkld.size(); i++) {\n            benchid.push_back((int)wkld[i]);\n        }\n        struct timespec t1, t2;\n        clock_gettime(CLOCK_REALTIME,&t1);\n        this->bench_create2(benchid);\n        /* Create an extreme point */\n        for (int i = 0; i < NPH; i++) {\n            phase_t p(this->bench[i],ULIM);\n            this->ext_point.push_back(p);\n            phase_t p2(this->bench[i],LLIM[this->bench[i]]);\n            this->ext_point2.push_back(p2);\n        }\n        /* Use a DGGD Algorithm */\n        \n        this->ptss_pkmin();\n        clock_gettime(CLOCK_REALTIME,&t2);\n        this->ptss_etmin();\n        double roip = (t2.tv_nsec-t1.tv_nsec)*10e-9 + (t2.tv_sec-t1.tv_sec);\n        \n        /* Display/Dump */\n        for(i = 0; i < NPH; i++) {\n            os << this->dggd_point[i].alloc << \",\";\n        }\n        os << compute_pkpower(this->dggd_point) << \",\";\n        if (compute_execution_time(this->dggd_point) <= this->deadline) {\n            os << \"passed,\";\n        } else {\n            os << \"failed,\";\n        }\n        os << roip << \",\";\n        os << compute_pkpower(this->ext_point) << \",\";\n        os << compute_execution_time(this->dggd_point2) << endl;\n        \n        // os << this->deadline <<\",\";\n        // for(i = 0; i < NPH; i++) {\n        //     os << this->bench[i] << \",\";\n        // }\n        // cout << endl;\n\n        benchid.clear();\n    } catch(out_of_range) {\n        done = true;\n        std::cout << \"Reached End of CSV File (numPhases = \"<< NPH <<\")\" << std::endl;\n        return;\n    }\n}\n\n// a == b ?\nbool is_eq(const alloc2_t &a, const alloc2_t &b) {\n    return (a == b);\n}\n\n// a > b ?\nbool is_gt(const alloc2_t &a, const alloc2_t &b) {\n    bool ret = !(is_eq(a,b));\n    int idx = 0;\n    for(auto it = a.begin();\n        it != a.end();\n        it++) {\n            if (it->alloc >= b[idx++].alloc)\n                ret = ret && true;\n            else\n                ret = ret && false;\n    }\n    return ret;\n}\n\n// a < b ?\nbool is_lt(const alloc2_t &a, const alloc2_t &b) {\n    bool ret = !(is_eq(a,b));\n    int idx = 0;\n    for(auto it = a.begin();\n        it != a.end();\n        it++) {\n            if (it->alloc <= b[idx++].alloc)\n                ret = ret && true;\n            else\n                ret = ret && false;\n    }\n    return ret;\n}\n\n// a and b are not comparable\nbool is_incomparable(const alloc2_t &a, const alloc2_t &b) {\n    bool ret = (!is_gt(a,b)) && \\\n               (!is_lt(a,b)) && \\\n               (!is_eq(a,b));\n    return ret;\n}\n\n// lexicographic comparison of two allocations ( a < b ? )\nbool lex_comp(const alloc2_t &a, const alloc2_t &b) {\n    auto it2 = b.begin();\n    for (auto it = a.begin(); it != a.end(); it++, it2++) {\n        if (it2->alloc < it->alloc)\n            return false;\n    }\n    return true;\n}\n\n\nvoid ptss_DSE_hrt::display() {\n    if (this->cvx_point.size() < NPH) {\n        throw invalid_argument(\"Did not create CVX Opt Point\");\n    }\n    if (this->dggd_point.size() < NPH) {\n        throw invalid_argument(\"Did not create DGGD Opt Point\");\n    }\n    if (this->opt_point.size() < NPH) {\n        cout << \"NO FEASIBLE PKP POINT FOUND\" << endl;\n    }\n    if (this->opt_point2.size() < NPH) {\n        cout << \"NO FEASIBLE ET POINT FOUND\" << endl;\n    }\n\n#ifdef DEBUG1\n    cout << \"Optimal PKP Point:\" << this->opt_point<< \",et:\" \\\n    << compute_execution_time(this->opt_point) \\\n    <<\",pkp:\"<<compute_pkpower(this->opt_point)<<endl;\n    \n    cout << \"Optimal ET Point:\" << this->opt_point2<< \",et:\" \\\n    << compute_execution_time(this->opt_point2) \\\n    <<\",pkp:\"<<compute_pkpower(this->opt_point2)<<endl;\n\n    cout << \"DGGD Point:\" << this->dggd_point<<\",et:\" \\\n    << compute_execution_time(this->dggd_point) \\\n    <<\",pkp:\"<<compute_pkpower(this->dggd_point)<<endl;\n\n    cout << \"DGGD2 Point:\" << this->dggd_point2<<\",et:\" \\\n    << compute_execution_time(this->dggd_point2) \\\n    <<\",pkp:\"<<compute_pkpower(this->dggd_point2)<<endl;\n#endif\n#ifndef SHUTDOWN_ORACLE\n    // cout << \"ufhew4r4{Oracle|CVX-Cont|CVX-Disc|DGGD},\"<<endl;\n    cout<<\"ufhew4r4-pkpcap,\"<<NPH<<\",\"\\\n        <<this->pkp_cap<<\",\"\\\n        <<this->deadline<<\",\"\\\n        <<compute_pkpower(this->opt_point)<<\",\"\\\n        <<compute_pkpower(this->ext_point)<<\",\"\\\n        <<this->cvx_pkp_min<<\",\"\\\n        <<compute_pkpower(this->cvx_point)<<\",\"\\\n        <<compute_pkpower(this->dggd_point)<<\",\"\\\n        <<compute_execution_time(this->opt_point2)<<\",\"\\\n        <<compute_execution_time(this->dggd_point2)<<endl;\n#else\n    cout << \"ufhew4r4{Worst|CVX-Cont|CVX-Disc|DGGD},\";\n#endif\n    cout << \"\\n\\n\\n\";\n}\n", "meta": {"hexsha": "f94b92bc077f206faff7b07cd41233e16067ca7c", "size": 18925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ptss_dse_hrt.cpp", "max_stars_repo_name": "Arka2009/ptss-dse", "max_stars_repo_head_hexsha": "9d56511635b5f87d020996ec4b89d224a97ade93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ptss_dse_hrt.cpp", "max_issues_repo_name": "Arka2009/ptss-dse", "max_issues_repo_head_hexsha": "9d56511635b5f87d020996ec4b89d224a97ade93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ptss_dse_hrt.cpp", "max_forks_repo_name": "Arka2009/ptss-dse", "max_forks_repo_head_hexsha": "9d56511635b5f87d020996ec4b89d224a97ade93", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3308383234, "max_line_length": 112, "alphanum_fraction": 0.5635402906, "num_tokens": 5646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4217583210624285}}
{"text": "\n#include <string>\n#include <sstream>\n#include <cassert>\n#include <algorithm> // std::max(a,b)\n\n//Boost \n#include <fstream>\n#include <iostream>\n#include <boost/iostreams/filtering_streambuf.hpp>\n#include <boost/iostreams/copy.hpp>\n#include <boost/iostreams/filter/gzip.hpp>\n\n//Root\n#include \"TApplication.h\"\n#include \"TComplex.h\"\n#include <TGraph.h>\n#include \"TAxis.h\"\n#include \"TCanvas.h\"\n#include \"TH1I.h\"\n#include \"THStack.h\"\n#include \"TLegend.h\"\n#include \"TH2D.h\"\n\n\nusing namespace std;\n\nchar muted_in(string ATCG_data);\n\ndouble compute_mut_freq(string ATCG_data, char muted_in);\n\nint compute_coverage(string ATCG_data);\n\ndouble compute_mut_rate(double P_hat, double death_prob, int extant);\n\nbool endpoint_muted(double mut_freq, int total_coverage, int extant);\n\n/*\nCount base as muted if endpoint frequency \n\n\tf >= Cutoff(Coverage, f_min) e Coverage = TotCoverage/3\n\n\tcutoff (Coverage, f_min) = f_min + alpha/Sqrt[Coverage]\n\nbased on extant f_min and corresponding alphas are\n\n\tf_min = {1/8, 1/12, 1/16, 1/20, 1/24, 1/28, 1/32, 1/48, 1/75, 1/100}\n\n\talpha = {0.52, 0.45, 0.36, 0.32, 0.3, 0.28, 0.25, 0.2, 0.18, 0.15} \n\t\n\textant: for defining minimum mut_freq to consider endpoint as muted\n\t\n\textant must be in {8, 12, 16, 20, 24, 28, 32, 48, 75, 100}\n\t\t\t    |                                   |\n\t\t\t    |-----------10 elements-------------|\n*/\n\nint main(){\n\n\t//*******************************************\n\t//          THRESHOLDS\n\t//*******************************************\n\tint ancestor_coverage_min = 30;\n\tlong int discarded_by_threshold = 0;\n\tdouble endpoint_max_mut_freq = 0.2;\n\n\t//*******************************************\n\t//          FILENAMES\n\t//*******************************************\n\tstring ancestor_1 = \"CRC1307-02-0.all_common.gz\"; \n\tstring ancestor_2 = \"CRC1307-09-0.all_common.gz\";\n\t\n\tstring endpoint_1 = \"CRC1307-02-1-E.all_common.gz\";\n\tstring endpoint_2 = \"CRC1307-09-1-B.all_common.gz\";\n\t\n\t\n\t//*******************************************\n\t//          COMPRESSED INPUT\n\t//*******************************************\n\t//(IN) ANCESTOR FILE 1 --------------------------------------------------\n\tifstream file_ancestor_1(ancestor_1, ios_base::in | ios_base::binary);\n    \t\n    \tif (file_ancestor_1.is_open() == false) {\n\t\tcerr << ancestor_1 << \" not opened: exit!\" <<endl;\n\t\treturn -1;\n\t}\n\t//uncompress\n    \tboost::iostreams::filtering_streambuf<boost::iostreams::input> ancestor_1_inbuf;\n    \tancestor_1_inbuf.push(boost::iostreams::gzip_decompressor());\n    \tancestor_1_inbuf.push(file_ancestor_1);\n    \t//Convert streambuf to istream\n    \tistream ancestor_1_instream(&ancestor_1_inbuf);\n\t\n\tcerr << endl << ancestor_1 << \" opened.\" << endl;\n\t\n\t//(IN) ANCESTOR FILE 2 --------------------------------------------------\n\tifstream file_ancestor_2(ancestor_2, ios_base::in | ios_base::binary);\n    \t\n    \t    \tif (file_ancestor_2.is_open() == false) {\n\t\tcerr << ancestor_2 << \" not opened: exit!\" <<endl;\n\t\treturn -1;\n\t}\n\t//uncompress\n    \tboost::iostreams::filtering_streambuf<boost::iostreams::input> ancestor_2_inbuf;\n    \tancestor_2_inbuf.push(boost::iostreams::gzip_decompressor());\n    \tancestor_2_inbuf.push(file_ancestor_2);\n    \t//Convert streambuf to istream\n    \tistream ancestor_2_instream(&ancestor_2_inbuf);\n\t\n\tcerr << endl << ancestor_2 << \" opened.\" << endl;\n\t\n\t//(IN) ENDPOINT FILE 1 --------------------------------------------------\n\tifstream file_endpoint_1(endpoint_1, ios_base::in | ios_base::binary);\n    \t\n    \tif (file_endpoint_1.is_open() == false) {\n\t\tcerr << endpoint_1 << \" not opened: exit!\" <<endl;\n\t\treturn -1;\n\t}\n\t//uncompress\n    \tboost::iostreams::filtering_streambuf<boost::iostreams::input> endpoint_1_inbuf;\n    \tendpoint_1_inbuf.push(boost::iostreams::gzip_decompressor());\n    \tendpoint_1_inbuf.push(file_endpoint_1);\n    \t//Convert streambuf to istream\n    \tistream endpoint_1_instream(&endpoint_1_inbuf);\n\t\n\tcerr << endl << endpoint_1 << \" opened.\" << endl;\n\t\n\t//(IN) ENDPOINT FILE 2 --------------------------------------------------\n\tifstream file_endpoint_2(endpoint_2, ios_base::in | ios_base::binary);\n    \t\n    \tif (file_endpoint_2.is_open() == false) {\n\t\tcerr << endpoint_2 << \" not opened: exit!\" <<endl;\n\t\treturn -1;\n\t}\n\t//uncompress\n    \tboost::iostreams::filtering_streambuf<boost::iostreams::input> endpoint_2_inbuf;\n    \tendpoint_2_inbuf.push(boost::iostreams::gzip_decompressor());\n    \tendpoint_2_inbuf.push(file_endpoint_2);\n    \t//Convert streambuf to istream\n    \tistream endpoint_2_instream(&endpoint_2_inbuf);\n\t\n\tcerr << endl << endpoint_2 << \" opened.\" << endl;\n\t\n\t\n\t//*******************************************\n\t//          PARSING VARIABLES\n\t//*******************************************\n\t//Ancestor 1 parsing variables-------------\n\tstring ancestor_1_line; //line of the file to parse\n\tstring ancestor_1_chromosome; //pos\n\tint ancestor_1_chromosome_number = 0;\n\tlong int ancestor_1_base_number = 0; //1-based\n\tstring ancestor_1_ATCG_data;\n\t\n\t//Ancestor 2 parsing variables-------------\n\tstring ancestor_2_line; //line of the file to parse\n\tstring ancestor_2_chromosome; //pos\n\tint ancestor_2_chromosome_number = 0;\n\tlong int ancestor_2_base_number = 0; //1-based\n\tstring ancestor_2_ATCG_data;\n\t\n\t//Endpoint 1 parsing variables-------------\n\tstring endpoint_1_line; //line of the file to parse\n\tstring endpoint_1_chromosome; //pos\n\tint endpoint_1_chromosome_number = 0;\n\tlong int endpoint_1_base_number = 0; //1-based\n\tstring endpoint_1_ATCG_data;\n\t\n\t\n\t//Endpoint 2 parsing variables-------------\n\tstring endpoint_2_line; //line of the file to parse\n\tstring endpoint_2_chromosome; //pos\n\tint endpoint_2_chromosome_number = 0;\n\tlong int endpoint_2_base_number = 0; //1-based\n\tstring endpoint_2_ATCG_data;\n\t\n\t//*******************************************\n\t//          USEFUL VARIABLES\n\t//*******************************************\n\tlong int total_lines = 0;\n\tlong int both_not_muted = 0;\n\tlong int both_muted = 0;\n\tlong int both_same_mutation = 0;\n\tlong int one_muted_and_one_not = 0;\n\t\n\tchar endpoint_1_muted_in;\n\tchar endpoint_2_muted_in;\n\tdouble endpoint_1_mut_freq;\n\tdouble endpoint_2_mut_freq;\n\t\n\tint extants [10] = {8, 12, 16, 20, 24, 28, 32, 48, 75, 100};\n\t\n\tlong int endpoint_1_muted_bases [10] = {}; //10 long int values, each initialized with a value of zero\n\tlong int endpoint_1_not_muted_bases [10] = {};\n\tdouble endpoint_1_P_hat [10] = {};\n\t\n\tlong int endpoint_2_muted_bases [10] = {}; \n\tlong int endpoint_2_not_muted_bases [10] = {};\n\tdouble endpoint_2_P_hat [10] = {};\n\t\n\t\n\t//ROOT\n\tTApplication myApp(\"myApp\",0,0);\n\t\n\t//Histograms (frequecy_1, frequency_2) \n\tTH2D *h_all = new TH2D(\"All mutations\", \"All mutations\", 201, 0., 1.005, 201, 0., 1.005);\n\t\n\tTH2D *h_same = new TH2D(\"Same mutation for both endpoints\", \"Same mutation for both endpoints\", 201, 0., 1.005, 201, 0., 1.005);\n\t\n\tTH2D *h_different = new TH2D(\"Different mutation for the two endpoints\", \"Different mutation for the two endpoints\", 201, 0., 1.005, 201, 0., 1.005);\n\t\n\t//*******************************************\n\t//          START\n\t//*******************************************\n\tcout<< endl << \"Start reading files...\" << endl;\n\t//Loop for all line \n\twhile (getline(ancestor_1_instream, ancestor_1_line)) {\n\t\t//Read a line from each file\n\t\tgetline(ancestor_2_instream, ancestor_2_line);\n\t\tgetline(endpoint_1_instream, endpoint_1_line);\n\t\tgetline(endpoint_2_instream, endpoint_2_line);\n\t\n\t\t// Parse ancestor_1 line \n\t\tstringstream ancestor_1_linestream(ancestor_1_line);\n\t\t//get file_2 line pos finding the separator ('\\t')\n\t\tgetline(ancestor_1_linestream, ancestor_1_chromosome, '\\t');\n\t\t//get file_2 loc\n\t\tancestor_1_linestream >> ancestor_1_base_number;\n\t\t//we need chromosome numeber and loc\n\t\t//extract chromosome number from chromosome string\n\t\t// \"chrN\", N integer\n\t\t//     ^        \n\t\tancestor_1_chromosome_number = atoi(&ancestor_1_chromosome[3]);\n\t\t//get file_2 ATCG data finding the separator ('\\n')\n\t\tgetline(ancestor_1_linestream, ancestor_1_ATCG_data, '\\n');\n\t\t\n\t\t// Parse ancestor_2 line\n\t\tstringstream ancestor_2_linestream(ancestor_2_line);\n\t\tgetline(ancestor_2_linestream, ancestor_2_chromosome, '\\t');\n\t\tancestor_2_linestream >> ancestor_2_base_number;\n\t\tancestor_2_chromosome_number = atoi(&ancestor_2_chromosome[3]);\n\t\tgetline(ancestor_2_linestream, ancestor_2_ATCG_data, '\\n');\n\t\t\n\t\t// Parse endpoint_1 line \n\t\tstringstream endpoint_1_linestream(endpoint_1_line);\n\t\tgetline(endpoint_1_linestream, endpoint_1_chromosome, '\\t');\n\t\tendpoint_1_linestream >> endpoint_1_base_number;\n\t\tendpoint_1_chromosome_number = atoi(&endpoint_1_chromosome[3]);\n\t\tgetline(endpoint_1_linestream, endpoint_1_ATCG_data, '\\n');\n\t\t\n\t\t// Parse endpoint_2 line\n\t\tstringstream endpoint_2_linestream(endpoint_2_line);\n\t\tgetline(endpoint_2_linestream, endpoint_2_chromosome, '\\t');\n\t\tendpoint_2_linestream >> endpoint_2_base_number;\n\t\tendpoint_2_chromosome_number = atoi(&endpoint_2_chromosome[3]);\n\t\tgetline(endpoint_2_linestream, endpoint_2_ATCG_data, '\\n');\n\t\t\n\t\t//check that we loaded corrisponding lines (=> input files are ok)\n\t\tassert((ancestor_1_chromosome_number == ancestor_2_chromosome_number) \n\t\t\t&& (ancestor_2_chromosome_number == endpoint_1_chromosome_number) \n\t\t\t&& (ancestor_2_chromosome_number == endpoint_2_chromosome_number));\n\t\t\t\n\t\tassert((ancestor_1_base_number == ancestor_2_base_number)\n\t\t\t&& (ancestor_2_base_number == endpoint_1_base_number)\n\t\t\t&& (ancestor_2_base_number == endpoint_2_base_number));\n\t\t\n\t\t//Count loaded lines\n\t\ttotal_lines++;\n\t\tif (total_lines % 100000000 == 0){\n\t\t\tcout << total_lines/100000000 << \"00 millions of lines read.\" << endl;\n\t\t}\n\t\t\n\t\t//Check ancestor coverage and discard according to threshold\n\t\tif (compute_coverage(ancestor_1_ATCG_data) < ancestor_coverage_min || \n\t\t\tcompute_coverage(ancestor_2_ATCG_data) < ancestor_coverage_min) {\n\t\t\t//one or both of the ancestors have a coverage under threshold\n\t\t\t//we discard the corresponding base \n\t\t\tdiscarded_by_threshold++;\n\t\t\t//skip this base and don't put it in the histograms\n\t\t\t//load next lines from files files\n\t\t\tcontinue; \n\t\t\t\t\n\t\t}\n\t\t\n\t\t//Check if endpoint 1 muted\n\t\tendpoint_1_muted_in = muted_in(endpoint_1_ATCG_data);\n\t\tif (endpoint_1_muted_in != ' '){\n\t\t\tendpoint_1_mut_freq = compute_mut_freq(endpoint_1_ATCG_data, endpoint_1_muted_in);\n\t\t} else endpoint_1_mut_freq = 0.;\n\t\t\n\t\t//Check if endpoint 2 muted\n\t\tendpoint_2_muted_in = muted_in(endpoint_2_ATCG_data);\n\t\tif (endpoint_2_muted_in != ' '){\n\t\t\tendpoint_2_mut_freq = compute_mut_freq(endpoint_2_ATCG_data, endpoint_2_muted_in);\n\t\t} else endpoint_2_mut_freq = 0.;\n\t\t\n\t\t//Check endpointand discard according to threshold\n\t\tif (endpoint_1_mut_freq > endpoint_max_mut_freq \n\t\t    || endpoint_2_mut_freq > endpoint_max_mut_freq) {\n\t\t    \tdiscarded_by_threshold++;\n\t\t    \tcontinue;\n\t\t    }\n\t\t\n\t\t//compute enpoint 1 and 2 coverages \n\t\tint endpoint_1_coverage = compute_coverage(endpoint_1_ATCG_data);\n\t\tint endpoint_2_coverage = compute_coverage(endpoint_2_ATCG_data);\n\t\t\n\t\tif (endpoint_1_muted_in == ' ' && endpoint_2_muted_in == ' '){\n\t\t\t//Both endpoints totally confim reference \n\t\t\tboth_not_muted++;\n\t\t\t//count these lines in both ancestors' denominator\n\t\t\t//for all extants \n\t\t\tfor (int i = 0; i < 10; i++){\n\t\t\t\tendpoint_1_not_muted_bases [i] ++;\n\t\t\t\tendpoint_2_not_muted_bases [i] ++;\n\t\t\t}\n\t\t} else {\n\t\t\t//at least one muted\n\t\t\th_all -> Fill(endpoint_1_mut_freq, endpoint_2_mut_freq);\n\t\t\t\n\t\t\tif(endpoint_1_muted_in == ' ' || endpoint_2_muted_in == ' '){\n\t\t\t\t//one muted and one not\n\t\t\t\tone_muted_and_one_not++;\n\t\t\t\th_different -> Fill(endpoint_1_mut_freq, endpoint_2_mut_freq);\n\t\t\t\t//Need to count that line based on the cutoff(extant)\n\t\t\t\t//for one of the two endpoints\n\t\t\t\t\n\t\t\t\tif (endpoint_2_muted_in == ' '){\n\t\t\t\t\t//endpoint 1 muted and 2 not\n\t\t\t\t\t\n\t\t\t\t\t//label endpoint_1 as muted or not\n\t\t\t\t\t//using cutoff varying extant\n\t\t\t\t\tfor (int i = 0; i < 10; i++){\n\t\t\t\t\t\t//base is not muted for endpoint 2\n\t\t\t\t\t\tendpoint_2_not_muted_bases [i] ++;\n\t\t\t\t\t\t//check cutoff for endpoint 1\n\t\t\t\t\t\tif (endpoint_muted(endpoint_1_mut_freq, endpoint_1_coverage, extants[i]) ){\n\t\t\t\t\t\t\tendpoint_1_muted_bases [i] ++;\n\t\t\t\t\t\t} else{\n\t\t\t\t\t\t\tendpoint_1_not_muted_bases [i] ++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t//endpoint 2 muted and 1 not\n\t\t\t\t\t//label endpoint_2 as muted or not\n\t\t\t\t\t//using cutoff varying extant\n\t\t\t\t\tfor (int i = 0; i < 10; i++){\n\t\t\t\t\t\t//base not muted for endpoint 1\n\t\t\t\t\t\tendpoint_1_not_muted_bases [i] ++;\n\t\t\t\t\t\t//check cutoff for endpoint 2\n\t\t\t\t\t\tif (endpoint_muted(endpoint_2_mut_freq, endpoint_2_coverage, extants[i]) ){\n\t\t\t\t\t\t\tendpoint_2_muted_bases [i] ++;\n\t\t\t\t\t\t} else{\n\t\t\t\t\t\t\tendpoint_2_not_muted_bases [i] ++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tboth_muted++;\n\t\t\t\tif(endpoint_1_muted_in == endpoint_2_muted_in) {\n\t\t\t\t\t//Same mutation for both endpoints\n\t\t\t\t\tboth_same_mutation++;\n\t\t\t\t\th_same -> Fill(endpoint_1_mut_freq, endpoint_2_mut_freq);\n\t\t\t\t\t//Skip these lines for the mut rate computation\n\t\t\t\t} else {\n\t\t\t\t\t//both muted but bifferent mutation\n\t\t\t\t\th_different -> Fill(endpoint_1_mut_freq, endpoint_2_mut_freq);\n\t\t\t\t\t//Need to count these lines based on the cutoff(extant)\n\t\t\t\t\t//for both the endpoints\n\t\t\t\t\t\n\t\t\t\t\tfor (int i = 0; i < 10; i++){\n\t\t\t\t\t\t//check cutoff for endpoint 1\n\t\t\t\t\t\tif (endpoint_muted(endpoint_1_mut_freq, endpoint_1_coverage, extants[i]) ){\n\t\t\t\t\t\t\tendpoint_1_muted_bases [i] ++;\n\t\t\t\t\t\t} else{\n\t\t\t\t\t\t\tendpoint_1_not_muted_bases [i] ++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//check cutoff for endpoint 2\n\t\t\t\t\t\tif (endpoint_muted(endpoint_2_mut_freq, endpoint_2_coverage, extants[i]) ){\n\t\t\t\t\t\t\tendpoint_2_muted_bases [i] ++;\n\t\t\t\t\t\t} else{\n\t\t\t\t\t\t\tendpoint_2_not_muted_bases [i] ++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t} //EOF\n\t\n\tassert(total_lines - discarded_by_threshold == both_not_muted + both_muted + one_muted_and_one_not);\n\tassert(both_same_mutation <= both_muted);\n\t\n\tcout <<\"Total bases in files: \" << total_lines << endl<<endl;\n\tcout <<\"Total lines discarded by threshold (ancestor coverage min): \" << discarded_by_threshold << endl;\n\tcout <<\"Both endpoints not muted: \" << both_not_muted <<endl;\n\tcout <<\"Both endpoints muted: \" << both_muted << endl;\n\tcout <<\"Both endpoints with the same mutation: \" << both_same_mutation << endl;\n\tcout <<\"One endpoint muted and one not: \"<< one_muted_and_one_not <<endl;\n\t\n\t//*******************************************\n\t//          FILES CLEANUP\n\t//*******************************************\n\tfile_ancestor_1.close();\n\tfile_ancestor_2.close();\n\tfile_endpoint_1.close();\n\tfile_endpoint_2.close();\n\t\n\t//*******************************************\n\t//         COMPUTE MUT RATE\n\t//*******************************************\n\tcout << \"Total lines considered for the estimation of mut rate (denominator): \"<< total_lines - discarded_by_threshold - both_same_mutation <<endl;\n\tdouble min_mu, max_mu;\n\t\n\t\n\tofstream endpoint_1_results;\n\tofstream endpoint_2_results;\n\tendpoint_1_results.open(\"CRC1307-02-1-E.all_common_results.csv\");\n\tendpoint_2_results.open(\"CRC1307-09-1-B.all_common_results.csv\");\n\t\n\tcout << endl << endl << \"Computing mutation rate for endpoint CRC1307-02-1-E\"<< endl<< endl;\n\tcout << \"extant\\tmuted_bases\\tp_hat\\tmin_mu\\tmax_mu\" << endl;\n\t\n\tendpoint_1_results << \"extant,p_hat,min_mu,max_mu\" << endl;\n\t\n\tfor (int i = 0; i < 10; i++){\n\t\tassert(total_lines - discarded_by_threshold - both_same_mutation == endpoint_1_muted_bases[i] + endpoint_1_not_muted_bases[i]);\n\t\tendpoint_1_results << extants [i] << \",\";\n\t\tcout << extants [i] << \"\\t\";\n\t\tcout << endpoint_1_muted_bases[i] << \"\\t\";\n\t\t\n\t\tendpoint_1_P_hat [i] = double(endpoint_1_muted_bases[i]) / double(endpoint_1_muted_bases[i] + endpoint_1_not_muted_bases[i]);\n\t\t\n\t\tendpoint_1_results << endpoint_1_P_hat [i] << \",\";\n\t\tcout << endpoint_1_P_hat [i] << \"\\t\";\n\t\t\n\t\tmin_mu = compute_mut_rate(endpoint_1_P_hat [i], 0.45, extants [i]);\n\t\tmax_mu = compute_mut_rate(endpoint_1_P_hat [i], 0.1, extants [i]);\n\t\t\n\t\tendpoint_1_results << min_mu << \",\" << max_mu << endl;\n\t\tcout << min_mu << \"\\t\" << max_mu << endl;\n\t}\n\t\n\tcout << endl << endl << \"Computing mutation rate for endpoint CRC1307-09-1-B\"<< endl <<endl;\n\tcout << \"extant\\tmuted_bases\\tp_hat\\tmin_mu\\tmax_mu\" << endl;\n\t\n\tendpoint_2_results << \"extant,p_hat,min_mu,max_mu\" << endl;\n\t\n\tfor (int i = 0; i < 10; i++){\n\t\tassert(total_lines - discarded_by_threshold - both_same_mutation == endpoint_2_muted_bases[i] + endpoint_2_not_muted_bases[i]);\n\t\tendpoint_2_results << extants [i] << \",\";\n\t\tcout << extants [i] << \"\\t\";\n\t\tcout << endpoint_2_muted_bases[i] << \"\\t\";\n\t\t\n\t\tendpoint_2_P_hat [i] = double(endpoint_2_muted_bases[i]) / double(endpoint_2_muted_bases[i] + endpoint_2_not_muted_bases[i]);\n\t\t\n\t\tendpoint_2_results << endpoint_2_P_hat [i] << \",\";\n\t\tcout << endpoint_2_P_hat [i] << \"\\t\";\n\t\t\n\t\tmin_mu = compute_mut_rate(endpoint_2_P_hat [i], 0.45, extants [i]);\n\t\tmax_mu = compute_mut_rate(endpoint_2_P_hat [i], 0.1, extants [i]);\n\t\t\n\t\tendpoint_2_results << min_mu << \",\" << max_mu << endl;\n\t\tcout << min_mu << \"\\t\" << max_mu << endl;\n\t}\n\t\n\t\n\tendpoint_1_results.close();\n\tendpoint_2_results.close();\n\t\n\tcout << \"Results written on .csv files.\" << endl << \"Starting ROOT graphs.\" << endl;\n\t\n\t//Start Root graphics\n\tTCanvas c1(\"Same mutation\", \"Same mutation\",800,800);\n   \th_same -> GetXaxis() -> SetTitle(\"mut freq endpoint 1\");\n   \th_same -> GetYaxis() -> SetTitle(\"mut freq endpoint 2\");\n   \th_same -> GetZaxis() -> SetTitle(\"Counts\");\n   \tc1.SetLogx();\n   \tc1.SetLogy();\n   \tc1.SetLogz();\n   \th_same -> Draw(\"colz\");\n   \t\n   \tTCanvas c2(\"Different mutation\", \"Different mutation\",800,800);\n   \th_different -> GetXaxis() -> SetTitle(\"mut freq endpoint 1\");\n   \th_different -> GetYaxis() -> SetTitle(\"mut freq endpoint 2\");\n   \th_different -> GetZaxis() -> SetTitle(\"Counts\");\n   \tc2.SetLogx();\n   \tc2.SetLogy();\n   \tc2.SetLogz();\n   \th_different -> Draw(\"colz\");\n   \t\n   \tTCanvas c3(\"All mutations\", \"All mutations\",800,800);\n   \th_all -> GetXaxis() -> SetTitle(\"mut freq endpoint 1\");\n   \th_all -> GetYaxis() -> SetTitle(\"mut freq endpoint 2\");\n   \th_all -> GetZaxis() -> SetTitle(\"Counts\");\n   \tc3.SetLogx();\n   \tc3.SetLogy();\n   \tc3.SetLogz();\n   \th_all -> Draw(\"colz\");\n   \t\n   \tmyApp.Run(1);\n\t\n\treturn 0;\n}\n\n\nchar muted_in(string ATCG_data){\n\n\tchar reference;\n\tint A_counter = 0;\n\tint a_counter = 0;\n\tint T_counter = 0;\n\tint t_counter = 0;\n\tint C_counter = 0;\n\tint c_counter = 0;\n\tint G_counter = 0;\n\tint g_counter = 0;\n\tint coverage = 0;\n\tchar muted_in;\n\t\n\tstringstream ATCG_linestream(ATCG_data);\n\tATCG_linestream >> reference;\n\t//counters\n\tATCG_linestream >> A_counter; coverage += A_counter;\n\tATCG_linestream >> T_counter; coverage += T_counter;\n\tATCG_linestream >> C_counter; coverage += C_counter;\n\tATCG_linestream >> G_counter; coverage += G_counter;\n\tATCG_linestream >> a_counter; coverage += a_counter;\n\tATCG_linestream >> t_counter; coverage += t_counter;\n\tATCG_linestream >> c_counter; coverage += c_counter;\n\tATCG_linestream >> g_counter; coverage += g_counter;\n\t\n\t//total counts (forward+reverse)\n\tint A = A_counter + a_counter;\n\tint T = T_counter + t_counter;\n\tint C = C_counter + c_counter;\n\tint G = G_counter + g_counter;\n\t\n\tif (reference == 'A'){\n\t\tint muted_reads = max(T,C);\n\t\tmuted_reads = max(muted_reads,G);\n\t\tif (muted_reads != 0) {\n\t\t\tif (muted_reads == T) muted_in = 'T';\n\t\t\tif (muted_reads == C) muted_in = 'C';\n\t\t\tif (muted_reads == G) muted_in = 'G';\n\t\t} else muted_in = ' ';\n\t}\n\tif (reference == 'T'){\n\t\tint muted_reads = max(A,C);\n\t\tmuted_reads = max(muted_reads,G);\n\t\tif (muted_reads != 0) {\n\t\t\tif (muted_reads == A) muted_in = 'A';\n\t\t\tif (muted_reads == C) muted_in = 'C';\n\t\t\tif (muted_reads == G) muted_in = 'G';\n\t\t} else muted_in = ' ';\n\t}\n\tif (reference == 'C'){\n\t\tint muted_reads = max(A,T);\n\t\tmuted_reads = max(muted_reads,G);\n\t\tif (muted_reads != 0) {\n\t\t\tif (muted_reads == A) muted_in = 'A';\n\t\t\tif (muted_reads == T) muted_in = 'T';\n\t\t\tif (muted_reads == G) muted_in = 'G';\n\t\t} else muted_in = ' ';\n\t}\n\tif (reference == 'G'){\n\t\tint muted_reads = max(A,T);\n\t\tmuted_reads = max(muted_reads,C);\n\t\tif (muted_reads != 0) {\n\t\t\tif (muted_reads == A) muted_in = 'A';\n\t\t\tif (muted_reads == T) muted_in = 'T';\n\t\t\tif (muted_reads == C) muted_in = 'C';\n\t\t} else muted_in = ' ';\n\t}\n\t\n\treturn muted_in;\n}\ndouble compute_mut_freq(string ATCG_data, char muted_in){\n\tassert(muted_in == 'A' || muted_in == 'T' || muted_in == 'C' || muted_in == 'G');\n\tchar reference;\n\tint A_counter = 0;\n\tint a_counter = 0;\n\tint T_counter = 0;\n\tint t_counter = 0;\n\tint C_counter = 0;\n\tint c_counter = 0;\n\tint G_counter = 0;\n\tint g_counter = 0;\n\tint coverage = 0;\n\t\n\tdouble mut_freq;\n\tint muted_reads=0;\n\t\n\tstringstream ATCG_linestream(ATCG_data);\n\tATCG_linestream >> reference;\n\t\n\tassert(muted_in != reference);\n\t\n\t//counters\n\tATCG_linestream >> A_counter; coverage += A_counter;\n\tATCG_linestream >> T_counter; coverage += T_counter;\n\tATCG_linestream >> C_counter; coverage += C_counter;\n\tATCG_linestream >> G_counter; coverage += G_counter;\n\tATCG_linestream >> a_counter; coverage += a_counter;\n\tATCG_linestream >> t_counter; coverage += t_counter;\n\tATCG_linestream >> c_counter; coverage += c_counter;\n\tATCG_linestream >> g_counter; coverage += g_counter;\n\t\n\tif(muted_in == 'A'){\n\t\tmuted_reads = A_counter + a_counter;\n\t\tmut_freq = double(muted_reads)/double(coverage);\n\t\treturn mut_freq;\n\t}\n\tif(muted_in == 'T'){\n\t\tmuted_reads = T_counter + t_counter;\n\t\tmut_freq = double(muted_reads)/double(coverage);\n\t\treturn mut_freq;\n\t}\n\tif(muted_in == 'C'){\n\t\tmuted_reads = C_counter + c_counter;\n\t\tmut_freq = double(muted_reads)/double(coverage);\n\t\treturn mut_freq;\n\t}\n\tif(muted_in == 'G'){\n\t\tmuted_reads = G_counter + g_counter;\n\t\tmut_freq = double(muted_reads)/double(coverage);\n\t\treturn mut_freq;\n\t}\n\t\n}\n\nint compute_coverage(string ATCG_data){\n\tchar reference;\n\tint A_counter = 0;\n\tint a_counter = 0;\n\tint T_counter = 0;\n\tint t_counter = 0;\n\tint C_counter = 0;\n\tint c_counter = 0;\n\tint G_counter = 0;\n\tint g_counter = 0;\n\tint coverage = 0;\n\n\tstringstream ATCG_linestream(ATCG_data);\n\tATCG_linestream >> reference;\n\t\n\t//counters\n\tATCG_linestream >> A_counter; coverage += A_counter;\n\tATCG_linestream >> T_counter; coverage += T_counter;\n\tATCG_linestream >> C_counter; coverage += C_counter;\n\tATCG_linestream >> G_counter; coverage += G_counter;\n\tATCG_linestream >> a_counter; coverage += a_counter;\n\tATCG_linestream >> t_counter; coverage += t_counter;\n\tATCG_linestream >> c_counter; coverage += c_counter;\n\tATCG_linestream >> g_counter; coverage += g_counter;\n\t\n\treturn coverage;\n}\n\ndouble compute_mut_rate(double P_hat, double death_prob, int extant){\n\n\t// gen = log_{2*(1-death_prob)} extant\n\tfloat generations = log(extant)/log(2.*(1.-death_prob));\n\t\n\t//integral estimate with continuous time\n\tfloat attempts = (1. - death_prob*death_prob) * (\n\t\t\t\t( pow((2*(1-death_prob)), generations - 1.) - 1.) /\n\t\t\t  \tlog(2.*(1.- death_prob))\n\t\t\t  \t) + extant;\n\t\t\t  \t\t\t  \t\n\tdouble mut_rate = -1. *( log(1. - P_hat)/attempts);\n\t\n\treturn mut_rate;\n\n}\n\nbool endpoint_muted(double mut_freq, int total_coverage, int extant){\n\t/*Count base as muted if endpoint frequency \n\n\tf >= Cutoff(Coverage, f_min) e Coverage = TotCoverage/3\n\n\tcutoff (Coverage, f_min) = f_min + alpha/Sqrt[Coverage]\n\nbased on extant f_min and corresponding alphas are\n\n\tf_min = {1/8, 1/12, 1/16, 1/20, 1/24, 1/28, 1/32, 1/48, 1/75, 1/100}\n\n\talpha = {0.52, 0.45, 0.36, 0.32, 0.3, 0.28, 0.25, 0.2, 0.18, 0.15} \n*/\n\tassert( extant == 8 || extant == 12 || extant == 16 || extant == 20\n\t\t|| extant == 24 || extant == 28 || extant == 32 || extant == 48\n\t\t|| extant == 75 || extant == 100);\n\t\t \n\tdouble f_min = 0.;\n\tfloat coverage = float(total_coverage)/3.;\n\tdouble alpha = 0.;\n\t\n\tf_min = 1./double(extant);\n\t\n\tif (extant == 8){\n\t\talpha = 0.52;\n\t}\n\tif (extant == 12){\n\t\talpha = 0.45;\n\t}\n\t\n\tif (extant == 16){\n\t\talpha = 0.36;\n\t}\n\tif (extant == 20){\n\t\talpha = 0.32;\n\t}\n\tif (extant == 24){\n\t\talpha = 0.3;\n\t}\n\tif (extant == 28){\n\t\talpha = 0.28;\n\t}\n\tif (extant == 32){\n\t\talpha = 0.25;\n\t}\n\tif (extant == 48){\n\t\talpha = 0.2;\n\t}\n\t\n\tif (extant == 75){\n\t\talpha = 0.18;\n\t}\n\tif (extant == 100){\n\t\talpha = 0.15;\n\t}\n\t\n\tif ( mut_freq >= f_min + alpha/sqrt(coverage) ) {\n\t\t//muted\n\t\treturn true;\n\t} else {\n\t\t//not muted\n\t\treturn false;\n\t}\n}\n", "meta": {"hexsha": "0d8ae58aed230b9575660bd0691e58403cc4806a", "size": 24008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Endpoint_Brothers/Code/estimate_mu.cpp", "max_stars_repo_name": "PietroRivetti/LD-mut-rate", "max_stars_repo_head_hexsha": "50f40b3bfd8be61b1a2d420f9fc85aacdb544b81", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Endpoint_Brothers/Code/estimate_mu.cpp", "max_issues_repo_name": "PietroRivetti/LD-mut-rate", "max_issues_repo_head_hexsha": "50f40b3bfd8be61b1a2d420f9fc85aacdb544b81", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Endpoint_Brothers/Code/estimate_mu.cpp", "max_forks_repo_name": "PietroRivetti/LD-mut-rate", "max_forks_repo_head_hexsha": "50f40b3bfd8be61b1a2d420f9fc85aacdb544b81", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3557951482, "max_line_length": 150, "alphanum_fraction": 0.653907031, "num_tokens": 7083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4217583210624285}}
{"text": "#include <iostream>\n#include <experimental/filesystem>\n\nnamespace fs = std::experimental::filesystem;\n\n#include \"include.hh\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <iostream>\n#include <map>\n#include <string>\n\nusing namespace EMC;\nusing namespace std;\n\nnamespace EMC {\n\nenum task {\n    tNONE = 0,\n    ASSEMBLE,\n\tREBIN,\n    INVERT,\n\tREBIN_INVERT,\n\tDE_PILEUP,\n    SUBTRACT,\n\tMULTIPLY_RESPONSE_CURVE,\n    PRINT_STATS,\n\tAPPLY,\n\tFIT_VALUES\n};\n\nmap<string, task> taskNameMap = {\n    { \"assemble\", ASSEMBLE },\n    { \"rebin\", REBIN },\n    { \"invert\", INVERT},\n    { \"rebin_invert\", REBIN_INVERT},\n    { \"de_pileup\", DE_PILEUP},\n    { \"subtract\", SUBTRACT},\n    { \"multiply_resp_curve\", MULTIPLY_RESPONSE_CURVE},\n    { \"print_stats\", PRINT_STATS},\n    { \"apply\", APPLY },\n    { \"fit_values\", FIT_VALUES }\n};\n\n} /* namespace EMC */\n\nusing namespace boost::numeric;\n\nint main(int argc, char* argv[]) {\n    cout << endl << \"error-matrix-calculation v1 (c) Simon Michalke 2020\" << endl;\n\n\n    task todo = tNONE;\n    bool forceOverwrite = false;\n    string output;\n    string input;\n\n    string matrixFileName;\n\n    std::vector<double> inputBinCenters;\n    matrixType matType = mtNumber;\n    int countRate = -1;\n\n    double minRow = -1;\n    double minCol = -1;\n    double minRowBin = -1;\n    double minColBin = -1;\n    double maxRow = -1;\n    double maxCol = -1;\n\n    float rowErrorEst = -1;\n    float colErrorEst = -1;\n\n    double lowerBound = 0;\n\n    bool fail = false;\n\n\tfor (int argPos = 1; argPos < argc; argPos++) {\n\t\tif (argv[argPos][0] == '-') {\n\t\t\tswitch (argv[argPos][1]) {\n\t\t\tcase 't': // what task\n\t\t\t\targPos++;\n\t\t\t\tif (taskNameMap.find(argv[argPos]) == taskNameMap.end()) {\n\t\t\t\t\tcout << \"tasks not recognized!\" << endl;\n\t\t\t\t\tfail = true;\n\t\t\t\t} else {\n\t\t\t\t\ttodo = taskNameMap.at(argv[argPos]);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'f':\n\t\t\t\tforceOverwrite = true;\n\t\t\t\tbreak;\n\t\t\tcase 'i': {\n\t\t\t\targPos++;\n\t\t\t\tinput = argv[argPos];\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'o':\n\t\t\t\targPos++;\n\t\t\t\toutput = argv[argPos];\n\t\t\t\tbreak;\n\t\t\tcase 'b': {\n\t\t\t\targPos++;\n\t\t\t\tauto binVec = split(argv[argPos], ',');\n\t\t\t\tunsigned int i = 0;\n\t\t\t\tunsigned int binCount = binVec.size();\n\t\t\t\tdouble binIncrement = -1;\n\t\t\t\tfor (;i<binVec.size();i++) {\n\t\t\t\t\tif (binVec[i] == \"...\") {\n\t\t\t\t\t\tbinIncrement = inputBinCenters[i-1] - inputBinCenters[i-2];\n\t\t\t\t\t\tinputBinCenters.push_back(inputBinCenters[i-1] + binIncrement);\n\t\t\t\t\t\tbinCount = std::stod(binVec[i+1]) / (inputBinCenters[i-1] - inputBinCenters[i-2]) - 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tinputBinCenters.push_back(std::stod(binVec[i]));\n\t\t\t\t}\n\t\t\t\tfor (;i<binCount;i++) {\n\t\t\t\t\tinputBinCenters.push_back(inputBinCenters[i] + binIncrement);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'm': {\n\t\t\t\targPos++;\n\t\t\t\tauto maxStrVec = split(argv[argPos], ',');\n\t\t\t\tminRow = std::stod(maxStrVec[0]);\n\t\t\t\tminCol = std::stod(maxStrVec[1]);\n\t\t\t\tminRowBin = std::stod(maxStrVec[2]);\n\t\t\t\tminColBin = std::stod(maxStrVec[3]);\n\t\t\t\tmaxRow = std::stod(maxStrVec[4]);\n\t\t\t\tmaxCol = std::stod(maxStrVec[5]);\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'T':\n\t\t\t\targPos++;\n\t\t\t\tif (matrixTypeMap.find(argv[argPos]) == matrixTypeMap.end()) {\n\t\t\t\t\tcout << \"matrix type not recognized!\" << endl;\n\t\t\t\t\tfail = true;\n\t\t\t\t} else {\n\t\t\t\t\tmatType = matrixTypeMap.at(argv[argPos]);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'c':\n\t\t\t\targPos++;\n\t\t\t\tcountRate = std::stoi(argv[argPos]);\n\t\t\t\tbreak;\n\t\t\tcase 'l':\n\t\t\t\targPos++;\n\t\t\t\tlowerBound = std::stof(argv[argPos]);\n\t\t\t\tbreak;\n\t\t\tcase 'M':\n\t\t\t\targPos++;\n\t\t\t\tmatrixFileName = argv[argPos];\n\t\t\t\tbreak;\n\t\t\tcase 'd': {\n\t\t\t\targPos++;\n\t\t\t\tauto strVec = split(argv[argPos], ',');\n\t\t\t\trowErrorEst = std::stod(strVec[0]);\n\t\t\t\tcolErrorEst = std::stod(strVec[1]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tcout << \"unexpected flag in argument number \" << argPos << endl;\n\t\t\t\tfail = true;\n\t\t\t}\n\t\t} else {\n\t\t\tcout << \"expected \\\"-\\\" in argument number \" << argPos << endl;\n\t\t\tfail = true;\n\t\t}\n\t}\n\n    if (fail) {\n        cout << \"aborted\" << endl;\n        todo = tNONE;\n    }\n\n\tswitch (todo) {\n\tcase ASSEMBLE: {\n\t\tcout << \"assembling matrix\" << endl;\n\t\tint retVal = assemble(forceOverwrite, input, output, inputBinCenters,\n\t\t\t\tmatType, countRate);\n\t\tcout << \"finished with status \" << retVal << endl;\n\t\tbreak;\n\t}\n\tcase REBIN: {\n\t\tcout << \"rebinning matrix\" << endl;\n\t\tint retVal = rebin(forceOverwrite, input, output, countRate, minRow,\n\t\t\t\tminCol, minRowBin, minColBin, maxRow, maxCol);\n\t\tcout << \"finished with status \" << retVal << endl;\n\t\tbreak;\n\t}\n\tcase INVERT: {\n\t\tcout << \"inverting matrix\" << endl;\n\t\tint retVal = invert(forceOverwrite, input, output);\n\t\tcout << \"finished with status \" << retVal << endl;\n\t\tbreak;\n\t}\n\tcase REBIN_INVERT: {\n\t\tcout << \"rebinning and inverting matrix\" << endl;\n\t\tint retVal = rebin_invert(forceOverwrite, input, output, countRate, minRow,\n\t\t\t\tminCol, minRowBin, minColBin, maxRow, maxCol, rowErrorEst, colErrorEst);\n\t\tcout << \"finished with status \" << retVal << endl;\n\t\tbreak;\n\t}\n\tcase DE_PILEUP: {\n\t\tcout << \"reversing pileup\" << endl;\n\t\tint retVal = de_pileup(forceOverwrite, input, output, countRate, lowerBound);\n\t\tcout << \"finished with status \" << retVal << endl;\n\t\tbreak;\n\t}\n\tcase SUBTRACT: {\n\t\tcout << \"subtracting matrix\" << endl;\n\t\tint retVal = subtract(forceOverwrite, input, output, matrixFileName);\n\t\tcout << \"finished with status \" << retVal << endl;\n\t\tbreak;\n\t}\n\tcase MULTIPLY_RESPONSE_CURVE: {\n\t\tcout << \"multiply-response-curving matrix\" << endl;\n\t\tint retVal = multiply_resp_curve(forceOverwrite, input, output, matrixFileName);\n\t\tcout << \"finished with status \" << retVal << endl;\n\t\tbreak;\n\t}\n\tcase PRINT_STATS: {\n\t\tcout << \"printing matrix stats matrix\" << endl;\n\t\tint retVal = print_stats(matrixFileName);\n\t\tcout << \"finished with status \" << retVal << endl;\n\t\tbreak;\n\t}\n\tcase APPLY: {\n\t\tcout << \"applying matrix\" << endl;\n\t\tint retVal = apply(forceOverwrite, input, output, matrixFileName);\n\t\tcout << \"finished with status \" << retVal << endl;\n\t\tbreak;\n\t}\n\tcase FIT_VALUES: {\n\t\tcout << \"fitting matrix parameters\" << endl;\n\t\tint retVal = fit_values(input, output, countRate, minRow,\n\t\t\t\tminCol, minRowBin, minColBin, maxRow, maxCol);\n\t\tcout << \"finished with status \" << retVal << endl;\n\t\tbreak;\n\t}\n\tcase tNONE:\n    default:\n        cout << \"\" << endl << endl;\n        cout << \" supported general arguments:\" << endl;\n        cout << \"   -t [ de_pileup | assemble | rebin | invert | rebin_invert | apply | print_stats | fit_values ]\" << endl;\n        cout << \"      specifies what task is being executed\" << endl;\n        cout << \"      should be specified first\" << endl;\n        cout << \"   -f overwrite output files / directories, deletes target files before writing\" << endl;\n        cout << \"   -i <filename>\" << endl;\n        cout << \"      input file name\" << endl;\n        cout << \"   -o <filename>\" << endl;\n        cout << \"      output file name\" << endl << endl;\n        cout << \"   In case of a vector the columns are expected to be bin center, value, value error\" << endl;\n        cout << \"   with space character for spacing\" << endl;\n        cout << \" arguments for specific tasks:\" << endl;\n        cout << \"   de_pileup: reconstructs pileup numerically\" << endl;\n        cout << \"     -c <integer>\" << endl;\n        cout << \"        total pixel count\" << endl;\n        cout << \"     -l <float>\" << endl;\n        cout << \"        up to this energy counts are set to 0\" << endl;\n        cout << \"   assemble: assembles a matrix based on putting spectrums into columns, output bins determined by input spectrum\" << endl;\n        cout << \"     -i <filename format string>\" << endl;\n        cout << \"        input file name. String that will be formatted using sprintf with data passed by -b\" << endl;\n        cout << \"        expects 'bin_center counts' in each line\" << endl;\n        cout << \"     -b <bin0>,<bin1>,...\" << endl;\n        cout << \"        list of input bin centers (floating point possible). Passed to -i via sprintf\" << endl;\n        cout << \"        for evently spaced bins e.g. 1,2,...,100 is also possible\" << endl;\n        cout << \"     -T <type>\" << endl;\n        cout << \"        output type; possible values are 'number', 'probability' and 'density'\" << endl;\n        cout << \"        in case of density bin width is determined based on the bin width in input files\" << endl;\n        cout << \"     -c <integer>\" << endl;\n        cout << \"        total events, count rate for normalization\" << endl;\n        cout << \"   rebin: rebins a matrix by merging bins in order to increase statistical significance\" << endl;\n        cout << \"     -c <integer>\" << endl;\n        cout << \"        dimension of output square matrix\" << endl;\n        cout << \"     -m <minRow><minCol><minRowBin><minColBin><maxRow><maxCol>\" << endl;\n        cout << \"        row and column bin parameters, float\" << endl;\n        cout << \"   rebin_invert: rebins a matrix and inverts it. Estimates errors as well.\" << endl;\n        cout << \"     -c <integer>\" << endl;\n        cout << \"        dimension of output square matrix\" << endl;\n        cout << \"     -m <minRow><minCol><minRowBin><minColBin><maxRow><maxCol>\" << endl;\n        cout << \"        row and column bin parameters, float\" << endl;\n        cout << \"     -d <row Error, float>,<column Error, float>\" << endl;\n        cout << \"        estimate error based on row and column error.\" << endl;\n        cout << \"   invert: inverts a matrix\" << endl;\n        cout << \"   subtract: subtracts spectra\" << endl;\n        cout << \"        uses <filelane>.cntr and <filelane>.step for input, output and filename of subtracted spectrum.\" << endl;\n        cout << \"     -M <filename>\" << endl;\n        cout << \"        filename of the spectrum that will be subtracted\" << endl;\n        cout << \"   multiply_resp_curve: scales spectrum with response curve\" << endl;\n        cout << \"        uses <filelane>.cntr and <filelane>.step for input and output\" << endl;\n        cout << \"     -M <filename>\" << endl;\n        cout << \"        filename of the transmission curve\" << endl;\n        cout << \"        this is assumed to be more dense than the input spectrum\" << endl;\n        cout << \"   print_stats: inverts a matrix\" << endl;\n        cout << \"     -M <filename>\" << endl;\n        cout << \"        filename of the matriy\" << endl;\n        cout << \"   apply: inverts a matrix; input and output are spectrum files\" << endl;\n        cout << \"        first column is expected to be bin center and second the counts in that bin\" << endl;\n        cout << \"        vector will be rebinned and rescaled to matrix dimensions\" << endl;\n        cout << \"        output is bin center and count rate\" << endl;\n        cout << \"     -M <filename>\" << endl;\n        cout << \"        filename of the matrix\" << endl;\n        cout << \"   fit_values: optimizes rebinning based on inverted matrix error metric\" << endl;\n        cout << \"               output is the base filename for the rebinned (.rebin.mat) and inverted (.rebin.inverted.mat) matrix\" << endl;\n        cout << \"               these matrices will be overwritten multiple times!\" << endl;\n        cout << \"     -c <integer>\" << endl;\n        cout << \"        dimension of output square matrix\" << endl;\n        cout << \"     -m <minRow><minCol><minRowBin><minColBin><maxRow><maxCol>\" << endl;\n        cout << \"        initial row and column bin parameters; minCol and maxCol will stay constant\" << endl;\n        cout << endl;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "55f2e58dc2368be93d8990d0069a0f3b3200cf0f", "size": 11403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "pixel-toolbox/error-matrix-calculation", "max_stars_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "pixel-toolbox/error-matrix-calculation", "max_issues_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "pixel-toolbox/error-matrix-calculation", "max_forks_repo_head_hexsha": "29539c9950552f64648932747ab4c07a32004766", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.858490566, "max_line_length": 141, "alphanum_fraction": 0.5874769797, "num_tokens": 3082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4216842814709032}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2021 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n\n#include \"SiconosVector.hpp\"\n#include \"SimpleMatrix.hpp\"\n#include \"BlockMatrixIterators.hpp\"\n#include \"BlockMatrix.hpp\"\n#include \"BlockVector.hpp\"\n\n#include \"SiconosAlgebra.hpp\"\n\n#include \"SiconosAlgebraProd.hpp\" // for subprod\n#include \"SiconosException.hpp\"\nusing namespace Siconos;\n\n\n\nvoid subprod(const SiconosMatrix& A, const SiconosVector& x, SiconosVector& y, const Index& coord, bool init)\n{\n  // To compute subY = subA * subX in an \"optimized\" way (in comparison with y = prod(A,x) )\n  // or subY += subA*subX if init = false.\n\n  // coord is [r0A r1A c0A c1A r0x r1x r0y r1y]\n  //\n  // subA is the sub-matrix of A, for row numbers between r0A and r1A-1 and columns between c0A and c1A-1.\n  // The same for x and y with rix and riy.\n\n  // Check dims\n  unsigned int rowA = coord[1] - coord[0];\n  unsigned int colA = coord[3] - coord[2];\n  unsigned int dimX = coord[5] - coord[4];\n  unsigned int dimY = coord[7] - coord[6];\n  if(colA != dimX)\n    THROW_EXCEPTION(\"inconsistent sizes between A and x.\");\n\n  if(rowA != dimY)\n    THROW_EXCEPTION(\"inconsistent sizes between A and y.\");\n\n  if(dimX > x.size() || dimY > y.size() || rowA > A.size(0) || colA > A.size(1))\n    THROW_EXCEPTION(\"input index too large.\");\n\n  Siconos::UBLAS_TYPE numA = A.num();\n  Siconos::UBLAS_TYPE numX = x.num();\n  Siconos::UBLAS_TYPE numY = y.num();\n\n  if(numA == Siconos::BLOCK)   // If A,x or y is Block\n    THROW_EXCEPTION(\"not yet implemented for A block matrices.\");\n\n  if(numA == Siconos::ZERO)  // A = 0\n  {\n    if(init)\n    {\n      if(numY == Siconos::DENSE)\n        ublas::subrange(*y.dense(), coord[6], coord[7]) *= 0.0;\n      else //if(numY==Siconos::SPARSE)\n        ublas::subrange(*y.sparse(), coord[6], coord[7]) *= 0.0;\n    }\n    //else nothing\n  }\n  else if(numA == Siconos::IDENTITY)  // A = identity\n  {\n    if(!init)\n      ublas::subrange(*y.dense(), coord[6], coord[7]) += ublas::subrange(*x.dense(), coord[4], coord[5]);\n    else\n    {\n      // if x and y do not share memory (ie are different objects)\n      if(&x != &y)\n        noalias(ublas::subrange(*y.dense(), coord[6], coord[7])) = ublas::subrange(*x.dense(), coord[4], coord[5]);\n\n      // else nothing\n    }\n  }\n\n  else // A is not 0 or identity\n  {\n    {\n      if(init)\n      {\n        if(&x != &y)  // if no common memory between x and y.\n        {\n          if(numX == Siconos::DENSE)\n          {\n            ublas::vector_range<DenseVect> subX(*x.dense(), ublas::range(coord[4], coord[5]));\n\n            if(numY != Siconos::DENSE)\n              THROW_EXCEPTION(\"y (output) must be a dense vector.\");\n            ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[6], coord[7]));\n\n            if(numA == Siconos::DENSE)\n            {\n              ublas::matrix_range<DenseMat> subA(*A.dense(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) = ublas::prod(subA, subX);\n            }\n            else if(numA == Siconos::TRIANGULAR)\n            {\n              ublas::matrix_range<TriangMat> subA(*A.triang(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) = ublas::prod(subA, subX);\n            }\n            else if(numA == Siconos::SYMMETRIC)\n            {\n              ublas::matrix_range<SymMat> subA(*A.sym(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) = ublas::prod(subA, subX);\n            }\n            else if(numA == Siconos::SPARSE)\n            {\n#ifdef BOOST_LIMITATION\n              THROW_EXCEPTION(\"ublas::matrix_range<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n              ublas::matrix_range<SparseMat> subA(*A.sparse(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) = ublas::prod(subA, subX);\n#endif\n            }\n            else //if(numA==Siconos::BANDED)\n            {\n              ublas::matrix_range<BandedMat> subA(*A.banded(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) = ublas::prod(subA, subX);\n            }\n          }\n          else //if(numX == Siconos::SPARSE)\n          {\n            ublas::vector_range<SparseVect> subX(*x.sparse(), ublas::range(coord[4], coord[5]));\n            if(numY != Siconos::DENSE && numA != Siconos::SPARSE)\n              THROW_EXCEPTION(\"y (output) must be a dense vector.\");\n\n            if(numA == Siconos::DENSE)\n            {\n              ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[6], coord[7]));\n              ublas::matrix_range<DenseMat> subA(*A.dense(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) = ublas::prod(subA, subX);\n            }\n            else if(numA == Siconos::TRIANGULAR)\n            {\n              ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[6], coord[7]));\n              ublas::matrix_range<TriangMat> subA(*A.triang(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) = ublas::prod(subA, subX);\n            }\n            else if(numA == Siconos::SYMMETRIC)\n            {\n              ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[6], coord[7]));\n              ublas::matrix_range<SymMat> subA(*A.sym(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) = ublas::prod(subA, subX);\n            }\n            else if(numA == Siconos::SPARSE)\n            {\n#ifdef BOOST_LIMITATION\n              THROW_EXCEPTION(\"ublas::matrix_range<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n              ublas::matrix_range<SparseMat> subA(*A.sparse(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n\n              if(numY == Siconos::DENSE)\n              {\n                ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[6], coord[7]));\n                noalias(subY) = ublas::prod(subA, subX);\n              }\n              else\n              {\n                ublas::vector_range<SparseVect> subY(*y.sparse(), ublas::range(coord[6], coord[7]));\n                noalias(subY) = ublas::prod(subA, subX);\n              }\n#endif\n            }\n            else //if(numA==Siconos::BANDED)\n            {\n              ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[6], coord[7]));\n              ublas::matrix_range<BandedMat> subA(*A.banded(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) = ublas::prod(subA, subX);\n            }\n          }\n        }\n        else // if x and y are the same object => alias\n        {\n          if(numX == Siconos::DENSE)\n          {\n            ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[4], coord[5]));\n            if(numA == Siconos::DENSE)\n            {\n              ublas::matrix_range<DenseMat> subA(*A.dense(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY = ublas::prod(subA, subY);\n            }\n            else if(numA == Siconos::TRIANGULAR)\n            {\n              ublas::matrix_range<TriangMat> subA(*A.triang(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY = ublas::prod(subA, subY);\n            }\n            else if(numA == Siconos::SYMMETRIC)\n            {\n              ublas::matrix_range<SymMat> subA(*A.sym(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY = ublas::prod(subA, subY);\n            }\n            else if(numA == Siconos::SPARSE)\n            {\n#ifdef BOOST_LIMITATION\n              THROW_EXCEPTION(\"ublas::matrix_range<SparseMat> and vector_range<SparseVect> does not exist for your boost distribution and your architecture.\");\n#else\n              ublas::matrix_range<SparseMat> subA(*A.sparse(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY = ublas::prod(subA, subY);\n#endif\n            }\n            else //if(numA==Siconos::BANDED)\n            {\n              ublas::matrix_range<BandedMat> subA(*A.banded(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY = ublas::prod(subA, subY);\n            }\n          }\n          else //if(numX == Siconos::SPARSE)\n          {\n            ublas::vector_range<SparseVect> subY(*y.sparse(), ublas::range(coord[4], coord[5]));\n            if(numA == Siconos::DENSE)\n            {\n              ublas::matrix_range<DenseMat> subA(*A.dense(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY = ublas::prod(subA, subY);\n            }\n            else if(numA == Siconos::TRIANGULAR)\n            {\n              ublas::matrix_range<TriangMat> subA(*A.triang(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY = ublas::prod(subA, subY);\n            }\n            else if(numA == Siconos::SYMMETRIC)\n            {\n              ublas::matrix_range<SymMat> subA(*A.sym(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY = ublas::prod(subA, subY);\n            }\n            else if(numA == Siconos::SPARSE)\n            {\n#ifdef BOOST_LIMITATION\n              THROW_EXCEPTION(\"ublas::matrix_range<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n              ublas::matrix_range<SparseMat> subA(*A.sparse(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY = ublas::prod(subA, subY);\n#endif\n            }\n            else //if(numA==Siconos::BANDED)\n            {\n              ublas::matrix_range<BandedMat> subA(*A.banded(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY = ublas::prod(subA, subY);\n            }\n          }\n        }\n      }\n      else // += case\n      {\n        if(&x != &y)  // if no common memory between x and y.\n        {\n          if(numX == Siconos::DENSE)\n          {\n            ublas::vector_range<DenseVect> subX(*x.dense(), ublas::range(coord[4], coord[5]));\n\n            if(numY != Siconos::DENSE)\n              THROW_EXCEPTION(\"y (output) must be a dense vector.\");\n            ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[6], coord[7]));\n\n            if(numA == Siconos::DENSE)\n            {\n              ublas::matrix_range<DenseMat> subA(*A.dense(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) += ublas::prod(subA, subX);\n            }\n            else if(numA == Siconos::TRIANGULAR)\n            {\n              ublas::matrix_range<TriangMat> subA(*A.triang(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) += ublas::prod(subA, subX);\n            }\n            else if(numA == Siconos::SYMMETRIC)\n            {\n              ublas::matrix_range<SymMat> subA(*A.sym(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) += ublas::prod(subA, subX);\n            }\n            else if(numA == Siconos::SPARSE)\n            {\n#ifdef BOOST_LIMITATION\n              THROW_EXCEPTION(\"ublas::matrix_range<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n              ublas::matrix_range<SparseMat> subA(*A.sparse(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) += ublas::prod(subA, subX);\n#endif\n            }\n            else //if(numA==Siconos::BANDED)\n            {\n              ublas::matrix_range<BandedMat> subA(*A.banded(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) += ublas::prod(subA, subX);\n            }\n          }\n          else //if(numX == Siconos::SPARSE)\n          {\n            ublas::vector_range<SparseVect> subX(*x.sparse(), ublas::range(coord[4], coord[5]));\n            if(numY != Siconos::DENSE && numA != Siconos::SPARSE)\n              THROW_EXCEPTION(\"y (output) must be a dense vector.\");\n\n            if(numA == Siconos::DENSE)\n            {\n              ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[6], coord[7]));\n              ublas::matrix_range<DenseMat> subA(*A.dense(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) += ublas::prod(subA, subX);\n            }\n            else if(numA == Siconos::TRIANGULAR)\n            {\n              ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[6], coord[7]));\n              ublas::matrix_range<TriangMat> subA(*A.triang(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) += ublas::prod(subA, subX);\n            }\n            else if(numA == Siconos::SYMMETRIC)\n            {\n              ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[6], coord[7]));\n              ublas::matrix_range<SymMat> subA(*A.sym(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) += ublas::prod(subA, subX);\n            }\n            else if(numA == Siconos::SPARSE)\n            {\n#ifdef BOOST_LIMITATION\n              THROW_EXCEPTION(\"ublas::matrix_range<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n              ublas::matrix_range<SparseMat> subA(*A.sparse(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              if(numY == Siconos::DENSE)\n              {\n                ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[6], coord[7]));\n                noalias(subY) += ublas::prod(subA, subX);\n              }\n              else\n              {\n                ublas::vector_range<SparseVect> subY(*y.sparse(), ublas::range(coord[6], coord[7]));\n                noalias(subY) += ublas::prod(subA, subX);\n              }\n#endif\n            }\n            else //if(numA==Siconos::BANDED)\n            {\n              ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[6], coord[7]));\n              ublas::matrix_range<BandedMat> subA(*A.banded(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              noalias(subY) += ublas::prod(subA, subX);\n            }\n          }\n        }\n        else // if x and y are the same object => alias\n        {\n          if(numX == Siconos::DENSE)\n          {\n            ublas::vector_range<DenseVect> subY(*y.dense(), ublas::range(coord[4], coord[5]));\n            if(numA == Siconos::DENSE)\n            {\n              ublas::matrix_range<DenseMat> subA(*A.dense(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY += ublas::prod(subA, subY);\n            }\n            else if(numA == Siconos::TRIANGULAR)\n            {\n              ublas::matrix_range<TriangMat> subA(*A.triang(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY += ublas::prod(subA, subY);\n            }\n            else if(numA == Siconos::SYMMETRIC)\n            {\n              ublas::matrix_range<SymMat> subA(*A.sym(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY += ublas::prod(subA, subY);\n            }\n            else if(numA == Siconos::SPARSE)\n            {\n#ifdef BOOST_LIMITATION\n              THROW_EXCEPTION(\"ublas::matrix_range<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n              ublas::matrix_range<SparseMat> subA(*A.sparse(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY += ublas::prod(subA, subY);\n#endif\n            }\n            else //if(numA==Siconos::BANDED)\n            {\n              ublas::matrix_range<BandedMat> subA(*A.banded(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY += ublas::prod(subA, subY);\n            }\n          }\n          else //if(numX == Siconos::SPARSE)\n          {\n            ublas::vector_range<SparseVect> subY(*y.sparse(), ublas::range(coord[4], coord[5]));\n            if(numA == Siconos::DENSE)\n            {\n              ublas::matrix_range<DenseMat> subA(*A.dense(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY += ublas::prod(subA, subY);\n            }\n            else if(numA == Siconos::TRIANGULAR)\n            {\n              ublas::matrix_range<TriangMat> subA(*A.triang(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY += ublas::prod(subA, subY);\n            }\n            else if(numA == Siconos::SYMMETRIC)\n            {\n              ublas::matrix_range<SymMat> subA(*A.sym(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY += ublas::prod(subA, subY);\n            }\n            else if(numA == Siconos::SPARSE)\n            {\n#ifdef BOOST_LIMITATION\n              THROW_EXCEPTION(\"ublas::matrix_range<SparseMat> does not exist for your boost distribution and your architecture.\");\n#else\n              ublas::matrix_range<SparseMat> subA(*A.sparse(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY += ublas::prod(subA, subY);\n#endif\n            }\n            else //if(numA==Siconos::BANDED)\n            {\n              ublas::matrix_range<BandedMat> subA(*A.banded(), ublas::range(coord[0], coord[1]), ublas::range(coord[2], coord[3]));\n              subY += ublas::prod(subA, subY);\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid subprod(const SiconosMatrix& A, const BlockVector& x, SiconosVector& y, const Index& coord, bool init)\n{\n  assert(!(A.isFactorized()) && \"A is Factorized in prod !!\");\n\n  // Number of the subvector of x that handles element at position coord[4]\n  std::size_t firstBlockNum = x.getNumVectorAtPos(coord[4]);\n  // Number of the subvector of x that handles element at position coord[5]\n  unsigned int lastBlockNum = x.getNumVectorAtPos(coord[5]);\n  Index subCoord = coord;\n  SPC::SiconosVector tmp = x.vector(firstBlockNum);\n  std::size_t subSize =  tmp->size(); // Size of the sub-vector\n  const SP::Index xTab = x.tabIndex();\n  if(firstBlockNum != 0)\n  {\n    subCoord[4] -= (*xTab)[firstBlockNum - 1];\n    subCoord[5] =  std::min(coord[5] - (*xTab)[firstBlockNum - 1], subSize);\n  }\n  else\n    subCoord[5] =  std::min(coord[5], subSize);\n\n  if(firstBlockNum == lastBlockNum)\n  {\n    subprod(A, *tmp, y, subCoord, init);\n  }\n  else\n  {\n    unsigned int xPos = 0 ; // Position in x of the current sub-vector of x\n    bool firstLoop = true;\n    subCoord[3] = coord[2] + subCoord[5] - subCoord[4];\n    for(VectorOfVectors::const_iterator it = x.begin(); it != x.end(); ++it)\n    {\n      if((*it)->num() == Siconos::BLOCK)\n        THROW_EXCEPTION(\"not yet implemented for x block of blocks ...\");\n      if(xPos >= firstBlockNum && xPos <= lastBlockNum)\n      {\n        tmp = x.vector(xPos);\n        if(firstLoop)\n        {\n          subprod(A, *tmp, y, subCoord, init);\n          firstLoop = false;\n        }\n        else\n        {\n          subCoord[2] += subCoord[5] - subCoord[4]; // !! old values for 4 and 5\n          subSize = tmp->size();\n          subCoord[4] = 0;\n          subCoord[5] = std::min(coord[5] - (*xTab)[xPos - 1], subSize);\n          subCoord[3] = subCoord[2] + subCoord[5] - subCoord[4];\n          subprod(A, *tmp, y, subCoord, false);\n        }\n      }\n      xPos++;\n    }\n  }\n}\n", "meta": {"hexsha": "733bb01389e45e54896d51f12df5726ce1eca293", "size": 20378, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/SiconosAlgebraSubProd.cpp", "max_stars_repo_name": "BuildJet/siconos", "max_stars_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "kernel/src/utils/SiconosAlgebra/SiconosAlgebraSubProd.cpp", "max_issues_repo_name": "BuildJet/siconos", "max_issues_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "kernel/src/utils/SiconosAlgebra/SiconosAlgebraSubProd.cpp", "max_forks_repo_name": "BuildJet/siconos", "max_forks_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 42.5427974948, "max_line_length": 159, "alphanum_fraction": 0.5488271666, "num_tokens": 5774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.42165036247900595}}
{"text": "#include <cassert>\n#include <iostream>\n#include <boost/static_assert.hpp>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_same.hpp>\n\ntemplate <typename V1, typename V2> class vector_sum;\n\ntemplate <typename T>\nclass vector \n{\n    void check_size(int that_size) const { assert(my_size == that_size); }\n    void check_index(int i) const { assert(i >= 0 && i < my_size); }\n  public:\n    typedef T    value_type;\n\n    explicit vector(int size)\n      : my_size(size), data( new T[my_size] )\n    {}\n\n    vector()\n      : my_size(0), data(0)\n    {}\n\n    vector( const vector& that )\n      : my_size(that.my_size), data( new T[my_size] )\n    {\n\tfor (int i= 0; i < my_size; ++i)\n\t    data[i]= that.data[i];\n    }\n\n    ~vector() { if (data) delete [] data ; }\n\n    template <typename Src>\n    vector& operator=( const Src& that ) \n    {\n\tcheck_size(that.size());\n\tfor (int i= 0; i < my_size; ++i)\n\t    data[i]= that[i];\n\treturn *this;\n    }\n\n    int size() const { return my_size ; }\n\n    const T& operator[]( int i ) const \n    {\n\tcheck_index(i);\n\treturn data[i];\n    }\n\t\t     \n    T& operator[]( int i ) \n    {\n\tcheck_index(i);\n\treturn data[i] ;\n    }\n\n  private:\n    int   my_size ;\n    T*    data ;\n};\n\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& os, const vector<T>& v)\n{\n  os << '[';\n  for (int i= 0; i < v.size(); ++i) os << v[i] << ',';\n  os << ']';\n  return os ;\n}\n\ntemplate <typename V1, typename V2>\nclass vector_sum\n{\n  public:\n    typedef typename V1::value_type value_type;\n    BOOST_STATIC_ASSERT((boost::is_same<typename V2::value_type, value_type>::value));\n\n    vector_sum(const V1& v1, const V2& v2) : v1(v1), v2(v2) \n    {\n\tassert(v1.size() == v2.size());\n    }\n\n    int size() const { return v1.size(); }\n\n    value_type operator[](int i) const { return v1[i] + v2[i]; }\n\n  private:\n    const V1 &v1;\n    const V2 &v2;\n};\n\ntemplate <typename  V1, typename V2>\n// typename boost::enable_if_c<is_vector<V1>::value && is_vector<V2>::value, vector_sum<V1, V2> >::type\nvector_sum<V1, V2> \ninline operator+( const V1& x, const V2& y ) \n{\n    return vector_sum<V1, V2>(x, y) ;\n}\n\n\n\n\n\nint main() \n{\n\n    vector<float> v( 4 ), w(4), x(4), y(4)  ;\n    v[0]= v[1]= 1.0; v[2]= 2.0 ; v[3] = -3.0 ;\n    w[0]= w[1]= 1.3; w[2]= 2.5 ; w[3] = -13.0 ;\n    x[0]= x[1]= 1.0; x[2]= 2.0 ; x[3] = 3.0 ;\n\n    std::cout << \"v = \" << v << std::endl ;\n\n    y= v + w + x;\n    std::cout << \"y = \" << y << std::endl ;\n\n    return 0 ;\n}\n", "meta": {"hexsha": "c9af1a3dc923fd01801f4e4ac379840f198c0a19", "size": 2456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DMCpp/GottschlingRepo/c++03/vector_expression_test.cpp", "max_stars_repo_name": "tzaffi/cpp", "max_stars_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-12-27T14:35:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-31T14:28:17.000Z", "max_issues_repo_path": "DMCpp/GottschlingRepo/c++03/vector_expression_test.cpp", "max_issues_repo_name": "tzaffi/cpp", "max_issues_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2017-12-07T14:54:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-28T02:14:07.000Z", "max_forks_repo_path": "DMCpp/GottschlingRepo/c++03/vector_expression_test.cpp", "max_forks_repo_name": "tzaffi/cpp", "max_forks_repo_head_hexsha": "43d99e70d8fa712f90ea0f6147774e4e0f2b11da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-01-04T13:40:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-02T12:49:21.000Z", "avg_line_length": 20.4666666667, "max_line_length": 103, "alphanum_fraction": 0.5602605863, "num_tokens": 808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4216503624790059}}
{"text": "#include \"cru/platform/GraphicsBase.hpp\"\n#include \"cru/platform/bootstrap/Bootstrap.hpp\"\n#include \"cru/platform/graphics/Factory.hpp\"\n#include \"cru/platform/graphics/Painter.hpp\"\n#include \"cru/platform/gui/UiApplication.hpp\"\n#include \"cru/platform/gui/Window.hpp\"\n\n#include <dlib/matrix.h>\n#include <dlib/numeric_constants.h>\n#include <cmath>\n\nusing cru::platform::Point;\n\nusing matrix14 = dlib::matrix<float, 1, 4>;\nusing matrix13 = dlib::matrix<float, 1, 3>;\nusing matrix44 = dlib::matrix<float, 4, 4>;\n\nmatrix44 Identity() {\n  matrix44 m;\n  m = dlib::identity_matrix<float, 4>();\n  return m;\n}\n\nmatrix44 T1(float a, float b, float c) {\n  auto m = Identity();\n\n  m(0, 3) = -a;\n  m(1, 3) = -b;\n  m(2, 3) = -c;\n\n  return m;\n}\n\nmatrix44 T2(float theta) {\n  auto m = Identity();\n\n  m(0, 0) = -std::cos(theta);\n  m(0, 2) = -std::sin(theta);\n  m(2, 0) = std::sin(theta);\n  m(2, 2) = -std::cos(theta);\n\n  return m;\n}\n\nmatrix44 T3(float phi) {\n  auto m = Identity();\n\n  m(1, 1) = std::sin(phi);\n  m(1, 2) = -std::cos(phi);\n  m(2, 1) = std::cos(phi);\n  m(2, 2) = std::sin(phi);\n\n  return m;\n}\n\nmatrix44 T4(float alpha) {\n  auto m = Identity();\n\n  m(0, 0) = std::cos(alpha);\n  m(1, 0) = std::sin(alpha);\n  m(0, 1) = -std::sin(alpha);\n  m(1, 1) = std::cos(alpha);\n\n  return m;\n}\n\nmatrix44 T5() {\n  auto m = Identity();\n\n  m(0, 0) = -1;\n\n  return m;\n}\n\nstruct Args {\n  float a;\n  float b;\n  float c;\n  float theta;\n  float phi;\n  float alpha;\n};\n\nmatrix44 Tv(Args args) {\n  return T1(args.a, args.b, args.c) * T2(args.theta) * T3(args.phi) *\n         T4(args.alpha) * T5();\n}\n\nmatrix14 Transform(matrix14 point, Args args) { return point * Tv(args); }\n\nmatrix14 Transform(matrix13 point, Args args) {\n  return matrix14{point(0), point(1), point(2), 1} * Tv(args);\n}\n\nPoint TransformTo2D(matrix14 point, float d) {\n  return Point{point(1), point(2)};\n}\n\nconst float length = 100;\n\nmatrix13 points[] = {\n    {0, 0, 0},\n    {length, 0, 0},\n    {length, 0, 0},\n    {length, length, 0},\n    {length, length, 0},\n    {0, length, 0},\n    {0, length, 0},\n    {0, 0, 0},\n    {0, 0, 0},\n    {0, 0, length},\n    {length, 0, 0},\n    {length, 0, length},\n    {length, length, 0},\n    {length, length, length},\n    {0, length, 0},\n    {0, length, length},\n    {0, 0, length},\n    {length, 0, length},\n    {length, 0, length},\n    {length, length, length},\n    {length, length, length},\n    {0, length, length},\n    {0, length, length},\n    {0, 0, length},\n};\n\nconst float pi = static_cast<float>(dlib::pi);\n\nArgs args{30, 40, 50, pi / 3.f, pi / 4.f, pi / 5.f};\n\nint main() {\n  std::vector<Point> points2d;\n\n  for (auto p : points) {\n    auto point2d = TransformTo2D(Transform(std::move(p), args), length);\n    points2d.push_back(point2d);\n  }\n\n  auto application = cru::platform::bootstrap::CreateUiApplication();\n  auto window = application->CreateWindow();\n\n  auto brush = application->GetGraphicsFactory()->CreateSolidColorBrush(\n      cru::platform::colors::black);\n\n  window->SetClientSize(cru::platform::Size(400, 400));\n\n  window->PaintEvent()->AddHandler([window, &brush, points2d](nullptr_t) {\n    auto painter = window->BeginPaint();\n    painter->PushState();\n    painter->ConcatTransform(cru::platform::Matrix::Translation(200, 200));\n    for (int i = 0; i < points2d.size(); i += 2) {\n      painter->DrawLine(points2d[i], points2d[i + 1], brush.get(), 1.f);\n    }\n    painter->PopState();\n  });\n\n  window->SetVisibility(cru::platform::gui::WindowVisibilityType::Show);\n\n  return application->Run();\n}\n", "meta": {"hexsha": "04f7edb76f8dc88c9a3a2f4aeea3ec26a63d7ad4", "size": 3489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/graphics_experiments/4.cpp", "max_stars_repo_name": "crupest/cru", "max_stars_repo_head_hexsha": "3c3a08a02a0f8fc56dc2da3374f025d4fdaf62c5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T11:43:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-30T11:43:03.000Z", "max_issues_repo_path": "demos/graphics_experiments/4.cpp", "max_issues_repo_name": "crupest/cru", "max_issues_repo_head_hexsha": "3c3a08a02a0f8fc56dc2da3374f025d4fdaf62c5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2021-08-22T12:55:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T15:01:29.000Z", "max_forks_repo_path": "demos/graphics_experiments/4.cpp", "max_forks_repo_name": "crupest/cru", "max_forks_repo_head_hexsha": "3c3a08a02a0f8fc56dc2da3374f025d4fdaf62c5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.537037037, "max_line_length": 75, "alphanum_fraction": 0.6064775007, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.42162074465440014}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#ifndef IONICLIQUID_HPP\n#define IONICLIQUID_HPP\n\n#include <cmath>\n#include <iosfwd>\n#include <vector>\n\n#include \"Config.hpp\"\n\n#include <Eigen/Core>\n\nclass Element;\n\n#include \"DerivativeTypes.hpp\"\n#include \"DerivativeUtils.hpp\"\n#include \"bi_operators/IntegratorForward.hpp\"\n#include \"GreensFunction.hpp\"\n#include \"dielectric_profile/Yukawa.hpp\"\n\n/*! \\file IonicLiquid.hpp\n *  \\class IonicLiquid\n *  \\brief Green's functions for ionic liquid, described by the linearized Poisson-Boltzmann equation.\n *  \\author Luca Frediani, Roberto Di Remigio\n *  \\date 2013-2015\n *  \\tparam DerivativeTraits evaluation strategy for the function and its derivatives\n *  \\tparam IntegratorPolicy policy for the calculation of the matrix represenation of S and D\n */\n\ntemplate <typename DerivativeTraits = AD_directional,\n          typename IntegratorPolicy = CollocationIntegrator>\nclass IonicLiquid __final : public GreensFunction<DerivativeTraits, IntegratorPolicy, Yukawa,\n                                     IonicLiquid<DerivativeTraits, IntegratorPolicy> >\n{\npublic:\n    IonicLiquid(double eps, double k) : GreensFunction<DerivativeTraits, IntegratorPolicy, Yukawa,\n                                                  IonicLiquid<DerivativeTraits, IntegratorPolicy> >() { this->profile_ = Yukawa(eps, k); }\n    IonicLiquid(double eps, double k, double f) : GreensFunction<DerivativeTraits, IntegratorPolicy, Yukawa,\n                                                  IonicLiquid<DerivativeTraits, IntegratorPolicy> >(f) { this->profile_ = Yukawa(eps, k); }\n    virtual ~IonicLiquid() {}\n\n    /*! Calculates the matrix representation of the S operator\n     *  \\param[in] e list of finite elements\n     */\n    virtual Eigen::MatrixXd singleLayer(const std::vector<Element> & e) const __override\n    {\n        return this->integrator_.singleLayer(*this, e);\n    }\n    /*! Calculates the matrix representation of the D operator\n     *  \\param[in] e list of finite elements\n     */\n    virtual Eigen::MatrixXd doubleLayer(const std::vector<Element> & e) const __override\n    {\n        return this->integrator_.doubleLayer(*this, e);\n    }\n\n    friend std::ostream & operator<<(std::ostream & os, IonicLiquid & gf) {\n        return gf.printObject(os);\n    }\nprivate:\n    /*!\n     *  Evaluates the Green's function given a pair of points\n     *\n     *  \\param[in] sp the source point\n     *  \\param[in] pp the probe point\n     */\n    virtual DerivativeTraits operator()(DerivativeTraits * sp, DerivativeTraits * pp) const __override\n    {\n        double eps = this->profile_.epsilon;\n\t    double k = this->profile_.kappa;\n        return (exp(-k * distance(sp, pp)) / (eps * distance(sp, pp)));\n    }\n    /*! Returns value of the directional derivative of the\n     *  Greens's function for the pair of points p1, p2:\n     *  \\f$ \\nabla_{\\mathbf{p_2}}G(\\mathbf{p}_1, \\mathbf{p}_2)\\cdot \\mathbf{n}_{\\mathbf{p}_2}\\f$\n     *  Notice that this method returns the directional derivative with respect\n     *  to the probe point, thus assuming that the direction is relative to that point.\n     *  \\param[in] direction the direction\n     *  \\param[in]        p1 first point\n     *  \\param[in]        p2 second point\n     */\n    virtual double kernelD_impl(const Eigen::Vector3d & direction,\n                              const Eigen::Vector3d & p1, const Eigen::Vector3d & p2) const __override\n    {\n        return this->profile_.epsilon * (this->derivativeProbe(direction, p1, p2));\n    }\n    virtual KernelS exportKernelS_impl() const __override {\n      return pcm::bind(&IonicLiquid<DerivativeTraits, IntegratorPolicy>::kernelS, *this, pcm::_1, pcm::_2);\n    }\n    virtual KernelD exportKernelD_impl() const __override {\n      return pcm::bind(&IonicLiquid<DerivativeTraits, IntegratorPolicy>::kernelD, *this, pcm::_1, pcm::_2, pcm::_3);\n    }\n    virtual std::ostream & printObject(std::ostream & os) __override\n    {\n        os << \"Green's function type: ionic liquid\" << std::endl;\n        os << this->profile_;\n        return os;\n    }\n};\n\n#endif // IONICLIQUID_HPP\n", "meta": {"hexsha": "32de44dbfc1cc4e5909fe813a77bb7d38b1e1e6d", "size": 5155, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/green/IonicLiquid.hpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/green/IonicLiquid.hpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/green/IonicLiquid.hpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9126984127, "max_line_length": 139, "alphanum_fraction": 0.6706110572, "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.42162074465440014}}
{"text": "\n#include \"MirrorPlasma.hpp\"\n#include \"PlasmaPhysics.hpp\"\n#include \"AtomicPhysics.hpp\"\n\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <boost/math/quadrature/gauss_kronrod.hpp>\n\n\nSpecies Electron{ .type = Species::Electron, .Charge = -1, .Mass = ElectronMass,  .Name = \"Electron\" };\nSpecies Proton{ .type = Species::Ion, .Charge = 1, .Mass = ProtonMass, .Name = \"Proton\"};\nSpecies Deuteron{ .type = Species::Ion, .Charge = 1, .Mass = 1.999*ProtonMass, .Name = \"Deuteron\" };\nSpecies NeutralHydrogen{ .type = Species::Neutral, .Charge = 0, .Mass = ProtonMass + ElectronMass, .Name = \"Neutral Hydrogen\"};\n\n// Cross Section objects for integration\nCrossSection protonImpactIonization( protonImpactIonizationCrossSection, 200, 1e6, Proton, NeutralHydrogen );\nCrossSection HydrogenChargeExchange( HydrogenChargeExchangeCrossSection, 0.1, 1e6, Proton, NeutralHydrogen );\nCrossSection electronImpactIonization( electronImpactIonizationCrossSection, 13.6, 1e6, Electron, NeutralHydrogen );\n\ndouble neutralsRateCoefficientHot( CrossSection const & sigma, MirrorPlasma const & plasma )\n{\n\t// E and T in eV, sigma in cm^2\n\t// k=<σv> in m^3/s\n\t// Assumes a Maxwellian distribution, COM energy (as opposed to incident)\n\n\tdouble temperature;\n\tif ( sigma.Particle.Name == \"Electron\" ){\n\t\ttemperature = plasma.ElectronTemperature * ReferenceTemperature; // Convert to Joules\n\t}\n\telse{\n\t\ttemperature = plasma.IonTemperature * ReferenceTemperature; // Convert to Joules\n\t}\n\n\tdouble Jacobian = ElectronCharge; // The integral is over Energy, which is in units of electronvolts, so transform the integrand back to eV\n\tauto integrand = [&]( double Energy ) {\n\t\tdouble sigmaM2 = sigma( Energy ) * 1e-4; // sigma is in cm^2, we need m^2\n\t\treturn Energy * ElectronCharge * sigmaM2 * ::exp( -Energy * ElectronCharge / temperature ) * Jacobian;\n\t};\n\n\tconstexpr double tolerance = 1e-5;\n\tconstexpr unsigned MaxDepth = 10;\n\tdouble HotRateCoeff = 4.0 / ( ::sqrt(2 * M_PI * sigma.ReducedMass * temperature) * temperature )\n\t         * boost::math::quadrature::gauss_kronrod<double, 255>::integrate( integrand, sigma.MinEnergy, sigma.MaxEnergy, MaxDepth, tolerance );\n\n#if defined( DEBUG ) && defined( ATOMIC_PHYSICS_DEBUG )\n\tstd::cerr << \"Computing a hot rate coefficient at T = \" << plasma.ElectronTemperature/1000 << \" eV and M = \" << plasma.MachNumber << \" gave <sigma v> = \" << HotRateCoeff  << std::endl;\n#endif\n\n\treturn HotRateCoeff;\n\n}\n\ndouble neutralsRateCoefficientCold( CrossSection const & sigma, MirrorPlasma const & plasma )\n{\n\t// sigma in cm^2\n\t// k=<σv> in m^3/s\n\t// Assumes ions are Maxwellian and neutrals are stationary\n\tdouble temperature;\n\tif ( sigma.Particle.Name == \"Electron\" ){\n\t\ttemperature = plasma.ElectronTemperature * ReferenceTemperature; // Convert to Joules\n\t}\n\telse{\n\t\ttemperature = plasma.IonTemperature * ReferenceTemperature; // Convert to Joules\n\t}\n\n\tdouble thermalSpeed = ::sqrt( 2.0 * temperature / sigma.Particle.Mass );\n\tdouble thermalMachNumber = plasma.MachNumber * ::sqrt( ::abs( sigma.Particle.Charge ) * plasma.ElectronTemperature * ReferenceTemperature / ( 2 * temperature ) );\n\n\tdouble Jacobian = ElectronCharge / (sigma.ReducedMass * thermalSpeed * thermalSpeed); // The integral is over Energy, which is in units of electronvolts, so transform the integrand back to eV, including change of variables from du to dE (less one power of u, which cancels with one in the integrand\n\tauto integrand = [&]( double Energy ) {\n\t\tdouble velocity = ::sqrt( 2.0 * Energy * ElectronCharge / sigma.ReducedMass );\n\t\tdouble u = velocity / thermalSpeed;\n\t\tdouble sigmaM2 = sigma( Energy ) * 1e-4; // sigma is in cm^2, we need m^2\n\t\treturn u * sigmaM2 * ( ::exp( -::pow( thermalMachNumber - u, 2 ) ) - ::exp( -::pow( thermalMachNumber + u, 2 ) ) ) * Jacobian;\n\t};\n\n\tconstexpr double tolerance = 1e-5;\n\tconstexpr unsigned MaxDepth = 10;\n\tdouble ColdRateCoeff = thermalSpeed / ( thermalMachNumber * ::sqrt(M_PI) )\n\t        * boost::math::quadrature::gauss_kronrod<double, 255>::integrate( integrand, sigma.MinEnergy, sigma.MaxEnergy, MaxDepth, tolerance );\n\n#if defined( DEBUG ) && defined( ATOMIC_PHYSICS_DEBUG )\n\tstd::cerr << \"Computing a cold rate coefficient at T = \" << plasma.ElectronTemperature*1000 << \" eV and M = \" << plasma.MachNumber << \" gave <sigma v> = \" << ColdRateCoeff  << std::endl;\n#endif\n\n\treturn ColdRateCoeff;\n}\n\n/*\ndouble meanFreePath( double density, double crossSection )\n{\n\treturn 1.0 / ( density * crossSection );\n}\n\nbool isShortMeanFreePathRegime( double meanFreePath, double characteristicLength, double minRatio = 10.0 )\n{\n\treturn ( characteristicLength / meanFreePath ) >= minRatio;\n}\n\nbool isCoronalEquilibrium( double excitationRate, double deexcitationRate, double minRatio = 10.0 )\n{\n\treturn ( deexcitationRate / excitationRate ) >= minRatio;\n}\n*/\n\ndouble reactionRate( double density_1, double density_2, double rateCoefficient, std::shared_ptr<MirrorPlasma> pMirrorPlasma )\n{\n\treturn density_1 * density_2 * rateCoefficient * pMirrorPlasma->pVacuumConfig->PlasmaVolume();\n}\n\ndouble EvaluateJanevCrossSectionFit ( std::vector<double> PolynomialCoefficients, double Energy )\n{\n\tconstexpr unsigned int N_JANEV_COEFFS = 9;\n\tif ( PolynomialCoefficients.size() != N_JANEV_COEFFS )\n\t\tthrow std::invalid_argument( \"Janev uses fixed order fits, there are not \" + std::to_string( N_JANEV_COEFFS ) + \" numbers. Something is wrong.\" );\n\tdouble sum = 0.0;\n\tfor ( size_t n = 0; n < PolynomialCoefficients.size(); n++ ) {\n      sum += PolynomialCoefficients.at( n ) * ::pow( ::log(Energy), n );\n   }\n\tdouble sigma = ::exp(sum);\n\treturn sigma;\n}\n\n/*\ndouble evaluateJanevDFunction( double beta )\n{\n\t// Function from Janev 1987 Appendix C\n\t// Used in some analytical fits for cross sections\n\tdouble DFunctionVal;\n\tif ( beta < 1e-3 ){\n\t\tDFunctionVal = 4 * beta * ::log( 1.4 / beta );\n\t} else if ( beta > 10 ) {\n\t\tDFunctionVal = beta / 2 * ::exp( - ::sqrt( 2 * beta ) );\n\t} else {\n\t\t// Create look up table and linearly interpolate to find DFunction\n\t\tstd::vector<double> betaInverse = { 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.8, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0, 8.0, 10.0, 12.5, 15.0, 20.0, 25.0, 30.0, 40.0, 60.0, 80.0, 100.0, 15.0, 200.0, 300.0, 400.0, 600.0, 800.0, 1000.0 };\n\t\tstd::vector<double> DFunction = { 0.057, 0.104, 0.135, 0.157, 0.175, 0.194, 0.230, 0.264, 0.296, 0.328, 0.367, 0.388, 0.399, 0.405, 0.410, 0.405, 0.399, 0.380, 0.345, 0.318, 0.285, 0.263, 0.227, 0.205, 0.190, 0.168, 0.141, 0.124, 0.110, 0.092, 0.080, 0.054, 0.042, 0.035, 0.028 };\n\t\tfor (size_t i = 0; i < betaInverse.size(); i++ ){\n\t\t\tif ( 1.0 / beta < betaInverse.at( i ) ){}\n\t\t\telse {\n\t\t\t\tdouble x1 = betaInverse.at( i - 1 );\n\t\t\t\tdouble x2 = betaInverse.at ( i );\n\t\t\t\tdouble y1 = DFunction.at( i - 1 );\n\t\t\t\tdouble y2 = DFunction.at ( i );\n\t\t\t\tDFunctionVal = y1 + ( y2 - y1 ) * ( 1.0 / beta - x1 ) / ( x2 - x1 );\n\t\t\t}\n\t\t}\n\t}\n\treturn DFunctionVal;\n}\n*/\n\ndouble electronImpactIonizationCrossSection( double CoMEnergy )\n{\n\t// Minimum energy of cross section in eV\n\tconstexpr double ionizationEnergy = 13.6;\n\tconstexpr double minimumEnergySigma = ionizationEnergy;\n\n\t// Contribution from ground state\n\t// Janev 1993, ATOMIC AND PLASMA-MATERIAL INTERACTION DATA FOR FUSION, Volume 4\n\t// Equation 1.2.1\n\t// e + H(1s) --> e + H+ + e\n\t// Accuracy is 10% or better\n\tconstexpr double fittingParamA = 0.18450;\n\tconstexpr std::array<double,5> fittingParamB{ -0.032226, -0.034539, 1.4003, -2.8115, 2.2986 };\n\n\tdouble sigma;\n\tif ( CoMEnergy < minimumEnergySigma ) {\n\t\tsigma = 0;\n\t}\n\telse {\n\t\tdouble sum = 0.0;\n\t\tdouble x = 1.0 - ionizationEnergy / CoMEnergy;\n\t\tfor ( size_t n = 0; n < fittingParamB.size(); n++ ) {\n\t      sum += fittingParamB.at( n ) * ::pow( x, n );\n\t   }\n\t\tsigma = 1.0e-13 / ( ionizationEnergy * CoMEnergy ) * ( fittingParamA * ::log( CoMEnergy / ionizationEnergy ) + sum );\n\t}\n\treturn sigma;\n}\n\n// Energy in electron volts, returns cross section in cm^2\ndouble protonImpactIonizationCrossSection( double Energy )\n{\n\t// Minimum energy of cross section in keV\n\tconst double minimumEnergySigma = 0.2;\n\t// Convert to keV\n\tdouble CoMEnergy = Energy / 1000;\n\n\t// Contribution from ground state\n\t// Janev 1993, ATOMIC AND PLASMA-MATERIAL INTERACTION DATA FOR FUSION, Volume 4\n\t// Equation 2.2.1\n\t// H+ + H(1s) --> H+ + H+ + e\n\t// Accuracy is 30% or better\n\tconstexpr double A1 = 12.899;\n\tconstexpr double A2 = 61.897;\n\tconstexpr double A3 = 9.2731e3;\n\tconstexpr double A4 = 4.9749e-4;\n\tconstexpr double A5 = 3.9890e-2;\n\tconstexpr double A6 = -1.5900;\n\tconstexpr double A7 = 3.1834;\n\tconstexpr double A8 = -3.7154;\n\n\tdouble sigma;\n\tif ( CoMEnergy < minimumEnergySigma ) {\n\t\tsigma = 0;\n\t}\n\telse {\n\t\t// Energy is in units of keV\n\t\tsigma = 1e-16 * A1 * ( ::exp( -A2 / CoMEnergy ) * ::log( 1 + A3 * CoMEnergy ) / CoMEnergy + A4 * ::exp( -A5 * CoMEnergy ) / ( ::pow( CoMEnergy, A6 ) + A7 * ::pow( CoMEnergy, A8 ) ) );\n\t}\n\treturn sigma;\n}\n\ndouble HydrogenChargeExchangeCrossSection( double CoMEnergy )\n{\n\t// Minimum energy of cross section in eV\n\t// const double minimumEnergySigma_1s = 0.1;\n\tconst double minimumEnergySigma_2p = 19.0;\n\tconst double minimumEnergySigma_2s = 0.1;\n\n\t// Contribution from ground -> ground state\n\t// Janev 1987 3.1.8\n\t// p + H(1s) --> H(1s) + p\n\tdouble sigma_1s;\n\tif ( CoMEnergy < minimumEnergySigma_2p ) {\n\t\tsigma_1s = 0;\n\t} else {\n\t\tsigma_1s = 0.6937e-14 * ::pow( 1 - 0.155 * ::log10( CoMEnergy ), 2 ) / (1 + 0.1112e-14 * ::pow( CoMEnergy, 3.3 ));\n\t}\n\n\t// Janev 1987 3.1.9\n\t// p + H(1s) --> H(2p) + p\n\tstd::vector<double> aSigma_2p = {-2.197571949935e+01, -4.742502251260e+01, 3.628013140596e+01, -1.423003075866e+01, 3.273090240144e+00, -4.557928912260e-01, 3.773588347458e-02, -1.707904867106e-03, 3.251203344615e-05};\n\t// Janev 1987 3.1.10\n\t// p + H(1s) --> H(2s) + p\n\tstd::vector<double> aSigma_2s = {-1.327325087764e+04, 1.317576614520e+04, -5.683932157858e+03, 1.386309780149e+03, -2.089794561307e+02, 1.992976245274e+01, -1.173800576157e+00, 3.902422810767e-02, -5.606240339932e-04};\n\n\t// Contribution from ground -> 2p orbital\n\tdouble sigma_2p;\n\tif ( CoMEnergy < minimumEnergySigma_2p ) {\n\t\tsigma_2p = 0;\n\t} else {\n\t\tsigma_2p = EvaluateJanevCrossSectionFit( aSigma_2p, CoMEnergy );\n\t}\n\n\t// Contribution from ground -> 2s orbital\n\tdouble sigma_2s;\n\tif ( CoMEnergy < minimumEnergySigma_2s ) {\n\t\tsigma_2s = 0;\n\t} else {\n\t\tsigma_2s = EvaluateJanevCrossSectionFit( aSigma_2s, CoMEnergy );\n\t}\n\n\treturn sigma_1s + sigma_2p + sigma_2s;\n}\n\n// Energy in electron volts, returns cross section in cm^2\ndouble radiativeRecombinationCrossSection( double Energy )\n{\n\t// From https://iopscience-iop-org.proxy-um.researchport.umd.edu/article/10.1088/1402-4896/ab060a\n\t// Igor A Kotelnikov and Alexander I Milstein 2019 Phys. Scr. 94 055403\n\t// Equation 9\n\t// H+ + e --> H + hν\n\n\tint Z = 1;\n\tdouble IonizationEnergy = 13.59844; // eV\n\tdouble J_Z = ::pow( Z, 2 ) * IonizationEnergy;\n\tdouble eta = ::sqrt( J_Z / Energy );\n\tdouble sigma = ::pow( 2, 8 ) * ::pow( M_PI * BohrRadius, 2 ) / 3 * ::pow( eta, 6 ) * ::exp( - 4 * eta * atan( 1 / eta ) ) / ( ( 1 - ::exp( -2 * M_PI * eta ) ) * ::pow( ::pow( eta, 2 ) + 1, 2 ) ) * ::pow( FineStructureConstant, 3 );\n\n\tsigma *= 1e4; // convert to cm^2\n\treturn sigma;\n}\n\n// double electronHydrogenExcitationN2CrossSection( double Te )\n// {\n// \t// Minimum energy of cross section in eV\n// \tconst double excitationEnergy = 10.2;\n// \tconst double cutoffEnergy1 = 11.56;\n// \tconst double cutoffEnergy2 = 12.23;\n//\n// \t// Contribution from ground state\n// \t// Janev 1993, ATOMIC AND PLASMA-MATERIAL INTERACTION DATA FOR FUSION, Volume 4\n// \t// Equation 1.1.3\n// \t// e + H(1s) --> e + H*(n=2)\n// \t// Accuracy is 10% or better\n// \tstd::vector<double> fittingParamA = { 1.4182, -20.877, 49.735, -46.249, 17.442, 4.4979 };\n//\n// \tdouble sigma;\n// \tif ( Te < excitationEnergy ) {\n// \t\tsigma = 0;\n// \t}\n// \telse if ( Te < cutoffEnergy1 ) {\n// \t\tsigma = 1e-16 * ( 0.255 + 0.1865 * ( Te - excitationEnergy ) );\n// \t}\n// \telse if ( Te < cutoffEnergy2 ) {\n// \t\tsigma = 5.025e-17;\n// \t}\n// \telse {\n// \t\tdouble sum = 0.0;\n// \t\tdouble XEnergy = Te / excitationEnergy;\n// \t\tfor ( size_t n = 0; n < fittingParamA.size() - 1; n++ ) {\n// \t      sum += fittingParamA.at( n ) / ::pow( XEnergy, n - 1 );\n// \t   }\n// \t\tsigma = 5.984e-16 / Te * ( sum + fittingParamA.back() * ::log( XEnergy ) );\n// \t}\n// \treturn sigma;\n// }\n//\n// double protonHydrogenExcitationN2CrossSection( double Ti )\n// {\n// \t// Minimum energy of cross section in keV\n// \tconst double minimumEnergySigma = 0.6;\n// \tdouble TiKEV = Ti / 1000;\n//\n// \t// Contribution from ground state\n// \t// Janev 1993, ATOMIC AND PLASMA-MATERIAL INTERACTION DATA FOR FUSION, Volume 4\n// \t// Equation 2.2.1\n// \t// H+ + H(1s) --> H+ + H+ + e\n// \t// Accuracy is 100% or better\n// \tconst double A1 = 34.433;\n// \tconst double A2 = 44.057;\n// \tconst double A3 = 0.56870;\n// \tconst double A4 = 8.5476;\n// \tconst double A5 = 7.8501;\n// \tconst double A6 = -9.2217;\n// \tconst double A7 = 1.8020e-2;\n// \tconst double A8 = 1.6931;\n// \tconst double A9 = 1.9422e-3;\n// \tconst double A10 = 2.9068;\n//\n// \tdouble sigma;\n// \tif ( TiKEV < minimumEnergySigma ) {\n// \t\tsigma = 0;\n// \t}\n// \telse {\n// \t\t// Energy is in units of keV\n// \t\tsigma = 1e-16 * A1 * ( ::exp( -A2 / TiKEV ) * ::log( 1 + A3 * TiKEV ) / TiKEV + A4 * ::exp( -A5 * TiKEV ) / ( ::pow( TiKEV, A6 ) ) + A7 * ::exp( -A8 / TiKEV ) / ( 1 + A9 * ::pow( TiKEV, A10 ) ) );\n// \t}\n// \treturn sigma;\n// }\n\n/*\n * Use the above functions to set steady-state neutral density/source\n *\n */\nvoid MirrorPlasma::ComputeSteadyStateNeutrals()\n{\n\t// Do not recalculate if we're in fixed-neutral-density mode\n\tif ( FixedNeutralDensity )\n\t\treturn;\n\n\t// Calculate the Ionization Rate of cold neutrals from proton and electron impact:\n\tdouble IonizationRate =\n\t\tneutralsRateCoefficientCold( protonImpactIonization, *this ) * IonDensity * ReferenceDensity +\n\t\tneutralsRateCoefficientCold( electronImpactIonization, *this ) * ElectronDensity * ReferenceDensity;\n\n#if defined( DEBUG ) && defined( ATOMIC_PHYSICS_DEBUG )\n\tstd::cerr << \"Current Ionization Rate is \" << IonizationRate << std::endl;\n#endif\n\n\t// Assume mix of neutrals is such that the particle densities are maintained so we just need to produce enough electrons from the source gas to balance the losses\n\tdouble ElectronLossRate = ParallelElectronParticleLoss() + ClassicalElectronParticleLosses();\n\t// Steady State requires\n\t//\t\tLosses = n_N * n_e * IonizationRateCoefficient * Volume\n\t// so n_N = (Losses/Volume) / ( n_e * IonizationRateCoefficient )\n\t//\t\t    = (Losses/Volume) / IonizationRate\n\tNeutralDensity = ElectronLossRate / ( IonizationRate );\n\t// Normalize neutral density\n\tNeutralDensity = NeutralDensity / ReferenceDensity;\n\tNeutralSource = ElectronLossRate;\n}\n\n// Number of ions lost as neutrals per second per unit volume\n// requires computed neutral density\ndouble MirrorPlasma::CXLossRate() const\n{\n\tif ( !pVacuumConfig->IncludeCXLosses )\n\t\treturn 0.0;\n\n\tdouble CXRateCoefficient = neutralsRateCoefficientCold( HydrogenChargeExchange, *this );\n\n#if defined( DEBUG ) && defined( ATOMIC_PHYSICS_DEBUG )\n\tstd::cerr << \"Current CX Loss Rate is \" << CXRateCoefficient * ( NeutralDensity * ReferenceDensity * IonDensity * ReferenceDensity ) << \" particles/s\"<<std::endl;\n#endif\n\n\treturn CXRateCoefficient * ( NeutralDensity * ReferenceDensity * IonDensity * ReferenceDensity );\n}\n", "meta": {"hexsha": "5560a9e2e49cb28546940b0a84e24f3d8027f48a", "size": 15342, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Neutrals.cpp", "max_stars_repo_name": "MylesKelly/MCTrans", "max_stars_repo_head_hexsha": "9d38178d3150d4c1dcde16489a2df3cca2d49c74", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Neutrals.cpp", "max_issues_repo_name": "MylesKelly/MCTrans", "max_issues_repo_head_hexsha": "9d38178d3150d4c1dcde16489a2df3cca2d49c74", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Neutrals.cpp", "max_forks_repo_name": "MylesKelly/MCTrans", "max_forks_repo_head_hexsha": "9d38178d3150d4c1dcde16489a2df3cca2d49c74", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8405063291, "max_line_length": 299, "alphanum_fraction": 0.6778125407, "num_tokens": 5105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.787931185683219, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.42162073932499333}}
{"text": "#include <opengv/optimization_tools/objective_function_tools/GlobalPnPFunctionInfo.hpp>\n#include <Eigen/Dense>\n#include <opengv/Indices.hpp>\n#include <iostream>\n\nGlobalPnPFunctionInfo::GlobalPnPFunctionInfo(const opengv::absolute_pose::AbsoluteAdapterBase & adapter){\n\n  opengv::Indices indices(adapter.getNumberCorrespondences());\n  int total_points = (int) indices.size();\n  //std::cout << \"Total points: \" << total_points << std::endl;\n  Mt =  Eigen::Matrix3d::Zero(3,3);\n  Mrt = Eigen::MatrixXd::Zero(3,9);\n  Mr =  Eigen::MatrixXd::Zero(9,9);\n  vt =  Eigen::VectorXd::Zero(3,1);\n  vr =  Eigen::VectorXd::Zero(9,1);\n  //Eigen::MatrixXd Constant = Eigen::MatrixXd::Zero(1,1);\n  \n  //Variables defined for debugging\n  /*Eigen::MatrixXd C_all = Eigen::MatrixXd::Zero(3, total_points);\n  Eigen::MatrixXd V_all = Eigen::MatrixXd::Zero(3, total_points);\n  Eigen::MatrixXd X_all = Eigen::MatrixXd::Zero(3, total_points);*/\n  Eigen::Matrix3d id = Eigen::Matrix3d::Identity(3,3);\n\n  Eigen::Matrix<double,3,1> vi;\n  Eigen::Matrix<double,3,1> xi;\n  Eigen::Matrix<double,3,1> ci;\n  Eigen::Matrix3d Qi;\n  Eigen::Matrix3d Vi;\n  Eigen::MatrixXd Mr_i  = Eigen::MatrixXd::Zero(3,9);\n  Eigen::MatrixXd Mrt_i = Eigen::MatrixXd::Zero(3,9);\n  Eigen::Matrix3d I_V   = Eigen::MatrixXd::Zero(3,3);\n  Eigen::MatrixXd vr_1  = Eigen::MatrixXd::Zero(1,3);\n  Eigen::MatrixXd vr_2  = Eigen::MatrixXd::Zero(1,9);\n  for( int i = 0; i < total_points; i++ )\n  {\n    vi = adapter.getCamRotation(indices[i]) * adapter.getBearingVector(indices[i]);\n    xi = adapter.getPoint(indices[i]);\n    ci = adapter.getCamOffset(indices[i]);\n    /*C_all.block<3,1>(0,i) = ci;\n    X_all.block<3,1>(0,i) = xi;\n    V_all.block<3,1>(0,i) = vi;*/\n    Vi = vi * vi.transpose() / (vi.transpose() * vi);\n    Qi = (id - Vi).transpose() * (id - Vi);\n    \n    I_V = id - Vi;\n    Mt = Mt + Qi;\n    vt = vt - (2 * Qi * ci);\n    //Constant = Constant + ci.transpose() * Qi * ci;\n   \n    //Calculate Mr  \n    Mr_i.block<3,3>(0,0) = xi(0,0) * I_V;\n    Mr_i.block<3,3>(0,3) = xi(1,0) * I_V;\n    Mr_i.block<3,3>(0,6) = xi(2,0) * I_V;\n   \n    Mr = Mr + Mr_i.transpose() * Mr_i;\n   \n    //Calculate Mrt\n    Mrt_i.block<3,3>(0,0) = xi(0,0) * Qi;\n    Mrt_i.block<3,3>(0,3) = xi(1,0) * Qi;\n    Mrt_i.block<3,3>(0,6) = xi(2,0) * Qi;\n    \n    Mrt = Mrt + 2*Mrt_i;\n       \n    //Calculate vr\n    vr_1 = ci.transpose() * Qi;\n    vr_2.block<1,3>(0,0) = -2 * xi(0,0) * vr_1;\n    vr_2.block<1,3>(0,3) = -2 * xi(1,0) * vr_1;\n    vr_2.block<1,3>(0,6) = -2 * xi(2,0) * vr_1;\n    vr = vr + vr_2.transpose();\n  }\n  /*std::cout << \"Data:\" << std::endl;\n  std::cout << \"ci\" << std::endl << C_all << std::endl;\n  std::cout << \"xi\" << std::endl << X_all << std::endl;\n  std::cout << \"vi\" << std::endl << V_all << std::endl;\n  \n  std::cout << \"Final results: \" << std::endl;\n  std::cout << \"Mt: \"  << std::endl << Mt << std::endl;\n  std::cout << \"Mrt: \" << std::endl << Mrt << std::endl;\n  std::cout << \"Mr:\"   << std::endl << Mr  << std::endl;\n  std::cout << \"vt:\"   << std::endl << vt  << std::endl;\n  std::cout << \"vr:\"   << std::endl << vr   << std::endl;\n  std::cout << \"Const: \" << std::endl << Constant << std::endl;*/\n}\n\nGlobalPnPFunctionInfo::~GlobalPnPFunctionInfo(){};\n\ndouble GlobalPnPFunctionInfo::objective_function_value(const opengv::rotation_t & rotation, const opengv::translation_t & translation){\n  const double * p = &rotation(0);\n  Map<const Matrix<double,1,9> > r(p, 1, 9);\n  Eigen::MatrixXd e = (translation.transpose() * Mt * translation)\n    + (translation.transpose() * Mrt *  r.transpose())\n    + (vt.transpose() * translation)\n    + (r * Mr * r.transpose() )\n    + (vr.transpose() * r.transpose());\n  return ( e(0,0));\n}\n\nopengv::rotation_t GlobalPnPFunctionInfo::rotation_gradient(const opengv::rotation_t & rotation, const opengv::translation_t & translation){\n  const double * p = &rotation(0);\n  Map<const Matrix<double,1,9> > r(p, 1, 9);\n  Eigen::MatrixXd result = (2 * Mr * r.transpose()) + ( Mrt.transpose() * translation ) + vr;\n  double * ptr = &result(0);\n  Map<Matrix<double, 3,3> > m(ptr, 3, 3);\n  return m;\n}\n\nopengv::translation_t GlobalPnPFunctionInfo::translation_gradient(const opengv::rotation_t & rotation, const opengv::translation_t & translation){\n  const double * p = &rotation(0);\n  Map<const Matrix<double,1,9> > r(p, 1, 9);\n  return ( (2 * Mt * translation) + (  Mrt * r.transpose() ) + vt );\n}\n", "meta": {"hexsha": "aed88e6161ef77e786ef864603e22100f232d125", "size": 4365, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimization_tools/objective_function_tools/GlobalPnPFunctionInfo.cpp", "max_stars_repo_name": "mateus03/2018AMMPoseSolver", "max_stars_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-05-15T12:41:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T10:42:52.000Z", "max_issues_repo_path": "src/optimization_tools/objective_function_tools/GlobalPnPFunctionInfo.cpp", "max_issues_repo_name": "mateus03/2018AMMPoseSolver", "max_issues_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimization_tools/objective_function_tools/GlobalPnPFunctionInfo.cpp", "max_forks_repo_name": "mateus03/2018AMMPoseSolver", "max_forks_repo_head_hexsha": "787886846199cd0864c4e59a6545c40c3120010a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-27T18:11:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T18:11:14.000Z", "avg_line_length": 38.9732142857, "max_line_length": 146, "alphanum_fraction": 0.6087056128, "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.42155768709602404}}
{"text": "//Machine-generated by miind.py. Edit at your own risk.\n\n#include <boost/timer/timer.hpp>\n#include <GeomLib.hpp>\n#include <TwoDLib.hpp>\n#include <MPILib/include/MPINetworkCode.hpp>\n#include <MPILib/include/RateAlgorithmCode.hpp>\n#include <MPILib/include/SimulationRunParameter.hpp>\n#include <MPILib/include/report/handler/RootReportHandler.hpp>\n#include <MPILib/include/WilsonCowanAlgorithm.hpp>\n#include <MPILib/include/PersistantAlgorithm.hpp>\n#include <MPILib/include/DelayAlgorithmCode.hpp>\n#include <MPILib/include/RateFunctorCode.hpp>\n#include \"Euler.hpp\"\n\ntypedef MPILib::MPINetwork<MPILib::DelayedConnection, MPILib::utilities::CircularDistribution> Network;\n\t// defining variables\nconst double TIME_END = 10000.0;\n\n\nvector<TwoDLib::Redistribution> RetrieveMappingFromXML(const std::string& type, pugi::xml_node root)\n{\n\tPred pred(type);\n\tpugi::xml_node rev_node = root.find_child(pred);\n\n\tif (rev_node.name() != std::string(\"Mapping\") ||\n\t    rev_node.attribute(\"type\").value() != type)\n\t  throw TwoDLib::TwoDLibException(\"Couldn't find mapping in model file\");\n\n\tstd::ostringstream ostrev;\n\trev_node.print(ostrev);\n\tstd::istringstream istrev(ostrev.str());\n\tvector<TwoDLib::Redistribution> vec_rev = TwoDLib::ReMapping(istrev);\n\treturn vec_rev;\n}\n\nTwoDLib::Mesh RetrieveMeshFromXML(pugi::xml_node root)\n{\n        pugi::xml_node mesh_node = root.first_child();\n\tif (mesh_node.name() != std::string(\"Mesh\") )\n\t  throw TwoDLib::TwoDLibException(\"Couldn't find mesh node in model file\");\n\tstd::ostringstream ostmesh;\n\tmesh_node.print(ostmesh);\n\tstd::istringstream istmesh(ostmesh.str());\n\tTwoDLib::Mesh mesh(istmesh);\n\treturn mesh;\n}\n\nMPILib::Rate RateFunction_1(MPILib::Time t){\n\treturn 3.5;\n}\nMPILib::Rate RateFunction_2(MPILib::Time t){\n\treturn t > 1500 ? 3.5 : 0;\n}\n\n\nint main(int argc, char *argv[]){\n\tNetwork network;\n\tboost::timer::auto_cpu_timer t;\n\n#ifdef ENABLE_MPI\n\t// initialise the mpi environment this cannot be forwarded to a class\n\tboost::mpi::environment env(argc, argv);\n#endif\n\n\ttry {\t// generating algorithms\n\n\tpugi::xml_document doc;\t\n\tpugi::xml_parse_result result = doc.load_file(\"rinzel.model\");\n\tpugi::xml_node  root = doc.first_child();\n \n\tTwoDLib::Mesh mesh1 = RetrieveMeshFromXML(root);\n\tTwoDLib::Mesh mesh2 = mesh1;\n\n\tstd::vector<TwoDLib::Redistribution> vec_rev1 = RetrieveMappingFromXML(\"Reversal\",root);\n\tstd::vector<TwoDLib::Redistribution> vec_rev2 = vec_rev1;\n\tstd::vector<TwoDLib::Redistribution> vec_res1 = RetrieveMappingFromXML(\"Reset\",root);\n\tstd::vector<TwoDLib::Redistribution> vec_res2 = vec_res1;\n\n\tstd::vector<TwoDLib::Mesh> vec_vec_mesh { mesh1, mesh2 };\n\tstd::vector< std::vector<TwoDLib::Redistribution> > vec_vec_rev { vec_rev1, vec_rev2 };\n\tstd::vector< std::vector<TwoDLib::Redistribution> > vec_vec_res { vec_res1, vec_res2 };\n \n\tTwoDLib::Ode2DSystemGroup group(vec_vec_mesh,vec_vec_rev, vec_vec_res);\n\tgroup.Initialize(0,0,0);\n\tgroup.Initialize(1,0,0);\n\n\tTwoDLib::TransitionMatrix mat1(\"rinzel_0.1_0_0_0_.mat\");\n        TwoDLib::TransitionMatrix mat2(\"rinzel_-0.1_0_0_0_.mat\");\n\n\tTwoDLib::CSRMatrix csr01(mat2,group,0); // inhibitory so mat2\n\tTwoDLib::CSRMatrix csr02(mat1,group,0); // excitatory so mat1; mesh id 0 relates to the first mesh\n\tTwoDLib::CSRMatrix csr10(mat2,group,1); // inhibitory so mat2; mesh id 1 relates to the second mesh\n\tTwoDLib::CSRMatrix csr13(mat1,group,1); // excitatory so mat 1\n\n\tstd::vector<TwoDLib::CSRMatrix> vecmat{csr01, csr02, csr10, csr13}; // the input rates corresponding to these matrices must be presented in the same order\n\n\t// Establish number of steps\n\tMPILib::Time t_step = mesh1.TimeStep();\n\tMPILib::Number n_steps = static_cast<MPILib::Number>(floor(TIME_END/t_step));\n\tstd::cout << \"Number of simulation steps: \" << n_steps << std::endl;;\n\t\n\t// Placeholder for firing rates\n\tconst MPILib::Number nr_populations = 4;\n\tstd::vector<MPILib::Rate> vec_rates(nr_populations,0.0);\n\tstd::vector<MPILib::Rate> vec_input(nr_populations,0.0);\n\n\t// create a vector for the derivative                                                                                                                                       \n\tstd::vector<double> dydt(group.Mass().size());\n\n\t// Euler step parameter\n\tTwoDLib::MasterParameter par(500);\n\tdouble h = 1./par._N_steps*mesh1.TimeStep();\n\n\t// generating connections\n\tDelayedConnection con_0_2_0(1.,0.1,0);\n\tDelayedConnection con_1_3_0(1.,0.1,0);\n\tDelayedConnection con_1_0_0(500.,-0.1,0);\n\tDelayedConnection con_0_1_0(500.,-0.1,0);\n\n\tfor(MPILib::Index istep = 0; istep < n_steps; istep++){\n\t  MPILib::Time t = t_step*istep;\n\t  group.Evolve();\n\t  // retain Hugh's original numbering convention\n\n\t  vec_input[0] = con_0_1_0._number_of_connections*vec_rates[1]; \n\t  vec_input[1] = con_0_2_0._number_of_connections*vec_rates[2];\n\t  vec_input[2] = con_1_0_0._number_of_connections*vec_rates[0]; \n\t  vec_input[3] = con_1_3_0._number_of_connections*vec_rates[3];\n\n\t  for (MPILib::Index i_part = 0; i_part < par._N_steps; i_part++ ){\n\t    TwoDLib::ClearDerivative(dydt);\n\t    TwoDLib::CalculateDerivative(group,dydt,vecmat,vec_input);\n\t    TwoDLib::AddDerivative(group.Mass(),dydt,h);\n\t  }\n\n\t  group.RedistributeProbability();\n\t  group.RemapReversal();\n\n\t  vec_rates[0] = group.F()[0];\n\t  vec_rates[1] = group.F()[1];\n\t  vec_rates[2] = RateFunction_1(t);\n\t  vec_rates[3] = RateFunction_2(t);\n\n\t  if (istep%1 == 0) std::cout << mesh1.TimeStep()*istep << \" \" << group.F()[0] << \" \" << group.F()[1] << std::endl;\n\t}\n\n\tstd::ofstream ofst1(\"dens1.dat\");\n\tstd::ofstream ofst2(\"dens2.dat\");\n\n\tstd::vector<std::ostream*> vec_stream{ &ofst1, &ofst2};\n\tgroup.Dump(vec_stream);\n\n\t} catch(std::exception& exc){\n\t\tstd::cout << exc.what() << std::endl;\n#ifdef ENABLE_MPI\n\t//Abort the MPI environment in the correct way :\n\tenv.abort(1);\n\t#endif \n\t}\n\n\tstd::cout << \"Overall time spend\\n\";\n\tt.report();\n\t\t\n\treturn 0;\n}\n", "meta": {"hexsha": "56149d8efef6e18d2e2ad590da13990121ac84e3", "size": 5825, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/IntegrationTwoDLib/rinzel.cpp", "max_stars_repo_name": "dekamps/miind", "max_stars_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-09-15T17:28:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T20:26:47.000Z", "max_issues_repo_path": "apps/IntegrationTwoDLib/rinzel.cpp", "max_issues_repo_name": "dekamps/miind", "max_issues_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T07:50:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T16:20:37.000Z", "max_forks_repo_path": "apps/IntegrationTwoDLib/rinzel.cpp", "max_forks_repo_name": "dekamps/miind", "max_forks_repo_head_hexsha": "4b321c62c2bd27eb0d5d8336a16a9e840ba63856", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-14T20:52:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T12:18:18.000Z", "avg_line_length": 34.880239521, "max_line_length": 173, "alphanum_fraction": 0.7112446352, "num_tokens": 1742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676284, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.42148941559653164}}
{"text": "// Copyright 2018-2019 The Simons Foundation, Inc. - All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef NETKET_SR_HPP\n#define NETKET_SR_HPP\n\n#include <complex>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/IterativeLinearSolvers>\n\n#include \"Utils/parallel_utils.hpp\"\n#include \"Utils/random_utils.hpp\"\n#include \"common_types.hpp\"\n#include \"matrix_replacement.hpp\"\n\nnamespace netket {\n\n// Generalized Stochastic Reconfiguration Updates\nclass SR {\n  double sr_diag_shift_;\n  bool use_iterative_;\n  bool use_cholesky_;\n  bool is_holomorphic_;\n\n  Eigen::MatrixXd Sreal_;\n  Eigen::MatrixXcd Scomplex_;\n\n public:\n  SR() { setDefaultParameters(); }\n\n  void ComputeUpdate(const Eigen::Ref<const Eigen::MatrixXcd> Oks,\n                     const Eigen::Ref<const Eigen::VectorXcd> grad,\n                     Eigen::Ref<Eigen::VectorXcd> deltaP) {\n    double nsamp = Oks.rows();\n\n    SumOnNodes(nsamp);\n    auto npar = grad.size();\n    if (is_holomorphic_) {\n      if (!use_iterative_) {\n        // Explicit construction of the S matrix\n        Scomplex_.resize(npar, npar);\n        Scomplex_ = (Oks.adjoint() * Oks);\n        SumOnNodes(Scomplex_);\n        Scomplex_ /= nsamp;\n\n        // Adding diagonal shift\n        Scomplex_ += Eigen::MatrixXd::Identity(npar, npar) * sr_diag_shift_;\n\n        if (use_cholesky_ == false) {\n          Eigen::FullPivHouseholderQR<Eigen::MatrixXcd> qr(npar, npar);\n          qr.setThreshold(1.0e-6);\n          qr.compute(Scomplex_);\n          deltaP = qr.solve(grad);\n        } else {\n          Eigen::LLT<Eigen::MatrixXcd> llt(npar);\n          llt.compute(Scomplex_);\n          deltaP = llt.solve(grad);\n        }\n      } else {\n        Eigen::ConjugateGradient<SrMatrixComplex, Eigen::Lower | Eigen::Upper,\n                                 Eigen::IdentityPreconditioner>\n            it_solver;\n        // Eigen::GMRES<MatrixReplacement, Eigen::IdentityPreconditioner>\n        // it_solver;\n        it_solver.setTolerance(1.0e-3);\n        SrMatrixComplex S;\n        S.attachMatrix(Oks);\n        S.setShift(sr_diag_shift_);\n        S.setScale(1. / nsamp);\n\n        it_solver.compute(S);\n        deltaP = it_solver.solve(grad);\n        MPI_Barrier(MPI_COMM_WORLD);\n      }\n    } else {\n      if (!use_iterative_) {\n        // Explicit construction of the S matrix\n        Sreal_.resize(npar, npar);\n        Sreal_ = (Oks.adjoint() * Oks).real();\n        SumOnNodes(Sreal_);\n        Sreal_ /= nsamp;\n\n        // Adding diagonal shift\n        Sreal_ += Eigen::MatrixXd::Identity(npar, npar) * sr_diag_shift_;\n\n        if (use_cholesky_ == false) {\n          Eigen::FullPivHouseholderQR<Eigen::MatrixXd> qr(npar, npar);\n          qr.setThreshold(1.0e-6);\n          qr.compute(Sreal_);\n          deltaP.real() = qr.solve(grad.real());\n        } else {\n          Eigen::LLT<Eigen::MatrixXd> llt(npar);\n          llt.compute(Sreal_);\n          deltaP.real() = llt.solve(grad.real());\n          deltaP.imag().setZero();\n        }\n      } else {\n        Eigen::ConjugateGradient<SrMatrixReal, Eigen::Lower | Eigen::Upper,\n                                 Eigen::IdentityPreconditioner>\n            it_solver;\n        // Eigen::GMRES<MatrixReplacement, Eigen::IdentityPreconditioner>\n        // it_solver;\n        it_solver.setTolerance(1.0e-3);\n        SrMatrixReal S;\n        S.attachMatrix(Oks);\n        S.setShift(sr_diag_shift_);\n        S.setScale(1. / nsamp);\n\n        it_solver.compute(S);\n        deltaP.real() = it_solver.solve(grad.real());\n        deltaP.imag().setZero();\n        MPI_Barrier(MPI_COMM_WORLD);\n      }\n    }\n  }\n\n  void setDefaultParameters() {\n    sr_diag_shift_ = 0.01;\n    use_iterative_ = false;\n    use_cholesky_ = true;\n    is_holomorphic_ = true;\n  }\n\n  void setParameters(double diagshift = 0.01, bool use_iterative = false,\n                     bool use_cholesky = true, bool is_holomorphic = true) {\n    sr_diag_shift_ = diagshift;\n    use_iterative_ = use_iterative;\n    use_cholesky_ = use_cholesky;\n    is_holomorphic_ = is_holomorphic;\n\n    InfoMessage() << \"Using the Stochastic reconfiguration method\" << std::endl;\n\n    if (use_iterative_) {\n      InfoMessage() << \"With iterative solver\" << std::endl;\n    } else {\n      if (use_cholesky_) {\n        InfoMessage() << \"Using Cholesky decomposition\" << std::endl;\n      }\n    }\n  }\n};  // namespace netket\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "2e9dfc3ba05545d664ed864f74d26061e54b344d", "size": 4969, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Sources/Optimizer/stochastic_reconfiguration.hpp", "max_stars_repo_name": "tvieijra/netket", "max_stars_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-29T02:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T18:52:33.000Z", "max_issues_repo_path": "Sources/Optimizer/stochastic_reconfiguration.hpp", "max_issues_repo_name": "tvieijra/netket", "max_issues_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T11:12:00.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T17:04:41.000Z", "max_forks_repo_path": "Sources/Optimizer/stochastic_reconfiguration.hpp", "max_forks_repo_name": "tvieijra/netket", "max_forks_repo_head_hexsha": "ef3ff32b242f25b6a6ae0f08db1aada85775a2ea", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-02T07:29:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-04T21:55:21.000Z", "avg_line_length": 30.4846625767, "max_line_length": 80, "alphanum_fraction": 0.6248742202, "num_tokens": 1257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914975839675, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4214894094393276}}
{"text": "// Copyright Nick Thompson, 2019\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n#ifndef BOOST_MATH_QUADRATURE_DETAIL_OOURA_FOURIER_INTEGRALS_DETAIL_HPP\n#define BOOST_MATH_QUADRATURE_DETAIL_OOURA_FOURIER_INTEGRALS_DETAIL_HPP\n#include <utility> // for std::pair.\n#include <mutex>\n#include <atomic>\n#include <vector>\n#include <iostream>\n#include <boost/math/special_functions/expm1.hpp>\n#include <boost/math/special_functions/sin_pi.hpp>\n#include <boost/math/special_functions/cos_pi.hpp>\n#include <boost/math/constants/constants.hpp>\n\nnamespace boost { namespace math { namespace quadrature { namespace detail {\n\n// Ooura and Mori, A robust double exponential formula for Fourier-type integrals,\n// eta is the argument to the exponential in equation 3.3:\ntemplate<class Real>\nstd::pair<Real, Real> ooura_eta(Real x, Real alpha) {\n    using std::expm1;\n    using std::exp;\n    using std::abs;\n    Real expx = exp(x);\n    Real eta_prime = 2 + alpha/expx + expx/4;\n    Real eta;\n    // This is the fast branch:\n    if (abs(x) > 0.125) {\n        eta = 2*x - alpha*(1/expx - 1) + (expx - 1)/4;\n    }\n    else {// this is the slow branch using expm1 for small x:\n        eta = 2*x - alpha*expm1(-x) + expm1(x)/4;\n    }\n    return {eta, eta_prime};\n}\n\n// Ooura and Mori, A robust double exponential formula for Fourier-type integrals,\n// equation 3.6:\ntemplate<class Real>\nReal calculate_ooura_alpha(Real h)\n{\n    using boost::math::constants::pi;\n    using std::log1p;\n    using std::sqrt;\n    Real x = sqrt(16 + 4*log1p(pi<Real>()/h)/h);\n    return 1/x;\n}\n\ntemplate<class Real>\nstd::pair<Real, Real> ooura_sin_node_and_weight(long n, Real h, Real alpha)\n{\n    using std::expm1;\n    using std::exp;\n    using std::abs;\n    using boost::math::constants::pi;\n    using std::isnan;\n\n    if (n == 0) {\n        // Equation 44 of https://arxiv.org/pdf/0911.4796.pdf\n        // Fourier Transform of the Stretched Exponential Function: Analytic Error Bounds,\n        // Double Exponential Transform, and Open-Source Implementation,\n        // Joachim Wuttke, \n        // The C library libkww provides functions to compute the Kohlrausch-Williams-Watts function, \n        // the Laplace-Fourier transform of the stretched (or compressed) exponential function exp(-t^beta)\n        // for exponent beta between 0.1 and 1.9 with sixteen decimal digits accuracy.\n\n        Real eta_prime_0 = Real(2) + alpha + Real(1)/Real(4);\n        Real node = pi<Real>()/(eta_prime_0*h);\n        Real weight = pi<Real>()*boost::math::sin_pi(1/(eta_prime_0*h));\n        Real eta_dbl_prime = -alpha + Real(1)/Real(4);\n        Real phi_prime_0 = (1 - eta_dbl_prime/(eta_prime_0*eta_prime_0))/2;\n        weight *= phi_prime_0;\n        return {node, weight};\n    }\n    Real x = n*h;\n    auto p = ooura_eta(x, alpha);\n    auto eta = p.first;\n    auto eta_prime = p.second;\n\n    Real expm1_meta = expm1(-eta);\n    Real exp_meta = exp(-eta);\n    Real node = -n*pi<Real>()/expm1_meta;\n\n\n    // I have verified that this is not a significant source of inaccuracy in the weight computation:\n    Real phi_prime = -(expm1_meta + x*exp_meta*eta_prime)/(expm1_meta*expm1_meta);\n\n    // The main source of inaccuracy is in computation of sin_pi.\n    // But I've agonized over this, and I think it's as good as it can get:\n    Real s = pi<Real>();\n    Real arg;\n    if(eta > 1) {\n        arg = n/( 1/exp_meta - 1 );\n        s *= boost::math::sin_pi(arg);\n        if (n&1) {\n            s *= -1;\n        }\n    }\n    else if (eta < -1) {\n        arg = n/(1-exp_meta);\n        s *= boost::math::sin_pi(arg);\n    }\n    else {\n        arg = -n*exp_meta/expm1_meta;\n        s *= boost::math::sin_pi(arg);\n        if (n&1) {\n            s *= -1;\n        }\n    }\n\n    Real weight = s*phi_prime;\n    return {node, weight};\n}\n\n#ifdef BOOST_MATH_INSTRUMENT_OOURA\ntemplate<class Real>\nvoid print_ooura_estimate(size_t i, Real I0, Real I1, Real omega) {\n    using std::abs;\n    std::cout << std::defaultfloat\n              << std::setprecision(std::numeric_limits<Real>::digits10)\n              << std::fixed;\n    std::cout << \"h = \" << Real(1)/Real(1<<i) << \", I_h = \" << I0/omega\n              << \" = \" << std::hexfloat << I0/omega << \", absolute error estimate = \"\n              << std::defaultfloat << std::scientific << abs(I0-I1)  << std::endl;\n}\n#endif\n\n\ntemplate<class Real>\nstd::pair<Real, Real> ooura_cos_node_and_weight(long n, Real h, Real alpha)\n{\n    using std::expm1;\n    using std::exp;\n    using std::abs;\n    using boost::math::constants::pi;\n\n    Real x = h*(n-Real(1)/Real(2));\n    auto p = ooura_eta(x, alpha);\n    auto eta = p.first;\n    auto eta_prime = p.second;\n    Real expm1_meta = expm1(-eta);\n    Real exp_meta = exp(-eta);\n    Real node = pi<Real>()*(Real(1)/Real(2)-n)/expm1_meta;\n\n    Real phi_prime = -(expm1_meta + x*exp_meta*eta_prime)/(expm1_meta*expm1_meta);\n\n    // Takuya Ooura and Masatake Mori,\n    // Journal of Computational and Applied Mathematics, 112 (1999) 229-241.\n    // A robust double exponential formula for Fourier-type integrals.\n    // Equation 4.6\n    Real s = pi<Real>();\n    Real arg;\n    if (eta < -1) {\n        arg = -(n-Real(1)/Real(2))/expm1_meta;\n        s *= boost::math::cos_pi(arg);\n    }\n    else {\n        arg = -(n-Real(1)/Real(2))*exp_meta/expm1_meta;\n        s *= boost::math::sin_pi(arg);\n        if (n&1) {\n            s *= -1;\n        }\n    }\n\n    Real weight = s*phi_prime;\n    return {node, weight};\n}\n\n\ntemplate<class Real>\nclass ooura_fourier_sin_detail {\npublic:\n    ooura_fourier_sin_detail(const Real relative_error_goal, size_t levels) {\n#ifdef BOOST_MATH_INSTRUMENT_OOURA\n      std::cout << \"ooura_fourier_sin with relative error goal \" << relative_error_goal \n        << \" & \" << levels << \" levels.\" << std::endl;\n#endif // BOOST_MATH_INSTRUMENT_OOURA\n        if (relative_error_goal < std::numeric_limits<Real>::epsilon() * 2) {\n            throw std::domain_error(\"The relative error goal cannot be smaller than the unit roundoff.\");\n        }\n        using std::abs;\n        requested_levels_ = levels;\n        starting_level_ = 0;\n        rel_err_goal_ = relative_error_goal;\n        big_nodes_.reserve(levels);\n        bweights_.reserve(levels);\n        little_nodes_.reserve(levels);\n        lweights_.reserve(levels);\n\n        for (size_t i = 0; i < levels; ++i) {\n            if (std::is_same<Real, float>::value) {\n                add_level<double>(i);\n            }\n            else if (std::is_same<Real, double>::value) {\n                add_level<long double>(i);\n            }\n            else {\n                add_level<Real>(i);\n            }\n        }\n    }\n\n    std::vector<std::vector<Real>> const & big_nodes() const {\n        return big_nodes_;\n    }\n\n    std::vector<std::vector<Real>> const & weights_for_big_nodes() const {\n        return bweights_;\n    }\n\n    std::vector<std::vector<Real>> const & little_nodes() const {\n        return little_nodes_;\n    }\n\n    std::vector<std::vector<Real>> const & weights_for_little_nodes() const {\n        return lweights_;\n    }\n\n    template<class F>\n    std::pair<Real,Real> integrate(F const & f, Real omega) {\n        using std::abs;\n        using std::max;\n        using boost::math::constants::pi;\n\n        if (omega == 0) {\n            return {Real(0), Real(0)};\n        }\n        if (omega < 0) {\n            auto p = this->integrate(f, -omega);\n            return {-p.first, p.second};\n        }\n\n        Real I1 = std::numeric_limits<Real>::quiet_NaN();\n        Real relative_error_estimate = std::numeric_limits<Real>::quiet_NaN();\n        // As we compute integrals, we learn about their structure.\n        // Assuming we compute f(t)sin(wt) for many different omega, this gives some\n        // a posteriori ability to choose a refinement level that is roughly appropriate.\n        size_t i = starting_level_;\n        do {\n            Real I0 = estimate_integral(f, omega, i);\n#ifdef BOOST_MATH_INSTRUMENT_OOURA\n            print_ooura_estimate(i, I0, I1, omega);\n#endif\n            Real absolute_error_estimate = abs(I0-I1);\n            Real scale = (max)(abs(I0), abs(I1));\n            if (!isnan(I1) && absolute_error_estimate <= rel_err_goal_*scale) {\n                starting_level_ = (max)(long(i) - 1, long(0));\n                return {I0/omega, absolute_error_estimate/scale};\n            }\n            I1 = I0;\n        } while(++i < big_nodes_.size());\n\n        // We've used up all our precomputed levels.\n        // Now we need to add more.\n        // It might seems reasonable to just keep adding levels indefinitely, if that's what the user wants.\n        // But in fact the nodes and weights just merge into each other and the error gets worse after a certain number.\n        // This value for max_additional_levels was chosen by observation of a slowly converging oscillatory integral:\n        // f(x) := cos(7cos(x))sin(x)/x\n        size_t max_additional_levels = 4;\n        while (big_nodes_.size() < requested_levels_ + max_additional_levels) {\n            size_t ii = big_nodes_.size();\n            if (std::is_same<Real, float>::value) {\n                add_level<double>(ii);\n            }\n            else if (std::is_same<Real, double>::value) {\n                add_level<long double>(ii);\n            }\n            else {\n                add_level<Real>(ii);\n            }\n            Real I0 = estimate_integral(f, omega, ii);\n            Real absolute_error_estimate = abs(I0-I1);\n            Real scale = (max)(abs(I0), abs(I1));\n#ifdef BOOST_MATH_INSTRUMENT_OOURA\n            print_ooura_estimate(ii, I0, I1, omega);\n#endif\n            if (absolute_error_estimate <= rel_err_goal_*scale) {\n                starting_level_ = (max)(long(ii) - 1, long(0));\n                return {I0/omega, absolute_error_estimate/scale};\n            }\n            I1 = I0;\n            ++ii;\n        }\n\n        starting_level_ = static_cast<long>(big_nodes_.size() - 2);\n        return {I1/omega, relative_error_estimate};\n    }\n\nprivate:\n\n    template<class PreciseReal>\n    void add_level(size_t i) {\n        using std::abs;\n        size_t current_num_levels = big_nodes_.size();\n        Real unit_roundoff = std::numeric_limits<Real>::epsilon()/2;\n        // h0 = 1. Then all further levels have h_i = 1/2^i.\n        // Since the nodes don't nest, we could conceivably divide h by (say) 1.5, or 3.\n        // It's not clear how much benefit (or loss) would be obtained from this.\n        PreciseReal h = PreciseReal(1)/PreciseReal(1<<i);\n\n        std::vector<Real> bnode_row;\n        std::vector<Real> bweight_row;\n\n        // This is a pretty good estimate for how many elements will be placed in the vector:\n        bnode_row.reserve((static_cast<size_t>(1)<<i)*sizeof(Real));\n        bweight_row.reserve((static_cast<size_t>(1)<<i)*sizeof(Real));\n\n        std::vector<Real> lnode_row;\n        std::vector<Real> lweight_row;\n\n        lnode_row.reserve((static_cast<size_t>(1)<<i)*sizeof(Real));\n        lweight_row.reserve((static_cast<size_t>(1)<<i)*sizeof(Real));\n\n        Real max_weight = 1;\n        auto alpha = calculate_ooura_alpha(h);\n        long n = 0;\n        Real w;\n        do {\n            auto precise_nw = ooura_sin_node_and_weight(n, h, alpha);\n            Real node = static_cast<Real>(precise_nw.first);\n            Real weight = static_cast<Real>(precise_nw.second);\n            w = weight;\n            if (bnode_row.size() == bnode_row.capacity()) {\n                bnode_row.reserve(2*bnode_row.size());\n                bweight_row.reserve(2*bnode_row.size());\n            }\n\n            bnode_row.push_back(node);\n            bweight_row.push_back(weight);\n            if (abs(weight) > max_weight) {\n                max_weight = abs(weight);\n            }\n            ++n;\n            // f(t)->0 as t->infty, which is why the weights are computed up to the unit roundoff.\n        } while(abs(w) > unit_roundoff*max_weight);\n\n        // This class tends to consume a lot of memory; shrink the vectors back down to size:\n        bnode_row.shrink_to_fit();\n        bweight_row.shrink_to_fit();\n        // Why we are splitting the nodes into regimes where t_n >> 1 and t_n << 1?\n        // It will create the opportunity to sensibly truncate the quadrature sum to significant terms.\n        n = -1;\n        do {\n            auto precise_nw = ooura_sin_node_and_weight(n, h, alpha);\n            Real node = static_cast<Real>(precise_nw.first);\n            if (node <= 0) {\n                break;\n            }\n            Real weight = static_cast<Real>(precise_nw.second);\n            w = weight;\n            using std::isnan;\n            if (isnan(node)) {\n                // This occurs at n = -11 in quad precision:\n                break;\n            }\n            if (lnode_row.size() > 0) {\n                if (lnode_row[lnode_row.size()-1] == node) {\n                    // The nodes have fused into each other:\n                    break;\n                }\n            }\n            if (lnode_row.size() == lnode_row.capacity()) {\n                lnode_row.reserve(2*lnode_row.size());\n                lweight_row.reserve(2*lnode_row.size());\n            }\n            lnode_row.push_back(node);\n            lweight_row.push_back(weight);\n            if (abs(weight) > max_weight) {\n                max_weight = abs(weight);\n            }\n            --n;\n            // f(t)->infty is possible as t->0, hence compute up to the min.\n        } while(abs(w) > (std::numeric_limits<Real>::min)()*max_weight);\n\n        lnode_row.shrink_to_fit();\n        lweight_row.shrink_to_fit();\n\n        // std::scoped_lock once C++17 is more common?\n        std::lock_guard<std::mutex> lock(node_weight_mutex_);\n        // Another thread might have already finished this calculation and appended it to the nodes/weights:\n        if (current_num_levels == big_nodes_.size()) {\n            big_nodes_.push_back(bnode_row);\n            bweights_.push_back(bweight_row);\n\n            little_nodes_.push_back(lnode_row);\n            lweights_.push_back(lweight_row);\n        }\n    }\n\n    template<class F>\n    Real estimate_integral(F const & f, Real omega, size_t i) {\n        // Because so few function evaluations are required to get high accuracy on the integrals in the tests,\n        // Kahan summation doesn't really help.\n        //auto cond = boost::math::tools::summation_condition_number<Real, true>(0);\n        Real I0 = 0;\n        auto const & b_nodes = big_nodes_[i];\n        auto const & b_weights = bweights_[i];\n        // Will benchmark if this is helpful:\n        Real inv_omega = 1/omega;\n        for(size_t j = 0 ; j < b_nodes.size(); ++j) {\n            I0 += f(b_nodes[j]*inv_omega)*b_weights[j];\n        }\n\n        auto const & l_nodes = little_nodes_[i];\n        auto const & l_weights = lweights_[i];\n        // If f decays rapidly as |t|->infty, not all of these calls are necessary.\n        for (size_t j = 0; j < l_nodes.size(); ++j) {\n            I0 += f(l_nodes[j]*inv_omega)*l_weights[j];\n        }\n        return I0;\n    }\n\n    std::mutex node_weight_mutex_;\n    // Nodes for n >= 0, giving t_n = pi*phi(nh)/h. Generally t_n >> 1.\n    std::vector<std::vector<Real>> big_nodes_;\n    // The term bweights_ will indicate that these are weights corresponding\n    // to the big nodes:\n    std::vector<std::vector<Real>> bweights_;\n\n    // Nodes for n < 0: Generally t_n << 1, and an invariant is that t_n > 0.\n    std::vector<std::vector<Real>> little_nodes_;\n    std::vector<std::vector<Real>> lweights_;\n    Real rel_err_goal_;\n    std::atomic<long> starting_level_;\n    size_t requested_levels_;\n};\n\ntemplate<class Real>\nclass ooura_fourier_cos_detail {\npublic:\n    ooura_fourier_cos_detail(const Real relative_error_goal, size_t levels) {\n#ifdef BOOST_MATH_INSTRUMENT_OOURA\n      std::cout << \"ooura_fourier_cos with relative error goal \" << relative_error_goal\n        << \" & \" << levels << \" levels.\" << std::endl;\n      std::cout << \"epsilon for type = \" << std::numeric_limits<Real>::epsilon() << std::endl;\n#endif // BOOST_MATH_INSTRUMENT_OOURA\n        if (relative_error_goal < std::numeric_limits<Real>::epsilon() * 2) {\n            throw std::domain_error(\"The relative error goal cannot be smaller than the unit roundoff!\");\n        }\n\n        using std::abs;\n        requested_levels_ = levels;\n        starting_level_ = 0;\n        rel_err_goal_ = relative_error_goal;\n        big_nodes_.reserve(levels);\n        bweights_.reserve(levels);\n        little_nodes_.reserve(levels);\n        lweights_.reserve(levels);\n\n        for (size_t i = 0; i < levels; ++i) {\n            if (std::is_same<Real, float>::value) {\n                add_level<double>(i);\n            }\n            else if (std::is_same<Real, double>::value) {\n                add_level<long double>(i);\n            }\n            else {\n                add_level<Real>(i);\n            }\n        }\n\n    }\n\n    template<class F>\n    std::pair<Real,Real> integrate(F const & f, Real omega) {\n        using std::abs;\n        using std::max;\n        using boost::math::constants::pi;\n\n        if (omega == 0) {\n            throw std::domain_error(\"At omega = 0, the integral is not oscillatory. The user must choose an appropriate method for this case.\\n\");\n        }\n\n        if (omega < 0) {\n            return this->integrate(f, -omega);\n        }\n\n        Real I1 = std::numeric_limits<Real>::quiet_NaN();\n        Real absolute_error_estimate = std::numeric_limits<Real>::quiet_NaN();\n        Real scale = std::numeric_limits<Real>::quiet_NaN();\n        size_t i = starting_level_;\n        do {\n            Real I0 = estimate_integral(f, omega, i);\n#ifdef BOOST_MATH_INSTRUMENT_OOURA\n            print_ooura_estimate(i, I0, I1, omega);\n#endif\n            absolute_error_estimate = abs(I0-I1);\n            scale = (max)(abs(I0), abs(I1));\n            if (!isnan(I1) && absolute_error_estimate <= rel_err_goal_*scale) {\n                starting_level_ = (max)(long(i) - 1, long(0));\n                return {I0/omega, absolute_error_estimate/scale};\n            }\n            I1 = I0;\n        } while(++i < big_nodes_.size());\n\n        size_t max_additional_levels = 4;\n        while (big_nodes_.size() < requested_levels_ + max_additional_levels) {\n            size_t ii = big_nodes_.size();\n            if (std::is_same<Real, float>::value) {\n                add_level<double>(ii);\n            }\n            else if (std::is_same<Real, double>::value) {\n                add_level<long double>(ii);\n            }\n            else {\n                add_level<Real>(ii);\n            }\n            Real I0 = estimate_integral(f, omega, ii);\n#ifdef BOOST_MATH_INSTRUMENT_OOURA\n            print_ooura_estimate(ii, I0, I1, omega);\n#endif\n            absolute_error_estimate = abs(I0-I1);\n            scale = (max)(abs(I0), abs(I1));\n            if (absolute_error_estimate <= rel_err_goal_*scale) {\n                starting_level_ = (max)(long(ii) - 1, long(0));\n                return {I0/omega, absolute_error_estimate/scale};\n            }\n            I1 = I0;\n            ++ii;\n        }\n\n        starting_level_ = static_cast<long>(big_nodes_.size() - 2);\n        return {I1/omega, absolute_error_estimate/scale};\n    }\n\nprivate:\n\n    template<class PreciseReal>\n    void add_level(size_t i) {\n        using std::abs;\n        size_t current_num_levels = big_nodes_.size();\n        Real unit_roundoff = std::numeric_limits<Real>::epsilon()/2;\n        PreciseReal h = PreciseReal(1)/PreciseReal(1<<i);\n\n        std::vector<Real> bnode_row;\n        std::vector<Real> bweight_row;\n        bnode_row.reserve((static_cast<size_t>(1)<<i)*sizeof(Real));\n        bweight_row.reserve((static_cast<size_t>(1)<<i)*sizeof(Real));\n\n        std::vector<Real> lnode_row;\n        std::vector<Real> lweight_row;\n\n        lnode_row.reserve((static_cast<size_t>(1)<<i)*sizeof(Real));\n        lweight_row.reserve((static_cast<size_t>(1)<<i)*sizeof(Real));\n\n        Real max_weight = 1;\n        auto alpha = calculate_ooura_alpha(h);\n        long n = 0;\n        Real w;\n        do {\n            auto precise_nw = ooura_cos_node_and_weight(n, h, alpha);\n            Real node = static_cast<Real>(precise_nw.first);\n            Real weight = static_cast<Real>(precise_nw.second);\n            w = weight;\n            if (bnode_row.size() == bnode_row.capacity()) {\n                bnode_row.reserve(2*bnode_row.size());\n                bweight_row.reserve(2*bnode_row.size());\n            }\n\n            bnode_row.push_back(node);\n            bweight_row.push_back(weight);\n            if (abs(weight) > max_weight) {\n                max_weight = abs(weight);\n            }\n            ++n;\n            // f(t)->0 as t->infty, which is why the weights are computed up to the unit roundoff.\n        } while(abs(w) > unit_roundoff*max_weight);\n\n        bnode_row.shrink_to_fit();\n        bweight_row.shrink_to_fit();\n        n = -1;\n        do {\n            auto precise_nw = ooura_cos_node_and_weight(n, h, alpha);\n            Real node = static_cast<Real>(precise_nw.first);\n            // The function cannot be singular at zero,\n            // so zero is not a unreasonable node,\n            // unlike in the case of the Fourier Sine.\n            // Hence only break if the node is negative.\n            if (node < 0) {\n                break;\n            }\n            Real weight = static_cast<Real>(precise_nw.second);\n            w = weight;\n            if (lnode_row.size() > 0) {\n                if (lnode_row.back() == node) {\n                    // The nodes have fused into each other:\n                    break;\n                }\n            }\n            if (lnode_row.size() == lnode_row.capacity()) {\n                lnode_row.reserve(2*lnode_row.size());\n                lweight_row.reserve(2*lnode_row.size());\n            }\n\n            lnode_row.push_back(node);\n            lweight_row.push_back(weight);\n            if (abs(weight) > max_weight) {\n                max_weight = abs(weight);\n            }\n            --n;\n        } while(abs(w) > (std::numeric_limits<Real>::min)()*max_weight);\n\n        lnode_row.shrink_to_fit();\n        lweight_row.shrink_to_fit();\n\n        std::lock_guard<std::mutex> lock(node_weight_mutex_);\n        // Another thread might have already finished this calculation and appended it to the nodes/weights:\n        if (current_num_levels == big_nodes_.size()) {\n            big_nodes_.push_back(bnode_row);\n            bweights_.push_back(bweight_row);\n\n            little_nodes_.push_back(lnode_row);\n            lweights_.push_back(lweight_row);\n        }\n    }\n\n    template<class F>\n    Real estimate_integral(F const & f, Real omega, size_t i) {\n        Real I0 = 0;\n        auto const & b_nodes = big_nodes_[i];\n        auto const & b_weights = bweights_[i];\n        Real inv_omega = 1/omega;\n        for(size_t j = 0 ; j < b_nodes.size(); ++j) {\n            I0 += f(b_nodes[j]*inv_omega)*b_weights[j];\n        }\n\n        auto const & l_nodes = little_nodes_[i];\n        auto const & l_weights = lweights_[i];\n        for (size_t j = 0; j < l_nodes.size(); ++j) {\n            I0 += f(l_nodes[j]*inv_omega)*l_weights[j];\n        }\n        return I0;\n    }\n\n    std::mutex node_weight_mutex_;\n    std::vector<std::vector<Real>> big_nodes_;\n    std::vector<std::vector<Real>> bweights_;\n\n    std::vector<std::vector<Real>> little_nodes_;\n    std::vector<std::vector<Real>> lweights_;\n    Real rel_err_goal_;\n    std::atomic<long> starting_level_;\n    size_t requested_levels_;\n};\n\n\n}}}}\n#endif\n", "meta": {"hexsha": "5dc2499334c0804e8cf0320a7413e1bdba592b48", "size": 23586, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/quadrature/detail/ooura_fourier_integrals_detail.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 597.0, "max_stars_repo_stars_event_min_datetime": "2018-07-17T10:59:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:59:36.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/quadrature/detail/ooura_fourier_integrals_detail.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/quadrature/detail/ooura_fourier_integrals_detail.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 112.0, "max_forks_repo_forks_event_min_datetime": "2018-07-26T04:36:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T02:29:34.000Z", "avg_line_length": 36.1748466258, "max_line_length": 146, "alphanum_fraction": 0.5821673874, "num_tokens": 5967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.42147789508488914}}
{"text": "#pragma once\n\n#if defined(_OPENMP)\n#include <omp.h>\n#endif\n\n#include <cstdint>\n#include <functional>\n#include <limits>\n#include <stdexcept>\n#include <vector>\n\n#include <Eigen/Geometry>\n#include <common_robotics_utilities/openmp_helpers.hpp>\n\nnamespace common_robotics_utilities\n{\n/// Compute Hausdorff distance between two distributions.\n/// \"The Hausdorff distance is the longest distance you can be forced to travel\n/// by an adversary who chooses a point in one of the two sets, from where you\n/// then must travel to the other set. In other words, it is the greatest of all\n/// the distances from a point in one set to the closest point in the other\n/// set.\" - from Wikipedia\nnamespace simple_hausdorff_distance\n{\n/// Compute Hausdorff distance between @param first_distribution and @param\n/// second_distribution using @param distance_function to compute distance\n/// between an element in @param first_distribution and an element in @param\n/// second_distribution. @return distance between distributions.\n/// Computation is performed in parallel, and the larger of the two input\n/// distributions is automatically selected to be the outer (parallelized) loop.\ntemplate<typename FirstDatatype, typename SecondDatatype,\n         typename FirstContainer=std::vector<FirstDatatype>,\n         typename SecondContainer=std::vector<SecondDatatype>>\ninline double ComputeDistanceParallel(\n    const FirstContainer& first_distribution,\n    const SecondContainer& second_distribution,\n    const std::function<double(const FirstDatatype&,\n                               const SecondDatatype&)>& distance_fn)\n{\n  if (first_distribution.empty())\n  {\n    throw std::invalid_argument(\"first_distribution is empty\");\n  }\n  if (second_distribution.empty())\n  {\n    throw std::invalid_argument(\"second_distribution is empty\");\n  }\n  // Swap if needed to make the outer parallel loop be larger\n  const bool swap = (first_distribution.size() < second_distribution.size());\n  const auto& outer_distribution\n      = (swap) ? second_distribution : first_distribution;\n  const auto& inner_distribution\n      = (swap) ? first_distribution : second_distribution;\n  // Make per-thread storage\n  std::vector<double> per_thread_storage(\n      openmp_helpers::GetNumOmpThreads(), 0.0);\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n  for (size_t idx = 0; idx < outer_distribution.size(); idx++)\n  {\n    const FirstDatatype& first = outer_distribution[idx];\n    double minimum_distance = std::numeric_limits<double>::infinity();\n    for (size_t jdx = 0; jdx < inner_distribution.size(); jdx++)\n    {\n      const SecondDatatype& second = inner_distribution[jdx];\n      const double current_distance = distance_fn(first, second);\n      if (current_distance < minimum_distance)\n      {\n        minimum_distance = current_distance;\n      }\n    }\n    const auto current_thread_id = openmp_helpers::GetContextOmpThreadNum();\n    if (minimum_distance > per_thread_storage.at(current_thread_id))\n    {\n      per_thread_storage.at(current_thread_id) = minimum_distance;\n    }\n  }\n  double maximum_minimum_distance = 0.0;\n  for (const double& temp_minimum_distance : per_thread_storage)\n  {\n    if (temp_minimum_distance > maximum_minimum_distance)\n    {\n      maximum_minimum_distance = temp_minimum_distance;\n    }\n  }\n  return maximum_minimum_distance;\n}\n\n/// Compute Hausdorff distance between @param first_distribution and @param\n/// second_distribution using @param distance_function to compute distance\n/// between an element in @param first_distribution and an element in @param\n/// second_distribution. @return distance between distributions.\ntemplate<typename FirstDatatype, typename SecondDatatype,\n         typename FirstContainer=std::vector<FirstDatatype>,\n         typename SecondContainer=std::vector<SecondDatatype>>\ninline double ComputeDistanceSerial(\n    const FirstContainer& first_distribution,\n    const SecondContainer& second_distribution,\n    const std::function<double(const FirstDatatype&,\n                               const SecondDatatype&)>& distance_fn)\n{\n  if (first_distribution.empty())\n  {\n    throw std::invalid_argument(\"first_distribution is empty\");\n  }\n  if (second_distribution.empty())\n  {\n    throw std::invalid_argument(\"second_distribution is empty\");\n  }\n  double maximum_minimum_distance = 0.0;\n  for (size_t idx = 0; idx < first_distribution.size(); idx++)\n  {\n    const FirstDatatype& first = first_distribution[idx];\n    double minimum_distance = std::numeric_limits<double>::infinity();\n    for (size_t jdx = 0; jdx < second_distribution.size(); jdx++)\n    {\n      const SecondDatatype& second = second_distribution[jdx];\n      const double current_distance = distance_fn(first, second);\n      if (current_distance < minimum_distance)\n      {\n        minimum_distance = current_distance;\n      }\n    }\n    if (minimum_distance > maximum_minimum_distance)\n    {\n      maximum_minimum_distance = minimum_distance;\n    }\n  }\n  return maximum_minimum_distance;\n}\n\n/// Compute Hausdorff distance between @param first_distribution and @param\n/// second_distribution using @param distance_matrix which stores the pairwise\n/// distance between all elements in @param first_distribution and @param\n/// second_distribution. @return distance between distributions.\n/// Computation is performed in parallel, and the larger of the two input\n/// distributions is automatically selected to be the outer (parallelized) loop.\ntemplate<typename FirstDatatype, typename SecondDatatype,\n         typename FirstContainer=std::vector<FirstDatatype>,\n         typename SecondContainer=std::vector<SecondDatatype>>\ninline double ComputeDistanceParallel(\n    const FirstContainer& first_distribution,\n    const SecondContainer& second_distribution,\n    const Eigen::MatrixXd& distance_matrix)\n{\n  if (first_distribution.empty())\n  {\n    throw std::invalid_argument(\"first_distribution is empty\");\n  }\n  if (second_distribution.empty())\n  {\n    throw std::invalid_argument(\"second_distribution is empty\");\n  }\n  if (static_cast<size_t>(distance_matrix.rows()) != first_distribution.size()\n      || static_cast<size_t>(distance_matrix.cols())\n         != second_distribution.size())\n  {\n    throw std::invalid_argument(\"distance_matrix is the wrong size\");\n  }\n  // Swap if needed to make the outer parallel loop be larger\n  const bool swap = (first_distribution.size() < second_distribution.size());\n  const auto& outer_distribution\n      = (swap) ? second_distribution : first_distribution;\n  const auto& inner_distribution\n      = (swap) ? first_distribution : second_distribution;\n  // Make per-thread storage\n  std::vector<double> per_thread_storage(\n      openmp_helpers::GetNumOmpThreads(), 0.0);\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n  for (size_t idx = 0; idx < outer_distribution.size(); idx++)\n  {\n    double minimum_distance = std::numeric_limits<double>::infinity();\n    for (size_t jdx = 0; jdx < inner_distribution.size(); jdx++)\n    {\n      // Swap the lookup if we've swapped the loops\n      const ssize_t row = (swap) ? static_cast<ssize_t>(jdx)\n                                 : static_cast<ssize_t>(idx);\n      const ssize_t col = (swap) ? static_cast<ssize_t>(idx)\n                                 : static_cast<ssize_t>(jdx);\n      const double current_distance = distance_matrix(row, col);\n      if (current_distance < minimum_distance)\n      {\n        minimum_distance = current_distance;\n      }\n    }\n    const auto current_thread_id = openmp_helpers::GetContextOmpThreadNum();\n    if (minimum_distance > per_thread_storage.at(current_thread_id))\n    {\n      per_thread_storage.at(current_thread_id) = minimum_distance;\n    }\n  }\n  double maximum_minimum_distance = 0.0;\n  for (const double& temp_minimum_distance : per_thread_storage)\n  {\n    if (temp_minimum_distance > maximum_minimum_distance)\n    {\n      maximum_minimum_distance = temp_minimum_distance;\n    }\n  }\n  return maximum_minimum_distance;\n}\n\n/// Compute Hausdorff distance between @param first_distribution and @param\n/// second_distribution using @param distance_matrix which stores the pairwise\n/// distance between all elements in @param first_distribution and @param\n/// second_distribution. @return distance between distributions.\ntemplate<typename FirstDatatype, typename SecondDatatype,\n         typename FirstContainer=std::vector<FirstDatatype>,\n         typename SecondContainer=std::vector<SecondDatatype>>\ninline double ComputeDistanceSerial(\n    const FirstContainer& first_distribution,\n    const SecondContainer& second_distribution,\n    const Eigen::MatrixXd& distance_matrix)\n{\n  if (first_distribution.empty())\n  {\n    throw std::invalid_argument(\"first_distribution is empty\");\n  }\n  if (second_distribution.empty())\n  {\n    throw std::invalid_argument(\"second_distribution is empty\");\n  }\n  if (static_cast<size_t>(distance_matrix.rows()) != first_distribution.size()\n      || static_cast<size_t>(distance_matrix.cols())\n         != second_distribution.size())\n  {\n    throw std::invalid_argument(\"distance_matrix is the wrong size\");\n  }\n  double maximum_minimum_distance = 0.0;\n  for (size_t idx = 0; idx < first_distribution.size(); idx++)\n  {\n    double minimum_distance = std::numeric_limits<double>::infinity();\n    for (size_t jdx = 0; jdx < second_distribution.size(); jdx++)\n    {\n      const double current_distance\n          = distance_matrix(static_cast<ssize_t>(idx),\n                            static_cast<ssize_t>(jdx));\n      if (current_distance < minimum_distance)\n      {\n        minimum_distance = current_distance;\n      }\n    }\n    if (minimum_distance > maximum_minimum_distance)\n    {\n      maximum_minimum_distance = minimum_distance;\n    }\n  }\n  return maximum_minimum_distance;\n}\n\n/// Compute Hausdorff distance between @param first_distribution and @param\n/// second_distribution using @param distance_function to compute distance\n/// between an element in @param first_distribution and an element in @param\n/// second_distribution. @return distance between distributions.\n/// @param use_parallel selects if the computation should be performed in\n/// parallel. If computation is performed in parallel, the larger of the two\n/// input distributions is automatically selected to be the outer (parallelized)\n/// loop.\ntemplate<typename FirstDatatype, typename SecondDatatype,\n         typename FirstContainer=std::vector<FirstDatatype>,\n         typename SecondContainer=std::vector<SecondDatatype>>\ninline double ComputeDistance(\n    const FirstContainer& first_distribution,\n    const SecondContainer& second_distribution,\n    const std::function<double(const FirstDatatype&,\n                               const SecondDatatype&)>& distance_fn,\n    const bool use_parallel = false)\n{\n  if (use_parallel)\n  {\n    return ComputeDistanceParallel\n        <FirstDatatype, SecondDatatype, FirstContainer, SecondContainer>(\n            first_distribution, second_distribution, distance_fn);\n  }\n  else\n  {\n    return ComputeDistanceSerial\n        <FirstDatatype, SecondDatatype, FirstContainer, SecondContainer>(\n            first_distribution, second_distribution, distance_fn);\n  }\n}\n\n/// Compute Hausdorff distance between @param first_distribution and @param\n/// second_distribution using @param distance_matrix which stores the pairwise\n/// distance between all elements in @param first_distribution and @param\n/// second_distribution. @return distance between distributions.\n/// @param use_parallel selects if the computation should be performed in\n/// parallel. If computation is performed in parallel, the larger of the two\n/// input distributions is automatically selected to be the outer (parallelized)\n/// loop.\ntemplate<typename FirstDatatype, typename SecondDatatype,\n         typename FirstContainer=std::vector<FirstDatatype>,\n         typename SecondContainer=std::vector<SecondDatatype>>\ninline double ComputeDistance(\n    const FirstContainer& first_distribution,\n    const SecondContainer& second_distribution,\n    const Eigen::MatrixXd& distance_matrix,\n    const bool use_parallel = false)\n{\n  if (use_parallel)\n  {\n    return ComputeDistanceParallel\n        <FirstDatatype, SecondDatatype, FirstContainer, SecondContainer>(\n            first_distribution, second_distribution, distance_matrix);\n  }\n  else\n  {\n    return ComputeDistanceSerial\n        <FirstDatatype, SecondDatatype, FirstContainer, SecondContainer>(\n            first_distribution, second_distribution, distance_matrix);\n  }\n}\n}  // namespace simple_hausdorff_distance\n}  // namespace common_robotics_utilities\n", "meta": {"hexsha": "740289d332bdb88439c833235a6662bc6ff48b3c", "size": 12548, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common_robotics_utilities/simple_hausdorff_distance.hpp", "max_stars_repo_name": "calderpg/common_robotics_utilities", "max_stars_repo_head_hexsha": "8b1c06dd45b283f8234c6a4d565bcb7078d1a851", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-10-15T19:04:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T01:35:16.000Z", "max_issues_repo_path": "include/common_robotics_utilities/simple_hausdorff_distance.hpp", "max_issues_repo_name": "calderpg/common_robotics_utilities", "max_issues_repo_head_hexsha": "8b1c06dd45b283f8234c6a4d565bcb7078d1a851", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-18T19:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-21T15:08:21.000Z", "max_forks_repo_path": "include/common_robotics_utilities/simple_hausdorff_distance.hpp", "max_forks_repo_name": "calderpg/common_robotics_utilities", "max_forks_repo_head_hexsha": "8b1c06dd45b283f8234c6a4d565bcb7078d1a851", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-10-17T21:12:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-18T03:53:47.000Z", "avg_line_length": 39.3354231975, "max_line_length": 80, "alphanum_fraction": 0.7319891616, "num_tokens": 2608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.42142902819302797}}
{"text": "/*\n * Copyright (c) 2011-2019, The DART development contributors\n * All rights reserved.\n *\n * The list of contributors can be found at:\n *   https://github.com/dartsim/dart/blob/master/LICENSE\n *\n * This file is provided under the following \"BSD-style\" License:\n *   Redistribution and use in source and binary forms, with or\n *   without modification, are permitted provided that the following\n *   conditions are met:\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n *   CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *   POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef DART_MATH_GEOMETRY_HPP_\n#define DART_MATH_GEOMETRY_HPP_\n\n#include <Eigen/Dense>\n\n#include \"dart/common/Deprecated.hpp\"\n#include \"dart/math/Constants.hpp\"\n#include \"dart/math/MathTypes.hpp\"\n\nnamespace dart {\nnamespace math {\n\n/// \\brief\nEigen::Matrix3s makeSkewSymmetric(const Eigen::Vector3s& _v);\n\n/// \\brief\nEigen::Vector3s fromSkewSymmetric(const Eigen::Matrix3s& _m);\n\n//------------------------------------------------------------------------------\n/// \\brief\nEigen::Quaternion_s expToQuat(const Eigen::Vector3s& _v);\n\n/// \\brief\nEigen::Vector3s quatToExp(const Eigen::Quaternion_s& _q);\n\n/// \\brief\nEigen::Vector3s rotatePoint(\n    const Eigen::Quaternion_s& _q, const Eigen::Vector3s& _pt);\n\n/// \\brief\nEigen::Vector3s rotatePoint(\n    const Eigen::Quaternion_s& _q, s_t _x, s_t _y, s_t _z);\n\n/// \\brief\nEigen::Matrix3s quatDeriv(const Eigen::Quaternion_s& _q, int _el);\n\n/// \\brief\nEigen::Matrix3s quatSecondDeriv(\n    const Eigen::Quaternion_s& _q, int _el1, int _el2);\n\n//------------------------------------------------------------------------------\n/// \\brief Given Euler XYX angles, return a 3x3 rotation matrix, which is\n/// equivalent to RotX(angle(0)) * RotY(angle(1)) * RotX(angle(2)).\nEigen::Matrix3s eulerXYXToMatrix(const Eigen::Vector3s& _angle);\n\n/// \\brief Given EulerXYZ angles, return a 3x3 rotation matrix, which is\n/// equivalent to RotX(angle(0)) * RotY(angle(1)) * RotZ(angle(2)).\nEigen::Matrix3s eulerXYZToMatrix(const Eigen::Vector3s& _angle);\n\n/// \\brief Given EulerXZX angles, return a 3x3 rotation matrix, which is\n/// equivalent to RotX(angle(0)) * RotZ(angle(1)) * RotX(angle(2)).\nEigen::Matrix3s eulerXZXToMatrix(const Eigen::Vector3s& _angle);\n\n/// \\brief Given EulerXZY angles, return a 3x3 rotation matrix, which is\n/// equivalent to RotX(angle(0)) * RotZ(angle(1)) * RotY(angle(2)).\nEigen::Matrix3s eulerXZYToMatrix(const Eigen::Vector3s& _angle);\n\n/// \\brief Given EulerYXY angles, return a 3x3 rotation matrix, which is\n/// equivalent to RotY(angle(0)) * RotX(angle(1)) * RotY(angle(2)).\nEigen::Matrix3s eulerYXYToMatrix(const Eigen::Vector3s& _angle);\n\n/// \\brief Given EulerYXZ angles, return a 3x3 rotation matrix, which is\n/// equivalent to RotY(angle(0)) * RotX(angle(1)) * RotZ(angle(2)).\nEigen::Matrix3s eulerYXZToMatrix(const Eigen::Vector3s& _angle);\n\n/// \\brief Given EulerYZX angles, return a 3x3 rotation matrix, which is\n/// equivalent to RotY(angle(0)) * RotZ(angle(1)) * RotX(angle(2)).\nEigen::Matrix3s eulerYZXToMatrix(const Eigen::Vector3s& _angle);\n\n/// \\brief Given EulerYZY angles, return a 3x3 rotation matrix, which is\n/// equivalent to RotY(angle(0)) * RotZ(angle(1)) * RotY(angle(2)).\nEigen::Matrix3s eulerYZYToMatrix(const Eigen::Vector3s& _angle);\n\n/// \\brief Given EulerZXY angles, return a 3x3 rotation matrix, which is\n/// equivalent to RotZ(angle(0)) * RotX(angle(1)) * RotY(angle(2)).\nEigen::Matrix3s eulerZXYToMatrix(const Eigen::Vector3s& _angle);\n\n/// \\brief Given EulerZYX angles, return a 3x3 rotation matrix, which is\n/// equivalent to RotZ(angle(0)) * RotY(angle(1)) * RotX(angle(2)).\n/// singularity : angle[1] = -+ 0.5*PI\nEigen::Matrix3s eulerZYXToMatrix(const Eigen::Vector3s& _angle);\n\n/// \\brief Given EulerZXZ angles, return a 3x3 rotation matrix, which is\n/// equivalent to RotZ(angle(0)) * RotX(angle(1)) * RotZ(angle(2)).\nEigen::Matrix3s eulerZXZToMatrix(const Eigen::Vector3s& _angle);\n\n/// \\brief Given EulerZYZ angles, return a 3x3 rotation matrix, which is\n/// equivalent to RotZ(angle(0)) * RotY(angle(1)) * RotZ(angle(2)).\n/// singularity : angle[1] = 0, PI\nEigen::Matrix3s eulerZYZToMatrix(const Eigen::Vector3s& _angle);\n\n//------------------------------------------------------------------------------\n/// \\brief get the Euler XYX angle from R\nEigen::Vector3s matrixToEulerXYX(const Eigen::Matrix3s& _R);\n\n/// \\brief get the Euler XYZ angle from R\nEigen::Vector3s matrixToEulerXYZ(const Eigen::Matrix3s& _R);\n\n///// \\brief get the Euler XZX angle from R\n// Eigen::Vector3s matrixToEulerXZX(const Eigen::Matrix3s& R);\n\n/// \\brief get the Euler XZY angle from R\nEigen::Vector3s matrixToEulerXZY(const Eigen::Matrix3s& _R);\n\n///// \\brief get the Euler YXY angle from R\n// Eigen::Vector3s matrixToEulerYXY(const Eigen::Matrix3s& R);\n\n/// \\brief get the Euler YXZ angle from R\nEigen::Vector3s matrixToEulerYXZ(const Eigen::Matrix3s& _R);\n\n/// \\brief get the Euler YZX angle from R\nEigen::Vector3s matrixToEulerYZX(const Eigen::Matrix3s& _R);\n\n///// \\brief get the Euler YZY angle from R\n// Eigen::Vector3s matrixToEulerYZY(const Eigen::Matrix3s& R);\n\n/// \\brief get the Euler ZXY angle from R\nEigen::Vector3s matrixToEulerZXY(const Eigen::Matrix3s& _R);\n\n/// \\brief get the Euler ZYX angle from R\nEigen::Vector3s matrixToEulerZYX(const Eigen::Matrix3s& _R);\n\n///// \\brief get the Euler ZXZ angle from R\n// Eigen::Vector3s matrixToEulerZXZ(const Eigen::Matrix3s& R);\n\n///// \\brief get the Euler ZYZ angle from R\n// Eigen::Vector3s matrixToEulerZYZ(const Eigen::Matrix3s& R);\n\n//------------------------------------------------------------------------------\n\n/// Returns the Jacobian of an SO(3) element w.r.t. its exponential\n/// coordinates where the Jacobian maps the time derivative of the exponential\n/// coordinates to the angular velocity in the world frame.\nEigen::Matrix3s so3LeftJacobian(const Eigen::Vector3s& w);\n\n/// Returns the Jacobian of an SO(3) element w.r.t. its exponential\n/// coordinates where the Jacobian maps the time derivative of the exponential\n/// coordinates to the angular velocity in the body frame.\nEigen::Matrix3s so3RightJacobian(const Eigen::Vector3s& w);\n\n/// Returns the time derivative of the left Jacobian of SO(3).\nEigen::Matrix3s so3LeftJacobianTimeDeriv(\n    const Eigen::Vector3s& q, const Eigen::Vector3s& dq);\n\n/// Returns the time derivative of the right Jacobian of SO(3).\nEigen::Matrix3s so3RightJacobianTimeDeriv(\n    const Eigen::Vector3s& q, const Eigen::Vector3s& dq);\n\n/// \\brief Exponential mapping\nEigen::Isometry3s expMap(const Eigen::Vector6s& _S);\n\n/// \\brief Exponential mapping, DART style. This treats the exponentiation\n/// operation as a rotation, and then a translation, rather than an integration\n/// of a screw.\nEigen::Isometry3s expMapDart(const Eigen::Vector6s& _S);\n\n/// \\brief fast version of Exp(se3(s, 0))\n/// \\todo This expAngular() can be replaced by Eigen::AngleAxis() but we need\n/// to verify that they have exactly same functionality.\n/// See: https://github.com/dartsim/dart/issues/88\nEigen::Isometry3s expAngular(const Eigen::Vector3s& _s);\n\n/// \\brief Computes the Rotation matrix from a given expmap vector.\nEigen::Matrix3s expMapRot(const Eigen::Vector3s& _expmap);\n\n/// \\brief Computes the Jacobian of the expmap\nEigen::Matrix3s expMapJac(const Eigen::Vector3s& _expmap);\n\n/// Returns the Jacobian of an SO(3) element w.r.t. its exponential\n/// coordinates where the Jacobian maps the time derivative of the exponential\n/// coordinates to the angular velocity in the world frame.\nEigen::Matrix3s so3LeftJacobian(const Eigen::Vector3s& w);\n\n/// Returns the Jacobian of an SO(3) element w.r.t. its exponential\n/// coordinates where the Jacobian maps the time derivative of the exponential\n/// coordinates to the angular velocity in the body frame.\nEigen::Matrix3s so3RightJacobian(const Eigen::Vector3s& w);\n\n/// \\brief Computes the Jacobian of the logMap(R * expMapRot(expMap))\nEigen::Matrix3s expMapJacAt(\n    const Eigen::Vector3s& _expmap, const Eigen::Matrix3s& R);\n\n/// \\brief Computes the time derivative of the expmap Jacobian.\nEigen::Matrix3s expMapJacDot(\n    const Eigen::Vector3s& _expmap, const Eigen::Vector3s& _qdot);\n\nEigen::Matrix3s so3LeftJacobianTimeDeriv(\n    const Eigen::Vector3s& q, const Eigen::Vector3s& dq);\n\nEigen::Matrix3s so3RightJacobianTimeDeriv(\n    const Eigen::Vector3s& q, const Eigen::Vector3s& dq);\n\nEigen::Matrix3s so3RightJacobianTimeDerivDeriv(\n    const Eigen::Vector3s& q, const Eigen::Vector3s& dq, int index);\n\nEigen::Matrix3s so3RightJacobianTimeDerivDeriv2(\n    const Eigen::Vector3s& q, const Eigen::Vector3s& dq, int index);\n\n/// \\brief computes the derivative of the Jacobian of the expmap wrt to _qi\n/// indexed dof; _qi \\f$ \\in \\f$ {0,1,2}\nEigen::Matrix3s expMapJacDeriv(const Eigen::Vector3s& _expmap, int _qi);\n\n/// \\brief computes the gradient of logMap(expMapRot()) wrt to _qi\n/// indexed dof; _qi \\f$ \\in \\f$ {0,1,2}\nEigen::Vector3s expMapGradient(const Eigen::Vector3s& pos, int _qi);\n\n/// \\brief computes the gradient of logMap(expMapRot(screw * eps) *\n/// expMapRot(original)) wrt to eps\nEigen::Vector3s expMapNestedGradient(\n    const Eigen::Vector3s& original, const Eigen::Vector3s& screw);\n\nEigen::Vector3s finiteDifferenceExpMapNestedGradient(\n    const Eigen::Vector3s& original,\n    const Eigen::Vector3s& screw,\n    bool useRidders = true);\n\nEigen::Vector3s finiteDifferenceRiddersExpMapNestedGradient(\n    const Eigen::Vector3s& original, const Eigen::Vector3s& screw);\n\n/// \\brief Log mapping\n/// \\note When @f$|Log(R)| = @pi@f$, Exp(LogR(R) = Exp(-Log(R)).\n/// The implementation returns only the positive one.\nEigen::Vector3s logMap(const Eigen::Matrix3s& _R);\n\n/// \\brief Log mapping\nEigen::Vector6s logMap(const Eigen::Isometry3s& _T);\n\n/// This takes a screw axis and a point, and gives us the direction that the\n/// point will move if we increase theta by an infinitesimal amount.\nEigen::Vector3s gradientWrtTheta(\n    const Eigen::Vector6s& screwAxis, const Eigen::Vector3s& point, s_t theta);\n\n/// This takes a rotation axis and a point, and gives us the direction that the\n/// point will move if we increase the theta by an infinitesimal amount.\nEigen::Vector3s gradientWrtThetaPureRotation(\n    const Eigen::Vector3s& omega, const Eigen::Vector3s& point, s_t theta);\n\n/// This returns the average of the points on edge A and edge B closest to each\n/// other.\nEigen::Vector3s getContactPoint(\n    const Eigen::Vector3s& edgeAPoint,\n    const Eigen::Vector3s& edgeADir,\n    const Eigen::Vector3s& edgeBPoint,\n    const Eigen::Vector3s& edgeBDir,\n    s_t radiusA = 1.0,\n    s_t radiusB = 1.0);\n\n/// This returns gradient of the average of the points on edge A and edge B\n/// closest to each other, allowing all the inputs to change.\nEigen::Vector3s getContactPointGradient(\n    const Eigen::Vector3s& edgeAPoint,\n    const Eigen::Vector3s& edgeAPointGradient,\n    const Eigen::Vector3s& edgeADir,\n    const Eigen::Vector3s& edgeADirGradient,\n    const Eigen::Vector3s& edgeBPoint,\n    const Eigen::Vector3s& edgeBPointGradient,\n    const Eigen::Vector3s& edgeBDir,\n    const Eigen::Vector3s& edgeBDirGradient,\n    s_t radiusA = 1.0,\n    s_t radiusB = 1.0);\n\nEigen::VectorXs dampedPInv(\n    const Eigen::MatrixXs& J, const Eigen::VectorXs& x, s_t damping = 0.05);\n\nbool hasTinySingularValues(\n    const Eigen::MatrixXs& J, s_t clippingThreshold = 1e-4);\n\nEigen::MatrixXs clippedSingularsPinv(\n    const Eigen::MatrixXs& J, s_t clippingThreshold = 1e-4);\n\n//------------------------------------------------------------------------------\n/// \\brief Rectify the rotation part so as that it satifies the orthogonality\n/// condition.\n///\n/// It is one step of @f$R_{i_1}=1/2(R_i + R_i^{-T})@f$.\n/// Hence by calling this function iterativley, you can make the rotation part\n/// closer to SO(3).\n// SE3 Normalize(const SE3& T);\n\n/// \\brief reparameterize such as ||s'|| < M_PI and Exp(s) == Epx(s')\n// Axis Reparameterize(const Axis& s);\n\n//------------------------------------------------------------------------------\n/// \\brief adjoint mapping\n/// \\note @f$Ad_TV = ( Rw@,, ~p @times Rw + Rv)@f$,\n/// where @f$T=(R,p)@in SE(3), @quad V=(w,v)@in se(3) @f$.\nEigen::Vector6s AdT(const Eigen::Isometry3s& _T, const Eigen::Vector6s& _V);\n\n/// \\brief Get linear transformation matrix of Adjoint mapping\nEigen::Matrix6s getAdTMatrix(const Eigen::Isometry3s& T);\n\n// TODO(JS): Rename and add documentation\nEigen::Matrix6s AdTMatrix(const Eigen::Isometry3s& T);\nEigen::Matrix6s AdInvTMatrix(const Eigen::Isometry3s& T);\n\n// TODO(JS): Rename and add documentation\nEigen::Matrix6s dAdTMatrix(const Eigen::Isometry3s& T);\nEigen::Matrix6s dAdInvTMatrix(const Eigen::Isometry3s& T);\n\n/// Adjoint mapping for dynamic size Jacobian\ntemplate <typename Derived>\ntypename Derived::PlainObject AdTJac(\n    const Eigen::Isometry3s& _T, const Eigen::MatrixBase<Derived>& _J)\n{\n  // Check the number of rows is 6 at compile time\n  EIGEN_STATIC_ASSERT(\n      Derived::RowsAtCompileTime == 6,\n      THIS_METHOD_IS_ONLY_FOR_MATRICES_OF_A_SPECIFIC_SIZE);\n\n  typename Derived::PlainObject ret(_J.rows(), _J.cols());\n\n  // Compute AdT column by column\n  for (int i = 0; i < _J.cols(); ++i)\n    ret.col(i) = AdT(_T, _J.col(i));\n\n  return ret;\n}\n\n/// Adjoint mapping for fixed size Jacobian\ntemplate <typename Derived>\ntypename Derived::PlainObject AdTJacFixed(\n    const Eigen::Isometry3s& _T, const Eigen::MatrixBase<Derived>& _J)\n{\n  // Check if _J is fixed size Jacobian\n  EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived);\n\n  // Check the number of rows is 6 at compile time\n  EIGEN_STATIC_ASSERT(\n      Derived::RowsAtCompileTime == 6,\n      THIS_METHOD_IS_ONLY_FOR_MATRICES_OF_A_SPECIFIC_SIZE);\n\n  typename Derived::PlainObject ret(_J.rows(), _J.cols());\n\n  // Compute AdT\n  ret.template topRows<3>().noalias() = _T.linear() * _J.template topRows<3>();\n  ret.template bottomRows<3>().noalias()\n      = -ret.template topRows<3>().colwise().cross(_T.translation())\n        + _T.linear() * _J.template bottomRows<3>();\n\n  return ret;\n}\n\n/// \\brief Fast version of Ad([R 0; 0 1], V)\nEigen::Vector6s AdR(const Eigen::Isometry3s& _T, const Eigen::Vector6s& _V);\n\n/// \\brief fast version of Ad(T, se3(w, 0))\nEigen::Vector6s AdTAngular(\n    const Eigen::Isometry3s& _T, const Eigen::Vector3s& _w);\n\n/// \\brief fast version of Ad(T, se3(0, v))\nEigen::Vector6s AdTLinear(\n    const Eigen::Isometry3s& _T, const Eigen::Vector3s& _v);\n\n///// \\brief fast version of Ad([I p; 0 1], V)\n// se3 AdP(const Vec3& p, const se3& s);\n\n/// \\brief Change coordinate Frame of a Jacobian\ntemplate <typename Derived>\ntypename Derived::PlainObject AdRJac(\n    const Eigen::Isometry3s& _T, const Eigen::MatrixBase<Derived>& _J)\n{\n  EIGEN_STATIC_ASSERT(\n      Derived::RowsAtCompileTime == 6,\n      THIS_METHOD_IS_ONLY_FOR_MATRICES_OF_A_SPECIFIC_SIZE);\n\n  typename Derived::PlainObject ret(_J.rows(), _J.cols());\n\n  ret.template topRows<3>().noalias() = _T.linear() * _J.template topRows<3>();\n\n  ret.template bottomRows<3>().noalias()\n      = _T.linear() * _J.template bottomRows<3>();\n\n  return ret;\n}\n\ntemplate <typename Derived>\ntypename Derived::PlainObject AdRInvJac(\n    const Eigen::Isometry3s& _T, const Eigen::MatrixBase<Derived>& _J)\n{\n  EIGEN_STATIC_ASSERT(\n      Derived::RowsAtCompileTime == 6,\n      THIS_METHOD_IS_ONLY_FOR_MATRICES_OF_A_SPECIFIC_SIZE);\n\n  typename Derived::PlainObject ret(_J.rows(), _J.cols());\n\n  ret.template topRows<3>().noalias()\n      = _T.linear().transpose() * _J.template topRows<3>();\n\n  ret.template bottomRows<3>().noalias()\n      = _T.linear().transpose() * _J.template bottomRows<3>();\n\n  return ret;\n}\n\ntemplate <typename Derived>\ntypename Derived::PlainObject adJac(\n    const Eigen::Vector6s& _V, const Eigen::MatrixBase<Derived>& _J)\n{\n  EIGEN_STATIC_ASSERT(\n      Derived::RowsAtCompileTime == 6,\n      THIS_METHOD_IS_ONLY_FOR_MATRICES_OF_A_SPECIFIC_SIZE);\n\n  typename Derived::PlainObject ret(_J.rows(), _J.cols());\n\n  ret.template topRows<3>().noalias()\n      = -_J.template topRows<3>().colwise().cross(_V.head<3>());\n\n  ret.template bottomRows<3>().noalias()\n      = -_J.template bottomRows<3>().colwise().cross(_V.head<3>())\n        - _J.template topRows<3>().colwise().cross(_V.tail<3>());\n\n  return ret;\n}\n\n/// \\brief fast version of Ad(Inv(T), V)\nEigen::Vector6s AdInvT(const Eigen::Isometry3s& _T, const Eigen::Vector6s& _V);\n\n/// Adjoint mapping for dynamic size Jacobian\ntemplate <typename Derived>\ntypename Derived::PlainObject AdInvTJac(\n    const Eigen::Isometry3s& _T, const Eigen::MatrixBase<Derived>& _J)\n{\n  // Check the number of rows is 6 at compile time\n  EIGEN_STATIC_ASSERT(\n      Derived::RowsAtCompileTime == 6,\n      THIS_METHOD_IS_ONLY_FOR_MATRICES_OF_A_SPECIFIC_SIZE);\n\n  typename Derived::PlainObject ret(_J.rows(), _J.cols());\n\n  // Compute AdInvT column by column\n  for (int i = 0; i < _J.cols(); ++i)\n    ret.col(i) = AdInvT(_T, _J.col(i));\n\n  return ret;\n}\n\n/// Adjoint mapping for fixed size Jacobian\ntemplate <typename Derived>\ntypename Derived::PlainObject AdInvTJacFixed(\n    const Eigen::Isometry3s& _T, const Eigen::MatrixBase<Derived>& _J)\n{\n  // Check if _J is fixed size Jacobian\n  EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived);\n\n  // Check the number of rows is 6 at compile time\n  EIGEN_STATIC_ASSERT(\n      Derived::RowsAtCompileTime == 6,\n      THIS_METHOD_IS_ONLY_FOR_MATRICES_OF_A_SPECIFIC_SIZE);\n\n  typename Derived::PlainObject ret(_J.rows(), _J.cols());\n\n  // Compute AdInvT\n  ret.template topRows<3>().noalias()\n      = _T.linear().transpose() * _J.template topRows<3>();\n  ret.template bottomRows<3>().noalias()\n      = _T.linear().transpose()\n        * (_J.template bottomRows<3>()\n           + _J.template topRows<3>().colwise().cross(_T.translation()));\n\n  return ret;\n}\n\n///// \\brief fast version of Ad(Inv(T), se3(Eigen_Vec3(0), v))\n// Eigen::Vector3s AdInvTLinear(const Eigen::Isometry3s& T,\n//                             const Eigen::Vector3s& v);\n\n///// \\brief fast version of Ad(Inv(T), se3(w, Eigen_Vec3(0)))\n// Axis AdInvTAngular(const SE3& T, const Axis& w);\n\n///// \\brief Fast version of Ad(Inv([R 0; 0 1]), V)\n// se3 AdInvR(const SE3& T, const se3& V);\n\n/// \\brief Fast version of Ad(Inv([R 0; 0 1]), se3(0, v))\nEigen::Vector6s AdInvRLinear(\n    const Eigen::Isometry3s& _T, const Eigen::Vector3s& _v);\n\n/// \\brief dual adjoint mapping\n/// \\note @f$Ad^{@,*}_TF = ( R^T (m - p@times f)@,,~ R^T f)@f$,\n/// where @f$T=(R,p)@in SE(3), F=(m,f)@in se(3)^*@f$.\nEigen::Vector6s dAdT(const Eigen::Isometry3s& _T, const Eigen::Vector6s& _F);\n\n///// \\brief fast version of Ad(Inv(T), dse3(Eigen_Vec3(0), F))\n// dse3 dAdTLinear(const SE3& T, const Vec3& F);\n\n/// \\brief fast version of dAd(Inv(T), F)\nEigen::Vector6s dAdInvT(const Eigen::Isometry3s& _T, const Eigen::Vector6s& _F);\n\n/// \\brief fast version of dAd(Inv([R 0; 0 1]), F)\nEigen::Vector6s dAdInvR(const Eigen::Isometry3s& _T, const Eigen::Vector6s& _F);\n\n///// \\brief fast version of dAd(Inv(SE3(p)), dse3(Eigen_Vec3(0), F))\n// dse3 dAdInvPLinear(const Vec3& p, const Vec3& F);\n\n/// \\brief adjoint mapping\n/// \\note @f$ad_X Y = ( w_X @times w_Y@,,~w_X @times v_Y - w_Y @times v_X),@f$,\n/// where @f$X=(w_X,v_X)@in se(3), @quad Y=(w_Y,v_Y)@in se(3) @f$.\nEigen::Vector6s ad(const Eigen::Vector6s& _X, const Eigen::Vector6s& _Y);\n\n// TODO(JS): Rename and add documentation\nEigen::Matrix6s adMatrix(const Eigen::Vector6s& X);\n\n/// \\brief fast version of ad(se3(Eigen_Vec3(0), v), S)\n// Vec3 ad_Vec3_se3(const Vec3& v, const se3& S);\n\n/// \\brief fast version of ad(se3(w, 0), se3(v, 0)) -> check\n// Axis ad_Axis_Axis(const Axis& w, const Axis& v);\n\n/// \\brief dual adjoint mapping\n/// \\note @f$ad^{@,*}_V F = (m @times w + f @times v@,,~ f @times w),@f$\n/// , where @f$F=(m,f)@in se^{@,*}(3), @quad V=(w,v)@in se(3) @f$.\nEigen::Vector6s dad(const Eigen::Vector6s& _s, const Eigen::Vector6s& _t);\n\n/// \\brief\nInertia transformInertia(const Eigen::Isometry3s& _T, const Inertia& _AI);\n\n/// Use the Parallel Axis Theorem to compute the moment of inertia of a body\n/// whose center of mass has been shifted from the origin\nEigen::Matrix3s parallelAxisTheorem(\n    const Eigen::Matrix3s& _original,\n    const Eigen::Vector3s& _comShift,\n    s_t _mass);\n\nenum AxisType\n{\n  AXIS_X = 0,\n  AXIS_Y = 1,\n  AXIS_Z = 2\n};\n\n/// Compute a rotation matrix from a vector. One axis of the rotated coordinates\n/// by the rotation matrix matches the input axis where the axis is specified\n/// by axisType.\nEigen::Matrix3s computeRotation(\n    const Eigen::Vector3s& axis, AxisType axisType = AxisType::AXIS_X);\n\n/// Compute a transform from a vector and a position. The rotation of the result\n/// transform is computed by computeRotationMatrix(), and the translation is\n/// just the input translation.\nEigen::Isometry3s computeTransform(\n    const Eigen::Vector3s& axis,\n    const Eigen::Vector3s& translation,\n    AxisType axisType = AxisType::AXIS_X);\n\n/// Generate frame given origin and z-axis\nDART_DEPRECATED(6.0)\nEigen::Isometry3s getFrameOriginAxisZ(\n    const Eigen::Vector3s& _origin, const Eigen::Vector3s& _axisZ);\n\n/// \\brief Check if determinant of _R is equat to 1 and all the elements are not\n/// NaN values.\nbool verifyRotation(const Eigen::Matrix3s& _R);\n\n/// \\brief Check if determinant of the rotational part of _T is equat to 1 and\n/// all the elements are not NaN values.\nbool verifyTransform(const Eigen::Isometry3s& _T);\n\n/// Compute the angle (in the range of -pi to +pi) which ignores any full\n/// rotations\n#ifdef DART_USE_ARBITRARY_PRECISION\ninline s_t wrapToPi(s_t angle)\n{\n  s_t pi = constantsd::pi();\n  return fmod(angle + pi, 2 * pi) - pi;\n}\n#else\ninline s_t wrapToPi(s_t angle)\n{\n  constexpr auto pi = constantsd::pi();\n\n  return std::fmod(angle + pi, 2 * pi) - pi;\n}\n#endif\n\ntemplate <typename MatrixType, typename ReturnType>\nvoid extractNullSpace(const Eigen::JacobiSVD<MatrixType>& _SVD, ReturnType& _NS)\n{\n  int rank = 0;\n  // TODO(MXG): Replace this with _SVD.rank() once the latest Eigen is released\n  if (_SVD.nonzeroSingularValues() > 0)\n  {\n    s_t thresh = max(\n        _SVD.singularValues().coeff(0) * 1e-10,\n        std::numeric_limits<s_t>::min());\n    int i = _SVD.nonzeroSingularValues() - 1;\n    while (i >= 0 && _SVD.singularValues().coeff(i) < thresh)\n      --i;\n    rank = i + 1;\n  }\n\n  int cols = _SVD.matrixV().cols(), rows = _SVD.matrixV().rows();\n  _NS = _SVD.matrixV().block(0, rank, rows, cols - rank);\n}\n\ntemplate <typename MatrixType, typename ReturnType>\nvoid computeNullSpace(const MatrixType& _M, ReturnType& _NS)\n{\n  Eigen::JacobiSVD<MatrixType> svd(_M, Eigen::ComputeFullV);\n  extractNullSpace(svd, _NS);\n}\n\ntypedef std::vector<Eigen::Vector3s> SupportGeometry;\n\ntypedef common::aligned_vector<Eigen::Vector2s> SupportPolygon;\n\n/// Project the support geometry points onto a plane with the given axes\n/// and then compute their convex hull, which will take the form of a polgyon.\n/// _axis1 and _axis2 must both have unit length for this function to work\n/// correctly.\nSupportPolygon computeSupportPolgyon(\n    const SupportGeometry& _geometry,\n    const Eigen::Vector3s& _axis1 = Eigen::Vector3s::UnitX(),\n    const Eigen::Vector3s& _axis2 = Eigen::Vector3s::UnitY());\n\n/// Same as computeSupportPolgyon, except you can pass in a\n/// std::vector<std::size_t> which will have the same size as the returned\n/// SupportPolygon, and each entry will contain the original index of each point\n/// in the SupportPolygon\nSupportPolygon computeSupportPolgyon(\n    std::vector<std::size_t>& _originalIndices,\n    const SupportGeometry& _geometry,\n    const Eigen::Vector3s& _axis1 = Eigen::Vector3s::UnitX(),\n    const Eigen::Vector3s& _axis2 = Eigen::Vector3s::UnitY());\n\n/// Computes the convex hull of a set of 2D points\nSupportPolygon computeConvexHull(const SupportPolygon& _points);\n\n/// Computes the convex hull of a set of 2D points and fills in _originalIndices\n/// with the original index of each entry in the returned SupportPolygon\nSupportPolygon computeConvexHull(\n    std::vector<std::size_t>& _originalIndices, const SupportPolygon& _points);\n\n/// Compute the centroid of a polygon, assuming the polygon is a convex hull\nEigen::Vector2s computeCentroidOfHull(const SupportPolygon& _convexHull);\n\n/// Intersection_t is returned by the computeIntersection() function to indicate\n/// whether there was a valid intersection between the two line segments\nenum IntersectionResult\n{\n\n  INTERSECTING = 0, ///< An intersection was found\n  PARALLEL,         ///< The line segments are parallel\n  BEYOND_ENDPOINTS  ///< There is no intersection because the end points do not\n                    ///< expand far enough\n\n};\n\n/// Compute the intersection between a line segment that goes from a1 -> a2 and\n/// a line segment that goes from b1 -> b2.\nIntersectionResult computeIntersection(\n    Eigen::Vector2s& _intersectionPoint,\n    const Eigen::Vector2s& a1,\n    const Eigen::Vector2s& a2,\n    const Eigen::Vector2s& b1,\n    const Eigen::Vector2s& b2);\n\n/// Compute a 2D cross product\ns_t cross(const Eigen::Vector2s& _v1, const Eigen::Vector2s& _v2);\n\n/// Returns true if the point _p is inside the support polygon\nbool isInsideSupportPolygon(\n    const Eigen::Vector2s& _p,\n    const SupportPolygon& _support,\n    bool _includeEdge = true);\n\n/// Returns the point which is closest to _p that also lays on the line segment\n/// that goes from _s1 -> _s2\nEigen::Vector2s computeClosestPointOnLineSegment(\n    const Eigen::Vector2s& _p,\n    const Eigen::Vector2s& _s1,\n    const Eigen::Vector2s& _s2);\n\n/// Returns the point which is closest to _p that also lays on the edge of the\n/// support polygon\nEigen::Vector2s computeClosestPointOnSupportPolygon(\n    const Eigen::Vector2s& _p, const SupportPolygon& _support);\n\n/// Same as closestPointOnSupportPolygon, but also fills in _index1 and _index2\n/// with the indices of the line segment\nEigen::Vector2s computeClosestPointOnSupportPolygon(\n    std::size_t& _index1,\n    std::size_t& _index2,\n    const Eigen::Vector2s& _p,\n    const SupportPolygon& _support);\n\n/// This computes and returns the closest point on a line, given by a point and\n/// a direction, to a goal point\nEigen::Vector3s closestPointOnLine(\n    const Eigen::Vector3s& pointOnLine,\n    const Eigen::Vector3s& lineDirection,\n    const Eigen::Vector3s& goalPoint);\n\n/// This computes and returns the gradient of closestPointOnLine(), given the\n/// gradients of its inputs\nEigen::Vector3s closestPointOnLineGradient(\n    const Eigen::Vector3s& pointOnLine,\n    const Eigen::Vector3s& pointOnLineGradient,\n    const Eigen::Vector3s& lineDirection,\n    const Eigen::Vector3s& lineDirectionGradient,\n    const Eigen::Vector3s& goalPoint,\n    const Eigen::Vector3s& goalPointGradient);\n\n// Represents a bounding box with minimum and maximum coordinates.\nclass BoundingBox\n{\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  BoundingBox();\n  BoundingBox(const Eigen::Vector3s& min, const Eigen::Vector3s& max);\n\n  inline const Eigen::Vector3s& getMin() const\n  {\n    return mMin;\n  }\n  inline const Eigen::Vector3s& getMax() const\n  {\n    return mMax;\n  }\n\n  inline void setMin(const Eigen::Vector3s& min)\n  {\n    mMin = min;\n  }\n  inline void setMax(const Eigen::Vector3s& max)\n  {\n    mMax = max;\n  }\n\n  // \\brief Centroid of the bounding box (i.e average of min and max)\n  inline Eigen::Vector3s computeCenter() const\n  {\n    return (mMax + mMin) * 0.5;\n  }\n  // \\brief Coordinates of the maximum corner with respect to the centroid.\n  inline Eigen::Vector3s computeHalfExtents() const\n  {\n    return (mMax - mMin) * 0.5;\n  }\n  // \\brief Length of each of the sides of the bounding box.\n  inline Eigen::Vector3s computeFullExtents() const\n  {\n    return (mMax - mMin);\n  }\n\nprotected:\n  // \\brief minimum coordinates of the bounding box\n  Eigen::Vector3s mMin;\n  // \\brief maximum coordinates of the bounding box\n  Eigen::Vector3s mMax;\n};\n\n} // namespace math\n} // namespace dart\n\n#endif // DART_MATH_GEOMETRY_HPP_\n", "meta": {"hexsha": "547dcd73b25231ba262534a1ce6556425c4ca3c9", "size": 28931, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/math/Geometry.hpp", "max_stars_repo_name": "jyf588/nimblephysics", "max_stars_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T06:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T09:59:09.000Z", "max_issues_repo_path": "dart/math/Geometry.hpp", "max_issues_repo_name": "jyf588/nimblephysics", "max_issues_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dart/math/Geometry.hpp", "max_forks_repo_name": "jyf588/nimblephysics", "max_forks_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T13:56:14.000Z", "avg_line_length": 36.7144670051, "max_line_length": 80, "alphanum_fraction": 0.7041927344, "num_tokens": 8243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.42142902819302785}}
{"text": "#ifndef LBP_XCSLBP_HPP\n#define LBP_XCSLBP_HPP\n\n#include <lbp/defs.hpp>\n#include <lbp/utils.hpp>\n#include <lbp/detail/neighborhoods.hpp>\n#include <lbp/detail/sampling.hpp>\n\n#include <opencv2/core.hpp>\n\n#include <boost/hana/fold.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <boost/integer.hpp>\n\n//\n// @inproceedings{silva2015extended,\n//   title={An eXtended center-symmetric local binary pattern for background modeling and subtraction in videos},\n//   author={Silva, Caroline and Bouwmans, Thierry and Fr{\\'e}licot, Carl},\n//   booktitle={International Joint Conference on Computer Vision, Imaging and Computer Graphics Theory and Applications, VISAPP 2015},\n//   year={2015}\n// }\n//\n\nnamespace lbp {\nnamespace xcslbp_detail {\n\ntemplate< typename T >\nauto xcslbp = [](auto N, auto S) {\n    return [=](const cv::Mat& src, size_t i, size_t j, const T& epsilon) {\n        using namespace cv;\n        using namespace hana::literals;\n\n        const auto c = S (src, i, j);\n\n        return boost::hana::fold (\n            N, 0, [&, shift = 0](auto accum, auto x) mutable {\n                const auto a = S (src, i + x [0_c], j + x [1_c]);\n                const auto b = S (src, i - x [0_c], j - x [1_c]);\n\n                const auto g1 = a - b + c;\n                const auto g2 = (a - c) * (b - c);\n\n                return accum | (((g1 + g2) >= epsilon) << shift++);\n            });\n    };\n};\n\n} // namespace xcslbp_detail\n\ntemplate< typename T, size_t R, size_t P >\nauto xcslbp = [](const cv::Mat& src, const T& epsilon = T { }) {\n    using value_type = typename boost::uint_t< P/2 >::least;\n        \n    cv::Mat dst (src.size (), opencv_type< value_type >, cv::Scalar (0));\n\n    auto op = xcslbp_detail::xcslbp< T > (\n        detail::semicircular_neighborhood< R, P >,\n        detail::nearest_sampler< T >);\n\n#pragma omp parallel for\n    for (size_t i = R; i < src.rows - R; ++i) {\n        for (size_t j = R; j < src.cols - R; ++j) {\n            dst.at< value_type > (i, j) = op (src, i, j, epsilon);\n        }\n    }\n\n    return dst;\n};\n\n} // namespace lbp\n\n#endif // LBP_XCSLBP_HPP\n", "meta": {"hexsha": "5d1f6e0db2cb52c8752301758542883d28f2bb05", "size": 2083, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lbp/xcslbp.hpp", "max_stars_repo_name": "thinkoid/lbp", "max_stars_repo_head_hexsha": "9ce3bc41a8961cf0304c5d271cd882b4cae78cb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-11-02T12:45:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-25T03:51:09.000Z", "max_issues_repo_path": "include/lbp/xcslbp.hpp", "max_issues_repo_name": "thinkoid/lbp", "max_issues_repo_head_hexsha": "9ce3bc41a8961cf0304c5d271cd882b4cae78cb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/lbp/xcslbp.hpp", "max_forks_repo_name": "thinkoid/lbp", "max_forks_repo_head_hexsha": "9ce3bc41a8961cf0304c5d271cd882b4cae78cb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T09:10:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-02T09:19:34.000Z", "avg_line_length": 28.1486486486, "max_line_length": 135, "alphanum_fraction": 0.5914546327, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.42136933876782484}}
{"text": "//  Copyright John Maddock 2007.\r\n//  Copyright Paul A. Bristow 2010\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Note that this file contains quickbook mark-up as well as code\r\n// and comments, don't change any of the special comment mark-ups!\r\n\r\n#include <iostream>\r\nusing std::cout;  using std::endl;\r\n#include <cerrno> // for ::errno\r\n\r\n//[policy_eg_6\r\n\r\n/*`\r\nSuppose we want a set of distributions to behave as follows:\r\n\r\n* Return infinity on overflow, rather than throwing an exception.\r\n* Don't perform any promotion from double to long double internally.\r\n* Return the closest integer result from the quantiles of discrete\r\ndistributions.\r\n\r\nWe'll begin by including the needed header for all the distributions:\r\n*/\r\n\r\n#include <boost/math/distributions.hpp>\r\n\r\n/*`\r\n\r\nOpen up an appropriate namespace, calling it `my_distributions`,\r\nfor our distributions, and define the policy type we want.\r\nAny policies we don't specify here will inherit the defaults:\r\n\r\n*/\r\n\r\nnamespace my_distributions\r\n{\r\n  using namespace boost::math::policies;\r\n  // using boost::math::policies::errno_on_error; // etc.\r\n\r\n  typedef policy<\r\n     // return infinity and set errno rather than throw:\r\n     overflow_error<errno_on_error>,\r\n     // Don't promote double -> long double internally:\r\n     promote_double<false>,\r\n     // Return the closest integer result for discrete quantiles:\r\n     discrete_quantile<integer_round_nearest>\r\n  > my_policy;\r\n\r\n/*`\r\n\r\nAll we need do now is invoke the BOOST_MATH_DECLARE_DISTRIBUTIONS\r\nmacro passing the floating point type `double` and policy types `my_policy` as arguments:\r\n\r\n*/\r\n\r\nBOOST_MATH_DECLARE_DISTRIBUTIONS(double, my_policy)\r\n\r\n} // close namespace my_namespace\r\n\r\n/*`\r\n\r\nWe now have a set of typedefs defined in namespace my_distributions\r\nthat all look something like this:\r\n\r\n``\r\ntypedef boost::math::normal_distribution<double, my_policy> normal;\r\ntypedef boost::math::cauchy_distribution<double, my_policy> cauchy;\r\ntypedef boost::math::gamma_distribution<double, my_policy> gamma;\r\n// etc\r\n``\r\n\r\nSo that when we use my_distributions::normal we really end up using\r\n`boost::math::normal_distribution<double, my_policy>`:\r\n\r\n*/\r\n\r\nint main()\r\n{\r\n   // Construct distribution with something we know will overflow\r\n  // (using double rather than if promoted to long double):\r\n   my_distributions::normal norm(10, 2);\r\n\r\n   errno = 0;\r\n   cout << \"Result of quantile(norm, 0) is: \"\r\n      << quantile(norm, 0) << endl; // -infinity.\r\n   cout << \"errno = \" << errno << endl;\r\n   errno = 0;\r\n   cout << \"Result of quantile(norm, 1) is: \"\r\n      << quantile(norm, 1) << endl; // +infinity.\r\n   cout << \"errno = \" << errno << endl;\r\n\r\n   // Now try a discrete distribution.\r\n   my_distributions::binomial binom(20, 0.25);\r\n   cout << \"Result of quantile(binom, 0.05) is: \"\r\n      << quantile(binom, 0.05) << endl; // To check we get integer results.\r\n   cout << \"Result of quantile(complement(binom, 0.05)) is: \"\r\n      << quantile(complement(binom, 0.05)) << endl;\r\n}\r\n\r\n/*`\r\n\r\nWhich outputs:\r\n\r\n[pre\r\nResult of quantile(norm, 0) is: -1.#INF\r\nerrno = 34\r\nResult of quantile(norm, 1) is: 1.#INF\r\nerrno = 34\r\nResult of quantile(binom, 0.05) is: 1\r\nResult of quantile(complement(binom, 0.05)) is: 8\r\n]\r\n\r\nThis mechanism is particularly useful when we want to define a\r\nproject-wide policy, and don't want to modify the Boost source\r\nor set  project wide build macros (possibly fragile and easy to forget).\r\n\r\n*/\r\n//] //[/policy_eg_6]\r\n\r\n", "meta": {"hexsha": "08972fd09fbde940a5ff46daba19c6912e81a8d4", "size": 3629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/policy_eg_6.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/math/example/policy_eg_6.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/math/example/policy_eg_6.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 29.7459016393, "max_line_length": 90, "alphanum_fraction": 0.6938550565, "num_tokens": 911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.4213693318577852}}
{"text": "// Copyright Stephan T. Lavavej, http://nuwen.net .\n// Distributed under the Boost Software License, Version 1.0.\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://boost.org/LICENSE_1_0.txt .\n\n#ifndef PHAM_ARITH_HH\n#define PHAM_ARITH_HH\n\n#include \"compiler.hh\"\n\n#ifdef NUWEN_PLATFORM_MSVC\n    #pragma once\n#endif\n\n// Based on the ANSI C Arithmetic Coding Library by Fred Wheeler,\n// which was adapted from the program in \"Arithmetic Coding For Data\n// Compression\", by Ian H. Witten, Radford M. Neal, and John G. Cleary,\n// Communications Of The ACM, June 1987, Vol. 30, No. 6.\n\n#include \"typedef.hh\"\n#include \"vector.hh\"\n\n#include \"external_begin.hh\"\n    #include <boost/utility.hpp>\n#include \"external_end.hh\"\n\nnamespace nuwen {\n    inline vuc_t   arith(const vuc_t& v);\n    inline vuc_t unarith(const vuc_t& v);\n}\n\nnamespace pham {\n    namespace arith {\n\n// The triple of (CODE_VALUE_BITS, MAX_FREQUENCY, INCREMENT_VALUE) is deeply magic.\n// It controls how much compression is achieved by BWT/MTF-2/ZLE/Arith.\n// The CACM paper explains that when frequency counts are represented in F bits,\n// code values are represented in C bits, and arithmetic is performed with\n// P bits of precision, the following must hold: F <= C - 2 and F + C <= P.\n// For sl_t arithmetic, P = 31, so F = 14 and C = 16 are possible.\n// For ul_t arithmetic, P = 32, so F = 15 and C = 17 are possible.\n// CODE_VALUE_BITS is C, while MAX_FREQUENCY may be as large as 2^F - 1.\n// As MAX_FREQUENCY becomes larger, the arithmetic coder gains a more precise\n// memory (its model of the frequencies becomes closer to the true, unscaled\n// frequencies), but the arithmetic coder also becomes less adaptive, as\n// rescalings are forced less frequently. Adaptiveness is good for compressing\n// BWT/MTF-2/ZLE data, which consists of lengthy stretches of \"boring\" low bytes,\n// interspersed with bursts of \"exciting\" high bytes. When the arithmetic coder\n// adapts quickly, better compression is achieved. A generalization of the\n// CACM model can achieve the best of both worlds: use the largest possible\n// MAX_FREQUENCY to give the coder a good memory, but increment the frequency counts\n// by more than 1. This forces more frequent rescaling.\n// (16, 16383, 1): Used by the CACM code (as well as Fred Wheeler's). As they used\n// sl_t arithmetic, this was \"maximally\" precise but not very adaptive.\n// (16, 8192, 16): Suggested by Fenwick, this forces rescaling 32x more often,\n// at the cost of precision.\n// (16, 16383, 32): Used by the first libnuwen implementation, 1.0.22.0. Combines\n// Fenwick's rescaling with CACM's precision.\n// (17, 32767, 1): Used by libnuwen 1.0.23.0 through 1.0.28.0. I reread the CACM\n// paper and realized that ul_t arithmetic allowed higher precision.\n// (17, 32767, 64): Used by libnuwen 2.0.0.0 and beyond. Combines maximum precision\n// with Fenwick's frequent rescaling.\n\n// Here is how BWT/MTF-2/ZLE/Arith behaves on suall10.txt (9873495 bytes)\n// with the various triples:\n//     CACM (16, 16383,  1): 2073812 bytes, 1.680 bits/byte: The untuned baseline.\n//  Fenwick (16,  8192, 16): 2050015 bytes, 1.661 bits/byte: A clear improvement.\n// 1.0.22.0 (16, 16383, 32): 2033592 bytes, 1.648 bits/byte: Even better.\n// 1.0.23.0 (17, 32767,  1): 2078591 bytes, 1.684 bits/byte: Crippling regression.\n//  2.0.0.0 (17, 32767, 64): 2026462 bytes, 1.642 bits/byte: Best of all worlds.\n\n        const nuwen::ul_t CODE_VALUE_BITS = 17;\n        const nuwen::ul_t MAX_FREQUENCY   = 32767;\n        const nuwen::ul_t INCREMENT_VALUE = 64;\n\n        const nuwen::ul_t TOP_VALUE       = (1 << CODE_VALUE_BITS) - 1;\n        const nuwen::ul_t FIRST_QTR       = TOP_VALUE / 4 + 1;\n        const nuwen::ul_t HALF            = 2 * FIRST_QTR;\n        const nuwen::ul_t THIRD_QTR       = 3 * FIRST_QTR;\n\n        typedef nuwen::us_t symbol_t;\n\n        const symbol_t    SENTINEL        = 256;\n        const symbol_t    NUM_SYMBOLS     = 257;\n\n        class model : public boost::noncopyable {\n        public:\n            model() {\n                for (nuwen::ul_t i = 0; i < NUM_SYMBOLS; ++i) {\n                    m_freq[i] = 1;\n                }\n\n                for (nuwen::ul_t i = 0; i < NUM_SYMBOLS + 1; ++i) {\n                    m_cfreq[i] = NUM_SYMBOLS - i;\n                }\n            }\n\n            nuwen::ul_t operator[](const symbol_t i) const {\n                return m_cfreq[i];\n            }\n\n            void update(const symbol_t sym) {\n                // The CACM code used a hardcoded increment value of 1 and wrote this test\n                // (using current terminology) as m_cfreq[0] == MAX_FREQUENCY, which was correct.\n                // libnuwen 1.0.28.0 and earlier used a generalized INCREMENT_VALUE and wrote this test\n                // (using current terminology) as m_cfreq[0] >= MAX_FREQUENCY, which was WRONG.\n                // The correct generalization is below; an invariant of the model is that\n                // m_cfreq[0] is ALWAYS <= MAX_FREQUENCY. If we detect that adding INCREMENT_VALUE\n                // will destroy this invariant, we must rescale so that the invariant will be\n                // maintained.\n\n                if (m_cfreq[0] + INCREMENT_VALUE > MAX_FREQUENCY) {\n                    nuwen::ul_t cum = 0;\n                    m_cfreq[NUM_SYMBOLS] = 0;\n\n                    for (int i = NUM_SYMBOLS - 1; i >= 0; --i) {\n                        m_freq[i] = (m_freq[i] + 1) / 2;\n                        cum += m_freq[i];\n                        m_cfreq[i] = cum;\n                    }\n                }\n\n                m_freq[sym] += INCREMENT_VALUE;\n\n                for (int i = 0; i < sym + 1; ++i) {\n                    m_cfreq[i] += INCREMENT_VALUE;\n                }\n            }\n\n        private:\n            nuwen::ul_t m_freq[NUM_SYMBOLS];\n            nuwen::ul_t m_cfreq[NUM_SYMBOLS + 1];\n        };\n\n        class encoder : public boost::noncopyable {\n        public:\n            encoder() : m_low(0), m_high(TOP_VALUE), m_fbits(0), m_out(), m_acm() { }\n\n            void encode(const symbol_t sym) {\n                const nuwen::ul_t range = m_high - m_low + 1;\n                m_high = m_low + range * m_acm[sym] / m_acm[0] - 1;\n                m_low  = m_low + range * m_acm[static_cast<symbol_t>(sym + 1)] / m_acm[0];\n\n                while (true) {\n                    if (m_high < HALF) {\n                        bit_plus_follow(0);\n                    } else if (m_low >= HALF) {\n                        bit_plus_follow(1);\n                        m_low  -= HALF;\n                        m_high -= HALF;\n                    } else if (m_low >= FIRST_QTR && m_high < THIRD_QTR) {\n                        ++m_fbits;\n                        m_low  -= FIRST_QTR;\n                        m_high -= FIRST_QTR;\n                    } else {\n                        break;\n                    }\n\n                    m_low  = 2 * m_low;\n                    m_high = 2 * m_high + 1;\n                }\n\n                m_acm.update(sym);\n            }\n\n            nuwen::vuc_t finalize() {\n                ++m_fbits;\n\n                bit_plus_follow(m_low >= FIRST_QTR);\n\n                return m_out.vuc();\n            }\n\n        private:\n            void bit_plus_follow(const bool bit) {\n                m_out.push_back(bit);\n\n                while (m_fbits > 0) {\n                    m_out.push_back(!bit);\n                    --m_fbits;\n                }\n            }\n\n            nuwen::ul_t              m_low;\n            nuwen::ul_t              m_high;\n            nuwen::ul_t              m_fbits;\n            nuwen::pack::packed_bits m_out;\n            model                    m_acm;\n        };\n\n        class decoder : public boost::noncopyable {\n        public:\n            decoder(const nuwen::vuc_ci_t start, const nuwen::vuc_ci_t finish)\n                : m_curr(start), m_shift(7), m_end(finish), m_value(0), m_low(0), m_high(TOP_VALUE), m_acm() {\n\n                for (nuwen::ul_t i = 0; i < CODE_VALUE_BITS; ++i) {\n                    m_value <<= 1;\n                    m_value += input_bit();\n                }\n            }\n\n            symbol_t decode() {\n                const nuwen::ul_t range = m_high - m_low + 1;\n                const nuwen::ul_t cum = ((m_value - m_low + 1) * m_acm[0] - 1) / range;\n\n                symbol_t sym;\n\n                for (sym = 0; m_acm[static_cast<symbol_t>(sym + 1)] > cum; ++sym) { }\n\n                m_high = m_low + range * m_acm[sym] / m_acm[0] - 1;\n                m_low  = m_low + range * m_acm[static_cast<symbol_t>(sym + 1)] / m_acm[0];\n\n                while (true) {\n                    if (m_high < HALF) {\n                    } else if (m_low >= HALF) {\n                        m_value -= HALF;\n                        m_low   -= HALF;\n                        m_high  -= HALF;\n                    } else if (m_low >= FIRST_QTR && m_high < THIRD_QTR) {\n                        m_value -= FIRST_QTR;\n                        m_low   -= FIRST_QTR;\n                        m_high  -= FIRST_QTR;\n                    } else {\n                        break;\n                    }\n\n                    m_low   = 2 * m_low;\n                    m_high  = 2 * m_high + 1;\n                    m_value = 2 * m_value + input_bit();\n                }\n\n                m_acm.update(sym);\n\n                return sym;\n            }\n\n        private:\n            bool input_bit() {\n                if (m_curr != m_end) {\n                    const bool ret = *m_curr >> m_shift & 1;\n\n                    if (m_shift == 0) {\n                        m_shift = 7;\n                        ++m_curr;\n                    } else {\n                        --m_shift;\n                    }\n\n                    return ret;\n                } else {\n                    return 0;\n                }\n            }\n\n            nuwen::vuc_ci_t m_curr;\n            nuwen::uc_t     m_shift;\n            nuwen::vuc_ci_t m_end;\n            nuwen::ul_t     m_value;\n            nuwen::ul_t     m_low;\n            nuwen::ul_t     m_high;\n            model           m_acm;\n        };\n    }\n}\n\ninline nuwen::vuc_t nuwen::arith(const vuc_t& v) {\n    pham::arith::encoder ae;\n\n    for (vuc_ci_t i = v.begin(); i != v.end(); ++i) {\n        ae.encode(*i);\n    }\n\n    ae.encode(pham::arith::SENTINEL);\n\n    return ae.finalize();\n}\n\ninline nuwen::vuc_t nuwen::unarith(const vuc_t& v) {\n    pham::arith::decoder ad(v.begin(), v.end());\n\n    vuc_t ret;\n\n    while (true) {\n        const pham::arith::symbol_t decoded = ad.decode();\n\n        if (decoded != pham::arith::SENTINEL) {\n            ret.push_back(static_cast<uc_t>(decoded));\n        } else {\n            return ret;\n        }\n    }\n}\n\n#endif // Idempotency\n", "meta": {"hexsha": "1db57bb9c506d6ff4b0727b3c408df8ebb218c3c", "size": 10708, "ext": "hh", "lang": "C++", "max_stars_repo_path": "arith.hh", "max_stars_repo_name": "nurettin/libnuwen", "max_stars_repo_head_hexsha": "5b3012d9e75552c372a4d09b218b7af04a928e68", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-09-17T10:33:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T10:03:42.000Z", "max_issues_repo_path": "arith.hh", "max_issues_repo_name": "nurettin/libnuwen", "max_issues_repo_head_hexsha": "5b3012d9e75552c372a4d09b218b7af04a928e68", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arith.hh", "max_forks_repo_name": "nurettin/libnuwen", "max_forks_repo_head_hexsha": "5b3012d9e75552c372a4d09b218b7af04a928e68", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-05T04:31:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-05T04:31:22.000Z", "avg_line_length": 36.2983050847, "max_line_length": 110, "alphanum_fraction": 0.5195181173, "num_tokens": 2799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.42130541500737867}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_TANH_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_TANH_HPP_INCLUDED\n\n#include <boost/simd/detail/overload.hpp>\n#include <boost/simd/arch/common/detail/generic/tanh_kernel.hpp>\n#include <boost/simd/meta/as_logical.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/simd/constant/mtwo.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/bitwise_xor.hpp>\n#include <boost/simd/function/exp.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/nbtrue.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/plus.hpp>\n#include <boost/simd/function/rec.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/tanh.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF( tanh_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::floating_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        //////////////////////////////////////////////////////////////////////////////\n        // if x = abs(a0) is less than 5/8 tanh is computed using a polynomial(float)\n        // (respectively rational(double)) approx from cephes.\n        // else\n        // tanh(a0) is  sign(a0)*(1 - 2/(exp(2*x)+1))\n        //////////////////////////////////////////////////////////////////////////////\n        A0 x = bs::abs(a0);\n        auto test0= is_less(x, Ratio<A0, 5, 8>());\n        A0 bts = bitofsign(a0);\n        std::size_t nb = nbtrue(test0);\n        A0 z = One<A0>();\n        if(nb > 0)\n        {\n          A0 x2 = sqr(x);\n          z = detail::tanh_kernel<A0>::tanh(x, x2);\n          if(nb >= A0::static_size) return  bitwise_xor(z, bts);\n        }\n        A0 r = fma(Mtwo<A0>(), rec(inc(exp(x+x))), One<A0>());\n        return bitwise_xor(if_else(test0, z, r), bts);\n      }\n   };\n\n} } }\n\n#endif\n", "meta": {"hexsha": "2f4aef1c7aded8b09de451b9b5d4632300d962b4", "size": 2693, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/tanh.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/simd/function/tanh.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/simd/function/tanh.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 37.4027777778, "max_line_length": 100, "alphanum_fraction": 0.5451169699, "num_tokens": 633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4213053153475091}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n  @copyright 2015 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_FUNCTION_GENERIC_REM_2PI_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_FUNCTION_GENERIC_REM_2PI_HPP_INCLUDED\n\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/inv2pi.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/pio_2.hpp>\n#include <boost/simd/constant/pix2_1.hpp>\n#include <boost/simd/constant/pix2_2.hpp>\n#include <boost/simd/constant/pix2_3.hpp>\n#include <boost/simd/constant/threeeps.hpp>\n#include <boost/simd/constant/twopi.hpp>\n#include <boost/simd/constant/zero.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_greater.hpp>\n#include <boost/simd/function/is_less.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/plus.hpp>\n#include <boost/simd/function/rem_pio2.hpp>\n#include <boost/simd/function/rem_pio2_medium.hpp>\n#include <boost/simd/function/round2even.hpp>\n#include <boost/simd/function/tofloat.hpp>\n#include <boost/simd/arch/common/detail/tags.hpp>\n#include <boost/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD (rem_2pi_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::generic_ < bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      using i_t = bd::as_integer_t<A0>;\n      A0 xr;\n      i_t n = rem_pio2(a0, xr);\n      xr = xr+tofloat(n)*Pio_2<A0>();\n      return if_else((xr > Pi<A0>()), xr-Twopi<A0>(), xr);\n    }\n\n  };\n\n  BOOST_DISPATCH_OVERLOAD (rem_2pi_\n                          , (typename A0, typename A1)\n                          , bd::cpu_\n                          , bd::generic_ <bd::floating_<A0> >\n                          , bd::target_ <bd::unspecified_<A1> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0, A1 const&) const BOOST_NOEXCEPT\n    {\n      typedef typename A1::type selector;\n      return rem2pi<selector, void>::rem(a0);\n    }\n\n    template < class T, class dummy = void> struct rem2pi\n    {\n      static BOOST_FORCEINLINE A0 rem( A0 const&, A0 &, A0&) BOOST_NOEXCEPT\n      {\n        BOOST_ASSERT_MSG(false, \"wrong target for rem_2pi\");\n      }\n    };\n    template < class dummy> struct rem2pi < tag::big_tag, dummy>\n    {\n      static BOOST_FORCEINLINE A0 rem( A0 const& x) BOOST_NOEXCEPT\n      {\n        return rem_2pi(x);\n      }\n    };\n    template < class dummy> struct rem2pi < tag::very_small_tag, dummy > // |a0| <2*pi\n    {\n      static BOOST_FORCEINLINE A0 rem( A0 const& x) BOOST_NOEXCEPT\n      {\n        return if_else(gt(x, Pi<A0>()), x-Twopi<A0>(),\n                       if_else(lt(x, -Pi<A0>()), x+Twopi<A0>(), x));\n      }\n    };\n    template < class dummy> struct rem2pi < tag::small_tag, dummy >// |a0| <= 20*pi\n    {\n      static BOOST_FORCEINLINE A0 rem( A0 const& x) BOOST_NOEXCEPT\n      {\n        A0 xi =  round2even(x*Inv2pi<A0>());\n        A0 xr = x-xi*Pix2_1<A0>();\n        xr -= xi*Pix2_2<A0>();\n        xr -= xi*Pix2_3<A0>();\n        return xr;\n      }\n    };\n\n    template < class dummy> struct rem2pi < tag::medium_tag, dummy >\n    {\n      static BOOST_FORCEINLINE A0 rem( A0 const& x) BOOST_NOEXCEPT\n      {\n        using i_t = bd::as_integer_t<A0>;\n        A0 xr;\n        i_t n = rem_pio2_medium(x, xr);\n        xr += tofloat(n)*Pio_2<A0>();\n        xr = if_else(gt(xr, Pi<A0>()), xr-Twopi<A0>(), xr);\n        return xr;\n      }\n    };\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "81005cd73ddca6cd17fdb307e5d8a749dd78eebe", "size": 4113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/generic/function/rem_2pi.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/generic/function/rem_2pi.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/generic/function/rem_2pi.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.904, "max_line_length": 100, "alphanum_fraction": 0.5842450766, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4213053153475091}}
{"text": "/******************************************************************************\n\n  This source file is part of the Avogadro project.\n\n  Copyright 2010 Eric C. Brown\n\n  This source code is released under the New BSD License, (the \"License\").\n\n  Unless required by applicable law or agreed to in writing, software\n  distributed under the License is distributed on an \"AS IS\" BASIS,\n  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n  See the License for the specific language governing permissions and\n  limitations under the License.\n\n******************************************************************************/\n\n#include \"qtaimcriticalpointlocator.h\"\n#include \"qtaimlsodaintegrator.h\"\n#include \"qtaimmathutilities.h\"\n#include \"qtaimodeintegrator.h\"\n#include \"qtaimwavefunction.h\"\n\n#include <Eigen/Core>\n\n#include <QList>\n\n#include <QtConcurrent/QtConcurrentMap>\n\n#include <QDataStream>\n#include <QDir>\n#include <QFile>\n#include <QTemporaryFile>\n\n#include <QVariant>\n\n#include <QFuture>\n#include <QFutureWatcher>\n#include <QProgressDialog>\n\nusing namespace std;\nusing namespace Eigen;\n\n#define HUGE_REAL_NUMBER 1.e20\n#define SMALL_GRADIENT_NORM 1.e-4\n\nnamespace Avogadro {\nnamespace QtPlugins {\n\nQList<QVariant> QTAIMLocateNuclearCriticalPoint(QList<QVariant> input)\n{\n  const QString fileName = input.at(0).toString();\n  const qint64 nucleus = input.at(1).toInt();\n  const QVector3D x0y0z0(input.at(2).toReal(), input.at(3).toReal(),\n                         input.at(4).toReal());\n\n  QTAIMWavefunction wfn;\n  wfn.loadFromBinaryFile(fileName);\n\n  QTAIMWavefunctionEvaluator eval(wfn);\n\n  QVector3D result;\n\n  if (wfn.nuclearCharge(nucleus) < 4) {\n    //      QTAIMODEIntegrator\n    //      ode(eval,QTAIMODEIntegrator::CMBPMinusThreeGradientInElectronDensity);\n    QTAIMLSODAIntegrator ode(\n      eval, QTAIMLSODAIntegrator::CMBPMinusThreeGradientInElectronDensity);\n    result = ode.integrate(x0y0z0);\n  } else {\n    result = x0y0z0;\n  }\n\n  bool correctSignature;\n  Matrix<qreal, 3, 1> xyz;\n  xyz << result.x(), result.y(), result.z();\n\n  if (QTAIMMathUtilities::signatureOfASymmetricThreeByThreeMatrix(\n        eval.hessianOfElectronDensity(xyz)) == -3) {\n    correctSignature = true;\n  } else {\n    correctSignature = false;\n  }\n\n  QList<QVariant> value;\n\n  if (correctSignature) {\n    value.append(correctSignature);\n    value.append(result.x());\n    value.append(result.y());\n    value.append(result.z());\n  } else {\n    value.append(false);\n  }\n\n  return value;\n}\n\nQList<QVariant> QTAIMLocateBondCriticalPoint(QList<QVariant> input)\n{\n\n  QList<QVariant> value;\n  value.clear();\n\n  const QString wfnFileName = input.at(0).toString();\n  const QString nuclearCriticalPointsFileName = input.at(1).toString();\n  const qint64 nucleusA = input.at(2).toInt();\n  const qint64 nucleusB = input.at(3).toInt();\n  const QVector3D x0y0z0(input.at(4).toReal(), input.at(5).toReal(),\n                         input.at(6).toReal());\n\n  QTAIMWavefunction wfn;\n  wfn.loadFromBinaryFile(wfnFileName);\n\n  QList<QVector3D> nuclearCriticalPoints;\n  QFile nuclearCriticalPointsFile(nuclearCriticalPointsFileName);\n  nuclearCriticalPointsFile.open(QIODevice::ReadOnly);\n  QDataStream nuclearCriticalPointsFileIn(&nuclearCriticalPointsFile);\n  nuclearCriticalPointsFileIn >> nuclearCriticalPoints;\n  nuclearCriticalPointsFile.close();\n\n  QList<QPair<QVector3D, qreal>> betaSpheres;\n  for (qint64 i = 0; i < nuclearCriticalPoints.length(); ++i) {\n    QPair<QVector3D, qreal> thisBetaSphere;\n    thisBetaSphere.first = nuclearCriticalPoints.at(i);\n    thisBetaSphere.second = 0.1;\n    betaSpheres.append(thisBetaSphere);\n  }\n\n  QTAIMWavefunctionEvaluator eval(wfn);\n\n  QList<QVector3D> ncpList;\n\n  QVector3D result;\n  //    QTAIMODEIntegrator\n  //    ode(eval,QTAIMODEIntegrator::CMBPMinusOneGradientInElectronDensity);\n  QTAIMLSODAIntegrator ode(\n    eval, QTAIMLSODAIntegrator::CMBPMinusOneGradientInElectronDensity);\n  result = ode.integrate(x0y0z0);\n  Matrix<qreal, 3, 1> xyz;\n  xyz << result.x(), result.y(), result.z();\n\n  if (!(QTAIMMathUtilities::signatureOfASymmetricThreeByThreeMatrix(\n          eval.hessianOfElectronDensity(xyz)) == -1) ||\n      (eval.gradientOfElectronDensity(xyz)).norm() > SMALL_GRADIENT_NORM) {\n    value.append(false);\n    value.append(result.x());\n    value.append(result.y());\n    value.append(result.z());\n    return value;\n  }\n\n  Matrix<qreal, 3, 3> eigenvectorsOfHessian;\n  eigenvectorsOfHessian =\n    QTAIMMathUtilities::eigenvectorsOfASymmetricThreeByThreeMatrix(\n      eval.hessianOfElectronDensity(xyz));\n  Matrix<qreal, 3, 1> highestEigenvectorOfHessian;\n  highestEigenvectorOfHessian << eigenvectorsOfHessian(0, 2),\n    eigenvectorsOfHessian(1, 2), eigenvectorsOfHessian(2, 2);\n\n  const qreal smallStep = 0.01;\n\n  QVector3D forwardStartingPoint(\n    result.x() + smallStep * highestEigenvectorOfHessian(0),\n    result.y() + smallStep * highestEigenvectorOfHessian(1),\n    result.z() + smallStep * highestEigenvectorOfHessian(2));\n\n  QVector3D backwardStartingPoint(\n    result.x() - smallStep * highestEigenvectorOfHessian(0),\n    result.y() - smallStep * highestEigenvectorOfHessian(1),\n    result.z() - smallStep * highestEigenvectorOfHessian(2));\n\n  //    QTAIMODEIntegrator\n  //    forwardODE(eval,QTAIMODEIntegrator::SteepestAscentPathInElectronDensity);\n  QTAIMLSODAIntegrator forwardODE(\n    eval, QTAIMLSODAIntegrator::SteepestAscentPathInElectronDensity);\n  forwardODE.setBetaSpheres(betaSpheres);\n  QVector3D forwardEndpoint = forwardODE.integrate(forwardStartingPoint);\n  QList<QVector3D> forwardPath = forwardODE.path();\n\n  //    QTAIMODEIntegrator\n  //    backwardODE(eval,QTAIMODEIntegrator::SteepestAscentPathInElectronDensity);\n  QTAIMLSODAIntegrator backwardODE(\n    eval, QTAIMLSODAIntegrator::SteepestAscentPathInElectronDensity);\n  backwardODE.setBetaSpheres(betaSpheres);\n  QVector3D backwardEndpoint = backwardODE.integrate(backwardStartingPoint);\n  QList<QVector3D> backwardPath = backwardODE.path();\n\n  qreal smallestDistance = HUGE_REAL_NUMBER;\n  qint64 smallestDistanceIndex = 0;\n\n  for (qint64 n = 0; n < wfn.numberOfNuclei(); ++n) {\n    Matrix<qreal, 3, 1> a(forwardEndpoint.x(), forwardEndpoint.y(),\n                          forwardEndpoint.z());\n    Matrix<qreal, 3, 1> b(wfn.xNuclearCoordinate(n), wfn.yNuclearCoordinate(n),\n                          wfn.zNuclearCoordinate(n));\n\n    qreal distance = QTAIMMathUtilities::distance(a, b);\n\n    if (distance < smallestDistance) {\n      smallestDistance = distance;\n      smallestDistanceIndex = n;\n    }\n  }\n  qint64 forwardNucleusIndex = smallestDistanceIndex;\n\n  smallestDistance = HUGE_REAL_NUMBER;\n  smallestDistanceIndex = 0;\n\n  for (qint64 n = 0; n < wfn.numberOfNuclei(); ++n) {\n    Matrix<qreal, 3, 1> a(backwardEndpoint.x(), backwardEndpoint.y(),\n                          backwardEndpoint.z());\n    Matrix<qreal, 3, 1> b(wfn.xNuclearCoordinate(n), wfn.yNuclearCoordinate(n),\n                          wfn.zNuclearCoordinate(n));\n\n    qreal distance = QTAIMMathUtilities::distance(a, b);\n\n    if (distance < smallestDistance) {\n      smallestDistance = distance;\n      smallestDistanceIndex = n;\n    }\n  }\n  qint64 backwardNucleusIndex = smallestDistanceIndex;\n\n  bool bondPathConnectsPair;\n  if ((forwardNucleusIndex == nucleusA && backwardNucleusIndex == nucleusB) ||\n      (forwardNucleusIndex == nucleusB && backwardNucleusIndex == nucleusA)) {\n    bondPathConnectsPair = true;\n  } else {\n    bondPathConnectsPair = false;\n  }\n\n  if (bondPathConnectsPair) {\n    value.append(true);\n    value.append(nucleusA);\n    value.append(nucleusB);\n    value.append(result.x());\n    value.append(result.y());\n    value.append(result.z());\n    Matrix<qreal, 3, 1> xyz_;\n    xyz_ << result.x(), result.y(), result.z();\n    value.append(eval.laplacianOfElectronDensity(xyz_));\n    value.append(QTAIMMathUtilities::ellipticityOfASymmetricThreeByThreeMatrix(\n      eval.hessianOfElectronDensity(xyz_)));\n    value.append(1 + forwardPath.length() + 1 + backwardPath.length() + 1);\n    value.append(forwardEndpoint.x());\n    for (qint64 i = forwardPath.length() - 1; i >= 0; --i) {\n      value.append(forwardPath.at(i).x());\n    }\n    value.append(result.x());\n    for (qint64 i = 0; i < backwardPath.length(); ++i) {\n      value.append(backwardPath.at(i).x());\n    }\n    value.append(backwardEndpoint.x());\n    value.append(forwardEndpoint.y());\n    for (qint64 i = forwardPath.length() - 1; i >= 0; --i) {\n      value.append(forwardPath.at(i).y());\n    }\n    value.append(result.y());\n    for (qint64 i = 0; i < backwardPath.length(); ++i) {\n      value.append(backwardPath.at(i).y());\n    }\n    value.append(backwardEndpoint.y());\n    value.append(forwardEndpoint.z());\n    for (qint64 i = forwardPath.length() - 1; i >= 0; --i) {\n      value.append(forwardPath.at(i).z());\n    }\n    value.append(result.z());\n    for (qint64 i = 0; i < backwardPath.length(); ++i) {\n      value.append(backwardPath.at(i).z());\n    }\n    value.append(backwardEndpoint.z());\n\n  } else {\n    value.append(false);\n    // for debugging\n    value.append(result.x());\n    value.append(result.y());\n    value.append(result.z());\n  }\n\n  return value;\n}\n\nQList<QVariant> QTAIMLocateElectronDensitySink(QList<QVariant> input)\n{\n  qint64 counter = 0;\n  const QString fileName = input.at(counter).toString();\n  counter++;\n  //    const qint64 nucleus=input.at(counter).toInt(); counter++\n  qreal x0 = input.at(counter).toReal();\n  counter++;\n  qreal y0 = input.at(counter).toReal();\n  counter++;\n  qreal z0 = input.at(counter).toReal();\n  counter++;\n\n  const QVector3D x0y0z0(x0, y0, z0);\n\n  QTAIMWavefunction wfn;\n  wfn.loadFromBinaryFile(fileName);\n\n  QTAIMWavefunctionEvaluator eval(wfn);\n\n  bool correctSignature;\n  QVector3D result;\n\n  Matrix<qreal, 3, 1> xyz;\n  xyz << x0, y0, z0;\n  if (eval.electronDensity(xyz) < 1.e-1) {\n    correctSignature = false;\n  } else {\n    //      QTAIMODEIntegrator\n    //      ode(eval,QTAIMODEIntegrator::CMBPMinusThreeGradientInElectronDensityLaplacian);\n    QTAIMLSODAIntegrator ode(\n      eval,\n      QTAIMLSODAIntegrator::CMBPMinusThreeGradientInElectronDensityLaplacian);\n    result = ode.integrate(x0y0z0);\n\n    Matrix<qreal, 3, 1> xyz_;\n    xyz_ << result.x(), result.y(), result.z();\n\n    if (eval.electronDensity(xyz_) > 1.e-1 &&\n        eval.gradientOfElectronDensityLaplacian(xyz_).norm() < 1.e-3) {\n      if (QTAIMMathUtilities::signatureOfASymmetricThreeByThreeMatrix(\n            eval.hessianOfElectronDensityLaplacian(xyz_)) == -3) {\n        correctSignature = true;\n      } else {\n        correctSignature = false;\n      }\n    } else {\n      correctSignature = false;\n    }\n  }\n\n  QList<QVariant> value;\n  if (correctSignature) {\n    value.append(correctSignature);\n    value.append(result.x());\n    value.append(result.y());\n    value.append(result.z());\n  } else {\n    value.append(false);\n  }\n\n  return value;\n}\n\nQList<QVariant> QTAIMLocateElectronDensitySource(QList<QVariant> input)\n{\n  qint64 counter = 0;\n  const QString fileName = input.at(counter).toString();\n  counter++;\n  //    const qint64 nucleus=input.at(counter).toInt(); counter++\n  qreal x0 = input.at(counter).toReal();\n  counter++;\n  qreal y0 = input.at(counter).toReal();\n  counter++;\n  qreal z0 = input.at(counter).toReal();\n  counter++;\n\n  const QVector3D x0y0z0(x0, y0, z0);\n\n  QTAIMWavefunction wfn;\n  wfn.loadFromBinaryFile(fileName);\n\n  QTAIMWavefunctionEvaluator eval(wfn);\n\n  bool correctSignature;\n  QVector3D result;\n\n  Matrix<qreal, 3, 1> xyz;\n  xyz << x0, y0, z0;\n  if (eval.electronDensity(xyz) < 1.e-1) {\n    correctSignature = false;\n  } else {\n    //      QTAIMODEIntegrator\n    //      ode(eval,QTAIMODEIntegrator::CMBPPlusThreeGradientInElectronDensityLaplacian);\n    QTAIMLSODAIntegrator ode(\n      eval,\n      QTAIMLSODAIntegrator::CMBPPlusThreeGradientInElectronDensityLaplacian);\n    result = ode.integrate(x0y0z0);\n\n    Matrix<qreal, 3, 1> xyz_;\n    xyz_ << result.x(), result.y(), result.z();\n\n    if (eval.electronDensity(xyz_) > 1.e-1 &&\n        eval.gradientOfElectronDensityLaplacian(xyz_).norm() < 1.e-3) {\n      if (QTAIMMathUtilities::signatureOfASymmetricThreeByThreeMatrix(\n            eval.hessianOfElectronDensityLaplacian(xyz_)) == 3) {\n        correctSignature = true;\n      } else {\n        correctSignature = false;\n      }\n    } else {\n      correctSignature = false;\n    }\n  }\n\n  QList<QVariant> value;\n  if (correctSignature) {\n    value.append(correctSignature);\n    value.append(result.x());\n    value.append(result.y());\n    value.append(result.z());\n  } else {\n    value.append(false);\n  }\n\n  return value;\n}\n\nQTAIMCriticalPointLocator::QTAIMCriticalPointLocator(QTAIMWavefunction& wfn)\n{\n  m_wfn = &wfn;\n\n  m_nuclearCriticalPoints.empty();\n  m_bondCriticalPoints.empty();\n  m_ringCriticalPoints.empty();\n  m_cageCriticalPoints.empty();\n\n  m_laplacianAtBondCriticalPoints.empty();\n  m_ellipticityAtBondCriticalPoints.empty();\n\n  m_bondPaths.empty();\n  m_bondedAtoms.empty();\n\n  m_electronDensitySources.empty();\n  m_electronDensitySinks.empty();\n}\n\nvoid QTAIMCriticalPointLocator::locateNuclearCriticalPoints()\n{\n\n  QString tempFileName = QTAIMCriticalPointLocator::temporaryFileName();\n\n  QList<QList<QVariant>> inputList;\n\n  const qint64 numberOfNuclei = m_wfn->numberOfNuclei();\n\n  for (qint64 n = 0; n < numberOfNuclei; ++n) {\n    QList<QVariant> input;\n    input.append(tempFileName);\n    input.append(n);\n    input.append(m_wfn->xNuclearCoordinate(n));\n    input.append(m_wfn->yNuclearCoordinate(n));\n    input.append(m_wfn->zNuclearCoordinate(n));\n\n    inputList.append(input);\n  }\n\n  m_wfn->saveToBinaryFile(tempFileName);\n\n  QProgressDialog dialog;\n  dialog.setWindowTitle(\"QTAIM\");\n  dialog.setLabelText(QString(\"Nuclear Critical Points Search\"));\n\n  QFutureWatcher<void> futureWatcher;\n  QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset()));\n  QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel()));\n  QObject::connect(&futureWatcher, SIGNAL(progressRangeChanged(int, int)),\n                   &dialog, SLOT(setRange(int, int)));\n  QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &dialog,\n                   SLOT(setValue(int)));\n\n  QFuture<QList<QVariant>> future =\n    QtConcurrent::mapped(inputList, QTAIMLocateNuclearCriticalPoint);\n  futureWatcher.setFuture(future);\n  dialog.exec();\n  futureWatcher.waitForFinished();\n\n  QList<QList<QVariant>> results;\n  if (futureWatcher.future().isCanceled()) {\n    results.clear();\n  } else {\n    results = future.results();\n  }\n\n  QFile file;\n  file.remove(tempFileName);\n\n  for (qint64 n = 0; n < results.length(); ++n) {\n\n    bool correctSignature = results.at(n).at(0).toBool();\n\n    if (correctSignature) {\n\n      QVector3D result(results.at(n).at(1).toReal(),\n                       results.at(n).at(2).toReal(),\n                       results.at(n).at(3).toReal());\n\n      m_nuclearCriticalPoints.append(result);\n    }\n  }\n}\n\nvoid QTAIMCriticalPointLocator::locateBondCriticalPoints()\n{\n\n  if (m_nuclearCriticalPoints.length() < 1) {\n    return;\n  }\n\n  const qint64 numberOfNuclei = m_wfn->numberOfNuclei();\n\n  if (numberOfNuclei < 2) {\n    return;\n  }\n\n  QString tempFileName = QTAIMCriticalPointLocator::temporaryFileName();\n\n  QString nuclearCriticalPointsFileName =\n    QTAIMCriticalPointLocator::temporaryFileName();\n  QFile nuclearCriticalPointsFile(nuclearCriticalPointsFileName);\n  nuclearCriticalPointsFile.open(QIODevice::WriteOnly);\n  QDataStream nuclearCriticalPointsOut(&nuclearCriticalPointsFile);\n  nuclearCriticalPointsOut << m_nuclearCriticalPoints;\n  nuclearCriticalPointsFile.close();\n\n  QList<QList<QVariant>> inputList;\n\n  for (qint64 M = 0; M < numberOfNuclei - 1; ++M) {\n    for (qint64 N = M + 1; N < numberOfNuclei; ++N) {\n\n      const qreal distanceCutoff = 8.0;\n\n      Matrix<qreal, 3, 1> a;\n      Matrix<qreal, 3, 1> b;\n\n      a << m_wfn->xNuclearCoordinate(M), m_wfn->yNuclearCoordinate(M),\n        m_wfn->zNuclearCoordinate(M);\n      b << m_wfn->xNuclearCoordinate(N), m_wfn->yNuclearCoordinate(N),\n        m_wfn->zNuclearCoordinate(N);\n\n      if (QTAIMMathUtilities::distance(a, b) < distanceCutoff) {\n        QVector3D x0y0z0(\n          (m_wfn->xNuclearCoordinate(M) + m_wfn->xNuclearCoordinate(N)) / 2.0,\n          (m_wfn->yNuclearCoordinate(M) + m_wfn->yNuclearCoordinate(N)) / 2.0,\n          (m_wfn->zNuclearCoordinate(M) + m_wfn->zNuclearCoordinate(N)) / 2.0);\n\n        QList<QVariant> input;\n        input.append(tempFileName);\n        input.append(nuclearCriticalPointsFileName);\n        input.append(M);\n        input.append(N);\n        input.append(x0y0z0.x());\n        input.append(x0y0z0.y());\n        input.append(x0y0z0.z());\n\n        inputList.append(input);\n      }\n    } // end N\n  }   // end M\n\n  m_wfn->saveToBinaryFile(tempFileName);\n\n  QProgressDialog dialog;\n  dialog.setWindowTitle(\"QTAIM\");\n  dialog.setLabelText(QString(\"Bond Critical Points Search\"));\n\n  QFutureWatcher<void> futureWatcher;\n  QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset()));\n  QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel()));\n  QObject::connect(&futureWatcher, SIGNAL(progressRangeChanged(int, int)),\n                   &dialog, SLOT(setRange(int, int)));\n  QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &dialog,\n                   SLOT(setValue(int)));\n\n  QFuture<QList<QVariant>> future =\n    QtConcurrent::mapped(inputList, QTAIMLocateBondCriticalPoint);\n  ;\n  futureWatcher.setFuture(future);\n  dialog.exec();\n  futureWatcher.waitForFinished();\n\n  QList<QList<QVariant>> results;\n  if (futureWatcher.future().isCanceled()) {\n    results.clear();\n  } else {\n    results = future.results();\n  }\n\n  QFile file;\n  file.remove(tempFileName);\n  file.remove(nuclearCriticalPointsFileName);\n\n  for (qint64 i = 0; i < results.length(); ++i) {\n    QList<QVariant> thisCriticalPoint = results.at(i);\n\n    bool success = thisCriticalPoint.at(0).toBool();\n\n    if (success) {\n      QPair<qint64, qint64> bondedAtoms_;\n      bondedAtoms_.first = thisCriticalPoint.at(1).toInt();\n      bondedAtoms_.second = thisCriticalPoint.at(2).toInt();\n      m_bondedAtoms.append(bondedAtoms_);\n\n      QVector3D coordinates(thisCriticalPoint.at(3).toReal(),\n                            thisCriticalPoint.at(4).toReal(),\n                            thisCriticalPoint.at(5).toReal());\n\n      m_bondCriticalPoints.append(coordinates);\n\n      m_laplacianAtBondCriticalPoints.append(thisCriticalPoint.at(6).toReal());\n      m_ellipticityAtBondCriticalPoints.append(\n        thisCriticalPoint.at(7).toReal());\n      qint64 pathLength = thisCriticalPoint.at(8).toInt();\n\n      QList<QVector3D> bondPath;\n      for (qint64 j = 0; j < pathLength; ++j) {\n        QVector3D pathPoint(\n          thisCriticalPoint.at(9 + j).toReal(),\n          thisCriticalPoint.at(9 + j + pathLength).toReal(),\n          thisCriticalPoint.at(9 + j + 2 * pathLength).toReal());\n\n        bondPath.append(pathPoint);\n      }\n\n      m_bondPaths.append(bondPath);\n    }\n  }\n}\n\nvoid QTAIMCriticalPointLocator::locateElectronDensitySources()\n{\n\n  QString tempFileName = QTAIMCriticalPointLocator::temporaryFileName();\n\n  QList<QList<QVariant>> inputList;\n\n  qreal xmin, ymin, zmin;\n  qreal xmax, ymax, zmax;\n  qreal xstep, ystep, zstep;\n\n  // TODO: if only we were using Eigen data structures...\n  QList<qreal> xNuclearCoordinates;\n  QList<qreal> yNuclearCoordinates;\n  QList<qreal> zNuclearCoordinates;\n\n  for (qint64 i = 0; i < m_wfn->numberOfNuclei(); ++i) {\n    xNuclearCoordinates.append(m_wfn->xNuclearCoordinate(i));\n    yNuclearCoordinates.append(m_wfn->yNuclearCoordinate(i));\n    zNuclearCoordinates.append(m_wfn->zNuclearCoordinate(i));\n  }\n\n  xmin = xNuclearCoordinates.first();\n  xmax = xNuclearCoordinates.first();\n  for (qint64 i = 1; i < m_wfn->numberOfNuclei(); ++i) {\n    if (xNuclearCoordinates.at(i) < xmin) {\n      xmin = xNuclearCoordinates.at(i);\n    }\n    if (xNuclearCoordinates.at(i) > xmax) {\n      xmax = xNuclearCoordinates.at(i);\n    }\n  }\n\n  ymin = yNuclearCoordinates.first();\n  ymax = yNuclearCoordinates.first();\n  for (qint64 i = 1; i < yNuclearCoordinates.count(); ++i) {\n    if (yNuclearCoordinates.at(i) < ymin) {\n      ymin = yNuclearCoordinates.at(i);\n    }\n    if (yNuclearCoordinates.at(i) > ymax) {\n      ymax = yNuclearCoordinates.at(i);\n    }\n  }\n\n  zmin = zNuclearCoordinates.first();\n  zmax = zNuclearCoordinates.first();\n  for (qint64 i = 1; i < zNuclearCoordinates.count(); ++i) {\n    if (zNuclearCoordinates.at(i) < zmin) {\n      zmin = zNuclearCoordinates.at(i);\n    }\n    if (zNuclearCoordinates.at(i) > zmax) {\n      zmax = zNuclearCoordinates.at(i);\n    }\n  }\n\n  xmin = -2.0 + xmin;\n  ymin = -2.0 + ymin;\n  zmin = -2.0 + zmin;\n\n  xmax = 2.0 + xmax;\n  ymax = 2.0 + ymax;\n  zmax = 2.0 + zmax;\n\n  xstep = ystep = zstep = 0.5;\n\n  for (qreal x = xmin; x < xmax + xstep; x = x + xstep) {\n    for (qreal y = ymin; y < ymax + ystep; y = y + ystep) {\n      for (qreal z = zmin; z < zmax + zstep; z = z + zstep) {\n        QList<QVariant> input;\n        input.append(tempFileName);\n        //          input.append( n );\n        input.append(x);\n        input.append(y);\n        input.append(z);\n\n        inputList.append(input);\n      }\n    }\n  }\n\n  m_wfn->saveToBinaryFile(tempFileName);\n\n  QProgressDialog dialog;\n  dialog.setWindowTitle(\"QTAIM\");\n  dialog.setLabelText(QString(\"Electron Density Sources Search\"));\n\n  QFutureWatcher<void> futureWatcher;\n  QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset()));\n  QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel()));\n  QObject::connect(&futureWatcher, SIGNAL(progressRangeChanged(int, int)),\n                   &dialog, SLOT(setRange(int, int)));\n  QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &dialog,\n                   SLOT(setValue(int)));\n\n  QFuture<QList<QVariant>> future =\n    QtConcurrent::mapped(inputList, QTAIMLocateElectronDensitySource);\n  futureWatcher.setFuture(future);\n  dialog.exec();\n  futureWatcher.waitForFinished();\n\n  QList<QList<QVariant>> results;\n  if (futureWatcher.future().isCanceled()) {\n    results.clear();\n  } else {\n    results = future.results();\n  }\n\n  QFile file;\n  file.remove(tempFileName);\n\n  for (qint64 n = 0; n < results.length(); ++n) {\n\n    qint64 counter = 0;\n    bool correctSignature = results.at(n).at(counter).toBool();\n    counter++;\n\n    if (correctSignature) {\n      qreal x = results.at(n).at(counter).toReal();\n      counter++;\n      qreal y = results.at(n).at(counter).toReal();\n      counter++;\n      qreal z = results.at(n).at(counter).toReal();\n      counter++;\n\n      if ((xmin < x && x < xmax) && (ymin < y && y < ymax) &&\n          (zmin < z && z < zmax)) {\n        QVector3D result(x, y, z);\n\n        qreal smallestDistance = HUGE_REAL_NUMBER;\n\n        for (qint64 i = 0; i < m_electronDensitySources.length(); ++i) {\n\n          Matrix<qreal, 3, 1> a(x, y, z);\n          Matrix<qreal, 3, 1> b(m_electronDensitySources.at(i).x(),\n                                m_electronDensitySources.at(i).y(),\n                                m_electronDensitySources.at(i).z());\n\n          qreal distance = QTAIMMathUtilities::distance(a, b);\n\n          if (distance < smallestDistance) {\n            smallestDistance = distance;\n          }\n        }\n\n        if (smallestDistance > 1.e-2) {\n          m_electronDensitySources.append(result);\n        }\n      }\n    }\n  }\n  //    qDebug() << \"SOURCES\" << m_electronDensitySources;\n}\n\nvoid QTAIMCriticalPointLocator::locateElectronDensitySinks()\n{\n\n  QString tempFileName = QTAIMCriticalPointLocator::temporaryFileName();\n\n  QList<QList<QVariant>> inputList;\n\n  qreal xmin, ymin, zmin;\n  qreal xmax, ymax, zmax;\n  qreal xstep, ystep, zstep;\n\n  // TODO: if only we were using Eigen data structures...\n  QList<qreal> xNuclearCoordinates;\n  QList<qreal> yNuclearCoordinates;\n  QList<qreal> zNuclearCoordinates;\n\n  for (qint64 i = 0; i < m_wfn->numberOfNuclei(); ++i) {\n    xNuclearCoordinates.append(m_wfn->xNuclearCoordinate(i));\n    yNuclearCoordinates.append(m_wfn->yNuclearCoordinate(i));\n    zNuclearCoordinates.append(m_wfn->zNuclearCoordinate(i));\n  }\n\n  xmin = xNuclearCoordinates.first();\n  xmax = xNuclearCoordinates.first();\n  for (qint64 i = 1; i < m_wfn->numberOfNuclei(); ++i) {\n    if (xNuclearCoordinates.at(i) < xmin) {\n      xmin = xNuclearCoordinates.at(i);\n    }\n    if (xNuclearCoordinates.at(i) > xmax) {\n      xmax = xNuclearCoordinates.at(i);\n    }\n  }\n\n  ymin = yNuclearCoordinates.first();\n  ymax = yNuclearCoordinates.first();\n  for (qint64 i = 1; i < yNuclearCoordinates.count(); ++i) {\n    if (yNuclearCoordinates.at(i) < ymin) {\n      ymin = yNuclearCoordinates.at(i);\n    }\n    if (yNuclearCoordinates.at(i) > ymax) {\n      ymax = yNuclearCoordinates.at(i);\n    }\n  }\n\n  zmin = zNuclearCoordinates.first();\n  zmax = zNuclearCoordinates.first();\n  for (qint64 i = 1; i < zNuclearCoordinates.count(); ++i) {\n    if (zNuclearCoordinates.at(i) < zmin) {\n      zmin = zNuclearCoordinates.at(i);\n    }\n    if (zNuclearCoordinates.at(i) > zmax) {\n      zmax = zNuclearCoordinates.at(i);\n    }\n  }\n\n  xmin = -2.0 + xmin;\n  ymin = -2.0 + ymin;\n  zmin = -2.0 + zmin;\n\n  xmax = 2.0 + xmax;\n  ymax = 2.0 + ymax;\n  zmax = 2.0 + zmax;\n\n  xstep = ystep = zstep = 0.5;\n\n  for (qreal x = xmin; x < xmax + xstep; x = x + xstep) {\n    for (qreal y = ymin; y < ymax + ystep; y = y + ystep) {\n      for (qreal z = zmin; z < zmax + zstep; z = z + zstep) {\n        QList<QVariant> input;\n        input.append(tempFileName);\n        //          input.append( n );\n        input.append(x);\n        input.append(y);\n        input.append(z);\n\n        inputList.append(input);\n      }\n    }\n  }\n\n  m_wfn->saveToBinaryFile(tempFileName);\n\n  QProgressDialog dialog;\n  dialog.setWindowTitle(\"QTAIM\");\n  dialog.setLabelText(QString(\"Electron Density Sinks Search\"));\n\n  QFutureWatcher<void> futureWatcher;\n  QObject::connect(&futureWatcher, SIGNAL(finished()), &dialog, SLOT(reset()));\n  QObject::connect(&dialog, SIGNAL(canceled()), &futureWatcher, SLOT(cancel()));\n  QObject::connect(&futureWatcher, SIGNAL(progressRangeChanged(int, int)),\n                   &dialog, SLOT(setRange(int, int)));\n  QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &dialog,\n                   SLOT(setValue(int)));\n\n  QFuture<QList<QVariant>> future =\n    QtConcurrent::mapped(inputList, QTAIMLocateElectronDensitySink);\n  futureWatcher.setFuture(future);\n  dialog.exec();\n  futureWatcher.waitForFinished();\n\n  QList<QList<QVariant>> results;\n  if (futureWatcher.future().isCanceled()) {\n    results.clear();\n  } else {\n    results = future.results();\n  }\n\n  QFile file;\n  file.remove(tempFileName);\n\n  for (qint64 n = 0; n < results.length(); ++n) {\n\n    qint64 counter = 0;\n    bool correctSignature = results.at(n).at(counter).toBool();\n    counter++;\n\n    if (correctSignature) {\n      qreal x = results.at(n).at(counter).toReal();\n      counter++;\n      qreal y = results.at(n).at(counter).toReal();\n      counter++;\n      qreal z = results.at(n).at(counter).toReal();\n      counter++;\n\n      if ((xmin < x && x < xmax) && (ymin < y && y < ymax) &&\n          (zmin < z && z < zmax)) {\n        QVector3D result(x, y, z);\n\n        qreal smallestDistance = HUGE_REAL_NUMBER;\n\n        for (qint64 i = 0; i < m_electronDensitySinks.length(); ++i) {\n\n          Matrix<qreal, 3, 1> a(x, y, z);\n          Matrix<qreal, 3, 1> b(m_electronDensitySinks.at(i).x(),\n                                m_electronDensitySinks.at(i).y(),\n                                m_electronDensitySinks.at(i).z());\n\n          qreal distance = QTAIMMathUtilities::distance(a, b);\n\n          if (distance < smallestDistance) {\n            smallestDistance = distance;\n          }\n        }\n\n        if (smallestDistance > 1.e-2) {\n          m_electronDensitySinks.append(result);\n        }\n      }\n    }\n  }\n  //    qDebug() << \"SINKS\" << m_electronDensitySinks;\n}\n\nQString QTAIMCriticalPointLocator::temporaryFileName()\n{\n  QTemporaryFile temporaryFile;\n  temporaryFile.open();\n  QString tempFileName = temporaryFile.fileName();\n  temporaryFile.close();\n  temporaryFile.remove();\n\n  // wait for temporary file to be deleted\n  QDir dir;\n  do {\n    // Nothing\n  } while (dir.exists(tempFileName));\n\n  return tempFileName;\n}\n\n} // namespace QtPlugins\n} // namespace Avogadro\n", "meta": {"hexsha": "cedd0de412c43ba86b0bb3dc542e497f82c532c9", "size": 28356, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "avogadro/qtplugins/qtaim/qtaimcriticalpointlocator.cpp", "max_stars_repo_name": "berquist/avogadrolibs", "max_stars_repo_head_hexsha": "e169315d8f9527d6b8bee1b7426eabb8a188073b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 244.0, "max_stars_repo_stars_event_min_datetime": "2015-09-09T15:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T17:44:21.000Z", "max_issues_repo_path": "avogadro/qtplugins/qtaim/qtaimcriticalpointlocator.cpp", "max_issues_repo_name": "berquist/avogadrolibs", "max_issues_repo_head_hexsha": "e169315d8f9527d6b8bee1b7426eabb8a188073b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 670.0, "max_issues_repo_issues_event_min_datetime": "2015-05-08T18:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T19:47:08.000Z", "max_forks_repo_path": "avogadro/qtplugins/qtaim/qtaimcriticalpointlocator.cpp", "max_forks_repo_name": "berquist/avogadrolibs", "max_forks_repo_head_hexsha": "e169315d8f9527d6b8bee1b7426eabb8a188073b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 129.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T01:18:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T08:50:25.000Z", "avg_line_length": 29.9113924051, "max_line_length": 91, "alphanum_fraction": 0.660600931, "num_tokens": 7689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.42114852774612693}}
{"text": "#ifndef __METROPOLIS_HPP__\n#define __METROPOLIS_HPP__\n\n#include <vector>\n#include <array>\n#include <random>\n#include <functional>\n#include <limits>\n#include <armadillo>\n#include <exception>\n#include <initializer_list>\n#include \"pauth_types.hpp\"\n#include \"molecular.hpp\"\n#include \"potentials.hpp\"\n#include \"acceptance.hpp\"\n#include \"boundary.hpp\"\n#include \"distance.hpp\"\n#include \"trial.hpp\"\n#include \"seed.hpp\"\n\n/* TODO: make random number generator more general so that user can specify\n *       which random number generator they'd prefer to use\n */\n\nnamespace pauth {\n\nstatic const double _default_kB = 1.0;\n\nstatic metric _default_metric = periodic_euclidean;\nstatic bc _default_bc = periodic_bc;\nstatic acc _default_acc = metropolis_acc;\n\nclass metropolis {\npublic:\n  static metric DEFAULT_METRIC;\n  static bc DEFAULT_BC;\n  static acc DEFAULT_ACC;\n\n  /*! \\brief Default constructor\n   */\n  metropolis() {}\n\n  /*! \\brief Constructor for a Markov chain Monte Carlo simulation\n   *\n   * \\param     id          Molecular id of simulation molecules\n   * \\param     N           Number of molecules\n   * \\param     D           Number of dimensions \n   * \\param     L           Simulation box edge length\n   * \\param     tmg         Trial move generator\n   * \\param     pot         Molecular potential\n   * \\param     T           Simulation temperature\n   * \\param     kB          Boltzmann's constant\n   * \\param     m           Metric for measuring molecule-molecule distances\n   * \\param     bc          Boundary conditions\n   * \\param     acceptance  Determines whether a move is accepted for rejected\n   * \\param     sg          Function for generating a seed\n   * \\param     init_zeros  If true, initializes all molecules to position zero\n   * \\return                Markov chain Monte Carlo simulation object\n   */\n  metropolis(const molecular_id id, const size_t N, const size_t D, \n             const double L, trial_move_generator tmg,\n             abstract_potential* pot, const double T, \n             const double kB = _default_kB, \n             metric m = _default_metric, bc boundary = _default_bc,\n             acc acceptance = _default_acc,\n             seed_gen sg = _default_seed_gen,\n             const bool init_zeros = false); \n\n  /*! \\brief Constructor for a Markov chain Monte Carlo simulation\n   *\n   * \\param     fname         Filename of initial molecular positions\n   * \\param     id            Molecular id of simulation molecules\n   * \\param     N             Number of molecules\n   * \\param     D             Number of dimensions \n   * \\param     L             Simulation box edge length\n   * \\param     tmg           Trial move generator\n   * \\param     pot           Molecular potential\n   * \\param     T             Simulation temperature\n   * \\param     kB            Boltzmann's constant\n   * \\param     m             Metric for measuring molecule-molecule distances\n   * \\param     bc            Boundary conditions\n   * \\param     acceptance    Determines whether a move is accepted for rejected\n   * \\param     sg            Function for generating a seed\n   * \\return                  Markov chain Monte Carlo simulation object\n   */\n  metropolis(const char *fname, const molecular_id id, const size_t N, \n             const size_t D, const double L, trial_move_generator tmg,\n             abstract_potential* pot, const double T, \n             const double kB = _default_kB, \n             metric m = _default_metric, bc boundary = _default_bc,\n             acc acceptance = _default_acc,\n             seed_gen sg = _default_seed_gen); \n\n  /*! \\brief Constructor for a Markov chain Monte Carlo simulation\n   *\n   * \\param     fname         Filename of initial molecular positions\n   * \\param     N             Number of molecules\n   * \\param     D             Number of dimensions \n   * \\param     L             Simulation box edge length\n   * \\param     tmg           Trial move generator\n   * \\param     pot           Molecular potential\n   * \\param     T             Simulation temperature\n   * \\param     kB            Boltzmann's constant\n   * \\param     m             Metric for measuring molecule-molecule distances\n   * \\param     bc            Boundary conditions\n   * \\param     acceptance    Determines whether a move is accepted for rejected\n   * \\param     sg            Function for generating a seed\n   * \\return                  Markov chain Monte Carlo simulation object\n   */\n  metropolis(const char *fname, const size_t N, \n             const size_t D, const double L, trial_move_generator tmg,\n             abstract_potential* pot, const double T, \n             const double kB = _default_kB, \n             metric m = _default_metric, bc boundary = _default_bc,\n             acc acceptance = _default_acc,\n             seed_gen sg = _default_seed_gen);\n\n  /*! \\brief Constructor for a Markov chain Monte Carlo simulation\n   *\n   * \\param     id          Molecular id of simulation molecules\n   * \\param     N           Number of molecules\n   * \\param     D           Number of dimensions \n   * \\param     L           Simulation box edge length\n   * \\param     tmg         Trial move generator\n   * \\param     pots        Molecular potentials\n   * \\param     T           Simulation temperature\n   * \\param     kB          Boltzmann's constant\n   * \\param     m           Metric for measuring molecule-molecule distances\n   * \\param     bc          Boundary conditions\n   * \\param     acceptance  Determines whether a move is accepted for rejected\n   * \\param     sg          Function for generating a seed\n   * \\param     init_zeros  If true, initializes all molecules to position zero\n   * \\return                Markov chain Monte Carlo simulation object\n   */\n  metropolis(const molecular_id id, const size_t N, const size_t D, \n             const double L, trial_move_generator tmg,\n             std::initializer_list<abstract_potential*> pots, const double T, \n             const double kB = _default_kB, \n             metric m = _default_metric, bc boundary = _default_bc,\n             acc acceptance = _default_acc,\n             seed_gen sg = _default_seed_gen,\n             const bool init_zeros = false); \n\n  /*! \\brief Constructor for a Markov chain Monte Carlo simulation\n   *\n   * \\param     fname         Filename of initial molecular positions\n   * \\param     id            Molecular id of simulation molecules\n   * \\param     N             Number of molecules\n   * \\param     D             Number of dimensions \n   * \\param     L             Simulation box edge length\n   * \\param     tmg           Trial move generator\n   * \\param     pots        Molecular potentials\n   * \\param     T             Simulation temperature\n   * \\param     kB            Boltzmann's constant\n   * \\param     m             Metric for measuring molecule-molecule distances\n   * \\param     bc            Boundary conditions\n   * \\param     acceptance    Determines whether a move is accepted for rejected\n   * \\param     sg            Function for generating a seed\n   * \\return                  Markov chain Monte Carlo simulation object\n   */\n  metropolis(const char *fname, const molecular_id id, const size_t N, \n             const size_t D, const double L, trial_move_generator tmg,\n             std::initializer_list<abstract_potential*> pots, const double T, \n             const double kB = _default_kB, \n             metric m = _default_metric, bc boundary = _default_bc,\n             acc acceptance = _default_acc,\n             seed_gen sg = _default_seed_gen); \n\n  /*! \\brief Constructor for a Markov chain Monte Carlo simulation\n   *\n   * \\param     fname         Filename of initial molecular positions\n   * \\param     N             Number of molecules\n   * \\param     D             Number of dimensions \n   * \\param     L             Simulation box edge length\n   * \\param     tmg           Trial move generator\n   * \\param     pots        Molecular potentials\n   * \\param     T             Simulation temperature\n   * \\param     kB            Boltzmann's constant\n   * \\param     m             Metric for measuring molecule-molecule distances\n   * \\param     bc            Boundary conditions\n   * \\param     acceptance    Determines whether a move is accepted for rejected\n   * \\param     sg            Function for generating a seed\n   * \\return                  Markov chain Monte Carlo simulation object\n   */\n  metropolis(const char *fname, const size_t N, \n             const size_t D, const double L, trial_move_generator tmg,\n             std::initializer_list<abstract_potential*> pots, const double T, \n             const double kB = _default_kB, \n             metric m = _default_metric, bc boundary = _default_bc,\n             acc acceptance = _default_acc,\n             seed_gen sg = _default_seed_gen);\n\n  /*! \\brief Copy constructor\n   *\n   * \\param     sim         Metropolis simulation object\n   * \\param     sg          Function for generating a seed\n   * \\return                Copy\n   */\n  metropolis(const metropolis &sim, seed_gen sg = _default_seed_gen) \n    : _molecular_ids(sim._molecular_ids), _positions(sim._positions), \n      _edge_lengths(sim._edge_lengths), _V(sim._V), _potentials(sim._potentials),\n      _T(sim._T), _kB(sim._kB), _beta(sim._beta), _m(sim._m), _bc(sim._bc),\n      _eps_dist(0.0, 1.0), _choice_dist(0, sim._molecular_ids.size()-1), \n      _tmg(sim._tmg), _acc(sim._acc), \n      _parallel_callbacks(sim._parallel_callbacks), \n      _sequential_callbacks(sim._sequential_callbacks), _step(sim._step),\n      _dx(sim._dx), _choice(sim._choice), _dU(sim._dU), _U(sim._U), _eps(sim._eps),\n      _accepted(sim._accepted) { _rng.seed(sg()); }\n\n  /*! \\brief Assignment operator\n   *\n   * \\param     rhs     Metropolis simulation object\n   * \\return            Self\n   */\n  metropolis operator=(const metropolis &rhs); \n\n  /*! \\brief Update the (cached) system energy\n   */\n  void update_U();\n\n  /*! \\brief Get number of molecules\n   *\n   * \\return      Number of molecules\n   */\n  inline auto N() const { return _molecular_ids.size(); }\n\n  /*! \\brief Get number of dimensions\n   *\n   * \\return      Number of dimensions\n   */\n  inline auto D() const { return _positions.n_rows; }\n\n  /*! \\brief Get molecular ids\n   *\n   * \\return      Container of molecular ids\n   */\n  inline const auto &molecular_ids() const { return _molecular_ids; }\n\n  /*! \\brief Get molecular positions\n   *\n   * \\return      Molecular positions\n   */\n  inline auto &positions() { return _positions; }\n  \n  /*! \\brief Get molecular positions\n   *\n   * \\return      Molecular positions\n   */\n  inline const auto &positions() const { return _positions; }\n\n  /*! \\brief Get Boltzmann's constant\n   *\n   * \\return      Boltzmann's constant\n   */\n  inline auto kB() const { return _kB; }\n\n  /*! \\brief Get temperature\n   *\n   * \\return      Temperature\n   */\n  inline auto T() const { return _T; }\n\n  /*! \\brief Get beta\n   *\n   * \\return      1 / kT\n   */\n  inline auto beta() const { return _beta; }\n\n  /*! \\brief Get distance between molecules\n   *\n   * \\param   r_i            Position of molecule i\n   * \\param   r_j            Position of molecule j\n   * \\param   edge_lengths   Edge lengths of simulation box\n   * \\return                 Distance\n   */\n  inline auto m(const arma::vec &r_i, const arma::vec &r_j, \n                const arma::vec &edge_lengths) const { \n    return std::get<1>(_m)(r_i, r_j, edge_lengths);\n  }\n\n  /*! \\brief Get relative position\n   *\n   * \\param   r_i            Position of molecule i\n   * \\param   r_j            Position of molecule j\n   * \\param   edge_lengths   Edge lengths of simulation box\n   * \\return                 Relative position\n   */\n  inline auto rij(const arma::vec &r_i, const arma::vec &r_j, \n                  const arma::vec &edge_lengths) const { \n    return std::get<0>(_m)(r_i, r_j, edge_lengths);\n  }\n\n  /*! \\brief Get edge lengths of simulation box\n   *\n   * \\return      Edge lengths\n   */\n  inline const auto &edge_lengths() const { return _edge_lengths; }\n\n  /*! \\brief Get volume of simulation box\n   *\n   * \\return      Volume\n   */\n  inline auto V() const { return _V; }\n\n  /*! \\brief Add a callback function\n   *\n   * \\param   cb    Callback function to add\n   */\n  inline void add_parallel_callback(const callback &cb) const { \n    _parallel_callbacks.push_back(cb); \n  }\n\n  /*! \\brief Add a callback function\n   *\n   * \\param   cb    Callback function to add\n   */\n  inline void add_sequential_callback(const callback &cb) const { \n    _sequential_callbacks.push_back(cb); \n  }\n\n  /*! \\brief Add a callback function to default container\n   *\n   * \\param   cb    Callback function to add\n   */\n  inline void add_callback(const callback &cb) const { \n    add_sequential_callback(cb); \n  }\n\n  /*! \\brief Add a stopping criterion\n   *\n   * \\param   sc    Stopping criterion\n   */\n  inline void add_stopping_criterion(const stopping_criterion &sc) const { \n    _stopping_criteria.push_back(sc); \n  }\n\n  /*! \\brief Clear all stopping criteria\n   */\n  inline void clear_stopping_criteria() const { \n    _stopping_criteria.clear(); \n  }\n\n  /*! \\brief Get current step\n   *\n   * \\return    Current step\n   */\n  inline auto step() const { return _step; }\n\n  /*! \\brief Molecular potentials accessor\n   *\n   * \\return    Molecular potentials\n   */\n  inline const auto &potentials() const { return _potentials; }\n\n  /*! \\brief Accessor for trial move\n   *\n   * \\return    Change in x for trial move\n   */\n  inline const auto &dx() const { return _dx; }\n\n  /*! \\brief Index of molecule that has been chosen to move\n   *\n   * \\return      Molecule number of ``chosen'' molecule\n   */\n  inline auto choice() const { return _choice; }\n\n  /*! \\brief Accessor for change in energy that results from the move\n   *\n   * \\return      Change in energy as a result of trial move\n   */\n  inline const auto &dU() const { return _dU; }\n  \n  /*! \\brief Accessor for the current system energy\n   *\n   * \\return      System energy\n   */\n  inline const auto &U() const { return _U; }\n\n  /*! \\brief Accessor for random number used to determine acceptance/rejection\n   *\n   * \\return      Epsilon such that epsilon < B results in accepting the move\n   */\n  inline const auto &eps() const { return _eps; }\n  \n  /*! \\brief Accessor for whether or not the trial move was accepted\n   *\n   * \\return      Answers: ``was the trial move accepted?''\n   */\n  inline const auto &accepted() const { return _accepted; }\n\n  /*! \\brief Run metropolis simulation\n   *\n   * \\param   nsteps    Number of steps to simulate\n   */\n  long unsigned simulate(const long unsigned nsteps);\n\n  /*! \\brief Set molecular positions\n   *\n   * \\param   new_positions   New position matrix\n   */\n  inline void set_positions(const arma::mat &new_positions) {\n    _positions = new_positions;\n    update_U();\n  }\n\n  /*! \\brief Set molecular position for molecule j\n   *\n   * \\param   new_x   New position\n   * \\param   j       Index of molecular to change\n   */\n  inline void set_positions(const arma::vec &new_x, const size_t j) {\n    _positions.col(j) = new_x;\n    update_U();\n  }\n\n  /*! \\brief Seed the random number generator\n   *\n   * \\param     sd      Seed\n   */\n  inline void seed(const unsigned sd) {\n    _rng.seed(sd);\n  }\n\n  /*! \\brief Reset number of steps\n   *\n   * \\param   step    Step number to set\n   */\n  inline void reset_step(const unsigned long step = 0) {\n    _step = step;\n  }\n\nprivate:\n  std::vector<molecular_id> _molecular_ids;\n  arma::mat _positions;\n  arma::vec _edge_lengths;\n  double _V;\n  std::vector<abstract_potential*> _potentials;\n  double _T;\n  double _kB;\n  double _beta;\n  metric _m;\n  bc _bc;\n  std::default_random_engine _rng;\n  std::uniform_real_distribution<double> _eps_dist;\n  std::uniform_int_distribution<size_t> _choice_dist;\n  trial_move_generator _tmg;\n  acc _acc;\n  mutable std::vector<callback> _parallel_callbacks;\n  mutable std::vector<callback> _sequential_callbacks;\n  mutable std::vector<stopping_criterion> _stopping_criteria;\n  long unsigned _step;\n\n  arma::vec _dx;\n  size_t _choice;\n  double _dU;\n  double _U;\n  double _eps;\n  bool _accepted;\n};\n\n} // namespace pauth\n\n#endif\n", "meta": {"hexsha": "6982e06a3a02ae371d757140f1b6e0d43f7d4e22", "size": 16116, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/metropolis.hpp", "max_stars_repo_name": "grasingerm/port-authority", "max_stars_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/metropolis.hpp", "max_issues_repo_name": "grasingerm/port-authority", "max_issues_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/metropolis.hpp", "max_forks_repo_name": "grasingerm/port-authority", "max_forks_repo_head_hexsha": "51db6b09d6a1545eafeaf6be037a23d47313c490", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7327586207, "max_line_length": 83, "alphanum_fraction": 0.6208116158, "num_tokens": 3832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4211485210718869}}
{"text": "/*\n * Copyright 2020 University of Liège\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"wAdjoint.h\"\n#include \"wProblem.h\"\n#include \"wMedium.h\"\n#include \"wAssign.h\"\n#include \"wFreestream.h\"\n#include \"wWake.h\"\n#include \"wBoundary.h\"\n#include \"wSolver.h\"\n\n#include \"wMshData.h\"\n#include \"wNode.h\"\n#include \"wElement.h\"\n#include \"wTag.h\"\n#include \"wCache.h\"\n#include \"wMem.h\"\n#include \"wResults.h\"\n#include \"wMshExport.h\"\n#include \"wSparseLu.h\"\n\n#include <Eigen/Sparse>\n\n#include <tbb/task_scheduler_init.h>\n#include <tbb/tbb.h>\n#include <tbb/parallel_do.h>\n#include <tbb/spin_mutex.h>\n\n#include <iomanip>\n\nusing namespace tbox;\nusing namespace flow;\n\n#define ANSI_COLOR_YELLOW \"\\x1b[1;33m\"\n#define ANSI_COLOR_RESET \"\\x1b[0m\"\n\n/**\n * @brief Initialize the adjoint solver\n * @authors Adrien Crovato\n */\nAdjoint::Adjoint(std::shared_ptr<Solver> _sol) : sol(_sol)\n{\n    // Default parameters\n    nthreads = sol->nthreads;\n    verbose = sol->verbose;\n\n    // Setup variables (unkwown and residual vectors)\n    lambdaL.resize(sol->pbl->msh->nodes.size(), 0.);\n    lambdaD.resize(sol->pbl->msh->nodes.size(), 0.);\n}\n\n/**\n * @brief Run the linear solver\n *\n * Solve the adjoint steady transonic Full Potential Equation\n * i.e. computes sensitivites for lift and drag cost functions\n * @authors Adrien Crovato\n */\nvoid Adjoint::run()\n{\n    // Init\n    tbb::task_scheduler_init init(nthreads);\n\n    // Display solver parameters\n    std::cout << \"--- Adjoint solver ---\\n\"\n              << \"Number of threads: \" << nthreads << \"\\n\"\n              << std::endl;\n    // Map solution vectors\n    Eigen::Map<Eigen::VectorXd> lambdaL_(lambdaL.data(), lambdaL.size()), lambdaD_(lambdaD.data(), lambdaD.size());\n    // build SoE\n    Eigen::SparseMatrix<double, Eigen::RowMajor> dR(sol->pbl->msh->nodes.size(), sol->pbl->msh->nodes.size());\n    buildDR(dR);\n    std::vector<double> dummyL(sol->pbl->msh->nodes.size()), dummyD(sol->pbl->msh->nodes.size()); // dummy bs vector\n    Eigen::Map<Eigen::VectorXd> dL_(dummyL.data(), dummyL.size()), dD_(dummyD.data(), dummyD.size());\n    buildDI(dL_, dD_);\n\n    // Setup linear solver and solve linear SoE dR {lambdaL, lambdaD} = {dL, dD}\n    SparseLu lu;\n    lu.compute(dR, dL_, lambdaL_);\n    lu.compute(dR, dD_, lambdaD_);\n\n    // Check residual\n    Eigen::VectorXd rLambdaL = dR * lambdaL_ - dL_;\n    Eigen::VectorXd rLambdaD = dR * lambdaD_ - dD_;\n\n    std::cout << std::setw(8) << \"L_Iter\" << std::setw(15) << \"Sens[lambdaL]\" << std::setw(15) << \"Sens[lambdaD]\"\n              << std::setw(15) << \"Res[lambdaL]\" << std::setw(15) << \"Res[lambdaD]\" << std::endl;\n    std::cout << std::fixed << std::setprecision(5);\n    std::cout << std::setw(8) << 0 << std::setw(15) << lambdaL_.norm() << std::setw(15) << lambdaD_.norm()\n              << std::setw(15) << log10(rLambdaL.norm()) << std::setw(15) << log10(rLambdaD.norm()) << std::endl;\n\n    std::cout << ANSI_COLOR_YELLOW << \"Warning: the adjoint solver is experimental and has not been validated!\\n\"\n              << ANSI_COLOR_RESET << std::endl;\n}\n\n/**\n * @brief Build the Jacobian matrix\n * @authors Adrien Crovato\n * @todo Refactor, this is heavily copy-pasted from Newton::buildJ\n */\nvoid Adjoint::buildDR(Eigen::SparseMatrix<double, Eigen::RowMajor> &dR)\n{\n    // Multithread\n    tbb::spin_mutex mutex;\n\n    // List of triplets to build Jacobian matrix\n    std::deque<Eigen::Triplet<double>> T;\n\n    // Full Potential Equation with upwind bias: analytical derivatives\n    auto fluid = sol->pbl->medium;\n    tbb::parallel_do(fluid->adjMap.begin(), fluid->adjMap.end(), [&](std::pair<Element *, std::vector<Element *>> p) {\n        // Current element\n        Element *e = p.first;\n        // Upwind element\n        Element *eU = p.second[0];\n\n        // Subsonic contribution (drho*grad_phi*grad_psi + rho*grad_phi*grad_psi)\n        Eigen::MatrixXd Ae1 = e->buildDK(sol->phi, fluid->rho);\n        Eigen::MatrixXd Ae2 = e->buildK(sol->phi, fluid->rho);\n        // Supersonic contribution\n        double mCOv = 0.95; // solver should be converged, so we set the lowest numerical viscosity\n        double muCv = 1.0;\n        double mach = fluid->mach.eval(*e, sol->phi, 0);\n        if (mach > mCOv)\n        {\n            // switching function and derivative\n            double mu = muCv * (1 - (mCOv * mCOv) / (mach * mach));\n            double dmu = 2 * muCv * mCOv * mCOv / (mach * mach * mach);\n\n            // scale 1st and 2nd terms\n            Ae1 *= 1 - mu;\n            Ae2 *= 1 - mu;\n\n            // 3rd term (mu*drhoU*grad_phi*grad_psi)\n            Eigen::MatrixXd Ae3 = mu * fluid->rho.evalD(*eU, sol->phi, 0) * e->buildDs(sol->phi, Fct0C(1.)) *\n                                  eU->computeGrad(sol->phi, 0).transpose() * eU->getVCache().getDsf(0);\n\n            // 4th term (mu*rhoU*grad_phi*grad_psi)\n            Eigen::MatrixXd Ae4 = mu * fluid->rho.eval(*eU, sol->phi, 0) * e->buildK(sol->phi, Fct0C(1.));\n\n            // 5th term dmu*(rhoU-rho)*grad_phi*grad_psi\n            Eigen::MatrixXd Ae5 = dmu * (fluid->rho.eval(*eU, sol->phi, 0) - fluid->rho.eval(*e, sol->phi, 0)) *\n                                  e->buildDK(sol->phi, fluid->mach);\n\n            // Assembly (supersonic)\n            tbb::spin_mutex::scoped_lock lock(mutex);\n            for (size_t ii = 0; ii < e->nodes.size(); ++ii)\n            {\n                Node *nodi = e->nodes[ii];\n                for (size_t jj = 0; jj < e->nodes.size(); ++jj)\n                {\n                    Node *nodj = e->nodes[jj];\n                    T.push_back(Eigen::Triplet<double>(nodi->row, nodj->row, Ae4(ii, jj) + Ae5(ii, jj)));\n                }\n                for (size_t jj = 0; jj < eU->nodes.size(); ++jj)\n                {\n                    Node *nodj = eU->nodes[jj];\n                    T.push_back(Eigen::Triplet<double>(nodi->row, nodj->row, Ae3(ii, jj)));\n                }\n            }\n        }\n        // Assembly (subsonic)\n        tbb::spin_mutex::scoped_lock lock(mutex);\n        for (size_t ii = 0; ii < e->nodes.size(); ++ii)\n        {\n            Node *nodi = e->nodes[ii];\n            for (size_t jj = 0; jj < e->nodes.size(); ++jj)\n            {\n                Node *nodj = e->nodes[jj];\n                T.push_back(Eigen::Triplet<double>(nodi->row, nodj->row, Ae1(ii, jj) + Ae2(ii, jj)));\n            }\n        }\n    });\n    // Apply wake BCs for adjoint problem\n    for (auto wake : sol->pbl->wBCs)\n    {\n        tbb::parallel_do(wake->wEle.begin(), wake->wEle.end(), [&](WakeElement *we) {\n            Eigen::MatrixXd Kupup(we->nColUp, we->nRow);\n            Eigen::MatrixXd Kuplw(we->nColUp, we->nRow);\n            Eigen::MatrixXd Klwup(we->nColLw, we->nRow);\n            Eigen::MatrixXd Klwlw(we->nColLw, we->nRow);\n            buildWake(we, Kupup, Kuplw, Klwup, Klwlw);\n            // Assembly\n            tbb::spin_mutex::scoped_lock lock(mutex);\n            for (size_t ii = 0; ii < we->nColUp; ++ii)\n            {\n                Node *nodi = we->volUpE->nodes[ii];\n                for (size_t jj = 0; jj < we->nRow; ++jj)\n                {\n                    Node *nodj = we->surUpE->nodes[jj];\n                    T.push_back(Eigen::Triplet<double>(nodi->row, nodj->row, 2 * Kupup(ii, jj)));\n                    // dR.coeffRef(nodi->row, nodj->row) += 2 * Kupup(ii, jj);\n                    nodj = we->surLwE->nodes[jj];\n                    T.push_back(Eigen::Triplet<double>(nodi->row, nodj->row, Kuplw(ii, jj)));\n                    // dR.coeffRef(nodi->row, nodj->row) += Kuplw(ii, jj);\n                }\n            }\n            for (size_t ii = 0; ii < we->nColLw; ++ii)\n            {\n                Node *nodi = we->volLwE->nodes[ii];\n                for (size_t jj = 0; jj < we->nRow; ++jj)\n                {\n                    Node *nodj = we->surUpE->nodes[jj];\n                    // dR.coeffRef(nodi->row, nodj->row) -= 2 * Klwup(ii, jj);\n                    T.push_back(Eigen::Triplet<double>(nodi->row, nodj->row, -2 * Klwup(ii, jj)));\n                    nodj = we->surLwE->nodes[jj];\n                    // dR.coeffRef(nodi->row, nodj->row) -= Klwlw(ii, jj);\n                    T.push_back(Eigen::Triplet<double>(nodi->row, nodj->row, -Klwlw(ii, jj)));\n                }\n            }\n        });\n    }\n    // Build Jacobian matrix without BCs\n    dR.setFromTriplets(T.begin(), T.end());\n    // Apply Dirichlet BCs\n    for (auto dBC : sol->pbl->dBCs)\n    {\n        for (auto nod : dBC->nodes)\n        {\n            for (Eigen::SparseMatrix<double, Eigen::RowMajor>::InnerIterator it(dR, nod->row); it; ++it)\n            {\n                if (it.row() == it.col())\n                    it.valueRef() = 1.;\n                else\n                    it.valueRef() = 0.;\n            }\n        }\n    }\n    for (auto fBC : sol->pbl->fBCs)\n    {\n        for (auto e : fBC->tag->elems)\n        {\n            for (auto nod : e->nodes)\n            {\n                for (Eigen::SparseMatrix<double, Eigen::RowMajor>::InnerIterator it(dR, nod->row); it; ++it)\n                {\n                    if (it.row() == it.col())\n                        it.valueRef() = 1.;\n                    else\n                        it.valueRef() = 0.;\n                }\n            }\n        }\n    }\n    // Transpose\n    dR.transpose();\n    // Clean matrix and turn to compressed row format\n    dR.prune(0.);\n    dR.makeCompressed();\n\n    if (verbose)\n        std::cout << \"J (\" << dR.rows() << \",\" << dR.cols() << \") nnz=\" << dR.nonZeros() << \"\\n\";\n}\n\n/**\n * @brief Build the derivatives of the cost functions\n * @authors Adrien Crovato\n * @todo Refactor, to be checked\n */\nvoid Adjoint::buildDI(Eigen::Map<Eigen::VectorXd> &dL, Eigen::Map<Eigen::VectorXd> &dD)\n{\n    // Multithread\n    tbb::spin_mutex mutex;\n\n    // Derivative of lift and drag\n    for (auto sur : sol->pbl->bnd)\n    {\n        tbb::parallel_do(sur->groups[0]->tag->elems.begin(), sur->groups[0]->tag->elems.end(), [&](Element *e) {\n            // Build flux factor\n            Element *eV = sur->svMap.at(e);\n            Eigen::RowVectorXd be(eV->nodes.size());\n            buildBoundary(e, eV, be);\n            // Compute scaling factor\n            Eigen::Vector3d Vi(0., 0., 0.);\n            Vi(0) = -sin(sol->pbl->alpha);\n            Vi(sol->pbl->nDim - 1) = cos(sol->pbl->alpha);\n            double factorL = -1 / sol->pbl->S_ref * sol->pbl->medium->cP.evalD(*eV, sol->phi, 0) * e->normal().dot(Vi);\n            Vi(0) = cos(sol->pbl->alpha);\n            Vi(sol->pbl->nDim - 1) = sin(sol->pbl->alpha);\n            double factorD = -1 / sol->pbl->S_ref * sol->pbl->medium->cP.evalD(*eV, sol->phi, 0) * e->normal().dot(Vi);\n\n            // Assembly\n            tbb::spin_mutex::scoped_lock lock(mutex);\n            for (size_t ii = 0; ii < eV->nodes.size(); ++ii)\n            {\n                Node *nodi = eV->nodes[ii];\n                dL(nodi->row) += factorL * be(ii);\n                dD(nodi->row) += factorD * be(ii);\n            }\n        });\n    }\n    // Apply Dirichlet BCs, adjoint solution vanishes at infinity\n    for (auto dBC : sol->pbl->dBCs)\n    {\n        for (auto nod : dBC->nodes)\n        {\n            dL(nod->row) = 0.;\n            dD(nod->row) = 0.;\n        }\n    }\n    for (auto fBC : sol->pbl->fBCs)\n    {\n        for (auto e : fBC->tag->elems)\n        {\n            for (auto nod : e->nodes)\n            {\n                dL(nod->row) = 0.;\n                dD(nod->row) = 0.;\n            }\n        }\n    }\n\n    if (verbose)\n    {\n        std::cout << \"dL (\" << dL.size() << \")\\n\";\n        std::cout << \"dD (\" << dD.size() << \")\\n\";\n    }\n}\n\n/**\n * @brief Build the boundary contribution for the adjoint equation\n * @authors Adrien Crovato\n * @todo Refactor, to be checked and moved to Boundary::buildAdjNs()\n */\nvoid Adjoint::buildBoundary(Element *&e, Element *&eV, Eigen::RowVectorXd &be)\n{\n    // Get shape functions\n    Eigen::MatrixXd const &volDff = eV->getVCache().getDsf(0);\n    // Get Jacobian\n    Mem &surMem = e->getVMem();\n    Mem &volMem = eV->getVMem();\n    // b = V*[inv(J)*dN]\n    be = eV->computeGrad(sol->phi, 0).transpose() * volMem.getJinv(0) * volDff * surMem.getVol();\n}\n\n/**\n * @brief Build the wake contribution for the adjoint equation\n * @authors Adrien Crovato\n * @todo Refactor, to be checked and moved to WakeElement::buildAdjNK()\n */\nvoid Adjoint::buildWake(WakeElement *&we, Eigen::MatrixXd &Kupup, Eigen::MatrixXd &Kuplw, Eigen::MatrixXd &Klwup,\n                        Eigen::MatrixXd &Klwlw)\n{\n    // Get shape functions and Gauss points\n    Cache &surCacheUp = we->surUpE->getVCache();\n    Gauss &surGaussUp = surCacheUp.getVGauss();\n    Cache &surCacheLw = we->surLwE->getVCache();\n    Gauss &surGaussLw = surCacheLw.getVGauss();\n    Eigen::MatrixXd const &volUpDff = we->volUpE->getVCache().getDsf(0);\n    Eigen::MatrixXd const &volLwDff = we->volLwE->getVCache().getDsf(0);\n    // Get Jacobian\n    Mem &surMemUp = we->surUpE->getVMem();\n    Mem &surMemLw = we->surLwE->getVMem();\n    Eigen::MatrixXd const &volUpJ = we->volUpE->getVMem().getJinv(0);\n    Eigen::MatrixXd const &volLwJ = we->volLwE->getVMem().getJinv(0);\n    // Reset matrices\n    Kupup = Eigen::MatrixXd::Zero(we->nColUp, we->nRow);\n    Kuplw = Eigen::MatrixXd::Zero(we->nColUp, we->nRow);\n    Klwup = Eigen::MatrixXd::Zero(we->nColLw, we->nRow);\n    Klwlw = Eigen::MatrixXd::Zero(we->nColLw, we->nRow);\n\n    // unit normal\n    Eigen::VectorXd nUp = Eigen::VectorXd::Zero(sol->pbl->nDim);\n    Eigen::VectorXd nLw = Eigen::VectorXd::Zero(sol->pbl->nDim);\n    nUp(0) = we->surUpE->normal()(0);\n    nUp(sol->pbl->nDim - 1) = we->surUpE->normal()(sol->pbl->nDim - 1);\n    nLw(0) = we->surLwE->normal()(0);\n    nLw(sol->pbl->nDim - 1) = we->surLwE->normal()(sol->pbl->nDim - 1);\n    // intermediate vectors\n    Eigen::VectorXd nJdNUp(we->nColUp);\n    Eigen::VectorXd nJdNLw(we->nColLw);\n    Eigen::VectorXd VJdNUp(we->nColUp);\n    Eigen::VectorXd VJdNLw(we->nColLw);\n    nJdNUp = volUpDff * volUpJ.transpose() * nUp;\n    nJdNLw = volLwDff * volLwJ.transpose() * nLw;\n    VJdNUp = volUpDff * volUpJ.transpose() * we->volUpE->computeGrad(sol->phi, 0);\n    VJdNLw = volLwDff * volLwJ.transpose() * we->volLwE->computeGrad(sol->phi, 0);\n\n    // Build\n    /* @todo assemble on contributing nodes for lower surfaces => nRow <- we->surE->nodes.size() */\n    for (size_t k = 0; k < surGaussUp.getN(); ++k)\n    {\n        // N\n        Eigen::RowVectorXd Nup = surCacheUp.getSf(k).transpose();\n        Eigen::RowVectorXd Nlw = surCacheLw.getSf(k).transpose();\n        // K = K + N*VJdN*w*dtm\n        Kupup += VJdNUp * Nup * surGaussUp.getW(k) * surMemUp.getDetJ(k);\n        Klwup += VJdNLw * Nup * surGaussUp.getW(k) * surMemUp.getDetJ(k);\n        // K = K + N*nJdN*w*dtm\n        Kuplw += nJdNUp * Nlw * surGaussLw.getW(k) * surMemLw.getDetJ(k);\n        Klwlw += nJdNLw * Nlw * surGaussLw.getW(k) * surMemLw.getDetJ(k);\n    }\n}\n\n/**\n * @brief Write the results\n * @authors Adrien Crovato\n */\nvoid Adjoint::save(int n, std::shared_ptr<MshExport> mshWriter)\n{\n    // Write files\n    std::cout << \"Saving files... \" << std::endl;\n    // setup results\n    Results results;\n    results.scalars_at_nodes[\"lambdaL\"] = &lambdaL;\n    results.scalars_at_nodes[\"lambdaD\"] = &lambdaD;\n    // save (all mesh and boundary surface)\n    if (n > 0)\n    {\n        mshWriter->save(sol->pbl->msh->name + \"_adjoint_\" + std::to_string(n), results);\n        for (auto sur : sol->pbl->bnd)\n            sur->save(sur->groups[0]->tag->name + \"adjoint_\" + std::to_string(n), results);\n    }\n    else\n    {\n        mshWriter->save(sol->pbl->msh->name + \"_adjoint\", results);\n        for (auto sur : sol->pbl->bnd)\n            sur->save(sur->groups[0]->tag->name + \"_adjoint\", results);\n    }\n}\n\nvoid Adjoint::write(std::ostream &out) const\n{\n    out << \"flow::Adjoint\"\n        << \"\\n\";\n}\n", "meta": {"hexsha": "ee9c88dbf5701de97aa4ae19037f5a56a3e9f724", "size": 16250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sandbox/clangformat/wAdjoint.cpp", "max_stars_repo_name": "rboman/progs", "max_stars_repo_head_hexsha": "c60b4e0487d01ccd007bcba79d1548ebe1685655", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-12T13:26:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T16:14:53.000Z", "max_issues_repo_path": "sandbox/clangformat/wAdjoint.cpp", "max_issues_repo_name": "rboman/progs", "max_issues_repo_head_hexsha": "c60b4e0487d01ccd007bcba79d1548ebe1685655", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-01T07:08:46.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-28T07:32:42.000Z", "max_forks_repo_path": "sandbox/clangformat/wAdjoint.cpp", "max_forks_repo_name": "rboman/progs", "max_forks_repo_head_hexsha": "c60b4e0487d01ccd007bcba79d1548ebe1685655", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T13:13:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-13T20:08:15.000Z", "avg_line_length": 36.8480725624, "max_line_length": 119, "alphanum_fraction": 0.5502769231, "num_tokens": 4992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4211485210718869}}
{"text": "#include <iostream>\n#include <boost/units/unit.hpp>\n#include <boost/units/make_scaled_unit.hpp>\n#include <boost/units/systems/si.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace boost::units;\nusing namespace boost::units::si;\n\nint main()\n{\n    typedef make_scaled_unit<si::length, scale<10, static_rational<-2>>>::type cm;\n    quantity<cm> d(2.0 * si::meter);\n    quantity<si::time> t(100.0 * si::seconds);\n    quantity<si::velocity> x(d / t);\n\n    cout << d.value() << \"cm\" << endl;\n    cout << t.value() << \"sec\" << endl;\n    cout << x.value() << \"m/sec\" << endl;\n}\n\n/*\n200cm\n100sec\n0.02m/sec\n*/", "meta": {"hexsha": "a016ebb6749366c00b0ec0aad477220c417088e2", "size": 614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "various/boost_examples/units.cpp", "max_stars_repo_name": "chgogos/oop", "max_stars_repo_head_hexsha": "3b0e6bbd29a76f863611e18d082913f080b1b571", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-04-23T13:45:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T18:26:47.000Z", "max_issues_repo_path": "various/boost_examples/units.cpp", "max_issues_repo_name": "chgogos/oop", "max_issues_repo_head_hexsha": "3b0e6bbd29a76f863611e18d082913f080b1b571", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "various/boost_examples/units.cpp", "max_forks_repo_name": "chgogos/oop", "max_forks_repo_head_hexsha": "3b0e6bbd29a76f863611e18d082913f080b1b571", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-09-01T15:17:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-13T20:31:36.000Z", "avg_line_length": 22.7407407407, "max_line_length": 82, "alphanum_fraction": 0.6433224756, "num_tokens": 183, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4211192283271316}}
{"text": "#include <polyfem/SpectralBasis2d.hpp>\n\n#include <polyfem/QuadraticBSpline2d.hpp>\n#include <polyfem/QuadQuadrature.hpp>\n#include <polyfem/MeshNodes.hpp>\n\n#include <polyfem/LinearSolver.hpp>\n#include <polyfem/FEBasis2d.hpp>\n#include <polyfem/Types.hpp>\n\n#include <polyfem/Common.hpp>\n\n#include <Eigen/Sparse>\n\n#include <cassert>\n#include <iostream>\n#include <vector>\n#include <array>\n#include <map>\n\n\nnamespace polyfem\n{\n    using namespace Eigen;\n\n    namespace\n    {\n        void basis(const Eigen::MatrixXd &uv, const int n, const int m, Eigen::MatrixXd &result)\n        {\n            const int n_pts = int(uv.rows());\n            assert(uv.cols() == 2);\n\n            result.resize(n_pts, 1);\n\n            for(int i = 0; i < n_pts; ++i)\n                result(i) = sin(n*M_PI*uv(i,0)) * sin(m*M_PI*uv(i,1));\n        }\n\n\n        void derivative(const Eigen::MatrixXd &uv, const int n, const int m, Eigen::MatrixXd &result)\n        {\n            const int n_pts = int(uv.rows());\n            assert(uv.cols() == 2);\n\n            result.resize(n_pts, 2);\n\n            for(int i = 0; i < n_pts; ++i)\n            {\n                const double u = uv(i,0);\n                const double v = uv(i,1);\n\n                result(i,0) = cos(n*M_PI*uv(i,0)) * sin(m*M_PI*uv(i,1));\n                result(i,1) = sin(n*M_PI*uv(i,0)) * cos(m*M_PI*uv(i,1));\n            }\n        }\n    }\n\n    int SpectralBasis2d::build_bases(\n        const Mesh2D &mesh,\n        const int quadrature_order,\n        const int order,\n        std::vector< ElementBases > &bases,\n        std::vector< ElementBases > &gbases,\n        std::vector< LocalBoundary > &local_boundary)\n    {\n        bases.resize(1);\n        ElementBases &b = bases.front();\n        b.has_parameterization = false;\n\n        const int n_bases = order * order;\n\n        b.bases.resize(n_bases);\n        b.set_quadrature([quadrature_order](Quadrature &quad){\n            QuadQuadrature quad_quadrature;\n            quad_quadrature.get_quadrature(quadrature_order, quad);\n        });\n\n\n        for (int i = 0; i < order; ++i) {\n            for (int j = 0; j < order; ++j) {\n                const int global_index = order*i + j;\n                assert(global_index < n_bases);\n\n                b.bases[global_index].init(-3, global_index, j, Eigen::MatrixXd::Zero(1, 2));\n                b.bases[global_index].set_basis([i, j](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { basis(uv, i, j, val); });\n                b.bases[global_index].set_grad([i, j](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { derivative(uv, i, j, val); });\n            }\n        }\n\n\n        // gbases.resize(1);\n        // ElementBases &gb = bases.front();\n        // gb.bases.resize(n_bases);\n        // gb.set_quadrature([quadrature_order](Quadrature &quad){\n        //     QuadQuadrature quad_quadrature;\n        //     quad_quadrature.get_quadrature(quadrature_order, quad);\n        // });\n        // b.has_parameterization = false;\n\n        // for (int j = 0; j < n_bases; ++j) {\n        //     const int global_index = j;\n\n        //     gb.bases[j].init(global_index, j, Eigen::Vector2d(0,0));\n        //     gb.bases[j].set_basis([j](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { basis(uv, j, val); });\n        //     gb.bases[j].set_grad([j](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { derivative(uv, j, val); });\n        // }\n\n\n        return n_bases;\n    }\n\n}\n", "meta": {"hexsha": "1cd81c26e55b6195901f8505bf03dea4f29c16a1", "size": 3402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/basis/SpectralBasis2d.cpp", "max_stars_repo_name": "ldXiao/polyfem", "max_stars_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/basis/SpectralBasis2d.cpp", "max_issues_repo_name": "ldXiao/polyfem", "max_issues_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/basis/SpectralBasis2d.cpp", "max_forks_repo_name": "ldXiao/polyfem", "max_forks_repo_head_hexsha": "d4103af16979ff67d461a9ebe46a14bbc4dc8c7c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1061946903, "max_line_length": 135, "alphanum_fraction": 0.5511463845, "num_tokens": 935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4211192283271316}}
{"text": "\n/******************************************************************************\n\n  Dual-point generalized Hough Transform for 2D object recognition.\n\n  Copyright (c) 2013\n  Dzmitry Hlindzich <hlindzich@gmail.com>\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions\n  are met:\n  1.  Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n  2.  Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and/or other materials provided with the distribution.\n\n  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND\n  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n  ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n  SUCH DAMAGE.\n\n*******************************************************************************/\n\n#ifndef DPG_HOUGH_TRANSFORM_HPP_55B0255B_E6C8_4302_9114_D1B684CD3419_\n#define DPG_HOUGH_TRANSFORM_HPP_55B0255B_E6C8_4302_9114_D1B684CD3419_\n\n#include <utility>\n#include <vector>\n#include <list>\n#include <set>\n#include <cmath>\n#include <algorithm>\n#include <complex>\n#include <boost/noncopyable.hpp>\n#include <boost/assert.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"bo/config.hpp\"\n#include \"bo/core/vector.hpp\"\n#include \"bo/math/blas_extensions.hpp\"\n#include \"bo/core/raw_image_2d.hpp\"\n#include \"bo/math/topology.hpp\"\n#include \"bo/math/blas_extensions.hpp\"\n#include \"bo/surfaces/convex_hull_3d.hpp\"\n\nnamespace bo {\nnamespace recognition {\n\nnamespace detail {\n\n// A 4-dimensional hyperplane defined by a point located\n// on this plane and the plane's normal vector.\ntemplate <typename RealType>\nclass Hyperplane4D\n{\npublic:\n    typedef Vector<RealType, 4> Point4D;\n\n    Hyperplane4D(const Point4D &point, const Point4D &normal)\n        : point_(point), kEpsilon(0.0001)\n    {\n        Point4D n = normal / normal.euclidean_norm();\n        normal_ = n;\n\n        // Decomposition matrix (inverse of the base one).\n        m_ = math::matrix<RealType>(4, 4);\n        m_(0, 0) =  n[3]; m_(0, 1) =  n[2]; m_(0, 2) = -n[1]; m_(0, 3) = -n[0];\n        m_(1, 0) = -n[2]; m_(1, 1) =  n[3]; m_(1, 2) =  n[0]; m_(1, 3) = -n[1];\n        m_(2, 0) =  n[1]; m_(2, 1) = -n[0]; m_(2, 2) =  n[3]; m_(2, 3) = -n[2];\n        m_(3, 0) =  n[0]; m_(3, 1) =  n[1]; m_(3, 2) =  n[2]; m_(3, 3) =  n[3];\n    }\n\n    inline\n    const Point4D& point() const\n    { return point_; }\n\n    inline\n    const Point4D& normal() const\n    { return normal_; }\n\n    // Computes intersection of a line defined by two 4-dimensional points\n    // with the hyperplane. Considers the intersection as a linear coordinate 't'\n    // such that the intersection point is calculated as P = q1 + t * (q2 - q1).\n    // If the line intersects with the hyperplane, returns true and updates the\n    // function parameter 't'. Otherwise returns false.\n    bool intersect(const Point4D& q1, const Point4D& q2, RealType& t)\n    {\n        Point4D q1p = point_ - q1;\n        Point4D e = q2 - q1;\n        RealType dot1 = q1p * normal_;\n\n        RealType e_norm = e.euclidean_norm();\n        // This case is needed for continuity, when two very close points\n        // both belong to the hyperplane.\n        if (e_norm < kEpsilon)\n        {\n            if (dot1 < kEpsilon)\n            {\n                t = RealType(0);\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        RealType dot2 = e * normal_;\n\n        if (std::abs(dot2 / e_norm) > kEpsilon)\n        {\n            // If the line is not parallel to the hyperplane.\n            t = dot1 / dot2;\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }\n\n    // Computes the decomposition of the point in the hyperplane's\n    // coordinate system defined by the decomposition matrix.\n    Point4D decompose(const Point4D& p)\n    {\n        Point4D q = p - point_;\n\n        math::matrix<RealType> v(4, 1);\n        v(0, 0) = q[0];\n        v(1, 0) = q[1];\n        v(2, 0) = q[2];\n        v(3, 0) = q[3];\n\n        // Compute decomposition in the projection basis.\n        v = math::prod(m_, v);\n\n        return Point4D(v(0, 0), v(1, 0), v(2, 0), v(3, 0));\n    }\n\nprivate:\n\n    Point4D point_;\n    Point4D normal_;\n\n    // Hyperplane's decomposition matrix.\n    math::matrix<RealType> m_;\n\n    const RealType kEpsilon;\n};\n\ntemplate <typename RealType>\nclass Space\n{\npublic:\n    typedef Vector<RealType, 4> Point4D;\n    typedef std::vector<Point4D> Points4D;\n    typedef Vector<std::size_t, 4> Size4D;\n    typedef std::pair<Point4D, Point4D> Box4D;\n    typedef bo::math::OrthotopeTopology<RealType, 4> Geometry;\n    typedef detail::Hyperplane4D<RealType> Hyperplane;\n\n    // A line in 4D is defined by any point located\n    // on this line and its directional vector.\n    struct Line4D\n    {\n        Line4D()\n            : point(Point4D(0)), direction(Point4D(0))\n        { }\n\n        Line4D(const Point4D &_point, const Point4D &_direction)\n            : point(_point), direction(_direction)\n        { }\n\n        Point4D point;\n        Point4D direction;\n    };\n\n    typedef Vector<RealType, 2> SegmentCoordinates;\n    typedef std::vector<Space> Spaces;\n\n    // A segment in 4D is modelled by a 4D line and the\n    // coordinates of two points on this line\n    // relatively to the line's direction vector.\n    typedef std::pair<Line4D, SegmentCoordinates> Segment4D;\n\n    Space(const Box4D &box = Box4D(Point4D(0, 0, 0, 0), Point4D(0, 0, 0, 0)),\n          const Size4D &divisions_per_dimension = Size4D(2, 2, 2, 2),\n          std::size_t max_resolution_level = 1,\n          std::size_t cell_resolution_increment = 1,\n          std::size_t resolution_level = 0):\n        box_(box),  divisions_per_dimension_(divisions_per_dimension),\n        max_resolution_level_(max_resolution_level), resolution_level_(resolution_level),\n        votes_(0)\n    {\n        BOOST_ASSERT(resolution_level_ <= max_resolution_level_);\n\n        // Adjust the cell resolution increment.\n        if (resolution_level_ + cell_resolution_increment > max_resolution_level_)\n        {\n            cell_resolution_increment_ = max_resolution_level_ - resolution_level_;\n        }\n        else\n        {\n            cell_resolution_increment_ =  cell_resolution_increment;\n        }\n\n        // Compute the size of cells used for vote calculation.\n        for (std::size_t i = 0; i < 4; ++i)\n        {\n            std::size_t cells_in_dimension = static_cast<std::size_t>(\n                std::pow(RealType(divisions_per_dimension_[i]),\n                         RealType(max_resolution_level_) - RealType(resolution_level_)));\n\n            cell_size_[i] = (box_.second[i] - box_.first[i]) /  cells_in_dimension;\n        }\n\n        min_cell_volume_ = std::pow((cell_size_[0] + cell_size_[1] + cell_size_[2] +\n                cell_size_[3]) / 4, 3);\n\n        // Compute the number of probabilistic elements used for the subdivision policy.\n        prob_element_count_ = 1;\n        for (std::size_t i = 0; i < 4; ++i)\n        {\n            std::size_t prob_elements_in_dimension = static_cast<std::size_t>(\n                std::pow(RealType(divisions_per_dimension_[i]), RealType(cell_resolution_increment_)));\n\n            prob_element_count_ *= prob_elements_in_dimension;\n        }\n    }\n\n    // Subdivides the space.\n    void subdivide()\n    {\n        subspaces_.clear();\n\n        std::size_t subdivision_count_ = divisions_per_dimension_[0] * divisions_per_dimension_[1] *\n                                         divisions_per_dimension_[2] * divisions_per_dimension_[3];\n\n        subspaces_.reserve(subdivision_count_);\n\n        Point4D sizes4d = box_.second - box_.first;\n        Point4D steps4d = Point4D(sizes4d[0] / RealType(divisions_per_dimension_[0]),\n                                  sizes4d[1] / RealType(divisions_per_dimension_[1]),\n                                  sizes4d[2] / RealType(divisions_per_dimension_[2]),\n                                  sizes4d[3] / RealType(divisions_per_dimension_[3]));\n\n        for (std::size_t d0 = 0; d0 < divisions_per_dimension_[0]; ++d0)\n            for (std::size_t d1 = 0; d1 < divisions_per_dimension_[1]; ++d1)\n                for (std::size_t d2 = 0; d2 < divisions_per_dimension_[2]; ++d2)\n                    for (std::size_t d3 = 0; d3 < divisions_per_dimension_[3]; ++d3)\n                    {\n                        // Create a subspace.\n                        Point4D translation(d0 * steps4d[0], d1 * steps4d[1], d2 * steps4d[2],\n                                d3 * steps4d[3]);\n                        Box4D b(box_.first + translation, box_.first + translation + steps4d);\n                        Space s(b, divisions_per_dimension_, max_resolution_level_,\n                                cell_resolution_increment_, resolution_level_ + 1);\n\n                        subspaces_.push_back(s);\n                    }\n\n    }\n\n    inline Spaces& get_subspaces()\n    {\n        return subspaces_;\n    }\n\n    inline const Spaces& get_subspaces() const\n    {\n         return subspaces_;\n    }\n\n    inline const Box4D& get_bounding_box() const\n    {\n        return box_;\n    }\n\n    inline RealType get_votes() const\n    {\n        return votes_;\n    }\n\n    inline std::size_t get_prob_element_count() const\n    {\n        return prob_element_count_;\n    }\n\n    void reset_votes()\n    {\n        votes_ = 0;\n    }\n\n    inline std::size_t get_resolution_level() const\n    {\n        return resolution_level_;\n    }\n\n    inline std::size_t get_max_resolution_level() const\n    {\n        return max_resolution_level_;\n    }\n\n    inline Point4D get_mass_center() const\n    {\n        return (box_.first + box_.second) / 2;\n    }\n\n    void vote(Segment4D segment)\n    {\n        // The number of votes that the space receives in the result of the intersection\n        // equals to the lenght of the resulting segment.\n        // Compute the segment.\n        Point4D s = segment.first.direction * (segment.second[1] - segment.second[0]);\n\n        // Increase the votes.\n        // Continuous. Attention: has no effect if the intersection is in one point.\n        votes_ += s.euclidean_norm();\n    }\n\n    void vote_unit(const Segment4D &segment)\n    {\n        // Binary.\n        if (segment.second[0] > -std::numeric_limits<RealType>::max() &&\n            segment.second[0] < std::numeric_limits<RealType>::max())\n        {\n            votes_ += 1;\n        }\n    }\n\n    // Increases the number of votes on the number of intersection of the given segment\n    // with the grid defined by the space cell size.\n    void vote_descrete(const Segment4D &segment)\n    {\n        // We will accumulate the coordinates of intersections of the given segment\n        // with the grid of the given cell size.\n        std::set<RealType> intersections;\n\n        // Find coordinates of the intersection of the line with the space.\n        Segment4D base_seg = intersect(segment.first);\n\n\n        RealType t1_base = base_seg.second[0];\n        RealType t2_base = base_seg.second[1];\n        // Order.\n        order(t1_base, t2_base);\n\n        RealType t1 = segment.second[0];\n        RealType t2 = segment.second[1];\n        // Order.\n        order(t1, t2);\n\n        // Segment direction.\n        Point4D v = segment.first.direction;\n\n        // For each dimension define the coordinate step beetween two cells (dimension levels).\n        for (std::size_t d = 0; d < 4; ++d)\n        {\n            if (v[d] != 0)\n            // If it is zero, the segment does not intersect the levels of this dimension and\n            // we can skip further analysis.\n            {\n                RealType dt = std::abs(cell_size_[d] / v[d]);\n\n                // Accumulate all intersections of this dimension situated between the begin\n                // and the end of the segment. TODO: optimize it!\n                for (RealType t = t1_base + dt; t < t2_base; t += dt)\n                {\n                    if (t > t1 && t < t2)\n                        intersections.insert(t);\n                }\n            }\n        }\n\n        votes_ += intersections.size() + 1;\n    }\n\n    // Increases the votes on the number equal to the taxicab norm of the\n    // corresponding inner segment relatively to the space grid.\n    void vote_taxicab(const Segment4D &segment)\n    {\n        // If the segment is not zero.\n        if (segment.second[0] == segment.second[1])\n            return;\n\n        std::size_t taxicab_dst = 0;\n\n        // Local coordinate origin.\n        Point4D bot = box_.first;\n        Point4D top = box_.second;\n\n        // The end points of the segment.\n        Point4D p1 = segment.first.point + segment.first.direction * segment.second[0];\n        Point4D p2 = segment.first.point + segment.first.direction * segment.second[1];\n\n        // Segment direction.\n        Point4D v = segment.first.direction;\n\n        // For each dimension define the coordinate step beetween two cells (dimension levels).\n        for (std::size_t d = 0; d < 4; ++d)\n        {\n            if (v[d] != 0)\n            // If it is zero, the segment does not intersect the levels of this dimension and\n            // we can skip further analysis.\n            {\n                RealType proj1 = p1[d];\n                RealType proj2 = p2[d];\n                order(proj1, proj2);\n\n                order(bot[d], top[d]);\n\n                cut(proj1, bot[d], top[d]);\n                cut(proj2, bot[d], top[d]);\n\n                BOOST_ASSERT(proj1 >= bot[d] && proj2 >= bot[d]);\n\n                RealType block1 = std::floor((proj1 - bot[d]) / cell_size_[d]);\n                RealType block2 =  std::ceil((proj2 - bot[d]) / cell_size_[d]);\n\n                taxicab_dst += static_cast<std::size_t>(block2 - block1);\n            }\n        }\n\n        votes_ += taxicab_dst;\n    }\n\n    // Increases the votes on the number equal to the maximum (uniform) norm of the\n    // inner segment relatively to the space grid.\n    void vote_maxnorm(const Segment4D &segment)\n    {\n        // If the segment is not zero.\n        if (segment.second[0] == segment.second[1])\n            return;\n\n        std::size_t maximum_norm = 0;\n\n        // Local coordinate origin.\n        Point4D bot = box_.first;\n        Point4D top = box_.second;\n\n        // The end points of the segment.\n        Point4D p1 = segment.first.point + segment.first.direction * segment.second[0];\n        Point4D p2 = segment.first.point + segment.first.direction * segment.second[1];\n\n        // Segment direction.\n        Point4D v = segment.first.direction;\n\n        // For each dimension define the coordinate step beetween two cells (dimension levels).\n        for (std::size_t d = 0; d < 4; ++d)\n        {\n            if (v[d] != 0)\n            // If it is zero, the segment does not intersect the levels of this dimension and\n            // we can skip further analysis.\n            {\n                RealType proj1 = p1[d];\n                RealType proj2 = p2[d];\n                order(proj1, proj2);\n\n                order(bot[d], top[d]);\n\n                cut(proj1, bot[d], top[d]);\n                cut(proj2, bot[d], top[d]);\n\n                BOOST_ASSERT(proj1 >= bot[d] && proj2 >= bot[d]);\n\n                RealType block1 = std::floor((proj1 - bot[d]) / cell_size_[d]);\n                RealType block2 =  std::ceil((proj2 - bot[d]) / cell_size_[d]);\n\n                std::size_t dst = static_cast<std::size_t>(block2 - block1);\n\n                if (maximum_norm < dst)\n                    maximum_norm = dst;\n            }\n        }\n\n        votes_ += maximum_norm;\n    }\n\n    // Returns the result of intersection of the given segment with the space.\n    Segment4D intersect(Segment4D segment)\n    {\n        // Cut the segment in each of four dimensions.\n        for (std::size_t d = 0; d < 4; ++d)\n            cut_segment(segment, d, box_.first[d], box_.second[d]);\n\n        return segment;\n    }\n\n    // Returns the result of intersection (segment) of the given 4D line with the space.\n    Segment4D intersect(Line4D line)\n    {\n        // Create the \"infinite\" segment coordinates that models the whole line.\n        RealType mmax = std::numeric_limits<RealType>::max();\n        SegmentCoordinates coord(-mmax, mmax);\n\n        // Create the \"infinite\" segment.\n        Segment4D infinite_seg(line, coord);\n\n        return intersect(infinite_seg);\n    }\n\n    // Returns the points that define the polyhedron of the hyperplane-hyperrectangle\n    // intersection.\n    Points4D intersect(Hyperplane plane)\n    {\n        Points4D vertices;\n\n        Point4D d = box_.second - box_.first;\n\n        typename Geometry::Edges edges = Geometry::edges();\n\n        for (typename Geometry::Edges::const_iterator it = edges.begin();\n             it != edges.end(); ++it)\n        {\n            typename Geometry::Point e1 = it->first;\n            typename Geometry::Point e2 = it->second;\n\n            // Calculate the adjacent vertices of the box edges.\n            Point4D q1 = box_.first + Point4D(e1[0] * d[0], e1[1] * d[1],\n                                              e1[2] * d[2], e1[3] * d[3]);\n            Point4D q2 = box_.first + Point4D(e2[0] * d[0], e2[1] * d[1],\n                                              e2[2] * d[2], e2[3] * d[3]);\n\n            // Calculate intersection of the edge with the plane.\n            RealType t;\n            if (plane.intersect(q1, q2, t))\n            {\n                // Add the intersection point if it belongs to the edge.\n                if (t >= 0 && t <= 1)\n                {\n                    vertices.push_back(q1 + t * (q2 - q1));\n                }\n            }\n        }\n\n        return vertices;\n    }\n\n    RealType intersection_volume(Hyperplane plane)\n    {\n        RealType kEpsilon(0.001);\n\n        // The points of intersection with the plane in 4D.\n        Points4D vertices4 = intersect(plane);\n\n        // Container for projections.\n        typedef surfaces::IncrementalConvexHull3D<RealType> Hull;\n        typename Hull::Points3D vertices3;\n\n        // Project the vertices into 3D.\n        for (typename Points4D::const_iterator it = vertices4.begin();\n             it != vertices4.end(); ++it)\n        {\n            Point4D p = plane.decompose(*it);\n\n            // The vertex must lie in 3D!\n            BOOST_ASSERT(std::abs(p[3]) < kEpsilon);\n            BO_UNUSED(kEpsilon);\n\n            // Projection.\n            typename Hull::Point3D pr(p[0], p[1], p[2]);\n\n            vertices3.push_back(pr);\n        }\n\n        if(vertices3.size() > 3)\n        {\n            // Compute the convex hull and its volume.\n            Hull hull3d(vertices3);\n            return hull3d.get_volume();\n        }\n        else\n        {\n            return 0;\n        }\n    }\n\n    // The number of votes that the space receives is equal to the volume\n    // of the resulting hyperrectangle-hyperplane intersection.\n    void vote(Hyperplane plane)\n    {\n        RealType volume = intersection_volume(plane);\n\n        votes_ += volume;\n    }\n\n    // The number of votes that the space receives is equal to the number\n    // of the cells that the hyperrectangle-hyperplane intersection \"covers\".\n    void vote_descrete(Hyperplane plane)\n    {\n        RealType volume = intersection_volume(plane);\n\n        RealType vote = volume / min_cell_volume_;\n\n        votes_ += std::floor(vote) + 1;\n    }\n\n    void vote_unit(Hyperplane plane)\n    {\n        if (intersect(plane).size() > 0)\n            votes_ += 1;\n    }\n\nprivate:\n    Spaces subspaces_;\n    Box4D box_;\n    Size4D divisions_per_dimension_;\n    std::size_t max_resolution_level_;\n    std::size_t cell_resolution_increment_;\n    std::size_t resolution_level_;\n    RealType votes_;\n    Point4D cell_size_;\n    RealType min_cell_volume_;\n    std::size_t prob_element_count_;\n\n    // Cuts the segment in the given dimension according to two given levels.\n    void cut_segment(Segment4D &seg, std::size_t dimension, RealType level1, RealType level2)\n    {\n        // Sort the levels: level1 <= level2.\n        order(level1, level2);\n\n        // The origin point and the direction.\n        Point4D p = seg.first.point;\n        Point4D v = seg.first.direction;\n\n        // If the segment is parallel to the levels of this dimension.\n        if (v[dimension] == 0)\n        {\n             // If the origin is outside the levels, return infinite point.\n            if (p[dimension] > level2 || p[dimension] < level1)\n                seg.second[0] = seg.second[1] = std::numeric_limits<RealType>::max();\n\n            // Otherwise return the same segment.\n            return;\n        }\n\n        // Define the coordinates of the line instersection with the dimension levels.\n        RealType t1 = (level1 - p[dimension]) / v[dimension];\n        RealType t2 = (level2 - p[dimension]) / v[dimension];\n\n        // Sort the coordinates: t1 <= t2.\n        order(t1, t2);\n\n        // If the segments is outside the levels (less), move it in the negative\n        // infinite point.\n        if (seg.second[0] < t1 && seg.second[1] < t1)\n        {\n            seg.second[0] = seg.second[1] = -std::numeric_limits<RealType>::max();\n            return;\n        }\n\n        // If the segments is outside the levels (less), move it in the positive\n        // infinite point.\n        if (seg.second[0] > t2 && seg.second[1] > t2)\n        {\n            seg.second[0] = seg.second[1] = std::numeric_limits<RealType>::max();\n            return;\n        }\n\n        // Cut the segment.\n        for (int i = 0; i < 2; ++i)\n        {\n            if (seg.second[i] < t1)\n                seg.second[i] = t1;\n\n            if (seg.second[i] > t2)\n                seg.second[i] = t2;\n        }\n\n    }\n\n    inline void order(RealType &a, RealType &b)\n    {\n        if (a > b) std::swap(a, b);\n    }\n\n    inline void cut(RealType &x, RealType a, RealType b)\n    {\n        if (x < a)\n            x = a;\n        if (x > b)\n            x = b;\n    }\n};\n\n\ntemplate <typename RealType>\nclass SubdivisionPolicy\n{\npublic:\n    typedef Space<RealType> Space4D;\n\n    // Returns the minimal number of spaces (at the current resolution level) from\n    // the beginning of the given sorted collection such that occurrence of the\n    // subspaces (at the cell resolution level) with maximal number of votes is\n    // not less then the given probability p. Attention: the input collection of\n    // spaces must be sorted in descending order!\n    static std::size_t probabilistic(const typename Space4D::Spaces &spaces, RealType p)\n    {\n        typename Space4D::Spaces subcollection1;\n        typename Space4D::Spaces subcollection2 = spaces;\n\n        std::size_t n = 0;\n\n        // Find the minimal number of spaces that satisfy the probability constraint.\n        while (n < spaces.size() &&\n               p_max_value_in_subcollection(subcollection1, subcollection2) < p)\n        {\n            typename Space<RealType>::Spaces::iterator it = subcollection2.begin();\n\n            subcollection1.push_back(*it);\n            subcollection2.erase(it);\n            n = subcollection1.size();\n        }\n\n        return n;\n    }\n\n    // Computes the probability of the event that the maximal value of subcollection1 is greater\n    // than the maximal value from subcollection2.\n    static RealType p_max_value_in_subcollection(const typename Space4D::Spaces &subcollection1,\n                                                 const typename Space4D::Spaces &subcollection2)\n    {\n        // Compute the maximal vote in subcollection1.\n        std::size_t max_votes = 0;\n        for (typename Space4D::Spaces::const_iterator it = subcollection1.begin();\n             it != subcollection1.end(); ++it)\n        {\n            std::size_t votes = std::size_t(it->get_votes());\n            if (max_votes < votes)\n            {\n                max_votes = votes;\n            }\n        }\n\n        RealType p = 0;\n\n        // Compute the probability.\n        for (std::size_t t = 1; t <= max_votes; ++t)\n        {\n            RealType f1 = F_joint(subcollection1, t);\n            RealType f2 = F_joint(subcollection1, t - 1);\n            RealType f3 = F_joint(subcollection2, t - 1);\n\n            p += (f1 - f2) * f3;\n        }\n\n        return p;\n    }\n\n    // Joint distribution function for spaces.\n    static RealType F_joint(const typename Space4D::Spaces &spaces, std::size_t x)\n    {\n        if (spaces.size() == 0) return 0;\n\n        RealType f = 1;\n\n        for (typename Space4D::Spaces::const_iterator it = spaces.begin();\n             it != spaces.end(); ++it)\n        {\n            f *= F(std::size_t(it->get_votes()), it->get_prob_element_count(), x);\n        }\n\n        return f;\n    }\n\n    // Distribution function.\n    static RealType F(std::size_t k, std::size_t n, std::size_t x)\n    {\n        // Some cases of small values (k, n) are implemented explicitly\n        // avoiding the Gumbel-based approximation in order to increase\n        // precision.\n        if (k == 0)\n        {\n            return RealType(1);\n        }\n        if (n == 1)\n        {\n            return (x >= k) ? RealType(1) : RealType(0);\n        }\n\n        return std::exp(-std::exp((mu(k, n) - x) / beta(k, n)));\n    }\n\n    // Mean.\n    static RealType E(std::size_t k, std::size_t n)\n    {\n        // Euler–Mascheroni constant.\n        const RealType gamma = RealType(0.5772);\n\n        return mu(k, n) + gamma * beta(k, n);\n    }\n\n    static RealType mu(std::size_t k, std::size_t n)\n    {\n        return RealType(1.16) * k * std::pow(RealType(n), RealType(-2) / 3) + 1;\n    }\n\n    static RealType beta(std::size_t k, std::size_t n)\n    {\n        return RealType(0.4) * k * std::pow(RealType(n), RealType(-4) / 5) + RealType(0.32);\n    }\n};\n\n\n// Compares two spaces using an approximation of the Gumbold means.\ntemplate <typename RealType>\nbool operator < (const Space<RealType> &s1, const Space<RealType> &s2)\n{\n    RealType mean1 = SubdivisionPolicy<RealType>::E(std::size_t(s1.get_votes()),\n                                                    s1.get_prob_element_count());\n    RealType mean2 = SubdivisionPolicy<RealType>::E(std::size_t(s2.get_votes()),\n                                                    s2.get_prob_element_count());\n    return\n        (mean1 < mean2) ? true : false;\n}\n\n} // namespace detail\n\ntemplate <typename RealType>\nclass DualPointGHT: public boost::noncopyable\n{\npublic:\n    typedef DualPointGHT<RealType> this_type;\n    typedef Vector<RealType, 2> Point2D;\n    typedef std::vector<Point2D> Points2D;\n    typedef std::pair<Point2D, Point2D> Reference;\n    typedef std::pair<Point2D, Point2D> SearchArea;\n    typedef std::pair<Reference, RealType> ReferenceVote;\n    typedef std::vector<ReferenceVote> ReferenceVotes;\n    // Feature is a model point and a tangent vector.\n    typedef std::pair<Point2D, Point2D> Feature;\n    typedef std::vector<Feature> Features; \n    typedef std::pair<RealType, RealType> ATableElement;\n    typedef std::list<ATableElement> ATableRow;\n    typedef std::vector<ATableRow> ATable;\n    typedef detail::Space<RealType> Space4D;\n    typedef detail::SubdivisionPolicy<RealType> SubPolicy;\n\n    DualPointGHT(const Features &model_features, const Reference &model_reference, \n                 RealType tangent_accuracy = RealType(0.005)):\n    model_reference_(model_reference), tangent_accuracy_(tangent_accuracy),\n    pi_(boost::math::constants::pi<RealType>())\n    {\n        encode(model_features);\n\n        model_base_ = (model_reference_.second - model_reference_.first).euclidean_norm();\n    }\n\n    void project_detected_lines(const Features &object_features, const Point2D &scaling_range,\n                                bo::RawImage2D<RealType> &image1, bo::RawImage2D<RealType> &image2)\n    {\n        for (typename Features::const_iterator it = object_features.begin();\n             it != object_features.end(); ++it)\n        {\n            // Reconstruct all the 4D lines from the alpha-table relatively to the current feature.\n            for (std::size_t index = 0; index < atable_.size(); ++index)\n            {\n                // Probable angle between the directional vector and the tangent.\n                RealType gamma = atable_gamma(index);\n\n                // Find all corresponding directional vectors v2 defined by the\n                // (alpha, beta) angles of the current table row.\n                for (typename ATableRow::const_iterator abit = atable_.at(index).begin();\n                     abit !=  atable_.at(index).end(); ++abit)\n                {\n                    typename Space4D::Line4D line4 = line4_from_feature_and_atable_element(\n                                *it, gamma, *abit);\n\n                    // Create two segments on this line that correspond to the given scaling range.\n                    Point2D v1(line4.direction[0], line4.direction[1]);\n                    Point2D v2(line4.direction[2], line4.direction[3]);\n                    RealType vnorm = (v2 - v1).euclidean_norm();\n                    Point2D segment_coords = scaling_range * model_base_ / vnorm;\n\n                    typename Space4D::Segment4D segment1(line4,  segment_coords);\n                    typename Space4D::Segment4D segment2(line4, -segment_coords);\n\n                    project_segment(segment1, image1, image2);\n                    project_segment(segment2, image1, image2);\n                }\n            }\n        }\n    }\n\n    void project_segment(const typename Space4D::Segment4D &segment,\n                         bo::RawImage2D<RealType> &image1, bo::RawImage2D<RealType> &image2)\n    {\n        const RealType delta_t = RealType(0.01);\n\n        RealType t1 = segment.second[0];\n        RealType t2 = segment.second[1];\n\n        typename Space4D::Point4D p = segment.first.point;\n        typename Space4D::Point4D v = segment.first.direction;\n\n        if (t1 > t2)\n            std::swap(t1, t2);\n\n        Vector<int, 4> tmp(0, 0, 0, 0);\n\n        for (RealType t = t1; t < t2; t += delta_t)\n        {\n            typename Space4D::Point4D xt = p + v * t;\n\n            Vector<int, 4> rounded((int)xt[0], (int)xt[1], (int)xt[2], (int)xt[3]);\n\n            if (rounded != tmp)\n            {\n                tmp = rounded;\n\n                if (rounded[0] >= 0 && rounded[0] < image1.width() &&\n                    rounded[1] >= 0 && rounded[1] < image1.height())\n                {\n                    image1(rounded[0], rounded[1]) += 1;\n                }\n\n                if (rounded[2] >= 0 && rounded[2] < image2.width() &&\n                    rounded[3] >= 0 && rounded[3] < image2.height())\n                {\n                    image2(rounded[2], rounded[3]) += 1;\n                }\n            }\n        }\n    }\n\n    // Detects the references that define probable poses of the model within the \n    // given features.\n    ReferenceVotes fast_detect(const Features &object_features, RealType probability, \n                               typename Space4D::Size4D divisions_per_dimension,\n                               std::size_t maximal_resolution_level,\n                               std::size_t cell_resolution_increment,\n                               SearchArea reference_box1,\n                               SearchArea reference_box2,\n                               Point2D scaling_range = Point2D(0.95f, 1.05f))\n    {\n        ReferenceVotes ref_votes;\n\n        // Create the root space object.\n        typename Space4D::Point4D p1(reference_box1.first[0], reference_box1.first[1],\n                                  reference_box2.first[0], reference_box2.first[1]);\n        typename Space4D::Point4D p2(reference_box1.second[0], reference_box1.second[1],\n                                  reference_box2.second[0], reference_box2.second[1]);\n\n        Space4D s (typename Space4D::Box4D(p1, p2), divisions_per_dimension,\n                   maximal_resolution_level, cell_resolution_increment, 0);\n\n        // In the case if the scaling is incorrect.\n        normalize_scaling_range(scaling_range);\n\n        // Hierarchical search for the vote peak in the space.\n        process_space(s, object_features, scaling_range, probability);\n\n        // Get all subspaces from the last resolution level;\n        typename Space4D::Spaces leafs;\n        get_resolution_level(s, leafs, maximal_resolution_level);\n\n        // Sort in descending order.\n        std::sort(leafs.rbegin(), leafs.rend());\n\n        // Extract the references.\n        for (typename Space4D::Spaces::const_iterator it = leafs.begin();\n             it != leafs.end(); ++it)\n        {\n            // Attention: the space is approximated by its mass center!\n            typename Space4D::Point4D c = it->get_mass_center();\n\n            Reference ref(Point2D(c[0], c[1]), Point2D(c[2], c[3]));\n            ReferenceVote rv(ref, it->get_votes());\n            ref_votes.push_back(rv);\n        }\n\n        return ref_votes;\n    }\n\n    // Detects the references that define probable poses of the model within the\n    // given features.\n    ReferenceVotes cross_level_detect(const Features &object_features, RealType probability,\n                                      typename Space4D::Size4D divisions_per_dimension,\n                                      std::size_t maximal_resolution_level,\n                                      std::size_t cell_resolution_increment,\n                                      SearchArea reference_box1,\n                                      SearchArea reference_box2,\n                                      Point2D scaling_range = Point2D(0.95f, 1.05f))\n    {\n        ReferenceVotes ref_votes;\n\n        // Create the root space object.\n        typename Space4D::Point4D p1(reference_box1.first[0], reference_box1.first[1],\n                                  reference_box2.first[0], reference_box2.first[1]);\n        typename Space4D::Point4D p2(reference_box1.second[0], reference_box1.second[1],\n                                  reference_box2.second[0], reference_box2.second[1]);\n\n        Space4D s (typename Space4D::Box4D(p1, p2), divisions_per_dimension,\n                   maximal_resolution_level, cell_resolution_increment, 0);\n\n        // In the case if the scaling is incorrect.\n        normalize_scaling_range(scaling_range);\n\n        std::size_t divisions = divisions_per_dimension[0] * divisions_per_dimension[1] *\n                divisions_per_dimension[2] * divisions_per_dimension[3];\n\n        // Initialize temporary collections of spaces.\n        typename Space4D::Spaces in, out;\n        in.push_back(s);\n\n        for (std::size_t level = 0; level < maximal_resolution_level; ++level)\n        {\n            out.clear();\n            out.reserve(in.size() * divisions);\n\n            // Compute the votes for the level subdivision spaces.\n            for (typename Space4D::Spaces::iterator it = in.begin(); it != in.end(); ++it)\n            {\n                subdivide_with_votes(*it, object_features, scaling_range);\n                // Insert all subspaces into the output collection.\n                out.insert(out.end(), it->get_subspaces().begin(), it->get_subspaces().end());\n            }\n\n            // Sort the subspaces in descending order.\n            std::sort(out.rbegin(), out.rend());\n\n            // Find minimal number of subspaces that satisfy the probability constrains.\n            std::size_t n;\n            if (level == maximal_resolution_level - 1)\n            {\n                n = out.size();\n            }\n            else\n            {\n                n = SubPolicy::probabilistic(out, probability);\n            }\n\n            // Update the input collection with the best subspaces.\n            in.clear();\n            in.insert(in.end(), out.begin(), out.begin() + n);\n        }\n\n        // Extract the references.\n        for (typename Space4D::Spaces::const_iterator it = in.begin(); it != in.end(); ++it)\n        {\n            // Attention: the space is approximated by its mass center!\n            typename Space4D::Point4D c = it->get_mass_center();\n\n            Reference ref(Point2D(c[0], c[1]), Point2D(c[2], c[3]));\n            ReferenceVote rv(ref, it->get_votes());\n            ref_votes.push_back(rv);\n        }\n\n        return ref_votes;\n    }\n\n\n    // Reconstructs the points of the model that has the pose defined by the given reference.\n    Points2D reconstruct(const Reference &reference_points)\n    {\n        Points2D points;\n\n        // Reconstruct the model points from all alpha and beta angles and\n        // the given two reference points.\n        for (typename DualPointGHT<RealType>::ATable::const_iterator ait = atable_.begin();\n             ait != atable_.end(); ++ait)\n            for (typename DualPointGHT<RealType>::ATableRow::const_iterator it = ait->begin();\n                 it != ait->end(); ++it)\n            {\n                points.push_back(find_intersection(reference_points, *it));\n            }\n\n        return points;\n    }\n\nprivate:\n    Reference model_reference_;\n    RealType model_base_;\n    RealType tangent_accuracy_;\n    ATable atable_;\n    RealType pi_;\n\n    // Row index in the alpha-table for the given tangent angle.\n    inline std::size_t atable_index(RealType gamma)\n    {\n        return static_cast<std::size_t>((gamma + pi_) / (2 * pi_) * (atable_.size() - 1));\n    }\n\n    // Approximate gamma angle that corresponds to the alpha-table row index.\n    inline RealType atable_gamma(std::size_t index)\n    {\n        return index * 2 * pi_ / (atable_.size() - 1) - pi_;\n    }\n\n    // Rotates the given vector in a radians.\n    inline Point2D rotate(const Point2D &v, RealType a) const\n    {\n        RealType cosa = std::cos(a);\n        RealType sina = std::sin(a);\n\n        return Point2D(cosa * v[0] - sina * v[1], sina * v[0] + cosa * v[1]);\n    }\n\n    // Computes the \"positive\" normal to the given vector.\n    inline Point2D normal(const Point2D &v)\n    {\n        return rotate(v, pi_ / 2);\n    }\n\n    // Computes the signed angle in radians [-pi, pi] betwen the vectors relatively to\n    // the base vector.\n    RealType angle(const Point2D &base, const Point2D &v)\n    {\n        // Cosine between the vectors.\n        RealType cosa = base * v / base.euclidean_norm() / v.euclidean_norm();\n\n        // Angle without the sign.\n        RealType a = std::acos(cosa);\n\n        // Normal vector for the base.\n        Point2D norm_base = normal(base);\n\n        // The sign is defined by the halfspace relatively to base where v is located.\n        int sign = norm_base * v < 0 ? -1 : 1;\n\n        // Angle with sign.\n        return sign * a;\n    }\n\n    // Computes the intersection of two lines, defined by the reference points and\n    // the given element of the alpha-table.\n    Point2D find_intersection(const Reference &reference_points, const ATableElement &e)\n    {\n        // Reference points.\n        Point2D p1 = reference_points.first;\n        Point2D p2 = reference_points.second;\n\n        // Reference vector.\n        Point2D ab = p2 - p1;\n\n        // If the intersection is located on the reference line, compute the intersection\n        // directly.\n        if (e.first == 0)\n        {\n            return p1 + e.second * ab;\n        }\n\n        // Find the first direction with the base norm.\n        Point2D v1 = rotate(ab, e.first);\n\n        // Calculate the intersection point.\n        RealType sinb = std::sin(e.second);\n        RealType sinba = std::sin(e.second - e.first);\n\n        // The intersection is not on the reference line and not in the infinity.\n        BOOST_ASSERT(sinba != 0);\n\n        // The coordinate of the intersection point relatively to v1.\n        RealType t = sinb / sinba;\n\n        return p1 + t * v1;\n    }\n\n    // Fills in the alpha-table using the given model features\n    // and two reference points.\n    void encode(const Features &model_features)\n    {\n        const RealType epsilon = RealType(0.001);\n\n        // Define the number of discrete tangent angles.\n        unsigned int tangent_angle_number = static_cast<unsigned int>(2 * pi_ / tangent_accuracy_);\n\n        // Allocate memory for the alpha-table.\n        atable_.resize(tangent_angle_number);\n\n        // The reference vector.\n        Point2D ab = model_reference_.second - model_reference_.first;\n\n        // Fill in the alpha-table.\n        for (typename Features::const_iterator it = model_features.begin();\n             it != model_features.end(); ++it)\n        {\n            // Current model point.\n            Point2D c = it->first;\n            // Boundary tangent at the current model point.\n            Point2D tangent = it->second;\n\n            // Vectors from the reference points to the current model point.\n            Point2D v1 = c - model_reference_.first;\n            Point2D v2 = c - model_reference_.second;\n\n            // Compute the reference angles.\n            RealType alpha = angle(ab, v1);\n            RealType beta = angle(ab, v2);\n            // Compute the tangential angle.\n            RealType gamma = angle(v1, tangent);\n\n            // Correction for the points located on the reference line.\n            // This case is encoded as: alpha = 0; beta = coordinate of the current model point\n            // on the reference line relatively to the reference vector.\n            if (std::abs(std::sin(beta)) < epsilon)\n            {\n                alpha = 0;\n                RealType abnorm =  ab.euclidean_norm();\n                beta = ab * v1 / (abnorm * abnorm);\n            }\n\n            // Define the row for the computed angles in the alpha-table and insert\n            // the angles into the table.\n            atable_.at(atable_index(gamma)).push_back(ATableElement(alpha, beta));\n        }\n    }\n\n    void normalize_scaling_range(Point2D &scaling_range)\n    {\n        if (scaling_range[0] < 0)\n            scaling_range[0] = 0;\n\n        if (scaling_range[1] < 0)\n            scaling_range[1] = 0;\n\n        if (scaling_range[0] > scaling_range[1])\n            std::swap(scaling_range[0], scaling_range[1]);\n    }\n\n    inline void subdivide_with_votes(Space4D &s, const Features &object_features,\n                                     const Point2D &scaling_range)\n    {\n        // Create the space subdivision.\n        s.subdivide();\n\n        // Calculate the votes for the obtained subspaces.\n        for (typename Space4D::Spaces::iterator it = s.get_subspaces().begin();\n             it != s.get_subspaces().end(); ++it)\n        {\n            feature_to_vote(*it, object_features, scaling_range);\n        }\n    }\n\n    // Recursively fills in the space tree calculating votes for each subspace.\n    void process_space(Space4D &s, const Features &object_features, const Point2D &scaling_range,\n                       RealType probability)\n    {\n        if (s.get_resolution_level() >= s.get_max_resolution_level())\n            return;\n\n        // Subdivide the space and compute votes for its subspaces.\n        subdivide_with_votes(s, object_features, scaling_range);\n\n        // Sorting subspaces in descending order!\n        std::sort(s.get_subspaces().rbegin(), s.get_subspaces().rend());\n\n        // The minimal number of spaces from the beginning of the space collection such\n        // that the probability of maximal element is not less than the given value.\n        std::size_t n = SubPolicy::probabilistic(s.get_subspaces(), probability);\n\n        for (std::size_t i = 0; i < n; ++i)\n        {\n            // Continue the subdivision procedure recursively.\n            process_space(s.get_subspaces().at(i), object_features, scaling_range, probability);\n        }\n    }\n\n    // Intersects the given space with the lines produced by the object features and increase the\n    // number of the space votes.\n    void feature_to_vote(Space4D &s, const Features &object_features, const Point2D &scaling_range)\n    {\n        for (typename Features::const_iterator it = object_features.begin();\n             it != object_features.end(); ++it)\n        {\n            feature_to_vote2(s, *it, scaling_range);\n        }\n    }\n\n    // Intersects the given space with the line defined by the feature (position and\n    // tangent) and increase the number of the space votes.\n    inline void feature_to_vote(Space4D &s, const Feature &f, const Point2D &scaling_range)\n    {\n        // Reconstruct all the 4D lines from the alpha-table relatively to the current feature.\n        for (std::size_t index = 0; index < atable_.size(); ++index)\n        {\n            // Probable angle between the directional vector and the tangent.\n            RealType gamma = atable_gamma(index);\n\n            // Find all corresponding directional vectors v2 defined by the\n            // (alpha, beta) angles of the current table row.\n            for (typename ATableRow::const_iterator abit = atable_.at(index).begin();\n                 abit !=  atable_.at(index).end(); ++abit)\n            {\n                typename Space4D::Line4D line4 = line4_from_feature_and_atable_element(f,\n                        gamma, *abit);\n\n                // Create two segments on this line that correspond to the given scaling range.\n                Point2D v1(line4.direction[0], line4.direction[1]);\n                Point2D v2(line4.direction[2], line4.direction[3]);\n                RealType vnorm = (v2 - v1).euclidean_norm();\n                Point2D segment_coords = scaling_range * model_base_ / vnorm;\n\n                typename Space4D::Segment4D segment1(line4,  segment_coords);\n                typename Space4D::Segment4D segment2(line4, -segment_coords);\n\n                // Intersect and compute the votes.\n                s.vote_maxnorm(s.intersect(segment1));\n                s.vote_maxnorm(s.intersect(segment2));\n            }\n        }\n    }\n\n    inline typename Space4D::Line4D line4_from_feature_and_atable_element(const Feature &f,\n            RealType gamma, const ATableElement &e)\n    {\n        Point2D c = f.first;\n        Point2D tan = f.second;\n\n        // Normalized directional vector.\n        Point2D v1 = rotate(tan, -gamma);\n        v1 = v1 / v1.euclidean_norm();\n\n        RealType alpha = e.first;\n        RealType beta = e.second;\n\n        Point2D v2 = rotate(v1, beta - alpha);\n\n        // Consider the directional vectors ratio.\n        if (alpha != 0)\n            // The conventional case.\n            v2 *= std::sin(alpha) / std::sin(beta);\n        else\n            // The directional vectors are located on the reference line.\n            v2 *= 1 - 1 / beta;\n\n        // Compose a 4D line.\n        // The point on this line.\n        typename Space4D::Point4D p4(c.x(), c.y(), c.x(), c.y());\n        // The directional vector of the line.\n        typename Space4D::Point4D v4(v1.x(), v1.y(), v2.x(), v2.y());\n        // The line in 4D.\n        typename Space4D::Line4D line4(p4, v4);\n\n        return line4;\n    }\n\n    // Intersects the given space with the hyperplane defined by the feature\n    // (position and tangent) and increase the number of the space votes.\n    inline void feature_to_vote2(Space4D &s, const Feature &f, const Point2D &scaling_range)\n    {\n        // Reconstruct all the 4D hyperplanes from the alpha-table relatively to the current feature.\n        for (std::size_t index = 0; index < atable_.size(); ++index)\n        {\n            // Probable angle between the directional vector and the tangent.\n            RealType gamma = atable_gamma(index);\n\n            // Find all corresponding directional vectors v2 defined by the (alpha, beta)\n            // angles of the current table row.\n            for (typename ATableRow::const_iterator abit = atable_.at(index).begin();\n                 abit !=  atable_.at(index).end(); ++abit)\n            {\n                // Reconstruct the 4D line.\n                typename Space4D::Line4D line4 = line4_from_feature_and_atable_element(f,\n                        gamma, *abit);\n\n                // Use the hyperplane paradigm.\n                typename Space4D::Point4D norm(line4.direction[3], line4.direction[2],\n                                            -line4.direction[1], -line4.direction[0]);\n                typename Space4D::Point4D point = line4.point;\n                typename Space4D::Hyperplane plane(point, norm);\n\n                // Check the plane constrains here and vote.\n                if (is_in_scaling_constrains(s, plane, scaling_range) &&\n                    is_in_tangent_constrains(s, plane, RealType(0.3)))\n                {\n                     s.vote_descrete(plane);\n                }\n            }\n        }\n    }\n\n    int location_by_line(const Point2D &bot, const Point2D &top,\n                         const Point2D &b, const Point2D &normal) const\n    {\n        Point2D d = top - bot;\n\n        RealType proj_min = std::numeric_limits<RealType>::max();\n        RealType proj_max = -proj_min;\n\n        for (std::size_t i = 0; i < 2; ++i)\n            for (std::size_t j = 0; j < 2; ++j)\n            {\n                Point2D p = bot + Point2D(d[0] * i, d[1] * j);\n\n                RealType proj = (p - b) * normal;\n\n                if (proj_min > proj)\n                    proj_min = proj;\n\n                if (proj_max < proj)\n                    proj_max = proj;\n            }\n\n        if ((proj_min == 0 && proj_max == 0) || proj_min * proj_max < 0)\n            return 0;\n\n        return proj_max > 0 ? 1 : -1;\n    }\n\n    bool is_in_scaling_constrains(const Space4D &s,\n                                  const typename Space4D::Hyperplane &plane,\n                                  const Point2D &scaling_range) const\n    {\n        // Compute directional vectors.\n        Point2D v1(-plane.normal()[3], -plane.normal()[2]);\n        Point2D v2(plane.normal()[1], plane.normal()[0]);\n\n        RealType vnorm = (v2 - v1).euclidean_norm();\n        Point2D scaling = scaling_range * model_base_ / vnorm;\n\n        typename Space4D::Box4D box = s.get_bounding_box();\n\n        // Box projections.\n        Point2D bot_v1(box.first[0], box.first[1]);\n        Point2D top_v1(box.second[0], box.second[1]);\n        Point2D bot_v2(box.first[2], box.first[3]);\n        Point2D top_v2(box.second[2], box.second[3]);\n\n        Point2D b(plane.point()[0], plane.point()[1]);\n\n        // Points on the lines.\n        Point2D b_v1q1 = b + v1 * scaling[0];\n        Point2D b_v1q2 = b + v1 * scaling[1];\n        Point2D b_v2q1 = b + v2 * scaling[0];\n        Point2D b_v2q2 = b + v2 * scaling[1];\n\n        Point2D b_v1q1_inv = b - v1 * scaling[0];\n        Point2D b_v1q2_inv = b - v1 * scaling[1];\n        Point2D b_v2q1_inv = b - v2 * scaling[0];\n        Point2D b_v2q2_inv = b - v2 * scaling[1];\n\n        return (location_by_line(bot_v1, top_v1, b_v1q1, v1) >= 0 &&\n                location_by_line(bot_v1, top_v1, b_v1q2, v1) <= 0 &&\n                location_by_line(bot_v2, top_v2, b_v2q1, v2) >= 0 &&\n                location_by_line(bot_v2, top_v2, b_v2q2, v2) <= 0) ||\n               (location_by_line(bot_v1, top_v1, b_v1q1_inv, -v1) >= 0 &&\n                location_by_line(bot_v1, top_v1, b_v1q2_inv, -v1) <= 0 &&\n                location_by_line(bot_v2, top_v2, b_v2q1_inv, -v2) >= 0 &&\n                location_by_line(bot_v2, top_v2, b_v2q2_inv, -v2) <= 0);\n    }\n\n    inline void sector_constraint(const Point2D &v, RealType sigma,\n                                  Point2D &nw) const\n    {\n        Point2D w = rotate(v, sigma);\n\n        nw[0] = -w[1];\n        nw[1] = w[0];\n\n        // Correct the sign of the normal.\n        if (nw * (v - w) > 0)\n            nw *= -1;\n    }\n\n    bool is_in_tangent_constrains(const Space4D &s,\n                                  const typename Space4D::Hyperplane &plane,\n                                  const RealType sigma) const\n    {\n        // Compute directional vectors v1 and v2.\n        Point2D v1(-plane.normal()[3], -plane.normal()[2]);\n        Point2D v2(plane.normal()[1], plane.normal()[0]);\n\n        typename Space4D::Box4D box = s.get_bounding_box();\n\n        // Box projections.\n        Point2D bot_v1(box.first[0], box.first[1]);\n        Point2D top_v1(box.second[0], box.second[1]);\n        Point2D bot_v2(box.first[2], box.first[3]);\n        Point2D top_v2(box.second[2], box.second[3]);\n\n        Point2D b(plane.point()[0], plane.point()[1]);\n\n        // Calculate vectors constraining the sigma-sector.\n        Point2D nw1, nw2, nu1, nu2;\n        sector_constraint(v1, sigma, nw1);\n        sector_constraint(v1, -sigma, nu1);\n        sector_constraint(v2, sigma, nw2);\n        sector_constraint(v2, -sigma, nu2);\n\n        return (location_by_line(bot_v1, top_v1, b, nw1) *\n                location_by_line(bot_v1, top_v1, b, nu1) >= 0) &&\n               (location_by_line(bot_v2, top_v2, b, nw2) *\n                location_by_line(bot_v2, top_v2, b, nu2) >= 0);\n    }\n\n    // Recursively traces the space tree and inserts into the container the elements from\n    // the given resolution level.\n    void get_resolution_level(const Space4D &s, typename Space4D::Spaces &container,\n                              std::size_t resolution_level)\n    {\n        if (s.get_resolution_level() == resolution_level)\n            container.push_back(s);\n        else\n        {\n            const typename Space4D::Spaces subs = s.get_subspaces();\n\n            for (typename Space4D::Spaces::const_iterator it = subs.begin();\n                 it != subs.end(); ++it)\n            {\n                get_resolution_level(*it, container, resolution_level);\n            }\n        }\n\n    }\n\n};\n\n} // namespace recognition\n} // namespace bo\n\n#endif // DPG_HOUGH_TRANSFORM_HPP_55B0255B_E6C8_4302_9114_D1B684CD3419_\n", "meta": {"hexsha": "a2c41fe7f68e3fb0c41cd99455542dc6011950bc", "size": 54144, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/recognition/dpg_hough_transform_2d.hpp", "max_stars_repo_name": "rukletsov/bo", "max_stars_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T03:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T10:53:32.000Z", "max_issues_repo_path": "Bo/recognition/dpg_hough_transform_2d.hpp", "max_issues_repo_name": "rukletsov/bo", "max_issues_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bo/recognition/dpg_hough_transform_2d.hpp", "max_forks_repo_name": "rukletsov/bo", "max_forks_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5508864084, "max_line_length": 103, "alphanum_fraction": 0.577016844, "num_tokens": 13136, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789040926008, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.42106107166847156}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"per_face_normals.h\"\n#include <Eigen/Geometry>\n\n#define SQRT_ONE_OVER_THREE 0.57735026918962573\ntemplate <typename DerivedV, typename DerivedF, typename DerivedZ, typename DerivedN>\nIGL_INLINE void igl::per_face_normals(\n  const Eigen::MatrixBase<DerivedV>& V,\n  const Eigen::MatrixBase<DerivedF>& F,\n  const Eigen::MatrixBase<DerivedZ> & Z,\n  Eigen::PlainObjectBase<DerivedN> & N)\n{\n  N.resize(F.rows(),3);\n  // loop over faces\n  int Frows = F.rows();\n#pragma omp parallel for if (Frows>10000)\n  for(int i = 0; i < Frows;i++)\n  {\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v1 = V.row(F(i,1)) - V.row(F(i,0));\n    const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> v2 = V.row(F(i,2)) - V.row(F(i,0));\n    N.row(i) = v1.cross(v2);//.normalized();\n    typename DerivedV::Scalar r = N.row(i).norm();\n    if(r == 0)\n    {\n      N.row(i) = Z;\n    }else\n    {\n      N.row(i) /= r;\n    }\n  }\n}\n\ntemplate <typename DerivedV, typename DerivedF, typename DerivedN>\nIGL_INLINE void igl::per_face_normals(\n  const Eigen::MatrixBase<DerivedV>& V,\n  const Eigen::MatrixBase<DerivedF>& F,\n  Eigen::PlainObjectBase<DerivedN> & N)\n{\n  Eigen::Matrix<typename DerivedN::Scalar,3,1> Z(0,0,0);\n  return per_face_normals(V,F,Z,N);\n}\n\ntemplate <typename DerivedV, typename DerivedF, typename DerivedN>\nIGL_INLINE void igl::per_face_normals_stable(\n  const Eigen::MatrixBase<DerivedV>& V,\n  const Eigen::MatrixBase<DerivedF>& F,\n  Eigen::PlainObjectBase<DerivedN> & N)\n{\n  typedef Eigen::Matrix<typename DerivedV::Scalar,1,3> RowVectorV3;\n  typedef typename DerivedV::Scalar Scalar;\n\n  const size_t m = F.rows();\n\n  N.resize(F.rows(),3);\n  // Grad all points\n  for(size_t f = 0;f<m;f++)\n  {\n    const RowVectorV3 p0 = V.row(F(f,0));\n    const RowVectorV3 p1 = V.row(F(f,1));\n    const RowVectorV3 p2 = V.row(F(f,2));\n    const RowVectorV3 n0 = (p1 - p0).cross(p2 - p0);\n    const RowVectorV3 n1 = (p2 - p1).cross(p0 - p1);\n    const RowVectorV3 n2 = (p0 - p2).cross(p1 - p2);\n\n    // careful sum\n    for(int d = 0;d<3;d++)\n    {\n      // This is a little _silly_ in terms of complexity, but its recursive\n      // implementation is clean looking...\n      const std::function<Scalar(Scalar,Scalar,Scalar)> sum3 =\n        [&sum3](Scalar a, Scalar b, Scalar c)->Scalar\n      {\n        if(fabs(c)>fabs(a))\n        {\n          return sum3(c,b,a);\n        }\n        // c < a\n        if(fabs(c)>fabs(b))\n        {\n          return sum3(a,c,b);\n        }\n        // c < a, c < b\n        if(fabs(b)>fabs(a))\n        {\n          return sum3(b,a,c);\n        }\n        return (a+b)+c;\n      };\n\n      N(f,d) = sum3(n0(d),n1(d),n2(d));\n    }\n    // sum better not be sure, or else NaN\n    N.row(f) /= N.row(f).norm();\n  }\n\n}\n\n#include \"cotmatrix.h\"\n\ntemplate <\n  typename DerivedV,\n  typename DerivedI,\n  typename DerivedC,\n  typename DerivedN,\n  typename DerivedVV,\n  typename DerivedFF,\n  typename DerivedJ>\nIGL_INLINE void igl::per_face_normals(\n  const Eigen::MatrixBase<DerivedV> & V,\n  const Eigen::MatrixBase<DerivedI> & I,\n  const Eigen::MatrixBase<DerivedC> & C,\n  Eigen::PlainObjectBase<DerivedN> & N,\n  Eigen::PlainObjectBase<DerivedVV> & VV,\n  Eigen::PlainObjectBase<DerivedFF> & FF,\n  Eigen::PlainObjectBase<DerivedJ> & J)\n{\n  assert(V.cols() == 3);\n  typedef Eigen::Index Index;\n  typedef typename DerivedN::Scalar Scalar;\n  // Use Bunge et al. algorithm in igl::cotmatrix to insert a point for each\n  // polygon which minimizes squared area.\n  {\n    Eigen::SparseMatrix<Scalar> _1,_2,P;\n    igl::cotmatrix(V,I,C,_1,_2,P);\n    VV = P*V;\n  }\n  // number of polygons\n  const Eigen::Index m = C.size()-1;\n  N.resize(m,3);\n  FF.resize(C(m),3);\n  J.resize(C(m));\n  {\n    Eigen::Index k = 0;\n    for(Eigen::Index p = 0;p<m;p++)\n    {\n      N.row(p).setZero();\n      // number of faces/vertices in this simple polygon\n      const Index np = C(p+1)-C(p);\n      for(Eigen::Index i = 0;i<np;i++)\n      {\n        FF.row(k) << \n          I(C(p)+((i+0)%np)),\n          I(C(p)+((i+1)%np)),\n          V.rows()+p;\n        J(k) = p;\n        k++;\n        typedef Eigen::Matrix<Scalar,1,3> V3;\n        N.row(p) +=\n          V3(VV.row(I(C(p)+((i+0)%np)))-VV.row(V.rows()+p)).cross(\n          V3(VV.row(I(C(p)+((i+1)%np)))-VV.row(V.rows()+p)));\n      }\n      // normalize to take average\n      N.row(p) /= N.row(p).stableNorm();\n    }\n    assert(k == FF.rows());\n  }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, 3, 1, -1, 3>, Eigen::Matrix<float, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<unsigned int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 0, -1, 3> >&);\n// generated by autoexplicit.sh\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<float, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<float, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\n// Nonsense template. Where'd this come from? AABB nonsense?\nnamespace igl{template<> void per_face_normals<Eigen::Matrix<double, -1, 2, 0, -1, 2>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 2, 0, -1, 2> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&){} }\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<float, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<float, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<float, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, 3, 1, 0, 3, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, 3, 1, 0, 3, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, 1, 3, 1, 1, 3>, Eigen::Matrix<double, 1, -1, 1, 1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, 1, 3, 1, 1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 1, -1, 1, 1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<double, -1, 3, 1, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, -1, 1, -1, -1>, Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1>, Eigen::Matrix<float, -1, -1, 1, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, -1, 1, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, -1, 1, -1, -1> >&);\ntemplate void igl::per_face_normals<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, 3, 1, -1, 3>, Eigen::Matrix<float, -1, 3, 1, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<unsigned int, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> >&);\ntemplate void igl::per_face_normals<class Eigen::Matrix<double,-1,3,0,-1,3>,class Eigen::Matrix<int,-1,-1,0,-1,-1>,class Eigen::Matrix<double,-1,-1,0,-1,-1> >(class Eigen::MatrixBase<class Eigen::Matrix<double,-1,3,0,-1,3> > const &,class Eigen::MatrixBase<class Eigen::Matrix<int,-1,-1,0,-1,-1> > const &,class Eigen::PlainObjectBase<class Eigen::Matrix<double,-1,-1,0,-1,-1> > &);\ntemplate void igl::per_face_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, 2, 3, 0, 2, 3>, Eigen::Matrix<double, 2, 3, 0, 2, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, 2, 3, 0, 2, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 2, 3, 0, 2, 3> >&);\ntemplate void igl::per_face_normals_stable<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);\ntemplate void igl::per_face_normals_stable<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\ntemplate void igl::per_face_normals_stable<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, 3, 0, -1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&);\n#endif\n", "meta": {"hexsha": "4e7dd41d80f9133488643818efb9a20f506d692f", "size": 14089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/depends/igl/headers/igl/per_face_normals.cpp", "max_stars_repo_name": "GitZHCODE/zspace_modules", "max_stars_repo_head_hexsha": "2264cb837d2f05184a51b7b453c7e24288e88ee1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/depends/igl/headers/igl/per_face_normals.cpp", "max_issues_repo_name": "GitZHCODE/zspace_modules", "max_issues_repo_head_hexsha": "2264cb837d2f05184a51b7b453c7e24288e88ee1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/depends/igl/headers/igl/per_face_normals.cpp", "max_forks_repo_name": "GitZHCODE/zspace_modules", "max_forks_repo_head_hexsha": "2264cb837d2f05184a51b7b453c7e24288e88ee1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 72.6237113402, "max_line_length": 774, "alphanum_fraction": 0.6109021222, "num_tokens": 5449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.42096312375149497}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\nCopyright (C) 2012 Klaus Spanderen\n\nThis file is part of QuantLib, a free-software/open-source library\nfor financial quantitative analysts and developers - http://quantlib.org/\n\nQuantLib is free software: you can redistribute it and/or modify it\nunder the terms of the QuantLib license.  You should have received a\ncopy of the license along with this program; if not, please email\n<quantlib-dev@lists.sf.net>. The license is also available online at\n<http://quantlib.org/license.shtml>.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file sparsematrix.hpp\n    \\brief typedef for boost sparse matrix class\n*/\n\n#ifndef quantlib_sparse_matrix_hpp\n#define quantlib_sparse_matrix_hpp\n\n#include <ql/qldefines.hpp>\n\n#if !defined(QL_NO_UBLAS_SUPPORT)\n\n#include <ql/math/array.hpp>\n\n#if defined(QL_PATCH_MSVC)\n#pragma warning(push)\n#pragma warning(disable:4180)\n#pragma warning(disable:4127)\n#endif\n\n#if defined(__clang__) && BOOST_VERSION > 105300\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wunused-function\"\n#endif\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n\n#if BOOST_VERSION == 106400\n#include <boost/serialization/array_wrapper.hpp>\n#endif\n\n#include <boost/numeric/ublas/matrix_sparse.hpp>\n\n#if defined(QL_PATCH_MSVC)\n#pragma warning(pop)\n#endif\n\n#if defined(__clang__) && BOOST_VERSION > 105300\n#pragma clang diagnostic pop\n#endif\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\nnamespace QuantLib {\n    typedef boost::numeric::ublas::compressed_matrix<Real> SparseMatrix;\n    typedef boost::numeric::ublas::matrix_reference<SparseMatrix>\n        SparseMatrixReference;\n\n    inline Disposable<Array> prod(const SparseMatrix& A, const Array& x) {\n        Array b(x.size(), 0.0);\n\n        for (Size i=0; i < A.filled1()-1; ++i) {\n            const Size begin = A.index1_data()[i];\n            const Size end   = A.index1_data()[i+1];\n            Real t=0;\n            for (Size j=begin; j < end; ++j) {\n                t += A.value_data()[j]*x[A.index2_data()[j]];\n            }\n\n            b[i]=t;\n        }\n        return b;\n    }\n}\n\n#endif\n#endif\n", "meta": {"hexsha": "cd69351577ae9ed330d6a08cf0906b0293d94000", "size": 2544, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/math/matrixutilities/sparsematrix.hpp", "max_stars_repo_name": "urgu00/QuantLib", "max_stars_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-12T01:27:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T17:44:12.000Z", "max_issues_repo_path": "ql/math/matrixutilities/sparsematrix.hpp", "max_issues_repo_name": "urgu00/QuantLib", "max_issues_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T08:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:06:53.000Z", "max_forks_repo_path": "ql/math/matrixutilities/sparsematrix.hpp", "max_forks_repo_name": "urgu00/QuantLib", "max_forks_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-04T15:19:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T08:24:37.000Z", "avg_line_length": 27.956043956, "max_line_length": 87, "alphanum_fraction": 0.6961477987, "num_tokens": 627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.4209631143704429}}
{"text": "#define PY_ARRAY_UNIQUE_SYMBOL superimg_PyArray_API\n#define NO_IMPORT_ARRAY\n\n#include <string>\n#include <cmath>\n\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\n\n#include <boost/array.hpp>\n\n#include <boost/accumulators/accumulators.hpp>\n\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/median.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/extended_p_square_quantile.hpp>\n#include <boost/accumulators/statistics/tail_quantile.hpp>\n\n#include <vigra/numpy_array.hxx>\n#include <vigra/numpy_array_converters.hxx>\n\n#include \"seglib/cgp2d/cgp2d.hxx\"\n#include \"seglib/cgp2d/cgp2d_python.hxx\"\n#include \"seglib/distances/distance.hxx\"\n\n\nnamespace python = boost::python;\n\nnamespace cgp2d {\n\n    // tgrid and input image type\n    typedef Cgp<CoordinateType,LabelType> CgpType;\n    typedef CgpType::TopologicalGridType TopologicalGridType;\n\n\n    void mergeFeatures(\n        vigra::NumpyArray<1,LabelType>          labeling,\n        const size_t                            numberOfLabels,\n        vigra::NumpyArray<1,float>              weights,\n        vigra::NumpyArray<2,float>              features,\n        vigra::NumpyArray<2,float>              mergedFeatures,\n        vigra::NumpyArray<1,float>              weightBuffer\n    ){ \n        CGP_ASSERT_OP(labeling.shape(0),==,features.shape(0));\n        CGP_ASSERT_OP(labeling.shape(0),==,mergedFeatures.shape(0));\n        CGP_ASSERT_OP(features.shape(1),==,mergedFeatures.shape(1));\n        CGP_ASSERT_OP(weightBuffer.shape(0),==,features.shape(0));\n\n        // initalize with zeros\n        std::fill(mergedFeatures.begin(),mergedFeatures.begin()+numberOfLabels,0.0);\n        std::fill(weightBuffer.begin(),weightBuffer.begin()+numberOfLabels,0.0);\n\n\n        const size_t nItems = labeling.shape(0);\n        const size_t nFeatures = features.shape(1);\n\n        // accumulate\n        for(size_t i=0;i<nItems;++i){\n\n            // get the label\n            const size_t label = labeling(i);\n            // get the weight\n            const float weight = weights(i);\n            // accumulate features\n            for(size_t f=0;f<nFeatures;++f){\n                mergedFeatures(label,f)+=weight*features(i,f);\n            }\n            // accumulate weights\n            weightBuffer(i)+=weight;\n        }\n        // normalize \n\n        for(size_t label=0;label<numberOfLabels;++label){\n            const float weight=weights(label);\n            for(size_t f=0;f<nFeatures;++f){\n                mergedFeatures(label,f)/=weight;\n            }\n        }\n\n    }\n\n\n    float withinClusterDist(\n        vigra::NumpyArray<1,LabelType>          labeling,\n        const size_t                            numberOfLabels,\n        vigra::NumpyArray<1,float>              weights,\n        vigra::NumpyArray<2,float>              features,\n        vigra::NumpyArray<2,float>              mergedFeatures\n    ){\n        CGP_ASSERT_OP(labeling.shape(0),==,features.shape(0));\n        CGP_ASSERT_OP(labeling.shape(0),==,mergedFeatures.shape(0));\n        CGP_ASSERT_OP(features.shape(1),==,mergedFeatures.shape(1));\n\n\n        const size_t nItems = labeling.shape(0);\n        const size_t nFeatures = features.shape(1);\n\n        float totalD = 0.0;\n\n        for(size_t i=0;i<nItems;++i){\n\n            // get the label\n            const size_t label = labeling(i);\n\n            // compute the distance between the feature of the item (superpixel)\n            // and the feature of the cluster (cluster of superpixel / \"HyperRegion\")\n            vigra::MultiArrayView<1,float> a=features.bindInner(i);\n            vigra::MultiArrayView<1,float> b=mergedFeatures.bindInner(label);\n            const  float d = distances::Distance<float>::klDivergenz(a.begin(),a.end(),b.begin(),b.end());\n            // get the weight of the item (superpixel size)\n            const float weight=weights(i);\n\n            totalD += weight*d;\n\n\n            //weightBuffer(l)+=weight\n        }\n        return totalD;\n    }\n\n    float betweenClusterDist(\n        const Cgp<CoordinateType,LabelType> &   cgp,\n        vigra::NumpyArray<1,LabelType>          labeling,\n        const size_t                            numberOfLabels,\n        vigra::NumpyArray<2,float>              mergedFeatures\n    ){\n\n        float totalD=0.0f;\n\n        std::set<size_t> used;\n        const size_t nBoundaries = cgp.numCells(1);\n        for(size_t b=0;b<nBoundaries;++b){\n            const size_t r1 = cgp.bound<1>(b,0)-1;\n            const size_t r2 = cgp.bound<1>(b,1)-1; \n\n            size_t l1 =labeling(r1);\n            size_t l2 =labeling(r2);\n\n            // active boundarie ? \n            if(l1!=l2){\n\n                if(l2<l1){\n                    std::swap(l1,l2);\n                }\n                const size_t key = l1+ l2*numberOfLabels;\n                if(used.find(key)==used.end()){\n                    used.insert(key);\n                    vigra::MultiArrayView<1,float> a=mergedFeatures.bindInner(l1);\n                    vigra::MultiArrayView<1,float> b=mergedFeatures.bindInner(l2);\n                    const float d = distances::Distance<float>::klDivergenz(a.begin(),a.end(),b.begin(),b.end());\n                    totalD+=d;\n                }\n            }       \n        }\n        return totalD;\n    }\n\n\n\n    void export_merge(){\n\n        python::def(\"_mergeFeatures\",vigra::registerConverters(&mergeFeatures),\n            (\n                python::arg(\"labeling\"),\n                python::arg(\"numberOfLabels\"),\n                python::arg(\"weights\"),\n                python::arg(\"features\"),\n                python::arg(\"mergedFeatures\"),\n                python::arg(\"weightBuffer\")\n            )\n        );\n\n        python::def(\"_withinClusterDist\",vigra::registerConverters(&withinClusterDist),\n            (\n                python::arg(\"labeling\"),\n                python::arg(\"numberOfLabels\"),\n                python::arg(\"weights\"),\n                python::arg(\"features\"),\n                python::arg(\"mergedFeatures\")\n            )\n        );\n\n        python::def(\"_betweenClusterDist\",vigra::registerConverters(&betweenClusterDist),\n            (\n                python::arg(\"cgp\"),\n                python::arg(\"labeling\"),\n                python::arg(\"numberOfLabels\"),\n                python::arg(\"mergedFeatures\")\n            )\n        );\n\n    }\n\n}", "meta": {"hexsha": "d5deb99495b23173c6da1281a7794416f103e29a", "size": 6375, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/python/cgp2d/misc/py_merge.cxx", "max_stars_repo_name": "DerThorsten/seglib", "max_stars_repo_head_hexsha": "4655079e390e301dd93e53f5beed6c9737d6df9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/python/cgp2d/misc/py_merge.cxx", "max_issues_repo_name": "DerThorsten/seglib", "max_issues_repo_head_hexsha": "4655079e390e301dd93e53f5beed6c9737d6df9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/python/cgp2d/misc/py_merge.cxx", "max_forks_repo_name": "DerThorsten/seglib", "max_forks_repo_head_hexsha": "4655079e390e301dd93e53f5beed6c9737d6df9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6923076923, "max_line_length": 113, "alphanum_fraction": 0.5645490196, "num_tokens": 1476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.42095357735720895}}
{"text": "#include \"scan_calculator.h\"\n#include <graycode.h>\n#include <multiview.h>\n#include <iostream>\n#include <fstream>\n\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <boost/thread.hpp>\n\nvoid ScanCalculator::ScanWorker(int threadId, int startRow, int endRow)\n{\n\tMultiView stereoView;\n\tstereoView.ReadRawCal(\"rawcal.ini\");\n\n\tstd::vector<cv::Point2f> p;\n\tstd::vector<cv::Point3f> lines;\n\tfor(int r = startRow; r < endRow; r++)//for(int r = 1; r < size.height-5; r++)\n\t{\n\t\tfor(int c = 1; c < 1290; c++)//for(int c = 1; c < size.width-5; c++)\n\t\t{\n\t\t\tp.push_back(cv::Point2f(c, r));\n\t\t}\n\t}\n\tcv::computeCorrespondEpilines(p, 1, F, lines);\n\t//std::cout << \"size of lines: \"<< lines.size() << std::endl;\n\n\tcv::Mat cam0pnts(1,1,CV_64FC2);\n\tcv::Mat cam1pnts(1,1,CV_64FC2);\n\n\t//find correspondence and triangulate\n\tT2DLINED l;\n\tint counter = 0;\n\tfor(int r = startRow; r < endRow; r++)\n\t{\n\t\t//std::cout << \"thread \" << threadId << \" : \" << r << std::endl;\n\t\tfor(int c = 1; c < 1290; c++)//for(int c = 1; c < size.width-5; c++)\n\t\t{\n\t\t\tcv::Mat pnts3D = cv::Mat(1,1,CV_64FC4);\n\n\t\t\tl.p0.x = 0;\n\t\t\tl.p0.y = -(lines[counter].z/lines[counter].y);\n\t\t\tdouble m = -(lines[counter].x / lines[counter].y);\n\t\t\tdouble angle = atan(m);            \n\t\t\tl.vr.x = 1250*cos(angle);\n\t\t\tl.vr.y = 1250*sin(angle);\n\n\t\t\tdouble _U=0, _V=0;\n\t\t\tdouble srcW = BLInterpolate(p[counter].x, p[counter].y, absL);\n\t\t\tcounter++;\n\n\t\t\tif(!stereoView.DetectPtOnEplipolarLine(l, srcW, absR, p[counter-1].x, p[counter-1].y, _U, _V, 2, PP2))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcam0pnts.at<cv::Point2d>(0) = p[counter-1];\n\t\t\tcam1pnts.at<cv::Point2d>(0) = cv::Point2d(_U, _V);\n\n\t\t\tcv::triangulatePoints(PP1,PP2,cam0pnts,cam1pnts,pnts3D);\n\t\t\tpnts3D = pnts3D / pnts3D.at<double>(3);\n\n\t\t\tclouds[threadId].push_back(pnts3D);\n\t\t}\n\t}\n}\n\nvoid LoadAbsolutePhase(const char* filename, cv::Mat& absPhase)\n{\n    cv::Mat dummy = cv::imread(filename, CV_16U);\n    short result = 0;\n\n    for(int r = 0; r < absPhase.rows; r++)\n    {\n        for(int c = 0; c < absPhase.cols; c++)\n        {\n            unsigned short val = dummy.at<unsigned short>(cv::Point2i(c,r));\n\n            result = val;\n            if(val > 32767)\n                result = val - 65536;\n\n            absPhase.at<short>(cv::Point2i(c,r)) = result;\n        }\n    }\n}\n\nScanCalculator::ScanCalculator()\n{\n}\n\nScanCalculator::~ScanCalculator()\n{\n\n}\n\nbool ScanCalculator::StartCalculation(std::vector<std::vector<cv::Mat> >& sequence, CalibrationResult& c_result)\n{\n\tint height = sequence[0][0].rows;\n\tint width = sequence[0][0].cols;\n    cv::Size size = cv::Size(sequence[0][0].cols, sequence[0][0].rows);\n    CalculateAbsPhase(sequence);\n\n\tabsL = cv::Mat(height, width, CV_16S);\n    absR = cv::Mat(height, width, CV_16S);\n    LoadAbsolutePhase(\"absL.tiff\", absL);\n    LoadAbsolutePhase(\"absR.tiff\", absR);\n\n    cv::stereoRectify(c_result.K[0], c_result.D[0], c_result.K[1], c_result.D[1], size, c_result.R, c_result.T, R1, R2, P1, P2, Q);\n\tF = c_result.F;\n\n    //P = [K*R -(K*R)*C];\n    cv::Mat exterior = cv::Mat::zeros(4,4,CV_64F);\n    cv::Mat middle = cv::Mat::eye(3,4,CV_64F);\n    //std::cout << middle << std::endl;\n\n    PP1 = cv::Mat::zeros(3,4,CV_64F);\n    cv::Mat rotmat;\n    cv::Rodrigues(c_result.rvecs[0][0], rotmat);\n    //rotmat = rotmat.inv();\n    exterior.at<double>(0,0) = rotmat.at<double>(0,0);\n    exterior.at<double>(0,1) = rotmat.at<double>(0,1);\n    exterior.at<double>(0,2) = rotmat.at<double>(0,2);\n    exterior.at<double>(1,0) = rotmat.at<double>(1,0);\n    exterior.at<double>(1,1) = rotmat.at<double>(1,1);\n    exterior.at<double>(1,2) = rotmat.at<double>(1,2);\n    exterior.at<double>(2,0) = rotmat.at<double>(2,0);\n    exterior.at<double>(2,1) = rotmat.at<double>(2,1);\n    exterior.at<double>(2,2) = rotmat.at<double>(2,2);\n    exterior.at<double>(0,3) = c_result.tvecs[0][0].at<double>(0);\n    exterior.at<double>(1,3) = c_result.tvecs[0][0].at<double>(1);\n    exterior.at<double>(2,3) = c_result.tvecs[0][0].at<double>(2);\n    exterior.at<double>(3,0) = 0;\n    exterior.at<double>(3,1) = 0;\n    exterior.at<double>(3,2) = 0;\n    exterior.at<double>(3,3) = 1;\n    PP1 = c_result.K[0] * middle * exterior;\n    PP1 = PP1 / PP1.at<double>(2,3);\n    std::cout << \"P hesaplanan 1\" << PP1 << std::endl;\n\n    PP2 = cv::Mat::zeros(3,4,CV_64F);\n    cv::Mat rotmat2;\n    cv::Rodrigues(c_result.rvecs[1][0], rotmat2);\n    exterior.at<double>(0,0) = rotmat2.at<double>(0,0);\n    exterior.at<double>(0,1) = rotmat2.at<double>(0,1);\n    exterior.at<double>(0,2) = rotmat2.at<double>(0,2);\n    exterior.at<double>(1,0) = rotmat2.at<double>(1,0);\n    exterior.at<double>(1,1) = rotmat2.at<double>(1,1);\n    exterior.at<double>(1,2) = rotmat2.at<double>(1,2);\n    exterior.at<double>(2,0) = rotmat2.at<double>(2,0);\n    exterior.at<double>(2,1) = rotmat2.at<double>(2,1);\n    exterior.at<double>(2,2) = rotmat2.at<double>(2,2);\n    exterior.at<double>(0,3) = c_result.tvecs[1][0].at<double>(0);\n    exterior.at<double>(1,3) = c_result.tvecs[1][0].at<double>(1);\n    exterior.at<double>(2,3) = c_result.tvecs[1][0].at<double>(2);\n    exterior.at<double>(3,0) = 0;\n    exterior.at<double>(3,1) = 0;\n    exterior.at<double>(3,2) = 0;\n    exterior.at<double>(3,3) = 1;\n    PP2 = c_result.K[1] * middle * exterior;\n    PP2 = PP2 / PP2.at<double>(2,3);\n    std::cout << \"P hesaplanan 2\" << PP2 << std::endl;\n\n\tboost::thread_group tg;\n\tint thread_amount = 64;\n\tclouds.resize(thread_amount);\n\tint step = 960 / thread_amount;\n\tfor(int i = 0; i<thread_amount; i++)\n\t{\n\t\ttg.create_thread(boost::bind(&ScanCalculator::ScanWorker, this, i, (i*step)+1, (i+1)*step ));\n\t}\n\n\tint t0 = time(NULL);\r\n\ttg.join_all();\r\n\tint t1 = time(NULL);\r\n\tprintf (\"time = %d secs\\n\", t1 - t0);\n\n\tstd::ofstream file(\"out.txt\");\r\n\tfor(int i = 0; i < clouds.size(); i++)\r\n\t{\r\n\t\tm_ptCloud.insert(m_ptCloud.end(), clouds[i].begin(), clouds[i].end());\r\n\t}\n\n    return true;\n}\n\nstd::vector<cv::Mat>* ScanCalculator::GetCloud()\n{\n    return& m_ptCloud;\n}\n\nvoid ScanCalculator::CalculateAbsPhase(std::vector<std::vector<cv::Mat> >& sequence)\n{\n    int height = sequence[0][0].rows;\n    int width = sequence[0][0].cols;\n    cv::Mat absPhaseL = cv::Mat::zeros( height, width, CV_16U );\n    cv::Mat absPhaseR = cv::Mat::zeros( height, width, CV_16U );\n    CalculateGP(absPhaseL, sequence[0], 1, 16, 17);\n    cv::imwrite(\"absL.tiff\", absPhaseL);\n    CalculateGP(absPhaseR, sequence[1], 1, 16, 17);\n    cv::imwrite(\"absR.tiff\", absPhaseR);\n}\n", "meta": {"hexsha": "2cda63d12b071a1176dfa3f16213946de527ec22", "size": 6467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scan_calculator.cpp", "max_stars_repo_name": "for-aiur/scan3d", "max_stars_repo_head_hexsha": "0e60beeab9e1b2776f88fd7062d86737e9f4671d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scan_calculator.cpp", "max_issues_repo_name": "for-aiur/scan3d", "max_issues_repo_head_hexsha": "0e60beeab9e1b2776f88fd7062d86737e9f4671d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-04T06:41:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T06:41:01.000Z", "max_forks_repo_path": "scan_calculator.cpp", "max_forks_repo_name": "for-aiur/scan3d", "max_forks_repo_head_hexsha": "0e60beeab9e1b2776f88fd7062d86737e9f4671d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5463414634, "max_line_length": 131, "alphanum_fraction": 0.6121849389, "num_tokens": 2261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4208970817081695}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <iomanip>\n\n#include \"../include/structures.h\"\n#include \"../include/transformations.h\"\n//#include \"../../point_to_plane_tait_bryan_wc_jacobian.h\"\n//#include \"../../point_to_plane_rodrigues_wc_jacobian.h\"\n//#include \"../../point_to_plane_quaternion_wc_jacobian.h\"\n#include \"../../quaternion_constraint_jacobian.h\"\n#include \"../include/cauchy.h\"\n#include \"../../distance_point_to_plane_tait_bryan_wc_jacobian.h\"\n#include \"../../distance_point_to_plane_rodrigues_wc_jacobian.h\"\n#include \"../../distance_point_to_plane_quaternion_wc_jacobian.h\"\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = 0.0, rotate_y = 0.0;\nfloat translate_z = -10.0;\nfloat translate_x, translate_y = 0.0;\n\nstd::vector<Eigen::Affine3d> trajectory;\nstd::vector<Eigen::Affine3d> planes_global;\nstd::vector<std::vector<Eigen::Affine3d>> planes_local;\n\n\nbool initGL(int *argc, char **argv);\nvoid display();\nvoid keyboard(unsigned char key, int x, int y);\nvoid mouse(int button, int state, int x, int y);\nvoid motion(int x, int y);\nvoid reshape(int w, int h);\nvoid printHelp();\n\nint main(int argc, char *argv[]){\n\tTaitBryanPose pose;\n\tpose.px = -40;\n\tpose.py = 0;\n\tpose.pz = 0;\n\tpose.om = 0;\n\tpose.fi = 0;\n\tpose.ka = 0;\n\ttrajectory.push_back(affine_matrix_from_pose_tait_bryan(pose));\n\n\tpose.px = -20;\n\tpose.py = 0;\n\tpose.pz = 0;\n\tpose.om = 0;\n\tpose.fi = 0;\n\tpose.ka = 0;\n\ttrajectory.push_back(affine_matrix_from_pose_tait_bryan(pose));\n\n\tpose.px = -0;\n\tpose.py = 0;\n\tpose.pz = 0;\n\tpose.om = 0;\n\tpose.fi = 0;\n\tpose.ka = 0;\n\ttrajectory.push_back(affine_matrix_from_pose_tait_bryan(pose));\n\n\tpose.px = 20;\n\tpose.py = 0;\n\tpose.pz = 0;\n\tpose.om = 0;\n\tpose.fi = 0;\n\tpose.ka = 0;\n\ttrajectory.push_back(affine_matrix_from_pose_tait_bryan(pose));\n\n\tpose.px = 40;\n\tpose.py = 0;\n\tpose.pz = 0;\n\tpose.om = 0;\n\tpose.fi = 0;\n\tpose.ka = 0;\n\ttrajectory.push_back(affine_matrix_from_pose_tait_bryan(pose));\n\n\tfor(size_t i = 0 ; i < 100; i++){\n\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 100;\n\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 100;\n\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 100;\n\n\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 10;\n\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 10;\n\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 10;\n\t\tplanes_global.push_back(affine_matrix_from_pose_tait_bryan(pose));\n\t}\n\n\tplanes_local.resize(trajectory.size());\n\tfor(size_t i = 0 ; i < trajectory.size(); i++){\n\t\tEigen::Affine3d m_inv = trajectory[i].inverse();\n\n\t\tfor(size_t j = 0 ; j < planes_global.size(); j++){\n\t\t\tEigen::Affine3d m_line_local = m_inv * planes_global[j];\n\t\t\tplanes_local[i].push_back(m_line_local);\n\t\t}\n\t}\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\n\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"distance_point_to_plane\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01,\n\t\t\t10000.0);\n\tglutReshapeFunc(reshape);\n\n\treturn true;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tfor(size_t i = 0 ; i < trajectory.size(); i++){\n\t\tEigen::Affine3d &m = trajectory[i];\n\n\t\tglBegin(GL_LINES);\n\t\t\tglColor3f(1.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\t\tglVertex3f(m(0,3) + m(0,0), m(1,3) + m(1,0), m(2,3) + m(2,0));\n\n\t\t\tglColor3f(0.0f, 1.0f, 0.0f);\n\t\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\t\tglVertex3f(m(0,3) + m(0,1), m(1,3) + m(1,1), m(2,3) + m(2,1));\n\n\t\t\tglColor3f(0.0f, 0.0f, 1.0f);\n\t\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\t\tglVertex3f(m(0,3) + m(0,2), m(1,3) + m(1,2), m(2,3) + m(2,2));\n\t\tglEnd();\n\t}\n\n\tglColor3f(0.8,0.8,0.8);\n\tglBegin(GL_LINE_STRIP);\n\tfor(size_t i = 0 ; i < trajectory.size(); i++){\n\t\tEigen::Affine3d &m = trajectory[i];\n\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t}\n\tglEnd();\n\n\tfor(size_t i = 0 ; i < planes_local.size(); i++){\n\t\tEigen::Affine3d &m = trajectory[i];\n\n\t\tfor(size_t j = 0 ; j < planes_local[i].size(); j++){\n\t\t\tEigen::Affine3d m_line_global = m * planes_local[i][j];\n\n\t\t\tglBegin(GL_LINES);\n\t\t\t\tglColor3f(1.0f, 0.0f, 0.0f);\n\t\t\t\tglVertex3f(m_line_global(0,3), m_line_global(1,3), m_line_global(2,3));\n\t\t\t\tglVertex3f(m_line_global(0,3) + m_line_global(0,0), m_line_global(1,3) + m_line_global(1,0), m_line_global(2,3) + m_line_global(2,0));\n\n\t\t\t\tglColor3f(0.0f, 1.0f, 0.0f);\n\t\t\t\tglVertex3f(m_line_global(0,3), m_line_global(1,3), m_line_global(2,3));\n\t\t\t\tglVertex3f(m_line_global(0,3) + m_line_global(0,1), m_line_global(1,3) + m_line_global(1,1), m_line_global(2,3) + m_line_global(2,1));\n\n\t\t\t\tglColor3f(0.0f, 0.0f, 1.0f);\n\t\t\t\tglVertex3f(m_line_global(0,3), m_line_global(1,3), m_line_global(2,3));\n\t\t\t\tglVertex3f(m_line_global(0,3) + m_line_global(0,2), m_line_global(1,3) + m_line_global(1,2), m_line_global(2,3) + m_line_global(2,2));\n\t\t\tglEnd();\n\t\t}\n\t}\n\n\tglutSwapBuffers();\n}\n\n\nvoid keyboard(unsigned char key, int /*x*/, int /*y*/) {\n\tswitch (key) {\n\t\tcase (27): {\n\t\t\tglutDestroyWindow(glutGetWindow());\n\t\t\treturn;\n\t\t}\n\t\tcase 'n':{\n\t\t\tfor(size_t i = 0 ; i  < trajectory.size(); i++){\n\t\t\t\tTaitBryanPose pose;\n\t\t\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.0;\n\t\t\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.0;\n\t\t\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.0;\n\t\t\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\ttrajectory[i] = trajectory[i] * affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 't':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0 ; i < planes_local.size(); i++){\n\t\t\t\tfor(size_t j = 0 ; j < planes_local.size(); j++){\n\t\t\t\t\tif(i != j){\n\t\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(trajectory[i]);\n\n\t\t\t\t\t\tfor(size_t k = 0 ; k < planes_local[i].size(); k++){\n\t\t\t\t\t\t\tEigen::Affine3d plane_target_global = trajectory[j] * planes_local[j][k];\n\n\t\t\t\t\t\t\tdouble a,b,c,d;\n\t\t\t\t\t\t\ta = plane_target_global(0,2);\n\t\t\t\t\t\t\tb = plane_target_global(1,2);\n\t\t\t\t\t\t\tc = plane_target_global(2,2);\n\t\t\t\t\t\t\td = -a * plane_target_global(0,3) - b * plane_target_global(1,3) - c * plane_target_global(2,3);\n\n\t\t\t\t\t\t\tEigen::Vector3d point_source_local(planes_local[i][k](0,3), planes_local[i][k](1,3), planes_local[i][k](2,3));\n\t\t\t\t\t\t\tEigen::Matrix<double, 1, 1> delta;\n\t\t\t\t\t\t\tdelta_distance_point_to_plane_tait_bryan_wc(delta,\n\t\t\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka,\n\t\t\t\t\t\t\t\t\tpoint_source_local.x(), point_source_local.y(), point_source_local.z(),\n\t\t\t\t\t\t\t\t\ta, b, c, d);\n\n\t\t\t\t\t\t\tEigen::Matrix<double, 1, 6> delta_jacobian;\n\t\t\t\t\t\t\tdelta_distance_point_to_plane_tait_bryan_wc_jacobian(delta_jacobian,\n\t\t\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka,\n\t\t\t\t\t\t\t\t\tpoint_source_local.x(), point_source_local.y(), point_source_local.z(),\n\t\t\t\t\t\t\t\t\ta, b, c, d);\n\n\n\t\t\t\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\t\t\t\tfor(int ii = 0; ii < 1; ii++){\n\t\t\t\t\t\t\t\tfor(int jj = 0; jj < 6; jj++){\n\t\t\t\t\t\t\t\t\tint ic = i * 6;\n\t\t\t\t\t\t\t\t\tif(delta_jacobian(ii,jj) != 0.0){\n\t\t\t\t\t\t\t\t\t\ttripletListA.emplace_back(ir + ii, ic + jj , -delta_jacobian(ii,jj));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  cauchy(delta(0,0), 1));\n\n\t\t\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), trajectory.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(trajectory.size() * 6, trajectory.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(trajectory.size() * 6, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == trajectory.size() * 6){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < trajectory.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(trajectory[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\n\t\t\t\t\ttrajectory[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'r':{\n\t\t\tfor(size_t i = 0; i < trajectory.size(); i++){\n\t\t\t\tTaitBryanPose posetb = pose_tait_bryan_from_affine_matrix(trajectory[i]);\n\t\t\t\tposetb.om += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.0000001;\n\t\t\t\tposetb.fi += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.0000001;\n\t\t\t\tposetb.ka += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.0000001;\n\t\t\t\ttrajectory[i] = affine_matrix_from_pose_tait_bryan(posetb);\n\t\t\t}\n\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0 ; i < planes_local.size(); i++){\n\t\t\t\tfor(size_t j = 0 ; j < planes_local.size(); j++){\n\t\t\t\t\tif(i != j){\n\t\t\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(trajectory[i]);\n\n\t\t\t\t\t\tfor(size_t k = 0 ; k < planes_local[i].size(); k++){\n\t\t\t\t\t\t\tEigen::Affine3d plane_target_global = trajectory[j] * planes_local[j][k];\n\n\t\t\t\t\t\t\tdouble a,b,c,d;\n\t\t\t\t\t\t\ta = plane_target_global(0,2);\n\t\t\t\t\t\t\tb = plane_target_global(1,2);\n\t\t\t\t\t\t\tc = plane_target_global(2,2);\n\t\t\t\t\t\t\td = -a * plane_target_global(0,3) - b * plane_target_global(1,3) - c * plane_target_global(2,3);\n\n\t\t\t\t\t\t\tEigen::Vector3d point_source_local(planes_local[i][k](0,3), planes_local[i][k](1,3), planes_local[i][k](2,3));\n\t\t\t\t\t\t\tEigen::Matrix<double, 1, 1> delta;\n\t\t\t\t\t\t\tdelta_distance_point_to_plane_rodrigues_wc(delta,\n\t\t\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.sx, pose.sy, pose.sz,\n\t\t\t\t\t\t\t\t\tpoint_source_local.x(), point_source_local.y(), point_source_local.z(),\n\t\t\t\t\t\t\t\t\ta, b, c, d);\n\n\t\t\t\t\t\t\tEigen::Matrix<double, 1, 6> delta_jacobian;\n\t\t\t\t\t\t\tdelta_distance_point_to_plane_rodrigues_wc_jacobian(delta_jacobian,\n\t\t\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.sx, pose.sy, pose.sz,\n\t\t\t\t\t\t\t\t\tpoint_source_local.x(), point_source_local.y(), point_source_local.z(),\n\t\t\t\t\t\t\t\t\ta, b, c, d);\n\n\n\t\t\t\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\t\t\t\tfor(int ii = 0; ii < 1; ii++){\n\t\t\t\t\t\t\t\tfor(int jj = 0; jj < 6; jj++){\n\t\t\t\t\t\t\t\t\tint ic = i * 6;\n\t\t\t\t\t\t\t\t\tif(delta_jacobian(ii,jj) != 0.0){\n\t\t\t\t\t\t\t\t\t\ttripletListA.emplace_back(ir + ii, ic + jj , -delta_jacobian(ii,jj));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  cauchy(delta(0,0), 1));\n\n\t\t\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), trajectory.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(trajectory.size() * 6, trajectory.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(trajectory.size() * 6, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == trajectory.size() * 6){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < trajectory.size(); i++){\n\t\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(trajectory[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.sx += h_x[counter++];\n\t\t\t\t\tpose.sy += h_x[counter++];\n\t\t\t\t\tpose.sz += h_x[counter++];\n\n\t\t\t\t\ttrajectory[i] = affine_matrix_from_pose_rodrigues(pose);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'q':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0 ; i < planes_local.size(); i++){\n\t\t\t\tfor(size_t j = 0 ; j < planes_local.size(); j++){\n\t\t\t\t\tif(i != j){\n\t\t\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(trajectory[i]);\n\n\t\t\t\t\t\tfor(size_t k = 0 ; k < planes_local[i].size(); k++){\n\t\t\t\t\t\t\tEigen::Affine3d plane_target_global = trajectory[j] * planes_local[j][k];\n\n\t\t\t\t\t\t\tdouble a,b,c,d;\n\t\t\t\t\t\t\ta = plane_target_global(0,2);\n\t\t\t\t\t\t\tb = plane_target_global(1,2);\n\t\t\t\t\t\t\tc = plane_target_global(2,2);\n\t\t\t\t\t\t\td = -a * plane_target_global(0,3) - b * plane_target_global(1,3) - c * plane_target_global(2,3);\n\n\t\t\t\t\t\t\tEigen::Vector3d point_source_local(planes_local[i][k](0,3), planes_local[i][k](1,3), planes_local[i][k](2,3));\n\t\t\t\t\t\t\tEigen::Matrix<double, 1, 1> delta;\n\t\t\t\t\t\t\tdelta_distance_point_to_plane_quaternion_wc(delta,\n\t\t\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.q0, pose.q1, pose.q2, pose.q3,\n\t\t\t\t\t\t\t\t\tpoint_source_local.x(), point_source_local.y(), point_source_local.z(),\n\t\t\t\t\t\t\t\t\ta, b, c, d);\n\n\t\t\t\t\t\t\tEigen::Matrix<double, 1, 7> delta_jacobian;\n\t\t\t\t\t\t\tdelta_distance_point_to_plane_quaternion_wc_jacobian(delta_jacobian,\n\t\t\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.q0, pose.q1, pose.q2, pose.q3,\n\t\t\t\t\t\t\t\t\tpoint_source_local.x(), point_source_local.y(), point_source_local.z(),\n\t\t\t\t\t\t\t\t\ta, b, c, d);\n\n\n\t\t\t\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\t\t\t\tfor(int ii = 0; ii < 1; ii++){\n\t\t\t\t\t\t\t\tfor(int jj = 0; jj < 7; jj++){\n\t\t\t\t\t\t\t\t\tint ic = i * 7;\n\t\t\t\t\t\t\t\t\tif(delta_jacobian(ii,jj) != 0.0){\n\t\t\t\t\t\t\t\t\t\ttripletListA.emplace_back(ir + ii, ic + jj , -delta_jacobian(ii,jj));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  cauchy(delta(0,0), 1));\n\n\t\t\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\t\t\ttripletListA.emplace_back(ir + 6 , 6, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 6 , ir + 6, 10000000000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 6 , 0, 0);\n\n\t\t\tfor(size_t i = 0 ; i < trajectory.size(); i++){\n\t\t\t\tint ic = i * 7;\n\t\t\t\tir = tripletListB.size();\n\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(trajectory[i]);\n\n\t\t\t\tdouble delta;\n\t\t\t\tquaternion_constraint(delta, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\tEigen::Matrix<double, 1, 4> jacobian;\n\t\t\t\tquaternion_constraint_jacobian(jacobian, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\ttripletListA.emplace_back(ir, ic + 3 , -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 4 , -jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 5 , -jacobian(0,2));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 6 , -jacobian(0,3));\n\n\t\t\t\ttripletListP.emplace_back(ir, ir, 1000000.0);\n\n\t\t\t\ttripletListB.emplace_back(ir, 0, delta);\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), trajectory.size() * 7);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(trajectory.size() * 7, trajectory.size() * 7);\n\t\t\tEigen::SparseMatrix<double> AtPB(trajectory.size() * 7, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == trajectory.size() * 7){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < trajectory.size(); i++){\n\t\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(trajectory[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.q0 += h_x[counter++];\n\t\t\t\t\tpose.q1 += h_x[counter++];\n\t\t\t\t\tpose.q2 += h_x[counter++];\n\t\t\t\t\tpose.q3 += h_x[counter++];\n\t\t\t\t\ttrajectory[i] = affine_matrix_from_pose_quaternion(pose);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"n: add noise to trajectory\" << std::endl;\n\tstd::cout << \"t: optimize Tait-Bryan\" << std::endl;\n\tstd::cout << \"r: optimize Rodrigues\" << std::endl;\n\tstd::cout << \"q: optimize Quaternion\" << std::endl;\n}\n", "meta": {"hexsha": "7df6ba7b28c81e9677e82e71cb18902d19d28d83", "size": 23541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/distance_point_to_plane.cpp", "max_stars_repo_name": "michalpelka/observation_equations", "max_stars_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codes/c++Examples/src/distance_point_to_plane.cpp", "max_issues_repo_name": "michalpelka/observation_equations", "max_issues_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/c++Examples/src/distance_point_to_plane.cpp", "max_forks_repo_name": "michalpelka/observation_equations", "max_forks_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4703448276, "max_line_length": 138, "alphanum_fraction": 0.630304575, "num_tokens": 8064, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.42089303074173956}}
{"text": "/* Copyright (C) 2012-2020 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n/**\n * @file tableLookup.cpp\n * @brief Code for homomorphic table lookup and fixed-point functions\n */\n#include <limits>\n#include <cmath>\n#include <cstdlib>\n#include <stdexcept>\n#include <NTL/BasicThreadPool.h>\n#include <helib/intraSlot.h>\n#include <helib/tableLookup.h>\n\n#ifdef HELIB_DEBUG\n#include <helib/debugging.h>\n#endif\n\nnamespace helib {\n\nstatic void recursiveProducts(const CtPtrs& products,\n                              const CtPtrs_slice& array);\nstatic double pow2_double(long n); // compute 2^n as double\n\n// For an n-size array, compute the 2^n products\n//     products[j] = \\prod_{i s.t. j_i=1} array[i]\n//                   \\times \\prod_{i s.t. j_i=0}(a-array[i])\nvoid computeAllProducts(/*Output*/ CtPtrs& products,\n                        /*Index*/ const CtPtrs& array,\n                        std::vector<zzX>* unpackSlotEncoding)\n{\n  HELIB_TIMER_START;\n  long nBits = array.size();\n  if (lsize(products) > 0) {\n    long nBits2 = NTL::NumBits(lsize(products) - 1); // ceil(log_2(size))\n    if (nBits > nBits2)\n      nBits = nBits2; // ignore extra bits in 'array'\n  }\n  if (nBits < 1)\n    return; // do nothing\n  // Output cannot be bigger than 2^16\n  assertTrue(nBits <= 16, \"Output cannot be bigger than 2^16\");\n\n  if (lsize(products) == 0) // try to set the output size\n    products.resize(1L << nBits, &array);\n  for (long i = 0; i < lsize(products); i++)\n    products[i]->clear();\n\n  // Check that we have enough levels, try to bootstrap otherwise\n  assertNotNull(array.ptr2nonNull(),\n                \"Invalid array (could not find non-null Ctxt)\");\n  long bpl = array.ptr2nonNull()->getContext().BPL();\n  if (findMinBitCapacity(array) < (NTL::NumBits(nBits) + 1) * bpl) {\n    const Ctxt* ct = array.ptr2nonNull(); // find some non-null Ctxt\n    assertNotNull(unpackSlotEncoding,\n                  \"unpackSlotEncoding must not be null when bootstrapping\");\n    assertTrue(ct->getPubKey().isBootstrappable(),\n               \"Cannot bootstrap with non-bootstrappable public key\");\n    packedRecrypt(array,\n                  *unpackSlotEncoding,\n                  *(ct->getContext().ea),\n                  /*belowLevel=*/nBits + 3);\n  }\n  if (findMinBitCapacity(array) < (NTL::NumBits(nBits) + 1) * bpl)\n    throw LogicError(\"not enough levels for table lookup\");\n\n  // Call the recursive function that computes the products\n  recursiveProducts(products, CtPtrs_slice(array, 0, nBits));\n}\n\n// The input is a plaintext table T[] and an array of encrypted bits\n// I[], holding the binary representation of an index i into T.\n// The output is the encrypted value T[i].\nvoid tableLookup(Ctxt& out,\n                 const std::vector<zzX>& table,\n                 const CtPtrs& idx,\n                 std::vector<zzX>* unpackSlotEncoding)\n{\n  HELIB_TIMER_START;\n  out.clear();\n  std::vector<Ctxt> products(lsize(table),\n                             out); // to hold subset products of idx\n  CtPtrs_vectorCt pWrap(products); // A wrapper\n\n  // Compute all products of encrypted bits =: b_i\n  computeAllProducts(pWrap, idx, unpackSlotEncoding);\n\n  // Compute the sum b_i * T[i]\n  NTL_EXEC_RANGE(lsize(table), first, last)\n  for (long i = first; i < last; i++)\n    products[i].multByConstant(table[i]); // p[i] = p[i]*T[i]\n  NTL_EXEC_RANGE_END\n  for (long i = 0; i < lsize(table); i++)\n    out += products[i];\n}\n\n// A counterpart of tableLookup. The input is an encrypted table T[]\n// and an array of encrypted bits I[], holding the binary representation\n// of an index i into T.  This function increments by one the entry T[i].\nvoid tableWriteIn(const CtPtrs& table,\n                  const CtPtrs& idx,\n                  std::vector<zzX>* unpackSlotEncoding)\n{\n  HELIB_TIMER_START;\n  const Ctxt* ct = table.ptr2nonNull(); // find some non-null Ctxt\n  long size = lsize(table);\n  if (size == 0)\n    return;\n  std::vector<Ctxt> products(size, Ctxt(ZeroCtxtLike, *ct));\n  CtPtrs_vectorCt pWrap(products); // A wrapper\n\n  // Compute all products of encrypted bits =: b_i\n  computeAllProducts(pWrap, idx, unpackSlotEncoding);\n\n  // increment each entry of T[i] by products[i]\n  NTL_EXEC_RANGE(lsize(table), first, last)\n  for (long i = first; i < last; i++)\n    *table[i] += products[i];\n  NTL_EXEC_RANGE_END\n}\n\n// The function buildLookupTable is documented in tableLookup.h.\n// The output is returned in T, size of T will be 2^{nbits_in}.\n// For every signed integer x with bit-size 'nbits_in', we will have\n//     T[x] = f(x * 2^{scale_in}) * 2^{-scale_out}),\n// rounded to the nearest integer and truncated to 'nbits_out' bits.\n// The bits are packed inside the slots, so it is assumed that each\n// slot has enough room to fit these many bits. (Otherwise we only\n// keep as many low-order bits as fit in a slot.)\nvoid buildLookupTable(std::vector<zzX>& T, // encoded result is returned in T\n                      std::function<double(double)> f,\n                      long nbits_in, // number of precision bits\n                      long scale_in, // scaling factor\n                      long sign_in,  // 1: 2's complement signed, 0: unsigned\n                      long nbits_out,\n                      long scale_out,\n                      long sign_out,\n                      const EncryptedArray& ea)\n{\n  HELIB_TIMER_START;\n  // tables of size > 2^{16} are not supported\n  assertTrue(nbits_in <= 16, \"tables of size > 2^{16} are not supported\");\n  long sz = 1L << nbits_in;\n  T.resize(sz);\n\n  double pow2_scale_in = pow2_double(scale_in);        // 2^{nbits_in}\n  double pow2_neg_scale_out = pow2_double(-scale_out); // 2^{-nbits_out}\n\n  // Compute the largest and smallest values that can be in T\n  long largest_value, smallest_value;\n  if (sign_out) { // values in T are encoded in 2's complement\n    largest_value = (1L << (nbits_out - 1)) - 1;\n    smallest_value = -(1L << (nbits_out - 1));\n  } else { // values in T are all non-negative\n    largest_value = (1L << nbits_out) - 1;\n    smallest_value = 0;\n  }\n\n  for (long i = 0; i < sz; i++) { // Compute the entries of T\n    long x;\n    if (sign_in) { // indexes into T are in 2's complement\n      long sign_bit = (1L << (nbits_in - 1)) & i;\n      x = i - 2 * sign_bit;\n    } else\n      x = i; // indexes into T are all non-negative\n\n    // Compute the value that should go in the table as rounded double\n    double scaled_x = double(x) * pow2_scale_in;\n    double y = round(f(scaled_x) * pow2_neg_scale_out);\n\n    // saturated arithmetic (set to smallest or largest values)\n    // NOTE: this should work fine even if y is an infinity\n    long value;\n    if (std::isnan(y))\n      value = 0;\n    else if (y > largest_value)\n      value = largest_value;\n    else if (y < smallest_value)\n      value = smallest_value;\n    else\n      value = y;\n\n    // convert to unsigned and mask to nbits_out bits\n    unsigned long uvalue = value;\n    uvalue &= ((1UL << nbits_out) - 1UL); // keep only bottom nbits_out bits\n\n    packConstant(T[i], uvalue, nbits_out, ea);\n  }\n}\n\n// A recursive function to compute, for an n-size array, the 2^n products\n//     products[j] = \\prod_{i s.t. j_i=1} array[i]\n//                   \\times \\prod_{i s.t. j_i=0}(a-array[i])\n// It is assume that 'products' size <= 2^n, else only 1st 2^n entries are set\nstatic void recursiveProducts(const CtPtrs& products, const CtPtrs_slice& array)\n{\n  long nBits = lsize(array);\n  long N = lsize(products);\n  if (nBits == 0 || N == 0)\n    return; // nothing to do\n\n  if (N > (1L << nBits))\n    N = (1L << nBits);\n  else if (N < (1L << (nBits - 1)))\n    nBits = NTL::NumBits(N - 1); // Ensure nBits <= ceil(log2(N))\n\n  if (N <= 2) { // edge condition\n    *products[0] = *array[0];\n    products[0]->negate();\n    products[0]->addConstant(NTL::ZZ(1)); // out[0] = 1-in\n    if (N > 1)\n      *products[1] = *array[0]; // out[1] = in\n  }\n  // optimization for n=2: a single multiplication instead of 4\n  else if (N <= 4) {\n    *products[0] = *array[1];           // x1\n    products[0]->multiplyBy(*array[0]); // x1 x0\n\n    *products[1] = *array[0];     // x0\n    *products[1] -= *products[0]; // x0 - x1 x0 = (1-x1)x0\n\n    *products[2] = *array[1];     // x1\n    *products[2] -= *products[0]; // x1 - x1 x0 = x1(1-x0)\n\n    if (N > 3)\n      *products[3] = *products[0]; // x1 x0\n\n    products[0]->addConstant(NTL::ZZ(1)); // 1 +x1 x0\n    *products[0] -= *array[1];            // 1 +x1 x0 -x1\n    *products[0] -= *array[0];            // 1 +x1 x0 -x1 -x0 = (1-x1)(1-x0)\n  } else {                                // split the array into two parts;\n    // first part is highest pow(2) < n, second part is what is left\n\n    long n1 = 1L << (NTL::NumBits(nBits) - 1); // largest power of two <= n\n    if (nBits <= n1)\n      n1 = n1 / 2;               // largest power of two < n\n    long k = 1L << n1;           // size of first part\n    long l = 1L << (nBits - n1); // size of second part\n\n    const Ctxt* ct = array.ptr2nonNull(); // find some non-null Ctxt\n    std::vector<Ctxt> products1(k, Ctxt(ZeroCtxtLike, *ct));\n    std::vector<Ctxt> products2(l, Ctxt(ZeroCtxtLike, *ct));\n\n    // compute first part of the array\n    recursiveProducts(CtPtrs_vectorCt(products1), CtPtrs_slice(array, 0, n1));\n\n    // recursive call on second part of array\n    recursiveProducts(CtPtrs_vectorCt(products2),\n                      CtPtrs_slice(array, n1, nBits - n1));\n\n    // multiplication to get all subset products\n    NTL_EXEC_RANGE(lsize(products), first, last)\n    for (long ii = first; ii < last; ii++) {\n      long j = ii / k;\n      long i = ii - j * k;\n      *products[ii] = products1[i];\n      products[ii]->multiplyBy(products2[j]);\n    }\n    NTL_EXEC_RANGE_END\n  }\n}\n\nstatic double pow2_double(long n) // compute 2^n as double\n{\n  double res = 1;\n  long abs_n = std::labs(n);\n\n  for (long i = 0; i < abs_n; i++)\n    res *= 2;\n  if (n < 0)\n    res = 1 / res;\n  return res;\n}\n\n} // namespace helib\n", "meta": {"hexsha": "ba2b2e72653d18095fb339a6f1ea1a017452b91c", "size": 10454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tableLookup.cpp", "max_stars_repo_name": "jatanloya/HElib-PSI", "max_stars_repo_head_hexsha": "b5ec2844216ac87f1e20542e31ebb98363c14a6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1360.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T23:57:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T01:25:28.000Z", "max_issues_repo_path": "src/tableLookup.cpp", "max_issues_repo_name": "felipeturing/HElib", "max_issues_repo_head_hexsha": "6b9ae8b5ab43af3b566598c095d4edaba6d6a775", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 226.0, "max_issues_repo_issues_event_min_datetime": "2015-01-13T08:07:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T09:26:24.000Z", "max_forks_repo_path": "src/tableLookup.cpp", "max_forks_repo_name": "felipeturing/HElib", "max_forks_repo_head_hexsha": "6b9ae8b5ab43af3b566598c095d4edaba6d6a775", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 402.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T04:14:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T00:50:34.000Z", "avg_line_length": 36.6807017544, "max_line_length": 80, "alphanum_fraction": 0.6184235699, "num_tokens": 3009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4208930230309941}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_REVERSEBITS_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_REVERSEBITS_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/function/simd/bitwise_and.hpp>\n#include <boost/simd/function/simd/bitwise_cast.hpp>\n#include <boost/simd/function/simd/bitwise_or.hpp>\n#include <boost/simd/function/simd/shift_left.hpp>\n#include <boost/simd/function/simd/shr.hpp>\n#include <boost/simd/constant/ratio.hpp>\n#include <boost/dispatch/meta/as_integer.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD(reversebits_\n                          , (typename A0, typename X)\n                          , bd::cpu_\n                          , bs::pack_<bd::ints8_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        using utype = bd::as_integer_t<A0, unsigned>;\n        utype v = bitwise_cast<utype>(a0);\n        const utype m1  = utype(0x55); //binary: 0101...\n        const utype m2  = utype(0x33); //binary: 00110011..\n        const utype m4  = utype(0x0f); //binary:  4 zeros,  4 ones ...\n        // swap odd and even bits\n        v = bitwise_or(bitwise_and(shr(v, 1), m1), shift_left(bitwise_and(v, m1), 1));\n        // swap consecutive pairs\n        v = bitwise_or(bitwise_and(shr(v, 2), m2), shift_left(bitwise_and(v, m2), 2));\n        // swap nibbles ...\n        v = bitwise_or(bitwise_and(shr(v, 4), m4), shift_left(bitwise_and(v, m4), 4));\n        return bitwise_cast<A0>(v);\n        }\n   };\n\n   BOOST_DISPATCH_OVERLOAD(reversebits_\n                          , (typename A0, typename X)\n                          , bd::cpu_\n                          , bs::pack_<bd::ints64_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        using utype = bd::as_integer_t<A0, unsigned>;\n        utype v = bitwise_cast<utype>(a0);\n        const utype m1  = utype(0x5555555555555555ull); //binary: 0101...\n        const utype m2  = utype(0x3333333333333333ull); //binary: 00110011..\n        const utype m4  = utype(0x0f0f0f0f0f0f0f0full); //binary:  4 zeros,  4 ones ...\n        const utype m8  = utype(0x00ff00ff00ff00ffull); //binary:  8 zeros,  8 ones ...\n        const utype m16 = utype(0x0000ffff0000ffffull); //binary:  16 zeros,  16 ones ...\n        const utype m32 = utype(0x00000000ffffffffull); //binary:  32 zeros,  32 ones ...\n        // swap odd and even bits\n        v = bitwise_or(bitwise_and(shr(v, 1), m1), shift_left(bitwise_and(v, m1), 1));\n        // swap consecutive pairs\n        v = bitwise_or(bitwise_and(shr(v, 2), m2), shift_left(bitwise_and(v, m2), 2));\n        // swap nibbles ...\n        v = bitwise_or(bitwise_and(shr(v, 4), m4), shift_left(bitwise_and(v, m4), 4));\n        // swap bytes ...\n        v = bitwise_or(bitwise_and(shr(v, 8), m8), shift_left(bitwise_and(v, m8), 8));\n        // swap shorts ...\n        v = bitwise_or(bitwise_and(shr(v, 16), m16), shift_left(bitwise_and(v, m16), 16));\n        // swap ints ...\n        v = bitwise_or(bitwise_and(shr(v, 32), m32), shift_left(bitwise_and(v, m32), 32));\n        return bitwise_cast<A0>(v);\n        }\n   };\n\n   BOOST_DISPATCH_OVERLOAD(reversebits_\n                          , (typename A0, typename X)\n                          , bd::cpu_\n                          , bs::pack_<bd::ints16_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        using utype = bd::as_integer_t<A0, unsigned>;\n        utype v = bitwise_cast<utype>(a0);\n        const utype m1  = utype(0x5555); //binary: 0101...\n        const utype m2  = utype(0x3333); //binary: 00110011..\n        const utype m4  = utype(0x0f0f); //binary:  4 zeros,  4 ones ...\n        const utype m8  = utype(0x00ff); //binary:  8 zeros,  8 ones ...\n        // swap odd and even bits\n        v = bitwise_or(bitwise_and(shr(v, 1), m1), shift_left(bitwise_and(v, m1), 1));\n        // swap consecutive pairs\n        v = bitwise_or(bitwise_and(shr(v, 2), m2), shift_left(bitwise_and(v, m2), 2));\n        // swap nibbles ...\n        v = bitwise_or(bitwise_and(shr(v, 4), m4), shift_left(bitwise_and(v, m4), 4));\n        // swap bytes ...\n        v = bitwise_or(bitwise_and(shr(v, 8), m8), shift_left(bitwise_and(v, m8), 8));\n        return bitwise_cast<A0>(v);\n        }\n   };\n\n   BOOST_DISPATCH_OVERLOAD(reversebits_\n                          , (typename A0, typename X)\n                          , bd::cpu_\n                          , bs::pack_<bd::ints32_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()( const A0& a0) const BOOST_NOEXCEPT\n      {\n        using utype = bd::as_integer_t<A0, unsigned>;\n        utype v = bitwise_cast<utype>(a0);\n        const utype m1  = utype(0x55555555); //binary: 0101...\n        const utype m2  = utype(0x33333333); //binary: 00110011..\n        const utype m4  = utype(0x0f0f0f0f); //binary:  4 zeros,  4 ones ...\n        const utype m8  = utype(0x00ff00ff); //binary:  8 zeros,  8 ones ...\n        const utype m16 = utype(0x0000ffff); //binary:  16 zeros,  16 ones ...\n        // swap odd and even bits\n        v = bitwise_or(bitwise_and(shr(v, 1), m1), shift_left(bitwise_and(v, m1), 1));\n        // swap consecutive pairs\n        v = bitwise_or(bitwise_and(shr(v, 2), m2), shift_left(bitwise_and(v, m2), 2));\n        // swap nibbles ...\n        v = bitwise_or(bitwise_and(shr(v, 4), m4), shift_left(bitwise_and(v, m4), 4));\n        // swap bytes ...\n        v = bitwise_or(bitwise_and(shr(v, 8), m8), shift_left(bitwise_and(v, m8), 8));\n        // swap shorts ...\n        v = bitwise_or(bitwise_and(shr(v, 16), m16), shift_left(bitwise_and(v, m16), 16));\n        return bitwise_cast<A0>(v);\n        }\n   };\n} } }\n\n#endif\n", "meta": {"hexsha": "1dd405fc509fa6b8cef22276b4d0d2169813e2e8", "size": 6380, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/function/reversebits.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/simd/function/reversebits.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/simd/function/reversebits.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.2482269504, "max_line_length": 100, "alphanum_fraction": 0.5650470219, "num_tokens": 1867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4208930153202483}}
{"text": "/*\r\n\tThis file is part of cpp-ethereum.\r\n\r\n\tcpp-ethereum is free software: you can redistribute it and/or modify\r\n\tit under the terms of the GNU General Public License as published by\r\n\tthe Free Software Foundation, either version 3 of the License, or\r\n\t(at your option) any later version.\r\n\r\n\tcpp-ethereum is distributed in the hope that it will be useful,\r\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n\tGNU General Public License for more details.\r\n\r\n\tYou should have received a copy of the GNU General Public License\r\n\talong with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n/** @file BasicGasPricer.cpp\r\n * @author Gav Wood <i@gavwood.com>\r\n * @date 2015\r\n */\r\n\r\n#pragma warning(push)\r\n#pragma GCC diagnostic push\r\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\r\n#include <boost/math/distributions/normal.hpp>\r\n#pragma warning(pop)\r\n#pragma GCC diagnostic pop\r\n#include \"BasicGasPricer.h\"\r\n#include \"BlockChain.h\"\r\nusing namespace std;\r\nusing namespace dev;\r\nusing namespace dev::eth;\r\n\r\nvoid BasicGasPricer::update(BlockChain const& _bc)\r\n{\r\n\tunsigned c = 0;\r\n\th256 p = _bc.currentHash();\r\n\tm_gasPerBlock = _bc.info(p).gasLimit();\r\n\r\n\tmap<u256, u256> dist;\r\n\tu256 total = 0;\r\n\r\n\t// make gasPrice versus gasUsed distribution for the last 1000 blocks\r\n\twhile (c < 1000 && p)\r\n\t{\r\n\t\tBlockHeader bi = _bc.info(p);\r\n\t\tif (bi.transactionsRoot() != EmptyTrie)\r\n\t\t{\r\n\t\t\tauto bb = _bc.block(p);\r\n\t\t\tRLP r(bb);\r\n\t\t\tBlockReceipts brs(_bc.receipts(bi.hash()));\r\n\t\t\tsize_t i = 0;\r\n\t\t\tfor (auto const& tr: r[1])\r\n\t\t\t{\r\n\t\t\t\tTransaction tx(tr.data(), CheckTransaction::None);\r\n\t\t\t\tu256 gu = brs.receipts[i].cumulativeGasUsed();\r\n\t\t\t\tdist[tx.gasPrice()] += gu;\r\n\t\t\t\ttotal += gu;\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tp = bi.parentHash();\r\n\t\t++c;\r\n\t}\r\n\r\n\t// fill m_octiles with weighted gasPrices\r\n\tif (total > 0)\r\n\t{\r\n\t\tm_octiles[0] = dist.begin()->first;\r\n\r\n\t\t// calc mean\r\n\t\tu256 mean = 0;\r\n\t\tfor (auto const& i: dist)\r\n\t\t\tmean += i.first * i.second;\r\n\t\tmean /= total;\r\n\r\n\t\t// calc standard deviation\r\n\t\tu256 sdSquared = 0;\r\n\t\tfor (auto const& i: dist)\r\n\t\t\tsdSquared += i.second * (i.first - mean) * (i.first - mean);\r\n\t\tsdSquared /= total;\r\n\r\n\t\tif (sdSquared)\r\n\t\t{\r\n\t\t\tlong double sd = sqrt(sdSquared.convert_to<long double>());\r\n\t\t\tlong double normalizedSd = sd / mean.convert_to<long double>();\r\n\r\n\t\t\t// calc octiles normalized to gaussian distribution\r\n\t\t\tboost::math::normal gauss(1.0, (normalizedSd > 0.01) ? normalizedSd : 0.01);\r\n\t\t\tfor (size_t i = 1; i < 8; i++)\r\n\t\t\t\tm_octiles[i] = u256(mean.convert_to<long double>() * boost::math::quantile(gauss, i / 8.0));\r\n\t\t\tm_octiles[8] = dist.rbegin()->first;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfor (size_t i = 0; i < 9; i++)\r\n\t\t\t\tm_octiles[i] = (i + 1) * mean / 5;\r\n\t\t}\r\n\t}\r\n}\r\n", "meta": {"hexsha": "a9e1925416ee0a6ec704f5fb070c64559492fbe3", "size": 2801, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/contract/libethereum/BasicGasPricer.cpp", "max_stars_repo_name": "iTondy/gkccash_core", "max_stars_repo_head_hexsha": "f12f12ca9cc6605e338b4171ffe97072a5b4b57d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 66.0, "max_stars_repo_stars_event_min_datetime": "2020-04-20T14:52:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T11:49:33.000Z", "max_issues_repo_path": "src/contract/libethereum/BasicGasPricer.cpp", "max_issues_repo_name": "iTondy/gkccash_core", "max_issues_repo_head_hexsha": "f12f12ca9cc6605e338b4171ffe97072a5b4b57d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2020-04-21T05:19:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-23T07:20:01.000Z", "max_forks_repo_path": "src/contract/libethereum/BasicGasPricer.cpp", "max_forks_repo_name": "iTondy/gkccash_core", "max_forks_repo_head_hexsha": "f12f12ca9cc6605e338b4171ffe97072a5b4b57d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2020-04-20T16:03:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-12T04:11:04.000Z", "avg_line_length": 27.7326732673, "max_line_length": 97, "alphanum_fraction": 0.6479828633, "num_tokens": 802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.42072783475438463}}
{"text": "// C++ standard library headers\n#include <algorithm>\n#include <cmath>\n#include <cstdlib>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <vector>\n\n// Boost headers\n#include <boost/math/interpolators/pchip.hpp>\n#include <boost/math/quadrature/tanh_sinh.hpp>\n\n// triumf++ headers\n#include <triumf/bnmr/nuclei.hpp>\n#include <triumf/nmr/dipole_dipole.hpp>\n#include <triumf/nmr/nuclei.hpp>\n#include <triumf/numpy.hpp>\n#include <triumf/srim/pdf.hpp>\n#include <triumf/superconductivity/bcs.hpp>\n#include <triumf/superconductivity/pippard.hpp>\n\n// ROOT headers\n#include <ROOT/RCsvDS.hxx>\n#include <ROOT/RDF/RInterface.hxx>\n#include <ROOT/RDataFrame.hxx>\n#include <TCanvas.h>\n#include <TGraph.h>\n\n//\ndouble slr_fcn(double d, double R_0, double d_0) {\n  // return d < d_0 ? 1.5 * R_0 : R_0 * std::exp((d - d_0) / (10.0 * d_0));\n  return d < d_0 ? 1.0 * R_0 : 0.5 * R_0;\n}\n\n/// model slr rate\ntemplate <typename T = double>\nT slr_rate_z(T z, T temperature, T critical_temperature, T gap_meV, T xi_0,\n             T mean_free_path, T lambda_0, T exponent, T applied_field,\n             T dipole_field, T correlation_rate, T slr_constant, T slr_exponent,\n             T surface_thickness, T surface_rate) {\n  // correct depth for the surface layer\n  T _z_ = z - surface_thickness;\n  if (_z_ < 0.0) {\n    return surface_rate;\n  } else {\n    // calculate the local field from the screening profile\n    T screened_field =\n        temperature > critical_temperature\n            ? applied_field\n            : triumf::superconductivity::pippard::field_penetration<T>(\n                  _z_, temperature, critical_temperature, gap_meV, xi_0,\n                  mean_free_path, lambda_0, exponent, applied_field);\n    // calculate the dipole-dipole SLR rate in the superconducting state\n    T dd_rate = triumf::nmr::dipole_dipole::slr_rate<double>(\n        screened_field, dipole_field, correlation_rate,\n        triumf::bnmr::nuclei::lithium_8<T>::gyromagnetic_ratio(),\n        triumf::nmr::nuclei::niobium_93<T>::gyromagnetic_ratio());\n    // calculate the SLR rate in the normal state\n    T ns_rate = slr_constant * std::pow(temperature, slr_exponent);\n    // return the \"surface\" contribution at shallow depths\n    return dd_rate + ns_rate;\n  }\n}\n\nconst double TEMPERATURE = 2.5;\nconst double T_C = 9.25;\nconst double D_0 = triumf::superconductivity::bcs::gap_meV<double>(TEMPERATURE);\nconst double XI_0 = 38.0;\nconst double ELL = 1e4;\nconst double LAMBDA_0 = 40.0;\nconst double EXPONENT = 4.0;\nconst double B_0 = 0.02;\nconst double B_D = 5e-5;\nconst double NU_C = 0.1 / 23.8e-6;\nconst double SLR_C = 0.75;\nconst double SLR_N = 1.0;\nconst double SURFACE_THICKNESS = 5.0;\nconst double SURFACE_RATE = 10.0;\n\nconstexpr double GLOBAL_R_0 = 1.0;\nconstexpr double GLOBAL_D_0 = 15.0;\n\n//\ntemplate <typename T = double> class DepthAverage {\npublic:\n  // constructor\n  DepthAverage(const std::string &csv_filename) {\n    // read the data into a ROOT DataFrame...\n    auto df = ROOT::RDF::MakeCsvDataFrame(csv_filename);\n    // ...and extract the values\n    _energy = df.Take<T>(\"Energy (keV)\").GetValue();\n    _alpha = df.Take<T>(\"Alpha\").GetValue();\n    _alpha_error = df.Take<T>(\"Alpha Error\").GetValue();\n    _beta = df.Take<T>(\"Beta\").GetValue();\n    _beta_error = df.Take<T>(\"Beta Error\").GetValue();\n    _z_max = df.Take<T>(\"Max (nm)\").GetValue();\n    _z_max_error = df.Take<T>(\"Max Error (nm)\").GetValue();\n  };\n\n  //\n  T energy_min() {\n    return *std::min_element(_energy.begin(), _energy.end()) +\n           std::sqrt(std::numeric_limits<T>::epsilon());\n  };\n\n  //\n  T energy_max() {\n    return *std::max_element(_energy.begin(), _energy.end()) -\n           std::sqrt(std::numeric_limits<T>::epsilon());\n  };\n\n  //\n  T alpha(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>> alpha_interpolator(\n        std::move(std::vector<T>(_energy)), std::move(std::vector<T>(_alpha)));\n    return alpha_interpolator(energy_keV);\n  };\n\n  //\n  T beta(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>> beta_interpolator(\n        std::move(std::vector<T>(_energy)), std::move(std::vector<T>(_beta)));\n    return beta_interpolator(energy_keV);\n  };\n\n  //\n  T z_max(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>> z_max_interpolator(\n        std::move(std::vector<T>(_energy)), std::move(std::vector<T>(_z_max)));\n    return z_max_interpolator(energy_keV);\n  };\n\n  //\n  T z_average(T energy_keV) {\n    T a = alpha(energy_keV);\n    T b = beta(energy_keV);\n    T zm = z_max(energy_keV);\n    return zm * a / (a + b);\n  };\n  \n  /*\n  // depth-averaging using numeric integration\n  T operator()(T energy_keV) {\n    // T a = alpha(energy_keV);\n    // T b = beta(energy_keV);\n    // T zm = z_max(energy_keV);\n    static boost::math::quadrature::tanh_sinh<T> integrator;\n    auto integrand = [&](T z) {\n      // return slr_fcn(z, GLOBAL_R_0, GLOBAL_D_0) *\n      return slr_rate_z<T>(z, TEMPERATURE, T_C, D_0, XI_0, ELL, LAMBDA_0,\n                           EXPONENT, B_0, B_D, NU_C, SLR_C, SLR_N,\n                           SURFACE_THICKNESS, SURFACE_RATE) *\n             triumf::srim::pdf::modified_beta<T>(\n                 z, alpha(energy_keV), beta(energy_keV), z_max(energy_keV));\n    };\n    T Q =\n        integrator.integrate(integrand, 0.0, z_max(energy_keV),\n                             std::cbrt(std::numeric_limits<double>::epsilon()));\n    return Q;\n  };\n  */\n\n  // depth-averaging using \"histogram\" summation\n  T operator()(T energy_keV) {\n    constexpr std::size_t n = 201;\n    // bin edges\n    std::vector<T> z_edge =\n        triumf::numpy::linspace<T>(0.0, z_max(energy_keV), n);\n    // bin widths - adjust ranges by one for \"correct\" size\n    std::vector<T> dz(n - 1);\n    std::adjacent_difference(std::begin(z_edge) + 1, std::end(z_edge),\n                             std::begin(dz));\n    // bin centres\n    std::vector<T> z(n - 1);\n    // probabilities\n    std::vector<T> p_z(n - 1);\n    std::vector<T> weights(n - 1);\n    std::vector<T> slr_rates(n - 1);\n\n    for (std::size_t i = 0; i < z.size(); ++i) {\n      z.at(i) = z_edge.at(i) + 0.5 * dz.at(i);\n      p_z.at(i) = triumf::srim::pdf::modified_beta<T>(\n          z.at(i), alpha(energy_keV), beta(energy_keV), z_max(energy_keV));\n      // std::cout << \"p(\" << z.at(i) << \" nm ) = \" << p_z.at(i) << \" nm^-1\\n\";\n      weights.at(i) = dz.at(i) * p_z.at(i);\n      // slr_rates.at(i) = slr_fcn(z.at(i), GLOBAL_R_0, GLOBAL_D_0);\n      slr_rates.at(i) = slr_rate_z<T>(z.at(i), TEMPERATURE, T_C, D_0, XI_0, ELL,\n                                      LAMBDA_0, EXPONENT, B_0, B_D, NU_C, SLR_C,\n                                      SLR_N, SURFACE_THICKNESS, SURFACE_RATE);\n    }\n\n    T sum_weights = std::reduce(std::begin(weights), std::end(weights));\n    // std::cout << \"sum_weights = \" << sum_weights << \"\\n\";\n    T sum_weights_slr = std::transform_reduce(\n        std::begin(weights), std::end(weights), std::begin(slr_rates), 0.0);\n    // std::cout << \"sum_weights_slr = \" << sum_weights_slr << \"\\n\";\n    T weighted_average = sum_weights_slr / sum_weights;\n    return weighted_average;\n  };\n\nprivate:\n  // vectors of data from csv file\n  std::vector<T> _energy;\n  std::vector<T> _alpha;\n  std::vector<T> _alpha_error;\n  std::vector<T> _beta;\n  std::vector<T> _beta_error;\n  std::vector<T> _z_max;\n  std::vector<T> _z_max_error;\n};\n\nvoid test_depth_averaging() {\n  const double alpha = 2.5;\n  const double beta = 4.5;\n  const double z_max = 250.0;\n\n  //\n  // const double R_0 = 10.0;\n  // const double d_0 = 25.0; // (1.0 / 6.0) * z_max;\n\n  // bin edges\n  std::vector<double> z_edge = triumf::numpy::linspace<double>(0.0, z_max, 201);\n  // bin widths - adjust ranges by one for \"correct\" size\n  std::vector<double> dz(z_edge.size() - 1);\n  std::adjacent_difference(std::begin(z_edge) + 1, std::end(z_edge),\n                           std::begin(dz));\n  // bin centres\n  std::vector<double> z(z_edge.size() - 1);\n  // probabilities\n  std::vector<double> p_z(z_edge.size() - 1);\n\n  std::vector<double> weights(z_edge.size() - 1);\n\n  std::vector<double> slr_rates(z_edge.size() - 1);\n\n  std::cout << std::setprecision(16);\n  std::cout << std::fixed;\n\n  for (std::size_t i = 0; i < z.size(); ++i) {\n    z.at(i) = z_edge.at(i) + 0.5 * dz.at(i);\n    p_z.at(i) = triumf::srim::pdf::modified_beta(z.at(i), alpha, beta, z_max);\n    // std::cout << \"p(\" << z.at(i) << \" nm ) = \" << p_z.at(i) << \" nm^-1\\n\";\n\n    weights.at(i) = dz.at(i) * p_z.at(i);\n    // slr_rates.at(i) = slr_fcn(z.at(i), GLOBAL_R_0, GLOBAL_D_0);\n    slr_rates.at(i) = slr_rate_z<double>(\n        z.at(i), TEMPERATURE, T_C, D_0, XI_0, ELL, LAMBDA_0, EXPONENT, B_0, B_D,\n        NU_C, SLR_C, SLR_N, SURFACE_THICKNESS, SURFACE_RATE);\n  }\n\n  double sum_weights = std::reduce(std::begin(weights), std::end(weights));\n  std::cout << \"sum_weights = \" << sum_weights << \"\\n\";\n\n  double sum_weights_slr = std::transform_reduce(\n      std::begin(weights), std::end(weights), std::begin(slr_rates), 0.0);\n  std::cout << \"sum_weights_slr = \" << sum_weights_slr << \"\\n\";\n\n  double weighted_average = sum_weights_slr / sum_weights;\n  // std::cout << \"weighted_average = \" << weighted_average << \"\\n\";\n\n  /*\n  for (std::size_t i = 0; i < z.size(); ++i) {\n    p_z.at(i) = triumf::srim::pdf::modified_beta(z.at(i), alpha, beta, z_max);\n    std::cout << \"p(\" << z.at(i) << \" nm ) = \" << p_z.at(i) << \" nm^-1\\n\";\n  }\n  */\n\n  // double sum = std::reduce(std::begin(p_z), std::end(p_z));\n  // std::cout << \"sum = \" << sum << \"\\n\";\n\n  //\n\n  /*\n  std::cout << dz.size() << \"\\n\";\n  for (auto &bw : dz) {\n    std::cout << bw << \"\\n\";\n  }\n  */\n\n  /*\n  std::transform(std::begin(z), std::end(z), std::begin(p_z), [&](double d) {\n    return triumf::srim::pdf::modified_beta(z.at(i), alpha, beta, z_max);\n  });\n  */\n\n  TCanvas *c_p = new TCanvas();\n\n  TGraph *g_p = new TGraph(z.size(), z.data(), p_z.data());\n  g_p->SetTitle(\";Depth (nm);Stopping probability (nm^{-1})\");\n  g_p->SetMarkerStyle(kFullCircle);\n  g_p->SetMarkerColor(kBlack);\n  g_p->Draw(\"AP\");\n\n  TCanvas *c_slr = new TCanvas();\n\n  TGraph *g_slr = new TGraph(z.size(), z.data(), slr_rates.data());\n  g_slr->SetTitle(\";Depth (nm);Model SLR Rate (s^{-1})\");\n  g_slr->SetMarkerStyle(kFullCircle);\n  g_slr->SetMarkerColor(kBlack);\n  g_slr->Draw(\"AP\");\n  // g_slr->GetYaxis()->SetRangeUser(0, 10);\n  \n  // logarithmic scale\n  // gPad->SetLogx();\n  gPad->SetLogy();\n\n  // tick marks on all sides of the plot\n  gPad->SetTickx();\n  gPad->SetTicky();\n\n  // grid lines\n  gPad->SetGridx();\n  gPad->SetGridy();\n\n  c_slr->Print(\"toy_depth_model.pdf\", \"EmbedFonts\");\n\n  // use numeric integration!\n  // the \"summation\" approach (which is error-prone) converges to this answer\n  // when the number of \"bins\" becomes large (e.g., ~1000).\n  static boost::math::quadrature::tanh_sinh<double> slr_integrator;\n  auto slr_integrand = [&](double d) {\n    return triumf::srim::pdf::modified_beta(d, alpha, beta, z_max) *\n           slr_fcn(d, GLOBAL_R_0, GLOBAL_D_0);\n    /*\n    slr_rate_z<double>(d, TEMPERATURE, T_C, D_0, XI_0, ELL, LAMBDA_0,\n                       EXPONENT, B_0, B_D, NU_C, SLR_C, SLR_N,\n                       SURFACE_THICKNESS, SURFACE_RATE);\n    */\n  };\n  double Q = slr_integrator.integrate(slr_integrand, 0.0, z_max);\n  std::cout << \"weighted_average    = \" << weighted_average << \"\\n\";\n  std::cout << \"numeric_integration = \" << Q << \"\\n\";\n  double tolerance = std::sqrt(std::numeric_limits<double>::epsilon());\n  std::cout << \"tolerance           = \" << tolerance << \"\\n\";\n\n  DepthAverage<double> da(\"srim_profile_8li_nb_fitpar.csv\");\n  // double delta = 0.001;\n  std::vector<double> energies =\n      triumf::numpy::linspace<double>(da.energy_min(), da.energy_max(), 100);\n  std::vector<double> rates;\n  std::vector<double> mean_depths;\n\n  auto time_start = std::chrono::steady_clock::now();\n  for (auto &e : energies) {\n    rates.push_back(da(e));\n    mean_depths.push_back(da.z_average(e));\n  }\n  auto time_stop = std::chrono::steady_clock::now();\n\n  TCanvas *c_r = new TCanvas();\n\n  TGraph *g_r = new TGraph(energies.size(), energies.data(), rates.data());\n  g_r->SetMarkerStyle(kFullCircle);\n  g_r->SetMarkerColor(kRed);\n  g_r->SetTitle(\";Energy (keV);Depth averaged SLR rate 1/T_{1} (s^{-1})\");\n\n  g_r->Draw(\"AP\");\n  // g_r->GetYaxis()->SetRangeUser(0, 10);\n  \n  // logarithmic scale\n  // gPad->SetLogx();\n  gPad->SetLogy();\n\n  // tick marks on all sides of the plot\n  gPad->SetTickx();\n  gPad->SetTicky();\n\n  // grid lines\n  gPad->SetGridx();\n  gPad->SetGridy();\n\n  c_r->Print(\"toy_depth_average.pdf\", \"EmbedFonts\");\n\n  TCanvas *c_rz = new TCanvas();\n\n  TGraph *g_rz =\n      new TGraph(mean_depths.size(), mean_depths.data(), rates.data());\n  g_rz->SetMarkerStyle(kFullCircle);\n  g_rz->SetMarkerColor(kRed);\n  g_rz->SetTitle(\";z_{average} (nm);Depth averaged SLR rate 1/T_{1} (s^{-1})\");\n\n  g_rz->Draw(\"AP\");\n  // g_rz->GetYaxis()->SetRangeUser(0, 10);\n\n  c_rz->Print(\"toy_depth_average2.pdf\", \"EmbedFonts\");\n\n  std::chrono::duration<double> elapsed_seconds = time_stop - time_start;\n  std::cout << \"Elapsed time: \" << elapsed_seconds.count() << \" (s)\\n\";\n}\n\n#ifndef __CLING__\nint main() {\n  test_depth_averaging();\n  return EXIT_SUCCESS;\n}\n#endif\n", "meta": {"hexsha": "60f378585d575b626612d3f676e9c6797124e66b", "size": 13201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/test_depth_averaging.cpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/test_depth_averaging.cpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/test_depth_averaging.cpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0852130326, "max_line_length": 80, "alphanum_fraction": 0.6215438224, "num_tokens": 4122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8615382058759128, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.42067480034217253}}
{"text": "#include <iostream>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/timer.hpp>\n\n\n#include <vector>\n#include <math.h>\n\n#include \"NRGclasses.hpp\"\n\n\nvoid OneChQS_UpdateQm1fQ(CNRGmatrix &Qm1fNQ,CNRGarray Aeig, \n\t\t\t CNRGbasisarray Abasis){\n\n\n  boost::numeric::ublas::matrix<double> Mtemp;\n  boost::numeric::ublas::matrix<double> fnw;\n\n  int icount=0;\n\n  Qm1fNQ.ClearAll();\n\n  Qm1fNQ.SyncNRGarray(Aeig);\n\n  // Find blocks such that Q'=Q+1, S'=S+-1/2\n\n  for (int ii=0;ii<Aeig.NumBlocks();ii++)\n    {\n      double Qi=Aeig.GetQNumber(ii,0);\n      double Si=Aeig.GetQNumber(ii,1);\n\n      int Nstibl=Aeig.GetBlockSize(ii);\n\n      for (int jj=ii+1;jj<Aeig.NumBlocks();jj++)\n\t{\n      \n\t  double Qj=Aeig.GetQNumber(jj,0);\n\t  double Sj=Aeig.GetQNumber(jj,1);\n\n\t  int Nstjbl=Aeig.GetBlockSize(jj);\n\n\t  int kkp=0;\n\t  //if (Sj==Si+0.5) kkp=23;\n\t  //if (Sj==Si-0.5) kkp=32;\n\t  if (fabs(Sj-(Si+0.5))<1.0E-10) kkp=23;\n\t  if (fabs(Sj-(Si-0.5))<1.0E-10) kkp=32;\n\n\t  //\t  if ( (Qj==Qi+1.0)&&( kkp!=0 ) )\n\t  if ( ( fabs(Qj-(Qi+1.0))<1.0E-10 )&&( kkp!=0 ) )\n\t    {\n\n\t      cout << \"  Setting up Block i : \" << ii \n\t\t   << \" (size \" <<  Nstibl \n\t\t   << \") x Block j \" << jj\n\t\t   << \" (size \" << Nstjbl << \")\" << endl;\n\n \t      Qm1fNQ.MatBlockMap.push_back(ii);\n \t      Qm1fNQ.MatBlockMap.push_back(jj);\n\t      Qm1fNQ.MatBlockBegEnd.push_back(icount);\n\t      icount+=Nstibl*Nstjbl;\n\t      Qm1fNQ.MatBlockBegEnd.push_back(icount-1);\n\n\n\n\t      // Sets the uBLAS matrix for Z_QS(iblock)\n\t      // Sets the uBLAS matrix for Z_QS(jblock)\n\n\n\t      cout << \"    Setting up BLAS matrices...\" << endl;\n// \t      boost::numeric::ublas::matrix<double> Zibl=Aeig.EigVec2BLAS(ii);\n// \t      boost::numeric::ublas::matrix<double> Zjbl=Aeig.EigVec2BLAS(jj);\n\n\t      boost::numeric::ublas::matrix<double> Zibl(Nstibl,Nstibl);\n\t      boost::numeric::ublas::matrix<double> Zjbl(Nstjbl,Nstjbl);\n\t      Zibl=Aeig.EigVec2BLAS(ii);\n\t      Zjbl=Aeig.EigVec2BLAS(jj);\n\n\n\t      cout << \"    ...Zs done ...\" << endl;\n\t      // Sets the uBLAS matrix <type|fn|type^'> with a bunch of zeroes\n\n\t      boost::numeric::ublas::matrix<double> fnbasis (Nstibl,Nstjbl);\n\n\t      // Check time\n\t      boost::timer t;\n\t      double time_elapsed;\n\n\n\t      // Loop on each block\n\t      int istbl=0;\n\t      for (int ist=Abasis.GetBlockLimit(ii,0);\n\t\t   ist<=Abasis.GetBlockLimit(ii,1);ist++)\n\t\t{\n\t\t  int typei=Abasis.iType[ist];\n\t\t  int stcfi=Abasis.StCameFrom[ist];\n\t\t  //cout << \"Type i : \" << typei << endl;\n\t\t  int jstbl=0;\n\t\t  for (int jst=Abasis.GetBlockLimit(jj,0);\n\t\t       jst<=Abasis.GetBlockLimit(jj,1);jst++)\n\t\t    {\n\t\t      int typej=Abasis.iType[jst];\n\t\t      int stcfj=Abasis.StCameFrom[jst];\n\t\t      //cout << \"Type j : \" << typej << endl;\n\t\t      // setting MatBlockMap\n//  \t\t      Qm1fNQ.MatBlockMap.push_back(ii);\n//  \t\t      Qm1fNQ.MatBlockMap.push_back(jj);\n\n\t\t      fnbasis(istbl,jstbl)=0.0;\n\n\t\t      // Both basis sates have to originate from the same \n\t\t      // previous state! Otherwise, zero.\n\n\t\t      if (stcfi==stcfj)\n\t\t\t{\n\t\t\t  if (  \n\t\t\t      ( (typei==1) && (typej==2) &&(kkp==23) )||\n\t\t\t      ( (typei==1) && (typej==3) &&(kkp==32) )\n\t\t\t      ) \n\t\t\t    fnbasis(istbl,jstbl)=1.0;\n\t\t\t  if ( (typej==4)&&(typei==2)&&(kkp==32) )\n\t\t\t    fnbasis(istbl,jstbl)=-sqrt((2.0*Si+1.0)/(2.0*Si));\n\t\t\t  if ( (typej==4)&&(typei==3)&&(kkp==23) )\n\t\t\t    fnbasis(istbl,jstbl)=sqrt((2.0*Si+1.0)/(2.0*Si+2.0)); \n\t\t\t}\n\t\t      //cout << \"fn(\" << istbl << \",\" << jstbl << \") = \";\n\t\t      //cout << fnbasis(istbl,jstbl) << endl;\n\n\t\t      jstbl++;\n\t\t    }\n\t\t  istbl++;\n\n\t\t}\n      \n\t      cout << \"    ...fnbasis done.\" << endl;\n\n\t      // Multiply the 3 of them. Zi has eigvecs in ROWS!\n\n\t      cout << \"    Multiplying BLAS matrices... \" << endl;\n\n//  \t      boost::numeric::ublas::matrix<double> Mtemp=prod(fnbasis,trans(Zjbl));\n//  \t      boost::numeric::ublas::matrix<double> fnw=prod (Zibl,Mtemp);\n// \t      fnw=prod (Zibl,Mtemp);\n\n\t      //Mtemp.resize(Nstibl,Nstjbl);\n\t      fnw.resize(Nstibl,Nstjbl);\n \t      //noalias(Mtemp)=prod(fnbasis,trans(Zjbl));\n\t      //cout << \"    ...one done...\" << endl;\n \t      //noalias(fnw)=prod (Zibl, Mtemp );\n\n\t      t.restart();\n \t      noalias(fnw)=prod (Zibl, \n\t\t\tboost::numeric::ublas::matrix<double>(prod(fnbasis,trans(Zjbl))) );\n\t      time_elapsed=t.elapsed();\n\t      cout << \"    ...done. Elapsed time:\" << time_elapsed << endl;\n\n\n\n//   \t      cout << \"Z(i=\"<<ii<<\")  : \" <<  Zibl << endl;\n//   \t      cout << \"Z(j=\"<<jj<<\")  : \" <<  Zjbl << endl;\n//    \t      cout << \"fbasis   :\" <<  fnbasis << endl;\n//    \t      cout << \"Zi.fbasis.ZjT : \" <<  fnw << endl;\n\n\n\t      // Add to Qm1fNQ\n\t      for (int ii=0;ii<fnw.size1();ii++)\n\t\t{\n\t\t  for (int jj=0;jj<fnw.size2();jj++)\n\t\t    {\n\t\t      Qm1fNQ.MatEl.push_back(fnw(ii,jj));\n\t\t    }\n\t\t}\n\n\t    }\n\t}\n      //Loop in jblock\n    }\n  // Loop in iblock\n\n\n\n\n//    cout << \"Qm1fNQ MatBlockMap : \";\n//    for (int ii=0;ii<Qm1fNQ.MatBlockMap.size();ii++)\n//      cout << Qm1fNQ.MatBlockMap[ii] << \" \";\n//    cout << endl;\n\n// Too slow.\n//     Qm1fNQ.FilterMap_SetBegEnd();\n\n\n//    cout << \"Filtered Qm1fNQ MatBlockMap : \";\n//    for (int ii=0;ii<Qm1fNQ.MatBlockMap.size();ii++)\n//      cout << Qm1fNQ.MatBlockMap[ii] << \" \";\n//    cout << endl;\n//    cout << \"Qm1fNQ MatBlockBegEnd : \";\n//    for (int ii=0;ii<Qm1fNQ.MatBlockBegEnd.size();ii++)\n//      cout << Qm1fNQ.MatBlockBegEnd[ii] << \" \";\n//    cout << endl;\n\n\n//   for (int ibl=0;ibl<Qm1fNQ.NumMatBlocks();ibl++)\n//     {\n//       Qm1fNQ.PrintMatBlock(ibl);\n//     }\n\n}\n\n\n", "meta": {"hexsha": "37332eed7bbe10f154f9f802ed1e70156d8d7959", "size": 5545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/OneChQS/OneChQS_UpdateMatricesOLD_II.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/OneChQS/OneChQS_UpdateMatricesOLD_II.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OneChQS/OneChQS_UpdateMatricesOLD_II.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1556603774, "max_line_length": 81, "alphanum_fraction": 0.5448151488, "num_tokens": 2011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8479677583778258, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.420671572521527}}
{"text": "// g2o - General Graph Optimization\n// Copyright (C) 2011 R. Kuemmerle, G.Grisetti, W. Burgard\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright notice,\n//   this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright\n//   notice, this list of conditions and the following disclaimer in the\n//   documentation and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n// IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"closed_form_calibration.h\"\n\n#include \"g2o/types/sclam2d/odometry_measurement.h\"\n\n#include <iostream>\n#include <limits>\n\n#include <Eigen/SVD>\n\n#define SQR(X)\t\t( std::pow(X,2) )\n#define CUBE(X)\t\t( std::pow(X,3) )\n\nnamespace g2o {\n\nbool ClosedFormCalibration::calibrate(const MotionInformationVector& measurements, SE2& laserOffset, Eigen::Vector3d& odomParams)\n{\n  std::vector<VelocityMeasurement, Eigen::aligned_allocator<VelocityMeasurement> > velMeasurements;\n  for (size_t i = 0; i < measurements.size(); ++i) {\n    const SE2& odomMotion = measurements[i].odomMotion;\n    const double& timeInterval = measurements[i].timeInterval;\n    MotionMeasurement mm(odomMotion.translation().x(), odomMotion.translation().y(), odomMotion.rotation().angle(), timeInterval);\n    VelocityMeasurement velMeas = OdomConvert::convertToVelocity(mm);\n    velMeasurements.push_back(velMeas);\n  }\n\n  double J_21, J_22;\n  {\n    Eigen::MatrixXd A(measurements.size(), 2);\n    Eigen::VectorXd x(measurements.size());\n    for (size_t i = 0; i < measurements.size(); ++i) {\n      const SE2& laserMotion = measurements[i].laserMotion;\n      const double& timeInterval = measurements[i].timeInterval;\n      const VelocityMeasurement& velMeas = velMeasurements[i];\n      A(i, 0) = velMeas.vl() * timeInterval;\n      A(i, 1) = velMeas.vr() * timeInterval;\n      x(i) = laserMotion.rotation().angle();\n    }\n    // (J_21, J_22) = (-r_l / b, r_r / b)\n    Eigen::Vector2d linearSolution = (A.transpose() * A).inverse() * A.transpose() * x;\n    //std::cout << linearSolution.transpose() << std::endl;\n    J_21 = linearSolution(0);\n    J_22 = linearSolution(1);\n  }\n\n  // construct M\n  Eigen::Matrix<double, 5, 5> M;\n  M.setZero();\n  for (size_t i = 0; i < measurements.size(); ++i) {\n    const SE2& laserMotion = measurements[i].laserMotion;\n    const double& timeInterval = measurements[i].timeInterval;\n    const VelocityMeasurement& velMeas = velMeasurements[i];\n    Eigen::Matrix<double, 2, 5> L;\n    double omega_o_k = J_21 * velMeas.vl() + J_22 * velMeas.vr();\n    double o_theta_k = omega_o_k * timeInterval;\n    double sx = 1.;\n    double sy = 0.;\n    if (fabs(o_theta_k) > std::numeric_limits<double>::epsilon()) {\n      sx = sin(o_theta_k)       / o_theta_k;\n      sy = (1 - cos(o_theta_k)) / o_theta_k;\n    }\n    double c_x = 0.5 * timeInterval * (-J_21 * velMeas.vl() + J_22 * velMeas.vr()) * sx;\n    double c_y = 0.5 * timeInterval * (-J_21 * velMeas.vl() + J_22 * velMeas.vr()) * sy;\n    L(0, 0) = -c_x;\n    L(0, 1) = 1 - cos(o_theta_k);\n    L(0, 2) = sin(o_theta_k);\n    L(0, 3) = laserMotion.translation().x(); \n    L(0, 4) = -laserMotion.translation().y();\n    L(1, 0) = -c_y;\n    L(1, 1) = - sin(o_theta_k);\n    L(1, 2) = 1 - cos(o_theta_k);\n    L(1, 3) = laserMotion.translation().y(); \n    L(1, 4) = laserMotion.translation().x();\n    M.noalias() += L.transpose() * L;\n  }\n  //std::cout << M << std::endl;\n\n  // compute lagrange multiplier\n  // and solve the constrained least squares problem\n  double m11 = M(0,0);\n  double m13 = M(0,2);\n  double m14 = M(0,3);\n  double m15 = M(0,4);\n  double m22 = M(1,1);\n  double m34 = M(2,3);\n  double m35 = M(2,4);\n  double m44 = M(3,3); \n\n  double a = m11 * SQR(m22) - m22 * SQR(m13);\n  double b = 2*m11 * SQR(m22) * m44 - SQR(m22) * SQR(m14) - 2*m22 * SQR(m13) * m44 - 2*m11 * m22 * SQR(m34) \n    - 2*m11 * m22 * SQR(m35) - SQR(m22) * SQR(m15) + 2*m13 * m22 * m34 * m14 + SQR(m13) * SQR(m34) \n    + 2*m13 * m22 * m35 * m15 + SQR(m13) * SQR(m35);\n  double c = - 2*m13 * CUBE(m35) * m15 - m22 * SQR(m13) * SQR(m44) + m11 * SQR(m22) * SQR(m44) + SQR(m13) * SQR(m35) * m44\n    + 2*m13 * m22 * m34 * m14 * m44 + SQR(m13) * SQR(m34) * m44 - 2*m11 * m22 * SQR(m34) * m44 - 2 * m13 * CUBE(m34) * m14\n    - 2*m11 * m22 * SQR(m35) * m44 + 2*m11 * SQR(m35) * SQR(m34) + m22 * SQR(m14) * SQR(m35) - 2*m13 * SQR(m35) * m34 * m14\n    - 2*m13 * SQR(m34) * m35 * m15 + m11 * std::pow(m34, 4) + m22 * SQR(m15) * SQR(m34) + m22 * SQR(m35) * SQR(m15)\n    + m11 * std::pow(m35, 4) - SQR(m22) * SQR(m14) * m44 + 2*m13 * m22 * m35 * m15 * m44 + m22 * SQR(m34) * SQR(m14)\n    - SQR(m22) * SQR(m15) * m44;\n\n  // solve the quadratic equation\n  double lambda1, lambda2;\n  if(a < std::numeric_limits<double>::epsilon()) {\n    if(b <= std::numeric_limits<double>::epsilon())\n      return false;\n    lambda1 = lambda2 = -c/b;\n  } else {\n    double delta = b*b - 4*a*c;\n    if (delta < 0)\n      return false;\n    lambda1 = 0.5 * (-b-sqrt(delta)) / a;\n    lambda2 = 0.5 * (-b+sqrt(delta)) / a;\n  }\n\n  Eigen::VectorXd x1 = solveLagrange(M, lambda1);\n  Eigen::VectorXd x2 = solveLagrange(M, lambda2);\n  double err1 = x1.dot(M * x1);\n  double err2 = x2.dot(M * x2);\n\n  const Eigen::VectorXd& calibrationResult = err1 < err2 ? x1 : x2;\n  odomParams(0) = - calibrationResult(0) * J_21;\n  odomParams(1) = calibrationResult(0) * J_22;\n  odomParams(2) = calibrationResult(0);\n\n  laserOffset = SE2(calibrationResult(1), calibrationResult(2), atan2(calibrationResult(4), calibrationResult(3)));\n\n  return true;\n}\n\nEigen::VectorXd ClosedFormCalibration::solveLagrange(const Eigen::Matrix<double,5,5>& M, double lambda)\n{\n  // A = M * lambda*W (see paper)\n  Eigen::Matrix<double,5,5> A;\n  A.setZero();\n  A(3,3) = A(4,4) = lambda;\n  A.noalias() += M;\n\n  // compute the kernel of A by SVD\n  Eigen::JacobiSVD< Eigen::Matrix<double,5,5> > svd(A, ComputeFullV);\n  Eigen::VectorXd result = svd.matrixV().col(4);\n  //for (int i = 0; i < 5; ++i)\n  //std::cout << \"singular value \" << i << \" \"  << svd.singularValues()(i) << std::endl;\n  //std::cout << \"kernel base \" << result << std::endl;\n\n  // enforce the conditions\n  // x_1 > 0\n  if (result(0) < 0.)\n    result *= -1;\n  // x_4^2 + x_5^2 = 1\n  double scale = sqrt(pow(result(3), 2) + pow(result(4), 2));\n  result /= scale;\n\n  return result;\n}\n\n} // end namespace\n", "meta": {"hexsha": "d6e11a0acc620fa65ba46047403408ce458b2369", "size": 7228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "g2o/g2o/examples/calibration_odom_laser/closed_form_calibration.cpp", "max_stars_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_stars_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2018-01-18T15:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T23:07:15.000Z", "max_issues_repo_path": "g2o/g2o/examples/calibration_odom_laser/closed_form_calibration.cpp", "max_issues_repo_name": "thecoldviews/ORB_Android", "max_issues_repo_head_hexsha": "942d69269d7bf259fee4702fe5ead1c3fab67352", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-01-31T05:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-26T14:06:53.000Z", "max_forks_repo_path": "g2o/g2o/examples/calibration_odom_laser/closed_form_calibration.cpp", "max_forks_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_forks_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-08-08T12:18:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T08:07:55.000Z", "avg_line_length": 39.9337016575, "max_line_length": 130, "alphanum_fraction": 0.6397343664, "num_tokens": 2383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.42064686763944026}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n\n#include <Utils/DataStructures/OccupiedMolecularOrbitals.h>\n#include <Utils/Scf/LcaoUtils/HFWaveFunctionOverlap.h>\n#include <Eigen/Dense>\n\nnamespace Scine {\nnamespace Utils {\n\nnamespace LcaoUtils {\n\ndouble HFWaveFunctionOverlap::calculateOrthonormalOverlap(const OccupiedMolecularOrbitals& c1,\n                                                          const OccupiedMolecularOrbitals& c2) {\n  // Convert to uhf to make comparison of RHF - UHF possible\n  // TODO: make more efficient if no conversion is needed\n  auto unrestricted1 = c1.toUnrestricted();\n  auto unrestricted2 = c2.toUnrestricted();\n  return unrestrictedOrthonormalOverlap(unrestricted1, unrestricted2);\n}\n\ndouble HFWaveFunctionOverlap::calculateNonOrthonormalOverlap(const OccupiedMolecularOrbitals& c1,\n                                                             const OccupiedMolecularOrbitals& c2, const Eigen::MatrixXd& s) {\n  // Convert to uhf to make comparison of RHF - UHF possible\n  // TODO: make more efficient if no conversion is needed\n  auto unrestricted1 = c1.toUnrestricted();\n  auto unrestricted2 = c2.toUnrestricted();\n  return unrestrictedNonOrthonormalOverlap(unrestricted1, unrestricted2, s);\n}\n\ndouble HFWaveFunctionOverlap::unrestrictedOrthonormalOverlap(const OccupiedMolecularOrbitals& c1,\n                                                             const OccupiedMolecularOrbitals& c2) {\n  double f1 = orthonormalContribution(c1.alphaMatrix(), c2.alphaMatrix());\n  double f2 = orthonormalContribution(c1.betaMatrix(), c2.betaMatrix());\n  // Return a product of determinants:\n  // The determinant of a block diagonal matrix is the product of the determinants of the block\n  return f1 * f2;\n}\n\ndouble HFWaveFunctionOverlap::unrestrictedNonOrthonormalOverlap(const OccupiedMolecularOrbitals& c1,\n                                                                const OccupiedMolecularOrbitals& c2,\n                                                                const Eigen::MatrixXd& s) {\n  double f1 = nonOrthonormalContribution(c1.alphaMatrix(), c2.alphaMatrix(), s);\n  double f2 = nonOrthonormalContribution(c1.betaMatrix(), c2.betaMatrix(), s);\n  // Return a product of determinants:\n  // The determinant of a block diagonal matrix is the product of the determinants of the block\n  return f1 * f2;\n}\n\ndouble HFWaveFunctionOverlap::orthonormalContribution(const Eigen::MatrixXd& m1, const Eigen::MatrixXd& m2) {\n  if (m1.cols() != m2.cols()) {\n    throw std::runtime_error(\"Not possible to calculate overlap between systems with different number of electrons.\");\n  }\n  return (m1.transpose() * m2).determinant();\n}\n\ndouble HFWaveFunctionOverlap::nonOrthonormalContribution(const Eigen::MatrixXd& m1, const Eigen::MatrixXd& m2,\n                                                         const Eigen::MatrixXd& s) {\n  if (m1.cols() != m2.cols()) {\n    throw std::runtime_error(\"Not possible to calculate overlap between systems with different number of electrons.\");\n  }\n  return (m1.transpose() * s * m2).determinant();\n}\n\n} // namespace LcaoUtils\n} // namespace Utils\n} // namespace Scine\n", "meta": {"hexsha": "c4a76ea9a4e7fdff8d4f0dd71b4db0d4f9d7cf3e", "size": 3298, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Scf/LcaoUtils/HFWaveFunctionOverlap.cpp", "max_stars_repo_name": "DockBio/utilities", "max_stars_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Utils/Scf/LcaoUtils/HFWaveFunctionOverlap.cpp", "max_issues_repo_name": "DockBio/utilities", "max_issues_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Utils/Utils/Scf/LcaoUtils/HFWaveFunctionOverlap.cpp", "max_forks_repo_name": "DockBio/utilities", "max_forks_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.8055555556, "max_line_length": 125, "alphanum_fraction": 0.6791995149, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4204928846683308}}
{"text": "/* ScaFES\n * Copyright (c) 2011-2015, ZIH, TU Dresden, Federal Republic of Germany.\n * For details, see the files COPYING and LICENSE in the base directory\n * of the package.\n */\n\n/**\n *  @file EMFDTD.hpp\n *\n *  @brief Implementation of EMFDTD.\n */\n\n#ifndef EMFDTD_HPP_\n#define EMFDTD_HPP_\n\n#include <fstream>\n#include <string>\n#include <vector>\n\n#include <boost/property_tree/ini_parser.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/serialization/vector.hpp>\n\n#include <ScaFES.hpp>\n\n#include \"physical_constants.hpp\"\n#include \"geometry/IndicatorEllipsoid.hpp\"\n#include \"CPMLParams.hpp\"\n#include \"stencils/CompleteCPMLCurlStencil.hpp\"\n\n#include \"sources/ModulatedGaussianSource.hpp\"\n#include \"conversion.hpp\"\n\n/*******************************************************************************\n ******************************************************************************/\n/**\n * \\class EMFDTDng\n *  @brief Class for discretized EM problem.\n *\n * \\section EMFDTDng3D EMFDTD at ellipsoid.\n *\n * The EM problem is discretized using the FDTD method (Finite Differences\n * at the Time Domain).\n *\n * The workflow for running the simulation is as follows:\n *\n *      - Set up the computational domain within in the source code.\n *      - Recompile source code.\n *      - Set up EM parameters within the ini file.\n *      - Run simulation.\n *\n * Parameters of the PML (perfectly matched layers):\n *\n *      [PML]\n        d=10\n        m_a=1.\n        m=3\n        k_max=1.\n        s_max=0.01222\n        a_max=1.e-3\n\n * Location and parameters of the source.\n *\n        [source]\n        ; Location within computational domain\n        location=25x25x25\n        ; modulation frequency:\n        f_mod = 0\n        Gauss pulse: time step with maximal stimulation (=1)\n        t0 = 40.0\n        ; Width\n        spread = 8.0\n\n * Location and target file of the sink.\n *\n        [sink]\n        ; Location within computational domain\n        location=30x30x30\n        ; Target file\n        data_file = reference.txt\n\n * Domain initialization\n *\n        [initialization]\n        ; for ellipsoid: (px,py,pz,rx,ry,rz)\n        parameters = 100 100 100 50 50 50\n */\n\n/** data field access by symbolic name. */\nenum class DFs: std::vector<std::string>::size_type {\n    SIGMA=0,\n    Ex, Ey, Ez,\n    Hx, Hy, Hz,\n    Dx, Dy, Dz,\n    Ix, Iy, Iz,\n    Psi_ExDy, Psi_ExDz, Psi_EyDx,\n    Psi_EyDz, Psi_EzDx, Psi_EzDy,\n    Psi_HxDy, Psi_HxDz, Psi_HyDx,\n    Psi_HyDz, Psi_HzDx, Psi_HzDy\n};\n\n/** when to write which data field. */\ntypedef ScaFES::WriteHowOften W;\nstd::vector<W> initWritePolicy()\n{\n    std::vector<W> v;\n    v.push_back(W::AT_START);\n    v.push_back(W::LIKE_GIVEN_AT_CL); v.push_back(W::LIKE_GIVEN_AT_CL); v.push_back(W::LIKE_GIVEN_AT_CL);\n    v.push_back(W::NEVER); v.push_back(W::NEVER); v.push_back(W::NEVER);\n    v.push_back(W::NEVER); v.push_back(W::NEVER); v.push_back(W::NEVER);\n    v.push_back(W::NEVER); v.push_back(W::NEVER); v.push_back(W::NEVER);\n    v.push_back(W::NEVER); v.push_back(W::NEVER); v.push_back(W::NEVER);\n    v.push_back(W::NEVER); v.push_back(W::NEVER); v.push_back(W::NEVER);\n    v.push_back(W::NEVER); v.push_back(W::NEVER); v.push_back(W::NEVER);\n    v.push_back(W::NEVER); v.push_back(W::NEVER); v.push_back(W::NEVER);\n    return v;\n}\nstatic const std::vector<W> writePolicy = initWritePolicy();\n\n/** data field names. */\nstd::vector<std::string> initDFNames()\n{\n    std::vector<std::string> v;\n    v.push_back(\"SIGMA\");\n    v.push_back(\"Ex\"); v.push_back(\"Ey\"); v.push_back(\"Ez\");\n    v.push_back(\"Hx\"); v.push_back(\"Hy\"); v.push_back(\"Hz\");\n    v.push_back(\"Dx\"); v.push_back(\"Dy\"); v.push_back(\"Dz\");\n    v.push_back(\"Ix\"); v.push_back(\"Iy\"); v.push_back(\"Iz\");\n    v.push_back(\"Psi_ExDy\"); v.push_back(\"Psi_ExDz\"); v.push_back(\"Psi_EyDx\");\n    v.push_back(\"Psi_EYDz\"); v.push_back(\"Psi_EzDx\"); v.push_back(\"Psi_EzDy\");\n    v.push_back(\"Psi_HxDy\"); v.push_back(\"Psi_HxDz\"); v.push_back(\"Psi_HyDx\");\n    v.push_back(\"Psi_HyDz\"); v.push_back(\"Psi_HzDx\"); v.push_back(\"Psi_HzDy\");\n    return v;\n}\nstatic const std::vector<std::string> DFNames = initDFNames();\n\n/** MPI halos. */\nstd::vector<int> initHaloWidths()\n{\n    std::vector<int> v;\n    v.push_back(0);\n    v.push_back(1); v.push_back(1); v.push_back(1);\n    v.push_back(1); v.push_back(1); v.push_back(1);\n    v.push_back(0); v.push_back(0); v.push_back(0);\n    v.push_back(0); v.push_back(0); v.push_back(0);\n    v.push_back(0); v.push_back(0); v.push_back(0);\n    v.push_back(0); v.push_back(0); v.push_back(0);\n    v.push_back(0); v.push_back(0); v.push_back(0);\n    v.push_back(0); v.push_back(0); v.push_back(0);\n    return v;\n}\nstatic const std::vector<int> HaloWidths = initHaloWidths();\n\ntemplate<typename CT, bool ForwardOnly>\nclass EMFDTDng: public ScaFES::Problem< EMFDTDng<CT, ForwardOnly>, CT, 3> {\npublic:\n    static const size_t DIM=3;\nprivate:\n    typedef ScaFES::Problem< EMFDTDng<CT, ForwardOnly>, CT, 3> Super;\n    typedef std::vector<std::string>::size_type size_type;\n    typedef ScaFES::Ntuple<int, DIM> Index;\n    typedef typename Index::value_type index_type;\n    using PTree=boost::property_tree::ptree;\n\n    // Stencils\n    typedef CompleteCurlCPMLStencil<CT, Index, 0, 0, 1, 0, 1, 0> HxStencil;\n    typedef CompleteCurlCPMLStencil<CT, Index, 1, 0, 0, 0, 0, 1> HyStencil;\n    typedef CompleteCurlCPMLStencil<CT, Index, 0, 1, 0, 1, 0, 0> HzStencil;\n    typedef CompleteCurlCPMLStencil<CT, Index, 0, -1, 0, 0, 0, -1> DxStencil;\n    typedef CompleteCurlCPMLStencil<CT, Index, 0, 0, -1, -1, 0, 0> DyStencil;\n    typedef CompleteCurlCPMLStencil<CT, Index, -1, 0, 0, 0, -1, 0> DzStencil;\npublic:\n\n    EMFDTDng(\n        ScaFES::Parameters const& cl,\n        ScaFES::GridGlobal<DIM> const& gg,\n        const PTree& ptree\n        )\n    : Super(cl, gg, true\n        , DFNames // DF names\n        , HaloWidths // MPI halo width\n        , std::vector<bool>(DFNames.size(), false) // is known? --> false\n        , std::vector<int>(DFNames.size(), 0) // border layers: 0 -> complete volume\n        , std::vector<CT>(DFNames.size(), CT(0.)) // initial values for DFs\n        , writePolicy\n        , std::vector<bool>(DFNames.size(), false) // compute error? --> false\n        , parse<CT>(ptree.get<std::string>(\"initialization.parameters\"), \" \") // params, vOld in initialize()\n        )\n    , ptree_(ptree)\n    , cfln_(.5)\n    , ds_(1.)\n    , dt_((cfln_*ds_)/C_0)\n    , cpmlp_(dt_,\n        ptree_.get<std::size_t>(\"PML.d\"),\n        ptree_.get<CT>(\"PML.m_a\"),\n        ptree_.get<CT>(\"PML.m\"),\n        ptree_.get<CT>(\"PML.k_max\"),\n        ptree_.get<CT>(\"PML.s_max\"),\n        ptree_.get<CT>(\"PML.a_max\")\n        )\n    , first_idx_(0, 0, 0)\n    , last_idx_(cl.nNodes().at(0)-1, cl.nNodes().at(2)-1, cl.nNodes().at(2)-1)\n    , loc_src_(vec2idx(parse<index_type>(ptree_.get<std::string>(\"source.location\"))))\n    , loc_sink_(vec2idx(parse<index_type>(ptree_.get<std::string>(\"sink.location\"))))\n    , reference_(load_reference(ptree_.get<std::string>(\"optimization.reference_data_file\"), cl.nTimesteps()))\n    , src_(dt_,ptree_)\n    , hxstencil_(cpmlp_, Index(1, 0, 0), Index(0, -1, -1), last_idx_, cfln_)\n    , hystencil_(cpmlp_, Index(0, 1, 0), Index(-1, 0, -1), last_idx_, cfln_)\n    , hzstencil_(cpmlp_, Index(0, 0, 1), Index(-1, -1, 0), last_idx_, cfln_)\n    , dxstencil_(cpmlp_, Index(0, 0, 1), Index(-1, 0, 0), last_idx_, -cfln_)\n    , dystencil_(cpmlp_, Index(1, 0, 1), Index(0, -1, 0), last_idx_, -cfln_)\n    , dzstencil_(cpmlp_, Index(1, 1, 0), Index(0, 0, -1), last_idx_, -cfln_)\n    {\n        boost::mpi::communicator world;\n\n        if (world.rank()==0)\n            std::cout<<\"Source at \"<<loc_src_\n            <<\"\\nSink at \"<<loc_sink_\n            <<\"\\nInitialization parameters: \"\n            <<ptree.get<std::string>(\"initialization.parameters\")\n            <<std::endl;\n\n        if (loc_src_==loc_sink_)\n            throw std::runtime_error(\"Source and sink cannot be at the same position.\");\n\n        if ((loc_src_<first_idx_)||(loc_src_>last_idx_))\n            throw std::runtime_error(\"Source not within simulation area.\");\n        if ((loc_sink_<first_idx_)||(loc_sink_>last_idx_))\n            throw std::runtime_error(\"Sink not within simulation area.\");\n\n        if (cl.tau()!=1.0)\n            throw std::runtime_error(\"Please choose \\\"--starttime\\\" and \\\"--endtime\\\" so that tau()=1.0.\");\n    }\n\n    /**\n     * Empty.\n     */\n    template<typename TT>\n    void initInner(std::vector< ScaFES::DataField<TT, DIM> >& /*vNew*/,\n        std::vector< ScaFES::DataField<TT, DIM> > const& /*vOld*/,\n        Index const& /*idxNode*/,\n        int const& /*timestep*/) { }\n\n    /**\n     * Empty.\n     */\n    template<typename TT>\n    void initBorder(std::vector< ScaFES::DataField<TT, DIM> >& /*vNew*/,\n            std::vector< ScaFES::DataField<TT, DIM> > const& /*vOld*/,\n            Index const& /*idxNode*/,\n            int const& /*timestep*/) { }\n\n    /**\n     * Initialize from p.\n     */\n    template <typename TT>\n    void initInner\n    (\n     std::vector< ScaFES::DataField<TT, DIM> >& dfs,\n     std::vector<TT> const& p,\n     Index const& idx,\n     int const& /*timestep*/\n    )\n    {\n            typedef ScaFES::Ntuple<TT, DIM> TT3;\n            TT3 fidx(TT(idx.elem(0)), TT(idx.elem(1)), TT(idx.elem(2)));\n\n            const TT inside=3.546e7;\n            const TT outside=0.;\n\n            IndicatorEllipsoid<TT> e(p.at(0), p.at(1), p.at(2), p.at(3), p.at(4), p.at(5), inside, outside);\n\n            const TT sigma=e(fidx);\n\n            dfs[0](idx)=sigma;\n    }\n\n    /**\n     * Wire to initInner.\n     */\n    template<typename TT>\n    void initBorder(std::vector< ScaFES::DataField<TT, DIM> >& dfs,\n            std::vector<TT> const& p,\n            Index const& idx,\n            int const& timestep)\n    {\n        this->initInner(dfs, p, idx, timestep);\n    }\n\n    /**\n     * Compute H.\n     */\n    template<typename TT>\n    void updateInner(std::vector< ScaFES::DataField<TT, DIM> >& n,\n            std::vector< ScaFES::DataField<TT, DIM> > const& o,\n            Index const& idx,\n            int const& /*timestep*/)\n    {\n        // start by updating H from E\n        n[sc(DFs::Hx)](idx)=hxstencil_(idx, o[sc(DFs::Hx)],\n            o[sc(DFs::Ey)], o[sc(DFs::Psi_EyDz)], n[sc(DFs::Psi_EyDz)],\n            o[sc(DFs::Ez)], o[sc(DFs::Psi_EzDy)], n[sc(DFs::Psi_EzDy)]);\n\n        n[sc(DFs::Hy)](idx)=hystencil_(idx, o[sc(DFs::Hy)],\n            o[sc(DFs::Ez)], o[sc(DFs::Psi_EzDx)], n[sc(DFs::Psi_EzDx)],\n            o[sc(DFs::Ex)], o[sc(DFs::Psi_ExDz)], n[sc(DFs::Psi_ExDz)]);\n\n        n[sc(DFs::Hz)](idx)=hzstencil_(idx, o[sc(DFs::Hz)],\n            o[sc(DFs::Ex)], n[sc(DFs::Psi_ExDy)], n[sc(DFs::Psi_ExDy)],\n            o[sc(DFs::Ey)], n[sc(DFs::Psi_EyDx)], n[sc(DFs::Psi_EyDx)]);\n    }\n\n    /**\n     * Wire to updateInner.\n     */\n    template<typename TT>\n    void updateBorder(std::vector< ScaFES::DataField<TT, DIM> >& vNew,\n            std::vector< ScaFES::DataField<TT, DIM>>const& vOld,\n            Index const& idx,\n            int const& timestep)\n    {\n        updateInner(vNew, vOld, idx, timestep);\n    }\n\n    /**\n     * Compute E.\n     */\n    template<typename TT>\n    void updateInner2(std::vector< ScaFES::DataField<TT, DIM> >& n,\n            std::vector< ScaFES::DataField<TT, DIM> > const& o,\n            Index const& idx,\n            int const& /*timestep*/)\n    {\n        // update D from H\n        // n.b.:\n        // 1) although comfortable, DO NOT USE \"auto\" for type deduction. ADOL-C yiels obscure and hard to debug compilation failures otherwise (\"auto\"-deduced rhs type is not assignable).\n        // 2) although comfortable, NEVER violate the \"compute -> use -> persist\" order for (AD-)active variables. ADOL-C will simply not work if you persist a datum (i.e., write it to memory) and re-use it from there. The use of temporaries is a workaround.\n        TT Dx=dxstencil_(idx, o[sc(DFs::Dx)],\n            o[sc(DFs::Hz)], o[sc(DFs::Psi_HzDy)], n[sc(DFs::Psi_HzDy)],\n            o[sc(DFs::Hy)], o[sc(DFs::Psi_HyDz)], n[sc(DFs::Psi_HyDz)]);\n\n        TT Dy=dystencil_(idx, o[sc(DFs::Dy)],\n            o[sc(DFs::Hx)], o[sc(DFs::Psi_HxDz)], n[sc(DFs::Psi_HxDz)],\n            o[sc(DFs::Hz)], o[sc(DFs::Psi_HzDx)], n[sc(DFs::Psi_HzDx)]);\n\n        TT Dz=dzstencil_(idx, o[sc(DFs::Dz)],\n            o[sc(DFs::Hy)], o[sc(DFs::Psi_HyDx)], n[sc(DFs::Psi_HyDx)],\n            o[sc(DFs::Hx)], o[sc(DFs::Psi_HxDy)], n[sc(DFs::Psi_HxDy)]);\n\n        TT ga=1./(1.+(o[sc(DFs::SIGMA)](idx))*dt_/EPSILON_0);\n        TT gb=(o[sc(DFs::SIGMA)](idx))*dt_/EPSILON_0;\n\n        TT Ex=ga*(Dx-o[sc(DFs::Ix)](idx));\n        TT Ey=ga*(Dy-o[sc(DFs::Iy)](idx));\n        TT Ez=ga*(Dz-o[sc(DFs::Iz)](idx));\n\n        n[sc(DFs::Ix)](idx)=o[sc(DFs::Ix)](idx)+(gb*Ex);\n        n[sc(DFs::Iy)](idx)=o[sc(DFs::Iy)](idx)+(gb*Ey);\n        n[sc(DFs::Iz)](idx)=o[sc(DFs::Iz)](idx)+(gb*Ez);\n\n        // write temporaries to dependent fields, see above, item 2\n        n[sc(DFs::Dx)](idx)=Dx;\n        n[sc(DFs::Dy)](idx)=Dy;\n        n[sc(DFs::Dz)](idx)=Dz;\n        n[sc(DFs::Ex)](idx)=Ex;\n        n[sc(DFs::Ey)](idx)=Ey;\n\n        // inject source, use old time\n        if (idx==loc_src_)\n            n[sc(DFs::Ez)](idx)=src_((o[sc(DFs::Ez)]).time());\n        else\n            n[sc(DFs::Ez)](idx)=Ez;\n\n        // collect sink\n        if (idx==loc_sink_) {\n            convert<CT, TT> c;\n            CT val=c(n[sc(DFs::Ez)](idx));\n            sink_.push_back(val);\n        }\n    }\n\n    /**\n     * Wire to updateInner2.\n     */\n    template<typename TT>\n    void updateBorder2(std::vector< ScaFES::DataField<TT, DIM> >& vNew,\n            std::vector< ScaFES::DataField<TT, DIM>>const& vOld,\n            Index const& idx,\n            int const& timestep)\n    {\n        updateInner2(vNew, vOld, idx, timestep);\n    }\n\n    /**\n     * Empty.\n     */\n    template<typename TT>\n    void evalInner(std::vector< ScaFES::DataField<TT, DIM> >& /*vNew*/,\n        ScaFES::Ntuple<int, DIM> const& /*idxNode*/,\n        int const& /*timestep*/) { }\n\n    /**\n     * Empty.\n     */\n    template<typename TT>\n    void evalBorder(std::vector< ScaFES::DataField<TT, DIM> >& /*vNew*/,\n            ScaFES::Ntuple<int, DIM> const& /*idxNode*/,\n            int const& /*timestep*/) { }\n\n    /**\n     * Write sink data to file.\n     */\n    void writeSinkData()\n    {\n        boost::mpi::communicator world;\n\n        if (world.size()!=1) {\n            if (world.rank()==0) {\n                if (sink_.size()==0)\n                    world.recv(boost::mpi::any_source, 0, sink_);\n            } else {\n                if (sink_.size()!=0)\n                    world.send(0, 0, sink_);\n            }\n        }\n\n        if (world.rank()!=0)\n            return;\n\n        const std::string fname=ptree_.get<std::string>(\"sink.data_file\");\n\n        if (fname.size()==0)\n            throw std::runtime_error(\"Sink file name empty.\");\n\n        std::cout<<\"Writing sink data to file \\\"\"\n            <<fname<<\"\\\"...\"\n            <<std::flush;\n\n        std::ofstream of(fname.c_str());\n        of.setf(of.scientific);\n        of.precision(20);\n\n        for (auto it=sink_.begin(); it!=sink_.end(); ++it)\n            of<<(*it)<<std::endl;\n\n        std::cout<<\"done.\"<<std::endl;\n    }\n\nprivate:\n    /**\n     * Layer structure for datafields with holes.\n     */\n    std::vector<int> layers(const PTree& p)\n    {\n        std::vector<int> ret(13, 0);\n        const int d=p.get<int>(\"PML.d\")+2;\n\n        for (int i=0; i<12; ++i)\n            ret.push_back(d);\n\n        return ret;\n    };\n\n    /**\n     * Parse into vector.\n     * @param s\n     * @param sep\n     * @return\n     */\n    template <typename T>\n    static std::vector<T> parse(const std::string& s, const char* sep=\"x\")\n    {\n        boost::char_separator<char> csep(sep);\n        boost::tokenizer<boost::char_separator<char> > tok(s, csep);\n\n        std::vector<T> ret;\n\n        for (auto ti=tok.begin(); ti!=tok.end(); ++ti) {\n            try {\n            ret.push_back(boost::lexical_cast<T>(*ti));\n            }\n            catch (...) {\n                std::cout << \"While parsing string \\\"\" << s << \"\\\":\" << std::endl;\n                throw;\n            }\n        }\n        return ret;\n    }\n\n    /**\n     * Make Index from vector.\n     * @param v\n     * @return\n     */\n    static Index vec2idx(const std::vector<typename Index::value_type>& v)\n    {\n        Index ret;\n\n        for (unsigned long int i=0; i<Index::DIM; ++i)\n            ret[i]=v.at(i);\n\n        return ret;\n    }\n\n    /**\n     * Cast \"nice names\" into accessible ints\n     * @param df\n     * @return\n     */\n    static size_type sc(const DFs & df)\n    {\n        return static_cast<size_type> (df);\n    }\n\n    /**\n     * Load reference data from file.\n     */\n    static std::vector<CT> load_reference(const std::string& fname, const unsigned int& n)\n    {\n        boost::mpi::communicator world;\n        std::vector<CT> ret;\n\n        if (ForwardOnly==true) {\n            if (world.rank()==0)\n                std::cout<<\"NOT reading reference from file. Calling TF evaluation routines WILL FAIL!\"<<std::endl;\n            return ret;\n        }\n\n        /** TODO: This statement is unreachable in case ForwardOnly=true. */\n        if (world.rank()==0) {\n            std::ifstream ifs(fname.c_str());\n\n            if (!ifs.is_open())\n                throw std::runtime_error(\"Failed opening file \\\"\"+fname+\"\\\".\");\n\n            while ((ifs.good()) && (ret.size()<n)) {\n                std::string line;\n                std::getline(ifs, line);\n                try {\n                    ret.push_back(boost::lexical_cast<CT, std::string>(line));\n                } catch (...) {\n                    std::cout<<\"While parsing reference file \\\"\" << fname << \"\\\": \" <<std::endl;\n                    throw;\n                }\n            }\n\n            if (ret.size()<n)\n                throw std::runtime_error(\"Reference file \\\"\"+fname+\"\\\" contains too few items.\");\n        }\n\n        if (world.size()>1)\n            boost::mpi::broadcast(world, ret, 0);\n\n        return ret;\n    }\n\n    const PTree ptree_;\n    const CT cfln_, ds_, dt_;\n    const CPMLParams<CT> cpmlp_;\n    const Index first_idx_, last_idx_, loc_src_, loc_sink_;\n    const std::vector<CT> reference_;\n    const ModulatedGaussianSource<CT> src_;\n    std::vector<CT> sink_;\n\n    const HxStencil hxstencil_;\n    const HyStencil hystencil_;\n    const HzStencil hzstencil_;\n    const DxStencil dxstencil_;\n    const DyStencil dystencil_;\n    const DzStencil dzstencil_;\n};\n\n#endif // EMFDTD_HPP_\n\n", "meta": {"hexsha": "a3aab644b78e3151ae2d13a8dc0abf31887f8233", "size": 18456, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/EMFDTD/EMFDTD.hpp", "max_stars_repo_name": "nih23/MRIDrivenHeatSimulation", "max_stars_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/EMFDTD/EMFDTD.hpp", "max_issues_repo_name": "nih23/MRIDrivenHeatSimulation", "max_issues_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_issues_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/EMFDTD/EMFDTD.hpp", "max_forks_repo_name": "nih23/MRIDrivenHeatSimulation", "max_forks_repo_head_hexsha": "de6d16853df1faf44c700d1fc06584351bf6c816", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0416666667, "max_line_length": 258, "alphanum_fraction": 0.5592219332, "num_tokens": 5696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.42048550754393865}}
{"text": "#include \"feature_estimator.h\"\n\n#include <Eigen/Dense>\n\nnamespace {\n\nint calculate_medoid_index(std::vector<Eigen::Vector3d> &points) {\n  std::vector<double> distances(points.size(), 0);\n  for (auto i = 0u; i < points.size(); ++i) {\n    for (auto j = 0u; j < points.size(); ++j) {\n      const double distance = (points[i] - points[j]).eval().norm();\n      distances[i] += distance;\n    }\n  }\n\n  int min_idx = 0;\n  double min_distance = std::numeric_limits<double>::max();\n  for (auto i = 0u; i < distances.size(); ++i) {\n    if (distances[i] < min_distance) {\n      min_idx = i;\n      min_distance = distances[i];\n    }\n  }\n\n  return min_idx;\n}\n\n}  // namespace\n\nnamespace pcs {\n\nFeatureEstimator::FeatureEstimator(std::shared_ptr<pcs::PointCloud> point_cloud,\n                                   double voxel_size, int num_neighbors,\n                                   int num_scales, int batch_size)\n    : point_cloud_(point_cloud),\n      voxel_size_(voxel_size),\n      num_neighbors_(num_neighbors),\n      num_scales_(num_scales),\n      batch_size_(batch_size),\n      tree_(nullptr),\n      num_points_(0),\n      has_colors_(false),\n      pool_(std::thread::hardware_concurrency()) {\n  if (point_cloud_ and not point_cloud_->empty()) {\n    num_points_ = point_cloud_->points_.size();\n    has_colors_ = point_cloud_->has_colors();\n    tree_ = std::shared_ptr<KDTree<3>>(new KDTree<3>(\n        point_cloud_->points_, std::thread::hardware_concurrency()));\n\n    // Build points pyramid\n    point_clouds_.push_back(point_cloud_);\n    trees_.push_back(tree_);\n    for (auto s = 1u; s < num_scales_; ++s) {\n      const auto voxel_scale = std::pow(2, s);\n      auto down_scaled_cloud =\n          voxel_down_sample(*(point_clouds_[s - 1]), voxel_size_ * voxel_scale);\n      point_clouds_.push_back(down_scaled_cloud);\n\n      auto tree = std::shared_ptr<KDTree<3>>(new KDTree<3>(\n          point_clouds_[s]->points_, std::thread::hardware_concurrency()));\n      trees_.push_back(tree);\n    }\n  }\n}\n\nEigen::VectorXd FeatureEstimator::get_features_for_point(\n    std::size_t point_id) const {\n  if (point_id >= num_points_) {\n    std::string error_string(\"given point index { \");\n    error_string +=\n        std::to_string(point_id) + \" } is bigger then point cloud size { \";\n    error_string += std::to_string(num_points_) + \" }\";\n    throw std::out_of_range(error_string);\n  }\n\n  const std::size_t num_features = feature_size();\n  Eigen::VectorXd features(num_features);\n  Eigen::Vector3d point = point_cloud_->points_[point_id];\n  Eigen::Vector3d neig_color(0., 0., 0.);\n\n  for (auto s = 0u; s < point_clouds_.size(); ++s) {\n    const std::size_t scale_offset = s * features_per_scale;\n    auto neighbors = trees_[s]->find_nns(point, num_neighbors_);\n    if (s == 0 and has_colors_) {\n      for (auto k = 0u; k < neighbors.size(); ++k) {\n        neig_color += (point_cloud_->colors_[neighbors[k].first]);\n      }\n    }\n    std::vector<Eigen::Vector3d> n_points;\n    for (auto j = 0u; j < neighbors.size(); ++j) {\n      n_points.push_back(point_clouds_[s]->points_[neighbors[j].first]);\n    }\n\n    Eigen::Vector3d medoid = n_points[calculate_medoid_index(n_points)];\n    Eigen::Matrix3d cov = Eigen::Matrix3d::Zero();\n    Eigen::MatrixXd data = Eigen::MatrixXd::Zero(num_neighbors_, 3);\n    for (auto j = 0u; j < num_neighbors_; ++j) {\n      data.row(j) = n_points[j].transpose();\n    }\n\n    Eigen::MatrixXd centered = data.rowwise() - data.colwise().mean();\n    cov = (centered.transpose() * centered) / (num_neighbors_ - 1);\n\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig(cov);\n    Eigen::Matrix3d eigenvectors = eig.eigenvectors();\n    Eigen::Vector3d eigenvalues = eig.eigenvalues();\n    eigenvalues.normalize();\n\n    // Covariance features\n    const double omnivariance =\n        std::pow(eigenvalues(0) * eigenvalues(1) * eigenvalues(2), 1.0 / 3.0);\n\n    features[scale_offset + 0] = omnivariance;\n    double eigenentropy = 0.0;\n    for (int k = 0; k < 3; ++k) {\n      eigenentropy -= (eigenvalues(k) * std::log(eigenvalues(k)));\n    }\n\n    features[scale_offset + 1] = eigenentropy;\n\n    const double anisotropy =\n        (eigenvalues(2) - eigenvalues(0)) / eigenvalues(2);\n    features[scale_offset + 2] = anisotropy;\n\n    const double planarity = (eigenvalues(1) - eigenvalues(0)) / eigenvalues(2);\n    features[scale_offset + 3] = planarity;\n\n    const double linearity = (eigenvalues(2) - eigenvalues(1)) / eigenvalues(2);\n    features[scale_offset + 4] = linearity;\n\n    const double surface_variation = eigenvalues(0);\n    features[scale_offset + 5] = surface_variation;\n\n    const double scatter = eigenvalues(0) / eigenvalues(2);\n    features[scale_offset + 6] = scatter;\n\n    const double verticality = 1. - std::abs(eigenvectors.col(0)[2]);\n    features[scale_offset + 7] = verticality;\n\n    // Moments features\n    double first_order_first_axis = 0;\n    double first_order_second_axis = 0;\n    double second_order_first_axis = 0;\n    double second_order_second_axis = 0;\n    for (auto &p : n_points) {\n      Eigen::Vector3d diff = p - medoid;\n      first_order_first_axis += diff.dot(eigenvectors.col(2));\n      first_order_second_axis += diff.dot(eigenvectors.col(1));\n      second_order_first_axis +=\n          first_order_first_axis * first_order_first_axis;\n      second_order_second_axis +=\n          first_order_second_axis * first_order_second_axis;\n    }\n    features[scale_offset + 8] = first_order_first_axis;\n    features[scale_offset + 9] = first_order_second_axis;\n    features[scale_offset + 10] = second_order_first_axis;\n    features[scale_offset + 11] = second_order_second_axis;\n\n    // Height features\n    double z_min = std::numeric_limits<double>::max();\n    double z_max = -std::numeric_limits<double>::max();\n    for (auto &p : n_points) {\n      const double z = p.z();\n      if (z < z_min) {\n        z_min = z;\n      }\n      if (z > z_max) {\n        z_max = z;\n      }\n    }\n\n    const double vertical_range = z_max - z_min;\n    features[scale_offset + 12] = vertical_range;\n\n    const double height_below = point.z() - z_min;\n    features[scale_offset + 13] = height_below;\n\n    const double height_above = z_max - point.z();\n    features[scale_offset + 14] = height_above;\n  }\n\n  // Color features calculated if initial cloud has colors\n  if (has_colors_) {\n    const std::size_t geometric_features_offset =\n        num_scales_ * features_per_scale;\n    Eigen::Vector3d main_color = point_cloud_->colors_[point_id];\n    features[geometric_features_offset + 0] = main_color(0);\n    features[geometric_features_offset + 1] = main_color(1);\n    features[geometric_features_offset + 2] = main_color(2);\n\n    neig_color /= num_neighbors_;\n    features[geometric_features_offset + 3] = neig_color(0);\n    features[geometric_features_offset + 4] = neig_color(1);\n    features[geometric_features_offset + 5] = neig_color(2);\n  }\n  features =\n      features.unaryExpr([](double v) { return std::isfinite(v) ? v : 0.0; });\n  return features;\n}\n\nEigen::MatrixXd FeatureEstimator::get_features_for_batch(\n    std::size_t start_id, std::size_t end_id) const {\n  if (end_id > point_cloud_->points_.size() or\n      start_id >= point_cloud_->points_.size() or end_id <= start_id) {\n    std::string error_string(\"invalid slice { \");\n    error_string += std::to_string(start_id) + \" : \";\n    error_string += std::to_string(end_id) + \" } for array with { \";\n    error_string += std::to_string(point_cloud_->points_.size()) + \" } points\";\n    throw std::out_of_range(error_string);\n  }\n\n  const std::size_t range = end_id - start_id;\n  const std::size_t num_features = feature_size();\n  Eigen::MatrixXd result(range, num_features);\n  const double drange =\n      static_cast<double>(range) / static_cast<double>(pool_.num_threads());\n  const std::size_t num_points_per_thread =\n      std::max<std::size_t>(1u, std::ceil(drange));\n  const std::size_t max_threads = std::min(pool_.num_threads(), range);\n  for (auto i = 0u; i < max_threads; ++i) {\n    const auto s = start_id + i * num_points_per_thread;\n    const auto e = std::min(end_id, s + num_points_per_thread);\n    pool_.add_task([&result, s, e, start_id, this] {\n      for (auto j = s; j < e; ++j) {\n        result.row(j - start_id) = get_features_for_point(j);\n      }\n    });\n  }\n  pool_.wait();\n\n  return result;\n}\n\nEigen::MatrixXd FeatureEstimator::get_features_for_points(\n    const std::vector<int> &idxs) const {\n  const std::size_t range = idxs.size();\n  const std::size_t num_features = feature_size();\n  Eigen::MatrixXd result(range, num_features);\n  const double drange =\n      static_cast<double>(range) / static_cast<double>(pool_.num_threads());\n  const std::size_t num_points_per_thread =\n      std::max<std::size_t>(1u, std::ceil(drange));\n  const std::size_t max_threads = std::min(pool_.num_threads(), range);\n  std::vector<std::future<void>> futures;\n  for (auto i = 0u; i < max_threads; ++i) {\n    const auto s = i * num_points_per_thread;\n    const auto e = std::min(range, s + num_points_per_thread);\n    futures.push_back(pool_.add_task([&result, &idxs, s, e, this] {\n      for (auto j = s; j < e; ++j) {\n        result.row(j) = get_features_for_point(idxs[j]);\n      }\n    }));\n  }\n  for (auto &&x : futures) {\n    x.get();\n  }\n\n  return result;\n}\n\nstd::size_t FeatureEstimator::num_points() const { return num_points_; }\n\nstd::vector<unsigned int> FeatureEstimator::soft_voting_smoothing(\n    const Eigen::MatrixXd &probabilities, std::size_t num_neighbors) const {\n  std::vector<unsigned int> classes(probabilities.rows());\n\n  if (probabilities.size() == 0) {\n    return classes;\n  }\n  const std::size_t num_classes = probabilities.cols();\n\n  const double drange = static_cast<double>(num_points_) /\n                        static_cast<double>(pool_.num_threads());\n  const std::size_t num_points_per_thread =\n      std::max<std::size_t>(1u, std::ceil(drange));\n  const std::size_t max_threads = std::min(pool_.num_threads(), num_points_);\n  for (auto i = 0u; i < max_threads; ++i) {\n    const auto s = i * num_points_per_thread;\n    const auto e = std::min(num_points_, s + num_points_per_thread);\n    pool_.add_task(\n        [&classes, &probabilities, num_neighbors, num_classes, s, e, this] {\n          for (auto point_id = s; point_id < e; ++point_id) {\n            Eigen::Vector3d point = point_cloud_->points_[point_id];\n            const Eigen::Vector3d main_color = point_cloud_->colors_[point_id];\n            const auto neighbors = tree_->find_nns(point, num_neighbors);\n            float weight_sum = 0.f;\n            Eigen::VectorXd commite_result = Eigen::VectorXd::Zero(num_classes);\n            for (const auto &neighbor : neighbors) {\n              commite_result += probabilities.row(neighbor.first);\n            }\n            Eigen::VectorXd::Index index;\n            commite_result.maxCoeff(&index);\n            classes[point_id] = index;\n          }\n        });\n  }\n  pool_.wait();\n\n  return classes;\n}\n\nstd::size_t FeatureEstimator::num_batches() const {\n  return static_cast<std::size_t>(\n      std::ceil(static_cast<double>(num_points_) / batch_size_));\n}\n\nstd::size_t FeatureEstimator::batch_size() const { return batch_size_; }\n\nEigen::MatrixXd FeatureEstimator::get_features_for_batch(\n    std::size_t batch_id) const {\n  const std::size_t start_id = batch_id * batch_size_;\n  const std::size_t end_id =\n      std::min<std::size_t>(start_id + batch_size_, num_points_);\n  return get_features_for_batch(start_id, end_id);\n}\n\nstd::size_t FeatureEstimator::feature_size() const {\n  if (has_colors_) {\n    return color_features + features_per_scale * num_scales_;\n  } else {\n    return features_per_scale * num_scales_;\n  }\n}\n\nstd::vector<unsigned int> FeatureEstimator::hard_voting_smoothing(\n    const std::vector<unsigned int> &labels, std::size_t num_neighbors) const {\n  std::vector<unsigned int> smooth_labels(labels.size(), 0);\n\n  if (labels.empty()) {\n    return smooth_labels;\n  }\n\n  const double drange = static_cast<double>(num_points_) /\n                        static_cast<double>(pool_.num_threads());\n  const std::size_t num_points_per_thread =\n      std::max<std::size_t>(1u, std::ceil(drange));\n  const std::size_t max_threads = std::min(pool_.num_threads(), num_points_);\n  for (auto i = 0u; i < max_threads; ++i) {\n    const auto s = i * num_points_per_thread;\n    const auto e = std::min(num_points_, s + num_points_per_thread);\n    pool_.add_task([this, s, e, num_neighbors, &smooth_labels, &labels] {\n      for (auto point_id = s; point_id < e; ++point_id) {\n        Eigen::Vector3d point = point_cloud_->points_[point_id];\n        const auto neighbors = tree_->find_nns(point, num_neighbors);\n        std::unordered_map<unsigned int, int> commite_result;\n        for (const auto &neighbor : neighbors) {\n          commite_result[labels[neighbor.first]]++;\n        }\n        unsigned int max_class = 0;\n        int max_value = -1;\n        for (auto &v : commite_result) {\n          if (v.second > max_value) {\n            max_class = v.first;\n            max_value = v.second;\n          }\n        }\n        smooth_labels[point_id] = max_class;\n      }\n    });\n  }\n  pool_.wait();\n\n  return smooth_labels;\n}\n\n}  // namespace pcs\n", "meta": {"hexsha": "aae3b590ed4f59af4974df5048848e2c0d20c36b", "size": 13179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/feature_estimator.cpp", "max_stars_repo_name": "aleksrgarkusha/pcs", "max_stars_repo_head_hexsha": "597a2aa020a60473307ef09a8939db1d93657f8a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-26T02:17:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T13:20:33.000Z", "max_issues_repo_path": "src/feature_estimator.cpp", "max_issues_repo_name": "aleksrgarkusha/pcs", "max_issues_repo_head_hexsha": "597a2aa020a60473307ef09a8939db1d93657f8a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/feature_estimator.cpp", "max_forks_repo_name": "aleksrgarkusha/pcs", "max_forks_repo_head_hexsha": "597a2aa020a60473307ef09a8939db1d93657f8a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9100817439, "max_line_length": 80, "alphanum_fraction": 0.6550572881, "num_tokens": 3499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4204855075439386}}
{"text": "#include <limits>\n#include <Eigen/Geometry>\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <pybind11/numpy.h>\n\n#include <igl/point_mesh_squared_distance.h>\n#include <igl/AABB.h>\n\n\nnamespace py = pybind11;\nusing namespace Eigen;\n\ntypedef Eigen::Vector3d Vec3d;\ntypedef Eigen::Vector2d Vec2d;\n\n\nstd::tuple<py::array_t<int>, py::array_t<double>, py::array_t<int>, py::array_t<double>> \nrayMeshIntersect(\n        py::array_t<double> verts_in, \n        py::array_t<int> tris_in,\n        py::array_t<double> ray_pts_in, \n        py::array_t<double> ray_dirs_in, \n        double max_distance, \n        double max_angle,\n        bool allow_backface_hit) \n{\n    auto verts = verts_in.unchecked<2>();\n    auto tris = tris_in.unchecked<2>();\n    auto rayPts = ray_pts_in.unchecked<2>();\n    auto rayDirs = ray_dirs_in.unchecked<2>();\n\n    std::vector<int> hitTris;\n    std::vector<Vec2d> hitUVs;\n    std::vector<Vec3d> hitPoints;\n    std::vector<int> hitRayIndices;\n\n    double maxAngleCos = std::cos(max_angle);\n    for(int iray = 0; iray < rayPts.shape(0); iray++) {\n        Vec3d rayPos(rayPts(iray, 0), rayPts(iray, 1), rayPts(iray, 2));\n        Vec3d rayDir(rayDirs(iray, 0), rayDirs(iray, 1), rayDirs(iray, 2));\n        Vec3d rayDirNorm = rayDir.normalized();\n        Vec3d bestHit;\n        float bestU, bestV, bestAngleCos;\n        int bestTri = -1;\n        float best_t = std::numeric_limits<float>::infinity();\n        for(int itri = 0; itri < tris.shape(0); itri++) {\n            // put data into Vec3d for easy dot/cross operations\n            auto i1 = tris(itri, 0); auto i2 = tris(itri, 1); auto i3 = tris(itri, 2);\n            Vec3d v1(verts(i1, 0), verts(i1, 1), verts(i1, 2));\n            Vec3d v2(verts(i2, 0), verts(i2, 1), verts(i2, 2));\n            Vec3d v3(verts(i3, 0), verts(i3, 1), verts(i3, 2));\n            // perform ray-triangle hit test\n            Vec3d edge1 = v2 - v1;\n            Vec3d edge2 = v3 - v1;\n            Vec3d pvec = rayDir.cross(edge2);\n            float det = edge1.dot(pvec);\n            if(std::abs(det) < std::numeric_limits<double>::epsilon()) {\n                continue;\n            }\n            float invDet = 1.0 / det;\n            Vec3d tvec = rayPos - v1;\n            float u = tvec.dot(pvec) * invDet;\n            if(u < 0.0 || u > 1.0) {\n                continue;\n            }\n            Vec3d qvec = tvec.cross(edge1);\n            float v = rayDir.dot(qvec) * invDet;\n            if(v < 0.0 || u + v > 1.0) {\n                continue;\n            }\n            float t = edge2.dot(qvec) * invDet;\n            Vec3d hitPoint = v1 + edge1*u + edge2*v;\n            // check if nearest hit and if it is valid\n            if(fabs(t) < fabs(best_t) && (hitPoint - rayPos).norm() < max_distance) {\n                bestHit = hitPoint;\n                bestU = u; bestV = v;\n                bestTri = itri;\n                best_t = t;\n                Vec3d normal = edge1.normalized().cross(edge2.normalized()).normalized();\n                if (allow_backface_hit) {\n                    bestAngleCos = fmax(rayDirNorm.dot(normal), rayDirNorm.dot(normal * -1.f));\n                }\n                else {\n                    bestAngleCos = rayDirNorm.dot(normal);\n                }\n            }\n        }\n        if(bestTri > -1) {\n            // check ray-normal angle\n            if(bestAngleCos < maxAngleCos) {\n                continue;\n            }\n            hitUVs.emplace_back(bestU, bestV);\n            hitPoints.push_back(bestHit);\n            hitRayIndices.push_back(iray);\n            hitTris.push_back(bestTri);\n        }\n    }\n\n    return std::make_tuple(\n            py::array_t<int>(hitTris.size(), hitTris.data()),\n            py::array_t<double>({(unsigned long)hitUVs.size(), 2ul}, (double*)hitUVs.data()),\n            py::array_t<int>(hitRayIndices.size(), hitRayIndices.data()),\n            py::array_t<double>({(unsigned long)hitPoints.size(), 3ul}, (double*)hitPoints.data())\n    );\n}\n\nstd::tuple<VectorXi, MatrixX2d, VectorXi>\nrayMeshIntersectFast(\n        const MatrixXd& verts, \n        const MatrixXi& tris,\n        const MatrixXd& ray_pts, \n        const MatrixXd& ray_dirs)\n{\n    igl::AABB<MatrixXd, 3> tree;\n    tree.init(verts, tris);\n\n    std::vector<std::pair<igl::Hit, int>> hits;\n    for (int i = 0; i < ray_pts.rows(); i++) {\n        igl::Hit hit;\n        if (tree.intersect_ray(verts, tris, ray_pts.row(i), ray_dirs.row(i), hit)) {\n            hits.emplace_back(hit, i);\n        }\n    }\n\n    VectorXi tri_ixs(hits.size());\n    MatrixX2d barys(hits.size(), 2);\n    VectorXi ray_ixs(hits.size());\n\n    for(int i = 0; i < hits.size(); i++) {\n        ray_ixs(i) = hits[i].second;\n        const igl::Hit & hit = hits[i].first;\n        tri_ixs(i) = hit.id;\n        barys.row(i) = Vec2d((double)hit.u, (double)hit.v);\n    }\n    \n    return std::make_tuple(tri_ixs, barys, ray_ixs);\n}\n\nstd::tuple<VectorXd, VectorXi, MatrixX3d, MatrixX2d>\nclosestPointOnMesh(const MatrixXd& P, const MatrixXd& V, const MatrixXi& tris) \n{\n    VectorXd sq_dists;\n    MatrixX3d hit_pts;\n    VectorXi tri_ixs;\n    igl::point_mesh_squared_distance(P, V, tris, sq_dists, tri_ixs, hit_pts);\n\n    // determine uv coordinates of those closest hits\n    MatrixX2d hit_uv(hit_pts.rows(), 2);\n    for (int i = 0; i < P.rows(); ++i) {\n        Vector3d p = hit_pts.row(i);\n        Vector3i tri = tris.row(tri_ixs(i));\n        // setup local coordinate frame\n        Vector3d e10 = V.row(tri(1)) - V.row(tri(0));\n        Vector3d e20 = V.row(tri(2)) - V.row(tri(0));\n        Vector3d n = e10.cross(e20); // normal\n        Matrix3d F;\n        F << e10, e20, n;\n        // invert local coordinate frame to get\n        // frame-local coordinates\n        Vector3d v0 = hit_pts.row(i) - V.row(tri(0));\n        Vector3d uvw = F.inverse() * v0;\n        hit_uv(i, 0) = uvw(0);\n        hit_uv(i, 1) = uvw(1);\n    }\n\n    return std::make_tuple(sq_dists, tri_ixs, hit_pts, hit_uv);\n};\n\nPYBIND11_PLUGIN(_intersections_ext) {\n    using namespace pybind11::literals;\n\n    py::module m(\"_intersections_ext\");\n    m.def(\"ray_mesh_intersect\", &rayMeshIntersect,\n            \"verts\"_a, \"tris\"_a, \"ray_pts\"_a, \"ray_dirs\"_a,\n            \"max_distance\"_a = std::numeric_limits<double>::infinity(),\n            \"max_angle\"_a = std::numeric_limits<double>::infinity(),\n            \"allow_backface_hit\"_a = true);\n\n    m.def(\"ray_mesh_intersect_fast\", &rayMeshIntersectFast,\n            \"verts\"_a, \"tris\"_a, \"ray_pts\"_a, \"ray_dirs\"_a);\n\n    m.def(\"closest_points_on_mesh\", &closestPointOnMesh,\n          \"points\"_a, \"vertices\"_a, \"triangles\"_a);\n\n    return m.ptr();\n}\n\n", "meta": {"hexsha": "df4d83511279f59cdb9a0d30b084b46907380e70", "size": 6606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/intersections.cpp", "max_stars_repo_name": "tneumann/cgtools", "max_stars_repo_head_hexsha": "8f77b6a4642fe79ac85b8449ebd3f72ea0e56032", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-05-02T14:08:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-15T16:07:19.000Z", "max_issues_repo_path": "src/intersections.cpp", "max_issues_repo_name": "tneumann/cgtools", "max_issues_repo_head_hexsha": "8f77b6a4642fe79ac85b8449ebd3f72ea0e56032", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/intersections.cpp", "max_forks_repo_name": "tneumann/cgtools", "max_forks_repo_head_hexsha": "8f77b6a4642fe79ac85b8449ebd3f72ea0e56032", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-02T14:08:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T03:47:29.000Z", "avg_line_length": 34.7684210526, "max_line_length": 98, "alphanum_fraction": 0.5656978504, "num_tokens": 1940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4204855017564221}}
{"text": "\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <vector>\n#include <math.h>\n\n#include \"NRGclasses.hpp\"\nusing namespace std;\n\n\n\n//////////////\ndouble CNRGarray::EniBlockj(int i, int j){\n\n  // returns the energy of the i-th state in block j\n\n  double aux=0.0;\n  \n  if ( (2*j-2)<BlockBegEnd.size() )\n    {\n      if ( (BlockBegEnd[2*j-2]+(i-1))<dEn.size() )\n\t{\n\t  aux=dEn[BlockBegEnd[2*j-2]+(i-1)];\n\t}\n    }\n  \n  return(aux);\n\n}\n//////////////\n// void CNRGarray::SetsizeBlock(){\n\n//   int ii,i1;\n//   for (ii=0;ii<BlockBegEnd.size();ii+=2)\n//     {\n//       sizeBlock.push_back(BlockBegEnd[ii+1]-BlockBegEnd[ii]+1);\n//     }\n  \n\n// }\n//////////////\nvoid CNRGarray::PrintQNumbers(){\n\n\n  int ii;\n  cout << \"Qnumbers : \" << endl;\n  for (ii=0;ii<QNumbers.size();ii++)\n    cout << QNumbers[ii] << \"  \";\n  cout << endl;\n}\n\n//////////////\nvoid CNRGarray::PrintAll(){\n\n\n  int ii;\n  void CNRGarray::PrintQNumbers();\n\n  PrintQNumbers();\n\n  cout << \"dEn : \" << endl;\n  for (ii=0;ii<dEn.size();ii++)\n    cout << dEn[ii] << \" \";\n  cout << endl;\n\n  cout << \"BlockBegEnd : \" << endl;\n  for (ii=0;ii<BlockBegEnd.size();ii+=2)\n    cout << BlockBegEnd[ii] << \" \"<< BlockBegEnd[ii+1] << \", \";\n  cout << endl;\n\n  cout << \"Size Blocks : \" << endl;\n  for (ii=0;ii<NumBlocks();ii++)\n    cout << GetBlockSize(ii) << \" \";\n  cout << endl;\n}\n//////////////\n\nint CNRGarray::NumBlocks(){\n  \n  return((int)(QNumbers.size()/NQNumbers));\n\n}\n//////////////\nint CNRGarray::Nstates(){\n\n  return(BlockBegEnd[NQNumbers*(NumBlocks()-1)+1]-BlockBegEnd[0]+1);\n  \n}\n\n\n//////////////\nvoid CNRGarray::SetDegen(){\n\n  int nst,ii,jj;\n\n  // Needs work\n  \n//   iDegen.push_back(1);\n//   ii=1;\n//   while ( ii<dEn.size() )\n//     {\n//       if (fabs(dEn[ii]-dEn[ii-1])<1.0E-10) nst=iDegen[ii-1]+1;\n//       else nst=1;\n//       iDegen.push_back(nst);\n//       ii++;\n//     }\n\n}\n\n\nvoid CNRGarray::FilterQNumbers(){\n\n  int equal=0;\n  int ii,i1;\n\n  vector<double>::iterator qnums_iter,qnums_iter2,qnums_ii1,qnums_ii2;\n\n  for (qnums_iter=QNumbers.begin(); qnums_iter<QNumbers.end(); \n       qnums_iter+=NQNumbers)\n    {\n\n      //      cout << \"Iter1 = \" << (*qnums_iter) << endl;\n      ii=1;\n      qnums_iter2=qnums_iter+ii*NQNumbers;\n      while (qnums_iter2<QNumbers.end())\n\t{\n\t  //  cout << \"Iter2 = \" << (*qnums_iter2) << endl;\n\t  equal=1;\n\t  i1=0;\n\t  for (qnums_ii2=qnums_iter2;\n\t       qnums_ii2<qnums_iter2+NQNumbers;qnums_ii2++)\n\t    {\n\t      qnums_ii1=qnums_iter+i1;\n\t      if ( (*qnums_ii2==*qnums_ii1)&&(equal==1) ) equal=1;\n\t      else equal=0;\n\t      i1++;\n\t    }\n\t  if (equal==1)\n\t    {\n\t      QNumbers.erase(qnums_iter2,qnums_iter2+NQNumbers);             \n\t    }\n\t  ii++;\n\t  qnums_iter2=qnums_iter+ii*NQNumbers;\n\t}\n    }\n\n}\n\n//////////////\nvoid CNRGarray::ClearAll(){\n\n  QNumbers.clear();\n  dEn.clear();\n  dEigVec.clear();\n  iDegen.clear(); \n\n  BlockBegEnd.clear();\n  \n\n}\n\n//////////////\ndouble CNRGarray::GetQNumber(int iblock, int whichqn){\n\n  int iq=iblock*NQNumbers+whichqn;\n      \n  return(QNumbers[iq]);\n}\n\n//////////////\nint CNRGarray::GetBlockLimit(int iblock, int whichlimit){\n\n  return(BlockBegEnd[2*iblock+whichlimit]);\n  \n}\n\n//////////////\nint CNRGarray::GetBlockSize(int iblock){\n\n  return(BlockBegEnd[2*iblock+1]-BlockBegEnd[2*iblock]+1);\n  \n}\n\n\n////////////////////////////////////\n// Class CNRGbasisarray functions //\n////////////////////////////////////\n\n\n//////////////\n//void CNRGbasisarray::ClearVecsBasis(){\nvoid CNRGbasisarray::ClearAll(){\n\n  CNRGarray::ClearAll();\n\n  iType.clear();\n  StCameFrom.clear();\n  \n\n}\n//////////////\nvoid CNRGbasisarray::PrintAll(){\n\n  CNRGarray::PrintAll();\n\n  cout << \"Type : \" << endl;\n  for (int ii=0;ii<iType.size();ii++)\n    cout << iType[ii] << \" \";\n  cout << endl;\n\n  cout << \"StCameFrom : \" << endl;\n  for (int ii=0;ii<StCameFrom.size();ii++)\n    cout << StCameFrom[ii] << \" \";\n  cout << endl;\n  \n\n}\n///////////////////\n\n////////////////////////////////////\n// Class CNRGmatrix functions //\n////////////////////////////////////\n\n// vector<double> CNRGmatrix::GetFullMatrix(int Nst){\n\n//   vector<double> Mat((Nst*Nst),0.0); //All zeros\n  \n//   int i1;\n//   for (int ii=0;ii<vec.size();ii++)\n// \t{\n// \t  i1=ij2r(Nst,vec[ii].ist,vec[ii].jst);\n// \t  if (i1<Mat.size()) Mat[i1]=vec[ii].val;\n// \t  i1=ij2r(Nst,vec[ii].jst,vec[ii].ist);\n// \t  if (i1<Mat.size()) Mat[i1]=vec[ii].val;\n// \t}\n\n//   return(Mat);\n\n// }\n//////////////\nint CNRGmatrix::GetMatBlockLimit(int iblock1, int iblock2, int whichlimit){\n\n  int ii=0;\n\n  while ( ((iblock1!=MatBlockMap[ii])||(iblock2!=MatBlockMap[ii+1]))\n\t  &&(ii<MatBlockMap.size()) ) ii+=2;\n\n  return(MatBlockBegEnd[2*ii+whichlimit]);\n\n\n}\n\n//////////////\nint CNRGmatrix::GetMatBlockSize(int iblock1, int iblock2){\n\n  int ii=0;\n\n  while ( ((iblock1!=MatBlockMap[ii])||(iblock2!=MatBlockMap[ii+1]))\n\t  &&(ii<MatBlockMap.size()) ) ii+=2;\n\n  return(MatBlockBegEnd[2*ii+1]-MatBlockBegEnd[2*ii]+1);\n\n}\n\nvoid CNRGmatrix::DiagBlock(int iblock,\n\t\t\t   vector<double> &eigvalues, \n\t\t\t   vector<double> &eigvectors){\n\n  // LAPACK variables\n  char JOBZ='N',UPLO='U';\n  int Nst;\n  int INFO=0,LDA,LWORK;\n\n  // LDA=Nst\n  // LWORK=3*Nst-1\n\n  double *A;\n  double *eigv;\n  double *work;\n\n  // Get Block info\n\n  \n  Nst=GetMatBlockSize(iblock,iblock);\n//   cout << \"Size block                 : \" << GetBlockSize(iblock) << endl;\n//   cout << \"No of independent elements : \" << GetMatrixBlockSize(iblock) \n//        << endl;\n  \n  //Nst=2;\n  LDA=Nst;\n  LWORK=3*Nst-1;\n  eigv = new double [Nst];\n  work = new double [LWORK];\n  A = new double[Nst*Nst];\n\n\n  // I'll work on a routine to map upper triangular to r. \n  // For now, let's use this:\n  double **Aaux;\n  Aaux = new double*[Nst];\n  for (int ii=0;ii<Nst;ii++) Aaux[ii]=new double[Nst];\n\n\n  for (int ii=0;ii<MatEl.size();ii++)\n    {\n//       // This takes a tremendous amount of CPU time! Must do better!\n//       if ( (vec[ii].Bli==iblock)&&(vec[ii].Blj==iblock) )\n// \t{\n// \t  // Awful construcion. An invitation to segmentation faults.\n// \t  Aaux[vec[ii].ibl][vec[ii].jbl]=vec[ii].val;\n// \t  Aaux[vec[ii].jbl][vec[ii].ibl]=vec[ii].val;\n// \t}\n    }\n  int i1=0;\n  for (int ii=0;ii<Nst;ii++)\n    {\n      for (int jj=0;jj<Nst;jj++)\n\t{\n\t  A[i1]=Aaux[ii][jj];\n\t  i1++;\n\t}\n    }\n//   int i1=0;\n//   int r1=0;\n//   for (int i=GetBlockLimit(iblock,0);\n//            i<GetBlockLimit(iblock,1);i++)\n//     {\n//       for (int j=i;\n//            j<GetBlockLimit(iblock,1);j++)\n// \t{\n// \t  r1=ij2r(Nstates(),i,j);\n//       Aaux[]=vec[r1].val;\n// \t}\n//       i1++;\n//     }\n\n//   A[0]=1.0;\n//   A[1]=-sqrt(2.0);\n//   A[2]=-sqrt(2.0);\n//   A[3]=1.0;\n\n  dsyev_(&JOBZ,&UPLO,&Nst,&A[0],&LDA,eigv,work,&LWORK,&INFO);\n\n  for (int ii=0;ii<Nst;ii++)\n    {\n      eigvalues.push_back(eigv[ii]);\n      eigvectors.push_back(eigv[ii]);\n      cout << \" Block  : \" << iblock << endl;\n      std::cout << \"E = \" << eigvalues[ii] << std::endl;\n    }\n\n\n  delete[] eigv;\n  delete[] work;\n  delete[] A;\n\n  for (int ii=0;ii<Nst;ii++) delete[] Aaux[ii];\n  delete[] Aaux;\n\n\n}\n", "meta": {"hexsha": "9a8a29f6c313f01a6d0405e708a0226cf281f71e", "size": 7001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/OldStuff/NRGclasses.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/OldStuff/NRGclasses.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/OldStuff/NRGclasses.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.2865013774, "max_line_length": 77, "alphanum_fraction": 0.5420654192, "num_tokens": 2378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.42045041554942664}}
{"text": "#include \"modprop/compo/AdditiveWrapper.hpp\"\n#include \"modprop/neural/LinearLayer.hpp\"\n#include \"modprop/neural/FullyConnectedNet.hpp\"\n\n#include \"modprop/neural/HingeActivation.hpp\"\n#include \"modprop/neural/SigmoidActivation.hpp\"\n#include \"modprop/neural/NullActivation.hpp\"\n#include \"modprop/neural/NetworkTypes.h\"\n\n#include \"modprop/optim/SquaredLoss.hpp\"\n#include \"modprop/optim/StochasticMeanCost.hpp\"\n#include \"modprop/optim/ParameterL2Cost.hpp\"\n\n#include \"optim/Optimizers.h\"\n\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/random_device.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\n#include \"modprop/utils/Derivatives.hpp\"\n#include \"modprop/utils/Randomization.hpp\"\n\n#include <deque>\n#include <cstdlib>\n#include <iostream>\n\nusing namespace percepto;\n\n// Comment the above and uncomment below to use Rectified Linear Units instead\ntypedef PerceptronNet TestNet;\n// typedef ReLUNet TestNet;\n\nunsigned int inputDim = 1;\nunsigned int outputDim = 1;\nunsigned int numHiddenLayers = 3;\nunsigned int layerWidth = 20;\nunsigned int batchSize = 20;\n\nstruct Regressor\n{\n\tTerminalSource<VectorType> netInput;\n\tTestNet net;\n\tSquaredLoss<VectorType> loss;\n\n\tRegressor()\n\t: net( inputDim, outputDim, numHiddenLayers, layerWidth,\n\t       SigmoidActivation(), TestNet::OUTPUT_UNRECTIFIED )\n\t{\n\t\tnet.SetSource( &netInput );\n\t\tloss.SetSource( &net.GetOutputSource() );\n\t}\n\n\tRegressor( const Regressor& other )\n\t: net( other.net )\n\t{\n\t\tnet.SetSource( &netInput );\n\t\tloss.SetSource( &net.GetOutputSource() );\n\t}\n\n\tvoid Foreprop()\n\t{\n\t\tnetInput.Foreprop();\n\t}\n\n\tdouble GetOutput()\n\t{\n\t\treturn net.GetOutput()(0);\n\t}\n\n\tvoid Invalidate()\n\t{\n\t\tnetInput.Invalidate();\n\t}\n};\n\nstruct RegressionProblem\n: public NaturalOptimizationProblem\n{\n\tstd::deque<Regressor> regressors;\n\tStochasticMeanCost<double> losses;\n\tParameterL2Cost regularizer;\n\tAdditiveWrapper<double> objective;\n\t\n\tParameters::Ptr params;\n\n\tRegressionProblem( Parameters::Ptr p,\n\t                   unsigned int batchSize,\n\t                   double l2Weight ) \n\t{\n\t\tparams = p;\n\t\tlosses.SetBatchSize( batchSize );\n\t\tregularizer.SetWeight( l2Weight );\n\t\tregularizer.SetParameters( params );\n\t\tobjective.SetSourceA( &losses );\n\t\tobjective.SetSourceB( &regularizer );\n\t}\n\n\tvirtual bool IsMinimization() const { return true; }\n\n\tvirtual void Resample()\n\t{\n\t\tlosses.Resample();\n\t}\n\n\tvirtual double ComputeObjective()\n\t{\n\t\tInvalidate();\n\t\tForeprop();\n\t\treturn objective.GetOutput();\n\t}\n\n\tvirtual VectorType ComputeGradient()\n\t{\n\t\tInvalidate();\n\t\tForeprop();\n\t\tBackprop();\n\t\treturn params->GetDerivs();\n\t}\n\n\tvirtual VectorType ComputeNaturalGradient()\n\t{\n\t\tInvalidate();\n\t\tForeprop();\n\t\tBackpropNatural();\n\t\treturn params->GetDerivs();\n\t}\n\n\tvirtual VectorType GetParameters() const\n\t{\n\t\treturn params->GetParamsVec();\n\t}\n\n\tvirtual void SetParameters( const VectorType& p )\n\t{\n\t\tparams->SetParamsVec( p );\n\t}\n\n\tvoid Invalidate()\n\t{\n\t\tfor( unsigned int i = 0; i < regressors.size(); i++ )\n\t\t{\n\t\t\tregressors[i].Invalidate();\n\t\t}\n\t\tregularizer.Invalidate();\n\t\tparams->ResetAccumulators();\n\t}\n\n\tvoid Foreprop()\n\t{\n\t\tconst std::vector<unsigned int>& inds = losses.GetActiveInds();\n\t\tBOOST_FOREACH( unsigned int i, inds )\n\t\t{\n\t\t\tregressors[i].Foreprop();\n\t\t}\n\t\tregularizer.Foreprop();\n\t}\n\n\tvoid ForepropAll()\n\t{\n\t\tfor( unsigned int i = 0; i < regressors.size(); i++ )\n\t\t{\n\t\t\tregressors[i].Foreprop();\n\t\t}\n\t\tregularizer.Foreprop();\n\t}\n\n\tvoid Backprop()\n\t{\n\t\tobjective.Backprop( MatrixType::Identity(1,1) );\n\t}\n\n\tvoid BackpropNatural()\n\t{\n\t\tconst std::vector<unsigned int>& inds = losses.GetActiveInds();\n\t\tMatrixType dodw = MatrixType::Identity( 1, 1 ) / inds.size();\n\t\tBOOST_FOREACH( unsigned int i, inds )\n\t\t{\n\t\t\tregressors[i].loss.Backprop( dodw );\n\t\t}\n\t}\n};\n\n// The highly nonlinear function we will try to fit\ndouble f( double x )\n{\n\treturn 8 * std::cos( x ) + 2.5 * x * sin( x ) + 2.8 * x;\n}\n\n// Generate a specified number of random xs and corresponding ys\nvoid generate_data( std::vector<VectorType>& xs,\n                    std::vector<VectorType>& ys,\n                    unsigned int num_data )\n{\n\tboost::random::mt19937 generator;\n\tboost::random::random_device rng;\n\tgenerator.seed( rng );\n\tboost::random::uniform_real_distribution<> xDist( -5.0, 5.0 );\n\n\txs.clear(); \n\tys.clear(); \n\txs.reserve( num_data );\n\tys.reserve( num_data );\n\n\tVectorType x(1,1);\n\tVectorType y(1,1);\n\tfor( unsigned int i = 0; i < num_data; i++ )\n\t{\n\t\tx(0) = xDist( generator );\n\t\ty(0) = f( x(0) );\n\t\txs.push_back( x );\n\t\tys.push_back( y );\n\t}\n}\n\nint main( int argc, char** argv )\n{\n\tunsigned int numTrain = 150;\n\tunsigned int numTest = 200;\n\tdouble l2Weight = 1E-3;\n\n\tstd::vector<VectorType> xTest, yTest, xTrain, yTrain;\n\tgenerate_data( xTest, yTest, numTest );\n\tgenerate_data( xTrain, yTrain, numTrain );\n\n\tstd::cout << \"Initializing net...\" << std::endl;\n\tstd::cout << \"Creating linear layers...\" << std::endl;\n\n\t// // ReLU initialization\n\tRegressor reg;\n\tParameters::Ptr params = reg.net.CreateParameters();\n\n\t// Randomize parameters\n\tVectorType p( params->ParamDim() );\n\trandomize_vector( p, -0.2, 0.2 );\n\tparams->SetParamsVec( p );\n\tstd::cout << \"Initial net: \" << std::endl << reg.net << std::endl;\n\n\t// Create the loss functions\n\tstd::cout << \"Generating losses...\" << std::endl;\n\tRegressionProblem trainProblem( params, batchSize, l2Weight );\n\tRegressionProblem testProblem( params, batchSize, l2Weight );\n\t\n\t// NOTE If we don't reserve, the vector resizing and moving may\n\t// invalidate the references. Alternatively we can use a deque\n\tfor( unsigned int i = 0; i < numTrain; i++ )\n\t{\n\t\ttrainProblem.regressors.emplace_back( reg );\n\t\ttrainProblem.regressors[i].netInput.SetOutput( xTrain[i] );\n\t\ttrainProblem.regressors[i].loss.SetTarget( yTrain[i] );\n\t\ttrainProblem.losses.AddSource( &trainProblem.regressors[i].loss );\n\t}\n\n\tfor( unsigned int i = 0; i < numTest; i++ )\n\t{\n\t\ttestProblem.regressors.emplace_back( reg );\n\t\ttestProblem.regressors[i].netInput.SetOutput( xTest[i] );\n\t\ttestProblem.regressors[i].loss.SetTarget( yTest[i] );\n\t\ttestProblem.losses.AddSource( &testProblem.regressors[i].loss );\n\t}\n\n\tModularOptimizer optimizer;\n\t\n\t// AdamSearchDirector::Ptr director = std::make_shared<AdamSearchDirector>();\n\t// GradientSearchDirector::Ptr director = std::make_shared<GradientSearchDirector>();\n\tNaturalSearchDirector::Ptr director = std::make_shared<NaturalSearchDirector>();\n\toptimizer.SetSearchDirector( director );\n\n\tBacktrackingSearchStepper::Ptr stepper = std::make_shared<BacktrackingSearchStepper>();\n\tstepper->SetInitialStep( 1E-1 );\n\tstepper->SetBacktrackingRatio( 0.5 );\n\tstepper->SetMaxBacktracks( 20 );\n\tstepper->SetImprovementRatio( 0.75 );\n\n\t// L1ConstrainedSearchStepper::Ptr stepper = std::make_shared<L1ConstrainedSearchStepper>();\n\t// stepper->SetMaxL1Norm( 1E-1 );\n\t// stepper->SetStepSize( 1E-2 );\n\toptimizer.SetSearchStepper( stepper );\n\n\tRuntimeTerminationChecker::Ptr runtimeChecker = std::make_shared<RuntimeTerminationChecker>();\n\truntimeChecker->SetMaxRuntime( 20 );\n\toptimizer.AddTerminationChecker( runtimeChecker );\n\n\t// GradientTerminationChecker::Ptr gradientChecker = std::make_shared<GradientTerminationChecker>();\n\t// gradientChecker->SetMinGradientNorm( 1E-9 );\n\t// optimizer.AddTerminationChecker( gradientChecker );\n\n\t// IterationTerminationChecker::Ptr iterationChecker = std::make_shared<IterationTerminationChecker>();\n\t// iterationChecker->SetMaxIterations( 1e3 );\n\t// optimizer.AddTerminationChecker( iterationChecker );\n\n\ttrainProblem.Invalidate();\n\ttestProblem.Invalidate();\n\ttrainProblem.ForepropAll();\n\ttestProblem.ForepropAll();\n\ttrainProblem.losses.ParentCost::Foreprop();\n\ttestProblem.losses.ParentCost::Foreprop();\n\tstd::cout << \"initial train avg loss: \" << trainProblem.losses.ParentCost::GetOutput() << std::endl;\n\tstd::cout << \"initial train max loss: \" << trainProblem.losses.ParentCost::ComputeMax() << std::endl;\n\tstd::cout << \"initial test avg loss: \" << testProblem.losses.ParentCost::GetOutput() << std::endl;\n\tstd::cout << \"initial test max loss: \" << testProblem.losses.ParentCost::ComputeMax() << std::endl;\n\n\tstd::cout << \"Beginning optimization...\" << std::endl;\n\toptimizer.ResetAll();\n\ttrainProblem.Resample();\n\tOptimizationResults result = optimizer.Optimize( trainProblem );\n\tstd::cout << \"Terminated with condition: \" << result.status << std::endl;\n\tstd::cout << \"Final net: \" << std::endl << reg.net << std::endl;\n\n\ttrainProblem.Invalidate();\n\ttestProblem.Invalidate();\n\ttrainProblem.ForepropAll();\n\ttestProblem.ForepropAll();\n\ttrainProblem.losses.ParentCost::Foreprop();\n\ttestProblem.losses.ParentCost::Foreprop();\n\tstd::cout << \"train avg loss: \" << trainProblem.losses.ParentCost::GetOutput() << std::endl;\n\tstd::cout << \"train max loss: \" << trainProblem.losses.ParentCost::ComputeMax() << std::endl;\n\tstd::cout << \"test avg loss: \" << testProblem.losses.ParentCost::GetOutput() << std::endl;\n\tstd::cout << \"test max loss: \" << testProblem.losses.ParentCost::ComputeMax() << std::endl;\n\n\tfor( unsigned int i = 0; i < numTest; i++ )\n\t{\n\t\tstd::cout << \"xtest: \" << xTest[i] << \" ytest: \" << yTest[i]\n\t\t          << \" regout: \" << testProblem.regressors[i].GetOutput() << std::endl;\n\t}\n\n\treturn 0;\n}", "meta": {"hexsha": "a0c5abf45b23065616cb49e918adf062f396e002", "size": 9140, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "optim/tests/NetworkTest.cpp", "max_stars_repo_name": "Humhu/percepto", "max_stars_repo_head_hexsha": "4a45cce7dd294a8ce0b962bb68cae5c2b48c3b7f", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-15T09:34:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-15T09:34:24.000Z", "max_issues_repo_path": "optim/tests/NetworkTest.cpp", "max_issues_repo_name": "Humhu/percepto", "max_issues_repo_head_hexsha": "4a45cce7dd294a8ce0b962bb68cae5c2b48c3b7f", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optim/tests/NetworkTest.cpp", "max_forks_repo_name": "Humhu/percepto", "max_forks_repo_head_hexsha": "4a45cce7dd294a8ce0b962bb68cae5c2b48c3b7f", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9510703364, "max_line_length": 104, "alphanum_fraction": 0.7059080963, "num_tokens": 2474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.42045040849717774}}
{"text": "#include <armadillo>\n#include <emissions.hpp>\n#include <ForwardBackward.hpp>\n#include <cmath>\n#include <json.hpp>\n#include <iostream>\n#include <vector>\n\nusing namespace arma;\nusing namespace std;\nusing json = nlohmann::json;\n\nnamespace hsmm {\n\n    double gaussianlogpdf_(double x, double mu, double sigma) {\n        double ret = ((x - mu)*(x - mu)) / (-2*sigma*sigma);\n        ret = ret - log(sqrt(2 * M_PI) * sigma);\n        return ret;\n    }\n\n    double gaussianpdf_(double x, double mu, double sigma) {\n        return exp(gaussianlogpdf_(x, mu, sigma));\n    }\n\n    field<mat> fromMatToField(const mat& obs) {\n        field<mat> ret(obs.n_cols);\n        for(int i = 0; i < obs.n_cols; i++)\n            ret(i) = obs.col(i);\n        return ret;\n    }\n\n    mat fromFieldToMat(const field<mat>& obs) {\n        int total_cols = 0;\n        int total_rows = obs(0).n_rows;\n        for(auto& m : obs) {\n            total_cols += m.n_cols;\n            assert(m.n_rows == total_rows);\n        }\n        mat ret(total_rows, total_cols);\n        int idx = 0;\n        for(auto& m: obs) {\n            ret.cols(idx, m.n_cols - 1) = m;\n            idx += m.n_cols;\n        }\n        return ret;\n    }\n\n\n    /**\n     * Abstract emission implementation.\n     */\n    AbstractEmission::AbstractEmission(int nstates, int dimension) :\n            nstates_(nstates), dimension_(dimension) {}\n\n    int AbstractEmission::getNumberStates() const {\n        return nstates_;\n    }\n\n    int AbstractEmission::getDimension() const {\n        return dimension_;\n    }\n\n    cube AbstractEmission::likelihoodCube(int min_duration, int ndurations,\n            const field<mat>& obs) const {\n        return exp(loglikelihoodCube(min_duration, ndurations, obs));\n    }\n\n    // This should return a cube of dimensions (nstates, nobs, ndurations)\n    // where the entry (i, j, k) is the log-likelihood of the observations\n    // in the interval [j, min_duration + k - 1] being produced by state i.\n    cube AbstractEmission::loglikelihoodCube(int min_duration, int ndurations,\n            const field<mat>& obs) const {\n        int nobs = obs.n_elem;\n        cube pdf(getNumberStates(), nobs, ndurations);\n        pdf.fill(-datum::inf);\n        for(int i = 0; i < getNumberStates(); i++)\n            for(int t = 0; t < nobs; t++)\n                for(int d = 0; d < ndurations; d++) {\n                    if (t + min_duration + d > nobs)\n                        break;\n                    int end_idx = t + min_duration + d - 1;\n                    pdf(i, t, d) = loglikelihood(i, obs.rows(t, end_idx));\n                }\n        return pdf;\n    }\n\n    field<mat> AbstractEmission::sampleFromState(int state, int size) {\n        return sampleFromState(state, size, rand_generator_);\n    }\n\n    json AbstractEmission::to_stream() const {\n        cout << \"Warning: serialization of emission parameters not implemented\"\n                << endl;\n        return json::object();  // empty json object by default.\n    }\n\n    void AbstractEmission::from_stream(const json& emission_params) {\n        cout << \"Warning: not updating the emission parameters from the stream\"\n                << endl;\n        return;\n    }\n\n\n    /*\n     * AbstractEmissionOnlineSetting implementation\n     */\n    field<mat> AbstractEmissionOnlineSetting::sampleNextObsGivenPastObs(int state,\n            int seg_dur, const field<mat>& past_obs) {\n        return sampleNextObsGivenPastObs(state, seg_dur, past_obs,\n                rand_generator_);\n    }\n\n    // Default implementation. Disregards any information from the last\n    // segment.\n    field<mat> AbstractEmissionOnlineSetting::sampleFirstSegmentObsGivenLastSegment(\n            int curr_state, int curr_seg_dur, const field<mat> &last_segment,\n            int last_state, std::mt19937 &rng) const {\n        field<mat> empty_segment;\n        return sampleNextObsGivenPastObs(curr_state, curr_seg_dur,\n                empty_segment, rng);\n    }\n\n    field<mat> AbstractEmissionOnlineSetting::sampleFirstSegmentObsGivenLastSegment(\n            int curr_state, int curr_seg_dur, const field<mat> &last_segment,\n            int last_state) {\n        return sampleFirstSegmentObsGivenLastSegment(curr_state, curr_seg_dur,\n                last_segment, last_state, rand_generator_);\n    }\n\n    /**\n     * AbstractEmissionIIDobs implementation\n     */\n    AbstractEmissionConditionalIIDobs::AbstractEmissionConditionalIIDobs(\n            int nstates, int dimension) :\n            AbstractEmission(nstates, dimension) {}\n\n    double AbstractEmissionConditionalIIDobs::loglikelihood(int state,\n            const field<mat>& obs) const {\n        double ret = 0;\n        int seg_dur = obs.n_elem;\n        for(int i = 0; i < seg_dur; i++) {\n\n            // If there are missing outputs just skip them.\n            if (!obs(i).is_empty())\n                ret += loglikelihoodIIDobs(state, seg_dur, i, obs(i));\n        }\n        return ret;\n    }\n\n\n    /**\n     * DummyGaussianEmission implementation.\n     */\n    DummyGaussianEmission::DummyGaussianEmission(vec& means, vec& std_devs) :\n            AbstractEmissionOnlineSetting(means.n_elem, 1), means_(means),\n            std_devs_(std_devs) {\n        assert(means_.n_elem == std_devs_.n_elem);\n    }\n\n    DummyGaussianEmission* DummyGaussianEmission::clone() const {\n        return new DummyGaussianEmission(*this);\n    }\n\n    double DummyGaussianEmission::loglikelihood(int state,\n            const field<mat>& obs) const {\n        double ret = 0;\n        int seg_dur = obs.n_elem;\n        for(int i = 0; i < seg_dur; i++) {\n\n            // If there are missing outputs just skip them.\n            if (!obs(i).is_empty())\n                ret += loglikelihoodIIDobs(state, seg_dur, i, obs(i));\n        }\n        return ret;\n    }\n\n    double DummyGaussianEmission::loglikelihoodIIDobs(int state, int seg_dur,\n            int offset, const mat& single_obs) const {\n        assert(single_obs.n_rows == 1 && single_obs.n_cols == 1);\n        return gaussianlogpdf_(single_obs(0, 0), means_(state),\n                std_devs_(state));\n    }\n\n    json DummyGaussianEmission::to_stream() const {\n        vector<double> means = conv_to<vector<double>>::from(means_);\n        vector<double> std_devs = conv_to<vector<double>>::from(std_devs_);\n        json ret;\n        ret[\"means\"] = means;\n        ret[\"std_devs\"] = std_devs;\n        return ret;\n    }\n\n    void DummyGaussianEmission::reestimate(int min_duration,\n            const field<cube>& meta, const field<field<mat>>& mobs) {\n        int nseq = mobs.n_elem;\n        for(int i = 0; i < getNumberStates(); i++) {\n\n            // Reestimating the mean.\n            vector<double> num_mult;\n            vector<double> num_obs;\n            for(int s = 0; s < nseq; s++) {\n                auto& obs = mobs(s);\n                int nobs = obs.n_elem;\n                const cube& eta = meta(s);\n                int ndurations = eta.n_cols;\n                for(int t = min_duration - 1; t < nobs; t++) {\n                    for(int d = 0; d < ndurations; d++) {\n                        int first_idx_seg = t - min_duration - d + 1;\n                        if (first_idx_seg < 0)\n                            break;\n\n                        // Since the observations factorize given t, d and i.\n                        for(int k = first_idx_seg; k <= t; k++) {\n                            num_mult.push_back(eta(i, d, t));\n                            num_obs.push_back(obs(k)(0,0));\n                        }\n                    }\n                }\n            }\n            vec num_mult_v(num_mult);\n            vec num_obs_v(num_obs);\n            num_mult_v = num_mult_v - logsumexp(num_mult_v);\n            num_mult_v = exp(num_mult_v);\n            double new_mean = dot(num_mult_v, num_obs_v);\n\n            // Reestimating the variance.\n            vector<double> num_obs_var;\n            for(int s = 0; s < nseq; s++) {\n                const auto& obs = mobs(s);\n                int nobs = obs.n_elem;\n                const cube& eta = meta(s);\n                int ndurations = eta.n_cols;\n                for(int t = min_duration - 1; t < nobs; t++) {\n                    for(int d = 0; d < ndurations; d++) {\n                        int first_idx_seg = t - min_duration - d + 1;\n                        if (first_idx_seg < 0)\n                            break;\n\n                        // Since the observations factorize given t, d and i.\n                        for(int k = first_idx_seg; k <= t; k++) {\n                            double diff = (obs(k)(0,0) - new_mean);\n                            num_obs_var.push_back(diff * diff);\n                        }\n                    }\n                }\n            }\n            vec num_obs_var_v(num_obs_var);\n            double new_variance = dot(num_mult_v, num_obs_var_v);\n\n            means_(i) = new_mean;\n            std_devs_(i) = sqrt(new_variance);\n        }\n    }\n\n    field<mat> DummyGaussianEmission::sampleFromState(int state,\n            int size, mt19937 &rng) const {\n        mat ret = randn<mat>(1, size) * std_devs_(state) + means_(state);\n        return fromMatToField(ret);\n    }\n\n    field<mat> DummyGaussianEmission::sampleNextObsGivenPastObs(int state,\n            int seg_dur, const field<mat>& past_obs, mt19937 &rng) const {\n        assert(past_obs.n_elem < seg_dur);\n        field<mat> ret(seg_dur);\n        int idx = 0;\n        for(int i = 0; i < past_obs.n_elem; i++, idx++)\n            ret(i) = past_obs(i);\n        for(int i = idx; i < seg_dur; i++)\n            ret(i) = randn<mat>(1, 1) * std_devs_(state) + means_(state);\n        return ret;\n    }\n\n\n    /**\n     * DummyMultivariateGaussianEmission implementation.\n     */\n    DummyMultivariateGaussianEmission::DummyMultivariateGaussianEmission(\n            mat& means, double std_dev_output_noise) :\n            AbstractEmission(means.n_rows, means.n_cols), means_(means),\n            std_dev_output_noise_(std_dev_output_noise) {}\n\n    DummyMultivariateGaussianEmission* DummyMultivariateGaussianEmission::\n            clone() const {\n        return new DummyMultivariateGaussianEmission(*this);\n    }\n\n    double DummyMultivariateGaussianEmission::loglikelihood(int state,\n                const field<mat>& obs) const {\n        mat copy_obs = fromFieldToMat(obs);\n        assert(copy_obs.n_rows == getDimension());\n        int size = copy_obs.n_cols;\n        for(int i = 0; i < getDimension(); i++)\n            copy_obs.row(i) -= linspace<rowvec>(0.0, 1.0, size) +\n                    means_(state, i);\n        double ret = 0.0;\n        for(int i = 0; i < getDimension(); i++)\n            for(int j = 0; j < size; j++)\n                ret += gaussianlogpdf_(copy_obs(i, j), 0,\n                        std_dev_output_noise_);\n        return ret;\n    }\n\n    void DummyMultivariateGaussianEmission::reestimate(int min_duration,\n            const field<cube>& eta, const field<field<mat>>& mobs) {\n        // TODO.\n    }\n\n    field<mat> DummyMultivariateGaussianEmission::sampleFromState(\n            int state, int size, mt19937 &rng) const {\n        mat ret = randn<mat>(getDimension(), size) * std_dev_output_noise_;\n        for(int i = 0; i < getDimension(); i++)\n            ret.row(i) += linspace<rowvec>(0.0, 1.0, size) + means_(state, i);\n        return fromMatToField(ret);\n    }\n\n};\n\n", "meta": {"hexsha": "55525610345d1bde2eeb51ddd5877b5ec068ad89", "size": 11308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/emissions.cpp", "max_stars_repo_name": "DiegoAE/BOSD", "max_stars_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T05:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:14:31.000Z", "max_issues_repo_path": "src/emissions.cpp", "max_issues_repo_name": "DiegoAE/BOSD", "max_issues_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T15:29:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T10:14:54.000Z", "max_forks_repo_path": "src/emissions.cpp", "max_forks_repo_name": "DiegoAE/BOSD", "max_forks_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T07:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T07:44:09.000Z", "avg_line_length": 35.5597484277, "max_line_length": 84, "alphanum_fraction": 0.5619915104, "num_tokens": 2723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.42039750381364044}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Johannes Goettker-Schnetmann\n Copyright (C) 2015 Klaus Spanderen\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/math/functional.hpp>\n#include <ql/time/calendars/nullcalendar.hpp>\n#include <ql/processes/hestonprocess.hpp>\n#include <ql/processes/blackscholesprocess.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/termstructures/volatility/equityfx/blackconstantvol.hpp>\n#include <ql/experimental/finitedifferences/bsmrndcalculator.hpp>\n#include <ql/experimental/finitedifferences/hestonrndcalculator.hpp>\n\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n#include <boost/bind.hpp>\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\n#include <complex>\n\nnamespace QuantLib {\n\nnamespace {\n        struct HestonParams {\n            Real v0, kappa, theta, sigma, rho;\n        };\n\n        HestonParams getHestonParams(\n            const ext::shared_ptr<HestonProcess>& process) {\n            const HestonParams p = { process->v0(),    process->kappa(),\n                                     process->theta(), process->sigma(),\n                                     process->rho() };\n            return p;\n        }\n\n        std::complex<Real> gamma(const HestonParams& p, Real p_x) {\n            return std::complex<Real>(p.kappa, p.rho*p.sigma*p_x);\n        }\n\n        std::complex<Real> omega(const HestonParams& p, Real p_x) {\n           const std::complex<Real> g = gamma(p, p_x);\n           return std::sqrt(g*g\n                  + p.sigma*p.sigma*std::complex<Real>(p_x*p_x, -p_x));\n        }\n\n        class CpxPv_Helper\n            : public std::unary_function<Real, Real > {\n          public:\n            CpxPv_Helper(const HestonParams& p, Real x, Time t)\n              : p_(p), t_(t), x_(x),\n                c_inf_(std::min(10.0, std::max(0.0001,\n                      std::sqrt(1.0-square<Real>()(p_.rho))/p_.sigma))\n                      *(p_.v0 + p_.kappa*p_.theta*t))  {}\n\n            Real operator()(Real x) const {\n                return std::real(transformPhi(x));\n            }\n\n            Real p0(Real p_x) const {\n                if (p_x < QL_EPSILON) {\n                    return 0.0;\n                }\n\n                const Real u_x = std::max(QL_EPSILON, -std::log(p_x)/c_inf_);\n                return std::real(phi(u_x)\n                        /((p_x*c_inf_)*std::complex<Real>(0.0, u_x)));\n            }\n\n          private:\n            std::complex<Real> transformPhi(Real x) const {\n                if (x < QL_EPSILON) {\n                    return std::complex<Real>(0.0, 0.0);\n                }\n\n                const Real u_x = -std::log(x)/c_inf_;\n                return phi(u_x)/(x*c_inf_);\n            }\n\n            std::complex<Real> phi(Real p_x) const {\n                const Real sigma2 = p_.sigma*p_.sigma;\n                const std::complex<Real> g = gamma(p_, p_x);\n                const std::complex<Real> o = omega(p_, p_x);\n                const std::complex<Real> gamma = (g-o)/(g+o);\n\n                return 2.0*std::exp(std::complex<Real>(0.0, p_x*x_)\n                        - p_.v0*std::complex<Real>(p_x*p_x, -p_x)\n                          /(g+o*(1.0+std::exp(-o*t_))/(1.0-std::exp(-o*t_)))\n                         +p_.kappa*p_.theta/sigma2*(\n                           (g-o)*t_ - 2.0*std::log((1.0-gamma*std::exp(-o*t_))\n                                                               /(1.0-gamma))));\n            }\n\n            const HestonParams& p_;\n            const Time t_;\n            const Real x_, c_inf_;\n        };\n    }\n\n\n    HestonRNDCalculator::HestonRNDCalculator(\n        const ext::shared_ptr<HestonProcess>& hestonProcess,\n        Real integrationEps, Size maxIntegrationIterations)\n    : hestonProcess_(hestonProcess),\n      x0_(std::log(hestonProcess_->s0()->value())),\n      integrationEps_(integrationEps),\n      maxIntegrationIterations_(maxIntegrationIterations) { }\n\n    Real HestonRNDCalculator::x_t(Real x, Time t) const {\n        const DiscountFactor dr = hestonProcess_->riskFreeRate()->discount(t);\n        const DiscountFactor dq = hestonProcess_->dividendYield()->discount(t);\n\n        return x - x0_ + std::log(dr/dq);\n    }\n\n    Real HestonRNDCalculator::pdf(Real x, Time t) const {\n        return GaussLobattoIntegral(\n            maxIntegrationIterations_, 0.1*integrationEps_)(\n            CpxPv_Helper(getHestonParams(hestonProcess_), x_t(x, t), t),\n            0.0, 1.0)/M_TWOPI;\n    }\n\t\n    Real HestonRNDCalculator::cdf(Real x, Time t) const {\n        return GaussLobattoIntegral(\n            maxIntegrationIterations_, 0.1*integrationEps_)(\n            boost::bind(&CpxPv_Helper::p0,\n                CpxPv_Helper(getHestonParams(hestonProcess_), x_t(x,t),t),_1),\n            0.0, 1.0)/M_TWOPI + 0.5;\n\n    }\n    Real HestonRNDCalculator::invcdf(Real p, Time t) const {\n        const Real v0    = hestonProcess_->v0();\n        const Real kappa = hestonProcess_->kappa();\n        const Real theta = hestonProcess_->theta();\n\n        const Volatility expVol\n            = std::sqrt(theta + (v0-theta)*(1-std::exp(-kappa*t))/(t*kappa));\n\n        const ext::shared_ptr<BlackScholesMertonProcess> bsmProcess(\n            ext::make_shared<BlackScholesMertonProcess>(\n                hestonProcess_->s0(),\n                hestonProcess_->dividendYield(),\n                hestonProcess_->riskFreeRate(),\n                Handle<BlackVolTermStructure>(\n                    ext::make_shared<BlackConstantVol>(\n                            hestonProcess_->riskFreeRate()->referenceDate(),\n                            NullCalendar(),\n                            expVol,\n                            hestonProcess_->riskFreeRate()->dayCounter()))));\n\n        const Real guess = BSMRNDCalculator(bsmProcess).invcdf(p, t);\n\n        return RiskNeutralDensityCalculator::InvCDFHelper(\n            this, guess, 0.1*integrationEps_, maxIntegrationIterations_)\n            .inverseCDF(p, t);\n    }\n}\n", "meta": {"hexsha": "86f78242f982b3ff18440df69954c68377ac3d6a", "size": 6840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/finitedifferences/hestonrndcalculator.cpp", "max_stars_repo_name": "tlapfai/My-Quantlib", "max_stars_repo_head_hexsha": "9e24dafd8c849659d3a9b4b432abf854441ab825", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ql/experimental/finitedifferences/hestonrndcalculator.cpp", "max_issues_repo_name": "tlapfai/My-Quantlib", "max_issues_repo_head_hexsha": "9e24dafd8c849659d3a9b4b432abf854441ab825", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/finitedifferences/hestonrndcalculator.cpp", "max_forks_repo_name": "tlapfai/My-Quantlib", "max_forks_repo_head_hexsha": "9e24dafd8c849659d3a9b4b432abf854441ab825", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4269662921, "max_line_length": 87, "alphanum_fraction": 0.5751461988, "num_tokens": 1762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4203797836795593}}
{"text": "//\n//  ShamirSharesEngine.cpp\n//  edgeRuntime\n//  online modulus version branched\n//  Any version of an Engine nees to instantiate th buffers and the ZZ field as well.\n//  Created by Abdelrahaman Aly on 20/11/13.\n//  Copyright (c) 2013 Abdelrahaman Aly. All rights reserved.\n//\n\n#include <iostream>\n\n#include <math.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n#include <NTL/ZZ_pX.h>\n\n#include <cstdlib>\n//#include <mach/mach.h>\n//#include <mach/mach_time.h>\n\n#include \"MathUtil.h\"\n\n#include \"StandardPlayer.h\"\n#include \"StandardShare.h\"\n\n#include \"SharesManager.h\"\n#include \"ShamirSharesEngine.h\"\n#include \"SharesListener.h\"\n#include \"EngineBuffers.h\"\n\n#include \"Constants.h\"\n#include \"ShareUtil.h\"\n#include \"List.h\"\n\n\nusing namespace NTL;\n\nnamespace SmcEngines\n{\n    Listeners::SharesListener * ShamirSharesEngine::listener_=NULL;\n       double ShamirSharesEngine::relativeTime=0;\n    \n    //Configuration Methods Implementations\n    \n    ShamirSharesEngine::ShamirSharesEngine(Players::StandardPlayer * player,  Utils::List<Players::StandardPlayer> * players, bool signed_)\n    {\n        //initialize engine varialbes\n        this->player_ = player;\n        this->players_=players;\n        this->signed_=signed_;\n        this->nBits_= Utilities::Constants::SYSTEM_B;\n        this->p_=Utilities::Constants::SYSTEM_P;\n        this->l_= Utilities::Constants::SYSTEM_L;\n        this->k_=Utilities::Constants::SYSTEM_K;\n        std::cout<<\"p \"<< this->p_<<\" \"<<sizeof(long long)<<\"\\n\";\n        NTL::ZZ_p::init(NTL::conv<NTL::ZZ>(this->p_));\n        //std::cout<< \"the result: \"<< conv<ZZ_p>(2)*conv<ZZ_p>(2)<<\"\\n\";\n        //generates all alpha vectors that might be necessary to compare bit strings\n        this->lAlphas_ = new vec_ZZ_p[this->nBits_];\n        for (int i =1; i<= this->nBits_; i++)\n        {\n            this->lAlphas_[i-1]= VectorCopy(Utilities::MathUtil::multiplyLagrangePolynomials(1, i+1, 1),(i+1)+1);\n        }\n        \n        //initialize context objects\n        this->shareManager_ = new Managers::SharesManager(player, players);\n        this->generator_= new ShareGenerators::ShamirGenerator(player,this->p_);\n        \n        //initialize application buffers\n        for (int i=0;i<players_->getLength(); i++)\n        {\n            Buffers::EngineBuffers::syncBuffer_.push_back( NULL);\n        }\n        \n        Buffers::EngineBuffers::workingBuffer_=new Utils::List<Shares::StandardShare>(this->players_->getLength());\n        Buffers::EngineBuffers::nextOperationBuffer_=new Utils::List<Shares::StandardShare>(this->players_->getLength());\n        \n        //start listeners\n        ShamirSharesEngine::listener_= new Listeners::SharesListener(this->player_,this->players_);\n        ShamirSharesEngine::listener_->startListner();\n    };\n    \n    Players::StandardPlayer * ShamirSharesEngine::getPlayer()\n    {\n        return this->player_;\n    };\n    //private native operations\n    \n    //Native implementation eliminating the conversion process should accelerate it. Loose of generality thinking on reliability.\n    long ShamirSharesEngine::addSecure(long a, long b)\n    {\n        //Modulus operation perform by NTL libraries.\n        NTL::ZZ_p ap= NTL::conv<NTL::ZZ_p>(a);\n        ZZ_p bp= conv<ZZ_p>(b);\n        return conv<long>(ap+bp);\n    };\n    \n    //Native implementation eliminating the conversion process should accelerate it. Loose of generality thinking on reliability.\n    long ShamirSharesEngine::multiplySecure(long a, long b)\n    {\n        //Modulus operation perform by NTL libraries.\n        NTL::ZZ_p ap= NTL::conv<NTL::ZZ_p>(a);\n        ZZ_p bp= conv<ZZ_p>(b);\n        \n        return conv<long>(ap*bp);\n    };\n    \n    //add scalar with shared values\n    long ShamirSharesEngine::addScalarSecure(long  a, long  shareValue)\n    {\n        return 0;\n    };\n    \n    //returns  a-b in modulo p\n    long ShamirSharesEngine::substractSecure(long  a, long  b)\n    {\n        //changes the sign of the share value -- this is just a -1 multiplication at the moment given that scalar mult.\n        //can be done without communication.\n        long aux = this->multiplySecure(-1, b);//multiplication method used bc it performs finite field mult.\n        return this->addSecure(a, aux);// add method used bc it performs finit field add.\n    };\n    \n    //private bitwise operations\n    \n    //calculates next carry bit\n    Shares::StandardShare * ShamirSharesEngine::carrySharemindSecure(Shares::StandardShare * a, Shares::StandardShare * b,Shares::StandardShare * c)\n    {\n        Shares::StandardShare * carry = this->multiplyShares(a,b);\n        Shares::StandardShare * aux= this->multiplyShares(b, c);\n        carry= this->xorShares(carry, aux);\n        aux= this->multiplyShares(a, c);\n        carry=this->xorShares(carry, aux);\n        \n        delete aux;\n        delete carry;\n        \n        return carry;\n    };\n    \n    //performs bit addition in a secure fashion\n    Utils::List<Shares::StandardShare> * ShamirSharesEngine::bitwiseAdditionSecure(Utils::List<Shares::StandardShare> * a,Utils::List<Shares::StandardShare> *b,Utils::List<Shares::StandardShare> * c)\n    {\n        int l= a->getLength();\n        Utils::List<Shares::StandardShare> * sum= new Utils::List<Shares::StandardShare>(l);\n        Shares::StandardShare * bit =NULL;\n        for (int i=0; i<l-1; i++) {\n            bit= this->multiply(c->get(i+1), -2);\n            bit=this->addTo(bit, c->get(i));\n            bit=this->addTo(bit, b->get(i));\n            bit=this->addTo(bit, a->get(i));\n            sum->add(bit);\n        }\n        bit=this->sxor(c->get(l-1), b->get(l-1));\n        bit=this->xorTo(bit, a->get(l-1));\n        sum->add(bit);\n        return sum;\n    };\n    \n    //transforms bit numbers to decimal numbers\n    Shares::StandardShare * ShamirSharesEngine::btod(Utils::List<Shares::StandardShare> * bin, int size)\n    {\n        Shares::StandardShare * total = NULL;\n        if (size>0)\n        {\n            Shares::StandardShare * aux =NULL;\n            total= bin->get(0)->clone(); //It is equivalent to do bin[0]*2^0\n            for (int i=1; i<size; i++)\n            {\n                aux=this->multiply(bin->get(i),  conv<long>(power(conv<ZZ>(2), i)));\n                total= this->addTo(total, aux);\n                delete aux;\n            }\n        }\n        \n        return total;\n    };\n    \n    //generates a vector with a one signaling the most significative bit\n    Utils::List<Shares::StandardShare> *  ShamirSharesEngine::obtainMostSignificativeBit(Utils::List<Shares::StandardShare> * c)\n    {\n        Shares::StandardShare * destroy = NULL;\n        //dummy share of 1. It is a possibility to move it to the constants class.\n        Shares::StandardShare * dummy = Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), 1);\n        int l = c->getLength();//this->nBits_;\n        \n        Shares::StandardShare ** f= new Shares::StandardShare * [l];\n        Shares::StandardShare ** d= new Shares::StandardShare * [l];\n        \n        Utils::List<Shares::StandardShare> * result = new Utils::List<Shares::StandardShare> (l);\n        \n        for (int i=l-1; i>=0; i--)// it should start from the l-1 bit, that is represented by the second one, the first one is array positioning related\n        {\n            Shares::StandardShare * aux= this->multiply(c->get(i), -1);\n            aux=this->addTo(aux,dummy);\n            if (i <= l-1-1) //the same as in the for, the number one correspond to the l-1 bit that is represented by the second one, the first one is array positioning related\n                \n            {\n                //is the step 2 of the algorithm\n                f[i]=this->multiply(f[i+1], aux);\n                \n                //is the step 3 of the algorithm\n                destroy= aux;\n                aux=this->multiply(f[i], -1);\n                delete destroy;\n                d[i]=(this->add(f[i+1], aux));\n                \n            }\n            else\n            {\n                f[i]=(aux);\n                aux=this->multiply(f[i], -1);\n                d[i]=(this->add(dummy, aux));\n            }\n            delete aux;\n        }\n        //builds the array response\n        for (int i =0; i< l; i++)\n        {\n            \n            delete f[i];\n            result->add(d[i]);\n        }\n        \n        delete dummy;\n        delete  []f;\n        delete  []d;\n        \n        return result;\n    };\n    \n    //calculates the complement 2 of a shared value given the bitsize desired for its transformation\n    Utils::List<Shares::StandardShare> *  ShamirSharesEngine::obtainComplementTwoInShares(long value, int l=0)\n    {\n        if (l==0)\n        {\n            l=this->nBits_;\n        }\n        //int p= this->nBits_;\n        int player=this->player_->getPlayer();\n        int * iValues= NULL;\n        iValues=Utilities::MathUtil::obtainComplementTwo(value, l);\n        return Utilities::ShareUtil::wrapStandardShareList(player,  iValues, l);\n    };\n    \n    //private comparison operations\n    \n    //Secure Equality and Greater-Than Tests with Sublinear Online Complexity.\n    Shares::StandardShare * ShamirSharesEngine::greaterThanlBitsShares(Shares::StandardShare * a, Shares::StandardShare * b, int ap, int bp,int l)\n    {\n        Shares::StandardShare * destroy = NULL;\n        //TODO:Check what has to be done on mod 2^l and why\n        //--stopping condition of the recurssion\n        if (l==1)\n        {\n            //1-[y]+[x][y]\n            Shares::StandardShare * response= NULL;\n            Shares::StandardShare * aux= this->substract((long)1, b);\n            response =this->addTo(this->multiply(a, b),aux);\n            delete aux;\n            return response;\n            \n        }\n        //--initialization of variables\n        int k =this->k_;\n        \n        //operation constantly repeated around the formulation\n        int ld2= l/2; //l/2\n        ZZ_p lp2= power(conv<ZZ_p>(2), l); //2^(l)\n        ZZ_p ld2p2= power(conv<ZZ_p>(2), ld2);//2^(l/2)\n        \n        //--[z]=2^l +x-y\n        //puts in bit 2^l the operation x>= a given value\n        Shares::StandardShare * z = this->substract(a, b);\n        /*\n         std::cout<<\"l:\"<< l<<\" a: \"<< this->reconstructShare(a)<<\"\\n\";\n         std::cout<<\"l:\"<< l<<\" b: \"<< this->reconstructShare(b)<<\"\\n\";\n         std::cout<<\"l:\"<< l<<\" bz: \"<< this->reconstructShare(z)<<\"\\n\";\n         */\n        z=this->addTo(z, conv<long>(lp2));\n        \n        //--Preprocessing Random Number\n        \n        //Formulation to get a number of exactly 2^l+k random number with randombit generation for the l first bits.\n        //R^(l) and r|_ - r-|\n        Shares::StandardShare *r=NULL;\n        Utils::List<Shares::StandardShare> * rBit= NULL;\n        if( this->generateDagmardBitwiseRandomNumber(&(r),&(rBit),l)!= 1)\n        {\n            //TODO:implement error classes\n            return NULL;\n        }\n        Shares::StandardShare * rTop=Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), 0);\n        Shares::StandardShare  *rSub=Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), 0);\n        //we use this form and not the provided methods by the framework because this form simplifies a for loop\n        \n        for(int i=0; i<ld2;i++)\n        {\n            ZZ_p twoCoeff= conv<ZZ_p>(2);\n            twoCoeff=power(twoCoeff,i);\n            \n            destroy =this->multiply(rBit->get(i), conv<long> (twoCoeff));\n            rSub=this-> addTo(rSub,destroy) ;\n            delete destroy;\n            \n            destroy =this->multiply(rBit->get(i+ld2), conv<long> (twoCoeff));\n            rTop=this-> addTo(rTop,destroy);\n            delete destroy;\n            \n            \n        }\n        \n        //Construction of R in such a way  the l less significative bits are equal to the r_l bits just generateed\n        //Additionally R has to be a number of as top 2^l*k +l(n).\n        //The only use of k is to give statistical certainty\n        //r<z^k\n        ZZ_p randK= conv<ZZ_p>((rand()% conv<long>(power(conv<ZZ_p>(2),k)-2))+1);//TODO: replace for shoup rand\n        \n        Utils::List<Shares::StandardShare> *randVals= this->shareValue(conv<long>(randK));\n        \n        \n        Shares::StandardShare * R=this->multiplyTo(this->add(randVals->get(ap-1),randVals->get(bp-1)),conv<long>(power(conv<ZZ_p>(2),l)));// (2^l)*(r_a +r_b) <-> (2^l)*((2^(k))*2)\n        \n        //the multiplication by 2^l is like when you calculate the power of 10 to n value and just add the number of 0 to the right of the number\n        //in there this is used to give back the ducenes (series of 2) that the first 2 bits have lost and then add the 2 less significative bits\n        /*\n         std::cout<<\"l:\"<< l<<\" Ra: \"<< this->reconstructShare(randVals->get(ap-1))<<\"\\n\";\n         std::cout<<\"l:\"<< l<<\" Rb: \"<< this->reconstructShare(randVals->get(bp-1))<<\"\\n\";\n         std::cout<<\"l:\"<< l<<\" Rp: \"<< this->reconstructShare(R)<<\"\\n\";\n         */\n        R= this->addTo(R,r);// R_ + (2^l/2)*[r-|] +[r_|]--> (r)or this->add(this->multiply(rTop, conv<long>(power(conv<ZZ_p>(2),ld2))), rSub)\n        \n        //--online processing\n        //randomization of  m\n        Shares::StandardShare * mShare = this->add(z ,R);\n        \n        //open m and  put it inside the P field\n        ZZ_p m = (conv<ZZ_p>(this->reconstructShare(mShare)));// reconstruct Share should return the value in the field but\n        /*                                                       // for better reading we apply a conv\n         //batch of debuggin\n         std::cout<<\"l:\"<< l<<\" m: \"<< m<<\"\\n\";\n         std::cout<<\"l:\"<< l<<\" r: \"<< this->reconstructShare(r)<<\"\\n\";\n         std::cout<<\"l:\"<< l<<\" z: \"<< this->reconstructShare(z)<<\"\\n\";\n         std::cout<<\"l:\"<< l<<\" rK: \"<< randK<<\"\\n\";\n         \n         std::cout<<\"l:\"<< l<<\" rTop: \"<< this->reconstructShare(rTop)<<\"\\n\";\n         std::cout<<\"l:\"<< l<<\" rSub: \"<< this->reconstructShare(rSub)<<\"\\n\";\n         std::cout<<\"l:\"<< l<<\" R: \"<< this->reconstructShare(R)<<\"\\n\"; //\n         */\n        //separate  the top and the bottom bits on m\n        //this operations are performed to be able to calculate z mod 2^l\n        long lm =conv<long>(m);\n        long mSub = lm% conv<long>(ld2p2);\n        long mTop = (lm/conv<long>(ld2p2)) %conv<long>(ld2p2);// the division has the same effect as we were dividing  a decimal number\n        // by the number of decimal you want to move to the right\n        //std::cout<<\"l:\"<< l<<\" mSub: \"<< mSub<<\"\\n\";\n        //std::cout<<\"l:\"<< l<<\" mTop: \"<< mTop<<\"\\n\";\n        \n        //obtains the equality from the top bits\n        //TODO: implement an scalar  equality operation - look for possible improvements\n        //TODO: manage the same naming standard example r and mShare.. should be rShare\n        Shares::StandardShare * mTopShare = Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), mTop);\n        Shares::StandardShare * e = this->equalToToftShares(mTopShare, rTop, l/2);// this variable is called b in Tofts paper -- it uses half of bits\n        Shares::StandardShare *  mMin = this->addTo(this->multiply(e, conv<long>(conv<ZZ_p>(mSub)-conv<ZZ_p>(mTop))), mTop);\n        \n        Shares::StandardShare *  rMin = this->addTo(this->multiplyTo(this->substract(rSub, rTop),e), rTop);\n        //recurssion\n        Shares::StandardShare * smr=this->greaterThanlBitsShares(mMin, rMin, ap,bp,ld2);\n        Shares::StandardShare * f = this->substract(1,smr);\n        ZZ_p mMod=conv<ZZ_p>(lm% conv<long>(lp2));\n        /*\n         //info ethiquetes ->lTODO:ook for loggers in C++ and replace\n         std::cout<<\"l:\"<< l<<\"mMin: \"<< this->reconstructShare(mMin)<<\"\\n\"; //\n         std::cout<<\"l:\"<< l<<\"rMin: \"<< this->reconstructShare(rMin)<<\"\\n\"; //\n         std::cout<<\"l:\"<< l<<\"e: \"<< this->reconstructShare(e)<<\"\\n\"; //\n         std::cout<<\"l:\"<< l<<\"f: \"<< this->reconstructShare(f)<<\"\\n\"; //\n         std::cout<<\"l:\"<< l<<\"m: \"<< lm<<\"\\n\"; //\n         std::cout<<\"l:\"<< l<<\"m mod 2^l: \"<< mMod<<\"\\n\"; //\n         */\n        Shares::StandardShare *  zMod2l = this->substract(conv<long>(mMod), r);\n        Shares::StandardShare * f2l=this->multiply(f, conv<long>(lp2));\n        zMod2l= this->addTo(zMod2l,f2l);\n        //std::cout<<\"l:\"<< l<<\"zMod2l: \"<< this->reconstructShare( zMod2l)<<\"\\n\"; //\n        //return zMod2l;\n        ZZ_p zp=conv<ZZ_p>(power(conv<ZZ>(conv<ZZ_p>(1)/conv<ZZ_p>(2)),l));\n        //std::cout<<\"l:\"<< l<<\"zp: \"<< zp<<\"\\n\"; //\n        Shares::StandardShare * rcontent=this->multiplyTo(this->substract(z, zMod2l),conv<long>(zp));//conv<long>(-1*lp2)\n        //std::cout<<\"l:\"<< l<<\"rcontent \"<< rcontent->getValue()<<\"\\n\";\n        // std::cout<<\"l:\"<< l<<\"rcontent \"<< this->reconstructShare( rcontent)<<\"\\n\";\n        \n        Utilities::ShareUtil::destroyList(rBit);\n        delete rSub;\n        delete rTop;\n        Utilities::ShareUtil::destroyList(randVals);\n        delete R;\n        delete z;\n        delete mShare;\n        delete mTopShare;\n        delete e;\n        delete mMin;\n        delete rMin;\n        delete smr;\n        delete r;\n        delete f;\n        delete f2l;\n        delete zMod2l;\n        return rcontent;\n        \n    };\n    \n    //private transmission related methods\n    \n    //interpolates shared values\n    long ShamirSharesEngine::interpolateValues(Utils::List<Shares::StandardShare> * shares)\n    {\n        int players = this->players_->getLength();\n        long * values= new long[players];\n        for (int i=0; i<players; i++)\n        {\n            values[i]= shares->get(i)->getValue();\n        }\n        long response =Utilities::MathUtil::lagrangianInterpolation(values, players);\n        \n        delete [] values;\n        return response;\n        \n    };\n    \n    //Random number generation methods\n    \n    //generates a random number in a naive fashion.\n    Shares::StandardShare * ShamirSharesEngine::generateShareRandomNumber()\n    {\n        return this->generateShareRandomNumber(this->p_);\n    };\n    \n    //generates a random number in a naive fashion using custom thereshold\n    Shares::StandardShare * ShamirSharesEngine::generateShareRandomNumber(long threshold)\n    {\n        int players = this->players_->getLength();\n        int localRandom= (rand()% (threshold-2))+1;\n        Utils::List<Shares::StandardShare> *  numberShares= this->shareValue(localRandom);\n        Shares::StandardShare * number=NULL;\n        if(players>0)\n        {\n            number= numberShares->get(0)->clone();\n        }\n        for (int i=1; i<players; i++)\n        {\n            number= this->addTo(number, numberShares->get(i));\n        }\n        \n        Utilities::ShareUtil::destroyList(numberShares);\n        \n        return number;\n    };\n    \n    //Uses Damgard technique to generate random bit\n    Shares::StandardShare * ShamirSharesEngine::generateDagmardRandomBit()\n    {\n        ZZ_p aSquareValue;\n        Shares::StandardShare * a=NULL;\n        Shares::StandardShare * aSquare=NULL;\n        do {\n            delete a;\n            delete aSquare;\n            //obtain a random value\n            a= this->generateShareRandomNumber();\n            \n            //square the random value\n            aSquare= this->multiply(a, a);\n            \n            //Open the shares\n            aSquareValue= conv<ZZ_p>(this->reconstructShare(aSquare));\n            \n        } while (aSquareValue==0);\n        \n        //get the square root of the value\n        ZZ_p b= conv<ZZ_p>(SqrRootMod(conv<ZZ>(aSquareValue), conv<ZZ>(this->p_)));\n        \n        //get the inverse of the value\n        b= conv<ZZ_p>(1)/b;//power(b,conv<ZZ>(-1));//\n        \n        //multiplication by the random number\n        Shares::StandardShare * c= this->multiply(a,  conv<long>(b));\n        \n        //generates the bit excecuting (c+1)/2\n        //obtain 1/2 or 2^-1\n        ZZ_p oneHalf=power(conv<ZZ_p>(2),conv<ZZ>(-1));\n        \n        //execute final mathematical operations to convert -1;1 to 0;1\n        Shares::StandardShare * d=this->add(c, 1);\n        d=this->multiplyTo(d, conv<long>(oneHalf));\n        \n        delete a;\n        delete aSquare;\n        delete c;\n        \n        return d;\n    };\n    \n    //generates random generated number using Damgard tehcniques.\n    int ShamirSharesEngine::generateDagmardBitwiseRandomNumber(Shares::StandardShare ** number, Utils::List<Shares::StandardShare> ** bitwiseNumber, int l)\n    {\n        \n        long p= this->p_;\n        long openC=0;\n        Utils::List<Shares::StandardShare> * rBitShares= NULL;\n        \n        do\n        {\n            Utilities::ShareUtil::destroyList(rBitShares);\n            rBitShares= new Utils::List<Shares::StandardShare>(l);\n            for(int i=0; i< l;i++)\n            {\n\n                rBitShares->add(this->generateDagmardRandomBit());\n\n            };\n            \n            if(this->nBits_==l)\n            {\n                Shares::StandardShare * c = this->bitwiseLessThanSecureScalar(rBitShares, p);\n                openC= this->reconstructShare(c);\n                delete c;\n            }\n            else\n            {\n                openC=1;\n            }\n            \n            \n        }while (openC==0);\n        \n        Shares::StandardShare * r= obtainDecimalShareFromBits(rBitShares);\n        \n        *number=r;\n        *bitwiseNumber=rBitShares;\n        \n        return 1;\n    };\n    \n    // generate random nuber and its bit decomposition using a naive approach\n    int ShamirSharesEngine::generateBitwiseRandomNumber(Shares::StandardShare ** number, Utils::List<Shares::StandardShare> ** bitwiseNumber, int l)\n    {\n        int players = this->players_->getLength();\n        long p= this->p_;\n        long localRandom= (rand()% p-1)+0;\n        \n        Utils::List<Shares::StandardShare> *  numberShares= this->shareValue(localRandom);\n        Utils::List<Utils::List<Shares::StandardShare> >* bitShares= this->shareValueBitwise(localRandom,l);\n        \n        if(players>0)\n        {\n            *number= numberShares->get(0);\n            *bitwiseNumber=bitShares->get(0)->clone();\n        }\n        Utils::List<Shares::StandardShare> * aux=NULL;\n        for (int i=1; i<players; i++)\n        {\n            *number= this->addTo(*number, numberShares->get(i));\n            aux = *bitwiseNumber;\n            *bitwiseNumber=this->bitwiseAdditionShares(*bitwiseNumber, bitShares->get(i), Utilities::Constants::SHAREMIND_CARRY);\n            \n            Utilities::ShareUtil::destroyList(aux);\n            Utilities::ShareUtil::destroyList(bitShares->get(i));\n        }\n        \n        Utilities::ShareUtil::destroyList(numberShares);\n        delete bitShares;\n        \n        return 1;\n    };\n    \n    //Binary operation Methods\n    \n    //otains the decimal share form of a vector of shared bits\n    Shares::StandardShare * ShamirSharesEngine::obtainDecimalShareFromBits(Utils::List<Shares::StandardShare> * a)\n    {\n        return this->btod(a, a->getLength());\n    };\n    \n    //calculates the corresponding carry list of shared bits\n    Utils::List<Shares::StandardShare> * ShamirSharesEngine::carrySharemindShares(Utils::List<Shares::StandardShare> * a, Utils::List<Shares::StandardShare> * b)\n    {\n        int l=a->getLength();\n        Utils::List<Shares::StandardShare> * c= new Utils::List<Shares::StandardShare>(l);\n        c->add(Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), 0));// it should be always a number modulus the correct  value\n        //executes the operation for each pair of bits\n        for (int i=0; i<l-1; i++)\n        {\n            c->add(this->carrySharemindSecure(a->get(i), b->get(i),c->get(i)));\n        }\n        return c;\n        \n    };\n    \n    //performs a bit addition using the method selected\n    Utils::List<Shares::StandardShare> * ShamirSharesEngine::bitwiseAdditionShares(Utils::List<Shares::StandardShare> * a,Utils::List<Shares::StandardShare> * b,int type)\n    {\n        Utils::List<Shares::StandardShare> * carries= NULL;\n        switch (type)\n        {\n            case 1: //Utilities::Constants::SHAREMIND_CARRY\n                carries= this->carrySharemindShares(a, b);\n                break;\n                \n            default:\n                break;\n        }\n        return this->bitwiseAdditionSecure(a, b, carries);\n        \n    };\n    \n    //decompose a shared value into its bitshares - uses deafult bitsize for that matter, build a method that parametrize this option.\n    Utils::List<Shares::StandardShare> *  ShamirSharesEngine::obtainBitsFromShare(Shares::StandardShare * share)\n    {\n        int l= this->nBits_;\n        Shares::StandardShare * a= share;\n        //p stands for pointer\n        Utils::List<Shares::StandardShare> ** pRanBin =new Utils::List<Shares::StandardShare> *;\n        Shares::StandardShare ** pRan= new Shares::StandardShare *;\n        \n        //fills the pointers of the random number\n        if (this->generateBitwiseRandomNumber(pRan, pRanBin, l)!=1)\n        {\n            return NULL;\n        }\n        \n        Shares::StandardShare * ran= *(pRan);\n        Utils::List<Shares::StandardShare> * ranBin= *(pRanBin);\n        Shares::StandardShare * nA= this->multiply(a, -1);\n        Shares::StandardShare * c= this->add(ran, nA);\n        \n        //Open Share c\n        long cValue= this->reconstructShare(c);\n        \n        Utils::List<Shares::StandardShare> * complementTwoCValue= this->obtainComplementTwoInShares(cValue, l);\n        \n        \n        Utils::List<Shares::StandardShare> * d= this->bitwiseAdditionShares(ranBin, complementTwoCValue, Utilities::Constants::SHAREMIND_CARRY);\n        //TODO: Complete the algorithm with the validation needed when it works on a given field\n        \n        delete a;\n        Utilities::ShareUtil::destroyList( *pRanBin);\n        delete *pRan;\n        delete ran;\n        delete ranBin;\n        delete nA;\n        delete c;\n        Utilities::ShareUtil::destroyList(complementTwoCValue);\n        \n        return d;\n    };\n    \n    // returns the result of a>b\n    Shares::StandardShare * ShamirSharesEngine::bitwiseGreaterThanSecure(Utils::List<Shares::StandardShare> * a,Utils::List<Shares::StandardShare> * b)\n    {\n        int l= a->getLength();//this->nBits_;\n        int player=this->player_->getPlayer();\n        Utils::List<Shares::StandardShare> * c= new Utils::List<Shares::StandardShare> (l);\n        Utils::List<Shares::StandardShare> * d=NULL;\n        Utils::List<Shares::StandardShare> * e= new Utils::List<Shares::StandardShare> (l);\n        Shares::StandardShare * result= Utilities::ShareUtil::wrapStandardShare(player, 0);\n        //parallelism, this could be a parallel task for instance, to try to accelerate the performance\n        for (int i=0; i<l; i++)\n        {\n            c->add(this->sxor(a->get(i), b->get(i)));\n        }\n        d=this->obtainMostSignificativeBit(c);\n        for (int i=0; i<l; i++)\n        {\n            e->add(this->multiply(a->get(i), d->get(i)));\n        }\n        for (int i=0; i<l; i++)\n        {\n            result= this->addTo(result, e->get(i));\n        }\n        Utilities::ShareUtil::destroyList(c);\n        Utilities::ShareUtil::destroyList(d);\n        Utilities::ShareUtil::destroyList(e);\n        return result;\n    };\n    \n    //if a<b returns 1 else (a>=b) returns 0\n    Shares::StandardShare * ShamirSharesEngine::bitwiseLessThanSecureScalar(Utils::List<Shares::StandardShare> * a,long b)\n    {\n        int bits= a->getLength();\n        int player=this->player_->getPlayer();\n        Utils::List<Shares::StandardShare> * c= new Utils::List<Shares::StandardShare> (bits);\n        Utils::List<Shares::StandardShare> * d=NULL;\n        Utils::List<Shares::StandardShare> * e= new Utils::List<Shares::StandardShare> (bits);\n        Shares::StandardShare * result= Utilities::ShareUtil::wrapStandardShare(player, 0);\n        int* bBits= Utilities::MathUtil::obtainBits(b, bits);\n        //parallelism, this could be a parallel task for instance, to try to accelerate the performance\n        for (int i=0; i<bits; i++)\n        {\n            c->add(this->sxor(a->get(i), bBits[i]));\n        }\n        \n        d=this->obtainMostSignificativeBit(c);\n        \n        for (int i=0; i<bits; i++)\n        {\n            e->add(this->multiply( d->get(i),bBits[i]));\n        }\n        for (int i=0; i<bits; i++)\n        {\n            result= this->addTo(result, e->get(i));\n        }\n        \n        Utilities::ShareUtil::destroyList(c);\n        Utilities::ShareUtil::destroyList(d);\n        Utilities::ShareUtil::destroyList(e);\n        delete [] bBits;\n        \n        return result;\n    };\n    \n    //if a== 0 returns 1 else (a>=b) returns 0\n    Shares::StandardShare * ShamirSharesEngine::zeroTestXorShares(Shares::StandardShare * a)\n    {\n        int l= this->l_;\n        int player=this->player_->getPlayer();\n        Utils::List<Shares::StandardShare> * d =NULL;\n        Utils::List<Shares::StandardShare> * e= new Utils::List<Shares::StandardShare> (l);\n\n        Shares::StandardShare * R= this->generateShareRandomNumber(conv<long>(power(conv<ZZ_p>(2), this->k_-1 )));\n        Shares::StandardShare *r=NULL;\n        Utils::List<Shares::StandardShare> * rBit= NULL;\n        if( this->generateDagmardBitwiseRandomNumber(&(r),&(rBit),l)!= 1)\n        {\n            //TODO:implement error classes\n            return NULL;\n        }\n        //std::cout << \"Operation after bit generation: \"<<Buffers::EngineBuffers::operationCounter_<<\"\\n\";\n        \n        Shares::StandardShare * c = this->add(a, conv<long>(power(conv<ZZ_p>(2),l-1)));\n        Shares::StandardShare * aux = this->multiply(R,conv<long>(power(conv<ZZ_p>(2),l)));\n        c= this->addTo(c,aux);\n        c= this->addTo(c,r);\n        long o_c= this->reconstructShare(c);\n        o_c= o_c %conv<long>(power(conv<ZZ_p>(2),l));\n        delete aux;\n        \n        int* bBits= Utilities::MathUtil::obtainBits(o_c, l);\n        //parallelism, this could be a parallel task for instance, to try to accelerate the performance\n        for (int i=0; i<l; i++)\n        {\n            e->add(this->sxor(rBit->get(i), bBits[i]));\n        }\n        d=this->obtainMostSignificativeBit(e);\n        Shares::StandardShare * equal = Utilities::ShareUtil::wrapStandardShare(player, 0);\n        for (int i=0; i<l; i++)\n        {\n            equal =this->addTo(equal,d->get(i));\n\n        }\n        equal = this->substractTo(1, equal);\n\n        delete r;\n        delete R;\n        delete c;\n        Utilities::ShareUtil::destroyList(rBit);\n        Utilities::ShareUtil::destroyList(d);\n        Utilities::ShareUtil::destroyList(e);\n        delete [] bBits;\n        \n        return this->substractTo(1,equal);\n    };\n    \n    \n    Shares::StandardShare * ShamirSharesEngine::bitwiseLessThanSecureScalar(long b, Utils::List<Shares::StandardShare> * a)\n    {\n        Shares::StandardShare * c= this->bitwiseLessThanEqualSecureScalar(a, b);\n        c= this->substractTo(1, c);\n        return c;\n    };\n\n    //if a<b returns 1 else (a>=b) returns 0\n    Shares::StandardShare * ShamirSharesEngine::bitwiseLessThanEqualSecureScalar(Utils::List<Shares::StandardShare> * a,long b)\n    {\n        int bits= a->getLength();\n        int player=this->player_->getPlayer();\n        Utils::List<Shares::StandardShare> * c= new Utils::List<Shares::StandardShare> (bits);\n        Utils::List<Shares::StandardShare> * d=NULL;\n        Utils::List<Shares::StandardShare> * e= new Utils::List<Shares::StandardShare> (bits);\n        int* bBits= Utilities::MathUtil::obtainBits(b, bits);\n        //parallelism, this could be a parallel task for instance, to try to accelerate the performance\n        for (int i=0; i<bits; i++)\n        {\n            c->add(this->sxor(a->get(i), bBits[i]));\n        }\n        \n        d=this->obtainMostSignificativeBit(c);\n        \n        for (int i=0; i<bits; i++)\n        {\n            e->add(this->multiply( d->get(i),bBits[i]));\n        }\n        Shares::StandardShare * equal= Utilities::ShareUtil::wrapStandardShare(player, 0);\n        Shares::StandardShare * result = Utilities::ShareUtil::wrapStandardShare(player, 0);\n        for (int i=0; i<bits; i++)\n        {\n            equal =this->addTo(equal,d->get(i));\n            result= this->addTo(result, e->get(i));\n        }\n        equal = this->substractTo(1, equal);\n        Utilities::ShareUtil::destroyList(c);\n        Utilities::ShareUtil::destroyList(d);\n        Utilities::ShareUtil::destroyList(e);\n        delete [] bBits;\n        Shares::StandardShare * aux = this->add(equal,result);\n        Shares::StandardShare * aux_m = this->multiply(equal, result);\n        delete result;\n        aux= this->substractTo(aux, aux_m);\n        result = aux;\n        \n        delete  equal;\n        delete aux_m;\n\n        return result;\n    };\n\n    \n    //scalar public operations\n    //*a+b where b is scalar\n    Shares::StandardShare * ShamirSharesEngine::addScalar(Shares::StandardShare * a, long b)\n    {\n        return Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(),this->addSecure( a->getValue(),b));\n        \n    };\n    \n    //a*b where b is scalar\n    Shares::StandardShare * ShamirSharesEngine::multiplyScalar(Shares::StandardShare * a, long b)\n    {\n        \n        return Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(),multiplySecure(a->getValue(),b));\n    };\n    \n    //*a xor b where b is scalar\n    Shares::StandardShare * ShamirSharesEngine::xorScalar(Shares::StandardShare * a, long b)\n    {\n        Shares::StandardShare * resultXor= this->multiply(a,b);\n        resultXor= this->multiplyTo(resultXor, -2);\n        resultXor=this->addTo(resultXor, a);\n        resultXor=this->addTo(resultXor, b);\n        return resultXor;\n    };\n    \n    //a-b where b is scalar\n    Shares::StandardShare * ShamirSharesEngine::substractScalar(Shares::StandardShare * a, long b)\n    {\n        return Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), this->substractSecure(a->getValue(),b));\n    };\n    \n    //a-b where a is scalar\n    Shares::StandardShare * ShamirSharesEngine::substractScalar(long b, Shares::StandardShare * a)\n    {\n        return Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), this->substractSecure(b,a->getValue()));\n    };\n    \n    //Basic Shares operation Methods\n    \n    //a+b\n    Shares::StandardShare * ShamirSharesEngine::addShares(Shares::StandardShare *a,Shares::StandardShare *b)\n    {\n        //Native implementation eliminating the conversion process should accelerate it. Loose of generality thinking on reliability.\n        return Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), this->addSecure(a->getValue(),b->getValue()));\n    };\n    \n    //returns a-b\n    Shares::StandardShare * ShamirSharesEngine::substractShares(Shares::StandardShare *a,Shares::StandardShare *b)\n    {\n        return Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), this->substractSecure(a->getValue(),b->getValue()));\n    };\n    \n    //a*b\n    Shares::StandardShare * ShamirSharesEngine::multiplyShares(Shares::StandardShare * a, Shares::StandardShare * b)\n    {\n        Utils::List<Shares::StandardShare>  *list;\n        Shares::StandardShare *  product= Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), 0);\n        \n        long simpleProduct=this->multiplySecure(a->getValue(),b->getValue());\n        list= this->shareValue(simpleProduct);\n        this->generator_->multiplicationRegeneration(product, players_->getLength(), list);\n        Utilities::ShareUtil::destroyList(list);\n        return product;\n        \n    };\n    \n    //a^(-1)\n    Shares::StandardShare * ShamirSharesEngine::invertShare(Shares::StandardShare *a)\n    {\n        //declaration of variables\n        Shares::StandardShare * r=NULL;\n        Shares::StandardShare * mShare=NULL;\n        ZZ_p m;\n        long lm;\n        //loop to assure m is invertible i.e.(different from 0)\n        do\n        {\n            delete r;\n            delete mShare;\n            //get a random number and multiplies it for a, and then opens the result\n            r= this->generateShareRandomNumber();\n            mShare=this->multiply(a, r);\n            m =conv<ZZ_p>( this->reconstructShare(mShare));\n            \n        }while (m==0);\n        //inverse of m calculation\n        m= 1/m;\n        lm=conv<long>(m);\n        //simplification of the random factor, to get a clean and shared 1/a\n        Shares::StandardShare * inverse= this->multiply(r, lm);\n        \n        delete r;\n        delete mShare;\n        \n        return inverse;\n    };\n    \n    //\n    Shares::StandardShare * ShamirSharesEngine::mod2m(Shares::StandardShare * a, int k, int m)\n    {\n        //random bits of size l\n        Shares::StandardShare * R= this->generateShareRandomNumber(conv<long>(power(conv<ZZ_p>(2),k +this->k_-1 -m)));\n        Shares::StandardShare *r=NULL;\n        Utils::List<Shares::StandardShare> * rBit= NULL;\n        if( this->generateDagmardBitwiseRandomNumber(&(r),&(rBit),m)!= 1)\n        {\n            //TODO:implement error classes\n            return NULL;\n        }\n        \n        Shares::StandardShare * c = this->add(a, conv<long>(power(conv<ZZ_p>(2),k-1)));\n        Shares::StandardShare * aux = this->multiply(R,conv<long>(power(conv<ZZ_p>(2),m)));\n        c= this->addTo(c,aux);\n        c= this->addTo(c,r);\n        long o_c= this->reconstructShare(c);\n        delete aux;\n        o_c= o_c%conv<long>(power(conv<ZZ_p>(2),m));\n\n        Shares::StandardShare * u=this->bitwiseLessThanSecureScalar(o_c,rBit);// r<=c :: c<r\n\n        Shares::StandardShare * result =this->substract(o_c, r);\n        aux= this->multiply(u, conv<long>(power(conv<ZZ_p>(2),m)));\n        result = this->addTo(result, aux);\n        \n        delete R;\n        Utilities::ShareUtil::destroyList(rBit);\n        delete r;\n        delete u;\n        delete aux;\n        delete c;\n        return result;\n\n    };\n    \n    //a^e the list contains only non zero powers. Power of 0 that is equal  to 1 is excluded from the list.\n    Utils::List<Shares::StandardShare> * ShamirSharesEngine::powerShare(Shares::StandardShare * share, int e)\n    {\n        Utils::List<Shares::StandardShare> * list = new Utils::List<Shares::StandardShare>(e);\n        \n        //create elements for the fanInMultiplications\n        for (int i=0; i<e; i++)\n        {\n            list->add(share);\n        }\n        Utils::List<Shares::StandardShare> * result =this->fanInMultiplicationShares(list);\n        \n        delete list; //is delete list and not destroyList because we do not want to delete the items inside the list,\n        //(references to the same share) but  we want to eliminate its container\n        \n        return result;\n    };\n    \n    //fan in operations\n    Utils::List<Shares::StandardShare> * ShamirSharesEngine::fanInMultiplicationShares(Utils::List<Shares::StandardShare> * shares)\n    {\n        //this method works only with shared values and perform only secure operations.\n        //which means if you know in advance the first element on this multiplication is going to be a 1 you could not use it.\n        \n        int size=shares->getLength();\n        Utils::List<Shares::StandardShare> * list = new Utils::List<Shares::StandardShare>(size);\n        list->add(shares->get(0)->clone());\n        for(int i=1; i<size;i++)\n        {\n            list->add(this->multiply(list->get(i-1), shares->get(i)));\n            \n        }\n        return list;\n    };\n    \n    //secure methods: polymorphism\n    \n    //a+b\n    Shares::StandardShare * ShamirSharesEngine::add(Shares::StandardShare *a,Shares::StandardShare *b)\n    {\n        //any normalization here\n        return this->addShares(a, b);\n    };\n    \n    //a+b\n    Shares::StandardShare * ShamirSharesEngine::add(Shares::StandardShare * a, long b)\n    {\n        return this->addScalar(a, b);\n    };\n    \n    //a+=b\n    Shares::StandardShare * ShamirSharesEngine::addTo(Shares::StandardShare *a,Shares::StandardShare *b)\n    {\n        //any normalization here\n        Shares::StandardShare *result =this->add(a, b);\n        delete a;\n        return result;\n    };\n    \n    //a+=b\n    Shares::StandardShare * ShamirSharesEngine::addTo(Shares::StandardShare *a,long b)\n    {\n        //any normalization here\n        Shares::StandardShare *result =this->add(a, b);\n        delete a;\n        return result;\n    };\n    \n    //a-=b\n    Shares::StandardShare * ShamirSharesEngine::substractTo(Shares::StandardShare *a,Shares::StandardShare *b)\n    {\n        //any normalization here\n        Shares::StandardShare *result =this->substract(a, b);\n        delete a;\n        return result;\n    };\n    \n    //a-=b\n    Shares::StandardShare * ShamirSharesEngine::substractTo(Shares::StandardShare *a, long b)\n    {\n        //any normalization here\n        Shares::StandardShare *result =this->substract(a, b);\n        delete a;\n        return result;\n    };\n    \n    //a-=b\n    Shares::StandardShare * ShamirSharesEngine::substractTo( long b, Shares::StandardShare *a )\n    {\n        //any normalization here\n        Shares::StandardShare *result =this->substract(b,a);\n        delete a;\n        return result;\n    };\n    \n    //a-b\n    Shares::StandardShare * ShamirSharesEngine::substract(Shares::StandardShare *a,Shares::StandardShare *b)\n    {\n        //any normalization here\n        return this->substractShares(a, b);\n    };\n    \n    //a-b\n    Shares::StandardShare * ShamirSharesEngine::substract(Shares::StandardShare * a, long b)\n    {\n        //any normalization here\n        return this->substractScalar(a, b);\n        \n    };\n    \n    //a-b\n    Shares::StandardShare * ShamirSharesEngine::substract( long b, Shares::StandardShare * a)\n    {\n        //any normalization here\n        return this->substractScalar(b, a);\n        \n    };\n    \n    //a*=b\n    Shares::StandardShare * ShamirSharesEngine::multiplyTo( Shares::StandardShare * a, Shares::StandardShare *b )\n    {\n        //any normalization here\n        Shares::StandardShare *result =this->multiply(a, b);\n        delete a;\n        return result;\n    };\n    \n    //a*=b\n    Shares::StandardShare * ShamirSharesEngine::multiplyTo( Shares::StandardShare * a, long b )\n    {\n        //any normalization here\n        Shares::StandardShare *result =this->multiply(a, b);\n        delete a;\n        return result;\n    };\n    \n    //a*b\n    Shares::StandardShare * ShamirSharesEngine::multiply(Shares::StandardShare *a,Shares::StandardShare *b)\n    {\n        //any normalization here\n        return this->multiplyShares(a, b);\n    };\n    \n    //a*b\n    Shares::StandardShare * ShamirSharesEngine::multiply(Shares::StandardShare * a, long b)\n    {\n        return this->multiplyScalar(a, b);\n    };\n    \n    //c= a xor b\n    Shares::StandardShare * ShamirSharesEngine::sxor( Shares::StandardShare * a, Shares::StandardShare *b )\n    {\n        //any normalization here\n        Shares::StandardShare *result =this->xorShares(a, b);\n        return result;\n    };\n    \n    //c=a xor b\n    Shares::StandardShare * ShamirSharesEngine::sxor( Shares::StandardShare * a, long b )\n    {\n        //any normalization here\n        Shares::StandardShare *result =this->xorScalar(a, b);\n        return result;\n    };\n    \n    //a xor=b\n    Shares::StandardShare * ShamirSharesEngine::xorTo( Shares::StandardShare * a, Shares::StandardShare *b )\n    {\n        //any normalization here\n        Shares::StandardShare *result =this->xorShares(a, b);\n        delete a;\n        return result;\n    };\n    \n    //a xor=b\n    Shares::StandardShare * ShamirSharesEngine::xorTo( Shares::StandardShare * a, bool b )\n    {\n        //any normalization here\n        Shares::StandardShare *result =this->xorScalar(a, b);\n        delete a;\n        return result;\n    };\n    \n    \n    //public applications\n    \n    //a xor b\n    Shares::StandardShare * ShamirSharesEngine::xorShares(Shares::StandardShare * a, Shares::StandardShare * b)\n    {\n        Shares::StandardShare * resultXor= this->multiply(a,b);\n        resultXor= this->multiplyTo(resultXor, -2);\n        resultXor=this->addTo(resultXor, a);\n        resultXor=this->addTo(resultXor, b);\n        return resultXor;\n        \n    };\n    \n    //a>b using bitwise decomposition -Damgar 2006 method\n    Shares::StandardShare * ShamirSharesEngine::greaterThanShares(Shares::StandardShare * a, Shares::StandardShare * b)\n    {\n       // if (a->getBits()==NULL)\n       // {\n       //     a->setBits(this->obtainBitsFromShare(a));\n       // }\n       // if(b->getBits()==NULL)\n        //{\n        //    b->setBits(this->obtainBitsFromShare(b));\n        //}\n        return NULL;\n        //return this->bitwiseGreaterThanSecure(a->getBits(), b->getBits());\n    };\n    \n    //a==0\n    Shares::StandardShare * ShamirSharesEngine::zeroTestShares(Shares::StandardShare * a,  int l)\n    {\n        /*\n         //this method follows Toft's implementation on:\n         //Secure Equality and Greater-Than Tests with Sublinear Online Complexity.\n         //It strictly follows and uses the methods the original paper suggests.\n         //Including all the Damgard[6] reference on Toft's paper for inverse random numbers\n         //and random generation numbers.\n         */\n        \n        Shares::StandardShare * rAdjustment = NULL;\n        int k = this->k_;\n        \n        if (l!= this->nBits_)\n        {\n            //r_a= r(2^k +ln(n))*2^l\n            rAdjustment=this->multiplyTo(this->generateShareRandomNumber(conv<long>(power(conv<ZZ_p>(2),k))), conv<long>(power(conv<ZZ_p>(2),l))); //once used destroys generated number\n        }\n        else\n        {\n            //r_a=0\n            rAdjustment= Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), 0);\n        }\n        //gets a random number with 2^l ceroes bits\n        //----preprocessing----\n        int l_m = l;\n        int player= this->player_->getPlayer();\n        \n        //generation r and its bit decomposition --using damgard bit decomposition and random number generation\n        \n        Utils::List<Shares::StandardShare> *rBits= NULL;\n        Shares::StandardShare * r = NULL;\n        \n        if(this->generateDagmardBitwiseRandomNumber(&(r), &(rBits), l)!=1)\n        {\n            return NULL;\n        }\n        \n        //generation of R and R inverse and it's potences using Damgard random number generation and fan in multiplication.\n        Shares::StandardShare * R= this->generateShareRandomNumber();\n        Shares::StandardShare * RInverse= this->invertShare(R);\n        Utils::List<Shares::StandardShare> *RPowers=this->powerShare(R, l_m);\n        \n        \n        // ----online phase----\n        //calculate m and opens it\n        Shares::StandardShare * mShare= this->addTo( this->add(a, r),rAdjustment); //once used the generated instance for addition it destroys it.\n        \n        ZZ_p m= conv<ZZ_p>( this->reconstructShare(mShare));\n        \n        int * mBits= Utilities::MathUtil::obtainBits(conv<long>(m), l_m);\n        //calulates H+1. Sums xor of r bits and m bits\n        // gets the sumatory of xor r vsm bits --Calculates Hamming distance H\n        Shares::StandardShare * H= Utilities::ShareUtil::wrapStandardShare(player, 0);\n        for (int i=0; i<l_m; i++)\n        {\n            Shares::StandardShare * lXor= this->sxor(rBits->get(i), mBits[i]);\n            H= this->addTo(H,lXor );\n            delete lXor;\n        }\n\n        //add one to hamming distance\n        Shares::StandardShare * HPlusOne= this->add(H, 1);\n        \n        //randomize H+1 with R^-1\n        Shares::StandardShare * m_hShare= this->multiply(RInverse, HPlusOne);\n        ZZ_p m_h = conv<ZZ_p>(this->reconstructShare(m_hShare));\n      \n      \n        //simplification of the random number  on the m and obtention of the m^i factors\n\n\n        ZZ_p auxm=conv<ZZ_p>(1);\n        Utils::List<Shares::StandardShare> *HPlusOnePowers= new Utils::List<Shares::StandardShare>(l_m+1);\n        \n\n        HPlusOnePowers->add(Utilities::ShareUtil::wrapStandardShare(player, 1));\n        for (int i=1; i<=l_m; i++) {\n            auxm=auxm*m_h;\n            HPlusOnePowers->add(this->multiply(RPowers->get(i-1), conv<long>(auxm)));\n            \n        }\n   \n        //lagrange interpolation of the funciont P(x) where P(1)=1 and P(x)= 0 for x!=1 and 0< x<=m+1\n        vec_ZZ_p alphas =  this->lAlphas_[l-1]; //VectorCopy(Utilities::MathUtil::multiplyLagrangePolynomials(1, l_m+1, 1),(l_m+1)+1); // this should be precalculated to accelerate the processing\n        Shares::StandardShare * eq= this->multiply(HPlusOnePowers->get(0), conv<long>(alphas[0]));// in this case the first term should always be one\n        for (int i=1; i<=l_m; i++)\n        {\n            Shares::StandardShare * destroy=this->multiply(HPlusOnePowers->get(i), conv<long>(alphas[i]));\n            eq= this->addTo(eq, destroy);\n            delete destroy;\n        }\n  \n        delete rAdjustment;\n        Utilities::ShareUtil::destroyList(rBits);\n        delete  r;\n        Utilities::ShareUtil::destroyList(RPowers);\n        delete R;\n        delete RInverse;\n        delete mShare;\n        delete  [] mBits;\n        delete H;\n        delete HPlusOne;\n        delete m_hShare;\n        Utilities::ShareUtil::destroyList(HPlusOnePowers);\n       // delete eq;\n        return eq;\n\n    };\n    \n    //returns a-b=0\n    Shares::StandardShare * ShamirSharesEngine::equalToToftShares(Shares::StandardShare * a, Shares::StandardShare * b, int l)\n    {\n        totalCom++;\n        //stopping condition\n        if (l==1)\n        {\n            Shares::StandardShare * rXor =this->sxor(a, b);\n            Shares::StandardShare * result=this->substract((long)1,rXor);\n            delete rXor;\n            return result;// x=1- a xor b if a =1, x=0 - a=0, x=1\n        }\n        else if (l==0)\n        {\n            l=this->nBits_;\n        }\n        \n        //instead of a secure operation we perform a mod addition on the bit size\n        //x= Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), conv<long>( AddMod(a->getValue(), x->getValue(), l)));\n        //x = Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), conv<long>(SubMod(SubMod(a->getValue(), b->getValue(),conv<long>(aux)),conv<long>(aux),conv<long>(aux))));\n        \n        //calculate the difference between a and b\n        Shares::StandardShare * x= this->substract(a, b);\n        //long aux= conv<long>(power(conv<ZZ>(2),l));\n        \n        //Shares::StandardShare * R = this->generateShareRandomNumber(); //the game of multiplying by the random and then\n        //Shares::StandardShare * invR= this->invertShare(R);            //doing the operation and multiplying by the inverse\n        //is not possible, given that x%2^l is not equvalent to ((r*x)%2^l)/r\n        //Shares::StandardShare * xo= x;\n        //x= multiply(R, x);\n        //ZZ_p xp =conv<ZZ_p>(this->reconstructShare(x)/ aux);        //the game of multiplying by the random and then\n        //x= this->multiply(invR, conv<long>(xp));                    //doing the operation and multiplying by the inverse\n        //x=this->substract(xo, x);                                   //is not possible, given that x%2^l is not equvalent to floor(((r*x)/2^l))/r\n        //std::cout<<\"l:\"<<l<<\"a: \"<< this->reconstructShare(a)<< \" b: \" << this->reconstructShare(b)<<\" xp: \"<< xp<< \" xo: \"<<this->reconstructShare(xo)<<\" x: \"<<this->reconstructShare(x)<<\" R: \"<< this->reconstructShare(R)<< \" RI: \"<< this->reconstructShare(invR)<<\"\\n\";\n        //check whether the difference is equal to 0\n        Shares::StandardShare * result=this->zeroTestShares(x,l);\n        \n        delete x;\n        \n        return result;\n        \n    };\n    \n    //encapsulates access to nBits_ fro comparison procedure\n    Shares::StandardShare * ShamirSharesEngine::equalToToftShares(Shares::StandardShare * a, Shares::StandardShare * b)\n    {\n        return this->equalToToftShares(a, b,this->nBits_);\n    };\n    \n    //returns a>=b -memory save method\n    Shares::StandardShare * ShamirSharesEngine::greaterEqualThanToftShares(Shares::StandardShare * a, Shares::StandardShare * b)\n    {\n        int pa=a->getPlayerId();\n        int pb= b->getPlayerId();\n        //in case of use of build function for shares the difference between the players has to be stated\n        if(pa==pb)\n        {\n            pa=1; //assumtion first player\n            pb=2; //assumption second player\n        }\n        Shares::StandardShare * response =NULL;\n        long p2l=conv<long>(power(conv<ZZ_p>(2), this->l_/2)-1);\n        if(this->signed_==true)\n        {\n            Shares::StandardShare *a_aux= this->add(a, p2l);\n            Shares::StandardShare *b_aux= this->add(b, p2l);\n            if (pb==0) {\n                std::cout<< \"problem out of the blue\";\n            }\n            response=this->greaterThanlBitsShares(a_aux, b_aux,pa,pb, this->l_);\n            delete a_aux;\n            delete b_aux;\n        }\n        else\n        {\n            response= this->greaterThanlBitsShares(a, b,pa,pb, this->l_);\n        }\n        //this method receives the players as parameters fiven that they are necessary to select the secret random numbers - this is to extriclty adhere to the algorithm\n        return response;\n    };\n    \n    \n    \n    //This is actually  Catrinas method for comparitions. Implementation Memory Secure\n    Shares::StandardShare * ShamirSharesEngine::lessThanZeroCatrinaModShares(Shares::StandardShare * a)\n    {\n        totalCom++;\n        Shares::StandardShare * c= a->clone();\n        long p2l2= conv<long>(power(conv<ZZ_p>(2),this->l_-1));\n        \n        long inv_p2l2= conv<long>(power(conv<ZZ_p>(p2l2),-1));\n\n        Shares::StandardShare * res = this->mod2m(c, this->l_, this->l_-1);\n        c= this->substractTo(c, res);\n        Shares::StandardShare * result = this->multiplyTo(this->multiplyTo(c, inv_p2l2),-1);\n        // is minus one because the division is being performed out of the field c is negative\n        \n        delete res;\n        \n        return result;\n    };\n\n    //ltz(a) :a<0\n    Shares::StandardShare * ShamirSharesEngine::lessThanCatrinaModShares(Shares::StandardShare * a, Shares::StandardShare * b)\n    {\n        Shares::StandardShare * c = this->substract(a, b);\n        Shares::StandardShare * result = this->lessThanZeroCatrinaModShares(c);\n        delete c;\n        return result;\n    };\n    \n    //ltz(-a) : a>0\n    Shares::StandardShare * ShamirSharesEngine::greaterThanCatrinaModShares(Shares::StandardShare * a, Shares::StandardShare * b)\n    {\n        Shares::StandardShare * c = this->substract(b, a);\n        Shares::StandardShare * result = this->lessThanZeroCatrinaModShares(c);\n        delete c;\n        return result;\n    };\n    \n    //1-ltz(-a) : a<=0\n    Shares::StandardShare * ShamirSharesEngine::lessEqualThanCatrinaModShares(Shares::StandardShare * a, Shares::StandardShare * b)\n    {\n        Shares::StandardShare * c = this->substract(b, a);\n        c= this->substractTo(1, c);\n        Shares::StandardShare * result = this->lessThanZeroCatrinaModShares(c);\n        delete c;\n        return result;\n    };\n    //1-ltz(a) : a<=0\n    Shares::StandardShare * ShamirSharesEngine::greaterEqualThanCatrinaModShares(Shares::StandardShare * a, Shares::StandardShare * b)\n    {\n        Shares::StandardShare * c = this->substract(a, b);\n        c= this->substractTo(1, c);\n        Shares::StandardShare * result = this->lessThanZeroCatrinaModShares(c);\n        delete c;\n        return result;\n    };\n    \n    //c?onTrue:onFalse\n    Shares::StandardShare * ShamirSharesEngine::assigmentOperationShares(Shares::StandardShare *c, Shares::StandardShare *onTrue,Shares::StandardShare *onFalse)\n    {\n        Shares::StandardShare * result =NULL;\n        \n        result= this->multiplyTo(this->substract(onTrue,onFalse), c);\n        result= this->addTo(result,onFalse);\n        return result;\n    };\n    \n    Shares::StandardShare * ShamirSharesEngine::assigmentOperationShares(Shares::StandardShare *c, Shares::StandardShare *onTrue,long onFalse)\n    {\n        Shares::StandardShare * result =NULL;\n        \n        result= this->multiplyTo(this->substract(onTrue,onFalse), c);\n        result= this->addTo(result,onFalse);\n        return result;\n    };\n    \n    //connectivity methods\n    Shares::StandardShare * ShamirSharesEngine::buildShare(long value)\n    {\n        return Utilities::ShareUtil::wrapStandardShare(this->player_->getPlayer(), value);\n    };\n    \n    //sync several shares across all players.\n    Utils::List<Utils::List<Shares::StandardShare> > * ShamirSharesEngine::syncGlobal(Utils::List<Shares::StandardShare> * shares)\n    {\n        Utils::List<Utils::List<Shares::StandardShare> > *list= new Utils::List<Utils::List<Shares::StandardShare> >(players_->getLength());\n        for (int i=0; i<shares->getLength(); i++)\n        {\n            Utils::List<Shares::StandardShare> * aux=this->transmitShare(shares->get(i));\n            list->add(aux);\n        }\n        return list;\n        \n    };\n    \n    //returns a<b -memory save method\n    Shares::StandardShare * ShamirSharesEngine::lessThanToftShares(Shares::StandardShare * a, Shares::StandardShare * b)\n    {\n        Shares::StandardShare * comp =this->greaterEqualThanToftShares(a, b);\n        Shares::StandardShare * result =this->substract(1,comp);\n        delete comp;\n        return result;\n    };\n    \n    \n    //reconstruct several shares - similar to the method gather_shares in VIFF\n    std::vector<long>  ShamirSharesEngine::reconstructShares(Utils::List<Shares::StandardShare> * shares)\n    {\n        int size = shares->getLength();\n        std::vector<long> values;\n        values.resize(size);\n        Utils::List<Utils::List<Shares::StandardShare> > * syncShares= this->syncGlobal(shares);\n        long ld2=0;\n        if (signed_==true)\n        {\n            ld2= conv<long>(power(conv<ZZ_p>(2), this->l_-1));\n        }\n        for (int i=0; i<size; i++)\n        {\n            values[i]= this->interpolateValues(syncShares->get(i));\n            Utilities::ShareUtil::destroyList(syncShares->get(i));\n            if(signed_== true && values[i]>=ld2)\n            {\n                values[i]=values[i]- Utilities::Constants::SYSTEM_P;\n            }\n        }\n        delete syncShares;\n        \n        \n        return values;\n    };\n    \n    //reconstruct single share\n    long ShamirSharesEngine::reconstructShare(Shares::StandardShare * share)\n    {\n        \n        Utils::List<Shares::StandardShare> * shares= this->transmitShare(share);\n        long result=this->interpolateValues(shares);\n\n        Utilities::ShareUtil::destroyList(shares);\n        return result;\n        \n    };\n    \n    //present single share\n    long ShamirSharesEngine::presentShare(Shares::StandardShare * share)\n    {\n        long result = this->reconstructShare(share);\n        long lp2= conv<long>(power(conv<ZZ_p>(2),31));\n        if(this->signed_ && result> lp2-1)\n        {\n            result =result - Utilities::Constants::SYSTEM_P;\n        }\n        return result;\n    };\n    //Tranmission Methods Implementations\n    \n    //Broadcast a share towards all the players, method used for sync, and reconstructions\n    Utils::List<Shares::StandardShare> * ShamirSharesEngine::transmitShare(Shares::StandardShare *  share)\n    {\n      //double begin_time = mach_absolute_time();\n\n        //player claims ownership of the share before transmission\n        Shares::StandardShare * localShare= share->clone();\n        localShare->setPlayerId(this->player_->getPlayer());\n        \n        //create distribution list for  all players for everybody to be able to interpolate later\n        Utils::List<Shares::StandardShare> *list = new Utils::List<Shares::StandardShare>(players_->getLength());\n        for (int i=0; i<this->players_->getLength(); i++) {\n            list->add(localShare);\n        }\n        //transimssion process\n        Utils::List<Shares::StandardShare> * aux =this->shareManager_->transmitShares(list,  Buffers::EngineBuffers::operationCounter_+1);\n        Buffers::EngineBuffers::operationCounter_++;\n        \n        //instead of using destroy list, destroy the shares individually that way we dont waste a for loop\n        delete  localShare;\n        delete list;\n\n        \n        //ShamirSharesEngine::relativeTime += double( mach_absolute_time() - begin_time );\n        \n        return aux;\n    };\n    \n    //method used to share original value, not to bradcast shares\n    Utils::List<Shares::StandardShare> * ShamirSharesEngine::shareValue(long value)\n    {\n      //        double tInitial =mach_absolute_time();\n        \n        Utils::List<Shares::StandardShare> *list = new Utils::List<Shares::StandardShare>(players_->getLength());\n        this->generator_->generateShares(value, players_->getLength(),list);\n        //it invokes it directly because saving RAM memory, given that no modification is needed. i\n        Utils::List<Shares::StandardShare> * aux =this->shareManager_->transmitShares(list,  Buffers::EngineBuffers::operationCounter_+1);\n        Buffers::EngineBuffers::operationCounter_++;\n        \n        Utilities::ShareUtil::destroyList(list);\n    \n        //ShamirSharesEngine::relativeTime += (mach_absolute_time() - tInitial);\n        \n        return aux;\n        \n    };\n    \n    // this method provides a matrix on which the columns are players and rows are the numbers.\n    //for that matter we need to do a transposition of the natural disposition of the values\n    Utils::List<Utils::List<Shares::StandardShare> > * ShamirSharesEngine::transmitShareBitwise(Utils::List<Shares::StandardShare> * shares, int l)\n    {\n        //ET: here change shares->getLength()\n        int players= this->players_->getLength();\n        Utils::List<Utils::List<Shares::StandardShare> > * list = new Utils::List<Utils::List<Shares::StandardShare> >(players);\n        for(int i=0; i<players;i++)\n        {\n            list->add(new Utils::List<Shares::StandardShare>);\n        }\n        for (int i=0; i<l; i++)\n        {\n            Utils::List<Shares::StandardShare> * localList=this->transmitShare(shares->get(i));\n            \n            for (int j=0; j<players; j++)\n            {\n                list->get(j)->add(localList->get(j));\n            }\n            //list->add(this->transmitShare(shares->get(i)));\n        }\n        return list;\n    };\n    \n    //this method provides a matrix on which the columns are players and rows are the numbers.\n    //for that matter we need to do a transposition of the natural disposition of the values\n    Utils::List<Utils::List<Shares::StandardShare> > * ShamirSharesEngine::shareValueBitwise(long value, int l)\n    {\n        //int size =this->nBits_;\n        int players= this->players_->getLength();\n        int * bits= Utilities::MathUtil::obtainBits(value, l);\n        Utils::List<Utils::List<Shares::StandardShare> > * list = new Utils::List<Utils::List<Shares::StandardShare> >(players);\n        \n        //instantation of the lists\n        for(int i=0; i<players;i++)\n        {\n            list->add(new Utils::List<Shares::StandardShare>);\n        }\n        \n        //creation of the matrix of values\n        for (int i=0; i<l; i++)\n        {\n            Utils::List<Shares::StandardShare> * localList=this->shareValue(bits[i]);\n            for (int j=0; j<players; j++)\n            {\n                list->get(j)->add(localList->get(j));\n            }\n            \n        }\n        \n        delete [] bits;\n        \n        return list;\n    };\n    \n    \n    ShamirSharesEngine::~ShamirSharesEngine()\n    {\n        listener_->stopListener();\n        delete Buffers::EngineBuffers::nextOperationBuffer_;\n        delete Buffers::EngineBuffers::workingBuffer_;\n        delete this->listener_;\n        delete this->shareManager_;\n        delete this->generator_;\n        \n        for (int i=0; i<Buffers::EngineBuffers::incomingSharesBuffer_.capacity(); i++)\n        {\n            \n            Shares::StandardShare *aux=Buffers::EngineBuffers::incomingSharesBuffer_[i];\n            if (aux!=NULL) {\n                \n                delete aux;\n            }\n            Buffers::EngineBuffers::incomingSharesBuffer_.clear();\n            \n        }\n    };\n    \n    double    ShamirSharesEngine::getTime()\n    {\n        //return 1;\n        return ShamirSharesEngine::relativeTime;\n    };\n}\n", "meta": {"hexsha": "bebf0069a1392f828e09089fbb691d546dd56dad", "size": 64251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "edgeRuntime/ShamirSharesEngine.cpp", "max_stars_repo_name": "abdelrahamanaly/mpcToolkit", "max_stars_repo_head_hexsha": "fe656355cef77f9c40284339ba6d5e03dea03467", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T16:11:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T15:08:05.000Z", "max_issues_repo_path": "edgeRuntime/ShamirSharesEngine.cpp", "max_issues_repo_name": "abdelrahamanaly/mpcToolkit", "max_issues_repo_head_hexsha": "fe656355cef77f9c40284339ba6d5e03dea03467", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "edgeRuntime/ShamirSharesEngine.cpp", "max_forks_repo_name": "abdelrahamanaly/mpcToolkit", "max_forks_repo_head_hexsha": "fe656355cef77f9c40284339ba6d5e03dea03467", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T03:22:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T03:22:28.000Z", "avg_line_length": 38.8928571429, "max_line_length": 272, "alphanum_fraction": 0.589702884, "num_tokens": 16216, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152325073083132, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.4203501167129751}}
{"text": "/*!@file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include \"Molassembler/DistanceGeometry/MetricMatrix.h\"\n#include \"Molassembler/Types.h\"\n\n#include <Eigen/Eigenvalues>\n\nnamespace Scine {\nnamespace Molassembler {\nnamespace DistanceGeometry {\n\nvoid MetricMatrix::constructFromTemporary_(Eigen::MatrixXd&& distances) {\n  /* We have to be a little careful since only strict upper triangle of\n   * distances contains anything of use to us.\n   *\n   * So we have to make sure the first index is always smaller than the second\n   * to reference the correct entry.\n   */\n\n  const AtomIndex N = distances.rows();\n\n  /* Resize our underlying matrix. There is no need to zero-initialize since all\n   * parts of the lower triangle (including the diagonal) are overwritten.\n   */\n  matrix_.resize(N, N);\n\n  /* We need to accomplish the following:\n   *\n   * Every entry in the lower triangle of matrix_ (including the diagonal)\n   * needs to be set according to the result of the following equations:\n   *\n   * D0[i]² =   (1/N) * sum_{j}(distances[i, j]²)\n   *          - (1/(N²)) * sum_{j < k}(distances[j, k]²)\n   *\n   *  (The second term is independent of i and can be precalculated!)\n   *\n   * matrix_[i, j] = ( D0[i]² + D0[j]² - distances[i, j]² ) / 2\n   *\n   * On the diagonal, where i == j:\n   * matrix_[i, i] = ( D0[i]² + D0[i]² - distances[i, i]² ) / 2\n   *                     ^--------^      ^-------------^\n   *                       equal               =0\n   *\n   * -> matrix_[i, i] = D0[i]²\n   *\n   * So, we can store all of D0 immediately on matrix_'s diagonal and perform\n   * the remaining transformation afterwards.\n   */\n\n  // Since we need squares EVERYWHERE, just square the whole distances matrix\n  distances = distances.cwiseProduct(distances);\n\n  double doubleSumTerm = 0;\n  for(AtomIndex j = 0; j < N; ++j) {\n    for(AtomIndex k = j + 1; k < N; ++k) {\n      doubleSumTerm += distances(j, k);\n    }\n  }\n  doubleSumTerm /= N * N;\n\n  for(AtomIndex i = 0; i < N; ++i) {\n    // compute first term\n    double firstTerm = 0;\n    for(AtomIndex j = 0; j < N; ++j) {\n      if(i == j) {\n        continue;\n      }\n\n      firstTerm += distances(\n        std::min(i, j),\n        std::max(i, j)\n      );\n    }\n    firstTerm /= N;\n\n    // assign as difference, no need to sqrt, we need the squares in a moment\n    matrix_.diagonal()(i) = firstTerm - doubleSumTerm;\n  }\n\n  /* Write off-diagonal elements into lower triangle\n   * Why the lower triangle? Because that is the only part of the matrix\n   * referenced by Eigen's SelfAdjointEigenSolver, which we will use in a bit\n   * to embed the metric matrix\n   */\n  for(AtomIndex i = 0; i < N; i++) {\n    for(AtomIndex j = i + 1; j < N; j++) {\n      matrix_(j, i) = (\n        // D0[i]²             + D0[j]²                - d(i, j)²\n        matrix_.diagonal()(i) + matrix_.diagonal()(j) - distances(i, j)\n      ) / 2.0;\n    }\n  }\n}\n\nMetricMatrix::MetricMatrix(Eigen::MatrixXd distanceMatrix) {\n  constructFromTemporary_(std::move(distanceMatrix));\n}\n\nconst Eigen::MatrixXd& MetricMatrix::access() const {\n  return matrix_;\n}\n\nEigen::MatrixXd MetricMatrix::embed() const {\n  return embedWithFullDiagonalization();\n}\n\nEigen::MatrixXd MetricMatrix::embedWithFullDiagonalization() const {\n  constexpr unsigned dimensionality = 4;\n\n  // SelfAdjointEigenSolver only references the lower triangle\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigenSolver(matrix_);\n\n  Eigen::VectorXd eigenvalues = eigenSolver.eigenvalues();\n\n  // Construct L\n  Eigen::MatrixXd L = Eigen::MatrixXd::Zero(dimensionality, dimensionality);\n  // We want the algebraically largest eigenvalues (up to four, if present)\n  unsigned numEigenvalues = std::min(\n    static_cast<unsigned>(eigenvalues.size()),\n    dimensionality\n  );\n  for(unsigned i = 0; i < numEigenvalues; ++i) {\n    /* Since Eigen stores them in increasing order, we have to fetch the\n     * algebraically largest from the back. We only want to use the eigenpair\n     * if the eigenvalue is greater than zero.\n     */\n    if(eigenvalues(eigenvalues.size() - i - 1) > 0) {\n      L.diagonal()(i) = std::sqrt(\n        eigenvalues(eigenvalues.size() - i - 1)\n      );\n    }\n  }\n\n  // V is initially N x N\n  Eigen::MatrixXd V = eigenSolver.eigenvectors();\n  /* Again, eigenvectors are sorted in increasing corresponding eigenvalues\n   * algebraic value. We have to reverse them to match the ordering in L.\n   */\n  V.rowwise().reverseInPlace();\n  V.conservativeResize(V.rows(), dimensionality);\n  // now N x dimensionality\n\n  /* Calculate X = VL\n   * (N x 4) · (4 x 4) -> (N x 4), but we want (4 x N), so we transpose\n   */\n  return (V * L).transpose();\n}\n\nbool MetricMatrix::operator == (const MetricMatrix& other) const {\n  return matrix_ == other.matrix_;\n}\n\n} // namespace DistanceGeometry\n} // namespace Molassembler\n} // namespace Scine\n", "meta": {"hexsha": "55a864dc53bc5fd2c16b8facd63a269f7b4d4be1", "size": 4958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Molassembler/DistanceGeometry/MetricMatrix.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "src/Molassembler/DistanceGeometry/MetricMatrix.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Molassembler/DistanceGeometry/MetricMatrix.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 30.9875, "max_line_length": 80, "alphanum_fraction": 0.6383622428, "num_tokens": 1357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.4203501074543424}}
{"text": "/*\n * Copyright (C) 2022 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <string>\n#include <Eigen/Eigen>\n#include <ignition/common/Profiler.hh>\n#include <ignition/math/Vector3.hh>\n#include <ignition/plugin/Register.hh>\n#include <sdf/sdf.hh>\n\n#include \"ignition/gazebo/Link.hh\"\n#include \"ignition/gazebo/Model.hh\"\n\n#include \"SimpleHydrodynamics.hh\"\n\nusing namespace ignition;\nusing namespace gazebo;\nusing namespace systems;\n\nclass ignition::gazebo::systems::SimpleHydrodynamicsPrivate\n{\n  /// \\brief The link entity.\n  public: ignition::gazebo::Link link;\n\n  /// \\brief Model interface.\n  public: Model model{kNullEntity};\n\n  /// \\brief Added mass in surge, X_\\dot{u}.\n  public: double paramXdotU{0.0};\n\n  /// \\brief Added mass in sway, Y_\\dot{v}.\n  public: double paramYdotV{0.0};\n\n  /// \\brief Added mass in heave, Z_\\dot{w}.\n  public: double paramZdotW{0.0};\n\n  /// \\brief Added mass in roll, K_\\dot{p}.\n  public: double paramKdotP{0.0};\n\n  /// \\brief Added mass in pitch, M_\\dot{q}.\n  public: double paramMdotQ{0.0};\n\n  /// \\brief Added mass in yaw, N_\\dot{r}.\n  public: double paramNdotR{0.0};\n\n  /// \\brief Linear drag in surge.\n  public: double paramXu{0.0};\n\n  /// \\brief Quadratic drag in surge.\n  public: double paramXuu{0.0};\n\n  /// \\brief Linear drag in sway.\n  public: double paramYv{0.0};\n\n  /// \\brief Quadratic drag in sway.\n  public: double paramYvv{0.0};\n\n  /// \\brief Linear drag in heave.\n  public: double paramZw{0.0};\n\n  /// \\brief Quadratic drag in heave.\n  public: double paramZww{0.0};\n\n  /// \\brief Linear drag in roll.\n  public: double paramKp{0.0};\n\n  /// \\brief Quadratic drag in roll.\n  public: double paramKpp{0.0};\n\n  /// \\brief Linear drag in pitch.\n  public: double paramMq{0.0};\n\n  /// \\brief Quadratic drag in pitch.\n  public: double paramMqq{0.0};\n\n  /// \\brief Linear drag in yaw.\n  public: double paramNr{0.0};\n\n  /// \\brief Quadratic drag in yaw.\n  public: double paramNrr{0.0};\n\n  /// \\brief Added mass of vehicle.\n  /// See: https://en.wikipedia.org/wiki/Added_mass\n  public: Eigen::MatrixXd Ma;\n};\n\n\n//////////////////////////////////////////////////\nSimpleHydrodynamics::SimpleHydrodynamics()\n  : dataPtr(std::make_unique<SimpleHydrodynamicsPrivate>())\n{\n}\n\n//////////////////////////////////////////////////\nvoid SimpleHydrodynamics::Configure(const Entity &_entity,\n    const std::shared_ptr<const sdf::Element> &_sdf,\n    EntityComponentManager &_ecm,\n    EventManager &/*_eventMgr*/)\n{\n  this->dataPtr->model = Model(_entity);\n\n  // Parse required elements.\n  if (!_sdf->HasElement(\"link_name\"))\n  {\n    ignerr << \"No <link_name> specified\" << std::endl;\n    return;\n  }\n\n  std::string linkName = _sdf->Get<std::string>(\"link_name\");\n  this->dataPtr->link = Link(this->dataPtr->model.LinkByName(_ecm, linkName));\n  if (!this->dataPtr->link.Valid(_ecm))\n  {\n    ignerr << \"Could not find link named [\" << linkName\n           << \"] in model\" << std::endl;\n    return;\n  }\n\n  this->dataPtr->link.EnableVelocityChecks(_ecm);\n  this->dataPtr->link.EnableAccelerationChecks(_ecm);\n\n  this->dataPtr->paramXdotU       = _sdf->Get<double>(\"xDotU\", 5  ).first;\n  this->dataPtr->paramYdotV       = _sdf->Get<double>(\"yDotV\", 5  ).first;\n  this->dataPtr->paramZdotW       = _sdf->Get<double>(\"zDotW\", 0.1).first;\n  this->dataPtr->paramKdotP       = _sdf->Get<double>(\"kDotP\", 0.1).first;\n  this->dataPtr->paramMdotQ       = _sdf->Get<double>(\"mDotQ\", 0.1).first;\n  this->dataPtr->paramNdotR       = _sdf->Get<double>(\"nDotR\", 1  ).first;\n  this->dataPtr->paramXu          = _sdf->Get<double>(\"xU\",   20  ).first;\n  this->dataPtr->paramXuu         = _sdf->Get<double>(\"xUU\",   0  ).first;\n  this->dataPtr->paramYv          = _sdf->Get<double>(\"yV\",   20  ).first;\n  this->dataPtr->paramYvv         = _sdf->Get<double>(\"yVV\",   0  ).first;\n  this->dataPtr->paramZw          = _sdf->Get<double>(\"zW\",   20  ).first;\n  this->dataPtr->paramZww         = _sdf->Get<double>(\"zWW\",   0  ).first;\n  this->dataPtr->paramKp          = _sdf->Get<double>(\"kP\",   20  ).first;\n  this->dataPtr->paramKpp         = _sdf->Get<double>(\"kPP\",   0  ).first;\n  this->dataPtr->paramMq          = _sdf->Get<double>(\"mQ\",   20  ).first;\n  this->dataPtr->paramMqq         = _sdf->Get<double>(\"mQQ\",   0  ).first;\n  this->dataPtr->paramNr          = _sdf->Get<double>(\"nR\",   20  ).first;\n  this->dataPtr->paramNrr         = _sdf->Get<double>(\"nRR\",   0  ).first;\n\n  // Added mass according to Fossen's equations (p 37).\n  this->dataPtr->Ma = Eigen::MatrixXd::Zero(6, 6);\n\n  this->dataPtr->Ma(0, 0) = this->dataPtr->paramXdotU;\n  this->dataPtr->Ma(1, 1) = this->dataPtr->paramYdotV;\n  this->dataPtr->Ma(2, 2) = this->dataPtr->paramZdotW;\n  this->dataPtr->Ma(3, 3) = this->dataPtr->paramKdotP;\n  this->dataPtr->Ma(4, 4) = this->dataPtr->paramMdotQ;\n  this->dataPtr->Ma(5, 5) = this->dataPtr->paramNdotR;\n\n  igndbg << \"SimpleHydrodynamics plugin successfully configured with the \"\n         << \"following parameters:\"                        << std::endl;\n  igndbg << \"  <link_name>: \" << linkName                  << std::endl;\n  igndbg << \"  <xDotU>: \"     << this->dataPtr->paramXdotU << std::endl;\n  igndbg << \"  <yDotV>: \"     << this->dataPtr->paramYdotV << std::endl;\n  igndbg << \"  <zDotW>: \"     << this->dataPtr->paramZdotW << std::endl;\n  igndbg << \"  <kDotP>: \"     << this->dataPtr->paramKdotP << std::endl;\n  igndbg << \"  <mDotQ>: \"     << this->dataPtr->paramMdotQ << std::endl;\n  igndbg << \"  <nDotR>: \"     << this->dataPtr->paramNdotR << std::endl;\n  igndbg << \"  <xU>: \"        << this->dataPtr->paramXu    << std::endl;\n  igndbg << \"  <xUU>: \"       << this->dataPtr->paramXuu   << std::endl;\n  igndbg << \"  <yV>: \"        << this->dataPtr->paramYv    << std::endl;\n  igndbg << \"  <yVV>: \"       << this->dataPtr->paramYvv   << std::endl;\n  igndbg << \"  <zW>: \"        << this->dataPtr->paramZw    << std::endl;\n  igndbg << \"  <zWW>: \"       << this->dataPtr->paramZww   << std::endl;\n  igndbg << \"  <kP>: \"        << this->dataPtr->paramKp    << std::endl;\n  igndbg << \"  <kPP>: \"       << this->dataPtr->paramKpp   << std::endl;\n  igndbg << \"  <mQ>: \"        << this->dataPtr->paramMq    << std::endl;\n  igndbg << \"  <mQQ>: \"       << this->dataPtr->paramMqq   << std::endl;\n  igndbg << \"  <nR>: \"        << this->dataPtr->paramNr    << std::endl;\n  igndbg << \"  <nRR>: \"       << this->dataPtr->paramNrr   << std::endl;\n}\n\n//////////////////////////////////////////////////\nvoid SimpleHydrodynamics::PreUpdate(\n    const ignition::gazebo::UpdateInfo &/*_info*/,\n    ignition::gazebo::EntityComponentManager &_ecm)\n{\n  IGN_PROFILE(\"SimpleHydrodynamics::PreUpdate\");\n\n  if (!this->dataPtr->link.Valid(_ecm))\n    return;\n\n  Eigen::VectorXd stateDot = Eigen::VectorXd(6);\n  Eigen::VectorXd state    = Eigen::VectorXd(6);\n  Eigen::MatrixXd Cmat     = Eigen::MatrixXd::Zero(6, 6);\n  Eigen::MatrixXd Dmat     = Eigen::MatrixXd::Zero(6, 6);\n\n  // Get vehicle state.\n  auto worldAngularVel = this->dataPtr->link.WorldAngularVelocity(_ecm);\n  auto worldLinearVel = this->dataPtr->link.WorldLinearVelocity(_ecm);\n  auto worldAngularAccel = this->dataPtr->link.WorldAngularAcceleration(_ecm);\n  auto worldLinearAccel = this->dataPtr->link.WorldLinearAcceleration(_ecm);\n\n  // Sanity check: Make sure that we can read the full state.\n  if (!worldAngularVel)\n  {\n    ignerr << \"No angular velocity\" <<\"\\n\";\n    return;\n  }\n\n  if (!worldLinearVel)\n  {\n    ignerr << \"No linear velocity\" <<\"\\n\";\n    return;\n  }\n\n  if (!worldAngularAccel)\n  {\n    ignerr << \"No angular acceleration\" <<\"\\n\";\n    return;\n  }\n\n  if (!worldLinearAccel)\n  {\n    ignerr << \"No linear acceleration\" <<\"\\n\";\n    return;\n  }\n\n  // Transform from world to local frame.\n  auto comPose = this->dataPtr->link.WorldInertialPose(_ecm);\n  auto localAngularVel   = comPose->Rot().Inverse() * (*worldAngularVel);\n  auto localLinearVel    = comPose->Rot().Inverse() * (*worldLinearVel);\n  auto localAngularAccel = comPose->Rot().Inverse() * (*worldAngularAccel);\n  auto localLinearAccel  = comPose->Rot().Inverse() * (*worldLinearAccel);\n\n  stateDot << localLinearAccel.X(), localLinearAccel.Y(), localLinearAccel.Z(),\n   localAngularAccel.X(), localAngularAccel.Y(), localAngularAccel.Z();\n\n  state << localLinearVel.X(), localLinearVel.Y(), localLinearVel.Z(),\n    localAngularVel.X(), localAngularVel.Y(), localAngularVel.Z();\n\n  // Added Mass.\n  const Eigen::VectorXd kAmassVec = -1.0 * this->dataPtr->Ma * stateDot;\n\n  // Coriolis - added mass components.\n  Cmat(0, 5) = this->dataPtr->paramYdotV * localLinearVel.Y();\n  Cmat(1, 5) = this->dataPtr->paramXdotU * localLinearVel.X();\n  Cmat(5, 0) = this->dataPtr->paramYdotV * localLinearVel.Y();\n  Cmat(5, 1) = this->dataPtr->paramXdotU * localLinearVel.X();\n\n  // Drag.\n  Dmat(0, 0) = this->dataPtr->paramXu +\n    this->dataPtr->paramXuu * std::abs(localLinearVel.X());\n  Dmat(1, 1) = this->dataPtr->paramYv +\n    this->dataPtr->paramYvv * std::abs(localLinearVel.Y());\n  Dmat(2, 2) = this->dataPtr->paramZw +\n    this->dataPtr->paramZww * std::abs(localLinearVel.Z());\n  Dmat(3, 3) = this->dataPtr->paramKp +\n    this->dataPtr->paramKpp * std::abs(localAngularVel.X());\n  Dmat(4, 4) = this->dataPtr->paramMq +\n    this->dataPtr->paramMqq * std::abs(localAngularVel.Y());\n  Dmat(5, 5) = this->dataPtr->paramNr +\n    this->dataPtr->paramNrr * std::abs(localAngularVel.Z());\n\n  const Eigen::VectorXd kDvec = -1.0 * Dmat * state;\n\n  // Sum all forces - in body frame.\n  const Eigen::VectorXd kForceSum = kAmassVec + kDvec;\n\n  // Transform the force and torque to the world frame.\n  ignition::math::Vector3d forceWorld = (*comPose).Rot().RotateVector(\n    ignition::math::Vector3d(kForceSum(0), kForceSum(1), kForceSum(2)));\n  ignition::math::Vector3d torqueWorld = (*comPose).Rot().RotateVector(\n    ignition::math::Vector3d(kForceSum(3), kForceSum(4), kForceSum(5)));\n\n  // Apply the force and torque at COM.\n  this->dataPtr->link.AddWorldWrench(_ecm, forceWorld, torqueWorld);\n}\n\nIGNITION_ADD_PLUGIN(SimpleHydrodynamics,\n                    ignition::gazebo::System,\n                    SimpleHydrodynamics::ISystemConfigure,\n                    SimpleHydrodynamics::ISystemPreUpdate)\n\nIGNITION_ADD_PLUGIN_ALIAS(SimpleHydrodynamics,\n                          \"ignition::gazebo::systems::SimpleHydrodynamics\")\n", "meta": {"hexsha": "16b03cf7aa630ff7af2c041aa470aff309b2eb98", "size": 10800, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mbzirc_ign/src/SimpleHydrodynamics.cc", "max_stars_repo_name": "j-rivero/mbzirc", "max_stars_repo_head_hexsha": "7ca99733f024cf22f1f884e61c679ca6c92ac12f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mbzirc_ign/src/SimpleHydrodynamics.cc", "max_issues_repo_name": "j-rivero/mbzirc", "max_issues_repo_head_hexsha": "7ca99733f024cf22f1f884e61c679ca6c92ac12f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mbzirc_ign/src/SimpleHydrodynamics.cc", "max_forks_repo_name": "j-rivero/mbzirc", "max_forks_repo_head_hexsha": "7ca99733f024cf22f1f884e61c679ca6c92ac12f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1134020619, "max_line_length": 79, "alphanum_fraction": 0.6281481481, "num_tokens": 3393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4203113874342996}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// statistics::survival::data::data::mngr::default_parameter_records.hpp     //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_SURVIVAL_DATA_DATA_MNGR_DEFAULT_PARAMETER_RECORDS_HPP_ER_2009\n#define BOOST_STATISTICS_SURVIVAL_DATA_DATA_MNGR_DEFAULT_PARAMETER_RECORDS_HPP_ER_2009\n#include <algorithm>\n#include <ext/algorithm> // is_sorted\n#include <iterator>\n#include <boost/serialization/base_object.hpp>\n#include <boost/range.hpp>\n#include <boost/functional/clock.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/statistics/model/wrap/unary/parameter.hpp>\n#include <boost/statistics/model/wrap/unary/model.hpp>\n#include <boost/statistics/model/wrap/aggregate/model_parameter.hpp>\n#include <boost/statistics/survival/data/data/mngr/records.hpp>\n#include <boost/statistics/survival/data/data/mngr/default_covariates_model.hpp>\n#include <boost/statistics/survival/data/random/default_batch.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace survival{\nnamespace data{\n\n    // Same as dataset_y but can self-generate records by internally using\n    // default_batch\n    //\n    // P parameter type\n    template<typename T,typename P>\n    class default_parameter_records_mngr : public records_mngr<T>{\n        typedef records_mngr<T> super_t;\n        typedef statistics::model::parameter_wrapper<P> parameter_wrapper_type; \n        \n        public:\n        typedef functional::clock<T>    clock_type;\n\n        // [ Construction ]\n        default_parameter_records_mngr();\n        default_parameter_records_mngr(const P&);\n        \n        // [ Update ]\n        // Generates records at the back of container\n        template<typename N,typename X,typename M,typename U>\n        void back_generate(\n            N n,\n            default_covariates_model_mngr<X,M> cm,\n            const clock_type& c,\n            U& urng\n        );\n\n        template<typename N,typename X,typename M,typename U>\n        void back_generate(\n            N n,\n            default_covariates_model_mngr<X,M> cm,\n            const T& t,     // clock parameters\n            const T& delta,\n            U& urng\n        );\n\n        void set_parameter(const P& p);\n\n        // [ Access ] \n        parameter_wrapper_type parameter_wrapper()const;\n\n        protected:\n        // [ Archive ]\n        friend class boost::serialization::access;\n        \n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int version);\n\n        // [ Variables ]\n        P p_;\n    };\n\n    // [ Construction ]\n    template<typename T,typename P>\n    default_parameter_records_mngr<T,P>::default_parameter_records_mngr(){}\n\n    template<typename T,typename P>\n    default_parameter_records_mngr<T,P>::default_parameter_records_mngr(\n        const P& p\n    )\n    :p_(p){}\n    \n    // [ Update ]\n    \n    template<typename T,typename P>\n    void default_parameter_records_mngr<T,P>::set_parameter(const P& p)\n    {\n        this->p_ = p;\n    }\n    \n    template<typename T,typename P>\n        template<typename N,typename X,typename M,typename U>\n    void default_parameter_records_mngr<T,P>::back_generate(\n        N n,\n        default_covariates_model_mngr<X,M> cm, \n        const clock_type& c, \n        U& urng\n    ){\n        typedef default_covariates_model_mngr<X,M>          cm_;\n        typedef typename cm_::x_values_type                 rx_;\n        typedef random::meta_default_batch<T,M,P,rx_>       meta_;\n        typedef typename meta_::type                        batch_;\n        typedef variate_generator<U&,batch_>                vg_; \n        typedef statistics::model::model_parameter_<M,P>    mp_;\n\n        typename meta_::rcov_ r_x = meta_::rcov(\n            cm.x_values(), \n            0,\n            n\n        );\n\n        mp_ mp(\n            cm.model_wrapper(),\n            this->parameter_wrapper()\n        );\n        batch_ b = meta_::make( \n            mp,\n            c, \n            r_x\n        );\n\n        vg_ vg( urng, b ); \n        std::generate_n(\n            std::back_inserter( this->records_ ),\n            n,\n            vg\n        ); \n\n        BOOST_ASSERT(\n            is_sorted(\n                boost::begin( this->records() ),\n                boost::end( this->records() )\n            )\n        );// clock is supposed to tick forward\n\n    }\n\n    template<typename T,typename P>\n        template<typename N,typename X,typename M,typename U>\n    void default_parameter_records_mngr<T,P>::back_generate(\n        N n,\n        default_covariates_model_mngr<X,M> cm,\n        const T& t,\n        const T& delta,\n        U& urng\n    )\n    {\n        return default_parameter_records_mngr<T,P>::back_generate(\n            n,\n            cm, \n            clock_type(t,delta), \n            urng\n        );        \n    }\n\n    // [ Access ] \n    template<typename T,typename P>\n    typename default_parameter_records_mngr<T,P>::parameter_wrapper_type \n    default_parameter_records_mngr<T,P>::parameter_wrapper()const{\n        return parameter_wrapper_type(this->p_);\n    }\n\n    // [ Archive ]\n    template<typename T,typename P>\n    template<class Archive>\n    void default_parameter_records_mngr<T,P>::serialize(\n        Archive & ar, \n        const unsigned int version\n    )\n    {\n        ar & boost::serialization::base_object<super_t>(*this);\n        ar & (this->p_);\n    }\n    \n}// data\n}// survival\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "0f525422d0a189c7f2ee5d48684a9d9b2448742a", "size": 5813, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "survival_data copy/boost/statistics/survival/data/data/mngr/default_parameter_records.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "survival_data copy/boost/statistics/survival/data/data/mngr/default_parameter_records.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "survival_data copy/boost/statistics/survival/data/data/mngr/default_parameter_records.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.920212766, "max_line_length": 86, "alphanum_fraction": 0.5840357819, "num_tokens": 1257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334525, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4203113874342995}}
{"text": "/*\r\n Copyright (c) 2010, The Barbarian Group\r\n All rights reserved.\r\n\r\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\r\n the following conditions are met:\r\n\r\n    * Redistributions of source code must retain the above copyright notice, this list of conditions and\r\n\tthe following disclaimer.\r\n    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\r\n\tthe following disclaimer in the documentation and/or other materials provided with the distribution.\r\n\r\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\r\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\r\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\r\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n POSSIBILITY OF SUCH DAMAGE.\r\n*/\r\n\r\n#include \"cinder/PolyLine.h\"\r\n\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/multi/multi.hpp>\r\n\r\nnamespace cinder {\r\n\r\ntemplate<typename T>\r\nT PolyLine<T>::getPosition( float t ) const\r\n{\r\n\ttypedef typename T::TYPE R;\r\n\tif( mPoints.size() <= 1 ) return T::zero();\r\n\tif( t >= 1 ) return mPoints.back();\r\n\tif( t <= 0 ) return mPoints[0];\r\n\t\r\n\tsize_t numSpans = mPoints.size() - 1;\r\n\tsize_t span = (size_t)math<R>::floor( t * numSpans );\r\n\tR lerpT = ( t - span / (R)numSpans ) * numSpans;\r\n\treturn mPoints[span] * ( 1 - lerpT ) + mPoints[span+1] * lerpT;\r\n}\r\n\r\ntemplate<typename T>\r\nT PolyLine<T>::getDerivative( float t ) const\r\n{\r\n\ttypedef typename T::TYPE R;\r\n\tif( mPoints.size() <= 1 ) return T::zero();\r\n\tif( t >= 1 ) return mPoints.back() - mPoints[mPoints.size()-2];\r\n\tif( t <= 0 ) return mPoints[1] - mPoints[0];\r\n\t\r\n\tsize_t numSpans = mPoints.size() - 1;\r\n\tsize_t span = (size_t)math<R>::floor( t * numSpans );\r\n\treturn mPoints[span+1] - mPoints[span];\r\n}\r\n\r\ntemplate<typename T>\r\nvoid PolyLine<T>::scale( const T &scaleFactor, T scaleCenter )\r\n{\r\n\tfor( typename std::vector<T>::iterator ptIt = mPoints.begin(); ptIt != mPoints.end(); ++ptIt )\r\n\t\t*ptIt = scaleCenter + ( *ptIt - scaleCenter ) * scaleFactor;\r\n}\r\n\r\ntemplate<typename T>\r\nvoid PolyLine<T>::offset( const T &offsetBy )\r\n{\r\n\tfor( typename std::vector<T>::iterator ptIt = mPoints.begin(); ptIt != mPoints.end(); ++ptIt )\r\n\t\t*ptIt += offsetBy;\r\n}\r\n\r\ntemplate<typename T>\r\nT linearYatX( const Vec2<T> p[2], T x )\r\n{\r\n\tif( p[0].x == p[1].x ) \treturn p[0].y;\r\n\treturn p[0].y + (p[1].y - p[0].y) * (x - p[0].x) / (p[1].x - p[0].x);\r\n}\r\n\r\ntemplate<typename T>\r\nsize_t linearCrossings( const Vec2<T> p[2], const Vec2f &pt )\r\n{\r\n\tif( (p[0].x < pt.x && pt.x <= p[1].x ) ||\r\n\t\t(p[1].x < pt.x && pt.x <= p[0].x )) {\r\n\t\tif( pt.y > linearYatX<T>( p, pt.x ) )\r\n\t\t\treturn 1;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\ntemplate<typename T>\r\nbool PolyLine<T>::contains( const Vec2f &pt ) const\r\n{\r\n\tif( mPoints.size() <= 2 )\r\n\t\treturn false;\r\n\r\n\tsize_t crossings = 0;\r\n\tfor( size_t s = 0; s < mPoints.size() - 1; ++s ) {\r\n\t\tcrossings += linearCrossings( &(mPoints[s]), pt );\r\n\t}\r\n\r\n\tVec2f temp[2];\r\n\ttemp[0] = mPoints[mPoints.size()-1];\r\n\ttemp[1] = mPoints[0];\r\n\tcrossings += linearCrossings( &(temp[0]), pt );\r\n\t\r\n\treturn (crossings & 1) == 1;\r\n}\r\n\r\n\r\nnamespace {\r\ntypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;\r\n\r\ntemplate<typename T>\r\nstd::vector<PolyLine<T> > convertBoostGeometryPolygons( std::vector<polygon> &polygons )\r\n{\r\n\tstd::vector<PolyLine<T> > result;\r\n\tfor( std::vector<polygon>::const_iterator outIt = polygons.begin(); outIt != polygons.end(); ++outIt ) {\r\n\t\ttypedef polygon::inner_container_type::const_iterator RingIterator;\r\n\t\ttypedef polygon::ring_type::const_iterator PointIterator;\r\n\r\n\t\tresult.push_back( PolyLine<T>() );\t\r\n\t\tfor( PointIterator pt = outIt->outer().begin(); pt != outIt->outer().end(); ++pt )\r\n\t\t\tresult.back().push_back( T( boost::geometry::get<0>(*pt), boost::geometry::get<1>(*pt) ) );\r\n\r\n\t\tfor( RingIterator crunk = outIt->inners().begin(); crunk != outIt->inners().end(); ++crunk ) {\r\n\t\t\tPolyLine<T> contour;\r\n\t\t\tfor( PointIterator pt = crunk->begin(); pt != crunk->end(); ++pt )\r\n\t\t\t\tcontour.push_back( T( boost::geometry::get<0>(*pt), boost::geometry::get<1>(*pt) ) );\r\n\t\t\tresult.push_back( contour );\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn result;\r\n}\r\n\r\ntemplate<typename T>\r\npolygon convertPolyLinesToBoostGeometry( const std::vector<PolyLine<T> > &a )\r\n{\r\n\tpolygon result;\r\n\t\r\n\tfor( typename std::vector<T>::const_iterator ptIt = a[0].getPoints().begin(); ptIt != a[0].getPoints().end(); ++ptIt )\r\n\t\tresult.outer().push_back( boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( ptIt->x, ptIt->y ) );\r\n\tfor( typename std::vector<PolyLine<T> >::const_iterator plIt = a.begin() + 1; plIt != a.end(); ++plIt ) {\r\n\t\tpolygon::ring_type ring;\r\n\t\tfor( typename std::vector<T>::const_iterator ptIt = plIt->getPoints().begin(); ptIt != plIt->getPoints().end(); ++ptIt )\r\n\t\t\tring.push_back( boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( ptIt->x, ptIt->y ) );\r\n\t\tresult.inners().push_back( ring );\r\n\t}\r\n\t\r\n\tboost::geometry::correct( result );\r\n\t\r\n\treturn result;\r\n}\r\n} // anonymous namespace\r\n\r\ntemplate<typename T>\r\nstd::vector<PolyLine<T> > PolyLine<T>::calcUnion( const std::vector<PolyLine<T> > &a, std::vector<PolyLine<T> > &b )\r\n{\r\n\ttypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;\r\n\r\n\tif( a.empty() )\r\n\t\treturn b;\r\n\telse if( b.empty() )\r\n\t\treturn a;\r\n\r\n\tpolygon polyA = convertPolyLinesToBoostGeometry( a );\r\n\tpolygon polyB = convertPolyLinesToBoostGeometry( b );\r\n\t\r\n\tstd::vector<polygon> output;\r\n\tboost::geometry::union_( polyA, polyB, output );\r\n\r\n\treturn convertBoostGeometryPolygons<T>( output );\r\n}\r\n\r\ntemplate<typename T>\r\nstd::vector<PolyLine<T> > PolyLine<T>::calcIntersection( const std::vector<PolyLine<T> > &a, std::vector<PolyLine<T> > &b )\r\n{\r\n\ttypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;\r\n\r\n\tif( a.empty() )\r\n\t\treturn b;\r\n\telse if( b.empty() )\r\n\t\treturn a;\r\n\r\n\tpolygon polyA = convertPolyLinesToBoostGeometry( a );\r\n\tpolygon polyB = convertPolyLinesToBoostGeometry( b );\r\n\t\r\n\tstd::vector<polygon> output;\r\n\tboost::geometry::intersection( polyA, polyB, output );\r\n\r\n\treturn convertBoostGeometryPolygons<T>( output );\r\n}\r\n\r\ntemplate<typename T>\r\nstd::vector<PolyLine<T> > PolyLine<T>::calcXor( const std::vector<PolyLine<T> > &a, std::vector<PolyLine<T> > &b )\r\n{\r\n\ttypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;\r\n\r\n\tif( a.empty() )\r\n\t\treturn b;\r\n\telse if( b.empty() )\r\n\t\treturn a;\r\n\r\n\tpolygon polyA = convertPolyLinesToBoostGeometry( a );\r\n\tpolygon polyB = convertPolyLinesToBoostGeometry( b );\r\n\t\r\n\tstd::vector<polygon> output;\r\n\tboost::geometry::sym_difference( polyA, polyB, output );\r\n\r\n\treturn convertBoostGeometryPolygons<T>( output );\r\n}\r\n\r\ntemplate<typename T>\r\nstd::vector<PolyLine<T> > PolyLine<T>::calcDifference( const std::vector<PolyLine<T> > &a, std::vector<PolyLine<T> > &b )\r\n{\r\n\ttypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;\r\n\r\n\tif( a.empty() )\r\n\t\treturn b;\r\n\telse if( b.empty() )\r\n\t\treturn a;\r\n\r\n\tpolygon polyA = convertPolyLinesToBoostGeometry( a );\r\n\tpolygon polyB = convertPolyLinesToBoostGeometry( b );\r\n\t\r\n\tstd::vector<polygon> output;\r\n\tboost::geometry::difference( polyA, polyB, output );\r\n\r\n\treturn convertBoostGeometryPolygons<T>( output );\r\n}\r\n\r\ntemplate class PolyLine<Vec2f>;\r\ntemplate class PolyLine<Vec2d>;\r\n\r\n} // namespace cinder\r\n", "meta": {"hexsha": "41607c1b057d368eea0d77c8f480facdb5f21884", "size": 8083, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/Cinder/src/cinder/PolyLine.cpp", "max_stars_repo_name": "timmb/HarmonicMotion", "max_stars_repo_head_hexsha": "4ddf8ce98377260e57b6293d093a144a25ce3132", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-20T03:56:15.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-20T03:56:15.000Z", "max_issues_repo_path": "lib/Cinder/src/cinder/PolyLine.cpp", "max_issues_repo_name": "timmb/HarmonicMotion", "max_issues_repo_head_hexsha": "4ddf8ce98377260e57b6293d093a144a25ce3132", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/Cinder/src/cinder/PolyLine.cpp", "max_forks_repo_name": "timmb/HarmonicMotion", "max_forks_repo_head_hexsha": "4ddf8ce98377260e57b6293d093a144a25ce3132", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1054852321, "max_line_length": 124, "alphanum_fraction": 0.6720277125, "num_tokens": 2227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.42031138743429947}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef MTL_INFINITY_NORM_INCLUDE\n#define MTL_INFINITY_NORM_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/concept/magnitude.hpp>\n#include <boost/numeric/mtl/utility/enable_if.hpp>\n#include <boost/numeric/mtl/utility/is_row_major.hpp>\n#include <boost/numeric/mtl/utility/category.hpp>\n#include <boost/numeric/mtl/utility/tag.hpp>\n#include <boost/numeric/mtl/utility/property_map.hpp>\n#include <boost/numeric/mtl/operation/max_of_sums.hpp>\n#include <boost/numeric/mtl/vector/lazy_reduction.hpp>\n#include <boost/numeric/mtl/vector/reduction.hpp>\n#include <boost/numeric/mtl/vector/reduction_functors.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n\nnamespace mtl {\n\n    namespace vec {\n\n\ttemplate <unsigned long Unroll, typename Vector>\n\ttypename traits::enable_if_vector<Vector, typename RealMagnitude<typename Collection<Vector>::value_type>::type>::type\n\tinline infinity_norm(const Vector& vector)\n\t{\n\t    vampir_trace<2006> tracer;\n\t    typedef typename RealMagnitude<typename Collection<Vector>::value_type>::type result_type;\n\t    return reduction<Unroll, infinity_norm_functor, result_type>::apply(vector);\n\t}\n\n\t/*! Infinity-norm for vectors: infinity_norm(x) \\f$\\rightarrow |x|_\\infty\\f$.\n\t    \\retval The magnitude type of the respective value type, see Magnitude.\n\n\t    The norms are defined as \\f$|v|_\\infty=\\max_i |v_i|\\f$.\n\n\t    Vector norms are unrolled 8-fold by default. \n\t    An n-fold unrolling can be generated with infinity_norm<n>(x).\n\t    The maximum for n is 8 (it might be increased later).\n\t**/\n\ttemplate <typename Vector>\n\ttypename mtl::traits::enable_if_vector<Vector, typename RealMagnitude<typename Collection<Vector>::value_type>::type>::type\n\tinline infinity_norm(const Vector& vector)\n\t{\n\t    return infinity_norm<8>(vector);\n\t}\n\n\ttemplate <typename Vector>\n\tlazy_reduction<Vector, infinity_norm_functor> inline lazy_infinity_norm(const Vector& v)\n\t{  return lazy_reduction<Vector, infinity_norm_functor>(v); \t}\n    }\n\n    namespace mat {\n\t\n\t// Ignore unrolling for matrices \n\ttemplate <unsigned long Unroll, typename Matrix>\n\ttypename mtl::traits::enable_if_matrix<Matrix, typename RealMagnitude<typename Collection<Matrix>::value_type>::type>::type\n\tinline infinity_norm(const Matrix& matrix)\n\t{\n\t    vampir_trace<3011> tracer;\n\t    using mtl::impl::max_of_sums;\n\t    typename mtl::traits::row<Matrix>::type                             row(matrix); \n\t    return max_of_sums(matrix, mtl::traits::is_row_major<typename OrientedCollection<Matrix>::orientation>(), \n\t\t\t       row, num_rows(matrix));\n\t}\n\n\t/*! Infinity-norm for matrices: infinity_norm(x) \\f$\\rightarrow |x|_\\infty\\f$.\n\t    \\retval The magnitude type of the respective value type, see Magnitude.\n\n\t    The norms are defined as \\f$|A|_\\infty=\\max_i\\{\\sum_j(|A_{ij}|)\\}\\f$.\n\t    Matrix norms are not (yet) optimized by unrolling.\n\t**/\n\ttemplate <typename Matrix>\n\ttypename mtl::traits::enable_if_matrix<Matrix, typename RealMagnitude<typename Collection<Matrix>::value_type>::type>::type\n\tinline infinity_norm(const Matrix& matrix)\n\t{\n\t    return infinity_norm<8>(matrix);\n\t}\n    }\n\n    using vec::infinity_norm;\n    using vec::lazy_infinity_norm;\n    using mat::infinity_norm;\n\n} // namespace mtl\n\n#endif // MTL_INFINITY_NORM_INCLUDE\n", "meta": {"hexsha": "e79dae0f24f221096c1ba5f5880f48c4a1e83361", "size": 3717, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/infinity_norm.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/mtl/operation/infinity_norm.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/mtl/operation/infinity_norm.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 37.5454545455, "max_line_length": 124, "alphanum_fraction": 0.7382297552, "num_tokens": 912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.42026249810177757}}
{"text": "/*\nMaximilien Danisch\nMai 2016\nhttp://bit.ly/maxdan94\nmaximilien.danisch@telecom-paristech.fr\n\nInfo:\nFeel free to use these lines as you wish. This program computes the exact density-friendly decomposition.\n\nTo compile:\ng++ exactDF.cpp -fopenmp -fpermissive -o exactDF -O3\n\nTo execute:\n./exactDF ncpu iter net.txt rates.txt pavafit.txt cuts.txt exact.txt\n\n- nthreads is the number of threads to use\n- iter is the number of iterations over all edges to perform\n- net.txt should contain the graph (one edge on each line: 2 unsigned separated by a space)\n- rates.txt will contain the density value for each node\n- pavafit.txt will contain the profile given by the PAVA fit, that is the week approximation of the density-friendly (\"size density density-upperbound\" on each line)\n- cuts.txt will contain the profile given by correct cuts, that is the strong approximation of the density-friendly (\"size density density-upperbound\" on each line)\n- exact.txt will contain the exact density-friendly (\"size density\" on each line (it is not necesarily in decreasing order of density))\nSome information will be printed in the terminal.\n\n\n*/\n\n#include <boost/graph/edge_list.hpp>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/lexical_cast.hpp>\n#include <vector>\n#include <algorithm>\n#include <utility>\n#include <stdio.h> \n#include <stdlib.h>\n#include <omp.h>\n#include <time.h>\n\n#define NLINKS 500000000 //maximum number of edges for memory allocation, will increase if needed\n\ntypedef struct {\n\tunsigned s;\n\tunsigned t;\n  double a;//alpha value of edge (s,t)\n} edge;\n\ntypedef struct {\n\tunsigned n;\n\tdouble r;//rate value of node n\n} node;\n\ntypedef struct {\n\tunsigned n;//number of nodes\n\tunsigned e;//number of edges\n\tunsigned *map;//correspondance between old and new nodeID\n\tedge *edges;//list of all edges\n\tnode *nodes;//value associated to each node\n  double *ne;//ne[i]=number of edges from i to nodes before (used for pava)\n\tunsigned *cd;//cumulative degree\n\tunsigned *cuts;\n  unsigned iter;//number of iterations\n} optim;\n\n//compute the maximum of three unsigned\ninline unsigned max3(unsigned a,unsigned b,unsigned c){\n\ta=(a>b) ? a : b;\n\treturn (a>c) ? a : c;\n}\n\noptim* readedgelist(char* edgelist){\n\tunsigned e1=NLINKS;\n\toptim *opt=(optim*)malloc(sizeof(optim));\n\tFILE *file;\n\n\topt->n=0;\n\topt->e=0;\n\tfile=fopen(edgelist,\"r\");\n\topt->edges=(edge*)malloc(e1*sizeof(edge));\n\twhile (fscanf(file,\"%u %u\", &(opt->edges[opt->e].s), &(opt->edges[opt->e].t))==2) {\n\t\topt->n=max3(opt->n,opt->edges[opt->e].s,opt->edges[opt->e].t);\n\t\tif (opt->e++==e1) {\n\t\t\te1+=NLINKS;\n\t\t\topt->edges=(edge*)realloc(opt->edges,e1*sizeof(edge));\n\t\t}\n\t}\n\tfclose(file);\n\topt->n++;\n\topt->edges=(edge*)realloc(opt->edges,opt->e*sizeof(edge));\n\treturn opt;\n}\n\nvoid relabel(optim *opt) {\n\tunsigned i,j;\n\tunsigned *newlabel;\n\n\tnewlabel=(unsigned*)malloc(opt->n*sizeof(unsigned));\n\tfor (i=0;i<opt->n;i++) {\n\t\tnewlabel[i]=opt->n;\n\t}\n\topt->map=(unsigned*)malloc(opt->n*sizeof(unsigned));\n\tj=0;\n\tfor (i=0;i<opt->e;i++) {\n\t\tif (newlabel[opt->edges[i].s]==opt->n){\n\t\t\tnewlabel[opt->edges[i].s]=j;\n\t\t\topt->map[j++]=opt->edges[i].s;\n\t\t}\n\t\tif (newlabel[opt->edges[i].t]==opt->n){\n\t\t\tnewlabel[opt->edges[i].t]=j;\n\t\t\topt->map[j++]=opt->edges[i].t;\n\t\t}\n\t\topt->edges[i].s=newlabel[opt->edges[i].s];\n\t\topt->edges[i].t=newlabel[opt->edges[i].t];\n\t}\n\topt->n=j;\n\tfree(newlabel);\n\topt->map=(unsigned*)realloc(opt->map,opt->n*sizeof(unsigned));\n}\n\n//Step 1: Frank-Wolf gradiant descent\n\n//initialize the optim datastructure\nvoid init(optim *opt){\n  opt->iter=0;\n\topt->nodes=(node*)malloc(opt->n*sizeof(node));\n  for (unsigned k=0;k<opt->n;k++){\n    opt->nodes[k].n=k;\n    opt->nodes[k].r=0;\n  }\n\tfor (unsigned k=0;k<opt->e;k++){\n    opt->edges[k].a=.5;\n\t\topt->nodes[opt->edges[k].s].r+=.5;\n\t\topt->nodes[opt->edges[k].t].r+=.5;\n\t}\n}\n\n//one pass over all edges\nvoid onepass(optim *opt){\n\tunsigned i,j,k;\n\tdouble gamma;\n\topt->iter++;\n\tgamma=2./(2.+opt->iter);\n\t#pragma omp parallel for private(i,j,k)\n\tfor (k=0;k<opt->e;k++){//parfor\n\t\ti=opt->edges[k].s;\n\t\tj=opt->edges[k].t;\n\t\tif (opt->nodes[i].r<opt->nodes[j].r){\n\t\t\t#pragma omp atomic update\n\t\t\topt->nodes[i].r+=gamma*(1-opt->edges[k].a);//carefull\n\t\t\t#pragma omp atomic update\n\t\t\topt->nodes[j].r-=gamma*(1-opt->edges[k].a);\n\t\t\topt->edges[k].a=(1.-gamma)*opt->edges[k].a+gamma;\n\t\t}\n\t\telse if (opt->nodes[i].r>opt->nodes[j].r){\n\t\t\t#pragma omp atomic update\n\t\t\topt->nodes[i].r-=gamma*opt->edges[k].a;//carefull\n\t\t\t#pragma omp atomic update\n\t\t\topt->nodes[j].r+=gamma*opt->edges[k].a;\n\t\t\topt->edges[k].a*=(1.-gamma);\n\t\t}\n\t}\n}\n\n//to print in file the value for each stub: NOT USED\nvoid print_alphas(optim* opt, char* alphas){\n\tFILE *file=fopen(alphas,\"w\");\n\tunsigned long long k;\n\tfor (k=0;k<opt->e;k++){\n\t\tfprintf(file,\"%u %u %e\\n\",opt->map[opt->edges[k].s],opt->map[opt->edges[k].t],opt->edges[k].a);\n\t}\n\tfclose(file);\n}\n\nvoid freeoptim(optim *opt){\n\tfree(opt->map);\n\tfree(opt->edges);\n\tfree(opt->nodes);\n  free(opt->ne);\n\tfree(opt->cuts);\n\tfree(opt);\n}\n\n//Step 2: Isotonic regression with PAVA\n\n//used for quicksort (greatest hit in CS before this algorithm)\nstatic int compare_nodes(void const *a, void const *b){\n\tif (((node*)a)->r <= ((node*)b)->r)\n\t\treturn 1;\n\treturn -1;\n}\n//used for quicksort (greatest hit in CS before this algorithm)\nstatic int compare_edges(void const *a, void const *b){\n\tedge *pa = (edge *)a;\n\tedge *pb = (edge *)b;\n\tif ((*pa).s>(*pb).s)\n\t\treturn 1;\n\tif ((*pa).s<(*pb).s)\n\t\treturn -1;\n\tif ((*pa).t<=(*pb).t)\n\t\treturn 1;\n\treturn -1;\n}\n\nvoid prepava(optim *opt){\n  unsigned u,v;\n  unsigned *newlabel=(unsigned*)malloc(opt->n*sizeof(unsigned));\n  qsort(opt->nodes,opt->n,sizeof(node),compare_nodes);\n\n  for (unsigned i=0;i<opt->n;i++){\n    newlabel[opt->nodes[i].n]=i;\n  }\n  for (unsigned i=0;i<opt->e;i++){\n\t\tu=newlabel[opt->edges[i].s];\n\t\tv=newlabel[opt->edges[i].t];\n\t\tif (u<v){\n\t\t\topt->edges[i].s=u;\n\t\t\topt->edges[i].t=v;\n\t\t}\n\t\telse {\n\t\t\topt->edges[i].s=v;\n\t\t\topt->edges[i].t=u;\n\t\t\topt->edges[i].a=1-opt->edges[i].a;\n\t\t}\n\t}\n  //free(newlabel);\n  qsort(opt->edges,opt->e,sizeof(edge),compare_edges);\n\n\topt->cd=(unsigned*)calloc((opt->n+1),sizeof(unsigned));\n\tfor (unsigned i=0;i<opt->e;i++){\n\t\topt->cd[opt->edges[i].s+1]++;\n\t}\n\tfor (unsigned i=0;i<opt->n;i++){\n\t\topt->cd[i+1]+=opt->cd[i];\n\t}\n\n  opt->ne=(double*)calloc(opt->n,sizeof(double));\n  for (unsigned i=0;i<opt->e;i++){\n    u=opt->edges[i].s;\n    v=opt->edges[i].t;\n    opt->ne[(u>v)?u:v]++;\n  }\n}\n\n\n//to print in file the value for each node\nvoid print_rates(optim* opt,char* rates){\n\tFILE *file=fopen(rates,\"w\");\n\tunsigned i;\n\tfor (i=0;i<opt->n;i++){\n\t\tfprintf(file,\"%u %e\\n\",opt->map[opt->nodes[i].n],opt->nodes[i].r);\n\t}\n\tfclose(file);\n}\n\n\n//fit data structure:\ntypedef struct {\n\tunsigned n;//total number of aggregated points\n\tunsigned *nag;//nag[i]=number of points aggregated in i\n\tdouble *val;//val[i]=value of the aggregated points\n} isoreg;\n\n//Pool Adjacent Violators Algorithm. Values to fit in vect and size of vect.\nisoreg *pava(double *vect,unsigned n){\n\tisoreg *fit=(isoreg*)malloc(sizeof(isoreg));\n\tunsigned *nag=(unsigned*)malloc(n*sizeof(unsigned));\n\tdouble *val=(double*)malloc(n*sizeof(double));\n\tunsigned i,j;\n\n\tnag[0]=1;\n\tval[0]=vect[0];\n\tj=0;\n\tfor (i=1;i<n;i++){\n\t\tj+=1;\n\t\tval[j]=vect[i];\n\t\tnag[j]=1;\n\t\twhile ((j>0) && (val[j]>val[j-1]-1e-10)){//do val[j]>val[j-1] to have a non-increasing monotonic regression.\n\t\t\tval[j-1]=(nag[j]*val[j]+nag[j-1]*val[j-1])/(nag[j]+nag[j-1]);\n\t\t\tnag[j-1]+=nag[j];\n\t\t\tj--;\n\t\t}\n\t}\n\tfit->n=j+1;\n\tfit->nag=nag;\n\tfit->val=val;\n\treturn fit;\n}\n\n//printing the result in file output: \"nag val\" on each line\nvoid print_fit(isoreg *fit,char* output){\n\tFILE *file=fopen(output,\"w\");\n\tfor (unsigned i=0;i<fit->n;i++){\n\t\tfprintf(file,\"%u %.10le\\n\",fit->nag[i],fit->val[i]);\n\t}\n\tfclose(file);\n}\n\nvoid freeisoreg(isoreg *fit){\n\tfree(fit->nag);\n\tfree(fit->val);\n\tfree(fit);\n}\n\n//Step 3: Checking if the cuts given by PAVA are correct\n\n//printing the result in file output: \"nag val\" on each line\nisoreg* mkcut(isoreg* fit, optim *opt){\n\tunsigned j1,j2,ncuts=0;\n\tdouble *r=(double*)malloc(opt->n*sizeof(double));\n\tdouble *r2=(double*)malloc(opt->n*sizeof(double));\n\tdouble min, max;\n\tedge ed;\n\tunsigned *d=(unsigned*)calloc(opt->n,sizeof(unsigned));\n\tunsigned *d2=(unsigned*)malloc(opt->n*sizeof(unsigned));\n\tisoreg *fit2=(isoreg*)malloc(sizeof(isoreg));\n\tfit2->nag=(unsigned*)calloc(opt->n,sizeof(unsigned));\n\tfit2->val=(double*)calloc(opt->n,sizeof(double));\n\tfit2->n=0;\n\n\topt->cuts=(unsigned*)malloc(opt->n*sizeof(unsigned));\n\n\tfor (unsigned k=0;k<opt->n;k++){\n\t\tr[k]=opt->nodes[k].r;\n\t\tr2[k]=r[k];\n\t}\n\n\tj1=0;\n\tj2=0;\n\tfor (unsigned i=0;i<fit->n;i++){\n\t\tfit2->nag[ncuts]+=fit->nag[i];\n\t\tfit2->val[ncuts]+=fit->nag[i]*fit->val[i];\n\t\tj2+=fit->nag[i];\n\t\tfor (unsigned u=j1;u<j2;u++){\n\t\t\td2[u]=0;\n\t\t\tfor (unsigned k=opt->cd[u]+d[u];k<opt->cd[u+1];k++){\n\t\t\t\ted=opt->edges[k];\n\t\t\t\tif (ed.t>=j2){\n\t\t\t\t\tr2[u]-=ed.a;\n\t\t\t\t\tr2[ed.t]+=ed.a;\n\t\t\t\t\td2[u]++;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tmin=opt->nodes[0].r;\n\t\tfor (unsigned k=j1;k<j2;k++){\n\t\t\tmin=(min<r2[k])?min:r2[k];\n\t\t}\n\t\tmax=0;\n\t\tfor (unsigned k=j2;k<opt->n;k++){\n\t\t\tmax=(max>r2[k])?max:r2[k];\n\t\t}\n\t\tif (max<min){\n\t\t\tfor (unsigned k=j1;k<j2;k++){\n\t\t\t\topt->cuts[k]=ncuts;\n\t\t\t}\n\t\t\tfit2->val[ncuts]/=fit2->nag[ncuts];\n\t\t\tfor (unsigned u=j1;u<j2;u++){\n\t\t\t\td[u]+=d2[u];\n\t\t\t}\n\t\t\tfor (unsigned k=j1;k<opt->n;k++){///////////\n\t\t\t\tr[k]=r2[k];\n\t\t\t}\n\t\t\tncuts++;\n\t\t\tj1=j2;\n\t\t}\n\t\telse{\n\t\t\tfor (unsigned k=j1;k<opt->n;k++){///////////\n\t\t\t\tr2[k]=r[k];\n\t\t\t}\n\t\t}\n\t}\n\tfit2->n=ncuts;//+1;\n\treturn fit2;\n}\n\n//Step 4: Density-Friendly in each indepent subgraphs\n\ntypedef struct {\n\tunsigned s;\n\tunsigned t;\n} edge2;\n\ntypedef struct {\n\tunsigned n;//number of nodes\n\tunsigned e;//number of edges\n\tunsigned l;//number of loops\n\tedge2 *edges;//list of edges\n\tunsigned *loops;//loops[i]=number of loops of node i\n\tunsigned *deg;//deg[i]=degree of node i\n} subgraph;\n\nvoid freesubgraph(subgraph* sg){\n\tfree(sg->edges);\n\tfree(sg->loops);\n\tfree(sg->deg);\n\tfree(sg);\n}\n\nsubgraph **mkindep(optim* opt,unsigned *nsub){\n\t*nsub=opt->cuts[opt->n-1]+1;\n\tsubgraph **sgs=(subgraph**)malloc((*nsub)*sizeof(subgraph*));\n\tunsigned *newlabel=(unsigned*)malloc(opt->n*sizeof(unsigned));\n\tunsigned j,p,u,v,u2,v2;\n\tfor (unsigned k=0;k<*nsub;k++){\n\t\tsgs[k]=(subgraph*)malloc(sizeof(subgraph));\n\t\tsgs[k]->n=0;\n\t\tsgs[k]->e=0;\n\t\tsgs[k]->l=0;\n\t}\n\tj=0;\n\tfor (unsigned k=0;k<opt->n;k++){\n\t\tsgs[opt->cuts[k]]->n++;\n\t\tnewlabel[k]=j++;\n\t\tif ((k<opt->n-1) && (opt->cuts[k] != opt->cuts[k+1])){\n\t\t\tj=0;\n\t\t}\n\t}\n\tfor (unsigned k=0;k<opt->e;k++){\n\t\tu=opt->edges[k].s;\n\t\tv=opt->edges[k].t;\n\t\tp=opt->cuts[v];\n\t\tif (opt->cuts[u]==p){\n\t\t\tsgs[p]->e++;\n\t\t}\n\t}\n\tfor (unsigned k=0;k<*nsub;k++){\n\t\tsgs[k]->edges=(edge2*)malloc(sgs[k]->e*sizeof(edge2));\n\t\tsgs[k]->loops=(unsigned*)calloc(sgs[k]->n,sizeof(unsigned));\n\t\tsgs[k]->deg=(unsigned*)calloc(sgs[k]->n,sizeof(unsigned));\n\t\tsgs[k]->e=0;\n\t}\n\tfor (unsigned k=0;k<opt->e;k++){\n\t\tu=opt->edges[k].s;\n\t\tv=opt->edges[k].t;\n\t\tu2=newlabel[u];\n\t\tv2=newlabel[v];\n\t\tp=opt->cuts[v];\n\t\tif (opt->cuts[u]==p){\n\t\t\tsgs[p]->edges[sgs[p]->e].s=u2;\n\t\t\tsgs[p]->edges[sgs[p]->e++].t=v2;\n\t\t\tsgs[p]->deg[u2]++;\n\t\t\tsgs[p]->deg[v2]++;\n\t\t}\n\t\telse{\n\t\t\tsgs[p]->loops[v2]++;\n\t\t\tsgs[p]->l++;\n\t\t}\n\t}\n\treturn sgs;\n}\n\nsubgraph *allocsubgraph(unsigned n,unsigned e){\n\tsubgraph *sg=(subgraph*)malloc(sizeof(subgraph));\n\tsg->n=n;\n\tsg->e=0;\n\tsg->l=0;\n\tsg->deg=(unsigned*)calloc(n,sizeof(unsigned));\n\tsg->loops=(unsigned*)calloc(n,sizeof(unsigned));\n\tsg->edges=(edge2*)malloc(e*sizeof(edge2));\n\treturn sg;\n}\n\nusing namespace boost;\ntypedef adjacency_list_traits < vecS, vecS, directedS > Traits; //the associated types of the adjacency_list class\ntypedef adjacency_list < vecS, vecS, directedS,\n\t    property < vertex_name_t, unsigned,\n\t    property < vertex_index_t, long,\n\t    property < vertex_color_t, boost::default_color_type,\n\t    property < vertex_distance_t, double,///////////???\n\t    property < vertex_predecessor_t, Traits::edge_descriptor > > > > >,\n\t    property < edge_capacity_t, double,\n\t    property < edge_residual_capacity_t, double,\n\t    property < edge_reverse_t, Traits::edge_descriptor > > > > Graph; //the associated properties of the ajacency_list\n\nvoid AddEdge(Traits::vertex_descriptor &v1, Traits::vertex_descriptor &v2, property_map < Graph, edge_reverse_t >::type &rev, const double capacity, Graph &g) {\n  Traits::edge_descriptor e1 = add_edge(v1, v2, g).first;\n  Traits::edge_descriptor e2 = add_edge(v2, v1, g).first;\n  put(edge_capacity, g, e1, capacity);\n   rev[e1] = e2;\n   rev[e2] = e1;\n}\n\nvoid ReReadGraph(Traits::vertex_descriptor &s, Traits::vertex_descriptor &t, subgraph *sg, Graph &g) {\n\tgraph_traits<Graph>::vertex_descriptor u, v;\n\tproperty_map < Graph, edge_reverse_t >::type rev = get(edge_reverse, g);\n\tdouble alpha=(sg->e+sg->l)/((double)(sg->n))+1./(((double)sg->n)*((double)sg->n));\n\tdouble capacity1=2*alpha, capacity2, capacity3=1.;\n\tfor (unsigned i=0; i<sg->n; i++) {\n\t\tu=add_vertex(g);\n\t\tcapacity2=(sg->deg[i]+2.*sg->loops[i]);\n\t\tAddEdge(s,u, rev, capacity2, g);\n\t\tAddEdge(u,t, rev, capacity1, g);\n\t}\n\tfor(unsigned i=0; i<sg->e; i++){\n\t\tu=vertex(sg->edges[i].s+2,g);\n\t\tv=vertex(sg->edges[i].t+2,g);\n\t\tAddEdge(u,v,rev, capacity3, g);\n\t\tAddEdge(v,u,rev, capacity3, g);\n\t}\n}\n\nvoid maxflow(subgraph* sg,FILE *file) {\n\tTraits::vertex_descriptor s, t;\n\tGraph g;\n\tproperty_map < Graph, vertex_color_t >::type col = get(vertex_color, g);\n\ts=add_vertex(g);\n  t=add_vertex(g);\n\tReReadGraph(s, t, sg, g);\n\tdouble flow = boykov_kolmogorov_max_flow(g ,s, t);\n\t//std::cout << \"number of nodes: \" << sg->n << std::endl;\n\t//std::cout << \"number of edges: \" << sg->e << std::endl;\n\t//std::cout << \"number of loops: \" << sg->l << std::endl;\n\t//std::cout << \"flow: \" << flow << std::endl;\n\n\tbool *isin=(bool *)calloc(sg->n,sizeof(bool));\n\tunsigned n_nodes=0;\n\tfor(unsigned i=0;i<sg->n;i++){\n\t\tif (col[vertex(i+2,g)]==4){\n\t\t\tisin[i]=1;\n\t\t\tn_nodes++;\n\t\t\t//std::cout << i << \" \" << col[vertex(i+2,g)] << std::endl;\n\t\t}\n\t}\n\tg.clear();\n\tif (n_nodes>0){\n\t\tsubgraph *sg1=allocsubgraph(n_nodes,sg->e);\n\t\tsubgraph *sg2=allocsubgraph(sg->n-n_nodes,sg->e);\n\t\tunsigned *newlabel=(unsigned*)malloc(sg->n*sizeof(unsigned));\n\t\tunsigned j1=0,j2=0;\n\t\tfor(unsigned i=0;i<sg->n;i++){\n\t\t\tif (isin[i]){\n\t\t\t\tsg1->loops[j1]=sg->loops[i];\n\t\t\t\tsg1->l+=sg->loops[i];\n\t\t\t\tnewlabel[i]=j1++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tsg2->loops[j2]=sg->loops[i];\n\t\t\t\tsg2->l+=sg->loops[i];\n\t\t\t\tnewlabel[i]=j2++;\n\t\t\t}\n\t\t}\n\t\tj1=0,j2=0;\n\t\tfor(unsigned i=0;i<sg->e;i++){\n\t\t\tif (isin[sg->edges[i].s] && isin[sg->edges[i].t]){\n\t\t\t\tsg1->edges[j1].s=newlabel[sg->edges[i].s];\n\t\t\t\tsg1->edges[j1].t=newlabel[sg->edges[i].t];\n\t\t\t\tsg1->deg[sg1->edges[j1].s]++;\n\t\t\t\tsg1->deg[sg1->edges[j1].t]++;\n\t\t\t\tj1++;\n\t\t\t}\n\t\t\telse if (isin[sg->edges[i].s] && (isin[sg->edges[i].t]==0)){\n\t\t\t\tsg2->loops[newlabel[sg->edges[i].t]]++;\n\t\t\t\tsg2->l++;\n\t\t\t}\n\t\t\telse if ((isin[sg->edges[i].s]==0) && isin[sg->edges[i].t]){\n\t\t\t\tsg2->loops[newlabel[sg->edges[i].s]]++;\n\t\t\t\tsg2->l++;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tsg2->edges[j2].s=newlabel[sg->edges[i].s];\n\t\t\t\tsg2->edges[j2].t=newlabel[sg->edges[i].t];\n\t\t\t\tsg2->deg[sg2->edges[j2].s]++;\n\t\t\t\tsg2->deg[sg2->edges[j2].t]++;\n\t\t\t\tj2++;\n\t\t\t}\n\t\t}\n\t\tsg1->e=j1;\n\t\tsg2->e=j2;\n\t\tfree(isin);\n\t\tfreesubgraph(sg);\n\t\tmaxflow(sg1,file);\n\t\tmaxflow(sg2,file);\n\t}\n\telse {\n\t\t//<< \"n,e,d = \"\n\t\t#pragma omp critical\n\t\t{\n\t\t\tfprintf(file,\"%u %le\\n\",sg->n,((double)(sg->e+sg->l))/sg->n);\n\t\t\t//fprintf(file,\"%u %u %u %le\\n\",sg->n,sg->e,sg->l,((double)(sg->e+sg->l))/sg->n);\n\t\t\t//std::cout << sg->n << \" \" << sg->e << \" \" << sg->l << \" \" << ((double)(sg->e+sg->l))/sg->n << std::endl;\n\t\t}\n\t\tfree(isin);\n\t\tfreesubgraph(sg);\n\t}\n}\n\n\nint main(int argc,char** argv){\n\toptim* opt;\n  isoreg *fit,*fit2;\n\tsubgraph** sgs;\n\tunsigned nsgs;\n\tunsigned nthreads=atoi(argv[1]);\n\tunsigned rep=atoi(argv[2]);\n  char* edgelist=argv[3];\n  char* rates=argv[4];\n  char* pavafit=argv[5];\n\tchar* cuts=argv[6];\n\tchar* exact=argv[7];\n\n  omp_set_num_threads(nthreads);\n\n\ttime_t t1,t2,t3;\n\tt1=time(NULL);\n\tprintf(\"- Reading edgelist from file %s\\n\",edgelist);\n\topt=readedgelist(edgelist);\n\tt2=time(NULL);\n\tprintf(\"- Time = %ldh%ldm%lds\\n\",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60));\n\tprintf(\"- Building the datastructure\\n\");\n\tt1=time(NULL);\n\trelabel(opt);\n\tt2=time(NULL);\n\tprintf(\"- Time = %ldh%ldm%lds\\n\",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60));\n\tprintf(\"- Building the datastructure\\n\");\n\tprintf(\"- Number of nodes = %u\\n\",opt->n);\n\tprintf(\"- Number of edges = %u\\n\",opt->e);\n\tprintf(\"- Computing the locally densest decomposition\\n\");\n\n  printf(\"- Step 1: Frank-Wolf gradiant descent (%u iterations)\\n\",rep);\n\tt1=time(NULL);\n\tinit(opt);\n\tfor (unsigned i=0;i<rep;i++){\n\t\t//printf(\"%u\\n\",i);\n\t\tonepass(opt);\n\t}\n\tt2=time(NULL);\n\tprintf(\"- Time = %ldh%ldm%lds\\n\",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60));\n  //print_alphas(opt,alphas);\n\n  printf(\"- Step 2: Isotonic regression with PAVA\\n\");\n\tt1=time(NULL);\n  prepava(opt);\n  fit=pava(opt->ne,opt->n);\n\tt2=time(NULL);\n\tprintf(\"- Time = %ldh%ldm%lds\\n\",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60));\n\t\n  print_fit(fit,pavafit);\n  print_rates(opt,rates);\n\n  printf(\"- Step 3: Checking if the %u cuts given by PAVA are correct\\n\",fit->n);\n\tt1=time(NULL);\n\tfit2=mkcut(fit,opt);\n\tfreeisoreg(fit);\n  print_fit(fit2,cuts);\n\tt2=time(NULL);\n\tprintf(\"- Time = %ldh%ldm%lds\\n\",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60));\n\n  printf(\"- Step 4: Density-Friendly in each %u indepent subgraphs\\n\",fit2->n-1);\n\tfreeisoreg(fit2);\n\tt1=time(NULL);\n\tsgs=mkindep(opt,&nsgs);\n\tfreeoptim(opt);\n\tFILE *file=fopen(exact,\"w\");\n\tunsigned k;\n\t#pragma omp parallel for schedule(dynamic) private(k)\n\tfor(k=0;k<nsgs;k++){\n\t\tmaxflow(sgs[k],file);\n\t}\n\tfclose(file);\n\tt2=time(NULL);\n\tprintf(\"- Time = %ldh%ldm%lds\\n\",(t2-t1)/3600,((t2-t1)%3600)/60,((t2-t1)%60));\n\n\treturn 0;\n}\n", "meta": {"hexsha": "3c75152e048796cc1b711d96e52c651fee2cb128", "size": 17843, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exactDF.cpp", "max_stars_repo_name": "maxdan94/Density-Friendly", "max_stars_repo_head_hexsha": "61556df60665e72b2f0254c92f5f52a8f7ae96a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-05-24T16:33:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-25T20:05:14.000Z", "max_issues_repo_path": "exactDF.cpp", "max_issues_repo_name": "maxdan94/Density-Friendly", "max_issues_repo_head_hexsha": "61556df60665e72b2f0254c92f5f52a8f7ae96a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exactDF.cpp", "max_forks_repo_name": "maxdan94/Density-Friendly", "max_forks_repo_head_hexsha": "61556df60665e72b2f0254c92f5f52a8f7ae96a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-02T01:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T01:28:28.000Z", "avg_line_length": 26.5126300149, "max_line_length": 165, "alphanum_fraction": 0.6242223841, "num_tokens": 6099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4202624900653335}}
{"text": "/*\n * poh_color_bfs.hpp\n * Author: Aven Bross\n * \n * Implementation of Poh path 3-coloring algorithm for triangulated plane graphs\n * that uses a breadth first search to find chordless paths.\n */\n\n#ifndef __POH_COLOR_BFS_HPP\n#define __POH_COLOR_BFS_HPP\n\n// STL headers\n#include <vector>\n#include <queue>\n#include <stdexcept>\n#include <utility>\n#include <string>\n\n// Basic graph headers\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n\n// Local project headers\n#include \"incidence_list_helpers.hpp\"\n\n\n/*\n * poh_color_bfs_recursive\n * \n * inputs: A weakly triangulated planar graph with vertex indices (predfined\n *     boost property), a valid planar embedding of the graph modeling the boost\n *     PlanarEmbedding concept, a read-write-able vertex property map to store\n *     vertex colors, a read-write-able vertex property map to store integer\n *     marks for BFS, a read-write-able vertex property map to store the parent\n *     vertex for backtracking after the BFS, the first and last vertex of two\n *     disjoint colored paths P=p_0...p_n and Q=q_0...q_m such that p_0...p_nq_m\n *     ...q_0 is a cycle, an unsigned int count such that all vertex marks\n *     assigned so far are less than count, and finally the third color that has\n *     not been used on the paths P and Q.\n *\n * output: The coloring vertex property will contain a valid path 3-coloring of\n *     the subgraph bounded by p_0...p_nq_m...q_0 such that no interior vertex\n *     shares a color with a neighbor in P or Q.\n */\n\nnamespace {\n    template<\n            typename graph_t,\n            typename planar_embedding_t,\n            typename color_map_t,\n            typename mark_map_t,\n            typename parent_map_t,\n            typename color_t,\n            typename vertex_t\n                = typename boost::graph_traits<graph_t>::vertex_descriptor\n        >\n    void poh_color_bfs_recursive(\n            const graph_t & graph,\n            const planar_embedding_t & planar_embedding,\n            color_map_t & color_map,\n            mark_map_t & mark_map,\n            parent_map_t & parent_map,\n            vertex_t p_0, vertex_t p_n, vertex_t q_0,\n            vertex_t q_m, std::size_t count, color_t new_color\n        )\n    {\n        color_t p_color = color_map[p_0], q_color = color_map[q_0];\n        vertex_t t_0 = p_0, t_l = p_n;\n    \n        // Remove triangles from the end until we find an interior vertex t_l\n        do {\n            if(p_0 == p_n && q_0 == q_m) return;\n        \n            // Find the edge between p_n and q_m in q_m's incidence list\n            auto edge_iter = find_edge_iterator(\n                    q_m, p_n, planar_embedding, graph\n                );\n        \n            // Find the neighbor t_l counterclockwise from p_n around q_m\n            if(edge_iter == planar_embedding[q_m].end()) {\n                throw std::runtime_error(\"No edge between p_n and q_m).\");\n            }\n            else if(++edge_iter == planar_embedding[q_m].end()) {\n                t_l = get_incident_vertex(\n                        q_m, *planar_embedding[q_m].begin(), graph\n                    );\n            }\n            else {\n                t_l = get_incident_vertex(q_m, *edge_iter, graph);\n            }\n        \n            // If t_l is in P or Q we have found a colored face and remove it\n            if(color_map[t_l] == p_color) {\n                p_n = t_l;\n            }\n            else if(color_map[t_l] == q_color) {\n                q_m = t_l;\n            }\n        } while(color_map[t_l] == p_color || color_map[t_l] == q_color);\n    \n        vertex_t current_vertex, p_i = p_0, q_j = q_0;\n    \n        // Perform a BFS from t_l to find and color a path T between P and Q\n        {\n            std::queue<vertex_t> bfs_queue;\n            std::size_t bfs_mark = count++;\n            bfs_queue.push(t_l);\n            mark_map[t_l] = bfs_mark;\n            parent_map[t_l] = t_l;\n    \n            while(t_0 == p_0 && !bfs_queue.empty()) {\n                current_vertex = bfs_queue.front();\n                bfs_queue.pop();\n        \n                auto edge_iter = planar_embedding[current_vertex].begin();\n                vertex_t last_neighbor = get_incident_vertex(\n                        current_vertex, *edge_iter, graph\n                    );\n            \n                // Loop through the neighbors of current_vertex\n                do {\n                    // If we hit the end of the list, wrap to the start\n                    if(++edge_iter == planar_embedding[current_vertex].end())\n                        edge_iter = planar_embedding[current_vertex].begin();\n                \n                    vertex_t neighbor = get_incident_vertex(\n                            current_vertex, *edge_iter, graph\n                        );\n                \n                    std::size_t mark = mark_map[neighbor];\n                    color_t color = color_map[neighbor];\n                    color_t last_color = color_map[last_neighbor];\n                \n                    // If we hit an unmarked vertex, add it to the queue\n                    if(\n                            mark != bfs_mark && color != p_color &&\n                            color != q_color\n                        )\n                    {\n                        parent_map[neighbor] = current_vertex;\n                        mark_map[neighbor] = bfs_mark;\n                        bfs_queue.push(neighbor);\n                    }\n                    // If we find an edge P to Q, we have completed T\n                    else if(color == q_color && last_color == p_color) {\n                        t_0 = current_vertex;\n                        p_i = last_neighbor;\n                        q_j = neighbor;\n                    \n                        break;\n                    }\n                \n                    last_neighbor = neighbor;\n                } while(edge_iter != planar_embedding[current_vertex].begin());\n            }\n        \n            if(t_0 == p_0) {\n                throw std::runtime_error(\n                        \"BFS failed to find edge between paths.\"\n                    );\n            }\n        }\n        \n        // If the edge p_iq_j is a chord we must color the rest\n        if(p_i != p_0 || q_j != q_0) {\n            poh_color_bfs_recursive(\n                    graph, planar_embedding, color_map, mark_map, parent_map,\n                    p_0, p_i, q_0, q_j, count, new_color\n                );\n        }\n    \n        color_map[current_vertex] = new_color;\n    \n        // Backtrack through BFS tree from t_0 to color the path T\n        while(parent_map[current_vertex] != current_vertex) {\n            current_vertex = parent_map[current_vertex];\n            color_map[current_vertex] = new_color;\n        }\n    \n        // Color the subgraph bounded by p_i...p_n and T\n        poh_color_bfs_recursive(\n                graph, planar_embedding, color_map, mark_map, parent_map,\n                p_i, p_n, t_0, t_l, count, q_color\n            );\n    \n        // Color the subgraph bounded by T and q_m...q_j\n        poh_color_bfs_recursive(\n                graph, planar_embedding, color_map, mark_map, parent_map,\n                q_m, q_j, t_l, t_0, count, p_color\n            );\n    }\n}\n\n\n/*\n * poh_color_bfs\n * \n * inputs: A weakly triangulated planar graph with vertex indices (predfined\n *     boost property), a valid planar embedding of the graph modeling the boost\n *     PlanarEmbedding concept, a read-write-able vertex property map to store\n *     vertex colors, pairs of bidirectional iterators for lists of vertices\n *     of two disjoint colored paths P=p_0...p_n and Q=q_0...q_m such that\n *     p_0...p_nq_m...q_0 is a cycle, and three colors for the path 3-coloring\n *     (no vertex should be assigned any of these three colors before calling\n *     this function).\n *\n * output: The coloring vertex property will contain a valid path 3-coloring of\n *     the subgraph bounded by p_0...p_nq_m...q_0 such that vertices in P are\n *     recieve the first color, vertices in Q the second color, and no interior\n *     vertex shares a color with a neighbor in P or Q.\n */\n\ntemplate<\n        typename graph_t,\n        typename planar_embedding_t,\n        typename color_map_t,\n        typename mark_map_t,\n        typename parent_map_t,\n        typename vertex_iterator_t,\n        typename color_t\n    >\nvoid poh_color_bfs(\n        const graph_t & graph,\n        const planar_embedding_t & planar_embedding,\n        vertex_iterator_t p_begin, vertex_iterator_t p_end,\n        vertex_iterator_t q_begin, vertex_iterator_t q_end,\n        color_t c_0, color_t c_1, color_t c_2,\n        mark_map_t & mark_map,\n        parent_map_t & parent_map,\n        color_map_t & color_map\n    )\n{ \n    // Color the path P\n    for(vertex_iterator_t p_iter = p_begin; p_iter != p_end; ++p_iter) {\n        color_map[*p_iter] = c_0;\n    }\n    \n    // Color the path Q\n    for(vertex_iterator_t q_iter = q_begin; q_iter != q_end; ++q_iter) {\n        color_map[*q_iter] = c_1;\n    }\n    \n    // Construct the path 3-coloring\n    poh_color_bfs_recursive(\n            graph, planar_embedding, color_map, mark_map, parent_map,\n            *p_begin, *(--p_end), *q_begin, *(--q_end), 1, c_2\n        );\n}\n\n\n/*\n * A wrapper that automatically constructs fast property maps for the parent_map\n * and neighbor_range_map, but requires that graph_t is some definition of\n * boost::adjacency_list.\n */\n\ntemplate<\n        typename graph_t,\n        typename planar_embedding_t,\n        typename vertex_iterator_t,\n        typename color_t,\n        typename color_map_t\n    >\nvoid poh_color_bfs(\n        const graph_t & graph,\n        const planar_embedding_t & planar_embedding,\n        vertex_iterator_t p_begin, vertex_iterator_t p_end,\n        vertex_iterator_t q_begin, vertex_iterator_t q_end,\n        color_t c_0, color_t c_1, color_t c_2,\n        color_map_t & color_map\n    )\n{\n    // Vertex type\n    typedef typename boost::graph_traits<graph_t>::vertex_descriptor vertex_t;\n    \n    // Vertex property map to store vertex marks\n    typedef boost::iterator_property_map<\n            std::vector<int>::iterator,\n            typename boost::property_map<\n                    graph_t, boost::vertex_index_t\n                >::const_type\n        > integer_property_map_t;\n    \n    // Vertex property map to store BFS tree\n    typedef boost::iterator_property_map<\n            typename std::vector<vertex_t>::iterator, \n            typename boost::property_map<\n                    graph_t, boost::vertex_index_t\n                >::const_type\n        > parent_map_t;\n    \n    // Construct a vertex property map to store vertex marks\n    std::vector<int> mark_storage(num_vertices(graph));\n    integer_property_map_t mark_map(\n            mark_storage.begin(), boost::get(boost::vertex_index, graph)\n        );\n    \n    // Construct a vertex property map to store neighbor ranges\n    std::vector<vertex_t> parent_storage(num_vertices(graph));\n    parent_map_t parent_map(\n            parent_storage.begin(), boost::get(boost::vertex_index, graph)\n        );\n    \n    // Construct the path 3-coloring\n    poh_color_bfs(\n            graph,\n            planar_embedding,\n            p_begin, p_end,\n            q_begin, q_end,\n            c_0, c_1, c_2,\n            mark_map,\n            parent_map,\n            color_map\n        );\n}\n\n#endif\n", "meta": {"hexsha": "05fa3308d1f12f382e6ce793201d283600199bda", "size": 11427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/path_coloring/poh_color_bfs.hpp", "max_stars_repo_name": "permutationlock/path_coloring_bgl", "max_stars_repo_head_hexsha": "ec8ca14faadfdf65f7dcab9aef5a91d82dc7d6d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/include/path_coloring/poh_color_bfs.hpp", "max_issues_repo_name": "permutationlock/path_coloring_bgl", "max_issues_repo_head_hexsha": "ec8ca14faadfdf65f7dcab9aef5a91d82dc7d6d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/path_coloring/poh_color_bfs.hpp", "max_forks_repo_name": "permutationlock/path_coloring_bgl", "max_forks_repo_head_hexsha": "ec8ca14faadfdf65f7dcab9aef5a91d82dc7d6d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8213166144, "max_line_length": 80, "alphanum_fraction": 0.5760042006, "num_tokens": 2590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178686187839, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4202624820288893}}
{"text": "// ======================================================================\n/*!\n * \\file NFmiWebMercatorArea.cpp\n * \\brief Implementation of class NFmiWebMercatorArea\n */\n// ======================================================================\n/*!\n * \\class NFmiWebMercatorArea\n *\n * Provides for equidistance cylindrical projection. Maps geodetic\n * coordinates (in degrees) to rectangular mercator xy coordinates\n * (in meters) and vice versa.\n *\n * Projection is based on EPSG:3857\n */\n// ======================================================================\n\n#include \"NFmiWebMercatorArea.h\"\n#include <boost/functional/hash.hpp>\n#include <fmt/format.h>\n#include <macgyver/Exception.h>\n#include <limits>\n\nusing namespace std;\n\nconst double kSemiAxis = 6378137.0;\n\n// ----------------------------------------------------------------------\n/*!\n * Default constructor\n */\n// ----------------------------------------------------------------------\n\nNFmiWebMercatorArea::NFmiWebMercatorArea()\n    : NFmiArea(),\n      itsBottomLeftLatLon(),\n      itsTopRightLatLon(),\n      itsXScaleFactor(),\n      itsYScaleFactor(),\n      itsWorldRect()\n{\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Constructor\n *\n * \\param theBottomLeftLatLon Undocumented\n * \\param theTopRightLatLon Undocumented\n * \\param theTopLeftXY Undocumented\n * \\param theBottomRightXY Undocumented\n */\n// ----------------------------------------------------------------------\n\nNFmiWebMercatorArea::NFmiWebMercatorArea(const NFmiPoint& theBottomLeftLatLon,\n                                         const NFmiPoint& theTopRightLatLon,\n                                         const NFmiPoint& theTopLeftXY,\n                                         const NFmiPoint& theBottomRightXY,\n                                         bool usePacificView)\n    : NFmiArea(theTopLeftXY, theBottomRightXY, usePacificView),\n      itsBottomLeftLatLon(theBottomLeftLatLon),\n      itsTopRightLatLon(theTopRightLatLon),\n      itsXScaleFactor(),\n      itsYScaleFactor(),\n      itsWorldRect()\n{\n  try\n  {\n    Init();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Copy constructor\n *\n * \\param theLatLonArea The other object being copied\n */\n// ----------------------------------------------------------------------\n\nNFmiWebMercatorArea::NFmiWebMercatorArea(const NFmiWebMercatorArea& theLatLonArea)\n\n    = default;\n\n// ----------------------------------------------------------------------\n/*!\n * \\return Undocumented\n * \\todo Should return an boost::shared_ptr instead\n */\n// ----------------------------------------------------------------------\n\nNFmiArea* NFmiWebMercatorArea::Clone() const\n{\n  try\n  {\n    return new NFmiWebMercatorArea(*this);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param fKeepWorldRect Undocumented\n */\n// ----------------------------------------------------------------------\n\nvoid NFmiWebMercatorArea::Init(bool fKeepWorldRect)\n{\n  try\n  {\n    if (itsTopRightLatLon.X() < itsBottomLeftLatLon.X())\n      itsTopRightLatLon += NFmiPoint(360., 0.);\n\n    if (!fKeepWorldRect)\n      itsWorldRect =\n          NFmiRect(LatLonToWorldXY(itsBottomLeftLatLon), LatLonToWorldXY(itsTopRightLatLon));\n\n    itsXScaleFactor = Width() / itsWorldRect.Width();\n    itsYScaleFactor = Height() / itsWorldRect.Height();\n\n    NFmiArea::Init(fKeepWorldRect);\n\n    const char* fmt = \"+proj=webmerc +R={}\";\n    itsProjStr = fmt::format(fmt, kRearth);\n    itsSpatialReference = std::make_shared<Fmi::SpatialReference>(itsProjStr);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theLatLonPoint Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiWebMercatorArea::LatLonToWorldXY(const NFmiPoint& theLatLonPoint) const\n{\n  try\n  {\n    // Limit Y-values to prevent infinity\n\n    double y = std::max(std::min(theLatLonPoint.Y(), 89.9999), -89.9999);\n\n    return NFmiPoint(kSemiAxis * FmiRad(theLatLonPoint.X()),\n                     kSemiAxis * log(tan(FmiRad(45. + 0.5 * y))));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theLatLonPoint Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiWebMercatorArea::ToXY(const NFmiPoint& theLatLonPoint) const\n{\n  try\n  {\n    // Transforms input geodetic coordinates (longitude,latitude) into local (relative)\n    // coordinates on xy-plane.\n    double xLocal, yLocal;\n\n    // Transform input geodetic coordinates into world coordinates (meters) on xy-plane.\n    NFmiPoint latlon(FixLongitude(theLatLonPoint.X()), theLatLonPoint.Y());\n    NFmiPoint xyWorld(LatLonToWorldXY(latlon));\n\n    // Finally, transform world xy-coordinates into local xy-coordinates\n    xLocal = Left() + itsXScaleFactor * (xyWorld.X() - itsWorldRect.Left());\n    yLocal = Top() + itsYScaleFactor * (itsWorldRect.Bottom() - xyWorld.Y());\n\n    return NFmiPoint(xLocal, yLocal);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theXYPoint Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiWebMercatorArea::WorldXYToLatLon(const NFmiPoint& theXYPoint) const\n{\n  try\n  {\n    // Computes the geodetic coordinates (in degrees) from the input (metric) world xy coordinates\n\n    double worldY = theXYPoint.Y();\n    double lon = NFmiLongitude(FmiDeg(theXYPoint.X() / kSemiAxis), PacificView()).Value();\n    double lat = FmiDeg(2.0 * atan(exp(worldY / kSemiAxis)) - 0.5 * kPii);\n\n    return NFmiPoint(lon, lat);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theXYPoint Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiWebMercatorArea::XYToWorldXY(const NFmiPoint& theXYPoint) const\n{\n  try\n  {\n    // Transform local xy-coordinates into world xy-coordinates (meters).\n    double xWorld = itsWorldRect.Left() + (theXYPoint.X() - Left()) / itsXScaleFactor;\n    double yWorld = itsWorldRect.Bottom() - (theXYPoint.Y() - Top()) / itsYScaleFactor;\n    return NFmiPoint(xWorld, yWorld);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theXYPoint Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiWebMercatorArea::WorldXYToXY(const NFmiPoint& theWorldXYPoint) const\n{\n  try\n  {\n    double x = itsXScaleFactor * (theWorldXYPoint.X() - itsWorldRect.Left()) + Left();\n    double y = Top() - itsYScaleFactor * (theWorldXYPoint.Y() - itsWorldRect.Bottom());\n    return NFmiPoint(x, y);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theXYPoint Undocumented\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\nconst NFmiPoint NFmiWebMercatorArea::ToLatLon(const NFmiPoint& theXYPoint) const\n{\n  try\n  {\n    // Transforms input local xy-coordinates into geodetic coordinates\n    // (longitude,latitude) on globe.\n    return WorldXYToLatLon(XYToWorldXY(theXYPoint));\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiWebMercatorArea::XScale() const\n{\n  try\n  {\n    return 1. / itsXScaleFactor;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\return Undocumented\n */\n// ----------------------------------------------------------------------\n\ndouble NFmiWebMercatorArea::YScale() const\n{\n  try\n  {\n    return 1. / itsYScaleFactor;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\param theBottomLeftLatLon Undocumented\n * \\param theTopRightLatLon Undocumented\n * \\return Undocumented\n * \\todo Should return an boost::shared_ptr instead\n */\n// ----------------------------------------------------------------------\n\nNFmiArea* NFmiWebMercatorArea::NewArea(const NFmiPoint& theBottomLeftLatLon,\n                                       const NFmiPoint& theTopRightLatLon,\n                                       bool allowPacificFix) const\n{\n  try\n  {\n    if (allowPacificFix)\n    {\n      PacificPointFixerData fixedPointData =\n          NFmiArea::PacificPointFixer(theBottomLeftLatLon, theTopRightLatLon);\n      return new NFmiWebMercatorArea(fixedPointData.itsBottomLeftLatlon,\n                                     fixedPointData.itsTopRightLatlon,\n                                     TopLeft(),\n                                     BottomRight(),\n                                     fixedPointData.fIsPacific);\n    }\n\n    return new NFmiWebMercatorArea(\n        theBottomLeftLatLon, theTopRightLatLon, TopLeft(), BottomRight(), PacificView());\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Write the object to the given output stream\n *\n * \\param file The output stream to write to\n * \\return The output stream written to\n */\n// ----------------------------------------------------------------------\n\nstd::ostream& NFmiWebMercatorArea::Write(std::ostream& file) const\n{\n  try\n  {\n    NFmiArea::Write(file);\n    file << itsBottomLeftLatLon;\n    file << itsTopRightLatLon;\n\n    // Dummies to replace old removed variables\n    file << \"0 0\\n0 0\\n\";\n\n    file << itsXScaleFactor << \" \";\n    file << itsYScaleFactor << std::endl;\n    return file;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Read new object contents from the given input stream\n *\n * \\param file The input stream to read from\n * \\return The input stream read from\n */\n// ----------------------------------------------------------------------\n\nstd::istream& NFmiWebMercatorArea::Read(std::istream& file)\n{\n  try\n  {\n    double dummy;\n\n    NFmiArea::Read(file);\n    file >> itsBottomLeftLatLon;\n    file >> itsTopRightLatLon;\n    PacificView(NFmiArea::IsPacificView(itsBottomLeftLatLon, itsTopRightLatLon));\n\n    file >> dummy >> dummy >> dummy >> dummy;  // old removed variables\n\n    file >> itsXScaleFactor;\n    file >> itsYScaleFactor;\n\n    itsWorldRect =\n        NFmiRect(LatLonToWorldXY(itsBottomLeftLatLon), LatLonToWorldXY(itsTopRightLatLon));\n\n    Init();\n\n    return file;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nconst std::string NFmiWebMercatorArea::AreaStr() const\n{\n  try\n  {\n    std::ostringstream out;\n    out << \"webmercator:\" << BottomLeftLatLon().X() << ',' << BottomLeftLatLon().Y() << ','\n        << TopRightLatLon().X() << ',' << TopRightLatLon().Y();\n    return out.str();\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Return Well Known Text representation of the GCS\n *\n * We shall return EPSG:3857, but may have to return the following if using the plain\n * EPSG does not work for all software\n *\n * PROJCS[\"WGS 84 / Pseudo-Mercator\",\n *    GEOGCS[\"WGS 84\",\n *        DATUM[\"WGS_1984\",\n *            SPHEROID[\"WGS 84\",6378137,298.257223563,\n *                AUTHORITY[\"EPSG\",\"7030\"]],\n *            AUTHORITY[\"EPSG\",\"6326\"]],\n *        PRIMEM[\"Greenwich\",0,\n *            AUTHORITY[\"EPSG\",\"8901\"]],\n *        UNIT[\"degree\",0.0174532925199433,\n *            AUTHORITY[\"EPSG\",\"9122\"]],\n *        AUTHORITY[\"EPSG\",\"4326\"]],\n *    PROJECTION[\"Mercator_1SP\"],\n *    PARAMETER[\"central_meridian\",0],\n *    PARAMETER[\"scale_factor\",1],\n *    PARAMETER[\"false_easting\",0],\n *    PARAMETER[\"false_northing\",0],\n *    UNIT[\"metre\",1,\n *        AUTHORITY[\"EPSG\",\"9001\"]],\n *    AXIS[\"X\",EAST],\n *    AXIS[\"Y\",NORTH],\n *    EXTENSION[\"PROJ4\",\"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0\n * +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs\"], AUTHORITY[\"EPSG\",\"3857\"]]\n *\n */\n// ----------------------------------------------------------------------\n\nconst std::string NFmiWebMercatorArea::WKT() const\n{\n  return \"EPSG:3857\";\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Equality comparison with an NFmiWebMercatorArea.\n *\n * \\param theArea The other area being compared to\n * \\return True, if the NFmiWebMercatorArea parts are equivalent\n * \\todo Use static_cast instead of C-style cast\n */\n// ----------------------------------------------------------------------\n\nbool NFmiWebMercatorArea::operator==(const NFmiArea& theArea) const\n{\n  try\n  {\n    return *this == static_cast<const NFmiWebMercatorArea&>(theArea);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * Equality comparison\n *\n * \\param theArea The other area being compared to\n * \\return True, if the areas are equivalent\n * \\todo Investigate whether NFmiArea::operator== should also be called.\n */\n// ----------------------------------------------------------------------\n\nbool NFmiWebMercatorArea::operator==(const NFmiWebMercatorArea& theArea) const\n{\n  try\n  {\n    if ((itsBottomLeftLatLon == theArea.itsBottomLeftLatLon) &&\n        (itsTopRightLatLon == theArea.itsTopRightLatLon) &&\n        (itsXScaleFactor == theArea.itsXScaleFactor) &&\n        (itsYScaleFactor == theArea.itsYScaleFactor) && (itsWorldRect == theArea.itsWorldRect))\n      return true;\n\n    return false;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ----------------------------------------------------------------------\n/*!\n * \\brief Hash value\n */\n// ----------------------------------------------------------------------\n\nstd::size_t NFmiWebMercatorArea::HashValue() const\n{\n  try\n  {\n    std::size_t hash = NFmiArea::HashValue();\n    boost::hash_combine(hash, itsBottomLeftLatLon.HashValue());\n    boost::hash_combine(hash, itsTopRightLatLon.HashValue());\n    boost::hash_combine(hash, boost::hash_value(itsXScaleFactor));\n    boost::hash_combine(hash, boost::hash_value(itsYScaleFactor));\n    boost::hash_combine(hash, itsWorldRect.HashValue());\n    return hash;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n// ======================================================================\n", "meta": {"hexsha": "7817109668fbae3af53cd64faf2f6d19807fed4f", "size": 15634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "newbase/NFmiWebMercatorArea.cpp", "max_stars_repo_name": "fmidev/smartmet-library-newbase", "max_stars_repo_head_hexsha": "12d93660c06e3c66a039ea75530bd9ca5daf7ab8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "newbase/NFmiWebMercatorArea.cpp", "max_issues_repo_name": "fmidev/smartmet-library-newbase", "max_issues_repo_head_hexsha": "12d93660c06e3c66a039ea75530bd9ca5daf7ab8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2017-01-17T10:46:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-21T07:50:17.000Z", "max_forks_repo_path": "newbase/NFmiWebMercatorArea.cpp", "max_forks_repo_name": "fmidev/smartmet-library-newbase", "max_forks_repo_head_hexsha": "12d93660c06e3c66a039ea75530bd9ca5daf7ab8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-01-17T07:33:28.000Z", "max_forks_repo_forks_event_max_datetime": "2018-04-26T07:10:23.000Z", "avg_line_length": 28.3738656987, "max_line_length": 98, "alphanum_fraction": 0.5144556735, "num_tokens": 3568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.4202173876200337}}
{"text": "// Copyright (c) 2021 George E. Brown and Rahul Narain\n//\n// WRAPD uses the MIT License (https://opensource.org/licenses/MIT)\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is furnished\n// to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n// By George E. Brown (https://www-users.cse.umn.edu/~brow2327/)\n\n#ifndef SRC_MATH_HPP_\n#define SRC_MATH_HPP_\n\n#include <Eigen/SparseCholesky>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/IterativeLinearSolvers>\n\n#include <iostream>\n#include <memory>\n#include <string>\n#include <vector>\n\nnamespace wrapd {\nnamespace math {\n\nusing VecX = Eigen::VectorXd;\nusing VecXi = Eigen::VectorXi;\nusing MatX = Eigen::MatrixXd;\nusing MatXi = Eigen::MatrixXi;\nusing MatX2 = Eigen::MatrixX2d;\nusing Mat2X = Eigen::Matrix2Xd;\nusing SpMat = Eigen::SparseMatrix<double, Eigen::RowMajor>;\nusing DiagMat = Eigen::DiagonalMatrix<double, Eigen::Dynamic>;\nusing RowVec3 = Eigen::RowVector3d;\n\nusing Triplet = Eigen::Triplet<double>;\nusing Triplets = std::vector<Triplet>;\n\nusing Doubles = std::vector<double>;\n\nusing Cholesky = Eigen::SimplicialLDLT< Eigen::SparseMatrix<double>, Eigen::Lower>;\n\nusing AlignedBox = Eigen::AlignedBox<double, 3>;\n\n// Singular value decomposition\ntemplate <typename TYPE>\nusing JacobiSVD = Eigen::JacobiSVD<TYPE>;\nstatic constexpr int ComputeFullU = Eigen::ComputeFullU;\nstatic constexpr int ComputeFullV = Eigen::ComputeFullV;\n\n// Mapping between vectors and matrices\ntemplate <typename TYPE>\nusing Map = Eigen::Map<TYPE>;\n\n// Vectors of doubles\ntemplate <int DIM>\nusing Vec = Eigen::Matrix<double, DIM, 1>;\nusing Vec2 = Vec<2>;\nusing Vec3 = Vec<3>;\nusing Vec4 = Vec<4>;\n\n// Vectors of floats\ntemplate <int DIM>\nusing Vecf = Eigen::Matrix<float, DIM, 1>;\nusing Vec2f = Vecf<2>;\nusing Vec3f = Vecf<3>;\nusing Vec4f = Vecf<4>;\n\n// Vectors of integers\ntemplate <int DIM>\nusing Veci = Eigen::Matrix<int, DIM, 1>;\nusing Vec1i = Veci<1>;\nusing Vec2i = Veci<2>;\nusing Vec3i = Veci<3>;\nusing Vec4i = Veci<4>;\n\ntemplate <int ROWS, int COLS>\nusing Mat = Eigen::Matrix<double, ROWS, COLS>;\n\nusing Mat1x3 = Mat<1, 3>;\nusing Mat2x2 = Mat<2, 2>;\nusing Mat2x3 = Mat<2, 3>;\nusing Mat3x2 = Mat<3, 2>;\nusing Mat3x3 = Mat<3, 3>;\nusing Mat3x4 = Mat<3, 4>;\n\ninline double clamp(const double minval, const double val, const double maxval) {\n    double retval = val;\n    if (val < minval) {\n        retval = minval;\n    }\n    if (val > maxval) {\n        retval = maxval;\n    }\n    return retval;\n}\n\ninline void svd(\n        const math::Mat2x2& F,\n        math::Vec2& sigma,\n        math::Mat2x2& U,\n        math::Mat2x2& V,\n        bool prevent_flips = true) {\n    math::JacobiSVD<math::Mat2x2> svd(F, math::ComputeFullU | math::ComputeFullV);\n    sigma = svd.singularValues();\n    U = svd.matrixU();\n    V = svd.matrixV();\n\n    if (prevent_flips && (U*V.transpose()).determinant() < 0.) {\n        math::Mat2x2 J = math::Mat2x2::Identity();\n        J(1, 1) = -1.0;\n        if (U.determinant() < 0.) {\n            U = U * J;\n            sigma[1] = -sigma[1];\n        }\n        if (V.determinant() < 0.0) {\n            math::Mat2x2 Vt = V.transpose();\n            Vt = J * Vt;\n            V = Vt.transpose();\n            sigma[1] = -sigma[1];\n        }\n    }\n}\n\ninline void polar(\n        const math::Mat2x2& F,\n        math::Mat2x2& R,\n        math::Mat2x2& S,\n        bool prevent_flips = true) {\n    math::Vec2 sigma;\n    math::Mat2x2 U;\n    math::Mat2x2 V;\n    svd(F, sigma, U, V, prevent_flips);\n    R = U * V.transpose();\n    S = V * sigma.asDiagonal() * V.transpose();\n}\n\ninline math::Mat2x2 rot(const math::Mat2x2& A) {\n    math::Vec2 b(A(0, 0) + A(1, 1), A(0, 1) - A(1, 0));\n    b.normalize();\n    math::Mat2x2 R2;\n    R2(0, 0) = R2(1, 1) = b(0);\n    R2(0, 1) = b(1);\n    R2(1, 0) = -b(1);\n    return R2;\n}\n\ninline math::Mat2x2 sym(const math::Mat2x2& A) {\n    math::Mat2x2 R = rot(A);\n    return R.transpose() * A;\n}\n\n}  // namespace math\n} // namespace wrapd\n\n\n#endif  // SRC_MATH_HPP_", "meta": {"hexsha": "43a1c52c52c3608c0169ff0dfa93403443f90c1b", "size": 4917, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Math.hpp", "max_stars_repo_name": "georgbrown/wrapd-2d", "max_stars_repo_head_hexsha": "1f7d0659582297f97212c83c67dca81948ed70f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T23:11:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T06:18:26.000Z", "max_issues_repo_path": "src/Math.hpp", "max_issues_repo_name": "georgbrown/wrapd-2d", "max_issues_repo_head_hexsha": "1f7d0659582297f97212c83c67dca81948ed70f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math.hpp", "max_forks_repo_name": "georgbrown/wrapd-2d", "max_forks_repo_head_hexsha": "1f7d0659582297f97212c83c67dca81948ed70f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-07-28T02:36:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:27:26.000Z", "avg_line_length": 28.7543859649, "max_line_length": 86, "alphanum_fraction": 0.6591417531, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.42021195932279093}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>\n// \n// This Source Code Form is subject to the terms of the Mozilla Public License \n// v. 2.0. If a copy of the MPL was not distributed with this file, You can \n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"cotmatrix.h\"\n#include <vector>\n\n// For error printing\n#include <cstdio>\n#include \"cotmatrix_entries.h\"\n\n// Bug in unsupported/Eigen/SparseExtra needs iostream first\n#include <iostream>\n\ntemplate <typename DerivedV, typename DerivedF, typename Scalar>\nIGL_INLINE void igl::cotmatrix(\n  const Eigen::MatrixBase<DerivedV> & V, \n  const Eigen::MatrixBase<DerivedF> & F, \n  Eigen::SparseMatrix<Scalar>& L)\n{\n  using namespace Eigen;\n  using namespace std;\n\n  L.resize(V.rows(),V.rows());\n  Matrix<int,Dynamic,2> edges;\n  int simplex_size = F.cols();\n  // 3 for triangles, 4 for tets\n  assert(simplex_size == 3 || simplex_size == 4);\n  if(simplex_size == 3)\n  {\n    // This is important! it could decrease the comptuation time by a factor of 2\n    // Laplacian for a closed 2d manifold mesh will have on average 7 entries per\n    // row\n    L.reserve(10*V.rows());\n    edges.resize(3,2);\n    edges << \n      1,2,\n      2,0,\n      0,1;\n  }else if(simplex_size == 4)\n  {\n    L.reserve(17*V.rows());\n    edges.resize(6,2);\n    edges << \n      1,2,\n      2,0,\n      0,1,\n      3,0,\n      3,1,\n      3,2;\n  }else\n  {\n    return;\n  }\n  // Gather cotangents\n  Matrix<Scalar,Dynamic,Dynamic> C;\n  cotmatrix_entries(V,F,C);\n  \n  vector<Triplet<Scalar> > IJV;\n  IJV.reserve(F.rows()*edges.rows()*4);\n  // Loop over triangles\n  for(int i = 0; i < F.rows(); i++)\n  {\n    // loop over edges of element\n    for(int e = 0;e<edges.rows();e++)\n    {\n      int source = F(i,edges(e,0));\n      int dest = F(i,edges(e,1));\n      IJV.push_back(Triplet<Scalar>(source,dest,C(i,e)));\n      IJV.push_back(Triplet<Scalar>(dest,source,C(i,e)));\n      IJV.push_back(Triplet<Scalar>(source,source,-C(i,e)));\n      IJV.push_back(Triplet<Scalar>(dest,dest,-C(i,e)));\n    }\n  }\n  L.setFromTriplets(IJV.begin(),IJV.end());\n}\n\n#include \"massmatrix.h\"\n#include \"pinv.h\"\n#include \"cotmatrix_entries.h\"\n#include \"diag.h\"\n#include \"massmatrix.h\"\n#include <Eigen/Geometry>\n\ntemplate <\n  typename DerivedV, \n  typename DerivedI, \n  typename DerivedC, \n  typename Scalar>\nIGL_INLINE void igl::cotmatrix(\n  const Eigen::MatrixBase<DerivedV> & V, \n  const Eigen::MatrixBase<DerivedI> & I, \n  const Eigen::MatrixBase<DerivedC> & C, \n  Eigen::SparseMatrix<Scalar>& L,\n  Eigen::SparseMatrix<Scalar>& M,\n  Eigen::SparseMatrix<Scalar>& P)\n{\n  typedef Eigen::Matrix<Scalar,1,3> RowVector3S;\n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> MatrixXS;\n  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,1> VectorXS;\n  typedef Eigen::Index Index;\n  // number of vertices\n  const Index n = V.rows();\n  // number of polyfaces\n  const Index m = C.size()-1;\n  assert(V.cols() == 2 || V.cols() == 3);\n  std::vector<Eigen::Triplet<Scalar> > Lfijv;\n  std::vector<Eigen::Triplet<Scalar> > Mfijv;\n  std::vector<Eigen::Triplet<Scalar> > Pijv;\n  // loop over vertices; set identity for original vertices\n  for(Index i = 0;i<V.rows();i++) { Pijv.emplace_back(i,i,1); }\n  // loop over faces\n  for(Index p = 0;p<C.size()-1;p++)\n  {\n    // number of faces/vertices in this simple polygon\n    const Index np = C(p+1)-C(p);\n    // Working \"local\" list of vertices; last vertex is new one\n    // this needs to have 3 columns so Eigen doesn't complain about cross\n    // products below.\n    Eigen::Matrix<Scalar,Eigen::Dynamic,3> X = decltype(X)::Zero(np+1,3);\n    for(Index i = 0;i<np;i++){ X.row(i).head(V.cols()) = V.row(I(C(p)+i)); };\n    // determine weights definig position of inserted vertex\n    {\n      MatrixXS A = decltype(A)::Zero(np+1,np);\n      // My equation (38) would be A w = b.\n      VectorXS b = decltype(b)::Zero(np+1);\n      for(Index k = 0;k<np;k++)\n      { \n        const RowVector3S Xkp1mk = X.row((k+1)%np)-X.row(k);\n        const RowVector3S Xkp1mkck = Xkp1mk.cross(X.row(k));\n        for(Index i = 0;i<np;i++)\n        { \n          b(i) -= 2.*(X.row(i).cross(Xkp1mk)).dot(Xkp1mkck);\n          for(Index j = 0;j<np;j++)\n          { \n            A(i,j) += 2.*(X.row(j).cross(Xkp1mk)).dot(X.row(i).cross(Xkp1mk));\n          }\n        }\n      }\n      A.row(np).setConstant(1);\n      b(np) = 1;\n      const VectorXS w =\n        Eigen::CompleteOrthogonalDecomposition<Eigen::MatrixXd>(A).solve(b);\n      X.row(np) = w.transpose()*X.topRows(np);\n      // scatter w into new row of P\n      for(Index i = 0;i<np;i++) { Pijv.emplace_back(n+p,I(C(p)+i),w(i)); }\n    }\n    // \"local\" fan of faces. These could be statically cached, but this will\n    // not be the bottleneck.\n    Eigen::MatrixXi F(np,3);\n    for(Index i = 0;i<np;i++)\n    { \n      F(i,0) = i; \n      F(i,1) = (i+1)%np; \n      F(i,2) = np; \n    }\n    // Cotangent contributions\n    MatrixXS K;\n    igl::cotmatrix_entries(X,F,K);\n    // Massmatrix entried\n    VectorXS Mp;\n    {\n      Eigen::SparseMatrix<Scalar> M;\n      igl::massmatrix(X,F,igl::MASSMATRIX_TYPE_DEFAULT,M);\n      Mp = M.diagonal();\n    }\n    // Scatter into fine Laplacian and mass matrices\n    const auto J = [&n,&np,&p,&I,&C](Index i)->Index{return i==np?n+p:I(C(p)+i);};\n    // Should just build Mf as a vector...\n    for(Index i = 0;i<np+1;i++) { Mfijv.emplace_back(J(i),J(i),Mp(i)); }\n    // loop over faces\n    for(Index f = 0;f<np;f++)\n    {\n      for(Index c = 0;c<3;c++)\n      {\n        const Index i = F(f,(c+1)%3);\n        const Index j = F(f,(c+2)%3);\n        // symmetric off-diagonal\n        Lfijv.emplace_back(J(i),J(j),K(f,c));\n        Lfijv.emplace_back(J(j),J(i),K(f,c));\n        // diagonal\n        Lfijv.emplace_back(J(i),J(i),-K(f,c));\n        Lfijv.emplace_back(J(j),J(j),-K(f,c));\n      }\n    }\n  }\n  P.resize(n+m,n);\n  P.setFromTriplets(Pijv.begin(),Pijv.end());\n  Eigen::SparseMatrix<Scalar> Lf(n+m,n+m);\n  Lf.setFromTriplets(Lfijv.begin(),Lfijv.end());\n  Eigen::SparseMatrix<Scalar> Mf(n+m,n+m);\n  Mf.setFromTriplets(Mfijv.begin(),Mfijv.end());\n  L = P.transpose() * Lf * P;\n  // \"unlumped\" M\n  const Eigen::SparseMatrix<Scalar> PTMP = P.transpose() * Mf * P;\n  // Lump M\n  const VectorXS Mdiag = PTMP * VectorXS::Ones(n,1);\n  igl::diag(Mdiag,M);\n\n  MatrixXS Vf = P*V;\n  Eigen::MatrixXi Ff(I.size(),3);\n  {\n    Index f = 0;\n    for(Index p = 0;p<C.size()-1;p++)\n    {\n      const Index np = C(p+1)-C(p);\n      for(Index c = 0;c<np;c++)\n      {\n        Ff(f,0) = I(C(p)+c);\n        Ff(f,1) = I(C(p)+(c+1)%np);\n        Ff(f,2) = V.rows()+p;\n        f++;\n      }\n    }\n    assert(f == Ff.rows());\n  }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\n// generated by autoexplicit.sh\ntemplate void igl::cotmatrix<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::SparseMatrix<double, 0, int>&, Eigen::SparseMatrix<double, 0, int>&, Eigen::SparseMatrix<double, 0, int>&);\n// generated by autoexplicit.sh\ntemplate void igl::cotmatrix<Eigen::Matrix<double, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 1, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::SparseMatrix<double, 0, int>&);\ntemplate void igl::cotmatrix<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 4, 0, -1, 4>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 4, 0, -1, 4> > const&, Eigen::SparseMatrix<double, 0, int>&);\ntemplate void igl::cotmatrix<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> > const&, Eigen::SparseMatrix<double, 0, int>&);\ntemplate void igl::cotmatrix<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, double>(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::SparseMatrix<double, 0, int>&);\n#endif\n", "meta": {"hexsha": "c65fd7d45bc573ef7202b89a8a163256171f6123", "size": 8412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/libigl/include/igl/cotmatrix.cpp", "max_stars_repo_name": "chefmramos85/monster-mash", "max_stars_repo_head_hexsha": "239a41f6f178ca83c4be638331e32f23606b0381", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1125.0, "max_stars_repo_stars_event_min_datetime": "2021-02-01T09:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:50:40.000Z", "max_issues_repo_path": "third_party/libigl/include/igl/cotmatrix.cpp", "max_issues_repo_name": "ryan-cranfill/monster-mash", "max_issues_repo_head_hexsha": "c1b906d996885f8a4011bdf7558e62e968e1e914", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T12:36:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T14:02:50.000Z", "max_forks_repo_path": "third_party/libigl/include/igl/cotmatrix.cpp", "max_forks_repo_name": "ryan-cranfill/monster-mash", "max_forks_repo_head_hexsha": "c1b906d996885f8a4011bdf7558e62e968e1e914", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2021-02-13T10:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T11:55:20.000Z", "avg_line_length": 36.2586206897, "max_line_length": 464, "alphanum_fraction": 0.6016405136, "num_tokens": 2817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.42017460345092894}}
{"text": "/*\n * EigenvalueCovariance.cpp\n *\n *  Created on: May 6, 2015\n *      Author: dbazazian\n */\n\n\n\n     #include <iostream>\n     #include <Eigen/Eigenvalues>\n     #include <Eigen/Dense>\n     #include <vector>\n     #include <math.h>\n     #include <cmath>\n     #include <fstream>\n     #include <string>\n     #include <vector>\n     #include <pcl/io/io.h>\n     #include <pcl/io/pcd_io.h>\n     #include <pcl/point_types.h>\n     #include <pcl/features/integral_image_normal.h>\n     #include <pcl/features/normal_3d.h>\n     #include <pcl/common/common_headers.h>\n     #include <pcl/features/integral_image_normal.h>\n     #include <pcl/features/normal_3d.h>\n     #include <pcl/visualization/cloud_viewer.h>\n     #include <pcl/filters/passthrough.h>\n     #include <pcl/ModelCoefficients.h>\n     #include <pcl/filters/project_inliers.h>\n     #include <pcl/features/shot_omp.h>\n     #include \"pcl/features/fpfh.h\"\n     #include <pcl/io/ply_io.h>\n\nusing namespace std;\nusing namespace Eigen;\n\n\nint\nmain (int argc, char*argv[])\n{\n\t  pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);\n\n\n\t // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/Wedge/W0.2S45T45.pcd\", *cloud);\n\t // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/TwoPlane22.pcd\", *cloud);\n\t  //  pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/CubeSharpEdge.pcd\", *cloud);\n\t  // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/OnePlane.pcd\", *cloud);\n\t   // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/bunny.pcd\",*cloud);\n\t   // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/Statue.pcd\", *cloud);\n\t     // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/dragon.pcd\", *cloud);\n\t  // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/IntersectionThreePlanes.pcd\", *cloud);\n\n\n\t  // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AddingNoise/Bunny03Noise50.pcd\", *cloud);\n\t  pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/TetrahedronMultiple.pcd\", *cloud);\n\n\t    // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/SpherMultiple.pcd\", *cloud);\n\n\t      // pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AimAtShape/trim-starC.pcd\", *cloud);\n\t      //\tpcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AimAtShape/VaseC.pcd\", *cloud);\n\t       //  pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AimAtShape/twirlC.pcd\", *cloud);\n\t      \t//  pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AimAtShape/fandiskC.pcd\", *cloud);\n\t      //pcl::io::loadPCDFile (\"/Path/TO/ArtificialPointClouds/AimAtShape/sharp_sphereC.pcd\", *cloud);\n\n\t   std::cout << \"Number of points in the Cube Input cloud is:\"<< cloud->points.size() << std::endl;\n\n\t  pcl::PointCloud<pcl::PointXYZRGBA>::Ptr Normals (new pcl::PointCloud<pcl::PointXYZRGBA>);\n\t  Normals->resize(cloud->size());\n\n\t  // K nearest neighbor search\n\t  int KNumbersNeighbor = 10; // numbers of neighbors 7 , 120\n\t  std::vector<int> NeighborsKNSearch(KNumbersNeighbor);\n\t  std::vector<float> NeighborsKNSquaredDistance(KNumbersNeighbor);\n\n\t  int* NumbersNeighbor = new  int [cloud ->points.size ()];\n\t  pcl::KdTreeFLANN<pcl::PointXYZRGBA> kdtree;\n\t  kdtree.setInputCloud (cloud);\n\t  pcl::PointXYZRGBA searchPoint;\n\n\n\n\t  double* SmallestEigen = new  double [cloud->points.size() ];\n\t  double* MiddleEigen = new  double [cloud->points.size() ];\n\t  double* LargestEigen = new  double [cloud->points.size() ];\n\n\t  double* DLS = new  double [cloud->points.size() ];\n\t  double* DLM = new  double [cloud->points.size() ];\n\t  double* DMS = new  double [cloud->points.size() ];\n\t  double* Sigma = new  double [cloud->points.size() ];\n\n//\t\tstd::vector<double> SmallestEigen;\n//\t\tstd::vector<double> MiddleEigen;\n//\t\tstd::vector<double> LargestEigen;\n//\n//\t\tstd::vector<double> DLS;\n//\t\tstd::vector<double> DML;\n//\t\tstd::vector<double> DMS;\n\n\t    //  ************ All the Points of the cloud *******************\n\tfor (size_t i = 0; i < cloud ->points.size (); ++i) {\n\n\tsearchPoint.x =   cloud->points[i].x;\n\tsearchPoint.y =   cloud->points[i].y;\n\tsearchPoint.z =   cloud->points[i].z;\n\n\tif ( kdtree.nearestKSearch (searchPoint, KNumbersNeighbor, NeighborsKNSearch, NeighborsKNSquaredDistance) > 0 ) {\n\t\t NumbersNeighbor[i]= NeighborsKNSearch.size (); }\n\t    else { NumbersNeighbor[i] = 0; }\n\n\tfloat Xmean; float Ymean; float Zmean;\n\tfloat sum= 0.00;\n// Computing Covariance Matrix\n\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n      sum += cloud->points[ NeighborsKNSearch[ii] ].x; }\n\tXmean = sum / NumbersNeighbor[i] ;\n\tsum= 0.00;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += cloud->points[NeighborsKNSearch[ii] ].y;}\n\t\t\tYmean = sum / NumbersNeighbor[i] ;\n\t\t sum= 0.00;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += cloud->points[NeighborsKNSearch[ii] ].z;}\n\t\t\tZmean = sum / NumbersNeighbor[i] ;\n\n\t\t\tfloat\tCovXX;  float CovXY; float CovXZ; float CovYX; float CovYY; float CovYZ; float CovZX; float CovZY; float CovZZ;\n\n\t\t\tsum = 0.00 ;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += ( (cloud->points[NeighborsKNSearch[ii] ].x - Xmean ) * ( cloud->points[NeighborsKNSearch[ii] ].x - Xmean )  );}\n\t\t\tCovXX = sum / ( NumbersNeighbor[i]-1) ;\n\n\t\t\tsum = 0.00 ;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += ( (cloud->points[NeighborsKNSearch[ii] ].x - Xmean ) * ( cloud->points[NeighborsKNSearch[ii] ].y - Ymean )  );}\n\t\t\tCovXY = sum / ( NumbersNeighbor[i]-1) ;\n\n\t\t\tCovYX = CovXY ;\n\n\t\t\tsum = 0.00 ;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += ( (cloud->points[NeighborsKNSearch[ii] ].x - Xmean ) * ( cloud->points[NeighborsKNSearch[ii] ].z - Zmean )  );}\n\t\t\tCovXZ= sum / ( NumbersNeighbor[i]-1) ;\n\n\t\t\tCovZX = CovXZ;\n\n\t\t\tsum = 0.00 ;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += ( (cloud->points[NeighborsKNSearch[ii] ].y - Ymean ) * ( cloud->points[NeighborsKNSearch[ii] ].y - Ymean )  );}\n\t\t\tCovYY = sum / ( NumbersNeighbor[i]-1) ;\n\n\t\t\tsum = 0.00 ;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += ( (cloud->points[NeighborsKNSearch[ii] ].y - Ymean ) * ( cloud->points[NeighborsKNSearch[ii] ].z - Zmean )  );}\n\t\t\tCovYZ = sum / ( NumbersNeighbor[i]-1) ;\n\n\t\t\tCovZY = CovYZ;\n\n\t\t\tsum = 0.00 ;\n\t\t\tfor (size_t ii = 0; ii < NeighborsKNSearch.size (); ++ii){\n\t\t\tsum += ( (cloud->points[NeighborsKNSearch[ii] ].z - Zmean ) * ( cloud->points[NeighborsKNSearch[ii] ].z - Zmean )  );}\n\t\t\tCovZZ = sum / ( NumbersNeighbor[i]-1) ;\n\n// Computing Eigenvalue and EigenVector\n   Matrix3f Cov;\n   Cov << CovXX, CovXY, CovXZ, CovYX, CovYY, CovYZ, CovZX, CovZY, CovZZ;\n\n  SelfAdjointEigenSolver<Matrix3f> eigensolver(Cov);\n  if (eigensolver.info() != Success) abort();\n\n  double EigenValue1 = eigensolver.eigenvalues()[0];\n  double EigenValue2 = eigensolver.eigenvalues()[1];\n  double EigenValue3 = eigensolver.eigenvalues()[2];\n\n  double Smallest = 0.00; double Middle = 0.00; double Largest= 0.00;\n  if (EigenValue1<  EigenValue2 ) { Smallest =  EigenValue1 ; } else { Smallest = EigenValue2 ; }\n  if (EigenValue3<  Smallest ) { Smallest =  EigenValue3 ; }\n\n\n  if(EigenValue1 <= EigenValue2 && EigenValue1 <= EigenValue3) {\n\t  Smallest = EigenValue1;\n  if(EigenValue2 <= EigenValue3) {Middle = EigenValue2; Largest = EigenValue3;}\n  else {Middle = EigenValue3; Largest = EigenValue2;}\n  }\n\n  if(EigenValue1 >= EigenValue2 && EigenValue1 >= EigenValue3)\n  {\n\t  Largest = EigenValue1;\n  if(EigenValue2 <= EigenValue3) { Smallest = EigenValue2; Middle = EigenValue3; }\n  else {Smallest = EigenValue3; Middle = EigenValue2;}\n  }\n\n  if ((EigenValue1 >= EigenValue2 && EigenValue1 <= EigenValue3) || (EigenValue1 <= EigenValue2 && EigenValue1 >= EigenValue3))\n  {\n\t  Middle = EigenValue1;\n  if(EigenValue2 >= EigenValue3){Largest = EigenValue2; Smallest = EigenValue3;}\n  else{Largest = EigenValue3; Smallest = EigenValue2;}\n  }\n\nSmallestEigen[i]= Smallest ;\nMiddleEigen[i]= Middle;\nLargestEigen[i]= Largest;\n\nDLS[i] =    std::abs ( SmallestEigen[i] / LargestEigen[i]) ;          // std::abs ( LargestEigen[i] -  SmallestEigen[i] ) ;\nDLM[i] = std::abs ( MiddleEigen[i] /  LargestEigen[i]) ;             // std::abs (  LargestEigen[i] - MiddleEigen[i] ) ;\nDMS[i] = std::abs ( SmallestEigen[i] / MiddleEigen[i]) ;       // std::abs ( MiddleEigen[i] -  SmallestEigen[i] ) ;\nSigma[i] = (SmallestEigen[i] ) / ( SmallestEigen[i] + MiddleEigen[i] + LargestEigen[i] ) ;\n\t} // For each point of the cloud\n\n\t  std::cout<< \" Computing Sigma is Done! \" << std::endl;\n// Color Map For the difference of the eigen values\n\n\t  double MaxD=0.00 ;\n\t  double MinD= cloud ->points.size ();\n\t  int Ncolors=256;\n\n\t  for (size_t i = 0; i < cloud ->points.size (); ++i) {\n\t  \tif (  Sigma [i] < MinD) MinD= Sigma [i];\n\t  \tif (  Sigma[i] > MaxD) MaxD = Sigma [i];\n\t  }\n\n\t  std::cout<< \" Minimum is :\" << MinD<< std::endl;\n\t  std::cout<< \" Maximum  is :\" << MaxD << std::endl;\n\n//   *****************************************\n\t/*\n\t  // computing the standard deviation\n\t double ss = 0.00 ;\n\t  for (size_t i = 0; i < cloud ->points.size (); ++i) {\n\t\t  ss += Sigma [i] ;}\n\t  double avg = ss / cloud ->points.size () ;\n\t  ss = 0.00 ;\n\t  for (size_t i = 0; i < cloud ->points.size (); ++i) {\n\t\t  ss += (Sigma [i] -  avg ) * (  Sigma [i] -  avg ) ;}\n\t  double stddvtion =   sqrt (  ss  /  ( cloud ->points.size () - 1 )  ) ;\n\n\t  std::cout<< \" Standard Deviation is :\" << stddvtion << std::endl;\n\n\t   MaxD = ( 2 )* stddvtion;\n\t  //MaxD = 10* stddvtion;\n\n\t  // Color table\n\t\tdouble line;\n\t\tdouble code[Ncolors][3];\n\t   ifstream colorcode ( \"/Path/TO/ArtificialPointClouds/JetColorDensity/ColorCodes256.txt\" );\n\t   //store color codes in array\n\t    int i=0,j=0;\n\t    while( colorcode>> line ) {\n\t    code[i][j]=line;\n\t    j++;\n\t    if (j == 3)\n\t    i++;\n\t}\n\t    code[1][0] = 0;\n\t    code[1][1] = 0;\n\t    code[1][2] = 135.468;\n\n\n\n\t    // jet color map\n\n\tint level = 0;\n\tfloat step = ( ( MaxD -  MinD) / Ncolors ) ;\n\t    for (size_t i = 0; i < cloud ->points.size (); ++i) {\nif (  SmallestEigen [i] <= MaxD ) {\n\t    level = floor( (SmallestEigen [i] - MinD ) /  step ) ;\n\n\t    cloud->points[i].r = code[ level ][0];\n\t    cloud->points[i].g =  code[ level ][1];\n\t    cloud->points[i].b =  code[ level ][2];\n} // if sigma less than Max\n\t    }\n*/\n//    *****************************************\n\n\n//   *****************************************\n\t    int Edgepoints = 0;\n\t    // Red and white (khaki)\n\n\t    for (size_t i = 0; i < cloud ->points.size (); ++i) {\n\t    \t    cloud->points[i].r = 240;\n\t    \t    cloud->points[i].g =  230 ;\n\t    \t    cloud->points[i].b =  140;\n\t            }\n\n\t  int level = 0;\n\t  float step = ( ( MaxD -  MinD) / Ncolors ) ;\n\t //  level = floor( (Sigma [i] - MinD ) /  step ) ;\nfor (size_t i = 0; i < cloud ->points.size (); ++i) {\n\t  if ( Sigma [i] > ( MinD + ( 6* step) ) ) {  //6*step\n\t    cloud->points[i].r = 255;\n\t    cloud->points[i].g =  0 ;\n\t    cloud->points[i].b =  0;\n\n\t    //    Dim gray....\n//\t\t    cloud->points[i].r = 105;\n//\t\t    cloud->points[i].g = 105 ;\n//\t\t    cloud->points[i].b = 105;\n\t    Edgepoints ++;\n        }\n     }\n\n//   *****************************************\n\n\nstd::cout<< \" Number of Edge points  is :\" << Edgepoints << std::endl;\n\n\t    // writing the Sigma on the disk\n//\t    \t   \t\tstd::ofstream ofsSigma;\n//\t    \t   \t\tofsSigma.open(\"/Path/TO/SigmaDragon.txt\");\n//\t    \t            for (size_t i = 0; i < cloud ->points.size (); ++i) {\n//\t    \t            \tofsSigma << Sigma [i]<< \",\"<< std::endl ;\n//\t    \t                    }\n\n\n\n\n  \tpcl::PLYWriter writePLY;\n //  writePLY.write (\"/Path/TO/RatioSmallestEigen22.ply\", *cloud,  false);\n\t //   writePLY.write (\"/Path/TO/CloudEigeJnetTwirl.ply\", *cloud,  false);\n\t// writePLY.write (\"/Path/TO/CloudEigeJnetDragon.ply\", *cloud,  false);\n  // writePLY.write (\"/Path/TO/EigenTwoPlane90N10.ply\", *cloud,  false);\n  \t // writePLY.write (\"/Path/TO/DragonRedWhite.ply\", *cloud,  false);\n  \t// writePLY.write (\"/Path/TO/IntersectionThreePlanes.ply\", *cloud,  false);\n  \t// writePLY.write (\"/Path/TO/BunnyNoise50.ply\", *cloud,  false);\n  \t//writePLY.write (\"/Path/TO/BunnyEdges.ply\", *cloud,  false);\n  \t writePLY.write (\"/Path/TO/TetahedronMultiple.ply\", *cloud,  false);\n\n  pcl::visualization::CloudViewer viewer(\"Cloud Viewer\");\n  viewer.showCloud(cloud);\n  while (!viewer.wasStopped ())\n  {}\n\n  return 0;\n  }", "meta": {"hexsha": "0da61c866bd626432a36807e84187234a5e4702e", "size": 12333, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Difference_Eigenvalues.cpp", "max_stars_repo_name": "n1ckfg/Edge_Extraction", "max_stars_repo_head_hexsha": "2bbe215350faf02334652af54eac4f4666872d4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 102.0, "max_stars_repo_stars_event_min_datetime": "2017-12-14T14:17:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T12:26:13.000Z", "max_issues_repo_path": "Difference_Eigenvalues.cpp", "max_issues_repo_name": "n1ckfg/Edge_Extraction", "max_issues_repo_head_hexsha": "2bbe215350faf02334652af54eac4f4666872d4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-08-22T23:08:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-30T10:24:35.000Z", "max_forks_repo_path": "Difference_Eigenvalues.cpp", "max_forks_repo_name": "n1ckfg/Edge_Extraction", "max_forks_repo_head_hexsha": "2bbe215350faf02334652af54eac4f4666872d4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 33.0, "max_forks_repo_forks_event_min_datetime": "2017-07-12T03:05:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T09:00:30.000Z", "avg_line_length": 36.7053571429, "max_line_length": 127, "alphanum_fraction": 0.6101516257, "num_tokens": 3894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943603346811, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4201745913191602}}
{"text": "#ifndef _GLOB_H_\n#define _GLOB_H_\n\n#include <sys/resource.h>\n\n#include <exception>\n#include <iostream>\n#include <utility>\n#include <cstdlib>\n#include <fstream>\n#include <memory>\n#include <string>\n#include <mutex>\n#include <list>\n#include <map> \n#include <random>\n#include <omp.h>\n#include <iomanip>\n#include <stdexcept>\n#include <chrono>\n#include <cmath>\n#include <cassert>\n#include <algorithm>\n\n#include <json.hpp>\n#include <progressBar.hpp>\n\n#include <boost/filesystem/operations.hpp>\n#include <boost/filesystem/path.hpp>\n\n\n#include <CGAL/Line_2.h>\n#include <CGAL/Origin.h>\n#include <CGAL/Polygon_2.h>\n//#include <CGAL/Cartesian.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>  //new \n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Delaunay_mesher_2.h>\n#include <CGAL/point_generators_2.h>\n#include <CGAL/squared_distance_2.h>\n#include <CGAL/Aff_transformation_2.h>\n#include <CGAL/Delaunay_mesh_face_base_2.h>\n#include <CGAL/Delaunay_mesh_size_criteria_2.h>\n#include <CGAL/Triangulation_face_base_with_info_2.h>\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\n\n#define CGAL_HAS_THREADS\n\n\n#include <GeographicLib/Geodesic.hpp>\n#include <GeographicLib/Constants.hpp>\n#include <GeographicLib/GeoCoords.hpp>\n#include <GeographicLib/LocalCartesian.hpp>\n\n#include <osrm/match_parameters.hpp>\n#include <osrm/nearest_parameters.hpp>\n#include <osrm/route_parameters.hpp>\n#include <osrm/table_parameters.hpp>\n#include <osrm/trip_parameters.hpp>\n#include <osrm/coordinate.hpp>\n#include <osrm/engine_config.hpp>\n#include <osrm/json_container.hpp>\n#include <osrm/osrm.hpp>\n#include <osrm/status.hpp>\n\n\n\nstruct FaceInfo2 {\n\tFaceInfo2() {}\n\tint nesting_level;\n\tbool in_domain()\n\t{\n\t\treturn nesting_level%2 == 1;\n\t}\n};\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel      K;//new\n//typedef CGAL::Simple_cartesian<double> K;\n\ntypedef CGAL::Aff_transformation_2<K> Transformation;\n\ntypedef CGAL::Line_2<K>     Line2D;\ntypedef CGAL::Point_2<K>    Point2D;\ntypedef CGAL::Triangle_2<K> Triangle2D;//new\ntypedef CGAL::Vector_2<K>   Vector2D;\ntypedef CGAL::Polygon_2<K>  Polygon2D;\n\ntypedef CGAL::Triangulation_vertex_base_2<K>                      Vb;\ntypedef CGAL::Triangulation_face_base_with_info_2<FaceInfo2,K>    Fbb;//new\n//typedef CGAL::Delaunay_mesh_face_base_2<K>                        Fb;\ntypedef CGAL::Constrained_triangulation_face_base_2<K,Fbb>        Fb;//new\ntypedef CGAL::Triangulation_data_structure_2<Vb, Fb>              Tds;\n\ntypedef CGAL::Exact_predicates_tag                                Itag;//new\ntypedef CGAL::Constrained_Delaunay_triangulation_2<K, Tds, Itag>  CDT;//new\n//typedef CGAL::Constrained_Delaunay_triangulation_2<K, Tds>        CDT;\n\ntypedef CGAL::Delaunay_mesh_size_criteria_2<CDT>                  Mesh_2_criteria;\n\n\nusing json=nlohmann::json;\nusing namespace GeographicLib;\n\nextern bool        g_showProgressBar;\nextern float       g_closeEnough;\nextern float       g_randomWalkwayRadius;\nextern float       g_attractionRadius;\nextern uint32_t    g_epochInitSim;\nextern uint32_t    g_currTimeSim;\nextern std::string g_baseDir;\nextern uint32_t    g_AgentsMem;\nextern float       g_deltaT;\n\n//Variables globales para medir tiempo\nextern uint32_t g_timeExecMakeAgents;\nextern uint32_t g_timeExecCal;\nextern uint32_t g_timeExecSim;\n\nextern std::vector<std::string> g_logZonesDensity;\nextern std::vector<uint32_t>    g_logUsePhone;\nextern std::vector<std::string> g_logVelocity;\n\n//enum model_t {ShortestPath=0, FollowTheCrowd=1, RandomWalkway=2, WorkingDay, SNITCH=666};\nenum model_t {Residents=0, Visitors_I=1, Visitors_II=2};\n\n\n\nextern std::map<std::string, model_t> model_map;\n\n\n#endif\n", "meta": {"hexsha": "53da520a1b8958278eb1c9b909f5959faae2892d", "size": 3650, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/include/glob.hh", "max_stars_repo_name": "gabriel-astudillo/demps", "max_stars_repo_head_hexsha": "6c7a7a21a05de2b5be68f1b1f33bf1ec3476f87a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/include/glob.hh", "max_issues_repo_name": "gabriel-astudillo/demps", "max_issues_repo_head_hexsha": "6c7a7a21a05de2b5be68f1b1f33bf1ec3476f87a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/glob.hh", "max_forks_repo_name": "gabriel-astudillo/demps", "max_forks_repo_head_hexsha": "6c7a7a21a05de2b5be68f1b1f33bf1ec3476f87a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6515151515, "max_line_length": 91, "alphanum_fraction": 0.755890411, "num_tokens": 1008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.42007153348554366}}
{"text": "#ifndef GP_HPP_INCLUDED\n#define GP_HPP_INCLUDED\n#include <vector>\n#include <memory>\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Cholesky>\n\nnamespace boat {\ndouble normal_lnp(double x, double mean, double variance);\ntypedef enum { SQUARED_EXP, MATERN52 } kernel_t;\n\nclass GPParams{\n  public:\n  GPParams():mean_(0.0), amplitude_(1.0), default_noise_(0.1),\n  kernel_(MATERN52) {}\n\n  void amplitude(double amplitude) {\n    amplitude_ = amplitude;\n  }\n\n  void stdev(double stdev) {\n    amplitude_ = stdev * stdev;\n  }\n\n  void default_noise(double default_noise) {\n    assert(default_noise >= 0.0);\n    //default_noise_ = std::max(default_noise, 1e-4);\n    default_noise_ = default_noise;\n  }\n\n  void mean(double mean) {\n    mean_ = mean;\n  }\n\n  void linear_scales(const std::vector<double>& linear_scales){\n    linear_scales_ = linear_scales;\n    inv_linear_scales_ = Eigen::VectorXd::Map(linear_scales.data(), linear_scales.size())\n                           .array()\n                           .inverse();\n  }\n\n  void kernel(kernel_t kernel){\n    kernel_ = kernel;\n  }\n\n\n  double stdev() const {\n    return sqrt(amplitude_);\n  }\n\n  double amplitude() const {\n    return amplitude_;\n  }\n\n  double mean() const {\n    return mean_;\n  }\n\n  double default_noise() const {\n    return default_noise_;\n  }\n\n  const Eigen::VectorXd& inv_linear_scales() const {\n    return inv_linear_scales_;\n  }\n\n  const std::vector<double>& linear_scales() const {\n    return linear_scales_;\n  }\n\n  kernel_t kernel() const {\n    return kernel_;\n  }\n\n  private:\n  double mean_;\n  double amplitude_;\n  double default_noise_;\n  std::vector<double> linear_scales_;\n  Eigen::VectorXd inv_linear_scales_;\n  kernel_t kernel_;\n};\n\nstruct GaussianDistrib {\n  double mu_;\n  double var_;\n  double mu() {\n    return mu_;\n  }\n  double var() {\n    return var_;\n  }\n  double stdev() {\n    return sqrt(var_);\n  }\n};\n\nclass GP {\n  friend class TreedGPS;\n  public:\n  GP();\n  GP(GPParams params);\n  void set_params(GPParams params);\n  int num_dims() const;\n  double observe(const std::vector<double>& x_new, double y_new);\n  double observe(const std::vector<double>& x_new, double y_new, double noise);\n\n  double predict_mean(const std::vector<double>& x_new) const;\n  GaussianDistrib predict_distrib(const std::vector<double>& x_new) const;\n  void print() const;\n\n   //private:\n   double observe_i(const std::vector<double>& x_new,\n                    double y_new, double noise_var);\n   void compute_cholesky() const;\n   int at_index(const Eigen::RowVectorXd& v) const;\n   void remove_observation(int i);\n   Eigen::MatrixXd covariance(const Eigen::MatrixXd& x1,\n                              const Eigen::MatrixXd& x2) const;\n\n  void compute_cholesky_from_scratch() const;\n\n  // Parameters\n  GPParams params_;\n\n  // Processed data\n  Eigen::MatrixXd observed_x_;\n  Eigen::VectorXd observed_y_;\n  Eigen::VectorXd noise_var_;\n\n  mutable Eigen::MatrixXd covariance_cholesky_;\n  mutable Eigen::VectorXd alpha_;\n};\n\nclass TreedGPS {\n  public:\n  TreedGPS();\n  TreedGPS(GPParams params, int observation_thresh = 64, int overlap = 3);\n  TreedGPS(const TreedGPS& other);\n  TreedGPS& operator=(const TreedGPS& other);\n  void set_params(GPParams params);\n\n  double observe(const std::vector<double>& x_new, double y_new);\n  double observe(const std::vector<double>& x_new, double y_new, double noise);\n\n  double predict_mean(const std::vector<double>& x_new) const;\n  GaussianDistrib predict_distrib(const std::vector<double>& x_new) const;\n\n  private:\n  bool side(const std::vector<double>& x_new) const;\n\n  //Lots of helpers for the splitting\n  std::pair<std::vector<int>, std::vector<int>> compute_thresh_and_divide(double max_diff);\n  std::pair<std::vector<int>, std::vector<int>> compute_thresh_props();\n  void check_thresh();\n  void copy_observation(bool s, int i);\n  void compute_children_cholesky();\n\n  int observation_thresh_;\n  int overlap_;\n\n  int thresh_dim_;\n  double thresh_;\n  double inv_ls_along_thresh_dim_;\n  std::unique_ptr<GP> gp_;\n  std::unique_ptr<TreedGPS> left_;\n  std::unique_ptr<TreedGPS> right_;\n};\n}\n#endif  // GP_HPP_INCLUDED\n", "meta": {"hexsha": "d1a164118bd53b9fd87ed1e46e22ccf4697a47b8", "size": 4114, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/probabilistic/gp.hpp", "max_stars_repo_name": "EvilMcJerkface/BOAT", "max_stars_repo_head_hexsha": "90b7583407ece7a74068d98b836f40c52305d6a4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 56.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T23:48:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-31T14:03:18.000Z", "max_issues_repo_path": "src/probabilistic/gp.hpp", "max_issues_repo_name": "EvilMcJerkface/BOAT", "max_issues_repo_head_hexsha": "90b7583407ece7a74068d98b836f40c52305d6a4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T08:44:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-22T16:04:18.000Z", "max_forks_repo_path": "src/probabilistic/gp.hpp", "max_forks_repo_name": "EvilMcJerkface/BOAT", "max_forks_repo_head_hexsha": "90b7583407ece7a74068d98b836f40c52305d6a4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2017-02-01T08:31:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-15T05:52:43.000Z", "avg_line_length": 23.9186046512, "max_line_length": 91, "alphanum_fraction": 0.6937287312, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.42007152690445315}}
{"text": "/**\n * Copyright (c) 2021 Melown Technologies SE\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * *  Redistributions of source code must retain the above copyright notice,\n *    this list of conditions and the following disclaimer.\n *\n * *  Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include \"multipolymesh.hpp\"\n\n#include \"math/math.hpp\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n\nnamespace geometry\n{\nnamespace ublas = boost::numeric::ublas;\n\nFacePlaneCrs::FacePlaneCrs(const math::Point3& p1,\n                           const math::Point3& p2,\n                           const math::Point3& p3)\n{\n    // get base vectors\n    math::Point3 n1 = math::normalize(p2 - p1);\n    normal_ = math::normalize(math::crossProduct(p2 - p1, p3 - p1));\n    math::Point3 n2 = math::normalize(math::crossProduct(normal_, n1));\n\n    p2g_ = math::identity4();\n\n    auto col1 = ublas::column(p2g_, 0);\n    auto col2 = ublas::column(p2g_, 1);\n    auto col3 = ublas::column(p2g_, 2);\n    auto col4 = ublas::column(p2g_, 3);\n    ublas::subrange(col1, 0, 3) = n1;\n    ublas::subrange(col2, 0, 3) = n2;\n    ublas::subrange(col3, 0, 3) = normal_;\n    ublas::subrange(col4, 0, 3) = p1;\n\n    g2p_ = math::matrixInvert(p2g_);\n}\n\n} // namespace geometry\n", "meta": {"hexsha": "ce7b55f3ef8c53e0b07eec427dcc231efdf634cb", "size": 2307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geometry/multipolymesh.cpp", "max_stars_repo_name": "Melown/libgeometry", "max_stars_repo_head_hexsha": "cfeba420776193b3daf12b1926c4762334bf572b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-06-23T19:09:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-26T06:52:15.000Z", "max_issues_repo_path": "geometry/multipolymesh.cpp", "max_issues_repo_name": "Melown/libgeometry", "max_issues_repo_head_hexsha": "cfeba420776193b3daf12b1926c4762334bf572b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry/multipolymesh.cpp", "max_forks_repo_name": "Melown/libgeometry", "max_forks_repo_head_hexsha": "cfeba420776193b3daf12b1926c4762334bf572b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8196721311, "max_line_length": 78, "alphanum_fraction": 0.7026441266, "num_tokens": 590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.41993712045654225}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2017 - 2020 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n// Config files\n#include <SAMRAI_config.h>\n\n// Headers for basic PETSc functions\n#include <petscsys.h>\n\n// Headers for basic SAMRAI objects\n#include <BergerRigoutsos.h>\n#include <CartesianGridGeometry.h>\n#include <LoadBalancer.h>\n#include <StandardTagAndInitialize.h>\n\n// Headers for basic libMesh objects\n#include <libmesh/boundary_info.h>\n#include <libmesh/equation_systems.h>\n#include <libmesh/exodusII_io.h>\n#include <libmesh/mesh.h>\n#include <libmesh/mesh_function.h>\n#include <libmesh/mesh_generation.h>\n#include <libmesh/mesh_triangle_interface.h>\n\n// Headers for application-specific algorithm/data structure objects\n#include <ibamr/IBExplicitHierarchyIntegrator.h>\n#include <ibamr/IBFEMethod.h>\n#include <ibamr/INSCollocatedHierarchyIntegrator.h>\n#include <ibamr/INSStaggeredHierarchyIntegrator.h>\n\n#include <ibtk/AppInitializer.h>\n#include <ibtk/IBTKInit.h>\n#include <ibtk/IBTK_MPI.h>\n#include <ibtk/libmesh_utilities.h>\n#include <ibtk/muParserCartGridFunction.h>\n#include <ibtk/muParserRobinBcCoefs.h>\n\n#include <boost/multi_array.hpp>\n\n// Set up application namespace declarations\n#include <ibamr/app_namespaces.h>\n\n// Elasticity model data.\nnamespace ModelData\n{\n// The tether penalty functions each require some data that is set in the\n// input file. This data is passed to each object through the void *ctx\n// context data pointer. Here we collect all relevant tether data in a struct:\nstruct ElasticityData\n{\n    const double c1_s;\n    const double kappa_s;\n    const double mu_s;\n    const double lambda_s;\n\n    ElasticityData(Pointer<Database> input_db)\n        : c1_s(input_db->getDouble(\"C1_S\")),\n          kappa_s(input_db->getDouble(\"KAPPA_S\")),\n          mu_s(input_db->getDouble(\"MU_S\")),\n          lambda_s(input_db->getDouble(\"LAMBDA_S\"))\n    {\n    }\n};\n\n// Tether (penalty) force function for the solid block.\nvoid\nblock_tether_force_function(VectorValue<double>& F,\n                            const TensorValue<double>& /*FF*/,\n                            const libMesh::Point& X,\n                            const libMesh::Point& s,\n                            Elem* const /*elem*/,\n                            const std::vector<const std::vector<double>*>& /*var_data*/,\n                            const std::vector<const std::vector<VectorValue<double> >*>& /*grad_var_data*/,\n                            double /*time*/,\n                            void* ctx)\n{\n    const ElasticityData* const elasticity_data = reinterpret_cast<ElasticityData*>(ctx);\n\n    F = elasticity_data->kappa_s * (s - X);\n    return;\n} // block_tether_force_function\n\n// Tether (penalty) force function for the thin beam.\nvoid\nbeam_tether_force_function(VectorValue<double>& F,\n                           const TensorValue<double>& /*FF*/,\n                           const libMesh::Point& X,\n                           const libMesh::Point& s,\n                           Elem* const /*elem*/,\n                           const std::vector<const std::vector<double>*>& /*var_data*/,\n                           const std::vector<const std::vector<VectorValue<double> >*>& /*grad_var_data*/,\n                           double /*time*/,\n                           void* ctx)\n{\n    const double r = sqrt((s(0) - 0.2) * (s(0) - 0.2) + (s(1) - 0.2) * (s(1) - 0.2));\n    if (r <= 0.05)\n    {\n        const ElasticityData* const elasticity_data = reinterpret_cast<ElasticityData*>(ctx);\n        F = elasticity_data->kappa_s * (s - X);\n    }\n    else\n    {\n        F.zero();\n    }\n    return;\n} // beam_tether_force_function\n\n// (Penalty) stress tensor function for the solid block.\nvoid\nblock_PK1_stress_function(TensorValue<double>& PP,\n                          const TensorValue<double>& FF,\n                          const libMesh::Point& /*X*/,\n                          const libMesh::Point& /*s*/,\n                          Elem* const /*elem*/,\n                          const std::vector<const std::vector<double>*>& /*var_data*/,\n                          const std::vector<const std::vector<VectorValue<double> >*>& /*grad_var_data*/,\n                          double /*time*/,\n                          void* ctx)\n{\n    const ElasticityData* const elasticity_data = reinterpret_cast<ElasticityData*>(ctx);\n\n    PP = 2.0 * elasticity_data->c1_s * (FF - tensor_inverse_transpose(FF, NDIM));\n    return;\n} // block_PK1_stress_function\n\nvoid\nbeam_PK1_stress_function(TensorValue<double>& PP,\n                         const TensorValue<double>& FF,\n                         const libMesh::Point& /*X*/,\n                         const libMesh::Point& /*s*/,\n                         Elem* const /*elem*/,\n                         const std::vector<const std::vector<double>*>& /*var_data*/,\n                         const std::vector<const std::vector<VectorValue<double> >*>& /*grad_var_data*/,\n                         double /*time*/,\n                         void* ctx)\n{\n    const ElasticityData* const elasticity_data = reinterpret_cast<ElasticityData*>(ctx);\n    static const TensorValue<double> II(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);\n    const TensorValue<double> CC = FF.transpose() * FF;\n    const TensorValue<double> EE = 0.5 * (CC - II);\n    const TensorValue<double> SS = elasticity_data->lambda_s * EE.tr() * II + 2.0 * elasticity_data->mu_s * EE;\n    PP = FF * SS;\n    return;\n} // beam_PK1_stress_function\n} // namespace ModelData\nusing namespace ModelData;\n\n// Function prototypes\nstatic ofstream drag_stream, lift_stream, A_x_posn_stream, A_y_posn_stream;\nvoid postprocess_data(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                      Pointer<INSHierarchyIntegrator> navier_stokes_integrator,\n                      Mesh& beam_mesh,\n                      EquationSystems* beam_equation_systems,\n                      Mesh& block_mesh,\n                      EquationSystems* block_equation_systems,\n                      const int iteration_num,\n                      const double loop_time,\n                      const string& data_dump_dirname);\n\n/*******************************************************************************\n * For each run, the input filename and restart information (if needed) must   *\n * be given on the command line.  For non-restarted case, command line is:     *\n *                                                                             *\n *    executable <input file name>                                             *\n *                                                                             *\n * For restarted run, command line is:                                         *\n *                                                                             *\n *    executable <input file name> <restart directory> <restart number>        *\n *                                                                             *\n *******************************************************************************/\n\nint\nmain(int argc, char* argv[])\n{\n    // Initialize IBAMR and libraries. Deinitialization is handled by this object as well.\n    IBTKInit ibtk_init(argc, argv, MPI_COMM_WORLD);\n    const LibMeshInit& init = ibtk_init.getLibMeshInit();\n\n    { // cleanup dynamically allocated objects prior to shutdown\n\n        // Parse command line options, set some standard options from the input\n        // file, initialize the restart database (if this is a restarted run),\n        // and enable file logging.\n        Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, \"IB.log\");\n        Pointer<Database> input_db = app_initializer->getInputDatabase();\n\n        // Get various standard options set in the input file.\n        const bool dump_viz_data = app_initializer->dumpVizData();\n        const int viz_dump_interval = app_initializer->getVizDumpInterval();\n        const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter();\n#ifdef LIBMESH_HAVE_EXODUS_API\n        const bool uses_exodus = dump_viz_data && !app_initializer->getExodusIIFilename().empty();\n#else\n        const bool uses_exodus = false;\n        if (!app_initializer->getExodusIIFilename().empty())\n        {\n            plog << \"WARNING: libMesh was compiled without Exodus support, so no \"\n                 << \"Exodus output will be written in this program.\\n\";\n        }\n#endif\n        const string block_exodus_filename = app_initializer->getExodusIIFilename(\"block\");\n        const string beam_exodus_filename = app_initializer->getExodusIIFilename(\"beam\");\n\n        const bool dump_restart_data = app_initializer->dumpRestartData();\n        const int restart_dump_interval = app_initializer->getRestartDumpInterval();\n        const string restart_dump_dirname = app_initializer->getRestartDumpDirectory();\n        const string restart_read_dirname = app_initializer->getRestartReadDirectory();\n        const int restart_restore_num = app_initializer->getRestartRestoreNumber();\n\n        const bool dump_postproc_data = app_initializer->dumpPostProcessingData();\n        const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval();\n        const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory();\n        if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty())\n        {\n            Utilities::recursiveMkdir(postproc_data_dump_dirname);\n        }\n\n        const bool dump_timer_data = app_initializer->dumpTimerData();\n        const int timer_dump_interval = app_initializer->getTimerDumpInterval();\n\n        // Create a simple FE mesh.\n        const double dx = input_db->getDouble(\"DX\");\n        const double ds = input_db->getDouble(\"MFAC\") * dx;\n\n        Mesh block_mesh(init.comm(), NDIM);\n        string block_elem_type = input_db->getString(\"BLOCK_ELEM_TYPE\");\n        const double R = 0.05;\n        if (block_elem_type == \"TRI3\" || block_elem_type == \"TRI6\")\n        {\n#ifdef LIBMESH_HAVE_TRIANGLE\n            const int num_circum_nodes = ceil(2.0 * M_PI * R / ds);\n            for (int k = 0; k < num_circum_nodes; ++k)\n            {\n                const double theta = 2.0 * M_PI * static_cast<double>(k) / static_cast<double>(num_circum_nodes);\n                block_mesh.add_point(libMesh::Point(R * cos(theta), R * sin(theta)));\n            }\n            TriangleInterface triangle(block_mesh);\n            triangle.triangulation_type() = TriangleInterface::GENERATE_CONVEX_HULL;\n            triangle.elem_type() = Utility::string_to_enum<ElemType>(block_elem_type);\n            triangle.desired_area() = sqrt(3.0) / 4.0 * ds * ds;\n            triangle.insert_extra_points() = true;\n            triangle.smooth_after_generating() = true;\n            triangle.triangulate();\n            block_mesh.prepare_for_use();\n#else\n            TBOX_ERROR(\"ERROR: libMesh appears to have been configured without support for Triangle,\\n\"\n                       << \"       but Triangle is required for TRI3 or TRI6 elements.\\n\");\n#endif\n        }\n        else\n        {\n            // NOTE: number of segments along boundary is 4*2^r.\n            const double num_circum_segments = ceil(2.0 * M_PI * R / ds);\n            const int r = log2(0.25 * num_circum_segments);\n            MeshTools::Generation::build_sphere(block_mesh, R, r, Utility::string_to_enum<ElemType>(block_elem_type));\n        }\n        for (MeshBase::node_iterator n_it = block_mesh.nodes_begin(); n_it != block_mesh.nodes_end(); ++n_it)\n        {\n            Node& n = **n_it;\n            n(0) += 0.2;\n            n(1) += 0.2;\n        }\n\n        Mesh beam_mesh(init.comm(), NDIM);\n        string beam_elem_type = input_db->getString(\"BEAM_ELEM_TYPE\");\n        MeshTools::Generation::build_square(beam_mesh,\n                                            ceil(0.4 / ds),\n                                            ceil(0.02 / ds),\n                                            0.2,\n                                            0.6,\n                                            0.19,\n                                            0.21,\n                                            Utility::string_to_enum<ElemType>(beam_elem_type));\n        beam_mesh.prepare_for_use();\n\n        vector<MeshBase*> meshes(2);\n        meshes[0] = &block_mesh;\n        meshes[1] = &beam_mesh;\n\n        // Create major algorithm and data objects that comprise the\n        // application.  These objects are configured from the input database\n        // and, if this is a restarted run, from the restart database.\n        Pointer<INSHierarchyIntegrator> navier_stokes_integrator;\n        const string solver_type = app_initializer->getComponentDatabase(\"Main\")->getString(\"solver_type\");\n        if (solver_type == \"STAGGERED\")\n        {\n            navier_stokes_integrator = new INSStaggeredHierarchyIntegrator(\n                \"INSStaggeredHierarchyIntegrator\",\n                app_initializer->getComponentDatabase(\"INSStaggeredHierarchyIntegrator\"));\n        }\n        else if (solver_type == \"COLLOCATED\")\n        {\n            navier_stokes_integrator = new INSCollocatedHierarchyIntegrator(\n                \"INSCollocatedHierarchyIntegrator\",\n                app_initializer->getComponentDatabase(\"INSCollocatedHierarchyIntegrator\"));\n        }\n        else\n        {\n            TBOX_ERROR(\"Unsupported solver type: \" << solver_type << \"\\n\"\n                                                   << \"Valid options are: COLLOCATED, STAGGERED\");\n        }\n        Pointer<IBFEMethod> ib_method_ops =\n            new IBFEMethod(\"IBFEMethod\",\n                           app_initializer->getComponentDatabase(\"IBFEMethod\"),\n                           meshes,\n                           app_initializer->getComponentDatabase(\"GriddingAlgorithm\")->getInteger(\"max_levels\"),\n                           /*register_for_restart*/ true,\n                           restart_read_dirname,\n                           restart_restore_num);\n        Pointer<IBHierarchyIntegrator> time_integrator =\n            new IBExplicitHierarchyIntegrator(\"IBHierarchyIntegrator\",\n                                              app_initializer->getComponentDatabase(\"IBHierarchyIntegrator\"),\n                                              ib_method_ops,\n                                              navier_stokes_integrator);\n        Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>(\n            \"CartesianGeometry\", app_initializer->getComponentDatabase(\"CartesianGeometry\"));\n        Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>(\"PatchHierarchy\", grid_geometry);\n        Pointer<StandardTagAndInitialize<NDIM> > error_detector =\n            new StandardTagAndInitialize<NDIM>(\"StandardTagAndInitialize\",\n                                               time_integrator,\n                                               app_initializer->getComponentDatabase(\"StandardTagAndInitialize\"));\n        Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>();\n        Pointer<LoadBalancer<NDIM> > load_balancer =\n            new LoadBalancer<NDIM>(\"LoadBalancer\", app_initializer->getComponentDatabase(\"LoadBalancer\"));\n        Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm =\n            new GriddingAlgorithm<NDIM>(\"GriddingAlgorithm\",\n                                        app_initializer->getComponentDatabase(\"GriddingAlgorithm\"),\n                                        error_detector,\n                                        box_generator,\n                                        load_balancer);\n\n        // Configure the IBFE solver.\n        ElasticityData elasticity_data(input_db);\n        void* const elasticity_data_ptr = reinterpret_cast<void*>(&elasticity_data);\n        IBFEMethod::LagBodyForceFcnData block_tether_force_data(\n            block_tether_force_function, std::vector<IBTK::SystemData>(), elasticity_data_ptr);\n        IBFEMethod::PK1StressFcnData block_PK1_stress_data(\n            block_PK1_stress_function, std::vector<IBTK::SystemData>(), elasticity_data_ptr);\n        ib_method_ops->registerLagBodyForceFunction(block_tether_force_data, 0);\n        ib_method_ops->registerPK1StressFunction(block_PK1_stress_data, 0);\n        string block_kernel_fcn = input_db->getStringWithDefault(\"BLOCK_KERNEL_FUNCTION\", \"PIECEWISE_LINEAR\");\n        FEDataManager::InterpSpec block_interp_spec = ib_method_ops->getDefaultInterpSpec();\n        block_interp_spec.kernel_fcn = block_kernel_fcn;\n        ib_method_ops->setInterpSpec(block_interp_spec, 0);\n        FEDataManager::SpreadSpec block_spread_spec = ib_method_ops->getDefaultSpreadSpec();\n        block_spread_spec.kernel_fcn = block_kernel_fcn;\n        ib_method_ops->setSpreadSpec(block_spread_spec, 0);\n\n        IBFEMethod::LagBodyForceFcnData beam_tether_force_data(\n            beam_tether_force_function, std::vector<IBTK::SystemData>(), elasticity_data_ptr);\n        IBFEMethod::PK1StressFcnData beam_PK1_stress_data(\n            beam_PK1_stress_function, std::vector<IBTK::SystemData>(), elasticity_data_ptr);\n        ib_method_ops->registerLagBodyForceFunction(beam_tether_force_data, 1);\n        ib_method_ops->registerPK1StressFunction(beam_PK1_stress_data, 1);\n        string beam_kernel_fcn = input_db->getStringWithDefault(\"BEAM_KERNEL_FUNCTION\", \"IB_3\");\n        FEDataManager::InterpSpec beam_interp_spec = ib_method_ops->getDefaultInterpSpec();\n        beam_interp_spec.kernel_fcn = beam_kernel_fcn;\n        ib_method_ops->setInterpSpec(beam_interp_spec, 1);\n        FEDataManager::SpreadSpec beam_spread_spec = ib_method_ops->getDefaultSpreadSpec();\n        beam_spread_spec.kernel_fcn = beam_kernel_fcn;\n        ib_method_ops->setSpreadSpec(beam_spread_spec, 1);\n\n        ib_method_ops->initializeFEEquationSystems();\n        EquationSystems* block_equation_systems = ib_method_ops->getFEDataManager(0)->getEquationSystems();\n        EquationSystems* beam_equation_systems = ib_method_ops->getFEDataManager(1)->getEquationSystems();\n\n        // Create Eulerian initial condition specification objects.\n        if (input_db->keyExists(\"VelocityInitialConditions\"))\n        {\n            Pointer<CartGridFunction> u_init = new muParserCartGridFunction(\n                \"u_init\", app_initializer->getComponentDatabase(\"VelocityInitialConditions\"), grid_geometry);\n            navier_stokes_integrator->registerVelocityInitialConditions(u_init);\n        }\n\n        if (input_db->keyExists(\"PressureInitialConditions\"))\n        {\n            Pointer<CartGridFunction> p_init = new muParserCartGridFunction(\n                \"p_init\", app_initializer->getComponentDatabase(\"PressureInitialConditions\"), grid_geometry);\n            navier_stokes_integrator->registerPressureInitialConditions(p_init);\n        }\n\n        // Create Eulerian boundary condition specification objects (when necessary).\n        const IntVector<NDIM>& periodic_shift = grid_geometry->getPeriodicShift();\n        vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM);\n        if (periodic_shift.min() > 0)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                u_bc_coefs[d] = NULL;\n            }\n        }\n        else\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                const std::string bc_coefs_name = \"u_bc_coefs_\" + std::to_string(d);\n\n                const std::string bc_coefs_db_name = \"VelocityBcCoefs_\" + std::to_string(d);\n\n                u_bc_coefs[d] = new muParserRobinBcCoefs(\n                    bc_coefs_name, app_initializer->getComponentDatabase(bc_coefs_db_name), grid_geometry);\n            }\n            navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs);\n        }\n\n        // Create Eulerian body force function specification objects.\n        if (input_db->keyExists(\"ForcingFunction\"))\n        {\n            Pointer<CartGridFunction> f_fcn = new muParserCartGridFunction(\n                \"f_fcn\", app_initializer->getComponentDatabase(\"ForcingFunction\"), grid_geometry);\n            time_integrator->registerBodyForceFunction(f_fcn);\n        }\n\n        // Set up visualization plot file writers.\n        Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter();\n        if (uses_visit)\n        {\n            time_integrator->registerVisItDataWriter(visit_data_writer);\n        }\n        std::unique_ptr<ExodusII_IO> block_exodus_io(uses_exodus ? new ExodusII_IO(block_mesh) : NULL);\n        std::unique_ptr<ExodusII_IO> beam_exodus_io(uses_exodus ? new ExodusII_IO(beam_mesh) : NULL);\n\n        // Check to see if this is a restarted run to append current exodus files\n        if (uses_exodus)\n        {\n            const bool from_restart = RestartManager::getManager()->isFromRestart();\n            block_exodus_io->append(from_restart);\n            beam_exodus_io->append(from_restart);\n        }\n\n        // Initialize hierarchy configuration and data on all patches.\n        ib_method_ops->initializeFEData();\n        time_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm);\n\n        // Deallocate initialization objects.\n        app_initializer.setNull();\n\n        // Print the input database contents to the log file.\n        plog << \"Input database:\\n\";\n        input_db->printClassData(plog);\n\n        // Write out initial visualization data.\n        int iteration_num = time_integrator->getIntegratorStep();\n        double loop_time = time_integrator->getIntegratorTime();\n        if (dump_viz_data)\n        {\n            pout << \"\\n\\nWriting visualization files...\\n\\n\";\n            if (uses_visit)\n            {\n                time_integrator->setupPlotData();\n                visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n            }\n            if (uses_exodus)\n            {\n                block_exodus_io->write_timestep(\n                    block_exodus_filename, *block_equation_systems, iteration_num / viz_dump_interval + 1, loop_time);\n                beam_exodus_io->write_timestep(\n                    beam_exodus_filename, *beam_equation_systems, iteration_num / viz_dump_interval + 1, loop_time);\n            }\n        }\n\n        // Open streams to save lift and drag coefficients.\n        if (IBTK_MPI::getRank() == 0)\n        {\n            drag_stream.open(\"C_D.curve\", ios_base::out | ios_base::trunc);\n            lift_stream.open(\"C_L.curve\", ios_base::out | ios_base::trunc);\n            A_x_posn_stream.open(\"A_x.curve\", ios_base::out | ios_base::trunc);\n            A_y_posn_stream.open(\"A_y.curve\", ios_base::out | ios_base::trunc);\n        }\n\n        // Main time step loop.\n        double loop_time_end = time_integrator->getEndTime();\n        double dt = 0.0;\n        while (!MathUtilities<double>::equalEps(loop_time, loop_time_end) && time_integrator->stepsRemaining())\n        {\n            iteration_num = time_integrator->getIntegratorStep();\n            loop_time = time_integrator->getIntegratorTime();\n\n            pout << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"At beginning of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n\n            dt = time_integrator->getMaximumTimeStepSize();\n            time_integrator->advanceHierarchy(dt);\n            loop_time += dt;\n\n            pout << \"\\n\";\n            pout << \"At end       of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"\\n\";\n\n            // At specified intervals, write visualization and restart files,\n            // print out timer data, and store hierarchy data for post\n            // processing.\n            iteration_num += 1;\n            const bool last_step = !time_integrator->stepsRemaining();\n            if (dump_viz_data && (iteration_num % viz_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting visualization files...\\n\\n\";\n                if (uses_visit)\n                {\n                    time_integrator->setupPlotData();\n                    visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n                }\n                if (uses_exodus)\n                {\n                    block_exodus_io->write_timestep(block_exodus_filename,\n                                                    *block_equation_systems,\n                                                    iteration_num / viz_dump_interval + 1,\n                                                    loop_time);\n                    beam_exodus_io->write_timestep(\n                        beam_exodus_filename, *beam_equation_systems, iteration_num / viz_dump_interval + 1, loop_time);\n                }\n            }\n            if (dump_restart_data && (iteration_num % restart_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting restart files...\\n\\n\";\n                RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num);\n                ib_method_ops->writeFEDataToRestartFile(restart_dump_dirname, iteration_num);\n            }\n            if (dump_timer_data && (iteration_num % timer_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting timer data...\\n\\n\";\n                TimerManager::getManager()->print(plog);\n            }\n            if (dump_postproc_data && (iteration_num % postproc_data_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting state data...\\n\\n\";\n                postprocess_data(patch_hierarchy,\n                                 navier_stokes_integrator,\n                                 beam_mesh,\n                                 beam_equation_systems,\n                                 block_mesh,\n                                 block_equation_systems,\n                                 iteration_num,\n                                 loop_time,\n                                 postproc_data_dump_dirname);\n            }\n        }\n\n        // Close the logging streams.\n        if (IBTK_MPI::getRank() == 0)\n        {\n            drag_stream.close();\n            lift_stream.close();\n            A_x_posn_stream.close();\n            A_y_posn_stream.close();\n        }\n\n        // Cleanup Eulerian boundary condition specification objects (when\n        // necessary).\n        for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d];\n\n    } // cleanup dynamically allocated objects prior to shutdown\n} // main\n\nvoid\npostprocess_data(Pointer<PatchHierarchy<NDIM> > /*patch_hierarchy*/,\n                 Pointer<INSHierarchyIntegrator> /*navier_stokes_integrator*/,\n                 Mesh& beam_mesh,\n                 EquationSystems* beam_equation_systems,\n                 Mesh& block_mesh,\n                 EquationSystems* block_equation_systems,\n                 const int /*iteration_num*/,\n                 const double loop_time,\n                 const string& /*data_dump_dirname*/)\n{\n    double F_integral[NDIM];\n    for (unsigned int d = 0; d < NDIM; ++d) F_integral[d] = 0.0;\n    Mesh* mesh[2] = { &beam_mesh, &block_mesh };\n    EquationSystems* equation_systems[2] = { beam_equation_systems, block_equation_systems };\n    for (unsigned int k = 0; k < 2; ++k)\n    {\n        System& F_system = equation_systems[k]->get_system<System>(IBFEMethod::FORCE_SYSTEM_NAME);\n        NumericVector<double>* F_vec = F_system.solution.get();\n        NumericVector<double>* F_ghost_vec = F_system.current_local_solution.get();\n        copy_and_synch(*F_vec, *F_ghost_vec);\n        DofMap& F_dof_map = F_system.get_dof_map();\n        std::vector<std::vector<unsigned int> > F_dof_indices(NDIM);\n        std::unique_ptr<FEBase> fe(FEBase::build(NDIM, F_dof_map.variable_type(0)));\n        std::unique_ptr<QBase> qrule = QBase::build(QGAUSS, NDIM, FIFTH);\n        fe->attach_quadrature_rule(qrule.get());\n        const std::vector<std::vector<double> >& phi = fe->get_phi();\n        const std::vector<double>& JxW = fe->get_JxW();\n        boost::multi_array<double, 2> F_node;\n        const MeshBase::const_element_iterator el_begin = mesh[k]->active_local_elements_begin();\n        const MeshBase::const_element_iterator el_end = mesh[k]->active_local_elements_end();\n        for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)\n        {\n            Elem* const elem = *el_it;\n            fe->reinit(elem);\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                F_dof_map.dof_indices(elem, F_dof_indices[d], d);\n            }\n            const int n_qp = qrule->n_points();\n            const int n_basis = static_cast<int>(F_dof_indices[0].size());\n            get_values_for_interpolation(F_node, *F_ghost_vec, F_dof_indices);\n            for (int qp = 0; qp < n_qp; ++qp)\n            {\n                for (int k = 0; k < n_basis; ++k)\n                {\n                    for (int d = 0; d < NDIM; ++d)\n                    {\n                        F_integral[d] += F_node[k][d] * phi[k][qp] * JxW[qp];\n                    }\n                }\n            }\n        }\n    }\n    IBTK_MPI::sumReduction(F_integral, NDIM);\n    if (IBTK_MPI::getRank() == 0)\n    {\n        drag_stream.precision(12);\n        drag_stream.setf(ios::fixed, ios::floatfield);\n        drag_stream << loop_time << \" \" << -F_integral[0] << endl;\n        lift_stream.precision(12);\n        lift_stream.setf(ios::fixed, ios::floatfield);\n        lift_stream << loop_time << \" \" << -F_integral[1] << endl;\n    }\n\n    System& X_system = beam_equation_systems->get_system<System>(IBFEMethod::COORDS_SYSTEM_NAME);\n    NumericVector<double>* X_vec = X_system.solution.get();\n    std::unique_ptr<NumericVector<Number> > X_serial_vec = NumericVector<Number>::build(X_vec->comm());\n    X_serial_vec->init(X_vec->size(), true, SERIAL);\n    X_vec->localize(*X_serial_vec);\n    DofMap& X_dof_map = X_system.get_dof_map();\n    vector<unsigned int> vars(2);\n    vars[0] = 0;\n    vars[1] = 1;\n    MeshFunction X_fcn(*beam_equation_systems, *X_serial_vec, X_dof_map, vars);\n    X_fcn.init();\n    DenseVector<double> X_A(2);\n    X_fcn(libMesh::Point(0.6, 0.2, 0), 0.0, X_A);\n    if (IBTK_MPI::getRank() == 0)\n    {\n        A_x_posn_stream.precision(12);\n        A_x_posn_stream.setf(ios::fixed, ios::floatfield);\n        A_x_posn_stream << loop_time << \" \" << X_A(0) << endl;\n        A_y_posn_stream.precision(12);\n        A_y_posn_stream.setf(ios::fixed, ios::floatfield);\n        A_y_posn_stream << loop_time << \" \" << X_A(1) << endl;\n    }\n    return;\n} // postprocess_data\n", "meta": {"hexsha": "5b710d23089a22363b39b34f78d7b4c0ef277710", "size": 31085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/IBFE/explicit/ex6/example.cpp", "max_stars_repo_name": "kkeonho/IBAMR", "max_stars_repo_head_hexsha": "50d5c37d8f2952abc21f05ab224f22003d23d6e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 264.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T12:11:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:10:37.000Z", "max_issues_repo_path": "examples/IBFE/explicit/ex6/example.cpp", "max_issues_repo_name": "kkeonho/IBAMR", "max_issues_repo_head_hexsha": "50d5c37d8f2952abc21f05ab224f22003d23d6e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1057.0, "max_issues_repo_issues_event_min_datetime": "2015-04-27T04:27:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:14:59.000Z", "max_forks_repo_path": "examples/IBFE/explicit/ex6/example.cpp", "max_forks_repo_name": "drwells/IBAMR", "max_forks_repo_head_hexsha": "0ceda3873405a35da4888c99e7d2b24d132f9071", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 126.0, "max_forks_repo_forks_event_min_datetime": "2015-02-13T15:36:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T21:59:50.000Z", "avg_line_length": 47.2416413374, "max_line_length": 120, "alphanum_fraction": 0.5912497989, "num_tokens": 6815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303285397348, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.41993712045654225}}
{"text": "#include \"TimeIntegrator.h\"\n\n#include <exception>\n#include <Eigen/Dense>\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/SparseLU>\n#include <cinder/Log.h>\n\nnamespace ar\n{\n    VectorX TimeIntegrator::solveDense(const MatrixX& A, const VectorX& b) const\n    {\n        switch (denseSolver)\n        {\n        case DenseLinearSolver::PartialPivLU: {return A.partialPivLu().solve(b); }\n        case DenseLinearSolver::FullPivLU:\n            {\n                Eigen::FullPivLU<MatrixX> decomp = A.fullPivLu();\n                decomp.setThreshold(1e-5);\n                int rank = decomp.rank();\n                if (rank == std::min(A.rows(), A.cols()))\n                    CI_LOG_D(\"rank is \" << decomp.rank() << \" (of \" << std::min(A.rows(), A.cols()) << \")\");\n                else\n                    CI_LOG_W(\"Matrix is not of full rank, only \" << rank << \" of \" << std::min(A.rows(), A.cols()));\n                return decomp.solve(b);\n            }\n        case DenseLinearSolver::HouseholderQR: {return A.householderQr().solve(b); }\n        case DenseLinearSolver::ColPivHousholderQR:\n            {\n                Eigen::ColPivHouseholderQR<MatrixX> decomp = A.colPivHouseholderQr();\n                int rank = decomp.rank();\n                if (rank == std::min(A.rows(), A.cols()))\n                    CI_LOG_D(\"rank is \" << decomp.rank() << \" (of \" << std::min(A.rows(), A.cols()) << \")\");\n                else\n                    CI_LOG_W(\"Matrix is not of full rank, only \" << rank << \" of \" << std::min(A.rows(), A.cols()));\n                return decomp.solve(b);\n            }\n        case DenseLinearSolver::FullPivHouseholderQR:\n            {\n                Eigen::FullPivHouseholderQR<MatrixX> decomp = A.fullPivHouseholderQr();\n                int rank = decomp.rank();\n                if (rank == std::min(A.rows(), A.cols()))\n                    CI_LOG_D(\"rank is \" << decomp.rank() << \" (of \" << std::min(A.rows(), A.cols()) << \")\");\n                else\n                    CI_LOG_W(\"Matrix is not of full rank, only \" << rank << \" of \" << std::min(A.rows(), A.cols()));\n                return decomp.solve(b);\n            }\n        case DenseLinearSolver::CompleteOrthogonalDecomposition: {return A.completeOrthogonalDecomposition().solve(b); }\n        case DenseLinearSolver::LLT: {return A.llt().solve(b); }\n        case DenseLinearSolver::LDLT: {return A.ldlt().solve(b); }\n        default: throw std::exception(\"unsupported solver\");\n        }\n    }\n\n    VectorX TimeIntegrator::solveSparse(const SparseMatrixRowMajor & A, const VectorX & b, const VectorX& guess) const\n    {\n        //TODO: do I want to support custom number of iterations and thesholds?\n        switch (sparseSolver)\n        {\n        case SparseLinearSolver::ConjugateGradient:\n            {\n                Eigen::ConjugateGradient<SparseMatrixRowMajor, Eigen::Lower | Eigen::Upper> cg;\n                if (sparseSolverIterations > 0) cg.setMaxIterations(sparseSolverIterations);\n                if (sparseSolverTolerance > 0) cg.setTolerance(sparseSolverTolerance);\n                cg.compute(A);\n                if (guess.size() > 0)\n                    return cg.solveWithGuess(b, guess);\n                else\n                    return cg.solve(b);\n            }\n        case SparseLinearSolver::BiCGSTAB:\n        {\n            Eigen::BiCGSTAB<SparseMatrixRowMajor> cg;\n            if (sparseSolverIterations > 0) cg.setMaxIterations(sparseSolverIterations);\n            if (sparseSolverTolerance > 0) cg.setTolerance(sparseSolverTolerance);\n            cg.compute(A);\n            if (guess.size() > 0)\n                return cg.solveWithGuess(b, guess);\n            else\n                return cg.solve(b);\n        }\n        case SparseLinearSolver::LU:\n        {\n            CI_LOG_E(\"Sparse LU does only work with column-major matrices\");\n            return VectorX::Zero(b.size());\n        }\n        default: throw std::exception(\"unsupported solver\");\n        }\n    }\n\n    VectorX TimeIntegrator::solveSparse(const SparseMatrixColumnMajor & A, const VectorX & b, const VectorX& guess) const\n    {\n        //TODO: do I want to support custom number of iterations and thesholds?\n        switch (sparseSolver)\n        {\n        case SparseLinearSolver::ConjugateGradient:\n        {\n            Eigen::ConjugateGradient<SparseMatrixColumnMajor, Eigen::Lower | Eigen::Upper> cg;\n            if (sparseSolverIterations > 0) cg.setMaxIterations(sparseSolverIterations);\n            if (sparseSolverTolerance > 0) cg.setTolerance(sparseSolverTolerance);\n            cg.compute(A);\n            if (guess.size() > 0)\n                return cg.solveWithGuess(b, guess);\n            else\n                return cg.solve(b);\n        }\n        case SparseLinearSolver::BiCGSTAB:\n        {\n            Eigen::BiCGSTAB<SparseMatrixColumnMajor> cg;\n            if (sparseSolverIterations > 0) cg.setMaxIterations(sparseSolverIterations);\n            if (sparseSolverTolerance > 0) cg.setTolerance(sparseSolverTolerance);\n            cg.compute(A);\n            if (guess.size() > 0)\n                return cg.solveWithGuess(b, guess);\n            else\n                return cg.solve(b);\n        }\n        case SparseLinearSolver::LU:\n        {\n            Eigen::SparseLU<SparseMatrixColumnMajor, Eigen::COLAMDOrdering<int>> lu;\n            lu.analyzePattern(A);\n            lu.factorize(A);\n            return lu.solve(b);\n        }\n        default: throw std::exception(\"unsupported solver\");\n        }\n    }\n\n    std::shared_ptr<TimeIntegrator> TimeIntegrator::createIntegrator(Integrator type, Eigen::Index dof)\n    {\n        switch (type)\n        {\n        case Integrator::Newmark1: return std::make_shared<TimeIntegrator_Newmark1>(dof);\n        case Integrator::Newmark2: return std::make_shared<TimeIntegrator_Newmark2>(dof);\n        case Integrator::ExplicitCentralDifferences: return std::make_shared<TimeIntegrator_ExplicitCentralDifferences>(dof);\n        case Integrator::ImplicitLinearAcceleartion: return std::make_shared<TimeIntegrator_ImplicitLinearAcceleration>(dof);\n        case Integrator::Newmark3: return std::make_shared<TimeIntegrator_Newmark3>(dof);\n        case Integrator::HHTAlpha: return std::make_shared<TimeIntegrator_HHTalpha>(dof);\n        default: throw std::exception(\"unknown integrator\");\n        }\n    }\n}\n", "meta": {"hexsha": "cbfba9df41dbef01098a033aded4ba604bd437de", "size": 6338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ActionReconstructionLib/TimeIntegrator1.cpp", "max_stars_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_stars_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-03-08T18:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T20:32:56.000Z", "max_issues_repo_path": "ActionReconstructionLib/TimeIntegrator1.cpp", "max_issues_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_issues_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ActionReconstructionLib/TimeIntegrator1.cpp", "max_forks_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_forks_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-26T01:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T13:32:46.000Z", "avg_line_length": 44.3216783217, "max_line_length": 125, "alphanum_fraction": 0.5804670243, "num_tokens": 1486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.41993711521347377}}
{"text": "/*\n\ncopyright (c) 2021, adrien blassiau and corentin juvigny\n\npermission to use, copy, modify, and/or distribute this software\nfor any purpose with or without fee is hereby granted, provided\nthat the above copyright notice and this permission notice appear\nin all copies.\n\nthe software is provided \"as is\" and the author disclaims all\nwarranties with regard to this software including all implied\nwarranties of merchantability and fitness. in no event shall the\nauthor be liable for any special, direct, indirect, or\nconsequential damages or any damages whatsoever resulting from\nloss of use, data or profits, whether in an action of contract,\nnegligence or other tortious action, arising out of or in\nconnection with the use or performance of this software.\n\n*/\n\n/** @file mip.cpp\n *\n * @brief Mixed integer algorithm to construct the optimal solution of the problem\n *\n */\n\n#define TBB_SUPPRESS_DEPRECATED_MESSAGES 1\n\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <algorithm>\n#include <mip.hpp>\n#include <utility>\n#include <ilcplex/ilocplex.h>\n\n#define EPSILON 10e-10\n\ntypedef std::map<Node<2>*,std::pair<IloNum,long>,Node<2>::NodeCmp> IloNumIndexMap;\ntypedef std::map<Node<2>*,IloNumVar,Node<2>::NodeCmp> IloNumVarMap;\ntypedef std::map<Node<2>*,IloNum,Node<2>::NodeCmp> IloNumMap;\ntypedef boost::adjacency_list < boost::vecS, boost::vecS, boost::undirectedS > graph_t;\ntypedef boost::graph_traits < graph_t >::vertex_descriptor vertex_descriptor;\n\nILOLAZYCONSTRAINTCALLBACK1( ValidityCallback\n                          , const IloNumVarMap&\n                          , X )\n{\n   IloNumIndexMap Xr;\n   size_t index = 0;\n#if 0\n   for (const auto &[name,value] : X)\n      Xr[name] = std::make_pair(getValue(value),index++);\n#else\n   for (const auto &[node,value] : X) {\n      IloInt x = getValue(value);\n      if ( abs(1 - x) <= EPSILON )\n         Xr[node] = std::make_pair(x,index++);\n      else\n         Xr[node] = std::make_pair(x,-1);\n   }\n#endif\n\n   graph_t graph;\n#if 0\n   for (struct {size_t i; IloNumIndexMap::const_iterator it;} ist = {0, Xr.cbegin()}; ist.it != Xr.cend(); ist.it++, ist.i++) {\n      for (struct {size_t j; IloNumIndexMap::const_iterator jt;} jst = {ist.i, ist.it}; jst.jt != Xr.cend(); jst.jt++, jst.j++) {\n         if ( abs(ist.it->second.first - 1) <= 10e-10\n            && (std::find( ist.it->first->communication_queue().cbegin()\n                         , ist.it->first->communication_queue().cend()\n                         , jst.jt->first ) != ist.it->first->communication_queue().end()) ) {\n            boost::add_edge(ist.i,jst.j,graph);\n         }\n      }\n   }\n#endif\n#if 1\n   for (const auto &[node,pair] : Xr) {\n      const auto [value1,index1] = pair;\n      if ( abs(value1 - 1) <= EPSILON ) {\n         for (const auto &neighbour : node->communication_queue()) {\n            const auto [value2,index2] = Xr[neighbour];\n            if ( abs(value2 - 1) <= EPSILON )\n               boost::add_edge(index1,index2,graph);\n         }\n      }\n   }\n#endif\n#if 0\n   std::vector<Node<2>*> nodes(X.size());\n   std::transform( Xr.cbegin()\n                 , Xr.cend()\n                 , nodes.begin()\n                 , [](const auto &node) { return node.first; });\n   for (size_t i = 0; i < nodes.size(); i++) {\n      for (size_t j = i+1; j < nodes.size(); j++) {\n         if ( Xr[nodes[i]].value == 1\n            && (std::find( nodes[i]->communication_queue().cbegin()\n                         , nodes[i]->communication_queue().cend()\n                         , nodes[j] ) != nodes[i]->communication_queue().end()) ) {\n            boost::add_edge(i,j,graph);\n         }\n      }\n   }\n\n#endif\n\n   std::vector<size_t> component(boost::num_vertices(graph));\n   size_t num = boost::connected_components(graph,&component[0]);\n\n   if ( num > 1 ) { // Graph is disconnected\n      IloExpr e(getEnv());\n      IloInt nbr = 0;\n      for (const auto &[node,tuple] : Xr) {\n         if ( tuple.first == 1 ) {\n            e += X.find(node)->second; \n            nbr++;\n         } else {\n            //e -= X.find(node)->second;\n         }\n      }\n      addLocal(e <= nbr-1);\n      e.end();\n   }\n}\n\nvoid mip_resolution_2D(Grid<2> &g)\n{      \n   IloEnv env;\n   \n   IloModel model(env);\n\n   // Decision var\n   IloNumVarMap X;\n   for (const auto &s : g.nodes()) { \n      std::stringstream ss;\n      ss << \"x_\" << s->name();\n      X[s.get()] = IloNumVar(env,0,1,ILOBOOL,ss.str().c_str());\n   }\n   \n   // Objective\n   IloExpr obj(env);\n   for (auto &x_s : X)\n      obj += x_s.second;\n   model.add(IloMinimize(env,obj,\"obj\"));\n   obj.end();\n\n   // Constraints\n   for (const auto &s : g.nodes()) {\n      IloExpr e_com(env);\n      IloExpr e_capt(env);\n      for (const auto &v : s->communication_queue())\n         e_com += X[v];\n      for (const auto &v : s->capture_queue())\n         e_capt += X[v];\n      model.add(e_com >= 1);\n      model.add(e_capt >= 1);\n      e_capt.end();\n      e_com.end();\n   }\n   model.add(X[g.well().get()] == 1);\n\n   IloCplex cplex(model);\n\n   cplex.setParam(IloCplex::Param::Threads,8);\n   cplex.setParam(IloCplex::Param::MIP::Strategy::File,1);\n   cplex.setParam(IloCplex::Param::MIP::Limits::Solutions,1000);\n   cplex.use(ValidityCallback(env,X));\n   cplex.solve();\n\n   IloAlgorithm::Status status = cplex.getStatus();\n   std::stringstream ss; \n   ss << \"Solution status:                   \" << cplex.getStatus();\n   std::string separator_line(ss.str().length(),'-');\n   std::cout << separator_line << std::endl;\n   std::cout << ss.str() << std::endl;\n   IloNumIndexMap Xr;\n   graph_t graph;\n   size_t index = 0;\n   switch ( status ) {\n      case IloAlgorithm::Optimal:\n         std::cout << \"Nodes processed:                   \" << cplex.getNnodes() << std::endl;\n         std::cout << \"Active user cuts/lazy constraints: \" << cplex.getNcuts(IloCplex::CutUser) << std::endl;\n         std::cout << \"Time elapsed:                      \" << cplex.getTime() << std::endl;\n         std::cout << \"Optimal value:                     \" << cplex.getObjValue()-1 << std::endl;\n         for (const auto &[node,value] : X) {\n            IloInt x = cplex.getValue(value);\n            if ( abs(1 - x) <= EPSILON )\n               Xr[node] = std::make_pair(x,index++);\n            else\n               Xr[node] = std::make_pair(x,-1);\n         }\n         for (const auto &v : g.nodes()) {\n            if ( Xr[v.get()].first == 1 ) {\n               typename Node<2>::Queue queue;\n               for (const auto &node : v->communication_queue())\n                  if ( Xr[node].first == 1 ) {\n                     queue.push_front(node);\n                  }\n               v->set_new_sensor(queue);\n            }\n         }\n         {\n            for (const auto &[node,pair] : Xr) {\n               const auto [value1,index1] = pair;\n               if ( abs(value1 - 1) <= EPSILON ) {\n                  for (const auto &neighbour : node->communication_queue()) {\n                     const auto [value2,index2] = Xr[neighbour];\n                     if ( abs(value2 - 1) <= EPSILON ) {\n                        boost::add_edge(index1,index2,graph);\n                        std::cout << \"Node \"<<*node<<\" connected to node \"<<*neighbour<< \" with indices : \" << index1 << \" \" << index2 << std::endl;\n                     }\n                  }\n               }\n            }\n            std::vector<size_t> component(boost::num_vertices(graph));\n            long num = boost::connected_components(graph,&component[0]);\n            std::cout << \"Number of connected components \" << num << std::endl;\n            std::cout << \"Number of vertices in the graph : \" << boost::num_vertices(graph) << std::endl;\n\n            for (const auto &[node,pair] : Xr) {\n               const auto [value1,index1] = pair;\n               if ( abs(value1 - 1) <= EPSILON ) {\n                  std::cout << \"Node \" << *node << \" in component \" << component[index1] << std::endl;\n               }\n            }\n\n         }\n         break;\n      default:\n         break;\n   }\n   std::cout << separator_line << std::endl;\n\n   model.end();\n   cplex.end();\n   env.end();\n}\n", "meta": {"hexsha": "fb89660d6cff3c533245cd3c55045df7a3c65897", "size": 8143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpplib/src/mip.cpp", "max_stars_repo_name": "corentinjuvigny/PROJET_META", "max_stars_repo_head_hexsha": "e88af2bc6d10363ce747ce5baeba2cf34bad34e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpplib/src/mip.cpp", "max_issues_repo_name": "corentinjuvigny/PROJET_META", "max_issues_repo_head_hexsha": "e88af2bc6d10363ce747ce5baeba2cf34bad34e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpplib/src/mip.cpp", "max_forks_repo_name": "corentinjuvigny/PROJET_META", "max_forks_repo_head_hexsha": "e88af2bc6d10363ce747ce5baeba2cf34bad34e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0711297071, "max_line_length": 148, "alphanum_fraction": 0.5480781039, "num_tokens": 2184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4198689200097167}}
{"text": "/*\n * poh_color.hpp\n * Author: Aven Bross\n * \n * Implementation of Poh path 3-coloring algorithm for triangulated plane graphs\n * that traces a chordless path along the inside of the outer face.\n */\n\n#ifndef __POH_COLOR_HPP\n#define __POH_COLOR_HPP\n\n// STL headers\n#include <vector>\n#include <queue>\n#include <stdexcept>\n#include <utility>\n\n// Basic graph headers\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n\n// Local project headers\n#include \"incidence_list_helpers.hpp\"\n\n\n/*\n * poh_color_recursive\n * \n * assumptions: There are two disjoint colored paths P=p_0...p_n and Q=q_0...q_m\n *     such that p_0...p_nq_m...q_0 is a cycle, and all vertices on the interior\n *     of the subgrapph bounded by this cycle with at least one neighbor in P\n *     have been marked with an identifying integer.\n *\n * inputs: A weakly triangulated planar graph with vertex indices (predfined\n *     boost property), a valid planar embedding of the graph modeling the boost\n *     PlanarEmbedding concept, a read-write-able vertex property map to store\n *     vertex colors, a read-write-able vertex property map to store integer\n *     marks for BFS, a read-write-able vertex property map to store start and\n *     stop iterators in each incidence list, the vertex u such that p_0uq_0\n *     is a triangle, the integer mark for vertices with neighbors in P, an\n *     unsigned integer count such that all vertex marks assigned so far are\n *     less than count, and finally the color for the path T to be constructed,\n *     the color of the path P, and the color of the path Q.\n *\n * output: The coloring vertex property will contain a valid path 3-coloring of\n *     the subgraph bounded by p_0...p_nq_m...q_0 such that no interior vertex\n *     shares a color with a neighbor in P or Q.\n */\n\nnamespace {\n    template<\n            typename graph_t, typename planar_embedding_t, typename color_map_t,\n            typename mark_map_t, typename neighbor_range_map_t,\n            typename color_t, typename vertex_t\n                = typename boost::graph_traits<graph_t>::vertex_descriptor\n        >\n    void poh_color_recursive(\n            const graph_t & graph, const planar_embedding_t & planar_embedding,\n            color_map_t & color_map, mark_map_t & mark_map,\n            neighbor_range_map_t & neighbor_range_map, vertex_t u,\n            int face_mark, int count,\n            color_t t_color, color_t p_color, color_t q_color\n        )\n    {\n        // t_i will track the last vertex of T, and w the first interior vertex\n        vertex_t t_i = u, w = u;\n    \n        // Initialize remaining variables for the loop constructing T\n        auto edge_iter = neighbor_range_map[u].first;\n        int below_t_mark = count++;\n        color_map[u] = t_color;\n    \n        // If u is the only remaining interior vertex we are are done\n        if(neighbor_range_map[u].first == neighbor_range_map[u].second){\n            return;\n        }\n    \n        // Construct the path T one vertex at a time, with current vertex t_i\n        while(edge_iter++ != neighbor_range_map[t_i].second)\n        {\n            // If we hit the end of the incidence list, wrap to the start\n            if(edge_iter == planar_embedding[t_i].end())\n                edge_iter = planar_embedding[t_i].begin();\n        \n            vertex_t n = get_incident_vertex(t_i, *edge_iter, graph);\n        \n            // Note if the vertex n may be added to T\n            bool continue_path = (mark_map[n] == face_mark\n                && color_map[n] != p_color && color_map[n] != q_color);\n        \n            // If we will add n to T or we hit the end, color vertices above T\n            if(continue_path || color_map[n] == p_color) {\n                if(continue_path) {\n                    color_map[n] = t_color;\n                }\n            \n                vertex_t l = n;\n            \n                // Loop through neighbors of t_i that lie above T\n                while(edge_iter++ != neighbor_range_map[t_i].second) {\n                    // If we hit the end of the list, wrap to the start\n                    if(edge_iter == planar_embedding[t_i].end())\n                        edge_iter = planar_embedding[t_i].begin();\n                \n                    vertex_t v = get_incident_vertex(t_i, *edge_iter, graph);\n                \n                    // If v is in P and l is uncolored, make recursive call\n                    if(color_map[v] == p_color)\n                    {\n                        if(color_map[l] != p_color && color_map[l] != q_color\n                            && color_map[l] != t_color)\n                        {\n                            poh_color_recursive(\n                                    graph, planar_embedding, color_map,\n                                    mark_map, neighbor_range_map, l, face_mark,\n                                    count, q_color, p_color, t_color\n                                );\n                        }\n                    }\n                \n                    l = v;\n                }\n            \n                // If we are adding n to T, setup next loop with t_i = n\n                if(continue_path) {\n                    auto n_back_iter = find_edge_iterator_restricted(\n                            n, t_i, neighbor_range_map[n].first,\n                            neighbor_range_map[n].second, planar_embedding,\n                            graph\n                        );\n            \n                    neighbor_range_map[n].first = n_back_iter;\n                    edge_iter = n_back_iter;\n                    t_i = n;\n                }\n                // Otherwise we have completed T and we are done\n                else {\n                    return;\n                }\n            }\n            // If n is in Q we have an edge T to Q and may split along it\n            else if(color_map[n] == q_color) {\n                // Color the left cycle if it has uncolored vertices\n                if(w != u) {\n                    poh_color_recursive(\n                            graph, planar_embedding, color_map, mark_map,\n                            neighbor_range_map, w, below_t_mark, count,\n                            p_color, t_color, q_color\n                        );\n                \n                    u = t_i;\n                    w = t_i;\n                }\n            }\n            // If n is interior and has not been visited, mark and initialize it\n            else if(mark_map[n] != below_t_mark) {\n                auto back_iter = find_edge_iterator(\n                        n, t_i, planar_embedding, graph\n                    );\n            \n                // If this is the first interior vertex hit, save it as w\n                if(w == u) {\n                    w = n;\n                }\n            \n                // Increment back_iter counterclockwise, wrapping in list \n                if(++back_iter == planar_embedding[n].end()) {\n                    back_iter = planar_embedding[n].begin();\n                }\n            \n                initialize_neighbor_range(\n                        n, back_iter, neighbor_range_map, planar_embedding\n                    );\n                mark_map[n] = below_t_mark;\n            }\n        }\n    }\n}\n\n\n/*\n * poh_color\n * \n * inputs: A weakly triangulated planar graph with vertex indices (predfined\n *     boost property), a valid planar embedding of the graph modeling the boost\n *     PlanarEmbedding concept, a read-write-able vertex property map to store\n *     vertex colors, pairs of bidirectional iterators for lists of vertices\n *     of two disjoint colored paths P=p_0...p_n and Q=q_0...q_m such that\n *     p_0...p_nq_m...q_0 is a cycle, and three colors for the path 3-coloring.\n *\n * output: The coloring vertex property will contain a valid path 3-coloring of\n *     the subgraph bounded by p_0...p_nq_m...q_0 such that vertices in P are\n *     recieve the first color, vertices in Q the second color, and no interior\n *     vertex shares a color with a neighbor in P or Q.\n */\n\ntemplate<\n        typename graph_t,\n        typename planar_embedding_t,\n        typename color_map_t,\n        typename mark_map_t,\n        typename neighbor_range_map_t,\n        typename vertex_iterator_t,\n        typename color_t\n    >\nvoid poh_color(\n        const graph_t & graph,\n        const planar_embedding_t & planar_embedding,\n        vertex_iterator_t p_begin, vertex_iterator_t p_end,\n        vertex_iterator_t q_begin, vertex_iterator_t q_end,\n        color_t c_0, color_t c_1, color_t c_2,\n        neighbor_range_map_t & neighbor_range_map,\n        mark_map_t & mark_map,\n        color_map_t & color_map\n    )\n{\n    // Type definitions\n    typedef typename boost::graph_traits<graph_t>::vertex_descriptor vertex_t;\n    \n    // Intitialize neighbor ranges for vertices in the path P\n    vertex_t l = *q_begin;\n    for(vertex_iterator_t p_iter = p_begin; p_iter != p_end; ++p_iter) {\n        vertex_t v = *p_iter;\n        \n        auto back_iter = find_edge_iterator(v, l, planar_embedding, graph);\n        initialize_neighbor_range(\n                v, back_iter, neighbor_range_map, planar_embedding\n            );\n        \n        l = v;\n    }\n    \n    // Color the path Q\n    for(vertex_iterator_t q_iter = q_begin; q_iter != q_end; ++q_iter) {\n        vertex_t v = *q_iter;\n        \n        color_map[v] = c_1;\n    }\n    \n    // Construct the path 3-coloring\n    poh_color_recursive(\n            graph, planar_embedding, color_map, mark_map,\n            neighbor_range_map, *p_begin, 1, 2,\n            c_0, c_2, c_1\n        );\n}\n\n/*\n * A wrapper that automatically constructs fast property maps for the mark_map\n * and neighbor_range_map, but requires that graph_t is some definition of\n * boost::adjacency_list.\n */\n\ntemplate<\n        typename graph_t,\n        typename planar_embedding_t,\n        typename color_map_t,\n        typename vertex_iterator_t,\n        typename color_t\n    >\nvoid poh_color(\n        const graph_t & graph,\n        const planar_embedding_t & planar_embedding,\n        vertex_iterator_t p_begin, vertex_iterator_t p_end,\n        vertex_iterator_t q_begin, vertex_iterator_t q_end,\n        color_t c_0, color_t c_1, color_t c_2,\n        color_map_t & color_map\n    )\n{\n    // Vertex property map type to store vertex marks\n    typedef boost::iterator_property_map<\n            std::vector<int>::iterator,\n            typename boost::property_map<\n                    graph_t, boost::vertex_index_t\n                >::const_type\n        > integer_property_map_t;\n    \n    // Vertex property map type for the neighbor ranges of planar_embedding_t\n    typedef typename boost::property_traits<planar_embedding_t>::value_type\n            ::const_iterator embedding_iterator_t;\n    typedef typename std::vector<\n            std::pair<embedding_iterator_t, embedding_iterator_t>\n        > neighbor_range_storage_t;\n    typedef boost::iterator_property_map<\n            typename neighbor_range_storage_t::iterator,\n            typename boost::property_map<\n                    graph_t, boost::vertex_index_t\n                >::const_type\n        > neighbor_range_map_t;\n    \n    // Construct a vertex property map to store vertex marks\n    std::vector<int> mark_storage(boost::num_vertices(graph));\n    integer_property_map_t mark_map(\n            mark_storage.begin(), boost::get(boost::vertex_index, graph)\n        );\n    \n    // Construct a vertex property map to store neighbor ranges\n    neighbor_range_storage_t neighbor_range_storage(num_vertices(graph));\n    neighbor_range_map_t neighbor_range_map(\n            neighbor_range_storage.begin(),\n            boost::get(boost::vertex_index, graph)\n        );\n    \n    // Construct the path 3-coloring\n    poh_color(\n            graph,\n            planar_embedding,\n            p_begin, p_end,\n            q_begin, q_end,\n            1, 2, 3,\n            neighbor_range_map,\n            mark_map,\n            color_map\n        );\n}\n\n#endif\n", "meta": {"hexsha": "58860b11afdf0057b2c05ef61e746f4c553aa794", "size": 12010, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/path_coloring/poh_color.hpp", "max_stars_repo_name": "permutationlock/path_coloring_bgl", "max_stars_repo_head_hexsha": "ec8ca14faadfdf65f7dcab9aef5a91d82dc7d6d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/include/path_coloring/poh_color.hpp", "max_issues_repo_name": "permutationlock/path_coloring_bgl", "max_issues_repo_head_hexsha": "ec8ca14faadfdf65f7dcab9aef5a91d82dc7d6d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/path_coloring/poh_color.hpp", "max_forks_repo_name": "permutationlock/path_coloring_bgl", "max_forks_repo_head_hexsha": "ec8ca14faadfdf65f7dcab9aef5a91d82dc7d6d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6489028213, "max_line_length": 80, "alphanum_fraction": 0.5800999167, "num_tokens": 2600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4198428145312696}}
{"text": "#pragma once\n\n#include <boost/functional/hash.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/laguerre.hpp>\n#include <stdexcept>\n\n#include \"spectral/basis/spectral_function/spectral_function_base.hpp\"\n#include \"spectral/basis/spectral_function/spectral_weight_function.hpp\"\n\n\nnamespace boltzmann {\n\nnamespace local_ {\nstruct laguerreKS_id_t\n{\n private:\n  constexpr const static double FUZZY = 1e6;\n\n public:\n  typedef laguerreKS_id_t id_t;\n\n  /// Default constructor\n  laguerreKS_id_t()\n      : j(std::nan(\"nan\"))\n      , k(std::nan(\"nan\"))\n      , fw(std::nan(\"nan\"))\n      , idw(std::nan(\"nan\"))\n  {\n  }\n\n  laguerreKS_id_t(int k_, int j_, double fw_)\n      : j(j_)\n      , k(k_)\n      , fw(fw_)\n      , idw(FUZZY * fw_)\n  {\n  }\n\n  laguerreKS_id_t(const id_t& id)\n      : j(id.j)\n      , k(id.k)\n      , fw(id.fw)\n      , idw(id.idw)\n  {\n  }\n\n  /// order parameter\n  int j;\n  /// Polynomial degree\n  int k;\n  /// weight exponent\n  double fw;\n  /// weight id\n  long int idw;\n\n  bool operator<(const id_t& other) const\n  {\n    return std::tie(j, k, idw) < std::tie(other.j, other.k, other.idw);\n    //#warning \"fix this!\"\n    //    return k < other.k;\n  }\n\n  // ----------------------------------------------------------------------\n  inline bool operator==(const id_t& other) const\n  {\n    return std::tie(j, k, idw) == std::tie(other.j, other.k, other.idw);\n    //#warning \"fix this!\"\n    //    return k == other.k;\n  }\n\n  // ----------------------------------------------------------------------\n  friend std::ostream& operator<<(std::ostream& stream, const id_t& x)\n  {\n    stream << x.to_string();\n    return stream;\n  }\n\n  // ----------------------------------------------------------------------\n  std::string to_string() const\n  {\n    return \"(fw_\" + boost::lexical_cast<std::string>(fw) + \", k_\" +\n           boost::lexical_cast<std::string>(k) + \", j_\" + boost::lexical_cast<std::string>(j) +\n           \") \";\n  }\n\n  // ----------------------------------------------------------------------\n  inline std::tuple<int, int, long int> key() const { return std::make_tuple(j, k, idw); }\n};\n}  // end namespace local_\n}  // end namespace boltzmann\n\nnamespace std {\n// hash functions for id's\ntemplate <>\nclass hash<boltzmann::local_::laguerreKS_id_t>\n{\n public:\n  size_t operator()(const boltzmann::local_::laguerreKS_id_t& id) const\n  {\n    std::size_t current = std::hash<double>()(id.fw);\n    boost::hash_combine(current, std::hash<int>()(id.k));\n    boost::hash_combine(current, std::hash<int>()(id.j));\n    return current;\n  }\n};\n}  // end namespace std\n\nnamespace boltzmann {\n\n/**\n * @brief Laguerre Radial Polynomial used by Kitzler & Schoeberl\n *\n * Normalization & Orthogonality\n * =============================\n *\n * For \\f$ k_1 \\equiv k_2 \\operatorname{mod} 2 \\f$, \\f$k_1\\f$ even:\n * \\f[\n *   \\int_0^{\\infty} r^{2j}  r^{2j} L^{(2j)}_{\\frac{k_1}{2}-j}(r^2)\n * L^{(2j)}_{\\frac{k_2}{2}-j} (r^2) e^{-r^2}\\; r \\operatorname{d} r= \\frac{1}{2} \\delta_{k_1, k_2}\n * \\f]\n *\n *  For \\f$ k_1 \\equiv k_2 \\operatorname{mod} 2 \\f$, \\f$k_1\\f$ odd:\n * \\f[\n *   \\int_0^{\\infty} r^{2j+1}  r^{2j+1} L^{(2j+1)}_{\\frac{k_1-1}{2}-j}(r^2)\n * L^{(2j+1)}_{\\frac{k_2-1}{2}-j} (r^2) e^{-r^2}\\; r \\operatorname{d} r= \\frac{1}{2} \\delta_{k_1,\n * k_2}\n * \\f]\n *\n */\nclass LaguerreKS : public weighted<LaguerreKS, true>,\n                   public local_::index_policy<local_::laguerreKS_id_t>\n{\n public:\n  typedef double numeric_t;\n\n public:\n  /**\n   * @brief Basis functions of the form \\f$ r^{2*j + k\\mod2} L_{(k-k\\mod2)/2-j}^{2*j + k\\mod2}(r^2)\n   * \\f$\n   *\n   *\n   * @param k  polynomial degree\n   * @param j  angular parameter\n   * @param w  weight\n   *\n   * @return\n   */\n  explicit LaguerreKS(int k, int j, double w = 0.5);\n  explicit LaguerreKS(const id_t& id)\n      : id_(id)\n  {\n  }\n  LaguerreKS(){};\n\n  /// evaluate polynomial part\n  numeric_t evaluate(double r) const;\n\n  /// evaluate weight\n  numeric_t weight(double r) const;\n\n  /// return weight\n  numeric_t w() const { return id_.fw; }\n\n  const id_t& get_id() const { return id_; }\n\n  unsigned int get_order() const { return 2 * id_.j + id_.k % 2; }\n  unsigned int get_degree() const { return id_.k / 2 - id_.j; }\n\n private:\n  id_t id_;\n};\n\n// ----------------------------------------------------------------------\ninline LaguerreKS::LaguerreKS(int k, int j, double w)\n    : id_(k, j, w)\n{\n  if (j > k / 2) {\n    std::runtime_error(\"invalid combination of parameters in LaguerreKS\");\n  }\n}\n\n// ----------------------------------------------------------------------\ninline typename LaguerreKS::numeric_t\nLaguerreKS::evaluate(double r) const\n{\n  int alpha = 2 * id_.j + (id_.k % 2);\n  int n = id_.k / 2 - id_.j;\n\n  // normalization factor\n  double a = 1;\n  for (int i = n + alpha; i > n; --i) {\n    a *= i;\n  }\n\n  return std::pow(r, 2 * id_.j + (id_.k % 2)) * boost::math::laguerre(n, alpha, r * r) /\n         std::sqrt(a);\n}\n\n// ----------------------------------------------------------------------\ninline typename LaguerreKS::numeric_t\nLaguerreKS::weight(double r) const\n{\n  return std::exp(-r * r * id_.fw);\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "323210bca9b4f6a9ce24db026b2aefa2b778e860", "size": 5192, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/basis/spectral_function/spectral_ks_radial.hpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spectral/basis/spectral_function/spectral_ks_radial.hpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spectral/basis/spectral_function/spectral_ks_radial.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8421052632, "max_line_length": 99, "alphanum_fraction": 0.5398690293, "num_tokens": 1599, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4198428145312696}}
{"text": "#pragma once\n#include <random>\n#include <bitset>\n#include <fstream>\n#include <ios>\n#include <string>\n#include <cassert>\n#include <Eigen/Eigen>\n\n#include <tbb/tbb.h>\n\n#include <nlohmann/json.hpp>\n\n#include \"Utilities/type_traits.hpp\"\n#include \"Utilities/Utility.hpp\"\n#include \"Serializers/SerializeEigen.hpp\"\n\nnamespace yannq\n{\n//! \\ingroup Machines\n//! RBM machine\ntemplate<typename T>\nclass RBM\n{\n\tstatic_assert(std::is_floating_point<T>::value || is_complex_type<T>::value, \"T must be floating or complex\");\npublic:\n\tusing Scalar = T;\n\tusing RealScalar = typename yannq::remove_complex<T>::type;\n\n\tusing Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\tusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\tusing VectorRef = Eigen::Ref<Vector>;\n\tusing VectorConstRef = Eigen::Ref<const Vector>;\n\n\tusing RealVector = Eigen::Matrix<RealScalar, Eigen::Dynamic, 1>;\n\t\n\tusing DataT = std::tuple<Eigen::VectorXi, Vector>;\n\nprivate:\n\tuint32_t n_; //# of qubits\n\tuint32_t m_; //# of hidden units\n\n\tbool useBias_;\n\n\tMatrix W_; //W should be m by n\n\tVector a_; //a is length n\n\tVector b_; //b is length m\n\npublic:\n\tRBM(uint32_t n, uint32_t m, bool useBias = true) noexcept\n\t\t: n_(n), m_(m), useBias_(useBias), W_(m, n), a_(n), b_(m) \n\t{\n\t\ta_.setZero();\n\t\tb_.setZero();\n\t\tW_.setZero();\n\t}\n\n\tRBM() noexcept\n\t\t: useBias_{true}\n\t{\n\t}\n\n\n\ttemplate<typename U, std::enable_if_t<std::is_convertible_v<U, T> && !std::is_same_v<U, T>, int> = 0>\n\tRBM(const RBM<U>& rhs) \n\t\t: n_{rhs.getN()}, m_{rhs.getM()}, useBias_{rhs.useBias()}\n\t{\n\t\tW_ = rhs.getW().template cast<T>();\n\t\ta_ = rhs.getA().template cast<T>();\n\t\tb_ = rhs.getB().template cast<T>();\n\t}\n\n\tRBM(const RBM& rhs) /* noexcept */ = default;\n\tRBM(RBM&& rhs) /* noexcept */ = default;\n\n\ttemplate<typename U, std::enable_if_t<std::is_convertible_v<U, T> && !std::is_same_v<U, T>, int> = 0>\n\tRBM& operator=(const RBM<U>& rhs) \n\t{\n\t\tn_ = rhs.n_;\n\t\tm_ = rhs.m_;\n\t\tuseBias_ = rhs.useBias_;\n\n\t\tW_ = rhs.W_.template cast<T>();\n\t\ta_ = rhs.a_.template cast<T>();\n\t\tb_ = rhs.b_.template cast<T>();\n\n\t\treturn *this;\n\t}\n\n\tRBM& operator=(const RBM& rhs) /* noexcept */ = default;\n\tRBM& operator=(RBM&& rhs) /* noexcept */ = default;\n\n\n\ttemplate<typename U, std::enable_if_t<std::is_convertible_v<T, U>, int> = 0>\n\tRBM<U> cast() const\n\t{\n\t\tRBM<U> res(n_, m_, useBias_);\n\t\tres.setA(a_.template cast<U>());\n\t\tres.setB(b_.template cast<U>());\n\t\tres.setW(W_.template cast<U>());\n\t\treturn res;\n\t}\n\n\tnlohmann::json desc() const\n\t{\n\t\treturn nlohmann::json\n\t\t{\n\t\t\t{\"name\", \"RBM\"},\n\t\t\t{\"useBias\", useBias_},\n\t\t\t{\"n\", n_},\n\t\t\t{\"m\", m_}\n\t\t};\n\t}\n\n\tinline uint32_t getN() const\n\t{\n\t\treturn n_;\n\t}\n\tinline uint32_t getM() const\n\t{\n\t\treturn m_;\n\t}\n\n\tinline uint32_t getDim() const\n\t{\n\t\tif(useBias_)\n\t\t\treturn n_*m_ + n_ + m_;\n\t\telse\n\t\t\treturn n_*m_;\n\t}\n\n\tinline bool useBias() const\n\t{\n\t\treturn useBias_;\n\t}\n\n\tinline Vector calcTheta(const Eigen::VectorXi& sigma) const\n\t{\n\t\tVector s = sigma.cast<T>();\n\t\treturn W_*s + b_;\n\t}\n\tinline Vector calcGamma(const Eigen::VectorXi& hidden) const\n\t{\n\t\tVector h = hidden.cast<T>();\n\t\treturn W_.transpose()*h + a_;\n\t}\n\t\n\tvoid setUseBias(bool newBias)\n\t{\n\t\tuseBias_ = newBias;\n\t}\n\n\tvoid resize(uint32_t n, uint32_t m)\n\t{\n\t\tn_ = n;\n\t\tm_ = m;\n\n\t\ta_.resize(n);\n\t\tb_.resize(m);\n\t\tW_.resize(m,n);\n\n\t\tif(!useBias_)\n\t\t{\n\t\t\ta_.setZero();\n\t\t\tb_.setZero();\n\t\t}\n\t}\n\n\tvoid conservativeResize(uint32_t newM)\n\t{\n\t\tVector newB = Vector::Zero(newM);\n\t\tnewB.head(m_) = b_;\n\n\t\tMatrix newW = Matrix::Zero(newM, n_);\n\t\tnewW.topRows(m_) = W_;\n\n\t\tm_ = newM;\n\t\tb_ = std::move(newB);\n\t\tW_ = std::move(newW);\n\t}\n\n\tvoid setW(const Eigen::Ref<const Matrix>& m)\n\t{\n\t\tassert(m.rows() == W_.rows() && m.cols() == W_.cols());\n\t\tW_ = m;\n\t}\n\n\tvoid setA(const VectorConstRef& A)\n\t{\n\t\tassert(A.size() == a_.size());\n\t\tif(!useBias_)\n\t\t\treturn ;\n\t\ta_ = A;\n\t}\n\n\tvoid setB(const VectorConstRef& B)\n\t{\n\t\tassert(B.size() == b_.size());\n\t\tif(!useBias_)\n\t\t\treturn ;\n\t\tb_ = B;\n\t}\n\n\n\tinline const T& W(uint32_t j, uint32_t i) const\n\t{\n\t\treturn W_.coeff(j,i);\n\t}\n\tinline const T& A(uint32_t i) const\n\t{\n\t\treturn a_.coeff(i);\n\t}\n\tinline const T& B(uint32_t j) const\n\t{\n\t\treturn b_.coeff(j);\n\t}\n\n\tinline T& W(uint32_t j, uint32_t i) \n\t{\n\t\treturn W_.coeffRef(j,i);\n\t}\n\tinline T& A(uint32_t i) \n\t{\n\t\treturn a_.coeffRef(i);\n\t}\n\tinline T& B(uint32_t j) \n\t{\n\t\treturn b_.coeffRef(j);\n\t}\n\n\t\n\tconst Matrix& getW() const & { return W_; } \n\tMatrix getW() && { return std::move(W_); } \n\n\tconst Vector& getA() const & { return a_; } \n\tVector getA() && { return std::move(a_); } \n\n\tconst Vector& getB() const & { return b_; } \n\tVector getB() && { return std::move(b_); } \n\n\n\t//! update Bias A by adding v\n\tvoid updateA(const VectorConstRef& v)\n\t{\n\t\tassert(useBias_);\n\t\ta_ += v;\n\t}\n\t//! update Bias B by adding v\n\tvoid updateB(const VectorConstRef& v)\n\t{\n\t\tassert(useBias_);\n\t\tb_ += v;\n\t}\n\t//! update the weight W by adding m\n\tvoid updateW(const Eigen::Ref<const Matrix>& m)\n\t{\n\t\tW_ += m;\n\t}\n\n\t//! update all parameters.\n\tvoid updateParams(const VectorConstRef& m)\n\t{\n\t\tassert(m.size() == getDim());\n\t\tW_ += Eigen::Map<const Matrix>(m.data(), m_, n_);\n\t\tif(!useBias_)\n\t\t\treturn ;\n\t\ta_ += Eigen::Map<const Vector>(m.data() + m_*n_, n_);\n\t\tb_ += Eigen::Map<const Vector>(m.data() + m_*n_ + n_, m_);\n\t}\n\n\tVector getParams() const\n\t{\n\t\tVector res(getDim());\n\t\tres.head(n_*m_) = Eigen::Map<const Vector>(W_.data(), W_.size());\n\t\tif(!useBias_)\n\t\t\treturn res;\n\n\t\tres.segment(n_*m_, n_) = a_;\n\t\tres.segment(n_*m_ + n_, m_) = b_;\n\t\treturn res;\n\t}\n\n\tvoid setParams(const VectorConstRef& r)\n\t{\n\t\tassert(r.size() == getDim());\n\t\tEigen::Map<Vector>(W_.data(), W_.size()) = r.head(n_*m_);\n\t\tif(!useBias_)\n\t\t\treturn ;\n\t\ta_ = r.segment(n_*m_, n_);\n\t\tb_ = r.segment(n_*m_ + n_, m_);\n\t}\n\n\tbool hasNaN() const\n\t{\n\t\treturn a_.hasNaN() || b_.hasNaN() || W_.hasNaN();\n\t}\n\n\t/* When T is real type */\n\ttemplate <typename RandomEngine, class U=T,\n            \tstd::enable_if_t < !is_complex_type<U>::value, int > = 0 >\n\tvoid initializeRandom(RandomEngine& re, T sigma = 1e-3)\n\t{\n\t\tstd::normal_distribution<T> nd{0, sigma};\n\t\tif(useBias_)\n\t\t{\n\t\t\tfor(uint32_t i = 0u; i < n_; i++)\n\t\t\t{\n\t\t\t\ta_.coeffRef(i) = nd(re);\n\t\t\t}\n\t\t\tfor(uint32_t i = 0u; i < m_; i++)\n\t\t\t{\n\t\t\t\tb_.coeffRef(i) = nd(re);\n\t\t\t}\n\t\t}\n\t\tfor(uint32_t j = 0u; j < n_; j++)\n\t\t{\n\t\t\tfor(uint32_t i = 0u; i < m_; i++)\n\t\t\t{\n\t\t\t\tW_.coeffRef(i, j) = nd(re);\n\t\t\t}\n\t\t}\n\t}\n\n\t/* When T is complex type */\n\ttemplate <typename RandomEngine, class U=T,\n               std::enable_if_t < is_complex_type<U>::value, int > = 0 >\n\tvoid initializeRandom(RandomEngine& re, typename remove_complex<T>::type sigma = 1e-3)\n\t{\n\t\tstd::normal_distribution<typename remove_complex<T>::type> nd{0, sigma};\n\t\t\n\t\tif(useBias_)\n\t\t{\n\t\t\tfor(uint32_t i = 0u; i < n_; i++)\n\t\t\t{\n\t\t\t\ta_.coeffRef(i) = T{nd(re), nd(re)};\n\t\t\t}\n\t\t\tfor(uint32_t i = 0u; i < m_; i++)\n\t\t\t{\n\t\t\t\tb_.coeffRef(i) = T{nd(re), nd(re)};\n\t\t\t}\n\t\t}\n\t\tfor(uint32_t j = 0; j < n_; j++)\n\t\t{\n\t\t\tfor(uint32_t i = 0u; i < m_; i++)\n\t\t\t{\n\t\t\t\tW_.coeffRef(i, j) = T{nd(re), nd(re)};\n\t\t\t}\n\t\t}\n\t}\n\n\tbool operator==(const RBM<T>& rhs) const\n\t{\n\t\tif(n_ != rhs.n_ || m_ != rhs.m_)\n\t\t\treturn false;\n\t\tbool equalW = (W_ == rhs.W_);\n\t\tif(useBias_)\n\t\t\treturn equalW && (a_ == rhs.a_) && (b_ == rhs.b_);\n\t\telse\n\t\t\treturn equalW;\n\t}\n\n\tstd::tuple<Eigen::VectorXi, Vector> makeData(const Eigen::VectorXi& sigma) const\n\t{\n\t\treturn std::make_tuple(sigma, calcTheta(sigma));\n\t}\n\n\tT logCoeff(const std::tuple<Eigen::VectorXi, Vector>& t) const\n\t{\n\t\tusing std::cosh;\n\n\t\tVector ss = std::get<0>(t).template cast<T>();\n\t\tT s = a_.transpose()*ss;\n\t\tfor(uint32_t j = 0u; j < m_; j++)\n\t\t{\n\t\t\ts += logCosh(std::get<1>(t).coeff(j));\n\t\t}\n\t\treturn s;\n\t}\n\n\tT coeff(const std::tuple<Eigen::VectorXi, Vector>& t) const\n\t{\n\t\tusing std::cosh;\n\n\t\tVector ss = std::get<0>(t).template cast<T>();\n\t\tT s = a_.transpose()*ss;\n\t\tT p = exp(s) * std::get<1>(t).array().cosh().prod();\n\t\treturn p;\n\t}\n\n\tVector logDeriv(const std::tuple<Eigen::VectorXi, Vector>& t) const \n\t{ \n\t\tVector res(getDim()); \n\n\t\tVector tanhs = std::get<1>(t).array().tanh(); \n\t\tVector sigma = std::get<0>(t).template cast<Scalar>();\n\t\t\n\t\tfor(uint32_t i = 0u; i < n_; i++) \n\t\t{ \n\t\t\tres.segment(i*m_, m_) = sigma(i)*tanhs; \n\t\t}\n\t\tif(!useBias_)\n\t\t\treturn res;\n\t\tres.segment(n_*m_, n_) = sigma;\n\t\tres.segment(n_*m_ + n_, m_) = tanhs; \n\t\treturn res; \n\t} \n};\n\n\ntemplate<typename T>\ntypename RBM<T>::Vector getPsi(const RBM<T>& qs, bool normalize)\n{\n\tconst uint32_t n = qs.getN();\n\ttypename RBM<T>::Vector psi(1u<<n);\n\ttbb::parallel_for(0u, (1u << n),\n\t\t[n, &qs, &psi](uint32_t idx)\n\t{\n\t\tauto s = toSigma(n, idx);\n\t\tpsi(idx) = qs.coeff(qs.makeData(s));\n\t});\n\tif(normalize)\n\t\tpsi.normalize();\n\treturn psi;\n}\n\ntemplate<typename T, typename Iterable> //Iterable must be random access iterable\ntypename RBM<T>::Vector getPsi(const RBM<T>& qs, Iterable&& basis, bool normalize)\n{\n\tconst uint32_t n = qs.getN();\n\ttypename RBM<T>::Vector psi(basis.size());\n\n\ttbb::parallel_for(std::size_t(0u), basis.size(),\n\t\t[n, &qs, &psi, &basis](std::size_t idx)\n\t{\n\t\tauto s = toSigma(n, basis[idx]);\n\t\tpsi(idx) = qs.coeff(qs.makeData(s));\n\t});\n\tif(normalize)\n\t\tpsi.normalize();\n\treturn psi;\n}\ntemplate<typename T>\ntypename RBM<T>::RealVector getProbs(const RBM<T>& qs, bool normalize)\n{\n\treturn getPsi(qs, normalize).cwiseAbs2();\n}\n\ntemplate<typename T, typename Iterable> //Iterable must be random access iterable\ntypename RBM<T>::RealVector getProbs(const RBM<T>& qs, Iterable&& basis, bool normalize)\n{\n\treturn getPsi(qs, std::forward<Iterable>(basis), normalize).cwiseAbs2();\n}\n}//namespace yannq\n", "meta": {"hexsha": "d3e2f2a19dd747827834dcb1d3bcab2905bfb80b", "size": 9456, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Machines/RBM.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Machines/RBM.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Machines/RBM.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8281938326, "max_line_length": 111, "alphanum_fraction": 0.6144247039, "num_tokens": 3143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4198428145312696}}
{"text": "\r\n// Copyright Aleksey Gurtovoy 2001-2004\r\n//\r\n// Distributed under the Boost Software License, Version 1.0. \r\n// (See accompanying file LICENSE_1_0.txt or copy at \r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// See http://www.boost.org/libs/mpl for documentation.\r\n\r\n// $Id: integer.cpp 49268 2008-10-11 06:26:17Z agurtovoy $\r\n// $Date: 2008-10-11 02:26:17 -0400 (Sat, 11 Oct 2008) $\r\n// $Revision: 49268 $\r\n\r\n#include <boost/mpl/multiplies.hpp>\r\n#include <boost/mpl/list.hpp>\r\n#include <boost/mpl/lower_bound.hpp>\r\n#include <boost/mpl/transform_view.hpp>\r\n#include <boost/mpl/sizeof.hpp>\r\n#include <boost/mpl/int.hpp>\r\n#include <boost/mpl/identity.hpp>\r\n#include <boost/mpl/base.hpp>\r\n#include <boost/mpl/eval_if.hpp>\r\n#include <boost/mpl/deref.hpp>\r\n#include <boost/mpl/begin_end.hpp>\r\n#include <boost/mpl/assert.hpp>\r\n\r\n#include <boost/type_traits/is_same.hpp>\r\n\r\nnamespace mpl = boost::mpl;\r\nusing namespace mpl::placeholders;\r\n\r\ntemplate< int bit_size >\r\nclass big_int\r\n{\r\n    // ...\r\n};\r\n\r\ntemplate< int bit_size >\r\nstruct integer\r\n{\r\n    typedef mpl::list<char,short,int,long> builtins_;\r\n    typedef typename mpl::base< typename mpl::lower_bound<\r\n          mpl::transform_view< builtins_\r\n            , mpl::multiplies< mpl::sizeof_<_1>, mpl::int_<8> >\r\n            >\r\n        , mpl::int_<bit_size>\r\n        >::type >::type iter_;\r\n\r\n    typedef typename mpl::end<builtins_>::type last_;\r\n    typedef typename mpl::eval_if<\r\n          boost::is_same<iter_,last_>\r\n        , mpl::identity< big_int<bit_size> >\r\n        , mpl::deref<iter_>\r\n        >::type type;\r\n};\r\n\r\ntypedef integer<1>::type int1;\r\ntypedef integer<5>::type int5;\r\ntypedef integer<15>::type int15;\r\ntypedef integer<32>::type int32;\r\ntypedef integer<100>::type int100;\r\n\r\nBOOST_MPL_ASSERT(( boost::is_same< int1, char > ));\r\nBOOST_MPL_ASSERT(( boost::is_same< int5, char > ));\r\nBOOST_MPL_ASSERT(( boost::is_same< int15, short > ));\r\nBOOST_MPL_ASSERT(( boost::is_same< int32, int > ));\r\nBOOST_MPL_ASSERT(( boost::is_same< int100, big_int<100> > ));\r\n", "meta": {"hexsha": "f3e369c942c1dd327ca05da52da4d015e886937a", "size": 2028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/mpl/example/integer.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/mpl/example/integer.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/mpl/example/integer.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 29.8235294118, "max_line_length": 64, "alphanum_fraction": 0.6622287968, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979746, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.41984280658781}}
{"text": "/**\n * @file print_helper.hpp\n * @author francois.hamonic@gmail.com\n * @brief\n * @version 0.1\n * @date 2021-07-19\n */\n#ifndef PRINT_HELPER_HPP\n#define PRINT_HELPER_HPP\n\n#include <math.h>\n#include <filesystem>\n\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm.hpp>\n\n#include <fmt/os.h>\n\n#include \"landscape/decored_landscape.hpp\"\n#include \"landscape/mutable_landscape.hpp\"\n\n#include \"Eigen/Dense\"\n#include \"algorithms/multiplicative_dijkstra.hpp\"\n#include \"lemon/dijkstra.h\"\n\n#include \"fast-cpp-csv-parser/csv.h\"\n#include \"solvers/concept/solver.hpp\"\n\n#include \"lemon/dim2.h\"\n#include \"lemon/graph_to_eps.h\"\n\n#include \"indices/eca.hpp\"\n\n#include \"helper.hpp\"\n\nnamespace Helper {\n/**\n * @brief Finds the maximum node scaling for which no nodes overlaps.\n *\n * Finds the maximum scaling coeficient of nodes radius for which their is no\n * overlaps in their graphical representation. Runs in $O(n^2)$, where $n$ is\n * the number of nodes.\n *\n * @tparam GR\n * @tparam QM\n * @tparam DM\n * @tparam CM\n * @param landscape\n * @return double\n */\ntemplate <typename LS>\nstd::pair<double, double> findNodeScale(const LS & landscape) {\n    using Graph = typename LS::Graph;\n    const Graph & graph = landscape.getNetwork();\n    const typename LS::CoordsMap & coordsMap = landscape.getCoordsMap();\n    const typename LS::QualityMap & qualityMap = landscape.getQualityMap();\n\n    if(lemon::countNodes(graph) < 2) return std::make_pair(1, 0);\n\n    auto dist = [&](typename Graph::Node u, typename Graph::Node v) {\n        const double dx = coordsMap[u].x - coordsMap[v].x;\n        const double dy = coordsMap[u].y - coordsMap[v].y;\n        return std::sqrt(dx * dx + dy * dy);\n    };\n    auto radius = [&](typename Graph::Node u) {\n        return std::sqrt(qualityMap[u] / (2 * M_PI));\n    };\n    double r_max = std::numeric_limits<double>::max();\n    double min_dist = 0.0;\n    for(typename Graph::NodeIt u(graph); u != lemon::INVALID; ++u) {\n        for(typename Graph::NodeIt v(graph); v != lemon::INVALID; ++v) {\n            if(u == v) continue;\n            const double r = dist(u, v) / (radius(u) + radius(v));\n            if(r < r_max) {\n                r_max = r;\n                min_dist = dist(u, v);\n            }\n        }\n    }\n    return std::make_pair(r_max, min_dist);\n}\n\ntemplate <typename LS>\nvoid printLandscape(const LS & landscape, std::filesystem::path path) {\n    const MutableLandscape::Graph & graph = landscape.getNetwork();\n    std::string name = path.stem();\n\n    auto radius = [&](double area) { return std::sqrt(area / (2 * M_PI)); };\n    const auto & [r_max, min_dist] = findNodeScale(landscape);\n    const double a_max = r_max * 2 * radius(minNonZeroQuality(landscape));\n\n    const bool directed = false;\n\n    double node_scale = 0.7;\n    double text_scale =\n        0.75 / (1 + static_cast<int>(std::log10(lemon::countNodes(graph))));\n    double arrow_scale = (1 - node_scale) * 2 / 3;\n    double arc_width = node_scale * a_max / 16;\n\n    MutableLandscape::Graph::NodeMap<std::string> node_idsMap(graph, \"\\7\");\n    MutableLandscape::Graph::NodeMap<lemon::Color> node_colorsMap(graph,\n                                                                  lemon::WHITE);\n    MutableLandscape::Graph::NodeMap<double> node_sizesMap(graph,\n                                                           arc_width * 0.9);\n    for(MutableLandscape::NodeIt v(graph); v != lemon::INVALID; ++v) {\n        if(landscape.getQuality(v) == 0) continue;\n        node_idsMap[v] = std::to_string(graph.id(v));\n        node_sizesMap[v] = radius(landscape.getQuality(v));\n    }\n\n    MutableLandscape::Graph::ArcMap<lemon::Color> arcs_colorsMap(graph,\n                                                                 lemon::BLACK);\n    MutableLandscape::Graph::ArcMap<double> arc_widths(graph, arc_width);\n\n    return lemon::graphToEps(graph, \"output/\" + name)\n        .title(name)\n        .coords(landscape.getCoordsMap())\n        .autoNodeScale(false)\n        .absoluteNodeSizes(true)\n        .nodeSizes(node_sizesMap)\n        .nodeScale(node_scale * r_max)\n        .autoArcWidthScale(false)\n        .absoluteArcWidths(true)\n        .arcWidths(arc_widths)\n        .arcWidthScale(1)\n        .drawArrows(directed)\n        .arrowLength(arrow_scale * min_dist)\n        .arrowWidth(arc_width * 2)\n        .nodeTexts(node_idsMap)\n        .nodeTextSize(text_scale * a_max)\n        .nodeColors(node_colorsMap)\n        .arcColors(arcs_colorsMap)\n        .enableParallel(directed)\n        .parArcDist(2 * arrow_scale * min_dist)\n        .border(20)\n        .run();\n}\n\ntemplate <typename LS>\nvoid printInstance(const LS & landscape, const RestorationPlan<LS> & plan,\n                   std::filesystem::path path) {\n    using Graph = typename LS::Graph;\n\n    const Graph & graph = landscape.getNetwork();\n    std::string name = path.stem();\n\n    auto radius = [&](double area) { return std::sqrt(area / (2 * M_PI)); };\n    const auto & [r_max, min_dist] = findNodeScale(landscape);\n    const double a_max = r_max * 2 * radius(minNonZeroQuality(landscape));\n\n    const bool directed = false;\n\n    double node_scale = 0.7;\n    double text_scale =\n        0.75 / (1 + static_cast<int>(std::log10(lemon::countNodes(graph))));\n    double arrow_scale = (1 - node_scale) * 2 / 3;\n    double arc_width = node_scale * a_max / 16;\n\n    typename Graph::template NodeMap<std::string> node_idsMap(graph, \"\");\n    typename Graph::template NodeMap<lemon::Color> node_colorsMap(graph,\n                                                                  lemon::BLACK);\n    typename Graph::template NodeMap<double> node_sizesMap(graph,\n                                                           arc_width * 0.9);\n    for(typename Graph::NodeIt v(graph); v != lemon::INVALID; ++v) {\n        if(landscape.getQuality(v) == 0) continue;\n        node_idsMap[v] = std::to_string(graph.id(v));\n        node_colorsMap[v] = lemon::WHITE;\n        node_sizesMap[v] = radius(landscape.getQuality(v));\n    }\n\n    typename Graph::template ArcMap<lemon::Color> arcs_colorsMap(graph,\n                                                                 lemon::BLACK);\n    typename Graph::template ArcMap<double> arc_widths(graph, arc_width);\n\n    for(typename Graph::NodeIt u(graph); u != lemon::INVALID; ++u)\n        node_colorsMap[u] = plan[u].empty() ? lemon::BLACK : lemon::RED;\n\n    for(typename Graph::ArcIt a(graph); a != lemon::INVALID; ++a)\n        arcs_colorsMap[a] = plan[a].empty() ? lemon::BLACK : lemon::RED;\n\n    return lemon::graphToEps(graph, path)\n        .title(name)\n        .coords(landscape.getCoordsMap())\n        .autoNodeScale(false)\n        .absoluteNodeSizes(true)\n        .nodeSizes(node_sizesMap)\n        .nodeScale(node_scale * r_max)\n        .autoArcWidthScale(false)\n        .absoluteArcWidths(true)\n        .arcWidths(arc_widths)\n        .arcWidthScale(1)\n        .drawArrows(directed)\n        .arrowLength(arrow_scale * min_dist)\n        .arrowWidth(arc_width * 2)\n        .nodeTexts(node_idsMap)\n        .nodeTextSize(text_scale * a_max)\n        .nodeColors(node_colorsMap)\n        .arcColors(arcs_colorsMap)\n        .enableParallel(directed)\n        .parArcDist(2 * arrow_scale * min_dist)\n        .border(2)\n        .run();\n}\n\nvoid printSolution(const MutableLandscape & landscape,\n                   const RestorationPlan<MutableLandscape> & plan,\n                   std::string name, concepts::Solver & solver, double B,\n                   const Solution & solution);\n\n// need to include the binary search tree for y-h , y+h search\nstd::pair<MutableLandscape::Node, MutableLandscape::Node> neerestNodes(\n    const MutableLandscape & landscape);\n\ntemplate <typename Graph>\nclass GraphToGraphviz {\npublic:\n    using NodePosMap =\n        typename Graph::template NodeMap<lemon::dim2::Point<double>>;\n    using NodeSizeMap = typename Graph::template NodeMap<double>;\n    using NodeColorMap = typename Graph::template NodeMap<int>;\n    using ArcSizeMap = typename Graph::template ArcMap<double>;\n    using ArcColorMap = typename Graph::template ArcMap<int>;\n\n    using Node = typename Graph::Node;\n    using NodeIt = typename Graph::NodeIt;\n    using Arc = typename Graph::Arc;\n    using ArcIt = typename Graph::ArcIt;\n\nprivate:\n    const Graph & _graph;\n    std::filesystem::path _path;\n    NodePosMap _nodePos;\n    NodeSizeMap _nodeSizes;\n    NodeColorMap _nodeColors;\n    ArcSizeMap _arcSizes;\n    ArcColorMap _arcColors;\n\n    double _pageWidth;\n    double _pageHeight;\n\n    double _node_size_scale;\n    double _arc_size_scale;\n\npublic:\n    GraphToGraphviz(const Graph & g, const std::filesystem::path & p)\n        : _graph(g)\n        , _path(p)\n        , _nodePos(g)\n        , _nodeSizes(g, 1)\n        , _nodeColors(g, 0xffffff)\n        , _arcSizes(g, 1)\n        , _arcColors(g, 0x000000)\n        , _pageWidth(8)\n        , _pageHeight(11)\n        , _node_size_scale(1)\n        , _arc_size_scale(1) {}\n\n    template <typename PM>\n    GraphToGraphviz<Graph> & nodePos(const PM & posMap) {\n        for(NodeIt u(_graph); u != lemon::INVALID; ++u) _nodePos[u] = posMap[u];\n        return *this;\n    }\n    template <typename SM>\n    GraphToGraphviz<Graph> & nodeSizes(const SM & sizeMap) {\n        for(NodeIt u(_graph); u != lemon::INVALID; ++u)\n            _nodeSizes[u] = sizeMap[u];\n        return *this;\n    }\n    GraphToGraphviz<Graph> & nodeScale(const double scale) {\n        _node_size_scale = scale;\n        return *this;\n    }\n    template <typename CM>\n    GraphToGraphviz<Graph> & nodeColors(const CM & colorMap) {\n        for(NodeIt u(_graph); u != lemon::INVALID; ++u)\n            _nodeColors[u] = colorMap[u];\n        return *this;\n    }\n    template <typename AM>\n    GraphToGraphviz<Graph> & arcSizes(const AM & sizeMap) {\n        for(ArcIt a(_graph); a != lemon::INVALID; ++a)\n            _arcSizes[a] = sizeMap[a];\n        return *this;\n    }\n    GraphToGraphviz<Graph> & arcScale(const double scale) {\n        _arc_size_scale = scale;\n        return *this;\n    }\n    template <typename CM>\n    GraphToGraphviz<Graph> & arcColors(const CM & colorMap) {\n        for(ArcIt a(_graph); a != lemon::INVALID; ++a)\n            _arcColors[a] = colorMap[a];\n        return *this;\n    }\n    GraphToGraphviz<Graph> & pageSize(double width, double height) {\n        _pageWidth = width;\n        _pageHeight = height;\n        return *this;\n    }\n\n    void run() const {\n        double min_x, max_x, min_y, max_y;\n        min_x = max_x = _nodePos[_graph.nodeFromId(0)].x;\n        min_y = max_y = _nodePos[_graph.nodeFromId(0)].y;\n        for(NodeIt u(_graph); u != lemon::INVALID; ++u) {\n            min_x = std::min(min_x, _nodePos[u].x);\n            max_x = std::max(max_x, _nodePos[u].x);\n            min_y = std::min(min_y, _nodePos[u].y);\n            max_y = std::max(max_y, _nodePos[u].y);\n        }\n        const double scale = std::min(_pageWidth / (max_x - min_x),\n                                      _pageHeight / (max_y - min_y));\n        auto scale_x = [&](double x) { return scale * (x - min_x); };\n        auto scale_y = [&](double y) { return scale * (y - min_y); };\n        auto scale_size = [&](double s) {\n            return _node_size_scale * scale * s;\n        };\n\n        std::vector<Node> colorSortedNodes;\n        for(NodeIt u(_graph); u != lemon::INVALID; ++u)\n            colorSortedNodes.push_back(u);\n        std::sort(colorSortedNodes.begin(), colorSortedNodes.end(),\n                  [&](Node & a, Node & b) {\n                      return _nodeColors[a] < _nodeColors[b];\n                  });\n\n        std::vector<Arc> colorSortedArcs;\n        for(ArcIt a(_graph); a != lemon::INVALID; ++a)\n            colorSortedArcs.push_back(a);\n        std::sort(\n            colorSortedArcs.begin(), colorSortedArcs.end(),\n            [&](Arc & a, Arc & b) { return _arcColors[a] < _arcColors[b]; });\n\n        auto dot_file = fmt::output_file(_path.generic_string());\n        dot_file.print(\"digraph {{size=\\\"{},{}\\\";\\n\", _pageWidth, _pageHeight);\n        dot_file.print(\n            \"graph [pad=\\\"0.2,0.1\\\" bgcolor=transparent overlap=scale]\\n\");\n        dot_file.print(\"node [style=filled shape=\\\"circle\\\"]\\n\");\n        dot_file.print(\"edge [style=filled]\\n\");\n\n        int prev_color = -1;\n        for(Node u : colorSortedNodes) {\n            if(_nodeColors[u] != prev_color) {\n                dot_file.print(\"node [fillcolor=\\\"#{:06x}\\\"]\\n\",\n                               _nodeColors[u]);\n                prev_color = _nodeColors[u];\n            }\n            dot_file.print(\"{} [width=\\\"{}\\\" pos=\\\"{},{}!\\\"]\\n\", _graph.id(u),\n                           scale_size(std::sqrt(_nodeSizes[u])), scale_x(_nodePos[u].x),\n                           scale_y(_nodePos[u].y));\n        }\n\n        prev_color = -1;\n        for(Arc a : colorSortedArcs) {\n            if(_arcColors[a] != prev_color) {\n                dot_file.print(\"edge [color=\\\"#{:06x}\\\"]\\n\", _arcColors[a]);\n                prev_color = _arcColors[a];\n            }\n            dot_file.print(\n                \"{} -> {} [penwidth=\\\"{}\\\"]\\n\", _graph.id(_graph.source(a)),\n                _graph.id(_graph.target(a)), _arc_size_scale * _arcSizes[a]);\n        }\n\n        dot_file.print(\"}}\");\n    }\n};\n\ntemplate <typename LS>\nvoid printLandscapeGraphviz(const LS & landscape, std::filesystem::path path) {\n    using Graph = typename LS::Graph;\n    using Node = typename LS::Graph::Node;\n    using NodeIt = typename LS::Graph::NodeIt;\n    using Arc = typename LS::Graph::Arc;\n    using ArcIt = typename LS::Graph::ArcIt;\n    using NodeColorMap = typename Graph::template NodeMap<int>;\n    using ArcColorMap = typename Graph::template ArcMap<int>;\n\n    const Graph & graph = landscape.getNetwork();\n\n    NodeColorMap nodeColors(graph);\n    for(NodeIt u(graph); u != lemon::INVALID; ++u)\n        nodeColors[u] = landscape.getQuality(u) > 0 ? 0x50e050 : 0x101010;\n\n    GraphToGraphviz<Graph>(graph, path)\n        .nodePos(landscape.getCoordsMap())\n        .nodeSizes(landscape.getQualityMap())\n        .nodeColors(nodeColors)\n        .run();\n};\n\ntemplate <typename LS>\nvoid printInstanceGraphviz(const LS & landscape,\n                           const RestorationPlan<LS> & plan,\n                           std::filesystem::path path) {\n    using Graph = typename LS::Graph;\n    using Node = typename LS::Graph::Node;\n    using NodeIt = typename LS::Graph::NodeIt;\n    using Arc = typename LS::Graph::Arc;\n    using ArcIt = typename LS::Graph::ArcIt;\n    using NodeColorMap = typename Graph::template NodeMap<int>;\n    using ArcColorMap = typename Graph::template ArcMap<int>;\n\n    const Graph & graph = landscape.getNetwork();\n\n    NodeColorMap nodeColors(graph);\n    for(NodeIt u(graph); u != lemon::INVALID; ++u)\n        nodeColors[u] = plan.contains(u) ? 0xe05050 : 0x50e050;\n\n    ArcColorMap arcColors(graph);\n    for(ArcIt a(graph); a != lemon::INVALID; ++a) {\n        if(!plan.contains(a)) {\n            arcColors[a] = 0x101010;\n            continue;\n        }\n        arcColors[a] = 0xe05050;\n        Node u = graph.source(a);\n        Node v = graph.target(a);\n        nodeColors[u] = (nodeColors[u] & 0xffff00) | 0xe00000;\n        nodeColors[v] = (nodeColors[v] & 0xffff00) | 0xe00000;\n    }\n    for(NodeIt u(graph); u != lemon::INVALID; ++u)\n        nodeColors[u] = landscape.getQuality(u) > 0 ? nodeColors[u] : 0x101010;\n\n    GraphToGraphviz<Graph>(graph, path)\n        .nodePos(landscape.getCoordsMap())\n        .nodeSizes(landscape.getQualityMap())\n        .nodeColors(nodeColors)\n        .arcScale(3)\n        .arcColors(arcColors)\n        .run();\n};\n\ntemplate <typename LS>\nvoid printSolutionGraphviz(const LS & landscape,\n                           const RestorationPlan<LS> & plan,\n                           const Solution & solution,\n                           std::filesystem::path path) {\n    using Graph = typename LS::Graph;\n    using Node = typename LS::Graph::Node;\n    using NodeIt = typename LS::Graph::NodeIt;\n    using Arc = typename LS::Graph::Arc;\n    using ArcIt = typename LS::Graph::ArcIt;\n    using NodeColorMap = typename Graph::template NodeMap<int>;\n    using ArcColorMap = typename Graph::template ArcMap<int>;\n    using ArcSizesMap = typename Graph::template ArcMap<double>;\n\n    const Graph & graph = landscape.getNetwork();\n\n    NodeColorMap nodeColors(graph);\n    for(NodeIt u(graph); u != lemon::INVALID; ++u)\n        nodeColors[u] =\n            plan.contains(u)\n                ? 0xe05050\n                : (landscape.getQuality(u) > 0 ? 0x50e050 : 0x101010);\n\n    ArcColorMap arcColors(graph);\n    for(ArcIt a(graph); a != lemon::INVALID; ++a) {\n        arcColors[a] = plan.contains(a) ? 0xe05050 : 0x101010;\n        if(plan.contains(a)) {\n            Node u = graph.source(a);\n            Node v = graph.target(a);\n            nodeColors[u] = (nodeColors[u] & 0x00ffff) | 0xe00000;\n            nodeColors[v] = (nodeColors[v] & 0x00ffff) | 0xe00000;\n        }\n    }\n\n    ArcSizesMap arcSizes(graph, 1);\n    const auto & arcCentrality = *Helper::corridorCentralityMap(landscape);\n    double max_centrality = 0;\n    for(ArcIt a(graph); a != lemon::INVALID; ++a)\n        max_centrality = std::max(max_centrality, arcCentrality[a]);\n\n    const double pow = std::log(10) / std::log(max_centrality);\n\n    for(ArcIt a(graph); a != lemon::INVALID; ++a) {\n        if(arcCentrality[a] == 0) continue;\n        arcSizes[a] = std::pow(arcCentrality[a], pow);\n        if(arcSizes[a] > 0) arcColors[a] = 0x5050e0;\n        if(Node u = graph.source(a); landscape.getQuality(u) == 0)\n            nodeColors[u] = (nodeColors[u] & 0xffff00) | 0x0000e0;\n        if(Node v = graph.target(a); landscape.getQuality(v) == 0)\n            nodeColors[v] = (nodeColors[v] & 0xffff00) | 0x0000e0;\n    }\n\n    GraphToGraphviz<Graph>(graph, path)\n        .nodePos(landscape.getCoordsMap())\n        .nodeSizes(landscape.getQualityMap())\n        .nodeColors(nodeColors)\n        .arcSizes(arcSizes)\n        .arcColors(arcColors)\n        .run();\n};\n\n}  // namespace Helper\n\n#endif  // PRINT_HELPER_HPP", "meta": {"hexsha": "d9dc95345a5accd6b4a2c71ca504c62ef11019b4", "size": 17980, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/print_helper.hpp", "max_stars_repo_name": "fhamonic/landscape_opt", "max_stars_repo_head_hexsha": "7f32749336590c8d8b5875300228196a05137267", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T11:56:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T11:56:09.000Z", "max_issues_repo_path": "include/print_helper.hpp", "max_issues_repo_name": "fhamonic/landscape_opt", "max_issues_repo_head_hexsha": "7f32749336590c8d8b5875300228196a05137267", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/print_helper.hpp", "max_forks_repo_name": "fhamonic/landscape_opt", "max_forks_repo_head_hexsha": "7f32749336590c8d8b5875300228196a05137267", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-27T16:58:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T16:58:19.000Z", "avg_line_length": 36.25, "max_line_length": 88, "alphanum_fraction": 0.5958286986, "num_tokens": 4663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4196843712038927}}
{"text": "#pragma once\n\n// system includes --------------------------------------------------\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <cmath>\n#include <stdexcept>\n#include <vector>\n// own includes -----------------------------------------------------\n#include \"aux/message.hpp\"\n#include \"aux/timer.hpp\"\n#include \"shift_hermite.hpp\"\n\nnamespace boltzmann {\n\ntemplate <typename BASIS, typename NUMERIC = double>\nclass ShiftHermite2D\n{\n public:\n  typedef NUMERIC numeric_t;\n  typedef BASIS basis_t;\n  typedef std::vector<numeric_t> std_vec_t;\n\n public:\n  /**\n   *\n   *\n   * @param basis\n   * @param N      max. polynomial degree+1 in one variable\n   */\n  ShiftHermite2D(const basis_t& basis);\n\n  void init();\n\n  void shift(numeric_t* c, numeric_t x, numeric_t y);\n\n  // debug\n  const HShiftMatrix<numeric_t>& get_sx() { return sx_op_; }\n  const HShiftMatrix<numeric_t>& get_sy() { return sy_op_; }\n\n private:\n  typedef typename BASIS::elem_t elem_t;\n  typedef typename boost::mpl::at_c<typename elem_t::types_t, 0>::type hx_t;\n  typedef typename boost::mpl::at_c<typename elem_t::types_t, 1>::type hy_t;\n  typedef Eigen::Matrix<numeric_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> matrix_t;\n\n private:\n  const basis_t& basis_;\n  /// buffers\n  matrix_t buf_in;\n  matrix_t buf_out;\n  /// permutation vector\n  std::vector<unsigned int> perm_;\n  bool is_initialized_;\n\n  typename elem_t::Acc::template get<hx_t> get_hx;\n  typename elem_t::Acc::template get<hy_t> get_hy;\n\n  HShiftMatrix<numeric_t> sx_op_;\n  HShiftMatrix<numeric_t> sy_op_;\n};\n\n// ----------------------------------------------------------------------\ntemplate <typename BASIS, typename NUMERIC>\nShiftHermite2D<BASIS, NUMERIC>::ShiftHermite2D(const basis_t& basis)\n    : basis_(basis)\n    ,\n\n    perm_(basis.n_dofs())\n    , is_initialized_(false)\n{ /* empty */\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename BASIS, typename NUMERIC>\nvoid\nShiftHermite2D<BASIS, NUMERIC>::init()\n{\n  // max degree\n  unsigned int max_kx =\n      get_hx(*std::max_element(basis_.begin(),\n                               basis_.end(),\n                               [&](const elem_t& e1, const elem_t& e2) {\n                                 return get_hx(e1).get_id().k < get_hx(e2).get_id().k;\n                               }))\n          .get_id()\n          .k;\n  unsigned int max_ky =\n      get_hy(*std::max_element(basis_.begin(),\n                               basis_.end(),\n                               [&](const elem_t& e1, const elem_t& e2) {\n                                 return get_hy(e1).get_id().k < get_hy(e2).get_id().k;\n                               }))\n          .get_id()\n          .k;\n  buf_in.resize(max_kx + 1, max_ky + 1);\n  buf_out.resize(max_kx + 1, max_ky + 1);\n\n  buf_in.fill(0);\n  buf_out.fill(0);\n\n  unsigned int stride = buf_in.cols();\n\n  // build permutation vector\n  unsigned int i = 0;\n  for (auto elem = basis_.begin(); elem < basis_.end(); ++elem, ++i) {\n    unsigned int kx = get_hx(*elem).get_id().k;\n    unsigned int ky = get_hy(*elem).get_id().k;\n    perm_[i] = kx * stride + ky;\n  }\n\n  Timer timer;\n  // initialize shift matrices\n  timer.restart();\n  sx_op_.init(max_kx);\n  sy_op_.init(max_ky);\n  print_timer(timer.stop(), \"initialize shift matrices\");\n  is_initialized_ = true;\n}\n\n// ----------------------------------------------------------------------\ntemplate <typename BASIS, typename NUMERIC>\nvoid\nShiftHermite2D<BASIS, NUMERIC>::shift(numeric_t* c, numeric_t x, numeric_t y)\n{\n  assert(is_initialized_);\n\n  // permute\n  numeric_t* in = buf_in.data();\n\n  for (unsigned int i = 0; i < basis_.n_dofs(); ++i) {\n    in[perm_[i]] = c[i];\n  }\n\n  // apply shift matrices\n  sx_op_.setx(x);\n  sy_op_.setx(y);\n\n  auto& Sx = sx_op_.get();\n  auto& Sy = sy_op_.get();\n\n  buf_out = Sx * buf_in * Sy.transpose();\n\n  numeric_t* out = buf_out.data();\n\n  // invert permutation and overwrite c\n  for (unsigned int i = 0; i < basis_.n_dofs(); ++i) {\n    c[i] = out[perm_[i]];\n  }\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "585386a70dbbc479d5efcb3afe142586a70d895f", "size": 4038, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spectral/shift_hermite_2d.hpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "spectral/shift_hermite_2d.hpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spectral/shift_hermite_2d.hpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 26.3921568627, "max_line_length": 93, "alphanum_fraction": 0.5705794948, "num_tokens": 1066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4196843636807008}}
{"text": "#pragma once\n\n#include <cassert>\n#include <iostream>\n#include <algorithm>\n#include <numeric>\n\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/serialization/vector.hpp>\n\n#include <common/error.hpp>\n\n#include <tensor/index.hpp>\n#include <tensor/tensor.hpp>\n\nnamespace Construction {\n\tnamespace Tensor {\n\n\t\tclass IsNoPermutationException : public Exception {\n\t\tpublic:\n\t\t\tIsNoPermutationException(const std::string& error) : Exception(error) { }\n\t\t\tIsNoPermutationException() : Exception(\"The given combination is no permutation\") {}\n\t\t};\n\n\t\tclass BinaryPermutation {\n\t\tpublic:\n\t\t\tBinaryPermutation() = default;\n\n\t\t\tBinaryPermutation(unsigned a, unsigned b) : a(a), b(b) { }\n\t\t\tBinaryPermutation(const BinaryPermutation& other)\n\t\t\t\t: a(other.a), b(other.b) { }\n\t\tpublic:\n\t\t\tbool operator==(const BinaryPermutation& other) const {\n\t\t\t\treturn a == other.a && b == other.b;\n\t\t\t}\n\n\t\t\tbool operator!=(const BinaryPermutation& other) const {\n\t\t\t\treturn a != other.a || b != other.b;\n\t\t\t}\n\t\tpublic:\n\t\t\tIndices operator()(const Indices& indices) const {\n\t\t\t\tassert(a > 0 && b > 0 && indices.Size() >= a && indices.Size() >= b);\n\n\t\t\t\tIndices result;\n\n\t\t\t\tfor (unsigned i=0; i < indices.Size(); ++i) {\n\t\t\t\t\tif (i == a-1) result.Insert(indices[b-1]);\n\t\t\t\t\telse if (i == b-1) result.Insert(indices[a-1]);\n\t\t\t\t\telse result.Insert(indices[i]);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tstd::vector<int> operator()(std::vector<int> list) const {\n\t\t\t\tassert(a > 0 && b > 0 && list.size() >= a && list.size() >= b);\n\n\t\t\t\tstd::vector<int> result;\n\n\t\t\t\tfor (unsigned i=0; i < list.size(); ++i) {\n\t\t\t\t\tif (i == a-1) result.push_back(list[b-1]);\n\t\t\t\t\telse if (i == b-1) result.push_back(list[a-1]);\n\t\t\t\t\telse result.push_back(list[i]);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\ttemplate<typename... Args>\n\t\t\tstd::vector<int> operator()(Args... args) const {\n\t\t\t\treturn (*this)({ args... });\n\t\t\t}\n\n\t\t\t/*Tensor operator()(const Tensor& tensor) const {\n\t\t\t\treturn Tensor\n\t\t\t}*/\n\t\tpublic:\n\t\t\tfriend std::ostream& operator<<(std::ostream& os, const BinaryPermutation& permutation) {\n\t\t\t\tos << \"(\" << permutation.a << \" <-> \" << permutation.b << \")\";\n\t\t\t\treturn os;\n\t\t\t}\n\t\tprivate:\n\t\t\tfriend class boost::serialization::access;\n\n\t\t\ttemplate<class Archive>\n\t\t\tvoid serialize(Archive& ar, const unsigned int version) {\n\t\t\t\tar & a;\n\t\t\t\tar & b;\n\t\t\t}\n\t\tprivate:\n\t\t\tunsigned a;\n\t\t\tunsigned b;\n\t\t};\n\n\t\t/**\n\t\t\t\\class Permutation\n\n\t\t\tAllows arbitrary permutation of an index combination\n\t\t */\n\t\tclass Permutation {\n\t\tpublic:\n\t\t\tPermutation() = default;\n\n\t\t\tPermutation(unsigned a, unsigned b) {\n\t\t\t\tthis->permute.emplace_back(BinaryPermutation(a,b));\n\t\t\t}\n\n\t\t\tPermutation(const BinaryPermutation& permute) {\n\t\t\t\tthis->permute.push_back(permute);\n\t\t\t}\n\n\t\t\tPermutation(std::vector<BinaryPermutation> permute)\n\t\t\t\t: permute(permute) { }\n\n\t\t\t// Copy constructor\n\t\t\tPermutation(const Permutation& other)\n\t\t\t\t: permute(other.permute) { }\n\t\tpublic:\n\t\t\t/*Permutation& operator=(std::vector<BinaryPermutation> permute) {\n\t\t\t\tthis->permute = permute;\n\t\t\t\treturn *this;\n\t\t\t}*/\n\n\t\t\tPermutation& operator=(const Permutation& other) {\n\t\t\t\tpermute = other.permute;\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tPermutation& operator=(Permutation&& other) {\n\t\t\t\tpermute = std::move(other.permute);\n\t\t\t\treturn *this;\n\t\t\t}\n\t\tpublic:\n\t\t\tvoid Insert(const BinaryPermutation& p) {\n\t\t\t\tpermute.push_back(p);\n\t\t\t}\n\n\t\t\tvoid Insert(unsigned a, unsigned b) {\n\t\t\t\tpermute.emplace_back(BinaryPermutation(a,b));\n\t\t\t}\n \t\tpublic:\n\t\t\tIndices operator()(const Indices& indices) const {\n\t\t\t\tIndices result = indices;\n\t\t\t\tfor (auto& p : permute) {\n\t\t\t\t\tresult = p(result);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tstd::vector<int> operator()(const std::vector<int>& indices) const {\n\t\t\t\tstd::vector<int> result = indices;\n\t\t\t\tfor (auto& p : permute) {\n\t\t\t\t\tresult = p(result);\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\ttemplate<typename... Args>\n\t\t\tstd::vector<unsigned> operator()(Args... args) const {\n\t\t\t\treturn (*this)({args...});\n\t\t\t}\n\t\tpublic:\n\t\t\tbool IsEven() const {\n\t\t\t\treturn permute.size() % 2 == 0;\n\t\t\t}\n\n\t\t\tbool IsOdd() const {\n\t\t\t\treturn permute.size() % 2 != 0;\n\t\t\t}\n\n\t\t\tint Sign() const {\n\t\t\t\treturn IsOdd() ? -1 : 1;\n\t\t\t}\n\t\tpublic:\n\t\t\t/**\n\t\t\t\t\\brief A cyclic permutation of the indices\n\n\t\t\t\t{abcd} => {bcda}\n\t\t\t */\n\t\t\tstatic Indices Cyclic(const Indices& indices) {\n\t\t\t\tPermutation p;\n\t\t\t\tfor (int i=1; i<indices.Size(); i++) {\n\t\t\t\t\tp.Insert(i, i+1);\n\t\t\t\t}\n\t\t\t\treturn p(indices);\n\t\t\t}\n\n\t\t\tstatic std::vector<int> Cyclic(const std::vector<int>& indices) {\n\t\t\t\tPermutation p;\n\t\t\t\tfor (int i=1; i<indices.size(); i++) {\n\t\t\t\t\tp.Insert(i, i+1);\n\t\t\t\t}\n\t\t\t\treturn p(indices);\n\t\t\t}\n\n\t\t\ttemplate<typename... Args>\n\t\t\tstatic std::vector<int> Cyclic(Args... args) {\n\t\t\t\treturn Cyclic({ args... });\n\t\t\t}\n\n\t\t\t/**\n\t\t\t\tReturns a permutation to get from an index combination to another\n\n\n\t\t\t */\n\t\t\tstatic Permutation From(const Indices& indices, const Indices& to) {\n\t\t\t\tif (!indices.IsPermutationOf(to)) {\n\t\t\t\t\tthrow IsNoPermutationException();\n\t\t\t\t}\n\n\t\t\t\t// Clone the vector\n\t\t\t\tauto vec = indices;\n\n\t\t\t\tint pos = 0;\n\t\t\t\tPermutation result;\n\n\t\t\t\tfor (int i=0; i<indices.Size(); ++i) {\n\t\t\t\t\tauto current = vec[pos];\n\t\t\t\t\tauto id = std::find(to.begin(), to.end(), current) - to.begin();\n\n\t\t\t\t\tif (id == pos) {\n\t\t\t\t\t\tpos++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tresult.Insert(pos + 1, id + 1);\n\n\t\t\t\t\t// Do the switch\n\t\t\t\t\tstd::iter_swap(vec.begin() + pos, vec.begin() + id);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tstatic Permutation From(const std::vector<int>& indices, const std::vector<int>& to) {\n\t\t\t\tif (!Indices::IsPermutationOf(indices, to)) {\n\t\t\t\t\tthrow IsNoPermutationException();\n\t\t\t\t}\n\n\t\t\t\t// Clone the vector\n\t\t\t\tauto vec = indices;\n\n\t\t\t\tint pos = 0;\n\t\t\t\tPermutation result;\n\n\t\t\t\tfor (int i=0; i<indices.size(); ++i) {\n\t\t\t\t\tauto current = vec[pos];\n\t\t\t\t\tauto id = std::find(to.begin(), to.end(), current) - to.begin();\n\n\t\t\t\t\tif (id == pos) {\n\t\t\t\t\t\tpos++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tresult.Insert(pos + 1, id + 1);\n\n\t\t\t\t\t// Do the switch\n\t\t\t\t\tstd::iter_swap(vec.begin() + pos, vec.begin() + id);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\tstatic Permutation From(const std::vector<unsigned>& indices, const std::vector<unsigned>& to) {\n\t\t\t\tif (!Indices::IsPermutationOf(indices, to)) {\n\t\t\t\t\tthrow IsNoPermutationException();\n\t\t\t\t}\n\n\t\t\t\t// Clone the vector\n\t\t\t\tauto vec = indices;\n\n\t\t\t\tint pos = 0;\n\t\t\t\tPermutation result;\n\n\t\t\t\tfor (int i=0; i<indices.size(); ++i) {\n\t\t\t\t\tauto current = vec[pos];\n\t\t\t\t\tauto id = std::find(to.begin(), to.end(), current) - to.begin();\n\n\t\t\t\t\tif (id == pos) {\n\t\t\t\t\t\tpos++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tresult.Insert(pos + 1, id + 1);\n\n\t\t\t\t\t// Do the switch\n\t\t\t\t\tstd::iter_swap(vec.begin() + pos, vec.begin() + id);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t}\n\n            static Permutation From(Indices indices, std::map<Index, Index> transformation) {\n                Permutation result;\n\n                for (unsigned i=0; i<indices.Size(); ++i) {\n                    auto it = transformation.find(indices[i]);\n                    if (it == transformation.end()) throw IsNoPermutationException();\n\n                    unsigned pos=0;\n                    bool found=false;\n                    for (unsigned j=0; j<indices.Size(); ++j) {\n                        if (it->second == indices[j]) { pos = j; found=true; break; }\n                    }\n\n                    if (!found) throw IsNoPermutationException();\n\n                    result.Insert({ i+1, pos+1 });\n                }\n\n                return result;\n            }\n\n            inline static Indices Shuffle(Indices indices, std::map<Index, Index> transformation) {\n                return From(indices, transformation)(indices);\n            }\n\t\tpublic:\n\t\t\tfriend std::ostream& operator<<(std::ostream& os, const Permutation& permutation) {\n\t\t\t\tos << \"[\";\n\t\t\t\tfor (int i=0; i<permutation.permute.size(); i++) {\n\t\t\t\t\tos << permutation.permute[i];\n\t\t\t\t\tif (i !=permutation.permute.size()-1) os << \", \";\n\t\t\t\t}\n\t\t\t\tos << \"]\";\n\t\t\t\treturn os;\n\t\t\t}\n\t\tprivate:\n\t\t\tfriend class boost::serialization::access;\n\n\t\t\ttemplate<class Archive>\n\t\t\tvoid serialize(Archive& ar, const unsigned int version) {\n\t\t\t\tar & permute;\n\t\t\t}\n\t\tprivate:\n\t\t\tstd::vector<BinaryPermutation> permute;\n\t\t};\n\n\t}\n}\n", "meta": {"hexsha": "6a144dbc8a169d99f1e74bac67507cbda9f4825d", "size": 8184, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/tensor/permutation.hpp", "max_stars_repo_name": "constructivegravity/construct", "max_stars_repo_head_hexsha": "f10e60cc982a2571aa6af7bd08f19aa5254a69de", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-08-01T13:55:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-04T19:27:14.000Z", "max_issues_repo_path": "lib/tensor/permutation.hpp", "max_issues_repo_name": "constructivegravity/construct", "max_issues_repo_head_hexsha": "f10e60cc982a2571aa6af7bd08f19aa5254a69de", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-07-19T11:50:54.000Z", "max_issues_repo_issues_event_max_datetime": "2016-09-05T14:31:21.000Z", "max_forks_repo_path": "lib/tensor/permutation.hpp", "max_forks_repo_name": "constructivegravity/construct", "max_forks_repo_head_hexsha": "f10e60cc982a2571aa6af7bd08f19aa5254a69de", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-19T08:35:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T19:27:35.000Z", "avg_line_length": 24.0, "max_line_length": 99, "alphanum_fraction": 0.5850439883, "num_tokens": 2193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.6442251201477016, "lm_q1q2_score": 0.4196191746683297}}
{"text": "//============================================================================\n// Name         : dnatemplatecalcfuncs.hpp\n// Author       : Roger Fraser\n// Contributors :\n// Version      : 1.00\n// Copyright    : Copyright 2017 Geoscience Australia\n//\n//                Licensed under the Apache License, Version 2.0 (the \"License\");\n//                you may not use this file except in compliance with the License.\n//                You may obtain a copy of the License at\n//               \n//                http ://www.apache.org/licenses/LICENSE-2.0\n//               \n//                Unless required by applicable law or agreed to in writing, software\n//                distributed under the License is distributed on an \"AS IS\" BASIS,\n//                WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//                See the License for the specific language governing permissions and\n//                limitations under the License.\n//\n// Description  : Advanced and common calculation functions using standard\n//\t\t\t\t  data types\n//============================================================================\n\n#ifndef DNATEMPLATECALCFUNCS_H_\n#define DNATEMPLATECALCFUNCS_H_\n\n#if defined(_MSC_VER)\n\t#if defined(LIST_INCLUDES_ON_BUILD) \n\t\t#pragma message(\"  \" __FILE__) \n\t#endif\n#endif\n\n#include <algorithm>\n#include <numeric>\n#include <functional>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <stdlib.h>\n#include <math.h>\n#include <iostream>\n\n#include <boost/shared_ptr.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include <include/config/dnatypes.hpp>\n#include <include/config/dnaconsts.hpp>\n\nusing namespace std;\nusing namespace boost;\n\ntemplate <class U>\nU sumOfConsecutiveIntegers(const U& max, const U& min = 1)\n{\n\t//U q(static_cast<U>(average<double, U>(max, min) * max));\n\tU sum(0);\n\tfor (U u=min; u<=max; u++)\n\t\tsum += u;\n\treturn sum;\t\n}\n\ntemplate <typename T, typename U>\nT removeNegativeZero(const T& t, const U& precision)\n{\n\tif (t < 0.0 || t == T(-0.0))\n\t{\n\t\tT v(floor((t * pow(10.0, precision)) + 0.5));\n\t\tif (fabs(v) > 0.)\n\t\t\t// t is non-zero at precision\n\t\t\treturn t;\n\t\t// t is a negative zero\n\t\treturn 0.;\n\t}\n\treturn t;\t\n}\n\ntemplate <typename T>\nbool are_floats_equal(const T& lhs, const T& rhs, const T epsilon=PRECISION_1E6)\n{\n\treturn (fabs(lhs - rhs) < epsilon);\n}\n\ntemplate <typename T, typename U, typename iterator>\nT average(const iterator begin, const iterator end, U& sum)\n{\n\tU n(static_cast<UINT32>(std::distance(begin, end)));\n\tsum = accumulate(begin, end, 0);\n\treturn static_cast<T>(sum) / n;\n}\n\ntemplate <class T, class U>\nT average(const U& a, const U& b)\n{\n\tT t(a + b);\n\treturn t / 2.;\n}\n\ntemplate <class T>\nT average(const T& a, const T& b)\n{\n\tT t(a + b);\n\treturn (t / (T)(2.));\n}\n\ntemplate <class T, typename U>\nT minVal(const T& lhs, const U& rhs)\n{\n\tif (lhs < rhs)\n\t\treturn lhs;\n\telse \n\t\treturn rhs;\n}\n\ntemplate <class T, typename U>\nT maxVal(const T& lhs, const U& rhs)\n{\n\tif (lhs > rhs)\n\t\treturn lhs;\n\telse \n\t\treturn rhs;\n}\n\n// use this for longitude values only, where 180 degrees\n// marks the boundary between east (positive) and west (negative)\ntemplate <class T>\nT Rad180Mod(const T &dValue)\n{\n\tif (dValue < -PI)\n\t\t return dValue + (PI + PI);\n\telse if (dValue > PI)\n\t\t return dValue - (PI + PI);\n\treturn dValue;\n}\n\ntemplate <class T>\nT degrees_to_radians_(T& degrees)\n{\n\treturn (degrees * DEG_TO_RAD);\n}\n\ntemplate <class T>\nT Radians(T& degrees)\n{\n\treturn degrees_to_radians_(degrees);\n}\n\ntemplate <class T>\nT Radians(const T& degrees)\n{\n\treturn degrees_to_radians_(degrees);\n}\n\ntemplate <class T>\nvoid Radians(T* degrees)\n{\n\t*degrees = degrees_to_radians_(*degrees);\n}\n\ntemplate <class T>\nT radians_to_degrees_(T& radians)\n{\n\treturn (radians * RAD_TO_DEG);\n}\n\ntemplate <class T>\nT Degrees(T& radians)\n{\n\treturn radians_to_degrees_(radians);\n}\n\ntemplate <class T>\nT Degrees(const T& radians)\n{\n\treturn radians_to_degrees_(radians);\n}\n\ntemplate <class T>\nvoid Degrees(T* radians)\n{\n\t*radians = radians_to_degrees_(*radians);\n}\n\n// use DegreesL(const T& radians) for longitude values only, where 180 degrees\n// marks the boundary between east (positive) and west (negative)\ntemplate <class T>\nT DegreesL(const T& radians)\n{\n\treturn (Rad180Mod(radians) * RAD_TO_DEG);\n}\n\n// use DegreesL(T* dValue) for longitude values only, where 180 degrees\n// marks the boundary between east (positive) and west (negative)\ntemplate <class T>\nvoid DegreesL(T* dValue)\n{\n\t*dValue = (Rad180Mod(*dValue) * RAD_TO_DEG);\n}\n\n// Seconds from Radians\ntemplate <class T>\nT Seconds(const T& radians)\n{\n\treturn radians * RAD_TO_SEC;\n}\n\ntemplate <class T>\nT Seconds(T* radians)\n{\n\treturn *radians * RAD_TO_SEC;\n}\n\ntemplate <class T>\nT SecondstoRadians(const T& seconds)\n{\n\treturn seconds / static_cast<T>(RAD_TO_SEC);\n}\n\ntemplate <class T, typename U>\nvoid DegtoDms(const T& dDegrees, U* dDegMinSec)\n{\n\tT d, m, s;\n\n\t*dDegMinSec = fabs(dDegrees);\t\t // retain original value\n\td = floor(*dDegMinSec);\n\tm = floor((((*dDegMinSec) - d) * 60.0));\n\ts = ((*dDegMinSec) - d - (m/60.0)) * 3600.0;\n\tif (fabs(s - 60.0) < 0.000000001)\n\t{\n\t\ts = 0.0;\n\t\tm += 1.0;\n\t}\n\t*dDegMinSec = d + (m/100.0) + (s/10000.0);\n\tif (dDegrees < 0.0)\n\t\t*dDegMinSec *= -1;\n}\n\n\n// DegtoDms helper\ntemplate <class T>\nT DegtoDms(const T& dDegrees)\n{\n\tT dDegMinSec;\n\tDegtoDms(dDegrees, &dDegMinSec);\n\treturn dDegMinSec;\n}\n\n\ntemplate <class T, typename U>\nvoid DmstoDeg(const T& dDegMinSec, U* dDegrees)\n{\n\tT dh, dm, ds;\n\n\tdh = fabs(dDegMinSec);\t\t // retain original value\n\t*dDegrees = floor(dh);\n\tdm = floor(((dh - (*dDegrees)) * 100.0) + 0.0001);\n\tds = (((dh - (*dDegrees)) * 100.0) - dm) * 100.0;\n\t*dDegrees += ((dm / 60.0) + (ds / 3600.0));\n\tif (dDegMinSec < 0.0)\n\t\t(*dDegrees) *= -1;\n}\n\n// DmstoDeg helper\ntemplate <class T>\nT DmstoDeg(const T& dDegMinSec)\n{\n\tT dDegrees;\n\tDmstoDeg(dDegMinSec, &dDegrees);\n\treturn dDegrees;\n}\n\ntemplate <class T, typename U>\nvoid DmstoRad(const T& dDegMinSec, U* dRadians)\n{\n\tT dh, dm, ds;\n\n\tdh = fabs(dDegMinSec);\t\t // retain original value\n\t*dRadians = floor(dh);\n\tdm = floor(((dh - (*dRadians)) * 100.0) + 0.0001);\n\tds = (((dh - (*dRadians)) * 100.0) - dm) * 100.0;\n\t*dRadians += ((dm / 60.0) + (ds / 3600.0));\n\tif (dDegMinSec < 0.0)\n\t\t(*dRadians) *= -1;\n\tRadians(dRadians);\n}\n\n// DmstoRad helper\ntemplate <class T>\nT DmstoRad(const T& dDegMinSec)\n{\n\tT dRadians;\n\tDmstoRad(dDegMinSec, &dRadians);\n\treturn dRadians;\n}\n\ntemplate <class T>\nT RadtoDms(const T& dRadians)\n{\n\tT dDms;\n\tDegtoDms(Degrees(dRadians), &dDms);\n\treturn dDms;\n}\n\ntemplate <class T>\nT RadtoDmsL(const T& dRadians)\n{\n\tT dDms;\n\tDegtoDms(DegreesL(dRadians), &dDms);\n\treturn dDms;\n}\n\ntemplate <class T, typename U>\nvoid DmintoDeg(const T& dDegMin, U* dDegrees)\n{\n\tT dh;\n\n\tdh = fabs(dDegMin);\t// retain original value\n\t*dDegrees = floor(dh);\n\t*dDegrees += (dh - *dDegrees) * 100.0 / 60.0;\n\tif (dDegMin < 0.0)\n\t\t*dDegrees *= -1;\n}\n\n// DmintoDeg helper\ntemplate <class T>\nT DmintoDeg(const T& dDegMin)\n{\n\tT dDegrees;\n\tDmintoDeg(dDegMin, &dDegrees);\n\treturn dDegrees;\n}\n\ntemplate <class T, typename U>\nvoid DegtoDmin(const T& dDegrees, U* dDegMin)\n{\n\tT d;\n\t\n\t*dDegMin = fabs(dDegrees);\t// retain original value\n\td = floor(*dDegMin);\n\t*dDegMin = d + ((*dDegMin - d) * 0.6);\n\t\n\tif (dDegrees < 0.0)\n\t\t*dDegMin *= -1;\n}\n\n// DegDmin helper\ntemplate <class T>\nT DegtoDmin(const T& dDegrees)\n{\n\tT dDegMin;\n\tDegtoDin(dDegrees, &dDegMin);\n\treturn dDegMin;\n}\n\n\ntemplate <class T>\n//            |\n//     4th    |   1st\n//            |\n//\t----------------------\n//            |\n//     3rd    |   2nd\n//            |\nT atan_2(const T& x, const T& y)\n{\n\tT theta(atan(x / y));\t\t\t// first quadrant (default)\n\tif (y < 0)\t\t\t\t\t\t// second or third quadrant\n\t\treturn theta + PI;\n\telse\n\t{\n\t\tif (x > 0)\t\t\t\t\t// first quadrant \n\t\t\treturn theta;\n\t\telse\t\t\t\t\t\t// fourth quadrant\n\t\t\treturn theta + TWO_PI;\n\t}\n  return 0.;\n}\n\n#endif /* DNATEMPLATECALCFUNCS_H_ */\n", "meta": {"hexsha": "ff58e26e47114d3b0435d478ba571f60f0c37bea", "size": 7856, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dynadjust/include/functions/dnatemplatecalcfuncs.hpp", "max_stars_repo_name": "nicgowans/DynAdjust", "max_stars_repo_head_hexsha": "7443f0a3a0487876dd2f568efaa6c7be0e3e75e3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2018-08-30T04:18:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T05:37:18.000Z", "max_issues_repo_path": "dynadjust/include/functions/dnatemplatecalcfuncs.hpp", "max_issues_repo_name": "nicgowans/DynAdjust", "max_issues_repo_head_hexsha": "7443f0a3a0487876dd2f568efaa6c7be0e3e75e3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 112.0, "max_issues_repo_issues_event_min_datetime": "2018-08-30T09:33:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T00:32:29.000Z", "max_forks_repo_path": "dynadjust/include/functions/dnatemplatecalcfuncs.hpp", "max_forks_repo_name": "nicgowans/DynAdjust", "max_forks_repo_head_hexsha": "7443f0a3a0487876dd2f568efaa6c7be0e3e75e3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2018-08-30T09:07:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T05:16:08.000Z", "avg_line_length": 20.72823219, "max_line_length": 90, "alphanum_fraction": 0.6313645621, "num_tokens": 2413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.6513548646660542, "lm_q1q2_score": 0.4196191659482787}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2012, 2013 Klaus Spanderen\n Copyright (C) 2014 Johannes Göttker-Schnetmann\n\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file fdmsquarerootfwdop.cpp\n    \\brief Fokker-Planck forward operator for an square root process\n*/\n\n#include <ql/math/functional.hpp>\n#include <ql/methods/finitedifferences/meshers/fdmmesher.hpp>\n#include <ql/methods/finitedifferences/operators/fdmlinearoplayout.hpp>\n#include <ql/methods/finitedifferences/operators/firstderivativeop.hpp>\n#include <ql/methods/finitedifferences/operators/secondderivativeop.hpp>\n\n#include <ql/experimental/finitedifferences/fdmsquarerootfwdop.hpp>\n#include <ql/experimental/finitedifferences/modtriplebandlinearop.hpp>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/distributions/non_central_chi_squared.hpp>\n\nnamespace QuantLib {\n\n    FdmSquareRootFwdOp::FdmSquareRootFwdOp(\n        const std::shared_ptr<FdmMesher>& mesher,\n        Real kappa, Real theta, Real sigma,\n        Size direction, TransformationType transform)\n    : direction_(direction),\n      kappa_(kappa),\n      theta_(theta),\n      sigma_(sigma),\n      transform_(transform),\n      mapX_(transform == Plain ?\n          new ModTripleBandLinearOp(FirstDerivativeOp(direction_, mesher)\n              .mult(kappa*(mesher->locations(direction_)-theta) + sigma*sigma)\n              .add(SecondDerivativeOp(direction_, mesher)\n                   .mult(0.5*sigma*sigma*mesher->locations(direction_)))\n                .add(Array(mesher->layout()->size(), kappa)))\n\n        : transform == Power ? new ModTripleBandLinearOp(\n            SecondDerivativeOp(direction_, mesher)\n               .mult(0.5*sigma*sigma*mesher->locations(direction_))\n               .add(FirstDerivativeOp(direction_, mesher)\n                     .mult(kappa*(mesher->locations(direction_)+theta)))\n               .add(Array(mesher->layout()->size(),\n                          2*kappa*kappa*theta/(sigma*sigma))))\n\n            : new ModTripleBandLinearOp(FirstDerivativeOp(direction_, mesher)\n                    .mult(Exp(-mesher->locations(direction))\n                        *( -0.5*sigma*sigma - kappa*theta) + kappa)\n                    .add(SecondDerivativeOp(direction_, mesher)\n                    .mult(0.5*sigma*sigma*Exp(-mesher->locations(direction))))\n                    .add(kappa*theta*Exp(-mesher->locations(direction))))\n            ),\n      v_  (mesher->layout()->dim()[direction_]) {\n\n        const FdmLinearOpIterator endIter = mesher->layout()->end();\n        for (FdmLinearOpIterator iter = mesher->layout()->begin();\n            iter != endIter; ++iter) {\n            const Real v = mesher->location(iter, direction_);\n            v_[iter.coordinates()[direction_]] = v;\n        }\n\n        // zero flux boundary condition\n        setLowerBC(mesher);\n        setUpperBC(mesher);\n    }\n\n    void FdmSquareRootFwdOp::setLowerBC(\n        const std::shared_ptr<FdmMesher>& mesher) {\n        const Size n = 1;\n        Real alpha, beta, gamma;\n\n        getCoeff(alpha, beta, gamma, n);\n        const Real f = lowerBoundaryFactor(transform_);\n\n        const Real b = -(h(n-1)+h(n))/zeta(n);\n        const Real c =  h(n-1)/zetap(n);\n\n        const FdmLinearOpIterator endIter = mesher->layout()->end();\n        for (FdmLinearOpIterator iter = mesher->layout()->begin();\n            iter != endIter; ++iter) {\n            if (iter.coordinates()[direction_] == 0) {\n                const Size idx = iter.index();\n                mapX_->diag()[idx]  = beta  + f*b; //*v(n-1);\n                mapX_->upper()[idx] = gamma + f*c; //*v(n-1);\n            }\n        }\n    }\n\n    void FdmSquareRootFwdOp::setUpperBC(\n        const std::shared_ptr<FdmMesher>& mesher) {\n        const Size n = v_.size();\n        Real alpha, beta, gamma;\n\n        getCoeff(alpha, beta, gamma, n);\n        const Real f = upperBoundaryFactor(transform_);\n\n        const Real b = (h(n)+h(n-1))/zeta(n);\n        const Real c = -h(n)/zetam(n);\n\n        const FdmLinearOpIterator endIter = mesher->layout()->end();\n        for (FdmLinearOpIterator iter = mesher->layout()->begin();\n            iter != endIter; ++iter) {\n            if (iter.coordinates()[direction_] == n-1) {\n                const Size idx = iter.index();\n                mapX_->diag()[idx] = beta   + f*b; //*v(n+1);\n                mapX_->lower()[idx] = alpha + f*c; //*v(n+1);\n            }\n        }\n    }\n\n    Real FdmSquareRootFwdOp::lowerBoundaryFactor(TransformationType transform) const {\n        if (transform == Plain) {\n            return f0Plain();\n        }\n        else if (transform == Power) {\n            return f0Power();\n        }\n        else if (transform == Log) {\n            return f0Log();\n        }\n        else\n            QL_FAIL(\"unknown transform\");\n    }\n\n    Real FdmSquareRootFwdOp::upperBoundaryFactor(TransformationType transform) const {\n        if (transform == Plain) {\n            return f1Plain();\n        }\n        else if (transform == Power) {\n            return f1Power();\n        }\n        else if (transform == Log) {\n            return f1Log();\n        }\n        else\n            QL_FAIL(\"unknown transform\");\n    }\n\n    Real FdmSquareRootFwdOp::f0Plain() const {\n        const Size n = 1;\n        const Real a = -(2*h(n-1)+h(n))/zetam(n);\n        const Real alpha = sigma_*sigma_*v(n)/zetam(n) - mu(n)*h(n)/zetam(n);\n        const Real nu = a*v(n-1) + (2*kappa_*(v(n-1)-theta_) + sigma_*sigma_)\n                                        /(sigma_*sigma_);\n\n        return alpha/nu*v(n-1);\n    }\n\n    Real FdmSquareRootFwdOp::f1Plain() const {\n        const Size n = v_.size();\n        const Real a =  (2*h(n)+h(n-1))/zetap(n);\n        const Real gamma = sigma_*sigma_*v(n)/zetap(n) + mu(n)*h(n-1)/zetap(n);\n        const Real nu = a*v(n+1) + (2*kappa_*(v(n+1)-theta_) + sigma_*sigma_)\n                        /(sigma_*sigma_);\n\n        return gamma/nu*v(n+1);\n    }\n\n    Real FdmSquareRootFwdOp::f0Power() const {\n        const Size n = 1;\n        const Real mu = kappa_*(v(n)+theta_);\n        const Real a = -(2*h(n-1)+h(n))/zetam(n);\n        const Real alpha = sigma_*sigma_*v(n)/zetam(n) - mu*h(n)/zetam(n);\n        const Real nu  = a*v(n-1) +2*(kappa_*v(n-1)/(sigma_*sigma_));\n\n        return alpha/nu*v(n-1);\n    }\n\n    Real FdmSquareRootFwdOp::f1Power() const {\n        const Size n = v_.size();\n        const Real mu = kappa_*(v(n)+theta_);\n        const Real a =  (2*h(n)+h(n-1))/zetap(n);\n        const Real gamma = sigma_*sigma_*v(n)/zetap(n) + mu*h(n-1)/zetap(n);\n        const Real nu = a*v(n+1) +2*(kappa_*v(n+1)/(sigma_*sigma_));\n\n        return gamma/nu*v(n+1); \n    }\n\n    Real FdmSquareRootFwdOp::f0Log() const {\n        const Size n = 1;\n        const Real mu = ((-kappa_*theta_-sigma_*sigma_/2.0)*exp(-v(1))+kappa_);\n        const Real a = -(2*h(n-1)+h(n))/zetam(n);\n        const Real alpha = sigma_*sigma_*exp(-v(n))/zetam(n) - mu*h(n)/zetam(n);\n        const Real nu = a*exp(-v(n-1)) + 2*kappa_*(1-theta_*exp(-v(n-1)))\n                        /(sigma_*sigma_);\n\n        return alpha/nu*exp(-v(n-1));\n    }\n\n    Real FdmSquareRootFwdOp::f1Log() const {\n        const Size n = v_.size();\n        const Real mu = ((-kappa_*theta_-sigma_*sigma_/2.0)*exp(-v(n))+kappa_);\n        const Real a =  (2*h(n)+h(n-1))/zetap(n);\n        const Real gamma = sigma_*sigma_*exp(-v(n))/zetap(n) + mu*h(n-1)/zetap(n);\n        const Real nu = a*exp(-v(n+1)) + 2*kappa_*(1-theta_*exp(-v(n+1)))\n                        /(sigma_*sigma_);\n\n        return gamma/nu*exp(-v(n+1));\n    }\n\n    Real FdmSquareRootFwdOp::v(Size i) const {\n        if (i > 0 && i <= v_.size()) {\n            return v_[i-1];\n        }\n        else if (i == 0) {\n            if (transform_ == Log) {\n                return 2*v_[0] - v_[1];\n//              log(std::max(0.5*exp(v_[0]), exp(v_[0] - 0.01 * (v_[1] - v_[0]))));\n            } else {\n                return std::max(0.5*v_[0], v_[0] - 0.01 * (v_[1] - v_[0]));\n            }\n        }\n        else if (i == v_.size()+1) {\n            return v_.back() + (v_.back() - *(v_.end()-2));\n        }\n        else {\n            QL_FAIL(\"unknown index\");\n        }\n    }\n\n    Real FdmSquareRootFwdOp::h(Size i) const {\n        return v(i+1) - v(i);\n    }\n    Real FdmSquareRootFwdOp::mu(Size i) const {\n        return kappa_*(v(i) - theta_) + sigma_*sigma_;\n    }\n    Real FdmSquareRootFwdOp::zetam(Size i) const {\n        return h(i-1)*(h(i-1)+h(i));\n    }\n    Real FdmSquareRootFwdOp::zeta(Size i) const {\n        return h(i-1)*h(i);\n    }\n    Real FdmSquareRootFwdOp::zetap(Size i) const {\n        return h(i)*(h(i-1)+h(i));\n    }\n\n    Size FdmSquareRootFwdOp::size() const {\n        return 1;\n    }\n    void FdmSquareRootFwdOp::setTime(Time, Time) {\n    }\n\n    void FdmSquareRootFwdOp::getCoeff(Real& alpha, Real& beta,\n                                               Real& gamma, Size n) const {\n        if (transform_ == Plain) {\n            getCoeffPlain(alpha, beta, gamma, n);\n        }\n        else if (transform_ == Power) {\n            getCoeffPower(alpha, beta, gamma, n);\n        }\n        else if (transform_ == Log) {\n            getCoeffLog(alpha, beta, gamma, n);\n        } \n    }\n\n    void FdmSquareRootFwdOp::getCoeffPlain(Real& alpha, Real& beta,\n                                               Real& gamma, Size n) const {\n        alpha =   sigma_*sigma_*v(n)/zetam(n) - mu(n)*h(n)/zetam(n);\n        beta  = - sigma_*sigma_*v(n)/zeta(n)\n                    + mu(n)*(h(n)-h(n-1))/zeta(n) + kappa_;\n        gamma =   sigma_*sigma_*v(n)/zetap(n) + mu(n)*h(n-1)/zetap(n);\n\n    }\n\n    void FdmSquareRootFwdOp::getCoeffLog(Real& alpha, Real& beta,\n                                               Real& gamma, Size n) const {\n        const Real mu = ((-kappa_*theta_-sigma_*sigma_/2.0)*exp(-v(n))+kappa_);\n        alpha =   sigma_*sigma_*exp(-v(n))/zetam(n) - mu*h(n)/zetam(n);\n        beta  = - sigma_*sigma_*exp(-v(n))/zeta(n)\n                          + mu*(h(n)-h(n-1))/zeta(n) + kappa_*theta_*exp(-v(n));\n        gamma =   sigma_*sigma_*exp(-v(n))/zetap(n) + mu*h(n-1)/zetap(n);\n    }\n\n    void FdmSquareRootFwdOp::getCoeffPower(Real& alpha, Real& beta,\n                                               Real& gamma, Size n) const {\n        const Real mu = kappa_*(theta_+v(n));\n        alpha = (sigma_*sigma_*v(n) - mu*h(n))/zetam(n);\n        beta = (-sigma_*sigma_*v(n) + mu*(h(n)-h(n-1)))/zeta(n)\n                                + 2*kappa_*kappa_*theta_/(sigma_*sigma_);\n        gamma=  (sigma_*sigma_*v(n) + mu*h(n-1))/zetap(n);\n    }\n\n    Disposable<Array> FdmSquareRootFwdOp::apply(const Array& p) const {\n        return mapX_->apply(p);\n    }\n\n    Disposable<Array> FdmSquareRootFwdOp::apply_mixed(const Array& r) const {\n        Array retVal(r.size(), 0.0);\n        return retVal;\n    }\n    Disposable<Array> FdmSquareRootFwdOp::apply_direction(\n        Size direction, const Array& r) const {\n        if (direction == direction_) {\n            return mapX_->apply(r);\n        }\n        else {\n            Array retVal(r.size(), 0.0);\n            return retVal;\n        }\n    }\n    Disposable<Array> FdmSquareRootFwdOp::solve_splitting(\n        Size direction, const Array& r, Real dt) const {\n        if (direction == direction_) {\n            return mapX_->solve_splitting(r, dt, 1.0);\n        }\n        else {\n            Array retVal(r);\n            return retVal;\n        }\n    }\n\n    Disposable<Array> FdmSquareRootFwdOp::preconditioner(\n        const Array& r, Real dt) const {\n        return solve_splitting(direction_, r, dt);\n    }\n\n    #if !defined(QL_NO_UBLAS_SUPPORT)\n    Disposable<std::vector<SparseMatrix> >\n    FdmSquareRootFwdOp::toMatrixDecomp() const {\n        std::vector<SparseMatrix> retVal(1, mapX_->toMatrix());\n        return retVal;\n    }\n    #endif\n}\n", "meta": {"hexsha": "1409c19b8a5f3c99e847827ceb1c3e051e490f8c", "size": 12473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/finitedifferences/fdmsquarerootfwdop.cpp", "max_stars_repo_name": "aashaka/QuantLib-1.9", "max_stars_repo_head_hexsha": "25e321c516d6e11603cdd01e3750e20461f5adf3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-23T20:34:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-23T20:34:32.000Z", "max_issues_repo_path": "ql/experimental/finitedifferences/fdmsquarerootfwdop.cpp", "max_issues_repo_name": "aashaka/QuantLib-1.9", "max_issues_repo_head_hexsha": "25e321c516d6e11603cdd01e3750e20461f5adf3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ql/experimental/finitedifferences/fdmsquarerootfwdop.cpp", "max_forks_repo_name": "aashaka/QuantLib-1.9", "max_forks_repo_head_hexsha": "25e321c516d6e11603cdd01e3750e20461f5adf3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3644314869, "max_line_length": 86, "alphanum_fraction": 0.5545578449, "num_tokens": 3474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4195636631240942}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_ELLIPTIC_FUNCTIONS_SCALAR_AM_HPP_INCLUDED\n#define NT2_ELLIPTIC_FUNCTIONS_SCALAR_AM_HPP_INCLUDED\n\n#include <nt2/elliptic/functions/am.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <nt2/elliptic/functions/generic/details/am_kernel.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/pio_2.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/functions/scalar/abs.hpp>\n#include <nt2/include/functions/scalar/atan.hpp>\n#include <nt2/include/functions/scalar/exp.hpp>\n#include <nt2/include/functions/scalar/is_equal.hpp>\n#include <nt2/include/functions/scalar/is_eqz.hpp>\n\nnamespace nt2 { namespace ext\n{\n\n   BOOST_DISPATCH_IMPLEMENT  (am_, tag::cpu_,\n                              (A0)(A1)(A2),\n                              (scalar_<floating_<A0> >)\n                              (scalar_<floating_<A1> >)\n                              (scalar_<floating_<A2> >)\n                             )\n  {\n    typedef A0 result_type;\n    BOOST_FORCEINLINE result_type operator()(const A0 & u, const A1 & x,\n                                             const A2 & tol) const\n    {\n      if(is_eqz(x)) return u;\n      result_type k = nt2::abs(x);\n      if(eq(k, One<A0>())) return Two<A0>()*atan(exp(u))-Pio_2<A0>();\n      return details::am_kernel(u, k, tol);\n    }\n  };\n\n} }\n#endif\n", "meta": {"hexsha": "850ff60e69381f229d29b118b28e13c026e5320e", "size": 1836, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/elliptic/include/nt2/elliptic/functions/scalar/am.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/elliptic/include/nt2/elliptic/functions/scalar/am.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/elliptic/include/nt2/elliptic/functions/scalar/am.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 39.0638297872, "max_line_length": 80, "alphanum_fraction": 0.5620915033, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4195636631240942}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2020, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGY_CARTESIAN_SIDE_NON_ROBUST_HPP\n#define BOOST_GEOMETRY_STRATEGY_CARTESIAN_SIDE_NON_ROBUST_HPP\n\n#include <boost/geometry/util/select_most_precise.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n#include <boost/geometry/util/precise_math.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace side\n{\n\n/*!\n\\brief Adaptive precision predicate to check at which side of a segment a point lies:\n    left of segment (>0), right of segment (< 0), on segment (0).\n\\ingroup strategies\n\\tparam CalculationType \\tparam_calculation\n\\details This predicate determines at which side of a segment a point lies\n*/\ntemplate\n<\n    typename CalculationType = void\n>\nstruct side_non_robust\n{\npublic:\n    //! \\brief Computes double the signed area of the CCW triangle p1, p2, p\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n    template\n    <\n        typename P1,\n        typename P2,\n        typename P\n    >\n    static inline int apply(P1 const& p1, P2 const& p2, P const& p)\n    {\n        typedef typename select_calculation_type_alt\n            <\n                CalculationType,\n                P1,\n                P2,\n                P\n            >::type coordinate_type;\n        typedef typename select_most_precise\n            <\n                coordinate_type,\n                double\n            >::type promoted_type;\n\n        auto detleft = (promoted_type(get<0>(p1)) - promoted_type(get<0>(p)))\n                * (promoted_type(get<1>(p2)) - promoted_type(get<1>(p)));\n        auto detright = (promoted_type(get<1>(p1)) - promoted_type(get<1>(p)))\n                * (promoted_type(get<0>(p2)) - promoted_type(get<0>(p)));\n        return detleft > detright ? 1 : (detleft < detright ? -1 : 0 );\n\n    }\n#endif\n\n};\n\n}} // namespace strategy::side\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGY_CARTESIAN_SIDE_NON_ROBUST_HPP\n", "meta": {"hexsha": "2ef109cc1b1f23a1a704790b008cbaeb4848fc3c", "size": 2143, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategy/cartesian/side_non_robust.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategy/cartesian/side_non_robust.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategy/cartesian/side_non_robust.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 27.8311688312, "max_line_length": 85, "alphanum_fraction": 0.6649556696, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.41955156343075906}}
{"text": "#ifndef STAN_ANALYZE_MCMC_COMPUTE_EFFECTIVE_SAMPLE_SIZE_HPP\n#define STAN_ANALYZE_MCMC_COMPUTE_EFFECTIVE_SAMPLE_SIZE_HPP\n\n#include <stan/math/prim/fun/Eigen.hpp>\n#include <stan/analyze/mcmc/autocovariance.hpp>\n#include <stan/analyze/mcmc/split_chains.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <limits>\n\nnamespace stan {\nnamespace analyze {\n/**\n * Computes the effective sample size (ESS) for the specified\n * parameter across all kept samples.  The value returned is the\n * minimum of ESS and the number_total_draws *\n * log10(number_total_draws).\n *\n * See more details in Stan reference manual section \"Effective\n * Sample Size\". http://mc-stan.org/users/documentation\n *\n * Current implementation assumes draws are stored in contiguous\n * blocks of memory.  Chains are trimmed from the back to match the\n * length of the shortest chain.  Note that the effective sample size\n * can not be estimated with less than four draws.\n *\n * @param draws stores pointers to arrays of chains\n * @param sizes stores sizes of chains\n * @return effective sample size for the specified parameter\n */\ninline double compute_effective_sample_size(std::vector<const double*> draws,\n                                            std::vector<size_t> sizes) {\n  int num_chains = sizes.size();\n  size_t num_draws = sizes[0];\n  for (int chain = 1; chain < num_chains; ++chain) {\n    num_draws = std::min(num_draws, sizes[chain]);\n  }\n\n  if (num_draws < 4) {\n    return std::numeric_limits<double>::quiet_NaN();\n  }\n\n  // check if chains are constant; all equal to first draw's value\n  bool are_all_const = false;\n  Eigen::VectorXd init_draw = Eigen::VectorXd::Zero(num_chains);\n\n  for (int chain_idx = 0; chain_idx < num_chains; chain_idx++) {\n    Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>> draw(\n        draws[chain_idx], sizes[chain_idx]);\n\n    for (int n = 0; n < num_draws; n++) {\n      if (!boost::math::isfinite(draw(n))) {\n        return std::numeric_limits<double>::quiet_NaN();\n      }\n    }\n\n    init_draw(chain_idx) = draw(0);\n\n    if (draw.isApproxToConstant(draw(0))) {\n      are_all_const |= true;\n    }\n  }\n\n  if (are_all_const) {\n    // If all chains are constant then return NaN\n    // if they all equal the same constant value\n    if (init_draw.isApproxToConstant(init_draw(0))) {\n      return std::numeric_limits<double>::quiet_NaN();\n    }\n  }\n\n  Eigen::Matrix<Eigen::VectorXd, Eigen::Dynamic, 1> acov(num_chains);\n  Eigen::VectorXd chain_mean(num_chains);\n  Eigen::VectorXd chain_var(num_chains);\n  for (int chain = 0; chain < num_chains; ++chain) {\n    Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>> draw(\n        draws[chain], sizes[chain]);\n    autocovariance<double>(draw, acov(chain));\n    chain_mean(chain) = draw.mean();\n    chain_var(chain) = acov(chain)(0) * num_draws / (num_draws - 1);\n  }\n\n  double mean_var = chain_var.mean();\n  double var_plus = mean_var * (num_draws - 1) / num_draws;\n  if (num_chains > 1)\n    var_plus += math::variance(chain_mean);\n  Eigen::VectorXd rho_hat_s(num_draws);\n  rho_hat_s.setZero();\n  Eigen::VectorXd acov_s(num_chains);\n  for (int chain = 0; chain < num_chains; ++chain)\n    acov_s(chain) = acov(chain)(1);\n  double rho_hat_even = 1.0;\n  rho_hat_s(0) = rho_hat_even;\n  double rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus;\n  rho_hat_s(1) = rho_hat_odd;\n\n  // Convert raw autocovariance estimators into Geyer's initial\n  // positive sequence. Loop only until num_draws - 4 to\n  // leave the last pair of autocorrelations as a bias term that\n  // reduces variance in the case of antithetical chains.\n  size_t s = 1;\n  while (s < (num_draws - 4) && (rho_hat_even + rho_hat_odd) > 0) {\n    for (int chain = 0; chain < num_chains; ++chain)\n      acov_s(chain) = acov(chain)(s + 1);\n    rho_hat_even = 1 - (mean_var - acov_s.mean()) / var_plus;\n    for (int chain = 0; chain < num_chains; ++chain)\n      acov_s(chain) = acov(chain)(s + 2);\n    rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus;\n    if ((rho_hat_even + rho_hat_odd) >= 0) {\n      rho_hat_s(s + 1) = rho_hat_even;\n      rho_hat_s(s + 2) = rho_hat_odd;\n    }\n    s += 2;\n  }\n\n  int max_s = s;\n  // this is used in the improved estimate, which reduces variance\n  // in antithetic case -- see tau_hat below\n  if (rho_hat_even > 0)\n    rho_hat_s(max_s + 1) = rho_hat_even;\n\n  // Convert Geyer's initial positive sequence into an initial\n  // monotone sequence\n  for (int s = 1; s <= max_s - 3; s += 2) {\n    if (rho_hat_s(s + 1) + rho_hat_s(s + 2) > rho_hat_s(s - 1) + rho_hat_s(s)) {\n      rho_hat_s(s + 1) = (rho_hat_s(s - 1) + rho_hat_s(s)) / 2;\n      rho_hat_s(s + 2) = rho_hat_s(s + 1);\n    }\n  }\n\n  double num_total_draws = num_chains * num_draws;\n  // Geyer's truncated estimator for the asymptotic variance\n  // Improved estimate reduces variance in antithetic case\n  double tau_hat = -1 + 2 * rho_hat_s.head(max_s).sum() + rho_hat_s(max_s + 1);\n  return std::min(num_total_draws / tau_hat,\n                  num_total_draws * std::log10(num_total_draws));\n}\n\n/**\n * Computes the effective sample size (ESS) for the specified\n * parameter across all kept samples.  The value returned is the\n * minimum of ESS and the number_total_draws *\n * log10(number_total_draws).\n *\n * See more details in Stan reference manual section \"Effective\n * Sample Size\". http://mc-stan.org/users/documentation\n *\n * Current implementation assumes draws are stored in contiguous\n * blocks of memory.  Chains are trimmed from the back to match the\n * length of the shortest chain.  Note that the effective sample size\n * can not be estimated with less than four draws.  Argument size\n * will be broadcast to same length as draws.\n *\n * @param draws stores pointers to arrays of chains\n * @param size size of chains\n * @return effective sample size for the specified parameter\n */\ninline double compute_effective_sample_size(std::vector<const double*> draws,\n                                            size_t size) {\n  int num_chains = draws.size();\n  std::vector<size_t> sizes(num_chains, size);\n  return compute_effective_sample_size(draws, sizes);\n}\n\n/**\n * Computes the split effective sample size (ESS) for the specified\n * parameter across all kept samples.  The value returned is the\n * minimum of ESS and the number_total_draws *\n * log10(number_total_draws). When the number of total draws N is\n * odd, the (N+1)/2th draw is ignored.\n *\n * See more details in Stan reference manual section \"Effective\n * Sample Size\". http://mc-stan.org/users/documentation\n *\n * Current implementation assumes draws are stored in contiguous\n * blocks of memory.  Chains are trimmed from the back to match the\n * length of the shortest chain.  Note that the effective sample size\n * can not be estimated with less than four draws.\n *\n * @param draws stores pointers to arrays of chains\n * @param sizes stores sizes of chains\n * @return effective sample size for the specified parameter\n */\ninline double compute_split_effective_sample_size(\n    std::vector<const double*> draws, std::vector<size_t> sizes) {\n  int num_chains = sizes.size();\n  size_t num_draws = sizes[0];\n  for (int chain = 1; chain < num_chains; ++chain) {\n    num_draws = std::min(num_draws, sizes[chain]);\n  }\n\n  std::vector<const double*> split_draws = split_chains(draws, sizes);\n\n  double half = num_draws / 2.0;\n  std::vector<size_t> half_sizes(2 * num_chains, std::floor(half));\n\n  return compute_effective_sample_size(split_draws, half_sizes);\n}\n\n/**\n * Computes the split effective sample size (ESS) for the specified\n * parameter across all kept samples.  The value returned is the\n * minimum of ESS and the number_total_draws *\n * log10(number_total_draws). When the number of total draws N is\n * odd, the (N+1)/2th draw is ignored.\n *\n * See more details in Stan reference manual section \"Effective\n * Sample Size\". http://mc-stan.org/users/documentation\n *\n * Current implementation assumes draws are stored in contiguous\n * blocks of memory.  Chains are trimmed from the back to match the\n * length of the shortest chain.  Note that the effective sample size\n * can not be estimated with less than four draws.  Argument size\n * will be broadcast to same length as draws.\n *\n * @param draws stores pointers to arrays of chains\n * @param size size of chains\n * @return effective sample size for the specified parameter\n */\ninline double compute_split_effective_sample_size(\n    std::vector<const double*> draws, size_t size) {\n  int num_chains = draws.size();\n  std::vector<size_t> sizes(num_chains, size);\n  return compute_split_effective_sample_size(draws, sizes);\n}\n\n}  // namespace analyze\n}  // namespace stan\n\n#endif\n", "meta": {"hexsha": "4d58330b202776107f0137287162252d278aa9a8", "size": 8707, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/analyze/mcmc/compute_effective_sample_size.hpp", "max_stars_repo_name": "sidkapoor97/stan", "max_stars_repo_head_hexsha": "70b2b23f2312320b1008d776fdf44461ae2f52ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/stan/analyze/mcmc/compute_effective_sample_size.hpp", "max_issues_repo_name": "sidkapoor97/stan", "max_issues_repo_head_hexsha": "70b2b23f2312320b1008d776fdf44461ae2f52ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stan/analyze/mcmc/compute_effective_sample_size.hpp", "max_forks_repo_name": "sidkapoor97/stan", "max_forks_repo_head_hexsha": "70b2b23f2312320b1008d776fdf44461ae2f52ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3690987124, "max_line_length": 80, "alphanum_fraction": 0.6998966349, "num_tokens": 2300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.6548947425132315, "lm_q1q2_score": 0.419549053200119}}
{"text": "/*\n * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the Autonomous Systems Lab, ETH Zurich nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL Christian Gehring, Hannes Sommer, Paul Furgale,\n * Remo Diethelm BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n*/\n\n#pragma once\n\n#include <cmath>\n\n#include <Eigen/Geometry>\n\n#include \"kindr/common/common.hpp\"\n#include \"kindr/common/assert_macros_eigen.hpp\"\n#include \"kindr/rotations/RotationBase.hpp\"\n\nnamespace kindr {\n\n\n/*! \\class RotationMatrix\n *  \\brief Implementation of matrix rotation based on Eigen::Matrix<Scalar, 3, 3>\n *\n *  The following four typedefs are provided for convenience:\n *   - \\ref RotationMatrixAD \"RotationMatrixD\" for double primitive type\n *   - \\ref RotationMatrixAF \"RotationMatrixF\" for float primitive type\n *\n *  \\tparam PrimType_ the primitive type of the data (double or float)\n *\n *  \\ingroup rotations\n */\ntemplate<typename PrimType_>\nclass RotationMatrix : public RotationBase<RotationMatrix<PrimType_>>, private Eigen::Matrix<PrimType_, 3, 3> {\n private:\n  /*! \\brief The base type.\n   */\n  typedef Eigen::Matrix<PrimType_, 3, 3> Base;\n public:\n  /*! \\brief The implementation type.\n   *  The implementation type is always an Eigen object.\n   */\n  typedef Base Implementation;\n  /*! \\brief The primitive type.\n   *  Float/Double\n   */\n  typedef PrimType_ Scalar;\n\n  /*! \\brief Default constructor using identity rotation.\n   */\n  RotationMatrix()\n    : Base(Base::Identity()) {\n  }\n\n  /*! \\brief Constructor using nine scalars.\n   *  In debug mode, an assertion is thrown if the matrix is not a rotation matrix.\n   *  \\param r11     entry in row 1, col 1\n   *  \\param r12     entry in row 1, col 2\n   *  \\param r13     entry in row 1, col 3\n   *  \\param r21     entry in row 2, col 1\n   *  \\param r22     entry in row 2, col 2\n   *  \\param r23     entry in row 2, col 3\n   *  \\param r31     entry in row 3, col 1\n   *  \\param r32     entry in row 3, col 2\n   *  \\param r33     entry in row 3, col 3\n   */\n  RotationMatrix(Scalar r11, Scalar r12, Scalar r13,\n                 Scalar r21, Scalar r22, Scalar r23,\n                 Scalar r31, Scalar r32, Scalar r33) {\n\n    *this << r11,r12,r13,r21,r22,r23,r31,r32,r33;\n\n    KINDR_ASSERT_MATRIX_NEAR_DBG(std::runtime_error, this->toImplementation() * this->toImplementation().transpose(), Base::Identity(), static_cast<Scalar>(1e-4), \"Input matrix is not orthogonal.\");\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, this->determinant(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input matrix determinant is not 1.\");\n  }\n\n  /*! \\brief Constructor using Eigen::Matrix.\n   *  In debug mode, an assertion is thrown if the rotation vector has not unit length.\n   *  \\param other   Eigen::Matrix<PrimType_,3,3>\n   */\n  explicit RotationMatrix(const Base& other)\n  // : Base(other)\n  {\n\n    this->toImplementation() = other;\n\n    KINDR_ASSERT_MATRIX_NEAR_DBG(std::runtime_error, other * other.transpose(), Base::Identity(), static_cast<Scalar>(1e-4), \"Input matrix is not orthogonal.\");\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, other.determinant(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input matrix determinant is not 1.\");\n  }\n\n  /*! \\brief Constructor using another rotation.\n   *  \\param other   other rotation\n   */\n  template<typename OtherDerived_>\n  inline explicit RotationMatrix(const RotationBase<OtherDerived_>& other)\n  // : Base(internal::ConversionTraits<RotationMatrix, OtherDerived_>::convert(other.derived()).toImplementation())\n  {\n    this->toImplementation() = internal::ConversionTraits<RotationMatrix, OtherDerived_>::convert(other.derived()).toImplementation();\n  }\n\n  /*! \\brief Assignment operator using another rotation.\n   *  \\param other   other rotation\n   *  \\returns referece\n   */\n  template<typename OtherDerived_>\n  RotationMatrix& operator =(const RotationBase<OtherDerived_>& other) {\n    this->toImplementation() = internal::ConversionTraits<RotationMatrix, OtherDerived_>::convert(other.derived()).toImplementation();\n    return *this;\n  }\n\n  /*! \\brief Parenthesis operator to convert from another rotation.\n   *  \\param other   other rotation\n   *  \\returns reference\n   */\n  template<typename OtherDerived_>\n  RotationMatrix& operator ()(const RotationBase<OtherDerived_>& other) {\n    this->toImplementation() = internal::ConversionTraits<RotationMatrix, OtherDerived_>::convert(other.derived()).toImplementation();\n    return *this;\n  }\n\n  /*! \\brief Returns the inverse of the rotation.\n   *  \\returns the inverse of the rotation\n   */\n  RotationMatrix inverted() const {\n    RotationMatrix matrix;\n    matrix.toImplementation() = this->toImplementation().transpose();\n    return matrix;\n  }\n\n  /*! \\brief Inverts the rotation.\n   *  \\returns reference\n   */\n  RotationMatrix& invert() {\n    *this = this->inverted();\n    return *this;\n  }\n\n  /*! \\brief Returns the transpose of the rotation matrix.\n   *  \\returns the inverse of the rotation\n   */\n  RotationMatrix transposed() const {\n    RotationMatrix matrix;\n    matrix.toImplementation() = this->toImplementation().transpose();\n    return matrix;\n  }\n\n  /*! \\brief Transposes the rotation matrix.\n   *  \\returns reference\n   */\n  RotationMatrix& transpose() {\n    *this = this->transposed();\n    return *this;\n  }\n\n  /*! \\brief Returns the determinant of the rotation matrix.\n   *  \\returns determinant of the rotation matrix\n   */\n  Scalar determinant() const {\n  return toImplementation().determinant();\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation for direct manipulation (recommended only for advanced users)\n   */\n  inline Implementation& toImplementation() {\n    return static_cast<Implementation&>(*this);\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation for direct manipulation (recommended only for advanced users)\n   */\n  inline const Implementation& toImplementation() const {\n    return static_cast<const Implementation&>(*this);\n  }\n\n  /*! \\brief Reading access to the rotation matrix.\n   *  \\returns rotation matrix (matrix) with reading access\n   */\n  inline Implementation matrix() const {\n      return this->toImplementation();\n  }\n\n  /*! \\brief  Writing access to the rotation matrix.\n   */\n  inline void setMatrix(const Implementation & input) {\n      this->toImplementation() = input;\n  }\n\n  /*! \\brief  Writing access to the rotation matrix.\n   */\n  inline void setMatrix(Scalar r11, Scalar r12, Scalar r13,\n                        Scalar r21, Scalar r22, Scalar r23,\n                        Scalar r31, Scalar r32, Scalar r33) {\n\n     *this << r11,r12,r13,r21,r22,r23,r31,r32,r33;\n\n  }\n\n  /*! \\brief Sets the rotation to identity.\n   *  \\returns reference\n   */\n  RotationMatrix& setIdentity() {\n    this->Implementation::setIdentity();\n    return *this;\n  }\n\n  /*! \\brief Returns a unique matrix rotation.\n   *  A rotation matrix is always unique.\n   *  This function is used to compare different rotations.\n   *  \\returns copy of the matrix rotation which is unique\n   */\n  RotationMatrix getUnique() const {\n    return *this;\n  }\n\n  /*! \\brief Modifies the matrix rotation such that it becomes unique.\n   *  A rotation matrix is always unique.\n   *  \\returns reference\n   */\n  RotationMatrix& setUnique() {\n    return *this;\n  }\n\n  /*! \\brief Concenation operator.\n   *  This is explicitly specified, because Eigen::Matrix provides also an operator*.\n   *  \\returns the concenation of two rotations\n   */\n  using RotationBase<RotationMatrix<PrimType_>>::operator*; // otherwise ambiguous RotationBase and Eigen\n\n  /*! \\brief Equivalence operator.\n   *  This is explicitly specified, because Eigen::Matrix provides also an operator==.\n   *  \\returns true if two rotations are equal.\n   */\n  using RotationBase<RotationMatrix<PrimType_>>::operator==; // otherwise ambiguous RotationBase and Eigen\n\n  /*! \\brief Inequivalence operator.\n   *  This is explicitly specified, because Eigen::Matrix provides also an operator!=.\n   *  \\returns true if two rotations are not equal.\n   */\n  using RotationBase<RotationMatrix<PrimType_>>::operator!=; // otherwise ambiguous RotationBase and Eigen\n\n\n  /*! \\brief Used for printing the object with std::cout.\n   *  \\returns std::stream object\n   */\n  friend std::ostream& operator << (std::ostream& out, const RotationMatrix& rotationMatrix) {\n    out << rotationMatrix.toImplementation();\n    return out;\n  }\n};\n\n//! \\brief Active matrix rotation with double primitive type\ntypedef RotationMatrix<double>  RotationMatrixD;\n//! \\brief Active matrix rotation with float primitive type\ntypedef RotationMatrix<float>  RotationMatrixF;\n//! \\brief Passive matrix rotation with double primitive type\ntypedef RotationMatrix<double> RotationMatrixPD;\n//! \\brief Passive matrix rotation with float primitive type\ntypedef RotationMatrix<float> RotationMatrixPF;\n\n\n\nnamespace internal {\n\ntemplate<typename PrimType_>\nclass get_scalar<RotationMatrix<PrimType_>> {\n public:\n  typedef PrimType_ Scalar;\n};\n\ntemplate<typename PrimType_>\nclass get_matrix3X<RotationMatrix<PrimType_>>{\n public:\n  typedef int  IndexType;\n\n  template <IndexType Cols>\n  using Matrix3X = Eigen::Matrix<PrimType_, 3, Cols>;\n};\n\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Conversion Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\ntemplate<typename DestPrimType_, typename SourcePrimType_>\nclass ConversionTraits<RotationMatrix<DestPrimType_>, AngleAxis<SourcePrimType_>> {\n public:\n  inline static RotationMatrix<DestPrimType_> convert(const AngleAxis<SourcePrimType_>& aa) {\n    RotationMatrix<DestPrimType_> matrix;\n    matrix.toImplementation() = (aa.toImplementation().template cast<DestPrimType_>()).toRotationMatrix();\n    return matrix;\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_>\nclass ConversionTraits<RotationMatrix<DestPrimType_>, RotationVector<SourcePrimType_>> {\n public:\n  inline static RotationMatrix<DestPrimType_> convert(const RotationVector<SourcePrimType_>& rotationVector) {\n    return RotationMatrix<DestPrimType_>(RotationQuaternion<DestPrimType_>(rotationVector));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_>\nclass ConversionTraits<RotationMatrix<DestPrimType_>, RotationQuaternion<SourcePrimType_>> {\n public:\n  inline static RotationMatrix<DestPrimType_> convert(const RotationQuaternion<SourcePrimType_>& q) {\n    RotationMatrix<DestPrimType_> matrix;\n    matrix.toImplementation() = (q.toImplementation().template cast<DestPrimType_>()).toRotationMatrix();\n    return matrix;\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_>\nclass ConversionTraits<RotationMatrix<DestPrimType_>, RotationMatrix<SourcePrimType_>> {\n public:\n  inline static RotationMatrix<DestPrimType_> convert(const RotationMatrix<SourcePrimType_>& R) {\n    RotationMatrix<DestPrimType_> matrix;\n    matrix.toImplementation() = R.toImplementation().template cast<DestPrimType_>();\n    return matrix;\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_>\nclass ConversionTraits<RotationMatrix<DestPrimType_>, EulerAnglesXyz<SourcePrimType_>> {\n public:\n  inline static RotationMatrix<DestPrimType_> convert(const EulerAnglesXyz<SourcePrimType_>& xyz) {\n      RotationMatrix<DestPrimType_> matrix;\n      matrix.toImplementation() = RotationQuaternion<DestPrimType_>(xyz).toImplementation().toRotationMatrix();\n      return matrix;\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_>\nclass ConversionTraits<RotationMatrix<DestPrimType_>, EulerAnglesZyx<SourcePrimType_>> {\n public:\n  inline static RotationMatrix<DestPrimType_> convert(const EulerAnglesZyx<SourcePrimType_>& zyx) {\n    RotationMatrix<DestPrimType_> matrix;\n    matrix.toImplementation() = RotationQuaternion<DestPrimType_>(zyx).toImplementation().toRotationMatrix();\n    return matrix;\n  }\n};\n\n\n\n/*! \\brief Multiplication of two rotation matrices\n */\ntemplate<typename PrimType_>\nclass MultiplicationTraits<RotationBase<RotationMatrix<PrimType_>>, RotationBase<RotationMatrix<PrimType_>>> {\n public:\n  inline static RotationMatrix<PrimType_> mult(const RotationMatrix<PrimType_>& lhs, const RotationMatrix<PrimType_>& rhs) {\n      RotationMatrix<PrimType_> result;\n      result.toImplementation() = lhs.toImplementation() * rhs.toImplementation();\n      return result;\n  }\n};\n\n\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Rotation Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Comparison Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Box Operations - required?\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Fixing Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\ntemplate<typename PrimType_>\nclass FixingTraits<RotationMatrix<PrimType_>> {\n public:\n  inline static void fix(RotationMatrix<PrimType_>& R) {\n    const PrimType_ factor = 1/pow(R.determinant(), 1.0/3.0);\n    R.setMatrix(factor*R.matrix()(0,0),\n                factor*R.matrix()(0,1),\n                factor*R.matrix()(0,2),\n                factor*R.matrix()(1,0),\n                factor*R.matrix()(1,1),\n                factor*R.matrix()(1,2),\n                factor*R.matrix()(2,0),\n                factor*R.matrix()(2,1),\n                factor*R.matrix()(2,2));\n  }\n};\n\n\n} // namespace internal\n} // namespace kindr\n", "meta": {"hexsha": "609237f6c60a575716ee3049cc46d87d2dd65a2d", "size": 16529, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kindr/rotations/RotationMatrix.hpp", "max_stars_repo_name": "ThomasZiegler/kindr", "max_stars_repo_head_hexsha": "63f8dbab6e382f525614fd5db94e8dfacac44d4e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-05T13:17:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-05T13:17:18.000Z", "max_issues_repo_path": "include/kindr/rotations/RotationMatrix.hpp", "max_issues_repo_name": "ThomasZiegler/kindr", "max_issues_repo_head_hexsha": "63f8dbab6e382f525614fd5db94e8dfacac44d4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/kindr/rotations/RotationMatrix.hpp", "max_forks_repo_name": "ThomasZiegler/kindr", "max_forks_repo_head_hexsha": "63f8dbab6e382f525614fd5db94e8dfacac44d4e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8289156627, "max_line_length": 217, "alphanum_fraction": 0.6247806885, "num_tokens": 3428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.640635854839898, "lm_q1q2_score": 0.419549053200119}}
{"text": "#include \"multiplicative_relations.h\"\n#include <hamming/jain_commitment/jain_commitment.h>\n#include <NTL/mat_GF2.h>\n#include <NTL/vec_GF2.h>\n#include <hamming/knowledge_of_valid_opening/knowledge_of_valid_opening.h>\n#include <utils/utils.h>\n\nvoid hamming_metric::multiplicative_relations::initialize_commitments_and_responses(\n        commitments_t *commitments,\n        responses_t *responses) {\n\n    responses->t_i_0.SetLength(I);\n    responses->t_i_1.SetLength(I);\n    responses->t_i_2.SetLength(I);\n    responses->t_i_j_0.SetLength(I);\n    responses->t_i_j_1.SetLength(I);\n    responses->t_i_j_2.SetLength(I);\n\n    commitments->c_i_0.SetLength(I);\n    commitments->c_i_1.SetLength(I);\n    commitments->c_i_2.SetLength(I);\n    commitments->c_i_j_0.SetLength(I);\n    commitments->c_i_j_1.SetLength(I);\n    commitments->c_i_j_2.SetLength(I);\n\n    commitments->r_i_0.SetLength(I);\n    commitments->r_i_1.SetLength(I);\n    commitments->r_i_2.SetLength(I);\n    commitments->r_i_j_0.SetLength(I);\n    commitments->r_i_j_1.SetLength(I);\n    commitments->r_i_j_2.SetLength(I);\n\n    for (int i = 0; i < I; i++) {\n        responses->t_i_j_0[i].SetLength(J);\n        responses->t_i_j_1[i].SetLength(J);\n        responses->t_i_j_2[i].SetLength(J);\n\n        commitments->c_i_j_0[i].SetLength(J);\n        commitments->c_i_j_1[i].SetLength(J);\n        commitments->c_i_j_2[i].SetLength(J);\n\n        commitments->r_i_j_0[i].SetLength(J);\n        commitments->r_i_j_1[i].SetLength(J);\n        commitments->r_i_j_2[i].SetLength(J);\n    }\n}\n\nvoid hamming_metric::multiplicative_relations::generate_private_key(\n        private_key_t *private_key) {\n\n    //Generate m\n    {\n        private_key->m.kill();\n        private_key->m.SetLength(I);\n\n        utils::generate_random_binary_vector(\n                private_key->m[0],\n                JAIN_V);\n\n        utils::generate_random_binary_vector(\n                private_key->m[1],\n                JAIN_V);\n\n        private_key->m[2].SetLength(JAIN_V);\n        for (int i = 0; i < JAIN_V; i++) {\n            private_key->m[2][i] = private_key->m[0][i] * private_key->m[1][i];\n        }\n    }\n\n    //Generate e\n    {\n        private_key->e.kill();\n        private_key->e.SetLength(I);\n\n        for (int i = 0; i < I; i++) {\n            utils::generate_vector_of_weight_w(\n                    private_key->e[i],\n                    JAIN_K,\n                    W);\n        }\n    }\n}\n\nvoid hamming_metric::multiplicative_relations::generate_public_key(\n        public_key_t *public_key,\n        const private_key_t *private_key) {\n\n    public_key->commitments_i.kill();\n    public_key->commitments_i.SetLength(I);\n\n    utils::generate_random_binary_matrix(\n            public_key->A,\n            JAIN_K,\n            JAIN_L + JAIN_V);\n\n\n    for (int i = 0; i < I; i++) {\n        NTL::vec_GF2 r;\n        utils::generate_random_binary_vector(\n                r,\n                JAIN_L);\n\n        hamming_metric::commitment::generate_commitment(\n                public_key->commitments_i[i],\n                public_key->A,\n                r,\n                private_key->m[i],\n                private_key->e[i]);\n    }\n}\n\nvoid hamming_metric::multiplicative_relations::generate_random_values(\n        random_values_t *random_values,\n        const multiplicative_relation_matrices_t *matrices) {\n\n    //Generate u_i_j\n    {\n        random_values->u_i_j.kill();\n        random_values->u_i_j.SetLength(I);\n        for (int i = 0; i < I; i++) {\n            random_values->u_i_j[i].SetLength(J);\n            for (int j = 0; j < J; j++) {\n                random_values->u_i_j[i][j] = NTL::random_vec_GF2(JAIN_L);\n            }\n        }\n    }\n\n    //Generate f_i_j\n    {\n        random_values->f_i_j.kill();\n        random_values->f_i_j.SetLength(I);\n        for (int i = 0; i < I; i++) {\n            random_values->f_i_j[i].SetLength(J);\n            for (int j = 0; j < J; j++) {\n                random_values->f_i_j[i][j] = NTL::random_vec_GF2(JAIN_K);\n            }\n        }\n    }\n\n    //Generate v_i_j\n    {\n        random_values->v_i_j.kill();\n        random_values->v_i_j.SetLength(I);\n        for (int i = 0; i < I; i++) {\n            random_values->v_i_j[i].SetLength(J);\n            for (int j = 0; j < J; j++) {\n                random_values->v_i_j[i][j] = NTL::random_vec_GF2(JAIN_V);\n            }\n        }\n    }\n\n    {\n        random_values->u_i.kill();\n        random_values->u_i.SetLength(I);\n        for (int i = 0; i < I; i++) {\n            random_values->u_i[i] = NTL::random_vec_GF2(JAIN_L);\n        }\n    }\n\n    {\n        random_values->f_i.kill();\n        random_values->f_i.SetLength(I);\n        for (int i = 0; i < I; i++) {\n            random_values->f_i[i] = NTL::random_vec_GF2(JAIN_K);\n        }\n    }\n\n    //Generate v_i\n    {\n        random_values->v_i.kill();\n        random_values->v_i.SetLength(I);\n        for (int i = 0; i < I; i++) {\n            random_values->v_i[i].SetLength(JAIN_V);\n            for (int j = 0; j < J; j++) {\n                random_values->v_i[i] += (matrices->R[j] * random_values->v_i_j[i][j]);\n            }\n        }\n    }\n}\n\nvoid hamming_metric::multiplicative_relations::generate_revealed_values(\n        revealed_values_t *revealed_values,\n        const private_key_t *private_key,\n        const public_key_t *public_key) {\n\n    revealed_values->commitments_i_j.kill();\n    revealed_values->commitments_i_j.SetLength(I);\n\n    revealed_values->e_i_j.kill();\n    revealed_values->e_i_j.SetLength(I);\n\n    revealed_values->P_i.SetLength(I);\n    revealed_values->P_i_j.SetLength(I);\n\n    NTL::Vec<NTL::vec_GF2> m_prime_i;\n    {\n        m_prime_i.SetLength(I);\n        utils::sample_messages(m_prime_i[0], m_prime_i[1], m_prime_i[2], JAIN_V);\n        utils::generate_relation_matrix(\n                revealed_values->matrices._R,\n                revealed_values->matrices.R,\n                m_prime_i,\n                private_key->m,\n                JAIN_V);\n    }\n\n\n    {\n        generate_m_prime_i_j_from_m_prime_i(\n                revealed_values->m_prime_i_j,\n                m_prime_i);\n    }\n\n    NTL::vec_GF2 r;\n    for (int i = 0; i < I; i++) {\n        revealed_values->commitments_i_j[i].SetLength(J);\n        revealed_values->e_i_j[i].SetLength(J);\n        revealed_values->P_i_j[i].SetLength(J);\n\n        utils::create_permutation_matrix(\n                revealed_values->P_i[i],\n                JAIN_K);\n\n        for (int j = 0; j < J; j++) {\n            utils::create_permutation_matrix(\n                    revealed_values->P_i_j[i][j],\n                    JAIN_K);\n\n            utils::generate_random_binary_vector(\n                    r,\n                    JAIN_L);\n\n            utils::generate_vector_of_weight_w(\n                    revealed_values->e_i_j[i][j],\n                    JAIN_K,\n                    W);\n\n            hamming_metric::commitment::generate_commitment(\n                    revealed_values->commitments_i_j[i][j],\n                    public_key->A,\n                    r,\n                    revealed_values->m_prime_i_j[i][j],\n                    revealed_values->e_i_j[i][j]);\n        }\n    }\n}\n\nvoid hamming_metric::multiplicative_relations::generate_m_prime_i_j_from_m_prime_i(\n        NTL::Vec<NTL::Vec<NTL::vec_GF2>> &m_prime_i_j,\n        const NTL::Vec<NTL::vec_GF2> &m_prime_i) {\n\n    m_prime_i_j.kill();\n    m_prime_i_j.SetLength(I);\n    int start_index;\n\n    for (int i = 0; i < I; i++) {\n        m_prime_i_j[i].SetLength(J);\n        start_index = 0;\n        for (int j = 0; j < J; j++) {\n            NTL::vec_GF2 tmp;\n            tmp.SetLength(JAIN_V);\n            for (int z = 0; z < JAIN_V; z++) {\n                tmp[z] = m_prime_i[i][start_index + z];\n            }\n            start_index += JAIN_V;\n            m_prime_i_j[i][j].append(tmp);\n        }\n    }\n\n}\n\nvoid hamming_metric::multiplicative_relations::generate_commitments_and_responses(\n        responses_t *responses,\n        commitments_t *commitments,\n        const random_values_t *random_values,\n        const revealed_values_t *revealed_values,\n        const public_key_t *public_key,\n        const private_key_t *private_key) {\n\n    for (int i = 0; i < I; i++) {\n\n        auto u_v = random_values->u_i[i];\n        u_v.append(random_values->v_i[i]);\n        knowledge_of_valid_opening::generate_commitment_and_response_0(\n                commitments->c_i_0[i],\n                commitments->r_i_0[i],\n                responses->t_i_0[i],\n                u_v,\n                public_key->A,\n                random_values->f_i[i]);\n\n        knowledge_of_valid_opening::generate_commitment_and_response_1(\n                commitments->c_i_1[i],\n                commitments->r_i_1[i],\n                responses->t_i_1[i],\n                public_key->A,\n                revealed_values->P_i[i],\n                random_values->f_i[i]);\n\n        knowledge_of_valid_opening::generate_commitment_and_response_2(\n                commitments->c_i_2[i],\n                commitments->r_i_2[i],\n                responses->t_i_2[i],\n                public_key->A,\n                revealed_values->P_i[i],\n                random_values->f_i[i],\n                private_key->e[i]);\n\n        for (int j = 0; j < J; j++) {\n\n            u_v = random_values->u_i_j[i][j];\n            u_v.append(random_values->v_i_j[i][j]);\n            knowledge_of_valid_opening::generate_commitment_and_response_0(\n                    commitments->c_i_j_0[i][j],\n                    commitments->r_i_j_0[i][j],\n                    responses->t_i_j_0[i][j],\n                    u_v,\n                    public_key->A,\n                    random_values->f_i_j[i][j]);\n\n            knowledge_of_valid_opening::generate_commitment_and_response_1(\n                    commitments->c_i_j_1[i][j],\n                    commitments->r_i_j_1[i][j],\n                    responses->t_i_j_1[i][j],\n                    public_key->A,\n                    revealed_values->P_i_j[i][j],\n                    random_values->f_i_j[i][j]);\n\n            knowledge_of_valid_opening::generate_commitment_and_response_2(\n                    commitments->c_i_j_2[i][j],\n                    commitments->r_i_j_2[i][j],\n                    responses->t_i_j_2[i][j],\n                    public_key->A,\n                    revealed_values->P_i_j[i][j],\n                    random_values->f_i_j[i][j],\n                    revealed_values->e_i_j[i][j]);\n        }\n    }\n}\n\nint hamming_metric::multiplicative_relations::verify_0(\n        const NTL::Vec<NTL::vec_GF2> &c_i_0,\n        const NTL::Vec<NTL::vec_GF2> &r_i_0,\n        const NTL::Vec<NTL::vec_GF2> &t_i_0,\n        const NTL::Vec<NTL::vec_GF2> &c_i_1,\n        const NTL::Vec<NTL::vec_GF2> &r_i_1,\n        const NTL::Vec<NTL::vec_GF2> &t_i_1,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &c_i_j_0,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &r_i_j_0,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &t_i_j_0,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &c_i_j_1,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &r_i_j_1,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &t_i_j_1,\n        const NTL::Vec<NTL::mat_GF2> &P_i,\n        const NTL::Vec<NTL::Vec<NTL::mat_GF2>> &P_i_j,\n        const NTL::Vec<NTL::mat_GF2> &R,\n        const public_key_t *public_key) {\n\n    for (int i = 0; i < I; i++) {\n        auto _t0 = utils::encode_binary_vector(t_i_0[i], JAIN_V);\n        auto _t1 = utils::encode_binary_vector(t_i_1[i], JAIN_V);\n\n        if (hamming_metric::commitment::verify(\n                c_i_0[i],\n                public_key->A,\n                r_i_0[i],\n                _t0) != 0) {\n            std::cout << \"Multiplicative Relations. Verification failed on ch = 0 and c0\" << std::endl;\n            return 1;\n        }\n\n        if (hamming_metric::commitment::verify(\n                c_i_1[i],\n                public_key->A,\n                r_i_1[i],\n                _t1) != 0) {\n            std::cout << \"Multiplicative Relations. Verification failed on ch = 0 and c1\" << std::endl;\n            return 1;\n        }\n        for (int j = 0; j < J; j++) {\n            _t0 = utils::encode_binary_vector(t_i_j_0[i][j], JAIN_V);\n            _t1 = utils::encode_binary_vector(t_i_j_1[i][j], JAIN_V);\n\n            if (hamming_metric::commitment::verify(\n                    c_i_j_0[i][j],\n                    public_key->A,\n                    r_i_j_0[i][j],\n                    _t0) != 0) {\n                std::cout << \"Multiplicative Relations. Verification failed on ch = 0 and c0\" << std::endl;\n                return 1;\n            }\n\n            if (hamming_metric::commitment::verify(\n                    c_i_j_1[i][j],\n                    public_key->A,\n                    r_i_j_1[i][j],\n                    _t1) != 0) {\n                std::cout << \"Multiplicative Relations. Verification failed on ch = 0 and c1\" << std::endl;\n                return 1;\n            }\n        }\n    }\n\n    NTL::Vec<NTL::vec_GF2> results_i;\n    NTL::Vec<NTL::Vec<NTL::vec_GF2>> results_i_j;\n    results_i_j.SetLength(I);\n    for (int i = 0; i < I; i++) {\n        NTL::vec_GF2 result;\n\n        if (utils::solve_equation(\n                result,\n                public_key->A,\n                t_i_0[i] + (NTL::inv(P_i[i]) * t_i_1[i])) != 0) {\n            std::cout << \"No Solutions\" << std::endl;\n            return 1;\n        }\n        results_i.append(result);\n\n        for (int j = 0; j < J; j++) {\n            if (utils::solve_equation(\n                    result,\n                    public_key->A,\n                    t_i_j_0[i][j] + (NTL::inv(P_i_j[i][j]) * t_i_j_1[i][j])) != 0) {\n                std::cout << \"No Solutions\" << std::endl;\n                return 1;\n            }\n            results_i_j[i].append(result);\n        }\n    }\n\n    NTL::Vec<NTL::vec_GF2> b_i;\n    b_i.SetLength(I);\n    for (int i = 0; i < I; i++) {\n        b_i[i].SetLength(JAIN_V);\n        for (int j = 0; j < JAIN_V; j++) {\n            b_i[i][j] = results_i[i][j + JAIN_L];\n        }\n    }\n\n    NTL::Vec<NTL::Vec<NTL::vec_GF2>> b_i_j;\n    b_i_j.SetLength(I);\n    for (int i = 0; i < I; i++) {\n        b_i_j[i].SetLength(J);\n        for (int j = 0; j < J; j++) {\n            b_i_j[i][j].SetLength(JAIN_V);\n            for (int z = 0; z < JAIN_V; z++) {\n                b_i_j[i][j][z] = results_i_j[i][j][z + JAIN_L];\n            }\n        }\n    }\n\n    NTL::Vec<NTL::vec_GF2> r_b;\n    r_b.SetLength(I);\n    for (int i = 0; i < I; i++) {\n        for (int j = 0; j < J; j++) {\n            r_b[i].SetLength(JAIN_V);\n            r_b[i] += (R[j] * b_i_j[i][j]);\n        }\n        if (b_i[i] != r_b[i]) {\n            std::cout << \"Error: verify_0\" << std::endl;\n            return 1;\n        }\n    }\n\n    return 0;\n}\n\nint hamming_metric::multiplicative_relations::verify_1(\n        const NTL::Vec<NTL::vec_GF2> &c_i_0,\n        const NTL::Vec<NTL::vec_GF2> &r_i_0,\n        const NTL::Vec<NTL::vec_GF2> &t_i_0,\n        const NTL::Vec<NTL::vec_GF2> &c_i_2,\n        const NTL::Vec<NTL::vec_GF2> &r_i_2,\n        const NTL::Vec<NTL::vec_GF2> &t_i_2,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &c_i_j_0,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &r_i_j_0,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &t_i_j_0,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &c_i_j_2,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &r_i_j_2,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &t_i_j_2,\n        const NTL::Vec<NTL::mat_GF2> &P_i,\n        const NTL::Vec<NTL::Vec<NTL::mat_GF2>> &P_i_j,\n        const NTL::Vec<NTL::mat_GF2> &R,\n        const NTL::mat_GF2 &_R,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &commitments_i_j,\n        const public_key_t *public_key) {\n\n    for (int i = 0; i < I; i++) {\n        auto _t0 = utils::encode_binary_vector(t_i_0[i], JAIN_V);\n        auto _t2 = utils::encode_binary_vector(t_i_2[i], JAIN_V);\n\n        if (hamming_metric::commitment::verify(\n                c_i_0[i],\n                public_key->A,\n                r_i_0[i],\n                _t0) != 0) {\n            std::cout << \"Multiplicative Relations. Verification failed on ch = 1 and c0\" << std::endl;\n            return 1;\n        }\n\n        if (hamming_metric::commitment::verify(\n                c_i_2[i],\n                public_key->A,\n                r_i_2[i],\n                _t2) != 0) {\n            std::cout << \"Multiplicative Relations. Verification failed on ch = 1 and c2\" << std::endl;\n            return 1;\n        }\n        for (int j = 0; j < J; j++) {\n            _t0 = utils::encode_binary_vector(t_i_j_0[i][j], JAIN_V);\n            _t2 = utils::encode_binary_vector(t_i_j_2[i][j], JAIN_V);\n\n            if (hamming_metric::commitment::verify(\n                    c_i_j_0[i][j],\n                    public_key->A,\n                    r_i_j_0[i][j],\n                    _t0) != 0) {\n                std::cout << \"Multiplicative Relations. Verification failed on ch = 1 and c0\" << std::endl;\n                return 1;\n            }\n\n            if (hamming_metric::commitment::verify(\n                    c_i_j_2[i][j],\n                    public_key->A,\n                    r_i_j_2[i][j],\n                    _t2) != 0) {\n                std::cout << \"Multiplicative Relations. Verification failed on ch = 1 and c2\" << std::endl;\n                return 1;\n            }\n        }\n    }\n\n    // Check rank of matrix\n    auto m = _R;\n    if (NTL::gauss(m) != m.NumRows()) {\n        std::cout << \"Not full rank matrix\" << std::endl;\n        return 1;\n    }\n\n    // Ensure that each row has weight one\n    for (int i = 0; i < m.NumRows(); i++) {\n        if (NTL::weight(m[i]) != 1) {\n            std::cout << \"Invalid weight\" << std::endl;\n            return 1;\n        }\n    }\n\n\n    NTL::Vec<NTL::vec_GF2> results_i;\n    NTL::Vec<NTL::Vec<NTL::vec_GF2>> results_i_j;\n    results_i_j.SetLength(I);\n    for (int i = 0; i < I; i++) {\n        NTL::vec_GF2 result;\n\n        if (utils::solve_equation(\n                result,\n                public_key->A,\n                public_key->commitments_i[i] + t_i_0[i] + (NTL::inv(P_i[i]) * t_i_2[i])) != 0) {\n            std::cout << \"No Solutions 1\" << std::endl;\n            return 1;\n        }\n        results_i.append(result);\n\n        for (int j = 0; j < J; j++) {\n            if (utils::solve_equation(\n                    result,\n                    public_key->A,\n                    commitments_i_j[i][j] + t_i_j_0[i][j] +\n                    (NTL::inv(P_i_j[i][j]) * t_i_j_2[i][j])) != 0) {\n                std::cout << \"No Solutions 2\" << std::endl;\n                return 1;\n            }\n            results_i_j[i].append(result);\n        }\n    }\n\n    NTL::Vec<NTL::vec_GF2> b_i;\n    b_i.SetLength(I);\n    for (int i = 0; i < I; i++) {\n        b_i[i].SetLength(JAIN_V);\n        for (int j = 0; j < JAIN_V; j++) {\n            b_i[i][j] = results_i[i][j + JAIN_L];\n        }\n    }\n\n    NTL::Vec<NTL::Vec<NTL::vec_GF2>> b_i_j;\n    b_i_j.SetLength(I);\n    for (int i = 0; i < I; i++) {\n        b_i_j[i].SetLength(J);\n        for (int j = 0; j < J; j++) {\n            b_i_j[i][j].SetLength(JAIN_V);\n            for (int z = 0; z < JAIN_V; z++) {\n                b_i_j[i][j][z] = results_i_j[i][j][z + JAIN_L];\n            }\n        }\n    }\n\n    NTL::Vec<NTL::vec_GF2> r_b;\n    r_b.SetLength(I);\n    for (int i = 0; i < I; i++) {\n        for (int j = 0; j < J; j++) {\n            r_b[i].SetLength(JAIN_V);\n            r_b[i] += (R[j] * b_i_j[i][j]);\n        }\n        if (b_i[i] != r_b[i]) {\n            std::cout << \"Error: verify_0\" << std::endl;\n            return 1;\n        }\n    }\n\n    return 0;\n}\n\nint hamming_metric::multiplicative_relations::verify_2(\n        const NTL::Vec<NTL::vec_GF2> &c_i_1,\n        const NTL::Vec<NTL::vec_GF2> &r_i_1,\n        const NTL::Vec<NTL::vec_GF2> &t_i_1,\n        const NTL::Vec<NTL::vec_GF2> &c_i_2,\n        const NTL::Vec<NTL::vec_GF2> &r_i_2,\n        const NTL::Vec<NTL::vec_GF2> &t_i_2,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &c_i_j_1,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &r_i_j_1,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &t_i_j_1,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &c_i_j_2,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &r_i_j_2,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &t_i_j_2,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &e_i_j,\n        const NTL::Vec<NTL::Vec<NTL::vec_GF2>> &m_prime_i_j,\n        const public_key_t *public_key) {\n\n    for (int i = 0; i < I; i++) {\n        auto _t1 = utils::encode_binary_vector(t_i_1[i], JAIN_V);\n        auto _t2 = utils::encode_binary_vector(t_i_2[i], JAIN_V);\n\n        if (hamming_metric::commitment::verify(\n                c_i_1[i],\n                public_key->A,\n                r_i_1[i],\n                _t1) != 0) {\n            std::cout << \"Linear Relations. Verification failed on ch = 2 and c1\" << std::endl;\n            return 1;\n        }\n\n        if (hamming_metric::commitment::verify(\n                c_i_2[i],\n                public_key->A,\n                r_i_2[i],\n                _t2) != 0) {\n            std::cout << \"Linear Relations. Verification failed on ch = 2 and c2\" << std::endl;\n            return 1;\n        }\n        for (int j = 0; j < J; j++) {\n            _t1 = utils::encode_binary_vector(t_i_j_1[i][j], JAIN_V);\n            _t2 = utils::encode_binary_vector(t_i_j_2[i][j], JAIN_V);\n\n            if (hamming_metric::commitment::verify(\n                    c_i_j_1[i][j],\n                    public_key->A,\n                    r_i_j_1[i][j],\n                    _t1) != 0) {\n                std::cout << \"Linear Relations. Verification failed on ch = 2 and c1\" << std::endl;\n                return 1;\n            }\n\n            if (hamming_metric::commitment::verify(\n                    c_i_j_2[i][j],\n                    public_key->A,\n                    r_i_j_2[i][j],\n                    _t2) != 0) {\n                std::cout << \"Linear Relations. Verification failed on ch = 2 and c2\" << std::endl;\n                return 1;\n            }\n\n            if (NTL::weight(e_i_j[i][j]) != W) {\n                std::cout << \"Error: Wrong weight\" << std::endl;\n                return 1;\n            }\n\n        }\n    }\n\n    for (int j = 0; j < J; j++) {\n        for (int z = 0; z < m_prime_i_j[0][j].length(); z++) {\n            if (m_prime_i_j[0][j][z] * m_prime_i_j[1][j][z] !=\n                m_prime_i_j[2][j][z]) {\n                std::cout << \"Error: Wrong relations\" << std::endl;\n                return 1;\n            }\n        }\n\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "a855bc5e3d4e415163d4a4240db5e6406ed52471", "size": 22447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hamming/multiplicative_relations/multiplicative_relations.cpp", "max_stars_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_stars_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/hamming/multiplicative_relations/multiplicative_relations.cpp", "max_issues_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_issues_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hamming/multiplicative_relations/multiplicative_relations.cpp", "max_forks_repo_name": "Crypto-TII/2020-CANS-rank_commitments", "max_forks_repo_head_hexsha": "fa42c3c3771cabf3eaeca43cff91b3927554be93", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-16T07:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-16T07:21:24.000Z", "avg_line_length": 32.2978417266, "max_line_length": 107, "alphanum_fraction": 0.5040762685, "num_tokens": 6576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407017, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.41946180192948007}}
{"text": "/* \n * Copyright 2009-2015 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <votca/tools/linalg.h>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include \"mkl.h\"\n#include \"mkl_lapacke.h\"\n\n\nnamespace votca { namespace tools {\n\nusing namespace std;\n\n\n/* Wrapper for DSYEV\n *  - make copy of input matrix\n */\n\n\nbool linalg_eigenvalues( ub::matrix<double> &A, ub::vector<double> &E, ub::matrix<double> &V)\n{\n    // cout << \" \\n I'm really using MKL! \" << endl;\n    \n    int n = A.size1();\n    int lda = n ;\n    // make sure that containers for eigenvalues and eigenvectors are of correct size\n    E.resize(n);\n    V.resize(n, n);\n    // Query and allocate the optimal workspace \n    double wkopt;\n    double* work;\n    int info;\n    int lwork;\n    lwork = -1;\n\n    // MKL is different to GSL because it overwrites the input matrix\n    V = A; // make a copy (might actually be unnecessary in most cases!)\n\n    // make a pointer to the ublas matrix so that LAPACK understands it\n    double * pV = const_cast<double*>(&V.data().begin()[0]);\n    double * pE = const_cast<double*>(&E.data()[0]);\n    \n    // call LAPACK via C interface\n    info = LAPACKE_dsyev( LAPACK_ROW_MAJOR, 'V', 'U', n, pV , lda, pE );\n\n    if( info > 0 ) {\n        return false;\n    } else {\n        return true;\n    }\n};\n\n\n\n\nbool linalg_eigenvalues_symmetric( ub::symmetric_matrix<double> &A, ub::vector<double> &E, ub::matrix<double> &V)\n{\n    // cout << \" \\n I'm really using MKL! \" << endl;\n    \n    int n = A.size1();\n    int lda = n ;\n    // make sure that containers for eigenvalues and eigenvectors are of correct size\n    E.resize(n);\n    V.resize(n, n);\n    // Query and allocate the optimal workspace \n    double wkopt;\n    double* work;\n    int info;\n    int lwork;\n    lwork = -1;\n\n    // MKL does not handle conversion of a symmetric_matrix \n    V = A;\n    \n    // make a pointer to the ublas matrix so that LAPACK understands it\n    double * pV = const_cast<double*>(&V.data().begin()[0]);\n    double * pE = const_cast<double*>(&E.data()[0]);\n    \n    // call LAPACK via C interface\n    info = LAPACKE_dsyev( LAPACK_ROW_MAJOR, 'V', 'U', n, pV , lda, pE );\n\n    if( info > 0 ) {\n        return false;\n    } else {\n        return true;\n    }\n};\n\n\nbool linalg_eigenvalues(  ub::vector<double> &E, ub::matrix<double> &V)\n{\n    // cout << \" \\n I'm really using MKL! \" << endl;\n    \n    int n = V.size1();\n    int lda = n ;\n    // make sure that containers for eigenvalues and eigenvectors are of correct size\n    E.resize(n);\n    // V.resize(n, n);\n    // Query and allocate the optimal workspace \n    double wkopt;\n    double* work;\n    int info;\n    int lwork;\n    lwork = -1;\n\n    // MKL is different to GSL because it overwrites the input matrix\n    // V = A; // make a copy (might actually be unnecessary in most cases!)\n\n    // make a pointer to the ublas matrix so that LAPACK understands it\n    double * pV = const_cast<double*>(&V.data().begin()[0]);\n    double * pE = const_cast<double*>(&E.data()[0]);\n    \n    // call LAPACK via C interface\n    info = LAPACKE_dsyev( LAPACK_ROW_MAJOR, 'V', 'U', n, pV , lda, pE );\n\n    if( info > 0 ) {\n        return false;\n    } else {\n        return true;\n    }\n};\n\n\n\nbool linalg_eigenvalues(  ub::vector<float> &E, ub::matrix<float> &V)\n{\n    // cout << \" \\n I'm really using MKL! \" << endl;\n    \n    int n = V.size1();\n    int lda = n ;\n    // make sure that containers for eigenvalues and eigenvectors are of correct size\n    E.resize(n);\n    // V.resize(n, n);\n    // Query and allocate the optimal workspace \n    float wkopt;\n    float* work;\n    int info;\n    int lwork;\n    lwork = -1;\n\n    // MKL is different to GSL because it overwrites the input matrix\n    // V = A; // make a copy (might actually be unnecessary in most cases!)\n\n    // make a pointer to the ublas matrix so that LAPACK understands it\n    float * pV = const_cast<float*>(&V.data().begin()[0]);\n    float * pE = const_cast<float*>(&E.data()[0]);\n    \n    // call LAPACK via C interface\n    info = LAPACKE_ssyev( LAPACK_ROW_MAJOR, 'V', 'U', n, pV , lda, pE );\n\n    if( info > 0 ) {\n        return false;\n    } else {\n        return true;\n    }\n};\n\n\n\n\n/*\n * use expert routine to calculate only a subrange of eigenvalues\n */\nbool linalg_eigenvalues( ub::matrix<double> &A, ub::vector<double> &E, ub::matrix<double> &V , int nmax)\n{\n    /*\n     * INPUT:  matrix A (N,N)\n     * OUTPUT: matrix V (N,NMAX)\n     *         vector E (NMAX)\n     */\n    double wkopt;\n    double* work;\n    double abstol, vl, vu;\n     \n    MKL_INT lda;\n    MKL_INT info;\n    MKL_INT lwork;\n    MKL_INT il, iu, m, ldz ;\n    \n    int n = A.size1();\n    MKL_INT ifail[n];\n    lda = n;\n    ldz = nmax;\n    \n    \n    \n    // make sure that containers for eigenvalues and eigenvectors are of correct size\n    E.resize(nmax);\n    V.resize(n,nmax);\n\n    \n    lwork = -1;\n    il = 1;\n    iu = nmax;\n    abstol = 0.0; // use default\n    vl = 0.0;\n    vu = 0.0;\n    // make a pointer to the ublas matrix so that LAPACK understands it\n    double * pA = const_cast<double*>(&A.data().begin()[0]);   \n    double * pV = const_cast<double*>(&V.data().begin()[0]);\n    double * pE = const_cast<double*>(&E.data()[0]);\n    \n    // call LAPACK via C interface\n    info = LAPACKE_dsyevx( LAPACK_ROW_MAJOR, 'V', 'I', 'U', n, pA , lda, vl, vu, il, iu, abstol, &m, pE, pV, nmax,  ifail );\n\n    if( info > 0 ) {\n        return false;\n    } else {\n        return true;\n    }\n};\n\n\n\n/*\n * use expert routine to calculate only a subrange of eigenvalues\n */\nbool linalg_eigenvalues( ub::matrix<float> &A, ub::vector<float> &E, ub::matrix<float> &V , int nmax)\n{\n    /*\n     * INPUT:  matrix A (N,N)\n     * OUTPUT: matrix V (N,NMAX)\n     *         vector E (NMAX)\n     */\n    float wkopt;\n    float* work;\n    float abstol, vl, vu;\n     \n    MKL_INT lda;\n    MKL_INT info;\n    MKL_INT lwork;\n    MKL_INT il, iu, m, ldz ;\n    \n    int n = A.size1();\n    MKL_INT ifail[n];\n    lda = n;\n    ldz = nmax;\n    \n    \n    \n    // make sure that containers for eigenvalues and eigenvectors are of correct size\n    E.resize(nmax);\n    V.resize(n,nmax);\n\n    \n    lwork = -1;\n    il = 1;\n    iu = nmax;\n    abstol = 0.0; // use default\n    vl = 0.0;\n    vu = 0.0;\n    // make a pointer to the ublas matrix so that LAPACK understands it\n    float * pA = const_cast<float*>(&A.data().begin()[0]);   \n    float * pV = const_cast<float*>(&V.data().begin()[0]);\n    float * pE = const_cast<float*>(&E.data()[0]);\n    \n    // call LAPACK via C interface\n    info = LAPACKE_ssyevx( LAPACK_ROW_MAJOR, 'V', 'I', 'U', n, pA , lda, vl, vu, il, iu, abstol, &m, pE, pV, nmax,  ifail );\n\n    if( info > 0 ) {\n        return false;\n    } else {\n        return true;\n    }\n};\n\n\n\n/* calculate the eigenvalues and vectors of the generalized eigenvalue problem */\nbool linalg_eigenvalues_general( ub::matrix<double> &A,ub::matrix<double> &B, ub::vector<double> &E, ub::matrix<double> &V)\n{\n    // cout << \" \\n I'm really using MKL! \" << endl;\n    //check to see if matrices have same size\n    int n = A.size1();\n    int lda = n ;\n    int ldb =B.size1();\n    ub::matrix<double> _B(ldb,ldb);\n    _B=B;\n    if (lda!=ldb){\n        cout << \"Matrices A and B have not the same size\"<< endl;\n        exit(1);\n    }\n    // make sure that containers for eigenvalues and eigenvectors are of correct size\n    E.resize(n);\n    V.resize(n, n);\n    // Query and allocate the optimal workspace \n    double wkopt;\n    double* work;\n    int info;\n    int lwork;\n    lwork = -1;\n\n    // MKL is different to GSL because it overwrites the input matrix\n    V = A; // make a copy (might actually be unnecessary in most cases!)\n\n    // make a pointer to the ublas matrix so that LAPACK understands it \n    double * pB = const_cast<double*>(&_B.data().begin()[0]);  \n    double * pV = const_cast<double*>(&V.data().begin()[0]);\n    double * pE = const_cast<double*>(&E.data()[0]);\n    \n    // call LAPACK via C interface\n    info = LAPACKE_dsygv( LAPACK_ROW_MAJOR,1,'V', 'U', n, pV , lda,pB,ldb, pE );\n\n    if( info > 0 ) {\n        return false;\n    } else {\n        return true;\n    }\n};\n\n\n}}\n", "meta": {"hexsha": "ae13ee81844c5138622a123d1d4fda1a6a501515", "size": 8661, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/linalg/mkl/eigensystems.cc", "max_stars_repo_name": "vaidyanathanms/votca.tools", "max_stars_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libtools/linalg/mkl/eigensystems.cc", "max_issues_repo_name": "vaidyanathanms/votca.tools", "max_issues_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libtools/linalg/mkl/eigensystems.cc", "max_forks_repo_name": "vaidyanathanms/votca.tools", "max_forks_repo_head_hexsha": "62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4054878049, "max_line_length": 124, "alphanum_fraction": 0.5936958781, "num_tokens": 2522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.41946180192948}}
{"text": "#pragma once\n\n#include <cmath>\n#include <boost/optional.hpp>\n#include <boost/functional/hash.hpp>\n#include <QtCore/QPointF>\n#include <protobuf/Point.pb.h>\n#include <sstream>\n#include <string>\n\nnamespace Geometry2d {\n/**\nSimple class to represent a point in 2d space. Uses floating point coordinates\n*/\nclass Point {\npublic:\n    const double& x() const { return _x; }\n    const double& y() const { return _y; }\n    double& x() { return _x; }\n    double& y() { return _y; }\n\n    /**\n    sets the point to x,y\n    @param x the x coordinate\n    @param y the y coordinate\n    */\n    Point(double x = 0, double y = 0) : _x(x), _y(y) {}\n\n    /**\n     * Implicit constructor for creating a Point from a Packet::Point\n     */\n    Point(const Packet::Point& other) : Point(other.x(), other.y()) {}\n\n    /**\n     * Implicit constructor for creating a Point from a QPointF\n     */\n    Point(const QPointF& other) : Point(other.x(), other.y()) {}\n\n    /**\n     * Implicit constructor for creating a Point from a QPoint\n     */\n    Point(const QPoint& other) : Point(other.x(), other.y()) {}\n\n    /**\n     * Implicit constructor for creating a Point from a double*\n     */\n    Point(const double* other) : Point(other[0], other[1]) {}\n\n    /**\n     * to draw stuff and interface with QT\n     */\n    QPointF toQPointF() const { return QPointF(x(), y()); }\n\n    operator Packet::Point() const {\n        Packet::Point out;\n        out.set_x(x());\n        out.set_y(y());\n        return out;\n    }\n    /**\n     * does vector addition\n     * adds the + operator, shorthand\n     */\n    Point operator+(Point other) const {\n        return Point(x() + other.x(), y() + other.y());\n    }\n\n    /**\n     * see operator+\n     * does vector division, note the operator\n     */\n    Point operator/(Point other) const {\n        return Point(x() / other.x(), y() / other.y());\n    }\n\n    /**\n     * @returns (x*x,y*y)\n     */\n    Point operator*(Point other) const {\n        return Point(x() * other.x(), y() * other.y());\n    }\n\n    /**\n     * see operator+\n     * does vector subtraction, note the operator\n     * without parameter, it is the negative\n     */\n    Point operator-(Point other) const {\n        return Point(x() - other.x(), y() - other.y());\n    }\n\n    /**\n     * multiplies the point by a -1 vector\n     */\n    Point operator-() const { return Point(-x(), -y()); }\n\n    /**\n     * see operator+\n     * this modifies the value instead of returning a new value\n     */\n    Point& operator+=(Point other) {\n        x() += other.x();\n        y() += other.y();\n\n        return *this;\n    }\n\n    /**\n     * see operator-\n     * this modifies the value instead of returning a new value\n     */\n    Point& operator-=(Point other) {\n        x() -= other.x();\n        y() -= other.y();\n\n        return *this;\n    }\n\n    /**\n     * see operator*\n     * this modifies the value instead of returning a new value\n     */\n    Point& operator*=(double s) {\n        x() *= s;\n        y() *= s;\n\n        return *this;\n    }\n\n    /**\n     * see operator/\n     * this modifies the value instead of returning a new value\n     */\n    Point& operator/=(double s) {\n        x() /= s;\n        y() /= s;\n\n        return *this;\n    }\n\n    /**\n     * adds the / operator for vectors\n     *  scalar division\n     */\n    Point operator/(double s) const { return Point(x() / s, y() / s); }\n    /**\n     * adds the * operator for vectors\n     * scalar multiplication\n     */\n    Point operator*(double s) const { return Point(x() * s, y() * s); }\n\n    /**\n     * compares two points to see if both x and y are the same\n     * adds the == operator\n     */\n    bool operator==(Point other) const {\n        return x() == other.x() && y() == other.y();\n    }\n\n    /**\n     * this is the negation of operator operator !=\n     */\n    bool operator!=(Point other) const {\n        return x() != other.x() || y() != other.y();\n    }\n\n    const double& operator[](int i) const {\n        if (0 == i) {\n            return _x;\n        } else if (1 == i) {\n            return _y;\n        } else {\n            throw std::out_of_range(\"Out of range index for Geometry2d::Point\");\n        }\n    }\n\n    double& operator[](int i) {\n        return const_cast<double&>((static_cast<const Point*>(this))->operator[](i));\n    }\n\n    /**\n     * Hash function for Geometry2d::Point\n     */\n    static size_t hash(Point pt) {\n        size_t seed = 0;\n        boost::hash_combine(seed, pt.x());\n        boost::hash_combine(seed, pt.y());\n        return seed;\n    }\n\n\n    /**\n    computes the dot product of this point and another.\n    behaves as if the points were 2d vectors\n    @param p the second point\n    @return the dot product of the two\n    */\n    double dot(Point p) const { return x() * p.x() + y() * p.y(); }\n\n    /**\n    computes the magnitude of the point, as if it were a vector\n    @return the magnitude of the point\n    */\n    double mag() const { return sqrtf(x() * x() + y() * y()); }\n\n    /**\n    computes magnitude squared\n    this is faster than mag()\n    @return the magnitude squared\n    */\n    double magsq() const { return x() * x() + y() * y(); }\n\n    /**\n     * @brief Restricts the point to a given magnitude\n     * @param max The magnitude to restrict the vector\n     */\n    Point& clamp(double max) {\n        double ratio = mag() / max;\n        if (ratio > 1) {\n            x() /= ratio;\n            y() /= ratio;\n        }\n        return *this;\n    }\n\n    /**\n    rotates the point around another point by specified angle in the CCW\n    direction\n    @param origin the point to rotate around\n    @param angle the angle in radians\n    */\n    Point& rotate(const Point& origin, double angle) {\n        *this -= origin;\n        rotate(angle);\n        *this += origin;\n        return *this;\n    }\n\n    /**\n    * rotates the point around the origin\n    */\n    Point& rotate(double angle) {\n        double newX = x() * cos(angle) - y() * sin(angle);\n        double newY = y() * cos(angle) + x() * sin(angle);\n        x() = newX;\n        y() = newY;\n        return *this;\n    }\n\n    /**\n     * Like rotate(), but returns a new point instead of changing *this\n     */\n    Point rotated(double angle) const {\n        double newX = x() * cos(angle) - y() * sin(angle);\n        double newY = y() * cos(angle) + x() * sin(angle);\n        return Point(newX, newY);\n    }\n\n    /**\n     * Returns a new Point rotated around the origin\n     */\n    Point rotated(const Point& origin, double angle) const {\n        return rotated(*this, origin, angle);\n    }\n\n    /**\n    * static function to use rotate\n    */\n    static Point rotated(const Point& pt, const Point& origin, double angle) {\n        Point newPt = pt;\n        newPt.rotate(origin, angle);\n        return newPt;\n    }\n\n    /**\n    computes the distance from the current point to another\n    @param other the point to find the distance to\n    @return the distance between the points\n    */\n    double distTo(const Point& other) const {\n        Point delta = other - *this;\n        return delta.mag();\n    }\n\n    /**\n    * Returns a vector with the same direction as this vector but with magnitude\n    * given,\n    * unless this vector is zero.\n    * If the vector is (0,0), Point(0,0) is returned\n    */\n    Point normalized(double magnitude = 1.0) const {\n        double m = mag();\n        if (m == 0) {\n            return Point(0, 0);\n        }\n\n        return Point(magnitude * x() / m, magnitude * y() / m);\n    }\n\n    /// Alias for normalized() - matches Eigen's syntax\n    Point norm() const { return normalized(); }\n\n    /**\n    * Returns true if this point is within the given distance (threshold) of\n    * (pt)\n    */\n    bool nearPoint(const Point& other, double threshold) const {\n        return (*this - other).magsq() <= (threshold * threshold);\n    }\n\n    /**\n    * Returns the angle of this point in radians CCW from +X.\n    */\n    double angle() const { return atan2(y(), x()); }\n\n    /**\n    * Returns a unit vector in the given direction (in radians)\n    */\n    static Point direction(double theta) {\n        return Point(cos(theta), sin(theta));\n    }\n\n    /** returns the perpendicular to the point, Clockwise */\n    Point perpCW() const { return Point(y(), -x()); }\n\n    /** returns the perpendicular to the point, Counter Clockwise */\n    Point perpCCW() const { return Point(-y(), x()); }\n\n    /** saturates the magnitude of a vector */\n    static Geometry2d::Point saturate(Geometry2d::Point value, double max) {\n        double mag = value.mag();\n        if (mag > fabs(max)) {\n            return value.normalized() * fabs(max);\n        }\n        return value;\n    }\n\n    double angleTo(const Point& other) const { return (other - *this).angle(); }\n\n    double cross(const Point& other) const {\n        return x() * other.y() - y() * other.x();\n    }\n\n    /** returns the angle between the two normalized points (radians) */\n    double angleBetween(const Point& other) const {\n        return acos(normalized().dot(other.normalized()));\n    }\n\n    bool nearlyEquals(Point other) const;\n\n    std::string toString() const {\n        std::stringstream str;\n        str << \"Point(\" << x() << \", \" << y() << \")\";\n        return str.str();\n    }\n\n    friend std::ostream& operator<<(std::ostream& stream, const Point& point) {\n        stream << point.toString();\n        return stream;\n    }\n\nprivate:\n    double _x, _y;\n};  // \\class Point\n\n// global operations\n\n/**\n * adds the * operator for vectors\n * scalar multiplication\n */\ninline Point operator*(const double& s, const Point& pt) {\n    return Point(pt.x() * s, pt.y() * s);\n}\n}\n", "meta": {"hexsha": "04d4a6200ec21129b6b1153bd962593d5a7b3d2d", "size": 9557, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "common/Geometry2d/Point.hpp", "max_stars_repo_name": "rfccambridge/robocup-software-2017", "max_stars_repo_head_hexsha": "c35cf6455597c1d4eb3b4afd0694fb9f5f6a3c0a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "common/Geometry2d/Point.hpp", "max_issues_repo_name": "rfccambridge/robocup-software-2017", "max_issues_repo_head_hexsha": "c35cf6455597c1d4eb3b4afd0694fb9f5f6a3c0a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common/Geometry2d/Point.hpp", "max_forks_repo_name": "rfccambridge/robocup-software-2017", "max_forks_repo_head_hexsha": "c35cf6455597c1d4eb3b4afd0694fb9f5f6a3c0a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4175531915, "max_line_length": 85, "alphanum_fraction": 0.5505911897, "num_tokens": 2353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.5888891307678321, "lm_q1q2_score": 0.41942579188134793}}
{"text": "#include \"ros/ros.h\"  \n// 话题同步处理\n#include \"message_filters/subscriber.h\"\n#include \"message_filters/synchronizer.h\"\n#include \"message_filters/sync_policies/approximate_time.h\"\n// opencv接口\n#include \"cv_bridge/cv_bridge.h\"\n#include \"image_transport/image_transport.h\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include \"opencv2/core/core.hpp\"\n#include \"opencv2/features2d/features2d.hpp\"\n#include <opencv2/calib3d/calib3d.hpp>\n//ros消息类型头文件\n#include \"sensor_msgs/Image.h\"\n#include \"sensor_msgs/image_encodings.h\"\n//系统指令头文件\n#include <boost/thread/thread.hpp>\n#include <boost/foreach.hpp>\n// pcl点云库\n#include <pcl/io/pcd_io.h>\n#include \"pcl_ros/point_cloud.h\"\n#include <pcl_conversions/pcl_conversions.h>\n#include <pcl/point_types.h>\n#include <pcl/PCLPointCloud2.h>\n#include <pcl/conversions.h>\n#include <pcl_ros/transforms.h>\n//内部时钟\n#include <chrono>\n#include \"sensor_msgs/Imu.h\"\n#include \"eigen3/Eigen/Core\"\n#include <sophus/se3.hpp>\n#include <iostream>\n//g2o\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/core/optimization_algorithm_levenberg.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n\nusing namespace std;\nusing namespace cv;\n\nsensor_msgs::Image image_;\ncv::Mat cvColorImgMat;\ncv::Mat cvColorImgMat2;\npcl::PCLPointCloud2 pcl_pc2;\npcl::PCLPointCloud2 pcl_pc2l;\nuint8_t flag=0;\nlong int cnt = 0;\ntypedef std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\ntypedef std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VecVector3d;\n\n/// vertex and edges used in g2o ba\nclass VertexPose : public g2o::BaseVertex<6, Sophus::SE3d> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  virtual void setToOriginImpl() override {\n    _estimate = Sophus::SE3d();\n  }\n\n  /// left multiplication on SE3\n  virtual void oplusImpl(const double *update) override {\n    Eigen::Matrix<double, 6, 1> update_eigen;\n    update_eigen << update[0], update[1], update[2], update[3], update[4], update[5];\n    _estimate = Sophus::SE3d::exp(update_eigen) * _estimate;\n  }\n\n  virtual bool read(istream &in) override {}\n\n  virtual bool write(ostream &out) const override {}\n};\n/// g2o edge\nclass EdgeProjectXYZRGBDPoseOnly : public g2o::BaseUnaryEdge<3, Eigen::Vector3d, VertexPose> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  EdgeProjectXYZRGBDPoseOnly(const Eigen::Vector3d &point) : _point(point) {}\n\n  virtual void computeError() override {\n    const VertexPose *pose = static_cast<const VertexPose *> ( _vertices[0] );\n    _error = _measurement - pose->estimate() * _point;\n  }\n\n  virtual void linearizeOplus() override {\n    VertexPose *pose = static_cast<VertexPose *>(_vertices[0]);\n    Sophus::SE3d T = pose->estimate();\n    Eigen::Vector3d xyz_trans = T * _point;\n    _jacobianOplusXi.block<3, 3>(0, 0) = -Eigen::Matrix3d::Identity();\n    _jacobianOplusXi.block<3, 3>(0, 3) = Sophus::SO3d::hat(xyz_trans);\n  }\n\n  bool read(istream &in) {}\n\n  bool write(ostream &out) const {}\n\nprotected:\n  Eigen::Vector3d _point;\n};\nvoid pose_estimation_3d3d(const vector<Point3f> &pts1,\n                          const vector<Point3f> &pts2,\n                          Mat &R, Mat &t) {\n  Point3f p1, p2;     // center of mass\n  int N = pts1.size();\n  for (int i = 0; i < N; i++) {\n    p1 += pts1[i];\n    p2 += pts2[i];\n  }\n  p1 = Point3f(Vec3f(p1) / N);\n  p2 = Point3f(Vec3f(p2) / N);\n  vector<Point3f> q1(N), q2(N); // remove the center\n  for (int i = 0; i < N; i++) {\n    q1[i] = pts1[i] - p1;\n    q2[i] = pts2[i] - p2;\n  }\n\n  // compute q1*q2^T\n  Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n  for (int i = 0; i < N; i++) {\n    W += Eigen::Vector3d(q1[i].x, q1[i].y, q1[i].z) * Eigen::Vector3d(q2[i].x, q2[i].y, q2[i].z).transpose();\n  }\n  cout << \"W=\" << W << endl;\n\n  // SVD on W\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd(W, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Eigen::Matrix3d U = svd.matrixU();\n  Eigen::Matrix3d V = svd.matrixV();\n\n  cout << \"U=\" << U << endl;\n  cout << \"V=\" << V << endl;\n\n  Eigen::Matrix3d R_ = U * (V.transpose());\n  if (R_.determinant() < 0) {\n    R_ = -R_;\n  }\n  Eigen::Vector3d t_ = Eigen::Vector3d(p1.x, p1.y, p1.z) - R_ * Eigen::Vector3d(p2.x, p2.y, p2.z);\n\n  // convert to cv::Mat\n  R = (Mat_<double>(3, 3) <<\n    R_(0, 0), R_(0, 1), R_(0, 2),\n    R_(1, 0), R_(1, 1), R_(1, 2),\n    R_(2, 0), R_(2, 1), R_(2, 2)\n  );\n  t = (Mat_<double>(3, 1) << t_(0, 0), t_(1, 0), t_(2, 0));\n}\n\nvoid bundleAdjustmentGaussNewton(const VecVector3d &points_3d,const VecVector2d &points_2d,const cv::Mat &K,Sophus::SE3d &pose) {\n    typedef Eigen::Matrix<double,6,1> Vector6d;\n    const int iterations = 10;\n    double cost = 0,lastCost = 0;\n    double fx = K.at<double>(0,0);\n    double fy = K.at<double>(1,1);\n    double cx = K.at<double>(0,2);\n    double cy = K.at<double>(1,2);\n    for(int iter = 0;iter < iterations; iter++){\n        Eigen::Matrix<double,6,6> H = Eigen::Matrix<double,6,6>::Zero();\n        Vector6d b = Vector6d::Zero();\n        cost = 0;\n        //compute cost\n        for(int i = 0;i < points_3d.size(); i++){\n            Eigen::Vector3d pc = pose * points_3d[i];\n            double inv_z = 1.0 / pc[2];\n            double inv_z2 = inv_z * inv_z;\n            Eigen::Vector2d proj(fx * pc[0] / pc[2] + cx,fy * pc[1] / pc[2] + cy);\n            Eigen::Vector2d e = points_2d[i] - proj;\n            cost+=e.squaredNorm();\n\n            Eigen::Matrix<double,2,6> J;\n            J << -fx * inv_z,\n            0,\n            fx * pc[0] * inv_z2,\n            fx * pc[0] * pc[1] * inv_z2,\n            -fx - fx * pc[0] * pc[0] * inv_z2,\n            fx * pc[1] * inv_z,\n            0,\n            -fy * inv_z,\n            fy * pc[1] * inv_z2,\n            fy + fy * pc[1] * pc[1] * inv_z2,\n            -fy * pc[0] * pc[1] * inv_z2,\n            -fy * pc[0] * inv_z;\n\n            H += J.transpose() * J;\n            b += -J.transpose() * e;\n        }\n        Vector6d dx;\n        dx = H.ldlt().solve(b);\n        if(isnan(dx[0])){\n            std::cout << \"result is nan!\" << std::endl;\n            break;\n        }\n        \n        if(iter > 0 && cost >= lastCost){\n            // cost increase, update is not good\n            std::cout << \"cost: \" << cost << \", last cost: \" << lastCost << std::endl;\n            break;\n        }\n\n        //update estimation\n        pose = Sophus::SE3d::exp(dx) * pose;\n        lastCost = cost;\n        std::cout << \"iteration \" << iter << \" cost=\" << std::setprecision(12) << cost << std::endl;\n        if(dx.norm() < 1e-6){\n            break;\n        }\n    }\n    std::cout << \"pose by g-n \\n\" << pose.matrix() <<std::endl;\n}\n\n\n\nvoid callback(const sensor_msgs::ImuConstPtr& imu,const sensor_msgs::PointCloud2ConstPtr& point){\n    std::cout <<\"this is quternion\"   << imu-> orientation.x << std::endl;\n    cv_bridge::CvImagePtr cvImagePtr;\n    pcl_conversions::toPCL(*point,pcl_pc2);\n    pcl::PointCloud<pcl::PointXYZ>::Ptr temp_cloud(new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::PointCloud<pcl::PointXYZ>::Ptr temp_cloud_last(new pcl::PointCloud<pcl::PointXYZ>);\n    pcl::fromPCLPointCloud2(pcl_pc2,*temp_cloud);\n    ROS_INFO(\"Cloud:width = %d,height = %d\",point->width,point->height);\n    try{\n        pcl::toROSMsg(*point,image_);\n    }catch(std::runtime_error e){\n        ROS_ERROR_STREAM(\"Error in converting cloud to image message: \" << e.what());\n    }\n    try{\n        cvImagePtr = cv_bridge::toCvCopy(image_,sensor_msgs::image_encodings::BGR8);\n    }catch(cv_bridge::Exception e){\n        ROS_ERROR_STREAM(\"Cv_bridge Exception:\" << e.what());\n        return;\n    }    \n    cvColorImgMat = cvImagePtr->image;\n\n    if(flag==0){//如果是第一次进入，则和第一帧解算相同\n        // pcl::PointCloud<pcl::PointXYZ>::Ptr temp_cloud_last(new pcl::PointCloud<pcl::PointXYZ>);\n        pcl::fromPCLPointCloud2(pcl_pc2,*temp_cloud_last);\n        cvColorImgMat2 = cvImagePtr->image;\n        flag =2;\n    }else{\n        // pcl::PointCloud<pcl::PointXYZ>::Ptr temp_cloud_last(new pcl::PointCloud<pcl::PointXYZ>);\n        pcl::fromPCLPointCloud2(pcl_pc2l,*temp_cloud_last);            \n    }\n\n    std::vector<cv::KeyPoint> keypoints,keypoints2;\n    cv::Mat descriptors,descriptors2;\n    cv::Ptr<cv::FeatureDetector> detector = cv::ORB::create();\n    cv::Ptr<cv::DescriptorExtractor> descriptor = cv::ORB::create();\n    cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n    std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();\n    detector->detect(cvColorImgMat,keypoints);\n    detector->detect(cvColorImgMat2,keypoints2);\n    descriptor->compute(cvColorImgMat,keypoints,descriptors);\n    descriptor->compute(cvColorImgMat2,keypoints2,descriptors2);\n    std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();\n    std::chrono::duration<double> time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);\n    ROS_INFO(\"extract ORB cost = %f seconds\",time_used.count());\n    \n    // cvColorImgMat2 = cvColorImgMat;\n    // cv::Mat outimg,outimg2;\n    // cv::drawKeypoints(cvColorImgMat,keypoints,outimg,cv::Scalar::all(-1),cv::DrawMatchesFlags::DEFAULT);\n    // cv::drawKeypoints(cvColorImgMat2,keypoints2,outimg2,cv::Scalar::all(-1),cv::DrawMatchesFlags::DEFAULT);\n    // cv::imshow(\"colorview\",outimg2);\n    // cv::imshow(\"ORB feature\",outimg);\n    \n    //match\n    std::vector<cv::DMatch> matches;\n    t1 = std::chrono::steady_clock::now();\n    try\n    {\n        matcher->match(descriptors,descriptors2,matches);\n    }\n    catch(const cv::Exception& e)\n    {\n        ROS_INFO(e.what());\n    }\n    \n\n    t2 = std::chrono::steady_clock::now();\n    time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);\n    ROS_INFO(\"match ORB cost %f seconds\",time_used.count());\n\n    //choise better match\n    auto min_max = std::minmax_element(matches.begin(),matches.end(),\n        [](const cv::DMatch &m1,const cv::DMatch &m2){return m1.distance < m2.distance;});\n    double min_dist = min_max.first->distance;\n    double max_dist = min_max.second->distance;\n    std::vector<cv::DMatch> good_matches;\n    for (int i = 0; i < descriptors.rows; i++){\n        if(matches[i].distance <= std::max(2 * min_dist,30.0))\n            good_matches.push_back(matches[i]);\n    }\n\n    //获取3D点\n    cv::Point3f d;\n    std::vector<cv::Point3f> pts_3d,pts_3d_last;\n    std::vector<cv::Point2f> pts_2d,pts_2d_last;\n    BOOST_FOREACH(cv::DMatch m,good_matches){\n        d.x = temp_cloud_last->points[int(keypoints2[m.queryIdx].pt.y)*640 + int(keypoints2[m.queryIdx].pt.x)].x;\n        d.y = temp_cloud_last->points[int(keypoints2[m.queryIdx].pt.y)*640 + int(keypoints2[m.queryIdx].pt.x)].y;\n        d.z = temp_cloud_last->points[int(keypoints2[m.queryIdx].pt.y)*640 + int(keypoints2[m.queryIdx].pt.x)].z;\n        if(isnan(d.x)||isnan(d.y)||isnan(d.z))\n            continue;\n        pts_3d.push_back(d);\n        pts_2d.push_back(keypoints[m.queryIdx].pt);\n        // ROS_INFO(\"%f %f %f\",d.x,d.y,d.z);\n        // ROS_INFO(\"%d %d\",int(keypoints[m.queryIdx].pt.x),int(keypoints[m.queryIdx].pt.y));\n    }\n    std::cout << \"3d-2s pairs: \" << pts_3d.size() << std::endl;\n    cv::Mat K = (cv::Mat_<double>(3, 3) << 525.0, 0, 319.5, 0, 525.0, 239.5, 0, 0, 1);\n    \n    //Opencv 解位姿\n    // t1 = std::chrono::steady_clock::now();\n    // cv::Mat r, t;\n    // cv::solvePnP(pts_3d, pts_2d, K, cv::Mat(), r, t,false,CV_ITERATIVE); // 调用OpenCV 的 PnP 求解，可选择EPNP，DLS等方法\n    // cv::Mat R;\n    // cv::Rodrigues(r, R); // r为旋转向量形式，用Rodrigues公式转换为矩阵\n    // t2 = std::chrono::steady_clock::now();\n    // time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);\n    // std::cout << \"solve pnp in opencv cost time: \" << time_used.count() << \" seconds.\" << std::endl;\n\n    // std::cout << \"R=\" << std::endl << R << std::endl;\n    // std::cout << \"t=\" << std::endl << t << std::endl;\n\n    //gaussNewton 解位姿\n    VecVector3d pts_3d_eigen;\n    VecVector2d pts_2d_eigen;\n    for (size_t i = 0; i < pts_3d.size(); ++i) {\n        pts_3d_eigen.push_back(Eigen::Vector3d(pts_3d[i].x, pts_3d[i].y, pts_3d[i].z));\n        pts_2d_eigen.push_back(Eigen::Vector2d(pts_2d[i].x, pts_2d[i].y));\n    }\n    std::cout << \"calling bundle adjustment by gauss newton \" << std::endl;\n    Sophus::SE3d pose_gn;\n    t1 = std::chrono::steady_clock::now();\n    bundleAdjustmentGaussNewton(pts_3d_eigen,pts_2d_eigen,K,pose_gn);\n    t2 = std::chrono::steady_clock::now();\n    time_used = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);\n    std::cout << \"solve pnp by gauss newton cost time: \" << time_used.count() << \" seconds.\" << std::endl;\n        \n    //保存上一帧的数据\n    pcl_pc2l = pcl_pc2;\n    cvColorImgMat2 = cvColorImgMat;\n\n    //draw the answer\n    cv::Mat img_match;\n    cv::Mat img_goodmatch;\n    cv::drawMatches(cvColorImgMat,keypoints,cvColorImgMat2,keypoints2,good_matches,img_goodmatch);\n    cv::imshow(\"good matches\",img_goodmatch);\n    // cv::imshow(\"grayview\",cvGrayImgMat);\n    cv::waitKey(5);\n}\nint main(int argc, char *argv[])\n{\n    ros::init(argc,argv,\"grayView\");\n    ros::NodeHandle nh_;\n    message_filters::Subscriber<sensor_msgs::Imu> sub(nh_,\"/imu_data\",1);\n    message_filters::Subscriber<sensor_msgs::PointCloud2> sub2(nh_,\"/camera/depth_registered/points\",1);\n    typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Imu,sensor_msgs::PointCloud2> MySync;\n    message_filters::Synchronizer<MySync> sync(MySync(10),sub,sub2);\n    sync.registerCallback(boost::bind(&callback,_1,_2));\n    // cv::namedWindow(\"colorview\",cv::WINDOW_NORMAL);\n    // cv::moveWindow(\"colorview\",100,100);\n    // cv::namedWindow(\"grayview\",cv::WINDOW_NORMAL);\n    // cv::moveWindow(\"grayview\",600,100);\n    ros::spin();\n    return 0;\n}\n", "meta": {"hexsha": "932a023700420b9dde9e593e73469422d9f64e43", "size": 13732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ORB_feature.cpp", "max_stars_repo_name": "Bonoy0328/robot_description", "max_stars_repo_head_hexsha": "288af718fecf7122e35eb0cb8fead15fa72ca5e3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ORB_feature.cpp", "max_issues_repo_name": "Bonoy0328/robot_description", "max_issues_repo_head_hexsha": "288af718fecf7122e35eb0cb8fead15fa72ca5e3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ORB_feature.cpp", "max_forks_repo_name": "Bonoy0328/robot_description", "max_forks_repo_head_hexsha": "288af718fecf7122e35eb0cb8fead15fa72ca5e3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5191256831, "max_line_length": 129, "alphanum_fraction": 0.6275852024, "num_tokens": 4357, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4194257918813479}}
{"text": "/* Copyright © 2017 Apple Inc. All rights reserved.\n *\n * Use of this source code is governed by a BSD-3-clause license that can\n * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause\n */\n#ifndef TURI_LINE_SEARCH_H_\n#define TURI_LINE_SEARCH_H_\n\n// Types\n#include <core/data/flexible_type/flexible_type.hpp>\n\n// Optimization\n#include <ml/optimization/optimization_interface.hpp>\n#include <ml/optimization/regularizer_interface.hpp>\n#include <Eigen/Core>\n#include <core/logging/assertions.hpp>\n\n// TODO: List of todo's for this file\n//------------------------------------------------------------------------------\n// 1. Feature: Armijo cubic interpolation line search.\n// 2. Feature: Wolfe cubic interpolation line search.\n// 3. Optimization: Add accepted function value to the ls_return structure\n//    (reduces 1 func eval per iteration)\n//\n\nnamespace turi {\n\nnamespace optimization {\n\n\n/**\n * \\ingroup group_optimization\n * \\addtogroup line_search Line Search\n * \\{\n */\n\n\n/** \"Zoom\" phase for More and Thuente line seach.\n *\n * \\note Applicable for smooth functions only.\n *\n * This code is a C++ port of Jorge Nocedal's implementaiton of More and\n * Thuente [2] line search. This code was availiable at\n * http://www.ece.northwestern.edu/~nocedal/lbfgs.html\n *\n * Nocedal's Condition for Use: This software is freely available for\n * educational or commercial purposes. We expect that all publications\n * describing work using this software quote at least one of the references\n * given below. This software is released under the BSD License\n *\n * The purpose of cstep is to compute a safeguarded step for a linesearch and\n * to update an interval of uncertainty for a minimizer of the function.\n *\n * The parameter stx contains the step with the least function value. The\n * parameter stp contains the current step. It is assumed that the derivative\n * at stx is negative in the direction of the step. If brackt is set true then\n * a minimizer has been bracketed in an interval of uncertainty with endpoints\n * stx and sty.\n *\n *\n * \\param[in] stx  Best step obtained so far.\n * \\param[in] fx   Function value at the best step so far.\n * \\param[in] dx   Directional derivative at the best step so far.\n * \\param[in] sty  Step at the end point of the uncertainty interval.\n * \\param[in] fy   Function value at end point of uncertainty interval.\n * \\param[in] dy   Directional derivative at end point of uncertainty interval.\n * \\param[in] stp  Current step.\n * \\param[in] fp   Function value at current step.\n * \\param[in] dp   Directional derivative at the current step.\n * \\param[in] brackt Has the minimizer has been bracketed?\n * \\param[in] stpmin Min step size\n * \\param[in] stpmax Max step size.\n *\n *\n */\ninline bool cstep(double &stx, double &fx, double &dx,\n           double &sty, double &fy, double &dy,\n           double &stp, double &fp,  double &dp,\n           bool &brackt, double stpmin, double stpmax){\n\n\n  const double p66 = 0.66;\n  bool info = false;\n\n  // Check the input parameters for errors.\n  // This should not happen.\n  if ((brackt && (stp <= std::min(stx,sty) || stp >= std::max(stx,sty)))\n      || (dx*(stp-stx) >= LS_ZERO) || (stpmax < stpmin)){\n     return info;\n  }\n\n\n  // Determine if the derivatives have opposite sign.\n  double sgnd = dp*(dx/std::abs(dx));\n\n  // Local variables\n  bool bound;\n  double theta, s, gamma, p, q, r, stpc, stpq, stpf;\n\n  // First case.\n  // -------------------------------------------------------------------------\n  // A higher function value. The minimum is bracketed. If the cubic step is\n  // closer to stx than the quadratic step, the cubic step is taken, else the\n  // average of the cubic and quadratic steps is taken.\n  if (fp > fx){\n\n    info = true;\n    bound = true;\n    theta = 3*(fx - fp)/(stp - stx) + dx + dp;\n    s = std::max(std::abs(theta), std::max(std::abs(dx),std::abs(dp)));\n    gamma = s*sqrt(pow(theta/s,2) - (dx/s)*(dp/s));\n\n    if (stp < stx)\n     gamma = -gamma;\n\n    p = (gamma - dx) + theta;\n    q = ((gamma - dx) + gamma) + dp;\n    r = p/q;\n    stpc = stx + r*(stp - stx);\n    stpq = stx + ((dx/((fx-fp)/(stp-stx)+dx))/2)*(stp - stx);\n\n    if (std::abs(stpc-stx) < std::abs(stpq-stx)){\n       stpf = stpc;\n    } else{\n      stpf = stpc + (stpq - stpc)/2;\n    }\n\n    brackt = true;\n\n  }\n  // Second case.\n  // -------------------------------------------------------------------------\n  // A lower function value and derivatives of opposite sign. The\n  // minimum is bracketed. If the cubic step is closer to stx than the\n  // quadratic (secant) step, the cubic step is taken, else the quadratic step\n  // is taken.\n  else if(sgnd <= 0){\n\n    info = true;\n    bound = false;\n\n    theta = 3*(fx - fp)/(stp - stx) + dx + dp;\n    s = std::max(std::abs(theta), std::max(std::abs(dx),std::abs(dp)));\n    gamma = s*sqrt(pow(theta/s,2) - (dx/s)*(dp/s));\n\n    if (stp > stx)\n       gamma = -gamma;\n\n    p = (gamma - dp) + theta;\n    q = ((gamma - dp) + gamma) + dx;\n    r = p/q;\n    stpc = stp + r*(stx - stp);\n    stpq = stp + (dp/(dp-dx))*(stx - stp);\n    if (std::abs(stpc-stp) > std::abs(stpq-stp)){\n       stpf = stpc;\n    } else {\n       stpf = stpq;\n    }\n    brackt = true;\n  }\n  // Third case.\n  // -------------------------------------------------------------------------\n  // A lower function value, derivatives of the same sign, and the\n  // magnitude of the derivative decreases.  The cubic step is only used if the\n  // cubic tends to infinity in the direction of the step or if the minimum of\n  // the cubic is beyond stp. Otherwise the cubic step is defined to be either\n  // stpmin or stpmax. The quadratic (secant) step is also computed and if the\n  // minimum is bracketed then the the step closest to stx is taken, else the\n  // step farthest away is taken.\n  else if (std::abs(dp) < std::abs(dx)){\n\n    info = true;\n    bound = true;\n    theta = 3*(fx - fp)/(stp - stx) + dx + dp;\n    s = std::max(std::abs(theta), std::max(std::abs(dx),std::abs(dp)));\n\n    // The case gamma = 0 only arises if the cubic does not tend to infinity\n    // in the direction of the step.\n\n    gamma = s*sqrt(std::max(0., pow((theta/s),2) - (dx/s)*(dp/s)));\n    if (stp > stx){\n        gamma = -gamma;\n    }\n\n    p = (gamma - dp) + theta;\n    q = (gamma + (dx - dp)) + gamma;\n    r = p/q;\n    if((r < 0.0) && (std::abs(gamma) <= OPTIMIZATION_ZERO)){\n       stpc = stp + r*(stx - stp);\n    }else if (stp > stx){\n       stpc = stpmax;\n    }else{\n       stpc = stpmin;\n    }\n\n    stpq = stp + (dp/(dp-dx))*(stx - stp);\n    if (brackt){\n       if (std::abs(stp-stpc) < std::abs(stp-stpq)){\n          stpf = stpc;\n       }else{\n          stpf = stpq;\n       }\n    }else{\n       if (std::abs(stp-stpc) > std::abs(stp-stpq)){\n          stpf = stpc;\n       }else{\n          stpf = stpq;\n       }\n    }\n\n  }\n  // Fourth case.\n  // -------------------------------------------------------------------------\n  // A lower function value, derivatives of the same sign, and the magnitude of\n  // the derivative does not decrease. If the minimum is not bracketed, the\n  // step is either stpmin or stpmax, else the cubic step is taken.\n  else{\n     info = true;\n     bound = false;\n     if (brackt){\n        theta = 3*(fp - fy)/(sty - stp) + dy + dp;\n        s = std::max(std::abs(theta), std::max(std::abs(dy),std::abs(dp)));\n        gamma = s*sqrt(pow(theta/s,2) - (dy/s)*(dp/s));\n\n        if (stp > sty){\n            gamma = -gamma;\n        }\n        p = (gamma - dp) + theta;\n        q = ((gamma - dp) + gamma) + dy;\n        r = p/q;\n        stpc = stp + r*(sty - stp);\n        stpf = stpc;\n     }else if (stp > stx){\n        stpf = stpmax;\n     }else {\n        stpf = stpmin;\n     }\n  }\n\n  // Update the interval of uncertainty.\n  // This update does not depend on the new step or the case analysis above.\n  if (fp > fx){\n     sty = stp;\n     fy = fp;\n     dy = dp;\n  }else{\n\n     if (sgnd < 0.0){\n        sty = stx;\n        fy = fx;\n        dy = dx;\n     }\n     stx = stp;\n     fx = fp;\n     dx = dp;\n  }\n\n  // Compute the new step and safeguard it.\n  stpf = std::min(stpmax,stpf);\n  stpf = std::max(stpmin,stpf);\n  stp = stpf;\n  if (brackt && bound){\n     if (sty > stx){\n        stp = std::min(stx+p66*(sty-stx),stp);\n     }else{\n        stp = std::max(stx+p66*(sty-stx),stp);\n     }\n  }\n\n  // cstep-failed\n  if (info == false){\n     logprogress_stream << \"Warning:\"\n                        << \" Unable to interpolate step size intervals.\"\n                        << std::endl;\n  }\n  return info;\n\n}\n\n\n\n/**\n *\n * Compute step sizes for line search methods to satisfy Strong Wolfe conditions.\n *\n * \\note Applicable for smooth functions only.\n *\n * This code is a C++ port of Jorge Nocedal's implementaiton of More and\n * Thuente [2] line search. This code was availiable at\n * http://www.ece.northwestern.edu/~nocedal/lbfgs.html\n *\n *   Line search based on More' and Thuente [1] to find a step which satisfies\n *   a Wolfe conditions for sufficient decrease condition and a curvature\n *   condition.\n *\n *   At each stage the function updates an interval of uncertainty with\n *   endpoints. The interval of uncertainty is initially chosen so that it\n *   contains a minimizer of the modified function\n *\n *        f(x+stp*s) - f(x) - ftol*stp*(gradf(x)'s).\n *\n *   If a step is obtained for which the modified function has a nonpositive\n *   function value and nonnegative derivative, then the interval of\n *   uncertainty is chosen so that it contains a minimizer of f(x+stp*s).\n *\n *   The algorithm is designed to find a step which satisfies the sufficient\n *   decrease condition\n *         f(x+stp*s) .le. f(x) + ftol*stp*(gradf(x)'s),          [W1]\n *   and the curvature condition\n *         std::abs(gradf(x+stp*s)'s)) .le. gtol*std::abs(gradf(x)'s).      [W2]\n *\n *  References:\n *\n *  (1) More, J. J. and D. J. Thuente. \"Line Search Algorithms with\n *  Guaranteed Sufficient Decrease.\" ACM Transactions on Mathematical Software\n *  20, no. 3 (1994): 286-307.\n *\n * (2) Wright S.J  and J. Nocedal. Numerical optimization. Vol. 2.\n *                         New York: Springer, 1999.\n * \\param[in] model Any model with a first order optimization interface.\n * \\param[in] init_step Initial step size\n * \\param[in] point Starting point for the solver.\n * \\param[in] gradient Gradient value at this point (saves computation)\n * \\param[in]    reg   Shared ptr to an interface to a smooth regularizer.\n * \\returns stats Line searnorm ch return object\n *\n*/\ntemplate <typename Vector>\ninline ls_return more_thuente(\n    first_order_opt_interface& model,\n    double init_step,\n    double init_func_value,\n    DenseVector point,\n    Vector gradient,\n    DenseVector direction,\n    double function_scaling = 1.0,\n    const std::shared_ptr<smooth_regularizer_interface> reg=NULL,\n    size_t max_function_evaluations = LS_MAX_ITER){\n\n\n    // Initialize the return object\n    ls_return stats;\n\n    // Input checking: Initial step size can't be zero.\n    if (init_step <= LS_ZERO){\n      logprogress_stream << \" Error:\"\n                         <<\" \\nInitial step step less than \"<< LS_ZERO\n                         << \".\" << std::endl;\n      return stats;\n    }\n\n\n    // Check that the initia direction is a descent direction.\n    // This can only occur of your gradients were computed incorrectly\n    // or the problem is non-convex.\n    DenseVector x0 = point;\n    double Dphi0 = gradient.dot(direction);\n    if ( (init_step <= 0) | (Dphi0 >= OPTIMIZATION_ZERO) ){\n      logprogress_stream << \" Error: Search direction is not a descent direction.\"\n                          <<\" \\nDetected numerical difficulties.\" << std::endl;\n    }\n\n    // Initializing local variables\n    // stx, fx, dgx: Values of the step, function, and derivative at the best\n    //               step.\n    //\n    // sty, fy, dgy: Values of the step, function, and derivative at the other\n    //               endpoint of the interval of uncertainty.\n    //\n    // st, f, dg   : Values of the step, function, and derivative at current\n    //               step\n    //\n    // g           : Gradient w.r.t x and step (vector) at the current point\n    //\n    double stx = LS_ZERO;\n    double fx = init_func_value;\n    double dgx = Dphi0;                   // Derivative of f(x + s d) w.r.t s\n\n    double sty = LS_ZERO;\n    double fy = init_func_value;\n    double dgy = Dphi0;\n\n    double stp = init_step;\n    double f = init_func_value;\n    double dg = Dphi0;\n    Vector g = gradient;\n    DenseVector reg_gradient(gradient.size());\n\n    // Interval [stmax, stmin] of uncertainty\n    double stmax = LS_ZERO;\n    double stmin = LS_MAX_STEP_SIZE;\n\n    // Flags and local variables\n    bool brackt = false;                 // Bracket or Zoon phase?\n    bool stage1 = true;\n\n    double wolfe_func_dec  = LS_C1*Dphi0;         // Wolfe condition [W1]\n    double wolfe_curvature = LS_C2*Dphi0;         // Wolfe condition [W2]\n    double width = stmax - stmin;\n    double width2 = 2*width;\n\n\n    // Constants used in this code.\n    // (Based on http://www.ece.northwestern.edu/~nocedal/lbfgs.html)\n    const double p5 = 0.5;\n    const double p66 = 0.66;\n    const double xtrapf = 4;\n    bool infoc = true;                            // Zoom status\n\n    // Start searching\n    while (true){\n\n      // Set the min and max steps based on the current interval of uncertainty.\n      if (brackt == true){\n        stmin = std::min(stx,sty);\n        stmax = std::max(stx,sty);\n      }else{\n        stmin = stx;\n        stmax = stp + xtrapf*(stp - stx);\n      }\n\n      // Force the step to be within the bounds\n      stp = std::max(stp,LS_ZERO);\n      stp = std::min(stp,LS_MAX_STEP_SIZE);\n\n      // If an unusual termination is to occur then let 'stp' be the lowest point\n      // obtained so far.\n      if ( (infoc == false)\n          || (brackt && (stmax-stmin <= LS_ZERO))){\n\n         logprogress_stream << \"Warning:\"\n            << \" Unusual termination criterion reached.\"\n            << \"\\nReturning the best step found so far.\"\n            << \" This typically happens when the number of features is much\"\n            << \" larger than the number of training samples. Consider pruning\"\n            << \" features manually or increasing the regularization value.\"\n            << std::endl;\n         stp = stx;\n      }\n\n      // Reached func evaluation limit -- return the best one so far.\n      if (size_t(stats.func_evals) >= max_function_evaluations){\n        stats.step_size = stx;\n        stats.status = true;\n        return stats;\n      }\n\n      // Evaluate the function and gradient at stp and compute the directional\n      // derivative.\n      point = x0 + stp * direction;\n      model.compute_first_order_statistics(point, g, f);\n      stats.num_passes++;\n      stats.func_evals++;\n      stats.gradient_evals++;\n      if (reg != NULL){\n        reg->compute_gradient(point, reg_gradient);\n        f += reg->compute_function_value(point);\n        g += reg_gradient;\n      }\n\n      if(function_scaling != 1.0) {\n        f *= function_scaling;\n        g *= function_scaling;\n      }\n\n      dg = g.dot(direction);\n\n      double ftest = init_func_value + stp*wolfe_func_dec;\n\n      // Termination checking\n      // Note: There are many good checks and balances used in Nocedal's code\n      // Some of them are overly defensive and should not happen.\n\n      // Rounding errors\n      if ( (brackt && ((stp <= stmin) || (stp >= stmax))) || (infoc == false)){\n          logprogress_stream << \"Warning: Rounding errors\"\n            << \" prevent further progress. \\nThere may not be a step which\"\n            << \" satisfies the sufficient decrease and curvature conditions.\"\n            << \" \\nTolerances may be too small or dataset may be poorly scaled.\"\n            << \" This typically happens when the number of features is much\"\n            << \" larger than the number of training samples. Consider pruning\"\n            << \" features manually or increasing the regularization value.\"\n            << std::endl;\n          stats.step_size = stp;\n          stats.status = false;\n          return stats;\n      }\n\n      // Step is more than LS_MAX_STEP_SIZE\n      if ((stp >= LS_MAX_STEP_SIZE) && (f <= ftest) && (dg <= wolfe_func_dec)){\n        logprogress_stream << \"Warning: Reached max step size.\"\n                           << std::endl;\n        stats.step_size = stp;\n        stats.status = true;\n        return stats;\n      }\n\n      // Step is smaller than LS_ZERO\n      if ((stp <= LS_ZERO) && ((f > ftest) || (dg >= wolfe_func_dec))){\n        logprogress_stream << \"Error: Reached min step size.\"\n                           << \" Cannot proceed anymore.\"\n                           << std::endl;\n        stats.step_size = stp;\n        stats.status = false;\n        return stats;\n      }\n\n\n\n      // Relative width of the interval of uncertainty is reached.\n      if (brackt && (stmax-stmin <= LS_ZERO)){\n        logprogress_stream << \"Error: \\nInterval of uncertainty\"\n                           << \"lower than step size limit.\" << std::endl;\n        stats.status = false;\n        return stats;\n      }\n\n      // Wolfe conditions W1 and W2 are satisfied! Woo!\n      if ((f <= ftest) && (std::abs(dg) <= -wolfe_curvature)){\n        stats.step_size = stp;\n        stats.status = true;\n        return stats;\n      }\n\n      // Stage 1 is a search for steps for which the modified function has\n      // a nonpositive value and nonnegative derivative.\n      if ( stage1 && (f <= ftest) && (dg >= wolfe_curvature)){\n             stage1 = false;\n      }\n\n\n      // A modified function is used to predict the step only if we have not\n      // obtained a step for which the modified function has a nonpositive\n      // function value and nonnegative derivative, and if a lower function\n      // value has been  obtained but the decrease is not sufficient.\n\n      if (stage1 && (f <= fx) && (f > ftest)){\n\n         // Define the modified function and derivative values.\n         double fm = f - stp*wolfe_func_dec;\n         double fxm = fx - stx*wolfe_func_dec;\n         double fym = fy - sty*wolfe_func_dec;\n         double dgm = dg - wolfe_func_dec;\n         double dgxm = dgx - wolfe_func_dec;\n         double dgym = dgy - wolfe_func_dec;\n\n         // Call cstep to update the interval of uncertainty and to compute the\n         // new step.\n         infoc = cstep(stx,fxm, dgxm,\n                       sty, fym, dgym,\n                       stp, fm, dgm,\n                       brackt,\n                       stmin,stmax);\n\n         // Reset the function and gradient values for f.\n         fx = fxm + stx*wolfe_func_dec;\n         fy = fym + sty*wolfe_func_dec;\n         dgx = dgxm + wolfe_func_dec;\n         dgy = dgym + wolfe_func_dec;\n\n      }else{\n\n         // Call cstep to update the interval of uncertainty and to compute the\n         // new step.\n         infoc = cstep(stx,fx, dgx,\n                       sty, fy, dgy,\n                       stp, f, dg,\n                       brackt,\n                       stmin,stmax);\n\n      }\n\n\n      // Force a sufficient decrease in the size of the interval of uncertainty.\n      if (brackt){\n         if (std::abs(sty-stx) >= p66*width2){\n           stp = stx + p5*(sty - stx);\n         }\n\n         width2 = width;\n         width = std::abs(sty-stx);\n      }\n\n    } // end-of-while\n\n    return stats;\n\n}\n\n\n/**\n *\n * Armijo backtracking to compute step sizes for line search methods.\n *\n * \\note Applicable for smooth functions only.\n *\n * Line search based on an backtracking strategy to ensure sufficient\n * decrease in function values at each iteration.\n *\n * References:\n * (1) Wright S.J  and J. Nocedal. Numerical optimization. Vol. 2.\n *                         New York: Springer, 1999.\n *\n * \\param[in] model Any model with a first order optimization interface.\n * \\param[in] init_step Initial step size.\n * \\param[in] init_func Initial function value.\n * \\param[in] point     Starting point for the solver.\n * \\param[in] gradient  Gradient value at this point.\n * \\param[in] direction Direction of the next step .\n *\n * \\returns stats Line searnorm ch return object\n *\n*/\ntemplate <typename Vector>\ninline ls_return armijo_backtracking(\n    first_order_opt_interface& model,\n    double init_step,\n    double init_func_value,\n    DenseVector point,\n    Vector gradient,\n    DenseVector direction){\n\n    // Step 1: Initialize the function\n    // ------------------------------------------------------------------------\n    // Min function decrease according to Armijo conditions.\n    // The choice of constants are based on Nocedal and Wright [1].\n    double sufficient_decrease = LS_C1*(gradient.dot(direction));\n    ls_return stats;\n    double step_size = init_step;\n    DenseVector new_point = point;\n\n    // Step 2: Backtrack\n    // -----------------------------------------------------------------------\n    while (stats.func_evals <= LS_MAX_ITER && step_size >= LS_ZERO){\n\n      // Check for sufficient decrease\n      new_point = point + step_size * direction;\n      if (model.compute_function_value(new_point) <= init_func_value\n          + step_size * sufficient_decrease){\n\n        stats.step_size = step_size;\n        stats.status = true;\n        return stats;\n\n      }\n\n      step_size *= 0.5;\n      stats.func_evals += 1;\n\n    }\n\n    return stats;\n}\n\n\n/**\n *\n * Backtracking to compute step sizes for line search methods.\n *\n * \\note Applicable for non-smooth functions.\n *\n * Line search based on an backtracking strategy to \"some\" decrease in function\n * values at each iteration.\n *\n * References:\n * (1) Wright S.J  and J. Nocedal. Numerical optimization. Vol. 2.\n *                         New York: Springer, 1999.\n *\n * \\param[in] model Any model with a first order optimization interface.\n * \\param[in] init_step Initial step size.\n * \\param[in] init_func Initial function value.\n * \\param[in] point     Starting point for the solver.\n * \\param[in] gradient  Gradient value at this point.\n * \\param[in] direction Direction of the next step .\n * \\param[in] reg       Regularizer interface!\n *\n * \\returns stats Line searnorm ch return object\n *\n*/\ntemplate <typename Vector>\ninline ls_return backtracking(\n    first_order_opt_interface& model,\n    double init_step,\n    double init_func_value,\n    DenseVector point,\n    Vector gradient,\n    DenseVector direction,\n    const std::shared_ptr<regularizer_interface> reg=NULL){\n\n    // Step 1: Initialize the function\n    // ------------------------------------------------------------------------\n    ls_return stats;\n    double step_size = init_step;\n    DenseVector delta_point(point.size());;\n    DenseVector new_point(point.size());;\n\n    // Step 2: Backtrack\n    // -----------------------------------------------------------------------\n    while (stats.func_evals <= LS_MAX_ITER && step_size >= LS_ZERO){\n\n      // Check for sufficient decrease\n      new_point = point + step_size * direction;\n      if(reg != NULL){\n        reg->apply_proximal_operator(new_point, step_size);\n      }\n\n      delta_point = new_point - point;\n      if (model.compute_function_value(new_point) <=\n             init_func_value + gradient.dot(delta_point)\n                            + 0.5 * delta_point.squaredNorm()/step_size){\n\n        stats.step_size = step_size;\n        stats.status = true;\n        return stats;\n\n      }\n\n      step_size *= 0.5;\n      stats.func_evals += 1;\n\n    }\n\n    return stats;\n}\n\n/** This function estimates a minumum point between\n *  two function values with known gradients.\n *\n *  The minimum value must lie between the two function values, f1 and f2, and the\n *  gradients must indicate the minimum lies between the two values and that the\n *  function is convex.\n *\n *  Under these situations, a third degree polynomial / cubic spline can be fit\n *  to the two function points, and this is gauranteed to have a single minimum\n *  between f1 and f2.  This is what this function returns.\n *\n *  \\param[in] dist  The distance between the points f1 and f2.\n *  \\param[in] f1    The value of the function at the left point.\n *  \\param[in] f2    The value of the function at the right point.\n *  \\param[in] g1    The derivative of the function at the left point.\n *  \\param[in] g2    The derivative of the function at the right point.\n *\n */\ninline double gradient_bracketed_linesearch(double dist, double f1, double f2,\n                                            double g1, double g2) {\n  // Assume f1 is evaluated at 0, f2 is evaluated at 1.  To make the latter true,\n  // we need to multiply the gradients by the appropriate scaling factor.\n  g1 *= dist;\n  g2 *= dist;\n\n  // We have to have this such that a minimum point is between f1 and f2, which\n  DASSERT_LE(g1, 1e-4);   // Condition 1\n  DASSERT_GE(g2, -1e-4);  // Condition 2\n\n  // Also make sure the function is convex;\n  DASSERT_LE(f2 - g2, f1 + 1e-4);  // Condition 3\n  DASSERT_LE(f1 + g1, f2 + 1e-4);  // Condition 4\n\n\n  // Now, we have 4 known variables, so construct a 3rd order polynomial to\n  // approximate the solution between the two points.  Then find the minimum of\n  // that.\n\n  // With the convexity coefficients above, a third order polynomial, given as\n  //\n  //   p(t) = a*t^3 + b*t^2 + c*t + d\n  //\n  // will have exactly one minima between 0 and 1 by the conditions above.\n  //\n  // The coefficients can be easily derived by:\n  // p(0) = f1\n  // p(1) = f2\n  // p'(0) = g1\n  // p'(1) = g2\n  //\n  // Some algebra yields:\n  //\n  const double a = -2*(f2 - f1) + (g2 + g1);\n  const double b = 3*(f2 - f1) - g2 - 2*g1;\n  const double c = g1;\n  const double d = f1;\n\n  // std::cout << \"coeff = (\" << a << \", \" << b << \", \" << c << std::endl;\n\n  // Starting iterate\n  double left = 0;\n  double right = 1;\n\n  double best_value = std::min(f1, f2);\n  double best_loc = f1 < f2 ? 0 : 1;\n\n\n  for(size_t m_iter = 0; m_iter < 32; ++m_iter) {\n\n    double t = 0.5 * (right + left);\n\n    // Make sure that the recent value is indeed better\n    double v = d + c*t + b*t*t + a*t*t*t;\n    // double vpp = 2*b + 6*a*t;\n\n    if(v < best_value) {\n      best_value = v;\n      best_loc = t;\n    }\n\n    if(right - left < 1e-6) {\n      break;\n    }\n\n    double vp = c + 2*b*t + 3*a*t*t;\n\n    if(vp > 0) {\n      right = t;\n    } else {\n      left = t;\n    }\n\n  }\n\n  return dist * best_loc;\n}\n\n\n\n\n/// \\}\n\n} // optimizaiton\n\n} // turicreate\n\n#endif\n", "meta": {"hexsha": "d4d64cdb9b702cf3c061fb69830a393cfa8afb35", "size": 26297, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ml/optimization/line_search-inl.hpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/ml/optimization/line_search-inl.hpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/ml/optimization/line_search-inl.hpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 31.569027611, "max_line_length": 86, "alphanum_fraction": 0.5902574438, "num_tokens": 6854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.41942579188134776}}
{"text": "\n//////////////////////////////////////////////////////////////////////////////////\n// MIT License\n//\n// Copyright (c) 2017 Vicon Motion Systems Ltd\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//////////////////////////////////////////////////////////////////////////////////\n#include \"RetimerUtils.h\"\n\n#include <ViconDataStreamSDKCoreUtils/ClientUtils.h>\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace bmc = boost::math::constants;\n\nnamespace ClientUtils\n{\n  typedef std::array< double, 4 > Quaternion;\n  typedef std::array< double, 3 > Axis;\n  typedef std::array< double, 3 > Displacement;\n\n  Quaternion Conjugate( const Quaternion & i_rInput )\n  {\n    Quaternion conj = { -i_rInput[0], -i_rInput[1], -i_rInput[2], i_rInput[3] };\n    return conj;\n  }\n\n  Quaternion Inverse( const Quaternion & i_rInput )\n  {\n    Quaternion inv = Conjugate( i_rInput );\n    double DotProd = 0;\n    for( unsigned i = 0; i < 4; ++i ) DotProd += ( i_rInput[i] * i_rInput[i] );\n    for( unsigned i = 0; i < 4; ++i ) inv[i] /= DotProd;\n    return inv;\n  }\n\n  Axis Imaginary( const Quaternion & i_rInput )\n  {\n    Axis axis = { i_rInput[0], i_rInput[1], i_rInput[2] };\n    return axis;\n  }\n\n  double Magnitude( const Axis & i_rInput )\n  {\n    double mag = 0;\n    for( unsigned int i = 0; i < 3; ++i )\n    {\n      mag += i_rInput[i] * i_rInput[i];\n    }\n    return sqrt( mag );\n  }\n\n\n  void Normalize( Axis & io_rInput )\n  {\n    double Mag = Magnitude( io_rInput );\n    io_rInput /= Mag;\n  }\n\n  bool ToAxisAngle( const Quaternion & i_rInput, Axis & o_rAxis, double & o_rAngle )\n  {\n    bool success = true;\n\n    // angle is always positive\n    Axis imag = Imaginary( i_rInput );\n    double mag = Magnitude( imag );\n    o_rAngle = 2 * std::atan2( mag, i_rInput[3] );\n    \n    // direc parallel to imag. part\n    o_rAxis = imag;\n    if( mag == 0.0 ) \n    {\n      // or signal exception here.\n      o_rAxis[2] = 1.0;                    \n      success = false;\n    }\n    else\n    {\n      // normalize direction vector\n      for( unsigned int i = 0; i < 3; ++i ) o_rAxis[i] /= mag;                       \n    }\n    return success;\n  }\n\n  Quaternion FromAxisAngle( const Axis & i_rAxis, const double & i_rAngle )\n  {\n    // This should take a normalized vector\n    Axis AxisCopy = i_rAxis;\n    Normalize( AxisCopy );\n\n    Quaternion output;\n\n    // half angle\n    double a = i_rAngle * 0.5;  \n    double s = std::sin( a );\n    \n    for( int i = 0; i < 3; i++ )            \n    {\n      // imaginary vector is sine of half angle multiplied with axis\n      output[i] = s * AxisCopy[i];\n    }\n\n    // real part is cosine of half angle\n    output[3] = std::cos( a );   \n\n    return output;\n  }\n\n  RotationMatrix ToRotationMatrix( const Quaternion & i_rInput )\n  {\n    double x2 = i_rInput[0] * i_rInput[0];\n    double xy = i_rInput[0] * i_rInput[1];\n    double rx = i_rInput[3] * i_rInput[0];\n    double y2 = i_rInput[1] * i_rInput[1];\n    double yz = i_rInput[1] * i_rInput[2];\n    double ry = i_rInput[3] * i_rInput[1];\n    double z2 = i_rInput[2] * i_rInput[2];\n    double zx = i_rInput[2] * i_rInput[0]; \n    double rz = i_rInput[3] * i_rInput[2];\n    double r2 = i_rInput[3] * i_rInput[3];\n\n    RotationMatrix Output;\n    // fill diagonal terms \n    Output[ 0 ] = r2 + x2 - y2 - z2;    //(0,0)\n    Output[ 4 ] = r2 - x2 + y2 - z2; // (1,1)\n    Output[ 8 ] = r2 - x2 - y2 + z2; // (2,2)\n\n    // fill off diagonal terms (output not transposed; differing from vnl_quaternion::rotation_matrix_transposed\n    Output[ 3 ] = 2 * ( xy + rz ); // (1,0)            \n    Output[ 6 ] = 2 * ( zx - ry ); // (2,0)\n    Output[ 7 ] = 2 * ( yz + rx ); // (2,1)\n    Output[ 1 ] = 2 * ( xy - rz ); // (0,1)\n    Output[ 2 ] = 2 * ( zx + ry ); // (0,2)\n    Output[ 5 ] = 2 * ( yz - rx ); // (1,2)\n\n    return Output;\n  }\n\n  Axis operator*( const Axis & i_rLeft, double i_rVal )\n  {\n    Axis Result;\n    std::transform( i_rLeft.begin(), i_rLeft.end(), Result.begin(), [&]( double x ){ return x * i_rVal; } );\n    return Result;\n  }\n\n  Axis operator+=( Axis & i_rLeft, const Axis & i_rRight )\n  {\n    std::transform( i_rLeft.begin(), i_rLeft.end(), i_rRight.begin(), i_rLeft.begin(), []( double x, double y ){ return x + y; } );\n    return i_rLeft;\n  }\n\n  Quaternion operator*( const Quaternion & i_rLeft, const Quaternion & i_rRight )\n  {\n    Quaternion output;\n    double r1 = i_rLeft[3];                  // real and img parts of args\n    double r2 = i_rRight[3];\n    Axis i1 = Imaginary( i_rLeft );\n    Axis i2 = Imaginary( i_rRight );\n    double real_v = ( r1 * r2 ) - DotProduct( i1, i2 ); // real&img of product q1*q2\n    Axis img = CrossProduct( i1, i2 );\n    Axis i2r1 = i2*r1;\n    Axis i1r2 = i1*r2;\n    Axis i2r1i1r2 = i2r1 + i1r2;\n    img += i2r1i1r2;\n    output = { img[0], img[1], img[2], real_v };\n    return output;\n  }\n\n  // Simple interpolation using linear interpolation and prediction\n  /// Returns a rotation prediction at time t3 from 2 rotation r1 at time t1 and r2 and time t2\n  /// where t3 > t2 > t1\n  // From http://answers.unity3d.com/questions/168779/extrapolating-quaternion-rotation.html\n  Quaternion PredictRotation( Quaternion r1, double t1, Quaternion r2, double t2, double t3 )\n  {\n    Quaternion rot = r2 * Inverse( r1 ); // rot is rotation from t1 to t2\n\n    double dt = ( t3 - t1 ) / ( t2 - t1 ); // dt = extrapolation factor\n\n    // Convert to Axis/Angle\n    Axis axis;\n    double angle;\n    if( !ToAxisAngle( rot, axis, angle ) )\n    {\n      // Check the magnitude of the imaginary part is not zero, as then\n      // the axis of the quaternion will not be well defined.\n      return r1;\n    }\n\n    // Assume shortest path\n    if( angle > bmc::pi< double >() ) angle -= ( 2 * bmc::pi< double >() );\n\n    // Multiple angle by extrapolation factor\n    angle = fmod( angle * dt, ( 2 * bmc::pi< double >() ) );\n\n    // Combine with first rotation\n    Quaternion r3 = FromAxisAngle( axis, angle ) * r1;\n\n    return r3;\n  }\n\n  /// Returns a translation prediction at time t3 from 2 translations at time d1, t1; d2, t2 where t3 > t2 > t1 \n  /// Can also be used for linear interpolation where t2 > t3 > t1\n  Displacement PredictDisplacement( const Displacement & d1, double t1, const Displacement & d2, double t2, double t3 )\n  {\n\n    // disp is displacement from t1 to t2\n    Displacement disp( d2 - d1 );\n\n    // extrapolation factor\n    double dt = ( t3 - t1 ) / ( t2 - t1 );\n\n    // multiply displacement by extrapolation factor\n    disp *= dt;\n\n    // Combine with first displacement\n    Displacement d3 = d1 + disp;\n\n    return d3;\n  }\n\n  double PredictVal(const double d1, const double t1, const double d2, const double t2, double t3)\n  {\n    // disp is displacement from t1 to t2\n    double disp( d2 - d1 );\n\n    // extrapolation factor\n    double dt = ( t3 - t1 ) / ( t2 - t1 );\n\n    // multiply displacement by extrapolation factor\n    disp *= dt;\n\n    // Combine with first displacement\n    double d3 = d1 + disp;\n\n    return d3;\n\n  }\n}\n\n\n", "meta": {"hexsha": "982a07170a02b725a5dda427003ee95123da6b49", "size": 7972, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Vicon/CrossMarket/DataStream/ViconDataStreamSDKCore/RetimerUtils.cpp", "max_stars_repo_name": "BrainsOnBoard/ViconDataStreamSDK", "max_stars_repo_head_hexsha": "6ec2a4a77ecb31910aaf82df814f359399c1e173", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-21T21:59:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-21T21:59:32.000Z", "max_issues_repo_path": "Vicon/CrossMarket/DataStream/ViconDataStreamSDKCore/RetimerUtils.cpp", "max_issues_repo_name": "BrainsOnBoard/ViconDataStreamSDK", "max_issues_repo_head_hexsha": "6ec2a4a77ecb31910aaf82df814f359399c1e173", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vicon/CrossMarket/DataStream/ViconDataStreamSDKCore/RetimerUtils.cpp", "max_forks_repo_name": "BrainsOnBoard/ViconDataStreamSDK", "max_forks_repo_head_hexsha": "6ec2a4a77ecb31910aaf82df814f359399c1e173", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-17T13:49:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-17T13:49:30.000Z", "avg_line_length": 30.8992248062, "max_line_length": 131, "alphanum_fraction": 0.6049924737, "num_tokens": 2344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.41942579188134776}}
{"text": "/* boost random/nierderreiter_base2.hpp header file\n *\n * Copyright Justinas Vygintas Daugmaudis 2010-2018\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_RANDOM_NIEDERREITER_BASE2_HPP\n#define BOOST_RANDOM_NIEDERREITER_BASE2_HPP\n\n#include <boost/random/detail/niederreiter_base2_table.hpp>\n#include <boost/random/detail/gray_coded_qrng.hpp>\n\n#include <boost/dynamic_bitset.hpp>\n\nnamespace boost {\nnamespace random {\n\n/** @cond */\nnamespace qrng_detail {\nnamespace nb2 {\n\n// Return the base 2 logarithm for a given bitset v\ntemplate <typename DynamicBitset>\ninline typename DynamicBitset::size_type\nbitset_log2(const DynamicBitset& v)\n{\n  if (v.none())\n    boost::throw_exception( std::invalid_argument(\"bitset_log2\") );\n\n  typename DynamicBitset::size_type hibit = v.size() - 1;\n  while (!v.test(hibit))\n    --hibit;\n  return hibit;\n}\n\n\n// Multiply polynomials over Z_2.\ntemplate <typename PolynomialT, typename DynamicBitset>\ninline void modulo2_multiply(PolynomialT P, DynamicBitset& v, DynamicBitset& pt)\n{\n  pt.reset(); // pt == 0\n  for (; P; P >>= 1, v <<= 1)\n    if (P & 1) pt ^= v;\n  pt.swap(v);\n}\n\n\n// Calculate the values of the constants V(J,R) as\n// described in BFN section 3.3.\n//\n// pb = polynomial defined in section 2.3 of BFN.\ntemplate <typename DynamicBitset>\ninline void calculate_v(const DynamicBitset& pb,\n  typename DynamicBitset::size_type kj,\n  typename DynamicBitset::size_type pb_degree,\n  DynamicBitset& v)\n{\n  typedef typename DynamicBitset::size_type size_type;\n\n  // Now choose values of V in accordance with\n  // the conditions in section 3.3.\n  size_type r = 0;\n  for ( ; r != kj; ++r)\n    v.reset(r);\n\n  // Quoting from BFN: \"Our program currently sets each K_q\n  // equal to eq. This has the effect of setting all unrestricted\n  // values of v to 1.\"\n  for ( ; r < pb_degree; ++r)\n    v.set(r);\n\n  // Calculate the remaining V's using the recursion of section 2.3,\n  // remembering that the B's have the opposite sign.\n  for ( ; r != v.size(); ++r)\n  {\n    bool term = false;\n    for (typename DynamicBitset::size_type k = 0; k < pb_degree; ++k)\n    {\n      term ^= pb.test(k) & v[r + k - pb_degree];\n    }\n    v[r] = term;\n  }\n}\n\n} // namespace nb2\n\ntemplate<typename UIntType, unsigned w, typename Nb2Table>\nstruct niederreiter_base2_lattice\n{\n  typedef UIntType value_type;\n\n  BOOST_STATIC_ASSERT(w > 0u);\n  BOOST_STATIC_CONSTANT(unsigned, bit_count = w);\n\nprivate:\n  typedef std::vector<value_type> container_type;\n\npublic:\n  explicit niederreiter_base2_lattice(std::size_t dimension)\n  {\n    resize(dimension);\n  }\n\n  void resize(std::size_t dimension)\n  {\n    typedef boost::dynamic_bitset<> bitset_type;\n\n    dimension_assert(\"Niederreiter base 2\", dimension, Nb2Table::max_dimension);\n\n    // Initialize the bit array\n    container_type cj(bit_count * dimension);\n\n    // Reserve temporary space for lattice computation\n    bitset_type v, pb, tmp;\n\n    // Compute Niedderreiter base 2 lattice\n    for (std::size_t dim = 0; dim != dimension; ++dim)\n    {\n      const typename Nb2Table::value_type poly = Nb2Table::polynomial(dim);\n      if (poly > std::numeric_limits<value_type>::max()) {\n        boost::throw_exception( std::range_error(\"niederreiter_base2: polynomial value outside the given value type range\") );\n      }\n\n      const unsigned degree = multiprecision::msb(poly); // integer log2(poly)\n      const unsigned space_required = degree * ((bit_count / degree) + 1); // ~ degree + bit_count\n\n      v.resize(degree + bit_count - 1);\n\n      // For each dimension, we need to calculate powers of an\n      // appropriate irreducible polynomial, see Niederreiter\n      // page 65, just below equation (19).\n      // Copy the appropriate irreducible polynomial into PX,\n      // and its degree into E. Set polynomial B = PX ** 0 = 1.\n      // M is the degree of B. Subsequently B will hold higher\n      // powers of PX.\n      pb.resize(space_required); tmp.resize(space_required);\n\n      typename bitset_type::size_type kj, pb_degree = 0;\n      pb.reset(); // pb == 0\n      pb.set(pb_degree); // set the proper bit for the pb_degree\n\n      value_type j = high_bit_mask_t<bit_count - 1>::high_bit;\n      do\n      {\n        // Now choose a value of Kj as defined in section 3.3.\n        // We must have 0 <= Kj < E*J = M.\n        // The limit condition on Kj does not seem to be very relevant\n        // in this program.\n        kj = pb_degree;\n\n        // Now multiply B by PX so B becomes PX**J.\n        // In section 2.3, the values of Bi are defined with a minus sign :\n        // don't forget this if you use them later!\n        nb2::modulo2_multiply(poly, pb, tmp);\n        pb_degree += degree;\n        if (pb_degree >= pb.size()) {\n          // Note that it is quite possible for kj to become bigger than\n          // the new computed value of pb_degree.\n          pb_degree = nb2::bitset_log2(pb);\n        }\n\n        // If U = 0, we need to set B to the next power of PX\n        // and recalculate V.\n        nb2::calculate_v(pb, kj, pb_degree, v);\n\n        // Niederreiter (page 56, after equation (7), defines two\n        // variables Q and U.  We do not need Q explicitly, but we\n        // do need U.\n\n        // Advance Niederreiter's state variables.\n        for (unsigned u = 0; j && u != degree; ++u, j >>= 1)\n        {\n          // Now C is obtained from V. Niederreiter\n          // obtains A from V (page 65, near the bottom), and then gets\n          // C from A (page 56, equation (7)).  However this can be done\n          // in one step.  Here CI(J,R) corresponds to\n          // Niederreiter's C(I,J,R), whose values we pack into array\n          // CJ so that CJ(I,R) holds all the values of C(I,J,R) for J from 1 to NBITS.\n          for (unsigned r = 0; r != bit_count; ++r) {\n            value_type& num = cj[dimension * r + dim];\n            // set the jth bit in num\n            num = (num & ~j) | (-v[r + u] & j);\n          }\n        }\n      } while (j != 0);\n    }\n\n    bits.swap(cj);\n  }\n\n  typename container_type::const_iterator iter_at(std::size_t n) const\n  {\n    BOOST_ASSERT(!(n > bits.size()));\n    return bits.begin() + n;\n  }\n\nprivate:\n  container_type bits;\n};\n\n} // namespace qrng_detail\n\ntypedef detail::qrng_tables::niederreiter_base2 default_niederreiter_base2_table;\n\n/** @endcond */\n\n//!Instantiations of class template niederreiter_base2_engine model a \\quasi_random_number_generator.\n//!The niederreiter_base2_engine uses the algorithm described in\n//! \\blockquote\n//!Bratley, Fox, Niederreiter, ACM Trans. Model. Comp. Sim. 2, 195 (1992).\n//! \\endblockquote\n//!\n//!\\attention niederreiter_base2_engine skips trivial zeroes at the start of the sequence. For example,\n//!the beginning of the 2-dimensional Niederreiter base 2 sequence in @c uniform_01 distribution will look\n//!like this:\n//!\\code{.cpp}\n//!0.5, 0.5,\n//!0.75, 0.25,\n//!0.25, 0.75,\n//!0.375, 0.375,\n//!0.875, 0.875,\n//!...\n//!\\endcode\n//!\n//!In the following documentation @c X denotes the concrete class of the template\n//!niederreiter_base2_engine returning objects of type @c UIntType, u and v are the values of @c X.\n//!\n//!Some member functions may throw exceptions of type std::range_error. This\n//!happens when the quasi-random domain is exhausted and the generator cannot produce\n//!any more values. The length of the low discrepancy sequence is given by\n//! \\f$L=Dimension \\times (2^{w} - 1)\\f$.\ntemplate<typename UIntType, unsigned w, typename Nb2Table = default_niederreiter_base2_table>\nclass niederreiter_base2_engine\n  : public qrng_detail::gray_coded_qrng<\n      qrng_detail::niederreiter_base2_lattice<UIntType, w, Nb2Table>\n    >\n{\n  typedef qrng_detail::niederreiter_base2_lattice<UIntType, w, Nb2Table> lattice_t;\n  typedef qrng_detail::gray_coded_qrng<lattice_t> base_t;\n\npublic:\n  //!Effects: Constructs the default `s`-dimensional Niederreiter base 2 quasi-random number generator.\n  //!\n  //!Throws: bad_alloc, invalid_argument, range_error.\n  explicit niederreiter_base2_engine(std::size_t s)\n    : base_t(s) // initialize lattice here\n  {}\n\n#ifdef BOOST_RANDOM_DOXYGEN\n  //=========================Doxygen needs this!==============================\n  typedef UIntType result_type;\n\n  //!Returns: Tight lower bound on the set of values returned by operator().\n  //!\n  //!Throws: nothing.\n  static BOOST_CONSTEXPR result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()\n  { return (base_t::min)(); }\n\n  //!Returns: Tight upper bound on the set of values returned by operator().\n  //!\n  //!Throws: nothing.\n  static BOOST_CONSTEXPR result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()\n  { return (base_t::max)(); }\n\n  //!Returns: The dimension of of the quasi-random domain.\n  //!\n  //!Throws: nothing.\n  std::size_t dimension() const { return base_t::dimension(); }\n\n  //!Effects: Resets the quasi-random number generator state to\n  //!the one given by the default construction. Equivalent to u.seed(0).\n  //!\n  //!\\brief Throws: nothing.\n  void seed()\n  {\n    base_t::seed();\n  }\n\n  //!Effects: Effectively sets the quasi-random number generator state to the `init`-th\n  //!vector in the `s`-dimensional quasi-random domain, where `s` == X::dimension().\n  //!\\code\n  //!X u, v;\n  //!for(int i = 0; i < N; ++i)\n  //!    for( std::size_t j = 0; j < u.dimension(); ++j )\n  //!        u();\n  //!v.seed(N);\n  //!assert(u() == v());\n  //!\\endcode\n  //!\n  //!\\brief Throws: range_error.\n  void seed(UIntType init)\n  {\n    base_t::seed(init);\n  }\n\n  //!Returns: Returns a successive element of an `s`-dimensional\n  //!(s = X::dimension()) vector at each invocation. When all elements are\n  //!exhausted, X::operator() begins anew with the starting element of a\n  //!subsequent `s`-dimensional vector.\n  //!\n  //!Throws: range_error.\n  result_type operator()()\n  {\n    return base_t::operator()();\n  }\n\n  //!Effects: Advances *this state as if `z` consecutive\n  //!X::operator() invocations were executed.\n  //!\\code\n  //!X u = v;\n  //!for(int i = 0; i < N; ++i)\n  //!    u();\n  //!v.discard(N);\n  //!assert(u() == v());\n  //!\\endcode\n  //!\n  //!Throws: range_error.\n  void discard(boost::uintmax_t z)\n  {\n    base_t::discard(z);\n  }\n\n  //!Returns true if the two generators will produce identical sequences of outputs.\n  BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(niederreiter_base2_engine, x, y)\n  { return static_cast<const base_t&>(x) == y; }\n\n  //!Returns true if the two generators will produce different sequences of outputs.\n  BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(niederreiter_base2_engine)\n\n  //!Writes the textual representation of the generator to a @c std::ostream.\n  BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, niederreiter_base2_engine, s)\n  { return os << static_cast<const base_t&>(s); }\n\n  //!Reads the textual representation of the generator from a @c std::istream.\n  BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, niederreiter_base2_engine, s)\n  { return is >> static_cast<base_t&>(s); }\n\n#endif // BOOST_RANDOM_DOXYGEN\n};\n\n\n/**\n * @attention This specialization of \\niederreiter_base2_engine supports up to 4720 dimensions.\n *\n * Binary irreducible polynomials (primes in the ring `GF(2)[X]`, evaluated at `X=2`) were generated\n * while condition `max(prime)` < 2<sup>16</sup> was satisfied.\n *\n * There are exactly 4720 such primes, which yields a Niederreiter base 2 table for 4720 dimensions.\n *\n * However, it is possible to provide your own table to \\niederreiter_base2_engine should the default one be insufficient.\n */\ntypedef niederreiter_base2_engine<boost::uint_least64_t, 64u, default_niederreiter_base2_table> niederreiter_base2;\n\n} // namespace random\n\n} // namespace boost\n\n#endif // BOOST_RANDOM_NIEDERREITER_BASE2_HPP\n", "meta": {"hexsha": "149a4a4b4c5225448a6188954e0195e79863c281", "size": 11736, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/random/niederreiter_base2.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/random/niederreiter_base2.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/random/niederreiter_base2.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 32.5096952909, "max_line_length": 126, "alphanum_fraction": 0.6717791411, "num_tokens": 3177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4193925278658847}}
{"text": "///\r\n/// @file dijkstra-bgl.h\r\n/// @author Jxtopher\r\n/// @version 1\r\n/// @date 2019\r\n/// @brief Implementation dijkstra with Boost Graph Library\r\n/// \\details BGL : https://www.boost.org/doc/libs/1_46_1/libs/graph/doc/adjacency_list.html\r\n///          Dijkstra :https://fr.wikipedia.org/wiki/Algorithme_de_Dijkstra\r\n///\r\n\r\n#include <cstdlib>\r\n#include <iostream>\r\n\r\n#include <boost/graph/graph_utility.hpp> // print_graph\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/properties.hpp>\r\n\r\nusing namespace std;\r\nusing namespace boost;\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// Définitions des types pour le graphe\r\n//-----------------------------------------------------------------------------\r\n\r\n///\r\n/// @brief Définition du type pour les noeuds graphe\r\n///\r\nstruct VertexProperties {\r\n    float d;\r\n    int predecessor;\r\n    VertexProperties() : d(std::numeric_limits<float>::infinity()), predecessor(-1) {}\r\n    VertexProperties(float d, int predecessor) : d(d), predecessor(-1) {}\r\n};\r\n\r\n///\r\n/// @brief Définition du type pour les liens graphe\r\n///\r\nstruct EdgeProperties {\r\n    int weight;\r\n    EdgeProperties() : weight(0) { }\r\n    EdgeProperties(int weight) : weight(weight) { }\r\n};\r\n\r\nstruct EdgeInfoPropertyTag {\r\n    typedef edge_property_tag kind;\r\n    static std::size_t const num; // ???\r\n};\r\n\r\nstd::size_t const EdgeInfoPropertyTag::num = (std::size_t)&EdgeInfoPropertyTag::num;\r\ntypedef property<EdgeInfoPropertyTag, EdgeProperties> edge_info_prop_type;\r\n\r\n///\r\n/// @brief Type de graphe\r\n///\r\ntypedef adjacency_list<\r\n    boost::vecS, boost::vecS, boost::undirectedS,\r\n    VertexProperties,                               // Type vertex\r\n    edge_info_prop_type                             // Type edge\r\n> Graph;\r\n\r\n//-----------------------------------------------------------------------------\r\n// En plus\r\n//-----------------------------------------------------------------------------\r\nvoid test(Graph &g) {\r\n    // Visiter les voisins du sommet 0\r\n    auto neighbours = boost::adjacent_vertices(0, g);\r\n    \r\n    for (auto vd : make_iterator_range(neighbours))\r\n        std::cout << \"0 has adjacent vertex \" << vd << \"\\n\";\r\n\r\n    g[0].d = 42;\r\n    cout<<g[0].d<<endl;\r\n\r\n    //cout<<edge(0,2,g).second<<endl;\r\n\r\n    EdgeProperties p = get(EdgeInfoPropertyTag(), g, edge(0,2,g).first);\r\n    std::cout << \"weight: \" << p.weight << std::endl;\r\n\r\n    get(EdgeInfoPropertyTag(), g, edge(0,2,g).first).weight = 33;\r\n    std::cout << \"weight: \" << get(EdgeInfoPropertyTag(), g, edge(0,2,g).first).weight << std::endl;\r\n    \r\n    // Nombre de sommets\r\n    cout<<num_vertices(g)<<endl;\r\n    cout<<num_edges(g)<<endl;\r\n\r\n    // Affiche le graphe\r\n    print_graph(g);\r\n\r\n}\r\n//-----------------------------------------------------------------------------\r\n// dijkstra\r\n//-----------------------------------------------------------------------------\r\n///\r\n/// @brief Crée une instance de graphe\r\n///\r\n/// \\param g : graphe\r\n///\r\nvoid createInstanceGraph(Graph &g) {\r\n    add_vertex(VertexProperties(std::numeric_limits<float>::infinity(), -1), g);\r\n    add_vertex(g);\r\n    add_vertex(g);\r\n    add_vertex(g);\r\n    add_vertex(g);\r\n\r\n    add_edge(0, 1, EdgeProperties(7), g);\r\n    add_edge(0, 2, EdgeProperties(9), g);\r\n    add_edge(0, 5, EdgeProperties(14), g);\r\n    add_edge(1, 3, EdgeProperties(15), g);\r\n    add_edge(1, 2, EdgeProperties(10), g);\r\n    add_edge(2, 3, EdgeProperties(11), g);\r\n    add_edge(2, 5, EdgeProperties(2), g);\r\n    add_edge(4, 3, EdgeProperties(6), g);\r\n    add_edge(5, 4, EdgeProperties(9), g);\r\n}\r\n\r\n///\r\n/// @brief donne le plus petit élément de la liste l\r\n///\r\n/// \\param g : graphe\r\n/// \\param l : liste de noeud\r\n///\r\n/// \\return le plus petit élément de la liste l\r\n///\r\nunsigned int extrait_min(Graph const &g, list<unsigned int> &l) {\r\n    list<unsigned int>::iterator iter = min_element(l.begin(), l.end());\r\n    l.erase(iter);\r\n    return *iter;\r\n}\r\n\r\n///\r\n/// @brief *\r\n///\r\n/// \\param u : *\r\n/// \\param v : *\r\n///\r\nvoid relacher(Graph &g, unsigned int u, unsigned int v) {\r\n    EdgeProperties p = get(EdgeInfoPropertyTag(), g, edge(u, v, g).first);\r\n    //std::cout << \"weight: \" << p.weight << std::endl;\r\n\r\n    if ((g[u].d + p.weight) < g[v].d ) {\r\n        g[v].d = g[u].d + p.weight;\r\n        g[v].predecessor = u;\r\n    }\r\n}\r\n\r\n///\r\n/// @brief algo de dijkstra\r\n///\r\n/// \\param g : graphe\r\n///\r\n/// \\return le plus court chemin\r\n///\r\nlist<unsigned int> dijkstra(Graph &g) {\r\n    g[0].d = 0;             // Sommet de début\r\n    list<unsigned int> F;   // liste des sommets à visiter\r\n    list<unsigned int> E;   // liste des sommets avec longueurs finales de plus court chemin à partir de l’origine s\r\n    for (unsigned int i = 0 ; i < num_vertices(g) ; i++)\r\n        F.push_back(i);\r\n\r\n    while (!F.empty()) {\r\n        unsigned int u = extrait_min(g, F);\r\n        E.push_back(u);\r\n\r\n        // Visite les voisins du sommet u\r\n        auto neighbours = boost::adjacent_vertices(u, g);\r\n        for (auto v : make_iterator_range(neighbours)) {\r\n            //std::cout << \"0 has adjacent vertex \" << v << \"\\n\";\r\n            relacher(g, u, v);\r\n        }\r\n    }\r\n\r\n\r\n    // Lecture du résultat\r\n    list<unsigned int> resultat;\r\n    int x = num_vertices(g) - 1;\r\n    resultat.push_back(x);\r\n    while (0 < x) {\r\n        x = g[x].predecessor;\r\n        resultat.push_back(x);\r\n    }\r\n\r\n    return resultat;\r\n}\r\n\r\nint main() {\r\n    // Crée un graphe g\r\n    Graph g;\r\n\r\n    // Crée une instance de graphe\r\n    createInstanceGraph(g);\r\n\r\n    // Affiche le graphe\r\n    cout<<\"[+] liste d'adjacence :\"<<endl;\r\n    print_graph(g);\r\n\r\n    // Appel de l'algo dijkstra\r\n    list<unsigned int> r = dijkstra(g);\r\n\r\n    // Affiche le plus court chemin\r\n    cout<<endl<<\"[+] le plus court chemin :\"<<endl;\r\n    for (auto v : r)\r\n        std::cout << v<<\" \";\r\n    cout<<endl;\r\n\r\n    return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "032885f06897a977490ed208e2f2f6d0125443a7", "size": 5906, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/dijkstra-bgl.cpp", "max_stars_repo_name": "jxtopher/quick-codes", "max_stars_repo_head_hexsha": "577711394f3f338c061f1e53df875d958c645071", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/dijkstra-bgl.cpp", "max_issues_repo_name": "jxtopher/quick-codes", "max_issues_repo_head_hexsha": "577711394f3f338c061f1e53df875d958c645071", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/dijkstra-bgl.cpp", "max_forks_repo_name": "jxtopher/quick-codes", "max_forks_repo_head_hexsha": "577711394f3f338c061f1e53df875d958c645071", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3942307692, "max_line_length": 117, "alphanum_fraction": 0.53826617, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.6859494550081926, "lm_q1q2_score": 0.4193771313829563}}
{"text": "/*\n\n * @file LinearInterpolationVectorSpaceCurve.hpp\n * @date Aug 17, 2014\n * @author Paul Furgale, Abel Gawel, Renaud Dube\n\n\n#include <curves/LinearInterpolationVectorSpaceCurve.hpp>\n#include <iostream>\n#include <boost/bind.hpp>\n#include <boost/function.hpp>\n\nnamespace curves {\n\ntemplate<int N>\nLinearInterpolationVectorSpaceCurve<N>::LinearInterpolationVectorSpaceCurve() : VectorSpaceCurve<N>() {}\n\ntemplate<int N>\nLinearInterpolationVectorSpaceCurve<N>::~LinearInterpolationVectorSpaceCurve() {}\n\ntemplate<int N>\nvoid LinearInterpolationVectorSpaceCurve<N>::print(const std::string& str) const {\n  std::cout << \"=========================================\" << std::endl;\n  std::cout << \"=======LINEAR INTERPOLATION CURVE========\" << std::endl;\n  std::cout << str << std::endl;\n  std::cout << \"number of coefficients: \" << manager_.size() << std::endl;\n  std::cout << \"dimension: \" << N << std::endl;\n  std::stringstream ss;\n  std::vector<Key> keys;\n  std::vector<Time> times;\n  manager_.getTimes(&times);\n  manager_.getKeys(&keys);\n  std::cout << \"curve defined between times: \" << manager_.getMinTime() <<\n      \" and \" << manager_.getMaxTime() <<std::endl;\n  std::cout <<\"=========================================\" <<std::endl;\n  for (size_t i = 0; i < manager_.size(); i++) {\n    ss << \"coefficient \" << keys[i] << \": \";\n    std::cout << ss.str() << manager_.getCoefficientByKey(keys[i]).transpose() << std::endl;\n    std::cout << \" | time: \" << times[i];\n    std::cout << std::endl;\n    ss.str(\"\");\n  }\n  std::cout <<\"=========================================\" <<std::endl;\n}\n\ntemplate<int N>\nTime LinearInterpolationVectorSpaceCurve<N>::getMaxTime() const {\n  return manager_.getMaxTime();\n}\n\ntemplate<int N>\nTime LinearInterpolationVectorSpaceCurve<N>::getMinTime() const {\n  return manager_.getMinTime();\n}\n\ntemplate<int N>\nvoid LinearInterpolationVectorSpaceCurve<N>::fitCurve(const std::vector<Time>& times,\n                                                      const std::vector<ValueType>& values,\n                                                      std::vector<Key>* outKeys) {\n  CHECK_EQ(times.size(), values.size());\n\n  if(times.size() > 0) {\n    manager_.clear();\n    if (outKeys != NULL) {\n      outKeys->clear();\n      outKeys->reserve(times.size());\n    }\n    std::vector<Coefficient> coefficients;\n    coefficients.reserve(times.size());\n    size_t vsize = values[0].size();\n    for(size_t i = 0; i < values.size(); ++i) {\n      CHECK_EQ(vsize, values[i].size()) << \"The vectors must be uniform length.\";\n      coefficients.push_back(Coefficient(values[i]));\n    }\n    manager_.insertCoefficients(times,coefficients,outKeys);\n  }\n}\n\ntemplate<int N>\nvoid LinearInterpolationVectorSpaceCurve<N>::extend(const std::vector<Time>& times,\n                                                    const std::vector<ValueType>& values,\n                                                    std::vector<Key>* outKeys) {\n\n  CHECK_EQ(times.size(), values.size()) << \"number of times and number of coefficients don't match\";\n  std::vector<Coefficient> coefficients(values.size());\n  for (size_t i = 0; i < values.size(); ++i) {\n    coefficients[i] = Coefficient(values[i]);\n  }\n  manager_.insertCoefficients(times, coefficients, outKeys);\n}\n\ntemplate<int N>\ntypename LinearInterpolationVectorSpaceCurve<N>::ValueType\nLinearInterpolationVectorSpaceCurve<N>::evaluate(Time time) const {\n  CoefficientIter rval0, rval1;\n  bool success = manager_.getCoefficientsAt(time, &rval0, &rval1);\n  CHECK(success) << \"Unable to get the coefficients at time \" << time;\n\n  Time dt = rval1->first - rval0->first;\n  Time t = rval1->first - time;\n  // Alpha goes from zero to one.\n  double alpha = double(t)/double(dt);\n\n  return alpha * rval0->second.coefficient + (1.0 - alpha) * rval1->second.coefficient;\n}\n\ntemplate<int N>\ntypename LinearInterpolationVectorSpaceCurve<N>::DerivativeType\nLinearInterpolationVectorSpaceCurve<N>::evaluateDerivative(Time time,\n                                                           unsigned derivativeOrder) const {\n\n  // time is out of bound --> error\n  CHECK_GE(time, this->getMinTime()) << \"Time out of bounds\";\n  CHECK_LT(time, this->getMaxTime()) << \"Time out of bounds\";\n  CHECK_GT(derivativeOrder, 0) << \"DerivativeOrder must be greater than 0\";\n\n  typename LinearInterpolationVectorSpaceCurve<N>::DerivativeType dCoeff;\n  Time dt;\n  CoefficientIter rval0, rval1;\n  bool success = manager_.getCoefficientsAt(time, &rval0, &rval1);\n  CHECK(success) << \"Unable to get the coefficients at time \" << time;\n  // first derivative\n  if (derivativeOrder == 1) {\n    dCoeff = rval1->second.coefficient - rval0->second.coefficient;\n    dt = rval1->first - rval0->first;\n    return dCoeff/dt;\n  } else { // order of derivative > 1 returns vector of zeros\n    dCoeff.Zero();\n    return dCoeff;\n  }\n}\n\n// Evaluation function in functional form. To be passed to the expression\ntemplate<int N>\nEigen::Matrix<double,N,1> linearInterpolation(Eigen::Matrix<double,N,1>  v1,\n                                              Eigen::Matrix<double,N,1>  v2, double alpha,\n                                              gtsam::OptionalJacobian<N,N> H1,\n                                              gtsam::OptionalJacobian<N,N> H2) {\n  if (H1) { *H1 = Eigen::Matrix<double,N,N>::Identity()*(1-alpha); }\n  if (H2) { *H2 = Eigen::Matrix<double,N,N>::Identity()*alpha; }\n\n  return v1*(1-alpha) + v2*alpha;\n}\n\ntemplate<int N>\ngtsam::Expression<typename LinearInterpolationVectorSpaceCurve<N>::ValueType>\nLinearInterpolationVectorSpaceCurve<N>::getValueExpression(const Time& time) const {\n  typedef typename LinearInterpolationVectorSpaceCurve<N>::ValueType ValueType;\n  using namespace gtsam;\n  CoefficientIter rval0, rval1;\n  bool success = manager_.getCoefficientsAt(time, &rval0, &rval1);\n  CHECK(success) << \"Unable to get the coefficients at time \" << time;\n\n  Expression<ValueType> leaf1(rval0->second.key);\n  Expression<ValueType> leaf2(rval1->second.key);\n\n  double alpha = double(time - rval0->first)/double(rval1->first - rval0->first);\n\n  Expression<ValueType> rval(boost::bind(&linearInterpolation<N>, _1, _2, alpha, _3, _4),\n                             leaf1, leaf2);\n\n  return rval;\n}\n\ntemplate<int N>\ngtsam::Expression<typename LinearInterpolationVectorSpaceCurve<N>::DerivativeType>\nLinearInterpolationVectorSpaceCurve<N>::getDerivativeExpression(const Time& time, unsigned derivativeOrder) const {\n  // \\todo Abel and Renaud\n  CHECK(false) << \"Not implemented\";\n}\n\ntemplate<int N>\nvoid LinearInterpolationVectorSpaceCurve<N>::initializeGTSAMValues(gtsam::KeySet keys, gtsam::Values* values) const {\n  manager_.initializeGTSAMValues(keys, values);\n}\n\ntemplate<int N>\nvoid LinearInterpolationVectorSpaceCurve<N>::initializeGTSAMValues(gtsam::Values* values) const {\n  manager_.initializeGTSAMValues(values);\n}\n\ntemplate<int N>\nvoid LinearInterpolationVectorSpaceCurve<N>::updateFromGTSAMValues(const gtsam::Values& values) {\n  manager_.updateFromGTSAMValues(values);\n}\n\ntemplate<int N>\nvoid LinearInterpolationVectorSpaceCurve<N>::clear() {\n  manager_.clear();\n}\n\ntemplate<int N>\nvoid LinearInterpolationVectorSpaceCurve<N>::addPriorFactors(gtsam::NonlinearFactorGraph* graph, Time priorTime) const {\n  gtsam::noiseModel::Constrained::shared_ptr priorNoise = gtsam::noiseModel::Constrained::All(gtsam::traits<Coefficient>::dimension);\n\n  // Constraint the coefficients which influence the curve value at priorTime\n  CoefficientIter rVal0, rVal1;\n  manager_.getCoefficientsAt(priorTime, &rVal0, &rVal1);\n\n  gtsam::ExpressionFactor<Coefficient> factor0(priorNoise,\n                                          rVal0->second.coefficient,\n                                          gtsam::Expression<Coefficient>(rVal0->second.key));\n  gtsam::ExpressionFactor<Coefficient> factor1(priorNoise,\n                                          rVal1->second.coefficient,\n                                          gtsam::Expression<Coefficient>(rVal1->second.key));\n  graph->push_back(factor0);\n  graph->push_back(factor1);\n}\n\ntemplate<int N>\nvoid LinearInterpolationVectorSpaceCurve<N>::transformCurve(const ValueType T) {\n  //todo\n}\n\ntemplate<int N>\nTime LinearInterpolationVectorSpaceCurve<N>::getTimeAtKey(gtsam::Key key) const {\n  return manager_.getCoefficientTimeByKey(key);\n}\n\n} // namespace curves\n*/\n", "meta": {"hexsha": "60809e6aa8db41b8bed304022afbf7a864550133", "size": 8311, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "curves/include/curves/LinearInterpolationVectorSpaceCurve-inl.hpp", "max_stars_repo_name": "leggedrobotics/curves", "max_stars_repo_head_hexsha": "696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 66.0, "max_stars_repo_stars_event_min_datetime": "2017-03-07T06:22:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T08:27:03.000Z", "max_issues_repo_path": "curves/include/curves/LinearInterpolationVectorSpaceCurve-inl.hpp", "max_issues_repo_name": "leggedrobotics/curves", "max_issues_repo_head_hexsha": "696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2017-01-26T15:07:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-05T10:24:17.000Z", "max_forks_repo_path": "curves/include/curves/LinearInterpolationVectorSpaceCurve-inl.hpp", "max_forks_repo_name": "leggedrobotics/curves", "max_forks_repo_head_hexsha": "696db3e9ecf67c143e7b48a8dd53d2c5ea1ba2fe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2017-01-29T02:18:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T12:35:08.000Z", "avg_line_length": 37.4369369369, "max_line_length": 133, "alphanum_fraction": 0.6600890386, "num_tokens": 2039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4192687440390793}}
{"text": "/* Computes the joint distribution over all the latent variables in the model using Gibbs Sampling.\n *\n * This latent variable model adapted from the one described in \"Learning an Input Filter for\n * Argument Structure Acquisition\" by Perkins, Feldman, and Lidz. See the paper for details.\n */\n\n#include \"metropolis_hastings.hpp\"\n#include \"sample_models.hpp\"\n#include \"utils.hpp\"\n\n#include <CLI/CLI.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/log/core.hpp>\n#include <boost/log/expressions.hpp>\n#include <boost/log/trivial.hpp>\n#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <string>\n#include <tuple>\n#include <utility>\n\nusing namespace FilterModel;\nnamespace logging = boost::log;\n\n/**\n * Jointly inferrs the alpha vector of each object, the epsilon, and the delta value for some\n * objects by using a fixed number of iterations of gibbs sampling.\n *\n * The sampling uses the following flow:\n *   alpha -> epsilon -> delta.\n *\n * This function takes as input a vector of category count vectors of each object and the number of\n * iterations or time steps to sample over.\n *\n * This function outputs a tuple of three vectors. The first vector contains the sampled\n * alpha of each object in the data at each time step. So the first element of outer vector\n * is a vector of alphas sampled at the first time step, the second element is the\n * alphas at the second time step, etc. The second and third vectors are the sampled epsilon\n * and delta values at each time step respectively.\n */\nstd::tuple<std::vector<std::vector<alpha_t>>, std::vector<double>, std::vector<delta_t>,\n           std::vector<double>>\njoint_inference(std::vector<category_counts_t> &data, int iterations,\n                std::function<void(std::vector<std::vector<alpha_t>>, std::vector<double>,\n                                   std::vector<delta_t>, std::vector<double>)>\n                    write_batch,\n                int batch_size, Options options) {\n    BOOST_LOG_TRIVIAL(info) << \"Starting Gibbs Sampling\";\n\n    int n_categories = 0;\n    if (data.size() > 0) {\n        n_categories = data.at(0).size();\n    }\n\n    std::default_random_engine generator;\n    generator.seed(std::chrono::system_clock::now().time_since_epoch().count());\n\n    std::uniform_real_distribution<double> parameter_distribution(0.0, 1.0);\n    std::vector<double> epsilons = {parameter_distribution(generator)};\n    std::vector<delta_t> deltas = {\n        sample_symmetric_simplex(parameter_distribution, generator, n_categories)};\n    // Each item contains a vector of the estimated alpha of each object at each timestep.\n    std::vector<std::vector<alpha_t>> models;\n    models.push_back(std::vector<alpha_t>());\n\n    ModelDistribution model_distribution(data, generator, options);\n    ModelSampler sampler(data, generator, options);\n\n    std::vector<double> log_likelyhoods;\n\n    for (int iteration = 1; iteration <= iterations; ++iteration) {\n        BOOST_LOG_TRIVIAL(info) << \"Iteration \" << iteration;\n\n        if (options.fixed_alphas.empty()) {\n            std::vector<alpha_t> new_models =\n                sampler.sample(epsilons.at(iteration - 1), deltas.at(iteration - 1));\n            models.push_back(new_models);\n        } else {\n            models.push_back(options.fixed_alphas);\n        }\n\n        epsilons.push_back(MetropolisHastingsSampler::sample<double, std::default_random_engine>(\n            10,  // Iterations\n            [delta = deltas.at(iteration - 1), model = models.at(iteration),\n             model_distribution](double epsilon) {\n                std::vector<std::vector<alpha_t>> alphas_per_object(model.size());\n                for (int i = 0; i < alphas_per_object.size(); ++i) {\n                    alphas_per_object.at(i) = std::vector<alpha_t>(1, model.at(i));\n                }\n                std::vector<std::vector<double>> log_alpha_likelyhoods_per_object =\n                    model_distribution.distribution(alphas_per_object, epsilon, delta);\n                std::vector<double> log_alpha_likelyhoods(log_alpha_likelyhoods_per_object.size());\n                std::transform(log_alpha_likelyhoods_per_object.begin(),\n                               log_alpha_likelyhoods_per_object.end(),\n                               log_alpha_likelyhoods.begin(),\n                               [](std::vector<double> v) { return v[0]; });\n\n                return std::accumulate(log_alpha_likelyhoods.begin(), log_alpha_likelyhoods.end(),\n                                       0.0);\n            },  // log_pdf\n            [&parameter_distribution](std::default_random_engine &generator) {\n                return parameter_distribution(generator);\n            },  // uniform_sampler\n            [](double center, std::default_random_engine &generator) {\n                std::normal_distribution<> dist(center, 0.25);\n                return sample_probability(dist, generator);\n            },  // conditional_sampler\n            generator));\n\n        deltas.push_back(MetropolisHastingsSampler::sample<delta_t, std::default_random_engine>(\n            10,  // Iterations\n            [epsilon = epsilons.at(iteration), model = models.at(iteration),\n             model_distribution](delta_t delta) {\n                std::vector<std::vector<alpha_t>> alphas_per_object(model.size());\n                for (int i = 0; i < alphas_per_object.size(); ++i) {\n                    alphas_per_object.at(i) = std::vector<alpha_t>(1, model.at(i));\n                }\n                std::vector<std::vector<double>> log_alpha_likelyhoods_per_object =\n                    model_distribution.distribution(alphas_per_object, epsilon, delta);\n                std::vector<double> log_alpha_likelyhoods =\n                    flatten<double>(log_alpha_likelyhoods_per_object);\n\n                return accumulate(log_alpha_likelyhoods.begin(), log_alpha_likelyhoods.end(), 0.0);\n            },  // log_pdf\n            [parameter_distribution, n_categories](std::default_random_engine &generator) {\n                return sample_symmetric_simplex(parameter_distribution, generator, n_categories);\n            },  // uniform_sampler\n            [](delta_t center, std::default_random_engine &generator) {\n                return sample_gaussian_simplex<>(center, 0.25, generator);\n            },  // Conditional sampler\n            generator));\n\n        if (options.record_likelyhood) {\n            std::vector<double> log_likelyhood_per_object =\n                flatten<double>(model_distribution.distribution(\n                    models.at(iteration), epsilons.at(iteration), deltas.at(iteration)));\n            log_likelyhoods.push_back(std::accumulate(log_likelyhood_per_object.begin(),\n                                                      log_likelyhood_per_object.end(), 0.0));\n        }\n\n        if (iteration % batch_size == batch_size - 1 || iteration == iterations) {\n            int batch = iteration / batch_size + 1;\n            int start_index = (batch - 1) * batch_size;\n            int end_index = std::min(batch * batch_size, iterations + 1);\n\n            std::vector<std::vector<alpha_t>> alpha_batch(models.begin() + start_index,\n                                                          models.begin() + end_index);\n            std::vector<double> epsilon_batch(epsilons.begin() + start_index,\n                                              epsilons.begin() + end_index);\n            std::vector<delta_t> delta_batch(deltas.begin() + start_index,\n                                             deltas.begin() + end_index);\n            std::vector<double> log_likelyhood_batch;\n            if (options.record_likelyhood) {\n                log_likelyhood_batch = std::vector<double>(log_likelyhoods.begin() + start_index,\n                                                           log_likelyhoods.begin() + end_index);\n            }\n\n            write_batch(alpha_batch, epsilon_batch, delta_batch, log_likelyhood_batch);\n        }\n    }\n\n    return std::make_tuple(models, epsilons, deltas, log_likelyhoods);\n}\n\n/**\n * Reads in a csv file of category_count_t objects in order.\n * See category_count_t in types.hpp for details.\n * Expects a header line.\n */\nstd::vector<category_counts_t> read_category_counts_file(std::string in_path) {\n    std::ifstream in_file(in_path);\n    std::string line;\n    std::vector<category_counts_t> data;\n    if (in_file.is_open()) {\n        // Trim the header line\n        getline(in_file, line);\n        while (getline(in_file, line)) {\n            std::vector<std::string> items;\n            boost::split(items, line, boost::is_any_of(\",\"));\n            category_counts_t datum = {std::stoi(items.at(1)), std::stoi(items.at(2)),\n                                       std::stoi(items.at(3))};\n            data.push_back(datum);\n        }\n        in_file.close();\n    } else {\n        BOOST_LOG_TRIVIAL(fatal) << \"File \" << in_path << \" not found.\";\n        assert(false);\n    }\n\n    return data;\n}\n\nstd::vector<alpha_t> read_alphas(std::string alpha_path) {\n    std::ifstream in_file(alpha_path);\n    std::string line;\n    std::vector<alpha_t> alphas;\n    if (in_file.is_open()) {\n        // Trim the header line\n        getline(in_file, line);\n        while (getline(in_file, line)) {\n            std::vector<std::string> items;\n            boost::split(items, line, boost::is_any_of(\",\"));\n            alpha_t alpha = {bool(std::stoi(items.at(1))), bool(std::stoi(items.at(2))),\n                             bool(std::stoi(items.at(3)))};\n            alphas.push_back(alpha);\n        }\n        in_file.close();\n    } else {\n        BOOST_LOG_TRIVIAL(fatal) << \"File \" << alpha_path << \" not found.\";\n        assert(false);\n    }\n\n    return alphas;\n}\n\nstd::ofstream setup_output(std::string out_path) {\n    return std::ofstream(out_path, std::ios::out | std::ios::trunc);\n}\n\n/**\n * Sets the current logging level.\n */\nvoid initLogging() {\n    logging::core::get()->set_filter(logging::trivial::severity >= logging::trivial::info);\n}\n\nint main(int argc, char *const *argv) {\n    initLogging();\n\n    // Setting up command line flags.\n    CLI::App app{\"Input Filter Model\"};\n\n    std::string in_path = \"input.csv\";\n    app.add_option(\"-i,--in\", in_path,\n                   \"The path to a csv file containing pairs of direct object and object counts.\")\n        ->required();\n\n    std::string out_path = \"output.csv\";\n    app.add_option(\"-o,--output\", out_path, \"The path of the output file.\")->required();\n\n    int iterations = 1;\n    app.add_option(\"--iterations\", iterations,\n                   \"The number of iterations to run Gibbs sampling for.\");\n\n    std::string alpha_path;\n    CLI::Option *alpha_path_option = app.add_option(\n        \"--alpha-path\", alpha_path, \"Path to fixed alpha values to use, only if provided.\");\n\n    std::string message;\n    CLI::Option *message_option =\n        app.add_option(\"-m, --message\", message, \"Message to be written at the top of the output.\")\n            ->required();\n\n    bool record_likelyhood = false;\n    CLI::Option *record_likelyhood_flag =\n        app.add_flag(\"--record-likelyhood\", record_likelyhood,\n                     \"Additionally record the likelyhood of the sampled parameters.\");\n\n    bool exact = false;\n    CLI::Option *exact_flag =\n        app.add_flag(\"--exact\", exact, \"Prevent approximations in calcualtion.\");\n\n    bool comparison = false;\n    app.add_flag(\"--comparison\", comparison,\n                 \"If both integration methods shosuld be used and compared.\")\n        ->excludes(exact_flag);\n\n    bool use_smaller_alphas = false;\n    CLI::Option *use_smaller_alphas_flag = app.add_flag(\"--use-smaller-alphas\", use_smaller_alphas,\n                                                        \"Only consider alphas that are possible.\")\n                                               ->excludes(alpha_path_option);\n\n    CLI11_PARSE(app, argc, argv);\n\n    std::vector<alpha_t> alphas;\n    if (!alpha_path.empty()) {\n        alphas = read_alphas(alpha_path);\n    }\n\n    Options options;\n    options.comparison = comparison;\n    options.exact = exact;\n    options.use_smaller_alphas = use_smaller_alphas;\n    options.record_likelyhood = record_likelyhood;\n    options.fixed_alphas = alphas;\n\n    auto data = read_category_counts_file(in_path);\n\n    std::ofstream out_file = setup_output(out_path);\n\n    out_file << \"Comment: \" << message << \", Input path: \" << in_path\n             << \", Output path: \" << out_path << \", Alpha path: \" << alpha_path\n             << \", Iterations: \" << std::to_string(iterations)\n             << \", Comparison: \" << std::to_string(options.comparison)\n             << \", Exact: \" << std::to_string(options.exact)\n             << \", Use smaller alphas: \" << std::to_string(options.use_smaller_alphas)\n             << \", Record likelyhood: \" << std::to_string(options.record_likelyhood) << std::endl;\n\n    auto write_batch = [&out_file](std::vector<std::vector<alpha_t>> alpha_batch,\n                                   std::vector<double> epsilon_batch,\n                                   std::vector<delta_t> delta_batch,\n                                   std::vector<double> log_likelyhood_batch) {\n        for (int i = 0; i < alpha_batch.size(); ++i) {\n            if (!log_likelyhood_batch.empty()) {\n                out_file << vector_of_vector_to_string<>(alpha_batch.at(i)) << \",\"\n                         << epsilon_batch.at(i) << \",\" << vector_to_string<>(delta_batch.at(i))\n                         << \",\" << log_likelyhood_batch.at(i) << std::endl;\n            } else {\n                out_file << vector_of_vector_to_string<>(alpha_batch.at(i)) << \",\"\n                         << epsilon_batch.at(i) << \",\" << vector_to_string<>(delta_batch.at(i))\n                         << std::endl;\n            }\n        }\n    };\n\n    joint_inference(data, iterations, write_batch, 100, options);\n\n    BOOST_LOG_TRIVIAL(info) << \"Inference complete.\";\n\n    out_file.close();\n}\n", "meta": {"hexsha": "ddb8a1e3dfabc3e7bc748ed7c9c48b61d82527ef", "size": 13931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/joint_distribution.cpp", "max_stars_repo_name": "skinnersBoxy/input-filter", "max_stars_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/joint_distribution.cpp", "max_issues_repo_name": "skinnersBoxy/input-filter", "max_issues_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/joint_distribution.cpp", "max_forks_repo_name": "skinnersBoxy/input-filter", "max_forks_repo_head_hexsha": "6528b6dc094c59ac6d28a24016d0c42de495d313", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9969135802, "max_line_length": 99, "alphanum_fraction": 0.6041920896, "num_tokens": 3039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.63341027059799, "lm_q1q2_score": 0.41926873945847387}}
{"text": "/*\narg min Sum_i Ei(Ri)\n  s.t. ~Ri Ri = 1\n\nEi = Sum_j wij |Ri qji ~Ri - pji|^2 + A Sum_j cij |Ri - Rj|^2 + ei |Ri - R_{i-1}|^2\n\nwhere:  Sum_j wij = 1    and     ei + Sum_j cij = 1\n\nEi = Sum_j wij |Ri qji - pji Ri|^2 + A Sum_j cij |Ri - Rj|^2 + ei |Ri - R_{i-1}|^2\n\nSince: Sum_j wij |Ri qji - pji Ri|^2 = Ri^T Hi Ri\n\nEi = Ri^T Hi Ri + A Sum_j cij |Ri - Rj|^2 + ei |Ri - R_{i-1}|^2\n\ndEi/Ri = 2 Hi Ri + 2 A sum_j(cij Ri - Rj) + 2 ei (Ri - R_{i-1})\ndEi/Ri = Hi Ri + A sum_j(cij Ri) - A sum_j(cij Rj) + ei Ri - ei R_{i-1}\ndEi/Ri = Hi Ri + A Ri sum_j(cij) - A sum_j(cij Rj) + ei Ri - ei R_{i-1}\ndEi/Ri = (Hi + A sum_j(cij) I + ei I) Ri - sum_j(A cij Rj) - ei R_{i-1}\n\nSetting dEi/Ri = 0\n\n(Hi + A sum_j(cij) I + ei I) Ri - sum_j(A cij Rj) - ei R_{i-1} = 0\n\nSetting Mi = Hi + (A sum_j(cij) + ei) I\n\nAnd imposing: sum_j(cij) + ei = 1\n\nMi = Hi + A I\n\nMi Ri = sum_j(A cij Rj) + ei R_{i-1}\n\nM R = L R + ei R_prev\n\nWhere \n   M is stacking Mi at the diagonal\n   L is laplacian matrix from sum_j(A cij Rj)\n   R_prev is stacking feedback R_{i-1}\n\nSolve (M - L) R = ei R_prev\ns.t R = R_const,  at the constrained points.\n*/\n#ifdef WIN32\n#define NOMINMAX\n#include <windows.h>\n#endif\n\n#if defined (__APPLE__) || defined (OSX)\n#include <OpenGL/gl.h>\n#include <GLUT/glut.h>\n#else\n#include <GL/gl.h>\n#include <GL/glut.h>\n#endif\n\n#include \"GA/c3ga.h\"\n#include \"GA/c3ga_util.h\"\n#include \"GA/gl_util.h\"\n\n#include \"primitivedraw.h\"\n#include \"gahelper.h\"\n#include \"Laplacian.h\"\n\n#include <memory>\n\n#include <vector>\n#include <queue>\n#include <map>\n#include \"numerics.h\"\n#include \"HalfEdge/Mesh.h\"\n#include \"GARotorEstimator.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/Geometry>\n\n// #include <ppl.h>\n\n#include \"Benchs.h\"\n\nconst char *WINDOW_TITLE = \"Interactive 3D Shape Deformation using Conformal Geometric Algebra\";\n\n// GLUT state information\nint g_viewportWidth = 800;\nint g_viewportHeight = 600;\n\nvoid display();\nvoid reshape(GLint width, GLint height);\nvoid MouseButton(int button, int state, int x, int y);\nvoid MouseMotion(int x, int y);\nvoid KeyboardUpFunc(unsigned char key, int x, int y);\nvoid SpecialFunc(int key, int x, int y);\nvoid SpecialUpFunc(int key, int x, int y);\nvoid Idle();\nvoid DestroyWindow();\n\n//using namespace boost;\nusing namespace c3ga;\nusing namespace std;\nusing namespace numerics;\n\nclass Camera\n{\npublic:\n\tfloat\t\tpos[3];\n\tfloat\t\tfw[3];\n\tfloat\t\tup[3];\n\tfloat\t\ttranslateVel;\n\tfloat\t\trotateVel;\n\n\tCamera()\n\t{\n\t\tfloat\t\t_pos[] = { 0, 0, -2};\n\t\tfloat\t\t_fw[] = { 0, 0, 1 };\n\t\tfloat\t\t_up[] = { 0, 1, 0 };\n\n\t\ttranslateVel = 0.005;\n\t\trotateVel = 0.005;\n\t\tmemcpy(pos, _pos, sizeof(float)*3);\n\t\tmemcpy(fw, _fw, sizeof(float)*3);\n\t\tmemcpy(up, _up, sizeof(float)*3);\n\t}\n\n\tvoid glLookAt()\n\t{\n\t\tgluLookAt( pos[0], pos[1], pos[2], fw[0],  fw[1],  fw[2], up[0],  up[1],  up[2] );\n\t}\n};\n\nclass VertexBuffer\n{\npublic:\n\tstd::vector<Eigen::Vector3d> deformedPositions; //deformed mesh positions\n\tstd::map<int, Eigen::Vector3d> constrainedPositions; //positional constraints\n\tstd::vector<Eigen::Vector3d> laplacianCoordinates; //laplacian Coordinates\n\tstd::vector<Eigen::Vector3d> normals; //for rendering (lighting)\n\tstd::vector<Eigen::Vector3d> normalsOrig; //original normals\n\tstd::vector<Eigen::Quaterniond> rotors;\n\tint size;\n\n\tVertexBuffer() : size(0)\n\t{\n\t}\n\n\tvoid resize(int size)\n\t{\n\t\tthis->size = size;\n\t\tdeformedPositions.resize(size);\n\t\tlaplacianCoordinates.resize(size);\n\t\tnormals.resize(size);\n\t\tnormalsOrig.resize(size);\n\t\trotors.resize(size);\n\t}\n\tint get_size() { return size; }\n\n};\n\nclass IndexBuffer {\npublic:\n\tstd::vector<int> faces;\n\tint size;\n\n\tIndexBuffer() : size(0)\n\t{\n\t}\n\n\tvoid resize(int size)\n\t{\n\t\tthis->size = size;\n\t\tfaces.resize(size);\n\t}\n\tint get_size() { return size; }\n\n};\n\nclass Handle\n{\npublic:\n\trotor R;\n\ttranslator T;\n\ttranslator Tcenter;\n\tdualSphere dS;\n\tstd::set<int> constraints;\n\n\tHandle() {\n\t\tT = _rotor(1.0);\n\t\tR = _translator(1.0);\n\t\tTcenter = _translator(1.0);\n\t}\n\tHandle(dualSphere dS)\n\t{\n\t\tnormalizedPoint x = DualSphereCenter(dS);\n\t\tTcenter = exp(-0.5 * _vectorE3GA(x) * ni);\n\t\tT = _translator(1.0);\n\t\tR = _rotor(1.0);\n\t\tthis->dS = dS;\n\t}\n\n\tTRversor GetTRVersor()\n\t{\n\t\treturn _TRversor(T * _TRversor(Tcenter * R * inverse(Tcenter)));\n\t}\n};\n\nCamera g_camera;\nMesh mesh, meshLow;\nmap<int, int> mapping;\nvectorE3GA g_prevMousePos;\nbool g_rotateModel = false;\nbool g_rotateModelOutOfPlane = false;\nrotor g_modelRotor = _rotor(1.0);\nbool g_rotateKeyRotors = false;\nbool g_translateKeyRotors = false;\nbool g_computeBasis = false;\nfloat g_dragDistance = -1.0f;\nint g_dragObject;\nstd::shared_ptr<SparseMatrix> A;\nstd::shared_ptr<SparseMatrix> AHi;\nEigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> solverLow, solverHi;\nEigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> solverRotations;\nEigen::SparseMatrix<double> RotationMatrix;\nvector<Eigen::Triplet<double>> triplets;\nint systemType = LaplaceBeltrami; //MeanValue; //LaplaceBeltrami\nbool g_showSpheres = true;\nbool g_showWires = false;\nbool g_iterateManyTimes = false;\nEigen::MatrixXd b3Low;\nEigen::MatrixXd xyzLow;\nEigen::MatrixXd b3Hi;\nEigen::MatrixXd xyzHi;\nEigen::VectorXd Rknown;\nEigen::MatrixXd RknownHi;\nEigen::MatrixXd RbestHi;\n\ndouble g_meshArea = 0.0;\n\nbool g_automaticAnimation = false;\nbool g_convergence = false;\nBenchmarks benchs;\n\nVertexBuffer vertexDescriptors;\nVertexBuffer vertexDescriptorsLow;\nIndexBuffer trianglesHi;\nstd::vector<Handle> handles;\nstd::set<int> allconstraints;\n\nEigen::Affine3d MotorToMatrix(const TRversor& R) {\n\tTRversor Ri = inverse(R);\n\n\t// compute images of basis vectors:\n\tc3ga::flatPoint imageOfE1NI = _flatPoint(R * c3ga::e1ni * Ri);\n\tc3ga::flatPoint imageOfE2NI = _flatPoint(R * c3ga::e2ni * Ri);\n\tc3ga::flatPoint imageOfE3NI = _flatPoint(R * c3ga::e3ni * Ri);\n\tc3ga::flatPoint imageOfNONI = _flatPoint(R * c3ga::noni * Ri);\n\n\t// create matrix representation:\n\tEigen::Affine3d M;\n\tM(0, 0) = imageOfE1NI.m_c[0];\n\tM(1, 0) = imageOfE1NI.m_c[1];\n\tM(2, 0) = imageOfE1NI.m_c[2];\n\tM(3, 0) = imageOfE1NI.m_c[3];\n\tM(0, 1) = imageOfE2NI.m_c[0];\n\tM(1, 1) = imageOfE2NI.m_c[1];\n\tM(2, 1) = imageOfE2NI.m_c[2];\n\tM(3, 1) = imageOfE2NI.m_c[3];\n\tM(0, 2) = imageOfE3NI.m_c[0];\n\tM(1, 2) = imageOfE3NI.m_c[1];\n\tM(2, 2) = imageOfE3NI.m_c[2];\n\tM(3, 2) = imageOfE3NI.m_c[3];\n\tM(0, 3) = imageOfNONI.m_c[0];\n\tM(1, 3) = imageOfNONI.m_c[1];\n\tM(2, 3) = imageOfNONI.m_c[2];\n\tM(3, 3) = imageOfNONI.m_c[3];\n\treturn M;\n}\n\nvoid ComputeLaplacianCoordinates(std::shared_ptr<SparseMatrix> A, Mesh* mesh, std::vector<Eigen::Vector3d>& laplacianCoordinates)\n{\n\tstd::fill(laplacianCoordinates.begin(), laplacianCoordinates.end(), Eigen::Vector3d(0, 0, 0));\n\n\tauto numRows = A->numRows();\n\n\tfor (int i = 0; i < numRows; ++i)\n\t{\n\t\tSparseMatrix::RowIterator aIter = A->iterator(i);\n\t\tfor (; !aIter.end(); ++aIter)\n\t\t{\n\t\t\tauto j = aIter.columnIndex();\n\t\t\tlaplacianCoordinates[i] += mesh->vertexAt(j).p * aIter.value();\n\t\t}\n\t}\n}\n\nbool is_constrained(std::set<int>& constraints, int vertex)\n{\n\treturn constraints.find(vertex) != constraints.end();\n}\n\nvoid PreFactor(std::shared_ptr<SparseMatrix> A, std::set<int>& constraints, Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>>& solver)\n{\n\n\tEigen::SparseMatrix<double> Lc = Eigen::SparseMatrix<double>(A->numRows(), A->numColumns());\n\n\tauto numRows = A->numRows();\n\tfor (int i = 0; i < numRows; ++i)\n\t{\n\t\tif (!is_constrained(constraints, i))\n\t\t{\n\t\t\tSparseMatrix::RowIterator aIter = A->iterator(i);\n\t\t\tfor (; !aIter.end(); ++aIter)\n\t\t\t{\n\t\t\t\tauto j = aIter.columnIndex();\n\t\t\t\tLc.insert(i, j) = (*A)(i, j);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLc.insert(i, i) = 1.0;\n\t\t}\n\t}\n\n\tLc.makeCompressed();\n\tsolver.compute(Lc);\n\tif (solver.info() != Eigen::Success) {\n\t\t// TODO: error handling\n\t}\n\n}\n\ndouble meshArea(Mesh *mesh)\n{\n\tdouble area = 0.0;\n\tfor(Face& face :  mesh->getFaces())\n\t{\n\t\tEigen::Vector3d\tu = face.edge->next->vertex->p - face.edge->vertex->p;\n\t\tEigen::Vector3d\tv = face.edge->next->next->vertex->p - face.edge->vertex->p;\n\t\tarea += 0.5 * u.cross(v).norm();\n\t}\n\treturn area;\n}\n\nvoid meshMapping(Mesh *meshLow, Mesh *mesh, map<int, int>& mapping)\n{\n\tfor (Vertex& vertexLow : meshLow->getVertices())\n\t{\n\t\tdouble minDist = 1e38;\n\t\tint mappedPoint = -1;\n\t\tEigen::Vector3d& pLow = vertexLow.p;\n\t\tfor (Vertex& vertexHi : mesh->getVertices())\n\t\t{\n\t\t\tEigen::Vector3d& p = vertexHi.p;\n\t\t\tdouble dist = (pLow - p).norm();\n\t\t\tif (dist < minDist) {\n\t\t\t\tminDist = dist;\n\t\t\t\tmappedPoint = vertexHi.ID;\n\t\t\t}\n\t\t}\n\t\tmapping[vertexLow.ID] = mappedPoint;\n\t}\n}\n\nint main(int argc, char* argv[])\n{\n\tmesh.readOBJ(\"cactus2.obj\"); //cactus2.obj  armadillo.obj\n\tmesh.CenterAndNormalize();\n\tmesh.computeNormals();\n\n\tmeshLow.readOBJ(\"cactus1.obj\"); //cactus1.obj armadillo1.obj\n\tmeshLow.CenterAndNormalize();\n\tmeshLow.computeNormals();\n\n\tmeshMapping(&meshLow, &mesh, mapping);\n\n\t// GLUT Window Initialization:\n\tglutInit (&argc, argv);\n\tglutInitWindowSize(g_viewportWidth, g_viewportHeight);\n\tglutInitDisplayMode( GLUT_RGB | GLUT_ALPHA | GLUT_DOUBLE | GLUT_DEPTH);\n\tglutCreateWindow(WINDOW_TITLE);\n\n\t// Register callbacks:\n\tglutDisplayFunc(display);\n\tglutReshapeFunc(reshape);\n\tglutMouseFunc(MouseButton);\n\tglutMotionFunc(MouseMotion);\n\tglutKeyboardUpFunc(KeyboardUpFunc);\n\tglutSpecialFunc(SpecialFunc);\n\tglutSpecialUpFunc(SpecialUpFunc);\n\tglutIdleFunc(Idle);\n\tatexit(DestroyWindow);\n\n\tInitializeDrawing();\n\n\t//cactus.obj\n\thandles.push_back(Handle(_dualSphere(c3gaPoint(.0, .04, 0.7) - 0.5*SQR(0.15)*ni)));\n\thandles.push_back(Handle(_dualSphere(c3gaPoint(.0, .04, -0.8) - 0.5*SQR(0.15)*ni)));\n\n\t////cylinder.obj\n\t//handles.push_back(Handle(_dualSphere(c3gaPoint(.0, 0.9, .0) - 0.5*SQR(0.25)*ni)));\n\t//handles.push_back(Handle(_dualSphere(c3gaPoint(.0, -0.9, .0) - 0.5*SQR(0.25)*ni)));\n\n\t// //Armadillo foot and hand\n\t// handles.push_back(Handle(_dualSphere(c3gaPoint(-.5, 0.45, -.3) - 0.5*SQR(0.15)*ni))); // hand\n\t// handles.push_back(Handle(_dualSphere(c3gaPoint(.2, -0.6, .1) - 0.5*SQR(0.15)*ni))); // foot\n\t// handles.push_back(Handle(_dualSphere(c3gaPoint(.45, 0.45, -.3) - 0.5*SQR(0.15)*ni))); // hand\n\t// handles.push_back(Handle(_dualSphere(c3gaPoint(-.3, -0.6, .1) - 0.5*SQR(0.15)*ni))); // foot\n\t// //Armadillo hip y head\n\t// handles.push_back(Handle(_dualSphere(c3gaPoint(.0, 0.4, -.2) - 0.5*SQR(0.15)*ni)));\n\t// handles.push_back(Handle(_dualSphere(c3gaPoint(.0, -0.05, .1) - 0.5*SQR(0.15)*ni)));\n\n\tvertexDescriptorsLow.resize(meshLow.numVertices());\n\tvertexDescriptors.resize(mesh.numVertices());\n\ttrianglesHi.resize(mesh.numFaces() * 3);\n\n\tfor( Vertex& vertexLow : meshLow.getVertices())\n\t{\n\t\tvertexDescriptorsLow.rotors[vertexLow.ID] = Eigen::Quaterniond::Identity();\n\t\tnormalizedPoint position = c3gaPoint(vertexLow.p.x(), vertexLow.p.y(), vertexLow.p.z());\n\n\t\tfor (Handle& handle : handles)\n\t\t{\n\t\t\tTRversor TR = handle.GetTRVersor();\n\n\t\t\tif (_double(position << (TR * handle.dS * inverse(TR))) > 0) //inside the sphere\n\t\t\t{\n\t\t\t\thandle.constraints.insert(vertexLow.ID);\n\t\t\t\tvertexDescriptorsLow.constrainedPositions[vertexLow.ID] = vertexLow.p;\n\t\t\t}\n\t\t}\n\t}\n\n\tA = CreateLaplacianMatrix( &meshLow, systemType );\n\t\n\tComputeLaplacianCoordinates(A, &meshLow, vertexDescriptorsLow.laplacianCoordinates);\n\n\tb3Low = Eigen::MatrixXd(A->numRows(), 3);\n\n\tfor (Handle& handle : handles) {\n\t\tallconstraints.insert(handle.constraints.begin(), handle.constraints.end());\n\t}\n\tPreFactor(A, allconstraints, solverLow);\n\n\tg_meshArea = meshArea(&meshLow);\n\n\tfor (Vertex& vertexHi : mesh.getVertices()) {\n\t\tvertexDescriptors.normalsOrig[vertexHi.ID] = vertexHi.n;\n\t\tvertexDescriptors.rotors[vertexHi.ID] = Eigen::Quaterniond::Identity();\n\t}\n\n\tfor (Face& face : mesh.getFaces()) {\n\t\tint i = face.ID;\n\t\tint\tv1 = face.edge->vertex->ID;\n\t\tint\tv2 = face.edge->next->vertex->ID;\n\t\tint\tv3 = face.edge->next->next->vertex->ID;\n\t\ttrianglesHi.faces[i * 3 + 0] = v1;\n\t\ttrianglesHi.faces[i * 3 + 1] = v2;\n\t\ttrianglesHi.faces[i * 3 + 2] = v3;\n\t}\n\n\n\tAHi = CreateLaplacianMatrix(&mesh, systemType);\n\tComputeLaplacianCoordinates(AHi, &mesh, vertexDescriptors.laplacianCoordinates);\n\tstd::set<int> constraintsHi;\n\tfor (map<int, int>::iterator iter = mapping.begin(); iter != mapping.end(); iter++){\n\t\tconstraintsHi.insert(iter->second);\n\t}\n\tb3Hi = Eigen::MatrixXd(AHi->numRows(), 3);\n\tPreFactor(AHi, constraintsHi, solverHi);\n\n  RotationMatrix = Eigen::SparseMatrix<double>(A->numRows()*4, A->numColumns()*4);\n  triplets.resize(A->NonZeros()*16);\n  Rknown = Eigen::VectorXd(A->numRows()*4);\n  Rknown.setZero();\n  RknownHi = Eigen::MatrixXd(AHi->numRows(), 4);\n  RknownHi.setZero();\n\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nvoid SolvePoissonEquation(VertexBuffer& vertexDescriptors)\n{\n\tint n = vertexDescriptors.get_size();\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tb3Low.row(i) = vertexDescriptors.laplacianCoordinates[i];\n\t}\n\n\tfor (Handle& handle : handles) {\n\t\tEigen::Affine3d M = MotorToMatrix(handle.GetTRVersor());\n\t\tfor (int i : handle.constraints) {\n\t\t\tb3Low.row(i) = M * vertexDescriptors.constrainedPositions[i];\n\t\t}\n\t}\n\n\txyzLow = solverLow.solve(b3Low);\n\n\tfor( int i = 0 ; i < n ; ++i ) {\n\t\tvertexDescriptors.deformedPositions[i] = xyzLow.row(i);\n\t}\n}\n\nvoid SolvePoissonEquationHi(VertexBuffer& vertexDescriptors, VertexBuffer& vertexDescriptorsLow)\n{\n\tint n = vertexDescriptors.get_size();\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tb3Hi.row(i) = vertexDescriptors.laplacianCoordinates[i];\n\t}\n\n\tfor (auto&& pair : mapping){\n\t\tb3Hi.row(pair.second) = vertexDescriptorsLow.deformedPositions[pair.first];\n\t}\n\n\txyzHi = solverHi.solve(b3Hi);\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tvertexDescriptors.deformedPositions[i] = xyzHi.row(i);\n\t\tvertexDescriptors.normals[i] = vertexDescriptors.rotors[i]._transformVector(vertexDescriptors.normalsOrig[i]);\n\t}\n}\n\n/*\nLaplacian: L(Ri) => Ri = Sum_j wij Rj\n\nSolve Sum_i wij (Ri - Rj) = 0\ns.t Ri = R_const,  at the constrained points.\n\nL Ri = 0\ns.t Ri = R_const\n\nWhere L is discrete laplacian operator\n*/\nvoid LaplacianRotationsInterpolation(VertexBuffer& vertexDescriptors, VertexBuffer& vertexDescriptorsLow)\n{\n\tint n = vertexDescriptors.get_size();\n\n\tfor (auto&& pair : mapping){\n\t\tRknownHi.row(pair.second) = vertexDescriptorsLow.rotors[pair.first].coeffs();\n\t}\n\n\tRbestHi = solverHi.solve(RknownHi);\n\n\tfor (int i = 0; i < n; ++i) {\n\t\tvertexDescriptors.rotors[i] = Eigen::Quaterniond((Eigen::Vector4d)RbestHi.row(i)).normalized();\n\t}\n}\n\n/*\nEi = sum_j |Ri qij ~Ri - pij|^2\nEi = sum_j |Ri qij - pij Ri|^2\n\nRi = w + B\n\n(w + B) qij - pij (w + B)\nw qij + B qij - pij w - pij B\nw qij + B qij - pij w - pij B\n\npij B = pij . B + pij x B\nB qij = B . qij + B x qij = qij . B - qij x B\n\nw qij + (qij . B - qij x B) - pij w - (pij . B + pij x B)\nw qij + qij . B - qij x B - pij w - pij . B - pij x B\n\n(qij - pij) w + (qij - pij) . B - (qij + pij) x B\n\n(qij - pij) w - (qij - pij)^T B - [qij + pij]_x B\n\n|0            -(qij - pij)^T  | |w| = |-(qij - pij)^T B               |\n|(qij - pij)   [qij + pij]^T_x| |B|   |(qij - pij) w - [qij + pij]_x B|\n\nd = (qij - pij)\ns = (qij + pij)\nd w - s^T B - [s]_x B\n\n|0    -d^T  | |w| = |-d^T B       |\n|d   [s]^T_x| |B|   |d w - [s]_x B|\n\n|0    -d^T  |^T |0    -d^T  | = \n|d   [s]^T_x|   |d   [s]^T_x|\n\n|0    d^T  | |0    -d^T  | = |d^T d    d^T [s]^T_x              |\n|-d   [s]_x| |d   [s]^T_x|   |[s]_x d  -d (-d^T) + [s]_x [s]^T_x|\n\n|0    d^T  | |0    -d^T  | = |d^T d    d^T [s]^T_x    |\n|-d   [s]_x| |d   [s]^T_x|   |[s]_x d  d d^T - [s]^2_x|\n\n| ||d||^2   (s x d)^T      |\n| s x d     d d^T - [s]^2_x|\n\n| ||d||^2   (s x d)^T                |\n| s x d     d d^T - s s^T + ||s||^2 I|\n\nd = (qij - pij)\ns = (qij + pij)\n\n||d||^2 = - 2 pij^T qij + ||pij||^2 + ||qij||^2\n||s||^2 = + 2 pij^T qij + ||pij||^2 + ||qij||^2\ns x d = 2 pij x qij\nd d^T = qij qij^T - pij qij^T - qij pij^T + pij pij^T \ns s^T = qij qij^T + pij qij^T + qij pij^T + pij pij^T\nd d^T - s s^T = - 2 pij qij^T - 2 qij pij^T\n\n| ||d||^2   (s x d)^T                |\n| s x d     d d^T - s s^T + ||s||^2 I|\n\n-2 | qij^T pij   (qij x pij)^T                      | + ||pij||^2 + ||qij||^2 I4x4\n   | qij x pij   qij pij^T + pij qij^T - qij^T pij I|   \n\nCOORDINATES:\n\nqij pij^T = | qx | |px py pz | = | qx px  qx py  qx pz |\n            | qy |               | qy px  qy py  qy pz |\n            | qz |               | qz px  qz py  qz pz |\n\n\nTrace(qij pij^T) = qij^T pij\nqij x pij = [(qy pz - qz py) e2e3, (qz px - qx pz) e3e1, (qx py - qy px) e1e2]\npij qij^T = (qij pij^T)^T\nqij pij^T + pij qij^T = qij pij^T + (qij pij^T)^T =\n\n| qx px  qx py  qx pz | | qx px  qy px  qz px |   | qx px+qx px  qx py+qy px  qx pz+qz px |\n| qy px  qy py  qy pz | | qx py  qy py  qz py | = | qy px+qx py  qy py+qy py  qy pz+qz py |\n| qz px  qz py  qz pz | | qx pz  qy pz  qz pz |   | qz px+qx pz  qz py+qy pz  qz pz+qz pz |\n\nqij = a e1 + b e2 + c e3\npij = d e1 + e e2 + f e3\n(b f - c e) e2e3 + (c d - a f) e3e1 + (a e - b d) e1e2\n(qy pz - qz py) e2e3 + (qz px - qx pz) e3e1 + (qx py - qy px) e1e2\n*/\nvoid E3GA_Prep(const vector<Eigen::Vector3d>& P, const vector<Eigen::Vector3d>& Q, const vector<double>& w, const int N, Eigen::Matrix4d &JtJ)\n{\n\tEigen::Matrix3d Sx;\n\tdouble wj;\n\tSx.setZero();\n\tdouble S = 0;\n\tfor (size_t j = 0; j < N; ++j) {\n\t\twj = w[j];\n\t\tconst Eigen::Vector3d& Qj = Q[j];\n\t\tconst Eigen::Vector3d& Pj = P[j];\n\t\tS += wj * Pj.dot(Pj);\n\t\tS += wj * Qj.dot(Qj);\n\t\tSx.noalias() += (wj * Pj) * Qj.transpose();\n\t}\n\n\twj = 0.5 * S;\n \tJtJ(0,0) = wj - Sx.trace();\n\twj = wj + Sx.trace();\n\tJtJ(0,1) = -(Sx(1, 2) - Sx(2, 1));\n\tJtJ(0,2) = -(Sx(2, 0) - Sx(0, 2));\n\tJtJ(0,3) = -(Sx(0, 1) - Sx(1, 0));\n\tJtJ(1,1) = -2.0 * Sx(0, 0) + wj;  \n\tJtJ(1,2) = -(Sx(0, 1) + Sx(1, 0)); \n\tJtJ(1,3) = -(Sx(2, 0) + Sx(0, 2));\n\tJtJ(2,2) = -2.0 * Sx(1, 1) + wj;  \n\tJtJ(2,3) = -(Sx(1, 2) + Sx(2, 1));\n\tJtJ(3,3) = -2.0 * Sx(2, 2) + wj;\n  JtJ.selfadjointView<Eigen::Upper>().evalTo(JtJ);\n}\n\n/*\nEi = sum_j cij |Ri qij ~Ri - pij|^2 + alphaA sum_j wij |Rj - Ri|^2\nEi = sum_j cij |Ri qij - pij Ri|^2 + alphaA sum_j wij |Rj - Ri|^2\n\nEi = Ri^T Mi Ri + alphaA sum_j wij (Rj^T Rj - Rj^T Ri + Ri^T Ri)\nd/Ri Ei = Mi Ri + sum_j alphaA wij (-Rj + Ri)\n\nMi Ri + sum_j alphaA wij (-Rj + Ri) = 0\nMi Ri - sum_j alphaA wij (Rj) + sum_j alphaA wij (Ri) = 0\n\nSince sum_j alphaA wij = alphaA\n\nMi Ri + alphaA Ri - sum_j alphaA wij (Rj) = 0\n(Mi + alphaA I) Ri = sum_j alphaA wij Rj\n*/\nEigen::Quaterniond E3GA_Fast4(const vector<Eigen::Vector3d>& P, const vector<Eigen::Vector3d>& Q, const vector<double>& w, double alphaA, const vector<Eigen::Quaterniond>& Rq, const int N)\n{\n\tEigen::Matrix4d JtJ;\n\tEigen::Matrix3d Sx;\n  Eigen::Vector4d b;\n\n  b.setZero();\n  for (int i = 0; i < N; ++i)\n\t{\n\t\tconst Eigen::Quaterniond& Qi = Rq[i];\n\t\tb(0) += Qi.w(); // 1.0\n\t\tb(1) += Qi.x(); // e1 ^ e2\n\t\tb(2) += Qi.y(); // e1 ^ e3\n\t\tb(3) += Qi.z(); // e2 ^ e3\n\t}\n  \n  b *= alphaA / (double) N;\n\n\tdouble wj;\n\tSx.setZero();\n\tdouble S = 0;\n\tfor (size_t j = 0; j < N; ++j) {\n\t\twj = w[j];\n\t\tconst Eigen::Vector3d& Qj = Q[j];\n\t\tconst Eigen::Vector3d& Pj = P[j];\n\t\tS += wj * Pj.dot(Pj);\n\t\tS += wj * Qj.dot(Qj);\n\t\tSx.noalias() += (wj * Pj) * Qj.transpose();\n\t}\n\n\twj = 0.5 * S;\n \tJtJ(0,0) = wj - Sx.trace() + alphaA;\n\twj = wj + Sx.trace() + alphaA;\n\tJtJ(0,1) = -(Sx(1, 2) - Sx(2, 1));\n\tJtJ(0,2) = -(Sx(2, 0) - Sx(0, 2));\n\tJtJ(0,3) = -(Sx(0, 1) - Sx(1, 0));\n\tJtJ(1,1) = -2.0 * Sx(0, 0) + wj;  \n\tJtJ(1,2) = -(Sx(0, 1) + Sx(1, 0)); \n\tJtJ(1,3) = -(Sx(2, 0) + Sx(0, 2));\n\tJtJ(2,2) = -2.0 * Sx(1, 1) + wj;  \n\tJtJ(2,3) = -(Sx(1, 2) + Sx(2, 1));\n\tJtJ(3,3) = -2.0 * Sx(2, 2) + wj;\n  JtJ.selfadjointView<Eigen::Upper>().evalTo(JtJ);\n\n  Eigen::Vector4d x = JtJ.inverse().eval() * b;\n  return Eigen::Quaterniond(x(0), x(1), x(2), x(3)).normalized();\n}\n\nvoid SolveRotationsSystem(Mesh *mesh, std::shared_ptr<SparseMatrix> A, VertexBuffer& vertexDescriptors, std::set<int>& constraints, bool analyzeSystem)\n{\n\tvector<Eigen::Vector3d> P;\n\tvector<Eigen::Vector3d> Q;\n  vector<double> w;\n  vector<int> neighbors;\n  Eigen::VectorXd Rbest;\n  Eigen::Matrix4d JtJ;\n  vector<Eigen::Quaterniond> Rq;\n\n\tP.resize(32);\n\tQ.resize(32);\n  neighbors.resize(32);\n  triplets.reserve(A->NonZeros()*16);\n  w.resize(32);\n  Rq.resize(32);\n\tconst double alpha = 0.14;\n\tconst double ei = 0.2;\n  const double cij = 1.0;\n  const double alphaA = alpha * g_meshArea;\n  int nnz = 0;\n  \n\tfor (Vertex& vertex : mesh->getVertices())\n\t{\n\t\tint i = vertex.ID;\n    int ii = i*4;\n\n\t\tEigen::Vector3d &pi = vertex.p;\n\t\tEigen::Vector3d &tpi = vertexDescriptors.deformedPositions[i];\n\n\t\tint vertexDegree = 0;\n\t\tfor (Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator(); vertexDegree < 32 && !edgeAroundIter.end(); edgeAroundIter++, vertexDegree++)\n\t\t{\n\t\t\tint j = edgeAroundIter.edge_out()->pair->vertex->ID;\n\n\t\t\tEigen::Vector3d &tpj = vertexDescriptors.deformedPositions[j];\n\t\t\tEigen::Vector3d &pj = mesh->vertexAt(j).p;\n\t\t\tP[vertexDegree] = pj - pi;\n\t\t\tQ[vertexDegree] = tpj - tpi;\n      neighbors[vertexDegree] = j;\n      w[vertexDegree] = (*A)(i, j);\n\t\t}\n    if (!is_constrained(constraints, i)) {\n  \t\tdouble invVertexDegree = (alphaA * cij) / ((double)vertexDegree + ei); // Plus ei since we consider the feedback.\n      for(int v = 0; v < vertexDegree; ++v) {\n        int jj = neighbors[v]*4;\n        triplets[nnz++] = Eigen::Triplet<double>(ii+0, jj+0, -invVertexDegree);\n        triplets[nnz++] = Eigen::Triplet<double>(ii+1, jj+1, -invVertexDegree);\n        triplets[nnz++] = Eigen::Triplet<double>(ii+2, jj+2, -invVertexDegree);\n        triplets[nnz++] = Eigen::Triplet<double>(ii+3, jj+3, -invVertexDegree);\n      }\n      E3GA_Prep(P, Q, w, vertexDegree, JtJ);\n      JtJ(0, 0) += alphaA + 1e-6;\n      JtJ(1, 1) += alphaA + 1e-6;\n      JtJ(2, 2) += alphaA + 1e-6;\n      JtJ(3, 3) += alphaA + 1e-6;\n      triplets[nnz++] = Eigen::Triplet<double>(ii+0, ii+0, JtJ(0, 0));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+0, ii+1, JtJ(0, 1));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+0, ii+2, JtJ(0, 2));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+0, ii+3, JtJ(0, 3));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+1, ii+0, JtJ(1, 0));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+1, ii+1, JtJ(1, 1));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+1, ii+2, JtJ(1, 2));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+1, ii+3, JtJ(1, 3));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+2, ii+0, JtJ(2, 0));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+2, ii+1, JtJ(2, 1));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+2, ii+2, JtJ(2, 2));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+2, ii+3, JtJ(2, 3));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+3, ii+0, JtJ(3, 0));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+3, ii+1, JtJ(3, 1));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+3, ii+2, JtJ(3, 2));\n      triplets[nnz++] = Eigen::Triplet<double>(ii+3, ii+3, JtJ(3, 3));\n      // Feedback added on the RHS.\n      invVertexDegree *= ei;\n      Rknown[ii+0] = invVertexDegree * vertexDescriptors.rotors[i].w();\n      Rknown[ii+1] = invVertexDegree * vertexDescriptors.rotors[i].x();\n      Rknown[ii+2] = invVertexDegree * vertexDescriptors.rotors[i].y();\n      Rknown[ii+3] = invVertexDegree * vertexDescriptors.rotors[i].z();\n    }\n    else\n    {\n      for(int v = 0; v < vertexDegree; ++v) {\n        Rq[v] = vertexDescriptors.rotors[neighbors[v]];\n      }\n\n      Eigen::Quaterniond M = E3GA_Fast4(P, Q, w, alphaA, Rq, vertexDegree);\n      Rknown[ii+0] = M.w();\n      Rknown[ii+1] = M.x();\n      Rknown[ii+2] = M.y();\n      Rknown[ii+3] = M.z();\n      triplets[nnz++] = Eigen::Triplet<double>(ii+0, ii+0, 1.0);\n      triplets[nnz++] = Eigen::Triplet<double>(ii+1, ii+1, 1.0);\n      triplets[nnz++] = Eigen::Triplet<double>(ii+2, ii+2, 1.0);\n      triplets[nnz++] = Eigen::Triplet<double>(ii+3, ii+3, 1.0);     \n    }\n\t}\n  RotationMatrix.setFromTriplets(triplets.begin(), triplets.begin() + nnz);\n  if(analyzeSystem) {\n    solverRotations.analyzePattern(RotationMatrix);\n  }\n  solverRotations.factorize(RotationMatrix);\n\tif (solverRotations.info() != Eigen::Success) {\n\t\t// TODO: error handling\n\t}\n\tRbest = solverRotations.solve(Rknown);\n\n\tfor (int i = 0; i < vertexDescriptors.get_size(); ++i) {\n    int ii = i*4;\n    Eigen::Quaterniond M = Eigen::Quaterniond(Rbest(ii+0), Rbest(ii+1), Rbest(ii+2), Rbest(ii+3));\n\t\tvertexDescriptors.rotors[i] = M.normalized();\n\t}\n\n  std::fill(vertexDescriptors.laplacianCoordinates.begin(), vertexDescriptors.laplacianCoordinates.end(), Eigen::Vector3d(0, 0, 0));\n\n\t//concurrency::parallel_for_each(mesh->getVertices().begin(), mesh->getVertices().end(), [&](Vertex& vertex)\n\tfor (Vertex& vertex : mesh->getVertices())\n\t{\n\t\tint i = vertex.ID;\n\t\tfor (Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator(); !edgeAroundIter.end(); edgeAroundIter++)\n\t\t{\n\t\t\tint j = edgeAroundIter.edge_out()->pair->vertex->ID;\n\t\t\tdouble wij = (*A)(i, j);\n\t\t\tEigen::Quaterniond&Ri = vertexDescriptors.rotors[i];\n\t\t\tEigen::Quaterniond&Rj = vertexDescriptors.rotors[j];\n\t\t\tEigen::Vector3d V = mesh->vertexAt(j).p - mesh->vertexAt(i).p;\n\t\t\tvertexDescriptors.laplacianCoordinates[i] += 0.5 * wij * (Ri._transformVector(V) + Rj._transformVector(V));;\n\t\t}\n\t}\n}\n\nvoid transferRotations(Mesh *mesh, std::shared_ptr<SparseMatrix> A, VertexBuffer& vertexDescriptors, VertexBuffer& vertexDescriptorsLow)\n{\n  LaplacianRotationsInterpolation(vertexDescriptors, vertexDescriptorsLow);\n\n\tstd::fill(vertexDescriptors.laplacianCoordinates.begin(), vertexDescriptors.laplacianCoordinates.end(), Eigen::Vector3d(0, 0, 0));\n\n\t//concurrency::parallel_for_each(mesh->getVertices().begin(), mesh->getVertices().end(), [&](Vertex& vertex)\n\tfor (Vertex& vertex : mesh->getVertices())\n\t{\n\t\tint i = vertex.ID;\n\t\tfor (Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator(); !edgeAroundIter.end(); edgeAroundIter++)\n\t\t{\n\t\t\tint j = edgeAroundIter.edge_out()->pair->vertex->ID;\n\t\t\tdouble wij = (*A)(i, j);\n\t\t\tEigen::Quaterniond &Ri = vertexDescriptors.rotors[i];\n\t\t\tEigen::Quaterniond &Rj = vertexDescriptors.rotors[j];\n\t\t\tEigen::Vector3d V = mesh->vertexAt(j).p - mesh->vertexAt(i).p;\n\t\t\tvertexDescriptors.laplacianCoordinates[i] += 0.5 * wij * (Ri._transformVector(V) + Rj._transformVector(V));;\n\t\t}\n\t}\n\t//});\n}\n\ndouble ComputeEnergy(Mesh *mesh, std::shared_ptr<SparseMatrix> A, VertexBuffer& vertexDescriptors)\n{\n\tdouble arapEnergy = 0.0;\n\tconst double alpha = 0.28;\n\t//concurrency::parallel_for_each(mesh->vertices.begin(), mesh->vertices.end(), [&](Vertex * vertex)\n\tfor (Vertex& vertex : mesh->getVertices())\n\t{\n\t\tint i = vertex.ID;\n\n\t\tEigen::Vector3d& pi = vertex.p;\n\t\tEigen::Vector3d &tpi = vertexDescriptors.deformedPositions[i];\n\t\tauto& Ri = vertexDescriptors.rotors[i];\n\n\t\tint vertexDegree = 0;\n\t\tfor (Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator(); !edgeAroundIter.end(); edgeAroundIter++)\n\t\t{\n\t\t\tvertexDegree++;\n\t\t}\n\n\t\tdouble invVertexDegree = alpha * g_meshArea / (double)vertexDegree;\n\n\t\tfor (Vertex::EdgeAroundIterator edgeAroundIter = vertex.iterator(); !edgeAroundIter.end(); edgeAroundIter++)\n\t\t{\n\t\t\tint j = edgeAroundIter.edge_out()->pair->vertex->ID;\n\n\t\t\tEigen::Vector3d &tpj = vertexDescriptors.deformedPositions[j];\n\t\t\tEigen::Vector3d &pj = mesh->vertexAt(j).p;\n\n\t\t\tEigen::Vector3d eij = (pj - pi);\n\t\t\tauto q_ij = tpj - tpi;\n\t\t\tauto p_ij = eij;\n\t\t\tauto& Rj = vertexDescriptors.rotors[j];\n\n\t\t\tarapEnergy += (*A)(i, j) * (Ri._transformVector(p_ij) - q_ij).squaredNorm();\n\t\t\tarapEnergy += invVertexDegree * (Rj.coeffs() - Ri.coeffs()).squaredNorm();\n\t\t}\n\t}//);\n\n\treturn arapEnergy;\n}\n\nvoid display()\n{\n\t/*\n\t *\tmatrices\n\t */\n\tglViewport( 0, 0, g_viewportWidth, g_viewportHeight );\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tpickLoadMatrix();\n\tGLpick::g_frustumFar = 1000.0;\n\tGLpick::g_frustumNear = .1;\n\tgluPerspective( 60.0, (double)g_viewportWidth/(double)g_viewportHeight, GLpick::g_frustumNear, GLpick::g_frustumFar );\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\n\tglShadeModel(GL_SMOOTH);\t//gouraud shading\n\tglClearDepth(1.0f);\n\tglClearColor( .75f, .75f, .75f, .0f );\n\tglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );\n\n\t/*\n\t *\testados\n\t */\n\tglEnable(GL_CULL_FACE);\t\t//face culling\n\tglCullFace( GL_BACK );\n\tglFrontFace( GL_CCW );\n\tglEnable(GL_DEPTH_TEST);\t//z-buffer\n\tglDepthFunc(GL_LEQUAL);\n\n\t/*\n\t *\tiluminacion\n\t */\n\tfloat\t\tambient[] = { .3f, .3f, .3f, 1.f };\n\tfloat\t\tdiffuse[] = { .3f, .3f, .3f, 1.f };\n\tfloat\t\tposition[] = { .0f, 0.f, -150.f, 1.f };\n\tfloat\t\tspecular[] = { 1.f, 1.f, 1.f };\n\n\tglLightfv( GL_LIGHT0, GL_AMBIENT, ambient );\n\tglLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );\n\tglLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0);\n\tglLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.0125);\n\tglEnable(  GL_LIGHT0   );\n\tglEnable(  GL_LIGHTING );\n\tglMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, specular );\n\tglMaterialf( GL_FRONT_AND_BACK, GL_SHININESS, 50.f );\n\n\tglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n\n\tglLoadIdentity();\n\n\tg_camera.glLookAt();\n\n\tglLightfv( GL_LIGHT0, /*GL_POSITION*/GL_SPOT_DIRECTION, position );\n\n\tglPushMatrix();\n\n\trotorGLMult(g_modelRotor);\n\n\tbenchs.Begin();\n\n\tif(!g_computeBasis)\n\t{\n\t\tstatic bool oneTime = true;\n\t\tif (oneTime || (g_rotateKeyRotors || g_translateKeyRotors || g_automaticAnimation))\n\t\t{\n\t\t\tif(oneTime == true)\n\t\t\t{\n\t\t\t\tSolvePoissonEquation(vertexDescriptorsLow);\n\t\t\t}\n\n\t\t\tfor(int i = 0 ; i < 3 ; ++i)\n\t\t\t{\n        SolveRotationsSystem(&meshLow, A, vertexDescriptorsLow, allconstraints, oneTime == true);\n\t\t\t\tSolvePoissonEquation(vertexDescriptorsLow);\n\t\t\t}\n\t\t\ttransferRotations(&mesh, AHi, vertexDescriptors, vertexDescriptorsLow);\n\t\t\tSolvePoissonEquationHi(vertexDescriptors, vertexDescriptorsLow);\n\n      oneTime = false;\n\t\t}\n\t}\n\tif(g_iterateManyTimes)\n\t{\n\t\tif (g_convergence)\n\t\t{\n\t\t\tclock_t begin;\n\t\t\tclock_t end;\n\t\t\tdouble avgTime = 0.0;\n\n\t\t\tauto arapEnergy = ComputeEnergy(&meshLow, A, vertexDescriptorsLow);\n\t\t\tint count = 0;\n\t\t\tfor (; count < 2500; ++count)\n\t\t\t{\n\t\t\t\tbegin = clock();\n\n        SolveRotationsSystem(&meshLow, A, vertexDescriptorsLow, allconstraints, false);\n\t\t\t\tSolvePoissonEquation(vertexDescriptorsLow);\n\n\t\t\t\tend = clock();\n\n\t\t\t\tdouble secDeform = (double)(end - begin) / CLOCKS_PER_SEC;\n\n\t\t\t\tavgTime += secDeform;\n\n\t\t\t\tauto newArapEnergy = ComputeEnergy(&meshLow, A, vertexDescriptorsLow);\n\t\t\t\tif (fabs(arapEnergy - newArapEnergy) < 1e-4)\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"convergence after \" << count + 1 << \" iterations\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tarapEnergy = newArapEnergy;\n\t\t\t}\n\t\t\tarapEnergy = ComputeEnergy(&meshLow, A, vertexDescriptorsLow);\n\t\t\tstd::cout << arapEnergy << std::endl;\n\t\t\tstd::cout << \"Average iteration time (sec): \" << avgTime / (double)(count + 1) << endl;\n\t\t\tstd::cout << \"Total accum time (sec): \" << avgTime << endl;\n\n\t\t\ttransferRotations(&mesh, AHi, vertexDescriptors, vertexDescriptorsLow);\n\t\t\tSolvePoissonEquationHi(vertexDescriptors, vertexDescriptorsLow);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int i = 0; i < 100; ++i)\n\t\t\t{\n        SolveRotationsSystem(&meshLow, A, vertexDescriptorsLow, allconstraints, false);\n\t\t\t\tSolvePoissonEquation(vertexDescriptorsLow);\n\t\t\t}\n\t\t\ttransferRotations(&mesh, AHi, vertexDescriptors, vertexDescriptorsLow);\n\t\t\tSolvePoissonEquationHi(vertexDescriptors, vertexDescriptorsLow);\n\t\t}\n\t\tg_iterateManyTimes = false;\n\t}\n\n\tbenchs.End();\n\n\tif (GLpick::g_pickActive) glLoadName((GLuint)-1);\n\n\tdouble alpha = 1.0;\n\n\t//glEnable (GL_BLEND);\n\t//glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\t//alpha = 0.5;\n\n\t//Mesh-Faces Rendering\n\tglPolygonMode( GL_FRONT_AND_BACK, GL_FILL /*GL_LINE GL_FILL GL_POINT*/);\n\tglEnable (GL_POLYGON_OFFSET_FILL);\n\tglPolygonOffset (1., 1.);\n\tglColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);\n\tglEnable( GL_COLOR_MATERIAL );\n\tif (GLpick::g_pickActive) glLoadName((GLuint)10);\n\n\tglColor4d(1, 1, 1, alpha);\n\tglEnableClientState(GL_NORMAL_ARRAY);\n\tglEnableClientState(GL_VERTEX_ARRAY);\n\tglVertexPointer(3, GL_DOUBLE, 0, &vertexDescriptors.deformedPositions[0]);\n\tglNormalPointer(GL_DOUBLE, 0, &vertexDescriptors.normals[0]);\n\t// draw the model\n\tglDrawElements(GL_TRIANGLES, trianglesHi.get_size(), GL_UNSIGNED_INT, &trianglesHi.faces[0]);\n\t// deactivate vertex arrays after drawing\n\tglDisableClientState(GL_VERTEX_ARRAY);\n\tglDisableClientState(GL_NORMAL_ARRAY);\n\n\tif (g_showWires)\n\t{\n\t\tif (!GLpick::g_pickActive)\n\t\t{\n\t\t\t//Mesh-Edges Rendering (superimposed to faces)\n\t\t\tglPolygonMode(GL_FRONT_AND_BACK, GL_LINE /*GL_LINE GL_FILL GL_POINT*/);\n\t\t\tglColor4d(.5, .5, .5, alpha);\n\t\t\tglDisable(GL_LIGHTING);\n\t\t\tglEnableClientState(GL_VERTEX_ARRAY);\n\t\t\tglVertexPointer(3, GL_DOUBLE, 0, &vertexDescriptors.deformedPositions[0]);\n\t\t\t// draw the model\n\t\t\tglDrawElements(GL_TRIANGLES, trianglesHi.get_size(), GL_UNSIGNED_INT, &trianglesHi.faces[0]);\n\t\t\t// deactivate vertex arrays after drawing\n\t\t\tglDisableClientState(GL_VERTEX_ARRAY);\n\t\t\tglEnable(GL_LIGHTING);\n\t\t}\n\t}\n\n\t//for (map<int, int>::iterator iter = mapping.begin(); iter != mapping.end(); iter++){\n\t//\tDrawPoint(c3gaPoint(vertexDescriptors[iter->second]->deformedPosition));\n\t//}\n\n\tglDisable( GL_COLOR_MATERIAL );\n\tglDisable(GL_POLYGON_OFFSET_FILL);\n\n\t//glDisable (GL_BLEND);\n\n\tif(g_showSpheres)\n\t{\n\t\t//Handles rendering\n\t\tglPolygonMode( GL_FRONT_AND_BACK, GL_FILL /*GL_LINE GL_FILL GL_POINT*/);\n\n\t\tfloat\tturcoise[] = { .0f, .5f, .5f, 0.3f };\n\t\tfloat\tred[] = { .5f, .0f, .0f, 0.3f };\n\n\t\tfor( int k = 0 ; k < handles.size() ; ++k)\n\t\t{\n\t\t\tif (GLpick::g_pickActive) glLoadName((GLuint)k);\n\t\t\tTRversor R = handles[k].GetTRVersor();\n\t\t\tDrawTransparentDualSphere( _dualSphere( R * handles[k].dS * inverse(R) ), turcoise );\n\t\t}\t\t\n\t}\n\n\tglPopMatrix();\n\n\tglutSwapBuffers();\n}\n\nvoid reshape(GLint width, GLint height)\n{\n\tg_viewportWidth = width;\n\tg_viewportHeight = height;\n\n\t// redraw viewport\n\tglutPostRedisplay();\n}\n\nvectorE3GA mousePosToVector(int x, int y) {\n\tx -= g_viewportWidth / 2;\n\ty -= g_viewportHeight / 2;\n\treturn _vectorE3GA((float)-x * e1 - (float)y * e2);\n}\n\nvoid MouseButton(int button, int state, int x, int y)\n{\n\tg_rotateModel = false;\n\tg_rotateKeyRotors = false;\n\tg_translateKeyRotors = false;\n\n\tif (button == GLUT_LEFT_BUTTON)\n\t{\n\t\tg_prevMousePos = mousePosToVector(x, y);\n\n\t\tGLpick::g_pickWinSize = 1;\n\t\tg_dragObject = pick(x, g_viewportHeight - y, display, &g_dragDistance);\n\n\t\tif(g_dragObject == -1 || g_dragObject == 10 )\n\t\t{\n\t\t\tvectorE3GA mousePos = mousePosToVector(x, y);\n\t\t\tg_rotateModel = true;\n\n\t\t\tif ((_Float(norm_e(mousePos)) / _Float(norm_e(g_viewportWidth * e1 + g_viewportHeight * e2))) < 0.2)\n\t\t\t\tg_rotateModelOutOfPlane = true;\n\t\t\telse g_rotateModelOutOfPlane = false;\n\t\t}\n\t\telse if(g_dragObject >= 0 && g_dragObject < handles.size())\n\t\t{\n\t\t\tg_rotateKeyRotors = true;\n\t\t}\n\t}\n\n\tif (button == GLUT_RIGHT_BUTTON)\n\t{\n\t\tg_prevMousePos = mousePosToVector(x, y);\n\n\t\tGLpick::g_pickWinSize = 1;\n\t\tg_dragObject = pick(x, g_viewportHeight - y, display, &g_dragDistance);\n\n\t\tif(g_dragObject >= 0 && g_dragObject < handles.size())\n\t\t\tg_translateKeyRotors = true;\n\t}\n}\n\nvoid MouseMotion(int x, int y)\n{\n\tif (g_rotateModel || g_rotateKeyRotors || g_translateKeyRotors )\n\t{\n\t\t// get mouse position, motion\n\t\tvectorE3GA mousePos = mousePosToVector(x, y);\n\t\tvectorE3GA motion = mousePos - g_prevMousePos;\n\n\t\tif (g_rotateModel)\n\t\t{\n\t\t\t// update rotor\n\t\t\tif (g_rotateModelOutOfPlane)\n\t\t\t\tg_modelRotor = exp(g_camera.rotateVel * (motion ^ e3) ) * g_modelRotor;\n\t\t\telse \n\t\t\t\tg_modelRotor = exp(0.00001f * (motion ^ mousePos) ) * g_modelRotor;\n\t\t}\n\t\tif(g_rotateKeyRotors)\n\t\t{\n\t\t\trotor R1 =  _rotor( inverse(g_modelRotor) * exp(-g_camera.rotateVel * (motion ^ e3) ) * g_modelRotor);\n\t\t\t//rotor R1 =  _rotor( exp(-g_camera.rotateVel * (motion ^ e3) ) );\n\t\t\tif(g_dragObject < handles.size())\n\t\t\t{\n\t\t\t\trotor R = handles[g_dragObject].R;\n\t\t\t\thandles[g_dragObject].R = normalize(_TRversor( R1 * R  ) );\n\t\t\t}\n\t\t}\n\n\t\tif(g_translateKeyRotors)\n\t\t{\n\t\t\tnormalizedTranslator T1 = _normalizedTranslator(inverse(g_modelRotor) * exp( _freeVector(-g_camera.translateVel*motion*ni) ) * g_modelRotor);\n\t\t\tif(g_dragObject < handles.size())\n\t\t\t{\n\t\t\t\ttranslator T = handles[g_dragObject].T;\n\t\t\t\thandles[g_dragObject].T = normalize(_TRversor( T1 * T ));\n\t\t\t}\n\t\t}\n\n\t\t// remember mouse pos for next motion:\n\t\tg_prevMousePos = mousePos;\n\n\t\t// redraw viewport\n\t\tglutPostRedisplay();\n\t}\n}\n\nvoid SpecialFunc(int key, int x, int y)\n{\n\tswitch(key) {\n\t\tcase GLUT_KEY_F1 :\n\t\t\t{\n\t\t\t\tint mod = glutGetModifiers();\n\t\t\t\tif(mod == GLUT_ACTIVE_CTRL || mod == GLUT_ACTIVE_SHIFT )\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GLUT_KEY_UP:\n\t\t\t{\n\t\t\t\tif(g_rotateKeyRotors)\n\t\t\t\t{\n\t\t\t\t\thandles[g_dragObject].dS = ChangeDualSphereRadiusSize(handles[g_dragObject].dS, 0.025);\n\n\t\t\t\t\t// redraw viewport\n\t\t\t\t\tglutPostRedisplay();\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase GLUT_KEY_DOWN:\n\t\t\t{\n\t\t\t\tif(g_rotateKeyRotors)\n\t\t\t\t{\n\t\t\t\t\thandles[g_dragObject].dS = ChangeDualSphereRadiusSize(handles[g_dragObject].dS, -0.025);\n\n\t\t\t\t\t// redraw viewport\n\t\t\t\t\tglutPostRedisplay();\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t}\n}\n\nvoid SpecialUpFunc(int key, int x, int y)\n{\n}\n\nvoid KeyboardUpFunc(unsigned char key, int x, int y)\n{\n\tif (key == 'c' || key == 'C')\n\t{\n\t\tg_convergence = !g_convergence;\n\t\tvectorE3GA motion = _vectorE3GA(-70.0, -60.0, 0);\n\t\tnormalizedTranslator T1 = _normalizedTranslator(inverse(g_modelRotor) * exp(_freeVector(-g_camera.translateVel*motion*ni)) * g_modelRotor);\n\t\ttranslator T = handles[0].T;\n\t\thandles[0].T = normalize(_TRversor(T1 * T));\n\n\t\tglutPostRedisplay();\n\t}\n\n\tif (key == 'a' || key == 'A')\n\t{\n\t\tg_automaticAnimation = !g_automaticAnimation;\n\t\tif (g_automaticAnimation)\n\t\t{\n\t\t\tbenchs.Start();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbenchs.Stop();\n\t\t}\n\n\t\tglutPostRedisplay();\n\t}\n\n\tif(key == 'w' || key == 'W')\n\t{\n\t\tg_showWires = !g_showWires;\n\t\tglutPostRedisplay();\n\t}\n\t\n\tif( key == 'h' || key == 'H' )\n\t{\n\t\tg_showSpheres = !g_showSpheres;\n\t\tglutPostRedisplay();\n\t}\n\n\tif( key == 'x' || key == 'X' )\n\t{\n\t\tg_iterateManyTimes = true;\n\t\tglutPostRedisplay();\n\t}\n}\n\nvoid Idle()\n{\n\t// redraw viewport\n\tif (g_automaticAnimation)\n\t{\n\t\tconst int minCount = -50;\n\t\tconst int maxCount = 50;\n\t\tstatic int mycount = 0;\n\t\tstatic int direction = 0;\n\t\tvectorE3GA motion = _vectorE3GA(1.0, 0, 0);\n\t\tif (mycount == maxCount)\n\t\t{\n\t\t\tdirection = 1;\n\t\t}\n\t\tif (mycount == minCount)\n\t\t{\n\t\t\tdirection = 0;\n\t\t}\n\n\t\tif (mycount < maxCount && direction == 0)\n\t\t{\n\t\t\tmotion = _vectorE3GA(1.0, 0, 0);\n\t\t\tmycount++;\n\t\t}\n\t\tif (mycount > minCount && direction == 1)\n\t\t{\n\t\t\tmotion = _vectorE3GA(-1.0, 0, 0);\n\t\t\tmycount--;\n\t\t}\n\n\t\tnormalizedTranslator T1 = _normalizedTranslator(inverse(g_modelRotor) * exp(_freeVector(-g_camera.translateVel*motion*ni)) * g_modelRotor);\n\t\ttranslator T = handles[0].T;\n\t\thandles[0].T = normalize(_TRversor(T1 * T));\n\n\t\tif (!benchs.IsStarted())\n\t\t{\n\t\t\tbenchs.Start();\n\t\t}\n\n\t\tglutPostRedisplay();\n\t}\n}\n\nvoid DestroyWindow()\n{\n\tReleaseDrawing();\n}\n\n", "meta": {"hexsha": "b86a329abb8c54143f8b683784429f9e6f65b34a", "size": 38314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Flatten.cpp", "max_stars_repo_name": "mauriciocele/arap-sr-linearized", "max_stars_repo_head_hexsha": "94d7cb8b48b63da2065993528dcc97712523fb07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T15:14:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T14:08:49.000Z", "max_issues_repo_path": "src/Flatten.cpp", "max_issues_repo_name": "mauriciocele/arap-sr-linearized", "max_issues_repo_head_hexsha": "94d7cb8b48b63da2065993528dcc97712523fb07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Flatten.cpp", "max_forks_repo_name": "mauriciocele/arap-sr-linearized", "max_forks_repo_head_hexsha": "94d7cb8b48b63da2065993528dcc97712523fb07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1100513573, "max_line_length": 188, "alphanum_fraction": 0.6471263768, "num_tokens": 13384, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.4191305779174033}}
{"text": "#ifndef __PARTICLE_FILTER_HAND_LIKELIHOOD_HPP\n#define __PARTICLE_FILTER_HAND_LIKELIHOOD_HPP\n\n#include <cmath>\n#include <ctime>\n#include <vector>\n#include <algorithm>\n#include <Eigen/Dense>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n\n#include <padenti/image.hpp>\n#include <padenti/mh_rtree.hpp>\n#include <padenti/cl_regressor.hpp>\n\n#include \"rchord_meanshift.hpp\"\n\n#include \"particle_filter_hand.hpp\"\n#include \"particle_filter_base.hpp\"\n\n// Random Forest parameters\n#define RF_FEAT_SIZE (2)\n#define RF_VAL_SIZE  (4)\n#define RF_N_HYPH    (2)\n\n// Meanshift parameters\n#define MS_N_HYPH    (10)\n#define MS_SIGMA    (1.6223)\n#define MS_STEPSIZE (0.2)\n#define MS_STEPTHR  (0.025)\n#define MS_SAMECTHR (0.15)\n#define MS_NITERTHR (10u)\n#define MS_SAMPLED_PIXELS (200u)\n\n// Likelihood parameters\n#define EVAL_SIGMA  (MS_SIGMA/3)\n\n// Commodity typedefs to avoid long class type declaration\ntypedef Image<unsigned short, 1> DepthT;\ntypedef Image<unsigned char, 1> MaskT;\ntypedef Image<int, 1> PredictionT;\ntypedef MHRTree<short int, RF_FEAT_SIZE, RF_VAL_SIZE, RF_N_HYPH> MHRTreeT;\ntypedef RTreeNode<short int, RF_FEAT_SIZE, RF_VAL_SIZE> RTreeNodeT;\ntypedef CLRegressor<unsigned short, 1, short, RF_FEAT_SIZE, RF_VAL_SIZE> RegressorT;\n\n\nclass HandLikelihoodModel: public LikelihoodModel<HAND_STATE_SIZE>\n{\nprivate:\n  RegressorT &regressor;\n  Particle<HAND_STATE_SIZE> prevState;\n  std::vector<Eigen::Matrix3f> modes;\n  std::vector<float> modesW;\n  std::vector<int> modesCount;\n  std::vector<float> modesVar;\n  int nModes;\n  float evalSigma;\n  float deltaT;\npublic:\n\n  HandLikelihoodModel(RegressorT &regressor, \n\t\t      float evalSigma=EVAL_SIGMA):\n    regressor(regressor),\n    modes(std::vector<Eigen::Matrix3f>(MS_N_HYPH)),\n    modesW(std::vector<float>(MS_N_HYPH)),\n    modesCount(std::vector<int>(MS_N_HYPH)),\n    modesVar(std::vector<float>(MS_N_HYPH)),\n    nModes(0),\n    evalSigma(evalSigma)\n  {}\n\n  const std::vector<Eigen::Matrix3f> &getModes() const {return modes;}\n  const std::vector<float> &getModeWeights() const {return modesW;}\n  const std::vector<int> &getModeCount() const {return modesCount;}\n  const std::vector<float> &getModeVar() const {return modesVar;}\n  int getNModes() const {return nModes;}\n\n  void eval(std::vector<Particle<HAND_STATE_SIZE> > &particles) const\n  {\n    Eigen::Quaternion<float> prevq(prevState.state[0],\n\t\t\t\t   prevState.state[1],\n\t\t\t\t   prevState.state[2],\n\t\t\t\t   prevState.state[3]);\n    Eigen::Vector3d prevV(prevState.state[4],\n\t\t\t  prevState.state[5],\n\t\t\t  prevState.state[6]);\n\n    // Compute the particles weight as the Panzer window estimate on rotation chordal\n    // distance values using a Gaussian kernel\n    // TODO: per-mode bandwidth as in Herdtweek paper?\n    for (int i=0; i<particles.size(); i++)\n    {\n      Eigen::Quaternion<float> q(particles.at(i).state[0],\n\t\t\t\t particles.at(i).state[1],\n\t\t\t\t particles.at(i).state[2],\n\t\t\t\t particles.at(i).state[3]);\n      Eigen::Vector3d currV(particles.at(i).state[4],\n\t\t\t    particles.at(i).state[5],\n\t\t\t    particles.at(i).state[6]);\n      Eigen::Matrix3f R(q);\n\n      // Compute the likelihood\n      double l = 0;\n      for (int j=0; j<nModes; j++)\n      {\n\tEigen::Matrix3f rotDiff = R-modes.at(j);\n\tl += modesW.at(j) * exp(-rotDiff.cwiseProduct(rotDiff).sum()/(evalSigma*evalSigma));\n\t//l += modesCount.at(j)/sqrt(modesVar.at(j)) * \n\t//  exp(-rotDiff.cwiseProduct(rotDiff).sum()/(modesVar.at(j)));\n      }\n\n\n     // Compute the velocity with respect to the previous best particle rotation\n      // TODO: parameterize velocity bound\n      Eigen::Quaternion<float> deltaq;\n      Eigen::AngleAxisf axang;\n      float V;\n      deltaq = q * prevq.inverse();\n      axang = deltaq;\n      V = axang.angle()/deltaT;\n      particles.at(i).likelihood = V<10*M_PI ? l : 0.;\n\n\n      //particles.at(i).likelihood = l;      \n      //double diffV = (currV-prevV).norm();\n      //particles.at(i).likelihood *= exp(-(diffV*diffV)/(M_PI*M_PI));\n      //particles.at(i).likelihood *= exp(-(V*V)/(25*M_PI*M_PI));\n      \n    }\n  }\n\n  void updateModel(const Particle<HAND_STATE_SIZE> &_prevState, \n\t\t   const MHRTreeT &rtree, const DepthT &depthmap,\n\t\t   float _deltaT=1./30)\n  {\n    // Perform RF prediction on the current depthmap. The depthmap is supposed to\n    // be already segmented\n    // - Mask as non-zero pixels\n    MaskT mask(depthmap.getWidth(), depthmap.getHeight());\n    cv::Mat cvDepth(depthmap.getHeight(), depthmap.getWidth(), CV_16U,\n\t\t    reinterpret_cast<unsigned char*>(depthmap.getData()));\n    cv::Mat cvMask(depthmap.getHeight(), depthmap.getWidth(), CV_8U,\n\t\t   reinterpret_cast<unsigned char*>(mask.getData()));\n    cvMask.setTo(0);\n    cvMask.setTo(1, cvDepth>0);\n\n    // - perform prediction\n    // TODO: handle multiple trees\n    PredictionT prediction(depthmap.getWidth(), depthmap.getHeight());\n    regressor.predict(0, depthmap, prediction, mask);\n\n    // - sample image pixels, i.e. work on a subset of the per-pixel prediction\n    // in order to guarantee real-time execution\n    unsigned int *nonNullPixelsBuff = \n      new unsigned int[prediction.getWidth()*prediction.getHeight()];\n    unsigned int nonNullPixels=0, nSamples=0;\n    for (unsigned int i=0; i<prediction.getWidth()*prediction.getHeight(); i++)\n    {\n      if (mask.getData()[i]) nonNullPixelsBuff[nonNullPixels++]=i;\n    }\n    nSamples = std::min(MS_SAMPLED_PIXELS, nonNullPixels);\n\n    if (!nSamples)\n    {\n      // TODO: how to handle the lack of samples?\n      return;\n    }\n\n    unsigned int *samples = new unsigned int[nSamples];\n    if (nSamples<MS_SAMPLED_PIXELS)\n    {\n      // Not enough samples (i.e. non-null pixels) to perform sampling.\n      // Simply copy the whole set of samples\n      std::copy(nonNullPixelsBuff, nonNullPixelsBuff+nSamples, samples);\n    }\n    else\n    {\n      boost::random::mt19937 gen(time(NULL));\n      boost::random::uniform_int_distribution<> U(0, nonNullPixels-1);\n      for (int i=0; i<nSamples; i++) samples[i] = nonNullPixelsBuff[U(gen)];\n    }\n\n    // Build the list of votes (i.e. Euler angles) and perform meanshift\n    std::vector<Eigen::Vector3f> votes;\n    std::vector<float> votesW;\n    for (int i=0; i<nSamples; i++)\n    {\n      int nodeID = prediction.getData()[samples[i]];\n      unsigned int nVotes = rtree.getNVotes()[nodeID];\n\n      for (int j=0; j<nVotes; j++)\n      {\n\tEigen::Vector3f vote;\n\tfloat *votesPtr = \n\t  &rtree.getVotes()[nodeID*RF_VAL_SIZE*RF_N_HYPH + j*RF_VAL_SIZE];\n\tfloat *weightPtr = \n\t  &rtree.getVoteWeights()[nodeID*RF_N_HYPH+j];\n\n\tvote.z() = votesPtr[0]*M_PI/180.; //static_cast<double>(votesPtr[0])*M_PI/180.;\n        vote.y() = votesPtr[1]*M_PI/180.; //static_cast<double>(votesPtr[1])*M_PI/180.;\n\tvote.x() = votesPtr[2]*M_PI/180.; //static_cast<double>(votesPtr[2])*M_PI/180.;\n\tvotes.push_back(vote);\n\tvotesW.push_back(*weightPtr);\n\t//votesW.push_back(static_cast<double>(*weightPtr));\n      }\n    }\n\n    std::vector<Eigen::Vector3f> eulModes(MS_N_HYPH);\n    std::vector<int> voteModeID(votes.size());\n    nModes = MultiGuessRChordMeanShift(votes, votesW, votes, eulModes, voteModeID,\n\t\t\t\t       MS_SIGMA, MS_STEPSIZE, MS_STEPTHR,\n\t\t\t\t       MS_NITERTHR, MS_SAMECTHR);\n\n    // Store modes found as rotation matrices\n    for (int i=0; i<nModes; i++)\n    {\n      modes.at(i) = Eigen::AngleAxisf(eulModes.at(i).x(), Eigen::Vector3f::UnitZ()) * \n\t            Eigen::AngleAxisf(eulModes.at(i).y(), Eigen::Vector3f::UnitY()) * \n\t            Eigen::AngleAxisf(eulModes.at(i).z(), Eigen::Vector3f::UnitX());\n    }\n    \n    // Update the mode weights as the sum of (weights of the) votes that converge to\n    // each specific mode\n    std::fill(modesW.begin(), modesW.end(), 0.);\n    std::fill(modesCount.begin(), modesCount.end(), 0);\n    std::fill(modesVar.begin(), modesVar.end(), 0.);\n    for (int i=0; i<votes.size(); i++)\n    {\n      if (voteModeID.at(i)!=-1) \n      {\n\tmodesW.at(voteModeID.at(i)) += votesW.at(i);\n\tmodesCount.at(voteModeID.at(i))++;\n\t\n\tEigen::Matrix3f voteMat(Eigen::AngleAxisf(votes.at(i).x()*M_PI/180,\n\t\t\t\t\t\t  Eigen::Vector3f::UnitZ()) * \n\t\t\t\tEigen::AngleAxisf(votes.at(i).y()*M_PI/180,\n\t\t\t\t\t\t  Eigen::Vector3f::UnitY()) * \n\t\t\t\tEigen::AngleAxisf(votes.at(i).z()*M_PI/180,\n\t\t\t\t\t\t  Eigen::Vector3f::UnitX()));\n\tEigen::Quaternion<float> modeQ(modes.at(voteModeID.at(i)));\n\tEigen::Quaternion<float> voteQ(voteMat);\n\n\tEigen::Quaternion<double> tmp(voteQ.inverse() * modeQ);\n\tfloat distQ = 2.*acos(fabs(tmp.w()));\n\tmodesVar.at(voteModeID.at(i)) += distQ*distQ;\n      }\n    }\n\n    for (int i=0; i<nModes; i++) modesVar.at(i)/=modesCount.at(i);\n\n    // Finally, save the previous state and time delta (they will be used to disregard unplausible rotations)\n    prevState = _prevState;\n    deltaT = _deltaT;\n\n    // Done\n    delete []samples;\n    delete []nonNullPixelsBuff;\n  }\n};\n\n\n#endif // __PARTICLE_FILTER_HAND_LIKELIHOOD_HPP\n", "meta": {"hexsha": "9537484de3f8d644b4619a74330283a58b61d9bf", "size": 8922, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/particle_filter/particle_filter_hand_likelihood.hpp", "max_stars_repo_name": "mUogoro/hand_rotation_estimation_tutorial", "max_stars_repo_head_hexsha": "98707de67448016e63bb8480090e4fa139dbc896", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T01:05:09.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T01:05:09.000Z", "max_issues_repo_path": "src/particle_filter/particle_filter_hand_likelihood.hpp", "max_issues_repo_name": "mUogoro/hand_rotation_estimation_tutorial", "max_issues_repo_head_hexsha": "98707de67448016e63bb8480090e4fa139dbc896", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/particle_filter/particle_filter_hand_likelihood.hpp", "max_forks_repo_name": "mUogoro/hand_rotation_estimation_tutorial", "max_forks_repo_head_hexsha": "98707de67448016e63bb8480090e4fa139dbc896", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-11-08T09:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T07:57:45.000Z", "avg_line_length": 33.6679245283, "max_line_length": 109, "alphanum_fraction": 0.6710378839, "num_tokens": 2549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.41909848712758835}}
{"text": "// Copyright 2010 The Trustees of Indiana University.\r\n\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n//  Authors: Jeremiah Willcock\r\n//           Andrew Lumsdaine\r\n\r\n#ifndef BOOST_GRAPH_RANDOM_SPANNING_TREE_HPP\r\n#define BOOST_GRAPH_RANDOM_SPANNING_TREE_HPP\r\n\r\n#include <vector>\r\n#include <boost/assert.hpp>\r\n#include <boost/graph/loop_erased_random_walk.hpp>\r\n#include <boost/graph/random.hpp>\r\n#include <boost/graph/iteration_macros.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/config.hpp>\r\n#include <boost/graph/graph_traits.hpp>\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/graph/properties.hpp>\r\n#include <boost/graph/named_function_params.hpp>\r\n\r\nnamespace boost {\r\n\r\n  namespace detail {\r\n    // Use Wilson's algorithm (based on loop-free random walks) to generate a\r\n    // random spanning tree.  The distribution of edges used is controlled by\r\n    // the next_edge() function, so this version allows either weighted or\r\n    // unweighted selection of trees.\r\n    // Algorithm is from http://en.wikipedia.org/wiki/Uniform_spanning_tree\r\n    template <typename Graph, typename PredMap, typename ColorMap, typename NextEdge>\r\n    void random_spanning_tree_internal(const Graph& g, typename graph_traits<Graph>::vertex_descriptor s, PredMap pred, ColorMap color, NextEdge next_edge) {\r\n      typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n      typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\r\n\r\n      BOOST_ASSERT (num_vertices(g) >= 1); // g must also be undirected (or symmetric) and connected\r\n\r\n      typedef color_traits<typename property_traits<ColorMap>::value_type> color_gen;\r\n      BGL_FORALL_VERTICES_T(v, g, Graph) put(color, v, color_gen::white());\r\n\r\n      std::vector<vertex_descriptor> path;\r\n\r\n      put(color, s, color_gen::black());\r\n      put(pred, s, graph_traits<Graph>::null_vertex());\r\n\r\n      BGL_FORALL_VERTICES_T(v, g, Graph) {\r\n        if (get(color, v) != color_gen::white()) continue;\r\n        loop_erased_random_walk(g, v, next_edge, color, path);\r\n        for (typename std::vector<vertex_descriptor>::const_reverse_iterator i = path.rbegin();\r\n             boost::next(i) !=\r\n               (typename std::vector<vertex_descriptor>::const_reverse_iterator)path.rend();\r\n             ++i) {\r\n          typename std::vector<vertex_descriptor>::const_reverse_iterator j = i;\r\n          ++j;\r\n          BOOST_ASSERT (get(color, *j) == color_gen::gray());\r\n          put(color, *j, color_gen::black());\r\n          put(pred, *j, *i);\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  // Compute a uniformly-distributed spanning tree on a graph.  Use Wilson's algorithm:\r\n  // @inproceedings{wilson96generating,\r\n  //    author = {Wilson, David Bruce},\r\n  //    title = {Generating random spanning trees more quickly than the cover time},\r\n  //    booktitle = {STOC '96: Proceedings of the twenty-eighth annual ACM symposium on Theory of computing},\r\n  //    year = {1996},\r\n  //    isbn = {0-89791-785-5},\r\n  //    pages = {296--303},\r\n  //    location = {Philadelphia, Pennsylvania, United States},\r\n  //    doi = {http://doi.acm.org/10.1145/237814.237880},\r\n  //    publisher = {ACM},\r\n  //    address = {New York, NY, USA},\r\n  //  }\r\n  //\r\n  template <typename Graph, typename Gen, typename PredMap, typename ColorMap>\r\n  void random_spanning_tree(const Graph& g, Gen& gen, typename graph_traits<Graph>::vertex_descriptor root,\r\n                            PredMap pred, static_property_map<double>, ColorMap color) {\r\n    unweighted_random_out_edge_gen<Graph, Gen> random_oe(gen);\r\n    detail::random_spanning_tree_internal(g, root, pred, color, random_oe);\r\n  }\r\n\r\n  // Compute a weight-distributed spanning tree on a graph.\r\n  template <typename Graph, typename Gen, typename PredMap, typename WeightMap, typename ColorMap>\r\n  void random_spanning_tree(const Graph& g, Gen& gen, typename graph_traits<Graph>::vertex_descriptor root,\r\n                            PredMap pred, WeightMap weight, ColorMap color) {\r\n    weighted_random_out_edge_gen<Graph, WeightMap, Gen> random_oe(weight, gen);\r\n    detail::random_spanning_tree_internal(g, root, pred, color, random_oe);\r\n  }\r\n\r\n  template <typename Graph, typename Gen, typename P, typename T, typename R>\r\n  void random_spanning_tree(const Graph& g, Gen& gen, const bgl_named_params<P, T, R>& params) {\r\n    using namespace boost::graph::keywords;\r\n    typedef bgl_named_params<P, T, R> params_type;\r\n    BOOST_GRAPH_DECLARE_CONVERTED_PARAMETERS(params_type, params)\r\n    random_spanning_tree(g,\r\n                         gen,\r\n                         arg_pack[_root_vertex | *vertices(g).first],\r\n                         arg_pack[_predecessor_map],\r\n                         arg_pack[_weight_map | static_property_map<double>(1.)],\r\n                         boost::detail::make_color_map_from_arg_pack(g, arg_pack));\r\n  }\r\n}\r\n\r\n#include <boost/graph/iteration_macros_undef.hpp>\r\n\r\n#endif // BOOST_GRAPH_RANDOM_SPANNING_TREE_HPP\r\n", "meta": {"hexsha": "b4ea2198acc974b809de402aa8938bcbf5397e46", "size": 5118, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/graph/random_spanning_tree.hpp", "max_stars_repo_name": "importlib/klib", "max_stars_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "master/core/third/boost/graph/random_spanning_tree.hpp", "max_issues_repo_name": "isuhao/klib", "max_issues_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "master/core/third/boost/graph/random_spanning_tree.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 46.1081081081, "max_line_length": 158, "alphanum_fraction": 0.6787807737, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.6297746143530797, "lm_q1q2_score": 0.41905867802124214}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// p_square_cumulative_distribution.hpp\r\n//\r\n//  Copyright 2005 Daniel Egloff, Olivier Gygi. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_CUMUL_DIST_HPP_DE_01_01_2006\r\n#define BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_CUMUL_DIST_HPP_DE_01_01_2006\r\n\r\n#include <vector>\r\n#include <functional>\r\n#include <boost/parameter/keyword.hpp>\r\n#include <boost/range.hpp>\r\n#include <boost/mpl/placeholders.hpp>\r\n#include <boost/accumulators/accumulators_fwd.hpp>\r\n#include <boost/accumulators/framework/accumulator_base.hpp>\r\n#include <boost/accumulators/framework/extractor.hpp>\r\n#include <boost/accumulators/numeric/functional.hpp>\r\n#include <boost/accumulators/framework/parameters/sample.hpp>\r\n#include <boost/accumulators/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/count.hpp>\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n///////////////////////////////////////////////////////////////////////////////\r\n// num_cells named parameter\r\n//\r\nBOOST_PARAMETER_NESTED_KEYWORD(tag, p_square_cumulative_distribution_num_cells, num_cells)\r\n\r\nBOOST_ACCUMULATORS_IGNORE_GLOBAL(p_square_cumulative_distribution_num_cells)\r\n\r\nnamespace impl\r\n{\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // p_square_cumulative_distribution_impl\r\n    //  cumulative_distribution calculation (as histogram)\r\n    /**\r\n        @brief Histogram calculation of the cumulative distribution with the \\f$P^2\\f$ algorithm\r\n\r\n        A histogram of the sample cumulative distribution is computed dynamically without storing samples\r\n        based on the \\f$ P^2 \\f$ algorithm. The returned histogram has a specifiable amount (num_cells)\r\n        equiprobable (and not equal-sized) cells.\r\n\r\n        For further details, see\r\n\r\n        R. Jain and I. Chlamtac, The P^2 algorithm for dynamic calculation of quantiles and\r\n        histograms without storing observations, Communications of the ACM,\r\n        Volume 28 (October), Number 10, 1985, p. 1076-1085.\r\n\r\n        @param p_square_cumulative_distribution_num_cells.\r\n    */\r\n    template<typename Sample>\r\n    struct p_square_cumulative_distribution_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::average<Sample, std::size_t>::result_type float_type;\r\n        typedef std::vector<float_type> array_type;\r\n        typedef std::vector<std::pair<float_type, float_type> > histogram_type;\r\n        // for boost::result_of\r\n        typedef iterator_range<typename histogram_type::iterator> result_type;\r\n\r\n        template<typename Args>\r\n        p_square_cumulative_distribution_impl(Args const &args)\r\n          : num_cells(args[p_square_cumulative_distribution_num_cells])\r\n          , heights(num_cells + 1)\r\n          , actual_positions(num_cells + 1)\r\n          , desired_positions(num_cells + 1)\r\n          , positions_increments(num_cells + 1)\r\n          , histogram(num_cells + 1)\r\n          , is_dirty(true)\r\n        {\r\n            std::size_t b = this->num_cells;\r\n\r\n            for (std::size_t i = 0; i < b + 1; ++i)\r\n            {\r\n                this->actual_positions[i] = i + 1.;\r\n                this->desired_positions[i] = i + 1.;\r\n                this->positions_increments[i] = numeric::average(i, b);\r\n            }\r\n        }\r\n\r\n        template<typename Args>\r\n        void operator ()(Args const &args)\r\n        {\r\n            this->is_dirty = true;\r\n\r\n            std::size_t cnt = count(args);\r\n            std::size_t sample_cell = 1; // k\r\n            std::size_t b = this->num_cells;\r\n\r\n            // accumulate num_cells + 1 first samples\r\n            if (cnt <= b + 1)\r\n            {\r\n                this->heights[cnt - 1] = args[sample];\r\n\r\n                // complete the initialization of heights by sorting\r\n                if (cnt == b + 1)\r\n                {\r\n                    std::sort(this->heights.begin(), this->heights.end());\r\n                }\r\n            }\r\n            else\r\n            {\r\n                // find cell k such that heights[k-1] <= args[sample] < heights[k] and adjust extreme values\r\n                if (args[sample] < this->heights[0])\r\n                {\r\n                    this->heights[0] = args[sample];\r\n                    sample_cell = 1;\r\n                }\r\n                else if (this->heights[b] <= args[sample])\r\n                {\r\n                    this->heights[b] = args[sample];\r\n                    sample_cell = b;\r\n                }\r\n                else\r\n                {\r\n                    typename array_type::iterator it;\r\n                    it = std::upper_bound(\r\n                        this->heights.begin()\r\n                      , this->heights.end()\r\n                      , args[sample]\r\n                    );\r\n\r\n                    sample_cell = std::distance(this->heights.begin(), it);\r\n                }\r\n\r\n                // increment positions of markers above sample_cell\r\n                for (std::size_t i = sample_cell; i < b + 1; ++i)\r\n                {\r\n                    ++this->actual_positions[i];\r\n                }\r\n\r\n                // update desired position of markers 2 to num_cells + 1\r\n                // (desired position of first marker is always 1)\r\n                for (std::size_t i = 1; i < b + 1; ++i)\r\n                {\r\n                    this->desired_positions[i] += this->positions_increments[i];\r\n                }\r\n\r\n                // adjust heights of markers 2 to num_cells if necessary\r\n                for (std::size_t i = 1; i < b; ++i)\r\n                {\r\n                    // offset to desire position\r\n                    float_type d = this->desired_positions[i] - this->actual_positions[i];\r\n\r\n                    // offset to next position\r\n                    float_type dp = this->actual_positions[i + 1] - this->actual_positions[i];\r\n\r\n                    // offset to previous position\r\n                    float_type dm = this->actual_positions[i - 1] - this->actual_positions[i];\r\n\r\n                    // height ds\r\n                    float_type hp = (this->heights[i + 1] - this->heights[i]) / dp;\r\n                    float_type hm = (this->heights[i - 1] - this->heights[i]) / dm;\r\n\r\n                    if ( ( d >= 1. && dp > 1. ) || ( d <= -1. && dm < -1. ) )\r\n                    {\r\n                        short sign_d = static_cast<short>(d / std::abs(d));\r\n\r\n                        // try adjusting heights[i] using p-squared formula\r\n                        float_type h = this->heights[i] + sign_d / (dp - dm) * ( (sign_d - dm) * hp + (dp - sign_d) * hm );\r\n\r\n                        if ( this->heights[i - 1] < h && h < this->heights[i + 1] )\r\n                        {\r\n                            this->heights[i] = h;\r\n                        }\r\n                        else\r\n                        {\r\n                            // use linear formula\r\n                            if (d>0)\r\n                            {\r\n                                this->heights[i] += hp;\r\n                            }\r\n                            if (d<0)\r\n                            {\r\n                                this->heights[i] -= hm;\r\n                            }\r\n                        }\r\n                        this->actual_positions[i] += sign_d;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            if (this->is_dirty)\r\n            {\r\n                this->is_dirty = false;\r\n\r\n                // creates a vector of std::pair where each pair i holds\r\n                // the values heights[i] (x-axis of histogram) and\r\n                // actual_positions[i] / cnt (y-axis of histogram)\r\n\r\n                std::size_t cnt = count(args);\r\n\r\n                for (std::size_t i = 0; i < this->histogram.size(); ++i)\r\n                {\r\n                    this->histogram[i] = std::make_pair(this->heights[i], numeric::average(this->actual_positions[i], cnt));\r\n                }\r\n            }\r\n            //return histogram;\r\n            return make_iterator_range(this->histogram);\r\n        }\r\n\r\n    private:\r\n        std::size_t num_cells;            // number of cells b\r\n        array_type  heights;              // q_i\r\n        array_type  actual_positions;     // n_i\r\n        array_type  desired_positions;    // n'_i\r\n        array_type  positions_increments; // dn'_i\r\n        mutable histogram_type histogram; // histogram\r\n        mutable bool is_dirty;\r\n    };\r\n\r\n} // namespace detail\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::p_square_cumulative_distribution\r\n//\r\nnamespace tag\r\n{\r\n    struct p_square_cumulative_distribution\r\n      : depends_on<count>\r\n      , p_square_cumulative_distribution_num_cells\r\n    {\r\n        /// INTERNAL ONLY\r\n        ///\r\n        typedef accumulators::impl::p_square_cumulative_distribution_impl<mpl::_1> impl;\r\n    };\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::p_square_cumulative_distribution\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::p_square_cumulative_distribution> const p_square_cumulative_distribution = {};\r\n\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(p_square_cumulative_distribution)\r\n}\r\n\r\nusing extract::p_square_cumulative_distribution;\r\n\r\n// So that p_square_cumulative_distribution can be automatically substituted with\r\n// weighted_p_square_cumulative_distribution when the weight parameter is non-void\r\ntemplate<>\r\nstruct as_weighted_feature<tag::p_square_cumulative_distribution>\r\n{\r\n    typedef tag::weighted_p_square_cumulative_distribution type;\r\n};\r\n\r\ntemplate<>\r\nstruct feature_of<tag::weighted_p_square_cumulative_distribution>\r\n  : feature_of<tag::p_square_cumulative_distribution>\r\n{\r\n};\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#endif\r\n", "meta": {"hexsha": "33e800b733fd6c276408a608017ce957c7641264", "size": 10082, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "BoostSharp/include/boost/accumulators/statistics/p_square_cumul_dist.hpp", "max_stars_repo_name": "Icenium/BoostSharp", "max_stars_repo_head_hexsha": "1dd31065fcd65ae6304b182c558bac7c7a738ad5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-11T05:30:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-24T05:41:33.000Z", "max_issues_repo_path": "src/third_party/boost/boost/accumulators/statistics/p_square_cumul_dist.hpp", "max_issues_repo_name": "wugh7125/installwizard", "max_issues_repo_head_hexsha": "42f8aeb78026ff81838528968b1503e73f6c2864", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/third_party/boost/boost/accumulators/statistics/p_square_cumul_dist.hpp", "max_forks_repo_name": "wugh7125/installwizard", "max_forks_repo_head_hexsha": "42f8aeb78026ff81838528968b1503e73f6c2864", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-26T17:00:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T17:00:08.000Z", "avg_line_length": 38.1893939394, "max_line_length": 125, "alphanum_fraction": 0.5198373339, "num_tokens": 2035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.41901221247769027}}
{"text": "/*=============================================================================\nCopyright 2020 Syed Ali Hasan <alihasan9922@gmail.com>\n\nDistributed under the Boost Software License, Version 1.0. (See accompanying\nfile License.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n\n#ifndef BOOST_ASTRONOMY_TIME_CONVERSIONS\n#define BOOST_ASTRONOMY_TIME_CONVERSIONS\n\n#include <string>\n#include <exception>\n#include <boost/astronomy/time/parser.hpp>\n#include <boost/date_time/gregorian/gregorian.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\nnamespace boost { namespace astronomy { namespace time {\n\n/**\n * Universal time (UT), and therefore the local civil time in any\n * part of the world, is related to the apparent motion of the Sun\n * around the Earth.\n *\n * Sidereal Time (ST) is a time scale that is based on Earth's rate\n * of rotation measured relative to the fixed stars.\n */\n\n/**\n * The Greenwich Sidereal Time(GST) is the sidereal time correct for observations\n * made on the Greenwich meridian, longitude 0◦.\n */\n\ndouble julian_date(boost::posix_time::ptime t)\n{\n    //Get date from UT\n    boost::gregorian::date dt = t.date();\n\n    //Set y = year, m = month and d = day\n    double y = dt.year();\n    double m = dt.month();\n    double d = dt.day();\n\n    //If m = 1 or 2, set yprime = y − 1 and mprime = m + 12; otherwise yprime = y and mprime = m.\n    double yprime;\n    double mprime;\n    if ( (m == 1) || (m == 2) )\n    {\n        yprime = y - 1;\n        mprime = m + 12;\n    }\n    else\n    {\n        yprime = y;\n        mprime = m;\n    }\n\n    //Calculate B, check if the date is later than 1582 October 15\n    double B;\n    boost::gregorian::date dt1(1582, boost::gregorian::Oct , 1);\n    if ( dt > dt1 )\n    {\n        double A = floor(yprime / 100);\n        B = 2 - A + floor(A / 4);\n    }\n    else\n    {\n        B = 0;\n    }\n\n    //Calculate C, check if yprime is negative\n    double C;\n    if (yprime < 0)\n    {\n        C = floor((365.25 * yprime) - 0.75);\n    }\n    else\n    {\n        C = floor(365.25 * yprime);\n    }\n\n    //Calculate D\n    double D;\n    D = floor(30.6001 * (mprime + 1));\n\n    //Finding Julian date\n    double JD;\n    JD = B + C + D + d + 1720994.5;\n\n    return JD;\n}\n\ndecimal_hour GST(boost::posix_time::ptime t)\n{\n    //Get Julian Day Number\n    double JD = julian_date(t);\n\n    double S = JD - 2451545.0;\n\n    double T = S/36525.0;\n\n    double T0 = 6.697374558 + (2400.051336 * T) + (0.000025862 * T * T);\n\n    //Reduce the result to the range 0 to 24 by adding or subtracting multiples of 24\n    T0 = T0 - 24.0 * floor(T0/24.0);\n\n    //Convert UT to decimal hours\n    double UT = ((t.time_of_day().seconds())/60.0 + t.time_of_day().minutes())/60.0 + t.time_of_day().hours();\n\n    //Multiply UT by 1.002737909\n    double A = UT * 1.002737909;\n\n    T0 += A;\n\n    //Add this to T0 and reduce to the range 0 to 24 if necessary by subtracting or adding 24. This is the GST.\n    T0 = T0 - 24.0 * floor(T0/24.0);\n\n    //Return GST in decimal hours\n    return {T0};\n}\n\nenum class DIRECTION {WEST, EAST};\n\n//Local Sidereal Time (LST)\ndecimal_hour LST(double longitude, DIRECTION direction, boost::posix_time::ptime t)\n{\n    double gst = GST(t).get();\n\n    if(longitude == 0)\n      return {gst};\n\n    //Convert longitude to hours\n    double long_hours = longitude / 15.0;\n\n    switch(direction)\n    {\n      case DIRECTION::WEST:\n          //Multiply with direction\n          long_hours = -1 * long_hours;\n            break;\n      case DIRECTION::EAST:\n          //Multiply with direction\n          long_hours = 1 * long_hours;\n            break;\n    }\n\n    long_hours = long_hours + gst;\n\n    //Bring the result into the range 0 to 24 by adding or subtracting 24 if necessary.\n    //This is the local sidereal time (LST).\n    long_hours = long_hours - 24.0 * floor(long_hours/24.0);\n\n    return {long_hours};\n}\n\n}}} // namespace::astronomy::time\n#endif //BOOST_ASTRONOMY_TIME_CONVERSIONS\n", "meta": {"hexsha": "ca3571786c61aa690475526950ea48adc5d05ab7", "size": 4009, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/time/time_conversions.hpp", "max_stars_repo_name": "nitink25/astronomy", "max_stars_repo_head_hexsha": "0a1d137171b08d1014d4ff138b2a40a146f4f39b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T13:53:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T20:37:18.000Z", "max_issues_repo_path": "include/boost/astronomy/time/time_conversions.hpp", "max_issues_repo_name": "nitink25/astronomy", "max_issues_repo_head_hexsha": "0a1d137171b08d1014d4ff138b2a40a146f4f39b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 96.0, "max_issues_repo_issues_event_min_datetime": "2019-05-28T17:46:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-09T07:59:17.000Z", "max_forks_repo_path": "include/boost/astronomy/time/time_conversions.hpp", "max_forks_repo_name": "nitink25/astronomy", "max_forks_repo_head_hexsha": "0a1d137171b08d1014d4ff138b2a40a146f4f39b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T21:09:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T06:24:39.000Z", "avg_line_length": 25.5350318471, "max_line_length": 111, "alphanum_fraction": 0.5931653779, "num_tokens": 1135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4190122124776902}}
{"text": "#include \"element.h\"\n#include <armadillo>\n\n//#define NDEBUG 1\n#include <cassert>\n\nusing namespace arma;\n\n// TODO let's store material properties in a struct or an instance and only keep a reference to it\n// TODO most matrices we can make a fixed, static size. implement this for better performance\n// TODO consider a more flyweight approach... how much can we slim down cost of creating an element?\n// TODO convert c style arrays to c++ arrays\n// TODO separate material data from mesh data\n// TODO convert for loops to ranged loops\n// TODO delegate integration to a separate \"Integration\" class\n\n/**\n * Default constructor for a mechanical finite element\n * \n * @return MechElem\n */\nMechElem::MechElem() {}\n\n/**\n * Constructor for a mechanical finite element\n * \n * @param [int] E Modulus of elasticity\n * @param [double] v Poissons ratio\n * @param [vec*] b Body forces: x-direction, y-direction\n * @param [vec*] t Traction forces: bottom, right, top, left\n * @param [int*] gnodes Nodal numbers: bot-left, bot-right, top-right, top-left\n * @param [mat*] gcoords Global coordinates corresponding to each node\n * @param [int*] gdof Global degrees of freedom\n * @return MechElem\n */\nMechElem::MechElem(long long int E, double v, vec *pb, vec *pt, int *gnodes, \n        mat *pgcoords, int *gdofs) : E(E), v(v), pb(pb), pt(pt), \n        gnodes(gnodes), pgcoords(pgcoords), gdofs(gdofs) {};\n\n/**\n * Clone of a mechanical finite element\n * \n * @param [int] \n * @return MechElem\n */\nMechElem::MechElem(const MechElem& orig) \n{\n}\n\n/**\n * Deallocation of a mechanical finite element\n * \n * @param void \n * @return void\n */\nMechElem::~MechElem(void) \n{\n}\n\n/**\n * Accessor for global nodal coordinates\n * \n * @return mat *gcoords\n */\nmat *MechElem::getGcoords() { return pgcoords; }\n\n/**\n * Accessor for global node numbers\n * \n * @return int *gnodes\n */\nint *MechElem::getGnodes() { return gnodes; }\n\n/**\n * Accessor for global degrees of freedom\n * \n * @return int *gdofs\n */\nint *MechElem::getGdofs() { return gdofs; }\n\n/*\n * Q4 class constants\n */\ndouble const Q4::gaussPoints[] = { -0.5774, 0.5774 };\nint const Q4::weights[] = { 1, 1 };\n\n/**\n * Default constructor for a Q4 finite element\n * \n * @return Q4\n */\nQ4::Q4() {}\n\n// TODO: consider separating material data from element object\n\n/**\n * Constructor for a Q4 finite element\n * \n * @param [int] E Modulus of elasticity\n * @param [double] v Poissons ratio\n * @param [double] h Thickness or 'height' of the element\n * @param [vec] b Body forces: x-direction, y-direction\n * @param [vec] t Traction forces: bottom, right, top, left\n * @param [int*] gnodes Nodal numbers: bot-left, bot-right, top-right, top-left\n * @param [mat*] gcoords Global coordinates corresponding to each node\n * @param [int*] gdof Global degrees of freedom\n * @return Q4\n */\nQ4::Q4(long long int E, double v, double h, vec *pb, vec *pt, int *gnodes, \n    mat *pgcoords, int *gdofs) : MechElem(E, v, pb, pt, gnodes, pgcoords, \n    gdofs), h(h) {};\n\n\n/**\n * Deallocation of a Q4 finite element\n * \n * @param void \n * @return void\n */\nQ4::~Q4(void) \n{\n}\n\n// consider inline functions?\n/*\n * Define the Q4 shape functions\n */\n#define Q4__N1(xi, eta) (1-xi)*(1-eta)/4\n#define Q4__N2(xi, eta) (1+xi)*(1-eta)/4\n#define Q4__N3(xi, eta) (1+xi)*(1+eta)/4\n#define Q4__N4(xi, eta) (1-xi)*(1+eta)/4\n        \n/**\n * Calculates the N matrix\n * \n * @param [double] xi Xi coordinate in parent coordinates\n * @param [double] eta Eta coordinate in parent coordinates\n * @return [mat] N matrix\n */\nmat Q4::N(double xi, double eta) \n{\n    mat::fixed<Q4__DOF_PER_NODE,Q4__DOF_PER_NODE*Q4__NUM_NODES> N;\n    N << Q4__N1(xi, eta) << 0 << Q4__N2(xi, eta) << 0 << Q4__N3(xi, eta) << 0\n            << Q4__N4(xi, eta) << 0 << endr\n      << 0 << Q4__N1(xi, eta) << 0 << Q4__N2(xi, eta) << 0 << Q4__N3(xi, eta)\n            << 0 << Q4__N4(xi, eta) << endr;\n    return N;\n}\n\n/*\n * Define the partials of the Q4 shape functions with respect to xi and eta\n */\n#define Q4__dN1_dxi(eta) -(1-eta)/4\n#define Q4__dN2_dxi(eta) (1-eta)/4\n#define Q4__dN3_dxi(eta) (1+eta)/4\n#define Q4__dN4_dxi(eta) -(1+eta)/4\n#define Q4__dN1_deta(xi) -(1-xi)/4\n#define Q4__dN2_deta(xi) -(1+xi)/4\n#define Q4__dN3_deta(xi) (1+xi)/4\n#define Q4__dN4_deta(xi) (1-xi)/4\n\n/**\n * Calculates the jacobian\n * \n * @param [double] xi Xi coordinate in parent coordinates\n * @param [double] eta Eta coordinate in parent coordinates\n * @return [mat] Jacobian\n */\nmat Q4::J(double xi, double eta) \n{\n    mat::fixed<Q4__DOF_PER_NODE,Q4__NUM_NODES> dj;\n    dj << Q4__dN1_dxi(eta) << Q4__dN2_dxi(eta) << Q4__dN3_dxi(eta)\n            << Q4__dN4_dxi(eta) << endr\n       << Q4__dN1_deta(xi) << Q4__dN2_deta(xi) << Q4__dN3_deta(xi)\n            << Q4__dN4_deta(xi) << endr;\n    mat jacobian = dj * *pgcoords;\n    return jacobian;\n}\n\n// TODO: have Q4 inherit from 'shell element' in order to maximize code reuse\n\n/**\n * Calculate the element body force, mutator\n * \n * @param [vec&] bodyForce Body force vector\n * @return void\n */\nvoid Q4::mbodyForce(vec &bodyForce)\n{\n    assert(bodyForce.n_rows == Q4__DOF_PER_NODE*Q4__NUM_NODES);\n    // TODO make zeros at or not at the beg of function consistent across functions\n    bodyForce.zeros();\n    unsigned int i, j;\n    double xi, eta, weightX, weightY;\n    \n    /*\n     * calculate element body force using gauss quadrature\n     */\n    for (i = 0; i < Q4::numPointsX; i++) \n    {\n        xi = Q4::gaussPoints[i];\n        weightX = Q4::weights[i];\n        for (j = 0; j < Q4::numPointsY; j++) \n        {\n            eta = Q4::gaussPoints[j];\n            weightY = Q4::weights[j];\n            bodyForce += weightX * weightY * trans(N(xi, eta)) * *pb \n                    * det(J(xi, eta));\n        }\n    }\n    bodyForce *= h;\n}\n\n//TODO: fix this function\n/**\n * Calculates the traction for a surface, mutator\n * \n * @param [vec&] traction Traction force vector\n * @return void\n */\nvoid Q4::mtraction(vec &traction) \n{\n    traction.zeros();\n    unsigned int i, j;\n    double xi, eta, weightX, weightY;\n    \n    /*\n     * calculate element body force using gauss quadrature\n     */\n    for (i = 0; i < Q4::numPointsX; i++) \n    {\n        xi = Q4::gaussPoints[i];\n        weightX = Q4::weights[i];\n        for (j = 0; j < Q4::numPointsY; j++) \n        {\n            eta = Q4::gaussPoints[j];\n            weightY = Q4::gaussPoints[j];\n            traction += weightX * weightY * trans(N(xi, eta)) * *pt \n                    * det(J(xi, eta));\n        }\n    }\n    traction *= h;\n}\n\n#define Q4__STRAIN_COMP 3\n\n/**\n * Calculates the stiffness matrix for the element, mutator\n * \n * @param [mat*] stiff Element stiffness matrix\n * @param [PlaneState] pState Plane state control\n * @return void\n */\nvoid Q4::mstiffness(mat &stiff, int pState = PSTRESS) \n{\n    assert(stiff.n_rows == Q4__DOF_PER_NODE*Q4__NUM_NODES);\n    assert(stiff.n_cols == Q4__DOF_PER_NODE*Q4__NUM_NODES);\n    \n    stiff.zeros();\n    Mat<int>::fixed<3,4> e;\n    e << 1 << 0 << 0 << 0 << endr\n      << 0 << 0 << 0 << 1 << endr\n      << 0 << 1 << 1 << 0 << endr;\n    unsigned int i, j, k, m;\n    double xi, eta, weightX, weightY, temp;\n    mat nStar = zeros<mat>(Q4__DOF_PER_NODE*Q4__DOF_PER_NODE,Q4__DOF_PER_NODE*\n                Q4__NUM_NODES);\n    mat jacobian(Q4__DOF_PER_NODE*Q4__DOF_PER_NODE,\n            Q4__DOF_PER_NODE*Q4__DOF_PER_NODE);\n    mat invJac(Q4__DOF_PER_NODE*Q4__DOF_PER_NODE,\n            Q4__DOF_PER_NODE*Q4__DOF_PER_NODE);\n    mat JE = zeros<mat>(Q4__DOF_PER_NODE*Q4__DOF_PER_NODE,\n        Q4__DOF_PER_NODE*Q4__DOF_PER_NODE);\n    mat B(Q4__STRAIN_COMP,Q4__DOF_PER_NODE*Q4__NUM_NODES);\n    mat C(Q4__STRAIN_COMP,Q4__STRAIN_COMP);\n    \n    /* TODO: separate this logic and material properties from element so that \n     *          the C matrix will not need calculated a billion times */\n    // PROB AN EXPENSIVE OPERATION, DO SOMETHING ABOUT THIS\n    switch (pState)\n    {\n        case PSTRESS:\n            C << 1 << v << 0 << endr\n              << v << 1 << 0 << endr\n              << 0 << 0 << (1-v)/2 << endr;\n            C *= E/(1-v*v);\n            break;\n        case PSTRAIN:\n            C << 1-v << v << 0 << endr\n              << v << 1-v << 0 << endr\n              << 0 << 0 << (1-2*v)/2 << endr;\n            C *= E/((1-v)*(1-2*v));\n            break;\n        default:\n            // TODO: IDK, FIX THIS I GUESS\n            cout << \"Cannot understand plane state\" << endl;\n            assert(0);\n    }\n    \n    /*\n     * calculate element stiffness matrix using gauss quadrature\n     */\n    for (i = 0; i < Q4::numPointsX; i++) \n    {\n        xi = Q4::gaussPoints[i];\n        weightX = Q4::weights[i];\n        /*\n         * create \"nStar\" matrix\n         */\n        for (j = 1; j < Q4__DOF_PER_NODE*Q4__DOF_PER_NODE; j+=2)\n        {\n            nStar(j,j/2) = Q4__dN1_deta(xi);\n            nStar(j,j/2+2) = Q4__dN2_deta(xi);\n            nStar(j,j/2+4) = Q4__dN3_deta(xi);\n            nStar(j,j/2+6) = Q4__dN4_deta(xi);\n        }\n        /*\n         * look up 'eta'\n         * look up weight in the y-direction\n         * calculate jacobian\n         * build JE matrix\n         * finish building nStar\n         */\n        for (j = 0; j < Q4::numPointsY; j++) \n        {\n            eta = Q4::gaussPoints[j];\n            weightY = Q4::weights[j];\n            jacobian = J(xi, eta);\n            invJac = inv(jacobian);\n            for (k = 0; k < Q4__DOF_PER_NODE; k++)\n            {\n                for (m = 0; m < Q4__DOF_PER_NODE; m++)\n                {\n                    temp = invJac(k,m);\n                    JE(k,m) = temp;\n                    JE(k+Q4__DOF_PER_NODE,m+Q4__DOF_PER_NODE) = temp;\n                }\n            }\n            \n            for (k = 0; k < Q4__DOF_PER_NODE*Q4__DOF_PER_NODE; k+=2)\n            {\n                nStar(k,k/2) = Q4__dN1_dxi(eta);\n                nStar(k,k/2+2) = Q4__dN2_dxi(eta);\n                nStar(k,k/2+4) = Q4__dN3_dxi(eta);\n                nStar(k,k/2+6) = Q4__dN4_dxi(eta);\n            }\n            // this is derived in class notes (Aquino)\n            B = e * JE * nStar;\n            stiff += weightX * weightY * trans(B) * C * B * det(jacobian);\n        }\n    }\n    stiff *= h;\n}\n\n//TODO implement Q4R element\n", "meta": {"hexsha": "2d28bcbc18ca27ca42c2a023ec4d4558b92b4e1e", "size": 10141, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/element.cpp", "max_stars_repo_name": "chalavadi/HELWFEM", "max_stars_repo_head_hexsha": "e6d5bc2c95d4de1638c680d079bc41a85cc784a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-16T02:03:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-16T02:03:27.000Z", "max_issues_repo_path": "src/element.cpp", "max_issues_repo_name": "chalavadi/HELWFEM", "max_issues_repo_head_hexsha": "e6d5bc2c95d4de1638c680d079bc41a85cc784a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/element.cpp", "max_forks_repo_name": "chalavadi/HELWFEM", "max_forks_repo_head_hexsha": "e6d5bc2c95d4de1638c680d079bc41a85cc784a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-16T02:03:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-16T02:03:28.000Z", "avg_line_length": 28.4859550562, "max_line_length": 100, "alphanum_fraction": 0.5818952766, "num_tokens": 3218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4190122124776902}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2015 Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#ifndef ROKKO_UTILITY_XYZ_HAMILTONIAN_MPI_HPP\n#define ROKKO_UTILITY_XYZ_HAMILTONIAN_MPI_HPP\n\n#include \"mpi.h\"\n#include <vector>\n#include <boost/tuple/tuple.hpp>\n\n#include <iostream>\n\n#include <rokko/distributed_matrix.hpp>\n#include <rokko/localized_matrix.hpp>\n\nnamespace rokko {\n\nnamespace xyz_hamiltonian {\n\nvoid multiply(const MPI_Comm& comm, int L, const std::vector<std::pair<int, int> >& lattice, const std::vector<boost::tuple<double, double, double> >& coupling, const double* v, double* w, double* buffer) {\n  int myrank, nproc;\n  MPI_Status status;\n  int ierr;\n\n  MPI_Comm_size(comm, &nproc);\n  MPI_Comm_rank(comm, &myrank);\n\n  int n = nproc;\n  int p = -1;\n  do {\n    n /= 2;\n    ++p;\n  } while (n > 0);\n\n  if (nproc != (1 << p)) {\n    if ( myrank == 0 ) {\n      std::cout << \"This program can be run only for powers of 2\" << std::endl;\n    }\n    MPI_Abort(comm, 1);\n  }\n  int N = 1 << (L-p);\n\n  for (int l=0; l<lattice.size(); ++l) {\n    int i = lattice[l].first;\n    int j = lattice[l].second;\n    double jx = coupling[l].get<0>();\n    double jy = coupling[l].get<1>();\n    double jz = coupling[l].get<2>();\n\n    double diag_plus = jz / 4.0;\n    double diag_minus = - jz / 4.0;\n    double offdiag_plus = (jx + jy) / 4.0;\n    double offdiag_minus = (jx - jy) / 4.0;\n\n    if (i < (L-p)) {\n      if (j < (L-p)) {\n        int m1 = 1 << i;\n        int m2 = 1 << j;\n        int m3 = m1 + m2;\n        for (int k=0; k<N; ++k) {\n          if (((k & m3) == m1) || ((k & m3) == m2)) {  // when (bit i == 1, bit j == 0) or (bit i == 0, bit j == 1)\n            w[k] += diag_minus * v[k] + offdiag_plus * v[k^m3];\n          } else {\n            w[k] += diag_plus * v[k] + offdiag_minus * v[k^m3];\n          }\n        }\n      } else {\n        int m = 1 << (j-(L-p));\n        MPI_Sendrecv(const_cast<double*>(&v[0]), N, MPI_DOUBLE,\n                     myrank ^ m, 0,\n                     &buffer[0], N, MPI_DOUBLE, \n                     myrank ^ m, 0,\n                     comm, &status);\n        int m1 = 1 << i;\n        if ((myrank & m) == m) { \n          for (int k=0; k<N; ++k) {\n            if ((k & m1) == m1) {\n              w[k] += diag_plus * v[k] + offdiag_minus * buffer[k^m1];\n            } else {\n              w[k] += diag_minus * v[k] + offdiag_plus * buffer[k^m1];\n            }\n          }\n        } else {\n          for (int k=0; k<N; ++k) {\n            if ((k & m1) == m1) {\n              w[k] += diag_minus * v[k] + offdiag_plus * buffer[k^m1];\n            } else {\n              w[k] += diag_plus * v[k] + offdiag_minus * buffer[k^m1];\n            }\n          }\n        }\n      }\n    } else {\n      if (j < (L-p)) {\n        int m = 1 << (i-(L-p));\n        MPI_Sendrecv(const_cast<double*>(&v[0]), N, MPI_DOUBLE,\n                     myrank ^ m, 0,\n                     &buffer[0], N, MPI_DOUBLE,\n                     myrank ^ m, 0,\n                     comm, &status);\n        int m1 = 1 << j;\n        if ((myrank & m) == m) {\n          for (int k=0; k<N; ++k) {\n            if ((k & m1) == m1) {\n              w[k] += diag_plus * v[k] + offdiag_minus * buffer[k^m1];\n            } else {\n              w[k] += diag_minus * v[k] + offdiag_plus * buffer[k^m1];\n            }\n          }\n        } else {\n          for (int k=0; k<N; ++k) {\n            if ((k & m1) == m1) {\n              w[k] += diag_minus * v[k] + offdiag_plus * buffer[k^m1];\n            } else {\n              w[k] += diag_plus * v[k] + offdiag_minus * buffer[k^m1];\n            }\n          }\n        }\n      } else {\n        int m = (1 << (i-(L-p))) + (1 << (j-(L-p)));\n        MPI_Sendrecv(const_cast<double*>(&v[0]), N, MPI_DOUBLE,\n                     myrank ^ m, 0,\n                     &buffer[0], N, MPI_DOUBLE,\n                     myrank ^ m, 0,\n                     comm, &status);\n        if (((myrank & m) != m) && ((myrank & m) != 0)) {\n          for (int k=0; k<N; ++k) {\n            w[k] += diag_minus * v[k] + offdiag_plus * buffer[k];\n          }\n        } else {\n          for (int k=0; k<N; ++k) {\n            w[k] += diag_plus * v[k] + offdiag_minus * buffer[k];\n          }\n        }\n      }\n    }\n  }\n}\n\nvoid multiply(const MPI_Comm& comm, int L, const std::vector<std::pair<int, int> >& lattice, const std::vector<boost::tuple<double, double, double> >& coupling, const std::vector<double>& v, std::vector<double>& w, std::vector<double>& buffer) {\n  multiply(comm, L, lattice, coupling, &v[0], &w[0], &buffer[0]);\n}\n\nvoid fill_diagonal(const MPI_Comm& comm, int L, const std::vector<std::pair<int, int> >& lattice, const std::vector<boost::tuple<double, double, double> >& coupling, double* w) {\n  int myrank, nproc;\n\n  MPI_Comm_size(comm, &nproc);\n  MPI_Comm_rank(comm, &myrank);\n\n  int n = nproc;\n  int p = -1;\n  do {\n    n /= 2;\n    ++p;\n  } while (n > 0);\n\n  if (nproc != (1 << p)) {\n    if ( myrank == 0 ) {\n      std::cout << \"This program can be run only for powers of 2\" << std::endl;\n    }\n    MPI_Abort(comm, 1);\n  }\n\n  int N_seq = 1 << L;\n  int N = 1 << (L-p);\n  int myrank_shift = myrank * N;\n  int nproc_shift = (nproc-1) * N;\n  int mask = N - 1;\n\n  for (int k=0; k<N; ++k) {\n    w[k] = 0;\n  }\n\n  for (int l=0; l<lattice.size(); ++l) {\n    int i = lattice[l].first;\n    int j = lattice[l].second;\n    double jx = coupling[l].get<0>();\n    double jy = coupling[l].get<1>();\n    double jz = coupling[l].get<2>();\n    double diag_plus = jz / 4.0;\n    double diag_minus = - jz / 4.0;\n    double offdiag_plus = (jx + jy) / 4.0;\n    double offdiag_minus = (jx - jy) / 4.0;\n\n    int m1 = 1 << i;\n    int m2 = 1 << j;\n    int m3 = m1 + m2;\n\n    for (int k=0; k<N_seq; ++k) {\n      if (myrank_shift == (k & nproc_shift)) {\n        if (((k & m3) == m1) || ((k & m3) == m2)) {  // when (bit i == 1, bit j == 0) or (bit i == 0, bit j == 1)\n          w[k & mask] += diag_minus;\n        } else {\n          w[k & mask] += diag_plus;\n        }        \n      }\n    }  // end for k\n  } // end for lattice\n}\n\nvoid fill_diagonal(const MPI_Comm& comm, int L, const std::vector<std::pair<int, int> >& lattice, const std::vector<boost::tuple<double, double, double> >& coupling, std::vector<double>& w) {\n  fill_diagonal(comm, L, lattice, coupling, &w[0]);\n}\n\ntemplate<typename T, typename MATRIX_MAJOR>\nvoid generate(int L, const std::vector<std::pair<int, int> >& lattice,\n  const std::vector<boost::tuple<double, double, double> >& coupling,\n  rokko::distributed_matrix<T, MATRIX_MAJOR>& mat) {\n  mat.set_zeros();\n  int N = 1 << L;\n  for (int l=0; l<lattice.size(); ++l) {\n    int i = lattice[l].first;\n    int j = lattice[l].second;\n    double jx = coupling[l].get<0>();\n    double jy = coupling[l].get<1>();\n    double jz = coupling[l].get<2>();\n    double diag_plus = jz / 4.0;\n    double diag_minus = - jz/ 4.0;\n    double offdiag_plus = (jx + jy) / 4.0;\n    double offdiag_minus = (jx - jy) / 4.0;\n\n    int m1 = 1 << i;\n    int m2 = 1 << j;\n    int m3 = m1 + m2;\n\n    for (int k=0; k<N; ++k) {\n      if (mat.is_gindex_mycol(k)) {\n        int local_k = mat.translate_g2l_col(k);\n        if (((k & m3) == m1) || ((k & m3) == m2)) {  // when (bit i == 1, bit j == 0) or (bit i == 0, bit j == 1)\n          if (mat.is_gindex_myrow(k^m3)) {\n            mat.update_local(mat.translate_g2l_row(k^m3), local_k, offdiag_plus);\n          }\n          if (mat.is_gindex_myrow(k)) {\n            mat.update_local(mat.translate_g2l_row(k), local_k, diag_minus);\n          }\n        } else {\n          if (mat.is_gindex_myrow(k^m3)) {\n            mat.update_local(mat.translate_g2l_row(k^m3), local_k, offdiag_minus);\n          }\n          if (mat.is_gindex_myrow(k)) {\n            mat.update_local(mat.translate_g2l_row(k), local_k, diag_plus);\n          }\n        }\n      }\n    }\n  }\n}\n\n// The following routine uses local indices.  It works correctly.\n/*\ntemplate <typename MATRIX_MAJOR>\nvoid generate(int L, const std::vector<std::pair<int, int> >& lattice, const std::vector<boost::tuple<double, double, double> >& coupling, rokko::distributed_matrix<MATRIX_MAJOR>& mat) {\n  mat.set_zeros();\n  int N = 1 << L;\n  for (int l=0; l<lattice.size(); ++l) {\n    int i = lattice[l].first;\n    int j = lattice[l].second;\n    double jx = coupling[l].get<0>();\n    double jy = coupling[l].get<1>();\n    double jz = coupling[l].get<2>();\n    double diag_plus = jz / 4.0;\n    double diag_minus = - jz/ 4.0;\n    double offdiag_plus = (jx + jy) / 4.0;\n    double offdiag_minus = (jx - jy) / 4.0;\n\n    int m1 = 1 << i;\n    int m2 = 1 << j;\n    int m3 = m1 + m2;\n    for(int local_i = 0; local_i < mat.get_m_local(); ++local_i) {\n      int k1 = mat.translate_l2g_row(local_i);\n      for(int local_j = 0; local_j < mat.get_n_local(); ++local_j) {\n        int k2 = mat.translate_l2g_col(local_j);\n        if (((k2 & m3) == m1) || ((k2 & m3) == m2)) {  // when (bit i == 1, bit j == 0) or (bit i == 0, bit j == 1)\n          if (k1 == (k2^m3)) {\n            mat.update_local(local_i, local_j, offdiag_plus);\n          }\n          if (k1 == k2) {\n            mat.update_local(local_i, local_j, diag_minus);\n          }\n        } else {\n          if (k1 == (k2^m3)) {\n            mat.update_local(local_i, local_j, offdiag_minus);\n          }\n          if (k1 == k2) {\n            //std::cout << \"k1=\" << k1 << \" k2=\" << k2 << std::endl;\n            mat.update_local(local_i, local_j, diag_plus);\n          }\n        }\n      }\n    }\n  }\n}\n*/\n\n} // namespace xyz_hamiltonian\n\n} // namespace rokko\n\n#endif // ROKKO_UTILITY_XYZ_HAMILTONIAN_MPI_HPP\n", "meta": {"hexsha": "95a33b5783645a02bade8dbbefac583b05c01244", "size": 9889, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rokko/utility/xyz_hamiltonian_mpi.hpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rokko/utility/xyz_hamiltonian_mpi.hpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rokko/utility/xyz_hamiltonian_mpi.hpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1071428571, "max_line_length": 245, "alphanum_fraction": 0.4978258671, "num_tokens": 3148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.41900550103040457}}
{"text": "#include <cmath>\n#include <algorithm>\n#include <numeric>\n#include <boost/unordered_map.hpp>\n#include <emmintrin.h>\n#include <immintrin.h>\n#include \"rchord_meanshift.hpp\"\n\n#include <iostream>\n\nstatic void _meanShiftIter(const std::vector<Eigen::Matrix3f> &votes,\n\t\t\t   const std::vector<float> &weights,\n\t\t\t   const Eigen::Matrix3f &guess, Eigen::Matrix3f &mode,  float b);\nstatic void _RChordMeanShift(const std::vector<Eigen::Matrix3f> &votes,\n\t\t\t     const std::vector<float> &votesWeight,\n\t\t\t     const Eigen::Matrix3f &guess, Eigen::Matrix3f &mode,\n\t\t\t     float b, float stepSize, float stepThr, unsigned int nIterThr);\nstatic inline void _cvtVEuler2Rotm(const std::vector<Eigen::Vector3f> &votesEul,\n\t\t\t\t   std::vector<Eigen::Matrix3f> &votesRotm);\nstatic inline void _cvtVRotm2Euler(const std::vector<Eigen::Matrix3f> &votesRotm,\n\t\t\t\t   std::vector<Eigen::Vector3f> &votesEul);\nstatic inline void _cvtEuler2Rotm(const Eigen::Vector3f &voteEul, Eigen::Matrix3f &voteRotm);\nstatic inline void _cvtRotm2Euler(const Eigen::Matrix3f &voteRotm, Eigen::Vector3f &voteEul);\nstatic inline float _rotmDist2(const Eigen::Matrix3f &m1, const Eigen::Matrix3f &m2);\n\n\n\nvoid RChordMeanShift(const std::vector<Eigen::Vector3f> &votes,\n\t\t     const std::vector<float> &votesWeight,\n\t\t     const Eigen::Vector3f &guess, Eigen::Vector3f &mode,\n\t\t     float b, float stepSize, float stepThr, unsigned int nIterThr)\n{\n  std::vector<Eigen::Matrix3f> votesRotm(votes.size());\n  Eigen::Matrix3f guessRotm, modeRotm;\n\n  _cvtVEuler2Rotm(votes, votesRotm);\n  _cvtEuler2Rotm(guess, guessRotm);\n\n  _RChordMeanShift(votesRotm, votesWeight, guessRotm, modeRotm,\n\t\t   b, stepSize, stepThr, nIterThr);\n\n  _cvtRotm2Euler(modeRotm, mode);\n}\n\n\n\nstatic void _RChordMeanShift(const std::vector<Eigen::Matrix3f> &votes,\n\t\t\t     const std::vector<float> &votesWeight,\n\t\t\t     const Eigen::Matrix3f &guess, Eigen::Matrix3f &mode,\n\t\t\t     float b, float stepSize, float stepThr, unsigned int nIterThr)\n{\n  Eigen::Matrix3f currGuess = guess;\n  \n  for (int i=0; i<nIterThr; i++)\n  {\n    Eigen::Matrix3f m;\n    float dist;\n    \n    _meanShiftIter(votes, votesWeight, currGuess, m, b);\n    dist = _rotmDist2(currGuess, m);\n    \n    // Move to the meanshift mode by stepSize. Use quaternion interpolation to\n    // rotate towards the target rotation.\n    Eigen::Quaternion<float> q1(currGuess);\n    Eigen::Quaternion<float> q2(m);\n\n    currGuess = q1.slerp(stepSize, q2);\n    if (dist<stepThr*stepThr) break;\n  }\n  mode = currGuess;\n}\n\n\nstruct CmpIdxByWeight\n{\n  const std::vector<float> *w;\n  CmpIdxByWeight(const std::vector<float> &w):w(&w){};\n  bool operator() (unsigned int i1, unsigned int i2) const {return w->at(i1)>w->at(i2);}\n};\n\nstruct CmpIdxByNGuess\n{\n  const std::vector<int> *nGuess;\n  CmpIdxByNGuess(const std::vector<int> &nGuess):nGuess(&nGuess){};\n  bool operator() (unsigned int i1, unsigned int i2) const {return nGuess->at(i1)>nGuess->at(i2);}\n};\n\nunsigned int  MultiGuessRChordMeanShift(const std::vector<Eigen::Vector3f> &votes,\n\t\t\t\t\tconst std::vector<float> &votesWeight,\n\t\t\t\t\tconst std::vector<Eigen::Vector3f> guesses,\n\t\t\t\t\tstd::vector<Eigen::Vector3f> &modes,\n\t\t\t\t\tstd::vector<int> &guessModeID,\n\t\t\t\t\tfloat b, float stepSize, float stepThr,\n\t\t\t\t\tunsigned int nIterThr, float sameModeThr)\n{\n  std::vector<Eigen::Matrix3f> vRotm(votes.size());\n  std::vector<Eigen::Matrix3f> gRotm(guesses.size());\n  std::vector<Eigen::Matrix3f> mRotm(guesses.size());\n  std::vector<Eigen::Matrix3f> cRotm;\n  std::vector<int> cNGuess;\n  unsigned int nCModes=1;\n\n  _cvtVEuler2Rotm(votes, vRotm);\n  _cvtVEuler2Rotm(guesses, gRotm);\n\n  #pragma omp parallel for\n  for (int i=0; i<gRotm.size(); i++)\n  {\n    _RChordMeanShift(vRotm, votesWeight,\n\t\t     gRotm.at(i), mRotm.at(i),\n\t\t     b, stepSize, stepThr, nIterThr);\n  }\n\n  // Greedy clustering of modes (count how many guesses reach each mode as weel)\n  cRotm.push_back(mRotm.at(0));\n  cNGuess.push_back(1);\n  guessModeID.at(0) = 0;\n  for (int i=1; i<mRotm.size(); i++)\n  {\n    bool newMode = true;\n    for (int j=0; j<nCModes; j++)\n    {\n      if (_rotmDist2(mRotm.at(i), cRotm.at(j))<sameModeThr*sameModeThr)\n      {\n\tcNGuess.at(j)++;\n\tguessModeID.at(i) = j;\n\tnewMode = false;\n\tbreak;\n      }\n    }\n    if (newMode)\n    {\n      cRotm.push_back(mRotm.at(i));\n      cNGuess.push_back(1);\n      guessModeID.at(i) = nCModes;\n      nCModes++;\n    }\n  }\n\n  // Sort the modes by the number of guesses that converged to it\n  std::vector<unsigned int> idx;\n  for (unsigned int i=0; i<nCModes; i++) idx.push_back(i);\n  if (idx.size()>1) std::sort(idx.begin(), idx.end(), CmpIdxByNGuess(cNGuess));\n\n  int outNModes = std::min(nCModes, static_cast<unsigned int>(modes.size()));\n  for (int i=0; i<outNModes; i++)\n  {\n    _cvtRotm2Euler(cRotm.at(idx[i]), modes.at(i));\n  }\n\n  // Update the mode id for votes that reached the current node\n  // Note: Set the mode id to -1 if the guess reached a discarded mode\n  boost::unordered_map<int, int> sortedModeIDMap;\n  for (int i=0; i<nCModes; i++) sortedModeIDMap[idx[i]] = (i<outNModes) ? i : -1;\n  for (int i=0; i<votes.size(); i++) guessModeID.at(i) = sortedModeIDMap.at(guessModeID.at(i));\n\n  return outNModes;\n}\n\n\n\nvoid _meanShiftIter(const std::vector<Eigen::Matrix3f> &votes,\n\t\t    const std::vector<float> &weights,\n\t\t    const Eigen::Matrix3f &guess, Eigen::Matrix3f &mode, float b)\n{\n  Eigen::Matrix3f sumR = Eigen::Matrix3f::Zero();\n  \n  // Weighted sum of rotations\n  for (int i=0; i<votes.size(); i++)\n  {\n    // Compute the current vote weight (i.e. provided weight multiplied by Guassian kernel\n    // on chordal quaternion distance (i.e. Euclidean norm of R3 representation))\n    float w = weights.at(i) * exp(-_rotmDist2(guess, votes.at(i))/(b*b));\n    /*\n    Eigen::Quaternion<float> q1(guess);\n    Eigen::Quaternion<float> q2(votes.at(i));\n    float dist = q1.angularDistance(q2);\n    float w = weights.at(i) * exp(-(dist*dist)/(b*b));\n    */\n    sumR += w*votes.at(i);\n  }\n  \n  // Compute the average rotation as in\n  // Hartley, Richard, et al. \"Rotation averaging.\" International journal of computer vision 103.3 (2013): 267-305.\n  Eigen::JacobiSVD<Eigen::Matrix3f> SVDR(sumR, Eigen::ComputeFullU|Eigen::ComputeFullV);\n  mode = SVDR.matrixU()*SVDR.matrixV().transpose();\n  if (mode.determinant()<0)\n  {\n    mode = SVDR.matrixU()*Eigen::Vector3f(1,1,-1).asDiagonal()*SVDR.matrixV().transpose();\n  }\n}\n\n\n\nvoid _cvtVEuler2Rotm(const std::vector<Eigen::Vector3f> &votesEul,\n\t\t    std::vector<Eigen::Matrix3f> &votesRotm)\n{\n  for (int i=0; i<votesEul.size(); i++)\n  {\n    const Eigen::Vector3f &currVoteEul = votesEul.at(i);\n    Eigen::Matrix3f &currVoteRotm = votesRotm.at(i);\n    _cvtEuler2Rotm(currVoteEul, currVoteRotm);\n  }\n}\n\nvoid _cvtVRotm2Euler(const std::vector<Eigen::Matrix3f> &votesRotm,\n\t\t    std::vector<Eigen::Vector3f> &votesEul)\n{\n  for (int i=0; i<votesEul.size(); i++)\n  {\n    const Eigen::Matrix3f &currVoteRotm = votesRotm.at(i);\n    Eigen::Vector3f &currVoteEul = votesEul.at(i);\n    _cvtRotm2Euler(currVoteRotm, currVoteEul);\n  }\n}\n\nvoid _cvtEuler2Rotm(const Eigen::Vector3f &voteEul, Eigen::Matrix3f &voteRotm)\n{\n  voteRotm = Eigen::AngleAxisf(voteEul.x(), Eigen::Vector3f::UnitZ()) * \n             Eigen::AngleAxisf(voteEul.y(), Eigen::Vector3f::UnitY()) * \n             Eigen::AngleAxisf(voteEul.z(), Eigen::Vector3f::UnitX());\n}\n\nvoid _cvtRotm2Euler(const Eigen::Matrix3f &voteRotm, Eigen::Vector3f &voteEul)\n{\n  voteEul = voteRotm.eulerAngles(2,1,0);\n}\n\n\nfloat _rotmDist2(const Eigen::Matrix3f &m1, const Eigen::Matrix3f &m2)\n{\n  Eigen::Matrix3f rotDiff = m1-m2;\n  return rotDiff.cwiseProduct(rotDiff).sum();\n}\n", "meta": {"hexsha": "13ed30427495656d7b4e2213a7e73afad9dbbe04", "size": 7602, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mean_shift/rchord_meanshift.cpp", "max_stars_repo_name": "mUogoro/hand_rotation_estimation_tutorial", "max_stars_repo_head_hexsha": "98707de67448016e63bb8480090e4fa139dbc896", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T01:05:09.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T01:05:09.000Z", "max_issues_repo_path": "src/mean_shift/rchord_meanshift.cpp", "max_issues_repo_name": "mUogoro/hand_rotation_estimation_tutorial", "max_issues_repo_head_hexsha": "98707de67448016e63bb8480090e4fa139dbc896", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mean_shift/rchord_meanshift.cpp", "max_forks_repo_name": "mUogoro/hand_rotation_estimation_tutorial", "max_forks_repo_head_hexsha": "98707de67448016e63bb8480090e4fa139dbc896", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-11-08T09:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T07:57:45.000Z", "avg_line_length": 32.3489361702, "max_line_length": 115, "alphanum_fraction": 0.6806103657, "num_tokens": 2454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.41900549533227044}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/make_shared.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <Eigen/Core>\n\n#include <tudat/astro/basic_astro/physicalConstants.h>\n#include <tudat/basics/testMacros.h>\n#include <tudat/math/basic/mathematicalConstants.h>\n#include \"tudat/astro/basic_astro/unitConversions.h\"\n#include <tudat/astro/basic_astro/orbitalElementConversions.h>\n#include \"tudat/astro/gravitation/librationPoint.h\"\n#include \"tudat/astro/gravitation/unitConversionsCircularRestrictedThreeBodyProblem.h\"\n#include \"tudat/simulation/propagation_setup/propagationCR3BPFullProblem.h\"\n\n#include <tudat/simulation/simulation.h>\n#include <tudat/io/basicInputOutput.h>\n#include <tudat/io/applicationOutput.h>\n#include \"tudat/astro/ephemerides/approximatePlanetPositions.h\"\n#include \"tudat/astro/gravitation/unitConversionsCircularRestrictedThreeBodyProblem.h\"\n\n\nint main( )\n{\n    using namespace tudat;\n    using namespace tudat::input_output;\n    using namespace tudat::simulation_setup;\n\n    spice_interface::loadStandardSpiceKernels( );\n\n\n    // Global characteristics of the problem\n    double distanceSunJupiter = 778.0e9;\n\n    // Initialise the spacecraft state (B. Taylor, D. (1981). Horseshoe periodic orbits in the restricted problem of three bodies\n    // for a sun-Jupiter mass ratio. Astronomy and Astrophysics. 103. 288-294.)\n    Eigen::Vector6d initialState = Eigen::Vector6d::Zero();\n    initialState[0] = - 7.992e11;\n    initialState[4] =  -1.29e4;\n\n    // Create integrator settings.\n    double initialTime = 0.0;\n    const double fixedStepSize = 100000.0;\n    std::shared_ptr< numerical_integrators::IntegratorSettings< > > integratorSettings =\n            std::make_shared < numerical_integrators::IntegratorSettings < > >\n            ( numerical_integrators::rungeKutta4, initialTime, fixedStepSize );\n\n    // Create system of bodies.\n    std::vector < std::string > bodiesCR3BP;\n    bodiesCR3BP.push_back( \"Sun\" );\n    bodiesCR3BP.push_back( \"Jupiter\" );\n\n    // Define propagator settings variables.\n    std::vector< std::string > bodiesToPropagate;\n    std::vector< std::string > centralBodies;\n    bodiesToPropagate.push_back( \"Spacecraft\" );\n    centralBodies.push_back( \"SSB\" );\n\n    // Define final time for the propagation.\n    double gravitationalParameterSun = createGravityFieldModel(\n                getDefaultGravityFieldSettings(\n                    \"Sun\", TUDAT_NAN, TUDAT_NAN ), \"Sun\" )->getGravitationalParameter( );\n    double gravitationalParameterJupiter = createGravityFieldModel(\n                getDefaultGravityFieldSettings(\n                    \"Jupiter\", TUDAT_NAN, TUDAT_NAN ), \"Jupiter\" )->getGravitationalParameter( );\n    double finalTime = tudat::circular_restricted_three_body_problem::convertDimensionlessTimeToDimensionalTime(\n                29.2386 * ( 2.0 * mathematical_constants::PI ), gravitationalParameterSun, gravitationalParameterJupiter, distanceSunJupiter);\n\n    SystemOfBodies idealBodyMap = propagators::setupBodyMapCR3BP(\n                distanceSunJupiter, \"Sun\", \"Jupiter\", \"Spacecraft\" );\n\n    std::map< double, Eigen::Vector6d> fullPropagation;\n    std::map< double, Eigen::Vector6d> cr3bpPropagation;\n\n    /// Ideal case: full dynamics problem with the CR3BP assumtions\n    {\n\n\n        // Create acceleration map.\n        basic_astrodynamics::AccelerationMap accelerationModelMap = propagators::setupAccelerationMapCR3BP(\n                    \"Sun\", \"Jupiter\", bodiesToPropagate.at( 0 ), centralBodies.at( 0 ), idealBodyMap );\n\n        // Calculate the difference between CR3BP and full problem.\n        propagators::propagateCR3BPAndFullDynamicsProblem(\n                    initialTime, finalTime, initialState, integratorSettings, accelerationModelMap,\n                    bodiesToPropagate, centralBodies, idealBodyMap, bodiesCR3BP, fullPropagation,\n                    cr3bpPropagation );\n\n        Eigen::Vector6d stateDifference =\n                fullPropagation.rbegin( )->second - cr3bpPropagation.rbegin( )->second;\n\n        std::cout << \"state difference at final time: \" << stateDifference << std::endl;\n    }\n\n\n    std::map< double, Eigen::Vector6d> fullPropagationPerturbedCase;\n    std::map< double, Eigen::Vector6d> cr3bpPropagationPerturbedCase;\n\n    /// Perturbed case\n    {\n\n        std::string frameOrigin = \"SSB\";\n        std::string frameOrientation = \"ECLIPJ2000\";\n\n        SystemOfBodies perturbedBodyMap;\n\n\n        std::vector< std::string > additionalBodies = { \"Earth\", \"Mars\", \"Venus\", \"Saturn\" };\n        for( unsigned int i = 0; i < additionalBodies.size( ); i++ )\n        {\n\n            perturbedBodyMap[ additionalBodies.at( i ) ] = std::make_shared< Body >( );\n            perturbedBodyMap[ additionalBodies.at( i ) ]->setEphemeris(\n                        std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                                additionalBodies.at( i ) ) );\n            perturbedBodyMap[ additionalBodies.at( i ) ]->setGravityFieldModel(\n                        createGravityFieldModel(\n                            std::make_shared< CentralGravityFieldSettings >(\n                                spice_interface::getBodyGravitationalParameter(\n                                    additionalBodies.at( i ) ) ), additionalBodies.at( i ) ) );\n        }\n\n        perturbedBodyMap[ \"Sun\" ] = idealBodyMap[ \"Sun\" ];\n        perturbedBodyMap[ \"Jupiter\" ] = idealBodyMap[ \"Jupiter\" ];\n\n\n        // Create the body to be propagated.\n        perturbedBodyMap[ \"Spacecraft\" ] = std::make_shared< Body >( );\n        perturbedBodyMap[ \"Spacecraft\" ]->setEphemeris( std::make_shared< ephemerides::TabulatedCartesianEphemeris< > >(\n                                                            std::shared_ptr< interpolators::OneDimensionalInterpolator\n                                                            < double, Eigen::Vector6d > >( ), \"SSB\", frameOrientation ) );\n\n        setGlobalFrameBodyEphemerides( perturbedBodyMap, frameOrigin, frameOrientation );\n\n\n        // Set of accelerations experienced by the spacecraft.\n        std::map< std::string, std::vector< std::shared_ptr< AccelerationSettings > > > bodyToPropagateAccelerations;\n        bodyToPropagateAccelerations[\"Sun\"].push_back(std::make_shared< AccelerationSettings >(\n                                                          basic_astrodynamics::central_gravity ) );\n        bodyToPropagateAccelerations[\"Jupiter\"].push_back(std::make_shared< AccelerationSettings >(\n                                                              basic_astrodynamics::central_gravity ) );\n        bodyToPropagateAccelerations[\"Earth\"].push_back(std::make_shared< AccelerationSettings >(\n                                                            basic_astrodynamics::central_gravity ) );\n        bodyToPropagateAccelerations[\"Mars\"].push_back(std::make_shared< AccelerationSettings >(\n                                                           basic_astrodynamics::central_gravity ) );\n        bodyToPropagateAccelerations[\"Venus\"].push_back(std::make_shared< AccelerationSettings >(\n                                                            basic_astrodynamics::central_gravity ) );\n        bodyToPropagateAccelerations[\"Saturn\"].push_back(std::make_shared< AccelerationSettings >(\n                                                             basic_astrodynamics::central_gravity ) );\n\n        SelectedAccelerationMap accelerationMap;\n        accelerationMap[ \"Spacecraft\" ] = bodyToPropagateAccelerations;\n\n\n        // Create the acceleration map.\n        basic_astrodynamics::AccelerationMap accelerationModelMapPerturbedCase = createAccelerationModelsMap(\n                    perturbedBodyMap, accelerationMap, bodiesToPropagate, centralBodies );\n\n\n        // Calculate the difference between CR3BP and full problem.\n        propagators::propagateCR3BPAndFullDynamicsProblem(\n                    initialTime, finalTime, initialState, integratorSettings,\n                    accelerationModelMapPerturbedCase,\n                    bodiesToPropagate, centralBodies, perturbedBodyMap, bodiesCR3BP,\n                    fullPropagationPerturbedCase,\n                    cr3bpPropagationPerturbedCase );\n\n        Eigen::Vector6d stateDifferencePerturbedCase =\n                fullPropagationPerturbedCase.rbegin( )->second - cr3bpPropagationPerturbedCase.rbegin( )->second;\n\n        std::cout << \"state difference at final time for the perturbed case: \" << stateDifferencePerturbedCase << std::endl;\n\n    }\n\n    /// Ouputs\n\n    // Outputs for the ideal case\n    {\n        std::map< double, Eigen::Vector6d > fullPropagationNormalisedCoRotatingFrame;\n        for( std::map< double, Eigen::Vector6d >::iterator itr = fullPropagation.begin( );\n             itr != fullPropagation.end( ); itr++ ){\n            fullPropagationNormalisedCoRotatingFrame[ itr->first ] = tudat::circular_restricted_three_body_problem::convertCartesianToCorotatingNormalizedCoordinates(\n                        gravitationalParameterSun, gravitationalParameterJupiter, distanceSunJupiter, itr->second, itr->first);\n        }\n\n        std::map< double, Eigen::Vector6d > cr3bpNormalisedCoRotatingFrame;\n        for( std::map< double, Eigen::Vector6d >::iterator itr = cr3bpPropagation.begin( );\n             itr != cr3bpPropagation.end( ); itr++ ){\n            cr3bpNormalisedCoRotatingFrame[ itr->first ] = tudat::circular_restricted_three_body_problem::convertCartesianToCorotatingNormalizedCoordinates(\n                        gravitationalParameterSun, gravitationalParameterJupiter, distanceSunJupiter, itr->second, itr->first);\n        }\n\n\n        input_output::writeDataMapToTextFile( fullPropagation,\n                                              \"fullProblemPropagation.dat\",\n                                              tudat_applications::getOutputPath( ),\n                                              \"\",\n                                              std::numeric_limits< double >::digits10,\n                                              std::numeric_limits< double >::digits10,\n                                              \",\" );\n\n        input_output::writeDataMapToTextFile( fullPropagationNormalisedCoRotatingFrame,\n                                              \"fullProblemPropagationNormalisedCoRotatingFrame.dat\",\n                                              tudat_applications::getOutputPath( ),\n                                              \"\",\n                                              std::numeric_limits< double >::digits10,\n                                              std::numeric_limits< double >::digits10,\n                                              \",\" );\n\n        input_output::writeDataMapToTextFile( cr3bpPropagation,\n                                              \"CR3BPsolution.dat\",\n                                              tudat_applications::getOutputPath( ),\n                                              \"\",\n                                              std::numeric_limits< double >::digits10,\n                                              std::numeric_limits< double >::digits10,\n                                              \",\" );\n\n        input_output::writeDataMapToTextFile( cr3bpNormalisedCoRotatingFrame,\n                                              \"CR3BPnormalisedCoRotatingFrame.dat\",\n                                              tudat_applications::getOutputPath( ),\n                                              \"\",\n                                              std::numeric_limits< double >::digits10,\n                                              std::numeric_limits< double >::digits10,\n                                              \",\" );\n    }\n\n    // Outputs for the perturbed case\n    {\n        std::map< double, Eigen::Vector6d > fullPropagationNormalisedCoRotatingFramePerturbedCase;\n        for( std::map< double, Eigen::Vector6d >::iterator itr = fullPropagationPerturbedCase.begin( );\n             itr != fullPropagationPerturbedCase.end( ); itr++ ){\n            fullPropagationNormalisedCoRotatingFramePerturbedCase[ itr->first ] = tudat::circular_restricted_three_body_problem::\n                    convertCartesianToCorotatingNormalizedCoordinates(gravitationalParameterSun, gravitationalParameterJupiter,\n                                                                      distanceSunJupiter, itr->second, itr->first);\n        }\n\n        std::map< double, Eigen::Vector6d > cr3bpNormalisedCoRotatingFramePerturbedCase;\n        for( std::map< double, Eigen::Vector6d >::iterator itr = cr3bpPropagationPerturbedCase.begin( );\n             itr != cr3bpPropagationPerturbedCase.end( ); itr++ ){\n            cr3bpNormalisedCoRotatingFramePerturbedCase[ itr->first ] = tudat::circular_restricted_three_body_problem::\n                    convertCartesianToCorotatingNormalizedCoordinates(\n                        gravitationalParameterSun, gravitationalParameterJupiter, distanceSunJupiter, itr->second, itr->first);\n        }\n\n\n        input_output::writeDataMapToTextFile( fullPropagationPerturbedCase,\n                                              \"fullProblemPropagationPerturbedCase.dat\",\n                                              tudat_applications::getOutputPath( ),\n                                              \"\",\n                                              std::numeric_limits< double >::digits10,\n                                              std::numeric_limits< double >::digits10,\n                                              \",\" );\n\n        input_output::writeDataMapToTextFile( fullPropagationNormalisedCoRotatingFramePerturbedCase,\n                                              \"fullProblemPropagationNormalisedCoRotatingFramePerturbedCase.dat\",\n                                              tudat_applications::getOutputPath( ),\n                                              \"\",\n                                              std::numeric_limits< double >::digits10,\n                                              std::numeric_limits< double >::digits10,\n                                              \",\" );\n\n        input_output::writeDataMapToTextFile( cr3bpPropagationPerturbedCase,\n                                              \"CR3BPsolutionPerturbedCase.dat\",\n                                              tudat_applications::getOutputPath( ),\n                                              \"\",\n                                              std::numeric_limits< double >::digits10,\n                                              std::numeric_limits< double >::digits10,\n                                              \",\" );\n\n        input_output::writeDataMapToTextFile( cr3bpNormalisedCoRotatingFramePerturbedCase,\n                                              \"CR3BPnormalisedCoRotatingFramePerturbedCase.dat\",\n                                              tudat_applications::getOutputPath( ),\n                                              \"\",\n                                              std::numeric_limits< double >::digits10,\n                                              std::numeric_limits< double >::digits10,\n                                              \",\" );\n    }\n\n    // Final statement.\n    // The exit code EXIT_SUCCESS indicates that the program was successfully executed.\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "e4b270f8f46b35b9278534136e283a9a79479f6d", "size": 15678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tudat/satellite_propagation/fullPropagationSpacecraftCR3BP.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/tudat/satellite_propagation/fullPropagationSpacecraftCR3BP.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tudat/satellite_propagation/fullPropagationSpacecraftCR3BP.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.6917808219, "max_line_length": 166, "alphanum_fraction": 0.5847684654, "num_tokens": 3170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859598, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.41896197029837495}}
{"text": "\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <thread>\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <Eigen/Dense>\n\n#include <stdio.h>  \n\n#include \"patch.h\"\n\nusing std::cout;\nusing std::endl;\nusing std::vector;\n\nnamespace OFC\n{\n  \n  typedef __v4sf v4sf;\n\n  PatClass::PatClass(\n    const camparam* cpt_in,\n    const camparam* cpo_in,\n    const optparam* op_in,\n    const int patchid_in)\n  : \n    cpt(cpt_in),\n    cpo(cpo_in),\n    op(op_in),\n    patchid(patchid_in)\n{\n  pc = new patchstate;\n  CreateStatusStruct(pc);\n\n  tmp.resize(op->novals,1);\n  dxx_tmp.resize(op->novals,1);\n  dyy_tmp.resize(op->novals,1);\n}\n\nvoid PatClass::CreateStatusStruct(patchstate * psin)\n{\n  // get reference / template patch\n  psin->pdiff.resize(op->novals,1);\n  psin->pweight.resize(op->novals,1);\n}\n\nPatClass::~PatClass()\n{\n  delete pc;\n}\n\nvoid PatClass::InitializePatch(Eigen::Map<const Eigen::MatrixXf> * im_ao_in, Eigen::Map<const Eigen::MatrixXf> * im_ao_dx_in, Eigen::Map<const Eigen::MatrixXf> * im_ao_dy_in, const Eigen::Vector2f pt_ref_in)\n{\n  im_ao = im_ao_in;\n  im_ao_dx = im_ao_dx_in;\n  im_ao_dy = im_ao_dy_in;\n\n  pt_ref = pt_ref_in;\n  ResetPatch();\n\n  getPatchStaticNNGrad(im_ao->data(), im_ao_dx->data(), im_ao_dy->data(), &pt_ref, &tmp, &dxx_tmp, &dyy_tmp);\n\n  ComputeHessian();\n}\n\nvoid PatClass::ComputeHessian()\n{\n  #if (SELECTMODE==1)\n  pc->Hes(0,0) = (dxx_tmp.array() * dxx_tmp.array()).sum();\n  pc->Hes(0,1) = (dxx_tmp.array() * dyy_tmp.array()).sum();\n  pc->Hes(1,1) = (dyy_tmp.array() * dyy_tmp.array()).sum();\n  pc->Hes(1,0) = pc->Hes(0,1);\n  if (pc->Hes.determinant()==0)\n  {\n    pc->Hes(0,0)+=1e-10;\n    pc->Hes(1,1)+=1e-10;\n  }\n  #else\n  pc->Hes(0,0) = (dxx_tmp.array() * dxx_tmp.array()).sum();\n  if (pc->Hes.sum()==0)\n    pc->Hes(0,0)+=1e-10;\n  #endif\n}\n\nvoid PatClass::SetTargetImage(Eigen::Map<const Eigen::MatrixXf> * im_bo_in, Eigen::Map<const Eigen::MatrixXf> * im_bo_dx_in, Eigen::Map<const Eigen::MatrixXf> * im_bo_dy_in)\n{\n  im_bo = im_bo_in;\n  im_bo_dx = im_bo_dx_in;\n  im_bo_dy = im_bo_dy_in;\n\n  ResetPatch();\n}\n\nvoid PatClass::ResetPatch()\n{ \n  pc->hasconverged=0; \n  pc->hasoptstarted=0; \n\n  pc->pt_st = pt_ref;\n  pc->pt_iter = pt_ref;\n\n  pc->p_in.setZero();\n  pc->p_iter.setZero();\n  pc->delta_p.setZero();    \n\n  pc->delta_p_sqnorm = 1e-10;\n  pc->delta_p_sqnorm_init = 1e-10; \n  pc->mares = 1e20;\n  pc->mares_old = 1e20;\n  pc->cnt=0;\n  pc->invalid = false;\n}\n\n#if (SELECTMODE==1)\nvoid PatClass::OptimizeStart(const Eigen::Vector2f p_in_arg)\n#else\nvoid PatClass::OptimizeStart(const Eigen::Matrix<float, 1, 1> p_in_arg)\n#endif\n{\n  pc->p_in   = p_in_arg;\n  pc->p_iter = p_in_arg;\n\n  // convert from input parameters to 2D query location(s) for patches\n  paramtopt();\n\n  // save starting location, only needed for outlier check\n  pc->pt_st = pc->pt_iter;\n\n  //Check if initial position is already invalid\n  if (pc->pt_iter[0] < cpt->tmp_lb  || pc->pt_iter[1] < cpt->tmp_lb ||    // check if patch left valid image region\n      pc->pt_iter[0] > cpt->tmp_ubw || pc->pt_iter[1] > cpt->tmp_ubh)  \n  {\n    pc->hasconverged=1;\n    pc->pdiff = tmp;\n    pc->hasoptstarted=1;\n  }\n  else\n  {\n    pc->cnt=0; // reset iteration counter\n    pc->delta_p_sqnorm = 1e-10;\n    pc->delta_p_sqnorm_init = 1e-10;  // set to arbitrary low value, s.t. that loop condition is definitely true on first iteration\n    pc->mares = 1e5;          // mean absolute residual\n    pc->mares_old = 1e20; // for rate of change, keep mares from last iteration in here. Set high so that loop condition is definitely true on first iteration\n    pc->hasconverged=0;\n\n    OptimizeComputeErrImg();\n    \n    pc->hasoptstarted=1;\n    pc->invalid = false;\n  }\n}\n\n#if (SELECTMODE==1)\nvoid PatClass::OptimizeIter(const Eigen::Vector2f p_in_arg, const bool untilconv)\n#else\nvoid PatClass::OptimizeIter(const Eigen::Matrix<float, 1, 1> p_in_arg, const bool untilconv)\n#endif  \n{\n  if (!pc->hasoptstarted)\n  {\n    ResetPatch(); \n    OptimizeStart(p_in_arg);  \n  }\n  int oldcnt=pc->cnt;\n\n  // optimize patch until convergence, or do only one iteration if DIS visualization is used\n  while (  ! (pc->hasconverged || (untilconv == false && (pc->cnt > oldcnt)))  ) \n  {\n    pc->cnt++;\n\n    // Projection onto sd_images\n    #if (SELECTMODE==1)\n      pc->delta_p[0] = (dxx_tmp.array() * pc->pdiff.array()).sum();\n      pc->delta_p[1] = (dyy_tmp.array() * pc->pdiff.array()).sum();\n    #else\n      pc->delta_p[0] = (dxx_tmp.array() * pc->pdiff.array()).sum();\n    #endif\n\n    pc->delta_p = pc->Hes.llt().solve(pc->delta_p); // solve linear system\n    \n    pc->p_iter -= pc->delta_p; // update flow vector\n    \n    #if (SELECTMODE==2) // if stereo depth\n    if (cpt->camlr==0)\n      pc->p_iter[0] = std::min(pc->p_iter[0],0.0f); // disparity in t can only be negative (in right image)\n    else\n      pc->p_iter[0] = std::max(pc->p_iter[0],0.0f); // ... positive (in left image)\n    #endif\n      \n    // compute patch locations based on new parameter vector\n    paramtopt(); \n      \n    // check if patch(es) moved too far from starting location, if yes, stop iteration and reset to starting location\n    if ((pc->pt_st - pc->pt_iter).norm() > op->outlierthresh  // check if query patch moved more than >padval from starting location -> most likely outlier\n        ||                  \n        pc->pt_iter[0] < cpt->tmp_lb  || pc->pt_iter[1] < cpt->tmp_lb ||    // check patch left valid image region\n        pc->pt_iter[0] > cpt->tmp_ubw || pc->pt_iter[1] > cpt->tmp_ubh)  \n    {\n      pc->p_iter = pc->p_in; // reset\n      paramtopt(); \n      pc->hasconverged=1;\n      pc->hasoptstarted=1;\n    }\n        \n    OptimizeComputeErrImg();\n  }\n}\n\ninline void PatClass::paramtopt()\n{\n    #if (SELECTMODE==1)   \n      pc->pt_iter = pt_ref + pc->p_iter;    // for optical flow the point displacement and the parameter vector are equivalent\n    #else\n      pc->pt_iter[0] = pt_ref[0] + pc->p_iter[0];\n    #endif\n}\n\nvoid PatClass::LossComputeErrorImage(Eigen::Matrix<float, Eigen::Dynamic, 1>* patdest, Eigen::Matrix<float, Eigen::Dynamic, 1>* wdest, const Eigen::Matrix<float, Eigen::Dynamic, 1>* patin,  const Eigen::Matrix<float, Eigen::Dynamic, 1>*  tmpin)\n{\n  v4sf * pd = (v4sf*) patdest->data(),\n       * pa = (v4sf*) patin->data(),  \n       * te = (v4sf*) tmpin->data(),\n       * pw = (v4sf*) wdest->data();\n\n  if (op->costfct==0) // L2 cost function\n  {\n    for (int i=op->novals/4; i--; ++pd, ++pa, ++te, ++pw)\n    {\n      (*pd) = (*pa)-(*te);  // difference image\n      (*pw) = __builtin_ia32_andnps(op->negzero,  (*pd) );\n    }\n  }\n  else if (op->costfct==1) // L1 cost function\n  {\n    for (int i=op->novals/4; i--; ++pd, ++pa, ++te, ++pw)\n    {\n      (*pd) = (*pa)-(*te);   // difference image\n      (*pd) = __builtin_ia32_orps( __builtin_ia32_andps(op->negzero,  (*pd) )  , __builtin_ia32_sqrtps (__builtin_ia32_andnps(op->negzero,  (*pd) )) );  // sign(pdiff) * sqrt(abs(pdiff))\n      (*pw) = __builtin_ia32_andnps(op->negzero,  (*pd) );\n    }\n  }\n  else if (op->costfct==2) // Pseudo Huber cost function\n  {\n    for (int i=op->novals/4; i--; ++pd, ++pa, ++te, ++pw)\n    {\n      (*pd) = (*pa)-(*te);   // difference image\n      (*pd) = __builtin_ia32_orps(__builtin_ia32_andps(op->negzero,  (*pd) ), \n                                  __builtin_ia32_sqrtps (\n                                    __builtin_ia32_mulps(                                                                                         // PSEUDO HUBER NORM\n                                          __builtin_ia32_sqrtps (op->ones + __builtin_ia32_divps(__builtin_ia32_mulps((*pd),(*pd)) , op->normoutlier_tmpbsq)) - op->ones, // PSEUDO HUBER NORM \n                                          op->normoutlier_tmp2bsq)                                                                                                // PSEUDO HUBER NORM\n                                     )\n                                    ); // sign(pdiff) * sqrt( 2*b^2*( sqrt(1+abs(pdiff)^2/b^2)+1)  )) // <- looks like this without SSE instruction\n      (*pw) = __builtin_ia32_andnps(op->negzero,  (*pd) );                                    \n    }\n  }\n}\n\nvoid PatClass::OptimizeComputeErrImg()\n{\n  getPatchStaticBil(im_bo->data(), &(pc->pt_iter), &(pc->pdiff));\n\n  // Get photometric patch error\n  LossComputeErrorImage(&pc->pdiff, &pc->pweight, &pc->pdiff, &tmp);\n\n  // Compute step norm\n  pc->delta_p_sqnorm = pc->delta_p.squaredNorm();\n  if (pc->cnt==1)\n    pc->delta_p_sqnorm_init = pc->delta_p_sqnorm;\n\n  // Check early termination criterions\n  pc->mares_old = pc->mares;\n  pc->mares = pc->pweight.lpNorm<1>() / (op->novals);\n  if ( !  ((pc->cnt < op->max_iter) &  (pc->mares  > op->res_thresh) &  \n          ((pc->cnt < op->min_iter) |  (pc->delta_p_sqnorm / pc->delta_p_sqnorm_init >= op->dp_thresh)) &\n          ((pc->cnt < op->min_iter) |  (pc->mares / pc->mares_old <= op->dr_thresh)))  )\n    pc->hasconverged=1;\n        \n}\n\n// Extract patch on integer position, and gradients, No Bilinear interpolation\nvoid PatClass::getPatchStaticNNGrad(const float* img, const float* img_dx, const float* img_dy, \n                    const Eigen::Vector2f* mid_in, \n                    Eigen::Matrix<float, Eigen::Dynamic, 1>* tmp_in_e,  \n                    Eigen::Matrix<float, Eigen::Dynamic, 1>*  tmp_dx_in_e, \n                    Eigen::Matrix<float, Eigen::Dynamic, 1>* tmp_dy_in_e)\n{\n  float *tmp_in    = tmp_in_e->data();\n  float *tmp_dx_in = tmp_dx_in_e->data();\n  float *tmp_dy_in = tmp_dy_in_e->data();\n  \n  Eigen::Vector2i pos;\n  Eigen::Vector2i pos_it;\n  \n  pos[0] = round((*mid_in)[0]) + cpt->imgpadding;\n  pos[1] = round((*mid_in)[1]) + cpt->imgpadding;\n    \n  int posxx = 0;\n\n  int lb = -op->p_samp_s/2;\n  int ub = op->p_samp_s/2-1;  \n\n  for (int j=lb; j <= ub; ++j)    \n  {\n    for (int i=lb; i <= ub; ++i, ++posxx)\n    {\n      pos_it[0] = pos[0]+i;      \n      pos_it[1] = pos[1]+j;\n      int idx = pos_it[0] + pos_it[1] * cpt->tmp_w;\n\n      #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)  // Single channel\n      tmp_in[posxx] = img[idx];\n      tmp_dx_in[posxx] = img_dx[idx];\n      tmp_dy_in[posxx] = img_dy[idx];\n      #else  // 3 RGB channels\n      idx *= 3;\n      tmp_in[posxx] = img[idx]; tmp_dx_in[posxx] = img_dx[idx]; tmp_dy_in[posxx] = img_dy[idx]; ++posxx; ++idx;\n      tmp_in[posxx] = img[idx]; tmp_dx_in[posxx] = img_dx[idx]; tmp_dy_in[posxx] = img_dy[idx]; ++posxx; ++idx;\n      tmp_in[posxx] = img[idx]; tmp_dx_in[posxx] = img_dx[idx]; tmp_dy_in[posxx] = img_dy[idx];\n      #endif\n    }\n  }\n\n  // PATCH NORMALIZATION\n  if (op->patnorm>0) // Subtract Mean\n    tmp_in_e->array() -= (tmp_in_e->sum() / op->novals);    \n}\n\n// Extract patch on float position with bilinear interpolation, no gradients.\nvoid PatClass::getPatchStaticBil(const float* img, const Eigen::Vector2f* mid_in,  Eigen::Matrix<float, Eigen::Dynamic, 1>* tmp_in_e)\n{\n  float *tmp_in    = tmp_in_e->data();\n  \n  Eigen::Vector2f resid;\n  Eigen::Vector4f we; // bilinear weight vector\n  Eigen::Vector4i pos;\n  Eigen::Vector2i pos_it;\n  \n  // Compute the bilinear weight vector, for patch without orientation/scale change -> weight vector is constant for all pixels\n  pos[0] = ceil((*mid_in)[0]+.00001f); // ensure rounding up to natural numbers\n  pos[1] = ceil((*mid_in)[1]+.00001f);\n  pos[2] = floor((*mid_in)[0]);\n  pos[3] = floor((*mid_in)[1]);  \n  \n  resid[0] = (*mid_in)[0] - (float)pos[2];\n  resid[1] = (*mid_in)[1] - (float)pos[3];\n  we[0] = resid[0]*resid[1];\n  we[1] = (1-resid[0])*resid[1];\n  we[2] = resid[0]*(1-resid[1]);\n  we[3] = (1-resid[0])*(1-resid[1]);\n\n  pos[0] += cpt->imgpadding;\n  pos[1] += cpt->imgpadding;\n  \n  float * tmp_it = tmp_in;\n  const float * img_a, * img_b, * img_c, * img_d, *img_e; \n   \n  #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)  // 1 channel image\n    img_e = img    + pos[0]-op->p_samp_s/2;\n  #else                                       // 3-channel RGB image\n    img_e = img    + (pos[0]-op->p_samp_s/2)*3;\n  #endif\n  \n  int lb = -op->p_samp_s/2;\n  int ub = op->p_samp_s/2-1;     \n\n  for (pos_it[1]=pos[1]+lb; pos_it[1] <= pos[1]+ub; ++pos_it[1])    \n  {\n    #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)  // 1 channel image\n      img_a = img_e +  pos_it[1]    * cpt->tmp_w;\n      img_c = img_e + (pos_it[1]-1) * cpt->tmp_w;\n      img_b = img_a-1;\n      img_d = img_c-1;\n    #else                                     // 3-channel RGB image\n      img_a = img_e +  pos_it[1]    * cpt->tmp_w * 3;\n      img_c = img_e + (pos_it[1]-1) * cpt->tmp_w * 3;\n      img_b = img_a-3;\n      img_d = img_c-3;\n    #endif\n    \n\n    for (pos_it[0]=pos[0]+lb; pos_it[0] <= pos[0]+ub; ++pos_it[0], \n            ++tmp_it,++img_a,++img_b,++img_c,++img_d)    \n    {\n      #if (SELECTCHANNEL==1 | SELECTCHANNEL==2)  // Single channel\n        (*tmp_it)     = we[0] * (*img_a) + we[1] * (*img_b) + we[2] * (*img_c) + we[3] * (*img_d); \n      #else // 3-channel RGB image\n        (*tmp_it)     = we[0] * (*img_a) + we[1] * (*img_b) + we[2] * (*img_c) + we[3] * (*img_d); ++tmp_it; ++img_a; ++img_b; ++img_c; ++img_d;\n        (*tmp_it)     = we[0] * (*img_a) + we[1] * (*img_b) + we[2] * (*img_c) + we[3] * (*img_d); ++tmp_it; ++img_a; ++img_b; ++img_c; ++img_d;\n        (*tmp_it)     = we[0] * (*img_a) + we[1] * (*img_b) + we[2] * (*img_c) + we[3] * (*img_d);\n      #endif\n    }\n  }\n  // PATCH NORMALIZATION\n  if (op->patnorm>0) // Subtract Mean\n    tmp_in_e->array() -= (tmp_in_e->sum() / op->novals);    \n}  \n \n\n}\n\n\n", "meta": {"hexsha": "42410117f9886cd9c8151b446b4563bab6b70396", "size": 13351, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "of_dis/patch.cpp", "max_stars_repo_name": "beaupreda/IMOT_OpticalFlow_Edges", "max_stars_repo_head_hexsha": "633b8fec2c2a4525d1e62d385e553789d56f61f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-01-31T13:32:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T16:35:29.000Z", "max_issues_repo_path": "of_dis/patch.cpp", "max_issues_repo_name": "beaupreda/IMOT_OpticalFlow_Edges", "max_issues_repo_head_hexsha": "633b8fec2c2a4525d1e62d385e553789d56f61f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-09-14T11:02:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-29T23:28:48.000Z", "max_forks_repo_path": "of_dis/patch.cpp", "max_forks_repo_name": "beaupreda/IMOT_OpticalFlow_Edges", "max_forks_repo_head_hexsha": "633b8fec2c2a4525d1e62d385e553789d56f61f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-04-01T12:20:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T03:42:54.000Z", "avg_line_length": 32.7230392157, "max_line_length": 244, "alphanum_fraction": 0.5801063591, "num_tokens": 4474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4189619702983749}}
{"text": "#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <boost/assign/list_of.hpp>\n#include \"source/newtonian/common/hllc.hpp\"\n#include \"source/newtonian/common/ideal_gas.hpp\"\n#include \"source/newtonian/one_dimensional/hdsim.hpp\"\n#include \"source/newtonian/one_dimensional/pcm1d.hpp\"\n#include \"source/newtonian/one_dimensional/plm1d.hpp\"\n#include \"source/newtonian/one_dimensional/eos_consistent1d.hpp\"\n#include \"source/newtonian/one_dimensional/spatial_distribution1d.hpp\"\n#include \"source/newtonian/one_dimensional/eulerian1d.hpp\"\n#include \"source/newtonian/one_dimensional/periodic_1d.hpp\"\n#include \"source/newtonian/one_dimensional/zero_force_1d.hpp\"\n#include \"source/misc/int2str.hpp\"\n#include \"source/misc/utils.hpp\"\n#include \"source/misc/simple_io.hpp\"\n#include \"source/newtonian/one_dimensional/hdf5_diagnostics1d.hpp\"\n#include \"source/newtonian/test_1d/main_loop_1d.hpp\"\n\nusing namespace std;\nusing namespace interpolations1d;\nusing namespace simulation1d;\nusing namespace diagnostics1d;\n\nnamespace {\nSpatialReconstruction1D const& choose_between\n(SpatialReconstruction1D const& opt1,\n SpatialReconstruction1D const& opt2,\n SpatialReconstruction1D const& opt3,\n string const& name1,\n string const& name2,\n string const& name3,\n string const& choice)\n{\n  if(name1==choice)\n    return opt1;\n  else if(name2==choice)\n    return opt2;\n  else if(name3==choice)\n    return opt3;\n  else\n    throw \"Unknown option \"+choice;\n}\n\nclass SimData\n{\npublic:\n\n  SimData(string const& interp_method_name):\n    vertices_(linspace(0,1,100)),\n    eos_(5./3.),\n    pcm_(),\n    plm_naive_(),\n    plm_(plm_naive_,eos_),\n    interpm_(choose_between(pcm_,plm_naive_,plm_,\n\t\t\t    \"pcm\",\"plm_naive\",\"plm\",\n\t\t\t    interp_method_name)),\n    density_(1,0.3,2,0.7,1),\n    pressure_(1),\n    xvelocity_(1),\n    yvelocity_(0),\n    rs_(),\n    vm_(),\n    bc_(),\n    force_(),\n    sim_(pg_,\n\t vertices_,\n\t interpm_,\n\t density_,\n\t pressure_,\n\t xvelocity_,\n\t yvelocity_,\n\t eos_,\n\t rs_,\n\t vm_,\n\t bc_,\n\t force_) {}\n\n  hdsim1D& getSim(void)\n  {\n    return sim_;\n  }\n\nprivate:\n  const SlabSymmetry1D pg_;\n  const vector<double> vertices_;\n  const IdealGas eos_;\n  PCM1D pcm_;\n  PLM1D plm_naive_;\n  EOSConsistent plm_;\n  SpatialReconstruction1D const& interpm_;\n  const TwoSteps density_;\n  const Uniform pressure_;\n  const Uniform xvelocity_;\n  const Uniform yvelocity_;\n  const Hllc rs_;\n  const Eulerian1D vm_;\n  const Periodic1D bc_;\n  const ZeroForce1D force_;\n  hdsim1D sim_;\n};\n}\n\nint main(void)\n{\n  const vector<string> interp_names = \n    boost::assign::list_of(\"pcm\")(\"plm_naive\")(\"plm\");\n  for(size_t i=0;i<interp_names.size();++i){\n    SimData sim_data(interp_names[i]);\n\n    main_loop(sim_data.getSim(),\n\t      1, 1e6, 2,\n\t      \"time.txt\");\n\n    write_snapshot_to_hdf5(sim_data.getSim(),\n\t\t\t   interp_names[i]+\"_final.h5\");\n  }\n  \n  return 0;\n}\n", "meta": {"hexsha": "082805bf8b957af7c930ac2c407941cded4f1ae5", "size": 2833, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/tests/newtonian/one_dimensional/pure_advection_2o/test.cpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/tests/newtonian/one_dimensional/pure_advection_2o/test.cpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/tests/newtonian/one_dimensional/pure_advection_2o/test.cpp", "max_forks_repo_name": "GalaxyHunters/Vivid", "max_forks_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-29T09:39:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-25T19:17:49.000Z", "avg_line_length": 23.2213114754, "max_line_length": 70, "alphanum_fraction": 0.7243205083, "num_tokens": 822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936324115011, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4189619644622411}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2005 Aurelien Chanudet\n Copyright (C) 2005 Plamen Neykov\n Copyright (C) 2005, 2006 Eric Ehlers\n Copyright (C) 2006, 2007 Ferdinando Ametrano\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#ifdef HAVE_CONFIG_H\n#include <qlo/config.hpp>\n#endif\n\n#include <qlo/yieldtermstructures.hpp>\n#include <qlo/ratehelpers.hpp>\n\n#include <ql/time/date.hpp>\n#include <ql/termstructures/yield/discountcurve.hpp>\n#include <ql/termstructures/yield/forwardcurve.hpp>\n#include <ql/termstructures/yield/zerocurve.hpp>\n#include <ql/termstructures/yield/impliedtermstructure.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/termstructures/yield/forwardspreadedtermstructure.hpp>\n#include <ql/math/interpolations/cubicinterpolation.hpp>\n#include <ql/math/interpolations/forwardflatinterpolation.hpp>\n#include <ql/math/interpolations/backwardflatinterpolation.hpp>\n\n#include <boost/algorithm/string/case_conv.hpp>\n\nusing boost::algorithm::to_upper_copy;\nusing boost::shared_ptr;\n\nusing ObjectHandler::ValueObject;\n\nusing QuantLib::CubicInterpolation;\nusing QuantLib::InterpolatedDiscountCurve;\nusing QuantLib::InterpolatedZeroCurve;\nusing QuantLib::InterpolatedForwardCurve;\n\nnamespace QuantLibAddin {\n\n    DiscountCurve::DiscountCurve(\n        const shared_ptr<ValueObject>& prop,\n        const std::vector<QuantLib::Date>& dates,\n        const std::vector<QuantLib::DiscountFactor>& dfs,\n        const QuantLib::DayCounter& dayCounter,\n        bool perm) : YieldTermStructure(prop, perm)\n    {\n        QL_REQUIRE(!dates.empty(), \"no input dates given\");\n        libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n            QuantLib::DiscountCurve(dates, dfs, dayCounter));\n    }\n\n    ZeroCurve::ZeroCurve(const shared_ptr<ValueObject>& prop,\n                         const std::vector<QuantLib::Date>& dates,\n                         const std::vector<QuantLib::Rate>& zeroRates,\n                         const QuantLib::DayCounter& dayCounter,\n                         bool perm) : YieldTermStructure(prop, perm)\n    {\n        QL_REQUIRE(!dates.empty(), \"no input dates given\");\n        libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n            QuantLib::ZeroCurve(dates, zeroRates, dayCounter));\n    }\n\n    ForwardCurve::ForwardCurve(const shared_ptr<ValueObject>& prop,\n                               const std::vector<QuantLib::Date>& dates,\n                               const std::vector<QuantLib::Rate>& fwdRates,\n                               const QuantLib::DayCounter& dayCounter,\n                               bool perm) : YieldTermStructure(prop, perm)\n    {\n        QL_REQUIRE(!dates.empty(), \"no input dates given\");\n        libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n            QuantLib::ForwardCurve(dates, fwdRates, dayCounter));\n    }\n\n    FlatForward::FlatForward(const shared_ptr<ValueObject>& prop,\n                             QuantLib::Natural nDays,\n                             const QuantLib::Calendar& calendar,\n                             const QuantLib::Handle<QuantLib::Quote>& forward,\n                             const QuantLib::DayCounter& dayCounter,\n                             QuantLib::Compounding compounding,\n                             QuantLib::Frequency frequency,\n                             bool perm)\n    : YieldTermStructure(prop, perm)\n    {\n        libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n            QuantLib::FlatForward(nDays, calendar, forward, dayCounter,\n                                  compounding, frequency));\n    }\n\n    ForwardSpreadedTermStructure::ForwardSpreadedTermStructure(\n            const shared_ptr<ValueObject>& prop,\n            const QuantLib::Handle<QuantLib::YieldTermStructure>& hYTS,\n            const QuantLib::Handle<QuantLib::Quote>& spread,\n            bool perm) : YieldTermStructure(prop, perm) {\n\n        libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n            QuantLib::ForwardSpreadedTermStructure(hYTS, spread));\n    }\n\n\n    ImpliedTermStructure::ImpliedTermStructure(\n            const shared_ptr<ValueObject>& prop,\n            const QuantLib::Handle<QuantLib::YieldTermStructure>& hYTS,\n            const QuantLib::Date& referenceDate,\n            bool perm)\n    : YieldTermStructure(prop, perm)\n    {\n        libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n            QuantLib::ImpliedTermStructure(hYTS, referenceDate));\n    }\n\n\n    InterpolatedYieldCurve::InterpolatedYieldCurve(\n            const shared_ptr<ValueObject>& prop,\n            const std::vector<QuantLib::Date>& dates,\n            const std::vector<QuantLib::Real>& data,\n            const QuantLib::Calendar& calendar,\n            const QuantLib::DayCounter& dayCounter,\n            const std::vector<QuantLib::Handle<QuantLib::Quote> >& jumps,\n            const std::vector<QuantLib::Date>& jumpDates,\n            const std::string& traitsID,\n            const std::string& interpolatorID,\n            bool perm)\n    : YieldTermStructure(prop, perm),\n      traitsID_(to_upper_copy(traitsID)),\n      interpolatorID_(to_upper_copy(interpolatorID))\n    {\n        if (traitsID_==\"DISCOUNT\") {\n            if (interpolatorID_==\"BACKWARDFLAT\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::BackwardFlat>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates));\n            } else if (interpolatorID_==\"FORWARDFLAT\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::ForwardFlat>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates));\n            } else if (interpolatorID_==\"LINEAR\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::Linear>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates));\n            } else if (interpolatorID_==\"LOGLINEAR\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::LogLinear>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates));\n            } else if (interpolatorID_==\"CUBICNATURALSPLINE\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Spline, false,\n                                        CubicInterpolation::SecondDerivative, 0.0,\n                                        CubicInterpolation::SecondDerivative, 0.0)));\n            } else if (interpolatorID_==\"LOGCUBICNATURALSPLINE\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Spline, false,\n                                           CubicInterpolation::SecondDerivative, 0.0,\n                                           CubicInterpolation::SecondDerivative, 0.0)));\n            } else if (interpolatorID_==\"MONOTONICCUBICNATURALSPLINE\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Spline, true,\n                                        CubicInterpolation::SecondDerivative, 0.0,\n                                        CubicInterpolation::SecondDerivative, 0.0)));\n            } else if (interpolatorID_==\"MONOTONICLOGCUBICNATURALSPLINE\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Spline, true,\n                                           CubicInterpolation::SecondDerivative, 0.0,\n                                           CubicInterpolation::SecondDerivative, 0.0)));\n            } else if (interpolatorID_==\"KRUGERCUBIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Kruger)));\n            } else if (interpolatorID_==\"KRUGERLOGCUBIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Kruger)));\n            } else if (interpolatorID_==\"FRITSCHBUTLANDCUBIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::FritschButland)));\n            } else if (interpolatorID_==\"FRITSCHBUTLANDLOGCUBIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::FritschButland)));\n            } else if (interpolatorID_==\"PARABOLIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Parabolic, false)));\n            } else if (interpolatorID_==\"LOGPARABOLIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Parabolic, false)));\n            } else if (interpolatorID_==\"MONOTONICPARABOLIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Parabolic, true)));\n            } else if (interpolatorID_==\"MONOTONICLOGPARABOLIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedDiscountCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Parabolic, true)));\n            } else\n                QL_FAIL(\"unknown interpolatorID: \" << interpolatorID_);\n        } else if (traitsID_==\"ZEROYIELD\") {\n            if (interpolatorID_==\"BACKWARDFLAT\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::BackwardFlat>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates));\n            } else if (interpolatorID_==\"FORWARDFLAT\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::ForwardFlat>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates));\n            } else if (interpolatorID_==\"LINEAR\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::Linear>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates));\n            } else if (interpolatorID_==\"LOGLINEAR\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::LogLinear>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates));\n            } else if (interpolatorID_==\"CUBICNATURALSPLINE\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Spline, false,\n                                        CubicInterpolation::SecondDerivative, 0.0,\n                                        CubicInterpolation::SecondDerivative, 0.0)));\n            } else if (interpolatorID_==\"LOGCUBICNATURALSPLINE\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Spline, false,\n                                           CubicInterpolation::SecondDerivative, 0.0,\n                                           CubicInterpolation::SecondDerivative, 0.0)));\n            } else if (interpolatorID_==\"MONOTONICCUBICNATURALSPLINE\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Spline, true,\n                                        CubicInterpolation::SecondDerivative, 0.0,\n                                        CubicInterpolation::SecondDerivative, 0.0)));\n            } else if (interpolatorID_==\"MONOTONICLOGCUBICNATURALSPLINE\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Spline, true,\n                                           CubicInterpolation::SecondDerivative, 0.0,\n                                           CubicInterpolation::SecondDerivative, 0.0)));\n            } else if (interpolatorID_==\"KRUGERCUBIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Kruger)));\n            } else if (interpolatorID_==\"KRUGERLOGCUBIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Kruger)));\n            } else if (interpolatorID_==\"FRITSCHBUTLANDCUBIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::FritschButland)));\n            } else if (interpolatorID_==\"FRITSCHBUTLANDLOGCUBIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::FritschButland)));\n            } else if (interpolatorID_==\"PARABOLIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Parabolic, false)));\n            } else if (interpolatorID_==\"LOGPARABOLIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Parabolic, false)));\n            } else if (interpolatorID_==\"MONOTONICPARABOLIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Parabolic, true)));\n            } else if (interpolatorID_==\"MONOTONICLOGPARABOLIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedZeroCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Parabolic, true)));\n            } else\n                QL_FAIL(\"unknown interpolatorID: \" << interpolatorID_);\n        } else if (traitsID_==\"FORWARDRATE\") {\n            if (interpolatorID_==\"BACKWARDFLAT\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::BackwardFlat>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates));\n            } else if (interpolatorID_==\"FORWARDFLAT\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::ForwardFlat>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates));\n            } else if (interpolatorID_==\"LINEAR\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::Linear>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates));\n            } else if (interpolatorID_==\"LOGLINEAR\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::LogLinear>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates));\n            } else if (interpolatorID_==\"CUBICNATURALSPLINE\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Spline, false,\n                                        CubicInterpolation::SecondDerivative, 0.0,\n                                        CubicInterpolation::SecondDerivative, 0.0)));\n            } else if (interpolatorID_==\"LOGCUBICNATURALSPLINE\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Spline, false,\n                                           CubicInterpolation::SecondDerivative, 0.0,\n                                           CubicInterpolation::SecondDerivative, 0.0)));\n            } else if (interpolatorID_==\"MONOTONICCUBICNATURALSPLINE\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Spline, true,\n                                        CubicInterpolation::SecondDerivative, 0.0,\n                                        CubicInterpolation::SecondDerivative, 0.0)));\n            } else if (interpolatorID_==\"MONOTONICLOGCUBICNATURALSPLINE\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Spline, true,\n                                           CubicInterpolation::SecondDerivative, 0.0,\n                                           CubicInterpolation::SecondDerivative, 0.0)));\n            } else if (interpolatorID_==\"KRUGERCUBIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Kruger)));\n            } else if (interpolatorID_==\"KRUGERLOGCUBIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Kruger)));\n            } else if (interpolatorID_==\"FRITSCHBUTLANDCUBIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::FritschButland)));\n            } else if (interpolatorID_==\"FRITSCHBUTLANDLOGCUBIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::FritschButland)));\n            } else if (interpolatorID_==\"PARABOLIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Parabolic)));\n            } else if (interpolatorID_==\"LOGPARABOLIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Parabolic, false)));\n            } else if (interpolatorID_==\"MONOTONICPARABOLIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::Cubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::Cubic(CubicInterpolation::Parabolic, true)));\n            } else if (interpolatorID_==\"MONOTONICLOGPARABOLIC\") {\n                libraryObject_ = shared_ptr<QuantLib::Extrapolator>(new\n                    InterpolatedForwardCurve<QuantLib::LogCubic>(\n                        dates, data, dayCounter, calendar, jumps, jumpDates,\n                        QuantLib::LogCubic(CubicInterpolation::Parabolic, true)));\n            } else\n                QL_FAIL(\"unknown interpolatorID: \" << interpolatorID_);\n        } else\n            QL_FAIL(\"unknown traitsID: \" << traitsID_);\n \n    }\n\n    #define RESOLVE_TEMPLATE(NAME) \\\n        if (traitsID_==\"DISCOUNT\") { \\\n            if (interpolatorID_==\"BACKWARDFLAT\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::BackwardFlat> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"FORWARDFLAT\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::ForwardFlat> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"LINEAR\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::Linear> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"LOGLINEAR\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::LogLinear> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"CUBICNATURALSPLINE\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"LOGCUBICNATURALSPLINE\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"MONOTONICCUBICNATURALSPLINE\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"MONOTONICLOGCUBICNATURALSPLINE\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"KRUGERCUBIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"KRUGERLOGCUBIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"FRITSCHBUTLANDCUBIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"FRITSCHBUTLANDLOGCUBIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"PARABOLIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"LOGPARABOLIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"MONOTONICPARABOLIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"MONOTONICLOGPARABOLIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedDiscountCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else \\\n                QL_FAIL(\"unknown interpolatorID: \" << interpolatorID_); \\\n        } else if (traitsID_==\"ZEROYIELD\") { \\\n            if (interpolatorID_==\"BACKWARDFLAT\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::BackwardFlat> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"FORWARDFLAT\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::ForwardFlat> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"LINEAR\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::Linear> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"LOGLINEAR\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::LogLinear> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"CUBICNATURALSPLINE\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"LOGCUBICNATURALSPLINE\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"MONOTONICCUBICNATURALSPLINE\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"MONOTONICLOGCUBICNATURALSPLINE\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"KRUGERCUBIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"KRUGERLOGCUBIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"FRITSCHBUTLANDCUBIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"FRITSCHBUTLANDLOGCUBIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"PARABOLIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"LOGPARABOLIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"MONOTONICPARABOLIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"MONOTONICLOGPARABOLIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedZeroCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else \\\n                QL_FAIL(\"unknown interpolatorID: \" << interpolatorID_); \\\n        } else if (traitsID_==\"FORWARDRATE\") { \\\n            if (interpolatorID_==\"BACKWARDFLAT\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::BackwardFlat> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"FORWARDFLAT\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::ForwardFlat> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"LINEAR\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::Linear> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"LOGLINEAR\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::LogLinear> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"CUBICNATURALSPLINE\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"LOGCUBICNATURALSPLINE\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"MONOTONICCUBICNATURALSPLINE\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"MONOTONICLOGCUBICNATURALSPLINE\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"KRUGERCUBIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"KRUGERLOGCUBIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"FRITSCHBUTLANDCUBIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"FRITSCHBUTLANDLOGCUBIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"PARABOLIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"LOGPARABOLIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"MONOTONICPARABOLIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::Cubic> >(libraryObject_)->NAME(); \\\n            } else if (interpolatorID_==\"MONOTONICLOGPARABOLIC\") { \\\n                return boost::dynamic_pointer_cast<InterpolatedForwardCurve<QuantLib::LogCubic> >(libraryObject_)->NAME(); \\\n            } else \\\n                QL_FAIL(\"unknown interpolatorID: \" << interpolatorID_); \\\n        } else \\\n            QL_FAIL(\"unknown traitsID: \" << traitsID_);\n\n    const std::vector<QuantLib::Time>& InterpolatedYieldCurve::times() const {\n        RESOLVE_TEMPLATE(times)\n    }\n\n    const std::vector<QuantLib::Date>& InterpolatedYieldCurve::dates() const {\n        RESOLVE_TEMPLATE(dates)\n    }\n\n    const std::vector<QuantLib::Real>& InterpolatedYieldCurve::data() const {\n        RESOLVE_TEMPLATE(data)\n    }\n\n    const std::vector<QuantLib::Time>& InterpolatedYieldCurve::jumpTimes() const {\n        RESOLVE_TEMPLATE(jumpTimes)\n    }\n\n    const std::vector<QuantLib::Date>& InterpolatedYieldCurve::jumpDates() const {\n        RESOLVE_TEMPLATE(jumpDates)\n    }\n\n    InterpolatedYieldCurve::InterpolatedYieldCurve(\n            const shared_ptr<ValueObject>& prop,\n            const std::string& traitsID,\n            const std::string& interpolatorID,\n            bool perm)\n    : YieldTermStructure(prop, perm),\n      traitsID_(to_upper_copy(traitsID)),\n      interpolatorID_(to_upper_copy(interpolatorID))\n    {\n    }\n\n    // Stream operator to write a InterpolatedYieldCurvePair to a stream - for logging / error handling.\n    std::ostream &operator<<(std::ostream &out,\n                             InterpolatedYieldCurvePair tokenPair)\n    {\n        out << \"InterpolatedYieldCurve<\";\n\n        switch (tokenPair.first) {\n            case InterpolatedYieldCurve::Discount:\n                out << \"<Discount, \";\n                break;\n            case InterpolatedYieldCurve::ForwardRate:\n                out << \"<ForwardRate, \";\n                break;\n            case InterpolatedYieldCurve::ZeroYield:\n                out << \"<ZeroYield, \";\n                break;\n            default:\n                OH_FAIL(\"Unknown value for enumeration QuantLibAddin::InterpolatedYieldCurve::Traits\");\n        }\n\n        switch (tokenPair.second) {\n            case InterpolatedYieldCurve::BackwardFlat:\n                out << \"BackwardFlat>\";\n                break;\n            case InterpolatedYieldCurve::ForwardFlat:\n                out << \"ForwardFlat>\";\n                break;\n            case InterpolatedYieldCurve::Linear:\n                out << \"Linear>\";\n                break;\n            case InterpolatedYieldCurve::LogLinear:\n                out << \"LogLinear>\";\n                break;\n            case InterpolatedYieldCurve::CubicNaturalSpline:\n                out << \"CubicNaturalSpline>\";\n                break;\n            case InterpolatedYieldCurve::LogCubicNaturalSpline:\n                out << \"LogCubicNaturalSpline>\";\n                break;\n            case InterpolatedYieldCurve::MonotonicCubicNaturalSpline:\n                out << \"MonotonicCubicNaturalSpline>\";\n                break;\n            case InterpolatedYieldCurve::MonotonicLogCubicNaturalSpline:\n                out << \"MonotonicLogCubicNaturalSpline>\";\n                break;\n            case InterpolatedYieldCurve::KrugerCubic:\n                out << \"KrugerCubic>\";\n                break;\n            case InterpolatedYieldCurve::KrugerLogCubic:\n                out << \"KrugerLogCubic>\";\n                break;\n            case InterpolatedYieldCurve::FritschButlandCubic:\n                out << \"FritschButlandCubic>\";\n                break;\n            case InterpolatedYieldCurve::FritschButlandLogCubic:\n                out << \"FritschButlandLogCubic>\";\n                break;\n            case InterpolatedYieldCurve::Parabolic:\n                out << \"Parabolic>\";\n                break;\n            case InterpolatedYieldCurve::LogParabolic:\n                out << \"LogParabolic>\";\n                break;\n            case InterpolatedYieldCurve::MonotonicParabolic:\n                out << \"MonotonicParabolic>\";\n                break;\n            case InterpolatedYieldCurve::MonotonicLogParabolic:\n                out << \"MonotonicLogParabolic>\";\n                break;\n            default:\n                OH_FAIL(\"Unknown value for enumeration QuantLibAddin::InterpolatedYieldCurve::Interpolator\");\n        }\n\n        return out;\n    }\n\n}\n", "meta": {"hexsha": "168baffb69ac34c806f9366a5cd419d1d07d2780", "size": 37916, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLibAddin/qlo/yieldtermstructures.cpp", "max_stars_repo_name": "txu2014/quantlib", "max_stars_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantLibAddin/qlo/yieldtermstructures.cpp", "max_issues_repo_name": "txu2014/quantlib", "max_issues_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLibAddin/qlo/yieldtermstructures.cpp", "max_forks_repo_name": "txu2014/quantlib", "max_forks_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-24T04:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T04:54:18.000Z", "avg_line_length": 60.6656, "max_line_length": 129, "alphanum_fraction": 0.6037029222, "num_tokens": 8872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4189515826160247}}
{"text": "#pragma once\n\n#include <functional>\n\n#include <boost/math/special_functions/prime.hpp>\n#include <boost/multiprecision/gmp.hpp>\n#include <boost/multiprecision/miller_rabin.hpp>\n#include <boost/random.hpp>\n#include <boost/random/random_device.hpp>\n#include <exrandom/discrete_normal_distribution.hpp>\n#include <nfl/params.hpp>\n\n#include <gmpxx.h>\n#include <sodium/randombytes.h>\n#include \"Common.hpp\"\n\n\n/** Overriding abs for basic int type **/\nnamespace boost {\nnamespace multiprecision {\nRegularInteger abs(RegularInteger in) { return in; }\n}  // namespace multiprecision\n}  // namespace boost\n\nnamespace ligero {\nnamespace math {\n\n/** Scaling function to bring randomness within a desired range  \n * @param val input, modulusIdx raw randomness, prime index \n * @return scaled randomness\n */\n\nuint64_t scaleToPrime(uint64_t input, size_t modulusIdx) {\n    double scaleFactor = static_cast<double>(nfl::params<uint64_t>::P[modulusIdx])/static_cast<double>(1ull << 62);\n    uint64_t input62 = input & ((1ull << 62) - 1);\n    return static_cast<uint64_t>(static_cast<double>(input62)*scaleFactor);\n}\n\nuint64_t scaleToUpperBound(uint64_t input, size_t upperBound) {\n    float scaleFactor = static_cast<double>(upperBound)/static_cast<double>(1ull << 62);\n    uint64_t input62 = input & ((1ull << 62) - 1);\n    return static_cast<uint64_t>(static_cast<double>(input62)*scaleFactor);\n}\n\n/** Compute hash for given mpz value\n * @param val MPZ_class value\n * @return Hash of @p val\n */\nstd::string computeHash(mpz_class val) {\n    std::string s = val.get_str();\n    std::string os = val.get_str();\n\n    unsigned char hash[crypto_generichash_BYTES + 1];\n    const unsigned char *message = reinterpret_cast<const unsigned char *> (s.c_str());\n    crypto_generichash(hash, crypto_generichash_BYTES,\n            message, s.length(),\n            NULL, 0);\n    hash[crypto_generichash_BYTES] = 0;\n    DBG(\"For value os = \" << os << \" s = \" << s << \" generating hash = >>>\" << hash << \"<<<\");\n    return std::move(std::string(reinterpret_cast<char*>(hash)));\n}\n\n/** Compute hash for given NFL polynomial\n * @param val NFL polynomial\n * @return Hash of @p val\n */\ntemplate <typename T, size_t Degree, size_t NbPrimesQ>\nstd::string computeHash(nfl::poly_p<T, Degree, NbPrimesQ> val) {\n    std::stringstream ss(std::stringstream::out | std::stringstream::binary);\n    val.serialize_manually(ss);\n    std::string s = ss.str();\n\n    unsigned char hash[crypto_generichash_BYTES + 1];\n    const unsigned char *message = reinterpret_cast<const unsigned char *> (s.c_str());\n    crypto_generichash(hash, crypto_generichash_BYTES,\n            message, s.length(),\n            NULL, 0);\n    hash[crypto_generichash_BYTES] = 0;\n    std::string result = std::string(reinterpret_cast<char*>(hash));\n    return result;\n}\n\n/** Compute hash for given value\n * @param val ((a, b), c), where a, b is vector of mpz_class\n * @return Hash of c\n */\nstd::string computeHash(std::pair<std::pair<std::vector<mpz_class>, std::vector<mpz_class>>, mpz_class> val) {\n    mpz_class v = val.second;\n    return computeHash(v);\n}\n\n/** Default hash function for any type, will throw a runtime exception */\ntemplate <typename T>\nstd::string computeHash(T val) {\n    LOG(FATAL) << \"computeHash for this type is not implemented yet\";\n}\n\n/** Generate a vector of random numbers\n * @param seed Seed to initialize the random generator\n * @param size Length of the output random vector\n * @param numBits Number of bits of each value, default to 128 bits\n * @return A vector of random numbers\n **/\nstd::vector<mpz_class> generateRandomVector(mpz_class seed, size_t size, size_t numBits = 128) {\n    std::vector<mpz_class> result(size);\n\n    const int numBytes = lround(double(numBits) / 8);\n    const size_t bufferSize = size * (numBytes + 1);\n\n    char* buf = new char[bufferSize];\n\n    size_t seedSize = (mpz_sizeinbase (seed.get_mpz_t(), 2) + CHAR_BIT-1) / CHAR_BIT;\n    unsigned char seedArray[32U];\n    std::vector<unsigned char> seedVector(seedSize);\n\n    mpz_export(&seedVector[0], &seedSize, 1, 1, 0, 0, seed.get_mpz_t());\n    for (size_t i = 0; i < seedSize && i < 32; ++i) {\n        seedArray[i] = seedVector[i];\n    }\n    for (size_t i = seedSize; i < 32; ++i) {\n        seedArray[i] = static_cast<unsigned char>(0);\n    }\n\n    randombytes_buf_deterministic((void*)buf, bufferSize, seedArray);\n\n    size_t k = 0;\n    for (size_t i = 0; i < result.size(); ++i) {\n        assert(k < bufferSize);\n        mpz_import(result[i].get_mpz_t(), numBytes, 1, 1, 0, 0, &buf[k]);\n        k += numBytes;\n        assert(result[i] > 0);\n    }\n    delete[] buf;\n\n    return result;\n}\n\n/** Generate a single mpz random value\n * @param seed Seed to initialize random generator\n * @param numBits Number of bits of generated value\n * @return @p numBits bits random value\n */\nmpz_class generateRandomValue(mpz_class seed, size_t numBits = 128) {\n    mpz_class result;\n    {\n        std::vector t = generateRandomVector(seed, 1, numBits);\n        result = t[0];\n    }\n    return result;\n}\n\n/** A quick wrapper around GMP's powm implementation for different types. */\nmpz_class powm(const mpz_class& b, const mpz_class& p, const mpz_class& m) {\n    mpz_class x(b);\n    mpz_powm(x.get_mpz_t(), x.get_mpz_t(), p.get_mpz_t(), m.get_mpz_t());\n\n    return x;\n}\n\n/** A quick wrapper around GMP's powm implementation for different types. */\ntemplate <typename NumberType>\nNumberType powm(const NumberType& b, const NumberType& p, const NumberType& m) {\n    MPInt x(b);\n    MPInt y(p);\n    MPInt z(m);\n\n    MPInt o;\n\n    mpz_powm(o.backend().data(),\n             x.backend().data(),\n             y.backend().data(),\n             z.backend().data());\n\n    return NumberType(o);\n}\n\n/** A quick wrapper around GMP's powm implementation for different types. */\nRegularInteger powm (const RegularInteger& b, const long p, const RegularInteger& m) {\n    MPInt x (b);\n    MPInt y (p);\n    MPInt z (m);\n\n    mpz_powm(\n        x.backend().data(),\n        x.backend().data(),\n        y.backend().data(),\n        z.backend().data()\n    );\n\n    return RegularInteger(x);\n}\n\n/** Divide and round the quotient to nearest integer\n * @param a divident\n * @param b divisor\n * @return quotient rounded to nearest integer\n */\nInt64 divideAndRound(const Int64& a, const Int64& b) {\n    Int64 quotient, remainder;\n    boost::multiprecision::divide_qr(a, b, quotient, remainder);\n    if (remainder * 2 >= b) {\n        quotient++;\n    }\n    return quotient;\n}\n\n/** 128 bits power\n * @param a 64 bits integer\n * @param exp 64 bits integer\n * @return 128 bits @p a ^ @p exp\n */\nWideInteger pow(RegularInteger a, RegularInteger exp) {\n    MPInt x(0);\n    MPInt y(a);\n\n    mpz_pow_ui(\n        x.backend().data(),\n        y.backend().data(),\n        exp);\n\n    return WideInteger(x);\n}\n\nWideInteger pow(RegularInteger a, int exp) {\n    MPInt x(0);\n    MPInt y(a);\n\n    mpz_pow_ui(\n        x.backend().data(),\n        y.backend().data(),\n        exp);\n\n    return WideInteger(x);\n}\n\n/** N bits power\n * @param a N bits number of type T\n * @param exp 64 bits integer\n * @return N bits @p a ^ @p exp of type T\n */\ntemplate <typename NumberType>\nNumberType pow(NumberType a, uint64_t exp) {\n    MPInt x(0);\n    MPInt y(a);\n\n    mpz_pow_ui(\n        x.backend().data(),\n        y.backend().data(),\n        exp);\n\n    return NumberType(x);\n}\n\n/** Divide and round the quotient to nearest integer\n * @param a divident of type mpz_int\n * @param b divisor of type mpz_int\n * @return quotient rounded to nearest integer\n */\nMPInt divideAndRound(const MPInt& a, const MPInt& b) {\n    MPInt quotient, remainder;\n    boost::multiprecision::divide_qr(a, b, quotient, remainder);\n    if (remainder * 2 >= b) {\n        quotient++;\n    }\n    return quotient;\n}\n\n/** Divide and round the quotient to nearest integer\n * @param a divident of type int\n * @param b divisor of type int\n * @return quotient rounded to nearest integer\n */\nint64_t divideAndRound(int64_t a, int64_t b) {\n    int64_t remainder = a % b;\n    int64_t result = static_cast<int64_t>(a / b);\n    if (remainder * 2 >= b) {\n        result++;\n    }\n    return result;\n}\n\n/** Mod function overloading\n * @param a mpz_class\n * @param b mpz_class\n * @return @p a % @p b\n */\nmpz_class mod(const mpz_class& a, const mpz_class& b) {\n    return powm(a, 1, b);\n}\n\n/** Mod function overloading\n * @param a boost mpz_int\n * @param b boost mpz_int\n * @return @p a % @p b\n */\nMPInt mod(MPInt a, MPInt b) {\n    return boost::multiprecision::powm(a, 1, b);\n}\n\n/** Mod function overloading\n * @param a 64 bits integer\n * @param b 64 bits integer\n * @return @p a % @p b\n */\nRegularInteger mod(RegularInteger a, RegularInteger b) {\n// return static_cast<RegularInteger>(boost::multiprecision::powm(MPInt(a), 1, MPInt(b)));\n   return static_cast<RegularInteger>((static_cast<WideInteger>(a % b) + static_cast<WideInteger>(b)) % static_cast<WideInteger>(b));\n}\n\nRegularInteger\nmod(WideInteger a, WideInteger b) {\n// return static_cast<RegularInteger>(boost::multiprecision::powm(MPInt(a), 1, MPInt(b)));\n   return (((a % b) + b) % b);\n}\n\n/** Mod function overloading\n * @param a 64 bits integer\n * @param b 64 bits integer\n * @return @p a % @p b\n */\nInt64 mod(Int64 a, Int64 b) {\n    return boost::multiprecision::powm(a, 1, b);\n}\n\n/** Mod function overloading\n * @param a 64 bits integer\n * @param b 64 bits integer\n * @return @p a % @p b\n */\nint64_t mod(int64_t a, int64_t b) {\n    return ((a % b) + b) % b;\n}\n\ntemplate <typename NumberType>\nstruct ChiDist {\n\n    // This constant defines distributions standard deviation\n\n    std::mt19937 g;\n    double chiStd;\n\n    ChiDist(int seed, double _chiStd) : g(seed), chiStd(_chiStd){ }\n    ChiDist(int seed) : g(seed), chiStd(ligero::kDefaultChiStd){ }\n\n    ChiDist() : g(std::random_device()()), chiStd(ligero::kDefaultChiStd){}\n\n    NumberType operator()() {\n        exrandom::discrete_normal_distribution N(0, 1, lround(chiStd * 10), 10);\n        return boost::multiprecision::abs(NumberType(N(g)));\n    }\n};\n\n/** Sample a vector of random field element\n * @param m Size of total samples\n * @param q Boundary\n * @param chiStd Standard deviation\n * @return A vector of random sample\n */\ntemplate <typename FieldT>\nstd::vector<FieldT> sampleRandomVectorOverField(size_t m, FieldT q, double chiStd) {\n    //std::function<typename FieldT::underlyingType>\n    auto dist = ligero::math::ChiDist<typename FieldT::underlyingType>(std::random_device()(), chiStd);\n    std::vector<FieldT> e(m);\n\n    for (int i = 0; i < static_cast<int>(m); i++) {\n        typename FieldT::underlyingType tmp;\n        do {\n            tmp = static_cast<typename FieldT::underlyingType>(dist());\n        } while (tmp>q.getValue());\n\n        e[i] = FieldT(tmp);\n    }\n\n    return e;\n}\n\n/** A quick wrapper around GMP's modular inverse implementation for different types.\n *\n *  Note that the implementation here promotes arbitrary number types to our MPInt\n *  type so that we can call into `mpz_invert` directly with mpz types. This allows\n *  us to leverage GMP's existing implementation, but obviously has overhead. May\n *  be an optimization opportunity later if we want to consider writing our own modular\n *  inverse implementation.\n */\nmpz_class\nmod_inverse (const mpz_class& a, const mpz_class& b) {\n    mpz_t z;\n    mpz_init(z);\n\n    int r = mpz_invert(z, a.get_mpz_t(), b.get_mpz_t());\n\n    if (r == 0)\n        throw std::runtime_error(\"Modular inverse does not exist for the given operands.\");\n\n    auto result = mpz_class(z);\n    mpz_clear(z);\n\n    return result;\n}\n\n\n/** Deconstruct input `v` by Chinese Remainder Theorem given a vector of moduli\n *  in the input `alphas`.\n */\nstd::vector<mpz_class> crt_deconstruct (mpz_class v, const std::vector<mpz_class>& alphas)\n{\n    std::vector<mpz_class> ds (alphas.size());\n\n    for (int i = 0; i < alphas.size(); ++i) {\n        ds[i] = mod(v, alphas[i]);\n    }\n\n    return ds;\n}\n\n/** Reconstruct a value `v` by Chinese Remainder Theorem given a vector of its\n *  components and a vector of moduli.\n */\nmpz_class crt_reconstruct (const std::vector<mpz_class>& ds, std::vector<mpz_class>& coeffs, const std::vector<mpz_class>& alphas)\n{\n    if (ds.size() != alphas.size())\n        throw std::runtime_error(\"Reconstruction vector lengths don't match.\");\n\n    coeffs.resize(ds.size());\n\n    //mpz_class p = alphas.prod();\n    mpz_class p = 1;\n    for (size_t i = 0; i < alphas.size(); ++i) {\n        p *= alphas[i];\n    }\n\n    for (size_t i = 0; i < ds.size(); ++i) {\n        mpz_class pa = p / alphas[i];\n        mpz_class x = mod(pa, alphas[i]);\n        coeffs[i] = pa * mod_inverse(x, alphas[i]);\n    }\n\n    mpz_class dotProduct = 0;\n    for (size_t i = 0; i < ds.size(); ++i) {\n        dotProduct += ds[i] * coeffs[i];\n    }\n\n    return dotProduct % p;\n}\n\n/** A quick helper function for calculating the product of a vector of numbers. */\nmpz_class vectorProduct(const std::vector<mpz_class>& xs) {\n    mpz_class product = 1;\n\n    for (auto& x : xs)\n        product = product * x;\n\n    return product;\n}\n/* fixed version */\nstd::pair<std::vector<mpz_class>, std::vector<size_t>>\nfixed_bucket_n_primes (int productBitThreshold, size_t degree, int tauLimitBit)\n{\n    int number_of_buckets = std::ceil(double(productBitThreshold)/double(tauLimitBit)); // This rounds down.\n    std::vector<mpz_class> alphas(number_of_buckets);\n    std::vector<size_t> bucketSize(number_of_buckets);\n\n\n    gmp_randclass grc(gmp_randinit_default);\n    grc.seed(0);\n\n    for (int i = 0; i < number_of_buckets; ++i) {\n        mpz_class r = grc.get_z_bits(tauLimitBit);\n        while (!boost::multiprecision::miller_rabin_test(MPInt(r.get_mpz_t()), 64) || mpz_sizeinbase(r.get_mpz_t(),2) < tauLimitBit) {\n            r = grc.get_z_bits(tauLimitBit);\n        }\n        alphas[i] = r;\n        // DBG(\"alphas[\" << i << \"] = \" << r);\n    }\n\n\n    for (size_t i = 0; i < number_of_buckets; ++i) {\n        bucketSize[i] = lrint(floor(double(degree) / double(number_of_buckets)));\n        DBG(\"bucketSize[ \" << i << \"] = \" << bucketSize[i]);\n    }\n\n    return std::pair{alphas, bucketSize};\n}\n\n\n/** Implements a prime bucketing algorithm, returning a vector of numbers such that\n *  each number is a product of subsequent primes that is at least 18bits, and such\n *  that the product of numbers in the vector is at least `productBitThreshold` bits.\n */\nstd::pair<std::vector<mpz_class>, std::vector<size_t>>\nbalanced_bucket_n_primes (int productBitThreshold, size_t degree, int tauLimitBit, int startJ = 1)\n{\n    int number_of_buckets = std::ceil(double(productBitThreshold)/double(tauLimitBit)); // This rounds down.\n    std::vector<mpz_class> alphas(number_of_buckets);\n    std::vector<mpz_class> primes;\n    mpz_class alpha = 1;\n    int j = startJ;\n    while(1)\n    {\n        alpha*= boost::math::prime(j);\n        primes.push_back(boost::math::prime(j));\n        if(mpz_sizeinbase(alpha.get_mpz_t(), 2) >= static_cast<unsigned int>(productBitThreshold)) break;\n        j++;\n    }\n    DBG(\"Maximum size of prime = \" << mpz_sizeinbase((primes[primes.size()-1]).get_mpz_t(),2));\n\n    std::vector<double> weights(number_of_buckets);\n    for ( int i = 0; i < number_of_buckets; i++)\n    {\n      alphas[i] = 1;\n      weights[i] = 1;\n    }\n    double sum = 0.0;\n    for ( int i = primes.size()-1;i >= 0;  i--)\n    {\n      double maxweight = weights[0];\n      int maxpos = 0;\n      for (int j = 1; j < number_of_buckets; j++)\n      {\n\t      mpz_class temp = alphas[j];\n        if(weights[j] > maxweight && mpz_sizeinbase(temp.get_mpz_t(),2) <= tauLimitBit)\n        {\n          maxweight = weights[j];\n          maxpos = j;\n        }\n      }\n      alphas[maxpos] *= primes[i];\n      weights[maxpos] *= (double(1.0) - (double(1)/primes[i].get_d()));\n    }\n    for ( int i = 0; i < number_of_buckets; i++)\n    {\n      weights[i] = double(1)/weights[i];\n      sum += weights[i];\n    }\n\n    std::vector<size_t> bucketSize(weights.size());\n    size_t total = 0;\n    for (size_t i = 0; i < weights.size() - 1; ++i) {\n        bucketSize[i] = lround(double(weights[i] * double(degree)) / double(sum));\n        total += bucketSize[i];\n        DBG(\"bucketSize[ \" << i << \"] = \" << bucketSize[i]);\n    }\n    bucketSize[bucketSize.size() - 1] = degree - total;\n    DBG(\"bucketSize[ \" << bucketSize.size() - 1 << \"] = \" << bucketSize[bucketSize.size() - 1]);\n\n    return std::pair{alphas, bucketSize};\n    }\n\n}//namespace math\n}//namespace ligero\n", "meta": {"hexsha": "ff2fe7acce8eee0f2d8106016f0d3c3c67ff5b8b", "size": 16396, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Math.hpp", "max_stars_repo_name": "Eleven-Z/LigeroRSA", "max_stars_repo_head_hexsha": "17d8b3d00604da1e0272035e871fac3add8d7551", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Math.hpp", "max_issues_repo_name": "Eleven-Z/LigeroRSA", "max_issues_repo_head_hexsha": "17d8b3d00604da1e0272035e871fac3add8d7551", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-09T05:48:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-09T05:48:09.000Z", "max_forks_repo_path": "include/Math.hpp", "max_forks_repo_name": "Eleven-Z/LigeroRSA", "max_forks_repo_head_hexsha": "17d8b3d00604da1e0272035e871fac3add8d7551", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7568058076, "max_line_length": 134, "alphanum_fraction": 0.6454623079, "num_tokens": 4498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.41895158261602466}}
{"text": "/**********************************************************************\n*  Copyright (c) 2008-2015, Alliance for Sustainable Energy.  \n*  All rights reserved.\n*  \n*  This library is free software; you can redistribute it and/or\n*  modify it under the terms of the GNU Lesser General Public\n*  License as published by the Free Software Foundation; either\n*  version 2.1 of the License, or (at your option) any later version.\n*  \n*  This library is distributed in the hope that it will be useful,\n*  but WITHOUT ANY WARRANTY; without even the implied warranty of\n*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n*  Lesser General Public License for more details.\n*  \n*  You should have received a copy of the GNU Lesser General Public\n*  License along with this library; if not, write to the Free Software\n*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA\n**********************************************************************/\n\n#include \"Geometry.hpp\"\n#include \"Intersection.hpp\"\n#include \"Transformation.hpp\"\n\n#include \"../core/Assert.hpp\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include <polypartition/polypartition.h>\n\n#include <list>\n\nnamespace openstudio{\n  /// convert degrees to radians\n  double degToRad(double degrees)\n  {\n    return degrees*boost::math::constants::pi<double>()/180.0;\n  }\n\n  /// convert radians to degrees\n  double radToDeg(double radians)\n  {\n    return radians*180.0/boost::math::constants::pi<double>();\n  }\n\n  /// compute area from surface as Point3dVector\n  boost::optional<double> getArea(const Point3dVector& points)\n  {\n    boost::optional<double> result;\n    OptionalVector3d newall = getNewallVector(points);\n    if (newall){\n      result = newall->length() / 2.0;\n    }\n    return result;\n  }\n\n  // compute Newall vector from Point3dVector, direction is same as outward normal\n  // magnitude is twice the area\n  OptionalVector3d getNewallVector(const Point3dVector& points)\n  {\n    OptionalVector3d result;\n    unsigned N = points.size();\n    if (N >= 3){\n      Vector3d vec;\n      for (unsigned i = 1; i < N-1; ++i){\n        Vector3d v1 = points[i] - points[0];\n        Vector3d v2 = points[i+1] - points[0];\n        vec += v1.cross(v2);\n      }\n     result = vec;\n   }\n   return result;\n  }\n\n  // compute outward normal from Point3dVector\n  OptionalVector3d getOutwardNormal(const Point3dVector& points)\n  {\n    OptionalVector3d result = getNewallVector(points);\n    if (result){\n      if (!result->normalize()){\n        result.reset();\n      }\n    }\n    return result;\n  }\n\n  /// compute centroid from surface as Point3dVector\n  OptionalPoint3d getCentroid(const Point3dVector& points)\n  {\n    OptionalPoint3d result;\n\n    if (points.size() >= 3){\n      // convert to face coordinates\n      Transformation alignFace = Transformation::alignFace(points);\n      Point3dVector surfacePoints = alignFace.inverse()*points;\n\n      unsigned N = surfacePoints.size();\n      double A = 0;\n      double cx = 0;\n      double cy = 0;\n      for (unsigned i = 0; i < N; ++i){\n        double x1, x2, y1, y2;\n        if (i == N-1){\n          x1 = surfacePoints[i].x();\n          x2 = surfacePoints[0].x();\n          y1 = surfacePoints[i].y();\n          y2 = surfacePoints[0].y();\n        }else{\n          x1 = surfacePoints[i].x();\n          x2 = surfacePoints[i+1].x();\n          y1 = surfacePoints[i].y();\n          y2 = surfacePoints[i+1].y();\n        }\n\n        double dA = (x1*y2-x2*y1);\n        A += 0.5*dA;\n        cx += (x1+x2)*dA;\n        cy += (y1+y2)*dA;\n      }\n\n      if (A > 0){\n        // centroid in face coordinates\n        Point3d surfaceCentroid(cx/(6.0*A), cy/(6.0*A), 0.0);\n\n        // centroid\n        result = alignFace*surfaceCentroid;\n      }\n    }\n    return result;\n  }\n\n  /// reorder points to upper-left-corner convention\n  Point3dVector reorderULC(const Point3dVector& points)\n  {\n    unsigned N = points.size();\n    if (N < 3){\n      return Point3dVector();\n    }\n\n    // transformation to align face\n    Transformation t = Transformation::alignFace(points);\n    Point3dVector facePoints = t.inverse()*points;\n\n    // find ulc index in face coordinates\n    double maxY = std::numeric_limits<double>::min();\n    double minX = std::numeric_limits<double>::max();\n    unsigned ulcIndex = 0;\n    for(unsigned i = 0; i < N; ++i){\n      OS_ASSERT(std::abs(facePoints[i].z()) < 0.001);\n      if ((maxY < facePoints[i].y()) || ((maxY < facePoints[i].y() + 0.00001) && (minX > facePoints[i].x()))){\n        ulcIndex = i;\n        maxY = facePoints[i].y();\n        minX = facePoints[i].x();\n      }\n    }\n\n    // no-op\n    if (ulcIndex == 0){\n      return points;\n    }\n\n    // create result\n    Point3dVector result;\n    std::copy (points.begin() + ulcIndex, points.end(), std::back_inserter(result));\n    std::copy (points.begin(), points.begin() + ulcIndex, std::back_inserter(result));\n    OS_ASSERT(result.size() == N);\n    return result;\n  }\n\n  std::vector<Point3d> removeCollinear(const Point3dVector& points, double tol)\n  {\n    unsigned N = points.size();\n    if (N < 3){\n      return points;\n    }\n\n    std::vector<Point3d> result;\n    Point3d lastPoint = points[0];\n    result.push_back(lastPoint);\n\n    for (unsigned i = 1; i < N; ++i){\n      Point3d currentPoint = points[i];\n      Point3d nextPoint = points[0];\n      if (i < N-1){\n        nextPoint = points[i+1];\n      }\n\n      Vector3d a = (currentPoint - lastPoint);\n      Vector3d b = (nextPoint - currentPoint);\n\n      // if these fail to normalize we have zero length vectors (e.g. adjacent points)\n      if (a.normalize()){\n        if (b.normalize()){\n\n          Vector3d c = a.cross(b);\n          if (c.length() >= tol){\n            // cross product is significant\n            result.push_back(currentPoint);\n            lastPoint = currentPoint;\n          }else{\n            // see if dot product is near -1\n            double d = a.dot(b);\n            if (d <= -1.0 + tol){\n              // this is a line reversal\n              result.push_back(currentPoint);\n              lastPoint = currentPoint;\n            }\n          }\n        }\n      }\n    }\n\n    return result;\n  }\n\n  double getDistance(const Point3d& point1, const Point3d& point2) {\n    double dx = point1.x() - point2.x();\n    double dy = point1.y() - point2.y();\n    double dz = point1.z() - point2.z();\n    double result = std::sqrt(dx*dx + dy*dy + dz*dz);\n    return result;\n  }\n\n  double getDistancePointToLineSegment(const Point3d& point, const std::vector<Point3d>& lineSegment)\n  {\n    if (lineSegment.size() != 2){\n      return 0;\n    }\n\n    // http://paulbourke.net/geometry/pointlineplane/\n\n    Point3d point1 = lineSegment[0];\n    Point3d point2 = lineSegment[1];\n\n    Vector3d p2p1 = point2-point1;\n    Vector3d p3p1 = point-point1;\n\n    double d12 = p2p1.length();\n    if (d12 < 1.0e-12){\n      return p3p1.length();\n    }\n\n    Point3d closestPoint;\n    double u = p3p1.dot(p2p1) / (d12*d12);\n    if (u < 0){\n      closestPoint = point1;\n    }else if (u > 1){\n      closestPoint = point2;\n    }else{\n      closestPoint = point1 + u*p2p1;\n    }\n\n    Vector3d diff = point - closestPoint;\n\n    return diff.length();\n  }\n\n  double getDistancePointToTriangle(const Point3d& point, const std::vector<Point3d>& triangle)\n  {\n    if (triangle.size() != 3){\n      return 0;\n    }\n\n    //Distance Between Point and Triangle in 3D\n    //David Eberly\n    //Geometric Tools, LLC\n    //http://www.geometrictools.com/\n\n    //T(s; t) = B+sE0+tE1\n\n    Point3d B = triangle[0];\n    Vector3d E0 = triangle[1] - triangle[0];\n    Vector3d E1 = triangle[2] - triangle[0];\n    Vector3d BminusP = B - point;\n\n    double b = E0.dot(E1);\n\n    if (std::abs(b) > 1.0-1.0E-12){\n      // triangle is collinear\n      return 0;\n    }\n\n    double a = E0.dot(E0);\n    double c = E1.dot(E1);\n    double d = E0.dot(BminusP);\n    double e = E1.dot(BminusP);\n    // double f = BminusP.dot(BminusP); // unused\n\n    double det = a*c-b*b; \n    double s = b*e-c*d; \n    double t = b*d-a*e;\n\n    Point3d closestPoint;\n\n    if ( s+t <= det ) {\n      if ( s < 0 ) {  \n        if ( t < 0 ) { \n          //region 4, closest to point triangle[0] \n          return getDistance(point, triangle[0]);\n        } else { \n          //region 3, closest to line triangle[0] to triangle[2] \n          std::vector<Point3d> line;\n          line.push_back(triangle[0]);\n          line.push_back(triangle[2]);\n          return getDistancePointToLineSegment(point, line); \n        } \n      } else if ( t < 0 ) { \n        //region 5, closest to line triangle[0] to triangle[1] \n        std::vector<Point3d> line;\n        line.push_back(triangle[0]);\n        line.push_back(triangle[1]);\n        return getDistancePointToLineSegment(point, line);\n      } else { \n        //region 0, closest point is inside triangle\n        double invDet = 1.0/det;\n        closestPoint = B + invDet*s*E0 + invDet*t*E1;\n      }\n    } else {\n      if ( s < 0 ) { \n        //region 2, closest to point triangle[2]\n        return getDistance(point, triangle[2]);\n      } else if ( t < 0 ) { \n        //region 6, closest to point triangle[1]\n        return getDistance(point, triangle[1]);\n      } else { \n        //region 1, closest to line triangle[1] to triangle[2]\n        std::vector<Point3d> line;\n        line.push_back(triangle[1]);\n        line.push_back(triangle[2]);\n        return getDistancePointToLineSegment(point, line);\n      }\n    }\n  \n    Vector3d diff = point-closestPoint;\n    return diff.length();\n  }\n\n  double getAngle(const Vector3d& vector1, const Vector3d& vector2) {\n    Vector3d working1(vector1);\n    working1.normalize();\n    Vector3d working2(vector2);\n    working2.normalize();\n    return acos(working1.dot(working2));\n  }\n\n  /// compute distance in meters between two points on the Earth's surface\n  /// lat and lon are specified in degrees\n  double getDistanceLatLon(double lat1, double lon1, double lat2, double lon2)\n  {\n\n    // for more accuracy would want to use WGS-84 ellipsoid params and Vincenty formula\n\n    // Haversine formula \n    double R = 6371000; // Earth radius meters\n    double deltaLat = degToRad(lat2-lat1);\n    double deltaLon = degToRad(lon2-lon1); \n    double a = sin(deltaLat/2) * sin(deltaLat/2) +\n               cos(degToRad(lat1)) * cos(degToRad(lat2)) * \n               sin(deltaLon/2) * sin(deltaLon/2); \n    double c = 2 * atan2(sqrt(a), sqrt(1-a)); \n    double d = R * c;\n\n    return d;\n  }\n\n  bool circularEqual(const Point3dVector& points1, const Point3dVector& points2, double tol)\n  {\n    unsigned N = points1.size();\n    if (N != points2.size()){\n      return false;\n    }\n\n    if (N == 0){\n      return true;\n    }\n\n    bool result = false;\n\n    // look for a common starting point\n    for (unsigned i = 0; i < N; ++i){\n      if (getDistance(points1[0], points2[i]) <= tol){\n\n        result = true;\n\n        // check all other points\n        for (unsigned j = 0; j < N; ++j){\n          if (getDistance(points1[j], points2[(i + j) % N]) > tol){\n            result = false;\n            break;\n          }\n        }\n      }\n\n      if (result){\n        return result;\n      }\n    }\n\n    return result;\n  }\n\n  Point3d getCombinedPoint(const Point3d& point3d, std::vector<Point3d>& allPoints, double tol)\n  {\n    for (const Point3d& otherPoint : allPoints){\n      if (std::sqrt(std::pow(point3d.x()-otherPoint.x(), 2) + std::pow(point3d.y()-otherPoint.y(), 2) + std::pow(point3d.z()-otherPoint.z(), 2)) < tol){\n        return otherPoint;\n      }\n    }\n    allPoints.push_back(point3d);\n    return point3d;\n  }\n\n  std::vector<std::vector<Point3d> > computeTriangulation(const Point3dVector& vertices, const std::vector<std::vector<Point3d> >& holes, double tol)\n  {\n    std::vector<std::vector<Point3d> > result;\n\n    // check input\n    if (vertices.size () < 3){\n      return result;\n    }\n\n    boost::optional<Vector3d> normal = getOutwardNormal(vertices);\n    if (!normal || normal->z() > -0.999){\n      return result;\n    }\n\n    for (const auto& hole : holes){\n      normal = getOutwardNormal(hole);\n      if (!normal || normal->z() > -0.999){\n        return result;\n      }\n    }\n\n    std::vector<Point3d> allPoints;\n\n    // PolyPartition does not support holes which intersect the polygon or share an edge\n    // if any hole is not fully contained we will use boost to remove all the holes\n    bool polyPartitionHoles = true;\n    for (const std::vector<Point3d>& hole : holes){\n      if (!within(hole, vertices, tol)){\n        // PolyPartition can't handle this\n        polyPartitionHoles = false;\n        break;\n      }\n    }\n\n    if (!polyPartitionHoles){\n      // use boost to do all the intersections\n      std::vector<std::vector<Point3d> > allFaces = subtract(vertices, holes, tol);\n      std::vector<std::vector<Point3d> > noHoles;\n      for (const std::vector<Point3d>& face : allFaces){\n        std::vector<std::vector<Point3d> > temp = computeTriangulation(face, noHoles);\n        result.insert(result.end(), temp.begin(), temp.end());\n      }\n      return result;\n    }\n\n    // convert input to vector of TPPLPoly\n    std::list<TPPLPoly> polys;\n\n    TPPLPoly outerPoly; // must be counter-clockwise, input vertices are clockwise\n    outerPoly.Init(vertices.size());\n    outerPoly.SetHole(false);\n    unsigned n = vertices.size();\n    for(unsigned i = 0; i < n; ++i){\n\n      // should all have zero z coordinate now\n      double z = vertices[n-i-1].z();\n      if (abs(z) > tol){\n        LOG_FREE(Error, \"utilities.geometry.computeTriangulation\", \"All points must be on z = 0 plane for triangulation methods\");\n        return result;\n      }\n\n      Point3d point = getCombinedPoint(vertices[n-i-1], allPoints, tol);\n      outerPoly[i].x = point.x();\n      outerPoly[i].y = point.y();\n    }\n    outerPoly.SetOrientation(TPPL_CCW);\n    polys.push_back(outerPoly);\n\n\n    for (const std::vector<Point3d>& holeVertices : holes){\n\n      if (holeVertices.size () < 3){\n        LOG_FREE(Error, \"utilities.geometry.computeTriangulation\", \"Hole has fewer than 3 points, ignoring\");\n        continue;\n      }\n\n      TPPLPoly innerPoly; // must be clockwise, input vertices are clockwise\n      innerPoly.Init(holeVertices.size());\n      innerPoly.SetHole(true);\n      //std::cout << \"inner :\";\n      for(unsigned i = 0; i < holeVertices.size(); ++i){\n\n        // should all have zero z coordinate now\n        double z = holeVertices[i].z();\n        if (abs(z) > tol){\n          LOG_FREE(Error, \"utilities.geometry.computeTriangulation\", \"All points must be on z = 0 plane for triangulation methods\");\n          return result;\n        }\n\n        Point3d point = getCombinedPoint(holeVertices[i], allPoints, tol);\n        innerPoly[i].x = point.x();\n        innerPoly[i].y = point.y();\n      }\n      innerPoly.SetOrientation(TPPL_CW);\n      polys.push_back(innerPoly);\n    }\n\n    // do partitioning\n    TPPLPartition pp;\n    std::list<TPPLPoly> resultPolys;\n    int test = pp.Triangulate_EC(&polys,&resultPolys);\n    if (test == 0){\n      test = pp.Triangulate_MONO(&polys, &resultPolys);\n    }\n    if (test == 0){\n      LOG_FREE(Error, \"utilities.geometry.computeTriangulation\", \"Failed to partition polygon\");\n      return result;\n    }\n\n    // convert back to vertices\n    std::list<TPPLPoly>::iterator it, itend;\n    //std::cout << \"Start\" << std::endl;\n    for(it = resultPolys.begin(), itend = resultPolys.end(); it != itend; ++it){\n\n      it->SetOrientation(TPPL_CW);\n\n      std::vector<Point3d> triangle;\n      for (long i = 0; i < it->GetNumPoints(); ++i){\n        TPPLPoint point = it->GetPoint(i);\n        triangle.push_back(Point3d(point.x, point.y, 0));\n      }\n      //std::cout << triangle << std::endl;\n      result.push_back(triangle);\n    }\n    //std::cout << \"End\" << std::endl;\n\n    return result;\n  }\n\n  std::vector<Point3d> moveVerticesTowardsPoint(const Point3dVector& vertices, const Point3d& point, double distance)\n  {\n    Point3dVector result;\n    for (const Point3d& vertex : vertices){\n      Vector3d vector = point-vertex;\n      vector.setLength(distance);\n      result.push_back(vertex+vector);\n    }\n    return result;\n  }\n  \n  std::vector<Point3d> reverse(const Point3dVector& vertices)\n  {\n    std::vector<Point3d> result(vertices);\n    std::reverse(result.begin(), result.end());\n    return result;\n  }\n\n} // openstudio\n", "meta": {"hexsha": "2948ad64376de8f54e37765f1fd77f05426d2c1e", "size": 16292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/geometry/Geometry.cpp", "max_stars_repo_name": "pepsi7959/OpenstudioThai", "max_stars_repo_head_hexsha": "fb18afb8b983f71dd5eb171e753dac7d9a4b811b", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-06-28T09:06:24.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-28T09:06:24.000Z", "max_issues_repo_path": "openstudiocore/src/utilities/geometry/Geometry.cpp", "max_issues_repo_name": "pepsi7959/OpenstudioThai", "max_issues_repo_head_hexsha": "fb18afb8b983f71dd5eb171e753dac7d9a4b811b", "max_issues_repo_licenses": ["blessing"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2015-05-05T16:16:33.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-10T08:15:50.000Z", "max_forks_repo_path": "openstudiocore/src/utilities/geometry/Geometry.cpp", "max_forks_repo_name": "pepsi7959/OpenstudioThai", "max_forks_repo_head_hexsha": "fb18afb8b983f71dd5eb171e753dac7d9a4b811b", "max_forks_repo_licenses": ["blessing"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-09-23T12:51:13.000Z", "max_forks_repo_forks_event_max_datetime": "2017-09-23T12:51:13.000Z", "avg_line_length": 29.0928571429, "max_line_length": 152, "alphanum_fraction": 0.5966732138, "num_tokens": 4457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4188656360794607}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2009, Willow Garage, Inc.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n#include \"precomp.hpp\"\n\n// Eigen\n#include <Eigen/Core>\n\n// OpenCV\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/sfm/numeric.hpp>\n#include <opencv2/sfm/projection.hpp>\n\n// libmv headers\n#include \"libmv/multiview/projection.h\"\n\n#include <iostream>\n\nnamespace cv\n{\nnamespace sfm\n{\n\ntemplate<typename T>\nvoid\nhomogeneousToEuclidean(const Mat & X_, Mat & x_)\n{\n  int d = X_.rows - 1;\n\n  const Mat_<T> & X_rows = X_.rowRange(0,d);\n  const Mat_<T> h = X_.row(d);\n\n  const T * h_ptr = h[0], *h_ptr_end = h_ptr + h.cols;\n  const T * X_ptr = X_rows[0];\n  T * x_ptr = x_.ptr<T>(0);\n  for (; h_ptr != h_ptr_end; ++h_ptr, ++X_ptr, ++x_ptr)\n  {\n    const T * X_col_ptr = X_ptr;\n    T * x_col_ptr = x_ptr, *x_col_ptr_end = x_col_ptr + d * x_.step1();\n    for (; x_col_ptr != x_col_ptr_end; X_col_ptr+=X_rows.step1(), x_col_ptr+=x_.step1() )\n      *x_col_ptr = (*X_col_ptr) / (*h_ptr);\n  }\n}\n\nvoid\nhomogeneousToEuclidean(InputArray X_, OutputArray x_)\n{\n  // src\n  const Mat X = X_.getMat();\n\n  // dst\n   x_.create(X.rows-1, X.cols, X.type());\n  Mat x = x_.getMat();\n\n  // type\n  if( X.depth() == CV_32F )\n  {\n    homogeneousToEuclidean<float>(X,x);\n  }\n  else\n  {\n    homogeneousToEuclidean<double>(X,x);\n  }\n}\n\nvoid\neuclideanToHomogeneous(InputArray x_, OutputArray X_)\n{\n  const Mat x = x_.getMat();\n  const Mat last_row = Mat::ones(1, x.cols, x.type());\n  vconcat(x, last_row, X_);\n}\n\ntemplate<typename T>\nvoid\nprojectionFromKRt(const Mat_<T> &K, const Mat_<T> &R, const Mat_<T> &t, Mat_<T> P)\n{\n  hconcat( K*R, K*t, P );\n}\n\nvoid\nprojectionFromKRt(InputArray K_, InputArray R_, InputArray t_, OutputArray P_)\n{\n  const Mat K = K_.getMat(), R = R_.getMat(), t = t_.getMat();\n  const int depth = K.depth();\n  CV_Assert((K.cols == 3 && K.rows == 3) && (t.cols == 1 && t.rows == 3) && (K.size() == R.size()));\n  CV_Assert((depth == CV_32F || depth == CV_64F) && depth == R.depth() && depth == t.depth());\n\n  P_.create(3, 4, depth);\n\n  Mat P = P_.getMat();\n\n  // type\n  if( depth == CV_32F )\n  {\n    projectionFromKRt<float>(K, R, t, P);\n  }\n  else\n  {\n    projectionFromKRt<double>(K, R, t, P);\n  }\n\n}\n\ntemplate<typename T>\nvoid\nKRtFromProjection( const Mat_<T> &P_, Mat_<T> K_, Mat_<T> R_, Mat_<T> t_ )\n{\n  libmv::Mat34 P;\n  libmv::Mat3 K, R;\n  libmv::Vec3 t;\n\n  cv2eigen( P_, P );\n\n  libmv::KRt_From_P( P, &K, &R, &t );\n\n  eigen2cv( K, K_ );\n  eigen2cv( R, R_ );\n  eigen2cv( t, t_ );\n}\n\nvoid\nKRtFromProjection( InputArray P_, OutputArray K_, OutputArray R_, OutputArray t_ )\n{\n  const Mat P = P_.getMat();\n  const int depth = P.depth();\n  CV_Assert((P.cols == 4 && P.rows == 3) && (depth == CV_32F || depth == CV_64F));\n\n  K_.create(3, 3, depth);\n  R_.create(3, 3, depth);\n  t_.create(3, 1, depth);\n\n  Mat K = K_.getMat(), R = R_.getMat(), t = t_.getMat();\n\n  // type\n  if( depth == CV_32F )\n  {\n    KRtFromProjection<float>(P, K, R, t);\n  }\n  else\n  {\n    KRtFromProjection<double>(P, K, R, t);\n  }\n}\n\ntemplate<typename T>\nT\ndepthValue( const Mat_<T> &R_, const Mat_<T> &t_, const Mat_<T> &X_ )\n{\n  Matx<T,3,3> R(R_);\n  Vec<T,3> t(t_);\n\n  if ( X_.rows == 3)\n  {\n    Vec<T,3> X(X_);\n    return (R*X)(2) + t(2);\n  }\n  else\n  {\n    Vec<T,4> X(X_);\n    Vec<T,3> Xe;\n    homogeneousToEuclidean(X,Xe);\n    return depthValue<T>( Mat(R), Mat(t), Mat(Xe) );\n  }\n}\n\ndouble\ndepth( InputArray R_, InputArray t_, InputArray X_)\n{\n  const Mat R = R_.getMat(), t = t_.getMat(), X = X_.getMat();\n  const int depth = R.depth();\n  CV_Assert( R.rows == 3 && R.cols == 3 && t.rows == 3 && t.cols == 1 );\n  CV_Assert( (X.rows == 3 && X.cols == 1) || (X.rows == 4 && X.cols == 1) );\n  CV_Assert( depth == CV_32F || depth == CV_64F );\n\n  double depth_value = 0.0;\n\n  if ( depth == CV_32F )\n  {\n    depth_value = static_cast<double>(depthValue<float>(R, t, X));\n  }\n  else\n  {\n    depth_value = depthValue<double>(R, t, X);\n  }\n\n  return depth_value;\n}\n\n} /* namespace sfm */\n} /* namespace cv */\n", "meta": {"hexsha": "49e73d98df468c8397bb1108468325a1ae5481ec", "size": 5538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/sfm/src/projection.cpp", "max_stars_repo_name": "Nondzu/opencv_contrib", "max_stars_repo_head_hexsha": "0b0616a25d4239ee81fda965818b49b721620f56", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7158.0, "max_stars_repo_stars_event_min_datetime": "2016-07-04T22:19:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:54:32.000Z", "max_issues_repo_path": "modules/sfm/src/projection.cpp", "max_issues_repo_name": "Nondzu/opencv_contrib", "max_issues_repo_head_hexsha": "0b0616a25d4239ee81fda965818b49b721620f56", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2184.0, "max_issues_repo_issues_event_min_datetime": "2016-07-05T12:04:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T19:10:12.000Z", "max_forks_repo_path": "modules/sfm/src/projection.cpp", "max_forks_repo_name": "Nondzu/opencv_contrib", "max_forks_repo_head_hexsha": "0b0616a25d4239ee81fda965818b49b721620f56", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5535.0, "max_forks_repo_forks_event_min_datetime": "2016-07-06T12:01:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:13:24.000Z", "avg_line_length": 24.7232142857, "max_line_length": 100, "alphanum_fraction": 0.6375947996, "num_tokens": 1741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.41886563607946053}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <list>\n#include <set>\n#include <stack>\n#include <algorithm>\n#include <boost/date_time.hpp>\n\ntypedef std::vector<std::vector<unsigned long>> Graph;\n\nstd::stack<unsigned long> topological(Graph vertices, unsigned long vertice_count){\n\n    std::cout << (\"finding topological\") << std::endl;\n    std::set<unsigned long> notfound;\n    for(unsigned long i=0;i<vertices.size();i++) notfound.emplace(i);\n    std::set<unsigned long> found;\n    std::stack<unsigned long> topo;\n    std::stack<std::pair<unsigned long, bool>> stack;\n\n    while (topo.size() < vertices.size()){\n        if (stack.empty()){\n            auto p = notfound.begin();\n            stack.emplace(*p, false);\n        }\n        std::pair<unsigned long,bool> holder = stack.top();\n        stack.pop();\n        unsigned long i = holder.first;\n        bool backtracking = holder.second;\n        auto pos = found.find(i);\n        if (not backtracking and pos == found.end()){\n            notfound.erase(notfound.find(i));\n            found.emplace(i);\n            std::vector<unsigned long> children = vertices[i];\n            bool pisfound = false;\n            for(auto p = children.begin(); p != children.end(); pisfound ? p = children.erase(p) : p++ ){ // remove found children\n                pisfound = false;\n                if (found.find(*p) != found.end()){\n                    pisfound = true;\n                }\n            }\n            if(not children.empty()){\n                stack.emplace(i, true);\n                for (unsigned long v : children){\n                    stack.emplace(v, false);\n                }\n            } else {\n                topo.emplace(i);\n            }\n        } else if (backtracking){\n            topo.emplace(i);\n        }\n\n    }\n    return topo;\n}\n\nvoid load_vertices(const std::string &filename, bool get_r,\n        Graph &vertices, Graph &vertices_r\n                ,unsigned long &vertice_count, unsigned long &edge_count){\n\n    std::cout << \"reading file\" << std::endl;\n    std::fstream file(filename, std::ios::in);\n\n    file >> vertice_count >> edge_count;\n\n    vertices.reserve(static_cast<unsigned long>(vertice_count));\n    vertices_r.reserve(static_cast<unsigned long>(vertice_count));\n    for(unsigned long _ = 0; _ < vertice_count; _++){\n        vertices.emplace_back(std::vector<unsigned long>());\n        if (get_r) vertices_r.emplace_back(std::vector<unsigned long>());\n    }\n\n    unsigned long to, fro;\n    while (file >> to >> fro) {\n        vertices[to].emplace_back(fro);\n        if (get_r) vertices_r[fro].emplace_back(to);\n    }\n    file.close();\n}\n\n\nstd::vector<std::vector<unsigned long>> findComponents(Graph vertices, unsigned long vertice_count, std::stack<unsigned long> order){\n    std::cout << \"finding components\" << std::endl;\n    std::vector<unsigned long> nodecomp;\n    nodecomp.reserve(static_cast<unsigned long>(vertice_count));\n    for(unsigned long _ = 0; _ < vertice_count; _++) nodecomp.emplace_back(ULONG_MAX);\n    unsigned long comp = 0;\n\n    while (not order.empty()){\n        unsigned long v = order.top();\n        order.pop();\n\n        if (nodecomp[v] == ULONG_MAX){\n            std::vector<unsigned long> children = vertices[v];\n            nodecomp[v] = comp;\n            while (not children.empty()){\n                auto p = children.begin();\n                unsigned long c = *p;\n                children.erase(p);\n                if (nodecomp[c] == ULONG_MAX){\n                    nodecomp[c] = comp;\n                    std::vector<unsigned long> subch = vertices[c];\n                    for (unsigned long i : subch) children.emplace_back(i);\n\n                }\n            }\n            comp++;\n        }\n\n    }\n    std::vector<std::vector<unsigned long>> result;\n    result.reserve(static_cast<unsigned long>(comp));\n    for(unsigned long _ = 0; _ < comp; _++) result.emplace_back(std::vector<unsigned long>());\n    for(unsigned long i = 0; i < nodecomp.size(); i++){\n        unsigned long v = nodecomp[i];\n        result[v].emplace_back(i);\n    }\n    return result;\n\n}\n\n\nint main(int argc, char* argv[]) {\n\n    std::string filename = \"L7Skandinavia\";\n    if (argc > 1)\n        filename = argv[1];\n\n    Graph vertices;\n    Graph vertices_r;\n    unsigned long vertice_count = 0;\n    unsigned long edge_count = 0;\n\n    boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time();\n    load_vertices(filename, true, vertices, vertices_r, vertice_count, edge_count);\n     boost::posix_time::ptime end = boost::posix_time::microsec_clock::local_time();\n    std::cout << \"loaded \" << vertices.size() << \" vertices in \" << (end-start).total_microseconds()/1000000. << \" seconds\" << std::endl;\n\n    start = boost::posix_time::microsec_clock::local_time();\n    std::stack<unsigned long> topo = topological(vertices, vertice_count);\n    end = boost::posix_time::microsec_clock::local_time();\n    auto ostart = start;\n    std::cout << \"found topological order in \" << (end-start).total_microseconds()/1000000. << \" seconds\" << std::endl;\n\n    start = boost::posix_time::microsec_clock::local_time();\n    auto strongs = findComponents(vertices_r, vertice_count, topo);\n    end = boost::posix_time::microsec_clock::local_time();\n    std::cout << \"found components in \" << (end-start).total_microseconds()/1000000. << \" seconds\" << std::endl;\n    std::cout << \"total time: \" << (end-ostart).total_microseconds()/1000000 << \" seconds\" << std::endl;\n\n\n    std::cout << \"grafen \" << filename << \" har \" << strongs.size() << \" sterkt sammenhengende komponenter.\" << std::endl;\n    if (strongs.size() < 100){\n        std::cout << \"Komponent\\t\\tNoder i komponenten\" << std::endl;\n        for(unsigned long i = 0; i < strongs.size(); i++){\n            std::vector<unsigned long> v = strongs[i];\n            std::cout << i << \"\\t\\t\\t\\t\";\n            for(unsigned long j = 0; j < v.size(); j++){\n                std::cout << v[j];\n                if (j+1 < v.size()) std::cout << \", \";\n            }\n            std::cout << std::endl;\n        }\n    }\n\n    return EXIT_SUCCESS;\n\n\n}\n", "meta": {"hexsha": "fa8c7582d8fa9c1552fb3376e8f30061a0f8608a", "size": 6101, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "oving7/main.cpp", "max_stars_repo_name": "odderikf/algdat", "max_stars_repo_head_hexsha": "9b5e5ea42ca0fefda3c1e9be5cff0be4797a8aae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-12T21:49:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-12T21:49:32.000Z", "max_issues_repo_path": "oving7/main.cpp", "max_issues_repo_name": "odderikf/algdat", "max_issues_repo_head_hexsha": "9b5e5ea42ca0fefda3c1e9be5cff0be4797a8aae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "oving7/main.cpp", "max_forks_repo_name": "odderikf/algdat", "max_forks_repo_head_hexsha": "9b5e5ea42ca0fefda3c1e9be5cff0be4797a8aae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6783625731, "max_line_length": 137, "alphanum_fraction": 0.5807244714, "num_tokens": 1437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.41886563607946053}}
{"text": "#include \"NumberMpq.h\"\n\n#include \"NumberClI.h\"\n#include \"NumberClRA.h\"\n#include \"NumberMpz.h\"\n\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/split.hpp>\n\n\nnamespace carl {\n\n#ifdef USE_CLN_NUMBERS\n\t\tNumber<mpq_class>::Number(const Number<cln::cl_RA>& n) : Number(n.toString()) {} \n\t\tNumber<mpq_class>::Number(const Number<cln::cl_I>& n) : Number(n.toString()) {} \n#endif\n\n\n\t//TODO: probably also add possibility to construct from fraction strings; is there a reason for this complicated method? instead of using mpq_class constructor??\n\tNumber<mpq_class>::Number(const std::string& s) {\n\t\tstd::vector<std::string> strs;\n\t\tboost::split(strs, s, boost::is_any_of(\".\"));\n\n\t\tif(strs.size() > 2)\n\t\t{\n\t\t    throw std::invalid_argument(\"More than one delimiter in the string.\");\n\t\t}\n\t\tmpq_class result;\n\t\tif(!strs.front().empty())\n\t\t{\n\t\t    result += mpq_class(strs.front());\n\t\t}\n\t\tif(strs.size() > 1)\n\t\t{\n\t\t    //if(strs.back().size() > )\n\t\t    result += (mpq_class(strs.back())/carl::pow(mpz_class(10),static_cast<unsigned>(strs.back().size())));\n\t\t}\n\t\tmData = result;\n\t}\n\n\t//constructs a/b:\n\tNumber<mpq_class>::Number(const Number<mpz_class>& a,const Number<mpz_class>& b) { mData = mpq_class(a.getValue(),b.getValue()); }\n\n\n\tNumber<mpq_class>::Number(const Number<mpz_class>& n) { mData = mpq_class(n.getValue()); }\n\tNumber<mpq_class>::Number(const mpz_class& n) { mData = mpq_class(n); }\n\n\n\n\t\n\n\n\n\n\n   \n\n\t//TODO: doesn't mpq_class have a standard \"output\" as well?\n\tstd::string Number<mpq_class>::toString(bool _infix) const\n\t{\n\t\tstd::stringstream s;\n\t\tbool negative = (mData < mpq_class(0));\n\t\tif(negative) s << \"(-\" << (_infix ? \"\" : \" \");\n\t\tif(_infix) s << this->abs();\n\t\telse\n\t\t{\n\t\t    mpz_class d = mData.get_den();\n\t\t    if(constant_one<mpz_class>::get() != mData) {\n\t\t\tmpz_class abs1, abs2;\n\t\t\tmpz_abs(abs1.get_mpz_t(), mData.get_num().get_mpz_t());\n\t\t\tmpz_abs(abs2.get_mpz_t(), d.get_mpz_t());\n\t\t\ts << \"(/ \" << abs1 << \" \" << abs2 << \")\";\n\t\t    } else {\n\t\t\ts << this->abs().mData;\n\t\t\t}\n\t\t}\n\t\tif(negative)\n\t\t    s << \")\";\n\t\treturn s.str();\n\t}\n\n\n\t bool Number<mpq_class>::sqrt_exact(Number<mpq_class>& b) const\n\t    {\n\t\tif( mpq_sgn(mData.__get_mp()) < 0 ) return false;\n\t\tmpz_class den = mData.get_den();\n\t\tmpz_class num = mData.get_num();\n\t\tmpz_class root_den;\n\t\tmpz_class root_den_rem;\n\t\tmpz_sqrtrem(root_den.__get_mp(), root_den_rem.__get_mp(), den.__get_mp());\n\t\tif( !Number( root_den_rem ).isZero() )\n\t\t    return false;\n\n\t\tmpz_class root_num;\n\t\tmpz_class root_num_rem;\n\t\tmpz_sqrtrem(root_num.__get_mp(), root_num_rem.__get_mp(), num.__get_mp());\n\t\tif( !Number( root_num_rem ).isZero() )\n\t\t    return false;\n\n\t\tmpq_class resNum;\n\t\tmpq_set_z(resNum.get_mpq_t(), root_num.get_mpz_t());\n\t\tmpq_class resDen;\n\t\tmpq_set_z(resDen.get_mpq_t(), root_den.get_mpz_t());\n\t\t\n\t\tmpq_class fraction;\n\t\tmpq_div(fraction.get_mpq_t(), resNum.get_mpq_t(), resDen.get_mpq_t());\n\n\t\tb = Number<mpq_class>(fraction);\n\t\treturn true;\n\t    } \n\n\t    Number<mpq_class> Number<mpq_class>::sqrt() const {\n\t\tstd::pair<Number<mpq_class>,Number<mpq_class>> r = this->sqrt_safe();\n\t\treturn (r.first + r.second) / 2;\n\t    }\n\n\t    std::pair<Number<mpq_class>,Number<mpq_class>> Number<mpq_class>::sqrt_safe() const\n\t    {\n\t\tassert( mpq_sgn(mData.__get_mp()) > 0 );\n\t\tmpz_class den = mData.get_den();\n\t\tmpz_class num = mData.get_num();\n\t\tmpz_class root_den;\n\t\tmpz_class root_den_rem;\n\t\tmpz_sqrtrem(root_den.__get_mp(), root_den_rem.__get_mp(), den.__get_mp());\n\n\t\tmpz_class root_num;\n\t\tmpz_class root_num_rem;\n\t\tmpz_sqrtrem(root_num.__get_mp(), root_num_rem.__get_mp(), num.__get_mp());\n\n\t\tmpq_class lower;\n\t\tmpq_class upper;\n\n\t\tlower = root_num;\n\t\tif(root_den_rem == 0)\n\t\t    lower /= root_den;\n\t\telse\n\t\t    lower /= root_den+1;\n\n\t\tif(root_num_rem == 0)\n\t\t    upper = root_num;\n\t\telse\n\t\t    upper = root_num+1;\n\n\t\tupper /= root_den;\n\n\t\treturn std::make_pair(Number(lower),Number(upper));\n\t    }\n\n\t    std::pair<Number<mpq_class>, Number<mpq_class>> Number<mpq_class>::sqrt_fast() const\n\t    {\n\t\tassert(mData >= 0);\n\t#if 1\n\t\treturn sqrt_safe(); //NOTE: there was something (probably) equivalent to sqrt_safe() here, so this replacement should be ok\n\t#else\n\t\tmpq_class exact_root;\n\t\tif (carl::sqrtp(mData, exact_root)) {\n\t\t    // root can be computed exactly.\n\t\t    return std::make_pair(exact_root, exact_root);\n\t\t} else {\n\t\t    // compute an approximation with sqrt(). we can assume that the surrounding integers contain the actual root.\n\t\t    mpf_class af = sqrt(mpf_class(mData));\n\t\t    mpq_class lower(af - carl::constant_one<mpf_class>::get());\n\t\t    mpq_class upper(af + carl::constant_one<mpf_class>::get());\n\t\t    assert(lower * lower < mData);\n\t\t    assert(upper * upper > mData);\n\t\t    return std::make_pair(lower, upper);\n\t\t}\n\t#endif\n\t    }\n\n\n\n}\n", "meta": {"hexsha": "425c61cdba1df03df990d08cb153f4eb2f4ff183", "size": 4765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/carl/numbers/number/NumberMpq.cpp", "max_stars_repo_name": "smtrat/carl-windows", "max_stars_repo_head_hexsha": "22b3a7677477cdbed9adc7619479ce82a0304666", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/carl/numbers/number/NumberMpq.cpp", "max_issues_repo_name": "smtrat/carl-windows", "max_issues_repo_head_hexsha": "22b3a7677477cdbed9adc7619479ce82a0304666", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/carl/numbers/number/NumberMpq.cpp", "max_forks_repo_name": "smtrat/carl-windows", "max_forks_repo_head_hexsha": "22b3a7677477cdbed9adc7619479ce82a0304666", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3850574713, "max_line_length": 162, "alphanum_fraction": 0.6593913956, "num_tokens": 1430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.41886563607946053}}
{"text": "#ifndef MIA_SPACIAL_HPP\n#define MIA_SPACIAL_HPP\n\n#include <array>\n#include <cstddef>\n#include <functional>\n#include <tuple>\n#include <type_traits>\n#include <utility>\n#include <gsl/gsl_assert>\n#include <gsl/gsl_util>\n#include <boost/hana/equal.hpp>\n#include <boost/hana/ext/std/array.hpp>\n#include <boost/hana/range.hpp>\n#include <boost/hana/unpack.hpp>\n#include <range/v3/utility/common_type.hpp>\n#include <range/v3/utility/concepts.hpp>\n#include <jegp/utility.hpp>\n#include <mia/concepts.hpp>\n#include <mia/units.hpp>\n\nnamespace mia {\n\nenum class Axis { x, y, z };\n\ntemplate <Axis A, class Qty>\nclass Coordinate;\n\nnamespace detail {\n\n    template <Axis A>\n    struct Mp_coordinate {\n        template <class Qty>\n        using fn = Coordinate<A, Qty>;\n    };\n\n} // namespace detail\n\ntemplate <Axis A, class Qty>\nclass Coordinate\n  : public Unit_alias<detail::Mp_coordinate<A>::template fn, Qty> {\npublic:\n    static_assert(A >= Axis::x);\n\n    static constexpr Axis axis{A};\n\n    using Unit_alias<detail::Mp_coordinate<A>::template fn, Qty>::Unit_alias;\n};\n\ntemplate <class Qty>\nusing Abscissa = Coordinate<Axis::x, Qty>;\ntemplate <class Qty>\nusing Ordinate = Coordinate<Axis::y, Qty>;\ntemplate <class Qty>\nusing Applicate = Coordinate<Axis::z, Qty>;\n\n} // namespace mia\n\nnamespace ranges {\n\ntemplate <mia::Axis A, class Qty1, class Qty2>\nstruct common_type<mia::Coordinate<A, Qty1>, mia::Coordinate<A, Qty2>> {\n    using type = mia::Coordinate<A, common_type_t<Qty1, Qty2>>;\n};\n\n} // namespace ranges\n\nnamespace std {\n\ntemplate <mia::Axis A, class Qty>\nstruct hash<mia::Coordinate<A, Qty>>\n  : mia::detail::Unit_alias_hash<\n        mia::detail::Mp_coordinate<A>::template fn, Qty> {\n};\n\n} // namespace std\n\nnamespace mia {\n\nenum class Coordinates;\n\ntemplate <Coordinates C, class Qty>\nclass Point {\npublic:\n    static_assert(C >= Coordinates{1});\n    static_assert(Quantity<Qty>{});\n\n    static constexpr Coordinates coordinates{C};\n    using quantity = Qty;\n\nprivate:\n    static constexpr boost::hana::range<int, 0, jegp::underlying(coordinates)>\n        ints{};\n\n    static constexpr std::array axes{boost::hana::unpack(\n        ints, [](auto... int_c) { return std::array{Axis{int_c()}...}; })};\n\npublic:\n    Point()             = default;\n    Point(const Point&) = default;\n    Point(Point&&)      = default;\n    ~Point()            = default;\n    Point& operator=(const Point&) = default;\n    Point& operator=(Point&&) = default;\n\n    template <\n        Axis... A, class... Qty2,\n        CONCEPT_REQUIRES_(\n            std::conjunction_v<\n                std::bool_constant<boost::hana::equal(axes, std::array{A...})>,\n                ranges::Constructible<\n                    Coordinate<A, quantity>, const Coordinate<A, Qty2>&>...>)>\n    explicit constexpr Point(const Coordinate<A, Qty2>&... coord) noexcept(\n        std::conjunction_v<std::is_nothrow_constructible<\n            Coordinate<A, quantity>, const Coordinate<A, Qty2>&>...>)\n      : coords{coord...}\n    {\n    }\n\n    template <\n        class Qty2, CONCEPT_REQUIRES_(ranges::Constructible<quantity, Qty2>{})>\n    constexpr Point(const Point<coordinates, Qty2>& pt) noexcept(\n        std::is_nothrow_copy_constructible_v<Qty2>&&\n            std::is_nothrow_constructible_v<quantity, Qty2>)\n      : coords{boost::hana::unpack(ints, [&](auto... int_c) {\n            return Coords{pt.template get<int_c>()...};\n        })}\n    {\n    }\n\n    constexpr Abscissa<quantity>& x() noexcept\n    {\n        return std::get<jegp::underlying(Axis::x)>(coords);\n    }\n    constexpr const Abscissa<quantity>& x() const noexcept\n    {\n        return std::get<jegp::underlying(Axis::x)>(coords);\n    }\n\n    template <Axis A = Axis::y, CONCEPT_REQUIRES_(A <= axes.back())>\n    constexpr Ordinate<quantity>& y() noexcept\n    {\n        return std::get<jegp::underlying(A)>(coords);\n    }\n    template <Axis A = Axis::y, CONCEPT_REQUIRES_(A <= axes.back())>\n    constexpr const Ordinate<quantity>& y() const noexcept\n    {\n        return std::get<jegp::underlying(A)>(coords);\n    }\n\n    template <Axis A = Axis::z, CONCEPT_REQUIRES_(A <= axes.back())>\n    constexpr Applicate<quantity>& z() noexcept\n    {\n        return std::get<jegp::underlying(A)>(coords);\n    }\n    template <Axis A = Axis::z, CONCEPT_REQUIRES_(A <= axes.back())>\n    constexpr const Applicate<quantity>& z() const noexcept\n    {\n        return std::get<jegp::underlying(A)>(coords);\n    }\n\n    template <std::size_t I>\n    constexpr Coordinate<Axis{I}, quantity>& get() noexcept\n    {\n        return std::get<I>(coords);\n    }\n    template <std::size_t I>\n    constexpr const Coordinate<Axis{I}, quantity>& get() const noexcept\n    {\n        return std::get<I>(coords);\n    }\n\nprivate:\n    static constexpr auto coords_tuple = [](auto... int_c) {\n        return std::tuple<Coordinate<axes[int_c], quantity>...>{};\n    };\n\n    using Coords = decltype(boost::hana::unpack(ints, coords_tuple));\n\n    Coords coords;\n};\n\ntemplate <Axis... A, class Qty>\nexplicit Point(Coordinate<A, Qty>...)->Point<Coordinates{sizeof...(A)}, Qty>;\n\ntemplate <class Qty>\nusing Point2d = Point<Coordinates{2}, Qty>;\ntemplate <class Qty>\nusing Point3d = Point<Coordinates{3}, Qty>;\n\ntemplate <\n    std::size_t I, Coordinates C, class Qty,\n    CONCEPT_REQUIRES_(I < jegp::underlying(C))>\nconstexpr Coordinate<Axis{I}, Qty>& get(Point<C, Qty>& pt) noexcept\n{\n    return pt.template get<I>();\n}\ntemplate <\n    std::size_t I, Coordinates C, class Qty,\n    CONCEPT_REQUIRES_(I < jegp::underlying(C))>\nconstexpr const Coordinate<Axis{I}, Qty>& get(const Point<C, Qty>& pt) noexcept\n{\n    return pt.template get<I>();\n}\n\ntemplate <\n    Axis A, Coordinates C, class Qty,\n    CONCEPT_REQUIRES_(Axis::x <= A && A < static_cast<Axis>(C))>\nconstexpr Coordinate<A, Qty>& get(Point<C, Qty>& pt) noexcept\n{\n    return pt.template get<jegp::underlying(A)>();\n}\ntemplate <\n    Axis A, Coordinates C, class Qty,\n    CONCEPT_REQUIRES_(Axis::x <= A && A < static_cast<Axis>(C))>\nconstexpr const Coordinate<A, Qty>& get(const Point<C, Qty>& pt) noexcept\n{\n    return pt.template get<jegp::underlying(A)>();\n}\n\ntemplate <\n    class Coord, Coordinates C, class Qty,\n    CONCEPT_REQUIRES_(\n        std::is_same_v<Coord, Coordinate<Coord::axis, Qty>> &&\n        (Axis::x <= Coord::axis && Coord::axis < static_cast<Axis>(C)))>\nconstexpr Coord& get(Point<C, Qty>& pt) noexcept\n{\n    return pt.template get<jegp::underlying(Coord::axis)>();\n}\ntemplate <\n    class Coord, Coordinates C, class Qty,\n    CONCEPT_REQUIRES_(\n        std::is_same_v<Coord, Coordinate<Coord::axis, Qty>> &&\n        (Axis::x <= Coord::axis && Coord::axis < static_cast<Axis>(C)))>\nconstexpr const Coord& get(const Point<C, Qty>& pt) noexcept\n{\n    return pt.template get<jegp::underlying(Coord::axis)>();\n}\n\ntemplate <\n    Coordinates C, class Qty1, class Qty2,\n    CONCEPT_REQUIRES_(ranges::EqualityComparable<Qty1, Qty2>{})>\nconstexpr auto operator==(\n    const Point<C, Qty1>& l,\n    const Point<C, Qty2>&\n        r) noexcept(noexcept(std::declval<Qty1>() == std::declval<Qty2>()))\n{\n    return boost::hana::unpack(\n        boost::hana::range_c<int, 0, jegp::underlying(C)>, [&](auto... int_c) {\n            return (... && (get<int_c>(l) == get<int_c>(r)));\n        });\n}\ntemplate <Coordinates C, class Qty1, class Qty2>\nconstexpr auto operator!=(\n    const Point<C, Qty1>& l,\n    const Point<C, Qty2>& r) noexcept(noexcept(!(l == r)))\n    -> decltype(!(l == r))\n{\n    return !(l == r);\n}\n\n} // namespace mia\n\nnamespace std {\n\ntemplate <mia::Coordinates C, class Qty>\nstruct tuple_size<mia::Point<C, Qty>>\n  : integral_constant<size_t, jegp::underlying(C)> {\n};\n\ntemplate <size_t I, mia::Coordinates C, class Qty>\nstruct tuple_element<I, mia::Point<C, Qty>> {\n    static_assert(I < jegp::underlying(C));\n\n    using type = mia::Coordinate<mia::Axis{I}, Qty>;\n};\n\n} // namespace std\n\nnamespace ranges {\n\ntemplate <mia::Coordinates C, class Qty1, class Qty2>\nstruct common_type<mia::Point<C, Qty1>, mia::Point<C, Qty2>> {\n    using type = mia::Point<C, common_type_t<Qty1, Qty2>>;\n};\n\n} // namespace ranges\n\nnamespace mia::detail {\n\ntemplate <class Tuple, class = void>\nstruct Tuple_hash\n  : Tuple_hash<Tuple, std::make_index_sequence<std::tuple_size_v<Tuple>>> {\n};\n\ntemplate <class Tuple, std::size_t... I>\nstruct Tuple_hash<Tuple, std::index_sequence<I...>>\n  : private std::hash<std::tuple_element_t<I, Tuple>>... {\n    constexpr auto operator()(const Tuple& t) const\n        noexcept(noexcept(jegp::hash_combine(get<I>(t)...)))\n            -> decltype(jegp::hash_combine(get<I>(t)...))\n    {\n        return jegp::hash_combine(get<I>(t)...);\n    }\n};\n\n} // namespace mia::detail\n\nnamespace std {\n\ntemplate <mia::Coordinates C, class Qty>\nstruct hash<mia::Point<C, Qty>> : mia::detail::Tuple_hash<mia::Point<C, Qty>> {\n};\n\n} // namespace std\n\nnamespace mia {\n\ntemplate <Axis A, class Qty>\nclass Dimension;\n\nnamespace detail {\n\n    template <Axis A>\n    struct Mp_dimension {\n        template <class Qty>\n        using fn = Dimension<A, Qty>;\n    };\n\n} // namespace detail\n\ntemplate <Axis A, class Qty>\nclass Dimension : public Unit_alias<detail::Mp_dimension<A>::template fn, Qty> {\npublic:\n    static_assert(A >= Axis::x);\n\n    static constexpr Axis axis{A};\n\n    using Unit_alias<detail::Mp_dimension<A>::template fn, Qty>::Unit_alias;\n};\n\ntemplate <class Qty>\nusing Width = Dimension<Axis::x, Qty>;\ntemplate <class Qty>\nusing Height = Dimension<Axis::y, Qty>;\ntemplate <class Qty>\nusing Depth = Dimension<Axis::z, Qty>;\n\n} // namespace mia\n\nnamespace ranges {\n\ntemplate <mia::Axis A, class Qty1, class Qty2>\nstruct common_type<mia::Dimension<A, Qty1>, mia::Dimension<A, Qty2>> {\n    using type = mia::Dimension<A, common_type_t<Qty1, Qty2>>;\n};\n\n} // namespace ranges\n\nnamespace std {\n\ntemplate <mia::Axis A, class Qty>\nstruct hash<mia::Dimension<A, Qty>>\n  : mia::detail::Unit_alias_hash<\n        mia::detail::Mp_dimension<A>::template fn, Qty> {\n};\n\n} // namespace std\n\nnamespace mia {\n\nenum class Dimensions;\n\ninline namespace literals {\n    inline namespace dimensions_literals { //\n\n        constexpr Dimensions operator\"\"_D(unsigned long long d)\n        {\n            return gsl::narrow_cast<Dimensions>(d);\n        }\n\n    } // namespace dimensions_literals\n} // namespace literals\n\ntemplate <Dimensions D, class Qty>\nclass Size {\npublic:\n    static_assert(D >= 1_D);\n    static_assert(Quantity<Qty>{});\n\n    static constexpr Dimensions dimensions{D};\n    using quantity = Qty;\n\nprivate:\n    static constexpr boost::hana::range<int, 0, jegp::underlying(dimensions)>\n        ints{};\n\n    static constexpr std::array axes{boost::hana::unpack(\n        ints, [](auto... int_c) { return std::array{Axis{int_c()}...}; })};\n\npublic:\n    Size(const Size&) = default;\n    Size(Size&&)      = default;\n    ~Size()           = default;\n    Size& operator=(const Size&) = default;\n    Size& operator=(Size&&) = default;\n\n    template <\n        Axis... A, class... Qty2,\n        CONCEPT_REQUIRES_(\n            std::conjunction_v<\n                std::bool_constant<boost::hana::equal(axes, std::array{A...})>,\n                ranges::Constructible<\n                    Dimension<A, quantity>, const Dimension<A, Qty2>&>...>)>\n    explicit constexpr Size(const Dimension<A, Qty2>&... dim)\n      : dims{[&] {\n            (..., Expects((dim > Dimension<A, Qty2>{})));\n            return Dims{dim...};\n        }()}\n    {\n    }\n\n    template <\n        class Qty2, CONCEPT_REQUIRES_(ranges::Constructible<quantity, Qty2>{})>\n    constexpr Size(const Size<dimensions, Qty2>& sz) noexcept(\n        std::is_nothrow_copy_constructible_v<Qty2>&&\n            std::is_nothrow_constructible_v<quantity, Qty2>)\n      : dims{boost::hana::unpack(ints, [&](auto... int_c) {\n            return Dims{sz.template get<int_c>()...};\n        })}\n    {\n    }\n\n    constexpr void w(const Width<quantity>& w)\n    {\n        Expects(w > Width<quantity>{});\n        std::get<jegp::underlying(Axis::x)>(dims) = w;\n    }\n    template <Axis A = Axis::y, CONCEPT_REQUIRES_(A <= axes.back())>\n    constexpr void h(const Height<quantity>& h)\n    {\n        Expects(h > Height<quantity>{});\n        std::get<jegp::underlying(A)>(dims) = h;\n    }\n    template <Axis A = Axis::z, CONCEPT_REQUIRES_(A <= axes.back())>\n    constexpr void d(const Depth<quantity>& d)\n    {\n        Expects(d > Depth<quantity>{});\n        std::get<jegp::underlying(A)>(dims) = d;\n    }\n\n    template <Axis A, CONCEPT_REQUIRES_(Axis::x <= A && A <= axes.back())>\n    constexpr void set(const Dimension<A, quantity>& dim)\n    {\n        Expects((dim > Dimension<A, quantity>{}));\n        std::get<jegp::underlying(A)>(dims) = dim;\n    }\n\n    constexpr Width<quantity> w() const\n        noexcept(std::is_nothrow_copy_constructible_v<Width<quantity>>)\n    {\n        return std::get<jegp::underlying(Axis::x)>(dims);\n    }\n    template <Axis A = Axis::y, CONCEPT_REQUIRES_(A <= axes.back())>\n    constexpr Height<quantity> h() const\n        noexcept(std::is_nothrow_copy_constructible_v<Height<quantity>>)\n    {\n        return std::get<jegp::underlying(A)>(dims);\n    }\n    template <Axis A = Axis::z, CONCEPT_REQUIRES_(A <= axes.back())>\n    constexpr Depth<quantity> d() const\n        noexcept(std::is_nothrow_copy_constructible_v<Depth<quantity>>)\n    {\n        return std::get<jegp::underlying(A)>(dims);\n    }\n\n    template <std::size_t I>\n    constexpr Dimension<Axis{I}, quantity> get() const noexcept(\n        std::is_nothrow_copy_constructible_v<Dimension<Axis{I}, quantity>>)\n    {\n        return std::get<I>(dims);\n    }\n\nprivate:\n    static constexpr auto dims_tuple = [](auto... int_c) {\n        return std::tuple<Dimension<axes[int_c], quantity>...>{};\n    };\n\n    using Dims = decltype(boost::hana::unpack(ints, dims_tuple));\n\n    Dims dims;\n};\n\ntemplate <Axis... A, class Qty>\nexplicit Size(Dimension<A, Qty>...)->Size<Dimensions{sizeof...(A)}, Qty>;\n\ntemplate <class Qty>\nusing Size2d = Size<2_D, Qty>;\ntemplate <class Qty>\nusing Size3d = Size<3_D, Qty>;\n\ntemplate <\n    std::size_t I, Dimensions D, class Qty,\n    CONCEPT_REQUIRES_(I < jegp::underlying(D))>\nconstexpr Dimension<Axis{I}, Qty> get(const Size<D, Qty>& sz) noexcept(\n    std::is_nothrow_copy_constructible_v<Dimension<Axis{I}, Qty>>)\n{\n    return sz.template get<I>();\n}\ntemplate <\n    Axis A, Dimensions D, class Qty,\n    CONCEPT_REQUIRES_(Axis::x <= A && A < static_cast<Axis>(D))>\nconstexpr Dimension<A, Qty> get(const Size<D, Qty>& sz) noexcept(\n    std::is_nothrow_copy_constructible_v<Dimension<A, Qty>>)\n{\n    return sz.template get<jegp::underlying(A)>();\n}\ntemplate <\n    class Dim, Dimensions D, class Qty,\n    CONCEPT_REQUIRES_(\n        std::is_same_v<Dim, Dimension<Dim::axis, Qty>> &&\n        (Axis::x <= Dim::axis && Dim::axis < static_cast<Axis>(D)))>\nconstexpr Dim get(const Size<D, Qty>& sz) noexcept(\n    std::is_nothrow_copy_constructible_v<Dim>)\n{\n    return sz.template get<jegp::underlying(Dim::axis)>();\n}\n\ntemplate <\n    Dimensions D, class Qty1, class Qty2,\n    CONCEPT_REQUIRES_(ranges::EqualityComparable<Qty1, Qty2>{})>\nconstexpr auto operator==(\n    const Size<D, Qty1>& l,\n    const Size<D, Qty2>&\n        r) noexcept(noexcept(std::declval<Qty1>() == std::declval<Qty2>()))\n{\n    return boost::hana::unpack(\n        boost::hana::range_c<int, 0, jegp::underlying(D)>, [&](auto... int_c) {\n            return (... && (get<int_c>(l) == get<int_c>(r)));\n        });\n}\ntemplate <Dimensions D, class Qty1, class Qty2>\nconstexpr auto operator!=(\n    const Size<D, Qty1>& l,\n    const Size<D, Qty2>& r) noexcept(noexcept(!(l == r))) -> decltype(!(l == r))\n{\n    return !(l == r);\n}\n\n} // namespace mia\n\nnamespace std {\n\ntemplate <mia::Dimensions D, class Qty>\nstruct tuple_size<mia::Size<D, Qty>>\n  : integral_constant<size_t, jegp::underlying(D)> {\n};\n\ntemplate <size_t I, mia::Dimensions D, class Qty>\nstruct tuple_element<I, mia::Size<D, Qty>> {\n    static_assert(I < jegp::underlying(D));\n\n    using type = mia::Dimension<mia::Axis{I}, Qty>;\n};\n\n} // namespace std\n\nnamespace ranges {\n\ntemplate <mia::Dimensions D, class Qty1, class Qty2>\nstruct common_type<mia::Size<D, Qty1>, mia::Size<D, Qty2>> {\n    using type = mia::Size<D, common_type_t<Qty1, Qty2>>;\n};\n\n} // namespace ranges\n\nnamespace std {\n\ntemplate <mia::Dimensions D, class Qty>\nstruct hash<mia::Size<D, Qty>> : mia::detail::Tuple_hash<mia::Size<D, Qty>> {\n};\n\n} // namespace std\n\n#endif // MIA_SPACIAL_HPP\n", "meta": {"hexsha": "effca32ddfa70d5683d98458536db94082018704", "size": 16351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mia/spacial.hpp", "max_stars_repo_name": "johelegp/Made_in_Abyss", "max_stars_repo_head_hexsha": "eb62e00c7c9a17c194c946b7bb756b3d143be9a4", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-01T12:50:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-01T12:50:29.000Z", "max_issues_repo_path": "include/mia/spacial.hpp", "max_issues_repo_name": "johelegp/Made_in_Abyss", "max_issues_repo_head_hexsha": "eb62e00c7c9a17c194c946b7bb756b3d143be9a4", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mia/spacial.hpp", "max_forks_repo_name": "johelegp/Made_in_Abyss", "max_forks_repo_head_hexsha": "eb62e00c7c9a17c194c946b7bb756b3d143be9a4", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9027303754, "max_line_length": 80, "alphanum_fraction": 0.6357409333, "num_tokens": 4367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.41886563607946053}}
{"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2014 by Synge Todo <wistaria@comp-phys.org>\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n// C++ version of TITPACK Ver.2 by H. Nishimori\n\n#ifndef TITPACK_SMALL_HPP\n#define TITPACK_SMALL_HPP\n\n#include \"common.hpp\"\n#include \"hamiltonian.hpp\"\n#include <vector>\n#include <boost/tuple/tuple.hpp>\n\n//\n// matrix elements\n//\n\ntemplate<typename MATRIX>\nvoid elm3(hamiltonian const& hop, MATRIX& elemnt) {\n  elemnt.set_zeros();\n  for (int k = 0; k < hop.num_bonds(); ++k) {\n    int isite1, isite2;\n    boost::tie(isite1, isite2) = hop.site_pair(k);\n    int is = (1 << isite1) + (1 << isite2);\n    double wght = hop.bond_weight(k);\n    double diag = 0.5 * wght * hop.z_ratio(k);\n    #pragma omp parallel for schedule(static)\n    for (int i = 0; i < hop.dimension(); ++i) {\n      if (elemnt.is_gindex_myrow(i)) {\n        int ibit = hop.config(i) & is;\n        if (ibit == 0 || ibit == is) {\n          elemnt.update_global(i, i, -diag);\n        } else {\n          elemnt.update_global(i, i, +diag);\n          int newcfg = hop.config2index(hop.config(i) ^ is);\n          elemnt.update_global(i, newcfg, -wght);\n        }\n      }\n    }\n  }\n}\n\ntemplate<typename MATRIX>\nvoid elm3_sx(subspace const& ss, int i1, int i2, MATRIX& elemnt) {\n  elemnt.set_zeros();\n  if (i1 < 0 || i1 >= ss.num_sites() || i2 < 0 || i2 >= ss.num_sites() || i1 == i2) {\n    std::cerr << \" #(W01)# Wrong site number given to xcorr\\n\";\n    return;\n  }\n  int is = (1 << i1) + (1 << i2);\n  #pragma omp parallel for schedule(static)\n  for (int i = 0; i < ss.dimension(); ++i) {\n    if (elemnt.is_gindex_myrow(i)) {\n      int ibit = ss.config(i) & is;\n      if (ibit != 0 && ibit != is) {\n        int newcfg = ss.config2index(ss.config(i) ^ is);\n        elemnt.update_global(i, newcfg, 0.25);\n      }\n    }\n  }\n}\n\n//\n// check of the eigenvector and eigenvalue\n//\n// elemnt    @ nonzero elements\n// x         @ eigenvector to be checked\n// xindex\n// return value: Hexpec <x*H*x>\n\ntemplate<typename MATRIX>\ndouble check3(MATRIX const& elemnt, MATRIX const& x, int xindex, MATRIX& y) {\n  int idim = elemnt.rows();\n  double dnorm = 0;\n  for (int j = 0; j < idim; ++j) {\n    dnorm += x(j, xindex) * x(j, xindex);\n  }\n  if (dnorm < 1e-30) {\n    std::cerr << \" #(W18)# Null vector given to check3\\n\";\n    return 0;\n  }\n  for (int i = 0; i < idim; ++i) {\n    y(i, xindex) = 0;\n    for (int j = 0; j < idim; ++j) y(i, xindex) += elemnt(i, j) * x(j, xindex);\n  }\n  double prd = 0;\n  for (int i = 0; i < idim; ++i) prd += y(i, xindex) * x(i, xindex);\n  std::cout << \"---------------------------- Information from check3\\n\"\n            << \"<x*H*x> = \"<< prd << std::endl\n            << \"H*x(j)/x(j) (j=min(idim/3,13)-1,idim,max(1,idim/20))\";\n  int count = 0;\n  for (int i = std::min((int)(idim / 3), 13) - 1; i < idim; i += std::max(1,idim/20), ++count) {\n    if (count % 4 == 0) std::cout << std::endl;\n    std::cout << '\\t' << y(i, xindex) / x(i, xindex);\n  }\n  std::cout << std::endl << \"---------------------------------------------------\\n\";\n  return prd;\n}\n\ntemplate<typename MATRIX>\ndouble check3_mpi(MATRIX const& elemnt, MATRIX const& x, int xindex, MATRIX& y) {\n  int idim = elemnt.get_n_global();\n  double dnorm = dot_product(x, false, xindex, x, false, xindex);\n  product_v(1.0, elemnt, false, x, false, xindex, 0.0, y, false, xindex);\n  double prd = dot_product(x, false, xindex, y, false, xindex) / dnorm;\n\n  if (x.is_gindex(0, xindex)) {\n    std::cout << \"---------------------------- Information from check3\\n\"\n              << \"<x*H*x> = \"<< prd << std::endl\n              << \"H*x(j)/x(j) (j=min(idim/3,13)-1,idim,max(1,idim/20))\";\n  }\n  std::cout << std::flush;\n  MPI_Barrier(elemnt.get_grid().get_comm());\n  int count = 0;\n  for (int i = std::min((int)(idim / 3), 13) - 1; i < idim; i += std::max(1,idim/20), ++count) {\n    if (x.is_gindex(i, xindex)) {\n      if (count % 4 == 0) std::cout << std::endl;\n      std::cout << '\\t' << y.get_global(i, xindex) / x.get_global(i, xindex);\n    }\n    std::cout << std::flush;\n    MPI_Barrier(elemnt.get_grid().get_comm());\n  }\n  if (x.is_gindex(0, xindex)) {\n    std::cout << std::endl << \"---------------------------------------------------\\n\";\n  }\n  std::cout << std::flush;\n  return prd;\n}\n\ntemplate<typename MATRIX>\nvoid xcorr3_mpi(subspace const& ss, std::vector<int> const& npair, MATRIX const& x, int xindex,\n                std::vector<double>& sxx, MATRIX& sx, MATRIX& y) {\n  double dnorm = dot_product(x, false, xindex, x, false, xindex);\n  int nbond = npair.size() / 2;\n  for (int k = 0; k < nbond; ++k) {\n    int i1 = npair[k * 2];\n    int i2 = npair[k * 2 + 1];\n    elm3_sx(ss, i1, i2, sx);\n    product_v(1.0, sx, false, x, false, xindex, 0.0, y, false, xindex);\n    sxx[k] =dot_product(x, false, xindex, y, false, xindex) / dnorm;\n  }\n}\n\n#endif\n", "meta": {"hexsha": "56d8ed72944b34d956d4120f582f8b12e0c6337c", "size": 5121, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tutorial/titpack/03_rokko_cxx/small.hpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorial/titpack/03_rokko_cxx/small.hpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial/titpack/03_rokko_cxx/small.hpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4705882353, "max_line_length": 96, "alphanum_fraction": 0.541691076, "num_tokens": 1687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203136, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.41886562832255975}}
{"text": "// Copyright 2014 Vinzenz Feenstra\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//   http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n#ifndef GUARD_LSL_RUNTIME_QUATERNION_HH_INCLUDED\n#define GUARD_LSL_RUNTIME_QUATERNION_HH_INCLUDED\n\n#include <boost/math/constants/constants.hpp>\n#include <lsl/runtime/vector.hh>\n\nnamespace lsl {\nnamespace runtime {\n    struct Quaternion {\n        double x, y, z, s;\n    };\n\n    inline Quaternion identity(Quaternion) {\n        return {0., 0., 0., 1.};\n    }\n\n    inline Quaternion add(Quaternion l, Quaternion r) {\n        return Quaternion{\n            l.x + r.x,\n            l.y + r.y,\n            l.z + r.z,\n            l.s + l.s\n        };\n    }\n\n    inline Quaternion sub(Quaternion l, Quaternion r) {\n        return Quaternion{\n            l.x - r.x,\n            l.y - r.y,\n            l.z - r.z,\n            l.s - r.s\n        };\n    }\n\n    inline Quaternion mul(Quaternion l, Quaternion r) {\n        return Quaternion{\n            r.s * l.x + r.x * l.s + r.y * l.z - r.z * l.y,\n            r.s * l.y + r.y * l.s + r.z * l.x - r.x * l.z,\n            r.s * l.z + r.z * l.s + r.x * l.y - r.y * l.x,\n            r.s * l.s - r.x * l.x - r.y * l.y - r.z * l.z\n        };\n    }\n\n    inline Vector mul(Vector l, Quaternion r) {\n        Quaternion vq{l.x, l.y, l.z, 0.};\n        Quaternion nq{-r.x, -r.y, -r.z, r.s};\n        Quaternion result = mul(nq, mul(vq, r));\n        return{result.x, result.y, result.z};\n    }\n\n    inline Quaternion mul(Quaternion l, double r) {\n        return {l.x * r, l.y * r, l.z * r, l.s * r};\n    }\n\n    inline Quaternion div(Quaternion l, Quaternion r) {\n        r.s = -r.s;\n        return mul(l, r);\n    }\n\n    inline Vector div(Vector l, Quaternion r) {\n        r.s = -r.s;\n        return mul(l, r);\n    }\n\n    inline Vector operator * (Vector const & a, Quaternion const & b) {\n        return mul(a, b);\n    }\n    inline Quaternion operator * (Quaternion const & a, Quaternion const & b) {\n        return mul(a, b);\n    }\n    inline Quaternion operator * (Quaternion const & a, double b) {\n        return mul(a, b);\n    }\n    inline Quaternion operator / (Quaternion const & a, Quaternion const & b) {\n        return div(a, b);\n    }\n    inline Vector operator / (Vector const & a, Quaternion const & b) {\n        return div(a, b);\n    }\n    inline Quaternion operator + (Quaternion const & a, Quaternion const & b) {\n        return add(a, b);\n    }\n    inline Quaternion operator - (Quaternion const & a, Quaternion const & b) {\n        return sub(a, b);\n    }\n\n    inline bool operator==(Quaternion l, Quaternion r) {\n        return l.x == r.x\n            && l.y == r.y\n            && l.z == r.z\n            && l.s == r.s;\n    }\n\n    inline bool operator!=(Quaternion l, Quaternion r) {\n        return !(l == r);\n    }\n\n    inline Quaternion from_euler(Vector euler) {\n        double c1 = cos(euler.x * 0.5);\n        double c2 = cos(euler.y * 0.5);\n        double c3 = cos(euler.z * 0.5);\n\n        double s1 = sin(euler.x * 0.5);\n        double s2 = sin(euler.y * 0.5);\n        double s3 = sin(euler.z * 0.5);\n\n        Quaternion b{\n            s1 * c2 * c3 + c1 * s2 * s3,\n            c1 * s2 * c3 - s1 * c2 * s3,\n            s1 * s2 * c3 + c1 * c2 * s3,\n            c1 * c2 * c3 - s1 * s2 * s3,\n        };\n\n        auto a = Quaternion{0., 0., s3, c3}\n                 * Quaternion{0., s2, 0., c2}\n                 * Quaternion{s1, 0., 0., s1};\n        auto c = a + b;\n        auto d = a - b;\n        static double const err = 0.00001;\n        if(   (fabs(c.x) > err && fabs(d.x) > err)\n           || (fabs(c.y) > err && fabs(d.y) > err)\n           || (fabs(c.z) > err && fabs(d.z) > err)\n           || (fabs(c.s) > err && fabs(d.s) > err)) {\n            return b;\n        }\n        return a;\n    }\n\n    static double const FP_MAG_THRESHOLD        = 0.0000001;\n    static double const GIMBAL_THRESHOLD        = 0.000436;\n    static double const ONE_PART_IN_A_MILLION   = 0.000001;\n\n    inline Vector to_euler(Quaternion r) {\n        using namespace boost::math::double_constants;\n\n        double sx = 2. * (r.x * r.s - r.y * r.z);\n        double sy = 2. * (r.y * r.s + r.x * r.z);\n\n        double ys = r.s * r.s - r.y * r.y;\n        double xz = r.x * r.x - r.z * r.z;\n\n        double cx = ys - xz;\n        double cy = sqrt(sx * sx + cx * cx);\n\n        if(cy > GIMBAL_THRESHOLD) {\n            return Vector{\n                atan2(sx, cx),\n                atan2(sy, cy),\n                atan2(2 * (r.z * r.s - r.x * r.y), ys + xz)\n            };\n        }\n\n        if(sy > 0) {\n            return Vector{\n                0.,\n                half_pi,\n                2. * atan2(r.z + r.x, r.s + r.y)\n            };\n        }\n        return Vector{\n            0.,\n            half_pi * -1.,\n            atan2(r.z - r.x, r.s - r.y)\n        };\n    }\n\n    inline double mag(Quaternion q) {\n        return sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.s * q.s);\n    }\n\n    inline Quaternion normalize(Quaternion q) {\n\n        double m = mag(q);\n        if(m < FP_MAG_THRESHOLD) {\n            return Quaternion{0., 0., 0., 1.};\n        }\n        if(fabs(1. - m) > ONE_PART_IN_A_MILLION) {\n            double oomag = 1. / m;\n            return Quaternion{\n                q.x * oomag,\n                q.y * oomag,\n                q.z * oomag,\n                q.s * oomag\n            };\n        }\n        return q;\n    }\n\n    inline bool operator<(Quaternion l, Quaternion r) {\n        return mag(l) < mag(r);\n    }\n}\n}\n\n#endif //GUARD_LSL_RUNTIME_QUATERNION_HH_INCLUDED\n", "meta": {"hexsha": "c4116ed5762e3f8398346c6d77aaa95944fbdbbe", "size": 5985, "ext": "hh", "lang": "C++", "max_stars_repo_path": "lsl/runtime/quaternion.hh", "max_stars_repo_name": "vinzenz/lsl-emu", "max_stars_repo_head_hexsha": "3f799248ee57d0d11d6f12e6ff0f48cf359ced1e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-28T19:26:44.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-28T19:26:44.000Z", "max_issues_repo_path": "lsl/runtime/quaternion.hh", "max_issues_repo_name": "vinzenz/lsl-emu", "max_issues_repo_head_hexsha": "3f799248ee57d0d11d6f12e6ff0f48cf359ced1e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lsl/runtime/quaternion.hh", "max_forks_repo_name": "vinzenz/lsl-emu", "max_forks_repo_head_hexsha": "3f799248ee57d0d11d6f12e6ff0f48cf359ced1e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6363636364, "max_line_length": 79, "alphanum_fraction": 0.494235589, "num_tokens": 1701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289835, "lm_q2_score": 0.5506073655352405, "lm_q1q2_score": 0.4188198579383262}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2006,2010-2012 Free Software Foundation, Inc.\n *\n * This file is part of GNU Radio\n *\n * GNU Radio is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3, or (at your option)\n * any later version.\n *\n * GNU Radio is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GNU Radio; see the file COPYING.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street,\n * Boston, MA 02110-1301, USA.\n */\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"costas_loop_cc_impl.h\"\n#include <gnuradio/io_signature.h>\n#include <gnuradio/expj.h>\n#include <gnuradio/sincos.h>\n#include <gnuradio/math.h>\n#include <boost/format.hpp>\n\nnamespace gr {\n  namespace digital {\n\n    costas_loop_cc::sptr\n    costas_loop_cc::make(float loop_bw, int order, bool use_snr)\n    {\n      return gnuradio::get_initial_sptr\n\t(new costas_loop_cc_impl(loop_bw, order, use_snr));\n    }\n\n    static int ios[] = { sizeof(gr_complex), sizeof(float), sizeof(float), sizeof(float) };\n    static std::vector<int> iosig(ios, ios+sizeof(ios)/sizeof(int));\n\n    costas_loop_cc_impl::costas_loop_cc_impl(float loop_bw, int order, bool use_snr)\n      : sync_block(\"costas_loop_cc\",\n                   io_signature::make(1, 1, sizeof(gr_complex)),\n                   io_signature::makev(1, 4, iosig)),\n\tblocks::control_loop(loop_bw, 1.0, -1.0),\n\td_order(order), d_error(0), d_noise(1.0), d_phase_detector(NULL)\n    {\n      // Set up the phase detector to use based on the constellation order\n      switch(d_order) {\n      case 2:\n        if(use_snr)\n          d_phase_detector = &costas_loop_cc_impl::phase_detector_snr_2;\n\telse\n          d_phase_detector = &costas_loop_cc_impl::phase_detector_2;\n\tbreak;\n\n      case 4:\n        if(use_snr)\n          d_phase_detector = &costas_loop_cc_impl::phase_detector_snr_4;\n\telse\n          d_phase_detector = &costas_loop_cc_impl::phase_detector_4;\n\tbreak;\n\n      case 8:\n        if(use_snr)\n          d_phase_detector = &costas_loop_cc_impl::phase_detector_snr_8;\n\telse\n          d_phase_detector = &costas_loop_cc_impl::phase_detector_8;\n\tbreak;\n\n      default:\n\tthrow std::invalid_argument(\"order must be 2, 4, or 8\");\n\tbreak;\n      }\n\n      message_port_register_in(pmt::mp(\"noise\"));\n      set_msg_handler(\n        pmt::mp(\"noise\"),\n        boost::bind(&costas_loop_cc_impl::handle_set_noise,\n                    this, _1));\n    }\n\n    costas_loop_cc_impl::~costas_loop_cc_impl()\n    {\n    }\n\n    float\n    costas_loop_cc_impl::phase_detector_8(gr_complex sample) const\n    {\n      /* This technique splits the 8PSK constellation into 2 squashed\n\t QPSK constellations, one when I is larger than Q and one\n\t where Q is larger than I. The error is then calculated\n\t proportionally to these squashed constellations by the const\n\t K = sqrt(2)-1.\n\n\t The signal magnitude must be > 1 or K will incorrectly bias\n\t the error value.\n\n\t Ref: Z. Huang, Z. Yi, M. Zhang, K. Wang, \"8PSK demodulation for\n\t new generation DVB-S2\", IEEE Proc. Int. Conf. Communications,\n\t Circuits and Systems, Vol. 2, pp. 1447 - 1450, 2004.\n      */\n\n      float K = (sqrt(2.0) - 1);\n      if(fabsf(sample.real()) >= fabsf(sample.imag())) {\n\treturn ((sample.real()>0 ? 1.0 : -1.0) * sample.imag() -\n\t\t(sample.imag()>0 ? 1.0 : -1.0) * sample.real() * K);\n      }\n      else {\n\treturn ((sample.real()>0 ? 1.0 : -1.0) * sample.imag() * K -\n\t\t(sample.imag()>0 ? 1.0 : -1.0) * sample.real());\n      }\n    }\n\n    float\n    costas_loop_cc_impl::phase_detector_4(gr_complex sample) const\n    {\n      return ((sample.real()>0 ? 1.0 : -1.0) * sample.imag() -\n\t      (sample.imag()>0 ? 1.0 : -1.0) * sample.real());\n    }\n\n    float\n    costas_loop_cc_impl::phase_detector_2(gr_complex sample) const\n    {\n      return (sample.real()*sample.imag());\n    }\n\n    float\n    costas_loop_cc_impl::phase_detector_snr_8(gr_complex sample) const\n    {\n      float K = (sqrt(2.0) - 1);\n      float snr = abs(sample)*abs(sample) / d_noise;\n      if(fabsf(sample.real()) >= fabsf(sample.imag())) {\n\treturn ((blocks::tanhf_lut(snr*sample.real()) * sample.imag()) -\n          (blocks::tanhf_lut(snr*sample.imag()) * sample.real() * K));\n      }\n      else {\n\treturn ((blocks::tanhf_lut(snr*sample.real()) * sample.imag() * K) -\n          (blocks::tanhf_lut(snr*sample.imag()) * sample.real()));\n      }\n    }\n\n    float\n    costas_loop_cc_impl::phase_detector_snr_4(gr_complex sample) const\n    {\n      float snr = abs(sample)*abs(sample) / d_noise;\n      return ((blocks::tanhf_lut(snr*sample.real()) * sample.imag()) -\n              (blocks::tanhf_lut(snr*sample.imag()) * sample.real()));\n    }\n\n    float\n    costas_loop_cc_impl::phase_detector_snr_2(gr_complex sample) const\n    {\n      float snr = abs(sample)*abs(sample) / d_noise;\n      return blocks::tanhf_lut(snr*sample.real()) * sample.imag();\n    }\n\n    float\n    costas_loop_cc_impl::error() const\n    {\n      return d_error;\n    }\n\n    void\n    costas_loop_cc_impl::handle_set_noise(pmt::pmt_t msg)\n    {\n      if(pmt::is_real(msg)) {\n        d_noise = pmt::to_double(msg);\n        d_noise = powf(10.0f, d_noise/10.0f);\n      }\n    }\n\n    int\n    costas_loop_cc_impl::work(int noutput_items,\n\t\t\t      gr_vector_const_void_star &input_items,\n\t\t\t      gr_vector_void_star &output_items)\n    {\n      const gr_complex *iptr = (gr_complex *) input_items[0];\n      gr_complex *optr = (gr_complex *) output_items[0];\n      float *freq_optr  = output_items.size() >= 2 ? (float *) output_items[1] : NULL;\n      float *phase_optr = output_items.size() >= 3 ? (float *) output_items[2] : NULL;\n      float *error_optr = output_items.size() >= 4 ? (float *) output_items[3] : NULL;\n\n      gr_complex nco_out;\n\n      std::vector<tag_t> tags;\n      get_tags_in_range(tags, 0, nitems_read(0),\n                        nitems_read(0)+noutput_items,\n                        pmt::intern(\"phase_est\"));\n\n      for(int i = 0; i < noutput_items; i++) {\n        if(tags.size() > 0) {\n          if(tags[0].offset-nitems_read(0) == (size_t)i) {\n            d_phase = (float)pmt::to_double(tags[0].value);\n            tags.erase(tags.begin());\n          }\n        }\n\n        nco_out = gr_expj(-d_phase);\n        optr[i] = iptr[i] * nco_out;\n\n        d_error = (*this.*d_phase_detector)(optr[i]);\n        d_error = gr::branchless_clip(d_error, 1.0);\n\n        advance_loop(d_error);\n        phase_wrap();\n        frequency_limit();\n\n        if (freq_optr != NULL)\n          freq_optr[i] = d_freq;\n        if (phase_optr != NULL)\n          phase_optr[i] = d_phase;\n        if (error_optr != NULL)\n          error_optr[i] = d_error;\n      }\n\n      return noutput_items;\n    }\n\n    void\n    costas_loop_cc_impl::setup_rpc()\n    {\n#ifdef GR_CTRLPORT\n      // Getters\n      add_rpc_variable(\n          rpcbasic_sptr(new rpcbasic_register_get<costas_loop_cc, float>(\n\t      alias(), \"error\",\n\t      &costas_loop_cc::error,\n\t      pmt::mp(-2.0f), pmt::mp(2.0f), pmt::mp(0.0f),\n\t      \"\", \"Error signal of loop\", RPC_PRIVLVL_MIN,\n              DISPTIME | DISPOPTSTRIP)));\n\n      add_rpc_variable(\n          rpcbasic_sptr(new rpcbasic_register_get<control_loop, float>(\n\t      alias(), \"frequency\",\n\t      &control_loop::get_frequency,\n\t      pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f),\n\t      \"\", \"Frequency Est.\", RPC_PRIVLVL_MIN,\n              DISPTIME | DISPOPTSTRIP)));\n\n      add_rpc_variable(\n          rpcbasic_sptr(new rpcbasic_register_get<control_loop, float>(\n\t      alias(), \"phase\",\n\t      &control_loop::get_phase,\n\t      pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f),\n\t      \"\", \"Phase Est.\", RPC_PRIVLVL_MIN,\n              DISPTIME | DISPOPTSTRIP)));\n\n      add_rpc_variable(\n          rpcbasic_sptr(new rpcbasic_register_get<control_loop, float>(\n\t      alias(), \"loop_bw\",\n\t      &control_loop::get_loop_bandwidth,\n\t      pmt::mp(0.0f), pmt::mp(2.0f), pmt::mp(0.0f),\n\t      \"\", \"Loop bandwidth\", RPC_PRIVLVL_MIN,\n              DISPTIME | DISPOPTSTRIP)));\n\n      // Setters\n      add_rpc_variable(\n          rpcbasic_sptr(new rpcbasic_register_set<control_loop, float>(\n\t      alias(), \"loop_bw\",\n\t      &control_loop::set_loop_bandwidth,\n\t      pmt::mp(0.0f), pmt::mp(1.0f), pmt::mp(0.0f),\n\t      \"\", \"Loop bandwidth\",\n\t      RPC_PRIVLVL_MIN, DISPNULL)));\n#endif /* GR_CTRLPORT */\n    }\n\n  } /* namespace digital */\n} /* namespace gr */\n", "meta": {"hexsha": "edf0db33ef79aef5adbcc9cb2145dbf9de70f346", "size": 8670, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-digital/lib/costas_loop_cc_impl.cc", "max_stars_repo_name": "v1259397/cosmic-gnuradio", "max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z", "max_issues_repo_path": "gnuradio-3.7.13.4/gr-digital/lib/costas_loop_cc_impl.cc", "max_issues_repo_name": "v1259397/cosmic-gnuradio", "max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gnuradio-3.7.13.4/gr-digital/lib/costas_loop_cc_impl.cc", "max_forks_repo_name": "v1259397/cosmic-gnuradio", "max_forks_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4130434783, "max_line_length": 91, "alphanum_fraction": 0.6190311419, "num_tokens": 2460, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.41881985196330285}}
{"text": "#include <boost/assert.hpp>\n#include <boost/foreach.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n//#include <boost/math/special_functions/binomial.hpp>\n#include <cmath>\n#include <Eigen/Dense>\n#include <limits>\n#include <vector>\n\n#include <fstream>\n\n#include \"kalman_filter.hpp\"\n#include \"kalman_filter_cache.hpp\"\n#include \"model.hpp\"\n#include \"partition.hpp\"\n#include \"io.hpp\"\n\n//using boost::math::binomial_coefficient;\n\nnamespace biggles\n{\n\nnamespace model\n{\n\nnamespace detail\n{\n\n// log multivariate gamma function with p == 2\ninline float lgamma_2(float x)\n{\n    // see http://en.wikipedia.org/wiki/Multivariate_gamma_function\n    return 0.5f*logf(M_PI) + lgammaf(x) + lgammaf(x-0.5f);\n}\n\n// log of the inverse Wishart PDF.\ninline float log_inverse_wishart_pdf(const Eigen::Matrix2f& B, const Eigen::Matrix2f& Phi, int m)\n{\n    // see http://en.wikipedia.org/wiki/Inverse-Wishart_distribution\n\n    float log_det_B = logf(B.determinant());\n    float log_det_Phi = logf(Phi.determinant());\n    float trace_Phi_B_inv = (Phi * B.inverse()).trace();\n\n    return 0.5f*m*log_det_Phi - 0.5f*(m+2+1)*log_det_B - 0.5f*trace_Phi_B_inv - 0.5f*(2*m)*logf(2.f) - lgamma_2(0.5f*m);\n}\n\n}\n\n/// \\brief calculates p(partition | clutter rate)\n///\n/// This function seems to be uncontroversial\nfloat log_partition_given_clutter_rate_density(const partition& part_sample, const model::parameters& para_sample) {\n    const time_stamp part_first_ts = part_sample.first_time_stamp();\n    const time_stamp part_last_ts = part_sample.last_time_stamp();\n    const time_stamp part_duration = part_last_ts - part_first_ts;\n    /*\n    std::vector<size_t> clutter_counts(part_duration);\n    BOOST_FOREACH(const observation& obs, part_sample.clutter()) {\n        ++clutter_counts[t(obs) - part_first_ts];\n    }\n    */\n    float lambda_f = clutter_rate(para_sample);\n    /*\n    if (not std::isfinite(lambda_f)) {\n        std::stringstream sstr;\n        sstr << \"clutter rate is not finite: \" << lambda_f;\n        throw std::runtime_error(sstr.str()) ;\n    }\n    */\n    BOOST_ASSERT(std::isfinite(lambda_f));\n    BOOST_ASSERT(lambda_f >= 0);\n    float log_part_clutter = part_sample.clutter().size() * logf(lambda_f) - part_duration * lambda_f;\n    for (clutter_t::const_iterator it = part_sample.clutter().begin(); it not_eq part_sample.clutter().end(); ++it) {\n        log_part_clutter += -lgammaf(1.f + it->second.size());\n    }\n    return log_part_clutter;\n}\n\nfloat log_partition_given_survival_prob_density(const partition& part_sample, const model::parameters& para_sample) {\n    binomial_coefficient& binom_coeff = binomial_coefficient::get();\n    const time_stamp part_first_ts = part_sample.first_time_stamp();\n    const time_stamp part_last_ts = part_sample.last_time_stamp();\n    const time_stamp part_duration = part_last_ts - part_first_ts;\n    const int min_surv = 0; // number of guaranteed survivals\n    std::vector<size_t> survival_events(part_duration);\n    std::vector<size_t> death_events(part_duration);\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, part_sample.tracks()) {\n        BOOST_ASSERT(t_ptr->duration() > min_surv);\n        time_stamp track_first_ts = t_ptr->first_time_stamp();\n        time_stamp track_last_ts = t_ptr->last_time_stamp();\n        for (time_stamp ts = track_first_ts - part_first_ts + 1 + min_surv; ts < track_last_ts - part_first_ts; ++ts)\n            survival_events[ts]++;\n        if (track_last_ts < part_last_ts)\n            death_events[track_last_ts - part_first_ts]++;\n    }\n    float log_part_surv = 0.f;\n    float log_p_s = logf(survival_probability(para_sample));\n    float log_1m_p_s = logf(1.f - survival_probability(para_sample));\n    for ( time_stamp i = 0; i < part_duration; ++i) {\n        log_part_surv += logf(binom_coeff(survival_events[i] + death_events[i], survival_events[i])) +\n            survival_events[i] * log_p_s + death_events[i] * log_1m_p_s;\n    }\n    return log_part_surv;\n}\n\nfloat log_partition_given_observation_prob_density(const partition& part_sample, const model::parameters& para_sample) {\n    binomial_coefficient& binom_coeff = binomial_coefficient::get();\n    const time_stamp part_first_ts = part_sample.first_time_stamp();\n    const time_stamp part_last_ts = part_sample.last_time_stamp();\n    const time_stamp part_duration = part_last_ts - part_first_ts;\n    const size_t min_obs = 0; //number of guaranteed observations\n    std::vector<size_t> track_events(part_duration);\n    std::vector<size_t> observation_events(part_duration);\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, part_sample.tracks()) {\n        time_stamp track_first_ts = t_ptr->first_time_stamp();\n        time_stamp track_last_ts = t_ptr->last_time_stamp();\n        for (time_stamp ts = track_first_ts - part_first_ts; ts < track_last_ts - part_first_ts; ++ts)\n            track_events[ts]++;\n        BOOST_ASSERT(t_ptr->observations().size() >= min_obs);\n        observation_collection::const_iterator obs_iter = t_ptr->observations().begin();\n        for (size_t i = 0; i < min_obs; ++i) {\n            track_events[t(*obs_iter) - part_first_ts]--;\n            obs_iter++;\n        }\n        for (; obs_iter != t_ptr->observations().end(); ++obs_iter)\n            observation_events[t(*obs_iter) - part_first_ts]++;\n    }\n    float log_part_obs = 0.f;\n    float log_p_o = logf(observation_probability(para_sample));\n    float log_1m_p_o = logf(1.f - observation_probability(para_sample));\n    for (time_stamp i = 0; i < part_duration; ++i) {\n        log_part_obs += logf(binom_coeff(track_events[i], observation_events[i])) +\n            observation_events[i] * log_p_o + (track_events[i] - observation_events[i]) * log_1m_p_o;\n    }\n    return log_part_obs;\n}\n\nfloat log_partition_given_birth_rate_density(const partition& part_sample, const model::parameters& para_sample) {\n    const time_stamp part_first_ts = part_sample.first_time_stamp();\n    const time_stamp part_last_ts = part_sample.last_time_stamp();\n    const time_stamp part_duration = part_last_ts - part_first_ts;\n    const int min_surv = 0; // number of guaranteed survivals\n    std::vector<size_t> birth_events(part_duration);\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, part_sample.tracks()) {\n        BOOST_ASSERT(t_ptr->duration() > min_surv);\n        time_stamp track_first_ts = t_ptr->first_time_stamp();\n        birth_events[track_first_ts - part_first_ts]++;\n    }\n    float lambda_b = birth_rate(para_sample);\n    size_t n_total_born(part_sample.tracks().size());\n    float log_part_birth = n_total_born * logf(lambda_b) - (part_duration - min_surv) * lambda_b;\n    // TODO: the value for lgammaf may be stored and recalled rather than recalculated; could be faster.\n    for (time_stamp i = 0; i < part_duration; ++i)\n        log_part_birth += -lgammaf(1.f + birth_events[i]);\n    return log_part_birth;\n}\n\nfloat log_partition_given_parameters_density_orig(const partition& partition, const model::parameters& parameters)\n{\n    float log_pdf = 0.f;\n\n    off_t n_frames = partition.duration();\n\n    // ensemble statistics over all time stamps\n    off_t n_total_born(partition.tracks().size());\n    off_t n_total_false(partition.clutter().size());\n    off_t n_total_died(partition.tracks().size()); // everything that has a beginning has an end, Neo.\n    off_t n_total_survived(0);\n    off_t n_total_generated(0);\n\n    // calculate n_total_survived and n_total_generated. record birth times for tracks\n    std::vector<size_t> birth_counts(partition.last_time_stamp() - partition.first_time_stamp());\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, partition.tracks())\n    {\n        BOOST_ASSERT(t_ptr->duration() > 1);\n        // a track 'survives' for one fewer ticks than it's duration\n        n_total_survived += t_ptr->duration() - 1;\n\n\n        // the track's size is the number of observations within it\n        n_total_generated += t_ptr->size();\n\n        // record birth time\n        BOOST_ASSERT(t_ptr->first_time_stamp() >= partition.first_time_stamp());\n        BOOST_ASSERT(t_ptr->first_time_stamp() - partition.first_time_stamp() < static_cast<time_stamp>(birth_counts.size()));\n        ++birth_counts[t_ptr->first_time_stamp() - partition.first_time_stamp()];\n    }\n\n    // record clutter counts\n    std::vector<size_t> clutter_counts(partition.last_time_stamp() - partition.first_time_stamp());\n    for (clutter_t::const_iterator it = partition.clutter().begin(); it not_eq partition.clutter().end(); ++it) {\n        clutter_counts[it->first - partition.first_time_stamp()] = it->second.size();\n    }\n\n    // p_s term\n    float p_s = frame_to_frame_survival_probability(parameters);\n    BOOST_ASSERT(std::isfinite(p_s) and p_s >= 0);\n    log_pdf += n_total_survived * logf(p_s) + n_total_died * logf(1.f - p_s);\n\n    // p_d term\n    float p_d = generate_observation_probability(parameters);\n    BOOST_ASSERT(std::isfinite(p_d) and p_d >= 0);\n    log_pdf += n_total_generated * logf(p_d) + (n_total_survived + n_total_born - n_total_generated) * logf(1.f - p_d);\n\n    // start of lambda_b term\n    float lambda_b = mean_new_tracks_per_frame(parameters);\n    BOOST_ASSERT(std::isfinite(lambda_b) and lambda_b >= 0);\n    log_pdf += n_total_born * logf(lambda_b) - n_frames * lambda_b; // ... still to calculate log gamma terms\n\n    // start of lambda_f term\n    float lambda_f = mean_false_observations_per_frame(parameters);\n    if (not std::isfinite(lambda_f)) {\n        std::stringstream sstr;\n        sstr << \"clutter rate is not finite: \" << lambda_f;\n        throw std::runtime_error(sstr.str()) ; // TODO debug cleaning up\n    }\n    BOOST_ASSERT(std::isfinite(lambda_f));\n    BOOST_ASSERT(lambda_f >= 0);\n    log_pdf += n_total_false * logf(lambda_f) - n_frames * lambda_f; // ... still to calculate log gamma terms\n\n    // finish lambda_b and lambda_f terms\n    for(time_stamp ts = partition.first_time_stamp(); ts < partition.last_time_stamp(); ++ts)\n    {\n        // finish lambda_b term\n        log_pdf += -lgammaf(1.f + birth_counts[ts - partition.first_time_stamp()]);\n\n        // finish lambda_f term\n        log_pdf += -lgammaf(1.f + clutter_counts[ts - partition.first_time_stamp()]);\n    }\n\n    return log_pdf; // the rest is just a repeat of P(T|clutter_rate)\n\n}\n\nfloat log_partition_given_parameters_density(\n        const partition& partition_sample, const model::parameters& parameter_sample)\n{\n    return log_partition_given_parameters_density_orig(partition_sample, parameter_sample);\n}\n\nfloat log_clutter_given_parameters_density(const partition& part, const model::parameters& parameters) {\n    return -logf(part.volume())*part.clutter().size();\n}\n\nfloat log_track_given_parameters_density(const boost::shared_ptr<const track>& track_p, const model::parameters& parameters)\n{\n    return track_p->log_posterior(parameters);\n}\n\nfloat log_parameters_prior_density(const model::parameters& parameters)\n{\n    // finite regions of support:\n    if(mean_new_tracks_per_frame(parameters) <= 0.f)\n        return -std::numeric_limits<float>::max();\n    if(mean_false_observations_per_frame(parameters) <= 0.f)\n        return -std::numeric_limits<float>::max();\n    if(frame_to_frame_survival_probability(parameters) < 0.f)\n        return -std::numeric_limits<float>::max();\n    if(frame_to_frame_survival_probability(parameters) > 1.f)\n        return -std::numeric_limits<float>::max();\n    if(generate_observation_probability(parameters) < 0.f)\n        return -std::numeric_limits<float>::max();\n    if(generate_observation_probability(parameters) > 1.f)\n        return -std::numeric_limits<float>::max();\n\n\n    /*\n    if (mean_false_observations_per_frame(parameters) != 0.1f) { // FIXME PRIOR calculation\n        return -std::numeric_limits<float>::max();\n    }\n    if (mean_new_tracks_per_frame(parameters) != .5f) { // FIXME PRIOR calculation\n        return -std::numeric_limits<float>::max();\n    }\n    if (generate_observation_probability(parameters) != .9f) { // FIXME PRIOR calculation\n        return -std::numeric_limits<float>::max();\n    }\n    if (frame_to_frame_survival_probability(parameters) != .9f) { // FIXME PRIOR calculation\n        return -std::numeric_limits<float>::max();\n    }\n    */\n    // prior on R:\n    // FIXME PRIOR calculation\n    /*\n    if ( observation_error_covariance(parameters) == Eigen::Matrix2f::Identity()* 0.09f ) {\n        return 0.f;\n    } else {\n        return -std::numeric_limits<float>::max();\n    }\n    */\n    return detail::log_inverse_wishart_pdf(observation_error_covariance(parameters), 2.f * Eigen::Matrix2f::Identity(), 5);\n}\n\nfloat log_likelihood(const partition& part_sample, const model::parameters& para_sample) {\n    float log_pdf(0.f);\n\n    // track PDFs\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, part_sample.tracks())\n    {\n        log_pdf += log_track_given_parameters_density(t_ptr, para_sample);\n    }\n\n    // clutter PDF\n    log_pdf += log_clutter_given_parameters_density(part_sample, para_sample);\n    return log_pdf;\n}\n\nfloat log_tracks_given_parameters_density(const partition& part, const model::parameters& parameters) {\n    // track PDFs\n    float log_pdf(0.f);\n    BOOST_FOREACH(const boost::shared_ptr<const track>& t_ptr, part.tracks())\n    {\n        float track_log_pdf = log_track_given_parameters_density(t_ptr, parameters);\n        if (not std::isfinite(track_log_pdf)) {\n            std::cerr << \"track duration \" << t_ptr->duration() << std::endl;\n            std::cerr << \"track size \" << t_ptr->size() << std::endl;\n        }\n        log_pdf += track_log_pdf;\n    }\n    return log_pdf;\n}\n\nvoid dump_part_para(const partition& part, const model::parameters& para) {\n    size_t ctr = 0;\n    std::string fname = boost::str(boost::format(\"no_finite_log_pdf.%04d.json\") % ctr);\n    while (boost::filesystem::exists(fname)) {\n        ctr++;\n        if (ctr > 9999) {\n            std::cerr << \"nothing dumped :(\" << std::endl;\n            return;\n        }\n        fname = boost::str(boost::format(\"no_finite_log_pdf.%04d.json\") % ctr);\n    }\n    std::ofstream fh(fname.c_str());\n    fh << \"{ \\\"parameters\\\": \";\n    io::write_model_parameters_to_json_stream(fh, para);\n    fh << \", \\\"partition\\\": \" << std::endl;\n    io::write_partition_to_json_stream(fh, part);\n    fh << \"}\" << std::endl;\n}\n\nfloat log_partition_given_parameters_and_data_density(const partition& part, const model::parameters& parameters)\n{\n    float log_pdf(0.f);\n    float temp(0.f);\n\n    // clutter PDF\n    temp = log_clutter_given_parameters_density(part, parameters);\n    if (not std::isfinite(temp)) {\n        std::cerr << \" *** clutter log density not finite\" << std::endl;\n        std::cerr << \"     \" << part.volume() << std::endl;\n        dump_part_para(part, parameters);\n    }\n    log_pdf += temp;\n\n    temp = log_tracks_given_parameters_density(part, parameters);\n    if (not std::isfinite(temp)) {\n        std::cerr << \" *** track log density not finite\" << std::endl;\n        std::cerr << temp << std::endl;\n        std::cerr << model::observation_error_covariance(parameters) << std::endl;\n        dump_part_para(part, parameters);\n    }\n    log_pdf += temp;\n\n\n    //log_pdf = 0.f; // FIXME PRIOR test get rid of this line again\n\n    // data-independent track PDF\n    temp = log_partition_given_parameters_density(part, parameters);\n    if (not std::isfinite(temp)) {\n        std::cerr << \" *** partition log density not finite\" << std::endl;\n        dump_part_para(part, parameters);\n    }\n    log_pdf += temp;\n\n    // prior\n    // the prior is only need to record the log pdf and not for the sampling itself.\n    // log_pdf += log_parameters_prior_density(parameters);\n\n    return log_pdf;\n}\n\n}\n\n}\n", "meta": {"hexsha": "47395839860b65019527439c9baf1ab754518748", "size": 15703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "biggles/model.cpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "biggles/model.cpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "biggles/model.cpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5762273902, "max_line_length": 126, "alphanum_fraction": 0.6887219003, "num_tokens": 3844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8376199673867852, "lm_q2_score": 0.5, "lm_q1q2_score": 0.4188099836933926}}
{"text": "// Copyright (c) 2015 Zachary Kann\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n// ---\n// Author: Zachary Kann\n\n#include <fstream>\n#include <cmath>\r\n#include <complex>\n#include <armadillo>\n#include \"boost/program_options.hpp\"\r\n#include \"z_constants.hpp\"\n#include \"z_conversions.hpp\"\n#include \"z_string.hpp\"\r\n\nnamespace po = boost::program_options;\n\r\nint main (int argc, char *argv[]) {\n\n  enum Chromophore {kOH, kOD};\n\n  std::string V_filename;\n  po::options_description desc(\"Options\");\n  desc.add_options()\n    (\"help,h\",  \"Print help messages\")\n    (\"V_file,c\", po::value<std::string>(&V_filename),\n     \"Choice of chromophore (OH or OD)\")\n    (\"chromophore,c\", po::value<std::string>(),\n     \"Choice of chromophore (OH or OD)\");\n\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, desc), vm);\n  po::notify(vm);\n\n  if (vm.count(\"help\")) {\n    std::cout << desc << \"\\n\";\n    exit(EXIT_SUCCESS);\n  }\n\n  Chromophore chromophore;\n  const std::string& vm_chromophore =\n      vm[\"chromophore\"].as<std::string>();\n  if (vm_chromophore == \"OH\")\n    chromophore = kOH;\n  else if (vm_chromophore == \"OD\")\n    chromophore = kOD;\n  else\n    assert(false && \"Unrecognized chromophore option\");\n\n  double red_mass = (chromophore == kOH) ? MASS_H*MASS_OD : MASS_D*MASS_OH;\r\n  red_mass *= AMU_TO_KG/MASS_HOD;\r\n  double delta_x = 0.02e-10;\r\n  int points = 56;\r\n\n  arma::mat T = arma::zeros<arma::mat>(points, points);\n  arma::mat V = arma::zeros<arma::mat>(points, points);\n  arma::mat H = arma::zeros<arma::mat>(points, points);\r\n\r\n  std::ifstream V_file(V_filename.c_str());\r\n\r\n  for (int i=0; i<points; i++)\n    V_file >> V(i,i);\n\r\n  for (int i_col = 0; i_col < points; ++i_col) {\r\n    for (int i_row = 0; i_row < points; ++i_row) {\r\n      T(i_row, i_col) =\n          H_BAR*H_BAR/2.0/red_mass/delta_x/delta_x/C_SPEED_CGS/PLANCK;\r\n      V(i_row, i_col) *= 220000;\r\n      if ((i_col-i_row)%2)\n        T(i_row, i_col) *= -1.0;\r\n      if (i_row == i_col)\n        T(i_row, i_col) *= M_PI*M_PI/3.0;\r\n      else\n        T(i_row, i_col) *= 2.0/(i_col-i_row)/(i_col-i_row);\r\n    }\r\n  }\n  H = T+V;\n  arma::rowvec eigenvalues = arma::eig_sym(H);\r\n\r\n  std::ofstream output_file(\"freqs.dat\");\r\n  output_file << eigenvalues(1) - eigenvalues(0);\r\n}\r\n", "meta": {"hexsha": "5662b1b86324f349c6e1b3ab82ce7a9416cd966a", "size": 3275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "thekannman/z_dvr", "max_stars_repo_head_hexsha": "05843c3e0d091589bcb0050cf428de5c910bb5e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "thekannman/z_dvr", "max_issues_repo_head_hexsha": "05843c3e0d091589bcb0050cf428de5c910bb5e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "thekannman/z_dvr", "max_forks_repo_head_hexsha": "05843c3e0d091589bcb0050cf428de5c910bb5e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.75, "max_line_length": 81, "alphanum_fraction": 0.6687022901, "num_tokens": 921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624890918021, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.41880146805801577}}
{"text": "// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef NETKET_VARIATIONALMONTECARLO_HPP\n#define NETKET_VARIATIONALMONTECARLO_HPP\n\n#include <complex>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <Eigen/Dense>\n#include <Eigen/IterativeLinearSolvers>\n#include <nonstd/optional.hpp>\n\n#include \"Machine/machine.hpp\"\n#include \"Operator/abstract_operator.hpp\"\n#include \"Optimizer/optimizer.hpp\"\n#include \"Output/json_output_writer.hpp\"\n#include \"Sampler/abstract_sampler.hpp\"\n#include \"Stats/stats.hpp\"\n#include \"Utils/parallel_utils.hpp\"\n#include \"Utils/random_utils.hpp\"\n#include \"common_types.hpp\"\n#include \"matrix_replacement.hpp\"\n\nnamespace netket {\n\n// Variational Monte Carlo schemes to learn the ground state\n// Available methods:\n// 1) Stochastic reconfiguration optimizer\n//   both direct and sparse version\n// 2) Gradient Descent optimizer\nclass VariationalMonteCarlo {\n  using GsType = Complex;\n  using VectorT = Eigen::Matrix<Complex, Eigen::Dynamic, 1>;\n  using MatrixT = Eigen::Matrix<Complex, Eigen::Dynamic, Eigen::Dynamic>;\n\n  const AbstractOperator &ham_;\n  AbstractSampler &sampler_;\n  AbstractMachine &psi_;\n\n  std::vector<std::vector<int>> connectors_;\n  std::vector<std::vector<double>> newconfs_;\n  std::vector<Complex> mel_;\n\n  Eigen::VectorXcd elocs_;\n  MatrixT Ok_;\n  VectorT Okmean_;\n\n  Eigen::MatrixXd vsamp_;\n\n  Eigen::VectorXcd grad_;\n  Eigen::VectorXcd gradprev_;\n\n  double sr_diag_shift_;\n  bool sr_rescale_shift_;\n  bool use_iterative_;\n\n  int totalnodes_;\n  int mynode_;\n\n  AbstractOptimizer &opt_;\n\n  std::vector<AbstractOperator *> obs_;\n  std::vector<std::string> obsnames_;\n  ObsManager obsmanager_;\n\n  bool dosr_;\n\n  bool use_cholesky_;\n\n  int nsamples_;\n  int nsamples_node_;\n  int ninitsamples_;\n  int ndiscardedsamples_;\n\n  Complex elocmean_;\n  double elocvar_;\n  int npar_;\n\n public:\n  class Iterator {\n   public:\n    // typedefs required for iterators\n    using iterator_category = std::input_iterator_tag;\n    using difference_type = Index;\n    using value_type = Index;\n    using pointer_type = Index *;\n    using reference_type = Index &;\n\n   private:\n    VariationalMonteCarlo &vmc_;\n    Index step_size_;\n    nonstd::optional<Index> n_iter_;\n\n    Index cur_iter_;\n\n   public:\n    Iterator(VariationalMonteCarlo &vmc, Index step_size,\n             nonstd::optional<Index> n_iter)\n        : vmc_(vmc),\n          step_size_(step_size),\n          n_iter_(std::move(n_iter)),\n          cur_iter_(0) {}\n\n    Index operator*() const { return cur_iter_; }\n\n    Iterator &operator++() {\n      vmc_.Advance(step_size_);\n      cur_iter_ += step_size_;\n      return *this;\n    }\n\n    // TODO(C++17): Replace with comparison to special Sentinel type, since\n    // C++17 allows end() to return a different type from begin().\n    bool operator!=(const Iterator &) {\n      return !n_iter_.has_value() || cur_iter_ < n_iter_.value();\n    }\n    // pybind11::make_iterator requires operator==\n    bool operator==(const Iterator &other) { return !(*this != other); }\n\n    Iterator begin() const { return *this; }\n    Iterator end() const { return *this; }\n  };\n\n  VariationalMonteCarlo(const AbstractOperator &hamiltonian,\n                        AbstractSampler &sampler, AbstractOptimizer &optimizer,\n                        int nsamples, int discarded_samples = -1,\n                        int discarded_samples_on_init = 0,\n                        const std::string &method = \"Sr\",\n                        double diag_shift = 0.01, bool rescale_shift = false,\n                        bool use_iterative = false, bool use_cholesky = true)\n      : ham_(hamiltonian),\n        sampler_(sampler),\n        psi_(sampler.GetMachine()),\n        opt_(optimizer),\n        elocvar_(0.) {\n    Init(nsamples, discarded_samples, discarded_samples_on_init, method,\n         diag_shift, rescale_shift, use_iterative, use_cholesky);\n  }\n\n  void Init(int nsamples, int discarded_samples, int discarded_samples_on_init,\n            const std::string &method, double diagshift, bool rescale_shift,\n            bool use_iterative, bool use_cholesky) {\n    npar_ = psi_.Npar();\n\n    opt_.Init(psi_.GetParameters());\n\n    grad_.resize(npar_);\n    Okmean_.resize(npar_);\n\n    setSrParameters();\n\n    MPI_Comm_size(MPI_COMM_WORLD, &totalnodes_);\n    MPI_Comm_rank(MPI_COMM_WORLD, &mynode_);\n\n    nsamples_ = nsamples;\n\n    nsamples_node_ = int(std::ceil(double(nsamples_) / double(totalnodes_)));\n\n    ninitsamples_ = discarded_samples_on_init;\n\n    if (discarded_samples == -1) {\n      ndiscardedsamples_ = 0.1 * nsamples_node_;\n    } else {\n      ndiscardedsamples_ = discarded_samples;\n    }\n\n    if (method == \"Gd\") {\n      dosr_ = false;\n    } else {\n      setSrParameters(diagshift, rescale_shift, use_iterative, use_cholesky);\n    }\n\n    if (dosr_) {\n      InfoMessage() << \"Using the Stochastic reconfiguration method\"\n                    << std::endl;\n\n      if (use_iterative_) {\n        InfoMessage() << \"With iterative solver\" << std::endl;\n      } else {\n        if (use_cholesky_) {\n          InfoMessage() << \"Using Cholesky decomposition\" << std::endl;\n        }\n      }\n    } else {\n      InfoMessage() << \"Using a gradient-descent based method\" << std::endl;\n    }\n\n    InfoMessage() << \"Variational Monte Carlo running on \" << totalnodes_\n                  << \" processes\" << std::endl;\n\n    MPI_Barrier(MPI_COMM_WORLD);\n  }\n\n  void AddObservable(AbstractOperator &ob, const std::string &obname) {\n    obs_.push_back(&ob);\n    obsnames_.push_back(obname);\n  }\n\n  void InitSweeps() {\n    sampler_.Reset();\n\n    for (int i = 0; i < ninitsamples_; i++) {\n      sampler_.Sweep();\n    }\n  }\n\n  void Sample() {\n    sampler_.Reset();\n\n    for (int i = 0; i < ndiscardedsamples_; i++) {\n      sampler_.Sweep();\n    }\n\n    vsamp_.resize(nsamples_node_, psi_.Nvisible());\n\n    for (int i = 0; i < nsamples_node_; i++) {\n      sampler_.Sweep();\n      vsamp_.row(i) = sampler_.Visible();\n    }\n  }\n\n  /**\n   * Computes the expectation values of observables from the currently stored\n   * samples.\n   */\n  void ComputeObservables() {\n    const Index nsamp = vsamp_.rows();\n    for (const auto &obname : obsnames_) {\n      obsmanager_.Reset(obname);\n    }\n    for (Index i_samp = 0; i_samp < nsamp; ++i_samp) {\n      for (std::size_t i_obs = 0; i_obs < obs_.size(); ++i_obs) {\n        const auto &op = obs_[i_obs];\n        const auto &name = obsnames_[i_obs];\n        obsmanager_.Push(name, ObsLocValue(*op, vsamp_.row(i_samp)).real());\n      }\n    }\n  }\n\n  void Gradient() {\n    obsmanager_.Reset(\"Energy\");\n    obsmanager_.Reset(\"EnergyVariance\");\n\n    const int nsamp = vsamp_.rows();\n    elocs_.resize(nsamp);\n    Ok_.resize(nsamp, psi_.Npar());\n\n    for (int i = 0; i < nsamp; i++) {\n      elocs_(i) = ObsLocValue(ham_, vsamp_.row(i));\n      Ok_.row(i) = psi_.DerLog(vsamp_.row(i));\n      obsmanager_.Push(\"Energy\", elocs_(i).real());\n    }\n\n    elocmean_ = elocs_.mean();\n    SumOnNodes(elocmean_);\n    elocmean_ /= double(totalnodes_);\n\n    Okmean_ = Ok_.colwise().mean();\n    SumOnNodes(Okmean_);\n    Okmean_ /= double(totalnodes_);\n\n    Ok_ = Ok_.rowwise() - Okmean_.transpose();\n\n    elocs_ -= elocmean_ * Eigen::VectorXd::Ones(nsamp);\n\n    for (int i = 0; i < nsamp; i++) {\n      obsmanager_.Push(\"EnergyVariance\", std::norm(elocs_(i)));\n    }\n\n    grad_ = 2. * (Ok_.adjoint() * elocs_);\n\n    // Summing the gradient over the nodes\n    SumOnNodes(grad_);\n    grad_ /= double(totalnodes_ * nsamp);\n  }\n\n  /**\n   * Computes the value of the local estimator of the operator `ob` in\n   * configuration `v` which is defined by O_loc(v) = ⟨v|ob|Ψ⟩ / ⟨v|Ψ⟩.\n   *\n   * @param ob Operator representing the observable.\n   * @param v Many-body configuration\n   * @return The value of the local observable O_loc(v).\n   */\n  Complex ObsLocValue(const AbstractOperator &ob, const Eigen::VectorXd &v) {\n    ob.FindConn(v, mel_, connectors_, newconfs_);\n\n    assert(connectors_.size() == mel_.size());\n\n    auto logvaldiffs = (psi_.LogValDiff(v, connectors_, newconfs_));\n\n    assert(mel_.size() == std::size_t(logvaldiffs.size()));\n\n    Complex obval = 0;\n\n    for (int i = 0; i < logvaldiffs.size(); i++) {\n      obval += mel_[i] * std::exp(logvaldiffs(i));\n    }\n\n    return obval;\n  }\n\n  double ElocMean() { return elocmean_.real(); }\n\n  double Elocvar() { return elocvar_; }\n\n  void Advance(Index steps = 1) {\n    assert(steps > 0);\n    for (Index i = 0; i < steps; ++i) {\n      Sample();\n      Gradient();\n      UpdateParameters();\n    }\n  }\n\n  Iterator Iterate(const nonstd::optional<Index> &n_iter = nonstd::nullopt,\n                   Index step_size = 1) {\n    assert(!n_iter.has_value() || n_iter.value() > 0);\n    assert(step_size > 0);\n\n    opt_.Reset();\n    InitSweeps();\n\n    Advance(step_size);\n    return Iterator(*this, step_size, n_iter);\n  }\n\n  void Run(const std::string &output_prefix,\n           nonstd::optional<Index> n_iter = nonstd::nullopt,\n           Index step_size = 1, Index save_params_every = 50) {\n    assert(n_iter > 0);\n    assert(step_size > 0);\n    assert(save_params_every > 0);\n\n    nonstd::optional<JsonOutputWriter> writer;\n    if (mynode_ == 0) {\n      writer.emplace(output_prefix + \".log\", output_prefix + \".wf\",\n                     save_params_every);\n    }\n\n    for (const auto step : Iterate(n_iter, step_size)) {\n      ComputeObservables();\n\n      // Note: This has to be called in all MPI processes, because converting\n      // the ObsManager to JSON performs a MPI reduction.\n      auto obs_data = json(obsmanager_);\n      obs_data[\"Acceptance\"] = sampler_.Acceptance();\n\n      // writer.has_value() iff the MPI rank is 0, so the output is only\n      // written once\n      if (writer.has_value()) {\n        writer->WriteLog(step, obs_data);\n        writer->WriteState(step, psi_);\n      }\n      MPI_Barrier(MPI_COMM_WORLD);\n    }\n  }\n\n  void UpdateParameters() {\n    auto pars = psi_.GetParameters();\n\n    if (dosr_) {\n      const int nsamp = vsamp_.rows();\n\n      Eigen::VectorXcd b = Ok_.adjoint() * elocs_;\n      SumOnNodes(b);\n      b /= double(nsamp * totalnodes_);\n\n      if (!use_iterative_) {\n        // Explicit construction of the S matrix\n        Eigen::MatrixXcd S = Ok_.adjoint() * Ok_;\n        SumOnNodes(S);\n        S /= double(nsamp * totalnodes_);\n\n        // Adding diagonal shift\n        S += Eigen::MatrixXd::Identity(pars.size(), pars.size()) *\n             sr_diag_shift_;\n\n        Eigen::VectorXcd deltaP;\n        if (use_cholesky_ == false) {\n          Eigen::FullPivHouseholderQR<Eigen::MatrixXcd> qr(S.rows(), S.cols());\n          qr.setThreshold(1.0e-6);\n          qr.compute(S);\n          deltaP = qr.solve(b);\n        } else {\n          Eigen::LLT<Eigen::MatrixXcd> llt(S.rows());\n          llt.compute(S);\n          deltaP = llt.solve(b);\n        }\n        // Eigen::VectorXcd deltaP=S.jacobiSvd(ComputeThinU |\n        // ComputeThinV).solve(b);\n\n        assert(deltaP.size() == grad_.size());\n        grad_ = deltaP;\n\n        if (sr_rescale_shift_) {\n          Complex nor = (deltaP.dot(S * deltaP));\n          grad_ /= std::sqrt(nor.real());\n        }\n\n      } else {\n        Eigen::ConjugateGradient<MatrixReplacement, Eigen::Lower | Eigen::Upper,\n                                 Eigen::IdentityPreconditioner>\n            it_solver;\n        // Eigen::GMRES<MatrixReplacement, Eigen::IdentityPreconditioner>\n        // it_solver;\n        it_solver.setTolerance(1.0e-3);\n        MatrixReplacement S;\n        S.attachMatrix(Ok_);\n        S.setShift(sr_diag_shift_);\n        S.setScale(1. / double(nsamp * totalnodes_));\n\n        it_solver.compute(S);\n        auto deltaP = it_solver.solve(b);\n\n        grad_ = deltaP;\n        if (sr_rescale_shift_) {\n          auto nor = deltaP.dot(S * deltaP);\n          grad_ /= std::sqrt(nor.real());\n        }\n\n        // if(mynode_==0){\n        //   std::cerr<<it_solver.iterations()<<\"\n        //   \"<<it_solver.error()<<std::endl;\n        // }\n        MPI_Barrier(MPI_COMM_WORLD);\n      }\n    }\n\n    opt_.Update(grad_, pars);\n\n    SendToAll(pars);\n\n    psi_.SetParameters(pars);\n    MPI_Barrier(MPI_COMM_WORLD);\n  }\n\n  void setSrParameters(double diagshift = 0.01, bool rescale_shift = false,\n                       bool use_iterative = false, bool use_cholesky = true) {\n    sr_diag_shift_ = diagshift;\n    sr_rescale_shift_ = rescale_shift;\n    use_iterative_ = use_iterative;\n    dosr_ = true;\n    use_cholesky_ = use_cholesky;\n  }\n\n  AbstractMachine &GetMachine() { return psi_; }\n  const ObsManager &GetObsManager() const { return obsmanager_; }\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "9734704339c3ee202e6dcd3c30c4ead8ec726452", "size": 13152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/GroundState/variational_montecarlo.hpp", "max_stars_repo_name": "flatironinstitute/netket", "max_stars_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T19:00:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T01:03:15.000Z", "max_issues_repo_path": "NetKet/GroundState/variational_montecarlo.hpp", "max_issues_repo_name": "flatironinstitute/netket", "max_issues_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetKet/GroundState/variational_montecarlo.hpp", "max_forks_repo_name": "flatironinstitute/netket", "max_forks_repo_head_hexsha": "888a4b56b6242d62b45d32eda43e10066c65fdf9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-23T01:04:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T01:04:00.000Z", "avg_line_length": 27.9829787234, "max_line_length": 80, "alphanum_fraction": 0.6288017032, "num_tokens": 3445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4188014572074346}}
{"text": "/*                                                                                                                  \n *                                                                                                                   * Note: This license has also been called the \"New BSD License\" \n * or \"Modified BSD License\".\n * \n * Copyright (c) 2021 Electronics and Telecommunications Research \n * Institute All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * 1. Redistributions of source code must retain the above copyright notice, \n *    this list of conditions and the following disclaimer.\n * \n * 2. Redistributions in binary form must reproduce the above copyright notice, \n *    this list of conditions and the following disclaimer in the documentation \n *    and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors \n *    may be used to endorse or promote products derived from this software \n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT \n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS \n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, \n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; \n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT \n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN \n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n * POSSIBILITY OF SUCH DAMAGE.\n*/\n \n/**\n * CityGeodeticCalculator.cpp\n *\n * $Revision: 625 $\n * $LastChangedDate: 2019-07-19 15:18:25 +0900 (Fri, 19 Jul 2019) $\n */\n\n#include <boost/math/constants/constants.hpp>\n#include <string>\n#include <vector>\n#include <cmath>\n#include \"City.h\"\n#include \"CityGeodeticCalculator.h\"\n#include \"CityUtils.h\"\n\nnamespace dtsim {\n\nconst double CityGeodeticCalculator::WGS84_a = 6378137;\nconst double CityGeodeticCalculator::WGS84_b = 6356752.314245;\nconst double CityGeodeticCalculator::WGS84_f = 1/298.257223563;\nconst double CityGeodeticCalculator::RADIUS_EARTH = 6371000.0;\n\nCityGeodeticCalculator::CityGeodeticCalculator()\n{\n\tif (City::instance()->containProperty(\"geodetic.distance.formula\")) {\n\t\tstd::string formulaStr = City::instance()->getStringProperty(\"geodetic.distance.formula\");\n\n\t\tif ((formulaStr.compare(\"haversine\") == 0) || (formulaStr.compare(\"Haversine\") == 0))\n\t\t\tformula = GEODETIC_HAVERSINE;\n\t\telse if ((formulaStr.compare(\"vincenty\") == 0) || (formulaStr.compare(\"Vincenty\") == 0))\n\t\t\tformula = GEODETIC_VINCENTY;\n\t\telse\n\t\t\tformula = GEODETIC_HAVERSINE;\n\t} else {\n\t\tformula = GEODETIC_HAVERSINE;\n\t}\n}\n\nCityGeodeticCalculator::~CityGeodeticCalculator()\n{\n\t_instance = 0;\n}\n\nCityGeodeticCalculator* CityGeodeticCalculator::_instance = 0;\n\nCityGeodeticCalculator* CityGeodeticCalculator::instance()\n{\n\tif (_instance == 0)\n\t\t_instance = new CityGeodeticCalculator();\n\n\treturn _instance;\n}\n\nvoid CityGeodeticCalculator::haversine_getDestinationPoint(double startLon, double startLat,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t   double distance, double azimuth,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t   double& destLon, double& destLat)\n{\n\tdouble delta = distance / RADIUS_EARTH;\n\tdouble theta = degreesToRadians(azimuth);\n\n\tdouble lambda1 = degreesToRadians(startLon);\n\tdouble phi1 = degreesToRadians(startLat);\n\n\tdouble sinPhi2 = (std::sin(phi1) * std::cos(delta)) +\n\t\t\t\t\t (std::cos(phi1) * std::sin(delta) * std::cos(theta));\n\tdouble phi2 = std::asin(sinPhi2);\n\n\tdouble x = std::cos(delta) - (std::sin(phi1) * sinPhi2);\n\tdouble y = std::sin(theta) * std::sin(delta) * std::cos(phi1);\n\tdouble lambda2 = lambda1 + std::atan2(y, x);\n\n\tdestLon = radiansToDegrees(lambda2);\n\tdestLat = radiansToDegrees(phi2);\n}\n\nvoid CityGeodeticCalculator::vincenty_getDestinationPoint(double startLon, double startLat,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  double distance, double azimuth,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  double& destLon, double& destLat)\n{\n\tdouble lambda1 = degreesToRadians(startLon);\n\tdouble phi1 = degreesToRadians(startLat);\n\tdouble alpha1 = degreesToRadians(azimuth);\n\tdouble s = distance;\n\n\tdouble sinAlpha1 = std::sin(alpha1);\n\tdouble cosAlpha1 = std::cos(alpha1);\n\n\tdouble tanU1 = (1 - WGS84_f) * std::tan(phi1);\n\tdouble cosU1 = 1 / std::sqrt((1 + tanU1*tanU1));\n\tdouble sinU1 = tanU1 * cosU1;\n\n\tdouble sigma1 = std::atan2(tanU1, cosAlpha1);\n\tdouble sinAlpha = cosU1 * sinAlpha1;\n\tdouble cosSqAlpha = 1 - sinAlpha*sinAlpha;\n\tdouble uSq = cosSqAlpha * (WGS84_a*WGS84_a - WGS84_b*WGS84_b) / (WGS84_b*WGS84_b);\n\tdouble A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));\n\tdouble B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));\n\n\tdouble cos2SigmaM, sinSigma, cosSigma, deltaSigma;\n\n\tdouble sigma = s / (WGS84_b*A);\n\tdouble sigmaP;\n\tint iterations = 0;\n\tdo {\n\t\tcos2SigmaM = std::cos(2*sigma1 + sigma);\n\t\tsinSigma = std::sin(sigma);\n\t\tcosSigma = std::cos(sigma);\n\t\tdeltaSigma = B * sinSigma * (cos2SigmaM + B/4*(cosSigma*(-1 + 2*cos2SigmaM*cos2SigmaM)-\n\t\t\t\t\t B / 6*cos2SigmaM*(-3 + 4*sinSigma*sinSigma)*(-3 + 4*cos2SigmaM*cos2SigmaM)));\n\t\tsigmaP = sigma;\n\t\tsigma = s / (WGS84_b*A) + deltaSigma;\n\t} while ((std::abs(sigma - sigmaP) > 1e-12) && (++iterations < 1000));\n\n\tdouble chi = sinU1*sinSigma - cosU1*cosSigma*cosAlpha1;\n\tdouble phi2 = std::atan2(sinU1*cosSigma + cosU1*sinSigma*cosAlpha1, (1-WGS84_f)*std::sqrt(sinAlpha*sinAlpha + chi*chi));\n\tdouble lambda = std::atan2(sinSigma*sinAlpha1, cosU1*cosSigma - sinU1*sinSigma*cosAlpha1);\n\tdouble C = WGS84_f/16*cosSqAlpha*(4 + WGS84_f*(4 - 3*cosSqAlpha));\n\tdouble L = lambda - (1-C) * WGS84_f * sinAlpha * (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));\n\tdouble lambda2 = lambda1 + L;\n\n\tdouble alpha2 = std::atan2(sinAlpha, -chi);\n\n\tdestLon = radiansToDegrees(lambda2);\n\tdestLat = radiansToDegrees(phi2);\n}\n\nvoid CityGeodeticCalculator::getDestinationPoint(double startLon, double startLat,\n\t\t\t\t\t\t\t\t\t\t\t\t double distance, double azimuth,\n\t\t\t\t\t\t\t\t\t\t\t\t double& destLon, double& destLat)\n{\n\tif (formula == GEODETIC_HAVERSINE)\n\t\thaversine_getDestinationPoint(startLon, startLat, distance, azimuth, destLon, destLat);\n\telse\n\t\tvincenty_getDestinationPoint(startLon, startLat, distance, azimuth, destLon, destLat);\n}\n\nvoid CityGeodeticCalculator::getDestinationPoint(CityCoordinate& startPoint,\n\t\t\t\t\t\t\t\t\t\t\t\t double distance, double azimuth,\n\t\t\t\t\t\t\t\t\t\t\t\t CityCoordinate& destPoint)\n{\n\tgetDestinationPoint(startPoint.x, startPoint.y, distance, azimuth, destPoint.x, destPoint.y);\n}\n\nvoid CityGeodeticCalculator::getMidPoint(double startLon, double startLat,\n\t\t\t\t\t\t\t\t\t\t double destLon, double destLat,\n\t\t\t\t\t\t\t\t\t\t double& midLon, double& midLat)\n{\n\tdouble lambda1 = degreesToRadians(startLon);\n\tdouble phi1 = degreesToRadians(startLat);\n\tdouble phi2 = degreesToRadians(destLat);\n\n\tdouble deltaLambda = degreesToRadians(destLon - startLon);\n\n\tstd::vector<double> A;\n\tstd::vector<double> B;\n\tstd::vector<double> C;\n\tdouble x, y, z;\n\n\tx = std::cos(phi1);\n\ty = 0;\n\tz = std::sin(phi1);\n\tA.push_back(x);\n\tA.push_back(y);\n\tA.push_back(z);\n\n\tx = std::cos(phi2) * std::cos(deltaLambda);\n\ty = std::cos(phi2) * std::sin(deltaLambda);\n\tz = std::sin(phi2);\n\tB.push_back(x);\n\tB.push_back(y);\n\tB.push_back(z);\n\n\tx = A[0] + B[0];\n\ty = A[1] + B[1];\n\tz = A[2] + B[2];\n\tC.push_back(x);\n\tC.push_back(y);\n\tC.push_back(z);\n\n\tdouble phiM = std::atan2(C[2], std::sqrt((C[0]*C[0]) + (C[1]*C[1])));\n\tdouble lambdaM = lambda1 + std::atan2(C[1], C[0]);\n\n\tmidLon = radiansToDegrees(lambdaM);\n\tmidLat = radiansToDegrees(phiM);\n}\n\nvoid CityGeodeticCalculator::getMidPoint(CityCoordinate& startPoint, CityCoordinate& destPoint, \n\t\t\t\t\t\t\t\t\t\t CityCoordinate& midPoint)\n{\n\tgetMidPoint(startPoint.x, startPoint.y, destPoint.x, destPoint.y, midPoint.x, midPoint.y);\n}\n\nvoid CityGeodeticCalculator::getIntermediatePoint(double startLon, double startLat, double fraction,\n\t\t\t\t\t\t\t\t\t\t\t\t  double destLon, double destLat,\n\t\t\t\t\t\t\t\t\t\t\t\t  double& intermediateLon, double& intermediateLat)\n{\n\tif ((startLon == destLon) && (startLat == destLat)) {\n\t\tintermediateLon = startLon;\n\t\tintermediateLat = startLat;\n\t\treturn;\n\t}\n\n\tdouble lambda1 = degreesToRadians(startLon);\n\tdouble phi1 = degreesToRadians(startLat);\n\tdouble lambda2 = degreesToRadians(destLon);\n\tdouble phi2 = degreesToRadians(destLat);\n\n\tdouble deltaPhi = phi2 - phi1;\n\tdouble deltaLambda = lambda2 - lambda1;\n\n\tdouble a = (std::sin(deltaPhi*0.5)*std::sin(deltaPhi*0.5)) +\n\t\t\t   (std::cos(phi1)*std::cos(phi2)*std::sin(deltaLambda*0.5)*std::sin(deltaLambda*0.5));\n\tdouble delta = 2 * std::atan2(std::sqrt(a), std::sqrt(1-a));\n\n\tdouble A = std::sin((1-fraction)*delta) / std::sin(delta);\n\tdouble B = std::sin(fraction*delta) / std::sin(delta);\n\n\tdouble x = (A * std::cos(phi1) * std::cos(lambda1)) + (B * std::cos(phi2) * std::cos(lambda2));\n\tdouble y = (A * std::cos(phi1) * std::sin(lambda1)) + (B * std::cos(phi2) * std::sin(lambda2));\n\tdouble z = (A * std::sin(phi1)) + (B * std::sin(phi2));\n\n\tdouble phi3 = std::atan2(z, std::sqrt((x*x) + (y*y)));\n\tdouble lambda3 = std::atan2(y, x);\n\n\tintermediateLon = radiansToDegrees(lambda3);\n\tintermediateLat = radiansToDegrees(phi3);\n}\n\nvoid CityGeodeticCalculator::getIntermediatePoint(CityCoordinate& startPoint, double fraction,\n\t\t\t\t\t\t\t\t\t\t\t\t  CityCoordinate& destPoint,\n\t\t\t\t\t\t\t\t\t\t\t\t  CityCoordinate& intermediatePoint)\n{\n\tgetIntermediatePoint(startPoint.x, startPoint.y, fraction, destPoint.x, destPoint.y,\n\t\t\t\t\t\t intermediatePoint.x, intermediatePoint.y);\n}\n\ndouble CityGeodeticCalculator::haversine_getDistance(double startLon, double startLat,\n\t\t\t\t\t\t\t\t\t\t\t\t\t double destLon, double destLat)\n{\n\tdouble lambda1 = degreesToRadians(startLon);\n\tdouble phi1 = degreesToRadians(startLat);\n\tdouble lambda2 = degreesToRadians(destLon);\n\tdouble phi2 = degreesToRadians(destLat);\n\n\tdouble deltaPhi = phi2 - phi1;\n\tdouble deltaLambda = lambda2 - lambda1;\n\n\tdouble a = (std::sin(deltaPhi*0.5) * std::sin(deltaPhi*0.5)) +\n\t\t\t   (std::cos(phi1)*std::cos(phi2)*std::sin(deltaLambda*0.5)*std::sin(deltaLambda*0.5));\n\tdouble c = 2.0 * std::atan2(std::sqrt(a), std::sqrt(1-a));\n\n\treturn RADIUS_EARTH * c;\n}\n\ndouble CityGeodeticCalculator::vincenty_getDistance(double startLon, double startLat,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdouble destLon, double destLat, double& azimuth)\n{\n\tdouble lambda1 = degreesToRadians(startLon);\n\tdouble phi1 = degreesToRadians(startLat);\n\tdouble lambda2 = degreesToRadians(destLon);\n\tdouble phi2 = degreesToRadians(destLat);\n\n\tdouble L = lambda2 - lambda1;\n\tdouble tanU1 = (1 - WGS84_f) * std::tan(phi1);\n\tdouble cosU1 = 1 / std::sqrt((1 + tanU1*tanU1));\n\tdouble sinU1 = tanU1 * cosU1;\n\tdouble tanU2 = (1 - WGS84_f) * std::tan(phi2);\n\tdouble cosU2 = 1 / std::sqrt((1 + tanU2*tanU2));\n\tdouble sinU2 = tanU2 * cosU2;\n\n\tdouble sinLambda, cosLambda, sinSigma = 0, cosSigma = 0, sinAlpha;\n\tdouble sinSqSigma, cosSqAlpha = 0, cos2SigmaM = 0, sigma = 0, C;\n\n\tdouble lambda = L;\n\tdouble lambdaP;\n\tint iterations = 0;\n\n\tbool antimeridian = std::abs(L) > boost::math::constants::pi<double>();\n\n\tdo {\n\t\tsinLambda = std::sin(lambda);\n\t\tcosLambda = std::cos(lambda);\n\n\t\tsinSqSigma = (cosU2*sinLambda)*(cosU2*sinLambda) +\n\t\t\t\t\t (cosU1*sinU2 - sinU1*cosU2*cosLambda) *\n\t\t\t\t\t (cosU1*sinU2 - sinU1*cosU2*cosLambda);\n\n\t\tif (std::abs(sinSqSigma) < std::numeric_limits<double>::epsilon())\n\t\t\tbreak;\n\n\t\tsinSigma = std::sqrt(sinSqSigma);\n\t\tcosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;\n\n\t\tsigma = std::atan2(sinSigma, cosSigma);\n\t\tsinAlpha = cosU1*cosU2*sinLambda / sinSigma;\n\t\tcosSqAlpha = 1 - sinAlpha*sinAlpha;\n\t\tcos2SigmaM = (cosSqAlpha != 0) ? (cosSigma - 2*sinU1*sinU2/cosSqAlpha) : 0;\n\n\t\tC = WGS84_f/16*cosSqAlpha*(4 + WGS84_f*(4 - 3*cosSqAlpha));\n\t\tlambdaP = lambda;\n\t\tlambda = L + (1-C)*WGS84_f*sinAlpha*(sigma + C*sinSigma*(cos2SigmaM + C*cosSigma*(-1 + 2*cos2SigmaM*cos2SigmaM)));\n\t} while ((std::abs(lambda - lambdaP) > 1e-12) && (++iterations < 1000));\n\n\tdouble uSq = cosSqAlpha * (WGS84_a*WGS84_a - WGS84_b*WGS84_b) / (WGS84_b*WGS84_b);\n\tdouble A = 1 + uSq/16384*(4096 + uSq*(-768 + uSq*(320  -175*uSq)));\n\tdouble B = uSq/1024 * (256 + uSq*(-128 + uSq*(74 - 47*uSq)));\n\tdouble deltaSigma = B*sinSigma*(cos2SigmaM + B/4*(cosSigma*(-1 + 2*cos2SigmaM*cos2SigmaM) -\n\t\t\t\t\t\tB/6*cos2SigmaM*(-3 + 4*sinSigma*sinSigma)*(-3 + 4*cos2SigmaM*cos2SigmaM)));\n\n\tdouble distance = WGS84_b*A*(sigma - deltaSigma);\n\n\tdouble alpha = std::atan2(cosU2*sinLambda, cosU1*sinU2 - sinU1*cosU2*cosLambda);\n\tdouble degrees = radiansToDegrees(alpha);\n\tif ((0 > degrees) || (degrees >= 360))\n\t\tdegrees = std::fmod((std::fmod(degrees, 360.0) + 360.0), 360.0);\n\n\tazimuth = std::abs(distance) < std::numeric_limits<double>::epsilon() ? NAN : degrees;\n\n\treturn distance;\n}\n\ndouble CityGeodeticCalculator::getDistance(double startLon, double startLat,\n\t\t\t\t\t\t\t\t\t\t   double destLon, double destLat)\n{\n\tif (formula == GEODETIC_HAVERSINE) {\n\t\treturn haversine_getDistance(startLon, startLat, destLon, destLat);\n\t} else {\n\t\tdouble azimuth;\n\t\treturn vincenty_getDistance(startLon, startLat, destLon, destLat, azimuth);\n\t}\n}\n\ndouble CityGeodeticCalculator::getDistance(CityCoordinate& startPoint, CityCoordinate& destPoint)\n{\n\treturn getDistance(startPoint.x, startPoint.y, destPoint.x, destPoint.y);\n}\n\ndouble CityGeodeticCalculator::haversine_getAzimuth(double startLon, double startLat,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdouble destLon, double destLat)\n{\n\tdouble phi1 = degreesToRadians(startLat);\n\tdouble phi2 = degreesToRadians(destLat);\n\n\tdouble deltaLambda = degreesToRadians(destLon - startLon);\n\n\tdouble x = (std::cos(phi1) * std::sin(phi2)) -\n\t\t\t   (std::sin(phi1) * std::cos(phi2) * std::cos(deltaLambda));\n\tdouble y = std::sin(deltaLambda) * std::cos(phi2);\n\tdouble theta = std::atan2(y, x);\n\n\tdouble azimuth = radiansToDegrees(theta);\n\n\tif ((0 > azimuth) || (azimuth >= 360))\n\t\tazimuth = std::fmod((std::fmod(azimuth, 360.0) + 360.0), 360.0);\n\n\treturn azimuth;\n}\n\ndouble CityGeodeticCalculator::vincenty_getAzimuth(double startLon, double startLat,\n\t\t\t\t\t\t\t\t\t\t\t\t   double destLon, double destLat)\n{\n\tdouble azimuth;\n\tvincenty_getDistance(startLon, startLat, destLon, destLat, azimuth);\n\n\treturn azimuth;\n}\n\ndouble CityGeodeticCalculator::getAzimuth(double startLon, double startLat,\n\t\t\t\t\t\t\t\t\t\t  double destLon, double destLat)\n{\n\tif ((startLon == destLon) && (startLat == destLat))\n\t\treturn NAN;\n\n\tif (formula == GEODETIC_HAVERSINE)\n\t\treturn haversine_getAzimuth(startLon, startLat, destLon, destLat);\n\telse\n\t\treturn vincenty_getAzimuth(startLon, startLat, destLon, destLat);\n}\n\ndouble CityGeodeticCalculator::getAzimuth(CityCoordinate& startPoint, CityCoordinate& destPoint)\n{\n\treturn getAzimuth(startPoint.x, startPoint.y, destPoint.x, destPoint.y);\n}\n\n} /* namespace dtsim */\n", "meta": {"hexsha": "9286d5e8be916cde08b6d521d349aa51a78ae4ea", "size": 14949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/city/CityGeodeticCalculator.cpp", "max_stars_repo_name": "etri/dtsim", "max_stars_repo_head_hexsha": "927c8e05c08c74ed376ec233ff677cd35b29e6f0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/city/CityGeodeticCalculator.cpp", "max_issues_repo_name": "etri/dtsim", "max_issues_repo_head_hexsha": "927c8e05c08c74ed376ec233ff677cd35b29e6f0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/city/CityGeodeticCalculator.cpp", "max_forks_repo_name": "etri/dtsim", "max_forks_repo_head_hexsha": "927c8e05c08c74ed376ec233ff677cd35b29e6f0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5083135392, "max_line_length": 181, "alphanum_fraction": 0.6948290856, "num_tokens": 4303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639791, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.41860923171785214}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n#pragma once\n\n#include <Eigen/Dense>\n#include <iostream>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"sphere.hpp\"\n#include \"clusterer.hpp\"\n#include \"dir.hpp\"\n#include \"cat.hpp\"\n\nusing namespace Eigen;\nusing std::cout;\nusing std::endl;\n\ntemplate<class T>\nclass KMeans : public Clusterer<T>\n{\npublic:\n  KMeans(const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx, uint32_t K,\n    boost::mt19937* pRndGen);\n  virtual ~KMeans();\n\n//  void initialize(const Matrix<T,Dynamic,Dynamic>& x);\n\n  virtual void updateLabels();\n  virtual void updateCenters();\n  virtual MatrixXu mostLikelyInds(uint32_t n, Matrix<T,Dynamic,Dynamic>& deviates);\n  virtual T avgIntraClusterDeviation();\n\n  virtual T dist(const Matrix<T,Dynamic,1>& a, const Matrix<T,Dynamic,1>& b);\n  virtual bool closer(T a, T b);\n  virtual uint32_t indOfClosestCluster(int32_t i);\n  virtual Matrix<T,Dynamic,1> computeCenter(uint32_t k);\n  \n\nprotected:\n  Sphere<T> S_;  // TODO this should not be here - needed for the empty cluster\n};\n\n// --------------------------- impl -------------------------------------------\n\ntemplate<class T>\nKMeans<T>::KMeans(\n    const boost::shared_ptr<Matrix<T,Dynamic,Dynamic> >& spx, uint32_t K,\n    boost::mt19937* pRndGen)\n  : Clusterer<T>(spx,K, pRndGen), S_(this->D_) \n{\n  Matrix<T,Dynamic,1> alpha(this->K_);\n  alpha.setOnes(this->K_);\n  Dir<Cat<T>,T> dir(alpha,this->pRndGen_);\n  Cat<T> pi = dir.sample(); \n  cout<<\"init pi=\"<<pi.pdf().transpose()<<endl;\n  pi.sample(this->z_);\n\n  this->ps_.setZero(); \n//  updateCenters();\n//  for(uint32_t k=0; k<this->K_; ++k)\n//    this->ps_.col(k) = S_.sampleUnif(this->pRndGen_);\n//  cout<<\"init centers\"<<endl<<this->ps_<<endl;\n}\n\ntemplate<class T>\nKMeans<T>::~KMeans()\n{}\n\n\ntemplate<class T>\nT KMeans<T>::dist(const Matrix<T,Dynamic,1>& a, const Matrix<T,Dynamic,1>& b)\n{\n  return (a-b).norm();\n};\n\ntemplate<class T>\nbool KMeans<T>::closer(T a, T b)\n{\n  return a<b; // if dist a is smaller than dist b a is closer than b (Eucledian)\n};\n\n\ntemplate<class T>\nuint32_t KMeans<T>::indOfClosestCluster(int32_t i)\n{\n  T sim_closest = dist(this->ps_.col(0), this->spx_->col(i));\n  uint32_t z_i = 0;\n  for(uint32_t k=1; k<this->K_; ++k)\n  {\n    T sim_k = dist(this->ps_.col(k), this->spx_->col(i));\n    if( closer(sim_k, sim_closest))\n    {\n      sim_closest = sim_k;\n      z_i = k;\n    }\n  }\n  return z_i;\n};\n\ntemplate<class T>\nvoid KMeans<T>::updateLabels()\n{\n#pragma omp parallel for \n  for(uint32_t i=0; i<this->N_; ++i)\n  {\n    this->z_(i) = indOfClosestCluster(i);\n  }\n}\n\ntemplate<class T>\nMatrix<T,Dynamic,1> KMeans<T>::computeCenter(uint32_t k)\n{\n  this->Ns_(k) = 0.0;\n  Matrix<T,Dynamic,1> mean_k(this->D_);\n  mean_k.setZero(this->D_);\n  for(uint32_t i=0; i<this->N_; ++i)\n    if(this->z_(i) == k)\n    {\n      mean_k += this->spx_->col(i); \n      this->Ns_(k) ++;\n    }\n  return mean_k/this->Ns_(k);\n}\n\ntemplate<class T>\nvoid KMeans<T>::updateCenters()\n{\n#pragma omp parallel for \n  for(uint32_t k=0; k<this->K_; ++k)\n  {\n    this->ps_.col(k) = computeCenter(k);\n    if (this->Ns_(k) <= 0) \n      this->ps_.col(k) = S_.sampleUnif(this->pRndGen_);\n  }\n}\n\ntemplate<class T>\nMatrixXu KMeans<T>::mostLikelyInds(uint32_t n, \n    Matrix<T,Dynamic,Dynamic>& deviates)\n{\n  MatrixXu inds = MatrixXu::Zero(n,this->K_);\n  deviates = Matrix<T,Dynamic,Dynamic>::Ones(n,this->K_);\n  \n#pragma omp parallel for \n  for (uint32_t k=0; k<this->K_; ++k)\n  {\n    for (uint32_t i=0; i<this->N_; ++i)\n      if(this->z_(i) == k)\n      {\n        T deviate = dist(this->ps_.col(k), this->spx_->col(i));\n//        T deviate = (this->ps_.col(k) - this->spx_->col(i)).norm();\n        for (uint32_t j=0; j<n; ++j)\n          if(closer(deviate, deviates(j,k)))\n          {\n            for(uint32_t l=n-1; l>j; --l)\n            {\n              deviates(l,k) = deviates(l-1,k);\n              inds(l,k) = inds(l-1,k);\n            }\n            deviates(j,k) = deviate;\n            inds(j,k) = i;\n//            cout<<\"after update \"<<logLike<<endl;\n//            Matrix<T,Dynamic,Dynamic> out(n,this->K_*2);\n//            out<<logLikes.cast<T>(),inds.cast<T>();\n//            cout<<out<<endl;\n            break;\n          }\n      }\n  } \n  cout<<\"::mostLikelyInds: deviates\"<<endl;\n  cout<<deviates<<endl;\n  cout<<\"::mostLikelyInds: inds\"<<endl;\n  cout<<inds<<endl;\n  return inds;\n};\n\ntemplate<class T>\nT KMeans<T>::avgIntraClusterDeviation()\n{\n  Matrix<T,Dynamic,1> deviates(this->K_);\n  deviates.setZero(this->K_);\n#pragma omp parallel for \n  for (uint32_t k=0; k<this->K_; ++k)\n  {\n    this->Ns_(k) = 0.0;\n    for (uint32_t i=0; i<this->N_; ++i)\n      if(this->z_(i) == k)\n      {\n        deviates(k) += dist(this->ps_.col(k), this->spx_->col(i));\n//        deviates(k) += (this->ps_.col(k) - this->spx_->col(i)).norm();\n        this->Ns_(k) ++;\n      }\n    if(this->Ns_(k) > 0.0) deviates(k) /= this->Ns_(k);\n  }\n  return deviates.sum()/static_cast<T>(this->K_);\n}\n", "meta": {"hexsha": "bd36345f1b75a93ed3663ea55d952990aa70d424", "size": 5043, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/deprecated/kmeans.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/deprecated/kmeans.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/deprecated/kmeans.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 25.215, "max_line_length": 83, "alphanum_fraction": 0.5968669443, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4186092248530757}}
{"text": "/*\n * convlayer.cpp\n *\n * Feed-forward:\n *    z(l) = a(l-1) * w(l) + b(l) // where * is conv operation and b(l) is a scalar\n *    a(l) = activation(z(l))\n *\n * Back propagation:\n *    gradient(C, a(l-1)) = full_conv(delta(l), rotate180(w(l)))\n *\n *    delta(l) = elem_prod(gradient(C, a(l)), activation_derivative(z(l)))\n *    dC/dw(l) = conv(a(l), delta(l + 1))\n *    dC/db(l) = sum_elem(delta(l + 1))\n */\n#include <boost/assert.hpp>\n\n#include \"core/utils.h\"\n#include \"core/random.h\"\n#include \"core/functions.h\"\n#include \"contlayer.h\"\n#include \"convlayer.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace yann;\n\nnamespace yann {\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// ConvolutionalLayerContext implementation\n//\nclass ConvolutionalLayer_Context :\n    public Layer::Context\n{\n  typedef Layer::Context Base;\n\n  friend class ConvolutionalLayer;\n\npublic:\n  ConvolutionalLayer_Context(\n      const MatrixSize & output_size,\n      const MatrixSize & batch_size) :\n    Base(output_size, batch_size)\n  {\n    _zz.resizeLike(get_output());\n  }\n  ConvolutionalLayer_Context(const RefVectorBatch & output) :\n    Base(output)\n  {\n    _zz.resizeLike(get_output());\n  }\n\nprotected:\n  VectorBatch _zz;\n}; // class ConvolutionalLayer_Context\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// ConvolutionalLayer_TrainingContext implementation\n//\nclass ConvolutionalLayer_TrainingContext :\n  public ConvolutionalLayer_Context\n{\n  typedef ConvolutionalLayer_Context Base;\n\n  friend class ConvolutionalLayer;\n\npublic:\n  ConvolutionalLayer_TrainingContext(\n      const MatrixSize & output_size,\n      const MatrixSize & batch_size,\n      const MatrixSize & filter_size,\n      const unique_ptr<Layer::Updater> & updater) :\n    Base(output_size, batch_size),\n    _ww_rotated(filter_size, filter_size),\n    _delta_ww(filter_size, filter_size),\n    _delta_bb(0),\n    _ww_updater(updater->copy()),\n    _bb_updater(updater->copy())\n  {\n    YANN_CHECK_GT(filter_size, 0);\n    YANN_CHECK_GT(output_size, 0);\n    YANN_CHECK_GT(batch_size, 0);\n\n    _delta.resizeLike(_zz);\n    _sigma_derivative_zz.resizeLike(_zz);\n\n    _ww_updater->init(filter_size, filter_size);\n    _bb_updater->init(1, 1);\n  }\n  ConvolutionalLayer_TrainingContext(\n      const RefVectorBatch & output,\n      const MatrixSize & filter_size,\n      const unique_ptr<Layer::Updater> & updater) :\n    Base(output),\n    _ww_rotated(filter_size, filter_size),\n    _delta_ww(filter_size, filter_size),\n    _delta_bb(0),\n    _ww_updater(updater->copy()),\n    _bb_updater(updater->copy())\n  {\n    YANN_CHECK_GT(filter_size, 0);\n    YANN_CHECK_GT(yann::get_batch_size(output), 0);\n    YANN_CHECK_GT(yann::get_batch_item_size(output), 0);\n\n    _delta.resizeLike(_zz);\n    _sigma_derivative_zz.resizeLike(_zz);\n\n    _ww_updater->init(filter_size, filter_size);\n    _bb_updater->init(1, 1);\n  }\n\n  // Layer::Context  overwrites\n  virtual void start_epoch()\n  {\n    YANN_SLOW_CHECK(_ww_updater);\n    YANN_SLOW_CHECK(_bb_updater);\n\n    Base::start_epoch();\n\n    _ww_updater->start_epoch();\n    _bb_updater->start_epoch();\n  }\n\n  virtual void reset_state()\n  {\n    YANN_SLOW_CHECK(_ww_updater);\n    YANN_SLOW_CHECK(_bb_updater);\n\n    Base::reset_state();\n\n    _delta_ww.setZero();\n    _delta_bb = 0;\n\n    _ww_updater->reset();\n    _bb_updater->reset();\n  }\n\nprivate:\n  Matrix _ww_rotated;\n  Matrix _delta_ww;\n  Value  _delta_bb;\n\n  VectorBatch _delta;\n  VectorBatch _sigma_derivative_zz;\n\n  unique_ptr<Layer::Updater> _ww_updater;\n  unique_ptr<Layer::Updater> _bb_updater;\n}; // class ConvolutionalLayer_TrainingContext\n\n\n}; // namespace yann\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// yann::ConvolutionalLayer implementation\n//\nMatrixSize yann::ConvolutionalLayer::get_input_size(\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols)\n{\n  return input_rows * input_cols;\n}\n\nMatrixSize yann::ConvolutionalLayer::get_conv_output_rows(\n    const MatrixSize & input_rows,\n    const MatrixSize & filter_rows)\n{\n  return (input_rows - filter_rows + 1);\n}\nMatrixSize yann::ConvolutionalLayer::get_conv_output_cols(\n    const MatrixSize & input_cols,\n    const MatrixSize & filter_cols)\n{\n  return (input_cols - filter_cols + 1);\n}\nMatrixSize yann::ConvolutionalLayer::get_conv_output_size(\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    const MatrixSize & filter_rows,\n    const MatrixSize & filter_cols)\n{\n  return get_conv_output_rows(input_rows, filter_rows)\n      * get_conv_output_cols(input_cols, filter_cols);\n}\nMatrixSize yann::ConvolutionalLayer::get_conv_output_size(\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    const MatrixSize & filter_size)\n{\n  return get_conv_output_size(input_rows, input_cols, filter_size, filter_size);\n}\n\nMatrixSize yann::ConvolutionalLayer::get_full_conv_output_rows(\n    const MatrixSize & input_rows,\n    const MatrixSize & filter_rows)\n{\n  return (input_rows + filter_rows - 1);\n}\nMatrixSize yann::ConvolutionalLayer::get_full_conv_output_cols(\n    const MatrixSize & input_cols,\n    const MatrixSize & filter_cols)\n{\n  return (input_cols + filter_cols - 1);\n}\nMatrixSize yann::ConvolutionalLayer::get_full_conv_output_size(\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    const MatrixSize & filter_rows,\n    const MatrixSize & filter_cols)\n{\n  return get_full_conv_output_rows(input_rows, filter_rows)\n      * get_full_conv_output_cols(input_cols, filter_cols);\n}\nMatrixSize yann::ConvolutionalLayer::get_full_conv_output_size(\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    const MatrixSize & filter_size)\n{\n  return get_full_conv_output_size(\n      input_rows, input_cols,\n      filter_size, filter_size);\n}\n\nvoid yann::ConvolutionalLayer::plus_conv(\n    const RefConstMatrix & input,\n    const RefConstMatrix & filter,\n    RefMatrix output,\n    bool clear_output)\n{\n  YANN_SLOW_CHECK_GT(filter.rows(), 0);\n  YANN_SLOW_CHECK_GT(filter.cols(), 0);\n  YANN_SLOW_CHECK_LE(filter.rows(), input.rows());\n  YANN_SLOW_CHECK_LE(filter.cols(), input.cols());\n\n  const auto input_rows = input.rows();\n  const auto filter_rows = filter.rows();\n  const auto filter_cols = filter.cols();\n  const auto output_rows = get_conv_output_rows(input.rows(), filter_rows);\n  const auto output_cols = get_conv_output_cols(input.cols(), filter_cols);\n\n  if(clear_output) {\n    output.setZero();\n  }\n\n  YANN_SLOW_CHECK_EQ(output.rows(), output_rows);\n  YANN_SLOW_CHECK_EQ(output.cols(), output_cols);\n  YANN_SLOW_CHECK_LE(filter_rows, input_rows);\n  YANN_SLOW_CHECK_LE(output_rows, input_rows);\n\n  auto apply_to_row = [&](const auto & ii, const auto & filter_start_row, const auto & filter_max_rows) mutable {\n    const auto in_row = input.row(ii);\n    // then through the filter by rows, account for \"cutoff\" at bottom rows\n    for(MatrixSize kk = filter_start_row, ll = ii - filter_start_row; kk < filter_max_rows; ++kk, --ll) {\n      const auto filter_row = filter.row(kk);\n      auto out_row = output.row(ll);\n      for(MatrixSize jj = 0; jj < output_cols; ++jj) {\n          const auto in_block = in_row.segment(jj, filter_cols);\n          out_row(jj) += (in_block.array() * filter_row.array()).sum();\n      }\n    }\n  };\n\n  // iterate through the input by rows\n  MatrixSize filter_start_row = 0, filter_max_rows = 0;\n  for(MatrixSize ii = 0; ii < input_rows; ++ii) {\n    if(ii < filter_rows) {\n      // filter at the top of the input; bottom filter rows\n      // don't contribute to the output\n      ++filter_max_rows;\n    }\n    if(ii >= output_rows) {\n      // filter at the bottom of the input; top filter rows\n      // don't contribute to the output\n      ++filter_start_row;\n    }\n\n    // and now through each col and then filter row\n    apply_to_row(ii, filter_start_row, filter_max_rows);\n  }\n}\n\nvoid yann::ConvolutionalLayer::plus_conv(\n    const RefConstVectorBatch & input,\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    const RefConstMatrix & filter,\n    RefVectorBatch output,\n    bool clear_output)\n{\n  YANN_SLOW_CHECK_GT(filter.rows(), 0);\n  YANN_SLOW_CHECK_GT(filter.cols(), 0);\n  YANN_SLOW_CHECK_LE(filter.rows(), input_rows);\n  YANN_SLOW_CHECK_LE(filter.cols(), input_cols);\n  YANN_SLOW_CHECK_GT(get_batch_size(input), 0);\n  YANN_SLOW_CHECK_EQ(get_batch_item_size(input), input_rows * input_cols);\n  YANN_SLOW_CHECK_EQ(get_batch_size(output), get_batch_size(input));\n\n  const auto filter_rows = filter.rows();\n  const auto filter_cols = filter.cols();\n  const auto output_rows = get_conv_output_rows(input_rows, filter_rows);\n  const auto output_cols = get_conv_output_cols(input_cols, filter_cols);\n  const auto batch_size = get_batch_size(input);\n  YANN_SLOW_CHECK_EQ(get_batch_item_size(output), output_rows * output_cols);\n\n  if(clear_output) {\n    output.setZero();\n  }\n\n  // ATTENTION: this code operates on raw Matrix.data() and might be broken\n  // if Matrix.data() layout changes\n  for(MatrixSize ii = 0; ii < batch_size; ++ii) {\n    const auto in_batch = get_batch(input, ii);\n    auto out_batch = get_batch(output, ii);\n    MapConstMatrix in(in_batch.data(), input_rows, input_cols);\n    MapMatrix out(out_batch.data(), output_rows, output_cols);\n    plus_conv(in, filter, out, false); // we already cleared output if needed\n  }\n}\n\nvoid yann::ConvolutionalLayer::full_conv(\n    const RefConstMatrix & input,\n    const RefConstMatrix & filter,\n    RefMatrix output)\n{\n  YANN_SLOW_CHECK_GT(filter.rows(), 0);\n  YANN_SLOW_CHECK_GT(filter.cols(), 0);\n  YANN_SLOW_CHECK_LE(filter.rows(), input.rows());\n  YANN_SLOW_CHECK_LE(filter.cols(), input.cols());\n\n  const auto input_rows = input.rows();\n  const auto input_cols = input.cols();\n  const auto filter_rows = filter.rows();\n  const auto filter_cols = filter.cols();\n  const auto output_cols = get_full_conv_output_cols(input_cols, filter_cols);\n\n  YANN_SLOW_CHECK_EQ(output.rows(), get_full_conv_output_rows(input_rows, filter_rows));\n  YANN_SLOW_CHECK_EQ(output.cols(), output_cols);\n\n  // clear output\n  output.setZero();\n\n  MatrixSize input_row, output_col, output_last_row;\n  auto apply_filter = [&](const auto & in_block, const auto & filter_block) mutable {\n    // iterate through the filter by rows, account for \"cutoff\" at bottom rows\n    for(MatrixSize kk = 0; kk < filter_rows; ++kk) {\n      output(output_last_row - kk, output_col) += (in_block.array() * filter_block.row(kk).array()).sum();\n    }\n  };\n\n  // iterate through the input by rows\n  for(input_row = 0, output_last_row = filter_rows - 1;\n      input_row < input_rows;\n      ++input_row, ++output_last_row)\n  {\n    auto in_row = input.row(input_row);\n\n    // iterate through output columns: we have 3 stages:\n    // - filter on the left side of input with partial overlap\n    // - filter over input with full overlap\n    // - filter on the right side of input with partial overlap\n\n    // on the left side from input\n    MatrixSize in_start = 0, filter_start = filter_cols - 1, col_size = 1;\n    for(output_col = 0; col_size < filter_cols; ++output_col, ++col_size, --filter_start) {\n      // in_start == 0\n      // col_size == output_col + 1\n      // filter_start == filter_cols - col_size;\n      auto in_block = in_row.segment(0, col_size);\n      apply_filter(in_block, filter.rightCols(col_size));\n    }\n\n    // full overlap by columns\n    for(; output_col < input_cols; ++output_col, ++in_start) {\n      // in_start == output_col - filter_cols + 1;\n      // col_size == filter_cols\n      // filter_start == 0\n      auto in_block = in_row.segment(in_start, col_size);\n      // using here just filter instead of filter.rightCols() affects perf in a bad way\n      apply_filter(in_block, filter.leftCols(col_size));\n    }\n\n    // on the right side from input\n    for(--col_size; output_col < output_cols; ++output_col, ++in_start, --col_size) {\n      // in_start == output_col - filter_cols + 1;\n      // col_size == input_cols - in_start;\n      // filter_start == 0\n      auto in_block = in_row.segment(in_start, col_size);\n      apply_filter(in_block, filter.leftCols(col_size));\n    }\n  }\n}\n\nvoid yann::ConvolutionalLayer::full_conv(\n    const RefConstVectorBatch & input,\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    const RefConstMatrix & filter,\n    RefVectorBatch output)\n{\n  YANN_SLOW_CHECK_GT(filter.rows(), 0);\n  YANN_SLOW_CHECK_GT(filter.cols(), 0);\n  YANN_SLOW_CHECK_LE(filter.rows(), input_rows);\n  YANN_SLOW_CHECK_LE(filter.cols(), input_cols);\n  YANN_SLOW_CHECK_GT(get_batch_size(input), 0);\n  YANN_SLOW_CHECK_EQ(get_batch_item_size(input), input_rows * input_cols);\n  YANN_SLOW_CHECK_EQ(get_batch_size(output), get_batch_size(input));\n\n  const auto filter_rows = filter.rows();\n  const auto filter_cols = filter.cols();\n  const auto output_rows = get_full_conv_output_rows(input_rows, filter_rows);\n  const auto output_cols = get_full_conv_output_cols(input_cols, filter_cols);\n  const auto batch_size = get_batch_size(input);\n  YANN_SLOW_CHECK_EQ(get_batch_item_size(output), output_rows * output_cols);\n\n  // ATTENTION: this code operates on raw Matrix.data() and might be broken\n  // if Matrix.data() layout changes\n  for(MatrixSize ii = 0; ii < batch_size; ++ii) {\n    auto in_batch = get_batch(input, ii);\n    auto out_batch = get_batch(output, ii);\n    MapConstMatrix in(in_batch.data(), input_rows, input_cols);\n    MapMatrix out(out_batch.data(), output_rows, output_cols);\n    full_conv(in, filter, out);\n  }\n}\n\nvoid yann::ConvolutionalLayer::rotate180(const Matrix & input, Matrix & output)\n{\n  output.resize(input.rows(), input.cols());\n  for (MatrixSize ii = 0, size1 = input.rows(), size2 = input.cols(); ii < size1;\n      ++ii) {\n    for (MatrixSize jj = 0; jj < size2; ++jj) {\n      output(ii, jj) = input(size1 - ii - 1, size2 - jj - 1);\n    }\n  }\n}\n\n// Convolutional layer: broadcast from input to all the conv layers\nunique_ptr<BroadcastLayer> yann::ConvolutionalLayer::create_conv_bcast_layer(\n    const size_t & output_frames_num,\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    const MatrixSize & filter_size,\n    const unique_ptr<ActivationFunction> & activation_function)\n{\n  YANN_CHECK_GT(output_frames_num, 0);\n\n  auto bcast_layer = make_unique<BroadcastLayer>();\n  YANN_CHECK(bcast_layer);\n  for(auto ii = output_frames_num; ii > 0; --ii) {\n    auto conv_layer = make_unique<ConvolutionalLayer>(\n        input_rows,\n        input_cols,\n        filter_size);\n    YANN_CHECK(conv_layer);\n\n    if(activation_function) {\n      conv_layer->set_activation_function(activation_function);\n    }\n    bcast_layer->append_layer(std::move(conv_layer));\n  }\n\n  return bcast_layer;\n}\n\nyann::ConvolutionalLayer::ConvolutionalLayer(\n    const MatrixSize & input_rows,\n    const MatrixSize & input_cols,\n    const MatrixSize & filter_size) :\n  _input_rows(input_rows),\n  _input_cols(input_cols),\n  _filter_size(filter_size),\n  _ww(filter_size, filter_size),\n  _bb(0),\n  _activation_function(new SigmoidFunction())\n{\n  YANN_CHECK_GE(input_rows, filter_size);\n  YANN_CHECK_GE(input_cols, filter_size);\n  YANN_CHECK_GT(filter_size, 0);\n}\n\nyann::ConvolutionalLayer::~ConvolutionalLayer()\n{\n}\n\nvoid yann::ConvolutionalLayer::set_activation_function(\n    const unique_ptr<ActivationFunction> & activation_function)\n{\n  YANN_CHECK(activation_function);\n  _activation_function = activation_function->copy();\n}\n\nvoid yann::ConvolutionalLayer::set_values(const Matrix & ww, const Value & bb)\n{\n  YANN_CHECK(is_same_size(ww, _ww));\n  _ww = ww;\n  _bb = bb;\n}\n\n// Layer overwrites\nbool yann::ConvolutionalLayer::is_valid() const\n{\n  if(!Base::is_valid()) {\n    return false;\n  }\n  if(!_activation_function) {\n    return false;\n  }\n  return true;\n}\n\nstd::string yann::ConvolutionalLayer::get_name() const\n{\n  return \"ConvolutionalLayer\";\n}\n\nstring yann::ConvolutionalLayer::get_info() const\n{\n  YANN_CHECK(is_valid());\n\n  ostringstream oss;\n  oss << Base::get_info()\n      << \" activation: \" << _activation_function->get_info()\n      << \", input rows: \" << _input_rows\n      << \", input cols: \" << _input_cols\n      << \", filter: \" << _filter_size\n      << \", output rows: \" << get_output_rows()\n      << \", output cols: \" << get_output_cols()\n  ;\n  return oss.str();\n}\n\nbool yann::ConvolutionalLayer::is_equal(const Layer& other, double tolerance) const\n{\n  if(!Base::is_equal(other, tolerance)) {\n    return false;\n  }\n  auto * the_other = dynamic_cast<const ConvolutionalLayer*>(&other);\n  if(the_other == nullptr) {\n    return false;\n  }\n  // TOOD: add deep compare\n  if(_activation_function->get_info() != the_other->_activation_function->get_info()) {\n    return false;\n  }\n  if(!_ww.isApprox(the_other->_ww, tolerance)) {\n    return false;\n  }\n  if(fabs(_bb - the_other->_bb) >= tolerance) {\n    return false;\n  }\n  return true;\n}\n\nMatrixSize yann::ConvolutionalLayer::get_input_size() const\n{\n  return get_input_size(_input_rows, _input_cols);\n}\n\nMatrixSize yann::ConvolutionalLayer::get_output_size() const\n{\n  return get_conv_output_size(_input_rows, _input_cols, _filter_size);\n}\n\nMatrixSize yann::ConvolutionalLayer::get_output_rows() const\n{\n  return get_conv_output_rows(_input_rows, _filter_size);\n}\n\nMatrixSize yann::ConvolutionalLayer::get_output_cols() const\n{\n  return get_conv_output_cols(_input_cols, _filter_size);\n}\n\nunique_ptr<Layer::Context> yann::ConvolutionalLayer::create_context(\n    const MatrixSize & batch_size) const\n{\n  return make_unique<ConvolutionalLayer_Context>(get_output_size(), batch_size);\n}\nunique_ptr<Layer::Context> yann::ConvolutionalLayer::create_context(\n    const RefVectorBatch & output) const\n{\n  return make_unique<ConvolutionalLayer_Context>(output);\n}\nunique_ptr<Layer::Context> yann::ConvolutionalLayer::create_training_context(\n    const MatrixSize & batch_size,\n    const std::unique_ptr<Layer::Updater> & updater) const\n{\n  YANN_CHECK(updater);\n  YANN_CHECK(is_valid());\n  return make_unique<ConvolutionalLayer_TrainingContext>(\n      get_output_size(), batch_size, _filter_size, updater);\n}\nunique_ptr<Layer::Context> yann::ConvolutionalLayer::create_training_context(\n    const RefVectorBatch & output,\n    const std::unique_ptr<Layer::Updater> & updater) const\n{\n  YANN_CHECK(updater);\n  YANN_CHECK(is_valid());\n  return make_unique<ConvolutionalLayer_TrainingContext>(\n      output, _filter_size, updater);\n}\n\nvoid yann::ConvolutionalLayer::feedforward(\n    const RefConstVectorBatch & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  auto ctx = dynamic_cast<ConvolutionalLayer_Context *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(is_valid());\n\n  // z(l) = conv(a(l-1))*w(l) + b(l)\n  plus_conv(input, _input_rows, _input_cols, _ww, ctx->_zz);\n  ctx->_zz.array() += _bb;\n\n  // a(l) = activation(z(l))\n  YANN_CHECK(is_same_size(ctx->_zz, ctx->get_output()));\n  _activation_function->f(ctx->_zz, ctx->get_output(), mode);\n}\n\nvoid yann::ConvolutionalLayer::feedforward(\n    const RefConstSparseVectorBatch & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  throw runtime_error(\"ConvolutionalLayer::feedforward() is not implemented for sparse vectors\");\n}\n\nvoid yann::ConvolutionalLayer::backprop(\n    const RefConstVectorBatch & gradient_output,\n    const RefConstVectorBatch & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  auto ctx = dynamic_cast<ConvolutionalLayer_TrainingContext*>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(is_valid());\n  YANN_CHECK_GT(get_batch_size(gradient_output), 0);\n  YANN_CHECK_EQ(get_batch_item_size(gradient_output), get_output_size());\n  YANN_CHECK_EQ(get_batch_size(input), get_batch_size(gradient_output));\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_CHECK(!gradient_input || is_same_size(input, *gradient_input));\n\n  // just to make it easier to read\n  const auto & zz = ctx->_zz;\n  auto & sigma_derivative_zz = ctx->_sigma_derivative_zz;\n  auto & delta = ctx->_delta;\n  auto & delta_ww = ctx->_delta_ww;\n  auto & delta_bb = ctx->_delta_bb;\n  const auto batch_size = get_batch_size(input);\n\n  // delta(l) = elem_prod(gradient(C, a(l)), activation_derivative(z(l)))\n  YANN_CHECK(is_same_size(zz, sigma_derivative_zz));\n  YANN_CHECK(is_same_size(zz, gradient_output));\n  _activation_function->derivative(zz, sigma_derivative_zz);\n  delta.array() = gradient_output.array() * sigma_derivative_zz.array();\n\n  // update deltas\n  // dC/dw(l) = conv(a(l), delta(l + 1))\n  // dC/db(l) = sum_elem(delta(l + 1))\n  YANN_CHECK_EQ(batch_size, get_batch_size(delta));\n  for (MatrixSize ii = 0; ii < batch_size; ++ii) {\n    auto input_batch = get_batch(input, ii);\n    auto delta_batch = get_batch(delta, ii);\n    MapConstMatrix input_row(input_batch.data(), _input_rows, _input_cols);\n    MapConstMatrix delta_row(delta_batch.data(), get_output_rows(), get_output_cols());\n    plus_conv(input_row, delta_row, delta_ww, false); // delta_ww += conv()\n  }\n  delta_bb += delta.array().sum();\n\n  // we don't need to calculate the first gradient(C, a(l)) for the actual inputs\n  if(gradient_input) {\n    // gradient(C, a(l-1)) = full_conv(delta(l), rotate180(w(l)))\n    rotate180(_ww, ctx->_ww_rotated); // TODO: we can cache the rotation if _ww doesn't change\n    full_conv(delta, get_output_rows(), get_output_cols(), ctx->_ww_rotated, *gradient_input);\n  }\n}\n\nvoid yann::ConvolutionalLayer::backprop(\n    const RefConstVectorBatch & gradient_output,\n    const RefConstSparseVectorBatch & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  throw runtime_error(\"ConvolutionalLayer::backprop() is not implemented for sparse vectors\");\n}\n\nvoid yann::ConvolutionalLayer::init(enum InitMode mode, optional<InitContext> init_context)\n{\n  switch (mode) {\n  case InitMode_Zeros:\n    _ww.setZero();\n    _bb = 0;;\n    break;\n  case InitMode_Random:\n    {\n      unique_ptr<RandomGenerator> gen01 = RandomGenerator::normal_distribution(0, 1,\n          init_context ? optional<Value>(init_context->seed()) : boost::none);\n      gen01->generate(_ww);\n      gen01->generate(_bb);\n    }\n    break;\n  }\n}\n\nvoid yann::ConvolutionalLayer::update(Context * context, const size_t & tests_num)\n{\n  auto ctx = dynamic_cast<ConvolutionalLayer_TrainingContext *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(ctx->_ww_updater);\n  YANN_CHECK(ctx->_bb_updater);\n  YANN_CHECK(is_same_size(_ww, ctx->_delta_ww));\n\n  ctx->_ww_updater->update(ctx->_delta_ww, tests_num, _ww);\n  ctx->_bb_updater->update(ctx->_delta_bb, tests_num, _bb);\n}\n\n// the format is (w:<weights>,b:<bias>)\nvoid yann::ConvolutionalLayer::read(std::istream & is)\n{\n  Base::read(is);\n\n  read_char(is, '(');\n  read_object(is, \"w\", _ww);\n  read_char(is, ',');\n  read_object(is, \"b\", _bb);\n  read_char(is, ')');\n}\n\n// the format is (w:<weights>,b:<bias>)\nvoid yann::ConvolutionalLayer::write(std::ostream & os) const\n{\n  Base::write(os);\n\n  os << \"(\";\n  write_object(os, \"w\", _ww);\n  os << \",\";\n  write_object(os, \"b\", _bb);\n  os << \")\";\n}\n\n", "meta": {"hexsha": "ca4e48f99fce8f488d2a713f0174b063e274770d", "size": 23082, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/layers/convlayer.cpp", "max_stars_repo_name": "lsh123/yann", "max_stars_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:14:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T10:25:07.000Z", "max_issues_repo_path": "src/layers/convlayer.cpp", "max_issues_repo_name": "lsh123/yann", "max_issues_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/layers/convlayer.cpp", "max_forks_repo_name": "lsh123/yann", "max_forks_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0241935484, "max_line_length": 113, "alphanum_fraction": 0.7029720128, "num_tokens": 5969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.41859541277783463}}
{"text": "//\n// Created by wang yu on 2018/6/20.\n//\n#include \"mview.h\"\n#include <iostream>\n\n#include <Eigen/Eigen>\n#include <Eigen/Dense>\n#include <opencv2/core.hpp>\n#include <opencv/cv.hpp>\n#include <opencv2/core/eigen.hpp>\n\nstatic int debug_count = 0;\n\ncv::Mat convertRgbToOpenCV(const RgbImage& rgb) {\n\tGrayImage r = rgb.unaryExpr([](Eigen::Vector3f rgb) { return rgb[0]; });\n\tGrayImage g = rgb.unaryExpr([](Eigen::Vector3f rgb) { return rgb[1]; });\n\tGrayImage b = rgb.unaryExpr([](Eigen::Vector3f rgb) { return rgb[2]; });\n\n\tcv::Mat r_mat;\n    cv::eigen2cv(r,r_mat);\n\tcv::Mat g_mat;\n    cv::eigen2cv(g,g_mat);\n\tcv::Mat b_mat;\n    cv::eigen2cv(b,b_mat);\n\n\tcv::Mat arr[3] { r_mat, g_mat, b_mat };\n\tcv::Mat rgb_mat;\n\tcv::merge(arr, 3, rgb_mat);\n\treturn rgb_mat;\n}\n\nRgbImage convertOpenCVToRgb(const cv::Mat imageMat){\n    cv::Mat rgb[3];\n    cv::split(imageMat, rgb);\n\n\tint width = imageMat.cols;\n\tint height = imageMat.rows;\n    GrayImage r(height, width), g(height, width), b(height, width);\n\n    cv::cv2eigen(rgb[0], r);\n    cv::cv2eigen(rgb[1], g);\n    cv::cv2eigen(rgb[2], b);\n\n    RgbImage rgbImage (g.rows(), g.cols());\n\n    for(int row=0;row<g.rows();row++){\n        for(int col=0;col<g.cols();col++){\n            rgbImage(row,col)<<r(row,col),g(row,col),b(row,col);\n        }\n    }\n\n    return rgbImage;\n}\n\n\nvoid remap_rgb(cv::Mat& rgb_image, cv::Mat map1, cv::Mat map2) {\n\tcv::Mat rgbs[3];\n\tcv::split(rgb_image, rgbs);\n  \n\tcv::Mat rgbs_out[3];\n\tfor(int i = 0; i < 3; i++)\n\t\tcv::remap(rgbs[i], rgbs_out[i], map1, map2, cv::INTER_NEAREST, cv::BORDER_CONSTANT);\n\n\tcv::merge(rgbs_out, 3, rgb_image);\n}\n\nauto rectify(const Image& left, const Image& right) -> Rectified{\n    //load data\n    GrayImage left_gray_pixels=left.gray_pixels;\n    RgbImage left_rgb_pixels=left.rgb_pixels;\n\n    GrayImage right_gray_pixels=right.gray_pixels;\n    RgbImage right_rgb_pixels=right.rgb_pixels;\n\n\tEigen::Matrix4f left_to_right = right.extrinsics * left.extrinsics.inverse();\n\tfor(int i = 0; i < 3; i++)\n\t\tassert(left_to_right(3, i) == 0);\n\tassert(left_to_right(3, 3) == 1.0);\n\n    //rotation and transformation from left camera to right camera\n    Eigen::Matrix3f R = left_to_right.block<3, 3>(0, 0);\n    Eigen::Vector3f T = R.transpose() * left_to_right.block<3, 1>(0, 3);\n\n    //convert eigen matrix to mat\n    cv::Mat left_gray_mat, left_ground_mat;\n    cv::eigen2cv(left_gray_pixels, left_gray_mat);\n    cv::eigen2cv(left.ground_truth, left_ground_mat);\n    cv::Mat left_rgb_mat = convertRgbToOpenCV(left_rgb_pixels);\n\n    cv::Mat right_gray_mat, right_ground_mat;\n    cv::eigen2cv(right_gray_pixels, right_gray_mat);\n    cv::eigen2cv(right.ground_truth, right_ground_mat);\n    cv::Mat right_rgb_mat = convertRgbToOpenCV(right_rgb_pixels);\n    cv::Mat left_intrinsics_mat, right_intrinsics_mat, R_mat, T_mat;\n\n    cv::eigen2cv(left.intrinsics,left_intrinsics_mat);\n    cv::eigen2cv(right.intrinsics,right_intrinsics_mat);\n\n    cv::eigen2cv(R,R_mat);\n    cv::eigen2cv(T,T_mat);\n\n\tR_mat.assignTo(R_mat, CV_64F);\n\tT_mat.assignTo(T_mat, CV_64F);\n\n    cv::Size imageSize = left_gray_mat.size();\n\tcv::Size targetSize = imageSize; // (left_gray_mat.cols/4., left_gray_mat.rows/4.);\n    cv::Mat R1,R2,P1,P2,Q;\n    cv::stereoRectify(left_intrinsics_mat,{},right_intrinsics_mat,{},imageSize,R_mat,T_mat,R1,R2,P1,P2,Q,\n\t\t\tcv::CALIB_ZERO_DISPARITY,\n\t\t   \t1,targetSize,0,0);\n\n    cv::Mat map1, map2, left_gray_out, left_ground_out;\n    cv::initUndistortRectifyMap(left_intrinsics_mat,{},R1,P1,targetSize,CV_32FC1,map1,map2);\n    cv::remap(left_gray_mat, left_gray_out, map1, map2, cv::INTER_NEAREST, cv::BORDER_CONSTANT);\n    cv::remap(left_ground_mat, left_ground_out, map1, map2, cv::INTER_NEAREST, cv::BORDER_CONSTANT);\n\tleft_gray_mat = left_gray_out;\n\tremap_rgb(left_rgb_mat, map1, map2);\n\n    cv::Mat map3,map4, right_gray_out, right_ground_out;\n    cv::initUndistortRectifyMap(right_intrinsics_mat,{},R2,P2,targetSize,CV_32FC1,map3,map4);\n    cv::remap(right_gray_mat, right_gray_out, map3, map4, cv::INTER_NEAREST, cv::BORDER_CONSTANT);\n    cv::remap(right_ground_mat, right_ground_out, map3, map3, cv::INTER_NEAREST, cv::BORDER_CONSTANT);\n\tright_gray_mat = right_gray_out;\n\tremap_rgb(right_rgb_mat, map3, map4);\n\n\tstd::cout << \"Debugging rectification results\\n\";\n\tstd::cout << \"R1 \" << R1 << \"\\nR2 \" << R2 << \"\\nP1 \" << P1 << \"\\nP2\" << P2 << \"\\nQ \" << Q << std::endl;\n\n#if !MVIEW_NDEBUG\n\tstd::stringstream debug_name;\n\tstd::string debug_left = ((debug_name << \"debug.rectified\" << debug_count << \".left.png\"), debug_name.str()); debug_name.str(\"\");\n\tstd::string debug_right = ((debug_name << \"debug.rectified\" << debug_count << \".right.png\"), debug_name.str()); debug_name.str(\"\");\n\tstd::string debug_depth = ((debug_name << \"debug.rectified\" << debug_count << \".depth.png\"), debug_name.str()); debug_name.str(\"\");\n\tdebug_count++;\n\n\tcv::imwrite(debug_left, left_gray_mat*255.);\n\tcv::imwrite(debug_right, right_gray_mat*255.);\n\tcv::imwrite(debug_depth, left_ground_out*25.);\n#endif\n\n\tRectified rectified;\n\n    //convert mat to eigen matrix\n\trectified.pixel_left_gray = GrayImage(left_gray_mat.rows, left_gray_mat.cols);\n\trectified.left_ground_truth = GrayImage(left_gray_mat.rows, left_gray_mat.cols);\n    cv::cv2eigen(left_gray_mat, rectified.pixel_left_gray);\n    cv::cv2eigen(left_ground_out, rectified.left_ground_truth);\n\trectified.pixel_left_rgb = convertOpenCVToRgb(left_rgb_mat);\n\n\trectified.pixel_right_gray = GrayImage (right_gray_mat.rows, right_gray_mat.cols);\n\trectified.right_ground_truth = GrayImage(right_gray_mat.rows, right_gray_mat.cols);\n    cv::cv2eigen(right_gray_mat, rectified.pixel_right_gray);\n    cv::cv2eigen(right_ground_out, rectified.right_ground_truth);\n\trectified.pixel_right_rgb = convertOpenCVToRgb(right_rgb_mat);\n\n\trectified.extrinsics_left = left.extrinsics;\n\trectified.extrinsics_right = right.extrinsics;\n\n\trectified.R1 = R1;\n\trectified.R2 = R2;\n\trectified.P1 = P1;\n\trectified.P2 = P2;\n\trectified.Q = Q;\n\n    return rectified;\n}\n\n", "meta": {"hexsha": "a74db5d4ed8571d4461075eaa57ee1ec67486242", "size": 5951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rectify.cpp", "max_stars_repo_name": "temple-reconstruction/mview", "max_stars_repo_head_hexsha": "1440b5716d595c5c4d568fc45dd5afbb6f54dfc7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-17T07:39:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-24T21:09:27.000Z", "max_issues_repo_path": "rectify.cpp", "max_issues_repo_name": "temple-reconstruction/mview", "max_issues_repo_head_hexsha": "1440b5716d595c5c4d568fc45dd5afbb6f54dfc7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-11T19:25:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-11T21:51:32.000Z", "max_forks_repo_path": "rectify.cpp", "max_forks_repo_name": "temple-reconstruction/mview", "max_forks_repo_head_hexsha": "1440b5716d595c5c4d568fc45dd5afbb6f54dfc7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2130177515, "max_line_length": 132, "alphanum_fraction": 0.707444127, "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5851011542032313, "lm_q1q2_score": 0.4185954056775979}}
{"text": "// implements the solver class - Felipe Figueredo Rocha \n#ifndef _solver_hpp\n#define _solver_hpp\n\n#include <iostream>\n#include <iomanip>\n#include <string>\n#include <fstream>\n#include <vector>\n#include <stdlib.h>  \n#include <sstream>\n#include <cmath>\n#include \"utils.hpp\"\n#include \"linAlg.hpp\"\n#include \"data.hpp\"\n#include \"simulSettings.hpp\"\n#include \"solvergp.h\"\n#include <armadillo>\n\n//~ #define DEBUG if(false)\n#define DEBUG if(true)\n\nusing namespace arma;\nusing namespace std;\n\nclass Solver{\n\tpublic:\n\t// see constructor for further explanation about the variabls\n\tData *d;\n\tSimulSettings *s;\n\tmat *A; // stiffness matrix\n\tvec *b; // force vector\n\tvec *Sol; // force vector\n\tvector<intVec*> *Coupling; // Coupling vector, works similar to flagDirich\n\tSolver() {}\n\tvoid init();\n\tvoid prepareMatrices(); // alloc linear system matrices and vector\n\tvoid createCoupling(); \n\tvoid linsolve(); // call the routine of solving the lin System\n\tvoid enforceDirichlet(SGPrealVec *vDirich, intVec *flagDirich, double pen); // modify matrices to enforce Dirichlet\n\tvoid assembly(SGPrealMat *A_L, SGPrealVec *b_L, int e); // assembly local in global matrices\n\tvoid assemblyCoupling(intVec *Cvec, intMat *Cmat_L, int e);\n\tvoid globalToLocal(SGPrealVec *XLL,SGPrealVec *Sol0E, SGPrealVec *Sol1E,SGPrealVec *ParamE, int e); // fills the e^{th} of the mesh in a auxiliary object\n\tvoid localToGlobal(SGPrealVec *ParamE,int e); // fills the e^{th} of the mesh in a auxiliary object\n\tvoid run();\n};\n\nvoid Solver:: init(){\n\ts = new SimulSettings;\n\ts->loadSettings();\n\td = new Data;\n\td->loadSGPmesh();\n\td->loadSGPdirich(s->NSubsteps);\n\td->loadSGPinifile();\n\td->loadSGPparam();\n\tprepareMatrices();\n\tcreateCoupling();\n}\n\nvoid Solver:: prepareMatrices(){\n\tint n = d->Ndof*d->Nnodes;\n\n \tA = new mat(n,n);\n\tb = new vec(n);\n\tSol = new vec(n);\n\n}\n\nvoid Solver:: createCoupling(){\n\tint n = d->Ndof*d->Nnodes;\n\tint NodElt = d->eNNod->max();\n\tint MaxLRows = NodElt*d->Ndof;\n\tintMat *CouplingE = new intMat(MaxLRows,MaxLRows);\n\tElemGroup elG;\n\t\n\tCoupling = new vector<intVec*>(s->NSubsteps); \n\tfor(int i=0; i<s->NSubsteps; i++) Coupling->at(i) = new intVec(n);\n\n\tfor(int k = 0; k< s->NSubsteps; k++){\t\t\n\t\t\n\t\tfor(int e=0; e< d->Nelem; e++){\t\n\t\t\tint iGroup = (*d->eType)(e);\n\t\t\t\n\t\t\telG = s->substeps->at(k).elGroup->at(iGroup);\n\t\t\t\n\t\t\t(*CouplingE)=0;\n\t\t\t\n\t\t\tif(elG.FlagElemLib<0){\n\t\t\t\tgetLocalSymbolic(&elG.ElemLib, CouplingE->v, elG.CommonPar->v,&d->Ndof, &d->Ndim, &MaxLRows);\n\t\t\t}\n\t\t\t\n\t\t\tassemblyCoupling(Coupling->at(k),CouplingE,e);\n\t\t}\n\t\t\n\t\tfor(int i=0; i<n; i++) (*Coupling->at(k))(i) = (*Coupling->at(k))(i) - 1; \n\t}\n}\n\nvoid Solver:: linsolve(){\n\tsolve(*Sol,*A,*b);\n}\n\t \nvoid Solver :: enforceDirichlet(SGPrealVec *vDirich, intVec *flagDirich, double pen = 99999.9){\n\n\tfor(int i = 0 ; i<b->size(); i++){\n\t\tif((*flagDirich)(i)==-1){\n\t\t\t(*b)(i) = pen*(*vDirich)(i);\n\t\t\t(*A)(i,i) = pen*1.0;\n\t\t\tfor(int j = 0 ; j<b->size(); j++){ if(j!=i) (*A)(i,j) = 0.0;}\n\t\t}\n\t}\n}\n//~ \nvoid Solver :: assembly(SGPrealMat *A_L, SGPrealVec *b_L, int e){\n\t\n\tint ip,jp,kip,kjp;\n\t\n\tint iShiftElem = (*d->eNNod_acc)(e);\n\t\n\tfor(int i=0; i<(*d->eNNod)(e); i++){ for(int ii=0; ii<d->Ndof; ii++){\n\t\tip = i*d->Ndof + ii;\n\t\tkip = (*d->Elem)(iShiftElem + i)*d->Ndof + ii;\n\t\t(*b)(kip) += (*b_L)(ip);\n\t\tfor(int j=0; j<(*d->eNNod)(e); j++){ for(int jj=0; jj<d->Ndof; jj++){\n\t\t\tjp = j*d->Ndof + jj;\n\t\t\tkjp = (*d->Elem)(iShiftElem + j)*d->Ndof + jj;\n\t\t\t(*A)(kip,kjp) += (*A_L)(ip,jp);\t\t\t\n\t\t}\n\t\t}\n\t}\n\t}\n}\n\nvoid Solver :: assemblyCoupling(intVec *Cvec, intMat *Cmat_L, int e){\n\t\n\tint ip,kip;\n\tint iShiftElem = (*d->eNNod_acc)(e);\n\t\n\tfor(int i=0; i<(*d->eNNod)(e); i++){ for(int ii=0; ii<d->Ndof; ii++){\n\t\tip = i*d->Ndof + ii;\n\t\tkip = (*d->Elem)(iShiftElem + i)*d->Ndof + ii;\n\t\tif((*Cmat_L)(ip,ip) == 1){\n\t\t\t(*Cvec)(kip) = 1;\n\t\t}\n\t}\n\t}\n}\n\nvoid Solver :: globalToLocal(SGPrealVec *XLL,SGPrealVec *Sol0E, SGPrealVec *Sol1E, SGPrealVec *ParamE, int e){\n\t\tint ipDim,kpDim,ipDof,kpDof;\n\t\tint iShiftElem = (*d->eNNod_acc)(e);\n\t\tint iShiftMat = (*d->eMat)(e);\n\t\tint iShiftParam = (*d->eParamSize_acc)(iShiftMat);\n\t\n\t\t(*XLL) = 0.0;\n\t\t(*Sol0E) = 0.0;\n\t\t(*Sol1E) = 0.0;\n\t\t(*ParamE) = 0.0;\n\t\t \n\t\tfor(int i=0;i<(*d->eNNod)(e);i++){\n\t\t\tipDim = i*d->Ndim;\n\t\t\tkpDim = (*d->Elem)(iShiftElem + i)*d->Ndim;\n\t\t\tipDof = i*d->Ndof;\n\t\t\tkpDof = (*d->Elem)(iShiftElem + i)*d->Ndof;\n\t\t\t\t\t\n\t\t\tfor(int j=0 ; j<d->Ndim; j++) (*XLL)(ipDim + j) = (*d->X)(kpDim +j);\n\t\t\t\n\t\t\tfor(int j=0 ; j<d->Ndof; j++){\n\t\t\t\t(*Sol0E)(ipDof + j) = (*d->Sol0)(kpDof + j);\n\t\t\t\t(*Sol1E)(ipDof + j) = (*d->Sol1)(kpDof + j);\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor(int k=0; k<(*d->eParamSize)(iShiftMat) ; k++) (*ParamE)(k) = (*d->Param)(iShiftParam + k);\n\t\t\n}\n\nvoid Solver :: localToGlobal(SGPrealVec *ParamE, int e){\n\t\tint iShiftMat = (*d->eMat)(e);\n\t\tint iShiftParam = (*d->eParamSize_acc)(iShiftMat);\n\t\t\t \t\n\t\tfor(int k=0; k<(*d->eParamSize)(iShiftMat) ; k++) (*d->Param)(iShiftParam + k) = (*ParamE)(k);\n}\n\nvoid Solver :: run(){\n\tint timeStep, iGroup;\n\tint id_Elem_Family, MaxLRows, iDofT, NodElt;\n\tintVec *JParam;\n\tdouble DTm, Time;\n\tSGPrealVec *BE, *XLL, *Sol0E, *Sol1E, *CommonParE, *ParamE;\n\tSGPrealMat *AE; \n\tElemGroup elG;\n\tdouble error, tol, emax = 99999.0;\n\tint itNL, maxit;\n\tbool isNL;\n\t\n\tNodElt = d->eNNod->max();\n\tMaxLRows = NodElt*d->Ndof;\n\n\tAE = new SGPrealMat(MaxLRows,MaxLRows);\n\tBE = new SGPrealVec(MaxLRows);\n\tXLL = new SGPrealVec(NodElt*d->Ndim);\n\tSol0E = new SGPrealVec(MaxLRows);\n\tSol1E = new SGPrealVec(MaxLRows);\n\tParamE = new SGPrealVec(d->eParamSize->max()); \n\tJParam = new intVec(3); // temporary\n\t\n\tTime = s->Tini; \n\tDTm = s->DelT; \t\n\ttimeStep = 0;\n\t\n\td->writeSGPdataout(timeStep,Time,DTm);\n\t\n\twhile(Time < s->Tmax){\n\t\tDEBUG{cout << \"=> Beginning Timestep = \" << timeStep << \", time = \" << Time << \"  =====\\n \" << endl;}\n\t\t\n\t\tfor(int k = 0; k< s->NSubsteps; k++){\n\t\t\t\n\t\t\terror = emax;\n\t\t\titNL = 0;\n\t\t\tisNL = s->substeps->at(k).isNL;\n\t\t\tif(isNL){\n\t\t\t\tmaxit = s->substeps->at(k).maxit;\n\t\t\t\ttol = s->substeps->at(k).tol;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmaxit = 1; // force to stop with just one iteration\n\t\t\t\ttol = 0.0;\n\t\t\t}\n\t\t\t\n\t\t\tDEBUG{cout << \"===> Beginning SubStep = \" << k << \" ===========\" << endl;}\n\t\t\t\n\t\t\tDEBUG{if(isNL) cout << \"===> Starting NonLinear Convergence, tol = \" << tol << endl;}\n\t\t\twhile(error>tol && itNL<maxit){\n\t\t\t\t\n\t\t\t\tDEBUG{if(isNL) cout << \"===> Starting NonLinear Internal Loop, it = \" << itNL << \" =======\" << endl;} \n\t\t\t\n\t\t\t\tA->fill(0.0);\n\t\t\t\tb->fill(0.0);\n\t\t\t\t\t\n\t\t\t\t//~ cout << \"=====> Assemblying Global Matrices ================ \" << endl;\n\t\t\t\tfor(int e=0; e< d->Nelem; e++){\n\t\t\t\t\t\n\t\t\t\t\tglobalToLocal(XLL,Sol0E,Sol1E,ParamE,e);\n\t\t\t\t\t\n\t\t\t\t\tiGroup = (*d->eType)(e);\n\t\t\t\t\t\n\t\t\t\t\telG = s->substeps->at(k).elGroup->at(iGroup);\n\t\t\t\t\t\n\t\t\t\t\t(*AE)=0.0;\n\t\t\t\t\t(*BE)=0.0;\n\t\t\t\t\t\n\t\t\t\t\tif(elG.FlagElemLib<0){\n\t\t\t\t\t\tgetLocalMatrix(&elG.ElemLib, AE->v, BE->v, &MaxLRows, XLL->v, &d->Ndim, &d->Ndof, &NodElt, Sol0E->v, Sol1E->v, \n\t\t\t\t\t\t\t\t\t\telG.CommonPar->v, ParamE->v, JParam->v, &s->DelT, &DTm, &Time);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tassembly(AE,BE,e);\n\t\t\t\t\t\n\t\t\t\t\tlocalToGlobal(ParamE,e);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tDEBUG{cout << \"=====> Solving Linear System ================ \" << endl;}\n\t\t\t\tenforceDirichlet( d->vDirich->at(k), d->flagDirich->at(k) , 1.0);\n\t\t\t\tenforceDirichlet( d->Sol1, Coupling->at(k) , 1.0);\n\t\t\t\t\t\n\t\t\t\tlinsolve();\n\t\t\t\tif(isNL){\n\t\t\t\t\terror = computeError(*Sol,*d->Sol1);\n\t\t\t\t\tDEBUG{cout << \"====> Ending NonLinear Internal Loop , it= \" << itNL << \" , error= \" << error << \" ==========\"<< endl;}\t\n\t\t\t\t} \n\t\t\t\t\n\t\t\t\titNL ++;\n\t\t\t\t*d->Sol1 = *Sol; // uses the operator overloading\n\t\t\t}\n\t\t\tDEBUG{if(isNL) cout << \"====> Convergence Achieved with it= \" << itNL-1 << \" , error= \" << error << \" ==========\"<< endl;}\n\t\t\t\n\t\t\tDEBUG{cout << \"===> Ending SubStep = \" << k << \" =============== \\n \" << endl;}\n\t\t}\n\t\t\n\t\tDEBUG{cout << \"=> Ending Timestep = \" << timeStep << \", time = \" << Time << \" ===== \\n\" << endl;}\n\t\t\n\t\tTime += s->DelT;\n\t\ttimeStep++;\n\t\t\n\t\t*d->Sol0 = *d->Sol1; // uses the operator overloading\n\t\t\n\t\tDEBUG{cout << \"=> Writing Results in File ====== \\n\\n\" << endl;}\n\t\td->writeSGPdataout(timeStep,Time,DTm);\n\t\td->writeSGPparam();\n\t}\n}\n\n\n\n#endif\n", "meta": {"hexsha": "993b29d9245d760328c06c807fca7138d831c56b", "size": 8028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/solver.hpp", "max_stars_repo_name": "felipefr/Piola", "max_stars_repo_head_hexsha": "2189b0a4d214f99cd550ee780f0b439e0763825f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/solver.hpp", "max_issues_repo_name": "felipefr/Piola", "max_issues_repo_head_hexsha": "2189b0a4d214f99cd550ee780f0b439e0763825f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver.hpp", "max_forks_repo_name": "felipefr/Piola", "max_forks_repo_head_hexsha": "2189b0a4d214f99cd550ee780f0b439e0763825f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0303030303, "max_line_length": 154, "alphanum_fraction": 0.5777279522, "num_tokens": 2969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834734, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.41859540567759784}}
{"text": "/*\n\nCopyright (c) 2005-2020, University of Oxford.\nAll rights reserved.\n\nUniversity of Oxford means the Chancellor, Masters and Scholars of the\nUniversity of Oxford, having an administrative office at Wellington\nSquare, Oxford OX1 2JD, UK.\n\nThis file is part of Chaste.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\n * Neither the name of the University of Oxford nor the names of its\n   contributors may be used to endorse or promote products derived from this\n   software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\nGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*/\n\n#ifndef VOLUMEDEPENDENTAVERAGEDSOURCEELLIPTICPDE_HPP_\n#define VOLUMEDEPENDENTAVERAGEDSOURCEELLIPTICPDE_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n\n#include \"NodeBasedCellPopulation.hpp\"\n#include \"AveragedSourceEllipticPde.hpp\"\n#include \"TetrahedralMesh.hpp\"\n#include \"AbstractLinearEllipticPde.hpp\"\n\n/**\n * An elliptic PDE to be solved numerically using the finite element method, for\n * coupling to a cell-based simulation.\n *\n * This class inherits from AveragedSourceEllipticPde and may only be used with\n * a NodeBasedCellPopulation, since it assumes that each cell is associated with\n * a Node object.\n *\n * The PDE takes the form\n *\n * Grad.(D*Grad(u)) + k*u*rho(x) = 0,\n *\n * where the scalars D and k are specified by the members mDiffusionCoefficient and\n * mSourceCoefficient, respectively. Their values must be set in the constructor.\n *\n * The function rho(x) denotes the local density of non-apoptotic cells. This\n * quantity is computed for each element of a 'coarse' finite element mesh that is\n * passed to the method SetupSourceTerms() and stored in the member mCellDensityOnCoarseElements.\n *\n * For a point x, rho(x) is a weighted sum of the non-apoptotic cells whose centres\n * lie in each finite element containing that point, scaled by the area of that element.\n * The weighting assigned to each cell is given by the square of the radius of the\n * associated node, which is accessed using the GetRadius() method.\n *\n * \\todo Consider creating a VolumeDependentAveragedSourceParabolicPde class\n */\ntemplate<unsigned DIM>\nclass VolumeDependentAveragedSourceEllipticPde : public AveragedSourceEllipticPde<DIM>\n{\n    friend class TestCellBasedEllipticPdes;\n\nprivate:\n\n    /** Needed for serialization.*/\n    friend class boost::serialization::access;\n    /**\n     * Serialize the PDE and its member variables.\n     *\n     * @param archive the archive\n     * @param version the current version of this class\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n       archive & boost::serialization::base_object<AveragedSourceEllipticPde<DIM> >(*this);\n    }\n\n    /** Static cast of the NodeBasedCellPopulation. */\n    NodeBasedCellPopulation<DIM>* mpStaticCastCellPopulation;\n\npublic:\n\n    /**\n     * Constructor.\n     *\n     * @param rCellPopulation reference to the cell population\n     * @param coefficient the coefficient of consumption of nutrient by cells (defaults to 0.0)\n     */\n    VolumeDependentAveragedSourceEllipticPde(AbstractCellPopulation<DIM>& rCellPopulation, double coefficient=0.0);\n\n    /**\n     * Set up the source terms.\n     *\n     * @param rCoarseMesh reference to the coarse mesh\n     * @param pCellPdeElementMap optional pointer to the map from cells to coarse elements\n     */\n    void SetupSourceTerms(TetrahedralMesh<DIM,DIM>& rCoarseMesh, std::map<CellPtr, unsigned>* pCellPdeElementMap=nullptr);\n};\n\n#include \"SerializationExportWrapper.hpp\"\nEXPORT_TEMPLATE_CLASS_SAME_DIMS(VolumeDependentAveragedSourceEllipticPde)\n\nnamespace boost\n{\nnamespace serialization\n{\n/**\n * Serialize information required to construct a VolumeDependentAveragedSourceEllipticPde.\n */\ntemplate<class Archive, unsigned DIM>\ninline void save_construct_data(\n    Archive & ar, const VolumeDependentAveragedSourceEllipticPde<DIM>* t, const unsigned int file_version)\n{\n    // Save data required to construct instance\n    const AbstractCellPopulation<DIM>* p_cell_population = &(t->rGetCellPopulation());\n    ar & p_cell_population;\n}\n\n/**\n * De-serialize constructor parameters and initialise a VolumeDependentAveragedSourceEllipticPde.\n */\ntemplate<class Archive, unsigned DIM>\ninline void load_construct_data(\n    Archive & ar, VolumeDependentAveragedSourceEllipticPde<DIM>* t, const unsigned int file_version)\n{\n    // Retrieve data from archive required to construct new instance\n    AbstractCellPopulation<DIM>* p_cell_population;\n    ar >> p_cell_population;\n\n    // Invoke inplace constructor to initialise instance\n    ::new(t)VolumeDependentAveragedSourceEllipticPde<DIM>(*p_cell_population);\n}\n}\n} // namespace ...\n\n#endif /*VOLUMEDEPENDENTAVERAGEDSOURCEELLIPTICPDE_HPP_*/\n", "meta": {"hexsha": "d5783e974dd1127e6ea3d95767eb6f5f13e3f550", "size": 5925, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cell_based/src/cell_based_pde/pdes/VolumeDependentAveragedSourceEllipticPde.hpp", "max_stars_repo_name": "SoftMatterMechanics/ApicalStressFibers", "max_stars_repo_head_hexsha": "17d343c09a246a50f9e3a3cbfc399ca6bef353ce", "max_stars_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T16:12:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-10T16:12:13.000Z", "max_issues_repo_path": "cell_based/src/cell_based_pde/pdes/VolumeDependentAveragedSourceEllipticPde.hpp", "max_issues_repo_name": "SoftMatterMechanics/ApicalStressFibers", "max_issues_repo_head_hexsha": "17d343c09a246a50f9e3a3cbfc399ca6bef353ce", "max_issues_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cell_based/src/cell_based_pde/pdes/VolumeDependentAveragedSourceEllipticPde.hpp", "max_forks_repo_name": "SoftMatterMechanics/ApicalStressFibers", "max_forks_repo_head_hexsha": "17d343c09a246a50f9e3a3cbfc399ca6bef353ce", "max_forks_repo_licenses": ["Apache-2.0", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T16:12:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-10T16:12:21.000Z", "avg_line_length": 38.7254901961, "max_line_length": 122, "alphanum_fraction": 0.7746835443, "num_tokens": 1346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4185954056775978}}
{"text": "/*\n * s2slayer.cpp\n *\n * Feed-forward:\n *    z(l) = a(l-1) * w + b // where * (vector, matrix) multiplication\n *    a(l) = activation(z(l))\n *\n * Back propagation:\n *    delta(l) = elem_prod(gradient(C, a(l)), activation_derivative(z(l)))\n *    dC/db(l) = delta(l)\n *    dC/dw(l) = a(l-1) * delta(l)\n *    gradient(C, a(l - 1)) = transp(w) * delta(l)\n */\n#include <boost/assert.hpp>\n\n#include \"core/utils.h\"\n#include \"core/random.h\"\n#include \"core/functions.h\"\n#include \"lstmlayer.h\"\n#include \"s2slayer.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace yann;\n\n\nnamespace yann {\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// Seq2SeqLayer_Context implementation\n//\nclass Seq2SeqLayer_Context :\n    public Layer::Context\n{\n  typedef Layer::Context Base;\n\n  friend class Seq2SeqLayer;\n\npublic:\n  Seq2SeqLayer_Context(\n      unique_ptr<Layer::Context> encoder_ctx,\n      unique_ptr<Layer::Context> decoder_ctx) :\n    Base(decoder_ctx->get_output()) // decoder output is our output\n  {\n    YANN_CHECK(encoder_ctx);\n    YANN_CHECK(decoder_ctx);\n    _encoder_ctx = std::move(encoder_ctx);\n    _decoder_ctx = std::move(decoder_ctx);\n  }\n\n  inline bool is_valid() const\n  {\n    return _encoder_ctx && _decoder_ctx;\n  }\n\n  // Layer::Context overwrites\n  virtual void start_epoch()\n  {\n    YANN_CHECK(is_valid());\n\n    Base::start_epoch();\n\n    _encoder_ctx->start_epoch();\n    _decoder_ctx->start_epoch();\n  }\n\n  virtual void reset_state()\n  {\n    YANN_CHECK(is_valid());\n\n    Base::reset_state();\n\n    _encoder_ctx->reset_state();\n    _decoder_ctx->reset_state();\n  }\nprotected:\n  unique_ptr<Layer::Context> _encoder_ctx;\n  unique_ptr<Layer::Context> _decoder_ctx;\n}; // class Seq2SeqLayer_Context\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// Seq2SeqLayer_TrainingContext implementation\n//\nclass Seq2SeqLayer_TrainingContext :\n    public Seq2SeqLayer_Context\n{\n  typedef Seq2SeqLayer_Context Base;\n  friend class Seq2SeqLayer;\n\npublic:\n  Seq2SeqLayer_TrainingContext(\n      unique_ptr<Layer::Context> encoder_ctx,\n      unique_ptr<Layer::Context> decoder_ctx) :\n    Base(std::move(encoder_ctx), std::move(decoder_ctx))\n  {\n    _decoder_input_gradient.resize(_decoder_ctx->get_output_size());\n    _decoder_output_gradient.resize(_decoder_ctx->get_output_size());\n  }\n\nprotected:\n  Vector _decoder_input_gradient;\n  Vector _decoder_output_gradient;\n}; // class Seq2SeqLayer_TrainingContext\n\n}; // namespace yann\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// yann::Seq2SeqLayer implementation\n//\nstd::unique_ptr<Seq2SeqLayer> yann::Seq2SeqLayer::create_lstm(\n      const MatrixSize & input_size,\n      const MatrixSize & output_size,\n      const std::unique_ptr<ActivationFunction> & gate_activation_function,\n      const std::unique_ptr<ActivationFunction> & io_activation_function)\n{\n  YANN_CHECK_GT(input_size, 0);\n  YANN_CHECK_GT(output_size, 0);\n  YANN_CHECK(gate_activation_function);\n  YANN_CHECK(io_activation_function);\n\n  auto encoder = make_unique<LstmLayer>(input_size, output_size);\n  YANN_CHECK(encoder);\n  encoder->set_activation_functions(gate_activation_function, io_activation_function);\n\n  auto decoder = make_unique<LstmLayer>(output_size, output_size);\n  YANN_CHECK(decoder);\n  decoder->set_activation_functions(gate_activation_function, io_activation_function);\n\n  return make_unique<Seq2SeqLayer>(std::move(encoder), std::move(decoder));\n}\n\nstd::unique_ptr<Seq2SeqLayer> yann::Seq2SeqLayer::create_lstm(\n    const MatrixSize & input_size,\n    const MatrixSize & output_size,\n    const std::unique_ptr<ActivationFunction> & activation_function)\n{\n  YANN_CHECK(activation_function);\n  return create_lstm(input_size, output_size, activation_function, activation_function);\n}\n\n\nyann::Seq2SeqLayer::Seq2SeqLayer(std::unique_ptr<Layer> encoder, std::unique_ptr<Layer> decoder) :\n    _encoder(std::move(encoder)),\n    _decoder(std::move(decoder))\n{\n  YANN_CHECK_EQ(_encoder->get_output_size(), _decoder->get_input_size());\n}\n\nyann::Seq2SeqLayer::~Seq2SeqLayer()\n{\n}\n\n// Layer overwrites\nbool yann::Seq2SeqLayer::is_valid() const\n{\n  if(!Base::is_valid()) {\n    return false;\n  }\n  if(!_encoder || !_encoder->is_valid()) {\n    return false;\n  }\n  if(!_decoder || !_decoder->is_valid()) {\n    return false;\n  }\n  return true;\n}\n\nstd::string yann::Seq2SeqLayer::get_name() const\n{\n  return \"Seq2SeqLayer\";\n}\n\nstring yann::Seq2SeqLayer::get_info() const\n{\n  YANN_CHECK(is_valid());\n\n  ostringstream oss;\n  oss << Base::get_info()\n      << \" encoder: \" << _encoder->get_info()\n      << \", decoder: \" << _decoder->get_info()\n  ;\n  return oss.str();\n}\n\nbool yann::Seq2SeqLayer::is_equal(const Layer & other, double tolerance) const\n{\n  if(!Base::is_equal(other, tolerance)) {\n    return false;\n  }\n  auto the_other = dynamic_cast<const Seq2SeqLayer*>(&other);\n  if(the_other == nullptr) {\n    return false;\n  }\n  if(is_valid() != the_other->is_valid()) {\n    return false;\n  }\n  if(_encoder && !_encoder->is_equal(*the_other->_encoder, tolerance)) {\n    return false;\n  }\n  if(_decoder && !_decoder->is_equal(*the_other->_decoder, tolerance)) {\n    return false;\n  }\n  return true;\n}\n\nMatrixSize yann::Seq2SeqLayer::get_input_size() const\n{\n  return _encoder ? _encoder->get_input_size() : 0;\n}\n\nMatrixSize yann::Seq2SeqLayer::get_output_size() const\n{\n  return _decoder ? _decoder->get_output_size() : 0;\n}\n\nunique_ptr<Layer::Context> yann::Seq2SeqLayer::create_context(const MatrixSize & batch_size) const\n{\n  YANN_CHECK(is_valid());\n\n  auto encoder_ctx = _encoder->create_context(batch_size);\n  YANN_CHECK(encoder_ctx);\n  auto decoder_ctx = _decoder->create_context(batch_size);\n  YANN_CHECK(decoder_ctx);\n\n  return make_unique<Seq2SeqLayer_Context>(std::move(encoder_ctx), std::move(decoder_ctx));\n}\nunique_ptr<Layer::Context> yann::Seq2SeqLayer::create_context(const RefVectorBatch & output) const\n{\n  YANN_CHECK(is_valid());\n\n  auto encoder_ctx = _encoder->create_context(get_batch_size(output));\n  YANN_CHECK(encoder_ctx);\n  auto decoder_ctx = _decoder->create_context(output); // decoder output is our output\n  YANN_CHECK(decoder_ctx);\n\n  return make_unique<Seq2SeqLayer_Context>(std::move(encoder_ctx), std::move(decoder_ctx));\n}\nunique_ptr<Layer::Context> yann::Seq2SeqLayer::create_training_context(\n    const MatrixSize & batch_size, const std::unique_ptr<Layer::Updater> & updater) const\n{\n  YANN_CHECK(is_valid());\n  YANN_CHECK(updater);\n\n  auto encoder_ctx = _encoder->create_training_context(batch_size, updater);\n  YANN_CHECK(encoder_ctx);\n  auto decoder_ctx = _decoder->create_training_context(batch_size, updater);\n  YANN_CHECK(decoder_ctx);\n\n  return make_unique<Seq2SeqLayer_TrainingContext>(std::move(encoder_ctx), std::move(decoder_ctx));\n}\nunique_ptr<Layer::Context> yann::Seq2SeqLayer::create_training_context(\n    const RefVectorBatch & output, const std::unique_ptr<Layer::Updater> & updater) const\n{\n  YANN_CHECK(is_valid());\n  YANN_CHECK(updater);\n\n  auto encoder_ctx = _encoder->create_training_context(get_batch_size(output), updater);\n  YANN_CHECK(encoder_ctx);\n  auto decoder_ctx = _decoder->create_training_context(output, updater); // decoder output is our output\n  YANN_CHECK(decoder_ctx);\n\n  return make_unique<Seq2SeqLayer_TrainingContext>(std::move(encoder_ctx), std::move(decoder_ctx));\n}\n\ntemplate<typename InputType>\nvoid yann::Seq2SeqLayer::feedforward_internal(\n    const InputType & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  auto ctx = dynamic_cast<Seq2SeqLayer_Context *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(ctx->is_valid());\n  YANN_CHECK(is_valid());\n\n  YANN_CHECK_LT(0, get_batch_size(input));\n  YANN_CHECK_LE(get_batch_size(input), get_batch_size(ctx->get_output()));\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n\n  //\n  // we assume all input is given to us \"at once\" no incremental feedforward\n  //\n  auto & encoder_ctx = ctx->_encoder_ctx;\n  auto & decoder_ctx = ctx->_decoder_ctx;\n\n  // feed input into encoder, overwrite the output\n  _encoder->feedforward(input, encoder_ctx.get(), Operation_Assign);\n  auto encoder_output_size = get_batch_size(encoder_ctx->get_output());\n  YANN_SLOW_CHECK_GT(encoder_output_size, 0);\n  auto state = get_batch(encoder_ctx->get_output(), encoder_output_size - 1); // last output\n\n  // feed state into decoder and then feed prev output\n  YANN_CHECK_EQ(mode, Operation_Assign); // we don't support anything else because we re-use output buffer\n  for(MatrixSize ii = 0; ii < ctx->get_batch_size(); ++ii) {\n    if(ii > 0) {\n      auto prev_output = get_batch(decoder_ctx->get_output(), ii - 1);\n      _decoder->feedforward(prev_output, decoder_ctx.get(), Operation_Assign);\n    } else {\n      _decoder->feedforward(state, decoder_ctx.get(), Operation_Assign);\n    }\n  }\n}\n\nvoid yann::Seq2SeqLayer::feedforward(\n    const RefConstVectorBatch & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  feedforward_internal(input, context, mode);\n}\n\nvoid yann::Seq2SeqLayer::feedforward(\n    const RefConstSparseVectorBatch & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  feedforward_internal(input, context, mode);\n}\n\ntemplate<typename InputType>\nvoid yann::Seq2SeqLayer::backprop_internal(\n    const RefConstVectorBatch & gradient_output,\n    const InputType & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  auto ctx = dynamic_cast<Seq2SeqLayer_TrainingContext *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(ctx->is_valid());\n  YANN_CHECK(is_valid());\n  YANN_CHECK_GT(get_batch_size(gradient_output), 0);\n  YANN_CHECK_EQ(get_batch_item_size(gradient_output), get_output_size());\n  YANN_CHECK_EQ(get_batch_size(input), get_batch_size(gradient_output));\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_CHECK(!gradient_input || is_same_size(input, *gradient_input));\n\n  //\n  // we assume all output is given to us \"at once\" no incremental backprop\n  //\n  auto & encoder_ctx = ctx->_encoder_ctx;\n  YANN_SLOW_CHECK(encoder_ctx);\n  auto & decoder_ctx = ctx->_decoder_ctx;\n  YANN_SLOW_CHECK(decoder_ctx);\n\n  auto encoder_output_size = get_batch_size(encoder_ctx->get_output());\n  YANN_SLOW_CHECK_GT(encoder_output_size, 0);\n  auto state = get_batch(encoder_ctx->get_output(), encoder_output_size - 1); // last output\n\n  // first we propagate back the output for decoder\n  auto & decoder_input_gradient = ctx->_decoder_input_gradient;\n  auto & decoder_output_gradient = ctx->_decoder_output_gradient;\n  YANN_SLOW_CHECK(is_same_size(decoder_input_gradient, decoder_output_gradient));\n\n  decoder_input_gradient.setZero();\n  decoder_output_gradient.setZero();\n\n  const auto batch_size = get_batch_size(gradient_output);\n  for(MatrixSize ii = batch_size - 1; ii >= 0; --ii) {\n    decoder_output_gradient += get_batch(gradient_output, ii);\n    if(ii > 0) {\n      auto decoder_prev_output = get_batch(decoder_ctx->get_output(), ii - 1);\n      _decoder->backprop(\n          decoder_output_gradient, // gradient_output\n          decoder_prev_output,     // input\n          make_optional<RefVectorBatch>(decoder_input_gradient),  // gradient_input\n          decoder_ctx.get());\n      swap(decoder_input_gradient, decoder_output_gradient);\n    } else {\n      _decoder->backprop(\n          decoder_output_gradient, // gradient_output\n          state,                   // input\n          make_optional<RefVectorBatch>(decoder_input_gradient),  // gradient_input\n          decoder_ctx.get());\n    }\n    // decoder_input_gradient contains the state gradient\n  }\n\n  // now propagate the gradient for encoder\n  decoder_output_gradient.setZero();\n  for(MatrixSize ii = batch_size - 1; ii >= 0; --ii) {\n    auto gradient_in = gradient_input ? make_optional<RefVectorBatch>(get_batch(*gradient_input, ii)) : boost::none;\n    InputType in = input.block(ii, 0, 1, input.cols()); // TODO: RowMajor, switch to get_batch()\n\n    _encoder->backprop(\n        decoder_input_gradient, // gradient_output\n        in,   // input\n        gradient_in,            // gradient_input\n        encoder_ctx.get());\n    if(ii == batch_size - 1) {\n      decoder_input_gradient.setZero(); // we don't care about encoder output except the last vector\n    }\n  }\n}\n\nvoid yann::Seq2SeqLayer::backprop(\n    const RefConstVectorBatch & gradient_output,\n    const RefConstVectorBatch & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n backprop_internal(gradient_output, input, gradient_input, context);\n}\n\nvoid yann::Seq2SeqLayer::backprop(\n    const RefConstVectorBatch & gradient_output,\n    const RefConstSparseVectorBatch & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  backprop_internal<RefConstSparseVectorBatch>(gradient_output, input, gradient_input, context);\n}\n\nvoid yann::Seq2SeqLayer::init(enum InitMode mode, boost::optional<InitContext> init_context)\n{\n  YANN_CHECK(is_valid());\n  _encoder->init(mode, init_context);\n  _decoder->init(mode, init_context);\n}\n\nvoid yann::Seq2SeqLayer::update(Context * context, const size_t & tests_num)\n{\n  auto ctx = dynamic_cast<Seq2SeqLayer_TrainingContext *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(ctx->is_valid());\n  YANN_CHECK(is_valid());\n\n  _encoder->update(ctx->_encoder_ctx.get(), tests_num);\n  _decoder->update(ctx->_decoder_ctx.get(), tests_num);\n}\n\n// the format is (e:<encoder>,d:<decoder>)\nvoid yann::Seq2SeqLayer::read(std::istream & is)\n{\n  YANN_CHECK(is_valid());\n\n  Base::read(is);\n\n  read_char(is, '(');\n  read_object(is, \"e\", *_encoder);\n  read_char(is, ',');\n  read_object(is, \"d\", *_decoder);\n  read_char(is, ')');\n}\n\n// the format is (e:<encoder>,d:<decoder>)\nvoid yann::Seq2SeqLayer::write(std::ostream & os) const\n{\n  YANN_CHECK(is_valid());\n\n  Base::write(os);\n\n  os << \"(\";\n  write_object(os, \"e\", *_encoder);\n  os << \",\";\n  write_object(os, \"d\", *_decoder);\n  os << \")\";\n}\n\n", "meta": {"hexsha": "5bd1b18cf1c1814df41637102cf1993353b691b0", "size": 14044, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/layers/s2slayer.cpp", "max_stars_repo_name": "lsh123/yann", "max_stars_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:14:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T10:25:07.000Z", "max_issues_repo_path": "src/layers/s2slayer.cpp", "max_issues_repo_name": "lsh123/yann", "max_issues_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/layers/s2slayer.cpp", "max_forks_repo_name": "lsh123/yann", "max_forks_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3326133909, "max_line_length": 116, "alphanum_fraction": 0.7079179721, "num_tokens": 3505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.41857806988876284}}
{"text": "/*******************************************************************************\n * Copyright (c) 2018-, UT-Battelle, LLC.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the MIT License \n * which accompanies this distribution. \n *\n * Contributors:\n *   Alexander J. McCaskey - initial API and implementation\n *   Thien Nguyen - implementation\n *******************************************************************************/\n#include \"qcor_observable.hpp\"\n\n#include \"ObservableTransform.hpp\"\n#include \"xacc.hpp\"\n// #include \"xacc_quantum_gate_api.hpp\"\n#include <spdlog/fmt/fmt.h>\n#include <Eigen/Dense>\n\n#include <algorithm>\n#include <cassert>\n\n#include \"CompositeInstruction.hpp\"\n#include \"FermionOperator.hpp\"\n#include \"PauliOperator.hpp\"\n#include \"qalloc.hpp\"\n#include \"qcor_ir.hpp\"\n#include \"qcor_pimpl_impl.hpp\"\n#include \"xacc_internal_compiler.hpp\"\n#include \"xacc_quantum_gate_api.hpp\"\n#include \"xacc_service.hpp\"\n\nnamespace qcor {\n\n// ---------------- Operator ---------------------- //\n\n// Internal hidden implementation\nclass Operator::OperatorImpl\n    : public commutative_ring<OperatorImpl>,\n      public equality_comparable<OperatorImpl>,\n      public commutative_multipliable<OperatorImpl, double>,\n      public commutative_multipliable<OperatorImpl, std::complex<double>> {\n  friend class Operator;\n\n private:\n  enum operation { PlusEquals, MinusEqual, StarEqual };\n\n  // This function performs sub-class specific algebraic operation \n  // with another operator instance, or scalar value (double, complex)\n  template <typename T>\n  struct cast_and_apply {\n    void operator()(std::shared_ptr<xacc::Observable> obs, operation _op,\n                    const OperatorImpl &other) {\n      auto input_casted = std::dynamic_pointer_cast<T>(obs);\n      auto other_casted = std::dynamic_pointer_cast<T>(other.op);\n      assert(input_casted && other_casted &&\n             \"Invalid Operator sub-types for arithmetic operation.\");\n\n      switch (_op) {\n        case operation::PlusEquals:\n          input_casted->operator+=(*other_casted.get());\n          break;\n        case operation::MinusEqual:\n          input_casted->operator-=(*other_casted.get());\n          break;\n        case operation::StarEqual:\n          input_casted->operator*=(*other_casted.get());\n          break;\n        default:\n          std::cout << \"Invalid Selection\\n\";\n          exit(0);\n          break;\n      }\n    }\n\n    void operator()(std::shared_ptr<xacc::Observable> obs,\n                    const double &value) {\n      auto input_casted = std::dynamic_pointer_cast<T>(obs);\n      assert(input_casted &&\n             \"Invalid Operator sub-types for arithmetic operation.\");\n      input_casted->operator*=(value);\n    }\n\n    void operator()(std::shared_ptr<xacc::Observable> obs,\n                    const std::complex<double> &value) {\n      auto input_casted = std::dynamic_pointer_cast<T>(obs);\n      assert(input_casted &&\n             \"Invalid Operator sub-types for arithmetic operation.\");\n      input_casted->operator*=(value);\n    }\n  };\n\n  // Apply the desired operation between this operator an the given other operator\n  OperatorImpl &apply(const operation &_op, const OperatorImpl &other) {\n    if (type == \"pauli\") {\n      cast_and_apply<xacc::quantum::PauliOperator>()(op, _op, other);\n    } else if (type == \"fermion\") {\n      cast_and_apply<xacc::quantum::FermionOperator>()(op, _op, other);\n    } else {\n      // FIXME / TODO As we add more Operator types, update\n      // this if/else section\n      error(\"Invalid Operator type for the given algebraic operation.\");\n    }\n    return *this;\n  }\n\n  // Apply the desired operation between this operator an the given scalar double\n  OperatorImpl &apply(const double &d) {\n    if (type == \"pauli\") {\n      cast_and_apply<xacc::quantum::PauliOperator>()(op, d);\n    } else if (type == \"fermion\") {\n      cast_and_apply<xacc::quantum::FermionOperator>()(op, d);\n    } else {\n      // FIXME / TODO As we add more Operator types, update\n      // this if/else section\n      error(\"Invalid Operator type for the given algebraic operation.\");\n    }\n    return *this;\n  }\n\n  // Apply the desired operation between this operator an the given scalar complex\n  OperatorImpl &apply(const std::complex<double> &d) {\n    if (type == \"pauli\") {\n      cast_and_apply<xacc::quantum::PauliOperator>()(op, d);\n    } else if (type == \"fermion\") {\n      cast_and_apply<xacc::quantum::FermionOperator>()(op, d);\n    } else {\n      // FIXME / TODO As we add more Operator types, update\n      // this if/else section\n      error(\"Invalid Operator type for the given algebraic operation.\");\n    }\n    return *this;\n  }\n\n  std::string type;\n  std::shared_ptr<xacc::Observable> op;\n\n public:\n  // Internal impl constructed from HetMap of options, or string-like expression\n  OperatorImpl() = default;\n  OperatorImpl(const std::string &_type, const std::string &expr)\n      : type(_type) {\n    op = xacc::quantum::getObservable(type, expr);\n  }\n\n  OperatorImpl(const std::string &name, xacc::HeterogeneousMap &options) {\n    auto tmp_op = xacc::quantum::getObservable(name, options);\n    auto obs_str = tmp_op->toString();\n\n    if (obs_str.find(\"^\") != std::string::npos) {\n\n      op = xacc::quantum::getObservable(\"fermion\", obs_str);\n      type = \"fermion\";\n\n    } else if (obs_str.find(\"X\") != std::string::npos ||\n               obs_str.find(\"Y\") != std::string::npos ||\n               obs_str.find(\"Z\") != std::string::npos) {\n      op = xacc::quantum::getObservable(\"pauli\", obs_str);\n      type = \"pauli\";\n    }\n  }\n\n  OperatorImpl(const std::string &_type, std::shared_ptr<xacc::Observable> _op)\n      : type(_type), op(_op) {}\n  OperatorImpl(const OperatorImpl &other) : type(other.type), op(other.op) {}\n\n  // Implement internal Algebraic API\n  OperatorImpl &operator+=(const OperatorImpl &v) noexcept {\n    return apply(operation::PlusEquals, v);\n  }\n\n  OperatorImpl &operator-=(const OperatorImpl &v) noexcept {\n    return apply(operation::MinusEqual, v);\n  }\n  OperatorImpl &operator*=(const OperatorImpl &v) noexcept {\n    return apply(operation::StarEqual, v);\n  }\n  OperatorImpl &operator*=(const double v) noexcept { return apply(v); }\n  OperatorImpl &operator*=(const std::complex<double> v) noexcept {\n    return apply(v);\n  }\n\n  bool operator==(const OperatorImpl &v) noexcept {\n    if (type == \"pauli\") {\n      auto casted = std::dynamic_pointer_cast<xacc::quantum::PauliOperator>(op);\n      auto other_casted =\n          std::dynamic_pointer_cast<xacc::quantum::PauliOperator>(v.op);\n      assert(casted && other_casted && \"Invalid types for Operator == check.\");\n      return casted->operator==(*other_casted.get());\n    } else if (type == \"fermion\") {\n      auto casted =\n          std::dynamic_pointer_cast<xacc::quantum::FermionOperator>(op);\n      auto other_casted =\n          std::dynamic_pointer_cast<xacc::quantum::FermionOperator>(v.op);\n      assert(casted && other_casted && \"Invalid types for Operator == check.\");\n      return casted->operator==(*other_casted.get());\n    } else {\n      // FIXME / TODO As we add more Operator types, update\n      // this if/else section\n    }\n    return false;\n  }\n\n  std::vector<Operator> getSubTerms() {\n    std::vector<Operator> ret;\n    for (auto sub_term : op->getSubTerms()) {\n      ret.emplace_back(OperatorImpl(type, sub_term));\n    }\n    return ret;\n  }\n\n  std::vector<Operator> getNonIdentitySubTerms() {\n    std::vector<Operator> ret;\n    for (auto sub_term : op->getNonIdentitySubTerms()) {\n      ret.emplace_back(OperatorImpl(type, sub_term));\n    }\n    return ret;\n  }\n\n  Operator getIdentitySubTerm() {\n    auto id_term = op->getIdentitySubTerm();\n    if (!id_term) {\n      // THROW AN ERROR.\n     error(\"There is no identity sub term. exiting.\");\n    }\n    return Operator(OperatorImpl(type, op->getIdentitySubTerm()));\n  }\n\n  bool hasIdentitySubTerm() { return op->getIdentitySubTerm() != nullptr; }\n  std::complex<double> coefficient() { return op->coefficient(); }\n\n  std::vector<SparseElement> to_sparse_matrix() {\n    auto sp_el = op->to_sparse_matrix();\n    std::vector<SparseElement> ret;\n    for (auto el : sp_el) {\n      ret.emplace_back(el.row(), el.col(), el.coeff());\n    }\n    return ret;\n  }\n\n  Operator commutator(Operator &other) {\n    return Operator(OperatorImpl(type, op->commutator(other.m_internal->op)));\n  }\n\n  std::pair<std::vector<int>, std::vector<int>> toBinaryVectors(\n      const int nQubits) {\n    assert(type == \"pauli\" && \"toBinaryVectors only works for pauli operators\");\n    return std::dynamic_pointer_cast<xacc::quantum::PauliOperator>(op)\n        ->toBinaryVectors(nQubits);\n  }\n\n  void mapQubitSites(std::map<int, int> &siteMap) {\n    assert(type == \"pauli\" && \"mapQubitSites only works for pauli operators\");\n    std::dynamic_pointer_cast<xacc::quantum::PauliOperator>(op)->mapQubitSites(\n        siteMap);\n  }\n};\n\nOperator &Operator::operator=(const Operator &other) {\n  m_internal->op = other.m_internal->op;\n  m_internal->type = other.m_internal->type;\n  return *this;\n}\n\nOperator::Operator(const std::string &name, xacc::HeterogeneousMap &options)\n    : m_internal(name, options) {}\nOperator::Operator(const std::string &type, const std::string &expr)\n    : m_internal(type, expr) {}\nOperator::Operator(const Operator &op)\n    : m_internal(op.m_internal.operator->()->type,\n                 op.m_internal.operator->()->op->toString()) {}\nOperator::Operator(const OperatorImpl &&impl)\n    : m_internal(impl.type, impl.op) {}\n\nOperator::Operator() = default;\nOperator::~Operator() = default;\n\nstd::shared_ptr<xacc::Identifiable> Operator::get_as_opaque() {\n  return std::dynamic_pointer_cast<xacc::Identifiable>(m_internal->op);\n}\n\nOperator &Operator::operator+=(const Operator &v) noexcept {\n  OperatorImpl *other = v.m_internal.operator->();\n  m_internal->operator+=(*other);\n  return *this;\n}\n\nOperator &Operator::operator-=(const Operator &v) noexcept {\n  OperatorImpl *other = v.m_internal.operator->();\n  m_internal->operator-=(*other);\n  return *this;\n}\nOperator &Operator::operator*=(const Operator &v) noexcept {\n  OperatorImpl *other = v.m_internal.operator->();\n  m_internal->operator*=(*other);\n  return *this;\n}\nbool Operator::operator==(const Operator &v) noexcept {\n  OperatorImpl *other = v.m_internal.operator->();\n  return m_internal->operator==(*other);\n}\nOperator &Operator::operator*=(const double v) noexcept {\n  m_internal->operator*=(v);\n  return *this;\n}\nOperator &Operator::operator*=(const std::complex<double> v) noexcept {\n  m_internal->operator*=(v);\n  return *this;\n}\n\nint Operator::nQubits() { return m_internal->op->nBits(); }\n\nstd::pair<std::vector<int>, std::vector<int>> Operator::toBinaryVectors(\n    const int nQubits) {\n  return m_internal->toBinaryVectors(nQubits);\n}\nvoid Operator::mapQubitSites(std::map<int, int> &siteMap) {\n  return m_internal->mapQubitSites(siteMap);\n}\n\nstd::vector<std::shared_ptr<CompositeInstruction>> Operator::observe(\n    std::shared_ptr<CompositeInstruction> program) {\n  auto as_xacc = program->as_xacc();\n  auto cis = m_internal->op->observe(as_xacc);\n  std::vector<std::shared_ptr<CompositeInstruction>> ret;\n  for (auto ci : cis) {\n    ret.emplace_back(std::make_shared<CompositeInstruction>(\n        std::dynamic_pointer_cast<xacc::Identifiable>(ci)));\n  }\n\n  return ret;\n}\n\nstd::vector<Operator> Operator::getSubTerms() {\n  return m_internal->getSubTerms();\n}\n\nstd::vector<Operator> Operator::getNonIdentitySubTerms() {\n  return m_internal->getNonIdentitySubTerms();\n}\nbool Operator::hasIdentitySubTerm() { return m_internal->hasIdentitySubTerm(); }\n\nstd::string Operator::toString() const { return m_internal->op->toString(); }\nOperator Operator::getIdentitySubTerm() {\n  return m_internal->getIdentitySubTerm();\n}\nstd::complex<double> Operator::coefficient() {\n  return m_internal->coefficient();\n}\n\nstd::vector<Operator::SparseElement> Operator::to_sparse_matrix() {\n  return m_internal->to_sparse_matrix();\n}\n\nOperator Operator::commutator(Operator &op) {\n  return m_internal->commutator(op);\n}\n\nOperator Operator::transform(const std::string &type,\n                             xacc::HeterogeneousMap m) {\n  auto transformed =\n      xacc::getService<xacc::ObservableTransform>(type)->transform(\n          m_internal->op);\n  auto new_type =\n      std::dynamic_pointer_cast<xacc::quantum::FermionOperator>(transformed)\n          ? \"fermion\"\n          : \"pauli\";\n  return Operator(OperatorImpl(new_type, transformed));\n}\n\nvoid __internal_exec_observer(\n    xacc::AcceleratorBuffer *b,\n    std::vector<std::shared_ptr<CompositeInstruction>> v) {\n  // auto vv = v.get()->operator->()->program;\n  std::vector<std::shared_ptr<xacc::CompositeInstruction>> tmp;\n  std::transform(v.begin(), v.end(), std::back_inserter(tmp),\n                 [](std::shared_ptr<CompositeInstruction> c)\n                     -> std::shared_ptr<xacc::CompositeInstruction> {\n                   return c->as_xacc();\n                 });\n  xacc::internal_compiler::execute(b, tmp);\n}\n\nOperator operator+(double coeff, Operator op) {\n  return Operator(\"pauli\", fmt::format(\"{}\", coeff)) + op;\n}\nOperator operator+(Operator op, double coeff) {\n  return op + Operator(\"pauli\", fmt::format(\"{}\", coeff));\n}\n\nOperator operator-(double coeff, Operator op) {\n  return Operator(\"pauli\", fmt::format(\"{}\", coeff)) - op;\n}\n\nOperator operator-(Operator op, double coeff) {\n  return op - Operator(\"pauli\", fmt::format(\"{}\", coeff));\n}\n\nOperator adag(int idx) {\n  return Operator(\"fermion\", fmt::format(\"1.0 {}^\", idx));\n}\nOperator a(int idx) { return Operator(\"fermion\", fmt::format(\"1.0 {}\", idx)); }\n\nOperator X(int idx) { return Operator(\"pauli\", fmt::format(\"X{}\", idx)); }\nOperator Y(int idx) { return Operator(\"pauli\", fmt::format(\"Y{}\", idx)); }\nOperator Z(int idx) { return Operator(\"pauli\", fmt::format(\"Z{}\", idx)); }\n\nOperator allZs(const int nQubits) {\n  auto ret = Z(0);\n  for (int i = 1; i < nQubits; i++) {\n    ret *= Z(i);\n  }\n  return ret;\n}\n\nOperator SP(int idx) {\n  std::complex<double> imag(0.0, 1.0);\n  return X(idx) + imag * Y(idx);\n}\n\nOperator SM(int idx) {\n  std::complex<double> imag(0.0, 1.0);\n  return X(idx) - imag * Y(idx);\n}\n\nEigen::MatrixXcd get_dense_matrix(Operator &op) {\n  auto mat_el = op.to_sparse_matrix();\n  auto size = std::pow(2, op.nBits());\n  Eigen::MatrixXcd mat = Eigen::MatrixXcd::Zero(size, size);\n  for (auto el : mat_el) {\n    mat(el.row(), el.col()) = el.coeff();\n  }\n  return mat;\n}\n\nOperator createOperator(const std::string &repr) {\n  if (!xacc::isInitialized())\n    xacc::internal_compiler::compiler_InitializeXACC();\n  return qcor::Operator(\"pauli\", repr);\n}\n\nOperator createOperator(const std::string &name, const std::string &repr) {\n  if (!xacc::isInitialized())\n    xacc::internal_compiler::compiler_InitializeXACC();\n  return qcor::Operator(name, repr);\n}\n\nOperator createOperator(const std::string &name, HeterogeneousMap &&options) {\n  return createOperator(name, options);\n}\nOperator createOperator(const std::string &name, HeterogeneousMap &options) {\n  return qcor::Operator(name, options);\n}\n\nOperator createObservable(const std::string &repr) {\n  return createOperator(repr);\n}\n\nOperator createObservable(const std::string &name, const std::string &repr) {\n  return createOperator(name, repr);\n}\n\nOperator operatorTransform(const std::string &type, Operator &op) {\n  return op.transform(type);\n}\n\nOperator _internal_python_createObservable(const std::string &name,\n                                           const std::string &repr) {\n  return createOperator(name, repr);\n}\n\nnamespace __internal__ {\nstd::map<std::size_t, Operator> cached_observables = {};\n\nstd::vector<std::shared_ptr<CompositeInstruction>> observe(\n    Operator &obs, std::shared_ptr<CompositeInstruction> program) {\n  return obs.observe(program);\n}\n}  // namespace __internal__\n\ndouble observe(std::shared_ptr<CompositeInstruction> program, Operator &obs,\n               xacc::internal_compiler::qreg &q) {\n  // Observe the program\n  auto v = obs.observe(program);\n\n  std::vector<std::shared_ptr<xacc::CompositeInstruction>> tmp;\n  std::transform(v.begin(), v.end(), std::back_inserter(tmp),\n                 [](std::shared_ptr<CompositeInstruction> c)\n                     -> std::shared_ptr<xacc::CompositeInstruction> {\n                   return c->as_xacc();\n                 });\n  xacc::internal_compiler::execute(q.results(), tmp);\n\n  // We want to contract q children buffer\n  // exp-val-zs with obs term coeffs\n  return q.weighted_sum(\n      std::dynamic_pointer_cast<xacc::Observable>(obs.get_as_opaque()).get());\n}\n\n}  // namespace qcor\n\nstd::ostream &operator<<(std::ostream &os, qcor::Operator const &m) {\n  return os << m.toString();\n}", "meta": {"hexsha": "1b2e3eef1ab36bba437d1a95f2eb41a9f73dbb76", "size": 16734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "runtime/observable/qcor_observable.cpp", "max_stars_repo_name": "vetter/qcor", "max_stars_repo_head_hexsha": "6f86835737277a26071593bb10dd8627c29d74a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 59.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:40:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:12:42.000Z", "max_issues_repo_path": "runtime/observable/qcor_observable.cpp", "max_issues_repo_name": "vetter/qcor", "max_issues_repo_head_hexsha": "6f86835737277a26071593bb10dd8627c29d74a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 137.0, "max_issues_repo_issues_event_min_datetime": "2019-09-13T15:50:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T14:19:46.000Z", "max_forks_repo_path": "runtime/observable/qcor_observable.cpp", "max_forks_repo_name": "vetter/qcor", "max_forks_repo_head_hexsha": "6f86835737277a26071593bb10dd8627c29d74a3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2019-07-08T17:30:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-03T16:24:12.000Z", "avg_line_length": 33.268389662, "max_line_length": 82, "alphanum_fraction": 0.6606908091, "num_tokens": 4174, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4185780698887628}}
{"text": "#include <kr_serial_interface/comm_types.h>\n#include <kr_serial_interface/decode_msgs.h>\n\n#include <Eigen/Geometry>\n\nnamespace kr_mav_msgs\n{\nbool decodeOutputData(const std::vector<uint8_t> &data, kr_mav_msgs::OutputData &output)\n{\n  struct OUTPUT_DATA output_data;\n  if(data.size() != sizeof(output_data))\n    return false;\n\n  memcpy(&output_data, &data[0], sizeof(output_data));\n  output.loop_rate = output_data.loop_rate;\n  output.voltage = output_data.voltage / 1e3f;\n\n  const double roll = output_data.roll / 1e2f * M_PI / 180;\n  const double pitch = output_data.pitch / 1e2f * M_PI / 180;\n  const double yaw = output_data.yaw / 1e2f * M_PI / 180;\n  // Asctec (2012 firmware) uses  Z-Y-X convention\n  Eigen::Quaternionf q = Eigen::AngleAxisf(yaw, Eigen::Vector3f::UnitZ()) *\n                         Eigen::AngleAxisf(pitch, Eigen::Vector3f::UnitY()) *\n                         Eigen::AngleAxisf(roll, Eigen::Vector3f::UnitX());\n  output.orientation.w = q.w();\n  output.orientation.x = q.x();\n  output.orientation.y = q.y();\n  output.orientation.z = q.z();\n\n  output.angular_velocity.x = output_data.ang_vel[0] * 0.0154f * M_PI / 180;\n  output.angular_velocity.y = output_data.ang_vel[1] * 0.0154f * M_PI / 180;\n  output.angular_velocity.z = output_data.ang_vel[2] * 0.0154f * M_PI / 180;\n\n  output.linear_acceleration.x = output_data.acc[0] / 1e3f * 9.81f;\n  output.linear_acceleration.y = output_data.acc[1] / 1e3f * 9.81f;\n  output.linear_acceleration.z = output_data.acc[2] / 1e3f * 9.81f;\n\n  output.pressure_dheight = output_data.dheight / 1e3f;\n  output.pressure_height = output_data.height / 1e3f;\n\n  output.magnetic_field.x = output_data.mag[0] / 2500.0f;\n  output.magnetic_field.y = output_data.mag[1] / 2500.0f;\n  output.magnetic_field.z = output_data.mag[2] / 2500.0f;\n\n  for(int i = 0; i < 8; i++)\n  {\n    output.radio_channel[i] = output_data.radio[i];\n  }\n\n  // Asctec firmware uses the following rotor numbering convention:\n  //   *1*    Front\n  // 3     4\n  //    2\n  //\n  // But we want:\n  //   *1*    Front\n  // 2     4\n  //    3\n  const int motors_map[] = {0, 2, 1, 3};\n  for(int i = 0; i < 4; i++)\n  {\n    // The following conversion is from\n    // http://wiki.asctec.de/display/AR/List+of+all+predefined+variables%2C+commands+and+parameters\n    //\n    // motorRPM = 1075+m*37.625\n    //\n    // Note: If m == 0, the motors are not spinning.\n    int m = output_data.rpm[motors_map[i]];\n    output.motor_rpm[i] = (m == 0 ? 0 : 1075) + m * 37.625;\n  }\n\n  output.seq = output_data.seq;\n\n  return true;\n}\n\nbool decodeStatusData(const std::vector<uint8_t> &data, kr_mav_msgs::StatusData &status)\n{\n  struct STATUS_DATA status_data;\n  if(data.size() != sizeof(status_data))\n    return false;\n  memcpy(&status_data, &data[0], sizeof(status_data));\n\n  status.loop_rate = status_data.loop_rate;\n  status.voltage = status_data.voltage / 1e3f;\n  status.seq = status_data.seq;\n\n  return true;\n}\n\n}  // namespace kr_mav_msgs\n", "meta": {"hexsha": "8848ae3ee318bc65bb0c871975dfc813a43f0174", "size": 2936, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "interfaces/kr_serial_interface/src/decode_msgs.cpp", "max_stars_repo_name": "fcladera/kr_mav_control", "max_stars_repo_head_hexsha": "3e4a80f9af469df59628537876fb4e9a8f2fcd14", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T17:04:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:43:50.000Z", "max_issues_repo_path": "interfaces/kr_serial_interface/src/decode_msgs.cpp", "max_issues_repo_name": "fcladera/kr_mav_control", "max_issues_repo_head_hexsha": "3e4a80f9af469df59628537876fb4e9a8f2fcd14", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T20:28:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-29T16:51:24.000Z", "max_forks_repo_path": "interfaces/kr_serial_interface/src/decode_msgs.cpp", "max_forks_repo_name": "fcladera/kr_mav_control", "max_forks_repo_head_hexsha": "3e4a80f9af469df59628537876fb4e9a8f2fcd14", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2021-02-10T09:38:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T15:55:59.000Z", "avg_line_length": 31.9130434783, "max_line_length": 99, "alphanum_fraction": 0.666893733, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4185780637740887}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_POW_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_POW_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/any.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_flint.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/is_odd.hpp>\n#include <boost/simd/function/logical_and.hpp>\n#include <boost/simd/function/logical_andnot.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/if_neg.hpp>\n#include <boost/simd/function/pow_abs.hpp>\n#include <boost/simd/function/shift_right.hpp>\n#include <boost/simd/function/sqr.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD_IF( pow_\n                           , (typename A0,typename X)\n                           , (detail::is_native<X>)\n                           , bd::cpu_\n                           , bs::pack_<bd::floating_<A0>,X>\n                           , bs::pack_<bd::floating_<A0>,X>\n                           )\n  {\n    BOOST_FORCEINLINE A0 operator()( const A0& a0, const A0& a1) BOOST_NOEXCEPT\n    {\n      auto nega0 = is_negative(a0);\n      A0 z = pow_abs(a0, a1);\n      z =  if_neg(logical_and(is_odd(a1), nega0), z);\n      auto invalid =  logical_andnot(nega0, logical_or(is_flint(a1), is_inf(a1)));\n      z = if_else(invalid, Nan<A0>(), z);\n      return z;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF(pow_\n                          , (typename A0,typename A1,typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::arithmetic_<A0>, X>\n                          , bs::pack_<bd::uint_<A1>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()(const A0& a0, const A1& a1 ) const BOOST_NOEXCEPT\n      {\n        A0 base = a0;\n        A1 exp = a1;\n        A0 result = One<A0>();\n        while(bs::any(exp))\n        {\n          result *= if_else(is_odd(exp), base, One<A0>());\n          exp =  exp >> 1;\n          base = sqr(base);\n        }\n        return result;\n       }\n   };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( pow_\n                          , (typename A0, typename A1, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::arithmetic_<A0>, X>\n                          , bd::constant_< bd::uint_<A1>>\n                          )\n  {\n    using result_type = A0;\n\n    BOOST_FORCEINLINE result_type operator() ( A0 const& a0, A1) const BOOST_NOEXCEPT\n    {\n      return pow_expander<A1::value>::call(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( pow_\n                          , (typename A0, typename A1, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::floating_<A0>, X>\n                          , bd::constant_< bd::int_<A1>>\n                          )\n  {\n    using result_type = A0;\n\n    BOOST_FORCEINLINE result_type operator() ( A0 const& a0, A1) const BOOST_NOEXCEPT\n    {\n      return eval(a0, boost::mpl::bool_<(A1::value >= 0)>());\n    }\n\n    BOOST_FORCEINLINE result_type eval( A0 const& a0, boost::mpl::true_) const BOOST_NOEXCEPT\n    {\n      return pow_expander<A1::value>::call(a0);\n    }\n\n    BOOST_FORCEINLINE result_type eval( A0 const& a0, boost::mpl::false_) const BOOST_NOEXCEPT\n    {\n      return pow_expander<-A1::value>::call(rec(a0));\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( pow_\n                          , (typename A0, typename A1, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::arithmetic_<A0>, X>\n                          , bd::scalar_< bd::uint_<A1>>\n                          )\n  {\n    using result_type = A0;\n\n    A0 operator() ( A0 const& a0, A1 const& a1) const BOOST_NOEXCEPT\n    {\n      A0 base = a0;\n      A1 exp = a1;\n\n      result_type result = One<result_type>();\n      while(exp)\n      {\n        if(is_odd(exp))\n          result *= base;\n        exp >>= 1;\n        base = sqr(base);\n      }\n\n      return result;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( pow_\n                          , (typename A0, typename A1, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::integer_<A0>, X>\n                          , bs::pack_< bd::int_<A1>, X>\n                          )\n  {\n    using result_type = A0;\n\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0, A1 const& a1) const BOOST_NOEXCEPT\n    {\n      BOOST_ASSERT_MSG( boost::simd::assert_all(a1 >= 0), \"integral pow with signed exponent\" );\n\n      using u_t =  bd::as_integer_t<A1, unsigned>;\n      return pow(a0, bitwise_cast<u_t>(a1));\n    }\n  };\n\n\n  BOOST_DISPATCH_OVERLOAD_IF ( pow_\n                          , (typename A0, typename A1, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::floating_<A0>, X>\n                          , bs::pack_< bd::int_<A1>, X>\n                          )\n  {\n    using result_type = A0;\n\n    A0 operator() ( A0 const& a0, A1 const& a1) const BOOST_NOEXCEPT\n    {\n      using u_t =  bd::as_integer_t<A1, unsigned>;\n      auto ltza1 = is_ltz(a1);\n      A0 p = pow(a0, bitwise_cast<u_t>(if_neg(ltza1, a1)));\n      return if_else(ltza1, rec(p), p);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF( pow_\n                            , (typename A0,typename X)\n                            , (detail::is_native<X>)\n                            , bs::raw_tag\n                            , bd::cpu_\n                            , bs::pack_<bd::floating_<A0>,X>\n                            , bs::pack_<bd::floating_<A0>,X>\n                           )\n  {\n    BOOST_FORCEINLINE A0 operator()(const raw_tag &,\n                                    const A0& a0, const A0& a1) BOOST_NOEXCEPT\n    {\n      auto nega0 = is_negative(a0);\n      A0 z = raw_(pow_abs(a0, a1));\n      z =  if_neg(logical_and(is_odd(a1), nega0), z);\n      auto invalid =  logical_andnot(nega0, logical_or(is_flint(a1), is_inf(a1)));\n      z = if_else(invalid, Nan<A0>(), z);\n      return z;\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "a3d6c34568067bbdd37ec2340617f3333ef183e0", "size": 6865, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/pow.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/simd/function/pow.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/simd/function/pow.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 33.0048076923, "max_line_length": 100, "alphanum_fraction": 0.4970138383, "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.4185564366990966}}
{"text": "//\n// Created by David Wise on 24/03/2017.\n//\n\n#include <iostream>\n#include \"donorClass.h\"\n#include <stdio.h>\n#include <Eigen/Dense>\n//#include \"gnuplot-iostream/gnuplot-iostream.h\"\n#include <fstream>\n\nusing namespace std;\n\nint main() {\n\n// Initialise a donor with required nuclear spin and hyperfine coupling\n\tDonor phos;\n    phos.initialise(0.5, 7.29e-26);\n\n// Create a savefile for the eigen values\n    std::ofstream saveFile(\"donorsgotest.txt\");\n\n// Create matrices to store eigenvalues (need (nucSpin + 0.5) * 4)\n    MatrixXcd eig1;\n    MatrixXcd eig2;\n    MatrixXcd eig3;\n    MatrixXcd eig4;\n    MatrixXcd fields;\n\n\n// Loop through a number of steps in magnetic field finding eigenvalues at each step\n    int numSteps = 1000;\n    for (double incr = 0; incr <numSteps; ++incr) {\n        double maxField = 1;\n        eig1.resize(numSteps, 1);\n        eig2.resize(numSteps, 1);\n        eig3.resize(numSteps, 1);\n        eig4.resize(numSteps, 1);\n        fields.resize(numSteps, 1);\n        MatrixXcd Eigs = phos.getEigs(incr);\n        eig1(incr) = Eigs(0);\n        eig2(incr) = Eigs(1);\n        eig4(incr) = Eigs(2);\n        eig3(incr) = Eigs(3);\n        fields(incr) = (maxField/numSteps)*incr;\n    };\n\n// Save eigenvalues to file\n    saveFile << \"Fields \\n\" << fields << \"\\n Eigs 1 \\n\" << eig1 << \"\\n Eigs 2 \\n\" << eig2 << \"\\n Eigs 3 \\n\" << eig3 << \"\\n Eigs 4 \\n\" << eig4;\n    saveFile.close();\n\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "b09daafa3a7ced6c852a8492f3a501b1eb12f05d", "size": 1416, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "Telthor/cppDonorSimulation", "max_stars_repo_head_hexsha": "f05d293d2eb8e06b0d02a4900f23beaf9296d018", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "Telthor/cppDonorSimulation", "max_issues_repo_head_hexsha": "f05d293d2eb8e06b0d02a4900f23beaf9296d018", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "Telthor/cppDonorSimulation", "max_forks_repo_head_hexsha": "f05d293d2eb8e06b0d02a4900f23beaf9296d018", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2857142857, "max_line_length": 142, "alphanum_fraction": 0.6193502825, "num_tokens": 445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.41855643140842363}}
{"text": "/*\n\nPICCANTE\nThe hottest HDR imaging library!\nhttp://vcg.isti.cnr.it/piccante\n\nCopyright (C) 2014\nVisual Computing Laboratory - ISTI CNR\nhttp://vcg.isti.cnr.it\nFirst author: Francesco Banterle\n\nThis Source Code Form is subject to the terms of the Mozilla Public\nLicense, v. 2.0. If a copy of the MPL was not distributed with this\nfile, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n*/\n\n#ifndef PIC_ALGORITHMS_POISSON_IMAGE_EDITING_HPP\n#define PIC_ALGORITHMS_POISSON_IMAGE_EDITING_HPP\n\n#include <vector>\n\n#include \"../base.hpp\"\n#include \"../image.hpp\"\n#include \"../util/std_util.hpp\"\n#include \"../filtering/filter_laplacian.hpp\"\n\n#ifndef PIC_DISABLE_EIGEN\n\n#ifndef PIC_EIGEN_NOT_BUNDLED\n    #include \"../externals/Eigen/Sparse\"\n    #include \"../externals/Eigen/src/SparseCore/SparseMatrix.h\"\n#else\n    #include <Eigen/Sparse>\n    #include <Eigen/src/SparseCore/SparseMatrix.h>\n#endif\n\n#endif\n\nnamespace pic {\n\n#ifndef PIC_DISABLE_EIGEN\n/**\n * @brief computePoissonImageEditing\n * @param source\n * @param target\n * @param mask\n * @param ret\n * @return\n */\nPIC_INLINE Image *computePoissonImageEditing(Image *source, Image *target, bool *mask, Image *ret = NULL)\n{\n    if((source == NULL) || (target == NULL) || (mask == NULL)) {\n        return NULL;\n    }\n\n    //allocate the output\n    if(ret == NULL) {\n        ret = target->clone();\n    }\n\n    int width  = target->width;\n    int height = target->height;\n\n    #ifdef PIC_DEBUG\n        printf(\"Init matrix...\");\n    #endif\n\n    Image *lap_source = FilterLaplacian::execute(source, NULL);\n\n    std::vector< Eigen::Triplet< double > > tL;\n\n    //indices pass\n    int *index = new int[width * height];\n    int count = 0;\n    for(int i = 0; i < height; i++) {\n        int tmpI = i * width;\n\n        for(int j = 0; j < width; j++) {\n            int indI = tmpI + j;\n\n            if(mask[indI]) {\n                index[indI] = count;\n                count++;\n            } else {\n                index[indI] = 0;\n            }\n        }\n    }\n\n    //matrix A pass\n    count = 0;\n    for(int i = 0; i < height; i++) {\n        int tmpI = i * width;\n\n        for(int j = 0; j < width; j++) {\n            int indI = tmpI + j;\n\n            if(mask[indI]) {\n                if((j + 1) < (width - 1)) {\n                    if(mask[indI + 1]) {\n                        tL.push_back(Eigen::Triplet< double > (count, index[indI + 1], -1.0));\n                    }\n                }\n\n                if((j - 1) > -1) {\n                    if(mask[indI - 1]) {\n                        tL.push_back(Eigen::Triplet< double > (count, index[indI - 1], -1.0));\n                    }\n                }\n\n                if((i + 1) < (height - 1)) {\n                    if(mask[indI + width]) {\n                        tL.push_back(Eigen::Triplet< double > (count, index[indI + width], -1.0));\n                    }\n                }\n\n                if((i - 1) > -1) {\n                    if(mask[indI - width]) {\n                        tL.push_back(Eigen::Triplet< double > (count, index[indI - width], -1.0));\n                    }\n                }\n\n                tL.push_back(Eigen::Triplet< double > (count, count , 4.0));\n\n                count++;\n            }\n        }\n    }\n\n    int tot = count;\n    Eigen::SparseMatrix<double> A = Eigen::SparseMatrix<double>(tot, tot);\n    A.setFromTriplets(tL.begin(), tL.end());\n\n    #ifdef PIC_DEBUG\n        printf(\"Ok\\n\");\n    #endif\n\n    //solve the linear system for each color channel\n    Eigen::SimplicialCholesky<Eigen::SparseMatrix<double> > solver(A);\n\n    for(int k=0; k< target->channels; k++) {\n\n        Eigen::VectorXd b, x;\n        b = Eigen::VectorXd::Zero(tot);\n\n        //assign values to b\n        int count = 0;\n        for(int i = 0; i < height; i++) {\n            int tmpI = i * width;\n\n            for(int j = 0; j < width; j++) {\n                int indI = (tmpI + j);\n\n                if(mask[indI]) {\n\n                    b[count] = -(*lap_source)(j, i)[k];\n\n                    if((j + 1) < (width - 1)) {\n                        if(!mask[indI + 1]) {\n                            b[count] += (*target)(j + 1, i)[k];\n                        }\n                    }\n\n                    if((j - 1) > -1) {\n                        if(!mask[indI - 1]) {\n                            b[count] += (*target)(j - 1, i)[k];\n                        }\n                    }                        \n\n                    if((i + 1) < (height - 1)) {\n                        if(!mask[indI + width]) {\n                            b[count] += (*target)(j, i + 1)[k];\n                        }\n                    }\n\n                    if((i - 1) > -1) {\n                        if(!mask[indI - width]) {\n                           b[count] += (*target)(j, i - 1)[k];\n                        }\n                    }\n\n                    count++;\n                }\n            }\n        }\n\n        x = solver.solve(b);\n\n        if(solver.info() != Eigen::Success) {\n            #ifdef PIC_DEBUG\n                printf(\"SOLVER FAILED!\\n\");\n            #endif\n\n            return NULL;\n        }\n\n        #ifdef PIC_DEBUG\n            printf(\"SOLVER SUCCESS!\\n\");\n        #endif\n\n        count = 0;\n        for(int i = 0; i < height; i++) {\n            int tmpI = i * width;\n\n            for(int j = 0; j < width; j++) {\n                int indI = (tmpI + j);\n\n                if(mask[indI]) {\n                    float val = float(x(count));\n                    (*ret)(j, i)[k] = val > 0.0f ? val : 0.0f;\n                    count++;\n                }\n            }\n        }\n    }\n\n    delete_s(lap_source);\n    delete_vec_s(index);\n\n    return ret;\n}\n#endif\n\n} // end namespace pic\n\n#endif /* PIC_ALGORITHMS_POISSON_IMAGE_EDITING_HPP */\n\n", "meta": {"hexsha": "a0ebf3a3e7371b3854bfea3032cf3997b09947d0", "size": 5727, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/poisson_image_editing.hpp", "max_stars_repo_name": "ecarpita93/HPC_projet_1", "max_stars_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/algorithms/poisson_image_editing.hpp", "max_issues_repo_name": "ecarpita93/HPC_projet_1", "max_issues_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/algorithms/poisson_image_editing.hpp", "max_forks_repo_name": "ecarpita93/HPC_projet_1", "max_forks_repo_head_hexsha": "a2c00e056c03227711c43cf2ad23d75c6afbe698", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0087336245, "max_line_length": 105, "alphanum_fraction": 0.4421162913, "num_tokens": 1482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.41854310467561573}}
{"text": "// Copyright 2004 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_BETWEENNESS_CENTRALITY_CLUSTERING_HPP\n#define BOOST_GRAPH_BETWEENNESS_CENTRALITY_CLUSTERING_HPP\n\n#include <boost/graph/betweenness_centrality.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <algorithm>\n#include <vector>\n#include <boost/property_map.hpp>\n\nnamespace boost {\n\n/** Threshold termination function for the betweenness centrality\n * clustering algorithm.\n */\ntemplate<typename T>\nstruct bc_clustering_threshold\n{\n  typedef T centrality_type;\n\n  /// Terminate clustering when maximum absolute edge centrality is\n  /// below the given threshold.\n  explicit bc_clustering_threshold(T threshold) \n    : threshold(threshold), dividend(1.0) {}\n  \n  /**\n   * Terminate clustering when the maximum edge centrality is below\n   * the given threshold.\n   *\n   * @param threshold the threshold value\n   *\n   * @param g the graph on which the threshold will be calculated\n   *\n   * @param normalize when true, the threshold is compared against the\n   * normalized edge centrality based on the input graph; otherwise,\n   * the threshold is compared against the absolute edge centrality.\n   */\n  template<typename Graph>\n  bc_clustering_threshold(T threshold, const Graph& g, bool normalize = true)\n    : threshold(threshold), dividend(1.0)\n  {\n    if (normalize) {\n      typename graph_traits<Graph>::vertices_size_type n = num_vertices(g);\n      dividend = T((n - 1) * (n - 2)) / T(2);\n    }\n  }\n\n  /** Returns true when the given maximum edge centrality (potentially\n   * normalized) falls below the threshold.\n   */\n  template<typename Graph, typename Edge>\n  bool operator()(T max_centrality, Edge, const Graph&)\n  {\n    return (max_centrality / dividend) < threshold;\n  }\n\n protected:\n  T threshold;\n  T dividend;\n};\n\n/** Graph clustering based on edge betweenness centrality.\n * \n * This algorithm implements graph clustering based on edge\n * betweenness centrality. It is an iterative algorithm, where in each\n * step it compute the edge betweenness centrality (via @ref\n * brandes_betweenness_centrality) and removes the edge with the\n * maximum betweenness centrality. The @p done function object\n * determines when the algorithm terminates (the edge found when the\n * algorithm terminates will not be removed).\n *\n * @param g The graph on which clustering will be performed. The type\n * of this parameter (@c MutableGraph) must be a model of the\n * VertexListGraph, IncidenceGraph, EdgeListGraph, and Mutable Graph\n * concepts.\n *\n * @param done The function object that indicates termination of the\n * algorithm. It must be a ternary function object thats accepts the\n * maximum centrality, the descriptor of the edge that will be\n * removed, and the graph @p g.\n *\n * @param edge_centrality (UTIL/OUT) The property map that will store\n * the betweenness centrality for each edge. When the algorithm\n * terminates, it will contain the edge centralities for the\n * graph. The type of this property map must model the\n * ReadWritePropertyMap concept. Defaults to an @c\n * iterator_property_map whose value type is \n * @c Done::centrality_type and using @c get(edge_index, g) for the \n * index map.\n *\n * @param vertex_index (IN) The property map that maps vertices to\n * indices in the range @c [0, num_vertices(g)). This type of this\n * property map must model the ReadablePropertyMap concept and its\n * value type must be an integral type. Defaults to \n * @c get(vertex_index, g).\n */\ntemplate<typename MutableGraph, typename Done, typename EdgeCentralityMap,\n         typename VertexIndexMap>\nvoid \nbetweenness_centrality_clustering(MutableGraph& g, Done done,\n                                  EdgeCentralityMap edge_centrality,\n                                  VertexIndexMap vertex_index)\n{\n  typedef typename property_traits<EdgeCentralityMap>::value_type\n    centrality_type;\n  typedef typename graph_traits<MutableGraph>::edge_iterator edge_iterator;\n  typedef typename graph_traits<MutableGraph>::edge_descriptor edge_descriptor;\n  typedef typename graph_traits<MutableGraph>::vertices_size_type\n    vertices_size_type;\n\n  if (edges(g).first == edges(g).second) return;\n\n  // Function object that compares the centrality of edges\n  indirect_cmp<EdgeCentralityMap, std::less<centrality_type> > \n    cmp(edge_centrality);\n\n  bool is_done;\n  do {\n    brandes_betweenness_centrality(g, \n                                   edge_centrality_map(edge_centrality)\n                                   .vertex_index_map(vertex_index));\n    edge_descriptor e = *max_element(edges(g).first, edges(g).second, cmp);\n    centrality_type max_centrality = get(edge_centrality, e);\n    is_done = done(get(edge_centrality, e), e, g);\n    if (!is_done) remove_edge(e, g);\n  } while (!is_done && edges(g).first != edges(g).second);\n}\n\n/**\n * \\overload\n */ \ntemplate<typename MutableGraph, typename Done, typename EdgeCentralityMap>\nvoid \nbetweenness_centrality_clustering(MutableGraph& g, Done done,\n                                  EdgeCentralityMap edge_centrality)\n{\n  betweenness_centrality_clustering(g, done, edge_centrality,\n                                    get(vertex_index, g));\n}\n\n/**\n * \\overload\n */ \ntemplate<typename MutableGraph, typename Done>\nvoid\nbetweenness_centrality_clustering(MutableGraph& g, Done done)\n{\n  typedef typename Done::centrality_type centrality_type;\n  std::vector<centrality_type> edge_centrality(num_edges(g));\n  betweenness_centrality_clustering(g, done, \n    make_iterator_property_map(edge_centrality.begin(), get(edge_index, g)),\n    get(vertex_index, g));\n}\n\n} // end namespace boost\n\n#endif // BOOST_GRAPH_BETWEENNESS_CENTRALITY_CLUSTERING_HPP\n", "meta": {"hexsha": "4fe407b07a767c44324e1407de2290f7b6c44be1", "size": 5954, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/bc_clustering.hpp", "max_stars_repo_name": "Imperator-Knoedel/Sunset", "max_stars_repo_head_hexsha": "19c95f4844586b96341f3474b58e0dacaae485b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-05T18:36:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-05T18:36:14.000Z", "max_issues_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/bc_clustering.hpp", "max_issues_repo_name": "Imperator-Knoedel/Sunset", "max_issues_repo_head_hexsha": "19c95f4844586b96341f3474b58e0dacaae485b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CvGameCoreDLL/Boost-1.32.0/include/boost/graph/bc_clustering.hpp", "max_forks_repo_name": "Imperator-Knoedel/Sunset", "max_forks_repo_head_hexsha": "19c95f4844586b96341f3474b58e0dacaae485b9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8674698795, "max_line_length": 79, "alphanum_fraction": 0.7297615049, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.4184991492345052}}
{"text": "/* dos_estimate_quartic.cc\n \nCopyright 2018 Grant M. Rotskoff\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n */\n\n#include <armadillo>\n#include \"particles.h\"\n#include \"quartic.h\"\n\n\nint main(int argc, char **argv)\n{\n\n  arma_rng::set_seed(45632426);\n  quartic g;\n  int dim = atoi(argv[1]);\n  double gamma = atof(argv[2]);\n  g.initialize(dim, gamma);\n  double hmin = 0.;\n  double hmax = 2. * dim;\n  double hres = 0.5;\n\n  g.qmin = -pow(4*hmax,0.25);\n  g.qmax = pow(4*hmax,0.25);\n\n  // set the integration parameters\n  double dt = 1e-3;\n  double tol = 1e-6;\n  int max_iter = 0;\n  bool use_mc = false;\n\n  int n_traj = atoi(argv[3]);\n  g.initialize_integration_variables(dt, gamma);\n  g.initialize_estimator(hmax, hres, hmin, n_traj);\n  // run the estimation trajectories\n  for (int i=0; i<n_traj; i++) {\n    g.run_estimation_trajectory(tol, hmax, max_iter, i, langevin, use_mc);\n  }\n  char dos_filename[80];\n  sprintf(dos_filename, \"quartic_dim=%03d_gamma=%05.3f_ntraj=%04d.dat\", dim, gamma, n_traj);\n  FILE *dosf = fopen(dos_filename, \"w\");\n  g.dump_dos_estimate(n_traj, dosf);\n}\n", "meta": {"hexsha": "04388ffa19db2674888eca76599e50a71b1cfdfb", "size": 2053, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/dos_estimate_quartic.cc", "max_stars_repo_name": "rotskoff/trajectory_estimators", "max_stars_repo_head_hexsha": "d4e757d85c1cc1b9826d68138f14ee4b7e3d02d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dos_estimate_quartic.cc", "max_issues_repo_name": "rotskoff/trajectory_estimators", "max_issues_repo_head_hexsha": "d4e757d85c1cc1b9826d68138f14ee4b7e3d02d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dos_estimate_quartic.cc", "max_forks_repo_name": "rotskoff/trajectory_estimators", "max_forks_repo_head_hexsha": "d4e757d85c1cc1b9826d68138f14ee4b7e3d02d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2549019608, "max_line_length": 460, "alphanum_fraction": 0.7379444715, "num_tokens": 531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.41849913981694487}}
{"text": "#include \"tasktorrent/tasktorrent.hpp\"\n#ifdef USE_MKL\n#include <mkl_cblas.h>\n#include <mkl_lapacke.h>\n#else\n#include <cblas.h>\n#include <lapacke.h>\n#endif\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <fstream>\n#include <array>\n#include <random>\n#include <mutex>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <set>\n\n#include <mpi.h>\n#include <cxxopts.hpp>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace ttor;\n\ntypedef array<int, 2> int2;\ntypedef array<int, 3> int3;\n\n/*\nParametrized priorities for cholesky:\n0. No priority, only enforces potrf>trsm>gemm\n1. Row-based priority, prioritize tasks with smaller row number in addition to priority 0.\n2. Critical path priority, prioritize tasks with longest distance to the exit task. For references, check out the paper\n    Beaumont, Olivier, et al. \"A Makespan Lower Bound for the Scheduling of the Tiled Cholesky Factorization based on ALAP Schedule.\" (2020).\n3. Critical path and row priority, prioritize tasks with smaller row number in addition to priority 2. We also enforces potrf>trsm>gemm\n*/\n\nenum PrioKind { no = 0, row = 1, cp = 2, cp_row = 3};\n\nvoid cholesky(const int n_threads, const int verb, const int block_size, const int num_blocks, const int nprows, const int npcols, \n              const PrioKind prio_kind, const bool log, const bool deps_log, const bool test, const int accumulate_parallel, const int upper_block_size)\n{\n    const int rank = comm_rank();\n    const int n_ranks = comm_size();\n    const int matrix_size = block_size * num_blocks;\n    assert(nprows * npcols == n_ranks);\n    std::atomic<long long int> potrf_us_t(0);\n    std::atomic<long long int> trsm_us_t(0);\n    std::atomic<long long int> gemm_us_t(0);\n    std::atomic<long long int> accu_us_t(0);\n\n    // Warmup MKL\n    {\n        Eigen::MatrixXd A = Eigen::MatrixXd::Identity(256,256);\n        Eigen::MatrixXd B = Eigen::MatrixXd::Identity(256,256);\n        Eigen::MatrixXd C = Eigen::MatrixXd::Identity(256,256);\n        for(int i = 0; i < 10; i++) {\n            cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 256, 256, 256, 1.0, A.data(), 256, B.data(), 256, 1.0, C.data(), 256);\n        }\n    }\n\n    // Compute random sizes\n    std::mt19937 gen(2020);\n    assert(upper_block_size <= 2*block_size);\n    const int lower_block_size = 2*block_size - upper_block_size;\n    std::uniform_int_distribution<> distrib(lower_block_size,upper_block_size); // average is block_size\n    if(rank == 0) printf(\"lower_block_size %d, upper_block_size %d\\n\", lower_block_size, upper_block_size);\n    std::vector<int> block_sizes(num_blocks, block_size);\n    {\n        int n = 0;\n        for(int i = 0; i < num_blocks-1; i++) {\n            int bs = std::min(matrix_size - n, distrib(gen));\n            n += bs;\n            block_sizes[i] = bs;\n        }\n        assert(matrix_size - n >= 0);\n        block_sizes[num_blocks-1] = matrix_size - n;\n    }\n    int total = std::accumulate(block_sizes.begin(), block_sizes.end(), 0);\n    assert(total == matrix_size);\n    std::vector<int> block_displ(num_blocks+1, 0);\n    for(int i = 1; i < num_blocks+1; i++) {\n        block_displ[i] = block_displ[i-1] + block_sizes[i-1];\n    }\n    std::vector<int> block_sizes_lda(num_blocks, 0);\n    for(int i = 0; i < num_blocks; i++) {\n        block_sizes_lda[i] = std::max(1, block_sizes[i]);\n    }\n    assert(block_displ[num_blocks] == matrix_size);\n    if(rank == 0) {\n        printf(\"block sizes: \");\n        for(int i = 0; i < num_blocks; i++) { \n            assert(block_sizes[i] >= 0);\n            printf(\"%d \", block_sizes[i]); \n        };\n        printf(\"\\n\");\n        printf(\"block displ: \");\n        for(int i = 0; i < num_blocks+1; i++) { \n            assert(block_displ[i] >= 0);\n            printf(\"%d \", block_displ[i]); \n        };\n        printf(\"\\n\");\n    }\n    \n    // Map tasks to ranks\n    auto block_2_rank = [&](int i, int j) {\n        assert(i >= 0 && i < num_blocks);\n        assert(j >= 0 && j < num_blocks);\n        int r = (j % npcols) * nprows + (i % nprows);\n        assert(r >= 0 && r < n_ranks);\n        return r;\n    };\n\n    const int rank_row = (rank % nprows);\n    const int rank_col = (rank / nprows);\n    auto block_2_rank_row = [&](int i, int j) {\n        return i % nprows;\n    };\n    auto block_2_rank_col = [&](int i, int j) {\n        return j % npcols;\n    };\n\n    // Map threads to ranks\n    auto block_2_thread = [&](int i, int j) {\n        int ii = i / nprows;\n        int jj = j / npcols;\n        int num_blocksit = num_blocks / nprows;\n        return (ii + jj * num_blocksit) % n_threads;\n    };\n\n    // Initializes the matrix\n    auto val = [&](int i, int j) { return 1/(double)((i-j)*(i-j)+1); };\n    vector<unique_ptr<MatrixXd>> blocks(num_blocks*num_blocks);\n    for (int ii=0; ii<num_blocks; ii++) {\n        for (int jj=0; jj<num_blocks; jj++) {\n            auto val_loc = [&](int i, int j) { return val(block_displ[ii]+i,block_displ[jj]+j); };\n            if(ii >= jj) {\n                if(block_2_rank(ii,jj) == rank) {\n                    blocks[ii+jj*num_blocks]=make_unique<MatrixXd>(block_sizes[ii],block_sizes[jj]);\n                    *blocks[ii+jj*num_blocks]=MatrixXd::NullaryExpr(block_sizes[ii],block_sizes[jj], val_loc);\n                } else {\n                    blocks[ii+jj*num_blocks]=make_unique<MatrixXd>(0,0);\n                }\n            }\n        }\n    }\n\n    // Holds the temporary matrices result of gemm to be accumulated by accu\n    // Each block holds data to be accumulated into a given block[ii+jj*num_blocks]\n    struct acc_data {\n        std::map<int, std::unique_ptr<MatrixXd>> to_accumulate; // to_accumulate[k] holds matrix result of gemm(k,i,j)\n        std::mutex mtx; // Protects that map\n    };\n    std::vector<acc_data> gemm_results(num_blocks*num_blocks); // gemm_results[ii+jj*num_blocks] holds the data to be accumulated into blocks[ii+jj*num_blocks]\n\n    // Set priorities\n    auto potf_block_2_prio = [&](int j) {\n        if (prio_kind == PrioKind::cp_row) {\n            return (double)(9*(num_blocks - j)-1) + 18 * num_blocks * num_blocks;\n        }\n        else if(prio_kind == PrioKind::cp) {\n            return (double)(9*(num_blocks - j)-1);\n        } \n        else if(prio_kind == PrioKind::row) {\n            return 3.0*(double)(num_blocks-j);\n        } \n        else {\n            return 3.0;\n        }\n    };\n    auto trsm_block_2_prio = [&](int2 ij) {\n        if (prio_kind == PrioKind::cp_row) {\n            return (double)((num_blocks - ij[0]) + num_blocks * (9.0 * num_blocks - 9.0 * ij[1] - 2.0) + 9 * num_blocks * num_blocks);\n        }\n        else if(prio_kind == PrioKind::cp) {\n            return (double)(9*(num_blocks - ij[1])-2);\n        } \n        else if(prio_kind == PrioKind::row) {\n            return 2.0*(double)(num_blocks - ij[0]);\n        } \n        else {\n            return 2.0;\n        }\n    };\n    auto gemm_block_2_prio = [&](int3 kij) {\n        if (prio_kind == PrioKind::cp_row) {\n            if (accumulate_parallel) {\n                return (double)(num_blocks - kij[1]) + num_blocks * (9.0 * num_blocks - 9.0 * kij[2] - 2.0);\n            }\n            else {\n                return (double)(num_blocks - kij[1]) + num_blocks * (9.0 * num_blocks - 3.0 * kij[2] - 6.0 * kij[0] - 2.0);\n            }\n        }\n        else if(prio_kind == PrioKind::cp) {\n            return (double)(9*num_blocks-9*kij[2]-2);\n        } \n        else if(prio_kind == PrioKind::row) {\n            return (double)(num_blocks - kij[1]);\n        } \n        else {\n            return 1.0;\n        }\n    };\n    // Names\n    auto potrf_name = [](int j) {\n        return \"POTRF_\" + to_string(j);\n    };\n    auto trsm_name = [](int2 ij) {\n        return \"TRSM_\" + to_string(ij[0]) + \"_\" + to_string(ij[1]);\n    };\n    auto gemm_name = [](int3 kij) {\n        return \"GEMM_\" + to_string(kij[0]) + \"_\" + to_string(kij[1]) + \"_\" + to_string(kij[2]);\n    };\n    auto accu_name = [](int3 kij) {\n        return \"ACCU_\" + to_string(kij[0]) + \"_\" + to_string(kij[1]) + \"_\" + to_string(kij[2]);\n    };\n\n    const int num_blocksmax = 15;\n    MPI_Barrier(MPI_COMM_WORLD);\n    if(comm_rank() == 0) {\n        printf(\"Block -> Rank\\n\");\n        for(int i = 0; i < min(num_blocksmax, num_blocks); i++) {\n            for(int j = 0; j < min(num_blocksmax, num_blocks); j++) {\n                if(i >= j) {\n                    printf(\"%2d \", block_2_rank(i, j));\n                }\n            }\n            printf(\"\\n\");\n        }\n        printf(\"Potf/trsm -> Priority\\n\");\n        for(int i = 0; i < min(num_blocksmax, num_blocks); i++) {\n            for(int j = 0; j < min(num_blocksmax, num_blocks); j++) {\n                if(i == j) {\n                    printf(\"%5f \", potf_block_2_prio(i));\n                } else if (i > j) {\n                    printf(\"%5f \", trsm_block_2_prio({i,j}));\n                };\n            }\n            printf(\"\\n\");\n        }\n        printf(\"Gemm -> Priority\\n\");\n        for(int k = 0; k < min(num_blocksmax, num_blocks); k++) {\n            printf(\"k = %d\\n\", k);\n            for(int i = 0; i < min(num_blocksmax, num_blocks); i++) {\n                for(int j = 0; j < min(num_blocksmax, num_blocks); j++) {\n                    if(i >= j) {\n                        if(k < j) {\n                            printf(\"%5f \", gemm_block_2_prio({k,i,j}));\n                        } else {\n                            printf(\".     \");\n                        }\n                    }\n                }\n                printf(\"\\n\");\n            }\n        }\n    }\n    for(int r = 0; r < ttor::comm_size(); r++) {\n        if(r == comm_rank()) {\n            printf(\"[%d] Block -> thread\\n\", r);\n            for(int i = 0; i < min(num_blocksmax, num_blocks); i++) {\n                for(int j = 0; j < min(num_blocksmax, num_blocks); j++) {\n                    if(i >= j && block_2_rank(i,j) == r) {\n                        printf(\"%2d \", block_2_thread(i, j));\n                    } else {\n                        printf(\" . \");\n                    }\n                }\n                printf(\"\\n\");\n            }\n        }\n        MPI_Barrier(MPI_COMM_WORLD);\n    }\n\n    // Initialize the communicator structure\n    Communicator comm(MPI_COMM_WORLD, verb);\n\n    // Initialize the runtime structures\n    Threadpool tp(n_threads, &comm, verb, \"Wk_Chol_\" + to_string(rank) + \"_\");\n    Taskflow<int>  potrf(&tp, verb);\n    Taskflow<int2> trsm(&tp, verb);\n    Taskflow<int3> gemm(&tp, verb);\n    Taskflow<int3> accu(&tp, verb);\n\n    Logger logger(1000000);\n    if(log) {\n        tp.set_logger(&logger);\n        comm.set_logger(&logger);\n    }\n\n    DepsLogger dlog(1000000);\n\n    // Send a potrf'ed pivot A(k,k) and trigger trsms below requiring A(k,k)\n    auto am_trsm = comm.make_large_active_msg( \n            [&](int& j) {\n                int off = (nprows + rank_row - block_2_rank_row(j,j)) % nprows;\n                assert(off > 0); // Can't be me\n                assert(off < nprows);\n                for (int i = j + off; i < num_blocks; i += nprows) {\n                    assert(block_2_rank(i,j) == rank);\n                    trsm.fulfill_promise({i,j});\n                }\n            },\n            [&](int& j) {\n                blocks[j+j*num_blocks]->resize(block_sizes[j],block_sizes[j]);\n                return blocks[j+j*num_blocks]->data();\n            },\n            [&](int&){\n                return;\n            });\n\n    /**\n     * j is the pivot's position at A(j,j)\n     */\n    potrf.set_task([&](int j) { // A[j,j] -> A[j,j]\n            assert(block_2_rank(j,j) == rank);\n            timer t_ = wctime();\n            LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', block_sizes[j], blocks[j+j*num_blocks]->data(), block_sizes_lda[j]);\n            timer t__ = wctime();\n            potrf_us_t += 1e6 * elapsed(t_, t__);\n        })\n        .set_fulfill([&](int j) { // Triggers all trsms on rows i > j, A[i,j]\n            assert(block_2_rank(j,j) == rank);\n            if(deps_log) {\n                for(int i = j+1; i < num_blocks; i++) {\n                    dlog.add_event(make_unique<DepsEvent>(potrf.name(j), trsm.name({i,j})));\n                }\n            }\n            // Trigger myself\n            for (int i = j + nprows; i < num_blocks; i += nprows) {\n                assert(block_2_rank(i,j) == rank);\n                trsm.fulfill_promise({i,j});\n            }\n            // Send to other procs in column\n            auto Ljjv = view<double>(blocks[j+j*num_blocks]->data(), block_sizes[j]*block_sizes[j]);\n            for(int p = 0; p < nprows; p++) {\n                if(j+p >= num_blocks) break;\n                int dest = block_2_rank(j+p,j);\n                if(dest != rank) {\n                    am_trsm->send_large(dest, Ljjv, j);\n                }\n            }\n\n        })\n        .set_indegree([&](int j) {\n            assert(block_2_rank(j,j) == rank);\n            if(accumulate_parallel) {\n                return j == 0 ? 1 : j; // Need j accumulations into (j,j) to trigger the potf\n            } else {\n                return 1;\n            }\n        })\n        .set_priority(potf_block_2_prio)\n        .set_mapping([&](int j) {\n            assert(block_2_rank(j,j) == rank);\n            return block_2_thread(j, j);\n        })\n        .set_name([&](int j) { // This is just for debugging and profiling\n            return potrf_name(j);\n        });\n\n    // Sends a panel (trsm'ed block A(i,j)) and trigger gemms requiring A(i,j)\n    auto am_gemm = comm.make_large_active_msg(\n        [&](int& i, int& j) {\n            if(block_2_rank_row(i,j) == rank_row) {\n                const int off_right = (npcols + rank_col - block_2_rank_col(i,j)) % npcols;\n                assert(off_right > 0); // Can't be me\n                assert(off_right < npcols);\n                assert(i >= 0 && i < num_blocks);\n                assert(j >= 0 && j < num_blocks);\n                for (int k = j + off_right; k < i; k += npcols) {\n                    assert(block_2_rank(i,k) == rank);\n                    gemm.fulfill_promise({j,i,k});\n                }\n            }\n            if(block_2_rank_col(i,i) == rank_col) {\n                const int off_below = (nprows + rank_row - block_2_rank_row(i,i)) % nprows;\n                assert(off_below >= 0); // Could be me\n                assert(off_below < nprows);\n                for (int k = i + off_below; k < num_blocks; k += nprows) {\n                    assert(block_2_rank(k,i) == rank);\n                    gemm.fulfill_promise({j,k,i});\n                }\n            }\n        },\n        [&](int& i, int& j) {\n            blocks[i+j*num_blocks]->resize(block_sizes[i],block_sizes[j]);\n            return blocks[i+j*num_blocks]->data();\n        },\n        [&](int& i, int& j) {\n            return;\n        });\n\n    /**\n     * ij is (Row, Col) of the block in the matrix at A(i,j)\n     **/\n    trsm.set_task([&](int2 ij) { // A[j,j] & A[i,j] -> A[i,j]\n            int i=ij[0]; \n            int j=ij[1]; \n            assert(block_2_rank(i,j) == rank);\n            assert(i > j);\n            timer t_ = wctime();\n            cblas_dtrsm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit, \n                block_sizes[i], block_sizes[j], 1.0, blocks[j+j*num_blocks]->data(), block_sizes_lda[j], blocks[i+j*num_blocks]->data(), block_sizes_lda[i]);\n            timer t__ = wctime();\n            trsm_us_t += 1e6 * elapsed(t_, t__);\n        })\n        .set_fulfill([&](int2 ij) {\n            int i=ij[0];\n            int j=ij[1];\n            assert(block_2_rank(i,j) == rank);\n            assert(i > j);\n            if(deps_log) {\n                for(int k = j+1; k < num_blocks; k++) {\n                    dlog.add_event(make_unique<DepsEvent>(trsm.name(ij), gemm.name({j,std::max(i,k),std::min(i,k)})));\n                }\n            }\n            // Local\n            // Careful to not count the pivot (syrk) twice\n            for (int k = j + npcols; k < i; k += npcols) {\n                assert(block_2_rank(i,k) == rank);\n                gemm.fulfill_promise({j,i,k});\n            }\n            if(block_2_rank_col(i,i) == rank_col) {\n                int off_below = (nprows + rank_row - block_2_rank_row(i,i)) % nprows;\n                for (int k = i + off_below; k < num_blocks; k += nprows) {\n                    assert(block_2_rank(k,i) == rank);\n                    gemm.fulfill_promise({j,k,i});\n                }\n            }\n            // Remote\n            auto Lijv = view<double>(blocks[i+j*num_blocks]->data(), block_sizes[i]*block_sizes[j]);\n            std::set<int> dests;\n            for (int c = 0; c < npcols; c++) {\n                if(j+c >= num_blocks) break;\n                int dest = block_2_rank(i,j+c);\n                if(dest != rank) dests.insert(dest);\n            }\n            for (int r = 0; r < nprows; r++) {\n                if(i+r >= num_blocks) break;\n                int dest = block_2_rank(i+r,i);\n                if(dest != rank) dests.insert(dest);\n            }\n            for(auto& dest: dests) {\n                am_gemm->send_large(dest, Lijv, i, j);\n            }\n        })\n        .set_indegree([&](int2 ij) {\n            assert(block_2_rank(ij[0],ij[1]) == rank);\n            if(accumulate_parallel) {\n                return 1 + ij[1]; // Potrf above and all gemms before\n            } else {\n                return 1 + (ij[1] == 0 ? 0 : 1); // Potrf and last gemm before\n            }\n        })\n        .set_priority(trsm_block_2_prio)\n        .set_mapping([&](int2 ij) {\n            assert(block_2_rank(ij[0],ij[1]) == rank);\n            return block_2_thread(ij[0], ij[1]);\n        })\n        .set_name([&](int2 ij) { // This is just for debugging and profiling\n            return trsm_name(ij);\n        });\n\n    /**\n     * k is the step (the pivot's position), ij are Row and Column, at A(i,j)\n     **/\n    gemm.set_task([&](int3 kij) {\n            assert(block_2_rank(kij[1],kij[2]) == rank);\n            const int k=kij[0];\n            const int i=kij[1];\n            const int j=kij[2];\n            assert(j <= i);\n            assert(k < j);\n            std::unique_ptr<MatrixXd> Atmp;\n            MatrixXd* Aij;\n            double beta = 1.0;\n            if(accumulate_parallel) {\n                beta = 0.0;\n                Atmp = make_unique<MatrixXd>(block_sizes[i], block_sizes[j]); // The matrix is allocated with garbage. The 0 in the BLAS call make sure its overwritten by 0's before doing any math\n                Aij = Atmp.get();\n            } else {\n                beta = 1.0;\n                Aij = blocks[i+j*num_blocks].get();\n            }\n            assert(Aij->rows() == block_sizes[i] && Aij->cols() == block_sizes[j]);\n            timer t_ = wctime();\n            if (i == j) {\n                cblas_dsyrk(CblasColMajor, CblasLower, CblasNoTrans, \n                    block_sizes[i], block_sizes[k], -1.0, blocks[i+k*num_blocks]->data(), block_sizes_lda[i], beta, Aij->data(), block_sizes_lda[i]);\n            } else {\n                cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, \n                    block_sizes[i], block_sizes[j], block_sizes[k], -1.0, blocks[i+k*num_blocks]->data(), block_sizes_lda[i], blocks[j+k*num_blocks]->data(), block_sizes_lda[j], beta, Aij->data(), block_sizes_lda[i]);\n            }\n            timer t__ = wctime();\n            gemm_us_t += 1e6 * elapsed(t_, t__);\n            if(accumulate_parallel) {\n                lock_guard<mutex> lock(gemm_results[i+j*num_blocks].mtx);\n                gemm_results[i+j*num_blocks].to_accumulate[k] = move(Atmp);\n            }\n        })\n        .set_fulfill([&](int3 kij) {\n            const int k=kij[0];\n            const int i=kij[1];\n            const int j=kij[2];\n            assert(block_2_rank(kij[1],kij[2]) == rank);\n            if(accumulate_parallel) {\n                if(deps_log) {\n                    dlog.add_event(make_unique<DepsEvent>(gemm.name(kij), accu.name(kij)));\n                }\n                accu.fulfill_promise(kij);\n            } else {\n                if (k < j-1) {\n                    if(deps_log) {\n                        dlog.add_event(make_unique<DepsEvent>(gemm.name(kij), gemm.name({k+1, i, j})));\n                    }\n                    gemm.fulfill_promise({k+1, i, j});\n                } else {\n                    if (i == j) {\n                        if(deps_log) {\n                            dlog.add_event(make_unique<DepsEvent>(gemm.name(kij), potrf.name(i)));\n                        }\n                        potrf.fulfill_promise(i);\n                    } else {\n                        if(deps_log) {\n                            dlog.add_event(make_unique<DepsEvent>(gemm.name(kij), trsm.name({i,j})));\n                        }\n                        trsm.fulfill_promise({i,j});\n                    }\n                }\n            }\n        })\n        .set_indegree([&](int3 kij) {\n            assert(block_2_rank(kij[1],kij[2]) == rank);\n            if(accumulate_parallel) {\n                return kij[1] == kij[2] ? 1 : 2; // Either one potf or two trsms\n            } else {\n                return (kij[1] == kij[2] ? 1 : 2) + (kij[0] == 0 ? 0 : 1); // one potrf or two trsms + the gemm before\n            }\n        })\n        .set_priority(gemm_block_2_prio)\n        .set_mapping([&](int3 kij) {\n            assert(block_2_rank(kij[1],kij[2]) == rank);\n            return block_2_thread(kij[1], kij[2]); // IMPORTANT if accumulate_parallel is true\n        })\n        .set_binding([&](int3 kij) {\n            return false; // If we accumulate in parallel, there is no order for the gemm so it doesnt matter ; If we don't then we do the gemm in sequence anyway\n        }).set_name([&](int3 kij) { // This is just for debugging and profiling\n            return gemm_name(kij);\n        });\n\n    /**\n     * k is the step (the pivot's position), ij are Row and Column, at A(i,j)\n     **/\n    accu.set_task([&](int3 kij) {\n            assert(block_2_rank(kij[1],kij[2]) == rank);\n            int k=kij[0]; // Step (gemm's pivot)\n            int i=kij[1]; // Row\n            int j=kij[2]; // Col\n            assert(j <= i);\n            assert(k < j);\n            std::unique_ptr<Eigen::MatrixXd> Atmp;\n            {\n                lock_guard<mutex> lock(gemm_results[i+j*num_blocks].mtx);\n                Atmp = move(gemm_results[i+j*num_blocks].to_accumulate[k]);\n                gemm_results[i+j*num_blocks].to_accumulate.erase(k);\n            }\n            timer t_ = wctime();\n            *blocks[i+j*num_blocks] += (*Atmp);\n            timer t__ = wctime();\n            accu_us_t += 1e6 * elapsed(t_, t__);\n        })\n        .set_fulfill([&](int3 kij) {\n            assert(block_2_rank(kij[1],kij[2]) == rank);\n            int k=kij[0];\n            int i=kij[1];\n            int j=kij[2];\n            assert(j <= i);\n            assert(k < j);\n            if(i == j) {\n                if(deps_log) {\n                    dlog.add_event(make_unique<DepsEvent>(accu.name(kij), potrf.name(i)));\n                }\n                potrf.fulfill_promise(i);\n            } else {\n                if(deps_log) {\n                    dlog.add_event(make_unique<DepsEvent>(accu.name(kij), trsm.name({i,j})));\n                }\n                trsm.fulfill_promise({i,j});\n            }\n        })\n        .set_indegree([&](int3 kij) {\n            assert(block_2_rank(kij[1],kij[2]) == rank);\n            return 1;\n        })\n        .set_mapping([&](int3 kij) {\n            assert(block_2_rank(kij[1],kij[2]) == rank);\n            return block_2_thread(kij[1], kij[2]); // IMPORTANT. Every (i,j) should map to a given fixed thread\n        })\n        .set_priority(gemm_block_2_prio)\n        .set_binding([&](int3 kij) {\n            assert(block_2_rank(kij[1],kij[2]) == rank);\n            return true; // IMPORTANT\n        })\n        .set_name([&](int3 kij) { // This is just for debugging and profiling\n            return accu_name(kij);\n        });\n\n    printf(\"Starting Cholesky factorization...\\n\");\n    MPI_Barrier(MPI_COMM_WORLD);\n    timer t0 = wctime();\n    if (rank == 0){\n        potrf.fulfill_promise(0);\n    }\n    tp.join();\n    MPI_Barrier(MPI_COMM_WORLD);\n    timer t1 = wctime();\n    double total_time = elapsed(t0, t1);\n    printf(\"Done with Cholesky factorization...\\n\");\n    printf(\"Elapsed time: %e\\n\", total_time);\n    printf(\"Potrf time: %e\\n\", potrf_us_t.load() * 1e-6);\n    printf(\"Trsm time: %e\\n\", trsm_us_t.load() * 1e-6);\n    printf(\"Gemm time: %e\\n\", gemm_us_t.load() * 1e-6);\n    printf(\"Accu time: %e\\n\", accu_us_t.load() * 1e-6);\n\n    printf(\"++++rank nranks n_threads matrix_size block_size num_blocks priority_kind accumulate upper_block_size total_time\\n\");\n    printf(\"[%d]>>>>%d %d %d %d %d %d %d %d %d %e\\n\",rank,rank,n_ranks,n_threads,matrix_size,block_size,num_blocks,(int)prio_kind,(int)accumulate_parallel,upper_block_size,total_time);\n\n    if(log) {\n        std::ofstream logfile;\n        string filename = \"ttor_dist_\"+to_string(block_size)+\"_\"+to_string(num_blocks)+\"_\"+ to_string(n_ranks)+\"_\"+to_string(n_threads)+\"_\"+to_string(prio_kind)+\".log.\"+to_string(rank);\n        logfile.open(filename);\n        logfile << logger;\n        logfile.close();\n    }\n\n    if(deps_log) {\n        std::ofstream depsfile;\n        string depsfilename = \"deps_ttor_dist_\"+to_string(block_size)+\"_\"+to_string(num_blocks)+\"_\"+ to_string(n_ranks)+\"_\"+to_string(n_threads)+\"_\"+to_string(prio_kind)+\".dot.\"+to_string(rank);\n        depsfile.open(depsfilename);\n        depsfile << dlog;\n        depsfile.close();\n    }\n\n    if(test) {\n        printf(\"Starting sending matrix to rank 0...\\n\");\n        MatrixXd A = MatrixXd::NullaryExpr(matrix_size,matrix_size,val);\n        MatrixXd L = MatrixXd::Zero(matrix_size,matrix_size);\n        // Send the matrix to rank 0\n        for (int ii=0; ii<num_blocks; ii++) {\n            for (int jj=0; jj<num_blocks; jj++) {\n                if (jj<=ii)  {\n                    int owner = block_2_rank(ii,jj);\n                    MPI_Status status;\n                    if (rank == 0 && rank != owner) { // Careful with deadlocks here\n                        blocks[ii+jj*num_blocks] = make_unique<Eigen::MatrixXd>(block_sizes[ii], block_sizes[jj]);\n                        MPI_Recv(blocks[ii+jj*num_blocks]->data(), block_sizes[ii]*block_sizes[jj], MPI_DOUBLE, owner, 0, MPI_COMM_WORLD, &status);\n                    } else if (rank != 0 && rank == owner) {\n                        MPI_Send(blocks[ii+jj*num_blocks]->data(), block_sizes[ii]*block_sizes[jj], MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);\n                    }\n                }\n            }\n        }\n\n        // Rank 0 test\n        if(rank == 0) {\n            printf(\"Starting test on rank 0...\\n\");\n            for (int ii=0; ii<num_blocks; ii++) {\n                for (int jj=0; jj<num_blocks; jj++) {\n                    if (jj<=ii) {\n                        L.block(block_displ[ii],block_displ[jj],block_sizes[ii],block_sizes[jj])=*blocks[ii+jj*num_blocks];\n                    }\n                }\n            }\n            auto L1=L.triangularView<Lower>();\n            VectorXd x = VectorXd::Random(matrix_size);\n            VectorXd b = A*x;\n            VectorXd bref = b;\n            L1.solveInPlace(b);\n            L1.transpose().solveInPlace(b);\n            double error = (b - x).norm() / x.norm();\n            printf(\"\\n=> Error solve %e\\n\\n\", error);\n            if(error > 1e-6) {\n                printf(\"\\n\\nERROR: error is too large!\\n\\n\");\n                exit(1);\n            }\n        }\n    }\n}\n\nint main(int argc, const char **argv)\n{\n    int req = MPI_THREAD_FUNNELED;\n    int prov = -1;\n\n    MPI_Init_thread(NULL, NULL, req, &prov);\n\n    assert(prov == req);\n\n    std::stringstream sstr;\n    sstr << comm_size();\n    const std::string comm_size_str = sstr.str();\n\n    cxxopts::Options options(\"2d_cholesky\", \"2D dense cholesky using TaskTorrent\");\n    options.add_options()\n        (\"help\", \"Print help\")\n        (\"n_threads\", \"Number of threads\", cxxopts::value<int>()->default_value(\"2\"))\n        (\"verb\", \"Verbosity level\", cxxopts::value<int>()->default_value(\"0\"))\n        (\"block_size\", \"Block size\", cxxopts::value<int>()->default_value(\"5\"))\n        (\"num_blocks\", \"Number of blocks\", cxxopts::value<int>()->default_value(\"10\"))\n        (\"nprows\", \"Number of processors accross rows\", cxxopts::value<int>()->default_value(\"1\"))\n        (\"npcols\", \"Number of processors accross columns\", cxxopts::value<int>()->default_value(comm_size_str.c_str()))\n        (\"kind\", \"Priority kind\", cxxopts::value<int>()->default_value(\"0\"))\n        (\"log\", \"Enable logging\", cxxopts::value<bool>()->default_value(\"false\"))\n        (\"depslog\", \"Enable dependency logging\", cxxopts::value<bool>()->default_value(\"false\"))\n        (\"test\", \"Test or not\", cxxopts::value<bool>()->default_value(\"true\"))\n        (\"accumulate\", \"Accumulate block GEMMs in parallel\", cxxopts::value<bool>()->default_value(\"false\"))\n        (\"upper_block_size\", \"Upper block size\", cxxopts::value<int>()->default_value(\"-1\"));\n    auto result = options.parse(argc, argv);\n\n    const int n_threads = result[\"n_threads\"].as<int>();\n    const int verb = result[\"verb\"].as<int>();\n    const int block_size = result[\"block_size\"].as<int>();\n    const int num_blocks = result[\"num_blocks\"].as<int>();\n    const int nprows = result[\"nprows\"].as<int>();\n    const int npcols = result[\"npcols\"].as<int>();\n    const PrioKind kind = (PrioKind) result[\"kind\"].as<int>();\n    const bool log = result[\"log\"].as<bool>();\n    const bool depslog = result[\"depslog\"].as<bool>();\n    const bool test = result[\"test\"].as<bool>();\n    const bool accumulate = result[\"accumulate\"].as<bool>();\n    const int upper_block_size = (result[\"upper_block_size\"].as<int>() == -1 ? block_size : result[\"upper_block_size\"].as<int>());\n\n    assert(block_size > 0);\n    assert(num_blocks > 0);\n    assert(n_threads > 0);\n    assert(verb >= 0);\n    assert(nprows >= 0);\n    assert(npcols >= 0);\n    assert(upper_block_size >= block_size && upper_block_size <= 2 * block_size);\n\n    if (result.count(\"help\")) {\n        std::cout << options.help({\"\", \"Group\"}) << endl;\n        exit(0);\n    }\n    if(comm_rank() == 0) printf(\"Arguments: block_size (size of blocks) %d\\nnum_blocks (# of blocks) %d\\nn_threads %d\\nverb %d\\nnprows %d\\nnpcols %d\\nkind %d\\nlog %d\\ndeplog %d\\ntest %d\\naccumulate %d\\nupper_block_size %d\\n\", block_size, num_blocks, n_threads, verb, nprows, npcols, (int)kind, log, depslog, test, accumulate, upper_block_size);\n\n    cholesky(n_threads, verb, block_size, num_blocks, nprows, npcols, kind, log, depslog, test, accumulate, upper_block_size);\n\n    MPI_Finalize();\n}\n", "meta": {"hexsha": "a8960ca3f26ae897fd82dcbab4b49202c52e10df", "size": 30614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "miniapp/dense_cholesky/2d_cholesky.cpp", "max_stars_repo_name": "Abeynaya/tasktorrent", "max_stars_repo_head_hexsha": "987718e6e9033ae8aa295323e4699e759d744e7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2019-09-29T19:33:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:48:40.000Z", "max_issues_repo_path": "miniapp/dense_cholesky/2d_cholesky.cpp", "max_issues_repo_name": "Abeynaya/tasktorrent", "max_issues_repo_head_hexsha": "987718e6e9033ae8aa295323e4699e759d744e7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-03-11T18:14:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-09T22:32:56.000Z", "max_forks_repo_path": "miniapp/dense_cholesky/2d_cholesky.cpp", "max_forks_repo_name": "Abeynaya/tasktorrent", "max_forks_repo_head_hexsha": "987718e6e9033ae8aa295323e4699e759d744e7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-10-22T06:40:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T08:17:39.000Z", "avg_line_length": 40.6560424967, "max_line_length": 344, "alphanum_fraction": 0.5183576142, "num_tokens": 8195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4184991316434253}}
{"text": "#include <boost/math/special_functions/next.hpp>\n#include <boost/random.hpp>\n\n#include <limits>\n#include <vector>\n\n#include \"caffe/common.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/rng.hpp\"\n\nnamespace caffe {\n\ntemplate<>\nvoid caffe_cpu_gemm<float,float>(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,\n    const float alpha, const float* A, const float* B, const float beta,\n    float* C) {\n  int lda = (TransA == CblasNoTrans) ? K : M;\n  int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_sgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B,\n      ldb, beta, C, N);\n}\n\ntemplate<>\nvoid caffe_cpu_gemm<double,double>(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,\n    const double alpha, const double* A, const double* B, const double beta,\n    double* C) {\n  int lda = (TransA == CblasNoTrans) ? K : M;\n  int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_dgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B,\n      ldb, beta, C, N);\n}\n\n#ifndef CPU_ONLY\ntemplate<>\nvoid caffe_cpu_gemm<float16,float16>(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,\n    const float16 alpha, const float16* A, const float16* B, const float16 beta,\n    float16* C) {\n}\ntemplate<>\nvoid caffe_cpu_gemm<float16,float>(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,\n    const float alpha, const float16* A, const float16* B, const float beta,\n    float16* C) {\n  if (M <= 0 || N <= 0 || K <= 0) {\n    return;\n  }\n  std::vector<float> a(M*K), b(K*N), c(M*N);\n  caffe_cpu_convert(a.size(), A, &a.front());\n  caffe_cpu_convert(b.size(), B, &b.front());\n  caffe_cpu_convert(c.size(), C, &c.front());\n  const int lda = (TransA == CblasNoTrans) ? K : M;\n  const int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_sgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, &a.front(), lda, &b.front(),\n      ldb, beta, &c.front(), N);\n  caffe_cpu_convert(c.size(), &c.front(), C);\n}\n#endif\n\ntemplate <>\nvoid caffe_cpu_gemv<float,float>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const float alpha, const float* A, const float* x,\n    const float beta, float* y) {\n  cblas_sgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_gemv<double,double>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const double alpha, const double* A, const double* x,\n    const double beta, double* y) {\n  cblas_dgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_cpu_gemv<float16,float>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const float alpha, const float16* A, const float16* x,\n    const float beta, float16* y) {\n  if (M <= 0 || N <= 0) {\n    return;\n  }\n  const int lx = (TransA == CblasNoTrans) ? N : M;\n  const int ly = (TransA == CblasNoTrans) ? M : N;\n  std::vector<float> a(M*N), xv(lx), yv(ly);\n  caffe_cpu_convert(a.size(), A, &a.front());\n  caffe_cpu_convert(xv.size(), x, &xv.front());\n  caffe_cpu_convert(yv.size(), y, &yv.front());\n  cblas_sgemv(CblasRowMajor, TransA, M, N, alpha, &a.front(), N, &xv.front(), 1, beta, &yv.front(), 1);\n  caffe_cpu_convert(yv.size(), &yv.front(), y);\n}\n\ntemplate <>\nvoid caffe_cpu_gemv<float16,float16>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const float16 alpha, const float16* A, const float16* xv,\n    const float16 beta, float16* y) {\n  //  cblas_hgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\n#endif\n\ntemplate <>\nvoid caffe_axpy<float,float>(const int N, const float alpha, const float* X,\n    float* Y) { cblas_saxpy(N, alpha, X, 1, Y, 1); }\n\ntemplate <>\nvoid caffe_axpy<double,double>(const int N, const double alpha, const double* X,\n    double* Y) { cblas_daxpy(N, alpha, X, 1, Y, 1); }\n\n#ifndef CPU_ONLY\n// TODO Consider CUDA\ntemplate<>\nvoid caffe_axpy<float16,float>(const int N, const float alpha, const float16* X, float16* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] = Get<float16>(alpha * Get<float>(X[i]) + Get<float>(Y[i]));\n  }\n}\ntemplate<>\nvoid caffe_axpy<float16,float16>(const int N, const float16 alpha, const float16* X, float16* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] = Get<float16>(Get<float>(alpha) * Get<float>(X[i]) + Get<float>(Y[i]));\n  }\n}\n#endif\n\ntemplate <typename Dtype>\nvoid caffe_set(const int N, const Dtype alpha, Dtype* Y) {\n  if (alpha == 0) {\n    memset(Y, 0, sizeof(Dtype) * N);  // NOLINT(caffe/alt_fn)\n    return;\n  }\n  for (int i = 0; i < N; ++i) {\n    Y[i] = alpha;\n  }\n}\n\ntemplate void caffe_set<int>(const int N, const int alpha, int* Y);\ntemplate void caffe_set<float>(const int N, const float alpha, float* Y);\ntemplate void caffe_set<double>(const int N, const double alpha, double* Y);\n\n#ifndef CPU_ONLY\ntemplate void caffe_set<float16>(const int N, const float16 alpha, float16* Y);\n#endif\n\ntemplate <>\nvoid caffe_add_scalar(const int N, const float alpha, float* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\ntemplate <>\nvoid caffe_add_scalar(const int N, const double alpha, double* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_add_scalar(const int N, const float alpha, float16* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] = Get<float16>( Get<float>(Y[i]) + alpha );\n  }\n}\ntemplate <>\nvoid caffe_add_scalar(const int N, const float16 alpha, float16* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] = Get<float16>( Get<float16>(Y[i]) + alpha );\n  }\n}\n#endif\n\ntemplate <typename Dtype, typename Mtype>\nvoid caffe_copy(const int N, const Dtype* X, Dtype* Y) {\n  if (X != Y) {\n    if (Caffe::mode() == Caffe::GPU) {\n#ifndef CPU_ONLY\n      // NOLINT_NEXT_LINE(caffe/alt_fn)\n      CUDA_CHECK(cudaMemcpy(Y, X, sizeof(Dtype) * N, cudaMemcpyDefault));\n#else\n      NO_GPU;\n#endif\n    } else {\n      memcpy(Y, X, sizeof(Dtype) * N);  // NOLINT(caffe/alt_fn)\n    }\n  }\n}\n\ntemplate void caffe_copy<int,int>(const int N, const int* X, int* Y);\ntemplate void caffe_copy<unsigned int, unsigned int>(const int N, const unsigned int* X,\n    unsigned int* Y);\ntemplate void caffe_copy<float,float>(const int N, const float* X, float* Y);\ntemplate void caffe_copy<double,double>(const int N, const double* X, double* Y);\n\n#ifndef CPU_ONLY\ntemplate void caffe_copy<float16,float>(const int N, const float16* X, float16* Y);\ntemplate void caffe_copy<float16,float16>(const int N, const float16* X, float16* Y);\n#endif\n\ntemplate <>\nvoid caffe_scal<float,float>(const int N, const float alpha, float *X) {\n  cblas_sscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_scal<double,double>(const int N, const double alpha, double *X) {\n  cblas_dscal(N, alpha, X, 1);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_scal<float16,float>(const int N, const float alpha, float16 *X) {\n  for (int i = 0; i < N; ++i) {\n    X[i] = Get<float16>( alpha * Get<float>(X[i]) );\n  }\n}\n\ntemplate <>\nvoid caffe_scal<float16,float16>(const int N, const float16 alpha, float16 *X) {\n  // cblas_hscal(N, alpha, X, 1);\n}\n#endif\n\ntemplate <>\nvoid caffe_cpu_axpby<float,float>(const int N, const float alpha, const float* X,\n                            const float beta, float* Y) {\n  cblas_saxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<double,double>(const int N, const double alpha, const double* X,\n                             const double beta, double* Y) {\n  cblas_daxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_cpu_axpby<float16,float16>(const int N, const float16 alpha, const float16* X,\n\t\t\t\t    const float16 beta, float16* Y) {}\ntemplate <>\nvoid caffe_cpu_axpby<float16,float>(const int N, const float alpha, const float16* X,\n                             const float beta, float16* Y) {\n  for (int i=0; i<N; i++) {\n    Y[i] = Get<float16>( alpha * Get<float>(X[i]) + beta * Get<float>(Y[i]) );\n  }\n}\n#endif\n\ntemplate <>\nvoid caffe_add<float,float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsAdd(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_add<double,double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdAdd(n, a, b, y);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_add<float16,float>(const int n, const float16* a, const float16* b,\n    float16* y) {\n  for (int i=0; i<n; i++) {\n    y[i] = Get<float16>( Get<float>(a[i]) + Get<float>(b[i]) );\n  }\n}\ntemplate <>\nvoid caffe_add<float16,float16>(const int n, const float16* a, const float16* b,\n    float16* y) {\n  for (int i=0; i<n; i++) {\n    y[i] = Get<float16>( Get<float16>(a[i]) + Get<float16>(b[i]) );\n  }\n}\n#endif\n\ntemplate <>\nvoid caffe_sub<float,float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsSub(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sub<double,double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdSub(n, a, b, y);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_sub<float16,float>(const int n, const float16* a, const float16* b,\n    float16* y) {\n  for (int i=0; i<n; i++) {\n    y[i] = Get<float16>( Get<float>(a[i]) - Get<float>(b[i]) );\n  }\n}\ntemplate <>\nvoid caffe_sub<float16,float16>(const int n, const float16* a, const float16* b,\n    float16* y) {\n  //  vhSub(n, a, b, y);\n}\n#endif\n\ntemplate <>\nvoid caffe_mul<float,float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsMul(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_mul<double,double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdMul(n, a, b, y);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_mul<float16,float>(const int n, const float16* a, const float16* b,\n    float16* y) {\n  for (int i=0; i<n; i++) {\n    y[i] = Get<float16>( Get<float>(a[i]) * Get<float>(b[i]) );\n  }\n}\ntemplate <>\nvoid caffe_mul<float16,float16>(const int n, const float16* a, const float16* b,\n    float16* y) {\n  //  vhMul(n, a, b, y);\n}\n#endif\n\ntemplate <>\nvoid caffe_div<float,float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsDiv(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_div<double,double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdDiv(n, a, b, y);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_div<float16,float>(const int n, const float16* a, const float16* b,\n    float16* y)\n{\n  for (int i=0; i<n; i++) {\n    y[i] = Get<float16>( Get<float>(a[i]) / Get<float>(b[i]) );\n  }\n}\n\ntemplate <>\nvoid caffe_div<float16,float16>(const int n, const float16* a, const float16* b,\n    float16* y) {\n  //  vhDiv(n, a, b, y);\n}\n#endif\n\ntemplate <>\nvoid caffe_powx<float,float>(const int n, const float* a, const float b,\n    float* y) {\n  vsPowx(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_powx<double,double>(const int n, const double* a, const double b,\n    double* y) {\n  vdPowx(n, a, b, y);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_powx<float16,float16>(const int n, const float16* a, const float16 b,\n    float16* y) {\n  //  vhPowx(n, a, b, y);\n}\ntemplate <>\nvoid caffe_powx<float16,float>(const int n, const float16* a, const float b, float16* y) {\n  for (int i=0; i<n; i++) {\n    y[i] = Get<float16>( pow(Get<float>(a[i]), b) );\n  }\n}\n#endif\n\ntemplate <>\nvoid caffe_sqr<float,float>(const int n, const float* a, float* y) {\n  vsSqr(n, a, y);\n}\n\ntemplate <>\nvoid caffe_sqr<double,double>(const int n, const double* a, double* y) {\n  vdSqr(n, a, y);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_sqr<float16,float16>(const int n, const float16* a, float16* y) {\n  vhSqr(n, a, y);\n}\ntemplate <>\nvoid caffe_sqr<float16,float>(const int n, const float16* a, float16* y) {\n  float f;\n  for (int i = 0; i < n; ++i) {\n    f = Get<float>(a[i]);\n    y[i] = Get<float16>(f * f);\n  }\n}\n#endif\n\ntemplate <>\nvoid caffe_exp<float,float>(const int n, const float* a, float* y) {\n  vsExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<double,double>(const int n, const double* a, double* y) {\n  vdExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_log<float>(const int n, const float* a, float* y) {\n  vsLn(n, a, y);\n}\n\ntemplate <>\nvoid caffe_log<double>(const int n, const double* a, double* y) {\n  vdLn(n, a, y);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_exp<float16, float16>(const int n, const float16* a, float16* y) {\n  vhExp(n, a, y);\n}\ntemplate <>\nvoid caffe_log<float16>(const int n, const float16* a, float16* y) {\n  vhLn(n, a, y);\n}\n#endif // ! CPU_ONLY\n\ntemplate <>\nvoid caffe_abs<float>(const int n, const float* a, float* y) {\n    vsAbs(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<double>(const int n, const double* a, double* y) {\n    vdAbs(n, a, y);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_exp<float16,float>(const int n, const float16* a, float16* y) {\n  for (int i=0; i<n; i++) {\n    y[i] = Get<float16>( exp(Get<float>(a[i])) );\n  }\n}\n#endif\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_abs<float16>(const int n, const float16* a, float16* y) {\n  for (int i=0; i<n; i++) {\n    y[i] = Get<float16>( fabs(Get<float>(a[i])) );\n  }\n}\n#endif\n\nunsigned int caffe_rng_rand() {\n  return (*caffe_rng())();\n}\n\ntemplate <typename Dtype>\nDtype caffe_nextafter(const Dtype b) {\n  return boost::math::nextafter<Dtype>(\n      b, std::numeric_limits<Dtype>::max());\n}\n\ntemplate\nfloat caffe_nextafter(const float b);\n\ntemplate\ndouble caffe_nextafter(const double b);\n\ntemplate <typename Dtype, typename Mtype>\nvoid caffe_rng_uniform(const int n, const Mtype a, const Mtype b, Dtype* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_LE(a, b);\n  boost::uniform_real<Mtype> random_distribution(a, caffe_nextafter<Mtype>(b));\n  boost::variate_generator<caffe::rng_t*, boost::uniform_real<Mtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = Get<Dtype>(variate_generator());\n  }\n}\n\ntemplate\nvoid caffe_rng_uniform<float,float>(const int n, const float a, const float b,\n                              float* r);\n\ntemplate\nvoid caffe_rng_uniform<double,double>(const int n, const double a, const double b,\n                               double* r);\n\n#ifndef CPU_ONLY\ntemplate\nvoid caffe_rng_uniform<float16,float>(const int n, const float a, const float b,\n                               float16* r);\n  template<>\nvoid caffe_rng_uniform<float16,float16>(const int n, const float16 a, const float16 b,\n\t\t\t\t\tfloat16* r) {}\n#endif\n\ntemplate <typename Dtype, typename Mtype>\nvoid caffe_rng_gaussian(const int n, const Mtype a,\n                        const Mtype sigma, Dtype* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GT(sigma, 0);\n  boost::normal_distribution<Mtype> random_distribution(a, sigma);\n  boost::variate_generator<caffe::rng_t*, boost::normal_distribution<Mtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = Get<Dtype>(variate_generator());\n  }\n}\n\ntemplate\nvoid caffe_rng_gaussian<float,float>(const int n, const float mu,\n                               const float sigma, float* r);\n\ntemplate\nvoid caffe_rng_gaussian<double,double>(const int n, const double mu,\n                                const double sigma, double* r);\n\n#ifndef CPU_ONLY\ntemplate\nvoid caffe_rng_gaussian<float16,float>(const int n, const float mu,\n                                const float sigma, float16* r);\n  template <>\nvoid caffe_rng_gaussian<float16,float16>(const int n, const float16 mu,\n\t\t\t\t\t const float16 sigma, float16* r) {}\n#endif\n\ntemplate <typename Dtype, typename Mtype>\nvoid caffe_rng_bernoulli(const int n, const Mtype p, int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n  boost::bernoulli_distribution<Mtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Mtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = Get<int>(variate_generator());\n  }\n}\n\ntemplate\nvoid caffe_rng_bernoulli<double,double>(const int n, const double p, int* r);\n\ntemplate\nvoid caffe_rng_bernoulli<float,float>(const int n, const float p, int* r);\n\n#ifndef CPU_ONLY\ntemplate\nvoid caffe_rng_bernoulli<float16,float>(const int n, const float p, int* r);\ntemplate\nvoid caffe_rng_bernoulli<float16,float16>(const int n, const float16 p, int* r);\n#endif\n\ntemplate <typename Dtype, typename Mtype>\nvoid caffe_rng_bernoulli(const int n, const Mtype p, unsigned int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n  boost::bernoulli_distribution<Mtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Mtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = static_cast<unsigned int>(variate_generator());\n  }\n}\n\ntemplate\nvoid caffe_rng_bernoulli<double,double>(const int n, const double p, unsigned int* r);\n\ntemplate\nvoid caffe_rng_bernoulli<float,float>(const int n, const float p, unsigned int* r);\n\n#ifndef CPU_ONLY\ntemplate\nvoid caffe_rng_bernoulli<float16,float>(const int n, const float p, unsigned int* r);\ntemplate\nvoid caffe_rng_bernoulli<float16,float16>(const int n, const float16 p, unsigned int* r);\n#endif\n\ntemplate <>\nfloat caffe_cpu_strided_dot<float,float>(const int n, const float* x, const int incx,\n    const float* y, const int incy) {\n  return cblas_sdot(n, x, incx, y, incy);\n}\n\ntemplate <>\ndouble caffe_cpu_strided_dot<double,double>(const int n, const double* x,\n    const int incx, const double* y, const int incy) {\n  return cblas_ddot(n, x, incx, y, incy);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nfloat caffe_cpu_strided_dot<float16,float>(const int n, const float16* x,\n    const int incx, const float16 *y, const int incy) {\n  float sum = 0.0f;\n  int idx_x, idx_y;\n  for (int i = 0; i < n; ++i) {\n    idx_x = i*incx;\n    idx_y = i*incy;\n    sum += Get<float>(x[idx_x]) * Get<float>(y[idx_y]);\n  }\n  return sum;\n}\n// TODO Consider CUDA\ntemplate <>\nfloat16 caffe_cpu_strided_dot<float16,float16>(const int n, const float16* x,\n    const int incx, const float16 *y, const int incy) {\n  float sum = 0.0f;\n  int idx_x, idx_y;\n  for (int i = 0; i < n; ++i) {\n    idx_x = i*incx;\n    idx_y = i*incy;\n    sum += Get<float>(x[idx_x]) * Get<float>(y[idx_y]);\n  }\n  return Get<float16>(sum);\n}\n#endif\n\ntemplate <typename Dtype, typename Mtype>\nMtype caffe_cpu_dot(const int n, const Dtype* x, const Dtype* y) {\n  return caffe_cpu_strided_dot<Dtype,Mtype>(n, x, 1, y, 1);\n}\n\ntemplate\nfloat caffe_cpu_dot<float,float>(const int n, const float* x, const float* y);\ntemplate\ndouble caffe_cpu_dot<double,double>(const int n, const double* x, const double* y);\n\n#ifndef CPU_ONLY\ntemplate\nfloat caffe_cpu_dot<float16,float>(const int n, const float16* x, const float16* y);\ntemplate\nfloat16 caffe_cpu_dot<float16,float16>(const int n, const float16* x, const float16* y);\n#endif\n\ntemplate <>\nint caffe_cpu_hamming_distance<float>(const int n, const float* x,\n                                  const float* y) {\n  int dist = 0;\n  for (int i = 0; i < n; ++i) {\n    dist += __builtin_popcount(static_cast<uint32_t>(x[i]) ^\n                               static_cast<uint32_t>(y[i]));\n  }\n  return dist;\n}\n\ntemplate <>\nint caffe_cpu_hamming_distance<double>(const int n, const double* x,\n                                   const double* y) {\n  int dist = 0;\n  for (int i = 0; i < n; ++i) {\n    dist += __builtin_popcountl(static_cast<uint64_t>(x[i]) ^\n                                static_cast<uint64_t>(y[i]));\n  }\n  return dist;\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nint caffe_cpu_hamming_distance<float16>(const int n, const float16* x,\n                                        const float16* y) {\n  int dist = 0;\n  for (int i = 0; i < n; ++i) {\n    dist += __builtin_popcount(static_cast<uint16_t>(Get<float>(x[i])) ^\n                               static_cast<uint16_t>(Get<float>(y[i])));\n  }\n  return dist;\n}\n#endif\n\ntemplate <>\nfloat caffe_cpu_asum<float,float>(const int n, const float* x) {\n  return cblas_sasum(n, x, 1);\n}\n\ntemplate <>\ndouble caffe_cpu_asum<double,double>(const int n, const double* x) {\n  return cblas_dasum(n, x, 1);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nfloat caffe_cpu_asum<float16,float>(const int n, const float16 *x) {\n  float sum = 0.0f;\n  for (int i = 0; i < n; ++i) {\n    sum += fabs(Get<float>(x[i]));\n  }\n  return sum;\n}\n\ntemplate <>\nfloat16 caffe_cpu_asum<float16,float16>(const int n, const float16 *x) {\n  float sum = 0.0f;\n  for (int i = 0; i < n; ++i) {\n    sum += fabs(Get<float>(x[i]));\n  }\n  return Get<float16>(sum);\n}\n#endif\n\ntemplate <>\nvoid caffe_cpu_scale<float,float>(const int n, const float alpha, const float *x,\n                            float* y) {\n  cblas_scopy(n, x, 1, y, 1);\n  cblas_sscal(n, alpha, y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_scale<double,double>(const int n, const double alpha, const double *x,\n                             double* y) {\n  cblas_dcopy(n, x, 1, y, 1);\n  cblas_dscal(n, alpha, y, 1);\n}\n\n#ifndef CPU_ONLY\ntemplate <>\nvoid caffe_cpu_scale<float16,float16>(const int n, const float16 alpha, const float16 *x,\n    float16 *y) {\n}\n\ntemplate <>\nvoid caffe_cpu_scale<float16,float>(const int n, const float alpha, const float16 *x,\n    float16 *y) {\n  for (int i=0; i<n; i++) {\n    y[i] = Get<float16>( alpha * Get<float>(x[i]) );\n  }\n}\n#endif\n\n}  // namespace caffe\n", "meta": {"hexsha": "3cef0aaa3bfdbcc93ed3cc8b194d70f36b871384", "size": 21199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_functions.cpp", "max_stars_repo_name": "oscmansan/nvcaffe", "max_stars_repo_head_hexsha": "22738c97e9c6991e49a12a924c3c773d95795b5c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/caffe/util/math_functions.cpp", "max_issues_repo_name": "oscmansan/nvcaffe", "max_issues_repo_head_hexsha": "22738c97e9c6991e49a12a924c3c773d95795b5c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/caffe/util/math_functions.cpp", "max_forks_repo_name": "oscmansan/nvcaffe", "max_forks_repo_head_hexsha": "22738c97e9c6991e49a12a924c3c773d95795b5c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.041005291, "max_line_length": 103, "alphanum_fraction": 0.6461153828, "num_tokens": 6463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744806385542, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.41836643732513235}}
{"text": "// Copyright (c) 2020 Marcus Valtonen Örnhag\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include \"get_valtonenornhag_arxiv_2020a.hpp\"\n#include <float.h>  // DBL_MAX\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <cmath>  // abs\n#include \"solver_valtonenornhag_arxiv_2020a_fHf.hpp\"\n#include \"normalize2dpts.hpp\"\n\nnamespace HomLib {\nnamespace ValtonenOrnhagArxiv2020A {\n    inline double get_algebraic_error_floor_fHf(const Eigen::VectorXd &data);\n\n    HomLib::PoseData get_fHf(\n        const Eigen::MatrixXd &p1,\n        const Eigen::MatrixXd &p2,\n        const Eigen::Matrix3d &R1,\n        const Eigen::Matrix3d &R2\n    ) {\n        int nbr_coeffs = 30;\n        int nbr_unknowns = 6;\n\n        // Save copies of the inverse rotation\n        Eigen::Matrix3d R1T = R1.transpose();\n        Eigen::Matrix3d R2T = R2.transpose();\n\n        // Compute normalization matrix\n        double scale = normalize2dpts(p1);\n        Eigen::Vector3d s;\n        s << scale, scale, 1.0;\n        Eigen::DiagonalMatrix<double, 3> S = s.asDiagonal();\n\n        // Normalize data\n        Eigen::Matrix3d x1;\n        Eigen::Matrix3d x2;\n        x1 = p1.colwise().homogeneous();\n        x2 = p2.colwise().homogeneous();\n\n        x1 = S * x1;\n        x2 = S * x2;\n\n        Eigen::MatrixXd x1t(2, 3);\n        x1t << x1.colwise().hnormalized();\n        Eigen::MatrixXd x2t(2, 3);\n        x2t << x2.colwise().hnormalized();\n\n        // Wrap input data to expected format\n        Eigen::VectorXd input(nbr_coeffs);\n        input << x1t.col(0),\n                 x2t.col(0),\n                 x1t.col(1),\n                 x2t.col(1),\n                 x1t.col(2),\n                 x2t.col(2),\n                 Eigen::Map<Eigen::VectorXd>(R1T.data(), 9),\n                 Eigen::Map<Eigen::VectorXd>(R2T.data(), 9);\n\n        // Extract solution\n        Eigen::MatrixXcd sols = HomLib::ValtonenOrnhagArxiv2020A::solver_fHf(input);\n\n        // Pre-processing: Remove complex-valued solutions\n        double thresh = 1e-5;\n        Eigen::ArrayXd real_sols(7);\n        real_sols = sols.imag().cwiseAbs().colwise().sum();\n        int nbr_real_sols = (real_sols <= thresh).count();\n\n        // Allocate space for putative (real) homographies\n        Eigen::MatrixXd best_homography(3, 3);\n        double best_focal_length;\n        double best_algebraic_error = DBL_MAX;\n        double algebraic_error;\n\n        // Since this is a 2.5 pt solver, use the last\n        // (previously unused) constraint, to discard\n        // false solutions.\n        Eigen::ArrayXd xx(6);\n        Eigen::VectorXd input_algebraic(nbr_coeffs + nbr_unknowns);\n\n        for (int i = 0; i < real_sols.size(); i++) {\n            if (real_sols(i) <= thresh) {\n                // Compute algebraic error, and compare to other solutions.\n                xx = sols.col(i).real();\n                input_algebraic << xx, input;\n                algebraic_error = HomLib::ValtonenOrnhagArxiv2020A::get_algebraic_error_floor_fHf(input_algebraic);\n\n                if (algebraic_error < best_algebraic_error) {\n                    best_algebraic_error = algebraic_error;\n                    best_homography << xx[0], xx[2], xx[1],\n                                           0, xx[3],     0,\n                                      -xx[1], xx[4], xx[0];\n                    best_focal_length = xx[5];\n                }\n            }\n        }\n        // Construct homography\n        Eigen::Matrix3d K, Ki, H;\n        K = Eigen::Vector3d(best_focal_length, best_focal_length, 1).asDiagonal();\n        Ki = Eigen::Vector3d(1, 1, best_focal_length).asDiagonal();\n        H = S.inverse() * K * R2 * best_homography * R1.transpose() * Ki * S;\n\n        // Package output\n        HomLib::PoseData posedata;\n        posedata.homography = H;\n        posedata.focal_length = best_focal_length / scale;\n\n        return posedata;\n    }\n\n    // Function that utilizes the last equation of the DLT system to discard false solutions\n    inline double get_algebraic_error_floor_fHf(const Eigen::VectorXd &data) {\n        const double* d = data.data();\n\n        // Compute algebraic error\n        double error;\n        error = -d[0]*std::pow(d[5], 2)*d[24]*d[34] - d[0]*d[5]*d[14]*d[18]*d[34] - d[0]*d[5]*d[15]*d[21]*d[34]\n            - d[0]*d[5]*d[16]*d[24]*d[28] - d[0]*d[5]*d[17]*d[24]*d[31] - d[0]*d[14]*d[16]*d[18]*d[28]\n            - d[0]*d[14]*d[17]*d[18]*d[31] - d[0]*d[15]*d[16]*d[21]*d[28] - d[0]*d[15]*d[17]*d[21]*d[31]\n            - d[1]*std::pow(d[5], 2)*d[26]*d[34] - d[1]*d[5]*d[14]*d[20]*d[34] - d[1]*d[5]*d[15]*d[23]*d[34]\n            - d[1]*d[5]*d[16]*d[26]*d[28] - d[1]*d[5]*d[17]*d[26]*d[31] - d[1]*d[14]*d[16]*d[20]*d[28]\n            - d[1]*d[14]*d[17]*d[20]*d[31] - d[1]*d[15]*d[16]*d[23]*d[28] - d[1]*d[15]*d[17]*d[23]*d[31]\n            - d[2]*std::pow(d[5], 2)*d[25]*d[34] - d[2]*d[5]*d[14]*d[19]*d[34] - d[2]*d[5]*d[15]*d[22]*d[34]\n            - d[2]*d[5]*d[16]*d[25]*d[28] - d[2]*d[5]*d[17]*d[25]*d[31] - d[2]*d[14]*d[16]*d[19]*d[28]\n            - d[2]*d[14]*d[17]*d[19]*d[31] - d[2]*d[15]*d[16]*d[22]*d[28] - d[2]*d[15]*d[17]*d[22]*d[31]\n            + d[3]*std::pow(d[5], 2)*d[25]*d[33] + d[3]*d[5]*d[14]*d[19]*d[33] + d[3]*d[5]*d[15]*d[22]*d[33]\n            + d[3]*d[5]*d[16]*d[25]*d[27] + d[3]*d[5]*d[17]*d[25]*d[30] + d[3]*d[14]*d[16]*d[19]*d[27]\n            + d[3]*d[14]*d[17]*d[19]*d[30] + d[3]*d[15]*d[16]*d[22]*d[27] + d[3]*d[15]*d[17]*d[22]*d[30];\n        return abs(error);\n    }\n}  // namespace ValtonenOrnhagArxiv2020A\n}  // namespace HomLib\n", "meta": {"hexsha": "7b702cc50dbe534e71fcbfd06e0df6e2a5f9359c", "size": 6525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/valtonenornhag_arxiv_2020a/get_valtonenornhag_arxiv_2020a_fHf.cpp", "max_stars_repo_name": "marcusvaltonen/HomLib", "max_stars_repo_head_hexsha": "cc8c3ba78bbfcb30fdbe17e5aa45405f4757889b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-07T18:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T10:37:37.000Z", "max_issues_repo_path": "src/solvers/valtonenornhag_arxiv_2020a/get_valtonenornhag_arxiv_2020a_fHf.cpp", "max_issues_repo_name": "marcusvaltonen/HomLib", "max_issues_repo_head_hexsha": "cc8c3ba78bbfcb30fdbe17e5aa45405f4757889b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solvers/valtonenornhag_arxiv_2020a/get_valtonenornhag_arxiv_2020a_fHf.cpp", "max_forks_repo_name": "marcusvaltonen/HomLib", "max_forks_repo_head_hexsha": "cc8c3ba78bbfcb30fdbe17e5aa45405f4757889b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T19:59:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T19:59:02.000Z", "avg_line_length": 43.5, "max_line_length": 115, "alphanum_fraction": 0.5725670498, "num_tokens": 2125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.41833995885897596}}
{"text": "﻿/*!\n * \\file plane.cpp\n *\n * \\author Han\n * \\date 2017/06/21\n *\n * 平面操作，主要包括坐标的三维和二维变换等\n */\n#include <MathGeoLib/MathGeoLib.h>\n\n#include <modelpro/mesh.h>\n#include <modelpro/plane.h>\n#include <sketchup/sketchup.h>\n\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <opencv2/calib3d.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/imgproc.hpp>\n\nnamespace h2o {\nPlane::Plane(const Vector3d &p, const Vector3d &n) {\n    Vector3d normal = n;\n    normal.normalize();\n    Vector3d z_axis = {0.0, 0.0, 1.0};\n\n    // 平面二三维变换的实质是一个旋转加平移\n    R_ = Quaterniond::FromTwoVectors(normal, z_axis);\n    T_ = -R_ * p;\n    Rinv_ = R_.inverse();\n\n    plane_ = Plane3d(n, p);\n}\n\nPlane::~Plane() {}\n\nVector2d Plane::to_2d(const Vector3d &point) const {\n    Vector3d plane = R_ * point + T_;\n    return plane.head(2);\n}\n\nVector3d Plane::to_3d(const Vector2d &point) const {\n    Vector3d point3d = {point.x(), point.y(), 0.0};\n    Vector3d object3d = Rinv_ * (point3d - T_);\n    return object3d;\n}\n\ndouble Plane::signed_distance(const Vector3d &point) const { return plane_.signedDistance(point); }\n\nbool Plane::on_plane(const Vector3d &point) const {\n    double distance = signed_distance(point);\n    // EPSILON_LENGTH 的精度是 0.001\n    if (distance < EPSILON_LENGTH && distance > -EPSILON_LENGTH) {\n        return true;\n    } else {\n        return false;\n    }\n}\n\nVector3d Plane::get_normal() const { return plane_.normal(); }\n\nPlaneRotated::PlaneRotated(const std::vector<Vector3d> &points3d, const Vector3d &n) : Plane() {\n    CHECK(points3d.size() >= 3);\n\n    Vector3d normal = n;\n    normal.normalize();\n    Vector3d z_axis(0.0, 0.0, 1.0);\n    Vector3d y_axis(0.0, 1.0, 0.0);\n    // 平面二三维变换的实质是一个旋转加平移\n    R_ = Quaterniond::FromTwoVectors(normal, z_axis);\n\n    T_ = -R_ * points3d[0];\n    Rinv_ = R_.inverse();\n\n    plane_ = Plane3d(n, points3d[0]);\n    // 将所有点变换到二维，计算 rotated rect\n    std::vector<cv::Point2f> plane2d(points3d.size());\n    std::transform(begin(points3d), end(points3d), begin(plane2d), [&](const Vector3d &p) {\n        Vector3d plane3d = R_ * p + T_;\n        CHECK(std::abs(plane3d.z()) < 0.1)\n            << \"Project to 2d plane failed, the z coord of the point is : \" << plane3d.z();\n        return cv::Point2f(plane3d.x(), plane3d.y());\n    });\n\n    /*\n     * OPENCV 的 rotated rect 的四个角点分别为\n     * point = center + R * corner\n     * R 为 Rotation2d 得到的\n     * 0 ----- 3\n     * |       |\n     * 1 ----- 2\n     */\n    cv::RotatedRect rect = cv::minAreaRect(plane2d);\n\n    Matrix3d R_z;\n    Vector3d T2;\n    Vector3d direction_y;\n\n    std::vector<cv::Point2f> points_rect(4);\n    std::vector<Vector3d> bb_3d(4);\n    rect.points(points_rect.data());\n\n    std::transform(begin(points_rect), end(points_rect), begin(bb_3d), [&](const cv::Point2f &p) {\n        Vector3d plane3d(p.x, p.y, 0.0);\n        Vector3d object3d = Rinv_ * (plane3d - T_);\n        return object3d;\n    });\n\n    // 绕z轴再旋转一定量，将二维平面的xy轴和他对其\n    // 这个 旋转的大小的计算是两种\n    if (std::abs(std::abs(normal.dot(z_axis)) - 1.0) < 1e-6) {\n        direction_y = Vector3d(points_rect[0].x - points_rect[1].x, points_rect[0].y - points_rect[1].y, 0.0);\n        R_z = Quaterniond::FromTwoVectors(direction_y, y_axis);\n        T2 = -R_z * Vector3d(points_rect[1].x, points_rect[1].y, 0.0);\n    } else {\n        // 需要保证 y 轴是朝上的，将某个朝上的轴，旋转到y轴\n        if (compare_z(bb_3d[0], bb_3d[1]) == 1) {\n            direction_y = Vector3d(points_rect[0].x - points_rect[1].x, points_rect[0].y - points_rect[1].y, 0.0);\n            R_z = Quaterniond::FromTwoVectors(direction_y, y_axis);\n            T2 = -R_z * Vector3d(points_rect[1].x, points_rect[1].y, 0.0);\n        } else if (compare_z(bb_3d[0], bb_3d[1]) == -1) {\n            direction_y = Vector3d(points_rect[1].x - points_rect[0].x, points_rect[1].y - points_rect[0].y, 0.0);\n            R_z = Quaterniond::FromTwoVectors(direction_y, y_axis);\n            T2 = -R_z * Vector3d(points_rect[3].x, points_rect[3].y, 0.0);\n        }\n        if (compare_z(bb_3d[0], bb_3d[3]) == 1) {\n            direction_y = Vector3d(points_rect[0].x - points_rect[3].x, points_rect[0].y - points_rect[3].y, 0.0);\n            R_z = Quaterniond::FromTwoVectors(direction_y, y_axis);\n            T2 = -R_z * Vector3d(points_rect[2].x, points_rect[2].y, 0.0);\n        } else if (compare_z(bb_3d[0], bb_3d[3]) == -1) {\n            direction_y = Vector3d(points_rect[3].x - points_rect[0].x, points_rect[3].y - points_rect[0].y, 0.0);\n            R_z = Quaterniond::FromTwoVectors(direction_y, y_axis);\n            T2 = -R_z * Vector3d(points_rect[0].x, points_rect[0].y, 0.0);\n        }\n    }\n    // plane3d = R_p + T\n    // texture = Rz * plane3d + T2, T2 用于将点 0 的坐标移动到 0\n    // texture = Rz * R_ * p + Rz * T + T2\n    T_ = R_z * T_ + T2;\n    R_ = R_z * R_;\n    Rinv_ = R_.inverse();\n    bb_3d_ = bb_3d;\n\n    init_plane_bb();\n}\n\nvoid PlaneRotated::set_gsd(double gsd) {\n    // 左上角的纹理影像坐标为 0，0，但是他的plane2d的坐标是最大的\n    io_(0, 0) = 1.0 / gsd;\n    io_(0, 1) = 0.0;\n    io_(0, 2) = 0.0;\n    io_(1, 0) = 0.0;\n    io_(1, 1) = -1.0 / gsd;\n    io_(1, 2) = bb_plane2d_.sizes()(1) / gsd;\n\n    Matrix2d A;\n    Vector2d b;\n    A = io_.block(0, 0, 2, 2);\n    b = io_.col(2);\n\n    iob_.block(0, 0, 2, 2) = A.inverse();\n    iob_.col(2) = -A.inverse() * b;\n}\n\nstd::vector<Vector2d> PlaneRotated::get_corners2d() const {\n    std::vector<Vector2d> bb_plane2d(4);\n    std::transform(begin(bb_3d_), end(bb_3d_), begin(bb_plane2d), [&](const Vector3d &p) { return to_2d(p); });\n    return bb_plane2d;\n}\n\nstd::vector<Vector3d> PlaneRotated::get_corners3d() const { return bb_3d_; }\n\nVector2d PlaneRotated::to_texture(const Vector3d &point) const {\n    Vector2d plane2d = to_2d(point);\n    Vector2d tex2d = io_ * plane2d.homogeneous();\n    return tex2d;\n}\n\nVector3d PlaneRotated::from_texture(const Vector2d &point) const {\n    Vector2d plane2d = iob_ * point.homogeneous();\n    Vector3d object3d = to_3d(plane2d);\n    return object3d;\n}\n\nOBB3d PlaneRotated::get_obb(double thickness) {\n    Vector3d normal = plane_.normal();\n\n    std::vector<Vector3d> corners3d = get_corners3d();\n    std::vector<Vector3d> points(corners3d.size() * 2);\n    for (int i = 0; i < corners3d.size(); ++i) {\n        Vector3d point = corners3d[i] + thickness * normal;\n        points[2 * i + 0] = point;\n\n        point = corners3d[i] - thickness * normal;\n        points[2 * i + 1] = point;\n    }\n\n    Vector3d dir1 = (corners3d[1] - corners3d[0]).normalized();\n    Vector3d dir2 = (corners3d[3] - corners3d[0]).normalized();\n\n    OBB3d obb = obb_compute(points, dir1, dir2);\n\n    return obb;\n}\n\nint PlaneRotated::compare_z(const Vector3d &p1, const Vector3d &p2) const {\n    if (p1.z() - p2.z() > EPSILON_LENGTH) {\n        return 1;\n    } else if (p1.z() - p2.z() < -EPSILON_LENGTH) {\n        return -1;\n    } else {\n        return 0;\n    }\n    return 0;\n}\n\nvoid PlaneRotated::init_plane_bb() {\n    // 把所有的 bb_3d 换算到平面坐标\n    for (const auto &corner : bb_3d_) {\n        bb_plane2d_.extend(to_2d(corner));\n    }\n}\n\nMatrix3d estimate_homography(const std::vector<Vector2d> &object, const std::vector<Vector2d> &image) {\n    std::vector<cv::Point2f> object2(object.size()), image2(image.size());\n    for (int i = 0; i < object.size(); ++i) {\n        object2[i] = cv::Point2f(object[i].x(), object[i].y());\n        image2[i] = cv::Point2f(image[i].x(), image[i].y());\n    }\n\n    cv::Mat mask;\n    cv::Mat H2 = cv::findHomography(image2, object2, mask, 0);\n    Matrix3d H;\n    cv::cv2eigen(H2, H);\n\n    return H;\n}\n\ndouble estimate_gsd(const std::vector<Vector2d> &object, const std::vector<Vector2d> &image) {\n    double gsd = 0.0;\n    for (int i = 0; i < image.size(); ++i) {\n\n        int j = (i + 1) % image.size();\n\n        Vector2d o1 = object[i];\n        Vector2d o2 = object[j];\n\n        Vector2d i1 = image[i];\n        Vector2d i2 = image[j];\n\n        gsd += (o1 - o2).norm() / (i1 - i2).norm();\n    }\n    gsd /= image.size();\n    return gsd;\n}\n\nPlaneRotated plane_from_face(VALUE face) {\n    Vector3d normal = su_face_normal(face);\n    std::vector<Vector3d> points = su_entity_vertices(face);\n    PlaneRotated plane(points, normal);\n\n    return plane;\n}\n\n} // namespace h2o\n", "meta": {"hexsha": "00f6a81163087b5e4a4f7caa97eebd85583b45a5", "size": 8114, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/model/plane.cpp", "max_stars_repo_name": "mmrwizard/RenderMatch-1", "max_stars_repo_head_hexsha": "a427138e6823675eaa76c693bc31a28566b4dcd8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/model/plane.cpp", "max_issues_repo_name": "mmrwizard/RenderMatch-1", "max_issues_repo_head_hexsha": "a427138e6823675eaa76c693bc31a28566b4dcd8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/model/plane.cpp", "max_forks_repo_name": "mmrwizard/RenderMatch-1", "max_forks_repo_head_hexsha": "a427138e6823675eaa76c693bc31a28566b4dcd8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-12T08:19:14.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-12T08:19:14.000Z", "avg_line_length": 30.5037593985, "max_line_length": 114, "alphanum_fraction": 0.6037712596, "num_tokens": 2936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4183399588589759}}
{"text": "#include <wav2midi/scale.hpp>\n#include <cmath>\n#include <boost/format.hpp>\n\n// scale::item\nnamespace wav2midi {\n    namespace {\n        const std::vector<std::string> scale_names{{\n            \"A%d\",\n            \"A#%d\",\n            \"B%d\",\n            \"C%d\",\n            \"C#%d\",\n            \"D%d\",\n            \"D#%d\",\n            \"E%d\",\n            \"F%d\",\n            \"F#%d\",\n            \"G%d\",\n            \"G#%d\",\n        }};\n    }\n\n    scale::item::item(uint32_t no) {\n        using namespace std;\n        no_ = no;\n        local_no_ = no_ % 12u;\n        octave_ = (no_ + 9u) / 12u;\n        frequency_ = scale::frequency_to_no(no_);\n        name_ = (boost::format(scale_names[local_no_]) % octave_).str();\n    }\n\n    uint32_t scale::item::no() const { return no_; }\n    uint32_t scale::item::local_no() const { return local_no_; }\n    uint32_t scale::item::octave() const { return octave_; }\n    double scale::item::frequency() const { return frequency_; }\n    const std::string & scale::item::name() const { return name_; }\n\n}\n\n// scale\nnamespace wav2midi {\n    scale::scale() {\n        for (auto no = 0u; no < scale::n; ++no) {\n            items_.emplace_back(no);\n        }\n    }\n\n    const scale::item & scale::operator [](uint32_t no) const {\n        static item unknown{0};\n        return no < 88u ? items_[no] : unknown;\n    }\n\n    const scale::item & scale::match(double frequency) const {\n        return (*this)[scale::frequency_to_no(frequency)];\n    }\n\n    uint32_t scale::frequency_to_no(double frequency) {\n        using namespace std;\n        return round(12.0 * log2(frequency / 27.5));\n    }\n\n    double scale::no_to_frequency(uint32_t no) {\n        using namespace std;\n        return 27.5 * pow(2.0, no / 12.0);\n    }\n}\n", "meta": {"hexsha": "e55702abb71d35626b7dd307e9da571f0a64aee1", "size": 1739, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/wav2midi/scale.cpp", "max_stars_repo_name": "mrk21/wav2midi", "max_stars_repo_head_hexsha": "01b7667c2fd7e18893a5cc97069aabc9397126e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2018-11-14T04:46:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T13:28:38.000Z", "max_issues_repo_path": "src/wav2midi/scale.cpp", "max_issues_repo_name": "mrk21/wav2midi", "max_issues_repo_head_hexsha": "01b7667c2fd7e18893a5cc97069aabc9397126e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-01-12T21:40:34.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-12T22:06:01.000Z", "max_forks_repo_path": "src/wav2midi/scale.cpp", "max_forks_repo_name": "mrk21/wav2midi", "max_forks_repo_head_hexsha": "01b7667c2fd7e18893a5cc97069aabc9397126e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-07-04T14:34:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T13:38:35.000Z", "avg_line_length": 25.5735294118, "max_line_length": 72, "alphanum_fraction": 0.5255894192, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4183399522292451}}
{"text": "#include <cstdio>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <map>\n#include <cfloat>\n#include <filesystem>\n\n#if WIN32\n#define NOMINMAX\n#endif\n\nnamespace fs = std::filesystem;\n\n// Eigen\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n\n// OpenMP\n#include <omp.h>\n\n// Argument parser\n#include \"argparse.h\"\n\n// Progress bar\n#include \"progress.h\"\n\n#define TINYPLY_IMPLEMENTATION\n#include \"triangle_point/tinyply.h\"\n#include \"triangle_point/vec.h\"\n#include \"triangle_point/poitri.h\"\n\n/** \\brief Compute triangle point distance and corresponding closest point.\n * \\param[in] point point\n * \\param[in] v1 first vertex\n * \\param[in] v2 second vertex\n * \\param[in] v3 third vertex\n * \\param[out] ray corresponding closest point\n * \\return distance\n */\nfloat triangle_point_distance(const Eigen::Vector3f point, const Eigen::Vector3f v1, const Eigen::Vector3f v2, const Eigen::Vector3f v3,\n    Eigen::Vector3f& closest_point) {\n\n    Vec3f x0(point.data());\n    Vec3f x1(v1.data());\n    Vec3f x2(v2.data());\n    Vec3f x3(v3.data());\n\n    Vec3f r(0);\n    float distance = point_triangle_distance(x0, x1, x2, x3, r);\n\n    for (int d = 0; d < 3; d++) {\n        closest_point(d) = r[d];\n    }\n\n    return distance;\n}\n\n/** \\brief Point cloud class forward declaration. */\nclass PointCloud;\n\n/** \\brief Just encapsulating vertices and faces. */\nclass Mesh {\npublic:\n    /** \\brief Empty constructor. */\n    Mesh() {\n\n    }\n\n    /** \\brief Reading an off file and returning the vertices x, y, z coordinates and the\n     * face indices.\n     * \\param[in] filepath path to the OFF file\n     * \\param[out] mesh read mesh with vertices and faces\n     * \\return success\n     */\n    static bool from_off(const std::string filepath, Mesh& mesh) {\n\n        std::ifstream* file = new std::ifstream(filepath.c_str());\n        std::string line;\n        std::stringstream ss;\n        int line_nb = 0;\n\n        std::getline(*file, line);\n        ++line_nb;\n\n        if (line != \"off\" && line != \"OFF\") {\n            std::cout << \"[Error] Invalid header: \\\"\" << line << \"\\\", \" << filepath << std::endl;\n            return false;\n        }\n\n        size_t n_edges;\n        std::getline(*file, line);\n        ++line_nb;\n\n        int n_vertices;\n        int n_faces;\n        ss << line;\n        ss >> n_vertices;\n        ss >> n_faces;\n        ss >> n_edges;\n\n        for (size_t v = 0; v < n_vertices; ++v) {\n            std::getline(*file, line);\n            ++line_nb;\n\n            ss.clear();\n            ss.str(\"\");\n\n            Eigen::Vector3f vertex;\n            ss << line;\n            ss >> vertex(0);\n            ss >> vertex(1);\n            ss >> vertex(2);\n\n            mesh.add_vertex(vertex);\n        }\n\n        size_t n;\n        for (size_t f = 0; f < n_faces; ++f) {\n            std::getline(*file, line);\n            ++line_nb;\n\n            ss.clear();\n            ss.str(\"\");\n\n            size_t n;\n            ss << line;\n            ss >> n;\n\n            if (n != 3) {\n                std::cout << \"[Error] Not a triangle (\" << n << \" points) at \" << (line_nb - 1) << std::endl;\n                return false;\n            }\n\n            Eigen::Vector3i face;\n            ss >> face(0);\n            ss >> face(1);\n            ss >> face(2);\n\n            mesh.add_face(face);\n        }\n\n        if (n_vertices != mesh.num_vertices()) {\n            std::cout << \"[Error] Number of vertices in header differs from actual number of vertices.\" << std::endl;\n            return false;\n        }\n\n        if (n_faces != mesh.num_faces()) {\n            std::cout << \"[Error] Number of faces in header differs from actual number of faces.\" << std::endl;\n            return false;\n        }\n\n        file->close();\n        delete file;\n\n        return true;\n    }\n\n    static bool from_ply(const std::string& filename, Mesh& mesh) {\n        using tinyply::PlyFile;\n        using tinyply::PlyData;\n\n        try {\n            // Open\n            std::ifstream reader(filename.c_str(), std::ios::binary);\n            if (reader.fail()) {\n                std::cerr << (\"Failed to open file: \" + filename) << std::endl;\n                return false;\n            }\n\n            // Read header\n            PlyFile file;\n            file.parse_header(reader);\n\n            // Request vertex data\n            std::shared_ptr<PlyData> vert_data, norm_data, uv_data, face_data;\n            try {\n                vert_data = file.request_properties_from_element(\"vertex\", { \"x\", \"y\", \"z\" });\n            }\n            catch (std::exception& e) {\n                std::cerr << \"tinyply exception: \" << e.what() << std::endl;\n            }\n\n            try {\n                norm_data = file.request_properties_from_element(\"vertex\", { \"nx\", \"ny\", \"nz\" });\n            }\n            catch (std::exception& e) {\n                // std::cerr << \"tinyply exception: \" << e.what() << std::endl;\n            }\n\n            try {\n                uv_data = file.request_properties_from_element(\"vertex\", { \"u\", \"v\" });\n            }\n            catch (std::exception& e) {\n                // std::cerr << \"tinyply exception: \" << e.what() << std::endl;\n            }\n\n            try {\n                face_data = file.request_properties_from_element(\"face\", { \"vertex_indices\" }, 3);\n            }\n            catch (std::exception& e) {\n                std::cerr << \"tinyply exception: \" << e.what() << std::endl;\n            }\n\n            // Read vertex data\n            file.read(reader);\n\n            // Copy vertex data\n            const size_t numVerts = vert_data->count;\n            std::vector<double> raw_vertices(numVerts * 3);\n            std::memcpy(raw_vertices.data(), vert_data->buffer.get(), sizeof(double) * numVerts * 3);\n\n            const size_t numFaces = face_data->count;\n            std::vector<uint32_t> raw_indices(numFaces * 3);\n            std::memcpy(raw_indices.data(), face_data->buffer.get(), sizeof(uint32_t) * numFaces * 3);\n\n            // Store in mesh\n            for (int i = 0; i < raw_vertices.size(); i += 3) {\n                Eigen::Vector3f v;\n                v << raw_vertices[i + 0], raw_vertices[i + 1], raw_vertices[i + 2];\n                mesh.add_vertex(v);\n            }\n\n            for (int i = 0; i < raw_indices.size(); i += 3) {\n                Eigen::Vector3i f;\n                f << raw_indices[i + 0], raw_indices[i + 1], raw_indices[i + 2];\n                mesh.add_face(f);\n            }\n        }\n        catch (const std::exception& e) {\n            std::cerr << \"Caught tinyply exception: \" << e.what() << std::endl;\n            return false;\n        }\n\n        return true;\n    }\n\n    /** \\brief Write mesh to OFF file.\n     * \\param[in] filepath path to OFF file to write\n     * \\return success\n     */\n    bool to_off(const std::string filepath) const {\n        std::ofstream* out = new std::ofstream(filepath, std::ofstream::out);\n        if (!static_cast<bool>(out)) {\n            return false;\n        }\n\n        (*out) << \"OFF\" << std::endl;\n        (*out) << this->num_vertices() << \" \" << this->num_faces() << \" 0\" << std::endl;\n\n        for (unsigned int v = 0; v < this->num_vertices(); v++) {\n            (*out) << this->vertices[v](0) << \" \" << this->vertices[v](1) << \" \" << this->vertices[v](2) << std::endl;\n        }\n\n        for (unsigned int f = 0; f < this->num_faces(); f++) {\n            (*out) << \"3 \" << this->faces[f](0) << \" \" << this->faces[f](1) << \" \" << this->faces[f](2) << std::endl;\n        }\n\n        out->close();\n        delete out;\n\n        return true;\n    }\n\n    /** \\brief Add a vertex.\n     * \\param[in] vertex vertex to add\n     */\n    void add_vertex(Eigen::Vector3f& vertex) {\n        this->vertices.push_back(vertex);\n    }\n\n    /** \\brief Get the number of vertices.\n     * \\return number of vertices\n     */\n    int num_vertices() const {\n        return static_cast<int>(this->vertices.size());\n    }\n\n    /** \\brief Get a vertex.\n     * \\param[in] v vertex index\n     * \\return vertex\n     */\n    Eigen::Vector3f vertex(int v) const {\n        assert(v >= 0 && v < this->num_vertices());\n        return this->vertices[v];\n    }\n\n    /** \\brief Add a face.\n     * \\param[in] face face to add\n     */\n    void add_face(Eigen::Vector3i& face) {\n        this->faces.push_back(face);\n    }\n\n    /** \\brief Get the number of faces.\n     * \\return number of faces\n     */\n    int num_faces() const {\n        return static_cast<int>(this->faces.size());\n    }\n\n    /** \\brief Get a face.\n     * \\param[in] f face index\n     * \\return face\n     */\n    Eigen::Vector3i face(int f) const {\n        assert(f >= 0 && f < this->num_faces());\n        return this->faces[f];\n    }\n\n    /** \\brief Sample points from the mesh\n     * \\param[in] mesh mesh to sample from\n     * \\param[in] n batch index in points\n     * \\param[in] points pre-initialized tensor holding points\n     */\n    bool sample(const int N, PointCloud& point_cloud) const;\n\nprivate:\n\n    /** \\brief Vertices as (x,y,z)-vectors. */\n    std::vector<Eigen::Vector3f> vertices;\n\n    /** \\brief Faces as list of vertex indices. */\n    std::vector<Eigen::Vector3i> faces;\n};\n\n/** \\brief Class representing a point cloud in 3D. */\nclass PointCloud {\npublic:\n    /** \\brief Constructor. */\n    PointCloud() {\n\n    }\n\n    /** \\brief Copy constructor.\n     * \\param[in] point_cloud point cloud to copy\n     */\n    PointCloud(const PointCloud& point_cloud) {\n        this->points.clear();\n\n        for (unsigned int i = 0; i < point_cloud.points.size(); i++) {\n            this->points.push_back(point_cloud.points[i]);\n        }\n    }\n\n    /** \\brief Destructor. */\n    ~PointCloud() {\n\n    }\n\n    /** \\brief Read point cloud from txt file.\n     * \\param[in] filepath path to file to read\n     * \\param[out] point_cloud\n     * \\return success\n     */\n    static bool from_txt(const std::string& filepath, PointCloud& point_cloud) {\n        std::ifstream file(filepath.c_str());\n        std::string line;\n        std::stringstream ss;\n\n        std::getline(file, line);\n        ss << line;\n\n        int n_points = 0;\n        ss >> n_points;\n\n        if (n_points < 0) {\n            return false;\n        }\n\n        for (int i = 0; i < n_points; i++) {\n            std::getline(file, line);\n\n            ss.clear();\n            ss.str(\"\");\n            ss << line;\n\n            Eigen::Vector3f point(0, 0, 0);\n            ss >> point(0);\n            ss >> point(1);\n            ss >> point(2);\n\n            point_cloud.add_point(point);\n        }\n\n        return true;\n    }\n\n    /** \\brief Add a point to the point cloud.\n     * \\param[in] point point to add\n     */\n    void add_point(const Eigen::Vector3f& point) {\n        this->points.push_back(point);\n    }\n\n    /** \\brief Get number of points.\n     * \\return number of points\n     */\n    unsigned int num_points() const {\n        return this->points.size();\n    }\n\n    /** \\brief Compute distance to mesh.\n      * \\param[in] mesh\n      * \\param[out] distances per point distances\n      * \\param[out] distance\n      * \\return success\n      */\n    bool compute_distance(const Mesh& mesh, float& _distance) {\n        _distance = 0;\n\n        if (this->num_points() <= 0) {\n            std::cout << \"[Error] no points in this point clouds\" << std::endl;\n            return false;\n        }\n\n        if (mesh.num_faces() <= 0) {\n            std::cout << \"[Error] no faces in given mesh\" << std::endl;\n            return false;\n        }\n\n#pragma omp parallel\n        {\n#pragma omp for\n            for (int i = 0; i < this->points.size(); i++) {\n\n                float min_distance = FLT_MAX;\n                for (int f = 0; f < mesh.num_faces(); f++) {\n                    Eigen::Vector3f closest_point;\n                    Eigen::Vector3f v1 = mesh.vertex(mesh.face(f)(0));\n                    Eigen::Vector3f v2 = mesh.vertex(mesh.face(f)(1));\n                    Eigen::Vector3f v3 = mesh.vertex(mesh.face(f)(2));\n\n                    triangle_point_distance(this->points[i], v1, v2, v3, closest_point);\n                    float distance = (this->points[i] - closest_point).norm();\n\n                    if (distance < min_distance) {\n                        min_distance = distance;\n                    }\n                }\n\n#pragma omp atomic\n                _distance += min_distance;\n            }\n        }\n\n        _distance /= this->num_points();\n        return true;\n    }\n\nprivate:\n    /** \\brief The points of the point cloud. */\n    std::vector<Eigen::Vector3f> points;\n\n};\n\n/** \\brief Sample points from the mesh\n * \\param[in] mesh mesh to sample from\n * \\param[in] n batch index in points\n * \\param[in] points pre-initialized tensor holding points\n */\nbool Mesh::sample(const int N, PointCloud& point_cloud) const {\n\n    // Stores the areas of faces.\n    std::vector<float> areas(this->num_faces());\n    float sum = 0;\n\n    // Build a probability distribution over faces.\n    for (int f = 0; f < this->num_faces(); f++) {\n        Eigen::Vector3f a = this->vertices[this->faces[f][0]];\n        Eigen::Vector3f b = this->vertices[this->faces[f][1]];\n        Eigen::Vector3f c = this->vertices[this->faces[f][2]];\n\n        // Angle between a->b and a->c.\n        Eigen::Vector3f ab = b - a;\n        Eigen::Vector3f ac = c - a;\n        float cos_angle = ab.dot(ac) / (ab.norm() * ac.norm());\n        float angle = std::acos(cos_angle);\n\n        // Compute triangle area.\n        float area = std::max(0., 0.5 * ab.norm() * ac.norm() * std::sin(angle));\n        //std::cout << area << \" \" << std::pow(area, 1./4.) << \" \" << angle << \" \" << ab.norm() << \" \" << ac.norm() << \" \" << std::sin(angle) << std::endl;\n\n        // Accumulate.\n        //area = std::sqrt(area);\n        areas[f] = area;\n        sum += area;\n        //areas.push_back(1);\n        //sum += 1;\n    }\n\n    //std::cout << sum << std::endl;\n    if (sum < 1e-6) {\n        std::cout << \"[Error] face area sum of \" << sum << std::endl;\n        return false;\n    }\n\n    for (int f = 0; f < this->num_faces(); f++) {\n        //std::cout << areas[f] << \" \";\n        areas[f] /= sum;\n        //std::cout << areas[f] << std::endl;\n    }\n\n    std::vector<float> cum_areas(areas.size());\n    cum_areas[0] = areas[0];\n\n    for (int f = 1; f < this->num_faces(); f++) {\n        cum_areas[f] = areas[f] + cum_areas[f - 1];\n    }\n\n    for (int f = 0; f < this->num_faces(); f++) {\n        int n = std::max(static_cast<int>(areas[f] * N), 1);\n\n        for (int i = 0; i < n; i++) {\n            float r1 = 0;\n            float r2 = 0;\n            do {\n                r1 = static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX);\n                r2 = static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX);\n            } while (r1 + r2 > 1.f);\n\n            int s = std::rand() % 3;\n            //std::cout << face << \" \" << areas[face] << std::endl;\n\n            Eigen::Vector3f a = this->vertices[this->faces[f](s)];\n            Eigen::Vector3f b = this->vertices[this->faces[f]((s + 1) % 3)];\n            Eigen::Vector3f c = this->vertices[this->faces[f]((s + 2) % 3)];\n\n            Eigen::Vector3f ab = b - a;\n            Eigen::Vector3f ac = c - a;\n\n            Eigen::Vector3f point = a + r1 * ab + r2 * ac;\n            point_cloud.add_point(point);\n        }\n    }\n\n    return true;\n}\n\n/** \\brief Read all files in a directory matching the given extension.\n * \\param[in] directory path to directory\n * \\param[out] files read file paths\n * \\param[in] extension extension to filter for\n */\nvoid read_directory(const fs::path directory, std::map<std::string, fs::path>& files, const std::vector<std::string>& extensions) {\n\n    files.clear();\n    fs::directory_iterator end;\n\n    for (fs::directory_iterator it(directory); it != end; ++it) {\n        bool filtered = true;\n        for (unsigned int i = 0; i < extensions.size(); i++) {\n            if (it->path().extension().string() == extensions[i]) {\n                filtered = false;\n            }\n        }\n\n        if (!filtered) {\n            const std::string basename = it->path().filename().stem().string();\n            files.insert(std::make_pair(basename, it->path()));\n        }\n    }\n}\n\n/** \\brief Main entrance point of the script.\n * Expects one parameter, the path to the corresponding config file in config/.\n */\nint main(int argc, char** argv) {\n    auto& parser = ArgumentParser::getInstance();\n    parser.addArgument(\"-i\", \"--input\", \"\", true, \"input, either single OFF file or directory containing OFF files where the names correspond to integers (zero padding allowed) and are consecutively numbered starting with zero\");\n    parser.addArgument(\"-r\", \"--reference\", \"\", true, \"reference, either single OFF or TXT file or directory containing OFF or TXT files where the names correspond to integers (zero padding allowed) and are consecutively numbered starting with zero (the file names need to correspond to those found in the input directory); for TXT files, accuracy cannot be computed\");\n    parser.addArgument(\"-o\", \"--output\", \"eval.txt\", false, \"output file, a TXT file containing accuracy and completeness for each input-reference pair as well as overall averages\");\n    parser.addArgument(\"-n\", \"--n_points\", 3000, false, \"number points to sample from meshes in order to compute distances\");\n    parser.addArgument(\"-s\", \"--n_skip\", 0, false, \"skip every n data, if specified\");\n\n    if (!parser.parse(argc, argv)) {\n        std::cout << parser.helpText() << std::endl;\n        std::exit(1);\n    }\n\n    fs::path input(parser.getString(\"input\").c_str());\n    if (!fs::is_directory(input) && !fs::is_regular_file(input)) {\n        std::cout << \"Input is neither directory nor file.\" << std::endl;\n        return 1;\n    }\n\n    fs::path reference(parser.getString(\"reference\").c_str());\n    if (!fs::is_directory(reference) && !fs::is_regular_file(reference)) {\n        std::cout << \"Reference is neither directory nor file.\" << std::endl;\n        return 1;\n    }\n\n    fs::path output(parser.getString(\"output\").c_str());\n    if (fs::is_regular_file(output)) {\n        std::cout << \"Output file already exists; overwriting.\" << std::endl;\n    }\n\n    const int N_points = parser.getInt(\"n_points\");\n    std::cout << \"Using \" << N_points << \" points.\" << std::endl;\n\n    // Traverse file or folder recursively\n    std::map<std::string, fs::path> input_files;\n    std::map<std::string, fs::path> reference_files;\n\n    if (fs::is_regular_file(input)) {\n        if (input.extension().string() != \".off\" && input.extension().string() != \".ply\") {\n            std::cout << \"Only OFF and PLY files supported as input.\" << std::endl;\n            return 1;\n        }\n\n        input_files.insert(std::make_pair(input.filename().stem().string(), input));\n    } else {\n        read_directory(input, input_files, { \".off\", \".ply\" });\n\n        if (input_files.size() <= 0) {\n            std::cout << \"Could not find any OFF and PLY files in input directory.\" << std::endl;\n            return 1;\n        }\n\n        std::cout << \"Read \" << input_files.size() << \" input files.\" << std::endl;\n    }\n\n    if (fs::is_regular_file(reference)) {\n        if (reference.extension().string() != \".off\" && reference.extension().string() != \".ply\" && reference.extension().string() != \".txt\") {\n            std::cout << \"Only OFF, PLY, or TXT files supported as reference.\" << std::endl;\n            return 1;\n        }\n\n        reference_files.insert(std::make_pair(reference.filename().stem().string(), reference));\n    } else {\n        read_directory(reference, reference_files, { \".off\", \".ply\", \".txt\" });\n\n        if (input_files.size() <= 0) {\n            std::cout << \"Could not find any OFF, PLY, or TXT files in reference directory.\" << std::endl;\n            return 1;\n        }\n\n        std::cout << \"Read \" << reference_files.size() << \" reference files.\" << std::endl;\n    }\n\n    // Skip files\n    const int n_skip = std::max(1, parser.getInt(\"n_skip\"));\n    std::cout << \"Skip every \" << n_skip << \" files.\" << std::endl;\n\n    std::map<std::string, fs::path> input_files_skip;\n    std::map<std::string, fs::path> reference_files_skip;\n    int skip_count = 0;\n    for (auto it = input_files.begin(); it != input_files.end(); ++it, ++skip_count) {\n        if (skip_count % n_skip == 0) {\n            const std::string basename = it->first;\n            input_files_skip.insert(std::make_pair(basename, input_files[basename]));\n            reference_files_skip.insert(std::make_pair(basename, reference_files[basename]));\n        }\n    }\n\n    input_files = input_files_skip;\n    reference_files = reference_files_skip;\n    std::cout << \"Process \" << input_files.size() << \" input files.\" << std::endl;\n    std::cout << \"Process \" << reference_files.size() << \" reference files.\" << std::endl;\n\n    // Compute accuracy and completeness\n    std::map<std::string, float> accuracies;\n    std::map<std::string, float> completenesses;\n    ProgressBar pbar(input_files.size());\n    for (auto it = input_files.begin(); it != input_files.end(); ++it) {\n        const std::string basename = it->first;\n        if (reference_files.find(basename) == reference_files.end()) {\n            std::cout << \"Could not find the reference file corresponding to \" << input_files[basename] << \".\" << std::endl;\n            return 1;\n        }\n\n        fs::path input_file = input_files[basename];\n        fs::path reference_file = reference_files[basename];\n\n        const std::string input_extension = input_file.extension().string();\n        const std::string reference_extension = reference_file.extension().string();\n\n        bool success = false;\n        Mesh input_mesh;\n        if (input_extension == \".off\") {\n            success = Mesh::from_off(input_file.string(), input_mesh);\n        } else if (input_extension == \".ply\") {\n            success = Mesh::from_ply(input_file.string(), input_mesh);\n        }\n\n        if (!success) {\n            std::cout << \"Could not read \" << input_file << \".\" << std::endl;\n            return 1;\n        }\n\n        if (reference_extension == \".off\" || reference_extension == \".ply\") {\n            Mesh reference_mesh;\n            if (reference_extension == \".off\") {\n                success = Mesh::from_off(reference_file.string(), reference_mesh);\n            } else if (reference_extension == \".ply\") {\n                success = Mesh::from_ply(reference_file.string(), reference_mesh);\n            }\n\n            if (!success) {\n                std::cout << \"Could not read \" << reference_file << \".\" << std::endl;\n                return 1;\n            }\n\n            PointCloud input_point_cloud;\n            success = input_mesh.sample(N_points, input_point_cloud);\n\n            if (success) {\n                float accuracy = 0;\n                success = input_point_cloud.compute_distance(reference_mesh, accuracy);\n\n                if (success) {\n                    accuracies[basename] = accuracy;\n                    std::cout << \"Computed accuracy for \" << input_file << \": \" << accuracy << std::endl;\n                } else {\n                    std::cout << \"Could not compute accuracy for \" << input_file << \".\" << std::endl;\n                }\n            } else {\n                std::cout << \"Could not compute accuracy for \" << input_file << \".\" << std::endl;\n            }\n\n            PointCloud reference_point_cloud;\n            reference_mesh.sample(N_points, reference_point_cloud);\n\n            if (success) {\n                float completeness = 0;\n                success = reference_point_cloud.compute_distance(input_mesh, completeness);\n\n                if (success) {\n                    completenesses[basename] = completeness;\n                    std::cout << \"Computed completeness for \" << input_file << \": \" << completeness << std::endl;\n                } else {\n                    std::cout << \"Could not compute completeness for \" << input_file << \".\" << std::endl;\n                }\n            } else {\n                std::cout << \"Could not compute completeness for \" << input_file << \".\" << std::endl;\n            }\n        } else if (reference_file.extension().string() == \".txt\") {\n            PointCloud reference_point_cloud;\n            success = PointCloud::from_txt(reference_file.string(), reference_point_cloud);\n\n            if (!success) {\n                std::cout << \"Could not read \" << reference_file << \".\" << std::endl;\n                return 1;\n            }\n\n            float completeness = 0;\n            success = reference_point_cloud.compute_distance(input_mesh, completeness);\n\n            if (success) {\n                completenesses[basename] = completeness;\n                std::cout << \"Computed completeness for \" << input_file << \".\" << std::endl;\n            } else {\n                std::cout << \"Could not compute completeness for \" << input_file << \".\" << std::endl;\n            }\n        } else {\n            std::cout << \"Reference file \" << reference_file << \" has invalid extension.\" << std::endl;\n        }\n\n        pbar.step();\n        printf(\"\\n\");\n    }\n\n    std::ofstream out(output.string().c_str(), std::ios::out);\n    if (out.fail()) {\n        std::cout << \"Could not open \" << output << std::endl;\n        exit(1);\n    }\n\n    float accuracy = 0;\n    float completeness = 0;\n\n    for (auto it = input_files.begin(); it != input_files.end(); it++) {\n        const std::string basename = it->first;\n\n        out << basename << \" \";\n        if (accuracies.find(basename) != accuracies.end()) {\n            out << accuracies[basename];\n            accuracy += accuracies[basename];\n        } else {\n            out << \"-1\";\n        }\n\n        out << \" \";\n        if (completenesses.find(basename) != completenesses.end()) {\n            out << completenesses[basename];\n            completeness += completenesses[basename];\n        } else {\n            out << \"-1\";\n        }\n\n        out << std::endl;\n    }\n\n\n    if (accuracies.size() > 0) {\n        accuracy /= accuracies.size();\n        out << accuracy;\n        std::cout << \"Accuracy (input to reference): \" << accuracy << std::endl;\n    } else {\n        out << \"-1\";\n        std::cout << \"Could not compute accuracy.\" << std::endl;\n    }\n\n    out << \" \";\n    if (completenesses.size() > 0) {\n        completeness /= completenesses.size();\n        out << completeness;\n        std::cout << \"Completeness (reference to input): \" << completeness << std::endl;\n    } else {\n        out << \"-1\";\n        std::cout << \"Could not compute completeness.\" << std::endl;\n    }\n\n    out.close();\n    std::cout << \"Wrote \" << output << \".\" << std::endl;\n\n    exit(0);\n}\n", "meta": {"hexsha": "28ebc318ac65509eac09fd8740afb808d88dab43", "size": 26595, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "tatsy/mesh-evaluation", "max_stars_repo_head_hexsha": "9ad7e3e551792844204acb8bbb49cc4eb250a36b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "tatsy/mesh-evaluation", "max_issues_repo_head_hexsha": "9ad7e3e551792844204acb8bbb49cc4eb250a36b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "tatsy/mesh-evaluation", "max_forks_repo_head_hexsha": "9ad7e3e551792844204acb8bbb49cc4eb250a36b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3934226553, "max_line_length": 369, "alphanum_fraction": 0.5347997744, "num_tokens": 6448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239133, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.41830855065354355}}
{"text": "#pragma once\n#include <Eigen/Dense>\n#include <fstream>\n#include <iostream>\n#include <list>\n#include <string>\n#include <iomanip>\n#include <limits>\n#include <vector>\n#include \"interpolator.hpp\"\n#include \"system.hpp\"\n#include \"rksolver.hpp\"\n#include \"wkbsolver.hpp\"\n\n\n/** A class to store all information related to a numerical solution run.  */\nclass Solution\n{\n    private:\n    double t, tf, rtol, atol, h0;\n    std::complex<double> x, dx;\n    int order;\n    const char* fo;\n    WKBSolver * wkbsolver;\n    WKBSolver1 wkbsolver1;\n    WKBSolver2 wkbsolver2;\n    WKBSolver3 wkbsolver3;\n    /** A \\a de_system object to carry information about the ODE. */\n    de_system *de_sys_;\n    /** These define the event at which integration finishes (currently: when tf\n     * is reached. */\n    double fend, fnext;\n    /** a boolean encoding the direction of integration: 1/True for forward. */\n    bool sign;\n\n    public:\n    Solution(de_system &de_sys, std::complex<double> x0, std::complex<double>\n    dx0, double t_i, double t_f, int o=3, double r_tol=1e-4, double a_tol=0.0,\n    double h_0=1, const char* full_output=\"\");\n\n    template<typename X = double> Solution(de_system &de_sys,\n    std::complex<double> x0, std::complex<double> dx0, double t_i, double t_f,\n    const X &do_times, int o=3, double r_tol=1e-4, double a_tol=0.0,\n    double h_0=1, const char* full_output=\"\");\n\n    void solve();\n    \n    /** Object to call RK steps */\n    RKSolver rksolver;\n    \n    /** Successful, total attempted, and successful WKB steps the solver took,\n     * respectively  */\n    int ssteps,totsteps,wkbsteps;\n    /** Lists to contain the solution and its derivative evaluated at internal\n     * points taken by the solver (i.e. not dense output) after a run */\n    std::list<std::complex<double>> sol, dsol;\n    /** List to contain the timepoints at which the solution and derivative are\n     * internally evaluated by the solver */\n    std::list<double> times;\n    /** List to contain the \"type\" of each step (RK/WKB) taken internally by the\n     * solver after a run */\n    std::list<bool> wkbs;\n    /** Lists to contain the timepoints at which dense output was evaluated */\n    std::list<double> dotimes, dotimes_rk;\n    /** Lists to contain the dense output of the solution and its derivative */\n    std::list<std::complex<double>> dosol, dodsol, dosol_rk, dodsol_rk;\n    /** Iterator to iterate over the dense output timepoints, for when these\n     * need to be written out to file */\n    std::list<double>::iterator dotit;\n\n};\n\n/** Constructor for when dense output was not requested. Sets up solution of the\n * ODE.\n *\n * @param[in] de_sys de_system object carrying information about the ODE being\n * solved\n * @param[in] x0, dx0 initial conditions for the ODE, \\f$ x(t) \\f$, \\f$ \\frac{dx}{dt} \\f$ evaluated at \n * the start of the integration range\n * @param[in] t_i start of integration range\n * @param[in] t_f end of integration range\n * @param[in] o order of WKB approximation to be used\n * @param[in] r_tol (local) relative tolerance\n * @param[in] a_tol (local) absolute tolerance \n * @param[in] h_0 initial stepsize to use\n * @param[in] full_output file name to write results to\n *  \n */ \nSolution::Solution(de_system &de_sys, std::complex<double> x0,\nstd::complex<double> dx0, double t_i, double t_f, int o, double r_tol, double\na_tol, double h_0, const char* full_output){\n    \n    // Make underlying equation system accessible\n    de_sys_ = &de_sys;\n\n    // Set parameters for solver\n    x = x0;\n    dx = dx0;\n    t = t_i;\n    tf = t_f;\n    order = o;\n    rtol = r_tol;\n    atol = a_tol;\n    h0 = h_0;\n    fo = full_output;\n    rksolver = RKSolver(*de_sys_);\n\n    // Determine direction of integration, fend>0 and integration ends when\n    // it crosses zero\n    if((t>=tf) and h0<0){\n        // backwards\n        fend = t-tf;\n        fnext = fend;\n        if(de_sys_->is_interpolated == 1){\n            de_sys_->Winterp.sign_ = 0;\n            de_sys_->Ginterp.sign_ = 0;\n        }\n        else\n            sign = 0;\n\n    }\n    else if((t<=tf) and h0>0){\n        // forward\n        fend = tf-t;\n        fnext = fend;\n        if(de_sys_->is_interpolated == 1){\n            de_sys_->Winterp.sign_ = 1;\n            de_sys_->Ginterp.sign_ = 1;\n        }\n        else\n            sign = 1;\n    }\n    else{\n        throw \"Direction of integration in conflict with direction of initial step, terminating. Please check your values for ti, tf, and h. \";\n        return;\n    }\n\n    // No dense output desired if this constructor was called, so only output\n    // answer at t_i and t_f\n    dotimes.push_back(t_i);\n    dotimes.push_back(t_f);\n    dosol.push_back(x0);\n    dodsol.push_back(dx0);\n    dotit = dotimes.end();\n\n    \n    switch(order){\n        case 1: wkbsolver1 = WKBSolver1(*de_sys_, order);\n                wkbsolver = &wkbsolver1;\n                break;\n        case 2: wkbsolver2 = WKBSolver2(*de_sys_, order);\n                wkbsolver = &wkbsolver2;\n                break;\n        case 3: wkbsolver3 = WKBSolver3(*de_sys_, order);\n                wkbsolver = &wkbsolver3;\n                break;\n    };\n};\n\n/** Constructor for when dense output was requested. Sets up solution of the\n * ODE.\n *\n * @param[in] de_sys de_system object carrying information about the ODE being\n * solved\n * @param[in] x0, dx0 initial conditions for the ODE, \\f$ x(t) \\f$, \\f$ \\frac{dx}{dt} \\f$ evaluated at \n * the start of the integration range\n * @param[in] t_i start of integration range\n * @param[in] t_f end of integration range\n * @param[in] do_times timepoints at which dense output is to be produced\n * @param[in] o order of WKB approximation to be used\n * @param[in] r_tol (local) relative tolerance\n * @param[in] a_tol (local) absolute tolerance \n * @param[in] h_0 initial stepsize to use\n * @param[in] full_output file name to write results to\n *  \n */ \ntemplate<typename X> Solution::Solution(de_system &de_sys, std::complex<double> x0,\nstd::complex<double> dx0, double t_i, double t_f, const X &do_times, int o, double r_tol, double\na_tol, double h_0, const char* full_output){\n\n    // Make underlying equation system accessible\n    de_sys_ = &de_sys;\n    // Set parameters for solver\n    x = x0;\n    dx = dx0;\n    t = t_i;\n    tf = t_f;\n    order = o;\n    rtol = r_tol;\n    atol = a_tol;\n    h0 = h_0;\n    fo = full_output;\n    rksolver = RKSolver(*de_sys_);\n\n    // Determine direction of integration, fend>0 and integration ends when\n    // it crosses zero\n    if((t>=tf) and h0<0){\n        // backwards\n        fend = t-tf;\n        fnext = fend;\n        if(de_sys_->is_interpolated == 1){\n            de_sys_->Winterp.sign_ = 0;\n            de_sys_->Ginterp.sign_ = 0;\n        }\n        else\n            sign = 0;\n    }\n    else if((t<=tf) and h0>0){\n        // forward\n        fend = tf-t;\n        fnext = fend;\n        if(de_sys_->is_interpolated == 1){\n            de_sys_->Winterp.sign_ = 1;\n            de_sys_->Ginterp.sign_ = 1;\n        }\n        else\n            sign = 1;\n    }\n    else{\n        throw \"Direction of integration in conflict with direction of initial step, terminating. Please check your values for ti, tf, and h. \";\n        return;\n    }\n\n    // Dense output checks: \n    int dosize = do_times.size();\n    dotimes.resize(dosize);\n    dosol.resize(dosize);\n    dodsol.resize(dosize);\n    int docount = 0;\n    auto doit = do_times.begin();\n    if(de_sys_->Winterp.sign_ == 1){\n        for(auto it=dotimes.begin(); it!=dotimes.end(); it++){\n            *it = *doit;\n            docount++; doit++;\n        }\n    }\n    else{\n         for(auto it=dotimes.rbegin(); it!=dotimes.rend(); ++it){\n            *it = *doit;\n            docount++; ++doit;\n        }\n    }\n    dotit = dotimes.begin();\n    switch(order){\n        case 1: wkbsolver1 = WKBSolver1(*de_sys_, order);\n                wkbsolver = &wkbsolver1;\n                break;\n        case 2: wkbsolver2 = WKBSolver2(*de_sys_, order);\n                wkbsolver = &wkbsolver2;\n                break;\n        case 3: wkbsolver3 = WKBSolver3(*de_sys_, order);\n                wkbsolver = &wkbsolver3;\n                break;\n    };\n};\n\n/** \\brief Function to solve the ODE \\f$ \\ddot{x} + 2\\gamma(t)\\dot{x} +\n * \\omega^2(t)x = 0 \\f$ for \\f$ x(t), \\frac{dx}{dt} \\f$.\n *\n * While solving the ODE, this function will populate the \\a Solution object\n * with the following results:\n * \n */\nvoid Solution::solve(){ \n    \n    int nrk, nwkb1, nwkb2;\n    // Settings for MS\n    nrk = 5;\n    nwkb1 = 2;\n    nwkb2 = 4;\n    Eigen::Matrix<std::complex<double>,2,2> rkstep;\n    Eigen::Matrix<std::complex<double>,3,2> wkbstep;\n    Eigen::Matrix<std::complex<double>,1,2> rkx, wkbx;\n    Eigen::Matrix<std::complex<double>,1,2> rkerr, wkberr, truncerr;\n    Eigen::Matrix<double,1,2> errmeasure_rk; \n    Eigen::Matrix<double,1,4> errmeasure_wkb;\n    double tnext, hnext, h, hrk, hwkb;\n    double wkbdelta, rkdelta;\n    std::complex<double> xnext, dxnext;\n    bool wkb = false;\n    Eigen::Index maxindex_wkb, maxindex_rk;\n    h = h0;\n    tnext = t+h;\n    // Initialise stats\n    sol.push_back(x);\n    dsol.push_back(dx);\n    times.push_back(t);\n    wkbs.push_back(false);\n    ssteps = 0;\n    totsteps = 0;\n    wkbsteps = 0;\n    // Dense output\n    std::list<double> inner_dotimes;\n    std::list<std::complex<double>> inner_dosols, inner_dodsols;\n    auto it_dosol = dosol.begin();\n    auto it_dodsol = dodsol.begin();\n    Eigen::Matrix<std::complex<double>,1,2> y_dense_rk;\n    std::complex<double> x_dense_rk, dx_dense_rk;\n\n    while(fend > 0){\n        // Check if we are reaching the end of integration\n        if(fnext < 0){\n            h = tf - t;\n            tnext = tf;\n        };\n\n        // Keep updating stepsize until step is accepted\n        while(true){\n            // RK step\n            rkstep = rksolver.step(x, dx, t, h);\n            rkx << rkstep(0,0), rkstep(0,1);\n            rkerr << rkstep(1,0), rkstep(1,1);\n            // WKB step\n            wkbstep = wkbsolver->step(x, dx, t, h, rksolver.ws, rksolver.gs, rksolver.ws5, rksolver.gs5);\n            wkbx = wkbstep.row(0);\n            wkberr = wkbstep.row(2);\n            truncerr = wkbstep.row(1);\n            // Safety feature for when all wkb steps are 0 (truncer=0), but not\n            // necessarily in good WKB regime:\n            truncerr(0) = std::max(1e-10,abs(truncerr(0)));\n            truncerr(1) = std::max(1e-10,abs(truncerr(1)));\n            // dominant error calculation\n            // Error scale measures\n            errmeasure_rk << std::abs(rkerr(0))/(std::abs(rkx(0))*rtol+atol), std::abs(rkerr(1))/(std::abs(rkx(1))*rtol+atol);\n            errmeasure_wkb << std::abs(truncerr(0))/(std::abs(wkbx(0))*rtol+atol),\n            std::abs(truncerr(1))/(std::abs(wkbx(1))*rtol+atol),\n            std::abs(wkberr(0))/(std::abs(wkbx(0))*rtol+atol),\n            std::abs(wkberr(1))/(std::abs(wkbx(1))*rtol+atol);\n            rkdelta = std::max(1e-10, errmeasure_rk.maxCoeff(&maxindex_rk)); \n            if(std::isnan(errmeasure_wkb.maxCoeff())==false &&\n               std::isinf(std::real(wkbx(0)))==false &&\n               std::isinf(std::imag(wkbx(0)))==false &&\n               std::isinf(std::real(wkbx(1)))==false &&\n               std::isinf(std::imag(wkbx(1)))==false &&\n               std::isnan(std::real(wkbx(0)))==false &&\n               std::isnan(std::imag(wkbx(0)))==false &&\n               std::isnan(std::real(wkbx(1)))==false &&\n               std::isnan(std::imag(wkbx(1)))==false){\n                wkbdelta = std::max(1e-10, errmeasure_wkb.maxCoeff(&maxindex_wkb));\n            }\n            else{\n                wkbdelta = std::numeric_limits<double>::infinity();\n            }\n\n            // predict next stepsize \n            hrk = h*std::pow((1.0/rkdelta),1.0/nrk);\n            if(maxindex_wkb<=1)\n                hwkb = h*std::pow(1.0/wkbdelta,1.0/nwkb1);\n            else\n                hwkb = h*std::pow(1.0/wkbdelta,1.0/nwkb2);\n            // choose step with larger predicted stepsize\n            if(std::abs(hwkb) >= std::abs(hrk)){\n                wkb = true;\n            }\n            else{\n                wkb = false;\n            }\n            if(wkb){\n                xnext = wkbx(0);\n                dxnext = wkbx(1);\n                // if wkb step chosen, ignore truncation error in\n                // stepsize-increase\n                wkbdelta = std::max(1e-10, errmeasure_wkb.tail(2).maxCoeff());\n                hnext = h*std::pow(1.0/wkbdelta,1.0/nwkb2);\n            }\n            else{\n                xnext = rkx(0);\n                dxnext = rkx(1);\n                hnext = hrk;\n            };\n            totsteps += 1;\n            // Checking for too many steps and low acceptance ratio:\n            if(totsteps % 5000 == 0){\n                std::cerr << \"Warning: the solver took \" << totsteps << \" steps, and may take a while to converge.\" << std::endl; \n                if(ssteps/totsteps < 0.05){\n                    std::cerr << \"Warning: the step acceptance ratio is below 5%, the solver may take a while to converge.\" << std::endl;\n                }\n            }\n\n            // check if chosen step was successful\n            if(std::abs(hnext)>=std::abs(h)){\n                if(dotit!=dotimes.end()){\n                    while((*dotit-t>=0 && tnext-*dotit>=0) or (*dotit-t<=0 && tnext-*dotit<=0)){\n                        inner_dotimes.push_back(*dotit);\n                        dotit++;\n                    }\n                    if(inner_dotimes.size() > 0){\n                        inner_dosols.resize(inner_dotimes.size());\n                        inner_dodsols.resize(inner_dotimes.size());\n                        if(wkb){\n                            // Dense output after successful WKB step\n                            wkbsolver->dense_step(t,inner_dotimes,inner_dosols,inner_dodsols);\n                        }\n                        else{\n                            // Dense output after successful RK step\n                            for(auto it=inner_dotimes.begin(); it!=inner_dotimes.end(); it++)\n                                rksolver.dense_step(t,h,x,dx,inner_dotimes,inner_dosols,inner_dodsols);\n                        }\n                    }\n                }\n                auto inner_it=inner_dosols.begin();\n                auto inner_dit=inner_dodsols.begin();\n                while(inner_it!=inner_dosols.end() && it_dosol!=dosol.end() && inner_dit!=inner_dodsols.end() && it_dodsol!=dodsol.end()){\n                    *it_dosol = *inner_it;\n                    *it_dodsol = *inner_dit;\n                    it_dodsol++;\n                    it_dosol++;\n                    inner_it++;\n                    inner_dit++;\n                }\n                inner_dotimes.resize(0);\n                inner_dosols.resize(0);\n                inner_dodsols.resize(0);\n               \n                // record type of step\n                if(wkb){\n                    wkbsteps +=1;\n                    wkbs.push_back(true);\n                }\n                else{\n                    wkbs.push_back(false);\n                }\n                sol.push_back(xnext);\n                dsol.push_back(dxnext);\n                times.push_back(tnext);\n                tnext += hnext;\n                x = xnext;\n                dx = dxnext;\n                t += h;\n                h = hnext;\n                if(h>0){\n                    fend=tf-t;\n                    fnext=tf-tnext;\n                }\n                else{\n                    fend=t-tf;\n                    fnext=tnext-tf;\n                };\n                ssteps +=1;\n                // Update interpolation bounds\n                if(de_sys_->is_interpolated == 1){\n                    de_sys_->Winterp.update_interp_bounds();\n                    de_sys_->Ginterp.update_interp_bounds();\n                }\n\n                break;\n            }\n            else{\n                if(wkb){\n                    if(maxindex_wkb<=1){\n                        if(nwkb1 > 1)\n                            hnext = h*std::pow(1.0/wkbdelta,1.0/(nwkb1-1));\n                        else\n                            hnext = 0.95*h*1.0/wkbdelta;\n                    }\n                    else\n                        hnext = h*std::pow(1.0/wkbdelta,1.0/(nwkb2-1));\n                }\n                else\n                    hnext = h*std::pow(1.0/rkdelta,1.0/(nrk-1));\n                h = hnext;\n                tnext = t + hnext;\n                if(h>0){\n                    fnext=tf-tnext;\n                }\n                else{\n                    fnext=tnext-tf;\n                };\n            };\n        };\n    };\n\n    // If integrating backwards, reverse dense output (because it will have been\n    // reversed at the start)\n    if(de_sys_->is_interpolated == 1){\n        if(de_sys_->Winterp.sign_ == 0){\n            dosol.reverse();\n            dodsol.reverse();\n        }\n    }\n    else{\n        if(sign == 0){\n            dosol.reverse();\n            dodsol.reverse();\n        }\n    }\n\n    // Write output to file if prompted\n    if(not (*fo==0)){\n        std::string output(fo);\n        std::ofstream f;\n        f.open(output);\n        f << \"# Summary:\\n# total steps taken: \" + std::to_string(totsteps) +\n        \"\\n# of which successful: \" + std::to_string(ssteps) + \"\\n# of which\"+\n        +\" wkb: \" + std::to_string(wkbsteps) + \"\\n# time, sol, dsol, wkb? (type)\\n\";\n        auto it_t = times.begin();\n        auto it_w = wkbs.begin();\n        auto it_x = sol.begin();\n        auto it_dx = dsol.begin();\n        for(int i=0; i<=ssteps; i++){\n            f << std::setprecision(15) << *it_t << \";\" <<\n            std::setprecision(15) << *it_x << \";\" << std::setprecision(15) <<\n            *it_dx << \";\" << *it_w << \"\\n\"; \n            ++it_t;\n            ++it_x;\n            ++it_dx;\n            ++it_w;\n        }\n        // print all dense output to file\n        int dosize = dosol.size();\n        auto it_dosol = dosol.begin();\n        auto it_dotimes = dotimes.begin();\n        auto it_dodsol = dodsol.begin();\n        for(int i=0; i<dosize; i++){\n            f << std::setprecision(20) << *it_dotimes << \";\" << std::setprecision(20) << *it_dosol << \";\" << *it_dodsol << \";\\n\";\n            ++it_dosol;\n            ++it_dodsol;\n            ++it_dotimes;\n        }\n\n        f.close();\n    }\n    \n};\n", "meta": {"hexsha": "e739b2ccaa99507db6794bb964da5db80fd55afc", "size": 18272, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/solver.hpp", "max_stars_repo_name": "lukashergt/oscode", "max_stars_repo_head_hexsha": "d5807fd0a3a92a57419aeb5e921f484d4a2ada60", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2019-06-11T02:24:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T20:40:05.000Z", "max_issues_repo_path": "include/solver.hpp", "max_issues_repo_name": "lukashergt/oscode", "max_issues_repo_head_hexsha": "d5807fd0a3a92a57419aeb5e921f484d4a2ada60", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2020-04-19T14:59:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T16:53:34.000Z", "max_forks_repo_path": "include/solver.hpp", "max_forks_repo_name": "lukashergt/oscode", "max_forks_repo_head_hexsha": "d5807fd0a3a92a57419aeb5e921f484d4a2ada60", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T08:27:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T11:46:46.000Z", "avg_line_length": 34.8038095238, "max_line_length": 143, "alphanum_fraction": 0.5264338879, "num_tokens": 4943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.41830853532674744}}
{"text": "/*\n * Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com)\n * Distributed under the MIT License.\n * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT\n */\n\n// This code will convert multiple cartesian state vectors \n// into TLE and check where exactly the Atom is failing. The cartesian\n// vectors are generated by converting randomly generated keplerian elements. \n// The conversion is achieved through the pykep library of ESA.  \n\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <exception>\n#include <cstdlib>\n#include <execinfo.h>\n\n#include <boost/exception/info.hpp>\n#include <libsgp4/Globals.h>\n#include <SML/sml.hpp>\n#include <SML/constants.hpp>\n#include <SML/basicFunctions.hpp>\n\n#include \"CppProject/randomKepElem.hpp\"\n#include \"CppProject/KepToCart.hpp\"\n#include \"CppProject/KepToCartToTLE.hpp\"\n#include \"CppProject/randomGen.hpp\"\n\n\ntypedef double Real;\ntypedef std::vector< Real > Vector6;\ntypedef std::vector< Real > Vector3;\ntypedef std::vector< Real > Vector2;\ntypedef std::vector < std::vector < Real > > Vector2D;\n\nint main(void)\n{\n\n    // some constants values are defined here\n    const double km2m = 1000; // conversion from km to m\n    // earth radius\n    const double EarthRadius = kXKMPER * km2m; // unit m\n    const double EarthDiam = 2 * EarthRadius;\n    // grav. parameter 'mu' of earth\n    // const double muEarth = kMU*( pow( 10, 9 ) ); // unit m^3/s^2\n    const int bypass = true; // make this false to execute code with random orbital elements\n\n    if(bypass == false){\n        // initialize input parameters for the function generating random orbital elements. Description can be\n        // found in randomKepElem.hpp for each of the following parameters. \n        const Vector2 range_a      = { (EarthDiam+100000), (EarthDiam+1000000) }; \n        const Vector2 range_e      = { 0, 1 };\n        const Vector2 range_i      = { 0, sml::convertDegreesToRadians( 180.0 ) };\n        const Vector2 range_raan   = { 0, sml::convertDegreesToRadians( 360.0 ) };\n        const Vector2 range_w      = { 0, sml::convertDegreesToRadians( 360.0 ) };\n        const Vector2 range_E      = { 0, sml::convertDegreesToRadians( 360.0 ) };\n        const int limit            = 100;\n        Vector2D randKep( limit, std::vector< Real >( 6 ) );\n        \n        // call the function to generate random keplerian orbital elements. Values are stored in randKepElem in a 2D\n        // vector format. A single row represents one set of orbital elements, arranged in the same order as the\n        // input argument order of the elements. \n        randomKepElem::randomKepElem( range_a, range_e, range_i, range_raan, range_w, range_E, limit, randKep );\n\n        \n        // remove orbital elements where the radius of perigee is inside earth\n        Vector2D randKepElem( limit, std::vector< Real >( 6 ) );\n        int newLimit = limit; // whenever a row of cartesian (keplerian) elements is removed, the limit will have to be changed. \n        Real radiusPerigee = 0; // variable storing the radius of Perigee for an orbit. this is used in our checking condition\n        std::vector< int > rowsToDelete; // stores the row numbers which have to be deleted\n        int insideCounter = 0; // to count the number of times radius of perigee is inside the Earth. \n        int outsideCounter = 0; // to count the number of times the radius of perigee is beyond a cetain upper limit\n        int newIndex = 0; // index counter for the second 2D vector\n        for(int j = 0; j < newLimit; j++)\n        {\n            radiusPerigee = randKep[ j ][ 0 ] * (1 - randKep[ j ][ 1 ]);\n            if(radiusPerigee <= EarthRadius )\n            {\n                insideCounter = insideCounter + 1; // counter increments everytime the condition is true\n            }\n            if(radiusPerigee >= (EarthRadius+2000000))\n            {\n                outsideCounter = outsideCounter + 1;\n            }\n            if(radiusPerigee > EarthRadius && radiusPerigee < (EarthRadius+2000000)) // this is obv not the most efficient way\n            {\n                randKepElem[ newIndex ] = randKep[ j ];\n                newIndex++;\n            }\n        } \n        randKepElem.erase( randKepElem.begin() + newIndex, randKepElem.end() ); // delete the left over rows in the final random keplerian element vector\n        std::vector< std::vector < Real > > ().swap(randKep); // create an empty vector with no memory allocated to it ...\n        // ... and swap it with the vector which you want to delete and deallocate the memory\n        std::cout << \"Inside counter value = \" << insideCounter << std::endl;\n        std::cout << \"Outside counter value = \" << outsideCounter << std::endl;\n        std::cout << \"Usefull sets left = \" << limit - (insideCounter + outsideCounter) << std::endl;\n        newLimit = randKepElem.size();\n        std::cout << \"Number of final rows in randKepElem 2D vector = \" << newLimit << std::endl;\n        KepToCartToTLE::KepToCartToTLE( newLimit, randKepElem );\n    }\n    else{\n            const int newLimit = 2;\n            Vector2D randKepElem( newLimit, std::vector < Real >( 6 ) );\n            int indexer = 0;\n\n            Vector2 range_a = { (EarthRadius + 100 * km2m), (EarthRadius + 1000 * km2m) }; // range for semi major axis\n            std::vector< Real > semiAxis (newLimit, 0); // initialize vector of size newLimit with all zeros as elements\n            randomGen::randomGen( range_a, newLimit, semiAxis); // random generator\n            for(int i = 0; i < newLimit; i++)\n            {\n                randKepElem[ i ][ 0 ] = semiAxis[ i ]; // semi major axis\n                randKepElem[ i ][ 1 ] = 0; // eccentricity\n                randKepElem[ i ][ 2 ] = sml::convertDegreesToRadians( 0 ); // inclination\n                randKepElem[ i ][ 3 ] = sml::convertDegreesToRadians( 0 ); // RAAN\n                randKepElem[ i ][ 4 ] = sml::convertDegreesToRadians( 0 ); //AOP\n                randKepElem[ i ][ 5 ] = sml::convertDegreesToRadians( 0 ); //EA\n            }\n            while( indexer < newLimit)\n            {\n                try\n                {\n                    indexer++;\n                    KepToCartToTLE::KepToCartToTLE( 1, randKepElem );   \n                    std::cout << \"indexer = \" << indexer << std::endl;\n                     \n                }\n                catch(const std::exception& err)\n                {\n                    std::cout << \"Error Caught = \";\n                    std::cout << err.what() << std::endl;\n                }\n            }\n        }\n   return EXIT_SUCCESS;\n}\n\n    \n\n\n", "meta": {"hexsha": "f86abe212946a2457853e21508cdc7af322a820e", "size": 6668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Atom-cartesianToTLE.cpp", "max_stars_repo_name": "abhi-agrawal/ATOM_ADR", "max_stars_repo_head_hexsha": "b3bfe9f0ff75bd188a06422342b3eec391942db9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Atom-cartesianToTLE.cpp", "max_issues_repo_name": "abhi-agrawal/ATOM_ADR", "max_issues_repo_head_hexsha": "b3bfe9f0ff75bd188a06422342b3eec391942db9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Atom-cartesianToTLE.cpp", "max_forks_repo_name": "abhi-agrawal/ATOM_ADR", "max_forks_repo_head_hexsha": "b3bfe9f0ff75bd188a06422342b3eec391942db9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.3055555556, "max_line_length": 153, "alphanum_fraction": 0.6084283143, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.41829521274664994}}
{"text": "#ifndef SLIDE_POINT_HPP_\n#define SLIDE_POINT_HPP_\n\n#include <array>\n#include <cstdlib>\n#include <iostream>\n\n#include <boost/assert.hpp>\n\n#include \"Direction.hpp\"\n#include \"util/abs.hpp\"\n#include \"util/define.hpp\"\n\n#ifdef __gcc__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wmaybe-uninitialized\"\n#endif\n\nnamespace slide\n{\n\nclass Point\n{\npublic:\n\tint y;\n\tint x;\n\n\tPoint() = default;\n\n\tconstexpr Point(int y, int x) : y(y), x(x) {}\n\n\tconstexpr explicit Point(uchar v, int w = MAX_DIVISION_NUM) : Point(v/w, v%w) {}\n\n\tconstexpr uchar toInt(int w = MAX_DIVISION_NUM) const {\n\t\treturn y * w + x;\n\t}\n\n\tconstexpr int l1norm() const {\n\t\treturn util::abs(y) + util::abs(x);\n\t}\n\n\tconstexpr bool isIn(int height, int width) const {\n\t\treturn isIn(0, 0, height, width);\n\t}\n\n\tconstexpr bool isIn(int py, int px, int height, int width) const {\n\t\treturn py <= y && y < py+height && px <= x && x < px+width;\n\t}\n\n\tconstexpr Point operator+ (const Point& p) const {\n\t\treturn Point(y+p.y, x+p.x);\n\t}\n\n\tconstexpr Point operator- (const Point& p) const {\n\t\treturn Point(y-p.y, x-p.x);\n\t}\n\n\tconstexpr Point operator+ () const {\n\t\treturn *this;\n\t}\n\n\tconstexpr Point operator- () const {\n\t\treturn Point(-y, -x);\n\t}\n\n\tPoint& operator+=(const Point& p){\n\t\ty += p.y;\n\t\tx += p.x;\n\t\treturn *this;\n\t}\n\n\tPoint& operator-=(const Point& p){\n\t\ty -= p.y;\n\t\tx -= p.x;\n\t\treturn *this;\n\t}\n\n\tconstexpr Point operator* (const int v) const {\n\t\treturn Point(y*v, x*v);\n\t}\n\n\tPoint& operator*=(const int v) {\n\t\ty *= v;\n\t\tx *= v;\n\t\treturn *this;\n\t}\n\n\tconstexpr bool operator==(const Point& p) const {\n\t\treturn y == p.y && x == p.x;\n\t}\n\n\tconstexpr bool operator!=(const Point& p) const {\n\t\treturn y != p.y || x != p.x;\n\t}\n\n\tbool operator< (const Point& p) const {\n\t\treturn (x != p.x ? x < p.x : y < p.y);\n\t}\n\n\tstatic constexpr Point delta(Direction dir) {\n\t\t/*\n\t\t// I wanna use C++14!\n\t\tswitch(dir){\n\t\t\tcase Direction::Up:    return Point(-1,  0);\n\t\t\tcase Direction::Right: return Point( 0,  1);\n\t\t\tcase Direction::Down:  return Point( 1,  0);\n\t\t\tcase Direction::Left:  return Point( 0, -1);\n\t\t}\n\t\t*/\n\t\treturn\n\t\tdir == Direction::Up ?    Point(-1,  0) : (\n\t\tdir == Direction::Right ? Point( 0,  1) : (\n\t\tdir == Direction::Down ?  Point( 1,  0) : \n\t\t\t\t\t\t\t\t  Point( 0, -1)\n\t\t));\n\t}\n\n\tfriend std::ostream& operator<<(std::ostream& out, const Point& p) {\n\t\treturn out << '(' << p.x << ',' << p.y << ')';\n\t}\n\n\n    /**************************************************************************\n     * Rotation and flip\n     *************************************************************************/\n\n\tconstexpr Point rotateCW(int H) const {\n\t\treturn Point(x, H-y-1);\n\t}\n\n\tconstexpr Point rotateCCW(int W) const {\n\t\treturn Point(W-x-1, y);\n\t}\n\n\tconstexpr Point opposite(int H, int W) const {\n\t\treturn Point(H-y-1, W-x-1);\n\t}\n\n\tconstexpr Point flipY(int H) const {\n\t\treturn Point(H-y-1, x);\n\t}\n\n\tconstexpr Point flipX(int W) const {\n\t\treturn Point(y, W-x-1);\n\t}\n\n\tPoint rotateFlip(Direction topSide, bool yflip, bool xflip, int H, int W) const {\n\t\tPoint ret = *this;\n\t\tif(yflip) ret = ret.flipY(H);\n\t\tif(xflip) ret = ret.flipX(W);\n\t\tif(topSide == Direction::Up)    return ret;\n\t\tif(topSide == Direction::Right) return rotateCCW(W);\n\t\tif(topSide == Direction::Down)  return opposite(H, W);\n\t\treturn rotateCW(H);\n\t}\n};\n\n} // end of namespace slide\n\n#ifdef __gcc__\n#pragma GCC diagnostic pop\n#endif\n\n#endif\n", "meta": {"hexsha": "efe6a6a132f77d5f31edfe1c565f55c639a6f09d", "size": 3362, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solver/modules/slide/include/slide/Point.hpp", "max_stars_repo_name": "taiheioki/procon2014_ut", "max_stars_repo_head_hexsha": "8199ff0a54220f1a0c51acece377f65b64db4863", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-14T06:41:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-29T01:56:08.000Z", "max_issues_repo_path": "solver/modules/slide/include/slide/Point.hpp", "max_issues_repo_name": "taiheioki/procon2014_ut", "max_issues_repo_head_hexsha": "8199ff0a54220f1a0c51acece377f65b64db4863", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solver/modules/slide/include/slide/Point.hpp", "max_forks_repo_name": "taiheioki/procon2014_ut", "max_forks_repo_head_hexsha": "8199ff0a54220f1a0c51acece377f65b64db4863", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3757575758, "max_line_length": 82, "alphanum_fraction": 0.5871505057, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.41829521274664994}}
{"text": "// Copyright 2004, 2005 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_FRUCHTERMAN_REINGOLD_FORCE_DIRECTED_LAYOUT_HPP\n#define BOOST_GRAPH_FRUCHTERMAN_REINGOLD_FORCE_DIRECTED_LAYOUT_HPP\n\n#include <cmath>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <vector>\n#include <list>\n#include <algorithm> // for std::min, std::max, std::accumulate\n#include <boost/graph/point_traits.hpp>\n#include <functional>\n#include <numeric>\n\n#include <stdlib.h> // for drand48\n\nnamespace boost {\n\nusing boost::graph::point_traits;\n\nstruct square_distance_attractive_force {\n  template<typename Graph, typename T>\n  T\n  operator()(typename graph_traits<Graph>::edge_descriptor,\n             T k,\n             T d,\n             const Graph&) const\n  {\n    return d * d / k;\n  }\n};\n\nstruct square_distance_repulsive_force {\n  template<typename Graph, typename T>\n  T\n  operator()(typename graph_traits<Graph>::vertex_descriptor,\n             typename graph_traits<Graph>::vertex_descriptor,\n             T k,\n             T d,\n             const Graph&) const\n  {\n    return k * k / d;\n  }\n};\n\ntemplate<typename T>\nstruct linear_cooling {\n  typedef T result_type;\n\n  linear_cooling(std::size_t iterations)\n    : temp(T(iterations) / T(10)), step(0.1) { }\n\n  linear_cooling(std::size_t iterations, T temp)\n    : temp(temp), step(temp / T(iterations)) { }\n\n  T operator()()\n  {\n    T old_temp = temp;\n    temp -= step;\n    if (temp < T(0)) temp = T(0);\n    return old_temp;\n  }\n\n private:\n  T temp;\n  T step;\n};\n\nstruct all_force_pairs\n{\n  template<typename Graph, typename ApplyForce >\n  void operator()(const Graph& g, ApplyForce apply_force)\n  {\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\n    vertex_iterator v, end;\n    for (tie(v, end) = vertices(g); v != end; ++v) {\n      vertex_iterator u = v;\n      for (++u; u != end; ++u) {\n        apply_force(*u, *v);\n        apply_force(*v, *u);\n      }\n    }\n  }\n};\n\nnamespace detail {\n  template<typename Point>\n  Point point_difference(const Point& p1, const Point& p2)\n  {\n    Point result;\n    std::size_t dims = point_traits<Point>::dimensions(p1);\n    for (std::size_t i = 0; i < dims; ++i)\n      result[i] = p1[i] - p2[i];\n    return result;\n  }\n\n  template<typename Point>\n  typename point_traits<Point>::component_type \n  point_norm(const Point& p)\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif\n    typename point_traits<Point>::component_type result(0);\n    std::size_t dims = point_traits<Point>::dimensions(p);\n    for (std::size_t i = 0; i < dims; ++i)\n      result += p[i] * p[i];\n    return sqrt(result);\n  }\n\n  template<typename Point>\n  void \n  maybe_jitter_point(Point& p1, const Point& p2, Point origin, Point extent)\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n    using std::fabs;\n    using std::rand;\n#endif // BOOST_NO_STDC_NAMESPACE\n    typedef typename point_traits<Point>::component_type Dim;\n    std::size_t dims = point_traits<Point>::dimensions(p1);\n    for (std::size_t i = 0; i < dims; ++i) {\n      Dim too_close = extent[i] / Dim(10000);\n      if (fabs(p1[i] - p2[i]) < too_close) {\n        Dim dist_to_move = sqrt(extent[i]) / Dim(200);\n        if (p1[i] - origin[i] < origin[i] + extent[i] - p1[i])\n          p1[i] += dist_to_move * Dim(rand() % 100) / Dim(100);\n        else\n          p1[i] -= dist_to_move * Dim(rand() % 100) / Dim(100);\n      }\n    }\n  }\n\n  template<typename PositionMap, typename DisplacementMap,\n           typename RepulsiveForce, typename Graph>\n  struct fr_apply_force\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n    typedef typename property_traits<PositionMap>::value_type Point;\n    typedef typename point_traits<Point>::component_type Dim;\n\n    fr_apply_force(const PositionMap& position,\n                   const DisplacementMap& displacement,\n                   Point origin, Point extent,\n                   RepulsiveForce repulsive_force, Dim k, const Graph& g)\n      : position(position), displacement(displacement), origin(origin),\n        extent(extent), repulsive_force(repulsive_force), k(k), g(g)\n    { \n      dims = point_traits<Point>::dimensions(origin);\n    }\n\n    void operator()(vertex_descriptor u, vertex_descriptor v)\n    {\n#ifndef BOOST_NO_STDC_NAMESPACE\n      using std::sqrt;\n#endif // BOOST_NO_STDC_NAMESPACE\n      if (u != v) {\n        // When the vertices land on top of each other, move the\n        // first vertex away from the boundaries.\n        maybe_jitter_point(position[u], position[v], origin, extent);\n\n        // DPG TBD: Can we use the Topology concept's\n        // distance/move_position_toward to handle this?\n        Point delta = detail::point_difference(position[v], position[u]);\n        Dim dist = detail::point_norm(delta);\n\n        if (dist == Dim(0)) {\n          for (std::size_t i = 0; i < dims; ++i)\n            displacement[v][i] += 0.01;\n        } else {\n          Dim fr = repulsive_force(u, v, k, dist, g);\n\n          for (std::size_t i = 0; i < dims; ++i)\n            displacement[v][i] += delta[i] / dist * fr;\n        }\n      }\n    }\n\n  private:\n    PositionMap position;\n    DisplacementMap displacement;\n    Point origin;\n    Point extent;\n    RepulsiveForce repulsive_force;\n    Dim k;\n    const Graph& g;\n    std::size_t dims;\n  };\n\n} // end namespace detail\n\ntemplate<typename PositionMap>\nstruct grid_force_pairs\n{\n  typedef typename property_traits<PositionMap>::value_type Point;\n  typedef typename point_traits<Point>::component_type Dim;\n\n  template<typename Graph>\n  explicit\n  grid_force_pairs(const Point& origin, const Point& extent, \n                   PositionMap position, const Graph& g)\n    : origin(origin), extent(extent), position(position)\n  {\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif // BOOST_NO_STDC_NAMESPACE\n    std::size_t dims = point_traits<Point>::dimensions(origin);\n    two_k = Dim(2) * sqrt(std::accumulate(&extent[0], &extent[0] + dims,\n                                          Dim(1), std::multiplies<Dim>()));\n\n    num_buckets.resize(dims);\n    for (std::size_t i = 0; i < dims; ++i)\n      num_buckets[i] = std::size_t(extent[i] / two_k + Dim(1));\n  }\n\n  template<typename Graph, typename ApplyForce >\n  void operator()(const Graph& g, ApplyForce apply_force)\n  {\n    typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n    typedef std::list<vertex_descriptor> bucket_t;\n    typedef std::vector<bucket_t> buckets_t;\n\n#ifndef BOOST_NO_STDC_NAMESPACE\n    using std::sqrt;\n#endif // BOOST_NO_STDC_NAMESPACE\n    std::size_t dims = point_traits<Point>::dimensions(origin);\n\n    buckets_t buckets(std::accumulate(&num_buckets[0], &num_buckets[0] + dims,\n                                      std::size_t(1), \n                                      std::multiplies<std::size_t>()));\n    vertex_iterator v, v_end;\n    for (tie(v, v_end) = vertices(g); v != v_end; ++v) {\n      std::vector<std::size_t> bucket(dims);\n      for (std::size_t i = 0; i < dims; ++i) {\n        bucket[i] = std::size_t((position[*v][i] + origin[i]) / two_k);\n        if (bucket[i] >= num_buckets[i]) bucket[i] = num_buckets[i] - 1;\n      }\n      buckets[bucket_to_index(bucket)].push_back(*v);\n    }\n\n    std::vector<std::size_t> cell(2);\n    do {\n      bucket_t& bucket = buckets[bucket_to_index(cell)];\n\n      std::vector<std::size_t> start_cell(dims);\n      std::vector<std::size_t> end_cell(dims);\n      \n      for (std::size_t i = 0; i < dims; ++i) {\n        start_cell[i] = cell[i] == 0? 0 : cell[i] - 1;\n        end_cell[i] = cell[i] == num_buckets[i] - 1? cell[i] : cell[i] + 1;\n      }\n\n      // Repulse vertices in this bucket\n      typedef typename bucket_t::iterator bucket_iterator;\n      \n      std::vector<std::size_t> adj_cell = start_cell;\n      do {\n        for (bucket_iterator u = bucket.begin(); u != bucket.end(); ++u) {\n          // Repulse vertices in this bucket\n          bucket_t& other_bucket = buckets[bucket_to_index(adj_cell)];\n          for (bucket_iterator v = other_bucket.begin(); v != other_bucket.end(); ++v) {\n            Point delta = detail::point_difference(position[*u],\n                                                   position[*v]);\n            Dim dist = detail::point_norm(delta);\n            if (dist < two_k) apply_force(*u, *v);\n          }\n        } \n      } while (next_bucket_in_subgrid(adj_cell, start_cell, end_cell));\n    } while (next_bucket(cell));\n  }\n  \nprivate:\n  bool next_bucket_in_subgrid(std::vector<std::size_t>& bucket,\n                              const std::vector<std::size_t>& start,\n                              const std::vector<std::size_t>& end)\n  {\n    // Find the next bucket \n    std::size_t index = bucket.size() - 1;\n    do {\n      if (bucket[index]++ >= end[index]) {\n        bucket[index] = start[index];\n        \n        if (index == 0)\n          return false;\n        --index;\n      } else {\n        return true;\n      }\n    } while (true);\n  }\n\n  bool next_bucket(std::vector<std::size_t>& bucket)\n  {\n    // Find the next bucket \n    std::size_t index = bucket.size() - 1;\n    do {\n      if (++bucket[index] >= num_buckets[index]) {\n        bucket[index] = 0;\n        \n        if (index == 0)\n          return false;\n        --index;\n      } else {\n        return true;\n      }\n    } while (true);\n  }\n\n  std::size_t bucket_to_index(const std::vector<std::size_t>& bucket)\n  {\n    std::size_t multiplier = 1;\n    std::size_t result = 0;\n\n    std::size_t dims = num_buckets.size();\n    for (std::size_t i = 0; i < dims; ++i) {\n      result += bucket[i] * multiplier;\n      multiplier *= num_buckets[i];\n    }\n    return result;\n  }\n\n  Point origin;\n  Point extent;\n  PositionMap position;\n  Dim two_k;\n  std::vector<std::size_t> num_buckets;\n};\n\ntemplate<typename PositionMap, typename Graph>\ninline grid_force_pairs<PositionMap>\nmake_grid_force_pairs\n  (typename property_traits<PositionMap>::value_type const& origin,\n   typename property_traits<PositionMap>::value_type const& extent,\n   const PositionMap& position, const Graph& g)\n{ return grid_force_pairs<PositionMap>(origin, extent, position, g); }\n\ntemplate<typename Graph, typename PositionMap, \n         typename AttractiveForce, typename RepulsiveForce,\n         typename ForcePairs, typename Cooling, typename DisplacementMap>\nvoid\nfruchterman_reingold_force_directed_layout\n (const Graph&    g,\n  PositionMap     position,\n  typename property_traits<PositionMap>::value_type const& origin,\n  typename property_traits<PositionMap>::value_type const& extent,\n  AttractiveForce attractive_force,\n  RepulsiveForce  repulsive_force,\n  ForcePairs      force_pairs,\n  Cooling         cool,\n  DisplacementMap displacement)\n{\n  typedef typename property_traits<PositionMap>::value_type Point;\n  typedef typename point_traits<Point>::component_type Dim;\n  typedef typename graph_traits<Graph>::vertex_iterator   vertex_iterator;\n  typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n  typedef typename graph_traits<Graph>::edge_iterator     edge_iterator;\n\n#ifndef BOOST_NO_STDC_NAMESPACE\n  using std::sqrt;\n#endif // BOOST_NO_STDC_NAMESPACE\n\n  std::size_t num_dimensions = point_traits<Point>::dimensions(origin);\n  Dim volume = std::accumulate(&extent[0], &extent[0] + num_dimensions,\n                               Dim(1), std::multiplies<Dim>());\n\n  // assume positions are initialized randomly\n  Dim k = sqrt(volume / num_vertices(g));\n\n  detail::fr_apply_force<PositionMap, DisplacementMap,\n                         RepulsiveForce, Graph>\n    apply_force(position, displacement, origin, extent, repulsive_force, k, g);\n\n  do {\n    // Calculate repulsive forces\n    vertex_iterator v, v_end;\n    for (tie(v, v_end) = vertices(g); v != v_end; ++v)\n      displacement[*v] = Point();\n    force_pairs(g, apply_force);\n\n    // Calculate attractive forces\n    edge_iterator e, e_end;\n    for (tie(e, e_end) = edges(g); e != e_end; ++e) {\n      vertex_descriptor v = source(*e, g);\n      vertex_descriptor u = target(*e, g);\n\n      if (u != v) {\n        // When the vertices land on top of each other, move the\n        // first vertex away from the boundaries.\n        ::boost::detail::maybe_jitter_point(position[u], position[v], \n                                            origin, extent);\n\n        // DPG TBD: Can we use the Topology concept's\n        // distance/move_position_toward to handle this?\n        Point delta = detail::point_difference(position[v], position[u]);\n        Dim dist = detail::point_norm(delta);\n        Dim fa = attractive_force(*e, k, dist, g);\n\n        for (std::size_t dim = 0; dim < num_dimensions; ++dim) {\n          displacement[v][dim] -= delta[dim] / dist * fa;\n          displacement[u][dim] += delta[dim] / dist * fa;\n        }\n      }\n    }\n\n    if (Dim temp = cool()) {\n      // Update positions\n      for (tie(v, v_end) = vertices(g); v != v_end; ++v) {\n        BOOST_USING_STD_MIN();\n        BOOST_USING_STD_MAX();\n        Dim disp_size = detail::point_norm(displacement[*v]);\n\n        for (std::size_t dim = 0; dim < num_dimensions; ++dim) {\n          position[*v][dim] += displacement[*v][dim] / disp_size \n                             * (min)(disp_size, temp);\n          position[*v][dim] = (min)(origin[dim] + extent[dim], \n                                    (max)(origin[dim], position[*v][dim]));\n        }\n      }\n    } else {\n      break;\n    }\n  } while (true);\n}\n\nnamespace detail {\n  template<typename DisplacementMap>\n  struct fr_force_directed_layout\n  {\n    template<typename Graph, typename PositionMap, \n             typename AttractiveForce, typename RepulsiveForce,\n             typename ForcePairs, typename Cooling,\n             typename Param, typename Tag, typename Rest>\n    static void\n    run(const Graph&    g,\n        PositionMap     position,\n        typename property_traits<PositionMap>::value_type const& origin,\n        typename property_traits<PositionMap>::value_type const& extent,\n        AttractiveForce attractive_force,\n        RepulsiveForce  repulsive_force,\n        ForcePairs      force_pairs,\n        Cooling         cool,\n        DisplacementMap displacement,\n        const bgl_named_params<Param, Tag, Rest>&)\n    {\n      fruchterman_reingold_force_directed_layout\n        (g, position, origin, extent, attractive_force, repulsive_force,\n         force_pairs, cool, displacement);\n    }\n  };\n\n  template<>\n  struct fr_force_directed_layout<error_property_not_found>\n  {\n    template<typename Graph, typename PositionMap, \n             typename AttractiveForce, typename RepulsiveForce,\n             typename ForcePairs, typename Cooling,\n             typename Param, typename Tag, typename Rest>\n    static void\n    run(const Graph&    g,\n        PositionMap     position,\n        typename property_traits<PositionMap>::value_type const& origin,\n        typename property_traits<PositionMap>::value_type const& extent,\n        AttractiveForce attractive_force,\n        RepulsiveForce  repulsive_force,\n        ForcePairs      force_pairs,\n        Cooling         cool,\n        error_property_not_found,\n        const bgl_named_params<Param, Tag, Rest>& params)\n    {\n      typedef typename property_traits<PositionMap>::value_type Point;\n      std::vector<Point> displacements(num_vertices(g));\n      fruchterman_reingold_force_directed_layout\n        (g, position, origin, extent, attractive_force, repulsive_force,\n         force_pairs, cool,\n         make_iterator_property_map\n         (displacements.begin(),\n          choose_const_pmap(get_param(params, vertex_index), g,\n                            vertex_index),\n          Point()));\n    }\n  };\n\n} // end namespace detail\n\ntemplate<typename Graph, typename PositionMap, typename Param,\n         typename Tag, typename Rest>\nvoid\nfruchterman_reingold_force_directed_layout\n  (const Graph&    g,\n   PositionMap     position,\n   typename property_traits<PositionMap>::value_type const& origin,\n   typename property_traits<PositionMap>::value_type const& extent,\n   const bgl_named_params<Param, Tag, Rest>& params)\n{\n  typedef typename property_value<bgl_named_params<Param,Tag,Rest>,\n                                  vertex_displacement_t>::type D;\n\n  detail::fr_force_directed_layout<D>::run\n    (g, position, origin, extent,\n     choose_param(get_param(params, attractive_force_t()),\n                  square_distance_attractive_force()),\n     choose_param(get_param(params, repulsive_force_t()),\n                  square_distance_repulsive_force()),\n     choose_param(get_param(params, force_pairs_t()),\n                  make_grid_force_pairs(origin, extent, position, g)),\n     choose_param(get_param(params, cooling_t()),\n                  linear_cooling<double>(100)),\n     get_param(params, vertex_displacement_t()),\n     params);\n}\n\ntemplate<typename Graph, typename PositionMap>\nvoid\nfruchterman_reingold_force_directed_layout\n  (const Graph&    g,\n   PositionMap     position,\n   typename property_traits<PositionMap>::value_type const& origin,\n   typename property_traits<PositionMap>::value_type const& extent)\n{\n  fruchterman_reingold_force_directed_layout\n    (g, position, origin, extent,\n     attractive_force(square_distance_attractive_force()));\n}\n\n} // end namespace boost\n\n#ifdef BOOST_GRAPH_IS_PARALLEL\n#  include <boost/graph/distributed/fruchterman_reingold.hpp>\n#endif // BOOST_GRAPH_IS_PARALLEL\n\n#endif // BOOST_GRAPH_FRUCHTERMAN_REINGOLD_FORCE_DIRECTED_LAYOUT_HPP\n", "meta": {"hexsha": "77d4a7e8b4e7dd0649a35374e19fd848e24b42fa", "size": 17774, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/graph/fruchterman_reingold.hpp", "max_stars_repo_name": "erwinvaneijk/bgl-python", "max_stars_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-06-19T08:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T11:09:05.000Z", "max_issues_repo_path": "boost/graph/fruchterman_reingold.hpp", "max_issues_repo_name": "erwinvaneijk/bgl-python", "max_issues_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/graph/fruchterman_reingold.hpp", "max_forks_repo_name": "erwinvaneijk/bgl-python", "max_forks_repo_head_hexsha": "6731d1e0e9681e99f1ad0a876b2adb8139d93027", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-07-13T07:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-26T15:08:03.000Z", "avg_line_length": 32.9148148148, "max_line_length": 88, "alphanum_fraction": 0.6402610555, "num_tokens": 4260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.4182952127466499}}
{"text": "#include <unsupported/Eigen/MatrixFunctions>\n#include <Eigen/Eigenvalues>\n#include \"BlockMatrix.h\"\n\nBlockMatrix::BlockMatrix(int L) {\n\tinit(L);\n}\n\nBlockMatrix::BlockMatrix(const BlockMatrix& bm) {\n\tinit(bm._L);\n\tfor (int i = 0; i < bm.size(); i++) {\n\t\tfor (int j = 0; j < bm.size(); j++) {\n\t\t\t_mats[i][j] = bm._mats[i][j];\n\t\t}\n\t}\n}\n\nBlockMatrix::BlockMatrix(int L, const Array& diag) {\n\tinit(L);\n\tstd::vector<int> index = buildIndex(_L);\n\tfor (int i = 0; i < size(); i++) {\n\t\t_mats[i][i] = diag.block(index[i], 0, StateCollection::Inst()->StateNumber(_L, i), 1).matrix().asDiagonal();\n\t}\n}\n\nBlockMatrix::~BlockMatrix() {\n/*\tfor (size_t i = 0; i < _mats.size(); i++) {\n\t\tfor (size_t j = 0; j < _mats.size(); j++) {\n\t\t\tif (_mats[i][j] != NULL) {\n\t\t\t\tdelete _mats[i][j];\n\t\t\t}\n\t\t}\n\t}*/\n}\n\nvoid BlockMatrix::init(int L) {\n\tthis->_L = L;\n\t_mats.resize((size_t)L + 1, std::vector<Matrix>(L + 1));\n}\n\nstd::vector<int> BlockMatrix::buildIndex(int L) {\n\tStateCollection* inst = StateCollection::Inst();\n\tstd::vector<int> index(L + 1);\n\tindex[0] = 0;\n\tfor (int i = 1; i <= L; i++) {\n\t\tindex[i] = inst->StateNumber(L, i - 1) + index[i - 1];\n\t}\n\n\treturn index;\n}\n\nbool BlockMatrix::isLadder(int* ladderSize) const {\n\tint diff = 0;\n\tbool first = true;\n\tfor (int i = 0; i < size(); i++) {\n\t\tfor (int j = 0; j < size(); j++) {\n\t\t\tif (empty(i, j)) continue;\n\t\t\tif (first) {\n\t\t\t\tdiff = i - j;\n\t\t\t\tfirst = false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (i - j != diff) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t*ladderSize = diff;\n\treturn true;\n}\n\nvoid BlockMatrix::fromMixing(const Array& left, const BlockMatrix& center, const Array& right) {\n\tinit(center._L);\n\n\tstd::vector<int> index = buildIndex(_L);\n\tfor (int i = 0; i < center.size(); i++) {\n\t\tfor (int j = 0; j < center.size(); j++) {\n\t\t\tif (center.empty(i, j)) continue;\n\t\t\t_mats[i][j].resize(center._mats[i][j].rows(), center._mats[i][j].cols());\n\t\t\t_mats[i][j].fill(0.0);\n\n\t\t\tfor (int x = 0; x < _mats[i][j].rows(); x++) {\n\t\t\t\tfor (int y = 0; y < _mats[i][j].cols(); y++) {\n\t\t\t\t\t_mats[i][j](x, y) = left(x + index[i]) * center._mats[i][j](x, y) * right(y + index[j]);\n\t\t\t\t}\n//\t\t\t\t_mats[i][j].row(x) = center._mats[i][j].row(x) * left(x + index[i]);\n\t\t\t}\n//\t\t\tfor (int y = 0; y < _mats[i][j].cols(); y++) {\n//\t\t\t\t_mats[i][j].col(y) *= right(y + index[j]);\n//\t\t\t}\n\t\t}\n\t}\n}\n\nvoid BlockMatrix::mixWith(const Array& left, const Array& right) {\n\tstd::vector<int> index = buildIndex(_L);\n\tfor (int i = 0; i < this->size(); i++) {\n\t\tfor (int j = 0; j < this->size(); j++) {\n\t\t\tif (empty(i, j)) continue;\n\n\t\t\tfor (int x = 0; x < _mats[i][j].rows(); x++) {\n\t\t\t\t_mats[i][j].row(x) *= left(x + index[i]);\n\t\t\t}\n\t\t\tfor (int y = 0; y < _mats[i][j].cols(); y++) {\n\t\t\t\t_mats[i][j].col(y) *= right(y + index[j]);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid BlockMatrix::mixWith(const BlockMatrix& left, const BlockMatrix& right) {\n\tfor (int i = 0; i < this->size(); i++) {\n\t\tfor (int j = 0; j < this->size(); j++) {\n\t\t\tif (empty(i, j)) continue;\n\t\t\t_mats[i][j] = left._mats[i][i] * _mats[i][j] * right._mats[j][j];\n\t\t}\n\t}\n}\n\nvoid BlockMatrix::fromMixing(const BlockMatrix& left, const Array& diag, const BlockMatrix& right) {\n\tif (left._L != right._L) {\n\t\tthrow OtocException(\"Dimension of left and right matrices are different.\");\n\t}\n\n\tinit(left._L);\n\tstd::vector<int> index = buildIndex(_L);\n\tfor (int i = 0; i < left.size(); i++) {\n\t\tfor (int k = 0; k < left.size(); k++) {\n\t\t\tif (left.empty(i, k)) continue;\n\t\t\tMatrix tmp = Matrix::Zero(left._mats[i][k].rows(), left._mats[i][k].cols());\n\t\t\tfor (int h = 0; h < tmp.cols(); h++) {\n\t\t\t\ttmp.col(h) = left._mats[i][k].col(h) * diag(h + index[k]);\n\t\t\t}\n\n\t\t\tfor (int j = 0; j < right.size(); j++) {\n\t\t\t\tif (right.empty(k, j)) continue;\n\t\t\t\tif (this->empty(i, j)) {\n\t\t\t\t\tthis->fill(i, j);\n\t\t\t\t}\n\t\t\t\tthis->_mats[i][j].noalias() += tmp * right._mats[k][j];\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid BlockMatrix::setZeroAt(const std::vector<int>& zeroPos) {\n\tstd::vector<int> index = buildIndex(_L);\n\tStateCollection* inst = StateCollection::Inst();\n\tint x = 0;\n\tfor (int i = 0; i < zeroPos.size(); i++) {\n\t\tif (zeroPos[i] >= index[x] + inst->StateNumber(_L, x)) x++;\n//\t\tstd::cout << \"i=\" << i << \", x=\" << x << \", state#=\" << inst->StateNumber(_L, x) << \", index[x]=\" << index[x] << std::endl;\n\t\tint y = 0;\n\t\tfor (int j = 0; j < zeroPos.size(); j++) {\n\t\t\tif (zeroPos[j] >= index[y] + inst->StateNumber(_L, y)) y++;\n//\t\t\tstd::cout << \"j=\" << j << \", y=\" << y << \", state#=\" << inst->StateNumber(_L, y) << \", index[y]=\" << index[y] << std::endl;\n\t\t\tif (empty(x, y)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t_mats[x][y](zeroPos[i] - index[x], zeroPos[j] - index[y]) = 0;\n\t\t}\n\t}\n}\n\nvoid BlockMatrix::diagonalize(Array& eigenValues, BlockMatrix& eigenVectors, BlockMatrix& eigenVectorsInv) const {\n\teigenValues.resize(StateCollection::Inst()->StateNumber(_L));\n\teigenVectors.init(_L);\n\teigenVectorsInv.init(_L);\n\n\tstd::vector<int> index = buildIndex(_L);\n\tEigen::ComplexEigenSolver<Matrix> solver;\n\tfor (int i = 0; i < size(); i++) {\n\t\tint n = _mats[i][i].rows();\n\t\tsolver.compute(_mats[i][i], true);\n\t\teigenValues.block(index[i], 0, n, 1) = solver.eigenvalues();\n\t\teigenVectors._mats[i][i] = solver.eigenvectors();\n\t\teigenVectorsInv._mats[i][i] = eigenVectors._mats[i][i].inverse();\n\t}\n}\n\nMatrix BlockMatrix::matrix() const {\n\tstd::vector<int> index = buildIndex(_L);\n\tint size = StateCollection::Inst()->StateNumber(_L);\n\tMatrix ret = Matrix::Zero(size, size);\n\tfor (int i = 0; i < this->size(); i++) {\n\t\tfor (int j = 0; j < this->size(); j++) {\n\t\t\tif (this->empty(i, j)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tret.block(index[i], index[j], this->_mats[i][j].rows(), this->_mats[i][j].cols()) = this->_mats[i][j];\n\t\t}\n\t}\n\n\treturn ret;\n}\n\nvoid BlockMatrix::fill(int i, int j) {\n\tStateCollection* inst = StateCollection::Inst();\n\t_mats[i][j] = Matrix::Zero(inst->StateNumber(_L, i), inst->StateNumber(_L, j));\n//\t_mats[i][j]->fill(0.0);\n}\n\nMatrix& BlockMatrix::block(int i, int j) {\n\treturn _mats[i][j];\n}\n\nBlockMatrix& BlockMatrix::operator += (const BlockMatrix& other) {\n\tif (this->_L != other._L) {\n\t\tthrow OtocException(\"Matrix with different dimensions cannot add.\");\n\t}\n\n\tfor (int i = 0; i < size(); i++) {\n\t\tfor (int j = 0; j < size(); j++) {\n\t\t\tif (other.empty(i, j)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (this->empty(i, j)) {\n\t\t\t\t_mats[i][j] = other._mats[i][j];\n\t\t\t}\n\t\t\telse {\n\t\t\t\t_mats[i][j] += other._mats[i][j];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn *this;\n}\n\nBlockMatrix& BlockMatrix::operator -= (const BlockMatrix& other) {\n\tif (this->_L != other._L) {\n\t\tthrow OtocException(\"Matrix with different dimensions cannot add.\");\n\t}\n\n\tfor (int i = 0; i < size(); i++) {\n\t\tfor (int j = 0; j < size(); j++) {\n\t\t\tif (other.empty(i, j)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (this->empty(i, j)) {\n\t\t\t\t_mats[i][j] = -other._mats[i][j];\n\t\t\t}\n\t\t\telse {\n\t\t\t\t_mats[i][j] -= other._mats[i][j];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn *this;\n}\n\nBlockMatrix BlockMatrix::operator - (const BlockMatrix& other) const {\n\tif (this->_L != other._L) {\n\t\tthrow OtocException(\"Matrix with different dimensions cannot multiply.\");\n\t}\n\n\tBlockMatrix res(this->size() - 1);\n\n\tfor (int i = 0; i < size(); i++) {\n\t\tfor (int j = 0; j < size(); j++) {\n\t\t\tif (this->empty(i, j) && other.empty(i, j)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (other.empty(i, j)) {\n\t\t\t\tres._mats[i][j] = this->_mats[i][j];\n\t\t\t}\n\t\t\telse if (this->empty(i, j)) {\n\t\t\t\tres._mats[i][j] = other._mats[i][j];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tres._mats[i][j] = this->_mats[i][j] - other._mats[i][j];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res;\n}\n\nBlockMatrix BlockMatrix::operator * (const BlockMatrix& other) const {\n\tif (this->_L != other._L) {\n\t\tthrow OtocException(\"Matrix with different dimensions cannot multiply.\");\n\t}\n\n\tBlockMatrix res(this->_L);\n\n\tfor (int i = 0; i < size(); i++) {\n\t\tfor (int j = 0; j < size(); j++) {\n\t\t\tfor (int k = 0; k < size(); k++) {\n\t\t\t\tif (this->empty(i, k) || other.empty(k, j)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (res.empty(i, j)) {\n\t\t\t\t\tres.fill(i, j);\n\t\t\t\t}\n\n\t\t\t\tres._mats[i][j].noalias() += this->_mats[i][k] * other._mats[k][j];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res;\n}\n\nvoid BlockMatrix::multiplyByLadder(const BlockMatrix& ladder, int ladderSize) {\n\tfor (int i = 0; i < size(); i++) {\n\t\tif (ladderSize >= 0) {\n\t\t\tfor (int j = 0; j < size(); j++) {\n\t\t\t\tint k = j + ladderSize;\n\t\t\t\tif (k >= size()) {\n\t\t\t\t\t_mats[i][j] = Matrix();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t_mats[i][j] = _mats[i][k] * ladder._mats[k][j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (int j = size() - 1; j >= 0; j--) {\n\t\t\t\tint k = j + ladderSize;\n\t\t\t\tif (k < 0) {\n\t\t\t\t\t_mats[i][j] = Matrix();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t_mats[i][j] = _mats[i][k] * ladder._mats[k][j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nBlockMatrix BlockMatrix::operator * (const var_t& val) const {\n\tBlockMatrix res(this->size() - 1);\n\n\tfor (int i = 0; i < size(); i++) {\n\t\tfor (int j = 0; j < size(); j++) {\n\t\t\tif (this->empty(i, j)) continue;\n\t\t\tres._mats[i][j] = _mats[i][j] * val;\n\t\t}\n\t}\n\n\treturn res;\n}\n\nBlockMatrix& BlockMatrix::operator *= (const var_t& val) {\n\tfor (int i = 0; i < size(); i++) {\n\t\tfor (int j = 0; j < size(); j++) {\n\t\t\tif (this->empty(i, j)) continue;\n\t\t\t_mats[i][j] *= val;\n\t\t}\n\t}\n\n\treturn *this;\n}\n\nBlockMatrix& BlockMatrix::operator *= (const Array& diag) {\n\tstd::vector<int> index = buildIndex(_L);\n\tfor (int i = 0; i < size(); i++) {\n\t\tfor (int j = 0; j < size(); j++) {\n\t\t\tif (empty(i, j)) continue;\n\t\t\tfor (int x = 0; x < _mats[i][j].cols(); x++) {\n\t\t\t\t_mats[i][j].col(x) *= diag(index[j] + x);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn *this;\n}\n\nBlockMatrix BlockMatrix::operator * (const Array& diag) {\n\tBlockMatrix ret(_L);\n\tstd::vector<int> index = buildIndex(_L);\n\tfor (int i = 0; i < size(); i++) {\n\t\tfor (int j = 0; j < size(); j++) {\n\t\t\tif (empty(i, j)) continue;\n\t\t\tret.fill(i, j);\n\t\t\tfor (int x = 0; x < _mats[i][j].cols(); x++) {\n\t\t\t\tret._mats[i][j].col(x) = _mats[i][j].col(x) * diag(index[j] + x);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn ret;\n}\n\nvar_t BlockMatrix::trace() const {\n\tvar_t ret(0.0);\n\tfor (int i = 0; i < size(); i++) {\n\t\tif (!empty(i, i)) {\n\t\t\tret += _mats[i][i].trace();\n\t\t}\n\t}\n\n\treturn ret;\n}\n\nBlockMatrix BlockMatrix::exp() const {\n\tint ladderSize;\n\tif (!isLadder(&ladderSize)) {\n\t\tthrow OtocException(\"Only ladder-like matrix can be exponentiated.\");\n\t}\n\n\tBlockMatrix res(this->size() - 1);\n\tStateCollection* inst = StateCollection::Inst();\n\tif (ladderSize == 0) {\n\t\tfor (int i = 0; i < res.size(); i++) {\n\t\t\tif (this->empty(i, i)) {\n\t\t\t\tres._mats[i][i] = Matrix::Identity(inst->StateNumber(this->_L, i), inst->StateNumber(this->_L, i));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tres._mats[i][i] = _mats[i][i].exp();\n\t\t\t}\n\t\t}\n\t}\n\telse {                                \n\t\tArray id = Array::Constant(inst->StateNumber(_L), 1);\n\t\tBlockMatrix mat(_L, id);\n\t\tres += mat;\n\t\tfor (int i = 1; i * std::abs(ladderSize) <= _L; i++) {\n\t\t\tmat.multiplyByLadder(*this, ladderSize);\n\t\t\tmat *= 1 / (f_type)i;\n\t\t\tres += mat;\n\t\t}\n\t}\n\n\treturn res;\n}\n\nBlockMatrix BlockMatrix::conjugate() const {\n\tBlockMatrix res(this->size() - 1);\n\tfor (int i = 0; i < res.size(); i++) {\n\t\tfor (int j = 0; j < res.size(); j++) {\n\t\t\tif (this->empty(i, j)) continue;\n\t\t\tres._mats[i][j] = _mats[i][j].conjugate();\n\t\t}\n\t}\n\n\treturn res;\n}\n\nBlockMatrix BlockMatrix::adjoint() const {\n\tBlockMatrix res(this->size() - 1);\n\tfor (int i = 0; i < res.size(); i++) {\n\t\tfor (int j = 0; j < res.size(); j++) {\n\t\t\tif (this->empty(i, j)) continue;\n\t\t\tres._mats[j][i] = _mats[i][j].adjoint();\n\t\t}\n\t}\n\n\treturn res;\n}\n\nBlockMatrix& BlockMatrix::adjointInPlace() {\n\tfor (int i = 0; i < size(); i++) {\n\t\tfor (int j = i; j < size(); j++) {\n\t\t\tif (this->empty(i, j) && this->empty(j, i)) continue;\n\t\t\tif (i == j) {\n\t\t\t\t_mats[i][j].adjointInPlace();\n\t\t\t} else if (this->empty(i, j)) {\n\t\t\t\t_mats[i][j] = _mats[j][i].adjoint();\n\t\t\t\t_mats[j][i] = Matrix();\n\t\t\t}\n\t\t\telse if (this->empty(j, i)){\n\t\t\t\t_mats[j][i] = _mats[i][j].adjoint();\n\t\t\t\t_mats[i][j] = Matrix();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tMatrix tmp = _mats[i][j];\n\t\t\t\t_mats[i][j] = _mats[j][i].adjoint();\n\t\t\t\t_mats[j][i] = tmp.adjoint();\n/*\t\t\t\tfor (int x = 0; x < _mats[i][j].rows(); x++) {\n\t\t\t\t\tfor (int y = 0; y < _mats[i][j].cols(); y++) {\n\t\t\t\t\t\tvar_t tmp = _mats[i][j](x, y);\n\t\t\t\t\t\t_mats[i][j](x, y) = std::conj(_mats[j][i](y, x));\n\t\t\t\t\t\t_mats[j][i](y, x) = std::conj(tmp);\n\t\t\t\t\t}\n\t\t\t\t}*/\n\t\t\t}\n\t\t}\n\t}\n\n\treturn *this;\n}\n\nBlockMatrix BlockMatrix::inverse() const {\n\tBlockMatrix res(this->size() - 1);\n\tfor (int i = 0; i < res.size(); i++) {\n\t\tres._mats[i][i] = _mats[i][i].inverse();\n\t}\n\n\treturn res;\n}\n\nBlockMatrix& BlockMatrix::inverseInPlace() {\n\tfor (int i = 0; i < size(); i++) {\n\t\t_mats[i][i] = _mats[i][i].inverse();\n\t}\n\n\treturn *this;\n}\n\nArray BlockMatrix::diagonal() const {\n\tstd::vector<int> index = buildIndex(_L);\n\tStateCollection* inst = StateCollection::Inst();\n\tArray ret = Array::Zero(inst->StateNumber(this->_L));\n\tfor (int m = 0; m <= this->_L; m++) {\n\t\tif (empty(m, m)) continue;\n\t\tret.block(index[m], 0, _mats[m][m].rows(), 1) = _mats[m][m].diagonal().array();\n\t}\n\n\treturn ret;\n}\n\nostream& operator << (ostream& os, const BlockMatrix& bm) {\n\tfor (int i = 0; i < bm.size(); i++) {\n\t\tfor (int j = 0; j < bm.size(); j++) {\n\t\t\tif (bm.empty(i, j)) continue;\n\t\t\tos << \"block(\" << i << \", \" << j << \")=\" << std::endl;\n\t\t\tos << bm._mats[i][j] << std::endl;\n\t\t}\n\t}\n\n\treturn os;\n}", "meta": {"hexsha": "dc25df2afa326870ba55615f35ff7054dec219b1", "size": 13013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BlockMatrix.cpp", "max_stars_repo_name": "gaolichen/otoc4n4sym", "max_stars_repo_head_hexsha": "b504f9eb6efdf52567b3655a2caff6238559ba64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BlockMatrix.cpp", "max_issues_repo_name": "gaolichen/otoc4n4sym", "max_issues_repo_head_hexsha": "b504f9eb6efdf52567b3655a2caff6238559ba64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BlockMatrix.cpp", "max_forks_repo_name": "gaolichen/otoc4n4sym", "max_forks_repo_head_hexsha": "b504f9eb6efdf52567b3655a2caff6238559ba64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7866666667, "max_line_length": 128, "alphanum_fraction": 0.5476062399, "num_tokens": 4625, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.41823561219340794}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_InterpolationPolicy_def.hpp\n//! \\author Alex Robinson\n//! \\brief  Intrepolation policy struct definitions\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_INTERPOLATION_POLICY_DEF_HPP\n#define UTILITY_INTERPOLATION_POLICY_DEF_HPP\n\n// Std Lib Includes\n#include <cmath>\n\n// Boost Includes\n#include <boost/mpl/or.hpp>\n\n// Trilinos Includes\n#include <Teuchos_ScalarTraits.hpp>\n\n// FRENSIE Includes\n#include \"Utility_ContractException.hpp\"\n\nnamespace Utility{\n\n// Interpolate between two points\ntemplate<typename IndepType, typename DepType>\ninline DepType LogLog::interpolate( const IndepType indep_var_0,\n\t\t\t\t    const IndepType indep_var_1,\n\t\t\t\t    const IndepType indep_var,\n\t\t\t\t    const DepType dep_var_0,\n\t\t\t\t    const DepType dep_var_1 )\n{\n  // The IndepType must be a floating point type\n  testStaticPrecondition( (QuantityTraits<IndepType>::is_floating_point::value) );\n  testStaticPrecondition( (QuantityTraits<DepType>::is_floating_point::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_0 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_1 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var_0 ) );\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var_1 ) );\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var_0 < indep_var_1 );\n  testPrecondition( indep_var >= indep_var_0 );\n  testPrecondition( indep_var <= indep_var_1 );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LogLog::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LogLog::isDepVarInValidRange( dep_var_1 ) );\n\n  return dep_var_0*\n    pow((dep_var_1/dep_var_0),\n\tlog(indep_var/indep_var_0)/log(indep_var_1/indep_var_0));\n}\n\n// Interpolate between two processed point\ntemplate<typename T>\ninline T LogLog::interpolate( const T processed_indep_var_0,\n\t\t\t      const T processed_indep_var,\n\t\t\t      const T processed_dep_var_0,\n\t\t\t      const T processed_slope )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (boost::is_floating_point<T>::value) );\n  // Make sure the processed independent variables are valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t     processed_indep_var_0 ) );\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t       processed_indep_var ) );\n  testPrecondition( processed_indep_var_0 <= processed_indep_var );\n  // Make sure the processed dependent variable is valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t       processed_dep_var_0 ) );\n  // Make sure that the slope is valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( processed_slope ) );\n  \n  return exp( processed_dep_var_0 + \n\t      processed_slope*(processed_indep_var - processed_indep_var_0) );\n}\n\n// Interpolate between two points and return the processed value\ntemplate<typename IndepType, typename DepType>\ninline typename QuantityTraits<DepType>::RawType \nLogLog::interpolateAndProcess( const IndepType indep_var_0,\n\t\t\t       const IndepType indep_var_1,\n\t\t\t       const IndepType indep_var,\n\t\t\t       const DepType dep_var_0,\n\t\t\t       const DepType dep_var_1 )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (QuantityTraits<IndepType>::is_floating_point::value) );\n  testStaticPrecondition( (QuantityTraits<DepType>::is_floating_point::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_0 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_1 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var_0 ) );\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var_1 ) );\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var_0 < indep_var_1 );\n  testPrecondition( indep_var >= indep_var_0 );\n  testPrecondition( indep_var <= indep_var_1 );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LogLog::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LogLog::isDepVarInValidRange( dep_var_1 ) );\n  \n  return log( getRawQuantity(dep_var_0) ) + log ( dep_var_1/dep_var_0 )*\n    log( indep_var/indep_var_0 )/log( indep_var_1/indep_var_0 );\n}\n\n// Interpolate between two processed points and return the processed value\ntemplate<typename T>\ninline T LogLog::interpolateAndProcess( const T processed_indep_var_0,\n\t\t\t\t\tconst T processed_indep_var,\n\t\t\t\t\tconst T processed_dep_var_0,\n\t\t\t\t\tconst T processed_slope )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (boost::is_floating_point<T>::value) );\n  // Make sure the processed independent variables are valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t     processed_indep_var_0 ) );\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t       processed_indep_var ) );\n  testPrecondition( processed_indep_var_0 <= processed_indep_var );\n  // Make sure the processed dependent variable is valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t       processed_dep_var_0 ) );\n  // Make sure that the slope is valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( processed_slope ) );\n  \n  return processed_dep_var_0 + \n    processed_slope*(processed_indep_var - processed_indep_var_0);\n}\n\n// Process the independent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType\nLogLog::processIndepVar( const T indep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var ) );\n  \n  return log( getRawQuantity(indep_var) );\n}\n\n// Process the dependent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType \nLogLog::processDepVar( const T dep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LogLog::isIndepVarInValidRange( dep_var ) );\n\n  return log( getRawQuantity(dep_var) );\n}\n\n// Recover the processed independent value\ntemplate<typename T>\ninline T LogLog::recoverProcessedIndepVar( const T processed_indep_var )\n{\n  return exp( processed_indep_var );\n}\n  \n// Recover the processed dependent value\ntemplate<typename T>\ninline T LogLog::recoverProcessedDepVar( const T processed_dep_var )\n{\n  return exp( processed_dep_var );\n}\n\n// Test if the independent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LogLog::isIndepVarInValidRange( const T indep_var )\n{\n  // Make sure the indep var is not inf or nan\n  testPrecondition( !QuantityTraits<T>::isnaninf( indep_var ) );\n    \n  return indep_var > QuantityTraits<T>::zero();\n}\n\n// Test if the dependent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LogLog::isDepVarInValidRange( const T dep_var )\n{\n  // Make sure the indep var is not inf or nan\n  testPrecondition( !QuantityTraits<T>::isnaninf( dep_var ) );\n    \n  return dep_var > QuantityTraits<T>::zero();\n}\n\n// The name of the policy\ninline const std::string LogLog::name()\n{\n  return \"LogLog\";\n}\n\n// Interpolate between two points\ntemplate<typename IndepType, typename DepType>\ninline DepType LogLin::interpolate( const IndepType indep_var_0,\n\t\t\t\t    const IndepType indep_var_1,\n\t\t\t\t    const IndepType indep_var,\n\t\t\t\t    const DepType dep_var_0,\n\t\t\t\t    const DepType dep_var_1 )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (QuantityTraits<IndepType>::is_floating_point::value) );\n  testStaticPrecondition( (QuantityTraits<DepType>::is_floating_point::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_0 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_1 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var_0 ) );\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var_1 ) );\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var_0 < indep_var_1 );\n  testPrecondition( indep_var >= indep_var_0 );\n  testPrecondition( indep_var <= indep_var_1 );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LogLin::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LogLin::isDepVarInValidRange( dep_var_1 ) );\n\n  return dep_var_0*pow((dep_var_1/dep_var_0), (indep_var-indep_var_0)/(indep_var_1-indep_var_0));\n}\n\n// Interpolate between two processed points\ntemplate<typename T>\ninline T LogLin::interpolate( const T processed_indep_var_0,\n\t\t\t      const T processed_indep_var,\n\t\t\t      const T processed_dep_var_0,\n\t\t\t      const T processed_slope )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (boost::is_floating_point<T>::value) );\n  // Make sure the processed independent variables are valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t     processed_indep_var_0 ) );\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t       processed_indep_var ) );\n  testPrecondition( processed_indep_var_0 <= processed_indep_var );\n  // Make sure the processed dependent variable is valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t       processed_dep_var_0 ) );\n  // Make sure that the slope is valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( processed_slope ) );\n  \n  return exp( processed_dep_var_0 + \n\t      processed_slope*(processed_indep_var - processed_indep_var_0) );\n}\n\n// Interpolate between two points and return the processed value\ntemplate<typename IndepType, typename DepType>\ninline typename QuantityTraits<DepType>::RawType \nLogLin::interpolateAndProcess( const IndepType indep_var_0,\n\t\t\t       const IndepType indep_var_1,\n\t\t\t       const IndepType indep_var,\n\t\t\t       const DepType dep_var_0,\n\t\t\t       const DepType dep_var_1 )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (QuantityTraits<IndepType>::is_floating_point::value) );\n  testStaticPrecondition( (QuantityTraits<DepType>::is_floating_point::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_0 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_1 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var_0 ) );\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var_1 ) );\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var_0 < indep_var_1 );\n  testPrecondition( indep_var >= indep_var_0 );\n  testPrecondition( indep_var <= indep_var_1 );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LogLin::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LogLin::isDepVarInValidRange( dep_var_1 ) );\n\n  return log( getRawQuantity(dep_var_0) ) + log( dep_var_1/dep_var_0 )*\n    (indep_var-indep_var_0)/(indep_var_1-indep_var_0);\n}\n\n// Interpolate between two processed points and return the processed value\ntemplate<typename T>\ninline T LogLin::interpolateAndProcess( const T processed_indep_var_0,\n\t\t\t\t\tconst T processed_indep_var,\n\t\t\t\t\tconst T processed_dep_var_0,\n\t\t\t\t\tconst T processed_slope )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (boost::is_floating_point<T>::value) );\n  // Make sure the processed independent variables are valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t     processed_indep_var_0 ) );\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t       processed_indep_var ) );\n  testPrecondition( processed_indep_var_0 <= processed_indep_var );\n  // Make sure the processed dependent variable is valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t       processed_dep_var_0 ) );\n  // Make sure that the slope is valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( processed_slope ) );\n  \n  return processed_dep_var_0 + \n    processed_slope*(processed_indep_var - processed_indep_var_0);\n}\n\n// Process the independent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType \nLogLin::processIndepVar( const T indep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var ) );\n  \n  return getRawQuantity(indep_var);\n}\n\n// Process the dependent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType \nLogLin::processDepVar( const T dep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LogLin::isDepVarInValidRange( dep_var ) );\n\n  return log( getRawQuantity(dep_var) );\n}\n\n// Recover the processed independent value\ntemplate<typename T>\ninline T LogLin::recoverProcessedIndepVar( const T processed_indep_var )\n{\n  return processed_indep_var;\n}\n  \n// Recover the processed dependent value\ntemplate<typename T>\ninline T LogLin::recoverProcessedDepVar( const T processed_dep_var )\n{\n  return exp( processed_dep_var );\n}\n\n// Test if the independent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LogLin::isIndepVarInValidRange( const T indep_var )\n{\n  // Make sure the indep var is not inf or nan\n  testPrecondition( !QuantityTraits<T>::isnaninf( indep_var ) );\n    \n  return true;\n}\n\n// Test if the dependent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LogLin::isDepVarInValidRange( const T dep_var )\n{\n  // Make sure the indep var is not inf or nan\n  testPrecondition( !QuantityTraits<T>::isnaninf( dep_var ) );\n    \n  return dep_var > QuantityTraits<T>::zero();\n}\n\n// The name of the policy\ninline const std::string LogLin::name()\n{\n  return \"LogLin\";\n}\n\n// Interpolate between two points\ntemplate<typename IndepType, typename DepType>\ninline DepType LinLog::interpolate( const IndepType indep_var_0,\n\t\t\t\t    const IndepType indep_var_1,\n\t\t\t\t    const IndepType indep_var,\n\t\t\t\t    const DepType dep_var_0,\n\t\t\t\t    const DepType dep_var_1 )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (QuantityTraits<IndepType>::is_floating_point::value) );\n  testStaticPrecondition( (QuantityTraits<DepType>::is_floating_point::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_0 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_1 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( LinLog::isIndepVarInValidRange( indep_var_0 ) );\n  testPrecondition( LinLog::isIndepVarInValidRange( indep_var_1 ) );\n  testPrecondition( LinLog::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var_0 < indep_var_1 );\n  testPrecondition( indep_var >= indep_var_0 );\n  testPrecondition( indep_var <= indep_var_1 );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LinLog::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LinLog::isDepVarInValidRange( dep_var_1 ) );\n\n  DepType term_2( (dep_var_1 - dep_var_0)*log(indep_var/indep_var_0)/\n\t\t  log(indep_var_1/indep_var_0) );\n\n  return dep_var_0 + term_2;\n}\n\n// Interpolate between two processed point\ntemplate<typename T>\ninline T LinLog::interpolate( const T processed_indep_var_0,\n\t\t\t      const T processed_indep_var,\n\t\t\t      const T processed_dep_var_0,\n\t\t\t      const T processed_slope )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (boost::is_floating_point<T>::value) );\n  // Make sure the processed independent variables are valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t     processed_indep_var_0 ) );\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t       processed_indep_var ) );\n  testPrecondition( processed_indep_var_0 <= processed_indep_var );\n  // Make sure the processed dependent variable is valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( \n\t\t\t\t\t\t       processed_dep_var_0 ) );\n  // Make sure that the slope is valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf( processed_slope ) );\n  \n  return processed_dep_var_0 + \n    processed_slope*(processed_indep_var - processed_indep_var_0 );\n}\n\n// Interpolate between two points and return the processed value\ntemplate<typename IndepType, typename DepType>\ninline typename QuantityTraits<DepType>::RawType \nLinLog::interpolateAndProcess( const IndepType indep_var_0,\n\t\t\t       const IndepType indep_var_1,\n\t\t\t       const IndepType indep_var,\n\t\t\t       const DepType dep_var_0,\n\t\t\t       const DepType dep_var_1 )\n{\n  return getRawQuantity( interpolate( indep_var_0, \n\t\t\t\t      indep_var_1, \n\t\t\t\t      indep_var, \n\t\t\t\t      dep_var_0, \n\t\t\t\t      dep_var_1 ) );\n}\n\n// Interpolate between two processed points and return the processed value\ntemplate<typename T>\ninline T LinLog::interpolateAndProcess( const T processed_indep_var_0,\n\t\t\t\t\tconst T processed_indep_var,\n\t\t\t\t\tconst T processed_dep_var_0,\n\t\t\t\t\tconst T processed_slope )\n{  \n  return interpolate( processed_indep_var_0,\n\t\t      processed_indep_var,\n\t\t      processed_dep_var_0,\n\t\t      processed_slope );\n}\n\n// Process the independent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType \nLinLog::processIndepVar( const T indep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LinLog::isIndepVarInValidRange( indep_var ) );\n  \n  return log( getRawQuantity(indep_var) );\n}\n\n// Process the dependent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType \nLinLog::processDepVar( const T dep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LinLog::isDepVarInValidRange( dep_var ) );\n\n  return getRawQuantity(dep_var);\n}\n\n// Recover the processed independent value\ntemplate<typename T>\ninline T LinLog::recoverProcessedIndepVar( const T processed_indep_var )\n{\n  return exp( processed_indep_var );\n}\n  \n// Recover the processed dependent value\ntemplate<typename T>\ninline T LinLog::recoverProcessedDepVar( const T processed_dep_var )\n{\n  return processed_dep_var;\n}\n\n// Test if the independent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LinLog::isIndepVarInValidRange( const T indep_var )\n{\n  // Make sure the indep var is not inf or nan\n  testPrecondition( !QuantityTraits<T>::isnaninf( indep_var ) );\n    \n  return indep_var > QuantityTraits<T>::zero();\n}\n\n// Test if the dependent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LinLog::isDepVarInValidRange( const T dep_var )\n{\n  // Make sure the indep var is not inf or nan\n  testPrecondition( !QuantityTraits<T>::isnaninf( dep_var ) );\n    \n  return true;\n}\n\n// The name of the policy\ninline const std::string LinLog::name()\n{\n  return \"LinLog\";\n}\n\n// Interpolate between two points\ntemplate<typename IndepType, typename DepType>\ninline DepType LinLin::interpolate( const IndepType indep_var_0,\n\t\t\t\t    const IndepType indep_var_1,\n\t\t\t\t    const IndepType indep_var,\n\t\t\t\t    const DepType dep_var_0,\n\t\t\t\t    const DepType dep_var_1 )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (QuantityTraits<IndepType>::is_floating_point::value) );\n  testStaticPrecondition( (QuantityTraits<DepType>::is_floating_point::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_0 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_1 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( LinLin::isIndepVarInValidRange( indep_var_0 ) );\n  testPrecondition( LinLin::isIndepVarInValidRange( indep_var_1 ) );\n  testPrecondition( LinLin::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var_0 < indep_var_1 );\n  testPrecondition( indep_var >= indep_var_0 );\n  testPrecondition( indep_var <= indep_var_1 );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LinLin::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LinLin::isDepVarInValidRange( dep_var_1 ) );\n\n  DepType term_2( (dep_var_1 - dep_var_0)/(indep_var_1 - indep_var_0)*\n\t\t  (indep_var - indep_var_0) );\n\n  return dep_var_0 + term_2;\n}\n\n// Interpolate between two processed point\ntemplate<typename T>\ninline T LinLin::interpolate( const T processed_indep_var_0,\n\t\t\t      const T processed_indep_var,\n\t\t\t      const T processed_dep_var_0,\n\t\t\t      const T processed_slope )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (boost::is_floating_point<T>::value) );\n  // Make sure the processed independent variables are valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf(\n\t\t\t\t\t\t     processed_indep_var_0 ) );\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf(\n\t\t\t\t\t\t       processed_indep_var ) );\n  testPrecondition( processed_indep_var_0 <= processed_indep_var );\n  // Make sure the processed dependent variable is valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf(\n\t\t\t\t\t\t       processed_dep_var_0 ) );\n  // Make sure the slope is valid\n  testPrecondition( !Teuchos::ScalarTraits<T>::isnaninf(processed_slope));\n  \n  return processed_dep_var_0 + \n    processed_slope*(processed_indep_var - processed_indep_var_0 );\n}\n\n// Interpolate between two points and return the processed value\ntemplate<typename IndepType, typename DepType>\ninline typename QuantityTraits<DepType>::RawType\nLinLin::interpolateAndProcess( const IndepType indep_var_0,\n\t\t\t       const IndepType indep_var_1,\n\t\t\t       const IndepType indep_var,\n\t\t\t       const DepType dep_var_0,\n\t\t\t       const DepType dep_var_1 )\n{\n  return getRawQuantity( interpolate( indep_var_0,\n\t\t\t\t      indep_var_1,\n\t\t\t\t      indep_var,\n\t\t\t\t      dep_var_0,\n\t\t\t\t      dep_var_1 ) );\n}\n\n// Interpolate between two processed points and return the processed value\ntemplate<typename T>\ninline T LinLin::interpolateAndProcess( const T processed_indep_var_0,\n\t\t\t\t\tconst T processed_indep_var,\n\t\t\t\t\tconst T processed_dep_var_0,\n\t\t\t\t\tconst T processed_slope )\n{\n  return interpolate( processed_indep_var_0,\n\t\t      processed_indep_var,\n\t\t      processed_dep_var_0,\n\t\t      processed_slope );\n}\n\n// Process the independent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType\nLinLin::processIndepVar( const T indep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LinLin::isIndepVarInValidRange( indep_var  ) );\n  \n  return getRawQuantity(indep_var);\n}\n\n// Process the dependent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType \nLinLin::processDepVar( const T dep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LinLin::isIndepVarInValidRange( dep_var ) );\n\n  return getRawQuantity(dep_var);\n}\n\n// Recover the processed independent value\ntemplate<typename T>\ninline T LinLin::recoverProcessedIndepVar( const T processed_indep_var )\n{\n  return processed_indep_var;\n}\n  \n// Recover the processed dependent value\ntemplate<typename T>\ninline T LinLin::recoverProcessedDepVar( const T processed_dep_var )\n{\n  return processed_dep_var;\n}\n\n// Test if the independent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LinLin::isIndepVarInValidRange( const T indep_var )\n{\n  // Make sure the indep var is not inf or nan\n  testPrecondition( !QuantityTraits<T>::isnaninf( indep_var ) );\n    \n  return true;\n}\n\n// Test if the dependent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LinLin::isDepVarInValidRange( const T dep_var )\n{\n  // Make sure the indep var is not inf or nan\n  testPrecondition( !QuantityTraits<T>::isnaninf( dep_var ) );\n    \n  return true;\n}\n\n// The name of the policy\ninline const std::string LinLin::name()\n{\n  return \"LinLin\";\n}\n\n} // end Utility namespace\n\n#endif // end UTILITY_INTERPOLATION_POLICY_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_InterpolationPolicy_def.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "4ebd67060de4dd91f5f14856bf6fb189a7f5b737", "size": 25159, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/core/src/Utility_InterpolationPolicy_def.hpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/utility/core/src/Utility_InterpolationPolicy_def.hpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/utility/core/src/Utility_InterpolationPolicy_def.hpp", "max_forks_repo_name": "lkersting/SCR-2123", "max_forks_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9441997063, "max_line_length": 97, "alphanum_fraction": 0.738662109, "num_tokens": 6619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.41823561219340794}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n// CorotatedLinearElasticity.hh\n////////////////////////////////////////////////////////////////////////////////\n/*! @file\n//  A general linear elastic material model with geometric nonlinearities for\n//  small strain, large deformation applications.\n//\n//  We use a (right) polar decomposition F = RS to remove the rigid rotation\n//  component R from the deformation gradient F. The resulting large deformation\n//  strain is S - I, also known as the Biot strain.\n*/\n//  Author:  Julian Panetta (jpanetta), julian.panetta@gmail.com\n//  Created:  05/19/2020 12:15:32\n////////////////////////////////////////////////////////////////////////////////\n#ifndef COROTATEDLINEARELASTICITY_HH\n#define COROTATEDLINEARELASTICITY_HH\n\n#include <Eigen/Dense>\n#include \"EnergyTraits.hh\"\n#include \"Tensor.hh\"\n\n// Dimension-specific calculations\ntemplate<typename _Real, size_t N>\nstruct CRQuantities;\n\ntemplate<typename _Real>\nstruct CRQuantities<_Real, 3> {\n    using GType    = Eigen::Matrix<_Real, 3, 3>;\n    using IRotType = Eigen::Matrix<_Real, 3, 1>; // infinitesimal rotation representation\n    using Mat      = Eigen::Matrix<_Real, 3, 3>;\n\n    template<typename Derived>\n    static GType getG(const Eigen::MatrixBase<Derived> &S) { return S.trace() * GType::Identity() - S; }\n\n    template<typename Derived>\n    static GType getGinv(const Eigen::MatrixBase<Derived> &G) { return G.inverse(); }\n\n    // Extract a vector representing the skew symmetric part 0.5 (A - A^T)\n    //     0 -c  b      [a]\n    //     c  0 -a  ==> [b]\n    //    -b  a  0      [c]\n    // (This is the vector `w` whose cross product `w x v` equals `0.5 (A - A^T) v`.)\n    template<typename Derived>\n    static IRotType sk_inv(const Eigen::MatrixBase<Derived> &A) {\n        return IRotType(0.5 * (A(2, 1) - A(1, 2)),\n                        0.5 * (A(0, 2) - A(2, 0)),\n                        0.5 * (A(1, 0) - A(0, 1)));\n    }\n\n    // B * sk(w)\n    template<typename Derived>\n    static Mat right_mul_sk(const Eigen::MatrixBase<Derived> &B, const IRotType &w) {\n        return B.rowwise().cross(w);\n    }\n};\n\ntemplate<typename _Real>\nstruct CRQuantities<_Real, 2> {\n    using GType    = _Real;\n    using IRotType = _Real;\n    using Mat      = Eigen::Matrix<_Real, 2, 2>;\n\n    template<typename Derived>\n    static GType getG(const Eigen::MatrixBase<Derived> &S) { return S.trace(); }\n\n    static GType getGinv(_Real G) { return 1.0 / G; }\n\n    // Extract a scalar representing the skew symmetric part 0.5 (A - A^T)\n    //   0 -a\n    //   a  0\n    // (This scalar represents the counterclockwise infinitesimal rotation\n    //  applied by `0.5 (A - A^T)`\n    template<typename Derived>\n    static IRotType sk_inv(const Eigen::MatrixBase<Derived> &A) {\n        return 0.5 * (A(1, 0) - A(0, 1));\n    }\n\n    // B * sk(w)\n    template<typename Derived>\n    static Mat right_mul_sk(const Eigen::MatrixBase<Derived> &B, const IRotType &w) {\n        Mat result;\n        result << w * B.col(1),\n                 -w * B.col(0);\n        return result;\n    }\n};\n\ntemplate <typename _Real, size_t _Dimension>\nstruct CorotatedLinearElasticity : public Concepts::CRLinearElaticEnergy {\n    using SMatrix = SymmetricMatrixValue<_Real, _Dimension>;\n    static constexpr EDensityType EDType = EDensityType::FBased;\n\n    static constexpr size_t Dimension = _Dimension;\n    static constexpr size_t N         = Dimension;\n    using Real = _Real;\n    using Matrix  = Eigen::Matrix<_Real, _Dimension, _Dimension>;\n    using ETensor = ElasticityTensor<_Real, _Dimension>;\n    using CRQ     = CRQuantities<_Real, _Dimension>;\n\n    // We can use simplified formulas if we know `elasticity_tensor` is isotropic. This is\n    // specified with the `isotropic` argument.\n    CorotatedLinearElasticity(const ETensor& elasticity_tensor, bool isotropic = false) :\n        m_elasticity_tensor(elasticity_tensor), m_isotropic(isotropic) {\n        setDeformationGradient(Matrix::Identity());\n    }\n\n    // Constructor copying material properties only, not the current deformation\n    CorotatedLinearElasticity(const CorotatedLinearElasticity &other, UninitializedDeformationTag &&)\n        : m_elasticity_tensor(other.m_elasticity_tensor), m_isotropic(other.m_isotropic) { }\n\n    void setDeformationGradient(const Matrix &F, const EvalLevel elevel = EvalLevel::Full) {\n        m_F = F;\n        Eigen::JacobiSVD<Matrix> svd;\n        svd.compute(F, Eigen::ComputeFullU | Eigen::ComputeFullV );\n        m_R = svd.matrixU() * svd.matrixV().transpose();\n        if (m_R.determinant() < 0) {\n            Matrix W = svd.matrixV();\n            W.col(svd.matrixV().cols() - 1) *= -1;\n            m_R = svd.matrixU() * W.transpose();\n        }\n        m_S = m_R.transpose() * F;\n\n        // Analog to infinitesimal strain for linear elasticity.\n        m_biotStrain = m_S - Matrix::Identity();\n\n        // Analog to Cauchy stress for linear elasticity.\n        m_biotStress = m_elasticity_tensor.doubleContract(SMatrix(m_biotStrain)).toMatrix();\n\n        if (elevel == EvalLevel::EnergyOnly) return;\n\n        m_G    = CRQ::getG(m_S);\n        m_Ginv = CRQ::getGinv(m_G);\n        if (!m_isotropic) {\n            // 2 sk(G^{-1} sk^{-1}(sigma * S)) := sk(g)\n            m_g = 2 * m_Ginv * CRQ::sk_inv(m_biotStress * m_S);\n            m_pk1_stress = m_R * m_biotStress - CRQ::right_mul_sk(m_R, m_g);\n        }\n        else {\n            // If the elasticity tensor is isotropic, then sigma and S commute\n            // (Biot stress and stretch factor share eigenvectors) and all\n            // \"rotational stress\" terms involving sk(g) vanish.\n            m_pk1_stress = m_R * m_biotStress;\n        }\n    }\n\n    const Matrix &getDeformationGradient() const { return m_F; }\n\n    _Real energy() const {\n        return 0.5 * doubleContract(m_biotStress, m_biotStrain);\n    }\n\n    // PK1 stress\n    _Real denergy(const Matrix& dF) const { return doubleContract(denergy(), dF); }\n\n    // Asymmetric!\n    Matrix denergy() const {\n        return m_pk1_stress;\n    }\n\n    // Symmetric!\n    Matrix PK2Stress() const { return m_F.inverse() * denergy(); }\n\n    const Matrix &R() const { return m_R; }\n    const Matrix &S() const { return m_S; }\n    const Matrix &biotStress() const { return m_biotStress; }\n\n    template<class Mat_>\n    Matrix delta_R(const Mat_ &dF) const {\n        typename CRQ::IRotType w = 2 * m_Ginv * CRQ::sk_inv(m_R.transpose() * dF);\n        return CRQ::right_mul_sk(m_R, w);\n    }\n\n    template<class Mat_>\n    Matrix delta_S(const Mat_ &dF, const Matrix &dR) const {\n        return dR.transpose() * m_F + m_R.transpose() * dF;\n    }\n\n    Matrix delta_sigma(const Matrix &dS) const {\n        return m_elasticity_tensor.doubleContract(SMatrix(dS)).toMatrix();\n    }\n\n    template<class Mat_>\n    Matrix delta_denergy(const Mat_ &dF) const {\n        Matrix dR     = delta_R(dF);\n        Matrix dS     = delta_S(dF, dR);\n        Matrix dsigma = delta_sigma(dS);\n\n        Matrix result = dR * m_biotStress + m_R * dsigma;\n\n        if (!m_isotropic) {\n            typename CRQ::IRotType dg = m_Ginv * (2 * CRQ::sk_inv(dsigma * m_S + m_biotStress * dS) - CRQ::getG(dS) * m_g);\n            result -= CRQ::right_mul_sk(dR, m_g) + CRQ::right_mul_sk(m_R, dg);\n        }\n        return result;\n    }\n\n    _Real d2energy(const Matrix &dF_lhs, const Matrix &dF_rhs) const {\n        return doubleContract(delta_denergy(dF_lhs), dF_rhs);\n    }\n\n    template<class Mat_, class Mat2_>\n    Matrix delta2_denergy(const Mat_ &dF_a, const Mat2_ &dF_b) const {\n        typename CRQ::IRotType w_a = 2 * m_Ginv * CRQ::sk_inv(m_R.transpose() * dF_a);\n        Matrix dR_a = CRQ::right_mul_sk(m_R, w_a),\n               dR_b = delta_R(dF_b);\n        Matrix dS_a = delta_S(dF_a, dR_a),\n               dS_b = delta_S(dF_b, dR_b);\n        Matrix dsigma_a = delta_sigma(dS_a);\n        Matrix dsigma_b = delta_sigma(dS_b);\n\n        Matrix d2R, d2S, d2sigma;\n        d2R = CRQ::right_mul_sk(dR_b, w_a)\n            + CRQ::right_mul_sk(m_R, m_Ginv * (2 * CRQ::sk_inv(dR_b.transpose() * dF_a) - CRQ::getG(dS_b) * w_a));\n\n        d2S = d2R.transpose() * m_F + dR_a.transpose() * dF_b + dR_b.transpose() * dF_a;\n        d2sigma = delta_sigma(d2S);\n\n        Matrix result = d2R * m_biotStress + dR_a * dsigma_b + dR_b * dsigma_a + m_R * d2sigma;\n\n        if (!m_isotropic) {\n            typename CRQ::IRotType dg_a = m_Ginv * (2 * CRQ::sk_inv(dsigma_a * m_S + m_biotStress * dS_a) - CRQ::getG(dS_a) * m_g),\n                                   dg_b = m_Ginv * (2 * CRQ::sk_inv(dsigma_b * m_S + m_biotStress * dS_b) - CRQ::getG(dS_b) * m_g),\n                                   d2g  = m_Ginv * (2 * CRQ::sk_inv(d2sigma  * m_S + dsigma_a * dS_b + dsigma_b * dS_a + m_biotStress * d2S) - CRQ::getG(d2S) * m_g - CRQ::getG(dS_a) * dg_b - CRQ::getG(dS_b) * dg_a);\n\n            result -= CRQ::right_mul_sk(d2R, m_g) + CRQ::right_mul_sk(dR_a, dg_b) + CRQ::right_mul_sk(dR_b, dg_a)\n                    + CRQ::right_mul_sk(m_R, d2g);\n        }\n        return result;\n    }\n\n    bool isIsotropic() const { return m_isotropic; }\n\nprivate:\n    ETensor m_elasticity_tensor;\n    Matrix m_F,\n           m_R, m_S, // Polar decomposition\n           m_biotStrain, m_biotStress, m_pk1_stress,\n           m_anisotropicRotationalStress; // Skew symmetric contribution to the PK1 stress; only nonzero for anisotropic material model.\n    typename CRQ::GType m_G, m_Ginv;\n    typename CRQ::IRotType m_g;\n    bool m_isotropic;\n};\n\n#endif /* end of include guard: COROTATEDLINEARELASTICITY_HH */\n", "meta": {"hexsha": "aaf0adadc17ffce9773da843d9c59c252273fdb7", "size": 9532, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/lib/MeshFEM/EnergyDensities/CorotatedLinearElasticity.hh", "max_stars_repo_name": "MeshFEM/MeshFEM", "max_stars_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "src/lib/MeshFEM/EnergyDensities/CorotatedLinearElasticity.hh", "max_issues_repo_name": "MeshFEM/MeshFEM", "max_issues_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "src/lib/MeshFEM/EnergyDensities/CorotatedLinearElasticity.hh", "max_forks_repo_name": "MeshFEM/MeshFEM", "max_forks_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 38.906122449, "max_line_length": 215, "alphanum_fraction": 0.6080570709, "num_tokens": 2769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4182356121934079}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   DataGen_OccupationNumberEvaluator.cpp\n//! \\author Alex Robinson\n//! \\brief  The occupation number evaluator definition\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <limits>\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// Teuchos Includes\n#include <Teuchos_ScalarTraits.hpp>\n\n// FRENSIE Includes\n#include \"DataGen_OccupationNumberEvaluator.hpp\"\n#include \"MonteCarlo_ComptonProfileHelpers.hpp\"\n#include \"Utility_SortAlgorithms.hpp\"\n#include \"Utility_PhysicalConstants.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_ContractException.hpp\"\n\nnamespace DataGen{\n\n// Constructor\n/*! \\details The full electron momentum grid and Compton profile should \n * be given. \n */\nOccupationNumberEvaluator::OccupationNumberEvaluator(\n\t\t   const Teuchos::Array<double>& electron_momentum_projections,\n\t\t   const Teuchos::Array<double>& compton_profile,\n\t\t   const double norm_constant_precision )\n  : d_compton_profile_norm_constant( 1.0 )\n{\n  // Make sure the electron momentum projections are valid\n  testPrecondition( electron_momentum_projections.size() > 1 );\n  testPrecondition( electron_momentum_projections.front() != 0.0 );\n  testPrecondition( electron_momentum_projections.front() == \n\t\t    -electron_momentum_projections.back() );\n  testPrecondition( Utility::Sort::isSortedAscending( \n\t\t\t\t       electron_momentum_projections.begin(),\n\t\t\t\t       electron_momentum_projections.end() ) );\n  // Make sure the compton profile is valid\n  testPrecondition( compton_profile.back() > 0.0 );\n  testPrecondition( compton_profile.front() == compton_profile.back() );\n  testPrecondition( compton_profile.size() == \n\t\t    electron_momentum_projections.size() );\n  \n  // Store the profile in a tabular distribution for quick interpolation\n  d_compton_profile.reset( new Utility::TabularDistribution<Utility::LogLin>(\n\t\t\t\t\t         electron_momentum_projections,\n\t\t\t\t\t         compton_profile ) );\n  \n  // Roundoff errors are common in the available Compton profile tables - \n  // renormalize the table\n  d_compton_profile_norm_constant = this->evaluateOccupationNumber( \n\t\t\t                  electron_momentum_projections.back(),\n\t\t\t\t\t  norm_constant_precision );\n}\n\n// Return the normalization constant used with the Compton profile\ndouble OccupationNumberEvaluator::getComptonProfileNormConstant() const\n{\n  return d_compton_profile_norm_constant;\n}\n\n// Evaluate the compton profile\ndouble OccupationNumberEvaluator::evaluateComptonProfile(\n\t\t\t      const double electron_momentum_projection ) const\n{\n  // Make sure the electron momentum projection is valid\n  testPrecondition( !Teuchos::ScalarTraits<double>::isnaninf(\n\t\t\t\t\t      electron_momentum_projection ) );\n\n  return d_compton_profile->evaluate( electron_momentum_projection )/\n    d_compton_profile_norm_constant;\n}\n\n// Evaluate the occupation number at a given electron momentum projection\ndouble OccupationNumberEvaluator::evaluateOccupationNumber(\n\t\t\t\t     const double electron_momentum_projection,\n\t\t\t\t     const double precision ) const\n{\n  // Make sure the electron momentum projection is valid\n  testPrecondition( !Teuchos::ScalarTraits<double>::isnaninf(\n\t\t\t\t\t      electron_momentum_projection ) );\n\n  double occupation_number;\n\n  if( electron_momentum_projection <= \n      d_compton_profile->getLowerBoundOfIndepVar() )\n  {\n    occupation_number = 0.0;\n  }\n  else if( electron_momentum_projection > \n\t   d_compton_profile->getLowerBoundOfIndepVar() )\n  {\n    boost::function<double (double pz)> compton_profile_wrapper = \n      boost::bind<double>( &OccupationNumberEvaluator::evaluateComptonProfile,\n\t\t\t   boost::cref( *this ),\n\t\t\t   _1 );\n\n    double abs_error;\n    \n    Utility::GaussKronrodIntegrator quadrature_gkq( precision );\n\n    if( electron_momentum_projection < \n\td_compton_profile->getUpperBoundOfIndepVar() )\n    {\n      quadrature_gkq.integrateAdaptively<15>(\n\t\t\t\t  compton_profile_wrapper,\n\t\t\t\t  d_compton_profile->getLowerBoundOfIndepVar(),\n\t\t\t\t  electron_momentum_projection,\n\t\t\t\t  occupation_number,\n\t\t\t\t  abs_error );\n    }\n    else\n    {\n      quadrature_gkq.integrateAdaptively<15>(\n\t\t\t\t  compton_profile_wrapper,\n\t\t\t\t  d_compton_profile->getLowerBoundOfIndepVar(),\n\t\t\t\t  d_compton_profile->getUpperBoundOfIndepVar(),\n\t\t\t\t  occupation_number,\n\t\t\t\t  abs_error );\n    }\t\n  }\n  \n  // Make sure the occupation number is valid\n  testPostcondition( occupation_number >= 0.0 );\n\n  return occupation_number;\n}\n\n\n} // end DataGen namespace\n\n//---------------------------------------------------------------------------//\n// end DataGen_OccupationNumberEvaluator.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "f9dc64efcfc1292119c5ddd4984d9578a78a2968", "size": 4830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/data_gen/electron_photon/src/DataGen_OccupationNumberEvaluator.cpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/data_gen/electron_photon/src/DataGen_OccupationNumberEvaluator.cpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/data_gen/electron_photon/src/DataGen_OccupationNumberEvaluator.cpp", "max_forks_repo_name": "lkersting/SCR-2123", "max_forks_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5416666667, "max_line_length": 79, "alphanum_fraction": 0.6977225673, "num_tokens": 1026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059560743422, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.41821787542874983}}
{"text": "/*\nBrian Staber (brian.staber@gmail.com)\n*/\n\n#ifndef NEUMANNINNERSURFACE_STOCHASTICPOLYCONVEXHGO_HPP\n#define NEUMANNINNERSURFACE_STOCHASTICPOLYCONVEXHGO_HPP\n\n#include \"tensor_calculus.hpp\"\n#include \"nearlyIncompressibleHyperelasticity.hpp\"\n#include \"laplacepp.hpp\"\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/beta.hpp>\n\nclass neumannInnerSurface_StochasticPolyconvexHGO : public nearlyIncompressibleHyperelasticity\n{\npublic:\n\n    laplace * Laplace;\n\n    double w1, w2, w3, w4;\n    double mean_c1, c1, deltaC1;\n    double mean_c2, c2, deltaC2;\n    double mean_u1, u1, deltaU1;\n    double mean_mu4, mu4, deltaG4;\n    double mean_mu1, mu1;\n    double mean_mu2, mu2;\n    double mean_mu3, mu3;\n    double alpha1, alpha2;\n    double alpha3, alpha4;\n    double tau1, tau2;\n    double alpha5, alpha6;\n    double beta3, beta4;\n    double theta;\n    double epsilon = 1e-6;\n\n    Epetra_IntSerialDenseVector cells_nodes_p1_med;\n    Epetra_SerialDenseVector w1_gmrf, w2_gmrf, w3_gmrf, w4_gmrf;\n    Epetra_SerialDenseVector a, b;\n    Epetra_SerialDenseVector E1,E2,E3;\n    Epetra_SerialDenseVector N;\n\n    neumannInnerSurface_StochasticPolyconvexHGO(Epetra_Comm & comm, Teuchos::ParameterList & Parameters){\n\n        std::string mesh_file               = Teuchos::getParameter<std::string>(Parameters.sublist(\"Mesh\"),  \"mesh_file\");\n        std::string boundary_file           = Teuchos::getParameter<std::string>(Parameters.sublist(\"Mesh\"),  \"boundary_file\");\n        unsigned int number_physical_groups = Teuchos::getParameter<unsigned int>(Parameters.sublist(\"Mesh\"), \"nb_phys_groups\");\n        std::string select_model            = Teuchos::getParameter<std::string>(Parameters.sublist(\"Mesh\"),  \"model\");\n\n        mean_mu1   = Teuchos::getParameter<double>(Parameters.sublist(select_model), \"mu1\");\n        mean_mu2   = Teuchos::getParameter<double>(Parameters.sublist(select_model), \"mu2\");\n        mean_mu3   = Teuchos::getParameter<double>(Parameters.sublist(select_model), \"mu3\");\n        mean_mu4   = Teuchos::getParameter<double>(Parameters.sublist(select_model), \"mu4\");\n        beta3      = Teuchos::getParameter<double>(Parameters.sublist(select_model), \"beta3\");\n        beta4      = Teuchos::getParameter<double>(Parameters.sublist(select_model), \"beta4\");\n        theta      = Teuchos::getParameter<double>(Parameters.sublist(select_model), \"theta\");\n        deltaC1    = Teuchos::getParameter<double>(Parameters.sublist(select_model), \"deltaC1\");\n        deltaC2    = Teuchos::getParameter<double>(Parameters.sublist(select_model), \"deltaC2\");\n        deltaU1    = Teuchos::getParameter<double>(Parameters.sublist(select_model), \"deltaU1\");\n        deltaG4    = Teuchos::getParameter<double>(Parameters.sublist(select_model), \"deltaG4\");\n\n        mean_c1 = 2.0*mean_mu3*beta3*beta3;\n        mean_c2 = 2.0*mean_mu1 + std::sqrt(3.0)*3.0*mean_mu2;\n        mean_u1 = 2.0*mean_mu1/mean_c2;\n\n        double gamma = 2.0*mean_mu1/(std::sqrt(3.0)*3.0*mean_mu2);\n        tau2         = (1.0 - deltaU1*deltaU1)/(deltaU1*deltaU1*gamma*(gamma+1.0));\n        tau1         = (2.0*mean_mu1/(std::sqrt(3.0)*3.0*mean_mu2))*tau2;\n\n        alpha1 = 1.0/(deltaC1*deltaC1);\n        alpha2 = mean_c1*deltaC1*deltaC1;\n        alpha3 = 1.0/(deltaC2*deltaC2);\n        alpha4 = mean_c2*deltaC2*deltaC2;\n        alpha5 = 1.0/(deltaG4*deltaG4);\n        alpha6 = mean_mu4*deltaG4*deltaG4;\n\n        Mesh = new mesh(comm, Parameters); //mesh_file, 1000.0);\n        Mesh->read_boundary_file(boundary_file,number_physical_groups);\n        Comm = Mesh->Comm;\n\n        Laplace = new laplace(*Mesh);\n\n        //$$Laplace\n        Epetra_FECrsMatrix matrix(Copy,*Laplace->FEGraph);\n        Epetra_Vector psi(*Laplace->StandardMap);\n        Epetra_Vector phi(*Laplace->StandardMap);\n        Epetra_FEVector rhs(*Laplace->StandardMap);\n        int bc_indx[2];\n        double bc_val[2];\n        bc_val[0] = 0.0; bc_val[1] = 1.0;\n        //Problem number one with aztec\n        bc_indx[0] = 2; bc_indx[1] = 3;\n        Laplace->solve_aztec(Parameters.sublist(\"Laplace\"), matrix, phi, rhs, &bc_indx[0], &bc_val[0]);\n        Laplace->print_solution(phi, \"laplace_inlet_to_outlet_aztec.mtx\");\n        //Problem number one with aztec\n        bc_indx[0] = 0; bc_indx[1] = 1;\n        Laplace->solve_aztec(Parameters.sublist(\"Laplace\"), matrix, psi, rhs, &bc_indx[0], &bc_val[0]);\n        Laplace->print_solution(psi, \"laplace_inner_to_outer_aztec.mtx\");\n        //Get local directions\n        Laplace->compute_local_directions(phi, psi);\n        Laplace->compute_center_local_directions(phi, psi);\n        //$$End\n\n        StandardMap = new Epetra_Map(-1,3*Mesh->n_local_nodes_without_ghosts,&Mesh->local_dof_without_ghosts[0],0,*Comm);\n        OverlapMap = new Epetra_Map(-1,3*Mesh->n_local_nodes,&Mesh->local_dof[0],0,*Comm);\n        ImportToOverlapMap = new Epetra_Import(*OverlapMap,*StandardMap);\n        create_FECrsGraph();\n\n        a.Resize(3);\n        b.Resize(3);\n        E1.Resize(3);\n        E2.Resize(3);\n        E3.Resize(3);\n        N.Resize(4);\n        setup_dirichlet_conditions();\n    }\n\n    ~neumannInnerSurface_StochasticPolyconvexHGO(){\n    }\n\n    void get_media(unsigned int & n_cells, unsigned int & n_nodes, std::string & path){\n\n        std::ifstream connectivity_file_med;\n        connectivity_file_med.open(path);\n\n        w1_gmrf.Resize(n_nodes);\n        w2_gmrf.Resize(n_nodes);\n        w3_gmrf.Resize(n_nodes);\n        w4_gmrf.Resize(n_nodes);\n        if (connectivity_file_med.is_open()){\n            cells_nodes_p1_med.Resize(4*n_cells);\n            for (unsigned int e=0; e<4*n_cells; ++e){\n                connectivity_file_med >> cells_nodes_p1_med[e];\n                cells_nodes_p1_med[e] = cells_nodes_p1_med[e]-1;\n            }\n            connectivity_file_med.close();\n        }\n        else{\n            std::cout << \"Couldn't open the connectivity file for the media.\\n\";\n        }\n\n    }\n\n    void get_matrix_and_rhs(Epetra_Vector & x, Epetra_FECrsMatrix & K, Epetra_FEVector & F){\n        assembleMixedDirichletDeformationDependentNeumann_homogeneousForcing(x,K,F);\n    }\n\n    void setup_dirichlet_conditions(){\n        //setup_clamp();\n        setup_semislipbc();\n        //setup_slipbc_and_clamp();\n        //setup_slipbc();\n    }\n\n    void apply_dirichlet_conditions(Epetra_FECrsMatrix & K, Epetra_FEVector & F, double & displacement){\n        //apply_clamp(K,F,displacement);\n        apply_semiselipbc(K,F,displacement);\n        //apply_slipbc_and_clamp(K,F,displacement);\n        //apply_slipbc(K,F,displacement);\n    }\n\n    void get_material_parameters(unsigned int & e_lid, unsigned int & gp){\n\n        int n_gauss_points = Mesh->n_gauss_cells;\n        int e_gid = Mesh->local_cells[e_lid];\n        int node;\n        double xi = Mesh->xi_cells[gp]; double eta = Mesh->eta_cells[gp]; double zeta = Mesh->zeta_cells[gp];\n        tetra4::shape_functions(N,xi,eta,zeta);\n\n        w1 = 0.0; w2 = 0.0; w3 = 0.0; w4 = 0.0;\n        for (unsigned int j=0; j<4; ++j){\n            node = cells_nodes_p1_med(4*e_gid+j);\n            w1 += N(j)*w1_gmrf(node);\n            w2 += N(j)*w2_gmrf(node);\n            w3 += N(j)*w3_gmrf(node);\n            w4 += N(j)*w4_gmrf(node);\n        }\n\n        c1  = icdf_gamma(w1,alpha1,alpha2);\n        c2  = icdf_gamma(w2,alpha3,alpha4);\n        u1  = icdf_beta (w3,tau1,tau2);\n        mu4 = icdf_gamma(w4,alpha5,alpha6);\n\n        mu1 = ( epsilon*mean_mu1 + (1.0/2.0)*c2*u1 )/( 1.0+epsilon );\n        mu2 = ( epsilon*mean_mu2 + (1.0/(std::sqrt(3.0)*3.0))*c2*(1.0-u1) )/( 1.0+epsilon );\n        mu3 = ( epsilon*mean_mu3 + c1/(2.0*beta3*beta3) )/( 1.0+epsilon );\n        mu4 = ( epsilon*mean_mu4 + mu4 )/( 1.0+epsilon );\n\n        for (int i=0; i<3; ++i){\n            E1(i) = Laplace->laplace_direction_one(n_gauss_points*e_lid+gp,i);\n            E2(i) = Laplace->laplace_direction_two_cross_one(n_gauss_points*e_lid+gp,i);\n            E3(i) = Laplace->laplace_direction_two(n_gauss_points*e_lid+gp,i);\n            a(i) = cos(theta)*E1(i) + sin(theta)*E2(i);\n            b(i) = cos(theta)*E1(i) - sin(theta)*E2(i);\n        }\n\n    }\n\n    double icdf_gamma(double & w, double & alpha, double & beta){\n        double erfx = boost::math::erf<double>(w/std::sqrt(2.0));\n        double y = (1.0/2.0)*(1.0 + erfx);\n        double yinv = boost::math::gamma_p_inv<double,double>(alpha,y);\n        double z = yinv*beta;\n        return z;\n    }\n\n    double icdf_beta(double & w, double & tau1, double & tau2){\n        double erfx = boost::math::erf<double>(w/std::sqrt(2.0));\n        double y = (1.0/2.0)*(1.0 + erfx);\n        double z = boost::math::ibeta_inv<double,double,double>(tau1,tau2,y);\n        return z;\n    }\n\n    void get_constitutive_tensors_static_condensation(Epetra_SerialDenseMatrix & deformation_gradient, double & det, Epetra_SerialDenseVector & inverse_cauchy, Epetra_SerialDenseVector & piola_isc, Epetra_SerialDenseVector & piola_vol, Epetra_SerialDenseMatrix & tangent_piola_isc, Epetra_SerialDenseMatrix & tangent_piola_vol){\n        model_C(deformation_gradient, det, inverse_cauchy, piola_isc, piola_vol, tangent_piola_isc, tangent_piola_vol);\n    }\n\n    void get_internal_pressure(double & theta, double & pressure, double & dpressure){\n        double ptheta = std::pow(theta,beta3);\n        pressure  = beta3*( (ptheta/theta) - (1.0/(ptheta*theta)) );\n        dpressure = beta3*( (beta3-1.0)*(ptheta/(theta*theta)) + (beta3+1.0)/(ptheta*theta*theta) );\n    }\n\n    void get_material_parameters_for_recover(unsigned int & e_lid){\n\n      int e_gid = Mesh->local_cells[e_lid];\n      double xi = 1.0/3.0; double eta = 1.0/3.0; double zeta = 1.0/3.0;\n      tetra4::shape_functions(N,xi,eta,zeta);\n\n      w1 = 0.0; w2 = 0.0; w3 = 0.0; w4 = 0.0;\n      for (unsigned int j=0; j<4; ++j){\n          int node = cells_nodes_p1_med(4*e_gid+j);\n          w1 += N(j)*w1_gmrf(node);\n          w2 += N(j)*w2_gmrf(node);\n          w3 += N(j)*w3_gmrf(node);\n          w4 += N(j)*w4_gmrf(node);\n      }\n\n      c1  = icdf_gamma(w1,alpha1,alpha2);\n      c2  = icdf_gamma(w2,alpha3,alpha4);\n      u1  = icdf_beta (w3,tau1,tau2);\n      mu4 = icdf_gamma(w4,alpha5,alpha6);\n\n      mu1 = ( epsilon*mean_mu1 + (1.0/2.0)*c2*u1 )/( 1.0+epsilon );\n      mu2 = ( epsilon*mean_mu2 + (1.0/(std::sqrt(3.0)*3.0))*c2*(1.0-u1) )/( 1.0+epsilon );\n      mu3 = ( epsilon*mean_mu3 + c1/(2.0*beta3*beta3) )/( 1.0+epsilon );\n      mu4 = ( epsilon*mean_mu4 + mu4 )/( 1.0+epsilon );\n\n      for (int i=0; i<3; ++i){\n          E1(i) = Laplace->laplace_direction_one_center(e_lid,i);\n          E2(i) = Laplace->laplace_direction_two_cross_one_center(e_lid,i);\n          E3(i) = Laplace->laplace_direction_two_center(e_lid,i);\n          a(i) = cos(theta)*E1(i) + sin(theta)*E2(i);\n          b(i) = cos(theta)*E1(i) - sin(theta)*E2(i);\n      }\n\n    }\n\n    void get_stress_for_recover(Epetra_SerialDenseMatrix & deformation_gradient, double & det, Epetra_SerialDenseMatrix & piola_stress){\n\n        det = deformation_gradient(0,0)*deformation_gradient(1,1)*deformation_gradient(2,2)\n            -deformation_gradient(0,0)*deformation_gradient(1,2)*deformation_gradient(2,1)\n            -deformation_gradient(0,1)*deformation_gradient(1,0)*deformation_gradient(2,2)\n            +deformation_gradient(0,1)*deformation_gradient(1,2)*deformation_gradient(2,0)\n            +deformation_gradient(0,2)*deformation_gradient(1,0)*deformation_gradient(2,1)\n            -deformation_gradient(0,2)*deformation_gradient(1,1)*deformation_gradient(2,0);\n\n        double alpha = std::pow(det,-2.0/3.0);\n        double beta = 1.0/(det*det);\n        Epetra_SerialDenseMatrix eye(3,3);\n        Epetra_SerialDenseMatrix M1(3,3), M2(3,3);\n        Epetra_SerialDenseMatrix C(3,3), L(3,3);\n        Epetra_SerialDenseMatrix piola_ani1(3,3), piola_ani2(3,3);\n\n        eye(0,0) = 1.0; eye(0,1) = 0.0; eye(0,2) = 0.0;\n        eye(1,0) = 0.0; eye(1,1) = 1.0; eye(1,2) = 0.0;\n        eye(2,0) = 0.0; eye(2,1) = 0.0; eye(2,2) = 1.0;\n\n        M1.Multiply('N','T',1.0,a,a,0.0);\n        M2.Multiply('N','T',1.0,b,b,0.0);\n\n        C.Multiply('T','N',1.0,deformation_gradient,deformation_gradient,0.0);\n\n        L(0,0) = (1.0/(det*det))*(C(1,1)*C(2,2)-C(1,2)*C(2,1));\n        L(1,1) = (1.0/(det*det))*(C(0,0)*C(2,2)-C(0,2)*C(2,0));\n        L(2,2) = (1.0/(det*det))*(C(0,0)*C(1,1)-C(0,1)*C(1,0));\n        L(1,2) = (1.0/(det*det))*(C(0,2)*C(1,0)-C(0,0)*C(1,2));\n        L(0,2) = (1.0/(det*det))*(C(0,1)*C(1,2)-C(0,2)*C(1,1));\n        L(0,1) = (1.0/(det*det))*(C(0,2)*C(2,1)-C(0,1)*C(2,2));\n        L(2,1) = L(1,2); L(2,0) = L(0,2); L(1,0) = L(0,1);\n\n        double I1   = C(0,0) + C(1,1) + C(2,2);\n        double II1  = C(0,0)*C(0,0) + C(1,1)*C(1,1) + C(2,2)*C(2,2) + 2.0*C(1,2)*C(1,2) + 2.0*C(0,2)*C(0,2) + 2.0*C(0,1)*C(0,1);\n        double I2   = (1.0/2.0)*(I1*I1-II1);\n        double I4_1 = C(0,0)*M1(0,0) + C(1,1)*M1(1,1) + C(2,2)*M1(2,2) + 2.0*C(0,1)*M1(0,1) + 2.0*C(0,2)*M1(0,2) + 2.0*C(1,2)*M1(1,2);\n        double I4_2 = C(0,0)*M2(0,0) + C(1,1)*M2(1,1) + C(2,2)*M2(2,2) + 2.0*C(0,1)*M2(0,1) + 2.0*C(0,2)*M2(0,2) + 2.0*C(1,2)*M2(1,2);\n        double pI2  = std::sqrt(I2);\n\n        double S4_1 = (I4_1-1.0)*(I4_1-1.0);\n        double S4_2 = (I4_2-1.0)*(I4_2-1.0);\n\n        double ptheta = std::pow(det,beta3);\n        double pressure = mu3*beta3*( (ptheta/det) - (1.0/(ptheta*det)) );\n\n        for (unsigned int i=0; i<3; ++i){\n            for (unsigned int j=0; j<3; ++j){\n                piola_stress(i,j) = 2.0*mu1*alpha*(eye(i,j)-(1.0/3.0)*L(i,j))\n                + mu2*beta*( 3.0*pI2*(I1*eye(i,j)-C(i,j)) - 2.0*I2*pI2*L(i,j) )\n                + det*pressure*L(i,j);\n                piola_ani1(i,j) = 4.0*mu4*(I4_1-1.0)*exp(beta4*S4_1)*M1(i,j);\n                piola_ani2(i,j) = 4.0*mu4*(I4_2-1.0)*exp(beta4*S4_2)*M2(i,j);\n            }\n        }\n\n        if (I4_1>1.0){\n            piola_stress += piola_ani1;\n        }\n        if (I4_2>1.0){\n            piola_stress += piola_ani2;\n        }\n\n    }\n\n    void setup_clamp(){\n        n_bc_dof = 0;\n        for (unsigned int i=0; i<Mesh->n_local_nodes_without_ghosts; ++i){\n            if (Mesh->nodes_to_boundaries(i,2)==1 || Mesh->nodes_to_boundaries(i,3)==1){\n                n_bc_dof+=3;\n            }\n        }\n\n        int indbc = 0;\n        dof_on_boundary = new int [n_bc_dof];\n        for (unsigned int inode=0; inode<Mesh->n_local_nodes_without_ghosts; ++inode){\n            if (Mesh->nodes_to_boundaries(inode,2)==1 || Mesh->nodes_to_boundaries(inode,3)==1){\n                dof_on_boundary[indbc+0] = 3*inode+0;\n                dof_on_boundary[indbc+1] = 3*inode+1;\n                dof_on_boundary[indbc+2] = 3*inode+2;\n                indbc+=3;\n            }\n        }\n    }\n\n    void setup_slipbc(){\n        const int nodesblk_gid0 = 480-1;\n        const int nodesblk_gid1 = 538-1;\n        const int nodesblk_gid2 = 577-1;\n\n        int node;\n        n_bc_dof = 0;\n        for (unsigned int i=0; i<Mesh->n_local_nodes_without_ghosts; ++i){\n            if (Mesh->nodes_to_boundaries(i,2)==1 || Mesh->nodes_to_boundaries(i,3)==1){\n                node = Mesh->local_nodes[i];\n                switch (node){\n                    case nodesblk_gid0:\n                        n_bc_dof+=2;\n                        break;\n                    case nodesblk_gid1:\n                        n_bc_dof+=2;\n                        break;\n                    case nodesblk_gid2:\n                        n_bc_dof+=2;\n                        break;\n                    default:\n                        n_bc_dof+=1;\n                        break;\n                };\n            }\n        }\n\n        int indbc = 0;\n        dof_on_boundary = new int [n_bc_dof];\n        for (unsigned int inode=0; inode<Mesh->n_local_nodes_without_ghosts; ++inode){\n            if (Mesh->nodes_to_boundaries(inode,2)==1 || Mesh->nodes_to_boundaries(inode,3)==1){\n                node = Mesh->local_nodes[inode];\n                switch (node){\n                    case nodesblk_gid0:\n                        dof_on_boundary[indbc+0] = 3*inode+0;\n                        dof_on_boundary[indbc+1] = 3*inode+1;\n                        indbc+=2;\n                        break;\n                    case nodesblk_gid1:\n                        dof_on_boundary[indbc+0] = 3*inode+0;\n                        dof_on_boundary[indbc+1] = 3*inode+2;\n                        indbc+=2;\n                        break;\n                    case nodesblk_gid2:\n                        dof_on_boundary[indbc+0] = 3*inode+0;\n                        dof_on_boundary[indbc+1] = 3*inode+2;\n                        indbc+=2;\n                        break;\n                    default:\n                        dof_on_boundary[indbc+0] = 3*inode+0;\n                        indbc+=1;\n                        break;\n                };\n            }\n        }\n    }\n\n    void setup_semislipbc(){\n        n_bc_dof = 0;\n        for (unsigned int i=0; i<Mesh->n_local_nodes_without_ghosts; ++i){\n            if (Mesh->nodes_to_boundaries(i,2)==1){\n                n_bc_dof+=1;\n            }\n            if (Mesh->nodes_to_boundaries(i,3)==1){\n                n_bc_dof+=3;\n            }\n        }\n\n        int indbc = 0;\n        dof_on_boundary = new int [n_bc_dof];\n        for (unsigned int inode=0; inode<Mesh->n_local_nodes_without_ghosts; ++inode){\n            if (Mesh->nodes_to_boundaries(inode,2)==1){\n                dof_on_boundary[indbc] = 3*inode+0;\n                indbc+=1;\n            }\n            if (Mesh->nodes_to_boundaries(inode,3)==1){\n                dof_on_boundary[indbc+0] = 3*inode+0;\n                dof_on_boundary[indbc+1] = 3*inode+1;\n                dof_on_boundary[indbc+2] = 3*inode+2;\n                indbc+=3;\n            }\n        }\n    }\n\n    void setup_slipbc_and_clamp(){\n        Epetra_IntSerialDenseVector nodesblk_gid(3);\n        nodesblk_gid(0) = 480-1;\n        nodesblk_gid(1) = 481-1;\n        nodesblk_gid(2) = 479-1;\n\n        /*nodesblk_gid(0) = 203-1;\n         nodesblk_gid(1) = 204-1;\n         nodesblk_gid(2) = 205-1;\n         nodesblk_gid(3) = 206-1;\n         nodesblk_gid(4) = 207-1;\n         nodesblk_gid(5) = 208-1;\n         nodesblk_gid(6) = 281-1;\n         nodesblk_gid(7) = 282-1;\n         nodesblk_gid(8) = 283-1;\n         nodesblk_gid(9) = 284-1;\n         nodesblk_gid(10) = 285-1;\n         nodesblk_gid(11) = 286-1;*/\n\n        int node;\n        n_bc_dof = 0;\n        for (unsigned int i=0; i<Mesh->n_local_nodes_without_ghosts; ++i){\n            if (Mesh->nodes_to_boundaries(i,2)==1 || Mesh->nodes_to_boundaries(i,3)==1){\n                node = Mesh->local_nodes[i];\n                if (node==nodesblk_gid(0)||node==nodesblk_gid(1)||node==nodesblk_gid(2)){\n                    n_bc_dof+=3;\n                }\n                else{\n                    n_bc_dof+=1;\n                }\n            }\n        }\n\n        int indbc = 0;\n        dof_on_boundary = new int [n_bc_dof];\n        for (unsigned int inode=0; inode<Mesh->n_local_nodes_without_ghosts; ++inode){\n            if (Mesh->nodes_to_boundaries(inode,2)==1 || Mesh->nodes_to_boundaries(inode,3)==1){\n                node = Mesh->local_nodes[inode];\n                if (node==nodesblk_gid(0)||node==nodesblk_gid(1)||node==nodesblk_gid(2)){\n                    dof_on_boundary[indbc+0] = 3*inode+0;\n                    dof_on_boundary[indbc+1] = 3*inode+1;\n                    dof_on_boundary[indbc+2] = 3*inode+2;\n                    indbc+=3;\n                }\n                else{\n                    dof_on_boundary[indbc+0] = 3*inode+0;\n                    indbc+=1;\n                }\n            }\n        }\n    }\n\n    void apply_clamp(Epetra_FECrsMatrix & K, Epetra_FEVector & F, double & displacement){\n        if (n_bc_dof>0){\n            int node;\n            for (int inode=0; inode<Mesh->n_local_nodes_without_ghosts; ++inode){\n                node = Mesh->local_nodes[inode];\n                if (Mesh->nodes_to_boundaries(inode,2)==1 || Mesh->nodes_to_boundaries(inode,3)==1){\n                    F[0][StandardMap->LID(3*node+0)] = displacement;\n                    F[0][StandardMap->LID(3*node+1)] = displacement;\n                    F[0][StandardMap->LID(3*node+2)] = displacement;\n                }\n            }\n        }\n        ML_Epetra::Apply_OAZToMatrix(dof_on_boundary,n_bc_dof,K);\n    }\n\n    void apply_slipbc(Epetra_FECrsMatrix & K, Epetra_FEVector & F, double & displacement){\n        const int nodesblk_gid0 = 480-1;\n        const int nodesblk_gid1 = 538-1;\n        const int nodesblk_gid2 = 577-1;\n\n        if (n_bc_dof>0){\n            int node;\n            for (int inode=0; inode<Mesh->n_local_nodes_without_ghosts; ++inode){\n                node = Mesh->local_nodes[inode];\n                if (Mesh->nodes_to_boundaries(inode,2)==1 || Mesh->nodes_to_boundaries(inode,3)==1){\n                    switch (node){\n                        case nodesblk_gid0:\n                            F[0][StandardMap->LID(3*node+0)] = displacement;\n                            F[0][StandardMap->LID(3*node+1)] = displacement;\n                            break;\n                        case nodesblk_gid1:\n                            F[0][StandardMap->LID(3*node+0)] = displacement;\n                            F[0][StandardMap->LID(3*node+2)] = displacement;\n                            break;\n                        case nodesblk_gid2:\n                            F[0][StandardMap->LID(3*node+0)] = displacement;\n                            F[0][StandardMap->LID(3*node+2)] = displacement;\n                            break;\n                        default:\n                            F[0][StandardMap->LID(3*node+0)] = displacement;\n                            break;\n                    };\n                }\n            }\n        }\n        ML_Epetra::Apply_OAZToMatrix(dof_on_boundary,n_bc_dof,K);\n    }\n\n    void apply_semiselipbc(Epetra_FECrsMatrix & K, Epetra_FEVector & F, double & displacement){\n        if (n_bc_dof>0){\n            int node;\n            for (int inode=0; inode<Mesh->n_local_nodes_without_ghosts; ++inode){\n                node = Mesh->local_nodes[inode];\n                if (Mesh->nodes_to_boundaries(inode,2)==1){\n                    F[0][StandardMap->LID(3*node+0)] = displacement;\n                }\n                if (Mesh->nodes_to_boundaries(inode,3)==1){\n                    F[0][StandardMap->LID(3*node+0)] = displacement;\n                    F[0][StandardMap->LID(3*node+1)] = displacement;\n                    F[0][StandardMap->LID(3*node+2)] = displacement;\n                }\n            }\n        }\n        ML_Epetra::Apply_OAZToMatrix(dof_on_boundary,n_bc_dof,K);\n    }\n\n    void apply_slipbc_and_clamp(Epetra_FECrsMatrix & K, Epetra_FEVector & F, double & displacement){\n        Epetra_IntSerialDenseVector nodesblk_gid(3);\n        nodesblk_gid(0) = 480-1;\n        nodesblk_gid(1) = 481-1;\n        nodesblk_gid(2) = 479-1;\n\n        if (n_bc_dof>0){\n            int node;\n            for (int inode=0; inode<Mesh->n_local_nodes_without_ghosts; ++inode){\n                node = Mesh->local_nodes[inode];\n                if (Mesh->nodes_to_boundaries(inode,2)==1 || Mesh->nodes_to_boundaries(inode,3)==1){\n                    if (node==nodesblk_gid(0)||node==nodesblk_gid(1)||node==nodesblk_gid(2)){\n                        F[0][StandardMap->LID(3*node+0)] = displacement;\n                        F[0][StandardMap->LID(3*node+1)] = displacement;\n                        F[0][StandardMap->LID(3*node+2)] = displacement;\n                    }\n                    else{\n                        F[0][StandardMap->LID(3*node+0)] = displacement;\n                    }\n                }\n            }\n        }\n        ML_Epetra::Apply_OAZToMatrix(dof_on_boundary,n_bc_dof,K);\n    }\n\n    void model_C(Epetra_SerialDenseMatrix & deformation_gradient, double & det, Epetra_SerialDenseVector & L, Epetra_SerialDenseVector & piola_isc, Epetra_SerialDenseVector & piola_vol, Epetra_SerialDenseMatrix & tangent_piola_isc, Epetra_SerialDenseMatrix & tangent_piola_vol){\n\n        det = deformation_gradient(0,0)*deformation_gradient(1,1)*deformation_gradient(2,2)\n            -deformation_gradient(0,0)*deformation_gradient(1,2)*deformation_gradient(2,1)\n            -deformation_gradient(0,1)*deformation_gradient(1,0)*deformation_gradient(2,2)\n            +deformation_gradient(0,1)*deformation_gradient(1,2)*deformation_gradient(2,0)\n            +deformation_gradient(0,2)*deformation_gradient(1,0)*deformation_gradient(2,1)\n            -deformation_gradient(0,2)*deformation_gradient(1,1)*deformation_gradient(2,0);\n\n        double alpha = std::pow(det,-2.0/3.0);\n\n        Epetra_SerialDenseVector eye(6);\n        Epetra_SerialDenseMatrix rightCauchy(3,3);\n        Epetra_SerialDenseVector M1(6), M2(6);\n        Epetra_SerialDenseVector C(6), D(6);\n        Epetra_SerialDenseVector piola_nh(6), piola_ani1(6), piola_ani2(6);\n\n        M1(0) = a(0)*a(0); M2(0) = b(0)*b(0);\n        M1(1) = a(1)*a(1); M2(1) = b(1)*b(1);\n        M1(2) = a(2)*a(2); M2(2) = b(2)*b(2);\n        M1(3) = a(1)*a(2); M2(3) = b(1)*b(2);\n        M1(4) = a(0)*a(2); M2(4) = b(0)*b(2);\n        M1(5) = a(0)*a(1); M2(5) = b(0)*b(1);\n\n        rightCauchy.Multiply('T','N',1.0,deformation_gradient,deformation_gradient,0.0);\n\n        eye(0) = 1.0; eye(1) = 1.0; eye(2) = 1.0; eye(3) = 0.0; eye(4) = 0.0; eye(5) = 0.0;\n\n        C(0) = rightCauchy(0,0); C(1) = rightCauchy(1,1); C(2) = rightCauchy(2,2);\n        C(3) = rightCauchy(1,2); C(4) = rightCauchy(0,2); C(5) = rightCauchy(0,1);\n\n        L(0) = (1.0/(det*det))*(rightCauchy(1,1)*rightCauchy(2,2)-rightCauchy(1,2)*rightCauchy(2,1));\n        L(1) = (1.0/(det*det))*(rightCauchy(0,0)*rightCauchy(2,2)-rightCauchy(0,2)*rightCauchy(2,0));\n        L(2) = (1.0/(det*det))*(rightCauchy(0,0)*rightCauchy(1,1)-rightCauchy(0,1)*rightCauchy(1,0));\n        L(3) = (1.0/(det*det))*(rightCauchy(0,2)*rightCauchy(1,0)-rightCauchy(0,0)*rightCauchy(1,2));\n        L(4) = (1.0/(det*det))*(rightCauchy(0,1)*rightCauchy(1,2)-rightCauchy(0,2)*rightCauchy(1,1));\n        L(5) = (1.0/(det*det))*(rightCauchy(0,2)*rightCauchy(2,1)-rightCauchy(0,1)*rightCauchy(2,2));\n\n        double I1   = C(0) + C(1) + C(2);\n        double II1  = C(0)*C(0) + C(1)*C(1) + C(2)*C(2) + 2.0*C(3)*C(3) + 2.0*C(4)*C(4) + 2.0*C(5)*C(5);\n        double I2   = (1.0/2.0)*(I1*I1-II1);\n        double I4_1 = C(0)*M1(0) + C(1)*M1(1) + C(2)*M1(2) + 2.0*C(5)*M1(5) + 2.0*C(4)*M1(4) + 2.0*C(3)*M1(3);\n        double I4_2 = C(0)*M2(0) + C(1)*M2(1) + C(2)*M2(2) + 2.0*C(5)*M2(5) + 2.0*C(4)*M2(4) + 2.0*C(3)*M2(3);\n        double pI2  = std::sqrt(I2);\n\n        double S4_1 = (I4_1-1.0)*(I4_1-1.0);\n        double S4_2 = (I4_2-1.0)*(I4_2-1.0);\n\n        for (unsigned int i=0; i<6; ++i){\n            D(i) = I1*eye(i) - C(i);\n            piola_nh(i) = 2.0*alpha*mu1*(eye(i)-(1.0/3.0)*I1*L(i));\n            piola_isc(i) = piola_nh(i) + (mu2/(det*det))*( 3.0*pI2*D(i) - 2.0*pI2*I2*L(i) );\n\n            piola_ani1(i) = 4.0*mu4*(I4_1-1.0)*exp(beta4*S4_1)*M1(i);\n            piola_ani2(i) = 4.0*mu4*(I4_2-1.0)*exp(beta4*S4_2)*M2(i);\n\n            piola_vol(i) = mu3*det*L(i);\n        }\n\n        double scalarAB;\n\n        scalarAB = mu3*det;\n        tensor_product(mu3*det,L,L,tangent_piola_vol,0.0);\n        scalarAB = -2.0*mu3*det;\n        sym_tensor_product(scalarAB,L,L,tangent_piola_vol,1.0);\n\n        scalarAB = -2.0/3.0;\n        tensor_product(scalarAB,piola_nh,L,tangent_piola_isc,0.0);\n        tensor_product(scalarAB,L,piola_nh,tangent_piola_isc,1.0);\n\n        scalarAB = -6.0*mu2*pI2/(det*det);\n        tensor_product(scalarAB,D,eye,tangent_piola_isc,1.0);\n        tensor_product(scalarAB,eye,D,tangent_piola_isc,1.0);\n\n        scalarAB = (-4.0/9.0)*mu1*alpha*I1 + 4.0*mu2*pI2*I2/(det*det);\n        tensor_product(scalarAB,L,L,tangent_piola_isc,1.0);\n\n        scalarAB = (4.0/3.0)*mu1*alpha*I1 + 4.0*mu2*pI2*I2/(det*det);\n        sym_tensor_product(scalarAB,L,L,tangent_piola_isc,1.0);\n\n        scalarAB = 3.0*mu2/(det*det*pI2);\n        tensor_product(scalarAB,D,D,tangent_piola_isc,1.0);\n\n        scalarAB = 6.0*mu2*pI2/(det*det);\n        tensor_product(scalarAB,eye,eye,tangent_piola_isc,1.0);\n\n        scalarAB = -scalarAB;\n        sym_tensor_product(scalarAB,eye,eye,tangent_piola_isc,1.0);\n\n        if (I4_1>1.0){\n            piola_isc += piola_ani1;\n            scalarAB = (8.0*mu4 + 16.0*mu4*beta4*S4_1)*exp(beta4*S4_1);\n            tensor_product(scalarAB,M1,M1,tangent_piola_isc,1.0);\n        }\n        if (I4_2>1.0){\n            piola_isc += piola_ani2;\n            scalarAB = (8.0*mu4 + 16.0*mu4*beta4*S4_2)*exp(beta4*S4_2);\n            tensor_product(scalarAB,M2,M2,tangent_piola_isc,1.0);\n        }\n    }\n\n    void model_B(Epetra_SerialDenseMatrix & deformation_gradient, double & det, Epetra_SerialDenseVector & piola_isc, Epetra_SerialDenseVector & piola_vol, Epetra_SerialDenseMatrix & tangent_piola_isc, Epetra_SerialDenseMatrix & tangent_piola_vol){\n\n        det = deformation_gradient(0,0)*deformation_gradient(1,1)*deformation_gradient(2,2)-deformation_gradient(0,0)*deformation_gradient(1,2)*deformation_gradient(2,1)-deformation_gradient(0,1)*deformation_gradient(1,0)*deformation_gradient(2,2)+deformation_gradient(0,1)*deformation_gradient(1,2)*deformation_gradient(2,0)+deformation_gradient(0,2)*deformation_gradient(1,0)*deformation_gradient(2,1)-deformation_gradient(0,2)*deformation_gradient(1,1)*deformation_gradient(2,0);\n\n        double alpha = std::pow(det,-2.0/3.0);\n\n        Epetra_SerialDenseMatrix rightCauchy(3,3);\n        Epetra_SerialDenseVector M1(6), M2(6);\n        Epetra_SerialDenseVector eye(6);\n        Epetra_SerialDenseVector C(6), D(6), L(6);\n        Epetra_SerialDenseVector dI4_1(6), dI4_2(6);\n        Epetra_SerialDenseVector piola_nh(6), piola_ani1(6), piola_ani2(6);\n\n        M1(0) = a(0)*a(0); M2(0) = b(0)*b(0);\n        M1(1) = a(1)*a(1); M2(1) = b(1)*b(1);\n        M1(2) = a(2)*a(2); M2(2) = b(2)*b(2);\n        M1(3) = a(1)*a(2); M2(3) = b(1)*b(2);\n        M1(4) = a(0)*a(2); M2(4) = b(0)*b(2);\n        M1(5) = a(0)*a(1); M2(5) = b(0)*b(1);\n\n        rightCauchy.Multiply('T','N',1.0,deformation_gradient,deformation_gradient,0.0);\n\n        eye(0) = 1.0; eye(1) = 1.0; eye(2) = 1.0; eye(3) = 0.0; eye(4) = 0.0; eye(5) = 0.0;\n\n        C(0) = rightCauchy(0,0); C(1) = rightCauchy(1,1); C(2) = rightCauchy(2,2);\n        C(3) = rightCauchy(1,2); C(4) = rightCauchy(0,2); C(5) = rightCauchy(0,1);\n\n        L(0) = (1.0/(det*det))*(rightCauchy(1,1)*rightCauchy(2,2)-rightCauchy(1,2)*rightCauchy(2,1));\n        L(1) = (1.0/(det*det))*(rightCauchy(0,0)*rightCauchy(2,2)-rightCauchy(0,2)*rightCauchy(2,0));\n        L(2) = (1.0/(det*det))*(rightCauchy(0,0)*rightCauchy(1,1)-rightCauchy(0,1)*rightCauchy(1,0));\n        L(3) = (1.0/(det*det))*(rightCauchy(0,2)*rightCauchy(1,0)-rightCauchy(0,0)*rightCauchy(1,2));\n        L(4) = (1.0/(det*det))*(rightCauchy(0,1)*rightCauchy(1,2)-rightCauchy(0,2)*rightCauchy(1,1));\n        L(5) = (1.0/(det*det))*(rightCauchy(0,2)*rightCauchy(2,1)-rightCauchy(0,1)*rightCauchy(2,2));\n\n        double I1 = C(0) + C(1) + C(2);\n        double II1 = C(0)*C(0) + C(1)*C(1) + C(2)*C(2) + 2.0*C(3)*C(3) + 2.0*C(4)*C(4) + 2.0*C(5)*C(5);\n        double I2 = (1.0/2.0)*(I1*I1-II1);\n        double I4_1 = C(0)*M1(0) + C(1)*M1(1) + C(2)*M1(2) + 2.0*C(5)*M1(5) + 2.0*C(4)*M1(4) + 2.0*C(3)*M1(3);\n        double I4_2 = C(0)*M2(0) + C(1)*M2(1) + C(2)*M2(2) + 2.0*C(5)*M2(5) + 2.0*C(4)*M2(4) + 2.0*C(3)*M2(3);\n        double pI2 = std::sqrt(I2);\n\n        double S4_1 = (alpha*I4_1-1.0)*(alpha*I4_1-1.0);\n        double S4_2 = (alpha*I4_2-1.0)*(alpha*I4_2-1.0);\n\n        for (unsigned int i=0; i<6; ++i){\n            D(i) = I1*eye(i) - C(i);\n            dI4_1(i) = M1(i)-(1.0/3.0)*I4_1*L(i);\n            dI4_2(i) = M2(i)-(1.0/3.0)*I4_2*L(i);\n            piola_nh(i) = 2.0*alpha*mu1*(eye(i)-(1.0/3.0)*I1*L(i));\n            piola_isc(i) = piola_nh(i) + (mu2/(det*det))*( 3.0*pI2*D(i) - 2.0*pI2*I2*L(i) );\n\n            piola_ani1(i) = 4.0*mu4*alpha*(alpha*I4_1-1.0)*exp(beta4*S4_1)*(M1(i)-(1.0/3.0)*I4_1*L(i));\n            piola_ani2(i) = 4.0*mu4*alpha*(alpha*I4_2-1.0)*exp(beta4*S4_2)*(M2(i)-(1.0/3.0)*I4_2*L(i));;\n\n            piola_vol(i) = det*L(i);\n        }\n\n        double scalarAB;\n\n        scalarAB = det;\n        tensor_product(det,L,L,tangent_piola_vol,0.0);\n        scalarAB = -2.0*det;\n        sym_tensor_product(scalarAB,L,L,tangent_piola_vol,1.0);\n\n        scalarAB = -2.0/3.0;\n        tensor_product(scalarAB,piola_nh,L,tangent_piola_isc,0.0);\n        tensor_product(scalarAB,L,piola_nh,tangent_piola_isc,1.0);\n\n        scalarAB = -6.0*mu2*pI2/(det*det);\n        tensor_product(scalarAB,D,eye,tangent_piola_isc,1.0);\n        tensor_product(scalarAB,eye,D,tangent_piola_isc,1.0);\n\n        scalarAB = (-4.0/9.0)*mu1*alpha*I1 + 4.0*mu2*pI2*I2/(det*det);\n        tensor_product(scalarAB,L,L,tangent_piola_isc,1.0);\n\n        scalarAB = (4.0/3.0)*mu1*alpha*I1 + 4.0*mu2*pI2*I2/(det*det);\n        sym_tensor_product(scalarAB,L,L,tangent_piola_isc,1.0);\n\n        scalarAB = 3.0*mu2/(det*det*pI2);\n        tensor_product(scalarAB,D,D,tangent_piola_isc,1.0);\n\n        scalarAB = 6.0*mu2*pI2/(det*det);\n        tensor_product(scalarAB,eye,eye,tangent_piola_isc,1.0);\n\n        scalarAB = -scalarAB;\n        sym_tensor_product(scalarAB,eye,eye,tangent_piola_isc,1.0);\n\n        if (I4_1>1.0){\n            piola_isc += piola_ani1;\n            scalarAB = -(8.0/3.0)*mu4*alpha*(alpha*I4_1-1.0)*exp(beta4*S4_1);\n            tensor_product(scalarAB,dI4_1,L,tangent_piola_isc,1.0);\n            scalarAB = (8.0/3.0)*mu4*alpha*alpha*exp(beta4*S4_1);\n            tensor_product(scalarAB,dI4_1,dI4_1,tangent_piola_isc,1.0);\n            scalarAB = 16.0*mu4*beta4*alpha*alpha*S4_1*exp(beta4*S4_1);\n            tensor_product(scalarAB,dI4_1,dI4_1,tangent_piola_isc,1.0);\n        }\n        if (I4_2>1.0){\n            piola_isc += piola_ani2;\n            scalarAB = -(8.0/3.0)*mu4*alpha*(alpha*I4_2-1.0)*exp(beta4*S4_2);\n            tensor_product(scalarAB,dI4_2,L,tangent_piola_isc,1.0);\n            scalarAB = (8.0/3.0)*mu4*alpha*alpha*exp(beta4*S4_2);\n            tensor_product(scalarAB,dI4_2,dI4_2,tangent_piola_isc,1.0);\n            scalarAB = 16.0*mu4*beta4*alpha*alpha*S4_2*exp(beta4*S4_2);\n            tensor_product(scalarAB,dI4_2,dI4_2,tangent_piola_isc,1.0);\n        }\n\n    }\n\n    void model_A(Epetra_SerialDenseMatrix & deformation_gradient, double & det, Epetra_SerialDenseVector & piola_isc, Epetra_SerialDenseVector & piola_vol, Epetra_SerialDenseMatrix & tangent_piola_isc, Epetra_SerialDenseMatrix & tangent_piola_vol){\n\n        det = deformation_gradient(0,0)*deformation_gradient(1,1)*deformation_gradient(2,2)-deformation_gradient(0,0)*deformation_gradient(1,2)*deformation_gradient(2,1)-deformation_gradient(0,1)*deformation_gradient(1,0)*deformation_gradient(2,2)+deformation_gradient(0,1)*deformation_gradient(1,2)*deformation_gradient(2,0)+deformation_gradient(0,2)*deformation_gradient(1,0)*deformation_gradient(2,1)-deformation_gradient(0,2)*deformation_gradient(1,1)*deformation_gradient(2,0);\n\n        double alpha = std::pow(det,-2.0/3.0);\n\n        Epetra_SerialDenseMatrix rightCauchy(3,3);\n        Epetra_SerialDenseVector M1(6), M2(6);\n        Epetra_SerialDenseVector eye(6);\n        Epetra_SerialDenseVector C(6), L(6), CC(6);\n        Epetra_SerialDenseVector CMMC1(6), CMMC2(6);\n        Epetra_SerialDenseVector D(6);\n        Epetra_SerialDenseVector dK3_1(6), dK3_2(6);\n        Epetra_SerialDenseVector piola_nh(6), piola_ani1(6), piola_ani2(6);\n\n        M1(0) = a(0)*a(0);\n        M1(1) = a(1)*a(1);\n        M1(2) = a(2)*a(2);\n        M1(3) = a(1)*a(2);\n        M1(4) = a(0)*a(2);\n        M1(5) = a(0)*a(1);\n\n        M2(0) = b(0)*b(0);\n        M2(1) = b(1)*b(1);\n        M2(2) = b(2)*b(2);\n        M2(3) = b(1)*b(2);\n        M2(4) = b(0)*b(2);\n        M2(5) = b(0)*b(1);\n\n        rightCauchy.Multiply('T','N',1.0,deformation_gradient,deformation_gradient,0.0);\n\n        eye(0) = 1.0; eye(1) = 1.0; eye(2) = 1.0; eye(3) = 0.0; eye(4) = 0.0; eye(5) = 0.0;\n\n        C(0) = rightCauchy(0,0); C(1) = rightCauchy(1,1); C(2) = rightCauchy(2,2);\n        C(3) = rightCauchy(1,2); C(4) = rightCauchy(0,2); C(5) = rightCauchy(0,1);\n\n        L(0) = (1.0/(det*det))*(rightCauchy(1,1)*rightCauchy(2,2)-rightCauchy(1,2)*rightCauchy(2,1));\n        L(1) = (1.0/(det*det))*(rightCauchy(0,0)*rightCauchy(2,2)-rightCauchy(0,2)*rightCauchy(2,0));\n        L(2) = (1.0/(det*det))*(rightCauchy(0,0)*rightCauchy(1,1)-rightCauchy(0,1)*rightCauchy(1,0));\n        L(3) = (1.0/(det*det))*(rightCauchy(0,2)*rightCauchy(1,0)-rightCauchy(0,0)*rightCauchy(1,2));\n        L(4) = (1.0/(det*det))*(rightCauchy(0,1)*rightCauchy(1,2)-rightCauchy(0,2)*rightCauchy(1,1));\n        L(5) = (1.0/(det*det))*(rightCauchy(0,2)*rightCauchy(2,1)-rightCauchy(0,1)*rightCauchy(2,2));\n\n        CMMC1(0) = 2.0*C(0)*M1(0) + 2.0*C(4)*M1(4) + 2.0*C(5)*M1(5);\n        CMMC1(1) = 2.0*C(1)*M1(1) + 2.0*C(3)*M1(3) + 2.0*C(5)*M1(5);\n        CMMC1(2) = 2.0*C(2)*M1(2) + 2.0*C(3)*M1(3) + 2.0*C(4)*M1(4);\n        CMMC1(3) = C(1)*M1(3) + C(3)*M1(1) + C(2)*M1(3) + C(3)*M1(2) + C(4)*M1(5) + C(5)*M1(4);\n        CMMC1(4) = C(0)*M1(4) + C(4)*M1(0) + C(2)*M1(4) + C(4)*M1(2) + C(3)*M1(5) + C(5)*M1(3);\n        CMMC1(5) = C(0)*M1(5) + C(5)*M1(0) + C(1)*M1(5) + C(5)*M1(1) + C(3)*M1(4) + C(4)*M1(3);\n\n        CMMC2(0) = 2.0*C(0)*M2(0) + 2.0*C(4)*M2(4) + 2.0*C(5)*M2(5);\n        CMMC2(1) = 2.0*C(1)*M2(1) + 2.0*C(3)*M2(3) + 2.0*C(5)*M2(5);\n        CMMC2(2) = 2.0*C(2)*M2(2) + 2.0*C(3)*M2(3) + 2.0*C(4)*M2(4);\n        CMMC2(3) = C(1)*M2(3) + C(3)*M2(1) + C(2)*M2(3) + C(3)*M2(2) + C(4)*M2(5) + C(5)*M2(4);\n        CMMC2(4) = C(0)*M2(4) + C(4)*M2(0) + C(2)*M2(4) + C(4)*M2(2) + C(3)*M2(5) + C(5)*M2(3);\n        CMMC2(5) = C(0)*M2(5) + C(5)*M2(0) + C(1)*M2(5) + C(5)*M2(1) + C(3)*M2(4) + C(4)*M2(3);\n\n        CC(0) = C(0)*C(0) + C(4)*C(4) + C(5)*C(5);\n        CC(1) = C(1)*C(1) + C(3)*C(3) + C(5)*C(5);\n        CC(2) = C(2)*C(2) + C(3)*C(3) + C(4)*C(4);\n        CC(3) = C(1)*C(3) + C(2)*C(3) + C(4)*C(5);\n        CC(4) = C(0)*C(4) + C(2)*C(4) + C(3)*C(5);\n        CC(5) = C(0)*C(5) + C(1)*C(5) + C(3)*C(4);\n\n        double I1 = C(0) + C(1) + C(2);\n        double II1 = C(0)*C(0) + C(1)*C(1) + C(2)*C(2) + 2.0*C(3)*C(3) + 2.0*C(4)*C(4) + 2.0*C(5)*C(5);\n        double I2 = (1.0/2.0)*(I1*I1-II1);\n        double I4_1 = C(0)*M1(0) + C(1)*M1(1) + C(2)*M1(2) + 2.0*C(5)*M1(5) + 2.0*C(4)*M1(4) + 2.0*C(3)*M1(3);\n        double I4_2 = C(0)*M2(0) + C(1)*M2(1) + C(2)*M2(2) + 2.0*C(5)*M2(5) + 2.0*C(4)*M2(4) + 2.0*C(3)*M2(3);\n        double I5_1 = CC(0)*M1(0) + CC(1)*M1(1) + CC(2)*M1(2) + 2.0*CC(5)*M1(5) + 2.0*CC(4)*M1(4) + 2.0*CC(3)*M1(3);\n        double I5_2 = CC(0)*M2(0) + CC(1)*M2(1) + CC(2)*M2(2) + 2.0*CC(5)*M2(5) + 2.0*CC(4)*M2(4) + 2.0*CC(3)*M2(3);\n        double K3_1 = I1*I4_1-I5_1;\n        double K3_2 = I1*I4_2-I5_2;\n        double pI2 = std::sqrt(I2);\n\n        for (unsigned int i=0; i<6; ++i){\n            D(i) = I1*eye(i) - C(i);\n            piola_nh(i) = 2.0*alpha*mu1*(eye(i)-(1.0/3.0)*I1*L(i));\n            piola_isc(i) = piola_nh(i) + (mu2/(det*det))*( 3.0*pI2*D(i) - 2.0*pI2*I2*L(i) );\n\n            dK3_1(i) = I4_1*eye(i) + I1*M1(i) - CMMC1(i);\n            dK3_2(i) = I4_2*eye(i) + I1*M2(i) - CMMC2(i);\n            piola_ani1(i) = 2.0*mu4*beta4*std::pow(K3_1-2.0,beta4-1.0)*dK3_1(i);\n            piola_ani2(i) = 2.0*mu4*beta4*std::pow(K3_2-2.0,beta4-1.0)*dK3_2(i);\n\n            piola_vol(i) = det*L(i);\n        }\n\n        double scalarAB;\n\n        scalarAB = det;\n        tensor_product(det,L,L,tangent_piola_vol,0.0);\n        scalarAB = -2.0*det;\n        sym_tensor_product(scalarAB,L,L,tangent_piola_vol,1.0);\n\n        scalarAB = -2.0/3.0;\n        tensor_product(scalarAB,piola_nh,L,tangent_piola_isc,0.0);\n        tensor_product(scalarAB,L,piola_nh,tangent_piola_isc,1.0);\n\n        scalarAB = -6.0*mu2*pI2/(det*det);\n        tensor_product(scalarAB,D,eye,tangent_piola_isc,1.0);\n        tensor_product(scalarAB,eye,D,tangent_piola_isc,1.0);\n\n        scalarAB = (-4.0/9.0)*mu1*alpha*I1 + 4.0*mu2*pI2*I2/(det*det);\n        tensor_product(scalarAB,L,L,tangent_piola_isc,1.0);\n\n        scalarAB = (4.0/3.0)*mu1*alpha*I1 + 4.0*mu2*pI2*I2/(det*det);\n        sym_tensor_product(scalarAB,L,L,tangent_piola_isc,1.0);\n\n        scalarAB = 3.0*mu2/(det*det*pI2);\n        tensor_product(scalarAB,D,D,tangent_piola_isc,1.0);\n\n        scalarAB = 6.0*mu2*pI2/(det*det);\n        tensor_product(scalarAB,eye,eye,tangent_piola_isc,1.0);\n\n        scalarAB = -scalarAB;\n        sym_tensor_product(scalarAB,eye,eye,tangent_piola_isc,1.0);\n\n        if (K3_1>2.0){\n            piola_isc += piola_ani1;\n            scalarAB = 4.0*mu4*beta4*(beta4-1.0)*std::pow(K3_1-2.0,beta4-2.0);\n            tensor_product(scalarAB,dK3_1,dK3_1,tangent_piola_isc,1.0);\n\n            scalarAB = 4.0*mu4*beta4*std::pow(K3_1-2.0,beta4-1.0);\n            tensor_product(scalarAB,eye,M1,tangent_piola_isc,1.0);\n            tensor_product(scalarAB,M1,eye,tangent_piola_isc,1.0);\n            scalarAB = -scalarAB;\n            sym_tensor_product(scalarAB,M1,eye,tangent_piola_isc,1.0);\n            sym_tensor_product(scalarAB,eye,M1,tangent_piola_isc,1.0);\n        }\n        if (K3_2>2.0){\n            piola_isc += piola_ani2;\n            scalarAB = 4.0*mu4*beta4*(beta4-1.0)*std::pow(K3_2-2.0,beta4-2.0);\n            tensor_product(scalarAB,dK3_2,dK3_2,tangent_piola_isc,1.0);\n\n            scalarAB = 4.0*mu4*beta4*std::pow(K3_2-2.0,beta4-1.0);\n            tensor_product(scalarAB,eye,M2,tangent_piola_isc,1.0);\n            tensor_product(scalarAB,M2,eye,tangent_piola_isc,1.0);\n            scalarAB = -scalarAB;\n            sym_tensor_product(scalarAB,M2,eye,tangent_piola_isc,1.0);\n            sym_tensor_product(scalarAB,eye,M2,tangent_piola_isc,1.0);\n        }\n    }\n\n};\n\n#endif\n", "meta": {"hexsha": "eedfef27a75b327c9da68a2657b8f45e6655cb2c", "size": 41775, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/neumannInnerSurface_StochasticPolyconvexHGO.hpp", "max_stars_repo_name": "bstaber/Trilinos", "max_stars_repo_head_hexsha": "12ada5a678338a1da962113a4fad708f93b19e03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/neumannInnerSurface_StochasticPolyconvexHGO.hpp", "max_issues_repo_name": "bstaber/Trilinos", "max_issues_repo_head_hexsha": "12ada5a678338a1da962113a4fad708f93b19e03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/neumannInnerSurface_StochasticPolyconvexHGO.hpp", "max_forks_repo_name": "bstaber/Trilinos", "max_forks_repo_head_hexsha": "12ada5a678338a1da962113a4fad708f93b19e03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8711063373, "max_line_length": 482, "alphanum_fraction": 0.5614841412, "num_tokens": 15493, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.41821787285005063}}
{"text": "#include \"teca_descriptive_statistics.h\"\n\n#include \"teca_cartesian_mesh.h\"\n#include \"teca_table.h\"\n#include \"teca_array_collection.h\"\n#include \"teca_variant_array.h\"\n#include \"teca_metadata.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <set>\n#include <cmath>\n\n#if defined(TECA_HAS_BOOST)\n#include <boost/program_options.hpp>\n#endif\n\nusing std::string;\nusing std::vector;\nusing std::set;\nusing std::cerr;\nusing std::endl;\n\n//#define TECA_DEBUG\n\nnamespace internal\n{\ntemplate <typename num_t>\nvoid quartiles(const num_t *ptr, size_t n, num_t &lq, num_t &med, num_t &uq)\n{\n    size_t nb = n*sizeof(num_t);\n    num_t *tmp = static_cast<num_t*>(malloc(nb));\n    memcpy(tmp, ptr, nb);\n    size_t n25 = n/4;\n    size_t n50 = n/2;\n    size_t n75 = (n*3)/4;\n    std::partial_sort(tmp, tmp+n75+1, tmp+n);\n    lq = tmp[n25];\n    med = tmp[n50];\n    uq = tmp[n75];\n    free(tmp);\n}\n\ntemplate <typename num_t>\nvoid quartiles2(const num_t *ptr, size_t n, num_t &lq, num_t &med, num_t &uq)\n{\n    size_t nb = n*sizeof(num_t);\n    num_t *tmp = static_cast<num_t*>(malloc(nb));\n    memcpy(tmp, ptr, nb);\n\n    size_t n25 = n/4;\n    std::nth_element(tmp, tmp+n25, tmp+n);\n    lq = tmp[n25];\n\n    size_t n50 = n/2;\n    std::nth_element(tmp, tmp+n50, tmp+n);\n    med = tmp[n50];\n\n    size_t n75 = (n*3)/4;\n    std::nth_element(tmp, tmp+n75, tmp+n);\n    uq = tmp[n75];\n\n    free(tmp);\n}\n\ntemplate <typename num_t>\nnum_t min(const num_t *ptr, size_t n)\n{\n    num_t min = std::numeric_limits<num_t>::max();\n    for (size_t i = 0; i < n; ++i)\n        min = min > ptr[i] ? ptr[i] : min;\n    return min;\n}\n\ntemplate <typename num_t>\nnum_t max(const num_t *ptr, size_t n)\n{\n    num_t max = std::numeric_limits<num_t>::lowest();\n    for (size_t i = 0; i < n; ++i)\n        max = max < ptr[i] ? ptr[i] : max;\n    return max;\n}\n\ntemplate <typename num_t>\nnum_t sum(const num_t *ptr, size_t n)\n{\n    num_t s = num_t();\n    for (size_t i = 0; i < n; ++i)\n        s += ptr[i];\n    return s;\n}\n\ntemplate <typename num_t>\nnum_t var(const num_t *ptr, size_t n, num_t av)\n{\n    if (!n) return num_t();\n    num_t v = num_t();\n    for (size_t i = 0; i < n; ++i)\n    {\n        num_t d = ptr[i] - av;\n        v += d*d;\n    }\n    v /= num_t(n);\n    return v;\n}\n};\n\n\n// --------------------------------------------------------------------------\nteca_descriptive_statistics::teca_descriptive_statistics()\n{\n    this->set_number_of_input_connections(1);\n    this->set_number_of_output_ports(1);\n}\n\n// --------------------------------------------------------------------------\nteca_descriptive_statistics::~teca_descriptive_statistics()\n{}\n\n#if defined(TECA_HAS_BOOST)\n// --------------------------------------------------------------------------\nvoid teca_descriptive_statistics::get_properties_description(\n    const string &prefix, options_description &global_opts)\n{\n    options_description opts(\"Options for \"\n        + (prefix.empty()?\"teca_descriptive_statistics\":prefix));\n\n    opts.add_options()\n        TECA_POPTS_GET(std::vector<std::string>, prefix, dependent_variables,\n            \"list of arrays to compute statistics for\")\n        ;\n\n    global_opts.add(opts);\n}\n\n// --------------------------------------------------------------------------\nvoid teca_descriptive_statistics::set_properties(\n    const string &prefix, variables_map &opts)\n{\n    TECA_POPTS_SET(opts, std::vector<std::string>, prefix, dependent_variables)\n}\n#endif\n\n// --------------------------------------------------------------------------\nvoid teca_descriptive_statistics::get_dependent_variables(\n    const teca_metadata &request, std::vector<std::string> &dep_vars)\n{\n    dep_vars = this->dependent_variables;\n\n    if (dep_vars.empty())\n    {\n        std::string key = \"teca_descriptive_statistics::dependent_variables\";\n        if (request.has(key))\n            request.get(key, dep_vars);\n    }\n}\n\n// --------------------------------------------------------------------------\nstd::vector<teca_metadata>\nteca_descriptive_statistics::get_upstream_request(\n    unsigned int port, const std::vector<teca_metadata> &input_md,\n    const teca_metadata &request)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id()\n        << \"teca_descriptive_statistics::get_upstream_request\" << endl;\n#endif\n    (void)port;\n    (void)input_md;\n\n    vector<teca_metadata> up_reqs;\n\n    // copy the incoming request to preserve the downstream\n    // requirements and add the arrays we need\n    teca_metadata req(request);\n\n    std::set<std::string> arrays;\n    if (req.has(\"arrays\"))\n        req.get(\"arrays\", arrays);\n\n    // intercept request for our output\n    //arrays.erase(this->get_derived_variable(request));\n\n    // get the names of the arrays we need to request\n    std::vector<std::string> dep_vars;\n    this->get_dependent_variables(req, dep_vars);\n\n    size_t n = dependent_variables.size();\n    for (size_t i = 0; i < n; ++i)\n        arrays.insert(dep_vars[i]);\n\n    req.set(\"arrays\", arrays);\n    up_reqs.push_back(req);\n\n    return up_reqs;\n}\n\n\n// --------------------------------------------------------------------------\nconst_p_teca_dataset teca_descriptive_statistics::execute(\n    unsigned int port,\n    const std::vector<const_p_teca_dataset> &input_data,\n    const teca_metadata &request)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id() << \"teca_descriptive_statistics::execute\" << endl;\n#endif\n    (void)port;\n\n    // get the input mesh\n    const_p_teca_cartesian_mesh in_mesh\n        = std::dynamic_pointer_cast<const teca_cartesian_mesh>(input_data[0]);\n\n    if (!in_mesh)\n    {\n        TECA_ERROR(\"dataset is not a teca_cartesian_mesh\")\n        return nullptr;\n    }\n\n    // set up the output\n    p_teca_table table = teca_table::New();\n    table->declare_columns(\"step\", long(), \"time\", double());\n\n    std::string calendar;\n    in_mesh->get_calendar(calendar);\n    table->set_calendar(calendar);\n\n    std::string time_units;\n    in_mesh->get_time_units(time_units);\n    table->set_time_units(time_units);\n\n    unsigned long step;\n    in_mesh->get_time_step(step);\n    table << step;\n\n    double time;\n    in_mesh->get_time(time);\n    table << time;\n\n    // dependent variables\n    std::vector<std::string> dep_var_names;\n    this->get_dependent_variables(request, dep_var_names);\n\n    // for each variable\n    size_t n_dep_vars = dep_var_names.size();\n    for (size_t i = 0; i < n_dep_vars; ++i)\n    {\n        const std::string &dep_var_name = dep_var_names[i];\n\n        // get the array\n        const_p_teca_variant_array dep_var\n            = in_mesh->get_point_arrays()->get(dep_var_name);\n        if (!dep_var)\n        {\n            TECA_ERROR(\"dependent variable \" << i << \" \\\"\"\n                << dep_var_name << \"\\\" not present.\")\n            return nullptr;\n        }\n\n        TEMPLATE_DISPATCH(const teca_variant_array_impl,\n            dep_var.get(),\n\n            size_t n = dep_var->size();\n            const NT *pv = static_cast<const TT*>(dep_var.get())->get();\n\n            // compute stats\n            NT mn = internal::min(pv, n);\n            NT mx = internal::max(pv, n);\n            NT av = internal::sum(pv, n)/NT(n);\n            NT vr = internal::var(pv, n, av);\n            NT lq; NT med; NT uq;\n            internal::quartiles2(pv, n, lq, med, uq);\n\n            // add to output table\n            table->declare_columns(\n                \"min \" + dep_var_name, NT(), \"max \" + dep_var_name, NT(),\n                \"avg \" + dep_var_name, NT(), \"var \" + dep_var_name, NT(),\n                \"low_q \" + dep_var_name, NT(), \"med \" + dep_var_name, NT(),\n                \"up_q \" + dep_var_name, NT());\n\n            table << mn << mx << av << vr << lq << med << uq;\n            )\n    }\n\n    return table;\n}\n", "meta": {"hexsha": "80482ba1ad28bbf0d951484cbc71d7e406631d61", "size": 7692, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "alg/teca_descriptive_statistics.cxx", "max_stars_repo_name": "mhaseeb123/TECA", "max_stars_repo_head_hexsha": "4233bac9dd2a86da3848ae088b462b4544b3ddc7", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "alg/teca_descriptive_statistics.cxx", "max_issues_repo_name": "mhaseeb123/TECA", "max_issues_repo_head_hexsha": "4233bac9dd2a86da3848ae088b462b4544b3ddc7", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "alg/teca_descriptive_statistics.cxx", "max_forks_repo_name": "mhaseeb123/TECA", "max_forks_repo_head_hexsha": "4233bac9dd2a86da3848ae088b462b4544b3ddc7", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7083333333, "max_line_length": 81, "alphanum_fraction": 0.5822932917, "num_tokens": 1950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.6757646010190476, "lm_q1q2_score": 0.418149912927306}}
{"text": "#ifndef CPP_OCTREE_HPP\n#define CPP_OCTREE_HPP\n\n#include <vector>\n#include <bitset>\n\n#include <algorithm>\n\n#include <iostream>\n\n#include <Eigen/Core>\n\n\nnamespace detail {\n\n  // a fast linear (morton) octree\n  template<class T>\n  struct cell {\n\n    static constexpr std::size_t brute_force_threshold = 256;\n  \n    static constexpr std::size_t max_level = (8 * sizeof(T)) / 3;\n    using coord = std::bitset<max_level>;\n  \n    static constexpr T resolution() { return 1ul << max_level; }\n\n    static constexpr std::size_t size = 3 * max_level;\n    using bits_type = std::bitset<size>;\n    bits_type bits;\n\n    explicit cell(const bits_type& bits={}) noexcept : bits(bits) { }\n    \n    // decode a cell code as individual coordinate codes\n    template<class Func>\n    void decode(Func&& func) const {\n      coord x, y, z;\n\n      auto value = bits.to_ulong();\n      for(std::size_t i = 0; i < max_level; ++i) {\n        x[i] = value & 4;\n        y[i] = value & 2;\n        z[i] = value & 1;\n\n        value >>= 3;\n      }\n\n      func(x, y, z);\n    }\n\n    // encode cell from x y z codes\n    static cell encode(const coord& x, const coord& y, const coord& z) {\n      T value = 0;\n      for(std::size_t i = 0; i < max_level; ++i) {\n        const std::size_t j = max_level - 1 - i;\n        value <<= 3;\n\n        value |= x[j] * 4 + y[j] * 2 + z[j] * 1;\n      }\n\n      return cell(value);\n    }\n\n\n    // encode a cell at a given level\n    static cell encode(bool x, bool y, bool z, std::size_t level) {\n      bits_type result = 0;\n      result[2] = x;\n      result[1] = y;\n      result[0] = z;\n    \n      return cell(result << (3 * level));\n    }\n  \n\n    // generate possible delta (-1, 0, 1) for a cell given maximum value\n    template<class Func>\n    static void iter_delta(T c, T max, const Func& func) {\n      if(c) func(-1);\n      func(0);\n      if(c < max) func(1);\n    }\n  \n\n    // iterate cell neighbors at given level (cell must be admissible at this\n    // level i.e. zero lower-order bits)\n    template<class Func>\n    void neighbors(std::size_t level, Func&& func) const {\n      const T max = 1ul << (max_level - level);\n    \n      decode([&](coord x, coord y, coord z) {\n          const auto cx = (x >> level).to_ulong();\n          const auto cy = (y >> level).to_ulong();\n          const auto cz = (z >> level).to_ulong();\n\n          iter_delta(cx, max, [&](int dx) {\n              const auto rx = (cx + dx) << level;\n              const auto ax = std::abs(dx);\n                        \n              iter_delta(cy, max, [&](int dy) {\n                  const auto ry = (cy + dy) << level;\n                  const auto ay = std::abs(dy);\n                                \n                  iter_delta(cz, max, [&](int dz) {\n                      const auto rz = (cz + dz) << level;\n                      const auto az = std::abs(dz);\n                      if(ax + ay + az) {\n                        func(rx, ry, rz);\n                      }\n                    });\n                });\n            });\n        });\n    }\n\n\n    template<class Func>\n    void children(std::size_t level, const Func& func) const noexcept {\n      const T first = bits.to_ulong();\n      const T incr = 1ul << (3 * level);\n      const T last = first + (incr << 3);\n\n      for(T value = first, next; value != last; value = next) {\n        next = value + incr;\n        func(cell(value), cell(next - 1));\n      }\n    }\n    \n    // debugging\n    friend std::ostream& operator<<(std::ostream& out, const cell& self) {\n      self.decode([&](coord x, coord y, coord z) {\n          out << \"(\" << x << \", \" << y << \", \" << z << \")\";\n        });\n      return out;\n    }\n    \n  };\n\n\n  template<class T>\n  using coord = typename cell<T>::coord;\n\n  // a fixed-size (dynamically chosen) sorted array\n  template<class Key, class Value>\n  class sorted_array {\n    \n    struct item_type {\n      Key key;\n      Value value;\n    \n      bool operator<(const item_type& other) const { return key < other.key; }\n    \n      friend bool operator<(const item_type& self, const Key& key) { return self.key < key; }\n      friend bool operator<(const Key& key, const item_type& self) { return key < self.key; }    \n    };\n  \n    std::vector<item_type> items;\n  public:\n    sorted_array(std::size_t size, const Key& key = {}, const Value& value = {})\n      : items(size, item_type{key, value}) { };\n\n    std::size_t size() const { return items.size(); }\n  \n    void insert(const Key& key, const Value& value) {\n      items.pop_back();\n\n      auto it = std::upper_bound(items.begin(), items.end(), key);\n      items.emplace(it, key, value);\n    }\n\n    auto begin() const -> decltype(items.begin()) { return items.begin(); }\n    auto end() const -> decltype(items.begin()) { return items.begin(); }\n\n    auto back() const -> decltype(items.back()) { return items.back(); }    \n  };\n\n\n  // brute force 1-nn\n  template<class Real, class Distance, class Iterator>\n  static Iterator find_nearest(const Distance& distance, Real& best, Iterator first, Iterator last) noexcept {\n    Iterator res = last;\n\n    for(Iterator it = first; it != last; ++it) {\n      const Real d = distance(*it);\n      if(d < best) {\n        best = d;\n        res = it;\n      }\n    }\n    \n    return res;\n  }\n\n\n  // brute force k-nn\n  template<class Real, class Distance, class Iterator>\n  static void find_nearest(sorted_array<Real, Iterator>& result, const Distance& distance,\n                           Iterator first, Iterator last) noexcept {\n    for(Iterator it = first; it != last; ++it) {\n      const Real d = distance(*it);\n      if(d < result.back().key) {\n        result.insert(d, it);\n      }\n    }\n  }\n\n\n\n  // octree based 1-nn\n  template<class Real, class Distance, class Iterator, class T>\n  static Iterator find_nearest(const Distance& distance, Real& best, Iterator first, Iterator last,\n                               const cell<T>& origin, std::size_t level = cell<T>::max_level) noexcept {\n    const std::size_t size = last - first;\n  \n    // base case\n    if(size <= cell<T>::brute_force_threshold || !level) {\n      return find_nearest(distance, best, first, last);\n    }\n\n    // recursive case\n    struct chunk_type {\n      Real d;\n      cell<T> c;\n      Iterator begin, end;\n    \n      inline bool operator<(const chunk_type& other) const { return d < other.d; }\n    };\n\n    const std::size_t next_level = level - 1;\n    \n    chunk_type chunks[8];\n    std::size_t non_empty = 0;\n\n    origin.children(next_level, [&](cell<T> lower, cell<T> upper) noexcept {\n        assert(upper.bits.to_ulong() > lower.bits.to_ulong());\n\n        // find range for lower/upper cell corners\n        const Iterator begin = std::lower_bound(first, last, lower);\n        if(begin == last) return; // no point found in subcell\n            \n        const Iterator end = std::upper_bound(begin, last, upper);\n\n        assert(end >= begin);\n        chunks[non_empty++] = {distance(lower, next_level), lower, begin, end};\n      });\n\n    // paranoid sanity checks\n    assert(non_empty <= 8);\n    assert(chunks[0].begin == first);\n    assert(chunks[count - 1].end == last);    \n\n    // order non-empty subcells by distance\n    std::sort(chunks, chunks + non_empty);\n\n    Iterator result = last;\n    for(auto it = chunks, end = chunks + non_empty; it != end; ++it) {\n      if(it->d < best) {\n        const Real old_best = best;\n        const Iterator sub = find_nearest(distance, best, it->begin, it->end, it->c, next_level);\n        \n        if(best < old_best) {\n          result = sub;\n        }\n      }\n    }\n\n    return result;\n  };\n\n\n  // // octree based k-nn\n  // template<class Real, class Distance, class Iterator, class T>\n  // static void find_nearest(sorted_array<Real, Iterator>& result, const Distance& distance,\n  //                          Iterator first, Iterator last,\n  //                          const cell<T>& origin, std::size_t level = cell<T>::max_level) noexcept {\n  //     // range size\n  //     const std::size_t size = last - first;\n  \n  //     // base case\n  //     if( (level == 0) || size <= cell<T>::brute_force_threshold) {\n  //         find_nearest(result, distance, first, last);\n  //     }\n  \n  //     // recursive case: split cell\n  //     const std::size_t next_level = level - 1;\n\n  //     // subcell info TODO rename\n  //     struct chunk_type {\n  //         Real d;\n  //         cell<T> c;\n  //         Iterator begin, end;\n    \n  //         bool operator<(const chunk_type& other) const { return d < other.d; }\n  //     };\n\n  //     chunk_type chunks[8];\n  //     std::size_t count = 0;\n\n  //     // obtain subcell info, skip if empty\n  //     for(cell<T> c : typename cell<T>::children(origin, next_level)) {\n  //         const Iterator begin = std::lower_bound(first, last, c);\n  //         if(begin == last) continue; // no point found in subcell\n\n  //         // note: we want upper bound since we may have duplicate cells in the\n  //         // range (e.g. many points in same leafs)\n  //         const Iterator end = std::lower_bound(begin, last, c.next(next_level));\n    \n  //         chunks[count] = {distance(c, next_level), c, begin, end};\n  //         ++count; \n  //     }\n\n  //     assert(count <= 8);\n\n  //     // process subcells by distance to query point\n  //     std::sort(chunks, chunks + count);\n  \n  //     for(auto it = chunks, end = chunks + count; it != end; ++it) {\n  //         // don't visit subcell if our furthest guess is closer than the subcell\n  //         if(it->d < result.back().key) {\n  //             find_nearest(result, distance, it->begin, it->end, it->c, next_level);\n  //         }\n  //     }\n\n  //     return result;\n  // };\n\n}\n\n}\n\ntemplate<class Real=double, class T=unsigned long>\nclass octree {\n  struct item; \n    \n  using data_type = std::vector<item>;\n  data_type data;\n\npublic:\n  struct distance;\n    \n  // TODO use traits\n  using real = Real;\n  using vec3 = Eigen::Matrix<real, 3, 1>;\n    \n\n  using cell = detail::cell<T>;\n  using coord = detail::coord<T>;\n    \n  // preallocate octree data\n  void reserve(std::size_t count) { data.reserve(count); }\n\n  // clear octree data\n  void clear() { data.clear(); }\n\n  // number of octree cells\n  std::size_t size() const { return data.size(); }\n  \n  static cell hash(const vec3& p) {\n    auto s = (p * cell::resolution()).template cast<T>();\n    return cell::encode(s.x(), s.y(), s.z());\n  }\n\n  static vec3 origin(const cell& c) {\n    vec3 res;\n    c.decode([&](const coord& x, const coord& y, const coord& z) {\n        res = {x.to_ulong(), y.to_ulong(), z.to_ulong()};\n      });\n        \n    return res / cell::resolution();\n  }\n  \n\n  // append a point to the octree\n  void add(const vec3* p) {\n    data.push_back({hash(*p), p});\n  }\n\n  // sort octree cells\n  void sort() { std::sort(data.begin(), data.end()); }\n    \n  // nearest-neighbor search\n  const vec3* nearest(const vec3& query) const {\n    if(data.empty()) return nullptr;\n        \n    real best = std::numeric_limits<real>::max();\n    auto it = find_nearest(distance{query}, best, data.begin(), data.end(), cell(0));\n    assert(it != data.end());\n        \n    return it->p;\n  }\n\n  // template<class OutputIterator>\n  // void nearest(OutputIterator out, const vec3& query, std::size_t count = 1) const {\n  //     assert(count >= data.size());\n        \n  //     using iterator = typename data_type::iterator;\n    \n  //     detail::sorted_array<real, iterator> knn(count, std::numeric_limits<real>::max());\n  //     find_nearest(knn, distance{query}, data.begin(), data.end(), cell(0));\n\n  //     for(auto& it : knn) {\n  //         *out++ = it.value.p;\n  //     }\n  // }\n  \n  \n};\n\ntemplate<class Real, class T>\nstruct octree<Real, T>::item {\n  cell c;\n  const vec3* p;\n\n  friend inline bool operator<(const T& c, const item& self) {\n    return c < self.c.bits.to_ulong();\n  }\n\n  friend inline bool operator<(const item& self, const T& c) {\n    return self.c.bits.to_ulong() < c;\n  }\n\n  friend inline bool operator<(const cell& c, const item& self) {\n    return c.bits.to_ulong() < self.c.bits.to_ulong();\n  }\n\n  friend inline bool operator<(const item& self, const cell& c) {\n    return self.c.bits.to_ulong() < c.bits.to_ulong();\n  }\n\n  \n  friend inline bool operator<(const item& lhs, const item& rhs) {\n    return lhs.c.bits.to_ulong() < rhs.c.bits.to_ulong();\n  }\n};\n\n\ntemplate<class Real, class T>\nstruct octree<Real, T>::distance {\n  const vec3 query;\n  const vec3 scaled_query;\n\n  // mutable std::size_t point_count = 0, box_count = 0;\n\n  // ~distance() {\n  //   std::clog << \" point distances: \" << point_count\n  //             << \" box distances: \" << box_count << std::endl;\n  // }\n    \n  distance(const vec3& query)\n    : query(query),\n      scaled_query(query * cell::resolution()) { }\n    \n  // distance to point\n  real operator()(const vec3& p) const noexcept {\n    // ++point_count;\n    return (query - p).squaredNorm();\n  }\n\n  real operator()(const item& i) const noexcept {\n    return operator()(*i.p);\n  }\n\n\n  // compute scaled_query - proj(scaled_query) onto cell c at given level    \n  vec3 project(const cell& c, std::size_t level) const {\n    vec3 res;\n    c.decode([&](coord sx, coord sy, coord sz) {\n        const vec3 low{sx.to_ulong(), sy.to_ulong(), sz.to_ulong()};\n        const vec3 local = scaled_query - low;\n        res = local.array() - local.array().min(1ul << level).max(0);\n      });\n    return res;\n  }\n\n  // distance to cell\n  real operator()(const cell& c, std::size_t level) const noexcept {\n    // ++box_count;\n    constexpr real factor = 1.0 / (cell::resolution() * cell::resolution());\n    return project(c, level).squaredNorm() * factor;\n  }\n};\n\n\n#endif\n", "meta": {"hexsha": "9921f9a79d8f0772b803875ace2138004814494e", "size": 13600, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "octree.hpp", "max_stars_repo_name": "maxime-tournier/cpp", "max_stars_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "octree.hpp", "max_issues_repo_name": "maxime-tournier/cpp", "max_issues_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "octree.hpp", "max_forks_repo_name": "maxime-tournier/cpp", "max_forks_repo_head_hexsha": "303def38a523f0e5699ef389182974f4f50d10fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0991735537, "max_line_length": 110, "alphanum_fraction": 0.5622058824, "num_tokens": 3556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.41779159065203125}}
{"text": "#if HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n#include <math.h>\n#include <iostream>\n#include <vector>\n#include <map>\n#include <string>\n#include <iomanip>\n#include <tuple>\n\n#include <dune/common/array.hh>\n#include <dune/common/exceptions.hh>\n#include <dune/common/fvector.hh>\n#include <dune/common/parallel/mpihelper.hh>\n#include <dune/common/parametertree.hh>\n#include <dune/common/parametertreeparser.hh>\n\n#include <dune/grid/common/mcmgmapper.hh>\n\n#pragma GCC diagnostic push\n#ifdef __clang__\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#endif\n#include <dune/grid/io/file/vtk/subsamplingvtkwriter.hh>\n#pragma GCC diagnostic pop\n\n#include <dune/grid/spgrid.hh>\n#pragma GCC diagnostic push\n#ifdef __clang__\n#pragma GCC diagnostic ignored \"-Wnew-returns-null\"\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#endif\n#include <dune/grid/alugrid.hh>\n#pragma GCC diagnostic pop\n\n\n\n\n#include <boost/get_pointer.hpp>\n\n// the following is needed for clang\n#if defined( BOOST_NO_CXX11_SMART_PTR )\n\nnamespace boost {\n       template<typename T>\n       T *get_pointer(std::shared_ptr<T> p)\n       {\n               return p.get();\n       }\n}\n\n#endif\n\nconst int DIM = 3;\nbool rank0;\n\n\n#include \"coefficients.hh\"\n#include \"vector.hh\"\n#include \"operator.hh\"\n#include \"subgrid.hh\"\n#include \"measure.hh\"\n\n\n#ifdef AS_LIB\n#include <boost/python.hpp>\n#include <boost/python/stl_iterator.hpp>\n#endif\n\n\n\nclass Discretization\n{\npublic:\n  typedef Dune::SPGrid<double, DIM> G;\n  typedef G::LeafGridView GV;\n  static const int dim = GV::dimension;\n  typedef GV::Grid::ctype Coord;\n\n  typedef SpaceOperator<GV> OP;\n  typedef Dune::MultipleCodimMultipleGeomTypeMapper<GV, Dune::MCMGElementLayout> Mapper;\n\n  // Restricted operator types\n  typedef Dune::ALUGrid<GV::dimension, GV::dimensionworld, Dune::cube, Dune::nonconforming, Dune::No_Comm> RG;\n  typedef typename RG::LeafGridView RGV;\n  typedef SpaceOperator<RGV, std::shared_ptr<RG> > ROP;\n\n  std::shared_ptr<G> g;\n  std::shared_ptr<GV> gv;\n  std::shared_ptr<Coefficients<DIM> > coefficients;\n  std::shared_ptr<OP> go;\n  std::shared_ptr<Mapper> mapper;\n  double T;\n  int nt;\n  bool doVisualize;\n\n  Discretization(const std::string paramFile)\n  {\n    // Instatiate grid\n    typedef typename G::Traits::Domain Domain;\n    typedef typename Domain::Cube Cube;\n    typedef typename Domain::Topology Topology;\n\n    Dune::ParameterTree pt;\n    Dune::ParameterTreeParser::readINITree(paramFile, pt);\n\n    Dune::FieldVector<double, DIM> O(0.);\n    Dune::FieldVector<double, DIM> L(-1.);\n    Dune::array<int,DIM> N;\n\n    auto spt = pt.sub(\"geometry.size\");\n    for (int i = 0; i < DIM; i++) {\n      L[i] = spt.get(std::to_string(i), -1.);\n      assert(L[i] > 0);\n    }\n\n    spt = pt.sub(\"grid.intervals\");\n    for (int i = 0; i < DIM; i++) {\n      N[i] = spt.get(std::to_string(i), -1);\n      assert(N[i] > 0);\n    }\n\n    Cube cube(O, L);\n    std::vector<Cube> cubes(1);\n    cubes[0] = cube;\n    int periodic = 0;\n    for (int i = 0; i < DIM; i++) {\n      periodic += (1 << i);\n    }\n    Domain domain(cubes, (Topology) periodic);\n\n    Dune::array<int,DIM> overlap;\n    for (int i = 0; i < DIM; i++) {\n      overlap[i] = 1;\n    }\n\n    if (rank0) std::cout << \"Instantiating grid:  \" << std::flush;\n    g = std::make_shared<G>(domain, N, overlap);\n    if (rank0) std::cout << \"done\" << std::endl;\n\n    gv = std::make_shared<GV>(g->leafView());\n    coefficients = std::make_shared<Coefficients<DIM> >(pt);\n    go = std::make_shared<OP>(gv, coefficients);\n    mapper = std::make_shared<Mapper>(*gv);\n\n    T = pt.get(\"timestepping.end\", -1e99);\n    assert(T > 0);\n    nt = pt.get(\"timestepping.nt\", -1);\n    assert(nt > 0);\n    int vis = pt.get(\"timestepping.visualize\", -1);\n    assert(0 <= vis <= 1);\n    doVisualize = vis;\n  }\n\n  void initialProjection(Vector& u)\n  {\n    auto iend = gv->template end<0>();\n    for (auto it = gv->template begin<0>(); it != iend; ++it) {\n      int ind = mapper->map(*it);\n      auto x = it->geometry().center();\n      double y = 1.;\n      for (int i = 0; i < GV::dimension; i++) {\n        y *= sin(2 * M_PI * x[i]);\n      }\n      y = 0.5 * (y + 1.);\n      u[ind] = y;      \n    }\n  }\n\n  void visualize(Vector& u, const std::string& filename)\n  {\n    Dune::VTKWriter<GV> vtkwriter(*gv);\n    vtkwriter.addCellData(u, \"solution\");\n    vtkwriter.write(filename, Dune::VTK::appendedraw);\n  }\n\n  std::string filename(int step)\n  {\n    std::ostringstream s;\n    s << \"burgers-\" << std::setfill('0') << std::setw(5) << step;\n    return s.str();\n  }\n\n  void solve()\n  {\n    if (rank0) std::cout << \"Computing initial values:  \" << std::flush;\n    Vector u(mapper->size(), 0.);\n    initialProjection(u);\n    if (doVisualize) visualize(u, filename(0));\n    if (rank0) std::cout << \"done\" << std::endl;\n\n    double dt = T / nt;\n    Vector utmp(mapper->size(), 0.);\n\n    for(int t = 0; t < nt; t++) {\n      if (rank0) std::cout << \"\\rComputing time steps:  \" << std::setw(3) << t << std::setw(0) << \"/\" << nt << \" \" << std::flush;\n      go->apply(u, utmp, coefficients->exponent, -dt);\n      u += utmp;\n      utmp = 0.;\n      if (doVisualize) visualize(u, filename(t+1));\n    }\n\n    if (rank0) std::cout << \"\\rComputing time steps:  done       \" << std::endl;\n  }\n\n  std::tuple<double, std::vector<double>, std::vector<int> >\n    getSubgridData(const std::vector<int>& dofs, int offset)\n  {\n    return ::getSubgridData<DIM, GV, Mapper>(*gv, *mapper, dofs, offset);\n  }\n\n\n  std::tuple< std::shared_ptr<ROP>, std::vector<int>, std::vector<int> >\n    makeRestrictedSpaceOperator(double diameter, const std::vector<double>& centers, const std::vector<int>& sourceDofs)\n  {\n    auto retval = makeSubgrid<DIM>(diameter, centers, sourceDofs);\n\n    auto subgrid = std::get<0>(retval);\n    auto rgv = std::make_shared<RGV>(subgrid->leafView());\n    auto rgo = std::make_shared<ROP>(rgv, coefficients, subgrid);\n\n    return std::make_tuple(rgo,\n                           std::move(std::get<1>(retval)),\n                           std::move(std::get<2>(retval)));\n  }\n\n  std::size_t dimSolution()\n  {\n    return mapper->size();\n  }\n\n#ifdef AS_LIB\n\n\n  template<typename T> std::vector<T> toStdVector(const boost::python::object& iterable)\n  {\n      return std::vector<T>(boost::python::stl_input_iterator<T>(iterable),\n                            boost::python::stl_input_iterator<T>());\n  }\n\n  template <class T> boost::python::list toPythonList(const std::vector<T>& vector) {\n      typename std::vector<T>::iterator iter;\n      boost::python::list list;\n      for (const T& item: vector) {\n          list.append(item);\n      }\n      return list;\n  }\n\n  boost::python::object getSubgridDataWrapper(const boost::python::list& dofs, int offset)\n  {\n    auto dofVec = toStdVector<int>(dofs);\n    auto retval = getSubgridData(dofVec, offset);\n    return boost::python::make_tuple(std::get<0>(retval),\n                                     toPythonList<double>(std::get<1>(retval)),\n                                     toPythonList<int>(std::get<2>(retval)));\n  }\n\n  boost::python::object makeRestrictedSpaceOperatorWrapper(const double diameter,\n                                                           const boost::python::list& centers,\n                                                           const::boost::python::list& sourceDofs)\n  {\n    auto centersVec = toStdVector<double>(centers);\n    auto sourceDofsVec = toStdVector<int>(sourceDofs);\n    auto retval = makeRestrictedSpaceOperator(diameter, centersVec, sourceDofsVec);\n    return boost::python::make_tuple(std::get<0>(retval),\n                                     toPythonList<int>(std::get<1>(retval)),\n                                     toPythonList<int>(std::get<2>(retval)));\n  }\n\n\n  static void export_()\n  {\n    using boost::python::class_;\n    using boost::python::init;\n    using boost::python::make_getter;\n    using boost::python::return_value_policy;\n    using boost::python::return_by_value;\n\n    class_<Discretization, boost::noncopyable>(\"Discretization\", init<std::string>())\n        .def(\"solve\", &Discretization::solve)\n        .def(\"getSubgridData\", &Discretization::getSubgridDataWrapper)\n        .def(\"makeRestrictedSpaceOperator\", &Discretization::makeRestrictedSpaceOperatorWrapper)\n        .def(\"visualize\", &Discretization::visualize)\n        .def(\"initialProjection\", &Discretization::initialProjection)\n        .def_readonly(\"T\", &Discretization::T)\n        .def_readonly(\"nt\", &Discretization::nt)\n        .add_property(\"go\", make_getter(&Discretization::go, return_value_policy<return_by_value>()))\n        .add_property(\"dimSolution\", &Discretization::dimSolution)\n    ;\n  }\n#endif\n\n};\n\n\n#ifdef AS_LIB\n\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\nusing boost::python::class_;\nusing boost::python::def;\nusing boost::python::extract;\nusing boost::python::incref;\nusing boost::python::register_exception_translator;\nusing boost::python::to_python_converter;\nusing boost::python::vector_indexing_suite;\n\nvoid exceptionTranslator(Dune::Exception const& x)\n{\n  PyErr_SetString(PyExc_UserWarning, x.what().c_str());\n}\n\nBOOST_PYTHON_MODULE(libdune_burgers)\n{\n  register_exception_translator<Dune::Exception>(exceptionTranslator);\n\n  class_<std::vector<int>, std::shared_ptr<std::vector<int> > >(\"std_vector_int\")\n      .def(vector_indexing_suite<std::vector<int> >());\n\n  Vector::export_();\n  Discretization::OP::export_(\"SpaceOperator\");\n  Discretization::ROP::export_(\"RestrictedSpaceOperator\");\n  Discretization::export_();\n\n}\n\n#else\n\nint main(int argc, char** argv)\n{\n  auto& helper = Dune::MPIHelper::instance(argc, argv);\n  rank0 = (helper.rank() == 0);\n\n  if (argc!=2) {\n    if (rank0) std::cout << \"usage: ./burgers <parameter file>\" << std::endl;\n    return 1;\n  }\n\n  try{\n    Discretization discretization(argv[1]);\n    auto timeNeeded = measure<>::execution([&]{discretization.solve();});\n    std::cout << \"Time needed for solve: \" << timeNeeded << std::endl;\n  }\n  catch (Dune::Exception &e){\n    std::cerr << \"Dune reported error: \" << e << std::endl;\n  return 1;\n  }\n  catch (...){\n    std::cerr << \"Unknown exception thrown!\" << std::endl;\n  return 1;\n  }\n}\n\n#endif\n", "meta": {"hexsha": "4a4ae1e5fb9fd686e0afe7134835e026ca245b51", "size": 10140, "ext": "cc", "lang": "C++", "max_stars_repo_path": "dune-burgers/src/dune_burgers.cc", "max_stars_repo_name": "pymor/dune-burgers-demo", "max_stars_repo_head_hexsha": "a9c86c685964b6fe38ce238381afec05b22e057f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dune-burgers/src/dune_burgers.cc", "max_issues_repo_name": "pymor/dune-burgers-demo", "max_issues_repo_head_hexsha": "a9c86c685964b6fe38ce238381afec05b22e057f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dune-burgers/src/dune_burgers.cc", "max_forks_repo_name": "pymor/dune-burgers-demo", "max_forks_repo_head_hexsha": "a9c86c685964b6fe38ce238381afec05b22e057f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4033613445, "max_line_length": 129, "alphanum_fraction": 0.6301775148, "num_tokens": 2783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4177915842563189}}
{"text": "/* Author: Wolfgang Bangerth and Ralf Hartmann, University of Heidelberg, 2000 */\n\n/*    $Id: step-7.cc 27657 2012-11-21 13:19:08Z bangerth $       */\n/*                                                                */\n/*    Copyright (C) 2000-2004, 2006-2009, 2011-2012 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n// @sect3{Include files}\n\n// These first include files have all been treated in previous examples, so we\n// won't explain what is in them again.\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/data_out.h>\n\n// In this example, we will not use the numeration scheme which is used per\n// default by the DoFHandler class, but will renumber them using the\n// Cuthill-McKee algorithm. As has already been explained in step-2, the\n// necessary functions are declared in the following file:\n#include <deal.II/dofs/dof_renumbering.h>\n// Then we will show a little trick how we can make sure that objects are not\n// deleted while they are still in use. For this purpose, deal.II has the\n// SmartPointer helper class, which is declared in this file:\n#include <deal.II/base/smartpointer.h>\n// Next, we will want to use the function VectorTools::integrate_difference()\n// mentioned in the introduction, and we are going to use a ConvergenceTable\n// that collects all important data during a run and prints it at the end as a\n// table. These comes from the following two files:\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/base/convergence_table.h>\n// And finally, we need to use the FEFaceValues class, which is declared in\n// the same file as the FEValues class:\n#include <deal.II/fe/fe_values.h>\n\n// We need one more include from standard C++, which is necessary when we try\n// to find out the actual type behind a pointer to a base class. We will\n// explain this in slightly more detail below. The other two include files are\n// obvious then:\n#include <typeinfo>\n#include <fstream>\n#include <iostream>\n\n// The last step before we go on with the actual implementation is to open a\n// namespace <code>Step7</code> into which we will put everything, as\n// discussed at the end of the introduction, and to import the members of\n// namespace <code>dealii</code> into it:\nnamespace Step7\n{\n  using namespace dealii;\n\n  // @sect3{Equation data}\n\n  // Before implementing the classes that actually solve something, we first\n  // declare and define some function classes that represent right hand side\n  // and solution classes. Since we want to compare the numerically obtained\n  // solution to the exact continuous one, we need a function object that\n  // represents the continuous solution. On the other hand, we need the right\n  // hand side function, and that one of course shares some characteristics\n  // with the solution. In order to reduce dependencies which arise if we have\n  // to change something in both classes at the same time, we move the common\n  // characteristics of both functions into a base class.\n  //\n  // The common characteristics for solution (as explained in the\n  // introduction, we choose a sum of three exponentials) and right hand side,\n  // are these: the number of exponentials, their centers, and their half\n  // width. We declare them in the following class. Since the number of\n  // exponentials is a constant scalar integral quantity, C++ allows its\n  // definition (i.e. assigning a value) right at the place of declaration\n  // (i.e. where we declare that such a variable exists).\n  template <int dim>\n  class SolutionBase\n  {\n  protected:\n    static const unsigned int n_source_centers = 3;\n    static const Point<dim>   source_centers[n_source_centers];\n    static const double       width;\n  };\n\n\n  // The variables which denote the centers and the width of the exponentials\n  // have just been declared, now we still need to assign values to\n  // them. Here, we can show another small piece of template sorcery, namely\n  // how we can assign different values to these variables depending on the\n  // dimension. We will only use the 2d case in the program, but we show the\n  // 1d case for exposition of a useful technique.\n  //\n  // First we assign values to the centers for the 1d case, where we place the\n  // centers equidistantly at -1/3, 0, and 1/3. The <code>template\n  // &lt;&gt;</code> header for this definition indicates an explicit\n  // specialization. This means, that the variable belongs to a template, but\n  // that instead of providing the compiler with a template from which it can\n  // specialize a concrete variable by substituting <code>dim</code> with some\n  // concrete value, we provide a specialization ourselves, in this case for\n  // <code>dim=1</code>. If the compiler then sees a reference to this\n  // variable in a place where the template argument equals one, it knows that\n  // it doesn't have to generate the variable from a template by substituting\n  // <code>dim</code>, but can immediately use the following definition:\n  template <>\n  const Point<1>\n  SolutionBase<1>::source_centers[SolutionBase<1>::n_source_centers]\n    = { Point<1>(-1.0 / 3.0),\n        Point<1>(0.0),\n        Point<1>(+1.0 / 3.0)\n      };\n\n  // Likewise, we can provide an explicit specialization for\n  // <code>dim=2</code>. We place the centers for the 2d case as follows:\n  template <>\n  const Point<2>\n  SolutionBase<2>::source_centers[SolutionBase<2>::n_source_centers]\n    = { Point<2>(-0.5, +0.5),\n        Point<2>(-0.5, -0.5),\n        Point<2>(+0.5, -0.5)\n      };\n\n  // There remains to assign a value to the half-width of the exponentials. We\n  // would like to use the same value for all dimensions. In this case, we\n  // simply provide the compiler with a template from which it can generate a\n  // concrete instantiation by substituting <code>dim</code> with a concrete\n  // value:\n  template <int dim>\n  const double SolutionBase<dim>::width = 1./3.;\n\n\n\n  // After declaring and defining the characteristics of solution and right\n  // hand side, we can declare the classes representing these two. They both\n  // represent continuous functions, so they are derived from the\n  // Function&lt;dim&gt; base class, and they also inherit the characteristics\n  // defined in the SolutionBase class.\n  //\n  // The actual classes are declared in the following. Note that in order to\n  // compute the error of the numerical solution against the continuous one in\n  // the L2 and H1 norms, we have to provide value and gradient of the exact\n  // solution. This is more than we have done in previous examples, where all\n  // we provided was the value at one or a list of points. Fortunately, the\n  // Function class also has virtual functions for the gradient, so we can\n  // simply overload the respective virtual member functions in the Function\n  // base class. Note that the gradient of a function in <code>dim</code>\n  // space dimensions is a vector of size <code>dim</code>, i.e. a tensor of\n  // rank 1 and dimension <code>dim</code>. As for so many other things, the\n  // library provides a suitable class for this.\n  //\n  // Just as in previous examples, we are forced by the C++ language\n  // specification to declare a seemingly useless default constructor.\n  template <int dim>\n  class Solution : public Function<dim>,\n    protected SolutionBase<dim>\n  {\n  public:\n    Solution () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n\n    virtual Tensor<1,dim> gradient (const Point<dim>   &p,\n                                    const unsigned int  component = 0) const;\n  };\n\n\n  // The actual definition of the values and gradients of the exact solution\n  // class is according to their mathematical definition and does not need\n  // much explanation.\n  //\n  // The only thing that is worth mentioning is that if we access elements of\n  // a base class that is template dependent (in this case the elements of\n  // SolutionBase&lt;dim&gt;), then the C++ language forces us to write\n  // <code>this-&gt;n_source_centers</code> (for example). Note that the\n  // <code>this-&gt;</code> qualification is not necessary if the base class\n  // is not template dependent, and also that the gcc compilers prior to\n  // version 3.4 don't enforce this requirement of the C++ standard. The\n  // reason why this is necessary is complicated; some books on C++ may\n  // explain it, so if you are interested you can look it up under the phrase\n  // <code>two-stage (name) lookup</code>.\n  template <int dim>\n  double Solution<dim>::value (const Point<dim>   &p,\n                               const unsigned int) const\n  {\n    double return_value = 0;\n    for (unsigned int i=0; i<this->n_source_centers; ++i)\n      {\n        const Point<dim> x_minus_xi = p - this->source_centers[i];\n        return_value += std::exp(-x_minus_xi.square() /\n                                 (this->width * this->width));\n      }\n\n    return return_value;\n  }\n\n\n  // Likewise, this is the computation of the gradient of the solution.  In\n  // order to accumulate the gradient from the contributions of the\n  // exponentials, we allocate an object <code>return_value</code> that\n  // denotes the mathematical quantity of a tensor of rank <code>1</code> and\n  // dimension <code>dim</code>. Its default constructor sets it to the vector\n  // containing only zeroes, so we need not explicitly care for its\n  // initialization.\n  //\n  // Note that we could as well have taken the type of the object to be\n  // Point&lt;dim&gt; instead of Tensor&lt;1,dim&gt;. Tensors of rank 1 and\n  // points are almost exchangeable, and have only very slightly different\n  // mathematical meanings. In fact, the Point&lt;dim&gt; class is derived\n  // from the Tensor&lt;1,dim&gt; class, which makes up for their mutual\n  // exchange ability. Their main difference is in what they logically mean:\n  // points are points in space, such as the location at which we want to\n  // evaluate a function (see the type of the first argument of this function\n  // for example). On the other hand, tensors of rank 1 share the same\n  // transformation properties, for example that they need to be rotated in a\n  // certain way when we change the coordinate system; however, they do not\n  // share the same connotation that points have and are only objects in a\n  // more abstract space than the one spanned by the coordinate\n  // directions. (In fact, gradients live in `reciprocal' space, since the\n  // dimension of their components is not that of a length, but one over\n  // length).\n  template <int dim>\n  Tensor<1,dim> Solution<dim>::gradient (const Point<dim>   &p,\n                                         const unsigned int) const\n  {\n    Tensor<1,dim> return_value;\n\n    for (unsigned int i=0; i<this->n_source_centers; ++i)\n      {\n        const Point<dim> x_minus_xi = p - this->source_centers[i];\n\n        // For the gradient, note that its direction is along (x-x_i), so we\n        // add up multiples of this distance vector, where the factor is given\n        // by the exponentials.\n        return_value += (-2 / (this->width * this->width) *\n                         std::exp(-x_minus_xi.square() /\n                                  (this->width * this->width)) *\n                         x_minus_xi);\n      }\n\n    return return_value;\n  }\n\n\n\n  // Besides the function that represents the exact solution, we also need a\n  // function which we can use as right hand side when assembling the linear\n  // system of discretized equations. This is accomplished using the following\n  // class and the following definition of its function. Note that here we\n  // only need the value of the function, not its gradients or higher\n  // derivatives.\n  template <int dim>\n  class RightHandSide : public Function<dim>,\n    protected SolutionBase<dim>\n  {\n  public:\n    RightHandSide () : Function<dim>() {}\n\n    virtual double value (const Point<dim>   &p,\n                          const unsigned int  component = 0) const;\n  };\n\n\n  // The value of the right hand side is given by the negative Laplacian of\n  // the solution plus the solution itself, since we wanted to solve\n  // Helmholtz's equation:\n  template <int dim>\n  double RightHandSide<dim>::value (const Point<dim>   &p,\n                                    const unsigned int) const\n  {\n    double return_value = 0;\n    for (unsigned int i=0; i<this->n_source_centers; ++i)\n      {\n        const Point<dim> x_minus_xi = p - this->source_centers[i];\n\n        // The first contribution is the Laplacian:\n        return_value += ((2*dim - 4*x_minus_xi.square()/\n                          (this->width * this->width)) /\n                         (this->width * this->width) *\n                         std::exp(-x_minus_xi.square() /\n                                  (this->width * this->width)));\n        // And the second is the solution itself:\n        return_value += std::exp(-x_minus_xi.square() /\n                                 (this->width * this->width));\n      }\n\n    return return_value;\n  }\n\n\n  // @sect3{The Helmholtz solver class}\n\n  // Then we need the class that does all the work. Except for its name, its\n  // interface is mostly the same as in previous examples.\n  //\n  // One of the differences is that we will use this class in several modes:\n  // for different finite elements, as well as for adaptive and global\n  // refinement. The decision whether global or adaptive refinement shall be\n  // used is communicated to the constructor of this class through an\n  // enumeration type declared at the top of the class. The constructor then\n  // takes a finite element object and the refinement mode as arguments.\n  //\n  // The rest of the member functions are as before except for the\n  // <code>process_solution</code> function: After the solution has been\n  // computed, we perform some analysis on it, such as computing the error in\n  // various norms. To enable some output, it requires the number of the\n  // refinement cycle, and consequently gets it as an argument.\n  template <int dim>\n  class HelmholtzProblem\n  {\n  public:\n    enum RefinementMode\n    {\n      global_refinement, adaptive_refinement\n    };\n\n    HelmholtzProblem (const FiniteElement<dim> &fe,\n                      const RefinementMode      refinement_mode);\n\n    ~HelmholtzProblem ();\n\n    void run ();\n\n  private:\n    void setup_system ();\n    void assemble_system ();\n    void solve ();\n    void refine_grid ();\n    void process_solution (const unsigned int cycle);\n\n    // Now for the data elements of this class. Among the variables that we\n    // have already used in previous examples, only the finite element object\n    // differs: The finite elements which the objects of this class operate on\n    // are passed to the constructor of this class. It has to store a pointer\n    // to the finite element for the member functions to use. Now, for the\n    // present class there is no big deal in that, but since we want to show\n    // techniques rather than solutions in these programs, we will here point\n    // out a problem that often occurs -- and of course the right solution as\n    // well.\n    //\n    // Consider the following situation that occurs in all the example\n    // programs: we have a triangulation object, and we have a finite element\n    // object, and we also have an object of type DoFHandler that uses both of\n    // the first two. These three objects all have a lifetime that is rather\n    // long compared to most other objects: they are basically set at the\n    // beginning of the program or an outer loop, and they are destroyed at\n    // the very end. The question is: can we guarantee that the two objects\n    // which the DoFHandler uses, live at least as long as they are in use?\n    // This means that the DoFHandler must have some kind of lock on the\n    // destruction of the other objects, and it can only release this lock\n    // once it has cleared all active references to these objects. We have\n    // seen what happens if we violate this order of destruction in the\n    // previous example program: an exception is thrown that terminates the\n    // program in order to notify the programmer of this potentially dangerous\n    // state where an object is pointed to that no longer persists.\n    //\n    // We will show here how the library managed to find out that there are\n    // still active references to an object. Basically, the method is along\n    // the following line: all objects that are subject to such potentially\n    // dangerous pointers are derived from a class called Subscriptor. For\n    // example, the Triangulation, DoFHandler, and a base class of the\n    // FiniteElement class are derived from Subscriptor. This latter class\n    // does not offer much functionality, but it has a built-in counter which\n    // we can subscribe to, thus the name of the class. Whenever we initialize\n    // a pointer to that object, we can increase its use counter, and when we\n    // move away our pointer or do not need it any more, we decrease the\n    // counter again. This way, we can always check how many objects still use\n    // that object.\n    //\n    // On the other hand, if an object of a class that is derived from the\n    // Subscriptor class is destroyed, it also has to call the destructor of\n    // the Subscriptor class. In this destructor, there will then be a check\n    // whether the counter is really zero. If yes, then there are no active\n    // references to this object any more, and we can safely destroy it. If\n    // the counter is non-zero, however, then the destruction would result in\n    // stale and thus potentially dangerous pointers, and we rather throw an\n    // exception to alert the programmer that this is doing something\n    // dangerous and the program better be fixed.\n    //\n    // While this certainly all sounds very well, it has some problems in\n    // terms of usability: what happens if I forget to increase the counter\n    // when I let a pointer point to such an object? And what happens if I\n    // forget to decrease it again? Note that this may lead to extremely\n    // difficult to find bugs, since the place where we have forgotten\n    // something may be far away from the place where the check for zeroness\n    // of the counter upon destruction actually fails. This kind of bug is\n    // rather annoying and usually very hard to fix.\n    //\n    // The solution to this problem is to again use some C++ trickery: we\n    // create a class that acts just like a pointer, i.e. can be dereferenced,\n    // can be assigned to and from other pointers, and so on. This can be done\n    // by overloading the several dereferencing operators of that\n    // class. Within the constructors, destructors, and assignment operators\n    // of that class, we can however also manage increasing or decreasing the\n    // use counters of the objects we point to. Objects of that class\n    // therefore can be used just like ordinary pointers to objects, but they\n    // also serve to change the use counters of those objects without the need\n    // for the programmer to do so herself. The class that actually does all\n    // this is called SmartPointer and takes as template parameter the data\n    // type of the object which it shall point to. The latter type may be any\n    // class, as long as it is derived from the Subscriptor class.\n    //\n    // In the present example program, we want to protect the finite element\n    // object from the situation that for some reason the finite element\n    // pointed to is destroyed while still in use. We therefore use a\n    // SmartPointer to the finite element object; since the finite element\n    // object is actually never changed in our computations, we pass a const\n    // FiniteElement&lt;dim&gt; as template argument to the SmartPointer\n    // class. Note that the pointer so declared is assigned at construction\n    // time of the solve object, and destroyed upon destruction, so the lock\n    // on the destruction of the finite element object extends throughout the\n    // lifetime of this HelmholtzProblem object.\n    Triangulation<dim>                      triangulation;\n    DoFHandler<dim>                         dof_handler;\n\n    SmartPointer<const FiniteElement<dim> > fe;\n\n    ConstraintMatrix                        hanging_node_constraints;\n\n    SparsityPattern                         sparsity_pattern;\n    SparseMatrix<double>                    system_matrix;\n\n    Vector<double>                          solution;\n    Vector<double>                          system_rhs;\n\n    // The second to last variable stores the refinement mode passed to the\n    // constructor. Since it is only set in the constructor, we can declare\n    // this variable constant, to avoid that someone sets it involuntarily\n    // (e.g. in an `if'-statement where == was written as = by chance).\n    const RefinementMode                    refinement_mode;\n\n    // For each refinement level some data (like the number of cells, or the\n    // L2 error of the numerical solution) will be generated and later\n    // printed. The TableHandler can be used to collect all this data and to\n    // output it at the end of the run as a table in a simple text or in LaTeX\n    // format. Here we don't only use the TableHandler but we use the derived\n    // class ConvergenceTable that additionally evaluates rates of\n    // convergence:\n    ConvergenceTable                        convergence_table;\n  };\n\n\n  // @sect3{The HelmholtzProblem class implementation}\n\n  // @sect4{HelmholtzProblem::HelmholtzProblem}\n\n  // In the constructor of this class, we only set the variables passed as\n  // arguments, and associate the DoF handler object with the triangulation\n  // (which is empty at present, however).\n  template <int dim>\n  HelmholtzProblem<dim>::HelmholtzProblem (const FiniteElement<dim> &fe,\n                                           const RefinementMode refinement_mode) :\n    dof_handler (triangulation),\n    fe (&fe),\n    refinement_mode (refinement_mode)\n  {}\n\n\n  // @sect4{HelmholtzProblem::~HelmholtzProblem}\n\n  // This is no different than before:\n  template <int dim>\n  HelmholtzProblem<dim>::~HelmholtzProblem ()\n  {\n    dof_handler.clear ();\n  }\n\n\n  // @sect4{HelmholtzProblem::setup_system}\n\n  // The following function sets up the degrees of freedom, sizes of matrices\n  // and vectors, etc. Most of its functionality has been showed in previous\n  // examples, the only difference being the renumbering step immediately\n  // after first distributing degrees of freedom.\n  //\n  // Renumbering the degrees of freedom is not overly difficult, as long as\n  // you use one of the algorithms included in the library. It requires only a\n  // single line of code. Some more information on this can be found in\n  // step-2.\n  //\n  // Note, however, that when you renumber the degrees of freedom, you must do\n  // so immediately after distributing them, since such things as hanging\n  // nodes, the sparsity pattern etc. depend on the absolute numbers which are\n  // altered by renumbering.\n  //\n  // The reason why we introduce renumbering here is that it is a relatively\n  // cheap operation but often has a beneficial effect: While the CG iteration\n  // itself is independent of the actual ordering of degrees of freedom, we\n  // will use SSOR as a preconditioner. SSOR goes through all degrees of\n  // freedom and does some operations that depend on what happened before; the\n  // SSOR operation is therefore not independent of the numbering of degrees\n  // of freedom, and it is known that its performance improves by using\n  // renumbering techniques. A little experiment shows that indeed, for\n  // example, the number of CG iterations for the fifth refinement cycle of\n  // adaptive refinement with the Q1 program used here is 40 without, but 36\n  // with renumbering. Similar savings can generally be observed for all the\n  // computations in this program.\n  template <int dim>\n  void HelmholtzProblem<dim>::setup_system ()\n  {\n    dof_handler.distribute_dofs (*fe);\n    DoFRenumbering::Cuthill_McKee (dof_handler);\n\n    hanging_node_constraints.clear ();\n    DoFTools::make_hanging_node_constraints (dof_handler,\n                                             hanging_node_constraints);\n    hanging_node_constraints.close ();\n\n    sparsity_pattern.reinit (dof_handler.n_dofs(),\n                             dof_handler.n_dofs(),\n                             dof_handler.max_couplings_between_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n    hanging_node_constraints.condense (sparsity_pattern);\n    sparsity_pattern.compress();\n\n    system_matrix.reinit (sparsity_pattern);\n\n    solution.reinit (dof_handler.n_dofs());\n    system_rhs.reinit (dof_handler.n_dofs());\n  }\n\n\n  // @sect4{HelmholtzProblem::assemble_system}\n\n  // Assembling the system of equations for the problem at hand is mostly as\n  // for the example programs before. However, some things have changed\n  // anyway, so we comment on this function fairly extensively.\n  //\n  // At the top of the function you will find the usual assortment of variable\n  // declarations. Compared to previous programs, of importance is only that\n  // we expect to solve problems also with bi-quadratic elements and therefore\n  // have to use sufficiently accurate quadrature formula. In addition, we\n  // need to compute integrals over faces, i.e. <code>dim-1</code> dimensional\n  // objects. The declaration of a face quadrature formula is then\n  // straightforward:\n  template <int dim>\n  void HelmholtzProblem<dim>::assemble_system ()\n  {\n    QGauss<dim>   quadrature_formula(3);\n    QGauss<dim-1> face_quadrature_formula(3);\n\n    const unsigned int n_q_points    = quadrature_formula.size();\n    const unsigned int n_face_q_points = face_quadrature_formula.size();\n\n    const unsigned int dofs_per_cell = fe->dofs_per_cell;\n\n    FullMatrix<double>   cell_matrix (dofs_per_cell, dofs_per_cell);\n    Vector<double>       cell_rhs (dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    // Then we need objects which can evaluate the values, gradients, etc of\n    // the shape functions at the quadrature points. While it seems that it\n    // should be feasible to do it with one object for both domain and face\n    // integrals, there is a subtle difference since the weights in the domain\n    // integrals include the measure of the cell in the domain, while the face\n    // integral quadrature requires the measure of the face in a\n    // lower-dimensional manifold. Internally these two classes are rooted in\n    // a common base class which does most of the work and offers the same\n    // interface to both domain and interface integrals.\n    //\n    // For the domain integrals in the bilinear form for Helmholtz's equation,\n    // we need to compute the values and gradients, as well as the weights at\n    // the quadrature points. Furthermore, we need the quadrature points on\n    // the real cell (rather than on the unit cell) to evaluate the right hand\n    // side function. The object we use to get at this information is the\n    // FEValues class discussed previously.\n    //\n    // For the face integrals, we only need the values of the shape functions,\n    // as well as the weights. We also need the normal vectors and quadrature\n    // points on the real cell since we want to determine the Neumann values\n    // from the exact solution object (see below). The class that gives us\n    // this information is called FEFaceValues:\n    FEValues<dim>  fe_values (*fe, quadrature_formula,\n                              update_values   | update_gradients |\n                              update_quadrature_points | update_JxW_values);\n\n    FEFaceValues<dim> fe_face_values (*fe, face_quadrature_formula,\n                                      update_values         | update_quadrature_points  |\n                                      update_normal_vectors | update_JxW_values);\n\n    // Then we need some objects already known from previous examples: An\n    // object denoting the right hand side function, its values at the\n    // quadrature points on a cell, the cell matrix and right hand side, and\n    // the indices of the degrees of freedom on a cell.\n    //\n    // Note that the operations we will do with the right hand side object are\n    // only querying data, never changing the object. We can therefore declare\n    // it <code>const</code>:\n    const RightHandSide<dim> right_hand_side;\n    std::vector<double>  rhs_values (n_q_points);\n\n    // Finally we define an object denoting the exact solution function. We\n    // will use it to compute the Neumann values at the boundary from\n    // it. Usually, one would of course do so using a separate object, in\n    // particular since the exact solution is generally unknown while the\n    // Neumann values are prescribed. We will, however, be a little bit lazy\n    // and use what we already have in information. Real-life programs would\n    // to go other ways here, of course.\n    const Solution<dim> exact_solution;\n\n    // Now for the main loop over all cells. This is mostly unchanged from\n    // previous examples, so we only comment on the things that have changed.\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        cell_matrix = 0;\n        cell_rhs = 0;\n\n        fe_values.reinit (cell);\n\n        right_hand_side.value_list (fe_values.get_quadrature_points(),\n                                    rhs_values);\n\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            {\n              for (unsigned int j=0; j<dofs_per_cell; ++j)\n                // The first thing that has changed is the bilinear form. It\n                // now contains the additional term from the Helmholtz\n                // equation:\n                cell_matrix(i,j) += ((fe_values.shape_grad(i,q_point) *\n                                      fe_values.shape_grad(j,q_point)\n                                      +\n                                      fe_values.shape_value(i,q_point) *\n                                      fe_values.shape_value(j,q_point)) *\n                                     fe_values.JxW(q_point));\n\n              cell_rhs(i) += (fe_values.shape_value(i,q_point) *\n                              rhs_values [q_point] *\n                              fe_values.JxW(q_point));\n            }\n\n        // Then there is that second term on the right hand side, the contour\n        // integral. First we have to find out whether the intersection of the\n        // faces of this cell with the boundary part Gamma2 is nonzero. To\n        // this end, we loop over all faces and check whether its boundary\n        // indicator equals <code>1</code>, which is the value that we have\n        // assigned to that portions of the boundary composing Gamma2 in the\n        // <code>run()</code> function further below. (The default value of\n        // boundary indicators is <code>0</code>, so faces can only have an\n        // indicator equal to <code>1</code> if we have explicitly set it.)\n        for (unsigned int face=0; face<GeometryInfo<dim>::faces_per_cell; ++face)\n          if (cell->face(face)->at_boundary()\n              &&\n              (cell->face(face)->boundary_indicator() == 1))\n            {\n              // If we came into here, then we have found an external face\n              // belonging to Gamma2. Next, we have to compute the values of\n              // the shape functions and the other quantities which we will\n              // need for the computation of the contour integral. This is\n              // done using the <code>reinit</code> function which we already\n              // know from the FEValue class:\n              fe_face_values.reinit (cell, face);\n\n              // And we can then perform the integration by using a loop over\n              // all quadrature points.\n              //\n              // On each quadrature point, we first compute the value of the\n              // normal derivative. We do so using the gradient of the exact\n              // solution and the normal vector to the face at the present\n              // quadrature point obtained from the\n              // <code>fe_face_values</code> object. This is then used to\n              // compute the additional contribution of this face to the right\n              // hand side:\n              for (unsigned int q_point=0; q_point<n_face_q_points; ++q_point)\n                {\n                  const double neumann_value\n                    = (exact_solution.gradient (fe_face_values.quadrature_point(q_point)) *\n                       fe_face_values.normal_vector(q_point));\n\n                  for (unsigned int i=0; i<dofs_per_cell; ++i)\n                    cell_rhs(i) += (neumann_value *\n                                    fe_face_values.shape_value(i,q_point) *\n                                    fe_face_values.JxW(q_point));\n                }\n            }\n\n        // Now that we have the contributions of the present cell, we can\n        // transfer it to the global matrix and right hand side vector, as in\n        // the examples before:\n        cell->get_dof_indices (local_dof_indices);\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          {\n            for (unsigned int j=0; j<dofs_per_cell; ++j)\n              system_matrix.add (local_dof_indices[i],\n                                 local_dof_indices[j],\n                                 cell_matrix(i,j));\n\n            system_rhs(local_dof_indices[i]) += cell_rhs(i);\n          }\n      }\n\n    // Likewise, elimination and treatment of boundary values has been shown\n    // previously.\n    //\n    // We note, however that now the boundary indicator for which we\n    // interpolate boundary values (denoted by the second parameter to\n    // <code>interpolate_boundary_values</code>) does not represent the whole\n    // boundary any more. Rather, it is that portion of the boundary which we\n    // have not assigned another indicator (see below). The degrees of freedom\n    // at the boundary that do not belong to Gamma1 are therefore excluded\n    // from the interpolation of boundary values, just as we want.\n    hanging_node_constraints.condense (system_matrix);\n    hanging_node_constraints.condense (system_rhs);\n\n    std::map<unsigned int,double> boundary_values;\n    VectorTools::interpolate_boundary_values (dof_handler,\n                                              0,\n                                              Solution<dim>(),\n                                              boundary_values);\n    MatrixTools::apply_boundary_values (boundary_values,\n                                        system_matrix,\n                                        solution,\n                                        system_rhs);\n  }\n\n\n  // @sect4{HelmholtzProblem::solve}\n\n  // Solving the system of equations is done in the same way as before:\n  template <int dim>\n  void HelmholtzProblem<dim>::solve ()\n  {\n    SolverControl           solver_control (1000, 1e-12);\n    SolverCG<>              cg (solver_control);\n\n    PreconditionSSOR<> preconditioner;\n    preconditioner.initialize(system_matrix, 1.2);\n\n    cg.solve (system_matrix, solution, system_rhs,\n              preconditioner);\n\n    hanging_node_constraints.distribute (solution);\n  }\n\n\n  // @sect4{HelmholtzProblem::refine_grid}\n\n  // Now for the function doing grid refinement. Depending on the refinement\n  // mode passed to the constructor, we do global or adaptive refinement.\n  //\n  // Global refinement is simple, so there is not much to comment on.  In case\n  // of adaptive refinement, we use the same functions and classes as in the\n  // previous example program. Note that one could treat Neumann boundaries\n  // differently than Dirichlet boundaries, and one should in fact do so here\n  // since we have Neumann boundary conditions on part of the boundaries, but\n  // since we don't have a function here that describes the Neumann values (we\n  // only construct these values from the exact solution when assembling the\n  // matrix), we omit this detail even though they would not be hard to add.\n  //\n  // At the end of the switch, we have a default case that looks slightly\n  // strange: an <code>Assert</code> statement with a <code>false</code>\n  // condition. Since the <code>Assert</code> macro raises an error whenever\n  // the condition is false, this means that whenever we hit this statement\n  // the program will be aborted. This in intentional: Right now we have only\n  // implemented two refinement strategies (global and adaptive), but someone\n  // might want to add a third strategy (for example adaptivity with a\n  // different refinement criterion) and add a third member to the enumeration\n  // that determines the refinement mode. If it weren't for the default case\n  // of the switch statement, this function would simply run to its end\n  // without doing anything. This is most likely not what was intended. One of\n  // the defensive programming techniques that you will find all over the\n  // deal.II library is therefore to always have default cases that abort, to\n  // make sure that values not considered when listing the cases in the switch\n  // statement are eventually caught, and forcing programmers to add code to\n  // handle them. We will use this same technique in other places further down\n  // as well.\n  template <int dim>\n  void HelmholtzProblem<dim>::refine_grid ()\n  {\n    switch (refinement_mode)\n      {\n      case global_refinement:\n      {\n        triangulation.refine_global (1);\n        break;\n      }\n\n      case adaptive_refinement:\n      {\n        Vector<float> estimated_error_per_cell (triangulation.n_active_cells());\n\n        typename FunctionMap<dim>::type neumann_boundary;\n        KellyErrorEstimator<dim>::estimate (dof_handler,\n                                            QGauss<dim-1>(3),\n                                            neumann_boundary,\n                                            solution,\n                                            estimated_error_per_cell);\n\n        GridRefinement::refine_and_coarsen_fixed_number (triangulation,\n                                                         estimated_error_per_cell,\n                                                         0.3, 0.03);\n\n        triangulation.execute_coarsening_and_refinement ();\n\n        break;\n      }\n\n      default:\n      {\n        Assert (false, ExcNotImplemented());\n      }\n      }\n  }\n\n\n  // @sect4{HelmholtzProblem::process_solution}\n\n  // Finally we want to process the solution after it has been computed. For\n  // this, we integrate the error in various norms, and we generate tables\n  // that will later be used to display the convergence against the continuous\n  // solution in a nice format.\n  template <int dim>\n  void HelmholtzProblem<dim>::process_solution (const unsigned int cycle)\n  {\n    // Our first task is to compute error norms. In order to integrate the\n    // difference between computed numerical solution and the continuous\n    // solution (described by the Solution class defined at the top of this\n    // file), we first need a vector that will hold the norm of the error on\n    // each cell. Since accuracy with 16 digits is not so important for these\n    // quantities, we save some memory by using <code>float</code> instead of\n    // <code>double</code> values.\n    //\n    // The next step is to use a function from the library which computes the\n    // error in the L2 norm on each cell.  We have to pass it the DoF handler\n    // object, the vector holding the nodal values of the numerical solution,\n    // the continuous solution as a function object, the vector into which it\n    // shall place the norm of the error on each cell, a quadrature rule by\n    // which this norm shall be computed, and the type of norm to be\n    // used. Here, we use a Gauss formula with three points in each space\n    // direction, and compute the L2 norm.\n    //\n    // Finally, we want to get the global L2 norm. This can of course be\n    // obtained by summing the squares of the norms on each cell, and taking\n    // the square root of that value. This is equivalent to taking the l2\n    // (lower case <code>l</code>) norm of the vector of norms on each cell:\n    Vector<float> difference_per_cell (triangulation.n_active_cells());\n    VectorTools::integrate_difference (dof_handler,\n                                       solution,\n                                       Solution<dim>(),\n                                       difference_per_cell,\n                                       QGauss<dim>(3),\n                                       VectorTools::L2_norm);\n    const double L2_error = difference_per_cell.l2_norm();\n\n    // By same procedure we get the H1 semi-norm. We re-use the\n    // <code>difference_per_cell</code> vector since it is no longer used\n    // after computing the <code>L2_error</code> variable above.\n    VectorTools::integrate_difference (dof_handler,\n                                       solution,\n                                       Solution<dim>(),\n                                       difference_per_cell,\n                                       QGauss<dim>(3),\n                                       VectorTools::H1_seminorm);\n    const double H1_error = difference_per_cell.l2_norm();\n\n    // Finally, we compute the maximum norm. Of course, we can't actually\n    // compute the true maximum, but only the maximum at the quadrature\n    // points. Since this depends quite sensitively on the quadrature rule\n    // being used, and since we would like to avoid false results due to\n    // super-convergence effects at some points, we use a special quadrature\n    // rule that is obtained by iterating the trapezoidal rule five times in\n    // each space direction. Note that the constructor of the QIterated class\n    // takes a one-dimensional quadrature rule and a number that tells it how\n    // often it shall use this rule in each space direction.\n    //\n    // Using this special quadrature rule, we can then try to find the maximal\n    // error on each cell. Finally, we compute the global L infinity error\n    // from the L infinite errors on each cell. Instead of summing squares, we\n    // now have to take the maximum value over all cell-wise entries, an\n    // operation that is conveniently done using the Vector::linfty()\n    // function:\n    const QTrapez<1>     q_trapez;\n    const QIterated<dim> q_iterated (q_trapez, 5);\n    VectorTools::integrate_difference (dof_handler,\n                                       solution,\n                                       Solution<dim>(),\n                                       difference_per_cell,\n                                       q_iterated,\n                                       VectorTools::Linfty_norm);\n    const double Linfty_error = difference_per_cell.linfty_norm();\n\n    // After all these errors have been computed, we finally write some\n    // output. In addition, we add the important data to the TableHandler by\n    // specifying the key of the column and the value.  Note that it is not\n    // necessary to define column keys beforehand -- it is sufficient to just\n    // add values, and columns will be introduced into the table in the order\n    // values are added the first time.\n    const unsigned int n_active_cells=triangulation.n_active_cells();\n    const unsigned int n_dofs=dof_handler.n_dofs();\n\n    std::cout << \"Cycle \" << cycle << ':'\n              << std::endl\n              << \"   Number of active cells:       \"\n              << n_active_cells\n              << std::endl\n              << \"   Number of degrees of freedom: \"\n              << n_dofs\n              << std::endl;\n\n    convergence_table.add_value(\"cycle\", cycle);\n    convergence_table.add_value(\"cells\", n_active_cells);\n    convergence_table.add_value(\"dofs\", n_dofs);\n    convergence_table.add_value(\"L2\", L2_error);\n    convergence_table.add_value(\"H1\", H1_error);\n    convergence_table.add_value(\"Linfty\", Linfty_error);\n  }\n\n\n  // @sect4{HelmholtzProblem::run}\n\n  // As in previous example programs, the <code>run</code> function controls\n  // the flow of execution. The basic layout is as in previous examples: an\n  // outer loop over successively refined grids, and in this loop first\n  // problem setup, assembling the linear system, solution, and\n  // post-processing.\n  //\n  // The first task in the main loop is creation and refinement of grids. This\n  // is as in previous examples, with the only difference that we want to have\n  // part of the boundary marked as Neumann type, rather than Dirichlet.\n  //\n  // For this, we will use the following convention: Faces belonging to Gamma1\n  // will have the boundary indicator <code>0</code> (which is the default, so\n  // we don't have to set it explicitely), and faces belonging to Gamma2 will\n  // use <code>1</code> as boundary indicator.  To set these values, we loop\n  // over all cells, then over all faces of a given cell, check whether it is\n  // part of the boundary that we want to denote by Gamma2, and if so set its\n  // boundary indicator to <code>1</code>. For the present program, we\n  // consider the left and bottom boundaries as Gamma2. We determine whether a\n  // face is part of that boundary by asking whether the x or y coordinates\n  // (i.e. vector components 0 and 1) of the midpoint of a face equals -1, up\n  // to some small wiggle room that we have to give since it is instable to\n  // compare floating point numbers that are subject to round off in\n  // intermediate computations.\n  //\n  // It is worth noting that we have to loop over all cells here, not only the\n  // active ones. The reason is that upon refinement, newly created faces\n  // inherit the boundary indicator of their parent face. If we now only set\n  // the boundary indicator for active faces, coarsen some cells and refine\n  // them later on, they will again have the boundary indicator of the parent\n  // cell which we have not modified, instead of the one we\n  // intended. Consequently, we have to change the boundary indicators of\n  // faces of all cells on Gamma2, whether they are active or not.\n  // Alternatively, we could of course have done this job on the coarsest mesh\n  // (i.e. before the first refinement step) and refined the mesh only after\n  // that.\n  template <int dim>\n  void HelmholtzProblem<dim>::run ()\n  {\n    for (unsigned int cycle=0; cycle<7; ++cycle)\n      {\n        if (cycle == 0)\n          {\n            GridGenerator::hyper_cube (triangulation, -1, 1);\n            triangulation.refine_global (1);\n\n            typename Triangulation<dim>::cell_iterator\n            cell = triangulation.begin (),\n            endc = triangulation.end();\n            for (; cell!=endc; ++cell)\n              for (unsigned int face=0;\n                   face<GeometryInfo<dim>::faces_per_cell;\n                   ++face)\n                if ((std::fabs(cell->face(face)->center()(0) - (-1)) < 1e-12)\n                    ||\n                    (std::fabs(cell->face(face)->center()(1) - (-1)) < 1e-12))\n                  cell->face(face)->set_boundary_indicator (1);\n          }\n        else\n          refine_grid ();\n\n\n        // The next steps are already known from previous examples. This is\n        // mostly the basic set-up of every finite element program:\n        setup_system ();\n\n        assemble_system ();\n        solve ();\n\n        // The last step in this chain of function calls is usually the\n        // evaluation of the computed solution for the quantities one is\n        // interested in. This is done in the following function. Since the\n        // function generates output that indicates the number of the present\n        // refinement step, we pass this number as an argument.\n        process_solution (cycle);\n      }\n\n    // @sect5{Output of graphical data}\n\n    // After the last iteration we output the solution on the finest\n    // grid. This is done using the following sequence of statements which we\n    // have already discussed in previous examples. The first step is to\n    // generate a suitable filename (called <code>gmv_filename</code> here,\n    // since we want to output data in GMV format; we add the prefix to\n    // distinguish the filename from that used for other output files further\n    // down below). Here, we augment the name by the mesh refinement\n    // algorithm, and as above we make sure that we abort the program if\n    // another refinement method is added and not handled by the following\n    // switch statement:\n    std::string gmv_filename;\n    switch (refinement_mode)\n      {\n      case global_refinement:\n        gmv_filename = \"solution-global\";\n        break;\n      case adaptive_refinement:\n        gmv_filename = \"solution-adaptive\";\n        break;\n      default:\n        Assert (false, ExcNotImplemented());\n      }\n\n    // We augment the filename by a postfix denoting the finite element which\n    // we have used in the computation. To this end, the finite element base\n    // class stores the maximal polynomial degree of shape functions in each\n    // coordinate variable as a variable <code>degree</code>, and we use for\n    // the switch statement (note that the polynomial degree of bilinear shape\n    // functions is really 2, since they contain the term <code>x*y</code>;\n    // however, the polynomial degree in each coordinate variable is still\n    // only 1). We again use the same defensive programming technique to\n    // safeguard against the case that the polynomial degree has an unexpected\n    // value, using the <code>Assert (false, ExcNotImplemented())</code> idiom\n    // in the default branch of the switch statement:\n    switch (fe->degree)\n      {\n      case 1:\n        gmv_filename += \"-q1\";\n        break;\n      case 2:\n        gmv_filename += \"-q2\";\n        break;\n\n      default:\n        Assert (false, ExcNotImplemented());\n      }\n\n    // Once we have the base name for the output file, we add an extension\n    // appropriate for GMV output, open a file, and add the solution vector to\n    // the object that will do the actual output:\n    gmv_filename += \".gmv\";\n    std::ofstream output (gmv_filename.c_str());\n\n    DataOut<dim> data_out;\n    data_out.attach_dof_handler (dof_handler);\n    data_out.add_data_vector (solution, \"solution\");\n\n    // Now building the intermediate format as before is the next step. We\n    // introduce one more feature of deal.II here. The background is the\n    // following: in some of the runs of this function, we have used\n    // biquadratic finite elements. However, since almost all output formats\n    // only support bilinear data, the data is written only bilinear, and\n    // information is consequently lost.  Of course, we can't change the\n    // format in which graphic programs accept their inputs, but we can write\n    // the data differently such that we more closely resemble the information\n    // available in the quadratic approximation. We can, for example, write\n    // each cell as four sub-cells with bilinear data each, such that we have\n    // nine data points for each cell in the triangulation. The graphic\n    // programs will, of course, display this data still only bilinear, but at\n    // least we have given some more of the information we have.\n    //\n    // In order to allow writing more than one sub-cell per actual cell, the\n    // <code>build_patches</code> function accepts a parameter (the default is\n    // <code>1</code>, which is why you haven't seen this parameter in\n    // previous examples). This parameter denotes into how many sub-cells per\n    // space direction each cell shall be subdivided for output. For example,\n    // if you give <code>2</code>, this leads to 4 cells in 2D and 8 cells in\n    // 3D. For quadratic elements, two sub-cells per space direction is\n    // obviously the right choice, so this is what we choose. In general, for\n    // elements of polynomial order <code>q</code>, we use <code>q</code>\n    // subdivisions, and the order of the elements is determined in the same\n    // way as above.\n    //\n    // With the intermediate format so generated, we can then actually write\n    // the graphical output in GMV format:\n    data_out.build_patches (fe->degree);\n    data_out.write_gmv (output);\n\n    // @sect5{Output of convergence tables}\n\n    // After graphical output, we would also like to generate tables from the\n    // error computations we have done in\n    // <code>process_solution</code>. There, we have filled a table object\n    // with the number of cells for each refinement step as well as the errors\n    // in different norms.\n\n    // For a nicer textual output of this data, one may want to set the\n    // precision with which the values will be written upon output. We use 3\n    // digits for this, which is usually sufficient for error norms. By\n    // default, data is written in fixed point notation. However, for columns\n    // one would like to see in scientific notation another function call sets\n    // the <code>scientific_flag</code> to <code>true</code>, leading to\n    // floating point representation of numbers.\n    convergence_table.set_precision(\"L2\", 3);\n    convergence_table.set_precision(\"H1\", 3);\n    convergence_table.set_precision(\"Linfty\", 3);\n\n    convergence_table.set_scientific(\"L2\", true);\n    convergence_table.set_scientific(\"H1\", true);\n    convergence_table.set_scientific(\"Linfty\", true);\n\n    // For the output of a table into a LaTeX file, the default captions of\n    // the columns are the keys given as argument to the\n    // <code>add_value</code> functions. To have TeX captions that differ from\n    // the default ones you can specify them by the following function calls.\n    // Note, that `\\\\' is reduced to `\\' by the compiler such that the real\n    // TeX caption is, e.g., `$L^\\infty$-error'.\n    convergence_table.set_tex_caption(\"cells\", \"\\\\# cells\");\n    convergence_table.set_tex_caption(\"dofs\", \"\\\\# dofs\");\n    convergence_table.set_tex_caption(\"L2\", \"$L^2$-error\");\n    convergence_table.set_tex_caption(\"H1\", \"$H^1$-error\");\n    convergence_table.set_tex_caption(\"Linfty\", \"$L^\\\\infty$-error\");\n\n    // Finally, the default LaTeX format for each column of the table is `c'\n    // (centered). To specify a different (e.g. `right') one, the following\n    // function may be used:\n    convergence_table.set_tex_format(\"cells\", \"r\");\n    convergence_table.set_tex_format(\"dofs\", \"r\");\n\n    // After this, we can finally write the table to the standard output\n    // stream <code>std::cout</code> (after one extra empty line, to make\n    // things look prettier). Note, that the output in text format is quite\n    // simple and that captions may not be printed directly above the specific\n    // columns.\n    std::cout << std::endl;\n    convergence_table.write_text(std::cout);\n\n    // The table can also be written into a LaTeX file.  The (nicely)\n    // formatted table can be viewed at after calling `latex filename' and\n    // e.g. `xdvi filename', where filename is the name of the file to which\n    // we will write output now. We construct the file name in the same way as\n    // before, but with a different prefix \"error\":\n    std::string error_filename = \"error\";\n    switch (refinement_mode)\n      {\n      case global_refinement:\n        error_filename += \"-global\";\n        break;\n      case adaptive_refinement:\n        error_filename += \"-adaptive\";\n        break;\n      default:\n        Assert (false, ExcNotImplemented());\n      }\n\n    switch (fe->degree)\n      {\n      case 1:\n        error_filename += \"-q1\";\n        break;\n      case 2:\n        error_filename += \"-q2\";\n        break;\n      default:\n        Assert (false, ExcNotImplemented());\n      }\n\n    error_filename += \".tex\";\n    std::ofstream error_table_file(error_filename.c_str());\n\n    convergence_table.write_tex(error_table_file);\n\n\n    // @sect5{Further table manipulations}\n\n    // In case of global refinement, it might be of interest to also output\n    // the convergence rates. This may be done by the functionality the\n    // ConvergenceTable offers over the regular TableHandler. However, we do\n    // it only for global refinement, since for adaptive refinement the\n    // determination of something like an order of convergence is somewhat\n    // more involved. While we are at it, we also show a few other things that\n    // can be done with tables.\n    if (refinement_mode==global_refinement)\n      {\n        // The first thing is that one can group individual columns together\n        // to form so-called super columns. Essentially, the columns remain\n        // the same, but the ones that were grouped together will get a\n        // caption running across all columns in a group. For example, let's\n        // merge the \"cycle\" and \"cells\" columns into a super column named \"n\n        // cells\":\n        convergence_table.add_column_to_supercolumn(\"cycle\", \"n cells\");\n        convergence_table.add_column_to_supercolumn(\"cells\", \"n cells\");\n\n        // Next, it isn't necessary to always output all columns, or in the\n        // order in which they were originally added during the run.\n        // Selecting and re-ordering the columns works as follows (note that\n        // this includes super columns):\n        std::vector<std::string> new_order;\n        new_order.push_back(\"n cells\");\n        new_order.push_back(\"H1\");\n        new_order.push_back(\"L2\");\n        convergence_table.set_column_order (new_order);\n\n        // For everything that happened to the ConvergenceTable until this\n        // point, it would have been sufficient to use a simple\n        // TableHandler. Indeed, the ConvergenceTable is derived from the\n        // TableHandler but it offers the additional functionality of\n        // automatically evaluating convergence rates. For example, here is\n        // how we can let the table compute reduction and convergence rates\n        // (convergence rates are the binary logarithm of the reduction rate):\n        convergence_table\n        .evaluate_convergence_rates(\"L2\", ConvergenceTable::reduction_rate);\n        convergence_table\n        .evaluate_convergence_rates(\"L2\", ConvergenceTable::reduction_rate_log2);\n        convergence_table\n        .evaluate_convergence_rates(\"H1\", ConvergenceTable::reduction_rate_log2);\n        // Each of these function calls produces an additional column that is\n        // merged with the original column (in our example the `L2' and the\n        // `H1' column) to a supercolumn.\n\n        // Finally, we want to write this convergence chart again, first to\n        // the screen and then, in LaTeX format, to disk. The filename is\n        // again constructed as above.\n        std::cout << std::endl;\n        convergence_table.write_text(std::cout);\n\n        std::string conv_filename = \"convergence\";\n        switch (refinement_mode)\n          {\n          case global_refinement:\n            conv_filename += \"-global\";\n            break;\n          case adaptive_refinement:\n            conv_filename += \"-adaptive\";\n            break;\n          default:\n            Assert (false, ExcNotImplemented());\n          }\n        switch (fe->degree)\n          {\n          case 1:\n            conv_filename += \"-q1\";\n            break;\n          case 2:\n            conv_filename += \"-q2\";\n            break;\n          default:\n            Assert (false, ExcNotImplemented());\n          }\n        conv_filename += \".tex\";\n\n        std::ofstream table_file(conv_filename.c_str());\n        convergence_table.write_tex(table_file);\n      }\n  }\n\n  // The final step before going to <code>main()</code> is then to close the\n  // namespace <code>Step7</code> into which we have put everything we needed\n  // for this program:\n}\n\n// @sect3{Main function}\n\n// The main function is mostly as before. The only difference is that we solve\n// three times, once for Q1 and adaptive refinement, once for Q1 elements and\n// global refinement, and once for Q2 elements and global refinement.\n//\n// Since we instantiate several template classes below for two space\n// dimensions, we make this more generic by declaring a constant at the\n// beginning of the function denoting the number of space dimensions. If you\n// want to run the program in 1d or 2d, you will then only have to change this\n// one instance, rather than all uses below:\nint main ()\n{\n  const unsigned int dim = 2;\n\n  try\n    {\n      using namespace dealii;\n      using namespace Step7;\n\n      deallog.depth_console (0);\n\n      // Now for the three calls to the main class. Each call is blocked into\n      // curly braces in order to destroy the respective objects (i.e. the\n      // finite element and the HelmholtzProblem object) at the end of the\n      // block and before we go to the next run. This avoids conflicts with\n      // variable names, and also makes sure that memory is released\n      // immediately after one of the three runs has finished, and not only at\n      // the end of the <code>try</code> block.\n      {\n        std::cout << \"Solving with Q1 elements, adaptive refinement\" << std::endl\n                  << \"=============================================\" << std::endl\n                  << std::endl;\n\n        FE_Q<dim> fe(1);\n        HelmholtzProblem<dim>\n        helmholtz_problem_2d (fe, HelmholtzProblem<dim>::adaptive_refinement);\n\n        helmholtz_problem_2d.run ();\n\n        std::cout << std::endl;\n      }\n\n      {\n        std::cout << \"Solving with Q1 elements, global refinement\" << std::endl\n                  << \"===========================================\" << std::endl\n                  << std::endl;\n\n        FE_Q<dim> fe(1);\n        HelmholtzProblem<dim>\n        helmholtz_problem_2d (fe, HelmholtzProblem<dim>::global_refinement);\n\n        helmholtz_problem_2d.run ();\n\n        std::cout << std::endl;\n      }\n\n      {\n        std::cout << \"Solving with Q2 elements, global refinement\" << std::endl\n                  << \"===========================================\" << std::endl\n                  << std::endl;\n\n        FE_Q<dim> fe(2);\n        HelmholtzProblem<dim>\n        helmholtz_problem_2d (fe, HelmholtzProblem<dim>::global_refinement);\n\n        helmholtz_problem_2d.run ();\n\n        std::cout << std::endl;\n      }\n\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n\n\n// What comes here is basically just an annoyance that you can ignore if you\n// are not working on an AIX system: on this system, static member variables\n// are not instantiated automatically when their enclosing class is\n// instantiated. This leads to linker errors if these variables are not\n// explicitly instantiated. As said, this is, strictly C++ standards speaking,\n// not necessary, but it doesn't hurt either on other systems, and since it is\n// necessary to get things running on AIX, why not do it:\nnamespace Step7\n{\n  template const double SolutionBase<2>::width;\n}\n", "meta": {"hexsha": "4fb6bc7c48a3cdc4806c350e1ea2304331b67676", "size": 64855, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-7/step-7.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/step-7/step-7.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/step-7/step-7.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 46.962346126, "max_line_length": 91, "alphanum_fraction": 0.6591164906, "num_tokens": 14640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.41779157974921066}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n */\n\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n\n#include <boost/math/special_functions/factorials.hpp>\n\n#include \"Tudat/Mathematics/BasicMathematics/legendrePolynomials.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\nnamespace tudat\n{\nnamespace basic_mathematics\n{\n\n\n\n//! Default constructor, initializes cache object with 0 maximum degree and order.\nLegendreCache::LegendreCache( const bool useGeodesyNormalization )\n{\n    useGeodesyNormalization_  = useGeodesyNormalization;\n\n    if( useGeodesyNormalization_ )\n    {\n        legendrePolynomialFunction_ = geodesyNormalizedLegendrePolynomialFunction;\n    }\n    else\n    {\n        legendrePolynomialFunction_ = regularLegendrePolynomialFunction;\n    }\n\n    resetMaximumDegreeAndOrder( 1, 1 );\n\n    computeSecondDerivatives_ = 0;\n\n}\n\n//! Constructor\nLegendreCache::LegendreCache( const int maximumDegree, const int maximumOrder, const bool useGeodesyNormalization  )\n{\n    useGeodesyNormalization_  = useGeodesyNormalization;\n\n    if( useGeodesyNormalization_ )\n    {\n        legendrePolynomialFunction_ = geodesyNormalizedLegendrePolynomialFunction;\n    }\n    else\n    {\n        legendrePolynomialFunction_ = regularLegendrePolynomialFunction;\n    }\n\n    resetMaximumDegreeAndOrder( maximumDegree, maximumOrder );\n    computeSecondDerivatives_ = 0;\n}\n\n//! Get Legendre polynomial from cache when possible, and from direct computation otherwise.\nvoid LegendreCache::update( const double polynomialParameter  )\n{\n    // Check if cache needs update\n    if( !( polynomialParameter == currentPolynomialParameter_ ) )\n    {\n        currentPolynomialParameter_ = polynomialParameter;\n\n        // Set complement of argument (assuming it to be sine of latitude) cosine of latitude is always positive.\n        currentPolynomialParameterComplement_ = std::sqrt( 1.0 - polynomialParameter * polynomialParameter );\n\n        LegendreCache& thisReference = *this;\n\n        int jMax = -1;\n        for( int i = 0; i <= maximumDegree_; i++ )\n        {\n            jMax = std::min( i, maximumOrder_ );\n            for( int j = 0; j <= jMax ; j++ )\n            {\n                // Compute legendre polynomial\n                legendreValues_[ i * ( maximumOrder_ + 1 ) + j ] = legendrePolynomialFunction_( i, j, thisReference );\n\n                if( j != 0 )\n                {\n                    // Compute legendre polynomial derivative\n                    if( useGeodesyNormalization_ )\n                    {\n                        legendreDerivatives_[ i * ( maximumOrder_ + 1 ) + ( j - 1 ) ] =\n                                computeGeodesyLegendrePolynomialDerivative(\n                                    i, j - 1, currentPolynomialParameter_,\n                                    legendreValues_[ i * ( maximumOrder_ + 1 ) + ( j - 1 ) ],\n                                legendreValues_[ i * ( maximumOrder_ + 1 ) + j ],\n                                derivativeNormalizations_[ i * ( maximumOrder_ + 1 ) + ( j - 1 ) ] );\n                    }\n                    else\n                    {\n                        legendreDerivatives_[ i * ( maximumOrder_ + 1 ) + ( j - 1 ) ] =\n                                computeLegendrePolynomialDerivative(\n                                    j - 1, currentPolynomialParameter_,\n                                    legendreValues_[ i * ( maximumOrder_ + 1 ) + ( j - 1 ) ],\n                                legendreValues_[ i * ( maximumOrder_ + 1 ) + j ] );\n                    }\n\n                }\n            }\n\n            // Compute legendre polynomial derivative for i = j  (if needed)\n            if( jMax == i )\n            {\n                if( useGeodesyNormalization_ )\n                {\n                    legendreDerivatives_[ i * ( maximumOrder_ + 1 ) +  jMax ] =\n                            computeGeodesyLegendrePolynomialDerivative(\n                                i, jMax, currentPolynomialParameter_,\n                                legendreValues_[ i * ( maximumOrder_ + 1 ) + jMax ], 0.0,\n                            derivativeNormalizations_[ i * ( maximumOrder_ + 1 ) + jMax ] );\n                }\n                else\n                {\n                    legendreDerivatives_[ i * ( maximumOrder_ + 1 ) + jMax ] =\n                            computeLegendrePolynomialDerivative(\n                                jMax, currentPolynomialParameter_,\n                                legendreValues_[ i * ( maximumOrder_ + 1 ) + jMax ], 0.0 );\n                }\n            }\n        }\n\n        // Compute second derivatives of Legendre polynomials if needed\n        if( computeSecondDerivatives_ )\n        {\n            for( int i = 0; i <= maximumDegree_; i++ )\n            {\n                jMax = std::min( i, maximumOrder_ );\n                for( int j = 0; j <= jMax ; j++ )\n                {\n                    if( j != 0 )\n                    {\n                        // Compute legendre polynomial second derivatives\n                        if( useGeodesyNormalization_ )\n                        {\n                            legendreSecondDerivatives_[ i * ( maximumOrder_ + 1 ) + ( j - 1 ) ] =\n                                    computeGeodesyLegendrePolynomialSecondDerivative(\n                                        i, j - 1, currentPolynomialParameter_,\n                                        legendreValues_[ i * ( maximumOrder_ + 1 ) + ( j - 1 ) ],\n                                    legendreValues_[ i * ( maximumOrder_ + 1 ) + j ],\n                                    legendreDerivatives_[ i * ( maximumOrder_ + 1 ) + ( j - 1 ) ],\n                                    legendreDerivatives_[ i * ( maximumOrder_ + 1 ) + j ],\n                                    derivativeNormalizations_[ i * ( maximumOrder_ + 1 ) + ( j - 1 ) ] );\n                        }\n                        else\n                        {\n                            legendreSecondDerivatives_[ i * ( maximumOrder_ + 1 ) + ( j - 1 ) ] =\n                                    computeGeodesyLegendrePolynomialSecondDerivative(\n                                        i, j - 1, currentPolynomialParameter_,\n                                        legendreValues_[ i * ( maximumOrder_ + 1 ) + ( j - 1 ) ],\n                                    legendreValues_[ i * ( maximumOrder_ + 1 ) + j ],\n                                    legendreDerivatives_[ i * ( maximumOrder_ + 1 ) + ( j - 1 ) ],\n                                    legendreDerivatives_[ i * ( maximumOrder_ + 1 ) + j ], 1.0 );\n                        }\n\n                    }\n                }\n                // Compute legendre polynomial second derivative for i = j  (if needed)\n                if( jMax == i )\n                {\n                    if( useGeodesyNormalization_ )\n                    {\n                        legendreSecondDerivatives_[ i * ( maximumOrder_ + 1 ) +  jMax ] =\n                                computeGeodesyLegendrePolynomialSecondDerivative(\n                                    i, jMax, currentPolynomialParameter_,\n                                    legendreValues_[ i * ( maximumOrder_ + 1 ) + jMax ], 0.0,\n                                legendreDerivatives_[ i * ( maximumOrder_ + 1 ) + jMax ], 0.0,\n                                derivativeNormalizations_[ i * ( maximumOrder_ + 1 ) + jMax ] );\n                    }\n                    else\n                    {\n                        legendreSecondDerivatives_[ i * ( maximumOrder_ + 1 ) +  jMax ] =\n                                computeGeodesyLegendrePolynomialSecondDerivative(\n                                    i, jMax, currentPolynomialParameter_,\n                                    legendreValues_[ i * ( maximumOrder_ + 1 ) + jMax ], 0.0,\n                                legendreDerivatives_[ i * ( maximumOrder_ + 1 ) + jMax ], 0.0,\n                                1.0 );\n                    }\n                }\n\n            }\n        }\n    }\n}\n\n//! Update maximum degree and order of cache\nvoid LegendreCache::resetMaximumDegreeAndOrder( const int maximumDegree, const int maximumOrder )\n{\n    maximumDegree_ = maximumDegree;\n    maximumOrder_ = maximumOrder;\n\n    if( maximumOrder_ > maximumDegree_ )\n    {\n        maximumOrder_ = maximumDegree_;\n    }\n\n    legendreValues_.resize( ( maximumDegree_ + 1 ) * ( maximumOrder_ + 1 ) );\n    legendreDerivatives_.resize( ( maximumDegree_ + 1 ) * ( maximumOrder_ + 1 ) );\n    legendreSecondDerivatives_.resize( ( maximumDegree_ + 1 ) * ( maximumOrder_ + 1 ) );\n\n    derivativeNormalizations_.resize( ( maximumDegree_ + 1 ) * ( maximumOrder_ + 1 ) );\n\n    for( int i = 0; i <= maximumDegree_; i++ )\n    {\n        for( int j = 0; ( ( j <= i ) && ( j <= maximumOrder_ ) ) ; j++ )\n        {\n            // Compute normalization correction factor.\n            derivativeNormalizations_[ i * ( maximumOrder_ + 1 ) + j ] = std::sqrt(\n                        ( static_cast< double >( i + j + 1 ) )\n                        * ( static_cast< double >( i - j ) ) );\n\n            // If order is zero apply multiplication factor.\n            if ( j == 0 )\n            {\n                derivativeNormalizations_[ i * ( maximumOrder_ + 1 ) + j ] *= std::sqrt( 0.5 );\n            }\n        }\n    }\n\n    currentPolynomialParameter_ = TUDAT_NAN;\n    currentPolynomialParameterComplement_ = TUDAT_NAN;\n}\n\n\n//! Get Legendre polynomial value from the cache.\ndouble LegendreCache::getLegendrePolynomial(\n        const int degree, const int order )\n{\n    if( degree > maximumDegree_ || order > maximumOrder_ )\n    {\n        std::string errorMessage = \"Error when requesting legendre cache, maximum degree or order exceeded \" +\n                std::to_string( degree ) + \" \" +\n                std::to_string( maximumDegree_ ) + \" \" +\n                std::to_string( order ) + \" \" +\n                std::to_string( maximumOrder_ );\n        throw std::runtime_error( errorMessage );\n        return TUDAT_NAN;\n    }\n    else if( order > degree )\n    {\n        return 0.0;\n    }\n    else\n    {\n        return legendreValues_[ degree * ( maximumOrder_ + 1  ) + order ];\n    };\n}\n\n//! Get first derivative of Legendre polynomial value from the cache.\ndouble LegendreCache::getLegendrePolynomialDerivative(\n        const int degree, const int order )\n{\n    if( degree > ( maximumDegree_ ) || order > maximumOrder_ )\n    {\n        std::string errorMessage = \"Error when requesting legendre cache first derivatives, maximum degree or order exceeded \" +\n                std::to_string( degree ) + \" \" +\n                std::to_string( maximumDegree_ ) + \" \" +\n                std::to_string( order ) + \" \" +\n                std::to_string( maximumOrder_ );\n        throw std::runtime_error( errorMessage );\n        return TUDAT_NAN;\n    }\n    else if( order > degree )\n    {\n        return 0.0;\n    }\n    else\n    {\n        return legendreDerivatives_[ degree * ( maximumOrder_ + 1  ) + order ];\n    };\n}\n\n//! Get second derivative of Legendre polynomial value from the cache.\ndouble LegendreCache::getLegendrePolynomialSecondDerivative(\n        const int degree, const int order )\n{\n    if( degree > ( maximumDegree_  ) || order > maximumOrder_ )\n    {\n        std::string errorMessage = \"Error when requesting legendre cache second derivatives, maximum degree or order exceeded \" +\n                std::to_string( degree ) + \" \" +\n                std::to_string( maximumDegree_ ) + \" \" +\n                std::to_string( order ) + \" \" +\n                std::to_string( maximumOrder_ );\n        throw std::runtime_error( errorMessage );\n        return TUDAT_NAN;\n    }\n    else if( computeSecondDerivatives_ == 0 )\n    {\n        throw std::runtime_error( \"Error when requesting legendre cache second derivatives, no computations performed\" );\n    }\n    else if( order > degree )\n    {\n        return 0.0;\n    }\n    else\n    {\n        return legendreSecondDerivatives_[ degree * ( maximumOrder_ + 1  ) + order ];\n    };\n}\n\n//! Compute unnormalized associated Legendre polynomial.\ndouble computeLegendrePolynomialFromCache( const int degree,\n                                           const int order,\n                                           LegendreCache& legendreCache )\n{\n    if( legendreCache.getUseGeodesyNormalization( ) )\n    {\n        throw std::runtime_error( \"Error when computing Legendre polynomial, input uses normalization\" );\n    }\n\n    // If degree or order is negative...\n    if ( degree < 0 || order < 0 )\n    {\n        // Set error message.\n        std::stringstream errorMessage;\n        errorMessage << \"Error: the Legendre polynomial of = \" << degree << \" and order = \"\n                     << order << \" is undefined.\" << std::endl;\n\n        // Throw a run-time error.\n        throw std::runtime_error( errorMessage.str( ) );\n    }\n\n    // Else if order is greater than degree...\n    else if ( order > degree && degree >= 0 )\n    {\n        // Return zero.\n        return 0.0;\n    }\n\n    // Else if order and degree are lower than 2...\n    else if ( degree <= 1 && order <= 1 )\n    {\n        // Compute polynomial explicitly.\n        return computeLegendrePolynomialExplicit( degree, order, legendreCache.getCurrentPolynomialParameter( ) );\n    }\n\n    // Else if degree and order are sectoral...\n    else if ( degree == order )\n    {\n        // Obtain polynomial of degree one and order one.\n        const double degreeOneOrderOnePolynomial = legendreCache.getLegendrePolynomial(\n                    1, 1 );\n\n        // Obtain prior sectoral polynomial.\n        const double priorSectoralPolynomial = legendreCache.getLegendrePolynomial(\n                    degree - 1, order - 1 );\n\n        // Compute polynomial.\n        return computeLegendrePolynomialDiagonal(\n                    degree, degreeOneOrderOnePolynomial, priorSectoralPolynomial );\n    }\n\n    // Else degree and order are zonal/tessoral...\n    else\n    {\n        // Obtain prior degree polynomial.\n        const double oneDegreePriorPolynomial = legendreCache.getLegendrePolynomial(\n                    degree - 1, order );\n\n        // Obtain two degrees prior polynomial.\n        const double twoDegreesPriorPolynomial = legendreCache.getLegendrePolynomial(\n                    degree - 2, order );\n\n        // Compute polynomial.\n        return computeLegendrePolynomialVertical( degree,\n                                                  order,\n                                                  legendreCache.getCurrentPolynomialParameter( ),\n                                                  oneDegreePriorPolynomial,\n                                                  twoDegreesPriorPolynomial );\n    }\n}\n\n\ndouble computeLegendrePolynomial( const int degree,\n                                  const int order,\n                                  const double legendreParameter )\n{\n    LegendreCache legendreCache( degree, order, 0 );\n    legendreCache.update( legendreParameter );\n    return computeLegendrePolynomialFromCache( degree, order, legendreCache );\n}\n\n\n//! Compute geodesy-normalized associated Legendre polynomial.\ndouble computeGeodesyLegendrePolynomialFromCache( const int degree,\n                                                  const int order,\n                                                  LegendreCache& geodesyLegendreCache )\n{\n\n    if( !geodesyLegendreCache.getUseGeodesyNormalization( ) )\n    {\n        throw std::runtime_error( \"Error when computing Legendre polynomial, input uses no normalization\" );\n    }\n\n    // If degree or order is negative...\n    if ( degree < 0 || order < 0 )\n    {\n        // Set error message.\n        std::stringstream errorMessage;\n        errorMessage << \"Error: the Legendre polynomial of = \" << degree << \" and order = \"\n                     << order << \" is undefined.\" << std::endl;\n\n        // Throw a run-time error.\n        throw std::runtime_error( errorMessage.str( ) );\n    }\n\n    // Else if order is greater than degree...\n    else if ( order > degree && degree >= 0 )\n    {\n        // Return zero.\n        return 0.0;\n    }\n\n    // Else if order and degree are lower than 2...\n    else if ( degree <= 1 && order <= 1 )\n    {\n        // Compute polynomial explicitly.\n        return computeGeodesyLegendrePolynomialExplicit( degree, order, geodesyLegendreCache.getCurrentPolynomialParameter( ) );\n    }\n\n    // Else if degree and order are sectoral...\n    else if ( degree == order )\n    {\n        // Obtain polynomial of degree one and order one.\n        double degreeOneOrderOnePolynomial = geodesyLegendreCache.getLegendrePolynomial(\n                    1, 1 );\n\n        // Obtain prior sectoral polynomial.\n        double priorSectoralPolynomial = geodesyLegendreCache.getLegendrePolynomial(\n                    degree - 1, order - 1 );\n\n        // Compute polynomial.\n        return computeGeodesyLegendrePolynomialDiagonal(\n                    degree, degreeOneOrderOnePolynomial, priorSectoralPolynomial );\n    }\n\n    // Else degree and order are zonal/tessoral...\n    else\n    {\n        // Obtain prior degree polynomial.\n        double oneDegreePriorPolynomial = geodesyLegendreCache.getLegendrePolynomial(\n                    degree - 1, order );\n\n        // Obtain two degrees prior polynomial.\n        double twoDegreesPriorPolynomial = geodesyLegendreCache.getLegendrePolynomial(\n                    degree - 2, order );\n\n        // Compute polynomial.\n        return computeGeodesyLegendrePolynomialVertical( degree,\n                                                         order,\n                                                         geodesyLegendreCache.getCurrentPolynomialParameter( ),\n                                                         oneDegreePriorPolynomial,\n                                                         twoDegreesPriorPolynomial );\n    }\n}\n\n//! Compute geodesy-normalized associated Legendre polynomial.\ndouble computeGeodesyLegendrePolynomial( const int degree,\n                                         const int order,\n                                         const double legendreParameter )\n{\n    LegendreCache legendreCache( degree, order, 1 );\n    legendreCache.update( legendreParameter );\n    return computeGeodesyLegendrePolynomialFromCache( degree, order, legendreCache );\n}\n\n//! Compute derivative of unnormalized Legendre polynomial.\ndouble computeLegendrePolynomialDerivative( const int order,\n                                            const double polynomialParameter,\n                                            const double currentLegendrePolynomial,\n                                            const double incrementedLegendrePolynomial )\n{\n    // Return polynomial derivative.\n    return incrementedLegendrePolynomial\n            / std::sqrt( 1.0 - polynomialParameter * polynomialParameter )\n            - static_cast< double >( order ) * polynomialParameter\n            / ( 1.0 - polynomialParameter * polynomialParameter )\n            * currentLegendrePolynomial;\n}\n\n//! Compute derivative of geodesy-normalized Legendre polynomial.\ndouble computeGeodesyLegendrePolynomialDerivative( const int degree,\n                                                   const int order,\n                                                   const double polynomialParameter,\n                                                   const double currentLegendrePolynomial,\n                                                   const double incrementedLegendrePolynomial,\n                                                   const double normalizationCorrection )\n{\n    // Return polynomial derivative.\n    return normalizationCorrection * incrementedLegendrePolynomial\n            / std::sqrt( 1.0 - polynomialParameter * polynomialParameter )\n            - static_cast< double >( order ) * polynomialParameter\n            / ( 1.0 - polynomialParameter * polynomialParameter )\n            * currentLegendrePolynomial;\n}\n\n//! Compute derivative of geodesy-normalized Legendre polynomial.\ndouble computeGeodesyLegendrePolynomialDerivative( const int degree,\n                                                   const int order,\n                                                   const double polynomialParameter,\n                                                   const double currentLegendrePolynomial,\n                                                   const double incrementedLegendrePolynomial )\n{\n    // Compute normalization correction factor.\n    double normalizationCorrection = std::sqrt(\n                ( static_cast< double >( degree + order + 1 ) )\n                * ( static_cast< double >( degree - order ) ) );\n\n    // If order is zero apply multiplication factor.\n    if ( order == 0 )\n    {\n        normalizationCorrection *= std::sqrt( 0.5 );\n    }\n\n    // Return polynomial derivative.\n    return computeGeodesyLegendrePolynomialDerivative(\n                degree, order, polynomialParameter, currentLegendrePolynomial,\n                incrementedLegendrePolynomial, normalizationCorrection );\n}\n\n//! Compute second derivative of geodesy-normalized associated Legendre polynomial.\ndouble computeGeodesyLegendrePolynomialSecondDerivative( const int degree,\n                                                         const int order,\n                                                         const double polynomialParameter,\n                                                         const double currentLegendrePolynomial,\n                                                         const double incrementedLegendrePolynomial,\n                                                         const double currentLegendrePolynomialDerivative,\n                                                         const double incrementedLegendrePolynomialDerivative,\n                                                         const double normalizationCorrection )\n{\n    double polynomialParameterSquare = polynomialParameter * polynomialParameter;\n\n    // Return polynomial derivative.\n    return normalizationCorrection * (\n                incrementedLegendrePolynomialDerivative / std::sqrt( 1.0 - polynomialParameterSquare ) +\n                polynomialParameter * std::pow( 1.0 - polynomialParameterSquare, -1.5 ) * incrementedLegendrePolynomial ) -\n            static_cast< double >( order ) *\n            ( polynomialParameter / ( 1.0 - polynomialParameter * polynomialParameter ) * currentLegendrePolynomialDerivative +\n              ( 1.0 + polynomialParameterSquare ) / ( ( 1.0 - polynomialParameterSquare ) * ( 1.0 - polynomialParameterSquare ) ) * currentLegendrePolynomial );\n}\n\n\n//! Compute low degree/order unnormalized Legendre polynomial explicitly.\ndouble computeLegendrePolynomialExplicit( const int degree,\n                                          const int order,\n                                          const double polynomialParameter )\n{\n    // Check which order is required for Legendre polynomial.\n    switch( degree )\n    {\n    case 0:\n        switch( order )\n        {\n        case 0:\n            return 1.0;\n        default:\n        {\n            std::string errorMessage = \"Error, explicit legendre polynomial not possible for \" +\n                    std::to_string( degree ) + \", \" +\n                    std::to_string( order );\n            throw std::runtime_error( errorMessage );\n        }\n        }\n        break;\n    case 1:\n        switch( order )\n        {\n        case 0:\n            return polynomialParameter;\n        case 1:\n            return std::sqrt( 1 - polynomialParameter * polynomialParameter );\n        default:\n        {\n            std::string errorMessage = \"Error, explicit legendre polynomial not possible for \" +\n                    std::to_string( degree ) + \", \" +\n                    std::to_string( order );\n            throw std::runtime_error( errorMessage );\n        }\n        }\n        break;\n    case 2:\n        switch( order )\n        {\n        case 0:\n            return 0.5 * ( 3.0 * polynomialParameter * polynomialParameter - 1.0 );\n        case 1:\n            return 3.0 * polynomialParameter\n                    * std::sqrt( 1.0 - polynomialParameter * polynomialParameter );\n        case 2:\n            return 3.0 * ( 1.0 - polynomialParameter * polynomialParameter );\n        default:\n        {\n            std::string errorMessage = \"Error, explicit legendre polynomial not possible for \" +\n                    std::to_string( degree ) + \", \" +\n                    std::to_string( order );\n            throw std::runtime_error( errorMessage );\n        }\n        }\n        break;\n    case 3:\n        switch( order )\n        {\n        case 0:\n            return 0.5 * polynomialParameter\n                    * ( 5.0 * polynomialParameter * polynomialParameter - 3.0 );\n        case 1:\n            return 1.5 * ( 5.0 * polynomialParameter * polynomialParameter - 1.0 )\n                    * std::sqrt( 1.0 - polynomialParameter * polynomialParameter );\n        case 2:\n            return 15.0 * polynomialParameter * ( 1.0 - polynomialParameter * polynomialParameter );\n        case 3:\n            return 15.0 * ( 1.0 - polynomialParameter * polynomialParameter )\n                    * std::sqrt( 1.0 - polynomialParameter * polynomialParameter );\n        default:\n        {\n            std::string errorMessage = \"Error, explicit legendre polynomial not possible for \" +\n                    std::to_string( degree ) + \", \" +\n                    std::to_string( order );\n            throw std::runtime_error( errorMessage );\n        }\n        }\n        break;\n    case 4:\n        switch( order )\n        {\n        case 0:\n            return ( 35.0 * polynomialParameter * polynomialParameter\n                     * polynomialParameter * polynomialParameter\n                     - 30.0 * polynomialParameter * polynomialParameter + 3.0 ) / 8.0;\n        case 1:\n            return -2.5 * ( 7.0 * polynomialParameter * polynomialParameter * polynomialParameter\n                            - 3.0 * polynomialParameter )\n                    * std::sqrt( 1.0 - polynomialParameter * polynomialParameter );\n        case 2:\n            return 15.0 / 2.0 * ( - 1.0 + 7.0 * polynomialParameter * polynomialParameter )\n                    * ( 1.0 - polynomialParameter * polynomialParameter );\n        case 3:\n            return -105.0 * polynomialParameter * ( 1.0 - polynomialParameter * polynomialParameter )\n                    * std::sqrt( 1.0 - polynomialParameter * polynomialParameter );\n        case 4:\n            return 105.0 * ( 1.0 - polynomialParameter * polynomialParameter )\n                    * ( 1.0 - polynomialParameter * polynomialParameter );\n\n        default:\n        {\n            std::string errorMessage = \"Error, explicit legendre polynomial not possible for \" +\n                    std::to_string( degree ) + \", \" +\n                    std::to_string( order );\n            throw std::runtime_error( errorMessage );\n        }\n        }\n        break;\n    default:\n    {\n        std::string errorMessage = \"Error, explicit legendre polynomial not possible for \" +\n                std::to_string( degree ) + \", \" +\n                std::to_string( order );\n        throw std::runtime_error( errorMessage );\n    }\n    }\n    return TUDAT_NAN;\n}\n\n//! Compute low degree/order geodesy-normalized Legendre polynomials explicitly.\ndouble computeGeodesyLegendrePolynomialExplicit( const int degree,\n                                                 const int order,\n                                                 const double polynomialParameter )\n{\n    // If 0,0 term is requested return Legendre polynomial value.\n    if ( degree == 0 && order == 0 )\n    {\n        return 1.0;\n    }\n\n    // Else if 1,0 term is requested return polynomial value.\n    else if ( degree == 1 && order == 0 )\n    {\n        return std::sqrt( 3.0 ) * polynomialParameter;\n    }\n\n    // Else if 1,1 term is requested return polynomial value.\n    else if ( degree == 1 && order == 1 )\n    {\n        return std::sqrt( 3.0 - 3.0 * polynomialParameter * polynomialParameter );\n    }\n\n    // Else the requested term cannot be computed; throw a run-time error.\n    else\n    {\n        // Set error message.\n        std::stringstream errorMessage;\n        errorMessage  <<  \"Error: computation of Legendre polynomial of = \"  <<  degree\n                       <<  \" and order = \"  <<  order  <<  \" is not supported.\"  <<  std::endl;\n\n        // Throw a run-time error.\n        throw std::runtime_error( errorMessage.str( ) );\n    }\n}\n\n//! Compute unnormalized Legendre polynomial through sectoral recursion.\ndouble computeLegendrePolynomialDiagonal( const int degree,\n                                          const double degreeOneOrderOnePolynomial,\n                                          const double priorSectoralPolynomial )\n{\n    // Return polynomial.\n    return ( 2.0 * static_cast< double >( degree ) - 1.0 )\n            * degreeOneOrderOnePolynomial * priorSectoralPolynomial;\n\n}\n\n//! Compute geodesy-normalized Legendre polynomial through sectoral recursion.\ndouble computeGeodesyLegendrePolynomialDiagonal( const int degree,\n                                                 const double degreeOneOrderOnePolynomial,\n                                                 const double priorSectoralPolynomial )\n{\n    // Return polynomial.\n    return std::sqrt( ( 2.0 * static_cast< double >( degree ) + 1.0 )\n                      / ( 6.0 * static_cast< double >( degree ) ) )\n            * degreeOneOrderOnePolynomial * priorSectoralPolynomial;\n}\n\n//! Compute unnormalized Legendre polynomial through degree recursion.\ndouble computeLegendrePolynomialVertical( const int degree,\n                                          const int order,\n                                          const double polynomialParameter,\n                                          const double oneDegreePriorPolynomial,\n                                          const double twoDegreesPriorPolynomial )\n{\n    // Return polynomial.\n    return ( ( 2.0 * static_cast< double >( degree ) - 1.0 ) * polynomialParameter\n             * oneDegreePriorPolynomial - ( static_cast< double >( degree + order ) - 1.0 )\n             * twoDegreesPriorPolynomial ) / ( static_cast< double >( degree - order ) );\n}\n\n//! Compute geodesy-normalized Legendre polynomial through degree recursion.\ndouble computeGeodesyLegendrePolynomialVertical( const int degree,\n                                                 const int order,\n                                                 const double polynomialParameter,\n                                                 const double oneDegreePriorPolynomial,\n                                                 const double twoDegreesPriorPolynomial )\n{\n    // Return polynomial.\n    return std::sqrt( ( 2.0 * static_cast< double >( degree ) + 1.0 )\n                      / ( ( static_cast< double >( degree + order ) ) * ( static_cast< double >( degree - order ) ) ) )\n            * ( std::sqrt( 2.0 * static_cast< double >( degree ) - 1.0 ) * polynomialParameter * oneDegreePriorPolynomial\n                - std::sqrt( ( static_cast< double >( degree + order ) - 1.0 )\n                             * ( static_cast< double >( degree - order ) - 1.0 )\n                             / ( 2.0 * static_cast< double >( degree ) - 3.0 ) )\n                * twoDegreesPriorPolynomial );\n}\n\n//! Function to calculate the normalization factor for Legendre polynomials to geodesy-normalized.\ndouble calculateLegendreGeodesyNormalizationFactor( const int degree, const int order )\n{\n\n    double deltaFunction = 0.0;\n    if( order == 0 )\n    {\n        deltaFunction = 1.0;\n    }\n\n    double factor = std::sqrt(\n                boost::math::factorial< double >( static_cast< double >( degree + order ) )\n                / ( ( 2.0 - deltaFunction ) * ( 2.0 * static_cast< double >( degree ) + 1.0 )\n                    * boost::math::factorial< double >( static_cast< double >( degree - order ) ) ) );\n    return 1.0 / factor;\n}\n\n//! Function to convert unnormalized to geodesy-normalized (4-pi normalized) spherical harmonic coefficients\nvoid convertUnnormalizedToGeodesyNormalizedCoefficients(\n        const Eigen::MatrixXd& unnormalizedCosineCoefficients,\n        const Eigen::MatrixXd& unnormalizedSineCoefficients,\n        Eigen::MatrixXd& normalizedCosineCoefficients,\n        Eigen::MatrixXd& normalizedSineCoefficients )\n{\n    normalizedCosineCoefficients.setZero( unnormalizedCosineCoefficients.rows( ), unnormalizedCosineCoefficients.cols( ) );\n    normalizedSineCoefficients.setZero( unnormalizedSineCoefficients.rows( ), unnormalizedCosineCoefficients.cols( ) );\n\n    double normalizationFactor;\n\n    for( unsigned degree = 0 ; degree < unnormalizedCosineCoefficients.rows( ); degree++ )\n    {\n        for( unsigned order = 0 ; ( order < unnormalizedCosineCoefficients.cols( ) && order <= degree ); order++ )\n        {\n            normalizationFactor = calculateLegendreGeodesyNormalizationFactor( degree, order );\n            normalizedCosineCoefficients( degree, order ) = unnormalizedCosineCoefficients( degree, order ) /\n                    normalizationFactor;\n            normalizedSineCoefficients( degree, order ) = unnormalizedSineCoefficients( degree, order ) /\n                    normalizationFactor;\n        }\n    }\n}\n\n//! Function to convert geodesy-normalized (4-pi normalized) to unnormalized spherical harmonic coefficients\nvoid convertGeodesyNormalizedToUnnormalizedCoefficients(\n        const Eigen::MatrixXd& normalizedCosineCoefficients,\n        const Eigen::MatrixXd& normalizedSineCoefficients,\n        Eigen::MatrixXd& unnormalizedCosineCoefficients,\n        Eigen::MatrixXd& unnormalizedSineCoefficients )\n{\n    unnormalizedCosineCoefficients.setZero( normalizedCosineCoefficients.rows( ), normalizedCosineCoefficients.cols( ) );\n    unnormalizedSineCoefficients.setZero( normalizedSineCoefficients.rows( ), normalizedSineCoefficients.cols( ) );\n\n    double normalizationFactor;\n\n    for( unsigned degree = 0 ; degree < unnormalizedCosineCoefficients.rows( ); degree++ )\n    {\n        for( unsigned order = 0 ; ( order < unnormalizedCosineCoefficients.cols( ) && order <= degree ); order++ )\n        {\n            normalizationFactor = calculateLegendreGeodesyNormalizationFactor( degree, order );\n            unnormalizedCosineCoefficients( degree, order ) = normalizedCosineCoefficients( degree, order ) *\n                    normalizationFactor;\n            unnormalizedSineCoefficients( degree, order ) = normalizedSineCoefficients( degree, order ) *\n                    normalizationFactor;\n        }\n    }\n}\n\n//! Function to convert unnormalized to geodesy-normalized (4-pi normalized) spherical harmonic coefficients\nvoid geodesyNormalizeUnnormalizedCoefficients(\n        Eigen::MatrixXd& cosineCoefficients,\n        Eigen::MatrixXd& sineCoefficients )\n{\n    double normalizationFactor;\n\n    for( unsigned degree = 0 ; degree < cosineCoefficients.rows( ); degree++ )\n    {\n        for( unsigned order = 0 ; ( order < sineCoefficients.cols( ) && order <= degree ); order++ )\n        {\n            normalizationFactor = calculateLegendreGeodesyNormalizationFactor( degree, order );\n            cosineCoefficients( degree, order ) /=  normalizationFactor;\n            sineCoefficients( degree, order ) /=  normalizationFactor;\n        }\n    }\n}\n\n} // namespace basic_mathematics\n} // namespace tudat\n", "meta": {"hexsha": "3c7da49836d55a858ca73e1b4e9158f89040d42c", "size": 35698, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/legendrePolynomials.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Mathematics/BasicMathematics/legendrePolynomials.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Mathematics/BasicMathematics/legendrePolynomials.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.0471142521, "max_line_length": 160, "alphanum_fraction": 0.5601714382, "num_tokens": 7426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.41778720172083267}}
{"text": "#ifndef FSTCLASSIFIERMULTINOMNAIVEBAYES_H\n#define FSTCLASSIFIERMULTINOMNAIVEBAYES_H\n\n/*!======================================================================\n   Feature Selection Toolbox 3 source code\n   ---------------------------------------\n\t\n   \\file    classifier_multinom_naivebayes.hpp\n   \\brief   Implements Naive-like Bayes classifier based on multinomial model\n   \\author  Petr Somol (somol@utia.cas.cz) with collaborators, see Contacts at http://fst.utia.cz\n   \\date    March 2011\n   \\version 3.1.0.beta\n   \\note    FST3 was developed using gcc 4.3 and requires\n   \\note    \\li Boost library (http://www.boost.org/, tested with versions 1.33.1 and 1.44),\n   \\note    \\li (\\e optionally) LibSVM (http://www.csie.ntu.edu.tw/~cjlin/libsvm/, \n                tested with version 3.00)\n   \\note    Note that LibSVM is required for SVM related tools only,\n            as demonstrated in demo12t.cpp, demo23.cpp, demo25t.cpp, demo32t.cpp, etc.\n\n*/ /* \n=========================================================================\nCopyright:\n  * FST3 software (with exception of any externally linked libraries) \n    is copyrighted by Institute of Information Theory and Automation (UTIA), \n    Academy of Sciences of the Czech Republic.\n  * FST3 source codes as presented here do not contain code of third parties. \n    FST3 may need linkage to external libraries to exploit its functionality\n    in full. For details on obtaining and possible usage restrictions \n    of external libraries follow their original sources (referenced from\n    FST3 documentation wherever applicable).\n  * FST3 software is available free of charge for non-commercial use. \n    Please address all inquires concerning possible commercial use \n    of FST3, or if in doubt, to FST3 maintainer (see http://fst.utia.cz)\n  * Derivative works based on FST3 are permitted as long as they remain\n    non-commercial only.\n  * Re-distribution of FST3 software is not allowed without explicit\n    consent of the copyright holder.\nDisclaimer of Warranty:\n  * FST3 software is presented \"as is\", without warranty of any kind, \n    either expressed or implied, including, but not limited to, the implied \n    warranties of merchantability and fitness for a particular purpose. \n    The entire risk as to the quality and performance of the program \n    is with you. Should the program prove defective, you assume the cost \n    of all necessary servicing, repair or correction.\nLimitation of Liability:\n  * The copyright holder will in no event be liable to you for damages, \n    including any general, special, incidental or consequential damages \n    arising out of the use or inability to use the code (including but not \n    limited to loss of data or data being rendered inaccurate or losses \n    sustained by you or third parties or a failure of the program to operate \n    with any other programs).\n========================================================================== */\n\n#include <boost/smart_ptr.hpp>\n#include <iostream>\n#include <sstream>\n#include <cmath>\n#include <cstring> // memcpy\n#include \"error.hpp\"\n#include \"global.hpp\"\n#include \"classifier.hpp\"\n#include \"model_multinom.hpp\"\n\n/*============== Template parameter type naming conventions ==============\n--------- Numeric types: -------------------------------------------------\nDATATYPE - data sample values - usually real numbers (but may be integers\n          in text processing etc.)\nREALTYPE - must be real numbers - for representing intermediate results of \n          calculations like mean, covariance etc.\nIDXTYPE - index values for enumeration of data samples - (nonnegative) integers, \n          extent depends on numbers of samples in data\nDIMTYPE - index values for enumeration of features (dimensions), or classes (not \n          class sizes) - (nonnegative) integers, usually lower extent than IDXTYPE, \n          but be aware of expressions like _classes*_features*_features ! \n          in linearized representations of feature matrices for all classes\nBINTYPE - feature selection marker type - represents ca. <10 different feature \n          states (selected, deselected, sel./desel. temporarily 1st nested loop, 2nd...)\nRETURNTYPE - criterion value: real value, but may be extended in future to support \n          multiple values \n--------- Class types: ---------------------------------------------------\nSUBSET       - class of class type Subset \nCLASSIFIER   - class implementing interface defined in abstract class Classifier \nEVALUATOR    - class implementing interface defined in abstract class Sequential_Step \nDISTANCE     - class implementing interface defined in abstract class Distance \nDATAACCESSOR - class implementing interface defined in abstract class Data_Accessor \nINTERVALCONTAINER - class of class type TIntervaller \nCONTAINER    - STL container of class type TInterval  \n========================================================================== */\n\nnamespace FST {\n\n/*! \\brief Implements Naive-like Bayes classifier based on multinomial model */\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nclass Classifier_Multinomial_NaiveBayes : public Classifier<RETURNTYPE,DIMTYPE,SUBSET,DATAACCESSOR> { // abstract class\n\t// \\note In this case the classifier should be better called Naive-like Bayes than Naive Bayes\npublic:\n\ttypedef boost::shared_ptr<DATAACCESSOR> PDataAccessor;\n\ttypedef boost::shared_ptr<SUBSET> const PSubset;\n\ttypedef typename DATAACCESSOR::PPattern PPattern;\n\tClassifier_Multinomial_NaiveBayes();\n\tvirtual ~Classifier_Multinomial_NaiveBayes() {notify(\"Classifier_Multinomial_NaiveBayes destructor.\");}\n\n\t/*! pre-learning mode: \n\t    if true, calls once _model->learn() for full set size and later in train() uses only narrow()ing to access submatrixes\n\t             (makes sense only as long as training data do not change, i.e., within one split)\n\t    if false (default), learns new model in each train() call \n\t*/\n\tvoid enable_prelearn_mode(const PDataAccessor da);\n\tvoid disable_prelearn_mode() {_prelearn_mode=false;}\n\tbool get_prelearn_mode() const {return _prelearn_mode;}\n\n\t// NOTE: must! be called before train() or test() calls whenever the training set changes (i.e., with changing da Splits)\n\tvoid initialize(const PDataAccessor da); // must be called to pre-compute mean[] and cov[]\n\n\tvirtual bool classify(DIMTYPE &cls, const PPattern &pattern);  // classifies pattern, returns the respective class index\n\tvirtual bool train(const PDataAccessor da, const PSubset sub); // learns from designated training part of data\n\tvirtual bool test(RETURNTYPE &result, const PDataAccessor da); // estimates accuracy using designated test data\n\t\n\tDIMTYPE get_n() const {assert(_model); return _model->get_n();}\n\tDIMTYPE get_d() const {assert(_model); return _model->get_d();}\n\n\tClassifier_Multinomial_NaiveBayes* clone() const;\n\tClassifier_Multinomial_NaiveBayes* sharing_clone() const {throw fst_error(\"Classifier_Multinomial_NaiveBayes::sharing_clone() not supported, use Classifier_Multinomial_NaiveBayes::clone() instead.\");}\n\tClassifier_Multinomial_NaiveBayes* stateless_clone() const {throw fst_error(\"Classifier_Multinomial_NaiveBayes::stateless_clone() not supported, use Classifier_Multinomial_NaiveBayes::clone() instead.\");}\n\t\n\tvirtual std::ostream& print(std::ostream& os) const {os << \"Classifier_Multinomial_NaiveBayes()\"; return os;}\nprivate:\n\tClassifier_Multinomial_NaiveBayes(const Classifier_Multinomial_NaiveBayes& cmnb); // copy-constructor \nprotected:\n\tboost::scoped_ptr<Model_Multinomial<DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> > _model;\n\n\tDIMTYPE _classes, _features; // size of arrays below\n\tboost::scoped_array<REALTYPE> _Pcd; // P(class|document) (lazy allocation)\n\nprivate:\n\tbool _prelearn_mode;\n\tboost::scoped_array<DIMTYPE> _index;\n\tDIMTYPE _subfeatures;\n};\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nClassifier_Multinomial_NaiveBayes<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::Classifier_Multinomial_NaiveBayes(const Classifier_Multinomial_NaiveBayes& cmnb) :\n\t_classes(cmnb._classes),\n\t_features(cmnb._features),\n\t_prelearn_mode(cmnb._prelearn_mode),\n\t_subfeatures(cmnb._subfeatures)\n{\n\tnotify(\"Classifier_Multinomial_NaiveBayes copy-constructor.\");\n\tif(cmnb._model) _model.reset(new Model_Multinomial<DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>(*cmnb._model));\n\tif(_classes>0)\n\t{\n\t\t_Pcd.reset(new REALTYPE[_classes]); memcpy((void *)_Pcd.get(),(void *)(cmnb._Pcd).get(),sizeof(REALTYPE)*_classes);\n\t}\n\t_index.reset(new DIMTYPE[_features]); memcpy((void *)_index.get(),(void *)(cmnb._index).get(),sizeof(DIMTYPE)*_features);\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nClassifier_Multinomial_NaiveBayes<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>* Classifier_Multinomial_NaiveBayes<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::clone() const\n{\n\tClassifier_Multinomial_NaiveBayes<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> *clone=new Classifier_Multinomial_NaiveBayes<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>(*this);\n\tclone->set_cloned();\n\treturn clone;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nClassifier_Multinomial_NaiveBayes<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::Classifier_Multinomial_NaiveBayes()\n{\n\tnotify(\"Classifier_Multinomial_NaiveBayes constructor.\");\n\t_model.reset(new Model_Multinomial<DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>);\n\t_classes=0;\n\t_features=0;\n\t_subfeatures=0;\n\t_prelearn_mode=false;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Classifier_Multinomial_NaiveBayes<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::enable_prelearn_mode(const PDataAccessor da)\n{\n\tnotify(\"Classifier_Multinomial_NaiveBayes::init_prelearn_mode().\");\n\tassert(_model);\n\tassert(da);\n\tassert(da->getNoOfFeatures()>0);\n\tassert(da->getNoOfClasses()>0);\n\t_model->learn(da);\n\t_prelearn_mode=true;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nvoid Classifier_Multinomial_NaiveBayes<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::initialize(PDataAccessor da)\n{\n\tnotify(\"Classifier_Multinomial_NaiveBayes::initialize().\");\n\t//assert(_model);\n\tassert(da);\n\tassert(da->getNoOfFeatures()>0);\n\tassert(da->getNoOfClasses()>0);\n\t\n\tif(!_Pcd || _classes!=da->getNoOfClasses()) _Pcd.reset(new REALTYPE[da->getNoOfClasses()]);\n\t_classes=da->getNoOfClasses();\n\n\tif(!_index || _features!=da->getNoOfFeatures()) _index.reset(new DIMTYPE[da->getNoOfFeatures()]);\n\t_features=da->getNoOfFeatures();\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Classifier_Multinomial_NaiveBayes<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::train(const PDataAccessor da, const PSubset sub)\n{\n\t// NOTE: mean[] and cov[] must be pre-computed using initialize()\n\t// NOTE: explicit call is needed here to ensure wrapper functionality\n\t//       but a work-aroung can be implemented to optionally disable the call\n\t//       (would make sense when testing different subsets for the same da split)\n\tinitialize(da);\n\t\n\tnotify(\"Classifier_Multinomial_NaiveBayes::train().\");\n\tassert(_model);\n\tassert(da);\n\tif(_prelearn_mode) assert(get_n()>0);\n\tassert(da->getNoOfFeatures()>0);\n\tassert(sub);\n\tassert(sub->get_frozen_mode()==false);\n\tif(_prelearn_mode) assert(sub->get_n_raw()==get_n());\n\t//{\n\t//\tostringstream sos;\n\t//\tsos << \"sub->get_n_raw()=\"<<sub->get_n_raw() << \" da->getNoOfFeatures()=\"<<da->getNoOfFeatures() << std::endl;\n\t//\tsyncout::print(std::cout,sos);\n\t//}\n\tassert(sub->get_n_raw()==da->getNoOfFeatures());\n\t\n\tif(_prelearn_mode) _model->narrow_to(sub); // assume _n-dimensional model is pre-learned and needs to be narrow()ed only (NOTE: training data must not change since)\n\telse {_model->learn(da,sub); _model->denarrow();} // re-learn from scratch, training data has changed (i.e., after switch to next data split)\n\n//\tif(sub->get_d_raw()==1) // ??? single feature subsets can not be used for multinomial model based classification\n//\t{\n//\t}\n\n\t// prepare feature subset index buffering\n\tDIMTYPE f;\n\tbool b;\n\tfor(b=sub->getFirstFeature(f),_subfeatures=0;b==true;b=sub->getNextFeature(f),_subfeatures++) {assert(_subfeatures<get_n()); _index[_subfeatures]=f;}\n\t\n\t_model->compute_theta(); //thetas to be used in classify() and test()\n\t\n#ifdef DEBUG\n\t{ostringstream sos; sos << \"index: \"; for(f=0;f<_subfeatures;f++) sos << _index[f] << \" \"; syncout::print(std::cout,sos);}\n#endif\n\tassert(_subfeatures==sub->get_d_raw());\n\treturn true;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Classifier_Multinomial_NaiveBayes<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::classify(DIMTYPE &cls, const PPattern &pattern)\n{\n\t// NOTE: mean[] and cov[] must be pre-computed using initialize()\n\t// NOTE: _inverse[] _det[] and _constant[] must be pre-computed\n\tnotify(\"Classifier_Multinomial_NaiveBayes::test().\");\n\tassert(_model);\n\tif(_prelearn_mode) assert(get_n()>0);\n\tassert(_model->get_classes()>1);\n\tassert(_classes==_model->get_classes());\n\tassert(_index);\n\tassert(_subfeatures==_model->get_d());\n\tif(!_prelearn_mode) assert(_subfeatures==_model->get_n());\n\tassert(_subfeatures>0);\n\t\t\n\tDIMTYPE f;\n\tDIMTYPE c_cand;\n\tREALTYPE res;\n\tDIMTYPE wTH;\n\tREALTYPE *theta=&(_model->get_theta()[0]); // dirty, but this object owns _model thus no memory corruption is possible\n\tREALTYPE *theta_tmp;\n\n\tif(_subfeatures==1) { \n\t\t// NOTE: single features are unusable for classification because theta=1 in each class,\n\t\t//       thus log(theta)=0 and consequently Pcd[] does not depend on feature frequency\n\t\tcls=0; // consider all single features equally unusable\n\t\treturn false;\n\t} else {\n\t\t// compute P(c|pattern) for each class\n\t\twTH=0;\n\t\tfor(c_cand=0;c_cand<_classes;c_cand++)\n\t\t{\n\t\t\ttheta_tmp=&theta[wTH];\n\t\t\tres=0.0;\n\t\t\tfor(f=0;f<_subfeatures;f++)\n\t\t\t{\n\t\t\t\t//{\n\t\t\t\t//\tostringstream sos; sos << \"f:\" << _index[f] << \" ptmp[]=\" << (REALTYPE)ptmp[_index[f]] << \", theta=\" << _model->get_theta()[wTH+f] << \", log=\" << log(_model->get_theta()[wTH+f]) << std::endl;\n\t\t\t\t//\tsyncout::print(std::cout,sos);\n\t\t\t\t//}\n\t\t\t\tres+=(REALTYPE)pattern[_index[f]] * log(theta_tmp[f]);\n\t\t\t}\n\t\t\t_Pcd[c_cand]=log(_model->get_Pc(c_cand))+res;\n\t\t\t//{\n\t\t\t//\tostringstream sos; sos << \" Pc[\"<<c_cand<<\"]=\" << _model->get_Pc(c_cand) << \", log(Pc)=\" << log(_model->get_Pc(c_cand)) << \", res=\"<< res << \", _Pcd[]=\" << _Pcd[c_cand] << std::endl << std::endl;\n\t\t\t//\tsyncout::print(std::cout,sos);\n\t\t\t//}\n\t\t\twTH+=_subfeatures;\n\t\t}\n\t\t// find maximum P[c|pattern]\n\t\tres=_Pcd[0]; cls=0;\n\t\tfor(c_cand=1;c_cand<_classes;c_cand++) if(_Pcd[c_cand]>res) {res=_Pcd[c_cand]; cls=c_cand;}\n\t}\n\treturn true;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Classifier_Multinomial_NaiveBayes<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::test(RETURNTYPE &result, const PDataAccessor da)\n{\n\t// NOTE: mean[] and cov[] must be pre-computed using initialize()\n\t// NOTE: _inverse[] _det[] and _constant[] must be pre-computed\n\tnotify(\"Classifier_Multinomial_NaiveBayes::test().\");\n\tassert(_model);\n\tif(_prelearn_mode) assert(get_n()>0);\n\tassert(_model->get_classes()>1);\n\tassert(_classes==_model->get_classes());\n\tassert(da);\n\tif(_prelearn_mode) assert(da->getNoOfFeatures()==get_n());\n\tassert(da->getNoOfClasses()>0);\n\tassert(da->getNoOfClasses()==_classes);\n\tassert(_index);\n\tassert(_subfeatures==_model->get_d());\n\tif(!_prelearn_mode) assert(_subfeatures==_model->get_n());\n\tassert(_subfeatures>0);\n\t\t\n\ttypename DATAACCESSOR::PPattern p;\n\tIDXTYPE s,i;\n\tIDXTYPE count, correct;\n\tDIMTYPE _features=da->getNoOfFeatures();\n\tDIMTYPE clstmp;\n\n\tif(_subfeatures==1) { \n\t\t// NOTE: single features are unusable for classification because theta=1 in each class,\n\t\t//       thus log(theta)=0 and consequently Pcd[] does not depend on feature frequency\n\t\tcorrect=0; count=1; // consider all single features equally unusable\n\t} else {\n\t\tbool b;\n\t\tconst DIMTYPE da_test_loop=1; // to avoid mixup of get*Block() loops of different types\n\t\n\t\tcount=0;\n\t\tcorrect=0;\n\t\tfor(DIMTYPE c_test=0;c_test<_classes;c_test++)\n\t\t{\n\t\t\tda->setClass(c_test);\n\t\t\tfor(b=da->getFirstBlock(TEST,p,s,da_test_loop);b==true;b=da->getNextBlock(TEST,p,s,da_test_loop)) for(i=0;i<s;i++)\n\t\t\t{\n\t\t\t\tif(!classify(clstmp,&p[i*_features])) return false;\n\t\t\t\tif(clstmp==c_test) correct++;\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n\tassert(count>0);\n\tresult=(RETURNTYPE)correct/(RETURNTYPE)count;\n#ifdef DEBUG\n\t{\n\t\tostringstream sos; sos << \" result=\" << result << std::endl;\n\t\tsyncout::print(std::cout,sos);\n\t}\n#endif\t\n\treturn true;\n}\n\n} // namespace\n#endif // FSTCLASSIFIERMULTINOMNAIVEBAYES_H ///:~\n", "meta": {"hexsha": "7332ddfe026c62c72ba21dbf279165432bc20ae6", "size": 17382, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extern/FST3lib/_src_criteria/classifier_multinom_naivebayes.hpp", "max_stars_repo_name": "boussaffawalid/FeatureSelection", "max_stars_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T20:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-23T06:46:02.000Z", "max_issues_repo_path": "extern/FST3lib/_src_criteria/classifier_multinom_naivebayes.hpp", "max_issues_repo_name": "boussaffawalid/FeatureSelection", "max_issues_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T08:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-10T08:57:35.000Z", "max_forks_repo_path": "extern/FST3lib/_src_criteria/classifier_multinom_naivebayes.hpp", "max_forks_repo_name": "boussaffawalid/FeatureSelection", "max_forks_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-04-13T13:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-02-26T08:18:47.000Z", "avg_line_length": 47.7527472527, "max_line_length": 219, "alphanum_fraction": 0.7281095386, "num_tokens": 4633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4177545775764706}}
{"text": "#include <Engine/MeshEdit/ARAP.h>\n#include <Engine/MeshEdit/MinSurf.h>\n#include <Engine/MeshEdit/Paramaterize.h>\n#include <Engine/Primitive/TriMesh.h>\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n#include <set>\n\nusing namespace Ubpa;\nusing namespace Eigen;\nusing namespace std;\n\nUbpa::ARAP::ARAP(Ptr<TriMesh> triMesh, int iter_n, int log_verbosity)\n\t: heMesh(make_shared<HEMesh<V>>())\n\t, heMesh_orig(make_shared<HEMesh<V>>())\n\t, iter_n(iter_n), log_verbosity(log_verbosity)\n{\n\tInit(triMesh, false, true);\n\n\t// copy it into triMesh_orig\n}\n\nvoid Ubpa::ARAP::Clear()\n{\n\theMesh->Clear();\n\theMesh_orig->Clear();\n\ttriMesh = nullptr;\n}\n\nstd::array<pointf2, 3> Ubpa::ARAP::genEmbed(pointf3 v0, pointf3 v1, pointf3 v2) {\n\tvecf3 v10 = v1 - v0;\n\tvecf3 v20 = v2 - v0;\n\tvecf3 v21 = v2 - v1;\n\n\tfloat cos_theta = v10.cos_theta(v20);\n\treturn std::array{ pointf2(0, 0), pointf2(v10.norm(), 0)\n\t\t, pointf2(v20.norm() * cos_theta, v20.norm() * sqrtf(1 - (cos_theta * cos_theta))) };\n}\n\nbool Ubpa::ARAP::Init(Ptr<TriMesh> triMesh, bool noClear, bool initOrig)\n{\n\tif (!noClear)\n\t\tClear();\n\n\tif (triMesh == nullptr)\n\t\treturn true;\n\n\tif (triMesh->GetType() == TriMesh::INVALID) {\n\t\tprintf(\"ERROR::ARAP::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is invalid\\n\");\n\t\treturn false;\n\t}\n\n\t// init half-edge structure\n\tsize_t nV = triMesh->GetPositions().size();\n\tvector<vector<size_t>> triangles;\n\ttriangles.reserve(triMesh->GetTriangles().size());\n\tfor (auto triangle : triMesh->GetTriangles())\n\t\ttriangles.push_back({ triangle->idx[0], triangle->idx[1], triangle->idx[2] });\n\theMesh->Reserve(nV);\n\theMesh->Init(triangles);\n\n\tif (initOrig) {\n\t\theMesh_orig->Clear();\n\t\theMesh_orig->Reserve(nV);\n\t\theMesh_orig->Init(triangles);\n\t}\n\n\tif (!heMesh->IsTriMesh() || !heMesh->HaveBoundary()) {\n\t\tprintf(\"ERROR::ARAP::Init:\\n\"\n\t\t\t\"\\t\"\"trimesh is not a triangle mesh or hasn't a boundaries\\n\");\n\t\theMesh->Clear();\n\t\tif (initOrig) {\n\t\t\theMesh_orig->Clear();\n\t\t}\n\t\treturn false;\n\t}\n\n\t// triangle mesh's positions ->  half-edge structure's positions\n\tfor (int i = 0; i < nV; i++) {\n\t\tauto v = heMesh->Vertices().at(i);\n\t\tv->pos = triMesh->GetPositions()[i].cast_to<vecf3>();\n\t\tif (initOrig) {\n\t\t\tauto u = heMesh_orig->Vertices().at(i);\n\t\t\tu->pos = triMesh->GetPositions()[i].cast_to<vecf3>();\n\t\t}\n\t}\n\n\tthis->triMesh = triMesh;\n\treturn true;\n}\n\n// calculate energy with HeMesh\n\n//namespace Ubpa {\n//\ttemplate<typename V, typename E, typename P>\n//\tconst std::vector<E*> TPolygon<V, E, P>::BoundaryEdges() {\n//\t\tstd::vector<E*> edges;\n//\t\tfor (auto he : BoundaryHEs())\n//\t\t\tedges.push_back(he->Edge());\n//\t\treturn edges;\n//\t}\n//\n//\ttemplate<typename V, typename E, typename P>\n//\tconst std::vector<V*> TPolygon<V, E, P>::BoundaryVertice() {\n//\t\tstd::vector<V*> vertices;\n//\t\tfor (auto he : BoundaryHEs())\n//\t\t\tvertices.push_back(he->Origin());\n//\t\treturn vertices;\n//\t}\n//}\n\nUbpa::ARAP::V* Ubpa::ARAP::findOpp(P* trig, V* v1, V* v2) {\n\tdecltype(v1) opp_v = nullptr;;\n\tif (trig != nullptr) {\n\t\tfor (auto vv : trig->BoundaryVertice()) {\n\t\t\tif (vv != v1 && vv != v2) {\n\t\t\t\topp_v = vv;\n\t\t\t}\n\t\t}\n\t\tassert(opp_v != nullptr);\n\t}\n\treturn opp_v;\n}\n\nstd::tuple<Vector2f, Vector2f> Ubpa::ARAP::calcXVecFull(int xi, int xj) {\n\tauto vi = heMesh_orig->Vertices()[xi];\n\tauto vj = heMesh_orig->Vertices()[xj];\n\n\tauto tri_ij = vi->HalfEdgeTo(vj)->Polygon();\n\tauto tri_ji = vj->HalfEdgeTo(vi)->Polygon();\n\n\tVector2f x_vec_ij = Vector2f::Zero();\n\tVector2f x_vec_ji = Vector2f::Zero();\n\n\t// calculate x vec in mapped 2d space\n\tauto getIdx = [](decltype(tri_ij) trig, decltype(vi) vert) {\n\t\tint i = 0;\n\t\tfor (auto vv : trig->BoundaryVertice()) {\n\t\t\tif (vv == vert) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\tassert(i < 3);\n\t\treturn i;\n\t};\n\n\tif (tri_ij != nullptr) {\n\t\tauto tri_ij_embed = genEmbed(tri_ij->BoundaryVertice()[0]->pos.cast_to<pointf3>()\n\t\t\t, tri_ij->BoundaryVertice()[1]->pos.cast_to<pointf3>()\n\t\t\t, tri_ij->BoundaryVertice()[2]->pos.cast_to<pointf3>());\n\n\t\tint vi_idx = getIdx(tri_ij, vi);\n\t\tint vj_idx = getIdx(tri_ij, vj);\n\t\tx_vec_ij = { (tri_ij_embed[vi_idx] - tri_ij_embed[vj_idx])[0]\n\t\t\t\t\t\t , (tri_ij_embed[vi_idx] - tri_ij_embed[vj_idx])[1] };\n\t\t\n\t\tif (log_verbosity > 40) {\n\t\t\tprintf(\"- embed_ij: \");\n\t\t\tprint(tri_ij_embed);\n\t\t\tprintf(\"- x_vec_ij: \\n\");\n\t\t\tcout << x_vec_ij << endl;\n\t\t}\n\t}\n\t\n\tif (tri_ji != nullptr) {\n\t\tauto tri_ji_embed = genEmbed(tri_ji->BoundaryVertice()[0]->pos.cast_to<pointf3>()\n\t\t\t, tri_ji->BoundaryVertice()[1]->pos.cast_to<pointf3>()\n\t\t\t, tri_ji->BoundaryVertice()[2]->pos.cast_to<pointf3>());\n\n\t\tint vi_idx = getIdx(tri_ji, vi);\n\t\tint vj_idx = getIdx(tri_ji, vj);\n\t\tx_vec_ji = { (tri_ji_embed[vi_idx] - tri_ji_embed[vj_idx])[0]\n\t\t\t\t\t\t , (tri_ji_embed[vi_idx] - tri_ji_embed[vj_idx])[1] };\n\n\t\tif (log_verbosity > 40) {\n\t\t\tprintf(\"- embed_ji: \");\n\t\t\tprint(tri_ji_embed);\n\t\t\tprintf(\"- x_vec_ji: \\n\");\n\t\t\tcout << x_vec_ji << endl;\n\t\t}\n\t}\n\n\treturn std::make_tuple(x_vec_ij, x_vec_ji);\n\n}\n\n// x_vec, cotij, cotji\nstd::tuple<Vector2f, double, double> Ubpa::ARAP::calcXVec(int xi, int xj) {\n\tauto vi = heMesh_orig->Vertices()[xi];\n\tauto vj = heMesh_orig->Vertices()[xj];\n\n\tauto tri_ij = vi->HalfEdgeTo(vj)->Polygon();\n\tauto tri_ji = vj->HalfEdgeTo(vi)->Polygon();\n\n\tif (log_verbosity > 50) {\n\t\tcout << \"- tri_ij: \";\n\t\tprint(tri_ij);\n\n\t\tcout << \"- tri_ji: \";\n\t\tprint(tri_ji);\n\t}\n\n\t// mapped NaN (inf) to zero\n\tauto getCtgf = [](float cosine) {\n\t\treturn (cosine == 1 || cosine == -1) ? 0 : (cosine / (sqrtf(1 - cosine * cosine)));\n\t};\n\n\tdecltype(vj) opp_v_ji = findOpp(tri_ji, vi, vj);\n\tdecltype(vj) opp_v_ij = findOpp(tri_ij, vi, vj);\n\n\tdouble cos_theta_ij = opp_v_ij != nullptr ? (vi->pos - opp_v_ij->pos).cos_theta(vj->pos - opp_v_ij->pos) : 1;\n\tdouble cos_theta_ji = opp_v_ji != nullptr ? (vi->pos - opp_v_ji->pos).cos_theta(vj->pos - opp_v_ji->pos) : 1;\n\n\tdouble cot_theta_ij = getCtgf(cos_theta_ij);\n\tdouble cot_theta_ji = getCtgf(cos_theta_ji);\n\n\t// calculate x vec in mapped 2d space\n\tauto getIdx = [](decltype(tri_ij) trig, decltype(vi) vert) {\n\t\tint i = 0;\n\t\tfor (auto vv : trig->BoundaryVertice()) {\n\t\t\tif (vv == vert) {\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\tassert(i < 3);\n\t\treturn i;\n\t};\n\n\tdecltype(tri_ij) trig;\n\t// only one trig necessary\n\tif (tri_ij == nullptr) {\n\t\ttrig = tri_ji;\n\t} else {\n\t\ttrig = tri_ij;\n\t}\n\n\tif (log_verbosity > 50) {\n\t\tprintf(\"- embed_input: \");\n\t\tprint(trig);\n\t}\n\n\tauto tri_embed = genEmbed(trig->BoundaryVertice()[0]->pos.cast_to<pointf3>()\n\t\t\t\t, trig->BoundaryVertice()[1]->pos.cast_to<pointf3>()\n\t\t\t\t, trig->BoundaryVertice()[2]->pos.cast_to<pointf3>());\n\n\tif (log_verbosity > 40) {\n\t\tprintf(\"- embed: \");\n\t\tprint(tri_embed);\n\t}\n\n\tint vi_idx = getIdx(trig, vi);\n\tint vj_idx = getIdx(trig, vj);\n\tVector2f x_vec = { (tri_embed[vi_idx] - tri_embed[vj_idx])[0]\n\t\t\t\t\t , (tri_embed[vi_idx] - tri_embed[vj_idx])[1] };\n\n\treturn std::make_tuple(x_vec, cot_theta_ij, cot_theta_ji);\n}\n\nvoid Ubpa::ARAP::UniformPara() {\n\t// First, detect and fix boundary\n\trandom_set<V*> boundary_points;\n\trandom_set<V*> inner_points;\n\n\tauto boundaries = this->heMesh->Boundaries();\n\tif (boundaries.size() != 1) {\n\t\tcout << \"ERROR::Parameterize::DoPara:\" << endl\n\t\t\t<< \"\\t\" << \"got boundaries = \" << boundaries.size()\n\t\t\t<< \" (expect 1)\" << endl;\n\t\treturn;\n\t}\n\n\tfor (auto v : boundaries[0]) {\n\t\tboundary_points.insert(v->Origin());\n\t}\n\n\tfor (auto v : heMesh->Vertices()) {\n\t\tif (!boundary_points.contains(v)) {\n\t\t\tinner_points.insert(v);\n\t\t}\n\t}\n\n\t//const float boost_factor = 100;\n\tconst float boost_factor = 1;\n\t// Fix our boundary\n\n\tint points_total = boundary_points.size();\n\tfloat step = 4.0f / points_total;\n\n\tfloat curr = 0;\n\tfor (auto v : boundary_points) {\n\t\tvecf3 new_pos;\n\t\tif (curr >= 0 && curr < 1) {\n\t\t\tnew_pos[0] = curr;\n\t\t\tnew_pos[1] = new_pos[2] = 0;\n\t\t} else if (curr >= 1 && curr < 2) {\n\t\t\tnew_pos[0] = 1;\n\t\t\tnew_pos[1] = curr - 1;\n\t\t\tnew_pos[2] = 0;\n\t\t} else if (curr >= 2 && curr < 3) {\n\t\t\tnew_pos[0] = 1 - (curr - 2);\n\t\t\tnew_pos[1] = 1;\n\t\t\tnew_pos[2] = 0;\n\t\t} else { // curr >= 3; remember to cut off as fp precision is an issue\n\t\t\tnew_pos[0] = 0;\n\t\t\tnew_pos[1] = curr > 4 ? 4 : 4 - curr;\n\t\t\tnew_pos[2] = 0;\n\t\t}\n\t\tv->pos = new_pos * boost_factor;\n\t\tcurr += step;\n\t}\n\n\t// Build sparse matrix\n\tsize_t n = inner_points.size();\n\tSparseMatrix<float> coeff_mat(n, n);\n\tcoeff_mat.setZero();\n\tVectorXf b_vec_x = VectorXf::Zero(n);\n\tVectorXf b_vec_y = VectorXf::Zero(n);\n\tVectorXf b_vec_z = VectorXf::Zero(n);\n\n\tcout << \"coeff mat build start\" << endl;\n\n\tint current_row = 0;\n\tfor (auto v : inner_points) {\n\t\t// vidx CERTAINLY follows order (and it's redundant)\n\t\tsize_t vidx = inner_points.idx(v);\n\t\tauto adj = v->AdjVertices();\n\t\tsize_t degree = v->Degree();\n\t\tfor (auto adjv : adj) {\n\t\t\t\t// check type\n\t\t\tif (boundary_points.contains(adjv)) { // this set is usually smaller\n\t\t\t\tb_vec_x(current_row) += (1.0f / degree) * adjv->pos[0];\n\t\t\t\tb_vec_y(current_row) += (1.0f / degree) * adjv->pos[1];\n\t\t\t\tb_vec_z(current_row) += (1.0f / degree) * adjv->pos[2];\n\t\t\t} else { // inner\n\t\t\t\tassert(inner_points.contains(adjv));\n\t\t\t\tsize_t adjidx = inner_points.idx(adjv);\n\t\t\t\t// todo add assert = 0\n\t\t\t\tcoeff_mat.insert(current_row, adjidx) = -1.0f / degree;\n\t\t\t}\n\t\t}\n\n\t\t// add itself\n\t\t// todo add assert\n\t\tcoeff_mat.insert(current_row, vidx) = 1;\n\t\tcurrent_row++;\n\t}\n\n\n\tcout << \"coeff mat build complete\" << endl;\n\n\t// Solve\n\tSparseQR<SparseMatrix<float>, COLAMDOrdering<int>> solver;\n\n\tcout << \"begin makeCompressed()\" << endl;\n\tcoeff_mat.makeCompressed();\n\n\tcout << \"begin compute()\" << endl;\n\tsolver.compute(coeff_mat);\n\tif (solver.info() != Eigen::Success) {\n\t\tcout << \"solver: decomposition was not successful.\" << endl;\n\t\treturn;\n\t}\n\n\tcout << \"begin solve() for x\" << endl;\n\tVectorXf res_x = solver.solve(b_vec_x);\n\n\tcout << \"begin solve() for y\" << endl;\n\tVectorXf res_y = solver.solve(b_vec_y);\n\n\tcout << \"begin solve() for z\" << endl;\n\tVectorXf res_z = solver.solve(b_vec_z);\n\n\t// Update vertex coordinates\n\tfor (int i = 0; i < n; i++) {\n\t\t// find the corresponding point\n\t\tauto v = inner_points[i];\n\t\tvecf3 new_pos = { res_x(i), res_y(i), res_z(i) }; // works?\n\n\t\t//cout << new_pos << endl;\n\t\tv->pos = new_pos;\n\t}\n\n}\n\nvoid Ubpa::ARAP::print(Ubpa::ARAP::V* v) {\n\tcout << \"V: (\" << v->pos[0] << \", \" << v->pos[1] << \", \" << v->pos[2] << \")\";\n}\nvoid Ubpa::ARAP::print(Ubpa::ARAP::P* p) {\n\tif (p == nullptr) {\n\t\tcout << \"P: nullptr\" << endl;\n\t\treturn;\n\t}\n\tcout << \"P: [\";\n\tprint(p->BoundaryVertice()[0]);\n\tcout << \", \";\n\tprint(p->BoundaryVertice()[1]);\n\tcout << \", \";\n\tprint(p->BoundaryVertice()[2]);\n\tcout << \"]\" << endl;\n}\n\n\nvoid Ubpa::ARAP::print(pointf2& v) {\n\tcout << \"V: (\" << v[0] << \", \" << v[1] << \")\";\n}\n\nvoid Ubpa::ARAP::print(std::array<pointf2, 3>& p) {\n\tcout << \"P: [\";\n\tprint(p[0]);\n\tcout << \", \";\n\tprint(p[1]);\n\tcout << \", \";\n\tprint(p[2]);\n\tcout << \"]\" << endl;\n}\n\ndouble Ubpa::ARAP::calcEnergy(vector<Matrix2f> L_t)\n{\n\tdouble energy = 0;\n\n\tauto polys = heMesh->Polygons();\n\tfor (int poly_id = 0; poly_id < polys.size(); poly_id++) {\n\t\tif (log_verbosity > 50) {\n\t\t\tprint(polys[poly_id]);\n\t\t}\n\n\t\tauto hes = polys[poly_id]->BoundaryHEs();\n\t\tfor (auto he : hes) {\n\t\t\t\n\t\t\tdouble cotij;\n\t\t\tVector2f x_vec;\n\t\t\tstd::tie(x_vec, cotij, std::ignore) = calcXVec(heMesh->Index(he->Origin()), heMesh->Index(he->End()));\n\n\t\t\tif (log_verbosity > 50) {\n\t\t\t\tcout << x_vec << endl;\n\t\t\t}\n\n\t\t\tVector2f u_vec = { he->Origin()->pos[0] - he->End()->pos[0] , he->Origin()->pos[1] - he->End()->pos[1] };\n\n\t\t\tdouble energy_component = cotij * (u_vec - L_t[poly_id] * x_vec).squaredNorm();\n\t\t\tif (log_verbosity > 50) {\n\t\t\t\tprintf(\"* energy += %lf\\n\", energy_component);\n\t\t\t}\n\t\t\tenergy += energy_component;\n\t\t}\n\t}\n\n\tenergy /= 2;\n\n\treturn energy;\n}\n\nvoid Ubpa::ARAP::DoARAP()\n{\n\tcout << \"DoARAP() called.\" << endl;\n\n\t// initialize 2d mapping\n\tUniformPara();\n\t//for (auto v : heMesh->Vertices()) {\n\t//\tv->pos[2] = 0;\n\t//}\n\n\tfor (auto v : heMesh->Vertices()) {\n\t\tassert(v->pos[2] == 0);\n\t}\n\t\n\t// envvars\n\tint total_polys = heMesh->NumPolygons();\n\tauto polys = heMesh->Polygons();\n\tauto polys_orig = heMesh_orig->Polygons();\n\n\t// initialize L_t\n\tvector<Matrix2f> L_t;\n\tfor (int i = 0; i < total_polys; i++) {\n\t\tL_t.push_back(Eigen::Matrix2f::Identity());\n\t\t//L_t.push_back(Eigen::Matrix2f::Zero());\n\t}\n\n\tprintf(\"Start with energy=%lf\\n\", calcEnergy(L_t));\n\n\tfor (int iter_count = 0; iter_count < iter_n; iter_count++) {\n\t\t{\n\t\t\t// local phase, update L_t\n\t\t\tfor (int poly_id = 0; poly_id < total_polys; poly_id++) {\n\t\t\t\t// calculate S_t(u) in place of J_t(u)\n\t\t\t\tMatrix2f S_u = Eigen::Matrix2f::Zero();\n\n\t\t\t\tauto verts = polys[poly_id]->BoundaryVertice();\n\t\t\t\tauto verts_orig = polys_orig[poly_id]->BoundaryVertice();\n\t\t\t\t// todo assuming counterclockwise\n\t\t\t\t// actually okay for both\n\n\t\t\t\tfor (int i = 0; i < 3; i++) {\n\t\t\t\t\t// cot = cos / sin\n\t\t\t\t\tint dest_angle = (i + 2) % 3;\n\t\t\t\t\tdouble cos_theta;\n\t\t\t\t\tauto embed = genEmbed(verts_orig[0]->pos.cast_to<pointf3>()\n\t\t\t\t\t\t, verts_orig[1]->pos.cast_to<pointf3>()\n\t\t\t\t\t\t, verts_orig[2]->pos.cast_to<pointf3>());\n\n\t\t\t\t\tif (dest_angle == 0) {\n\t\t\t\t\t\tcos_theta = (embed[2] - embed[0]).cos_theta(embed[1] - embed[0]);\n\t\t\t\t\t}\n\t\t\t\t\telse if (dest_angle == 1) {\n\t\t\t\t\t\tcos_theta = (embed[0] - embed[1]).cos_theta(embed[2] - embed[1]);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tcos_theta = (embed[0] - embed[2]).cos_theta(embed[1] - embed[2]);\n\t\t\t\t\t}\n\n\t\t\t\t\tdouble cot_theta = cos_theta / (sqrt(1 - cos_theta * cos_theta) + 1e-5);  // todo check 1e-5\n\n\t\t\t\t\tVector2f u_vec = { verts[i]->pos[0] - verts[(i + 1) % 3]->pos[0] , verts[i]->pos[1] - verts[(i + 1) % 3]->pos[1] };\n\t\t\t\t\tVector2f x_vec = { embed[i][0] - embed[(i + 1) % 3][0] , embed[i][1] - embed[(i + 1) % 3][1] };\n\n\t\t\t\t\tS_u += cot_theta * (u_vec * x_vec.transpose());\n\t\t\t\t}\n\n\t\t\t\tJacobiSVD<Matrix2f> svd(S_u, ComputeFullU | ComputeFullV);\n\t\t\t\tassert(svd.singularValues()(0) >= 0 && svd.singularValues()(1) >= 0);\n\n\t\t\t\t// the ARAP case\n\t\t\t\tMatrix2f res = svd.matrixU() * svd.matrixV().transpose();\n\t\t\t\tL_t[poly_id] = res;\n\t\t\t}\n\t\t}\n\t\tprintf(\"[%d] local iteration done, energy=%lf\\n\", iter_count, calcEnergy(L_t));\n\t\t// global iteration\n\t\t{\n\t\t\t// anchors containing vertices index\n\t\t\tstd::set<int> anchors;\n\t\t\t//anchors.insert(0);\n\t\t\t//anchors.insert(1);\n\n\t\t\tint total_vertices = heMesh->NumVertices();\n\t\t\tint vertices_unknown = total_vertices - anchors.size();\n\t\t\t//assert(total_polys == vertices_unknown + 2);\n\n\t\t\tstd::unordered_map<int, int> index_map;\n\t\t\t{\n\t\t\t\tint cur_row = 0;\n\t\t\t\tfor (int i = 0; i < total_vertices; i++) {\n\t\t\t\t\tif (anchors.count(i) > 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tindex_map[i] = cur_row;\n\t\t\t\t\t\tcur_row++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tassert(cur_row == vertices_unknown);\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<float> coeff_mat(vertices_unknown, vertices_unknown);\n\t\t\tEigen::VectorXf b_vec_x = VectorXf::Zero(vertices_unknown);\n\t\t\tEigen::VectorXf b_vec_y = VectorXf::Zero(vertices_unknown);\n\t\t\tcoeff_mat.setZero();\n\n\t\t\tint current_row = 0;\n\t\t\tfor (int i = 0; i < total_vertices; i++) {\n\t\t\t\tif (anchors.count(i) > 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// prepare coefficient\n\t\t\t\t// calculate cos_theta_ij\n\t\t\t\tauto v = heMesh->Vertices()[i];\n\t\t\t\t//cout << \"Processing vertice: \" << v << endl;\n\n\t\t\t\tfor (auto adjv : v->AdjVertices()) {\n\t\t\t\t\tint j = heMesh->Index(adjv);\n\n\t\t\t\t\t//auto he_ji = v->HalfEdgeTo(adjv);\n\t\t\t\t\t//auto he_ij = adjv->HalfEdgeTo(v);\n\t\t\t\t\tauto he_ji = adjv->HalfEdgeTo(v);\n\t\t\t\t\tauto he_ij = v->HalfEdgeTo(adjv);\n\n\t\t\t\t\tauto tri_ji = he_ji->Polygon();\n\t\t\t\t\tauto tri_ij = he_ij->Polygon();\n\n\t\t\t\t\tdouble ctg_ij, ctg_ji;\n\n\t\t\t\t\tif (log_verbosity > 50) {\n\t\t\t\t\t\tcout << \"* i: \";\n\t\t\t\t\t\tprint(v);\n\t\t\t\t\t\tcout << endl;\n\n\t\t\t\t\t\tcout << \"* j: \";\n\t\t\t\t\t\tprint(adjv);\n\t\t\t\t\t\tcout << endl;\n\t\t\t\t\t}\n\n\n\n\t\t\t\t\tstd::tie(std::ignore, ctg_ij, ctg_ji) = calcXVec(heMesh->Index(v), heMesh->Index(adjv));\n\n\t\t\t\t\tif (log_verbosity > 50) {\n\t\t\t\t\t\tprintf(\"* ctg_ij=%lf , ctg_ji=%lf\\n\", ctg_ij, ctg_ji);\n\t\t\t\t\t}\n\n\t\t\t\t\t// the u stuff\n\t\t\t\t\tif (anchors.count(j) > 0) {\n\t\t\t\t\t\t// put into b\n\t\t\t\t\t\tb_vec_x(current_row) += (ctg_ij + ctg_ji) * adjv->pos[0];\n\t\t\t\t\t\tb_vec_y(current_row) += (ctg_ij + ctg_ji) * adjv->pos[1];\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tcoeff_mat.coeffRef(current_row, index_map[j]) += -(ctg_ij + ctg_ji);\n\t\t\t\t\t}\n\n\t\t\t\t\tcoeff_mat.coeffRef(current_row, index_map[i]) += (ctg_ij + ctg_ji);\n\n\t\t\t\t\t// the x stuff\n\n\t\t\t\t\tVector2f x_vec_ij, x_vec_ji;\n\t\t\t\t\tstd::tie(x_vec_ij, x_vec_ji) = calcXVecFull(heMesh->Index(v), heMesh->Index(adjv));\n\n\t\t\t\t\tVector2f rhs = Vector2f::Zero();\n\n\t\t\t\t\tif (tri_ij != nullptr) {\n\t\t\t\t\t\trhs += ctg_ij * L_t[heMesh->Index(he_ij->Polygon())] * x_vec_ij;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (tri_ji != nullptr) {\n\t\t\t\t\t\trhs += ctg_ji * L_t[heMesh->Index(he_ji->Polygon())] * x_vec_ji;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (log_verbosity > 50) {\n\t\t\t\t\t\tcout << \"rhs: \" << endl;\n\t\t\t\t\t\tcout << rhs << endl;\n\t\t\t\t\t}\n\n\t\t\t\t\tb_vec_x(current_row) += rhs(0);\n\t\t\t\t\tb_vec_y(current_row) += rhs(1);\n\t\t\t\t}\n\t\t\t\tcurrent_row++;\n\t\t\t}\n\n\t\t\t// Solve\n\t\t\tSparseQR<SparseMatrix<float>, COLAMDOrdering<int>> solver;\n\n\t\t\tcout << \"begin makeCompressed()\" << endl;\n\t\t\tcoeff_mat.makeCompressed();\n\n\t\t\tif (log_verbosity > 50) {\n\t\t\t\tcout << coeff_mat << endl;\n\t\t\t}\n\n\t\t\tcout << \"begin compute()\" << endl;\n\t\t\tsolver.compute(coeff_mat);\n\t\t\tif (solver.info() != Eigen::Success) {\n\t\t\t\tcout << \"solver: decomposition was not successful.\" << endl;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (log_verbosity > 50) {\n\t\t\t\tcout << \"b_vec_x: \" << endl;\n\t\t\t\tcout << b_vec_x << endl;\n\n\t\t\t\tcout << \"b_vec_y: \" << endl;\n\t\t\t\tcout << b_vec_y << endl;\n\t\t\t}\n\n\t\t\tVectorXf x_res = solver.solve(b_vec_x);\n\t\t\tcout << \"error: \" << (coeff_mat * x_res - b_vec_x).squaredNorm() << \" (x_res)\" << endl;\n\n\t\t\tVectorXf y_res = solver.solve(b_vec_y);\n\t\t\tcout << \"error: \" << (coeff_mat * y_res - b_vec_y).squaredNorm() << \" (y_res)\" << endl;;\n\n\t\t\t// write back\n\t\t\tfor (int i = 0; i < total_vertices; i++) {\n\t\t\t\tif (anchors.count(i) > 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\theMesh->Vertices()[i]->pos = { x_res(index_map[i]), y_res(index_map[i]), 0 };\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tprintf(\"[%d] global iteration done, energy=%lf\\n\", iter_count, calcEnergy(L_t));\n\t}\n}\n\nbool Ubpa::ARAP::Run()\n{\n\tif (heMesh->IsEmpty() || !triMesh) {\n\t\tprintf(\"ERROR::ARAP::Run\\n\"\n\t\t\t\"\\t\"\"heMesh->IsEmpty() || !triMesh\\n\");\n\t\treturn false;\n\t}\n\n\tDoARAP();\n\n\t// half-edge structure -> triangle mesh\n\tsize_t nV = heMesh->NumVertices();\n\tsize_t nF = heMesh->NumPolygons();\n\tvector<pointf3> positions;\n\tvector<unsigned> indice;\n\tpositions.reserve(nV);\n\tindice.reserve(3 * nF);\n\tfor (auto v : heMesh->Vertices())\n\t\tpositions.push_back(v->pos.cast_to<pointf3>());\n\tfor (auto f : heMesh->Polygons()) { // f is triangle\n\t\tfor (auto v : f->BoundaryVertice()) // vertices of the triangle\n\t\t\tindice.push_back(static_cast<unsigned>(heMesh->Index(v)));\n\t}\n\n\ttriMesh->Init(indice, positions);\n\n\n\t//vector<pointf2> texcoords;\n\t//for (auto v : heMesh->Vertices())\n\t//\ttexcoords.push_back(v->pos.cast_to<pointf2>());\n\n\t//triMesh->Update(texcoords);\n\n\treturn true;\n}\n", "meta": {"hexsha": "a938253cab6ae1a5b5b680fc7a6d3221fdb5fe73", "size": 18653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/ARAP.cpp", "max_stars_repo_name": "libreliu/USTC-CG", "max_stars_repo_head_hexsha": "7064e6c72028187453375fdd6cb66c6ac0182ed2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-05-22T00:21:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T03:07:04.000Z", "max_issues_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/ARAP.cpp", "max_issues_repo_name": "libreliu/USTC-CG", "max_issues_repo_head_hexsha": "7064e6c72028187453375fdd6cb66c6ac0182ed2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homeworks/4_MinSurfMeshPara/project/src/Engine/MeshEdit/ARAP.cpp", "max_forks_repo_name": "libreliu/USTC-CG", "max_forks_repo_head_hexsha": "7064e6c72028187453375fdd6cb66c6ac0182ed2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-17T15:59:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-17T15:59:09.000Z", "avg_line_length": 25.6928374656, "max_line_length": 120, "alphanum_fraction": 0.6088564842, "num_tokens": 6204, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.41775456958798407}}
{"text": "/*\n * Copyright 2015-2017 Guillermo Frontera <guillermo.frontera@upm.es>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include \"graph_pathfinder.h\"\n\n#include <unordered_set>\n#include <unordered_map>\n\n#include <boost/heap/fibonacci_heap.hpp>\n\n#include <log/logger.h>\n#include <exc/exception.h>\n\nusing namespace ues::pf;\n\nconst std::string component_name = \"Pathfinder\";\n\nnamespace\n{\n\n/** The state type contains a point index and the estimated cost of such point.*/\ntemplate<unsigned short N>\nstruct state\n{\n    typename visibility_graph<N>::size_type point_index;\n    ues::math::numeric_type accumulated_cost;\n    ues::math::numeric_type estimated_cost;\n};\n\n/** The state_comparator class contains the required comparator method so the\n * states are sorted in the desired order in the priority queue. */\ntemplate<unsigned short N>\nstruct state_comparator\n{\n    bool operator() ( const state<N> & one, const state<N> & two ) const noexcept\n    {\n        return one.estimated_cost > two.estimated_cost;\n    }\n};\n\n/** The priority_queue stores and keeps a sorted list of state objects. */\ntemplate<unsigned short N>\nusing priority_queue = boost::heap::fibonacci_heap< state<N>, boost::heap::compare< state_comparator<N> > >;\n/** The index_set contains all the points whose cost has already been computed. */\ntemplate<unsigned short N>\nusing index_set = std::unordered_set< typename visibility_graph<N>::size_type >;\n/** Stores the handles that allow modifying the states of the priority queue. */\ntemplate<unsigned short N>\nusing handle_storage = std::unordered_map< typename visibility_graph<N>::size_type, typename priority_queue<N>::handle_type >;\n/** Stores the point from which current point has been reached. */\ntemplate<unsigned short N>\nusing parent_point = std::vector< typename visibility_graph<N>::size_type >;\n\n}\n\n\ntemplate<unsigned short N>\npath<N> graph_pathfinder<N>::find_path ( const ues::geom::point<N> & origin,\n                                         const ues::geom::point<N> & target )\n{\n    ues::log::logger lg;\n\n    if ( lg.min_level() <= ues::log::TRACE_LVL )\n    {\n        ues::log::event e ( ues::log::TRACE_LVL, component_name, \"Starting pathfinding\" );\n        e.message() << *graph << '\\n';\n        lg.record ( std::move ( e ) );\n    }\n\n    // Get indices to the origin and target points.\n    const typename visibility_graph<N>::size_type origin_index = graph->point_to_index ( origin );\n    const typename visibility_graph<N>::size_type target_index = graph->point_to_index ( target );\n\n    // Declare necesary data structures.\n    priority_queue<N> frontier;\n    handle_storage<N> handles;\n    index_set<N> explored;\n    parent_point<N> parents ( graph->size() );\n    parents[ origin_index ] = origin_index;\n\n    // Add initial node to the priority queue.\n    typename priority_queue<N>::handle_type handle = frontier.push ( { origin_index, 0, origin.distance_to ( target ) } );\n    handles.insert ( { origin_index, handle } );\n\n    while ( !frontier.empty() )\n    {\n        state<N> node = frontier.top();\n        frontier.pop();\n        handles.erase ( node.point_index );\n\n        if ( node.point_index == target_index )\n        {\n            path<N> reverse_result;\n            typename visibility_graph<N>::size_type current_point = target_index;\n            while ( current_point != parents[ current_point ] )\n            {\n                reverse_result.push_back ( graph->index_to_point ( current_point ) );\n                current_point = parents[ current_point ];\n            }\n            reverse_result.push_back ( origin );\n            path<N> result ( reverse_result.rbegin(), reverse_result.rend() );\n\n            if ( lg.min_level() <= ues::log::DEBUG_LVL )\n            {\n                ues::log::event e ( ues::log::DEBUG_LVL, component_name, \"Found path\" );\n                e.message() << \"Cost of the path: \" << node.accumulated_cost << '\\n';\n                e.message() << result << '\\n';\n                lg.record ( std::move ( e ) );\n            }\n\n            return std::move ( result );\n        }\n\n        explored.insert ( node.point_index );\n\n        for ( typename visibility_graph<N>::size_type p : graph->adjacents ( node.point_index ) )\n        {\n            if ( explored.find ( p ) == explored.end() )\n            {\n                // Get the cost of the edge from node.point_index to p.\n                ues::math::numeric_type last_edge;\n                graph->check_visibility ( node.point_index, p, last_edge );\n\n                // Generate a node with the cost of getting to p from node.point_index.\n                state<N> new_node;\n                new_node.point_index = p;\n                new_node.accumulated_cost = node.accumulated_cost + last_edge;\n                ues::math::numeric_type heuristic_cost = graph->index_to_point ( p ).distance_to ( target );\n                new_node.estimated_cost = new_node.accumulated_cost + heuristic_cost;\n\n                typename handle_storage<N>::const_iterator it = handles.find ( p );\n                if ( it == handles.end() )\n                {\n                    handle = frontier.push ( new_node );\n                    handles.insert ( { p, handle } );\n                    parents[p] = node.point_index;\n                }\n                else if ( new_node.estimated_cost < ( *it->second ).estimated_cost )\n                {\n                    ( *it->second ).estimated_cost = new_node.estimated_cost;\n                    ( *it->second ).accumulated_cost = new_node.accumulated_cost;\n                    frontier.decrease ( it->second );\n                    parents[p] = node.point_index;\n                }\n            }\n        }\n    }\n\n    throw ues::exc::exception ( \"Unable to find a path between points\", UES_CONTEXT );\n}\n\n\ntemplate<unsigned short N>\ngraph_pathfinder<N>::graph_pathfinder ( std::shared_ptr< visibility_graph<N> > graph )\n    : graph ( std::move ( graph ) )\n{\n    if ( this->graph.get() == nullptr )\n        throw ues::exc::exception ( \"Provided graph cannot be null\", UES_CONTEXT );\n}\n\n\n// Instantiate the templates in this translation unit, just once.\ntemplate class ues::pf::graph_pathfinder<2>;\ntemplate class ues::pf::graph_pathfinder<3>;\n", "meta": {"hexsha": "19c7c1396f64161299ae24bd3637439169a19fed", "size": 6710, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pf/visibility_graph/graph_pathfinder.cpp", "max_stars_repo_name": "gfrontera/pathfinding-benchmark", "max_stars_repo_head_hexsha": "d8fb1cb2af6924933759886765b4e8916b7bd8dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T07:35:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T17:30:10.000Z", "max_issues_repo_path": "pf/visibility_graph/graph_pathfinder.cpp", "max_issues_repo_name": "gfrontera/pathfinding-benchmark", "max_issues_repo_head_hexsha": "d8fb1cb2af6924933759886765b4e8916b7bd8dc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pf/visibility_graph/graph_pathfinder.cpp", "max_forks_repo_name": "gfrontera/pathfinding-benchmark", "max_forks_repo_head_hexsha": "d8fb1cb2af6924933759886765b4e8916b7bd8dc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4860335196, "max_line_length": 126, "alphanum_fraction": 0.6312965723, "num_tokens": 1464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.41772114132111177}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"opengl-precomp.h\"  // Precompiled header\n\n#include <mrpt/math/CMatrixF.h>\n#include <mrpt/math/TLine3D.h>\n#include <mrpt/math/geometry.h>\n#include <mrpt/math/matrix_serialization.h>\n#include <mrpt/opengl/CEllipsoid.h>\n#include <mrpt/serialization/CArchive.h>\n#include <Eigen/Dense>\n#include \"opengl_internals.h\"\n\nusing namespace mrpt;\nusing namespace mrpt::opengl;\nusing namespace mrpt::math;\nusing namespace std;\n\nIMPLEMENTS_SERIALIZABLE(CEllipsoid, CRenderizableDisplayList, mrpt::opengl)\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\t\trender\n  ---------------------------------------------------------------*/\nvoid CEllipsoid::render_dl() const\n{\n#if MRPT_HAS_OPENGL_GLUT\n\tMRPT_START\n\n\tconst size_t dim = m_cov.cols();\n\n\tif (m_eigVal(0, 0) != 0.0 && m_eigVal(1, 1) != 0.0 &&\n\t\t(dim == 2 || m_eigVal(2, 2) != 0.0) && m_quantiles != 0.0)\n\t{\n\t\tglEnable(GL_BLEND);\n\t\tcheckOpenGLError();\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\t\tcheckOpenGLError();\n\t\tglLineWidth(m_lineWidth);\n\t\tcheckOpenGLError();\n\n\t\tif (dim == 2)\n\t\t{\n\t\t\tglDisable(GL_LIGHTING);  // Disable lights when drawing lines\n\n\t\t\t// ---------------------\n\t\t\t//     2D ellipse\n\t\t\t// ---------------------\n\n\t\t\t/* Equivalent MATLAB code:\n\t\t\t *\n\t\t\t * q=1;\n\t\t\t * [vec val]=eig(C);\n\t\t\t * M=(q*val*vec)';\n\t\t\t * R=M*[x;y];\n\t\t\t * xx=R(1,:);yy=R(2,:);\n\t\t\t * plot(xx,yy), axis equal;\n\t\t\t */\n\n\t\t\tdouble ang;\n\t\t\tunsigned int i;\n\n\t\t\t// Compute the new vectors for the ellipsoid:\n\t\t\tauto M = CMatrixDouble(m_eigVal.asEigen() * m_eigVec.transpose());\n\t\t\tM *= double(m_quantiles);\n\n\t\t\tglBegin(GL_LINE_LOOP);\n\n\t\t\t// Compute the points of the 2D ellipse:\n\t\t\tfor (i = 0, ang = 0; i < m_2D_segments;\n\t\t\t\t i++, ang += (M_2PI / m_2D_segments))\n\t\t\t{\n\t\t\t\tdouble ccos = cos(ang);\n\t\t\t\tdouble ssin = sin(ang);\n\n\t\t\t\tconst float x = ccos * M(0, 0) + ssin * M(1, 0);\n\t\t\t\tconst float y = ccos * M(0, 1) + ssin * M(1, 1);\n\n\t\t\t\tglVertex2f(x, y);\n\t\t\t}  // end for points on ellipse\n\n\t\t\tglEnd();\n\n\t\t\t// 2D: Save bounding box:\n\t\t\tconst double max_radius =\n\t\t\t\tm_quantiles * std::max(m_eigVal(0, 0), m_eigVal(1, 1));\n\t\t\tm_bb_min = mrpt::math::TPoint3D(-max_radius, -max_radius, 0);\n\t\t\tm_bb_max = mrpt::math::TPoint3D(max_radius, max_radius, 0);\n\t\t\t// Convert to coordinates of my parent:\n\t\t\tm_pose.composePoint(m_bb_min, m_bb_min);\n\t\t\tm_pose.composePoint(m_bb_max, m_bb_max);\n\n\t\t\tglEnable(GL_LIGHTING);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// ---------------------\n\t\t\t//    3D ellipsoid\n\t\t\t// ---------------------\n\t\t\tGLfloat mat[16];\n\n\t\t\t//  A homogeneous transformation matrix, in this order:\n\t\t\t//\n\t\t\t//     0  4  8  12\n\t\t\t//     1  5  9  13\n\t\t\t//     2  6  10 14\n\t\t\t//     3  7  11 15\n\t\t\t//\n\t\t\tmat[3] = mat[7] = mat[11] = 0;\n\t\t\tmat[15] = 1;\n\t\t\tmat[12] = mat[13] = mat[14] = 0;\n\n\t\t\tmat[0] = m_eigVec(0, 0);\n\t\t\tmat[1] = m_eigVec(1, 0);\n\t\t\tmat[2] = m_eigVec(2, 0);  // New X-axis\n\t\t\tmat[4] = m_eigVec(0, 1);\n\t\t\tmat[5] = m_eigVec(1, 1);\n\t\t\tmat[6] = m_eigVec(2, 1);  // New X-axis\n\t\t\tmat[8] = m_eigVec(0, 2);\n\t\t\tmat[9] = m_eigVec(1, 2);\n\t\t\tmat[10] = m_eigVec(2, 2);  // New X-axis\n\n\t\t\tGLUquadricObj* obj = gluNewQuadric();\n\t\t\tcheckOpenGLError();\n\n\t\t\tif (!m_drawSolid3D)\n\t\t\t\tglDisable(GL_LIGHTING);  // Disable lights when drawing lines\n\n\t\t\tgluQuadricDrawStyle(obj, m_drawSolid3D ? GLU_FILL : GLU_LINE);\n\n\t\t\tglPushMatrix();\n\t\t\tglMultMatrixf(mat);\n\t\t\tglScalef(\n\t\t\t\tm_eigVal(0, 0) * m_quantiles, m_eigVal(1, 1) * m_quantiles,\n\t\t\t\tm_eigVal(2, 2) * m_quantiles);\n\n\t\t\tgluSphere(obj, 1, m_3D_segments, m_3D_segments);\n\t\t\tcheckOpenGLError();\n\n\t\t\tglPopMatrix();\n\n\t\t\tgluDeleteQuadric(obj);\n\t\t\tcheckOpenGLError();\n\n\t\t\t// 3D: Save bounding box:\n\t\t\tconst double max_radius =\n\t\t\t\tm_quantiles *\n\t\t\t\tstd::max(\n\t\t\t\t\tm_eigVal(0, 0), std::max(m_eigVal(1, 1), m_eigVal(2, 2)));\n\t\t\tm_bb_min = mrpt::math::TPoint3D(-max_radius, -max_radius, 0);\n\t\t\tm_bb_max = mrpt::math::TPoint3D(max_radius, max_radius, 0);\n\t\t\t// Convert to coordinates of my parent:\n\t\t\tm_pose.composePoint(m_bb_min, m_bb_min);\n\t\t\tm_pose.composePoint(m_bb_max, m_bb_max);\n\t\t}\n\n\t\tglDisable(GL_BLEND);\n\n\t\tglEnable(GL_LIGHTING);\n\t}\n\tMRPT_END_WITH_CLEAN_UP(cout << \"Covariance matrix leading to error is:\"\n\t\t\t\t\t\t\t\t<< endl\n\t\t\t\t\t\t\t\t<< m_cov << endl;);\n#endif\n}\n\nuint8_t CEllipsoid::serializeGetVersion() const { return 1; }\nvoid CEllipsoid::serializeTo(mrpt::serialization::CArchive& out) const\n{\n\twriteToStreamRender(out);\n\tout << m_cov << m_drawSolid3D << m_quantiles << (uint32_t)m_2D_segments\n\t\t<< (uint32_t)m_3D_segments << m_lineWidth;\n}\n\nvoid CEllipsoid::serializeFrom(\n\tmrpt::serialization::CArchive& in, uint8_t version)\n{\n\tswitch (version)\n\t{\n\t\tcase 0:\n\t\tcase 1:\n\t\t{\n\t\t\tuint32_t i;\n\t\t\treadFromStreamRender(in);\n\t\t\tif (version == 0)\n\t\t\t{\n\t\t\t\tCMatrixF c;\n\t\t\t\tin >> c;\n\t\t\t\tm_cov = c.cast_double();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tin >> m_cov;\n\t\t\t}\n\n\t\t\tin >> m_drawSolid3D >> m_quantiles;\n\t\t\tin >> i;\n\t\t\tm_2D_segments = i;\n\t\t\tin >> i;\n\t\t\tm_3D_segments = i;\n\t\t\tin >> m_lineWidth;\n\n\t\t\t// Update cov. matrix cache:\n\t\t\tsetCovMatrix(m_cov);\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tMRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version);\n\t};\n\tCRenderizableDisplayList::notifyChange();\n}\n\nbool quickSolveEqn(double a, double b_2, double c, double& t)\n{\n\tdouble delta = square(b_2) - a * c;\n\tif (delta == 0)\n\t\treturn (t = -b_2 / a) >= 0;\n\telse if (delta > 0)\n\t{\n\t\tdelta = sqrt(delta);\n\t\tif ((t = (-b_2 - delta) / a) >= 0)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn (t = (-b_2 + delta) / a) >= 0;\n\t}\n\telse\n\t\treturn false;\n}\n\nbool CEllipsoid::traceRay(const mrpt::poses::CPose3D& o, double& dist) const\n{\n\tif (m_cov.rows() != 3) return false;\n\tTLine3D lin, lin2;\n\tcreateFromPoseX((o - this->m_pose).asTPose(), lin);\n\tlin.unitarize();  // By adding this line, distance from any point of the\n\t// line to its base is exactly equal to the \"t\".\n\tfor (size_t i = 0; i < 3; i++)\n\t{\n\t\tlin2.pBase[i] = 0;\n\t\tlin2.director[i] = 0;\n\t\tfor (size_t j = 0; j < 3; j++)\n\t\t{\n\t\t\tdouble vji = m_eigVec(j, i);\n\t\t\tlin2.pBase[i] += vji * lin.pBase[j];\n\t\t\tlin2.director[i] += vji * lin.director[j];\n\t\t}\n\t}\n\tdouble a = 0, b_2 = 0, c = -square(m_quantiles);\n\tfor (size_t i = 0; i < 3; i++)\n\t{\n\t\tdouble ev = m_eigVal(i, i);\n\t\ta += square(lin2.director[i] / ev);\n\t\tb_2 += lin2.director[i] * lin2.pBase[i] / square(ev);\n\t\tc += square(lin2.pBase[i] / ev);\n\t}\n\treturn quickSolveEqn(a, b_2, c, dist);\n}\n\nvoid CEllipsoid::setCovMatrix(\n\tconst mrpt::math::CMatrixDouble& m, int resizeToSize)\n{\n\tMRPT_START\n\n\tASSERT_(m.cols() == m.rows());\n\tASSERT_(\n\t\tm.rows() == 2 || m.rows() == 3 ||\n\t\t(resizeToSize > 0 && (resizeToSize == 2 || resizeToSize == 3)));\n\n\tm_cov = m;\n\tif (resizeToSize > 0 && resizeToSize < (int)m.rows())\n\t\tm_cov.setSize(resizeToSize, resizeToSize);\n\n\tif (m_cov == m_prevComputedCov) return;  // Done.\n\n\tm_prevComputedCov = m_cov;\n\n\tCRenderizableDisplayList::notifyChange();\n\n\t// Handle the special case of an ellipsoid of volume = 0\n\tconst double d = m_cov.det();\n\tif (d == 0 || d != d)  // Note: \"d!=d\" is a great test for invalid numbers,\n\t// don't remove!\n\t{\n\t\t// All zeros:\n\t\tm_eigVec.setZero(3, 3);\n\t\tm_eigVal.setZero(3, 3);\n\t}\n\telse\n\t{\n\t\t// Not null matrix: compute the eigen-vectors & values:\n\t\tstd::vector<double> eigvals;\n\t\tif (m_cov.eig_symmetric(m_eigVec, eigvals))\n\t\t{\n\t\t\t// Do the scale at render to avoid recomputing the m_eigVal for\n\t\t\t// different m_quantiles\n\t\t\tm_eigVal.setDiagonal(eigvals);\n\t\t\tm_eigVal.array() = m_eigVal.array().sqrt().matrix();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_eigVec.setZero(3, 3);\n\t\t\tm_eigVal.setZero(3, 3);\n\t\t}\n\t}\n\n\tMRPT_END\n}\n\nvoid CEllipsoid::setCovMatrix(\n\tconst mrpt::math::CMatrixFloat& m, int resizeToSize)\n{\n\tCRenderizableDisplayList::notifyChange();\n\tsetCovMatrix(CMatrixDouble(m), resizeToSize);\n}\n\n/** Evaluates the bounding box of this object (including possible children) in\n * the coordinate frame of the object parent. */\nvoid CEllipsoid::getBoundingBox(\n\tmrpt::math::TPoint3D& bb_min, mrpt::math::TPoint3D& bb_max) const\n{\n\tbb_min = m_bb_min;\n\tbb_max = m_bb_max;\n}\n", "meta": {"hexsha": "b40fb736b05ec2d1ae9eca1465a5ca6d5efcc883", "size": 8464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/opengl/src/CEllipsoid.cpp", "max_stars_repo_name": "zarmomin/mrpt", "max_stars_repo_head_hexsha": "1baff7cf8ec9fd23e1a72714553bcbd88c201966", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T06:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T06:24:08.000Z", "max_issues_repo_path": "libs/opengl/src/CEllipsoid.cpp", "max_issues_repo_name": "gao-ouyang/mrpt", "max_issues_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/opengl/src/CEllipsoid.cpp", "max_forks_repo_name": "gao-ouyang/mrpt", "max_forks_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T02:55:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T02:55:04.000Z", "avg_line_length": 25.6484848485, "max_line_length": 80, "alphanum_fraction": 0.5923913043, "num_tokens": 2834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4177211413211117}}
{"text": "#include \"software/geom/util.h\"\n\n#include <algorithm>\n#include <boost/geometry/algorithms/intersection.hpp>\n#include <boost/geometry/geometries/segment.hpp>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <limits>\n#include <tuple>\n\n#include \"software/logger/logger.h\"\n#include \"software/new_geom/angle.h\"\n#include \"software/new_geom/rectangle.h\"\n#include \"software/new_geom/segment.h\"\n#include \"software/new_geom/triangle.h\"\n#include \"software/new_geom/util/collinear.h\"\n#include \"software/new_geom/util/distance.h\"\n#include \"software/new_geom/util/intersection.h\"\n#include \"software/new_geom/util/intersects.h\"\n\nbool isDegenerate(const Segment &segment)\n{\n    return distanceSquared(segment.getSegStart(), segment.getEnd()) < EPS2;\n}\n\ndouble length(const Segment &segment)\n{\n    return distance(segment.getSegStart(), segment.getEnd());\n}\n\ndouble lengthSquared(const Segment &segment)\n{\n    return distanceSquared(segment.getSegStart(), segment.getEnd());\n}\n\nbool collinear(const Segment &segment1, const Segment &segment2)\n{\n    // Two segments are collinear if all Points are collinear\n    if (collinear(segment1.getSegStart(), segment1.getEnd(), segment2.getSegStart()) &&\n        collinear(segment1.getSegStart(), segment1.getEnd(), segment2.getEnd()))\n    {\n        return true;\n    }\n    return false;\n}\n\nstd::vector<Point> lineCircleIntersect(const Point &centre, double radius,\n                                       const Point &segA, const Point &segB)\n{\n    std::vector<Point> ans;\n\n    // take care of 0 length segments too much error here\n    if ((segB - segA).lengthSquared() < EPS)\n    {\n        return ans;\n    }\n\n    double lenseg = (segB - segA).dot(centre - segA) / (segB - segA).length();\n    Point C       = segA + lenseg * (segB - segA).normalize();\n\n    // if C outside circle no intersections\n    if ((C - centre).lengthSquared() > radius * radius + EPS)\n    {\n        return ans;\n    }\n\n    // if C on circle perimeter return the only intersection\n    if ((C - centre).lengthSquared() < radius * radius + EPS &&\n        (C - centre).lengthSquared() > radius * radius - EPS)\n    {\n        ans.push_back(C);\n        return ans;\n    }\n    // first possible intersection\n    double lensegb = radius * radius - (C - centre).lengthSquared();\n\n    ans.push_back(C - (lensegb * (segB - segA).normalize()));\n    ans.push_back(C + lensegb * (segB - segA).normalize());\n\n    return ans;\n}\n\n\nPoint closestPointOnSeg(const Point &p, const Segment &segment)\n{\n    return closestPointOnSeg(p, segment.getSegStart(), segment.getEnd());\n}\nPoint closestPointOnSeg(const Point &centre, const Point &segA, const Point &segB)\n{\n    // if one of the end-points is extremely close to the centre point\n    // then return 0.0\n    if ((segB - centre).lengthSquared() < EPS2)\n    {\n        return segB;\n    }\n\n    if ((segA - centre).lengthSquared() < EPS2)\n    {\n        return segA;\n    }\n\n    // take care of 0 length segments\n    if ((segB - segA).lengthSquared() < EPS2)\n    {\n        return segA;\n    }\n\n    // find point C\n    // which is the projection onto the line\n    double lenseg = (segB - segA).dot(centre - segA) / (segB - segA).length();\n    Point C       = segA + lenseg * (segB - segA).normalize();\n\n    // check if C is in the line seg range\n    double AC     = (segA - C).lengthSquared();\n    double BC     = (segB - C).lengthSquared();\n    double AB     = (segA - segB).lengthSquared();\n    bool in_range = AC <= AB && BC <= AB;\n\n    // if so return C\n    if (in_range)\n    {\n        return C;\n    }\n    double lenA = (centre - segA).length();\n    double lenB = (centre - segB).length();\n\n    // otherwise return closest end of line-seg\n    if (lenA < lenB)\n    {\n        return segA;\n    }\n    return segB;\n}\n\nbool uniqueLineIntersects(const Point &a, const Point &b, const Point &c, const Point &d)\n{\n    return std::abs((d - c).cross(b - a)) > EPS;\n}\n\nPoint calcBlockCone(const Vector &a, const Vector &b, const double &radius)\n{\n    if (a.length() < EPS || b.length() < EPS)\n    {\n    }\n    // unit vector and bisector\n    Vector au = a / a.length();\n    Vector c  = au + b / b.length();\n    // use similar triangle\n    return Point(c * (radius / std::fabs(au.cross(c))));\n}\n\nPoint calcBlockCone(const Point &a, const Point &b, const Point &p, const double &radius)\n{\n    return p + (calcBlockCone(a - p, b - p, radius)).toVector();\n}\n\ndouble offsetToLine(Point x0, Point x1, Point p)\n{\n    Vector n;\n\n    // get normal to line\n    n = (x1 - x0).perpendicular().normalize();\n\n    return fabs(n.dot(p - x0));\n}\n\nAngle acuteVertexAngle(Vector v1, Vector v2)\n{\n    return v1.orientation().minDiff(v2.orientation());\n}\n\nAngle acuteVertexAngle(Point p1, Point p2, Point p3)\n{\n    return acuteVertexAngle(p1 - p2, p3 - p2);\n}\n\nbool pointInFrontVector(Point offset, Vector direction, Point p)\n{\n    // compare angle different\n    Angle a1   = direction.orientation();\n    Angle a2   = (p - offset).orientation();\n    Angle diff = (a1 - a2).clamp();\n    return diff < Angle::quarter() && diff > -Angle::quarter();\n}\n\nstd::pair<Point, Point> getCircleTangentPoints(const Point &start, const Circle &circle,\n                                               double buffer)\n{\n    // If the point is already inside the circe arccos won't work so just return\n    // the perp points\n    if (circle.contains(start))\n    {\n        double perpDist = std::sqrt(circle.getRadius() * circle.getRadius() -\n                                    (circle.getOrigin() - start).lengthSquared());\n        Point p1 =\n            start +\n            (circle.getOrigin() - start).perpendicular().normalize(perpDist + buffer);\n        Point p2 =\n            start -\n            ((circle.getOrigin() - start).perpendicular().normalize(perpDist + buffer));\n        return std::make_pair(p1, p2);\n    }\n    else\n    {\n        double radiusAngle =\n            std::acos(circle.getRadius() / (start - circle.getOrigin()).length());\n        Point p1 = circle.getOrigin() + (start - circle.getOrigin())\n                                            .rotate(Angle::fromRadians(radiusAngle))\n                                            .normalize(circle.getRadius() + buffer);\n        Point p2 = circle.getOrigin() + (start - circle.getOrigin())\n                                            .rotate(-Angle::fromRadians(radiusAngle))\n                                            .normalize(circle.getRadius() + buffer);\n        return std::make_pair(p1, p2);\n    }\n}\n\nstd::pair<Ray, Ray> getCircleTangentRaysWithReferenceOrigin(const Point reference,\n                                                            const Circle circle)\n{\n    auto [tangent_point1, tangent_point2] = getCircleTangentPoints(reference, circle, 0);\n\n    return std::make_pair(Ray(reference, (tangent_point1 - reference)),\n                          Ray(reference, (tangent_point2 - reference)));\n}\n\nPoint getPointsMean(const std::vector<Point> &points)\n{\n    Point average = Point(0, 0);\n    for (unsigned int i = 0; i < points.size(); i++)\n    {\n        average += points[i].toVector();\n    }\n\n    Vector averageVector = average.toVector();\n\n    averageVector /= static_cast<double>(points.size());\n    return Point(averageVector);\n}\n\nstd::optional<Segment> segmentEnclosedBetweenRays(Segment segment, Ray ray1, Ray ray2)\n{\n    // Create rays located at the extremes of the segment, that point in the direction\n    // outwards are parallel to the segment\n    const Ray extremes1 =\n        Ray(segment.getEnd(), Vector(segment.getEnd() - segment.getSegStart()));\n    const Ray extremes2 =\n        Ray(segment.getSegStart(), Vector(segment.getSegStart() - segment.getEnd()));\n\n    const std::optional<Point> extreme_intersect11 = intersection(extremes1, ray1);\n    const std::optional<Point> extreme_intersect12 = intersection(extremes2, ray1);\n    const std::optional<Point> extreme_intersect21 = intersection(extremes1, ray2);\n    const std::optional<Point> extreme_intersect22 = intersection(extremes2, ray2);\n\n    // Check for the cases that the rays intersect the same segment projection\n    if ((extreme_intersect11.has_value() && extreme_intersect21.has_value()) ||\n        (extreme_intersect12.has_value() && extreme_intersect22.has_value()))\n    {\n        return std::nullopt;\n    }\n    else\n    {\n        // Since we know that both rays aren't passing through the same side of the\n        // segment at this point, then as long as they both only intersect 1 point the\n        // segment must be enclosed between them\n        if ((extreme_intersect11.has_value() != extreme_intersect12.has_value()) &&\n            (extreme_intersect21.has_value() != extreme_intersect22.has_value()))\n        {\n            return std::make_optional(segment);\n        }\n        // Covers the case where a single ray passes by both sides of the segment\n        else\n        {\n            return std::nullopt;\n        }\n    }\n}\nstd::optional<Segment> getIntersectingSegment(Ray ray1, Ray ray2, Segment segment)\n{\n    // Check if the segment is enclosed between the rays\n    if (segmentEnclosedBetweenRays(segment, ray1, ray2))\n    {\n        return segment;\n    }\n\n    // Calculate intersections of each individual ray and the segment\n    std::vector<Point> intersection1 = intersection(ray1, segment);\n    std::vector<Point> intersection2 = intersection(ray2, segment);\n\n    std::optional<Point> intersect11;\n    std::optional<Point> intersect12;\n    std::optional<Point> intersect21;\n    std::optional<Point> intersect22;\n\n    if (!intersection1.empty())\n    {\n        intersect11 = intersection1[0];\n\n        if (intersection1.size() > 1)\n        {\n            intersect12 = intersection1[1];\n        }\n    }\n\n    if (!intersection2.empty())\n    {\n        intersect21 = intersection2[0];\n\n        if (intersection2.size() > 1)\n        {\n            intersect22 = intersection2[1];\n        }\n    }\n\n    // Check if there are any real intersections\n    if (!intersect11.has_value() && !intersect21.has_value())\n    {\n        return std::nullopt;\n    }\n    // Check if one of the rays is overlapping the segment. If this is the case, return\n    // the segment (If a ray intersects a ray more than one time it must be overlapping)\n    else if ((intersect11.has_value() && intersect12.has_value()) ||\n             (intersect21.has_value() && intersect22.has_value()))\n    {\n        return segment;\n    }\n    // If there is only one intersection point for each ray combine the intersections into\n    // a segment\n    else if ((intersect11.has_value() && !intersect12.has_value()) &&\n             (intersect21.has_value() && !intersect22.has_value()))\n    {\n        return std::make_optional(Segment(intersect11.value(), intersect21.value()));\n    }\n    // If only one ray intersects the segment return the segment between the intersection\n    // and the segment extreme Point (intersection11 is real, intersection22 is not)\n    else if (intersect11.has_value() && !intersect21.has_value())\n    {\n        const Ray extremes1 =\n            Ray(segment.getEnd(), Vector(segment.getEnd() - segment.getSegStart()));\n        const Ray extremes2 =\n            Ray(segment.getSegStart(), Vector(segment.getSegStart() - segment.getEnd()));\n        ;\n\n        std::optional<Point> extreme_intersect1 = intersection(extremes1, ray2);\n        std::optional<Point> extreme_intersect2 = intersection(extremes2, ray2);\n\n        if (extreme_intersect1.has_value())\n        {\n            return std::make_optional(Segment(intersect11.value(), segment.getEnd()));\n        }\n        else if (extreme_intersect2.has_value())\n        {\n            return std::make_optional(\n                Segment(intersect11.value(), segment.getSegStart()));\n        }\n    }\n    // If only one ray intersects the segment return the segment between the intersection\n    // and the segment extreme (intersection11 is real, intersection22 is not)\n    else if (intersect21.has_value() && !intersect11.has_value())\n    {\n        const Ray extremes1 =\n            Ray(segment.getEnd(), Vector(segment.getEnd() - segment.getSegStart()));\n        const Ray extremes2 =\n            Ray(segment.getSegStart(), Vector(segment.getSegStart() - segment.getEnd()));\n        ;\n\n        std::optional<Point> extreme_intersect1 = intersection(extremes1, ray1);\n        std::optional<Point> extreme_intersect2 = intersection(extremes2, ray1);\n\n        if (extreme_intersect1.has_value())\n        {\n            return std::make_optional(Segment(intersect21.value(), segment.getEnd()));\n        }\n        else if (extreme_intersect2.has_value())\n        {\n            return std::make_optional(\n                Segment(intersect21.value(), segment.getSegStart()));\n        }\n    }\n    // All cases have been checked, return std::nullopt\n    return std::nullopt;\n}\n\nstd::optional<Segment> mergeOverlappingParallelSegments(Segment segment1,\n                                                        Segment segment2)\n{\n    std::optional<Segment> redundant_segment =\n        mergeFullyOverlappingSegments(segment1, segment2);\n\n    // If the segments are not parallel, then return std::nullopt. (The segments are\n    // parallel of all points are collinear)\n    if (!collinear(segment1, segment2))\n    {\n        return std::nullopt;\n    }\n    // Check the case where one segment is completely contained in the other\n    else if (redundant_segment.has_value())\n    {\n        return redundant_segment;\n    }\n    // Check if the beginning of segment2 lays inside segment1\n    else if (segment1.contains(segment2.getSegStart()))\n    {\n        // If segment2.getSegStart() lays in segment1, then the combined segment is\n        // segment2,getEnd() and the point furthest from segment2.getEnd()\n        return (segment1.getSegStart() - segment2.getEnd()).lengthSquared() >\n                       (segment1.getEnd() - segment2.getEnd()).lengthSquared()\n                   ? Segment(segment1.getSegStart(), segment2.getEnd())\n                   : Segment(segment1.getEnd(), segment2.getEnd());\n    }\n    // Now check if the end of segment2 lays inside segment1\n    else if (segment1.contains(segment2.getEnd()))\n    {\n        // If segment2.getSegStart() lays in segment1, then the combined segment is\n        // segment2,getEnd() and the point furtherst from segmen2.getEnd()\n        return (segment1.getSegStart() - segment2.getSegStart()).lengthSquared() >\n                       (segment1.getEnd() - segment2.getSegStart()).lengthSquared()\n                   ? Segment(segment1.getSegStart(), segment2.getSegStart())\n                   : Segment(segment1.getEnd(), segment2.getSegStart());\n    }\n    return std::nullopt;\n}\n\nstd::optional<Segment> mergeFullyOverlappingSegments(Segment segment1, Segment segment2)\n{\n    // If the segments are not parallel, then return std::nullopt. (The segments are\n    // parallel if all points are collinear)\n    if (!collinear(segment1, segment2))\n    {\n        return std::nullopt;\n    }\n\n    Segment largest_segment, smallest_segment;\n    // Grab the largest segment\n    if (segment1.toVector().lengthSquared() > segment2.toVector().lengthSquared())\n    {\n        largest_segment  = segment1;\n        smallest_segment = segment2;\n    }\n    else\n    {\n        largest_segment  = segment2;\n        smallest_segment = segment1;\n    }\n\n    // The segment is redundant if both points of the smallest segment are contained in\n    // the largest segment\n    if (largest_segment.contains(smallest_segment.getSegStart()) &&\n        largest_segment.contains(smallest_segment.getEnd()))\n    {\n        return std::make_optional(largest_segment);\n    }\n    else\n    {\n        return std::nullopt;\n    }\n}\n\nstd::vector<Segment> getEmptySpaceWithinParentSegment(std::vector<Segment> segments,\n                                                      Segment parent_segment)\n{\n    // Make sure the starting point of all segments is closer to the start of the\n    // reference segment to simplify the evaluation\n    for (auto &unordered_seg : segments)\n    {\n        if ((parent_segment.getSegStart() - unordered_seg.getSegStart()).length() >\n            (parent_segment.getSegStart() - unordered_seg.getEnd()).length())\n        {\n            // We need to flip the start/end of the segment\n            Segment temp = unordered_seg;\n            unordered_seg.setSegStart(temp.getEnd());\n            unordered_seg.setEnd(temp.getSegStart());\n        }\n    }\n\n    // Now we must sort the segments so that we can iterate through them in order to\n    // generate open angles sort using a lambda expression\n    // We sort the segments based on how close their 'start' point is to the 'start'\n    // of the reference Segment\n    std::sort(segments.begin(), segments.end(), [parent_segment](Segment &a, Segment &b) {\n        return (parent_segment.getSegStart() - a.getSegStart()).length() <\n               (parent_segment.getSegStart() - b.getSegStart()).length();\n    });\n\n    // Now we need to find the largest open segment/angle\n    std::vector<Segment> open_segs;\n\n    // The first Angle is between the reference Segment and the first obstacle Segment\n    // After this one, ever open angle is between segment(i).end and\n    // segment(i+1).start\n    open_segs.push_back(\n        Segment(parent_segment.getSegStart(), segments.front().getSegStart()));\n\n    // The 'open' Segment in the space between consecutive 'blocking' Segments\n    for (std::vector<Segment>::const_iterator it = segments.begin();\n         it != segments.end() - 1; it++)\n    {\n        open_segs.push_back(Segment(it->getEnd(), (it + 1)->getSegStart()));\n    }\n\n    // Lastly, the final open angle is between obstacles.end().getEnd() and\n    // reference_segment.getEnd()\n    open_segs.push_back(Segment(segments.back().getEnd(), parent_segment.getEnd()));\n\n    // Remove all zero length open Segments\n    for (std::vector<Segment>::const_iterator it = open_segs.begin();\n         it != open_segs.end();)\n    {\n        if (it->length() < EPS)\n        {\n            open_segs.erase(it);\n        }\n        else\n        {\n            it++;\n        }\n    }\n\n    return open_segs;\n}\n\n\nstd::vector<Segment> projectCirclesOntoSegment(Segment segment,\n                                               std::vector<Circle> circles, Point origin)\n{\n    // Loop through all obstacles to create their projected Segment\n    std::vector<Segment> obstacle_segment_projections = {};\n\n    for (Circle circle : circles)\n    {\n        // If the reference is inside an obstacle there is no open direction\n        if (circle.contains(origin))\n        {\n            obstacle_segment_projections.push_back(segment);\n            return obstacle_segment_projections;\n        }\n\n        // Get the tangent rays from the reference point to the obstacle\n        auto [ray1, ray2] = getCircleTangentRaysWithReferenceOrigin(origin, circle);\n\n        // Project the tangent Rays to obtain a 'blocked' segment on the reference\n        // Segment\n        std::optional<Segment> intersect_segment =\n            getIntersectingSegment(ray1, ray2, segment);\n\n        if (intersect_segment.has_value())\n        {\n            obstacle_segment_projections.push_back(intersect_segment.value());\n        }\n    }\n    return obstacle_segment_projections;\n}\n\nstd::vector<Segment> combineToParallelSegments(std::vector<Segment> segments,\n                                               Vector direction)\n{\n    std::vector<Segment> projected_segments = {};\n\n\n    // Project all Segments onto the direction Vector\n    for (Segment segment : segments)\n    {\n        // The projection of the Segment without including the original Segment location\n        Vector raw_projection = segment.toVector().project(direction);\n\n        // Only count projections that have a non-zero magnitude\n        if (raw_projection.lengthSquared() > EPS)\n        {\n            projected_segments.push_back(\n                Segment(segment.getSegStart(), segment.getSegStart() + raw_projection));\n        }\n    }\n    std::vector<Segment> unique_segments;\n\n    unsigned int j = 0;\n    // Loop through all segments and combine segments\n    // to reduce the vector to the smallest number of independent (not overlapping)\n    // segments\n    while (projected_segments.size() > 0)\n    {\n        std::optional<Segment> temp_segment;\n        unique_segments.push_back(projected_segments[0]);\n        projected_segments.erase(projected_segments.begin());\n\n        for (unsigned int i = 0; i < projected_segments.size(); i++)\n        {\n            temp_segment = mergeOverlappingParallelSegments(unique_segments[j],\n                                                            projected_segments[i]);\n\n            if (temp_segment.has_value())\n            {\n                unique_segments[j] = temp_segment.value();\n                // Remove segments[i] from the list as it is not unique\n                projected_segments.erase(projected_segments.begin() + i);\n                i--;\n            }\n        }\n        j++;\n    }\n\n    return unique_segments;\n}\n", "meta": {"hexsha": "0efd683ea0f7f080d49c0fd83c6d157cda2eef06", "size": 20945, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/software/geom/util.cpp", "max_stars_repo_name": "EvanMorcom/Software", "max_stars_repo_head_hexsha": "586fb3cf8dc2d93de194d9815af5de63caa7e318", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/software/geom/util.cpp", "max_issues_repo_name": "EvanMorcom/Software", "max_issues_repo_head_hexsha": "586fb3cf8dc2d93de194d9815af5de63caa7e318", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/software/geom/util.cpp", "max_forks_repo_name": "EvanMorcom/Software", "max_forks_repo_head_hexsha": "586fb3cf8dc2d93de194d9815af5de63caa7e318", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7346600332, "max_line_length": 90, "alphanum_fraction": 0.625543089, "num_tokens": 4720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178138, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.41772113431464086}}
{"text": "//  (C) Copyright Nick Thompson 2018.\n//  (C) Copyright Matt Borland 2020.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_STATISTICS_UNIVARIATE_STATISTICS_HPP\n#define BOOST_MATH_STATISTICS_UNIVARIATE_STATISTICS_HPP\n\n#include <boost/math/statistics/detail/single_pass.hpp>\n#include <boost/math/tools/config.hpp>\n#include <boost/math/tools/assert.hpp>\n#include <algorithm>\n#include <iterator>\n#include <tuple>\n#include <cmath>\n#include <vector>\n#include <type_traits>\n#include <utility>\n#include <numeric>\n#include <list>\n\n// Support compilers with P0024R2 implemented without linking TBB\n// https://en.cppreference.com/w/cpp/compiler_support\n#ifndef BOOST_NO_CXX17_HDR_EXECUTION\n#include <execution>\n\nnamespace boost::math::statistics {\n\ntemplate<class ExecutionPolicy, class ForwardIterator>\ninline auto mean(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last)\n{\n    using Real = typename std::iterator_traits<ForwardIterator>::value_type;\n    BOOST_MATH_ASSERT_MSG(first != last, \"At least one sample is required to compute the mean.\");\n    \n    if constexpr (std::is_integral_v<Real>)\n    {\n        if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)\n        {\n            return detail::mean_sequential_impl<double>(first, last);\n        }\n        else\n        {\n            return std::reduce(exec, first, last, 0.0) / std::distance(first, last);\n        }\n    }\n    else\n    {\n        if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)\n        {\n            return detail::mean_sequential_impl<Real>(first, last);\n        }\n        else\n        {\n            return std::reduce(exec, first, last, Real(0.0)) / Real(std::distance(first, last));\n        }\n    }\n}\n\ntemplate<class ExecutionPolicy, class Container>\ninline auto mean(ExecutionPolicy&& exec, Container const & v)\n{\n    return mean(exec, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ForwardIterator>\ninline auto mean(ForwardIterator first, ForwardIterator last)\n{\n    return mean(std::execution::seq, first, last);\n}\n\ntemplate<class Container>\ninline auto mean(Container const & v)\n{\n    return mean(std::execution::seq, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ExecutionPolicy, class ForwardIterator>\ninline auto variance(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last)\n{\n    using Real = typename std::iterator_traits<ForwardIterator>::value_type;\n    \n    if constexpr (std::is_integral_v<Real>)\n    {\n        if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)\n        {\n           return std::get<2>(detail::variance_sequential_impl<std::tuple<double, double, double, double>>(first, last));\n        }\n        else\n        {\n            const auto results = detail::first_four_moments_parallel_impl<std::tuple<double, double, double, double, double>>(first, last);\n            return std::get<1>(results) / std::get<4>(results);\n        }\n    }\n    else\n    {\n        if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)\n        {\n            return std::get<2>(detail::variance_sequential_impl<std::tuple<Real, Real, Real, Real>>(first, last));\n        }\n        else\n        {\n            const auto results = detail::first_four_moments_parallel_impl<std::tuple<Real, Real, Real, Real, Real>>(first, last);\n            return std::get<1>(results) / std::get<4>(results);\n        }\n    }\n}\n\ntemplate<class ExecutionPolicy, class Container>\ninline auto variance(ExecutionPolicy&& exec, Container const & v)\n{\n    return variance(exec, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ForwardIterator>\ninline auto variance(ForwardIterator first, ForwardIterator last)\n{\n    return variance(std::execution::seq, first, last);\n}\n\ntemplate<class Container>\ninline auto variance(Container const & v)\n{\n    return variance(std::execution::seq, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ExecutionPolicy, class ForwardIterator>\ninline auto sample_variance(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last)\n{\n    const auto n = std::distance(first, last);\n    BOOST_MATH_ASSERT_MSG(n > 1, \"At least two samples are required to compute the sample variance.\");\n    return n*variance(exec, first, last)/(n-1);\n}\n\ntemplate<class ExecutionPolicy, class Container>\ninline auto sample_variance(ExecutionPolicy&& exec, Container const & v)\n{\n    return sample_variance(exec, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ForwardIterator>\ninline auto sample_variance(ForwardIterator first, ForwardIterator last)\n{\n    return sample_variance(std::execution::seq, first, last);\n}\n\ntemplate<class Container>\ninline auto sample_variance(Container const & v)\n{\n    return sample_variance(std::execution::seq, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ExecutionPolicy, class ForwardIterator>\ninline auto mean_and_sample_variance(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last)\n{\n    using Real = typename std::iterator_traits<ForwardIterator>::value_type;\n\n    if constexpr (std::is_integral_v<Real>)\n    {\n        if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)\n        {\n            const auto results = detail::variance_sequential_impl<std::tuple<double, double, double, double>>(first, last);\n            return std::make_pair(std::get<0>(results), std::get<2>(results)*std::get<3>(results)/(std::get<3>(results)-1.0));\n        }\n        else\n        {\n            const auto results = detail::first_four_moments_parallel_impl<std::tuple<double, double, double, double, double>>(first, last);\n            return std::make_pair(std::get<0>(results), std::get<1>(results) / (std::get<4>(results)-1.0));\n        }\n    }\n    else\n    {\n        if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)\n        {\n            const auto results = detail::variance_sequential_impl<std::tuple<Real, Real, Real, Real>>(first, last);\n            return std::make_pair(std::get<0>(results), std::get<2>(results)*std::get<3>(results)/(std::get<3>(results)-Real(1)));\n        }\n        else\n        {\n            const auto results = detail::first_four_moments_parallel_impl<std::tuple<Real, Real, Real, Real, Real>>(first, last);\n            return std::make_pair(std::get<0>(results), std::get<1>(results) / (std::get<4>(results)-Real(1)));\n        }\n    }\n}\n\ntemplate<class ExecutionPolicy, class Container>\ninline auto mean_and_sample_variance(ExecutionPolicy&& exec, Container const & v)\n{\n    return mean_and_sample_variance(exec, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ForwardIterator>\ninline auto mean_and_sample_variance(ForwardIterator first, ForwardIterator last)\n{\n    return mean_and_sample_variance(std::execution::seq, first, last);\n}\n\ntemplate<class Container>\ninline auto mean_and_sample_variance(Container const & v)\n{\n    return mean_and_sample_variance(std::execution::seq, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ExecutionPolicy, class ForwardIterator>\ninline auto first_four_moments(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last)\n{\n    using Real = typename std::iterator_traits<ForwardIterator>::value_type;\n\n    if constexpr (std::is_integral_v<Real>)\n    {\n        if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)\n        {\n            const auto results = detail::first_four_moments_sequential_impl<std::tuple<double, double, double, double, double>>(first, last); \n            return std::make_tuple(std::get<0>(results), std::get<1>(results) / std::get<4>(results), std::get<2>(results) / std::get<4>(results), \n                                std::get<3>(results) / std::get<4>(results));\n        }\n        else\n        {\n            const auto results = detail::first_four_moments_parallel_impl<std::tuple<double, double, double, double, double>>(first, last);\n            return std::make_tuple(std::get<0>(results), std::get<1>(results) / std::get<4>(results), std::get<2>(results) / std::get<4>(results), \n                                   std::get<3>(results) / std::get<4>(results));\n        }\n    }\n    else\n    {\n        if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)\n        {\n            const auto results = detail::first_four_moments_sequential_impl<std::tuple<Real, Real, Real, Real, Real>>(first, last);\n            return std::make_tuple(std::get<0>(results), std::get<1>(results) / std::get<4>(results), std::get<2>(results) / std::get<4>(results), \n                                   std::get<3>(results) / std::get<4>(results));\n        }\n        else\n        {\n            const auto results = detail::first_four_moments_parallel_impl<std::tuple<Real, Real, Real, Real, Real>>(first, last);\n            return std::make_tuple(std::get<0>(results), std::get<1>(results) / std::get<4>(results), std::get<2>(results) / std::get<4>(results), \n                                   std::get<3>(results) / std::get<4>(results));\n        }\n    }\n}\n\ntemplate<class ExecutionPolicy, class Container>\ninline auto first_four_moments(ExecutionPolicy&& exec, Container const & v)\n{\n    return first_four_moments(exec, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ForwardIterator>\ninline auto first_four_moments(ForwardIterator first, ForwardIterator last)\n{\n    return first_four_moments(std::execution::seq, first, last);\n}\n\ntemplate<class Container>\ninline auto first_four_moments(Container const & v)\n{\n    return first_four_moments(std::execution::seq, std::cbegin(v), std::cend(v));\n}\n\n// https://prod.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf\ntemplate<class ExecutionPolicy, class ForwardIterator>\ninline auto skewness(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last)\n{\n    using Real = typename std::iterator_traits<ForwardIterator>::value_type;\n    using std::sqrt;\n\n    if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)\n    {\n        if constexpr (std::is_integral_v<Real>)\n        {\n            return detail::skewness_sequential_impl<double>(first, last);\n        }\n        else\n        {\n            return detail::skewness_sequential_impl<Real>(first, last);\n        }\n    }\n    else \n    {\n        const auto [M1, M2, M3, M4] = first_four_moments(exec, first, last);\n        const auto n = std::distance(first, last);\n        const auto var = M2/(n-1);\n\n        if (M2 == 0)\n        {\n            // The limit is technically undefined, but the interpretation here is clear:\n            // A constant dataset has no skewness.\n            if constexpr (std::is_integral_v<Real>)\n            {\n                return double(0);\n            }\n            else\n            {\n                return Real(0);\n            }\n        }\n        else\n        {\n            return M3/(M2*sqrt(var)) / Real(2);\n        }\n    }\n}\n\ntemplate<class ExecutionPolicy, class Container>\ninline auto skewness(ExecutionPolicy&& exec, Container & v)\n{\n    return skewness(exec, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ForwardIterator>\ninline auto skewness(ForwardIterator first, ForwardIterator last)\n{\n    return skewness(std::execution::seq, first, last);\n}\n\ntemplate<class Container>\ninline auto skewness(Container const & v)\n{\n    return skewness(std::execution::seq, std::cbegin(v), std::cend(v));\n}\n\n// Follows equation 1.6 of:\n// https://prod.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf\ntemplate<class ExecutionPolicy, class ForwardIterator>\ninline auto kurtosis(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last)\n{\n    const auto [M1, M2, M3, M4] = first_four_moments(exec, first, last);\n    if (M2 == 0)\n    {\n        return M2;\n    }\n    return M4/(M2*M2);\n}\n\ntemplate<class ExecutionPolicy, class Container>\ninline auto kurtosis(ExecutionPolicy&& exec, Container const & v)\n{\n    return kurtosis(exec, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ForwardIterator>\ninline auto kurtosis(ForwardIterator first, ForwardIterator last)\n{\n    return kurtosis(std::execution::seq, first, last);\n}\n\ntemplate<class Container>\ninline auto kurtosis(Container const & v)\n{\n    return kurtosis(std::execution::seq, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ExecutionPolicy, class ForwardIterator>\ninline auto excess_kurtosis(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last)\n{\n    return kurtosis(exec, first, last) - 3;\n}\n\ntemplate<class ExecutionPolicy, class Container>\ninline auto excess_kurtosis(ExecutionPolicy&& exec, Container const & v)\n{\n    return excess_kurtosis(exec, std::cbegin(v), std::cend(v));\n}\n\ntemplate<class ForwardIterator>\ninline auto excess_kurtosis(ForwardIterator first, ForwardIterator last)\n{\n    return excess_kurtosis(std::execution::seq, first, last);\n}\n\ntemplate<class Container>\ninline auto excess_kurtosis(Container const & v)\n{\n    return excess_kurtosis(std::execution::seq, std::cbegin(v), std::cend(v));\n}\n\n\ntemplate<class ExecutionPolicy, class RandomAccessIterator>\nauto median(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last)\n{\n    const auto num_elems = std::distance(first, last);\n    BOOST_MATH_ASSERT_MSG(num_elems > 0, \"The median of a zero length vector is undefined.\");\n    if (num_elems & 1)\n    {\n        auto middle = first + (num_elems - 1)/2;\n        std::nth_element(exec, first, middle, last);\n        return *middle;\n    }\n    else\n    {\n        auto middle = first + num_elems/2 - 1;\n        std::nth_element(exec, first, middle, last);\n        std::nth_element(exec, middle, middle+1, last);\n        return (*middle + *(middle+1))/2;\n    }\n}\n\n\ntemplate<class ExecutionPolicy, class RandomAccessContainer>\ninline auto median(ExecutionPolicy&& exec, RandomAccessContainer & v)\n{\n    return median(exec, std::begin(v), std::end(v));\n}\n\ntemplate<class RandomAccessIterator>\ninline auto median(RandomAccessIterator first, RandomAccessIterator last)\n{\n    return median(std::execution::seq, first, last);\n}\n\ntemplate<class RandomAccessContainer>\ninline auto median(RandomAccessContainer & v)\n{\n    return median(std::execution::seq, std::begin(v), std::end(v));\n}\n\ntemplate<class ExecutionPolicy, class RandomAccessIterator>\ninline auto gini_coefficient(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last)\n{\n    using Real = typename std::iterator_traits<RandomAccessIterator>::value_type;\n\n    if(!std::is_sorted(exec, first, last))\n    {\n        std::sort(exec, first, last);\n    }\n\n    if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)\n    {\n        if constexpr (std::is_integral_v<Real>)\n        {\n            return detail::gini_coefficient_sequential_impl<double>(first, last);\n        }\n        else\n        {\n            return detail::gini_coefficient_sequential_impl<Real>(first, last);\n        }   \n    }\n    \n    else if constexpr (std::is_integral_v<Real>)\n    {\n        return detail::gini_coefficient_parallel_impl<double>(exec, first, last);\n    }\n\n    else\n    {\n        return detail::gini_coefficient_parallel_impl<Real>(exec, first, last);\n    }\n}\n\ntemplate<class ExecutionPolicy, class RandomAccessContainer>\ninline auto gini_coefficient(ExecutionPolicy&& exec, RandomAccessContainer & v)\n{\n    return gini_coefficient(exec, std::begin(v), std::end(v));\n}\n\ntemplate<class RandomAccessIterator>\ninline auto gini_coefficient(RandomAccessIterator first, RandomAccessIterator last)\n{\n    return gini_coefficient(std::execution::seq, first, last);\n}\n\ntemplate<class RandomAccessContainer>\ninline auto gini_coefficient(RandomAccessContainer & v)\n{\n    return gini_coefficient(std::execution::seq, std::begin(v), std::end(v));\n}\n\ntemplate<class ExecutionPolicy, class RandomAccessIterator>\ninline auto sample_gini_coefficient(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last)\n{\n    const auto n = std::distance(first, last);\n    return n*gini_coefficient(exec, first, last)/(n-1);\n}\n\ntemplate<class ExecutionPolicy, class RandomAccessContainer>\ninline auto sample_gini_coefficient(ExecutionPolicy&& exec, RandomAccessContainer & v)\n{\n    return sample_gini_coefficient(exec, std::begin(v), std::end(v));\n}\n\ntemplate<class RandomAccessIterator>\ninline auto sample_gini_coefficient(RandomAccessIterator first, RandomAccessIterator last)\n{\n    return sample_gini_coefficient(std::execution::seq, first, last);\n}\n\ntemplate<class RandomAccessContainer>\ninline auto sample_gini_coefficient(RandomAccessContainer & v)\n{\n    return sample_gini_coefficient(std::execution::seq, std::begin(v), std::end(v));\n}\n\ntemplate<class ExecutionPolicy, class RandomAccessIterator>\nauto median_absolute_deviation(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last, \n    typename std::iterator_traits<RandomAccessIterator>::value_type center=std::numeric_limits<typename std::iterator_traits<RandomAccessIterator>::value_type>::quiet_NaN())\n{\n    using std::abs;\n    using Real = typename std::iterator_traits<RandomAccessIterator>::value_type;\n    using std::isnan;\n    if (isnan(center))\n    {\n        center = boost::math::statistics::median(exec, first, last);\n    }\n    const auto num_elems = std::distance(first, last);\n    BOOST_MATH_ASSERT_MSG(num_elems > 0, \"The median of a zero-length vector is undefined.\");\n    auto comparator = [&center](Real a, Real b) { return abs(a-center) < abs(b-center);};\n    if (num_elems & 1)\n    {\n        auto middle = first + (num_elems - 1)/2;\n        std::nth_element(exec, first, middle, last, comparator);\n        return abs(*middle);\n    }\n    else\n    {\n        auto middle = first + num_elems/2 - 1;\n        std::nth_element(exec, first, middle, last, comparator);\n        std::nth_element(exec, middle, middle+1, last, comparator);\n        return (abs(*middle) + abs(*(middle+1)))/abs(static_cast<Real>(2));\n    }\n}\n\ntemplate<class ExecutionPolicy, class RandomAccessContainer>\ninline auto median_absolute_deviation(ExecutionPolicy&& exec, RandomAccessContainer & v, \n    typename RandomAccessContainer::value_type center=std::numeric_limits<typename RandomAccessContainer::value_type>::quiet_NaN())\n{\n    return median_absolute_deviation(exec, std::begin(v), std::end(v), center);\n}\n\ntemplate<class RandomAccessIterator>\ninline auto median_absolute_deviation(RandomAccessIterator first, RandomAccessIterator last, \n    typename RandomAccessIterator::value_type center=std::numeric_limits<typename RandomAccessIterator::value_type>::quiet_NaN())\n{\n    return median_absolute_deviation(std::execution::seq, first, last, center);\n}\n\ntemplate<class RandomAccessContainer>\ninline auto median_absolute_deviation(RandomAccessContainer & v, \n    typename RandomAccessContainer::value_type center=std::numeric_limits<typename RandomAccessContainer::value_type>::quiet_NaN())\n{\n    return median_absolute_deviation(std::execution::seq, std::begin(v), std::end(v), center);\n}\n\ntemplate<class ExecutionPolicy, class ForwardIterator>\nauto interquartile_range(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last)\n{\n    using Real = typename std::iterator_traits<ForwardIterator>::value_type;\n    static_assert(!std::is_integral_v<Real>, \"Integer values have not yet been implemented.\");\n    auto m = std::distance(first,last);\n    BOOST_MATH_ASSERT_MSG(m >= 3, \"At least 3 samples are required to compute the interquartile range.\");\n    auto k = m/4;\n    auto j = m - (4*k);\n    // m = 4k+j.\n    // If j = 0 or j = 1, then there are an even number of samples below the median, and an even number above the median.\n    //    Then we must average adjacent elements to get the quartiles.\n    // If j = 2 or j = 3, there are an odd number of samples above and below the median, these elements may be directly extracted to get the quartiles.\n\n    if (j==2 || j==3)\n    {\n        auto q1 = first + k;\n        auto q3 = first + 3*k + j - 1;\n        std::nth_element(exec, first, q1, last);\n        Real Q1 = *q1;\n        std::nth_element(exec, q1, q3, last);\n        Real Q3 = *q3;\n        return Q3 - Q1;\n    } else {\n        // j == 0 or j==1:\n        auto q1 = first + k - 1;\n        auto q3 = first + 3*k - 1 + j;\n        std::nth_element(exec, first, q1, last);\n        Real a = *q1;\n        std::nth_element(exec, q1, q1 + 1, last);\n        Real b = *(q1 + 1);\n        Real Q1 = (a+b)/2;\n        std::nth_element(exec, q1, q3, last);\n        a = *q3;\n        std::nth_element(exec, q3, q3 + 1, last);\n        b = *(q3 + 1);\n        Real Q3 = (a+b)/2;\n        return Q3 - Q1;\n    }\n}\n\ntemplate<class ExecutionPolicy, class RandomAccessContainer>\ninline auto interquartile_range(ExecutionPolicy&& exec, RandomAccessContainer & v)\n{\n    return interquartile_range(exec, std::begin(v), std::end(v));\n}\n\ntemplate<class RandomAccessIterator>\ninline auto interquartile_range(RandomAccessIterator first, RandomAccessIterator last)\n{\n    return interquartile_range(std::execution::seq, first, last);\n}\n\ntemplate<class RandomAccessContainer>\ninline auto interquartile_range(RandomAccessContainer & v)\n{\n    return interquartile_range(std::execution::seq, std::begin(v), std::end(v));\n}\n\ntemplate<class ExecutionPolicy, class ForwardIterator, class OutputIterator>\ninline OutputIterator mode(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, OutputIterator output)\n{   \n    if(!std::is_sorted(exec, first, last))\n    {\n        if constexpr (std::is_same_v<typename std::iterator_traits<ForwardIterator>::iterator_category(), std::random_access_iterator_tag>)\n        {\n            std::sort(exec, first, last);\n        }\n        else\n        {\n            BOOST_MATH_ASSERT(\"Data must be sorted for sequential mode calculation\");\n        }\n    }\n\n    return detail::mode_impl(first, last, output);\n}\n\ntemplate<class ExecutionPolicy, class Container, class OutputIterator>\ninline OutputIterator mode(ExecutionPolicy&& exec, Container & v, OutputIterator output)\n{\n    return mode(exec, std::begin(v), std::end(v), output);\n}\n\ntemplate<class ForwardIterator, class OutputIterator>\ninline OutputIterator mode(ForwardIterator first, ForwardIterator last, OutputIterator output)\n{\n    return mode(std::execution::seq, first, last, output);\n}\n\n// Requires enable_if_t to not clash with impl that returns std::list\n// Very ugly. std::is_execution_policy_v returns false for the std::execution objects and decltype of the objects (e.g. std::execution::seq)\ntemplate<class Container, class OutputIterator, std::enable_if_t<!std::is_convertible_v<std::execution::sequenced_policy, Container> &&\n                                                                 !std::is_convertible_v<std::execution::parallel_unsequenced_policy, Container> &&\n                                                                 !std::is_convertible_v<std::execution::parallel_policy, Container>\n                                                                 #if __cpp_lib_execution > 201900\n                                                                 && !std::is_convertible_v<std::execution::unsequenced_policy, Container>\n                                                                 #endif\n                                                                 , bool> = true>\ninline OutputIterator mode(Container & v, OutputIterator output)\n{\n    return mode(std::execution::seq, std::begin(v), std::end(v), output);\n}\n\n// std::list is the return type for the proposed STL stats library\n\ntemplate<class ExecutionPolicy, class ForwardIterator, class Real = typename std::iterator_traits<ForwardIterator>::value_type>\ninline auto mode(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last)\n{\n    std::list<Real> modes;\n    mode(exec, first, last, std::inserter(modes, modes.begin()));\n    return modes;\n}\n\ntemplate<class ExecutionPolicy, class Container>\ninline auto mode(ExecutionPolicy&& exec, Container & v)\n{\n    return mode(exec, std::begin(v), std::end(v));\n}\n\ntemplate<class ForwardIterator>\ninline auto mode(ForwardIterator first, ForwardIterator last)\n{\n    return mode(std::execution::seq, first, last);\n}\n\ntemplate<class Container>\ninline auto mode(Container & v)\n{\n    return mode(std::execution::seq, std::begin(v), std::end(v));\n}\n\n} // Namespace boost::math::statistics\n\n#else // Backwards compatible bindings for C++11\n\nnamespace boost { namespace math { namespace statistics {\n\ntemplate<bool B, class T = void>\nusing enable_if_t = typename std::enable_if<B, T>::type;\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double mean(const ForwardIterator first, const ForwardIterator last)\n{\n    BOOST_MATH_ASSERT_MSG(first != last, \"At least one sample is required to compute the mean.\");\n    return detail::mean_sequential_impl<double>(first, last);\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double mean(const Container& c)\n{\n    return mean(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real mean(const ForwardIterator first, const ForwardIterator last)\n{\n    BOOST_MATH_ASSERT_MSG(first != last, \"At least one sample is required to compute the mean.\");\n    return detail::mean_sequential_impl<Real>(first, last);\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real mean(const Container& c)\n{\n    return mean(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double variance(const ForwardIterator first, const ForwardIterator last)\n{\n    return std::get<2>(detail::variance_sequential_impl<std::tuple<double, double, double, double>>(first, last));\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double variance(const Container& c)\n{\n    return variance(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real variance(const ForwardIterator first, const ForwardIterator last)\n{\n    return std::get<2>(detail::variance_sequential_impl<std::tuple<Real, Real, Real, Real>>(first, last));\n\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real variance(const Container& c)\n{\n    return variance(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double sample_variance(const ForwardIterator first, const ForwardIterator last)\n{\n    const auto n = std::distance(first, last);\n    BOOST_MATH_ASSERT_MSG(n > 1, \"At least two samples are required to compute the sample variance.\");\n    return n*variance(first, last)/(n-1);\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double sample_variance(const Container& c)\n{\n    return sample_variance(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real sample_variance(const ForwardIterator first, const ForwardIterator last)\n{\n    const auto n = std::distance(first, last);\n    BOOST_MATH_ASSERT_MSG(n > 1, \"At least two samples are required to compute the sample variance.\");\n    return n*variance(first, last)/(n-1);\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real sample_variance(const Container& c)\n{\n    return sample_variance(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline std::pair<double, double> mean_and_sample_variance(const ForwardIterator first, const ForwardIterator last)\n{\n    const auto results = detail::variance_sequential_impl<std::tuple<double, double, double, double>>(first, last);\n    return std::make_pair(std::get<0>(results), std::get<3>(results)*std::get<2>(results)/(std::get<3>(results)-1.0));\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline std::pair<double, double> mean_and_sample_variance(const Container& c)\n{\n    return mean_and_sample_variance(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline std::pair<Real, Real> mean_and_sample_variance(const ForwardIterator first, const ForwardIterator last)\n{\n    const auto results = detail::variance_sequential_impl<std::tuple<Real, Real, Real, Real>>(first, last);\n    return std::make_pair(std::get<0>(results), std::get<3>(results)*std::get<2>(results)/(std::get<3>(results)-Real(1)));\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline std::pair<Real, Real> mean_and_sample_variance(const Container& c)\n{\n    return mean_and_sample_variance(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline std::tuple<double, double, double, double> first_four_moments(const ForwardIterator first, const ForwardIterator last)\n{\n    const auto results = detail::first_four_moments_sequential_impl<std::tuple<double, double, double, double, double>>(first, last); \n    return std::make_tuple(std::get<0>(results), std::get<1>(results) / std::get<4>(results), std::get<2>(results) / std::get<4>(results), \n                           std::get<3>(results) / std::get<4>(results));\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline std::tuple<double, double, double, double> first_four_moments(const Container& c)\n{\n    return first_four_moments(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline std::tuple<Real, Real, Real, Real> first_four_moments(const ForwardIterator first, const ForwardIterator last)\n{\n    const auto results = detail::first_four_moments_sequential_impl<std::tuple<Real, Real, Real, Real, Real>>(first, last);\n    return std::make_tuple(std::get<0>(results), std::get<1>(results) / std::get<4>(results), std::get<2>(results) / std::get<4>(results), \n                           std::get<3>(results) / std::get<4>(results));\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline std::tuple<Real, Real, Real, Real> first_four_moments(const Container& c)\n{\n    return first_four_moments(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double skewness(const ForwardIterator first, const ForwardIterator last)\n{\n    return detail::skewness_sequential_impl<double>(first, last);\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double skewness(const Container& c)\n{\n    return skewness(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real skewness(const ForwardIterator first, const ForwardIterator last)\n{\n    return detail::skewness_sequential_impl<Real>(first, last);\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real skewness(const Container& c)\n{\n    return skewness(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double kurtosis(const ForwardIterator first, const ForwardIterator last)\n{\n    std::tuple<double, double, double, double> M = first_four_moments(first, last);\n\n    if(std::get<1>(M) == 0)\n    {\n        return std::get<1>(M);\n    }\n    else\n    {\n        return std::get<3>(M)/(std::get<1>(M)*std::get<1>(M));\n    }\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double kurtosis(const Container& c)\n{\n    return kurtosis(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real kurtosis(const ForwardIterator first, const ForwardIterator last)\n{\n    std::tuple<Real, Real, Real, Real> M = first_four_moments(first, last);\n    \n    if(std::get<1>(M) == 0)\n    {\n        return std::get<1>(M);\n    }\n    else\n    {\n        return std::get<3>(M)/(std::get<1>(M)*std::get<1>(M));\n    }\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real kurtosis(const Container& c)\n{\n    return kurtosis(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double excess_kurtosis(const ForwardIterator first, const ForwardIterator last)\n{\n    return kurtosis(first, last) - 3;\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double excess_kurtosis(const Container& c)\n{\n    return excess_kurtosis(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real excess_kurtosis(const ForwardIterator first, const ForwardIterator last)\n{\n    return kurtosis(first, last) - 3;\n}\n\ntemplate<class Container, typename Real = typename Container::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real excess_kurtosis(const Container& c)\n{\n    return excess_kurtosis(std::begin(c), std::end(c));\n}\n\ntemplate<class RandomAccessIterator, typename Real = typename std::iterator_traits<RandomAccessIterator>::value_type>\nReal median(RandomAccessIterator first, RandomAccessIterator last)\n{\n    const auto num_elems = std::distance(first, last);\n    BOOST_MATH_ASSERT_MSG(num_elems > 0, \"The median of a zero length vector is undefined.\");\n    if (num_elems & 1)\n    {\n        auto middle = first + (num_elems - 1)/2;\n        std::nth_element(first, middle, last);\n        return *middle;\n    }\n    else\n    {\n        auto middle = first + num_elems/2 - 1;\n        std::nth_element(first, middle, last);\n        std::nth_element(middle, middle+1, last);\n        return (*middle + *(middle+1))/2;\n    }\n}\n\ntemplate<class RandomAccessContainer, typename Real = typename RandomAccessContainer::value_type>\ninline Real median(RandomAccessContainer& c)\n{\n    return median(std::begin(c), std::end(c));\n}\n\ntemplate<class RandomAccessIterator, typename Real = typename std::iterator_traits<RandomAccessIterator>::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double gini_coefficient(RandomAccessIterator first, RandomAccessIterator last)\n{\n    if(!std::is_sorted(first, last))\n    {\n        std::sort(first, last);\n    }\n\n    return detail::gini_coefficient_sequential_impl<double>(first, last);\n}\n\ntemplate<class RandomAccessContainer, typename Real = typename RandomAccessContainer::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double gini_coefficient(RandomAccessContainer& c)\n{\n    return gini_coefficient(std::begin(c), std::end(c));\n}\n\ntemplate<class RandomAccessIterator, typename Real = typename std::iterator_traits<RandomAccessIterator>::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real gini_coefficient(RandomAccessIterator first, RandomAccessIterator last)\n{\n    if(!std::is_sorted(first, last))\n    {\n        std::sort(first, last);\n    }\n\n    return detail::gini_coefficient_sequential_impl<Real>(first, last);\n}\n\ntemplate<class RandomAccessContainer, typename Real = typename RandomAccessContainer::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real gini_coefficient(RandomAccessContainer& c)\n{\n    return gini_coefficient(std::begin(c), std::end(c));\n}\n\ntemplate<class RandomAccessIterator, typename Real = typename std::iterator_traits<RandomAccessIterator>::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double sample_gini_coefficient(RandomAccessIterator first, RandomAccessIterator last)\n{\n    const auto n = std::distance(first, last);\n    return n*gini_coefficient(first, last)/(n-1);\n}\n\ntemplate<class RandomAccessContainer, typename Real = typename RandomAccessContainer::value_type, \n         enable_if_t<std::is_integral<Real>::value, bool> = true>\ninline double sample_gini_coefficient(RandomAccessContainer& c)\n{\n    return sample_gini_coefficient(std::begin(c), std::end(c));\n}\n\ntemplate<class RandomAccessIterator, typename Real = typename std::iterator_traits<RandomAccessIterator>::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real sample_gini_coefficient(RandomAccessIterator first, RandomAccessIterator last)\n{\n    const auto n = std::distance(first, last);\n    return n*gini_coefficient(first, last)/(n-1);\n}\n\ntemplate<class RandomAccessContainer, typename Real = typename RandomAccessContainer::value_type, \n         enable_if_t<!std::is_integral<Real>::value, bool> = true>\ninline Real sample_gini_coefficient(RandomAccessContainer& c)\n{\n    return sample_gini_coefficient(std::begin(c), std::end(c));\n}\n\ntemplate<class RandomAccessIterator, typename Real = typename std::iterator_traits<RandomAccessIterator>::value_type>\nReal median_absolute_deviation(RandomAccessIterator first, RandomAccessIterator last,\n    typename std::iterator_traits<RandomAccessIterator>::value_type center=std::numeric_limits<typename std::iterator_traits<RandomAccessIterator>::value_type>::quiet_NaN())\n{\n    using std::abs;\n    using std::isnan;\n    if (isnan(center))\n    {\n        center = boost::math::statistics::median(first, last);\n    }\n    const auto num_elems = std::distance(first, last);\n    BOOST_MATH_ASSERT_MSG(num_elems > 0, \"The median of a zero-length vector is undefined.\");\n    auto comparator = [&center](Real a, Real b) { return abs(a-center) < abs(b-center);};\n    if (num_elems & 1)\n    {\n        auto middle = first + (num_elems - 1)/2;\n        std::nth_element(first, middle, last, comparator);\n        return abs(*middle);\n    }\n    else\n    {\n        auto middle = first + num_elems/2 - 1;\n        std::nth_element(first, middle, last, comparator);\n        std::nth_element(middle, middle+1, last, comparator);\n        return (abs(*middle) + abs(*(middle+1)))/abs(static_cast<Real>(2));\n    }\n}\n\ntemplate<class RandomAccessContainer, typename Real = typename RandomAccessContainer::value_type>\ninline Real median_absolute_deviation(RandomAccessContainer& c,\n    typename RandomAccessContainer::value_type center=std::numeric_limits<typename RandomAccessContainer::value_type>::quiet_NaN())\n{\n    return median_absolute_deviation(std::begin(c), std::end(c), center);\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type>\nReal interquartile_range(ForwardIterator first, ForwardIterator last)\n{\n    static_assert(!std::is_integral<Real>::value, \"Integer values have not yet been implemented.\");\n    auto m = std::distance(first,last);\n    BOOST_MATH_ASSERT_MSG(m >= 3, \"At least 3 samples are required to compute the interquartile range.\");\n    auto k = m/4;\n    auto j = m - (4*k);\n    // m = 4k+j.\n    // If j = 0 or j = 1, then there are an even number of samples below the median, and an even number above the median.\n    //    Then we must average adjacent elements to get the quartiles.\n    // If j = 2 or j = 3, there are an odd number of samples above and below the median, these elements may be directly extracted to get the quartiles.\n\n    if (j==2 || j==3)\n    {\n        auto q1 = first + k;\n        auto q3 = first + 3*k + j - 1;\n        std::nth_element(first, q1, last);\n        Real Q1 = *q1;\n        std::nth_element(q1, q3, last);\n        Real Q3 = *q3;\n        return Q3 - Q1;\n    } \n    else \n    {\n        // j == 0 or j==1:\n        auto q1 = first + k - 1;\n        auto q3 = first + 3*k - 1 + j;\n        std::nth_element(first, q1, last);\n        Real a = *q1;\n        std::nth_element(q1, q1 + 1, last);\n        Real b = *(q1 + 1);\n        Real Q1 = (a+b)/2;\n        std::nth_element(q1, q3, last);\n        a = *q3;\n        std::nth_element(q3, q3 + 1, last);\n        b = *(q3 + 1);\n        Real Q3 = (a+b)/2;\n        return Q3 - Q1;\n    }\n}\n\ntemplate<class Container, typename Real = typename Container::value_type>\nReal interquartile_range(Container& c)\n{\n    return interquartile_range(std::begin(c), std::end(c));\n}\n\ntemplate<class ForwardIterator, class OutputIterator, \n    enable_if_t<std::is_same<typename std::iterator_traits<ForwardIterator>::iterator_category(), std::random_access_iterator_tag>::value, bool> = true>\ninline OutputIterator mode(ForwardIterator first, ForwardIterator last, OutputIterator output)\n{   \n    if(!std::is_sorted(first, last))\n    {\n        std::sort(first, last);\n    }\n\n    return detail::mode_impl(first, last, output);\n}\n\ntemplate<class ForwardIterator, class OutputIterator, \n    enable_if_t<!std::is_same<typename std::iterator_traits<ForwardIterator>::iterator_category(), std::random_access_iterator_tag>::value, bool> = true>\ninline OutputIterator mode(ForwardIterator first, ForwardIterator last, OutputIterator output)\n{   \n    if(!std::is_sorted(first, last))\n    {\n        BOOST_MATH_ASSERT(\"Data must be sorted for mode calculation\");\n    }\n\n    return detail::mode_impl(first, last, output);\n}\n\ntemplate<class Container, class OutputIterator>\ninline OutputIterator mode(Container& c, OutputIterator output)\n{\n    return mode(std::begin(c), std::end(c), output);\n}\n\ntemplate<class ForwardIterator, typename Real = typename std::iterator_traits<ForwardIterator>::value_type>\ninline std::list<Real> mode(ForwardIterator first, ForwardIterator last)\n{\n    std::list<Real> modes;\n    mode(first, last, std::inserter(modes, modes.begin()));\n    return modes;\n}\n\ntemplate<class Container, typename Real = typename Container::value_type>\ninline std::list<Real> mode(Container& c)\n{\n    return mode(std::begin(c), std::end(c));\n}\n}}}\n#endif\n#endif // BOOST_MATH_STATISTICS_UNIVARIATE_STATISTICS_HPP\n", "meta": {"hexsha": "08587a3b3217f6fd3c678a629bf66ef84c646501", "size": 44521, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/statistics/univariate_statistics.hpp", "max_stars_repo_name": "Taqaddusshafi/math", "max_stars_repo_head_hexsha": "9ded1522e2a4a3356c1e6b60a305ee3486542556", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-10T12:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-10T13:59:44.000Z", "max_issues_repo_path": "include/boost/math/statistics/univariate_statistics.hpp", "max_issues_repo_name": "Taqaddusshafi/math", "max_issues_repo_head_hexsha": "9ded1522e2a4a3356c1e6b60a305ee3486542556", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/math/statistics/univariate_statistics.hpp", "max_forks_repo_name": "Taqaddusshafi/math", "max_forks_repo_head_hexsha": "9ded1522e2a4a3356c1e6b60a305ee3486542556", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3801724138, "max_line_length": 173, "alphanum_fraction": 0.6954470924, "num_tokens": 10623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.41770607764551493}}
{"text": "#include \"ros/ros.h\"\n\n#include \"real_time_simulator/FSM.h\"\n#include \"real_time_simulator/State.h\"\n#include \"real_time_simulator/Sensor.h\"\n\n#include \"real_time_simulator/Control.h\"\n\n#include \"geometry_msgs/Vector3.h\"\n#include \"std_msgs/String.h\"\n\n#include <time.h>\n#include <sstream>\n#include <string>\n#include <iostream>\n#include <fstream>\n\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <unsupported/Eigen/EulerAngles>\n\n#include <chrono>\n#include <random>\n\nusing namespace Eigen;\n\nclass Rocket {\npublic:\n    float dry_mass;\n    float propellant_mass;\n    float Isp;\n    float minTorque;\n    float maxTorque;\n\n    std::vector<float> maxThrust{0, 0, 0};\n    std::vector<float> minThrust{0, 0, 0};\n\n    float dry_CM;\n    float propellant_CM;\n    float total_CM; // Current Cm of rocket, in real time\n\n    float total_length;\n\n    float initial_speed;\n\n    float h0;\n\n    std::vector<float> target_apogee = {0, 0, 0};\n    std::vector<float> Cd = {0, 0, 0};\n    std::vector<float> surface = {0, 0, 0};\n    std::vector<float> drag_coeff = {0, 0, 0};\n\n    std::vector<float> dry_Inertia{0, 0, 0};\n    std::vector<float> total_Inertia{0, 0, 0};\n\n    std::vector<float> J_inv{0, 0, 0};\n\n    // Sensor data\n    Vector3d sensor_acc;\n    Vector3d sensor_gyro;\n    float sensor_baro;\n\n    float acc_noise, acc_bias;\n    float gyro_noise, gyro_bias;\n    float baro_noise, baro_bias;\n\n    using state = Matrix<double, 14, 1>;\n    using control = Matrix<double, 3, 2>;\n\n    void update_CM(float current_prop_mass) {\n        total_CM = total_length - (dry_CM * dry_mass + propellant_CM * current_prop_mass) /\n                                  (dry_mass + current_prop_mass); // From aft of rocket\n\n        float new_inertia = dry_Inertia[0] + pow(total_CM - (total_length - propellant_CM), 2) * current_prop_mass;\n\n        total_Inertia[0] = new_inertia;\n        total_Inertia[1] = new_inertia;\n\n        J_inv[0] = total_CM / total_Inertia[0];\n        J_inv[1] = total_CM / total_Inertia[1];\n        J_inv[2] = 1 / total_Inertia[2];\n    }\n\n\n    void init(ros::NodeHandle n) {\n        n.getParam(\"/rocket/minTorque\", minTorque);\n        n.getParam(\"/rocket/maxTorque\", maxTorque);\n        n.getParam(\"/rocket/maxThrust\", maxThrust);\n        n.getParam(\"/rocket/minThrust\", minThrust);\n        n.getParam(\"/rocket/Isp\", Isp);\n\n        n.getParam(\"/rocket/dry_mass\", dry_mass);\n        n.getParam(\"/rocket/propellant_mass\", propellant_mass);\n\n        n.getParam(\"/rocket/Cd\", Cd);\n        n.getParam(\"/rocket/dry_I\", dry_Inertia);\n\n        n.getParam(\"/rocket/dry_CM\", dry_CM);\n        n.getParam(\"/rocket/propellant_CM\", propellant_CM);\n\n        n.getParam(\"/environment/apogee\", target_apogee);\n\n        n.getParam(\"/rocket/initial_speed\", initial_speed);\n\n        std::vector<float> diameter = {0, 0, 0};\n        std::vector<float> length = {0, 0, 0};\n\n        int nStage;\n\n        n.getParam(\"/rocket/diameters\", diameter);\n        n.getParam(\"/rocket/stage_z\", length);\n        n.getParam(\"/rocket/stages\", nStage);\n\n        total_length = length[nStage - 1];\n\n        surface[0] = diameter[1] * total_length;\n        surface[1] = surface[0];\n        surface[2] = diameter[1] * diameter[1] / 4 * 3.14159;\n\n        float rho_air = 1.225;\n        drag_coeff[0] = 0.5 * rho_air * surface[0] * Cd[0];\n        drag_coeff[1] = 0.5 * rho_air * surface[1] * Cd[1];\n        drag_coeff[2] = 0.5 * rho_air * surface[2] * Cd[2];\n\n        total_Inertia[2] = dry_Inertia[2];\n\n        update_CM(propellant_mass);\n\n        n.getParam(\"/perturbation/acc_noise\", acc_noise);\n        n.getParam(\"/perturbation/acc_bias\", acc_bias);\n\n        n.getParam(\"/perturbation/gyro_noise\", gyro_noise);\n        n.getParam(\"/perturbation/gyro_bias\", gyro_bias);\n\n        n.getParam(\"/perturbation/baro_noise\", baro_noise);\n        n.getParam(\"/perturbation/baro_bias\", baro_bias);\n\n        n.getParam(\"/environment/ground_altitude\", h0);\n\n    }\n\n    void dynamics_flight(const state &x,\n                         state &xdot,\n                         control &rocket_control,\n                         control &aero_control,\n                         control &perturbation_control,\n                         const double &t) {\n        // -------------- Simulation variables -----------------------------\n        double g0 = 3.986e14 / pow(6371e3 + h0 + x(2), 2);  // Earth gravity in [m/s^2]\n\n        double mass = dry_mass + x(13);                  // Instantaneous mass of the rocket in [kg]\n\n        // Orientation of the rocket with quaternion\n        Quaternion<double> attitude(x(9), x(6), x(7), x(8));\n        attitude.normalize();\n        Matrix<double, 3, 3> rot_matrix = attitude.toRotationMatrix();\n        //std::cout << (180/3.14)*std::acos(x(9)*x(9) - x(6)*x(6) - x(7)*x(7) + x(8)*x(8)) << \"\\n\";\n\n\n        // Force in inertial frame: gravity\n        Matrix<double, 3, 1> gravity;\n        gravity << 0, 0, g0 * mass;\n\n        // Total force in inertial frame [N]\n        Matrix<double, 3, 1> total_force;\n        total_force = rot_matrix * rocket_control.col(0) - gravity + aero_control.col(0) + perturbation_control.col(0);\n        //std::cout << total_force.transpose() << \"\\n\";\n\n\n        // Angular velocity omega in quaternion format to compute quaternion derivative\n        Quaternion<double> omega_quat(0.0, x(10), x(11), x(12));\n        //std::cout << x.segment(10,3).transpose()*57.29 << \"\\n\\n\";\n\n        // Tortal torque in body frame\n        Matrix<double, 3, 1> I_inv;\n        I_inv << 1 / total_Inertia[0], 1 / total_Inertia[1], 1 / total_Inertia[2];\n\n        Matrix<double, 3, 1> total_torque;\n        total_torque =\n                rocket_control.col(1) + rot_matrix.transpose() * (aero_control.col(1) + perturbation_control.col(1));\n\n        // -------------- Differential equation ---------------------\n\n        // Position variation is speed\n        xdot.head(3) = x.segment(3, 3);\n\n        // Speed variation is Force/mass\n        xdot.segment(3, 3) = total_force / mass;\n\n        // Quaternion variation is 0.5*w◦q\n        xdot.segment(6, 4) = 0.5 * (omega_quat * attitude).coeffs();\n\n        // Angular speed variation is Torque/Inertia\n        xdot.segment(10, 3) = rot_matrix * (total_torque.cwiseProduct(I_inv));\n\n        // Mass variation is proportional to total thrust\n        if (Isp != -1) {\n            xdot(13) = -rocket_control.col(0).norm() / (Isp * g0);\n        } else {\n            xdot(13) = 0;\n        }\n\n\n        // Fake sensor data update -----------------\n        sensor_acc = rot_matrix.transpose() * (total_force + gravity) / mass;\n\n        sensor_gyro = rot_matrix.transpose() * x.segment(10, 3);\n\n        sensor_baro = x(2);\n    }\n\n\n    void dynamics_rail(const state &x,\n                       state &xdot,\n                       control &rocket_control,\n                       control &aero_control,\n                       const double &t) {\n        // -------------- Simulation variables -----------------------------\n        double g0 = 3.986e14 / pow(6371e3 + x(2), 2);  // Earth gravity in [m/s^2]\n\n        double mass = dry_mass + x(13);     // Instantaneous mass of the rocket in [kg]\n\n        // Orientation of the rocket with quaternion\n        Quaternion<double> attitude(x(9), x(6), x(7), x(8));\n        attitude.normalize();\n        Matrix<double, 3, 3> rot_matrix = attitude.toRotationMatrix();\n\n        // Force in inertial frame: gravity\n        Matrix<double, 3, 1> gravity;\n        gravity << 0, 0, g0 * mass;\n\n        // Total force in initial body frame [N] (rail frame)\n        Matrix<double, 3, 1> total_force;\n        total_force = rocket_control.col(0) - rot_matrix.transpose() * (gravity + aero_control.col(0));\n\n        Matrix<double, 3, 1> body_acceleration;\n\n        total_force.head(2) << 0.0, 0.0; // Zero force on axes perpendicular to rail to force rocket to stay on rail\n        //std::cout << total_force << \"\\n\";\n\n\n        // Angular velocity omega in quaternion format to compute quaternion derivative\n        Quaternion<double> omega_quat(0.0, x(10), x(11), x(12));\n\n        // -------------- Differential equation ---------------------\n\n        // Position variation is speed\n        xdot.head(3) = x.segment(3, 3);\n\n        // Speed variation is Force/mass\n        xdot.segment(3, 3) = rot_matrix * total_force / mass;\n\n        // Quaternion variation is zero to keep rail orientation\n        xdot.segment(6, 4) << 0.5 * (omega_quat * attitude).coeffs();\n\n        // Angular speed variation is zero to keep rail orientation\n        xdot.segment(10, 3) << 0.0, 0.0, 0.0;\n\n        // Mass variation is proportional to total thrust\n        xdot.tail(1) << -rocket_control.col(0).norm() / (Isp * g0);\n\n        // Fake sensor data update -----------------\n        sensor_acc = (total_force + rot_matrix.transpose() * gravity) / mass;\n\n        sensor_gyro << 0.0, 0.0, 0.0;\n\n        sensor_baro = x(2);\n    }\n};\n", "meta": {"hexsha": "5659a703f312fd0a3bcb3b7543d955607fe63b8b", "size": 8964, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rocket.hpp", "max_stars_repo_name": "EPFLRocketTeam/real_time_simulator", "max_stars_repo_head_hexsha": "ec03a3baced59ea8cf4467ac8c22e0378d4268e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T17:25:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T00:26:25.000Z", "max_issues_repo_path": "src/rocket.hpp", "max_issues_repo_name": "EPFLRocketTeam/real_time_simulator", "max_issues_repo_head_hexsha": "ec03a3baced59ea8cf4467ac8c22e0378d4268e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-03-29T21:07:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:08:16.000Z", "max_forks_repo_path": "src/rocket.hpp", "max_forks_repo_name": "EPFLRocketTeam/real_time_simulator", "max_forks_repo_head_hexsha": "ec03a3baced59ea8cf4467ac8c22e0378d4268e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-18T05:24:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T05:24:15.000Z", "avg_line_length": 32.8351648352, "max_line_length": 119, "alphanum_fraction": 0.5837795627, "num_tokens": 2426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.417623796192907}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2006-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NASA Vision Workbench is licensed under the Apache License,\n//  Version 2.0 (the \"License\"); you may not use this file except in\n//  compliance with the License. You may obtain a copy of the License at\n//  http://www.apache.org/licenses/LICENSE-2.0\n//\n//  Unless required by applicable law or agreed to in writing, software\n//  distributed under the License is distributed on an \"AS IS\" BASIS,\n//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//  See the License for the specific language governing permissions and\n//  limitations under the License.\n// __END_LICENSE__\n\n\n// TestDatum.h\n#include <test/Helpers.h>\n\n#include <vw/Cartography/Datum.h>\n#include <vw/Core/Stopwatch.h>\n#include <boost/assign/std/vector.hpp>\n\nusing namespace vw;\nusing namespace vw::cartography;\nusing namespace vw::test;\n\nusing namespace boost::assign;\n\nvw::Vector3 vermille_2011_cart_to_geodetic( Datum const& d, Vector3 const& cart ) {\n  const double a2 = d.semi_major_axis() * d.semi_major_axis();\n  const double b2 = d.semi_minor_axis() * d.semi_minor_axis();\n  const double e2 = 1 - b2 / a2;\n  const double e4 = e2 * e2;\n\n  double xy_dist = sqrt( cart[0] * cart[0] + cart[1] * cart[1] );\n  double p = ( cart[0] * cart[0] + cart[1] * cart[1] ) / a2;\n  double q = ( 1 - e2 ) * cart[2] * cart[2] / a2;\n  double r = ( p + q - e4 ) / 6.0;\n  double r3 = r * r * r;\n\n  Vector3 llh;\n\n  double evolute = 8 * r3 + e4 * p * q;\n  double u = std::numeric_limits<double>::quiet_NaN();\n  if ( evolute > 0 ) {\n    // outside the evolute\n    double right_inside_pow = sqrt(e4 * p * q);\n    double sqrt_evolute = sqrt( evolute );\n    u = r + 0.5 * pow(sqrt_evolute + right_inside_pow,2.0/3.0) +\n      0.5 * pow(sqrt_evolute - right_inside_pow,2.0/3.0);\n  } else if ( fabs(cart[2]) < std::numeric_limits<double>::epsilon() ) {\n    // On the equator plane\n    llh[1] = 0;\n    llh[2] = norm_2( cart ) - d.semi_major_axis();\n  } else if ( evolute < 0 and fabs(q) > std::numeric_limits<double>::epsilon() ) {\n    // On or inside the evolute\n    double atan_result = atan2( sqrt( e4 * p * q ), sqrt( -evolute ) + sqrt(-8 * r3) );\n    u = -4 * r * sin( 2.0 / 3.0 * atan_result ) *\n      cos( M_PI / 6.0 + 2.0 / 3.0 * atan_result );\n  } else if ( fabs(q) < std::numeric_limits<double>::epsilon() and p <= e4 ) {\n    // In the singular disc\n    llh[2] = -d.semi_major_axis() * sqrt(1 - e2) * sqrt(e2 - p) / sqrt(e2);\n    llh[1] = 2 * atan2( sqrt(e4 - p), sqrt(e2*(e2 - p)) + sqrt(1-e2) * sqrt(p) );\n  } else {\n    // Near the cusps of the evolute\n    double inside_pow = sqrt(evolute) + sqrt(e4 * p * q);\n    u = r + 0.5 * pow(inside_pow,2.0/3.0) +\n      2 * r * r * pow(inside_pow,-2.0/3.0);\n  }\n\n  if (!std::isnan(u) ) {\n    double v = sqrt( u * u + e4 * q );\n    double u_v = u + v;\n    double w = e2 * ( u_v - q ) / ( 2 * v );\n    double k = u_v / ( w + sqrt( w * w + u_v ) );\n    double D = k * xy_dist / ( k + e2 );\n    double dist_2 = D * D + cart[2] * cart[2];\n    llh[2] = ( k + e2 - 1 ) * sqrt( dist_2 ) / k;\n    llh[1] = 2 * atan2( cart[2], sqrt( dist_2 ) + D );\n  }\n\n  if ( xy_dist + cart[0] > ( sqrt(2) - 1 ) * cart[1] ) {\n    // Longitude is between -135 and 135\n    llh[0] = 360.0 * atan2( cart[1], xy_dist + cart[0] ) / M_PI;\n  } else if ( xy_dist + cart[1] < ( sqrt(2) + 1 ) * cart[0] ) {\n    // Longitude is between -225 and 45\n    llh[0] = - 90.0 + 360.0 * atan2( cart[0], xy_dist - cart[1] ) / M_PI;\n  } else {\n    // Longitude is between -45 and 225\n    llh[0] = 90.0 - 360.0 * atan2( cart[0], xy_dist + cart[1] ) / M_PI;\n  }\n  llh[1] *= 180.0 / M_PI;\n\n  return llh;\n}\n\n#if defined(VW_HAVE_PKG_PROTOBUF) && VW_HAVE_PKG_PROTOBUF==1\nTEST( Datum, DatumDesc ) {\n  Datum datum(\"NAD27\");\n\n  DatumDesc desc = datum.build_desc();\n\n  Datum datum2(desc);\n\n  EXPECT_EQ(datum.build_desc().DebugString(), datum2.build_desc().DebugString());\n}\n#endif\n\nTEST( Datum, GeodeticConversion ) {\n  Datum datum(\"WGS84\");\n\n  std::vector<double> values;\n  values += -8000000.,-7000000.,-6500000.,-6100000.,-5788000.,-500000.,-100000.,-50000.,-10000.,-6000.,-1000.,-200.,-1.,0.,8000000.,7000000.,6500000.,6100000.,5788000.,500000.,100000.,50000.,10000.,6000.,1000.,200.,1;\n\n  // The precision seems to be around a center when the vector is near\n  // the center of the earth, which is the worse possible\n  // situation. Things are better near the surface.\n  for ( size_t ix = 0; ix < values.size(); ix++ ) {\n    for ( size_t iy = 0; iy < values.size(); iy++ ) {\n      for ( size_t iz = 0; iz < values.size(); iz++ ) {\n        Vector3 test_xyz(values[ix],values[iy],values[iz]);\n        EXPECT_VECTOR_NEAR( datum.geodetic_to_cartesian(vermille_2011_cart_to_geodetic(datum,test_xyz)),\n                            test_xyz, std::max(1e-12 * norm_2(test_xyz), 1e-2) );\n      }\n    }\n  }\n\n  EXPECT_VECTOR_NEAR( datum.geodetic_to_cartesian(datum.cartesian_to_geodetic(Vector3(10000,10,-10))),\n                      Vector3(10000,10,-10), 1e-6 );\n  EXPECT_VECTOR_NEAR( datum.cartesian_to_geodetic(datum.geodetic_to_cartesian(Vector3(30,-10,173740))),\n                      Vector3(30,-10,173740), 1e-6 );\n\n  datum.set_well_known_datum(\"D_MOON\"); // This is a spherical datum\n\n  // The precision seems to be around a center when the vector is near\n  // the center of the earth, which is the worse possible\n  // situation. Things are better near the surface.\n  for ( size_t ix = 0; ix < values.size(); ix++ ) {\n    for ( size_t iy = 0; iy < values.size(); iy++ ) {\n      for ( size_t iz = 0; iz < values.size(); iz++ ) {\n        Vector3 test_xyz(values[ix],values[iy],values[iz]);\n        EXPECT_VECTOR_NEAR( datum.geodetic_to_cartesian(vermille_2011_cart_to_geodetic(datum,test_xyz)),\n                            test_xyz, std::max(1e-12 * norm_2(test_xyz), 1e-2) );\n      }\n    }\n  }\n\n  EXPECT_VECTOR_NEAR( datum.geodetic_to_cartesian(datum.cartesian_to_geodetic(Vector3(10000,10,-10))),\n                      Vector3(10000,10,-10), 1e-6 );\n  EXPECT_VECTOR_NEAR( datum.cartesian_to_geodetic(datum.geodetic_to_cartesian(Vector3(30,-10,173740))),\n                      Vector3(30,-10,173740), 1e-6 );\n}\n", "meta": {"hexsha": "d2bf96c35c329c52229b0016c4a1055b049ed003", "size": 6275, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/vw/Cartography/tests/TestDatum.cxx", "max_stars_repo_name": "maxsu/visionworkbench", "max_stars_repo_head_hexsha": "34eb3009152d3696471056e65b313d964e658ee8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-12T19:42:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-12T19:42:48.000Z", "max_issues_repo_path": "src/vw/Cartography/tests/TestDatum.cxx", "max_issues_repo_name": "maxsu/visionworkbench", "max_issues_repo_head_hexsha": "34eb3009152d3696471056e65b313d964e658ee8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vw/Cartography/tests/TestDatum.cxx", "max_forks_repo_name": "maxsu/visionworkbench", "max_forks_repo_head_hexsha": "34eb3009152d3696471056e65b313d964e658ee8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2243589744, "max_line_length": 217, "alphanum_fraction": 0.6200796813, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.417623796192907}}
{"text": "// Created by Lina Felsner on Thu Aug 18th 2016\n\n#ifndef __model_fdct_calibration_correction_hxx\n#define __model_fdct_calibration_correction_hxx\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <LibProjectiveGeometry/ProjectionMatrix.h>\n#include \"Model.hxx\"\n\n#include <Utils/Projtable.hxx>\n\nnamespace Geometry {\n\n\tstruct ModelFDCTCalibrationCorrection : public Model<7>\n\t{\n\n\t\tdouble pp_u;\n\t\tdouble pp_v;\n\t\tdouble spacing;\n\t\tdouble sid;\n\t\tdouble sdd;\n\n\t\tstatic std::vector<std::string> ParameterNames()\n\t\t{\n\t\t\tstd::vector<std::string> names;\n\t\t\t// Set parameter names\n\t\t\tnames.resize(size());\n\t\t\tnames[0] = \"Translation u\";\n\t\t\tnames[1] = \"Translation v\";\n\t\t\tnames[2] = \"Yaw\";\n\t\t\tnames[3] = \"Pitch\";\n\t\t\tnames[4] = \"Roll\";\n\t\t\tnames[5] = \"Source Isocenter Distance\";\n\t\t\tnames[6] = \"Source Detector Distance\";\n\t\t\treturn names;\n\t\t}\n\n\t\tenum ParameterSet { Identity, DetectorShifts, DetectorRigid2D, DetectorRotations, SDDandSID, All };\n\t\tstatic std::vector<std::string> ParameterSets()\n\t\t{\n\t\t\tstd::vector<std::string> sets;\n\t\t\tsets[0] = \"Identity\";\n\t\t\tsets[1] = \"DetectorShifts\";\n\t\t\tsets[2] = \"DetectorRigid2D\";\n\t\t\tsets[4] = \"DetectorRotations\";\n\t\t\tsets[5] = \"Source Detector and Iso-Center Distances\";\n\t\t\tsets[6] = \"All\";\n\t\t\treturn sets;\n\t\t}\n\n\t\tvoid computeMeanPPandSIDandSDD(const std::vector<Geometry::ProjectionMatrix> Ps)\n\t\t{\n\t\t\tstd::vector<double> sids, sdds;\n\t\t\tProjTable::ctCircularTrajectoryToParameters(Ps, spacing, 0x0, 0x0, 0x0, &sids, &sdds);\n\n\t\t\t// calculate mean\n\t\t\tdouble sumSID = std::accumulate(sids.begin(), sids.end(), 0.0);\n\t\t\tsid = sumSID / sids.size();\n\t\t\tdouble sumSDD = std::accumulate(sdds.begin(), sdds.end(), 0.0);\n\t\t\tsdd = sumSDD / sdds.size();\n\n\t\t\tstd::cout << \"Mean sid and sdd: \" << sid << \" \" << sdd << std::endl;\n\n\t\t\tGeometry::RP2Point ppmean(0,0,0);\n\t\t\tfor (int i = 0; i < (int)Ps.size(); i++)\n\t\t\t{\n\t\t\t\tGeometry::RP2Point pp=Ps[i].block<3, 3>(0, 0)*Ps[i].block<1, 3>(2, 0).transpose();\n\t\t\t\tpp = pp / pp(2);\n\t\t\t\tppmean+=pp;\n\t\t\t}\n\t\t\tpp_u = ppmean[0] / ppmean(2);\n\t\t\tpp_v = ppmean[1] / ppmean(2);\n\t\t\tstd::cout << \"Mean principal point: \" << pp_u << \" \" << pp_v << std::endl;\n\t\t}\n\n\t\tModelFDCTCalibrationCorrection(int _nu, int _nv, double  _spacing, double sid, double sdd, ParameterSet active = Identity)\n\t\t\t: Model<7>(ParameterNames())\n\t\t\t, pp_u(0.5*_nu)\n\t\t\t, pp_v(0.5*_nv)\n\t\t\t, spacing(_spacing)\n\t\t{\n\t\t\t// Set parameter names\n\t\t\tnames = ModelFDCTCalibrationCorrection::ParameterNames();\n\t\t\t// Set active parameters\n\t\t\tsetActiveParameters(active);\n\t\t}\n\n\t\tModelFDCTCalibrationCorrection(double  _spacing, const std::vector<Geometry::ProjectionMatrix>& Ps, ParameterSet active = Identity)\n\t\t\t: Model<7>(ParameterNames())\n\t\t\t, spacing(_spacing)\n\t\t{\n\t\t\t// Set parameter names\n\t\t\tnames = ModelFDCTCalibrationCorrection::ParameterNames();\n\t\t\t// Set active parameters\n\t\t\tsetActiveParameters(active);\n\t\t\t// Analyze geometry\n\t\t\tcomputeMeanPPandSIDandSDD(Ps);\n\t\t}\n\n\t\t/// Several common sets of active parameters\n\t\tvoid setActiveParameters(ParameterSet set)\n\t\t{\n\t\t\tfor (int i = 0; i<size(); i++) active[i] = (set==All);\n\t\t\t\n\t\t\tswitch (set)\n\t\t\t{\t\n\t\t\t\tdefault:\n\t\t\t\tcase Identity:\n\t\t\t\tcase All:\n\t\t\t\t\tbreak;\n\t\t\t\tcase DetectorShifts:\n\t\t\t\t\tactive[0] = active[1] = true;\n\t\t\t\tbreak;\n\t\t\t\tcase SDDandSID:\n\t\t\t\t\tactive[5] = active[6] = true;\n\t\t\t\tbreak;\n\t\t\t\tcase DetectorRotations:\n\t\t\t\t\tactive[2]=active[3]=active[4]=true;\n\t\t\t\tbreak;\n\t\t\t\tcase DetectorRigid2D:\n\t\t\t\t\tactive[0] =active[1] = active[4] = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// Transform the Projection Matrix via: H*H_init*P*T\n\t\tvoid transform(std::vector<Geometry::ProjectionMatrix> &Ps, Eigen::Matrix3d H_init = Eigen::Matrix3d::Identity()) const\n\t\t{\n\n\t\t\t//TODO \n\t\t\tstd::pair<Eigen::Matrix3d, Eigen::Matrix4d> HT = getTransforms(Ps);\n\t\t\tEigen::Matrix3d H = HT.first;\n\t\t\tEigen::Matrix4d T = HT.second;\n\n\t\t\tfor (int i = 0; i < Ps.size(); i++)\n\t\t\t{\n\t\t\t\tPs[i] = H*H_init*Ps[i]*T;\n\t\t\t\tGeometry::normalizeProjectionMatrix(Ps[i]);\n\t\t\t}\n\t\t}\n\n\t\t// Compose a homography from Parametrization\n\t\tstd::pair<Eigen::Matrix3d, Eigen::Matrix4d> getTransforms(std::vector<Geometry::ProjectionMatrix> Ps) const\n\t\t{\n\t\t\tconst double *x(param); //parameter vector\n\n\t\t\tEigen::Matrix3d H = Eigen::Matrix3d::Identity();\n\t\t\tEigen::Matrix4d T = Eigen::Matrix4d::Identity();\n\n\t\t\tGeometry::RP2Point ppmean(pp_u, pp_v, 1.0);\n\n\t\t\tdouble sid_scale = (sid + x[5]) / sid;\n\t\t\tdouble sdd_scale = (sdd + x[6]) / sdd;\n\n//// H = Matrix 3x3\n\t\t\tEigen::Matrix3d H_roll, H_shift, H_scale;\n\t\t\tH_roll = H_shift = H_scale = H;\n\n\t\t\t// using the principal point / center of the image\n\t\t\tauto Hpp = H, Hppinv = H;\n\t\t\tHpp.block<3, 1>(0, 2) = ppmean;\n\t\t\tHppinv(0, 2) = -ppmean[0];\n\t\t\tHppinv(1, 2) = -ppmean[1];\n\n\t\t\t//Roll -> Rotation\n\t\t\tif (x[4] != 0)\n\t\t\t{\n\t\t\t\tH_roll <<\n\t\t\t\t\t+cos(x[4]), -sin(x[4]), 0,\n\t\t\t\t\t+sin(x[4]), +cos(x[4]), 0,\n\t\t\t\t\t0,\t\t\t0,\t\t\t1;\n\t\t\t}\n\n\t\t\t// Translation u and Yaw\n\t\t\tH_shift(0, 2) += x[0];\n\t\t\tH_shift(0, 2) += tan(x[2])*sdd;\n\n\t\t\t// Translation v and Pitch\n\t\t\tH_shift(1, 2) += x[1];\n\t\t\tH_shift(1, 2) += tan(x[3])*sdd;\n\n\t\t\t//SDD\n\t\t\tH_scale.block<2, 2>(0, 0) *= sdd_scale;\n\n\t\t\tH = H_shift * Hpp * H_roll * H_scale * Hppinv;\n\n//// T = Matrix 4x4\n\t\t\t//SID\n\t\t\tT.block<3, 3>(0, 0) *= sid_scale;\n\n//// HT\n\t\t\tstd::pair<Eigen::Matrix3d, Eigen::Matrix4d> HT = { H, T };\n\t\t\treturn HT;\n\t\t}\n\n\t};\n\n}\n\n#endif // __model_fdct_calibration_correction_hxx", "meta": {"hexsha": "5dc1c496920db7c24a93ee783731b80f5071635c", "size": 5274, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "code/LibProjectiveGeometry/Models/ModelFDCTCalibrationCorrection.hxx", "max_stars_repo_name": "mareikethies/EpipolarConsistency", "max_stars_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-21T16:33:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T03:03:00.000Z", "max_issues_repo_path": "code/LibProjectiveGeometry/Models/ModelFDCTCalibrationCorrection.hxx", "max_issues_repo_name": "mareikethies/EpipolarConsistency", "max_issues_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-14T07:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-14T07:48:55.000Z", "max_forks_repo_path": "code/LibProjectiveGeometry/Models/ModelFDCTCalibrationCorrection.hxx", "max_forks_repo_name": "mareikethies/EpipolarConsistency", "max_forks_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-05-15T21:38:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T07:20:47.000Z", "avg_line_length": 26.2388059701, "max_line_length": 133, "alphanum_fraction": 0.6327265832, "num_tokens": 1785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.41762379619290696}}
{"text": "/* CirKit: A circuit toolkit\n * Copyright (C) 2009-2015  University of Bremen\n * Copyright (C) 2015-2017  EPFL\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"arithmetic.hpp\"\n\n#include <boost/range/counting_range.hpp>\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\n/* move? */\nbdd ite( const bdd& cond, const bdd& _then, const bdd& _else )\n{\n  return ( !cond && _else ) || ( cond && _then );\n}\n\nstd::tuple<bdd, bdd> full_adder( const bdd& x, const bdd& y, const bdd& cin )\n{\n  const auto sum  = x ^ y ^ cin;\n  const auto cout = ( x && y ) || ( x && cin ) || ( y && cin );\n\n  return std::make_tuple( sum, cout );\n}\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nstd::vector<bdd> bdd_subtract( const std::vector<bdd>& minuend, const std::vector<bdd>& subtrahend )\n{\n  assert( minuend.size() == subtrahend.size() );\n  assert( !minuend.empty() );\n\n  std::vector<bdd> diff( minuend.size() );\n  bdd carry = minuend.front().manager->bdd_top();\n\n  for ( const auto& i : boost::counting_range( 0ul, static_cast<unsigned long>( minuend.size() ) ) )\n  {\n    std::tie( diff[i], carry ) = full_adder( minuend[i], !subtrahend[i], carry );\n  }\n\n  return diff;\n}\n\nstd::vector<bdd> bdd_abs( const std::vector<bdd>& n )\n{\n  std::vector<bdd> mask( n.size(), n.back() );\n  std::vector<bdd> result;\n\n  for ( const auto& i : boost::counting_range( 0ul, static_cast<unsigned long>( n.size() ) ) )\n  {\n    result.push_back( n[i] ^ mask[i] );\n  }\n\n  auto diff = bdd_subtract( result, mask );\n  std::copy( diff.begin(), diff.begin() + n.size(), result.begin() );\n\n  return result;\n}\n\nstd::vector<bdd> zero_extend( const std::vector<bdd>& n, unsigned to )\n{\n  assert( to >= n.size() );\n  auto ze = n;\n  ze.resize( to, n.front().manager->bdd_bot() );\n  return ze;\n}\n\nstd::vector<bdd> sign_extend( const std::vector<bdd>& n, unsigned to )\n{\n  assert( to >= n.size() );\n  auto se = n;\n  se.resize( to, n.back() );\n  return se;\n}\n\n}\n\n// Local Variables:\n// c-basic-offset: 2\n// eval: (c-set-offset 'substatement-open 0)\n// eval: (c-set-offset 'innamespace 0)\n// End:\n", "meta": {"hexsha": "003d051635240c95618d7e369c611d4465679e9e", "size": 3741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/dd/arithmetic.cpp", "max_stars_repo_name": "eletesta/cirkit", "max_stars_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/classical/dd/arithmetic.cpp", "max_issues_repo_name": "eletesta/cirkit", "max_issues_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/classical/dd/arithmetic.cpp", "max_forks_repo_name": "eletesta/cirkit", "max_forks_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5304347826, "max_line_length": 100, "alphanum_fraction": 0.5490510559, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.41753366139246473}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n    @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_FLOOR_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_FLOOR_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n\n    @ingroup group-arithmetic\n    This function object computes the greatest integral representable value of\n    its parameter type which is less or equal to it.\n\n    @par Header <boost/simd/function/floor.hpp>\n\n    @par Notes\n\n     - @c floor is also used as parameter to pass to @ref div or @ref rem\n\n    @par Decorators\n\n    - std_ for floating entries call std::floor\n\n    @see  ceil, round, nearbyint, trunc, ifloor\n\n    @par Example:\n\n      @snippet floor.cpp floor\n\n    @par Possible output:\n\n      @snippet floor.txt floor\n\n  **/\n  Value floor(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/floor.hpp>\n#include <boost/simd/function/simd/floor.hpp>\n\n#endif\n", "meta": {"hexsha": "bf01b8c3bf2b519043e5efac95f2d813be526414", "size": 1241, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/floor.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/floor.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/floor.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.4150943396, "max_line_length": 100, "alphanum_fraction": 0.5970991136, "num_tokens": 265, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850932, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.41753366139246473}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n//\n// Copyright (c) 2012 Barend Gehrels, Amsterdam, the Netherlands.\n//\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n// Projection example 5 (reworked from 4), using small factory\n\n#include <fstream>\n\n#include <boost/foreach.hpp>\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/register/point.hpp>\n#include <boost/geometry/multi/geometries/multi_polygon.hpp>\n\n#include <boost/geometry/io/svg/svg_mapper.hpp>\n#include <boost/geometry/extensions/gis/latlong/latlong.hpp>\n\n#include <boost/geometry/extensions/gis/projections/parameters.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/goode.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/moll.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/natearth.hpp>\n#include <boost/geometry/extensions/gis/projections/proj/robin.hpp>\n\n#include <boost/geometry/extensions/gis/projections/new_projection.hpp>\n\n// Define a specific projection transformer\n// (NOTE: this might become part of the library - copied from p04)\ntemplate <typename Projection>\nstruct projection_transformer\n{\n    Projection const& m_prj;\n\n    inline projection_transformer(Projection const& prj)\n        : m_prj(prj)\n    {}\n\n    inline bool apply(typename Projection::geographic_point_type const& p1,\n                typename Projection::cartesian_point_type& p2) const\n    {\n        return m_prj.forward(p1, p2);\n    }\n};\n\nvoid p05_example(int projection_id,\n        std::string const& wkt_filename,\n        std::string const& svg_filename)\n{\n    using namespace boost::geometry;\n    using namespace boost::geometry::projections;\n\n    typedef model::ll::point<degree> pll;\n    typedef model::d2::point_xy<double> pxy;\n\n    // Idea and headerfile \"new_projection\" submitted by Krzysztof Czainski:\n    // They are useful, when:\n    // - you have a small set of types of projections you'll use,\n    // - you know the type of projection during it's creation, and later \n    //   you want to use it through an abstract base pointer,\n    // - you want to avoid the overhead of factory: generating code for\n    //   creating a projection of every type you don't use, and selecting\n    //   the type from a string.\n\n    projection<pll, pxy>* prj = NULL;\n\n    parameters pars = projections::init(\"+ellps=WGS84\");\n    switch(projection_id)\n    {\n        case 1 : prj = new_projection<robin_spheroid<pll, pxy> >(pars); break;\n        case 2 : prj = new_projection<moll_spheroid<pll, pxy> >(pars); break;\n        case 3 : prj = new_projection<goode_spheroid<pll, pxy> >(pars); break;\n        case 4 : prj = new_projection<natearth_spheroid<pll, pxy> >(pars); break;\n        default : return;\n    }\n\n    typedef model::multi_polygon<model::polygon<pll> > mp_ll;\n    typedef model::multi_polygon<model::polygon<pxy> > mp_xy;\n\n    std::vector<mp_ll> countries_in_ll;\n\n    // Read polygons from WKT\n    std::ifstream cpp_file(wkt_filename.c_str());\n    if (! cpp_file.is_open())\n    {\n        throw std::string(\"File not found: \") + wkt_filename;\n    }\n\n    while (! cpp_file.eof() )\n    {\n        std::string line;\n        std::getline(cpp_file, line);\n        if (boost::starts_with(line, \"MULTIPOLYGON\"))\n        {\n            countries_in_ll.resize(countries_in_ll.size() + 1);\n            boost::geometry::read_wkt(line, countries_in_ll.back());\n        }\n    }\n\n    projection_transformer<projection<pll, pxy> > strategy(*prj);\n\n    // Project the polygons, and at the same time get the bounding box (in xy)\n    std::vector<mp_xy> countries_in_xy;\n    model::box<pxy> bbox;\n    assign_inverse(bbox);\n    BOOST_FOREACH(mp_ll const& country_ll, countries_in_ll) \n    {\n        mp_xy country_xy;\n        if (transform(country_ll, country_xy, strategy))\n        {\n            expand(bbox, return_envelope<model::box<pxy> >(country_xy));\n            countries_in_xy.push_back(country_xy);\n        }\n    }\n\n    // Create an SVG image\n    std::ofstream svg(svg_filename.c_str());\n    boost::geometry::svg_mapper<pxy> mapper(svg, 1000, 800);\n    mapper.add(bbox);\n\n    BOOST_FOREACH(mp_xy const& country, countries_in_xy) \n    {\n        mapper.map(country, \"fill-opacity:0.6;fill:rgb(153,204,0);stroke:rgb(0,128,0);stroke-width:0.2\");\n    }\n\n    delete prj;\n}\n\nint main(int argc, char** argv)\n{\n    // Note, file location: trunk/libs/geometry/example/data\n    // update path below if necessary\n    std::string const data = \"../../../../example/data/world.wkt\";\n    try\n    {\n        p05_example(1, data, \"p05_world_1.svg\");\n        p05_example(2, data, \"p05_world_2.svg\");\n        p05_example(3, data, \"p05_world_3.svg\");\n        p05_example(4, data, \"p05_world_4.svg\");\n    }\n    catch(std::exception const& e)\n    {\n        std::cerr << \"Exception: \" << e.what() << std::endl;\n        return 1;\n    }\n    catch(std::string const& s)\n    {\n        std::cerr << \"Exception: \" << s << std::endl;\n        return 1;\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "9cdb496eab683524bd604a560f795688ff390ac5", "size": 5137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/geometry/extensions/example/gis/projections/p05_example.cpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "libs/geometry/extensions/example/gis/projections/p05_example.cpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "libs/geometry/extensions/example/gis/projections/p05_example.cpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 32.9294871795, "max_line_length": 105, "alphanum_fraction": 0.6682888846, "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.41748744708837604}}
{"text": "/**\n * Contains the implementation of the protanope conversion.\n *\n * Copyright 2016 Jacob Voytko (jakevoytko@gmail.com)\n */\n\n\n#include \"proto.hpp\"\n\n#include <math.h>\n#include <algorithm>\n\n#include <boost/scoped_ptr.hpp>\n\n#include \"color.hpp\"\n\nusing video_colorblind::color::Rgb;\nusing video_colorblind::color::Xyy;\nusing video_colorblind::color::Xyz;\n\n\n/** The protanope confusion point in the xyY spectrum. */\nXyy xyyConfusionPoint = Xyy(0.747, 0.253, 1.0);\n\n\n/** Stores the coefficients of a quadratic polynomial. */\nstruct QuadraticPolynomial {\n  QuadraticPolynomial(double xSquare_, double x_, double c_):\n      xSquare(xSquare_), x(x_), c(c_) {}\n\n  const double xSquare;\n  const double x;\n  const double c;\n};\n\n\n/** Calculates a step of the LaGrange interpolation method. */\nQuadraticPolynomial lagrangeStepXyy(\n    const Xyy &xyy0, const Xyy &xyy1, const Xyy &xyy2) {\n  const double xSquare = xyy0.y / ((xyy0.x - xyy1.x) * (xyy0.x - xyy2.x));\n  const double x = xSquare * -xyy1.x + xSquare * -xyy2.x;\n  const double c = xSquare * xyy1.x * xyy2.x;\n  return QuadraticPolynomial(xSquare, x, c);\n}\n\n\n/** Interpolates through the three points given using Lagrange interpolation. */\nQuadraticPolynomial lagrangeInterpolateXyy(\n    const Xyy &xyy0, const Xyy &xyy1, const Xyy &xyy2) {\n  QuadraticPolynomial result0 = lagrangeStepXyy(xyy0, xyy1, xyy2);\n  QuadraticPolynomial result1 = lagrangeStepXyy(xyy1, xyy0, xyy2);\n  QuadraticPolynomial result2 = lagrangeStepXyy(xyy2, xyy0, xyy1);\n\n  return QuadraticPolynomial(\n    result0.xSquare + result1.xSquare + result2.xSquare,\n    result0.x + result1.x + result2.x,\n    result0.c + result1.c + result2.c);\n}\n\n\n/**\n * Protanopes can see wavelengths 470 and 575 correctly, as well as white. Doing\n * polynomial interpolation between these points produces a polynomial that can\n * be used to estimate all colors that protanopes can see.\n */\nQuadraticPolynomial xyyVisionCurve = lagrangeInterpolateXyy(\n  XYY_470, XYY_575, XYY_WHITE_D50);\n\n\n/** Represents a line. */\nstruct Line {\n  Line(double m_, double b_): m(m_), b(b_) {}\n\n  const double m;\n  const double b;\n};\n\n\n/** Calculates a line between the two given xyY coordinates. */\nLine xyyLine(const Xyy &xyy0, const Xyy &xyy1) {\n  // The confusion point for protanopes is outside the sRGB colorspace, so this\n  // can't divide-by-0.\n\n  if (xyy0.x > xyy1.x) {\n    return xyyLine(xyy1, xyy0);\n  }\n  double slope = (xyy1.y - xyy0.y) / (xyy1.x - xyy0.x);\n  return Line(slope, xyy0.y - slope * xyy0.x);\n}\n\n\n/**\n * Protans have a dark response curve at the red end of the spectrum. Some reds\n * are perceived at ~1/10 of the intensity that a normal observer would\n * see. Adjust for this.\n */\ndouble getProtanLuminance(const Xyz &xyz) {\n  return -0.460 * xyz.x + 1.359 * xyz.y + 0.101 * xyz.z;\n}\n\n\n/** \n * Calculates the intersection between a quadratic and a line using the\n * ::drumroll:: quadratic formula!\n */\nXyy intersectCurveLineXyy(\n    const QuadraticPolynomial &poly, const Line &line, double Y) {\n  double A = poly.xSquare;\n  double B = poly.x - line.m;\n  double C = poly.c - line.b;\n  double discriminant = B*B - 4.0 * A * C;\n\n  // Only the smaller X root falls in the color space.\n  assert(discriminant >= 0);\n\n  double x = (-B + sqrt(discriminant)) / (2.0 * A);\n\n  return Xyy(x, line.m * x + line.b, Y);\n}\n\n\n/** \n * If the xyy color falls outside the triangle defined by the sRGB primaries,\n * does a best-effort to move it back within the sRGB triangle by intersecting\n * the confusion line with the sRGB triangle.\n */\nXyy moveWithinRgb(const Line &line, const Xyy &xyy) {\n  // Two cases for protanopes: line intersects Blue->Green, line intersects\n  // Red->Green.\n  Line primaryLine = xyy.x < XYY_GREEN_PRIMARY.x ?\n        xyyLine(XYY_BLUE_PRIMARY, XYY_GREEN_PRIMARY) :\n        xyyLine(XYY_GREEN_PRIMARY, XYY_RED_PRIMARY);\n\n  double y = primaryLine.m * xyy.x + primaryLine.b;\n  if (xyy.y > y) {\n    double newX = (primaryLine.b - line.b) / (line.m - primaryLine.m);\n    double newY = primaryLine.m * newX + primaryLine.b;\n    return Xyy(newX, newY, xyy.Y);\n  }\n\n  return xyy;\n}\n\n\n/** Returns x if within min or max, otherwise the violated bound. */\ndouble clamp(double min, double x, double max) {\n  return std::max(min, std::min(x, max));\n}\n\n\nRgb video_colorblind::color::getProtoColor(const Rgb &inputRgb) {\n  Xyz xyz = rgbToXyz(inputRgb);\n  Xyy xyy = xyzToXyy(xyz);\n\n  // According to\n  // http://nvlpubs.nist.gov/nistpubs/jres/33/jresv33n6p407_A1b.pdf, luminance\n  // for protans must be adjusted because of the weak red frequency response.\n  double protanLuminance = getProtanLuminance(xyz);\n\n  // First, find the confusion line. All colors along this line are perceived as\n  // identical to protanopes.\n  Line confusionLine = xyyLine(xyyConfusionPoint, xyy);\n\n  // The intersection between the vision curve and the confusion line is an\n  // estimation of the color a protanope actually sees.\n  Xyy xyyIntersection = intersectCurveLineXyy(\n    xyyVisionCurve, confusionLine, protanLuminance);\n\n  // The color may have fallen outside the sRGB colorspace. If so, move it back\n  // along the confusion line. Note: This can still convert to colors outside of\n  // the display sRGB colorspace.\n  Xyy boundedXyy = moveWithinRgb(confusionLine, xyyIntersection);\n\n  // Convert back to RGB.\n  Rgb returnRgb = xyzToRgb(xyyToXyz(boundedXyy));\n\n  // Unclear what to do here besides clamp. If this is outside [0-255], then\n  // it's the case where there was no intersection between the confusion line\n  // and the sRGB colorspace.\n  return Rgb(\n    clamp(0, round(returnRgb.r), 255),\n    clamp(0, round(returnRgb.g), 255),\n    clamp(0, round(returnRgb.b), 255));\n}\n", "meta": {"hexsha": "dfd5c49e234dddeb22ef0431eb35780c3de864b4", "size": 5664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "color/proto.cpp", "max_stars_repo_name": "gnott/video_colorblind", "max_stars_repo_head_hexsha": "ac27b3e2d46fb004fe6ed8aac3de2c103ad8d85f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-08-31T18:18:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-26T15:24:47.000Z", "max_issues_repo_path": "color/proto.cpp", "max_issues_repo_name": "gnott/video_colorblind", "max_issues_repo_head_hexsha": "ac27b3e2d46fb004fe6ed8aac3de2c103ad8d85f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "color/proto.cpp", "max_forks_repo_name": "gnott/video_colorblind", "max_forks_repo_head_hexsha": "ac27b3e2d46fb004fe6ed8aac3de2c103ad8d85f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-04-26T15:24:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-26T15:24:53.000Z", "avg_line_length": 30.6162162162, "max_line_length": 80, "alphanum_fraction": 0.7048022599, "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.4174527376356793}}
{"text": "#include <DriftFluxWell.h>\n\n#include <boost/math/special_functions/cbrt.hpp>\n\n#include <cmath>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <queue>\n#include <ctime>\n\n#define PI 3.1415926535897932384626433832795\n\n\n// Namespace =======================================================================================\nnamespace WellSimulator {\n\t\n\ttypedef char\t\t\t\t\t\tstring_type;\n\ttypedef double\t\t\t\t\t\treal_type;\n\ttypedef unsigned int\t\t\t\tuint_type;\n\t//typedef WellSimulator::WellVector   vector_type;\n    typedef std::vector<double>\t\t\t\tvector_type;\n\ttypedef NodeCoordinates\t\t\t\tcoord_type;\n\n    enum{I_DIRECTION, J_DIRECTION, K_DIRECTION};\n    enum{WaterPhase, OilPhase, GasPhase, NumberOfPhases = 3};\n\n\tclass Timer{\n\tpublic:\n        Timer() : m_print_time(false) {}\n\n\t\tinline void start(){\n\t\t\tthis->old = (double)clock()/CLOCKS_PER_SEC;\n\t\t}\n\n\t\tinline void stop(){\n\t\t\tthis->now = (double)clock()/CLOCKS_PER_SEC;\n\t\t}\n\n\t\tinline double elapsed(){\n\t\t\treturn this->now - this->old;\n\t\t}\n\n        inline void print(std::string p_msg){\n            if(m_print_time){\n                std::cout << p_msg << this->elapsed();\n            }            \n        }\n\n        inline void enable_print_time(){\n            m_print_time = true;\n        }\n\n        inline void disable_print_time(){\n            m_print_time = false;\n        }\n\n\tprotected:\n        bool m_print_time;\n\t\tdouble now;\n\t\tdouble old;\n\t};\n\n    real_type calculate_inclination_correction(real_type p_inclination){\n        return - (  boost::math::cbrt(cos(p_inclination)) \n                  * pow( abs(cos(p_inclination)), 1.0/6.0 ) \n                  * pow(1.0 + sin(p_inclination),2.0) \n                 );\n    }\n\t\n\tDriftFluxWell::DriftFluxWell()\n\t{\n\t}\n\tDriftFluxWell::DriftFluxWell(\n\t\t\t\t\t\t\t\t const uint_type& p_nnodes,\n\t\t\t\t\t\t\t\t const real_type& p_radius\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t: m_oil_velocity\t( p_nnodes, 0 ),\n\t\t\t\t\t\t\t\t  m_water_velocity\t( p_nnodes, 0 ),\n\t\t\t\t\t\t\t\t  m_gas_velocity\t( p_nnodes, 0 ),\n\t\t\t\t\t\t\t\t  m_mean_velocity\t( p_nnodes, 0 ),\n\t\t\t\t\t\t\t\t  m_oil_vol_frac\t( p_nnodes, 0 ),\n\t\t\t\t\t\t\t\t  m_water_vol_frac\t( p_nnodes, 0 ),\n\t\t\t\t\t\t\t\t  m_gas_vol_frac\t( p_nnodes, 0 ),\n\t\t\t\t\t\t\t\t  m_gas_vol_frac_old\t( p_nnodes, 0 ),\n\t\t\t\t\t\t\t\t  m_oil_vol_frac_old\t( p_nnodes, 0 ),\n\t\t\t\t\t\t\t\t  m_water_vol_frac_old\t( p_nnodes, 0 ),\n\t\t\t\t\t\t\t\t  m_pressure_old\t\t( p_nnodes, 0 ),\n\t\t\t\t\t\t\t\t  m_mean_velocity_old\t( p_nnodes, 0 ),\t\t\t\t\t\t\t\t  \n\t\t\t\t\t\t\t\t  m_id\t\t\t\t( p_nnodes ),\n\t\t\t\t\t\t\t\t  m_gravity\t\t\t( 3, 0 ),\n\t\t\t\t\t\t\t\t  m_delta\t\t\t( total_var, 0 ),\n                                  m_matrix   (new smatrix_type(total_var*p_nnodes,total_var*p_nnodes)),\n                                  m_variables(new svector_type(total_var*p_nnodes)),\n                                  m_source   (new svector_type(total_var*p_nnodes)),\n                                  m_has_inclination_correction(true)\n\t{\t\t\t\t\t \n\t    \n\n\t\tfor( uint_type i = 0; i < m_id.size(); ++i )\n\t\t{\n\t\t\tthis->m_id[ i ].resize( total_var );\n\t\t\tm_id[ i ][ P ]\t     = total_var*i;\n\t\t\tm_id[ i ][ alpha_g ] = total_var*i + 1;\n\t\t\tm_id[ i ][ alpha_o ] = total_var*i + 2;\n\t\t\tm_id[ i ][ v ]       = total_var*i + 3;\n\t\t}\n\t\tthis->m_coordinates.resize( p_nnodes );\n\t\t\n\t\tthis->m_pressure.resize(p_nnodes, 100000.0);\n\t\tthis->m_nnodes = p_nnodes;\n\t\tthis->m_radius = p_radius;\t\t\n\t}\n\n\n\t\n\tDriftFluxWell::~DriftFluxWell()\n\t{\n\t}\n\n    // Initialize for RESERVOIR SOLVER ---->> FDarcy\n    void DriftFluxWell::Initialize(uint_type p_number_of_completions, uint_type p_direction, real_type p_well_radius, real_type p_BHPressure, vector_type p_well_length){\n\n\n        // first volume has no completions\n/*                            WELL\n             ___________________________________________\n            |   |     |     |     |     |     |     |   |\n            x   |  x  |  x  |  x  |  x  |  x  |  x  |   x\n            |___|_____|_____|_____|_____|_____|_____|___|\n                   ^     ^     ^     ^     ^     ^      ^\n                   |     |     |     |     |     |      |  Lateral Mass Inflow\n*/\n        uint_type well_size = p_number_of_completions+1;\n        m_oil_velocity.resize       ( well_size, 0.0 );\t\n        m_water_velocity.resize\t    ( well_size, 0.0 );\n        m_gas_velocity.resize\t    ( well_size, 0.0 );\n        m_mean_velocity.resize\t    ( well_size, 0.0 );\n        m_oil_vol_frac.resize\t    ( well_size, 0.0 );\n        m_water_vol_frac.resize\t    ( well_size, 0.0 );\n        m_gas_vol_frac.resize\t    ( well_size, 0.0 );\n        m_gas_vol_frac_old.resize\t( well_size, 0.0 );\n        m_oil_vol_frac_old.resize\t( well_size, 0.0 );\n        m_water_vol_frac_old.resize\t( well_size, 0.0 );\n        m_pressure_old.resize\t\t( well_size, 0.0 );\n        m_mean_velocity_old.resize  ( well_size, 0.0 );\t\t\t\t\t\t\t\t  \n        m_id.resize\t\t\t\t    ( well_size );\n        m_gravity.resize\t\t\t( 3, 0.0 );\n        m_delta.resize\t\t\t    ( total_var, 0 );\n        m_total_production.resize   ( NumberOfPhases, 0);\n       \n        m_oil_flow.resize(well_size, MakeShared<ConstantInflow>(0.0));\n        m_gas_flow.resize(well_size, MakeShared<ConstantInflow>(0.0));\n        m_water_flow.resize(well_size, MakeShared<ConstantInflow>(0.0));\n\n        m_matrix\t= SharedPointer<smatrix_type>( new smatrix_type(total_var*well_size,total_var*well_size) );\n        m_variables = SharedPointer<svector_type>( new svector_type(total_var*well_size) );\n        m_source\t= SharedPointer<svector_type>( new svector_type(total_var*well_size) );\n\n        for( uint_type i = 0; i < m_id.size(); ++i )\n        {\n            this->m_id[ i ].resize( total_var );\n            m_id[ i ][ P ]\t     = total_var*i;\n            m_id[ i ][ alpha_g ] = total_var*i + 1;\n            m_id[ i ][ alpha_o ] = total_var*i + 2;\n            m_id[ i ][ v ]       = total_var*i + 3;\n        }\n        this->m_coordinates.resize( well_size );\n\n        this->m_pressure.resize(well_size , p_BHPressure);\n        \n        this->set_bottom_pressure(p_BHPressure);\n        this->m_nnodes = well_size;\n        this->m_radius = p_well_radius;\n\n        this->set_with_gas (true);\n        this->set_mass_flux(false);\n        unsigned NODES = well_size;\n       \n        ////// CREATING WELL COORDINATE VECTOR //\n        std::vector<coord_type> COORD_VECTOR(NODES);\n        COORD_VECTOR[ 0 ][0] = 0;\n        COORD_VECTOR[ 0 ][1] = 0;\n        COORD_VECTOR[ 0 ][2] = 0;\n        if(p_direction == I_DIRECTION){\n            COORD_VECTOR[ 1 ][0] = COORD_VECTOR[ 0 ][0] + 0.1;\n            COORD_VECTOR[ 1 ][1] = 0.0;\n            COORD_VECTOR[ 1 ][2] = 0.0;\n        }\n        if(p_direction == J_DIRECTION){\n            COORD_VECTOR[ 1 ][0] = 0.0;\n            COORD_VECTOR[ 1 ][1] = COORD_VECTOR[ 0 ][1] + 0.1;\n            COORD_VECTOR[ 1 ][2] = 0.0;\n        }\n        if(p_direction == K_DIRECTION){\n            COORD_VECTOR[ 1 ][0] = 0.0;\n            COORD_VECTOR[ 1 ][1] = 0.0;\n            COORD_VECTOR[ 1 ][2] = COORD_VECTOR[ 0 ][2] + 0.1;\n        }\n\n        for( unsigned i = 2; i < NODES; ++i ){\n            double  LENGTH = p_well_length[ i-1 ]; // [ m ]\n            double  ds = LENGTH;\n            if(p_direction == I_DIRECTION){\n                COORD_VECTOR[ i ][0] = COORD_VECTOR[ i-1 ][0] + ds;\n                COORD_VECTOR[ i ][1] = 0.0;\n                COORD_VECTOR[ i ][2] = 0.0;\n            }\n            if(p_direction == J_DIRECTION){\n                COORD_VECTOR[ i ][0] = 0.0;\n                COORD_VECTOR[ i ][1] = COORD_VECTOR[ i-1 ][1] + ds;\n                COORD_VECTOR[ i ][2] = 0.0;\n            }\n            if(p_direction == K_DIRECTION){\n                COORD_VECTOR[ i ][0] = 0.0;\n                COORD_VECTOR[ i ][1] = 0.0;\n                COORD_VECTOR[ i ][2] = COORD_VECTOR[ i-1 ][2] + ds;\n            }\n           \t\t\n        }\n        ////// CREATED....\n\n        double PROFILE_PARAM_C_0 = 1.2;\n        double delta_t = 1.0;\n        double TOLERANCE = 1.0e-4;\n\n        double alpha_G = 0.000001;\n        double alpha_O = 0.999998;\n        double alpha_W = 1.0 - (alpha_G+alpha_O);\n        this->set_constant_vol_frac( alpha_O, alpha_G, alpha_W );\t\n        this->set_dt( delta_t );\n        this->set_final_timestep( 1000 );\n        this->set_C_0( PROFILE_PARAM_C_0 );\n\n        this->set_delta( 0.0001, 0.0001, 0.0001, 0.0001 );\n        this->set_constant_pressure( p_BHPressure );\n        this->set_heel_pressure( p_BHPressure );\n        this->set_constant_velocity( 0.0 );\n\n\n        this->set_boundary_velocity( 0.0 );        \n        this->set_newton_criteria( TOLERANCE );\n\n        inflow_vector_type inflow_gas(NODES, MakeShared<ConstantInflow>(0.0));\n        inflow_vector_type inflow_oil(NODES, MakeShared<ConstantInflow>(0.0));\n        inflow_vector_type inflow_water(NODES, MakeShared<ConstantInflow>(0.0));\n\n        this->initialize_flow(inflow_oil,inflow_water,inflow_gas);\n\n        this->set_coordinates(COORD_VECTOR);\n        this->set_gravity( 0., 0., 9.8 ); \n    }\n\tvoid DriftFluxWell::set_delta( real_type p_delta_P, real_type p_delta_alpha_g, real_type p_delta_alpha_o, real_type p_delta_v )\n\t{\n\t\tthis->m_delta[ P ]\t\t\t= p_delta_P;\n\t\tthis->m_delta[ alpha_g ]\t= p_delta_alpha_g;\n\t\tthis->m_delta[ alpha_o ]\t= p_delta_alpha_o;\n\t\tthis->m_delta[ v ]\t\t\t= p_delta_v;\n\t}\n\tvoid DriftFluxWell::set_dt( real_type p_dt )\n\t{\n\t\tthis->m_dt = p_dt;\n\t}\n\n    real_type norm(vector_type p_vector){\n        real_type Norm = 0;\n        for( uint_type i = 0; i < p_vector.size(); ++i )\n            Norm += p_vector[ i ]*p_vector[ i ];\n        return sqrt(Norm);\n    }\n\tvoid DriftFluxWell::set_bottom_pressure( real_type p_pressure ){\n\t\tthis->m_pressure[ 0 ] = p_pressure;\n\t}\n\n\t\n\tvoid DriftFluxWell::set_with_gas(bool p_choice){\n\t\tthis->m_with_gas = p_choice;\n\t}\n\n\n\treal_type DriftFluxWell::dt(){\n\t\treturn this->m_dt;\n\t}\n\n\treal_type DriftFluxWell::ksi( real_type p_velocity ){\n\t\treturn p_velocity >= 0 ? 0.5 : -0.5;\n        //return 0.0;\n\t}\n\t\n\treal_type DriftFluxWell::Volume( real_type dS ){\n\t\treturn this->area()*dS;\n\t}\n\n\treal_type DriftFluxWell::area(){\n\t\treturn this->m_radius*this->m_radius*PI;\n\t}\n\n\treal_type DriftFluxWell::gas_density(real_type p_pressure){\n\t\t//return 5.9733267069e-6*p_pressure; // Let's assume that for the moment... rho = P/(R.T), \n       // return p_pressure > 0.0 ? p_pressure/(316.0*316.0) : this->m_HEEL_PRESSURE/(316.0*316.0);\n        //return p_pressure/(316.0*316.0);\n        return m_gas_density_model->compute_density(p_pressure);\n        //return 10.0;\n\t\t//return 1.1245;\n\t}\t\t\t\t\t\t\t\t\t   // where R = 518.3 J/(Kg.K)and T = 323 K\t\n\n\treal_type DriftFluxWell::liquid_density(\n\t\t\t\t\t\t\t\t\t\t\treal_type p_oil_vol_frac,\n\t\t\t\t\t\t\t\t\t\t\treal_type p_water_vol_frac,\n\t\t\t\t\t\t\t\t\t\t\treal_type p_pressure\n\t\t\t\t\t\t\t\t\t\t\t)\n\t{    \n        if(p_water_vol_frac < 0.0) p_water_vol_frac = 0.0;\n        if(p_oil_vol_frac   < 0.0) p_oil_vol_frac   = 0.0;\n        real_type den = p_oil_vol_frac + p_water_vol_frac; // denominator\n        if( abs(den) < 1.0e-12){\n            return 0.5*this->oil_density  ( p_pressure ) + 0.5*this->water_density( p_pressure );\n        }\n        else{\n            \n            return (\n                    ( p_oil_vol_frac  *this->oil_density  ( p_pressure ) \n                    + p_water_vol_frac*this->water_density( p_pressure )) / den\t\t\t\t\n                   );\n        }\n\t\t\n\t\t\n\t}\n\n\treal_type DriftFluxWell::oil_density( real_type p_pressure ){\n\t\t//return 1000. + (p_pressure - 100000.0)/1.0e6; // that as well...\n        //return 800.0;\n        return m_oil_density_model->compute_density(p_pressure);\n\t}\n\n\treal_type DriftFluxWell::water_density( real_type p_pressure ){\n\t\t//return 1000. + (p_pressure - 100000.0)/1.0e6; // that as well...\n        //return 1000.0;\n        return m_water_density_model->compute_density(p_pressure);\n\t}\n\n\n\treal_type DriftFluxWell::mean_density( \n\t\t\t\t\t\t\t\t\t\t  const real_type& p_oil_vol_frac,\n\t\t\t\t\t\t\t\t\t\t  const real_type& p_water_vol_frac,\n\t\t\t\t\t\t\t\t\t\t  const real_type& p_gas_vol_frac,\n\t\t\t\t\t\t\t\t\t\t  const real_type& p_pressure\n\t\t\t\t\t\t\t\t\t\t  )\n    {         \n       \n\t\treturn (\n\t\t\t    p_oil_vol_frac   * this->oil_density  (p_pressure) +  \n\t\t\t\tp_water_vol_frac * this->water_density(p_pressure) +  \n\t\t\t\tp_gas_vol_frac   * this->gas_density  (p_pressure) \n\t\t\t   );           \n\t\t\n\t}\n\n\treal_type DriftFluxWell::friction_factor( real_type p_reynolds ){\n\t\t//if( p_reynolds == 0.0 )\n\t\t//\treturn 0.0;\n  //      else{\n  //          double e = 1.0e-4; // FoFo\n  //          double D = 2.0*m_radius;                \n  //          double l = log(pow(7.0/p_reynolds,0.9) + 0.27*e/D);             \n  //          double A = pow(-2.547*l,16.0);              \n  //          double B = pow(37530.0/p_reynolds,16.0);                 \n  //          double f0 = 8.0*pow(pow(8.0/p_reynolds,12.0)+1.0/pow((A+B),1.5),1.0/12.0);             \n  //          return f0;\n  //      }\n        return p_reynolds == 0.0 ? 0.0 : abs(64/p_reynolds); // Laminar AtTheMoment...\t\t\t\n\t}\n\n\treal_type DriftFluxWell::mean_velocity( uint_type p_index ){\n\t\treturn this->m_mean_velocity[ p_index ];\t\t\n\t}\n\t\n\treal_type DriftFluxWell::C_0(){\n\t\treturn this->m_profile_parameter_C_0;\n\t}\n\n\tvoid DriftFluxWell::set_C_0(real_type p_C_0){\n\t\tthis->m_profile_parameter_C_0 = p_C_0;\n\t}\n\n\n\t\n\n\treal_type DriftFluxWell::v_drift_flux( real_type p_gas_vol_frac, real_type p_pressure, real_type p_liquid_density )\n\t{\n\t\treal_type C  = this->m_profile_parameter_C_0;\n\t\treal_type rho_g = this->gas_density( p_pressure );\n\t\treal_type rho_l = p_liquid_density;\n\t\treal_type alphaC_0 = p_gas_vol_frac*C;\n        \n        \n\n\t\treturn 0.05; // SImple scheme\n\t\t//return 0.;  // homogeneous\n\t}\n\n\treal_type DriftFluxWell::mod_v_drift_flux(\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t  real_type p_mean_velocity, \n\t\t\t\t\t\t\t\t\t\t\t  real_type p_gas_vol_frac, \n\t\t\t\t\t\t\t\t\t\t\t  real_type p_oil_vol_frac,\n\t\t\t\t\t\t\t\t\t\t\t  real_type p_water_vol_frac,\n\t\t\t\t\t\t\t\t\t\t\t  real_type p_pressure  \n\t\t\t\t\t\t\t\t\t\t\t  )\n\t{\t\n        if(p_pressure < 0.0 || p_gas_vol_frac < 0.0 || p_oil_vol_frac < 0.0 || p_gas_vol_frac > 1.0 || p_oil_vol_frac > 1.0){\n            m_convergence_status = true;\n            return 0.0;\n        }\n\t\treal_type rho_m = this->mean_density( p_oil_vol_frac, p_water_vol_frac, p_gas_vol_frac, p_pressure );\n\t\treal_type rho_l = this->liquid_density( p_oil_vol_frac, p_water_vol_frac, p_pressure);\n\t\treal_type rho_g = this->gas_density( p_pressure );\n\n        float64 sigma_go = 0.0;\n        float64 sigma_gw = 0.0;\n        float64 interfacial_tension = 0.0;         \n\n        sigma_go = m_gas_oil_interfacial_tension_model->compute_interfacial_tension  ( ( p_pressure < 0.0) ? 0.0 : p_pressure );\n        sigma_gw = m_gas_water_interfacial_tension_model->compute_interfacial_tension( ( p_pressure < 0.0) ? 0.0 : p_pressure );\n         \n        real_type den = p_oil_vol_frac + p_water_vol_frac;        \n        if( abs(den) < 1.0e-12 ){\n            interfacial_tension   = 0.5*(sigma_go + sigma_gw);\n        }\n        else{\n            interfacial_tension = (p_oil_vol_frac*sigma_go + p_water_vol_frac*sigma_gw )/den;\n        }\n\n        float64 min_interfacial_tension = WellConstants::convert_Dynes_per_cm_to_Pa_m();\n        if( interfacial_tension < min_interfacial_tension ){\n            interfacial_tension = min_interfacial_tension;\n        }\n\n        \n        real_type D_hat = sqrt( gravity()*(rho_l - rho_g)/interfacial_tension )*2.0*m_radius;\n        real_type Ku;\n        if(D_hat <= 2.0){\n            Ku = 0.0;\n        }else if(D_hat >= 50){\n            Ku = 3.2;\n        }else{\n            Ku = 2.684*exp(0.003669*D_hat) - 3.847*exp(-0.1853*D_hat);\n        }\n        real_type Vc = pow( interfacial_tension*gravity()*(rho_l - rho_g)/(rho_l*rho_l) , 0.25 );\n        m_gas_liquid_profile_parameter_model->set_flooding_velocity( Ku*sqrt(rho_l/rho_g)*Vc );\n        m_gas_liquid_profile_parameter_model->set_mixture_velocity(p_mean_velocity);\n        m_gas_liquid_profile_parameter_model->set_volume_fraction(p_gas_vol_frac);\n        real_type C_0_gl = m_gas_liquid_profile_parameter_model->compute_profile_parameter();\n        m_gas_liquid_drift_velocity_model->set_volume_fraction(p_gas_vol_frac);\n        m_gas_liquid_drift_velocity_model->set_dispersed_density(rho_g);\n        m_gas_liquid_drift_velocity_model->set_not_dispersed_density(rho_l);\n        m_gas_liquid_drift_velocity_model->set_Ku_critical(Ku);\n        m_gas_liquid_drift_velocity_model->set_characteristic_velocity(Vc);\n        m_gas_liquid_drift_velocity_model->set_profile_parameter(C_0_gl);\n\t\treal_type v_d   = m_gas_liquid_drift_velocity_model->compute_drift_velocity();\n\n        if(m_has_inclination_correction){\n            v_d *= calculate_inclination_correction(m_well_inclination);\n        }        \n\n\t\treturn (v_d+(C_0_gl-1)*p_mean_velocity)/(1-(C_0_gl-1)*p_gas_vol_frac*(rho_l-rho_g)/rho_m );\t\t\n\t}\n\n\treal_type DriftFluxWell::mod_v_drift_flux_ow(\t\t\t\t\t\t\t\t\t\t\t\n\t\t\treal_type p_mean_velocity, \n\t\t\treal_type p_gas_vol_frac, \n\t\t\treal_type p_oil_vol_frac,\n\t\t\treal_type p_water_vol_frac,\n\t\t\treal_type p_pressure  \n\t\t\t)\n\t{\t\n        if(p_pressure < 0.0 || p_gas_vol_frac < 0.0 || p_oil_vol_frac < 0.0 || p_gas_vol_frac > 1.0 || p_oil_vol_frac > 1.0){\n            m_convergence_status = true;\n            return 0.0;\n        }\n\t\treal_type rho_o = this->oil_density( p_pressure );\n\t\treal_type rho_w = this->water_density( p_pressure );\n        real_type rho_l = this->liquid_density( p_oil_vol_frac, p_water_vol_frac, p_pressure );\n        real_type alpha_ol = p_oil_vol_frac/(p_oil_vol_frac + p_water_vol_frac + 1.0e-20);\n        m_oil_water_profile_parameter_model->set_volume_fraction(alpha_ol);       \n        real_type C_0_ow = m_oil_water_profile_parameter_model->compute_profile_parameter();\n        m_oil_water_drift_velocity_model->set_volume_fraction(alpha_ol);\n\n        float64 sigma_go = 0.0;\n        float64 sigma_gw = 0.0;\n        float64 interfacial_tension = 0.0;         \n\n        sigma_go = m_gas_oil_interfacial_tension_model->compute_interfacial_tension  ( ( p_pressure < 0.0) ? 0.0 : p_pressure );\n        sigma_gw = m_gas_water_interfacial_tension_model->compute_interfacial_tension( ( p_pressure < 0.0) ? 0.0 : p_pressure );\n        \n        float64 min_interfacial_tension = WellConstants::convert_Dynes_per_cm_to_Pa_m();\n        interfacial_tension = sigma_gw - sigma_go;\n        if( interfacial_tension < min_interfacial_tension ){\n            interfacial_tension = min_interfacial_tension;\n        }\n\n        real_type Vc = pow( interfacial_tension*gravity()*(rho_w - rho_o)/(rho_w*rho_w) , 0.25 );\n        m_oil_water_drift_velocity_model->set_characteristic_velocity(Vc);\n\t\treal_type v_d   = m_oil_water_drift_velocity_model->compute_drift_velocity();\n\n        if(m_has_inclination_correction){\n            v_d *= calculate_inclination_correction(m_well_inclination);\n        }\n\n        float64 a3 = 0.017*exp( pow(m_well_inclination,3.28) );\n        if (p_gas_vol_frac < a3){\n            v_d = (1.0 - p_gas_vol_frac/a3)*v_d;\n        }\n        else{\n            v_d = 0.0;\n        }\n\n        return (v_d + (C_0_ow - 1.0)*p_mean_velocity)/( 1.0 - (C_0_ow - 1.0)*p_oil_vol_frac*(rho_w-rho_o)/rho_l );\n\t}\n\n\n\n\tvoid DriftFluxWell::set_gravity( real_type p_valueX = 0., real_type p_valueY = 0., real_type p_valueZ = 9.8 )\n\t{\n\t\tthis->m_gravity[ 0 ] = p_valueX;\n\t\tthis->m_gravity[ 1 ] = p_valueY;\n\t\tthis->m_gravity[ 2 ] = p_valueZ;\n\t}\n\treal_type DriftFluxWell::gravity(){\n\t\treturn sqrt( m_gravity[ 0 ]*m_gravity[ 0 ] + m_gravity[ 1 ]*m_gravity[ 1 ] + m_gravity[ 2 ]*m_gravity[ 2 ] );\n\t}\n\n\tvoid DriftFluxWell::set_mean_velocity()\n\t{\t\t\n\t\tfor( uint_type i = 0; i < this->m_nnodes; ++i )\n\t\t{\t\t\t\n\t\t\treal_type   P = this->m_pressure[ i ];\n\t\t\treal_type a_g = this->m_gas_vol_frac[ i ];\n\t\t\treal_type a_o = this->m_oil_vol_frac[ i ];\n\t\t\treal_type a_w = this->m_water_vol_frac[ i ];\n\t\t\treal_type d_g = this->gas_density( P );\n\t\t\treal_type d_o = this->oil_density( P );\n\t\t\treal_type d_w = this->water_density( P );\n\t\t\treal_type v_g = this->m_gas_velocity[ i ];\n\t\t\treal_type v_o = this->m_oil_velocity[ i ];\n\t\t\treal_type v_w = this->m_water_velocity [ i ];\n\t\t\treal_type d_m = this->mean_density( a_o, a_w, a_g, P );\t\t\n\t\t\tthis->m_mean_velocity[ i ] = (a_g*d_g*v_g + a_o*d_o*v_o + a_w*d_w*v_w) / d_m; \t\t\t\t\t\t\t\t\t\t  \n\t\t}\n\t}\n\n\tvoid DriftFluxWell::set_constant_oil_vol_frac( real_type p_value )\n\t{\n\t\tfor( uint_type i = 0; i < this->m_nnodes; ++i )\n\t\t{\t\t\n\t\t\tthis->m_oil_vol_frac[ i ] = p_value;\t\t\t\t\t\t\t\t  \n\t\t}\n\t}\n\n\tvoid DriftFluxWell::set_constant_vol_frac( \n\t\t\t\t\t\t\t\t\t\t\t  real_type p_oil_vol_frac, \n\t\t\t\t\t\t\t\t\t\t\t  real_type p_gas_vol_frac, \n\t\t\t\t\t\t\t\t\t\t\t  real_type p_water_vol_frac \n\t\t\t\t\t\t\t\t\t\t\t  )\n\t{\n\t\tfor( uint_type i = 0; i < this->m_nnodes; ++i )\n\t\t{\t\t\n\t\t\tthis->m_oil_vol_frac[ i ]   = p_oil_vol_frac;\n\t\t\tthis->m_gas_vol_frac[ i ]   = p_gas_vol_frac;\n\t\t\tthis->m_water_vol_frac[ i ] = p_water_vol_frac;\n\t\t}\n\t}\n\n\tvoid DriftFluxWell::set_constant_pressure( real_type p_pressure )\n\t{\n\t\tfor( uint_type i = 0; i < this->m_nnodes; ++i )\n\t\t{\t\t\n\t\t\tthis->m_pressure[ i ] = p_pressure;\n\t\t}\n\t}\n\n\tvoid DriftFluxWell::set_constant_velocity( real_type p_velocity )\n\t{\n\t\tfor( uint_type i = 0; i < this->m_nnodes; ++i )\n\t\t{\t\t\n\t\t\tthis->m_mean_velocity[ i ] = p_velocity;\n\t\t}\n\t}\n\t\n\tuint_type DriftFluxWell::id( uint_type p_node , uint_type p_variable ){\n\t\treturn this->m_id[ p_node ][ p_variable ];\n\t}\n\t\n\treal_type DriftFluxWell::segment_length( coord_type p_coord_i, coord_type p_coord_j )\n\t{\t\t\n\t\treturn sqrt( \n\t\t\t\t\t(p_coord_i.getX()-p_coord_j.getX())*(p_coord_i.getX()-p_coord_j.getX())\n\t\t\t\t   +(p_coord_i.getY()-p_coord_j.getY())*(p_coord_i.getY()-p_coord_j.getY()) \n\t\t\t\t   +(p_coord_i.getZ()-p_coord_j.getZ())*(p_coord_i.getZ()-p_coord_j.getZ())\n\t\t\t\t   );\n\t}\n\treal_type DriftFluxWell::dot( vector_type& p_vec1, vector_type& p_vec2 )\n\t{\n\t\treal_type sum = 0;\n\t\tif (p_vec1.size() != p_vec2.size()){\n\t\t\tthrow std::runtime_error(\"Vector's length do not match...\");\n\t\t}\n\t\tfor( uint_type i = 0; i < p_vec1.size(); ++i )\n\t\t\tsum += p_vec1[ i ]*p_vec2[ i ];\n\t\treturn sum;           \n\t}\n\n\tvoid DriftFluxWell::set_newton_criteria(real_type p_tolerance){\n\t\tthis->NEWTON_CRIT = p_tolerance;\n\t}\n\n\tvoid DriftFluxWell::set_final_timestep(uint_type p_final_timestep ){\n\t\tthis->m_FINAL_TIMESTEP = p_final_timestep;\n\t}\n\treal_type DriftFluxWell::gas_viscosity( real_type p_pressure ){\n\t\t//return 5.0e-6;\n        return m_gas_viscosity_model->compute_viscosity(p_pressure);\n\t}\n\n\treal_type DriftFluxWell::oil_viscosity( real_type p_pressure ){\n\t\t//return 0.05;\n        return m_oil_viscosity_model->compute_viscosity(p_pressure);\n\t}\n\n\treal_type DriftFluxWell::water_viscosity( real_type p_pressure ){\n\t\t//return 0.05;\n        return m_water_viscosity_model->compute_viscosity(p_pressure);\n\t}\n\n\n\treal_type DriftFluxWell::R_m(\n\t\t\t\t\t\t\t\t real_type p_pressureW,\n\t\t\t\t\t\t\t\t real_type p_pressureP,\n\t\t\t\t\t\t\t\t real_type p_pressureE,\n\t\t\t\t\t\t\t\t real_type p_gas_vol_fracW,\n\t\t\t\t\t\t\t\t real_type p_gas_vol_fracP,\n\t\t\t\t\t\t\t\t real_type p_gas_vol_fracE,\n\t\t\t\t\t\t\t\t real_type p_oil_vol_fracW,\n\t\t\t\t\t\t\t\t real_type p_oil_vol_fracP,\n\t\t\t\t\t\t\t\t real_type p_oil_vol_fracE,\n\t\t\t\t\t\t\t\t real_type p_velocityW,\n\t\t\t\t\t\t\t\t real_type p_velocityP,\n\t\t\t\t\t\t\t\t uint_type p_node,\n\t\t\t\t\t\t\t\t string_type\t   position = 'C'\n\t\t\t\t\t\t\t\t )\n\t{\n\t\t\n\t\tswitch ( position )\n\t\t{\n\t\t\n\t\tcase 'L':\n\t\t\t{\n\t\t\t\treal_type dSw = 0.5*this->segment_length( m_coordinates[ p_node-1 ], m_coordinates[ p_node ] );\n\t\t\t\treal_type dSe = 0.;\n\t\t\t\treal_type dS  = dSw + dSe;\n\t\t\t\treal_type dV = this->Volume( dS );\n\n\t\t\t\treal_type water_vol_fracOld = 1.0 - (m_oil_vol_frac_old[ p_node ] + m_gas_vol_frac_old[ p_node ]);\n\t\t\t\treal_type water_vol_fracW\t= 1.0 - (p_gas_vol_fracW + p_oil_vol_fracW);\n\t\t\t\treal_type water_vol_fracP\t= 1.0 - (p_gas_vol_fracP + p_oil_vol_fracP);\n\n\t\t\t\treal_type rho_P_old = this->mean_density(m_oil_vol_frac_old[ p_node ], water_vol_fracOld, m_gas_vol_frac_old[ p_node ], m_pressure_old[ p_node ]);\n                \n                real_type rho_P = this->mean_density(p_oil_vol_fracP, water_vol_fracP, p_gas_vol_fracP, p_pressureP);\t\t\t\n\t\t\t\treal_type rho_W = this->mean_density(p_oil_vol_fracW, water_vol_fracW, p_gas_vol_fracW, p_pressureW);\n\n                real_type rhoG_P\t\t= this->gas_density( p_pressureP );\t\t\t\n                real_type rhoG_W\t\t= this->gas_density( p_pressureW );\n\n                real_type rhoW_P\t\t= this->water_density( p_pressureP );\t\t\t\n                real_type rhoW_W\t\t= this->water_density( p_pressureW );\n\n                real_type rhoO_P_old\t= this->oil_density( m_pressure_old[ p_node ] );\t\n                real_type rhoO_P\t\t= this->oil_density( p_pressureP );\t\t\t\n                real_type rhoO_W\t\t= this->oil_density( p_pressureW );\n\n                real_type rhoL_P\t\t= this->liquid_density( p_oil_vol_fracP, water_vol_fracP, p_pressureP );\t\t\t\n                real_type rhoL_W\t\t= this->liquid_density( p_oil_vol_fracW, water_vol_fracW, p_pressureW );\n                \n                real_type mixture_inlet;\n\n                real_type Qoil = m_oil_flow[ p_node ]->get_current_value();\n                real_type Qwater = m_water_flow[ p_node ]->get_current_value();\n                real_type Qgas = m_gas_flow[ p_node ]->get_current_value();\n\n                if(m_mass_flux){   \n                    mixture_inlet = Qoil + Qwater + Qgas;\n                }                      \n                else\n                {\n\t\t\t\t    real_type rhoGas_P\t     = this->gas_density\t( p_pressureP );\n\t\t\t\t    real_type rhoWater_P\t = this->water_density\t( p_pressureP );\n\t\t\t\t    real_type rhoOil_P\t     = this->oil_density\t( p_pressureP );\n\t\t\t\t    mixture_inlet  = rhoOil_P*Qoil + rhoWater_P*Qwater + rhoGas_P*Qgas;\n                }  \t\t\t\t\n\n\t\t\t\t\n\n\n                real_type mod_Vow_w\t= this->mod_v_drift_flux_ow( \n                    p_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n                    0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n                    );\n\n\n                real_type mod_Vgj_w\t= this->mod_v_drift_flux( \n                    p_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n                    0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n                    );\n\n                real_type gas_vol_frac_w   = 0.5*(p_gas_vol_fracP + p_gas_vol_fracW);\n                real_type oil_vol_frac_w   = 0.5*(p_oil_vol_fracP + p_oil_vol_fracW);\n                real_type water_vol_frac_w = 0.5*(water_vol_fracP + water_vol_fracW);\n                real_type rho_g_w = 0.5*(rhoG_W + rhoG_P);\n                real_type rho_o_w = 0.5*(rhoO_W + rhoO_P);\n                real_type rho_w_w = 0.5*(rhoW_W + rhoW_P);\n                real_type rho_l_w = 0.5*(rhoL_W + rhoL_P);\n                real_type rho_w = 0.5*(rho_W + rho_P);\n\n                real_type gas_velocity_w   = p_velocityW + rho_l_w/rho_w*mod_Vgj_w;\n                real_type liquid_velocity_w = p_velocityW - gas_vol_frac_w/(1 - gas_vol_frac_w + 1.0e-20)*rho_g_w/rho_w*mod_Vgj_w;\n                real_type oil_velocity_w   = liquid_velocity_w + rho_w_w/rho_l_w*mod_Vow_w;               \n                real_type water_velocity_w = liquid_velocity_w - (oil_vol_frac_w/(water_vol_frac_w + 1.0e-20))*(rho_o_w/rho_l_w)*mod_Vow_w;               \n                \n              \n\n                real_type ksi_w_oil     = this->ksi( oil_velocity_w   );\n                real_type ksi_w_gas     = this->ksi( gas_velocity_w   );\n                real_type ksi_w_water   = this->ksi( water_velocity_w );\n\n                real_type m_w_oil   = oil_velocity_w  *( (0.5+ksi_w_oil  )*rhoO_W*p_oil_vol_fracW + (0.5-ksi_w_oil  )*rhoO_P*p_oil_vol_fracP );\n                real_type m_w_water = water_velocity_w*( (0.5+ksi_w_water)*rhoW_W*water_vol_fracW + (0.5-ksi_w_water)*rhoW_P*water_vol_fracP );\n                real_type m_w_gas   = gas_velocity_w  *( (0.5+ksi_w_gas  )*rhoG_W*p_gas_vol_fracW + (0.5-ksi_w_gas  )*rhoG_P*p_gas_vol_fracP );\n\n                return (rho_P-rho_P_old)*dV/dt() - mixture_inlet \n                    +\tarea()*( p_velocityP*rho_P - (m_w_oil + m_w_water + m_w_gas) );\n\n                //real_type ksi_w = this->ksi( p_velocityW );\t\n\t\t\t/*return (rho_P-rho_P_old)*dV/dt() - mixture_inlet \n\t\t\t\t  +\tarea()*( p_velocityP*rho_P \n\t\t\t\t\t\t   - p_velocityW*( (0.5+ksi_w)*rho_W + (0.5-ksi_w)*rho_P ) );*/\t\n\t\t\t\n\t\t\t}\t\t\t\n\t\t\n\t\tcase 'C':\n\t\t\t{\n\t\t\t\t\n\t\t\t\treal_type dSw = 0.5*this->segment_length( m_coordinates[ p_node-1 ], m_coordinates[ p_node ] );\n\t\t\t\treal_type dSe = 0.5*this->segment_length( m_coordinates[ p_node ], m_coordinates[ p_node+1 ] );\n\t\t\t\treal_type dS  = dSw + dSe;\n\t\t\t\treal_type dV = this->Volume( dS );\n\n\t\t\t\treal_type water_vol_fracOld = 1.0 - (m_oil_vol_frac_old[ p_node ] + m_gas_vol_frac_old[ p_node ]);\n\t\t\t\treal_type water_vol_fracW\t= 1.0 - (p_gas_vol_fracW + p_oil_vol_fracW);\n\t\t\t\treal_type water_vol_fracP\t= 1.0 - (p_gas_vol_fracP + p_oil_vol_fracP);\n\t\t\t\treal_type water_vol_fracE\t= 1.0 - (p_gas_vol_fracE + p_oil_vol_fracE);\n\n\t\t\t\treal_type rho_P_old = this->mean_density(m_oil_vol_frac_old[ p_node ], water_vol_fracOld, m_gas_vol_frac_old[ p_node ], m_pressure_old[ p_node ]);\n                \n\n\n\t\t\t\treal_type rho_P = this->mean_density(p_oil_vol_fracP, water_vol_fracP, p_gas_vol_fracP, p_pressureP);\n\t\t\t\treal_type rho_E = this->mean_density(p_oil_vol_fracE, water_vol_fracE, p_gas_vol_fracE, p_pressureE);\n\t\t\t\treal_type rho_W = this->mean_density(p_oil_vol_fracW, water_vol_fracW, p_gas_vol_fracW, p_pressureW);\n\n                real_type rhoG_P\t\t= this->gas_density( p_pressureP );\n                real_type rhoG_E\t\t= this->gas_density( p_pressureE );\n                real_type rhoG_W\t\t= this->gas_density( p_pressureW );\n\n                real_type rhoW_P\t\t= this->water_density( p_pressureP );\n                real_type rhoW_E\t\t= this->water_density( p_pressureE );\n                real_type rhoW_W\t\t= this->water_density( p_pressureW );\n\n                real_type rhoO_P_old\t= this->oil_density( m_pressure_old[ p_node ] );\t\n                real_type rhoO_P\t\t= this->oil_density( p_pressureP );\n                real_type rhoO_E\t\t= this->oil_density( p_pressureE );\n                real_type rhoO_W\t\t= this->oil_density( p_pressureW );\n\n                real_type rhoL_P\t\t= this->liquid_density( p_oil_vol_fracP, water_vol_fracP, p_pressureP );\n                real_type rhoL_E\t\t= this->liquid_density( p_oil_vol_fracE, water_vol_fracE, p_pressureE );\n                real_type rhoL_W\t\t= this->liquid_density( p_oil_vol_fracW, water_vol_fracW, p_pressureW );\n                \n                real_type mixture_inlet;\n\n                real_type Qoil = m_oil_flow[ p_node ]->get_current_value();\n                real_type Qwater = m_water_flow[ p_node ]->get_current_value();\n                real_type Qgas = m_gas_flow[ p_node ]->get_current_value();\n\n                if(m_mass_flux){   \n                    mixture_inlet = Qoil + Qwater + Qgas;\n                }                      \n                else\n                {\n                    real_type rhoGas_P\t     = this->gas_density\t( p_pressureP );\n                    real_type rhoWater_P\t = this->water_density\t( p_pressureP );\n                    real_type rhoOil_P\t     = this->oil_density\t( p_pressureP );\n                    mixture_inlet  = rhoOil_P*Qoil + rhoWater_P*Qwater + rhoGas_P*Qgas;\n                }  \n\n\n                real_type mod_Vow_e\t= this->mod_v_drift_flux_ow( \n                    p_velocityP, 0.5*(p_gas_vol_fracP + p_gas_vol_fracE), 0.5*(p_oil_vol_fracP + p_oil_vol_fracE),\n                    0.5*(water_vol_fracP + water_vol_fracE), 0.5*(p_pressureP + p_pressureE)\n                    );\n\n                real_type mod_Vow_w\t= this->mod_v_drift_flux_ow( \n                    p_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n                    0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n                    );\n\n                real_type mod_Vgj_e\t\t= this->mod_v_drift_flux( \n                    p_velocityP, 0.5*(p_gas_vol_fracP + p_gas_vol_fracE), 0.5*(p_oil_vol_fracP + p_oil_vol_fracE),\n                    0.5*(water_vol_fracP + water_vol_fracE), 0.5*(p_pressureP + p_pressureE)\n                    );\n\n                real_type mod_Vgj_w\t\t= this->mod_v_drift_flux( \n                    p_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n                    0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n                    );\n\n                real_type gas_vol_frac_w   = 0.5*(p_gas_vol_fracP + p_gas_vol_fracW);\n                real_type oil_vol_frac_w   = 0.5*(p_oil_vol_fracP + p_oil_vol_fracW);\n                real_type water_vol_frac_w = 0.5*(water_vol_fracP + water_vol_fracW);\n                real_type rho_g_w = 0.5*(rhoG_W + rhoG_P);\n                real_type rho_o_w = 0.5*(rhoO_W + rhoO_P);\n                real_type rho_w_w = 0.5*(rhoW_W + rhoW_P);\n                real_type rho_l_w = 0.5*(rhoL_W + rhoL_P);\n                real_type rho_w = 0.5*(rho_W + rho_P);\n\n                real_type gas_velocity_w   = p_velocityW + rho_l_w/rho_w*mod_Vgj_w;\n                real_type liquid_velocity_w = p_velocityW - gas_vol_frac_w/(1 - gas_vol_frac_w + 1.0e-20)*rho_g_w/rho_w*mod_Vgj_w;\t \n                real_type water_velocity_w = liquid_velocity_w - (oil_vol_frac_w/(water_vol_frac_w + 1.0e-20))*(rho_o_w/rho_l_w)*mod_Vow_w;               \n                real_type oil_velocity_w = liquid_velocity_w + rho_w_w/rho_l_w*mod_Vow_w;  \n\n                \n                \n                real_type gas_vol_frac_e   = 0.5*(p_gas_vol_fracP + p_gas_vol_fracE);\n                real_type oil_vol_frac_e   = 0.5*(p_oil_vol_fracP + p_oil_vol_fracE);\n                real_type water_vol_frac_e = 0.5*(water_vol_fracP + water_vol_fracE);\n                real_type rho_g_e = 0.5*(rhoG_E + rhoG_P);\n                real_type rho_o_e = 0.5*(rhoO_E + rhoO_P);\n                real_type rho_w_e = 0.5*(rhoW_E + rhoW_P);\n                real_type rho_l_e = 0.5*(rhoL_E + rhoL_P);\n                real_type rho_e = 0.5*(rho_E + rho_P);\n\n                real_type gas_velocity_e = p_velocityP + rho_l_e/rho_e*mod_Vgj_e;\n                real_type liquid_velocity_e = p_velocityP - gas_vol_frac_e/(1 - gas_vol_frac_e + 1.0e-20)*rho_g_e/rho_e*mod_Vgj_e;\t \n                real_type water_velocity_e = liquid_velocity_e - (oil_vol_frac_e/(water_vol_frac_e + 1.0e-20))*(rho_o_e/rho_l_e)*mod_Vow_e;               \n                real_type oil_velocity_e = liquid_velocity_e + rho_w_e/rho_l_e*mod_Vow_e;\n\n              \n\n                real_type ksi_e_oil     = this->ksi( oil_velocity_e   );\n                real_type ksi_e_gas     = this->ksi( gas_velocity_e   );\n                real_type ksi_e_water   = this->ksi( water_velocity_e );\n\n                real_type ksi_w_oil     = this->ksi( oil_velocity_w   );\n                real_type ksi_w_gas     = this->ksi( gas_velocity_w   );\n                real_type ksi_w_water   = this->ksi( water_velocity_w );\t\n\n                real_type m_w_oil   = oil_velocity_w  *( (0.5+ksi_w_oil  )*rhoO_W*p_oil_vol_fracW + (0.5-ksi_w_oil  )*rhoO_P*p_oil_vol_fracP );\n                real_type m_w_water = water_velocity_w*( (0.5+ksi_w_water)*rhoW_W*water_vol_fracW + (0.5-ksi_w_water)*rhoW_P*water_vol_fracP );\n                real_type m_w_gas   = gas_velocity_w  *( (0.5+ksi_w_gas  )*rhoG_W*p_gas_vol_fracW + (0.5-ksi_w_gas  )*rhoG_P*p_gas_vol_fracP );\n\n                real_type m_e_oil   = oil_velocity_e  *( (0.5+ksi_e_oil  )*rhoO_P*p_oil_vol_fracP + (0.5-ksi_e_oil  )*rhoO_E*p_oil_vol_fracE );\n                real_type m_e_water = water_velocity_e*( (0.5+ksi_e_water)*rhoW_P*water_vol_fracP + (0.5-ksi_e_water)*rhoW_E*water_vol_fracE );\n                real_type m_e_gas   = gas_velocity_e  *( (0.5+ksi_e_gas  )*rhoG_P*p_gas_vol_fracP + (0.5-ksi_e_gas  )*rhoG_E*p_gas_vol_fracE );\n\n\n                return (rho_P-rho_P_old)*dV/dt() - mixture_inlet \n                    + area()*( m_e_oil+m_e_water+m_e_gas - ( m_w_oil+m_w_water+m_w_gas ) );\n\n\n\t\t\t\t/*real_type ksi_e = this->ksi( p_velocityP );\n\t\t\t\treal_type ksi_w = this->ksi( p_velocityW );\t\t\t\n\n\t\t\treturn (rho_P-rho_P_old)*dV/dt() - mixture_inlet \n\t\t\t\t  + area()*( p_velocityP*( (0.5+ksi_e)*rho_P + (0.5-ksi_e)*rho_E )\n\t\t\t\t\t\t   - p_velocityW*( (0.5+ksi_w)*rho_W + (0.5-ksi_w)*rho_P ) );*/\n\t\t\t\t\t\t\n\t\t\t}\n\t\tdefault:\n\t\t\treturn 0.;\t\n\t\t}\n\t\t\n\t}\n\n\treal_type DriftFluxWell::R_g(\n\t\t\t\t\t\t\t\t real_type p_pressureW,\n\t\t\t\t\t\t\t\t real_type p_pressureP,\n\t\t\t\t\t\t\t\t real_type p_pressureE,\n\t\t\t\t\t\t\t\t real_type p_gas_vol_fracW,\n\t\t\t\t\t\t\t\t real_type p_gas_vol_fracP,\n\t\t\t\t\t\t\t\t real_type p_gas_vol_fracE,\n\t\t\t\t\t\t\t\t real_type p_oil_vol_fracW,\n\t\t\t\t\t\t\t\t real_type p_oil_vol_fracP,\n\t\t\t\t\t\t\t\t real_type p_oil_vol_fracE,\n\t\t\t\t\t\t\t\t real_type p_velocityW,\n\t\t\t\t\t\t\t\t real_type p_velocityP,\n\t\t\t\t\t\t\t\t uint_type p_node,\n\t\t\t\t\t\t\t\t string_type\t   position = 'C'\n\t\t\t\t\t\t\t\t )\n\t{\n\t\tswitch( position )\n\t\t{\n\n\t\tcase 'L':\n\t\t\t{\n\t\t\t\treal_type dSw = 0.5*this->segment_length( m_coordinates[ p_node-1 ], m_coordinates[ p_node ] );\n\t\t\t\treal_type dSe = 0.;\n\t\t\t\treal_type dS  = dSw + dSe;\n\t\t\t\treal_type dV = this->Volume( dS );\n\n\t\t\t\treal_type water_vol_fracW\t= 1.0 - (p_gas_vol_fracW + p_oil_vol_fracW);\n\t\t\t\treal_type water_vol_fracP\t= 1.0 - (p_gas_vol_fracP + p_oil_vol_fracP);\n\n\t\t\t\treal_type rho_P\t\t= this->mean_density(p_oil_vol_fracP, water_vol_fracP, p_gas_vol_fracP, p_pressureP);\t\t\t\n\t\t\t\treal_type rho_W\t\t= this->mean_density(p_oil_vol_fracW, water_vol_fracW, p_gas_vol_fracW, p_pressureW);\n\n\t\t\t\treal_type rhoG_P_old\t= this->gas_density( m_pressure_old[ p_node ] );\t\n\t\t\t\treal_type rhoG_P\t\t= this->gas_density( p_pressureP );\t\t\t\n\t\t\t\treal_type rhoG_W\t\t= this->gas_density( p_pressureW );\n\n\t\t\t\treal_type rhoL_P\t\t= this->liquid_density( p_oil_vol_fracP, water_vol_fracP, p_pressureP );\t\t\t\n\t\t\t\treal_type rhoL_W\t\t= this->liquid_density( p_oil_vol_fracW, water_vol_fracW, p_pressureW );\n                \n                real_type gas_inlet;\n\n                real_type Qgas = m_gas_flow[ p_node ]->get_current_value();\n                if(m_mass_flux){\n                    gas_inlet = Qgas;\n                }                      \n                else\n                {\n                    gas_inlet = rhoG_P*Qgas;\n                }\n\n\n\n\t\t\t\treal_type mod_Vgj_w\t= this->mod_v_drift_flux( \n\t\t\t\t\tp_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n\t\t\t\t\t0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n\t\t\t\t\t);\n\n                real_type gas_velocity_w = p_velocityW + 0.5*(rhoL_W + rhoL_P)/(0.5*(rho_W + rho_P))*mod_Vgj_w;\n\t\t\t\treal_type ksi_w = this->ksi( gas_velocity_w );\t\n\n                return (p_gas_vol_fracP*rhoG_P - m_gas_vol_frac_old[ p_node ]*rhoG_P_old)*dV/dt() - gas_inlet\t\t\t\t \n\t\t\t\t + p_velocityP*area()*rhoG_P*p_gas_vol_fracP\n\t\t\t\t - gas_velocity_w*area()*( (0.5+ksi_w)*rhoG_W*p_gas_vol_fracW + (0.5-ksi_w)*rhoG_P*p_gas_vol_fracP );\t\t\t\t \n\n\t\t\t//return (p_gas_vol_fracP*rhoG_P - m_gas_vol_frac_old[ p_node ]*rhoG_P_old)*dV/dt() - gas_inlet\t\t\t\t \n\t\t\t//\t + p_velocityP*area()*rhoG_P*p_gas_vol_fracP\n\t\t\t//\t - p_velocityW*area()*( (0.5+ksi_w)*rhoG_W*p_gas_vol_fracW + (0.5-ksi_w)*rhoG_P*p_gas_vol_fracP )\t\t\t\t \n\t\t\t//\t //+ mod_Vgj_e*area()*( rhoG_P*rhoL_P/rho_P * p_gas_vol_fracP )\n\t\t\t//\t - mod_Vgj_w*area()*( (0.5+ksi_w)*rhoG_W*rhoL_W/rho_W * p_gas_vol_fracW + (0.5-ksi_w)*rhoG_P*rhoL_P/rho_P * p_gas_vol_fracP );\t\t\t\n\t\t\t\n\t\t\t}\n\t\t\t\n\n\t\tcase 'C':\n\t\t\t{\n\t\t\t\treal_type dSw = 0.5*this->segment_length( m_coordinates[ p_node-1 ], m_coordinates[ p_node ] );\n\t\t\t\treal_type dSe = 0.5*this->segment_length( m_coordinates[ p_node ], m_coordinates[ p_node+1 ] );\n\t\t\t\treal_type dS  = dSw + dSe;\n\t\t\t\treal_type dV  = this->Volume( dS );\t\t\t\n\n\t\t\t\treal_type water_vol_fracW\t= 1.0 - (p_gas_vol_fracW + p_oil_vol_fracW);\n\t\t\t\treal_type water_vol_fracP\t= 1.0 - (p_gas_vol_fracP + p_oil_vol_fracP);\n\t\t\t\treal_type water_vol_fracE\t= 1.0 - (p_gas_vol_fracE + p_oil_vol_fracE);\n\n\t\t\t\treal_type rho_P\t\t= this->mean_density(p_oil_vol_fracP, water_vol_fracP, p_gas_vol_fracP, p_pressureP);\t\n\t\t\t\treal_type rho_E\t\t= this->mean_density(p_oil_vol_fracE, water_vol_fracE, p_gas_vol_fracE, p_pressureE);\n\t\t\t\treal_type rho_W\t\t= this->mean_density(p_oil_vol_fracW, water_vol_fracW, p_gas_vol_fracW, p_pressureW);\n\n\t\t\t\treal_type rhoG_P_old = this->gas_density( m_pressure_old[ p_node ] );\t\n\t\t\t\treal_type rhoG_P\t\t= this->gas_density( p_pressureP );\n\t\t\t\treal_type rhoG_E\t\t= this->gas_density( p_pressureE );\n\t\t\t\treal_type rhoG_W\t\t= this->gas_density( p_pressureW );\n\n\t\t\t\treal_type rhoL_P\t\t= this->liquid_density( p_oil_vol_fracP, water_vol_fracP, p_pressureP );\n\t\t\t\treal_type rhoL_E\t\t= this->liquid_density( p_oil_vol_fracE, water_vol_fracE, p_pressureE );\n\t\t\t\treal_type rhoL_W\t\t= this->liquid_density( p_oil_vol_fracW, water_vol_fracW, p_pressureW );\n\n                real_type gas_inlet;\n                real_type Qgas = m_gas_flow[ p_node ]->get_current_value();\n                if(m_mass_flux){\n                    gas_inlet = Qgas;\n                }                      \n                else\n                {\n                    gas_inlet = rhoG_P*Qgas;\n                }\n\n\t\t\t\treal_type mod_Vgj_e\t\t= this->mod_v_drift_flux( \n\t\t\t\t\tp_velocityP, 0.5*(p_gas_vol_fracP + p_gas_vol_fracE), 0.5*(p_oil_vol_fracP + p_oil_vol_fracE),\n\t\t\t\t\t0.5*(water_vol_fracP + water_vol_fracE), 0.5*(p_pressureP + p_pressureE)\n\t\t\t\t\t);\n\n\t\t\t\treal_type mod_Vgj_w\t\t= this->mod_v_drift_flux( \n\t\t\t\t\tp_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n\t\t\t\t\t0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n\t\t\t\t\t);\n\n                real_type gas_velocity_w = p_velocityW + 0.5*(rhoL_W + rhoL_P)/(0.5*(rho_W + rho_P))*mod_Vgj_w;\n                real_type gas_velocity_e = p_velocityP + 0.5*(rhoL_P + rhoL_E)/(0.5*(rho_P + rho_E))*mod_Vgj_e;\n\n\t\t\t\treal_type ksi_e = this->ksi( gas_velocity_e );\n\t\t\t\treal_type ksi_w = this->ksi( gas_velocity_w );\n                return (p_gas_vol_fracP*rhoG_P - m_gas_vol_frac_old[ p_node ]*rhoG_P_old)*dV/dt() - gas_inlet\n                    + gas_velocity_e*area()*( (0.5+ksi_e)*rhoG_P*p_gas_vol_fracP + (0.5-ksi_e)*rhoG_E*p_gas_vol_fracE )\n                    - gas_velocity_w*area()*( (0.5+ksi_w)*rhoG_W*p_gas_vol_fracW + (0.5-ksi_w)*rhoG_P*p_gas_vol_fracP );\n                   \n\t\t\t/*return (p_gas_vol_fracP*rhoG_P - m_gas_vol_frac_old[ p_node ]*rhoG_P_old)*dV/dt() - gas_inlet\n\t\t\t\t + p_velocityP*area()*( (0.5+ksi_e)*rhoG_P*p_gas_vol_fracP + (0.5-ksi_e)*rhoG_E*p_gas_vol_fracE )\n\t\t\t\t - p_velocityW*area()*( (0.5+ksi_w)*rhoG_W*p_gas_vol_fracW + (0.5-ksi_w)*rhoG_P*p_gas_vol_fracP )\n\t\t\t\t + mod_Vgj_e*area()*( (0.5+ksi_e)*rhoG_P*rhoL_P/rho_P * p_gas_vol_fracP + (0.5-ksi_e)*rhoG_E*rhoL_E/rho_E * p_gas_vol_fracE )\n\t\t\t\t - mod_Vgj_w*area()*( (0.5+ksi_w)*rhoG_W*rhoL_W/rho_W * p_gas_vol_fracW + (0.5-ksi_w)*rhoG_P*rhoL_P/rho_P * p_gas_vol_fracP );*/\n\t\t\t}\n\n\t\tdefault:\n\t\t\treturn 0.;\n\t\t\t\n\t\t}\n\t}\n\n\treal_type DriftFluxWell::R_o(\n\t\t\t\t\t\t\t\t real_type p_pressureW,\n\t\t\t\t\t\t\t\t real_type p_pressureP,\n\t\t\t\t\t\t\t\t real_type p_pressureE,\n\t\t\t\t\t\t\t\t real_type p_gas_vol_fracW,\n\t\t\t\t\t\t\t\t real_type p_gas_vol_fracP,\n\t\t\t\t\t\t\t\t real_type p_gas_vol_fracE,\n\t\t\t\t\t\t\t\t real_type p_oil_vol_fracW,\n\t\t\t\t\t\t\t\t real_type p_oil_vol_fracP,\n\t\t\t\t\t\t\t\t real_type p_oil_vol_fracE,\n\t\t\t\t\t\t\t\t real_type p_velocityW,\n\t\t\t\t\t\t\t\t real_type p_velocityP,\n\t\t\t\t\t\t\t\t uint_type p_node,\n\t\t\t\t\t\t\t\t string_type\t   position = 'C'\n\t\t\t\t\t\t\t\t )\n\t{\n\t\tswitch( position )\n\t\t{\n\n\t\tcase 'L':\n\t\t\t{\n\t\t\t\treal_type dSw = 0.5*this->segment_length( m_coordinates[ p_node-1 ], m_coordinates[ p_node ] );\n\t\t\t\treal_type dSe = 0.;\n\t\t\t\treal_type dS  = dSw + dSe;\n\t\t\t\treal_type dV = this->Volume( dS );\n\n\t\t\t\treal_type water_vol_fracW\t= 1.0 - (p_gas_vol_fracW + p_oil_vol_fracW);\n\t\t\t\treal_type water_vol_fracP\t= 1.0 - (p_gas_vol_fracP + p_oil_vol_fracP); \n                \n\t\t\t\treal_type rho_P\t\t= this->mean_density(p_oil_vol_fracP, water_vol_fracP, p_gas_vol_fracP, p_pressureP);\t                \n\t\t\t\treal_type rho_W\t\t= this->mean_density(p_oil_vol_fracW, water_vol_fracW, p_gas_vol_fracW, p_pressureW);\n\n\t\t\t\t\t\t\t\t\t\n\t\t\t\treal_type rhoG_P\t\t= this->gas_density( p_pressureP );\t\t\t\n\t\t\t\treal_type rhoG_W\t\t= this->gas_density( p_pressureW );\n\n\t\t\t\treal_type rhoW_P\t\t= this->water_density( p_pressureP );\t\t\t\n\t\t\t\treal_type rhoW_W\t\t= this->water_density( p_pressureW );\n\n\t\t\t\treal_type rhoO_P_old\t= this->oil_density( m_pressure_old[ p_node ] );\t\n\t\t\t\treal_type rhoO_P\t\t= this->oil_density( p_pressureP );\t\t\t\n\t\t\t\treal_type rhoO_W\t\t= this->oil_density( p_pressureW );\n\n\t\t\t\treal_type rhoL_P\t\t= this->liquid_density( p_oil_vol_fracP, water_vol_fracP, p_pressureP );\t\t\t\n\t\t\t\treal_type rhoL_W\t\t= this->liquid_density( p_oil_vol_fracW, water_vol_fracW, p_pressureW );\n                \n                real_type oil_inlet;\n                real_type Qoil = m_oil_flow[ p_node ]->get_current_value();\n                if(m_mass_flux){\n                    oil_inlet = Qoil;\n                }                      \n                else\n                {\n                    oil_inlet = rhoO_P*Qoil;\n                }\n\t\t\t\t\n\n\t\t\t\treal_type mod_Vow_w\t= this->mod_v_drift_flux_ow( \n\t\t\t\t\tp_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n\t\t\t\t\t0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n\t\t\t\t\t);\n               \n\n\t\t\t\treal_type mod_Vgj_w\t= this->mod_v_drift_flux( \n\t\t\t\t\tp_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n\t\t\t\t\t0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n\t\t\t\t\t);\n\n\t\t\t\t//real_type mod_Vgj_e\t= this->mod_v_drift_flux(p_velocityP, p_gas_vol_fracP, p_oil_vol_fracP,\twater_vol_fracP, p_pressureP);\n                real_type gas_vol_frac_w = 0.5*(p_gas_vol_fracP + p_gas_vol_fracW);\n                real_type rho_g_w = 0.5*(rhoG_W + rhoG_P);\n                real_type rho_w_w = 0.5*(rhoW_W + rhoW_P);\n                real_type rho_l_w = 0.5*(rhoL_W + rhoL_P);\n                real_type rho_w = 0.5*(rho_W + rho_P);\n                real_type liquid_velocity_w = p_velocityW - gas_vol_frac_w/(1 - gas_vol_frac_w + 1.0e-20)*rho_g_w/rho_w*mod_Vgj_w;\t \n                \n                real_type oil_velocity_w = liquid_velocity_w + rho_w_w/rho_l_w*mod_Vow_w;               \n\t\t\t\treal_type ksi_w = this->ksi( oil_velocity_w );\n\n                return (p_oil_vol_fracP*rhoO_P - m_oil_vol_frac_old[ p_node ]*rhoO_P_old)*dV/dt() - oil_inlet\t\t\t\t \n                    + p_velocityP*area()*rhoO_P*p_oil_vol_fracP \n                    - oil_velocity_w*area()*( (0.5+ksi_w)*rhoO_W*p_oil_vol_fracW + (0.5-ksi_w)*rhoO_P*p_oil_vol_fracP );\t\t\t\t \n                                \n\t\t\t//return (p_oil_vol_fracP*rhoO_P - m_oil_vol_frac_old[ p_node ]*rhoO_P_old)*dV/dt() - oil_inlet\t\t\t\t \n\t\t\t//\t + p_velocityP*area()*rhoO_P*p_oil_vol_fracP \n   //              - p_velocityW*area()*( (0.5+ksi_w)*rhoO_W*p_oil_vol_fracW + (0.5-ksi_w)*rhoO_P*p_oil_vol_fracP )\t\t\t\t \n\t\t\t//\t - mod_Vow_w*area()*( rhoW_W/rhoL_W*(0.5+ksi_w)*rhoO_W*p_oil_vol_fracW + rhoW_P/rhoL_P*(0.5-ksi_w)*rhoO_P*p_oil_vol_fracP )\t\n\t\t\t//\t //- mod_Vgj_e*area()*( rhoG_P/rho_P*p_gas_vol_fracP/(1.0-p_gas_vol_fracP + 1.0e-20)*rhoO_P*p_oil_vol_fracP )\n\t\t\t//\t + mod_Vgj_w*area()*( rhoG_W/rho_W*p_gas_vol_fracW/(1.0-p_gas_vol_fracW + 1.0e-20)*(0.5+ksi_w)*rhoO_W*p_oil_vol_fracW \n\t\t\t//\t\t\t\t\t\t+ rhoG_P/rho_P*p_gas_vol_fracP/(1.0-p_gas_vol_fracP + 1.0e-20)*(0.5-ksi_w)*rhoO_P*p_oil_vol_fracP );\n\t\t\t\n\t\t\t}\n\t\t\t\n\n\t\tcase 'C':\n\t\t\t{\n\t\t\t\treal_type dSw = 0.5*this->segment_length( m_coordinates[ p_node-1 ], m_coordinates[ p_node ] );\n\t\t\t\treal_type dSe = 0.5*this->segment_length( m_coordinates[ p_node ], m_coordinates[ p_node+1 ] );\n\t\t\t\treal_type dS  = dSw + dSe;\n\t\t\t\treal_type dV  = this->Volume( dS );\t\n\n\t\t\t\treal_type water_vol_fracW\t= 1.0 - (p_gas_vol_fracW + p_oil_vol_fracW);\n\t\t\t\treal_type water_vol_fracP\t= 1.0 - (p_gas_vol_fracP + p_oil_vol_fracP);\n\t\t\t\treal_type water_vol_fracE\t= 1.0 - (p_gas_vol_fracE + p_oil_vol_fracE);\n\n\t\t\t\treal_type rho_P\t\t= this->mean_density(p_oil_vol_fracP, water_vol_fracP, p_gas_vol_fracP, p_pressureP);\t\n\t\t\t\treal_type rho_E\t\t= this->mean_density(p_oil_vol_fracE, water_vol_fracE, p_gas_vol_fracE, p_pressureE);\n\t\t\t\treal_type rho_W\t\t= this->mean_density(p_oil_vol_fracW, water_vol_fracW, p_gas_vol_fracW, p_pressureW);\n\t\t\t\t\t\t\t\t\n\t\t\t\treal_type rhoG_P\t\t= this->gas_density( p_pressureP );\n\t\t\t\treal_type rhoG_E\t\t= this->gas_density( p_pressureE );\n\t\t\t\treal_type rhoG_W\t\t= this->gas_density( p_pressureW );\n\n\t\t\t\treal_type rhoW_P\t\t= this->water_density( p_pressureP );\n\t\t\t\treal_type rhoW_E\t\t= this->water_density( p_pressureE );\n\t\t\t\treal_type rhoW_W\t\t= this->water_density( p_pressureW );\n\n\t\t\t\treal_type rhoO_P_old\t= this->oil_density( m_pressure_old[ p_node ] );\t\n\t\t\t\treal_type rhoO_P\t\t= this->oil_density( p_pressureP );\n\t\t\t\treal_type rhoO_E\t\t= this->oil_density( p_pressureE );\n\t\t\t\treal_type rhoO_W\t\t= this->oil_density( p_pressureW );\n\n\t\t\t\treal_type rhoL_P\t\t= this->liquid_density( p_oil_vol_fracP, water_vol_fracP, p_pressureP );\n\t\t\t\treal_type rhoL_E\t\t= this->liquid_density( p_oil_vol_fracE, water_vol_fracE, p_pressureE );\n\t\t\t\treal_type rhoL_W\t\t= this->liquid_density( p_oil_vol_fracW, water_vol_fracW, p_pressureW );\n\n                real_type oil_inlet;\n                real_type Qoil = m_oil_flow[ p_node ]->get_current_value();\n                if(m_mass_flux){\n                    oil_inlet = Qoil;\n                }                      \n                else\n                {\n                    oil_inlet = rhoO_P*Qoil;\n                }\n\n\t\t\t\treal_type mod_Vow_e\t= this->mod_v_drift_flux_ow( \n\t\t\t\t\tp_velocityP, 0.5*(p_gas_vol_fracP + p_gas_vol_fracE), 0.5*(p_oil_vol_fracP + p_oil_vol_fracE),\n\t\t\t\t\t0.5*(water_vol_fracP + water_vol_fracE), 0.5*(p_pressureP + p_pressureE)\n\t\t\t\t\t);\n\n\t\t\t\treal_type mod_Vow_w\t= this->mod_v_drift_flux_ow( \n\t\t\t\t\tp_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n\t\t\t\t\t0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n\t\t\t\t\t);\n\n\t\t\t\treal_type mod_Vgj_e\t\t= this->mod_v_drift_flux( \n\t\t\t\t\tp_velocityP, 0.5*(p_gas_vol_fracP + p_gas_vol_fracE), 0.5*(p_oil_vol_fracP + p_oil_vol_fracE),\n\t\t\t\t\t0.5*(water_vol_fracP + water_vol_fracE), 0.5*(p_pressureP + p_pressureE)\n\t\t\t\t\t);\n\n\t\t\t\treal_type mod_Vgj_w\t\t= this->mod_v_drift_flux( \n\t\t\t\t\tp_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n\t\t\t\t\t0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n\t\t\t\t\t);\n\n                real_type gas_vol_frac_w = 0.5*(p_gas_vol_fracP + p_gas_vol_fracW);\n                real_type rho_g_w = 0.5*(rhoG_W + rhoG_P);\n                real_type rho_w_w = 0.5*(rhoW_W + rhoW_P);\n                real_type rho_l_w = 0.5*(rhoL_W + rhoL_P);\n                real_type rho_w = 0.5*(rho_W + rho_P);\n                real_type liquid_velocity_w = p_velocityW - gas_vol_frac_w/(1 - gas_vol_frac_w + 1.0e-20)*rho_g_w/rho_w*mod_Vgj_w;\t \n\n                real_type oil_velocity_w = liquid_velocity_w + rho_w_w/rho_l_w*mod_Vow_w;  \n\n                real_type gas_vol_frac_e = 0.5*(p_gas_vol_fracP + p_gas_vol_fracE);\n                real_type rho_g_e = 0.5*(rhoG_E + rhoG_P);\n                real_type rho_w_e = 0.5*(rhoW_E + rhoW_P);\n                real_type rho_l_e = 0.5*(rhoL_E + rhoL_P);\n                real_type rho_e = 0.5*(rho_E + rho_P);\n                real_type liquid_velocity_e = p_velocityP - gas_vol_frac_e/(1 - gas_vol_frac_e + 1.0e-20)*rho_g_e/rho_e*mod_Vgj_e;\t \n\n                real_type oil_velocity_e = liquid_velocity_e + rho_w_e/rho_l_e*mod_Vow_e;  \n                \n\t\t\t\treal_type ksi_e = this->ksi( oil_velocity_e );\n\t\t\t\treal_type ksi_w = this->ksi( oil_velocity_w );\n\n                return (p_oil_vol_fracP*rhoO_P - m_oil_vol_frac_old[ p_node ]*rhoO_P_old)*dV/dt() - oil_inlet\n                    + oil_velocity_e*area()*( (0.5+ksi_e)*rhoO_P*p_oil_vol_fracP + (0.5-ksi_e)*rhoO_E*p_oil_vol_fracE )\n                    - oil_velocity_w*area()*( (0.5+ksi_w)*rhoO_W*p_oil_vol_fracW + (0.5-ksi_w)*rhoO_P*p_oil_vol_fracP );\n                    \n               \n\t\t\t/*return (p_oil_vol_fracP*rhoO_P - m_oil_vol_frac_old[ p_node ]*rhoO_P_old)*dV/dt() - oil_inlet\n\t\t\t\t + p_velocityP*area()*( (0.5+ksi_e)*rhoO_P*p_oil_vol_fracP + (0.5-ksi_e)*rhoO_E*p_oil_vol_fracE )\n\t\t\t\t - p_velocityW*area()*( (0.5+ksi_w)*rhoO_W*p_oil_vol_fracW + (0.5-ksi_w)*rhoO_P*p_oil_vol_fracP )\n\t\t\t\t + mod_Vow_e*area()*( rhoW_P/rhoL_P*(0.5+ksi_e)*rhoO_P*p_oil_vol_fracP + rhoW_E/rhoL_E*(0.5-ksi_e)*rhoO_E*p_oil_vol_fracE )\n\t\t\t\t - mod_Vow_w*area()*( rhoW_W/rhoL_W*(0.5+ksi_w)*rhoO_W*p_oil_vol_fracW + rhoW_P/rhoL_P*(0.5-ksi_w)*rhoO_P*p_oil_vol_fracP )\n\t\t\t\t - mod_Vgj_e*area()*( rhoG_P/rho_P*p_gas_vol_fracP/(1.0-p_gas_vol_fracP + 1.0e-20)*(0.5+ksi_e)*rhoO_P*p_oil_vol_fracP \n\t\t\t\t\t\t\t\t\t+ rhoG_E/rho_E*p_gas_vol_fracE/(1.0-p_gas_vol_fracE + 1.0e-20)*(0.5-ksi_e)*rhoO_E*p_oil_vol_fracE )\n\t\t\t\t + mod_Vgj_w*area()*( rhoG_W/rho_W*p_gas_vol_fracW/(1.0-p_gas_vol_fracW + 1.0e-20)*(0.5+ksi_w)*rhoO_W*p_oil_vol_fracW \n\t\t\t\t\t\t\t\t\t+ rhoG_P/rho_P*p_gas_vol_fracP/(1.0-p_gas_vol_fracP + 1.0e-20)*(0.5-ksi_w)*rhoO_P*p_oil_vol_fracP );*/\n\t\t\t}\n\n\t\tdefault:\n\t\t\treturn 0.;\n\t\t\t\n\t\t}\n\t}\n\n\t\n\n\n\n\treal_type DriftFluxWell::R_v(\n                                 real_type p_pressureW,\n\t\t\t\t\t\t\t\t real_type p_pressureP,\n\t\t\t\t\t\t\t\t real_type p_pressureE,\n                                 real_type p_pressureEE,\n                                 real_type p_gas_vol_fracW,\n\t\t\t\t\t\t\t\t real_type p_gas_vol_fracP,\n\t\t\t\t\t\t\t\t real_type p_gas_vol_fracE,\n                                 real_type p_gas_vol_fracEE,\n                                 real_type p_oil_vol_fracW,\n\t\t\t\t\t\t\t\t real_type p_oil_vol_fracP,\n\t\t\t\t\t\t\t\t real_type p_oil_vol_fracE,\n                                 real_type p_oil_vol_fracEE,\n\t\t\t\t\t\t\t\t real_type p_velocityW,\n\t\t\t\t\t\t\t\t real_type p_velocityP,\n\t\t\t\t\t\t\t\t real_type p_velocityE,\n\t\t\t\t\t\t\t\t uint_type p_node,\n\t\t\t\t\t\t\t\t string_type\t   position = 'C'\n\t\t\t\t\t\t\t\t )\n\t{\t\t\n\t\tswitch( position )\n\t\t{\n\t\tcase 'F':\n\t\t\t{\n\t\t\treal_type dS  = this->segment_length( m_coordinates[ p_node ], m_coordinates[ p_node+1 ] );\n\t\t\treal_type dSe = this->segment_length( m_coordinates[ p_node+1 ], m_coordinates[ p_node+2 ] );\n\t\t\treal_type dSw = 0.;\n\t\t\treal_type dV = this->Volume( dS );\n\n\t\t\t\n\t\t\treal_type water_vol_fracP_old\t= 1.0 - (m_oil_vol_frac_old[ p_node ]   + m_gas_vol_frac_old[ p_node ]\t);\n\t\t\treal_type water_vol_fracE_old\t= 1.0 - (m_oil_vol_frac_old[ p_node+1 ] + m_gas_vol_frac_old[ p_node+1 ]);\n            real_type water_vol_fracW\t\t= 1.0 - (p_gas_vol_fracW + p_oil_vol_fracW);\n            real_type water_vol_fracP\t\t= 1.0 - (p_gas_vol_fracP + p_oil_vol_fracP);\n            real_type water_vol_fracE\t\t= 1.0 - (p_gas_vol_fracE + p_oil_vol_fracE);\t\n            real_type water_vol_fracEE\t\t= 1.0 - (p_gas_vol_fracEE + p_oil_vol_fracEE);\n\n\t\t\treal_type rho_P_old = this->mean_density(m_oil_vol_frac_old[ p_node ], water_vol_fracP_old, m_gas_vol_frac_old[ p_node ], m_pressure_old[ p_node ]);\n\t\t\treal_type rho_E_old = this->mean_density(m_oil_vol_frac_old[ p_node+1 ], water_vol_fracE_old, m_gas_vol_frac_old[ p_node+1 ], m_pressure_old[ p_node+1 ]);\n\n\t\t\tvector_type S( 3 );\n\t\t\tS[ 0 ] = m_coordinates[ p_node ].getX() - m_coordinates[ p_node+1 ].getX();\n\t\t\tS[ 1 ] = m_coordinates[ p_node ].getY() - m_coordinates[ p_node+1 ].getY();\n\t\t\tS[ 2 ] = m_coordinates[ p_node ].getZ() - m_coordinates[ p_node+1 ].getZ();\n\n\t\t\treal_type d_e = dS/(dS+dSe);\n\t\t\treal_type d_w = dS/(dS+dSw);\n\t\t\t\t\t\t\n\t\t\treal_type angle = get_inclination() - PI/2;//PI/2 - 0*acos( dot( m_gravity, S )/(norm(m_gravity)*norm(S)) );\n\t\t\t\n            real_type rho_W   = this->mean_density(p_oil_vol_fracW, water_vol_fracW, p_gas_vol_fracW , p_pressureW );\n            real_type rho_P   = this->mean_density(p_oil_vol_fracP, water_vol_fracP, p_gas_vol_fracP, p_pressureP);\n            real_type rho_E   = this->mean_density(p_oil_vol_fracE, water_vol_fracE, p_gas_vol_fracE, p_pressureE);\n            real_type rho_EE  = this->mean_density(p_oil_vol_fracEE, water_vol_fracEE, p_gas_vol_fracEE , p_pressureEE);\n\n            real_type rhoG_W\t\t= this->gas_density( p_pressureW );\n            real_type rhoG_P\t\t= this->gas_density( p_pressureP );\n            real_type rhoG_E\t\t= this->gas_density( p_pressureE );\n            real_type rhoG_EE\t\t= this->gas_density( p_pressureEE );\n\n            real_type rhoL_W\t\t= this->liquid_density( p_oil_vol_fracW, water_vol_fracW, p_pressureW );\n            real_type rhoL_P\t\t= this->liquid_density( p_oil_vol_fracP, water_vol_fracP, p_pressureP );\n            real_type rhoL_E\t\t= this->liquid_density( p_oil_vol_fracE, water_vol_fracE, p_pressureE );\n            real_type rhoL_EE\t\t= this->liquid_density( p_oil_vol_fracEE, water_vol_fracEE, p_pressureEE );\n\n            real_type rhoW_W\t\t= this->water_density( p_pressureW );\n            real_type rhoW_P\t\t= this->water_density( p_pressureP );\n            real_type rhoW_E\t\t= this->water_density( p_pressureE );\n            real_type rhoW_EE\t\t= this->water_density( p_pressureEE );\n\n            real_type rhoO_W\t\t= this->oil_density( p_pressureW );\n            real_type rhoO_P\t\t= this->oil_density( p_pressureP );\n            real_type rhoO_E\t\t= this->oil_density( p_pressureE );\n            real_type rhoO_EE\t\t= this->oil_density( p_pressureEE ); \n\t\t\t\n\t\t\treal_type mean_pressure = 0.5*(p_pressureP + p_pressureE);\n\t\t\treal_type viscosity = 0.5*(p_gas_vol_fracP + p_gas_vol_fracE)*gas_viscosity\t ( mean_pressure ) \n\t\t\t\t\t\t\t\t+ 0.5*(p_oil_vol_fracP + p_oil_vol_fracE)*oil_viscosity\t ( mean_pressure ) \n\t\t\t\t\t\t\t\t+ 0.5*(water_vol_fracP + water_vol_fracE)*water_viscosity( mean_pressure );\n\n\n            real_type mod_Vow_W\t= this->mod_v_drift_flux_ow( \n                p_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n                0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n                );\n            real_type mod_Vow_P\t= this->mod_v_drift_flux_ow( \n                p_velocityP, 0.5*(p_gas_vol_fracP + p_gas_vol_fracE), 0.5*(p_oil_vol_fracP + p_oil_vol_fracE),\n                0.5*(water_vol_fracP + water_vol_fracE), 0.5*(p_pressureP + p_pressureE)\n                );\n            real_type mod_Vow_E\t= this->mod_v_drift_flux_ow( \n                p_velocityE, 0.5*(p_gas_vol_fracE + p_gas_vol_fracEE), 0.5*(p_oil_vol_fracE + p_oil_vol_fracEE),\n                0.5*(water_vol_fracE + water_vol_fracEE), 0.5*(p_pressureE + p_pressureEE)\n                );\n\n            real_type mod_Vgj_W\t= this->mod_v_drift_flux( \n                p_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n                0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n                );\n            real_type mod_Vgj_P\t= this->mod_v_drift_flux( \n                p_velocityP, 0.5*(p_gas_vol_fracP + p_gas_vol_fracE), 0.5*(p_oil_vol_fracP + p_oil_vol_fracE),\n                0.5*(water_vol_fracP + water_vol_fracE), 0.5*(p_pressureP + p_pressureE)\n                );\n            real_type mod_Vgj_E\t= this->mod_v_drift_flux( \n                p_velocityE, 0.5*(p_gas_vol_fracE + p_gas_vol_fracEE), 0.5*(p_oil_vol_fracE + p_oil_vol_fracEE),\n                0.5*(water_vol_fracE + water_vol_fracEE), 0.5*(p_pressureE + p_pressureEE)\n                );\n\n\n            //real_type Vc  = p_velocityP;\t\t\t\n            //real_type Re  = abs(0.5*(rho_P + rho_E)*Vc*2*m_radius/viscosity);\n            //real_type f_P = this->friction_factor( Re );\n\n            // OTHER Vc = j\n            real_type Vc = p_velocityP + 0.5*(p_gas_vol_fracP*(rhoL_P - rhoG_P)/rho_P*mod_Vgj_P + p_gas_vol_fracE*(rhoL_E - rhoG_E)/rho_E*mod_Vgj_E);\n            real_type Re  = abs(0.5*(rho_P + rho_E)*Vc*2.0*m_radius/viscosity);\n            real_type f_P = this->friction_factor( Re );\n\n\n            real_type gas_vol_frac_W   = 0.5*(p_gas_vol_fracP + p_gas_vol_fracW);\n            real_type oil_vol_frac_W   = 0.5*(p_oil_vol_fracP + p_oil_vol_fracW);\n            real_type water_vol_frac_W = 0.5*(water_vol_fracP + water_vol_fracW);\n            real_type rho_g_W = 0.5*(rhoG_W + rhoG_P);\n            real_type rho_o_W = 0.5*(rhoO_W + rhoO_P);\n            real_type rho_w_W = 0.5*(rhoW_W + rhoW_P);\n            real_type rho_l_W = 0.5*(rhoL_W + rhoL_P);\n            real_type rho_m_W = 0.5*(rho_W + rho_P);\n\n            real_type gas_velocity_W    = p_velocityW + rho_l_W/rho_g_W*mod_Vgj_W;\n            real_type liquid_velocity_W = p_velocityW - gas_vol_frac_W/(1 - gas_vol_frac_W + 1.0e-20)*rho_g_W/rho_m_W*mod_Vgj_W;\t \n            real_type water_velocity_W  = liquid_velocity_W - (oil_vol_frac_W/(water_vol_frac_W + 1.0e-20))*(rho_o_W/rho_l_W)*mod_Vow_W;               \n            real_type oil_velocity_W    = liquid_velocity_W + rho_w_W/rho_l_W*mod_Vow_W;  \n\n\n\n            real_type gas_vol_frac_P   = 0.5*(p_gas_vol_fracP + p_gas_vol_fracE);\n            real_type oil_vol_frac_P   = 0.5*(p_oil_vol_fracP + p_oil_vol_fracE);\n            real_type water_vol_frac_P = 0.5*(water_vol_fracP + water_vol_fracE);\n            real_type rho_g_P = 0.5*(rhoG_E + rhoG_P);\n            real_type rho_o_P = 0.5*(rhoO_E + rhoO_P);\n            real_type rho_w_P = 0.5*(rhoW_E + rhoW_P);\n            real_type rho_l_P = 0.5*(rhoL_E + rhoL_P);\n            real_type rho_m_P = 0.5*(rho_E + rho_P);\n\n            real_type gas_velocity_P    = p_velocityP + rho_l_P/rho_g_P*mod_Vgj_P;\n            real_type liquid_velocity_P = p_velocityP - gas_vol_frac_P/(1 - gas_vol_frac_P + 1.0e-20)*rho_g_P/rho_m_P*mod_Vgj_P;\t \n            real_type water_velocity_P  = liquid_velocity_P - (oil_vol_frac_P/(water_vol_frac_P + 1.0e-20))*(rho_o_P/rho_l_P)*mod_Vow_P;               \n            real_type oil_velocity_P    = liquid_velocity_P + rho_w_P/rho_l_P*mod_Vow_P;\n\n            real_type gas_vol_frac_E   = 0.5*(p_gas_vol_fracE + p_gas_vol_fracEE);\n            real_type oil_vol_frac_E   = 0.5*(p_oil_vol_fracE + p_oil_vol_fracEE);\n            real_type water_vol_frac_E = 0.5*(water_vol_fracE + water_vol_fracEE);\n            real_type rho_g_E = 0.5*(rhoG_E + rhoG_EE);\n            real_type rho_o_E = 0.5*(rhoO_E + rhoO_EE);\n            real_type rho_w_E = 0.5*(rhoW_E + rhoW_EE);\n            real_type rho_l_E = 0.5*(rhoL_E + rhoL_EE);\n            real_type rho_m_E = 0.5*(rho_E + rho_EE);\n\n            real_type gas_velocity_E    = p_velocityE + rho_l_E/rho_g_E*mod_Vgj_E;\n            real_type liquid_velocity_E = p_velocityE - gas_vol_frac_E/(1 - gas_vol_frac_E + 1.0e-20)*rho_g_E/rho_m_E*mod_Vgj_E;\t \n            real_type water_velocity_E  = liquid_velocity_E - (oil_vol_frac_E/(water_vol_frac_E + 1.0e-20))*(rho_o_E/rho_l_E)*mod_Vow_E;               \n            real_type oil_velocity_E    = liquid_velocity_E + rho_w_E/rho_l_E*mod_Vow_E;\n\n\n\n            real_type ksi_W_oil     = this->ksi( oil_velocity_W   );\n            real_type ksi_W_gas     = this->ksi( gas_velocity_W   );\n            real_type ksi_W_water   = this->ksi( water_velocity_W );\n\n            real_type ksi_P_oil     = this->ksi( oil_velocity_P   );\n            real_type ksi_P_gas     = this->ksi( gas_velocity_P   );\n            real_type ksi_P_water   = this->ksi( water_velocity_P );\n\n            real_type ksi_E_oil     = this->ksi( oil_velocity_E   );\n            real_type ksi_E_gas     = this->ksi( gas_velocity_E   );\n            real_type ksi_E_water   = this->ksi( water_velocity_E );\n\n            real_type m_W_oil   = oil_velocity_W  *( (0.5+ksi_W_oil  )*rhoO_W*p_oil_vol_fracW + (0.5-ksi_W_oil  )*rhoO_P*p_oil_vol_fracP );\n            real_type m_W_water = water_velocity_W*( (0.5+ksi_W_water)*rhoW_W*water_vol_fracW + (0.5-ksi_W_water)*rhoW_P*water_vol_fracP );\n            real_type m_W_gas   = gas_velocity_W  *( (0.5+ksi_W_gas  )*rhoG_W*p_gas_vol_fracW + (0.5-ksi_W_gas  )*rhoG_P*p_gas_vol_fracP );\n\n            real_type m_P_oil   = oil_velocity_P  *( (0.5+ksi_P_oil  )*rhoO_P*p_oil_vol_fracP + (0.5-ksi_P_oil  )*rhoO_E*p_oil_vol_fracE );\n            real_type m_P_water = water_velocity_P*( (0.5+ksi_P_water)*rhoW_P*water_vol_fracP + (0.5-ksi_P_water)*rhoW_E*water_vol_fracE );\n            real_type m_P_gas   = gas_velocity_P  *( (0.5+ksi_P_gas  )*rhoG_P*p_gas_vol_fracP + (0.5-ksi_P_gas  )*rhoG_E*p_gas_vol_fracE );\n\n            real_type m_E_oil   = oil_velocity_E  *( (0.5+ksi_E_oil  )*rhoO_P*p_oil_vol_fracE + (0.5-ksi_E_oil  )*rhoO_E*p_oil_vol_fracEE );\n            real_type m_E_water = water_velocity_E*( (0.5+ksi_E_water)*rhoW_P*water_vol_fracE + (0.5-ksi_E_water)*rhoW_E*water_vol_fracEE );\n            real_type m_E_gas   = gas_velocity_E  *( (0.5+ksi_E_gas  )*rhoG_P*p_gas_vol_fracE + (0.5-ksi_E_gas  )*rhoG_E*p_gas_vol_fracEE );\n\n            real_type ksi_e_oil = this->ksi( (1-d_e)*oil_velocity_P + d_e*oil_velocity_E );\n            real_type ksi_w_oil = this->ksi( (1-d_w)*oil_velocity_P + d_w*oil_velocity_W );\n            real_type ksi_e_water = this->ksi( (1-d_e)*water_velocity_P + d_e*water_velocity_E );\n            real_type ksi_w_water = this->ksi( (1-d_w)*water_velocity_P + d_w*water_velocity_W );\n            real_type ksi_e_gas = this->ksi( (1-d_e)*gas_velocity_P + d_e*gas_velocity_E );\n            real_type ksi_w_gas = this->ksi( (1-d_w)*gas_velocity_P + d_w*gas_velocity_W );\n\n            real_type m_e = 0.5*(m_E_oil  +m_P_oil)  *( (0.5+ksi_e_oil  )*oil_velocity_P   + (0.5-ksi_e_oil  )*oil_velocity_E )\n                          + 0.5*(m_E_water+m_P_water)*( (0.5+ksi_e_water)*water_velocity_P + (0.5-ksi_e_water)*water_velocity_E )\n                          + 0.5*(m_E_gas  +m_P_gas)  *( (0.5+ksi_e_gas  )*gas_velocity_P   + (0.5-ksi_e_gas  )*gas_velocity_E );\n\n            /*real_type m_w = 0.5*(m_W_oil  +m_P_oil)  *( (0.5+ksi_w_oil  )*oil_velocity_W   + (0.5-ksi_w_oil  )*oil_velocity_P )\n                          + 0.5*(m_W_water+m_P_water)*( (0.5+ksi_w_water)*water_velocity_W + (0.5-ksi_w_water)*water_velocity_P )\n                          + 0.5*(m_W_gas  +m_P_gas)  *( (0.5+ksi_w_gas  )*gas_velocity_W   + (0.5-ksi_w_gas  )*gas_velocity_P ); */ \n            real_type m_w = m_P_oil*oil_velocity_P +m_P_water*water_velocity_P + m_P_gas*gas_velocity_P ; \n\n            real_type m_t =  oil_velocity_P  *(rhoO_P*p_oil_vol_fracP + rhoO_E*p_oil_vol_fracE)\n                          +  water_velocity_P*(rhoW_P*water_vol_fracP + rhoW_E*water_vol_fracE)\n                          +  gas_velocity_P  *(rhoG_P*p_gas_vol_fracP + rhoG_E*p_gas_vol_fracE);\n\n\n            return ( m_t - (rho_P_old+rho_E_old)*m_mean_velocity_old[ p_node ] )*0.5*dV/dt()\n                + (m_e - m_w)*area()                \n                + (p_pressureE-p_pressureP)*area() + 0.5*(rho_P+rho_E)*gravity()*sin( angle )*dV + 0.125/m_radius*f_P*(rho_P + rho_E)*dV*Vc*abs(Vc);\n\n\n\n            // New friction factor wells\n            //OUYANG\n            //real_type q_w = ((*m_oil_flow)[ p_node ] + (*m_gas_flow)[ p_node ] + (*m_water_flow)[ p_node ])/dS;\n            //real_type v_eq = q_w/(PI*2*m_radius);\n            //real_type Re_w = abs(0.5*(rho_P + rho_E)*v_eq*2*m_radius/viscosity);\n\t\t\t//real_type f_P = this->friction_factor( Re )*(1+0.04304*pow(Re_w,0.6142));\n            // ASHEIM\n            //real_type q_m = p_velocityP*area();\n            //real_type q_i = ((*m_oil_flow)[ p_node ] + (*m_gas_flow)[ p_node ] + (*m_water_flow)[ p_node ]);\n            //real_type f_complet = q_m == 0? 0.0 : 4*2*m_radius*q_i/dS/q_m + 2*m_radius*q_i/dS/q_m*q_i/dS/q_m;\n            //real_type f_P = this->friction_factor( Re ) + f_complet;\n            \n\n\t\t\t//real_type mod_Vgj_P\t\t= this->mod_v_drift_flux( \n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t (1-d_w)*p_velocityP + d_w*p_velocityW, p_gas_vol_fracP, p_oil_vol_fracP,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t water_vol_fracP, p_pressureP\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t );\n\t\t\t//real_type mod_Vgj_E\t\t= this->mod_v_drift_flux( \n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t (1-d_e)*p_velocityP + d_e*p_velocityE, p_gas_vol_fracE, p_oil_vol_fracE,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t water_vol_fracE, p_pressureE\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t );\n\n\t\t\t//// OTHER Vc = j\n\t\t\t////real_type Vc = p_velocityP + 0.5*(p_gas_vol_fracP*(rhoL_P - rhoG_P)/rho_P*mod_Vgj_P + p_gas_vol_fracE*(rhoL_E - rhoG_E)/rho_E*mod_Vgj_E);\n\t\t\t////real_type Re  = abs(0.5*(rho_P + rho_E)*Vc*2*m_radius/viscosity);\n\t\t\t////real_type f_P = this->friction_factor( Re );\n\n\t\t\t//real_type ksi_e = this->ksi( (1-d_e)*p_velocityP + d_e*p_velocityE );\n\t\t\t//real_type ksi_w = this->ksi( (1-d_w)*p_velocityP + d_w*p_velocityW );\n\t\t\t//\n\t\t\t//\n\t\t\t////*return ( (rho_P+rho_E)*p_velocityP - (rho_P_old+rho_E_old)*m_mean_velocity_old[ p_node ] )*0.5*dV/dt()\n\t\t\t//\t + rho_E*area()*( (1-d_e)*p_velocityP + d_e*p_velocityE )*( (0.5+ksi_e)*p_velocityP + (0.5-ksi_e)*p_velocityE )\n\t\t\t//\t - rho_P*area()*( (1-d_w)*p_velocityP + d_w*p_velocityW )*( (0.5+ksi_w)*p_velocityW + (0.5-ksi_w)*p_velocityP )\n\t\t\t//\t + (p_pressureE-p_pressureP)*area() + 0.5*(rho_P+rho_E)*gravity()*sin( angle )*dV + 0.125/m_radius*f_P*(rho_P + rho_E)*dV*p_velocityP*abs(p_velocityP)\n\t\t\t//\t + rhoG_E*rhoL_E/rho_E*area()*mod_Vgj_E*mod_Vgj_E*p_gas_vol_fracE/(1-p_gas_vol_fracE)\n\t\t\t//\t - rhoG_P*rhoL_P/rho_P*area()*mod_Vgj_P*mod_Vgj_P*p_gas_vol_fracP/(1-p_gas_vol_fracP);*/\n\t\t\t//\n\t\t\t//real_type ksi_E = this->ksi( p_velocityE );\n\t\t\t//real_type ksi_P = this->ksi( p_velocityP );\t\t\t\n\n\t\t\t//real_type m_E\t= ((0.5+ksi_E)*rho_E + (0.5-ksi_E)*rho_EE )*p_velocityE*area();\n\t\t\t//real_type m_P\t= ((0.5+ksi_P)*rho_P + (0.5-ksi_P)*rho_E  )*p_velocityP*area();\n\t\t\t//real_type m_W\t= rho_P*p_velocityP*area();\n\n\t\t\t//return ( (rho_P+rho_E)*p_velocityP - (rho_P_old+rho_E_old)*m_mean_velocity_old[ p_node ] )*0.5*dV/dt()\n\t\t\t//\t + 0.5*(m_E+m_P)*( (0.5+ksi_e)*p_velocityP + (0.5-ksi_e)*p_velocityE )\n\t\t\t//\t - m_W*( (0.5+ksi_w)*p_velocityW + (0.5-ksi_w)*p_velocityP )\n\t\t\t//\t + (p_pressureE-p_pressureP)*area() + 0.5*(rho_P+rho_E)*gravity()*sin( angle )*dV + 0.125/m_radius*f_P*(rho_P + rho_E)*dV*Vc*abs(Vc)\n\t\t\t//     + rhoG_E*rhoL_E/rho_E*area()*mod_Vgj_E*mod_Vgj_E*p_gas_vol_fracE/(1-p_gas_vol_fracE + 1.0e-20)\n\t\t\t//\t - rhoG_P*rhoL_P/rho_P*area()*mod_Vgj_P*mod_Vgj_P*p_gas_vol_fracP/(1-p_gas_vol_fracP + 1.0e-20);\n\n\n\t\t\n\t\t\t\n\t\t\t/*return ( (rho_P+rho_E)*p_velocityP - (rho_P_old+rho_E_old)*m_mean_velocity_old[ p_node ] )*0.5*dV/dt()\n\t\t\t\t + rho_E*area()*( (1-d_e)*p_velocityP + d_e*p_velocityE )*( (0.5+ksi_e)*p_velocityP + (0.5-ksi_e)*p_velocityE )\n\t\t\t\t - rho_P*area()*( (1-d_w)*p_velocityP + d_w*p_velocityW )*( (0.5+ksi_w)*p_velocityW + (0.5-ksi_w)*p_velocityP )\n\t\t\t\t + (p_pressureE-p_pressureP)*area() + 0.5*(rho_P+rho_E)*gravity()*sin( angle )*dV + 0.125/m_radius*f_P*(rho_P + rho_E)*dV*m_j[ p_node ]*abs(m_j[ p_node ]);\n\t\t\t\t*/\n\t\t\t\t \n\t\t\t\t // + rhoG_E*rhoL_E/rho_E*area()*mod_Vgj_E*mod_Vgj_E*p_gas_vol_fracE/(1-p_gas_vol_fracE)\n\t\t\t\t// - rhoG_P*rhoL_P/rho_P*area()*mod_Vgj_P*mod_Vgj_P*p_gas_vol_fracP/(1-p_gas_vol_fracP);\n\t\t\t\n\t\t\t}\n\t\t\t\n\n\n\t\tcase 'L':\n\t\t\t{\n\t\t\treal_type dS  = this->segment_length( m_coordinates[ p_node ], m_coordinates[ p_node+1 ] );\n\t\t\treal_type dSe = 0.;\n\t\t\treal_type dSw = this->segment_length( m_coordinates[ p_node ], m_coordinates[ p_node-1 ] );\n\t\t\treal_type dV = this->Volume( dS );\n\n\t\t\treal_type water_vol_fracP_old\t= 1.0 - (m_oil_vol_frac_old[ p_node ]   + m_gas_vol_frac_old[ p_node ]\t);\n\t\t\treal_type water_vol_fracE_old\t= 1.0 - (m_oil_vol_frac_old[ p_node+1 ] + m_gas_vol_frac_old[ p_node+1 ]);\n            real_type water_vol_fracW\t\t= 1.0 - (p_gas_vol_fracW + p_oil_vol_fracW);\n            real_type water_vol_fracP\t\t= 1.0 - (p_gas_vol_fracP + p_oil_vol_fracP);\n            real_type water_vol_fracE\t\t= 1.0 - (p_gas_vol_fracE + p_oil_vol_fracE);\t\n            real_type water_vol_fracEE\t\t= 1.0 - (p_gas_vol_fracEE + p_oil_vol_fracEE);\t\t\n\n\t\t\treal_type rho_P_old = this->mean_density(m_oil_vol_frac_old[ p_node ], water_vol_fracP_old, m_gas_vol_frac_old[ p_node ], m_pressure_old[ p_node ]);\n\t\t\treal_type rho_E_old = this->mean_density(m_oil_vol_frac_old[ p_node+1 ], water_vol_fracE_old, m_gas_vol_frac_old[ p_node+1 ], m_pressure_old[ p_node+1 ]);\n\n\t\t\tvector_type S( 3 );\n\t\t\tS[ 0 ] = m_coordinates[ p_node ].getX() - m_coordinates[ p_node+1 ].getX();\n\t\t\tS[ 1 ] = m_coordinates[ p_node ].getY() - m_coordinates[ p_node+1 ].getY();\n\t\t\tS[ 2 ] = m_coordinates[ p_node ].getZ() - m_coordinates[ p_node+1 ].getZ();\n\n\t\t\treal_type d_e = dS/(dS+dSe);\n\t\t\treal_type d_w = dS/(dS+dSw);\n\n\t\t\treal_type angle = get_inclination() - PI/2; //- 0*acos( dot( m_gravity, S )/(norm(m_gravity)*norm(S)) );\t\t\t\t\t\t\n\t\t\t\n            real_type rho_W   = this->mean_density(p_oil_vol_fracW, water_vol_fracW, p_gas_vol_fracW , p_pressureW );\n            real_type rho_P   = this->mean_density(p_oil_vol_fracP, water_vol_fracP, p_gas_vol_fracP, p_pressureP);\n            real_type rho_E   = this->mean_density(p_oil_vol_fracE, water_vol_fracE, p_gas_vol_fracE, p_pressureE);\n            real_type rho_EE  = this->mean_density(p_oil_vol_fracEE, water_vol_fracEE, p_gas_vol_fracEE , p_pressureEE);\n\n            real_type rhoG_W\t\t= this->gas_density( p_pressureW );\n            real_type rhoG_P\t\t= this->gas_density( p_pressureP );\n            real_type rhoG_E\t\t= this->gas_density( p_pressureE );\n            real_type rhoG_EE\t\t= this->gas_density( p_pressureEE );\n\n            real_type rhoL_W\t\t= this->liquid_density( p_oil_vol_fracW, water_vol_fracW, p_pressureW );\n            real_type rhoL_P\t\t= this->liquid_density( p_oil_vol_fracP, water_vol_fracP, p_pressureP );\n            real_type rhoL_E\t\t= this->liquid_density( p_oil_vol_fracE, water_vol_fracE, p_pressureE );\n            real_type rhoL_EE\t\t= this->liquid_density( p_oil_vol_fracEE, water_vol_fracEE, p_pressureEE );\n\n            real_type rhoW_W\t\t= this->water_density( p_pressureW );\n            real_type rhoW_P\t\t= this->water_density( p_pressureP );\n            real_type rhoW_E\t\t= this->water_density( p_pressureE );\n            real_type rhoW_EE\t\t= this->water_density( p_pressureEE );\n\n            real_type rhoO_W\t\t= this->oil_density( p_pressureW );\n            real_type rhoO_P\t\t= this->oil_density( p_pressureP );\n            real_type rhoO_E\t\t= this->oil_density( p_pressureE );\n            real_type rhoO_EE\t\t= this->oil_density( p_pressureEE ); \n\t\t\t\n\t\t\treal_type mean_pressure = 0.5*(p_pressureP + p_pressureE);\n\t\t\treal_type viscosity = 0.5*(p_gas_vol_fracP + p_gas_vol_fracE)*gas_viscosity\t ( mean_pressure ) \n\t\t\t\t\t\t\t\t+ 0.5*(p_oil_vol_fracP + p_oil_vol_fracE)*oil_viscosity\t ( mean_pressure ) \n\t\t\t\t\t\t\t\t+ 0.5*(water_vol_fracP + water_vol_fracE)*water_viscosity( mean_pressure );\n\n\n            real_type mod_Vow_W\t= this->mod_v_drift_flux_ow( \n                p_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n                0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n                );\n            real_type mod_Vow_P\t= this->mod_v_drift_flux_ow( \n                p_velocityP, 0.5*(p_gas_vol_fracP + p_gas_vol_fracE), 0.5*(p_oil_vol_fracP + p_oil_vol_fracE),\n                0.5*(water_vol_fracP + water_vol_fracE), 0.5*(p_pressureP + p_pressureE)\n                );\n            real_type mod_Vow_E\t= this->mod_v_drift_flux_ow( \n                p_velocityE, 0.5*(p_gas_vol_fracE + p_gas_vol_fracEE), 0.5*(p_oil_vol_fracE + p_oil_vol_fracEE),\n                0.5*(water_vol_fracE + water_vol_fracEE), 0.5*(p_pressureE + p_pressureEE)\n                );\n\n            real_type mod_Vgj_W\t= this->mod_v_drift_flux( \n                p_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n                0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n                );\n            real_type mod_Vgj_P\t= this->mod_v_drift_flux( \n                p_velocityP, 0.5*(p_gas_vol_fracP + p_gas_vol_fracE), 0.5*(p_oil_vol_fracP + p_oil_vol_fracE),\n                0.5*(water_vol_fracP + water_vol_fracE), 0.5*(p_pressureP + p_pressureE)\n                );\n            real_type mod_Vgj_E\t= this->mod_v_drift_flux( \n                p_velocityE, 0.5*(p_gas_vol_fracE + p_gas_vol_fracEE), 0.5*(p_oil_vol_fracE + p_oil_vol_fracEE),\n                0.5*(water_vol_fracE + water_vol_fracEE), 0.5*(p_pressureE + p_pressureEE)\n                );\n\n\n            //real_type Vc  = p_velocityP;\t\t\t\n            //real_type Re  = abs(0.5*(rho_P + rho_E)*Vc*2.0*m_radius/viscosity);\n            //real_type f_P = this->friction_factor( Re );\n\n            // OTHER Vc = j\n            real_type Vc = p_velocityP + 0.5*(p_gas_vol_fracP*(rhoL_P - rhoG_P)/rho_P*mod_Vgj_P + p_gas_vol_fracE*(rhoL_E - rhoG_E)/rho_E*mod_Vgj_E);\n            real_type Re  = abs(0.5*(rho_P + rho_E)*Vc*2.0*m_radius/viscosity);\n            real_type f_P = this->friction_factor( Re );\n\n\n\n            real_type gas_vol_frac_W   = 0.5*(p_gas_vol_fracP + p_gas_vol_fracW);\n            real_type oil_vol_frac_W   = 0.5*(p_oil_vol_fracP + p_oil_vol_fracW);\n            real_type water_vol_frac_W = 0.5*(water_vol_fracP + water_vol_fracW);\n            real_type rho_g_W = 0.5*(rhoG_W + rhoG_P);\n            real_type rho_o_W = 0.5*(rhoO_W + rhoO_P);\n            real_type rho_w_W = 0.5*(rhoW_W + rhoW_P);\n            real_type rho_l_W = 0.5*(rhoL_W + rhoL_P);\n            real_type rho_m_W = 0.5*(rho_W + rho_P);\n\n            real_type gas_velocity_W    = p_velocityW + rho_l_W/rho_m_W*mod_Vgj_W;\n            real_type liquid_velocity_W = p_velocityW - gas_vol_frac_W/(1 - gas_vol_frac_W + 1.0e-20)*rho_g_W/rho_m_W*mod_Vgj_W;\t \n            real_type water_velocity_W  = liquid_velocity_W - (oil_vol_frac_W/(water_vol_frac_W + 1.0e-20))*(rho_o_W/rho_l_W)*mod_Vow_W;               \n            real_type oil_velocity_W    = liquid_velocity_W + rho_w_W/rho_l_W*mod_Vow_W;  \n\n\n\n            real_type gas_vol_frac_P   = 0.5*(p_gas_vol_fracP + p_gas_vol_fracE);\n            real_type oil_vol_frac_P   = 0.5*(p_oil_vol_fracP + p_oil_vol_fracE);\n            real_type water_vol_frac_P = 0.5*(water_vol_fracP + water_vol_fracE);\n            real_type rho_g_P = 0.5*(rhoG_E + rhoG_P);\n            real_type rho_o_P = 0.5*(rhoO_E + rhoO_P);\n            real_type rho_w_P = 0.5*(rhoW_E + rhoW_P);\n            real_type rho_l_P = 0.5*(rhoL_E + rhoL_P);\n            real_type rho_m_P = 0.5*(rho_E + rho_P);\n\n            real_type gas_velocity_P    = p_velocityP + rho_l_P/rho_m_P*mod_Vgj_P;\n            real_type liquid_velocity_P = p_velocityP - gas_vol_frac_P/(1 - gas_vol_frac_P + 1.0e-20)*rho_g_P/rho_m_P*mod_Vgj_P;\t \n            real_type water_velocity_P  = liquid_velocity_P - (oil_vol_frac_P/(water_vol_frac_P + 1.0e-20))*(rho_o_P/rho_l_P)*mod_Vow_P;               \n            real_type oil_velocity_P    = liquid_velocity_P + rho_w_P/rho_l_P*mod_Vow_P;\n\n            real_type gas_vol_frac_E   = 0.5*(p_gas_vol_fracE + p_gas_vol_fracEE);\n            real_type oil_vol_frac_E   = 0.5*(p_oil_vol_fracE + p_oil_vol_fracEE);\n            real_type water_vol_frac_E = 0.5*(water_vol_fracE + water_vol_fracEE);\n            real_type rho_g_E = 0.5*(rhoG_E + rhoG_EE);\n            real_type rho_o_E = 0.5*(rhoO_E + rhoO_EE);\n            real_type rho_w_E = 0.5*(rhoW_E + rhoW_EE);\n            real_type rho_l_E = 0.5*(rhoL_E + rhoL_EE);\n            real_type rho_m_E = 0.5*(rho_E + rho_EE);\n\n            real_type gas_velocity_E    = p_velocityE + rho_l_E/rho_m_E*mod_Vgj_E;\n            real_type liquid_velocity_E = p_velocityE - gas_vol_frac_E/(1 - gas_vol_frac_E + 1.0e-20)*rho_g_E/rho_m_E*mod_Vgj_E;\t \n            real_type water_velocity_E  = liquid_velocity_E - (oil_vol_frac_E/(water_vol_frac_E + 1.0e-20))*(rho_o_E/rho_l_E)*mod_Vow_E;               \n            real_type oil_velocity_E    = liquid_velocity_E + rho_w_E/rho_l_E*mod_Vow_E;\n\n\n\n            real_type ksi_W_oil     = this->ksi( oil_velocity_W   );\n            real_type ksi_W_gas     = this->ksi( gas_velocity_W   );\n            real_type ksi_W_water   = this->ksi( water_velocity_W );\n\n            real_type ksi_P_oil     = this->ksi( oil_velocity_P   );\n            real_type ksi_P_gas     = this->ksi( gas_velocity_P   );\n            real_type ksi_P_water   = this->ksi( water_velocity_P );\n\n            real_type ksi_E_oil     = this->ksi( oil_velocity_E   );\n            real_type ksi_E_gas     = this->ksi( gas_velocity_E   );\n            real_type ksi_E_water   = this->ksi( water_velocity_E );\n\n            real_type m_W_oil   = oil_velocity_W  *( (0.5+ksi_W_oil  )*rhoO_W*p_oil_vol_fracW + (0.5-ksi_W_oil  )*rhoO_P*p_oil_vol_fracP );\n            real_type m_W_water = water_velocity_W*( (0.5+ksi_W_water)*rhoW_W*water_vol_fracW + (0.5-ksi_W_water)*rhoW_P*water_vol_fracP );\n            real_type m_W_gas   = gas_velocity_W  *( (0.5+ksi_W_gas  )*rhoG_W*p_gas_vol_fracW + (0.5-ksi_W_gas  )*rhoG_P*p_gas_vol_fracP );\n\n            real_type m_P_oil   = oil_velocity_P  *( (0.5+ksi_P_oil  )*rhoO_P*p_oil_vol_fracP + (0.5-ksi_P_oil  )*rhoO_E*p_oil_vol_fracE );\n            real_type m_P_water = water_velocity_P*( (0.5+ksi_P_water)*rhoW_P*water_vol_fracP + (0.5-ksi_P_water)*rhoW_E*water_vol_fracE );\n            real_type m_P_gas   = gas_velocity_P  *( (0.5+ksi_P_gas  )*rhoG_P*p_gas_vol_fracP + (0.5-ksi_P_gas  )*rhoG_E*p_gas_vol_fracE );\n\n            real_type m_E_oil   = oil_velocity_E  *( (0.5+ksi_E_oil  )*rhoO_P*p_oil_vol_fracE + (0.5-ksi_E_oil  )*rhoO_E*p_oil_vol_fracEE );\n            real_type m_E_water = water_velocity_E*( (0.5+ksi_E_water)*rhoW_P*water_vol_fracE + (0.5-ksi_E_water)*rhoW_E*water_vol_fracEE );\n            real_type m_E_gas   = gas_velocity_E  *( (0.5+ksi_E_gas  )*rhoG_P*p_gas_vol_fracE + (0.5-ksi_E_gas  )*rhoG_E*p_gas_vol_fracEE );\n\n            real_type ksi_e_oil = this->ksi( (1-d_e)*oil_velocity_P + d_e*oil_velocity_E );\n            real_type ksi_w_oil = this->ksi( (1-d_w)*oil_velocity_P + d_w*oil_velocity_W );\n            real_type ksi_e_water = this->ksi( (1-d_e)*water_velocity_P + d_e*water_velocity_E );\n            real_type ksi_w_water = this->ksi( (1-d_w)*water_velocity_P + d_w*water_velocity_W );\n            real_type ksi_e_gas = this->ksi( (1-d_e)*gas_velocity_P + d_e*gas_velocity_E );\n            real_type ksi_w_gas = this->ksi( (1-d_w)*gas_velocity_P + d_w*gas_velocity_W );\n\n            real_type m_e = 0.5*(m_E_oil  +m_P_oil)  *( (0.5+ksi_e_oil  )*oil_velocity_P   + (0.5-ksi_e_oil  )*oil_velocity_E )\n                + 0.5*(m_E_water+m_P_water)*( (0.5+ksi_e_water)*water_velocity_P + (0.5-ksi_e_water)*water_velocity_E )\n                + 0.5*(m_E_gas  +m_P_gas)  *( (0.5+ksi_e_gas  )*gas_velocity_P   + (0.5-ksi_e_gas  )*gas_velocity_E );\n\n            real_type m_w = 0.5*(m_W_oil  +m_P_oil)  *( (0.5+ksi_w_oil  )*oil_velocity_W   + (0.5-ksi_w_oil  )*oil_velocity_P )\n                + 0.5*(m_W_water+m_P_water)*( (0.5+ksi_w_water)*water_velocity_W + (0.5-ksi_w_water)*water_velocity_P )\n                + 0.5*(m_W_gas  +m_P_gas)  *( (0.5+ksi_w_gas  )*gas_velocity_W   + (0.5-ksi_w_gas  )*gas_velocity_P );  \n\n\n            real_type m_t =  oil_velocity_P  *(rhoO_P*p_oil_vol_fracP + rhoO_E*p_oil_vol_fracE)\n                          +  water_velocity_P*(rhoW_P*water_vol_fracP + rhoW_E*water_vol_fracE)\n                          +  gas_velocity_P  *(rhoG_P*p_gas_vol_fracP + rhoG_E*p_gas_vol_fracE);\n\n            return ( m_t - (rho_P_old+rho_E_old)*m_mean_velocity_old[ p_node ] )*0.5*dV/dt()\n                + (m_e - m_w)*area()                \n                + (p_pressureE-p_pressureP)*area() + 0.5*(rho_P+rho_E)*gravity()*sin( angle )*dV + 0.125/m_radius*f_P*(rho_P + rho_E)*dV*Vc*abs(Vc);\n\n\n\n\n\n            // New friction factor wells\n            // OUYANG\n            //real_type q_w = 0.5*((*m_oil_flow)[ p_node ]+(*m_oil_flow)[ p_node +1] + (*m_gas_flow)[ p_node ]+(*m_gas_flow)[ p_node +1] + (*m_water_flow)[ p_node ]+(*m_water_flow)[ p_node+1 ])/dS;\n            //real_type v_eq = q_w/(PI*2*m_radius);\n            //real_type Re_w = abs(0.5*(rho_P + rho_E)*v_eq*2*m_radius/viscosity);\n            //real_type f_P = this->friction_factor( Re )*(1+0.04304*pow(Re_w,0.6142));\n            // ASHEIM\n            //real_type q_m = p_velocityP*area();\n            //real_type q_i = 0.5*((*m_oil_flow)[ p_node ] + (*m_oil_flow)[ p_node+1 ] + (*m_gas_flow)[ p_node ]+ (*m_gas_flow)[ p_node+1 ] + (*m_water_flow)[ p_node ] + (*m_water_flow)[ p_node+1 ]);\n            //real_type f_complet = q_m == 0? 0.0 : 4*2*m_radius*q_i/dS/q_m + 2*m_radius*q_i/dS/q_m*q_i/dS/q_m;\n            //real_type f_P = this->friction_factor( Re ) + f_complet;\n            \n\t\t\t//real_type mod_Vgj_P\t\t= this->mod_v_drift_flux( \n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t (1-d_w)*p_velocityP + d_w*p_velocityW, p_gas_vol_fracP, p_oil_vol_fracP,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t water_vol_fracP, p_pressureP\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t );\n\t\t\t//real_type mod_Vgj_E\t\t= this->mod_v_drift_flux( \n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t (1-d_e)*p_velocityP + d_e*p_velocityE, p_gas_vol_fracE, p_oil_vol_fracE,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t water_vol_fracE, p_pressureE\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t );\n\n\t\t\t//\n\t\t\t//// OTHER Vc = j\n\t\t\t////real_type Vc = p_velocityP + 0.5*(p_gas_vol_fracP*(rhoL_P - rhoG_P)/rho_P*mod_Vgj_P + p_gas_vol_fracE*(rhoL_E - rhoG_E)/rho_E*mod_Vgj_E);\n\t\t\t////real_type Re  = abs(0.5*(rho_P + rho_E)*Vc*2*m_radius/viscosity);\n\t\t\t////real_type f_P = this->friction_factor( Re );\n\n\t\t\t//real_type ksi_e = this->ksi( (1-d_e)*p_velocityP + d_e*p_velocityE );\n\t\t\t//real_type ksi_w = this->ksi( (1-d_w)*p_velocityP + d_w*p_velocityW );\n\t\t\t//\n\t\t\t//\n\t\t\t////*return ( (rho_P+rho_E)*p_velocityP - (rho_P_old+rho_E_old)*m_mean_velocity_old[ p_node ] )*0.5*dV/dt()\n\t\t\t//\t + rho_E*area()*( (1-d_e)*p_velocityP + d_e*p_velocityE )*( (0.5+ksi_e)*p_velocityP + (0.5-ksi_e)*p_velocityE ) \n\t\t\t//\t - rho_P*area()*( (1-d_w)*p_velocityP + d_w*p_velocityW )*( (0.5+ksi_w)*p_velocityW + (0.5-ksi_w)*p_velocityP )\n\t\t\t//\t + (p_pressureE-p_pressureP)*area() + 0.5*(rho_P+rho_E)*gravity()*sin( angle )*dV + 0.125/m_radius*f_P*(rho_P + rho_E)*dV*p_velocityP*abs(p_velocityP)\n\t\t\t//\t + rhoG_E*rhoL_E/rho_E*area()*mod_Vgj_E*mod_Vgj_E*p_gas_vol_fracE/(1-p_gas_vol_fracE)\n\t\t\t//\t - rhoG_P*rhoL_P/rho_P*area()*mod_Vgj_P*mod_Vgj_P*p_gas_vol_fracP/(1-p_gas_vol_fracP);*/\n\t\t\t//\n\t\t\t//\n\t\t\t//real_type ksi_P = this->ksi( p_velocityP );\n\t\t\t//real_type ksi_W = this->ksi( p_velocityW );\n\n\t\t\t//real_type m_E\t= rho_E*p_velocityE*area();\n\t\t\t//real_type m_P\t= ((0.5+ksi_P)*rho_P + (0.5-ksi_P)*rho_E  )*p_velocityP*area();\n\t\t\t//real_type m_W\t= ((0.5+ksi_W)*rho_W + (0.5-ksi_W)*rho_P  )*p_velocityW*area();\n\n   //                    \n\t\t\t//return ( (rho_P+rho_E)*p_velocityP - (rho_P_old+rho_E_old)*m_mean_velocity_old[ p_node ] )*0.5*dV/dt()\n\t\t\t//\t + 0.5*(m_E+m_P)*( (0.5+ksi_e)*p_velocityP + (0.5-ksi_e)*p_velocityE )\n\t\t\t//\t - 0.5*(m_P+m_W)*( (0.5+ksi_w)*p_velocityW + (0.5-ksi_w)*p_velocityP )\n\t\t\t//\t + (p_pressureE-p_pressureP)*area() + 0.5*(rho_P+rho_E)*gravity()*sin( angle )*dV + 0.125/m_radius*f_P*(rho_P + rho_E)*dV*Vc*abs(Vc)\n\t\t\t//\t + rhoG_E*rhoL_E/rho_E*area()*mod_Vgj_E*mod_Vgj_E*p_gas_vol_fracE/(1-p_gas_vol_fracE + 1.0e-20)\n\t\t\t//\t - rhoG_P*rhoL_P/rho_P*area()*mod_Vgj_P*mod_Vgj_P*p_gas_vol_fracP/(1-p_gas_vol_fracP + 1.0e-20);\n\t\t\t//\n\t\t\t////*return ( (rho_P+rho_E)*p_velocityP - (rho_P_old+rho_E_old)*m_mean_velocity_old[ p_node ] )*0.5*dV/dt()\n\t\t\t//\t + rho_E*area()*( (1-d_e)*p_velocityP + d_e*p_velocityE )*( (0.5+ksi_e)*p_velocityP + (0.5-ksi_e)*p_velocityE ) \n\t\t\t//\t - rho_P*area()*( (1-d_w)*p_velocityP + d_w*p_velocityW )*( (0.5+ksi_w)*p_velocityW + (0.5-ksi_w)*p_velocityP )\n\t\t\t//\t + (p_pressureE-p_pressureP)*area() + 0.5*(rho_P+rho_E)*gravity()*sin( angle )*dV + 0.125/m_radius*f_P*(rho_P + rho_E)*dV*m_j[ p_node ]*abs(m_j[ p_node ]);\n\t\t\t//\t */\n\t\t\t//\t \n\t\t\t//\t //+ rhoG_E*rhoL_E/rho_E*area()*mod_Vgj_E*mod_Vgj_E*p_gas_vol_fracE/(1-p_gas_vol_fracE)\n\t\t\t//\t// - rhoG_P*rhoL_P/rho_P*area()*mod_Vgj_P*mod_Vgj_P*p_gas_vol_fracP/(1-p_gas_vol_fracP);\n\n            \n\t\t\t}\n\t\t\t\n\n\n\t\tcase 'C':\n\t\t\t{\n\t\t\treal_type dS  = this->segment_length( m_coordinates[ p_node ], m_coordinates[ p_node+1 ] );\n\t\t\treal_type dSe = this->segment_length( m_coordinates[ p_node+1 ], m_coordinates[ p_node+2 ] );\n\t\t\treal_type dSw = this->segment_length( m_coordinates[ p_node ], m_coordinates[ p_node-1 ] );\n\t\t\treal_type dV = this->Volume( dS );\n\n\t\t\treal_type water_vol_fracP_old\t= 1.0 - (m_oil_vol_frac_old[ p_node ]   + m_gas_vol_frac_old[ p_node ]\t);\n\t\t\treal_type water_vol_fracE_old\t= 1.0 - (m_oil_vol_frac_old[ p_node+1 ] + m_gas_vol_frac_old[ p_node+1 ]);\n\t\t\treal_type water_vol_fracW\t\t= 1.0 - (p_gas_vol_fracW + p_oil_vol_fracW);\n\t\t\treal_type water_vol_fracP\t\t= 1.0 - (p_gas_vol_fracP + p_oil_vol_fracP);\n\t\t\treal_type water_vol_fracE\t\t= 1.0 - (p_gas_vol_fracE + p_oil_vol_fracE);\t\n\t\t\treal_type water_vol_fracEE\t\t= 1.0 - (p_gas_vol_fracEE + p_oil_vol_fracEE);\n\n\t\t\treal_type rho_P_old = this->mean_density(m_oil_vol_frac_old[ p_node ], water_vol_fracP_old, m_gas_vol_frac_old[ p_node ], m_pressure_old[ p_node ]);\n\t\t\treal_type rho_E_old = this->mean_density(m_oil_vol_frac_old[ p_node+1 ], water_vol_fracE_old, m_gas_vol_frac_old[ p_node+1 ], m_pressure_old[ p_node+1 ]);\n            real_type rhoG_P_old = this->gas_density( m_pressure_old[ p_node ] );\n            real_type rhoO_P_old = this->oil_density( m_pressure_old[ p_node ] );\n            real_type rhoW_P_old = this->water_density( m_pressure_old[ p_node ] );\n\n\t\t\tvector_type S( 3 );\n\t\t\tS[ 0 ] = m_coordinates[ p_node ].getX() - m_coordinates[ p_node+1 ].getX();\n\t\t\tS[ 1 ] = m_coordinates[ p_node ].getY() - m_coordinates[ p_node+1 ].getY();\n\t\t\tS[ 2 ] = m_coordinates[ p_node ].getZ() - m_coordinates[ p_node+1 ].getZ();\n\t\t\t\n\t\t\treal_type d_e = dS/(dS+dSe);\n\t\t\treal_type d_w = dS/(dS+dSw);\n\n\t\t\treal_type angle = get_inclination() - PI/2;// - 0*acos( dot( m_gravity, S )/(norm(m_gravity)*norm(S)) );\t\t\n\t\t\t\n\t\t\treal_type rho_W   = this->mean_density(p_oil_vol_fracW, water_vol_fracW, p_gas_vol_fracW , p_pressureW );\n\t\t\treal_type rho_P   = this->mean_density(p_oil_vol_fracP, water_vol_fracP, p_gas_vol_fracP, p_pressureP);\n\t\t\treal_type rho_E   = this->mean_density(p_oil_vol_fracE, water_vol_fracE, p_gas_vol_fracE, p_pressureE);\n\t\t\treal_type rho_EE  = this->mean_density(p_oil_vol_fracEE, water_vol_fracEE, p_gas_vol_fracEE , p_pressureEE);\n\t\t\t\n            real_type rhoG_W\t\t= this->gas_density( p_pressureW );\n\t\t\treal_type rhoG_P\t\t= this->gas_density( p_pressureP );\n\t\t\treal_type rhoG_E\t\t= this->gas_density( p_pressureE );\n            real_type rhoG_EE\t\t= this->gas_density( p_pressureEE );\n\n            real_type rhoL_W\t\t= this->liquid_density( p_oil_vol_fracW, water_vol_fracW, p_pressureW );\n\t\t\treal_type rhoL_P\t\t= this->liquid_density( p_oil_vol_fracP, water_vol_fracP, p_pressureP );\n\t\t\treal_type rhoL_E\t\t= this->liquid_density( p_oil_vol_fracE, water_vol_fracE, p_pressureE );\n            real_type rhoL_EE\t\t= this->liquid_density( p_oil_vol_fracEE, water_vol_fracEE, p_pressureEE );\n\n            real_type rhoW_W\t\t= this->water_density( p_pressureW );\n            real_type rhoW_P\t\t= this->water_density( p_pressureP );\n            real_type rhoW_E\t\t= this->water_density( p_pressureE );\n            real_type rhoW_EE\t\t= this->water_density( p_pressureEE );\n\n            real_type rhoO_W\t\t= this->oil_density( p_pressureW );\n            real_type rhoO_P\t\t= this->oil_density( p_pressureP );\n            real_type rhoO_E\t\t= this->oil_density( p_pressureE );\n            real_type rhoO_EE\t\t= this->oil_density( p_pressureEE );            \n\t\t\t\n\t\t\treal_type mean_pressure = 0.5*(p_pressureP + p_pressureE);\n\t\t\treal_type viscosity = 0.5*(p_gas_vol_fracP + p_gas_vol_fracE)*gas_viscosity\t ( mean_pressure ) \n\t\t\t\t\t\t\t\t+ 0.5*(p_oil_vol_fracP + p_oil_vol_fracE)*oil_viscosity\t ( mean_pressure ) \n\t\t\t\t\t\t\t\t+ 0.5*(water_vol_fracP + water_vol_fracE)*water_viscosity( mean_pressure );\t\n\n\n            // New friction factor wells\n            // OUYANG\n            //real_type q_w = 0.5*((*m_oil_flow)[ p_node ]+(*m_oil_flow)[ p_node +1] + (*m_gas_flow)[ p_node ]+(*m_gas_flow)[ p_node +1] + (*m_water_flow)[ p_node ]+(*m_water_flow)[ p_node+1 ])/dS;\n            //real_type v_eq = q_w/(PI*2*m_radius);\n            //real_type Re_w = abs(0.5*(rho_P + rho_E)*v_eq*2*m_radius/viscosity);\n            //real_type f_P = this->friction_factor( Re )*(1+0.04304*pow(Re_w,0.6142));\n            // ASHEIM\n            //real_type q_m = p_velocityP*area();\n            //real_type q_i = 0.5*((*m_oil_flow)[ p_node ] + (*m_oil_flow)[ p_node+1 ] + (*m_gas_flow)[ p_node ]+ (*m_gas_flow)[ p_node+1 ] + (*m_water_flow)[ p_node ] + (*m_water_flow)[ p_node+1 ]);\n            //real_type f_complet = q_m == 0? 0.0 : 4*2*m_radius*q_i/dS/q_m + 2*m_radius*q_i/dS/q_m*q_i/dS/q_m;\n            //real_type f_P = this->friction_factor( Re ) + f_complet;\n           \n\n\t\t\t/*real_type mod_Vgj_P\t\t= this->mod_v_drift_flux( \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(1-d_w)*p_velocityP + d_w*p_velocityW, p_gas_vol_fracP, p_oil_vol_fracP,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t water_vol_fracP, p_pressureP\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t );\n\t\t\treal_type mod_Vgj_E\t\t= this->mod_v_drift_flux( \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t (1-d_e)*p_velocityP + d_e*p_velocityE, p_gas_vol_fracE, p_oil_vol_fracE,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t water_vol_fracE, p_pressureE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t );\n            real_type mod_Vow_P\t= this->mod_v_drift_flux_ow( \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(1-d_w)*p_velocityP + d_w*p_velocityW, p_gas_vol_fracP, p_oil_vol_fracP,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t water_vol_fracP, p_pressureP\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t );\n\t\t\treal_type mod_Vow_E\t= this->mod_v_drift_flux_ow( \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t (1-d_e)*p_velocityP + d_e*p_velocityE, p_gas_vol_fracE, p_oil_vol_fracE,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t water_vol_fracE, p_pressureE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t );*/\n\n\n            real_type mod_Vow_W\t= this->mod_v_drift_flux_ow( \n                p_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n                0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n                );\n            real_type mod_Vow_P\t= this->mod_v_drift_flux_ow( \n                p_velocityP, 0.5*(p_gas_vol_fracP + p_gas_vol_fracE), 0.5*(p_oil_vol_fracP + p_oil_vol_fracE),\n                0.5*(water_vol_fracP + water_vol_fracE), 0.5*(p_pressureP + p_pressureE)\n                );\n            real_type mod_Vow_E\t= this->mod_v_drift_flux_ow( \n                p_velocityE, 0.5*(p_gas_vol_fracE + p_gas_vol_fracEE), 0.5*(p_oil_vol_fracE + p_oil_vol_fracEE),\n                0.5*(water_vol_fracE + water_vol_fracEE), 0.5*(p_pressureE + p_pressureEE)\n                );\n\n            real_type mod_Vgj_W\t= this->mod_v_drift_flux( \n                p_velocityW, 0.5*(p_gas_vol_fracP + p_gas_vol_fracW), 0.5*(p_oil_vol_fracP + p_oil_vol_fracW),\n                0.5*(water_vol_fracP + water_vol_fracW), 0.5*(p_pressureP + p_pressureW)\n                );\n            real_type mod_Vgj_P\t= this->mod_v_drift_flux( \n                p_velocityP, 0.5*(p_gas_vol_fracP + p_gas_vol_fracE), 0.5*(p_oil_vol_fracP + p_oil_vol_fracE),\n                0.5*(water_vol_fracP + water_vol_fracE), 0.5*(p_pressureP + p_pressureE)\n                );\n            real_type mod_Vgj_E\t= this->mod_v_drift_flux( \n                p_velocityE, 0.5*(p_gas_vol_fracE + p_gas_vol_fracEE), 0.5*(p_oil_vol_fracE + p_oil_vol_fracEE),\n                0.5*(water_vol_fracE + water_vol_fracEE), 0.5*(p_pressureE + p_pressureEE)\n                );\n                \n\n            //real_type Vc  = p_velocityP;\t\t\t\n            //real_type Re  = abs(0.5*(rho_P + rho_E)*Vc*2.0*m_radius/viscosity);\n            //real_type f_P = this->friction_factor( Re );\n\n            // OTHER Vc = j\n            real_type Vc = p_velocityP + 0.5*(p_gas_vol_fracP*(rhoL_P - rhoG_P)/rho_P*mod_Vgj_P + p_gas_vol_fracE*(rhoL_E - rhoG_E)/rho_E*mod_Vgj_E);\n            real_type Re  = abs(0.5*(rho_P + rho_E)*Vc*2.0*m_radius/viscosity);\n            real_type f_P = this->friction_factor( Re );\n\n\n\n            real_type gas_vol_frac_W   = 0.5*(p_gas_vol_fracP + p_gas_vol_fracW);\n            real_type oil_vol_frac_W   = 0.5*(p_oil_vol_fracP + p_oil_vol_fracW);\n            real_type water_vol_frac_W = 0.5*(water_vol_fracP + water_vol_fracW);\n            real_type rho_g_W = 0.5*(rhoG_W + rhoG_P);\n            real_type rho_o_W = 0.5*(rhoO_W + rhoO_P);\n            real_type rho_w_W = 0.5*(rhoW_W + rhoW_P);\n            real_type rho_l_W = 0.5*(rhoL_W + rhoL_P);\n            real_type rho_m_W = 0.5*(rho_W + rho_P);\n\n            real_type gas_velocity_W    = p_velocityW + rho_l_W/rho_m_W*mod_Vgj_W;\n            real_type liquid_velocity_W = p_velocityW - gas_vol_frac_W/(1 - gas_vol_frac_W + 1.0e-20)*rho_g_W/rho_m_W*mod_Vgj_W;\t \n            real_type water_velocity_W  = liquid_velocity_W - (oil_vol_frac_W/(water_vol_frac_W + 1.0e-20))*(rho_o_W/rho_l_W)*mod_Vow_W;               \n            real_type oil_velocity_W    = liquid_velocity_W + rho_w_W/rho_l_W*mod_Vow_W;  \n\n\n\n            real_type gas_vol_frac_P   = 0.5*(p_gas_vol_fracP + p_gas_vol_fracE);\n            real_type oil_vol_frac_P   = 0.5*(p_oil_vol_fracP + p_oil_vol_fracE);\n            real_type water_vol_frac_P = 0.5*(water_vol_fracP + water_vol_fracE);\n            real_type rho_g_P = 0.5*(rhoG_E + rhoG_P);\n            real_type rho_o_P = 0.5*(rhoO_E + rhoO_P);\n            real_type rho_w_P = 0.5*(rhoW_E + rhoW_P);\n            real_type rho_l_P = 0.5*(rhoL_E + rhoL_P);\n            real_type rho_m_P = 0.5*(rho_E + rho_P);\n\n            real_type gas_velocity_P    = p_velocityP + rho_l_P/rho_m_P*mod_Vgj_P;\n            real_type liquid_velocity_P = p_velocityP - gas_vol_frac_P/(1 - gas_vol_frac_P + 1.0e-20)*rho_g_P/rho_m_P*mod_Vgj_P;\t \n            real_type water_velocity_P  = liquid_velocity_P - (oil_vol_frac_P/(water_vol_frac_P + 1.0e-20))*(rho_o_P/rho_l_P)*mod_Vow_P;               \n            real_type oil_velocity_P    = liquid_velocity_P + rho_w_P/rho_l_P*mod_Vow_P;\n\n            real_type gas_vol_frac_E   = 0.5*(p_gas_vol_fracE + p_gas_vol_fracEE);\n            real_type oil_vol_frac_E   = 0.5*(p_oil_vol_fracE + p_oil_vol_fracEE);\n            real_type water_vol_frac_E = 0.5*(water_vol_fracE + water_vol_fracEE);\n            real_type rho_g_E = 0.5*(rhoG_E + rhoG_EE);\n            real_type rho_o_E = 0.5*(rhoO_E + rhoO_EE);\n            real_type rho_w_E = 0.5*(rhoW_E + rhoW_EE);\n            real_type rho_l_E = 0.5*(rhoL_E + rhoL_EE);\n            real_type rho_m_E = 0.5*(rho_E + rho_EE);\n\n            real_type gas_velocity_E    = p_velocityE + rho_l_E/rho_m_E*mod_Vgj_E;\n            real_type liquid_velocity_E = p_velocityE - gas_vol_frac_E/(1 - gas_vol_frac_E + 1.0e-20)*rho_g_E/rho_m_E*mod_Vgj_E;\t \n            real_type water_velocity_E  = liquid_velocity_E - (oil_vol_frac_E/(water_vol_frac_E + 1.0e-20))*(rho_o_E/rho_l_E)*mod_Vow_E;               \n            real_type oil_velocity_E    = liquid_velocity_E + rho_w_E/rho_l_E*mod_Vow_E;\n\n\n\n            real_type ksi_W_oil     = this->ksi( oil_velocity_W   );\n            real_type ksi_W_gas     = this->ksi( gas_velocity_W   );\n            real_type ksi_W_water   = this->ksi( water_velocity_W );\n\n            real_type ksi_P_oil     = this->ksi( oil_velocity_P   );\n            real_type ksi_P_gas     = this->ksi( gas_velocity_P   );\n            real_type ksi_P_water   = this->ksi( water_velocity_P );\n\n            real_type ksi_E_oil     = this->ksi( oil_velocity_E   );\n            real_type ksi_E_gas     = this->ksi( gas_velocity_E   );\n            real_type ksi_E_water   = this->ksi( water_velocity_E );\n\n            real_type m_W_oil   = oil_velocity_W  *( (0.5+ksi_W_oil  )*rhoO_W*p_oil_vol_fracW + (0.5-ksi_W_oil  )*rhoO_P*p_oil_vol_fracP );\n            real_type m_W_water = water_velocity_W*( (0.5+ksi_W_water)*rhoW_W*water_vol_fracW + (0.5-ksi_W_water)*rhoW_P*water_vol_fracP );\n            real_type m_W_gas   = gas_velocity_W  *( (0.5+ksi_W_gas  )*rhoG_W*p_gas_vol_fracW + (0.5-ksi_W_gas  )*rhoG_P*p_gas_vol_fracP );\n\n            real_type m_P_oil   = oil_velocity_P  *( (0.5+ksi_P_oil  )*rhoO_P*p_oil_vol_fracP + (0.5-ksi_P_oil  )*rhoO_E*p_oil_vol_fracE );\n            real_type m_P_water = water_velocity_P*( (0.5+ksi_P_water)*rhoW_P*water_vol_fracP + (0.5-ksi_P_water)*rhoW_E*water_vol_fracE );\n            real_type m_P_gas   = gas_velocity_P  *( (0.5+ksi_P_gas  )*rhoG_P*p_gas_vol_fracP + (0.5-ksi_P_gas  )*rhoG_E*p_gas_vol_fracE );\n\n            real_type m_E_oil   = oil_velocity_E  *( (0.5+ksi_E_oil  )*rhoO_P*p_oil_vol_fracE + (0.5-ksi_E_oil  )*rhoO_E*p_oil_vol_fracEE );\n            real_type m_E_water = water_velocity_E*( (0.5+ksi_E_water)*rhoW_P*water_vol_fracE + (0.5-ksi_E_water)*rhoW_E*water_vol_fracEE );\n            real_type m_E_gas   = gas_velocity_E  *( (0.5+ksi_E_gas  )*rhoG_P*p_gas_vol_fracE + (0.5-ksi_E_gas  )*rhoG_E*p_gas_vol_fracEE );\n\n            real_type ksi_e_oil = this->ksi( (1-d_e)*oil_velocity_P + d_e*oil_velocity_E );\n            real_type ksi_w_oil = this->ksi( (1-d_w)*oil_velocity_P + d_w*oil_velocity_W );\n            real_type ksi_e_water = this->ksi( (1-d_e)*water_velocity_P + d_e*water_velocity_E );\n            real_type ksi_w_water = this->ksi( (1-d_w)*water_velocity_P + d_w*water_velocity_W );\n            real_type ksi_e_gas = this->ksi( (1-d_e)*gas_velocity_P + d_e*gas_velocity_E );\n            real_type ksi_w_gas = this->ksi( (1-d_w)*gas_velocity_P + d_w*gas_velocity_W );\n\n            real_type m_e = 0.5*(m_E_oil  +m_P_oil)  *( (0.5+ksi_e_oil  )*oil_velocity_P   + (0.5-ksi_e_oil  )*oil_velocity_E )\n                          + 0.5*(m_E_water+m_P_water)*( (0.5+ksi_e_water)*water_velocity_P + (0.5-ksi_e_water)*water_velocity_E )\n                          + 0.5*(m_E_gas  +m_P_gas)  *( (0.5+ksi_e_gas  )*gas_velocity_P   + (0.5-ksi_e_gas  )*gas_velocity_E );\n\n            real_type m_w = 0.5*(m_W_oil  +m_P_oil)  *( (0.5+ksi_w_oil  )*oil_velocity_W   + (0.5-ksi_w_oil  )*oil_velocity_P )\n                          + 0.5*(m_W_water+m_P_water)*( (0.5+ksi_w_water)*water_velocity_W + (0.5-ksi_w_water)*water_velocity_P )\n                          + 0.5*(m_W_gas  +m_P_gas)  *( (0.5+ksi_w_gas  )*gas_velocity_W   + (0.5-ksi_w_gas  )*gas_velocity_P );\n\n          /*  real_type m_e = rhoO_E*p_oil_vol_fracE*((1-d_e)*oil_velocity_P + d_e*oil_velocity_E )*( (0.5+ksi_e_oil  )*oil_velocity_P   + (0.5-ksi_e_oil  )*oil_velocity_E )\n                          + rhoW_E*water_vol_fracE*((1-d_e)*water_velocity_P + d_e*water_velocity_E )*( (0.5+ksi_e_water)*water_velocity_P + (0.5-ksi_e_water)*water_velocity_E )\n                          + rhoG_E*p_gas_vol_fracE*((1-d_e)*gas_velocity_P + d_e*gas_velocity_E )*( (0.5+ksi_e_gas  )*gas_velocity_P   + (0.5-ksi_e_gas  )*gas_velocity_E );\n\n            real_type m_w = rhoO_P*p_oil_vol_fracP*((1-d_w)*oil_velocity_P + d_w*oil_velocity_W )*( (0.5+ksi_w_oil  )*oil_velocity_W   + (0.5-ksi_w_oil  )*oil_velocity_P )\n                          + rhoW_P*water_vol_fracP*((1-d_w)*water_velocity_P + d_w*water_velocity_W )*( (0.5+ksi_w_water)*water_velocity_W + (0.5-ksi_w_water)*water_velocity_P )\n                          + rhoG_P*p_gas_vol_fracP*((1-d_w)*gas_velocity_P + d_w*gas_velocity_W )*( (0.5+ksi_w_gas  )*gas_velocity_W   + (0.5-ksi_w_gas  )*gas_velocity_P );\n        */    \n            real_type m_t =  oil_velocity_P  *(rhoO_P*p_oil_vol_fracP + rhoO_E*p_oil_vol_fracE)\n                          +  water_velocity_P*(rhoW_P*water_vol_fracP + rhoW_E*water_vol_fracE)\n                          +  gas_velocity_P  *(rhoG_P*p_gas_vol_fracP + rhoG_E*p_gas_vol_fracE);\n\n            return ( m_t - (rho_P_old+rho_E_old)*m_mean_velocity_old[ p_node ] )*0.5*dV/dt()\n                + (m_e - m_w)*area()                \n                + (p_pressureE-p_pressureP)*area() + 0.5*(rho_P+rho_E)*gravity()*sin( angle )*dV + 0.125/m_radius*f_P*(rho_P + rho_E)*dV*Vc*abs(Vc);\n           \n\n\n\t\t\t// OTHER Vc = j\n\t\t\t//real_type Vc = p_velocityP + 0.5*(p_gas_vol_fracP*(rhoL_P - rhoG_P)/rho_P*mod_Vgj_P + p_gas_vol_fracE*(rhoL_E - rhoG_E)/rho_E*mod_Vgj_E);\n\t\t\t//real_type Re  = abs(0.5*(rho_P + rho_E)*Vc*2*m_radius/viscosity);\n\t\t\t//real_type f_P = this->friction_factor( Re );\n\n\t\t\n\t\t/*\treal_type ksi_e = this->ksi( (1-d_e)*p_velocityP + d_e*p_velocityE );\n\t\t\treal_type ksi_w = this->ksi( (1-d_w)*p_velocityP + d_w*p_velocityW );*/\n\t\t\t\n\t\t\t\n\t\t\t/*return ( (rho_P+rho_E)*p_velocityP - (rho_P_old+rho_E_old)*m_mean_velocity_old[ p_node ] )*0.5*dV/dt()\n\t\t\t\t + rho_E*area()*( (1-d_e)*p_velocityP + d_e*p_velocityE )*( (0.5+ksi_e)*p_velocityP + (0.5-ksi_e)*p_velocityE )\n\t\t\t\t - rho_P*area()*( (1-d_w)*p_velocityP + d_w*p_velocityW )*( (0.5+ksi_w)*p_velocityW + (0.5-ksi_w)*p_velocityP )\n\t\t\t\t + (p_pressureE-p_pressureP)*area() + 0.5*(rho_P+rho_E)*gravity()*sin( angle )*dV + 0.125/m_radius*f_P*(rho_P + rho_E)*dV*p_velocityP*abs(p_velocityP)\n\t\t\t\t + rhoG_E*rhoL_E/rho_E*area()*mod_Vgj_E*mod_Vgj_E*p_gas_vol_fracE/(1-p_gas_vol_fracE)\n\t\t\t\t - rhoG_P*rhoL_P/rho_P*area()*mod_Vgj_P*mod_Vgj_P*p_gas_vol_fracP/(1-p_gas_vol_fracP);*/\n\t\t\t//real_type ksi_E = this->ksi( p_velocityE );\n\t\t\t//real_type ksi_P = this->ksi( p_velocityP );\n\t\t\t//real_type ksi_W = this->ksi( p_velocityW );\n\n\t\t\t//real_type m_E\t= ((0.5+ksi_E)*rho_E + (0.5-ksi_E)*rho_EE )*p_velocityE*area();\n\t\t\t//real_type m_P\t= ((0.5+ksi_P)*rho_P + (0.5-ksi_P)*rho_E  )*p_velocityP*area();\n\t\t\t//real_type m_W\t= ((0.5+ksi_W)*rho_W + (0.5-ksi_W)*rho_P  )*p_velocityW*area();\n\n\t\t\t//return ( (rho_P+rho_E)*p_velocityP - (rho_P_old+rho_E_old)*m_mean_velocity_old[ p_node ] )*0.5*dV/dt()\n\t\t\t//\t + 0.5*(m_E+m_P)*( (0.5+ksi_e)*p_velocityP + (0.5-ksi_e)*p_velocityE )\n\t\t\t//\t - 0.5*(m_P+m_W)*( (0.5+ksi_w)*p_velocityW + (0.5-ksi_w)*p_velocityP )\n\t\t\t//\t + (p_pressureE-p_pressureP)*area() + 0.5*(rho_P+rho_E)*gravity()*sin( angle )*dV + 0.125/m_radius*f_P*(rho_P + rho_E)*dV*Vc*abs(Vc)\n\t\t\t//\t + rhoG_E*rhoL_E/rho_E*area()*mod_Vgj_E*mod_Vgj_E*p_gas_vol_fracE/(1-p_gas_vol_fracE + 1.0e-20)\n\t\t\t//\t - rhoG_P*rhoL_P/rho_P*area()*mod_Vgj_P*mod_Vgj_P*p_gas_vol_fracP/(1-p_gas_vol_fracP + 1.0e-20);\n\n\t\t\t/*return ( (rho_P+rho_E)*p_velocityP - (rho_P_old+rho_E_old)*m_mean_velocity_old[ p_node ] )*0.5*dV/dt()\n\t\t\t\t + rho_E*area()*( (1-d_e)*p_velocityP + d_e*p_velocityE )*( (0.5+ksi_e)*p_velocityP + (0.5-ksi_e)*p_velocityE )\n\t\t\t\t - rho_P*area()*( (1-d_w)*p_velocityP + d_w*p_velocityW )*( (0.5+ksi_w)*p_velocityW + (0.5-ksi_w)*p_velocityP )\n\t\t\t\t + (p_pressureE-p_pressureP)*area() + 0.5*(rho_P+rho_E)*gravity()*sin( angle )*dV + 0.125/m_radius*f_P*(rho_P + rho_E)*dV*m_j[ p_node ]*abs(m_j[ p_node ]);\n\t\t\t*/\n\t\t\t\t \n\t\t\t\t //+ rhoG_E*rhoL_E/rho_E*area()*mod_Vgj_E*mod_Vgj_E*p_gas_vol_fracE/(1-p_gas_vol_fracE)\n\t\t\t\t //- rhoG_P*rhoL_P/rho_P*area()*mod_Vgj_P*mod_Vgj_P*p_gas_vol_fracP/(1-p_gas_vol_fracP);\n\t\t\t}\n\n\t\tdefault:\n\t\t\treturn 0.;\n\t\t\t\n\t\t}\n\t}\n\n\t\n\n\tvoid DriftFluxWell::GMRES_Solve( smatrix_type &A, svector_type &x, svector_type &b )\n\t{\n\t\tm_convergence_status = true;\n            \t\t\t\n        itl::ILU<smatrix_type> precond(A);\n        // SSOR preconditioner\t\t\t\n        //itl::SSOR<smatrix_type> precond(A);\t\t\n        svector_type b2( A.ncols() );\t\t\t\n        itl::solve(precond(), b, b2); //gmres needs the preconditioned b to pass into iter object.\n        //iteration\n        int max_iter = 1000;\t//ex: 1000\t\t\t\n        itl::noisy_iteration<double> iter(b2, max_iter, 0.0, 1E-6);\n        int restart = 10; //restart constant: 10\n        // modified_gram_schmidt\t\t\t\t\n        itl::modified_gram_schmidt<svector_type> orth( restart, x.size() );\t\t\t\n        //gmres algorithm\t            \n        m_convergence_status = itl::gmres(A, x, b, precond(), restart, iter, orth); \n\t\t\t\n\t\n\t}\n\n\tvoid DriftFluxWell::compute_Jacobian()\n\t{\n\t\tbool WITH_GAS = this->m_with_gas;\n\t\tbool WITH_MOMENTUM = true;\n\n\t\treal_type s_R_m;\t\t\treal_type s_R_g;\t\t\treal_type s_R_o;\t\t\treal_type s_R_v;\n\t\treal_type R_m_dPW;\t\t\treal_type R_g_dPW;\t\t\treal_type R_o_dPW;\t\t\treal_type R_v_dPP;  \n\t\treal_type R_m_dPP;\t\t\treal_type R_g_dPP;\t\t\treal_type R_o_dPP;\t\t\treal_type R_v_dPE; \n\t\treal_type R_m_dPE;\t\t\treal_type R_g_dPE;\t\t\treal_type R_o_dPE;\t\t\treal_type R_v_dalphaGasP;\n\t\treal_type R_m_dalphaGasW;\treal_type R_g_dalphaGasW;\treal_type R_o_dalphaGasW;\treal_type R_v_dalphaGasE;  \n\t\treal_type R_m_dalphaGasP;\treal_type R_g_dalphaGasP;\treal_type R_o_dalphaGasP;\treal_type R_v_dalphaOilP; \n\t\treal_type R_m_dalphaGasE;\treal_type R_g_dalphaGasE;\treal_type R_o_dalphaGasE;\treal_type R_v_dalphaOilE;\n\t\treal_type R_m_dalphaOilW;\treal_type R_g_dalphaOilW;\treal_type R_o_dalphaOilW;\treal_type R_v_dvW;  \n\t\treal_type R_m_dalphaOilP;\treal_type R_g_dalphaOilP;\treal_type R_o_dalphaOilP;\treal_type R_v_dvP; \n\t\treal_type R_m_dalphaOilE;\treal_type R_g_dalphaOilE;\treal_type R_o_dalphaOilE;\treal_type R_v_dvE;\n\t\treal_type R_m_dvW;\t\t\treal_type R_g_dvW;\t\t\treal_type R_o_dvW;\t\t\t\n\t\treal_type R_m_dvP;\t\t\treal_type R_g_dvP;\t\t\treal_type R_o_dvP;\t\t\t\n\t\t\n        // EXTRA DERIVATIVES \n\t\treal_type R_v_dPW;\n        real_type R_v_dPEE;\n        real_type R_v_dalphaGasW;\n        real_type R_v_dalphaGasEE;\n        real_type R_v_dalphaOilW;\n        real_type R_v_dalphaOilEE;\n\n\t\treal_type delta_PP;\t\n\t\treal_type delta_alphaGasP;\n\t\treal_type delta_alphaOilP;\n\t\treal_type delta_vP;\n\t\treal_type delta_PW;\t\n\t\treal_type delta_alphaGasW;\n\t\treal_type delta_alphaOilW;\n\t\treal_type delta_vW;\t\n\t\treal_type delta_PE;\t\n\t\treal_type delta_alphaGasE;\n\t\treal_type delta_alphaOilE;\n\t\treal_type delta_vE;\t\n        real_type delta_PEE;\t\n        real_type delta_alphaGasEE;\n        real_type delta_alphaOilEE;\n\t\t\n\t\tuint_type CENT = 0;\n\t\tuint_type EAST = CENT + 1;\n\t\tuint_type WEST = CENT;\t\t\n\t\t\t\t\n\t\t\n\n\t\tdelta_PP\t\t= m_delta[ P ]*m_pressure[ CENT ];\n\t\tdelta_alphaGasP\t= m_gas_vol_frac[ CENT ] > 1e-8 ? m_delta[ alpha_g ]*m_gas_vol_frac[ CENT ] : 1e-4*m_delta[ alpha_g ];\n\t\tdelta_alphaOilP\t= m_oil_vol_frac[ CENT ] > 1e-8 ? m_delta[ alpha_o ]*m_oil_vol_frac[ CENT ] : 1e-4*m_delta[ alpha_o ];\n\t\tdelta_vP\t\t= abs(m_mean_velocity[ CENT ]) > 1e-8 ? m_delta[ v ]*m_mean_velocity[ CENT ] : 1e-4*m_delta[ v ];\t\t\n\t\tdelta_PE\t\t= m_delta[ P ]*m_pressure[ EAST ];\n\t\tdelta_alphaGasE\t= m_gas_vol_frac[ EAST ] > 1e-8 ? m_delta[ alpha_g ]*m_gas_vol_frac[ EAST ] : 1e-4*m_delta[ alpha_g ];\n\t\tdelta_alphaOilE\t= m_oil_vol_frac[ EAST ] > 1e-8 ? m_delta[ alpha_o ]*m_oil_vol_frac[ EAST ] : 1e-4*m_delta[ alpha_o ];\n\t\tdelta_vE\t\t= abs(m_mean_velocity[ EAST ]) > 1e-8 ? m_delta[ v ]*m_mean_velocity[ EAST ] : 1e-4*m_delta[ v ];\n        delta_PEE\t\t    = m_delta[ P ]*m_pressure[ EAST+1 ];\n        delta_alphaGasEE\t= m_gas_vol_frac[ EAST+1 ] > 1e-8 ? m_delta[ alpha_g ]*m_gas_vol_frac[ EAST+1 ] : 1e-4*m_delta[ alpha_g ];\n        delta_alphaOilEE\t= m_oil_vol_frac[ EAST+1 ] > 1e-8 ? m_delta[ alpha_o ]*m_oil_vol_frac[ EAST+1 ] : 1e-4*m_delta[ alpha_o ];\n\n\t//MIXTURE - PRESSURE == 0\t\t\n\t\t(*this->m_matrix)( id(0,P), id(0,P) )\t\t= 1.;\t\t\n\t\t\n\t//GAS\n\t\tif( WITH_GAS ){\t\t\t\n\t\t\t(*this->m_matrix)( id(0,alpha_g), id(0,alpha_g) ) = 1.;\t\t\t\n\t\t}\n\t\telse{\n\t\t\t(*this->m_matrix)( id(0,alpha_g), id(0,alpha_g) ) = 1.;\n\t\t}\n\t//OIL\n\t\t(*this->m_matrix)( id(0,alpha_o), id(0,alpha_o) ) = 1.;\n\n\t\tif( WITH_MOMENTUM ){\n\t\t\t//MOMENTUM\t\t\t\t\t\t\n\t\t\ts_R_v\t\t   = this->R_v(m_pressure[ CENT ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ CENT ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ CENT ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], 0, 'F');\n\t\t\tR_v_dPP\t\t   = this->R_v(m_pressure[ CENT ]  + delta_PP, m_pressure[ CENT ] + delta_PP, m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ],\n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ CENT ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ CENT ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], 0, 'F');\n\t\t\tR_v_dPE\t\t   = this->R_v(m_pressure[ CENT ], m_pressure[ CENT ], m_pressure[ EAST ] + delta_PE, m_pressure[ EAST+1 ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ CENT ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ CENT ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], 0, 'F');\n            R_v_dPEE\t   = this->R_v(m_pressure[ CENT ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ] + delta_PEE, m_gas_vol_frac[ CENT ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ CENT ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ CENT ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], 0, 'F');\n\t\t\tR_v_dalphaGasP = this->R_v(m_pressure[ CENT ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ CENT ] + delta_alphaGasP, m_gas_vol_frac[ CENT ] + delta_alphaGasP, m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ CENT ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ CENT ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], 0, 'F');\n\t\t\tR_v_dalphaGasE = this->R_v(m_pressure[ CENT ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ] + delta_alphaGasE, m_gas_vol_frac[ EAST+1 ], \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ CENT ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ CENT ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], 0, 'F');\n\t\t\tR_v_dalphaGasEE= this->R_v(m_pressure[ CENT ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ] + delta_alphaGasEE, \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ CENT ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ CENT ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], 0, 'F');\n\t\t\tR_v_dalphaOilP = this->R_v(m_pressure[ CENT ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ CENT ] + delta_alphaOilP, m_oil_vol_frac[ CENT ] + delta_alphaOilP, m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ CENT ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], 0, 'F');\n\t\t\tR_v_dalphaOilE = this->R_v(m_pressure[ CENT ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ CENT ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ] + delta_alphaOilE, m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ CENT ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], 0, 'F');\n\t\t\tR_v_dalphaOilEE= this->R_v(m_pressure[ CENT ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ CENT ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ] + delta_alphaOilEE, m_mean_velocity[ CENT ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], 0, 'F');\n\t\t\tR_v_dvP\t\t   = this->R_v(m_pressure[ CENT ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ CENT ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ CENT ], m_mean_velocity[ CENT ] + delta_vP, m_mean_velocity[ EAST ], 0, 'F');\n\t\t\tR_v_dvE\t\t   = this->R_v(m_pressure[ CENT ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ CENT ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ CENT ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ] + delta_vE, 0, 'F');\n\t\t\t//CENTRAL\t\t\n\t\t\t(*this->m_matrix)( id(0,v), id(0,P) )\t    = (R_v_dPP - s_R_v)/delta_PP;\t\t\n\t\t\t(*this->m_matrix)( id(0,v), id(0,alpha_g) ) = (R_v_dalphaGasP - s_R_v)/delta_alphaGasP;\n\t\t\t(*this->m_matrix)( id(0,v), id(0,alpha_o) ) = (R_v_dalphaOilP - s_R_v)/delta_alphaOilP;\n\t\t\t(*this->m_matrix)( id(0,v), id(0,v) )\t    = (R_v_dvP - s_R_v)/delta_vP;\n\t\t\t//EAST\t\n\t\t\t(*this->m_matrix)( id(0,v), id(0,P) + total_var )\t    = (R_v_dPE - s_R_v)/delta_PE;\n\t\t\t(*this->m_matrix)( id(0,v), id(0,alpha_g) + total_var ) = (R_v_dalphaGasE - s_R_v)/delta_alphaGasE;\n\t\t\t(*this->m_matrix)( id(0,v), id(0,alpha_o) + total_var ) = (R_v_dalphaOilE - s_R_v)/delta_alphaOilE;\n\t\t\t(*this->m_matrix)( id(0,v), id(0,v) + total_var )\t    = (R_v_dvE - s_R_v)/delta_vE;\n\t\t\t(*this->m_source)[ id(0, v) ]\t\t\t\t\t\t    = -s_R_v;\n            //EEAST\t\n            (*this->m_matrix)( id(0,v), id(0,P) + 2*total_var )\t      = (R_v_dPEE - s_R_v)/delta_PEE;\n            (*this->m_matrix)( id(0,v), id(0,alpha_g) + 2*total_var ) = (R_v_dalphaGasEE - s_R_v)/delta_alphaGasEE;\n            (*this->m_matrix)( id(0,v), id(0,alpha_o) + 2*total_var ) = (R_v_dalphaOilEE - s_R_v)/delta_alphaOilEE;\n\t\t}\n\t\telse{\n\t\t\t(*this->m_matrix)( id(0,v), id(0,P) + total_var ) = 1.;\t\t\t\n\t\t}\n\n\t\t\n\n\t\t++CENT;\n\t\t++EAST;\n\t\tuint_type LAST = this->number_of_nodes()-1;\n\t\tfor( uint_type i = 1; i < LAST - 1; ++i )\n\t\t{\n\n\t\t\tdelta_PP\t\t= m_delta[ P ]*m_pressure[ CENT ];\n\t\t\tdelta_alphaGasP\t= m_gas_vol_frac[ CENT ] > 1e-12 ? m_delta[ alpha_g ]*m_gas_vol_frac[ CENT ] : m_delta[ alpha_g ];\n\t\t\tdelta_alphaOilP\t= m_oil_vol_frac[ CENT ] > 1e-12 ? m_delta[ alpha_o ]*m_oil_vol_frac[ CENT ] : m_delta[ alpha_o ];\n\t\t\tdelta_vP\t\t= abs(m_mean_velocity[ CENT ]) > 1e-12 ? m_delta[ v ]*m_mean_velocity[ CENT ] : m_delta[ v ];\n\t\t\t\t\t\t\n\t\t\tdelta_PE\t\t= m_delta[ P ]*m_pressure[ EAST ];\n\t\t\tdelta_alphaGasE\t= m_gas_vol_frac[ EAST ] > 1e-12 ? m_delta[ alpha_g ]*m_gas_vol_frac[ EAST ] : m_delta[ alpha_g ];\n\t\t\tdelta_alphaOilE\t= m_oil_vol_frac[ EAST ] > 1e-12 ? m_delta[ alpha_o ]*m_oil_vol_frac[ EAST ] : m_delta[ alpha_o ];\n\t\t\tdelta_vE\t\t= abs(m_mean_velocity[ EAST ]) > 1e-12 ? m_delta[ v ]*m_mean_velocity[ EAST ] : m_delta[ v ];\n\n            delta_PEE\t\t    = m_delta[ P ]*m_pressure[ EAST+1 ];\n            delta_alphaGasEE\t= m_gas_vol_frac[ EAST+1 ] > 1e-8 ? m_delta[ alpha_g ]*m_gas_vol_frac[ EAST+1 ] : 1e-4*m_delta[ alpha_g ];\n            delta_alphaOilEE\t= m_oil_vol_frac[ EAST+1 ] > 1e-8 ? m_delta[ alpha_o ]*m_oil_vol_frac[ EAST+1 ] : 1e-4*m_delta[ alpha_o ];\n\n\t\t\tdelta_PW\t\t= m_delta[ P ]*m_pressure[ WEST ];\n\t\t\tdelta_alphaGasW\t= m_gas_vol_frac[ WEST ] > 1e-12 ? m_delta[ alpha_g ]*m_gas_vol_frac[ WEST ] : m_delta[ alpha_g ];\n\t\t\tdelta_alphaOilW\t= m_oil_vol_frac[ WEST ] > 1e-12 ? m_delta[ alpha_o ]*m_oil_vol_frac[ WEST ] : m_delta[ alpha_o ];\n\t\t\tdelta_vW\t\t= abs(m_mean_velocity[ WEST ]) > 1e-12 ? m_delta[ v ]*m_mean_velocity[ WEST ] : m_delta[ v ];\n\t\t\t\n\t\t//MIXTURE\n\t\t\ts_R_m\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\tR_m_dPW\t\t   = this->R_m(m_pressure[ WEST ] + delta_PW, m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\tR_m_dPP\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ] + delta_PP, m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\tR_m_dPE\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ] + delta_PE, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\tR_m_dalphaGasW = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ] + delta_alphaGasW, m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\tR_m_dalphaGasP = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ] + delta_alphaGasP, m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\tR_m_dalphaGasE = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ] + delta_alphaGasE,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\tR_m_dalphaOilW = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ] + delta_alphaOilW, m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\tR_m_dalphaOilP = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ] + delta_alphaOilP, m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\tR_m_dalphaOilE = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ] + delta_alphaOilE, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\tR_m_dvW\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ] + delta_vW, m_mean_velocity[ CENT ], i, 'C');\n\t\t\tR_m_dvP\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ] + delta_vP, i, 'C');\n\t\t\t//WEST\t\t\t\n\t\t\t(*this->m_matrix)( id(i,P), id(i,P) - total_var )\t\t= (R_m_dPW - s_R_m)/delta_PW;\n\t\t\t(*this->m_matrix)( id(i,P), id(i,alpha_g) - total_var )\t= (R_m_dalphaGasW - s_R_m)/delta_alphaGasW;\n\t\t\t(*this->m_matrix)( id(i,P), id(i,alpha_o) - total_var )\t= (R_m_dalphaOilW - s_R_m)/delta_alphaOilW;\n\t\t\t(*this->m_matrix)( id(i,P), id(i,v)  - total_var )\t\t= (R_m_dvW - s_R_m)/delta_vW;\n\t\t\t//CENTRAL\t\t\t\n\t\t\t(*this->m_matrix)( id(i,P), id(i,P) )\t\t= (R_m_dPP - s_R_m)/delta_PP;\n\t\t\t(*this->m_matrix)( id(i,P), id(i,alpha_g) )\t= (R_m_dalphaGasP - s_R_m)/delta_alphaGasP;\n\t\t\t(*this->m_matrix)( id(i,P), id(i,alpha_o) )\t= (R_m_dalphaOilP - s_R_m)/delta_alphaOilP;\n\t\t\t(*this->m_matrix)( id(i,P), id(i,v) )\t\t= (R_m_dvP - s_R_m)/delta_vP;\n\t\t\t//EAST\t\t\t\t\t\t\n\t\t\t(*this->m_matrix)( id(i,P), id(i,P) + total_var )\t\t= (R_m_dPE - s_R_m)/delta_PE;\n\t\t\t(*this->m_matrix)( id(i,P), id(i,alpha_g) + total_var )\t= (R_m_dalphaGasE - s_R_m)/delta_alphaGasE;\n\t\t\t(*this->m_matrix)( id(i,P), id(i,alpha_o) + total_var )\t= (R_m_dalphaOilE - s_R_m)/delta_alphaOilE;\n\t\t\t//SOURCE\n\t\t\t(*this->m_source)[ id(i, P) ]\t = -s_R_m;\t\t\n\n\t\t\tif( WITH_GAS ){\n\t\t\t//GAS\n\t\t\t\ts_R_g\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_g_dPW\t\t   = this->R_g(m_pressure[ WEST ] + delta_PW, m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_g_dPP\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ] + delta_PP, m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_g_dPE\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ] + delta_PE, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_g_dalphaGasW = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ] + delta_alphaGasW, m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_g_dalphaGasP = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ] + delta_alphaGasP, m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_g_dalphaGasE = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ] + delta_alphaGasE,  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_g_dalphaOilW = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ] + delta_alphaOilW, m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_g_dalphaOilP = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ] + delta_alphaOilP, m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_g_dalphaOilE = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ] + delta_alphaOilE, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_g_dvW\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ] + delta_vW, m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_g_dvP\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ] + delta_vP, i, 'C');\n\n\t\t\t\t//WEST\t\t\t\n\t\t\t\t(*this->m_matrix)( id(i,alpha_g), id(i,P) - total_var )\t\t\t= (R_g_dPW - s_R_g)/delta_PW;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_g), id(i,alpha_g) - total_var )\t= (R_g_dalphaGasW - s_R_g)/delta_alphaGasW;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_g), id(i,alpha_o) - total_var )\t= (R_g_dalphaOilW - s_R_g)/delta_alphaOilW;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_g), id(i,v) - total_var )\t\t\t= (R_g_dvW - s_R_g)/delta_vW;\n\t\t\t\t//CENTRAL\t\t\t\n\t\t\t\t(*this->m_matrix)( id(i,alpha_g), id(i,P) )\t\t\t= (R_g_dPP - s_R_g)/delta_PP;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_g), id(i,alpha_g) )\t= (R_g_dalphaGasP - s_R_g)/delta_alphaGasP;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_g), id(i,alpha_o) )\t= (R_g_dalphaOilP - s_R_g)/delta_alphaOilP;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_g), id(i,v) )\t\t\t= (R_g_dvP - s_R_g)/delta_vP;\n\t\t\t\t//EAST\t\t\t\t\n\t\t\t\t(*this->m_matrix)( id(i,alpha_g), id(i,P) + total_var )\t\t\t= (R_g_dPE - s_R_g)/delta_PE;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_g), id(i,alpha_g) + total_var )\t= (R_g_dalphaGasE - s_R_g)/delta_alphaGasE;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_g), id(i,alpha_o) + total_var )\t= (R_g_dalphaOilE - s_R_g)/delta_alphaOilE;\n\n\t\t\t\t// SOURCE\n\t\t\t\t(*this->m_source)[ id(i, alpha_g) ] = -s_R_g;\n\t\t\t}\n\t\t\telse{\n\t\t\t\t(*this->m_matrix)( id(i,alpha_g), id(i,alpha_g) ) = 1.;\n\t\t\t}\n\n\t\t\t\n\t\t\t//Oil\n\t\t\t\ts_R_o\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_o_dPW\t\t   = this->R_o(m_pressure[ WEST ] + delta_PW, m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_o_dPP\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ] + delta_PP, m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_o_dPE\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ] + delta_PE, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_o_dalphaGasW = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ] + delta_alphaGasW, m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_o_dalphaGasP = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ] + delta_alphaGasP, m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_o_dalphaGasE = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ] + delta_alphaGasE,  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_o_dalphaOilW = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ] + delta_alphaOilW, m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_o_dalphaOilP = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ] + delta_alphaOilP, m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_o_dalphaOilE = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ] + delta_alphaOilE, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_o_dvW\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ] + delta_vW, m_mean_velocity[ CENT ], i, 'C');\n\t\t\t\tR_o_dvP\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ] + delta_vP, i, 'C');\n\n\t\t\t\t//WEST\t\t\t\n\t\t\t\t(*this->m_matrix)( id(i,alpha_o), id(i,P) - total_var )\t\t\t= (R_o_dPW - s_R_o)/delta_PW;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_o), id(i,alpha_g) - total_var )\t= (R_o_dalphaGasW - s_R_o)/delta_alphaGasW;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_o), id(i,alpha_o) - total_var )\t= (R_o_dalphaOilW - s_R_o)/delta_alphaOilW;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_o), id(i,v) - total_var )\t\t\t= (R_o_dvW - s_R_o)/delta_vW;\n\t\t\t\t//CENTRAL\t\t\t\n\t\t\t\t(*this->m_matrix)( id(i,alpha_o), id(i,P) )\t\t\t= (R_o_dPP - s_R_o)/delta_PP;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_o), id(i,alpha_g) )\t= (R_o_dalphaGasP - s_R_o)/delta_alphaGasP;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_o), id(i,alpha_o) )\t= (R_o_dalphaOilP - s_R_o)/delta_alphaOilP;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_o), id(i,v) )\t\t\t= (R_o_dvP - s_R_o)/delta_vP;\n\t\t\t\t//EAST\t\t\t\t\n\t\t\t\t(*this->m_matrix)( id(i,alpha_o), id(i,P) + total_var )\t\t\t= (R_o_dPE - s_R_o)/delta_PE;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_o), id(i,alpha_g) + total_var )\t= (R_o_dalphaGasE - s_R_o)/delta_alphaGasE;\n\t\t\t\t(*this->m_matrix)( id(i,alpha_o), id(i,alpha_o) + total_var )\t= (R_o_dalphaOilE - s_R_o)/delta_alphaOilE;\n\n\t\t\t\t// SOURCE\n\t\t\t\t(*this->m_source)[ id(i, alpha_o) ] = -s_R_o;\n\t\t\t\n\n\t\t\tif( WITH_MOMENTUM ){\n                s_R_v\t\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');\n                R_v_dPW\t\t   = this->R_v(m_pressure[ WEST ] + delta_PW, m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ],\n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');              \n                R_v_dPP\t\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ] + delta_PP, m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ],\n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');\n                R_v_dPE\t\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ] + delta_PE, m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');\n                R_v_dPEE\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ] + delta_PEE, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');\n                R_v_dalphaGasW = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ] + delta_alphaGasW, m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');               \n                R_v_dalphaGasP = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ] + delta_alphaGasP, m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');\n                R_v_dalphaGasE = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ] + delta_alphaGasE, m_gas_vol_frac[ EAST+1 ], \n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');\n                R_v_dalphaGasEE= this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ] + delta_alphaGasEE, \n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');\n                R_v_dalphaOilW = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n                    m_oil_vol_frac[ WEST ] + delta_alphaOilW, m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');\n                R_v_dalphaOilP = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ] + delta_alphaOilP, m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');\n                R_v_dalphaOilE = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ] + delta_alphaOilE, m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');\n                R_v_dalphaOilEE= this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ] + delta_alphaOilEE, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');\n                R_v_dvW\t\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ],  \n\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ] + delta_vW, m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], i, 'C');\n                R_v_dvP\t\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ] + delta_vP, m_mean_velocity[ EAST ], i, 'C');\n                R_v_dvE\t\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST+1 ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST+1 ], \n                    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST+1 ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ] + delta_vE, i, 'C');\n\n\t\t\t\t//WEST\t\n                (*this->m_matrix)( id(i,v), id(i,P) - total_var )\t\t    = (R_v_dPW - s_R_v)/delta_PW;\t\n                (*this->m_matrix)( id(i,v), id(i,alpha_g) - total_var )     = (R_v_dalphaGasW - s_R_v)/delta_alphaGasW;\n                (*this->m_matrix)( id(i,v), id(i,alpha_o) - total_var  )    = (R_v_dalphaOilW - s_R_v)/delta_alphaOilW;\n\t\t\t\t(*this->m_matrix)( id(i,v), id(i,v) - total_var )           = (R_v_dvW - s_R_v)/delta_vW;\n\t\t\t\t//CENTRAL\t\t\t\n\t\t\t\t(*this->m_matrix)( id(i,v), id(i,P) )\t\t = (R_v_dPP - s_R_v)/delta_PP;\t\n\t\t\t\t(*this->m_matrix)( id(i,v), id(i,alpha_g) )  = (R_v_dalphaGasP - s_R_v)/delta_alphaGasP;\n\t\t\t\t(*this->m_matrix)( id(i,v), id(i,alpha_o) )  = (R_v_dalphaOilP - s_R_v)/delta_alphaOilP;\n\t\t\t\t(*this->m_matrix)( id(i,v), id(i,v) )\t\t = (R_v_dvP - s_R_v)/delta_vP;\n\t\t\t\t//EAST\t\t\t\t\n\t\t\t\t(*this->m_matrix)( id(i,v), id(i,P) + total_var )\t\t = (R_v_dPE - s_R_v)/delta_PE;\t\n\t\t\t\t(*this->m_matrix)( id(i,v), id(i,alpha_g) + total_var )  = (R_v_dalphaGasE - s_R_v)/delta_alphaGasE;\n\t\t\t\t(*this->m_matrix)( id(i,v), id(i,alpha_o) + total_var )  = (R_v_dalphaOilE - s_R_v)/delta_alphaOilE;\n\t\t\t\t(*this->m_matrix)( id(i,v), id(i,v) + total_var )\t\t = (R_v_dvE - s_R_v)/delta_vE;\n                //EEAST\t\t\t\t\n                (*this->m_matrix)( id(i,v), id(i,P) + 2*total_var )\t\t   = (R_v_dPEE - s_R_v)/delta_PEE;\t\n                (*this->m_matrix)( id(i,v), id(i,alpha_g) + 2*total_var )  = (R_v_dalphaGasEE - s_R_v)/delta_alphaGasEE;\n                (*this->m_matrix)( id(i,v), id(i,alpha_o) + 2*total_var )  = (R_v_dalphaOilEE - s_R_v)/delta_alphaOilEE;\n\t\t\t\t//SOURCE\n\t\t\t\t(*this->m_source)[ id(i, v) ]\t = -s_R_v;\n\t\t\t}\n\t\t\telse{\n\t\t\t\t(*this->m_matrix)( id(i,v), id(i,P) + total_var ) = 1.;\n\t\t\t}\n\t\t\n\t\t\t\t\t\t\n\t\t\t++WEST;\t++CENT;\t++EAST;\n\t\t}\n\n\t\tdelta_PP\t\t= m_delta[ P ]*m_pressure[ CENT ];\n\t\tdelta_alphaGasP\t= m_gas_vol_frac[ CENT ] > 1e-12 ? m_delta[ alpha_g ]*m_gas_vol_frac[ CENT ] : m_delta[ alpha_g ];\n\t\tdelta_alphaOilP\t= m_oil_vol_frac[ CENT ] > 1e-12 ? m_delta[ alpha_o ]*m_oil_vol_frac[ CENT ] : m_delta[ alpha_o ];\n\t\tdelta_vP\t\t= abs(m_mean_velocity[ CENT ]) > 1e-12 ? m_delta[ v ]*m_mean_velocity[ CENT ] : m_delta[ v ];\t\t\t\t\t\n\t\tdelta_PE\t\t= m_delta[ P ]*m_pressure[ EAST ];\n\t\tdelta_alphaGasE\t= m_gas_vol_frac[ EAST ] > 1e-12 ? m_delta[ alpha_g ]*m_gas_vol_frac[ EAST ] : m_delta[ alpha_g ];\n\t\tdelta_alphaOilE\t= m_oil_vol_frac[ EAST ] > 1e-12 ? m_delta[ alpha_o ]*m_oil_vol_frac[ EAST ] : m_delta[ alpha_o ];\n\t\tdelta_vE\t\t= abs(m_mean_velocity[ EAST ]) > 1e-12 ? m_delta[ v ]*m_mean_velocity[ EAST ] : m_delta[ v ];\t\t\t\n\t\tdelta_PW\t\t= m_delta[ P ]*m_pressure[ WEST ];\n\t\tdelta_alphaGasW\t= m_gas_vol_frac[ WEST ] > 1e-12 ? m_delta[ alpha_g ]*m_gas_vol_frac[ WEST ] : m_delta[ alpha_g ];\n\t\tdelta_alphaOilW\t= m_oil_vol_frac[ WEST ] > 1e-12 ? m_delta[ alpha_o ]*m_oil_vol_frac[ WEST ] : m_delta[ alpha_o ];\n\t\tdelta_vW\t\t= abs(m_mean_velocity[ WEST ]) > 1e-12 ? m_delta[ v ]*m_mean_velocity[ WEST ] : m_delta[ v ];\n\t\t\n\t\t\n\t//MIXTURE  \n\t\ts_R_m\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\tR_m_dPW\t\t   = this->R_m(m_pressure[ WEST ] + delta_PW, m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\tR_m_dPP\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ] + delta_PP, m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\tR_m_dPE\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ] + delta_PE, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\tR_m_dalphaGasW = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ] + delta_alphaGasW, m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\tR_m_dalphaGasP = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ] + delta_alphaGasP, m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\tR_m_dalphaGasE = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ] + delta_alphaGasE,  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\tR_m_dalphaOilW = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ] + delta_alphaOilW, m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\tR_m_dalphaOilP = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ] + delta_alphaOilP, m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\tR_m_dalphaOilE = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ] + delta_alphaOilE, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\tR_m_dvW\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ] + delta_vW, m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\tR_m_dvP\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ] + delta_vP, LAST - 1, 'C');\n\t\t//WEST\t\t\t\n\t\t(*this->m_matrix)( id(LAST - 1,P), id(LAST - 1,P) - total_var )\t\t\t= (R_m_dPW - s_R_m)/delta_PW;\n\t\t(*this->m_matrix)( id(LAST - 1,P), id(LAST - 1,alpha_g) - total_var )\t= (R_m_dalphaGasW - s_R_m)/delta_alphaGasW;\n\t\t(*this->m_matrix)( id(LAST - 1,P), id(LAST - 1,alpha_o) - total_var )\t= (R_m_dalphaOilW - s_R_m)/delta_alphaOilW;\n\t\t(*this->m_matrix)( id(LAST - 1,P), id(LAST - 1,v)  - total_var )\t\t= (R_m_dvW - s_R_m)/delta_vW;\n\t\t//CENTRAL\t\t\t\n\t\t(*this->m_matrix)( id(LAST - 1,P), id(LAST - 1,P) )\t\t\t= (R_m_dPP - s_R_m)/delta_PP;\n\t\t(*this->m_matrix)( id(LAST - 1,P), id(LAST - 1,alpha_g) )\t= (R_m_dalphaGasP - s_R_m)/delta_alphaGasP;\n\t\t(*this->m_matrix)( id(LAST - 1,P), id(LAST - 1,alpha_o) )\t= (R_m_dalphaOilP - s_R_m)/delta_alphaOilP;\n\t\t(*this->m_matrix)( id(LAST - 1,P), id(LAST - 1,v) )\t\t\t= (R_m_dvP - s_R_m)/delta_vP;\n\t\t//EAST\t\t\t\t\t\t\n\t\t(*this->m_matrix)( id(LAST - 1,P), id(LAST - 1,P) + total_var )\t\t\t= (R_m_dPE - s_R_m)/delta_PE;\n\t\t(*this->m_matrix)( id(LAST - 1,P), id(LAST - 1,alpha_g) + total_var )\t= (R_m_dalphaGasE - s_R_m)/delta_alphaGasE;\n\t\t(*this->m_matrix)( id(LAST - 1,P), id(LAST - 1,alpha_o) + total_var )\t= (R_m_dalphaOilE - s_R_m)/delta_alphaOilE;\n\t\t//SOURCE\n\t\t(*this->m_source)[ id(LAST - 1, P) ]\t = -s_R_m;\t\t\n\n\t\t\n\t\tif( WITH_GAS ){\n\t\t//GAS\t\n\t\t\ts_R_g\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_g_dPW\t\t   = this->R_g(m_pressure[ WEST ] + delta_PW, m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_g_dPP\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ] + delta_PP, m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_g_dPE\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ] + delta_PE, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_g_dalphaGasW = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ] + delta_alphaGasW, m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_g_dalphaGasP = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ] + delta_alphaGasP, m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_g_dalphaGasE = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ] + delta_alphaGasE,  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_g_dalphaOilW = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ] + delta_alphaOilW, m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_g_dalphaOilP = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ] + delta_alphaOilP, m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_g_dalphaOilE = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ] + delta_alphaOilE, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_g_dvW\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ] + delta_vW, m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_g_dvP\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ] + delta_vP, LAST - 1, 'C');\n\n\t\t\t//WEST\t\t\t\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_g), id(LAST - 1,P) - total_var )\t\t\t= (R_g_dPW - s_R_g)/delta_PW;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_g), id(LAST - 1,alpha_g) - total_var )\t\t= (R_g_dalphaGasW - s_R_g)/delta_alphaGasW;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_g), id(LAST - 1,alpha_o) - total_var )\t\t= (R_g_dalphaOilW - s_R_g)/delta_alphaOilW;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_g), id(LAST - 1,v) - total_var )\t\t\t= (R_g_dvW - s_R_g)/delta_vW;\n\t\t\t//CENTRAL\t\t\t\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_g), id(LAST - 1,P) )\t\t\t= (R_g_dPP - s_R_g)/delta_PP;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_g), id(LAST - 1,alpha_g) )\t\t= (R_g_dalphaGasP - s_R_g)/delta_alphaGasP;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_g), id(LAST - 1,alpha_o) )\t\t= (R_g_dalphaOilP - s_R_g)/delta_alphaOilP;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_g), id(LAST - 1,v) )\t\t\t= (R_g_dvP - s_R_g)/delta_vP;\n\t\t\t//EAST\t\t\t\t\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_g), id(LAST - 1,P) + total_var )\t\t\t= (R_g_dPE - s_R_g)/delta_PE;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_g), id(LAST - 1,alpha_g) + total_var )\t\t= (R_g_dalphaGasE - s_R_g)/delta_alphaGasE;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_g), id(LAST - 1,alpha_o) + total_var )\t\t= (R_g_dalphaOilE - s_R_g)/delta_alphaOilE;\n\n\t\t\t// SOURCE\n\t\t\t(*this->m_source)[ id(LAST - 1, alpha_g) ] = -s_R_g;\n\t\t\t\n\t\t}\n\t\telse{\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_g), id(LAST - 1,alpha_g) ) = 1.;\n\t\t}\n\n\n\t\t//Oil\n\t\t\ts_R_o\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_o_dPW\t\t   = this->R_o(m_pressure[ WEST ] + delta_PW, m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_o_dPP\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ] + delta_PP, m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_o_dPE\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ] + delta_PE, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_o_dalphaGasW = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ] + delta_alphaGasW, m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_o_dalphaGasP = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ] + delta_alphaGasP, m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_o_dalphaGasE = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ] + delta_alphaGasE,  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_o_dalphaOilW = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ] + delta_alphaOilW, m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_o_dalphaOilP = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ] + delta_alphaOilP, m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_o_dalphaOilE = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ] + delta_alphaOilE, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_o_dvW\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ] + delta_vW, m_mean_velocity[ CENT ], LAST - 1, 'C');\n\t\t\tR_o_dvP\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ],  \n\t\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ] + delta_vP, LAST - 1, 'C');\n\n\t\t\t//WEST\t\t\t\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_o), id(LAST - 1,P) - total_var )\t\t\t= (R_o_dPW - s_R_o)/delta_PW;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_o), id(LAST - 1,alpha_g) - total_var )\t\t= (R_o_dalphaGasW - s_R_o)/delta_alphaGasW;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_o), id(LAST - 1,alpha_o) - total_var )\t\t= (R_o_dalphaOilW - s_R_o)/delta_alphaOilW;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_o), id(LAST - 1,v) - total_var )\t\t\t= (R_o_dvW - s_R_o)/delta_vW;\n\t\t\t//CENTRAL\t\t\t\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_o), id(LAST - 1,P) )\t\t\t= (R_o_dPP - s_R_o)/delta_PP;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_o), id(LAST - 1,alpha_g) )\t\t= (R_o_dalphaGasP - s_R_o)/delta_alphaGasP;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_o), id(LAST - 1,alpha_o) )\t\t= (R_o_dalphaOilP - s_R_o)/delta_alphaOilP;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_o), id(LAST - 1,v) )\t\t\t= (R_o_dvP - s_R_o)/delta_vP;\n\t\t\t//EAST\t\t\t\t\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_o), id(LAST - 1,P) + total_var )\t\t\t= (R_o_dPE - s_R_o)/delta_PE;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_o), id(LAST - 1,alpha_g) + total_var )\t\t= (R_o_dalphaGasE - s_R_o)/delta_alphaGasE;\n\t\t\t(*this->m_matrix)( id(LAST - 1,alpha_o), id(LAST - 1,alpha_o) + total_var )\t\t= (R_o_dalphaOilE - s_R_o)/delta_alphaOilE;\n\n\t\t\t// SOURCE\n\t\t\t(*this->m_source)[ id(LAST - 1, alpha_o) ] = -s_R_o;\n\n\t\tif( WITH_MOMENTUM ){\t\t\t\t\n\t\t\t//MOMENTUM\n\n            s_R_v\t\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST ], \n                m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], LAST - 1, 'L');\n            R_v_dPW\t\t   = this->R_v(m_pressure[ WEST ] + delta_PW, m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST ],\n                m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], LAST - 1, 'L');              \n            R_v_dPP\t\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ] + delta_PP, m_pressure[ EAST ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST ],\n                m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], LAST - 1, 'L');\n            R_v_dPE\t\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ] + delta_PE, m_pressure[ EAST ] + delta_PE, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST ], \n                m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], LAST - 1, 'L');\n            R_v_dalphaGasW = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ] + delta_alphaGasW, m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST ], \n                m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], LAST - 1, 'L');               \n            R_v_dalphaGasP = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ] + delta_alphaGasP, m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST ], \n                m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], LAST - 1, 'L');\n            R_v_dalphaGasE = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ] + delta_alphaGasE, m_gas_vol_frac[ EAST ] + delta_alphaGasE, \n                m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], LAST - 1, 'L');\n            R_v_dalphaOilW = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST ], \n                m_oil_vol_frac[ WEST ] + delta_alphaOilW, m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], LAST - 1, 'L');\n            R_v_dalphaOilP = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST ], \n                m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ] + delta_alphaOilP, m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], LAST - 1, 'L');\n            R_v_dalphaOilE = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST ], \n                m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ] + delta_alphaOilE, m_oil_vol_frac[ EAST ] + delta_alphaOilE, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], LAST - 1, 'L');\n            R_v_dvW\t\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST ],  \n                m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ] + delta_vW, m_mean_velocity[ CENT ], m_mean_velocity[ EAST ], LAST - 1, 'L');\n            R_v_dvP\t\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST ], \n                m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ] + delta_vP, m_mean_velocity[ EAST ], LAST - 1, 'L');\n            R_v_dvE\t\t   = this->R_v(m_pressure[ WEST ], m_pressure[ CENT ], m_pressure[ EAST ], m_pressure[ EAST ], m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], m_gas_vol_frac[ EAST ], m_gas_vol_frac[ EAST ], \n                m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], m_oil_vol_frac[ EAST ], m_oil_vol_frac[ EAST ], m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], m_mean_velocity[ EAST ] + delta_vE, LAST - 1, 'L');\n\n\n\n\t\t\t\t//WEST\n                (*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,P) - total_var )\t\t    = (R_v_dPW - s_R_v)/delta_PW;\t\n                (*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,alpha_g) - total_var )   = (R_v_dalphaGasW - s_R_v)/delta_alphaGasW;\n                (*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,alpha_o) - total_var  )  = (R_v_dalphaOilW - s_R_v)/delta_alphaOilW;\n\t\t\t\t(*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,v) - total_var )         = (R_v_dvW - s_R_v)/delta_vW;\n\t\t\t\t//CENTRAL\t\t\t\n\t\t\t\t(*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,P) )\t\t\t= (R_v_dPP - s_R_v)/delta_PP;\t\n\t\t\t\t(*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,alpha_g) )   = (R_v_dalphaGasP - s_R_v)/delta_alphaGasP;\n\t\t\t\t(*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,alpha_o) )   = (R_v_dalphaOilP - s_R_v)/delta_alphaOilP;\n\t\t\t\t(*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,v) )\t\t\t= (R_v_dvP - s_R_v)/delta_vP;\n\t\t\t\t//EAST\t\t\t\t\n\t\t\t\t(*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,P) + total_var )\t\t   = (R_v_dPE - s_R_v)/delta_PE;\t\n\t\t\t\t(*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,alpha_g) + total_var )  = (R_v_dalphaGasE - s_R_v)/delta_alphaGasE;\n\t\t\t\t(*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,alpha_o) + total_var )  = (R_v_dalphaOilE - s_R_v)/delta_alphaOilE;\n\t\t\t\t(*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,v) + total_var )\t\t   = (R_v_dvE - s_R_v)/delta_vE;\n\t\t\t\t//SOURCE\n\t\t\t\t(*this->m_source)[ id(LAST - 1, v) ]\t = -s_R_v;\t\t\t\t\n\t\t\t}\n\t\t\telse{\n\t\t\t\t(*this->m_matrix)( id(LAST - 1,v), id(LAST - 1,P) + total_var ) = 1.;\n\t\t\t}\n\t\n\t\n\t\t\n\n\t\t++WEST;\t++CENT;\n\n\t\tdelta_PP\t\t= m_delta[ P ]*m_pressure[ CENT ];\n\t\tdelta_alphaGasP\t= m_gas_vol_frac[ CENT ] > 1e-12 ? m_delta[ alpha_g ]*m_gas_vol_frac[ CENT ] : m_delta[ alpha_g ];\n\t\tdelta_alphaOilP\t= m_oil_vol_frac[ CENT ] > 1e-12 ? m_delta[ alpha_o ]*m_oil_vol_frac[ CENT ] : m_delta[ alpha_o ];\n\t\tdelta_vP\t\t= abs(m_mean_velocity[ CENT ]) > 1e-12 ? m_delta[ v ]*m_mean_velocity[ CENT ] : m_delta[ v ];\t\t\t\t\t\n\t\t\n\t\t\t\n\t\tdelta_PW\t\t= m_delta[ P ]*m_pressure[ WEST ];\n\t\tdelta_alphaGasW\t= m_gas_vol_frac[ WEST ] > 1e-12 ? m_delta[ alpha_g ]*m_gas_vol_frac[ WEST ] : m_delta[ alpha_g ];\n\t\tdelta_alphaOilW\t= m_oil_vol_frac[ WEST ] > 1e-12 ? m_delta[ alpha_o ]*m_oil_vol_frac[ WEST ] : m_delta[ alpha_o ];\n\t\tdelta_vW\t\t= abs(m_mean_velocity[ WEST ]) > 1e-12 ? m_delta[ v ]*m_mean_velocity[ WEST ] : m_delta[ v ];\n\t\t\n\n\t\t//MIXTURE\t\t\t\t\n\t\t\ts_R_m\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_m_dPW\t\t   = this->R_m(m_pressure[ WEST ] + delta_PW, m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_m_dPP\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ] + delta_PP, 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_m_dalphaGasW = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ] + delta_alphaGasW, m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_m_dalphaGasP = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ] + delta_alphaGasP, 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_m_dalphaOilW = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ] + delta_alphaOilW, m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_m_dalphaOilP = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ] + delta_alphaOilP, 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_m_dvW\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ] + delta_vW, m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_m_dvP\t\t   = this->R_m(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ] + delta_vP, LAST, 'L');\n\t\t\t//WEST\t\t\t\n\t\t\t(*this->m_matrix)( id(LAST,P), id(LAST,P) - total_var )\t\t\t= (R_m_dPW - s_R_m)/delta_PW;\n\t\t\t(*this->m_matrix)( id(LAST,P), id(LAST,alpha_g) - total_var )\t= (R_m_dalphaGasW - s_R_m)/delta_alphaGasW;\n\t\t\t(*this->m_matrix)( id(LAST,P), id(LAST,alpha_o) - total_var )\t= (R_m_dalphaOilW - s_R_m)/delta_alphaOilW;\n\t\t\t(*this->m_matrix)( id(LAST,P), id(LAST,v)  - total_var )\t\t= (R_m_dvW - s_R_m)/delta_vW;\n\t\t\t//CENTRAL\t\t\t\t\t\n\t\t\t(*this->m_matrix)( id(LAST,P), id(LAST,P) )\t\t\t= (R_m_dPP - s_R_m)/delta_PP;\n\t\t\t(*this->m_matrix)( id(LAST,P), id(LAST,alpha_g) )\t= (R_m_dalphaGasP - s_R_m)/delta_alphaGasP;\n\t\t\t(*this->m_matrix)( id(LAST,P), id(LAST,alpha_o) )\t= (R_m_dalphaOilP - s_R_m)/delta_alphaOilP;\n\t\t\t(*this->m_matrix)( id(LAST,P), id(LAST,v) )\t\t\t= (R_m_dvP - s_R_m)/delta_vP;\n\t\t\t// SOURCE\n\t\t\t(*this->m_source)[ id(LAST, P) ]\t = -s_R_m;\t\t\t\n\t\t\t\n\t\t\n\t\tif( WITH_GAS ){\n\t\t//GAS\t\n\t\t\ts_R_g\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_g_dPW\t\t   = this->R_g(m_pressure[ WEST ] + delta_PW, m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_g_dPP\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ] + delta_PP, 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_g_dalphaGasW = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ] + delta_alphaGasW, m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_g_dalphaGasP = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ] + delta_alphaGasP, 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_g_dalphaOilW = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ] + delta_alphaOilW, m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_g_dalphaOilP = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ] + delta_alphaOilP, 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_g_dvW\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t       m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ] + delta_vW, m_mean_velocity[ CENT ], LAST, 'L');\n\t\t\tR_g_dvP\t\t   = this->R_g(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\t   m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ] + delta_vP, LAST, 'L');\n\n\t\t\t\n\t\t\t//WEST\t\t\n\t\t\t(*this->m_matrix)( id(LAST,alpha_g), id(LAST,P) - total_var )\t    = (R_g_dPW - s_R_g)/delta_PW;\n\t\t\t(*this->m_matrix)( id(LAST,alpha_g), id(LAST,alpha_g) - total_var ) = (R_g_dalphaGasW - s_R_g)/delta_alphaGasW;\n\t\t\t(*this->m_matrix)( id(LAST,alpha_g), id(LAST,alpha_o) - total_var ) = (R_g_dalphaOilW - s_R_g)/delta_alphaOilW;\n\t\t\t(*this->m_matrix)( id(LAST,alpha_g), id(LAST,v) - total_var )\t    = (R_g_dvW - s_R_g)/delta_vW;\n\t\t\t//CENTRAL\t\t\n\t\t\t(*this->m_matrix)( id(LAST,alpha_g), id(LAST,P) )\t    = (R_g_dPP - s_R_g)/delta_PP;\n\t\t\t(*this->m_matrix)( id(LAST,alpha_g), id(LAST,alpha_g) ) = (R_g_dalphaGasP - s_R_g)/delta_alphaGasP;\t\n\t\t\t(*this->m_matrix)( id(LAST,alpha_g), id(LAST,alpha_o) ) = (R_g_dalphaOilP - s_R_g)/delta_alphaOilP;\t\n\t\t\t(*this->m_matrix)( id(LAST,alpha_g), id(LAST,v) )\t    = (R_g_dvP - s_R_g)/delta_vP;\n\t\t\t// SOURCE\n\t\t\t(*this->m_source)[ id(LAST, alpha_g) ] = -s_R_g;\t\t\t\n\n\t\t}\n\t\telse{\n\t\t\t(*this->m_matrix)( id(LAST,alpha_g), id(LAST,alpha_g) ) = 1.;\n\t\t}\t\t\n       \n\t\ts_R_o\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\tR_o_dPW\t\t   = this->R_o(m_pressure[ WEST ] + delta_PW, m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\tR_o_dPP\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ] + delta_PP, 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\tR_o_dalphaGasW = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ] + delta_alphaGasW, m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\tR_o_dalphaGasP = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ] + delta_alphaGasP, 0,  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\tR_o_dalphaOilW = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ] + delta_alphaOilW, m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\tR_o_dalphaOilP = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ] + delta_alphaOilP, 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ], LAST, 'L');\n\t\tR_o_dvW\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t    m_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ] + delta_vW, m_mean_velocity[ CENT ], LAST, 'L');\n\t\tR_o_dvP\t\t   = this->R_o(m_pressure[ WEST ], m_pressure[ CENT ], 0, m_gas_vol_frac[ WEST ], m_gas_vol_frac[ CENT ], 0,  \n\t\t\t\t\t\t\t\t\tm_oil_vol_frac[ WEST ], m_oil_vol_frac[ CENT ], 0, m_mean_velocity[ WEST ], m_mean_velocity[ CENT ] + delta_vP, LAST, 'L');\n\n\t\t\t\n\t\t//WEST\t\t\n\t\t(*this->m_matrix)( id(LAST,alpha_o), id(LAST,P) - total_var )\t    = (R_o_dPW - s_R_o)/delta_PW;\n\t\t(*this->m_matrix)( id(LAST,alpha_o), id(LAST,alpha_g) - total_var ) = (R_o_dalphaGasW - s_R_o)/delta_alphaGasW;\n\t\t(*this->m_matrix)( id(LAST,alpha_o), id(LAST,alpha_o) - total_var ) = (R_o_dalphaOilW - s_R_o)/delta_alphaOilW;\n\t\t(*this->m_matrix)( id(LAST,alpha_o), id(LAST,v) - total_var )\t    = (R_o_dvW - s_R_o)/delta_vW;\n\t\t//CENTRAL\t\t\n\t\t(*this->m_matrix)( id(LAST,alpha_o), id(LAST,P) )\t    = (R_o_dPP - s_R_o)/delta_PP;\n\t\t(*this->m_matrix)( id(LAST,alpha_o), id(LAST,alpha_g) ) = (R_o_dalphaGasP - s_R_o)/delta_alphaGasP;\t\n\t\t(*this->m_matrix)( id(LAST,alpha_o), id(LAST,alpha_o) ) = (R_o_dalphaOilP - s_R_o)/delta_alphaOilP;\t\n\t\t(*this->m_matrix)( id(LAST,alpha_o), id(LAST,v) )\t    = (R_o_dvP - s_R_o)/delta_vP;\n\t\t// SOURCE           \n\t\t(*this->m_source)[ id(LAST, alpha_o) ] = -s_R_o;\t\t\t\n\n\n\n\t\t// MOMENTUM\t\t\t\t\t\n\t\t\t(*this->m_matrix)( id(LAST,v), id(LAST,v) )\t   = 1.;\n\t\t\n\t\t\n\t\t\n\t\t\t\n         /* std::ofstream matrixm(\"WellData\\\\Matrixmatlab.dat\");\n            matrixm << std::setprecision(3);\n\t\t\tmatrixm << \"[ \";\n\t\t\tfor( unsigned i =0 ; i<m_matrix->nrows(); ++i )\n\t\t\t{\t\t\t\t\n\t\t\t\tfor( unsigned j =0 ; j < m_matrix->ncols(); ++j )\n\t\t\t\t{\n\t\t\t\t\tmatrixm << \"  \" << (*m_matrix)(i,j) << \"  \";\n\t\t\t\t}\t\t\t\t\n\t\t\t\tmatrixm << \"\\n\";\t\t\t\t\n\t\t\t}\n\t\t\tmatrixm << \" ] \\n\\n\";\n\t\t\tmatrixm << \"[ \";\n\t\t\tfor( unsigned i =0 ; i<m_matrix->nrows(); ++i )\n\t\t\t{\t\t\t\t\n\t\t\t\tmatrixm << (*m_source)[ i ] << \"\\n\";\n\t\t\t}\n\t\t\tmatrixm << \" ] \";*/\n\n\t}\n\n    real_type DriftFluxWell::calculate_new_delta_t_size_diverged_solution(real_type delta_t_old){\n        return 0.5*delta_t_old;\n    }\n\n    real_type DriftFluxWell::calculate_new_delta_t_size_converged_solution(real_type delta_t_old)\n    {\n        real_type delta_t_S;\n\n        real_type delta_S_max;       \n\n        delta_S_max = 0.0;      \n\n        for( int i = 0; i < number_of_nodes(); ++i )\n        {   \n\n            real_type vol_frac_gas_variation = std::fabs( m_gas_vol_frac[i] - m_gas_vol_frac_old[i] );\n\n            real_type vol_frac_oil_variation= std::fabs( m_oil_vol_frac[i] - m_oil_vol_frac_old[i] );\n\n            real_type vol_frac_variation = std::max(vol_frac_gas_variation, vol_frac_oil_variation);\n\n\n            if (vol_frac_variation > delta_S_max) {\n                delta_S_max = vol_frac_variation;\n            }            \n        }\n\n        delta_t_S = delta_t_old * 0.05 / delta_S_max;\n       \n        real_type delta_t = std::min(  m_max_delta_t, std::max( 1e-5, delta_t_S));\n        if( m_current_time + delta_t > m_final_time){\n           delta_t =  m_final_time - m_current_time;\n        }\n        return delta_t;\n\n    }\n\n    void DriftFluxWell::restore_initial_guess(){\n        for( uint_type i = 0; i < number_of_nodes()-1; ++i )\n        {\n            this->m_pressure[ i ]\t\t= m_pressure_old[ i ];\n            this->m_gas_vol_frac[ i ]\t= m_gas_vol_frac_old[ i ];\n            this->m_oil_vol_frac[ i ]\t= m_oil_vol_frac_old[ i ];\n            this->m_mean_velocity[ i ]\t= m_mean_velocity_old[ i ];\n                                           \n            (*this->m_variables)[ total_var*i ]             = 0.0;\n            (*this->m_variables)[ total_var*i + alpha_g ]   = 0.0;\n            (*this->m_variables)[ total_var*i + alpha_o ]   = 0.0;\n            (*this->m_variables)[ total_var*i + v ]         = 0.0;\n\n          /*  this->m_water_vol_frac[ i ] = 1.0 - (m_gas_vol_frac[ i ] + m_oil_vol_frac[ i ]);\n\n\n\n            real_type KSI\t   = this->ksi( m_mean_velocity[ i ] );\n            real_type c_P\t   = (0.5+KSI)*m_pressure[ i ] + (0.5-KSI)*m_pressure[ i+1 ];\n            real_type c_alphaG = (0.5+KSI)*m_gas_vol_frac[ i ] + (0.5-KSI)*m_gas_vol_frac[ i+1 ];\n            real_type c_alphaO = (0.5+KSI)*m_oil_vol_frac[ i ] + (0.5-KSI)*m_oil_vol_frac[ i+1 ];\n            real_type c_alphaW = 1.0 - (c_alphaG+ c_alphaO);\n\n            real_type rho  = this->mean_density  ( c_alphaO, c_alphaW, c_alphaG, c_P );\n            real_type rhoL = this->liquid_density(c_alphaO, c_alphaW, c_P);\n            real_type rhoG = this->gas_density   ( c_P );\n            real_type rhoO = this->gas_density   ( c_P );\n            real_type rhoW = this->gas_density   ( c_P );\n\n            real_type mod_Vgj = this->mod_v_drift_flux( m_mean_velocity[ i ], 0.5*(m_gas_vol_frac[ i ]+m_gas_vol_frac[ i+1 ]), 0.5*(m_oil_vol_frac[ i ]+m_oil_vol_frac[ i+1 ]), 0.5*(m_water_vol_frac[ i ] + m_water_vol_frac[ i+1 ]), 0.5*(m_pressure[ i ]+m_pressure[ i+1 ]) );\n            real_type mod_Vow = this->mod_v_drift_flux_ow( m_mean_velocity[ i ], 0.5*(m_gas_vol_frac[ i ]+m_gas_vol_frac[ i+1 ]), 0.5*(m_oil_vol_frac[ i ]+m_oil_vol_frac[ i+1 ]), 0.5*(m_water_vol_frac[ i ] + m_water_vol_frac[ i+1 ]), 0.5*(m_pressure[ i ]+m_pressure[ i+1 ]) );\n\n\n            this->m_gas_velocity[ i ] = m_mean_velocity[ i ] + rhoL/rho*mod_Vgj;\t\t\t\n            real_type liquid_velocity = m_mean_velocity[ i ] - c_alphaG/(1 - c_alphaG + 1.0e-20)*rhoG/rho*mod_Vgj;\t\n\n            this->m_oil_velocity[ i ]   = liquid_velocity + rhoW/rhoL*mod_Vow;\n            this->m_water_velocity[ i ] = liquid_velocity - (c_alphaO/c_alphaW)*(rhoO/rhoL)*mod_Vow;\t\t*/\n\n        }\n\n        unsigned i = number_of_nodes()-1;\n\n        this->m_pressure[ i ]\t\t= m_pressure_old[ i ];\n        this->m_gas_vol_frac[ i ]\t= m_gas_vol_frac_old[ i ];\n        this->m_oil_vol_frac[ i ]\t= m_oil_vol_frac_old[ i ];\n        this->m_mean_velocity[ i ]\t= m_mean_velocity_old[ i ];\n\n        (*this->m_variables)[ total_var*i ]             = 0.0;\n        (*this->m_variables)[ total_var*i + alpha_g ]   = 0.0;\n        (*this->m_variables)[ total_var*i + alpha_o ]   = 0.0;\n        (*this->m_variables)[ total_var*i + v ]         = 0.0;\n\n      /*  this->m_water_vol_frac[ i ] = 1.0 - (m_gas_vol_frac[ i ] + m_oil_vol_frac[ i ]);\n        this->m_gas_velocity[ i ]\t= m_mean_velocity[ i ];\n        this->m_oil_velocity[ i ]   = m_mean_velocity[ i ];\n        this->m_water_velocity[ i ] = m_mean_velocity[ i ];*/\n\n\n\n        // Last volume fraction must be equal\n        this->m_gas_vol_frac[ 0 ] = this->m_gas_vol_frac[ 1 ];\n        this->m_oil_vol_frac[ 0 ] = this->m_oil_vol_frac[ 1 ];\n\n    }\n\n\n\tvoid DriftFluxWell::update_variables()\n\t{\n\t\t\n\t\tfor( uint_type i = 0; i < number_of_nodes()-1; ++i )\n\t\t{\n\t\t\tthis->m_pressure[ i ]\t\t+= (*this->m_variables)[ total_var*i ];\n\t\t\tthis->m_gas_vol_frac[ i ]\t+= (*this->m_variables)[ total_var*i + alpha_g ];\n\t\t\tthis->m_oil_vol_frac[ i ]\t+= (*this->m_variables)[ total_var*i + alpha_o ];\n\t\t\tthis->m_mean_velocity[ i ]\t+= (*this->m_variables)[ total_var*i + v ];\n\n           // (*this->m_variables)[ total_var*i ]             = 0.0;\n           // (*this->m_variables)[ total_var*i + alpha_g ]   = 0.0;\n           // (*this->m_variables)[ total_var*i + alpha_o ]   = 0.0;\n          //  (*this->m_variables)[ total_var*i + v ]         = 0.0;\n\n\t\t\tthis->m_water_vol_frac[ i ] = 1.0 - (m_gas_vol_frac[ i ] + m_oil_vol_frac[ i ]);\n\n\t\t\t\t\t\t\n\t\t\t\n\t\t\treal_type KSI\t   = this->ksi( m_mean_velocity[ i ] );\n\t\t\treal_type c_P\t   = (0.5+KSI)*m_pressure[ i ] + (0.5-KSI)*m_pressure[ i+1 ];\n\t\t\treal_type c_alphaG = (0.5+KSI)*m_gas_vol_frac[ i ] + (0.5-KSI)*m_gas_vol_frac[ i+1 ];\n\t\t\treal_type c_alphaO = (0.5+KSI)*m_oil_vol_frac[ i ] + (0.5-KSI)*m_oil_vol_frac[ i+1 ];\n\t\t\treal_type c_alphaW = 1.0 - (c_alphaG+ c_alphaO);\n\n\t\t\treal_type rho  = this->mean_density  ( c_alphaO, c_alphaW, c_alphaG, c_P );\n\t\t\treal_type rhoL = this->liquid_density(c_alphaO, c_alphaW, c_P);\n\t\t\treal_type rhoG = this->gas_density   ( c_P );\n\t\t\treal_type rhoO = this->gas_density   ( c_P );\n\t\t\treal_type rhoW = this->gas_density   ( c_P );\n\t\t\t\n\t\t\treal_type mod_Vgj = this->mod_v_drift_flux( m_mean_velocity[ i ], 0.5*(m_gas_vol_frac[ i ]+m_gas_vol_frac[ i+1 ]), 0.5*(m_oil_vol_frac[ i ]+m_oil_vol_frac[ i+1 ]), 0.5*(m_water_vol_frac[ i ] + m_water_vol_frac[ i+1 ]), 0.5*(m_pressure[ i ]+m_pressure[ i+1 ]) );\n\t\t\treal_type mod_Vow = this->mod_v_drift_flux_ow( m_mean_velocity[ i ], 0.5*(m_gas_vol_frac[ i ]+m_gas_vol_frac[ i+1 ]), 0.5*(m_oil_vol_frac[ i ]+m_oil_vol_frac[ i+1 ]), 0.5*(m_water_vol_frac[ i ] + m_water_vol_frac[ i+1 ]), 0.5*(m_pressure[ i ]+m_pressure[ i+1 ]) );\n\n\t\t\t\n\t\t\tthis->m_gas_velocity[ i ] = m_mean_velocity[ i ] + rhoL/rho*mod_Vgj;\t\t\t\n\t\t\treal_type liquid_velocity = m_mean_velocity[ i ] - c_alphaG/(1 - c_alphaG + 1.0e-20)*rhoG/rho*mod_Vgj;\t\n\t\t\t\n\t\t\tthis->m_oil_velocity[ i ]   = liquid_velocity + rhoW/rhoL*mod_Vow;\n\t\t\tthis->m_water_velocity[ i ] = liquid_velocity - (c_alphaO/(c_alphaW + 1.0e-20))*(rhoO/rhoL)*mod_Vow;\t\t\n\t\t\t\n\t\t}\n\n\t\tunsigned i = number_of_nodes()-1;\n\n\n\t\tthis->m_pressure[ i ]\t\t+= (*this->m_variables)[ total_var*i ];\n\t\tthis->m_gas_vol_frac[ i ]\t+= (*this->m_variables)[ total_var*i + alpha_g ];\n\t\tthis->m_oil_vol_frac[ i ]\t+= (*this->m_variables)[ total_var*i + alpha_o ];\n\t\tthis->m_mean_velocity[ i ]\t+= (*this->m_variables)[ total_var*i + v ];\n\n      //  (*this->m_variables)[ total_var*i ]             = 0.0;\n      //  (*this->m_variables)[ total_var*i + alpha_g ]   = 0.0;\n      //  (*this->m_variables)[ total_var*i + alpha_o ]   = 0.0;\n     //   (*this->m_variables)[ total_var*i + v ]         = 0.0;\n\n\t\tthis->m_water_vol_frac[ i ] = 1.0 - (m_gas_vol_frac[ i ] + m_oil_vol_frac[ i ]);\n\t\tthis->m_gas_velocity[ i ]\t= m_mean_velocity[ i ];\n\t\tthis->m_oil_velocity[ i ]   = m_mean_velocity[ i ];\n\t\tthis->m_water_velocity[ i ] = m_mean_velocity[ i ];\n\n\t\n\n\t\t// Last volume fraction must be equal\n\t\tthis->m_gas_vol_frac[ 0 ] = this->m_gas_vol_frac[ 1 ];\n\t\tthis->m_oil_vol_frac[ 0 ] = this->m_oil_vol_frac[ 1 ];\n\t\t\n\t}\n\n\t\n\n\tvoid DriftFluxWell::set_boundary_velocity( real_type p_velocity ){\n\t\tthis->m_mean_velocity[ number_of_nodes() - 1 ] = p_velocity;\n\t}\n\n    std::string make_filename( const std::string& basename, int index, const std::string& ext )\n\t{\n        std::ostringstream result;\n\t\tresult << basename << index << ext;\n\t\treturn result.str();\n\t}\n\n    void DriftFluxWell::update_variables_for_new_timestep(){\n        for( uint_type i = 0; i < number_of_nodes(); ++i){\n\n            m_gas_vol_frac_old[ i ]   = m_gas_vol_frac[ i ];\t\t\t\n            m_oil_vol_frac_old[ i ]   = m_oil_vol_frac[ i ];\n            m_water_vol_frac_old[ i ] = m_water_vol_frac[ i ];\n            m_pressure_old[ i ]\t\t  = m_pressure[ i ];\t\t\n            m_mean_velocity_old[ i ]  = m_mean_velocity[ i ];\n\n            m_water_flow[i]->calculate_value_at_time(m_current_time);\n            m_oil_flow[i]->calculate_value_at_time(m_current_time);\n            m_gas_flow[i]->calculate_value_at_time(m_current_time);               \n        }    \n    }                     \n\n\tvoid DriftFluxWell::solve()\n\t{\n        bool check_time = false;\n\t\tm_current_time = 0;\n\n\t\tuint_type FINAL_TIMESTEP = this->m_FINAL_TIMESTEP;\n\n\t\tthis->update_variables_for_new_timestep();\n\t\t\n\t\tthis->set_bottom_pressure( m_HEEL_PRESSURE ); // Pressure at heel is set\n\n        bool log_output_is_active = true;\n\n        std::ofstream log_results_file;\n        if(log_output_is_active)\n        {                           \n            log_results_file.open( \"..\\\\WellData\\\\log_results.txt\" );\n            log_results_file << \"Current time\" << \"\\t\"\n                << \"Newton Iter\"\t<< \"\\t\"\n                << \"Final norm\"     << \"\\n\";\n            log_results_file << std::setprecision(10);\n        }\n\t\t\n\t\tfor(uint_type TIMESTEP = 0; TIMESTEP < FINAL_TIMESTEP; ++TIMESTEP){\n\t\t//\t(*m_water_flow)[ number_of_nodes()-1 ] = (TIMESTEP+1)*dt() > 10.0 ? 1.5 : 1.5*(TIMESTEP+1)*dt()/10;\n\t\t//\t(*m_oil_flow)[ number_of_nodes()-1 ]   = (TIMESTEP+1)*dt() > 10.0 ? 1.5 : 1.5*(TIMESTEP+1)*dt()/10;\n\t\t//\t(*m_gas_flow)[ number_of_nodes()-1 ]   = (TIMESTEP+1)*dt() > 10.0 ? 0.02 : 0.02*(TIMESTEP+1)*dt()/10;\n\t\t\t\n\n\t\t\tif(TIMESTEP){ \n\t\t\t\t// Only enters loop for TIMESTEP > 0                    \n                set_dt( calculate_new_delta_t_size_converged_solution( dt() ) );                 \n\t\t\t\t//for( uint_type i = 0; i < number_of_nodes(); ++i){\n\t\t\t\t//\t//real_type dalpha    = m_gas_vol_frac[ i ]-m_gas_vol_frac_old[ i ];\n\t\t\t\t//\t//real_type dpressure = m_pressure[ i ]-m_pressure_old[ i ];\n\t\t\t\t//\t//real_type dvelocity = m_mean_velocity[ i ]-m_mean_velocity_old[ i ];\t\t\t\t\n\t\t\t\t//\t/*m_gas_vol_frac_old[ i ] = m_gas_vol_frac[ i ];\n\t\t\t\t//\tm_gas_vol_frac[ i ] =  m_gas_vol_frac[ i ] + dalpha;\n\n\t\t\t\t//\tm_oil_vol_frac_old[ i ] = m_oil_vol_frac[ i ];\n\t\t\t\t//\tm_water_vol_frac_old[ i ] = m_water_vol_frac[ i ];\n\n\t\t\t\t//\tm_pressure_old[ i ] = m_pressure[ i ];\n\t\t\t\t//\tm_pressure[ i ]     = m_pressure[ i ] + 0*dpressure;\n\n\t\t\t\t//\tm_mean_velocity_old[ i ] = m_mean_velocity[ i ];\n\t\t\t\t//\tm_mean_velocity[ i ]     = m_mean_velocity[ i ] + 0*dvelocity;*/\n\n\t\t\t\t//\tm_gas_vol_frac_old[ i ] = m_gas_vol_frac[ i ];\t\n\t\t\t\t//\tm_oil_vol_frac_old[ i ] = m_oil_vol_frac[ i ];\n\t\t\t\t//\t//m_water_vol_frac_old[ i ] = m_water_vol_frac[ i ];\n\t\t\t\t//\tm_pressure_old[ i ] = m_pressure[ i ];\t\n\t\t\t\t//\tm_mean_velocity_old[ i ] = m_mean_velocity[ i ];\n\t\t\t\t//\n\t\t\t\t//}\n\n                this->update_variables_for_new_timestep();\n\n                \n\t\t\t}\n\t\t\t\n\t\t\tuint_type r = 0;\n            std::queue<real_type> norm_history;\n\t\t\treal_type norma;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tstatic Timer timer;\n                //timer.enable_print_time();\n\n                timer.start();                   \n\t\t\t\tthis->compute_Jacobian();\n                timer.stop();\n                timer.print(\"\\njacobian time = \");\n\n\t\t\t\ttimer.start();\n\t\t\t\tGMRES_Solve( *m_matrix, *m_variables, *m_source );\n\t\t\t\t\n\t\t\t\ttimer.stop();\n                timer.print(\"\\nsolver time = \");\n\t\t\t\t\t\t\t\t\n\t\t\t\tthis->update_variables();\t\t\t\n\t\t\t\t\n                std::cout << std::setprecision(10);\n\t\t\t\t\n\t\t\t\tnorma = itl::two_norm(*m_source);\t\t\t\t\n                std::cout << \"\\n----norma residuo: \" << norma << \"-----\\n\";\n\t\t\t\t\n                norm_history.push(norma);\n                if(r > 3){\n                    norm_history.pop();\n                }\n\t\t\t\t/*for( uint_type i = 0; i < number_of_nodes()-1; ++i ){\n\t\t\t\t\tcout << setprecision(10);\t\t\t\t\n\t\t\t\t\tcout << \"pressure[ \"<< i <<\" ] = \" << this->m_pressure[ i ] <<\"\\t\";\n\t\t\t\t\tif( i == 0)\n\t\t\t\t\t\tcout <<\"\\t\";\n\t\t\t\t\tcout << \"Gas_vol_frac[ \"<< i <<\" ] = \" << this->m_gas_vol_frac[ i ] <<\"\\t\";\n\t\t\t\t\tcout << \"Oil_vol_frac[ \"<< i <<\" ] = \" << this->m_oil_vol_frac[ i ] <<\"\\t\";\t\n\t\t\t\t\tif( i == number_of_nodes() - 1)\n\t\t\t\t\t\tcout <<\"\\t\";\t\t\t\t\n\t\t\t\t\tcout << \"mean_velocity[ \"<< i <<\" ] = \" << this->m_mean_velocity[ i ] << \"\\n\";\t\t\t\n\n\t\t\t\t}*/\n                //if( norm_history.front() < norm_history.back() && r > 3)    m_convergence_status = true;\n                m_convergence_status = false;\n                if(norma > this->NEWTON_CRIT && r > 50 || m_convergence_status){\n                    set_dt( calculate_new_delta_t_size_diverged_solution( dt() ) ); \n                    std::cout << \"\\n********* Breaking timestep = \" << dt();\n                    int r_inner = 0;\n                    real_type new_norm = 0.0;\n                    std::queue<real_type> new_norm_history;\n                    restore_initial_guess();\n                    do{                                \n                        // Restart solution with half timestep \n                        timer.start();\n                        this->compute_Jacobian();\t\t\t\t\t\t\t\n                        timer.stop();\n                        timer.print(\"\\njacobian time = \");\n\n                        timer.start();\n                        GMRES_Solve( *m_matrix, *m_variables, *m_source );\n\n                        timer.stop();\n                        timer.print(\"\\nsolver time = \");\n                       \n                        this->update_variables();\t\t\t\n\n                        std::cout << std::setprecision(10);\n\n                        new_norm = itl::two_norm(*m_source);\t\t\t\t\n                        std::cout << \"\\n----norma residuo: \" << new_norm << \"-----\\n\";\n\n                        new_norm_history.push(new_norm);\n                        if(r_inner > 2){\n                            new_norm_history.pop();\n                        }\n                       // if( new_norm > norma && r_inner > 10) break;\n                        if( new_norm_history.front() < new_norm_history.back() && r_inner > 2) {\n                           // restore_initial_guess();\n                            break;\n                        }\n                        ++r_inner;                                             \n                    }while(new_norm > this->NEWTON_CRIT && r_inner < 30);\n                    std::cout << \"\\n********* Returning to normal loop\";\n                }\n\n\t\t\t\t\n\t\t\t\t++r;\n\t\t\t}while(norma > this->NEWTON_CRIT && r < 1000);\n\n            m_current_time += this->dt();\n            std::cout << \"TIME: \" << m_current_time << \" seconds\\n\\n\\n\"; \n                                           \n            if(log_output_is_active)\n            {          \t\t\n                log_results_file << m_current_time\t<< \"\\t\"\n                    << r\t    << \"\\t\"\n                    << norma\t<< \"\\n\";                                 \n            }\n\n            /*double transient_norm = 0;\n            double transient_norm_P = 0;\n            double transient_norm_alphaG = 0;\n            double transient_norm_alphaO = 0;\n            double transient_norm_v = 0;\n            for(unsigned i = 0; i < m_nnodes; ++i){\n                transient_norm_P += (m_pressure_old[i] - m_pressure[i])*(m_pressure_old[i] - m_pressure[i]);\n                transient_norm_alphaG += (m_gas_vol_frac_old[i] - m_gas_vol_frac[i])*(m_gas_vol_frac_old[i] - m_gas_vol_frac[i]);\t\n                transient_norm_alphaO += (m_oil_vol_frac_old[i] - m_oil_vol_frac[i])*(m_oil_vol_frac_old[i] - m_oil_vol_frac[i]);\n                transient_norm_v += (m_mean_velocity_old[i] - m_mean_velocity[i])*(m_mean_velocity_old[i] - m_mean_velocity[i]);\n            }\n            transient_norm_P = sqrt(transient_norm_P);\n            transient_norm_alphaG = sqrt(transient_norm_alphaG);\n            transient_norm_alphaO = sqrt(transient_norm_alphaO);\n            transient_norm_v = sqrt(transient_norm_v);\n            transient_norm = 0.0*transient_norm_P + transient_norm_alphaG + transient_norm_alphaO + 0.0*transient_norm_v;\n            transient_norm = transient_norm/dt();*/\n\n            //if(transient_norm < 1e-6 && TIMESTEP > 0 || TIMESTEP == FINAL_TIMESTEP-1 || abs(m_current_time - m_final_time) < 1.0e-8 )\n            if(TIMESTEP == FINAL_TIMESTEP-1 || abs(m_current_time - m_final_time) < 1.0e-8 )\n            {\n                std::ofstream results_file;\n                //results_file.open( make_filename( \"results\", TIMESTEP, \".dat\" ).c_str() );\n                results_file.open( \"..\\\\WellData\\\\results.txt\" );\n                results_file << \"Pressure [Pa]\"\t<< \"\\t\"\n                    << \"Gas Volume Fraction [-]\"    << \"\\t\"\n                    << \"Oil Volume Fraction [-]\"\t<< \"\\t\"\n                    << \"Water Volume Fraction [-]\"\t<< \"\\t\"\n                    << \"Mixture Velocity [m/s]\"\t    << \"\\t\"\n                    << \"Gas Velocity [m/s]\"\t        << \"\\t\"\n                    << \"Oil Velocity [m/s]\"\t        << \"\\t\"\n                    << \"Water Velocity [m/s]\"\t    << \"\\n\";\n                for( uint_type i = 0; i < number_of_nodes(); ++i )\n                {\n                    results_file << std::setprecision(10);\t\t\t\t\n                    results_file << this->m_pressure      [ i ]\t<< \"\\t\"\n                        << this->m_gas_vol_frac  [ i ]\t<< \"\\t\"\n                        << this->m_oil_vol_frac  [ i ]\t<< \"\\t\"\n                        << this->m_water_vol_frac[ i ]\t<< \"\\t\"\n                        << this->m_mean_velocity [ i ]\t<< \"\\t\"\n                        << this->m_gas_velocity  [ i ]\t<< \"\\t\"\n                        << this->m_oil_velocity  [ i ]\t<< \"\\t\"\n                        << this->m_water_velocity[ i ]\t<< \"\\n\";\t\t\t\t\t\t\t\t\t\t\t\t\n                }\n                results_file.close();\n                break;\n            }\n\t\t}\n\n        if(log_output_is_active)\n        {  \n            log_results_file.close();                     \n        }\n\t}\n\n\n\n\n    void DriftFluxWell::solve(vector_type& p_pressure)\n\t{\n\t\tm_current_time = 0;\n        static int STEPS = 0;\n        m_total_production[OilPhase]    = 0.0;\n        m_total_production[GasPhase]    = 0.0;\n        m_total_production[WaterPhase]  = 0.0;\n\n\t\tuint_type FINAL_TIMESTEP = this->m_FINAL_TIMESTEP;\n\t\tfor( uint_type i = 0; i < number_of_nodes(); ++i){\n\t\t\t\n\t\t\tm_gas_vol_frac_old[ i ]   = m_gas_vol_frac[ i ];\t\t\t\n\t\t\tm_oil_vol_frac_old[ i ]   = m_oil_vol_frac[ i ];\n\t\t\tm_water_vol_frac_old[ i ] = m_water_vol_frac[ i ];\n\t\t\tm_pressure_old[ i ]\t\t  = m_pressure[ i ];\t\t\n\t\t\tm_mean_velocity_old[ i ]  = m_mean_velocity[ i ];\n\t\t\t\n\t\t}\n\t\t\n\t\tthis->set_bottom_pressure( m_HEEL_PRESSURE ); // Pressure at heel is set\n\t\t\n\t\tfor(uint_type TIMESTEP = 0; TIMESTEP < FINAL_TIMESTEP; ++TIMESTEP){\n\t\t\tif(TIMESTEP){ \n\t\t\t\t// Only enters loop for TIMESTEP > 0\n\n\t\t\t\tfor( uint_type i = 0; i < number_of_nodes(); ++i){\n\t\t\t\t\tm_gas_vol_frac_old[ i ] = m_gas_vol_frac[ i ];\t\n\t\t\t\t\tm_oil_vol_frac_old[ i ] = m_oil_vol_frac[ i ];\t\t\t\t\t\n\t\t\t\t\tm_pressure_old[ i ] = m_pressure[ i ];\t\n\t\t\t\t\tm_mean_velocity_old[ i ] = m_mean_velocity[ i ]; \t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tuint_type r = 0;\n\t\t\treal_type norma;\n\t\t\tdo\n\t\t\t{\n\t\t\t\t\n\t\t\t\tthis->compute_Jacobian();\n\t\t\t\tGMRES_Solve( *m_matrix, *m_variables, *m_source ); \n\t\t\t\tthis->update_variables();\t\t\t\n\t\t\t\t\n\t\t\t\t//cout << setprecision(10);   \t\t\t\t\n\t\t\t\tnorma = itl::two_norm(*m_source);\t\t\t\t\n\t\t\t\t//cout << \"\\n----norma residuo: \" << norma << \"-----\\n\";\n\t\t\t\t\n\t\t\t\t/*for( uint_type i = 0; i < number_of_nodes()-1; ++i ){\n\t\t\t\t\tcout << setprecision(10);\t\t\t\t\n\t\t\t\t\tcout << \"pressure[ \"<< i <<\" ] = \" << this->m_pressure[ i ] <<\"\\t\";\n\t\t\t\t\tif( i == 0)\n\t\t\t\t\t\tcout <<\"\\t\";\n\t\t\t\t\tcout << \"Gas_vol_frac[ \"<< i <<\" ] = \" << this->m_gas_vol_frac[ i ] <<\"\\t\";\n\t\t\t\t\tcout << \"Oil_vol_frac[ \"<< i <<\" ] = \" << this->m_oil_vol_frac[ i ] <<\"\\t\";\t\n\t\t\t\t\tif( i == number_of_nodes() - 1)\n\t\t\t\t\t\tcout <<\"\\t\";\t\t\t\t\n\t\t\t\t\tcout << \"mean_velocity[ \"<< i <<\" ] = \" << this->m_mean_velocity[ i ] << \"\\n\";\t\t\t\n\n\t\t\t\t}*/\n\n\t\t\t\t\n\t\t\t\t++r;\n\t\t\t}while(norma > this->NEWTON_CRIT && r < 100); \n\t\t\t\n\t\t\tm_current_time += this->dt();\n            double transient_norm_pressure      = 0.0;\n            double transient_norm_gas_vol_frac  = 0.0;\n            double transient_norm_oil_vol_frac  = 0.0;\n            double transient_norm_velocity      = 0.0;\n            for(unsigned i = 0; i < m_nnodes; ++i){\n                transient_norm_pressure     += (m_pressure_old[i] - m_pressure[i])*(m_pressure_old[i] - m_pressure[i]);\n                transient_norm_gas_vol_frac += (m_gas_vol_frac_old[i] - m_gas_vol_frac[i])*(m_gas_vol_frac_old[i] - m_gas_vol_frac[i]);\t\n                transient_norm_oil_vol_frac += (m_oil_vol_frac_old[i] - m_oil_vol_frac[i])*(m_oil_vol_frac_old[i] - m_oil_vol_frac[i]);\n                transient_norm_velocity     += (m_mean_velocity_old[i] - m_mean_velocity[i])*(m_mean_velocity_old[i] - m_mean_velocity[i]);\t\n            }\n            double transient_norm = sqrt( transient_norm_pressure    ) \n                + sqrt( transient_norm_gas_vol_frac)\n                + sqrt( transient_norm_oil_vol_frac)\n                + sqrt( transient_norm_velocity    );\n\n\n\t\t\t\n            for( uint_type i = 0; i < number_of_nodes(); ++i){\n                m_gas_vol_frac_old[ i ] = m_gas_vol_frac[ i ];\t\n                m_oil_vol_frac_old[ i ] = m_oil_vol_frac[ i ];\t\t\t\t\t\n                m_pressure_old[ i ] = m_pressure[ i ];\t\n                m_mean_velocity_old[ i ] = m_mean_velocity[ i ]; \t\n            }\n\n            m_total_production[OilPhase]    += m_oil_vol_frac[0]  *abs(m_oil_velocity[0])  *area()*dt();\n            m_total_production[GasPhase]    += m_gas_vol_frac[0]  *abs(m_gas_velocity[0])  *area()*dt();\n            m_total_production[WaterPhase]  += m_water_vol_frac[0]*abs(m_water_velocity[0])*area()*dt();\n            /*cout << \"------> well transient volume production: \\n\" \n                 << \"\\t\\tPhaseWater: \"<< m_total_production[WaterPhase]  << \" m^3\\n\"\n                 << \"\\t\\tPhaseOil: \"<< m_total_production[OilPhase]      << \" m^3\\n\"\n                 << \"\\t\\tPhaseGas: \"<< m_total_production[GasPhase]      << \" m^3\\n\";*/\n           \n\n            if(transient_norm < 1.0e-3 && TIMESTEP > 0)\n            {\n                std::cout << \"------> well transient TIME: \" << m_current_time << \" seconds\\n\";\n                std::cout << \"----WELL---- >>>TRANSIENT NORM = \" << transient_norm << \"\\n\";\n                std::cout << \"total inflow: \\tOIL-> \" << m_oil_vol_frac[0]  *abs(m_oil_velocity[0])  *area() << \"\\n\" \n                    << \"total inflow: \\tGAS-> \" << m_gas_vol_frac[0]  *abs(m_gas_velocity[0])  *area() << \"\\n\" \n                    << \"total inflow: \\tWATER-> \" << m_water_vol_frac[0]*abs(m_water_velocity[0])*area() << \"\\n\";                 \n                std::ofstream results_file;\n                results_file.open( make_filename( \"WellData\\\\results\", STEPS, \".dat\" ).c_str() );                 \n                for( uint_type i = 0; i < number_of_nodes(); ++i )\n                {\n                    results_file << std::setprecision(10);\t\t\t\t\n                    results_file << this->m_pressure      [ i ]\t<< \"\\t\"\n                        << this->m_gas_vol_frac  [ i ]\t<< \"\\t\"\n                        << this->m_oil_vol_frac  [ i ]\t<< \"\\t\"\n                        << this->m_water_vol_frac[ i ]\t<< \"\\t\"\n                        << this->m_mean_velocity [ i ]\t<< \"\\t\"\n                        << this->m_gas_velocity  [ i ]\t<< \"\\t\"\n                        << this->m_oil_velocity  [ i ]\t<< \"\\t\"\n                        << this->m_water_velocity[ i ]\t<< \"\\n\";\t\t\t\t\t\t\t\t\t\t\t\t\n                }\n                results_file.close();\n                ++STEPS;\n                break;\n            }\n\t\t}\n        for(uint_type i = 1; i < this->m_pressure.size(); ++i){\n            p_pressure[i-1] = this->m_pressure[i];\n        }\n        // TODO:\n        // Calculate total volume of a phase 'p' produced:\n        // something like\n        // \n        // During transient time:\n        // Total_vol_phase_p += m_vol_frac_p * velocity_p * Area * dt();\n        // After reaching steady state:\n        // TIME = Reservoir_timestep - total_time_well;\n        // Total_vol_phase_p += m_vol_frac_p * velocity_p * Area * TIME;\n        //real_type m_reservoir_timestep = 8640.0;\n       // m_total_production[OilPhase]    += m_oil_vol_frac[0]  *abs(m_oil_velocity[0])  *area()*(m_reservoir_timestep-time);\n        //m_total_production[GasPhase]    += m_gas_vol_frac[0]  *abs(m_gas_velocity[0])  *area()*(m_reservoir_timestep-time);\n       // m_total_production[WaterPhase]  += m_water_vol_frac[0]*abs(m_water_velocity[0])*area()*(m_reservoir_timestep-time);\n       /* cout << \"-----------> well TOTAL volume production: \\n\" \n            << \"\\t\\t---PhaseWater: \"<< m_total_production[WaterPhase]  << \" m^3\\n\"\n            << \"\\t\\t---PhaseOil: \"<< m_total_production[OilPhase]      << \" m^3\\n\"\n            << \"\\t\\t---PhaseGas: \"<< m_total_production[GasPhase]      << \" m^3\\n\";*/\n\t}\n\n\n\n\n// Namespace =======================================================================================\n} // namespace WellSimulator", "meta": {"hexsha": "8ef2518a3a82ed8d3929f4cc6ba541c960e2cedc", "size": 202601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WellSimulator/WellSim/DriftFluxWell.cpp", "max_stars_repo_name": "arthursoprano/welldrift", "max_stars_repo_head_hexsha": "57fe6c2f5a5caea18c5e29fb1b17f6f29a59a98e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-14T21:46:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-14T21:46:21.000Z", "max_issues_repo_path": "WellSimulator/WellSim/DriftFluxWell.cpp", "max_issues_repo_name": "arthursoprano/welldrift", "max_issues_repo_head_hexsha": "57fe6c2f5a5caea18c5e29fb1b17f6f29a59a98e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WellSimulator/WellSim/DriftFluxWell.cpp", "max_forks_repo_name": "arthursoprano/welldrift", "max_forks_repo_head_hexsha": "57fe6c2f5a5caea18c5e29fb1b17f6f29a59a98e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-14T02:31:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T18:29:06.000Z", "avg_line_length": 60.3518022043, "max_line_length": 276, "alphanum_fraction": 0.6261617662, "num_tokens": 65030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.4174257078405764}}
{"text": "/***************************************************************************\n *   Copyright (C) 2007 by Reed A. Cartwright                              *\n *   reed@scit.us                                                          *\n *                                                                         *\n *   Permission is hereby granted, free of charge, to any person obtaining *\n *   a copy of this software and associated documentation files (the       *\n *   \"Software\"), to deal in the Software without restriction, including   *\n *   without limitation the rights to use, copy, modify, merge, publish,   *\n *   distribute, sublicense, and/or sell copies of the Software, and to    *\n *   permit persons to whom the Software is furnished to do so, subject to *\n *   the following conditions:                                             *\n *                                                                         *\n *   The above copyright notice and this permission notice shall be        *\n *   included in all copies or substantial portions of the Software.       *\n *                                                                         *\n *   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,       *\n *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    *\n *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\n *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR     *\n *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *\n *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *\n *   OTHER DEALINGS IN THE SOFTWARE.                                       *\n ***************************************************************************/\n\n#include <boost/math/special_functions/zeta.hpp>\n\n#include \"models.h\"\n\ninline double zeta(double z) { return boost::math::zeta<double>(z); }\n\nextern const int g_pupy[] = {0,1,0,1,-1};\nextern const int g_atgc[] = {0,1,1,0,-1};\n\nconst model_k2p_zeta::freq_type model_k2p_zeta::k2p_freqs = {0.25,0.25,0.25,0.25};\nconst model_k2p_geo::freq_type model_k2p_geo::k2p_freqs = {0.25,0.25,0.25,0.25};\n\n/***************************************************************************\n * class model_k2p_zeta                                                    *\n ***************************************************************************/\n\nvoid model_k2p_zeta::preallocate(size_t maxa, size_t maxd)\n{\n\tsize_t sz_max = std::max(maxa, maxd)+1;\n\tp_indel_size.resize(sz_max, 0.0);\n}\n\nvoid model_k2p_zeta::expectation_setup(const params_type &params, const freq_type &freq)\n{\n\tp_ts = 0.25-0.5*exp(-params[pT]*(2.0*params[pK]+1.0)/(params[pK]+1.0))\n\t\t\t+ 0.25*exp(-2.0*params[pT]/(params[pK]+1.0));\n\tp_tv = 0.5-0.5*exp(-2.0*params[pT]/(params[pK]+1.0));\n\tp_match = 1.0-p_ts-p_tv;\n\t\n\tp_end = 1.0/(params[pA]+1.0);\n\tp_2h =  (1.0-p_end)*exp(-2.0*params[pR]*params[pT]);\n\tp_2g =  (1.0-p_end)*0.5*(1.0-exp(-2.0*params[pR]*params[pT]));\n\t\n\tdouble nuc_scale2 = 0.25*p_2h\n\t\t*pow(p_match, p_match)\n\t\t*pow(p_ts, p_ts)\n\t\t*pow(0.5*p_tv, p_tv);\n\tnuc_scale = sqrt(nuc_scale2);\n\tamb_scale = 4.0;\n\t\n\tfor(size_t i=0;i<nN;++i)\n\t{\n\t\tp_substitution[i][i] = 0.25*p_2h*p_match/nuc_scale2;\n\t\t\n\t\tfor(size_t j=i+1;j<nN;++j)\n\t\t{\n\t\t\tp_substitution[j][i] = p_substitution[i][j] = p_2h*\n\t\t\t\t((g_pupy[i] == g_pupy[j]) ? 0.25*p_ts : 0.125*p_tv)\n\t\t\t\t/ nuc_scale2;\n\t\t}\n\t\tp_substitution[nN][i] = p_substitution[i][nN] = 0.0625*p_2h / nuc_scale2;\n\t}\n\tp_substitution[nN][nN] = 0.0625*p_2h / nuc_scale2;\n\t\t\n\tdouble z = params[pZ];\n\tdouble Z = p_2g/zeta(z);\n\tdouble s = 0.25/nuc_scale;\n\tdouble ss = s;\n\tfor(size_t u = 1; u < p_indel_size.size(); ++u)\n\t{\n\t\tp_indel_size[u] = pow((double)u, -z)*Z*ss;\n\t\tss *= s;\n\t}\n}\n\n/***************************************************************************\n * class model_k2p_geo                                                     *\n ***************************************************************************/\n\nvoid model_k2p_geo::preallocate(size_t maxa, size_t maxd)\n{\n\tsize_t sz_max = std::max(maxa, maxd)+1;\n\tp_indel_size.resize(sz_max, 0.0);\n}\n\nvoid model_k2p_geo::expectation_setup(const params_type &params, const freq_type &freq)\n{\n\tp_ts = 0.25-0.5*exp(-params[pT]*(2.0*params[pK]+1.0)/(params[pK]+1.0))\n\t\t\t+ 0.25*exp(-2.0*params[pT]/(params[pK]+1.0));\n\tp_tv = 0.5-0.5*exp(-2.0*params[pT]/(params[pK]+1.0));\n\tp_match = 1.0-p_ts-p_tv;\n\t\n\tp_end = 1.0/(params[pA]+1.0);\n\tp_2h =  (1.0-p_end)*exp(-2.0*params[pR]*params[pT]);\n\tp_2g =  (1.0-p_end)*0.5*(1.0-exp(-2.0*params[pR]*params[pT]));\n\t\n\tdouble nuc_scale2 = 0.25*p_2h\n\t\t*pow(p_match, p_match)\n\t\t*pow(p_ts, p_ts)\n\t\t*pow(0.5*p_tv, p_tv);\n\tnuc_scale = sqrt(nuc_scale2);\n\tamb_scale = 4.0;\n\t\n\tfor(size_t i=0;i<nN;++i)\n\t{\n\t\tp_substitution[i][i] = 0.25*p_2h*p_match/nuc_scale2;\n\t\t\n\t\tfor(size_t j=i+1;j<nN;++j)\n\t\t{\n\t\t\tp_substitution[j][i] = p_substitution[i][j] = p_2h*\n\t\t\t\t((g_pupy[i] == g_pupy[j]) ? 0.25*p_ts : 0.125*p_tv)\n\t\t\t\t/ nuc_scale2;\n\t\t}\n\t\tp_substitution[nN][i] = p_substitution[i][nN] = 0.0625*p_2h / nuc_scale2;\n\t}\n\tp_substitution[nN][nN] = 0.0625*p_2h / nuc_scale2;\n\t\t\n\tdouble s = 0.25/nuc_scale;\n\tdouble qq = 1.0/params[pQ];\n\tdouble dp = qq*s;\n\tfor(size_t u = 1; u < p_indel_size.size(); ++u)\n\t{\n\t\tp_indel_size[u] = p_2g*dp;\n\t\tdp *= (1.0-qq)*s;\n\t}\n\tp_open = qq*p_2g*s;\n\tp_extend = (1.0-qq)*s;\n}\n\n", "meta": {"hexsha": "0a01245bfe7d51b33f9717b07207511c4844c323", "size": 5311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/models.cpp", "max_stars_repo_name": "reedacartwright/emdel", "max_stars_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/models.cpp", "max_issues_repo_name": "reedacartwright/emdel", "max_issues_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-03T16:50:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-23T22:51:19.000Z", "max_forks_repo_path": "src/models.cpp", "max_forks_repo_name": "reedacartwright/emdel", "max_forks_repo_head_hexsha": "58ea9d4db89c4a1852ba5405ef73c2eca6539ce3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8819444444, "max_line_length": 88, "alphanum_fraction": 0.5332329128, "num_tokens": 1663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.41742570784057637}}
{"text": "\n#include <qlo/objects/obj_credit.hpp>\n\n#include <qlo/enumerations/factories/termstructuresfactory.hpp>\n\n#include <ql/instruments/stock.hpp>\n#include <ql/quote.hpp>\n#include <ql/currencies/europe.hpp>\n#include <ql/time/daycounter.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>\n#include <ql/termstructures/credit/interpolatedhazardratecurve.hpp>\n#include <ql/termstructures/credit/flathazardrate.hpp>\n#include <ql/termstructures/credit/piecewisedefaultcurve.hpp>\n#include <ql/math/interpolations/backwardflatinterpolation.hpp>\n#include <ql/math/interpolations/loginterpolation.hpp>\n#include <ql/math/interpolations/bilinearinterpolation.hpp>\n#include <ql/math/interpolations/bicubicsplineinterpolation.hpp>\n#include <ql/math/solver1d.hpp>\n#include <ql/math/solvers1d/brent.hpp>\n\n#include <ql/pricingengines/credit/midpointcdsengine.hpp>\n\n#include <ql/instruments/creditdefaultswap.hpp>\n#include <ql/experimental/credit/riskybond.hpp>\n#include <ql/experimental/credit/syntheticcdo.hpp>\n#include <ql/experimental/credit/midpointcdoengine.hpp>\n#include <ql/experimental/credit/nthtodefault.hpp>\n#include <ql/experimental/credit/integralntdengine.hpp>\n#include <ql/experimental/credit/basecorrelationstructure.hpp>\n#include <ql/experimental/credit/cdsoption.hpp>\n#include <ql/experimental/credit/blackcdsoptionengine.hpp>\n\n#include <boost/algorithm/string/case_conv.hpp>\n#include <boost/make_shared.hpp>\n\n#include <ql/settings.hpp>\n\nQuantLibAddin::CreditDefaultSwap::CreditDefaultSwap(\n    const boost::shared_ptr<reposit::ValueObject>& properties,\n            // BEGIN typemap rp_tm_default\n            QuantLib::Protection::Side BuyerSeller,\n            QuantLib::Real Notional,\n            QuantLib::Rate Upfront,\n            QuantLib::Rate Spread,\n            QuantLib::Schedule const &PremiumSchedule,\n            QuantLib::BusinessDayConvention PaymentConvention,\n            QuantLib::DayCounter const &DayCounter,\n            bool SettlesAccrual,\n            bool PayAtDefault,\n            QuantLib::Date const &ProtectionStart,\n            QuantLib::Date const &UpfrontDate,\n            // END   typemap rp_tm_default\n    bool permanent)\n: Instrument(properties, permanent) {\n\t\t// dirty way to decide if this is constructed through a run only version\n        if(UpfrontDate == QuantLib::Null<QuantLib::Date>() && Upfront == 0.) {\n            libraryObject_ = boost::shared_ptr<QuantLib::CreditDefaultSwap>(\n                new QuantLib::CreditDefaultSwap(\n                    BuyerSeller,\n                    Notional,\n                    Spread,\n                    PremiumSchedule,\n                    PaymentConvention,\n                    DayCounter,\n                    SettlesAccrual,\n                    PayAtDefault,\n                    ProtectionStart,\n                    boost::shared_ptr<QuantLib::Claim>()));\n        }else{\n                libraryObject_ = boost::shared_ptr<QuantLib::CreditDefaultSwap>(\n                    new QuantLib::CreditDefaultSwap(\n                        BuyerSeller,\n                        Notional,\n                        Upfront,\n                        Spread,\n                        PremiumSchedule,\n                        PaymentConvention,\n                        DayCounter,\n                        SettlesAccrual,\n                        PayAtDefault,\n                        ProtectionStart,\n                        UpfrontDate,\n                        boost::shared_ptr<QuantLib::Claim>()));\n        }\n}\n\nQuantLibAddin::HazardRateCurve::HazardRateCurve(\n    const boost::shared_ptr<reposit::ValueObject>& properties,\n            // BEGIN typemap rp_tm_default\n            std::vector< QuantLib::Date > const &CurveDates,\n            std::vector< QuantLib::Rate > const &CurveRates,\n            QuantLib::DayCounter const &DayCounter,\n            // END   typemap rp_tm_default\n    bool permanent)\n: DefaultProbabilityTermStructure(properties, permanent) {\n        QL_REQUIRE(!CurveDates.empty(), \"no input dates given\");\n        QL_REQUIRE(CurveDates.size() == CurveRates.size(), \n                   \"vector sizes differ\");\n        libraryObject_ = boost::shared_ptr<QuantLib::Extrapolator>(\n        new QuantLib::InterpolatedHazardRateCurve<QuantLib::BackwardFlat>(\n \t\t\t\t CurveDates, CurveRates, DayCounter));\n}\n\nQuantLibAddin::PiecewiseHazardRateCurve::PiecewiseHazardRateCurve(\n    const boost::shared_ptr<reposit::ValueObject>& properties,\n            // BEGIN typemap rp_tm_default\n            std::vector< boost::shared_ptr< QuantLib::DefaultProbabilityHelper > > const &Helpers,\n            QuantLib::DayCounter const &DayCounter,\n            QuantLib::Calendar const &Calendar,\n            std::string const &Interpolation,\n            QuantLib::Real Accuracy,\n            // END   typemap rp_tm_default\n    bool permanent)\n: DefaultProbabilityTermStructure(properties, permanent) {\n        if(Interpolation == std::string(\"LINEAR\")){\n            libraryObject_ = boost::shared_ptr<QuantLib::Extrapolator>(new\n                   QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate,\n                        QuantLib::Linear>(\n                            0, \n                            Calendar,\n                            Helpers, \n                            DayCounter));\n        }else if(Interpolation == std::string(\"BACKWARDFLAT\")) {\n            libraryObject_ = boost::shared_ptr<QuantLib::Extrapolator>(new\n                   QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate,\n                        QuantLib::BackwardFlat>(\n                            0, \n                            Calendar,\n                            Helpers, \n                            DayCounter));\n        }else{\n            QL_FAIL(\"Unrecognised interpolator\");\n        }\n\n        libraryObject_->enableExtrapolation();\n}\n\nconst std::vector<QuantLib::Date>& QuantLibAddin::PiecewiseHazardRateCurve::dates() const {\n    typedef QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate, QuantLib::BackwardFlat> flat_curve;\n    typedef QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate, QuantLib::Linear> lin_curve;\n    boost::shared_ptr<flat_curve> ptrBF =\n        boost::dynamic_pointer_cast<flat_curve>(libraryObject_);\n    if(ptrBF) return ptrBF->dates();\n    boost::shared_ptr<lin_curve> ptrLIN =\n        boost::dynamic_pointer_cast<lin_curve>(libraryObject_);\n    if(ptrLIN) return ptrLIN->dates();\n    QL_FAIL(\"Unable to cast default probability term structure.\");\n}\n\nconst std::vector<QuantLib::Real>& QuantLibAddin::PiecewiseHazardRateCurve::data() const {\n    typedef QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate, QuantLib::BackwardFlat> flat_curve;\n    typedef QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate, QuantLib::Linear> lin_curve;\n    boost::shared_ptr<flat_curve> ptrBF =\n        boost::dynamic_pointer_cast<flat_curve>(libraryObject_);\n    if(ptrBF) return ptrBF->data();\n    boost::shared_ptr<lin_curve> ptrLIN =\n        boost::dynamic_pointer_cast<lin_curve>(libraryObject_);\n    if(ptrLIN) return ptrLIN->data();\n    QL_FAIL(\"Unable to cast default probability term structure.\");\n}        \n\nQuantLibAddin::PiecewiseFlatForwardCurve::PiecewiseFlatForwardCurve(\n    const boost::shared_ptr<reposit::ValueObject>& properties,\n            // BEGIN typemap rp_tm_default\n            QuantLib::Date const &ReferenceDate,\n            std::vector< boost::shared_ptr< QuantLib::RateHelper > > const &RateHelpers,\n            QuantLib::DayCounter const &DayCounter,\n            QuantLib::Real Accuracy,\n            // END   typemap rp_tm_default\n    bool permanent)\n: YieldTermStructure(properties, permanent) {\n        libraryObject_ = boost::shared_ptr<QuantLib::Extrapolator>(new\n               QuantLib::PiecewiseYieldCurve<QuantLib::Discount,QuantLib::LogLinear>(ReferenceDate, RateHelpers, DayCounter));\n}\n\nQuantLibAddin::RiskyFixedBond::RiskyFixedBond(\n    const boost::shared_ptr<reposit::ValueObject>& properties,\n            // BEGIN typemap rp_tm_default\n            std::string Bondname,\n            QuantLib::Currency Currency,\n            QuantLib::Real Recovery,\n            QuantLib::Handle< QuantLib::DefaultProbabilityTermStructure > const &DefaultCurve,\n            QuantLib::Schedule const &Schedule,\n            QuantLib::Real Rate,\n            QuantLib::DayCounter DayCounter,\n            QuantLib::BusinessDayConvention PaymentConvention,\n            QuantLib::Real Notional,\n            QuantLib::Handle< QuantLib::YieldTermStructure > const &DiscountingCurve,\n            QuantLib::Date PricingDate,\n            // END   typemap rp_tm_default\n    bool permanent)\n: Instrument(properties, permanent) {\n        std::vector<QuantLib::Real> notionals(1,Notional);\n\n        libraryObject_ = boost::shared_ptr<QuantLib::RiskyFixedBond>(\n            new QuantLib::RiskyFixedBond(\n                    Bondname,Currency,Recovery,DefaultCurve,Schedule,Rate,DayCounter,\n                    PaymentConvention,notionals,DiscountingCurve///, PricingDate\n                                       ));\n}\n\nQuantLibAddin::Issuer::Issuer(\n    const boost::shared_ptr<reposit::ValueObject>& properties,\n            // BEGIN typemap rp_tm_default\n            boost::shared_ptr< QuantLib::DefaultProbabilityTermStructure > const &DefaultCurves,\n            boost::shared_ptr< QuantLib::DefaultEventSet > const &DefaultEvents,\n            // END   typemap rp_tm_default\n    bool permanent)\n: reposit::LibraryObject<QuantLib::Issuer>(properties, permanent) {\n        std::vector<QuantLib::Issuer::key_curve_pair> curves(1, std::make_pair(\n            QuantLib::NorthAmericaCorpDefaultKey(QuantLib::EURCurrency(),\n                                                     QuantLib::SeniorSec, \n                                                     QuantLib::Period(),\n                                                     1. // amount threshold\n                                                     ),\n            QuantLib::Handle<QuantLib::DefaultProbabilityTermStructure>(DefaultCurves)\n        ));\n        libraryObject_ = boost::shared_ptr<QuantLib::Issuer>(new QuantLib::Issuer(curves, *DefaultEvents));\n}\n\nQuantLibAddin::DefaultEventSet::DefaultEventSet(\n    const boost::shared_ptr<reposit::ValueObject>& properties,\n            // BEGIN typemap rp_tm_default\n            std::string const &EventType,\n            QuantLib::Date const &EventDate,\n            QuantLib::Currency const &Currency,\n            QuantLib::Seniority Seniority,\n            QuantLib::Date const &SettlementDate,\n            QuantLib::Real SettledRecovery,\n            // END   typemap rp_tm_default\n    bool permanent)\n: reposit::LibraryObject<QuantLib::DefaultEventSet>(properties, permanent) {\n        // if no match return empty set\n        libraryObject_ = boost::shared_ptr<QuantLib::DefaultEventSet>(new QuantLib::DefaultEventSet());\n\n        // only one recovery parsed by now; bankruptcy events need the whole\n        //  set or they fail to construct.\n        std::map<QuantLib::Seniority, QuantLib::Real> rrs;\n        rrs.insert(std::pair<QuantLib::Seniority, QuantLib::Real>(Seniority, SettledRecovery));\n        if(EventType==std::string(\"FailureToPayEvent\")) {\n            libraryObject_->insert(boost::shared_ptr<QuantLib::FailureToPayEvent> (\n                new QuantLib::FailureToPayEvent(EventDate, Currency, Seniority, 1.e7, \n                //implSettlemt, \n                SettlementDate,\n                rrs)));\n        }else if(EventType==std::string(\"BankruptcyEvent\")){\n            libraryObject_->insert(boost::shared_ptr<QuantLib::BankruptcyEvent> (\n                new QuantLib::BankruptcyEvent(EventDate, Currency, Seniority, \n                SettlementDate,\n                rrs)));\n        }\n}\n\nQuantLibAddin::BaseCorrelationTermStructure::BaseCorrelationTermStructure(\n    const boost::shared_ptr<reposit::ValueObject>& properties,\n            // BEGIN typemap rp_tm_default\n            std::string const &InterpolatorType,\n            QuantLib::Natural SettlementDays,\n            QuantLib::Calendar const &Calendar,\n            QuantLib::BusinessDayConvention Convention,\n            std::vector< QuantLib::Period > const &Tenors,\n            std::vector< QuantLib::Real > const &LossLevel,\n            std::vector< std::vector< QuantLib::Handle< QuantLib::Quote > > > const &Correlations,\n            QuantLib::DayCounter const &DayCounter,\n            // END   typemap rp_tm_default\n    bool permanent)\n: CorrelationTermStructure(properties, permanent) {\n        // select 2D interpolator:\n        //  Another option is to write one class per interpolator.\n        if(InterpolatorType == std::string(\"BILIN\")) {\n            libraryObject_ = boost::shared_ptr<QuantLib::BaseCorrelationTermStructure<QuantLib::BilinearInterpolation> >(new\n                QuantLib::BaseCorrelationTermStructure<QuantLib::BilinearInterpolation>(SettlementDays, Calendar, Convention, Tenors, LossLevel, Correlations, DayCounter));\n        //}else if(InterpolatorType == std::string(\"\")) {\n        }else if(InterpolatorType == std::string(\"BICUBIC\")) {\n            libraryObject_ = boost::shared_ptr<QuantLib::BaseCorrelationTermStructure<QuantLib::BicubicSpline> >(new\n                QuantLib::BaseCorrelationTermStructure<QuantLib::BicubicSpline>(SettlementDays, Calendar, Convention, Tenors, LossLevel, Correlations, DayCounter));\n        }else{\n            QL_FAIL(\"Can't determine base correlation surface interpolator.\");\n        }\n}\n\nQuantLib::Real QuantLibAddin::BaseCorrelationTermStructure::correlation(const QuantLib::Date& d, QuantLib::Real lossLevel) {\n    if(interpolType_ == std::string(\"BILIN\")) {\n        return boost::dynamic_pointer_cast<QuantLib::BaseCorrelationTermStructure<QuantLib::BilinearInterpolation> >\n            (libraryObject_)->correlation(d, lossLevel);\n    }else if(interpolType_ == std::string(\"BICUBIC\")) {\n        return boost::dynamic_pointer_cast<QuantLib::BaseCorrelationTermStructure<QuantLib::BicubicSpline> >\n            (libraryObject_)->correlation(d, lossLevel);\n    }else{\n        QL_FAIL(\"unknown 2D interpolator\");\n    }\n}\n", "meta": {"hexsha": "62afdd3cc6fca6bc88de30c81d49cb630065766d", "size": 14102, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "qlo/objects/obj_credit_hw.cpp", "max_stars_repo_name": "eehlers/QuantLibAddin", "max_stars_repo_head_hexsha": "bcbd9d1c0e7a4f4ce608470c6576d6e772305980", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-07-13T14:05:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T15:15:17.000Z", "max_issues_repo_path": "qlo/objects/obj_credit_hw.cpp", "max_issues_repo_name": "eehlers/QuantLibAddin", "max_issues_repo_head_hexsha": "bcbd9d1c0e7a4f4ce608470c6576d6e772305980", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qlo/objects/obj_credit_hw.cpp", "max_forks_repo_name": "eehlers/QuantLibAddin", "max_forks_repo_head_hexsha": "bcbd9d1c0e7a4f4ce608470c6576d6e772305980", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-01-28T07:18:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T03:48:52.000Z", "avg_line_length": 47.9659863946, "max_line_length": 172, "alphanum_fraction": 0.6467167778, "num_tokens": 3133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.4174257019559318}}
{"text": "// Copyright (C) 2019 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n// This file was created by Steffen Urban (urbste@googlemail.com) or\n// company address (steffen.urban@zeiss.com)\n// December 2018\n\n#include <glog/logging.h>\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n#include <Eigen/LU>\n#include <Eigen/QR>\n#include <Eigen/SVD>\n#include <random>\n\n#include \"theia/sfm/pose/four_point_focal_length_radial_distortion.h\"\n#include \"theia/sfm/pose/four_point_focal_length_radial_distortion_helper.h\"\n#include \"theia/util/random.h\"\n\nnamespace theia {\n\ndouble sgn(double val) { return (0.0 < val) - (val < 0.0); }\n\nusing Matrix34d = Eigen::Matrix<double, 3, 4>;\nusing Matrix24d = Eigen::Matrix<double, 2, 4>;\nusing Matrix42d = Eigen::Matrix<double, 4, 2>;\nusing Vector8d  = Eigen::Matrix<double, 8, 1>;\nusing Vector5d  = Eigen::Matrix<double, 5, 1>;\nusing Eigen::Map;\nusing Eigen::Vector3d;\nusing Eigen::Vector4d;\nusing Eigen::Matrix4d;\nusing Eigen::Matrix3d;\nusing Eigen::MatrixXd;\nusing Eigen::Matrix;\n\nbool FourPointsPoseFocalLengthRadialDistortion(\n    const std::vector<Eigen::Vector2d>& feature_vectors,\n    const std::vector<Eigen::Vector3d>& world_points,\n    std::vector<Eigen::Matrix3d>* rotations,\n    std::vector<Eigen::Vector3d>* translations,\n    std::vector<double>* radial_distortions,\n    std::vector<double>* focal_lengths) {\n  // check that input size of features and world points is 4\n  CHECK_GE(feature_vectors.size(), 4);\n  CHECK_EQ(feature_vectors.size(), world_points.size());\n\n  Vector4d d;\n  Matrix34d world_points_;\n  Matrix34d u;  // image points. Will be normalized.\n  for (int i = 0; i < 4; ++i) {\n    d[i] = feature_vectors[i].squaredNorm();\n    world_points_.col(i) = world_points[i];\n    u.col(i) = feature_vectors[i].homogeneous();\n  }\n\n  const Vector3d t0 = world_points_.rowwise().mean();\n  Matrix34d t0_mat;\n  t0_mat << t0, t0, t0, t0;\n\n  Matrix4d U;\n  U.topRows<3>() = world_points_ - t0_mat;\n  U.bottomRows<1>() << 1.0, 1.0, 1.0, 1.0;\n\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(\n      U.topRows<3>(), Eigen::ComputeFullV | Eigen::ComputeFullU);\n  Matrix3d R0 = svd.matrixU();\n\n  if (sgn(R0.determinant()) < 0.0) {\n    R0.col(0) *= -1;\n  }\n  R0.transposeInPlace();\n\n  U.topRows<3>() = R0 * U.topRows<3>();\n  const double scale =\n      U.topRows<3>().array().pow(2).colwise().sum().sqrt().mean();\n\n  U.topRows<3>() /= scale;\n\n  // rescale image points\n  const double f0 = u.topRows<2>().array().pow(2).colwise().sum().sqrt().mean();\n  u.topRows<2>() /= f0;\n\n  const double k0 = d.array().mean();\n  d /= k0;\n\n  Matrix<double, 5, 8> M;\n  M.fill(0.0);\n  M.row(0).leftCols<4>() = U.col(0);\n  M.row(1).rightCols<4>() = U.col(0);\n  for (int k = 1; k < 4; ++k) {\n    M.row(k + 1).leftCols<4>() = u.row(1).col(k) * U.col(k).transpose();\n    M.row(k + 1).rightCols<4>() = -u.row(0).col(k) * U.col(k).transpose();\n  }\n\n  Vector5d b;\n  b.fill(0.0);\n  b.topRows<2>() = u.col(0).topRows<2>();\n  Eigen::HouseholderQR<Eigen::MatrixXd> qr;\n  qr.compute(M.transpose());\n\n  Matrix<double, 8, 8> Q = qr.householderQ();\n  Matrix<double, 8, 5> R = qr.matrixQR().triangularView<Eigen::Upper>();\n\n  Matrix<double, 8, 4> N;\n  N.fill(0.0);\n  N.leftCols<3>() = Q.rightCols<3>();\n\n  // this random rotation is supposed to make the solver more stable\n  static RandomNumberGenerator random_number_gen(42);\n  Vector3d rot_vec(random_number_gen.RandDouble(-0.5, 0.5),\n                   random_number_gen.RandDouble(-0.5, 0.5),\n                   random_number_gen.RandDouble(-0.5, 0.5));\n  Eigen::AngleAxisd random_rot(rot_vec.norm(), rot_vec);\n  N.leftCols<3>() *= random_rot.toRotationMatrix();\n  Matrix<double, 8, 1> x0 =\n      Q.leftCols<5>() * (R.topRows<5>().transpose().fullPivLu().solve(b));\n  N.rightCols<1>() = x0;\n\n  Matrix<double, 6, 3> C;\n  C.fill(0.0);\n  Matrix34d UN1 = U.rightCols<3>().transpose() * N.topRows<4>();\n  Matrix34d UN2 = U.rightCols<3>().transpose() * N.bottomRows<4>();\n  Matrix<double, 6, 9> B;\n  B.fill(0.0);\n\n  B.topLeftCorner<3, 3>() = UN1.leftCols<3>();\n  B.bottomLeftCorner<3, 3>() = UN2.leftCols<3>();\n  B.topRightCorner<3, 1>() = UN1.rightCols<1>();\n  B.bottomRightCorner<3, 1>() = UN2.rightCols<1>();\n\n  B.block<3, 4>(0, 3) =\n      d.bottomRows<3>().transpose().replicate(4, 1).transpose().cwiseProduct(\n          UN1);\n  B.block<3, 4>(3, 3) =\n      d.bottomRows<3>().transpose().replicate(4, 1).transpose().cwiseProduct(\n          UN2);\n\n  B.col(7).topRows<3>() = -u.row(0).rightCols<3>().transpose().cwiseProduct(\n      U.row(2).rightCols<3>().transpose());\n  B.col(7).bottomRows<3>() = -u.row(1).rightCols<3>().transpose().cwiseProduct(\n      U.row(2).rightCols<3>().transpose());\n\n  // fill these guys\n  Matrix3d Utmp;\n  Utmp.row(0) = U.row(0).rightCols<3>();\n  Utmp.row(1) = U.row(1).rightCols<3>();\n  Utmp.row(2) = U.row(3).rightCols<3>();\n\n  Matrix3d u1temp;\n  u1temp.row(0) = u.row(0).rightCols<3>();\n  u1temp.row(1) = u.row(0).rightCols<3>();\n  u1temp.row(2) = u.row(0).rightCols<3>();\n  Matrix3d u2temp;\n  u2temp.row(0) = u.row(1).rightCols<3>();\n  u2temp.row(1) = u.row(1).rightCols<3>();\n  u2temp.row(2) = u.row(1).rightCols<3>();\n\n  C.block<3, 3>(0, 0) = Utmp.transpose().cwiseProduct(u1temp.transpose());\n  C.block<3, 3>(3, 0) = Utmp.transpose().cwiseProduct(u2temp.transpose());\n\n  Matrix<double, 3, 9> D = C.colPivHouseholderQr().solve(B);\n  Map<Eigen::RowVectorXd> N_(N.data(), N.size());\n  Map<Eigen::RowVectorXd> D_(D.data(), D.size());\n\n  Matrix<double, 64, 1> data;\n  data(0) = 0.0;  // used to keep matlab indices, just an index offset of 1\n  data.block<32, 1>(1, 0) = N_;\n  data.block<27, 1>(33, 0) = D_;\n  data(60, 0) = d(0, 0);\n  data.bottomRows<3>() = U.topRows<3>().col(0);\n\n  std::vector<Vector5d> valid_solutions;\n  FourPointsPoseFocalLengthRadialDistortionSolver(data, &valid_solutions);\n\n  rotations->resize(valid_solutions.size());\n  translations->resize(valid_solutions.size());\n  radial_distortions->resize(valid_solutions.size());\n  focal_lengths->resize(valid_solutions.size());\n\n  for (int i = 0; i < valid_solutions.size(); ++i) {\n    const double k = valid_solutions[i][3];\n    const double P33 = valid_solutions[i][4];\n    Eigen::Vector4d alpha(valid_solutions[i][0], valid_solutions[i][1],\n                          valid_solutions[i][2], 1.0);\n\n    Vector8d P12_ = N * alpha;\n    Map<Matrix42d> P12(P12_.data(), 4, 2);\n\n    Matrix<double, 9, 1> tmp;\n    tmp(0, 0) = alpha[0];\n    tmp(1, 0) = alpha[1];\n    tmp(2, 0) = alpha[2];\n    tmp(3, 0) = k * alpha(0);\n    tmp(4, 0) = k * alpha(1);\n    tmp(5, 0) = k * alpha(2);\n    tmp(6, 0) = k;\n    tmp(7, 0) = P33;\n    tmp(8, 0) = 1.0;\n\n    const Vector3d P3_124 = D * tmp;\n\n    Vector4d P3;\n    P3(0) = P3_124(0);\n    P3(1) = P3_124(1);\n    P3(2) = P33;\n    P3(3) = P3_124(2);\n\n    Matrix34d P;\n    P.topRows<2>() = P12.transpose();\n    P.bottomRows<1>() = P3;\n    P /= P.bottomRows<1>().leftCols<3>().norm();\n    const double f = P.topRows<1>().leftCols<3>().norm();\n    Matrix3d K = Matrix3d::Identity();\n    K(0, 0) = 1. / f;\n    K(1, 1) = 1. / f;\n\n    (*focal_lengths)[i] = f * f0;\n    (*radial_distortions)[i] = k / k0;\n\n    Matrix34d Rt = K * P;\n\n    if (Rt.topLeftCorner<3, 3>().determinant() < 0.0) Rt *= -1.0;\n\n    // scale radial distortion\n    // radial_distortions[i] *= (focal_lengths[i]*focal_lengths[i]);\n\n    Rt.col(3) = Rt.col(3) * scale - Rt.topLeftCorner<3, 3>() * R0 * t0;\n    Rt.topLeftCorner<3, 3>() = Rt.topLeftCorner<3, 3>() * R0;\n\n    (*rotations)[i] = Rt.topLeftCorner<3, 3>();\n    (*translations)[i] = Rt.col(3);\n  }\n\n  return valid_solutions.size() > 0;\n}\n}\n", "meta": {"hexsha": "c82ac55cc2b39a193b6ffa284d6160af03dab575", "size": 9324, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/pose/four_point_focal_length_radial_distortion.cc", "max_stars_repo_name": "FangLinHe/TheiaSfM", "max_stars_repo_head_hexsha": "d2112f15aa69a53dda68fe6c4bd4b0f1e2fe915b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 770.0, "max_stars_repo_stars_event_min_datetime": "2015-02-12T14:32:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T00:54:33.000Z", "max_issues_repo_path": "src/theia/sfm/pose/four_point_focal_length_radial_distortion.cc", "max_issues_repo_name": "sweeneychris/Theia", "max_issues_repo_head_hexsha": "d2112f15aa69a53dda68fe6c4bd4b0f1e2fe915b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 237.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T18:50:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T05:21:48.000Z", "max_forks_repo_path": "src/theia/sfm/pose/four_point_focal_length_radial_distortion.cc", "max_forks_repo_name": "sweeneychris/Theia", "max_forks_repo_head_hexsha": "d2112f15aa69a53dda68fe6c4bd4b0f1e2fe915b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 278.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T06:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T17:25:21.000Z", "avg_line_length": 34.2794117647, "max_line_length": 80, "alphanum_fraction": 0.6467181467, "num_tokens": 3018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.41742570195593176}}
{"text": "#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <boost/property_map.hpp>\n#include <boost/graph/adjacency_list.hpp>\n\n#include \"../../src/edmonds_optimum_branching.hpp\"\n\n// Define a directed graph type that associates a weight with each\n// edge. We store the weights using internal properties as described\n// in BGL.\ntypedef boost::property<boost::edge_weight_t, double>       EdgeProperty;\ntypedef boost::adjacency_list<boost::listS,\n                              boost::vecS,\n                              boost::directedS,\n                              boost::no_property,\n                              EdgeProperty>                 Graph;\ntypedef boost::graph_traits<Graph>::vertex_descriptor       Vertex;\ntypedef boost::graph_traits<Graph>::edge_descriptor         Edge;\n\nint\nmain(int argc, char *argv[])\n{\n    const int N = 4;\n\n    // Graph with N vertices    \n    Graph G(N);\n\n    // Create a vector to keep track of all the vertices and enable us\n    // to index them. As a side note, observe that this is not\n    // necessary since Vertex is probably an integral type. However,\n    // this may not be true of arbitrary graphs and I think this code\n    // is a better illustration of a more general case.\n    std::vector<Vertex> the_vertices;\n    BOOST_FOREACH (Vertex v, vertices(G))\n    {\n        the_vertices.push_back(v);\n    }\n    \n    // add a few edges with weights to the graph\n    add_edge(the_vertices[0], the_vertices[1], 3.0, G);\n    add_edge(the_vertices[0], the_vertices[2], 1.5, G);\n    add_edge(the_vertices[0], the_vertices[3], 1.8, G);\n    add_edge(the_vertices[1], the_vertices[2], 4.3, G);\n    add_edge(the_vertices[2], the_vertices[3], 2.2, G);\n\n    // This is how we can get a property map that gives the weights of\n    // the edges.\n    boost::property_map<Graph, boost::edge_weight_t>::type weights =\n        get(boost::edge_weight_t(), G);\n    \n    // This is how we can get a property map mapping the vertices to\n    // integer indices.\n    boost::property_map<Graph, boost::vertex_index_t>::type vertex_indices =\n        get(boost::vertex_index_t(), G);\n\n\n    // Print the graph (or rather the edges of the graph).\n    std::cout << \"This is the graph:\\n\";\n    BOOST_FOREACH (Edge e, edges(G))\n    {\n        std::cout << \"(\" << boost::source(e, G) << \", \"\n                  << boost::target(e, G) << \")\\t\"\n                  << get(weights, e) << \"\\n\";\n    }\n\n    // Find the maximum branching.\n    std::vector<Edge> branching;\n    edmonds_optimum_branching<true, false, false>(G,\n                                                  vertex_indices,\n                                                  weights,\n                                                  static_cast<Vertex *>(0),\n                                                  static_cast<Vertex *>(0),\n                                                  std::back_inserter(branching));\n    \n    // Print the edges of the maximum branching\n    std::cout << \"This is the maximum branching\\n\";\n    BOOST_FOREACH (Edge e, branching)\n    {\n        std::cout << \"(\" << boost::source(e, G) << \", \"\n                  << boost::target(e, G) << \")\\t\"\n                  << get(weights, e) << \"\\n\";\n    }\n    return 0;\n}\n", "meta": {"hexsha": "4770154e4c0c8233285b7b9232c5c24fa1370609", "size": 3235, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/examples/sparse-example.cpp", "max_stars_repo_name": "atofigh/edmonds-alg", "max_stars_repo_head_hexsha": "450d192bb839554b5cf61d4d1472a214ac77cdf4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-08-28T12:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T15:02:24.000Z", "max_issues_repo_path": "doc/examples/sparse-example.cpp", "max_issues_repo_name": "atofigh/edmonds-alg", "max_issues_repo_head_hexsha": "450d192bb839554b5cf61d4d1472a214ac77cdf4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-04-12T13:38:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-03T16:17:20.000Z", "max_forks_repo_path": "doc/examples/sparse-example.cpp", "max_forks_repo_name": "atofigh/edmonds-alg", "max_forks_repo_head_hexsha": "450d192bb839554b5cf61d4d1472a214ac77cdf4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-03-22T15:44:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T03:09:16.000Z", "avg_line_length": 37.183908046, "max_line_length": 81, "alphanum_fraction": 0.5644513138, "num_tokens": 732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.6442251133170356, "lm_q1q2_score": 0.41732788912767854}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2018-2020, LAAS-CNRS, New York University, Max Planck Gesellschaft,\n//                          University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_NUMDIFF_STATE_HPP_\n#define CROCODDYL_CORE_NUMDIFF_STATE_HPP_\n\n#include <boost/make_shared.hpp>\n#include <boost/shared_ptr.hpp>\n#include \"crocoddyl/core/state-base.hpp\"\n\nnamespace crocoddyl {\n\nclass StateNumDiff : public StateAbstract {\n public:\n  explicit StateNumDiff(boost::shared_ptr<StateAbstract> state);\n  ~StateNumDiff();\n\n  Eigen::VectorXd zero() const;\n  Eigen::VectorXd rand() const;\n  void diff(const Eigen::Ref<const Eigen::VectorXd>& x0, const Eigen::Ref<const Eigen::VectorXd>& x1,\n            Eigen::Ref<Eigen::VectorXd> dxout) const;\n  void integrate(const Eigen::Ref<const Eigen::VectorXd>& x, const Eigen::Ref<const Eigen::VectorXd>& dx,\n                 Eigen::Ref<Eigen::VectorXd> xout) const;\n  /**\n   * @brief This computes the Jacobian of the diff method by finite\n   * differentiation:\n   * \\f{equation}{\n   *    Jfirst[:,k] = diff(int(x_1, dx_dist), x_2) - diff(x_1, x_2)/disturbance\n   * \\f}\n   * and\n   * \\f{equation}{\n   *    Jsecond[:,k] = diff(x_1, int(x_2, dx_dist)) - diff(x_1, x_2)/disturbance\n   * \\f}\n   *\n   * @param Jfirst\n   * @param Jsecond\n   * @param firstsecond\n   */\n  void Jdiff(const Eigen::Ref<const Eigen::VectorXd>& x0, const Eigen::Ref<const Eigen::VectorXd>& x1,\n             Eigen::Ref<Eigen::MatrixXd> Jfirst, Eigen::Ref<Eigen::MatrixXd> Jsecond,\n             Jcomponent firstsecond = both) const;\n  /**\n   * @brief This computes the Jacobian of the integrate method by finite\n   * differentiation:\n   * \\f{equation}{\n   *    Jfirst[:,k] = diff( int(x, d_x), int( int(x, dx_dist), dx) )/disturbance\n   * \\f}\n   * and\n   * \\f{equation}{\n   *    Jsecond[:,k] = diff( int(x, d_x), int( x, dx + dx_dist) )/disturbance\n   * \\f}\n   *\n   * @param Jfirst\n   * @param Jsecond\n   * @param firstsecond\n   */\n  void Jintegrate(const Eigen::Ref<const Eigen::VectorXd>& x, const Eigen::Ref<const Eigen::VectorXd>& dx,\n                  Eigen::Ref<Eigen::MatrixXd> Jfirst, Eigen::Ref<Eigen::MatrixXd> Jsecond,\n                  Jcomponent firstsecond = both) const;\n  const double& get_disturbance() const;\n  void set_disturbance(const double& disturbance);\n\n private:\n  /**\n   * @brief This is the state we need to compute the numerical differentiation\n   * from.\n   */\n  boost::shared_ptr<StateAbstract> state_;\n  /**\n   * @brief This the increment used in the finite differentiation and integration.\n   */\n  double disturbance_;\n};\n\n}  // namespace crocoddyl\n\n#endif  // CROCODDYL_CORE_NUMDIFF_STATE_HPP_\n", "meta": {"hexsha": "4c16fe5b36fa6a9901aebc3fbb64c52db61427bb", "size": 2886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/numdiff/state.hpp", "max_stars_repo_name": "jcarpent/crocoddyl", "max_stars_repo_head_hexsha": "155999999f1fbd0c5760875584c540e2bc13645b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-21T12:11:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-21T12:11:15.000Z", "max_issues_repo_path": "include/crocoddyl/core/numdiff/state.hpp", "max_issues_repo_name": "boyali/crocoddyl", "max_issues_repo_head_hexsha": "155999999f1fbd0c5760875584c540e2bc13645b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crocoddyl/core/numdiff/state.hpp", "max_forks_repo_name": "boyali/crocoddyl", "max_forks_repo_head_hexsha": "155999999f1fbd0c5760875584c540e2bc13645b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.3571428571, "max_line_length": 106, "alphanum_fraction": 0.6254331254, "num_tokens": 760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.6477982315512489, "lm_q1q2_score": 0.4173278847027853}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// Copyright Christopher Kormanyos 2014.\n// Copyright John Maddock 2014.\n// Copyright Paul Bristow 2014.\n// Distributed under the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n\n// Implement quadruple-precision <cmath> support.\n\n#ifndef _BOOST_CSTDFLOAT_CMATH_2014_02_15_HPP_\n#define _BOOST_CSTDFLOAT_CMATH_2014_02_15_HPP_\n\n#include <boost/math/cstdfloat/cstdfloat_types.hpp>\n#include <boost/math/cstdfloat/cstdfloat_limits.hpp>\n\n#if defined(BOOST_CSTDFLOAT_HAS_INTERNAL_FLOAT128_T) && defined(BOOST_MATH_USE_FLOAT128) && !defined(BOOST_CSTDFLOAT_NO_LIBQUADMATH_SUPPORT)\n\n#include <cmath>\n#include <stdexcept>\n#include <iostream>\n#include <boost/cstdint.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/throw_exception.hpp>\n#include <boost/core/enable_if.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/type_traits/is_convertible.hpp>\n#include <boost/scoped_array.hpp>\n\n#if defined(_WIN32) && defined(__GNUC__)\n  // Several versions of Mingw and probably cygwin too have broken\n  // libquadmath implementations that segfault as soon as you call\n  // expq or any function that depends on it.\n#define BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS\n#endif\n\n// Here is a helper function used for raising the value of a given\n// floating-point type to the power of n, where n has integral type.\nnamespace boost {\n   namespace math {\n      namespace cstdfloat {\n         namespace detail {\n\n            template<class float_type, class integer_type>\n            inline float_type pown(const float_type& x, const integer_type p)\n            {\n               const bool isneg = (x < 0);\n               const bool isnan = (x != x);\n               const bool isinf = ((!isneg) ? bool(+x > (std::numeric_limits<float_type>::max)())\n                  : bool(-x > (std::numeric_limits<float_type>::max)()));\n\n               if (isnan) { return x; }\n\n               if (isinf) { return std::numeric_limits<float_type>::quiet_NaN(); }\n\n               const bool       x_is_neg = (x < 0);\n               const float_type abs_x = (x_is_neg ? -x : x);\n\n               if (p < static_cast<integer_type>(0))\n               {\n                  if (abs_x < (std::numeric_limits<float_type>::min)())\n                  {\n                     return (x_is_neg ? -std::numeric_limits<float_type>::infinity()\n                        : +std::numeric_limits<float_type>::infinity());\n                  }\n                  else\n                  {\n                     return float_type(1) / pown(x, static_cast<integer_type>(-p));\n                  }\n               }\n\n               if (p == static_cast<integer_type>(0))\n               {\n                  return float_type(1);\n               }\n               else\n               {\n                  if (p == static_cast<integer_type>(1)) { return x; }\n\n                  if (abs_x > (std::numeric_limits<float_type>::max)())\n                  {\n                     return (x_is_neg ? -std::numeric_limits<float_type>::infinity()\n                        : +std::numeric_limits<float_type>::infinity());\n                  }\n\n                  if (p == static_cast<integer_type>(2)) { return  (x * x); }\n                  else if (p == static_cast<integer_type>(3)) { return ((x * x) * x); }\n                  else if (p == static_cast<integer_type>(4)) { const float_type x2 = (x * x); return (x2 * x2); }\n                  else\n                  {\n                     // The variable xn stores the binary powers of x.\n                     float_type result(((p % integer_type(2)) != integer_type(0)) ? x : float_type(1));\n                     float_type xn(x);\n\n                     integer_type p2 = p;\n\n                     while (integer_type(p2 /= 2) != integer_type(0))\n                     {\n                        // Square xn for each binary power.\n                        xn *= xn;\n\n                        const bool has_binary_power = (integer_type(p2 % integer_type(2)) != integer_type(0));\n\n                        if (has_binary_power)\n                        {\n                           // Multiply the result with each binary power contained in the exponent.\n                           result *= xn;\n                        }\n                     }\n\n                     return result;\n                  }\n               }\n            }\n\n         }\n      }\n   }\n} // boost::math::cstdfloat::detail\n\n// We will now define preprocessor symbols representing quadruple-precision <cmath> functions.\n#if defined(BOOST_INTEL)\n#define BOOST_CSTDFLOAT_FLOAT128_LDEXP  __ldexpq\n#define BOOST_CSTDFLOAT_FLOAT128_FREXP  __frexpq\n#define BOOST_CSTDFLOAT_FLOAT128_FABS   __fabsq\n#define BOOST_CSTDFLOAT_FLOAT128_FLOOR  __floorq\n#define BOOST_CSTDFLOAT_FLOAT128_CEIL   __ceilq\n#if !defined(BOOST_CSTDFLOAT_FLOAT128_SQRT)\n#define BOOST_CSTDFLOAT_FLOAT128_SQRT   __sqrtq\n#endif\n#define BOOST_CSTDFLOAT_FLOAT128_TRUNC  __truncq\n#define BOOST_CSTDFLOAT_FLOAT128_EXP    __expq\n#define BOOST_CSTDFLOAT_FLOAT128_EXPM1  __expm1q\n#define BOOST_CSTDFLOAT_FLOAT128_POW    __powq\n#define BOOST_CSTDFLOAT_FLOAT128_LOG    __logq\n#define BOOST_CSTDFLOAT_FLOAT128_LOG10  __log10q\n#define BOOST_CSTDFLOAT_FLOAT128_SIN    __sinq\n#define BOOST_CSTDFLOAT_FLOAT128_COS    __cosq\n#define BOOST_CSTDFLOAT_FLOAT128_TAN    __tanq\n#define BOOST_CSTDFLOAT_FLOAT128_ASIN   __asinq\n#define BOOST_CSTDFLOAT_FLOAT128_ACOS   __acosq\n#define BOOST_CSTDFLOAT_FLOAT128_ATAN   __atanq\n#define BOOST_CSTDFLOAT_FLOAT128_SINH   __sinhq\n#define BOOST_CSTDFLOAT_FLOAT128_COSH   __coshq\n#define BOOST_CSTDFLOAT_FLOAT128_TANH   __tanhq\n#define BOOST_CSTDFLOAT_FLOAT128_ASINH  __asinhq\n#define BOOST_CSTDFLOAT_FLOAT128_ACOSH  __acoshq\n#define BOOST_CSTDFLOAT_FLOAT128_ATANH  __atanhq\n#define BOOST_CSTDFLOAT_FLOAT128_FMOD   __fmodq\n#define BOOST_CSTDFLOAT_FLOAT128_ATAN2  __atan2q\n#define BOOST_CSTDFLOAT_FLOAT128_LGAMMA __lgammaq\n#define BOOST_CSTDFLOAT_FLOAT128_TGAMMA __tgammaq\n//   begin more functions\n#define BOOST_CSTDFLOAT_FLOAT128_REMAINDER   __remainderq\n#define BOOST_CSTDFLOAT_FLOAT128_REMQUO      __remquoq\n#define BOOST_CSTDFLOAT_FLOAT128_FMA         __fmaq\n#define BOOST_CSTDFLOAT_FLOAT128_FMAX        __fmaxq\n#define BOOST_CSTDFLOAT_FLOAT128_FMIN        __fminq\n#define BOOST_CSTDFLOAT_FLOAT128_FDIM        __fdimq\n#define BOOST_CSTDFLOAT_FLOAT128_NAN         __nanq\n//#define BOOST_CSTDFLOAT_FLOAT128_EXP2      __exp2q\n#define BOOST_CSTDFLOAT_FLOAT128_LOG2        __log2q\n#define BOOST_CSTDFLOAT_FLOAT128_LOG1P       __log1pq\n#define BOOST_CSTDFLOAT_FLOAT128_CBRT        __cbrtq\n#define BOOST_CSTDFLOAT_FLOAT128_HYPOT       __hypotq\n#define BOOST_CSTDFLOAT_FLOAT128_ERF         __erfq\n#define BOOST_CSTDFLOAT_FLOAT128_ERFC        __erfcq\n#define BOOST_CSTDFLOAT_FLOAT128_LLROUND     __llroundq\n#define BOOST_CSTDFLOAT_FLOAT128_LROUND      __lroundq\n#define BOOST_CSTDFLOAT_FLOAT128_ROUND       __roundq\n#define BOOST_CSTDFLOAT_FLOAT128_NEARBYINT   __nearbyintq\n#define BOOST_CSTDFLOAT_FLOAT128_LLRINT      __llrintq\n#define BOOST_CSTDFLOAT_FLOAT128_LRINT       __lrintq\n#define BOOST_CSTDFLOAT_FLOAT128_RINT        __rintq\n#define BOOST_CSTDFLOAT_FLOAT128_MODF        __modfq\n#define BOOST_CSTDFLOAT_FLOAT128_SCALBLN     __scalblnq\n#define BOOST_CSTDFLOAT_FLOAT128_SCALBN      __scalbnq\n#define BOOST_CSTDFLOAT_FLOAT128_ILOGB       __ilogbq\n#define BOOST_CSTDFLOAT_FLOAT128_LOGB        __logbq\n#define BOOST_CSTDFLOAT_FLOAT128_NEXTAFTER   __nextafterq\n//#define BOOST_CSTDFLOAT_FLOAT128_NEXTTOWARD  __nexttowardq\n#define BOOST_CSTDFLOAT_FLOAT128_COPYSIGN     __copysignq\n#define BOOST_CSTDFLOAT_FLOAT128_SIGNBIT      __signbitq\n//#define BOOST_CSTDFLOAT_FLOAT128_FPCLASSIFY __fpclassifyq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISFINITE   __isfiniteq\n#define BOOST_CSTDFLOAT_FLOAT128_ISINF        __isinfq\n#define BOOST_CSTDFLOAT_FLOAT128_ISNAN        __isnanq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISNORMAL   __isnormalq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISGREATER  __isgreaterq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISGREATEREQUAL __isgreaterequalq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISLESS         __islessq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISLESSEQUAL    __islessequalq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISLESSGREATER  __islessgreaterq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISUNORDERED    __isunorderedq\n//   end more functions\n#elif defined(__GNUC__)\n#define BOOST_CSTDFLOAT_FLOAT128_LDEXP  ldexpq\n#define BOOST_CSTDFLOAT_FLOAT128_FREXP  frexpq\n#define BOOST_CSTDFLOAT_FLOAT128_FABS   fabsq\n#define BOOST_CSTDFLOAT_FLOAT128_FLOOR  floorq\n#define BOOST_CSTDFLOAT_FLOAT128_CEIL   ceilq\n#if !defined(BOOST_CSTDFLOAT_FLOAT128_SQRT)\n#define BOOST_CSTDFLOAT_FLOAT128_SQRT   sqrtq\n#endif\n#define BOOST_CSTDFLOAT_FLOAT128_TRUNC  truncq\n#define BOOST_CSTDFLOAT_FLOAT128_POW    powq\n#define BOOST_CSTDFLOAT_FLOAT128_LOG    logq\n#define BOOST_CSTDFLOAT_FLOAT128_LOG10  log10q\n#define BOOST_CSTDFLOAT_FLOAT128_SIN    sinq\n#define BOOST_CSTDFLOAT_FLOAT128_COS    cosq\n#define BOOST_CSTDFLOAT_FLOAT128_TAN    tanq\n#define BOOST_CSTDFLOAT_FLOAT128_ASIN   asinq\n#define BOOST_CSTDFLOAT_FLOAT128_ACOS   acosq\n#define BOOST_CSTDFLOAT_FLOAT128_ATAN   atanq\n#define BOOST_CSTDFLOAT_FLOAT128_FMOD   fmodq\n#define BOOST_CSTDFLOAT_FLOAT128_ATAN2  atan2q\n#define BOOST_CSTDFLOAT_FLOAT128_LGAMMA lgammaq\n#if !defined(BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS)\n#define BOOST_CSTDFLOAT_FLOAT128_EXP    expq\n#define BOOST_CSTDFLOAT_FLOAT128_EXPM1  expm1q\n#define BOOST_CSTDFLOAT_FLOAT128_SINH   sinhq\n#define BOOST_CSTDFLOAT_FLOAT128_COSH   coshq\n#define BOOST_CSTDFLOAT_FLOAT128_TANH   tanhq\n#define BOOST_CSTDFLOAT_FLOAT128_ASINH  asinhq\n#define BOOST_CSTDFLOAT_FLOAT128_ACOSH  acoshq\n#define BOOST_CSTDFLOAT_FLOAT128_ATANH  atanhq\n#define BOOST_CSTDFLOAT_FLOAT128_TGAMMA tgammaq\n#else // BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS\n#define BOOST_CSTDFLOAT_FLOAT128_EXP    expq_patch\n#define BOOST_CSTDFLOAT_FLOAT128_SINH   sinhq_patch\n#define BOOST_CSTDFLOAT_FLOAT128_COSH   coshq_patch\n#define BOOST_CSTDFLOAT_FLOAT128_TANH   tanhq_patch\n#define BOOST_CSTDFLOAT_FLOAT128_ASINH  asinhq_patch\n#define BOOST_CSTDFLOAT_FLOAT128_ACOSH  acoshq_patch\n#define BOOST_CSTDFLOAT_FLOAT128_ATANH  atanhq_patch\n#define BOOST_CSTDFLOAT_FLOAT128_TGAMMA tgammaq_patch\n#endif // BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS\n//   begin more functions\n#define BOOST_CSTDFLOAT_FLOAT128_REMAINDER   remainderq\n#define BOOST_CSTDFLOAT_FLOAT128_REMQUO      remquoq\n#define BOOST_CSTDFLOAT_FLOAT128_FMA         fmaq\n#define BOOST_CSTDFLOAT_FLOAT128_FMAX        fmaxq\n#define BOOST_CSTDFLOAT_FLOAT128_FMIN        fminq\n#define BOOST_CSTDFLOAT_FLOAT128_FDIM        fdimq\n#define BOOST_CSTDFLOAT_FLOAT128_NAN         nanq\n//#define BOOST_CSTDFLOAT_FLOAT128_EXP2      exp2q\n#define BOOST_CSTDFLOAT_FLOAT128_LOG2        log2q\n#define BOOST_CSTDFLOAT_FLOAT128_LOG1P       log1pq\n#define BOOST_CSTDFLOAT_FLOAT128_CBRT        cbrtq\n#define BOOST_CSTDFLOAT_FLOAT128_HYPOT       hypotq\n#define BOOST_CSTDFLOAT_FLOAT128_ERF         erfq\n#define BOOST_CSTDFLOAT_FLOAT128_ERFC        erfcq\n#define BOOST_CSTDFLOAT_FLOAT128_LLROUND     llroundq\n#define BOOST_CSTDFLOAT_FLOAT128_LROUND      lroundq\n#define BOOST_CSTDFLOAT_FLOAT128_ROUND       roundq\n#define BOOST_CSTDFLOAT_FLOAT128_NEARBYINT   nearbyintq\n#define BOOST_CSTDFLOAT_FLOAT128_LLRINT      llrintq\n#define BOOST_CSTDFLOAT_FLOAT128_LRINT       lrintq\n#define BOOST_CSTDFLOAT_FLOAT128_RINT        rintq\n#define BOOST_CSTDFLOAT_FLOAT128_MODF        modfq\n#define BOOST_CSTDFLOAT_FLOAT128_SCALBLN     scalblnq\n#define BOOST_CSTDFLOAT_FLOAT128_SCALBN      scalbnq\n#define BOOST_CSTDFLOAT_FLOAT128_ILOGB       ilogbq\n#define BOOST_CSTDFLOAT_FLOAT128_LOGB        logbq\n#define BOOST_CSTDFLOAT_FLOAT128_NEXTAFTER   nextafterq\n//#define BOOST_CSTDFLOAT_FLOAT128_NEXTTOWARD nexttowardq\n#define BOOST_CSTDFLOAT_FLOAT128_COPYSIGN    copysignq\n#define BOOST_CSTDFLOAT_FLOAT128_SIGNBIT     signbitq\n//#define BOOST_CSTDFLOAT_FLOAT128_FPCLASSIFY fpclassifyq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISFINITE   isfiniteq\n#define BOOST_CSTDFLOAT_FLOAT128_ISINF        isinfq\n#define BOOST_CSTDFLOAT_FLOAT128_ISNAN        isnanq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISNORMAL   isnormalq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISGREATER  isgreaterq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISGREATEREQUAL isgreaterequalq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISLESS         islessq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISLESSEQUAL    islessequalq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISLESSGREATER  islessgreaterq\n//#define BOOST_CSTDFLOAT_FLOAT128_ISUNORDERED    isunorderedq\n//   end more functions\n#endif\n\n// Implement quadruple-precision <cmath> functions in the namespace\n// boost::math::cstdfloat::detail. Subsequently inject these into the\n// std namespace via *using* directive.\n\n// Begin with some forward function declarations. Also implement patches\n// for compilers that have broken float128 exponential functions.\n\nextern \"C\" int quadmath_snprintf(char*, std::size_t, const char*, ...) throw();\n\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_LDEXP(boost::math::cstdfloat::detail::float_internal128_t, int) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_FREXP(boost::math::cstdfloat::detail::float_internal128_t, int*) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_FABS(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_FLOOR(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_CEIL(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_SQRT(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_TRUNC(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_POW(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_LOG(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_LOG10(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_SIN(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_COS(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_TAN(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ASIN(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ACOS(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ATAN(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_FMOD(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ATAN2(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_LGAMMA(boost::math::cstdfloat::detail::float_internal128_t) throw();\n\n//   begin more functions\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_REMAINDER(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_REMQUO(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t, int*) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_FMA(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_FMAX(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_FMIN(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_FDIM(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_NAN(const char*) throw();\n//extern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_EXP2         (boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_LOG2(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_LOG1P(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_CBRT(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_HYPOT(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_ERF(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_ERFC(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" long long int                                BOOST_CSTDFLOAT_FLOAT128_LLROUND(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" long int                                   BOOST_CSTDFLOAT_FLOAT128_LROUND(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_ROUND(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_NEARBYINT(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" long long int                                BOOST_CSTDFLOAT_FLOAT128_LLRINT(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" long int                                   BOOST_CSTDFLOAT_FLOAT128_LRINT(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_RINT(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_MODF(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t*) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_SCALBLN(boost::math::cstdfloat::detail::float_internal128_t, long int) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_SCALBN(boost::math::cstdfloat::detail::float_internal128_t, int) throw();\nextern \"C\" int                                      BOOST_CSTDFLOAT_FLOAT128_ILOGB(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_LOGB(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_NEXTAFTER(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\n//extern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_NEXTTOWARD   (boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_COPYSIGN(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" int                                                  BOOST_CSTDFLOAT_FLOAT128_SIGNBIT(boost::math::cstdfloat::detail::float_internal128_t) throw();\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_FPCLASSIFY   (boost::math::cstdfloat::detail::float_internal128_t) throw();\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISFINITE      (boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" int                                                  BOOST_CSTDFLOAT_FLOAT128_ISINF(boost::math::cstdfloat::detail::float_internal128_t) throw();\nextern \"C\" int                                                  BOOST_CSTDFLOAT_FLOAT128_ISNAN(boost::math::cstdfloat::detail::float_internal128_t) throw();\n//extern \"C\" boost::math::cstdfloat::detail::float_internal128_t  BOOST_CSTDFLOAT_FLOAT128_ISNORMAL   (boost::math::cstdfloat::detail::float_internal128_t) throw();\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISGREATER   (boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISGREATEREQUAL(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISLESS      (boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISLESSEQUAL   (boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISLESSGREATER(boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\n//extern \"C\" int                                                BOOST_CSTDFLOAT_FLOAT128_ISUNORDERED   (boost::math::cstdfloat::detail::float_internal128_t, boost::math::cstdfloat::detail::float_internal128_t) throw();\n //   end more functions\n\n#if !defined(BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS)\n\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_EXP(boost::math::cstdfloat::detail::float_internal128_t x) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_EXPM1(boost::math::cstdfloat::detail::float_internal128_t x) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_SINH(boost::math::cstdfloat::detail::float_internal128_t x) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_COSH(boost::math::cstdfloat::detail::float_internal128_t x) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_TANH(boost::math::cstdfloat::detail::float_internal128_t x) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ASINH(boost::math::cstdfloat::detail::float_internal128_t x) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ACOSH(boost::math::cstdfloat::detail::float_internal128_t x) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ATANH(boost::math::cstdfloat::detail::float_internal128_t x) throw();\nextern \"C\" boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_TGAMMA(boost::math::cstdfloat::detail::float_internal128_t x) throw();\n \n#else // BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS\n\n// Forward declaration of the patched exponent function, exp(x).\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_EXP(boost::math::cstdfloat::detail::float_internal128_t x);\n\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_EXPM1(boost::math::cstdfloat::detail::float_internal128_t x)\n{\n   // Compute exp(x) - 1 for x small.\n\n   // Use an order-36 polynomial approximation of the exponential function\n   // in the range of (-ln2 < x < ln2). Scale the argument to this range\n   // and subsequently multiply the result by 2^n accordingly.\n\n   // Derive the polynomial coefficients with Mathematica(R) by generating\n   // a table of high-precision values of exp(x) in the range (-ln2 < x < ln2)\n   // and subsequently applying the built-in *Fit* function.\n\n   // Table[{x, Exp[x] - 1}, {x, -Log[2], Log[2], 1/180}]\n   // N[%, 120]\n   // Fit[%, {x, x^2, x^3, x^4, x^5, x^6, x^7, x^8, x^9, x^10, x^11, x^12,\n   //         x^13, x^14, x^15, x^16, x^17, x^18, x^19, x^20, x^21, x^22,\n   //         x^23, x^24, x^25, x^26, x^27, x^28, x^29, x^30, x^31, x^32,\n   //         x^33, x^34, x^35, x^36}, x]\n\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\n\n   float_type sum;\n\n   if (x > BOOST_FLOAT128_C(0.693147180559945309417232121458176568075500134360255))\n   {\n      sum = ::BOOST_CSTDFLOAT_FLOAT128_EXP(x) - float_type(1);\n   }\n   else\n   {\n      // Compute the polynomial approximation of exp(alpha).\n      sum = ((((((((((((((((((((((((((((((((((((float_type(BOOST_FLOAT128_C(2.69291698127774166063293705964720493864630783729857438187365E-42))  * x\n         + float_type(BOOST_FLOAT128_C(9.70937085471487654794114679403710456028986572118859594614033E-41))) * x\n         + float_type(BOOST_FLOAT128_C(3.38715585158055097155585505318085512156885389014410753080500E-39))) * x\n         + float_type(BOOST_FLOAT128_C(1.15162718532861050809222658798662695267019717760563645440433E-37))) * x\n         + float_type(BOOST_FLOAT128_C(3.80039074689434663295873584133017767349635602413675471702393E-36))) * x\n         + float_type(BOOST_FLOAT128_C(1.21612504934087520075905434734158045947460467096773246215239E-34))) * x\n         + float_type(BOOST_FLOAT128_C(3.76998762883139753126119821241037824830069851253295480396224E-33))) * x\n         + float_type(BOOST_FLOAT128_C(1.13099628863830344684998293828608215735777107850991029729440E-31))) * x\n         + float_type(BOOST_FLOAT128_C(3.27988923706982293204067897468714277771890104022419696770352E-30))) * x\n         + float_type(BOOST_FLOAT128_C(9.18368986379558482800593745627556950089950023355628325088207E-29))) * x\n         + float_type(BOOST_FLOAT128_C(2.47959626322479746949155352659617642905315302382639380521497E-27))) * x\n         + float_type(BOOST_FLOAT128_C(6.44695028438447337900255966737803112935639344283098705091949E-26))) * x\n         + float_type(BOOST_FLOAT128_C(1.61173757109611834904452725462599961406036904573072897122957E-24))) * x\n         + float_type(BOOST_FLOAT128_C(3.86817017063068403772269360016918092488847584660382953555804E-23))) * x\n         + float_type(BOOST_FLOAT128_C(8.89679139245057328674891109315654704307721758924206107351744E-22))) * x\n         + float_type(BOOST_FLOAT128_C(1.95729410633912612308475595397946731738088422488032228717097E-20))) * x\n         + float_type(BOOST_FLOAT128_C(4.11031762331216485847799061511674191805055663711439605760231E-19))) * x\n         + float_type(BOOST_FLOAT128_C(8.22063524662432971695598123977873600603370758794431071426640E-18))) * x\n         + float_type(BOOST_FLOAT128_C(1.56192069685862264622163643500633782667263448653185159383285E-16))) * x\n         + float_type(BOOST_FLOAT128_C(2.81145725434552076319894558300988749849555291507956994126835E-15))) * x\n         + float_type(BOOST_FLOAT128_C(4.77947733238738529743820749111754320727153728139716409114011E-14))) * x\n         + float_type(BOOST_FLOAT128_C(7.64716373181981647590113198578807092707697416852226691068627E-13))) * x\n         + float_type(BOOST_FLOAT128_C(1.14707455977297247138516979786821056670509688396295740818677E-11))) * x\n         + float_type(BOOST_FLOAT128_C(1.60590438368216145993923771701549479323291461578567184216302E-10))) * x\n         + float_type(BOOST_FLOAT128_C(2.08767569878680989792100903212014323125428376052986408239620E-09))) * x\n         + float_type(BOOST_FLOAT128_C(2.50521083854417187750521083854417187750523408006206780016659E-08))) * x\n         + float_type(BOOST_FLOAT128_C(2.75573192239858906525573192239858906525573195144226062684604E-07))) * x\n         + float_type(BOOST_FLOAT128_C(2.75573192239858906525573192239858906525573191310049321957902E-06))) * x\n         + float_type(BOOST_FLOAT128_C(0.00002480158730158730158730158730158730158730158730149317774)))     * x\n         + float_type(BOOST_FLOAT128_C(0.00019841269841269841269841269841269841269841269841293575920)))     * x\n         + float_type(BOOST_FLOAT128_C(0.00138888888888888888888888888888888888888888888888889071045)))     * x\n         + float_type(BOOST_FLOAT128_C(0.00833333333333333333333333333333333333333333333333332986595)))     * x\n         + float_type(BOOST_FLOAT128_C(0.04166666666666666666666666666666666666666666666666666664876)))     * x\n         + float_type(BOOST_FLOAT128_C(0.16666666666666666666666666666666666666666666666666666669048)))     * x\n         + float_type(BOOST_FLOAT128_C(0.50000000000000000000000000000000000000000000000000000000006)))     * x\n         + float_type(BOOST_FLOAT128_C(0.99999999999999999999999999999999999999999999999999999999995)))     * x);\n   }\n\n   return sum;\n}\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_EXP(boost::math::cstdfloat::detail::float_internal128_t x)\n{\n   // Patch the expq() function for a subset of broken GCC compilers\n   // like GCC 4.7, 4.8 on MinGW.\n\n   // Use an order-36 polynomial approximation of the exponential function\n   // in the range of (-ln2 < x < ln2). Scale the argument to this range\n   // and subsequently multiply the result by 2^n accordingly.\n\n   // Derive the polynomial coefficients with Mathematica(R) by generating\n   // a table of high-precision values of exp(x) in the range (-ln2 < x < ln2)\n   // and subsequently applying the built-in *Fit* function.\n\n   // Table[{x, Exp[x] - 1}, {x, -Log[2], Log[2], 1/180}]\n   // N[%, 120]\n   // Fit[%, {x, x^2, x^3, x^4, x^5, x^6, x^7, x^8, x^9, x^10, x^11, x^12,\n   //         x^13, x^14, x^15, x^16, x^17, x^18, x^19, x^20, x^21, x^22,\n   //         x^23, x^24, x^25, x^26, x^27, x^28, x^29, x^30, x^31, x^32,\n   //         x^33, x^34, x^35, x^36}, x]\n\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\n\n   // Scale the argument x to the range (-ln2 < x < ln2).\n   BOOST_CONSTEXPR_OR_CONST float_type one_over_ln2 = float_type(BOOST_FLOAT128_C(1.44269504088896340735992468100189213742664595415299));\n   const float_type x_over_ln2 = x * one_over_ln2;\n\n   boost::int_fast32_t n;\n\n   if (x != x)\n   {\n      // The argument is NaN.\n      return std::numeric_limits<float_type>::quiet_NaN();\n   }\n   else if (::BOOST_CSTDFLOAT_FLOAT128_FABS(x) > BOOST_FLOAT128_C(+0.693147180559945309417232121458176568075500134360255))\n   {\n      // The absolute value of the argument exceeds ln2.\n      n = static_cast<boost::int_fast32_t>(::BOOST_CSTDFLOAT_FLOAT128_FLOOR(x_over_ln2));\n   }\n   else if (::BOOST_CSTDFLOAT_FLOAT128_FABS(x) < BOOST_FLOAT128_C(+0.693147180559945309417232121458176568075500134360255))\n   {\n      // The absolute value of the argument is less than ln2.\n      n = static_cast<boost::int_fast32_t>(0);\n   }\n   else\n   {\n      // The absolute value of the argument is exactly equal to ln2 (in the sense of floating-point equality).\n      return float_type(2);\n   }\n\n   // Check if the argument is very near an integer.\n   const float_type floor_of_x = ::BOOST_CSTDFLOAT_FLOAT128_FLOOR(x);\n\n   if (::BOOST_CSTDFLOAT_FLOAT128_FABS(x - floor_of_x) < float_type(BOOST_CSTDFLOAT_FLOAT128_EPS))\n   {\n      // Return e^n for arguments very near an integer.\n      return boost::math::cstdfloat::detail::pown(BOOST_FLOAT128_C(2.71828182845904523536028747135266249775724709369996), static_cast<boost::int_fast32_t>(floor_of_x));\n   }\n\n   // Compute the scaled argument alpha.\n   const float_type alpha = x - (n * BOOST_FLOAT128_C(0.693147180559945309417232121458176568075500134360255));\n\n   // Compute the polynomial approximation of expm1(alpha) and add to it\n   // in order to obtain the scaled result.\n   const float_type scaled_result = ::BOOST_CSTDFLOAT_FLOAT128_EXPM1(alpha) + float_type(1);\n\n   // Rescale the result and return it.\n   return scaled_result * boost::math::cstdfloat::detail::pown(float_type(2), n);\n}\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_SINH(boost::math::cstdfloat::detail::float_internal128_t x)\n{\n   // Patch the sinhq() function for a subset of broken GCC compilers\n   // like GCC 4.7, 4.8 on MinGW.\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\n\n   // Here, we use the following:\n   // Set: ex  = exp(x)\n   // Set: em1 = expm1(x)\n   // Then\n   // sinh(x) = (ex - 1/ex) / 2         ; for |x| >= 1\n   // sinh(x) = (2em1 + em1^2) / (2ex)  ; for |x| < 1\n\n   const float_type ex = ::BOOST_CSTDFLOAT_FLOAT128_EXP(x);\n\n   if (::BOOST_CSTDFLOAT_FLOAT128_FABS(x) < float_type(+1))\n   {\n      const float_type em1 = ::BOOST_CSTDFLOAT_FLOAT128_EXPM1(x);\n\n      return ((em1 * 2) + (em1 * em1)) / (ex * 2);\n   }\n   else\n   {\n      return (ex - (float_type(1) / ex)) / 2;\n   }\n}\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_COSH(boost::math::cstdfloat::detail::float_internal128_t x)\n{\n   // Patch the coshq() function for a subset of broken GCC compilers\n   // like GCC 4.7, 4.8 on MinGW.\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\n   const float_type ex = ::BOOST_CSTDFLOAT_FLOAT128_EXP(x);\n   return (ex + (float_type(1) / ex)) / 2;\n}\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_TANH(boost::math::cstdfloat::detail::float_internal128_t x)\n{\n   // Patch the tanhq() function for a subset of broken GCC compilers\n   // like GCC 4.7, 4.8 on MinGW.\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\n   const float_type ex_plus = ::BOOST_CSTDFLOAT_FLOAT128_EXP(x);\n   const float_type ex_minus = (float_type(1) / ex_plus);\n   return (ex_plus - ex_minus) / (ex_plus + ex_minus);\n}\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ASINH(boost::math::cstdfloat::detail::float_internal128_t x) throw()\n{\n   // Patch the asinh() function since quadmath does not have it.\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\n   return ::BOOST_CSTDFLOAT_FLOAT128_LOG(x + ::BOOST_CSTDFLOAT_FLOAT128_SQRT((x * x) + float_type(1)));\n}\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ACOSH(boost::math::cstdfloat::detail::float_internal128_t x) throw()\n{\n   // Patch the acosh() function since quadmath does not have it.\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\n   const float_type zp(x + float_type(1));\n   const float_type zm(x - float_type(1));\n\n   return ::BOOST_CSTDFLOAT_FLOAT128_LOG(x + (zp * ::BOOST_CSTDFLOAT_FLOAT128_SQRT(zm / zp)));\n}\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_ATANH(boost::math::cstdfloat::detail::float_internal128_t x) throw()\n{\n   // Patch the atanh() function since quadmath does not have it.\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\n   return (::BOOST_CSTDFLOAT_FLOAT128_LOG(float_type(1) + x)\n      - ::BOOST_CSTDFLOAT_FLOAT128_LOG(float_type(1) - x)) / 2;\n}\ninline boost::math::cstdfloat::detail::float_internal128_t BOOST_CSTDFLOAT_FLOAT128_TGAMMA(boost::math::cstdfloat::detail::float_internal128_t x) throw()\n{\n   // Patch the tgammaq() function for a subset of broken GCC compilers\n   // like GCC 4.7, 4.8 on MinGW.\n   typedef boost::math::cstdfloat::detail::float_internal128_t float_type;\n\n   if (x > float_type(0))\n   {\n      return ::BOOST_CSTDFLOAT_FLOAT128_EXP(::BOOST_CSTDFLOAT_FLOAT128_LGAMMA(x));\n   }\n   else if (x < float_type(0))\n   {\n      // For x < 0, compute tgamma(-x) and use the reflection formula.\n      const float_type positive_x = -x;\n      float_type gamma_value = ::BOOST_CSTDFLOAT_FLOAT128_TGAMMA(positive_x);\n      const float_type floor_of_positive_x = ::BOOST_CSTDFLOAT_FLOAT128_FLOOR(positive_x);\n\n      // Take the reflection checks (slightly adapted) from <boost/math/gamma.hpp>.\n      const bool floor_of_z_is_equal_to_z = (positive_x == ::BOOST_CSTDFLOAT_FLOAT128_FLOOR(positive_x));\n\n      BOOST_CONSTEXPR_OR_CONST float_type my_pi = BOOST_FLOAT128_C(3.14159265358979323846264338327950288419716939937511);\n\n      if (floor_of_z_is_equal_to_z)\n      {\n         const bool is_odd = ((boost::int32_t(floor_of_positive_x) % boost::int32_t(2)) != boost::int32_t(0));\n\n         return (is_odd ? -std::numeric_limits<float_type>::infinity()\n            : +std::numeric_limits<float_type>::infinity());\n      }\n\n      const float_type sinpx_value = x * ::BOOST_CSTDFLOAT_FLOAT128_SIN(my_pi * x);\n\n      gamma_value *= sinpx_value;\n\n      const bool result_is_too_large_to_represent = ((::BOOST_CSTDFLOAT_FLOAT128_FABS(gamma_value) < float_type(1))\n         && (((std::numeric_limits<float_type>::max)() * ::BOOST_CSTDFLOAT_FLOAT128_FABS(gamma_value)) < my_pi));\n\n      if (result_is_too_large_to_represent)\n      {\n         const bool is_odd = ((boost::int32_t(floor_of_positive_x) % boost::int32_t(2)) != boost::int32_t(0));\n\n         return (is_odd ? -std::numeric_limits<float_type>::infinity()\n            : +std::numeric_limits<float_type>::infinity());\n      }\n\n      gamma_value = -my_pi / gamma_value;\n\n      if ((gamma_value > float_type(0)) || (gamma_value < float_type(0)))\n      {\n         return gamma_value;\n      }\n      else\n      {\n         // The value of gamma is too small to represent. Return 0.0 here.\n         return float_type(0);\n      }\n   }\n   else\n   {\n      // Gamma of zero is complex infinity. Return NaN here.\n      return std::numeric_limits<float_type>::quiet_NaN();\n   }\n}\n#endif // BOOST_CSTDFLOAT_BROKEN_FLOAT128_MATH_FUNCTIONS\n\n// Define the quadruple-precision <cmath> functions in the namespace boost::math::cstdfloat::detail.\n\nnamespace boost {\n   namespace math {\n      namespace cstdfloat {\n         namespace detail {\n            inline   boost::math::cstdfloat::detail::float_internal128_t ldexp(boost::math::cstdfloat::detail::float_internal128_t x, int n) { return ::BOOST_CSTDFLOAT_FLOAT128_LDEXP(x, n); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t frexp(boost::math::cstdfloat::detail::float_internal128_t x, int* pn) { return ::BOOST_CSTDFLOAT_FLOAT128_FREXP(x, pn); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t fabs(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_FABS(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t abs(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_FABS(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t floor(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_FLOOR(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t ceil(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_CEIL(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t sqrt(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_SQRT(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t trunc(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_TRUNC(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t exp(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_EXP(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t expm1(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_EXPM1(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t pow(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t a) { return ::BOOST_CSTDFLOAT_FLOAT128_POW(x, a); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t pow(boost::math::cstdfloat::detail::float_internal128_t x, int a) { return ::BOOST_CSTDFLOAT_FLOAT128_POW(x, boost::math::cstdfloat::detail::float_internal128_t(a)); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t log(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LOG(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t log10(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LOG10(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t sin(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_SIN(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t cos(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_COS(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t tan(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_TAN(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t asin(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ASIN(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t acos(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ACOS(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t atan(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ATAN(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t sinh(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_SINH(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t cosh(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_COSH(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t tanh(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_TANH(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t asinh(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ASINH(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t acosh(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ACOSH(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t atanh(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ATANH(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t fmod(boost::math::cstdfloat::detail::float_internal128_t a, boost::math::cstdfloat::detail::float_internal128_t b) { return ::BOOST_CSTDFLOAT_FLOAT128_FMOD(a, b); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t atan2(boost::math::cstdfloat::detail::float_internal128_t y, boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ATAN2(y, x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t lgamma(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LGAMMA(x); }\n            inline   boost::math::cstdfloat::detail::float_internal128_t tgamma(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_TGAMMA(x); }\n            //   begin more functions\n            inline boost::math::cstdfloat::detail::float_internal128_t  remainder(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_REMAINDER(x, y); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  remquo(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y, int* z) { return ::BOOST_CSTDFLOAT_FLOAT128_REMQUO(x, y, z); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  fma(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y, boost::math::cstdfloat::detail::float_internal128_t z) { return BOOST_CSTDFLOAT_FLOAT128_FMA(x, y, z); }\n\n            inline boost::math::cstdfloat::detail::float_internal128_t  fmax(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_FMAX(x, y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               fmax(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return ::BOOST_CSTDFLOAT_FLOAT128_FMAX(x, y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               fmax(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_FMAX(x, y); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  fmin(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_FMIN(x, y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               fmin(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return ::BOOST_CSTDFLOAT_FLOAT128_FMIN(x, y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               fmin(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_FMIN(x, y); }\n\n            inline boost::math::cstdfloat::detail::float_internal128_t  fdim(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_FDIM(x, y); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  nanq(const char* x) { return ::BOOST_CSTDFLOAT_FLOAT128_NAN(x); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  exp2(boost::math::cstdfloat::detail::float_internal128_t x)\n            {\n               return ::BOOST_CSTDFLOAT_FLOAT128_POW(boost::math::cstdfloat::detail::float_internal128_t(2), x);\n            }\n            inline boost::math::cstdfloat::detail::float_internal128_t  log2(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LOG2(x); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  log1p(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LOG1P(x); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  cbrt(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_CBRT(x); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  hypot(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y, boost::math::cstdfloat::detail::float_internal128_t z) { return ::BOOST_CSTDFLOAT_FLOAT128_SQRT(x*x + y * y + z * z); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  hypot(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_HYPOT(x, y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               hypot(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return ::BOOST_CSTDFLOAT_FLOAT128_HYPOT(x, y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               hypot(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_HYPOT(x, y); }\n\n\n            inline boost::math::cstdfloat::detail::float_internal128_t  erf(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ERF(x); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  erfc(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ERFC(x); }\n            inline long long int                                        llround(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LLROUND(x); }\n            inline long int                                             lround(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LROUND(x); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  round(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ROUND(x); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  nearbyint(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_NEARBYINT(x); }\n            inline long long int                                        llrint(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LLRINT(x); }\n            inline long int                                             lrint(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LRINT(x); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  rint(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_RINT(x); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  modf(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t* y) { return ::BOOST_CSTDFLOAT_FLOAT128_MODF(x, y); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  scalbln(boost::math::cstdfloat::detail::float_internal128_t x, long int y) { return ::BOOST_CSTDFLOAT_FLOAT128_SCALBLN(x, y); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  scalbn(boost::math::cstdfloat::detail::float_internal128_t x, int y) { return ::BOOST_CSTDFLOAT_FLOAT128_SCALBN(x, y); }\n            inline int                                                  ilogb(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ILOGB(x); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  logb(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_LOGB(x); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  nextafter(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_NEXTAFTER(x, y); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  nexttoward(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return -(::BOOST_CSTDFLOAT_FLOAT128_NEXTAFTER(-x, -y)); }\n            inline boost::math::cstdfloat::detail::float_internal128_t  copysign   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_COPYSIGN(x, y); }\n            inline bool                                                 signbit   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_SIGNBIT(x); }\n            inline int                                                  fpclassify BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x)\n            {\n               if (::BOOST_CSTDFLOAT_FLOAT128_ISNAN(x))\n                  return FP_NAN;\n               else if (::BOOST_CSTDFLOAT_FLOAT128_ISINF(x))\n                  return FP_INFINITE;\n               else if (x == BOOST_FLOAT128_C(0.0))\n                  return FP_ZERO;\n\n               if (::BOOST_CSTDFLOAT_FLOAT128_FABS(x) < BOOST_CSTDFLOAT_FLOAT128_MIN)\n                  return FP_SUBNORMAL;\n               else\n                  return FP_NORMAL;\n            }\n            inline bool                                      isfinite   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x)\n            {\n               return !::BOOST_CSTDFLOAT_FLOAT128_ISNAN(x) && !::BOOST_CSTDFLOAT_FLOAT128_ISINF(x);\n            }\n            inline bool                                      isinf      BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ISINF(x); }\n            inline bool                                      isnan      BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x) { return ::BOOST_CSTDFLOAT_FLOAT128_ISNAN(x); }\n            inline bool                                      isnormal   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x) { return boost::math::cstdfloat::detail::fpclassify BOOST_PREVENT_MACRO_SUBSTITUTION(x) == FP_NORMAL; }\n            inline bool                                      isgreater      BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y)\n            {\n               if (isnan BOOST_PREVENT_MACRO_SUBSTITUTION(x) || isnan BOOST_PREVENT_MACRO_SUBSTITUTION(y))\n                  return false;\n               return x > y;\n            }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               isgreater BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return isgreater BOOST_PREVENT_MACRO_SUBSTITUTION(x, (boost::math::cstdfloat::detail::float_internal128_t)y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               isgreater BOOST_PREVENT_MACRO_SUBSTITUTION(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return isgreater BOOST_PREVENT_MACRO_SUBSTITUTION((boost::math::cstdfloat::detail::float_internal128_t)x, y); }\n\n            inline bool                                      isgreaterequal BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y)\n            {\n               if (isnan BOOST_PREVENT_MACRO_SUBSTITUTION(x) || isnan BOOST_PREVENT_MACRO_SUBSTITUTION(y))\n                  return false;\n               return x >= y;\n            }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               isgreaterequal BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return isgreaterequal BOOST_PREVENT_MACRO_SUBSTITUTION(x, (boost::math::cstdfloat::detail::float_internal128_t)y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               isgreaterequal BOOST_PREVENT_MACRO_SUBSTITUTION(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return isgreaterequal BOOST_PREVENT_MACRO_SUBSTITUTION((boost::math::cstdfloat::detail::float_internal128_t)x, y); }\n\n            inline bool                                      isless      BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y)\n            {\n               if (isnan BOOST_PREVENT_MACRO_SUBSTITUTION(x) || isnan BOOST_PREVENT_MACRO_SUBSTITUTION(y))\n                  return false;\n               return x < y;\n            }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               isless BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return isless BOOST_PREVENT_MACRO_SUBSTITUTION(x, (boost::math::cstdfloat::detail::float_internal128_t)y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               isless BOOST_PREVENT_MACRO_SUBSTITUTION(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return isless BOOST_PREVENT_MACRO_SUBSTITUTION((boost::math::cstdfloat::detail::float_internal128_t)x, y); }\n\n\n            inline bool                                      islessequal   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y)\n            {\n               if (isnan BOOST_PREVENT_MACRO_SUBSTITUTION(x) || isnan BOOST_PREVENT_MACRO_SUBSTITUTION(y))\n                  return false;\n               return x <= y;\n            }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               islessequal BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return islessequal BOOST_PREVENT_MACRO_SUBSTITUTION(x, (boost::math::cstdfloat::detail::float_internal128_t)y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               islessequal BOOST_PREVENT_MACRO_SUBSTITUTION(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return islessequal BOOST_PREVENT_MACRO_SUBSTITUTION((boost::math::cstdfloat::detail::float_internal128_t)x, y); }\n\n\n            inline bool                                      islessgreater   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y)\n            {\n               if (isnan BOOST_PREVENT_MACRO_SUBSTITUTION(x) || isnan BOOST_PREVENT_MACRO_SUBSTITUTION(y))\n                  return false;\n               return (x < y) || (x > y);\n            }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               islessgreater BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return islessgreater BOOST_PREVENT_MACRO_SUBSTITUTION(x, (boost::math::cstdfloat::detail::float_internal128_t)y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               islessgreater BOOST_PREVENT_MACRO_SUBSTITUTION(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return islessgreater BOOST_PREVENT_MACRO_SUBSTITUTION((boost::math::cstdfloat::detail::float_internal128_t)x, y); }\n\n\n            inline bool                                      isunordered   BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, boost::math::cstdfloat::detail::float_internal128_t y) { return ::BOOST_CSTDFLOAT_FLOAT128_ISNAN(x) || ::BOOST_CSTDFLOAT_FLOAT128_ISNAN(y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               isunordered BOOST_PREVENT_MACRO_SUBSTITUTION(boost::math::cstdfloat::detail::float_internal128_t x, T y) { return isunordered BOOST_PREVENT_MACRO_SUBSTITUTION(x, (boost::math::cstdfloat::detail::float_internal128_t)y); }\n            template <class T>\n            inline typename boost::enable_if_c<\n               boost::is_convertible<T, boost::math::cstdfloat::detail::float_internal128_t>::value\n               && !boost::is_same<T, boost::math::cstdfloat::detail::float_internal128_t>::value, boost::math::cstdfloat::detail::float_internal128_t>::type\n               isunordered BOOST_PREVENT_MACRO_SUBSTITUTION(T x, boost::math::cstdfloat::detail::float_internal128_t y) { return isunordered BOOST_PREVENT_MACRO_SUBSTITUTION((boost::math::cstdfloat::detail::float_internal128_t)x, y); }\n\n\n            //   end more functions\n         }\n      }\n   }\n} // boost::math::cstdfloat::detail\n\n// We will now inject the quadruple-precision <cmath> functions\n// into the std namespace. This is done via *using* directive.\nnamespace std\n{\n   using boost::math::cstdfloat::detail::ldexp;\n   using boost::math::cstdfloat::detail::frexp;\n   using boost::math::cstdfloat::detail::fabs;\n\n#if !(defined(_GLIBCXX_USE_FLOAT128) && defined(__GNUC__) && (__GNUC__ >= 7))\n   using boost::math::cstdfloat::detail::abs;\n#endif\n\n   using boost::math::cstdfloat::detail::floor;\n   using boost::math::cstdfloat::detail::ceil;\n   using boost::math::cstdfloat::detail::sqrt;\n   using boost::math::cstdfloat::detail::trunc;\n   using boost::math::cstdfloat::detail::exp;\n   using boost::math::cstdfloat::detail::expm1;\n   using boost::math::cstdfloat::detail::pow;\n   using boost::math::cstdfloat::detail::log;\n   using boost::math::cstdfloat::detail::log10;\n   using boost::math::cstdfloat::detail::sin;\n   using boost::math::cstdfloat::detail::cos;\n   using boost::math::cstdfloat::detail::tan;\n   using boost::math::cstdfloat::detail::asin;\n   using boost::math::cstdfloat::detail::acos;\n   using boost::math::cstdfloat::detail::atan;\n   using boost::math::cstdfloat::detail::sinh;\n   using boost::math::cstdfloat::detail::cosh;\n   using boost::math::cstdfloat::detail::tanh;\n   using boost::math::cstdfloat::detail::asinh;\n   using boost::math::cstdfloat::detail::acosh;\n   using boost::math::cstdfloat::detail::atanh;\n   using boost::math::cstdfloat::detail::fmod;\n   using boost::math::cstdfloat::detail::atan2;\n   using boost::math::cstdfloat::detail::lgamma;\n   using boost::math::cstdfloat::detail::tgamma;\n\n   //   begin more functions\n   using boost::math::cstdfloat::detail::remainder;\n   using boost::math::cstdfloat::detail::remquo;\n   using boost::math::cstdfloat::detail::fma;\n   using boost::math::cstdfloat::detail::fmax;\n   using boost::math::cstdfloat::detail::fmin;\n   using boost::math::cstdfloat::detail::fdim;\n   using boost::math::cstdfloat::detail::nanq;\n   using boost::math::cstdfloat::detail::exp2;\n   using boost::math::cstdfloat::detail::log2;\n   using boost::math::cstdfloat::detail::log1p;\n   using boost::math::cstdfloat::detail::cbrt;\n   using boost::math::cstdfloat::detail::hypot;\n   using boost::math::cstdfloat::detail::erf;\n   using boost::math::cstdfloat::detail::erfc;\n   using boost::math::cstdfloat::detail::llround;\n   using boost::math::cstdfloat::detail::lround;\n   using boost::math::cstdfloat::detail::round;\n   using boost::math::cstdfloat::detail::nearbyint;\n   using boost::math::cstdfloat::detail::llrint;\n   using boost::math::cstdfloat::detail::lrint;\n   using boost::math::cstdfloat::detail::rint;\n   using boost::math::cstdfloat::detail::modf;\n   using boost::math::cstdfloat::detail::scalbln;\n   using boost::math::cstdfloat::detail::scalbn;\n   using boost::math::cstdfloat::detail::ilogb;\n   using boost::math::cstdfloat::detail::logb;\n   using boost::math::cstdfloat::detail::nextafter;\n   using boost::math::cstdfloat::detail::nexttoward;\n   using boost::math::cstdfloat::detail::copysign;\n   using boost::math::cstdfloat::detail::signbit;\n   using boost::math::cstdfloat::detail::fpclassify;\n   using boost::math::cstdfloat::detail::isfinite;\n   using boost::math::cstdfloat::detail::isinf;\n   using boost::math::cstdfloat::detail::isnan;\n   using boost::math::cstdfloat::detail::isnormal;\n   using boost::math::cstdfloat::detail::isgreater;\n   using boost::math::cstdfloat::detail::isgreaterequal;\n   using boost::math::cstdfloat::detail::isless;\n   using boost::math::cstdfloat::detail::islessequal;\n   using boost::math::cstdfloat::detail::islessgreater;\n   using boost::math::cstdfloat::detail::isunordered;\n   //   end more functions\n\n   //\n   // Very basic iostream operator:\n   //\n   inline std::ostream& operator << (std::ostream& os, __float128 m_value)\n   {\n      std::streamsize digits = os.precision();\n      std::ios_base::fmtflags f = os.flags();\n      std::string s;\n\n      char buf[100];\n      boost::scoped_array<char> buf2;\n      std::string format = \"%\";\n      if (f & std::ios_base::showpos)\n         format += \"+\";\n      if (f & std::ios_base::showpoint)\n         format += \"#\";\n      format += \".*\";\n      if (digits == 0)\n         digits = 36;\n      format += \"Q\";\n      if (f & std::ios_base::scientific)\n         format += \"e\";\n      else if (f & std::ios_base::fixed)\n         format += \"f\";\n      else\n         format += \"g\";\n\n      int v = quadmath_snprintf(buf, 100, format.c_str(), digits, m_value);\n\n      if ((v < 0) || (v >= 99))\n      {\n         int v_max = v;\n         buf2.reset(new char[v + 3]);\n         v = quadmath_snprintf(&buf2[0], v_max + 3, format.c_str(), digits, m_value);\n         if (v >= v_max + 3)\n         {\n            BOOST_THROW_EXCEPTION(std::runtime_error(\"Formatting of float128_type failed.\"));\n         }\n         s = &buf2[0];\n      }\n      else\n         s = buf;\n      std::streamsize ss = os.width();\n      if (ss > static_cast<std::streamsize>(s.size()))\n      {\n         char fill = os.fill();\n         if ((os.flags() & std::ios_base::left) == std::ios_base::left)\n            s.append(static_cast<std::string::size_type>(ss - s.size()), fill);\n         else\n            s.insert(static_cast<std::string::size_type>(0), static_cast<std::string::size_type>(ss - s.size()), fill);\n      }\n\n      return os << s;\n   }\n\n\n} // namespace std\n\n// We will now remove the preprocessor symbols representing quadruple-precision <cmath>\n// functions from the preprocessor.\n\n#undef BOOST_CSTDFLOAT_FLOAT128_LDEXP\n#undef BOOST_CSTDFLOAT_FLOAT128_FREXP\n#undef BOOST_CSTDFLOAT_FLOAT128_FABS\n#undef BOOST_CSTDFLOAT_FLOAT128_FLOOR\n#undef BOOST_CSTDFLOAT_FLOAT128_CEIL\n#undef BOOST_CSTDFLOAT_FLOAT128_SQRT\n#undef BOOST_CSTDFLOAT_FLOAT128_TRUNC\n#undef BOOST_CSTDFLOAT_FLOAT128_EXP\n#undef BOOST_CSTDFLOAT_FLOAT128_EXPM1\n#undef BOOST_CSTDFLOAT_FLOAT128_POW\n#undef BOOST_CSTDFLOAT_FLOAT128_LOG\n#undef BOOST_CSTDFLOAT_FLOAT128_LOG10\n#undef BOOST_CSTDFLOAT_FLOAT128_SIN\n#undef BOOST_CSTDFLOAT_FLOAT128_COS\n#undef BOOST_CSTDFLOAT_FLOAT128_TAN\n#undef BOOST_CSTDFLOAT_FLOAT128_ASIN\n#undef BOOST_CSTDFLOAT_FLOAT128_ACOS\n#undef BOOST_CSTDFLOAT_FLOAT128_ATAN\n#undef BOOST_CSTDFLOAT_FLOAT128_SINH\n#undef BOOST_CSTDFLOAT_FLOAT128_COSH\n#undef BOOST_CSTDFLOAT_FLOAT128_TANH\n#undef BOOST_CSTDFLOAT_FLOAT128_ASINH\n#undef BOOST_CSTDFLOAT_FLOAT128_ACOSH\n#undef BOOST_CSTDFLOAT_FLOAT128_ATANH\n#undef BOOST_CSTDFLOAT_FLOAT128_FMOD\n#undef BOOST_CSTDFLOAT_FLOAT128_ATAN2\n#undef BOOST_CSTDFLOAT_FLOAT128_LGAMMA\n#undef BOOST_CSTDFLOAT_FLOAT128_TGAMMA\n\n//   begin more functions\n#undef BOOST_CSTDFLOAT_FLOAT128_REMAINDER\n#undef BOOST_CSTDFLOAT_FLOAT128_REMQUO\n#undef BOOST_CSTDFLOAT_FLOAT128_FMA\n#undef BOOST_CSTDFLOAT_FLOAT128_FMAX\n#undef BOOST_CSTDFLOAT_FLOAT128_FMIN\n#undef BOOST_CSTDFLOAT_FLOAT128_FDIM\n#undef BOOST_CSTDFLOAT_FLOAT128_NAN\n#undef BOOST_CSTDFLOAT_FLOAT128_EXP2\n#undef BOOST_CSTDFLOAT_FLOAT128_LOG2\n#undef BOOST_CSTDFLOAT_FLOAT128_LOG1P\n#undef BOOST_CSTDFLOAT_FLOAT128_CBRT\n#undef BOOST_CSTDFLOAT_FLOAT128_HYPOT\n#undef BOOST_CSTDFLOAT_FLOAT128_ERF\n#undef BOOST_CSTDFLOAT_FLOAT128_ERFC\n#undef BOOST_CSTDFLOAT_FLOAT128_LLROUND\n#undef BOOST_CSTDFLOAT_FLOAT128_LROUND\n#undef BOOST_CSTDFLOAT_FLOAT128_ROUND\n#undef BOOST_CSTDFLOAT_FLOAT128_NEARBYINT\n#undef BOOST_CSTDFLOAT_FLOAT128_LLRINT\n#undef BOOST_CSTDFLOAT_FLOAT128_LRINT\n#undef BOOST_CSTDFLOAT_FLOAT128_RINT\n#undef BOOST_CSTDFLOAT_FLOAT128_MODF\n#undef BOOST_CSTDFLOAT_FLOAT128_SCALBLN\n#undef BOOST_CSTDFLOAT_FLOAT128_SCALBN\n#undef BOOST_CSTDFLOAT_FLOAT128_ILOGB\n#undef BOOST_CSTDFLOAT_FLOAT128_LOGB\n#undef BOOST_CSTDFLOAT_FLOAT128_NEXTAFTER\n#undef BOOST_CSTDFLOAT_FLOAT128_NEXTTOWARD\n#undef BOOST_CSTDFLOAT_FLOAT128_COPYSIGN\n#undef BOOST_CSTDFLOAT_FLOAT128_SIGNBIT\n#undef BOOST_CSTDFLOAT_FLOAT128_FPCLASSIFY\n#undef BOOST_CSTDFLOAT_FLOAT128_ISFINITE\n#undef BOOST_CSTDFLOAT_FLOAT128_ISINF\n#undef BOOST_CSTDFLOAT_FLOAT128_ISNAN\n#undef BOOST_CSTDFLOAT_FLOAT128_ISNORMAL\n#undef BOOST_CSTDFLOAT_FLOAT128_ISGREATER\n#undef BOOST_CSTDFLOAT_FLOAT128_ISGREATEREQUAL\n#undef BOOST_CSTDFLOAT_FLOAT128_ISLESS\n#undef BOOST_CSTDFLOAT_FLOAT128_ISLESSEQUAL\n#undef BOOST_CSTDFLOAT_FLOAT128_ISLESSGREATER\n#undef BOOST_CSTDFLOAT_FLOAT128_ISUNORDERED\n//   end more functions\n\n#endif // Not BOOST_CSTDFLOAT_NO_LIBQUADMATH_SUPPORT (i.e., the user would like to have libquadmath support)\n\n#endif // _BOOST_CSTDFLOAT_CMATH_2014_02_15_HPP_\n\n", "meta": {"hexsha": "ba77b2a7ad6beece5d78e992856237f3c2110649", "size": 74176, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/cstdfloat/cstdfloat_cmath.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/math/cstdfloat/cstdfloat_cmath.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/math/cstdfloat/cstdfloat_cmath.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 67.7406392694, "max_line_length": 307, "alphanum_fraction": 0.7213519198, "num_tokens": 20568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863698, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.41732787594187887}}
{"text": "// Original work Copyright (c) 2016, University of Minnesota\n// Modified work Copyright 2019, Yue Peng\n//\n// ADMM-Elastic Uses the BSD 2-Clause License (http://www.opensource.org/licenses/BSD-2-Clause)\n// Redistribution and use in source and binary forms, with or without modification, are\n// permitted provided that the following conditions are met:\n// 1. Redistributions of source code must retain the above copyright notice, this list of\n//    conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list\n//    of conditions and the following disclaimer in the documentation and/or other materials\n//    provided with the distribution.\n// THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR  A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF MINNESOTA, DULUTH OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef ADMM_PASSIVECOLLISION_HPP\n#define ADMM_PASSIVECOLLISION_HPP\n\n#include <Eigen/Dense>\n#include \"Collider.hpp\"\n#include \"MCL/TetMesh.hpp\"\n#include \"MCL/TriangleMesh.hpp\"\n#include \"MCL/BVH.hpp\"\n\nnamespace admm {\n\nclass Floor : public PassiveCollision {\npublic:\n\ttypedef Eigen::Matrix<double,3,1> Vec3;\n\n\tdouble m_y;\n\tFloor( double y ) : m_y(y) {}\n\tvoid signed_distance( const Vec3 &x, Payload &p ) const {\n\t\tdouble dx = ( x[1] - m_y );\n\t\tif( dx > p.dx ){ return; }\n\t\tp.dx = dx;\n\t\tp.point = Vec3(x[0],m_y,x[2]);\n\t\tp.normal = Vec3(0,1,0);\n\t}\n};\n\n\nclass Sphere : public PassiveCollision {\npublic:\n\ttypedef Eigen::Matrix<double,3,1> Vec3;\n\n\tVec3 center;\n\tdouble rad;\n\tSphere( const Vec3 &c, double r ) : center(c), rad(r) {}\n\tvoid signed_distance( const Vec3 &x, Payload &p ) const {\n\t\tVec3 dir = x - center;\n\t\tdouble dx = dir.norm() - rad;\n\t\tif( dx > p.dx ){ return; }\n\t\tdir.normalize();\n\t\tp.dx = dx;\n\t\tp.point = center + dir*rad;\n\t\tp.normal = dir;\n\t}\n};\n\n\nclass PassiveMesh : public PassiveCollision {\npublic:\n\ttypedef Eigen::Matrix<double,3,1> Vec3;\n\tmcl::bvh::AABBTree<float,3> tri_tree;\n\tmcl::bvh::AABBTree<float,4> tet_tree;\n\n\tstd::shared_ptr<mcl::TetMesh> mesh;\n\tPassiveMesh( std::shared_ptr<mcl::TetMesh> mesh_ ) : mesh(mesh_){ update_bvh(); }\n\n\tvoid update_bvh(){\n\t\tmesh->need_faces();\n\t\ttri_tree.init( &mesh->faces[0][0], &mesh->vertices[0][0], mesh->faces.size() );\n\t\ttet_tree.init( &mesh->tets[0][0], &mesh->vertices[0][0], mesh->tets.size() );\n\t}\n\n\tvoid signed_distance( const Vec3 &x, Payload &p ) const {\n\n\t\t// First, check if objet is inside mesh\n\t\tmcl::bvh::PointInTet<float> p_in_mesh( x.cast<float>(), &mesh->vertices[0][0], &mesh->tets[0][0] );\n\t\tbool hit = tet_tree.traverse( p_in_mesh );\n\n\t\t// If there is an odd number of intersections, we are inside the mesh\n\t\tif( hit ){\n\t\t\tmcl::bvh::NearestTriangle<float> nearest_tri( x.cast<float>(), &mesh->vertices[0][0], &mesh->faces[0][0] );\n\t\t\ttri_tree.traverse( nearest_tri );\n\n\t\t\tmcl::Vec3i hit_face = mesh->faces[ nearest_tri.hit_tri ];\n\t\t\tconst mcl::Vec3f &p0 = mesh->vertices[hit_face[0]];\n\t\t\tconst mcl::Vec3f &p1 = mesh->vertices[hit_face[1]];\n\t\t\tconst mcl::Vec3f &p2 = mesh->vertices[hit_face[2]];\n\t\t\tmcl::Vec3f norm = (p1-p0).cross(p2-p0);\n\t\t\tnorm.normalize();\n\n\t\t\t// Set the payload data\n\t\t\tp.dx = -1.0*(nearest_tri.proj.cast<double>()-x).norm();\n\t\t\tp.point = nearest_tri.proj.cast<double>();\n\t\t\tp.normal = norm.cast<double>();\n\t\t}\n\n\t} // end signed distance\n};\n\n\n/*\nclass PassiveMesh : public PassiveCollision {\npublic:\n\ttypedef Eigen::Matrix<double,3,1> Vec3;\n\tmcl::bvh::AABBTree<float,3> m_tree;\n\n\tstd::shared_ptr<mcl::TriangleMesh> mesh;\n\tPassiveMesh( std::shared_ptr<mcl::TriangleMesh> mesh_ ) : mesh(mesh_){ update_bvh(); }\n\n\tvoid update_bvh(){\n\t\tm_tree.init( &mesh->faces[0][0], &mesh->vertices[0][0], mesh->faces.size() );\n\t}\n\n\tvoid signed_distance( const Vec3 &x, Payload &p ) const {\n\n\t\t// First, check if objet is inside mesh\n\t\tmcl::bvh::RayMultiHit<float> p_in_mesh( x.cast<float>(), &mesh->vertices[0][0], &mesh->faces[0][0] );\n\t\tm_tree.traverse( p_in_mesh );\n\n\t\t// If there is an odd number of intersections, we are inside the mesh\n\t\tif( p_in_mesh.hit_count % 2 == 1 ){\n\t\t\tmcl::bvh::NearestTriangle<float> nearest_tri( x.cast<float>(), &mesh->vertices[0][0], &mesh->faces[0][0] );\n\t\t\tm_tree.traverse( nearest_tri );\n\n\t\t\tmcl::Vec3i hit_face = mesh->faces[ nearest_tri.hit_tri ];\n\t\t\tconst mcl::Vec3f &p0 = mesh->vertices[hit_face[0]];\n\t\t\tconst mcl::Vec3f &p1 = mesh->vertices[hit_face[1]];\n\t\t\tconst mcl::Vec3f &p2 = mesh->vertices[hit_face[2]];\n\t\t\tmcl::Vec3f norm = (p1-p0).cross(p2-p0);\n\t\t\tnorm.normalize();\n\n\t\t\t// Set the payload data\n\t\t\tp.dx = -1.0*(nearest_tri.proj.cast<double>()-x).norm();\n\t\t\tp.point = nearest_tri.proj.cast<double>();\n\t\t\tp.normal = norm.cast<double>();\n\t\t}\n\n\t} // end signed distance\n};\n*/\n\n\n} // end of namespace admm\n\n#endif\n", "meta": {"hexsha": "3811614c70e1229d3e10e94865bca17a7b30342d", "size": 5302, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "admm_anderson_xzu/src/PassiveObject.hpp", "max_stars_repo_name": "bldeng/AA-ADMM", "max_stars_repo_head_hexsha": "d954518e8e379c378fd40ac72e2bcc64ff01cc57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2019-11-07T15:05:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T00:40:12.000Z", "max_issues_repo_path": "admm_anderson_xzu/src/PassiveObject.hpp", "max_issues_repo_name": "wangxihao/AA-ADMM", "max_issues_repo_head_hexsha": "d954518e8e379c378fd40ac72e2bcc64ff01cc57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "admm_anderson_xzu/src/PassiveObject.hpp", "max_forks_repo_name": "wangxihao/AA-ADMM", "max_forks_repo_head_hexsha": "d954518e8e379c378fd40ac72e2bcc64ff01cc57", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T02:47:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T07:00:44.000Z", "avg_line_length": 34.2064516129, "max_line_length": 110, "alphanum_fraction": 0.690116937, "num_tokens": 1546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.4173132766637645}}
{"text": "/*\n * car_longitudinal_model.hpp\n *\n * Created on: Oct 30, 2018 05:47\n * Description:\n *\n * Copyright (c) 2018 Ruixiang Du (rdu)\n */\n\n#ifndef CAR_LONGITUDINAL_MODEL_HPP\n#define CAR_LONGITUDINAL_MODEL_HPP\n\n#include <boost/numeric/odeint.hpp>\n\nnamespace robotnav {\n// Reference:\n//  [1] Althoff, M., and A. Mergel. 2011. “Comparison of Markov Chain\n//  Abstraction\n//      and Monte Carlo Simulation for the Safety Assessment of Autonomous\n//      Cars.” IEEE Transactions on Intelligent Transportation Systems 12 (4):\n//      1237–47.\nclass CarLongitudinalModel {\n public:\n  using control_type = double;\n  using state_type = std::vector<double>;\n\n  CarLongitudinalModel(control_type u) : u_(u) {}\n\n  static constexpr double v_sw = 7.3;    // switching velocity\n  static constexpr double v_max = 18.0;  // 18 m/s ~= 40 mph\n  static constexpr double a_max = 7.0;   // 7.0 m/s^2\n\n  // x1 = s, x2 = v\n  void operator()(const state_type &x, state_type &xd, const double);\n\n private:\n  control_type u_ = 0;\n};\n}  // namespace robotnav\n#endif /* CAR_LONGITUDINAL_MODEL_HPP */\n", "meta": {"hexsha": "0afe65c02f0de5aa51d3fe33b7517448e01aa19b", "size": 1068, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/modules/planning/decision/reachability/include/reachability/details/car_longitudinal_model.hpp", "max_stars_repo_name": "rxdu/robotnav", "max_stars_repo_head_hexsha": "fb36ac4ae9372f027c41e7be526ac1e72f094051", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-02T09:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T06:36:42.000Z", "max_issues_repo_path": "src/modules/planning/decision/reachability/include/reachability/details/car_longitudinal_model.hpp", "max_issues_repo_name": "rxdu/robotnav", "max_issues_repo_head_hexsha": "fb36ac4ae9372f027c41e7be526ac1e72f094051", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-30T02:01:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T08:06:40.000Z", "max_forks_repo_path": "src/modules/planning/decision/reachability/include/reachability/details/car_longitudinal_model.hpp", "max_forks_repo_name": "rxdu/robotnav", "max_forks_repo_head_hexsha": "fb36ac4ae9372f027c41e7be526ac1e72f094051", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-02T09:16:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T03:06:48.000Z", "avg_line_length": 26.0487804878, "max_line_length": 78, "alphanum_fraction": 0.6947565543, "num_tokens": 316, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145997, "lm_q2_score": 0.5506073655352403, "lm_q1q2_score": 0.41724716840858567}}
{"text": "//!\n//! @file       HEmatrix.cpp\n//! @brief      implementing functions for matrix operations\n//!\n//! @author     Miran Kim\n//! @date       Dec. 1, 2017\n//! @copyright  GNU Pub License\n//!\n\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <sys/time.h>\n\n#include <cmath>\n#include <chrono>\n#include <map>\n#include <math.h>  // pow\n#include <sys/time.h>\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <cstdlib>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include \"math.h\"\n#include <cassert>\n#include <random>\n#include <string>\n#include <iomanip>\n\n#include <NTL/xdouble.h>\n#include <NTL/ZZ.h>\n#include \"NTL/RR.h\"\n#include <NTL/ZZX.h>\n#include \"NTL/mat_RR.h\"\n#include \"NTL/vec_RR.h\"\n\n#include \"../src/Scheme.h\"\n#include \"../src/SecretKey.h\"\n#include \"../src/SchemeAlgo.h\"\n\n#include \"matrix.h\"\n#include \"HEmatrix.h\"\n\n\n#define timing 0 // use for printing out the timing\n\n\n//!@ Function: read the parameters\nvoid readHEMatpar(HEMatpar& HEmatpar, long nrows, long ncols, long pBits, long cBits, long logQ, long subdim, long nbatching){\n    HEmatpar.nrows = nrows;\n    HEmatpar.ncols = ncols;\n    \n    long dim = nrows;\n    if(dim < ncols) {\n        dim = ncols;\n    }\n    \n    HEmatpar.dim = (1<< (long)ceil(log2(dim)));  //! power of two\n    HEmatpar.dim1 = HEmatpar.dim - 1;\n    HEmatpar.logdim = (long) log2(HEmatpar.dim);\n    HEmatpar.sqrdim = (long) ceil(sqrt(HEmatpar.dim));\n    \n    HEmatpar.pBits = pBits;\n    HEmatpar.cBits = cBits;\n    HEmatpar.logQ = logQ;\n    \n    HEmatpar.subdim = subdim;  //! used for non-squared matrix multiplication\n    HEmatpar.nbatching = (1<< (long)ceil(log2(nbatching)));\n    \n    if(nbatching == 1){\n        HEmatpar.nslots = HEmatpar.dim * HEmatpar.dim;  //! just encode a single matrix\n    }\n    else{\n        HEmatpar.nslots = (HEmatpar.dim * HEmatpar.dim) * HEmatpar.nbatching;\n    }\n}\n\n\nvoid HEmatrix::encryptRmat(Ciphertext& ctxt, mat_RR& mat, long logp){\n    complex<double>* cmsg = new complex<double>[HEmatpar.nslots];\n    \n    NTL_EXEC_RANGE(HEmatpar.nrows, first, last);\n    for(int i = first; i < last; ++i){\n        for(long j = 0; j < HEmatpar.ncols; ++j){\n            double dtemp;\n            conv(dtemp, mat[i][j]);\n            cmsg[i*HEmatpar.dim + j].real(dtemp);\n        }\n    }\n    NTL_EXEC_RANGE_END;\n    \n    ctxt = scheme.encrypt(cmsg, HEmatpar.nslots, logp, HEmatpar.logQ);\n    delete[] cmsg;\n}\n\nvoid HEmatrix::decryptRmat(mat_RR& mat, Ciphertext& ctxt){\n    complex<double>* cmsg = scheme.decrypt(secretKey, ctxt);\n    mat.SetDims(HEmatpar.dim, HEmatpar.dim);\n    \n    long k = 0;\n    for(long i = 0; i < HEmatpar.dim; ++i){\n        for(long j = 0; j < HEmatpar.dim; ++j){\n            mat[i][j] = to_RR(cmsg[k].real());\n            k++;\n        }\n    }\n    delete[] cmsg;\n}\n\nvoid HEmatrix::encryptParallelRmat(Ciphertext& ctxt, mat_RR*& mat, long logp, long nbatching){\n    complex<double>* cmsg = new complex<double>[HEmatpar.nslots];\n    double* dtemp = new double[nbatching];\n    \n    NTL_EXEC_RANGE(nbatching, first, last);\n    for(int k = first; k < last; ++k){\n        // encode the kth matrix\n        for(long i = 0; i < HEmatpar.nrows; ++i){\n            for(long j = 0; j < HEmatpar.ncols; ++j){\n                conv(dtemp[k], mat[k][i][j]);\n                cmsg[(i*HEmatpar.dim + j)* HEmatpar.nbatching + k].real(dtemp[k]);\n            }\n        }\n    }\n    NTL_EXEC_RANGE_END;\n    \n    ctxt = scheme.encrypt(cmsg, HEmatpar.nslots, logp, HEmatpar.logQ);\n    \n    delete[] cmsg;\n    delete[] dtemp;\n}\n\nvoid HEmatrix::decryptParallelRmat(mat_RR*& mat, Ciphertext& ctxt){\n    complex<double>* cmsg = scheme.decrypt(secretKey, ctxt);\n    mat = new mat_RR[HEmatpar.nbatching];\n    \n    for(long k = 0; k < HEmatpar.nbatching; ++k){\n        mat[k].SetDims(HEmatpar.dim, HEmatpar.dim);\n        long l = 0;\n        for(long i = 0; i < HEmatpar.dim; ++i){\n            for(long j = 0; j < HEmatpar.dim; ++j){\n                mat[k][i][j] = to_RR(cmsg[l * HEmatpar.nbatching + k].real());\n                l++;\n            }\n        }\n    }\n    delete[] cmsg;\n}\n\nvoid HEmatrix::msgleftRotate(complex<double>*& res, complex<double>* vals, long dim, long nrot){\n    long nshift = (nrot)%HEmatpar.nslots;\n    \n    long k = dim - nshift;\n    for(long j = 0; j < k; ++j){\n        res[j] = vals[j + nshift];\n    }\n    for(long j = k; j < dim; ++j){\n        res[j] = vals[j - k];\n    }\n}\n\nvoid HEmatrix::msgrightRotate(complex<double>*& res, complex<double>* vals, long dim, long nrot){\n    long nshift = (nrot)%HEmatpar.nslots;\n    long k = dim - nshift;\n    \n    //! vals[0],vals[1],....,vals[d-nrot-1])\n    for(long j = 0; j < k; ++j){\n        res[nshift + j] = vals[j];\n    }\n    \n    //! (vals[d-nrot],vals[d-nrot+1],...,vals[d-1])\n    for(long j = k; j < dim; ++j){\n        res[j - k] = vals[j];\n    }\n}\n\nvoid HEmatrix::msgleftRotateAndEqual(complex<double>*& vals, long dim, long nrot){\n    complex<double>* res = new complex<double>[dim];\n\n    long nshift = (nrot)%HEmatpar.nslots;\n    long k = dim - nshift;\n    \n    for(long j = 0; j < k; ++j){\n        res[j] = vals[j + nshift];\n    }\n    for(long j = k; j < dim; ++j){\n        res[j] = vals[j - k];\n    }\n    for(long j = 0; j < dim; ++j){\n        vals[j] = res[j];\n    }\n}\n\nvoid HEmatrix::msgrightRotateAndEqual(complex<double>*& vals, long dim, long nrot){\n    complex<double>* res = new complex<double>[dim];\n    \n    long nshift = (nrot)%HEmatpar.nslots;\n    long k = dim - nrot;\n    \n    for(long j = 0; j < k; ++j){\n        res[nshift + j] = vals[j];\n    }\n    for(long j = k; j < dim; ++j){\n        res[j - k] = vals[j];\n    }\n    for(long j = 0; j < dim; ++j){\n        vals[j] = res[j];\n    }\n}\n\n\n//------------------------------------------------\n//! Transposition\n//------------------------------------------------\n\n//! Output: transpoly (\"2*dim\"), generate the polynomial for transpose\n//! Originally we need to generate\n//! rho(p[k]; -(d-1)*sqrt(r)i) where k = sqrt(r) * i + j, r = nrows, 0 <= i, j < sqrt(r)\n// (0, 1,   ..., d-1),  (-, d+1, ..., 2d-1)\n\nvoid HEmatrix::genTransPoly(ZZX*& transpoly){\n    complex<double>** lvals   = new complex<double>*[HEmatpar.dim];\n    complex<double>** rvals  = new complex<double>*[HEmatpar.dim];\n    long dsquare = (HEmatpar.nslots) - 1;\n    transpoly = new ZZX[2 * HEmatpar.dim];\n    long dimsqrdim = HEmatpar.sqrdim * HEmatpar.dim1;   //! (d-1) * sqrt(d)\n    \n    // k = i * sqrt(d) + j < d\n    bool btmp;\n    if((HEmatpar.dim % HEmatpar.sqrdim) == 0){\n        btmp = false;   //! all the terms have the same numbers\n    }\n    else{\n        btmp = true;\n    }\n    long ibound = (long) ceil((double)HEmatpar.dim/HEmatpar.sqrdim); //! number of \"i\"\n    \n    NTL_EXEC_RANGE(ibound, first, last);\n    for(int i = first; i < last; ++i){\n        long jbound = HEmatpar.sqrdim;\n        if ((btmp)&&(i == ibound - 1)){   //! last term\n            jbound = (HEmatpar.dim % HEmatpar.sqrdim);\n        }\n        \n        for(long j = 0; j < jbound; ++j){\n            long k = i * HEmatpar.sqrdim + j;\n            \n            lvals[k] = new complex<double>[HEmatpar.nslots];\n            rvals[k] = new complex<double>[HEmatpar.nslots];\n            \n            for(long l = 0; l < HEmatpar.dim - k; ++l){\n                long dtemp = l * (HEmatpar.dim + 1) + k;\n                lvals[k][dtemp].real(1.0);\n                rvals[k][dsquare - dtemp].real(1.0);\n            }\n            \n            msgrightRotateAndEqual(lvals[k], HEmatpar.nslots, i*dimsqrdim);  //! Lrho(P[k],-dsqrt(d)*i)\n            msgleftRotateAndEqual(rvals[k], HEmatpar.nslots, i*dimsqrdim);   //! Rrho(P[k],-dsqrt(d)*i)\n            \n            transpoly[k] = scheme.context.encode(lvals[k], HEmatpar.nslots, HEmatpar.cBits);\n            transpoly[k + HEmatpar.dim] = scheme.context.encode(rvals[k], HEmatpar.nslots, HEmatpar.cBits);\n        }\n    }\n    NTL_EXEC_RANGE_END;\n    delete[] lvals;\n    delete[] rvals;\n}\n\nvoid HEmatrix::transpose(Ciphertext& res, Ciphertext& ctxt, ZZX*& transpoly){\n    \n    long dimsqrdim = HEmatpar.sqrdim * HEmatpar.dim1;   // (d-1) * sqrt(d)\n    \n    bool btmp;\n    if((HEmatpar.dim % HEmatpar.sqrdim) == 0){\n        btmp = false;   //! all the terms have the same numbers\n    }\n    else{\n        btmp = true;\n    }\n    long ibound = (long) ceil((double)HEmatpar.dim/HEmatpar.sqrdim); //! number of \"i\"\n    \n    Ciphertext* Babyctxt1 = new Ciphertext[HEmatpar.sqrdim];\n    Ciphertext* Babyctxt2 = new Ciphertext[HEmatpar.sqrdim];\n    \n    Ciphertext** ltemp = new Ciphertext*[HEmatpar.sqrdim];\n    Ciphertext** rtemp = new Ciphertext*[HEmatpar.sqrdim];\n    \n    for(long i = 0; i < HEmatpar.sqrdim; ++i){\n        ltemp[i] = new Ciphertext[HEmatpar.sqrdim];\n        rtemp[i] = new Ciphertext[HEmatpar.sqrdim];\n    }\n    \n    //! diagonal\n    res = scheme.multByPoly(ctxt, transpoly[0], HEmatpar.cBits);\n    \n    Babyctxt1[0] = ctxt;\n    Babyctxt2[0] = ctxt;\n    \n    //! Babyctxt1[j] = rho(v; j * (d-1))\n    //! res[j] = rho(-, (d-1)*srt(d) * i) * rho(v; j * (d-1))\n    //HEmatpar.sqrdim\n    \n    NTL_EXEC_RANGE(HEmatpar.sqrdim - 1, first, last);\n    for(long j = first; j < last; ++j){\n        long j1 = (j + 1);  // 1 <= j1 <= sqrdim - 1\n\n        Babyctxt1[j1] = scheme.leftRotate(ctxt, j1 * (HEmatpar.dim1));   // prepare baby ctxt\n        Babyctxt2[j1] = scheme.rightRotate(ctxt, j1 * (HEmatpar.dim1));\n\n        ltemp[0][j1] = scheme.multByPoly(Babyctxt1[j1], transpoly[j1], HEmatpar.cBits);\n        rtemp[0][j1] = scheme.multByPoly(Babyctxt2[j1], transpoly[j1 + HEmatpar.dim], HEmatpar.cBits);\n\n        scheme.addAndEqual(ltemp[0][j1], rtemp[0][j1]);\n    }\n    NTL_EXEC_RANGE_END;\n\n    for(long j = 1; j < HEmatpar.sqrdim; ++j){\n        scheme.addAndEqual(res, ltemp[0][j]);\n    }\n\n    //! 1 <= i < d\n    //! [k]: rho(p[k];-dsqrt(d)*i1) * rho(v, j*(d-1)) -> rot by dsqrt(d)*i\n    //! res[j] = rho( rho(-, (d-1)*srt(d) * i) * rho(v; j * (d-1)) ; i * (d-1)\\sqrt(d) )\n    \n    NTL_EXEC_RANGE(ibound - 1, first, last);\n    for(long i = first; i < last; ++i){\n        long jbound = HEmatpar.sqrdim;\n        if (btmp &&(i == (ibound - 2))){\n            jbound = (HEmatpar.dim % HEmatpar.sqrdim);\n        }\n        \n        long i1 = i + 1;\n        long k = (i1) * HEmatpar.sqrdim;\n\n        //! 0 <= j < sqrdim\n        NTL_EXEC_RANGE(jbound, first, last);\n        for(long j = first; j < last; ++j){\n            ltemp[i1][j] = scheme.multByPoly(Babyctxt1[j], transpoly[k + j], HEmatpar.cBits);\n            rtemp[i1][j] = scheme.multByPoly(Babyctxt2[j], transpoly[k + j + HEmatpar.dim], HEmatpar.cBits);\n        }\n        NTL_EXEC_RANGE_END;\n\n        for(long j = 1; j < jbound; ++j){\n            scheme.addAndEqual(ltemp[i1][0], ltemp[i1][j]);\n            scheme.addAndEqual(rtemp[i1][0], rtemp[i1][j]);\n        }\n\n        scheme.leftRotateAndEqual(ltemp[i1][0], i1 * dimsqrdim);\n        scheme.rightRotateAndEqual(rtemp[i1][0], i1 * dimsqrdim);\n\n        scheme.addAndEqual(ltemp[i1][0], rtemp[i1][0]);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    for(long i = 1; i < ibound; ++i){\n        scheme.addAndEqual(res, ltemp[i][0]);\n    }\n    \n    scheme.reScaleByAndEqual(res, HEmatpar.cBits);   // Rescaling by scalarBits\n    \n    delete[] ltemp;\n    delete[] rtemp;\n}\n\nvoid HEmatrix::genTransPoly_Parallel(ZZX*& transpoly){\n    \n    bool btmp;\n    if((HEmatpar.dim % HEmatpar.sqrdim) == 0){ btmp = false; }    //! all the terms have the same numbers\n    else{ btmp = true; }\n    long ibound = (long) ceil((double)HEmatpar.dim/HEmatpar.sqrdim); //! number of \"i\"\n    \n    complex<double>** lvals   = new complex<double>*[HEmatpar.dim];\n    complex<double>** rvals  = new complex<double>*[HEmatpar.dim];\n    \n    transpoly = new ZZX[2 * HEmatpar.dim];\n    \n    long shiftunit = HEmatpar.sqrdim * HEmatpar.dim1 * HEmatpar.nbatching ;   //! (d-1) * sqrt(d) * l\n    long dsquare = ((HEmatpar.dim * HEmatpar.dim) - 1) *HEmatpar.nbatching ;  //! (d^2-1) * l\n    \n    //! k = (i * sqrt(d) + j)  < d\n    //! poly[k] = poly[i * sqrt(d) + j]  -> rho(poly[k]; i * (d-1)*sqrt(d) * l)\n    for(int i = 0; i < ibound; ++i){\n        long jbound = HEmatpar.sqrdim;\n        if ((btmp)&&(i == ibound - 1)){\n            jbound = (HEmatpar.dim % HEmatpar.sqrdim);\n        }\n        for(long j = 0; j < jbound; ++j){\n            long k = (i * HEmatpar.sqrdim + j);\n        \n            lvals[k] = new complex<double>[HEmatpar.nslots];\n            rvals[k] = new complex<double>[HEmatpar.nslots];\n            \n            for(long l = 0; l < HEmatpar.dim - k; ++l){\n                long dtemp= (l*(HEmatpar.dim+1) + k) * HEmatpar.nbatching;  //! starting index\n        \n                for(long n = 0; n < HEmatpar.nbatching; ++n){\n                    lvals[k][dtemp + n].real(1.0);\n                    rvals[k][dsquare - dtemp + n].real(1.0);\n                }\n            }\n        \n            //! Lrho(P[k], - i * (d-1) * sqrt(d) * (nbathcing))\n            //! Rrho(P[k],- i * (d-1) * sqrt(d) * (nbathcing))\n            msgrightRotateAndEqual(lvals[k], HEmatpar.nslots, i * shiftunit);\n            msgleftRotateAndEqual(rvals[k], HEmatpar.nslots, i * shiftunit);\n            \n            transpoly[k] = scheme.context.encode(lvals[k], HEmatpar.nslots, HEmatpar.cBits);\n            transpoly[k + HEmatpar.dim] = scheme.context.encode(rvals[k], HEmatpar.nslots, HEmatpar.cBits);\n            \n        }\n    }\n    delete[] lvals;\n    delete[] rvals;\n}\n\nvoid HEmatrix::transpose_Parallel(Ciphertext& res, Ciphertext& ctxt, ZZX*& transpoly){\n    long shiftunit = HEmatpar.sqrdim * HEmatpar.dim1 * HEmatpar.nbatching;  // (d-1) * sqrt(d) * l\n    long unit  = (HEmatpar.dim1) * HEmatpar.nbatching;\n    \n    bool btmp;\n    if((HEmatpar.dim % HEmatpar.sqrdim) == 0){ btmp = false; }    //! all the terms have the same numbers\n    else{ btmp = true; }\n    long ibound = (long) ceil((double)HEmatpar.dim/HEmatpar.sqrdim); //! number of \"i\"\n    \n    Ciphertext* Babyctxt1 = new Ciphertext[HEmatpar.sqrdim];\n    Ciphertext* Babyctxt2 = new Ciphertext[HEmatpar.sqrdim];\n    \n    Ciphertext** ltemp = new Ciphertext*[HEmatpar.sqrdim];\n    Ciphertext** rtemp = new Ciphertext*[HEmatpar.sqrdim];\n    \n    for(long i = 0; i < HEmatpar.sqrdim; ++i){\n        ltemp[i] = new Ciphertext[HEmatpar.sqrdim];\n        rtemp[i] = new Ciphertext[HEmatpar.sqrdim];\n    }\n    \n    //-------------------------\n    // i = 0, sqrt(d) polynomials\n    //-------------------------\n    res = scheme.multByPoly(ctxt, transpoly[0], HEmatpar.cBits);\n\n    Babyctxt1[0] = ctxt;\n    Babyctxt2[0] = ctxt;\n    \n    NTL_EXEC_RANGE(HEmatpar.sqrdim - 1, first, last);\n    for(long j = first; j < last; ++j){\n        long j1 = (j + 1);  //! 1 <= j1 <= sqrdim - 1\n        \n        // rho(v; j * (d-1) * l)\n        Babyctxt1[j1] = scheme.leftRotate(ctxt, j1 * unit);\n        Babyctxt2[j1] = scheme.rightRotate(ctxt, j1 * unit);\n        \n        ltemp[0][j1] = scheme.multByPoly(Babyctxt1[j1], transpoly[j1], HEmatpar.cBits);\n        rtemp[0][j1] = scheme.multByPoly(Babyctxt2[j1], transpoly[j1 + HEmatpar.dim], HEmatpar.cBits);\n        \n        scheme.addAndEqual(ltemp[0][j1], rtemp[0][j1]);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    for(long j = 1; j < HEmatpar.sqrdim; ++j){\n        scheme.addAndEqual(res, ltemp[0][j]);\n    }\n    \n    //! 1 <= i < d\n    //! [k]: rho(p[k];-dsqrt(d)*i1) * rho(v, j*(d-1)) -> rot by dsqrt(d)*i\n    \n    NTL_EXEC_RANGE(ibound - 1, first, last);\n    for(long i = first; i < last; ++i){\n        long jbound = HEmatpar.sqrdim;\n        if ((btmp)&&(i == ibound - 2)){\n            jbound = (HEmatpar.dim % HEmatpar.sqrdim);\n        }\n        \n        long i1 = i + 1;\n        long k = (i1) * HEmatpar.sqrdim;\n        \n        NTL_EXEC_RANGE(jbound, first, last);\n        for(long j = first; j < last; ++j){\n            ltemp[i1][j] = scheme.multByPoly(Babyctxt1[j], transpoly[k + j], HEmatpar.cBits);\n            rtemp[i1][j] = scheme.multByPoly(Babyctxt2[j], transpoly[k + j + HEmatpar.dim], HEmatpar.cBits);\n        }\n        NTL_EXEC_RANGE_END;\n        \n        for(long j = 1; j < jbound; ++j){\n            scheme.addAndEqual(ltemp[i1][0], ltemp[i1][j]);\n            scheme.addAndEqual(rtemp[i1][0], rtemp[i1][j]);\n        }\n        \n        scheme.leftRotateAndEqual(ltemp[i1][0], i1 * shiftunit);\n        scheme.rightRotateAndEqual(rtemp[i1][0], i1 * shiftunit);\n        \n        scheme.addAndEqual(ltemp[i1][0], rtemp[i1][0]);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    for(long i = 1; i < ibound; ++i){\n        scheme.addAndEqual(res, ltemp[i][0]);\n    }\n\n    scheme.reScaleByAndEqual(res, HEmatpar.cBits);   //! Rescaling by scalarBits\n    \n    delete[] ltemp;\n    delete[] rtemp;\n}\n\n\n//------------------------------------------------\n//! Shift\n//------------------------------------------------\n\n// num = 0: dimension d-1\n// subdim - 1: dimension (subdim-1)\nvoid HEmatrix::genShiftPoly(ZZX*& shiftpoly, long num){\n    long length = HEmatpar.dim1;\n    if(num != 0){\n        length = num;\n    }\n    \n    complex<double>** vals = new complex<double>*[length];\n    shiftpoly = new ZZX[length];\n    \n    // i: shifted by (i+1)\n    NTL_EXEC_RANGE(length, first, last);\n    for(int i = first; i < last; ++i){\n        vals[i] = new complex<double>[HEmatpar.nslots];\n        \n        for(long j = 0; j < HEmatpar.dim; ++j){\n            for(long k = 0; k < i + 1; ++k){\n                vals[i][j * HEmatpar.dim + k].real(1.0);\n            }\n        }\n        shiftpoly[i] = scheme.context.encode(vals[i], HEmatpar.nslots, HEmatpar.cBits);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    delete[] vals;\n}\n\nvoid HEmatrix::shiftBycols(Ciphertext& res, Ciphertext& ctxt,  long k , ZZX*& shiftpoly){\n    //! ctemp = Enc(m[1],.., m[k],0,,,0 | ....)\n    Ciphertext ctemp = scheme.multByPoly(ctxt, shiftpoly[k-1], HEmatpar.cBits);\n    scheme.reScaleByAndEqual(ctemp, HEmatpar.cBits);\n    \n    //! ctemp = Enc(0,,,0, m[k+1],...,m[d] | ....)\n    res = scheme.modDownTo(ctxt, ctemp.logq);\n    scheme.subAndEqual(res, ctemp);\n    \n    scheme.rightRotateAndEqual(ctemp, HEmatpar.dim - k);\n    scheme.leftRotateAndEqual(res, k);\n    scheme.addAndEqual(res, ctemp);\n}\n\nvoid HEmatrix::genShiftPoly_Parallel(ZZX*& shiftpoly){\n    complex<double>** vals   = new complex<double>*[HEmatpar.dim1];\n    shiftpoly = new ZZX[HEmatpar.dim1];\n    \n    NTL_EXEC_RANGE(HEmatpar.dim1, first, last);\n    for(int i = first; i < last; ++i){\n        vals[i] = new complex<double>[HEmatpar.nslots];\n        \n        for(long j = 0; j < HEmatpar.dim; ++j){\n            for(long k = 0; k < i + 1; ++k){\n                long dtemp = (j * HEmatpar.dim + k) * HEmatpar.nbatching;\n                \n                for(long n = 0; n < HEmatpar.nbatching; ++n){\n                    vals[i][dtemp + n].real(1.0);\n                }\n            }\n        }\n        shiftpoly[i] = scheme.context.encode(vals[i], HEmatpar.nslots, HEmatpar.cBits);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    delete[] vals;\n}\n\nvoid HEmatrix::shiftBycols_Parallel(Ciphertext& res, Ciphertext& ctxt, long k, ZZX*& shiftpoly){\n    //! ctemp = Enc(m[1],.., m[k],0,,,0 | ....)\n    Ciphertext ctemp = scheme.multByPoly(ctxt, shiftpoly[k-1], HEmatpar.cBits);\n    scheme.reScaleByAndEqual(ctemp, HEmatpar.cBits);\n    \n    //! ctemp = Enc(0,,,0, m[k+1],...,m[d] | ....)\n    res = scheme.modDownTo(ctxt, ctemp.logq);\n    scheme.subAndEqual(res, ctemp);\n    \n    scheme.rightRotateAndEqual(ctemp, (HEmatpar.dim - k) * HEmatpar.nbatching);\n    scheme.leftRotateAndEqual(res, k * HEmatpar.nbatching);\n    scheme.addAndEqual(res, ctemp);\n}\n\n//------------------------------------------------\n//! Matrix multiplication\n//------------------------------------------------\n\n//!@ Output: Initpoly[0] (constant left-polynomials for Amat): 0,1,....,d-1\n//!@         Initpoly[1] (constant right-polynomials for Amat):  -1,...,-(d-1)\n//!!         Initpoly[2] (constant polynomials for Bmat)\n\nvoid HEmatrix::genMultPoly(ZZX**& Initpoly){\n    bool btmp;\n    if((HEmatpar.dim % HEmatpar.sqrdim) == 0){\n        btmp = false;\n    }\n    else{\n        btmp = true;\n    }\n    long ibound = (long) ceil((double) HEmatpar.dim/HEmatpar.sqrdim); //! number of \"i\"\n    \n    Initpoly = new ZZX*[3];\n    \n    Initpoly[0] =  new ZZX[HEmatpar.dim];\n    Initpoly[1] =  new ZZX[HEmatpar.dim];\n    Initpoly[2] =  new ZZX[HEmatpar.dim];\n    \n    complex<double>** fvals1   = new complex<double>*[HEmatpar.dim];\n    complex<double>** fvals2   = new complex<double>*[HEmatpar.dim];\n    complex<double>** bvals    = new complex<double>*[HEmatpar.dim];\n\n    NTL_EXEC_RANGE(ibound, first, last);\n    for(int i = first; i < last; ++i){\n        long jbound = HEmatpar.sqrdim;\n        if ((btmp)&&(i == ibound - 1)){\n            jbound = (HEmatpar.dim % HEmatpar.sqrdim);\n        }\n        \n        for(long j = 0; j < jbound; ++j){\n            long k = i * HEmatpar.sqrdim + j;\n            fvals1[k] = new complex<double>[HEmatpar.nslots];\n            fvals2[k] = new complex<double>[HEmatpar.nslots];\n            bvals[k] = new complex<double>[HEmatpar.nslots];\n            \n            for(long l = 0; l < HEmatpar.dim - k; ++l){\n                fvals1[k][k * HEmatpar.dim + l].real(1.0);\n            }\n            msgleftRotate(fvals2[k], fvals1[k], HEmatpar.nslots, k*(2*HEmatpar.dim - 1));\n            \n            msgrightRotateAndEqual(fvals1[k], HEmatpar.nslots, i*HEmatpar.sqrdim);\n            Initpoly[0][k] = scheme.context.encode(fvals1[k], HEmatpar.nslots, HEmatpar.cBits);\n        \n            msgleftRotateAndEqual(fvals2[k], HEmatpar.nslots, i*HEmatpar.sqrdim);\n            Initpoly[1][k] = scheme.context.encode(fvals2[k], HEmatpar.nslots, HEmatpar.cBits);\n            \n            for(long l = 0; l < HEmatpar.dim; ++l){\n                bvals[k][l * HEmatpar.dim + k].real(1.0);\n            }\n            msgrightRotateAndEqual(bvals[k], HEmatpar.nslots, i*HEmatpar.sqrdim*HEmatpar.dim);\n            Initpoly[2][k] = scheme.context.encode(bvals[k], HEmatpar.nslots, HEmatpar.cBits);\n        }\n    }\n    NTL_EXEC_RANGE_END;\n\n    delete[] fvals1;\n    delete[] fvals2;\n    delete[] bvals;\n}\n\nvoid HEmatrix::genInitCtxt(Ciphertext& resA, Ciphertext& resB, Ciphertext& Actxt, Ciphertext& Bctxt, ZZX**& poly){\n    bool btmp;\n    if((HEmatpar.dim % HEmatpar.sqrdim) == 0){ btmp = false; }    //! all the terms have the same numbers\n    else{ btmp = true; }\n    long ibound = (long) ceil((double)HEmatpar.dim/HEmatpar.sqrdim); //! number of \"i\"\n    \n    Ciphertext** Actemp1 = new Ciphertext*[HEmatpar.sqrdim]; //! update right polynomial\n    Ciphertext** Actemp2 = new Ciphertext*[HEmatpar.sqrdim]; //! update right polynomial\n    Ciphertext** Bctemp = new Ciphertext*[HEmatpar.sqrdim];\n    \n    for(long i = 0; i < HEmatpar.sqrdim; ++i){\n        Actemp1[i] = new Ciphertext[HEmatpar.sqrdim];\n        Actemp2[i] = new Ciphertext[HEmatpar.sqrdim];\n        Bctemp[i]  = new Ciphertext[HEmatpar.sqrdim];\n    }\n    \n    //! 0. Store some ciphertexts (0,1,...,d-1), (,d+1,...2d-1)\n    //! v, lrho(v;1), lrho(v;2), ..., lrho(v;d-1)\n    //! -, rrho(v;1), rrho(v;2), ..., rrho(v;d-1)\n    \n    Ciphertext* BaByctxt1  = new Ciphertext[HEmatpar.dim];\n    Ciphertext* BaByctxt2  = new Ciphertext[HEmatpar.dim];\n    Ciphertext* BaByctxtB  = new Ciphertext[HEmatpar.dim];\n    \n    BaByctxt1[0] = Actxt;\n    BaByctxt2[0] = Actxt;\n    BaByctxtB[0] = Bctxt;\n    \n    //! i = 0:   Actxts[0] = v[0] + p1 * v[1] + ... + p[sqr(d)-1] *  v[sqr(d)-1]\n    resA = scheme.multByPoly(BaByctxt1[0], poly[0][0], HEmatpar.cBits);\n    resB = scheme.multByPoly(BaByctxtB[0], poly[2][0], HEmatpar.cBits);\n    \n    NTL_EXEC_RANGE(HEmatpar.sqrdim - 1, first, last);\n    for(long j = first; j < last; ++j){\n        long j1 = (j + 1);\n        BaByctxt1[j1] = scheme.leftRotate(Actxt, j1);\n        BaByctxt2[j1] = scheme.rightRotate(Actxt, j1);\n        BaByctxtB[j1] = scheme.leftRotate(Bctxt, (j1)*HEmatpar.dim);\n        \n        Actemp1[0][j1] = scheme.multByPoly(BaByctxt1[j1], poly[0][j1], HEmatpar.cBits);\n        Actemp2[0][j1] = scheme.multByPoly(BaByctxt2[j1], poly[1][j1], HEmatpar.cBits);\n        Bctemp[0][j1]  = scheme.multByPoly(BaByctxtB[j1], poly[2][j1], HEmatpar.cBits);\n        \n        scheme.addAndEqual(Actemp1[0][j1], Actemp2[0][j1]);\n    }\n    NTL_EXEC_RANGE_END;\n\n    for(long j = 1; j < HEmatpar.sqrdim; ++j){\n        scheme.addAndEqual(resA, Actemp1[0][j]);\n        scheme.addAndEqual(resB, Bctemp[0][j]);\n    }\n    \n    Ciphertext* Actxts1 = new Ciphertext[HEmatpar.dim];\n    Ciphertext* Actxts2 = new Ciphertext[HEmatpar.dim];\n    Ciphertext* Bctxts  = new Ciphertext[HEmatpar.dim];\n    \n    NTL_EXEC_RANGE(HEmatpar.dim - HEmatpar.sqrdim, first, last);\n    for(long k = first; k < last; ++k){\n        long k1 = (k + HEmatpar.sqrdim);\n        long i = (long)(k1 / HEmatpar.sqrdim);\n        long j = (long)(k1 % HEmatpar.sqrdim);\n        \n        Actxts1[k1] = scheme.multByPoly(BaByctxt1[j], poly[0][k1], HEmatpar.cBits);\n        Actxts2[k1] = scheme.multByPoly(BaByctxt2[j], poly[1][k1], HEmatpar.cBits);\n        Bctxts[k1]  = scheme.multByPoly(BaByctxtB[j], poly[2][k1], HEmatpar.cBits);\n        \n    }\n    NTL_EXEC_RANGE_END;\n    \n    NTL_EXEC_RANGE(ibound - 1, first, last);\n    for(long k = first; k < last; ++k){\n        long k1 = (k+1) * HEmatpar.sqrdim;\n        long jbound = HEmatpar.sqrdim;\n        if((btmp) && (k == ibound - 2)){\n            jbound = (HEmatpar.dim % HEmatpar.sqrdim);\n        }\n        for(long j = 1; j < jbound; ++j){\n            scheme.addAndEqual(Actxts1[k1], Actxts1[k1+j]);\n            scheme.addAndEqual(Actxts2[k1], Actxts2[k1+j]);\n            scheme.addAndEqual(Bctxts[k1], Bctxts[k1+j]);\n        }\n        \n        long k2 = (k1 - (k1 % HEmatpar.sqrdim));\n        scheme.leftRotateAndEqual(Actxts1[k1], k2);\n        scheme.rightRotateAndEqual(Actxts2[k1], k2);\n        scheme.leftRotateAndEqual(Bctxts[k1], k2 * HEmatpar.dim);\n        \n        scheme.addAndEqual(Actxts1[k1], Actxts2[k1]);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    for(long k = 1; k < ibound; ++k){\n        long k1 = k * HEmatpar.sqrdim;\n        scheme.addAndEqual(resA, Actxts1[k1]);\n        scheme.addAndEqual(resB, Bctxts[k1]);\n    }\n    \n    scheme.reScaleByAndEqual(resA, HEmatpar.cBits);\n    scheme.reScaleByAndEqual(resB, HEmatpar.cBits);\n\n    delete[] Actxts1;\n    delete[] Actxts2;\n    delete[] Bctxts;\n    \n    delete[] Actemp1;\n    delete[] Actemp2;\n    delete[] Bctemp;\n    \n    delete[] BaByctxt1;\n    delete[] BaByctxt2;\n    delete[] BaByctxtB;\n}\n\nvoid HEmatrix::HEmatmul_Hadamard(Ciphertext& res, Ciphertext* Actxts, Ciphertext* Bctxts, long num){\n    //! logq: Actxt > Actxts[0] = Actxts[i + 1] + 2*cBits\n    //! logq: Bctxt > Bctxts[0] = Bctxt[i + 1]\n    \n    long num1 = num - 1;\n    //! 1) Bctxts[0] < Actxts[1] < Actxts[0]\n    if(Actxts[1].logq > Bctxts[0].logq){\n        res = Actxts[0];\n        scheme.modDownToAndEqual(res, Bctxts[0].logq);\n        scheme.multAndEqual(res, Bctxts[0]);   //! log(res) = log Bctxt[0]\n        \n        NTL_EXEC_RANGE(num1, first, last);\n        for(int i = first; i < last; ++i){\n            long i1 = (i + 1);\n            scheme.modDownToAndEqual(Actxts[i1], Bctxts[0].logq);\n            scheme.multAndEqual(Actxts[i1], Bctxts[i1]);   //! log(Actxt[i+1]) = log Bctxt[0]\n        }\n        NTL_EXEC_RANGE_END;\n    }\n    \n    //! 2)  Actxts[1] < Actxts[0] < Bctxts[0]\n    else if(Actxts[0].logq < Bctxts[0].logq){\n        res = Bctxts[0];\n        scheme.modDownToAndEqual(res, Actxts[0].logq);\n        scheme.multAndEqual(res, Actxts[0]);   //! log(res) = log Actxt[0]\n        \n        NTL_EXEC_RANGE(num1, first, last);\n        for(int i = first; i < last; ++i){\n            long i1 = (i + 1);\n            scheme.modDownToAndEqual(Bctxts[i1], Actxts[i1].logq);\n            scheme.multAndEqual(Actxts[i1], Bctxts[i1]);\n        }\n        NTL_EXEC_RANGE_END;\n        \n        scheme.modDownToAndEqual(res, Actxts[1].logq);\n    }\n    \n    //! 3)  Actxts[1] < Bctxts[i] < Actxts[0]: the common case\n    else{\n        res = Actxts[0];\n        scheme.modDownToAndEqual(res, Bctxts[0].logq);\n        scheme.multAndEqual(res, Bctxts[0]);   //! log(res) = log Bctxt[0]\n        \n        NTL_EXEC_RANGE(num1, first, last);\n        for(int i = first; i < last; ++i){\n            long i1 = (i + 1);\n            scheme.modDownToAndEqual(Bctxts[i1], Actxts[i1].logq);\n            scheme.multAndEqual(Actxts[i1], Bctxts[i1]);\n        }\n        NTL_EXEC_RANGE_END;\n        \n        scheme.modDownToAndEqual(res, Actxts[1].logq);\n    }\n    \n    //! aggregate the results and rescaling\n    for(int i = 1; i < num; ++i){\n        scheme.addAndEqual(res, Actxts[i]);\n    }\n    scheme.reScaleByAndEqual(res, res.logp);\n  \n}\n\nvoid HEmatrix::HEmatmul(Ciphertext& res, Ciphertext& Actxt, Ciphertext& Bctxt, ZZX**& Initpoly, ZZX*& shiftpoly){\n    Ciphertext* Actxts = new Ciphertext[HEmatpar.dim];\n    Ciphertext* Bctxts = new Ciphertext[HEmatpar.dim];\n   \n    //! 1. Generate the initial ciphertexts\n    genInitCtxt(Actxts[0], Bctxts[0], Actxt, Bctxt, Initpoly);\n\n    //! 2. Column shifting of Actxt[0], Row shifting of Bctxt[0]\n    NTL_EXEC_RANGE(HEmatpar.dim1, first, last);\n    for(int i = first; i < last; ++i){\n        long i1 = (i + 1);\n        shiftBycols(Actxts[i1], Actxts[0], i1, shiftpoly);\n        Bctxts[i1] = scheme.leftRotate(Bctxts[0], HEmatpar.dim * (i1));\n    }\n    NTL_EXEC_RANGE_END;\n    \n    //! 3. Hadamard multiplication\n    HEmatmul_Hadamard(res, Actxts, Bctxts, HEmatpar.dim);\n    \n    delete[] Actxts;\n    delete[] Bctxts;\n}\n\nvoid HEmatrix::genMultPoly_Parallel(ZZX**& Initpoly){\n    long btmp;\n    if((HEmatpar.dim % HEmatpar.sqrdim) == 0){ btmp = false; }    //! all the terms have the same numbers\n    else{ btmp = true; }\n    long ibound = (long) ceil((double)HEmatpar.dim/HEmatpar.sqrdim); //! number of \"i\"\n\n    \n    Initpoly = new ZZX*[3];\n    \n    Initpoly[0] =  new ZZX[HEmatpar.dim];\n    Initpoly[1] =  new ZZX[HEmatpar.dim];\n    Initpoly[2] =  new ZZX[HEmatpar.dim];\n    \n    complex<double>** fvals1   = new complex<double>*[HEmatpar.dim];\n    complex<double>** fvals2   = new complex<double>*[HEmatpar.dim];\n    complex<double>** bvals    = new complex<double>*[HEmatpar.dim];\n    \n    \n    NTL_EXEC_RANGE(ibound, first, last);\n    for(int i = first; i < last; ++i){\n        long jbound = HEmatpar.sqrdim;\n        if ((btmp) && (i == (ibound - 1))){\n            jbound = (HEmatpar.dim % HEmatpar.sqrdim);\n        }\n        \n        for(long j = 0; j < jbound; ++j){\n            long k = i * HEmatpar.sqrdim + j;\n            fvals1[k] = new complex<double>[HEmatpar.nslots];\n            fvals2[k] = new complex<double>[HEmatpar.nslots];\n            bvals[k] = new complex<double>[HEmatpar.nslots];\n            \n            //! original: k * d <= index <= k * d + d - k -1\n            //! parallel: (k * d) * l + 0 <= ... <= (k * d) * l + (l-1)\n            //!           (k * d + d - k -1) * l + 0 <= ... <= (k * d + d - k -1) * l + (l-1) <  (k * d + d - k -1) * l + l\n            //!           from k * d * l <= index <  (k * d + d - k) * l\n            long start = k * HEmatpar.dim * HEmatpar.nbatching;\n            long end = ( k * HEmatpar.dim + HEmatpar.dim - k) * HEmatpar.nbatching;\n            for(long l = start; l < end; ++l){\n                fvals1[k][l].real(1.0);\n            }\n            \n            msgleftRotate(fvals2[k], fvals1[k], HEmatpar.nslots, k*(2*HEmatpar.dim - 1) * HEmatpar.nbatching);\n            \n            msgrightRotateAndEqual(fvals1[k], HEmatpar.nslots, i*HEmatpar.sqrdim * HEmatpar.nbatching);\n            Initpoly[0][k] = scheme.context.encode(fvals1[k], HEmatpar.nslots, HEmatpar.cBits);\n            \n            msgleftRotateAndEqual(fvals2[k], HEmatpar.nslots, i*HEmatpar.sqrdim * HEmatpar.nbatching);\n            Initpoly[1][k] = scheme.context.encode(fvals2[k], HEmatpar.nslots, HEmatpar.cBits);\n            \n            for(long l = 0; l < HEmatpar.dim; ++l){\n                long dtemp = (l * HEmatpar.dim + k) * HEmatpar.nbatching;\n                \n                for(long n = 0; n < HEmatpar.nbatching; ++n){\n                    bvals[k][dtemp + n].real(1.0);\n                }\n            }\n            msgrightRotateAndEqual(bvals[k], HEmatpar.nslots, i*HEmatpar.sqrdim*HEmatpar.dim * HEmatpar.nbatching);\n            Initpoly[2][k] = scheme.context.encode(bvals[k], HEmatpar.nslots, HEmatpar.cBits);\n        }\n    }\n    NTL_EXEC_RANGE_END;\n    \n    delete[] fvals1;\n    delete[] fvals2;\n    delete[] bvals;\n}\n\nvoid HEmatrix::genInitCtxt_Parallel(Ciphertext& resA, Ciphertext& resB, Ciphertext& Actxt, Ciphertext& Bctxt, ZZX**& poly){\n    bool btmp;\n    if((HEmatpar.dim % HEmatpar.sqrdim) == 0){ btmp = false; }    //! all the terms have the same numbers\n    else{ btmp = true; }\n    long ibound = (long) ceil((double)HEmatpar.dim/HEmatpar.sqrdim); //! number of \"i\"\n\n    \n    Ciphertext** Actemp1 = new Ciphertext*[HEmatpar.sqrdim]; //! update right polynomial\n    Ciphertext** Actemp2 = new Ciphertext*[HEmatpar.sqrdim]; //! update right polynomial\n    Ciphertext** Bctemp = new Ciphertext*[HEmatpar.sqrdim];\n    \n    for(long i = 0; i < HEmatpar.sqrdim; ++i){\n        Actemp1[i] = new Ciphertext[HEmatpar.sqrdim];\n        Actemp2[i] = new Ciphertext[HEmatpar.sqrdim];\n        Bctemp[i]  = new Ciphertext[HEmatpar.sqrdim];\n    }\n\n    //---------------------------------------------------------------\n    // 0. Store some ciphertexts (0,1,...,d-1), ( ,d+1,...2d-1)\n    // v, lrho(v;1), lrho(v;2), ..., lrho(v;d-1)\n    // -, rrho(v;1), rrho(v;2), ..., rrho(v;d-1)\n    \n    Ciphertext* BaByctxt1  = new Ciphertext[HEmatpar.dim];\n    Ciphertext* BaByctxt2  = new Ciphertext[HEmatpar.dim];\n    Ciphertext* BaByctxtB  = new Ciphertext[HEmatpar.dim];\n    \n    BaByctxt1[0] = Actxt;\n    BaByctxt2[0] = Actxt;\n    BaByctxtB[0] = Bctxt;\n    \n    resA = scheme.multByPoly(BaByctxt1[0], poly[0][0], HEmatpar.cBits);\n    resB = scheme.multByPoly(BaByctxtB[0], poly[2][0], HEmatpar.cBits);\n    \n    NTL_EXEC_RANGE(HEmatpar.sqrdim - 1, first, last);\n    for(long j = first; j < last; ++j){\n        long j1 = (j + 1);\n        BaByctxt1[j1] = scheme.leftRotate(Actxt, j1 * HEmatpar.nbatching);\n        BaByctxt2[j1] = scheme.rightRotate(Actxt, j1 * HEmatpar.nbatching);\n        BaByctxtB[j1] = scheme.leftRotate(Bctxt, (j1)*HEmatpar.dim * HEmatpar.nbatching);\n        \n        Actemp1[0][j1] = scheme.multByPoly(BaByctxt1[j1], poly[0][j1], HEmatpar.cBits);\n        Actemp2[0][j1] = scheme.multByPoly(BaByctxt2[j1], poly[1][j1], HEmatpar.cBits);\n        Bctemp[0][j1]  = scheme.multByPoly(BaByctxtB[j1], poly[2][j1], HEmatpar.cBits);\n        \n        scheme.addAndEqual(Actemp1[0][j1], Actemp2[0][j1]);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    for(long j = 1; j < HEmatpar.sqrdim; ++j){\n        scheme.addAndEqual(resA, Actemp1[0][j]);\n        scheme.addAndEqual(resB, Bctemp[0][j]);\n    }\n \n    //---------------------------\n    Ciphertext* Actxts1 = new Ciphertext[HEmatpar.dim];\n    Ciphertext* Actxts2 = new Ciphertext[HEmatpar.dim];\n    Ciphertext* Bctxts  = new Ciphertext[HEmatpar.dim];\n    \n    NTL_EXEC_RANGE(HEmatpar.dim - ibound, first, last);\n    for(long k = first; k < last; ++k){\n        long k1 = (k + HEmatpar.sqrdim);\n        long i = (long)(k1 / HEmatpar.sqrdim);\n        long j = (long)(k1 % HEmatpar.sqrdim);\n        \n        Actxts1[k1] = scheme.multByPoly(BaByctxt1[j], poly[0][k1], HEmatpar.cBits);\n        Actxts2[k1] = scheme.multByPoly(BaByctxt2[j], poly[1][k1], HEmatpar.cBits);\n        Bctxts[k1]  = scheme.multByPoly(BaByctxtB[j], poly[2][k1], HEmatpar.cBits);\n        \n    }\n    NTL_EXEC_RANGE_END;\n    \n    NTL_EXEC_RANGE(ibound - 1, first, last);\n    for(long k = first; k < last; ++k){\n        long k1 = (k+1) * HEmatpar.sqrdim;\n        \n        long jbound = HEmatpar.sqrdim;\n        if((btmp) && (k == ibound - 2)){\n            jbound = (HEmatpar.dim % HEmatpar.sqrdim);\n        }\n        for(long j = 1; j < jbound; ++j){\n            scheme.addAndEqual(Actxts1[k1], Actxts1[k1+j]);\n            scheme.addAndEqual(Actxts2[k1], Actxts2[k1+j]);\n            scheme.addAndEqual(Bctxts[k1], Bctxts[k1+j]);\n        }\n        \n        long k2 = (k1 - (k1 % HEmatpar.sqrdim)) * HEmatpar.nbatching;\n        scheme.leftRotateAndEqual(Actxts1[k1], k2);\n        scheme.rightRotateAndEqual(Actxts2[k1], k2);\n        scheme.leftRotateAndEqual(Bctxts[k1], k2 * HEmatpar.dim);\n        \n        scheme.addAndEqual(Actxts1[k1], Actxts2[k1]);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    \n    for(long k = 1; k < ibound; ++k){\n        long k1 = k * HEmatpar.sqrdim;\n        scheme.addAndEqual(resA, Actxts1[k1]);\n        scheme.addAndEqual(resB, Bctxts[k1]);\n    }\n    \n    scheme.reScaleByAndEqual(resA, HEmatpar.cBits);\n    scheme.reScaleByAndEqual(resB, HEmatpar.cBits);\n    \n    delete[] Actxts1;\n    delete[] Actxts2;\n    delete[] Bctxts;\n    \n    delete[] Actemp1;\n    delete[] Actemp2;\n    delete[] Bctemp;\n    \n    delete[] BaByctxt1;\n    delete[] BaByctxt2;\n    delete[] BaByctxtB;\n}\n\nvoid HEmatrix::HEmatmul_Parallel(Ciphertext& res, Ciphertext& Actxt, Ciphertext& Bctxt, ZZX**& Initpoly, ZZX*& shiftpoly){\n    Ciphertext* Actxts = new Ciphertext[HEmatpar.dim];\n    Ciphertext* Bctxts = new Ciphertext[HEmatpar.dim];\n    \n    //! 1. Generate the initial ciphertexts\n    genInitCtxt_Parallel(Actxts[0], Bctxts[0], Actxt, Bctxt, Initpoly);\n\n    //! 2. Column shifting of Actxt[0], Row shifting of Bctxt[0]\n    long unit = HEmatpar.dim  * HEmatpar.nbatching;\n    NTL_EXEC_RANGE(HEmatpar.dim1, first, last);\n    for(int i = first; i < last; ++i){\n        long i1 = (i + 1);\n        shiftBycols_Parallel(Actxts[i1], Actxts[0], i1, shiftpoly);\n        Bctxts[i1] = scheme.leftRotate(Bctxts[0], unit * (i1));\n    }\n    NTL_EXEC_RANGE_END;\n    \n    //! 3. Hadamard mult : Actxts[0] * Bctxts[0] + ... + Actxts[d-1] * Bctxts[d-1]\n    HEmatmul_Hadamard(res, Actxts, Bctxts, HEmatpar.dim);\n\n    delete[] Actxts;\n    delete[] Bctxts;\n}\n\nvoid HEmatrix::HErmatmul(Ciphertext& res, Ciphertext& Actxt, Ciphertext& Bctxt, ZZX**& Initpoly, ZZX*& shiftpoly){\n    Ciphertext* Actxts = new Ciphertext[HEmatpar.subdim];\n    Ciphertext* Bctxts = new Ciphertext[HEmatpar.subdim];\n    \n    //! 1. Generate the initial ciphertexts\n    genInitCtxt(Actxts[0], Bctxts[0], Actxt, Bctxt, Initpoly);\n    \n    //! 2. Column shifting of Actxt[0], Row shifting of Bctxt[0]\n    NTL_EXEC_RANGE(HEmatpar.subdim - 1, first, last);\n    for(int i = first; i < last; ++i){\n        long i1 = (i + 1);\n        shiftBycols(Actxts[i1], Actxts[0], i1, shiftpoly);\n        Bctxts[i1] = scheme.leftRotate(Bctxts[0], HEmatpar.dim * (i1));\n    }\n    NTL_EXEC_RANGE_END;\n \n    //! 3. Hadamard mult : Actxts[0] * Bctxts[0] + ... + Actxts[d-1] * Bctxts[d-1]\n    HEmatmul_Hadamard(res, Actxts, Bctxts, HEmatpar.subdim);\n    \n    //! 4. shift and aggregate the results\n    long index = (long) log2(HEmatpar.dim/HEmatpar.subdim);\n    \n    for(long i = 0; i < index; ++i){\n        Ciphertext ctemp = scheme.leftRotate(res, HEmatpar.dim*HEmatpar.subdim * (1<<i));\n        scheme.addAndEqual(res, ctemp);\n    }\n\n    delete[] Actxts;\n    delete[] Bctxts;\n}\n\nvoid HEmatrix::genMultBPoly(ZZX*& Initpoly){\n    bool btmp;\n    if((HEmatpar.dim % HEmatpar.sqrdim) == 0){ btmp = false; }    //! all the terms have the same numbers\n    else{ btmp = true; }\n    long ibound = (long) ceil((double)HEmatpar.dim/HEmatpar.sqrdim); //! number of \"i\"\n    \n    Initpoly =  new ZZX[HEmatpar.dim];\n    complex<double>** bvals  = new complex<double>*[HEmatpar.dim];\n    \n    NTL_EXEC_RANGE(ibound, first, last);\n    for(int i = first; i < last; ++i){\n        long jbound = HEmatpar.sqrdim;\n        if ((btmp)&&(i == ibound - 1)){\n            jbound = (HEmatpar.dim % HEmatpar.sqrdim);\n        }\n        for(long j = 0; j < jbound; ++j){\n            long k = i * HEmatpar.sqrdim + j;\n            bvals[k] = new complex<double>[HEmatpar.nslots];\n            \n            for(long l = 0; l < HEmatpar.dim; ++l){\n                bvals[k][l * HEmatpar.dim + k].real(1.0);\n            }\n            msgrightRotateAndEqual(bvals[k], HEmatpar.nslots, i*HEmatpar.sqrdim*HEmatpar.dim);\n            Initpoly[k] = scheme.context.encode(bvals[k], HEmatpar.nslots, HEmatpar.cBits);\n        }\n    }\n    NTL_EXEC_RANGE_END;\n    \n    delete[] bvals;\n}\n\nvoid HEmatrix::genInitActxt(Ciphertext*& Actxts, Mat<RR>& mat){\n    Mat<RR>* Amat = new Mat<RR>[HEmatpar.dim];\n    Actxts = new Ciphertext[HEmatpar.dim];\n    complex<double>** cmsg = new complex<double>*[HEmatpar.dim];\n\n    NTL_EXEC_RANGE(HEmatpar.dim, first, last);\n    for(long k = first; k < last; ++k){\n        Amat[k].SetDims(HEmatpar.dim, HEmatpar.dim);\n        long dimk = HEmatpar.dim - k;\n    \n        //! 0 <= i < d - k: shift by (k+i)-positions from mat[i]\n        for(long i = 0; i < dimk; ++i){\n            long nshift = k + i;\n            long nshift2 = HEmatpar.dim - nshift;\n            \n            for(long j = 0; j < nshift2; ++j){\n                Amat[k][i][j] = mat[i][j + nshift];\n            }\n            \n            for(long j = nshift2; j < HEmatpar.dim; ++j){\n                Amat[k][i][j] = mat[i][j - nshift2];\n            }\n        }\n        \n        //! i = d - k : Amat[k][i] <- mat[i]\n        if(k!=0){\n            for(long j = 0; j < HEmatpar.dim; ++j){\n                Amat[k][dimk][j] = mat[dimk][j];\n            }\n        }\n        \n        //! d - k + 1 <= i < d: shift by (k+i-d)-positions from mat[i]\n        for(long i = dimk + 1; i < HEmatpar.dim; ++i){\n            long nshift =  i - dimk;\n            long nshift2 = HEmatpar.dim - nshift;\n            \n            for(long j = 0; j < nshift2; ++j){\n                Amat[k][i][j] = mat[i][j + nshift];\n            }\n            for(long j = nshift2; j < HEmatpar.dim; ++j){\n                Amat[k][i][j] = mat[i][j - nshift2];\n            }\n        }\n    }\n    NTL_EXEC_RANGE_END;\n    \n    //! encryption of d Rmat\n    NTL_EXEC_RANGE(HEmatpar.dim, first, last);\n    for(long k = first; k < last; ++k){\n        cmsg[k] = new complex<double>[HEmatpar.nslots];\n    \n        for(long i = 0; i < HEmatpar.nrows; ++i){\n            for(long j = 0; j < HEmatpar.ncols; ++j){\n                double dtemp;\n                conv(dtemp, Amat[k][i][j]);\n                cmsg[k][i*HEmatpar.dim + j].real(dtemp);\n            }\n        }\n        Actxts[k] = scheme.encrypt(cmsg[k], HEmatpar.nslots, HEmatpar.pBits, HEmatpar.logQ);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    delete[] cmsg;\n}\n\nvoid HEmatrix::genInitBctxt(Ciphertext& resB, Ciphertext& Bctxt, ZZX*& poly){\n    bool btmp;\n    if((HEmatpar.dim % HEmatpar.sqrdim) == 0){\n        btmp = false;\n    }\n    else{\n        btmp = true;\n    }\n    long ibound = (long) ceil((double)HEmatpar.dim/HEmatpar.sqrdim);\n    \n    \n    Ciphertext** Bctemp = new Ciphertext*[HEmatpar.sqrdim];\n    for(long i = 0; i < HEmatpar.sqrdim; ++i){\n        Bctemp[i]  = new Ciphertext[HEmatpar.sqrdim];\n    }\n    \n    //! 0. Store some ciphertexts (0,1,...,d-1), ( ,d+1,...2d-1)\n    Ciphertext* BaByctxtB  = new Ciphertext[HEmatpar.dim];\n    \n    BaByctxtB[0] = Bctxt;\n    \n    //! i = 0:   Actxts[0] = v[0] + p1 * v[1] + ... + p[sqr(d)-1] *  v[sqr(d)-1]\n    resB = scheme.multByPoly(BaByctxtB[0], poly[0], HEmatpar.cBits);\n\n    NTL_EXEC_RANGE(HEmatpar.sqrdim - 1, first, last);\n    for(long j = first; j < last; ++j){\n        long j1 = (j + 1);\n        BaByctxtB[j1] = scheme.leftRotate(Bctxt, (j1)*HEmatpar.dim);\n        Bctemp[0][j1]  = scheme.multByPoly(BaByctxtB[j1], poly[j1], HEmatpar.cBits);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    for(long j = 1; j < HEmatpar.sqrdim; ++j){\n        scheme.addAndEqual(resB, Bctemp[0][j]);\n    }\n    \n    Ciphertext* Bctxts  = new Ciphertext[HEmatpar.dim];\n    \n    NTL_EXEC_RANGE(HEmatpar.dim - HEmatpar.sqrdim, first, last);\n    for(long k = first; k < last; ++k){\n        long k1 = (k + HEmatpar.sqrdim);\n        long i = (long)(k1 / HEmatpar.sqrdim);\n        long j = (long)(k1 % HEmatpar.sqrdim);\n        \n        Bctxts[k1]  = scheme.multByPoly(BaByctxtB[j], poly[k1], HEmatpar.cBits);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    NTL_EXEC_RANGE(ibound - 1, first, last);\n    for(long k = first; k < last; ++k){\n        long k1 = (k+1) * HEmatpar.sqrdim;\n        long jbound = HEmatpar.sqrdim;\n        if((btmp) && (k == ibound - 2)){\n            jbound = (HEmatpar.dim % HEmatpar.sqrdim);\n        }\n        \n        for(long j = 1; j < jbound; ++j){\n            scheme.addAndEqual(Bctxts[k1], Bctxts[k1+j]);\n        }\n        \n        long k2 = (k1 - (k1 % HEmatpar.sqrdim));\n        scheme.leftRotateAndEqual(Bctxts[k1], k2 * HEmatpar.dim);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    for(long k = 1; k < ibound; ++k){\n        long k1 = k * HEmatpar.sqrdim;\n        scheme.addAndEqual(resB, Bctxts[k1]);\n    }\n\n    scheme.reScaleByAndEqual(resB, HEmatpar.cBits);\n    \n    delete[] Bctxts;\n    delete[] Bctemp;\n    delete[] BaByctxtB;\n}\n\nvoid HEmatrix::HEmatmul_preprocessing(Ciphertext& res, Ciphertext*& Actxts, Ciphertext& Bctxt, ZZX*& Initpoly){\n\n    //! 1. Generate the initial ciphertexts\n    Ciphertext* Bctxts = new Ciphertext[HEmatpar.dim];\n    genInitBctxt(Bctxts[0], Bctxt, Initpoly);\n    \n    //! 2. Row shifting of Bctxt[0]\n    NTL_EXEC_RANGE(HEmatpar.dim1, first, last);\n    for(int i = first; i < last; ++i){\n        long i1 = (i + 1);\n        Bctxts[i1] = scheme.leftRotate(Bctxts[0], HEmatpar.dim * (i1));\n    }\n    NTL_EXEC_RANGE_END;\n    \n    //! 3. Hadamard mult : Actxts[0] * Bctxts[0] + ... + Actxts[d-1] * Bctxts[d-1]\n    NTL_EXEC_RANGE(HEmatpar.dim, first, last);\n    for(int i = first; i < last; ++i){\n        scheme.modDownToAndEqual(Actxts[i], Bctxts[0].logq);\n        scheme.multAndEqual(Actxts[i], Bctxts[i]);   // log(Actxt[i+1]) = log Bctxt[0]\n    }\n    NTL_EXEC_RANGE_END;\n    \n    res = Actxts[0];\n    for(int i = 1; i < HEmatpar.dim; ++i){\n        scheme.addAndEqual(res, Actxts[i]);\n    }\n    \n    scheme.reScaleByAndEqual(res, res.logp);\n\n    delete[] Bctxts;\n}\n\nvoid HEmatrix::genInitRecActxt(Ciphertext*& Actxts, Mat<RR>& mat){\n    // rep_mat: (mat; mat; ... ;mat) square mat\n    Mat<RR> replicate_mat;\n    replicate_mat.SetDims(HEmatpar.dim, HEmatpar.dim);\n    \n    long index_rows = HEmatpar.dim/HEmatpar.subdim;\n    \n    NTL_EXEC_RANGE(index_rows, first, last);\n    for(long k = first; k < last; ++k){\n        for(long i = 0; i < HEmatpar.subdim; ++i){\n            for(long j = 0; j < HEmatpar.dim; ++j){\n                replicate_mat[k*HEmatpar.subdim + i][j] = mat[i][j];\n            }\n        }\n    }\n    NTL_EXEC_RANGE_END;\n    \n    //! generate the (linear transformed) matrices\n    Mat<RR>* Amat = new Mat<RR>[HEmatpar.subdim];\n    Actxts = new Ciphertext[HEmatpar.subdim];\n    \n    NTL_EXEC_RANGE(HEmatpar.subdim, first, last);\n    for(long k = first; k < last; ++k){\n        Amat[k].SetDims(HEmatpar.dim, HEmatpar.dim);\n        long dimk= HEmatpar.dim - k;\n        \n        //! 0 <= i < d - k: shift by (k+i)-positions from mat[i]\n        for(long i = 0; i < dimk; ++i){\n            long nshift = k + i;\n            long nshift2 = HEmatpar.dim - nshift;\n            \n            for(long j = 0; j < nshift2; ++j){\n                Amat[k][i][j] = replicate_mat[i][j + nshift];\n            }\n            \n            for(long j = nshift2; j < HEmatpar.dim; ++j){\n                Amat[k][i][j] = replicate_mat[i][j - nshift2];\n            }\n        }\n        \n        //! i = d - k : Amat[k][i] <- mat[i]\n        if(k!=0){\n            for(long j = 0; j < HEmatpar.dim; ++j){\n                Amat[k][dimk][j] = replicate_mat[dimk][j];\n            }\n        }\n        \n        //! d - k + 1 <= i < d: shift by (k+i-d)-positions from mat[i]\n        for(long i = dimk + 1; i < HEmatpar.dim; ++i){\n            long nshift =  i - dimk;\n            long nshift2 = HEmatpar.dim - nshift;\n            \n            for(long j = 0; j < nshift2; ++j){\n                Amat[k][i][j] = replicate_mat[i][j + nshift];\n            }\n            for(long j = nshift2; j < HEmatpar.dim; ++j){\n                Amat[k][i][j] = replicate_mat[i][j - nshift2];\n            }\n        }\n    }\n    NTL_EXEC_RANGE_END;\n    \n    //! encryption of d Rmat\n    complex<double>** cmsg = new complex<double>*[HEmatpar.subdim];\n    NTL_EXEC_RANGE(HEmatpar.subdim, first, last);\n    for(long k = first; k < last; ++k){\n        cmsg[k] = new complex<double>[HEmatpar.nslots];\n        for(int i = 0; i < HEmatpar.nrows; ++i){\n            for(long j = 0; j < HEmatpar.ncols; ++j){\n                double dtemp;\n                conv(dtemp, Amat[k][i][j]);\n                cmsg[k][i*HEmatpar.dim + j].real(dtemp);\n            }\n        }\n        Actxts[k] = scheme.encrypt(cmsg[k], HEmatpar.nslots, HEmatpar.pBits, HEmatpar.logQ);\n    }\n    NTL_EXEC_RANGE_END;\n    \n    delete[] cmsg;\n}\n\nvoid HEmatrix::HErmatmul_preprocessing(Ciphertext& res, Ciphertext*& Actxts, Ciphertext& Bctxt, ZZX*& Initpoly){\n    \n    //! 1. Generate the initial ciphertexts\n    Ciphertext* Bctxts = new Ciphertext[HEmatpar.subdim];\n    genInitBctxt(Bctxts[0], Bctxt, Initpoly);\n    \n    //! 2. Row shifting of Bctxt[0]\n    NTL_EXEC_RANGE(HEmatpar.subdim - 1, first, last);\n    for(int i = first; i < last; ++i){\n        long i1 = (i + 1);\n        Bctxts[i1] = scheme.leftRotate(Bctxts[0], HEmatpar.dim * (i1));\n    }\n    NTL_EXEC_RANGE_END;\n    \n    //! 3. Hadamard mult : Actxts[0] * Bctxts[0] + ... + Actxts[d-1] * Bctxts[d-1]\n    NTL_EXEC_RANGE(HEmatpar.subdim, first, last);\n    for(int i = first; i < last; ++i){\n        scheme.modDownToAndEqual(Actxts[i], Bctxts[0].logq);\n        scheme.multAndEqual(Actxts[i], Bctxts[i]);   //! log(Actxt[i+1]) = log Bctxt[0]\n    }\n    NTL_EXEC_RANGE_END;\n    \n    //! aggregate the results\n    res = Actxts[0];\n    for(int i = 1; i < HEmatpar.subdim; ++i){\n        scheme.addAndEqual(res, Actxts[i]);\n    }\n    scheme.reScaleByAndEqual(res, res.logp);\n    \n    //! 4. shift and aggregate the results\n    long index = (long) log2(HEmatpar.dim/HEmatpar.subdim);\n    for(long i = 0; i < index; ++i){\n        Ciphertext ctemp = scheme.leftRotate(res, HEmatpar.dim*HEmatpar.subdim * (1<<i));\n        scheme.addAndEqual(res, ctemp);\n    }\n    \n    delete[] Bctxts;\n}\n", "meta": {"hexsha": "22f0b02c75b2a7e66bf678c44f1a5873154e53ab", "size": 49837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HEMat/HEmatrix.cpp", "max_stars_repo_name": "zghodsi/HEMat", "max_stars_repo_head_hexsha": "0a0770e56c814387c42bece88a77357da5f58851", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-03-20T03:49:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T06:30:51.000Z", "max_issues_repo_path": "HEMat/HEmatrix.cpp", "max_issues_repo_name": "zghodsi/HEMat", "max_issues_repo_head_hexsha": "0a0770e56c814387c42bece88a77357da5f58851", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-08-29T13:21:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T12:16:09.000Z", "max_forks_repo_path": "HEMat/HEmatrix.cpp", "max_forks_repo_name": "zghodsi/HEMat", "max_forks_repo_head_hexsha": "0a0770e56c814387c42bece88a77357da5f58851", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-21T10:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T08:47:07.000Z", "avg_line_length": 35.0964788732, "max_line_length": 126, "alphanum_fraction": 0.5554307041, "num_tokens": 16772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4172471623849637}}
{"text": "// ----------------------------------------------------------------------------\n// -                        Open3D: www.open3d.org                            -\n// ----------------------------------------------------------------------------\n// The MIT License (MIT)\n//\n// Copyright (c) 2018 www.open3d.org\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n// ----------------------------------------------------------------------------\n\n#include \"Feature.h\"\n\n#include <Eigen/Dense>\n#include <Open3D/Utility/Console.h>\n#include <Open3D/Geometry/PointCloud.h>\n#include <Open3D/Geometry/KDTreeFlann.h>\n\nnamespace open3d {\n\nnamespace {\n\nEigen::Vector4d ComputePairFeatures(const Eigen::Vector3d &p1,\n                                    const Eigen::Vector3d &n1,\n                                    const Eigen::Vector3d &p2,\n                                    const Eigen::Vector3d &n2) {\n    Eigen::Vector4d result;\n    Eigen::Vector3d dp2p1 = p2 - p1;\n    result(3) = dp2p1.norm();\n    if (result(3) == 0.0) {\n        return Eigen::Vector4d::Zero();\n    }\n    auto n1_copy = n1;\n    auto n2_copy = n2;\n    double angle1 = n1_copy.dot(dp2p1) / result(3);\n    double angle2 = n2_copy.dot(dp2p1) / result(3);\n    if (acos(fabs(angle1)) > acos(fabs(angle2))) {\n        n1_copy = n2;\n        n2_copy = n1;\n        dp2p1 *= -1.0;\n        result(2) = -angle2;\n    } else {\n        result(2) = angle1;\n    }\n    auto v = dp2p1.cross(n1_copy);\n    double v_norm = v.norm();\n    if (v_norm == 0.0) {\n        return Eigen::Vector4d::Zero();\n    }\n    v /= v_norm;\n    auto w = n1_copy.cross(v);\n    result(1) = v.dot(n2_copy);\n    result(0) = atan2(w.dot(n2_copy), n1_copy.dot(n2_copy));\n    return result;\n}\n\nstd::shared_ptr<Feature> ComputeSPFHFeature(\n        const PointCloud &input,\n        const KDTreeFlann &kdtree,\n        const KDTreeSearchParam &search_param) {\n    auto feature = std::make_shared<Feature>();\n    feature->Resize(33, (int)input.points_.size());\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n    for (int i = 0; i < (int)input.points_.size(); i++) {\n        const auto &point = input.points_[i];\n        const auto &normal = input.normals_[i];\n        std::vector<int> indices;\n        std::vector<double> distance2;\n        if (kdtree.Search(point, search_param, indices, distance2) > 1) {\n            // only compute SPFH feature when a point has neighbors\n            double hist_incr = 100.0 / (double)(indices.size() - 1);\n            for (size_t k = 1; k < indices.size(); k++) {\n                // skip the point itself, compute histogram\n                auto pf = ComputePairFeatures(point, normal,\n                                              input.points_[indices[k]],\n                                              input.normals_[indices[k]]);\n                int h_index = (int)(floor(11 * (pf(0) + M_PI) / (2.0 * M_PI)));\n                if (h_index < 0) h_index = 0;\n                if (h_index >= 11) h_index = 10;\n                feature->data_(h_index, i) += hist_incr;\n                h_index = (int)(floor(11 * (pf(1) + 1.0) * 0.5));\n                if (h_index < 0) h_index = 0;\n                if (h_index >= 11) h_index = 10;\n                feature->data_(h_index + 11, i) += hist_incr;\n                h_index = (int)(floor(11 * (pf(2) + 1.0) * 0.5));\n                if (h_index < 0) h_index = 0;\n                if (h_index >= 11) h_index = 10;\n                feature->data_(h_index + 22, i) += hist_incr;\n            }\n        }\n    }\n    return feature;\n}\n\n}  // unnamed namespace\n\nstd::shared_ptr<Feature> ComputeFPFHFeature(\n        const PointCloud &input,\n        const KDTreeSearchParam &search_param /* = KDTreeSearchParamKNN()*/) {\n    auto feature = std::make_shared<Feature>();\n    feature->Resize(33, (int)input.points_.size());\n    if (input.HasNormals() == false) {\n        PrintDebug(\n                \"[ComputeFPFHFeature] Failed because input point cloud has no \"\n                \"normal.\\n\");\n        return feature;\n    }\n    KDTreeFlann kdtree(input);\n    auto spfh = ComputeSPFHFeature(input, kdtree, search_param);\n#ifdef _OPENMP\n#pragma omp parallel for schedule(static)\n#endif\n    for (int i = 0; i < (int)input.points_.size(); i++) {\n        const auto &point = input.points_[i];\n        std::vector<int> indices;\n        std::vector<double> distance2;\n        if (kdtree.Search(point, search_param, indices, distance2) > 1) {\n            double sum[3] = {0.0, 0.0, 0.0};\n            for (size_t k = 1; k < indices.size(); k++) {\n                // skip the point itself\n                double dist = distance2[k];\n                if (dist == 0.0) continue;\n                for (int j = 0; j < 33; j++) {\n                    double val = spfh->data_(j, indices[k]) / dist;\n                    sum[j / 11] += val;\n                    feature->data_(j, i) += val;\n                }\n            }\n            for (int j = 0; j < 3; j++)\n                if (sum[j] != 0.0) sum[j] = 100.0 / sum[j];\n            for (int j = 0; j < 33; j++) {\n                feature->data_(j, i) *= sum[j / 11];\n                // The commented line is the fpfh function in the paper.\n                // But according to PCL implementation, it is skipped.\n                // Our initial test shows that the full fpfh function in the\n                // paper seems to be better than PCL implementation. Further\n                // test required.\n                feature->data_(j, i) += spfh->data_(j, i);\n            }\n        }\n    }\n    return feature;\n}\n\n}  // namespace open3d\n", "meta": {"hexsha": "1747c165df363ddcc95790796c98aa976cd7b9cf", "size": 6565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Open3D/Registration/Feature.cpp", "max_stars_repo_name": "HajimeTaira/Open3D", "max_stars_repo_head_hexsha": "21296f22e808caf7082fc5cf7d54aa2405cfc95e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-15T11:26:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T11:26:39.000Z", "max_issues_repo_path": "src/Open3D/Registration/Feature.cpp", "max_issues_repo_name": "Markstanford2019/Open3D", "max_issues_repo_head_hexsha": "af0900bd061d5b29d8a1be517ddbcb0d63164a62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Open3D/Registration/Feature.cpp", "max_forks_repo_name": "Markstanford2019/Open3D", "max_forks_repo_head_hexsha": "af0900bd061d5b29d8a1be517ddbcb0d63164a62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2760736196, "max_line_length": 80, "alphanum_fraction": 0.5396801219, "num_tokens": 1673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.41724518995574783}}
{"text": "#ifndef GEOMETRY_HPP\n#define GEOMETRY_HPP\n\n#include \"point.hpp\"\n\n#include <boost/assert.hpp>\n\n#include <vector>\n#include <algorithm>\n\nnamespace geometry\n{\n    enum class monoticity : unsigned char\n    {\n        INCREASING_X = 1,\n        INCREASING_Y = 2,\n        DECREASING_X = 4,\n        DECREASING_Y = 8,\n        CONSTANT_X   = 5,\n        CONSTANT_Y   = 10,\n        CONSTANT     = 15,\n        INVALID      = 0\n\n    };\n\n    enum class point_position : char\n    {\n        LEFT_OF_LINE,\n        RIGHT_OF_LINE,\n        ON_LINE\n    };\n\n    inline monoticity operator&(monoticity lhs, monoticity rhs)\n    {\n        return static_cast<geometry::monoticity>(static_cast<char>(lhs) & static_cast<char>(rhs));\n    }\n\n    /// Transforms the path from the goven monoticity to be x-monotone-increasing\n    inline void make_x_monotone_increasing(monoticity mono, std::vector<coordinate>& path)\n    {\n        BOOST_ASSERT(mono != monoticity::INVALID);\n\n        if ((mono & monoticity::INCREASING_X) != monoticity::INVALID)\n        {\n            return;\n        }\n\n        if ((mono & monoticity::DECREASING_X) == monoticity::INVALID)\n        {\n            // make x-monotone: swap x and y (mirror on (0,0)->(1,1))\n            if ((mono & monoticity::INCREASING_Y) != monoticity::INVALID ||\n                (mono & monoticity::DECREASING_Y) != monoticity::INVALID)\n            {\n                for (unsigned i = 0; i < path.size(); i++)\n                {\n                    std::swap(path[i].y, path[i].x);\n                }\n            }\n\n            // we are now x-monotone increasing\n            if ((mono & monoticity::INCREASING_Y) != monoticity::INVALID)\n            {\n                return;\n            }\n        }\n\n        // at this point we are always x-monotone descreasing: Mirror on y-Axis\n        std::transform(path.begin(), path.end(), path.begin(),\n                       [](coordinate c)\n                       {\n                            c.x *= -1;\n                            return c;\n                       });\n    }\n\n    /// Returns a vector that is orthogonal to the line implied by\n    /// first_line_point and second_line_point.\n    ///\n    /// This vector is not normalized!\n    inline coordinate line_normal(const coordinate& first_line_point,\n                                  const coordinate& second_line_point)\n    {\n        return coordinate {-second_line_point.y + first_line_point.y,\n                            second_line_point.x - first_line_point.x};\n    }\n\n    inline coordinate::value_type cross(const coordinate& a, const coordinate& b)\n    {\n        return a.x * b.y - a.y * b.x;\n    }\n\n    struct intersection_params\n    {\n        double first_param;\n        double second_param;\n        bool colinear;\n    };\n\n    inline intersection_params segment_intersection(\n            const coordinate& first_segment_a, const coordinate& first_segment_b,\n            const coordinate& second_segment_a, const coordinate& second_segment_b)\n    {\n        intersection_params params {0, 0, false};\n        const coordinate first_delta = first_segment_b - first_segment_a;\n        const coordinate second_delta = second_segment_b - second_segment_a;\n        auto direction_cross = cross(first_delta, second_delta);\n        // colinear\n        if (direction_cross == 0)\n        {\n            params.colinear = true;\n        }\n        else\n        {\n            params.first_param  = cross((second_segment_a - first_segment_a), second_delta) / direction_cross;\n            params.second_param = cross((second_segment_a - first_segment_a), first_delta) / direction_cross;\n        }\n\n        return params;\n    }\n\n    inline bool segments_intersect(const coordinate& first_segment_a, const coordinate& first_segment_b,\n                                   const coordinate& second_segment_a, const coordinate& second_segment_b)\n    {\n        auto params = segment_intersection(first_segment_a, first_segment_b, second_segment_a, second_segment_b);\n        auto u = params.first_param;\n        auto t = params.second_param;\n        if (params.colinear)\n        {\n            return false;\n        }\n\n        return (u >= 0 && u <= 1.0) && (t >= 0 && t <= 1.0);\n    }\n\n    inline point_position position_to_line(const coordinate& first_line_point,\n                                    const coordinate& second_line_point,\n                                    const coordinate& point)\n    {\n        auto delta = point - first_line_point;\n        auto p = glm::dot(line_normal(first_line_point, second_line_point), delta);\n\n        if (p > 0)\n            return point_position::LEFT_OF_LINE;\n        else if (p < 0)\n            return point_position::RIGHT_OF_LINE;\n\n        return point_position::ON_LINE;\n    }\n\n    /// returns an angle beteen 0 and 2*M_PI\n    inline float normalize_angle(float angle)\n    {\n        float normalized = angle;\n        while (normalized < 0) normalized      += 2*M_PI;\n        while (normalized > 2*M_PI) normalized -= 2*M_PI;\n\n        return normalized;\n    }\n\n    /// returns the shortest angle between two vectors with the given angles\n    inline float angle_diff(float first_angle, float second_angle)\n    {\n        float diff = std::abs(normalize_angle(first_angle) - normalize_angle(second_angle));\n        if (diff > M_PI)\n        {\n            diff = diff - M_PI;\n        }\n        return diff;\n    }\n\n    /// compares the slope of origin -> lhs and origin -> rhs and returns true\n    /// if the slope of lhs is bigger than rhs.\n    inline bool slope_compare(const coordinate& origin, const coordinate& lhs, const coordinate& rhs)\n    {\n        BOOST_ASSERT(lhs.x >= origin.x);\n        BOOST_ASSERT(rhs.x >= origin.x);\n\n        auto position = position_to_line(origin, lhs, rhs);\n\n        return position == point_position::RIGHT_OF_LINE ||\n              (position == point_position::ON_LINE &&\n               // origin -> rhs points in opposite direction\n               glm::dot(lhs - origin, rhs - origin) < 0);\n    }\n};\n#endif\n", "meta": {"hexsha": "d3eb30e7f67ce24766efe3390e8d67d60bb6f083", "size": 5983, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry.hpp", "max_stars_repo_name": "TheMarex/deberg", "max_stars_repo_head_hexsha": "050f9ae8930801cc03d216eddc515e9929f7b916", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-06-23T14:01:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-12T23:08:06.000Z", "max_issues_repo_path": "geometry.hpp", "max_issues_repo_name": "TheMarex/deberg", "max_issues_repo_head_hexsha": "050f9ae8930801cc03d216eddc515e9929f7b916", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry.hpp", "max_forks_repo_name": "TheMarex/deberg", "max_forks_repo_head_hexsha": "050f9ae8930801cc03d216eddc515e9929f7b916", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9946524064, "max_line_length": 113, "alphanum_fraction": 0.5784723383, "num_tokens": 1322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4172451834189369}}
{"text": "/*\n * reclayer.cpp\n *\n * Feed-forward:\n *  state:\n *    zz_h(t) = ww_hh * hh(t-1) + ww_xh*x(t) + b_h\n *    hh(t)   = state_activation_function(zz_h(t))\n *  output:\n *    zz_a(t) = ww_ha * hh(t) + b_a\n *    a(t)    = output_activation_function(zz_a(t))\n *\n * Back propagation:\n *   output:\n *    delta_a(t)  = elem_prod(gradient(C, a(t)), activation_derivative(zz_a(t)))\n *    dC/d b_a(t)   = delta_a(t)\n *    dC/d ww_ha(t) = hh(t) * delta_a(t)\n *    total_gradient(C, hh(t)) = gradient(C, hh(t)) + transp(ww_ha) * delta_a(t)\n *  state:\n *    delta_h(t) = elem_prod(total_gradient(C, hh(t)), activation_derivative(zz_h(t)))\n *    dC/d b_h(t) = delta_h(t)\n *    dC/d ww_xh(t) = x(t) * delta_h(t)\n *    dC/d ww_hh(t) = hh(t-1) * delta_h(t)\n *    gradient(C, hh(t-1)) = transp(ww_hh) * delta_h(t)\n *    gradient(C, x(t)) = transp(ww_xh) * delta_h(t)\n */\n#include <boost/assert.hpp>\n\n#include \"core/utils.h\"\n#include \"core/random.h\"\n#include \"core/functions.h\"\n#include \"reclayer.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace yann;\n\n\nnamespace yann {\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// RecurrentLayer_Context implementation\n//\nclass RecurrentLayer_Context :\n    public Layer::Context\n{\n  typedef Layer::Context Base;\n\n  friend class RecurrentLayer;\n\npublic:\n  RecurrentLayer_Context(\n      const MatrixSize & state_size,\n      const MatrixSize & output_size,\n      const MatrixSize & max_batch_size) :\n    Base(output_size, max_batch_size),\n    _pos(0)\n  {\n    init(state_size);\n  }\n\n  RecurrentLayer_Context(\n      const MatrixSize & state_size,\n      const RefVectorBatch & output) :\n    Base(output),\n    _pos(0)\n  {\n    init(state_size);\n  }\n\n  // Layer::Context overwrites\n  virtual void reset_state()\n  {\n    Base::reset_state();\n\n    _pos = 0;\n  }\n\nprivate:\n  void init(const MatrixSize & state_size)\n  {\n    YANN_CHECK_GT(state_size, 0);\n\n    _hh.resize(get_batch_size(), state_size);\n    _zz_h.resize(get_batch_size(), state_size);\n    _zz_a.resize(get_batch_size(), get_output_size());\n  }\n\nprotected:\n  MatrixSize _pos;\n  VectorBatch  _hh;       // state (save it for each step)\n  VectorBatch  _zz_h;\n  VectorBatch  _zz_a;\n}; // class RecurrentLayer_Context\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// RecurrentLayer_TrainingContext implementation\n//\nclass RecurrentLayer_TrainingContext :\n    public RecurrentLayer_Context\n{\n  typedef RecurrentLayer_Context Base;\n  friend class RecurrentLayer;\n\npublic:\n  RecurrentLayer_TrainingContext(\n      const MatrixSize & input_size,\n      const MatrixSize & state_size,\n      const MatrixSize & output_size,\n      const MatrixSize & batch_size,\n      const unique_ptr<Layer::Updater> & updater) :\n    Base(state_size, output_size, batch_size),\n    _ww_hh_updater(updater->copy()),\n    _ww_xh_updater(updater->copy()),\n    _bb_h_updater(updater->copy()),\n    _ww_ha_updater(updater->copy()),\n    _bb_a_updater(updater->copy())\n  {\n    init(input_size, state_size);\n  }\n\n  RecurrentLayer_TrainingContext(\n      const MatrixSize & input_size,\n      const MatrixSize & state_size,\n      const RefVectorBatch & output,\n      const unique_ptr<Layer::Updater> & updater) :\n    Base(state_size, output),\n    _ww_hh_updater(updater->copy()),\n    _ww_xh_updater(updater->copy()),\n    _bb_h_updater(updater->copy()),\n    _ww_ha_updater(updater->copy()),\n    _bb_a_updater(updater->copy())\n  {\n    init(input_size, state_size);\n  }\n\n  // Layer::Context overwrites\n  virtual void start_epoch()\n  {\n    YANN_SLOW_CHECK(_ww_hh_updater);\n    YANN_SLOW_CHECK(_ww_xh_updater);\n    YANN_SLOW_CHECK(_bb_h_updater);\n    YANN_SLOW_CHECK(_ww_ha_updater);\n    YANN_SLOW_CHECK(_bb_a_updater);\n\n    Base::start_epoch();\n\n    _ww_hh_updater->start_epoch();\n    _ww_xh_updater->start_epoch();\n    _bb_h_updater->start_epoch();\n    _ww_ha_updater->start_epoch();\n    _bb_a_updater->start_epoch();\n  }\n\n  virtual void reset_state()\n  {\n    YANN_SLOW_CHECK(_ww_hh_updater);\n    YANN_SLOW_CHECK(_ww_xh_updater);\n    YANN_SLOW_CHECK(_bb_h_updater);\n    YANN_SLOW_CHECK(_ww_ha_updater);\n    YANN_SLOW_CHECK(_bb_a_updater);\n\n    Base::reset_state();\n\n    _gradient_h.setZero();\n\n    _delta_ww_hh.setZero();\n    _delta_ww_xh.setZero();\n    _delta_bb_h.setZero();\n    _delta_ww_ha.setZero();\n    _delta_bb_a.setZero();\n\n    _ww_hh_updater->reset();\n    _ww_xh_updater->reset();\n    _bb_h_updater->reset();\n    _ww_ha_updater->reset();\n    _bb_a_updater->reset();\n  }\n\nprivate:\n  void init(const MatrixSize & input_size, const MatrixSize & state_size)\n  {\n    YANN_CHECK_GT(input_size, 0);\n    YANN_CHECK_GT(state_size, 0);\n\n    _delta_ww_hh.resize(state_size, state_size);\n    _delta_ww_xh.resize(input_size, state_size);\n    _delta_bb_h.resize(state_size);\n    _delta_ww_ha.resize(state_size, get_output_size());\n    _delta_bb_a.resize(get_output_size());\n\n    _gradient_h.resize(state_size);\n    _delta_h.resize(state_size);\n    _delta_a.resize(get_output_size());\n\n    _sigma_derivative_zz_h.resize(state_size);\n    _sigma_derivative_zz_a.resize(get_output_size());\n\n    _ww_hh_updater->init(_delta_ww_hh.rows(), _delta_ww_hh.cols());\n    _ww_xh_updater->init(_delta_ww_xh.rows(), _delta_ww_xh.cols());\n    _bb_h_updater->init(1, _delta_bb_h.size()); // RowMajor\n    _ww_ha_updater->init(_delta_ww_ha.rows(), _delta_ww_ha.cols());\n    _bb_a_updater->init(1, _delta_bb_a.size()); // RowMajor\n  }\n\nprivate:\n  Matrix _delta_ww_hh;\n  Matrix _delta_ww_xh;\n  Vector _delta_bb_h;\n  Matrix _delta_ww_ha;\n  Vector _delta_bb_a;\n\n  Vector _gradient_h;\n  Vector _delta_h;\n  Vector _delta_a;\n\n  Vector _sigma_derivative_zz_h;\n  Vector _sigma_derivative_zz_a;\n\n  unique_ptr<Layer::Updater> _ww_hh_updater;\n  unique_ptr<Layer::Updater> _ww_xh_updater;\n  unique_ptr<Layer::Updater> _bb_h_updater;\n  unique_ptr<Layer::Updater> _ww_ha_updater;\n  unique_ptr<Layer::Updater> _bb_a_updater;\n}; // class RecurrentLayer_TrainingContext\n\n}; // namespace yann\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// yann::RecurrentLayer implementation\n//\nyann::RecurrentLayer::RecurrentLayer(\n    const MatrixSize & input_size,\n    const MatrixSize & state_size,\n    const MatrixSize & output_size) :\n    _state_activation_function(new SigmoidFunction()),\n    _output_activation_function(new SigmoidFunction())\n{\n  YANN_CHECK_GT(input_size, 0);\n  YANN_CHECK_GT(state_size, 0);\n  YANN_CHECK_GT(output_size, 0);\n\n  _ww_hh.resize(state_size, state_size);\n  _ww_xh.resize(input_size, state_size);\n  _bb_h.resize(state_size);\n\n  _ww_ha.resize(state_size, output_size);\n  _bb_a.resize(output_size);\n}\n\nyann::RecurrentLayer::~RecurrentLayer()\n{\n}\n\nvoid yann::RecurrentLayer::set_values(\n    const Matrix & ww_hh, const Matrix & ww_xh, const Vector & bb_h,\n    const Matrix & ww_ha, const Vector & bb_a)\n{\n  YANN_CHECK(is_same_size(ww_hh, _ww_hh));\n  YANN_CHECK(is_same_size(ww_xh, _ww_xh));\n  YANN_CHECK(is_same_size(bb_h, _bb_h));\n  YANN_CHECK(is_same_size(ww_ha, _ww_ha));\n  YANN_CHECK(is_same_size(bb_a, _bb_a));\n  _ww_hh = ww_hh;\n  _ww_xh = ww_xh;\n  _bb_h  = bb_h;\n  _ww_ha = ww_ha;\n  _bb_a  = bb_a;\n}\n\nvoid yann::RecurrentLayer::set_activation_functions(\n    const std::unique_ptr<ActivationFunction> & state_activation_function,\n    const std::unique_ptr<ActivationFunction> & output_activation_function)\n{\n  YANN_CHECK(state_activation_function);\n  YANN_CHECK(output_activation_function);\n  _state_activation_function = state_activation_function->copy();\n  _output_activation_function = output_activation_function->copy();\n}\n\n// Layer overwrites\nbool yann::RecurrentLayer::is_valid() const\n{\n  if(!Base::is_valid()) {\n    return false;\n  }\n  if(!_state_activation_function || !_output_activation_function) {\n    return false;\n  }\n  if(_ww_hh.rows() != _ww_hh.cols()) {\n    return false;\n  }\n  if(_ww_xh.cols() != _ww_hh.cols()) {\n    return false;\n  }\n  if(_ww_hh.cols() != _bb_h.size()) {\n    return false;\n  }\n  if(_ww_hh.cols() != _ww_ha.rows()) {\n    return false;\n  }\n  if(_ww_ha.cols() != _bb_a.size()) {\n    return false;\n  }\n\n  return true;\n}\n\nstd::string yann::RecurrentLayer::get_name() const\n{\n  return \"RecurrentLayer\";\n}\n\nstring yann::RecurrentLayer::get_info() const\n{\n  YANN_CHECK(is_valid());\n\n  ostringstream oss;\n  oss << Base::get_info()\n      << \" state size: \" << get_state_size()\n      << \", state activation: \" << _state_activation_function->get_info()\n      << \", output activation: \" << _output_activation_function->get_info()\n      ;\n  return oss.str();\n}\n\nbool yann::RecurrentLayer::is_equal(const Layer & other, double tolerance) const\n{\n  if(!Base::is_equal(other, tolerance)) {\n    return false;\n  }\n  auto the_other = dynamic_cast<const RecurrentLayer*>(&other);\n  if(the_other == nullptr) {\n    return false;\n  }\n  // TOOD: add deep compare\n  if(_state_activation_function->get_info() != the_other->_state_activation_function->get_info()) {\n    return false;\n  }\n  if(_output_activation_function->get_info() != the_other->_output_activation_function->get_info()) {\n    return false;\n  }\n\n  if(!_ww_hh.isApprox(the_other->_ww_hh, tolerance)) {\n    return false;\n  }\n  if(!_ww_xh.isApprox(the_other->_ww_xh, tolerance)) {\n    return false;\n  }\n  if(!_bb_h.isApprox(the_other->_bb_h, tolerance)) {\n    return false;\n  }\n  if(!_ww_ha.isApprox(the_other->_ww_ha, tolerance)) {\n    return false;\n  }\n  if(!_bb_a.isApprox(the_other->_bb_a, tolerance)) {\n    return false;\n  }\n  return true;\n}\n\nMatrixSize yann::RecurrentLayer::get_input_size() const\n{\n  YANN_SLOW_CHECK(is_valid());\n  return _ww_xh.rows();\n}\n\nMatrixSize yann::RecurrentLayer::get_state_size() const\n{\n  YANN_SLOW_CHECK(is_valid());\n  return _ww_xh.cols();\n}\n\nMatrixSize yann::RecurrentLayer::get_output_size() const\n{\n  YANN_SLOW_CHECK(is_valid());\n  return _ww_ha.cols();\n}\n\nunique_ptr<Layer::Context> yann::RecurrentLayer::create_context(const MatrixSize & batch_size) const\n{\n  YANN_CHECK(is_valid());\n  return make_unique<RecurrentLayer_Context>(get_state_size(), get_output_size(), batch_size);\n}\nunique_ptr<Layer::Context> yann::RecurrentLayer::create_context(const RefVectorBatch & output) const\n{\n  YANN_CHECK(is_valid());\n  return make_unique<RecurrentLayer_Context>(get_state_size(), output);\n}\nunique_ptr<Layer::Context> yann::RecurrentLayer::create_training_context(\n    const MatrixSize & batch_size, const std::unique_ptr<Layer::Updater> & updater) const\n{\n  YANN_CHECK(is_valid());\n  YANN_CHECK(updater);\n  return make_unique<RecurrentLayer_TrainingContext>(\n      get_input_size(), get_state_size(), get_output_size(), batch_size, updater);\n}\nunique_ptr<Layer::Context> yann::RecurrentLayer::create_training_context(\n    const RefVectorBatch & output, const std::unique_ptr<Layer::Updater> & updater) const\n{\n  YANN_CHECK(is_valid());\n  YANN_CHECK(updater);\n  return make_unique<RecurrentLayer_TrainingContext>(\n      get_input_size(), get_state_size(), output, updater);\n}\n\ntemplate<typename InputType>\nvoid yann::RecurrentLayer::feedforward_internal(\n    const InputType & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  auto ctx = dynamic_cast<RecurrentLayer_Context *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(is_valid());\n  YANN_CHECK_LE(get_batch_size(input) + ctx->_pos, ctx->get_batch_size());\n  YANN_CHECK_LE(get_batch_size(input), get_batch_size(ctx->get_output()));\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_SLOW_CHECK(is_same_size(ctx->_zz_h, ctx->_hh));\n  YANN_SLOW_CHECK(is_same_size(ctx->_zz_a, ctx->get_output()));\n\n  for(MatrixSize ii = 0; ii < get_batch_size(input); ++ii, ++ctx->_pos) {\n    // hh(t) = state_activation_function(ww_hh * hh(t-1) + ww_xh*x(t) + b_h)  // state\n    auto in = get_batch(input, ii);\n    auto out = get_batch(ctx->get_output(), ctx->_pos);\n    auto hh = get_batch(ctx->_hh, ctx->_pos);\n    auto zz_h = get_batch(ctx->_zz_h, ctx->_pos);\n    auto zz_a = get_batch(ctx->_zz_a, ctx->_pos);\n\n    if(ctx->_pos > 0) {\n      auto hh_prev = get_batch(ctx->_hh, ctx->_pos - 1);\n      zz_h = MatrixFunctions<InputType>::product(hh_prev, _ww_hh) +\n             MatrixFunctions<InputType>::product(in, _ww_xh) +\n             _bb_h;\n    } else {\n      zz_h = MatrixFunctions<InputType>::product(in, _ww_xh) +\n            _bb_h;\n    }\n    _state_activation_function->f(zz_h, hh, Operation_Assign);\n\n    // a(t) = output_activation_function(ww_ha * hh(t) + b_a) // output\n    zz_a = MatrixFunctions<InputType>::product(hh, _ww_ha) +\n        _bb_a;\n    _state_activation_function->f(zz_a, out, mode);\n  }\n}\n\nvoid yann::RecurrentLayer::feedforward(\n    const RefConstVectorBatch & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  feedforward_internal(input, context, mode);\n}\n\nvoid yann::RecurrentLayer::feedforward(\n    const RefConstSparseVectorBatch & input,\n    Context * context,\n    enum OperationMode mode) const\n{\n  feedforward_internal(input, context, mode);\n}\n\ntemplate<typename InputType>\nvoid yann::RecurrentLayer::backprop_internal(\n    const RefConstVectorBatch & gradient_output,\n    const InputType & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  auto ctx = dynamic_cast<RecurrentLayer_TrainingContext *>(context);\n  YANN_CHECK(ctx);\n  YANN_CHECK(is_valid());\n  YANN_CHECK_GT(get_batch_size(gradient_output), 0);\n  YANN_CHECK_LE(get_batch_size(gradient_output), ctx->_pos);\n  YANN_CHECK_EQ(get_batch_item_size(gradient_output), get_output_size());\n  YANN_CHECK_EQ(get_batch_size(input), get_batch_size(gradient_output));\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_CHECK_EQ(get_batch_item_size(input), get_input_size());\n  YANN_CHECK(!gradient_input || is_same_size(input, *gradient_input));\n\n  for(MatrixSize ii = get_batch_size(gradient_output) - 1; ii >= 0 && (--ctx->_pos) >= 0; --ii) {\n    auto gradient_out = get_batch(gradient_output, ii);\n    auto in = get_batch(input, ii);\n    auto hh = get_batch(ctx->_hh, ctx->_pos);\n    auto zz_h = get_batch(ctx->_zz_h, ctx->_pos);\n    auto zz_a = get_batch(ctx->_zz_a, ctx->_pos);\n\n    //\n    // output:\n    //\n    auto & sigma_derivative_zz_a = ctx->_sigma_derivative_zz_a;\n    auto & delta_a = ctx->_delta_a;\n    auto & delta_ww_ha = ctx->_delta_ww_ha;\n    auto & delta_bb_a = ctx->_delta_bb_a;\n    auto & gradient_h = ctx->_gradient_h;\n\n    // delta_a(t)    = elem_prod(gradient(C, a(t)), activation_derivative(zz_a(t)))\n    YANN_SLOW_CHECK(is_same_size(zz_a, sigma_derivative_zz_a));\n    YANN_SLOW_CHECK(is_same_size(zz_a, gradient_out));\n    YANN_SLOW_CHECK(is_same_size(zz_a, delta_a));\n    _output_activation_function->derivative(zz_a, sigma_derivative_zz_a);\n    delta_a.array() = gradient_out.array() * sigma_derivative_zz_a.array();\n\n    // dC/d b_a(t)   = delta_a(t)\n    YANN_SLOW_CHECK(is_same_size(delta_bb_a, delta_a));\n    delta_bb_a.noalias()  += delta_a;\n\n    // dC/d ww_ha(t) = hh(t) * delta_a(t)\n    YANN_SLOW_CHECK(is_same_size(delta_ww_ha, _ww_ha));\n    delta_ww_ha.noalias() += MatrixFunctions<InputType>::product(hh.transpose(), delta_a);\n\n    // total_gradient(C, hh(t)) = gradient(C, hh(t)) + transp(ww_ha) * delta_a(t)\n    gradient_h.noalias()  += MatrixFunctions<InputType>::product(delta_a, _ww_ha.transpose());\n\n    //\n    // state:\n    //\n    auto & sigma_derivative_zz_h = ctx->_sigma_derivative_zz_h;\n    auto & delta_h = ctx->_delta_h;\n    auto & delta_ww_xh = ctx->_delta_ww_xh;\n    auto & delta_ww_hh = ctx->_delta_ww_hh;\n    auto & delta_bb_h = ctx->_delta_bb_h;\n\n    // delta_h(t) = elem_prod(total_gradient(C, hh(t)), activation_derivative(zz_h(t)))\n    YANN_CHECK(is_same_size(zz_h, sigma_derivative_zz_h));\n    YANN_CHECK(is_same_size(zz_h, gradient_h));\n    _state_activation_function->derivative(zz_h, sigma_derivative_zz_h);\n    delta_h.array() = gradient_h.array() * sigma_derivative_zz_h.array();\n\n    // dC/d b_h(t) = delta_h(t)\n    YANN_CHECK(is_same_size(delta_bb_h, delta_h));\n    delta_bb_h.noalias() += delta_h;\n\n    // dC/d ww_xh(t) = x(t) * delta_h(t)\n    YANN_SLOW_CHECK(is_same_size(delta_ww_xh, _ww_xh));\n    delta_ww_xh += MatrixFunctions<InputType>::product(in.transpose(), delta_h);\n\n    // dC/d ww_hh(t) = hh(t-1) * delta_h(t)\n    if(ctx->_pos > 0) {\n      auto prev_hh = get_batch(ctx->_hh, ctx->_pos - 1);\n      YANN_SLOW_CHECK(is_same_size(delta_ww_hh, _ww_hh));\n      delta_ww_hh.noalias() += MatrixFunctions<InputType>::product(prev_hh.transpose(), delta_h);\n    }\n\n    // gradient(C, hh(t-1)) = transp(ww_hh) * delta_h(t)\n    if(ctx->_pos > 0) {\n      gradient_h.noalias() = MatrixFunctions<InputType>::product(delta_h, _ww_hh.transpose());\n    }\n\n    // gradient(C, x(t)) = transp(ww_xh) * delta_h(t)\n    if(gradient_input) {\n      auto gradient_in = get_batch(*gradient_input, ii);\n      gradient_in.noalias() = MatrixFunctions<InputType>::product(delta_h, _ww_xh.transpose());\n    }\n  }\n}\n\nvoid yann::RecurrentLayer::backprop(\n    const RefConstVectorBatch & gradient_output,\n    const RefConstVectorBatch & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  backprop_internal(gradient_output, input, gradient_input, context);\n}\n\nvoid yann::RecurrentLayer::backprop(\n    const RefConstVectorBatch & gradient_output,\n    const RefConstSparseVectorBatch & input,\n    optional<RefVectorBatch> gradient_input,\n    Context * context) const\n{\n  // <RefConstSparseMatrix> is required for MatrixFunctions<>::product\n  backprop_internal<RefConstSparseMatrix>(gradient_output, input, gradient_input, context);\n}\n\nvoid yann::RecurrentLayer::init(enum InitMode mode, boost::optional<InitContext> init_context)\n{\n  switch (mode) {\n  case InitMode_Zeros:\n    _ww_hh.setZero();\n    _ww_xh.setZero();\n    _bb_h.setZero();\n    _ww_ha.setZero();\n    _bb_a.setZero();\n    break;\n  case InitMode_Random:\n    {\n      unique_ptr<RandomGenerator> gen01 = RandomGenerator::normal_distribution(0, 1,\n          init_context ? optional<Value>(init_context->seed()) : boost::none);\n      gen01->generate(_ww_hh);\n      gen01->generate(_ww_xh);\n      gen01->generate(_bb_h);\n      gen01->generate(_ww_ha);\n      gen01->generate(_bb_a);\n    }\n    break;\n  }\n}\n\nvoid yann::RecurrentLayer::update(Context * context, const size_t & tests_num)\n{\n  auto ctx = dynamic_cast<RecurrentLayer_TrainingContext *>(context);\n  YANN_CHECK(ctx);\n  YANN_SLOW_CHECK(ctx->_ww_hh_updater);\n  YANN_SLOW_CHECK(ctx->_ww_xh_updater);\n  YANN_SLOW_CHECK(ctx->_bb_h_updater);\n  YANN_SLOW_CHECK(ctx->_ww_ha_updater);\n  YANN_SLOW_CHECK(ctx->_bb_a_updater);\n  YANN_SLOW_CHECK(is_same_size(_ww_hh, ctx->_delta_ww_hh));\n  YANN_SLOW_CHECK(is_same_size(_ww_xh, ctx->_delta_ww_xh));\n  YANN_SLOW_CHECK(is_same_size(_bb_h, ctx->_delta_bb_h));\n  YANN_SLOW_CHECK(is_same_size(_ww_ha, ctx->_delta_ww_ha));\n  YANN_SLOW_CHECK(is_same_size(_bb_a, ctx->_delta_bb_a));\n\n  ctx->_ww_hh_updater->update(ctx->_delta_ww_hh, tests_num, _ww_hh);\n  ctx->_ww_xh_updater->update(ctx->_delta_ww_xh, tests_num, _ww_xh);\n  ctx->_bb_h_updater->update(ctx->_delta_bb_h, tests_num, _bb_h);\n  ctx->_ww_ha_updater->update(ctx->_delta_ww_ha, tests_num, _ww_ha);\n  ctx->_bb_a_updater->update(ctx->_delta_bb_a, tests_num, _bb_a);\n}\n\n// the format is (wh:<_ww_hh>,wx:<_ww_xh>,bh:<_bb_h>,wa:<_ww_ha>,ba:<_bb_a>)\nvoid yann::RecurrentLayer::read(std::istream & is)\n{\n  Base::read(is);\n\n  read_char(is, '(');\n  read_object(is, \"wh\", _ww_hh);\n  read_char(is, ',');\n  read_object(is, \"wx\", _ww_xh);\n  read_char(is, ',');\n  read_object(is, \"bh\", _bb_h);\n  read_char(is, ',');\n  read_object(is, \"wa\", _ww_ha);\n  read_char(is, ',');\n  read_object(is, \"ba\", _bb_a);\n  read_char(is, ')');\n}\n\n// the format is (wh:<_ww_hh>,wx:<_ww_xh>,bh:<_bb_h>,wa:<_ww_ha>,ba:<_bb_a>)\nvoid yann::RecurrentLayer::write(std::ostream & os) const\n{\n  Base::write(os);\n\n  os << \"(\";\n  write_object(os, \"wh\", _ww_hh);\n  os << \",\";\n  write_object(os, \"wx\", _ww_xh);\n  os << \",\";\n  write_object(os, \"bh\", _bb_h);\n  os << \",\";\n  write_object(os, \"wa\", _ww_ha);\n  os << \",\";\n  write_object(os, \"ba\", _bb_a);\n  os << \")\";\n}\n\n", "meta": {"hexsha": "4974a44ec9d4f324bb8e130a6852a294b7c8e2b9", "size": 20013, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/layers/reclayer.cpp", "max_stars_repo_name": "lsh123/yann", "max_stars_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T18:14:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-01T10:25:07.000Z", "max_issues_repo_path": "src/layers/reclayer.cpp", "max_issues_repo_name": "lsh123/yann", "max_issues_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/layers/reclayer.cpp", "max_forks_repo_name": "lsh123/yann", "max_forks_repo_head_hexsha": "4a12b7c1ee2d89d34772d647586b3018df6997db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2311178248, "max_line_length": 101, "alphanum_fraction": 0.6894518563, "num_tokens": 5718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.4171680014957301}}
{"text": "#include \"NlMeans.hpp\"\n\n#include \"thread/ThreadUtils.hpp\"\n#include \"thread/ThreadPool.hpp\"\n\n#include \"Logging.hpp\"\n\n#include <Eigen/Dense>\n#include <iostream>\n#include <vector>\n\nnamespace Tungsten {\n\nPixmap3f collaborativeRegression(const Pixmap3f &image, const Pixmap3f &guide,\n        const std::vector<PixmapF> &features, const Pixmap3f &imageVariance,\n        int F, int R, float k)\n{\n    int w = image.w();\n    int h = image.h();\n    int d = features.size() + 3;\n\n    // We parallellize by dicing up the image into 32x32 tiles\n    const int TileSize = 32;\n    int padSize = TileSize + 2*F;\n\n    struct Tile\n    {\n        Vec2i pos;\n        Box2i dstRect;\n        Pixmap3f result;\n        PixmapF resultWeights;\n        Tile(int x, int y) : pos(x, y) {}\n    };\n\n    std::vector<Tile> tiles;\n    for (int tileY : range(0, h, TileSize))\n        for (int tileX : range(0, w, TileSize))\n            tiles.emplace_back(tileX, tileY);\n\n    struct PerThreadData { Pixmap3f tmpBufA, tmpBufB; std::vector<PixmapF> weights; };\n    std::vector<std::unique_ptr<PerThreadData>> threadData(ThreadUtils::idealThreadCount());\n\n    ThreadUtils::pool->enqueue([&](uint32 i, uint32, uint32 threadId) {\n        printProgressBar(i, tiles.size());\n\n        if (!threadData[threadId]) {\n            threadData[threadId].reset(new PerThreadData());\n            threadData[threadId]->tmpBufA = Pixmap3f(padSize, padSize);\n            threadData[threadId]->tmpBufB = Pixmap3f(padSize, padSize);\n            for (int i = 0; i < (2*R + 1)*(2*R + 1); ++i)\n                threadData[threadId]->weights.emplace_back(TileSize, TileSize);\n        }\n        auto &data = *threadData[threadId];\n        Tile &tile = tiles[i];\n\n        for (auto &w : data.weights)\n            w.clear();\n\n        Box2i srcRect(tile.pos, min(tile.pos + TileSize, Vec2i(w, h)));\n        tile.dstRect = srcRect;\n        tile.dstRect.grow(R);\n        tile.dstRect.intersect(Box2i(Vec2i(0), Vec2i(w, h)));\n        int dstW = tile.dstRect.diagonal().x(), dstH = tile.dstRect.diagonal().y();\n\n        tile.result = Pixmap3f(dstW, dstH);\n        tile.resultWeights = PixmapF(dstW, dstH);\n\n        // Precompute weights for entire tile\n        for (int dy = -R, idxW = 0; dy <= R; ++dy)\n            for (int dx = -R; dx <= R; ++dx, ++idxW)\n                nlMeansWeights(data.weights[idxW], data.tmpBufA, data.tmpBufB, guide, imageVariance,\n                        srcRect, F, k, dx, dy, 2.0f);\n\n        for (int y = srcRect.min().y(); y < srcRect.max().y(); ++y) {\n            for (int x = srcRect.min().x(); x < srcRect.max().x(); ++x) {\n                int x0 = max(x - R, 0), x1 = min(w, x + R + 1);\n                int y0 = max(y - R, 0), y1 = min(h, y + R + 1);\n                int n = (x1 - x0)*(y1 - y0);\n\n                // Build weight matrix (W), feature matrix (X) and RHS (Y)\n                Eigen::VectorXf W(n);\n                Eigen::MatrixXf Y(n, 3);\n                Eigen::MatrixXf X(n, d);\n\n                for (int iy = y0; iy < y1; ++iy) {\n                    for (int ix = x0; ix < x1; ++ix) {\n                        int idxP = ix + iy*w;\n                        int idx = (ix - x0) + (iy - y0)*(x1 - x0);\n\n                        for (int i = 0; i < 3; ++i)\n                            Y(idx, i) = image[idxP][i];\n\n                        X(idx, 0) = 1.0f;\n                        X(idx, 1) = ix - x;\n                        X(idx, 2) = iy - y;\n                        for (size_t i = 0; i < features.size(); ++i)\n                            X(idx, i + 3) = features[i][idxP] - features[i][x + y*w];\n\n                        int idxW = (ix - x + R) + (iy - y + R)*(2*R + 1);\n                        W[idx] = data.weights[idxW][Vec2i(x, y) - tile.pos];\n                    }\n                }\n\n                // Solve least squares system\n                Eigen::VectorXf wSqrt = W.cwiseSqrt();\n                Eigen::MatrixXf denoised = X*(wSqrt.asDiagonal()*X).colPivHouseholderQr().solve(wSqrt.asDiagonal()*Y);\n\n                // Accumulate denoised patch into image\n                for (int iy = y0; iy < y1; ++iy) {\n                    for (int ix = x0; ix < x1; ++ix) {\n                        Vec2i p = Vec2i(ix, iy) - tile.dstRect.min();\n                        int idx = (ix - x0) + (iy - y0)*(x1 - x0);\n                        tile.result       [p] += W[idx]*Vec3f(denoised(idx, 0), denoised(idx, 1), denoised(idx, 2));\n                        tile.resultWeights[p] += W[idx];\n                    }\n                }\n            }\n        }\n\n    }, tiles.size())->wait();\n\n    // Gather results from all threads and divide by weights\n    Pixmap3f result(w, h);\n    PixmapF resultWeights(w, h);\n    for (const auto &tile : tiles) {\n        for (int y  : tile.dstRect.range(1)) {\n            for (int x  : tile.dstRect.range(0)) {\n                Vec2i p(x, y);\n                result       [p] += tile.result       [p - tile.dstRect.min()];\n                resultWeights[p] += tile.resultWeights[p - tile.dstRect.min()];\n            }\n        }\n    }\n    for (int j = 0; j < w*h; ++j)\n        result[j] /= resultWeights[j];\n\n    printProgressBar(tiles.size(), tiles.size());\n\n    return std::move(result);\n}\n\n}\n", "meta": {"hexsha": "0959f51af9db4ed82b37b89a15f2a1e562e1ff19", "size": 5188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/denoiser/Regression.cpp", "max_stars_repo_name": "chaosink/tungsten", "max_stars_repo_head_hexsha": "88ea02044dbaf20472a8173b6752460b50c096d8", "max_stars_repo_licenses": ["Apache-2.0", "Unlicense"], "max_stars_count": 1655.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T13:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T13:37:57.000Z", "max_issues_repo_path": "src/denoiser/Regression.cpp", "max_issues_repo_name": "chaosink/tungsten", "max_issues_repo_head_hexsha": "88ea02044dbaf20472a8173b6752460b50c096d8", "max_issues_repo_licenses": ["Apache-2.0", "Unlicense"], "max_issues_count": 65.0, "max_issues_repo_issues_event_min_datetime": "2015-01-13T08:34:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-08T05:07:58.000Z", "max_forks_repo_path": "src/denoiser/Regression.cpp", "max_forks_repo_name": "chaosink/tungsten", "max_forks_repo_head_hexsha": "88ea02044dbaf20472a8173b6752460b50c096d8", "max_forks_repo_licenses": ["Apache-2.0", "Unlicense"], "max_forks_count": 190.0, "max_forks_repo_forks_event_min_datetime": "2015-01-12T14:53:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T17:30:00.000Z", "avg_line_length": 36.2797202797, "max_line_length": 118, "alphanum_fraction": 0.4882420971, "num_tokens": 1471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4171632791584198}}
{"text": "/*\n * ElGammal.cpp\n *\n *  Created on: 03.10.2010\n *      Author: stephaniebayer\n */\n\n#include \"ElGammal.h\"\n#include \"G_q.h\"\n\n#include <NTL/ZZ.h>\nNTL_CLIENT\n\n#include \"Mod_p.h\"\n#include <stdio.h>\n#include <time.h>\n#include <vector>\n#include <fstream>\n\n\nElGammal::ElGammal() {\n\t// TODO Auto-generated constructor stub\n\n}\n\n//Creates ElGammal with secret key s, public key p and group H\nElGammal::ElGammal(long s, Mod_p p, G_q H){\n\tG=H;\n\tsk = to_ZZ(s);\n\tpk = p;\n\n}\n\n//Creates ElGammal with secret key s, public key p and group H\nElGammal::ElGammal(ZZ s, Mod_p p, G_q H){\n\tG=H;\n\tsk = s;\n\tpk = p;\n\n}\n\n//Creates ElGammal with secret key s and group H, the public key is pk = gen^s , gen generator of H\nElGammal::ElGammal(long s, G_q H){\n\tMod_p temp;\n\tG = H;\n\tsk = to_ZZ(s);\n\ttemp = Mod_p(G.get_gen().get_val(), G.get_mod());\n\tpk = temp.expo(s);\n}\n\n//Creates ElGammal with secret key s and group H, the public key is pk = gen^s , gen generator of H\nElGammal::ElGammal(ZZ s, G_q H){\n\tMod_p temp;\n\tG = H;\n\tsk = s;\n\ttemp = Mod_p(G.get_gen().get_val(), G.get_mod());\n\tpk = temp.expo(s);\n}\n\n//Set the group to G_q with order o, G_q subset of G_mod_p and generator gen, secret key is s and pk = gen^s\nElGammal::ElGammal(Mod_p gen, long o, long  mod, long s){\n\n\tG = G_q(gen, o, mod);\n\tsk = to_ZZ(s);\n\tMod_p temp;\n\ttemp = Mod_p(gen.get_val(), mod);\n\tpk = temp.expo(s);\n}\n\n//Set the group to G_q with order o, G_q subset of G_mod_p and generator gen, secret key is s and pk = gen^s\nElGammal::ElGammal(Mod_p gen, long o, ZZ  mod, long s){\n\n\tG = G_q(gen, o, mod);\n\tsk = to_ZZ(s);\n\tMod_p temp;\n\ttemp = Mod_p(gen.get_val(), mod);\n\tpk = temp.expo(s);\n}\n\n//Set the group to G_q with order o, G_q subset of G_mod_p and generator gen, secret key is s and pk = gen^s\nElGammal::ElGammal(Mod_p gen, long o, ZZ  mod, ZZ s){\n\n\tG = G_q(gen, o, mod);\n\tsk = s;\n\tMod_p temp;\n\ttemp = Mod_p(gen.get_val(), mod);\n\tpk = temp.expo(s);\n}\n\n//Set the group to G_q with order o, G_q subset of G_mod_p and generator gen, secret key is s and pk = gen^s\nElGammal::ElGammal(Mod_p gen, ZZ o, ZZ  mod, long s){\n\n\tG = G_q(gen, o, mod);\n\tsk = to_ZZ(s);\n\tMod_p temp;\n\ttemp = Mod_p(gen.get_val(), mod);\n\tpk = temp.expo(s);\n}\n\n//Set the group to G_q with order o, G_q subset of G_mod_p and generator gen, secret key is s and pk = gen^s\nElGammal::ElGammal(Mod_p gen, ZZ o, ZZ  mod, ZZ s){\n\n\tG = G_q(gen, o, mod);\n\tsk = s;\n\tMod_p temp;\n\ttemp = Mod_p(gen.get_val(), mod);\n\tpk = temp.expo(s);\n}\n\n//Set the group to G_q with order o, G_q subset of G_mod_p and generator gen, secret key is s and public key p\nElGammal::ElGammal(Mod_p gen, long o, long  mod, long s, Mod_p p){\n\n\tG = G_q(gen, o, mod);\n\tsk = to_ZZ(s);\n\tpk = p;\n}\n\n//Set the group to G_q with order o, G_q subset of G_mod_p and generator gen, secret key is s and public key p\nElGammal::ElGammal(Mod_p gen, long o, ZZ  mod, long s, Mod_p p){\n\n\tG = G_q(gen, o, mod);\n\tsk = to_ZZ(s);\n\tpk = p;\n}\n\n//Set the group to G_q with order o, G_q subset of G_mod_p and generator gen, secret key is s and public key p\nElGammal::ElGammal(Mod_p gen, long o, ZZ  mod, ZZ s, Mod_p p){\n\n\tG = G_q(gen, o, mod);\n\tsk = s;\n\tpk = p;\n}\n\n//Set the group to G_q with order o, G_q subset of G_mod_p and generator gen, secret key is s and public key p\nElGammal::ElGammal(Mod_p gen, ZZ o, ZZ  mod, long s, Mod_p p){\n\n\tG = G_q(gen, o, mod);\n\tsk = to_ZZ(s);\n\tpk = p;\n}\n\n//Set the group to G_q with order o, G_q subset of G_mod_p and generator gen, secret key is s and public key p\nElGammal::ElGammal(Mod_p gen, ZZ o, ZZ  mod, ZZ s, Mod_p p){\n\n\tG = G_q(gen, o, mod);\n\tsk = s;\n\tpk = p;\n}\n\n//Set the group to G_q with order o, G_q subset of G_mod_p and generator gen, secret key is s and public key p\nElGammal::ElGammal( long o, long  mod, long s, Mod_p p){\n\n\tG = G_q( o, mod);\n\tsk = to_ZZ(s);\n\tpk = p;\n}\n\n//Set the group to G_q with order o and modular value mod, secret key is s and public key p\nElGammal::ElGammal( long o, ZZ  mod, long s, Mod_p p){\n\n\tG = G_q( o, mod);\n\tsk = to_ZZ(s);\n\tpk = p;\n}\n\n//Set the group to G_q with order o and modular value mod, secret key is s and public key p\nElGammal::ElGammal( long o, ZZ  mod, ZZ s, Mod_p p){\n\n\tG = G_q( o, mod);\n\tsk = s;\n\tpk = p;\n}\n\n//Set the group to G_q with order o and modular value mod, secret key is s and public key p\nElGammal::ElGammal( ZZ o, ZZ  mod, long s, Mod_p p){\n\n\tG = G_q( o, mod);\n\tsk = to_ZZ(s);\n\tpk = p;\n}\n\n//Set the group to G_q with order o and modular value mod, secret key is s and public key p\nElGammal::ElGammal( ZZ o, ZZ  mod, ZZ s, Mod_p p){\n\n\tG = G_q( o, mod);\n\tsk = to_ZZ(s);\n\tpk = p;\n}\n\n//Set the group to G_q with order o and modular value mod, secret key is s and public key pk = gen^s\nElGammal::ElGammal( long o, long  mod, long s){\n\n\tG = G_q( o, mod);\n\tsk = to_ZZ(s);\n\tMod_p temp;\n\ttemp = Mod_p(G.get_gen().get_val(), mod);\n\tpk = temp.expo(s);\n}\n\n//Set the group to G_q with order o and modular value mod, secret key is s and public key pk = gen^s\nElGammal::ElGammal( long o, ZZ  mod, long s){\n\n\tG = G_q( o, mod);\n\tsk = to_ZZ(s);\n\tMod_p temp;\n\ttemp = Mod_p(G.get_gen().get_val(), mod);\n\tpk = temp.expo(s);\n}\n\n//Set the group to G_q with order o and modular value mod, secret key is s and public key pk = gen^s\nElGammal::ElGammal( long o, ZZ  mod, ZZ s){\n\n\tG = G_q( o, mod);\n\tsk = s;\n\tMod_p temp;\n\ttemp = Mod_p(G.get_gen().get_val(), mod);\n\tpk = temp.expo(s);\n}\n\n//Set the group to G_q with order o and modular value mod, secret key is s and public key pk = gen^s\nElGammal::ElGammal( ZZ o, ZZ  mod, long s){\n\n\tG = G_q( o, mod);\n\tsk = to_ZZ(s);\n\tMod_p temp;\n\ttemp = Mod_p(G.get_gen().get_val(), mod);\n\tpk = temp.expo(s);\n}\n\n//Set the group to G_q with order o and modular value mod, secret key is s and public key pk = gen^s\nElGammal::ElGammal( ZZ o, ZZ  mod, ZZ s){\n\n\tG = G_q( o, mod);\n\tsk = s;\n\tMod_p temp;\n\ttemp = Mod_p(G.get_gen().get_val(), mod);\n\tpk = temp.expo(s);\n}\n\n\nElGammal::~ElGammal() {\n\t// TODO Auto-generated destructor stub\n}\n\n//Access to the parameters\nG_q ElGammal::get_group()const{\n\treturn G;\n}\n\nMod_p ElGammal::get_pk() const{\n\n\treturn pk;\n}\n\nZZ ElGammal::get_sk()const{\n\n\treturn sk;\n}\n\n//functions to change parameters\nvoid ElGammal::set_group(G_q H){\n\n\tG = H;\n}\n\nvoid ElGammal::set_sk(long s){\n\n\tsk = to_ZZ(s);\n\tpk = G.get_gen().expo( s);\n}\n\nvoid ElGammal::set_sk(ZZ s){\n\n\tsk = s;\n\tpk = G.get_gen().expo(s);\n\tstring name = \"example.txt\";\n\tofstream ost;\n\tost.open(name.c_str(),ios::app);\n\tost<<\"private key and public key \"<<sk<<\" \"<<pk<<endl;\n}\n\n//functions to encrypt value/element\nCipher_elg ElGammal::encrypt(Mod_p el){\n\tCipher_elg c;\n\tMod_p temp_1, temp_2;\n\tZZ ran;\n\tSetSeed(to_ZZ(time(0)));\n\tran = RandomBnd(G.get_ord());\n\ttemp_1 = G.get_gen().expo(ran);\n\ttemp_2 = pk.expo(ran)*el;\n\tc = Cipher_elg(temp_1,temp_2);\n\treturn c;\n\n}\n\nCipher_elg ElGammal::encrypt(ZZ m){\n\tCipher_elg c;\n\tMod_p temp_1, temp_2;\n\tZZ ran;\n\tSetSeed(to_ZZ(time(0)));\n\tran = RandomBnd(G.get_ord());\n\tcout<< ran << endl;\n\ttemp_1 = G.get_gen().expo(ran);\n\ttemp_2 = pk.expo(ran)*Mod_p(m,G.get_mod());\n\tc = Cipher_elg(temp_1,temp_2);\n\treturn c;\n}\n\nCipher_elg ElGammal::encrypt(long m){\n\tCipher_elg c;\n\tMod_p temp_1, temp_2;\n\tZZ ran;\n\tSetSeed(to_ZZ(time(0)));\n\tran = RandomBnd(G.get_ord());\n\ttemp_1 = G.get_gen().expo(ran);\n\ttemp_2 = pk.expo(ran)*Mod_p(m,G.get_mod());\n\tc = Cipher_elg(temp_1,temp_2);\n\treturn c;\n}\n\nCipher_elg ElGammal::encrypt(Mod_p el, long ran){\n\tCipher_elg c;\n\tMod_p temp_1, temp_2;\n\ttemp_1 = G.get_gen().expo(ran);\n\ttemp_2 = pk.expo(ran)*el;\n\tc = Cipher_elg(temp_1,temp_2);\n\treturn c;\n\n}\n\nCipher_elg ElGammal::encrypt(Mod_p el, ZZ ran){\n\tCipher_elg c;\n\tMod_p temp_1, temp_2;\n\ttemp_1 = G.get_gen().expo(ran);\n\ttemp_2 = pk.expo(ran)*el;\n\tc = Cipher_elg(temp_1,temp_2);\n\treturn c;\n\n}\n\n\nCipher_elg ElGammal::encrypt(ZZ m, long ran){\n\tCipher_elg c;\n\tMod_p temp_1, temp_2;\n\ttemp_1 = G.get_gen().expo(ran);\n\ttemp_2 = pk.expo(ran)*Mod_p(m,G.get_mod());\n\tc = Cipher_elg(temp_1,temp_2);\n\treturn c;\n}\n\nCipher_elg ElGammal::encrypt(ZZ m, ZZ ran){\n\tCipher_elg c;\n\tMod_p temp_1, temp_2;\n\ttemp_1 = G.get_gen().expo(ran);\n\ttemp_2 = pk.expo(ran)*Mod_p(m,G.get_mod());\n\tc = Cipher_elg(temp_1,temp_2);\n\treturn c;\n}\n\n\nCipher_elg ElGammal::encrypt(long m, long ran){\n\tCipher_elg c;\n\tMod_p temp_1, temp_2;\n\ttemp_1 = G.get_gen().expo(ran);\n\ttemp_2 = pk.expo(ran)*Mod_p(m,G.get_mod());\n\tc = Cipher_elg(temp_1,temp_2);\n\treturn c;\n}\n\n\nCipher_elg ElGammal::encrypt(long m, ZZ ran){\n\tCipher_elg c;\n\tMod_p temp_1, temp_2;\n\ttemp_1 = G.get_gen().expo(ran);\n\ttemp_2 = pk.expo(ran)*Mod_p(m,G.get_mod());\n\tc = Cipher_elg(temp_1,temp_2);\n\treturn c;\n}\n\n//Decrypts the ciphertext c\nMod_p ElGammal::decrypt(Cipher_elg c){\n\tZZ temp;\n\tZZ mod = G.get_mod();\n\ttemp = InvMod(c.get_u(),mod);\n\ttemp = PowerMod(temp,sk, mod);\n\ttemp = MulMod(temp,c.get_v(),mod);\n\treturn temp;\n}\n\n//Assigment operator\nvoid ElGammal::operator=(const ElGammal& el){\n\n\tG = el.get_group();\n\tsk = el.get_sk();\n\tpk = el.get_pk();\n}\n\n", "meta": {"hexsha": "0801fbba3bcea91f148de64f461eeb52455e7e06", "size": 8831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ElGammal.cpp", "max_stars_repo_name": "3for/verifiable-shuffle", "max_stars_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-11T14:06:41.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T08:28:26.000Z", "max_issues_repo_path": "src/ElGammal.cpp", "max_issues_repo_name": "3for/verifiable-shuffle", "max_issues_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ElGammal.cpp", "max_forks_repo_name": "3for/verifiable-shuffle", "max_forks_repo_head_hexsha": "73f92b41bbe76eee4ef8ad35e6ccf7e83acef28b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-13T06:11:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-03T15:21:49.000Z", "avg_line_length": 22.1884422111, "max_line_length": 110, "alphanum_fraction": 0.6568904994, "num_tokens": 3146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4171632738201456}}
{"text": "#ifndef TRIUMF_BNMR_SRF_NONLOCAL_HPP\n#define TRIUMF_BNMR_SRF_NONLOCAL_HPP\n\n// C++ standard library headers\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <numeric>\n#include <vector>\n\n// Boost headers\n#include <boost/math/interpolators/pchip.hpp>\n#include <boost/math/quadrature/tanh_sinh.hpp>\n\n// triumf++ headers\n#include <triumf/bnmr/nuclei.hpp>\n#include <triumf/nmr/dipole_dipole.hpp>\n#include <triumf/nmr/nuclei.hpp>\n#include <triumf/numpy.hpp>\n#include <triumf/srim/pdf.hpp>\n#include <triumf/superconductivity/bcs.hpp>\n#include <triumf/superconductivity/pippard.hpp>\n\n// ROOT headers\n#include <ROOT/RCsvDS.hxx>\n#include <ROOT/RDF/RInterface.hxx>\n#include <ROOT/RDataFrame.hxx>\n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// β-detected nuclear magnetic resonance (β-NMR)\nnamespace bnmr {\n\n// superconducting radio-frequency (SRF) materials\nnamespace srf {\n\n// nonlocal electrodynamics\nnamespace nonlocal {\n\n/// model slr rate\ntemplate <typename T = double>\nT slr_rate_z(T z, T temperature, T critical_temperature, T gap_meV, T xi_0,\n             T mean_free_path, T lambda_0, T exponent, T applied_field,\n             T dipole_field, T correlation_rate, T slr_constant, T slr_exponent,\n             T surface_thickness, T surface_rate, T electron_phonon_coupling) {\n  // correct depth for the surface layer\n  T _z_ = z - surface_thickness;\n  if (_z_ < 0.0) {\n    return surface_rate;\n  } else {\n    // convert to values in the weak coupling limit\n    // see e.g., Eqs. (1) & (2) in:\n    // http://dx.doi.org/10.1103/PhysRevB.87.104508\n    T lambda_0_wc = xi_0 * electron_phonon_coupling;\n    T xi_0_wc = lambda_0 / std::sqrt(electron_phonon_coupling);\n    // calculate the local field from the screening profile\n    T screened_field =\n        temperature > critical_temperature\n            ? applied_field\n            : triumf::superconductivity::pippard::field_penetration<T>(\n                  _z_, temperature, critical_temperature, gap_meV, xi_0_wc,\n                  mean_free_path, lambda_0_wc, exponent, applied_field);\n    // calculate the dipole-dipole SLR rate in the superconducting state\n    T dd_rate = triumf::nmr::dipole_dipole::slr_rate<T>(\n        screened_field, dipole_field, correlation_rate,\n        triumf::bnmr::nuclei::lithium_8<T>::gyromagnetic_ratio(),\n        triumf::nmr::nuclei::niobium_93<T>::gyromagnetic_ratio());\n    // calculate the SLR rate in the normal state\n    T ns_rate = slr_constant * std::pow(temperature, slr_exponent);\n    // return the \"surface\" contribution at shallow depths\n    return dd_rate + ns_rate;\n  }\n}\n\n/// depth-resolved analyzer\ntemplate <typename T = double> class DepthResolvedAnalyzer {\npublic:\n  /// constructor.\n  DepthResolvedAnalyzer(const std::string &csv_filename) {\n    // read the data into a ROOT DataFrame...\n    auto df = ROOT::RDF::MakeCsvDataFrame(csv_filename);\n    // ...and extract the values\n    _energy = df.Take<T>(\"Energy (keV)\").GetValue();\n    _alpha = df.Take<T>(\"Alpha\").GetValue();\n    _alpha_error = df.Take<T>(\"Alpha Error\").GetValue();\n    _beta = df.Take<T>(\"Beta\").GetValue();\n    _beta_error = df.Take<T>(\"Beta Error\").GetValue();\n    _z_max = df.Take<T>(\"Max (nm)\").GetValue();\n    _z_max_error = df.Take<T>(\"Max Error (nm)\").GetValue();\n\n    // default initialized values\n    temperature = 2.5;\n    critical_temperature = 9.25;\n    gap_meV =\n        triumf::superconductivity::bcs::gap_meV<double>(critical_temperature);\n    xi_0 = 39.0;\n    mean_free_path = 1e4;\n    lambda_0 = 40.0;\n    exponent = 4.0;\n    applied_field = 0.02;\n    dipole_field = 1e-5;\n    correlation_rate = 1.0 / 23.8e-6;\n    slr_constant = 0.75;\n    slr_exponent = 1.0;\n    surface_thickness = 5.0;\n    surface_rate = 10.0;\n    electron_phonon_coupling = 1.0;\n    //\n    n_bins = 101;\n  };\n\n  /// Return the the minium energy available for interpolation.\n  T energy_min() {\n    return *std::min_element(_energy.begin(), _energy.end()) +\n           std::sqrt(std::numeric_limits<T>::epsilon());\n  };\n\n  /// Return the the maximum energy availalbe for interpolation.\n  T energy_max() {\n    return *std::max_element(_energy.begin(), _energy.end()) -\n           std::sqrt(std::numeric_limits<T>::epsilon());\n  };\n\n  /// Return an interpolated alpha value.\n  T alpha(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>> alpha_interpolator(\n        std::move(std::vector<T>(_energy)), std::move(std::vector<T>(_alpha)));\n    return alpha_interpolator(energy_keV);\n  };\n\n  /// Return an interpolated beta value.\n  T beta(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>> beta_interpolator(\n        std::move(std::vector<T>(_energy)), std::move(std::vector<T>(_beta)));\n    return beta_interpolator(energy_keV);\n  };\n\n  /// Return an interpolated z_max value.\n  T z_max(T energy_keV) {\n    static boost::math::interpolators::pchip<std::vector<T>> z_max_interpolator(\n        std::move(std::vector<T>(_energy)), std::move(std::vector<T>(_z_max)));\n    return z_max_interpolator(energy_keV);\n  };\n\n  /// Return the average implantation depth.\n  T z_average(T energy_keV) {\n    T a = alpha(energy_keV);\n    T b = beta(energy_keV);\n    T zm = z_max(energy_keV);\n    return zm * a / (a + b);\n  };\n\n  /*\n  /// depth-averaging using numeric integration\n  T operator()(T energy_keV) {\n    // T a = alpha(energy_keV);\n    // T b = beta(energy_keV);\n    // T zm = z_max(energy_keV);\n    static boost::math::quadrature::tanh_sinh<T> integrator;\n    auto integrand = [&](T z) {\n      return slr_fcn(z, GLOBAL_R_0, GLOBAL_D_0) *\n             triumf::srim::pdf::modified_beta<T>(\n                 z, alpha(energy_keV), beta(energy_keV), z_max(energy_keV));\n    };\n    T Q = integrator.integrate(integrand, 0.0, z_max(energy_keV));\n    return Q;\n  };\n  */\n\n  // depth-averaging using \"histogram\" summation\n  T operator()(T energy_keV) {\n    // bin edges\n    std::vector<T> z_edge =\n        triumf::numpy::linspace<T>(0.0, z_max(energy_keV), n_bins);\n    // bin widths - adjust ranges by one for \"correct\" size\n    std::vector<T> dz(n_bins - 1);\n    std::adjacent_difference(std::begin(z_edge) + 1, std::end(z_edge),\n                             std::begin(dz));\n    // bin centres\n    std::vector<T> z(n_bins - 1);\n    // probabilities\n    std::vector<T> p_z(n_bins - 1);\n    std::vector<T> weights(n_bins - 1);\n    std::vector<T> slr_rates(n_bins - 1);\n\n    for (std::size_t i = 0; i < z.size(); ++i) {\n      z.at(i) = z_edge.at(i) + 0.5 * dz.at(i);\n      p_z.at(i) = triumf::srim::pdf::modified_beta<T>(\n          z.at(i), alpha(energy_keV), beta(energy_keV), z_max(energy_keV));\n      // std::cout << \"p(\" << z.at(i) << \" nm ) = \" << p_z.at(i) << \" nm^-1\\n\";\n      weights.at(i) = dz.at(i) * p_z.at(i);\n      slr_rates.at(i) = slr_rate_z<T>(\n          z.at(i), temperature, critical_temperature, gap_meV, xi_0,\n          mean_free_path, lambda_0, exponent, applied_field, dipole_field,\n          correlation_rate, slr_constant, slr_exponent, surface_thickness,\n          surface_rate, electron_phonon_coupling);\n    }\n\n    T sum_weights = std::reduce(std::begin(weights), std::end(weights), 0.0);\n    // std::cout << \"sum_weights = \" << sum_weights << \"\\n\";\n    T sum_weights_slr = std::transform_reduce(\n        std::begin(weights), std::end(weights), std::begin(slr_rates), 0.0);\n    // std::cout << \"sum_weights_slr = \" << sum_weights_slr << \"\\n\";\n    T weighted_average = sum_weights_slr / sum_weights;\n    return weighted_average;\n  };\n\n  /// model parameters\n  T temperature;\n  T critical_temperature;\n  T gap_meV;\n  T xi_0;\n  T mean_free_path;\n  T lambda_0;\n  T exponent;\n  T applied_field;\n  T dipole_field;\n  T correlation_rate;\n  T slr_constant;\n  T slr_exponent;\n  T surface_thickness;\n  T surface_rate;\n  T electron_phonon_coupling;\n\nprivate:\n  /// vectors of data from csv file\n  std::vector<T> _energy;\n  std::vector<T> _alpha;\n  std::vector<T> _alpha_error;\n  std::vector<T> _beta;\n  std::vector<T> _beta_error;\n  std::vector<T> _z_max;\n  std::vector<T> _z_max_error;\n  /// number of bins + 1 used in the \"histogram\" summation\n  std::size_t n_bins;\n};\n\n} // namespace nonlocal\n\n} // namespace srf\n\n} // namespace bnmr\n\n} // namespace triumf\n\n#endif // TRIUMF_BNMR_SRF_NONLOCAL_HPP\n", "meta": {"hexsha": "13e6793b72a3fe628d84690d35ed72485a6fcf64", "size": 8242, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/bnmr/srf/nonlocal.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/triumf/bnmr/srf/nonlocal.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/triumf/bnmr/srf/nonlocal.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2338709677, "max_line_length": 80, "alphanum_fraction": 0.6584566853, "num_tokens": 2376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085708384735, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4171632738201456}}
{"text": "/*=============================================================================\nCopyright (c) 2016 Paul W. Bible\n\nDistributed under the Boost Software License, Version 1.0. (See accompanying\nfile LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n==============================================================================*/\n#ifndef GRASM_SHARED_INFORMATION\n#define GRASM_SHARED_INFORMATION\n\n#include <ggtk/SharedInformationInterface.hpp>\n#include <ggtk/TermInformationContentMap.hpp>\n#include <ggtk/GoGraph.hpp>\n#include <ggtk/Accumulators.hpp>\n#include <ggtk/SetUtilities.hpp>\n\n#include <utility>\n#include <algorithm>\n\n#include <boost/unordered_map.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n\n/*! \\class CoutoGraSMSharedInformation\n\t\\brief A class to calculate shared infromation accross disjoint common ancetors using the exact algorithm as written in the paper.\n\n\tThis class calculates shared infromation accross disjoint common ancetors.\n\n    F. M. Couto, M. J. Silva, and P. M. Coutinho, \"Measuring semantic similarity\n\tbetween Gene Ontology terms,\" Data & Knowledge Engineering, vol. 61, \n\tpp. 137-152, Apr 2007.\n\n\tCouto proposing calculating this value a subsituite for the IC of the MICA in calculating\n\t Resnik, Lin, and Jiang-Conrath\n\n*/\nclass CoutoGraSMSharedInformation : public SharedInformationInterface{\n\npublic:\n\t\n\t//! A constructor\n\t/*!\n\t\tCreates the CoutoGraSMGreaterOrEqual class\n\t*/\n\tinline CoutoGraSMSharedInformation(GoGraph* goGraph, TermInformationContentMap &icMap){\n\t\t_goGraph = goGraph;\n\t\t_icMap = icMap;\n\t\t_pathMemory = boost::unordered_map<std::string, size_t>();\n\t}\n\n\n\t//! A method for determining the common disjunctive ancestors\n\t/*!\n\t\tThis method returns the common disjunctive ancestors for two terms\n\t*/\n\tinline boost::unordered_set<std::string> getCommonDisjointAncestors(const std::string &termC1,const std::string &termC2){\n\n\t\tboost::unordered_set<std::string> ancestorsC1 = _goGraph->getAncestorTerms(termC1);\n\t\tancestorsC1.insert(termC1);\n\t\t//std::cout << ancestorsC1.size() << std::endl;\n\t\tboost::unordered_set<std::string> ancestorsC2 = _goGraph->getAncestorTerms(termC2);\n\t\tancestorsC2.insert(termC2);\n\t\t//std::cout << ancestorsC2.size() << std::endl;\n\t\t\n\t\t//Couto: CommonDisjAnc = {}\n\t\tboost::unordered_set<std::string> cda;\n\n\t\tif(termC1.compare(termC2) == 0){\n\t\t\tcda.insert(termC1);\n\t\t\treturn cda;\n\t\t}\n\n\t\t//Couto: Anc = CommonAnc(c1,c2)\n\t\tboost::unordered_set<std::string> commonAncestors = SetUtilities::set_intersection(ancestorsC1,ancestorsC2);\n\t\t//std::cout << commonAncestors.size() << std::endl;\n\n\t\tstd::vector<std::pair<double,std::string> > orderedCommonAncestors;\n\n\t\t\n\n\t\t//create a pair to associate a term with its information content\n\t\tboost::unordered_set<std::string>::iterator iter;\n\t\tfor(iter = commonAncestors.begin(); iter != commonAncestors.end(); ++iter){\n\t\t\tstd::string term = *iter;\n\t\t\torderedCommonAncestors.push_back(std::pair<double,std::string>(_icMap[term],term));\n\t\t}\n\n\t\t//sort descending\n\t\tstd::sort(orderedCommonAncestors.begin(),orderedCommonAncestors.end(),std::greater<std::pair<double,std::string> >());\n\n\t\t\n\t\t//start of main algorithm\n\t\tstd::vector<std::pair<double,std::string> >::iterator pairIter;\n\t\t//Couto: for all a in sortDescByIC(Anc) do ...\n\t\tfor(pairIter = orderedCommonAncestors.begin(); pairIter != orderedCommonAncestors.end(); ++pairIter){\n\t\t\tstd::pair<double,std::string> myPair = *pairIter;\n\t\t\t//std::cout << myPair.first << \" \" << myPair.second << std::endl;\n\n\t\t\tstd::string termA = myPair.second;\n\n\t\t\t//Couto: isDisj=true\n\t\t\tbool isDisj = true;\n\n\t\t\t//std::cout << \"testing \" << termA << std::endl;\n\n\t\t\t//Couto: for all cda in CommonDisjAnc do ...\n\t\t\tboost::unordered_set<std::string>::iterator cdaIter;\n\t\t\tfor(cdaIter = cda.begin(); cdaIter != cda.end();++cdaIter){\n\t\t\t\tstd::string termCda = *cdaIter;\n\n\t\t\t\t//std::cout << \"VS \" << termCda << std::endl;\n\n\t\t\t\t//continue if the terms are the same\n\t\t\t\tif(termCda.compare(termA) == 0){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t//Couto: isDisj = isDisj ^ ( DisjAnc(c1,(a,cda)) or DisjAnc(c2,(a,cda)) )\n\t\t\t\tisDisj = isDisj && (isDisjoint(termC1,termA,termCda) || isDisjoint(termC2,termA,termCda));\n\n\t\t\t}\n\n\t\t\t//Couto: if isDisj then...\n\t\t\tif(isDisj){\n\t\t\t\t//std::cout << myPair.second << \" is cda \" << std::endl;\n\t\t\t\t//Couto: addTo(CommonDisjAnc,a)\n\t\t\t\tcda.insert(myPair.second);\n\t\t\t}\n\t\t}\n\t\treturn cda;\n\t}\n\n\n\t//! A method for determining if for a term c, a pair (a1,a2) is disjoint in c\n\t/*!\n\t\tThis method returns\n\t*/\n\tinline bool isDisjoint(const std::string &termC, const std::string &termA1, const std::string &termA2){\n\n\t\t//std::cout << \"isDisjoint \" << termC << \" (\"  << termA1 << \" , \" << termA2 << \") \"; //<< std::endl;\n\t\t//if not from same ontology, return 0;\n\t\tif(_goGraph->getTermOntology(termA1) != _goGraph->getTermOntology(termA2) ||\n\t\t   _goGraph->getTermOntology(termC) != _goGraph->getTermOntology(termA1) ||\n\t\t   _goGraph->getTermOntology(termC) != _goGraph->getTermOntology(termA2))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tif(_icMap[termA1] <= _icMap[termA2]){\n\t\t\t//std::cout << \"case 1\" << std::endl;\n\t\t\tsize_t nPaths = getNumPaths(termA1,termA2);\n\t\t\t//std::cout << \"nPaths \" << termA1 << \" to \"  << termA2 << \" \" << nPaths << std::endl << std::endl;\n\t\t\tsize_t nPaths1 = getNumPaths(termA1,termC);\n\t\t\t//std::cout << \"nPaths \" << termA1 << \" to \"  << termC << \" \" << nPaths1 << std::endl << std::endl;\n\t\t\tsize_t nPaths2 = getNumPaths(termA2,termC);\n\t\t\t//std::cout << \"nPaths \" << termA2 << \" to \"  << termC << \" \" << nPaths2 << std::endl << std::endl;\n\t\t\tif(nPaths1 >= nPaths*nPaths2){\n\t\t\t\t//std::cout << \"true\" << std::endl;\n\t\t\t\treturn true;\n\t\t\t}else{\n\t\t\t\t//std::cout << \"false\" << std::endl;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t//return nPaths1 > nPaths*nPaths2;\n\t\t}else{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\n\t//! A method for calculating the number of paths for one term to another.\n\t/*!\n\t\tThis method returns the number of paths between two terms\n\t*/\n\tinline std::size_t getNumPaths(const std::string &termA, const std::string &termB){\n\t\tif(_icMap[termA] > _icMap[termB]){\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn pathCount(termA, termB);\n\t}\n\n\n\t//! An method for returning the shared information of two terms\n\t/*!\n\t\tThis method returns the mean information content disjoint common ancestors\n\t*/\n\tinline double sharedInformation(const std::string &termA, const std::string &termB){\n\t\t// return 0 for any terms not in the datbase\n\t\tif (!_icMap.hasTerm(termA) || !_icMap.hasTerm(termB)){\n\t\t\treturn 0.0;\n\t\t}\n\t\t// return 0 for terms in different ontologies\n\t\tif (_goGraph->getTermOntology(termA) != _goGraph->getTermOntology(termB)){\n\t\t\treturn 0.0;\n\t\t}\n\n\t\tAccumulators::MeanAccumulator meanIC;\n\t\tboost::unordered_set<std::string> cda = getCommonDisjointAncestors(termA,termB);\n\t\t//std::cout << \"size \" << cda.size() << std::endl;\n\n\t\tboost::unordered_set<std::string>::iterator iter = cda.begin();\n\t\tfor(;iter != cda.end(); ++iter){\n\t\t\t//std::cout << *iter << std::endl;\n\t\t\t//std::cout << _icMap[*iter] << std::endl;\n\t\t\tmeanIC(_icMap[*iter]);\n\t\t}\n\n\t\treturn Accumulators::extractMean(meanIC);\n\t}\n\n\t//! An interface method for returning the shared information of a single terms,or information content\n\t/*!\n\t\tThis method privdes a mechanism for returing a term's infromation content.\n\t*/\n\tinline double sharedInformation(const std::string &term){\n\t\t// return 0 for any terms not in the datbase\n\t\tif (!_icMap.hasTerm(term)){\n\t\t\treturn 0.0;\n\t\t}\n\t\treturn _icMap[term];\n\t}\n\n\t//! An interface method for returning the maximum information content for a term\n\t/*!\n\t\tThis method provides the absolute max information content within a corpus for normalization purposes.\n\t*/\n\tinline double maxInformationContent(const std::string &term){\n\n\t\tdouble maxIC;\n\n\t\t//select the correct ontology normalization factor\n\t\tGO::Onto ontoType = _goGraph->getTermOntology(term);\n\t\tif(ontoType == GO::BP){\n\t\t\tmaxIC = -std::log(_icMap.getMinBP());\n\t\t}else if(ontoType == GO::MF){\n\t\t\tmaxIC = -std::log(_icMap.getMinMF());\n\t\t}else{\n\t\t\tmaxIC = -std::log(_icMap.getMinCC());\n\t\t}\n\n\t\treturn maxIC;\n\t}\n\n\t//! An interface method for determining if a term can be found\n\t/*!\n\t\tDetermines if the term can be found in the current map.\n\t*/\n\tinline bool hasTerm(const std::string &term){\n\t\treturn _icMap.hasTerm(term);\n\t}\n\n\t//! An interface method for determining if the two terms are of like ontologies.\n\t/*!\n\t\tDetermine if two terms are of the same ontology.\n\t*/\n\tbool isSameOntology(const std::string &termA, const std::string &termB){\n\t\treturn _goGraph->getTermOntology(termA) == _goGraph->getTermOntology(termB);\n\t}\n\n\nprivate:\n\n\t//! Count paths from B to A\n\t/*!\n\t\tCount paths between B and A\n\t*/\n\tstd::size_t pathCount(const std::string &termA, const std::string &termB){\n\t\tif (_icMap[termA] > _icMap[termB]){\n\t\t\treturn 0;\n\t\t}\n\n\t\tboost::unordered_set<std::string> ancestors = _goGraph->getAncestorTerms(termB);\n\t\tboost::unordered_set<std::string> finished;\n\t\tboost::unordered_map<std::string, size_t> pathMap;\n\t\tancestors.insert(termB);\n\t\tGoGraph::Graph* g = _goGraph->getGraph();\n\t\tGoGraph::GoVertex v = _goGraph->getTermRootVertex(termB);\n\t\tvisitHelper(v, g, ancestors, finished, pathMap);\n\n\t\treturn pathMap[termA];\n\t}\n\n\t//! Recursive helper method that performs the DFS topological sort for path counting\n\t/*!\n\t\tA path counting topological sort recursive method.\n\t*/\n\tvoid visitHelper(const GoGraph::GoVertex &v, GoGraph::Graph* g,\n\t\tboost::unordered_set<std::string> &ancestors,\n\t\tboost::unordered_set<std::string> &finished,\n\t\tboost::unordered_map<std::string, size_t> &pathMap)\n\t{\n\t\tsize_t childCount = 0;\n\t\tstd::string vTerm = (*g)[v].termId;\n\t\t//std::cout << \"discover vertex \" << vTerm << std::endl;\n\n\t\t//examine children and recurse\n\t\tGoGraph::InEdgeIterator it, end;\n\t\tfor (boost::tie(it, end) = boost::in_edges(v, *g); it != end; ++it){\n\t\t\tGoGraph::GoVertex child = boost::source(*it, *g);\n\t\t\tstd::string childTerm = (*g)[child].termId;\n\t\t\tif (!SetUtilities::set_contains(ancestors, childTerm)){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t//recurse if child is not finished\n\t\t\tif (!SetUtilities::set_contains(finished, childTerm)){\n\t\t\t\tvisitHelper(child, g, ancestors, finished, pathMap);\n\t\t\t}\n\t\t\t++childCount;\n\t\t}\n\n\t\t//finish vertex\n\t\tfinished.insert(vTerm);\n\t\t//std::cout << \"finish vertex \" << vTerm << \", childred \" << childCount << std::endl;\n\t\tif (childCount == 0){\n\t\t\tpathMap[vTerm] = 1;\n\t\t}\n\t\telse{\n\t\t\tpathMap[vTerm] = 0;\n\t\t\tfor (boost::tie(it, end) = boost::in_edges(v, *g); it != end; ++it){\n\t\t\t\tGoGraph::GoVertex child = boost::source(*it, *g);\n\t\t\t\tstd::string childTerm = (*g)[child].termId;\n\t\t\t\tif (!SetUtilities::set_contains(ancestors, childTerm)){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tpathMap[vTerm] += pathMap[childTerm];\n\t\t\t}\n\t\t}\n\t}\n\n\t//! A private function to create a string key from a pair of terms\n\t/*!\n\t\tCreates a string key our of a pair to use in memorizing path counts\n\t*/\n\tstd::string keyPair(const std::string &termA, const std::string &termB){\n\t\tif (termA.compare(termB) > 0){\n\t\t\treturn termB + \"_\" + termA;\n\t\t}\n\t\telse{\n\t\t\treturn termB + \"_\" + termA;\n\t\t}\n\t}\n\n\t//! A private function to test if the key as been seen already\n\t/*!\n\t\tA private function to test if the key as been seen already.\n\t*/\n\tbool hasSeenKey(const std::string &key){\n\t\tif (_pathMemory.find(key) != _pathMemory.end()){\n\t\t\treturn true;\n\t\t}\n\t\telse{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tGoGraph* _goGraph;\n\tTermInformationContentMap _icMap;\n\tboost::unordered_map<std::string, size_t> _pathMemory;\n};\n#endif\n", "meta": {"hexsha": "3a419b9994ec7bc8942ce4bc82f44a0956a3271b", "size": 11351, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ggtk/CoutoGraSMSharedInformation.hpp", "max_stars_repo_name": "paulbible/ggtk", "max_stars_repo_head_hexsha": "9cdfb1ecced55db7353683b312b250e7238f61da", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-11T04:32:51.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-27T20:51:59.000Z", "max_issues_repo_path": "ggtk/CoutoGraSMSharedInformation.hpp", "max_issues_repo_name": "paulbible/ggtk", "max_issues_repo_head_hexsha": "9cdfb1ecced55db7353683b312b250e7238f61da", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-10-12T05:36:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-30T19:47:01.000Z", "max_forks_repo_path": "ggtk/CoutoGraSMSharedInformation.hpp", "max_forks_repo_name": "paulbible/ggtk", "max_forks_repo_head_hexsha": "9cdfb1ecced55db7353683b312b250e7238f61da", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-08-08T21:30:32.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-08T21:30:32.000Z", "avg_line_length": 31.5305555556, "max_line_length": 131, "alphanum_fraction": 0.6720112765, "num_tokens": 3391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669998, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.4170484111319453}}
{"text": "#include <map>\n#include <set>\n#include <utility>\n#include <vector>\n\n#include <Eigen/Core>\n\nnamespace from_igl {\n\n  using namespace igl;\n\n// Dijstra's algorithm for shortest paths, with multiple targets.\n// Adapted from http://rosettacode.org/wiki/Dijkstra%27s_algorithm .\n//\n// Inputs:\n//   source           index of source vertex\n//   targets          target vector set\n//   w                weight of edge corresponding to VV[i][j]\n//   VV               #V list of lists of incident vertices (adjacency list), e.g.\n//                    as returned by igl::adjacency_list\n//\n// Output:\n//   min_distance     #V by 1 list of the minimum distances from source to all vertices\n//   previous         #V by 1 list of the previous visited vertices (for each vertex) - used for backtracking\n//\nint dijkstra_compute_paths(const int &source,\n                           const std::set<int> &targets,\n                           const std::vector<std::vector<int> >& VV,\n                           const std::vector<std::vector<double> > &w,\n                           Eigen::VectorXd &min_distance,\n                           Eigen::VectorXi &previous)\n{\n  int numV = VV.size();\n  min_distance.setConstant(numV, 1, std::numeric_limits<double>::infinity());\n  min_distance[source] = 0;\n  previous.setConstant(numV, 1, -1);\n  std::set<std::pair<double, int> > vertex_queue;\n  vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n  while (!vertex_queue.empty())\n  {\n    double dist = vertex_queue.begin()->first;\n    int u = vertex_queue.begin()->second;\n    vertex_queue.erase(vertex_queue.begin());\n\n    if (targets.find(u)!= targets.end())\n      return u;\n\n    // Visit each edge exiting u\n    const std::vector<int> &neighbors = VV[u];\n    for (int i = 0; i < neighbors.size(); ++i)\n    {\n      int v = neighbors[i];\n      double distance_through_u = dist + w[u][i];\n\n      if (distance_through_u < min_distance[v]) {\n        vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n        min_distance[v] = distance_through_u;\n        previous[v] = u;\n        vertex_queue.insert(std::make_pair(min_distance[v], v));\n      }\n\n    }\n  }\n  //we should never get here\n  return -1;\n}\n} //from_igl\n", "meta": {"hexsha": "37fb53ea5015a71cc2607a100ccfe443b33bc6cd", "size": 2202, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "cgal_mesh_generation/dijkstra.hxx", "max_stars_repo_name": "chipbuster/skull-atlas", "max_stars_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cgal_mesh_generation/dijkstra.hxx", "max_issues_repo_name": "chipbuster/skull-atlas", "max_issues_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cgal_mesh_generation/dijkstra.hxx", "max_forks_repo_name": "chipbuster/skull-atlas", "max_forks_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4571428571, "max_line_length": 109, "alphanum_fraction": 0.6076294278, "num_tokens": 528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.41704839414981476}}
{"text": "/******************************************************************************\n * Author:   Laurent Kneip                                                    *\n * Contact:  kneip.laurent@gmail.com                                          *\n * License:  Copyright (c) 2013 Laurent Kneip, ANU. All rights reserved.      *\n *                                                                            *\n * Redistribution and use in source and binary forms, with or without         *\n * modification, are permitted provided that the following conditions         *\n * are met:                                                                   *\n * * Redistributions of source code must retain the above copyright           *\n *   notice, this list of conditions and the following disclaimer.            *\n * * Redistributions in binary form must reproduce the above copyright        *\n *   notice, this list of conditions and the following disclaimer in the      *\n *   documentation and/or other materials provided with the distribution.     *\n * * Neither the name of ANU nor the names of its contributors may be         *\n *   used to endorse or promote products derived from this software without   *\n *   specific prior written permission.                                       *\n *                                                                            *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"*\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  *\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *\n * ARE DISCLAIMED. IN NO EVENT SHALL ANU OR THE CONTRIBUTORS BE LIABLE        *\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT         *\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY  *\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF     *\n * SUCH DAMAGE.                                                               *\n ******************************************************************************/\n\n\n#include <opengv/absolute_pose/methods.hpp>\n#include <opengv/Indices.hpp>\n\n#include <Eigen/NonLinearOptimization>\n#include <Eigen/NumericalDiff>\n\n#include <opengv/absolute_pose/modules/main.hpp>\n#include <opengv/absolute_pose/modules/Epnp.hpp>\n#include <opengv/OptimizationFunctor.hpp>\n#include <opengv/math/cayley.hpp>\n#include <opengv/math/quaternion.hpp>\n#include <opengv/math/roots.hpp>\n\n#include <iostream>\n\nopengv::translation_t\nopengv::absolute_pose::p2p(\n    const AbsoluteAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  assert(indices.size()>1);\n  return p2p( adapter, indices[0], indices[1] );\n}\n\nopengv::translation_t\nopengv::absolute_pose::p2p(\n    const AbsoluteAdapterBase & adapter,\n    size_t index0,\n    size_t index1)\n{\n  Eigen::Vector3d e1 = adapter.getBearingVector(index0);\n  Eigen::Vector3d e3 = adapter.getBearingVector(index1);\n  e3 = e1.cross(e3);\n  e3 = e3/e3.norm();\n  Eigen::Vector3d e2 = e3.cross(e1);\n\n  rotation_t T;\n  T.row(0) = e1.transpose();\n  T.row(1) = e2.transpose();\n  T.row(2) = e3.transpose();\n\n  Eigen::Vector3d n1 = adapter.getPoint(index1) - adapter.getPoint(index0);\n  n1 = n1/n1.norm();\n  Eigen::Vector3d n3;\n  if( (fabs(n1[0]) > fabs(n1[1])) && (fabs(n1[0]) > fabs(n1[2])) )\n  {\n    n3[1] = 1.0;\n    n3[2] = 0.0;\n    n3[0] = -n1[1]/n1[0];\n  }\n  else\n  {\n    if( (fabs(n1[1]) > fabs(n1[0])) && (fabs(n1[1]) > fabs(n1[2])) )\n    {\n      n3[2] = 1.0;\n      n3[0] = 0.0;\n      n3[1] = -n1[2]/n1[1];\n    }\n    else\n    {\n      n3[0] = 1.0;\n      n3[1] = 0.0;\n      n3[2] = -n1[0]/n1[2];\n    }\n  }\n  n3 = n3 / n3.norm();\n  Eigen::Vector3d n2 = n3.cross(n1);\n\n  rotation_t N;\n  N.row(0) = n1.transpose();\n  N.row(1) = n2.transpose();\n  N.row(2) = n3.transpose();\n\n  Eigen::Matrix3d Q = T * adapter.getR().transpose() * N.transpose();\n  Eigen::Vector3d temp1 = adapter.getPoint(index1) - adapter.getPoint(index0);\n  double d_12 = temp1.norm();\n\n  Eigen::Vector3d temp2 = adapter.getBearingVector(index1);\n  double cos_beta = e1.dot(temp2);\n  double b = 1/( 1 - pow( cos_beta, 2 ) ) - 1;\n\n  if( cos_beta < 0 )\n    b = -sqrt(b);\n  else\n    b = sqrt(b);\n\n  double temp3 = d_12 * ( Q(1,0) * b - Q(0,0) );\n\n  translation_t solution = -temp3 * Q.row(0).transpose();\n  solution = adapter.getPoint(index0) + N.transpose()*solution;\n\n  if(\n    solution(0,0) != solution(0,0) ||\n    solution(1,0) != solution(1,0) ||\n    solution(2,0) != solution(2,0) )\n    solution = Eigen::Vector3d::Zero();\n\n  return solution;\n}\n\nopengv::transformations_t\nopengv::absolute_pose::p3p_kneip(\n    const AbsoluteAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  assert(indices.size()>2);\n  return p3p_kneip( adapter, indices[0], indices[1], indices[2] );\n}\n\nopengv::transformations_t\nopengv::absolute_pose::p3p_kneip(\n    const AbsoluteAdapterBase & adapter,\n    size_t index0,\n    size_t index1,\n    size_t index2)\n{\n  bearingVectors_t f;\n  f.push_back(adapter.getBearingVector(index0));\n  f.push_back(adapter.getBearingVector(index1));\n  f.push_back(adapter.getBearingVector(index2));\n  points_t p;\n  p.push_back(adapter.getPoint(index0));\n  p.push_back(adapter.getPoint(index1));\n  p.push_back(adapter.getPoint(index2));\n  transformations_t solutions;\n  modules::p3p_kneip_main( f, p, solutions );\n  return solutions;\n}\n\nopengv::transformations_t\nopengv::absolute_pose::p3p_gao(\n    const AbsoluteAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  assert(indices.size()>2);\n  return p3p_gao( adapter, indices[0], indices[1], indices[2] );\n}\n\nopengv::transformations_t\nopengv::absolute_pose::p3p_gao(\n    const AbsoluteAdapterBase & adapter,\n    size_t index0,\n    size_t index1,\n    size_t index2)\n{\n  bearingVectors_t f;\n  f.push_back(adapter.getBearingVector(index0));\n  f.push_back(adapter.getBearingVector(index1));\n  f.push_back(adapter.getBearingVector(index2));\n  points_t p;\n  p.push_back(adapter.getPoint(index0));\n  p.push_back(adapter.getPoint(index1));\n  p.push_back(adapter.getPoint(index2));\n  transformations_t solutions;\n  modules::p3p_gao_main( f, p, solutions );\n  return solutions;\n}\n\nopengv::transformations_t\nopengv::absolute_pose::gp3p(\n    const AbsoluteAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  assert(indices.size()>2);\n\n  Eigen::Matrix3d f;\n  Eigen::Matrix3d v;\n  Eigen::Matrix3d p;\n\n  for(size_t i = 0; i < 3; i++)\n  {\n    f.col(i) = adapter.getBearingVector(indices[i]);\n    rotation_t R = adapter.getCamRotation(indices[i]);\n    \n    //unrotate the bearingVectors already so the camera rotation doesn't appear\n    //in the problem\n    f.col(i) = R * f.col(i);\n    v.col(i) = adapter.getCamOffset(indices[i]);\n    p.col(i) = adapter.getPoint(indices[i]);\n  }\n\n  transformations_t solutions;\n  modules::gp3p_main(f,v,p,solutions);\n\n  return solutions;\n}\n\nopengv::transformations_t\nopengv::absolute_pose::gp3p(\n    const AbsoluteAdapterBase & adapter,\n    size_t index0,\n    size_t index1,\n    size_t index2)\n{\n  std::vector<int> indices;\n  indices.push_back(index0);\n  indices.push_back(index1);\n  indices.push_back(index2);\n\n  return gp3p(adapter,indices);\n}\n\nnamespace opengv\n{\nnamespace absolute_pose\n{\n\ntransformation_t epnp(\n    const AbsoluteAdapterBase & adapter,\n    const Indices & indices )\n{\n  //starting from 4 points, we have a unique solution\n  assert(indices.size() > 5);\n\n  modules::Epnp PnP;\n  PnP.set_maximum_number_of_correspondences(indices.size());\n  PnP.reset_correspondences();\n\n  for( size_t i = 0; i < indices.size(); i++ )\n  {\n    point_t p = adapter.getPoint(indices[i]);\n    bearingVector_t f = adapter.getBearingVector(indices[i]);\n    PnP.add_correspondence(p[0], p[1], p[2], f[0], f[1], f[2]);\n  }\n\n  double R_epnp[3][3], t_epnp[3];\n  PnP.compute_pose(R_epnp, t_epnp);\n\n  rotation_t rotation;\n  translation_t translation;\n\n  for(int r = 0; r < 3; r++)\n  {\n    for(int c = 0; c < 3; c++)\n      rotation(r,c) = R_epnp[r][c];\n  }\n\n  translation[0] = t_epnp[0];\n  translation[1] = t_epnp[1];\n  translation[2] = t_epnp[2];\n\n  //take inverse transformation\n  rotation.transposeInPlace();\n  translation = -rotation * translation;\n\n  transformation_t transformation;\n  transformation.col(3) = translation;\n  transformation.block<3,3>(0,0) = rotation;\n  return transformation;\n}\n\n}\n}\n\nopengv::transformation_t\nopengv::absolute_pose::epnp( const AbsoluteAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return epnp(adapter,idx);\n}\n\nopengv::transformation_t\nopengv::absolute_pose::epnp(\n    const AbsoluteAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return epnp(adapter,idx);\n}\n\nnamespace opengv\n{\nnamespace absolute_pose\n{\n\ntransformation_t gpnp(\n    const AbsoluteAdapterBase & adapter,\n    const Indices & indices )\n{\n  assert( indices.size() > 5 );\n\n  //compute the centroid\n  point_t c0 = Eigen::Vector3d::Zero();\n  for( size_t i = 0; i < indices.size(); i++ )\n    c0 = c0 + adapter.getPoint(indices[i]);\n  c0 = c0 / indices.size();\n\n  //compute the point-cloud\n  Eigen::MatrixXd p(3,indices.size());\n  for( size_t i = 0; i < indices.size(); i++ )\n    p.col(i) = adapter.getPoint(indices[i]) - c0;\n\n  //compute the moment\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVD(\n      p,\n      Eigen::ComputeThinU | Eigen::ComputeThinV );\n\n  //define the control points\n  points_t c;\n  c.push_back(c0);\n  //c.push_back(c0 + SVD.singularValues()[0] * SVD.matrixU().col(0));\n  //c.push_back(c0 + SVD.singularValues()[1] * SVD.matrixU().col(1));\n  //c.push_back(c0 + SVD.singularValues()[2] * SVD.matrixU().col(2));\n  c.push_back(c0 + 15.0 * SVD.matrixU().col(0));\n  c.push_back(c0 + 15.0 * SVD.matrixU().col(1));\n  c.push_back(c0 + 15.0 * SVD.matrixU().col(2));\n\n  //derive the barycentric frame\n  Eigen::Vector3d e1 = c[1]-c0;\n  double e1dote1 = e1.dot(e1);\n  Eigen::Vector3d e2 = c[2]-c0;\n  double e2dote2 = e2.dot(e2);\n  Eigen::Vector3d e3 = c[3]-c0;\n  double e3dote3 = e3.dot(e3);\n\n  //derive the weighting factors\n  Eigen::MatrixXd weights(4,indices.size());\n  for( size_t i = 0; i < indices.size(); i++ )\n  {\n    Eigen::Vector3d temp = p.col(i);\n    weights(1,i) = temp.dot(e1)/e1dote1;\n    weights(2,i) = temp.dot(e2)/e2dote2;\n    weights(3,i) = temp.dot(e3)/e3dote3;\n    weights(0,i) = 1.0-(weights(1,i)+weights(2,i)+weights(3,i));\n  }\n\n  //setup matrix A and vector b\n  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(2*indices.size(),12);\n  Eigen::MatrixXd b = Eigen::MatrixXd::Zero(2*indices.size(),1);\n  for( size_t i = 0; i < indices.size(); i++ )\n  {\n    translation_t camOffset = adapter.getCamOffset(indices[i]);\n    rotation_t camRotation = adapter.getCamRotation(indices[i]);\n    //respect the rotation\n    bearingVector_t f = camRotation * adapter.getBearingVector(indices[i]);\n\n    A(2*i,0)  =  weights(0,i)*f[2];\n    A(2*i,2)  = -weights(0,i)*f[0];\n    A(2*i,3)  =  weights(1,i)*f[2];\n    A(2*i,5)  = -weights(1,i)*f[0];\n    A(2*i,6)  =  weights(2,i)*f[2];\n    A(2*i,8)  = -weights(2,i)*f[0];\n    A(2*i,9)  =  weights(3,i)*f[2];\n    A(2*i,11) = -weights(3,i)*f[0];\n\n    A(2*i+1,1)  =  weights(0,i)*f[2];\n    A(2*i+1,2)  = -weights(0,i)*f[1];\n    A(2*i+1,4)  =  weights(1,i)*f[2];\n    A(2*i+1,5)  = -weights(1,i)*f[1];\n    A(2*i+1,7)  =  weights(2,i)*f[2];\n    A(2*i+1,8)  = -weights(2,i)*f[1];\n    A(2*i+1,10) =  weights(3,i)*f[2];\n    A(2*i+1,11) = -weights(3,i)*f[1];\n\n    b(2*i,0)   = f[2]*camOffset[0]-f[0]*camOffset[2];\n    b(2*i+1,0) = f[2]*camOffset[1]-f[1]*camOffset[2];\n  }\n\n  //computing the SVD\n  Eigen::JacobiSVD< Eigen::MatrixXd > SVD2(\n      A,\n      Eigen::ComputeThinV | Eigen::ComputeThinU );\n\n  //computing the pseudoinverse\n  Eigen::MatrixXd invD = Eigen::MatrixXd::Zero(12,12);\n  Eigen::MatrixXd D = SVD2.singularValues();\n  for( size_t i = 0; i < 12; i++ )\n  {\n    if( D(i,0) > 1.e-6 )\n      invD(i,i) = 1.0/D(i,0);\n    else\n      invD(i,i) = 0.0;\n  }\n\n  //Extract the nullsapce vectors;\n  Eigen::MatrixXd V = SVD2.matrixV();\n\n  //computing the nullspace intercept\n  Eigen::MatrixXd pinvA = V * invD * SVD2.matrixU().transpose();\n\n  //compute the intercept\n  Eigen::Matrix<double,12,1> a = pinvA * b;\n\n  //compute the solution\n  transformation_t transformation;\n  modules::gpnp_main( a, V, c, transformation );\n  return transformation;\n}\n\n}\n}\n\nopengv::transformation_t\nopengv::absolute_pose::gpnp( const AbsoluteAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return gpnp(adapter,idx);\n}\n\nopengv::transformation_t\nopengv::absolute_pose::gpnp(\n    const AbsoluteAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return gpnp(adapter,idx);\n}\n\nnamespace opengv\n{\nnamespace absolute_pose\n{\n\nvoid fill3x10( const Eigen::Vector3d & x, Eigen::Matrix<double,3,10> & Phi )\n{\n  double x1 = x[0];\n  double x2 = x[1];\n  double x3 = x[2];\n  \n  Phi << x1,  x1, -x1, -x1,     0.0,  2.0*x3, -2.0*x2, 2.0*x2, 2.0*x3,    0.0,\n         x2, -x2,  x2, -x2, -2.0*x3,     0.0,  2.0*x1, 2.0*x1,    0.0, 2.0*x3,\n         x3, -x3, -x3,  x3,  2.0*x2, -2.0*x1,     0.0,    0.0, 2.0*x1, 2.0*x2;\n}\n\nvoid f(\n    const Eigen::Matrix<double,10,10> & M,\n    const Eigen::Matrix<double,1,10> & C,\n    double gamma,\n    Eigen::Vector3d & f )\n{\n  f[0] = (2*M(0,4)+2*C(0,4));\n  f[1] = (2*M(0,5)+2*C(0,5));\n  f[2] = (2*M(0,6)+2*C(0,6));\n}\n\nvoid Jac(\n    const Eigen::Matrix<double,10,10> & M,\n    const Eigen::Matrix<double,1,10> & C,\n    double gamma,\n    Eigen::Matrix3d & Jac )\n{\n  Jac(0,0) = (2*M(4,4)+4*M(0,1)-4*M(0,0)+4*C(0,1)-4*C(0,0));\n  Jac(0,1) = (2*M(5,4)+2*M(0,7)+2*C(0,7));\n  Jac(0,2) = (2*M(6,4)+2*M(0,8)+2*C(0,8));\n  Jac(1,0) = (2*M(4,5)+2*M(0,7)+2*C(0,7));\n  Jac(1,1) = (2*M(5,5)+4*M(0,2)-4*M(0,0)+4*C(0,2)-4*C(0,0));\n  Jac(1,2) = (2*M(6,5)+2*M(0,9)+2*C(0,9));\n  Jac(2,0) = (2*M(4,6)+2*M(0,8)+2*C(0,8));\n  Jac(2,1) = (2*M(5,6)+2*M(0,9)+2*C(0,9));\n  Jac(2,2) = (2*M(6,6)+4*M(0,3)-4*M(0,0)+4*C(0,3)-4*C(0,0));\n}\n\ntransformations_t upnp(\n    const AbsoluteAdapterBase & adapter,\n    const Indices & indices )\n{\n  assert( indices.size() > 2 );\n    \n  Eigen::Matrix<double,3,3> F = Eigen::Matrix3d::Zero();\n  for( int i = 0; i < (int) indices.size(); i++ )\n  {\n    Eigen::Matrix<double,3,1> f = adapter.getCamRotation(indices[i]) * adapter.getBearingVector(indices[i]);\n    F += f * f.transpose();\n  }\n  \n  Eigen::Matrix<double,3,3> H_inv = (indices.size() * Eigen::Matrix<double,3,3>::Identity()) - F;\n  Eigen::Matrix<double,3,3> H = H_inv.inverse();\n  \n  Eigen::Matrix<double,3,10> I = Eigen::Matrix<double,3,10>::Zero();\n  Eigen::Matrix<double,3,1> J = Eigen::Matrix<double,3,1>::Zero();\n  Eigen::Matrix<double,3,10> Phi;\n  \n  for( int i = 0; i < (int) indices.size(); i++ )\n  {\n    Eigen::Matrix<double,3,1> f = adapter.getCamRotation(indices[i]) * adapter.getBearingVector(indices[i]);\n    Eigen::Matrix<double,3,3> Vk = H * ( f * f.transpose() - Eigen::Matrix<double,3,3>::Identity() );\n    Eigen::Matrix<double,3,1> p = adapter.getPoint(indices[i]);\n    Eigen::Matrix<double,3,1> v = adapter.getCamOffset(indices[i]);\n    \n    fill3x10(p,Phi);\n    I += Vk * Phi;\n    J += Vk * v;\n  }\n  \n  Eigen::Matrix<double,10,10> M = Eigen::Matrix<double,10,10>::Zero();\n  Eigen::Matrix<double,1,10>  C = Eigen::Matrix<double,1,10>::Zero();\n  double gamma = 0.0;\n  \n  for(int i = 0; i < (int) indices.size(); i++ )\n  {    \n    Eigen::Matrix<double,3,1> f = adapter.getCamRotation(indices[i]) * adapter.getBearingVector(indices[i]);\n    Eigen::Matrix<double,3,1> v = adapter.getCamOffset(indices[i]);\n    Eigen::Matrix<double,3,1> p = adapter.getPoint(indices[i]);\n    \n    fill3x10(p,Phi);\n    Eigen::Matrix<double,3,3> temp = f*f.transpose() - Eigen::Matrix<double,3,3>::Identity();\n    Eigen::Matrix<double,3,10> Ai =  temp * (Phi + I);\n    Eigen::Matrix<double,3, 1> bi = -temp * (  v + J);\n    \n    M     += (Ai.transpose() * Ai);\n    C     += (bi.transpose() * Ai);\n    gamma += (bi.transpose() * bi);\n  }\n  \n  //now do the main computation\n  std::vector<std::pair<double,Eigen::Vector4d>,Eigen::aligned_allocator< std::pair<double,Eigen::Vector4d> > > quaternions1;\n  if( indices.size() > 4 )\n    modules::upnp_main_sym( M, C, gamma, quaternions1 );\n  else\n    modules::upnp_main( M, C, gamma, quaternions1 );\n  \n  //prepare the output vector\n  transformations_t transformations;\n  \n  //Round 1: chirality check\n  std::vector<std::pair<double,Eigen::Vector4d>,Eigen::aligned_allocator< std::pair<double,Eigen::Vector4d> > > quaternions2;\n  for( int i = 0; i < quaternions1.size(); i++ )\n  {\n    rotation_t Rinv = math::quaternion2rot(quaternions1[i].second);\n    \n    Eigen::Matrix<double,10,1> s;\n    modules::upnp_fill_s( quaternions1[i].second, s );\n    translation_t tinv = I*s - J;\n    \n    if( transformations.size() == 0 )\n    {\n      transformation_t newTransformation;\n      newTransformation.block<3,3>(0,0) = Rinv.transpose();\n      newTransformation.block<3,1>(0,3) = -newTransformation.block<3,3>(0,0) * tinv;\n      transformations.push_back(newTransformation);\n    }\n    \n    int count_negative = 0;\n    \n    for( int j = 0; j < (int) indices.size(); j++ )\n    {\n      Eigen::Matrix<double,3,1> f = adapter.getCamRotation(indices[j]) * adapter.getBearingVector(indices[j]);\n      Eigen::Matrix<double,3,1> p = adapter.getPoint(indices[j]);\n      Eigen::Matrix<double,3,1> v = adapter.getCamOffset(indices[j]);\n      \n      Eigen::Vector3d p_est = Rinv*p + tinv - v;\n      \n      if( p_est.transpose()*f < 0.0 )\n        count_negative++;\n    }\n    \n    if( count_negative < floor(0.2 * indices.size() + 0.5) )\n      quaternions2.push_back(quaternions1[i]);\n  }\n  \n  if( quaternions2.size() == 0 )\n    return transformations;\n  else\n    transformations.clear();\n  \n  //Round 2: Second order optimality (plus polishing)\n  Eigen::Matrix<double,3,10> I_cay;\n  Eigen::Matrix<double,10,10> M_cay;\n  Eigen::Matrix<double,1,10>  C_cay;\n  double gamma_cay;\n  \n  for( size_t q = 0; q < quaternions2.size(); q++ )\n  {    \n    I_cay = Eigen::Matrix<double,3,10>::Zero();\n    rotation_t Rinv = math::quaternion2rot(quaternions2[q].second);\n    \n    for( int i = 0; i < (int) indices.size(); i++ )\n    {\n      Eigen::Matrix<double,3,1> f = adapter.getCamRotation(indices[i]) * adapter.getBearingVector(indices[i]);\n      Eigen::Matrix<double,3,3> Vk = H * ( f * f.transpose() - Eigen::Matrix<double,3,3>::Identity() );\n      Eigen::Matrix<double,3,1> p = Rinv * adapter.getPoint(indices[i]);\n      \n      fill3x10(p,Phi);\n      I_cay += Vk * Phi;\n    }\n    \n    M_cay = Eigen::Matrix<double,10,10>::Zero();\n    C_cay = Eigen::Matrix<double,1,10>::Zero();\n    gamma_cay = 0.0;\n    \n    for(int i = 0; i < (int) indices.size(); i++ )\n    {    \n      Eigen::Matrix<double,3,1> f = adapter.getCamRotation(indices[i]) * adapter.getBearingVector(indices[i]);\n      Eigen::Matrix<double,3,1> v = adapter.getCamOffset(indices[i]);\n      Eigen::Matrix<double,3,1> p = Rinv * adapter.getPoint(indices[i]);\n      \n      fill3x10(p,Phi);\n      Eigen::Matrix<double,3,3> temp = f*f.transpose() - Eigen::Matrix<double,3,3>::Identity();\n      Eigen::Matrix<double,3,10> Ai =  temp * (Phi + I_cay);\n      Eigen::Matrix<double,3,1> bi = -temp * (  v + J);\n      \n      M_cay     += (Ai.transpose() * Ai);\n      C_cay     += (bi.transpose() * Ai);\n      gamma_cay += (bi.transpose() * bi);\n    }\n    \n    //now analyze the eigenvalues of the \"Hessian\"\n    Eigen::Vector3d val;\n    Eigen::Matrix3d Jacobian;\n    f( M_cay, C_cay, gamma_cay, val );\n    Jac( M_cay, C_cay, gamma_cay, Jacobian );\n    std::vector<double> characteristicPolynomial;\n    characteristicPolynomial.push_back(-1.0);\n    characteristicPolynomial.push_back(Jacobian(2,2)+Jacobian(1,1)+Jacobian(0,0));\n    characteristicPolynomial.push_back(-Jacobian(2,2)*Jacobian(1,1)-Jacobian(2,2)*Jacobian(0,0)-Jacobian(1,1)*Jacobian(0,0)+pow(Jacobian(1,2),2)+pow(Jacobian(0,2),2)+pow(Jacobian(0,1),2));\n    characteristicPolynomial.push_back(Jacobian(2,2)*Jacobian(1,1)*Jacobian(0,0)+2*Jacobian(1,2)*Jacobian(0,2)*Jacobian(0,1)-Jacobian(2,2)*pow(Jacobian(0,1),2)-pow(Jacobian(1,2),2)*Jacobian(0,0)-Jacobian(1,1)*pow(Jacobian(0,2),2));\n    std::vector<double> roots = opengv::math::o3_roots( characteristicPolynomial );\n    \n    bool allPositive = true;\n    for( size_t i = 0; i < roots.size(); i++ )\n    {\n      if( roots[i] < 0.0 )\n      {\n        allPositive = false;\n        break;\n      }\n    }\n    \n    if( true )//allPositive)//use all results for the moment\n    {\n      //perform the polishing step\n      Eigen::Vector3d cay = - Jacobian.inverse() * val;\n      rotation_t Rinv2 = math::cayley2rot(cay) * Rinv;\n      quaternion_t q = math::rot2quaternion(Rinv2);\n      \n      Eigen::Matrix<double,10,1> s;\n      modules::upnp_fill_s(q,s);\n      translation_t tinv = I*s - J;\n      \n      transformation_t newTransformation;\n      newTransformation.block<3,3>(0,0) = Rinv2.transpose();\n      newTransformation.block<3,1>(0,3) = -newTransformation.block<3,3>(0,0) * tinv;\n      transformations.push_back(newTransformation);\n    }\n  }\n  \n  //if there are no results, simply add the one with lowest score\n  if( transformations.size() == 0 )\n  {\n    Eigen::Vector4d q = quaternions2[0].second;\n    Eigen::Matrix<double,10,1> s;\n    modules::upnp_fill_s(q,s);\n    translation_t tinv = I*s - J;\n    rotation_t Rinv = math::quaternion2rot(q);\n    \n    transformation_t newTransformation;\n    newTransformation.block<3,3>(0,0) = Rinv.transpose();\n    newTransformation.block<3,1>(0,3) = -newTransformation.block<3,3>(0,0) * tinv;\n    transformations.push_back(newTransformation);\n  }\n  \n  return transformations;\n}\n\n}\n}\n\nopengv::transformations_t\nopengv::absolute_pose::upnp( const AbsoluteAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return upnp(adapter,idx);\n}\n\nopengv::transformations_t\nopengv::absolute_pose::upnp(\n    const AbsoluteAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return upnp(adapter,idx);\n}\n\nnamespace opengv\n{\nnamespace absolute_pose\n{\n\nstruct OptimizeNonlinearFunctor1 : OptimizationFunctor<double>\n{\n  const AbsoluteAdapterBase & _adapter;\n  const Indices & _indices;\n\n  OptimizeNonlinearFunctor1(\n      const AbsoluteAdapterBase & adapter,\n      const Indices & indices ) :\n      OptimizationFunctor<double>(6,indices.size()),\n      _adapter(adapter),\n      _indices(indices) {}\n\n  int operator()(const VectorXd &x, VectorXd &fvec) const\n  {\n    assert( x.size() == 6 );\n    assert( (unsigned int) fvec.size() == _indices.size());\n\n    //compute the current position\n    translation_t translation = x.block<3,1>(0,0);\n    cayley_t cayley = x.block<3,1>(3,0);\n    rotation_t rotation = math::cayley2rot(cayley);\n\n    //compute inverse transformation\n    transformation_t inverseSolution;\n    inverseSolution.block<3,3>(0,0) = rotation.transpose();\n    inverseSolution.col(3) = -inverseSolution.block<3,3>(0,0)*translation;\n\n    Eigen::Matrix<double,4,1> p_hom;\n    p_hom[3] = 1.0;\n\n    for(size_t i = 0; i < _indices.size(); i++)\n    {\n      //get point in homogeneous form\n      p_hom.block<3,1>(0,0) = _adapter.getPoint(_indices[i]);\n\n      //compute the reprojection (this is working for both central and\n      //non-central case)\n      point_t bodyReprojection = inverseSolution * p_hom;\n      point_t reprojection = _adapter.getCamRotation(_indices[i]).transpose() *\n          (bodyReprojection - _adapter.getCamOffset(_indices[i]));\n      reprojection = reprojection / reprojection.norm();\n\n      //compute the score\n      double factor = 1.0;\n      fvec[i] = factor *\n          (1.0 -\n          (reprojection.transpose() * _adapter.getBearingVector(_indices[i])));\n    }\n\n    return 0;\n  }\n};\n\ntransformation_t optimize_nonlinear(\n    const AbsoluteAdapterBase & adapter,\n    const Indices & indices )\n{\n  const int n=6;\n  VectorXd x(n);\n\n  x.block<3,1>(0,0) = adapter.gett();\n  x.block<3,1>(3,0) = math::rot2cayley(adapter.getR());\n\n  OptimizeNonlinearFunctor1 functor( adapter, indices );\n  NumericalDiff<OptimizeNonlinearFunctor1> numDiff(functor);\n  LevenbergMarquardt< NumericalDiff<OptimizeNonlinearFunctor1> > lm(numDiff);\n\n  lm.resetParameters();\n  lm.parameters.ftol = 1.E1*NumTraits<double>::epsilon();\n  lm.parameters.xtol = 1.E1*NumTraits<double>::epsilon();\n  lm.parameters.maxfev = 1000;\n  lm.minimize(x);\n\n  transformation_t transformation;\n  transformation.col(3) = x.block<3,1>(0,0);\n  transformation.block<3,3>(0,0) = math::cayley2rot(x.block<3,1>(3,0));\n  return transformation;\n}\n\n}\n}\n\nopengv::transformation_t\nopengv::absolute_pose::optimize_nonlinear( const AbsoluteAdapterBase & adapter )\n{\n  Indices idx(adapter.getNumberCorrespondences());\n  return optimize_nonlinear(adapter,idx);\n}\n\nopengv::transformation_t\nopengv::absolute_pose::optimize_nonlinear(\n    const AbsoluteAdapterBase & adapter,\n    const std::vector<int> & indices )\n{\n  Indices idx(indices);\n  return optimize_nonlinear(adapter,idx);\n}\n", "meta": {"hexsha": "c8ab3f0f2d1ffdd6ca8fce51ce32d5cc22cd1011", "size": 25071, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/absolute_pose/methods.cpp", "max_stars_repo_name": "qintony/opengv", "max_stars_repo_head_hexsha": "f52f4019f9aca4b590b5c6c9bbe6354b973b56a1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-25T04:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-30T11:03:29.000Z", "max_issues_repo_path": "src/absolute_pose/methods.cpp", "max_issues_repo_name": "qintony/opengv", "max_issues_repo_head_hexsha": "f52f4019f9aca4b590b5c6c9bbe6354b973b56a1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/absolute_pose/methods.cpp", "max_forks_repo_name": "qintony/opengv", "max_forks_repo_head_hexsha": "f52f4019f9aca4b590b5c6c9bbe6354b973b56a1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-29T07:33:07.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-29T07:33:07.000Z", "avg_line_length": 31.0669144981, "max_line_length": 231, "alphanum_fraction": 0.6278967732, "num_tokens": 7822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4169687614286824}}
{"text": "#include \"precompiled.h\"\n#include \"explicit_fields.h\"\n#include \"auto_connecting_body.h\"\n\n#ifndef AUTOMATIC_PRECOMPILATION\n#include <string>\n#include <boost/optional.hpp>\n#include <pretty_printer.h>\n#endif\n\n#include \"logging.h\"\n#include \"grid_fields.h\"\n#include \"black_scholes.h\"\n#include \"global_config.h\"\n#include \"Math.h\"\n#include \"finite_difference_weights_config.h\"\n\nnamespace fipster { namespace explicit_fields {\n\n\tusing namespace std; \n\n\t// #################################################\n\t// ##############   PHASE 1:\t\t\t############\n\t// ##############   CONFIGURATION       ############\n\t// #################################################\n\n\tnode_factory::node_factory(const ptree& pt,shared_const_objs_t objs)\n\t\t: pt(pt),objs(objs)\n\t{\n\t\tstring stype(pt.get<string>(\"type\"));\n\t\tif(stype == \"CallPayoff\") type = CallPayoff;\n\t\telse if(stype == \"PutPayoff\") type = PutPayoff;\n\t\telse if(stype == \"BinaryCallPayoff\") type = BinaryCallPayoff;\n\t\telse if(stype == \"Put\") type = Put;\n\t\telse if(stype == \"Call\") type = Call;\n\t\telse BOOST_THROW_EXCEPTION(runtime_error(stype+\" is no valid Explicit Field Type\"));\n\t}\n\n\t// #################################################\n\t// ##############   PHASE 3:\t\t\t############\n\t// ##############   Node Bodies         ############\n\t// #################################################\n\t\n\t/** this class calculates the payoff of a Call/Put on the first\n\t\t\tassert\n\t */\n\ttemplate<type_t type>\n\tstruct VanillaPayoff_t{\n\t\tdouble strike;\n\t\t\n\t\t/** constructor that reads in configuration */\n\t\tVanillaPayoff_t\n\t\t(const ptree& pt,const field_arg_t<>&,shared_const_objs_t)\n\t\t\t:strike(pt.get<double>(\"strike\")){}\n\n\t\t/** core function, computing the value for a given state */\n\t\tdouble getValue(const state_t& state){\n\t\t\t/*if(state[0]>120){\n\t\t\t\tauto s2=state;\n\t\t\t\ts2[0]-=120;\n\t\t\t\treturn getValue(s2);\n\t\t\t}\n\t\t\tif(state[0]>75) return 0;*/\n\t\t\tdouble a=30;\n\t\t\tif(type==BinaryCall) return state[0] >= strike ? 1 : 0;\n\t\t\t\n\t\t\treturn max( (type==Call ? +1 : -1 )*(state[0]-strike-0*a),0.0);\n// -\n// \t\t\tmax( (type==Call ? +1 : -1 )*(state[0]-strike-a),0.0)-\n// \t\t\t\tmax( (type==Call ? +1 : -1 )*(state[0]-strike-2*a),0.0)+\n// \t\t\t\tmax( (type==Call ? +1 : -1 )*(state[0]-strike-3*a),0.0);\n\t\t};\n\t};\n\t\n\t/** this class calculates the Black Scholes Values for a Call/Put on \n\tthe geometric average of grid.D assets (using equal correlation, dividend and volatility)\n\t*/\n\ttemplate<type_t type>\n\tstruct BS_t{\n\t\tdouble strike,interest,volatility,correlation;\n\t\tblack_scholes bs;\n\n\t\t/** constructor that reads in configuration */\n\t\tBS_t(const ptree& pt,const field_arg_t<>& arg,shared_const_objs_t objs){\n\t\t\n\t\t\tauto same_as = pt.get_optional<string>(\"sameAs\");\n\n\t\t\tif(!same_as)\n\t\t\t\tbs=black_scholes(0,\n\t\t\t\t\tpt.get<double>(\"strike\"),\n\t\t\t\t\tglobal_config::get().years_per_btick*(pt.get<btime>(\"expiration\")-arg.time),\n\t\t\t\t\tpt.get<double>(\"interest\"),\n\t\t\t\t\tpt.get<double>(\"volatility\"),\n\t\t\t\t\tpt.get(\"dividend\",0.0),\n\t\t\t\t\tpt.get(\"correlation\",0.0),\n\t\t\t\t\targ.grid->D);\n\t\t\telse{\n\t\t\t\tFIPSTER_THROW_EXCEPTION(runtime_error(\"not implemented\"));\n\t\t\t\t/*\n\t\t\t\t//get the expectation value to take the interval from (if available)\n\t\t\t\tauto nf=dynamic_cast<const expectation_values::node_factory*>\n\t\t\t\t\t(objs->spacetime_fields.at(*same_as).get());\n\t\t\t\tif(!nf) FIPSTER_THROW_EXCEPTION(runtime_error(\"sameAs: \"+*same_as+\" is no expcetation_value\"));\n\t\t\t\tauto fdw=objs->fdweights_configs.at(nf->config->fd_weights_s);\n\t\t\t\tfdw->\n\t\t\t\t*/\n\t\t\t}\n\t\t}\n\n\t\t/** core function, computing the value for a given state */\n\t\tdouble getValue(const state_t& state);\n\t};\n\n\ttemplate<>\n\tdouble BS_t<Call>::getValue(const state_t& state)\n\t{\n\t\treturn bs.call(geometric_average(state,bs.n));\n\t};\n\n\ttemplate<>\n\tdouble BS_t<Put>::getValue(const state_t& state)\n\t{\n\t\treturn bs.put(geometric_average(state,bs.n));\n\t};\n\n\t//#######################  Node body ##############################\n\ttemplate<int sg, class result_t, class state_it,class core_t>//specify the sub-grid to work on\n\tstruct explicit_field_body : \n\t\tauto_connecting_body<explicit_field_body<sg,result_t,state_it,core_t>,//body_t\n\t\t\t\t\t\t\tresult_t>//result\n\t{\n\t\tcore_t core;\n\t\tconst btime time;\n\t\tgrid_ptr grid;\n\t\tstring meta_info;\n\t\tdouble factor;\n\n\t\tusing result_sptr_t = typename explicit_field_body::result_sptr_t;\n\t\tusing input_t = typename explicit_field_body::input_t;\n\n\t\texplicit_field_body(field_arg_t<> field_args,const ptree& pt,shared_const_objs_t objs)\n\t\t\t:core(core_t(pt,field_args,objs))\n\t\t\t,time(field_args.time)\n\t\t\t,grid(field_args.grid)\n\t\t\t,meta_info(pt.get<string>(\"type\")\n\t\t\t\t\t\t\t\t + \" EXPL FL (\"+toS(time)+\") \"+pt.get<string>(\"<xmlattr>.id\"))\n\t\t\t,factor(pt.get(\"factor\",1.0))\n\t\t{};\n\n\n\t\t//computation function #####################################################\n\t\tresult_sptr_t operator()(const input_t&){\n\t\t\t// logging\n\t\t\tif(1)thread_logger()<<\"EXPL FL (\"<<time<<\") | START\"<<endl;\n\t\t\tauto result = make_shared<result_t>\n\t\t\t\t(meta_info);\n\n\t\t\t//allocate new space for the result on the specified Grid\n\t\t\tauto end = result->resize(*grid);\n\n\t\t\tfor(state_it it(*grid); it!=end; ++it)\n\t\t\t\tresult->at(it.index()) = factor*core.getValue(it.state());\n\t\t\t\t\n\t//tbb::this_tbb_thread::sleep(tbb::tick_count::interval_t(0.2));\n\n\t\t\tif(1)thread_logger()<<\"EXPL FL| DONE\"<<endl;\n\t\t\treturn result;\n\t\t};\n\n\t};\n\n\t// #################################################\n\t// ##############   PHASE 2:\t\t\t############\n\t// ##############   Node Factory        ############\n\t// #################################################\n\n\tboost::optional<node_factory::arg_t>\n\tnode_factory::delegation(const arg_t& arg){\n\t\tif((type==CallPayoff || type==PutPayoff || type==BinaryCallPayoff) && arg.time != 0 ){\n\t\t\targ_t a=arg; a.time = 0;\n\t\t\treturn a;\n\t\t}\n\t\treturn boost::none;\n\t}\n\n\ttemplate<int sg,class result2_t,class iterator2_t,class sender2_t>\n\tsender2_t node_factory::selecting_setup( const node_factory::arg_t& arg)\n\t{\n\t\tswitch(type){\n\t\tcase CallPayoff:\n\t\t\treturn create_node\n\t\t\t\t(explicit_field_body<sg,result2_t,iterator2_t,VanillaPayoff_t<Call> >(arg,pt,objs));\n\t\tcase PutPayoff:\n\t\t\treturn create_node\n\t\t\t\t(explicit_field_body<sg,result2_t,iterator2_t,VanillaPayoff_t<Put> >(arg,pt,objs));\n\t\tcase BinaryCallPayoff:\n\t\t\treturn create_node\n\t\t\t\t(explicit_field_body<sg,result2_t,iterator2_t,VanillaPayoff_t<BinaryCall> >(arg,pt,objs));\n\t\tcase Call:\n\t\t\treturn create_node\n\t\t\t\t(explicit_field_body<sg,result2_t,iterator2_t,BS_t<Call> >          (arg,pt,objs));\n\t\tcase Put:\n\t\t\treturn create_node\n\t\t\t\t(explicit_field_body<sg,result2_t,iterator2_t,BS_t<Put> >           (arg,pt,objs));\n\t\tdefault:\n\t\t\tBOOST_THROW_EXCEPTION(runtime_error(toS(type)+\" is no valid Explicit Field Type\"));\n\t\t}\n\t}\n\t\t\n\t// spacetime_field: create_node\n\tnode_factory::sender_ptr node_factory::inner_setup(const arg_t& arg){\n\t\tauto a = delegation(arg); if(a) return get_node(*a);\n\t\treturn selecting_setup<J_SGS,\n\t\t\t\t\t\t\t\tdiscretized_space_field<J_SGS>,\n\t\t\t\t\t\t\t\tgrid_iterator<J_SGS,true>,\n\t\t\t\t\t\t\t\tsender_ptr\n\t\t\t\t\t\t\t>(arg);\n\t}\n\n\tnode_factory::bv_sender_ptr \n\t\tnode_factory::boundary_setup( const arg_t& arg ){ \n\t\tauto a = delegation(arg); if(a) return bv_get_node(*a);\n\t\treturn selecting_setup<J_SGS,\n\t\t\t\t\t\t\t\tboundary_field_t<J_SGS>,\n\t\t\t\t\t\t\t\tboundary_iterator<J_SGS-1,false,true>,\n\t\t\t\t\t\t\t\tbv_sender_ptr\n\t\t\t\t\t\t\t>(arg);\n\t}\n\n}}\n", "meta": {"hexsha": "af625a24f526210244d4ea5b686ff40242fba74a", "size": 7203, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/explicit_fields.cpp", "max_stars_repo_name": "johannesgerer/fipster", "max_stars_repo_head_hexsha": "10e840e01d196cddef75bf3eeb427f720b3e0ad6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-29T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-29T14:33:37.000Z", "max_issues_repo_path": "src/explicit_fields.cpp", "max_issues_repo_name": "johannesgerer/fipster", "max_issues_repo_head_hexsha": "10e840e01d196cddef75bf3eeb427f720b3e0ad6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/explicit_fields.cpp", "max_forks_repo_name": "johannesgerer/fipster", "max_forks_repo_head_hexsha": "10e840e01d196cddef75bf3eeb427f720b3e0ad6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1818181818, "max_line_length": 99, "alphanum_fraction": 0.6243231987, "num_tokens": 1957, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228891883799, "lm_q2_score": 0.6297746074044134, "lm_q1q2_score": 0.416862227670607}}
{"text": "#include <boost/optional.hpp>\n#include <numeric>\n#include <vector>\n\n// 重み付きUnionFind\ntemplate <typename T = int>\nclass WeightedUnionFind {\n\tstd::vector<size_t> parents;\n\tstd::vector<size_t> rank;\n\tstd::vector<T> diff_weight;\n\tT identity;\n\n\tpublic:\n\tWeightedUnionFind(size_t size, T id = static_cast<T>(0))\n\t\t: parents(size), rank(size, 0), diff_weight(size, id), identity(id) {\n\t\tstd::iota(this->parents.begin(), this->parents.end(), 0);\n\t}\n\n\t// 併合\n\tbool merge(size_t a, size_t b, T w) {\n\t\tsize_t ar = this->root(a);\n\t\tsize_t br = this->root(b);\n\t\tif(ar == br) {\n\t\t\treturn false;\n\t\t}\n\t\tT dw = w + this->weight(a) - this->weight(b);\n\t\tif(this->rank[ar] < this->rank[br]) {\n\t\t\tstd::swap(ar, br);\n\t\t\tdw = -dw;\n\t\t}\n\t\tif(this->rank[ar] == this->rank[br]) {\n\t\t\tthis->rank[ar]++;\n\t\t}\n\t\tthis->diff_weight[br] = dw;\n\t\tthis->parents[br] = ar;\n\t\treturn true;\n\t}\n\tbool unite(size_t a, size_t b, T w) { return this->merge(a, b, w); }\n\n\t// 同集合か判定\n\tbool is_same(size_t a, size_t b) { return this->root(a) == this->root(b); }\n\tbool is_union(size_t a, size_t b) { return this->is_same(a, b); }\n\n\t// 二要素感の距離(同集合に属していなければboost::none)\n\toptional<T> diff(size_t a, size_t b) {\n\t\tif(!this->is_same(a, b)) {\n\t\t\treturn nullopt;\n\t\t}\n\t\treturn optional<T>(this->weight(b) - this->weight(a));\n\t}\n\n\tprivate:\n\tsize_t root(int n) {\n\t\tif(this->parents[n] == n) {\n\t\t\treturn n;\n\t\t}\n\n\t\tsize_t r = this->root(this->parents[n]);\n\t\tthis->diff_weight[n] += this->diff_weight[this->parents[n]];\n\t\tthis->parents[n] = r;\n\t\treturn r;\n\t}\n\n\tT weight(size_t n) {\n\t\troot(n);\n\t\treturn this->diff_weight[n];\n\t}\n};\n", "meta": {"hexsha": "e2523bcebbc1e83cf9dec16aa158c35225b8d8a2", "size": 1564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "library/WeightedUnionFind.cpp", "max_stars_repo_name": "arlechann/atcoder", "max_stars_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "library/WeightedUnionFind.cpp", "max_issues_repo_name": "arlechann/atcoder", "max_issues_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "library/WeightedUnionFind.cpp", "max_forks_repo_name": "arlechann/atcoder", "max_forks_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6666666667, "max_line_length": 76, "alphanum_fraction": 0.6163682864, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.661922862511608, "lm_q1q2_score": 0.41686221087025344}}
{"text": "/* ----------------------------------------------------------------------- *//**\n *\n * @file svd.cpp\n *\n * @brief Functions for Singular Value Decomposition\n *\n * @date Jul 10, 2013\n *//* ----------------------------------------------------------------------- */\n\n\n#include <dbconnector/dbconnector.hpp>\n#include <math.h>\n#include <iostream>\n#include <algorithm>\n#include <functional>\n#include <numeric>\n#include \"svd.hpp\"\n#include <Eigen/SVD>\n\nnamespace madlib {\n\nusing namespace dbal::eigen_integration;// Use Eigen\n\nnamespace modules {\nnamespace linalg {\n\nusing madlib::dbconnector::postgres::madlib_construct_array;\n\n// To get a rank-k approximation of the original matrix if we perform k + s Lanczos\n// bidiagonalization steps followed by the SVD of a small matrix B(k+s) then the\n// algorithm constructs the best rank-k subspace in an extended subspace\n// Span[U(k+s)]. Hence we obtain a better rank-k approximation than the one\n// obtained after k steps steps of the standard Lanczos bidiagonalization algorithm.\n// There is a memory limit to the number of extended steps and we restrict that to\n// fixed number of steps for now.\n// Magic number computed using the 1GB memory limit.\n// MAX_LANCZOS_STEPS^2 < 10^9 bytes / (8 bytes * 3 matrices)\nconst size_t MAX_LANCZOS_STEPS = 5000;\n\n// For floating point equality comparisons,\n// it is safer to define a small range of values\n// that are \"zero\", rather than use the exact value of 0.\nconst double ZERO_THRESHOLD = 1e-8;\n\n/* Project the vector v into the vector u (in-place) */\nstatic void __project(MappedColumnVector& u, MutableNativeColumnVector& v){\n    double uu = u.dot(u);\n    double uv = u.dot(v);\n\n    double coef;\n    if (uu <= ZERO_THRESHOLD) { // if u is the zero vector, we have a division by zero problem\n        coef = 0;\n    } else\n        coef = uv / uu;\n    v = coef * u;\n}\n\n\n/**\n * @brief This function returns a random normalized unit vector of specified size\n * @param args[0]   The dimension\n * @return          The unit-norm vector\n **/\nAnyType svd_unit_vector::run(AnyType & args)\n{\n    int32_t dim = args[0].getAs<int32_t>();\n\n    if(dim < 1){\n        throw std::invalid_argument(\n            \"invalid argument - Positive integer expected for dimension\");\n    }\n\n    MutableNativeColumnVector vectorEigen;\n    Allocator& allocator = defaultAllocator();\n    vectorEigen.rebind(allocator.allocateArray<double>(dim));\n    vectorEigen.setRandom();\n    vectorEigen = vectorEigen.normalized();\n\n    // AnyType tuple;\n    // tuple << vectorEigen;\n    // return tuple;\n\n    return vectorEigen;\n}\n\n/**\n * @brief This function is the transition function of the aggregator computing the Lanczos vectors\n * @param args[0]   State variable (i.e. A * q_j OR A_trans * p_(j-1))\n * @param args[1]   Matrix row id\n * @param args[2]   Matrix row array\n * @param args[3]   Previous P/Q vector\n * @param args[4]   Row/Column dimension\n **/\nAnyType svd_lanczos_sfunc::run(AnyType & args){\n    int32_t row_id = args[1].getAs<int32_t>();\n    MappedColumnVector row_array = args[2].getAs<MappedColumnVector >();\n    MappedColumnVector vec = args[3].getAs<MappedColumnVector >();\n    int32_t dim = args[4].getAs<int32_t>();\n\n    if(dim < 1){\n        throw std::invalid_argument(\n            \"invalid argument - Positive integer expected for dimension\");\n    }\n\n    if(row_id <= 0 || row_id > dim){\n        throw std::invalid_argument(\n            \"invalid argument: row_id is out of range [1, dim]\");\n    }\n\n    if(row_array.size() != vec.size()){\n        throw std::invalid_argument(\n            \"dimensions mismatch: row_array.size() != vec.size(). \"\n            \"Data contains different sized arrays\");\n    }\n\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    MutableArrayHandle<double> state(NULL);\n    if(args[0].isNull()){\n        state = MutableArrayHandle<double>(\n            madlib_construct_array(\n                NULL, dim, FLOAT8OID, sizeof(double), true, 'd'));\n        for (int i = 0; i < dim; i++)\n            state[i] = 0;\n    }else{\n        state = args[0].getAs<MutableArrayHandle<double> >();\n    }\n\n    state[row_id - 1] = row_array.dot(vec);\n\n    return state;\n}\n\n/**\n * @brief This function is the merge function of the aggregator computing the Lanczos vectors\n * @param args[0]   State variable 1\n * @param args[1]   State variable 2\n **/\nAnyType svd_lanczos_prefunc::run(AnyType & args){\n    MutableArrayHandle<double> state1 = args[0].getAs<MutableArrayHandle<double> >();\n    ArrayHandle<double> state2 = args[1].getAs<ArrayHandle<double> >();\n\n    if(state1.size() != state2.size()){\n        throw std::runtime_error(\"dimension mismatch: state1.size() != state2.size()\");\n    }\n\n    for(size_t i = 0; i < state1.size(); i++)\n        state1[i] += state2[i];\n\n    return state1;\n}\n\n/**\n * @breif This function completes the computation of Lanczoc P vector\n * @param args[0]   Partial P vector from the aggregator\n * @param args[1]   Previous P vector\n * @param args[2]   Previous beta\n **/\nAnyType svd_lanczos_pvec::run(AnyType & args){\n    MutableNativeColumnVector partial_pvec = args[0].getAs<MutableNativeColumnVector>();\n\n    // When args[1] is NULL, it's special case for computing p_1\n    if (!args[1].isNull()){\n        MappedColumnVector prev_pvec = args[1].getAs< MappedColumnVector >();\n        double beta = args[2].getAs<double>();\n\n        if(partial_pvec.size() != prev_pvec.size()){\n            throw std::invalid_argument(\n                \"dimension mismatch: partial_pvec.size() != prev_pvec.size()\");\n        }\n        partial_pvec = partial_pvec - beta * prev_pvec;\n    }\n\n    double norm = partial_pvec.norm();\n    partial_pvec.normalize();\n\n    AnyType tuple;\n    tuple << norm << partial_pvec;\n    return tuple;\n}\n\n/**\n * @breif This function completes the computation of Lanczoc Q vector\n * @param args[0]   Partial Q vector from the aggregator\n * @param args[1]   Previous Q vector\n * @param args[2]   Current alpha\n **/\nAnyType svd_lanczos_qvec::run(AnyType & args){\n    MutableNativeColumnVector partial_qvec = args[0].getAs<MutableNativeColumnVector>();\n\n    MappedColumnVector prev_qvec = args[1].getAs< MappedColumnVector >();\n    double alpha = args[2].getAs<double>();\n\n    if(partial_qvec.size() != prev_qvec.size()){\n        throw std::invalid_argument(\n            \"dimension mismatch: partial_qvec.size() != prev_qvec.size()\");\n    }\n\n    partial_qvec = partial_qvec - alpha * prev_qvec;\n\n    // Different with svd_lanczos_pvec, the Q vector will be furhter orthogonalized\n    // and then be normalized in a separate function\n    return partial_qvec;\n}\n\n/**\n * @brief This function is the transition function of the aggregaror doing the Gram-Schmidt orthogonalization\n * @param args[0]   State variable: sum of projected vectors | vector v\n * @param args[1]   Unorthogonalized vector (v)\n * @param args[2]   Orthogonalized vector (u)\n **/\nAnyType svd_gram_schmidt_orthogonalize_sfunc::run(AnyType & args){\n\tMutableNativeColumnVector v = args[1].getAs<MutableNativeColumnVector >();\n\tMappedColumnVector u = args[2].getAs<MappedColumnVector >();\n\n\n    if(u.size() != v.size()){\n        throw std::invalid_argument(\n            \"dimensions mismatch: u.size() != v.size()\");\n    }\n\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    MutableArrayHandle<double> state(NULL);\n    if(args[0].isNull()){\n        state = MutableArrayHandle<double>(\n            madlib_construct_array(NULL,\n                                   static_cast<int>(u.size()) * 2,\n                                   FLOAT8OID, sizeof(double), true, 'd'));\n\n        // Save v into the state variable\n        memcpy(state.ptr() + u.size(), v.data(), v.size() * sizeof(double));\n    }else{\n        state = args[0].getAs<MutableArrayHandle<double> >();\n    }\n\n    // In-place projection\n    __project(u, v);\n\n    for(int i = 0; i < u.size(); i++){\n        state[i] += v[i];\n    }\n\n    return state;\n}\n\n/**\n * @brief This function is the merge function of the aggregator doing the Gram-Schmidt orthogonalization\n * @param args[0]   State variable 1\n * @param args[1]   State variable 2\n **/\nAnyType svd_gram_schmidt_orthogonalize_prefunc::run(AnyType & args){\n    MutableArrayHandle<double> state1 = args[0].getAs<MutableArrayHandle<double> >();\n    ArrayHandle<double> state2 = args[1].getAs<ArrayHandle<double> >();\n\n    if(state1.size() != state2.size()){\n        throw std::runtime_error(\"dimension mismatch: state1.size() != state2.size()\");\n    }\n\n    // Note that the second half of the state variable stores the vector v\n    for(size_t i = 0; i < state1.size() / 2; i++)\n        state1[i] += state2[i];\n\n    return state1;\n}\n\n/**\n * @brief This function is the final function of the aggregator doing the Gram-Schmidt orthogonalization\n * @param args[0]   State variable\n **/\nAnyType svd_gram_schmidt_orthogonalize_ffunc::run(AnyType & args){\n    ArrayHandle<double> state = args[0].getAs<ArrayHandle<double> >();\n\n    MutableNativeColumnVector u;\n    Allocator& allocator = defaultAllocator();\n    u.rebind(allocator.allocateArray<double>(state.size() / 2));\n\n    for(int i = 0; i < u.size(); i++){\n        u[i] = state[u.size() + i] - state[i];\n    }\n\n    double norm = u.norm();\n    u.normalize();\n\n    AnyType tuple;\n    tuple << norm << u;\n\n    return tuple;\n}\n\n// -- SVD Decomposition for Bidiagonal Matrix --------------------------------\n/**\n * @brief This function is the transition function of the aggregator computing the SVD\n * of a sparse bidiagonal matrix\n * @param args[0]   State variable (in-memory dense matrix)\n * @param args[1]   Dimension of the matrix (i.e. k)\n * @param args[2]   Row ID (i.e. row_id)\n * @param args[3]   Column ID (i.e. col_id)\n * @param args[4]   Value\n **/\nAnyType svd_decompose_bidiagonal_sfunc::run(AnyType & args){\n    if(args[1].isNull() || args[2].isNull()\n        || args[3].isNull() || args[4].isNull())\n        return args[0];\n\n    int32_t k = args[1].getAs<int32_t>();\n    int32_t row_id = args[2].getAs<int32_t>();\n    int32_t col_id = args[3].getAs<int32_t>();\n    double value = args[4].getAs<double>();\n\n    if(k < 0){\n        throw std::invalid_argument(\n            \"SVD error: k should be a positive integer\");\n    }\n    if(k > (int)MAX_LANCZOS_STEPS){\n        throw std::invalid_argument(\n            \"SVD error: k is too large, try with a value in the range of [1, 6000]\");\n    }\n    if(row_id <= 0 || row_id > k){\n        throw std::invalid_argument(\n            \"SVD error: row_id should be in the range of [1, k]\");\n    }\n    if(col_id <= 0 || col_id > k){\n        throw std::invalid_argument(\n            \"invalid parameter: col_id should be in the range of [1, k]\");\n    }\n\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    MutableArrayHandle<double> state(NULL);\n    if(args[0].isNull()){\n        state = MutableArrayHandle<double>(\n            madlib_construct_array(NULL, k * k, FLOAT8OID, sizeof(double), true, 'd'));\n    } else {\n        state = args[0].getAs<MutableArrayHandle<double> >();\n    }\n\n    state[(row_id - 1) * k + col_id - 1] = value;\n    return state;\n}\n\n/**\n * @brief This function is the merge function of the aggregator computing the SVD\n * of a sparse bidiagonal matrix\n * @param args[0]   State variable 1\n * @param args[1]   State varaible 2\n **/\nAnyType svd_decompose_bidiagonal_prefunc::run(AnyType & args){\n    MutableArrayHandle<double> state1 = args[0].getAs<MutableArrayHandle<double> >();\n    ArrayHandle<double> state2 = args[1].getAs<ArrayHandle<double> >();\n\n    if(state1.size() != state2.size()){\n        throw std::runtime_error(\"dimension mismatch: state1.size() != state2.size()\");\n    }\n\n    for(size_t i = 0; i < state1.size(); i++){\n        state1[i] += state2[i];\n    }\n\n    return state1;\n}\n\n/**\n * @brief Take the final matrix and run it by Eigen JacobiSVD to get the left and right\n    decompositions along with the eigen values\n **/\nAnyType svd_decompose_bidiagonal_ffunc::run(AnyType & args){\n    MappedColumnVector state = args[0].getAs<MappedColumnVector>();\n    size_t k = static_cast<size_t>(sqrt(static_cast<double>(state.size())));\n\n    // Note that Eigen Matrix deserializes the vector in the column order\n    // Thus transpose() is needed after resize()\n    Matrix b = state;\n    b.resize(k, k);\n    b.transposeInPlace();\n    Eigen::JacobiSVD<Matrix> svd(b, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n    // Note that AnyType serializes the Matrix Object in the column order\n    // Thus transpose() is needed before output\n    Matrix u = svd.matrixU().transpose();\n    Matrix v = svd.matrixV().transpose();\n    Matrix s = svd.singularValues();\n\n    AnyType tuple;\n    tuple << u << v << s;\n    return tuple;\n}\n\nAnyType svd_decompose_bidiag::run(AnyType & args){\n\n    // <row_id, col_id, value> triple indicate the values of a bidiagonal matrix\n    ArrayHandle<int32_t> row_id = args[0].getAs<ArrayHandle<int32_t> >();\n    ArrayHandle<int32_t> col_id = args[1].getAs<ArrayHandle<int32_t> >();\n    MappedColumnVector value = args[2].getAs<MappedColumnVector>();\n\n    // since row_id, col_id start indexing from 1, the max element indicates the\n    // dimension of of the bidiagonal matrix\n    int32_t row_dim = *std::max_element(row_id.ptr(), row_id.ptr() + row_id.size());\n    int32_t col_dim = *std::max_element(col_id.ptr(), col_id.ptr() + col_id.size());\n\n    Matrix b = Matrix::Zero(row_dim, col_dim);\n    for(size_t i = 0; i < row_id.size(); i++){\n        // we use -1 since row_id and col_id start from 1\n        b(row_id[i] - 1, col_id[i] - 1) = value[i];\n    }\n\n    Eigen::JacobiSVD<Matrix> svd(b, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n    // Note that AnyType serializes the Matrix Object in the column order\n    // Thus transpose() is needed before output\n    Matrix u = svd.matrixU().transpose();\n    Matrix v = svd.matrixV().transpose();\n    Matrix s = svd.singularValues();\n\n    AnyType tuple;\n    tuple << u << v << s;\n    return tuple;\n}\n\n/**\n * @brief This function is the transition function of the aggregator computing the Lanczos vectors\n * @param args[0]   State variable (i.e. A * q_j OR A_trans * p_(j-1))\n * @param args[1]   Matrix block row id\n * @param args[2]   Matrix block col id\n * @param args[3]   Matrix block\n * @param args[4]   Previous P/Q vector\n * @param args[5]   Row/Column dimension\n **/\nAnyType svd_block_lanczos_sfunc::run(AnyType & args){\n    int32_t row_id = args[1].getAs<int32_t>();\n    int32_t col_id = args[2].getAs<int32_t>();\n    MappedMatrix block = args[3].getAs<MappedMatrix>();\n    MappedColumnVector vec = args[4].getAs<MappedColumnVector >();\n    int32_t dim = args[5].getAs<int32_t>();\n\n    if(row_id <= 0){\n        throw std::invalid_argument(\n            \"SVD error: row_id should be in the range of [1, dim]\");\n    }\n    if(col_id <= 0){\n        throw std::invalid_argument(\n            \"invalid parameter: col_id should be in the range of [1, dim]\");\n    }\n\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    MutableArrayHandle<double> state(NULL);\n    if(args[0].isNull()){\n        state = MutableArrayHandle<double>(\n            madlib_construct_array(\n                NULL, dim, FLOAT8OID, sizeof(double), true, 'd'));\n    }else{\n        state = args[0].getAs<MutableArrayHandle<double> >();\n    }\n\n    // Note that block is constructed in the column-major order\n    size_t row_size = block.cols();\n    size_t col_size = block.rows();\n\n    Matrix v = block.transpose() * vec.segment((col_id - 1) * col_size, col_size);\n    for(int32_t i = 0; i < v.rows(); i++)\n        state[(row_id - 1) * row_size + i] += v.col(0)[i];\n\n    return state;\n}\n\n/**\n * @brief This function is the transition function of the aggregator computing the Lanczos vectors\n * @param args[0]   State variable (i.e. A * q_j OR A_trans * p_(j-1))\n * @param args[1]   Row ID\n * @param args[2]   Column ID\n * @param args[3]   Value\n * @param args[4]   Previous P/Q vector\n * @param args[5]   Row/Column dimension\n **/\nAnyType svd_sparse_lanczos_sfunc::run(AnyType & args){\n    int32_t row_id = args[1].getAs<int32_t>();\n    int32_t col_id = args[2].getAs<int32_t>();\n    double value = args[3].getAs<double>();\n\n    MappedColumnVector vec = args[4].getAs<MappedColumnVector >();\n    int32_t dim = args[5].getAs<int32_t>();\n\n    // FIXME: construct_array functions circumvent the abstraction layer. These\n    // should be replaced with appropriate Allocator:: calls.\n    MutableArrayHandle<double> state(NULL);\n    if(args[0].isNull()){\n        state = MutableArrayHandle<double>(\n            madlib_construct_array(\n                NULL, dim, FLOAT8OID, sizeof(double), true, 'd'));\n    }else{\n        state = args[0].getAs<MutableArrayHandle<double> >();\n    }\n\n    state[row_id - 1] += value * vec[col_id - 1];\n    return state;\n}\n\n/*\n *  @brief In-memory multiplication of a vector with a matrix\n *  @param vec  a 1 x r vector\n *  @param mat  a r x n matrix\n *  @param k    a positive number < n\n *  @note first cut mat to r x k, then return vec * mat\n */\nAnyType svd_vec_mult_matrix::run(AnyType & args){\n    MappedColumnVector vec = args[0].getAs<MappedColumnVector>();\n    MappedMatrix mat = args[1].getAs<MappedMatrix>();\n    int32_t k = args[2].getAs<int32_t>();\n\n    // Any integer is ok\n    if(k <= 0 || k > mat.rows()){\n        k = static_cast<int32_t>(mat.rows());\n    }\n\n    // Note mat is constructed in the column-first order\n    // which means that mat is actually transposed\n    if(vec.size() != mat.cols()){\n        throw std::invalid_argument(\n            \"dimensions mismatch: vec.size() != matrix.rows()\");\n    };\n\n    // trans(vec) * trans(mat) = mat * vec\n    Matrix r = mat.topRows(k) * vec;\n    ColumnVector v = r.col(0);\n    return v;\n}\n\ntypedef struct __sr_ctx{\n    ColumnVector vec;\n    Matrix mat;\n    int32_t max_call;\n    int32_t cur_call;\n    int32_t row_id;\n    int32_t k;\n} sr_ctx;\n\n/**\n * @param arg[0]    Column vector\n * @param arg[1]    Matrix (l x l)\n * @param args[2]   Column ID\n # @param arg[3]    k (Sub-matrix: l * k)\n **/\nvoid * svd_vec_trans_mult_matrix::SRF_init(AnyType &args){\n    sr_ctx * ctx = new sr_ctx;\n    ctx->vec = args[0].getAs<MappedColumnVector>();\n    ctx->mat = args[1].getAs<MappedMatrix>().transpose();\n    ctx->row_id = args[2].getAs<int32_t>();\n    ctx->k = args[3].getAs<int32_t>();\n\n    if(ctx->row_id <= 0 || ctx->row_id > ctx->mat.rows()){\n        elog(ERROR,\n            \"invalid parameter - row_id should be in the range of [1, mat.rows()]\");\n    }\n\n    if(ctx->k > ctx->mat.cols()){\n        elog(ERROR,\n            \"invalid parameter - k should be in the range of [0, mat.cols()]\");\n    }\n\n    ctx->max_call = static_cast<int32_t>(ctx->vec.size());\n    ctx->cur_call = 0;\n\n    return ctx;\n}\n\nAnyType svd_vec_trans_mult_matrix::SRF_next(void *user_fctx, bool *is_last_call){\n    sr_ctx * ctx = (sr_ctx *) user_fctx;\n    if (ctx->max_call == 0) {\n        *is_last_call = true;\n        return Null();\n    }\n\n    ColumnVector res = ctx->vec[ctx->cur_call] *\n                            ctx->mat.row(ctx->row_id - 1).segment(0, ctx->k);\n    AnyType tuple;\n    tuple << ctx->cur_call << res;\n\n    ctx->cur_call++;\n    ctx->max_call--;\n    *is_last_call = false;\n\n    return tuple;\n}\n\n} //namespace linalg\n} // namespace modules\n} //namespace madlib\n", "meta": {"hexsha": "0c120d6e4928f9155305367be6dfe2960ff95c26", "size": 19546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/modules/linalg/svd.cpp", "max_stars_repo_name": "iyerr3/madlib", "max_stars_repo_head_hexsha": "ab7166ff4fc55311ec29bb8b54d17becd9bb1750", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-01T17:58:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-01T17:58:05.000Z", "max_issues_repo_path": "src/modules/linalg/svd.cpp", "max_issues_repo_name": "iyerr3/madlib", "max_issues_repo_head_hexsha": "ab7166ff4fc55311ec29bb8b54d17becd9bb1750", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-09-06T05:50:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-06T05:50:17.000Z", "max_forks_repo_path": "src/modules/linalg/svd.cpp", "max_forks_repo_name": "iyerr3/madlib", "max_forks_repo_head_hexsha": "ab7166ff4fc55311ec29bb8b54d17becd9bb1750", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T20:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-03T20:50:13.000Z", "avg_line_length": 33.1850594228, "max_line_length": 109, "alphanum_fraction": 0.6379310345, "num_tokens": 5166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.41680336340405916}}
{"text": "/*\n * Dijkstra.cpp\n *\n * \t\\brief     My dijkstra implementation for the tenth exercise\n *  \\details   This class computes the longest shortest path for given startingPoint\n *  \\author    Julia Baumbach\n *  \\date      15.07.2017\n */\n\n#include \"DijkstraSolver.h\"\n\n#include <climits>\n#include <iostream>\n#include <boost/heap/fibonacci_heap.hpp>\n#include <exception>\n\n/**\n * \\struct compare_function\n * \\brief defines how 2 dijkstra pairs should be compared at fibonacci-heap\n * \\param edge1 first edge to compare\n * \\param edge2 second edge to compare\n * \\return true if the weight of edge2 is smaller than edge1's weight\n */\nstruct compare_function{\n\tbool operator()(const DijkstraPair edge1, const DijkstraPair edge2) const{\n\t\treturn edge1.second > edge2.second;\n\t}\n};\n\n/**\n * \\fn the constructor\n * \\brief initialize a new dijkstra instance while sorting the given edges\n * \\param weights Vector of the weights for the given graph\n * \\param edges Vector of the edges for the given graph\n * \\return the new dijkstra instance\n */\nDijkstraSolver::DijkstraSolver(SortedEdges sortedEdges, unsigned int numberOfVertices):\n\tsortedEdges(sortedEdges), numberOfVertices(numberOfVertices) {\n}\n\n/**\n * \\fn void dijkstra::computeShortestPath\n * \\brief computes all shortest paths from given start vertex for the initialized dijkstra instance and save the weights and predecessorMaps in the given maps\n * \\param unsigned int numberOfVertices Number of Vertices for the graph\n * \\param WeightMap& weightsToVertices map to store the weight to the i-th node at the i-th position\n * \\param vector<int>& predecessorMap map to store the i-th's predecessor at the i-th position\n */\nvoid DijkstraSolver::computeShortestPath(unsigned int startNode, WeightMap& weightsToVertices, std::vector<int>& predecessorMap){\n\tif(startNode > numberOfVertices){\n\t\tstd::cerr << \"Index of StartVertex must be less or equal to number of vertices\" << std::endl;\n\t\tthrow std::exception();\n\t}\n\tVisitedMap alreadyVisited(numberOfVertices+1, false);\n\n\t//Start in point startNode\n\tweightsToVertices[startNode] = 0;\n\tpredecessorMap[startNode] = startNode;\n\tint currentVertex = startNode;\n\tint currentDist = 0;\n\n\tboost::heap::fibonacci_heap<DijkstraPair, boost::heap::compare<compare_function>> heap;\n\t//Put the start vertex in the verticesToVisit list\n\theap.push(std::make_pair(startNode, 0));\n\n\twhile(!heap.empty()){\n\t\tif (!alreadyVisited.at(heap.top().first)){\n\t\t\tcurrentVertex = heap.top().first;\n\t\t\tcurrentDist = heap.top().second;\n\n\t\t\theap.pop();\n\n\t\t\tstd::vector<DijkstraPair> currentEdges = sortedEdges.at(currentVertex);\n\n\t\t\tfor (const DijkstraPair pair : currentEdges){\n\t\t\t\t//Find out the current neighbor vertex and the weight of the current edge\n\t\t\t\tint neighborVertex = pair.first;\n\t\t\t\tint currentWeight = pair.second;\n\t\t\t\t//Search for the right position in verticesToVisit-list. If Vertex is already visited, don't add this edge\n\t\t\t\tif (!alreadyVisited.at(neighborVertex)){\n\t\t\t\t\theap.push(std::make_pair(neighborVertex, currentDist + currentWeight));\n\t\t\t\t}\n\n\t\t\t\tint currentDistance = currentDist + currentWeight;\n\n\t\t\t\t//Update the predecessor and weightsToVerices maps\n\t\t\t\tif (currentDistance < weightsToVertices[neighborVertex]){\n\t\t\t\t\tweightsToVertices[neighborVertex] = currentDistance;\n\t\t\t\t\tpredecessorMap[neighborVertex] = currentVertex;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Current vertex is visited now\n\t\t\talreadyVisited.at(currentVertex) = true;\n\t\t} else {\n\t\t\theap.pop();\n\t\t}\n\t}\n}\n\n/*\n * \\fn int updateEdgeWeight(int edgeStart, int edgeEnd)\n * \\brief sets EdgeWeight of edge (edgestart, edgeEnd) to 0\n * \\param int edgeStart start vertex of the edge\n * \\param int edgeEnd end vertex of the edge\n * \\return returns the old weight of the edge\n */\nint DijkstraSolver::setEdgeWeightToZero(int edgeStart, int edgeEnd){\n\tstd::vector<DijkstraPair>& edges = sortedEdges[edgeStart];\n\n\tfor(DijkstraPair& pair : edges){\n\t\tif(pair.first == edgeEnd){\n\t\t\tint oldWeight = pair.second;\n\t\t\tpair.second = 0;\n\t\t\treturn oldWeight;\n\t\t}\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "aa2109d489f9db70ac87b55502d83501b7595868", "size": 3984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Julia/ex10/src/DijkstraSolver.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Julia/ex10/src/DijkstraSolver.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Julia/ex10/src/DijkstraSolver.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 33.4789915966, "max_line_length": 158, "alphanum_fraction": 0.7394578313, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.41672786591105526}}
{"text": "/**********************************************************************\r\n%\r\n% /// ASAR/MARA Research Group\r\n%\r\n% Technology Arts Sciences TH K�ln\r\n% Technical University of Berlin\r\n% Deutsche Telekom Laboratories\r\n% University of Rostock\r\n% WDR Westdeutscher Rundfunk\r\n% IOSONO GmbH Erfurt\r\n%\r\n% SOFiA sound field analysis\r\n%\r\n% M/F Modal radial filters R13-0306\r\n%     Soft amplification limiting\r\n%     On-axis powerloss compensation with\r\n%     N0plc to N0 interpolation.\r\n%\r\n% Copyright 2011-2017 Benjamin Bernsch�tz, rockzentrale 'AT' me.com\r\n%                        and Nils Peters, nils 'AT' icsi.berkeley.edu\r\n%\r\n% This file is part of the SOFiA toolbox under MIT-License\r\n%\r\n%\r\n% [dn, beam] = SOFIA_MF(N, kr, ac, [a_max], [plc], [fadeover])\r\n% ------------------------------------------------------------------------\r\n% dn          Vector of modal 0-N frequency domain filters\r\n% beam        Expected free field On-Axis kr-response\r\n% ------------------------------------------------------------------------\r\n% N           Maximum Order\r\n% kr          Vector or Matrix of kr values\r\n%             First Row   (M=1) N: kr values Microphone Radius\r\n%             Second Row  (M=2) N: kr values Sphere/Microphone2 Radius\r\n%             [kr_mic;kr_sphere] for Rigid/Dual Sphere Configurations\r\n%             ! If only one kr-vector is given using a Rigid/Dual Sphere\r\n%             Configuration: kr_sphere = kr_mic\r\n% ac          Array Configuration:\r\n%             0  Open Sphere with pressure Transducers (NO plc!)\r\n%             1  Open Sphere with cardioid Transducers\r\n%             2  Rigid Sphere with pressure Transducers\r\n%             3  Rigid Sphere with cardioid Transducers (Thx to Nils Peters!)\r\n%             4  Dual Open Sphere with pressure Transducers (Thx to Nils Peters!)\r\n% a_max       Maximum modal amplification limit in [dB]\r\n% plc         OnAxis powerloss-compensation:\r\n%             0  Off\r\n%             1  Full kr-spectrum plc\r\n%             2  Low kr only -> set fadeover\r\n% fadeover    Number of kr values to fade over +/- around min-distance\r\n%             gap of powerloss compensated filter and normal N0 filters.\r\n%             0 = auto fadeover\r\n%\r\n@ end of header\r\n%\r\n% CONTACT AND LICENSE INFORMATION:\r\n%\r\n% /// ASAR/MARA Research Group\r\n%\r\n%     [1] Technology Arts Sciences TH K�ln\r\n%     [2] Technical University of Berlin\r\n%     [3] Deutsche Telekom Laboratories\r\n%     [4] University of Rostock\r\n%     [5] WDR Westdeutscher Rundfunk\r\n%     [6] IOSONO GmbH Erfurt\r\n%\r\n% SOFiA sound field analysis toolbox\r\n%\r\n% Copyright 2011-2017 Benjamin Bernsch�tz et al.(�)\r\n%\r\n% Contact ------------------------------------\r\n% Technology Arts Sciences TH K�ln\r\n% Institute of Communications Systems\r\n% Betzdorfer Street 2\r\n% D-50679 Germany (Europe)\r\n%\r\n% phone       +49 221 8275 -2496\r\n% cell phone  +49 171 4176069\r\n% mail        rockzentrale 'at' me.com\r\n% --------------------------------------------\r\n%\r\n% This file is part of the SOFiA sound field analysis toolbox\r\n%\r\n% Licence Type: MIT License\r\n%\r\n% Permission is hereby granted, free of charge, to any person obtaining a\r\n% copy of this software and associated documentation files (the \"Software\"),\r\n% to deal in the Software without restriction, including without limitation\r\n% the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n% and/or sell copies of the Software, and to permit persons to whom the\r\n% Software is furnished to do so, subject to the following conditions:\r\n%\r\n% The above copyright notice and this permission notice shall be included\r\n% in all copies or substantial portions of the Software.\r\n%\r\n% THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n% OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r\n% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r\n% IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r\n% DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\r\n% OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\r\n% USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n%\r\n%\r\n% (�) Christoph P�rschmann [1]     christoph.poerschmann 'at' th-koeln.de\r\n%     Sascha Spors         [2,3,4] sascha.spors 'at' uni-rostock.de\r\n%     Stefan Weinzierl     [2]     stefan.weinzierl 'at' tu-berlin.de\r\n%     Nils Peters                  nils 'at' icsi.berkeley.edu\r\n%\r\n**********************************************************************/\r\n\r\n#include <mex.h>\r\n#include <complex>\r\n#include <math.h>\r\n#include <sofia_radial.h>\r\n#include <boost/math/special_functions/spherical_harmonic.hpp>\r\n\r\n#ifndef M_PI\r\n\t#define M_PI 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068\r\n#endif\r\n\r\n\r\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\r\n{\r\n   using namespace std;\r\n   using namespace boost::math;\r\n\r\n   int N, plc, ac, noplcflag, limiteronflag, normalizebeam, zeroflag;\r\n   long long unsigned int ctr, ctrb, ctrc, numberOfkrValues, locatemindistance, fadeover;\r\n   long long signed int ctrd;\r\n   double *kr, *krm, *krs;\r\n   double *ReturnReal,*ReturnImag,*ReturnRealB,*ReturnImagB;\r\n   double a_max, a_maxdB, amplicalc, mindistance, mix, filtergap;\r\n   complex<double> bnval;\r\n   complex<double> *xi, *beamresponse;\r\n   complex<double> **OutputArray;\r\n\r\n   #ifndef DEBUG\r\n    mexPrintf(\"SOFiA M/F - Modal radial filters R13-0306\\n\");\r\n   #endif\r\n\r\n   if(nrhs<3) {mexErrMsgIdAndTxt(\"SOFiA:MF:notEnoughInputs\",\r\n                 \"Minimum 3 Inputs required: N, kr, ac, [a_max], [plc], [fadeover]\");}\r\n\r\n    //Get first 3 ARGS\r\n    N           =           (int)mxGetScalar(prhs[0]);\r\n    kr          =                    mxGetPr(prhs[1]);\r\n    ac          =           (int)mxGetScalar(prhs[2]);\r\n\r\n    if(nrhs<4)\r\n    {\r\n        a_max=1;\r\n        a_maxdB=0;\r\n        limiteronflag=0;\r\n    }\r\n    else\r\n    {\r\n        a_maxdB =(double)mxGetScalar(prhs[3]);\r\n        limiteronflag=1;\r\n        a_max=pow(10,(a_maxdB/(double)20)); //dB-Value to double skalar\r\n    }\r\n\r\n    if(nrhs<5) {plc=0;}\r\n    else\r\n    {\r\n       plc = (int)mxGetScalar(prhs[4]);\r\n    }\r\n\r\n    if(nrhs<6) {fadeover=0;}\r\n    else\r\n    {\r\n       fadeover = (long long int)mxGetScalar(prhs[5]);\r\n    }\r\n\r\n\r\n    numberOfkrValues=mxGetN(prhs[1]);\r\n\r\n\r\n    if(mxGetM(prhs[1])>2)\r\n    {\r\n        {mexErrMsgIdAndTxt(\"SOFiA:MF:InputArgError\",\r\n                 \"Vector size not valid: NxM with N=1 or 2 and M=[...] expected.\");}\r\n    }\r\n\r\n    if(N<0)\r\n    {\r\n        {mexErrMsgIdAndTxt(\"SOFiA:MF:InputArgError\",\r\n                 \"N: Order not valid.\");}\r\n    }\r\n    if(a_maxdB<-20.0f)\r\n    {\r\n        {mexErrMsgIdAndTxt(\"SOFiA:MF:InputArgError\",\r\n                 \"a_max: Amplification limit too low.\");}\r\n    }\r\n\r\n    if(ac!=0 && ac!=1 && ac!=2 && ac!=3 && ac!=4)\r\n    {\r\n        {mexErrMsgIdAndTxt(\"SOFiA:MF:InputArgError\",\r\n                 \"ac: Array configuration not valid. ac=[0,1,2,3,4]\");}\r\n    }\r\n\r\n    if(plc!=0 && plc!=1 && plc!=2)\r\n    {\r\n        {mexErrMsgIdAndTxt(\"SOFiA:MF:InputArgError\",\r\n                 \"plc: Choice not valid. plc=[0,1,2]\");}\r\n    }\r\n\r\n    try\r\n     {\r\n        //Allocate Output Array Size [N]*[size(kr)]\r\n        OutputArray = new complex<double>*[N+1];\r\n\r\n        for(ctr = 0; ctr <= N; ctr++)\r\n           {OutputArray[ctr] = new complex<double>[numberOfkrValues];}\r\n\r\n\r\n        //Initializate Output Array\r\n        for(ctr = 0; ctr <= N; ctr++)\r\n           {\r\n            for(ctrb = 0; ctrb < numberOfkrValues; ctrb++)\r\n               {\r\n                    OutputArray[ctr][ctrb] = complex<double>(0,0);\r\n               }\r\n           }\r\n\r\n     }\r\n     catch(...)\r\n     { mexErrMsgIdAndTxt(\"SOFiA:MF:OutArrayAllocation\",\r\n                 \"Not able to allocate memory for the output Matrix. Maybe to large?\");\r\n     }\r\n\r\n\r\n\r\n    //Make Dynamic Arrays\r\n    krm    = new double [mxGetN(prhs[1])];\r\n    krs    = new double [mxGetN(prhs[1])];\r\n\r\n\r\n    for(ctr=0; ctr<(mxGetN(prhs[1])); ctr++)// ctr=ctr+mxGetM(prhs[1]))\r\n    {\r\n        krm[ctr]    = (double)kr[ctr*mxGetM(prhs[1])];\r\n        krs[ctr]    = (double)kr[ctr*mxGetM(prhs[1])+mxGetM(prhs[1])-1];\r\n    }\r\n\r\n\r\n     //Check for Zero-Elements in kr-Vector\r\n     for(ctr = 0; ctr < numberOfkrValues; ctr++)\r\n     {\r\n        zeroflag=0;\r\n        if (krm[ctr]<=0)\r\n        {\r\n            //mexPrintf(\"\\nWarning: kr (mic) contains zero element or negative value.\\n\");\r\n            zeroflag=1;\r\n\r\n            for(ctrb = ctr; ctrb < numberOfkrValues; ctrb++) //Try to repair with next valid element\r\n            {\r\n                if(krm[ctrb]>0)\r\n                {\r\n                    krm[ctr]=krm[ctrb];\r\n                    //mexPrintf(\"         Replaced by next valid kr element [%f].\\n\", krm[ctrb]);\r\n                    zeroflag=0;\r\n                    break;\r\n                }\r\n            }\r\n            if(zeroflag==1)\r\n              {\r\n                 mexErrMsgIdAndTxt(\"SOFiA:MF:DataNotValid\",\r\n                \"SOFiA MF Error: kr vector is not valid.\");\r\n              }\r\n\r\n        }\r\n\r\n        zeroflag=0;\r\n        if (krs[ctr]<=0)\r\n        {\r\n            //mexPrintf(\"\\nWarning: kr (sphere) contains zero element or negative value.\\n\");\r\n            zeroflag=1;\r\n\r\n            for(ctrb = ctr; ctrb < numberOfkrValues; ctrb++) //Try to repair with next valid element\r\n            {\r\n                if(krs[ctrb]>0)\r\n                {\r\n                    krs[ctr]=krs[ctrb];\r\n                    //mexPrintf(\"         Replaced by next valid kr element [%f].\\n\", krs[ctrb]);\r\n                    zeroflag=0;\r\n                    break;\r\n                }\r\n            }\r\n            if(zeroflag==1)\r\n              {\r\n                 mexErrMsgIdAndTxt(\"SOFiA:MF:DataNotValid\",\r\n                \"SOFiA MF Error: kr vector is not valid.\");\r\n              }\r\n\r\n        }\r\n     }\r\n\r\n\r\n    //DO bn-Filter Calculation\r\n     for(ctr = 0; ctr <= N; ctr++)\r\n           {\r\n\r\n            for(ctrb = 0; ctrb < numberOfkrValues; ctrb++)\r\n               {\r\n                    bnval=bn(ctr, krm[ctrb], krs[ctrb], ac);\r\n                    if(limiteronflag==1)\r\n                    {\r\n                        amplicalc=(2*a_max/M_PI)*abs(bnval)*atan(M_PI/(2*a_max*abs(bnval)));\r\n                    }\r\n                    else {amplicalc=1;}\r\n                    OutputArray[ctr][ctrb]=complex<double>(amplicalc,0)/bnval;\r\n               }\r\n           }\r\n\r\n\r\n     if(numberOfkrValues<32 && plc!=0)\r\n      {mexPrintf(\"\\nWARNING: Not enough kr values for PLC fading. PLC disabled.\\n\");\r\n          plc=0;}\r\n\r\n\r\n     //POWERLOSS COMPENSATION FILTER\r\n     noplcflag=0;\r\n     if(plc!=0)\r\n     {\r\n         xi= new complex<double>[numberOfkrValues]; //Array for xi-Term\r\n\r\n         for(ctr=0; ctr<numberOfkrValues; ctr++)\r\n         {\r\n            xi[ctr]=0;\r\n             for(ctrb=0; ctrb<=N; ctrb++)\r\n             {\r\n                 xi[ctr]+=complex<double>(2*ctrb+1,0)*(complex<double>(1,0)-OutputArray[ctrb][ctr]*bn(ctrb,krm[ctr],krs[ctr],ac));\r\n             }\r\n            xi[ctr]*=complex<double>(1,0)/bn(0,krm[ctr],krs[ctr],ac);\r\n            xi[ctr]+=OutputArray[0][ctr];\r\n         }\r\n     }//plc!=0 flag\r\n\r\n\r\n\r\n     if(plc==1) // -------------------- low kr only\r\n     {\r\n\r\n         //Find minimum distance\r\n         mindistance=(double)abs(OutputArray[0][0]-xi[0]);\r\n         locatemindistance=0;\r\n\r\n         for(ctr=0; ctr<numberOfkrValues; ctr++)\r\n         {\r\n             if((double)abs(OutputArray[0][ctr]-xi[ctr]) < mindistance)\r\n             {\r\n                 mindistance=(double)abs(OutputArray[0][ctr]-xi[ctr]);\r\n                 locatemindistance=ctr;\r\n             }\r\n\r\n         }\r\n\r\n         filtergap=20*log10(1/abs(OutputArray[0][locatemindistance]/xi[locatemindistance]));\r\n         mexPrintf(\"\\nFilter fade gap: %4.2f dB\",filtergap);\r\n\r\n         if (filtergap>(double)20.0f || filtergap<(double)-20.0f)\r\n         {mexPrintf(\"\\nWARNING: Filtergap is too large. Nonsense filter expected.\\nNo powerloss compensation filter applied.\");\r\n          noplcflag=1;}\r\n\r\n\r\n         //Overwrite order 0 filter in output matrix\r\n         if (noplcflag==0)\r\n         {\r\n             if (filtergap>(double)5.0f)\r\n                {mexPrintf(\"\\nWARNING: Filtergap is very large.\");}\r\n\r\n             if(fadeover==0) //Auto fadeover size\r\n             {\r\n                 fadeover=(long long int)(numberOfkrValues/100);\r\n                 if (a_maxdB>0)\r\n                 {\r\n                     fadeover=fadeover/(long long int)ceil(a_max/4);\r\n                 }\r\n\r\n                if((fadeover>locatemindistance) || ((locatemindistance+fadeover)>numberOfkrValues))\r\n                     {\r\n                     if ((long long int)(locatemindistance-fadeover)<(long long int)(numberOfkrValues-(locatemindistance+fadeover)))\r\n                      {\r\n                         fadeover=locatemindistance;\r\n                      }\r\n                       else\r\n                       {\r\n                         fadeover=numberOfkrValues-locatemindistance;\r\n                      }\r\n                      }\r\n                  mexPrintf(\"\\nAuto filter size: %d Taps.\", fadeover);\r\n             }\r\n\r\n             if((fadeover>locatemindistance) || ((locatemindistance+fadeover)>numberOfkrValues))\r\n             {\r\n               if ((long long int)(locatemindistance-fadeover)<(long long int)(numberOfkrValues-(locatemindistance+fadeover)))\r\n                {\r\n                    fadeover=locatemindistance;\r\n                }\r\n                 else\r\n                 {\r\n                    fadeover=numberOfkrValues-locatemindistance;\r\n                }\r\n                mexPrintf(\"\\nWARNING: Filter fade size too high. Reduced to %d Taps.\", fadeover);\r\n             }\r\n\r\n             mix=0;\r\n             for(ctr=0; ctr<=locatemindistance-fadeover; ctr++)\r\n             {\r\n                OutputArray[0][ctr]=xi[ctr];\r\n             }\r\n\r\n             for(ctr=locatemindistance-fadeover+1; ctr<=locatemindistance+fadeover-1; ctr++)\r\n                 {\r\n                    mix+=1/(double)(2*fadeover);\r\n                    OutputArray[0][ctr]=OutputArray[0][ctr]*complex<double>(mix,0)+xi[ctr]*complex<double>(1.0f-mix,0);\r\n                }\r\n\r\n\r\n             }//NoPLCFlagEnd\r\n     }//PLC=1 low kr only\r\n\r\n     if(plc==2) // full spectrum\r\n     {\r\n             for(ctr=0; ctr<numberOfkrValues; ctr++)\r\n             {\r\n                OutputArray[0][ctr]=xi[ctr];\r\n             }\r\n     }\r\n\r\n\r\n     //Ouput kr-Response\r\n     beamresponse= new complex<double>[numberOfkrValues]; //Array for kr-response-Term\r\n\r\n     normalizebeam=((N+1)*(N+1));\r\n\r\n     for(ctr=0; ctr<numberOfkrValues; ctr++)\r\n     {\r\n         beamresponse[ctr]=0;                            //Initialize\r\n         for(ctrb=0; ctrb<=N; ctrb++)                   //ctrb=n;\r\n         {\r\n             for(ctrc=0; ctrc<=(2*ctrb); ctrc++)        //ctrc=m;\r\n             {\r\n                 beamresponse[ctr]=beamresponse[ctr]+bn(ctrb,krm[ctr],krs[ctr],ac)*OutputArray[ctrb][ctr];\r\n             }\r\n         }\r\n         beamresponse[ctr]/=complex<double>((double)normalizebeam,0);\r\n     }\r\n\r\n\r\n\r\n     //Declare return ARG Matrix\r\n     plhs[0] = mxCreateDoubleMatrix(N+1,numberOfkrValues,mxCOMPLEX);\r\n     plhs[1] = mxCreateDoubleMatrix(1,numberOfkrValues,mxCOMPLEX);\r\n\r\n     ReturnReal = mxGetPr(plhs[0]);\r\n     ReturnImag = mxGetPi(plhs[0]);\r\n\r\n     //Return ARG Matrix Fill\r\n     ctrc=0;\r\n     for(ctr=0;ctr<numberOfkrValues;ctr++)\r\n        {\r\n        for(ctrb=0;ctrb<=N;ctrb++)\r\n             {\r\n                ReturnReal[ctrc]=real(OutputArray[ctrb][ctr]);\r\n                ReturnImag[ctrc]=imag(OutputArray[ctrb][ctr]);\r\n                ctrc++;\r\n              }\r\n        }\r\n\r\n    //Return Beamresponse\r\n     ReturnRealB = mxGetPr(plhs[1]);\r\n     ReturnImagB = mxGetPi(plhs[1]);\r\n\r\n     for(ctr=0;ctr<numberOfkrValues;ctr++)\r\n         {\r\n                ReturnRealB[ctr]=real(beamresponse[ctr]);\r\n                ReturnImagB[ctr]=imag(beamresponse[ctr]);\r\n         }\r\n\r\n      if(plc!=0)\r\n      {delete [] xi;}\r\n      delete [] beamresponse;\r\n      for(ctr = 0; ctr < (N+1); ctr++) delete OutputArray[ctr];\r\n\r\n}\r\n", "meta": {"hexsha": "ed104d35ab347db4dcc42cad1a584b35de21718a", "size": 16124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CORE_SOURCES/sofia_mf.cpp", "max_stars_repo_name": "AudioGroupCologne/SOFiA", "max_stars_repo_head_hexsha": "4e4e17ec0b14b8e450b68d3d72c33c6f8577c336", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-05-05T08:20:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T19:26:39.000Z", "max_issues_repo_path": "CORE_SOURCES/sofia_mf.cpp", "max_issues_repo_name": "AudioGroupCologne/SOFiA", "max_issues_repo_head_hexsha": "4e4e17ec0b14b8e450b68d3d72c33c6f8577c336", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CORE_SOURCES/sofia_mf.cpp", "max_forks_repo_name": "AudioGroupCologne/SOFiA", "max_forks_repo_head_hexsha": "4e4e17ec0b14b8e450b68d3d72c33c6f8577c336", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-01-09T16:38:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-05T19:14:58.000Z", "avg_line_length": 33.2453608247, "max_line_length": 133, "alphanum_fraction": 0.5211485984, "num_tokens": 4222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.4166555485506078}}
{"text": "#include <random>\n#include <unordered_map>\n#include <cstdio>\n\n#include <boost/functional/hash.hpp>\n\n#include \"agms.hh\"\n\nusing namespace std;\n\n\n//---------------------------\n// hash_family methods\n//---------------------------\n\nusing namespace agms;\n\nstatic mt19937_64 engine;\n\nhash_family::hash_family(depth_type _D) : D(_D) {\n    if (_D == 0) throw std::domain_error(\"0 depth in hash family\");\n\n    uniform_int_distribution<int64_t> U;\n\n    for (size_t i = 0; i < 6; i++) {\n        F[i] = new int64_t[_D];\n        for (size_t d = 0; d < _D; d++)\n            F[i][d] = U(engine);\n    }\n\n#if 0  // printout the random projection seeds\n    for(depth_type d=0; d<D; d++) {\n        printf(\"%4d:\",d);\n        for(size_t i=0;i<6; i++) {\n            printf(\" %12ld\", F[i][d]);\n        }\n        printf(\"\\n\");\n    }\n#endif\n}\n\n\nhash_family::~hash_family() {\n    for (size_t i = 0; i < 6; i++)\n        delete[] F[i];\n}\n\n\n// A cache type for hash families, which is cleared at destruction\nstruct agms_hf_cache\n        : unordered_map<depth_type, hash_family *> {\n    ~agms_hf_cache() {\n        for (auto x : *this)\n            delete x.second;\n    }\n};\n\n// The hash family cache variable\nstatic agms_hf_cache cache;\n\n\nhash_family *hash_family::get_cached(depth_type D) {\n    if (cache.find(D) != cache.end())\n        return cache[D];\n    else {\n        hash_family *ret = new hash_family(D);\n        cache[D] = ret;\n        return ret;\n    }\n}\n\n//\n// Return a 31-bit random hash\n//\ninline int64_t hash31(int64_t a, int64_t b, int64_t x) {\n    // use 64-bit arithmetic\n    int64_t result = (a * x) + b;\n    return ((result >> 31) ^ result) & 2147483647ll;\n}\n\nsize_t hash_family::hash(depth_type d, size_t x) const {\n    assert(d < D);\n    return hash31(F[0][d], F[1][d], x);\n}\n\n/// Return a 4-wise independent bit\nbool hash_family::fourwise(depth_type d, size_t x) const {\n    return\n            hash31(hash31(hash31(x, F[2][d], F[3][d]), x, F[4][d]), x, F[5][d])\n            & (1 << 15);\n}\n\n\nvoid projection::update_index(size_t key, Index &idx) const {\n    assert(idx.size() == depth());\n    size_t stride = 0;\n    for (size_t d = 0; d < depth(); d++) {\n        idx[d] = stride + hf->hash(d, key) % L;\n        stride += width();\n    }\n}\n\nvoid projection::update_mask(size_t key, Mask &mask) const {\n    assert(mask.size() == depth());\n    for (size_t d = 0; d < depth(); d++) {\n        mask[d] = hf->fourwise(d, key);\n    }\n}\n\n\nsize_t std::hash<projection>::operator()(const projection &p) const {\n    using boost::hash_value;\n    using boost::hash_combine;\n\n    size_t seed = 0;\n    hash_combine(seed, hash_value(p.hashf()));\n    hash_combine(seed, hash_value(p.width()));\n    return seed;\n}\n\ntemplate<typename T>\nvoid print_vec(const string &name, const T &a) {\n    size_t n = a.size();\n    cout << name << \"[\" << n << \"]={\";\n    for (size_t i = 0; i < n; i++)\n        cout << (i ? \",\" : \"\") << a[i];\n    cout << \"}\" << endl;\n}\n\n\ninc_sketch_updater::inc_sketch_updater(sketch &_sk)\n        : sk(_sk),\n          delta(_sk.proj.depth()),\n          mask(_sk.proj.depth()) {}\n\n\nvoid inc_sketch_updater::update(size_t key, double freq) {\n    sk.proj.update_index(key, delta.index);\n    sk.proj.update_mask(key, mask);\n\n    delta.xold = sk[delta.index];\n    for (size_t d = 0; d < mask.size(); d++) {\n        if (mask[d])\n            delta.xnew[d] = delta.xold[d] + freq;\n        else\n            delta.xnew[d] = delta.xold[d] - freq;\n    }\n\n    sk[delta.index] = delta.xnew;\n}\n\n\nisketch::isketch(const projection &_proj)\n        : sketch(_proj),\n          delta(proj.depth()),\n          mask(proj.depth()) {}\n\n\nvoid isketch::update(size_t key, double freq) {\n    proj.update_index(key, delta.index);\n    proj.update_mask(key, mask);\n\n    delta.xold = (*this)[delta.index];\n    for (size_t d = 0; d < mask.size(); d++) {\n        if (mask[d])\n            delta.xnew[d] = delta.xold[d] + freq;\n        else\n            delta.xnew[d] = delta.xold[d] - freq;\n    }\n\n    (*this)[delta.index] = delta.xnew;\n}\n", "meta": {"hexsha": "b2c6c56f8a5b1fdda78893bca3a522681a87f1a1", "size": 3989, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/networks/ddsim/agms.cc", "max_stars_repo_name": "ibalampanis/distributed-training-of-recurrent-neural-networks-by-fgm-protocol", "max_stars_repo_head_hexsha": "225146cbf31a27f2a290f54c5b29723635c94cab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/networks/ddsim/agms.cc", "max_issues_repo_name": "ibalampanis/distributed-training-of-recurrent-neural-networks-by-fgm-protocol", "max_issues_repo_head_hexsha": "225146cbf31a27f2a290f54c5b29723635c94cab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/networks/ddsim/agms.cc", "max_forks_repo_name": "ibalampanis/distributed-training-of-recurrent-neural-networks-by-fgm-protocol", "max_forks_repo_head_hexsha": "225146cbf31a27f2a290f54c5b29723635c94cab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0578034682, "max_line_length": 79, "alphanum_fraction": 0.554775633, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.626124191181315, "lm_q1q2_score": 0.4166296478988558}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <functional>\n#include <memory>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <boost/algorithm/string/trim.hpp>\n#include <string.h>\n#include <vector>\n#include \"Eigen/Core\"\n#include <Eigen/Geometry>\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n\nusing namespace std;\ntemplate<class T> struct Point{\n    template <typename NewType> Point<NewType> cast() const{\n        return Point<NewType>();\n    }\n};\nstruct tt{\n\tint x;\n\tint y;\n};\nint main()\n{\n\tEigen::Quaterniond quat0(1, 2,0,0);\n\tstd::cout<<\"quat0: \" <<quat0.w()<<\" \"<<quat0.x()<<\" \"<<quat0.y()<<\" \"<<quat0.z()<<\"\\n\";\n\tEigen::Matrix3d mat0 = quat0.toRotationMatrix();\n\tstd::cout<<\"mat0 (from quat0): \\n\" <<mat0 <<\"\\n\";\n\tEigen::Quaterniond quat1=quat0.conjugate();\n\tstd::cout<<\"quat0 conjugate: \" <<quat1.w()<<\" \"<<quat1.x()<<\" \"<<quat1.y()<<\" \"<<quat1.z()<<\"\\n\";\n\tstd::cout<<\"quat0: \" <<quat0.w()<<\" \"<<quat0.x()<<\" \"<<quat0.y()<<\" \"<<quat0.z()<<\"\\n\";\n\tquat0.normalize();\n\tstd::cout<<\"quat0: \" <<quat0.w()<<\" \"<<quat0.x()<<\" \"<<quat0.y()<<\" \"<<quat0.z()<<\"\\n\";\n\tEigen::Matrix3d mat1 = quat0.toRotationMatrix();\n\tstd::cout<<\"mat1 (quat0 normalized): \\n\" <<mat1 <<\"\\n\";\n\tEigen::Quaterniond quat(1, 0,0,0);\n\tstd::string ss0;\n\tstd::ofstream outFile(\"/home/student//Documents/cartographer/test_ceres_pcd/sweep4.txt\");\n\tstd::ostringstream ssout(\"~/Documents/cartographer/test_ceres_pcd/sweep4.txt\");\n\tssout<<\"hello\"<<2;\n\tssout.str(\"\");//reset\n\tssout<<\"newhello\"<<2;\n\toutFile<<\"hello\"<<3<<\"hello\";\n\toutFile<<ssout.str();\n\toutFile<<1<<\",\"<<2;\n\tstd::cout<<ssout.str();\n\n    std::cout<<\"Eigen::Quaterniond: \"<< quat.w() <<\"\\n\";\n\tEigen::Matrix3d mat3 = Eigen::Quaterniond(1, 0,0,0).toRotationMatrix();\n    Eigen::Vector3d v3d(-1., 0., 0.);\n    Eigen::Transform<double, 3, Eigen::Affine > pose_transform;\n\n    pose_transform.translation()=v3d;\n    pose_transform.rotate(Eigen::AngleAxis<double>(0.5, Eigen::Vector3d::UnitX()));\n    std::cout<<\"Eigen::Transform: rotation\"<< pose_transform.rotation() <<\"\\n\";\n    pose_transform.rotate(quat);\n    pose_transform.linear()=mat3; //Eigen::AngleAxis<double>(0.5, Eigen::Vector3d::UnitX());\n    //pose_transform.rotate() =mat3;\n    //pose_transform.block<3,3>(0,0) =mat3;\n    std::cout<<\"Eigen::Matrix3f: \"<< mat3 <<\"\\n\";\n    std::cout<<\"Eigen::Vector3d: \"<< v3d <<v3d[0]<<\"\\n\";\n    std::cout<<\"Eigen::Transform: \"<< pose_transform.translation() <<\"\\n\";\n    std::cout<<\"Eigen::Transform: rotation\"<< pose_transform.rotation() <<\"\\n\";\n    Eigen::Matrix<float, 3, 1> translation0(2,2,2);\n    Eigen::Matrix<double, 3, 1> translation1(translation0.cast<double>());\n\n\n    Point<float> p1;\n     Point<double> p2;\n    tt t1{1,2};\n    //tt t2(1,2); bad structure initialization\n    std::cout<<\"struct tt: \" <<t1.x<<\"\\n\";\n    std::vector<int> v = { 7, 5, 16, 8 };\n    std::vector<int> intvec1;\n    std::cout <<\"intvec1.size(): \"<< intvec1.size();\n    intvec1.push_back(3);\n    std::cout <<\"\\nintvec1.front(): \"<< intvec1.front()<<\"\\n\";\n\n    //std::cout<<p1 <<\" \"<<p2 <<\"\\n\";\n    p2 = p1.cast<double>();\n\tstd::array<int,3> a1{{1,2,3}};\n\tstd::cout<<a1.data()[2];\n\tstd::cout<<a1.at(2);\n\n    std::cout<<\"hello\";\n    std::string filename=\"testopt2.txt\";\n\n    std::cout<<NULL<<\"----\\n\";\nstd::ifstream stream(filename.c_str());\n//    std::ifstream stream(\"testopt2.txt\");\n    std::string myoptstr= std::string((std::istreambuf_iterator<char>(stream)),\n                     std::istreambuf_iterator<char>());\n    std::cout<< myoptstr;\nmap<string, string> mymap;\nchar *token;\ntoken = strtok(const_cast<char*>(myoptstr.c_str()), \"\\n\");\n    while (token != NULL) {\n        string s(token);\n        size_t pos = s.find(\":\");\n        //mymap[s.substr(0, pos)] = boost::algorithm::trim(s);\n\tstring svalue = s.substr(pos + 1, string::npos);\n\tboost::algorithm::trim(svalue);\n        mymap[s.substr(0, pos)] = svalue;\n\t//boost::algorithm::trim(s.substr(pos + 1, string::npos));\n        token = strtok(NULL, \"\\n\");\n\n\tif (s.substr(0, pos)==\"tst\"){\n\tstd::cout<<\"test tst\"<<std::endl;\n\t\tchar * token2;\n\t\t//std::cout<<svalue<<std::endl;\n\t\ttoken2 = strtok(const_cast<char*>(svalue.c_str()), \",\");\n\t\twhile (token2 != NULL) {\n\t\t\tstring ss(token2);\n\t\t\tstd::cout<<token2 <<\" \";\n        \t\ttoken2 = strtok(NULL, \",\");\n\t\t}\n\n\t}\n    }\n\n    std::cout<<\"\\n*****************\\ncout mymap:\\n\";\n    for (auto keyval : mymap)\n        cout << keyval.first << \":\" << keyval.second << endl;\n\n      pcl::PointCloud<pcl::PointXYZ> cloud;\n\n  // Fill in the cloud data\n  cloud.width    = 5;\n  cloud.height   = 1;\n  cloud.is_dense = false;\n  cloud.points.resize (cloud.width * cloud.height);\n\n  for (auto& point: cloud)\n  {\n    point.x = 1024 * rand () / (RAND_MAX + 1.0f);\n    point.y = 1024 * rand () / (RAND_MAX + 1.0f);\n    point.z = 1024 * rand () / (RAND_MAX + 1.0f);\n  }\n\n  pcl::io::savePCDFileASCII (\"test_pcd.pcd\", cloud);\n\n    return 0;\n}\n", "meta": {"hexsha": "6a416941ef020c8565dd107284e26a4a07f96728", "size": 4849, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test.cc", "max_stars_repo_name": "juwangvsu/cartographer-1", "max_stars_repo_head_hexsha": "b173fcba5b53f4372507a36f991673e8783fcdb8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test.cc", "max_issues_repo_name": "juwangvsu/cartographer-1", "max_issues_repo_head_hexsha": "b173fcba5b53f4372507a36f991673e8783fcdb8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test.cc", "max_forks_repo_name": "juwangvsu/cartographer-1", "max_forks_repo_head_hexsha": "b173fcba5b53f4372507a36f991673e8783fcdb8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9863945578, "max_line_length": 98, "alphanum_fraction": 0.5990925964, "num_tokens": 1500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.4166296386143745}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_FUN_MDIVIDE_LEFT_TRI_HPP\n#define STAN_MATH_PRIM_MAT_FUN_MDIVIDE_LEFT_TRI_HPP\n\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <stan/math/prim/mat/fun/promote_common.hpp>\n#include <stan/math/prim/mat/err/check_multiplicable.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n\nnamespace stan {\n  namespace math {\n\n    /**\n     * Returns the solution of the system Ax=b when A is triangular\n     * @param A Triangular matrix.  Specify upper or lower with TriView\n     * being Eigen::Upper or Eigen::Lower.\n     * @param b Right hand side matrix or vector.\n     * @return x = A^-1 b, solution of the linear system.\n     * @throws std::domain_error if A is not square or the rows of b don't\n     * match the size of A.\n     */\n    template <int TriView, typename T1, typename T2,\n              int R1, int C1, int R2, int C2>\n    inline\n    Eigen::Matrix<typename boost::math::tools::promote_args<T1, T2>::type,\n                  R1, C2>\n    mdivide_left_tri(const Eigen::Matrix<T1, R1, C1> &A,\n                     const Eigen::Matrix<T2, R2, C2> &b) {\n      check_square(\"mdivide_left_tri\", \"A\", A);\n      check_multiplicable(\"mdivide_left_tri\", \"A\", A, \"b\", b);\n      return promote_common<Eigen::Matrix<T1, R1, C1>,\n                            Eigen::Matrix<T2, R1, C1> >(A)\n        .template triangularView<TriView>()\n        .solve(promote_common<Eigen::Matrix<T1, R2, C2>,\n               Eigen::Matrix<T2, R2, C2> >(b));\n    }\n\n    /**\n     * Returns the solution of the system Ax=b when A is triangular and b=I.\n     * @param A Triangular matrix.  Specify upper or lower with TriView\n     * being Eigen::Upper or Eigen::Lower.\n     * @return x = A^-1 .\n     * @throws std::domain_error if A is not square\n     */\n    template<int TriView, typename T, int R1, int C1>\n    inline\n    Eigen::Matrix<T, R1, C1>\n    mdivide_left_tri(const Eigen::Matrix<T, R1, C1> &A) {\n      check_square(\"mdivide_left_tri\", \"A\", A);\n      int n = A.rows();\n      Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> b;\n      b.setIdentity(n, n);\n      A.template triangularView<TriView>().solveInPlace(b);\n      return b;\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "cba79c2f72e2b4b80c64403418223da81329bf76", "size": 2200, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/mdivide_left_tri.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/mdivide_left_tri.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/fun/mdivide_left_tri.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6666666667, "max_line_length": 76, "alphanum_fraction": 0.6318181818, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489892, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4165956760494676}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_LOG1P_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_LOG1P_HPP_INCLUDED\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/function/plain.hpp>\n\n#include <boost/simd/function/scalar/inc.hpp>\n#include <boost/simd/function/musl.hpp>\n#include <boost/simd/function/scalar/oneminus.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/scalar/inc.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/frexp.hpp>\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/function/musl.hpp>\n#include <boost/simd/function/plain.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/simd/detail/constant/log_2hi.hpp>\n#include <boost/simd/detail/constant/log_2lo.hpp>\n\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  BOOST_DISPATCH_OVERLOAD ( log1p_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( A0 const& a0) const BOOST_NOEXCEPT\n    {\n      return musl_(log1p)(a0);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD ( log1p_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const std_tag &, A0 a0) const BOOST_NOEXCEPT\n    {\n      return std::log1p(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( log1p_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::musl_tag\n                          , bd::scalar_< bd::single_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const musl_tag &, A0 x) const BOOST_NOEXCEPT\n    {\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      uiA0 ix = bitwise_cast<uiA0>(x);\n      iA0 k = 1;\n      A0 c = Zero<A0>(), f = x;\n      if (ix < 0x3ed413d0 || ix>>31)               /* 1+x < sqrt(2)+  */\n      {\n        if (ix >= 0xbf800000)                       /* x <= -1.0 */\n        {\n          if (x == Mone<A0>())  return Minf<A0>();  /* log1p(-1)=-inf */\n          return Nan<A0>();                         /* log1p(x<-1)=NaN */\n        }\n        if (ix<<1 < 0x33800000<<1)                  /* |x| < 2**-24 */\n        {\n          if ((ix&0x7f800000) == 0) return x;\n        }\n        if (ix <= 0xbe95f619)                       /* sqrt(2)/2- <= 1+x < sqrt(2)+ */\n        {\n          k = 0;\n        }\n      }\n      else if (ix >= 0x7f800000)  return x;\n      if (k)\n      {\n        /* reduce u into [sqrt(2)/2, sqrt(2)] */\n        A0 uf =  inc(x);\n        uiA0 iu = bitwise_cast<uiA0>(uf);\n        iu += 0x3f800000 - 0x3f3504f3;\n        k = bitwise_cast<iA0>(iu>>23) - 0x7f;\n        /* correction term ~ log(1+x)-log(u), avoid underflow in c/u */\n        if (k < 25)\n        {\n          c = k >= 2 ? oneminus(uf-x) : x-dec(uf);\n          c /= uf;\n        }\n\n        /* reduce u into [sqrt(2)/2, sqrt(2)] */\n        iu = (iu&0x007fffff) + 0x3f3504f3;\n        f =  dec(bitwise_cast<A0>(iu));\n      }\n      A0 s = f/(2.0f + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0, 0x3eccce13, 0x3e789e26>(w);\n      A0 t2= z*horn<A0, 0x3f2aaaaa, 0x3e91e9ee>(w);\n      A0 R = t2 + t1;\n      A0 hfsq = 0.5f*sqr(f);\n      A0 dk = k;\n      return  fma(dk, Log_2hi<A0>(), ((fma(s, (hfsq+R), dk*Log_2lo<A0>()+c) - hfsq) + f));\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( log1p_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::musl_tag\n                          , bd::scalar_< bd::double_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const musl_tag &, A0 x) const BOOST_NOEXCEPT\n    {\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      uiA0 hx = bitwise_cast<uiA0>(x) >> 32;\n      iA0 k = 1;\n\n      A0 c = Zero<A0>(), f = x;\n      if (hx < 0x3fda827a || hx>>31)               /* 1+x < sqrt(2)+ */\n      {\n        if (hx >= 0xbff00000)                      /* x <= -1.0 */\n        {\n          if (x == Mone<A0>()) return Minf<A0>();  /* log1p(-1)=-inf */\n          return Nan<A0>();                        /* log1p(x<-1)=NaN */\n        }\n        if (hx<<1 < 0x3ca00000<<1)                 /* |x| < 2**-53 */\n        {\n          if ((hx&0x7ff00000) == 0) return x;\n        }\n        if (hx <= 0xbfd2bec4)                      /* sqrt(2)/2- <= 1+x < sqrt(2)+ */\n        {\n          k = 0;\n        }\n      } else if (hx >= 0x7ff00000) return x;\n      if (k)\n      {\n        /* reduce x into [sqrt(2)/2, sqrt(2)] */\n        A0 uf =  inc(x);\n        uiA0 hu = bitwise_cast<uiA0>(uf)>>32;\n        hu += 0x3ff00000 - 0x3fe6a09e;\n        k = (int)(hu>>20) - 0x3ff;\n        /* correction term ~ log(1+x)-log(u), avoid underflow in c/u */\n        if (k < 54)\n        {\n          c = k >= 2 ? oneminus(uf-x) : x-dec(uf);\n          c /= uf;\n        }\n        hu =  (hu&0x000fffff) + 0x3fe6a09e;\n        f = bitwise_cast<A0>( bitwise_cast<uiA0>(hu<<32) | (bitwise_and(0xffffffffull, bitwise_cast<uiA0>(uf))));\n        f = dec(f);\n      }\n\n      A0 hfsq = 0.5*sqr(f);\n      A0 s = f/(2.0f + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0, 0x3fd999999997fa04ll, 0x3fcc71c51d8e78afll, 0x3fc39a09d078c69fll > (w);\n      A0 t2= z*horn<A0, 0x3fe5555555555593ll, 0x3fd2492494229359ll\n                      , 0x3fc7466496cb03dell, 0x3fc2f112df3e5244ll> (w);\n      A0 R = t2 + t1;\n      A0 dk = k;\n      return  fma(dk, Log_2hi<A0>(), ((fma(s, (hfsq+R), dk*Log_2lo<A0>()+c) - hfsq) + f));\n    }\n  };\n\n    BOOST_DISPATCH_OVERLOAD ( log1p_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::plain_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const plain_tag &, A0 x) const BOOST_NOEXCEPT\n    {\n      return musl_(log1p)(x); //the \"plain\" version of the algorithm is never speedier than the \"musl\" version.\n      // the call is here to allow a scalar fallback to simd calls\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "d2a1bf718f931a90d5abe7ee93fdc2b1431a4180", "size": 7147, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/log1p.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/scalar/function/log1p.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/scalar/function/log1p.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 34.1961722488, "max_line_length": 113, "alphanum_fraction": 0.4869175878, "num_tokens": 2223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.41659566937137327}}
{"text": "#include <cassert>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <Eigen/Core>\n#include \"genfile/Error.hpp\"\n#include \"genfile/VariantEntry.hpp\"\n#include \"components/SNPSummaryComponent/DifferentialMissingnessComputation.hpp\"\n#include \"metro/FishersExactTest.hpp\"\n#include \"metro/likelihood/Multinomial.hpp\"\n#include \"metro/likelihood/ProductOfMultinomials.hpp\"\n\nnamespace stats {\n\tDifferentialMissingnessComputation::UniquePtr DifferentialMissingnessComputation::create( std::string const& stratification_name, StrataMembers const& strata_members ) {\n\t\treturn DifferentialMissingnessComputation::UniquePtr(\n\t\t\tnew DifferentialMissingnessComputation( stratification_name, strata_members )\n\t\t) ;\n\t}\n\n\tDifferentialMissingnessComputation::DifferentialMissingnessComputation( std::string const& stratification_name, StrataMembers const& strata_members, double threshhold ):\n\t\tm_stratification_name( stratification_name ),\n\t\tm_strata_members( strata_members ),\n\t\tm_strata_levels( compute_strata_levels( m_strata_members ) ),\n\t\tm_threshhold( threshhold )\n\t{\n\t#if 0\n\t\tif( strata_members.size() != 2 ) {\n\t\t\tthrow genfile::BadArgumentError( \"DifferentialMissingnessComputation::DifferentialMissingnessComputation()\", \"strata_members( size \" + genfile::string_utils::to_string( strata_members.size() ) + \")\" ) ;\n\t\t}\n\t#endif\n\t}\n\n\tstd::vector< int > DifferentialMissingnessComputation::compute_strata_levels( StrataMembers const& strata_members ) const {\n\t\tstd::vector< int > result ;\n\t\tint level = 0 ;\n\t\tfor( StrataMembers::const_iterator i = strata_members.begin(); i != strata_members.end(); ++i, ++level ) {\n\t\t\tfor( std::size_t j = 0; j < i->second.size(); ++j ) {\n\t\t\t\tstd::size_t const index = i->second[j] ;\n\t\t\t\tresult.resize( std::max( result.size(), index+1 ), -1 ) ;\n\t\t\t\tresult[ index ] = level ;\n\t\t\t}\n\t\t}\n\t\treturn result ;\n\t}\n\n\tvoid DifferentialMissingnessComputation::operator()( VariantIdentifyingData const& snp, Genotypes const& genotypes, Ploidy const&, genfile::VariantDataReader&, ResultCallback callback ) {\n\t\t// construct a table\n\t\t// \n\t\t//                 missing     not missing\n\t\t//   stratum 1       a              b\n\t\t//   stratum 2       c              d\n\t\t// \n\t\t// on which we can do a Fisher's exact test or a product of binomial-type test.\n\t\t//\n\t\tint const number_of_strata = 1 + *std::max_element( m_strata_levels.begin(), m_strata_levels.end() ) ;\n\t\tEigen::MatrixXd table( number_of_strata, 2 ) ;\n\t\ttable.setZero() ;\n\t\tfor( int i = 0; i < genotypes.rows(); ++i ) {\n\t\t\tif( m_strata_levels[i] >= 0 ) {\n\t\t\t\tif( genotypes.row( i ).sum() < m_threshhold ) {\n\t\t\t\t\ttable( m_strata_levels[i], 0 )++ ;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttable( m_strata_levels[i], 1 )++ ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\t{\n\t\t\tStrataMembers::const_iterator i = m_strata_members.begin() ;\n\t\t\tStrataMembers::const_iterator const end_i = m_strata_members.end() ;\n\t\t\tfor( int level = 0; i != end_i; ++level, ++i ) {\n\t\t\t\tstd::string tag = \"[\" + m_stratification_name + \"=\" + genfile::string_utils::to_string( i->first ) + \"]\" ;\n\t\t\t\tcallback( \"missing\" + tag, table( level, 0 ) ) ;\n\t\t\t\tcallback( \"non_missing\" + tag, table( level, 1 ) ) ;\n\t\t\t}\n\t\t}\n\n\t\tstd::string const stub = \"missingness_by_\" + m_stratification_name ;\n\t//\tcallback( stub + \"_sample_odds_ratio\", table(0,0) * table(1,1) / ( table(0,1) * table(1,0) ) ) ;\n\t\n\t\tif( table.row(0).sum() > 0 && table.row(1).sum() > 0 ) {\n\t\t\t// perform the exact test.  For speed reasons this is only done if the chi-square approximation may be inaccurate.\n\t\t\tif( table.rows() == 2 ) {\n\t\t\t\ttry {\n\t\t\t\t\tmetro::FishersExactTest test( table ) ;\n\t\t\t\t\tcallback( stub + \"_exact_pvalue\", test.get_pvalue( metro::FishersExactTest::eTwoSided ) )  ;\n\t\t\t\t}\n\t\t\t\tcatch( std::exception const& e ) {\n\t\t\t\t\tcallback( stub + \"_exact_pvalue\", genfile::MissingValue() ) ;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcallback( stub + \"_exact_pvalue\", genfile::MissingValue() ) ;\n\t\t\t}\n\t\t\t{\n\t\t\t\tmetro::likelihood::Multinomial< double, Eigen::VectorXd, Eigen::MatrixXd > null_model( table.colwise().sum() ) ;\n\t\t\t\tnull_model.evaluate_at( null_model.get_MLE() ) ;\n\t\t\t\tmetro::likelihood::ProductOfMultinomials< double, Eigen::VectorXd, Eigen::MatrixXd > alternative_model( table ) ;\n\t\t\t\talternative_model.evaluate_at( alternative_model.get_MLE() ) ;\n\t\t\t\tdouble likelihood_ratio_statistic = -2.0 * ( null_model.get_value_of_function() - alternative_model.get_value_of_function() ) ;\n\n\t\t\t\tif( likelihood_ratio_statistic != likelihood_ratio_statistic || likelihood_ratio_statistic < 0.0 ) {\n\t\t\t\t\tlikelihood_ratio_statistic = std::numeric_limits< double >::quiet_NaN() ;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tboost::math::chi_squared_distribution< double > chi_squared( table.rows() - 1 ) ;\n\n\t\t\t\t\tdouble p_value = boost::math::cdf(\n\t\t\t\t\t\tboost::math::complement(\n\t\t\t\t\t\t\tchi_squared,\n\t\t\t\t\t\t\tlikelihood_ratio_statistic\n\t\t\t\t\t\t)\n\t\t\t\t\t) ;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\tcallback( stub + \"_lrt_pvalue\", p_value ) ;\n\t\t\t\t\tcallback( stub + \"_lrt_df\", genfile::VariantEntry::Integer( table.rows() - 1 )) ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::string DifferentialMissingnessComputation::get_summary( std::string const& prefix, std::size_t column_width ) const {\n\t\treturn prefix + \"DifferentialMissingnessComputation\" ;\n\t}\n}\n", "meta": {"hexsha": "db88dca9d75f319d6255d47aea7c44a153dc53e0", "size": 5129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/SNPSummaryComponent/src/DifferentialMissingnessComputation.cpp", "max_stars_repo_name": "gavinband/qctool", "max_stars_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "components/SNPSummaryComponent/src/DifferentialMissingnessComputation.cpp", "max_issues_repo_name": "gavinband/qctool", "max_issues_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "components/SNPSummaryComponent/src/DifferentialMissingnessComputation.cpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.032, "max_line_length": 205, "alphanum_fraction": 0.6833690778, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4165895413352822}}
{"text": "// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"paddle/phi/kernels/qr_kernel.h\"\n\n#include <Eigen/Dense>\n\n#include \"paddle/phi/backends/cpu/cpu_context.h\"\n#include \"paddle/phi/core/kernel_registry.h\"\n#include \"paddle/phi/kernels/funcs/complex_functors.h\"\n#include \"paddle/phi/kernels/funcs/parse_qr_mode.h\"\n\nnamespace phi {\n\ntemplate <typename T, typename Context>\nvoid QrKernel(const Context& ctx,\n              const DenseTensor& x,\n              const std::string& mode,\n              DenseTensor* q,\n              DenseTensor* r) {\n  bool compute_q;\n  bool reduced_mode;\n  std::tie(compute_q, reduced_mode) = phi::funcs::ParseQrMode(mode);\n  auto numel = x.numel();\n  PADDLE_ENFORCE_GT(\n      numel, 0, errors::PreconditionNotMet(\"The input of QR is empty.\"));\n  auto x_dims = x.dims();\n  int x_rank = x_dims.size();\n  int m = x_dims[x_rank - 2];\n  int n = x_dims[x_rank - 1];\n  int min_mn = std::min(m, n);\n  int k = reduced_mode ? min_mn : m;\n  int batch_size = numel / (m * n);\n  int x_stride = m * n;\n  int q_stride = m * k;\n  int r_stride = k * n;\n  auto* x_data = x.data<phi::dtype::Real<T>>();\n  T* q_data = nullptr;\n  if (compute_q) {\n    q_data = ctx.template Alloc<phi::dtype::Real<T>>(\n        q, batch_size * m * k * sizeof(phi::dtype::Real<T>));\n  }\n  auto* r_data = ctx.template Alloc<phi::dtype::Real<T>>(\n      r, batch_size * k * n * sizeof(phi::dtype::Real<T>));\n\n  // Implement QR by calling Eigen\n  for (int i = 0; i < batch_size; ++i) {\n    const T* x_matrix_ptr = x_data + i * x_stride;\n    T* r_matrix_ptr = r_data + i * r_stride;\n    using EigenDynamicMatrix =\n        Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n    auto x_matrix = Eigen::Map<const EigenDynamicMatrix>(x_matrix_ptr, m, n);\n    Eigen::HouseholderQR<EigenDynamicMatrix> qr(x_matrix);\n    if (reduced_mode) {\n      auto qr_top_matrix = qr.matrixQR().block(0, 0, min_mn, n);\n      auto r_matrix_view =\n          qr_top_matrix.template triangularView<Eigen::Upper>();\n      auto r_matrix = EigenDynamicMatrix(r_matrix_view);\n      memcpy(r_matrix_ptr, r_matrix.data(), r_matrix.size() * sizeof(T));\n    } else {\n      auto r_matrix_view =\n          qr.matrixQR().template triangularView<Eigen::Upper>();\n      auto r_matrix = EigenDynamicMatrix(r_matrix_view);\n      memcpy(r_matrix_ptr, r_matrix.data(), r_matrix.size() * sizeof(T));\n    }\n\n    if (compute_q) {\n      T* q_matrix_ptr = q_data + i * q_stride;\n      if (reduced_mode) {\n        auto q_matrix =\n            qr.householderQ() * EigenDynamicMatrix::Identity(m, min_mn);\n        q_matrix.transposeInPlace();\n        memcpy(q_matrix_ptr, q_matrix.data(), q_matrix.size() * sizeof(T));\n      } else {\n        auto q_matrix = qr.householderQ() * EigenDynamicMatrix::Identity(m, m);\n        q_matrix.transposeInPlace();\n        memcpy(q_matrix_ptr, q_matrix.data(), q_matrix.size() * sizeof(T));\n      }\n    }\n  }\n}\n\n}  // namespace phi\n\nPD_REGISTER_KERNEL(qr, CPU, ALL_LAYOUT, phi::QrKernel, float, double) {}\n", "meta": {"hexsha": "6a5551d95571b272935e33b8f9a03d30030ca9b5", "size": 3568, "ext": "cc", "lang": "C++", "max_stars_repo_path": "paddle/phi/kernels/cpu/qr_kernel.cc", "max_stars_repo_name": "L-Net-1992/Paddle", "max_stars_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-08-29T07:43:26.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-29T07:51:24.000Z", "max_issues_repo_path": "paddle/phi/kernels/cpu/qr_kernel.cc", "max_issues_repo_name": "L-Net-1992/Paddle", "max_issues_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paddle/phi/kernels/cpu/qr_kernel.cc", "max_forks_repo_name": "L-Net-1992/Paddle", "max_forks_repo_head_hexsha": "4d0ca02ba56760b456f3d4b42a538555b9b6c307", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-24T11:23:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T11:23:36.000Z", "avg_line_length": 36.7835051546, "max_line_length": 79, "alphanum_fraction": 0.6597533632, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389817407016, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4165895350317428}}
{"text": "#ifndef YQVMC_CI_BINDER_HPP\n#define YQVMC_CI_BINDER_HPP\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/moment.hpp>\n\nnamespace yqvmc { namespace ci {\n  class BinderCumulant {\n  public:\n    BinderCumulant() {}\n    typedef double result_type;\n\n    template <typename C>\n    void measure(const C& conf, std::size_t stamp) {\n      double m = 0.;\n      for (bool spin : conf)\n        m += spin ? +1. : -1.;\n      m_acc(m);\n    }\n\n    result_type result() {\n      double m4 = boost::accumulators::moment<4>(m_acc);\n      double m2 = boost::accumulators::moment<2>(m_acc);\n      return 1. - m4/3./m2/m2;\n    }\n\n  private:\n    boost::accumulators::accumulator_set<double,\n      boost::accumulators::stats<\n        boost::accumulators::tag::moment<2>,\n        boost::accumulators::tag::moment<4>\n      >\n    > m_acc;\n  };\n} }\n#endif\n", "meta": {"hexsha": "c85366233fec5bf6c37c046c3d9784028a1a3b48", "size": 915, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/yqvmc/classical_ising/binder.hpp", "max_stars_repo_name": "yangqi137/yqvmc", "max_stars_repo_head_hexsha": "73b7367f6d4b01ea61612ea0888b285c8dac2fad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/yqvmc/classical_ising/binder.hpp", "max_issues_repo_name": "yangqi137/yqvmc", "max_issues_repo_head_hexsha": "73b7367f6d4b01ea61612ea0888b285c8dac2fad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/yqvmc/classical_ising/binder.hpp", "max_forks_repo_name": "yangqi137/yqvmc", "max_forks_repo_head_hexsha": "73b7367f6d4b01ea61612ea0888b285c8dac2fad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0789473684, "max_line_length": 56, "alphanum_fraction": 0.6404371585, "num_tokens": 254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4164636403690688}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2011 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file markovfunctional.hpp\n    \\brief Markov Functional 1 Factor Model\n*/\n\n#ifndef quantlib_markovfunctional_hpp\n#define quantlib_markovfunctional_hpp\n\n#include <iostream>\n#include <iomanip>\n\n#include <boost/timer/timer.hpp>\n\n#include <math.h>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#include <ql/models/model.hpp>\n#include <ql/models/parameter.hpp>\n#include <ql/math/interpolation.hpp>\n#include <ql/math/interpolations/loginterpolation.hpp>\n#include <ql/math/integrals/gaussianquadratures.hpp>\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/solvers1D/brent.hpp>\n#include <ql/math/errorfunction.hpp>\n#include <ql/indexes/iborindex.hpp>\n#include <ql/indexes/swapindex.hpp>\n#include <ql/instruments/vanillaswap.hpp>\n#include <ql/time/date.hpp>\n#include <ql/time/period.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <ql/termstructures/volatility/swaption/swaptionvolstructure.hpp>\n#include <ql/termstructures/volatility/optionlet/optionletvolatilitystructure.hpp>\n#include <ql/termstructures/volatility/smilesection.hpp>\n#include <ql/stochasticprocess.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/pricingengines/blackcalculator.hpp>\n#include <ql/utilities/null.hpp>\n\n#include <mfstateprocess.hpp>\n#include <kahalesmilesection.hpp>\n\n\nnamespace QuantLib {\n\n    //! One factor Markov Functional model class.\n    /*! blah blah\n\t\tTODO use voltermstructure's timeFromReference() for std dev calculation of market digitals (or blackVariance()), also in swaption and caplet engine\n\t\t\t however, is this then still consistent with the process x starting at yts's reference date? think about that and make it consistent ...\n    */\n\n    class MarkovFunctional : public TermStructureConsistentModel, public CalibratedModel  {\n\n      public:\n\n\t\tstruct ModelSettings {\n\n\t\t\tModelSettings(const int xGridPoints,const Real xStdDevs,const int gaussHermitePoints,const Real digitalGap,const int arbitrageCheckGridPoints,\n\t\t\t\tconst Real rateCutLeft, const Rate rateCutRight, const Rate upperRateBound, const bool adjustDigitals, const bool forceExactYtsFit, const int digitalInterpolationDegree):\n\n\t\t\t\t\txGridPoints_(xGridPoints), xStdDevs_(xStdDevs), gaussHermitePoints_(gaussHermitePoints), digitalGap_(digitalGap),\n\t\t\t\t\tarbitrageCheckGridPoints_(arbitrageCheckGridPoints), rateCutLeft_(rateCutLeft), rateCutRight_(rateCutRight),\n\t\t\t\t\tupperRateBound_(upperRateBound), adjustDigitals_(adjustDigitals), forceExactYtsFit_(forceExactYtsFit), digitalInterpolationDegree_(digitalInterpolationDegree) {}\n\t\t\t\n\t\t\tvoid validate() const {\n\n\t\t\t\tQL_REQUIRE(xGridPoints_>0,\"At least one grid point (\" << xGridPoints_ << \") for the state process discretization must be given\");\n\t\t\t\tQL_REQUIRE(xStdDevs_>0.0,\"Multiple of standard deviations covered by state process discretization (\" << xStdDevs_ << \") must be positive\");\n\t\t\t\tQL_REQUIRE(gaussHermitePoints_>0,\"Number of gauss hermite integration points (\" << gaussHermitePoints_ << \") must be positive\");\n\t\t\t\tQL_REQUIRE(digitalGap_>0.0 && rateCutLeft_-digitalGap_/2.0 >=0.0 &&\n\t\t\t\t\trateCutLeft_+digitalGap_/2.0<=rateCutRight_ && rateCutRight_+digitalGap_/2.0 <=upperRateBound_,\n\t\t\t\t\t\"Rate cut left (\" << rateCutLeft_ << \"), digital gap (\" << digitalGap_ << \"), rate cut right (\" << rateCutRight_ << \n\t\t\t\t\t\") and upper rate bound (\" << upperRateBound_ << \") are not consistent\");\n\t\t\t\tQL_REQUIRE(arbitrageCheckGridPoints_>0,\"Number of grid points for arbitrage check (\" << arbitrageCheckGridPoints_ << \") must be positive\");\n\t\t\t\tQL_REQUIRE(digitalInterpolationDegree_>=0 && digitalInterpolationDegree_<=4,\"Polynomial degree for digital payoff interpolation (\" << digitalInterpolationDegree_ <<\") must be between 0 and 4\");\n\n\t\t\t}\n\n\t\t\tconst int xGridPoints_;\n\t\t\tconst Real xStdDevs_;\n\t\t\tconst int gaussHermitePoints_;\n\t\t\tconst Real digitalGap_;\n\t\t\tconst int arbitrageCheckGridPoints_;\n\t\t\tconst Real rateCutLeft_;\n\t\t\tconst Real rateCutRight_;\n\t\t\tconst Real upperRateBound_;\n\t\t\tconst bool adjustDigitals_;\n\t\t\tconst bool forceExactYtsFit_;\n\t\t\tconst int digitalInterpolationDegree_;\n\n\t\t};\n\n\t\tstruct CalibrationPoint {\n\t\t\tbool isCaplet_;\n\t\t\t//Date expiry_;\n\t\t\tPeriod tenor_;\n\t\t\tstd::vector<Date> paymentDates_;\n\t\t\tstd::vector<Real> yearFractions_;\n\t\t\tReal atm_;\n\t\t\tReal annuity_;\n\t\t\tReal afLeftBound_, afRightBound_;\n\t\t\tReal alphaL_,betaL_,alphaR_,betaR_;\n\t\t\tboost::shared_ptr<KahaleSmileSection> smileSection_;\n\t\t};\n\n\t\tstruct ModelOutputs {\n\t\t\tstd::vector<Date> expiries_;\n\t\t\tstd::vector<Period> tenors_;\n\t\t\tstd::vector<Real> afLeftBounds_;\n\t\t\tstd::vector<Real> afRightBounds_;\n\t\t\tstd::vector<Real> adjustmentFactors_;\n\t\t\tstd::vector<Real> digitalsAdjustmentFactors_;\n\t\t};\n\n        MarkovFunctional(const Handle<YieldTermStructure>& termStructure,\n\t\t\t\t\t\tconst Real reversion,\n\t\t\t\t\t\tconst std::vector<Date>& volstepdates,\n\t\t\t\t\t\tconst std::vector<Real>& volatilities,\n\t\t\t\t\t\tconst Handle<SwaptionVolatilityStructure>& swaptionVol,\n\t\t\t\t\t\tconst std::vector<Date>& swaptionExpiries,\n\t\t\t\t\t\tconst std::vector<Period>& swaptionTenors,\n\t\t\t\t\t\tconst boost::shared_ptr<SwapIndex>& swapIndexBase,\n\t\t\t\t\t\tconst int xGridPoints=512, const Real xStdDevs=7.0, const int gaussHermitePoints=32,\n\t\t\t\t\t\tconst Real digitalGap=1E-8, const int arbitrageCheckGridPoints=200, const Real rateCutLeft=0.0001, const Real rateCutRight=1.9000,\n\t\t\t\t\t\tconst Real upperRateBound=2.0, const bool adjustDigitals=false, const bool forceExactYtsFit=false, const int digitalInterpolationDegree=2);\n\n\t\tMarkovFunctional(const Handle<YieldTermStructure>& termStructure,\n\t\t\t\t\t\tconst Real reversion,\n\t\t\t\t\t\tconst std::vector<Date>& volstepdates,\n\t\t\t\t\t\tconst std::vector<Real>& volatilities,\n\t\t\t\t\t\tconst Handle<OptionletVolatilityStructure>& capletVol,\n\t\t\t\t\t\tconst std::vector<Date>& capletExpiries,\n\t\t\t\t\t\tconst boost::shared_ptr<IborIndex>& iborIndex,\n\t\t\t\t\t\tconst int xGridPoints=512, const Real xStdDevs=7.0, const int gaussHermitePoints=32,\n\t\t\t\t\t\tconst Real digitalGap=1E-8, const int arbitrageCheckGridPoints=200, const Real rateCutLeft=0.0001, const Real rateCutRight=1.9000,\n\t\t\t\t\t\tconst Real upperRateBound=2.0, const bool adjustDigitals=false, const bool forceExactYtsFit=false, const int digitalInterpolationDegree=2);\n\n\t\tconst ModelSettings& modelSettings() const { return modelSettings_; }\n\t\tconst ModelOutputs& modelOutputs() const { return modelOutputs_; }\n\n\t\tconst Date& numeraireDate() const { return numeraireDate_; }\n\t\tconst Time& numeraireTime() const { return numeraireTime_; }\n\n\t\tconst boost::shared_ptr<StochasticProcess1D> stateProcess() const { return stateProcess_; }\n\n\t\tReal numeraire(const Time t, const Real x=0.0) const;\n\t\tReal deflatedZerobond(const Time T, const Time t=0.0, const Real x=0.0) const;\n\n\t\tReal zerobond(const Time T, const Time t=0.0, const Real x=0.0) const;\n\t\tReal zerobond(const Date& maturity, const Date& referenceDate = Null<Date>(), const Real x=0.0) const;\n\n\t\tReal zerobondOption(const Option::Type& type, const Date& expiry, const Date& maturity, const Rate strike, const Date& referenceDate = Null<Date>(), const Real x=0.0) const;\n\n\t\tReal forwardRate(const Date& fixing, const Date& referenceDate = Null<Date>(), const Real x=0.0) const;\n\t\tReal swapRate(const Date& fixing, const Period& tenor, const Date& referenceDate = Null<Date>(), const Real x=0.0) const;\n\t\tReal swapAnnuity(const Date& fixing, const Period& tenor, const Date& referenceDate = Null<Date>(), const Real x=0.0) const;\n\n\t\tReal capletPrice(const Option::Type& type, const Date& expiry, const Rate strike, const Date& referenceDate = Null<Date>(), const Real x=0.0) const;\n\t\tReal swaptionPrice(const Option::Type& type, const Date& expiry, const Period& tenor, const Rate strike, const Date& referenceDate = Null<Date>(), const Real x=0.0) const;\n\n      protected:\n        \n\t\tvoid generateArguments();\n\n      private:\n\n\t\tvoid initialize();\n\t    void updateNumeraireTabulation();\n\n\t\tvoid makeSwaptionCalibrationPoint(const Date& expiry, const Period& tenor);\n\t\tvoid makeCapletCalibrationPoint(const Date& expiry);\n\t\t\n\t\tvoid arbitrageFreeStrikeRange(const Date& expiry, CalibrationPoint& p) const;\n\t\tReal marketSwapRate(const Date& expiry, const CalibrationPoint& p, const Real digitalPrice) const;\n\t\tReal marketDigitalPrice(const Date& expiry, const CalibrationPoint& p, const Option::Type& type, const Real strike) const;\n\t\tstatic Real gaussianPolynomialIntegral(const Real a, const Real b, const Real c, const Real d, const Real e, const Real x0, const Real x1);\n\n\t\tModelSettings modelSettings_;\n\t\tModelOutputs modelOutputs_;\n\n\t\tconst bool capletCalibrated_;\n\n\t\tboost::shared_ptr<GaussianQuadrature> gaussHermite_;\n\t\tconst CumulativeNormalDistribution cnd_;\n\n\t\tboost::shared_ptr<IborIndex> ytsLinkedIborIndex_;\n\t\tboost::shared_ptr<StochasticProcess1D> stateProcess_;\n\n\t\tstd::vector<boost::shared_ptr<std::vector<Real>>> numeraireDiscretization_;\n\t\tstd::vector<boost::shared_ptr<Interpolation>> numeraire_;\n\n\t\tParameter reversion_;\n\t\tParameter& sigma_;\n\t\t\n\t\tstd::vector<Date> volstepdates_;\n\t\tstd::vector<Time> volsteptimes_;\n\t\tArray volsteptimesArray_;\t\t\t\t// FIXME this is redundant (copy of volsteptimes_)\n\t\tstd::vector<double> volatilities_;\n\n\t\tDate numeraireDate_;\n\t\tTime numeraireTime_;\n\n\t\tHandle<SwaptionVolatilityStructure> swaptionVol_;\n\t\tHandle<OptionletVolatilityStructure> capletVol_;\n\n\t\tstd::vector<Date> swaptionExpiries_, capletExpiries_;\n\t\tstd::vector<Period> swaptionTenors_;\n\t\tboost::shared_ptr<SwapIndex> swapIndexBase_;\n\t\tboost::shared_ptr<IborIndex> iborIndex_;\n\n\t\t//std::set<CalibrationPoint> calibrationPoints_;\n\t\tstd::map<Date,CalibrationPoint> calibrationPoints_;\n\t\tstd::vector<double> times_;\n\t\tstd::vector<double> y_;\n\n\t\tmutable boost::timer::cpu_timer cpuTimer_,cpuTimer2_;\n\n    };\n\n\t//bool operator<(const MarkovFunctional::CalibrationPoint& a, const MarkovFunctional::CalibrationPoint& b);\n\n}\n\n\n#endif\n\n", "meta": {"hexsha": "a0698269bd84d1b2d4454580097bbbeb9a52d899", "size": 10596, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/preexperimental/markovfunctional_backup.hpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/experimental/preexperimental/markovfunctional_backup.hpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/experimental/preexperimental/markovfunctional_backup.hpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 43.4262295082, "max_line_length": 197, "alphanum_fraction": 0.7612306531, "num_tokens": 2722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4164636403690688}}
{"text": "#include <map>\n#include <queue>\n#include <unordered_map>\n#include <Eigen/Sparse>\n#include <Euclid/Geometry/DEC.h>\n#include <Euclid/Topology/HomologyGenerator.h>\n\nnamespace Euclid\n{\n\nnamespace _impl\n{\n\ntemplate<typename Mesh, typename T>\nvoid build_closedness_matrix(const Mesh& mesh,\n                             std::vector<Eigen::Triplet<T>>& triplets)\n{\n    auto fimap = get(boost::face_index, mesh);\n    auto eimap = get(boost::edge_index, mesh);\n    auto frange = faces(mesh);\n    --frange.second; // the last face is redundant\n    for (auto f : frange) {\n        auto fidx = get(fimap, f);\n        for (auto h : halfedges_around_face(halfedge(f, mesh), mesh)) {\n            auto e = edge(h, mesh);\n            triplets.emplace_back(\n                fidx, get(eimap, e), halfedge_orientation(mesh, h));\n        }\n    }\n}\n\ntemplate<typename Mesh, typename T>\nvoid build_harmonicity_matrix(const Mesh& mesh,\n                              std::vector<Eigen::Triplet<T>>& triplets)\n{\n    auto vimap = get(boost::vertex_index, mesh);\n    auto eimap = get(boost::edge_index, mesh);\n    auto offset = static_cast<int>(num_faces(mesh)) - 1;\n    auto vrange = vertices(mesh);\n    --vrange.second; // the last vertex is redundant\n    for (auto v : vrange) {\n        auto vidx = get(vimap, v);\n        for (auto h : halfedges_around_target(v, mesh)) {\n            auto e = edge(h, mesh);\n            auto w = cotangent_weight(h, mesh);\n            triplets.emplace_back(offset + vidx,\n                                  get(eimap, e),\n                                  halfedge_orientation(mesh, h) * w);\n        }\n    }\n}\n\ntemplate<typename Mesh, typename T>\nvoid build_duality_matrix(const Mesh& mesh,\n                          const VertexChains<Mesh>& basis,\n                          std::vector<Eigen::Triplet<T>>& triplets)\n{\n    auto eimap = get(boost::edge_index, mesh);\n    auto offset = static_cast<int>(num_faces(mesh) + num_vertices(mesh)) - 2;\n    for (size_t i = 0; i < basis.size(); ++i) {\n        for (size_t j = 0; j < basis[i].size(); ++j) {\n            auto vcurrent = basis[i][j];\n            auto vnext = basis[i][(j + 1) % basis[i].size()];\n            auto [h, hfound] = halfedge(vcurrent, vnext, mesh);\n            auto e = edge(h, mesh);\n            triplets.emplace_back(\n                offset + i, get(eimap, e), halfedge_orientation(mesh, h));\n        }\n    }\n}\n\ntemplate<typename Mesh,\n         typename Derived,\n         typename SEM,\n         typename SVM,\n         typename VertexUVMap,\n         typename VertexParameterizedMap>\nvoid integrate_holomorphic_one_forms(\n    const Mesh& mesh,\n    const Eigen::MatrixBase<Derived>& one_forms,\n    CGAL::Seam_mesh<Mesh, SEM, SVM>& seam_mesh,\n    VertexUVMap uvmap,\n    VertexParameterizedMap vpmap)\n{\n    using Seam_mesh = CGAL::Seam_mesh<Mesh, SEM, SVM>;\n    using Point_2 =\n        typename CGAL::Kernel_traits<typename boost::property_traits<\n            VertexUVMap>::value_type>::Kernel::Point_2;\n    using Vector_2 =\n        typename CGAL::Kernel_traits<typename boost::property_traits<\n            VertexUVMap>::value_type>::Kernel::Vector_2;\n    using vertex_descriptor =\n        typename boost::graph_traits<Seam_mesh>::vertex_descriptor;\n    auto underlying_eimap = get(boost::edge_index, mesh);\n\n    std::queue<vertex_descriptor> queue;\n    auto root = *(vertices(seam_mesh).first);\n    queue.push(root);\n    put(uvmap, root, Point_2(0, 0));\n    put(vpmap, root, true);\n    while (!queue.empty()) {\n        auto v = queue.front();\n        queue.pop();\n        for (auto h : halfedges_around_source(v, seam_mesh)) {\n            auto vv = target(h, seam_mesh);\n            if (!get(vpmap, vv)) {\n                auto underlying_e = edge(h.tmhd, mesh);\n                auto e_idx = get(underlying_eimap, underlying_e);\n                auto uv = get(uvmap, v);\n                auto s = halfedge_orientation(mesh, h.tmhd);\n                uv += s * Vector_2(one_forms(e_idx, 0), one_forms(e_idx, 1));\n                put(uvmap, vv, uv);\n                put(vpmap, vv, true);\n                queue.push(vv);\n            }\n        }\n    }\n}\n\n} // namespace _impl\n\ntemplate<typename Mesh, typename DerivedA, typename DerivedB>\nvoid holomorphic_one_form_basis(const Mesh& mesh,\n                                Eigen::MatrixBase<DerivedA>& primal,\n                                Eigen::MatrixBase<DerivedB>& conjugate)\n{\n    auto basis = greedy_homology_generators(mesh);\n    holomorphic_one_form_basis(mesh, basis, primal, conjugate);\n}\n\ntemplate<typename Mesh, typename DerivedA, typename DerivedB>\nvoid holomorphic_one_form_basis(const Mesh& mesh,\n                                const VertexChains<Mesh>& homology_generators,\n                                Eigen::MatrixBase<DerivedA>& primal,\n                                Eigen::MatrixBase<DerivedB>& conjugate)\n{\n    using Scalar = typename DerivedA::Scalar;\n    using Triplet = Eigen::Triplet<Scalar>;\n    using Triplets = std::vector<Triplet>;\n    using SpMat = Eigen::SparseMatrix<Scalar>;\n    using Vec = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using Mat = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    auto ng = homology_generators.size();\n    auto nv = num_vertices(mesh);\n    auto ne = num_edges(mesh);\n    auto nf = num_faces(mesh);\n    primal.derived().resize(ne, ng);\n\n    // Primal one form basis\n    Triplets triplets;\n    _impl::build_closedness_matrix(mesh, triplets);\n    _impl::build_harmonicity_matrix(mesh, triplets);\n    _impl::build_duality_matrix(mesh, homology_generators, triplets);\n    SpMat lhs(ne, ne);\n    lhs.setFromTriplets(triplets.begin(), triplets.end());\n    Eigen::SparseLU<SpMat> primal_solver;\n    primal_solver.compute(lhs);\n    for (size_t i = 0; i < ng; ++i) {\n        Vec rhs = Vec::Zero(ne);\n        rhs(nv + nf - 2 + i) = 1.0;\n        primal.col(i) = primal_solver.solve(rhs);\n    }\n\n    // Conjugate one form basis\n    Mat W(ng, ng);\n    for (size_t i = 0; i < ng; ++i) {\n        for (size_t j = 0; j < ng; ++j) {\n            Vec wedge;\n            wedge1(mesh, primal.col(i), primal.col(j), wedge);\n            W(i, j) = wedge.sum();\n        }\n    }\n    Mat B(ng, ng);\n    for (size_t i = 0; i < ng; ++i) {\n        for (size_t j = 0; j < ng; ++j) {\n            Vec wedge;\n            star_wedge1(mesh, primal.col(i), primal.col(j), wedge);\n            B(i, j) = wedge.sum();\n        }\n    }\n    Eigen::ColPivHouseholderQR<Mat> conjugate_solver;\n    conjugate_solver.compute(W);\n    Mat L = conjugate_solver.solve(B);\n    conjugate = primal * L;\n}\n\ntemplate<typename Mesh,\n         typename Derived,\n         typename SEM,\n         typename SVM,\n         typename VertexUVMap>\nvoid integrate_holomorphic_one_forms(\n    const Mesh& mesh,\n    const Eigen::MatrixBase<Derived>& one_forms,\n    CGAL::Seam_mesh<Mesh, SEM, SVM>& seam_mesh,\n    VertexUVMap uvmap)\n{\n    using SM = CGAL::Seam_mesh<Mesh, SEM, SVM>;\n    using vd = typename boost::graph_traits<SM>::vertex_descriptor;\n    using PM = std::map<vd, bool>;\n    PM parameterized;\n    boost::associative_property_map<PM> vpmap(parameterized);\n    _impl::integrate_holomorphic_one_forms(\n        mesh, one_forms, seam_mesh, uvmap, vpmap);\n}\n\ntemplate<typename Mesh, typename SEM, typename SVM>\nHolomorphic_one_forms_parameterizer3<Mesh, SEM, SVM>::\n    Holomorphic_one_forms_parameterizer3(const Mesh& mesh)\n    : _underlying_mesh(mesh)\n{\n    holomorphic_one_form_basis(mesh, _primal, _conjugate);\n    Eigen::VectorXd coeffs = Eigen::VectorXd::Zero(_primal.cols());\n    coeffs(0) = 1.0;\n    set_coeffs(coeffs);\n}\n\ntemplate<typename Mesh, typename SEM, typename SVM>\nHolomorphic_one_forms_parameterizer3<Mesh, SEM, SVM>::\n    Holomorphic_one_forms_parameterizer3(\n        const Mesh& mesh,\n        const VertexChains<Mesh>& homology_generators)\n    : _underlying_mesh(mesh)\n{\n    holomorphic_one_form_basis(mesh, homology_generators, _primal, _conjugate);\n    Eigen::VectorXd coeffs = Eigen::VectorXd::Zero(_primal.cols());\n    coeffs(0) = 1.0;\n    set_coeffs(coeffs);\n}\n\ntemplate<typename Mesh, typename SEM, typename SVM>\ntemplate<typename Derived>\nvoid Holomorphic_one_forms_parameterizer3<Mesh, SEM, SVM>::set_coeffs(\n    const Eigen::MatrixBase<Derived>& coeffs)\n{\n    _one_forms.resize(_primal.rows(), 2);\n    _one_forms.col(0) = _primal * coeffs;\n    _one_forms.col(1) = _conjugate * coeffs;\n}\n\ntemplate<typename Mesh, typename SEM, typename SVM>\ntemplate<typename VertexUVMap,\n         typename VertexIndexMap,\n         typename VertexParameterizedMap>\nCGAL::Surface_mesh_parameterization::Error_code\nHolomorphic_one_forms_parameterizer3<Mesh, SEM, SVM>::parameterize(\n    TriangleMesh& mesh,\n    halfedge_descriptor,\n    VertexUVMap uvmap,\n    VertexIndexMap,\n    VertexParameterizedMap vpmap)\n{\n    _impl::integrate_holomorphic_one_forms(\n        _underlying_mesh, _one_forms, mesh, uvmap, vpmap);\n    return CGAL::Surface_mesh_parameterization::OK;\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "eba053c7c43bc36343a8300f94d0d9b5d9f8b28b", "size": 8929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/Parameterization/src/HolomorphicOneForms.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "include/Euclid/Parameterization/src/HolomorphicOneForms.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Euclid/Parameterization/src/HolomorphicOneForms.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 34.4749034749, "max_line_length": 79, "alphanum_fraction": 0.6251539926, "num_tokens": 2240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631542, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4164636403690688}}
{"text": "/**======================================================================================================================================================\n * @brief  Approximate inference Marginalization\n *        /Script to find the amalgamation on CIMs.\n *          i.e Marginalization operation takes a CIM Q S|C , a set of variables X from,\n *            and an initial distribution P over the variables of S. It returns a reduced\n *            CIM of the form: Q S'|C = marg PX ( Q S|C ) where S'=S-X.\n *              The resulting approximation is a linear approximation of the marginal.\n *              Q S'|C (s'1 → s'2|c)≈ ∑ Q S|C (s'1⊕y → s'2⊕y|c) P0 (y|s'1,c)\n * \t\t\n * @version 1.0\n * @author Intern: Bernardin HOUESSOU for LIP6\n * Created on 6 juillet 2015, 17:37\n * File:   main.cpp\n *=====================================================================================================================================================\n*/\n\n//Used and required library(ies)/header(s)/inlcude(s)===============================================================================================================================\n#include <cstdlib>                    //\n#include <armadillo>                 // Armadillo header::armadillo library \n#include <iostream>                 // Console commands ::defines the standard Input/Output stream objects std::cout\n#include <string>                  // String header::defines several functions to manipulate C++ strings \n#include <fstream>                // File commands::defines the Input/Output stream class to operate on files\n#include <vector>                // For vector\n#include <cctype>               // For uppercase & lowercase conForersion\n#include <cstring>             // For  strcopy() and ....\n#include <map>                // Use of Map\n#include \"TabVar.h\"\n#include \"MatrixCIM.h\"       // Calling created header/library \n#include <sstream>\n#include <functional>   // std::minus\n#include <numeric>     // std::accumulate\n//Used namespaces====================================================================================================================================================\nusing namespace std;\nusing namespace arma;\n\n/********************************************************************************************************************************\n LIST OF USEFUL FUNCTIONS\n **/\n/***********************************************************************************************************************************************\nFunction \"countnumberfile()\" to count number of times the file \"lines1.txt\" has been used in the background\n-Specially created for the use in the function \"speciallogs()\n*/\nint countnumberfile()\n{\t\n\t//Needed variables       \n\tofstream outputFile1;\n\tint count1=0;      \t\n\t\t\t\t\n    //checking number of times the file 'lines1.txt' has been used\n\tifstream inputFile1(\"Resources/Temporary/lines1.txt\");\n\tinputFile1 >> count1; \n\tinputFile1.close();\n\tcount1++ ; \t\t\t\n\t\t\n    //Saving count to file 'lines1.txt'\t\n\toutputFile1.open (\"Resources/Temporary/lines1.txt\"); \t\t\t\t\n\toutputFile1 <<count1 << endl;\n\toutputFile1.close();\t\n\t\t\t\t\nreturn count1;\t\n}\n//End of Function \"countsaveddistrotofile()\"**************************************************************************************\n\n/****************************************************************************************************************************************************\nFunction \"speciallogs() to save all printed elements by \"cout<<\" on the screen into a file\n*/\nvoid speciallogs()\n{\t\n        //redirect output of cout to file \"Result/output.txt\t\n\tfreopen(\"Resources/Result/resultlogMarg.txt\", \"app\", stdout );\n\t//Displaying the n_th number before each trial   \n\tstd::cout<<\"|\"<<\"N°\"<<countnumberfile()<<\"|\"<<endl;        \n}\n//End of Function \"speciallogs()\"*********************************************************************************************************************       \t\n\n\n/********************************************************************************************************************************\nFunction \"createemptymfoismmatrix() \" to convert int to string \n*/\nstring int2strconvertor(int n) {\n\tstringstream ss;\n\tss << n;\t\n\treturn ss.str();\n}\n//End of function \"int2strconvertor() \" ******************************************************************************************************\n\n/********************************************************************************************************************************\nFunction \"str2intconvertor() \" to convert string to int\n*/\nint str2intconvertor(std::string str) {\n\t\t\n\treturn atoi( str.c_str() );\n}\n//End of function \"str2intconvertor( ) \" ******************************************************************************************************\n\n\n\n/********************************************************************************************************************************\nFunction \"convert() \" to convert multimaptomap\n*/\n\nms convert(const multimap_tablestring& multimapstring)\n{   \n    ms r;\n    \n    for (multimap_tablestring::const_iterator it = multimapstring.begin(); it !=multimapstring.end(); ++it)\n    {  \n       \n        std::vector<std::string>& s(r[it->first]);        \n        s.push_back(it->second);\n        \n    }   \n\n    return r;\n} \n//End of function \"convertmultimaptomap() \" ******************************************************************************************************\n\n\nms2 convert2(const multimap_tablestring& multimapstring2)\n{   \n    ms2 r;\n    \n    for (multimap_tablestring::const_iterator it = multimapstring2.begin(); it !=multimapstring2.end(); ++it)\n    {  \n       \n        std::set<std::string>& s(r[it->first]);        \n        s.insert(it->second);\n        \n    }   \n\n    return r;\n} \n//End of function \"convertmultimaptomap() \" ******************************************************************************************************\n\n\n\n/*Vector split function to split matrix values only from text file\n */\nStringVector splitvarnbstate(string str, char delimiter) {\n  StringVector internal;\n  stringstream ss(str); // Turn the string into a stream.\n  string tok;\n  string tok2=tok;\n \n  while(getline(ss, tok, delimiter)) \n  {\n        tok=tok2;\n        char delimiter2=';';        \n        while(getline(ss, tok, delimiter2)) {\n           if(getline(ss, tok, delimiter2)) {\n             // std::cout<<tok;\n            internal.push_back(tok);\n           }\n        }\n  } \nreturn internal;\n}\n\n/*Vector split function to split matrix values only from text file\n */\nStringVector splitmatrixvaluesonly11(string str, char delimiter) {\n  StringVector internal;\n  stringstream ss(str); // Turn the string into a stream.\n  string tok;\n  string tok2=tok;\n  while(getline(ss, tok, delimiter)) \n  {\n        tok=tok2;\n        char delimiter2=';';        \n        if(getline(ss, tok, delimiter2)) {\n                    if(getline(ss, tok, delimiter2)) {\n           if(getline(ss, tok, delimiter2)) {\n             // std::cout<<tok;\n            internal.push_back(tok);\n           }\n        }\n        }\n  } \nreturn internal;\n}\n\n\n/*Vector split function to split Variables only from text file\n */\nStringVector splitdistrovariable(string strv, char delimiterv) {\n  StringVector internalv;\n  delimiterv='|';//replace old delimiter by delimiterv\n  stringstream ssv(strv); // Turn the string into a stream.\n  string tokv;\n  string tok2v=tokv; \n  while(getline(ssv, tokv, delimiterv)) \n  {\n        tokv=tok2v;\n        char delimiter2v='+';\n        if(getline(ssv, tokv, delimiter2v)) {\n           if(getline(ssv ,tokv, delimiter2v)) {\n              //std::cout<<tok;\n            internalv.push_back(tokv);\n             }\n        }\n  } \nreturn internalv;\n}\n\n/*Vector split function to split distro Variables from text file\n */\nStringVector splitdistroparents(string str, char delimiter) {\n    \n  StringVector internal;\n  stringstream ss(str); // Turn the string into a stream.\n  string tok;\n  string tok2=tok;\n  delimiter='+';//replacing old delimiter=* to this one \n  while(getline(ss, tok, delimiter)) \n  {\n        tok=tok2;\n        char delimiter2='|';        \n        if(getline(ss, tok, delimiter2)) {\n            delimiter2=';';\n           if(getline(ss, tok, delimiter2))\n              internal.push_back(tok);           \n        }\n  } \nreturn internal;\n}\n\n/*Vector split function to split given distribution P0 values from text file\n */          \nStringVector splitdistrovalues(string str, char delimiter) {\n\n StringVector internal;\n  //char delimiter1=':';\n  stringstream ss(str); // Turn the string into a stream.\n  string tok;\n  string tok2=tok;\n  delimiter='+';\n    while(getline(ss, tok, delimiter)) \n    {\n         tok=tok2;\n         char delimiter2=';';\n         if(getline(ss, tok, delimiter2)) {\n             if(getline(ss, tok, delimiter2))\n                 \n            // std::cout<<tok;\n            internal.push_back(tok);\n   \n         }\n    } \nreturn internal;\n}\n\n\n\n/*Vector split function to split parents variables only from text file\n */\nStringVector splitvarparentsonly1(string str, char delimiter) {\n  StringVector internal;\n  //char delimiter1=':';\n  stringstream ss(str); // Turn the string into a stream.\n  string tok;\n  string tok2=tok;\n    while(getline(ss, tok, delimiter)) \n    {\n         tok=tok2;\n         char delimiter2=';';\n         if(getline(ss, tok, delimiter2)) {\n            // std::cout<<tok;\n            internal.push_back(tok);\n   \n         }\n    } \nreturn internal;\n}\n\n/*Vector split function to split Variables only from text file\n */\nStringVector splitvariable(string strv, char delimiterv) {\n  StringVector internalv;\n  delimiterv=',';//replace old delimiter by delimiterv\n  stringstream ssv(strv); // Turn the string into a stream.\n  string tokv;\n  string tok2v=tokv; \n  while(getline(ssv, tokv, delimiterv)) \n  {\n        tokv=tok2v;\n        char delimiter2v=':';\n        if(getline(ssv, tokv, delimiter2v)) {\n           if(getline(ssv ,tokv, delimiter2v)) {\n              //std::cout<<tok;\n            internalv.push_back(tokv);\n             }\n        }\n  } \nreturn internalv;\n}\n\n/*********************************************************************************************************************************************************************\n * MAIN FUNCTION \n *********************************************************************************************************************************************************************\n */\n\n\nint main(int argc, char** argv) {\n    \n    //Sending result to logfile\n    speciallogs();\n    \n    //load the text file and put it into a single string:\n    std::ifstream in(\"Resources/statespacevar.txt\");\n    std::stringstream buffer;\n    buffer << in.rdbuf();\n    std::string test = buffer.str();\n    //Declaring and initializing my delimiter\n    char delimiter1='|';\n    //Splitting content of file into vector 'varstat' to get state of var\n    StringVector varstate=splitvarnbstate(test, delimiter1);     \n    size_t varstatesize=varstate.size();//size of the vector 'varstat'    \n    map_table mapdesvarstate; \n    map_table::iterator itstate; \n    //\n    string KEY; \n    \n    //Splitting content of file into vector 'sep'\n    StringVector sep= splitmatrixvaluesonly11(test, delimiter1);     \n    size_t aa=sep.size();//size of the vector 'sep'\n    //     \n    StringVector variableinitial=splitvariable(test, delimiter1);   \n    size_t bb=variableinitial.size();//size of the vector 'sep'\n    //\n    StringVector parentsvariable=splitvarparentsonly1(test, delimiter1);   \n    size_t parentsvarsize=parentsvariable.size();//size of the vector 'sep'\n    //\n    StringVector matrixvalues=splitmatrixvaluesonly11(test, delimiter1);   \n    size_t matrixvaluessize=matrixvalues.size();//size of the vector 'sep'\n    //\n    map2string mapvarparstate;            \n    map2string::iterator mp3st;\n    //\n    map_tablelistbig my_map;\n    map_tablelistbig::iterator iterr;\n    int my_mapsize=my_map.size(); \n\n    map_tablelistbig my_map2;\n    map_tablelistbig::iterator iterr2;\n    int my_mapsize2=my_map2.size(); \n    //\n    Biglist biglist;        \n    //\n    std::vector<std::string> VartableIni;\n    biglist.Vartable=VartableIni;   \n    //\n    std::vector<std::string> VarstateIni;\n    biglist.Varstate=VarstateIni;\n    //        \n    std::vector<std::string> ParentstableIni;\n    biglist.Parentstable=ParentstableIni;      \n    //\n    std::vector<std::string> VarMatrixIni;\n    biglist.VarMatrix=VarMatrixIni;\n    //\n    for(size_t i = 0; i < bb; i++){  \n        biglist.Vartable.push_back (variableinitial[i]);        \n        biglist.Varstate.push_back (varstate[i+i]);            \n        biglist.Parentstable.push_back (parentsvariable[i]);        \n        biglist.VarMatrix.push_back (matrixvalues[i]);       \n        std::string Keystring;\n        Keystring=\"  \"+biglist.Vartable.at(i)+\"        \"+\"  \"+biglist.Varstate.at(i)+\" \"+\"       \"+biglist.Parentstable.at(i)+\"         \"+\" \"+biglist.VarMatrix.at(i);\n        my_map.insert( std::pair<int,std::string > (i,Keystring));\n    } \n            //Display content of map initial\n           // showmate(\" \", my_map);\n          //Delete element at position i and display content of map after deletion\n         // deletemapelement(0, my_map);\n   \n        //Splitting content of file into vector 'sep'\n        StringVector septest= splitvariable(test, delimiter1);     \n        size_t aatest=septest.size();//size of the vector 'sep'\n\n        map_tablestring mapdesvarstring; \n        map_tablestring::iterator itestring;         \n\n        mapdesvarstring[septest[0]]=varstate[0]; \n        \n    for (itestring=mapdesvarstring.begin(); itestring!=mapdesvarstring.end(); ++itestring) {   \n        for(size_t i = 1; i <aatest; i++){  \n            KEY=septest[i];\n            std::pair<map_tablestring::iterator,bool> retstring;\n            retstring = mapdesvarstring.insert ( std::pair<std::string,std::string >(KEY,varstate[i+i]) ); \n        } \n    }     \n        //Creation of stringvector to handle variable,state and ...\n        StringVector varok1;\n        StringVector varok1state;\n        StringVector savedoldvarok1;\n\n        for (itestring=mapdesvarstring.begin();itestring!=mapdesvarstring.end(); ++itestring){\n            varok1.push_back(itestring->first);\n            savedoldvarok1.push_back(itestring->first);\n            varok1state.push_back(itestring->second); \n            std::reverse(varok1state.begin(),varok1state.end());    \n        }\n        //cout << \"Map size \" << mapdesvarstring.size() << endl; \n        multimap_tablestring multimapstring;\n        multimap_tablestring::iterator multiitestring; \n        StringVector varandapparitioninmap;               \n         \n          for(size_t j = 0; j <bb; j++)          \n              multimapstring.insert(std::pair<const char* const,std::string>(variableinitial[j].c_str(), parentsvariable[j]));          \n                   \n            for(size_t j = 0; j <varok1.size(); j++)  {  \n               varandapparitioninmap.push_back(int2strconvertor(multimapstring.count(varok1[j].c_str())));\n            }\n        \n        StringVector reversevarok1;  \n        StringVector reversevarandapparitioninmap; \n        //std::cout << \"****************************************\"<<endl;   \n        //std::cout << \"Number of elements with key: \"<<endl;   \n        //for(size_t j = 0; j <varandapparitioninmap.size(); j++)\n        //cout<<\"\"<<varandapparitioninmap[j]<<endl<<endl; \n        std::reverse(varok1.begin(),varok1.end());\n        std::reverse(varandapparitioninmap.begin(),varandapparitioninmap.end());\n\n        for (std::vector<std::string>::iterator ite=varok1.begin(); ite!=varok1.end(); ++ite)\n              reversevarok1.push_back(*ite);          \n        for (std::vector<std::string>::iterator it=varandapparitioninmap.begin(); it!=varandapparitioninmap.end(); ++it) \n             reversevarandapparitioninmap.push_back(*it);\n         /*\n                 for(size_t j = 0; j <reversevarok1.size(); j++){  \n                      cout<<\"\"<<reversevarok1[j]<<\" : \"<<reversevarandapparitioninmap[j]<<endl<<endl; \n                }\n         */\n\n        for(size_t j = 0; j <varok1.size(); j++)  {  \n\n         varandapparitioninmap.push_back(int2strconvertor(multimapstring.count(varok1[j].c_str())));\n        }\n                             \n        //calling function to convert multimap to map\n        ms s(convert(multimapstring));        \n        \n        //declaration of an int vector to get the offset or \"pas\" value of a special variable for later use  \n        intVector offsetorpas;  \n        \n          for(size_t i = 0; i < mapdesvarstring.size(); i++)\n         {  \n            int offsetovar;\n            int wght1var=1;\n            if(i==0)\n            {\n              offsetovar=1;\n              //cout<<\"--Offset or Weight of Variable: \"<<i+1<<\" -- \"<<varok1.at(i)<<\" = \"<<offsetovar<<endl; \n              offsetorpas.push_back(offsetovar); \n            }\n            //Determination of the different offset basing on the number of state of each variable\n            if(i!=0){\n                //convert string to integer\n                int stateprevious;\n                stateprevious=atoi( varok1state.at(i-1).c_str() );  \n                //cout<<stateprevious<<endl;\n                if(i==1){\n                    offsetovar=1;                     \n                    offsetovar=offsetovar * stateprevious;\n                    offsetorpas.push_back(offsetovar); \n                }                 \n                if(i!=1){                        \n                offsetovar= offsetovar * stateprevious;\n                offsetorpas.push_back(offsetovar); \n                } \n             //cout<<\"--Offset or Weight of Variable: \"<<i+1<<\" -- \"<<varok1.at(i)<<\" = \"<<offsetovar<<endl;  \n            }\n            //cout<<varok1state.at(i)<<endl<<endl;\n         }          \n         \n/*****************************************************************************************************************************************************/\n                //STATING CREATING CIM MATRIXES AND USING THEIR VALUES FOR THE JIM MATRIX\n                int nbcimmatrix=bb;int matrixnbrows=2;int nbvariable=mapdesvarstring.size();\n\t      \n                //intVector valuediagonal;\n                doubleVector matvalueeach; \n                std::string indexmat;\t\n                std::string matvalue;\n                string fmatrixname;\n                mat matrixname;\n\t\tfor (int i=0;i<nbcimmatrix;i++) \n                {   //cout<<matrixvalues[i]<<endl;\n                    indexmat=int2strconvertor(i);\t\t\n                    //string fmatrixname=\"Q\"+indexmat;\n                    fmatrixname=\"Q\"+biglist.Vartable.at(i)+\"|\"+biglist.Parentstable.at(i);\n                    string fulltrixfilename=\"Resources/Matrices/CIMs/\"+ fmatrixname +\".txt\";\n                    matrixname.resize(matrixnbrows,matrixnbrows); // change the size of matrixname atomatically(data is not preserved)\n                    //matrixname.zeros();//set all elements to Zeros \n                    matrixname=matrixvalues[i];\n                    matrixname.save(fulltrixfilename,csv_ascii);\n                    //matrixname.print(fulltrixfilename);\n                     //cout << fmatrixname<<\".n_rows: \" << matrixname.n_rows << endl;  // .n_rows and .n_cols are read only\n                    //cout << fmatrixname<< \".n_cols: \" << matrixname.n_cols << endl;\n                    //get each matrix value and print them                            \n                     //cout<<fmatrixname<<endl;\n                     int nbdelements=matrixname.size();\n                     for(int i=0;i<=nbdelements-1;i++){\n                        indexmat=int2strconvertor(i);\n                        matvalue=\"val \"+indexmat;    \n                        //cout<< matvalue<<\": \"<<matrixname.at(i)<<endl;\n                        matvalueeach.push_back(matrixname.at(i));\n                     }\n\t\t}           \n                   // std::cout <<endl; //JUMP LINE\t\n                    int cimmatrow=pow(nbvariable, 2);\n                    mat JIM;string varall;string fjimmatname;string fulljimtrixname;\n                    fjimmatname=\"Q_JIM\";\n                    fulljimtrixname=\"Resources/Result/\"+ fjimmatname +\".txt\";\n                    JIM.resize(cimmatrow,cimmatrow);                        \n                    int matvalueeachsize=matvalueeach.size(); \n\n                    \n /*                    cout<<\"Vector containing all the elements of the CIM matrixes:\"<<endl;\n                     for (int n=0;n<matvalueeachsize;n++){\n                     cout<<matvalueeach[n]<<\"; \";\n                     }*/\n                                             \n                    //Convert String vector to int vector\n                    intVector convstr2intstate;\n                    for (int i=0;i<mapdesvarstring.size();i++){ \n                    convstr2intstate.push_back(atoi(varok1state[i].c_str()));\n                    }\n                    //Produit cartésien des états des variables ---  line=Prod*card(Var) orπ*card(Var)       \n                    //ostream_iterator< int > output( cout, \" \" );\n                    //cout << \"Contenu du vecteur: \";\n                    //copy( convstr2intstate.begin(), convstr2intstate.end(), output );\n                    //cout<<\"Produit Cartésien des variables:π*card(Var): \"<< accumulate (convstr2intstate.begin(), convstr2intstate.end(),1,multiplies<int>())<< endl;             \n                    int lineprodcarte=accumulate (convstr2intstate.begin(), convstr2intstate.end(),1,multiplies<int>());\n                    //cout <<lineprodcarte <<endl;\n                     \n                    int offsetoupas;\n                    for (int i=0;i<mapdesvarstring.size();i++) \n                    {  \n                       offsetoupas=offsetorpas[i];\n                       //cout<<\"--Offset or Weight of Variable: \"<<varok1.at(i)<<\" is:\"<<offsetoupas <<\" with state: \"<<varok1state[i]<<endl;\n\n                    }\n                     cout<<\"***************************************************\"<<endl;     \n                    int offsetpassize=offsetorpas.size(); \n                    for (int init=0;init<offsetpassize;init++) \n                    {                             \n                        offsetorpas[init];\n                    }\n                    \n                   ///Initializing some values for the JIM \n                    //WORKFORALL MATRIX\n                    JIM.at(0,1)=matvalueeach[1];//1 ->1 ->0,1\n                    JIM.at(1,0)=matvalueeach[2];//1 ->1 ->1,0\n\n                     int newvaluerow;\n                     int newvaluecol;\n                     int nullvalue=0;\n                     for (int l=0;l<cimmatrow;l++){\n                     int newrowcolsize=sqrt(cimmatrow);\n          \n                     //Starting distribution of CIM value to JIM   \n                     for (int at=1;at<newrowcolsize;at++){      \n\n                         int normalsize=my_map.size();\n                         int nonnormalsize=mapdesvarstring.size();\n                         int squaredenormal=sqrt(normalsize);\n                         if(normalsize%2!=0){\n                            newvaluerow=JIM.at(at+1,0)=matvalueeach[matvalueeachsize-6];//10->8 ->2,0 \n                            newvaluecol=JIM.at(at+1,l)=matvalueeach[matvalueeachsize-11];//5 ->11 ->2,3\n                            newvaluecol=JIM.at(at+2,at)=matvalueeach[matvalueeachsize-2];//14->13->3,1\n                            newvaluecol=JIM.at(at+2,at+1)=matvalueeach[matvalueeachsize-10];//6 ->14->3,2\n                         }\n                         else\n                         {\n                            newvaluerow=JIM.at(at,0)=matvalueeach[matvalueeachsize-14];//2 ->4 ->1,0\n                            newvaluerow=JIM.at(at+1,0)=matvalueeach[matvalueeachsize-6];//10->8 ->2,0 \n                            newvaluecol=JIM.at(at+1,l)=matvalueeach[matvalueeachsize-11];//5 ->11 ->2,3\n                            newvaluecol=JIM.at(at+2,at)=matvalueeach[matvalueeachsize-2];//14->13->3,1\n                            newvaluecol=JIM.at(at+2,at+1)=matvalueeach[matvalueeachsize-10];//6 ->14->3,2\n                        }  \n                     } \n                        //cout<<\"**************************************\"<<endl; \n                        for (int c=0;c<cimmatrow;c++){                            \n                            for (int at=1;at<newrowcolsize;at++){                            \n                                newvaluerow=JIM.at(0,at)=matvalueeach[at];//1 ->1 ->0,1\n                                newvaluerow=JIM.at(0,at+1)=matvalueeach[matvalueeachsize-7];//9  ->2 ->0,2 \n                                newvaluecol=JIM.at(at,c+1)=matvalueeach[matvalueeachsize-3];//13 ->7 ->1,3\n                            } \n                        }    \n                    }  \n                        //getting anti or opposite of the main diagonal of the JIM matrix \n                        vec newoppdiagonalval= diagvec(fliplr(JIM));\n                        vec newoppdiagonalval1= newoppdiagonalval.zeros();\n                        mat newJIM;\n                        mat revnewJIM;\n                        newJIM=fliplr(JIM);\n                        newJIM.diag().zeros();\n                        revnewJIM=fliplr(newJIM);                           \n                        //revnewJIM.print(\"JIM after oppo diagonal values set to 0\");\n                        //newoppdiagonalval.print(\"newoppdiagonalval\");\n                        JIM=revnewJIM;          \n                        \n                        //calculate -end diagonal value\n                        // Write the diagonal of the matrix when i = j                      \n                        for (int i=0;i<cimmatrow;i++)\n                        {\n                            double sumij=0;\n                            //display table                            \n                            for (int j=0;j<cimmatrow;j++)\n                                if (i != j){\t\t\t\t\n                                    sumij=sumij+ JIM(i,j);\n                                                               \n                            }\n                            //set all JIM(rows,rows) equal to sumij \n                           JIM(i,i)= -sumij;                        \n                        }\n                       \n                        JIM.print(fulljimtrixname);                        \n\t\t\tJIM.save(fulljimtrixname,csv_ascii);\n                        std::cout <<endl; //JUMP LINE\t\t\n                        cout<<\"***************************************************\"<<endl;  \n                        \n /*****************************************************************************************************************************************************/                                              \n/////STARTING MARGINALIZATION OF JIM                    \n    //Splitting distribution contents for marginalization from file into differents vectors \n    char delimiterdistro='*'; \n    StringVector distrovar=splitdistrovariable(test, delimiterdistro);  \n    StringVector distrovarparents=splitdistroparents(test, delimiterdistro);  \n    StringVector distroval=splitdistrovalues(test, delimiterdistro);  \n    //Getting sise of the different vectors\n    size_t distrovarsize=distrovar.size();//size of the vector 'distrovar'\n    size_t distrovarparsize=distrovarparents.size();//size of the vector 'distrovarparents'\n    size_t distrovalsize=distroval.size();//size of the vector 'distroval'\n    \n    //Printing their content\n    \n/*  for(auto i :distrovar)      cout<<\"VALUE OF distrovariables: \"<<i <<endl; \n    for(auto j :distrovarparents)      cout<<\"VALUE OF distrovarparents: \"<<j <<endl;   \n    for(auto k :distroval)      cout<<\"VALUE OF distrovalues: \"<<k <<endl;   \n */  \n    \n   //STATING CREATING Given Distribution matrices files AND USING THEIR VALUES TO get another MATRIX and marg...\n    //Initialization and creation of the required variables\n    int nbdistribution=distrovarsize;int distrorows=1;int distrocols=2;\t      \n    doubleVector distrovalueeach; \n    std::string indexdistro;\t\n    std::string distrovalue;\n    string fdistroname;\n    rowvec distro;                \n    \n    //starting of loopfor the creation\n    for (int i=0;i<nbdistribution;i++) \n    {       \n        //cout<<matrixvalues[i]<<endl;\n    indexdistro=int2strconvertor(i);\t\t\n    fdistroname=distrovar.at(i)+\"|\"+distrovarparents.at(i);\n    string fulltrixfilename=\"Resources/Matrices/Distribution/\"+ fdistroname +\".txt\";\n    distro.resize(distrorows,distrocols); // change the size of matrixname atomatically(data is not preserved)\n    //matrixname.zeros();//set all elements to Zeros \n    distro=distroval[i];\n    distro.save(fulltrixfilename,csv_ascii);\n    distro.print(fulltrixfilename);\n    std::cout <<endl; //JUMP LINE\n/*  cout << fdistroname<<\".n_rows: \" << distro.n_rows << endl;  // .n_rows and .n_cols are read only\n    cout << fdistroname<< \".n_cols: \" << distro.n_cols << endl;\n \n    //get each matrix value and print them                            \n    cout<<fdistroname<<endl;\n */\n    //Getting value of each distribution depending of the varaible\n    int nbdelements=distro.size();\n    //printing and stroring into vector those distribution \n    for(int i=0;i<=nbdelements-1;i++) {\n        indexdistro=int2strconvertor(i);\n//        distrovalue=\"val \"+indexdistro;    \n//        cout<< distrovalue<<\": \"<<distro.at(i)<<endl;\n        distrovalueeach.push_back(distro.at(i));                                                                                             \n        }                        \n    }                     \n                        \n///This part need to be modify in order to have an automatic assigment of the values of the different distro                        \n    ///creating row vectors for the different distrovalues\n    rowvec p01,p02,p03;                              \n    //                            \n    p01=distroval.at(0);                       \n    p02=distroval.at(1); \n    p03=distroval.at(2);  \n\n    //Concatening or joining distributions withparents\"                            \n    mat distoprodcombi=join_horiz(p02.t(),p03.t());\n    distoprodcombi.t();//transpose of...\n    distoprodcombi.print(\"Concatenate distributions with parents\\n\");                            \n    distoprodcombi.each_row() %= p01;   // p01 distri without parents \n    mat P0avt=distoprodcombi;\n    P0avt.print(\"\\nMatrix-before colonns elements sum\\n\"); \n    mat p0 = sum(distoprodcombi,1);\n    mat recupP0avt=P0avt;\n    //recupP0zavt.print(\"P0zavt recup\");\n    p0.print(\"\\nMatrix-after colonns elements sum\\n\");    \n\n    \n    //dividing each row element by the appropraite row element of p0 \n    size_t divr=0;//initializing divr\n    while( divr<p0.size()){\t\n         (P0avt.rows(divr,divr) ) /=p0[divr];\n         divr++;\n    }\n    mat res=P0avt ;\n    //res.print(\"\\n res\\n\");\n    cout<<\"\\n**************************************\"<<endl;  \n  ///Get necessary values from CIM of JIM for margin calculation\n    //Calcul of differents values to put in each row using operator * to perform element multiplication,   \n    res.at(0,0) *=matvalueeach[5];//3 // \n    res.at(0,1) *=matvalueeach[9];//5\n    res.at(1,0) *=matvalueeach[6];//15\n    res.at(1,1) *=matvalueeach[10];//4\n    //addition each elemt of a row an put it in a matrix of sise 2*1 of name res\n    res = sum(res,1); \n    //Concatening or joining distributions res to obtain expected result                           \n    res=join_horiz(res,res);\n    \n    //\n    mat marg=res;    \n    int P0varrowcol=distro.size();\n    string combidistromatname;string fullcombidistroname;\n    combidistromatname=\"Marg P0\";\n    fullcombidistroname=\"Resources/Result/\"+ combidistromatname +\".txt\";\n    marg.resize(P0varrowcol,P0varrowcol);   \n    \n    // Write the diagonal of the matrix when i = j                      \n    for (int i=0;i<P0varrowcol;i++)\n    {\n        double sumij=0;\n        double sumji=0; \n        //display table                            \n        for (int j=0;j<P0varrowcol;j++)\n            if (i != j){\t\t\t\t\n                sumij=sumij+ marg(i,j);\n                sumji=sumij+ marg(j,i);                                                                     \n        }\n        //set all JIM(rows,rows) equal to sumij \n       marg(i,i)= -sumij;                                               \n       \n    }\n    //DISPLAYING MARGINALIZATION VALUE\n    //marg.print(fullcombidistroname);\n    cout<<\"Result of the Marginalization is: \"<<endl<<endl<<combidistromatname<<\":\"<<endl;\n    cout<<marg<<endl;\n/*    JIM.save(fullcombidistroname,csv_ascii);\n    cout << combidistromatname<<\".n_rows: \" << marg.n_rows << endl;  // .n_rows and .n_cols are read only\n    cout << combidistromatname<< \".n_cols: \"<< marg.n_cols << endl;\n    cout<< combidistromatname<<\" size:\"<<marg.size()<<endl;\n    std::cout <<endl; //JUMP LINE*/\t\t\n    cout<<\"**************************************\"<<endl;  \n\n    std::cout <<endl; //JUMP LINE\n     return 0;\n}\n//END OF MAIN===================================================================================================================================================\n\n", "meta": {"hexsha": "a0c16bfc6adaa0450c320acd541634d37e0a12b1", "size": 33249, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CTBNs/ctbnmarginalization/main.cpp", "max_stars_repo_name": "Bernardinhouessou/Projets_C_plus_plus", "max_stars_repo_head_hexsha": "9808bd2a49365ec314b7577c11a32cd7c16faf84", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CTBNs/ctbnmarginalization/main.cpp", "max_issues_repo_name": "Bernardinhouessou/Projets_C_plus_plus", "max_issues_repo_head_hexsha": "9808bd2a49365ec314b7577c11a32cd7c16faf84", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CTBNs/ctbnmarginalization/main.cpp", "max_forks_repo_name": "Bernardinhouessou/Projets_C_plus_plus", "max_forks_repo_head_hexsha": "9808bd2a49365ec314b7577c11a32cd7c16faf84", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8063241107, "max_line_length": 198, "alphanum_fraction": 0.4972781136, "num_tokens": 7427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4163661004819539}}
{"text": "///////////////////////////////////////////////////////////////////\n//  Copyright Eduardo Quintana 2021\n//  Copyright Janek Kozicki 2021\n//  Copyright Christopher Kormanyos 2021\n//  Distributed under the Boost Software License,\n//  Version 1.0. (See accompanying file LICENSE_1_0.txt\n//  or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_FFT_BSLBACKEND_HPP\n  #define BOOST_MATH_FFT_BSLBACKEND_HPP\n\n  #include <algorithm>\n  #include <cmath>\n  #include <type_traits>\n  #include <boost/math/fft/multiprecision_complex.hpp>\n\n  #include <boost/math/fft/algorithms.hpp>\n  #include <boost/math/fft/real_algorithms.hpp>\n  #include <boost/math/fft/dft_api.hpp>\n\n  namespace boost { namespace math {  namespace fft { \n  \n  namespace detail {\n\n\n  /*\n    Boost DFT backend:\n    It handles RingTypes and it calls the appropriate specialized functions if\n    the type is complex.\n    \n    A type is considered \"complex\" if is_boost_complex::value == true. A user-defined\n    type can become complex by specializing that trait.\n    \n    We have specialized algorithms for complex numbers and general purpose DFT\n    that need the specification of a root of unity.\n    The general purpose DFT work with complex and non-complex types, but its\n    performance and precision could be lower than the specialized complex\n    versions.\n    \n    This interface selects general purpose DFT for non-complex types,\n    and for complex types the default behaviour is to use the specialized\n    complex algorithms, unless the user provides a root of unity 'W', in which case\n    the interface will execute general purpose DFT using W.\n  */\n  template<class RingType, class allocator_t = std::allocator<RingType> >\n  class bsl_backend\n  {\n  public:\n    using value_type     = RingType;\n    using allocator_type = allocator_t;\n    \n  private:\n    enum plan_type { forward_plan , backward_plan};\n    \n    void execute(plan_type plan, const RingType * in, RingType* out)const\n    {\n      const long N = static_cast<long>(size());\n      const int sign = (plan == forward_plan ? 1 : -1);\n      \n      // select the implementation according to the DFT size\n      switch(N)\n      {\n        case 0:\n          return;\n        case 1:\n          out[0]=in[0];\n          return;\n        case 2:\n          detail::complex_dft_2(in,out,sign);\n          return;\n      }\n      \n      if( detail::is_power2(N) )\n      {\n        detail::complex_dft_power2(in,in+N,out,sign);\n      }\n      else if(detail::is_prime(N))\n      {\n        // detail::complex_dft_prime_bruteForce(in,in+N,out,sign);\n        detail::complex_dft_prime_rader(in,in+N,out,sign,alloc);\n      }\n      else\n      {\n        detail::complex_dft_composite(in,in+N,out,sign,alloc);\n      }\n    }\n    \n  public:\n    \n    // the provided root of unity is used instead of exp(-i 2 pi/n)\n    constexpr bsl_backend(std::size_t n, const allocator_type& in_alloc = allocator_type{}):\n        alloc{in_alloc},\n        my_size{n}\n    { \n    }\n\n    ~bsl_backend()\n    {\n    }\n    \n    void resize(std::size_t new_size)\n    {\n      my_size = new_size;\n    }\n    RingType inverse_root(RingType root) const\n    {\n      return detail::power(root,size()-1);\n    }\n    \n    constexpr std::size_t size() const { return my_size; }\n\n    void forward(const RingType* in, RingType* out) const\n    {\n      execute(forward_plan,in,out);   \n    }\n\n    void backward(const RingType* in, RingType* out) const\n    {\n      execute(backward_plan,in,out);   \n    }\n    void dft(const RingType* in, RingType* out, RingType w) const\n    {\n      const long N = static_cast<long>(size());\n      // select the implementation according to the DFT size\n      if( detail::is_power2(N))\n      {\n        detail::dft_power2(in,in+N,out,w);\n      }\n      else\n      {\n        detail::dft_composite(in,in+N,out,w,alloc);\n      }\n    }\n\n  private:\n    allocator_type alloc;\n    std::size_t my_size{};\n  };\n  \n  \n  template<class T, class allocator_t = std::allocator<T> >\n  class bsl_rfft_backend\n  {\n  public:\n    using value_type     = T;\n    using allocator_type = allocator_t;\n    \n    // the provided root of unity is used instead of exp(-i 2 pi/n)\n    constexpr bsl_rfft_backend(std::size_t n, const allocator_type& in_alloc = allocator_type{}):\n        alloc{in_alloc},\n        my_size{n}\n    { \n    }\n\n    ~bsl_rfft_backend()\n    {\n    }\n    \n    void resize(std::size_t new_size)\n    {\n      my_size = new_size;\n    }\n    \n    constexpr std::size_t size() const { return my_size; }\n    constexpr std::size_t unique_complex_size() const { return my_size/2 + 1;}\n\n    void real_to_halfcomplex(const value_type* in, value_type* out) const\n    {\n      const long N = static_cast<long>(size());\n      // select the implementation according to the DFT size\n      switch(N)\n      {\n        case 0:\n          return;\n        case 1:\n          out[0]=in[0];\n          return;\n        case 2:\n          detail::real_dft_2(in,out,1);\n          return;\n      }\n      if( detail::is_power2(N))\n      {\n        detail::real_dft_power2(in,in+N,out,1);\n      }else\n      {\n        detail::real_dft_composite(in,in+N,out,1,alloc);\n      }\n      //if(detail::is_prime(N))\n      //{\n      //  detail::real_dft_prime_rader(in,in+N,out,sign,alloc);\n      //}\n    }\n    void halfcomplex_to_real(const value_type* in, value_type* out) const\n    {\n      const long N = static_cast<long>(size());\n      // select the implementation according to the DFT size\n      switch(N)\n      {\n        case 0:\n          return;\n        case 1:\n          out[0]=in[0];\n          return;\n        case 2:\n          detail::real_dft_2(in,out,1);\n          return;\n      }\n      if( detail::is_power2(N))\n      { \n        detail::real_inverse_dft_power2(in,in+N,out,1);\n      }else  \n      {\n        detail::real_inverse_dft_composite(in,in+N,out,1,alloc);\n      }\n      //if(detail::is_prime(N))\n      //{\n      //  detail::real_inverse_dft_prime_rader(in,in+N,out,sign,alloc);\n      //}\n    }\n\n  private:\n    allocator_type alloc;\n    std::size_t my_size{};\n  };\n  \n  } // namespace detail\n  \n  template<class RingType = std::complex<double>, class Allocator_t = std::allocator<RingType> >\n  using bsl_dft = detail::complex_dft<detail::bsl_backend,RingType,Allocator_t>;\n  \n  template<class T = double, class Allocator_t = std::allocator<T> >\n  using bsl_rdft = detail::real_dft<detail::bsl_rfft_backend,T,Allocator_t>;\n  \n  template<class RingType = std::complex<double>, class Allocator_t = std::allocator<RingType> >\n  using bsl_algebraic_dft = detail::algebraic_dft<detail::bsl_backend,RingType,Allocator_t>;\n  \n  using bsl_transform = transform< bsl_dft<> >;\n  using bsl_algebraic_transform = transform< bsl_algebraic_dft<> >;\n  using bsl_real_transform = transform< bsl_rdft<> >;\n  \n  } } } // namespace boost::math::fft\n\n#endif // BOOST_MATH_FFT_BSLBACKEND_HPP\n", "meta": {"hexsha": "636f16529c89b14ee57c7d162fffa82273eb382c", "size": 6831, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/fft/bsl_backend.hpp", "max_stars_repo_name": "BoostGSoC21/math", "max_stars_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/math/fft/bsl_backend.hpp", "max_issues_repo_name": "BoostGSoC21/math", "max_issues_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 30.0, "max_issues_repo_issues_event_min_datetime": "2021-06-22T12:59:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T09:27:49.000Z", "max_forks_repo_path": "include/boost/math/fft/bsl_backend.hpp", "max_forks_repo_name": "BoostGSoC21/math", "max_forks_repo_head_hexsha": "60051b121de05d7084ae1eb78053a209d06b7860", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T21:15:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T21:15:02.000Z", "avg_line_length": 27.8816326531, "max_line_length": 97, "alphanum_fraction": 0.620992534, "num_tokens": 1766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.41636609309953704}}
{"text": "//Copyright(c) 2016 Shuda Li[lishuda1980@gmail.com]\n//\n//Permission is hereby granted, free of charge, to any person obtaining a copy\n//of this software and associated documentation files(the \"Software\"), to deal\n//in the Software without restriction, including without limitation the rights\n//to use, copy, modify, merge, publish, distribute, sublicense, and / or sell\n//copies of the Software, and to permit persons to whom the Software is\n//furnished to do so, subject to the following conditions :\n//\n//The above copyright notice and this permission notice shall be included in\n//all copies or substantial portions of the Software.\n//\n//THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n//FOR A PARTICULAR PURPOSE AND NON - INFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR\n//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n//SOFTWARE.\n//\n\n#ifndef BTL_Eigen_UTILITY_HEADER\n#define BTL_Eigen_UTILITY_HEADER\n\n//eigen-based helpers\n#include \"OtherUtil.hpp\"\n#include <Eigen/Dense>\n#include <se3.hpp>\n#include <opencv2/core.hpp>\n\nnamespace btl\n{\nnamespace utility\n{\n\nusing namespace Eigen;\nusing namespace Sophus;\nusing namespace btl::utility;\n\ntemplate< class T >\nEigen::Matrix< T, 4, 4 > inver(const Eigen::Matrix< T, 4, 4 >& F_ctw_){\n\tusing namespace Eigen;\n\tMatrix< T, 4, 4 > F_wtc; F_wtc.setIdentity();\n\n\tMatrix< T, 3, 3 > R_trans = F_ctw_.block(0,0,3,3);\n\tMatrix< T, 3, 1 > Cw = F_ctw_.block(0,3,3,1);\n\n\tF_wtc.block(0,0,3,3) = R_trans.transpose();\n\tF_wtc.block(0,3,3,1) = -R_trans*Cw;\n\treturn F_wtc;\n}\n\ntemplate< class T >\nvoid getCwVwFromPrj_Cam2World(const Eigen::Matrix< T, 4, 4 >&  Prj_ctw_,Eigen::Matrix< T, 3, 1 >* pCw_,Eigen::Matrix< T, 3, 1 >* pVw_){\n\t*pCw_ = Prj_ctw_.template block<3,1>(0,3); //4th column is camera centre\n\t*pVw_ = Prj_ctw_.template block<3,1>(0,0); //1st column is viewing direction\n}\n\ntemplate< class T >\nvoid getRTCVfromModelViewGL ( const Eigen::Matrix< T, 4, 4 >&  mMat_, Eigen::Matrix< T, 3, 3 >* pmR_, Eigen::Matrix< T, 3, 1 >* pvT_ )\n{\n    (* pmR_) ( 0, 0 ) =  mMat_ ( 0, 0 );   (* pmR_) ( 0, 1 ) =   mMat_ ( 0, 1 );  (* pmR_) ( 0, 2 ) = mMat_ ( 0, 2 );\n    (* pmR_) ( 1, 0 ) = -mMat_ ( 1, 0 );   (* pmR_) ( 1, 1 ) = - mMat_ ( 1, 1 );  (* pmR_) ( 1, 2 ) = -mMat_ ( 1, 2 );\n    (* pmR_) ( 2, 0 ) = -mMat_ ( 2, 0 );   (* pmR_) ( 2, 1 ) = - mMat_ ( 2, 1 );  (* pmR_) ( 2, 2 ) = -mMat_ ( 2, 2 );\n    \n\t(*pvT_) ( 0 ) = mMat_ ( 0, 3 );\n    (*pvT_) ( 1 ) = -mMat_ ( 1, 3 );\n    (*pvT_) ( 2 ) = -mMat_ ( 2, 3 );\n\n    return;\n}\n\ntemplate< class T >\nEigen::Matrix< T, 4, 4 > setModelViewGLfromPrj(const Eigen::Transform<T, 3, Eigen::Affine> & Prj_)\n{\n\t// column first for pGLMat_[16];\n\t// row first for Matrix3d;\n\t// pGLMat_[ 0] =  mR_(0,0); pGLMat_[ 4] =  mR_(0,1); pGLMat_[ 8] =  mR_(0,2); pGLMat_[12] =  vT_(0);\n\t// pGLMat_[ 1] = -mR_(1,0); pGLMat_[ 5] = -mR_(1,1); pGLMat_[ 9] = -mR_(1,2); pGLMat_[13] = -vT_(1);\n\t// pGLMat_[ 2] = -mR_(2,0); pGLMat_[ 6] = -mR_(2,1); pGLMat_[10] = -mR_(2,2); pGLMat_[14] = -vT_(2);\n\t// pGLMat_[ 3] =  0;        pGLMat_[ 7] =  0;        pGLMat_[11] =  0;        pGLMat_[15] = 1;\n\n\tEigen::Matrix< T , 4, 4 > mMat;\n\tmMat.row( 0 ) =  Prj_.matrix().row( 0 );\n\tmMat.row( 1 ) = -Prj_.matrix().row( 1 );\n\tmMat.row( 2 ) = -Prj_.matrix().row( 2 );\n\tmMat.row( 3 ) =  Prj_.matrix().row( 3 );\n\n\treturn mMat;\n}\n\ntemplate< class T >\nEigen::Matrix< T , 4, 4 > setModelViewGLfromRTCV ( const SO3Group<T>& mR_, const Eigen::Matrix< T, 3, 1 >& vT_ )\n{\n    // column first for pGLMat_[16];\n    // row first for Matrix3d;\n    // pGLMat_[ 0] =  mR_(0,0); pGLMat_[ 4] =  mR_(0,1); pGLMat_[ 8] =  mR_(0,2); pGLMat_[12] =  vT_(0);\n    // pGLMat_[ 1] = -mR_(1,0); pGLMat_[ 5] = -mR_(1,1); pGLMat_[ 9] = -mR_(1,2); pGLMat_[13] = -vT_(1);\n    // pGLMat_[ 2] = -mR_(2,0); pGLMat_[ 6] = -mR_(2,1); pGLMat_[10] = -mR_(2,2); pGLMat_[14] = -vT_(2);\n    // pGLMat_[ 3] =  0;        pGLMat_[ 7] =  0;        pGLMat_[11] =  0;        pGLMat_[15] = 1;\n\n    Eigen::Matrix< T , 4, 4 > mMat;\n    mMat ( 0, 0 ) =  mR_.matrix() ( 0, 0 ); mMat ( 0, 1 ) =  mR_.matrix() ( 0, 1 ); mMat ( 0, 2 ) =  mR_.matrix() ( 0, 2 ); mMat ( 0, 3 ) =  vT_ ( 0 );\n    mMat ( 1, 0 ) = -mR_.matrix() ( 1, 0 ); mMat ( 1, 1 ) = -mR_.matrix() ( 1, 1 ); mMat ( 1, 2 ) = -mR_.matrix() ( 1, 2 ); mMat ( 1, 3 ) = -vT_ ( 1 );\n    mMat ( 2, 0 ) = -mR_.matrix() ( 2, 0 ); mMat ( 2, 1 ) = -mR_.matrix() ( 2, 1 ); mMat ( 2, 2 ) = -mR_.matrix() ( 2, 2 ); mMat ( 2, 3 ) = -vT_ ( 2 );\n    mMat ( 3, 0 ) =  0;            mMat ( 3, 1 ) =  0;            mMat ( 3, 2 ) =  0;            mMat ( 3, 3 ) =  1;\n    \n    return mMat;\n}\n\ntemplate< class T >\nEigen::Matrix< T , 4, 4 > setModelViewGLfromRCCV ( const Eigen::Matrix< T, 3, 3 >& mR_, const Eigen::Matrix< T, 3, 1 >& vC_ )\n{\n\tEigen::Matrix< T, 3,1> eivT = -mR_.transpose()*vC_;\n\treturn setModelViewGLfromRTCV(mR_,vC_);\n}\n\ntemplate< class T1, class T2 >\nvoid unprojectCamera2World ( const int& nX_, const int& nY_, const unsigned short& nD_, const Eigen::Matrix< T1, 3, 3 >& mK_, Eigen::Matrix< T2, 3, 1 >* pVec_ )\n{\n\t//the pixel coordinate is defined w.r.t. opencv camera reference, which is defined as x-right, y-downward and z-forward. It's\n\t//a right hand system.\n\t//when rendering the point using opengl's camera reference which is defined as x-right, y-upward and z-backward. the\n\t//\tglVertex3d ( Pt(0), -Pt(1), -Pt(2) );\n\tif ( nD_ > 400 ) {\n\t\tT2 dZ = nD_ / 1000.; //convert to meter\n\t\tT2 dX = ( nX_ - mK_ ( 0, 2 ) ) / mK_ ( 0, 0 ) * dZ;\n\t\tT2 dY = ( nY_ - mK_ ( 1, 2 ) ) / mK_ ( 1, 1 ) * dZ;\n\t\t( *pVec_ ) << dX + 0.0025, dY, dZ + 0.00499814; // the value is esimated using CCalibrateKinectExtrinsics::calibDepth()\n\t\t// 0.0025 by experience.\n\t}\n\telse {\n\t\t( *pVec_ ) << 0, 0, 0;\n\t}\n}\n\ntemplate< class T >\nvoid projectWorld2Camera ( const Eigen::Matrix< T, 3, 1 >& vPt_, const Eigen::Matrix3d& mK_, Eigen::Matrix< short, 2, 1>* pVec_  )\n{\n\t// this is much faster than the function\n\t// eiv2DPt = mK * vPt; eiv2DPt /= eiv2DPt(2);\n\t( *pVec_ ) ( 0 ) = short ( mK_ ( 0, 0 ) * vPt_ ( 0 ) / vPt_ ( 2 ) + mK_ ( 0, 2 ) + 0.5 );\n\t( *pVec_ ) ( 1 ) = short ( mK_ ( 1, 1 ) * vPt_ ( 1 ) / vPt_ ( 2 ) + mK_ ( 1, 2 ) + 0.5 );\n}\n\ntemplate< class T >\nvoid convertPrj2Rnt(const Eigen::Transform< T, 3, Eigen::Affine >& Prj_, SO3Group< T >* pR_, Eigen::Matrix< T, 3, 1 >* pT_)\n{\n\t*pR_ = SO3Group<T>(Prj_.linear());\n\t*pT_ = Prj_.translation();\n\treturn;\n}\ntemplate< class T >\nEigen::Transform< T, 3, Eigen::Affine > convertRnt2Prj(const SO3Group< T >& R_, const Eigen::Matrix< T, 3, 1 >& T_)\n{\n\tEigen::Transform< T, 3, Eigen::Affine > prj;\n\tprj.setIdentity();\n\tprj.linear() = R_.matrix();\n\tprj.translation() = T_;\n\treturn prj;\n}\ntemplate< class T >\nvoid convertPrjInv2RpnC( const Eigen::Matrix< T, 4, 4 >& Prj_, Eigen::Matrix< T, 3, 3 >* pR_trans_, Eigen::Matrix< T, 3, 1 >* pT_)\n{\n\t*pR_trans_ = Prj_.template block<3,3>(0,0);\n\t*pT_ = Prj_.template block<3,1>(0,3);\n\treturn;\n}\ntemplate< class T >\nEigen::Matrix< T, 4, 4 > convertRpnC2PrjInv(  const Eigen::Matrix< T, 3, 3 >& R_trans_, const Eigen::Matrix< T, 3, 1 >& C_ )\n{\n\tEigen::Matrix< T, 4, 4 > prj;\n\tprj.setIdentity();\n\tprj.template block<3,3>(0,0) = R_trans_;\n\tprj.template block<3,1>(0,3) = C_;\n\treturn prj;\n}\n\ntemplate< class T, int ROW, int COL >\nT matNormL1 ( const Eigen::Matrix< T, ROW, COL >& eimMat1_, const Eigen::Matrix< T, ROW, COL >& eimMat2_ )\n{\n\tEigen::Matrix< T, ROW, COL > eimTmp = eimMat1_ - eimMat2_;\n\tEigen::Matrix< T, ROW, COL > eimAbs = eimTmp.cwiseAbs();\n\treturn (T) eimAbs.sum();\n}\n\ntemplate< class T >\nvoid setSkew( T x_, T y_, T z_, Eigen::Matrix< T, 3,3 >* peimMat_){\n\t*peimMat_ << 0, -z_, y_, z_, 0, -x_, -y_, x_, 0 ;\n}\n\ntemplate< class T >\nvoid setRotMatrixUsingExponentialMap( T x_, T y_, T z_, Eigen::Matrix< T, 3,3 >* peimR_ ){\n\t//http://opencv.itseez.com/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html?highlight=rodrigues#void Rodrigues(InputArray src, OutputArray dst, OutputArray jacobian)\n\tT theta = sqrt( x_*x_ + y_*y_ + z_*z_ );\n\tif(\ttheta < std::numeric_limits<T>::epsilon() ){\n\t\t*peimR_ = Eigen::Matrix< T, 3,3 >::Identity();\n\t\treturn;\n\t}\n\tT sinTheta = sin(theta);\n\tT cosTheta = cos(theta);\n\tEigen::Matrix< T, 3,3 > eimSkew; \n\tsetSkew< T >(x_/theta,y_/theta,z_/theta,&eimSkew);\n\t*peimR_ = Eigen::Matrix< T, 3,3 >::Identity() + eimSkew*sinTheta + eimSkew*eimSkew*(1-cosTheta);\n}\n\n}//utility\n}//btl\n#endif\n", "meta": {"hexsha": "2a213c338c81beca2bfde9e0165f1b8cc39ae533", "size": 8515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "hdr_fusion/common/EigenUtil.hpp", "max_stars_repo_name": "ShudaLi/HDRFusion", "max_stars_repo_head_hexsha": "ab7242cd9b1686900c9bdc525f3f300740672ba0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2017-03-08T03:08:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T23:07:21.000Z", "max_issues_repo_path": "hdr_fusion/common/EigenUtil.hpp", "max_issues_repo_name": "etudemin/HDRFusion", "max_issues_repo_head_hexsha": "71bd48d8f9f49367bbcb58f201a09e182992bcce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hdr_fusion/common/EigenUtil.hpp", "max_forks_repo_name": "etudemin/HDRFusion", "max_forks_repo_head_hexsha": "71bd48d8f9f49367bbcb58f201a09e182992bcce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2017-02-22T12:45:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-22T00:47:16.000Z", "avg_line_length": 40.5476190476, "max_line_length": 183, "alphanum_fraction": 0.6066940693, "num_tokens": 3508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300449389326, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.41636609309953704}}
{"text": "/*\n * Copyright (c) 2013-2018 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef ODE_HPP\n#define ODE_HPP\n\n// ODE\n\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/interval-vector.hpp>\n#include <kv/make-candidate.hpp>\n#include <kv/psa.hpp>\n#include <kv/ode-param.hpp>\n\n#ifndef ODE_FAST\n#define ODE_FAST 1\n#endif\n\n#ifndef ODE_STEP_COMPONENT\n#define ODE_STEP_COMPONENT 0\n#endif\n\n#ifndef ODE_RESTART_RATIO\n#define ODE_RESTART_RATIO 1\n#endif\n\n#ifndef ODE_COEF_MID\n#define ODE_CORF_MID 0\n#endif\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate <class T, class F>\nint\node(F f, ub::vector< interval<T> >& init, const interval<T>& start, interval<T>& end, const ode_param<T> p = ode_param<T>(), ub::vector< psa< interval<T> > >* result_psa = NULL) {\n\tint n = init.size();\n\tint i, j;\n\n\tub::vector< psa< interval<T> > > x, y;\n\tpsa< interval<T> > torg;\n\tpsa< interval<T> > t;\n\n\tub::vector< psa< interval<T> > > z, w;\n\n\tpsa< interval<T> > temp;\n\tT m;\n\tub::vector<T> newton_step;\n\n\tbool flag, resized;\n\n\tinterval<T> deltat;\n\tub::vector< interval<T> > result;\n\n\tT radius, radius_tmp;\n\n\t#if ODE_STEP_COMPONENT == 1\n\tub::vector<T> tolerance(n);\n\t#else\n\tT tolerance;\n\t#endif\n\n\tint n_rad;\n\n\t#if ODE_RESTART_RATIO == 1\n\tT max_ratio;\n\t#endif\n\n\tint ret_val;\n\tinterval<T> end2;\n\tint restart;\n\n\tbool save_mode, save_uh, save_rh;\n\n\t#if ODE_STEP_COMPONENT == 1\n\tfor (i=0; i<n; i++) {\n\t\ttolerance(i) = std::max(T(1.), norm(init(i))) * p.epsilon;\n\t}\n\t#else\n\tm = 1.;\n\tfor (i=0; i<n; i++) {\n\t\tm = std::max(m, norm(init(i)));\n\t}\n\ttolerance = m * p.epsilon;\n\t#endif\n\n\tx = init;\n\ttorg.v.resize(2);\n\ttorg.v(0) = start; torg.v(1) = 1.;\n\n\tsave_mode = psa< interval<T> >::mode();\n\tsave_uh = psa< interval<T> >::use_history();\n\tsave_rh = psa< interval<T> >::record_history();\n\tpsa< interval<T> >::mode() = 1;\n\tpsa< interval<T> >::use_history() = false;\n\tpsa< interval<T> >::record_history() = false;\n\t#if ODE_FAST == 1\n\tpsa< interval<T> >::record_history() = true;\n\tpsa< interval<T> >::history().clear();\n\t#endif\n\tfor (j=0; j<p.order; j++) {\n\t\t#if ODE_FAST == 1\n\t\tif (j == 1) psa< interval<T> >::use_history() = true;\n\t\t#endif\n\t\tt = setorder(torg, j);\n\t\ty = f(x, t);\n\t\tfor (i=0; i<n; i++) {\n\t\t\ty(i) = integrate(y(i));\n\t\t\t// set order preparing for constant function\n\t\t\ty(i) = setorder(y(i), j+1);\n\t\t}\n\t\tx = init + y;\n\t}\n\n\tif (p.autostep) {\n\t\t// use two non-zero coefficients of higher order term\n\t\t#if ODE_STEP_COMPONENT == 1\n\t\tradius = std::numeric_limits<T>::infinity();\n\t\tfor (i=0; i<n; i++) {\n\t\t\tradius_tmp = 0.;\n\t\t\tn_rad = 0;\n\t\t\tfor (j = p.order; j>=1; j--) {\n\t\t\t\t#if ODE_COEF_MID == 1\n\t\t\t\tusing std::abs;\n\t\t\t\tm = abs(mid(x(i).v(j)));\n\t\t\t\t#else\n\t\t\t\tm = norm(x(i).v(j));\n\t\t\t\t#endif\n\t\t\t\tif (m == 0.) continue;\n\t\t\t\tradius_tmp = std::max(radius_tmp, (T)std::pow((double)m, 1./j));\n\t\t\t\tn_rad++;\n\t\t\t\tif (n_rad == 2) break;\n\t\t\t}\n\t\t\tradius = std::min(radius, std::pow((double)(tolerance(i)), 1./p.order) / radius_tmp);\n\t\t}\n\t\t#else // ODE_STEP_COMPONENT\n\t\tradius = 0.;\n\t\tn_rad = 0;\n\t\tfor (j = p.order; j>=1; j--) {\n\t\t\tm = 0.;\n\t\t\tfor (i=0; i<n; i++) {\n\t\t\t\t#if ODE_COEF_MID == 1\n\t\t\t\tusing std::abs;\n\t\t\t\tm = std::max(m, abs(mid(x(i).v(j))));\n\t\t\t\t#else\n\t\t\t\tm = std::max(m, norm(x(i).v(j)));\n\t\t\t\t#endif\n\t\t\t}\n\t\t\tif (m == 0.) continue;\n\t\t\tradius = std::max(radius, (T)std::pow((double)m, 1./j));\n\t\t\tn_rad++;\n\t\t\tif (n_rad == 2) break;\n\t\t}\n\t\tradius = std::pow((double)tolerance, 1./p.order) / radius;\n\t\t#endif // ODE_STEP_COMPONENT\n\t}\n\n\tpsa< interval<T> >::mode() = 2;\n\n\trestart = 0;\n\tresized = false;\n\n\twhile (true) {\n\t\tif (p.autostep) {\n\t\t\tend2 = mid(start + radius);\n\t\t\tif (end2 >= end.lower()) {\n\t\t\t\tend2 = end;\n\t\t\t\tradius = mid(end2 - start);\n\t\t\t\tret_val = 2;\n\t\t\t} else {\n\t\t\t\tret_val = 1;\n\t\t\t}\n\t\t} else {\n\t\t\tend2 = end;\n\t\t\tret_val = 2;\n\t\t}\n\t\tdeltat = end2 - start;\n\n\t\tpsa< interval<T> >::domain() = interval<T>(0., deltat.upper());\n\n\t\tz = x;\n\t\tt = setorder(torg, p.order);\n\n\t\ttry {\n\t\t\tw = f(z, t);\n\t\t}\n\t\tcatch (std::domain_error& e) {\n\t\t\tif (p.autostep && restart < p.restart_max) {\n\t\t\t\tpsa< interval<T> >::use_history() = false;\n\t\t\t\tif (p.verbose == 1) {\n\t\t\t\t\tstd::cout << \"ode: radius changed: \" << radius;\n\t\t\t\t}\n\t\t\t\tradius *= 0.5;\n\t\t\t\tif (p.verbose == 1) {\n\t\t\t\t\tstd::cout << \" -> \" << radius << \"\\n\";\n\t\t\t\t}\n\t\t\t\trestart++;\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tthrow std::domain_error(\"ode: evaluation error\");\n\t\t\t}\n\t\t}\n\n\t\tfor (i=0; i<n; i++) {\n\t\t\ttemp = integrate(w(i));\n\t\t\tw(i) = setorder(temp, p.order);\n\t\t}\n\t\tw = init + w;\n\n\t\tnewton_step.resize(n);\n\t\tfor (i=0; i<n; i++) {\n\t\t\tnewton_step(i) = norm(w(i).v(p.order) - z(i).v(p.order));\n\t\t}\n\t\tmake_candidate(newton_step);\n\t\tfor (i=0; i<n; i++) {\n\t\t\tz(i).v(p.order) += newton_step(i) * interval<T>(-1., 1.);\n\t\t}\n\n\t\tif (p.autostep && ret_val != 2 && resized == false) {\n\t\t\tresized = true;\n\t\t\tm = (std::numeric_limits<T>::min)();\n\t\t\t#if ODE_STEP_COMPONENT == 1\n\t\t\tfor (i=0; i<n; i++) {\n\t\t\t\tm = std::max(m, (rad(eval(z(i), deltat)) - rad(init(i))) / tolerance(i));\n\t\t\t}\n\t\t\t#else\n\t\t\tfor (i=0; i<n; i++) {\n\t\t\t\tm = std::max(m, rad(eval(z(i), deltat)) - rad(init(i)));\n\t\t\t}\n\t\t\tm = m / tolerance;\n\t\t\t#endif\n\t\t\tradius_tmp = radius / std::pow((double)m, 1. / p.order);\n\t\t\tif (radius_tmp >= radius && restart > 0) {\n\t\t\t\t// do nothing, not continue\n\t\t\t} else {\n\t\t\t\tradius = radius_tmp;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tw = f(z, t);\n\t\tfor (i=0; i<n; i++) {\n\t\t\ttemp = integrate(w(i));\n\t\t\tw(i) = setorder(temp, p.order);\n\t\t}\n\t\tw = init + w;\n\n\t\tflag = true;\n\t\t#if ODE_RESTART_RATIO == 1\n\t\tmax_ratio = 0.;\n\t\t#endif\n\t\tfor (i=0; i<n; i++) {\n\t\t\t#if ODE_RESTART_RATIO == 1\n\t\t\tmax_ratio = std::max(max_ratio, width(w(i).v(p.order)) / width(z(i).v(p.order)));\n\t\t\t#endif\n\t\t\tflag = flag && subset(w(i).v(p.order), z(i).v(p.order));\n\t\t}\n\t\tif (flag) break;\n\n\t\tif (!p.autostep || restart >= p.restart_max) {\n\t\t\tret_val = 0;\n\t\t\tbreak;\n\t\t}\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \"ode: radius changed: \" << radius;\n\t\t}\n\t\t#if ODE_RESTART_RATIO == 1\n\t\tradius *= std::max(std::min((T)0.5, (T)0.5 / max_ratio), (T)0.125);\n\t\t#else\n\t\tradius *= 0.5;\n\t\t#endif\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \" -> \" << radius << \"\\n\";\n\t\t}\n\t\trestart++;\n\t}\n\n\tif (ret_val != 0) {\n\t\tfor (j=0; j<p.iteration; j++) {\n\t\t\tz = w;\n\t\t\tw = f(z, t);\n\t\t\tfor (i=0; i<n; i++) {\n\t\t\t\ttemp = integrate(w(i));\n\t\t\t\tw(i) = setorder(temp, p.order);\n\t\t\t}\n\t\t\tw = init + w;\n\t\t\tfor (i=0; i<n; i++) {\n\t\t\t\tw(i).v(p.order) = intersect(w(i).v(p.order), z(i).v(p.order));\n\t\t\t}\n\t\t}\n\n\t\tresult.resize(n);\n\t\tfor (i=0; i<n; i++) {\n\t\t\tresult(i) = eval(w(i), deltat);\n\t\t}\n\n\t\tinit = result;\n\t\tif (ret_val == 1) end = end2;\n\t\tif (result_psa != NULL) *result_psa = w;\n\t}\n\n\tpsa< interval<T> >::mode() = save_mode;\n\tpsa< interval<T> >::use_history() = save_uh;\n\tpsa< interval<T> >::record_history() = save_rh;\n\n\treturn ret_val;\n}\n\ntemplate <class T, class F>\nint\nodelong(F f, ub::vector< interval<T> >& init, const interval<T>& start, interval<T>& end, ode_param<T> p = ode_param<T>()) {\n\n\tub::vector< interval<T> > x;\n\tinterval<T> t, t1;\n\tint r;\n\tint ret_val = 0;\n\n\tx = init;\n\tt = start;\n\tp.set_autostep(true);\n\twhile (1) {\n\t\tt1 = end;\n\n\t\tr = ode(f, x, t, t1, p);\n\t\tif (r == 0) {\n\t\t\tif (ret_val == 1) {\n\t\t\t\tinit = x;\n\t\t\t\tend = t;\n\t\t\t}\n\t\t\treturn ret_val;\n\t\t}\n\t\tret_val = 1;\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \"t: \" << t1 << \"\\n\";\n\t\t\tstd::cout << x << \"\\n\";\n\t\t}\n\t\tif (r == 2) {\n\t\t\tinit = x;\n\t\t\treturn 2;\n\t\t}\n\t\tt = t1;\n\t}\n}\n\n} // namespace kv\n\n#endif // ODE_HPP\n", "meta": {"hexsha": "dead86a3796c22d4a16208b11039f434f376374a", "size": 7479, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/ode.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "src/interval/kv/ode.hpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "src/interval/kv/ode.hpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 20.8328690808, "max_line_length": 179, "alphanum_fraction": 0.555822971, "num_tokens": 2714, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.6224593452091672, "lm_q1q2_score": 0.41635077711108825}}
{"text": "/**\n * @file random.hpp\n *\n * Miscellaneous math random-related routines.\n *\n * This file is part of mlpack 1.0.12.\n *\n * mlpack is free software; you may redstribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#ifndef __MY_MLPACK_CORE_MATH_RANDOM_HPP\n#define __MY_MLPACK_CORE_MATH_RANDOM_HPP\n\n#include <stdlib.h>\n#include <math.h>\n#include <float.h>\n\n#include <boost/random.hpp>\n\nnamespace mips {\nnamespace math /** Miscellaneous math routines. */ {\n\n// Annoying Boost versioning issues.\n#include <boost/version.hpp>\n\n#if BOOST_VERSION >= 104700\n  // Global random object.\n  extern boost::random::mt19937 randGen;\n  // Global uniform distribution.\n  extern boost::random::uniform_01<> randUniformDist;\n  // Global normal distribution.\n  extern boost::random::normal_distribution<> randNormalDist;\n#else\n  // Global random object.\n  extern boost::mt19937 randGen;\n\n  #if BOOST_VERSION >= 103900\n    // Global uniform distribution.\n    extern boost::uniform_01<> randUniformDist;\n  #else\n    // Pre-1.39 Boost.Random did not give default template parameter values.\n    extern boost::uniform_01<boost::mt19937, double> randUniformDist;\n  #endif\n\n  // Global normal distribution.\n  extern boost::normal_distribution<> randNormalDist;\n#endif\n\n/**\n * Set the random seed used by the random functions (Random() and RandInt()).\n * The seed is casted to a 32-bit integer before being given to the random\n * number generator, but a size_t is taken as a parameter for API consistency.\n *\n * @param seed Seed for the random number generator.\n */\ninline void RandomSeed(const size_t seed)\n{\n  randGen.seed((uint32_t) seed);\n  srand((unsigned int) seed);\n}\n\n/**\n * Generates a uniform random number between 0 and 1.\n */\ninline double Random()\n{\n#if BOOST_VERSION >= 103900\n  return randUniformDist(randGen);\n#else\n  // Before Boost 1.39, we did not give the random object when we wanted a\n  // random number; that gets given at construction time.\n  return randUniformDist();\n#endif\n}\n\n/**\n * Generates a uniform random number in the specified range.\n */\ninline double Random(const double lo, const double hi)\n{\n#if BOOST_VERSION >= 103900\n  return lo + (hi - lo) * randUniformDist(randGen);\n#else\n  // Before Boost 1.39, we did not give the random object when we wanted a\n  // random number; that gets given at construction time.\n  return lo + (hi - lo) * randUniformDist();\n#endif\n}\n\n/**\n * Generates a uniform random integer.\n */\ninline int RandInt(const int hiExclusive)\n{\n#if BOOST_VERSION >= 103900\n  return (int) std::floor((double) hiExclusive * randUniformDist(randGen));\n#else\n  // Before Boost 1.39, we did not give the random object when we wanted a\n  // random number; that gets given at construction time.\n  return (int) std::floor((double) hiExclusive * randUniformDist());\n#endif\n}\n\n/**\n * Generates a uniform random integer.\n */\ninline int RandInt(const int lo, const int hiExclusive)\n{\n#if BOOST_VERSION >= 103900\n  return lo + (int) std::floor((double) (hiExclusive - lo)\n                               * randUniformDist(randGen));\n#else\n  // Before Boost 1.39, we did not give the random object when we wanted a\n  // random number; that gets given at construction time.\n  return lo + (int) std::floor((double) (hiExclusive - lo)\n                               * randUniformDist());\n#endif\n\n}\n\n/**\n * Generates a normally distributed random number with mean 0 and variance 1.\n */\ninline double RandNormal()\n{\n  return randNormalDist(randGen);\n}\n\n/**\n * Generates a normally distributed random number with specified mean and\n * variance.\n *\n * @param mean Mean of distribution.\n * @param variance Variance of distribution.\n */\ninline double RandNormal(const double mean, const double variance)\n{\n  return variance * randNormalDist(randGen) + mean;\n}\n\n}; // namespace math\n}; // namespace mlpack\n\n#endif // __MLPACK_CORE_MATH_MATH_LIB_HPP\n", "meta": {"hexsha": "bb41c83d5f4e786ad7d835c7ef8ab637a3f42cc3", "size": 4039, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mips/my_mlpack/core/math/random.hpp", "max_stars_repo_name": "uma-pi1/LEMP", "max_stars_repo_head_hexsha": "e24ce821692aba8403ca8733382f53641f7f96d5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-07-28T07:05:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-16T17:34:42.000Z", "max_issues_repo_path": "mips/my_mlpack/core/math/random.hpp", "max_issues_repo_name": "d3v3l0/LEMP-benchmarking", "max_issues_repo_head_hexsha": "0279528b427aa4fae59e4d3598b1f098fcb4cf4b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-16T03:30:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T03:30:55.000Z", "max_forks_repo_path": "mips/my_mlpack/core/math/random.hpp", "max_forks_repo_name": "d3v3l0/LEMP-benchmarking", "max_forks_repo_head_hexsha": "0279528b427aa4fae59e4d3598b1f098fcb4cf4b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-16T08:21:24.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-04T06:37:41.000Z", "avg_line_length": 27.4761904762, "max_line_length": 78, "alphanum_fraction": 0.7135429562, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4163507595246603}}
{"text": "// Copyright Nick Thompson, 2017\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// This implements the compactly supported cubic b spline algorithm described in\n// Kress, Rainer. \"Numerical analysis, volume 181 of Graduate Texts in Mathematics.\" (1998).\n// Splines of compact support are faster to evaluate and are better conditioned than classical cubic splines.\n\n// Let f be the function we are trying to interpolate, and s be the interpolating spline.\n// The routine constructs the interpolant in O(N) time, and evaluating s at a point takes constant time.\n// The order of accuracy depends on the regularity of the f, however, assuming f is\n// four-times continuously differentiable, the error is of O(h^4).\n// In addition, we can differentiate the spline and obtain a good interpolant for f'.\n// The main restriction of this method is that the samples of f must be evenly spaced.\n// Look for barycentric rational interpolation for non-evenly sampled data.\n// Properties:\n// - s(x_j) = f(x_j)\n// - All cubic polynomials interpolated exactly\n\n#ifndef BOOST_MATH_INTERPOLATORS_CUBIC_B_SPLINE_HPP\n#define BOOST_MATH_INTERPOLATORS_CUBIC_B_SPLINE_HPP\n\n#include <boost/math/interpolators/detail/cubic_b_spline_detail.hpp>\n\nnamespace boost{ namespace math{\n\ntemplate <class Real>\nclass cubic_b_spline\n{\npublic:\n    // If you don't know the value of the derivative at the endpoints, leave them as nans and the routine will estimate them.\n    // f[0] = f(a), f[length -1] = b, step_size = (b - a)/(length -1).\n    template <class BidiIterator>\n    cubic_b_spline(const BidiIterator f, BidiIterator end_p, Real left_endpoint, Real step_size,\n                   Real left_endpoint_derivative = std::numeric_limits<Real>::quiet_NaN(),\n                   Real right_endpoint_derivative = std::numeric_limits<Real>::quiet_NaN());\n    cubic_b_spline(const Real* const f, size_t length, Real left_endpoint, Real step_size,\n       Real left_endpoint_derivative = std::numeric_limits<Real>::quiet_NaN(),\n       Real right_endpoint_derivative = std::numeric_limits<Real>::quiet_NaN());\n\n    cubic_b_spline() = default;\n    Real operator()(Real x) const;\n\n    Real prime(Real x) const;\n\nprivate:\n    std::shared_ptr<detail::cubic_b_spline_imp<Real>> m_imp;\n};\n\ntemplate<class Real>\ncubic_b_spline<Real>::cubic_b_spline(const Real* const f, size_t length, Real left_endpoint, Real step_size,\n                                     Real left_endpoint_derivative, Real right_endpoint_derivative) : m_imp(std::make_shared<detail::cubic_b_spline_imp<Real>>(f, f + length, left_endpoint, step_size, left_endpoint_derivative, right_endpoint_derivative))\n{\n}\n\ntemplate <class Real>\ntemplate <class BidiIterator>\ncubic_b_spline<Real>::cubic_b_spline(BidiIterator f, BidiIterator end_p, Real left_endpoint, Real step_size,\n   Real left_endpoint_derivative, Real right_endpoint_derivative) : m_imp(std::make_shared<detail::cubic_b_spline_imp<Real>>(f, end_p, left_endpoint, step_size, left_endpoint_derivative, right_endpoint_derivative))\n{\n}\n\ntemplate<class Real>\nReal cubic_b_spline<Real>::operator()(Real x) const\n{\n    return m_imp->operator()(x);\n}\n\ntemplate<class Real>\nReal cubic_b_spline<Real>::prime(Real x) const\n{\n    return m_imp->prime(x);\n}\n\n}}\n#endif\n", "meta": {"hexsha": "73ac1d01373e250b0eb9d2fb2791188240bd2cb0", "size": 3381, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/math/interpolators/cubic_b_spline.hpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/boost/math/interpolators/cubic_b_spline.hpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/boost/math/interpolators/cubic_b_spline.hpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 42.7974683544, "max_line_length": 253, "alphanum_fraction": 0.7518485655, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4163507595246603}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n#include <complex>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/vector/map_view.hpp>\n#include <boost/numeric/mtl/operation/print.hpp>\n#include <boost/numeric/mtl/operation/set_to_zero.hpp>\n#include <boost/numeric/mtl/operation/conj.hpp>\n#include <boost/numeric/mtl/operation/real.hpp>\n#include <boost/numeric/mtl/operation/imag.hpp>\n#include <boost/numeric/mtl/operation/scale.hpp>\n\n#if 0\n#include <boost/numeric/mtl/operation/hermitian.hpp>\n#endif\n\n\nusing std::cout;  using std::complex;\n\ntypedef complex<double> ct;\n\ndouble value(double)\n{\n    return 7.0;\n}\n\ncomplex<double> value(complex<double>)\n{\n    return ct(7.0, 1.0);\n}\n\n// scaled value\ndouble svalue(double)\n{\n    return 14.0;\n}\n\nct svalue(ct)\n{\n    return ct(14.0, 2.0);\n}\n\n// conjugated value\ndouble cvalue(double)\n{\n    return 7.0;\n}\n\nct cvalue(ct)\n{\n    return ct(7.0, -1.0);\n}\n\n// complex scaled value\nct csvalue(double)\n{\n    return ct(0.0, 7.0);\n}\n\nct csvalue(ct)\n{\n    return ct(-1.0, 7.0);\n}\n\n\ntemplate <typename Vector>\nvoid test(Vector& vector, const char* name)\n{\n    using mtl::real; using mtl::imag;\n\n    set_to_zero(vector);\n    typename Vector::value_type ref(0);\n\n    vector[2]= value(ref);\n    vector[4]= value(ref) + 1.0;\n    vector[5]= value(ref) + 2.0;\n\n#if 0 // When sparse vectors are used there should be an inserter class for vectors too\n    {\n\tinserter<Vector>  ins(vector);\n\tins(2) << value(ref);\n\tins(4) << value(ref) + 1.0;\n\tins(5) << value(ref) + 2.0;\n    }\n#endif\n\n    cout << \"\\n\\n\" << name << \"\\n\";\n    cout << \"Original vector:\\n\" << vector << \"\\n\";\n\n\n    mtl::vec::scaled_view<double, Vector>  scaled_vector(2.0, vector);\n    cout << \"vector  scaled with 2.0\\n\" << scaled_vector << \"\\n\";\n    MTL_THROW_IF(scaled_vector(2) != svalue(ref), mtl::runtime_error(\"scaling wrong\"));\n    \n    mtl::vec::conj_view<Vector>  conj_vector(vector);\n    cout << \"conjugated vector\\n\" << conj_vector << \"\\n\";\n    MTL_THROW_IF(conj_vector(2) != cvalue(ref), mtl::runtime_error(\" wrong\"));\n\n    mtl::vec::scaled_view<ct, Vector>  cscaled_vector(ct(0.0, 1.0), vector);\n    cout << \"vector scaled with i (complex(0, 1))\\n\" << cscaled_vector << \"\\n\";\n    MTL_THROW_IF(cscaled_vector(2) != csvalue(ref), mtl::runtime_error(\"complex scaling wrong\"));\n\n#if 0 // transposition of vector is not an issue (yet)\n    mtl::vec::hermitian_view<Vector>  hermitian_vector(vector);\n    cout << \"Hermitian vector (conjugate transposed)\\n\" << hermitian_vector << \"\\n\";\n    if (hermitian_vector(3, 2) != cvalue(ref)) \n\tthrow \"conjugate transposing  wrong\";\n#endif\n\n    cout << \"vector  scaled with 2.0 (free function)\\n\" << scale(2.0, vector) << \"\\n\";\n    MTL_THROW_IF(scale(2.0, vector)(2) != svalue(ref), mtl::runtime_error(\"scaling wrong\"));\n\n#if defined(__GNUC__) && __GNUC__ == 4 && (__GNUC_MINOR__ >= 3 && __GNUC_MINOR__ <= 6)\n    cout << \"conjugated vector (free function) \\n\" << mtl::conj(vector) << \"\\n\";\n    MTL_THROW_IF(mtl::conj(vector)[2] != cvalue(ref), mtl::runtime_error(\"conjugating wrong\"));\n\n    cout << \"real vector (free function) \\n\" << mtl::vec::real(vector) << \"\\n\";\n    MTL_THROW_IF(mtl::vec::real(vector)[2] != real(value(ref)), mtl::runtime_error(\"real part wrong\"));\n\n    cout << \"imag vector (free function) \\n\" << mtl::vec::imag(vector) << \"\\n\";\n    MTL_THROW_IF(mtl::vec::imag(vector)[2] != imag(value(ref)), mtl::runtime_error(\"imag part wrong\"));\n#else\n    cout << \"conjugated vector (free function) \\n\" << conj(vector) << \"\\n\";\n    MTL_THROW_IF(conj(vector)[2] != cvalue(ref), mtl::runtime_error(\"conjugating wrong\"));\n\n    cout << \"real vector (free function) \\n\" << real(vector) << \"\\n\";\n    MTL_THROW_IF(real(vector)[2] != real(value(ref)), mtl::runtime_error(\"real part wrong\"));\n\n    cout << \"imag vector (free function) \\n\" << imag(vector) << \"\\n\";\n    MTL_THROW_IF(imag(vector)[2] != imag(value(ref)), mtl::runtime_error(\"imag part wrong\"));\n#endif\n\n    cout << \"vector scaled with i (complex(0, 1)) (free function)\\n\" << scale(ct(0.0, 1.0), vector) << \"\\n\";\n    MTL_THROW_IF(scale(ct(0.0, 1.0), vector)(2) != csvalue(ref), mtl::runtime_error(\"complex scaling wrong\"));\n\n\n#if 0 // transposition of vector is not an issue (yet)\n    cout << \"Hermitian  vector (conjugate transposed) (free function)\\n\" << hermitian(vector) << \"\\n\";\n    if (hermitian(vector)(3, 2) != cvalue(ref)) \n\tthrow \"conjugate transposing wrong\";\n#endif\n\n\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    unsigned size= 7; \n    if (argc > 1) size= atoi(argv[1]); \n\n    mtl::dense_vector<double>                                 dv(size);\n    mtl::dense_vector<complex<double> >                       drc(size);\n\n    test(dv, \"Dense double vector\");\n    test(drc, \"Dense complex vector\");\n\n    return 0;\n}\n", "meta": {"hexsha": "da0de8fbb837e8551fd47a72b3f812567e575f87", "size": 5185, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/vector_map_view_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/vector_map_view_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/vector_map_view_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 29.9710982659, "max_line_length": 110, "alphanum_fraction": 0.643587271, "num_tokens": 1558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802471698041, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4163507513074475}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__FEEDBACK__COLLOCATION__MESH_HPP_\n#define SMOOTH__FEEDBACK__COLLOCATION__MESH_HPP_\n\n/**\n * @file\n * @brief Refinable Legendre-Gauss-Radau mesh of time interval [0, 1]\n */\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <smooth/internal/utils.hpp>\n#include <smooth/polynomial/quadrature.hpp>\n\n#include <ranges>\n#include <span>\n#include <vector>\n\n#include \"smooth/feedback/traits.hpp\"\n#include \"smooth/feedback/utils/sparse.hpp\"\n\nnamespace smooth::feedback {\n\nusing smooth::utils::zip;\n\nusing std::views::iota, std::views::drop, std::views::reverse, std::views::take,\n  std::views::transform, std::views::join;\n\nnamespace detail {\n\n/**\n * @brief Legendre-Gauss-Radau nodes including an extra node at +1.\n */\ntemplate<std::size_t K, std::size_t I = 8>\nconstexpr std::pair<std::array<double, K + 1>, std::array<double, K + 1>> lgr_plus_one()\n{\n  auto lgr_norm = ::smooth::lgr_nodes<K, I>();\n\n  std::array<double, K + 1> ns, ws;\n  for (auto i = 0u; i < K; ++i) {\n    ns[i] = lgr_norm.first[i];\n    ws[i] = lgr_norm.second[i];\n  }\n  ns[K] = 1;\n  ws[K] = 0;\n  return {ns, ws};\n}\n\n}  // namespace detail\n\n/**\n * @brief Collocation mesh of interval [0, 1].\n * @tparam _Kmin minimal number of collocation points per interval\n * @tparam _Kmax maximal number of collocation points per interval\n *\n * [0, 1] is divided into non-overlapping intervals I_i, and each interval I_i has K_i LGR\n * collocation points.\n */\ntemplate<std::size_t _Kmin = 5, std::size_t _Kmax = 10>\n  requires(_Kmin <= _Kmax)\nclass Mesh\n{\n  using MatMap = Eigen::Map<const Eigen::Matrix<double, -1, -1, Eigen::RowMajor>>;\n\npublic:\n  /// @brief Minimal number of collocation points per interval\n  static constexpr auto Kmin = _Kmin;\n  /// @brief Maximal number of collocation points per interval\n  static constexpr auto Kmax = _Kmax;\n\n  /**\n   * @brief Create a mesh consisting of a single interval [0, 1].\n   *\n   * @param Kmin minimal polynomial degree in mesh\n   * @param Kmax maximal polynomial degree in mesh\n   *\n   * @note It must hold that kKmin <= Kmin <= Kmax <= kKmax, where kKmin and kKmax are compile-time\n   * constants that define which LGR nodes to pre-compute.\n   *\n   * @note Allocates heap memory.\n   */\n  inline Mesh() : intervals_(1, Interval{.K = Kmin, .tau0 = 0.}) {}\n\n  /**\n   * @brief Create a mesh consisting of a n intervals of equal size over [0, 1].\n   *\n   * @param n number of intervals. If n==0, only a single interval is created.\n   * @param k polynomial degree for all intervals\n   *\n   * @note Allocates heap memory.\n   */\n  inline Mesh(const std::size_t n, const std::size_t k = Kmin)\n  {\n    assert(Kmin <= k && k <= Kmax + 1);\n\n    if (n < 2) {\n      intervals_.emplace_back(k, 0.);\n    } else {\n      const double dx = 1. / static_cast<double>(n);\n      intervals_.reserve(n);\n      for (std::size_t i = 0; i < n; ++i) {\n        intervals_.emplace_back(k, static_cast<double>(i) * dx);\n      }\n    }\n  }\n\n  /**\n   * @brief Number of intervals in mesh.\n   */\n  inline std::size_t N_ivals() const { return intervals_.size(); }\n\n  /**\n   * @brief Number of collocation points in mesh.\n   */\n  inline std::size_t N_colloc() const\n  {\n    return std::accumulate(\n      intervals_.begin(), intervals_.end(), 0u, [](std::size_t curr, const auto & x) {\n        return curr + x.K;\n      });\n  }\n\n  /**\n   * @brief Number of collocation points in interval i.\n   *\n   * @note This is also equal to the polynomial degree inside interval i, since the polynomial is\n   * fitted with an \"extra\" point belonging to the subsequent interval.\n   */\n  inline std::size_t N_colloc_ival(std::size_t i) const\n  {\n    assert(i < intervals_.size());\n    return intervals_[i].K;\n  }\n\n  /**\n   * @brief Refine interval using the ph strategy.\n   *\n   * @param i index of interval to refine\n   * @param D target number of collocation points in refined interval\n   *\n   * If D > Kmax, or current degree > Kmax    then the interval is divided into\n   *                                          n = max(2, ceil(D / Kmin)) intervals with deg Kmin\n   * If D < current degree,                   then nothing is done.\n   * If D <= Kmax,                            then the polynomial degree is increased to D.\n   *\n   * @note May allocate heap memory due to vector resizing if the number of intervals is increased.\n   */\n  inline void refine_ph(std::size_t i, std::size_t D)\n  {\n    assert(i < intervals_.size());\n    if (D > Kmax || intervals_[i].K > Kmax) {\n      // refine by splitting interval into n intervals, each with degree Kmin_\n      std::size_t n = std::max<std::size_t>(2u, (D + Kmin - 1) / Kmin);\n\n      const double tau0 = intervals_[i].tau0;\n      const double tauf = i + 1 < intervals_.size() ? intervals_[i + 1].tau0 : 1.;\n      const double taum = (tauf - tau0) / n;\n\n      while (n-- > 1) {\n        intervals_.insert(intervals_.begin() + i + 1, Interval{.K = Kmin, .tau0 = tau0 + n * taum});\n      }\n    } else if (D < intervals_[i].K) {\n      return;\n    } else if (D <= Kmax) {\n      // refine by increasing degree in interval\n      intervals_[i].K = D;\n    }\n  }\n\n  /**\n   * @brief Refine intervals in mesh to satisfy a target error criterion.\n   * @param errs relative errors for all intervals (@see mesh_dyn_error())\n   * @param target_err target relative error\n   */\n  inline void refine_errors(std::ranges::sized_range auto && errs, double target_err)\n  {\n    const auto N = N_ivals();\n\n    assert(N == std::size_t(std::ranges::size(errs)));\n\n    for (const auto & [i, e] : zip(iota(0u, N) | reverse, errs | reverse)) {\n\n      const auto Ki = N_colloc_ival(i);\n\n      if (e > target_err) {\n        const auto Ktarget = Ki + std::lround(std::log(e / target_err) / std::log(Ki) + 1);\n        refine_ph(i, Ktarget);\n      }\n    }\n  }\n\n  /**\n   * @brief Set the number of collocation points in interval i to K\n   * @param i interval index\n   * @param K number of collocation points s.t. (Kmin <= K <= Kmax + 1)\n   */\n  inline void set_N_colloc_ival(std::size_t i, std::size_t K)\n  {\n    assert(Kmin <= K);\n    assert(K <= Kmax + 1);\n    intervals_[i].K = K;\n  }\n\n  /**\n   * @brief Interval nodes (as range of doubles).\n   *\n   * @note Includes extra point at 1, i.e. size of returned range is equal to N_colloc_ival()+1\n   */\n  inline auto interval_nodes(std::size_t i) const\n  {\n    const std::size_t k = intervals_[i].K;\n\n    assert(Kmin <= k && k <= Kmax + 1);\n\n    std::span<const double> sp;\n\n    utils::static_for<Kmax + 2 - Kmin>([&](auto ivar) {\n      static constexpr auto K = Kmin + ivar;\n      if (K == k) {\n        static constexpr auto nw_ext_s = detail::lgr_plus_one<K>();\n\n        sp = std::span<const double>(nw_ext_s.first.data(), k + 1);\n      }\n    });\n\n    const double tau0 = intervals_[i].tau0;\n    const double tauf = i + 1 < intervals_.size() ? intervals_[i + 1].tau0 : 1.;\n    const double al   = (tauf - tau0) / 2;\n\n    return transform(std::move(sp), [tau0, al](double d) -> double { return tau0 + al * (d + 1); });\n  }\n\n  /**\n   * @brief Nodes (as range of doubles).\n   *\n   * @note Includes extra point at 1, i.e. size of returned range is equal to N_colloc()+1\n   *\n   * @note The result is an input range\n   */\n  inline auto all_nodes() const\n  {\n    const auto n_ivals = N_ivals();\n    auto all_views     = iota(0u, n_ivals) | transform([this, n_ivals = n_ivals](auto i) {\n                       const auto n_ival    = N_colloc_ival(i);\n                       const int64_t n_take = i + 1 < n_ivals ? n_ival : n_ival + 1;\n                       return interval_nodes(i) | take(n_take);\n                     });\n\n    return join(std::move(all_views));\n  }\n\n  /**\n   * @brief Interval weights (as range of doubles)\n   *\n   * @note Includes zero weight at 1, i.e. size of returned range is equal to N_colloc_ival()+1\n   */\n  inline auto interval_weights(std::size_t i) const\n  {\n    const std::size_t k = intervals_[i].K;\n\n    assert(Kmin <= k && k <= Kmax + 1);\n\n    std::span<const double> sp;\n\n    utils::static_for<Kmax + 2 - Kmin>([&](auto ivar) {\n      static constexpr auto K = Kmin + ivar;\n      if (K == k) {\n        static constexpr auto nw_ext_s = detail::lgr_plus_one<K>();\n\n        sp = std::span<const double>(nw_ext_s.second.data(), k + 1);\n      }\n    });\n\n    const double tau0 = intervals_[i].tau0;\n    const double tauf = i + 1 < intervals_.size() ? intervals_[i + 1].tau0 : 1.;\n    const double al   = (tauf - tau0) / 2;\n\n    return transform(std::move(sp), [al](double d) -> double { return al * d; });\n  }\n\n  /**\n   * @brief Weights (as range of doubles)\n   *\n   * @note Includes zero weight at 1, i.e. size of returned range is equal to N_colloc()+1\n   *\n   * @note The result is an input range\n   */\n  inline auto all_weights() const\n  {\n    const auto n_ivals = N_ivals();\n    auto all_views     = iota(0u, n_ivals) | transform([this, n_ivals = n_ivals](auto i) {\n                       const auto n_ival    = N_colloc_ival(i);\n                       const int64_t n_take = i + 1 < n_ivals ? n_ival : n_ival + 1;\n                       return interval_weights(i) | take(n_take);\n                     });\n\n    return join(std::move(all_views));\n  }\n\n  /**\n   * @brief Interval differentiation matrix w.r.t. [0, 1] timescale.\n   *\n   * Returns a \\f$ (K+1 \\times K) \\f$ matrix \\f$ D \\f$ s.t.\n   * \\f[\n   *   \\begin{bmatrix} y'(\\tau_{i, 0}) & y'(\\tau_{i, 1}) & \\cdots & y'(\\tau_{i, K-1}) \\end{bmatrix}\n   *  =\n   *   \\begin{bmatrix} y(\\tau_{i, 0}) & y(\\tau_{i, 1}) & \\cdots & y(\\tau_{i, K}) \\end{bmatrix} D\n   * \\f],\n   * where \\f$ y(\\cdot) \\in \\mathbb{R}^{d \\times 1} \\f$ is a Lagrange polynomial in interval i.\n   *\n   * @note Allocates heap memory for return value.\n   */\n  inline Eigen::MatrixXd interval_diffmat(std::size_t i) const\n  {\n    const std::size_t k = intervals_[i].K;\n\n    const double tau0 = intervals_[i].tau0;\n    const double tauf = i + 1 < intervals_.size() ? intervals_[i + 1].tau0 : 1.;\n\n    Eigen::MatrixXd ret(k + 1, k);\n\n    utils::static_for<Kmax + 2 - Kmin>([&](auto ivar) {\n      static constexpr auto K = Kmin + ivar;\n      if (K == k) {\n        static constexpr auto nw_ext_s = detail::lgr_plus_one<K>();\n        static constexpr auto B_ext_s  = lagrange_basis<K>(nw_ext_s.first);\n        static constexpr auto D_ext_s =\n          polynomial_basis_derivatives<K, K + 1>(B_ext_s, nw_ext_s.first)\n            .template block<K + 1, K>(0, 0);\n        ret = MatMap(D_ext_s[0].data(), k + 1, k);\n      }\n    });\n\n    ret *= 2. / (tauf - tau0);\n    return ret;\n  }\n\n  /**\n   * @brief Interval differentiation matrix (unscaled).\n   *\n   * Returns a Map D_us and a scalar alpha s.t. D = alpha * D_us\n   *\n   * @see interval_diffmat\n   */\n  inline std::pair<double, MatMap> interval_diffmat_unscaled(std::size_t i) const\n  {\n    const std::size_t k = intervals_[i].K;\n\n    const double tau0 = intervals_[i].tau0;\n    const double tauf = i + 1 < intervals_.size() ? intervals_[i + 1].tau0 : 1.;\n\n    MatMap ret(nullptr, 0, 0);\n\n    utils::static_for<Kmax + 2 - Kmin>([&](auto ivar) {\n      static constexpr auto K = Kmin + ivar;\n      if (K == k) {\n        static constexpr auto nw_ext_s = detail::lgr_plus_one<K>();\n        static constexpr auto B_ext_s  = lagrange_basis<K>(nw_ext_s.first);\n        static constexpr auto D_ext_s =\n          polynomial_basis_derivatives<K, K + 1>(B_ext_s, nw_ext_s.first)\n            .template block<K + 1, K>(0, 0);\n        // Eigen maps don't have copy constructors so use placement new\n        new (&ret) MatMap(D_ext_s[0].data(), k + 1, k);\n      }\n    });\n\n    return {2. / (tauf - tau0), ret};\n  }\n\n  /**\n   * @brief Interval integration matrix w.r.t. [0, 1] timescale.\n   *\n   * Returns a \\f$ (K \\times K) \\f$ matrix \\f$ I \\f$ s.t.\n   * \\f[\n   *   \\begin{bmatrix}\n   *      y(\\tau_{i, 1}) & y(\\tau_{i, 2}) & \\cdots & y(\\tau_{i, K})\n   *   \\end{bmatrix}\n   *  = y(\\tau_{i, 0}) \\begin{bmatrix} 1 & \\ldots & 1 \\end{bmatrix}\n   *    + \\begin{bmatrix}\n   *        \\dot y(\\tau_{i, 0}) & \\dot y(\\tau_{i, 1}) & \\cdots & \\dot y(\\tau_{i, K-1})\n   *      \\end{bmatrix} I\n   * \\f],\n   * where \\f$ y(\\cdot) \\in \\mathbb{R}^{d \\times 1} \\f$ is a Lagrange\n   * polynomial in interval i.\n   *\n   * @note Allocates heap memory for return value.\n   *\n   * @note Performs a matrix inverse.\n   */\n  inline Eigen::MatrixXd interval_intmat(std::size_t i) const\n  {\n    const std::size_t k = intervals_[i].K;\n    return interval_diffmat(i).block(1, 0, k, k).inverse();\n  }\n\n  /**\n   * @brief Find interval index that contains t\n   */\n  inline std::size_t interval_find(double t) const\n  {\n    if (t < 0) { return 0; }\n    if (t > 1) { return intervals_.size() - 1; }\n    auto it = utils::binary_interval_search(\n      intervals_, t, [](const auto & ival, double _t) { return ival.tau0 <=> _t; });\n    if (it != intervals_.end()) { return std::distance(intervals_.begin(), it); }\n    return 0;\n  }\n\n  /**\n   * @brief Increase the degree of all intervals by one (up to maximal degree Kmax + 1)\n   */\n  void increase_degrees()\n  {\n    for (auto & ival : intervals_) { ival.K = std::min(ival.K + 1, Kmax + 1); }\n  }\n\n  /**\n   * @brief Decrease the degree of all intervals by one (down to minimal degree Kmin)\n   */\n  void decrease_degrees()\n  {\n    for (auto & ival : intervals_) { ival.K = std::max(ival.K - 1, Kmin); }\n  }\n\n  /**\n   * @brief Evaluate a function\n   *\n   * @tparam RetT return value type\n   *\n   * @param t time value in [0, 1]\n   * @param r values for the collocation points (size N [extend=false] or N+1 [extend=true])\n   * @param p derivative to evaluate\n   * @param extend set to true if a value is provided for t=+1\n   */\n  template<smooth::traits::RnType RetT>\n  RetT eval(double t, std::ranges::range auto && r, std::size_t p = 0, bool extend = true) const\n  {\n    const std::size_t ival = interval_find(t);\n    const std::size_t k    = intervals_[ival].K;\n\n    const double tau0 = intervals_[ival].tau0;\n    const double tauf = ival + 1 < intervals_.size() ? intervals_[ival + 1].tau0 : 1.;\n\n    const double u = 2 * (t - tau0) / (tauf - tau0) - 1;\n\n    int64_t N_before = 0;\n    for (auto i = 0u; i < ival; ++i) { N_before += intervals_[i].K; }\n\n    // initialize output variable\n    RetT ret = RetT::Zero(dof(*std::ranges::begin(r)));\n\n    utils::static_for<Kmax + 2 - Kmin>([&](auto i) {\n      static constexpr auto K = Kmin + i;\n      if (K == k) {\n        if (extend || ival + 1 < intervals_.size()) {\n          static constexpr auto nw_ext_s = detail::lgr_plus_one<K>();\n          static constexpr auto B_ext_s  = lagrange_basis<K>(nw_ext_s.first);  // K+1 x K+1\n          const auto U                   = monomial_derivative<K>(u, p);       // 1 x K+1\n          const auto W                   = U * B_ext_s;                        // 1 x K+1\n\n          for (const auto & [w, v] : zip(std::span(W[0].data(), k + 1), r | drop(N_before))) {\n            ret += w * v;\n          }\n        } else {\n          static constexpr auto nw_s = lgr_nodes<K>();\n          static constexpr auto B_s  = lagrange_basis<K - 1>(nw_s.first);  // K x K\n          const auto U               = monomial_derivative<K - 1>(u, p);   // 1 x K\n          const auto W               = U * B_s;                            // 1 x K\n\n          for (const auto & [w, v] : zip(std::span(W[0].data(), k), r | drop(N_before))) {\n            ret += w * v;\n          }\n        }\n      }\n    });\n\n    return ret;\n  }\n\nprivate:\n  struct Interval\n  {\n    /// @brief Polynomial degree in interval\n    std::size_t K;\n    /// @brief Start of interval on [0, 1] timescale\n    double tau0;\n  };\n\n  /// @brief Mesh intervals\n  std::vector<Interval> intervals_;\n};\n\n/// @brief MeshType is a specialization of Mesh\ntemplate<typename T>\nconcept MeshType = traits::is_specialization_of_sizet_v<std::decay_t<T>, Mesh>;\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__COLLOCATION__MESH_HPP_\n", "meta": {"hexsha": "b7fa7e2d7e421a14824be41bd1a98237aa243a76", "size": 17060, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/collocation/mesh.hpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/smooth/feedback/collocation/mesh.hpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smooth/feedback/collocation/mesh.hpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5572519084, "max_line_length": 100, "alphanum_fraction": 0.6020515826, "num_tokens": 5063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4162936051428371}}
{"text": "/*\n * Copyright Andrey Semashev 2020\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * https://www.boost.org/LICENSE_1_0.txt)\n */\n/*!\n * \\file popcount.hpp\n *\n * This header defines \\c popcount algorithm, which counts the number of non-zero bits in an integer.\n */\n\n#ifndef BOOST_BIT_OPS_COUNTING_POPCOUNT_HPP_INCLUDED_\n#define BOOST_BIT_OPS_COUNTING_POPCOUNT_HPP_INCLUDED_\n\n#include <boost/cstdint.hpp>\n#include <boost/bit_ops/detail/config.hpp>\n#include <boost/bit_ops/detail/int_sizes.hpp>\n#include <boost/bit_ops/detail/type_traits/enable_if.hpp>\n#include <boost/bit_ops/detail/type_traits/integral_constant.hpp>\n#include <boost/bit_ops/detail/type_traits/is_integral.hpp>\n#include <boost/bit_ops/detail/type_traits/is_unsigned.hpp>\n\n#if defined(_MSC_VER)\n#include <intrin.h>\n#endif\n\nnamespace boost {\nnamespace bit_ops {\n\nnamespace detail {\n\n#if defined(BOOST_BIT_OPS_DETAIL_HAS_BUILTIN_POPCOUNT)\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N <= BOOST_BIT_OPS_DETAIL_SIZEOF_INT, unsigned int >::type popcount(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    return static_cast< unsigned int >(__builtin_popcount(value));\n}\n\n#if BOOST_BIT_OPS_DETAIL_SIZEOF_LONG > BOOST_BIT_OPS_DETAIL_SIZEOF_INT\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N == BOOST_BIT_OPS_DETAIL_SIZEOF_LONG, unsigned int >::type popcount(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    return static_cast< unsigned int >(__builtin_popcountl(value));\n}\n\n#endif // BOOST_BIT_OPS_DETAIL_SIZEOF_LONG > BOOST_BIT_OPS_DETAIL_SIZEOF_INT\n\n#if BOOST_BIT_OPS_DETAIL_SIZEOF_LLONG > BOOST_BIT_OPS_DETAIL_SIZEOF_LONG\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N == BOOST_BIT_OPS_DETAIL_SIZEOF_LLONG, unsigned int >::type popcount(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    return static_cast< unsigned int >(__builtin_popcountll(value));\n}\n\n#endif // BOOST_BIT_OPS_DETAIL_SIZEOF_LLONG > BOOST_BIT_OPS_DETAIL_SIZEOF_LONG\n\n#elif defined(BOOST_BIT_OPS_DETAIL_HAS_POPCNT)\n\n#if defined(BOOST_BIT_OPS_DETAIL_HAS_POPCNT16)\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N <= 2u, unsigned int >::type popcount(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    return static_cast< unsigned int >(__popcnt16(value));\n}\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N == 4u, unsigned int >::type popcount(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    return static_cast< unsigned int >(__popcnt(value));\n}\n\n#else // defined(BOOST_BIT_OPS_DETAIL_HAS_POPCNT16)\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N <= 4u, unsigned int >::type popcount(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n    return static_cast< unsigned int >(__popcnt(value));\n}\n\n#endif // defined(BOOST_BIT_OPS_DETAIL_HAS_POPCNT16)\n\ntemplate< typename T, unsigned int N >\ninline typename bit_ops::detail::enable_if< N == 8u, unsigned int >::type popcount(T value, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT\n{\n#if defined(BOOST_BIT_OPS_DETAIL_HAS_POPCNT64)\n    return static_cast< unsigned int >(__popcnt64(value));\n#else\n    return static_cast< unsigned int >(__popcnt(static_cast< unsigned int >(value)) + __popcnt(static_cast< unsigned int >(value >> 32u)));\n#endif\n}\n\n#else\n\ntemplate< typename T >\ninline unsigned int popcount(T value, bit_ops::detail::integral_constant< unsigned int, 1u >) BOOST_NOEXCEPT\n{\n    value = (value & 0x55u) + ((value >> 1u) & 0x55u);\n    value = (value & 0x33u) + ((value >> 2u) & 0x33u);\n    value = value + (value >> 4u);\n    return static_cast< unsigned int >(value & 15u);\n}\n\ntemplate< typename T >\ninline unsigned int popcount(T value, bit_ops::detail::integral_constant< unsigned int, 2u >) BOOST_NOEXCEPT\n{\n    value = (value & 0x5555u) + ((value >> 1u) & 0x5555u);\n    value = (value & 0x3333u) + ((value >> 2u) & 0x3333u);\n    value = (value + (value >> 4u)) & 0x0F0Fu;\n    value = value + (value >> 8u);\n    return static_cast< unsigned int >(value & 31u);\n}\n\ntemplate< typename T >\ninline unsigned int popcount(T value, bit_ops::detail::integral_constant< unsigned int, 4u >) BOOST_NOEXCEPT\n{\n    value = (value & 0x55555555u) + ((value >> 1u) & 0x55555555u);\n    value = (value & 0x33333333u) + ((value >> 2u) & 0x33333333u);\n    value = (value + (value >> 4u)) & 0x0F0F0F0Fu;\n    value = (value + (value >> 8u)) & 0x00FF00FFu;\n    value = value + (value >> 16u);\n    return static_cast< unsigned int >(value & 63u);\n}\n\ntemplate< typename T >\ninline unsigned int popcount(T value, bit_ops::detail::integral_constant< unsigned int, 8u >) BOOST_NOEXCEPT\n{\n    value = (value & UINT64_C(0x5555555555555555)) + ((value >> 1u) & UINT64_C(0x5555555555555555));\n    value = (value & UINT64_C(0x3333333333333333)) + ((value >> 2u) & UINT64_C(0x3333333333333333));\n    value = (value + (value >> 4u)) & UINT64_C(0x0F0F0F0F0F0F0F0F);\n    value = (value + (value >> 8u)) & UINT64_C(0x00FF00FF00FF00FF);\n    value = value + (value >> 16u);\n    value = value + (value >> 32u);\n    return static_cast< unsigned int >(value & 127u);\n}\n\n#endif\n\n} // namespace detail\n\n//! Returns the number of non-zero bits in \\a value\ntemplate< typename T >\ninline typename bit_ops::detail::enable_if<\n    bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value,\n    unsigned int\n>::type popcount(T value) BOOST_NOEXCEPT\n{\n    return bit_ops::detail::popcount(value, bit_ops::detail::integral_constant< unsigned int, sizeof(T) >());\n}\n\n} // namespace bit_ops\n} // namespace boost\n\n#endif // BOOST_BIT_OPS_COUNTING_POPCOUNT_HPP_INCLUDED_\n", "meta": {"hexsha": "913316300658bf276056041c5f265cf8991f839a", "size": 5958, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/bit_ops/counting/popcount.hpp", "max_stars_repo_name": "Lastique/bit_ops", "max_stars_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/bit_ops/counting/popcount.hpp", "max_issues_repo_name": "Lastique/bit_ops", "max_issues_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/bit_ops/counting/popcount.hpp", "max_forks_repo_name": "Lastique/bit_ops", "max_forks_repo_head_hexsha": "c0f8d03687affe2d4426d0ff623d6e511d5c1a5b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2375, "max_line_length": 192, "alphanum_fraction": 0.734810339, "num_tokens": 1694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.41629359743356725}}
{"text": "/**\n *  The definition of an abstraction class.\n *\n *  Created by Yinan Li on Aug. 30, 2017.\n *\n *  Hybrid Systems Group, University of Waterloo.\n */\n\n#ifndef _abstraction_h_\n#define _abstraction_h_\n\n#include <armadillo>\n#include <boost/dynamic_bitset.hpp>\n#include <functional>\n#include <set>\n\n#include \"transition.hpp\"\n#include \"system.hpp\"\n\n\nnamespace rocs {\n\n    // /**\n    //  * Boolean function defining a set.\n    //  */\n    // typedef bool (*gset)(const ivec &x);\n    \n    /**\n     * \\brief Weighting function (of edges) of transitions.\n     */\n    typedef double (*WGT)(std::vector<double> &x0,\n    \t\t\t  std::vector<double> &x1,\n    \t\t\t  std::vector<double> &u0);\n    \n    /**\n     * \\brief An abstraction class of a dynamical system.\n     *\n     * This is a template class where the typename %S will be replaced by the actual dynamical system type.\n     */\n    template<typename S>\n    class abstraction {\n\t\n    public:\n\tgrid _x;  /**< A grid of states */\n\tS *_ptrsys; /**< A pointer to the system object */\n\tstd::vector<int> _labels; /**< A vector of labels for the state grid _x */\n\tWGT _wf;  /**< Weighting callback function */\n\tfts _ts;  /**< The finite transition system */\n  \n\t/**\n\t * \\brief A constructor.\n\t *\n\t * Assign user defined system dynamics to an abstraction.\n\t *\n\t * @param[in] sys The pointer to a system object\n\t */\n\tabstraction(S *sys) : _x(sys->_xdim), _ptrsys(sys), _wf(NULL) {}\n\t/**\n\t * \\brief A constructor.\n\t *\n\t * Assign user defined system dynamics as well as a weighting function to an abstraction.\n\t *\n\t * @param[in] sys The pointer to a system object\n\t * @param[in] wf A weighting function\n\t */\n\tabstraction(S *sys, WGT wf) : _x(sys->_xdim), _ptrsys(sys), _wf(wf) {}\n\n\t/**\n\t * \\brief Initialize the states in the abstraction.\n\t *\n\t * This includes \n\t * - assigning a grid of states by the given bounds and grid size.\n\t * - assigning labels\n\t *\n\t * @param[in] eta An array of grid size\n\t * @param[in] xlb An array of lower bounds\n\t * @param[in] xub An array of upper bounds\n\t */\n\tvoid init_state(const double eta[], const double xlb[], const double xub[]) {\n\t    _x.gridding(eta, xlb, xub);\n\t    _labels.resize(_x._nv+1, 0); //the extra one is an out-of-domain node\n\t}\n\n\t/**\n\t * \\brief Initialize the finite transition system.\n\t *\n\t * Assign the number of predecessing (fts._npre) and successing (fts._npost) states.\n\t */\n\tbool init_transitions() {\n\t    if (_x._nv > 0 && _ptrsys->_ugrid._nv > 0) {\n\t\t_ts.init(_x._nv+1, _ptrsys->_ugrid._nv);\n\t    } else {\n\t\tstd::cout << \"Transition initialization failed: gridding problem.\\n\";\n\t\treturn false;\n\t    }\n\t    return true;\n\t}\n\t\n\t/**\n\t * \\brief Get state indicies of a given hyper-rectangle area.\n\t *\n\t * The area is given by its lower and upper bounds.\n\t * It is allowed to be out of domain, but only the inside domain part is considered.\n\t *\n\t * @param xlb The lower bound of the area\n\t * @param xub The upper bound of the area\n\t * @return a list of indicies.\n\t */\n\tstd::vector<size_t> get_discrete_states(const double xlb[], const double xub[]) {\n\t    ivec states(_x._dim);\n\t    for (int i = 0; i < _x._dim; ++i) {\n\t\tstates.setval(i, interval(xlb[i], xub[i]));\n\t    }\n\n\t    return _x.subset(states, false, false);  // allow area out of domain, and collect grids intersect the area\n\t}\n\n\t/**\n\t * Get discrete state indicies of a given area:\n\t * \\f$\\{x|g(x)=\\text{True}\\}\\f$.\n\t *\n\t * @param[in] g The function that determines if x is inside the set\n\t * @return a list of indicies.\n\t */\n\tstd::vector<size_t> get_discrete_states(std::function<bool(const ivec &)> g) {\n\t    std::vector<size_t> r;\n\t    if (_x._nv>0 && !_x._data.empty()) {\n\t\tivec x(_x._dim);\n\t\tfor (int i = 0; i < _x._nv; ++i) {\n\t\t    /* set interval x */\n\t\t    for (int j = 0; j < _x._dim; ++j) {\n\t\t\tx.setval(j, interval(_x._data[i][j]-_x._gw[j]/2, _x._data[i][j]+_x._gw[j]/2));\n\t\t    }\n\t\t    /* test */\n\t\t    if (g(x)) {\n\t\t\tr.push_back(i);\n\t\t    }\n\t\t}\n\t\t\n\t    } else {\n\t\tstd::cout << \"get_discrete_states: a grid of state space hasn't been iniitlized.\\n\";\n\t    }\n\t    return r;\n\t}\n\n\t/**\n\t * \\brief A template function that assigns labels to the state grid.\n\t *\n\t * @param[in] labeling A function that returns the label of a grid id\n\t */\n\ttemplate<typename F>\n\tvoid assign_labels(F labeling) {\n\t    for (size_t i = 0; i < _x._nv; ++i) {\n\t\tif(_labels[i] > -1)\n\t\t    _labels[i] = labeling(i);\n\t    }\n\t}\n\n\t/**\n\t * \\brief Assign the label to the out-of-domain part.\n\t *\n\t * @param[in] label The label given to the out-of-domain part\n\t */\n\tvoid assign_label_outofdomain(int label) {\n\t    _labels[_x._nv] = label;\n\t}\n\t\n\n\t/**\n\t * \\brief Assign transitions with robustness margins e1,e2.\n\t *\n\t * This function constructs an fts according to the given system.\n\t * \n\t * @param[in] e1 the robustness margin at the initial point.\n\t * @param[in] e2 the robustness margin at the end point.\n\t * @return whether construction is successful.\n\t */\n\tbool assign_transitions(const double e1[], const double e2[]) {\n\t    /* Initialize _ts (the transition system) */\n\t    if (!init_transitions())\n\t\treturn false;\n\t    int n = _x._dim;\n\t    size_t nx = _x._nv;\n\t    size_t nu = _ptrsys->_ugrid._nv;\n\t    // std::cout << \"dim=\" << n << ',' << \"#states=\" << nx << \",#inputs=\" << nu <<'\\n';\n\n\t    ivec ie2(n);\n\t    for (int j = 0; j < n; ++j)\n\t    \tie2.setval(j, interval(-e2[j],e2[j]));\n\n\t    std::vector<double> xmin(n), xmax(n);\n\t    for (int k = 0; k < n; ++k) {\n\t    \txmin[k] = _x._valmin[k]-_x._gw[k]/2.0;\n\t    \txmax[k] = xmin[k] + _x._gw[k]*_x._size[k];\n\t    }\n\t    ivec xbds(n);\n\t    for (int k = 0; k < n; ++k)\n\t\txbds.setval(k, interval(xmin[k], xmax[k]));\n\n\t    /* Out-of-domain indicator:\n\t     * 0:inside, 1:fully outside, 2:partially outside\n\t     */\n\t    std::vector<int> out_of_domain(nx*nu,0);\n\t\n\t    ivec y0(n);\n\t    std::vector<ivec> yt(nu, ivec(n));\n\t    std::vector<double> ytl(n), ytu(n);\n\t    size_t r, postid;\n\t    double idu;\n\t    std::vector<size_t> il(n), iu(n);\n\t    std::vector<size_t> stpost(nx*nu, 0), rngpost(nx*nu*n, 0);\n\t    \n\t    /* loop state grids */\n\t    for (size_t row = 0; row < nx; ++row) {\n\t\t/* the avoid points (labeled by -1) has no outgoing edges */\n\t\tif (_labels[row] == -1)\n\t\t    continue;\n\t\t/* compute reachable set */\n\t\tfor (int k = 0; k < n; ++k) {\n\t\t    y0.setval(k, interval(_x._data[row][k]-_x._gw[k]/2.0,\n\t\t    \t\t\t  _x._data[row][k]+_x._gw[k]/2.0));\n\t\t    // y0.setval(k, interval(_x._data[row][k]-_x._gw[k]/2.0-e1[k],\n\t\t    // \t\t\t  _x._data[row][k]+_x._gw[k]/2.0+e1[k]));\n\t\t}\t\t\n\t\t_ptrsys->get_reach_set(yt, y0);\n\t\tif (!yt.empty()) {\n\t\t    /* loop inputs */\n\t\t    for (size_t col = 0; col < nu; ++col) {\n\t\t\t// yt[col] += ie2;\n\t\t\t// /* Skip the yt[col] that is out of the domain _bds.\n\t\t\t//  * No need to delete the transitions to avoid area, since they are sinks.\n\t\t\t//  * */\n\t\t\t// if (!xbds.isin(yt[col]))\n\t\t\t//     continue;\n\t\t\t// /** Using this line will probably result in failure in synthesis **/\n\t\t\t// // if (!_x._bds.isin(yt[col]))\n\t\t\t// //     continue;\n\t\t\t\n\t\t\tif(xbds.isout(yt[col])) { //fully out of domain\n\t\t\t    out_of_domain[row*nu+col] = 1;\n\t\t\t    _ts._npost[row*nu+col] = 1;\n\t\t\t    _ts._ptrpost[row*nu+col] = _ts._ntrans;\n\t\t\t    ++_ts._ntrans;\n\t\t\t    continue;\n\t\t\t}\n\t\t\tif(!xbds.isin(yt[col])) {//partially inside domain\n\t\t\t    out_of_domain[row*nu+col] = 2;\n\t\t\t    /* Take intersection of xbds and yt[col] */\n\t\t\t    for(int k = 0; k < n; ++k) {\n\t\t\t\tytl[k] = yt[col][k].getinf()<xmin[k] ? xmin[k] : yt[col][k].getinf();\n\t\t\t\tytu[k] = yt[col][k].getsup()>xmax[k] ? xmax[k] : yt[col][k].getsup();\n\t\t\t    }\n\t\t\t} else { //fully inside domain\n\t\t\t    yt[col].getinf(ytl);\n\t\t\t    yt[col].getsup(ytu);\n\t\t\t}\n\t\t\t/* compute the indices of the bounds of the yt[col] */\n\t\t\t_ts._npost[row*nu + col] = 1;\n\t\t\tfor (int k = 0; k < n; ++k) {\n\t\t\t    il[k] = static_cast<size_t> ((ytl[k]-_x._valmin[k])/_x._gw[k]+0.5);\n\t\t\t    idu = (ytu[k]-_x._valmin[k])/_x._gw[k] + 0.5;\n\t\t\t    iu[k] = static_cast<size_t> (idu);\n\t\t\t    if (std::fabs(idu - iu[k]) < EPSIVAL)\n\t\t\t    \tiu[k] = iu[k] - 1;\n\t\t\t    // if (std::fabs(fmod(ytu[k]-_x._valmin[k], _x._gw[k]) - _x._gw[k]/2.) < EPSIVAL) /* fmod is slow */\n\t\t\t    // \tiu[k] = static_cast<size_t> ((ytu[k]-_x._valmin[k])/_x._gw[k]);\n\t\t\t    // else\n\t\t\t    // \tiu[k] = static_cast<size_t> ((ytu[k]-_x._valmin[k]+_x._gw[k]/2.0)/_x._gw[k]);\n\t\t\t    stpost[row*nu+col] += _x._base[k] * il[k]; /* compute the smallest post ID of all the post grid points */\n\t\t\t    rngpost[n*(row*nu+col)+k] = iu[k] - il[k] + 1;\n\t\t\t    _ts._npost[row*nu+col] *= rngpost[n*(row*nu+col)+k];\n\t\t\t}\n\t\t\t_ts._ptrpost[row*nu+col] = _ts._ntrans;\n\t\t\t_ts._ntrans += _ts._npost[row*nu+col];\n\n\t\t\t/* Add an out-of-domain transition */\n\t\t\tif(out_of_domain[row*nu+col]) {\n\t\t\t    ++_ts._npost[row*nu+col];\n\t\t\t    ++_ts._ntrans;\n\t\t\t}\n\t\t\t// /********** logging **********/\n\t\t\t// if(row == 0 && col == 16) {\n\t\t\t//     std::cout << \"y0=\" << y0 << '\\n'\n\t\t\t// \t      << \"yt=\" << yt[col] << '\\n'\n\t\t\t// \t      << \"out_of_domain=\" << out_of_domain[row*nu+col] << '\\n';\n\t\t\t//     if(out_of_domain[row*nu+col]>1) {\n\t\t\t// \tstd::cout << \"Intersection with domain: \";\n\t\t\t// \tfor(int k = 0; k < n; ++k)\n\t\t\t// \t    std::cout << '[' << ytl[k] << ',' << ytu[k] << \"] \";\n\t\t\t// \tstd::cout << '\\n';\n\t\t\t//     }\n\t\t\t//     std::cout << \"starting address of post transitions: \"\n\t\t\t// \t      << _ts._ptrpost[row*nu+col] << '\\n';\n\t\t\t//     std::cout << \"# of post transitions: \"\n\t\t\t// \t      << _ts._npost[row*nu+col] << '\\n';\n\t\t\t// }\n\t\t\t// /********** logging **********/\n\t\t    } // end input loop\n\t\t} else {\n\t\t    yt.resize(nu, ivec(n));\n\t\t}// end yt empty check\n\t    }  //end loop state grids\n\t    /* Assign out-of-domain posts */\n\t    if(_labels[nx] >= 0) {//assign a self-loop if the out-of-domain node is not avoided\n\t\tfor(size_t col = 0; col < nu; ++col) {\n\t\t    _ts._npost[nx*nu+col] = 1;\n\t\t    _ts._ptrpost[nx*nu+col] = _ts._ntrans;\n\t\t    ++_ts._ntrans;\n\t\t}\n\t    }\n\t    \n\t    /* assign _idpost, _cost and _npre */\n\t    _ts._idpost.resize(_ts._ntrans);\n\t    double w;\n\t    // for (size_t row = 0; row < nx; ++row) {\n\t    // \tfor (size_t col = 0; col < nu; ++col) {\n\t    // \t    /* assign post grid point IDs to _idpost */\n\t    // \t    if (_ts._npost[row*nu+col] == 0)\n\t    // \t\tcontinue;\n\t    // \t    for (int l = 0; l < _ts._npost[row*nu+col]; ++l) {\n\t    // \t\tpostid = stpost[row*nu+col];\n\t    // \t\tr = l;\n\t    // \t\tfor (int k = 0; k < n; ++k) {\n\t    // \t\t    postid += (r % rngpost[n*(row*nu+col)+k])*_x._base[k];\n\t    // \t\t    r = r / rngpost[n*(row*nu+col)+k];\n\t    // \t\t}\n\t    // \t\t_ts._idpost[_ts._ptrpost[row*nu+col]+l] = postid;\n\t    // \t\t/* assign cost (worst case): maximum from all posts */\n\t    // \t\tif (_wf) {\n\t    // \t\t    w = (*_wf)(_x._data[row], _x._data[postid], _ptrsys->_ugrid._data[col]);\n\t    // \t\t    _ts._cost[row*nu+col] = _ts._cost[row*nu+col]<w ? w : _ts._cost[row*nu+col];\n\t    // \t\t}\n\t\t\t\n\t    // \t\t_ts._npre[postid*nu+col] ++;\n\t    // \t    }\n\t    // \t} /* end for col */\n\t    // } /* end for row */\n\t    int num_post;\n\t    size_t ptrout;\n\t    for (size_t row = 0; row < nx; ++row) {\n\t\tfor (size_t col = 0; col < nu; ++col) {\n\t\t    // /********** logging **********/\n\t\t    // if(row == 0 && col == 16) {\n\t\t    // \tstd::cout << \"post nodes: \";\n\t\t    // }\n\t\t    // /********** logging **********/\n\t\t    /* assign post grid point IDs to _idpost */\n\t\t    if(out_of_domain[row*nu+col] != 1) {//intersect with domain\n\t\t\tif(out_of_domain[row*nu+col]) {\n\t\t\t    num_post = _ts._npost[row*nu+col] - 1;\n\t\t\t} else {\n\t\t\t    num_post = _ts._npost[row*nu+col];\n\t\t\t}\n\t\t\tfor (int l = 0; l < num_post; ++l) {\n\t\t\t    postid = stpost[row*nu+col];\n\t\t\t    r = l;\n\t\t\t    for (int k = 0; k < n; ++k) {\n\t\t\t\tpostid += (r % rngpost[n*(row*nu+col)+k])*_x._base[k];\n\t\t\t\tr = r / rngpost[n*(row*nu+col)+k];\n\t\t\t    }\n\t\t\t    _ts._idpost[_ts._ptrpost[row*nu+col]+l] = postid;\n\t\t\t    // /********** logging **********/\n\t\t\t    // if(row == 0 && col == 16) {\n\t\t\t    // \tstd::cout << \"ptrpost[\" << _ts._ptrpost[row*nu+col]+l << \"]=\"\n\t\t\t    // \t\t  << postid << '\\n';\n\t\t\t    // }\n\t\t\t    // /********** logging **********/\n\t\t\t    /* assign cost (worst case): maximum from all posts */\n\t\t\t    if (_wf) {\n\t\t\t\tw = (*_wf)(_x._data[row], _x._data[postid], _ptrsys->_ugrid._data[col]);\n\t\t\t\t_ts._cost[row*nu+col] = _ts._cost[row*nu+col]<w ? w : _ts._cost[row*nu+col];\n\t\t\t    }\n\t\t\t\n\t\t\t    ++_ts._npre[postid*nu+col];\n\t\t\t    // /********** logging **********/\n\t\t\t    // if(postid == 0 && col == 16)\n\t\t\t    // \tstd::cout << \"current # of predecessor of node x=0 under u=16: \"\n\t\t\t    // \t\t  << _ts._npre[postid*nu+col] << '\\n';\n\t\t\t    // /********** logging **********/\n\t\t\t}\n\t\t    }\n\t\t    if(out_of_domain[row*nu+col]) {//fully or partially out of domain\n\t\t\tptrout = _ts._ptrpost[row*nu+col]+_ts._npost[row*nu+col]-1;\n\t\t\t_ts._idpost[ptrout] = nx; //post node is xout\n\t\t\t++_ts._npre[nx*nu+col];\n\t\t\t// /********** logging **********/\n\t\t\t// if(row == 0 && col == 16) {\n\t\t\t//     std::cout << \"ptrpost[\" << ptrout << \"]=\"\n\t\t\t// \t      << nx << '\\n';\n\t\t\t// }\n\t\t\t// /********** logging **********/\n\t\t    }\n\t\t} /* end for col */\n\t    } /* end for row */\n\t    if(_labels[nx] >= 0) {//assign a self-loop if the out-of-domain node is not avoided\n\t\tfor(size_t col = 0; col < nu; ++col) {\n\t\t    _ts._idpost[_ts._ptrpost[nx*nu+col]] = nx; //xout is a sink\n\t\t    ++_ts._npre[nx*nu+col];\n\t\t}\n\t    }\n\t\n\t    /* Determine pre's by post's: loop _npost and _idpost */\n\t    _ts._idpre.resize(_ts._ntrans);  // initialize the size of pre's\n\t    /* assign _ptrpre by _npre */\n\t    size_t sum = 0;\n\t    for (size_t row = 0; row < nx+1; ++row) {\n\t\tfor (size_t col = 0; col < nu; ++col) {\n\t\t    _ts._ptrpre[row*nu+col] = sum;\n\t\t    sum += _ts._npre[row*nu+col];\n\t\t}\n\t    }\n\t    assert(sum == _ts._ntrans);\n\t    \n\t    /* assign _idpre */\n\t    std::vector<size_t> precount(nu*(nx+1), 0);\n\t    size_t idtspre;\n\t    for (size_t row = 0; row < nx+1; ++row) {\n\t\tfor (size_t col = 0; col < nu; ++col) {\n\t\t    // /********** logging **********/\n\t\t    // if (row == 0 && col == 16) {\n\t\t    // \tstd::cout << \"Assign pre transitions:\\n\";\n\t\t    // }\n\t\t    // /********** logging **********/\n\t\t    for (int ip = 0; ip < _ts._npost[row*nu+col]; ++ip) {\n\t\t\tpostid = _ts._idpost[_ts._ptrpost[row*nu+col]+ip];\n\t\t\tidtspre = postid * nu + col;\n\t\t\t_ts._idpre[_ts._ptrpre[idtspre]+precount[idtspre]++] = row;\n\t\t\t// precount[idtspre]++;\n\t\t\t// /********** logging **********/\n\t\t\t// if (row == 0 && col == 16) {\n\t\t\t//     std::cout << postid << \": idpre[\" << _ts._ptrpre[idtspre]\n\t\t\t// \t      << '+' << precount[idtspre]-1 << \"]=\"\n\t\t\t// \t      << row << '\\n';\n\t\t\t// }\n\t\t\t// if(_ts._ptrpre[idtspre]+precount[idtspre]-1 == 46) {\n\t\t\t//     std::cout << \"idpre[46] is filled at: \"\n\t\t\t// \t      << row << \"->(\" << col << \")->\" << postid\n\t\t\t// \t      << '\\n';\n\t\t\t// }\n\t\t\t// /********** logging **********/\n\t\t    }\n\t\t}\n\t    }\n\t    return true;\n\t}\n\t\n  \n\t/**\n\t * \\brief Assign transitions by subgridding.\n\t * see assign_transitions()\n\t *\n\t * @param[in] rp[] the pointer to an array of relative subgridding size\n\t * @return whether construction is successful.\n\t */\n\tbool assign_transitions_subgridding(const double rp[]) {\n\t    /*********** logging ***********/\n\t    // std::fstream logfile;\n\t    // logfile.open(\"y.log\", std::ios::out | std::ios::ate);\n\t    // std::fstream logfile2;\n\t    // logfile2.open(\"post946.log\", std::ios::out | std::ios::ate);\n\t    /*********** logging ***********/\n\t    if (!init_transitions())\n\t\treturn false;\n\t    int n = _x._dim;\n\t    size_t nx = _x._nv;\n\t    size_t nu = _ptrsys->_ugrid._nv;\n\t  \n\t    /* compute the number of sub grid points */\n\t    size_t subnv = 1;\n\t    std::vector<double> subgw(n);\n\t    std::vector<size_t> number(n);\n\t    for (int k = 0; k < n; ++k) {\n\t\tnumber[k] = ceil(1.0 / rp[k]);\n\t\tsubgw[k] = _x._gw[k] / number[k];\n\t\tsubnv *= number[k];\n\t    }\n\t    // std::cout << \"number of subgrids: \" << subnv << '\\n';\n    \n\t    /* transition computation by interval subgridding: loop states */\n\t    std::vector<double> xmin(n);\n\t    // std::vector<double> xc(n);\n\t    ivec v(n);\n\t    std::vector<size_t> subposts;\n\t    std::vector<std::vector<double>> sub(subnv, std::vector<double> (n));\n\t    std::vector<size_t>::iterator iter;\n\t    int np = 0;\n\t    /* loop state grids */\n\t    for (size_t row = 0; row < nx; ++row) {\n\t\tif (_labels[row] == -1) /* skip the avoid grid points (labeled by -1) */\n\t\t    continue;\n\t\t/* compute reachable set by interval subgridding */\n\t\tif (subnv == 1) {  // no subgridding\n\t\t    sub[0] = _x._data[row];\n\t\t} else {  // subnv > 1\n\t\t    for (int k = 0; k < n; ++k) {\n\t\t\t// xmin[k] = xc[k] - _gw[k]/2. + _rp[k]*_gw[k]/2.;\n\t\t\txmin[k] = _x._data[row][k] - _x._gw[k]/2. + subgw[k]/2.;\n\t\t    }\n\t\t    _x.griddingHelper(sub, xmin, subgw, number, subnv);\n\t\t}\n\t\tstd::vector< std::vector<ivec> > ys(subnv, std::vector<ivec> (nu));  // ys[vi][ui]\n\t\tfor (int vi = 0; vi < subnv; ++vi) {\n\t\t    for (int k = 0; k < n; ++k) {\n\t\t\tv.setval(k, interval(sub[vi][k]-subgw[k]/2, sub[vi][k]+subgw[k]/2));\n\t\t    } // assign v\n\t\t    /* get a list of post intervals w.r.t. different inputs */\n\t\t    _ptrsys->get_reach_set(ys[vi], v);\n\t\t} // end for loop (subgrid)\n\t\t\n\t\t/* loop inputs */\n\t\tfor (size_t col = 0; col < nu; ++col) {\n\t\t    std::set<size_t> posts;\n\t\t    /*********** logging ***********/\n\t\t    // logfile << col << \":\\n\";\n\t\t    /*********** logging ***********/\n\t    \n\t\t    /* loop subgrids: collect all unique posts */\n\t\t    for (int vi = 0; vi < subnv; ++vi) {\t\t\n\t\t\tsubposts = _x.subset(ys[vi][col], true, false);\n\t\t\tif (subposts.empty()) {  // out of domain\n\t\t\t    np = 0;\n\t\t\t    posts.clear();\n\t\t\t    break;  // jump out of the subgrid loop\n\t\t\t} else {\n\t\t\t    posts.insert(subposts.begin(), subposts.end());\n\t\t\t} // end if\n\t\t\t/*********** logging ***********/\n\t\t\t// logfile << ys[vi][col] << \"(\";\n\t\t\t// for (int i = 0; i < subposts.size(); ++i)\n\t\t\t//     logfile << subposts[i] << ',';\n\t\t\t// logfile << \")\\n\";\n\t\t\t/*********** logging ***********/\n\t\t    } // end collecting posts\n\n\t\t    /* assign posts */\n\t\t    if (!posts.empty()) {\n\t\t\t/*********** logging ***********/\n\t\t\t// logfile2 << col << '(' << posts.size() << \"): \";\n\t\t\t/*********** logging ***********/\n\t\t\t_ts._npost[row*nu + col] = posts.size();\n\t\t\t_ts._ptrpost[row*nu + col] = _ts._ntrans;\n\t\t\t_ts._ntrans += posts.size();\n\t\t\n\t\t\tfor (std::set<size_t>::iterator it = posts.begin(); it != posts.end(); ++it) {\n\t\t\t    _ts._idpost.push_back(*it);\n\t\t    \n\t\t\t    /* record the number of pres for state (*it) */\n\t\t\t    _ts._npre[(*it) * nu + col] ++;\n\t\t\t    /*********** logging ***********/\n\t\t\t    // logfile2 << *it << \", \";\n\t\t\t    /*********** logging ***********/\n\t\t\t}\n\t\t\t// logfile2 << '\\n';\n\t\t    }  // end transition assignment\n\t\t}  // end input loop\n\t\t// /*********** logging ***********/\n\t\t// logfile << '\\n';\n\t\t// /*********** logging ***********/\n\t\n\t    }  // end for loop states\n\n\t    std::cout << \"# of transitions: \" << _ts._ntrans << '\\n';\n\t    std::cout << \"length of _idpost: \" << _ts._idpost.size() << '\\n';\n\t    assert(_ts._idpost.size() == _ts._ntrans);\n\n\t    /* assign _cost */\n\t    double w;\n\t    size_t postid;\n\t    for (size_t row = 0; row < nx; ++row) {\n\t\tfor (size_t col = 0; col < nu; ++col) {\n\t\t    /* assign post grid point IDs to _idpost */\n\t\t    if (_ts._npost[row*nu+col] == 0)\n\t\t\tcontinue;\n\t\t    for (int l = 0; l < _ts._npost[row*nu+col]; ++l) {\n\t\t\t/* assign cost (worst case): maximum from all posts */\n\t\t\tpostid = _ts._ptrpost[row*nu+col]+l;\n\t\t\tif (_wf) {\n\t\t\t    w = (*_wf)(_x._data[row], _x._data[_ts._idpost[postid]], _ptrsys->_ugrid._data[col]);\n\t\t\t    _ts._cost[row*nu+col] = _ts._cost[row*nu+col]<w ? w : _ts._cost[row*nu+col];\n\t\t\t}\n\t\t    }\n\t\t} /* end for col */\n\t    } /* end for row */\n    \n\t    /* determine pre's by post's: loop _ts._npost and _idpost */\n\t    _ts._idpre.resize(_ts._ntrans);  // initialize the size of pre's\n\t    size_t sum = 0;\n\t    for (size_t row = 0; row < nx; ++row) {\n\t\tfor (size_t col = 0; col < nu; ++col) {\n\t\t    _ts._ptrpre[row*nu + col] = sum;\n\t\t    sum += _ts._npre[row*nu + col];\n\t\t}\n\t    }\n\t    /* assign _idpre */\n\t    std::vector<size_t> precount(_ptrsys->_ugrid._nv*_x._nv, 0);\n\t    size_t idtspre;\n\t    for (size_t row = 0; row < nx; ++row) {\n\t\tfor (size_t col = 0; col < nu; ++col) {\n\t\t    for (int ip = 0; ip < _ts._npost[row*nu + col]; ++ip) {\n\t\t\n\t\t\tidtspre = _ts._idpost[_ts._ptrpost[row*nu+col] + ip]*nu + col;\n\t\t\t_ts._idpre[_ts._ptrpre[idtspre] + precount[idtspre]] = row;\n\t\t\tprecount[idtspre] ++;\n\t\t    }\n\t\t}\n\t    }\n    \n\t    std::cout << \"length of _idpre: \" << _ts._idpre.size() << '\\n';\n\t    assert(_ts._idpre.size() == _ts._ntrans);\n\n\t    // logfile.close();\n\t    // logfile2.close();\n    \n\t    return true;\n\t}\n\t\n    }; /* the abstraction class */\n\n} // namespace rocs\n\n\n#endif\n", "meta": {"hexsha": "bdfd9e692cf583c6377af3102c082583e08167f3", "size": 20548, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/abstraction.hpp", "max_stars_repo_name": "yinanl/rocs", "max_stars_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/abstraction.hpp", "max_issues_repo_name": "yinanl/rocs", "max_issues_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/abstraction.hpp", "max_forks_repo_name": "yinanl/rocs", "max_forks_repo_head_hexsha": "bf2483903e39f4c0ea254a9ef56720a1259955ad", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9823434992, "max_line_length": 112, "alphanum_fraction": 0.5242359354, "num_tokens": 6858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4160257004378983}}
{"text": "// Boost.Polygon library voronoi_basic_tutorial.cpp file\n\n//          Copyright Andrii Sydorchuk 2010-2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n// See http://www.boost.org for updates, documentation, and revision history.\n\n#include <cstdio>\n#include <vector>\n\n#include <boost/polygon/voronoi.hpp>\nusing boost::polygon::voronoi_builder;\nusing boost::polygon::voronoi_diagram;\nusing boost::polygon::x;\nusing boost::polygon::y;\nusing boost::polygon::low;\nusing boost::polygon::high;\n\n#include \"voronoi_visual_utils.hpp\"\n\nstruct Point {\n  int a;\n  int b;\n  Point(int x, int y) : a(x), b(y) {}\n};\n\nstruct Segment {\n  Point p0;\n  Point p1;\n  Segment(int x1, int y1, int x2, int y2) : p0(x1, y1), p1(x2, y2) {}\n};\n\nnamespace boost {\nnamespace polygon {\n\ntemplate <>\nstruct geometry_concept<Point> {\n  typedef point_concept type;\n};\n\ntemplate <>\nstruct point_traits<Point> {\n  typedef int coordinate_type;\n\n  static inline coordinate_type get(\n      const Point& point, orientation_2d orient) {\n    return (orient == HORIZONTAL) ? point.a : point.b;\n  }\n};\n\ntemplate <>\nstruct geometry_concept<Segment> {\n  typedef segment_concept type;\n};\n\ntemplate <>\nstruct segment_traits<Segment> {\n  typedef int coordinate_type;\n  typedef Point point_type;\n\n  static inline point_type get(const Segment& segment, direction_1d dir) {\n    return dir.to_int() ? segment.p1 : segment.p0;\n  }\n};\n}  // polygon\n}  // boost\n\n// Traversing Voronoi edges using edge iterator.\nint iterate_primary_edges1(const voronoi_diagram<double>& vd) {\n  int result = 0;\n  for (voronoi_diagram<double>::const_edge_iterator it = vd.edges().begin();\n       it != vd.edges().end(); ++it) {\n    if (it->is_primary())\n      ++result;\n  }\n  return result;\n}\n\n// Traversing Voronoi edges using cell iterator.\nint iterate_primary_edges2(const voronoi_diagram<double> &vd) {\n  int result = 0;\n  for (voronoi_diagram<double>::const_cell_iterator it = vd.cells().begin();\n       it != vd.cells().end(); ++it) {\n    const voronoi_diagram<double>::cell_type& cell = *it;\n    const voronoi_diagram<double>::edge_type* edge = cell.incident_edge();\n    // This is convenient way to iterate edges around Voronoi cell.\n    do {\n      if (edge->is_primary())\n        ++result;\n      edge = edge->next();\n    } while (edge != cell.incident_edge());\n  }\n  return result;\n}\n\n// Traversing Voronoi edges using vertex iterator.\n// As opposite to the above two functions this one will not iterate through\n// edges without finite endpoints and will iterate only once through edges\n// with single finite endpoint.\nint iterate_primary_edges3(const voronoi_diagram<double> &vd) {\n  int result = 0;\n  for (voronoi_diagram<double>::const_vertex_iterator it =\n       vd.vertices().begin(); it != vd.vertices().end(); ++it) {\n    const voronoi_diagram<double>::vertex_type& vertex = *it;\n    const voronoi_diagram<double>::edge_type* edge = vertex.incident_edge();\n    // This is convenient way to iterate edges around Voronoi vertex.\n    do {\n      if (edge->is_primary())\n        ++result;\n      edge = edge->rot_next();\n    } while (edge != vertex.incident_edge());\n  }\n  return result;\n}\n\nint main() {\n  // Preparing Input Geometries.\n  std::vector<Point> points;\n  points.push_back(Point(0, 0));\n  points.push_back(Point(1, 6));\n  std::vector<Segment> segments;\n  segments.push_back(Segment(-4, 5, 5, -1));\n  segments.push_back(Segment(3, -11, 13, -1));\n\n  // Construction of the Voronoi Diagram.\n  voronoi_diagram<double> vd;\n  construct_voronoi(points.begin(), points.end(),\n                    segments.begin(), segments.end(),\n                    &vd);\n\n  // Traversing Voronoi Graph.\n  {\n    printf(\"Traversing Voronoi graph.\\n\");\n    printf(\"Number of visited primary edges using edge iterator: %d\\n\",\n        iterate_primary_edges1(vd));\n    printf(\"Number of visited primary edges using cell iterator: %d\\n\",\n        iterate_primary_edges2(vd));\n    printf(\"Number of visited primary edges using vertex iterator: %d\\n\",\n        iterate_primary_edges3(vd));\n    printf(\"\\n\");\n  }\n\n  // Using color member of the Voronoi primitives to store the average number\n  // of edges around each cell (including secondary edges).\n  {\n    printf(\"Number of edges (including secondary) around the Voronoi cells:\\n\");\n    for (voronoi_diagram<double>::const_edge_iterator it = vd.edges().begin();\n         it != vd.edges().end(); ++it) {\n      std::size_t cnt = it->cell()->color();\n      it->cell()->color(cnt + 1);\n    }\n    for (voronoi_diagram<double>::const_cell_iterator it = vd.cells().begin();\n         it != vd.cells().end(); ++it) {\n      printf(\"%lu \", it->color());\n    }\n    printf(\"\\n\");\n    printf(\"\\n\");\n  }\n\n  // Linking Voronoi cells with input geometries.\n  {\n    unsigned int cell_index = 0;\n    for (voronoi_diagram<double>::const_cell_iterator it = vd.cells().begin();\n         it != vd.cells().end(); ++it) {\n      if (it->contains_point()) {\n        if (it->source_category() ==\n            boost::polygon::SOURCE_CATEGORY_SINGLE_POINT) {\n          std::size_t index = it->source_index();\n          Point p = points[index];\n          printf(\"Cell #%u contains a point: (%d, %d).\\n\",\n                 cell_index, x(p), y(p));\n        } else if (it->source_category() ==\n                   boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT) {\n          std::size_t index = it->source_index() - points.size();\n          Point p0 = low(segments[index]);\n          printf(\"Cell #%u contains segment start point: (%d, %d).\\n\",\n                 cell_index, x(p0), y(p0));\n        } else if (it->source_category() ==\n                   boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT) {\n          std::size_t index = it->source_index() - points.size();\n          Point p1 = high(segments[index]);\n          printf(\"Cell #%u contains segment end point: (%d, %d).\\n\",\n                 cell_index, x(p1), y(p1));\n        }\n      } else {\n        std::size_t index = it->source_index() - points.size();\n        Point p0 = low(segments[index]);\n        Point p1 = high(segments[index]);\n        printf(\"Cell #%u contains a segment: ((%d, %d), (%d, %d)). \\n\",\n               cell_index, x(p0), y(p0), x(p1), y(p1));\n      }\n      ++cell_index;\n    }\n  }\n  return 0;\n}\n", "meta": {"hexsha": "84f0e4687e145829a9def6f1e99b2816e5f8e644", "size": 6338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/polygon/example/voronoi_basic_tutorial.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/polygon/example/voronoi_basic_tutorial.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/polygon/example/voronoi_basic_tutorial.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 31.8492462312, "max_line_length": 80, "alphanum_fraction": 0.6341117072, "num_tokens": 1638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.6723316926137812, "lm_q1q2_score": 0.4160256963752924}}
{"text": "/**\n * @file \tSteinerTreeHeuristic.cpp\n * @author \tFabian Wegscheider\n * @date \tJul 14, 2017\n */\n\n#include <sstream>\n#include <boost/heap/priority_queue.hpp>\n#include \"SteinerTreeHeuristic.h\"\n\nusing std::pair;\ntypename graph_traits<Graph>::out_edge_iterator it, itEnd;\n\n\n/**\n * Data that is stored in one node of the heap. Contains an integer and a double.\n * Comparisons are made by the double, smaller has higher priority\n */\nstruct heapData\n{\n\tpair<int,double> data;\n\n    heapData(pair<int,double> p):\n        data(p)\n    {}\n\n    bool operator<(heapData const & rhs) const {\n        return data.second > rhs.data.second;\n    }\n};\n\n\n/*\n * Implementation of the improved Shortest-Path-Heuristic. A standard binary heap\n * from boost is used and keys are never decreased, but instead new nodes are pushed\n * whenever a better path is found. The resulting tree is stored implicitly in\n * treePredecessors.\n */\ndouble SteinerTreeHeuristic::computeSteinerTree(Graph& g, int numVertices,\n\t\tint treePredecessors[], vector<int>& terminals, int root) {\n\n\tassert(NULL != treePredecessors);\n\n\t//terminals are scanned\n\tint numTerminals = terminals.size();\n\tbool* isTerminal = new bool[numVertices]();\n\tfor (int i = 0; i < numTerminals; ++i) {\n\t\tassert(terminals[i] < numVertices);\n\t\tisTerminal[terminals[i]] = true;\n\t}\n\n\tif (!isTerminal[root]) {\n\t\tdelete[] isTerminal;\n\t\treturn -1;\n\t}\n\n\theap::priority_queue<heapData> heap;\n\n\tdouble* distances = new double[numVertices];\n\tint* predecessors = new int[numVertices];\n\tpredecessors[root] = root;\n\tdouble treeCost = 0.;\n\n\t//initialization of heap, distance array and predecessors array. note: a -1\n\t//in predecessors means that the vertex has not been connected to the tree yet\n\tfor (int i = 0; i < numVertices; ++i) {\n\t\tif (i == root) {\n\t\t\theap.push(std::make_pair(i,0.));\n\t\t\tdistances[i] = 0.;\n\t\t\ttreePredecessors[i] = root;\n\t\t} else {\n\t\t\theap.push(std::make_pair(i, std::numeric_limits<double>::infinity()));\n\t\t\tdistances[i] = std::numeric_limits<double>::infinity();\n\t\t\ttreePredecessors[i] = -1;\n\t\t}\n\t}\n\n\tproperty_map<Graph, edge_weight_t>::type weights = get(edge_weight, g);\n\tproperty_map<Graph, vertex_index_t>::type index = get(vertex_index, g);\n\n\n\tint connectedTerminals = 1;\n\n\n\t//here the actual algorithm starts\n\twhile (connectedTerminals < numTerminals) {\n\t\tassert(!heap.empty());\t//heap should never be empty before tree contains all terminals\n\n\t\tpair<int,double> min = heap.top().data;\n\t\theap.pop();\n\n\n\t\t//if we scan a terminal, all vertices on shortest path to subtree\n\t\t//are added to heap with weight 0 and included into the tree\n\t\tif (min.first != root && isTerminal[min.first] && treePredecessors[min.first] == -1) {\n\t\t\t++connectedTerminals;\n\n\t\t\tmin.second = 0.;\n\t\t\tint nextVertex = predecessors[min.first];\n\t\t\ttreePredecessors[min.first] = predecessors[min.first];\n\n\t\t\tauto edgeInfo = edge(predecessors[min.first], min.first, g);\n\t\t\tassert(edgeInfo.second);\n\t\t\ttreeCost += weights[edgeInfo.first];\n\n\t\t\t//here all vertices on path from new terminal to tree are added again with key=0\n\t\t\twhile (treePredecessors[nextVertex] == -1) {\n\t\t\t\theap.push(std::make_pair(nextVertex, 0.));\n\t\t\t\ttreePredecessors[nextVertex] = predecessors[nextVertex];\n\t\t\t\ttreeCost += weights[edge(predecessors[nextVertex], nextVertex, g).first];\n\t\t\t\tnextVertex = predecessors[nextVertex];\n\t\t\t}\n\t\t}\n\n\t\t//this is basicalles the usual dijkstra with pushes instead of decreasekey operations\n\t\tfor (tie(it, itEnd) = out_edges(*(vertices(g).first+min.first), g);\n\t\t\t\tit != itEnd; ++it) {\n\t\t\tdouble tmp = min.second + weights[*it];\n\t\t\tint targetIndex = index[target(*it, g)];\n\t\t\t//we only consider vertices which have not been added to the tree yet\n\t\t\tif (treePredecessors[targetIndex] == -1 && tmp < distances[targetIndex]) {\n\t\t\t\tdistances[targetIndex] = tmp;\n\t\t\t\tpredecessors[targetIndex] = min.first;\n\t\t\t\theap.push(std::make_pair(targetIndex, tmp));\n\t\t\t}\n\t\t}\n\t}\n\n\tdelete[] isTerminal;\n\tdelete[] distances;\n\tdelete[] predecessors;\n\n\treturn treeCost;\n}\n\n\n\nbool SteinerTreeHeuristic::testAndPrintTree(Graph& g, int numVertices, int treePredecessors[],\n\t\tvector<int>& terminals, int root, string& edgeString) {\n\n\tstd::stringstream stream;\n\tbool* visited = new bool[numVertices]();\n\n\tfor (unsigned int i = 0; i < terminals.size(); ++i) {\n\t\tint curr = terminals[i];\n\t\tint vertexCount = 1;\n\t\tint edgeCount = 0;\n\t\twhile (curr != root && vertexCount != numVertices && curr != -1) {\n\t\t\tif (!visited[curr]) {\n\t\t\t\t++edgeCount;\n\t\t\t\t//edges are added to string and every 50 lines a linebreak is\n\t\t\t\t//added for the sake of readability\n\t\t\t\tif (edgeCount % 50 == 0) stream << std::endl;\n\t\t\t\tstream << \"(\" << curr << \",\" << treePredecessors[curr] << \") \";\n\t\t\t}\n\t\t\tcurr = treePredecessors[curr];\n\t\t\t++vertexCount;\n\t\t}\n\n\t\t//if a cycle is found or not all terminals are connected, result is false\n\t\tif (vertexCount == numVertices || curr == -1){\n\t\t\tdelete[] visited;\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tedgeString = stream.str();\n\n\tdelete[] visited;\n\treturn true;\n}\n\n\n\nbool SteinerTreeHeuristic::testTree(Graph& g, int numVertices, int treePredecessors[],\n\t\tvector<int>& terminals, int root) {\n\n\t\tbool* visited = new bool[numVertices]();\n\n\t\tfor (unsigned int i = 0; i < terminals.size(); ++i) {\n\t\t\tint curr = terminals[i];\n\t\t\tint vertexCount = 1;\n\t\t\tint edgeCount = 0;\n\t\t\twhile (curr != root && vertexCount != numVertices && curr != -1) {\n\t\t\t\tif (!visited[curr]) ++edgeCount;\n\t\t\t\tcurr = treePredecessors[curr];\n\t\t\t\t++vertexCount;\n\t\t\t}\n\n\t\t\t//if a cycle is found or not all terminals are connected, result is false\n\t\t\tif (vertexCount == numVertices || curr == -1){\n\t\t\t\tdelete[] visited;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tdelete[] visited;\n\t\treturn true;\n}\n\n\n\n", "meta": {"hexsha": "22a3ae113c24786d63e76ee1baca632fabce5d6a", "size": 5645, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Wegscheider/ex9/SteinerTreeHeuristic.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "Wegscheider/ex9/SteinerTreeHeuristic.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "Wegscheider/ex9/SteinerTreeHeuristic.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 27.8078817734, "max_line_length": 94, "alphanum_fraction": 0.6790079717, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6187804337438502, "lm_q1q2_score": 0.4160256923126865}}
{"text": "/**\n * This file contains an example of graphlab used for gibbs sampling\n * in a pairwise markov random field to denoise a synthetic noisy\n * image.\n *\n *  \\author Joseph Gonzalez\n */\n\n// INCLUDES ===================================================================>\n\n// Including Standard Libraries\n#include <cstdlib>\n#include <cassert>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <limits>\n#include <cmath>\n\n#include <boost/program_options.hpp>\n#include <boost/bind.hpp>\n\n#include <graphlab.hpp>\n\n// ============================================================================>\n//  Support code for loopy belief propagation\n#include \"image.hpp\"\n\n// Include the macro for the for each operation\n#include <graphlab/macros_def.hpp>\n\n// Determine the shared ata location of the shared edge factor and the\n// number of samples\nenum constants {EDGE_FACTOR_ID, NUM_SAMPLES_ID};\n\n// STRUCTS (Edge and Vertex data) =============================================>\n/**\n * The data associated with each variable in the pairwise markov\n * random field\n */\nstruct vertex_data {\n  size_t asg;\n  size_t updates;\n  unsigned char color;\n  graphlab::unary_factor potential;\n  //! store the Roa-Blackwell conditional belief estimate\n  graphlab::unary_factor belief;\n  std::vector<double> counts;\n  vertex_data() :\n    asg(0), updates(0), color(0) { }\n}; // End of vertex data\n\n/**\n * The data associated with each directed edge in the pairwise markov\n * random field\n */\nstruct edge_data { }; \n\n\ntypedef graphlab::graph< vertex_data, edge_data> graph_type;\ntypedef graphlab::types<graph_type> gl;\n\n\n// GraphLab Update Function ===================================================>\n\n/** Construct denoising ising model based on the image */\nvoid construct_graph(image& img,\n                     size_t num_rings,\n                     double sigma,\n                     gl::graph& graph);\n\n/** \n * The core belief propagation update function.  This update satisfies\n * the graphlab update_function interface.  \n */\ntemplate<bool UseCallback>\nvoid gibbs_update(gl::iscope& scope, \n                  gl::icallback& scheduler,\n                  gl::ishared_data* shared_data);\n\n/**\n *  The colore schedule is used by the set scheduler to describe an\n *  execution that updates all vertices of the same color (given by a\n *  checkerboard) pattern) in parallel.\n */\nvoid color_schedule(gl::set_scheduler &sched);\n// This ugly global variable is needed for the color_schedule\nsize_t nsamples;\n\n\n\n// Command Line Parsing =======================================================>\nstruct options {\n  size_t ncpus;\n  size_t samples;\n  size_t num_rings;\n  size_t rows;\n  size_t cols;\n  double sigma;\n  double lambda;\n  std::string smoothing;\n  std::string engine;\n  std::string scope;\n  std::string scheduler;\n  std::string orig_fn;\n  std::string noisy_fn;\n  std::string rb_pred_fn;\n  std::string counts_pred_fn;\n  std::string pred_type;\n};\n\n\n/**\n * Parse the command line arguments.  Returns false if there was a\n * problem in parsing command line arguments\n */    \nbool parse_command_line(int argc, char** argv, options& opts);\n\n\n/**\n * Display the program options\n */\nvoid display_options(options& opts);\n\n// MAIN =======================================================================>\nint main(int argc, char** argv) {\n  std::cout << \"This program uses gibbs sampling to denoise a synthetic image.\"\n            << std::endl;\n\n  // set the global logger\n  global_logger().set_log_level(LOG_WARNING);\n  global_logger().set_log_to_console(true);\n\n  // Parse command line arguments --------------------------------------------->\n  options opts; \n  bool success = parse_command_line(argc, argv, opts);\n  if(!success)  return EXIT_FAILURE;\n  display_options(opts);\n\n  // Create synthetic images -------------------------------------------------->\n  // Creating image for denoising\n  std::cout << \"Creating a synethic image.\" << std::endl;\n  image img(opts.rows, opts.cols);\n  img.paint_sunset(opts.num_rings);\n  std::cout << \"Saving image. \" << std::endl;\n  img.save(opts.orig_fn.c_str());\n  std::cout << \"Corrupting Image. \" << std::endl;\n  img.corrupt(opts.sigma);\n  std::cout << \"Saving corrupted image. \" << std::endl;\n  img.save(opts.noisy_fn.c_str());\n  img.save_vec(\"corrupted.tsv\");\n  \n  \n  // Create the graph --------------------------------------------------------->\n  gl::graph graph;\n  std::cout << \"Constructing pairwise Markov Random Field. \" << std::endl;\n  construct_graph(img, opts.num_rings, opts.sigma, graph);\n  image coloring_img(opts.rows, opts.cols);\n  for(size_t i = 0; i < graph.num_vertices(); ++i)\n    coloring_img.pixel(i) = graph.vertex_data(i).color;\n  coloring_img.save(\"coloring.pgm\");\n  \n \n\n\n  \n\n  // Setup global shared variables -------------------------------------------->\n  gl::thread_shared_data sdm;\n  // Initialize the edge agreement factor \n  std::cout << \"Initializing shared edge agreement factor. \" << std::endl;\n  // dummy variables 0 and 1 and num_rings by num_rings\n  graphlab::binary_factor edge_potential(0, opts.num_rings,\n                                         0, opts.num_rings);\n\n  // Set the smoothing type\n  if(opts.smoothing == \"square\") {\n    edge_potential.set_as_agreement(opts.lambda);\n  } else if (opts.smoothing == \"laplace\") {\n    edge_potential.set_as_laplace(opts.lambda);\n  } else {\n    std::cout << \"Invalid smoothing stype!\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  std::cout << edge_potential << std::endl;\n  sdm.set_constant(EDGE_FACTOR_ID, graphlab::any(edge_potential));\n  sdm.set_constant(NUM_SAMPLES_ID, graphlab::any(opts.samples));\n\n\n    \n  \n  // Create the engine -------------------------------------------------------->\n  gl::iengine* engine = NULL;\n  if(opts.scheduler == \"set\") {\n    nsamples = opts.samples;\n    \n    // Here we use the set scheduler which has some additional special setup\n    engine =\n      graphlab::engine_factory::new_engine(opts.engine,\n                                           \"set\",\n                                           \"null\",\n                                           graph,\n                                           opts.ncpus);\n    if(engine == NULL) {\n      std::cout << \"Unable to construct engine!\" << std::endl;\n      return EXIT_FAILURE;   \n    }\n    // Set the shared data manager for the engine\n    engine->set_shared_data_manager(&sdm);\n    // Attach the correct schedule\n    engine->get_scheduler().set_option(gl::scheduler_options::SCHEDULING_FUNCTION, \n                                       (void*)color_schedule);\n    \n  } else {\n    // Here we use the other schedulers which use a more default setup\n    engine =\n      graphlab::engine_factory::new_engine(opts.engine,\n                                           opts.scheduler,\n                                           opts.scope,\n                                           graph,\n                                           opts.ncpus);\n    if(engine == NULL) {\n      std::cout << \"Unable to construct engine!\" << std::endl;\n      return EXIT_FAILURE;   \n    }\n    // Set the shared data manager for the engine\n    engine->set_shared_data_manager(&sdm);\n\n    // Create a shuffled set of vertices\n    std::vector<gl::vertex_id_t> vertex_ids(opts.rows * opts.cols);\n    for(size_t i = 0; i < vertex_ids.size(); ++i) vertex_ids[i] = i;\n    std::random_shuffle(vertex_ids.begin(), vertex_ids.end());\n\n    // Add the tasks in shuffled order (helps with fifo scheduler)\n    const bool use_callback = true;\n    double residual = 1.0;\n    engine->get_scheduler().add_tasks(vertex_ids,\n                                      gibbs_update<use_callback>,\n                                      residual);\n  }\n\n  \n  // Running the engine ------------------------------------------------------->\n  std::cout << \"Running the engine. \" << std::endl;\n  graphlab::timer timer; timer.start(); \n  engine->start();\n  double runtime = timer.current_time();\n  size_t update_count = engine->last_update_count();\n  std::cout << \"Finished Running engine in \" << runtime \n            << \" seconds.\" << std::endl\n            << \"Total updates: \" << update_count << std::endl\n            << \"Efficiency: \" << (double(update_count) / runtime)\n            << \" updates per second \"\n            << std::endl;\n\n  \n  // Saving the output -------------------------------------------------------->\n  std::cout << \"Rendering the cleaned image. \" << std::endl;\n  image rb_img(opts.rows, opts.cols);\n  image counts_img(opts.rows, opts.cols);\n  if(opts.pred_type == \"map\") {\n    for(size_t v = 0; v < graph.num_vertices(); ++v) {\n      const vertex_data& vdata = graph.vertex_data(v);\n      rb_img.pixel(v) = vdata.belief.max_asg();\n      counts_img.pixel(v) =\n        std::max_element(vdata.counts.begin(), vdata.counts.end()) -\n        vdata.counts.begin();\n        \n    }\n  } else if(opts.pred_type == \"exp\") {\n    for(size_t v = 0; v < graph.num_vertices(); ++v) {\n      const vertex_data& vdata = graph.vertex_data(v);    \n      rb_img.pixel(v) = vdata.belief.expectation();\n      double expectation = 0;\n      for(size_t i = 0; i < vdata.counts.size(); ++i)\n        expectation += i * vdata.counts[i];\n      counts_img.pixel(v) = expectation;\n    }\n  } else {\n    std::cout << \"Invalid prediction type! : \" << opts.pred_type\n              << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  \n  std::cout << \"Saving cleaned image. \" << std::endl;\n  rb_img.save(opts.rb_pred_fn.c_str());\n  counts_img.save(opts.counts_pred_fn.c_str());\n  \n  std::cout << \"Done!\" << std::endl;\n  return EXIT_SUCCESS;\n} // End of main\n\n\n\n// Implementations ============================================================>\ntemplate<bool UseCallback>\nvoid gibbs_update(gl::iscope& scope, \n                  gl::icallback& scheduler,\n                  gl::ishared_data* shared_data) {\n\n  assert(shared_data != NULL);\n  // Get the shared data\n  size_t samples = shared_data->get_constant(NUM_SAMPLES_ID).as<size_t>();\n  \n\n  // Grab the state from the scope -------------------------------------------->\n  // Get the vertex data\n  vertex_data& vdata = scope.vertex_data();\n\n  // If this vertex has been updated sufficiently often then we don't\n  // update again\n  if(vdata.updates >= samples) return;  \n\n  // Construct the conditional------------------------------------------------->\n  // Initialize the conditional as the node potential\n  graphlab::unary_factor conditional(vdata.potential);\n\n  const graphlab::binary_factor& edge_factor =\n    shared_data->get_constant(EDGE_FACTOR_ID).as<graphlab::binary_factor>();\n\n  \n  // Condition on all neighbor assignments\n  foreach(graphlab::edge_id_t edgeid, scope.in_edge_ids()) {\n    graphlab::vertex_id_t source = scope.source(edgeid);\n    // Get the neighboring assignment\n    const vertex_data& neighbor = scope.neighbor_vertex_data(source);\n    // Get the edge factor\n    conditional.condition(edge_factor, neighbor.asg);\n    conditional.normalize();\n  }\n  \n  // Generate a sample -------------------------------------------------------->\n  size_t sample = conditional.sample();\n  vdata.asg = sample;  // Record the sample\n  vdata.updates++;     // Increment the updates\n  vdata.counts[vdata.asg]++; // increment the counts\n  \n  // Rao-Blackwell belief estimate \n  vdata.belief.plus(conditional);\n  \n  // Finalize belief on last update ------------------------------------------->\n  if(vdata.updates == samples ) { // If this is the last update\n    vdata.belief.normalize();\n    double Z = 0;\n    for(size_t i = 0; i < vdata.counts.size(); ++i)\n      Z += vdata.counts[i];\n    for(size_t i = 0; i < vdata.counts.size(); ++i)\n      vdata.counts[i] /= Z;\n  } else if(UseCallback) {\n    // Otherwise reschedule self\n    double residual = 1.0;\n    gl::update_task task(scope.vertex(), gibbs_update<UseCallback> );      \n    scheduler.add_task(task, residual);\n  }\n} // end of BP_update\n\n\n\nbool parse_command_line(int argc, char** argv, options& opts) {\n  // Because typing is painful\n  namespace boost_po = boost::program_options;\n  // Create a description for this program\n  boost_po::options_description\n    desc(\"Denoise a randomly generated image using Gibbs Sampling.\");\n  // Set the program options\n  desc.add_options()\n    (\"help\",   \"produce this help message\")\n    (\"ncpus\",  boost_po::value<size_t>(&(opts.ncpus))->default_value(2),\n     \"Number of cpus to use.\")\n    (\"samples\",  boost_po::value<size_t>(&(opts.samples))->default_value(100),\n     \"Number of samples to generate\")\n    (\"rings\",  boost_po::value<size_t>(&(opts.num_rings))->default_value(5),\n     \"Number of rings in the noisy image\")\n    (\"rows\",  boost_po::value<size_t>(&(opts.rows))->default_value(200),\n     \"Number of rows in the noisy image\")\n    (\"cols\",  boost_po::value<size_t>(&(opts.cols))->default_value(200),\n     \"Number of columns in the noisy image\")\n    (\"sigma\",  boost_po::value<double>(&(opts.sigma))->default_value(1.2),\n     \"Standard deviation of noise.\")\n    (\"lambda\",  boost_po::value<double>(&(opts.lambda))->default_value(3),\n     \"Smoothness parameter (larger => smoother).\")\n    (\"smoothing\",\n     boost_po::value<std::string>(&(opts.smoothing))->default_value(\"square\"),\n     \"Options are {square, laplace}\")\n    (\"engine\",\n     boost_po::value<std::string>(&(opts.engine))->default_value(\"threaded\"),\n     \"Options are {threaded, sequential}\")\n    (\"scope\",\n     boost_po::value<std::string>(&(opts.scope))->default_value(\"edge\"),\n     \"Options are {vertex, edge, full}\")\n    (\"scheduler\",\n     boost_po::value<std::string>(&(opts.scheduler))->default_value(\"fifo\"),\n     \"Options are {fifo, priority, sampling}\")\n    (\"orig\",\n     boost_po::value<std::string>(&(opts.orig_fn))->default_value(\"source_img.pgm\"),\n     \"Original image file name.\")\n    (\"noisy\",\n     boost_po::value<std::string>(&(opts.noisy_fn))->default_value(\"noisy_img.pgm\"),\n     \"Noisy image file name.\")\n    (\"rb_pred\",\n     boost_po::value<std::string>(&(opts.rb_pred_fn))->\n     default_value(\"rb_pred_img.pgm\"),\n     \"Predicted image file name for the Rao-Blackwell estimator.\")\n    (\"counts_pred\",\n     boost_po::value<std::string>(&(opts.counts_pred_fn))->\n     default_value(\"counts_pred_img.pgm\"),\n     \"Predicted image file name for the raw counts estimator.\")\n    (\"pred_type\",\n     boost_po::value<std::string>(&(opts.pred_type))->default_value(\"map\"),\n     \"Predicted image type {map, exp}\");\n  // Parse the arguments\n  boost_po::variables_map vm;\n  boost_po::store(boost_po::parse_command_line(argc, argv, desc), vm);\n  boost_po::notify(vm);\n  if(vm.count(\"help\")) {\n    std::cout << desc << std::endl;\n    return false;\n  }\n  return true;\n} // end of parse command line arguments\n\n\nvoid display_options(options& opts) {\n  std::cout << \"ncpus:          \" << opts.ncpus << std::endl\n            << \"samples:        \" << opts.samples << std::endl\n            << \"num_rings:      \" << opts.num_rings << std::endl\n            << \"rows:           \" << opts.rows << std::endl\n            << \"cols:           \" << opts.cols << std::endl\n            << \"sigma:          \" << opts.sigma << std::endl\n            << \"lambda:         \" << opts.lambda << std::endl\n            << \"smoothing:      \" << opts.smoothing << std::endl\n            << \"engine:         \" << opts.engine << std::endl\n            << \"scope:          \" << opts.scope << std::endl\n            << \"scheduler:      \" << opts.scheduler << std::endl\n            << \"orig_fn:        \" << opts.orig_fn << std::endl\n            << \"noisy_fn:       \" << opts.noisy_fn << std::endl\n            << \"rb_pred_fn:     \" << opts.rb_pred_fn << std::endl\n            << \"counts_pred_fn: \" << opts.counts_pred_fn << std::endl\n            << \"pred_type:      \" << opts.pred_type << std::endl;\n}\n\n\n\n// STRUCTS (Edge and Vertex data) =============================================>\n\nvoid construct_graph(image& img,\n                     size_t num_rings,\n                     double sigma,\n                     gl::graph& graph) {\n\n  // Initialize the vertex data to somethine sensible\n  vertex_data vdata;\n\n  vdata.belief.resize(num_rings);\n  vdata.belief.uniform(-std::numeric_limits<double>::max());\n  vdata.potential.resize(num_rings);\n  vdata.potential.uniform();\n  vdata.potential.normalize();\n  vdata.counts.resize(num_rings, 0);\n  for(size_t i = 0; i < num_rings; ++i)\n    vdata.counts[i] = 0;\n\n        \n  // Add all the vertices\n  double sigmaSq = sigma*sigma;\n  for(size_t i = 0; i < img.rows(); ++i) {\n    for(size_t j = 0; j < img.cols(); ++j) {\n      // initialize the potential and belief\n      uint32_t pixel_id = img.vertid(i, j);\n      vdata.potential.var() = vdata.belief.var() = pixel_id;\n      // Determine the color (in checkerboard form)\n      vdata.color = (i%2 == 0) ^ (j%2 == 0)? 1 : 0;\n      // Set the node potential\n      double obs = img.pixel(i, j);\n      for(size_t pred = 0; pred < num_rings; ++pred) {\n        vdata.potential.logP(pred) = \n          -(obs - pred)*(obs - pred) / (2.0 * sigmaSq);\n      }\n      vdata.potential.normalize();\n      // Set the initial assignment\n      vdata.asg = vdata.potential.sample();\n      // Store the actual data in the graph\n      size_t vert_id = graph.add_vertex(vdata);\n      // Ensure that we are using a consistent numbering\n      assert(vert_id == pixel_id);\n    } // end of for j in cols\n  } // end of for i in rows\n  // Construct an edge blob\n\n  // Add all the edges\n  for(size_t i = 0; i < img.rows(); ++i) {\n    for(size_t j = 0; j < img.cols(); ++j) {\n      size_t vertid = img.vertid(i,j);\n      if(i-1 < img.rows()) \n        graph.add_edge(vertid, img.vertid(i-1, j));\n      if(i+1 < img.rows())\n        graph.add_edge(vertid, img.vertid(i+1, j));\n      if(j-1 < img.cols())\n        graph.add_edge(vertid, img.vertid(i, j-1));\n      if(j+1 < img.cols())\n        graph.add_edge(vertid, img.vertid(i, j+1));\n    } // end of for j in cols\n  } // end of for i in rows\n} // End of construct graph\n\n\n/** Color selection function */\ntemplate<size_t color>\nbool select_color(graphlab::vertex_id_t v, \n                  const vertex_data& vdata) {\n  return vdata.color == color;\n}\n\n/**\n * The scheduling function used by the set scheduler to execute in\n * colored order\n */\nvoid color_schedule(gl::set_scheduler &sched) {\n  // There is a two coloring of this model\n  // All sets must be created before scheduling calls\n  std::vector<gl::ivertex_set*> colorsets(2);\n  // Colors do not change during execution\n  bool fixed_selection = true;\n  gl::selector_function select_color_0( select_color<0> );\n  colorsets[0] = &sched.attach(gl::rvset(select_color_0, fixed_selection),\n                               sched.root_set());\n  gl::selector_function select_color_1( select_color<1> );\n  colorsets[1] = &sched.attach(gl::rvset(select_color_1, fixed_selection),\n                               sched.root_set());\n  // Actually construct the color sets\n  sched.init();\n\n  // Build the execution plan\n  gl::execution_plan eplan;\n  for(size_t i = 0; i < colorsets.size(); ++i) {\n    std::cout << \"Set \" << i << \" has \"\n              << colorsets[i]->size() << \" vertices.\"\n              << std::endl;\n    const bool use_callback = false;\n    eplan.execute(*colorsets[i], gibbs_update<use_callback>);\n  }\n\n  // Compile the execution plan\n  graphlab::timer timer; timer.start();\n  eplan.generate_plan(sched.get_graph(), sched.num_cpus());\n  std::cout << \"Execution plan compiled in \"\n            << timer.current_time() << \" seconds\" << std::endl;\n\n  // Run the plan nsamples times\n  for(size_t iter = 0; iter < nsamples; ++iter)\n    sched.execute_plan(eplan);\n}\n\n", "meta": {"hexsha": "8fc6ccc8056389f7e7d3ee5a3550eb8ea55ee746", "size": 19574, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/image_denoise/gibbs_denoise.cpp", "max_stars_repo_name": "Lcrypto/graphlab", "max_stars_repo_head_hexsha": "4e525282d1c093bb8ad38e8941b87c86d6ad7ded", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2016-04-18T19:14:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T16:40:22.000Z", "max_issues_repo_path": "apps/image_denoise/gibbs_denoise.cpp", "max_issues_repo_name": "Lcrypto/graphlab", "max_issues_repo_head_hexsha": "4e525282d1c093bb8ad38e8941b87c86d6ad7ded", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apps/image_denoise/gibbs_denoise.cpp", "max_forks_repo_name": "Lcrypto/graphlab", "max_forks_repo_head_hexsha": "4e525282d1c093bb8ad38e8941b87c86d6ad7ded", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T03:00:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T00:22:23.000Z", "avg_line_length": 35.0788530466, "max_line_length": 84, "alphanum_fraction": 0.5901706345, "num_tokens": 4680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4160256923126864}}
{"text": "#include <fstream>\n#include <algorithm>\n#include <iterator>\n\n#include <boost/functional/value_factory.hpp>\n#include <boost/array.hpp>\n\n#include <CGAL/algorithm.h>\n#include <CGAL/point_generators_3.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/AABB_tree.h>\n#include <CGAL/AABB_traits.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/AABB_face_graph_triangle_primitive.h>\n#include <CGAL/AABB_halfedge_graph_segment_primitive.h>\n#include <CGAL/Timer.h>\n\ntypedef CGAL::Epick K;\ntypedef K::FT FT;\ntypedef K::Point_3 Point;\ntypedef K::Vector_3 Vector;\ntypedef K::Segment_3 Segment;\ntypedef K::Ray_3 Ray;\ntypedef CGAL::Surface_mesh<CGAL::Point_3<CGAL::Epick> > Mesh;\ntypedef CGAL::AABB_face_graph_triangle_primitive<Mesh,\nCGAL::Default,\nCGAL::Tag_false> T_Primitive;\ntypedef CGAL::AABB_traits<K, T_Primitive> T_Traits;\ntypedef CGAL::AABB_tree<T_Traits> T_Tree;\ntypedef T_Tree::Primitive_id T_Primitive_id;\n\ntypedef CGAL::AABB_halfedge_graph_segment_primitive<Mesh,\nCGAL::Default,\nCGAL::Tag_false> E_Primitive;\ntypedef CGAL::AABB_traits<K, E_Primitive> E_Traits;\ntypedef CGAL::AABB_tree<E_Traits> E_Tree;\ntypedef E_Tree::Primitive_id E_Primitive_id;\n\nint main()\n{\n  CGAL::Surface_mesh<CGAL::Point_3<CGAL::Epick> > m1, m2;\n  std::ifstream in(\"data/cube.off\");\n  if(in)\n    in >> m1;\n  else{\n    std::cout << \"error reading cube\" << std::endl;\n    return 1;\n  }\n  in.close();\n  in.open(CGAL::data_file_path(\"meshes/tetrahedron.off\"));\n  if(in)\n    in >> m2;\n  else{\n    std::cout << \"error reading tetrahedron\" << std::endl;\n    return 1;\n  }\n  in.close();\n  T_Tree tree(faces(m1).first, faces(m1).second, m1);\n  tree.insert(faces(m2).first, faces(m2).second, m2);\n  tree.build();\n  T_Tree::Bounding_box bbox = tree.bbox();\n  Point bbox_center((bbox.xmin() + bbox.xmax()) / 2,\n                     (bbox.ymin() + bbox.ymax()) / 2,\n                     (bbox.zmin() + bbox.zmax()) / 2);\n  std::vector< T_Primitive_id > intersections;\n  Ray ray(bbox_center+Vector(3,-0.25,0),bbox_center+Vector(-3,+0.25,0));\n  tree.all_intersected_primitives(ray,\n                                  std::back_inserter(intersections));\n  E_Tree e_tree(edges(m1).first, edges(m1).second, m1);\n  e_tree.insert(edges(m2).first, edges(m2).second, m2);\n  e_tree.build();\n  std::vector< E_Primitive_id > e_intersections;\n  Ray e_ray(Point(0,0,0),Point(0,1,1));\n  e_tree.all_intersected_primitives(e_ray,\n                                  std::back_inserter(e_intersections));\n\n\n\n  return 0;\n}\n", "meta": {"hexsha": "5b78ff33016336112af0c83afedb3cff3c1ea042", "size": 2493, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AABB_tree/test/AABB_tree/aabb_test_multi_mesh.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AABB_tree/test/AABB_tree/aabb_test_multi_mesh.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AABB_tree/test/AABB_tree/aabb_test_multi_mesh.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4024390244, "max_line_length": 72, "alphanum_fraction": 0.6971520257, "num_tokens": 740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355187, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.41601069998955925}}
{"text": "/**\n * \\file libsanm/tensor_svd.cpp\n * This file is part of SANM, a symbolic asymptotic numerical solver.\n */\n\n#include \"libsanm/tensor_svd.h\"\n#include \"libsanm/tensor_impl_helper.h\"\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\nusing namespace sanm;\n\nnamespace {\nvoid assign_check(size_t& dst, size_t v) {\n    if (!dst) {\n        dst = v;\n    } else {\n        sanm_assert(dst == v);\n    }\n}\n\nfp_t* get_full_ptr(TensorND& dst, const StSparseLinearTrans& lt) {\n    dst = lt.check_batched(true).as_full();\n    return const_cast<fp_t*>(dst.ptr());\n}\n\nfp_t clip_div(fp_t x, fp_t y) {\n    constexpr fp_t eps = 1e-12;\n    return x * y / (y * y + eps);\n}\n\nfp_t* ptr_offset(fp_t* p, size_t off) {\n    return p ? p + off : nullptr;\n}\n\n#define FOR4_BEGIN(i, j, k, l, n)              \\\n    do {                                       \\\n        for (size_t i = 0; i < n; ++i)         \\\n            for (size_t j = 0; j < n; ++j)     \\\n                for (size_t k = 0; k < n; ++k) \\\n                    for (size_t l = 0; l < n; ++l)\n#define FOR4_END() \\\n    }              \\\n    while (0)\n}  // anonymous namespace\n\nconst TensorND& TensorND::compute_batched_svd_w(TensorND& u, TensorND& s,\n                                                TensorND& w,\n                                                bool require_rotation) const {\n    SANM_SCOPED_PROFILER(\"batched_svd_w\");\n    sanm_assert(rank() == 3);\n    const size_t batch = shape(0), n = shape(1);\n    sanm_assert(n >= 2);\n    sanm_assert(shape(2) == n, \"not square matrices: %s\",\n                shape().str().c_str());\n    u.set_shape({batch, n, n});\n    s.set_shape({batch, n});\n    w.set_shape({batch, n, n});\n\n    auto mptr = ptr();\n    auto uptr = u.woptr(), sptr = s.woptr(), wptr = w.woptr();\n    auto run = [mptr, uptr, sptr, wptr, batch, n,\n                require_rotation]<Eigen::Index sn>() {\n        ScopedAllowMalloc scoped_allow_malloc;\n        Eigen::JacobiSVD<Eigen::Matrix<fp_t, sn, sn>> svd(\n                n, n, Eigen::ComputeFullU | Eigen::ComputeFullV);\n        Eigen::Matrix<fp_t, sn, sn> msrcT(n, n);\n        // note: with EIGEN_USE_LAPACKE, it JacobiSVD seems to fallback to MKL\n        // which would not be so slow\n        sanm_assert(n <= 16, \"TODO: switch to BDCSVD for large matrices\");\n        if (sn != Eigen::Dynamic) {\n            if (static_cast<Eigen::Index>(n) != sn) {\n                // hint the compiler that n equals to sn\n                __builtin_unreachable();\n            }\n        }\n        for (size_t i = 0; i < batch; ++i) {\n            EigenMat<sn, sn> msrc(const_cast<fp_t*>(mptr) + i * n * n, n, n);\n            msrcT = msrc;  // eigen svd class does not take Map inputs\n            svd.compute(msrcT);\n            EigenMat<sn, 1> ms(sptr + i * n, n, 1);\n            EigenMat<sn, sn> muT(uptr + i * n * n, n, n);\n            EigenMat<sn, sn> mwT(wptr + i * n * n, n, n);\n            // eigen uses column-major and computes M' = VSU'\n            ms = svd.singularValues();\n            muT = svd.matrixV().transpose();\n            if (require_rotation && ((svd.matrixU().determinant() < 0) !=\n                                     (svd.matrixV().determinant() < 0))) {\n#if 1\n                // negate some singular values so that det(w) = 1\n                constexpr fp_t EPS = 1e-3;\n                int best_idx = -1, best_idx_nr = n + 1;\n                for (size_t i = 0; i < n; ++i) {\n                    size_t j = i + 1;\n                    // ms already sorted\n                    while (j < n && std::fabs(ms(i) - ms(j)) < EPS) {\n                        ++j;\n                    }\n                    int nr = j - i;\n                    // best case is to negate an odd number of smallest singular\n                    // values (so si+sj != 0 in the hessian);\n                    // otherwise negate one value whose has the least\n                    // repetitionss\n                    if (nr <= best_idx_nr ||\n                        (nr == best_idx_nr + 1 && nr % 2 == 1)) {\n                        best_idx = i;\n                        best_idx_nr = nr;\n                        if (nr == 1) {\n                            break;\n                        }\n                    }\n                    i = j;\n                }\n                if (best_idx_nr == 1 || best_idx_nr % 2 == 0) {\n                    ms(best_idx) = -ms(best_idx);\n                    muT.row(best_idx) = -muT.row(best_idx);\n                } else {\n                    for (int i = best_idx; i < best_idx + best_idx_nr; ++i) {\n                        ms(i) = -ms(i);\n                        muT.row(i) = -muT.row(i);\n                    }\n                }\n#else\n                ms(n - 1) = -ms(n - 1);\n                muT.row(n - 1) = -muT.row(n - 1);\n#endif\n            }\n            // w=uv', w'=vu'\n            mwT.noalias() = svd.matrixU() * muT;\n        }\n    };\n#define CASE(sn)                  \\\n    do {                          \\\n        if (n == sn) {            \\\n            run.operator()<sn>(); \\\n            return *this;         \\\n        }                         \\\n    } while (0)\n    CASE(2);\n    CASE(3);\n#undef CASE\n    run.operator()<Eigen::Dynamic>();\n    return *this;\n}\n\nvoid sanm::svd_w_grad_revmode(StSparseLinearTrans& grad, const TensorND& mU,\n                              const TensorND& mS, const TensorND& mW,\n                              const StSparseLinearTrans& mdU,\n                              const StSparseLinearTrans& mdS,\n                              const StSparseLinearTrans& mdW) {\n    SANM_SCOPED_PROFILER(\"batched_svd_w_grad\");\n    auto run = [&]<Eigen::Index sn>() {\n        // extract sizes and pointers\n        const size_t batch = mU.shape(0), n = mU.shape(1);\n        if (sn != Eigen::Dynamic && static_cast<Eigen::Index>(n) != sn) {\n            // hint the compiler that n equals to sn\n            __builtin_unreachable();\n        }\n        TensorND mdU_full, mdS_full, mdW_full, mdM;\n        fp_t *mdU_ptr = nullptr, *mdS_ptr = nullptr, *mdW_ptr = nullptr;\n        size_t out_dim = 0;\n        if (mdU.valid()) {\n            mdU_ptr = get_full_ptr(mdU_full, mdU);\n            assign_check(out_dim, mdU.out_dim());\n        }\n        if (mdS.valid()) {\n            mdS_ptr = get_full_ptr(mdS_full, mdS);\n            assign_check(out_dim, mdS.out_dim());\n        }\n        if (mdW.valid()) {\n            mdW_ptr = get_full_ptr(mdW_full, mdW);\n            assign_check(out_dim, mdW.out_dim());\n        }\n        sanm_assert(out_dim, \"no output grad\");\n        if (grad.valid()) {\n            mdM = grad.check_batched(true).as_full();\n            sanm_assert(mdM.shape() == (TensorShape{batch, out_dim, n * n}));\n            grad = {};\n        } else {\n            mdM.set_shape({batch, out_dim, n * n}).fill_with_inplace(0);\n        }\n        auto mdMptr = mdM.rwptr();\n        auto mU_ptr = const_cast<fp_t*>(mU.ptr()),\n             mS_ptr = const_cast<fp_t*>(mS.ptr()),\n             mW_ptr = const_cast<fp_t*>(mW.ptr());\n\n        // allocate temporaries\n        ScopedAllowMalloc scoped_allow_malloc;\n        constexpr Eigen::Index snsqr = sn == Eigen::Dynamic ? sn : sn * sn;\n        Eigen::Matrix<fp_t, sn, sn> cV(n, n);\n        Eigen::Matrix<fp_t, snsqr, sn> dsdmT(n * n, n);\n        Eigen::Matrix<fp_t, snsqr, snsqr> dxdmT(n * n, n * n),\n                dydmT(n * n, n * n), dwdyT(n * n, n * n), dudxT(n * n, n * n),\n                tmpn2(n * n, n * n);\n        scoped_allow_malloc.disallow();\n\n        // matrix variables:\n        // prefix c means current (this batch)\n        // prefix d means derivative/jacobian\n        // suffix t/T means transposed (eigen uses col-major)\n\n        for (size_t ib = 0; ib < batch; ++ib) {\n            size_t ib_off = ib * n * n;\n            EigenMat<sn, sn> cUt(mU_ptr + ib_off, n, n),\n                    cWt(mW_ptr + ib_off, n, n);\n            EigenMat<sn, 1> cS(mS_ptr + ib * n, n, 1);\n            EigenMat<snsqr, Eigen::Dynamic> cdMt(mdMptr + ib_off * out_dim,\n                                                 n * n, out_dim);\n            cV.noalias() = cWt * cUt.transpose();\n            if (mdS_ptr) {\n                for (size_t si = 0; si < n; ++si) {\n                    for (size_t mi = 0; mi < n; ++mi) {\n                        for (size_t mj = 0; mj < n; ++mj) {\n                            dsdmT(mi * n + mj, si) = cUt(si, mi) * cV(mj, si);\n                        }\n                    }\n                }\n                EigenMat<sn, Eigen::Dynamic> cdSt(mdS_ptr + ib * n * out_dim, n,\n                                                  out_dim);\n                cdMt.noalias() += dsdmT * cdSt;\n            }\n            if (mdW_ptr || mdU_ptr) {\n                FOR4_BEGIN(i, j, k, l, n) {\n                    fp_t cij = cUt(i, k) * cV(l, j), cji = cUt(j, k) * cV(l, i),\n                         si = cS(i), sj = cS(j);\n                    if (mdW_ptr) {\n                        dydmT(k * n + l, i * n + j) =\n                                i == j ? 0 : clip_div(cij - cji, si + sj);\n                        dwdyT(k * n + l, i * n + j) = cUt(k, i) * cV(j, l);\n                    }\n                    if (mdU_ptr) {\n                        dudxT(k * n + l, i * n + j) = l == j ? cUt(k, i) : 0;\n                        dxdmT(k * n + l, i * n + j) =\n                                i == j ? 0\n                                       : clip_div(cij * sj + cji * si,\n                                                  sj * sj - si * si);\n                    }\n                }\n                FOR4_END();\n\n                if (mdW_ptr) {\n                    tmpn2.noalias() = dydmT * dwdyT;\n                    EigenMat<snsqr, Eigen::Dynamic> cdWt(\n                            mdW_ptr + ib_off * out_dim, n * n, out_dim);\n                    cdMt.noalias() += tmpn2 * cdWt;\n                }\n                if (mdU_ptr) {\n                    tmpn2.noalias() = dxdmT * dudxT;\n                    EigenMat<snsqr, Eigen::Dynamic> cdUt(\n                            mdU_ptr + ib_off * out_dim, n * n, out_dim);\n                    cdMt.noalias() += tmpn2 * cdUt;\n                }\n            }\n        }\n\n        grad.reset(StSparseLinearTrans::FULL, true, mdM);\n    };\n\n    size_t n = mU.shape(1);\n    sanm_assert(n >= 2);\n#define CASE(sn)                  \\\n    do {                          \\\n        if (n == sn) {            \\\n            run.operator()<sn>(); \\\n            return;               \\\n        }                         \\\n    } while (0)\n    CASE(2);\n    CASE(3);\n#undef CASE\n    run.operator()<Eigen::Dynamic>();\n}\n\nvoid sanm::svd_w_taylor_fwd(TensorND& mUk, TensorND& mSk, TensorND& mWk,\n                            const TensorND& mMk, const TensorND& mMbiask,\n                            const TensorND& mU0, const TensorND& mS0,\n                            const TensorND& mW0, const TensorND* mBu,\n                            const TensorND& mBw) {\n    SANM_SCOPED_PROFILER(\"svd_w_taylor_fwd\");\n    auto run = [&]<Eigen::Index sn>() {\n        const size_t batch = mMk.shape(0), n = mMk.shape(1);\n        if (sn != Eigen::Dynamic && static_cast<Eigen::Index>(n) != sn) {\n            // hint the compiler that n equals to sn\n            __builtin_unreachable();\n        }\n        fp_t *mUkptr = mBu ? mUk.woptr() : nullptr,\n             *mSkptr = mBu ? mSk.woptr() : nullptr, *mWkptr = mWk.woptr();\n#define DEF(x) auto x##ptr = const_cast<fp_t*>(x.ptr())\n        DEF(mMk);\n        DEF(mMbiask);\n        DEF(mU0);\n        DEF(mS0);\n        DEF(mW0);\n        DEF(mBw);\n#undef DEF\n        fp_t* mBuptr = mBu ? const_cast<fp_t*>(mBu->ptr()) : nullptr;\n\n        // matrix variables:\n        // prefix c means current (this batch)\n        // suffix t/T means transposed (eigen uses col-major)\n\n        // allocate temporaries\n        ScopedAllowMalloc scoped_allow_malloc;\n        Eigen::Matrix<fp_t, sn, sn> cV0(n, n), eqbT(n, n), tmp0(n, n),\n                tmp1(n, n);\n        MatrixMultiProduct<Eigen::Matrix<fp_t, sn, sn>> mprod(n, n);\n        scoped_allow_malloc.disallow();\n\n        for (size_t ib = 0; ib < batch; ++ib) {\n            size_t ib_off = ib * n * n;\n            EigenMat<sn, 1> cS0(mS0ptr + ib * n, n, 1),\n                    cSk(mSkptr + ib * n, n, 1);\n#define DEF(x) EigenMat<sn, sn> c##x##T(ptr_offset(m##x##ptr, ib_off), n, n)\n            DEF(Uk);\n            DEF(Wk);\n            DEF(Mk);\n            DEF(Mbiask);\n            DEF(U0);\n            DEF(W0);\n            DEF(Bu);\n            DEF(Bw);\n#undef DEF\n            cV0.noalias() = cW0T * cU0T.transpose();\n            tmp0 = cMkT - cMbiaskT;\n            mprod.init(cV0.transpose(), tmp0).mul_r_to(eqbT, cU0T.transpose());\n            {\n                // solve Wk\n                auto& rhs = tmp0;  // right hand side of the equation\n                tmp0 = eqbT.transpose();\n                rhs = tmp0 - eqbT;\n                rhs -= mprod.init(cV0.transpose(), cBwT.transpose())\n                               .mul_r(cV0)\n                               .mul_r(cS0.asDiagonal())\n                               .get();\n                auto& x = rhs;\n                for (size_t j = 0; j < n; ++j) {\n                    for (size_t i = 0; i < n; ++i) {\n                        x(i, j) = clip_div(rhs(i, j), cS0(i) + cS0(j));\n                    }\n                }\n                // update eqbT for future solves\n                if (mBu) {\n                    eqbT -= mprod.init(x.transpose(), cS0.asDiagonal()).get();\n                }\n                // solve cWkT\n                mprod.init(cV0, x.transpose()).mul_r_to(cWkT, cU0T);\n            }\n            if (!mBu) {\n                continue;\n            }\n            eqbT.noalias() += cBuT * cS0.asDiagonal();\n            cSk = eqbT.diagonal();\n            {\n                // solve Uk\n                auto& cUkTU0 = eqbT;  // Uk.T * U0\n                for (size_t j = 0; j < n; ++j) {\n                    for (size_t i = 0; i < j; ++i) {\n                        fp_t v = clip_div(eqbT(i, j), cS0(i) - cS0(j));\n                        cUkTU0(i, j) = v;\n                        cUkTU0(j, i) = -cBuT(j, i) - v;\n                    }\n                    cUkTU0(j, j) = -cBuT(j, j) / 2;\n                }\n                cUkT.noalias() = cUkTU0 * cU0T;\n            }\n        }\n    };\n    const size_t batch = mMk.shape(0), n = mMk.shape(1);\n    sanm_assert(n >= 2);\n    if (mBu) {\n        mUk.set_shape({batch, n, n});\n        mSk.set_shape({batch, n});\n    }\n    mWk.set_shape({batch, n, n});\n#define CASE(sn)                  \\\n    do {                          \\\n        if (n == sn) {            \\\n            run.operator()<sn>(); \\\n            return;               \\\n        }                         \\\n    } while (0)\n    CASE(2);\n    CASE(3);\n#undef CASE\n    run.operator()<Eigen::Dynamic>();\n}\n\nvoid sanm::svd_w_taylor_fwd_p(TensorND& mPk, TensorND& mWk, const TensorND& mMk,\n                              const TensorND& mU0, const TensorND& mS0,\n                              const TensorND& mW0, const TensorND& mBm,\n                              const TensorND& mBp, const TensorND& mBpw) {\n    SANM_SCOPED_PROFILER(\"svd_w_taylor_fwd_p\");\n    auto run = [&]<Eigen::Index sn>() {\n        const size_t batch = mMk.shape(0), n = mMk.shape(1);\n        if (sn != Eigen::Dynamic && static_cast<Eigen::Index>(n) != sn) {\n            // hint the compiler that n equals to sn\n            __builtin_unreachable();\n        }\n        fp_t *mPkptr = mPk.woptr(), *mWkptr = mWk.woptr();\n#define DEF(x) auto x##ptr = const_cast<fp_t*>(x.ptr())\n        DEF(mMk);\n        DEF(mU0);\n        DEF(mS0);\n        DEF(mW0);\n        DEF(mBm);\n        DEF(mBp);\n        DEF(mBpw);\n#undef DEF\n\n        // matrix variables:\n        // prefix c means current (this batch)\n        // suffix t/T means transposed (eigen uses col-major)\n\n        // allocate temporaries\n        ScopedAllowMalloc scoped_allow_malloc;\n        Eigen::Matrix<fp_t, sn, sn> cV0(n, n), eqbT(n, n);\n        Eigen::Matrix<fp_t, sn, 1> cS0inv(n, 1);\n        MatrixMultiProduct<Eigen::Matrix<fp_t, sn, sn>> mprod(n, n);\n        scoped_allow_malloc.disallow();\n\n        for (size_t ib = 0; ib < batch; ++ib) {\n            size_t ib_off = ib * n * n;\n            EigenMat<sn, 1> cS0(mS0ptr + ib * n, n, 1);\n#define DEF(x) EigenMat<sn, sn> c##x##T(m##x##ptr + ib_off, n, n)\n            DEF(Pk);\n            DEF(Wk);\n            DEF(Mk);\n            DEF(U0);\n            DEF(W0);\n            DEF(Bm);\n            DEF(Bp);\n            DEF(Bpw);\n#undef DEF\n            cV0.noalias() = cW0T * cU0T.transpose();\n            eqbT = cBmT - cBpT;\n            mprod.init(cU0T, eqbT).mul_r_to(eqbT, cU0T.transpose());\n            mprod.init(cS0.asDiagonal(), cV0.transpose())\n                    .mul_r(cMkT)\n                    .mul_r(cU0T.transpose());\n            eqbT += mprod.get();\n            eqbT += mprod.get().transpose();\n            auto& x = eqbT;\n            for (size_t j = 0; j < n; ++j) {\n                for (size_t i = 0; i < n; ++i) {\n                    x(i, j) = clip_div(eqbT(i, j), cS0(i) + cS0(j));\n                }\n            }\n            for (size_t i = 0; i < n; ++i) {\n                cS0inv(i) = clip_div(1, cS0(i));\n            }\n            mprod.init(cU0T.transpose(), x).mul_r_to(cPkT, cU0T);\n            eqbT = cMkT - cBpwT;\n            eqbT.noalias() -= cW0T * cPkT;\n            mprod.init(eqbT, cU0T.transpose())\n                    .mul_r(cS0inv.asDiagonal())\n                    .mul_r_to(cWkT, cU0T);\n        }\n    };\n    const size_t batch = mMk.shape(0), n = mMk.shape(1);\n    sanm_assert(n >= 2);\n    mPk.set_shape({batch, n, n});\n    mWk.set_shape({batch, n, n});\n#define CASE(sn)                  \\\n    do {                          \\\n        if (n == sn) {            \\\n            run.operator()<sn>(); \\\n            return;               \\\n        }                         \\\n    } while (0)\n    CASE(2);\n    CASE(3);\n#undef CASE\n    run.operator()<Eigen::Dynamic>();\n}\n", "meta": {"hexsha": "502ded6e66370c8ab8d832f8d40e7591e1f49fd2", "size": 17900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libsanm/tensor_svd.cpp", "max_stars_repo_name": "jia-kai/SANM", "max_stars_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T09:27:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T15:22:05.000Z", "max_issues_repo_path": "libsanm/tensor_svd.cpp", "max_issues_repo_name": "jia-kai/SANM", "max_issues_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-03T05:31:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-05T01:37:42.000Z", "max_forks_repo_path": "libsanm/tensor_svd.cpp", "max_forks_repo_name": "jia-kai/SANM", "max_forks_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6050420168, "max_line_length": 80, "alphanum_fraction": 0.4318994413, "num_tokens": 5028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.41599268295986397}}
{"text": "#ifndef STAN_MATH_TORSTEN_REFACTOR_LINODEMODEL_HPP\n#define STAN_MATH_TORSTEN_REFACTOR_LINODEMODEL_HPP\n\n#include <Eigen/Dense>\n#include <stan/math/torsten/events_manager.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/torsten/event_solver.hpp>\n#include <stan/math/torsten/pmx_linode_model.hpp>\n#include <stan/math/torsten/PKModel/PKModel.hpp>\n#include <stan/math/torsten/PKModel/Pred/Pred1_linOde.hpp>\n#include <stan/math/torsten/PKModel/Pred/PredSS_linOde.hpp>\n#include <stan/math/prim/mat/err/check_square.hpp>\n#include <vector>\n\nnamespace torsten {\n\n/**\n * Computes the predicted amounts in each compartment at each event\n * for a compartment model, described by a linear system of ordinary\n * differential equations. Uses the stan::math::matrix_exp \n * function.\n *\n * @tparam T0 type of scalar for time of events. \n * @tparam T1 type of scalar for amount at each event.\n * @tparam T2 type of scalar for rate at each event.\n * @tparam T3 type of scalar for inter-dose inteveral at each event.\n * @tparam T4 type of scalar for matrix describing linear ODE system.\n * @tparam T5 type of scalars for bio-variability parameters.\n * @tparam T6 type of scalars for tlag parameters \n * @param[in] time times of events  \n * @param[in] amt amount at each event\n * @param[in] rate rate at each event\n * @param[in] ii inter-dose interval at each event\n * @param[in] evid event identity: \n *                    (0) observation \n *                    (1) dosing\n *                    (2) other\n *                    (3) reset\n *                    (4) reset AND dosing\n * @param[in] cmt compartment number at each event \n * @param[in] addl additional dosing at each event \n * @param[in] ss steady state approximation at each event (0: no, 1: yes)\n * between time-points\n * @param[in] system square matrix describing the linear system of ODEs\n * @param[in] bio-variability at each event\n * @param[in] lag times at each event\n * @return a matrix with predicted amount in each compartment \n * at each event.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3,\n          typename T4, typename T5, typename T6>\nEigen::Matrix <typename torsten::return_t<T0, T1, T2, T3, T4, T5, T6>::type,\n               Eigen::Dynamic, Eigen::Dynamic>\npmx_solve_linode(const std::vector<T0>& time,\n            const std::vector<T1>& amt,\n            const std::vector<T2>& rate,\n            const std::vector<T3>& ii,\n            const std::vector<int>& evid,\n            const std::vector<int>& cmt,\n            const std::vector<int>& addl,\n            const std::vector<int>& ss,\n            const std::vector< Eigen::Matrix<T4, Eigen::Dynamic, Eigen::Dynamic> >& system,\n            const std::vector<std::vector<T5> >& biovar,\n            const std::vector<std::vector<T6> >& tlag) {\n  using std::vector;\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using boost::math::tools::promote_args;\n  using refactor::PKRec;\n\n  static const char* function(\"pmx_solve_linode\");\n  for (size_t i = 0; i < system.size(); i++)\n    stan::math::check_square(function, \"system matrix\", system[i]);\n  int nCmt = system[0].cols();\n\n  std::vector<T4> parameters_dummy(0);\n  std::vector<std::vector<T4> > pMatrix_dummy(1, parameters_dummy);\n  torsten::pmx_check(time, amt, rate, ii, evid, cmt, addl, ss,\n                pMatrix_dummy, biovar, tlag, function);\n\n#ifdef OLD_TORSTEN\n  return Pred(time, amt, rate, ii, evid, cmt, addl, ss,\n              pMatrix_dummy, biovar, tlag, nCmt, system,\n              Pred1_linOde(), PredSS_linOde());\n#else\n  using ER = NONMENEventsRecord<T0, T1, T2, T3, Eigen::Matrix<T4,-1,-1>, T5, T6>;\n  using EM = EventsManager<ER>;\n  const ER events_rec(nCmt, time, amt, rate, ii, evid, cmt, addl, ss, system, biovar, tlag);\n\n  Matrix<typename EM::T_scalar, Dynamic, Dynamic> pred =\n    Matrix<typename EM::T_scalar, Dynamic, Dynamic>::Zero(events_rec.num_event_times(), EM::nCmt(events_rec));\n\n  using model_type = refactor::PMXLinODEModel<typename EM::T_time, typename EM::T_scalar, typename EM::T_rate, typename EM::T_par>;\n  EventSolver<model_type> pr;\n  pr.pred(0, events_rec, pred);\n  return pred;\n\n#endif\n}\n\n/**\n * Overload function to allow user to pass a matrix for \n * system.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3,\n          typename T4, typename T_biovar, typename T_tlag>\nEigen::Matrix <typename torsten::return_t<T0, T1, T2, T3, T4,\n                                          typename torsten::value_type<T_biovar>::type,\n                                          typename torsten::value_type<T_tlag>::type>::type,\n               Eigen::Dynamic, Eigen::Dynamic>\npmx_solve_linode(const std::vector<T0>& time,\n                 const std::vector<T1>& amt,\n                 const std::vector<T2>& rate,\n                 const std::vector<T3>& ii,\n                 const std::vector<int>& evid,\n                 const std::vector<int>& cmt,\n                 const std::vector<int>& addl,\n                 const std::vector<int>& ss,\n                 const Eigen::Matrix<T4, -1, -1>& system,\n                 const std::vector<T_biovar>& biovar,\n                 const std::vector<T_tlag>& tlag) {\n  std::vector<Eigen::Matrix<T4, -1, -1> > system_{system};\n  auto biovar_ = torsten::to_array_2d(biovar);\n  auto tlag_ = torsten::to_array_2d(tlag);\n\n  return pmx_solve_linode(time, amt, rate, ii, evid, cmt, addl, ss,\n                          system_, biovar_, tlag_);\n}\n\n/**\n * Overload function to allow user to pass a matrix for \n * system.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3,\n          typename T4, typename T_biovar, typename T_tlag,\n          typename\n          std::enable_if_t<\n            !(torsten::is_std_vector<T_biovar>::value && torsten::is_std_vector<T_tlag>::value)>* = nullptr> //NOLINT\nEigen::Matrix <typename torsten::return_t<T0, T1, T2, T3, T4,\n                                          typename torsten::value_type<T_biovar>::type,\n                                          typename torsten::value_type<T_tlag>::type>::type,\n               Eigen::Dynamic, Eigen::Dynamic>\npmx_solve_linode(const std::vector<T0>& time,\n                 const std::vector<T1>& amt,\n                 const std::vector<T2>& rate,\n                 const std::vector<T3>& ii,\n                 const std::vector<int>& evid,\n                 const std::vector<int>& cmt,\n                 const std::vector<int>& addl,\n                 const std::vector<int>& ss,\n                 const std::vector< Eigen::Matrix<T4, -1, -1> >& system,\n                 const std::vector<T_biovar>& biovar,\n                 const std::vector<T_tlag>& tlag) {\n  auto biovar_ = torsten::to_array_2d(biovar);\n  auto tlag_ = torsten::to_array_2d(tlag);\n\n  return pmx_solve_linode(time, amt, rate, ii, evid, cmt, addl, ss,\n                          system, biovar_, tlag_);\n}\n\n  // old version by using transpose\ntemplate <typename T0, typename T1, typename T2, typename T3,\n  typename T4, typename T5, typename T6>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n                                                         typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n               Eigen::Dynamic, Eigen::Dynamic>\nlinOdeModel(const std::vector<T0>& time,\n            const std::vector<T1>& amt,\n            const std::vector<T2>& rate,\n            const std::vector<T3>& ii,\n            const std::vector<int>& evid,\n            const std::vector<int>& cmt,\n            const std::vector<int>& addl,\n            const std::vector<int>& ss,\n            const std::vector< Eigen::Matrix<T4, Eigen::Dynamic, Eigen::Dynamic> >& system,\n            const std::vector<std::vector<T5> >& biovar,\n            const std::vector<std::vector<T6> >& tlag) {\n  auto x = pmx_solve_linode(time, amt, rate, ii, evid, cmt, addl, ss, system, biovar, tlag);\n  return x.transpose();\n}\n\ntemplate <typename T0, typename T1, typename T2, typename T3,\n          typename T4, typename T_biovar, typename T_tlag>\nEigen::Matrix <typename torsten::return_t<T0, T1, T2, T3, T4,\n                                          typename torsten::value_type<T_biovar>::type,\n                                          typename torsten::value_type<T_tlag>::type>::type,\n               Eigen::Dynamic, Eigen::Dynamic>\nlinOdeModel(const std::vector<T0>& time,\n                 const std::vector<T1>& amt,\n                 const std::vector<T2>& rate,\n                 const std::vector<T3>& ii,\n                 const std::vector<int>& evid,\n                 const std::vector<int>& cmt,\n                 const std::vector<int>& addl,\n                 const std::vector<int>& ss,\n                 const Eigen::Matrix<T4, -1, -1>& system,\n                 const std::vector<T_biovar>& biovar,\n                 const std::vector<T_tlag>& tlag) {\n  auto x = pmx_solve_linode(time, amt, rate, ii, evid, cmt, addl, ss, system, biovar, tlag);\n  return x.transpose();\n}\n\n  template <typename T0, typename T1, typename T2, typename T3,\n            typename T4, typename T_biovar, typename T_tlag,\n            typename\n            std::enable_if_t<\n              !(torsten::is_std_vector<T_biovar>::value && torsten::is_std_vector<T_tlag>::value)>* = nullptr> //NOLINT\n  Eigen::Matrix <typename torsten::return_t<T0, T1, T2, T3, T4,\n                                            typename torsten::value_type<T_biovar>::type,\n                                            typename torsten::value_type<T_tlag>::type>::type,\n                 Eigen::Dynamic, Eigen::Dynamic>\n  linOdeModel(const std::vector<T0>& time,\n              const std::vector<T1>& amt,\n              const std::vector<T2>& rate,\n              const std::vector<T3>& ii,\n              const std::vector<int>& evid,\n              const std::vector<int>& cmt,\n              const std::vector<int>& addl,\n              const std::vector<int>& ss,\n              const std::vector< Eigen::Matrix<T4, -1, -1> >& system,\n              const std::vector<T_biovar>& biovar,\n              const std::vector<T_tlag>& tlag) {\n    auto x = pmx_solve_linode(time, amt, rate, ii, evid, cmt, addl, ss,\n                            system, biovar, tlag);\n    return x.transpose();\n  }\n\n}\n#endif\n", "meta": {"hexsha": "f645caec26cca6adef9649dae434f810dd065880", "size": 10193, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/pmx_solve_linode.hpp", "max_stars_repo_name": "csetraynor/Torsten", "max_stars_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/pmx_solve_linode.hpp", "max_issues_repo_name": "csetraynor/Torsten", "max_issues_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/pmx_solve_linode.hpp", "max_forks_repo_name": "csetraynor/Torsten", "max_forks_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.3173913043, "max_line_length": 131, "alphanum_fraction": 0.5977631708, "num_tokens": 2671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4159765674053582}}
{"text": "//\n//  FrictionUtils.hpp\n//  IPC\n//\n//  Created by Minchen Li on 9/26/19.\n//\n\n#ifndef FrictionUtils_hpp\n#define FrictionUtils_hpp\n\n#include \"Types.hpp\"\n\n#include \"MeshCollisionUtils.hpp\"\n\n#include <Eigen/Eigen>\n\n#include <iostream>\n#include <array>\n\nnamespace IPC {\n\n// Point - Triangle\n\ninline void computeTangentBasis_PT(\n    const Eigen::RowVector3d& v0,\n    const Eigen::RowVector3d& v1,\n    const Eigen::RowVector3d& v2,\n    const Eigen::RowVector3d& v3,\n    Eigen::Matrix<double, 3, 2>& basis)\n{\n    Eigen::Vector3d v12 = (v2 - v1).transpose();\n    basis.col(0) = v12.normalized();\n    basis.col(1) = v12.cross((v3 - v1).transpose()).cross(v12).normalized();\n}\n\ninline void computeClosestPoint_PT(\n    const Eigen::RowVector3d& v0,\n    const Eigen::RowVector3d& v1,\n    const Eigen::RowVector3d& v2,\n    const Eigen::RowVector3d& v3,\n    Eigen::Vector2d& beta)\n{\n    Eigen::Matrix<double, 2, 3> basis;\n    basis.row(0) = v2 - v1;\n    basis.row(1) = v3 - v1;\n    beta = (basis * basis.transpose()).ldlt().solve(basis * (v0 - v1).transpose());\n}\n\ninline void computeRelDX_PT(\n    const Eigen::RowVector3d& dx0,\n    const Eigen::RowVector3d& dx1,\n    const Eigen::RowVector3d& dx2,\n    const Eigen::RowVector3d& dx3,\n    double beta1, double beta2,\n    Eigen::RowVector3d& relDX)\n{\n    relDX = dx0 - (dx1 + beta1 * (dx2 - dx1) + beta2 * (dx3 - dx1));\n}\n\ninline void liftRelDXTanToMesh_PT(\n    const Eigen::Vector2d& relDXTan,\n    const Eigen::Matrix<double, 3, 2>& basis,\n    double beta1, double beta2,\n    Eigen::Matrix<double, 12, 1>& TTTDX)\n{\n    TTTDX.template segment<3>(0) = basis * relDXTan;\n    TTTDX.template segment<3>(3) = (-1 + beta1 + beta2) * TTTDX.template segment<3>(0);\n    TTTDX.template segment<3>(6) = -beta1 * TTTDX.template segment<3>(0);\n    TTTDX.template segment<3>(9) = -beta2 * TTTDX.template segment<3>(0);\n}\n\ninline void computeTTT_PT(\n    const Eigen::Matrix<double, 3, 2>& basis,\n    double beta1, double beta2,\n    Eigen::Matrix<double, 12, 12>& TTT)\n{\n    Eigen::Matrix<double, 2, 12> TT;\n    TT.template block<2, 3>(0, 0) = basis.transpose();\n    TT.template block<2, 3>(0, 3) = (-1 + beta1 + beta2) * basis.transpose();\n    TT.template block<2, 3>(0, 6) = -beta1 * basis.transpose();\n    TT.template block<2, 3>(0, 9) = -beta2 * basis.transpose();\n    TTT = TT.transpose() * TT;\n}\n\n// Edge - Edge\n\ninline void computeTangentBasis_EE(\n    const Eigen::RowVector3d& v0,\n    const Eigen::RowVector3d& v1,\n    const Eigen::RowVector3d& v2,\n    const Eigen::RowVector3d& v3,\n    Eigen::Matrix<double, 3, 2>& basis)\n{\n    Eigen::Vector3d v01 = (v1 - v0).transpose();\n    basis.col(0) = v01.normalized();\n    basis.col(1) = v01.cross((v3 - v2).transpose()).cross(v01).normalized();\n}\n\ninline void computeClosestPoint_EE(\n    const Eigen::RowVector3d& v0,\n    const Eigen::RowVector3d& v1,\n    const Eigen::RowVector3d& v2,\n    const Eigen::RowVector3d& v3,\n    Eigen::Vector2d& gamma)\n{\n    Eigen::RowVector3d e20 = v0 - v2;\n    Eigen::RowVector3d e01 = v1 - v0;\n    Eigen::RowVector3d e23 = v3 - v2;\n\n    Eigen::Matrix2d coefMtr;\n    coefMtr(0, 0) = e01.squaredNorm();\n    coefMtr(0, 1) = coefMtr(1, 0) = -e23.dot(e01);\n    coefMtr(1, 1) = e23.squaredNorm();\n\n    Eigen::Vector2d rhs;\n    rhs[0] = -e20.dot(e01);\n    rhs[1] = e20.dot(e23);\n\n    gamma = coefMtr.ldlt().solve(rhs);\n}\n\ninline void computeRelDX_EE(\n    const Eigen::RowVector3d& dx0,\n    const Eigen::RowVector3d& dx1,\n    const Eigen::RowVector3d& dx2,\n    const Eigen::RowVector3d& dx3,\n    double gamma1, double gamma2,\n    Eigen::RowVector3d& relDX)\n{\n    relDX = dx0 + gamma1 * (dx1 - dx0) - (dx2 + gamma2 * (dx3 - dx2));\n}\n\ninline void liftRelDXTanToMesh_EE(\n    const Eigen::Vector2d& relDXTan,\n    const Eigen::Matrix<double, 3, 2>& basis,\n    double gamma1, double gamma2,\n    Eigen::Matrix<double, 12, 1>& TTTDX)\n{\n    Eigen::Vector3d relDXTan3D = basis * relDXTan;\n    TTTDX.template segment<3>(0) = (1.0 - gamma1) * relDXTan3D;\n    TTTDX.template segment<3>(3) = gamma1 * relDXTan3D;\n    TTTDX.template segment<3>(6) = (gamma2 - 1.0) * relDXTan3D;\n    TTTDX.template segment<3>(9) = -gamma2 * relDXTan3D;\n}\n\ninline void computeTTT_EE(\n    const Eigen::Matrix<double, 3, 2>& basis,\n    double gamma1, double gamma2,\n    Eigen::Matrix<double, 12, 12>& TTT)\n{\n    Eigen::Matrix<double, 2, 12> TT;\n    TT.template block<2, 3>(0, 0) = (1.0 - gamma1) * basis.transpose();\n    TT.template block<2, 3>(0, 3) = gamma1 * basis.transpose();\n    TT.template block<2, 3>(0, 6) = (gamma2 - 1.0) * basis.transpose();\n    TT.template block<2, 3>(0, 9) = -gamma2 * basis.transpose();\n    TTT = TT.transpose() * TT;\n}\n\n// Point - Edge\n\ninline void computeTangentBasis_PE(\n    const Eigen::RowVector3d& v0,\n    const Eigen::RowVector3d& v1,\n    const Eigen::RowVector3d& v2,\n    Eigen::Matrix<double, 3, 2>& basis)\n{\n    Eigen::Vector3d v12 = (v2 - v1).transpose();\n    basis.col(0) = v12.normalized();\n    basis.col(1) = v12.cross((v0 - v1).transpose()).normalized();\n}\n\ninline void computeClosestPoint_PE(\n    const Eigen::RowVector3d& v0,\n    const Eigen::RowVector3d& v1,\n    const Eigen::RowVector3d& v2,\n    double& yita)\n{\n    Eigen::RowVector3d e12 = v2 - v1;\n    yita = (v0 - v1).dot(e12) / e12.squaredNorm();\n}\n\ninline void computeRelDX_PE(\n    const Eigen::RowVector3d& dx0,\n    const Eigen::RowVector3d& dx1,\n    const Eigen::RowVector3d& dx2,\n    double yita,\n    Eigen::RowVector3d& relDX)\n{\n    relDX = dx0 - (dx1 + yita * (dx2 - dx1));\n}\n\ninline void liftRelDXTanToMesh_PE(\n    const Eigen::Vector2d& relDXTan,\n    const Eigen::Matrix<double, 3, 2>& basis,\n    double yita,\n    Eigen::Matrix<double, 9, 1>& TTTDX)\n{\n    TTTDX.template segment<3>(0) = basis * relDXTan;\n    TTTDX.template segment<3>(3) = (yita - 1.0) * TTTDX.template segment<3>(0);\n    TTTDX.template segment<3>(6) = -yita * TTTDX.template segment<3>(0);\n}\n\ninline void computeTTT_PE(\n    const Eigen::Matrix<double, 3, 2>& basis,\n    double yita,\n    Eigen::Matrix<double, 9, 9>& TTT)\n{\n    Eigen::Matrix<double, 2, 9> TT;\n    TT.template block<2, 3>(0, 0) = basis.transpose();\n    TT.template block<2, 3>(0, 3) = (yita - 1.0) * basis.transpose();\n    TT.template block<2, 3>(0, 6) = -yita * basis.transpose();\n    TTT = TT.transpose() * TT;\n}\n\n// Point - Point\n\ninline void computeTangentBasis_PP(\n    const Eigen::RowVector3d& v0,\n    const Eigen::RowVector3d& v1,\n    Eigen::Matrix<double, 3, 2>& basis)\n{\n    Eigen::RowVector3d v01 = v1 - v0;\n    Eigen::RowVector3d xCross = Eigen::RowVector3d::UnitX().cross(v01);\n    Eigen::RowVector3d yCross = Eigen::RowVector3d::UnitY().cross(v01);\n    if (xCross.squaredNorm() > yCross.squaredNorm()) {\n        basis.col(0) = xCross.normalized().transpose();\n        basis.col(1) = v01.cross(xCross).normalized().transpose();\n    }\n    else {\n        basis.col(0) = yCross.normalized().transpose();\n        basis.col(1) = v01.cross(yCross).normalized().transpose();\n    }\n}\n\ninline void computeRelDX_PP(\n    const Eigen::RowVector3d& dx0,\n    const Eigen::RowVector3d& dx1,\n    Eigen::RowVector3d& relDX)\n{\n    relDX = dx0 - dx1;\n}\n\ninline void liftRelDXTanToMesh_PP(\n    const Eigen::Vector2d& relDXTan,\n    const Eigen::Matrix<double, 3, 2>& basis,\n    Eigen::Matrix<double, 6, 1>& TTTDX)\n{\n    TTTDX.template segment<3>(0) = basis * relDXTan;\n    TTTDX.template segment<3>(3) = -TTTDX.template segment<3>(0);\n}\n\ninline void computeTTT_PP(\n    const Eigen::Matrix<double, 3, 2>& basis,\n    Eigen::Matrix<double, 6, 6>& TTT)\n{\n    Eigen::Matrix<double, 2, 6> TT;\n    TT.template block<2, 3>(0, 0) = basis.transpose();\n    TT.template block<2, 3>(0, 3) = -basis.transpose();\n    TTT = TT.transpose() * TT;\n}\n\n// static friction clamping model\n// C0 clamping\ninline void f0_SF_C0(double x2, double eps_f, double& f0)\n{\n    f0 = x2 / (2.0 * eps_f) + eps_f / 2.0;\n}\n\ninline void f1_SF_div_relDXNorm_C0(double eps_f, double& result)\n{\n    result = 1.0 / eps_f;\n}\n\ninline void f2_SF_C0(double eps_f, double& f2)\n{\n    f2 = 1.0 / eps_f;\n}\n\n// C1 clamping\ninline void f0_SF_C1(double x2, double eps_f, double& f0)\n{\n    f0 = x2 * (-std::sqrt(x2) / 3.0 + eps_f) / (eps_f * eps_f) + eps_f / 3.0;\n}\n\ninline void f1_SF_div_relDXNorm_C1(double x2, double eps_f, double& result)\n{\n    result = (-std::sqrt(x2) + 2.0 * eps_f) / (eps_f * eps_f);\n}\n\ninline void f2_SF_C1(double x2, double eps_f, double& f2)\n{\n    f2 = 2.0 * (eps_f - std::sqrt(x2)) / (eps_f * eps_f);\n}\n\n// C2 clamping\ninline void f0_SF_C2(double x2, double eps_f, double& f0)\n{\n    f0 = x2 * (0.25 * x2 - (std::sqrt(x2) - 1.5 * eps_f) * eps_f) / (eps_f * eps_f * eps_f) + eps_f / 4.0;\n}\n\ninline void f1_SF_div_relDXNorm_C2(double x2, double eps_f, double& result)\n{\n    result = (x2 - (3.0 * std::sqrt(x2) - 3.0 * eps_f) * eps_f) / (eps_f * eps_f * eps_f);\n}\n\ninline void f2_SF_C2(double x2, double eps_f, double& f2)\n{\n    f2 = 3.0 * (x2 - (2.0 * std::sqrt(x2) - eps_f) * eps_f) / (eps_f * eps_f * eps_f);\n}\n\n// interfaces\ninline void f0_SF(double relDXSqNorm, double eps_f, double& f0)\n{\n#if (SFCLAMPING_ORDER == 0)\n    f0_SF_C0(relDXSqNorm, eps_f, f0);\n#elif (SFCLAMPING_ORDER == 1)\n    f0_SF_C1(relDXSqNorm, eps_f, f0);\n#elif (SFCLAMPING_ORDER == 2)\n    f0_SF_C2(relDXSqNorm, eps_f, f0);\n#endif\n}\n\ninline void f1_SF_div_relDXNorm(double relDXSqNorm, double eps_f, double& result)\n{\n#if (SFCLAMPING_ORDER == 0)\n    f1_SF_div_relDXNorm_C0(eps_f, result);\n#elif (SFCLAMPING_ORDER == 1)\n    f1_SF_div_relDXNorm_C1(relDXSqNorm, eps_f, result);\n#elif (SFCLAMPING_ORDER == 2)\n    f1_SF_div_relDXNorm_C2(relDXSqNorm, eps_f, result);\n#endif\n}\n\ninline void f2_SF(double relDXSqNorm, double eps_f, double& f2)\n{\n#if (SFCLAMPING_ORDER == 0)\n    f2_SF_C0(eps_f, f2);\n#elif (SFCLAMPING_ORDER == 1)\n    f2_SF_C1(relDXSqNorm, eps_f, f2);\n#elif (SFCLAMPING_ORDER == 2)\n    f2_SF_C2(relDXSqNorm, eps_f, f2);\n#endif\n}\n\n} // namespace IPC\n\n#endif /* FrictionUtils_hpp */\n", "meta": {"hexsha": "cabb3f444a41ff207b0732426f6f8872aea94564", "size": 9823, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/CollisionObject/FrictionUtils.hpp", "max_stars_repo_name": "vincentkslim/IPC", "max_stars_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 344.0, "max_stars_repo_stars_event_min_datetime": "2020-07-03T14:08:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T14:01:11.000Z", "max_issues_repo_path": "src/CollisionObject/FrictionUtils.hpp", "max_issues_repo_name": "vincentkslim/IPC", "max_issues_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2020-07-05T15:56:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T20:56:39.000Z", "max_forks_repo_path": "src/CollisionObject/FrictionUtils.hpp", "max_forks_repo_name": "vincentkslim/IPC", "max_forks_repo_head_hexsha": "eb702ead6f23a1dc0be39c9f5a0fd62c80abeb98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2020-07-04T05:04:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T02:09:23.000Z", "avg_line_length": 28.2270114943, "max_line_length": 106, "alphanum_fraction": 0.6436933727, "num_tokens": 3489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.415957694679659}}
{"text": "/* Copyright 2017 Battelle Energy Alliance, LLC\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n/*\n * distributionNDNormal.C\n * Created on Oct. 23, 2015\n * Author: @wangc\n * Extracted from @alfoa (Feb 6, 2014) distribution_base_ND.C\n *\n */\n\n#include \"distributionNDNormal.h\"\n#include \"distributionNDBase.h\"\n#include \"DistributionContainer.h\"\n#include <stdexcept>\n#include <iostream>\n#include \"MDreader.h\"\n#include \"distributionFunctions.h\"\n#include <cmath>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/math/distributions/chi_squared.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/erf.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include \"distribution_1D.h\"\nusing boost::math::normal;\n\n#include <ctime>\n\n#define _use_math_defines\n\n//#include <boost/numeric/ublas/matrix.hpp>\n//#include <boost/numeric/ublas/lu.hpp>\n//#include <boost/numeric/ublas/io.hpp>\n\n//using namespace boost::numeric::ublas;\n\n#define throwError(msg) { std::cerr << \"\\n\\n\" << msg << \"\\n\\n\"; throw std::runtime_error(\"Error\"); }\n\n#ifndef M_PI\n//PI is not actually defined anywhere in the C++ standard.\n#define M_PI 3.14159265358979323846\n#endif\n\nvoid BasicMultivariateNormal::base10ToBaseN(int value_base10, int base, std::vector<int> & value_base_n){\n    /**\n     * This function convert a number in base 10 to a new number in any base N\n     */\n\n     int index = 0 ;\n\n     if (value_base10 == 0)\n       value_base_n.push_back(0);\n     else{\n       while ( value_base10 != 0 ){\n         int remainder = value_base10 % base ;  // assume K > 1\n         value_base10  = value_base10 / base ;  // integer division\n         value_base_n.push_back(remainder);\n         index++ ;\n      }\n     }\n}\n\n//void BasicMultivariateNormal::basicMultivariateNormalInit(std::string data_filename, std::vector<double> mu){\nvoid BasicMultivariateNormal::basicMultivariateNormalInit(unsigned int &rows, unsigned int &columns, std::vector<std::vector<double> > cov_matrix, std::vector<double> mu){\n    /**\n     * This is the base function that initializes the Multivariate normal distribution\n     * Input Parameter\n     * rows: first dimension of covariance matrix\n     * columns: second dimension of covariance matrix\n     * cov_matrix: covariance matrix stored in vector<vector<double> >\n     * mu: mean value stored in vector<double>\n     */\n\n   _mu = mu;\n   _cov_matrix = cov_matrix;\n\n   std::vector<std::vector<double> > inverseCovMatrix (rows,std::vector< double >(columns));\n\n   computeInverse(_cov_matrix, inverseCovMatrix);\n\n   for (unsigned int i=0;i<rows;i++){\n    std::vector<double> temp;\n    for (unsigned int j=0;j<columns;j++)\n     temp.push_back(inverseCovMatrix.at(i).at(j));\n    _inverse_cov_matrix.push_back(temp);\n   }\n\n   unsigned int dimensions = _mu.size();\n   //for(int i=0; i<dimensions; i++)\n  //for(int j=0; j<dimensions; j++)\n   //std::cerr<<_inverse_cov_matrix[i][j]<<std::endl;\n\n   _determinant_cov_matrix = getDeterminant(_cov_matrix);\n\n   _cholesky_C = choleskyDecomposition(_cov_matrix);\n\n   if(rows != columns)\n     throwError(\"MultivariateNormal error: covariance matrix in is not a square matrix.\");\n\n   // Creation BasicMultiDimensionalCartesianSpline(std::vector< std::vector<double> > & discretizations, std::vector<double> & values, std::vector<double> alpha, std::vector<double> beta, bool cdf_provided)\n\n   int numberValues=1;\n   std::vector< std::vector<double> > discretizations;\n   std::vector<double> alpha (_mu.size());\n   std::vector<double> beta (_mu.size());\n   // for now we use this to be a bit more less problem dependent\n   double floatDiscretizations = (1./std::pow(1.e-4,1./ (double)dimensions)) + 0.5;\n   int numberOfDiscretizations = (int)floatDiscretizations;\n   for(unsigned int i=0; i<dimensions; i++){\n     alpha.at(i) = 0.0;\n     beta.at(i)  = 0.0;\n     numberValues = numberValues * numberOfDiscretizations;\n\n     std::vector<double> discretization_temp;\n     double sigma = sqrt(_cov_matrix[i][i]);\n     double deltaSigma = 12.0*sigma/(double)numberOfDiscretizations;\n     for(int n=0; n<numberOfDiscretizations; n++){\n       double disc_value = mu.at(i) - 6.0 * sigma + deltaSigma * (double)n;\n       discretization_temp.push_back(disc_value);\n     }\n     discretizations.push_back(discretization_temp);\n     _lower_bounds.push_back(discretization_temp.at(0));\n     _upper_bounds.push_back(discretization_temp.back());\n   }\n   std::vector< double > values (numberValues);\n   for(int i=0; i<numberValues; i++){\n     std::vector<int> intCoordinates;\n     base10ToBaseN(i,numberOfDiscretizations,intCoordinates);\n     std::vector<double> point_coordinates(dimensions);\n     std::vector<int> intCoordinatesFormatted(dimensions);\n\n     for(unsigned int j=0; j<dimensions; j++)\n       intCoordinatesFormatted.at(j) = 0;\n     for(unsigned int j=0; j<intCoordinates.size(); j++)\n       intCoordinatesFormatted.at(j) = intCoordinates.at(j);\n\n     for(unsigned int j=0; j<intCoordinates.size(); j++)\n       point_coordinates.at(j) = discretizations.at(j).at(intCoordinatesFormatted.at(j));\n\n     values.at(i) = getPdf(point_coordinates, _mu, _inverse_cov_matrix);\n   }\n   _cartesian_distribution = BasicMultiDimensionalCartesianSpline(discretizations,values,alpha,beta,false);\n\n}\n\nBasicMultivariateNormal::BasicMultivariateNormal(std::string data_filename, std::vector<double> mu){\n    /**\n     * This is the function that initializes the Multivariate normal distribution given:\n     * - data_filename: it specifies the covariance matrix\n     * - mu: the mean value vector\n     */\n  unsigned int rows,columns;\n  std::vector<std::vector<double> > cov_matrix;\n  readMatrix(data_filename, rows, columns, cov_matrix);\n  basicMultivariateNormalInit(rows,columns,cov_matrix, mu);\n}\n\nBasicMultivariateNormal::BasicMultivariateNormal(const char * data_filename, std::vector<double> mu){\n    /**\n     * This is the function that initializes the Multivariate normal distribution given:\n     * - data_filename: it specifies the covariance matrix\n     * - mu: the mean value vector\n     */\n  unsigned int rows,columns;\n  std::vector<std::vector<double> > cov_matrix;\n  readMatrix(std::string(data_filename), rows, columns, cov_matrix);\n  basicMultivariateNormalInit(rows,columns,cov_matrix, mu);\n  //basicMultivariateNormalInit(std::string(data_filename) , mu);\n}\n\nBasicMultivariateNormal::BasicMultivariateNormal(std::vector<std::vector<double> > cov_matrix, std::vector<double> mu){\n  /**\n   * This is the function that initializes the Multivariate normal distribution given:\n   * - cov_matrix: covariance matrix\n   * - mu: the mean value vector\n   */\n  unsigned int rows, columns;\n  rows = cov_matrix.size();\n  columns = cov_matrix.at(0).size();\n\n  basicMultivariateNormalInit(rows,columns,cov_matrix, mu);\n  //_mu = mu;\n  //_cov_matrix = cov_matrix;\n\n  //computeInverse(_cov_matrix, _inverse_cov_matrix);\n\n  //_determinant_cov_matrix = getDeterminant(_cov_matrix);\n}\n\n// Input Parameters: vectors of covariance and mu\nBasicMultivariateNormal::BasicMultivariateNormal(std::vector<double> vec_cov_matrix, std::vector<double> mu){\n  /**\n   * This is the function that initializes the Multivariate normal distribution given:\n   * Input Parameters\n   * - vec_cov_matrix: covariance matrix stored in a vector<double>\n   * - mu: the mean value vector\n   */\n\n  unsigned int rows, columns;\n  std::vector<std::vector<double> > cov_matrix;\n  // convert the vec_cov_matrix to cov_matrix, output the rows and columns of the covariance matrix\n  vectorToMatrix(rows,columns,vec_cov_matrix,cov_matrix);\n\n  basicMultivariateNormalInit(rows,columns,cov_matrix, mu);\n}\n\nBasicMultivariateNormal::BasicMultivariateNormal(std::vector<double> vec_cov_matrix, std::vector<double> mu, const char* type, int rank){\n  /**\n   * This is the function that initializes the Multivariate normal distribution given:\n   * First, we will make sure the given covariance, i.e. vec_cov_matrix, is symmetric, function 'computeNearestSymmetricMatrix' will be called\n   * Second, we will compute the svd of the computed symmetric matrix\n   * Third, we will make sure the reconstructed covariance matrix will be symmetric positive semidefinite matrix, function resetSingularValues will be called\n   * Reference for compute the nearest symmetric positive semidefinte matrix:\n   * 1. Nicholas J. Higham, \"Computing a Nearest Symmetric Positive Semidefinite Matrix,\" Linear Algebra and Its Applications, vol. 103, pp. 103-118 (1988)\n   * 2. Risto Vanhanen, \"Computing Positive Semidefinite Multigroup Nuclear Data Covariances,\" Nuclear Science and Engineering, vol. 179, pp. 411-422 (2015)\n   * Input Parameters\n   * - vec_cov_matrix: covariance matrix stored in a vector<double>\n   * - mu: the mean value vector\n   * - rank: the reduced dimension\n   * - type: the type of given covariance matrix (vec_cov_matrix), it can be 'abs' or 'rel', which means absolute covariance matrix or relative convariance matrix respectively.\n   */\n  unsigned int rows, columns;\n  std::vector<std::vector<double> > cov_matrix;\n  std::vector<std::vector<double> > symmetricCovMatrix;\n  // convert the vec_cov_matrix to cov_matrix, output the rows and columns of the covariance matrix\n  vectorToMatrix(rows,columns,vec_cov_matrix,cov_matrix);\n  // compute the nearest symmetric covariance matrix\n  computeNearestSymmetricMatrix(cov_matrix,symmetricCovMatrix);\n  _mu = mu;\n  _cov_matrix = symmetricCovMatrix;\n  _rank = (unsigned int) rank;\n  _covariance_type = std::string(type);\n  if(_rank > _mu.size()) {\n    throwError(\"The  provided rank  is larger than the given problem's dimension, it should be less or equal!\" );\n  }\n  if (_rank == _mu.size()) {\n    std::vector<std::vector<double> > inverseCovMatrix (rows,std::vector< double >(columns));\n    computeInverse(_cov_matrix, inverseCovMatrix);\n    for (unsigned int i=0;i<rows;i++){\n      std::vector<double> temp;\n      for (unsigned int j=0;j<columns;j++)\n      temp.push_back(inverseCovMatrix.at(i).at(j));\n      _inverse_cov_matrix.push_back(temp);\n    }\n    _determinant_cov_matrix = getDeterminant(_cov_matrix);\n  }\n\n  //compute the svd\n  computeSVD(_rank);\n  //setup the nearest symmetric semi-positive definite covariance matrix\n  resetSingularValues(_left_singular_vectors, _right_singular_vectors, _singular_values,_svd_transformed_matrix);\n\n  unsigned int dimensions = _mu.size();\n  // for now we use this to be a bit more less problem dependent\n  double floatDiscretizations = (1./std::pow(1.e-4,1./ (double)dimensions)) + 0.5;\n  int numberOfDiscretizations = (int)floatDiscretizations;\n    \n  for(unsigned int i=0; i<dimensions; i++){\n    std::vector<double> discretization_temp;\n    double sigma = sqrt(_cov_matrix[i][i]);\n    double deltaSigma = 12.0*sigma/(double)numberOfDiscretizations;\n    for(int n=0; n<numberOfDiscretizations; n++){\n      double disc_value = mu.at(i) - 6.0 * sigma + deltaSigma * (double)n;\n      discretization_temp.push_back(disc_value);\n    }\n    _lower_bounds.push_back(discretization_temp.at(0));\n    _upper_bounds.push_back(discretization_temp.back());\n  }\n\n}\n\nvoid BasicMultivariateNormal::computeSVD() {\n  /**\n   * This function will compute the svd for the covariance matrix stored in _cov_matrix\n   * and store the left singular vectors in _left_singular_vectors, right singular vectors in _right_singular_vectors\n   * singular values in _singular_values, and the transform matrix in _svd_transformed_matrix\n   * The transform matrix is defined as: _left_singular_vectors*sqrt(diag(_singular_values))\n   * @ In, None\n   * @ Out, None\n   */\n  svdDecomposition(_cov_matrix,_left_singular_vectors,_right_singular_vectors,_singular_values,_svd_transformed_matrix);\n}\n\nvoid BasicMultivariateNormal::computeSVD(int rank) {\n  /**\n   * This function will compute the truncated svd for the covariance matrix stored in _cov_matrix\n   * and store the left singular vectors in _left_singular_vectors, right singular vectors in _right_singular_vectors\n   * singular values in _singular_values, and the transform matrix in _svd_transformed_matrix\n   * The transform matrix is defined as: _left_singular_vectors*sqrt(diag(_singular_values))\n   * @ In, rank, int, the number of singular values that will be kept for the truncated svd\n   * @ Out, None\n   */\n  svdDecomposition(_cov_matrix,_left_singular_vectors,_right_singular_vectors,_singular_values,_svd_transformed_matrix, rank);\n}\n\nstd::vector<double> BasicMultivariateNormal::getTransformationMatrix() {\n  /**\n   * this function returns the transformation matrix\n   * @ In, None\n   * @ Out, returnVectors,std::vector<double>, the vector stores the left singular vectors\n   */\n  std::vector<double> returnVectors;\n  for(unsigned int i = 0; i < _svd_transformed_matrix.size(); ++i) {\n    for(unsigned int j = 0; j < _svd_transformed_matrix.at(0).size(); ++j) {\n      returnVectors.push_back(_svd_transformed_matrix.at(i).at(j));\n    }\n  }\n  return returnVectors;\n}\n\nstd::vector<double> BasicMultivariateNormal::getTransformationMatrix(std::vector<int> index) {\n  /**\n   * this function returns the transformation matrix\n   * @ In, index, std::vector<int>, the index of transformation matrix\n   * @ Out, returnVectors,std::vector<double>, the vector stores the left singular vectors associated with the provided index\n   */\n  std::vector<double> returnVectors;\n  for(unsigned int i = 0; i < _svd_transformed_matrix.size(); ++i) {\n    for(unsigned int j = 0; j < index.size(); ++j) {\n      if (index.at(j) < 0) {\n        throwError(\"Negative value is not allowed in the provided column index vector\");\n      }\n      returnVectors.push_back(_svd_transformed_matrix.at(i).at(index.at(j)));\n    }\n  }\n  return returnVectors;\n}\n\nstd::vector<int> BasicMultivariateNormal::getTransformationMatrixDimensions() {\n  /**\n   * return the row and colum of the transformation matrix stored in returnVector.at(0) and returnVector.at(1) respectively\n   * @ In, None\n   * @ Out, returnVector, std::vector<int>, row stored in returnVector.at(0), and column stored in returnVector.at(1)\n   */\n  std::vector<int> returnVector;\n  returnVector.push_back(_svd_transformed_matrix.size());\n  returnVector.push_back(_svd_transformed_matrix.at(0).size());\n  return returnVector;\n}\n\nstd::vector<int> BasicMultivariateNormal::getTransformationMatrixDimensions(std::vector<int> index) {\n  /**\n   * return the row and colum of the transformation matrix\n   * @ In, index, std::vector<int>, the index of transformation matrix\n   * @ Out,returnVector, std::vector<int>, row stored in returnVector.at(0), and column stored in returnVector.at(1).\n   */\n  std::vector<int> returnVector;\n  returnVector.push_back(_svd_transformed_matrix.size());\n  returnVector.push_back(index.size());\n  return returnVector;\n}\n\nstd::vector<double> BasicMultivariateNormal::getInverseTransformationMatrix() {\n  /**\n   * this function returns the inverse transformation matrix\n   * @ In, None\n   * @ Out, returnVectors,std::vector<double>, the vector stores the inverse transformation matrix\n   */\n  std::vector<std::vector<double> > inverse_transformed_matrix;\n  getInverseTransformedMatrix(_left_singular_vectors,_singular_values,inverse_transformed_matrix);\n  std::vector<double> returnVectors;\n  for(unsigned int i = 0; i < inverse_transformed_matrix.size(); ++i) {\n    for(unsigned int j = 0; j < inverse_transformed_matrix.at(0).size(); ++j) {\n      returnVectors.push_back(inverse_transformed_matrix.at(i).at(j));\n    }\n  }\n  return returnVectors;\n}\n\nstd::vector<double> BasicMultivariateNormal::getInverseTransformationMatrix(std::vector<int> index) {\n  /**\n   * this function returns the transformation matrix\n   * @ In, index, std::vector<int>, the index of inverse transformation matrix\n   * @ Out, returnVectors,std::vector<double>, the vector stores the inverse transformation matrix associated with the provided index\n   */\n  std::vector<std::vector<double> > inverse_transformed_matrix;\n  getInverseTransformedMatrix(_left_singular_vectors,_singular_values,inverse_transformed_matrix);\n  std::vector<double> returnVectors;\n  for(unsigned int i = 0; i < inverse_transformed_matrix.size(); ++i) {\n    for(unsigned int j = 0; j < index.size(); ++j) {\n      if (index.at(j) < 0) {\n        throwError(\"Negative value is not allowed in the provided column index vector\");\n      }\n      returnVectors.push_back(inverse_transformed_matrix.at(i).at(index.at(j)));\n    }\n  }\n  return returnVectors;\n}\n\nstd::vector<int> BasicMultivariateNormal::getInverseTransformationMatrixDimensions() {\n  /**\n   * return the row and colum of the inverse transformation matrix stored in returnVector.at(0) and returnVector.at(1) respectively\n   * @ In, None\n   * @ Out, returnVector, std::vector<int>, row stored in returnVector.at(0), and column stored in returnVector.at(1)\n   */\n  std::vector<std::vector<double> > inverse_transformed_matrix;\n  getInverseTransformedMatrix(_left_singular_vectors,_singular_values,inverse_transformed_matrix);\n  std::vector<int> returnVector;\n  returnVector.push_back(inverse_transformed_matrix.size());\n  returnVector.push_back(inverse_transformed_matrix.at(0).size());\n  return returnVector;\n}\n\nstd::vector<int> BasicMultivariateNormal::getInverseTransformationMatrixDimensions(std::vector<int> index) {\n  /**\n   * return the row and colum of the transformation matrix\n   * @ In, index, std::vector<int>, the index of inverse transformation matrix\n   * @ Out,returnVector, std::vector<int>, row stored in returnVector.at(0), and column stored in returnVector.at(1).\n   */\n  std::vector<std::vector<double> > inverse_transformed_matrix;\n  getInverseTransformedMatrix(_left_singular_vectors,_singular_values,inverse_transformed_matrix);\n  std::vector<int> returnVector;\n  returnVector.push_back(inverse_transformed_matrix.size());\n  returnVector.push_back(index.size());\n  return returnVector;\n}\n\nstd::vector<double> BasicMultivariateNormal::getLeftSingularVectors() {\n  /**\n   * this function returns the left singular vectors\n   * @ In, None\n   * @ Out, returnVectors, std::vector<double>, the vector stores the left singular vectors\n   */\n  std::vector<double> returnVectors;\n  for(unsigned int i = 0; i < _left_singular_vectors.size(); ++i) {\n    for(unsigned int j = 0; j < _left_singular_vectors.at(0).size(); ++j) {\n      returnVectors.push_back(_left_singular_vectors.at(i).at(j));\n    }\n  }\n  return returnVectors;\n}\n\nstd::vector<double> BasicMultivariateNormal::getLeftSingularVectors(std::vector<int> index) {\n  /**\n   * this function returns the left singular vectors associated with index\n   * @ In, index, std::vector<int>, the index of left singular vectors\n   * @ Out, returnVectors, std::vector<double> the vector stores the left singular vectors associated with index\n   */\n  std::vector<double> returnVectors;\n  for(unsigned int i = 0; i < _left_singular_vectors.size(); ++i) {\n    for(unsigned int j = 0; j < index.size(); ++j) {\n      if (index.at(j) < 0) {\n        throwError(\"Negative value is not allowed in the provided column index vector\");\n      }\n      returnVectors.push_back(_left_singular_vectors.at(i).at(index.at(j)));\n    }\n  }\n  return returnVectors;\n}\n\nstd::vector<double> BasicMultivariateNormal::getRightSingularVectors() {\n  /**\n   * this function returns the right singular vectors\n   * @ In, None\n   * @ Out, returnVectors, std::vector<double>, the vector stores the right singular vectors\n   */\n  std::vector<double> returnVectors;\n  for(unsigned int i = 0; i < _right_singular_vectors.size(); ++i) {\n    for(unsigned int j = 0; j < _right_singular_vectors.at(0).size(); ++j) {\n      returnVectors.push_back(_right_singular_vectors.at(i).at(j));\n    }\n  }\n  return returnVectors;\n}\n\nstd::vector<double> BasicMultivariateNormal::getRightSingularVectors(std::vector<int> index) {\n  /**\n   * this function returns the right singular vectors associated with the provided index\n   * @ In, index, std::vector<int> the index of left singular vectors\n   * @ Out, returnVectors, std::vector<double>, the vector stores the right singular vectors\n   */\n  std::vector<double> returnVectors;\n  for(unsigned int i = 0; i < _right_singular_vectors.size(); ++i) {\n    for(unsigned int j = 0; j < index.size(); ++j) {\n      if (index.at(j)< 0) {\n        throwError(\"Negative value is not allowed in the provided column index vector\");\n      }\n      returnVectors.push_back(_right_singular_vectors.at(i).at(index.at(j)));\n    }\n  }\n  return returnVectors;\n}\n\nstd::vector<double> BasicMultivariateNormal::getSingularValues() {\n  /**\n   * this function returns the singular values\n   * @ In, None\n   * @ Out, _singular_values, std::vector<double> the vector stores the singular values\n   */\n  return _singular_values;\n}\n\nstd::vector<double> BasicMultivariateNormal::getSingularValues(std::vector<int> index) {\n  /**\n   * this function returns the singular values associated with the provided index\n   * @ In, index, std::vector<int>, the  index of left singular vectors\n   * @ Out, returnVector, std::vector<double>, the vector stores the singular values associated with the provided inde\n   */\n  std::vector<double> returnVector;\n  for(unsigned int i = 0; i < index.size(); ++i) {\n    if (index.at(i) < 0) {\n      throwError(\"Negative value is not allowed in the provided index vector\");\n    }\n    returnVector.push_back(_singular_values.at(index.at(i)));\n  }\n  return returnVector;\n}\n\nstd::vector<int> BasicMultivariateNormal::getLeftSingularVectorsDimensions() {\n  /**\n   * return the row and column of left singular vectors stored in returnVector.at(0) and returnVector.at(1) respectively\n   * @ In, None\n   * @ Out, returnVector, std::vector<int>, row stored in returnVector.at(0), and column stored in returnVector.at(1)\n   */\n  std::vector<int> returnVector;\n  returnVector.push_back(_left_singular_vectors.size());\n  returnVector.push_back(_left_singular_vectors.at(0).size());\n  return returnVector;\n}\n\nstd::vector<int> BasicMultivariateNormal::getLeftSingularVectorsDimensions(std::vector<int> index) {\n  /**\n   * return the row and column of left singular vectors stored in returnVector.at(0) and returnVector.at(1) respectively\n   * @ In, index, std::vector<int>, the index of left singular vectors\n   * @ Out, returnVector, std::vector<int>, return the row and column of left singular vectors with provided index  stored in returnVector.at(0) and returnVector.at(1) respectively\n   */\n  std::vector<int> returnVector;\n  returnVector.push_back(_left_singular_vectors.size());\n  returnVector.push_back(index.size());\n  return returnVector;\n}\n\nstd::vector<int> BasicMultivariateNormal::getRightSingularVectorsDimensions() {\n  /**\n   * return the row and column of right singular vectors stored in returnVector.at(0) and returnVector.at(1) respectively\n   * @ In, None\n   * @ Out, returnVector, std::vector<int>, row stored in returnVector.at(0), and column stored in returnVector.at(1)\n   */\n  std::vector<int> returnVector;\n  returnVector.push_back(_right_singular_vectors.size());\n  returnVector.push_back(_right_singular_vectors.at(0).size());\n  return returnVector;\n}\n\nstd::vector<int> BasicMultivariateNormal::getRightSingularVectorsDimensions(std::vector<int> index) {\n  /**\n   * return the row and column of right singular vectors stored in returnVector.at(0) and returnVector.at(1) respectively\n   * @ In, index, std::vector<int>, the index of right singular vectors\n   * @ Out, returnVector, std::vector<int>, return the row and column of right singular vectors with provided index  stored in returnVector.at(0) and returnVector.at(1) respectively\n   */\n  std::vector<int> returnVector;\n  returnVector.push_back(_right_singular_vectors.size());\n  returnVector.push_back(index.size());\n  return returnVector;\n}\n\nint  BasicMultivariateNormal::getSingularValuesDimension() {\n  /**\n   * return the dimension of  singular value vector stored\n   * @ In, None\n   * @ Out, _singular_values.size(), int, the size of vector _singular_values\n   */\n  return _singular_values.size();\n}\n\nint  BasicMultivariateNormal::getSingularValuesDimension(std::vector<int> index) {\n  /**\n   * return the dimension of  singular value vector with provided index set.\n   * @ In, index, std::vector<int>, the index of singular values\n   * @ Out, index.size(), int, return the size of singular value vector with provided index set\n   */\n  return index.size();\n}\n\nstd::vector<double> BasicMultivariateNormal::coordinateInTransformedSpace(int rank) {\n  /**\n   * This function will return the coordinate in the transformed space\n   * This function will generate the coordinate for r (r=rank) random variables, each of them\n   * are drew from single normal distribution. We need a random number between 0 and 1 to drew\n   * the random variable. In addition, thi function will be used in the input dimensionality reduction\n   * application. We will transform the correlated variables into uncorrelated variables, and using this\n   * function to draw the samples for the uncorrelated variables, and later transform the samples to correlated\n   * variables.\n   * @ In, rank, int, the effective dimension of the transformed space\n   * @ Out, coordinate, std::vector<double>, the coordinate in the transformed space\n   */\n  //std::cout << \"BasicMultivariateNormal::coordinateInTransformedSpace\" << std::endl;\n  std::vector<double> coordinate;\n  BasicNormalDistribution * normalDistribution = new BasicNormalDistribution(0,1);\n  DistributionContainer *distributionInstance = & DistributionContainer::instance();\n  double randValue = 0.0;\n  for(int i = 0; i < rank; ++i) {\n    randValue = distributionInstance->random();\n    double coordinateValue = normalDistribution->inverseCdf(randValue);\n    coordinate.push_back(coordinateValue);\n  }\n  delete normalDistribution;\n  return coordinate;\n}\n\nstd::vector<double> BasicMultivariateNormal::coordinateInverseTransformed(std::vector<double> & coordinate) {\n  /**\n   * This function will transform the coordinate back to the original space\n   * and the transformation are computed using computeSVD.\n   * @ In, coordinate, std::vector<double>, the coordinate in the transformed space\n   * @ Out, originalCoordinate, std::vector<double>, the coordinate in the full space\n   */\n  //std::cout << \"BasicMultivariateNormal::coordinateInverseTransformed\" << std::endl;\n  std::vector<double> originalCoordinate;\n  for(unsigned int irow = 0; irow < _svd_transformed_matrix.size(); ++irow) {\n    double tempSum = 0.0;\n    for(unsigned int icol = 0; icol < _svd_transformed_matrix.at(0).size(); ++icol) {\n      tempSum = tempSum + _svd_transformed_matrix.at(irow).at(icol) * coordinate.at(icol);\n    }\n    originalCoordinate.push_back(tempSum);\n  }\n  if(_covariance_type == \"abs\") {\n    for(unsigned int idim = 0; idim < originalCoordinate.size(); ++idim) {\n      originalCoordinate.at(idim) += _mu.at(idim);\n    }\n  } else if (_covariance_type == \"rel\") {\n    for(unsigned int idim = 0; idim < originalCoordinate.size(); ++idim) {\n      originalCoordinate.at(idim) = _mu.at(idim)*(1.0 + originalCoordinate.at(idim));\n    }\n  } else {\n    throwError(\"MultivariateNormal Error: covariance type is not available\");\n  }\n  return originalCoordinate;\n}\n\nstd::vector<double> BasicMultivariateNormal::coordinateInverseTransformed(std::vector<double> & coordinate,std::vector<int> index) {\n  /**\n   * This function will transform the coordinate back to the original space\n   * @ In, index, std::vector<int>, the index set associated with the provied coordinate\n   * @ In, coordinate, std::vector<double>, the coordinate in the transformed space\n   * @ Out, originalCoordinate, std::vector<double>, and the coordinate in the full space.\n   */\n  std::vector<double> originalCoordinate;\n  for(unsigned int irow = 0; irow < _svd_transformed_matrix.size(); ++irow) {\n    double tempSum = 0.0;\n    for(unsigned int icol = 0; icol < index.size(); ++icol) {\n      if (index[icol] < 0) {\n        throwError(\"Negative value is not allowed for the index set.\");\n      }\n      tempSum = tempSum + _svd_transformed_matrix.at(irow).at(index.at(icol)) * coordinate.at(icol);\n    }\n    originalCoordinate.push_back(tempSum);\n  }\n  if(_covariance_type == \"abs\") {\n    for(unsigned int idim = 0; idim < originalCoordinate.size(); ++idim) {\n      originalCoordinate.at(idim) += _mu.at(idim);\n    }\n  } else if (_covariance_type == \"rel\") {\n    for(unsigned int idim = 0; idim < originalCoordinate.size(); ++idim) {\n      originalCoordinate.at(idim) = _mu.at(idim)*(1.0 + originalCoordinate.at(idim));\n    }\n  } else {\n    throwError(\"MultivariateNormal Error: covariance type is not available\");\n  }\n  return originalCoordinate;\n}\n\ndouble BasicMultivariateNormal::cellProbabilityWeight(std::vector<double> center, std::vector<double> dx){\n    /**\n     * This function calculates the integral of the pdf in a cell region\n     * In the 1D case a cell region is an interval [a,b], thus the integral of the pdf in such interval is\n     * calculated as CDF(b)-CDF(a). This functions perform a similar evolution but for a generic ND cell\n     * This function assumes all the input variables are uncorrelated, and follows univariate normal distribution N(0,1)\n     * @ In, center, std::vector<double>, a vector to store the grid coordinate, for ND grid sampler, center represents the coordinate of given grid point\n     * @ In, dx, std::vector<double>,  a vector to store the distance between given grid coordinate and its connected points, for ND grid sampler, dx represents the distance between grid_coordinate_plus_one - grid_coordinate_minus_one, where grid_coordinate_plus_one and grid_coordinate_minus_one are the shift of \"center\"\n     * @ Out, value, double, the probability weight for the cell\n     */\n\n  double value = 1.0;\n  double upperBound = 0.0;\n  double lowerBound = 0.0;\n  double cdfValue = 0.0;\n  BasicNormalDistribution * normalDistribution = new BasicNormalDistribution(0,1);\n  for (unsigned int i = 0; i < center.size(); ++i) {\n    upperBound = center.at(i) + dx.at(i)/2.0;\n    lowerBound = center.at(i) - dx.at(i)/2.0;\n    cdfValue = normalDistribution->cdf(upperBound) - normalDistribution->cdf(lowerBound);\n    value *= cdfValue;\n  }\n  return value;\n}\n\ndouble BasicMultivariateNormal::inverseMarginalForPCA(double f){\n    /**\n     * This function calculates the inverse marginal distribution at f of a MVN distribution when using pca decomposition\n     * @ In, f, double, the value picked in the marginal cdf distribution\n     * @ Out, normalDistribution->inverseCdf(f), double, the variable value corresponding to the marginal cdf distribution at f\n     */\n  BasicNormalDistribution * normalDistribution = new BasicNormalDistribution(0,1);\n  return normalDistribution->inverseCdf(f);\n}\n\ndouble BasicMultivariateNormal::marginalCdfForPCA(double x){\n    /**\n     * This function calculates the marginal cdf at x of a MVN distribution when using pca decomposition\n     * If PCA method is used, the marginal cdf is assumed to be standard normal distribution, i.e. mean = 0.0 , and sigma = 1.0\n     * @ In, x, double, the variable value\n     * @ Out, normalDistribution->cdf(x), double, the marginal cdf value at x\n     */\n  BasicNormalDistribution * normalDistribution = new BasicNormalDistribution(0,1);\n  return normalDistribution->cdf(x);\n}\n\ndouble BasicMultivariateNormal::getPdf(std::vector<double> x, std::vector<double> mu, std::vector<std::vector<double> > inverse_cov_matrix){\n  /**\n   * This function calculates the pdf values at x of a MVN distribution\n   */\n\n  double value = 0;\n\n   if(mu.size() == x.size()){\n     int dimensions = mu.size();\n     double expTerm=0;\n     std::vector<double> tempVector (dimensions);\n     for(int i=0; i<dimensions; i++){\n       tempVector[i]=0;\n       for(int j=0; j<dimensions; j++)\n         tempVector[i] += inverse_cov_matrix[i][j]*(x[j]-mu[j]);\n       expTerm += tempVector[i]*(x[i]-mu[i]);\n     }\n     value = 1/sqrt(_determinant_cov_matrix*pow(2*M_PI,dimensions))*exp(-0.5*expTerm);\n   }else\n     throwError(\"MultivariateNormal PDF error: evaluation point dimensionality is not correct\");\n   return value;\n}\n\ndouble BasicMultivariateNormal::pdfInTransformedSpace(std::vector<double> x){\n  /**\n   * This function calculates the pdf values at x in the PCA transformed space\n   * @ In, x, double, the coordinate in the transformed space\n   * @ Out, value, double, the pdf value in the transformed space\n   */\n  double value = 1.0;\n  BasicNormalDistribution * normalDistribution = new BasicNormalDistribution(0,1);\n  for (unsigned int i = 0; i < x.size(); ++i) {\n    value *=  normalDistribution->pdf(x.at(i));\n  }\n  delete normalDistribution;\n  return value;\n}\n\ndouble BasicMultivariateNormal::pdf(std::vector<double> x){\n    /**\n     * This function calculates the pdf values at x of a MVN distribution\n     */\n  return getPdf(x, _mu, _inverse_cov_matrix);\n}\n\ndouble BasicMultivariateNormal::cdf(std::vector<double> x){\n    /**\n     * This function calculates the cdf values at x of a MVN distribution\n     */\n  return _cartesian_distribution.cdf(x);\n}\n\nstd::vector<double> BasicMultivariateNormal::inverseCdf(double f, double g){\n    /**\n     * This function calculates the inverse CDF values at f of a MVN distribution\n     */\n  return _cartesian_distribution.inverseCdf(f,g);\n}\n\ndouble BasicMultivariateNormal::inverseMarginal(double f, int dimension){\n    /**\n     * This function calculates the inverse marginal distribution at f for a specific dimension of a MVN distribution\n     */\n  return _cartesian_distribution.inverseMarginal(f,dimension);\n}\n\nint BasicMultivariateNormal::returnDimensionality(){\n    /**\n     * This function returns the dimensionality of a MVN distribution\n     */\n  return _mu.size();\n}\n\nvoid BasicMultivariateNormal::updateRNGparameter(double tolerance, double initial_divisions){\n    /**\n     * This function updates the random number generator parameters of a MVN distribution\n     */\n  return _cartesian_distribution.updateRNGparameter(tolerance,initial_divisions);\n}\n\ndouble BasicMultivariateNormal::marginal(double x, int dimension){\n    /**\n     * This function calculates the marginal distribution at x for a specific dimension of a MVN distribution\n     */\n  return _cartesian_distribution.marginal(x,dimension);\n}\n\n//double BasicMultivariateNormal::cdf_(std::vector<double> x){\n//// if(_mu.size() == x.size()){\n////  int dimensions = _mu.size();\n////  //boost::math::chi_squared chiDistribution(dimensions);\n////\n////  double mahalanobis=0.0;\n////  std::vector<double> tempVector (dimensions);\n////  for(int i=0; i<dimensions; i++)\n////   tempVector[i]=0.0;\n////\n////  for(int i=0; i<dimensions; i++){\n////   tempVector[i]=0.0;\n////   for(int j=0; j<dimensions; j++)\n////    tempVector[i] += _inverseCovMatrix[i][j]*(x[j]-_mu[j]);\n////   mahalanobis += tempVector[i]*(x[i]-_mu[i]);\n////  }\n////  value = boost::math::gamma_p<double,double>(dimensions/2,mahalanobis/2);\n//// }else\n////  throwError(\"MultivariateNormal CDF error: evaluation point dimensionality is not correct\");\n//\n// double alpha = 2.5;\n// int Nmax = 50;\n// double epsilon= 0.01;\n// double delta;\n//\n// int dimensions = _cov_matrix.size();\n// double Intsum=0;\n// double Varsum=0;\n// int N = 0;\n// double error=10*epsilon;\n// std::vector<double> d (dimensions);\n// std::vector<double> e (dimensions);\n// std::vector<double> f (dimensions);\n//\n// d[0] = 0.0;\n// e[0] = phi(x[0]/_cholesky_C[0][0]);\n// f[0] = e[0] - d[0];\n//\n// boost::random::mt19937 rng;\n// rng.seed(time(NULL));\n// double range = rng.max() - rng.min();\n//\n// while (error>epsilon or N<Nmax){\n//  std::vector<double> w (dimensions-1);\n//\n//  for (int i=0; i<(dimensions-1); i++){\n//   w.at(i) = (rng()-rng.min())/range;\n//   //std::cout<< \"value: \" << w.at(i) << std::endl;\n//  }\n//\n//  std::vector<double> y (dimensions-1);\n//\n//  for (int i=1; i<dimensions; i++){\n//   double tempY = d.at(i-1) + w.at(i-1) * (e.at(i-1)-d.at(i-1));\n//\n//   y.at(i-1) = phiInv(tempY);\n//\n//   double tempE = x.at(i);\n//\n//   for (int j=0; j<(i-1); j++)\n//    tempE = tempE - _cholesky_C[i][j] * y.at(j) / _cholesky_C[i][i];\n//\n//   e.at(i)=phi(tempE);\n//   d.at(i)=0.0;\n//   f.at(i)=(e.at(i)-d.at(i))*f.at(i-1);\n//  }\n//\n//  N++;\n//  delta = (f.at(dimensions-1)-Intsum)/double(N);\n//  Intsum = Intsum + delta;\n//  Varsum = (double(N-2))*Varsum/double(N) + delta*delta;\n//  error = alpha * sqrt(Varsum);\n//\n//  std::cout << \"N \" << N << \" ; f: \" << f.at(dimensions-1) << \" ; delta: \" << delta << \" ; Intsum: \" << Intsum << \" ; Varsum: \" << Varsum << \"; error: \" << error << std::endl;\n// }\n//\n// return Intsum;\n//}\n\nBasicMultivariateNormal::~BasicMultivariateNormal(){\n\n}\n\ndouble BasicMultivariateNormal::phi(double x){\n double value = 0.5 * (1.0 + boost::math::erf<double>(x/sqrt(2.0)));\n //double value = 0.5 * (boost::math::erf<double>(x/sqrt(2)));\n return value;\n}\n\ndouble BasicMultivariateNormal::phiInv(double x){\n normal s;\n double value = quantile(s,x);\n return value;\n}\n\n//double BasicMultivariateNormal::rn(){\n//    boost::random::mt19937 rng;\n// rng.seed(time(NULL));\n// double range = rng.max() - rng.min();\n// double value = (rng()-rng.min())/range;\n// std::cout<< \"value: \" << value << std::endl;\n// return value;\n//}\n\n//double BasicMultivariateNormal::MVNDST(std::vector<double> a, std::vector<double> b, double alpha, double epsilon, int Nmax){\n// int dimensions = _cov_matrix.size();\n// double Intsum=0;\n// double Varsum=0;\n// int N = 0;\n// double error;\n// std::vector<double> d (dimensions);\n// std::vector<double> e (dimensions);\n// std::vector<double> f (dimensions);\n//\n// std::vector<std::vector<double> > cholesky_C = choleskyDecomposition(_cov_matrix);\n//\n// d[0] = phi(a[0]/cholesky_C[0][0]);\n// e[0] = phi(b[0]/cholesky_C[0][0]);\n// f[0] = e[0] - d[0];\n//\n//    boost::random::mt19937 rng;\n// rng.seed(time(NULL));\n// double range = rng.max() - rng.min();\n//\n// do{\n//  std::vector<double> w (dimensions-1);\n//  for (int i=0; i<(dimensions-1); i++){\n//   w.at(i) = (rng()-rng.min())/range;\n//   std::cout<< \"value: \" << rng() << std::endl;\n//  }\n//\n//  std::vector<double> y (dimensions-1);\n//  for (int i=1; i<dimensions; i++){\n//   double tempY = d.at(i-1) + w.at(i-1)*(e.at(i-1)-d.at(i-1));\n//   y.at(i-1) = phiInv(tempY);\n//\n//   double tempD = a.at(i);\n//   double tempE = b.at(i);\n//\n//   for (int j=0; j<(i-1); j++){\n//    tempD = tempD - cholesky_C[i][j] * y[j] / cholesky_C[i][i];\n//    tempE = tempE - cholesky_C[i][j] * y[j] / cholesky_C[i][i];\n//   }\n//\n//   d[i]=phi(tempD);\n//   e[i]=phi(tempE);\n//   f[i]=(e[i]-d[i])/f[i-1];\n//  }\n//\n//  N++;\n//  double delta = (f[dimensions-1]-Intsum)/N;\n//  Intsum = Intsum + delta;\n//  Varsum = (N-2)*Varsum/N + delta*delta;\n//  error = alpha * sqrt(Varsum);\n//\n// } while (error<epsilon and N<Nmax);\n//\n// return Intsum;\n//}\n\n//http://rosettacode.org/wiki/Cholesky_decomposition#C\ndouble *BasicMultivariateNormal::cholesky(double *A, int n) {\n    double *L = (double*)calloc(n * n, sizeof(double));\n    if (L == NULL)\n  exit(EXIT_FAILURE);\n\n    for (int i = 0; i < n; i++)\n  for (int j = 0; j < (i+1); j++) {\n      double s = 0;\n      for (int k = 0; k < j; k++)\n    s += L[i * n + k] * L[j * n + k];\n      L[i * n + j] = (i == j) ?\n         sqrt(A[i * n + i] - s) :\n         (1.0 / L[j * n + j] * (A[i * n + j] - s));\n  }\n\n    return L;\n}\n\nstd::vector<std::vector<double> > BasicMultivariateNormal::choleskyDecomposition(std::vector<std::vector<double> > matrix){\n std::vector<std::vector<double> > cholesky_C;\n\n int dimensions = matrix.size();\n double * m1 = new double[dimensions*dimensions];\n\n for (int r=0; r<dimensions; r++)\n  for (int c=0; c<dimensions; c++)\n   m1[r*dimensions+c] = matrix[r][c];\n\n double *c1 = cholesky(m1, dimensions);\n //std::cout << \"choleskyDecomposition\" << std::endl;\n //showMatrix(c1,dimensions);\n\n for (int r=0; r<dimensions; r++){\n  std::vector<double> temp;\n  for (int c=0; c<dimensions; c++)\n   temp.push_back(c1[r*dimensions+c]);\n  cholesky_C.push_back(temp);\n }\n delete m1;\n return cholesky_C;\n}\n\nvoid BasicMultivariateNormal::showMatrix(double *A, int n) {\n    for (int i = 0; i < n; i++) {\n  for (int j = 0; j < n; j++)\n      printf(\"%2.5f \", A[i * n + j]);\n  printf(\"\\n\");\n    }\n}\n\n//template<class T>\n//bool InvertMatrix(const matrix<T>& input, matrix<T>& inverse)\n//{\n// typedef permutation_matrix<std::size_t> pmatrix;\n//\n// // create a working copy of the input\n// matrix<T> A(input);\n//\n// // create a permutation matrix for the LU-factorization\n// pmatrix pm(A.size1());\n//\n// // perform LU-factorization\n// int res = lu_factorize(A, pm);\n// if (res != 0)\n//  return false;\n//\n// // create identity matrix of \"inverse\"\n// inverse.assign(identity_matrix<T> (A.size1()));\n//\n// // backsubstitute to get the inverse\n// lu_substitute(A, pm, inverse);\n//\n// return true;\n//}\n//\n//void getInverse(std::vector<std::vector<double> > matrix, std::vector<std::vector<double> > inverse_matrix){\n// int dimension = matrix.size();\n// double initialValues[dimension][dimension];\n// matrix<double> A(dimension, dimension), Z(dimension, dimension);\n//\n// for(int i=0; i<dimension; i++)\n//  for(int j=0; j<dimension; j++)\n//   initialValues[i][j]=matrix[i][j];\n// A = make_matrix_from_pointer(initialValues);\n// InvertMatrix(A, Z);\n//\n// for(int i=0; i<dimension; i++){\n//  std::vector<double> temp;\n//  for(int j=0; j<dimension; j++)\n//   temp.push_back(Z[i][j]);\n//  inverse_matrix.push_back(temp);\n// }\n//}\n", "meta": {"hexsha": "1d0f7e7b678c95c9bc6b8e001ae393fbb431614c", "size": 41840, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "crow/src/distributions/distributionNDNormal.cxx", "max_stars_repo_name": "rinelson456/raven", "max_stars_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 159.0, "max_stars_repo_stars_event_min_datetime": "2017-03-24T21:07:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:44:40.000Z", "max_issues_repo_path": "crow/src/distributions/distributionNDNormal.cxx", "max_issues_repo_name": "rinelson456/raven", "max_issues_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1667.0, "max_issues_repo_issues_event_min_datetime": "2017-03-27T14:41:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:50:06.000Z", "max_forks_repo_path": "crow/src/distributions/distributionNDNormal.cxx", "max_forks_repo_name": "rinelson456/raven", "max_forks_repo_head_hexsha": "1114246136a2f72969e75b5e99a11b35500d4eef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 95.0, "max_forks_repo_forks_event_min_datetime": "2017-03-24T21:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T17:30:22.000Z", "avg_line_length": 39.3233082707, "max_line_length": 322, "alphanum_fraction": 0.7007170172, "num_tokens": 10851, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.4159319342862605}}
{"text": "#include <Eigen/Dense>\n#include \"cxxopts.hpp\"\n#include \"simpleicp.h\"\n\nEigen::MatrixXd ImportXYZFileToMatrix(const std::string &path_to_pc);\n\nint main(int argc, char **argv)\n{\n  try\n  {\n\n    cxxopts::Options options(\"simpleicp\", \"A simple version of the ICP algorithm.\");\n\n    // clang-format off\n    options.add_options()\n      (\"f,fixed\", \"Path to fixed point cloud\",\n        cxxopts::value<std::string>())\n      (\"m,movable\", \"Path to movable point cloud\",\n        cxxopts::value<std::string>())\n      (\"c,correspondences\", \"Number of initially selected correspondences\",\n        cxxopts::value<int>()->default_value(\"1000\"))\n      (\"n,neighbors\", \"Number of neighbors used for plane estimation\",\n        cxxopts::value<int>()->default_value(\"10\"))\n      (\"p,min_planarity\", \"Minimal planarity value of planes used as correspondence\",\n        cxxopts::value<double>()->default_value(\"0.3\"))\n      (\"o,max_overlap_distance\", \"Maximum initial overlap distance. Set to negative value if point \"\n      \"clouds are fully overlapping.\",\n        cxxopts::value<double>()->default_value(\"-1\"))\n      (\"i,min_change\", \"Minimal change of mean and standard deviation of distances (in percent) \"\n                       \"needed to proceed to next iteration\",\n        cxxopts::value<double>()->default_value(\"1\"))\n      (\"x,max_iterations\", \"Maximum number of iterations\",\n        cxxopts::value<int>()->default_value(\"100\"))\n      (\"h,help\", \"Print usage\")\n      ;\n    // clang-format on\n\n    auto result = options.parse(argc, argv);\n\n    if (result.count(\"help\") || argc == 1)\n    {\n      std::cout << options.help() << std::endl;\n      exit(0);\n    }\n\n    auto X_fix = ImportXYZFileToMatrix(std::string(result[\"fixed\"].as<std::string>()));\n    auto X_mov = ImportXYZFileToMatrix(std::string(result[\"movable\"].as<std::string>()));\n\n    Eigen::Matrix<double, 4, 4> H = SimpleICP(X_fix,\n                                              X_mov,\n                                              result[\"correspondences\"].as<int>(),\n                                              result[\"neighbors\"].as<int>(),\n                                              result[\"min_planarity\"].as<double>(),\n                                              result[\"max_overlap_distance\"].as<double>(),\n                                              result[\"min_change\"].as<double>(),\n                                              result[\"max_iterations\"].as<int>());\n  }\n  catch (const std::exception &e)\n  {\n    std::cerr << \"Caught exception: \" << e.what() << std::endl;\n    return 1;\n  }\n  catch (...)\n  {\n    std::cerr << \"Caught unknown exception.\" << std::endl;\n    return 1;\n  }\n\n  return 0;\n}\n\nEigen::MatrixXd ImportXYZFileToMatrix(const std::string &path_to_pc)\n{\n  std::ifstream data(path_to_pc);\n  if (data.is_open())\n  {\n    // Read data from file\n    std::vector<std::vector<std::string>> parsedData;\n    std::string line;\n    while (getline(data, line))\n    {\n      std::stringstream lineStream(line);\n      std::string cell; // single value\n      std::vector<std::string> parsedRow;\n      while (getline(lineStream, cell, ' '))\n      {\n        parsedRow.push_back(cell);\n      }\n      parsedData.push_back(parsedRow);\n    }\n\n    // Check if each line contains exactly 3 values\n    for (int i = 0; i < parsedData.size(); i++)\n    {\n      if (parsedData[i].size() != 3)\n      {\n        std::cerr << \"Line \" << i + 1 << \" does not contain exactly 3 values!\" << std::endl;\n        exit(-1);\n      }\n    }\n\n    // Create eigen array\n    Eigen::MatrixXd X(parsedData.size(), 3);\n    for (int i = 0; i < parsedData.size(); i++)\n    {\n      for (int j = 0; j < parsedData[i].size(); j++)\n      {\n        try\n        {\n          X(i, j) = stod(parsedData[i][j]);\n        }\n        catch (std::exception &e)\n        {\n          std::cerr << \"Conversion of \" << parsedData[i][j] << \" on row/column=\" << i << \"/\" << j\n                    << \" is not possible!\" << std::endl;\n          exit(-1);\n        }\n      }\n    }\n\n    return X;\n  }\n  else\n  {\n    std::cerr << \"Error opening file!\" << std::endl;\n    exit(-1);\n  }\n}\n", "meta": {"hexsha": "76f893e2de0a4896361bd8c954f0fdbe9fdd8b0c", "size": 4085, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/src/simpleicp-cli.cpp", "max_stars_repo_name": "Pandinosaurus/simpleICP", "max_stars_repo_head_hexsha": "608748d1f6bd6dfcf9405054db89250d0795aedd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/src/simpleicp-cli.cpp", "max_issues_repo_name": "Pandinosaurus/simpleICP", "max_issues_repo_head_hexsha": "608748d1f6bd6dfcf9405054db89250d0795aedd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/src/simpleicp-cli.cpp", "max_forks_repo_name": "Pandinosaurus/simpleICP", "max_forks_repo_head_hexsha": "608748d1f6bd6dfcf9405054db89250d0795aedd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6666666667, "max_line_length": 100, "alphanum_fraction": 0.5365973072, "num_tokens": 989, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.41593193428626046}}
{"text": "//  Copyright John Maddock 2006, 2007.\n//  Copyright Paul A. Bristow 2006, 2007.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_STATS_TRIANGULAR_HPP\n#define BOOST_STATS_TRIANGULAR_HPP\n\n// http://mathworld.wolfram.com/TriangularDistribution.html\n// http://en.wikipedia.org/wiki/Triangular_distribution\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/special_functions/expm1.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include <utility>\n\nnamespace boost{ namespace math\n{\n  namespace detail\n  {\n    template <class RealType, class Policy>\n    inline bool check_triangular_lower(\n      const char* function,\n      RealType lower,\n      RealType* result, const Policy& pol)\n    {\n      if((boost::math::isfinite)(lower))\n      { // Any finite value is OK.\n        return true;\n      }\n      else\n      { // Not finite: infinity or NaN.\n        *result = policies::raise_domain_error<RealType>(\n          function,\n          \"Lower parameter is %1%, but must be finite!\", lower, pol);\n        return false;\n      }\n    } // bool check_triangular_lower(\n\n    template <class RealType, class Policy>\n    inline bool check_triangular_mode(\n      const char* function,\n      RealType mode,\n      RealType* result, const Policy& pol)\n    {\n      if((boost::math::isfinite)(mode))\n      { // any finite value is OK.\n        return true;\n      }\n      else\n      { // Not finite: infinity or NaN.\n        *result = policies::raise_domain_error<RealType>(\n          function,\n          \"Mode parameter is %1%, but must be finite!\", mode, pol);\n        return false;\n      }\n    } // bool check_triangular_mode(\n\n    template <class RealType, class Policy>\n    inline bool check_triangular_upper(\n      const char* function,\n      RealType upper,\n      RealType* result, const Policy& pol)\n    {\n      if((boost::math::isfinite)(upper))\n      { // any finite value is OK.\n        return true;\n      }\n      else\n      { // Not finite: infinity or NaN.\n        *result = policies::raise_domain_error<RealType>(\n          function,\n          \"Upper parameter is %1%, but must be finite!\", upper, pol);\n        return false;\n      }\n    } // bool check_triangular_upper(\n\n    template <class RealType, class Policy>\n    inline bool check_triangular_x(\n      const char* function,\n      RealType const& x,\n      RealType* result, const Policy& pol)\n    {\n      if((boost::math::isfinite)(x))\n      { // Any finite value is OK\n        return true;\n      }\n      else\n      { // Not finite: infinity or NaN.\n        *result = policies::raise_domain_error<RealType>(\n          function,\n          \"x parameter is %1%, but must be finite!\", x, pol);\n        return false;\n      }\n    } // bool check_triangular_x\n\n    template <class RealType, class Policy>\n    inline bool check_triangular(\n      const char* function,\n      RealType lower,\n      RealType mode,\n      RealType upper,\n      RealType* result, const Policy& pol)\n    {\n      if ((check_triangular_lower(function, lower, result, pol) == false)\n        || (check_triangular_mode(function, mode, result, pol) == false)\n        || (check_triangular_upper(function, upper, result, pol) == false))\n      { // Some parameter not finite.\n        return false;\n      }\n      else if (lower >= upper) // lower == upper NOT useful.\n      { // lower >= upper.\n        *result = policies::raise_domain_error<RealType>(\n          function,\n          \"lower parameter is %1%, but must be less than upper!\", lower, pol);\n        return false;\n      }\n      else\n      { // Check lower <= mode <= upper.\n        if (mode < lower)\n        {\n          *result = policies::raise_domain_error<RealType>(\n            function,\n            \"mode parameter is %1%, but must be >= than lower!\", lower, pol);\n          return false;\n        }\n        if (mode > upper)\n        {\n          *result = policies::raise_domain_error<RealType>(\n            function,\n            \"mode parameter is %1%, but must be <= than upper!\", upper, pol);\n          return false;\n        }\n        return true; // All OK.\n      }\n    } // bool check_triangular\n  } // namespace detail\n\n  template <class RealType = double, class Policy = policies::policy<> >\n  class triangular_distribution\n  {\n  public:\n    typedef RealType value_type;\n    typedef Policy policy_type;\n\n    triangular_distribution(RealType lower = -1, RealType mode = 0, RealType upper = 1)\n      : m_lower(lower), m_mode(mode), m_upper(upper) // Constructor.\n    { // Evans says 'standard triangular' is lower 0, mode 1/2, upper 1,\n      // has median sqrt(c/2) for c <=1/2 and 1 - sqrt(1-c)/2 for c >= 1/2\n      // But this -1, 0, 1 is more useful in most applications to approximate normal distribution,\n      // where the central value is the most likely and deviations either side equally likely.\n      RealType result;\n      detail::check_triangular(\"boost::math::triangular_distribution<%1%>::triangular_distribution\",lower, mode, upper, &result, Policy());\n    }\n    // Accessor functions.\n    RealType lower()const\n    {\n      return m_lower;\n    }\n    RealType mode()const\n    {\n      return m_mode;\n    }\n    RealType upper()const\n    {\n      return m_upper;\n    }\n  private:\n    // Data members:\n    RealType m_lower;  // distribution lower aka a\n    RealType m_mode;  // distribution mode aka c\n    RealType m_upper;  // distribution upper aka b\n  }; // class triangular_distribution\n\n  typedef triangular_distribution<double> triangular;\n\n  template <class RealType, class Policy>\n  inline const std::pair<RealType, RealType> range(const triangular_distribution<RealType, Policy>& /* dist */)\n  { // Range of permissible values for random variable x.\n    using boost::math::tools::max_value;\n    return std::pair<RealType, RealType>(-max_value<RealType>(), max_value<RealType>());\n  }\n\n  template <class RealType, class Policy>\n  inline const std::pair<RealType, RealType> support(const triangular_distribution<RealType, Policy>& dist)\n  { // Range of supported values for random variable x.\n    // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\n    return std::pair<RealType, RealType>(dist.lower(), dist.upper());\n  }\n\n  template <class RealType, class Policy>\n  RealType pdf(const triangular_distribution<RealType, Policy>& dist, const RealType& x)\n  {\n    static const char* function = \"boost::math::pdf(const triangular_distribution<%1%>&, %1%)\";\n    RealType lower = dist.lower();\n    RealType mode = dist.mode();\n    RealType upper = dist.upper();\n    RealType result = 0; // of checks.\n    if(false == detail::check_triangular(function, lower, mode, upper, &result, Policy()))\n    {\n      return result;\n    }\n    if(false == detail::check_triangular_x(function, x, &result, Policy()))\n    {\n      return result;\n    }\n    if((x < lower) || (x > upper))\n    {\n      return 0;\n    }\n    if (x == lower)\n    { // (mode - lower) == 0 which would lead to divide by zero!\n      return (mode == lower) ? 2 / (upper - lower) : RealType(0);\n    }\n    else if (x == upper)\n    {\n      return (mode == upper) ? 2 / (upper - lower) : RealType(0);\n    }\n    else if (x <= mode)\n    {\n      return 2 * (x - lower) / ((upper - lower) * (mode - lower));\n    }\n    else\n    {  // (x > mode)\n      return 2 * (upper - x) / ((upper - lower) * (upper - mode));\n    }\n  } // RealType pdf(const triangular_distribution<RealType, Policy>& dist, const RealType& x)\n\n  template <class RealType, class Policy>\n  inline RealType cdf(const triangular_distribution<RealType, Policy>& dist, const RealType& x)\n  {\n    static const char* function = \"boost::math::cdf(const triangular_distribution<%1%>&, %1%)\";\n    RealType lower = dist.lower();\n    RealType mode = dist.mode();\n    RealType upper = dist.upper();\n    RealType result = 0; // of checks.\n    if(false == detail::check_triangular(function, lower, mode, upper, &result, Policy()))\n    {\n      return result;\n    }\n    if(false == detail::check_triangular_x(function, x, &result, Policy()))\n    {\n      return result;\n    }\n    if((x <= lower))\n    {\n      return 0;\n    }\n    if (x >= upper)\n    {\n      return 1;\n    }\n    // else lower < x < upper\n    if (x <= mode)\n    {\n      return ((x - lower) * (x - lower)) / ((upper - lower) * (mode - lower));\n    }\n    else\n    {\n      return 1 - (upper - x) *  (upper - x) / ((upper - lower) * (upper - mode));\n    }\n  } // RealType cdf(const triangular_distribution<RealType, Policy>& dist, const RealType& x)\n\n  template <class RealType, class Policy>\n  RealType quantile(const triangular_distribution<RealType, Policy>& dist, const RealType& p)\n  {\n    BOOST_MATH_STD_USING  // for ADL of std functions (sqrt).\n    static const char* function = \"boost::math::quantile(const triangular_distribution<%1%>&, %1%)\";\n    RealType lower = dist.lower();\n    RealType mode = dist.mode();\n    RealType upper = dist.upper();\n    RealType result = 0; // of checks\n    if(false == detail::check_triangular(function,lower, mode, upper, &result, Policy()))\n    {\n      return result;\n    }\n    if(false == detail::check_probability(function, p, &result, Policy()))\n    {\n      return result;\n    }\n    if(p == 0)\n    {\n      return lower;\n    }\n    if(p == 1)\n    {\n      return upper;\n    }\n    RealType p0 = (mode - lower) / (upper - lower);\n    RealType q = 1 - p;\n    if (p < p0)\n    {\n      result = sqrt((upper - lower) * (mode - lower) * p) + lower;\n    }\n    else if (p == p0)\n    {\n      result = mode;\n    }\n    else // p > p0\n    {\n      result = upper - sqrt((upper - lower) * (upper - mode) * q);\n    }\n    return result;\n\n  } // RealType quantile(const triangular_distribution<RealType, Policy>& dist, const RealType& q)\n\n  template <class RealType, class Policy>\n  RealType cdf(const complemented2_type<triangular_distribution<RealType, Policy>, RealType>& c)\n  {\n    static const char* function = \"boost::math::cdf(const triangular_distribution<%1%>&, %1%)\";\n    RealType lower = c.dist.lower();\n    RealType mode = c.dist.mode();\n    RealType upper = c.dist.upper();\n    RealType x = c.param;\n    RealType result = 0; // of checks.\n    if(false == detail::check_triangular(function, lower, mode, upper, &result, Policy()))\n    {\n      return result;\n    }\n    if(false == detail::check_triangular_x(function, x, &result, Policy()))\n    {\n      return result;\n    }\n    if (x <= lower)\n    {\n      return 1;\n    }\n    if (x >= upper)\n    {\n      return 0;\n    }\n    if (x <= mode)\n    {\n      return 1 - ((x - lower) * (x - lower)) / ((upper - lower) * (mode - lower));\n    }\n    else\n    {\n      return (upper - x) *  (upper - x) / ((upper - lower) * (upper - mode));\n    }\n  } // RealType cdf(const complemented2_type<triangular_distribution<RealType, Policy>, RealType>& c)\n\n  template <class RealType, class Policy>\n  RealType quantile(const complemented2_type<triangular_distribution<RealType, Policy>, RealType>& c)\n  {\n    BOOST_MATH_STD_USING  // Aid ADL for sqrt.\n    static const char* function = \"boost::math::quantile(const triangular_distribution<%1%>&, %1%)\";\n    RealType l = c.dist.lower();\n    RealType m = c.dist.mode();\n    RealType u = c.dist.upper();\n    RealType q = c.param; // probability 0 to 1.\n    RealType result = 0; // of checks.\n    if(false == detail::check_triangular(function, l, m, u, &result, Policy()))\n    {\n      return result;\n    }\n    if(false == detail::check_probability(function, q, &result, Policy()))\n    {\n      return result;\n    }\n    if(q == 0)\n    {\n      return u;\n    }\n    if(q == 1)\n    {\n      return l;\n    }\n    RealType lower = c.dist.lower();\n    RealType mode = c.dist.mode();\n    RealType upper = c.dist.upper();\n\n    RealType p = 1 - q;\n    RealType p0 = (mode - lower) / (upper - lower);\n    if(p < p0)\n    {\n      RealType s = (upper - lower) * (mode - lower);\n      s *= p;\n      result = sqrt((upper - lower) * (mode - lower) * p) + lower;\n    }\n    else if (p == p0)\n    {\n      result = mode;\n    }\n    else // p > p0\n    {\n      result = upper - sqrt((upper - lower) * (upper - mode) * q);\n    }\n    return result;\n  } // RealType quantile(const complemented2_type<triangular_distribution<RealType, Policy>, RealType>& c)\n\n  template <class RealType, class Policy>\n  inline RealType mean(const triangular_distribution<RealType, Policy>& dist)\n  {\n    static const char* function = \"boost::math::mean(const triangular_distribution<%1%>&)\";\n    RealType lower = dist.lower();\n    RealType mode = dist.mode();\n    RealType upper = dist.upper();\n    RealType result = 0;  // of checks.\n    if(false == detail::check_triangular(function, lower, mode, upper, &result, Policy()))\n    {\n      return result;\n    }\n    return (lower + upper + mode) / 3;\n  } // RealType mean(const triangular_distribution<RealType, Policy>& dist)\n\n\n  template <class RealType, class Policy>\n  inline RealType variance(const triangular_distribution<RealType, Policy>& dist)\n  {\n    static const char* function = \"boost::math::mean(const triangular_distribution<%1%>&)\";\n    RealType lower = dist.lower();\n    RealType mode = dist.mode();\n    RealType upper = dist.upper();\n    RealType result = 0; // of checks.\n    if(false == detail::check_triangular(function, lower, mode, upper, &result, Policy()))\n    {\n      return result;\n    }\n    return (lower * lower + upper * upper + mode * mode - lower * upper - lower * mode - upper * mode) / 18;\n  } // RealType variance(const triangular_distribution<RealType, Policy>& dist)\n\n  template <class RealType, class Policy>\n  inline RealType mode(const triangular_distribution<RealType, Policy>& dist)\n  {\n    static const char* function = \"boost::math::mode(const triangular_distribution<%1%>&)\";\n    RealType mode = dist.mode();\n    RealType result = 0; // of checks.\n    if(false == detail::check_triangular_mode(function, mode, &result, Policy()))\n    { // This should never happen!\n      return result;\n    }\n    return mode;\n  } // RealType mode\n\n  template <class RealType, class Policy>\n  inline RealType median(const triangular_distribution<RealType, Policy>& dist)\n  {\n    BOOST_MATH_STD_USING // ADL of std functions.\n    static const char* function = \"boost::math::median(const triangular_distribution<%1%>&)\";\n    RealType mode = dist.mode();\n    RealType result = 0; // of checks.\n    if(false == detail::check_triangular_mode(function, mode, &result, Policy()))\n    { // This should never happen!\n      return result;\n    }\n    RealType lower = dist.lower();\n    RealType upper = dist.upper();\n    if (mode < (upper - lower) / 2)\n    {\n      return lower + sqrt((upper - lower) * (mode - lower)) / constants::root_two<RealType>();\n    }\n    else\n    {\n      return upper - sqrt((upper - lower) * (upper - mode)) / constants::root_two<RealType>();\n    }\n  } // RealType mode\n\n  template <class RealType, class Policy>\n  inline RealType skewness(const triangular_distribution<RealType, Policy>& dist)\n  {\n    BOOST_MATH_STD_USING  // for ADL of std functions\n    using namespace boost::math::constants; // for root_two\n    static const char* function = \"boost::math::skewness(const triangular_distribution<%1%>&)\";\n\n    RealType lower = dist.lower();\n    RealType mode = dist.mode();\n    RealType upper = dist.upper();\n    RealType result = 0; // of checks.\n    if(false == boost::math::detail::check_triangular(function,lower, mode, upper, &result, Policy()))\n    {\n      return result;\n    }\n    return root_two<RealType>() * (lower + upper - 2 * mode) * (2 * lower - upper - mode) * (lower - 2 * upper + mode) /\n      (5 * pow((lower * lower + upper + upper + mode * mode - lower * upper - lower * mode - upper * mode), RealType(3)/RealType(2)));\n  } // RealType skewness(const triangular_distribution<RealType, Policy>& dist)\n\n  template <class RealType, class Policy>\n  inline RealType kurtosis(const triangular_distribution<RealType, Policy>& dist)\n  { // These checks may be belt and braces as should have been checked on construction?\n    static const char* function = \"boost::math::kurtosis(const triangular_distribution<%1%>&)\";\n    RealType lower = dist.lower();\n    RealType upper = dist.upper();\n    RealType mode = dist.mode();\n    RealType result = 0;  // of checks.\n    if(false == detail::check_triangular(function,lower, mode, upper, &result, Policy()))\n    {\n      return result;\n    }\n    return static_cast<RealType>(12)/5; //  12/5 = 2.4;\n  } // RealType kurtosis_excess(const triangular_distribution<RealType, Policy>& dist)\n\n  template <class RealType, class Policy>\n  inline RealType kurtosis_excess(const triangular_distribution<RealType, Policy>& dist)\n  { // These checks may be belt and braces as should have been checked on construction?\n    static const char* function = \"boost::math::kurtosis_excess(const triangular_distribution<%1%>&)\";\n    RealType lower = dist.lower();\n    RealType upper = dist.upper();\n    RealType mode = dist.mode();\n    RealType result = 0;  // of checks.\n    if(false == detail::check_triangular(function,lower, mode, upper, &result, Policy()))\n    {\n      return result;\n    }\n    return static_cast<RealType>(-3)/5; // - 3/5 = -0.6\n    // Assuming mathworld really means kurtosis excess?  Wikipedia now corrected to match this.\n  }\n\n} // namespace math\n} // namespace boost\n\n// This include must be at the end, *after* the accessors\n// for this distribution have been defined, in order to\n// keep compilers that support two-phase lookup happy.\n#include <boost/math/distributions/detail/derived_accessors.hpp>\n\n#endif // BOOST_STATS_TRIANGULAR_HPP\n\n\n\n", "meta": {"hexsha": "735d20235cfe6ad27ffe7fde7294c9482250a4eb", "size": 17721, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/math/distributions/triangular.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2015-01-17T00:29:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-09T02:59:16.000Z", "max_issues_repo_path": "boost/boost/math/distributions/triangular.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2015-07-22T07:35:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T16:03:06.000Z", "max_forks_repo_path": "boost/boost/math/distributions/triangular.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 44.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T09:20:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-21T08:09:17.000Z", "avg_line_length": 33.8187022901, "max_line_length": 139, "alphanum_fraction": 0.6266576378, "num_tokens": 4524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.41587818692418427}}
{"text": "#include <functional>\n\n#include <Qt3DIncludes.h>\n#include <GaussIncludes.h>\n#include <FEMIncludes.h>\n\n//Any extra things I need such as constraints\n#include <ConstraintFixedPoint.h>\n#include <TimeStepperEigenFitSMW.h>\n#include <EigenFit.h>\n#include <fstream>\n\nusing namespace Gauss;\nusing namespace FEM;\nusing namespace ParticleSystem; //For Force Spring\n\n/* Tetrahedral finite elements */\n\n//typedef physical entities I need\n\n//typedef scene\ntypedef PhysicalSystemFEM<double, NeohookeanHFixedTet> FEMLinearTets;\n\ntypedef World<double, std::tuple<FEMLinearTets *>,\nstd::tuple<ForceSpringFEMParticle<double> *, ForceParticlesGravity<double> *>,\nstd::tuple<ConstraintFixedPoint<double> *> > MyWorld;\n\n//typedef World<double, std::tuple<FEMLinearTets *,PhysicalSystemParticleSingle<double> *>,\n//                      std::tuple<ForceSpringFEMParticle<double> *>,\n//                      std::tuple<ConstraintFixedPoint<double> *> > MyWorld;\n//typedef TimeStepperEigenFitSMW<double, AssemblerEigenSparseMatrix<double>, AssemblerEigenVector<double>> MyTimeStepper;\ntypedef TimeStepperEigenFitSMW<double, AssemblerParallel<double, AssemblerEigenSparseMatrix<double>>, AssemblerParallel<double, AssemblerEigenVector<double>> > MyTimeStepper;\n\ntypedef Scene<MyWorld, MyTimeStepper> MyScene;\n\n\n//typedef TimeStepperEigenFitSI<double, AssemblerParallel<double, AssemblerEigenSparseMatrix<double> >,\n//AssemblerParallel<double, AssemblerEigenVector<double> > > MyTimeStepper;\n\n//typedef Scene<MyWorld, MyTimeStepper> MyScene;\n\n// used for preStepCallback. should be delete\nstd::vector<ConstraintFixedPoint<double> *> movingConstraints;\nEigen::VectorXi movingVerts;\nEigen::MatrixXd V;\nEigen::MatrixXi F;\nchar **arg_list;\nunsigned int istep;\n\nvoid preStepCallback(MyWorld &world) {\n//    // This is an example callback\n//    if (atoi(arg_list[5]) == 2)\n//    {\n//        // This is an example callback\n//        \n//        //script some motion\n////\n//        if (istep < 50) {\n//            \n//            for(unsigned int jj=0; jj<movingConstraints.size(); ++jj) {\n//                if(movingConstraints[jj]->getImpl().getFixedPoint()[0] > -3) {\n//                    Eigen::Vector3d v = V.row(movingVerts[jj]);\n//                    Eigen::Vector3d new_p = v + Eigen::Vector3d(0.0,1.0/10,0.0);\n//                    movingConstraints[jj]->getImpl().setFixedPoint(new_p);\n//                }\n//            }\n//        }\n//    }\n}\n\nint main(int argc, char **argv) {\n    //    arg list\n    //    1: full path to coarse mesh\n    //    2: full path to fine mesh\n    //    3: youngs modulus (SI unit)\n    //    4: constraint threshold (for defualt constraint profile)\n    //    5: constraint profile switch\n    //    6: name of the initial deformation profile\n    //    7. number of time steps\n//    8. flag for using hausdorff distance\n//    9. number of modes to modifies\n    std::cout<<\"Test Neohookean FEM EigenFit\\n\";\n    \n    //Setup Physics\n    MyWorld world;\n    \n    arg_list = argv;\n    \n    Eigen::MatrixXd Vf;\n    Eigen::MatrixXi Ff;\n    \n    \n    \n    //    define the file separator base on system\n    const char kPathSeparator =\n#ifdef _WIN32\n    '\\\\';\n#else\n    '/';\n#endif\n    \n    if (argc > 1) {\n        // must supply all 9 parameters\n        \n        std::string cmeshname = argv[1];\n        std::string fmeshname = argv[2];\n        \n        readTetgen(V, F, dataDir()+cmeshname+\".node\", dataDir()+cmeshname+\".ele\");\n        readTetgen(Vf, Ff, dataDir()+fmeshname+\".node\", dataDir()+fmeshname+\".ele\");\n        \n        std::string::size_type found = cmeshname.find_last_of(kPathSeparator);\n        //    acutal name for the mesh, no path\n        std::string cmeshnameActual = cmeshname.substr(found+1);\n\n        //    acutal name for the mesh, no path\n        std::string fmeshnameActual = fmeshname.substr(found+1);\n\n        \n        //    parameters\n        double youngs = atof(argv[3]);\n        double poisson = 0.45;\n        int constraint_dir = 0; // constraint direction. 0 for x, 1 for y, 2 for z\n        double constraint_tol = atof(argv[4]);\n        //\n        // send the constraint switch in as well, or the fine embedded mesh. ugly\n        // the flag indicate whether to recalculated or not\n        // need to pass the material and constraint parameters to embedding too. need to do it again below. ugly\n        // also use the last two args to determine how many modes to fix. have to put it here now. ugly\n        EigenFit *test = new EigenFit(V,F,Vf,Ff,true,youngs,poisson,constraint_dir,constraint_tol, atoi(argv[5]),atoi(argv[8]),atoi(argv[9]));\n        \n        \n        world.addSystem(test);\n        \n\n        // projection matrix for constraints\n        Eigen::SparseMatrix<double> P;\n        if (atoi(argv[5]) == 0) {\n            // constraint switch\n            \n            //            zero gravity\n            Eigen::Vector3x<double> g;\n            g(0) = 0;\n            g(1) = 0;\n            g(2) = 0;\n            \n            for(unsigned int iel=0; iel<test->getImpl().getF().rows(); ++iel) {\n                \n                test->getImpl().getElement(iel)->setGravity(g);\n                \n            }\n            \n            world.finalize(); //After this all we're ready to go (clean up the interface a bit later)\n            \n            //            set the projection matrix to identity because there is no constraint to project\n//            Eigen::SparseMatrix<double> P;\n            P.resize(V.rows()*3,V.rows()*3);\n            P.setIdentity();\n//            std::cout<<P.rows();\n            //            no constraints\n        }\n        else if(atoi(argv[5]) == 1)\n        {\n            //    default constraint\n            fixDisplacementMin(world, test,constraint_dir,constraint_tol);\n            world.finalize(); //After this all we're ready to go (clean up the interface a bit later)\n            \n            // construct the projection matrix for stepper\n            Eigen::VectorXi indices = minVertices(test, constraint_dir,constraint_tol);\n            P = fixedPointProjectionMatrix(indices, *test,world);\n            \n        }\n        else if (atoi(argv[5]) == 2)\n        {\n            \n\n            movingVerts = minVertices(test, constraint_dir, constraint_tol);//indices for moving parts\n//\n            for(unsigned int ii=0; ii<movingVerts.rows(); ++ii) {\n                movingConstraints.push_back(new ConstraintFixedPoint<double>(&test->getQ()[movingVerts[ii]], Eigen::Vector3d(0,0,0)));\n                world.addConstraint(movingConstraints[ii]);\n            }\n            fixDisplacementMin(world, test,constraint_dir,constraint_tol);\n            \n            world.finalize(); //After this all we're ready to go (clean up the interface a bit later)\n            \n            P = fixedPointProjectionMatrix(movingVerts, *test,world);\n            \n        }\n        \n        // set material\n        for(unsigned int iel=0; iel<test->getImpl().getF().rows(); ++iel) {\n            \n            test->getImpl().getElement(iel)->setParameters(youngs, poisson);\n            \n        }\n        \n        auto q = mapStateEigen(world);\n        auto fine_q = mapStateEigen(test->getFineWorld());\n        //    default to zero deformation\n        q.setZero();\n\n        if (strcmp(argv[6],\"0\")==0) {\n            \n            q.setZero();\n        }\n        else\n        {\n            \n            std::string qfileName(argv[6]);\n            Eigen::VectorXd  tempv;\n            loadMarketVector(tempv,qfileName);\n\n            q = tempv;\n            \n        }\n        \n        MyTimeStepper stepper(0.01,P);\n        \n        //         the number of steps to take\n        \n        unsigned int file_ind = 0;\n        std::string name = \"pos\";\n        std::string fformat = \".obj\";\n        std::string filename = name + std::to_string(file_ind) + fformat;\n        std::string qname = cmeshnameActual + \"ExampleQ\";\n        std::string qfformat = \".mtx\";\n        std::string qfilename = qname + std::to_string(file_ind) + qfformat;\n        std::string qname2 = fmeshnameActual + \"ExampleQ\";\n        std::string qfilename2 = qname2 + std::to_string(file_ind) + qfformat;\n        \n        struct stat buf;\n        unsigned int idx;\n        \n        for(istep=0; istep<atoi(argv[7]) ; ++istep) {\n            stepper.step(world);\n            \n            // acts like the \"callback\" block\n            if (atoi(arg_list[5]) == 2)\n            {\n                //script some motion\n                //\n                \n                \n                for(unsigned int jj=0; jj<movingConstraints.size(); ++jj) {\n                    \n                    auto v_q = mapDOFEigen(movingConstraints[jj]->getDOF(0), world.getState());\n//\n//                    if ((istep%150) < 50) {\n//                        Eigen::Vector3d new_q = (istep%150)*Eigen::Vector3d(0.0,-1.0/100,0.0);\n//                        v_q = new_q;\n//                    }\n//                    else if ((istep%150) < 100)\n//                    {}\n//                    else\n//                    {\n//                        Eigen::Vector3d new_q =  (150-(istep%150))*Eigen::Vector3d(0.0,-1.0/100,0.0);\n//                        v_q = new_q;\n//                    }\n                    Eigen::Vector3d new_q = (istep)*Eigen::Vector3d(0.0,-1.0/100,0.0);\n                    v_q = new_q;\n\n                }\n            }\n            \n            //output data here\n            std::ofstream ofile;\n            ofile.open(\"KE.txt\", std::ios::app); //app is append which means it will put the text at the end\n            ofile << std::get<0>(world.getSystemList().getStorage())[0]->getImpl().getKineticEnergy(world.getState()) << std::endl;\n            ofile.close();\n            \n            while (stat(filename.c_str(), &buf) != -1)\n            {\n                file_ind++;\n                filename = name + std::to_string(file_ind) + fformat;\n                qfilename = qname + std::to_string(file_ind) + qfformat;\n                qfilename2 = qname2 + std::to_string(file_ind) + qfformat;\n                \n            }\n            \n            idx = 0;\n            // getGeometry().first is V\n            Eigen::MatrixXd V_disp = std::get<0>(world.getSystemList().getStorage())[0]->getGeometry().first;\n            \n            for(unsigned int vertexId=0;  vertexId < std::get<0>(world.getSystemList().getStorage())[0]->getGeometry().first.rows(); ++vertexId) {\n                \n                // because getFinePosition is in EigenFit, not another physical system Impl, so don't need getImpl()\n                V_disp(vertexId,0) += q(idx);\n                idx++;\n                V_disp(vertexId,1) += q(idx);\n                idx++;\n                V_disp(vertexId,2) += q(idx);\n                idx++;\n            }\n            igl::writeOBJ(filename,V_disp,std::get<0>(world.getSystemList().getStorage())[0]->getGeometry().second);\n            // coarse mesh data\n            q = mapStateEigen(world);\n            saveMarketVector(q, qfilename);\n            // fine mesh data from embedded mesh in eigenfit\n            fine_q = mapStateEigen(test->getFineWorld());\n            saveMarketVector(fine_q, qfilename2);\n        }\n    }\n    else\n    {\n        // using all default paramters for eigenfit\n     \n        //    default example meshes\n        std::string cmeshname = \"/meshesTetgen/arma/arma_6\";\n        std::string fmeshname = \"/meshesTetgen/arma/arma_1\";\n        \n        readTetgen(V, F, dataDir()+cmeshname+\".node\", dataDir()+cmeshname+\".ele\");\n        readTetgen(Vf, Ff, dataDir()+fmeshname+\".node\", dataDir()+fmeshname+\".ele\");\n        \n        std::string::size_type found = cmeshname.find_last_of(kPathSeparator);\n        //    acutal name for the mesh, no path\n        std::string cmeshnameActual = cmeshname.substr(found+1);\n        \n        \n        //    default parameters\n        double youngs = 5e5;\n        double poisson = 0.45;\n        int constraint_dir = 0; // constraint direction. 0 for x, 1 for y, 2 for z\n        double constraint_tol = 2e-1;\n        \n        // no constraint switch so just create the eigenfit obj with constraint switch set to 1\n        // the flag indicate whether to recalculated or not\n        // need to pass the material and constraint parameters to embedding too. need to do it again below. ugly\n        // also use the last two args to determine how many modes to fix. default not using hausdorff distance, and use 10 modes. have to put it here now.  ugly\n        EigenFit *test = new EigenFit(V,F,Vf,Ff,true,youngs,poisson,constraint_dir,constraint_tol, 1,false,10);\n        \n        // set material\n        for(unsigned int iel=0; iel<test->getImpl().getF().rows(); ++iel) {\n            \n            test->getImpl().getElement(iel)->setParameters(youngs, poisson);\n            \n        }\n        \n        world.addSystem(test);\n        \n        world.finalize(); //After this all we're ready to go (clean up the interface a bit later)\n        // IMPORTANT, need to finalized before fix boundary\n        \n        //    default constraint\n        fixDisplacementMin(world, test,constraint_dir,constraint_tol);\n        \n        // construct the projection matrix for stepper\n        Eigen::VectorXi indices = minVertices(test, constraint_dir,constraint_tol);\n        Eigen::SparseMatrix<double> P = fixedPointProjectionMatrix(indices, *test,world);\n        \n        \n        auto q = mapStateEigen(world);\n        \n        //    default to zero deformation\n        q.setZero();\n        \n\n        MyTimeStepper stepper(0.01,P);\n        \n        //Display\n        QGuiApplication app(argc, argv);\n        \n        MyScene *scene = new MyScene(&world, &stepper, preStepCallback);\n        GAUSSVIEW(scene);\n        \n        return app.exec();\n        \n    }\n    \n}\n", "meta": {"hexsha": "3b3d7f902b7fe4f799e51d6bb31645e0e5bfb909", "size": 13734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Examples/exampleEigenFit.cpp", "max_stars_repo_name": "ericchen321/GAUSS", "max_stars_repo_head_hexsha": "75d3a89e7f20989525449c46a92fb0eac4712505", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-14T19:19:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T13:32:48.000Z", "max_issues_repo_path": "src/Examples/exampleEigenFit.cpp", "max_issues_repo_name": "ericchen321/GAUSS", "max_issues_repo_head_hexsha": "75d3a89e7f20989525449c46a92fb0eac4712505", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-08-15T18:30:22.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-15T18:40:26.000Z", "max_forks_repo_path": "src/Examples/exampleEigenFit.cpp", "max_forks_repo_name": "edwinchenyj/GAUSS", "max_forks_repo_head_hexsha": "6aa9513d80f8afe10da12382ffbe16b030fad172", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T07:57:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T07:57:26.000Z", "avg_line_length": 37.1189189189, "max_line_length": 174, "alphanum_fraction": 0.5587592835, "num_tokens": 3312, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834734, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4158781798700372}}
{"text": "#include \"HelmertTransformation.h\"\n#include \"Exception.h\"\n#include <boost/math/constants/constants.hpp>\n#include <cstdio>\n#include <sstream>\n#include <stdexcept>\n\n#ifdef _MSC_VER\n#define __PRETTY_FUNCTION__ BOOST_CURRENT_FUNCTION\n#endif\n\nFmi::HelmertTransformation::HelmertTransformation() : m(1), ex(0), ey(0), ez(0), tx(0), ty(0), tz(0)\n{\n}\n\nboost::array<double, 3> Fmi::HelmertTransformation::operator()(\n    const boost::array<double, 3>& x) const\n{\n  try\n  {\n    boost::array<double, 3> y = {m * (x[0] + (-ez) * x[1] + (ey)*x[2]) + tx,\n                                 m * ((ez)*x[0] + x[1] + (-ex) * x[2]) + ty,\n                                 m * ((-ey) * x[0] + (ex)*x[1] + x[2]) + tz};\n    return y;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nvoid Fmi::HelmertTransformation::set_fmi_sphere_to_reference_ellipsoid_conv(\n    double r,\n    double lat,\n    double lon,\n    const ReferenceEllipsoid& ref,\n    enum FmiSphereConvScalingType scaling_type)\n{\n  try\n  {\n    ex = 0;\n    ey = 0;\n    ez = 0;\n    if (scaling_type == FMI_SPHERE_NO_SCALING)\n    {\n      m = 1;\n      const boost::array<double, 3> x0 = ref.to_geocentric(lat, lon, -r);\n      tx = x0[0];\n      ty = x0[1];\n      tz = x0[2];\n    }\n    else if (scaling_type == FMI_SPHERE_PRESERVE_EAST_WEST_SCALE)\n    {\n      const double a = ref.get_semimajor_axis();\n      const double e = ref.get_eccentricity();\n      const double v = sqrt(1 - e * e * sin(lat) * sin(lat));\n      m = a / (r * v);\n      tx = 0;\n      ty = 0;\n      tz = -a * e * e * sin(lat) / v;\n    }\n    else if (scaling_type == FMI_SPHERE_PRESERVE_SOUTH_NORTH_SCALE)\n    {\n      const double a = ref.get_semimajor_axis();\n      const double e = ref.get_eccentricity();\n      const double v = sqrt(1 - e * e * sin(lat) * sin(lat));\n      const double sf = sin(lat);\n      const double cf = cos(lat);\n      m = (a * (1 - e * e)) / (r * v * v * v);\n      tx = a * e * e * cos(lon) * cf * cf * cf / (v * v * v);\n      ty = a * e * e * sin(lon) * cf * cf * cf / (v * v * v);\n      tz = -a * e * e * (1 - e * e) * sf * sf * sf / (v * v * v);\n    }\n    else\n    {\n      std::ostringstream msg;\n      msg << __PRETTY_FUNCTION__ << \": wrong scaling type \" << scaling_type;\n      throw Fmi::Exception(BCP, msg.str());\n    }\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nvoid Fmi::HelmertTransformation::set_reference_ellipsoid_to_fmi_sphere_conv(\n    double r,\n    double lat,\n    double lon,\n    const ReferenceEllipsoid& ref,\n    enum FmiSphereConvScalingType scaling_type)\n{\n  try\n  {\n    ex = 0;\n    ey = 0;\n    ez = 0;\n    if (scaling_type == FMI_SPHERE_NO_SCALING)\n    {\n      m = 1;\n      const boost::array<double, 3> x0 = ref.to_geocentric(lat, lon, -r);\n      tx = -x0[0];\n      ty = -x0[1];\n      tz = -x0[2];\n    }\n    else if (scaling_type == FMI_SPHERE_PRESERVE_EAST_WEST_SCALE)\n    {\n      const double a = ref.get_semimajor_axis();\n      const double e = ref.get_eccentricity();\n      const double v = sqrt(1 - e * e * sin(lat) * sin(lat));\n      m = r * v / a;\n      tx = 0;\n      ty = 0;\n      tz = r * e * e * sin(lat);\n    }\n    else if (scaling_type == FMI_SPHERE_PRESERVE_SOUTH_NORTH_SCALE)\n    {\n      const double a = ref.get_semimajor_axis();\n      const double e = ref.get_eccentricity();\n      const double v = sqrt(1 - e * e * sin(lat) * sin(lat));\n      const double sf = sin(lat);\n      const double cf = cos(lat);\n      m = r * v * v * v / (a * (1 - e * e));\n      tx = -r * e * e * cos(lon) * cf * cf * cf / (1 - e * e);\n      ty = -r * e * e * sin(lon) * cf * cf * cf / (1 - e * e);\n      tz = r * e * e * sf * sf * sf;\n    }\n    else\n    {\n      std::ostringstream msg;\n      msg << __PRETTY_FUNCTION__ << \": wrong scaling type \" << scaling_type;\n      throw Fmi::Exception(BCP, msg.str());\n    }\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\nstd::string Fmi::get_fmi_sphere_towgs84_proj4_string(\n    double r,\n    double lat,\n    double lon,\n    enum Fmi::HelmertTransformation::FmiSphereConvScalingType scaling_type)\n{\n  try\n  {\n    const double AS = 180.0 * 3600.0 / boost::math::constants::pi<double>();\n    Fmi::HelmertTransformation conv;\n    conv.set_fmi_sphere_to_reference_ellipsoid_conv(\n        r, lat, lon, Fmi::ReferenceEllipsoid::wgs84, scaling_type);\n    char buffer[512];\n#ifndef _MSC_VER\n    snprintf(buffer,\n             sizeof(buffer),\n#else\n    _snprintf(buffer,\n              sizeof(buffer),\n#endif\n             \"+towgs84=%.1f,%.1f,%.1f,%.1f,%.1f,%.1f,%.0f \",\n             conv.tx,\n             conv.ty,\n             conv.tz,\n             AS * conv.ex,\n             AS * conv.ey,\n             AS * conv.ez,\n             1e6 * (conv.m - 1));\n    buffer[sizeof(buffer) - 1] = 0;\n    return buffer;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n", "meta": {"hexsha": "6f283faee36fde5a55f6de270355228fbdb65a89", "size": 4890, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "macgyver/HelmertTransformation.cpp", "max_stars_repo_name": "fmidev/smartmet-library-macgyver", "max_stars_repo_head_hexsha": "c91c28535c5df15856caf59e1d29f96917378eca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "macgyver/HelmertTransformation.cpp", "max_issues_repo_name": "fmidev/smartmet-library-macgyver", "max_issues_repo_head_hexsha": "c91c28535c5df15856caf59e1d29f96917378eca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-03-13T18:40:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T11:47:22.000Z", "max_forks_repo_path": "macgyver/HelmertTransformation.cpp", "max_forks_repo_name": "fmidev/smartmet-library-macgyver", "max_forks_repo_head_hexsha": "c91c28535c5df15856caf59e1d29f96917378eca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-03-16T07:47:23.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-16T07:47:23.000Z", "avg_line_length": 27.4719101124, "max_line_length": 100, "alphanum_fraction": 0.5443762781, "num_tokens": 1551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.41587817281589}}
{"text": "#include \"TROOT.h\"\n#include \"TStyle.h\"\n#include \"TFile.h\"\n#include \"TH1.h\"\n#include \"TGraphAsymmErrors.h\" \n#include \"TCanvas.h\"\n#include <cmath>\n#include <fstream>\n#include <iostream>\n\n#include <exception>\n#include <iterator>\n#include <string>\n#include <vector>\n\n#if (defined (STANDALONE) or defined (__CINT__) )\n    #include \"ClopperPearsonBinomialInterval.h\"\n#else\n    #include \"PhysicsTools/RooStatsCms/interface/ClopperPearsonBinomialInterval.h\"\n#endif\n\n#include <boost/program_options.hpp>\nusing namespace boost;\nnamespace po = boost::program_options;\nusing namespace std;\n\n// A helper function to simplify the main part.\ntemplate<class T>\nostream& operator<<(ostream& os, const vector<T>& v) {\n  copy(v.begin(), v.end(), ostream_iterator<T>(cout, \" \")); \n  return os;\n}\n\n\nint main(int ac, char *av[]) {\n  gROOT->SetBatch(kTRUE);\n  gROOT->SetStyle(\"Plain\");\n  \n  try{\n    string file;\n    string num;\n    string den;\n    string ext;\n    string pname;\n    unsigned int rebin=1;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n      (\"help,h\", \"produce help message\")\n      (\"input-file,i\", po::value<string >(&file), \"input file\")\n      (\"num,n\", po::value<string > (&num), \"numHisto\")\n      (\"den,d\", po::value<string > (&den), \"denHisto\")\n      (\"plotname,o\", po::value<string > (&pname), \"plot name\")\n      (\"rebin,r\", po::value<unsigned int > (&rebin)->default_value(1), \"rebin\")\n      (\"plot-format,p\", po::value<string>(&ext)->default_value(\"gif\"), \n       \"output plot format\");\n    \n    po::positional_options_description p;\n    po::variables_map vm;\n    po::store(po::command_line_parser(ac, av).\n\t      options(desc).positional(p).run(), vm); \n    po::notify(vm);\n\n\n\n       \n    if (vm.count(\"help\")) {\n      cout << \"Usage: options_description [options]\\n\";\n      cout << desc;\n      return 0;\n    }\n\n\n\n    \n   \n   \tTFile * root_file = new TFile(file.c_str(),\"read\");\n\t//TFile * root_file = new TFile(\"MuTrigger_133874_133828_768ub.root\",\"read\");\n\t//string d_string = *itd;\n\tstring  dirDen =   den;\n\tstring  dirNum =   num;\n\t\n\t\n\tTH1D * denh = (TH1D*) root_file->Get( dirDen.c_str()  );\n\tTH1D * numh = (TH1D*) root_file->Get( dirNum.c_str() );\n\t\n\t\n         int bins = denh->GetXaxis()->GetNbins();\n        bins = bins/rebin;\n\tconst double xMax = denh->GetXaxis()->GetXmax();\n  \tconst double xMin = denh->GetXaxis()->GetXmin();\n\t//std::cout << \"xMax \" << xMax << endl;\n\t//std::cout << \"xMin \" << xMax << endl;\n\t//std::cout << \"bins \" << bins << endl;\n\tdouble * x = new double[bins];\n\tdouble *eff = new double[bins];\n\tdouble * exl= new double[bins];\n\tdouble *exh = new double[bins];\n\tdouble *  eefflCP= new double[bins];\n\tdouble * eeffhCP = new double[bins];\n\t\n\tClopperPearsonBinomialInterval cp;\n\t//  alpha = 1 - CL\n\tconst double alpha = (1-0.682);\n\tcp.init(alpha);\n\tTH1D histo(\"histo\", \"Efficiency\", bins, xMin, xMax);\n\t\n\tfor(int i = 1; i <= bins; i++) {\n          int j = i-1;    \n\t  x[j] = ((double(i-0.5)) * (xMax - xMin) / (bins )) + xMin; \n\t    int n0 = denh->GetBinContent(i);\n\t  //\t  std::cout << \" n0 \" << n0 << endl;\n\t   int n1 = numh->GetBinContent(i);\n\t  // std::cout << \" n1 \" << n1 << endl;\n\t  if ( n0!=0) {\n\t    eff[j] = double(n1)/double(n0); \n\t    histo.SetBinContent(i,eff[j]); \n\t    exl[j] = exh[j] = 0;\n\t    cp.calculate(n1, n0);\n\t    eefflCP[j] = eff[j] - cp.lower();\n\t    eeffhCP[j] = cp.upper() - eff[j];\n\t  } else { \n\t    eff[j]=0;\n\t    histo.SetBinContent(i,eff[j]); \n\t    exl[j] = exh[j] = 0;\n\t    //cp.calculate(n1, n0);\n\t    eefflCP[i] = 0;\n\t    eeffhCP[i] = 0;\n\t    \n\t  }\n\t  //std::cout<< \"x[j] \" <<x[j]<<std::endl;\n\t  //std::cout<< \"n0 \" <<n0<<std::endl;\n\t  //std::cout<< \"n1 \" <<n1<<std::endl;\n\t  //histo.SetBinContent(i+1,eff[i]); \n\t      //exl[i] = exh[i] = 0;\n\t      //cp.calculate(n1, n0);\n\t      //eefflCP[i] = eff[i] - cp.lower();\n\t      //eeffhCP[i] = cp.upper() - eff[i];\n\t}\n\tTGraphAsymmErrors graphCP(bins, x, eff, exl, exh, eefflCP, eeffhCP);\n\tgraphCP.SetTitle(\"trigger (HLT_Mu9 path) efficiency\");\n\tgraphCP.SetMarkerColor(kRed);\n\tgraphCP.SetMarkerStyle(21);\n\tgraphCP.SetLineWidth(1);\n\tgraphCP.SetLineColor(kRed);\n        string cname = pname;\n\tTCanvas * c = new TCanvas(cname.c_str());\n\tgStyle->SetOptStat(0);\n\thisto.SetTitle(\"MC trigger (HLT_Mu9 path) efficiency\"); \n\thisto.Draw();\n\thisto.SetLineColor(kWhite);\n        histo.SetMinimum(0.0)\n;\thisto.GetXaxis()->SetTitle(\"p_{T} (GeV/c)\");\n\thisto.GetYaxis()->SetTitle(\"efficiency\");\n        graphCP.Draw(\"P\");\n    \tstring plot= \"HLTMu_9\" +  pname + \".\" +  ext ; \n\tc->SaveAs(plot.c_str());\n        string outfile= \"Effhisto\" +   pname + \".root\";\n\tTFile * output_file = TFile::Open(outfile.c_str(), \"recreate\");\n        string outdir =  pname;\n\tTDirectory * dir = output_file->mkdir(outdir.c_str());\n\tdir->cd();\n        c->Write();  \n        histo.Write();\n        graphCP.Write();  \n\toutput_file->Close();\n        delete c;\n      }    \n   \n  \n  catch(std::exception& e) {\n    cerr << \"error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n  catch(...) {\n    cerr << \"Exception of unknown type!\\n\";\n  }\n\n  return 0;\n}\n\n", "meta": {"hexsha": "c4707469c70d26f5497992cb68d9bbd3e484ec44", "size": 5043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/hltEffwithCPError.cpp", "max_stars_repo_name": "nistefan/cmssw", "max_stars_repo_head_hexsha": "ea13af97f7f2117a4f590a5e654e06ecd9825a5b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-24T19:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-19T11:45:32.000Z", "max_issues_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/hltEffwithCPError.cpp", "max_issues_repo_name": "nistefan/cmssw", "max_issues_repo_head_hexsha": "ea13af97f7f2117a4f590a5e654e06ecd9825a5b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-08-23T13:40:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-05T21:16:03.000Z", "max_forks_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/hltEffwithCPError.cpp", "max_forks_repo_name": "nistefan/cmssw", "max_forks_repo_head_hexsha": "ea13af97f7f2117a4f590a5e654e06ecd9825a5b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-08-21T16:37:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-09T13:33:17.000Z", "avg_line_length": 27.861878453, "max_line_length": 82, "alphanum_fraction": 0.589331747, "num_tokens": 1567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506635289836, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.4158767380837069}}
{"text": "/*-------------------------------------------------------------------\n\n                  Copyright (c) 2006\n         Nicola Beume <nicola.beume@tu-dortmund.de>\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n---------------------------------------------------------------------\n\nThis program calculates the dominated hypervolume or S-metric of a\nset of d-dimensional points (d>=3). Please refer to the following\npublication for a description of the algorithm:\n\nNicola Beume and Guenter Rudolph.\nFaster S-Metric Calculation by Considering Dominated Hypervolume\nas Klee's Measure Problem.\nIn: B. Kovalerchuk (ed.): Proceedings of the Second IASTED\nConference on Computational Intelligence (CI 2006), pp. 231-236.\nACTA Press: Anaheim, 2006.\n\nExtended version published as:\nTechnical Report of the Collaborative Research Centre 531\n'Computational Intelligence', CI-216/06, ISSN 1433-3325.\nUniversity of Dortmund, July 2006.\n\n-------------------------------------------------------------------*/\n\n#include <pybind11/pybind11.h>\n#include <pybind11/eigen.h>\n#include <cstdlib>\n#include <cstdio>\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <cmath>\n#include <bitset> // for calculation of trellis\n#include <vector>\n#include <Eigen/Dense>\nusing namespace std;\n\n\n\n/* function invoked by main */\nvoid stream(double regLow[], double regUp[], const vector<double*>& cubs, int lev, double cov);\nbool cmp(double* a, double* b);\n/* function invoked by stream */\n/*\ninline bool cmp(double* a, double* b);\ninline bool covers(const double* cub, const double regLow[]);\ninline bool partCovers(const double* cub, const double regUp[]);\ninline int containsBoundary(const double* cub, const double regLow[], const int split);\ninline double getMeasure(const double regLow[], const double regUp[]);\ninline int isPile(const double* cub, const double regLow[], const double regUp[]);\ninline double computeTrellis(const double regLow[], const double regUp[], const double trellis[]);\ninline double getMedian(vector<double>& bounds);\n*/\n\n\n/* global variables */\nstatic int dataNumber;\nstatic int dimension;\nstatic double dSqrtDataNumber;\nstatic double volume;\n\n\n\nstatic double calculate(int dim, int dataNum, const Eigen::MatrixXd &xd, const Eigen::MatrixXd &xr) {\n    /*\n     * arguments are:\n     * dimension of input data points\n     * number of input data points\n     * file name of input data\n     * file name of reference point\n     */\n\n    int i,j;\n    dimension = dim;\n    dataNumber = dataNum;\n    if (dimension < 3) {\n        fprintf(stderr, \"invalid argument\\n\");\n        exit(1);\n    }\n\n    static vector<double*> pointsInitial(dataNumber);\n\n    for (int i = 0; i < dataNumber; i++) {\n        pointsInitial[i] = new double[dimension];\n        for (int j = 0; j < dimension; j++) {\n            pointsInitial[i][j] = xd(i, j);\n        }\n    }\n\n    // read in reference point\n    static double* refPoint = new double[dimension];\n    for (int i = 0; i < dimension; i++) {\n        refPoint[i] = xr(i);\n    }\n\n\n    // initialize volume\n    volume = 0.0;\n    // sqrt of dataNumber\n    dSqrtDataNumber = sqrt((double)dataNumber);\n\n    // initialize region\n    double* regionLow = new double[dimension-1];\n    double* regionUp = new double[dimension-1];\n    for (j=0; j<dimension-1; j++)  {\n        // determine minimal j coordinate\n        double min = 10000000.0;\n        for (i=0; i<dataNumber; i++) {\n            if (pointsInitial[i][j] < min) {\n                min = pointsInitial[i][j];\n            }\n        }\n        regionLow[j] = min;\n        regionUp[j] = refPoint[j];\n    }\n\n    // sort pointList according to d-th dimension\n    sort(pointsInitial.begin(), pointsInitial.end(), cmp);\n\n    // call stream initially\n    stream(regionLow, regionUp, pointsInitial, 0, refPoint[dimension-1]);\n    // return hypervolume\n    return volume;\n}\n\n\ninline bool cmp(double* a, double* b) {\n    return (a[dimension-1] < b[dimension-1]);\n}\n\n\ninline bool covers(const double* cub, const double regLow[]) {\n    static int i;\n    for (i=0; i<dimension-1; i++) {\n        if (cub[i] > regLow[i]) {\n            return false;\n        }\n    }\n    return true;\n}\n\n\ninline bool partCovers(const double* cub, const double regUp[]) {\n    static int i;\n    for (i=0; i<dimension-1; i++) {\n        if (cub[i] >= regUp[i]) {\n            return false;\n        }\n    }\n    return true;\n}\n\n\ninline int containsBoundary(const double* cub, const double regLow[], const int split) {\n    // condition only checked for split>0\n    if (regLow[split] >= cub[split]){\n        // boundary in dimension split not contained in region, thus\n        // boundary is no candidate for the splitting line\n        return -1;\n    }\n    else {\n        static int j;\n        for (j=0; j<split; j++) { // check boundaries\n            if (regLow[j] < cub[j]) {\n                // boundary contained in region\n                return 1;\n            }\n        }\n    }\n    // no boundary contained in region\n    return 0;\n}\n\n\ninline double getMeasure(const double regLow[], const double regUp[]) {\n    static double vol;\n    static int i;\n    vol = 1.0;\n    for (i=0; i<dimension-1; i++) {\n        vol *= (regUp[i] - regLow[i]);\n    }\n    return vol;\n}\n\n\ninline int isPile(const double* cub, const double regLow[], const double regUp[]) {\n    static int pile;\n    static int k;\n\n    pile = dimension;\n    // check all dimensions of the node\n    for (k=0; k<dimension-1; k++) {\n        // k-boundary of the node's region contained in the cuboid?\n        if (cub[k] > regLow[k]) {\n            if (pile != dimension) {\n                // second dimension occured that is not completely covered\n                // ==> cuboid is no pile\n                return -1;\n            }\n            pile = k;\n        }\n    }\n    // if pile == this.dimension then\n    // cuboid completely covers region\n    // case is not possible since covering cuboids have been removed before\n\n    // region in only one dimenison not completly covered\n    // ==> cuboid is a pile\n    return pile;\n}\n\n\n\ninline double computeTrellis(const double regLow[], const double regUp[], const double trellis[]) {\n\n    static int i,j;\n    static double vol;\n    static int numberSummands;\n    static double summand;\n    static bitset<16> bitvector;\n\n    vol= 0.0;\n    summand = 0.0;\n    numberSummands = 0;\n\n    // calculate number of summands\n    static bitset<16> nSummands;\n    for (i=0; i<dimension-1; i++) {\n        nSummands[i] = 1;\n    }\n    numberSummands = nSummands.to_ulong();\n\n    static double* valueTrellis = new double[dimension-1];\n    static double* valueRegion = new double[dimension-1];\n    for (i=0; i<dimension-1; i++) {\n        valueTrellis[i] = trellis[i] - regUp[i];\n    }\n    for (i=0; i<dimension-1; i++) {\n        valueRegion[i] = regUp[i] - regLow[i];\n    }\n\n\n    static double* dTemp = new double[numberSummands/2 + 1];\n\n    // sum\n    for (i=1; i<=numberSummands/2; i++) {\n\n        // set bitvector length to fixed value 16\n        // TODO Warning: dimension-1 <= 16 is assumed\n        bitvector = (long)i;\n\n        // construct summand\n        // 0: take factor from region\n        // 1: take factor from cuboid\n        summand = 1.0;\n        for (j=0; j<dimension-2; j++) {\n            if (bitvector[j]) {\n                summand *= valueTrellis[j];\n            }\n            else {\n                summand *= valueRegion[j];\n            }\n        }\n        summand *= valueRegion[dimension-2];\n\n        // determine sign of summand\n        vol -= summand;\n        dTemp[i] =- summand;\n\n        // add summand to sum\n        // sign = (int) pow((double)-1, (double)counterOnes+1);\n        // vol += (sign * summand);\n    }\n\n\n    bitvector = (long)i;\n    summand = 1.0;\n    for (j=0; j<dimension-1; j++) {\n        if (bitvector[j]) {\n            summand *= valueTrellis[j];\n        }\n        else {\n            summand *= valueRegion[j];\n        }\n    }\n    vol -= summand;\n\n    for (i=1; i<=numberSummands/2; i++) {\n        summand = dTemp[i];\n        summand *= regUp[dimension-2] - trellis[dimension-2];\n        summand /= valueRegion[dimension-2];\n        vol -= summand;\n    }\n\n    //delete[] valueTrellis;\n    //delete[] valueRegion;\n    return vol;\n}\n\n\n\n// return median of the list of boundaries considered as a set\n// TODO linear implementation\ninline double getMedian(vector<double>& bounds) {\n    // do not filter duplicates\n    static unsigned int i;\n    if (bounds.size()==1) {\n        return bounds[0];\n    }\n    else if (bounds.size()==2) {\n        return bounds[1];\n    }\n    vector<double>::iterator median;\n    median = bounds.begin();\n    for(i=0;i<=bounds.size()/2;i++){\n        median++;\n    }\n    partial_sort(bounds.begin(),median,bounds.end());\n    return bounds[bounds.size()/2];\n}\n\n\n\n// recursive calculation of hypervolume\ninline void stream(double regionLow[], double regionUp[], const vector<double*>& points, int split, double cover) {\n\n    //--- init --------------------------------------------------------------//\n\n    static double coverOld;\n    coverOld = cover;\n    unsigned int coverIndex = 0;\n    static int c;\n\n    //--- cover -------------------------------------------------------------//\n\n    // identify first covering cuboid\n    double dMeasure = getMeasure(regionLow, regionUp);\n    while (cover == coverOld && coverIndex < points.size()) {\n        if ( covers(points[coverIndex], regionLow) ) {\n            // new cover value\n            cover = points[coverIndex][dimension-1];\n            volume += dMeasure * (coverOld - cover);\n        }\n        else coverIndex++;\n    }\n\n    /* coverIndex shall be the index of the first point in points which\n     * is ignored in the remaining process\n     *\n     * It may occur that that some points in front of coverIndex have the same\n     * d-th coordinate as the point at coverIndex. This points must be discarded\n     * and therefore the following for-loop checks for this points and reduces\n     * coverIndex if necessary.\n     */\n    for (c=coverIndex; c>0; c--) {\n        if (points[c-1][dimension-1] == cover) {\n            coverIndex--;\n        }\n    }\n\n    // abort if points is empty\n    if (coverIndex == 0) {\n        return;\n    }\n    // Note: in the remainder points is only considered to index coverIndex\n\n\n\n    //--- allPiles  ---------------------------------------------------------//\n\n    bool allPiles = true;\n    unsigned int i;\n\n    static int* piles = new int[coverIndex];\n    for (i = 0; i<coverIndex; i++) {\n        piles[i] = isPile(points[i], regionLow, regionUp);\n        if (piles[i] == -1) {\n            allPiles = false;\n            //delete[] piles;\n            break;\n        }\n    }\n\n    /*\n     * trellis[i] contains the values of the minimal i-coordinate of\n     * the i-piles.\n     * If there is no i-pile the default value is the upper bpund of the region.\n     * The 1-dimensional KMP of the i-piles is: reg[1][i] - trellis[i]\n     *\n     */\n\n    if (allPiles) { // sweep\n\n        // initialize trellis with region's upper bound\n        static double* trellis = new double[dimension-1];\n        for (c=0; c<dimension-1; c++) {\n            trellis[c] = regionUp[c];\n        }\n\n        double current = 0.0;\n        double next = 0.0;\n        i = 0;\n        do { // while(next != coverNew)\n            current = points[i][dimension-1];\n            do { // while(next == current)\n                if (points[i][piles[i]] < trellis[piles[i]]) {\n                    trellis[piles[i]] = points[i][piles[i]];\n                }\n                i++; // index of next point\n                if (i < coverIndex) {\n                    next = points[i][dimension-1];\n                }\n                else {\n                    next = cover;\n                }\n\n            } while(next == current);\n            volume += computeTrellis(regionLow, regionUp, trellis) * (next - current);\n        } while(next != cover);\n    }\n\n\n        //--- split -------------------------------------------------------------//\n        // inner node of partition tree\n    else{\n        double bound = -1.0;\n        vector<double> boundaries;\n        vector<double> noBoundaries;\n\n        do {\n            for (i=0; i<coverIndex; i++) {\n                int contained = containsBoundary(points[i], regionLow, split);\n                if (contained == 1) {\n                    boundaries.push_back(points[i][split]);\n                } else if (contained == 0) {\n                    noBoundaries.push_back(points[i][split]);\n                }\n            }\n\n            if (boundaries.size() >  0) {\n                bound = getMedian(boundaries);\n                //bound = getRandom(boundaries);\n            }\n            else if (noBoundaries.size() >  dSqrtDataNumber) {\n                bound = getMedian(noBoundaries);\n                //bound = getRandom(noBoundaries);\n            }\n            else {\n                split++;\n            }\n        } while (bound == -1.0);\n\n        double dLast;\n        vector<double*> pointsChild;\n        pointsChild.reserve(coverIndex);\n\n        // left child\n        // reduce maxPoint\n        dLast = regionUp[split];\n        regionUp[split] = bound;\n        for (i=0; i<coverIndex; i++) {\n            if (partCovers(points[i], regionUp)) {\n                pointsChild.push_back(points[i]);\n            }\n        }\n        if (!pointsChild.empty()) {\n            stream(regionLow, regionUp, pointsChild, split, cover);\n        }\n\n        // right child\n        // increase minPoint\n        pointsChild.clear();\n        regionUp[split] = dLast;\n        dLast = regionLow[split];\n        regionLow[split] = bound;\n        for (i=0; i<coverIndex; i++) {\n            if (partCovers(points[i], regionUp)) {\n                pointsChild.push_back(points[i]);\n            }\n        }\n        if (!pointsChild.empty()) {\n            stream(regionLow, regionUp, pointsChild, split, cover);\n        }\n        regionLow[split] = dLast;\n\n    }// end inner node\n\n} // end stream\n\n// ----------------\n// Python interface\n// ----------------\n\nnamespace py = pybind11;\n\nPYBIND11_MODULE(hypervolume, m)\n{\n    m.doc() = \"pybind11 hv plugin\";\n\n    m.def(\"calculate\", &calculate);\n}\n", "meta": {"hexsha": "f6c2464c089bbf62d0fac50b5e4db186565d1e4f", "size": 14700, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pymoo/cpp/hypervolume/src/hypervolume.cpp", "max_stars_repo_name": "yashvesikar/pymoo", "max_stars_repo_head_hexsha": "8ce725671d95df580654568fa9bc0e53268aff5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pymoo/cpp/hypervolume/src/hypervolume.cpp", "max_issues_repo_name": "yashvesikar/pymoo", "max_issues_repo_head_hexsha": "8ce725671d95df580654568fa9bc0e53268aff5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pymoo/cpp/hypervolume/src/hypervolume.cpp", "max_forks_repo_name": "yashvesikar/pymoo", "max_forks_repo_head_hexsha": "8ce725671d95df580654568fa9bc0e53268aff5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.488372093, "max_line_length": 115, "alphanum_fraction": 0.558707483, "num_tokens": 3606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.41584242564678175}}
{"text": "/**\n * @file dbscan.hpp\n * @author Ryan Curtin\n *\n * An implementation of the DBSCAN clustering method, which is flexible enough\n * to support other algorithms for finding nearest neighbors.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#ifndef MLPACK_METHODS_DBSCAN_DBSCAN_HPP\n#define MLPACK_METHODS_DBSCAN_DBSCAN_HPP\n\n#include <mlpack/core.hpp>\n#include <mlpack/methods/range_search/range_search.hpp>\n#include \"random_point_selection.hpp\"\n#include <boost/dynamic_bitset.hpp>\n\nnamespace mlpack {\nnamespace dbscan {\n\n/**\n * DBSCAN (Density-Based Spatial Clustering of Applications with Noise) is a\n * clustering technique described in the following paper:\n *\n * @code\n * @inproceedings{ester1996density,\n *   title={A density-based algorithm for discovering clusters in large spatial\n *       databases with noise.},\n *   author={Ester, M. and Kriegel, H.-P. and Sander, J. and Xu, X.},\n *   booktitle={Proceedings of the Second International Conference on Knowledge\n *       Discovery and Data Mining (KDD '96)},\n *   pages={226--231},\n *   year={1996}\n * }\n * @endcode\n *\n * The DBSCAN algorithm iteratively clusters points using range searches with a\n * specified radius parameter.  This implementation allows configuration of the\n * range search technique used and the point selection strategy by means of\n * template parameters.\n *\n * @tparam RangeSearchType Class to use for range searching.\n * @tparam PointSelectionPolicy Strategy for selecting next point to cluster\n *      with.\n */\ntemplate<typename RangeSearchType = range::RangeSearch<>,\n         typename PointSelectionPolicy = RandomPointSelection>\nclass DBSCAN\n{\n public:\n  /**\n   * Construct the DBSCAN object with the given parameters.\n   *\n   * @param epsilon Size of range query.\n   * @param minPoints Minimum number of points for each cluster.\n   * @param rangeSearch Optional instantiated RangeSearch object.\n   * @param pointSelector OptionL instantiated PointSelectionPolicy object.\n   */\n  DBSCAN(const double epsilon,\n         const size_t minPoints,\n         RangeSearchType rangeSearch = RangeSearchType(),\n         PointSelectionPolicy pointSelector = PointSelectionPolicy());\n\n  /**\n   * Performs DBSCAN clustering on the data, returning number of clusters \n   * and also the centroid of each cluster.\n   *\n   * @tparam MatType Type of matrix (arma::mat or arma::sp_mat).\n   * @param data Dataset to cluster.\n   * @param centroids Matrix in which centroids are stored.\n   */\n  template<typename MatType>\n  size_t Cluster(const MatType& data,\n                 arma::mat& centroids);\n\n  /**\n   * Performs DBSCAN clustering on the data, returning number of clusters \n   * and also the list of cluster assignments.\n   *\n   * @tparam MatType Type of matrix (arma::mat or arma::sp_mat).\n   * @param data Dataset to cluster.\n   * @param assignments Vector to store cluster assignments.\n   */\n  template<typename MatType>\n  size_t Cluster(const MatType& data,\n                 arma::Row<size_t>& assignments);\n\n  /**\n   * Performs DBSCAN clustering on the data, returning number of clusters, \n   * the centroid of each cluster and also the list of cluster assignments.\n   * If assignments[i] == assignments.n_elem - 1, then the point is considered\n   * \"noise\".\n   *\n   * @tparam MatType Type of matrix (arma::mat or arma::sp_mat).\n   * @param data Dataset to cluster.\n   * @param assignments Vector to store cluster assignments.\n   * @param centroids Matrix in which centroids are stored.\n   */\n  template<typename MatType>\n  size_t Cluster(const MatType& data,\n                 arma::Row<size_t>& assignments,\n                 arma::mat& centroids);\n\n private:\n  //! Maximum distance between two points to be part of same cluster.\n  double epsilon;\n\n  //! Minimum number of points to be in the epsilon-neighborhood (including\n  //! itself) for the point to be a core-point.\n  size_t minPoints;\n\n  //! Instantiated range search policy.\n  RangeSearchType rangeSearch;\n\n  //! Instantiated point selection policy.\n  PointSelectionPolicy pointSelector;\n\n  /**\n   * This function processes the point at index. It  marks the point as visited,\n   * checks if the given point is core or non-core.  If it is a core point, it\n   * expands the cluster, otherwise it returns.\n   *\n   * @tparam MatType Type of matrix (arma::mat or arma::sp_mat).\n   * @param data Dataset to cluster.\n   * @param unvisited Remembers if a point has been visited.\n   * @param index Index of point to be visited now.\n   * @param assignments Vector to store cluster assignments.\n   * @param currentCluster Index of cluster which will be  assigned to points in\n   *     current cluster.\n   * @param neighbors Matrix containing list of neighbors for each point which\n   *     fall in its epsilon-neighborhood.\n   * @param distances Matrix containing list of distances for each point which\n   *     fall in its epsilon-neighborhood.\n   * @param topLevel If true, then current point is the first point in the\n   *     current cluster, helps in detecting noise.\n   */\n  template<typename MatType>\n  size_t ProcessPoint(const MatType& data,\n                      boost::dynamic_bitset<>& unvisited,\n                      const size_t index,\n                      arma::Row<size_t>& assignments,\n                      const size_t currentCluster,\n                      const std::vector<std::vector<size_t>>& neighbors,\n                      const std::vector<std::vector<double>>& distances,\n                      const bool topLevel = true);\n};\n\n} // namespace dbscan\n} // namespace mlpack\n\n// Include implementation.\n#include \"dbscan_impl.hpp\"\n\n#endif\n", "meta": {"hexsha": "e35d7f9bfb191409f5d35465c0a07600bcbbdb01", "size": 5834, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/methods/dbscan/dbscan.hpp", "max_stars_repo_name": "NaxAlpha/mlpack-build", "max_stars_repo_head_hexsha": "1f0c1454d4b35eb97ff115669919c205cee5bd1c", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-21T11:08:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T07:52:14.000Z", "max_issues_repo_path": "src/mlpack/methods/dbscan/dbscan.hpp", "max_issues_repo_name": "okmegy/Mlpack", "max_issues_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/methods/dbscan/dbscan.hpp", "max_forks_repo_name": "okmegy/Mlpack", "max_forks_repo_head_hexsha": "ac9abef3c1353f483ed1af42ba5a7432f291ca1a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9240506329, "max_line_length": 80, "alphanum_fraction": 0.7002056908, "num_tokens": 1298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.41584242564678164}}
{"text": "#include <Columns/ColumnArray.h>\n#include <Columns/IColumn.h>\n#include <DataTypes/DataTypeArray.h>\n#include <DataTypes/DataTypesNumber.h>\n#include <DataTypes/IDataType.h>\n#include <DataTypes/getLeastSupertype.h>\n#include <Functions/FunctionFactory.h>\n#include <Functions/FunctionHelpers.h>\n\n#include <Eigen/Core>\n\nnamespace DB\n{\nnamespace ErrorCodes\n{\n    extern const int ILLEGAL_TYPE_OF_ARGUMENT;\n    extern const int LOGICAL_ERROR;\n}\n\ntemplate <const int N>\nstruct LpNorm\n{\n    static inline String name = \"L\" + std::to_string(N);\n    template <typename T>\n    static void compute(const std::vector<Eigen::VectorX<T>> & vec, PaddedPODArray<T> & array)\n    {\n        array.reserve(vec.size());\n        for (const auto & v : vec)\n        {\n            array.push_back(v.template lpNorm<N>());\n        }\n    }\n};\n\nstruct LinfNorm : LpNorm<Eigen::Infinity>\n{\n    static inline String name = \"Linf\";\n};\n\ntemplate <class Kernel>\nclass FunctionArrayNorm : public IFunction\n{\npublic:\n    static inline auto name = \"array\" + Kernel::name + \"Norm\";\n    String getName() const override { return name; }\n    static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionArrayNorm<Kernel>>(); }\n    size_t getNumberOfArguments() const override { return 1; }\n    bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; }\n    bool useDefaultImplementationForConstants() const override { return true; }\n\n    DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override\n    {\n        DataTypes types;\n        for (const auto & argument : arguments)\n        {\n            const auto * array_type = checkAndGetDataType<DataTypeArray>(argument.type.get());\n            if (!array_type)\n                throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, \"Argument of function {} must be array.\", getName());\n\n            types.push_back(array_type->getNestedType());\n        }\n        const auto & common_type = getLeastSupertype(types);\n        switch (common_type->getTypeId())\n        {\n            case TypeIndex::UInt8:\n            case TypeIndex::UInt16:\n            case TypeIndex::UInt32:\n            case TypeIndex::Int8:\n            case TypeIndex::Int16:\n            case TypeIndex::Int32:\n            case TypeIndex::Float32:\n                return std::make_shared<DataTypeFloat32>();\n            case TypeIndex::UInt64:\n            case TypeIndex::Int64:\n            case TypeIndex::Float64:\n                return std::make_shared<DataTypeFloat64>();\n            default:\n                throw Exception(\n                    ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,\n                    \"Arguments of function {} has nested type {}. \"\n                    \"Support: UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, Float64.\",\n                    getName(), common_type->getName());\n        }\n    }\n\n    ColumnPtr\n    executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t /*input_rows_count*/) const override\n    {\n        DataTypePtr type = typeid_cast<const DataTypeArray *>(arguments[0].type.get())->getNestedType();\n        ColumnPtr column = arguments[0].column->convertToFullColumnIfConst();\n        const auto * arr = assert_cast<const ColumnArray *>(column.get());\n\n        auto result = result_type->createColumn();\n        switch (result_type->getTypeId())\n        {\n            case TypeIndex::Float32:\n                executeWithType<Float32>(*arr, type, result);\n                break;\n            case TypeIndex::Float64:\n                executeWithType<Float64>(*arr, type, result);\n                break;\n            default:\n                throw Exception(ErrorCodes::LOGICAL_ERROR, \"Unexpected result type.\");\n        }\n        return result;\n    }\n\nprivate:\n    template <typename MatrixType>\n    void executeWithType(const ColumnArray & array, const DataTypePtr & type, MutableColumnPtr & column) const\n    {\n        std::vector<Eigen::VectorX<MatrixType>> vec;\n        columnToVectors(array, type, vec);\n        auto & data = assert_cast<ColumnVector<MatrixType> &>(*column).getData();\n        Kernel::compute(vec, data);\n    }\n\n    template <typename MatrixType>\n    void columnToVectors(const ColumnArray & array, const DataTypePtr & nested_type, std::vector<Eigen::VectorX<MatrixType>> & vec) const\n    {\n        switch (nested_type->getTypeId())\n        {\n            case TypeIndex::UInt8:\n                fillVectors<MatrixType, UInt8>(vec, array);\n                break;\n            case TypeIndex::UInt16:\n                fillVectors<MatrixType, UInt16>(vec, array);\n                break;\n            case TypeIndex::UInt32:\n                fillVectors<MatrixType, UInt32>(vec, array);\n                break;\n            case TypeIndex::UInt64:\n                fillVectors<MatrixType, UInt64>(vec, array);\n                break;\n            case TypeIndex::Int8:\n                fillVectors<MatrixType, Int8>(vec, array);\n                break;\n            case TypeIndex::Int16:\n                fillVectors<MatrixType, Int16>(vec, array);\n                break;\n            case TypeIndex::Int32:\n                fillVectors<MatrixType, Int32>(vec, array);\n                break;\n            case TypeIndex::Int64:\n                fillVectors<MatrixType, Int64>(vec, array);\n                break;\n            case TypeIndex::Float32:\n                fillVectors<MatrixType, Float32>(vec, array);\n                break;\n            case TypeIndex::Float64:\n                fillVectors<MatrixType, Float64>(vec, array);\n                break;\n            default:\n                throw Exception(\n                    ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,\n                    \"Arguments of function {} has nested type {}. \"\n                    \"Support: UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, Float64.\",\n                    getName(), nested_type->getName());\n        }\n    }\n\n    template <typename MatrixType, typename DataType>\n    requires std::is_same_v<MatrixType, DataType>\n    void fillVectors(std::vector<Eigen::VectorX<MatrixType>> & vec, const ColumnArray & array) const\n    {\n        const auto & data = typeid_cast<const ColumnVector<DataType> &>(array.getData()).getData();\n        const auto & offsets = array.getOffsets();\n        vec.reserve(offsets.size());\n        ColumnArray::Offset prev = 0;\n        for (auto off : offsets)\n        {\n            vec.emplace_back(Eigen::Map<const Eigen::VectorX<MatrixType>>(data.data() + prev, off - prev));\n            prev = off;\n        }\n    }\n\n    template <typename MatrixType, typename DataType>\n    void fillVectors(std::vector<Eigen::VectorX<MatrixType>> & vec, const ColumnArray & array) const\n    {\n        const auto & data = typeid_cast<const ColumnVector<DataType> &>(array.getData()).getData();\n        const auto & offsets = array.getOffsets();\n        vec.reserve(offsets.size());\n\n        ColumnArray::Offset prev = 0;\n        for (auto off : offsets)\n        {\n            Eigen::VectorX<MatrixType> mat(off - prev);\n            for (ColumnArray::Offset row = 0; row + prev < off; ++row)\n            {\n                mat[row] = static_cast<MatrixType>(data[prev + row]);\n            }\n            prev = off;\n            vec.emplace_back(mat);\n        }\n    }\n};\n\nvoid registerFunctionArrayNorm(FunctionFactory & factory)\n{\n    factory.registerFunction<FunctionArrayNorm<LpNorm<1>>>();\n    factory.registerFunction<FunctionArrayNorm<LpNorm<2>>>();\n    factory.registerFunction<FunctionArrayNorm<LinfNorm>>();\n}\n\n}\n", "meta": {"hexsha": "20fe85d7491a1df63176f60ea34429214649700a", "size": 7606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Functions/array/arrayNorm.cpp", "max_stars_repo_name": "mrk-andreev/ClickHouse", "max_stars_repo_head_hexsha": "a36f05d6b892aa714c02661c87e2c28f2239020d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-10T04:50:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:51:42.000Z", "max_issues_repo_path": "src/Functions/array/arrayNorm.cpp", "max_issues_repo_name": "mrk-andreev/ClickHouse", "max_issues_repo_head_hexsha": "a36f05d6b892aa714c02661c87e2c28f2239020d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Functions/array/arrayNorm.cpp", "max_forks_repo_name": "mrk-andreev/ClickHouse", "max_forks_repo_head_hexsha": "a36f05d6b892aa714c02661c87e2c28f2239020d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9223300971, "max_line_length": 137, "alphanum_fraction": 0.601761767, "num_tokens": 1667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4157576396218806}}
{"text": "//\n// Created by Beck on 7/3/18.\n// Mahony filter for attitude estimation\n// http://www.olliw.eu/2013/imu-data-fusing/#mahonycode\n//\n\n#include <iostream>\n#include <ros/ros.h>\n#include <ros/console.h>\n#include <std_msgs/String.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <sensor_msgs/Imu.h>\n#include <Eigen/Geometry>\n\nusing namespace std;\nusing namespace Eigen;\n\nros::Publisher pose_pub;\nstring imu_topic, publisher_topic;\n\nQuaterniond q = Quaterniond::Identity();  // state\ndouble sampleFreq = 400.0;  // sample frequency in Hz\ndouble Kp = 0.5;   // proportional gain\ndouble Ki = 0.1;   // integral gain\nVector3d integral = {0.0, 0.0, 0.0};\n\n\nvoid pub_fused_pose(const sensor_msgs::Imu &msg)\n{\n    sensor_msgs::Imu imu_with_pose;\n    imu_with_pose.header = msg.header;\n    imu_with_pose.orientation.w = q.w();\n    imu_with_pose.orientation.x = q.x();\n    imu_with_pose.orientation.y = q.y();\n    imu_with_pose.orientation.z = q.z();\n    imu_with_pose.angular_velocity = msg.angular_velocity;\n    imu_with_pose.angular_velocity_covariance = msg.angular_velocity_covariance;\n    imu_with_pose.linear_acceleration = msg.linear_acceleration;\n    imu_with_pose.linear_acceleration_covariance = msg.linear_acceleration_covariance;\n\n    pose_pub.publish(imu_with_pose);\n}\n\n\nvoid imu_callback(const sensor_msgs::Imu::ConstPtr &imu)\n{\n    Vector3d halfd, halfe;\n\n    Vector3d acc(imu->linear_acceleration.x, imu->linear_acceleration.y, imu->linear_acceleration.z);\n    acc.normalize();\n    Vector3d omg(imu->angular_velocity.x, imu->angular_velocity.y, imu->angular_velocity.z);\n    // omg.normalize();\n    double dt = 1.0 / sampleFreq;\n\n    if (!((acc[0] == 0.0) && (acc[1] == 0.0) && (acc[2] == 0.0))) {\n        // Estimate the gravity vector d from quaternion q\n        // d = Im(q^-1 e_z q)\n        halfd[0] = q.x() * q.z() - q.w() * q.y();\n        halfd[1] = q.w() * q.x() + q.y() * q.z();\n        halfd[2] = q.w() * q.w() - 0.5f + q.z() * q.z();\n\n        // calculate error vector e = a x d\n        halfe = acc.cross(halfd);\n        \n        if (Ki > 0.0) {\n            // In = In-1 + Ki * dt * e\n            integral += 2.0 * Ki * dt * halfe;\n            omg += integral;\n        }\n        else {\n            integral.setZero();\n        }\n        \n        // Apply proportional feedback w' = w + Kp * e + In\n        omg += 2.0 * Kp * halfe;\n    }\n\n    // Integrate rate of change using dq = 0.5 * q x w'\n    omg *= 0.5 * dt;\n\n    q.w() += (-q.x() * omg[0] - q.y() * omg[1] - q.z() * omg[2]);\n    q.x() += (q.w() * omg[0] + q.y() * omg[2] - q.z() * omg[1]);\n    q.y() += (q.w() * omg[1] - q.x() * omg[2] + q.z() * omg[0]);\n    q.z() += (q.w() * omg[2] + q.x() * omg[1] - q.y() * omg[0]);\n    \n    q.normalize();\n    pub_fused_pose(*imu);\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"attitude_estimator_imu\");\n    ros::NodeHandle n(\"~\");\n\n    n.param(\"imu_raw\", imu_topic, string(\"/dji_sdk/imu\")); // 400Hz\n    n.param(\"publisher_topic\", publisher_topic, string(\"/attitude_estimator/imu\"));\n\n    ros::Subscriber s3 = n.subscribe(imu_topic, 400, imu_callback);\n    pose_pub = n.advertise<sensor_msgs::Imu>(publisher_topic, 100);\n\n    ros::Rate r(400);\n    ros::spin();\n}\n", "meta": {"hexsha": "bc598394d4967ee38d8adb377045918399bd1b13", "size": 3192, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3_estimator/history/attitude_estimator/src/attitude_estimator_node.cpp", "max_stars_repo_name": "huying163/ros_environment", "max_stars_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-01-30T11:40:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T05:52:47.000Z", "max_issues_repo_path": "3_estimator/history/attitude_estimator/src/attitude_estimator_node.cpp", "max_issues_repo_name": "huying163/ros_environment", "max_issues_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3_estimator/history/attitude_estimator/src/attitude_estimator_node.cpp", "max_forks_repo_name": "huying163/ros_environment", "max_forks_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-23T08:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T08:14:57.000Z", "avg_line_length": 30.6923076923, "max_line_length": 101, "alphanum_fraction": 0.5993107769, "num_tokens": 986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149978955811, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.41566175819432744}}
{"text": "//Backend for the instanton finder in the AdS/Flat spacetime case.\r\n#define DLL_EXPORT\r\n#define INSTANTON_SOLVER_DLL_API //Comment this out if we wish to import these\r\n//from a DLL instead.\r\n#include \"project_specific.h\"\r\n\r\n#include \"multi_precision_definitions.h\"\r\n#include <boost/array.hpp>//For boost arrays (needed for ode_types)\r\n#include \"Flat.h\"\r\n\r\n//------------------------------------------------------------------------------\r\n//Main function to export:\r\ntemplate< class value_type , class time_type , class solution_type,\r\n          class solution_type_action >\r\nvoid odeSolveFlatFixedBackground\r\n    (value_type false_vacuum , value_type true_vacuum , value_type barrier ,\r\n     potential< value_type >& V , time_type chimax , int odeSolverToUse,\r\n     value_type RelTol, value_type AbsTol, value_type stepError, value_type xi,\r\n     value_type lowerBound , value_type upperBound ,\r\n     solution_grid< time_type , solution_type_action , value_type >& solOut,\r\n     value_type& DSout,value_type precision,std::ostream& outStream,\r\n     bool useSimpleBC,time_type epsilon_step)\r\n{\r\n//INPUTS:\r\n    /*prhs[0] = a in GeV\r\n     *prhs[1] = b (should be -1 < b < 1 to have a barrier)\r\n     *prhs[2] = g (dimensionless coupling strength)\r\n     *prhs[3] = chimax (\"infinity\" - ie, maximum time we allow)\r\n     *prhs[4] = odeSolver, ie, which ode integration routine to use.\r\n     *  odeSolver = 0 -> (Default) Cash-Karp method (Runge-Kutta)\r\n     *  odeSolver = 1 -> Cash-Karp method (Runge-Kutta)\r\n     *  odeSolver = 2 -> Dormand-Prince algorithm (Runge-Kutta)\r\n     *  odeSolver = 3 -> Fehlberg algorithm (Runge-Kutta)\r\n     *  odeSolver = 4 -> Bulirsch-Stoer algorithm (multi-step method)\r\n     *prhs[5] = RelTol, optional (defaults to 1e-15)\r\n     *prhs[6] = AbsTol, optional (defaults to 1e-15)\r\n     *prhs[7] - stepError - optional. Fraction of Taylor series validity bound\r\n     *          to use for first step. Defaults to 1e-15\r\n     *prhs[8] - xi, non-minimal coupling. (optional - default to 0).\r\n        NB - this won't actually affect the fixed background case in flat\r\n            space!!!\r\n     *prhs[9] - Lower bound on range to search (optional, defaults to barrier)\r\n     *prhs[10] - Upper bound on range to search (optional, defaults to\r\n                                                    true-vacuum)\r\n     *prhs[11] - solOut - solution grid to store final result in.\r\n     *prhs[12] - DSout - multi in which to store computed decay exponent.\r\n     prhs[13] - precision - difference desired between upper and lower bounds\r\n                on initial value of solution.\r\n     */\r\n\r\n    //Ok. we proceed by bisecting until we have a solution which overshoots\r\n    //beyond\r\n    //chimax, which stands in for infinity.\r\n\r\n    //Overshoots occur when the solution crosses zero before chimax.\r\n    //Undershoots when\r\n    //its derivative crosses zero before then.\r\n\r\n    //Instantiate the events function, state-type, dynamic BCs etc...\r\n    //typedef boost::array< value_type , 2 > FlatSolType;//solution without\r\n    //action, for speed.\r\n    //typedef boost::array< value_type , 5 > AdSFlatSolTypeAction;\r\n    typedef solution_type FlatSolType;\r\n    typedef solution_type_action FlatSolTypeAction;\r\n    typedef odeFlat< FlatSolType , time_type , value_type > odeRHSFlat;\r\n    typedef eventsFlat< FlatSolType , time_type , value_type > evFlat;\r\n    typedef dynamicBCsFlatFixed_taylor< value_type , FlatSolType , time_type >\r\n            dynBCFlat;\r\n    typedef odeFlatAction< FlatSolTypeAction , time_type , value_type >\r\n            odeRHSFlatAction;\r\n    typedef eventsFlat< FlatSolTypeAction , time_type , value_type >\r\n            evFlatAction;\r\n    typedef dynamicBCsFlatFixed_taylor< value_type , FlatSolTypeAction ,\r\n                                        time_type > dynBCFlatAction;\r\n\r\n    //Instantiation for overshoot/undershoot:\r\n\tvalue_type h = value_type(1.0);//h = phi_scale/M_p so h = 1 is Planck units.\r\n\tvalue_type V0 = value_type(0.0);//V at phi = 0.\r\n    odeRHSFlat odeToSolve(V,xi, h, V0); //ode to solve (gravitational instanton\r\n    //equation)\r\n    //Events function - choose upper and lower bounds 5% outside false and true\r\n    // vacuum, to leave us some leeway for numerical\r\n    //fluctuations near to the nominal boundaries.\r\n    evFlat events(false_vacuum,true_vacuum,false_vacuum,barrier,true_vacuum,\r\n                  outStream); //events function.\r\n        //Checks for events labelled IE:\r\n        //IE = 1 -> y crosses zero (terminal event, => overshoot)\r\n        //IE = 2 -> y' crosses zero (terminal event, => undershoot)\r\n        //IE = 3 -> a crosses zero (non-terminal event, for reference only)\r\n        //IE = 4 -> y crosses lowerBound (usually 0, but could be different -\r\n                                          //terminal event)\r\n        //IE = 5 -> y crosses upperBound (terminal event, indicates bad\r\n                                          //initial condition or perhaps a->0)\r\n    dynBCFlat bcAdjuster(V,stepError,1);//Performs analytic first step using a\r\n                                        // taylor series approximation.\r\n        //stepError - determines size of initial step.\r\n        //version (last argument) - specifies which version of the ode we are\r\n            //using.\r\n            //version = 0 -> normal ode, no action.\r\n            //version = 1 -> ode with action\r\n            //version = 2 -> linearised ode.\r\n    //bcFlat bcAdjusterSimple(V,xi,h,V0);\r\n\r\n\r\n\r\n    //Search loop:\r\n    int nMax = 200;\r\n    int counter = 0;\r\n    //Current bounds on location of bounce:\r\n    value_type lower = lowerBound;//Barrier\r\n    value_type upper = upperBound;//True vacuum\r\n    //outStream << \"Lower initial = \" << lower << std::endl;\r\n    //outStream << \"Upper initial = \" << upper << std::endl;\r\n    value_type guess;\r\n    multi diff = abs(upper - lower);\r\n    while(diff > precision)\r\n    {\r\n        //Bisect to get initial guess:\r\n        guess = (lower + upper)/multi(2.0);\r\n\r\n        //Check for when the solution passes through its FWHM:\r\n        events.value_to_check = (guess + false_vacuum)/value_type(2.0);\r\n\r\n        //Formulate initial conditions vector:\r\n        FlatSolType y0 = {{ guess , value_type(0.0) }};\r\n        //Step away to avoid co-ordinate singularity at chi = 0:\r\n        FlatSolType y01step;\r\n        time_type epsilon;\r\n        /*\r\n        if(!useSimpleBC)\r\n        {\r\n            epsilon = bcAdjuster(y0,y01step,0);//Copies solution after step of\r\n            //epsilon into y01step. Last argument tells us whether\r\n        }\r\n        else\r\n        {\r\n            epsilon = epsilon_step;\r\n            y01step = bcAdjusterSimple(epsilon,y0);\r\n        }\r\n        */\r\n        epsilon = bcAdjuster(y0,y01step);//Copies solution after step of\r\n        //epsilon into y01step. Last argument tells us whether\r\n            //we step forwards (0) or backwards (1) in time.\r\n        //Set up time range:\r\n        time_type tspanArray[2] = { epsilon , chimax };\r\n        std::vector< time_type > tspan;\r\n        tspan.assign(tspanArray,tspanArray + 2);\r\n        //Solve the ode:\r\n        solution_grid< time_type , FlatSolType , value_type > solTemp;\r\n        time_type initStepMax = 0.01/time_type(chimax);\r\n        int nSuccess = ode_solve<time_type,solution_type,value_type>\r\n        (odeToSolve,y01step,tspan,events,odeSolverToUse,solTemp,RelTol,AbsTol,\r\n         initStepMax);\r\n        if(nSuccess != 1)\r\n        {\r\n            outStream << \"nSuccess = \" << nSuccess << \" when solving for \"\r\n                      << \"AdS-Flat instantons.\" << std::endl;\r\n            throw \"Integration failure.\";\r\n        }\r\n        //Now check whether we found an overshoot or an undershoot:\r\n        bool overshoots = false;\r\n        bool undershoots = false;\r\n        for(int j = 0; j < int(solTemp.IE.size());j++)\r\n        {\r\n            switch(solTemp.IE[j])\r\n            {\r\n            case 1:\r\n                //overshoot.\r\n                //outStream << \"Overshoot.\" << std::endl;\r\n                //reportToCaller(\"Overshoot.\\n\");\r\n                overshoots = true;\r\n                upper = guess;\r\n                break;\r\n            case 2:\r\n                //undershoot, IF it occurs on the opposite side of the barrier\r\n                //to the true vacuum (theoretically impossible to occur on the\r\n                                      //other\r\n                //side, so must be a numerical artefact if it does).\r\n                if((true_vacuum - barrier)*(solTemp.YE[j][0] - barrier)\r\n                   < value_type(0.0))\r\n                {\r\n                    //outStream << \"Undershoot.\" << std::endl;\r\n                    //reportToCaller(\"Undershoot.\\n\");\r\n                    undershoots = true;\r\n                    lower = guess;\r\n                }\r\n                break;\r\n            case 3:\r\n                //FWHM. No need to do anything.\r\n                break;\r\n            case 4:\r\n                //Crossed lower bound. Indicates a bad initial condition.\r\n                outStream << \"Upper bound crossed during ode integration. \"\r\n                          << \"Possibly a bad initial condition (wrong side of \"\r\n                          << \"true vacuum) or solution undershot and event \"\r\n                          << \"detection failed to detect this.\" << std::endl;\r\n                //reportToCaller(\"Upper bound crossed during ode integration.\r\n                //Possibly a bad initial condition (wrong side of true vacuum)\r\n                //or solution undershot and event detection failed to detect\r\n                //this.\\n\");\r\n                throw \"Unexpected ode-event encountered during integration.\";\r\n                break;\r\n            case 5:\r\n                //Crossed upper bound. Indicates a bad initial condition.\r\n                outStream << \"Lower bound crossed during ode integration. \"\r\n                          << \"Possibly a bad initial condition (wrong side of \"\r\n                          << \"true vacuum) or solution overshot and event\"\r\n                          << \" detection failed to detect this.\" << std::endl;\r\n                //reportToCaller(\"Upper bound crossed during ode integration.\r\n                                 //Possibly a bad initial condition\r\n                                 //(wrong side of true vacuum) or solution\r\n                                 //undershot and event detection failed to\r\n                                 //detect this.\\n\");\r\n                throw \"Unexpected ode-event encountered during integration.\";\r\n            default:\r\n                outStream << \"Unrecognised ode-event.\" << std::endl;\r\n                //reportToCaller(\"Unrecognised ode-event.\\n\");\r\n                throw \"Unexpected ode-event encountered during integration.\";\r\n            }\r\n            if(overshoots || undershoots)\r\n            {\r\n                break;\r\n            }\r\n        }\r\n        counter++;\r\n        diff = abs(lower - upper);\r\n\r\n\r\n        if(overshoots)\r\n        {\r\n            //outStream << \"Overshoot.\\n\" << std::endl;\r\n        }\r\n        else if(undershoots)\r\n        {\r\n            //outStream << \"Undershoot.\\n\" << std::endl;\r\n        }\r\n\r\n        //Dump all available data if we get neither an overshoot nor an\r\n        //undershoot, as this is\r\n        //theoretically impossible so we want to understand what went wrong:\r\n        else if(!(overshoots||undershoots))\r\n        {\r\n            outStream << \"Neither undershoot nor overshoot detected. \"\r\n                      << \"(Perhaps integration range should be extended?) \"\r\n                      << \"Relevant data:\\n\";\r\n            outStream << \"no. of events = \" << int(solTemp.IE.size())\r\n                      << std::endl;\r\n            for(int i = 0; i < int(solTemp.IE.size());i++)\r\n            {\r\n                outStream << \"IE[\" << i << \"] = \" << solTemp.IE[i] << std::endl;\r\n                outStream << \"YE[\" << i << \"] = \" << std::endl;\r\n                for(int j = 0;j < 2;j++)\r\n                {\r\n                    outStream << solTemp.YE[i][j] << std::endl;\r\n                }\r\n                outStream << \"TE[\" << i << \"] = \" << solTemp.TE[i] << std::endl;\r\n            }\r\n            outStream << \"y0 = \\n\";\r\n            for(int i = 0;i < 2;i++)\r\n            {\r\n                outStream << y01step[i] << std::endl;\r\n            }\r\n            outStream << \"yend = \\n\";\r\n            for(int i = 0;i < 2;i++)\r\n            {\r\n                outStream << solTemp.Y[int(solTemp.Y.size() - 1)][i]\r\n                          << std::endl;\r\n            }\r\n            outStream << \"Tend = \" << solTemp.T[int(solTemp.T.size()) - 1]\r\n                      << std::endl;\r\n            //Now exit, throwing an error:\r\n            throw \"Error - Neither overshoot nor undershoot detected.\\n\";\r\n        }\r\n\r\n    }\r\n    //We found the bounce. Are we within precision?\r\n    if(diff > precision)\r\n    {\r\n        outStream << \"Loop exited before finding bounce.\" << std::endl;\r\n        //reportToCaller(\"Loop exited before finding bounce.\\n\");\r\n    }\r\n\r\n    //Compute action:\r\n    odeRHSFlatAction odeToSolveAction(V,xi,value_type(1.0),value_type(0.0));\r\n    evFlatAction eventsAction(false_vacuum,true_vacuum,false_vacuum,barrier,\r\n                              true_vacuum , outStream);\r\n    dynBCFlatAction bcAdjusterAction(V,stepError,2);\r\n\r\n    //Check for when the solution passes through its FWHM:\r\n    eventsAction.value_to_check = (guess + false_vacuum)/value_type(2.0);\r\n    //Disable termination so that we can see the full extent of the solution:\r\n    //eventsAction.terminate_on = false;\r\n    //eventsAction.dynamicSwitch[0] = false;\r\n    //eventsAction.dynamicSwitch[1] = false;\r\n\r\n    FlatSolTypeAction y0Action = {{ guess , value_type(0.0) ,\r\n                                    value_type(0.0) }};\r\n    FlatSolTypeAction y0Action1step;\r\n    time_type epsAction;\r\n    /*\r\n    if(!useSimpleBC)\r\n    {\r\n        epsAction = bcAdjusterAction(y0Action,y0Action1step,0);\r\n        //Copies solution after step of epsilon into y01step.\r\n        //Last argument tells us whether\r\n    }\r\n    else\r\n    {\r\n        epsAction = epsilon_step;\r\n        y0Action1step = bcAdjusterSimple(epsAction,y0Action);\r\n    }\r\n    */\r\n    epsAction = bcAdjusterAction(y0Action,y0Action1step);\r\n    time_type tspanArray[2] = { epsAction , chimax };\r\n    std::vector< time_type > tspan;\r\n    tspan.assign(tspanArray,tspanArray + 2);\r\n    time_type initStepMax = 0.01/time_type(chimax);\r\n    int nSuccess = ode_solve<time_type,solution_type_action,value_type>\r\n    (odeToSolveAction,y0Action1step,tspan,eventsAction,odeSolverToUse,solOut,\r\n     RelTol,AbsTol,initStepMax);\r\n    if(nSuccess != 1)\r\n    {\r\n        outStream << \"nSuccess = \" << nSuccess << \" when solving for AdS-Flat \"\r\n                  << \"instantons.\" << std::endl;\r\n        throw \"Integration failure.\";\r\n    }\r\n    DSout = solOut.Y[int(solOut.T.size()) - 1][2];\r\n    //Done.\r\n}\r\n//------------------------------------------------------------------------------\r\n//Export an ode solver:\r\n//Main function to export:\r\ntemplate< class value_type , class time_type , class solution_type,\r\n          class solution_type_action >\r\nvoid odeSolveFlatFixedBackgroundSingle\r\n    (value_type y0,value_type false_vacuum , value_type true_vacuum ,\r\n     value_type barrier , potential< value_type >& V , time_type chimax ,\r\n     int odeSolverToUse, value_type RelTol, value_type AbsTol,\r\n     value_type stepError, value_type xi, value_type lowerBound ,\r\n     value_type upperBound , solution_grid< time_type , solution_type_action ,\r\n     value_type >& solOut,value_type& DSout,value_type precision,\r\n     std::ostream& outStream)\r\n{\r\n//INPUTS:\r\n    /*prhs[0] = a in GeV\r\n     *prhs[1] = b (should be -1 < b < 1 to have a barrier)\r\n     *prhs[2] = g (dimensionless coupling strength)\r\n     *prhs[3] = chimax (\"infinity\" - ie, maximum time we allow)\r\n     *prhs[4] = odeSolver, ie, which ode integration routine to use.\r\n     *  odeSolver = 0 -> (Default) Cash-Karp method (Runge-Kutta)\r\n     *  odeSolver = 1 -> Cash-Karp method (Runge-Kutta)\r\n     *  odeSolver = 2 -> Dormand-Prince algorithm (Runge-Kutta)\r\n     *  odeSolver = 3 -> Fehlberg algorithm (Runge-Kutta)\r\n     *  odeSolver = 4 -> Bulirsch-Stoer algorithm (multi-step method)\r\n     *prhs[5] = RelTol, optional (defaults to 1e-15)\r\n     *prhs[6] = AbsTol, optional (defaults to 1e-15)\r\n     *prhs[7] - stepError - optional. Fraction of Taylor series validity bound\r\n     *          to use for first step. Defaults to 1e-15\r\n     *prhs[8] - xi, non-minimal coupling. (optional - default to 0).\r\n        NB - this won't actually affect the fixed background case in\r\n        flat space!!!\r\n     *prhs[9] - Lower bound on range to search (optional, defaults to barrier)\r\n     *prhs[10] - Upper bound on range to search (optional, defaults to\r\n                                                 true-vacuum)\r\n     *prhs[11] - solOut - solution grid to store final result in.\r\n     *prhs[12] - DSout - multi in which to store computed decay exponent.\r\n     prhs[13] - precision - difference desired between upper and lower bounds\r\n        on initial value of solution.\r\n     */\r\n\r\n    //Ok. we proceed by bisecting until we have a solution which overshoots\r\n    //beyond\r\n    //chimax, which stands in for infinity.\r\n\r\n    //Overshoots occur when the solution crosses zero before chimax.\r\n    // Undershoots when\r\n    //its derivative crosses zero before then.\r\n\r\n    //Instantiate the events function, state-type, dynamic BCs etc...\r\n    //typedef boost::array< value_type , 2 > FlatSolType;//solution without\r\n    //action, for speed.\r\n    //typedef boost::array< value_type , 5 > AdSFlatSolTypeAction;\r\n    typedef solution_type FlatSolType;\r\n    typedef solution_type_action FlatSolTypeAction;\r\n    typedef odeFlat< FlatSolType , time_type , value_type > odeRHSFlat;\r\n    typedef eventsFlat< FlatSolType , time_type , value_type > evFlat;\r\n    typedef dynamicBCsFlatFixed_taylor< value_type , FlatSolType , time_type >\r\n            dynBCFlat;\r\n    typedef odeFlatAction< FlatSolTypeAction , time_type , value_type >\r\n            odeRHSFlatAction;\r\n    typedef eventsFlat< FlatSolTypeAction , time_type , value_type >\r\n            evFlatAction;\r\n    typedef dynamicBCsFlatFixed_taylor< value_type , FlatSolTypeAction ,\r\n                                         time_type > dynBCFlatAction;\r\n\r\n    //Instantiation for overshoot/undershoot:\r\n    outStream << \"Setup ode...\" << std::endl;\r\n\tvalue_type h = value_type(1.0);//h = phi_scale/M_p so h = 1 is Planck units.\r\n\tvalue_type V0 = value_type(0.0);//V at phi = 0.\r\n    odeRHSFlat odeToSolve(V,xi, h, V0); //ode to solve (gravitational\r\n                                                        //instanton equation)\r\n\r\n    //Compute action:\r\n    odeRHSFlatAction odeToSolveAction(V,xi,value_type(1.0),value_type(0.0));\r\n    evFlatAction eventsAction(false_vacuum*value_type(1.05),true_vacuum*\r\n                              value_type(1.05),false_vacuum,barrier,\r\n                              true_vacuum , outStream);\r\n    dynBCFlatAction bcAdjusterAction(V,stepError,2);\r\n\r\n    outStream << \"Setup initial conditions...\" << std::endl;\r\n    FlatSolTypeAction y0Action = {{ y0 , value_type(0.0) , value_type(0.0) }};\r\n    outStream << \"V'(y0) = \" << V.d(y0) << std::endl;\r\n    FlatSolTypeAction y0Action1step;\r\n    time_type epsAction = bcAdjusterAction(y0Action,y0Action1step);\r\n    outStream << \"y0Action1step = \\n\" << y0Action1step[0] << \"\\n\"\r\n              << y0Action1step[1] << \"\\n\" << y0Action1step[2] << std::endl;\r\n    outStream << \"Setup timespan...\" << std::endl;\r\n    time_type tspanArray[2] = { epsAction , chimax };\r\n    std::vector< time_type > tspan;\r\n    tspan.assign(tspanArray,tspanArray + 2);\r\n    outStream << \"Integrating...\" << std::endl;\r\n    time_type initStepMax = 0.01/time_type(chimax);\r\n    int nSuccess = ode_solve<time_type,solution_type_action,value_type>\r\n    (odeToSolveAction,y0Action1step,tspan,eventsAction,odeSolverToUse,solOut,\r\n     RelTol,AbsTol,initStepMax);\r\n    if(nSuccess != 1)\r\n    {\r\n        outStream << \"nSuccess = \" << nSuccess << \" when solving for AdS-Flat \"\r\n                  << \"instantons.\" << std::endl;\r\n        throw \"Integration failure.\";\r\n    }\r\n    outStream << \"Compute action...\" << std::endl;\r\n    DSout = solOut.Y[int(solOut.T.size()) - 1][2];\r\n    //Done.\r\n    outStream << \"Done.\" << std::endl;\r\n}\r\n//------------------------------------------------------------------------------\r\n//------------------------------------------------------------------------------\r\n//Explicit instantiation and export of this function:\r\ntemplate DLL_EXPORT void odeSolveFlatFixedBackground\r\n    < multi , multi , boost::array< multi , 2 > , boost::array< multi , 3 > >\r\n    (multi , multi , multi , potential< multi >& , multi , int, multi, multi,\r\n     multi, multi, multi , multi ,\r\n     solution_grid< multi , boost::array< multi , 3 > , multi >& ,\r\n     multi&,multi,std::ostream&,bool,multi);\r\n//------------------------------------------------------------------------------\r\ntemplate DLL_EXPORT void odeSolveFlatFixedBackgroundSingle\r\n    < multi , multi , boost::array< multi , 2 > , boost::array< multi , 3 > >\r\n    (multi,multi , multi , multi , potential< multi >& , multi , int,\r\n     multi, multi, multi, multi,multi , multi ,\r\n     solution_grid< multi , boost::array< multi , 3 > , multi >& ,\r\n     multi&,multi,std::ostream&);\r\n//------------------------------------------------------------------------------\r\n", "meta": {"hexsha": "6c109da68e5eebee884d47d9d75b628756ebb1d2", "size": 21495, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Flat.cpp", "max_stars_repo_name": "svstopyra/dS_instanton_solver", "max_stars_repo_head_hexsha": "9517036c03ec9129989ed7f1e3eeecabf4119bfe", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Flat.cpp", "max_issues_repo_name": "svstopyra/dS_instanton_solver", "max_issues_repo_head_hexsha": "9517036c03ec9129989ed7f1e3eeecabf4119bfe", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Flat.cpp", "max_forks_repo_name": "svstopyra/dS_instanton_solver", "max_forks_repo_head_hexsha": "9517036c03ec9129989ed7f1e3eeecabf4119bfe", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.345814978, "max_line_length": 81, "alphanum_fraction": 0.5720865318, "num_tokens": 5170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4156617460501832}}
{"text": "/*\nCopyright (c) 2014 Mohamed Elsabagh <melsabag@gmu.edu>\n \nPermission is hereby granted, free of charge, to any person obtaining a copy of this \nsoftware and associated documentation files (the \"Software\"), to deal in the Software \nwithout restriction, including without limitation the rights to use, copy, modify, \nmerge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit \npersons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies \nor substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, \nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR \nPURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE \nFOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR \nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER \nDEALINGS IN THE SOFTWARE.\n*/\n\n#ifndef SAXQUANTIZER_HPP\n#define SAXQUANTIZER_HPP\n\n#include <deque>\n#include <vector>\n#include <cassert>\n#include <boost/math/distributions/normal.hpp>\n\nusing std::deque;\nusing std::vector;\n\nnamespace SaxQuantizer {\n \n  /**\n  * Helper routine to generate the SAX codebook (list of cutpoints) of a given size\n  * @param <alphabet_size>: number of desired codewords\n  * @param <cutpoints> (out): resulting codebook \n  */\n  inline void fill_cutpoints(size_t alphabet_size, vector<double> *cutpoints) {\n    assert(alphabet_size > 0);\n    static boost::math::normal dist(0.0, 1.0);\n    std::cout << \"alphabet: \" << alphabet_size << std::endl;\n    cutpoints->reserve(alphabet_size);\n    cutpoints->push_back(-DBL_MAX);\n    for (size_t i = 1; i < alphabet_size; ++i) {\n      double cdf = ((double) i) / alphabet_size;\n      cutpoints->push_back(quantile(dist, cdf));\n    }\n  }\n\n  /**\n   * Symbolic Aggregate Approximation with fractional sliding window, numerosity reduction, and scaling\n   */\n  class Sax {\n  private:\n    size_t m_window_size;\n    size_t m_string_size;\n    size_t m_alphabet_size;\n\n    double m_baseline_mean;\n    double m_baseline_stdev;\n    vector<double> m_cutpoints;\n\n    bool m_trained;\n\n    /**\n     * SAX with fractional sliding window and automatic scaling.\n     * @param <it>: start iterator\n     * @param <end>: end iterator\n     * @param <syms> (out): quantized range\n     */\n    template<class Iter>\n    void saxify(Iter it, const Iter end, vector<int> *syms) {\n      // perform PAA using a fractional sliding window\n      double paa[m_string_size];\n      double paa_window = ((double) m_window_size) / m_string_size;\n\n      double p = 0; // p for progress\n      double w = 1; // w for weight\n      size_t available = 0;\n\n      for (size_t i = 0; i < m_string_size && it != end; ++i, ++available) {  \n        // normalize around baseline\n        double normalized = (*it - m_baseline_mean) / m_baseline_stdev;\n        \n        paa[i] = 0;\n        double j = 0;\n        while (j < paa_window && it != end) {\n          paa[i] += w * normalized; // sum of (partial) elements inside the window\n          j += w;\n          p += w;\n\n          // window full\n          if (paa_window == p) {\n            if (fabs(w - 1.0) <= 0.01) {   // if last element fully consumed,\n              ++it;                        // then just move next.\n            } else {                       // o.w.,\n              w = 1.0 - w;                 // set remaining portion.\n            }\n\n            p = 0;                         // reset progress\n         \n          // window not full, but next must be split\n          } else if (paa_window - p < 1.0) {\n            w = paa_window - p;            // set needed portion\n            ++it;                          // move to next\n\n          // window not full, next can be fully consumed\n          } else {\n            ++it;                          // move to next\n          }\n        }\n\n        paa[i] /= j; // averaging\n      }\n\n      // map to symbols. 0-based.\n      for (size_t i = 0; i < available; ++i) {\n        int cnt = -1;\n        for (const auto & cp : m_cutpoints) {\n          if (paa[i] >= cp) ++cnt;\n        }\n        syms->push_back(cnt);\n      }\n    }\n\n  public:\n    /**\n    * Constructs a SAX quantizer of a given window size, string size and alphabet size.\n    * @param <window_size>: sliding window size\n    * @param <string_size>: output string size for each sliding window (can be greater than window_size)\n    * @param <alphabet_size>: number of codewords\n    */\n    Sax(size_t window_size, size_t string_size, size_t alphabet_size) \n     : m_window_size(window_size), m_string_size(string_size), m_alphabet_size(alphabet_size),\n       m_baseline_mean(0), m_baseline_stdev(1), m_trained(false) {\n\n      assert(window_size > 0);\n      assert(string_size > 0);\n      assert(alphabet_size > 0);\n\n      fill_cutpoints(alphabet_size, &m_cutpoints);\n    }\n\n    virtual ~Sax() {\n      m_cutpoints.clear();\n    }\n\n    /**\n     * Trains the quantizer from a given sample. This sets the baseline mean and stdevs, which are used in\n     * normalizing the input.\n     *\n     * @param <samples>: list of training values\n     */\n    template<typename Container>\n    void train(const Container & samples) {\n      double mean = 0;\n      double stdev = DBL_MIN;\n     \n      assert(!samples.empty());\n\n      if (samples.size() < 2) {\n        mean = samples[0];\n        stdev = DBL_MIN;\n\n      } else {\n        size_t n = 0;\n        double M2 = 0;\n        for (const auto & val : samples) {\n          ++n;\n          double delta = val - mean;\n          mean += delta / n;\n          M2 += delta * (val - mean);\n        }\n        stdev = sqrt(M2 / (n-1));\n      }\n\n      if (stdev == 0) stdev = DBL_MIN;\n\n      m_baseline_mean = mean;\n      m_baseline_stdev = stdev;\n\n      m_trained = true;\n    }\n\n    /**\n     * Quantizes the given input sequence into a discrete alphabet using SAX.\n     * Calling this method will also train the quantizer using the input sequence, if \n     * not already trained.\n     *\n     * @param <seq>: the input sequence to be quantized\n     * @param <qseq> (out): quantized output sequence \n     * @param reduce (default true): if true, applies run-length numerosity reduction\n     *\n     * Returns the number of consumed symbols from the input sequence.\n     */\n    template<typename Container>\n    size_t quantize(const Container & seq, vector<int> *qseq, bool reduce=true) {\n      if (!m_trained) train(seq);\n      \n      vector<int> buf1, buf2;\n      auto *syms_buf = &buf1;\n      auto *old_syms_buf = &buf2;\n\n      size_t consumed = 0;\n      for (consumed = 0; consumed < seq.size(); ++consumed) {\n\n        if (reduce) { // run-length numerosity reduction\n          syms_buf->clear();\n          saxify(seq.begin() +consumed, seq.end(), syms_buf);\n\n          // skip window if same as previous\n          if (*syms_buf != *old_syms_buf) {\n            qseq->insert(qseq->end(), syms_buf->begin(), syms_buf->end());\n            std::swap(syms_buf, old_syms_buf);\n          }\n\n        } else { // no reduction\n          saxify(seq.begin() +consumed, seq.end(), qseq);\n        }\n\n        // ignore excess elements, if sequence size isn't a multiple of window size\n        //if (seq.size() - consumed <= m_window_size) break;\n      }\n\n      return consumed;\n    }\n\n    /**\n     * Returns the order of the quantizer (here, the window size)\n     */\n    inline size_t order() const {\n      return m_window_size;\n    }\n\n  \n    /**\n     * Returns the compression ratio of the quantizer (input size / output size)\n     */\n    inline double ratio() const {\n      return ((double) m_window_size) / m_string_size;\n    }\n  };\n\n}\n\n#endif\n", "meta": {"hexsha": "4c8461d9b56edff06ecf7ffac2e668144c005acc", "size": 7804, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "saxquantizer.hpp", "max_stars_repo_name": "melsabagh/sax", "max_stars_repo_head_hexsha": "9550c8ef719a649cd19755d83aac9d592beddf09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-11-08T01:54:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-22T17:56:35.000Z", "max_issues_repo_path": "saxquantizer.hpp", "max_issues_repo_name": "melsabagh/sax", "max_issues_repo_head_hexsha": "9550c8ef719a649cd19755d83aac9d592beddf09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "saxquantizer.hpp", "max_forks_repo_name": "melsabagh/sax", "max_forks_repo_head_hexsha": "9550c8ef719a649cd19755d83aac9d592beddf09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-10-10T03:39:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-06T10:13:52.000Z", "avg_line_length": 31.4677419355, "max_line_length": 106, "alphanum_fraction": 0.5998206048, "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.41565459927447623}}
{"text": "/**\n * @file helper.hpp\n * @author francois.hamonic@gmail.com\n * @brief\n * @version 0.1\n * @date 2021-07-19\n */\n#ifndef HELPER_HPP\n#define HELPER_HPP\n\n#include <math.h>\n#include <filesystem>\n#include <iterator>\n\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm.hpp>\n\n#include \"landscape/decored_landscape.hpp\"\n#include \"landscape/mutable_landscape.hpp\"\n\n#include \"Eigen/Dense\"\n#include \"algorithms/multiplicative_dijkstra.hpp\"\n#include \"lemon/dijkstra.h\"\n\n#include \"fast-cpp-csv-parser/csv.h\"\n#include \"solvers/concept/solver.hpp\"\n\n#include \"lemon/dim2.h\"\n#include \"lemon/graph_to_eps.h\"\n\n#include \"indices/eca.hpp\"\n\nnamespace Helper {\n/**\n * @brief Compute the distance matrix of a graph.\n *\n * Generic implementation of computing the distance matrix of a graph by running\n * dijkstra for each node. The length map values must support numeric\n * operations. Complexities are $O((m+n) \\cdot \\log n)$ time and $O(n^2)$ space,\n * where $n$ is the number of nodes and $m$ the number of arcs. Diagonal entries\n * are $0$ and unreachable nodes entries are\n * $std::numeric_limits<Value>::max()$.\n *\n * @tparam GR : type of graph\n * @tparam DM : type of length map\n * @param g : graph\n * @param l : length map\n * @return Eigen::Matrix<typename DM::Value, Eigen::Dynamic, Eigen::Dynamic>*\n */\ntemplate <typename GR, typename DM>\nstatic Eigen::Matrix<typename DM::Value, Eigen::Dynamic, Eigen::Dynamic> *\ndistanceMatrix(const GR & g, DM & l) {\n    using Value = typename DM::Value;\n\n    const int n = lemon::countNodes(g);\n    Eigen::Matrix<Value, Eigen::Dynamic, Eigen::Dynamic> * distances =\n        new Eigen::Matrix<Value, Eigen::Dynamic, Eigen::Dynamic>(n, n);\n    distances->fill(std::numeric_limits<Value>::max());\n\n    lemon::SimplerDijkstra<GR, DM> dijkstra(g, l);\n\n    for(typename GR::NodeIt s(g); s != lemon::INVALID; ++s) {\n        const int id_s = g.id(s);\n        dijkstra.run(s);\n\n        for(typename GR::NodeIt t(g); t != lemon::INVALID; ++t) {\n            const int id_t = g.id(t);\n            Value & d_st = (*distances)(id_s, id_t);\n            if(!dijkstra.reached(t)) {\n                d_st = std::numeric_limits<Value>::max();\n                continue;\n            }\n            d_st = dijkstra.dist(t);\n        }\n    }\n    return distances;\n}\n\n/**\n * @brief Compute the distance matrix of a graph.\n *\n * Generic implementation of computing the distance matrix of a graph by running\n * dijkstra for each node. The probability map values must support numeric\n * operations. Complexities are $O((m+n) \\cdot \\log n)$ time and $O(n^2)$ space,\n * where $n$ is the number of nodes and $m$ the number of arcs. Diagonal entries\n * are $1$ and unreachable nodes entries are $0$.\n *\n * @tparam GR : type of graph\n * @tparam DM : type of length map\n * @param g : graph\n * @param p : probability map\n * @return Eigen::Matrix<typename DM::Value, Eigen::Dynamic, Eigen::Dynamic>*\n */\ntemplate <typename GR, typename DM>\nstatic Eigen::Matrix<typename DM::Value, Eigen::Dynamic, Eigen::Dynamic> *\nmultDistanceMatrix(const GR & g, DM & p) {\n    using Value = typename DM::Value;\n\n    const int n = lemon::countNodes(g);\n    Eigen::Matrix<Value, Eigen::Dynamic, Eigen::Dynamic> * distances =\n        new Eigen::Matrix<Value, Eigen::Dynamic, Eigen::Dynamic>(n, n);\n    distances->fill(0);\n\n    lemon::MultiplicativeSimplerDijkstra<GR, DM> dijkstra(g, p);\n\n    for(typename GR::NodeIt s(g); s != lemon::INVALID; ++s) {\n        const int id_s = g.id(s);\n        dijkstra.run(s);\n\n        for(typename GR::NodeIt t(g); t != lemon::INVALID; ++t) {\n            const int id_t = g.id(t);\n            Value & d_st = (*distances)(id_s, id_t);\n            if(!dijkstra.reached(t)) {\n                d_st = 0;\n                continue;\n            }\n            d_st = dijkstra.dist(t);\n        }\n    }\n    return distances;\n}\n\ntemplate <typename LS>\ndouble minNonZeroQuality(const LS & landscape) {\n    using Graph = typename LS::Graph;\n    const Graph & graph = landscape.getNetwork();\n    double min = std::numeric_limits<double>::max();\n    for(typename Graph::NodeIt v(graph); v != lemon::INVALID; ++v) {\n        if(landscape.getQuality(v) == 0) continue;\n        min = std::min(min, landscape.getQuality(v));\n    }\n    return min;\n}\n\n/**\n * @brief Compute the centrality of each arc, i.e the number of shortest paths\n * that contain it\n * @tparam GR\n * @tparam LM\n * @param graph\n * @param lengthMap\n * @return GR::ArcMap<int>*\n */\ntemplate <typename Graph, typename LengthMap>\nstd::unique_ptr<typename Graph::template ArcMap<int>> arcCentralityMap(\n    const Graph & graph, const LengthMap & lengthMap) {\n    using PredMap = typename Graph::template NodeMap<typename Graph::Arc>;\n\n    std::unique_ptr<typename Graph::template ArcMap<int>> centralityMap =\n        std::make_unique<typename Graph::template ArcMap<int>>(graph, 0);\n\n    lemon::Dijkstra<Graph, LengthMap> dijkstra(graph, lengthMap);\n\n    for(typename Graph::NodeIt s(graph); s != lemon::INVALID; ++s) {\n        dijkstra.run(s);\n        const PredMap & predMap = dijkstra.predMap();\n        for(typename Graph::NodeIt t(graph); t != lemon::INVALID; ++t) {\n            if(!dijkstra.reached(t)) continue;\n            typename Graph::Node u = t;\n            while(u != s) {\n                (*centralityMap)[predMap[u]] += 1;\n                u = graph.source(predMap[u]);\n            }\n        }\n    }\n    return centralityMap;\n}\n\n/**\n * @brief Compute the centrality of each arc, i.e the number of shortest paths\n * that contain it\n * @tparam GR\n * @tparam LM\n * @param graph\n * @param lengthMap\n * @return GR::ArcMap<int>*\n */\ntemplate <typename LS>\nstd::unique_ptr<typename LS::Graph::template ArcMap<double>>\ncorridorCentralityMap(const LS & landscape) {\n    using Graph = typename LS::Graph;\n    using PredMap = typename Graph::template NodeMap<typename Graph::Arc>;\n    const Graph & graph = landscape.getNetwork();\n\n    std::unique_ptr<typename Graph::template ArcMap<double>> centralityMap =\n        std::make_unique<typename Graph::template ArcMap<double>>(graph, 0);\n\n    lemon::Dijkstra<Graph, typename LS::ProbabilityMap> dijkstra(\n        graph, landscape.getProbabilityMap());\n\n    for(typename Graph::NodeIt s(graph); s != lemon::INVALID; ++s) {\n        if(landscape.getQuality(s) == 0) continue;\n        dijkstra.run(s);\n        const PredMap & predMap = dijkstra.predMap();\n        for(typename Graph::NodeIt t(graph); t != lemon::INVALID; ++t) {\n            if(landscape.getQuality(t) == 0) continue;\n            if(!dijkstra.reached(t)) continue;\n            typename Graph::Node u = t;\n            while(u != s) {\n                (*centralityMap)[predMap[u]] += 1;\n                u = graph.source(predMap[u]);\n            }\n        }\n    }\n    return centralityMap;\n}\n\n/**\n * @brief Computes the value of the ECA index of the specified landscape\n * graph.\n *\n * @time \\f$O(n \\cdot (m + n) \\log n)\\f$ where \\f$n\\f$ is the number of\n * nodes and \\f$m\\f$ the number of arcs\n * @space \\f$O(m)\\f$ where \\f$m\\f$ is the number of arcs\n */\ntemplate <typename GR, typename QM, typename PM>\nstd::vector<std::pair<typename GR::Node, double>> computeDistancePairs(\n    const GR & graph, const QM & qualityMap, const PM & probabilityMap,\n    const typename GR::Node s) {\n    using Node = typename GR::Node;\n\n    std::vector<std::pair<Node, double>> result;\n    result.reserve(lemon::countNodes(graph));\n    lemon::MultiplicativeSimplerDijkstra<GR, PM> dijkstra(graph,\n                                                          probabilityMap);\n    if(qualityMap[s] != 0) {\n        dijkstra.init(s);\n        while(!dijkstra.emptyQueue()) {\n            result.emplace_back(dijkstra.processNextNode());\n            if(result.back().second == 0.0) {\n                result.pop_back();\n                break;\n            }\n        }\n    }\n    return result;\n}\n\ntemplate <typename LS>\nstd::vector<std::pair<typename LS::Node, double>> computeDistancePairs(\n    const LS & landscape, const typename LS::Node s) {\n    auto result =\n        computeDistancePairs(landscape.getNetwork(), landscape.getQualityMap(),\n                             landscape.getProbabilityMap(), s);\n    return result;\n}\n\ntemplate <typename LS>\ndouble averageRatioOfNodesInECARealization(double ratio_of_eca,\n                                           LS && landscape) {\n    using Graph = typename std::remove_reference<LS>::type::Graph;\n    using NodeIt = typename std::remove_reference<LS>::type::NodeIt;\n\n    const Graph & graph = landscape.getNetwork();\n\n    double average_sum = 0.0;\n    int cpt = 0;\n    for(NodeIt s(graph); s != lemon::INVALID; ++s) {\n        const auto sorted_pairs = computeDistancePairs(landscape, s);\n\n        if(sorted_pairs.empty()) continue;\n\n        const double contribution_max = std::transform_reduce(\n            sorted_pairs.begin(), sorted_pairs.end(), 0.0, std::plus<double>(),\n            [&](const auto & p) {\n                return landscape.getQuality(s) * landscape.getQuality(p.first) *\n                       p.second;\n            });\n\n        int node_count = 0;\n        double contribution_sum = 0.0;\n        for(const auto & [t, p_st] : sorted_pairs) {\n            if(contribution_sum / contribution_max >= ratio_of_eca) break;\n            ++node_count;\n            contribution_sum +=\n                landscape.getQuality(s) * landscape.getQuality(t) * p_st;\n        }\n\n        average_sum += node_count / static_cast<double>(sorted_pairs.size());\n        ++cpt;\n    }\n    return average_sum / cpt;\n}\n\ntemplate <typename LS>\nDecoredLandscape<LS> decore_landscape(const LS & landscape,\n                                      const RestorationPlan<LS> & plan,\n                                      const Solution & solution) {\n    using Graph = typename LS::Graph;\n    const Graph & graph = landscape.getNetwork();\n    DecoredLandscape<LS> decored_landscape(landscape);\n\n    for(typename Graph::NodeIt u(graph); u != lemon::INVALID; ++u)\n        for(const auto & e : plan[u])\n            decored_landscape.getQualityRef(u) +=\n                solution[e.option] * e.quality_gain;\n    for(typename Graph::ArcIt a(graph); a != lemon::INVALID; ++a)\n        for(const auto & e : plan[a])\n            decored_landscape.getProbabilityRef(a) = std::max(\n                decored_landscape.getProbability(a),\n                landscape.getProbability(a) +\n                    solution[e.option] *\n                        (e.restored_probability - landscape.getProbability(a)));\n\n    return decored_landscape;\n}\n\ntemplate <typename LS>\nDecoredLandscape<LS> decore_landscape(const LS & landscape,\n                                      const RestorationPlan<LS> & plan) {\n    using Graph = typename LS::Graph;\n    const Graph & graph = landscape.getNetwork();\n    DecoredLandscape<LS> decored_landscape(landscape);\n\n    for(typename Graph::NodeIt u(graph); u != lemon::INVALID; ++u)\n        for(const auto & e : plan[u])\n            decored_landscape.getQualityRef(u) += e.quality_gain;\n    for(typename Graph::ArcIt a(graph); a != lemon::INVALID; ++a)\n        for(const auto & e : plan[a])\n            decored_landscape.getProbabilityRef(a) = std::max(\n                decored_landscape.getProbability(a), e.restored_probability);\n\n    return decored_landscape;\n}\n\nvoid printSolution(const MutableLandscape & landscape,\n                   const RestorationPlan<MutableLandscape> & plan,\n                   std::string name, concepts::Solver & solver, double B,\n                   const Solution & solution);\n\ntemplate <typename LS_From, typename LS_To>\nvoid copyPlan(\n    RestorationPlan<LS_To> & contracted_plan,\n    const RestorationPlan<LS_From> & plan,\n    const typename LS_From::Graph::template NodeMap<typename LS_To::Node> &\n        nodesRef,\n    const typename LS_From::Graph::template ArcMap<typename LS_To::Arc> &\n        arcsRef) {\n    assert(contracted_plan.getNbOptions() == 0);\n    for(const RestorationPlan<MutableLandscape>::Option i : plan.options())\n        contracted_plan.addOption(plan.getCost(i));\n\n    const typename LS_From::Graph & from_graph =\n        plan.getLandscape().getNetwork();\n\n    for(typename LS_From::Graph::NodeIt u(from_graph); u != lemon::INVALID; ++u)\n        for(const auto & e : plan[u])\n            contracted_plan.addNode(e.option, nodesRef[u], e.quality_gain);\n    for(typename LS_From::Graph::ArcIt a(from_graph); a != lemon::INVALID; ++a)\n        for(const auto & e : plan[a])\n            contracted_plan.addArc(e.option, arcsRef[a],\n                                   e.restored_probability);\n}\n\n// need to include the binary search tree for y-h , y+h search\nstd::pair<MutableLandscape::Node, MutableLandscape::Node> neerestNodes(\n    const MutableLandscape & landscape);\n\nvoid assert_well_formed(const MutableLandscape & landscape,\n                        const RestorationPlan<MutableLandscape> & plan);\n\n// template <typename GR>\n// class NodeIterator {\n// public:\n//     using Node = typename GR::Node;\n//     using NodeIt = typename GR::NodeIt;\n\n//     using difference_type = std::ptrdiff_t;\n//     using value_type = Node;\n//     using pointer = void;\n//     using reference = const Node&;\n//     using iterator_category = std::input_iterator_tag;\n\n// private:\n//     NodeIt it;\n// public:\n//     NodeIterator() : it(lemon::INVALID) {}\n//     NodeIterator(const GR & graph) : it(graph) {}\n//     NodeIterator(const NodeIterator<GR> & o) : it(o.it) {}\n\n//     NodeIterator& operator=(const NodeIterator<GR> & o) { it = o.it; return\n//     *this; }\n\n//     value_type operator*() const { return static_cast<value_type>(it); }\n//     NodeIterator operator++(int) const { return ++NodeIterator<GR>(*this); }\n//     NodeIterator& operator++() { ++it; return *this; }\n\n//     bool operator==(const NodeIterator<GR> & o) const { return o.it == it; }\n//     bool operator!=(const NodeIterator<GR> & o) const { return o.it != it; }\n// };\n\n// template <typename GR>\n// std::pair<NodeIterator<GR>, NodeIterator<GR>> nodesRange(const GR & graph) {\n//     return std::make_pair(NodeIterator(graph), NodeIterator<GR>());\n// }\n}  // namespace Helper\n\ntemplate <typename LS>\ndouble max_flow_in(const LS & landscape, const RestorationPlan<LS> & plan,\n                   typename LS::Node t) {\n    using Graph = typename LS::Graph;\n    using ProbabilityMap = typename LS::ProbabilityMap;\n    using Reversed = lemon::ReverseDigraph<const Graph>;\n\n    const Graph & original_g = landscape.getNetwork();\n    Reversed reversed_g(original_g);\n    ProbabilityMap probabilities(original_g);\n\n    for(typename Graph::ArcIt b(original_g); b != lemon::INVALID; ++b) {\n        probabilities[b] = landscape.getProbability(b);\n        for(auto const & e : plan[b])\n            probabilities[b] =\n                std::max(probabilities[b], e.restored_probability);\n    }\n\n    lemon::MultiplicativeSimplerDijkstra<Reversed, ProbabilityMap> dijkstra(\n        reversed_g, probabilities);\n    double sum = 0;\n    dijkstra.init(t);\n    while(!dijkstra.emptyQueue()) {\n        std::pair<typename Graph::Node, double> pair =\n            dijkstra.processNextNode();\n        typename Graph::Node v = pair.first;\n        const double p_tv = pair.second;\n        sum += landscape.getQuality(v) * p_tv;\n        for(auto const & e : plan[v]) sum += e.quality_gain * p_tv;\n    }\n    return sum;\n}\n\n#endif  // HELPER", "meta": {"hexsha": "bdee1ce6819cb4fea0ad459a700e84c02f7a8cd4", "size": 15307, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/helper.hpp", "max_stars_repo_name": "fhamonic/landscape_opt", "max_stars_repo_head_hexsha": "7f32749336590c8d8b5875300228196a05137267", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-23T11:56:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T11:56:09.000Z", "max_issues_repo_path": "include/helper.hpp", "max_issues_repo_name": "fhamonic/landscape_opt", "max_issues_repo_head_hexsha": "7f32749336590c8d8b5875300228196a05137267", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/helper.hpp", "max_forks_repo_name": "fhamonic/landscape_opt", "max_forks_repo_head_hexsha": "7f32749336590c8d8b5875300228196a05137267", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-27T16:58:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T16:58:19.000Z", "avg_line_length": 35.5150812065, "max_line_length": 80, "alphanum_fraction": 0.6243548703, "num_tokens": 3744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4156291315518877}}
{"text": "// Copyright (c) Dietmar Wolz.\r\n//\r\n// This source code is licensed under the MIT license found in the\r\n// LICENSE file in the root directory.\r\n\r\n// Eigen based implementation of differential evolution using on the DE/best/1 strategy.\r\n// Uses two deviations from the standard DE algorithm:\r\n// a) temporal locality introduced in \r\n// https://www.researchgate.net/publication/309179699_Differential_evolution_for_protein_folding_optimization_based_on_a_three-dimensional_AB_off-lattice_model\r\n// b) reinitialization of individuals based on their age. \r\n// requires https://github.com/imneme/pcg-cpp\r\n\r\n#include <Eigen/Core>\r\n#include <iostream>\r\n#include <float.h>\r\n#include <stdint.h>\r\n#include <ctime>\r\n#include <random>\r\n#include <queue>\r\n#include <tuple>\r\n#include \"pcg_random.hpp\"\r\n#include \"evaluator.h\"\r\n\r\nusing namespace std;\r\n\r\nnamespace differential_evolution {\r\n\r\nclass DeOptimizer {\r\n\r\npublic:\r\n\r\n    DeOptimizer(long runid_, Fitness *fitfun_, int dim_, int seed_,\r\n            int popsize_, int maxEvaluations_, double keep_,\r\n            double stopfitness_, double F_, double CR_) {\r\n        // runid used to identify a specific run\r\n        runid = runid_;\r\n        // fitness function to minimize\r\n        fitfun = fitfun_;\r\n        // Number of objective variables/problem dimension\r\n        dim = dim_;\r\n        // Population size\r\n        popsize = popsize_ > 0 ? popsize_ : 15 * dim;\r\n        // maximal number of evaluations allowed.\r\n        maxEvaluations = maxEvaluations_ > 0 ? maxEvaluations_ : 50000;\r\n        // keep best young after each iteration.\r\n        keep = keep_ > 0 ? keep_ : 30;\r\n        // Limit for fitness value.\r\n        stopfitness = stopfitness_;\r\n        F = F0 = F_ > 0 ? F_ : 0.5;\r\n        CR = CR0 = CR_ > 0 ? CR_ : 0.9;\r\n        // Number of iterations already performed.\r\n        iterations = 0;\r\n        bestY = DBL_MAX;\r\n        // stop criteria\r\n        stop = 0;\r\n        pos = 0;\r\n        //std::random_device rd;\r\n        rs = new pcg64(seed_);\r\n        init();\r\n    }\r\n\r\n    ~DeOptimizer() {\r\n        delete rs;\r\n    }\r\n\r\n    double rnd01() {\r\n        return distr_01(*rs);\r\n    }\r\n\r\n    int rndInt(int max) {\r\n        return (int) (max * distr_01(*rs));\r\n    }\r\n\r\n    vec nextX(int p, const vec &xp, const vec &xb) {\r\n        if (p == 0) {\r\n            iterations++;\r\n            CR = iterations % 2 == 0 ? 0.5 * CR0 : CR0;\r\n            F = iterations % 2 == 0 ? 0.5 * F0 : F0;\r\n        }\r\n        int r1, r2;\r\n        do {\r\n            r1 = rndInt(popsize);\r\n        } while (r1 == p || r1 == bestI);\r\n        do {\r\n            r2 = rndInt(popsize);\r\n        } while (r2 == p || r2 == bestI || r2 == r1);\r\n        vec x1 = popX.col(r1);\r\n        vec x2 = popX.col(r2);\r\n        vec x = xb + (x1 - x2) * F;\r\n        int r = rndInt(dim);\r\n        for (int j = 0; j < dim; j++)\r\n            if (j != r && rnd01() > CR)\r\n                x[j] = xp[j];\r\n        return fitfun->getClosestFeasible(x);\r\n    }\r\n\r\n    vec next_improve(const vec &xb, const vec &x, const vec &xi) {\r\n        return fitfun->getClosestFeasible(xb + ((x - xi) * 0.5));\r\n    }\r\n\r\n    vec ask(int &p) {\r\n        // ask for one new argument vector.\r\n        if (improvesX.empty()) {\r\n            p = pos;\r\n            vec x = nextX(p, popX.col(p), popX.col(bestI));\r\n            pos = (pos + 1) % popsize;\r\n            return x;\r\n        } else {\r\n            p = improvesP.front();\r\n            vec x = improvesX.front();\r\n            improvesP.pop();\r\n            improvesX.pop();\r\n            return x;\r\n        }\r\n    }\r\n\r\n    int tell(double y, const vec &x, int p) {\r\n        //tell function value for a argument list retrieved by ask_one().\r\n        if (isfinite(y) && y < popY[p]) {\r\n            if (iterations > 1) {\r\n                // temporal locality\r\n                improvesP.push(p);\r\n                improvesX.push(next_improve(popX.col(bestI), x, popX0.col(p)));\r\n            }\r\n            popX0.col(p) = popX.col(p);\r\n            popX.col(p) = x;\r\n            popY[p] = y;\r\n            popIter[p] = iterations;\r\n            if (y < popY[bestI]) {\r\n                bestI = p;\r\n                if (y < bestY) {\r\n                    bestY = y;\r\n                    bestX = x;\r\n                    if (isfinite(stopfitness) && bestY < stopfitness)\r\n                        stop = 1;\r\n                }\r\n            }\r\n        } else {\r\n            // reinitialize individual\r\n            if (keep * rnd01() < iterations - popIter[p]) {\r\n                popX.col(p) = fitfun->sample(*rs);\r\n                popY[p] = DBL_MAX;\r\n            }\r\n        }\r\n        return stop;\r\n    }\r\n\r\n    void doOptimize() {\r\n\r\n        // -------------------- Generation Loop --------------------------------\r\n        for (iterations = 1; fitfun->evaluations() < maxEvaluations;\r\n                iterations++) {\r\n\r\n            CR = iterations % 2 == 0 ? 0.5 * CR0 : CR0;\r\n            F = iterations % 2 == 0 ? 0.5 * F0 : F0;\r\n\r\n            for (int p = 0; p < popsize; p++) {\r\n                vec xp = popX.col(p);\r\n                vec xb = popX.col(bestI);\r\n                int r1, r2;\r\n                do {\r\n                    r1 = rndInt(popsize);\r\n                } while (r1 == p || r1 == bestI);\r\n                do {\r\n                    r2 = rndInt(popsize);\r\n                } while (r2 == p || r2 == bestI || r2 == r1);\r\n                vec x1 = popX.col(r1);\r\n                vec x2 = popX.col(r2);\r\n                int r = rndInt(dim);\r\n                vec x = vec(xp);\r\n                for (int j = 0; j < dim; j++) {\r\n                    if (j == r || rnd01() < CR) {\r\n                        x[j] = xb[j] + F * (x1[j] - x2[j]);\r\n                        if (!fitfun->feasible(j, x[j]))\r\n                            x[j] = fitfun->sample_i(j, *rs);\r\n                    }\r\n                }\r\n\r\n                double y = fitfun->eval(x);\r\n                if (isfinite(y) && y < popY[p]) {\r\n                    // temporal locality\r\n                    vec x2 = next_improve(xb, x, xp);\r\n                    double y2 = fitfun->eval(x2);\r\n                    if (isfinite(y2) && y2 < y) {\r\n                        y = y2;\r\n                        x = x2;\r\n                    }\r\n                    popX.col(p) = x;\r\n                    popY(p) = y;\r\n                    popIter[p] = iterations;\r\n                    if (y < popY[bestI]) {\r\n                        bestI = p;\r\n                        if (y < bestY) {\r\n                            bestY = y;\r\n                            bestX = x;\r\n                            if (isfinite(stopfitness) && bestY < stopfitness) {\r\n                                stop = 1;\r\n                                return;\r\n                            }\r\n                        }\r\n                    }\r\n                } else {\r\n                    // reinitialize individual\r\n                    if (keep * rnd01() < iterations - popIter[p]) {\r\n                        popX.col(p) = fitfun->sample(*rs);\r\n                        popY[p] = DBL_MAX;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    void do_optimize_delayed_update(int workers) {\r\n    \t iterations = 0;\r\n    \t fitfun->resetEvaluations();\r\n         workers = std::min(workers, popsize); // workers <= popsize\r\n    \t evaluator eval(fitfun, 1, workers);\r\n         int evals_size = popsize*10;\r\n    \t vec evals_x[evals_size];\r\n   \t     int evals_p[evals_size];\r\n         int cp = 0; \r\n         \r\n\t     // fill eval queue with initial population\r\n    \t for (int i = 0; i < workers; i++) {\r\n    \t\t int p;\r\n    \t\t vec x = ask(p);\r\n    \t\t eval.evaluate(x, cp);\r\n    \t\t evals_x[cp] = x;\r\n    \t\t evals_p[cp] = p;\r\n             cp = (cp + 1) % evals_size;             \r\n    \t }\r\n    \t while (fitfun->evaluations() < maxEvaluations) {\r\n    \t\t vec_id* vid = eval.result();\r\n    \t\t vec y = vec(vid->_v);\r\n    \t\t int id = vid->_id;\r\n    \t\t delete vid;\r\n    \t\t vec x = evals_x[id];\r\n             int p = evals_p[id];\r\n    \t\t tell(y(0), x, p); // tell evaluated x\r\n    \t\t if (fitfun->evaluations() >= maxEvaluations)\r\n    \t\t\t break;\r\n    \t\t x = ask(p);\r\n    \t\t eval.evaluate(x, cp);\r\n    \t\t evals_x[cp] = x;\r\n    \t\t evals_p[cp] = p;\r\n             cp = (cp + 1) % evals_size; \r\n    \t }\r\n\t}\r\n\r\n    void init() {\r\n        popX = mat(dim, popsize);\r\n        popX0 = mat(dim, popsize);\r\n        popY = vec(popsize);\r\n        for (int p = 0; p < popsize; p++) {\r\n            popX0.col(p) = popX.col(p) = fitfun->sample(*rs);\r\n            popY[p] = DBL_MAX; // compute fitness\r\n        }\r\n        bestI = 0;\r\n        bestX = popX.col(bestI);\r\n        popIter = zeros(popsize);\r\n    }\r\n\r\n    vec getBestX() {\r\n        return bestX;\r\n    }\r\n\r\n    double getBestValue() {\r\n        return bestY;\r\n    }\r\n\r\n    mat getX() {\r\n        return popX;\r\n    }\r\n\r\n    mat getY() {\r\n        return popY;\r\n    }\r\n\r\n    double getIterations() {\r\n        return iterations;\r\n    }\r\n\r\n    double getStop() {\r\n        return stop;\r\n    }\r\n\r\n    Fitness* getFitfun() {\r\n        return fitfun;\r\n    }\r\n\r\n    int getDim() {\r\n        return dim;\r\n    }\r\n\r\nprivate:\r\n    long runid;\r\n    Fitness *fitfun;\r\n    int popsize; // population size\r\n    int dim;\r\n    int maxEvaluations;\r\n    double keep;\r\n    double stopfitness;\r\n    int iterations;\r\n    double bestY;\r\n    vec bestX;\r\n    int bestI;\r\n    int stop;\r\n    double F0;\r\n    double CR0;\r\n    double F;\r\n    double CR;\r\n    pcg64 *rs;\r\n    mat popX;\r\n    mat popX0;\r\n    vec popY;\r\n    vec popIter;\r\n    queue<vec> improvesX;\r\n    queue<int> improvesP;\r\n    int pos;\r\n};\r\n\r\n// see https://cvstuff.wordpress.com/2014/11/27/wraping-c-code-with-python-ctypes-memory-and-pointers/\r\n\r\n}\r\n\r\nusing namespace differential_evolution;\r\n\r\n/*\r\n * Class:     fcmaes_core_Jni\r\n * Method:    optimizeDE\r\n * Signature: (Lfcmaes/core/Fitness;[D[D[DIDIDDDJII)I\r\n */\r\nJNIEXPORT jint JNICALL Java_fcmaes_core_Jni_optimizeDE(JNIEnv *env, jclass cls,\r\n        jobject func, jdoubleArray jlower, jdoubleArray jupper,\r\n        jdoubleArray jresult, jint maxEvals, jdouble stopfitness, jint popsize,\r\n        jdouble keep, jdouble F, jdouble CR, jlong seed, jint runid, jint workers) {\r\n\r\n    double *result = env->GetDoubleArrayElements(jresult, JNI_FALSE);\r\n    double *lower = env->GetDoubleArrayElements(jlower, JNI_FALSE);\r\n    double *upper = env->GetDoubleArrayElements(jupper, JNI_FALSE);\r\n    int dim = env->GetArrayLength(jlower);\r\n    vec lower_limit(dim), upper_limit(dim);\r\n    for (int i = 0; i < dim; i++) {\r\n        lower_limit[i] = lower[i];\r\n        upper_limit[i] = upper[i];\r\n    }\r\n    CallJava callJava(func, env);\r\n    Fitness fitfun(&callJava, dim, 1, lower_limit, upper_limit);\r\n\r\n    DeOptimizer opt(runid, &fitfun, dim, seed, popsize, maxEvals, keep,\r\n            stopfitness, F, CR);\r\n    try {\r\n        if (workers <= 1)\r\n            opt.doOptimize();\r\n        else\r\n            opt.do_optimize_delayed_update(workers);\r\n        vec bestX = opt.getBestX();\r\n        double bestY = opt.getBestValue();\r\n\r\n        for (int i = 0; i < dim; i++)\r\n            result[i] = bestX[i];\r\n\r\n        env->SetDoubleArrayRegion(jresult, 0, dim, (jdouble*) result);\r\n        env->ReleaseDoubleArrayElements(jresult, result, 0);\r\n        env->ReleaseDoubleArrayElements(jupper, upper, 0);\r\n        env->ReleaseDoubleArrayElements(jlower, lower, 0);\r\n        return fitfun.evaluations();\r\n\r\n    } catch (std::exception &e) {\r\n        cout << e.what() << endl;\r\n        return fitfun.evaluations();\r\n    }\r\n    return 0;\r\n}\r\n\r\n/*\r\n * Class:     fcmaes_core_Jni\r\n * Method:    initDE\r\n * Signature: (Lfcmaes/core/Fitness;[D[DIDDDJI)J\r\n */\r\nJNIEXPORT jlong JNICALL Java_fcmaes_core_Jni_initDE(JNIEnv *env, jclass cls,\r\n        jobject func, jdoubleArray jlower, jdoubleArray jupper, \r\n        jint popsize, jdouble keep, jdouble F, jdouble CR, jlong seed,\r\n        jint runid) {\r\n    double *lower = env->GetDoubleArrayElements(jlower, JNI_FALSE);\r\n    double *upper = env->GetDoubleArrayElements(jupper, JNI_FALSE);\r\n    int dim = env->GetArrayLength(jlower);\r\n    vec lower_limit(dim), upper_limit(dim);\r\n    for (int i = 0; i < dim; i++) {\r\n        lower_limit[i] = lower[i];\r\n        upper_limit[i] = upper[i];\r\n    }\r\n    CallJava* callJava = new CallJava(func, env);\r\n    Fitness* fitfun = new Fitness(callJava, dim, 1, lower_limit, upper_limit);     \r\n    DeOptimizer *opt = new DeOptimizer(runid, fitfun, dim, seed, popsize,\r\n            INT_MAX, keep, -DBL_MAX, F, CR);\r\n    env->ReleaseDoubleArrayElements(jupper, upper, 0);\r\n    env->ReleaseDoubleArrayElements(jlower, lower, 0);\r\n    return (intptr_t) opt;\r\n}\r\n\r\n/*\r\n * Class:     fcmaes_core_Jni\r\n * Method:    destroyDE\r\n * Signature: (J)V\r\n */\r\nJNIEXPORT void JNICALL Java_fcmaes_core_Jni_destroyDE(JNIEnv *env, jclass cls, intptr_t ptr) {\r\n    DeOptimizer* opt = (DeOptimizer*)ptr;\r\n    Fitness* fitfun = opt->getFitfun();\r\n    delete fitfun->getFunc();    \r\n    delete fitfun;\r\n    delete opt;\r\n}\r\n\r\n/*\r\n * Class:     fcmaes_core_Jni\r\n * Method:    askDE\r\n * Signature: (J)[D\r\n */\r\nJNIEXPORT jdoubleArray JNICALL Java_fcmaes_core_Jni_askDE(JNIEnv *env,\r\n        jclass cls, intptr_t ptr) {\r\n    DeOptimizer *opt = (DeOptimizer*) ptr;\r\n    int dim = opt->getDim();\r\n    jdoubleArray jx = env->NewDoubleArray(dim + 1);\r\n    double x[dim + 1];\r\n    int p;\r\n    vec args = opt->ask(p);\r\n    for (int i = 0; i < dim; i++)\r\n        x[i] = args[i];\r\n    x[dim] = p;\r\n    env->SetDoubleArrayRegion(jx, 0, dim + 1, x);\r\n    return jx;\r\n}\r\n\r\n/*\r\n * Class:     fcmaes_core_Jni\r\n * Method:    tellDE\r\n * Signature: (J[DDI)I\r\n */\r\nJNIEXPORT jint JNICALL Java_fcmaes_core_Jni_tellDE(JNIEnv *env, jclass cls,\r\n\t\tintptr_t ptr, jdoubleArray jx, jdouble y, jint p) {\r\n    DeOptimizer *opt = (DeOptimizer*) ptr;\r\n    int dim = opt->getDim();\r\n    double *x = env->GetDoubleArrayElements(jx, JNI_FALSE);\r\n    vec args(dim);\r\n    for (int i = 0; i < dim; i++)\r\n        args[i] = x[i];\r\n    opt->tell(y, args, p);\r\n    env->ReleaseDoubleArrayElements(jx, x, 0);\r\n    return opt->getStop();\r\n}\r\n\r\n/*\r\n * Class:     fcmaes_core_Jni\r\n * Method:    populationDE\r\n * Signature: (J)[D\r\n */\r\nJNIEXPORT jdoubleArray JNICALL Java_fcmaes_core_Jni_populationDE(JNIEnv *env,\r\n        jclass cls, intptr_t ptr) {\r\n    DeOptimizer *opt = (DeOptimizer*) ptr;\r\n    int size = opt->getX().size();\r\n    double* xdata = opt->getX().data();\r\n    jdoubleArray jres = env->NewDoubleArray(size);\r\n    env->SetDoubleArrayRegion(jres, 0, size, (jdouble*) xdata);\r\n    return jres;\r\n}\r\n\r\n", "meta": {"hexsha": "334b44f3fc477d02b2a04fc2e3e3d99047fdc0f0", "size": 14476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppsrc/deoptimizer.cpp", "max_stars_repo_name": "dietmarwo/fcmaes-java", "max_stars_repo_head_hexsha": "ec1704199783e93628f6fde42295c9b79cb48dde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-11-08T14:14:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T12:41:38.000Z", "max_issues_repo_path": "cppsrc/deoptimizer.cpp", "max_issues_repo_name": "dietmarwo/fcmaes-java", "max_issues_repo_head_hexsha": "ec1704199783e93628f6fde42295c9b79cb48dde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppsrc/deoptimizer.cpp", "max_forks_repo_name": "dietmarwo/fcmaes-java", "max_forks_repo_head_hexsha": "ec1704199783e93628f6fde42295c9b79cb48dde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-08T14:27:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-08T14:27:15.000Z", "avg_line_length": 30.9316239316, "max_line_length": 160, "alphanum_fraction": 0.5013125173, "num_tokens": 3796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5888891307678319, "lm_q1q2_score": 0.4156291315518876}}
{"text": "#include \"NTtimescales.h\"\n#include \"write.h\"\n#include \"messages.h\"\n#include \"globalVariables.h\"\n#include \"adafFunctions.h\"\n\n#include <flosses/nonThermalLosses.h>\n#include <flosses/lossesSyn.h>\n#include <flosses/lossesIC.h>\n#include <flosses/lossesBrem.h>\n#include <flosses/lossesHadronics.h>\n#include <flosses/lossesPhotoHadronic.h>\n#include <fparameters/SpaceIterator.h>\n#include <fparameters/Dimension.h>\n#include <fparameters/parameters.h>\n\n#include <boost/property_tree/ptree.hpp>\n\nvoid nonThermalTimescales(Particle& p, State& st, const std::string& filename)\n{\n\tif (p.id == \"ntElectron\")\n\t\tshow_message(msgStart, Module_electronRadLosses);\n\telse if (p.id == \"ntProton\")\n\t\tshow_message(msgStart, Module_protonRadLosses);\n\n\tstd::ofstream file,file2;\n\tfile.open(filename.c_str(), std::ios::out);\n\tif (p.id == \"ntProton\") file2.open(\"diffusion_adv.dat\", std::ios::out);\n\n\tfile << \"r [2M]\" \n\t\t<< \"\\t\" << \"Log(gamma)\"\n\t\t<< \"\\t\" << \"Acc\"\n\t\t<< \"\\t\" << \"Acc_SDA\"\n\t\t<< \"\\t\" << \"Adv\"\n\t\t<< \"\\t\" << \"Diff_K\"\n\t\t<< \"\\t\" << \"Diff_B\"\n\t\t<< \"\\t\" << \"Diff_|_\"\n\t\t<< \"\\t\" << \"Diff_||\"\n        << \"\\t\" << \"EmaxHillas\"\n\t\t<< \"\\t\" << \"Sy\"\n\t\t<< \"\\t\" << \"IC/pp\"\n\t\t<< \"\\t\" << \"pg/Bremss\"\n\t\t<< \"\\t\" << \"Relax\"\n\t\t\n\t\t<< std::endl;\n\t\n\tif (p.id == \"ntProton\") {\n\t\tfile2   << \"r [2M]\"\n\t\t\t\t<< \"\\t\" << \"Log(gamma)\"\n\t\t\t\t<< \"\\t\" << \"Diff_length\"\n\t\t\t\t<< \"\\t\" << \"dR\"\n\t\t\t\t<< \"\\t\" << \"Dlenght/dR\"\n\t\t\t\t<< std::endl;\n\t}\n\t\n\tint flag1, flag2, flag3, flag4, flag5, flag6, flag7;\n\tflag1 = flag2 = flag3 = flag4 = flag5 = flag6 = flag7 = 0;\n\tdouble logr1,logr2,logr3,logr4,logr5,logr6,logr7;\n\tlogr1 = log10(1.5);\n\tdouble aux = log10(st.denf_e.ps[DIM_R].last()/schwRadius)/7.0;\n\tlogr2 = logr1+aux;\n\tlogr3 = logr2+aux;\n\tlogr4 = logr3+aux;\n\tlogr5 = logr4+aux;\n\tlogr6 = logr5+aux;\n\tlogr7 = logr6+aux;\n\tp.ps.iterate([&](const SpaceIterator& iR) {\n\t\tdouble r = iR.val(DIM_R);\n\t\tdouble logr = log10(r/schwRadius);\n\t\tif (logr > logr1) flag1++;\n\t\tif (logr > logr2) flag2++;\n\t\tif (logr > logr3) flag3++;\n\t\tif (logr > logr4) flag4++;\n\t\tif (logr > logr5) flag5++;\n\t\tif (logr > logr6) flag6++;\n\t\tif (logr > 0.9*logr7) flag7++;\n\t\t\n\t\tif (flag1 == 1 || flag2 == 1 || flag3 == 1 || flag4 == 1 || flag5 == 1\n\t\t\t\t|| flag6 == 1 || flag7 == 1) {\n\t\t\tdouble tAdv = accretionTime(r);\n\t\t\tdouble vR = radialVel(r);\n\t\t\tdouble dR = r * (sqrt(paso_r)-1.0/sqrt(paso_r));\n\t\t\tdouble tCell = dR / abs(vR);\n\t\t\tdouble B = st.magf.get(iR);\n\t\t\tdouble height = height_fun(r);\n\t\t\tdouble rho = massDensityADAF(r);\n\t\t\tdouble eMaxHillas = electronCharge*B*height;\n\t\t\tp.ps.iterate([&](const SpaceIterator& iRE) {\n\t\t\t\tdouble E = iRE.val(DIM_E);\n\t\t\t\tdouble tAcc = 1.0/accelerationRate(E,B);\n\t\t\t\tdouble tAccSDA = accelerationTimeSDA(E,p,B,height,rho);\n\t\t\t\tdouble tDiffKol = diffusionTimeTurbulence(E,height,p,B);\n\t\t\t\tdouble tDiffBohm = height*height/BohmDiffusionCoeff(E,B);\n\t\t\t\tdouble tDiffParallel = diffusionTimeParallel(E,height,B);\n\t\t\t\tdouble tDiffPerpend = diffusionTimePerpendicular(E,height,B);\n\n\t\t\t\tfile << (int)(r/schwRadius)\t\t\t\t\t\t\t\t\t\t\t\t// 0\n\t\t\t\t\t << \"\\t\" << safeLog10(E/(p.mass*cLight2))\t\t\t\t\t\t\t// 1\n\t\t\t\t\t << \"\\t\" << safeLog10(tAcc)\t\t\t\t\t\t\t\t\t\t\t// 2\n\t\t\t\t\t << \"\\t\" << safeLog10(tAccSDA)\t\t\t\t\t\t\t\t\t\t// 3\n\t\t\t\t\t << \"\\t\" << safeLog10(tAdv)\t\t\t\t\t\t\t\t\t\t\t// 4\n\t\t\t\t\t << \"\\t\" << safeLog10(tDiffKol)\t\t\t\t\t\t\t\t\t\t// 5\n\t\t\t\t\t << \"\\t\" << safeLog10(tDiffBohm)\t\t\t\t\t\t\t\t\t// 6\n\t\t\t\t\t << \"\\t\" << safeLog10(tDiffParallel)\t\t\t\t\t\t\t\t// 7\n\t\t\t\t\t << \"\\t\" << safeLog10(tDiffPerpend)\t\t\t\t\t\t\t\t\t// 8\n\t\t\t\t\t << \"\\t\" << safeLog10(eMaxHillas/1.602e-12/(p.mass*cLight2));\t\t// 9\n\t\t\t\tif (p.id == \"ntProton\") {\n\t\t\t\t\tdouble diff_length = diffLength(E/(p.mass*cLight2),p,r,height,B,vR);\n\t\t\t\t\tfile2   << (int)(r/schwRadius)\n\t\t\t\t\t\t\t<< \"\\t\" << safeLog10(E/(p.mass*cLight2))\n\t\t\t\t\t\t\t<< \"\\t\" << safeLog10(diff_length/schwRadius)\n\t\t\t\t\t\t\t<< \"\\t\" << safeLog10(dR/schwRadius)\n\t\t\t\t\t\t\t<< \"\\t\" << diff_length/dR << std::endl;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (p.id == \"ntElectron\") {\n\t\t\t\t\tdouble tSyn = E/lossesSyn(E,B,p);\n\t\t\t\t\tdouble tIC = E/lossesIC(E,p,st.photon.distribution,iR.coord,st.photon.emin(),\n\t\t\t\t\t\t\t\t\t\t\tst.photon.emax());\n\t\t\t\t\tdouble tBrem = E/lossesBremss(E,st.denf_e.get(iR)+st.denf_i.get(iR),p);  \n\t\t\t\t\tfile << \"\\t\" << safeLog10(tSyn)\t\t// 10\n\t\t\t\t\t\t << \"\\t\" << safeLog10(tIC)\t\t// 11\n\t\t\t\t\t\t << \"\\t\" << safeLog10(tBrem)\t// 12\n\t\t\t\t\t\t << \"\\t\" << safeLog10(relaxTime_e(E,st.tempElectrons.get(iR),st.denf_e.get(iR)))\t// 13\n\t\t\t\t\t\t << std::endl;\n\t\t\t\t} else if(p.id == \"ntProton\") {\n\t\t\t\t\tdouble tAdi = 2.0*r/(-radialVel(r)) / (E/p.mass/cLight2);\n\t\t\t\t\tdouble tSyn = E/lossesSyn(E,B,p);\n\t\t\t\t\tdouble tIC_Th = E/lossesIC_Th(E,p,st.photon.distribution,iR.coord,st.photon.emin(),\n\t\t\t\t\t\t\t\t\t\t\tst.photon.emax());\n\t\t\t\t\tdouble tPP = E/lossesHadronics(E,st.denf_i.get(iR),p);\n\t\t\t\t\tdouble tPG = E/lossesPhotoMeson(E,p,st.photon.distribution,iR,st.photon.emin(),\n\t\t\t\t\t\t\t\t\tst.photon.emax());\n\t\t\t\t\tdouble tBH = E/lossesPhotoPair(E,p,st.photon.distribution,iR,st.photon.emin(),\n\t\t\t\t\t\t\t\t\tst.photon.emax());\n\t\t\t\t\tfile << \"\\t\" << safeLog10(tSyn)\t\t\t\t// 10\n\t\t\t\t\t\t << \"\\t\" << safeLog10(tIC_Th)\t\t\t// 11\n\t\t\t\t\t\t << \"\\t\" << safeLog10(tPP)\t\t\t\t// 12\n\t\t\t\t\t\t << \"\\t\" << safeLog10(tPG)\t\t\t\t// 13\n\t\t\t\t\t\t << \"\\t\" << safeLog10(tBH)\t\t\t\t// 14\n\t\t\t\t\t\t << \"\\t\" << safeLog10(tAdi)\t\t\t\t// 15\n\t\t\t\t\t\t << \"\\t\" << safeLog10(relaxTime_p(E, st.tempIons.get(iR), st.denf_i.get(iR)))\t\t// 16\n\t\t\t\t\t\t << std::endl;\n\t\t\t\t}\n\t\t\t},{-1, iR.coord[DIM_R], 0});\n\t\t}\n\t},{0,-1,0});\n\tfile.close();\n\n\tif (p.id == \"ntElectron\") {\n\t\tshow_message(msgEnd, Module_electronRadLosses);\n\t}\n\telse if (p.id == \"ntProton\") {\n\t\tfile2.close();\n\t\tshow_message(msgEnd, Module_protonRadLosses);\n\t}\n}\n\nusing namespace std;\n\nvoid secondariesTimescales(Particle& p, State& st, const std::string& filename)\n{\n\tofstream file;\n\tfile.open(filename.c_str(), ios::out);\n\n\tfile << \"r [M]\" \n\t\t<< \"\\t\" << \"Log(gamma)\"\n\t\t<< \"\\t\" << \"Adv\"\n\t\t<< \"\\t\" << \"Diff\"\n\t\t<< \"\\t\" << \"Decay\"\n\t\t<< \"\\t\" << \"Sy\"\n\t\t<< \"\\t\" << \"IC/pp\"\n\t\t<< \"\\t\" << \"pg/Bremss\"\n\t\t<< endl;\n\n\tint flag1,flag2,flag3,flag4,flag5;\n\tflag1 = flag2 = flag3 = flag4 = flag5 = 0;\n\tdouble logr1,logr2,logr3,logr4,logr5;\n\tlogr1 = log10(1.5);\n\tdouble aux = log10(st.denf_e.ps[DIM_R].last()/schwRadius)/4.0;\n\tlogr2 = logr1+aux;\n\tlogr3 = logr2+aux;\n\tlogr4 = logr3+aux;\n\tlogr5 = logr4+aux;\n\tp.ps.iterate([&](const SpaceIterator& iR) {\n\t\tdouble r = iR.val(DIM_R);\n\t\tdouble logr = log10(r/schwRadius);\n\t\tif (logr > logr1) flag1++;\n\t\tif (logr > logr2) flag2++;\n\t\tif (logr > logr3) flag3++;\n\t\tif (logr > logr4) flag4++;\n\t\tif (logr > 0.9*logr5) flag5++;\n\t\t\n\t\tif (flag1 == 1 || flag2 == 1 || flag3 == 1 || flag4 == 1 || flag5 == 1) {\n\t\t\tdouble tAdv = accretionTime(r);\n\t\t\tdouble B = st.magf.get(iR);\n\t\t\tdouble height = height_fun(r);\n\t\t\tp.ps.iterate([&](const SpaceIterator& iRE) {\n\t\t\t\tdouble E = iRE.val(DIM_E);\n\t\t\t\tdouble tAcc = 1.0/accelerationRate(E,B);\n\t\t\t\tdouble tDiff = diffusionTimeTurbulence(E,height,p,B);\n\t\t\t\tdouble tSyn = E/lossesSyn(E,B,p);\n\t\t\t\t\n\t\t\t\tfile << \"\\t\" << (int)(r/schwRadius)\n\t\t\t\t\t << \"\\t\" << safeLog10(E/(p.mass*cLight2))\n\t\t\t\t\t << \"\\t\" << safeLog10(tAdv)\n\t\t\t\t\t << \"\\t\" << safeLog10(tDiff)\n\t\t\t\t\t << \"\\t\" << safeLog10(tSyn);\n\t\t\t\t\n\t\t\t\tdouble tDecay(0.0),tPP(1.0e30),tPG(0.0),tBH(0.0);\n\t\t\t\tif (p.id == \"ntMuon\") {\n\t\t\t\t\ttDecay = muonMeanLife*(E/(p.mass*cLight2));\n\t\t\t\t\tfile << \"\\t\" << safeLog10(tDecay) << endl;\n\t\t\t\t} else if (p.id == \"ntChargedPion\") {\n\t\t\t\t\ttDecay = chargedPionMeanLife*(E/(p.mass*cLight2));\n\t\t\t\t\ttPP = E/lossesHadronics(E,st.denf_i.get(iR),p);\n\t\t\t\t\ttPG = E/lossesPhotoMeson(E,p,st.photon.distribution,iR,st.photon.emin(),\n\t\t\t\t\t\t\t\t\tst.photon.emax());\n\t\t\t\t\ttBH = E/lossesPhotoPair(E,p,st.photon.distribution,iR,st.photon.emin(),\n\t\t\t\t\t\t\t\t\tst.photon.emax());\n\t\t\t\t\tfile << \"\\t\" << safeLog10(tDecay)\n\t\t\t\t\t\t << \"\\t\" << safeLog10(tPP)\n\t\t\t\t\t\t << \"\\t\" << safeLog10(tPG)\n\t\t\t\t\t\t << \"\\t\" << safeLog10(tBH) << endl;\n\t\t\t\t}\n\t\t\t},{-1,iR.coord[DIM_R],0});\n\t\t}\n\t},{0,-1,0});\n\tfile.close();\n}\n\n\n\n\nvoid radiativeLossesNeutron(Particle& n, State& st, const std::string& filename)\n{\n\tstd::ofstream file;\n\tfile.open(filename.c_str(), std::ios::out);\n\n\tfile << \"r [Rs]\" \n\t\t<< \"\\t\" << \"E [GeV]\"\n\t\t<< \"\\t\" << \"Escape\"\n\t\t<< \"\\t\" << \"Decay\"\n\t\t<< \"\\t\" << \"pp\"\n\t\t<< \"\\t\" << \"pg\"\n\t\t<< std::endl;\n\t\n\tdouble phEmin = st.photon.emin();\n\tdouble phEmax = st.photon.emax();\n\t\n\tint flag1,flag2,flag3,flag4,flag5;\n\tflag1 = flag2 = flag3 = flag4 = flag5 = 0;\n\tdouble logr1,logr2,logr3,logr4,logr5;\n\tlogr1 = log10(1.5);\n\tdouble aux = log10(st.denf_e.ps[DIM_R].last()/schwRadius)/4.0;\n\tlogr2 = logr1+aux;\n\tlogr3 = logr2+aux;\n\tlogr4 = logr3+aux;\n\tlogr5 = logr4+aux;\n\tn.ps.iterate([&](const SpaceIterator& iR) {\n\t\tdouble r = iR.val(DIM_R);\n\t\tdouble logr = log10(r/schwRadius);\n\t\tif (logr > logr1) flag1++;\n\t\tif (logr > logr2) flag2++;\n\t\tif (logr > logr3) flag3++;\n\t\tif (logr > logr4) flag4++;\n\t\tif (logr > 0.9*logr5) flag5++;\n\t\t\n\t\tif (flag1 == 1 || flag2 == 1 || flag3 == 1 || flag4 == 1 || flag5 == 1) {\n\t\t\tn.ps.iterate([&](const SpaceIterator& iRE) {\n\t\t\t\tdouble En = iRE.val(DIM_E);\n\t\t\t\tdouble gamma_n = En / (n.mass*cLight2);\n\t\t\t\tdouble tEscape = height_fun(r) / cLight;\n\t\t\t\tdouble tDecay = gamma_n*neutronMeanLife;\n\t\t\t\tdouble loss_np = lossesHadronics(En,st.denf_i.get(iR),n);\n\t\t\t\tdouble loss_ng = lossesPhotoMeson(En,n,st.photon.distribution,iR,phEmin,phEmax);\n\t\t\t\tdouble tNP = (loss_np > 0.0) ? En / loss_np : 1e30;\n\t\t\t\tdouble tNG = (loss_ng > 0.0) ? En / loss_ng : 1e30;\n\n\t\t\t\tfile << r/schwRadius << \"\\t\" << En / (EV_TO_ERG*1e9)\n\t\t\t\t\t\t << \"\\t\" << tEscape\n\t\t\t\t\t\t << \"\\t\" << tDecay\n\t\t\t\t\t\t << \"\\t\" << tNP\n\t\t\t\t\t\t << \"\\t\" << tNG << endl;\n\t\t\t},{-1,iR.coord[DIM_R],0});\n\t\t}\n\t},{0,-1,0});\n\tfile.close();\n}\n\n", "meta": {"hexsha": "df9c7730c11040e68c9d6e96dff7bcd84f42e3e0", "size": 9391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adaf/NTtimescales.cpp", "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_issues_repo_path": "src/adaf/NTtimescales.cpp", "max_issues_repo_name": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/adaf/NTtimescales.cpp", "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2714776632, "max_line_length": 92, "alphanum_fraction": 0.571611117, "num_tokens": 3528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428946, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.41548913874871674}}
{"text": "#ifndef FIBER_HPP\n#define FIBER_HPP\n\n#include <skelly_sim.hpp>\n\n#include <Eigen/LU>\n#include <list>\n#include <unordered_map>\n\n#include <kernels.hpp>\n#include <params.hpp>\n\nclass Periphery;\n\n/// @brief Class to represent a single flexible filament\n///\n/// Actions on the fiber class are typically handled via the container object, which will\n/// distribute calls appropriately across all fibers in the container.\nclass Fiber {\n  public:\n    enum BC { Force, Torque, Velocity, AngularVelocity, Position, Angle };\n    static const std::string BC_name[];\n\n    // Input parameters\n    int n_nodes_;                  ///< number of nodes representing the fiber\n    double length_;                ///< Desired 'constraint' length of fiber\n    double length_prev_;           ///< Last accepted length_\n    double bending_rigidity_;      ///< bending rigidity 'E' of fiber\n    double penalty_param_ = 500.0; ///< @brief Tension penalty parameter for linear operator @see update_linear_operator\n    /// @brief scale of external force on node @see generate_external_force\n    /// \\f[{\\bf f} = f_s * {\\bf x}_s\\f]\n    double force_scale_ = 0.0;\n    // FIXME: Magic numbers in linear operator calculation\n    double beta_tstep_ = 1.0; ///< penalty parameter to ensure inextensibility\n    double epsilon_ = 1E-3;   ///< slenderness parameter\n\n    /// (body, site) pair for minus end binding. -1 implies unbound\n    std::pair<int, int> binding_site_{-1, -1};\n\n    double v_growth_ = 0.0;      ///< instantaneous fiber growth velocity\n    bool near_periphery = false; ///< flag if interacting with periphery\n\n    /// @brief Coefficient for SBT @see Fiber::init\n    /// \\f[ c_0 = -\\frac{log(e \\epsilon^\\ell)}{8 \\pi \\eta}\\f]\n    double c_0_;\n\n    /// @brief Coefficient for SBT @see Fiber::init\n    /// \\f[ c_1 = \\frac{1}{4\\pi\\eta} \\f]\n    double c_1_;\n\n    /// Boundary condition pair for minus end of fiber\n    std::pair<BC, BC> bc_minus_ = {BC::Velocity, BC::AngularVelocity};\n    /// Boundary condition pair for plus end of fiber\n    std::pair<BC, BC> bc_plus_ = {BC::Force, BC::Torque};\n\n    Eigen::MatrixXd x_;     ///< [ 3 x n_nodes_ ] matrix representing coordinates of fiber nodes\n    Eigen::MatrixXd xs_;    ///< [ 3 x n_nodes_ ] matrix representing first derivative of fiber nodes\n    Eigen::MatrixXd xss_;   ///< [ 3 x n_nodes_ ] matrix representing second derivative of fiber nodes\n    Eigen::MatrixXd xsss_;  ///< [ 3 x n_nodes_ ] matrix representing third derivative of fiber nodes\n    Eigen::MatrixXd xssss_; ///< [ 3 x n_nodes_ ] matrix representing fourth derivative of fiber nodes\n\n    /// [ 3*n_nodes_ x 3*n_nodes_] Oseen tensor for fiber @see Fiber::update_stokeslet\n    Eigen::MatrixXd stokeslet_;\n\n    Eigen::MatrixXd A_;                         ///< Fiber's linear operator for matrix solver\n    Eigen::FullPivLU<Eigen::MatrixXd> A_LU_; ///< Fiber preconditioner, LU decomposition of Fiber::A_\n    /// Fiber force operator, @see Fiber::update_force_operator, FiberContainer::apply_fiber_force\n    Eigen::MatrixXd force_operator_;\n    Eigen::VectorXd RHS_; ///< Current 'right-hand-side' for matrix formulation of solver\n\n    /// Structure that caches arrays useful for calculating various fiber values\n    typedef struct {\n        Eigen::ArrayXd alpha;\n        Eigen::ArrayXd alpha_roots;\n        Eigen::ArrayXd alpha_tension;\n        Eigen::ArrayXd weights_0;\n        Eigen::MatrixXd D_1_0;\n        Eigen::MatrixXd D_2_0;\n        Eigen::MatrixXd D_3_0;\n        Eigen::MatrixXd D_4_0;\n        Eigen::MatrixXd P_X;\n        Eigen::MatrixXd P_T;\n        Eigen::MatrixXd P_downsample_bc;\n    } fib_mat_t;\n\n    /// Map of cached matrices for different values of n_nodes_. Calculated automagically at program start. @see\n    /// compute_matrices\n    const static std::unordered_map<int, fib_mat_t> matrices_;\n\n    Fiber(toml::value &fiber_table, double eta);\n    Fiber() = default;\n\n    /// @brief initialize empty fiber\n    /// @param[in] n_nodes fiber 'resolution'\n    /// @param[in] bending_rigidity bending rigidity of fiber\n    /// @param[in] eta fluid viscosity\n    ///\n    /// @deprecated Initializing with a toml::table structure is the preferred initialization. This is only around for\n    /// testing.\n    Fiber(int n_nodes, double bending_rigidity, double eta) : n_nodes_(n_nodes), bending_rigidity_(bending_rigidity) {\n        init(eta);\n    };\n\n    ///< @brief Set some default values and resize arrays\n    ///\n    ///< _MUST_ be called from constructors.\n    ///\n    /// Initializes: Fiber::x_, Fiber::xs_, Fiber::xss_, Fiber::xsss_, Fiber::xssss_, Fiber::c_0_, Fiber::c_1_\n    void init(double eta) {\n        x_ = Eigen::MatrixXd::Zero(3, n_nodes_);\n        x_.row(0) = Eigen::ArrayXd::LinSpaced(n_nodes_, 0, 1.0).transpose();\n        xs_.resize(3, n_nodes_);\n        xss_.resize(3, n_nodes_);\n        xsss_.resize(3, n_nodes_);\n        xssss_.resize(3, n_nodes_);\n        length_prev_ = length_;\n\n        c_0_ = -log(M_E * std::pow(epsilon_, 2)) / (8 * M_PI * eta);\n        c_1_ = 2.0 / (8.0 * M_PI * eta);\n    };\n\n    void update_preconditioner();\n    void update_force_operator();\n    void update_RHS(double dt, MatrixRef &flow, MatrixRef &f_external);\n    void update_linear_operator(double dt, double eta);\n    void apply_bc_rectangular(double dt, MatrixRef &v_on_fiber, MatrixRef &f_on_fiber);\n    void translate(const Eigen::Vector3d &r) { x_.colwise() += r; };\n    void update_derivatives();\n    void update_stokeslet(double);\n    bool attached_to_body() { return binding_site_.first >= 0; };\n    MSGPACK_DEFINE_MAP(n_nodes_, length_, bending_rigidity_, penalty_param_, force_scale_, beta_tstep_, epsilon_,\n                       binding_site_, x_);\n};\n\n/// Class to hold the fiber objects.\n///\n/// The container object is designed to work on fibers local to that MPI rank. Each MPI rank\n/// should have its own container, with its own unique fibers. The container object does not\n/// have any knowledge of the MPI world state, which, for example, is passed in externally to\n/// the FiberContainer::flow method and potentially others.\n///\n/// Developer note: ideally all interactions with the fiber objects should be through this\n/// container, except for testing purposes. Operating on fibers outside of the container class\n/// is ill-advised.\nclass FiberContainer {\n  public:\n    std::list<Fiber> fibers; ///< Array of fibers local to this MPI rank\n    /// pointer to FMM object (pointer to avoid constructing stokeslet_kernel_ with default FiberContainer)\n    std::shared_ptr<kernels::FMM<stkfmm::Stk3DFMM>> stokeslet_kernel_;\n\n    /// Empty container constructor to avoid initialization list complications. No way to\n    /// initialize after using this constructor, so overwrite objects with full constructor.\n    FiberContainer() = default;\n    FiberContainer(toml::array &fiber_tables, Params &params);\n\n    void update_derivatives();\n    void update_stokeslets(double eta);\n    void update_linear_operators(double dt, double eta);\n    void update_cache_variables(double dt, double eta);\n    void update_RHS(double dt, MatrixRef &v_on_fibers, MatrixRef &f_on_fibers);\n    void apply_bc_rectangular(double dt, MatrixRef &v_on_fibers, MatrixRef &f_on_fibers);\n\n    /// @brief get total number of nodes across fibers in the container\n    /// Usually you need this to form arrays used as input later\n    /// @returns total number of nodes across fibers in the container :)\n    int get_local_node_count() const {\n        // FIXME: This could certainly be cached\n        int tot = 0;\n        for (auto &fib : fibers)\n            tot += fib.n_nodes_;\n        return tot;\n    };\n\n    int get_global_total_fib_nodes() const;\n\n    /// @brief Get the size of all local fibers contribution to the matrix problem solution\n    int get_local_solution_size() const { return get_local_node_count() * 4; }\n\n    /// @brief Get number of local fibers\n    int get_local_count() const { return fibers.size(); };\n\n    /// @brief Get number of local fibers\n    int get_global_count() const;\n\n    Eigen::MatrixXd generate_constant_force() const;\n    Eigen::MatrixXd get_local_node_positions() const;\n    Eigen::VectorXd get_RHS() const;\n    Eigen::MatrixXd flow(MatrixRef &forces, MatrixRef &r_trg_external, double eta) const;\n    Eigen::VectorXd matvec(VectorRef &x_all, MatrixRef &v_fib, MatrixRef &v_fib_boundary) const;\n    Eigen::MatrixXd apply_fiber_force(VectorRef &x_all) const;\n    Eigen::VectorXd apply_preconditioner(VectorRef &x_all) const;\n\n    void update_boundary_conditions(Periphery &shell, bool periphery_binding_flag);\n\n  private:\n    int world_size_ = -1;\n    int world_rank_;\n\n  public:\n    MSGPACK_DEFINE(fibers);\n};\n\n#endif\n", "meta": {"hexsha": "7cabbd685ce1474343e15b9b572a6df43284a100", "size": 8650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fiber.hpp", "max_stars_repo_name": "lu1and10/SkellySim", "max_stars_repo_head_hexsha": "6d319f2d1c1c85506d7debedc082747d89995045", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/fiber.hpp", "max_issues_repo_name": "lu1and10/SkellySim", "max_issues_repo_head_hexsha": "6d319f2d1c1c85506d7debedc082747d89995045", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/fiber.hpp", "max_forks_repo_name": "lu1and10/SkellySim", "max_forks_repo_head_hexsha": "6d319f2d1c1c85506d7debedc082747d89995045", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4019607843, "max_line_length": 120, "alphanum_fraction": 0.6885549133, "num_tokens": 2150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.41548913349681527}}
{"text": "#pragma once\n#include <Eigen/Sparse>\n#include <tuple>\n\n#include \"grid.h\"\n#include \"mtao/algebra/combinatorial.hpp\"\n#include \"mtao/iterator/enumerate.hpp\"\n#include \"staggered_grid_utils.hpp\"\n\nnamespace mtao::geometry::grid {\n\n// A not-so-simple staggered grid class\ntemplate <typename T, int Dim>\nstruct StaggeredGrid {\n   public:\n    constexpr static int D = Dim;\n    using GridType = GridD<T, Dim>;\n    using Scalar = T;\n    using BBox = typename GridType::BBox;\n    using Indexer = typename GridType::Indexer;\n    using coord_type = typename GridType::coord_type;\n    using Vec = typename GridType::Vec;\n    using VecMap = typename GridType::VecMap;\n    using CVecMap = typename GridType::CVecMap;\n    using IVec = typename GridType::IVec;\n    using IVecMap = typename GridType::IVecMap;\n    using CIVecMap = typename GridType::CIVecMap;\n    using StaggeredGrids =\n        decltype(staggered_grid::make_grids(std::declval<GridType>()));\n\n    const Vec& dx() const { return vertex_grid().dx(); }\n\n    template <int N>\n    constexpr static size_t form_grid_size() {\n        return std::tuple_size<std::tuple_element_t<N, StaggeredGrids>>();\n    }\n    /*\n    StaggeredGrid(const coord_type& shape): Base(shape) {\n        resize_grids();\n    }\n    */\n    template <typename U>\n    StaggeredGrid(const StaggeredGrid<U, D>& o)\n        : StaggeredGrid(o.vertex_grid().template cast<T>()) {}\n    // the vertex grid is the \"defining\" type\n    StaggeredGrid(const GridType& g) {\n        std::get<0>(std::get<0>(m_grids)) = g;\n        resize_grids();\n    }\n    StaggeredGrid(const coord_type& g) {\n        std::get<0>(std::get<0>(m_grids)) = g;\n        resize_grids();\n    }\n    /*\n    template <typename... Args>\n        StaggeredGrid(Args&&... args) {\n\n            static_assert((std::is_integral_v<Args> && ... ));\n            std::get<0>(std::get<0>(m_grids)) =\n    GridType(std::forward<Args>(args)...); resize_grids();\n        }\n        */\n    // template <typename... Args>\n    //    StaggeredGrid(const coord_type& shape, Args&&... args): Base(shape,\n    //    std::forward<Args>(args)...) {\n    //        resize_grids();\n    //    }\n    StaggeredGrid() {}\n    StaggeredGrid(const StaggeredGrid& other) = default;\n    StaggeredGrid(StaggeredGrid&& other) = default;\n    StaggeredGrid& operator=(const StaggeredGrid& other) = default;\n    StaggeredGrid& operator=(StaggeredGrid&& other) = default;\n\n    auto bbox() const { return vertex_grid().bbox(); }\n    static StaggeredGrid from_bbox(BBox bb, const coord_type& shape,\n                                   bool cubes = false) {\n        return GridType::from_bbox(bb, shape, cubes);\n    }\n    auto&& origin() const { return vertex_grid().origin(); }\n    template <int N, int K>\n    const GridType& grid() const {\n        return std::get<K>(std::get<N>(m_grids));\n    }\n    template <int N>\n    auto&& grids() const {\n        return std::get<N>(m_grids);\n    }\n    template <int N>\n    const GridType& grid(int K) const {\n        return std::get<N>(m_grids)[K];\n    }\n    auto&& vertex_grid() const { return grid<0, 0>(); }\n    auto&& cell_grid() const { return grid<D, 0>(); }\n    template <int N>\n    auto offsets() const {\n        return std::get<N>(m_offsets);\n    }\n    template <int N, int K>\n    int offset() const {\n        return offsets<N>()[K];\n    }\n    template <int N>\n    int offset(int K) const {\n        return offsets<N>()[K];\n    }\n\n    template <int N, int K>\n    size_t staggered_index(const coord_type& idx) const {\n        return offset<N, K>() + grid<N, K>().index(idx);\n    }\n    template <int N>\n    size_t staggered_index(const coord_type& idx, int K) const {\n        return offset<N>(K) + grid<N>(K).index(idx);\n    }\n    template <int N, int K>\n    auto staggered_unindex(int idx) const {\n        return grid<N, K>().unindex(idx - offset<N, K>());\n    }\n    template <int N>\n    auto staggered_unindex(int idx, int K) const {\n        return grid<N>(K).unindex(idx - offset<N>(K));\n    }\n    template <int N, int K>\n    auto staggered_vertices() const {\n        return grid<N, K>().vertices();\n    }\n    template <int N, int K>\n    auto staggered_vertex(const coord_type& idx) const {\n        return grid<N, K>().vertex(idx);\n    }\n    template <int N, int K>\n    const coord_type& staggered_shape() const {\n        return grid<N, K>().shape();\n    }\n    template <int N, int K>\n    size_t staggered_size() const {\n        return grid<N, K>().size();\n    }\n    template <int N>\n    auto staggered_vertices(int K) const {\n        return grid<N>(K).vertices();\n    }\n    template <int N>\n    auto staggered_vertex(const coord_type& idx, int K) const {\n        return grid<N>(K).vertex(idx);\n    }\n    template <int N>\n    const coord_type& staggered_shape(int K) const {\n        return grid<N>(K).shape();\n    }\n    template <int N>\n    size_t staggered_size(int K) const {\n        return grid<N>(K).size();\n    }\n    template <int N, int K = 0>\n    auto staggered_vertex(int idx) const {\n        return staggered_vertex<N, K>(staggered_unindex<N, K>(idx));\n    }\n    template <int N>\n    auto staggered_vertex(int idx, int K) const {\n        return staggered_vertex<N>(staggered_unindex<N>(idx, K), K);\n    }\n    template <int N, int K>\n    bool staggered_valid_index(const coord_type& idx) const {\n        return grid<N, K>().valid_index(idx);\n    }\n    template <int N>\n    bool staggered_valid_index(const coord_type& idx, int K) const {\n        return grid<N>(K).valid_index(idx);\n    }\n\n    auto vertex(const coord_type& idx) const {\n        return staggered_vertex<0, 0>(idx);\n    }\n    auto vertex(int idx) const { return vertex(staggered_unindex<0, 0>(idx)); }\n    auto vertices() const { return staggered_vertices<0, 0>(); }\n    auto cell_vertex(const coord_type& idx) const {\n        return staggered_vertex<D>(idx);\n    }\n    auto cell_vertex(int idx) const {\n        return vertex(staggered_unindex<D, 0>(idx));\n    }\n    auto cell_vertices() const { return staggered_vertices<D, 0>(); }\n\n    size_t u_index(const coord_type& idx) const {\n        return staggered_index<1, 0>(idx);\n    }\n    size_t v_index(const coord_type& idx) const {\n        return staggered_index<1, 1>(idx);\n    }\n    size_t w_index(const coord_type& idx) const {\n        return staggered_index<1, 2>(idx);\n    }\n    size_t vw_index(const coord_type& idx) const {\n        return staggered_index<2, 0>(idx);\n    }\n    size_t uw_index(const coord_type& idx) const {\n        return staggered_index<2, 1>(idx);\n    }\n    size_t uv_index(const coord_type& idx) const {\n        return staggered_index<2, 2>(idx);\n    }\n    size_t vertex_index(const coord_type& idx) const {\n        return staggered_index<0, 0>(idx);\n    }\n    size_t cell_index(const coord_type& idx) const {\n        return staggered_index<D, 0>(idx);\n    }\n    coord_type u_unindex(size_t idx) const {\n        return staggered_unindex<1, 0>(idx);\n    }\n    coord_type v_unindex(size_t idx) const {\n        return staggered_unindex<1, 1>(idx);\n    }\n    coord_type w_unindex(size_t idx) const {\n        return staggered_unindex<1, 2>(idx);\n    }\n    coord_type vw_unindex(size_t idx) const {\n        return staggered_unindex<2, 0>(idx);\n    }\n    coord_type uw_unindex(size_t idx) const {\n        return staggered_unindex<2, 1>(idx);\n    }\n    coord_type uv_unindex(size_t idx) const {\n        return staggered_unindex<2, 2>(idx);\n    }\n    coord_type vertex_unindex(size_t idx) const {\n        return staggered_unindex<0, 0>(idx);\n    }\n    coord_type cell_unindex(size_t idx) const {\n        return staggered_unindex<D, 0>(idx);\n    }\n\n    const coord_type& u_shape() const { return staggered_shape<1, 0>(); }\n    const coord_type& v_shape() const { return staggered_shape<1, 1>(); }\n    const coord_type& w_shape() const { return staggered_shape<1, 2>(); }\n    const coord_type& vw_shape() const { return staggered_shape<2, 0>(); }\n    const coord_type& uw_shape() const { return staggered_shape<2, 1>(); }\n    const coord_type& uv_shape() const { return staggered_shape<2, 2>(); }\n    const coord_type& vertex_shape() const { return staggered_shape<0, 0>(); }\n    const coord_type& cell_shape() const { return staggered_shape<D, 0>(); }\n\n    size_t u_size() const { return staggered_size<1, 0>(); }\n    size_t v_size() const { return staggered_size<1, 1>(); }\n    size_t w_size() const { return staggered_size<1, 2>(); }\n    size_t vw_size() const { return staggered_size<2, 0>(); }\n    size_t uw_size() const { return staggered_size<2, 1>(); }\n    size_t uv_size() const { return staggered_size<2, 2>(); }\n    size_t vertex_size() const { return staggered_size<0, 0>(); }\n    size_t cell_size() const { return staggered_size<D, 0>(); }\n\n    bool u_valid_index(const coord_type& idx) const {\n        return staggered_valid_index<1, 0>(idx);\n    }\n    bool v_valid_index(const coord_type& idx) const {\n        return staggered_valid_index<1, 1>(idx);\n    }\n    bool w_valid_index(const coord_type& idx) const {\n        return staggered_valid_index<1, 2>(idx);\n    }\n    bool vw_valid_index(const coord_type& idx) const {\n        return staggered_valid_index<2, 0>(idx);\n    }\n    bool uw_valid_index(const coord_type& idx) const {\n        return staggered_valid_index<2, 1>(idx);\n    }\n    bool uv_valid_index(const coord_type& idx) const {\n        return staggered_valid_index<2, 2>(idx);\n    }\n    bool vertex_valid_index(const coord_type& idx) const {\n        return staggered_valid_index<0, 0>(idx);\n    }\n    bool cell_valid_index(const coord_type& idx) const {\n        return staggered_valid_index<D, 0>(idx);\n    }\n\n    template <int D>\n    std::array<T, combinatorial::nCr(Dim, D)> form_volumes() const {\n        std::array<T, combinatorial::nCr(Dim, D)> R;\n        if constexpr (D == 0) {\n            return {{T(1)}};\n        } else if constexpr (D == 1) {\n            std::copy(dx().data(), dx().data() + dx().size(), R.begin());\n        } else if constexpr (D == Dim - 1) {\n            std::fill(R.begin(), R.end(), 1);\n            for (int i = 0; i < Dim; ++i) {\n                for (int j = 1; j < Dim; ++j) {\n                    R[i] *= dx()((i + j) % Dim);\n                }\n            }\n        } else if constexpr (D == Dim) {\n            return {{dx().prod()}};\n        }\n        return R;\n    }\n    std::vector<T> form_volumes(int D) const {\n        int size = combinatorial::nCr(Dim, D);\n        std::vector<T> R(size, 1);\n        if (D == 0) {\n            return {T(1)};\n        } else if (D == 1) {\n            std::copy(dx().data(), dx().data() + dx().size(), R.begin());\n        } else if (D == Dim - 1) {\n            std::fill(R.begin(), R.end(), 1);\n            for (int i = 0; i < Dim; ++i) {\n                for (int j = 1; j < Dim; ++j) {\n                    R[i] *= dx()((i + j) % Dim);\n                }\n            }\n        } else if (D == Dim) {\n            return {dx().prod()};\n        }\n        return R;\n    }\n\n    template <int D>\n    size_t form_size() const {\n        auto&& gs = std::get<D>(m_offsets);\n        using U = types::remove_cvref_t<decltype(gs)>;\n        return gs[std::tuple_size<U>() - 1];\n    }\n    size_t edge_size() const { return form_size<1>(); }\n    size_t flux_size() const { return form_size<D - 1>(); }\n\n    template <int D>\n    int form_type(int index) const {\n        if (index < 0) {\n            return -1;\n        }\n        using namespace iterator;\n        auto&& ofs = offsets<D>();\n        size_t result = 0;\n        using U = types::remove_cvref_t<decltype(ofs)>;\n        for (auto&& [i, v] : enumerate(reverse(ofs))) {\n            if (index >= v) {\n                result = std::tuple_size<U>() - i - 1;\n                break;\n            }\n        }\n        if (result >= ofs.size()) {\n            return -1;\n        }\n        return result;\n    }\n\n    size_t edge_type(int index) const { return form_type<1>(index); }\n    template <int D>\n    auto form_unindex(int idx) const {\n        int ft = form_type<D>(idx);\n        return std::make_tuple(staggered_unindex<D>(idx, ft), ft);\n    }\n    template <typename Derived>\n    auto coord(const Eigen::MatrixBase<Derived>& v) const {\n        return vertex_grid().coord(v);\n    }\n    template <int N>\n    Eigen::SparseMatrix<T> boundary() const {\n        int rows = form_size<N - 1>();\n        int cols = form_size<N>();\n        std::vector<Eigen::Triplet<T>> trips;\n        for (auto&& [K, grids] : iterator::enumerate(std::get<N>(m_grids))) {\n            std::bitset<D> difference_mask = combinatorial::nCr_mask<D>(N, K);\n            grid<N>(K).loop([&, K = K](const coord_type& c) {\n                int col = staggered_index<N>(c, K);\n                // auto s = staggered_shape<N>(K);\n                masked_difference_looper(\n                    difference_mask, c,\n                    [&](const coord_type& l, const coord_type& u, int d) {\n                        std::bitset mybs = difference_mask;\n                        mybs[d] = 0;\n                        int dim = combinatorial::nCr_unmask<D>(N - 1, mybs);\n\n                        // auto s = staggered_shape<N-1>(dim);\n                        int lrow =\n                            static_cast<int>(staggered_index<N - 1>(l, dim));\n                        int urow =\n                            static_cast<int>(staggered_index<N - 1>(u, dim));\n                        trips.emplace_back(lrow, col, T{-1});\n                        trips.emplace_back(urow, col, T{1});\n                    });\n            });\n        }\n\n        Eigen::SparseMatrix<T> A(rows, cols);\n        A.setFromTriplets(trips.begin(), trips.end());\n        return A;\n    }\n    template <int N, typename Func>\n    static void cell_vertex_looper(int K, const coord_type& c, Func&& f) {\n        staggered_grid::internal::bitmask_looper(\n            combinatorial::nCr_mask<D>(N, K), [&](const std::bitset<D>& bs) {\n                coord_type cc = c;\n                for (int j = 0; j < D; ++j) {\n                    cc[j] += bs[j];\n                }\n                f(cc);\n            });\n    }\n    template <int N, typename Func>\n    static void cell_dual_vertex_looper(int K, const coord_type& c, Func&& f) {\n        staggered_grid::internal::bitmask_looper(\n            !combinatorial::nCr_mask<D>(N, K), [&](const std::bitset<D>& bs) {\n                coord_type cc = c;\n                for (int j = 0; j < D; ++j) {\n                    cc[j] -= bs[j];\n                }\n                f(cc);\n            });\n    }\n\n    template <typename Func>\n    static void masked_difference_looper(const std::bitset<D>& mask,\n                                         const coord_type& c, Func&& f) {\n        coord_type cc = c;\n        for (int j = 0; j < D; ++j) {\n            if (mask[j]) {\n                cc[j]++;\n                const coord_type& ccc = cc;\n                f(c, ccc, j);\n                cc[j]--;\n            }\n        }\n    }\n    // f( lower_index_boundary, higher_index_boundary, index) as a centered\n    // difference stencil for <1>::instance boundary_cell_looper<1>(0,{N+.5},f)\n    // calls\n    //          f({N},{N+1},0)\n    // for <2>::instance boundary_cell_looper<2>(1,{N+.5,M+.5},f) calls\n    //          f({N,M+.5},{N+1,M+.5},0)\n    //          f({N+.5,M},{N+.5,M+1},1)\n    template <int N, typename Func>\n    static void cell_boundary_looper(int K, const coord_type& c, Func&& f) {\n        auto comb = combinatorial::nCr_mask<D>(N, K);\n        masked_difference_looper(comb, c, f);\n    }\n\n    // opposite of the above\n    template <int N, typename Func>\n    static void dual_cell_boundary_looper(int K, const coord_type& c,\n                                          Func&& f) {\n        coord_type cc = c;\n        auto comb = !combinatorial::nCr_mask<D>(N, K);\n        for (int j = 0; j < D; ++j) {\n            if (comb[j]) {\n                cc[j]--;\n                const coord_type& ccc = cc;\n                f(ccc, c, j);\n                cc[j]++;\n            }\n        }\n    }\n\n    template <int N>\n    auto form_vertices(int K, const coord_type& c) const {\n        std::array<int, 1 << N> ret;\n        auto it = ret.begin();\n        cell_vertex_looper<N>(\n            K, c, [&](const coord_type& c) { *(it++) = vertex_index(c); });\n        return ret;\n    }\n    template <int D>\n    auto form_vertices(int idx) const {\n        int K = form_type<D>(idx);\n        auto coord = staggered_unindex<D>(idx, K);\n        return form_vertices<D>(K, coord);\n    }\n    auto edge(int K, const coord_type& c) const -> std::array<int, 2> {\n        return form_vertices<1>(K, c);\n    }\n    auto edge(int idx) const { return form_vertices<1>(idx); }\n\n   private:\n    void resize_grids() {\n        m_grids = staggered_grid::make_grids(vertex_grid());\n        m_offsets = staggered_grid::staggered_grid_offsets(vertex_shape());\n    }\n    StaggeredGrids m_grids;\n    decltype(staggered_grid::staggered_grid_offsets(\n        std::declval<coord_type>())) m_offsets;\n};\n\nusing StaggeredGrid2f = StaggeredGrid<float, 2>;\nusing StaggeredGrid3f = StaggeredGrid<float, 3>;\nusing StaggeredGrid2d = StaggeredGrid<double, 2>;\nusing StaggeredGrid3d = StaggeredGrid<double, 3>;\n}  // namespace mtao::geometry::grid\n", "meta": {"hexsha": "cbca0c01ddb7a375bb9a6a811d579726d3161d6d", "size": 17088, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/geometry/grid/staggered_grid.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/geometry/grid/staggered_grid.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/geometry/grid/staggered_grid.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0882956879, "max_line_length": 79, "alphanum_fraction": 0.5609199438, "num_tokens": 4624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.41534673535163363}}
{"text": "#include <iostream>\r\n#include <list>\r\n#include <experimental/filesystem>\r\n#include <fstream>\r\n#include <map>\r\n#include <chrono>\r\n#include <cmath>\r\n#include <iomanip>\r\n#include <armadillo>\r\n#include <omp.h>\r\n#include <cassert>\r\n\r\n#include \"../../lib/json.hpp\"\r\n#include \"../exciton_transfer/cnt.h\"\r\n#include \"../helper/prepare_directory.hpp\"\r\n#include \"../helper/progress.hpp\"\r\n#include \"monte_carlo.h\"\r\n\r\n\r\nnamespace mc\r\n{\r\n\r\n  // high level method to calculate proper scattering table\r\n  std::vector<std::vector<scattering_struct>> monte_carlo::create_scattering_table(nlohmann::json j) {\r\n    assert(j.count(\"rate type\")>0);\r\n\r\n    std::string rate_type = j[\"rate type\"].get<std::string>();\r\n\r\n    std::cout << \"\\ninitializing scattering table with \" << rate_type << \"...\" << std::endl;\r\n\r\n\r\n    if (rate_type == \"davoody\") {\r\n\r\n      // get the parent directory for cnts\r\n      std::string parent_directory = j[\"cnts\"][\"directory\"];\r\n      j[\"cnts\"].erase(\"directory\");\r\n      j[\"cnts\"].erase(\"comment\");\r\n\r\n      // create excitons and calculate exciton dispersions\r\n      std::vector<cnt> cnts;\r\n      cnts.reserve(j[\"cnts\"].size()); // this is reservation of space is crucial to ensure we do not move\r\n                                      // cnts, since the move constructor is not implemented yet\r\n      \r\n      for (const auto& j_cnt : j[\"cnts\"]) {\r\n        cnts.emplace_back(cnt(j_cnt, parent_directory));\r\n        cnts.back().calculate_exciton_dispersion();\r\n      };\r\n\r\n\t  std::vector<std::vector<scattering_struct>> all_tables(size(cnts));\r\n\t  for (int i = 0; i < size(cnts); i++) {\r\n\t\t  all_tables[i] = std::vector<scattering_struct>(size(cnts));\r\n\t\t  for (int j = 0; j < size(cnts); j++) {\r\n\t\t\t  all_tables[i][j] = create_davoody_scatt_table(cnts[i], cnts[j]);\r\n\t\t  }\r\n\t  }\r\n\r\n\t  return all_tables;\r\n    }\r\n\r\n    /*if (rate_type == \"forster\") {\r\n      return create_forster_scatt_table(1.e15, 1.4e9);\r\n    }\r\n\r\n    if (rate_type == \"wong\") {\r\n      return create_forster_scatt_table(1.e13, 1.4e9);\r\n    }*/\r\n    \r\n    throw std::invalid_argument(\"rate type must be one of the following: \\\"davoody\\\", \\\"forster\\\", \\\"wong\\\"\");\r\n\r\n  };\r\n\r\n  // method to calculate scattering rate via davoody et al. method\r\n  scattering_struct monte_carlo::create_davoody_scatt_table(const cnt& d_cnt, const cnt& a_cnt) {\r\n    auto zshift_prop = _json_prop[\"zshift [m]\"];\r\n    arma::vec z_shift = arma::linspace<arma::vec>(zshift_prop[0], zshift_prop[1], zshift_prop[2]);\r\n\r\n    auto axis_shift_prop_1 = _json_prop[\"axis shift 1 [m]\"];\r\n    arma::vec axis_shift_1 = arma::linspace<arma::vec>(axis_shift_prop_1[0], axis_shift_prop_1[1], axis_shift_prop_1[2]);\r\n\r\n    auto axis_shift_prop_2 = _json_prop[\"axis shift 2 [m]\"];\r\n    arma::vec axis_shift_2 = arma::linspace<arma::vec>(axis_shift_prop_2[0], axis_shift_prop_2[1], axis_shift_prop_2[2]);\r\n\r\n    auto theta_prop = _json_prop[\"theta [degrees]\"];\r\n    arma::vec theta = arma::linspace<arma::vec>(theta_prop[0], theta_prop[1], theta_prop[2])*(constants::pi/180);\r\n\r\n    arma::field<arma::cube> rate(theta.n_elem);\r\n    rate.for_each([&](arma::cube& c){c.zeros(z_shift.n_elem, axis_shift_1.n_elem, axis_shift_2.n_elem);});\r\n\r\n    exciton_transfer ex_transfer(d_cnt, a_cnt);\r\n\r\n    ex_transfer.save_atom_locations(_output_directory.path(), {0, 0}, 1.5e-9, 0, \".0_angle\");\r\n    ex_transfer.save_atom_locations(_output_directory.path(), {0, 0}, 1.5e-9, constants::pi / 2, \".90_angle\");\r\n    ex_transfer.save_atom_locations(_output_directory.path(), {0, 0}, 1.5e-9, constants::pi, \".180_angle\");\r\n\r\n\r\n    #ifdef DEBUG_CHECK_RATES_SYMMETRY\r\n    {\r\n      double zsh = 1.5e-9;\r\n      double ash1 = 0;\r\n      double ash2 = 0;\r\n      \r\n      double th = 0;\r\n      double r = ex_transfer.first_order(zsh, {ash1, ash2}, th, false);\r\n      std::cout << \"rate(\" << th << \") = \" << r << std::endl;\r\n\r\n      th = constants::pi;\r\n      r = ex_transfer.first_order(zsh, {ash1, ash2}, th, false);\r\n      std::cout << \"rate(\" << th << \") = \" << r << std::endl;\r\n\r\n      std::exit(0);\r\n    }\r\n    #endif\r\n\r\n    // progress_bar prog(theta.n_elem*z_shift.n_elem*axis_shift_1.n_elem*axis_shift_2.n_elem,\"create davoody scattering table\");\r\n    progress_bar prog(theta.n_elem * z_shift.n_elem * axis_shift_1.n_elem * axis_shift_2.n_elem, \"create davoody scattering table\");\r\n\r\n    #pragma omp parallel\r\n    {\r\n      double th, zsh, ash1, ash2;\r\n\r\n      #pragma omp for\r\n      for (unsigned i_th = 0; i_th<theta.n_elem; ++i_th) {\r\n\r\n        th = theta(i_th);\r\n        for (unsigned i_zsh = 0; i_zsh < z_shift.n_elem; ++i_zsh) {\r\n          zsh = z_shift(i_zsh);\r\n          for (unsigned i_ash1 = 0; i_ash1 < axis_shift_1.n_elem; ++i_ash1) {\r\n            ash1 = axis_shift_1(i_ash1);\r\n            for (unsigned i_ash2 = 0; i_ash2 < axis_shift_2.n_elem; ++i_ash2) {\r\n              ash2 = axis_shift_2(i_ash2);\r\n              // prog.step();\r\n              rate(i_th)(i_zsh, i_ash1, i_ash2) = ex_transfer.first_order(zsh, {ash1, ash2}, th, false);\r\n              \r\n              #pragma omp critical\r\n              {\r\n                prog.step();\r\n              }\r\n            }\r\n          }\r\n        }\r\n\r\n      }\r\n    }\r\n\r\n    scattering_struct scat_table(rate,theta,z_shift,axis_shift_1,axis_shift_2);\r\n\r\n    double max_rate = 0;\r\n    double min_rate = 10e15;\r\n    rate.for_each([&min_rate](arma::cube& c) { min_rate = min_rate < c.min() ? min_rate : c.min(); });\r\n    rate.for_each([&max_rate](arma::cube& c) { max_rate = max_rate > c.max() ? max_rate : c.max(); });\r\n    \r\n    std::cout << std::endl\r\n              << \"max rate in davoody scattering table: \" << max_rate << \" [1/s]\" << std::endl\r\n              << \"min rate in davoody scattering table: \" << min_rate << \" [1/s]\"\r\n              << std::endl\r\n              << std::endl;\r\n\r\n    // std::string filename(_output_directory.path() / \"davoody_scat_rates.dat\");\r\n    scat_table.save(_output_directory.path());\r\n\r\n    return scat_table;\r\n  };\r\n\r\n  // method to calculate scattering rate via forster method\r\n  scattering_struct monte_carlo::create_forster_scatt_table(double gamma_0, double r_0) {\r\n    auto zshift_prop = _json_prop[\"zshift [m]\"];\r\n    arma::vec z_shift = arma::linspace<arma::vec>(zshift_prop[0], zshift_prop[1], zshift_prop[2]);\r\n\r\n    auto axis_shift_prop_1 = _json_prop[\"axis shift 1 [m]\"];\r\n    arma::vec axis_shift_1 = arma::linspace<arma::vec>(axis_shift_prop_1[0], axis_shift_prop_1[1], axis_shift_prop_1[2]);\r\n\r\n    auto axis_shift_prop_2 = _json_prop[\"axis shift 2 [m]\"];\r\n    arma::vec axis_shift_2 = arma::linspace<arma::vec>(axis_shift_prop_2[0], axis_shift_prop_2[1], axis_shift_prop_2[2]);\r\n\r\n    auto theta_prop = _json_prop[\"theta [degrees]\"];\r\n    arma::vec theta = arma::linspace<arma::vec>(theta_prop[0], theta_prop[1], theta_prop[2])*(constants::pi/180);\r\n\r\n    arma::field<arma::cube> rate(theta.n_elem);\r\n    rate.for_each([&](arma::cube& c){c.zeros(z_shift.n_elem, axis_shift_1.n_elem, axis_shift_2.n_elem);});\r\n\r\n    progress_bar prog(theta.n_elem*z_shift.n_elem*axis_shift_1.n_elem*axis_shift_2.n_elem,\"create forster scattering table\");\r\n\r\n    unsigned i_th=0;\r\n    for (const auto& th: theta) {\r\n      unsigned i_zsh=0;\r\n      for (const auto& zsh: z_shift) {\r\n        unsigned i_ash1=0;\r\n        for (const auto& ash1: axis_shift_1) {\r\n          unsigned i_ash2=0;\r\n          for (const auto& ash2: axis_shift_2) {\r\n            prog.step();\r\n            arma::vec r1 = {ash1, 0, 0};\r\n            arma::vec r2 = {ash2*std::cos(th), ash2*std::sin(th), zsh};\r\n            arma::vec dR = r1-r2;\r\n            double angle_factor = std::cos(th)-3*arma::dot(arma::normalise(r1),arma::normalise(dR))*arma::dot(arma::normalise(r2),arma::normalise(dR));\r\n            rate(i_th)(i_zsh,i_ash1,i_ash2) = gamma_0*std::pow(angle_factor,2)*std::pow(1.e-9/arma::norm(dR),6);\r\n            i_ash2++;\r\n          }\r\n          i_ash1++;\r\n        }\r\n        i_zsh++;\r\n      }\r\n      i_th++;\r\n    }\r\n\r\n    scattering_struct scat_table(rate,theta,z_shift,axis_shift_1,axis_shift_2);\r\n\r\n    return scat_table;\r\n  };\r\n\r\n  // slice the domain into n sections in each direction, and return a list of scatterers in the center region as the injection region\r\n  std::vector<const scatterer *> monte_carlo::injection_region(const std::vector<scatterer> &all_scat, const domain_t domain, const int n) {\r\n    assert((n > 0) && (n % 2 == 1));\r\n\r\n    double xmin = domain.first(0), ymin = domain.first(1), zmin = domain.first(2);\r\n    double xmax = domain.second(0), ymax = domain.second(1), zmax = domain.second(2);\r\n    double dx = (xmax - xmin) / double(n), dy = (ymax - ymin) / double(n), dz = (zmax - zmin) / double(n);\r\n\r\n    std::vector<double> x, y, z;\r\n\r\n    for (int i = 0; i <= n; ++i) {\r\n      x.push_back(double(i) * dx + xmin);\r\n      y.push_back(double(i) * dy + ymin);\r\n      z.push_back(double(i) * dz + zmin);\r\n    }\r\n\r\n    std::vector<const scatterer *> inject_list;\r\n\r\n    for (const auto& s : all_scat) {\r\n      if (x[n / 2] <= s.pos(0) && s.pos(0) <= x[n / 2 + 1] &&\r\n          y[n / 2] <= s.pos(1) && s.pos(1) <= y[n / 2 + 1] &&\r\n          z[n / 2] <= s.pos(2) && s.pos(2) <= z[n / 2 + 1])\r\n        inject_list.push_back(&s);\r\n    }\r\n\r\n\r\n    return inject_list;\r\n  }\r\n\r\n  // slice the domain into n sections in each direction, and return the domain that leaves only 1 section from each side\r\n  monte_carlo::domain_t monte_carlo::get_removal_domain(const monte_carlo::domain_t domain, const int n) {\r\n    assert((n > 1));\r\n\r\n    double xmin = domain.first(0), ymin = domain.first(1), zmin = domain.first(2);\r\n    double xmax = domain.second(0), ymax = domain.second(1), zmax = domain.second(2);\r\n    double dx = (xmax - xmin) / double(n), dy = (ymax - ymin) / double(n), dz = (zmax - zmin) / double(n);\r\n\r\n    std::vector<double> x, y, z;\r\n\r\n    for (int i = 0; i <= n; ++i) {\r\n      x.push_back(double(i) * dx + xmin);\r\n      y.push_back(double(i) * dy + ymin);\r\n      z.push_back(double(i) * dz + zmin);\r\n    }\r\n\r\n    domain_t removal_domain;\r\n    removal_domain.first = {x[1], y[1], z[1]};\r\n    removal_domain.second = {x[n-1], y[n-1], z[n-1]};\r\n\r\n    return removal_domain;\r\n  }\r\n\r\n  // initialize the simulation condition to calculate diffusion coefficient using green-kubo approach\r\n  void monte_carlo::kubo_init() {\r\n    // set maximum hopping radius\r\n    _max_hopping_radius = double(_json_prop[\"max hopping radius [m]\"]);\r\n    std::cout << \"maximum hopping radius: \" << _max_hopping_radius * 1.e9 << \" [nm]\\n\";\r\n\r\n    _particle_velocity = _json_prop[\"exciton velocity [m/s]\"];\r\n    std::cout << \"exciton velocity [m/s]: \" << _particle_velocity << std::endl;\r\n\r\n    //_scat_tables = create_scattering_table(_json_prop);\r\n    _all_scat_list = create_scatterers(_input_directory.path());\r\n\r\n    domain_t d = find_simulation_domain();\r\n    std::ios::fmtflags f(std::cout.flags()); // save cout flags to be reset after printing\r\n    std::cout << std::fixed << std::showpos;\r\n    std::cout << \"\\n\"\r\n              << \"simulation domain BEFORE trimming:\\n\"\r\n              << \"    x (\" << d.first(0) * 1e9 << \" , \" << d.second(0) * 1e9 << \") [nm]\\n\"\r\n              << \"    y (\" << d.first(1) * 1e9 << \" , \" << d.second(1) * 1e9 << \") [nm]\\n\"\r\n              << \"    z (\" << d.first(2) * 1e9 << \" , \" << d.second(2) * 1e9 << \") [nm]\\n\"\r\n              << std::endl;\r\n    std::cout.flags(f); // reset the cout flags\r\n\r\n    limit_t xlim = _json_prop[\"trim limits\"][\"xlim\"];\r\n    limit_t ylim = _json_prop[\"trim limits\"][\"ylim\"];\r\n    limit_t zlim = _json_prop[\"trim limits\"][\"zlim\"];\r\n\r\n    trim_scats(xlim, ylim, zlim, _all_scat_list);\r\n\r\n    _domain = find_simulation_domain();\r\n    f = std::cout.flags(); // save cout flags to be reset after printing\r\n    std::cout << std::fixed << std::showpos;\r\n    std::cout << \"\\n\"\r\n              << \"simulation domain AFTER trimming:\\n\"\r\n              << \"    x (\" << _domain.first(0) * 1e9 << \" , \" << _domain.second(0) * 1e9 << \") [nm]\\n\"\r\n              << \"    y (\" << _domain.first(1) * 1e9 << \" , \" << _domain.second(1) * 1e9 << \") [nm]\\n\"\r\n              << \"    z (\" << _domain.first(2) * 1e9 << \" , \" << _domain.second(2) * 1e9 << \") [nm]\\n\"\r\n              << std::endl;\r\n    std::cout.flags(f); // reset the cout flags\r\n\r\n    std::cout << \"total number of scatterers: \" << _all_scat_list.size() << std::endl;\r\n\r\n    _quenching_list = create_quenching_sites(_all_scat_list, 10000);\r\n    //set_scat_table(_scat_tables[0][0], _all_scat_list);\r\n\r\n    create_scatterer_buckets(_domain, _max_hopping_radius, _all_scat_list, _scat_buckets, _quenching_list, _q_buckets);\r\n    _scat_tables = create_scattering_table(_json_prop);\r\n    set_scat_table(_scat_tables[0][0], _all_scat_list);\r\n    set_max_rate(_max_hopping_radius, _all_scat_list);\r\n\r\n    int n = _json_prop[\"number of sections for injection region\"];\r\n    _inject_scats = injection_region(_all_scat_list, _domain, n);\r\n    _removal_domain = get_removal_domain(_domain, n);\r\n\r\n    _max_time = _json_prop[\"maximum time for kubo simulation [seconds]\"];\r\n  };\r\n\r\n  // create particles for kubo simulation\r\n  void monte_carlo::kubo_create_particles() {\r\n    int n_particle = _json_prop[\"number of particles for kubo simulation\"];\r\n    for (int i=0; i<n_particle; ++i) {\r\n      int dice = std::rand() % _inject_scats.size();\r\n      const scatterer *s = _inject_scats[dice];\r\n      arma::vec pos = s->pos();\r\n      _particle_list.push_back(particle(pos, s, _particle_velocity));\r\n      _particle_list.back().set_init_pos(pos);\r\n    }\r\n  }\r\n\r\n  // step the simulation in time\r\n  void monte_carlo::kubo_step(double dt) {\r\n    #pragma omp parallel\r\n    {\r\n      #pragma omp for\r\n      for (unsigned i = 0; i < _particle_list.size(); ++i) {\r\n        particle& p = _particle_list[i];\r\n        \r\n        p.step(dt, _all_scat_list, _max_hopping_radius);\r\n        \r\n        p.update_delta_pos();\r\n\r\n        if (arma::any(p.pos()<_removal_domain.first) || arma::any(_removal_domain.second < p.pos())){\r\n          int dice = std::rand() % _inject_scats.size();\r\n          const scatterer* s = _inject_scats[dice];\r\n          arma::vec pos = s->pos();\r\n          p.set_pos(pos);\r\n          p.set_scatterer(s);\r\n        }\r\n      }\r\n    }\r\n\r\n    // increase simulation time\r\n    _time += dt;\r\n  };\r\n\r\n  // save the displacement of individual particles in kubo simulation\r\n  void monte_carlo::kubo_save_individual_particle_dispalcements() {\r\n    if (! _displacement_file_x.is_open()) {\r\n      _displacement_file_x.open(_output_directory.path() / \"particle_dispalcement.x.dat\", std::ios::out);\r\n      _displacement_file_y.open(_output_directory.path() / \"particle_dispalcement.y.dat\", std::ios::out);\r\n      _displacement_file_z.open(_output_directory.path() / \"particle_dispalcement.z.dat\", std::ios::out);\r\n\r\n      _displacement_file_x << std::showpos << std::scientific;\r\n      _displacement_file_y << std::showpos << std::scientific;\r\n      _displacement_file_z << std::showpos << std::scientific;\r\n\r\n      _displacement_file_x << \"time\";\r\n      _displacement_file_y << \"time\";\r\n      _displacement_file_z << \"time\";\r\n      for (int i=0; i<int(_particle_list.size()); ++i){\r\n        _displacement_file_x << \",\" << i;\r\n        _displacement_file_y << \",\" << i;\r\n        _displacement_file_z << \",\" << i;\r\n      }\r\n      _displacement_file_x << std::endl;\r\n      _displacement_file_y << std::endl;\r\n      _displacement_file_z << std::endl;\r\n    }\r\n\r\n    _displacement_file_x << time();\r\n    _displacement_file_y << time();\r\n    _displacement_file_z << time();\r\n\r\n    for (const auto& p: _particle_list) {\r\n      _displacement_file_x << \",\" << p.delta_pos(0);\r\n      _displacement_file_y << \",\" << p.delta_pos(1);\r\n      _displacement_file_z << \",\" << p.delta_pos(2);\r\n    }\r\n    _displacement_file_x << std::endl;\r\n    _displacement_file_y << std::endl;\r\n    _displacement_file_z << std::endl;\r\n  };\r\n\r\n  void monte_carlo::kubo_save_avg_dispalcement_squared() {\r\n    if (!_displacement_squard_file.is_open()) {\r\n      _displacement_squard_file.open(_output_directory.path() / \"particle_dispalcement.avg.squared.dat\", std::ios::out);\r\n\r\n      _displacement_squard_file << std::showpos << std::scientific;\r\n      \r\n      _displacement_squard_file << \"# this file contains the average of dx^2, dy^2, and dz^2 of the particle ensemble over time\" << std::endl\r\n                                << \"# number of particles: \" << _particle_list.size() << std::endl\r\n                                << std::endl;\r\n\r\n      _displacement_squard_file << \"time,x,y,z\" << std::endl;\r\n    }\r\n\r\n    \r\n    double avg_x2=0, avg_y2=0, avg_z2=0;\r\n\r\n    for (const auto& p : _particle_list) {\r\n      avg_x2 += std::pow(p.delta_pos(0), 2);\r\n      avg_y2 += std::pow(p.delta_pos(1), 2);\r\n      avg_z2 += std::pow(p.delta_pos(2), 2);\r\n    }\r\n\r\n    avg_x2 /= double(_particle_list.size());\r\n    avg_y2 /= double(_particle_list.size());\r\n    avg_z2 /= double(_particle_list.size());\r\n\r\n    _displacement_squard_file << time() << \",\" << avg_x2 << \",\" << avg_y2 << \",\" << avg_z2 << std::endl;\r\n  }\r\n\r\n  void monte_carlo::kubo_save_diffusion_tensor(){\r\n    if (!_diffusion_tensor_file.is_open()) {\r\n      _diffusion_tensor_file.open(_output_directory.path() / \"particle_diffusion_tensor.dat\", std::ios::out);\r\n\r\n     _diffusion_tensor_file << std::showpos << std::scientific;\r\n      \r\n      _diffusion_tensor_file << \"# this file contains the diffusion tensor Dij of the particle ensemble over time\" << std::endl\r\n                                << \"# number of particles: \" << _particle_list.size() << std::endl\r\n                                << std::endl;\r\n\r\n      _diffusion_tensor_file << \"time,Dxx,Dxy,Dxz,Dyy,Dyz,Dzz\" << std::endl;\r\n    }\r\n\r\n    _diffusion_tensor_file << time();\r\n\r\n    double Dij, D1, D2, D3;\r\n    for(int i = 0; i < 3; i++){\r\n      for(int j = i; j < 3; j++){\r\n        for(const auto& p : _particle_list){\r\n          D1 += p.pos(i)*p.pos(j);\r\n          D2 += p.pos(i);\r\n          D3 += p.pos(j);\r\n        }\r\n        Dij = (D1 + D2 * D3)/(double)(_particle_list.size());\r\n        Dij /= double(2 * double(time()));\r\n        _diffusion_tensor_file << \",\" << Dij;\r\n      }\r\n    }\r\n    _diffusion_tensor_file << std::endl;\r\n  }\r\n\r\n  void monte_carlo::kubo_save_diffusion_length() {\r\n    if (!_diffusion_length_file.is_open()) {\r\n      _diffusion_length_file.open(_output_directory.path() / \"particle_diffusion_length.dat\", std::ios::out);\r\n\r\n      _diffusion_length_file << std::showpos << std::scientific;\r\n      \r\n      _diffusion_length_file << \"# this file contains the diffusion length in x,y,z of the particle ensemble over time\" << std::endl\r\n                                << \"# number of particles: \" << _particle_list.size() << std::endl\r\n                                << std::endl;\r\n\r\n      _diffusion_length_file << \"x,y,z\" << std::endl;\r\n    }\r\n\r\n    for (const auto& p : _particle_list) {\r\n      _diffusion_length_file << p.diff_len(0) << \",\" << p.diff_len(1) << \",\" << p.diff_len(2) << std::endl;\r\n    }\r\n    \r\n  }\r\n\r\n} // end of namespace mc", "meta": {"hexsha": "7af1209aa0c1618084d928edf91e4f598851fdb6", "size": 18940, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "montecarlo/src/monte_carlo/temp/monte_carlo.cpp", "max_stars_repo_name": "li779/DECaNT", "max_stars_repo_head_hexsha": "8fe0faedd372a8214f1bd475eb7451d2eee1ca56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T19:21:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T16:41:21.000Z", "max_issues_repo_path": "montecarlo/src/monte_carlo/temp/monte_carlo.cpp", "max_issues_repo_name": "li779/DECaNT", "max_issues_repo_head_hexsha": "8fe0faedd372a8214f1bd475eb7451d2eee1ca56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "montecarlo/src/monte_carlo/temp/monte_carlo.cpp", "max_forks_repo_name": "li779/DECaNT", "max_forks_repo_head_hexsha": "8fe0faedd372a8214f1bd475eb7451d2eee1ca56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-22T15:02:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T15:02:52.000Z", "avg_line_length": 39.8736842105, "max_line_length": 152, "alphanum_fraction": 0.5964625132, "num_tokens": 5351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.41534673535163363}}
{"text": "#ifndef STAN_MATH_PRIM_FUN_GAMMA_Q_HPP\n#define STAN_MATH_PRIM_FUN_GAMMA_Q_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n *\n   \\f[\n   \\mbox{gamma\\_q}(a, z) =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } a\\leq 0 \\textrm{ or } z < 0\\\\\n     Q(a, z) & \\mbox{if } a > 0, z \\geq 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } a = \\textrm{NaN or } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{gamma\\_q}(a, z)}{\\partial a} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } a\\leq 0 \\textrm{ or } z < 0\\\\\n     \\frac{\\partial\\, Q(a, z)}{\\partial a} & \\mbox{if } a > 0, z \\geq 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } a = \\textrm{NaN or } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{gamma\\_q}(a, z)}{\\partial z} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } a\\leq 0 \\textrm{ or } z < 0\\\\\n     \\frac{\\partial\\, Q(a, z)}{\\partial z} & \\mbox{if } a > 0, z \\geq 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } a = \\textrm{NaN or } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   Q(a, z)=\\frac{1}{\\Gamma(a)}\\int_z^\\infty t^{a-1}e^{-t}dt\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, Q(a, z)}{\\partial a} =\n -\\frac{\\Psi(a)}{\\Gamma^2(a)}\\int_z^\\infty t^{a-1}e^{-t}dt\n   + \\frac{1}{\\Gamma(a)}\\int_z^\\infty (a-1)t^{a-2}e^{-t}dt\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, Q(a, z)}{\\partial z} = -\\frac{z^{a-1}e^{-z}}{\\Gamma(a)}\n   \\f]\n   * @throws domain_error if x is at pole\n */\ninline double gamma_q(double x, double a) { return boost::math::gamma_q(x, a); }\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "0f2dbbf4357fb2c219292924275cf025cfb22b83", "size": 1615, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/gamma_q.hpp", "max_stars_repo_name": "HaoZeke/math", "max_stars_repo_head_hexsha": "fdf7f70dceed60f3b3f93137c6ac123a457b80a3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-18T13:10:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-18T13:10:50.000Z", "max_issues_repo_path": "stan/math/prim/fun/gamma_q.hpp", "max_issues_repo_name": "HaoZeke/math", "max_issues_repo_head_hexsha": "fdf7f70dceed60f3b3f93137c6ac123a457b80a3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T12:45:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-01T20:43:03.000Z", "max_forks_repo_path": "stan/math/prim/fun/gamma_q.hpp", "max_forks_repo_name": "SteveBronder/math", "max_forks_repo_head_hexsha": "3f21445458866897842878f65941c6bcb90641c2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3728813559, "max_line_length": 80, "alphanum_fraction": 0.5442724458, "num_tokens": 710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.41534673535163363}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\n *    All rights reserved.\n *\n *    Redistribution and use in source and binary forms, with or without modification, are\n *    permitted provided that the following conditions are met:\n *      - Redistributions of source code must retain the above copyright notice, this list of\n *        conditions and the following disclaimer.\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\n *        conditions and the following disclaimer in the documentation and/or other materials\n *        provided with the distribution.\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\n *        may be used to endorse or promote products derived from this software without specific\n *        prior written permission.\n *\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *    Changelog\n *      YYMMDD    Author            Comment\n *      121213    R.C.A. Boon       Creation of code.\n *      130117    R.C.A. Boon       Added solved boolean flag to applicable member functions (with\n *                                  help from S. Billemont). Moved constructor to header file.\n *                                  Moved debugged getMaximumNumberOfRevolutions to source file.\n *      130211    R.C.A. Boon       Added hasSolution flag to root finder.\n *      120227    S. Billemont      Removed hasSolution in favor of an exception.\n *      130325    R.C.A. Boon       Removed superfluous sanity check of number of revolutions in\n *                                  execute() function, fixed bug in computation of maximumNumberOf-\n *                                  Revolutions.\n *\n *    References\n *      PyKEP toolbox, Dario Izzo, ESA Advanced Concepts Team.\n *      Richard H. An Introduction to the Mathematics and Methods of Astrodynamics, Revised\n *          Edition.\n *      Battin, AIAA Education Series.\n *\n *    Notes\n *\n */\n\n#include <cmath>\n\n#include <boost/format.hpp>\n#include <boost/math/special_functions.hpp> // for asinh and acosh\n\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\n#include \"Tudat/Astrodynamics/MissionSegments/multiRevolutionLambertTargeterIzzo.h\"\n#include \"Tudat/Mathematics/BasicMathematics/convergenceException.h\"\n\nnamespace tudat\n{\nnamespace mission_segments\n{\n\n//! Compute solution for N revolutions and branch.\nvoid MultiRevolutionLambertTargeterIzzo::computeForRevolutionsAndBranch(\n        const int aNumberOfRevolutions, const bool aIsRightBranch )\n{\n    // Adjust parameters for new solution\n    numberOfRevolutions = aNumberOfRevolutions;\n    isRightBranch = aIsRightBranch;\n\n    // Check whether number of revolutions is possible\n    sanityCheckNumberOfRevolutions( );\n\n    // Execute problem solving for new solution\n    execute( );\n}\n\n//! Get maximum number of revolutions calculated.\nint MultiRevolutionLambertTargeterIzzo::getMaximumNumberOfRevolutions( )\n{\n    if ( !solved )\n    {\n        transformDimensions( );\n        sanityCheckNumberOfRevolutions( );\n    }\n\n    return maximumNumberOfRevolutions;\n}\n\n//! Sanity check number of revolutions.\nvoid MultiRevolutionLambertTargeterIzzo::sanityCheckNumberOfRevolutions( )\n{\n    // If not yet defined, calculate number of revolutions possible.\n    if ( maximumNumberOfRevolutions == NO_MAXIMUM_REVOLUTIONS )\n    {\n        // Temporarily store specified number, as numberOfRevolutions is needed to calculate max\n        // (this is a tricky way to work, but on the other hand this makes this approach decidedly\n        // different from PyKEP routines and it also happens only once per object).\n        int copyOfOriginalNumberOfRevolutions = numberOfRevolutions;\n\n        // Calculate first guess of maximum, by dividing the time of flight of the minimum energy\n        // ellipse by the normalized time of flight.\n        numberOfRevolutions = static_cast< int >(\n                    normalizedTimeOfFlight / (\n                        mathematical_constants::PI / 2.0\n                        * std::sqrt( 2.0 * normalizedSemiPerimeter\n                                     * normalizedSemiPerimeter\n                                     * normalizedSemiPerimeter ) ) );\n\n        // If the current guess for the maximum is non-zero, then additional analysis is required to\n        // determine the correct maximum.\n        if( numberOfRevolutions != 0)\n        {\n            // The following try-block is meant to check whether the solution converges or not. If\n            // the current guess for the maximum number of revolutions is correct, then the problem\n            // will converge. If it does not, an exception will be thrown stating that it did not\n            // converge. Catching this exception allows to decrease the guess only when the\n            // exception occurs, and not under other circumstances.\n            try\n            {\n                // Compute root (no further information is required)\n                computeRootTimeOfFlight();\n            }\n            catch( basic_mathematics::ConvergenceException )\n            {\n                // If the rootfinder did not converge, then the current guess is wrong and needs to\n                // be decreased\n                numberOfRevolutions--;\n            }\n        }\n        // No further analysis is needed of the current guess is equal to zero.\n\n        // Maximum is now found.\n        maximumNumberOfRevolutions = numberOfRevolutions;\n\n        // Reinstating original number of revolutions specified.\n        numberOfRevolutions = copyOfOriginalNumberOfRevolutions;\n    }\n\n    // Default: compare maximum with specified number of revolutions.\n    // If specified is larger than maximum, no solution is possible.\n    if ( numberOfRevolutions > maximumNumberOfRevolutions )\n    {\n        // Throw exception.\n        BOOST_THROW_EXCEPTION( std::runtime_error( \n            ( boost::format(\n                \"Number of revolutions specified in Lambert problem is larger than possible.\\n\"\n                \"Specified number of revolutions %d while the maximum is %d\" \n            ) % numberOfRevolutions % maximumNumberOfRevolutions).str( )\n        ) );\n    }\n    // Else, nothing wrong.\n}\n\n//! Execute solving procedure (for multiple revolutions).\nvoid MultiRevolutionLambertTargeterIzzo::execute( )\n{\n    // Sanity checks.\n    sanityCheckTimeOfFlight( );\n    sanityCheckGravitationalParameter( );\n\n    // Transform dimensions.\n    transformDimensions( );\n\n    /*// Sanity check for number of revolutions (must be after dimension removal).\n    sanityCheckNumberOfRevolutions( );*/\n\n    if ( numberOfRevolutions == 0 )\n    {\n        // call base class function that works on zero revolutions.\n        ZeroRevolutionLambertTargeterIzzo::execute( );\n    }\n    else\n    {\n        // Solve multi-rev root.\n        double multipleRevolutionXParameter = computeRootTimeOfFlight( );\n\n        // Reconstruct velocities.\n        computeVelocities( multipleRevolutionXParameter );\n    }\n\n    solved = true;\n}\n\n//! Compute time-of-flight using Lagrange's equation (for multiple revolutions).\ndouble MultiRevolutionLambertTargeterIzzo::computeTimeOfFlight( const double xParameter )\n{\n    // Determine semi-major axis.\n    const double semiMajorAxis = normalizedMinimumEnergySemiMajorAxis\n            / ( 1.0 - xParameter * xParameter );\n\n    // If x < 1, the solution is an ellipse.\n    if ( xParameter < 1.0 )\n    {\n        // Alpha parameter in Lagrange's equation (no explanation available).\n        const double alphaParameter = 2.0 * std::acos( xParameter );\n\n        // Beta parameter in Lagrange's equation (no explanation available).\n        double betaParameter;\n\n        // If long transfer arc.\n        if ( isLongway )\n        {\n            betaParameter = -2.0 * std::asin(\n                        std::sqrt( ( normalizedSemiPerimeter - normalizedChord )\n                                   / ( 2.0 * semiMajorAxis ) ) );\n        }\n        // Otherwise short transfer arc.\n        else\n        {\n            betaParameter = 2.0 * std::asin(\n                        std::sqrt( ( normalizedSemiPerimeter - normalizedChord )\n                                   / ( 2.0 * semiMajorAxis ) ) );\n        }\n\n        // Time-of-flight according to Lagrange including multiple revolutions.\n        const double timeOfFlight = semiMajorAxis * std::sqrt( semiMajorAxis ) *\n                ( ( alphaParameter - std::sin( alphaParameter ) )\n                  - ( betaParameter - std::sin( betaParameter ) )\n                  + 2.0 * mathematical_constants::PI\n                  * numberOfRevolutions );\n\n        return timeOfFlight;\n    }\n    // Otherwise it is a hyperbola.\n    else\n    {\n        // Alpha parameter in Lagrange's equation (no explanation available).\n        const double alphaParameter = 2.0 * boost::math::acosh( xParameter );\n\n        // Beta parameter in Lagrange's equation (no explanation available).\n        double betaParameter;\n\n        // If long transfer arc.\n        if ( isLongway )\n        {\n            betaParameter = -2.0 * boost::math::asinh( std::sqrt( ( normalizedSemiPerimeter\n                                                                    - normalizedChord )\n                                                                  / ( -2.0 * semiMajorAxis ) ) );\n        }\n        // Otherwise short transfer arc\n        else\n        {\n            betaParameter = 2.0 * boost::math::asinh( std::sqrt( ( normalizedSemiPerimeter\n                                                                   - normalizedChord )\n                                                                 / ( -2.0 * semiMajorAxis ) ) );\n        }\n\n        // Time-of-flight according to Lagrange.\n        const double timeOfFlightLagrange = -semiMajorAxis * std::sqrt( -semiMajorAxis ) *\n                ( ( std::sinh( alphaParameter ) - alphaParameter )\n                  - ( std::sinh( betaParameter ) - betaParameter ) );\n\n        return timeOfFlightLagrange;\n    }\n}\n\n//! Solve the time of flight equation for x (for multiple revolutions).\ndouble MultiRevolutionLambertTargeterIzzo::computeRootTimeOfFlight( )\n{\n    using mathematical_constants::PI;\n\n    // Define initial guesses for abcissae (x) and ordinates (y).\n    double x1, x2;\n\n    if ( isRightBranch )\n    { // right branch solution.\n        x1 = std::tan( .7234 * PI / 2.0 );\n        x2 = std::tan( .5234 * PI / 2.0 );\n    }\n    else\n    { // left branch solution.\n        x1 = std::tan( -.5234 * PI / 2.0 );\n        x2 = std::tan( -.2234 * PI / 2.0 );\n    }\n\n    double y1 = computeTimeOfFlight( std::atan( x1 ) * 2.0 / PI ) - normalizedTimeOfFlight;\n\n    double y2 = computeTimeOfFlight( std::atan( x2 ) * 2.0 / PI ) - normalizedTimeOfFlight;\n\n    // Declare and initialize root-finding parameters.\n    double rootFindingError = 1.0, xNew = 0.0, yNew = 0.0;\n    int iterator = 0;\n\n    // Root-finding loop.\n    while ( ( rootFindingError > convergenceTolerance ) && ( y1 != y2 )\n            && ( iterator < maximumNumberOfIterations ) )\n    {\n        // Update iterator.\n        iterator++;\n\n        // Compute new x-value.\n        xNew = ( x1 * y2 - y1 * x2 ) / ( y2 - y1 );\n\n        // Compute corresponding y-value.\n        yNew = computeTimeOfFlight( std::atan( xNew ) * 2.0 / PI ) - normalizedTimeOfFlight;\n\n        // Update abcissae and ordinates.\n        x1 = x2;\n        y1 = y2;\n        x2 = xNew;\n        y2 = yNew;\n\n        // Compute root-finding error.\n        rootFindingError = std::fabs( x1 - xNew );\n    }\n\n    // Verify that root-finder has converged.\n    if ( iterator == maximumNumberOfIterations )\n    {\n        BOOST_THROW_EXCEPTION( basic_mathematics::ConvergenceException( \n            ( boost::format(\n                \"Multi-Revolution Lambert targeter failed to converge to a solution.\\n\"\n                \"Reached the maximum number of iterations: %d\"\n            ) % maximumNumberOfIterations).str( )\n        ) );\n    }\n\n    // Revert to x parameter.\n    double xParameter = std::atan( xNew ) * 2.0 / PI;\n    return xParameter;\n}\n\n// Add compute maximum number of revolutions routine?\n\n} // namespace mission_segments\n} // namespace tudat\n", "meta": {"hexsha": "051dc777deda98a9cd4b0fe8bb801b37d8f6bc3c", "size": 12932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/MissionSegments/multiRevolutionLambertTargeterIzzo.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/MissionSegments/multiRevolutionLambertTargeterIzzo.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/MissionSegments/multiRevolutionLambertTargeterIzzo.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 39.5474006116, "max_line_length": 100, "alphanum_fraction": 0.6236467677, "num_tokens": 2859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.41523762126156255}}
{"text": "//\n// SPDX-License-Identifier: BSD-3-Clause\n// Copyright Contributors to the OpenEXR Project.\n//\n\n// clang-format off\n\n#include <Python.h>\n#include <boost/python.hpp>\n#include <boost/python/make_constructor.hpp>\n#include <boost/format.hpp>\n#include \"PyImathFun.h\"\n#include \"PyImathFunOperators.h\"\n#include \"PyImathDecorators.h\"\n#include \"PyImathExport.h\"\n#include \"PyImathAutovectorize.h\"\n\nnamespace PyImath {\n\nusing namespace boost::python;\n\nnamespace\n{\n\nstruct RegisterFloatDoubleOps\n{\n    template <typename T>\n    void operator() (T)\n    {\n        // nb: MSVC gets confused about which arg we want (it thinks it\n        // might be boost::arg), so telling it which one explicitly here.\n        typedef boost::python::arg arg;\n\n        generate_bindings<abs_op<T>,boost::mpl::true_>(\n            \"abs\",\n            \"return the absolute value of 'value'\",\n            (arg(\"value\")));\n\n        generate_bindings<sign_op<T>,boost::mpl::true_>(\n            \"sign\",\n            \"return 1 or -1 based on the sign of 'value'\",\n            (arg(\"value\")));\n\n        generate_bindings<log_op<T>,boost::mpl::true_>(\n            \"log\",\n            \"return the natural log of 'value'\",\n            (arg(\"value\")));\n\n        generate_bindings<log10_op<T>,boost::mpl::true_>(\n            \"log10\",\n            \"return the base 10 log of 'value'\",\n            (arg(\"value\")));\n\n        generate_bindings<lerp_op<T>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n            \"lerp\",\n            \"return the linear interpolation of 'a' to 'b' using parameter 't'\",\n            (arg(\"a\"),arg(\"b\"),arg(\"t\")));\n\n        generate_bindings<lerpfactor_op<T>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n            \"lerpfactor\",\n            \"return how far m is between a and b, that is return t such that\\n\"\n            \"if:\\n\"\n            \"    t = lerpfactor(m, a, b);\\n\"\n            \"then:\\n\"\n            \"    m = lerp(a, b, t);\\n\"\n            \"\\n\"\n            \"If a==b, return 0.\\n\",\n            (arg(\"m\"),arg(\"a\"),arg(\"b\")));\n\n        generate_bindings<clamp_op<T>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n            \"clamp\",\n            \"return the value clamped to the range [low,high]\",\n            (arg(\"value\"),arg(\"low\"),arg(\"high\")));\n\n        generate_bindings<floor_op<T>,boost::mpl::true_>(\n            \"floor\",\n            \"return the closest integer less than or equal to 'value'\",\n            (arg(\"value\")));\n\n        generate_bindings<ceil_op<T>,boost::mpl::true_>(\n            \"ceil\",\n            \"return the closest integer greater than or equal to 'value'\",\n            (arg(\"value\")));\n\n        generate_bindings<trunc_op<T>,boost::mpl::true_>(\n            \"trunc\",\n            \"return the closest integer with magnitude less than or equal to 'value'\",\n            (arg(\"value\")));\n\n        generate_bindings<rgb2hsv_op<T>,boost::mpl::true_>(\n            \"rgb2hsv\",\n            \"return the hsv version of an rgb color\",\n            args(\"rgb\"));\n\n        generate_bindings<hsv2rgb_op<T>,boost::mpl::true_>(\n            \"hsv2rgb\",\n            \"return the rgb version of an hsv color\",\n            args(\"hsv\"));\n\n        generate_bindings<sin_op<T>,boost::mpl::true_>(\n            \"sin\",\n            \"return the sine of the angle theta\",\n            args(\"theta\"));\n\n        generate_bindings<cos_op<T>,boost::mpl::true_>(\n            \"cos\",\n            \"return the cosine of the angle theta\",\n            args(\"theta\"));\n\n        generate_bindings<tan_op<T>,boost::mpl::true_>(\n            \"tan\",\n            \"return the tangent of the angle theta\",\n            args(\"theta\"));\n\n        generate_bindings<asin_op<T>,boost::mpl::true_>(\n            \"asin\",\n            \"return the arcsine of the value x\",\n            args(\"x\"));\n\n        generate_bindings<acos_op<T>,boost::mpl::true_>(\n            \"acos\",\n            \"return the arccosine of the value x\",\n            args(\"x\"));\n\n        generate_bindings<atan_op<T>,boost::mpl::true_>(\n            \"atan\",\n            \"return the arctangent of the value x\",\n            args(\"x\"));\n\n        generate_bindings<atan2_op<T>,boost::mpl::true_,boost::mpl::true_>(\n            \"atan2\",\n            \"return the arctangent of the coordinate x,y - note the y \"\n            \"is the first argument for consistency with libm ordering\",\n            args(\"y\",\"x\"));\n\n        generate_bindings<sqrt_op<T>,boost::mpl::true_>(\n            \"sqrt\",\n            \"return the square root of x\",\n            args(\"x\"));\n\n        generate_bindings<pow_op<T>,boost::mpl::true_,boost::mpl::true_>(\n            \"pow\",\n            \"return x**y\",\n            args(\"x\",\"y\"));\n\n        generate_bindings<exp_op<T>,boost::mpl::true_>(\n             \"exp\",\n             \"return exp(x)\",\n             args(\"x\"));\n\n        generate_bindings<sinh_op<T>,boost::mpl::true_>(\n             \"sinh\",\n             \"return sinh(x)\",\n             args(\"x\"));\n\n        generate_bindings<cosh_op<T>,boost::mpl::true_>(\n             \"cosh\",\n             \"return cosh(x)\",\n             args(\"x\"));\n\n        def(\"cmp\", IMATH_NAMESPACE::cmp<T>);\n        def(\"cmpt\", IMATH_NAMESPACE::cmpt<T>);\n        def(\"iszero\", IMATH_NAMESPACE::iszero<T>);\n        def(\"equal\", IMATH_NAMESPACE::equal<T, T, T>);\n    }\n};\n\n} // namespace\n\nvoid register_functions()\n{\n    //\n    // Utility Functions\n    //\n\n    // nb: MSVC gets confused about which arg we want (it thinks it\n    // might be boost::arg), so telling it which one explicitly here.\n    typedef boost::python::arg arg;\n\n    using fp_types = boost::mpl::vector<float, double>;\n    boost::mpl::for_each<fp_types>(RegisterFloatDoubleOps());\n\n    generate_bindings<abs_op<int>,boost::mpl::true_>(\n        \"abs\",\n        \"return the absolute value of 'value'\",\n        (arg(\"value\")));\n    \n    generate_bindings<sign_op<int>,boost::mpl::true_>(\n        \"sign\",\n        \"return 1 or -1 based on the sign of 'value'\",\n        (arg(\"value\")));\n    \n    generate_bindings<clamp_op<int>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n        \"clamp\",\n        \"return the value clamped to the range [low,high]\",\n        (arg(\"value\"),arg(\"low\"),arg(\"high\")));\n\n    generate_bindings<divs_op,boost::mpl::true_,boost::mpl::true_>(\n        \"divs\",\n        \"return x/y where the remainder has the same sign as x:\\n\"\n        \"    divs(x,y) == (abs(x) / abs(y)) * (sign(x) * sign(y))\\n\",\n        (arg(\"x\"),arg(\"y\")));\n    generate_bindings<mods_op,boost::mpl::true_,boost::mpl::true_>(\n        \"mods\",\n        \"return x%y where the remainder has the same sign as x:\\n\"\n        \"    mods(x,y) == x - y * divs(x,y)\\n\",\n        (arg(\"x\"),arg(\"y\")));\n\n    generate_bindings<divp_op,boost::mpl::true_,boost::mpl::true_>(\n        \"divp\",\n        \"return x/y where the remainder is always positive:\\n\"\n        \"    divp(x,y) == floor (double(x) / double (y))\\n\",\n        (arg(\"x\"),arg(\"y\")));\n    generate_bindings<modp_op,boost::mpl::true_,boost::mpl::true_>(\n        \"modp\",\n        \"return x%y where the remainder is always positive:\\n\"\n        \"    modp(x,y) == x - y * divp(x,y)\\n\",\n        (arg(\"x\"),arg(\"y\")));\n\n    generate_bindings<bias_op,boost::mpl::true_,boost::mpl::true_>(\n         \"bias\",\n         \"bias(x,b) is a gamma correction that remaps the unit interval such that bias(0.5, b) = b.\",\n         (arg(\"x\"),arg(\"b\")));\n\n    generate_bindings<gain_op,boost::mpl::true_,boost::mpl::true_>(\n         \"gain\",\n         \"gain(x,g) is a gamma correction that remaps the unit interval with the property that gain(0.5, g) = 0.5.\\n\"\n         \"The gain function can be thought of as two scaled bias curves forming an 'S' shape in the unit interval.\",\n         (arg(\"x\"),arg(\"g\")));\n\n    //\n    // Vectorized utility functions\n    // \n    generate_bindings<rotationXYZWithUpDir_op<float>,boost::mpl::true_,boost::mpl::true_,boost::mpl::true_>(\n        \"rotationXYZWithUpDir\",\n        \"return the XYZ rotation vector that rotates 'fromDir' to 'toDir'\"\n        \"using the up vector 'upDir'\",\n        args(\"fromDir\",\"toDir\",\"upDir\"));\n}\n\n} // namespace PyImath\n", "meta": {"hexsha": "c178dde7d4ca2406eb9cf6ff7b85c4ac471f2b57", "size": 8039, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python/PyImath/PyImathFun.cpp", "max_stars_repo_name": "JenusL/Imath", "max_stars_repo_head_hexsha": "749a1bfe017b2daccb3eb9759fbe837ea4718a0a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 156.0, "max_stars_repo_stars_event_min_datetime": "2020-06-14T06:29:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:55:55.000Z", "max_issues_repo_path": "src/python/PyImath/PyImathFun.cpp", "max_issues_repo_name": "JenusL/Imath", "max_issues_repo_head_hexsha": "749a1bfe017b2daccb3eb9759fbe837ea4718a0a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 146.0, "max_issues_repo_issues_event_min_datetime": "2020-06-13T18:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T16:47:29.000Z", "max_forks_repo_path": "src/python/PyImath/PyImathFun.cpp", "max_forks_repo_name": "JenusL/Imath", "max_forks_repo_head_hexsha": "749a1bfe017b2daccb3eb9759fbe837ea4718a0a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2020-06-16T18:44:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T20:50:06.000Z", "avg_line_length": 33.2190082645, "max_line_length": 117, "alphanum_fraction": 0.5501928101, "num_tokens": 2063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4152376133212064}}
{"text": "/*\n *  Copyright (c) 2008--2011, Universitaet Bremen\n *  All rights reserved.\n *\n *  Author: Christoph Hertzberg <chtz@informatik.uni-bremen.de>\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the Universitaet Bremen nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * @file mtk/src/mtkmath.hpp\n * @brief several math utility functions.\n */\n\n#ifndef MTKMATH_H_\n#define MTKMATH_H_\n\n#include <cmath>\n#include <boost/math/tools/precision.hpp>\n\n#include \"../types/vect.hpp\"\n\n#ifndef M_PI\n#define M_PI  3.1415926535897932384626433832795\n#endif\n\n\nnamespace MTK {\n\nnamespace internal {\n\ntemplate<class Manifold>\nstruct traits {\n\ttypedef typename Manifold::scalar scalar;\n\tenum {DOF = Manifold::DOF};\n\ttypedef vect<DOF, scalar> vectorized_type;\n\ttypedef Eigen::Matrix<scalar, DOF, DOF> matrix_type;\n};\n\ntemplate<>\nstruct traits<float> : traits<Scalar<float> > {};\ntemplate<>\nstruct traits<double> : traits<Scalar<double> > {};\n\n}  // namespace internal\n\n/**\n * \\defgroup MTKMath Mathematical helper functions\n */\n//@{\n\n//! constant @f$ \\pi @f$\nconst double pi = M_PI;\n\ntemplate<class scalar> inline scalar tolerance();\n\ntemplate<> inline float  tolerance<float >() { return 1e-5f; }\ntemplate<> inline double tolerance<double>() { return 1e-11; }\n\n\n/**\n * normalize @a x to @f$[-bound, bound] @f$.\n * \n * result for @f$ x = bound + 2\\cdot n\\cdot bound @f$ is arbitrary @f$\\pm bound @f$.\n */\ntemplate<class scalar>\ninline scalar normalize(scalar x, scalar bound){\n\tif(std::fabs(x) <= bound) return x;\n\tint r = (int)(x *(scalar(1.0)/ bound));\n\treturn x - ((r + (r>>31) + 1) & ~1)*bound; \n}\n\n\n//TODO this implementation might be faster?\ninline double normalize2(double x, double interval){\n\treturn x - interval * (rint(x * (1.0/interval)));\n}\n\n/**\n * Calculate cosine and sinc of sqrt(x2).\n * @param x2 the squared angle must be non-negative\n * @return a pair containing cos and sinc of sqrt(x2)\n */\ntemplate<class scalar>\nstd::pair<scalar, scalar> cos_sinc_sqrt(const scalar &x2){\n\tusing std::sqrt;\n\tusing std::cos;\n\tusing std::sin;\n\tstatic scalar const taylor_0_bound = boost::math::tools::epsilon<scalar>();\n\tstatic scalar const taylor_2_bound = sqrt(taylor_0_bound);\n\tstatic scalar const taylor_n_bound = sqrt(taylor_2_bound);\n\t\n\tassert(x2>=0 && \"argument must be non-negative\");\n\t\n\t// FIXME check if bigger bounds are possible\n\tif(x2>=taylor_n_bound) {\n\t\t// slow fall-back solution\n\t\tscalar x = sqrt(x2);\n\t\treturn std::make_pair(cos(x), sin(x)/x); // x is greater than 0.\n\t}\n\t\n\t// FIXME Replace by Horner-Scheme (4 instead of 5 FLOP/term, numerically more stable, theoretically cos and sinc can be calculated in parallel using SSE2 mulpd/addpd)\n\t// TODO Find optimal coefficients using Remez algorithm\n\tstatic scalar const inv[] = {1/3., 1/4., 1/5., 1/6., 1/7., 1/8., 1/9.};\n\tscalar cosi = 1., sinc=1;\n\tscalar term = -1/2. * x2;\n\tfor(int i=0; i<3; ++i) {\n\t\tcosi += term;\n\t\tterm *= inv[2*i];\n\t\tsinc += term;\n\t\tterm *= -inv[2*i+1] * x2;\n\t}\n\t\n\treturn std::make_pair(cosi, sinc);\n\t\n}\n\n\n\ntemplate<class scalar, int n>\nscalar exp(vectview<scalar, n> result, vectview<const scalar, n> vec, const scalar& scale = 1) {\n\tscalar norm2 = vec.squaredNorm();\n\tstd::pair<scalar, scalar> cos_sinc = cos_sinc_sqrt(scale*scale * norm2);\n\tscalar mult = cos_sinc.second * scale; // == std::sin(alpha) / norm;\n\tresult = mult * vec;\n\treturn cos_sinc.first;\n}\n\n\n/**\n * Inverse function to @c exp.\n * \n * @param result @c vectview to the result\n * @param w      scalar part of input\n * @param vec    vector part of input\n * @param scale  scale result by this value\n * @param plus_minus_periodicity if true values @f$[w, vec]@f$ and @f$[-w, -vec]@f$ give the same result \n */\ntemplate<class scalar, int n>\nvoid log(vectview<scalar, n> result,\n\t\tconst scalar &w, const vectview<const scalar, n> vec,\n\t\tconst scalar &scale, bool plus_minus_periodicity)\n{\n\t// FIXME implement optimized case for vec.squaredNorm() <= tolerance() * (w*w) via Rational Remez approximation ~> only one division\n\tscalar nv = vec.norm();\n\tif(nv < tolerance<scalar>()) {\n\t\tif(!plus_minus_periodicity && w < 0) {\n\t\t\t// find the maximal entry:\n\t\t\tint i;\n\t\t\tnv = vec.cwiseAbs().maxCoeff(&i);\n\t\t\tresult = scale * std::atan2(nv, w) * vect<n, scalar>::Unit(i);\n\t\t\treturn;\n\t\t}\n\t\tnv = tolerance<scalar>();\n\t}\n\tscalar s = scale / nv * (plus_minus_periodicity ? std::atan(nv / w) : std::atan2(nv, w) );\n\t\n\tresult = s * vec;\n}\n\n//@}\n\n} // namespace MTK\n\n\n#endif /* MTKMATH_H_ */\n", "meta": {"hexsha": "e0568185a60ef934edd2e37ae7c743520fb0a7e0", "size": 5845, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/slam_and_orientation/mtk/src/mtkmath.hpp", "max_stars_repo_name": "mfkiwl/ADEKF", "max_stars_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T11:04:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T01:43:07.000Z", "max_issues_repo_path": "examples/slam_and_orientation/mtk/src/mtkmath.hpp", "max_issues_repo_name": "mfkiwl/ADEKF", "max_issues_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/slam_and_orientation/mtk/src/mtkmath.hpp", "max_forks_repo_name": "mfkiwl/ADEKF", "max_forks_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-04-26T09:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T01:43:10.000Z", "avg_line_length": 30.6020942408, "max_line_length": 167, "alphanum_fraction": 0.6942686056, "num_tokens": 1595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4150926209911921}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_FUNCTIONS_GENERIC_REM_PIO2_CEPHES_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_FUNCTIONS_GENERIC_REM_PIO2_CEPHES_HPP_INCLUDED\n#include <nt2/trigonometric/functions/rem_pio2_cephes.hpp>\n#include <nt2/include/functions/simd/round.hpp>\n#include <nt2/include/functions/simd/fast_toint.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/functions/simd/minus.hpp>\n#include <nt2/include/functions/simd/bitwise_and.hpp>\n#include <nt2/include/constants/three.hpp>\n#include <nt2/include/constants/twoopi.hpp>\n#include <nt2/include/constants/pio2_1.hpp>\n#include <nt2/include/constants/pio2_2.hpp>\n#include <nt2/include/constants/pio2_3.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <boost/fusion/include/std_pair.hpp>\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::rem_pio2_cephes_, tag::cpu_\n                            , (A0)(A1)\n                            , (generic_ < floating_<A0> > )\n                              (generic_ < integer_<A1>  > )\n                              (generic_ < floating_<A0> > )\n                            )\n  {\n    typedef void result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& x, A1 & n, A0 & xr)\n    {\n      n = nt2::rem_pio2_cephes(x, xr);\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::rem_pio2_cephes_, tag::cpu_\n                            , (A0)\n                            , (generic_ < floating_<A0> > )\n                            )\n  {\n    typedef typename nt2::meta::as_integer<A0>::type int_t;\n    typedef std::pair<int_t, A0>               result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      result_type res;\n      res.first = nt2::rem_pio2_cephes(a0,res.second);\n      return res;\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::rem_pio2_cephes_, tag::cpu_\n                            , (A0)\n                            , (generic_< floating_<A0> >)\n                              (generic_< floating_<A0> >)\n                            )\n  {\n    typedef typename meta::as_integer<A0>::type result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& x, A0 & xr) const\n    {\n      A0 xi =  nt2::round(x*nt2::Twoopi<A0>());\n      xr  = x-xi*nt2::Pio2_1<A0>();\n      xr -= xi*nt2::Pio2_2<A0>();\n      xr -= xi*nt2::Pio2_3<A0>();\n      return nt2::bitwise_and(nt2::fast_toint(xi), Three<result_type>());\n    }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "5dcd95e3a77c4480004d67c2dcc8c03fd7c334f6", "size": 2923, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/generic/rem_pio2_cephes.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/generic/rem_pio2_cephes.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/functions/generic/rem_pio2_cephes.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4605263158, "max_line_length": 80, "alphanum_fraction": 0.5672254533, "num_tokens": 766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.415092613468761}}
{"text": "/*\n * @Description: Extended Kalman Filter for IMU-Lidar-GNSS-Odo-Mag fusion\n * @Author: Ge Yao\n * @Date: 2020-11-12 15:14:07\n */\n#include <limits>\n\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <ostream>\n\n// use sophus to handle so3 hat & SO3 log operations:\n#include <sophus/so3.hpp>\n\n// SVD for observability analysis:\n#include <Eigen/SVD>\n\n// mag table lookup:\n#include \"lidar_localization/models/mag_table/geo_mag_declination.hpp\"\n\n#include \"lidar_localization/models/kalman_filter/extended_kalman_filter.hpp\"\n\n#include \"lidar_localization/global_defination/global_defination.h\"\n\n#include \"lidar_localization/tools/CSVWriter.hpp\"\n\n#include \"glog/logging.h\"\n\nnamespace lidar_localization {\n\nExtendedKalmanFilter::ExtendedKalmanFilter(const YAML::Node& node) {\n    //\n    // parse config:\n    // \n    // a. earth constants:\n    EARTH.GRAVITY_MAGNITUDE = node[\"earth\"][\"gravity_magnitude\"].as<double>();\n    EARTH.ROTATION_SPEED = node[\"earth\"][\"rotation_speed\"].as<double>();\n   \n    EARTH.LATITUDE = node[\"earth\"][\"latitude\"].as<double>();\n    EARTH.LONGITUDE = node[\"earth\"][\"longitude\"].as<double>();\n    \n    /*\n    // TODO: fix missing dependency mathlib\n    double dec = get_mag_declination(\n        static_cast<float>(EARTH.LATITUDE), static_cast<float>(EARTH.LONGITUDE)\n    );\n    double inc = get_mag_inclination(\n        static_cast<float>(EARTH.LATITUDE), static_cast<float>(EARTH.LONGITUDE)\n    );\n    double mag = get_mag_strength(\n        static_cast<float>(EARTH.LATITUDE), static_cast<float>(EARTH.LONGITUDE)\n    );\n\n    EARTH.MAG.B_U = -mag*sin(inc/180.0*M_PI);\n    EARTH.MAG.B_N = +mag*cos(inc/180.0*M_PI)*cos(dec/180.0*M_PI);\n    EARTH.MAG.B_E = +mag*cos(inc/180.0*M_PI)*sin(dec/180.0*M_PI);\n    */\n\n    EARTH.MAG.B_E = node[\"earth\"][\"magneto\"][\"B_E\"].as<double>();\n    EARTH.MAG.B_N = node[\"earth\"][\"magneto\"][\"B_N\"].as<double>();\n    EARTH.MAG.B_U = node[\"earth\"][\"magneto\"][\"B_U\"].as<double>();\n\n    EARTH.LATITUDE *= M_PI / 180.0;\n\n    // b. prior state covariance:\n    COV.PRIOR.POSI = node[\"covariance\"][\"prior\"][\"pos\"].as<double>();\n    COV.PRIOR.VEL = node[\"covariance\"][\"prior\"][\"vel\"].as<double>();\n    // TODO: find a better way for quaternion orientation prior covariance assignment\n    COV.PRIOR.ORI = node[\"covariance\"][\"prior\"][\"ori\"].as<double>();\n    COV.PRIOR.EPSILON = node[\"covariance\"][\"prior\"][\"epsilon\"].as<double>();\n    COV.PRIOR.DELTA = node[\"covariance\"][\"prior\"][\"delta\"].as<double>();\n    // c. process noise:\n    COV.PROCESS.GYRO = node[\"covariance\"][\"process\"][\"gyro\"].as<double>();\n    COV.PROCESS.ACCEL = node[\"covariance\"][\"process\"][\"accel\"].as<double>();\n    // d. measurement noise:\n    COV.MEASUREMENT.POSE.POSI = node[\"covariance\"][\"measurement\"][\"pose\"][\"pos\"].as<double>();\n    COV.MEASUREMENT.POSE.ORI = node[\"covariance\"][\"measurement\"][\"pose\"][\"ori\"].as<double>();\n    COV.MEASUREMENT.POSI = node[\"covariance\"][\"measurement\"][\"pos\"].as<double>();\n    COV.MEASUREMENT.VEL = node[\"covariance\"][\"measurement\"][\"vel\"].as<double>();\n    COV.MEASUREMENT.MAG = node[\"covariance\"][\"measurement\"][\"mag\"].as<double>();\n    // e. motion constraint:\n    MOTION_CONSTRAINT.ACTIVATED = node[\"motion_constraint\"][\"activated\"].as<bool>();\n    MOTION_CONSTRAINT.W_B_THRESH = node[\"motion_constraint\"][\"w_b_thresh\"].as<double>();\n\n    // prompt:\n    LOG(INFO) << std::endl \n              << \"Iterative Extended Kalman Filter params:\" << std::endl\n              << \"\\tgravity magnitude: \" << EARTH.GRAVITY_MAGNITUDE << std::endl\n              << \"\\tearth rotation speed: \" << EARTH.ROTATION_SPEED << std::endl\n              << \"\\tlatitude: \" << EARTH.LATITUDE << std::endl\n              << \"\\tlongitude: \" << EARTH.LATITUDE << std::endl\n              << \"\\tmagneto: \" << std::endl\n              << \"\\t\\tB_E: \" << EARTH.MAG.B_E << std::endl\n              << \"\\t\\tB_N: \" << EARTH.MAG.B_N << std::endl\n              << \"\\t\\tB_U: \" << EARTH.MAG.B_U << std::endl\n              << std::endl\n              << \"\\tprior cov. pos.: \" << COV.PRIOR.POSI  << std::endl\n              << \"\\tprior cov. vel.: \" << COV.PRIOR.VEL << std::endl\n              << \"\\tprior cov. ori: \" << COV.PRIOR.ORI << std::endl\n              << \"\\tprior cov. epsilon.: \" << COV.PRIOR.EPSILON  << std::endl\n              << \"\\tprior cov. delta.: \" << COV.PRIOR.DELTA << std::endl\n              << std::endl\n              << \"\\tprocess noise gyro.: \" << COV.PROCESS.GYRO << std::endl\n              << \"\\tprocess noise accel.: \" << COV.PROCESS.ACCEL << std::endl\n              << std::endl\n              << \"\\tmeasurement noise pose.: \" << std::endl \n              << \"\\t\\tpos: \" << COV.MEASUREMENT.POSE.POSI << \", ori.: \" << COV.MEASUREMENT.POSE.ORI << std::endl\n              << \"\\tmeasurement noise pos.: \" << COV.MEASUREMENT.POSI << std::endl\n              << \"\\tmeasurement noise vel.: \" << COV.MEASUREMENT.VEL << std::endl\n              << \"\\tmeasurement noise mag.: \" << COV.MEASUREMENT.MAG << std::endl\n              << std::endl\n              << \"\\tmotion constraint: \" << std::endl \n              << \"\\t\\tactivated: \" << (MOTION_CONSTRAINT.ACTIVATED ? \"true\" : \"false\") << std::endl\n              << \"\\t\\tw_b threshold: \" << MOTION_CONSTRAINT.W_B_THRESH << std::endl\n              << std::endl;\n    \n    //\n    // init filter:\n    //\n    // a. earth constants:\n    g_ = Eigen::Vector3d(\n        0.0, \n        0.0, \n        EARTH.GRAVITY_MAGNITUDE\n    );\n    w_ = Eigen::Vector3d(\n        0.0,\n        EARTH.ROTATION_SPEED*cos(EARTH.LATITUDE),\n        EARTH.ROTATION_SPEED*sin(EARTH.LATITUDE)\n    );\n    b_ = Eigen::Vector3d(\n        EARTH.MAG.B_E,\n        EARTH.MAG.B_N,\n        EARTH.MAG.B_U\n    );\n    \n    // b. prior state & covariance:\n    ResetState();\n    ResetCovariance();\n\n    // c. process noise:\n    Q_.block<3, 3>(0, 0) = COV.PROCESS.GYRO*Eigen::Matrix3d::Identity();\n    Q_.block<3, 3>(3, 3) = COV.PROCESS.ACCEL*Eigen::Matrix3d::Identity();\n\n    // d. measurement noise:\n    RPose_.block<3, 3>(0, 0) = COV.MEASUREMENT.POSE.POSI*Eigen::Matrix3d::Identity();\n    RPose_.block<4, 4>(3, 3) = COV.MEASUREMENT.POSE.ORI*Eigen::Matrix4d::Identity();\n\n    RPoseVel_.block<3, 3>(0, 0) = COV.MEASUREMENT.POSE.POSI*Eigen::Matrix3d::Identity();\n    RPoseVel_.block<4, 4>(3, 3) = COV.MEASUREMENT.POSE.ORI*Eigen::Matrix4d::Identity();\n    RPoseVel_.block<3, 3>(7, 7) = COV.MEASUREMENT.VEL*Eigen::Matrix3d::Identity();\n\n    RPosi_.block<3, 3>(0, 0) = COV.MEASUREMENT.POSI*Eigen::Matrix3d::Identity();\n\n    RPosiVel_.block<3, 3>(0, 0) = COV.MEASUREMENT.POSI*Eigen::Matrix3d::Identity();\n    RPosiVel_.block<3, 3>(3, 3) = COV.MEASUREMENT.VEL*Eigen::Matrix3d::Identity();\n\n    RPosiMag_.block<3, 3>(0, 0) = COV.MEASUREMENT.POSI*Eigen::Matrix3d::Identity();\n    RPosiMag_.block<3, 3>(3, 3) = COV.MEASUREMENT.MAG*Eigen::Matrix3d::Identity();\n\n    RPosiVelMag_.block<3, 3>(0, 0) = COV.MEASUREMENT.POSI*Eigen::Matrix3d::Identity();\n    RPosiVelMag_.block<3, 3>(3, 3) = COV.MEASUREMENT.VEL*Eigen::Matrix3d::Identity();\n    RPosiVelMag_.block<3, 3>(6, 6) = COV.MEASUREMENT.MAG*Eigen::Matrix3d::Identity();\n\n    // e. process equation:\n    F_.block<3, 3>( INDEX_POS, INDEX_VEL ) = Eigen::Matrix3d::Identity();\n\n    // f. measurement equation:\n    GPose_.block<3, 3>( 0, INDEX_POS ) = Eigen::Matrix3d::Identity();\n    GPose_.block<4, 4>( 3, INDEX_ORI ) = Eigen::Matrix4d::Identity();\n\n    GPoseVel_.block<3, 3>( 0, INDEX_POS ) = Eigen::Matrix3d::Identity();\n    GPoseVel_.block<4, 4>( 3, INDEX_ORI ) = Eigen::Matrix4d::Identity();\n\n    GPosi_.block<3, 3>( 0, INDEX_POS ) = Eigen::Matrix3d::Identity();\n\n    GPosiVel_.block<3, 3>( 0, INDEX_POS ) = Eigen::Matrix3d::Identity();\n\n    GPosiMag_.block<3, 3>( 0, INDEX_POS ) = Eigen::Matrix3d::Identity();\n\n    GPosiVelMag_.block<3, 3>( 0, INDEX_POS ) = Eigen::Matrix3d::Identity();\n\n    // init soms:\n    QPose_.block<DIM_MEASUREMENT_POSE, DIM_STATE>(0, 0) = GPose_;\n    QPoseVel_.block<DIM_MEASUREMENT_POSE_VEL, DIM_STATE>(0, 0) = GPoseVel_;\n    QPosi_.block<DIM_MEASUREMENT_POSI, DIM_STATE>(0, 0) = GPosi_;\n    QPosiVel_.block<DIM_MEASUREMENT_POSI_VEL, DIM_STATE>(0, 0) = GPosiVel_;\n    QPosiMag_.block<DIM_MEASUREMENT_POSI_MAG, DIM_STATE>(0, 0) = GPosiMag_;\n    QPosVelMag_.block<DIM_MEASUREMENT_POSI_VEL_MAG, DIM_STATE>(0, 0) = GPosiVelMag_;\n}\n\n/**\n * @brief  init filter\n * @param  pose, init pose\n * @param  vel, init vel\n * @param  imu_data, init IMU measurements\n * @return true if success false otherwise\n */\nvoid ExtendedKalmanFilter::Init(\n    const Eigen::Vector3d &vel,\n    const IMUData &imu_data\n) {\n    // get init C_nb from IMU estimation:\n    Eigen::Matrix3d C_nb = imu_data.GetOrientationMatrix().cast<double>();\n    Eigen::Vector4d q_nb(\n        imu_data.orientation.w, \n        imu_data.orientation.x, \n        imu_data.orientation.y, \n        imu_data.orientation.z\n    );\n    // get init v_n from v_b:\n    Eigen::Vector3d v_n = C_nb*vel;\n\n    // set init pose:\n    init_pose_.block<3, 3>(0, 0) = C_nb;\n\n    // set init velocity:\n    init_vel_ = v_n;\n\n    // set init state:\n    X_.block<3, 1>(INDEX_POS, 0) = init_pose_.block<3, 1>(0, 3);\n    X_.block<3, 1>(INDEX_VEL, 0) = v_n;\n    X_.block<4, 1>(INDEX_ORI, 0) = q_nb;\n    X_.block<3, 1>(INDEX_GYRO_BIAS, 0) = gyro_bias_;\n    X_.block<3, 1>(INDEX_ACCEL_BIAS, 0) = accel_bias_;\n\n    // init IMU data buffer:\n    imu_data_buff_.clear();\n    imu_data_buff_.push_back(imu_data);\n\n    // init filter time:\n    time_ = imu_data.time;\n\n    LOG(INFO) << std::endl \n              << \"IEKF Inited at \" << static_cast<int>(time_) << std::endl\n              << \"Init Position: \" \n              << init_pose_(0, 3) << \", \"\n              << init_pose_(1, 3) << \", \"\n              << init_pose_(2, 3) << std::endl\n              << \"Init Velocity: \"\n              << init_vel_.x() << \", \"\n              << init_vel_.y() << \", \"\n              << init_vel_.z() << std::endl;\n}\n\n/**\n * @brief  Kalman update\n * @param  imu_data, input IMU measurements\n * @return true if success false otherwise\n */\nbool ExtendedKalmanFilter::Update(const IMUData &imu_data) {\n    // update IMU buff:\n    if (time_ < imu_data.time) {\n        // Kalman prediction for covariance:\n        UpdateCovarianceEstimation(imu_data);\n\n        // Kalman prediction for state:\n        imu_data_buff_.push_back(imu_data);\n        UpdateStateEstimation();\n        imu_data_buff_.pop_front();\n        \n        // move forward:\n        time_ = imu_data.time;\n\n        return true;\n    }\n\n    return false;\n}\n\n/**\n * @brief  Kalman correction, pose measurement and other measurement in body frame\n * @param  measurement_type, input measurement type\n * @param  measurement, input measurement\n * @return void                                   \n */\nbool ExtendedKalmanFilter::Correct(\n    const IMUData &imu_data, \n    const MeasurementType &measurement_type, const Measurement &measurement\n) { \n    static Measurement measurement_;\n\n    // get time delta:\n    double time_delta = measurement.time - time_;\n\n    if ( time_delta > -0.05 ) {\n        // perform Kalman prediction:\n        if ( time_ < measurement.time ) {\n            Update(imu_data);\n        }\n\n        // get observation in navigation frame:\n        measurement_ = measurement;\n        measurement_.T_nb = init_pose_ * measurement_.T_nb;\n\n        // correct error estimation:\n        CorrectStateEstimation(measurement_type, measurement_);\n\n        return true;\n    }\n\n    LOG(INFO) << \"IEKF Correct: Observation is not synced with filter. Skip, \" \n              << (int)measurement.time << \" <-- \" << (int)time_ << \" @ \" << time_delta\n              << std::endl; \n    \n    return false;\n}\n\n/**\n * @brief  get odometry estimation\n * @param  pose, init pose\n * @param  vel, init vel\n * @return void\n */\nvoid ExtendedKalmanFilter::GetOdometry(\n    Eigen::Matrix4f &pose, Eigen::Vector3f &vel\n) {\n    // init:\n    Eigen::Matrix4d pose_double = Eigen::Matrix4d::Identity();\n    Eigen::Vector3d vel_double = Eigen::Vector3d::Zero();\n\n    // eliminate error:\n    // a. position:\n    pose_double.block<3, 1>(0, 3) = X_.block<3, 1>(INDEX_POS, 0);\n    // b. velocity:\n    vel_double = X_.block<3, 1>(INDEX_VEL, 0);\n    // c. orientation:\n    Eigen::Quaterniond q_nb(\n        X_(INDEX_ORI + 0, 0),\n        X_(INDEX_ORI + 1, 0),\n        X_(INDEX_ORI + 2, 0),\n        X_(INDEX_ORI + 3, 0)\n    );\n    pose_double.block<3, 3>(0, 0) = q_nb.toRotationMatrix();\n\n    // finally:\n    pose_double = init_pose_.inverse() * pose_double;\n    vel_double = init_pose_.block<3, 3>(0, 0).transpose() * vel_double;\n\n    pose = pose_double.cast<float>();\n    vel = vel_double.cast<float>();\n}\n\n/**\n * @brief  get covariance estimation\n * @param  cov, covariance output\n * @return void\n */\nvoid ExtendedKalmanFilter::GetCovariance(Cov &cov) {\n    static int OFFSET_X = 0;\n    static int OFFSET_Y = 1;\n    static int OFFSET_Z = 2;\n\n    // a. delta position:\n    cov.pos.x = P_(INDEX_POS + OFFSET_X, INDEX_POS + OFFSET_X);\n    cov.pos.y = P_(INDEX_POS + OFFSET_Y, INDEX_POS + OFFSET_Y);\n    cov.pos.z = P_(INDEX_POS + OFFSET_Z, INDEX_POS + OFFSET_Z);\n\n    // b. delta velocity:\n    cov.vel.x = P_(INDEX_VEL + OFFSET_X, INDEX_VEL + OFFSET_X);\n    cov.vel.y = P_(INDEX_VEL + OFFSET_Y, INDEX_VEL + OFFSET_Y);\n    cov.vel.z = P_(INDEX_VEL + OFFSET_Z, INDEX_VEL + OFFSET_Z);\n\n    // c. delta orientation:\n    cov.ori.w = P_(INDEX_ORI + 0, INDEX_ORI + 0);\n    cov.ori.x = P_(INDEX_ORI + 1, INDEX_ORI + 1);\n    cov.ori.y = P_(INDEX_ORI + 2, INDEX_ORI + 2);\n    cov.ori.z = P_(INDEX_ORI + 3, INDEX_ORI + 3);\n\n    // d. gyro. bias:\n    cov.gyro_bias.x = P_(INDEX_GYRO_BIAS + OFFSET_X, INDEX_GYRO_BIAS + OFFSET_X);\n    cov.gyro_bias.y = P_(INDEX_GYRO_BIAS + OFFSET_Y, INDEX_GYRO_BIAS + OFFSET_Y);\n    cov.gyro_bias.z = P_(INDEX_GYRO_BIAS + OFFSET_Z, INDEX_GYRO_BIAS + OFFSET_Z);\n\n    // e. accel bias:\n    cov.accel_bias.x = P_(INDEX_ACCEL_BIAS + OFFSET_X, INDEX_ACCEL_BIAS + OFFSET_X);\n    cov.accel_bias.y = P_(INDEX_ACCEL_BIAS + OFFSET_Y, INDEX_ACCEL_BIAS + OFFSET_Y);\n    cov.accel_bias.z = P_(INDEX_ACCEL_BIAS + OFFSET_Z, INDEX_ACCEL_BIAS + OFFSET_Z);\n}\n\n/**\n * @brief  get unbiased angular velocity in body frame\n * @param  angular_vel, angular velocity measurement\n * @param  C_nb, corresponding orientation of measurement\n * @return unbiased angular velocity in body frame\n */\ninline Eigen::Vector3d ExtendedKalmanFilter::GetUnbiasedAngularVel(\n    const Eigen::Vector3d &angular_vel,\n    const Eigen::Matrix3d &C_nb\n) {\n    return angular_vel - gyro_bias_;\n}\n\n/**\n * @brief  get unbiased linear acceleration in navigation frame\n * @param  linear_acc, linear acceleration measurement\n * @param  C_nb, corresponding orientation of measurement\n * @return unbiased linear acceleration in navigation frame\n */\ninline Eigen::Vector3d ExtendedKalmanFilter::GetUnbiasedLinearAcc(\n    const Eigen::Vector3d &linear_acc,\n    const Eigen::Matrix3d &C_nb\n) {\n    return C_nb*(linear_acc - accel_bias_) - g_;\n}\n\n/**\n * @brief  remove gravity component from accel measurement\n * @param  f_b, accel measurement measurement\n * @param  C_nb, orientation matrix\n * @return f_b\n */\ninline Eigen::Vector3d ExtendedKalmanFilter::RemoveGravity (\n    const Eigen::Vector3d &f_b,\n    const Eigen::Matrix3d &C_nb\n) {\n    return f_b - C_nb.transpose()*g_;\n}\n\n/**\n * @brief  apply motion constraint on velocity estimation\n * @param  void\n * @return void\n */\nvoid ExtendedKalmanFilter::ApplyMotionConstraint(void) {\n    const Eigen::Quaterniond q_nb(\n        X_( INDEX_ORI + 0, 0),\n        X_( INDEX_ORI + 1, 0),\n        X_( INDEX_ORI + 2, 0),\n        X_( INDEX_ORI + 3, 0)\n    );\n    const Eigen::Matrix3d C_nb = q_nb.toRotationMatrix();\n\n    Eigen::Vector3d v_b = C_nb.transpose() * X_.block<3, 1>( INDEX_VEL, 0 );\n    v_b.y() = 0.0;\n    X_.block<3, 1>( INDEX_VEL, 0 ) = C_nb * v_b;\n}\n\n/**\n * @brief  get angular delta\n * @param  index_curr, current imu measurement buffer index\n * @param  index_prev, previous imu measurement buffer index\n * @param  angular_delta, angular delta output\n * @return true if success false otherwise\n */\nbool ExtendedKalmanFilter::GetAngularDelta(\n    const size_t index_curr, const size_t index_prev,\n    Eigen::Vector3d &angular_delta\n) {\n    if (\n        index_curr <= index_prev ||\n        imu_data_buff_.size() <= index_curr\n    ) {\n        return false;\n    }\n\n    const IMUData &imu_data_curr = imu_data_buff_.at(index_curr);\n    const IMUData &imu_data_prev = imu_data_buff_.at(index_prev);\n\n    double delta_t = imu_data_curr.time - imu_data_prev.time;\n\n    Eigen::Vector3d angular_vel_curr = Eigen::Vector3d(\n        imu_data_curr.angular_velocity.x,\n        imu_data_curr.angular_velocity.y,\n        imu_data_curr.angular_velocity.z\n    );\n    Eigen::Matrix3d R_curr = imu_data_curr.GetOrientationMatrix().cast<double>();\n    angular_vel_curr = GetUnbiasedAngularVel(angular_vel_curr, R_curr);\n\n    Eigen::Vector3d angular_vel_prev = Eigen::Vector3d(\n        imu_data_prev.angular_velocity.x,\n        imu_data_prev.angular_velocity.y,\n        imu_data_prev.angular_velocity.z\n    );\n    Eigen::Matrix3d R_prev = imu_data_prev.GetOrientationMatrix().cast<double>();\n    angular_vel_prev = GetUnbiasedAngularVel(angular_vel_prev, R_prev);\n\n    angular_delta = 0.5*delta_t*(angular_vel_curr + angular_vel_prev);\n\n    return true;\n}\n\n/**\n * @brief  update orientation with effective rotation angular_delta\n * @param  angular_delta, effective rotation\n * @param  R_curr, current orientation\n * @param  R_prev, previous orientation\n * @return void\n */\nvoid ExtendedKalmanFilter::UpdateOrientation(\n    const Eigen::Vector3d &angular_delta,\n    Eigen::Matrix3d &R_curr, Eigen::Matrix3d &R_prev\n) {\n    // magnitude:\n    double angular_delta_mag = angular_delta.norm();\n    // direction:\n    Eigen::Vector3d angular_delta_dir = angular_delta.normalized();\n\n    // build delta q:\n    double angular_delta_cos = cos(angular_delta_mag/2.0);\n    double angular_delta_sin = sin(angular_delta_mag/2.0);\n\n    Eigen::Quaterniond q(\n        X_(INDEX_ORI + 0, 0),\n        X_(INDEX_ORI + 1, 0),\n        X_(INDEX_ORI + 2, 0),\n        X_(INDEX_ORI + 3, 0)\n    );\n    Eigen::Quaterniond dq(\n        angular_delta_cos, \n        angular_delta_sin*angular_delta_dir.x(), \n        angular_delta_sin*angular_delta_dir.y(), \n        angular_delta_sin*angular_delta_dir.z()\n    );\n\n    // update:\n    R_prev = q.toRotationMatrix();\n\n    q = q*dq;\n    q.normalize();\n\n    R_curr = q.toRotationMatrix();\n\n    // write back:\n    X_(INDEX_ORI + 0, 0) = q.w();\n    X_(INDEX_ORI + 1, 0) = q.x();\n    X_(INDEX_ORI + 2, 0) = q.y();\n    X_(INDEX_ORI + 3, 0) = q.z();\n}\n\n/**\n * @brief  get velocity delta\n * @param  index_curr, current imu measurement buffer index\n * @param  index_prev, previous imu measurement buffer index\n * @param  R_curr, corresponding orientation of current imu measurement\n * @param  R_prev, corresponding orientation of previous imu measurement\n * @param  velocity_delta, velocity delta output\n * @param  linear_acc_mid, mid-value unbiased linear acc\n * @return true if success false otherwise\n */\nbool ExtendedKalmanFilter::GetVelocityDelta(\n    const size_t index_curr, const size_t index_prev,\n    const Eigen::Matrix3d &R_curr, const Eigen::Matrix3d &R_prev, \n    double &T, \n    Eigen::Vector3d &velocity_delta\n) {\n    if (\n        index_curr <= index_prev ||\n        imu_data_buff_.size() <= index_curr\n    ) {\n        return false;\n    }\n\n    const IMUData &imu_data_curr = imu_data_buff_.at(index_curr);\n    const IMUData &imu_data_prev = imu_data_buff_.at(index_prev);\n\n    T = imu_data_curr.time - imu_data_prev.time;\n\n    Eigen::Vector3d linear_acc_curr = Eigen::Vector3d(\n        imu_data_curr.linear_acceleration.x,\n        imu_data_curr.linear_acceleration.y,\n        imu_data_curr.linear_acceleration.z\n    );\n    linear_acc_curr = GetUnbiasedLinearAcc(linear_acc_curr, R_curr);\n    Eigen::Vector3d linear_acc_prev = Eigen::Vector3d(\n        imu_data_prev.linear_acceleration.x,\n        imu_data_prev.linear_acceleration.y,\n        imu_data_prev.linear_acceleration.z\n    );\n    linear_acc_prev = GetUnbiasedLinearAcc(linear_acc_prev, R_prev);\n    \n    // mid-value acc can improve error state prediction accuracy:\n    velocity_delta = 0.5*T*(linear_acc_curr + linear_acc_prev);\n\n    return true;\n}\n\n/**\n * @brief  update orientation with effective velocity change velocity_delta\n * @param  T, timestamp delta \n * @param  velocity_delta, effective velocity change\n * @return void\n */\nvoid ExtendedKalmanFilter::UpdatePosition(const double &T, const Eigen::Vector3d &velocity_delta) {\n    X_.block<3, 1>(INDEX_POS, 0) += T*X_.block<3, 1>(INDEX_VEL, 0) + 0.5*T*velocity_delta;\n    X_.block<3, 1>(INDEX_VEL, 0) += velocity_delta;\n}\n\n/**\n * @brief  update state estimation\n * @param  void\n * @return void\n */\nvoid ExtendedKalmanFilter::UpdateStateEstimation(void) {\n    // get deltas:\n    Eigen::Vector3d angular_delta; \n    GetAngularDelta(1, 0, angular_delta);\n\n    // update orientation:\n    Eigen::Matrix3d R_curr, R_prev;\n    UpdateOrientation(angular_delta, R_curr, R_prev);\n\n    // get velocity delta:\n    double T;\n    Eigen::Vector3d velocity_delta;\n    // save mid-value unbiased linear acc for error-state update:\n    GetVelocityDelta(1, 0, R_curr, R_prev, T, velocity_delta);\n\n    // update position:\n    UpdatePosition(T, velocity_delta);\n\n    // apply motion constraint:\n    ApplyMotionConstraint();\n}\n\n/**\n * @brief  get block matrix for velocity update by orientation quaternion\n * @param  f_b, accel measurement\n * @param  q_nb, orientation quaternion\n * @return block matrix Fvq\n */\nEigen::Matrix<double, 3, 4> ExtendedKalmanFilter::GetFVelOri(\n    const Eigen::Vector3d &f_b,\n    const Eigen::Quaterniond &q_nb\n) {\n    // get F:\n    Eigen::Matrix<double, 4, 3> T_Ff;\n    T_Ff << +q_nb.w(), -q_nb.z(), +q_nb.y(),\n            +q_nb.x(), +q_nb.y(), +q_nb.z(),\n            -q_nb.y(), +q_nb.x(), +q_nb.w(),\n            -q_nb.z(), -q_nb.w(), +q_nb.x();\n    Eigen::Vector4d F = 2 * T_Ff * f_b;\n\n    // get Fvq:\n    Eigen::Matrix<double, 3, 4> Fvq;\n    Fvq << +F(0), +F(1), +F(2), +F(3),\n           -F(3), -F(2), +F(1), +F(0),\n           +F(2), -F(3), -F(0), +F(1);\n\n    return Fvq;\n}\n\n/**\n * @brief  get block matrix for orientation quaternion update by orientation quaternion\n * @param  w_b, gyro measurement\n * @return block matrix Fqq\n */\nEigen::Matrix<double, 4, 4> ExtendedKalmanFilter::GetFOriOri(\n    const Eigen::Vector3d &w_b\n) {\n    // get Fqq:\n    Eigen::Matrix<double, 4, 4> Fqq;\n    Fqq <<      0.0, -w_b.x(), -w_b.y(), -w_b.z(),\n           +w_b.x(),      0.0, +w_b.z(), -w_b.y(),\n           +w_b.y(), -w_b.z(),      0.0, +w_b.x(),\n           +w_b.z(), +w_b.y(), -w_b.x(),      0.0;\n\n    return 0.5 * Fqq;\n}\n\n/**\n * @brief  get block matrix for orientation quaternion update by epsilon, angular velocity bias\n * @param  q_nb, orientation quaternion\n * @return block matrix Fqe\n */\nEigen::Matrix<double, 4, 3> ExtendedKalmanFilter::GetFOriEps(\n    const Eigen::Quaterniond &q_nb\n) {\n    // get Fqe:\n    Eigen::Matrix<double, 4, 3> Fqe;\n    Fqe << -q_nb.x(), -q_nb.y(), -q_nb.z(),\n           +q_nb.w(), -q_nb.z(), +q_nb.y(),\n           +q_nb.z(), +q_nb.w(), -q_nb.x(),\n           -q_nb.y(), +q_nb.x(), +q_nb.w();\n\n    return 0.5 * Fqe;\n}\n\n/**\n * @brief  set process equation\n * @param  void\n * @return void\n */\nvoid ExtendedKalmanFilter::SetProcessEquation(const IMUData &imu_data) {\n    // parse IMU measurement:\n    const Eigen::Vector3d f_b(\n        imu_data.linear_acceleration.x,\n        imu_data.linear_acceleration.y,\n        imu_data.linear_acceleration.z\n    );\n    const Eigen::Vector3d w_b(\n        imu_data.angular_velocity.x,\n        imu_data.angular_velocity.y,\n        imu_data.angular_velocity.z\n    );\n\n    // parse orientation:\n    const Eigen::Quaterniond q_nb(\n        X_(INDEX_ORI + 0, 0),\n        X_(INDEX_ORI + 1, 0),\n        X_(INDEX_ORI + 2, 0),\n        X_(INDEX_ORI + 3, 0)\n    );\n    const Eigen::Matrix3d C_nb = q_nb.toRotationMatrix();\n\n    //\n    // EKF is linearized around VectorX::Zero\n    //\n    // a. set equation for velocity:\n    F_.block<3, 4>(INDEX_VEL,         INDEX_ORI) = GetFVelOri(f_b, q_nb);\n    F_.block<3, 3>(INDEX_VEL,  INDEX_ACCEL_BIAS) = B_.block<3, 3>(INDEX_VEL, 3) = C_nb;\n    \n    // b. set equation for orientation quaternion:\n    F_.block<4, 4>(INDEX_ORI,         INDEX_ORI) = GetFOriOri(w_b);\n    F_.block<4, 3>(INDEX_ORI,   INDEX_GYRO_BIAS) = B_.block<4, 3>(INDEX_ORI, 0) = GetFOriEps(q_nb);\n}\n\n/**\n * @brief  update covariance estimation\n * @param  void\n * @return void\n */\nvoid ExtendedKalmanFilter::UpdateCovarianceEstimation(\n    const IMUData &imu_data\n) {\n    // update process equation:\n    SetProcessEquation(imu_data);\n\n    // get discretized process equations:\n    double T = imu_data.time - time_;\n\n    // approximate to 1st order:\n    MatrixF F = MatrixF::Identity() + T*F_;\n\n    MatrixB B = T*B_;\n\n    // perform Kalman prediction for covariance:\n    P_ = F*P_*F.transpose() + B*Q_*B.transpose();\n}\n\n/**\n * @brief  get block matrix for observation by orientation quaternion\n * @param  m_n, measurement in navigation frame\n * @param  q_nb, orientation quaternion\n * @return block matrix Gq\n */\nEigen::Matrix<double, 3, 4> ExtendedKalmanFilter::GetGMOri(\n    const Eigen::Vector3d &m_n,\n    const Eigen::Quaterniond &q_nb\n) {\n    // get F:\n    Eigen::Matrix<double, 4, 3> T_Gm;\n    T_Gm << +q_nb.w(), +q_nb.z(), -q_nb.y(),\n            +q_nb.x(), +q_nb.y(), +q_nb.z(),\n            -q_nb.y(), +q_nb.x(), -q_nb.w(),\n            -q_nb.z(), +q_nb.w(), +q_nb.x();\n    Eigen::Vector4d G = 2 * T_Gm * m_n;\n\n    // get Fvq:\n    Eigen::Matrix<double, 3, 4> Gq;\n    Gq << +G(0), +G(1), +G(2), +G(3),\n          +G(3), -G(2), +G(1), -G(0),\n          -G(2), -G(3), +G(0), +G(1);\n\n    return Gq;\n}\n\n/**\n * @brief  correct state estimation using frontend pose\n * @param  T_nb, input frontend pose estimation\n * @return void\n */\nvoid ExtendedKalmanFilter::CorrectStateEstimationPose(\n    const Eigen::Matrix4d &T_nb\n) {\n    // parse measurement:\n    YPose_.block<3, 1>(0, 0) = T_nb.block<3, 1>(0,3);\n    Eigen::Quaterniond q_nb(T_nb.block<3, 3>(0,0));\n    YPose_(3, 0) = q_nb.w();\n    YPose_(4, 0) = q_nb.x();\n    YPose_(5, 0) = q_nb.y();\n    YPose_(6, 0) = q_nb.z();\n\n    // build Kalman gain:\n    MatrixRPose R = GPose_*P_*GPose_.transpose() + RPose_;\n    MatrixKPose K = P_*GPose_.transpose()*R.inverse();\n\n    // perform Kalman correct:\n    P_ = (MatrixP::Identity() - K*GPose_)*P_;\n    X_ = X_ + K*(YPose_ - GPose_*X_);\n\n    // normalize quaternion:\n    X_.block<4, 1>( INDEX_ORI, 0 ).normalize();\n}\n\n/**\n * @brief  correct state estimation using GNSS position\n * @param  T_nb, input GNSS position\n * @return void\n */\nvoid ExtendedKalmanFilter::CorrectStateEstimationPosi(\n    const Eigen::Matrix4d &T_nb\n) {\n    // parse measurement:\n    YPosi_.block<3, 1>(0, 0) = T_nb.block<3, 1>(0,3);\n\n    // build Kalman gain:\n    MatrixRPosi R = GPosi_*P_*GPosi_.transpose() + RPosi_;\n    MatrixKPosi K = P_*GPosi_.transpose()*R.inverse();\n\n    // perform Kalman correct:\n    P_ = (MatrixP::Identity() - K*GPosi_)*P_;\n    X_ = X_ + K*(YPosi_ - GPosi_*X_);\n\n    // normalize quaternion:\n    X_.block<4, 1>( INDEX_ORI, 0 ).normalize();\n}\n\n/**\n * @brief  correct state estimation using frontend pose & body velocity measurement\n * @param  T_nb, input frontend pose estimation\n * @param  v_b, input odo\n * @return void\n */\nvoid ExtendedKalmanFilter::CorrectStateEstimationPoseVel(\n    const Eigen::Matrix4d &T_nb, \n    const Eigen::Vector3d &v_b\n) {\n    // parse measurement:\n    YPoseVel_.block<3, 1>(0, 0) = T_nb.block<3, 1>(0,3);\n\n    Eigen::Quaterniond q_nb_obs(T_nb.block<3, 3>(0,0));\n    YPoseVel_(3, 0) = q_nb_obs.w();\n    YPoseVel_(4, 0) = q_nb_obs.x();\n    YPoseVel_(5, 0) = q_nb_obs.y();\n    YPoseVel_(6, 0) = q_nb_obs.z();\n\n    YPoseVel_.block<3, 1>(7, 0) = v_b;\n\n    // iterative observation:\n    for (size_t i = 0; i < 3; ++i) {\n        // set observation equation:\n        Eigen::Quaterniond q_nb_pred(\n            X_(INDEX_ORI + 0, 0),\n            X_(INDEX_ORI + 1, 0),\n            X_(INDEX_ORI + 2, 0),\n            X_(INDEX_ORI + 3, 0)\n        );\n        Eigen::Matrix3d C_nb_pred = q_nb_pred.toRotationMatrix();\n        GPoseVel_.block<3, 3>( 7, INDEX_VEL ) = C_nb_pred.transpose();\n        GPoseVel_.block<3, 4>( 7, INDEX_ORI ) = GetGMOri(X_.block<3, 1>(INDEX_VEL, 0), q_nb_pred);\n\n        // build Kalman gain:\n        MatrixRPoseVel R = GPoseVel_*P_*GPoseVel_.transpose() + RPoseVel_;\n        MatrixKPoseVel K = P_*GPoseVel_.transpose()*R.inverse();\n        VectorYPoseVel Y = VectorYPoseVel::Zero();\n        Y.block<3, 1>(0, 0) = X_.block<3, 1>(INDEX_POS, 0);\n        Y.block<4, 1>(3, 0) = X_.block<4, 1>(INDEX_ORI, 0);\n        Y.block<3, 1>(7, 0) = C_nb_pred.transpose() * X_.block<3, 1>(INDEX_VEL, 0);\n\n        // perform Kalman correct:\n        P_ = (MatrixP::Identity() - K*GPoseVel_)*P_;\n        X_ = X_ + K*(YPoseVel_ - Y);\n\n        // normalize quaternion:\n        X_.block<4, 1>( INDEX_ORI, 0 ).normalize();\n    }\n}\n\n/**\n * @brief  correct state estimation using GNSS position and odometer measurement\n * @param  T_nb, input GNSS position \n * @param  v_b, input odo\n * @return void\n */\nvoid ExtendedKalmanFilter::CorrectStateEstimationPosiVel(\n    const Eigen::Matrix4d &T_nb, const Eigen::Vector3d &v_b\n) {\n    // parse measurement:\n    YPosiVel_.block<3, 1>(0, 0) = T_nb.block<3, 1>(0,3);\n    YPosiVel_.block<3, 1>(3, 0) = v_b;\n\n    // iterative observation:\n    for (size_t i = 0; i < 1; ++i) {\n        // set observation equation:\n        Eigen::Quaterniond q_nb(\n            X_(INDEX_ORI + 0, 0),\n            X_(INDEX_ORI + 1, 0),\n            X_(INDEX_ORI + 2, 0),\n            X_(INDEX_ORI + 3, 0)\n        );\n        Eigen::Matrix3d C_nb = q_nb.toRotationMatrix();\n        GPosiVel_.block<3, 3>( 3, INDEX_VEL ) = C_nb.transpose();\n        GPosiVel_.block<3, 4>( 3, INDEX_ORI ) = GetGMOri(X_.block<3, 1>(INDEX_VEL, 0), q_nb);\n\n        // build Kalman gain:\n        MatrixRPosiVel R = GPosiVel_*P_*GPosiVel_.transpose() + RPosiVel_;\n        MatrixKPosiVel K = P_*GPosiVel_.transpose()*R.inverse();\n        VectorYPosiVel Y = X_.block<6, 1>(0, 0);\n        Y.block<3, 1>(3, 0) = C_nb.transpose() * Y.block<3, 1>(3, 0);\n\n        // perform Kalman correct:\n        P_ = (MatrixP::Identity() - K*GPosiVel_)*P_;\n        X_ = X_ + K*(YPosiVel_ - Y);\n        \n        // normalize quaternion:\n        X_.block<4, 1>( INDEX_ORI, 0 ).normalize();\n    }\n}\n\n/**\n * @brief  correct state estimation using GNSS position and magneto measurement\n * @param  T_nb, input GNSS position \n * @param  B_b, input magneto\n * @return void\n */\nvoid ExtendedKalmanFilter::CorrectStateEstimationPosiMag(\n    const Eigen::Matrix4d &T_nb, const Eigen::Vector3d &B_b\n) {\n    // parse measurement:\n    YPosiMag_.block<3, 1>(0, 0) = T_nb.block<3, 1>(0,3);\n    YPosiMag_.block<3, 1>(3, 0) = B_b;\n\n    // iterative observation:\n    for (size_t i = 0; i < 1; ++i) {\n        // set observation equation:\n        const Eigen::Quaterniond q_nb(\n            X_(INDEX_ORI + 0, 0),\n            X_(INDEX_ORI + 1, 0),\n            X_(INDEX_ORI + 2, 0),\n            X_(INDEX_ORI + 3, 0)\n        );\n        Eigen::Matrix3d C_nb = q_nb.toRotationMatrix();\n        GPosiMag_.block<3, 4>( 3, INDEX_ORI ) = GetGMOri(b_, q_nb);\n\n        // build Kalman gain:\n        MatrixRPosiMag R = GPosiMag_*P_*GPosiMag_.transpose() + RPosiMag_;\n        MatrixKPosiMag K = P_*GPosiMag_.transpose()*R.inverse();\n        VectorYPosiMag Y = VectorYPosiMag::Zero();\n        Y.block<3, 1>(0, 0) = X_.block<3, 1>( INDEX_POS, 0);\n        Y.block<3, 1>(3, 0) = C_nb.transpose() * b_;\n\n        // perform Kalman correct:\n        P_ = (MatrixP::Identity() - K*GPosiMag_)*P_;\n        X_ = X_ + K*(YPosiMag_ - Y);\n\n        // normalize quaternion:\n        X_.block<4, 1>( INDEX_ORI, 0 ).normalize();\n    }\n}\n\n/**\n * @brief  correct state estimation using GNSS position, odometer and magneto measurement\n * @param  T_nb, input GNSS position \n * @param  v_b, input odo\n * @param  B_b, input magneto\n * @return void\n */\nvoid ExtendedKalmanFilter::CorrectStateEstimationPosiVelMag(\n    const Eigen::Matrix4d &T_nb, const Eigen::Vector3d &v_b, const Eigen::Vector3d &B_b\n) {\n    // parse measurement:\n    YPosiVelMag_.block<3, 1>(0, 0) = T_nb.block<3, 1>(0,3);\n    YPosiVelMag_.block<3, 1>(3, 0) = v_b;\n    YPosiVelMag_.block<3, 1>(6, 0) = B_b;\n\n    // iterative observation:\n    for (size_t i = 0; i < 1; ++i) {\n        // set observation equation:\n        const Eigen::Quaterniond q_nb(\n            X_(INDEX_ORI + 0, 0),\n            X_(INDEX_ORI + 1, 0),\n            X_(INDEX_ORI + 2, 0),\n            X_(INDEX_ORI + 3, 0)\n        );\n        Eigen::Matrix3d C_nb = q_nb.toRotationMatrix();\n        GPosiVelMag_.block<3, 3>( 3, INDEX_VEL ) = C_nb.transpose();\n        GPosiVelMag_.block<3, 4>( 3, INDEX_ORI ) = GetGMOri(X_.block<3, 1>(INDEX_VEL, 0), q_nb);\n        GPosiVelMag_.block<3, 4>( 6, INDEX_ORI ) = GetGMOri(b_, q_nb);\n\n        // build Kalman gain:\n        MatrixRPosiVelMag R = GPosiVelMag_*P_*GPosiVelMag_.transpose() + RPosiVelMag_;\n        MatrixKPosiVelMag K = P_*GPosiVelMag_.transpose()*R.inverse();\n        VectorYPosiVelMag Y = VectorYPosiVelMag::Zero();\n        Y.block<3, 1>(0, 0) = X_.block<3, 1>( INDEX_POS, 0);\n        Y.block<3, 1>(3, 0) = C_nb.transpose() * X_.block<3, 1>(INDEX_VEL, 0);\n        Y.block<3, 1>(6, 0) = C_nb.transpose() * b_;\n        \n        // perform Kalman correct:\n        P_ = (MatrixP::Identity() - K*GPosiVelMag_)*P_;\n        X_ = X_ + K*(YPosiVelMag_ - Y);\n\n        // normalize quaternion:\n        X_.block<4, 1>( INDEX_ORI, 0 ).normalize();\n    }\n}\n\n/**\n * @brief  correct state estimation\n * @param  measurement_type, measurement type\n * @param  measurement, input measurement\n * @return void\n */\nvoid ExtendedKalmanFilter::CorrectStateEstimation(\n    const MeasurementType &measurement_type, \n    const Measurement &measurement\n) {\n    switch ( measurement_type ) {\n        case MeasurementType::POSE:\n            CorrectStateEstimationPose(measurement.T_nb);\n            break;\n        case MeasurementType::POSE_VEL:\n            CorrectStateEstimationPoseVel(measurement.T_nb, measurement.v_b);\n            break;\n        case MeasurementType::POSI:\n            CorrectStateEstimationPosi(measurement.T_nb);\n            break;\n        case MeasurementType::POSI_VEL:\n            CorrectStateEstimationPosiVel(measurement.T_nb, measurement.v_b);\n            break;\n        case MeasurementType::POSI_MAG:\n            CorrectStateEstimationPosiMag(measurement.T_nb, measurement.B_b);\n            break;\n        case MeasurementType::POSI_VEL_MAG:\n            CorrectStateEstimationPosiVelMag(measurement.T_nb, measurement.v_b, measurement.B_b);\n            break;\n        default:\n            break;\n    }\n\n    // update bias:\n    if ( IsCovStable(INDEX_GYRO_BIAS, 1.0e-6) )  gyro_bias_ = X_.block<3, 1>(INDEX_GYRO_BIAS, 0);\n    if ( IsCovStable(INDEX_ACCEL_BIAS, 1.0e-6) ) accel_bias_ = X_.block<3, 1>(INDEX_ACCEL_BIAS, 0);\n}\n\n/**\n * @brief  is covariance stable\n * @param  INDEX_OFFSET, state index offset\n * @param  THRESH, covariance threshold, defaults to 1.0e-5\n * @return void\n */\nbool ExtendedKalmanFilter::IsCovStable(\n    const int INDEX_OFFSET,\n    const double THRESH\n) {\n    if ( INDEX_ORI == INDEX_OFFSET ) {\n        for (int i = 0; i < 4; ++i) {\n            if ( P_(INDEX_OFFSET + i, INDEX_OFFSET + i) > THRESH ) {\n                return false;\n            }\n        }\n    } else {\n        for (int i = 0; i < 3; ++i) {\n            if ( P_(INDEX_OFFSET + i, INDEX_OFFSET + i) > THRESH ) {\n                return false;\n            }\n        }\n    }\n\n    return true;\n}\n\n/**\n * @brief  reset filter state\n * @param  void\n * @return void\n */\nvoid ExtendedKalmanFilter::ResetState(void) {\n    // reset current state:\n    X_ = VectorX::Zero();\n}\n\n/**\n * @brief  reset filter covariance\n * @param  void\n * @return void\n */\nvoid ExtendedKalmanFilter::ResetCovariance(void) {\n    P_ = MatrixP::Zero();\n    \n    P_.block<3, 3>(       INDEX_POS,        INDEX_POS) = COV.PRIOR.POSI*Eigen::Matrix3d::Identity();\n    P_.block<3, 3>(       INDEX_VEL,        INDEX_VEL) = COV.PRIOR.VEL*Eigen::Matrix3d::Identity();\n    // TODO: find a better way for quaternion orientation prior covariance assignment\n    P_.block<4, 4>(       INDEX_ORI,        INDEX_ORI) = COV.PRIOR.ORI*Eigen::Matrix4d::Identity();\n    P_.block<3, 3>( INDEX_GYRO_BIAS,  INDEX_GYRO_BIAS) = COV.PRIOR.EPSILON*Eigen::Matrix3d::Identity();\n    P_.block<3, 3>(INDEX_ACCEL_BIAS, INDEX_ACCEL_BIAS) = COV.PRIOR.DELTA*Eigen::Matrix3d::Identity();\n}\n\n/**\n * @brief  get Q for pose measurement\n * @param  void\n * @return void\n */\nvoid ExtendedKalmanFilter::GetQPose(Eigen::MatrixXd &Q) {\n    // build observability matrix for position measurement:\n    for (int i = 1; i < DIM_STATE; ++i) {\n        QPose_.block<DIM_MEASUREMENT_POSE, DIM_STATE>(i*DIM_MEASUREMENT_POSE, 0) = (\n            QPose_.block<DIM_MEASUREMENT_POSE, DIM_STATE>((i - 1)*DIM_MEASUREMENT_POSE, 0) * F_\n        );\n    }\n\n    Q = QPose_;\n}\n\n/**\n * @brief  get Q for pose & body velocity measurement\n * @param  void\n * @return void\n */\nvoid  ExtendedKalmanFilter::GetQPoseVel(Eigen::MatrixXd &Q) {\n    // build observability matrix for position & velocity measurement:\n    QPoseVel_.block<DIM_MEASUREMENT_POSE_VEL, DIM_STATE>(0, 0) = GPoseVel_;\n    for (int i = 1; i < DIM_STATE; ++i) {\n        QPoseVel_.block<DIM_MEASUREMENT_POSE_VEL, DIM_STATE>(i*DIM_MEASUREMENT_POSE_VEL, 0) = (\n            QPoseVel_.block<DIM_MEASUREMENT_POSE_VEL, DIM_STATE>((i - 1)*DIM_MEASUREMENT_POSE_VEL, 0) * F_\n        );\n    }\n\n    Q = QPoseVel_;\n}\n\n/**\n * @brief  get Q for GNSS position measurement\n * @param  void\n * @return QPosi\n */\nvoid ExtendedKalmanFilter::GetQPosi(Eigen::MatrixXd &Q) {\n    // build observability matrix for position measurement:\n    for (int i = 1; i < DIM_STATE; ++i) {\n        QPosi_.block<DIM_MEASUREMENT_POSI, DIM_STATE>(i*DIM_MEASUREMENT_POSI, 0) = (\n            QPosi_.block<DIM_MEASUREMENT_POSI, DIM_STATE>((i - 1)*DIM_MEASUREMENT_POSI, 0) * F_\n        );\n    }  \n\n    Q = QPosi_;\n}\n\n/**\n * @brief  get Q for GNSS position & body velocity measurement\n * @param  void\n * @return QPosiVel\n */\n void ExtendedKalmanFilter::GetQPosiVel(Eigen::MatrixXd &Q) {\n    // build observability matrix for position & velocity measurement:\n    QPosiVel_.block<DIM_MEASUREMENT_POSI_VEL, DIM_STATE>(0, 0) = GPosiVel_;\n    for (int i = 1; i < DIM_STATE; ++i) {\n        QPosiVel_.block<DIM_MEASUREMENT_POSI_VEL, DIM_STATE>(i*DIM_MEASUREMENT_POSI_VEL, 0) = (\n            QPosiVel_.block<DIM_MEASUREMENT_POSI_VEL, DIM_STATE>((i - 1)*DIM_MEASUREMENT_POSI_VEL, 0) * F_\n        );\n    }\n\n    Q = QPosiVel_;\n}\n\n/**\n * @brief  get Q for GNSS position & magneto measurement\n * @param  void\n * @return QPosiMag\n */\n void ExtendedKalmanFilter::GetQPosiMag(Eigen::MatrixXd &Q) {\n    // build observability matrix for position measurement:\n    QPosiMag_.block<DIM_MEASUREMENT_POSI_MAG, DIM_STATE>(0, 0) = GPosiMag_;\n    for (int i = 1; i < DIM_STATE; ++i) {\n        QPosiMag_.block<DIM_MEASUREMENT_POSI_MAG, DIM_STATE>(i*DIM_MEASUREMENT_POSI_MAG, 0) = (\n            QPosiMag_.block<DIM_MEASUREMENT_POSI_MAG, DIM_STATE>((i - 1)*DIM_MEASUREMENT_POSI_MAG, 0) * F_\n        );\n    }\n\n    Q = QPosiMag_;\n}\n\n/**\n * @brief  get Q for GNSS position, body velocity & magneto measurement\n * @param  void\n * @return QPosiVelMag\n */\n void ExtendedKalmanFilter::GetQPosiVelMag(Eigen::MatrixXd &Q) {\n    // build observability matrix for position & velocity measurement:\n    QPosVelMag_.block<DIM_MEASUREMENT_POSI_VEL_MAG, DIM_STATE>(0, 0) = GPosiVelMag_;\n    for (int i = 1; i < DIM_STATE; ++i) {\n        QPosVelMag_.block<DIM_MEASUREMENT_POSI_VEL_MAG, DIM_STATE>(i*DIM_MEASUREMENT_POSI_VEL_MAG, 0) = (\n            QPosVelMag_.block<DIM_MEASUREMENT_POSI_VEL_MAG, DIM_STATE>((i - 1)*DIM_MEASUREMENT_POSI_VEL_MAG, 0) * F_\n        );\n    }\n    Q = QPosVelMag_;\n}\n\n/**\n * @brief  update observability analysis\n * @param  measurement_type, measurement type\n * @return void\n */\nvoid ExtendedKalmanFilter::UpdateObservabilityAnalysis(\n    const double &time,\n    const MeasurementType &measurement_type\n) {\n    // get Q:\n    Eigen::MatrixXd Q;\n    switch ( measurement_type ) {\n        case MeasurementType::POSE:\n            GetQPose(Q);\n            break;\n        case MeasurementType::POSE_VEL:\n            GetQPoseVel(Q);\n            break;\n        case MeasurementType::POSI:\n            GetQPosi(Q);\n            break;\n        case MeasurementType::POSI_VEL:\n            GetQPosiVel(Q);\n            break;\n        case MeasurementType::POSI_MAG:\n            GetQPosiMag(Q);\n            break;\n        case MeasurementType::POSI_VEL_MAG:\n            GetQPosiVelMag(Q);\n            break;\n        default:\n            break;\n    }\n\n    observability.time_.push_back(time);\n    observability.Q_.push_back(Q);\n}\n\n/**\n * @brief  save observability analysis to persistent storage\n * @param  measurement_type, measurement type\n * @return void\n */\nbool ExtendedKalmanFilter::SaveObservabilityAnalysis(\n    const MeasurementType &measurement_type\n) {\n    // get fusion strategy:\n    std::string type;\n    switch ( measurement_type ) {\n        case MeasurementType::POSE:\n            type = std::string(\"pose\");\n            break;\n        case MeasurementType::POSE_VEL:\n            type = std::string(\"pose_velocity\");\n            break;\n        case MeasurementType::POSI:\n            type = std::string(\"position\");\n            break;\n        case MeasurementType::POSI_VEL:\n            type = std::string(\"position_velocity\");\n            break;\n        case MeasurementType::POSI_MAG:\n            type = std::string(\"position_magneto\");\n            break;\n        case MeasurementType::POSI_VEL_MAG:\n            type = std::string(\"position_velocity_magneto\");\n            break;\n        default:\n            return false;\n            break;\n    }\n\n    // build Q_so:\n    const int N = observability.Q_.at(0).rows();\n\n    std::vector<std::vector<double>> q_data, q_so_data;\n\n    Eigen::MatrixXd Qso(\n        observability.Q_.size() * N,\n        DIM_STATE\n    );\n    for (size_t i = 0; i < observability.Q_.size(); ++i) {\n        const double &time = observability.time_.at(i);\n        const Eigen::MatrixXd &Q = observability.Q_.at(i);\n\n        Qso.block(i * N, 0, N, DIM_STATE) = Q;\n\n        KalmanFilter::AnalyzeQ(DIM_STATE, time, Q, q_data);\n\n        KalmanFilter::AnalyzeQ(DIM_STATE, time, Qso.block(0, 0, (i + 1)*N, DIM_STATE), q_so_data);\n    }\n\n    std::string q_data_csv = WORK_SPACE_PATH + \"/slam_data/observability/\" + type + \".csv\";\n    std::string q_so_data_csv = WORK_SPACE_PATH + \"/slam_data/observability/\" + type + \"_som.csv\";\n\n    KalmanFilter::WriteAsCSV(DIM_STATE, q_data, q_data_csv);\n    KalmanFilter::WriteAsCSV(DIM_STATE, q_so_data, q_so_data_csv);\n\n    return true;\n}\n\n} // namespace lidar_localization", "meta": {"hexsha": "f633eb8ff611ea7e2f27c00c36542c9e0c7637f9", "size": 42720, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/src/models/kalman_filter/extended_kalman_filter.cpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-03-19T05:51:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T06:10:16.000Z", "max_issues_repo_path": "08-graph-optimization/sensor-fusion-for-localization-and-mapping/workspace/assignments/08-graph-optimization/src/lidar_localization/src/models/kalman_filter/extended_kalman_filter.cpp", "max_issues_repo_name": "WeihengXia0123/LiDar-SLAM", "max_issues_repo_head_hexsha": "834060da7ee0125cefd310d6215821551bac16c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "08-graph-optimization/sensor-fusion-for-localization-and-mapping/workspace/assignments/08-graph-optimization/src/lidar_localization/src/models/kalman_filter/extended_kalman_filter.cpp", "max_forks_repo_name": "WeihengXia0123/LiDar-SLAM", "max_forks_repo_head_hexsha": "834060da7ee0125cefd310d6215821551bac16c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T12:31:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T17:12:44.000Z", "avg_line_length": 33.1162790698, "max_line_length": 116, "alphanum_fraction": 0.6238061798, "num_tokens": 13060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4150926134687609}}
{"text": "/**\n * @file /yocs_math_toolkit/include/yocs_math_toolkit/sophus_helpers.hpp\n **/\n/*****************************************************************************\n** Ifdefs\n*****************************************************************************/\n\n#ifndef yocs_math_toolkit_SOPHUS_HELPERS_HPP_\n#define yocs_math_toolkit_SOPHUS_HELPERS_HPP_\n\n/*****************************************************************************\n** Includes\n*****************************************************************************/\n\n#include <ecl/config/macros.hpp>\n#include <ecl/converters.hpp>\n#include <ecl/exceptions/standard_exception.hpp>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <iomanip>\n#include <iostream>\n#if defined(ECL_CXX11_FOUND)\n    #include <memory>\n#endif\n#include <sophus/se3.hpp>\n#include <sophus/se2.hpp>\n#include <sophus/so2.hpp>\n#include <sophus/so3.hpp>\n#include <string>\n\n#include \"formatters.hpp\"\n\n/*****************************************************************************\n** Namespace\n*****************************************************************************/\n\nnamespace Sophus {\n\n/*****************************************************************************\n ** C++11 Api Only\n *****************************************************************************/\n\n#if defined(ECL_CXX11_FOUND)\n    typedef std::shared_ptr<SE3f> SE3fPtr;\n\n    /// Converts a line drawn between two points on the z-plane into the transform of a sophus frame relative to the origin.\n    Sophus::SE3fPtr points2DToSophusTransform(float from_x, float from_y, float to_x, float to_y);\n#endif\n\n/*****************************************************************************\n** Interfaces\n*****************************************************************************/\n\ntemplate<typename T>\nstd::ostream & operator << ( std::ostream & out, const SE3<T> & se3 )\n{\n//  typename SE3<T>::Tangent tanget_vector = SE3<T>::log( se3 );\n//  out << tanget_vector.transpose();\n  const Eigen::Matrix<T,3,1> & t = se3.translation();\n  const Eigen::Quaternion<T> & q = se3.unit_quaternion();\n  out << t.transpose() << \" \" << q.x() << \" \" << q.y() << \" \" << q.z() << \" \" << q.w();\n  return out;\n}\n\ntemplate<typename T>\nstd::ostream & operator << ( std::ostream & out, const SE2<T> & se2 )\n{\n  typename SE2<T>::Tangent tanget_vector = SE2<T>::log( se2 );\n  out << tanget_vector.transpose();\n  return out;\n}\n\n/**\n * @brief Convert a full Sophus pose into a 2 dimensional pose.\n *\n * The 2d pose is a typical mobile robot 2d pose with (x, y, heading) with\n * heading measured in radians.\n **/\nEigen::Vector3f toPose2D(const Sophus::SE3f& pose);\n/**\n * @brief Convert a 2 dimensional pose to a full Sophus pose in 3d.\n *\n * The 2d pose is a typical mobile robot 2d pose with (x, y, heading) with\n * heading measured in radians.\n **/\nSophus::SE3f toPose3D(const Eigen::Vector3f& pose);\n\nclass PlanarRotation2Quaternion\n{\npublic:\n  PlanarRotation2Quaternion(){}\n  Eigen::Quaternionf operator() ( float theta )\n  {\n    Eigen::Matrix3f R = ( Eigen::AngleAxis<float> (static_cast<float> ( theta ), Eigen::Vector3f::UnitZ ()) ).matrix();\n    Eigen::Quaternionf q(R);\n    q.normalize();\n    return q;\n//    Eigen::Quaternionf q;\n//    // in this case x and y part is zero since we assumbed that rotationa round z axis on the xy-plane\n//    q.vec() << 0, 0, sin(theta*0.5f);\n//    q.w() = cos(theta*0.5f);\n//    q.normalize();\n//    return q;\n  }\n\n  void convert( float theta, Eigen::Quaternionf & q )\n  {\n    q.vec() << 0, 0, sin(theta*0.5f);\n    q.w() = cos(theta*0.5f);\n  }\n};\n\n\n} // namespace Sophus\n\n/*****************************************************************************\n** Converters\n*****************************************************************************/\n\nnamespace ecl {\n\n/**\n * @brief Converter class representing the Sophus::toPose3D method.\n */\ntemplate<>\nclass Converter<Sophus::SE3f, Eigen::Vector3f> {\npublic:\n  Sophus::SE3f operator()(const Eigen::Vector3f& pose);\n};\n\n/**\n * @brief Converter class representing the Sophus::toPose2D method.\n */\ntemplate<>\nclass Converter<Eigen::Vector3f, Sophus::SE3f> {\npublic:\n  Eigen::Vector3f operator()(const Sophus::SE3f& pose);\n};\n\n} // namespace ecl\n\n\n#endif /* yocs_math_toolkit_SOPHUS_HELPERS_HPP_ */\n", "meta": {"hexsha": "41fb1cd231c8dadab59f5def050aa519c26bc75f", "size": 4249, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ros/catkin_ws/src/ecl/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/helpers.hpp", "max_stars_repo_name": "Kanaderu/spiking-ddpg-mapless-navigation", "max_stars_repo_head_hexsha": "2b5e7e67385dee4428b8036bc4ffe95e812b34e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ros/catkin_ws/src/ecl/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/helpers.hpp", "max_issues_repo_name": "Kanaderu/spiking-ddpg-mapless-navigation", "max_issues_repo_head_hexsha": "2b5e7e67385dee4428b8036bc4ffe95e812b34e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ros/catkin_ws/src/ecl/ecl_core/ecl_linear_algebra/include/ecl/linear_algebra/sophus/helpers.hpp", "max_forks_repo_name": "Kanaderu/spiking-ddpg-mapless-navigation", "max_forks_repo_head_hexsha": "2b5e7e67385dee4428b8036bc4ffe95e812b34e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5069444444, "max_line_length": 124, "alphanum_fraction": 0.5267121676, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.41509260594632963}}
{"text": "// (C) Copyright Andrew Sutton 2007\r\n//\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0 (See accompanying file\r\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GRAPH_GEODESIC_DISTANCE_HPP\r\n#define BOOST_GRAPH_GEODESIC_DISTANCE_HPP\r\n\r\n#include <boost/graph/detail/geodesic.hpp>\r\n#include <boost/graph/exterior_property.hpp>\r\n\r\nnamespace boost\r\n{\r\ntemplate <typename Graph,\r\n          typename DistanceType,\r\n          typename ResultType,\r\n          typename Divides = std::divides<ResultType> >\r\nstruct mean_geodesic_measure\r\n    : public geodesic_measure<Graph, DistanceType, ResultType>\r\n{\r\n    typedef geodesic_measure<Graph, DistanceType, ResultType> base_type;\r\n    typedef typename base_type::distance_type distance_type;\r\n    typedef typename base_type::result_type result_type;\r\n\r\n    result_type operator ()(distance_type d, const Graph& g)\r\n    {\r\n        function_requires< VertexListGraphConcept<Graph> >();\r\n        function_requires< NumericValueConcept<DistanceType> >();\r\n        function_requires< NumericValueConcept<ResultType> >();\r\n        function_requires< AdaptableBinaryFunctionConcept<Divides,ResultType,ResultType,ResultType> >();\r\n\r\n        return (d == base_type::infinite_distance())\r\n            ? base_type::infinite_result()\r\n            : div(result_type(d), result_type(num_vertices(g) - 1));\r\n    }\r\n    Divides div;\r\n};\r\n\r\ntemplate <typename Graph, typename DistanceMap>\r\ninline mean_geodesic_measure<Graph, typename property_traits<DistanceMap>::value_type, double>\r\nmeasure_mean_geodesic(const Graph&, DistanceMap)\r\n{\r\n    return mean_geodesic_measure<Graph, typename property_traits<DistanceMap>::value_type, double>();\r\n}\r\n\r\ntemplate <typename T, typename Graph, typename DistanceMap>\r\ninline mean_geodesic_measure<Graph, typename property_traits<DistanceMap>::value_type, T>\r\nmeasure_mean_geodesic(const Graph&, DistanceMap)\r\n{\r\n    return mean_geodesic_measure<Graph, typename property_traits<DistanceMap>::value_type, T>();\r\n}\r\n\r\n// This is a little different because it's expected that the result type\r\n// should (must?) be the same as the distance type. There's a type of\r\n// transitivity in this thinking... If the average of distances has type\r\n// X then the average of x's should also be type X. Is there a case where this\r\n// is not true?\r\n//\r\n// This type is a little under-genericized... It needs generic parameters\r\n// for addition and division.\r\ntemplate <typename Graph, typename DistanceType>\r\nstruct mean_graph_distance_measure\r\n    : public geodesic_measure<Graph, DistanceType, DistanceType>\r\n{\r\n    typedef geodesic_measure<Graph, DistanceType, DistanceType> base_type;\r\n    typedef typename base_type::distance_type distance_type;\r\n    typedef typename base_type::result_type result_type;\r\n\r\n    inline result_type operator ()(distance_type d, const Graph& g)\r\n    {\r\n        function_requires< VertexListGraphConcept<Graph> >();\r\n        function_requires< NumericValueConcept<DistanceType> >();\r\n\r\n        if(d == base_type::infinite_distance()) {\r\n            return base_type::infinite_result();\r\n        }\r\n        else {\r\n            return d / result_type(num_vertices(g));\r\n        }\r\n    }\r\n};\r\n\r\ntemplate <typename Graph, typename DistanceMap>\r\ninline mean_graph_distance_measure<Graph, typename property_traits<DistanceMap>::value_type>\r\nmeasure_graph_mean_geodesic(const Graph&, DistanceMap)\r\n{\r\n    typedef typename property_traits<DistanceMap>::value_type T;\r\n    return mean_graph_distance_measure<Graph, T>();\r\n}\r\n\r\ntemplate <typename Graph,\r\n          typename DistanceMap,\r\n          typename Measure,\r\n          typename Combinator>\r\ninline typename Measure::result_type\r\nmean_geodesic(const Graph& g,\r\n                DistanceMap dist,\r\n                Measure measure,\r\n                Combinator combine)\r\n{\r\n    function_requires< DistanceMeasureConcept<Measure,Graph> >();\r\n    typedef typename Measure::distance_type Distance;\r\n\r\n    Distance n = detail::combine_distances(g, dist, combine, Distance(0));\r\n    return measure(n, g);\r\n}\r\n\r\ntemplate <typename Graph,\r\n            typename DistanceMap,\r\n            typename Measure>\r\ninline typename Measure::result_type\r\nmean_geodesic(const Graph& g, DistanceMap dist, Measure measure)\r\n{\r\n    function_requires< DistanceMeasureConcept<Measure,Graph> >();\r\n    typedef typename Measure::distance_type Distance;\r\n\r\n    return mean_geodesic(g, dist, measure, std::plus<Distance>());\r\n}\r\n\r\ntemplate <typename Graph, typename DistanceMap>\r\ninline double\r\nmean_geodesic(const Graph& g, DistanceMap dist)\r\n{ return mean_geodesic(g, dist, measure_mean_geodesic(g, dist)); }\r\n\r\ntemplate <typename T, typename Graph, typename DistanceMap>\r\ninline T\r\nmean_geodesic(const Graph& g, DistanceMap dist)\r\n{ return mean_geodesic(g, dist, measure_mean_geodesic<T>(g, dist)); }\r\n\r\n\r\ntemplate <typename Graph,\r\n            typename DistanceMatrixMap,\r\n            typename GeodesicMap,\r\n            typename Measure>\r\ninline typename property_traits<GeodesicMap>::value_type\r\nall_mean_geodesics(const Graph& g,\r\n                    DistanceMatrixMap dist,\r\n                    GeodesicMap geo,\r\n                    Measure measure)\r\n{\r\n    function_requires< VertexListGraphConcept<Graph> >();\r\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n    typedef typename graph_traits<Graph>::vertex_iterator VertexIterator;\r\n    function_requires< ReadablePropertyMapConcept<DistanceMatrixMap,Vertex> >();\r\n    typedef typename property_traits<DistanceMatrixMap>::value_type DistanceMap;\r\n    function_requires< DistanceMeasureConcept<Measure,Graph> >();\r\n    typedef typename Measure::result_type Result;\r\n    function_requires< WritablePropertyMapConcept<GeodesicMap,Vertex> >();\r\n    function_requires< NumericValueConcept<Result> >();\r\n\r\n    // NOTE: We could compute the mean geodesic here by performing additional\r\n    // computations (i.e., adding and dividing). However, I don't really feel\r\n    // like fully genericizing the entire operation yet so I'm not going to.\r\n\r\n    Result inf = numeric_values<Result>::infinity();\r\n    Result sum = numeric_values<Result>::zero();\r\n    VertexIterator i, end;\r\n    for(tie(i, end) = vertices(g); i != end; ++i) {\r\n        DistanceMap dm = get(dist, *i);\r\n        Result r = mean_geodesic(g, dm, measure);\r\n        put(geo, *i, r);\r\n\r\n        // compute the sum along with geodesics\r\n        if(r == inf) {\r\n            sum = inf;\r\n        }\r\n        else if(sum != inf) {\r\n            sum += r;\r\n        }\r\n    }\r\n\r\n    // return the average of averages.\r\n    return sum / Result(num_vertices(g));\r\n}\r\n\r\ntemplate <typename Graph, typename DistanceMatrixMap, typename GeodesicMap>\r\ninline typename property_traits<GeodesicMap>::value_type\r\nall_mean_geodesics(const Graph& g, DistanceMatrixMap dist, GeodesicMap geo)\r\n{\r\n    function_requires< GraphConcept<Graph> >();\r\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\r\n    function_requires< ReadablePropertyMapConcept<DistanceMatrixMap,Vertex> >();\r\n    typedef typename property_traits<DistanceMatrixMap>::value_type DistanceMap;\r\n    function_requires< WritablePropertyMapConcept<GeodesicMap,Vertex> >();\r\n    typedef typename property_traits<GeodesicMap>::value_type Result;\r\n\r\n    return all_mean_geodesics(g, dist, geo, measure_mean_geodesic<Result>(g, DistanceMap()));\r\n}\r\n\r\n\r\ntemplate <typename Graph, typename GeodesicMap, typename Measure>\r\ninline typename Measure::result_type\r\nsmall_world_distance(const Graph& g, GeodesicMap geo, Measure measure)\r\n{\r\n    function_requires< DistanceMeasureConcept<Measure,Graph> >();\r\n    typedef typename Measure::result_type Result;\r\n\r\n    Result sum = detail::combine_distances(g, geo, std::plus<Result>(), Result(0));\r\n    return measure(sum, g);\r\n}\r\n\r\ntemplate <typename Graph, typename GeodesicMap>\r\ninline typename property_traits<GeodesicMap>::value_type\r\nsmall_world_distance(const Graph& g, GeodesicMap geo)\r\n{ return small_world_distance(g, geo, measure_graph_mean_geodesic(g, geo)); }\r\n\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "c8e2f02875c40f67ec93927036f436bc72871494", "size": 8086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trunk/win/Source/Includes/Boost/graph/geodesic_distance.hpp", "max_stars_repo_name": "dyzmapl/BumpTop", "max_stars_repo_head_hexsha": "1329ea41411c7368516b942d19add694af3d602f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2016-01-13T12:49:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T04:10:40.000Z", "max_issues_repo_path": "trunk/win/Source/Includes/Boost/graph/geodesic_distance.hpp", "max_issues_repo_name": "dyzmapl/BumpTop", "max_issues_repo_head_hexsha": "1329ea41411c7368516b942d19add694af3d602f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2016-11-07T04:59:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T06:34:12.000Z", "max_forks_repo_path": "trunk/win/Source/Includes/Boost/graph/geodesic_distance.hpp", "max_forks_repo_name": "dyzmapl/BumpTop", "max_forks_repo_head_hexsha": "1329ea41411c7368516b942d19add694af3d602f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2016-01-17T03:16:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T12:20:36.000Z", "avg_line_length": 38.3222748815, "max_line_length": 105, "alphanum_fraction": 0.7113529557, "num_tokens": 1749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4150027651215128}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2021 Ilias Khairullin <ilias@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_RANDOM_ALGEBRAIC_ENGINE_HPP\n#define CRYPTO3_RANDOM_ALGEBRAIC_ENGINE_HPP\n\n#include <type_traits>\n\n#include <boost/type_traits.hpp>\n\n#include <boost/random/random_device.hpp>\n#include <boost/random/uniform_int_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n\n#include <nil/crypto3/algebra/type_traits.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace random {\n            /*!\n             * @brief\n             * @tparam AlgebraicType denote an some algebraic type (field, curve group types).\n             * @tparam Engine denote an some base \\RandomNumberEngine generating random numbers\n             *\n             * The class template algebraic_engine is a pseudo-random number engine adaptor that generate random values\n             * of algebraic type using data produced by the base engine. It models (not fully) a\n             * \\RandomNumberEngine. https://en.cppreference.com/w/cpp/named_req/RandomNumberEngine\n             *\n             * @warning The class template algebraic_engine differs from \\RandomNumberEngine as it doesn't have\n             * constructor and seed function with parameter of result_type. This is due to the fact that\n             * algebraic_engine is adapter wrapping some base \\RandomNumberEngine (Engine), so instead it has\n             * constructor and seed function with parameter of Engine::result_type.\n             */\n            template<typename AlgebraicType, typename Engine = boost::random::mt19937, typename = void>\n            struct algebraic_engine;\n\n            template<typename AlgebraicType, typename Engine>\n            struct algebraic_engine<\n                AlgebraicType,\n                Engine,\n                typename std::enable_if<algebra::is_field<AlgebraicType>::value &&\n                                        !algebra::is_extended_field<AlgebraicType>::value &&\n                                        boost::is_integral<typename Engine::result_type>::value>::type> {\n            protected:\n                typedef AlgebraicType field_type;\n                typedef typename field_type::value_type field_value_type;\n                typedef typename field_type::integral_type integral_type;\n\n                typedef Engine internal_generator_type;\n                typedef boost::random::uniform_int_distribution<integral_type> internal_distribution_type;\n\n                constexpr static integral_type _min = 0;\n                constexpr static integral_type _max = field_type::modulus - 1;\n\n            public:\n                typedef field_value_type result_type;\n\n                /**\n                 * Constructs a @c algebraic_engine and calls @c seed().\n                 */\n                algebraic_engine() {\n                    seed();\n                }\n                /**\n                 * Constructs a @c algebraic_engine and calls @c seed(value).\n                 */\n                BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(algebraic_engine, typename Engine::result_type, value) {\n                    seed(value);\n                }\n                /**\n                 * Constructs a algebraic_engine and calls @c seed(seq).\n                 *\n                 * @xmlnote\n                 * The copy constructor will always be preferred over\n                 * the templated constructor.\n                 * @endxmlnote\n                 */\n                BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(algebraic_engine, SeedSeq, seq) {\n                    seed(seq);\n                }\n\n                /** Calls @c seed(default_seed) of base Engine. */\n                void seed() {\n                    gen.seed();\n                }\n                /** Calls @c seed(value) of base Engine. */\n                BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(algebraic_engine, typename Engine::result_type, value) {\n                    gen.seed(value);\n                }\n                /** Calls @c seed(seq) of base Engine. */\n                BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(algebraic_engine, SeeqSeq, seq) {\n                    gen.seed(seq);\n                }\n\n                /** Returns the smallest value that the \\algebraic_random_device can produce. */\n                constexpr static inline result_type min() {\n                    constexpr result_type min_value(_min);\n                    return min_value;\n                }\n\n                /** Returns the largest value that the \\algebraic_random_device can produce. */\n                constexpr static inline result_type max() {\n                    constexpr result_type max_value(_max);\n                    return max_value;\n                }\n\n                /** Returns a random value in the range [min, max]. */\n                result_type operator()() {\n                    return dist(gen);\n                }\n\n                /**\n                 * Advances the state of the generator by @c z steps.  Equivalent to\n                 */\n                void discard(std::size_t z) {\n                    while (z--) {\n                        (*this)();\n                    }\n                }\n\n                /** Writes a algebraic_engine to a @c std::ostream */\n                template<class CharT, class Traits>\n                friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os,\n                                                                     const algebraic_engine& ae) {\n                    os << ae.gen;\n                    return os;\n                }\n\n                /** Reads a algebraic_engine from a @c std::istream */\n                template<class CharT, class Traits>\n                friend std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is,\n                                                                     algebraic_engine& ae) {\n                    is >> ae.gen;\n                    return is;\n                }\n\n                /**\n                 * Returns true if the two generators are in the same state,\n                 * and will thus produce identical sequences.\n                 */\n                friend bool operator==(const algebraic_engine& x_, const algebraic_engine& y_) {\n                    return x_.gen == y_.gen && x_.dist == y_.dist;\n                }\n\n                /**\n                 * Returns true if the two generators are in different states.\n                 */\n                friend bool operator!=(const algebraic_engine& x_, const algebraic_engine& y_) {\n                    return !(x_ == y_);\n                }\n\n            protected:\n                internal_generator_type gen;\n                internal_distribution_type dist = internal_distribution_type(_min, _max);\n            };\n\n            template<typename AlgebraicType, typename Engine>\n            struct algebraic_engine<\n                AlgebraicType,\n                Engine,\n                typename std::enable_if<algebra::is_field<AlgebraicType>::value &&\n                                        algebra::is_extended_field<AlgebraicType>::value &&\n                                        boost::is_integral<typename Engine::result_type>::value>::type> {\n            protected:\n                typedef AlgebraicType extended_field_type;\n                typedef typename extended_field_type::value_type extended_field_value_type;\n                typedef typename extended_field_type::underlying_field_type underlying_field_type;\n\n                typedef algebraic_engine<underlying_field_type, Engine> internal_generator_type;\n\n            public:\n                typedef extended_field_value_type result_type;\n\n                /**\n                 * Constructs a @c algebraic_engine and calls @c seed().\n                 */\n                algebraic_engine() {\n                    seed();\n                }\n                /**\n                 * Constructs a @c algebraic_engine and calls @c seed(value).\n                 */\n                BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(algebraic_engine, typename Engine::result_type, value) {\n                    seed(value);\n                }\n                /**\n                 * Constructs a algebraic_engine and calls @c seed(seq).\n                 *\n                 * @xmlnote\n                 * The copy constructor will always be preferred over\n                 * the templated constructor.\n                 * @endxmlnote\n                 */\n                BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(algebraic_engine, SeedSeq, seq) {\n                    seed(seq);\n                }\n\n                /** Calls @c seed(default_seed) of base Engine. */\n                void seed() {\n                    gen.seed();\n                }\n                /** Calls @c seed(value) of base Engine. */\n                BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(algebraic_engine, typename Engine::result_type, value) {\n                    gen.seed(value);\n                }\n                /** Calls @c seed(seq) of base Engine. */\n                BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(algebraic_engine, SeeqSeq, seq) {\n                    gen.seed(seq);\n                }\n\n                /** Returns the smallest value that the \\algebraic_random_device can produce. */\n                // TODO: evaluate min_value at compile-time\n                constexpr static inline result_type min() {\n                    result_type min_value;\n                    for (auto& coord : min_value.data) {\n                        coord = internal_generator_type::min();\n                    }\n\n                    return min_value;\n                }\n\n                /** Returns the largest value that the \\algebraic_random_device can produce. */\n                // TODO: evaluate max_value at compile-time\n                constexpr static inline result_type max() {\n                    result_type max_value;\n                    for (auto& coord : max_value.data) {\n                        coord = internal_generator_type::max();\n                    }\n\n                    return max_value;\n                }\n\n                /** Returns a random value in the range [min, max]. */\n                result_type operator()() {\n                    result_type result;\n                    for (auto& coord : result.data) {\n                        coord = gen();\n                    }\n\n                    return result;\n                }\n\n                /**\n                 * Advances the state of the generator by @c z steps.  Equivalent to\n                 */\n                void discard(std::size_t z) {\n                    while (z--) {\n                        (*this)();\n                    }\n                }\n\n                /** Writes a algebraic_engine to a @c std::ostream */\n                template<class CharT, class Traits>\n                friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os,\n                                                                     const algebraic_engine& ae) {\n                    os << ae.gen;\n                    return os;\n                }\n\n                /** Reads a algebraic_engine from a @c std::istream */\n                template<class CharT, class Traits>\n                friend std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is,\n                                                                     algebraic_engine& ae) {\n                    is >> ae.gen;\n                    return is;\n                }\n\n                /**\n                 * Returns true if the two generators are in the same state,\n                 * and will thus produce identical sequences.\n                 */\n                friend bool operator==(const algebraic_engine& x_, const algebraic_engine& y_) {\n                    return x_.gen == y_.gen;\n                }\n\n                /**\n                 * Returns true if the two generators are in different states.\n                 */\n                friend bool operator!=(const algebraic_engine& x_, const algebraic_engine& y_) {\n                    return !(x_ == y_);\n                }\n\n            protected:\n                internal_generator_type gen;\n            };\n\n            template<typename AlgebraicType, typename Engine>\n            struct algebraic_engine<\n                AlgebraicType,\n                Engine,\n                typename std::enable_if<algebra::is_curve_group<AlgebraicType>::value &&\n                                        boost::is_integral<typename Engine::result_type>::value>::type> {\n            protected:\n                typedef AlgebraicType group_type;\n                typedef typename group_type::value_type group_value_type;\n                typedef typename group_type::curve_type::scalar_field_type scalar_field_type;\n\n                typedef algebraic_engine<scalar_field_type, Engine> internal_generator_type;\n\n            public:\n                typedef group_value_type result_type;\n\n                /**\n                 * Constructs a @c algebraic_engine and calls @c seed().\n                 */\n                algebraic_engine() {\n                    seed();\n                }\n                /**\n                 * Constructs a @c algebraic_engine and calls @c seed(value).\n                 */\n                BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(algebraic_engine, typename Engine::result_type, value) {\n                    seed(value);\n                }\n                /**\n                 * Constructs a algebraic_engine and calls @c seed(seq).\n                 *\n                 * @xmlnote\n                 * The copy constructor will always be preferred over\n                 * the templated constructor.\n                 * @endxmlnote\n                 */\n                BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(algebraic_engine, SeedSeq, seq) {\n                    seed(seq);\n                }\n\n                /** Calls @c seed(default_seed) of base Engine. */\n                void seed() {\n                    gen.seed();\n                }\n                /** Calls @c seed(value) of base Engine. */\n                BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(algebraic_engine, typename Engine::result_type, value) {\n                    gen.seed(value);\n                }\n                /** Calls @c seed(seq) of base Engine. */\n                BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(algebraic_engine, SeeqSeq, seq) {\n                    gen.seed(seq);\n                }\n\n                /** Returns the smallest value that the \\algebraic_random_device can produce. */\n                // TODO: evaluate returned value at compile-time\n                constexpr static inline result_type min() {\n                    return result_type::zero();\n                }\n\n                /** Returns the largest value that the \\algebraic_random_device can produce. */\n                // TODO: evaluate max_value at compile-time\n                constexpr static inline result_type max() {\n                    return result_type::one() * (scalar_field_type::modulus - 1);\n                }\n\n                /**\n                 * Returns a random value in the range [min, max]. Elements of group are ordered in exponent growing\n                 * order with respect to group base element.\n                 */\n                // TODO: check correctness of the generation method\n                result_type operator()() {\n                    return result_type::one() * gen();\n                }\n\n                /**\n                 * Advances the state of the generator by @c z steps.  Equivalent to\n                 */\n                void discard(std::size_t z) {\n                    while (z--) {\n                        (*this)();\n                    }\n                }\n\n                /** Writes a algebraic_engine to a @c std::ostream */\n                template<class CharT, class Traits>\n                friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os,\n                                                                     const algebraic_engine& ae) {\n                    os << ae.gen;\n                    return os;\n                }\n\n                /** Reads a algebraic_engine from a @c std::istream */\n                template<class CharT, class Traits>\n                friend std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is,\n                                                                     algebraic_engine& ae) {\n                    is >> ae.gen;\n                    return is;\n                }\n\n                /**\n                 * Returns true if the two generators are in the same state,\n                 * and will thus produce identical sequences.\n                 */\n                friend bool operator==(const algebraic_engine& x_, const algebraic_engine& y_) {\n                    return x_.gen == y_.gen;\n                }\n\n                /**\n                 * Returns true if the two generators are in different states.\n                 */\n                friend bool operator!=(const algebraic_engine& x_, const algebraic_engine& y_) {\n                    return !(x_ == y_);\n                }\n\n            protected:\n                internal_generator_type gen;\n            };\n        }    // namespace random\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_RANDOM_ALGEBRAIC_ENGINE_HPP\n", "meta": {"hexsha": "8a78ac9fa1d0f478cc4f9b5154a1c12559a88a7f", "size": 18719, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/random/include/nil/crypto3/random/algebraic_engine.hpp", "max_stars_repo_name": "Curryrasul/knapsack-snark", "max_stars_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "libs/random/include/nil/crypto3/random/algebraic_engine.hpp", "max_issues_repo_name": "Curryrasul/knapsack-snark", "max_issues_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/random/include/nil/crypto3/random/algebraic_engine.hpp", "max_forks_repo_name": "Curryrasul/knapsack-snark", "max_forks_repo_head_hexsha": "633515a13906407338a81b9874d964869ddec624", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:53:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:53:21.000Z", "avg_line_length": 43.4315545244, "max_line_length": 119, "alphanum_fraction": 0.5051017683, "num_tokens": 3296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4149849311581832}}
{"text": "#include \"vtkCarGeometricCalibration.h\"\n\n#include <cmath>\n#include <numeric>\n#include <random>\n#include <iostream>\n#include <fstream>\n\n#include <vtkMath.h>\n\n#include <Eigen/Geometry>\n\n#include \"vtkConversions.h\"\n#include \"vtkEigenTools.h\"\n\nEigen::Vector3d GetXYZ(const vtkSmartPointer<vtkVelodyneTransformInterpolator> trajectory,\n                       double time)\n{\n  vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();\n  trajectory->InterpolateTransform(time, transform);\n  return PositionVectorFromTransform(transform);\n}\n\nEigen::Matrix3d GetR(const vtkSmartPointer<vtkVelodyneTransformInterpolator> trajectory,\n                     double time)\n{\n  vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();\n  trajectory->InterpolateTransform(time, transform);\n  return RotationMatrixFromTransform(transform);\n}\n\n// method to identify a directions in straight lines\nenum class DIRECTION_METHOD\n{\n  TWO_POINTS,\n};\n\n// method to identify the normal of the plane containing the turn\nenum class NORMAL_METHOD\n{\n  CROSS_PRODUCT,\n};\n\n// method to optimize the direction after the normal has been computed\nenum class DIRECTION_OPTIMIZATION_METHOD\n{\n  NONE,\n};\n\n// method to compute an average orientation\n// in a zone where the orientation should be constant\n// (but could contain noise)\nenum class AVERAGE_ORIENTATION_METHOD\n{\n  SINGLE_POINT\n};\n\nstd::vector<std::vector<double>> ComputeTurns(\n        const vtkSmartPointer<vtkVelodyneTransformInterpolator> poseTrajectory,\n        double timeWindow,\n        double curveTreshold,\n        bool emptyIntersection,\n        std::string debugCSV,\n        bool verbose\n        )\n{\n  int minPtsInDirectionSets = 3; // could be as low as 2\n  int minPtsInTurn = 3; // could be as low as 1\n  std::ofstream debugFile;\n  bool debugFileEnabled = !debugCSV.empty();\n  if (debugFileEnabled)\n  {\n    debugFile.open(debugCSV);\n  }\n  // Compute local curvature, in rad/second\n  // for each sample: is it inside a turn ?\n  // Using the curveTreshold treshold\n  std::vector<int> sampleId =\n    std::vector<int>();\n  sampleId.reserve(poseTrajectory->GetNumberOfTransforms());\n  std::vector<double> sampleTime =\n    std::vector<double>();\n  sampleTime.reserve(poseTrajectory->GetNumberOfTransforms());\n  std::vector<bool> sampleStatus =\n    std::vector<bool>();\n  sampleStatus.reserve(poseTrajectory->GetNumberOfTransforms());\n\n  if (verbose)\n  {\n    std::cout << \"Computing per-sample status for \"\n              << poseTrajectory->GetNumberOfTransforms()\n              << \" samples\" << std::endl;\n  }\n  for (int i = 0; i < poseTrajectory->GetNumberOfTransforms(); i++)\n  {\n    vtkSmartPointer<vtkTransform> sample = vtkSmartPointer<vtkTransform>::New();\n    double t;\n    poseTrajectory->GetSample(i, sample, t);\n    if (t - 0.5 * timeWindow < poseTrajectory->GetMinimumT()\n        || t + 0.5 * timeWindow > poseTrajectory->GetMaximumT())\n    {\n      continue;\n    }\n    sampleId.push_back(i);\n    sampleTime.push_back(t);\n\n    vtkSmartPointer<vtkTransform> prev = vtkSmartPointer<vtkTransform>::New();\n    poseTrajectory->InterpolateTransform(t - 0.5 * timeWindow, prev);\n    vtkSmartPointer<vtkTransform> next = vtkSmartPointer<vtkTransform>::New();\n    poseTrajectory->InterpolateTransform(t + 0.5 * timeWindow, next);\n    Eigen::AngleAxisd aa = Eigen::AngleAxisd(RotationMatrixFromTransform(next)\n\t\t    * RotationMatrixFromTransform(prev).transpose());\n    double curvature = std::abs(aa.angle()) / timeWindow;\n    sampleStatus.push_back(curvature >= curveTreshold);\n  }\n\n  if (verbose)\n  {\n    std::cout << \"Aggregating samples\" << std::endl;\n  }\n  // Compute turn limits (exprimed in samples indexes)\n  unsigned int i = 0; // ! warning that is not the id of a sample\n  // if the first samples are inside a turn, discard this turn\n  // and start searching turns after its end.\n  while (i < sampleStatus.size() && sampleStatus[i] == true)\n  {\n    i = i + 1;\n  }\n  // we are ready to search turns and know that sample i\n  // is not inside a turn\n  bool inside = false;\n\n  // turn_limits[n][0] will contain the time of the first sample inside turn n\n  // turn_limits[n][1] will contain the time of the last sample inside turn n\n  // We have turn_limits[n][0] <= turn_limits[n][1]\n  std::vector<std::vector<int>> turnLimits = std::vector<std::vector<int>>();\n  for (unsigned int j = i; j < sampleStatus.size(); j++)\n  {\n    if (!inside && sampleStatus[j])\n    {\n      // entering turn\n      inside = true;\n      turnLimits.push_back(std::vector<int>());\n      turnLimits[turnLimits.size() - 1].push_back(j);\n    }\n    else if (inside && !sampleStatus[j])\n    {\n      // leaving turn\n      inside = false;\n      turnLimits[turnLimits.size() - 1].push_back(j - 1);\n    }\n  }\n  // if the end of last turn is not seen, discard this turn\n  if (inside)\n  {\n    if (verbose)\n    {\n      std::cout << \"pop_back\" << std::endl;\n    }\n    turnLimits.pop_back();\n  }\n\n  // convert indexes to times:\n  if (verbose)\n  {\n    std::cout << \"Converting indexes to time\" << std::endl;\n  }\n  std::vector<std::vector<double>> turnTimes = std::vector<std::vector<double>>();\n\n  for (unsigned int i = 0; i < turnLimits.size(); i++) {\n    if (turnLimits[i][1] - turnLimits[i][0] + 1 < minPtsInTurn)\n    {\n      if (verbose)\n      {\n        std::cout << \"warning: skipped one turn that did not contain enough points\" << std::endl;\n      }\n      continue;\n    }\n    std::vector<double> times = std::vector<double>(2);\n    times[0] = sampleTime[turnLimits[i][0]];\n    times[1] = sampleTime[turnLimits[i][1]];\n    turnTimes.push_back(times);\n  }\n\n\n  // Now we want to get a direction vector before and after the curve,\n  // if that is possible.\n  // ! we cannot use the time to look N seconds before/after,\n  // because turns are ofen preceded by a traffic light\n  // which can be red, in this case there is a stop in the trajectory,\n  // right before the turn. Sometimes there is a stop\n  // just at the end of a turn if there is a traffic jam.\n  // In both cases the risk is that the set of points selected with time\n  // before/after the turn will be just 1 point,\n  // or will be a set of points very centered locally.\n  // (So this set of points will not permit a reliable estimation of\n  // a direction vector)\n\n  // precompute a way to tell the length of the curve at any time\n  // (will be used by dichotomy search)\n  if (verbose)\n  {\n    std::cout << \"Precomputing curve length\" << std::endl;\n  }\n  double currentLength = 0.0;\n  std::vector<double> length = std::vector<double>();\n  length.reserve(poseTrajectory->GetNumberOfTransforms());\n  std::vector<double> lengthTimes = std::vector<double>();\n  lengthTimes.reserve(poseTrajectory->GetNumberOfTransforms());\n  vtkSmartPointer<vtkTransform> sample = vtkSmartPointer<vtkTransform>::New();\n  double time;\n  poseTrajectory->GetSample(0, sample, time);\n  Eigen::Vector3d previousPos = PositionVectorFromTransform(sample);\n  for (int i = 0; i < poseTrajectory->GetNumberOfTransforms(); i++)\n  {\n    poseTrajectory->GetSample(i, sample, time);\n    Eigen::Vector3d pos = PositionVectorFromTransform(sample);\n    currentLength += (pos - previousPos).norm();\n    lengthTimes.push_back(time);\n    length.push_back(currentLength);\n    previousPos = pos;\n  }\n\n  if (verbose)\n  {\n    std::cout << \"Placing bounds\" << std::endl;\n  }\n  std::vector<std::vector<double>> bounds = std::vector<std::vector<double>>();\n  for (unsigned int i = 0; i < turnTimes.size(); i++)\n  {\n    int iStart = std::distance(lengthTimes.begin(),\n\t\t    std::lower_bound(lengthTimes.begin(), lengthTimes.end(), turnTimes[i][0]));\n    int iEnd = std::distance(lengthTimes.begin(),\n\t\t    std::lower_bound(lengthTimes.begin(), lengthTimes.end(), turnTimes[i][1]));\n    double turnLength = length[iEnd] - length[iStart];\n    if (verbose)\n    {\n      std::cout << \"turn length is: \" << turnLength << \" (scale unknown)\" << std::endl;\n    }\n    int iBefore = std::distance(length.begin(),\n\t\t    std::lower_bound(length.begin(), length.end(), length[iStart] - turnLength));\n    int iAfter = std::distance(length.begin(),\n\t\t    std::lower_bound(length.begin(), length.end(), length[iEnd] + turnLength));\n    // if it was not possible to find iBefore/iAfter\n    // it means that the turn is either at the very start\n    // or very end of the trajectory, so it is hard to tell which\n    // was the direction before the turn\n    if (iBefore == 0 || iAfter == static_cast<int>(length.size()))\n    {\n      continue;\n    }\n    // if there is not enough points in sets \"before\" or \"after\",\n    // discard this turn:\n    if (iStart - iBefore + 1 < minPtsInDirectionSets\n        || iAfter - iEnd + 1 < minPtsInDirectionSets)\n    {\n      continue;\n    }\n    std::vector<double> bound = std::vector<double>(4);\n    bound[0] = lengthTimes[iBefore];\n    bound[1] = turnTimes[i][0];\n    bound[2] = turnTimes[i][1];\n    bound[3] = lengthTimes[iAfter];\n    bounds.push_back(bound);\n  }\n\n  // look for bug in my algo/my code/the data:\n  std::vector<int> misbounded = std::vector<int>();\n  for (unsigned int i = 0; i < bounds.size(); i++)\n  {\n    if (!(bounds[i][0] < bounds[i][1]\n          && bounds[i][1] < bounds[i][2]\n          && bounds[i][2] < bounds[i][3]))\n    {\n      if (verbose)\n      {\n        std::cout << \"warning: turn \" << i\n          << \"(\" << bounds[i][0] << \", \"\n          << bounds[i][1] << \", \"\n          << bounds[i][2] << \", \"\n          << bounds[i][3] << \") is not bounded correctly, discarding it.\"\n          << std::endl;\n      }\n      misbounded.push_back(i);\n    }\n  }\n  // delete misbounded turns:\n  if (verbose)\n  {\n    std::cout << \"Discarding mis-bounded turns\" << std::endl;\n  }\n  for (int i = misbounded.size() - 1; i >= 0; i--)\n  {\n    bounds.erase(bounds.begin() + misbounded[i]);\n  }\n\n  // handle the cases where two turns are close\n  // if possible, make the bounds intersection empty\n  // this is not mandatory but it help visualization a lot\n  if (emptyIntersection)\n  {\n    if (verbose)\n    {\n      std::cout << \"Changing bounds to empty intersections\" << std::endl;\n    }\n    std::vector<int> mixedUpTurns = std::vector<int>();\n    for (unsigned int i = 1; i < bounds.size(); i++)\n    {\n      if (bounds[i - 1][3] > bounds[i][0])\n      {\n        double newLimit = 0.5 * (bounds[i - 1][3] + bounds[i][0]);\n        // check if this new_limit solves the problem:\n        if (newLimit <= bounds[i - 1][2])\n        {\n          // cannot solve easily, discard the first turn\n          if (verbose)\n          {\n          std::cout << \"warning: could not fix (first) turn \" << i - 1\n            << \" discarding it\" << std::endl;\n          }\n          mixedUpTurns.push_back(i - 1);\n        }\n        else if (newLimit >= bounds[i][1])\n        {\n          // cannot solve easily, discard the second turn\n          if (verbose)\n          {\n            std::cout << \"warning: could not fix (second) turn \" << i\n              << \" discarding it\" << std::endl;\n          }\n          mixedUpTurns.push_back(i);\n        }\n        else\n        {\n          // one could argue that we should not do this fix\n          // because the lengths of the curve in the new after/before\n          // parts will not be equal to the lengths inside the turns\n          if (verbose)\n          {\n            std::cout << \"warning: fixing bounds of turns \" << i - 1\n              << \" and \" << i << \" that are touching each other\" << std::endl;\n          }\n          bounds[i - 1][3] = newLimit;\n          bounds[i][0] = newLimit;\n        }\n      }\n    }\n\n    if (verbose)\n    {\n      std::cout << \"Discarding turns with no empty intersection\" << std::endl;\n    }\n    // delete turns whose bounds intersection could not be made empty:\n    for (int i = mixedUpTurns.size() - 1; i >= 0; i--)\n    {\n      bounds.erase(bounds.begin() + mixedUpTurns[i]);\n    }\n  }\n\n  // write debug file:\n  // may not work correctly if emptyIntersection != true\n  if (debugFileEnabled)\n  {\n    if (verbose)\n    {\n      std::cout << \"Writing debug file\" << std::endl;\n    }\n    int currentTurnToConsider = 0;\n    for (int i = 0; i < poseTrajectory->GetNumberOfTransforms(); i++)\n    {\n      vtkSmartPointer<vtkTransform> sample = vtkSmartPointer<vtkTransform>::New();\n      double time;\n      poseTrajectory->GetSample(i, sample, time);\n      double status;\n      if (currentTurnToConsider == static_cast<int>(bounds.size()))\n      {\n        status = 0.0; // will stay outside from now on\n      }\n      else if (time < bounds[currentTurnToConsider][0])\n      {\n        status = 0.0; // before\n      }\n      else if (time < bounds[currentTurnToConsider][1])\n      {\n        status = 0.4; // inside \"before\" set of samples\n      }\n      else if (time < bounds[currentTurnToConsider][2])\n      {\n        status = 1.0; // inside turn samples\n      }\n      else if (time < bounds[currentTurnToConsider][3])\n      {\n        status = 0.2; // inside \"after\" set of samples\n      }\n      else\n      {\n        status = 0.0; // after\n        currentTurnToConsider = currentTurnToConsider + 1;\n      }\n      if (debugFileEnabled)\n      {\n        debugFile << PositionVectorFromTransform(sample)[0]\n                  << \",\" << PositionVectorFromTransform(sample)[1]\n                  << \",\" << PositionVectorFromTransform(sample)[2]\n                  << \",\" << status << std::endl;\n      }\n    }\n  }\n\n\n  if (debugFileEnabled)\n  {\n    if (verbose)\n    {\n      std::cout << \"Closing debug file\" << std::endl;\n    }\n    debugFile.close();\n  }\n\n  return bounds;\n}\n\nbool ProcessTurn(\n        const vtkSmartPointer<vtkVelodyneTransformInterpolator> reference,\n        const vtkSmartPointer<vtkVelodyneTransformInterpolator> aligned,\n        double t0, double t1, double t2, double t3,\n        DIRECTION_METHOD directionMethod,\n        NORMAL_METHOD normalMethod,\n        DIRECTION_OPTIMIZATION_METHOD normalBasedDirectionOptimisation,\n        AVERAGE_ORIENTATION_METHOD orientationMethod,\n        Eigen::Matrix3d& rotationBefore, // 1st result\n        Eigen::Matrix3d& rotationAfter, // 2nd result\n        double& scaleBefore,\n        double& scaleAfter\n        )\n{\n  if (!(t0 < t1 && t1 < t2 && t2 < t3))\n  {\n    std::cerr << \"WARNING: times not valid in ProcessTurn(). Bug in implementation\" << std::endl;\n    return false; // rotationBefore/After are not valid\n  }\n\n  Eigen::Vector3d vBeforeReference = GetXYZ(reference, t1) - GetXYZ(reference, t0);\n  Eigen::Vector3d vAfterReference = GetXYZ(reference, t3) - GetXYZ(reference, t2);\n  Eigen::Vector3d vBeforeAligned = GetXYZ(aligned, t1) - GetXYZ(aligned, t0);\n  Eigen::Vector3d vAfterAligned = GetXYZ(aligned, t3) - GetXYZ(aligned, t2);\n\n  scaleBefore = vBeforeAligned.norm() / vBeforeReference.norm();\n  scaleAfter = vAfterAligned.norm() / vAfterReference.norm();\n\n  // depending on options, these values will be recomputed later\n  // using a more robust method\n  Eigen::Vector3d directionBeforeReference = vBeforeReference.normalized();\n  Eigen::Vector3d directionAfterReference = vAfterReference.normalized();\n  Eigen::Vector3d directionBeforeAligned = vBeforeAligned.normalized();\n  Eigen::Vector3d directionAfterAligned = vAfterAligned.normalized();\n\n  if (directionMethod == DIRECTION_METHOD::TWO_POINTS)\n  {\n    // no need to recompute direction{Before,After}{Reference,Aligned}\n  }\n  else\n  {\n    std::cerr << \"WARNING: unimplemented option passed to ProcessTurn()\" << std::endl;\n    return false; // rotationBefore/After are not valid\n  }\n\n  // compute normal to plane containing the trajectory\n  Eigen::Vector3d normalOrientationReference;\n  Eigen::Vector3d normalOrientationAligned;\n  if (normalMethod == NORMAL_METHOD::CROSS_PRODUCT)\n  {\n    normalOrientationReference = directionBeforeReference.cross(directionAfterReference);\n    normalOrientationAligned = directionBeforeAligned.cross(directionAfterAligned);\n  }\n  else\n  {\n    std::cerr << \"WARNING: unimplemented option passed to ProcessTurn()\" << std::endl;\n    return false; // rotationBefore/After are not valid\n  }\n\n  if (normalBasedDirectionOptimisation == DIRECTION_OPTIMIZATION_METHOD::NONE)\n  {\n    // nothing to do\n  }\n  else\n  {\n    std::cerr << \"WARNING: unimplemented option passed to ProcessTurn()\" << std::endl;\n    return false; // rotationBefore/After are not valid\n  }\n\n  // compute orientation of trajectories\n  Eigen::Matrix3d trajectoryOrientationBeforeReference;\n  // operator \"<<\" stacks the vectors horizontally\n  // (Eigen vectors are vertical i.e. single-column matrices)\n  trajectoryOrientationBeforeReference <<\n      directionBeforeReference,\n      normalOrientationReference,\n      directionBeforeReference.cross(normalOrientationReference);\n\n  Eigen::Matrix3d trajectoryOrientationAfterReference;\n  trajectoryOrientationAfterReference <<\n      directionAfterReference,\n      normalOrientationReference,\n      directionAfterReference.cross(normalOrientationReference);\n\n  Eigen::Matrix3d trajectoryOrientationBeforeAligned;\n  trajectoryOrientationBeforeAligned <<\n      directionBeforeAligned,\n      normalOrientationAligned,\n      directionBeforeAligned.cross(normalOrientationAligned);\n\n  Eigen::Matrix3d trajectoryOrientationAfterAligned;\n  trajectoryOrientationAfterAligned <<\n      directionAfterAligned,\n      normalOrientationAligned,\n      directionAfterAligned.cross(normalOrientationAligned);\n\n  Eigen::Matrix3d RRemapBefore = trajectoryOrientationBeforeReference\n      * trajectoryOrientationBeforeAligned.transpose();\n\n  Eigen::Matrix3d RRemapAfter = trajectoryOrientationAfterReference\n      * trajectoryOrientationAfterAligned.transpose();\n\n  Eigen::Matrix3d orientationBeforeReference;\n  Eigen::Matrix3d orientationAfterReference;\n  Eigen::Matrix3d orientationBeforeAligned;\n  Eigen::Matrix3d orientationAfterAligned;\n  // compute remapped orientation of sensors\n  if (orientationMethod == AVERAGE_ORIENTATION_METHOD::SINGLE_POINT)\n  {\n        orientationBeforeReference = GetR(reference, t0);\n        orientationAfterReference = GetR(reference, t3);\n        orientationBeforeAligned = GetR(aligned, t0);\n        orientationAfterAligned = GetR(aligned, t3);\n  }\n  else\n  {\n    std::cerr << \"WARNING: unimplemented option passed to ProcessTurn()\" << std::endl;\n    return false; // rotationBefore/After are not valid\n  }\n\n  // compute rotation between sensors\n  // so that R_rotation * orientation_aligned = orientation_reference\n  rotationBefore = orientationBeforeReference.transpose()\n      * RRemapBefore * orientationBeforeAligned;\n  rotationAfter = orientationAfterReference.transpose()\n      * RRemapAfter * orientationAfterAligned;\n  return true; // rotations are valid\n}\n\nbool ProcessTurn(\n        const vtkSmartPointer<vtkVelodyneTransformInterpolator> reference,\n        const vtkSmartPointer<vtkVelodyneTransformInterpolator> aligned,\n        double t0, double t1, double t2, double t3,\n        Eigen::Matrix3d& rotationBefore, // 1st result\n        Eigen::Matrix3d& rotationAfter, // 2nd result\n        double scaleBefore,\n        double scaleAfter\n        )\n{\n  return ProcessTurn(\n        reference,\n        aligned,\n        t0, t1, t2, t3,\n        DIRECTION_METHOD::TWO_POINTS,\n        NORMAL_METHOD::CROSS_PRODUCT,\n        DIRECTION_OPTIMIZATION_METHOD::NONE,\n        AVERAGE_ORIENTATION_METHOD::SINGLE_POINT,\n        rotationBefore,\n        rotationAfter,\n        scaleBefore,\n        scaleAfter\n        );\n}\n\nenum class ROTATION_ESTIMATOR\n{\n  ESTIMATOR_UNDEFINED = 0,\n  ESTIMATOR_L2_CHORDAL_SVD = 0\n};\n\nvoid estimateL2ChordalSVD(const std::vector<Eigen::Matrix3d>& rotations,\n                    Eigen::Matrix3d& result,\n                    bool& valid)\n{\n  if (rotations.size() == 0)\n  {\n    result = Eigen::Matrix3d::Identity();\n    valid = false;\n  }\n\n  Eigen::Matrix3d S = Eigen::Matrix3d::Zero();\n  for (unsigned int i = 0; i < rotations.size(); i++)\n  {\n    S += rotations[i];\n  }\n\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd(S, Eigen::ComputeFullU | Eigen::ComputeFullV);\n  Eigen::Matrix3d U = svd.matrixU();\n  Eigen::Matrix3d V = svd.matrixV();\n  // we should have S == U * D * V.transpose();\n\n  Eigen::Matrix3d R = U *  V.transpose(); // not using singular values\n  if (R.determinant() < 0.0) // i.e. close to -1\n  {\n    Eigen::Vector3d D;\n    D << 1.0, 1.0, -1.0;\n    R = U * D.asDiagonal() * V.transpose();\n  }\n\n  result = R;\n  valid = true;\n}\n\nvoid RansacRotation(const std::vector<Eigen::Matrix3d>& rotations,\n                    ROTATION_ESTIMATOR estimator,\n                    int maxIterations,\n                    int sampleToEstimate,\n                    int sampleToValidate,\n                    float maxAngleToFit,\n                    Eigen::Matrix3d& result,\n                    bool& valid,\n                    int& samplesUsed)\n{\n  std::default_random_engine rng = std::default_random_engine();\n  std::vector<int> shuffled(rotations.size());\n  std::iota(std::begin(shuffled), std::end(shuffled), 0); //0 is the starting number\n\n  if (estimator != ROTATION_ESTIMATOR::ESTIMATOR_L2_CHORDAL_SVD)\n  {\n    std::cerr << \"Unknown estimator passed to RansacRotation\" << std::endl;\n    result = Eigen::Matrix3d::Identity();\n    valid = false;\n    return;\n  }\n  for (int i = 0; i < maxIterations; i++)\n  {\n    // re-shuffle\n    std::shuffle(std::begin(shuffled), std::end(shuffled), rng);\n    std::vector<Eigen::Matrix3d> samples = std::vector<Eigen::Matrix3d>(sampleToEstimate);\n    for (int j = 0; j < sampleToEstimate; j++)\n    {\n      samples[j] = rotations[shuffled[j]];\n    }\n\n    Eigen::Matrix3d estimation;\n    bool estimationValid = false;\n    estimateL2ChordalSVD(samples, estimation, estimationValid);\n    if (!estimationValid)\n    {\n      continue;\n    }\n\n    // count how many rotations are close enough:\n    std::vector<Eigen::Matrix3d> samplesFitting = std::vector<Eigen::Matrix3d>();\n    samplesFitting.reserve(rotations.size());\n    for (unsigned int j = 0; j < rotations.size(); j++)\n    {\n      double angle = Eigen::AngleAxisd(estimation.transpose() * rotations[j]).angle();\n      if (angle <= maxAngleToFit)\n      {\n        samplesFitting.push_back(rotations[j]);\n      }\n    }\n\n    if (static_cast<int>(samplesFitting.size()) >= sampleToValidate)\n    {\n      // do a final estimation, then return\n      samplesUsed = samplesFitting.size();\n      Eigen::Matrix3d estimation;\n      bool estimationValid = false;\n      estimateL2ChordalSVD(samplesFitting, estimation, estimationValid);\n      result = estimation;\n      valid = estimationValid;\n      return;\n    }\n  }\n\n  result = Eigen::Matrix3d::Identity();\n  valid = false;\n}\n\nvoid ComputeCarCalibrationRotationScale(\n        const vtkSmartPointer<vtkTemporalTransforms> reference,\n        const vtkSmartPointer<vtkTemporalTransforms> aligned,\n        double curveTreshold,\n        int ransacMaxIter,\n        double ransacMaxAngleToFit,\n        double ransacFittingRatio,\n        double ransacValidationRatio,\n        DIRECTION_METHOD directionMethod,\n        NORMAL_METHOD normalMethod,\n        DIRECTION_OPTIMIZATION_METHOD normalBasedDirectionOptimisation,\n        AVERAGE_ORIENTATION_METHOD orientationMethod,\n        Eigen::Matrix3d& result,\n        double& scale,\n        bool& validResult,\n        bool verbose\n        )\n{\n  vtkSmartPointer<vtkVelodyneTransformInterpolator> referenceI\n      = reference->CreateInterpolator();\n  referenceI->SetInterpolationTypeToLinear();\n  vtkSmartPointer<vtkVelodyneTransformInterpolator> alignedI\n      = aligned->CreateInterpolator();\n  alignedI->SetInterpolationTypeToLinear();\n  if (verbose)\n  {\n    std::cout << \"Detecting turns\" << std::endl;\n  }\n  std::vector<std::vector<double>> turns =\n      ComputeTurns(referenceI, 0.8, curveTreshold, false, \"\", verbose);\n  if (verbose)\n  {\n    std::cout << \"Processing \" << turns.size() << \" turns\" << std::endl;\n  }\n\n  std::vector<Eigen::Matrix3d> rotations = std::vector<Eigen::Matrix3d>();\n  std::vector<double> scales;\n  for (unsigned int i = 0; i < turns.size(); i++)\n  {\n    if (turns[i][0] < alignedI->GetMinimumT()\n                    || turns[i][3] > alignedI->GetMaximumT())\n    {\n      // if this turn (that was seen in \"reference\")\n      // is not contained in aligned, skip it\n      continue;\n    }\n    Eigen::Matrix3d RBefore;\n    Eigen::Matrix3d RAfter;\n    double scaleBefore, scaleAfter;\n    ProcessTurn(referenceI, alignedI,\n                turns[i][0], turns[i][1], turns[i][2], turns[i][3],\n                    directionMethod,\n                    normalMethod,\n                    normalBasedDirectionOptimisation,\n                    orientationMethod,\n                    RBefore,\n                    RAfter,\n                    scaleBefore,\n                    scaleAfter);\n\n    scales.push_back(scaleBefore);\n    scales.push_back(scaleAfter);\n\n    Eigen::Vector3d yprBefore = (180.0 / vtkMath::Pi()) * RBefore.eulerAngles(2,1,0);\n    Eigen::Vector3d yprAfter = (180.0 / vtkMath::Pi()) * RAfter.eulerAngles(2,1,0);\n    if (verbose)\n    {\n      std::cout << \"rotation before: \" << yprBefore[2]\n                << \", \" << yprBefore[1]\n                << \", \" << yprBefore[0] << std::endl;\n      std::cout << \"rotation after: \" << yprAfter[2]\n                << \", \" << yprAfter[1]\n                << \", \" << yprAfter[0] << std::endl;\n    }\n\n    if (RBefore.allFinite())\n    {\n      rotations.push_back((RBefore));\n    }\n    if (RAfter.allFinite())\n    {\n      rotations.push_back((RAfter));\n    }\n  }\n\n  if (verbose)\n  {\n    // must be displayed before any call of median on the std::vector, else the\n    // order is changed\n    for (unsigned int i = 0; i < scales.size() / 2; i++)\n    {\n      std::cout << \"scale before: \" << scales[2*i]\n                << \", scale after: \" << scales[2*i+1] << std::endl;\n    }\n  }\n\n  scale = ComputeMedian(scales);\n\n  if (verbose)\n  {\n    std::cout << \"median of scales is: \" << ComputeMedian(scales) << std::endl;\n  }\n\n\n  Eigen::Matrix3d R;\n  bool valid;\n  int sampleUsed = 0;\n  RansacRotation(rotations,\n                 ROTATION_ESTIMATOR::ESTIMATOR_L2_CHORDAL_SVD,\n                 ransacMaxIter,\n                 std::max(1, static_cast<int>(vtkMath::Round(ransacFittingRatio * static_cast<double>(rotations.size())))),\n                 std::max(1, static_cast<int>(vtkMath::Round(ransacValidationRatio * static_cast<double>(rotations.size())))),\n                 (vtkMath::Pi() / 180.0) * ransacMaxAngleToFit,\n                 R,\n                 valid,\n                 sampleUsed);\n\n  if (verbose)\n  {\n    if (valid)\n    {\n      std::cout << \"Ransac result is valid\" << std::endl;\n    }\n    else\n    {\n      std::cout << \"Ransac result not valid\" << std::endl;\n    }\n  }\n  Eigen::Vector3d rotationYPR = (180.0 / vtkMath::Pi()) * R.eulerAngles(2,1,0);\n  if (verbose)\n  {\n    std::cout << \"Rotation found using \" << sampleUsed << \" samples among \" << rotations.size() << \": \"\n              << rotationYPR[2] << \", \" << rotationYPR[1] << \", \" << rotationYPR[0] << std::endl;\n  }\n\n  if (valid)\n  {\n    result = R;\n  }\n  else\n  {\n    result = Eigen::Matrix3d::Identity();\n  }\n\n  validResult = valid;\n}\n\nvoid ComputeCarCalibrationRotationScale(\n        const vtkSmartPointer<vtkTemporalTransforms> reference,\n        const vtkSmartPointer<vtkTemporalTransforms> aligned,\n        double curveTreshold,\n        int ransacMaxIter,\n        double ransacMaxAngleToFit,\n        double ransacFittingRatio,\n        double ransacValidationRatio,\n        Eigen::Matrix3d& result,\n        double& scale,\n        bool& validResult,\n        bool verbose\n        )\n{\n  ComputeCarCalibrationRotationScale(reference, aligned, curveTreshold,\n        ransacMaxIter, ransacMaxAngleToFit,\n        ransacFittingRatio, ransacValidationRatio,\n        DIRECTION_METHOD::TWO_POINTS,\n        NORMAL_METHOD::CROSS_PRODUCT,\n        DIRECTION_OPTIMIZATION_METHOD::NONE,\n        AVERAGE_ORIENTATION_METHOD::SINGLE_POINT,\n        result, scale, validResult, verbose);\n}\n", "meta": {"hexsha": "6804211cef1b977d5dd43c3da6a801d948a293f6", "size": 27770, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "VelodyneHDL/Common/vtkCarGeometricCalibration.cxx", "max_stars_repo_name": "zhihua-wang/VeloView", "max_stars_repo_head_hexsha": "609d3e4c0cf722c512f4b0b2a615208557bb7757", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-10-28T07:02:34.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-28T07:03:50.000Z", "max_issues_repo_path": "VelodyneHDL/Common/vtkCarGeometricCalibration.cxx", "max_issues_repo_name": "zactodd/VeloView", "max_issues_repo_head_hexsha": "e0bd72a32464a9f62385ac5ce25df33580ed3cc2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-17T13:25:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T21:26:11.000Z", "max_forks_repo_path": "VelodyneHDL/Common/vtkCarGeometricCalibration.cxx", "max_forks_repo_name": "zactodd/VeloView", "max_forks_repo_head_hexsha": "e0bd72a32464a9f62385ac5ce25df33580ed3cc2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-08T11:28:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-08T11:28:59.000Z", "avg_line_length": 32.5175644028, "max_line_length": 126, "alphanum_fraction": 0.6389268995, "num_tokens": 7006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4149849311581831}}
{"text": "/**\n * Copyright (c) 2009 Carnegie Mellon University.\n *     All rights reserved.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http://www.graphlab.ml.cmu.edu\n *\n */\n\n\n/**\n * \\file\n *\n * Matrix factorization with the Alternative Least Squares (ALS)  - parallel coordinate descent algorithm.\n * See the papers:\n * H.-F. Yu, C.-J. Hsieh, S. Si, I. S. Dhillon, Scalable Coordinate Descent Approaches to Parallel Matrix Factorization for Recommender Systems. IEEE International Conference on Data Mining(ICDM), December 2012.\n * Steffen Rendle, Zeno Gantner, Christoph Freudenthaler, and Lars Schmidt-Thieme. 2011. Fast context-aware recommendations with factorization machines. In Proceedings of the 34th international ACM SIGIR conference on Research and development in Information Retrieval (SIGIR '11). ACM, New York, NY, USA, 635-644.\n * Written by Danny Bickson, CMU\n */\n\n#include <graphlab/util/stl_util.hpp>\n#include <graphlab/util/timer.hpp>\n#include <graphlab.hpp>\n#include <graphlab/engine/gl3engine.hpp>\n#include <Eigen/Dense>\n#include \"eigen_serialization.hpp\"\n#include <graphlab/macros_def.hpp>\n\ntypedef Eigen::VectorXd vec_type;\n\n#define ALS_COORD_MAP_REDUCE 0\n#define ALS_COORD_TRANSFORM 1\n//when using negative node id range, we are not allowed to use\n//0 and 1 so we add 2.\nconst static int SAFE_NEG_OFFSET=2;\nconst static int regnormal = 0;\nstatic bool debug;\nint max_iter = 10;\ndouble maxval = 1e100;\ndouble minval = -1e100;\nstd::string predictions;\nbool isuser(uint node){\n  return ((int)node) >= 0;\n}\n\n/**\n * \\ingroup toolkit_matrix_factorization\n *\n * \\brief the vertex data type which contains the latent pvec.\n *\n * Each row and each column in the matrix corresponds to a different\n * vertex in the SGD graph.  Associated with each vertex is a pvec\n * (vector) of latent parameters that represent that vertex.  The goal\n * of the SGD algorithm is to find the values for these latent\n * parameters such that the non-zero entries in the matrix can be\n * predicted by taking the dot product of the row and column pvecs.\n */\nstruct vertex_data {\n  /**\n   * \\brief A shared \"constant\" that specifies the number of latent\n   * values to use.\n   */\n  static size_t NLATENT;\n  /** \\brief The latent pvec for this vertex */\n  vec_type pvec;\n  vec_type prev;\n  float z;\n  int t; //index inside the latent feature vector\n\n  /**\n   * \\brief Simple default constructor which randomizes the vertex\n   *  data\n   */\n  vertex_data() : t(0),z(0) { if (debug) pvec = vec_type::Ones(NLATENT); else randomize(); prev = vec_type::Zero(NLATENT); }\n  /** \\brief Randomizes the latent pvec */\n  void randomize() { pvec.resize(NLATENT); pvec.setRandom(); }\n  /** \\brief Save the vertex data to a binary archive */\n  void save(graphlab::oarchive& arc) const {\n    arc << pvec << t << prev << z;\n  }\n  /** \\brief Load the vertex data from a binary archive */\n  void load(graphlab::iarchive& arc) {\n    arc >> pvec >> t >> prev >> z;\n  }\n}; // end of vertex data\n\nstd::size_t hash_value(vertex_data const& b) {\n  return (size_t)b.pvec[0]*1000;\n}\n\n\n/**\n * \\brief The edge data stores the entry in the matrix.\n *\n * In addition the edge data sgdo stores the most recent error estimate.\n */\nstruct edge_data : public graphlab::IS_POD_TYPE {\n  /**\n   * \\brief The type of data on the edge;\n   *\n   * \\li *Train:* the observed value is correct and used in training\n   * \\li *Validate:* the observed value is correct but not used in training\n   * \\li *Predict:* The observed value is not correct and should not be\n   *        used in training.\n   */\n  enum data_role_type { TRAIN, VALIDATE, PREDICT  };\n\n  /** \\brief the observed value for the edge */\n  float obs;\n  \n  /** \\brief cached value for A_ij - prediction */\n  float R_ij;\n\n  /** \\brief The train/validation/test designation of the edge */\n  data_role_type role;\n\n  /** \\brief basic initialization */\n  edge_data(float obs = 0, data_role_type role = PREDICT) :\n    obs(obs), role(role), R_ij(0) { }\n\n}; // end of edge data\n\nstd::size_t hash_value(edge_data const& b) {\n  return boost::hash_value(b.obs);\n}\n\n\n/**\n * \\brief The graph type is defined in terms of the vertex and edge\n * data.\n */\ntypedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;\ntypedef graphlab::gl3engine<graph_type> engine_type;\n\nbool isuser_node(const graph_type::vertex_type& vertex){\n  return isuser(vertex.id());\n}\n\n\n\n/**\n * \\brief The graph loader function is a line parser used for\n * distributed graph construction.\n */\ninline bool graph_loader(graph_type& graph,\n                         const std::string& filename,\n                         const std::string& line) {\n  ASSERT_FALSE(line.empty());\n  // Determine the role of the data\n  edge_data::data_role_type role = edge_data::TRAIN;\n  if(boost::ends_with(filename,\".validate\")) role = edge_data::VALIDATE;\n  else if(boost::ends_with(filename, \".predict\")) role = edge_data::PREDICT;\n  // Parse the line\n  std::stringstream strm(line);\n  graph_type::vertex_id_type source_id(-1), target_id(-1);\n  float obs(0);\n  strm >> source_id >> target_id;\n\n  // for test files (.predict) no need to read the actual rating value.\n  if(role == edge_data::TRAIN || role == edge_data::VALIDATE) {\n    strm >> obs;\n  }\n  target_id = -(graphlab::vertex_id_type(target_id + SAFE_NEG_OFFSET));\n\n  // Create an edge and add it to the graph\n  graph.add_edge(source_id, target_id, edge_data(obs, role));\n  return true; // successful load\n} // end of graph_loader\n\ndouble LAMBDA = 0.001;\n\nclass gather_type {\npublic:\n  double numerator;\n  double denominator;\n\n  gather_type() { \n    numerator = 0;\n    denominator = 0;\n  }\n\n  gather_type(double numerator, double denominator) : numerator(numerator),\n     denominator(denominator){\n  }\n\n  /** \\brief Save the values to a binary archive */\n  void save(graphlab::oarchive& arc) const { arc << numerator << denominator; }\n\n  /** \\brief Read the values from a binary archive */\n  void load(graphlab::iarchive& arc) { arc >> numerator >> denominator; }  \n\n  /** \n   * sums up values\n   */\n  gather_type& operator+=(const gather_type& other) {\n    numerator += other.numerator;\n    denominator += other.denominator;\n    return *this;\n  } // end of operator+=\n\n}; // end of gather type\n\n\n\ngather_type als_coord_map(const graph_type::vertex_type& center,\n                         graph_type::edge_type& edge,\n                         const graph_type::vertex_type& other) {\n\n   if (center.data().t == 0){\n     double prediction = center.data().pvec.dot(other.data().pvec);\n     prediction = std::min(prediction, maxval);\n     prediction = std::max(prediction, minval);\n     edge.data().R_ij = edge.data().obs - prediction;\n   }\n   //compute numerator of equation (6) in ICDM paper above\n   //             (A_ij        - w_i^T*h_j  + wit          * h_jt        )*h_jt \n   gather_type ret((edge.data().R_ij\n                               + center.data().pvec[center.data().t] * other.data().pvec[center.data().t])*other.data().pvec[center.data().t],\n   //compute denominator of equation (6) in ICDM paper above\n   //h_jt^2\n     pow(other.data().pvec[center.data().t], 2));\n   return ret;\n\n}\n\nvoid als_coord_transform(const graph_type::vertex_type& center,\n                         graph_type::edge_type& edge,\n                         const graph_type::vertex_type& other) {\n   //update using equation (7) in ICDM paper\n   //R_ij     -= (z             - w_it         )*h_jt\n   edge.data().R_ij -= (center.data().z - center.data().prev[center.data().t])*other.data().pvec[center.data().t];\n}\n\n\n//sum up two numerators and denomenators\nvoid als_coord_combine(gather_type& v1, const gather_type& v2) {\n    v1 += v2;\n}\n\n//the main update function\nvoid als_coord_function(engine_type::context_type& context,\n                  graph_type::vertex_type& vertex) {\n       \n   double regularization = LAMBDA;\n   for (vertex.data().t=0; vertex.data().t< (int)vertex_data::NLATENT; vertex.data().t++){\n     gather_type frac =  context.map_reduce<gather_type>(ALS_COORD_MAP_REDUCE, graphlab::ALL_EDGES);\n     assert(frac.denominator > 0);\n     vertex.data().z = (frac.numerator/(frac.denominator+regularization));  \n     vertex.data().prev = vertex.data().pvec;\n     //update using equation (8) in ICDM paper\n     //w_it                              = z;\n     vertex.data().pvec[vertex.data().t] = vertex.data().z;\n  \n     //update the cached R_ij using equation (7) in ICDM paper \n     context.edge_transform(ALS_COORD_TRANSFORM, graphlab::ALL_EDGES);\n   }\n\n}\n\n\n/**\n * \\brief Given an edge compute the error associated with that edge\n */\ndouble extract_l2_error(const graph_type::edge_type & edge) {\n  double pred =\n      edge.source().data().pvec.dot(edge.target().data().pvec);\n  double rmse = (edge.data().obs - pred) * (edge.data().obs - pred);\n  return rmse;\n} // end of extract_l2_error\n\n\n\nsize_t vertex_data::NLATENT = 20;\n/**\n * \\brief The prediction saver is used by the graph.save routine to\n * output the final predictions back to the filesystem.\n */\nstruct prediction_saver {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  std::string save_vertex(const vertex_type& vertex) const {\n    return \"\"; //nop\n  }\n  std::string save_edge(const edge_type& edge) const {\n    if(edge.data().role == edge_data::PREDICT) {\n      std::stringstream strm;\n      double prediction = \n        edge.source().data().pvec.dot(edge.target().data().pvec);\n      prediction = std::min(prediction, maxval);\n      prediction = std::max(prediction, minval);\n      strm << edge.source().id() << '\\t';\n      strm << (-edge.target().id() - SAFE_NEG_OFFSET) << '\\t';\n      strm << prediction << '\\n';\n      return strm.str();\n    } else return \"\";\n  }\n}; // end of prediction_saver\n\n\nstruct linear_model_saver_U {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  /* save the linear model, using the format:\n     nodeid) factor1 factor2 ... factorNLATENT \\n\n  */\n  std::string save_vertex(const vertex_type& vertex) const {\n    if (vertex.num_out_edges() > 0){\n      std::string ret = boost::lexical_cast<std::string>(vertex.id()) + \" \";\n      for (uint i=0; i< vertex_data::NLATENT; i++)\n        ret += boost::lexical_cast<std::string>(vertex.data().pvec[i]) + \" \";\n        ret += \"\\n\";\n      return ret;\n    }\n    else return \"\";\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\";\n  }\n}; \n\nstruct linear_model_saver_V {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  /* save the linear model, using the format:\n     nodeid) factor1 factor2 ... factorNLATENT \\n\n  */\n  std::string save_vertex(const vertex_type& vertex) const {\n    if (vertex.num_out_edges() == 0){\n      std::string ret = boost::lexical_cast<std::string>(-vertex.id()-SAFE_NEG_OFFSET) + \") \";\n      for (uint i=0; i< vertex_data::NLATENT; i++)\n        ret += boost::lexical_cast<std::string>(vertex.data().pvec[i]) + \" \";\n        ret += \"\\n\";\n      return ret;\n    }\n    else return \"\";\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\";\n  }\n}; \n\n\n\nint main(int argc, char** argv) {\n  global_logger().set_log_level(LOG_INFO);\n  global_logger().set_log_to_console(true);\n\n  // Parse command line options -----------------------------------------------\n  const std::string description =\n      \"Compute the ALS factorization of a matrix.\";\n  graphlab::command_line_options clopts(description);\n  std::string input_dir;\n  std::string exec_type = \"synchronous\";\n  clopts.attach_option(\"matrix\", input_dir,\n                       \"The directory containing the matrix file\");\n  clopts.add_positional(\"matrix\");\n  clopts.attach_option(\"D\", vertex_data::NLATENT,\n                       \"Number of latent parameters to use.\");\n  clopts.attach_option(\"maxval\", maxval, \"max allowed value\");\n  clopts.attach_option(\"minval\", minval, \"min allowed value\");\n  clopts.attach_option(\"predictions\", predictions,\n                       \"The prefix (folder and filename) to save predictions.\");\n  clopts.attach_option(\"lambda\", LAMBDA,\n                       \"regularization weight\");\n  clopts.attach_option(\"max_iter\", max_iter,\n                       \"number of iterations\");\n  if(!clopts.parse(argc, argv) || input_dir == \"\") {\n    std::cout << \"Error in parsing command line arguments.\" << std::endl;\n    clopts.print_description();\n    return EXIT_FAILURE;\n  }\n  ///! Initialize control plain using mpi\n  graphlab::mpi_tools::init(argc, argv);\n  graphlab::distributed_control dc;\n\n  dc.cout() << \"Loading graph.\" << std::endl;\n  graphlab::timer timer;\n  graph_type graph(dc, clopts);\n  graph.load(input_dir, graph_loader);\n  dc.cout() << \"Loading graph. Finished in \"\n            << timer.current_time() << std::endl;\n\n  dc.cout() << \"Finalizing graph.\" << std::endl;\n  timer.start();\n  graph.finalize();\n  dc.cout() << \"Finalizing graph. Finished in \"\n            << timer.current_time() << std::endl;\n\n  if (!graph.num_edges() || !graph.num_vertices())\n     logstream(LOG_FATAL)<< \"Failed to load graph. Check your input path: \" << input_dir << std::endl;     \n\n\n  dc.cout()\n      << \"========== Graph statistics on proc \" << dc.procid()\n      << \" ===============\"\n      << \"\\n Num vertices: \" << graph.num_vertices()\n      << \"\\n Num edges: \" << graph.num_edges()\n      << \"\\n Num replica: \" << graph.num_replicas()\n      << \"\\n Replica to vertex ratio: \"\n      << float(graph.num_replicas())/graph.num_vertices()\n      << \"\\n --------------------------------------------\"\n      << \"\\n Num local own vertices: \" << graph.num_local_own_vertices()\n      << \"\\n Num local vertices: \" << graph.num_local_vertices()\n      << \"\\n Replica to own ratio: \"\n      << (float)graph.num_local_vertices()/graph.num_local_own_vertices()\n      << \"\\n Num local edges: \" << graph.num_local_edges()\n      //<< \"\\n Begin edge id: \" << graph.global_eid(0)\n        << \"\\n Edge balance ratio: \"\n        << float(graph.num_local_edges())/graph.num_edges()\n        << std::endl;\n\n  dc.cout() << \"Creating engine\" << std::endl;\n\n  engine_type engine(dc, graph, clopts);\n  engine.register_map_reduce(ALS_COORD_MAP_REDUCE, als_coord_map, als_coord_combine);\n  engine.register_edge_transform(ALS_COORD_TRANSFORM, als_coord_transform);\n  for (int i=0; i< max_iter; i++){\n     engine.parfor_all_local_vertices(als_coord_function);\n     engine.wait();\n     double rmse = graph.map_reduce_edges<double>(extract_l2_error);\n     dc.cout() << \"RMSE = \" << sqrt(rmse / graph.num_edges()) << std::endl;\n  }\n\n  const double runtime = timer.current_time();\n  dc.cout() << \"----------------------------------------------------------\"\n            << std::endl\n            << \"Final Runtime (seconds):   \" << runtime;\n\n  // Compute the final training error -----------------------------------------\n  dc.cout() << \"Final error: \" << std::endl;\n  // Make predictions ---------------------------------------------------------\n  if(!predictions.empty()) {\n    std::cout << \"Saving predictions\" << std::endl;\n    const bool gzip_output = false;\n    const bool save_vertices = false;\n    const bool save_edges = true;\n    const size_t threads_per_machine = 2;\n\n    //save the predictions\n    graph.save(predictions, prediction_saver(),\n               gzip_output, save_vertices, \n               save_edges, threads_per_machine);\n    //save the linear model\n    graph.save(predictions + \".U\", linear_model_saver_U(),\n\t\tgzip_output, save_edges, save_vertices, threads_per_machine);\n    graph.save(predictions + \".V\", linear_model_saver_V(),\n\t\tgzip_output, save_edges, save_vertices, threads_per_machine);\n  \n  }\n \n\n  graphlab::mpi_tools::finalize();\n  return EXIT_SUCCESS;\n} // end of main\n\n\n\n", "meta": {"hexsha": "285ccbe4d08cd9ccbfbec820c5513e0ce592fe81", "size": 16245, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/collaborative_filtering/warp_als_coord.cpp", "max_stars_repo_name": "coreyp1/graphlab", "max_stars_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T11:46:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T22:45:55.000Z", "max_issues_repo_path": "toolkits/collaborative_filtering/warp_als_coord.cpp", "max_issues_repo_name": "coreyp1/graphlab", "max_issues_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/collaborative_filtering/warp_als_coord.cpp", "max_forks_repo_name": "coreyp1/graphlab", "max_forks_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T12:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T16:48:40.000Z", "avg_line_length": 34.4904458599, "max_line_length": 313, "alphanum_fraction": 0.6483841182, "num_tokens": 4038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.414984924197607}}
{"text": "/**\n * \\file fea/tetrahedral_mesh.cpp\n * This file is part of SANM, a symbolic asymptotic numerical solver.\n */\n\n#include \"fea/tetrahedral_mesh.h\"\n#include \"fea/mesh_template.h\"\n\n#include <Eigen/Dense>\n\n#include <cerrno>\n#include <cstdio>\n#include <cstring>\n#include <fstream>\n\nusing namespace fea;\n\nINST_MESH_IO_TRANS(3, TetrahedralMesh);\n\nnamespace {\nvoid copy_mat3_cols(fp_t* dst, const Vec3& c0, const Vec3& c1, const Vec3& c2) {\n    const Vec3* cs[] = {&c0, &c1, &c2};\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            dst[i * 3 + j] = (*cs[j])[i];\n        }\n    }\n}\n}  // anonymous namespace\n\nconst CoordMat3D& TetrahedralMesh::vertex_norms() const {\n    if (m_vertex_norms.valid()) {\n        return m_vertex_norms.val();\n    }\n    size_t nr_tet = this->nr_tet();\n    m_vertex_norms.init();\n    CoordMat3D& vertex_norms = m_vertex_norms.val();\n    vertex_norms.resize(3, nr_tet * 4);\n    m_tet_volumes.resize(nr_tet);\n    auto ds_ptr = m_shape_matrix.set_shape({nr_tet, 3, 3}).woptr();\n\n    for (size_t i = 0; i < nr_tet; ++i) {\n        Vec3 x0 = m_vertices.col(m_tet(0, i)), x1 = m_vertices.col(m_tet(1, i)),\n             x2 = m_vertices.col(m_tet(2, i)), x3 = m_vertices.col(m_tet(3, i)),\n             v1 = x1 - x0, v2 = x2 - x0, v3 = x3 - x0;\n        copy_mat3_cols(ds_ptr + i * 9, v1, v2, v3);\n\n        fp_t det = v1.dot(v2.cross(v3));\n\n        m_tet_volumes[i] = std::fabs(det) / 6;\n\n        // - volume * D^{-T}, equal to -cofactor*sign(det)\n        // normal for a vertex is also the area-weighted outward normal of the\n        // opposite face\n\n        Vec3 t1 = v2.cross(v3), t2 = v3.cross(v1), t3 = v1.cross(v2);\n        if (det > 0) {\n            t1 = -t1;\n            t2 = -t2;\n            t3 = -t3;\n        }\n        vertex_norms.col(4 * i + 0) = -(t1 + t2 + t3);\n        vertex_norms.col(4 * i + 1) = t1;\n        vertex_norms.col(4 * i + 2) = t2;\n        vertex_norms.col(4 * i + 3) = t3;\n    }\n    vertex_norms *= 1.0 / 6;\n    return vertex_norms;\n}\n\nconst std::vector<fp_t>& TetrahedralMesh::tet_volumes() const {\n    if (m_tet_volumes.empty()) {\n        vertex_norms();\n    }\n    return m_tet_volumes;\n}\n\nconst sanm::TensorND& TetrahedralMesh::shape_matrix() const {\n    if (m_shape_matrix.empty()) {\n        vertex_norms();\n    }\n    return m_shape_matrix;\n}\n\nconst MeshVertexReverseList& TetrahedralMesh::vertex_reverse_list() const {\n    if (!m_vertex_reverse_list.valid()) {\n        m_vertex_reverse_list.init(\n                MeshVertexReverseList::from_mesh<4>(nr_vertices(), m_tet));\n    }\n    return m_vertex_reverse_list.val();\n}\n\nTetrahedralMeshPtr TetrahedralMesh::make_cuboid(size_t nr_vtx_x,\n                                                size_t nr_vtx_y,\n                                                size_t nr_vtx_z, fp_t size) {\n    sanm_assert(nr_vtx_x >= 2 && nr_vtx_y >= 2 && nr_vtx_z >= 2 && size > 0);\n    // code adopted from the CompFabAssignment\n    const int vertex_num = nr_vtx_x * nr_vtx_y * nr_vtx_z;\n    const int element_num =\n            5 * (nr_vtx_x - 1) * (nr_vtx_y - 1) * (nr_vtx_z - 1);\n    auto ret = std::make_shared<TetrahedralMesh>();\n    CoordMat3D& vertex = ret->m_vertices;\n    TetIndexMat& element = ret->m_tet;\n    vertex.resize(3, vertex_num);\n    element.resize(4, element_num);\n    int id = 0;\n    for (size_t i = 0; i < nr_vtx_x; i++) {\n        for (size_t j = 0; j < nr_vtx_y; j++) {\n            for (size_t k = 0; k < nr_vtx_z; k++) {\n                vertex(0, id) = i * size;\n                vertex(1, id) = j * size;\n                vertex(2, id) = k * size;\n                if (i == 0 || i == nr_vtx_x - 1 || j == 0 ||\n                    j == nr_vtx_y - 1 || k == 0 || k == nr_vtx_z - 1) {\n                    ret->m_surface_vtx.insert(id);\n                }\n                id++;\n            }\n        }\n    }\n    auto get_cuboid_id = [nr_vtx_y, nr_vtx_z](size_t x, size_t y,\n                                              size_t z) -> int {\n        return (x * nr_vtx_y + y) * nr_vtx_z + z;\n    };\n    id = 0;\n    for (size_t i = 0; i < nr_vtx_x - 1; i++) {\n        for (size_t j = 0; j < nr_vtx_y - 1; j++) {\n            for (size_t k = 0; k < nr_vtx_z - 1; k++) {\n                int hex_id[] = {get_cuboid_id(i, j, k),\n                                get_cuboid_id(i + 1, j, k),\n                                get_cuboid_id(i + 1, j + 1, k),\n                                get_cuboid_id(i, j + 1, k),\n                                get_cuboid_id(i, j, k + 1),\n                                get_cuboid_id(i + 1, j, k + 1),\n                                get_cuboid_id(i + 1, j + 1, k + 1),\n                                get_cuboid_id(i, j + 1, k + 1)};\n                auto add_face = [&](int a, int b, int c) {\n                    auto& t = ret->m_surfaces.emplace_back();\n                    t[0] = hex_id[a];\n                    t[1] = hex_id[b];\n                    t[2] = hex_id[c];\n                };\n\n                if (i == 0) {\n                    add_face(3, 0, 7);\n                    add_face(7, 0, 4);\n                }\n                if (i == nr_vtx_x - 2) {\n                    add_face(1, 2, 6);\n                    add_face(6, 5, 1);\n                }\n                if (j == 0) {\n                    add_face(0, 1, 5);\n                    add_face(0, 5, 4);\n                }\n                if (j == nr_vtx_y - 2) {\n                    add_face(7, 6, 3);\n                    add_face(6, 2, 3);\n                }\n                if (k == 0) {\n                    add_face(1, 3, 2);\n                    add_face(0, 3, 1);\n                }\n                if (k == nr_vtx_z - 2) {\n                    add_face(4, 5, 7);\n                    add_face(7, 5, 6);\n                }\n\n                // 0, 2, 1, 5\n                element(0, id) = hex_id[0];\n                element(1, id) = hex_id[2];\n                element(2, id) = hex_id[1];\n                element(3, id) = hex_id[5];\n                id++;\n                // 0, 4, 7, 5\n                element(0, id) = hex_id[0];\n                element(1, id) = hex_id[4];\n                element(2, id) = hex_id[7];\n                element(3, id) = hex_id[5];\n                id++;\n                // 0, 2, 5, 7\n                element(0, id) = hex_id[0];\n                element(1, id) = hex_id[2];\n                element(2, id) = hex_id[5];\n                element(3, id) = hex_id[7];\n                id++;\n                // 2, 6, 5, 7\n                element(0, id) = hex_id[2];\n                element(1, id) = hex_id[6];\n                element(2, id) = hex_id[5];\n                element(3, id) = hex_id[7];\n                id++;\n                // 0, 7, 3, 2\n                element(0, id) = hex_id[0];\n                element(1, id) = hex_id[7];\n                element(2, id) = hex_id[3];\n                element(3, id) = hex_id[2];\n                id++;\n            }\n        }\n    }\n    sanm_assert(id == element_num);\n    return ret;\n}\n\nTetrahedralMeshPtr TetrahedralMesh::from_tetgen_files(\n        const std::string& filebase) {\n    std::ifstream fin_ele{filebase + \".ele\"}, fin_node{filebase + \".node\"},\n            fin_face{filebase + \".face\"};\n    sanm_assert(fin_ele.good() && fin_node.good() && fin_face.good(),\n                \"failed to open input files: %s.{ele,node,face}\",\n                filebase.c_str());\n    auto ret = std::make_shared<TetrahedralMesh>();\n\n    // see https://wias-berlin.de/software/tetgen/fformats.node.html\n    size_t nr_vtx, dim, nr_attr, bound_mark;\n    fin_node >> nr_vtx >> dim >> nr_attr >> bound_mark;\n    sanm_assert(dim == 3 && !nr_attr && !bound_mark);\n\n    CoordMat3D& vtx = ret->m_vertices;\n    vtx.resize(3, nr_vtx);\n    for (size_t i = 0; i < nr_vtx; ++i) {\n        size_t idx;\n        fin_node >> idx >> vtx(0, i) >> vtx(1, i) >> vtx(2, i);\n        sanm_assert(idx == i, \"failed to read vertex %zu: got idx %zu\", i, idx);\n    }\n    sanm_assert(fin_node.good());\n\n    // see https://wias-berlin.de/software/tetgen/fformats.ele.html\n    size_t nr_tet, node_per_tet;\n    fin_ele >> nr_tet >> node_per_tet >> nr_attr;\n    sanm_assert(node_per_tet == 4 && !nr_attr);\n\n    TetIndexMat& tet = ret->m_tet;\n    tet.resize(4, nr_tet);\n    for (size_t i = 0; i < nr_tet; ++i) {\n        size_t idx;\n        fin_ele >> idx >> tet(0, i) >> tet(1, i) >> tet(2, i) >> tet(3, i);\n        sanm_assert(idx == i, \"failed to read tetrahedron %zu: got idx %zu\", i,\n                    idx);\n    }\n\n    size_t nr_face, boundary_marker;\n    fin_face >> nr_face >> boundary_marker;\n    for (size_t i = 0; i < nr_face; ++i) {\n        size_t idx;\n        int a, b, c;\n        fin_face >> idx >> a >> b >> c;\n        sanm_assert(idx == i);\n        ret->m_surface_vtx.insert(a);\n        ret->m_surface_vtx.insert(b);\n        ret->m_surface_vtx.insert(c);\n        if (boundary_marker) {\n            fin_face >> b;\n        }\n        // do not read into m_surfaces since tetgen may invert the surface\n    }\n\n    return ret;\n}\n\nvoid TetrahedralMesh::write_to_file(FILE* fout,\n                                    const VertexSet* filter_set) const {\n    if (!filter_set) {\n        if (!m_surfaces.empty()) {\n            write_to_file(fout, m_vertices, m_surfaces);\n            return;\n        }\n\n        if (!m_surface_vtx.empty()) {\n            filter_set = &m_surface_vtx;\n        }\n    }\n    write_to_file(fout, m_vertices, m_tet, filter_set);\n}\n\nvoid TetrahedralMesh::write_to_surface_vtx_file(FILE* fout) const {\n    sanm_assert(!m_surface_vtx.empty());\n    int vmin = std::numeric_limits<int>::max(), vmax = 0;\n    for (int i : m_surface_vtx) {\n        vmin = std::min(vmin, i);\n        vmax = std::max(vmax, i);\n    }\n    sanm_assert(vmin == 0, \"min surface vtx num is not zero: %d\", vmin);\n    sanm_assert(vmax == static_cast<int>(m_surface_vtx.size()) - 1,\n                \"max surface vtx num is %d, size is %zu\", vmax,\n                m_surface_vtx.size());\n\n    for (int i = vmin; i <= vmax; ++i) {\n        const Vec3& v = m_vertices.col(i);\n        fprintf(fout, \"%g %g %g\\n\", v[0], v[1], v[2]);\n    }\n}\n\nvoid TetrahedralMesh::write_to_file(FILE* fout, const CoordMat3D& V,\n                                    const TetIndexMat& F,\n                                    const VertexSet* filter_set) {\n    sanm_assert(fout);\n    std::unordered_map<int, int> vtx_id_map;\n    if (filter_set) {\n        sanm_assert(!filter_set->empty());\n    }\n    auto write_facet = [fout, filter_set, &vtx_id_map](int v0, int v1, int v2) {\n        if (filter_set) {\n            if (!filter_set->count(v0) || !filter_set->count(v1) ||\n                !filter_set->count(v2)) {\n                return;\n            }\n            v0 = vtx_id_map.at(v0);\n            v1 = vtx_id_map.at(v1);\n            v2 = vtx_id_map.at(v2);\n        }\n        fprintf(fout, \"f %d %d %d\\n\", v0 + 1, v1 + 1, v2 + 1);\n    };\n    for (int i = 0; i < V.cols(); ++i) {\n        if (!filter_set || filter_set->count(i)) {\n            if (filter_set) {\n                int id = vtx_id_map.size();\n                vtx_id_map[i] = id;\n            }\n            Vec3 vi = V.col(i);\n            fprintf(fout, \"v %g %g %g\\n\", vi.x(), vi.y(), vi.z());\n        }\n    }\n\n    for (Eigen::Index i = 0; i < F.cols(); ++i) {\n        int i0 = F(0, i), i1 = F(1, i), i2 = F(2, i), i3 = F(3, i);\n        Vec3 v0 = V.col(i0), v1 = V.col(i1), v2 = V.col(i2), v3 = V.col(i3);\n\n        if ((v1 - v0).dot((v2 - v0).cross(v3 - v0)) > 0) {\n            std::swap(i1, i2);\n        }\n\n        write_facet(i0, i1, i2);\n        write_facet(i1, i3, i2);\n        write_facet(i1, i0, i3);\n        write_facet(i0, i2, i3);\n    }\n}\n\nvoid TetrahedralMesh::write_to_file(FILE* fout, const CoordMat3D& V,\n                                    const FaceList& F) {\n    sanm_assert(fout && !F.empty());\n    std::unordered_map<int, int> vtx_id_map;\n    std::vector<int> vtx_ids;\n    vtx_ids.reserve(F.size() * 2);\n    vtx_id_map.reserve(F.size() * 2);\n\n    for (auto&& f : F) {\n        for (int v : f) {\n            int id = vtx_id_map.size();\n            if (vtx_id_map.insert({v, id}).second) {\n                vtx_ids.push_back(v);\n            }\n        }\n    }\n\n    for (int i : vtx_ids) {\n        Vec3 vi = V.col(i);\n        fprintf(fout, \"v %g %g %g\\n\", vi.x(), vi.y(), vi.z());\n    }\n\n    for (auto&& f : F) {\n        int v0 = vtx_id_map.at(f[0]), v1 = vtx_id_map.at(f[1]),\n            v2 = vtx_id_map.at(f[2]);\n        fprintf(fout, \"f %d %d %d\\n\", v0 + 1, v1 + 1, v2 + 1);\n    }\n}\n\nvoid TetrahedralMesh::replace_with_mask(const CoordMask3D& mask,\n                                        const sanm::TensorND& value) {\n    fea::replace_with_mask(m_vertices, mask, value.ptr(),\n                           value.shape().total_nr_elems());\n    clear_cache();\n}\n\nvoid TetrahedralMesh::apply_vtx_delta(const CoordMat3D& delta) {\n    sanm_assert(delta.cols() == m_vertices.cols());\n    m_vertices += delta;\n    clear_cache();\n}\n\nvoid TetrahedralMesh::replace_vtx(const CoordMat3D& vtx) {\n    sanm_assert(vtx.cols() == m_vertices.cols());\n    m_vertices = vtx;\n    clear_cache();\n}\n\nvoid TetrahedralMesh::clear_cache() {\n    m_vertex_norms.reset();\n    m_tet_volumes.clear();\n    m_shape_matrix.clear();\n}\n\nvoid TetrahedralMesh::resize_inplace(fp_t scale) {\n    m_vertices *= scale;\n    clear_cache();\n}\n", "meta": {"hexsha": "6c92904b0043d197099f32c49d5c5f6570547cd1", "size": 13255, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fea/tetrahedral_mesh.cpp", "max_stars_repo_name": "jia-kai/SANM", "max_stars_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T09:27:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T15:22:05.000Z", "max_issues_repo_path": "fea/tetrahedral_mesh.cpp", "max_issues_repo_name": "jia-kai/SANM", "max_issues_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-03T05:31:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-05T01:37:42.000Z", "max_forks_repo_path": "fea/tetrahedral_mesh.cpp", "max_forks_repo_name": "jia-kai/SANM", "max_forks_repo_head_hexsha": "2673ac476b3d2978a52bf47bc12d3402ea20f211", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2205513784, "max_line_length": 80, "alphanum_fraction": 0.4844964164, "num_tokens": 4021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.6370307944803832, "lm_q1q2_score": 0.41493309830420827}}
{"text": "#define CGAL_CHECK_EXPENSIVE\n\n#include <CGAL/Simple_cartesian.h>\n\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/boost/graph/Seam_mesh.h>\n\n#include <CGAL/Surface_mesh_parameterization/Error_code.h>\n#include <CGAL/surface_mesh_parameterization.h>\n\n#include <CGAL/Polygon_mesh_processing/measure.h>\n#include <CGAL/Polygon_mesh_processing/connected_components.h>\n\n#include <boost/functional/hash.hpp>\n\n#include <iostream>\n#include <fstream>\n\nnamespace SMP = CGAL::Surface_mesh_parameterization;\nnamespace PMP = CGAL::Polygon_mesh_processing;\n\ntypedef CGAL::Simple_cartesian<double>            Kernel;\ntypedef Kernel::Point_2                           Point_2;\ntypedef Kernel::Point_3                           Point_3;\n\n#define MVC_POLYHEDRON_MESH\n#define ARAP_POLYHEDRON_MESH\n#define BARY_SURF_MESH\n#define ARAP_SURF_MESH\n#define DCM_PM_SEAM_MESH\n#define DAC_SM_SEAM_MESH\n#define ORBIFOLD_SM_MESH\n#define ITERATIVE_SURF_MESH\n\n// POLYHEDRON_MESH\ntypedef CGAL::Polyhedron_3<Kernel>                                PMesh;\n\ntypedef boost::graph_traits<PMesh>::vertex_descriptor             PM_vertex_descriptor;\ntypedef boost::graph_traits<PMesh>::halfedge_descriptor           PM_halfedge_descriptor;\n\ntypedef CGAL::Unique_hash_map<PM_halfedge_descriptor, Point_2>    PM_UV_hmap;\ntypedef boost::associative_property_map<PM_UV_hmap>               PM_UV_pmap;\n\n// SURF_MESH\ntypedef CGAL::Surface_mesh<Point_3>                               SMesh;\n\ntypedef boost::graph_traits<SMesh>::vertex_descriptor             SM_vertex_descriptor;\ntypedef boost::graph_traits<SMesh>::halfedge_descriptor           SM_halfedge_descriptor;\n\ntypedef SMesh::Property_map<SM_halfedge_descriptor, Point_2>      SM_UV_pmap;\n\n// PM_SEAM_MESH\ntypedef boost::graph_traits<PMesh>::edge_descriptor               PM_edge_descriptor;\n\ntypedef CGAL::Unique_hash_map<PM_edge_descriptor, bool>           PM_seam_edge_hmap;\ntypedef boost::associative_property_map<PM_seam_edge_hmap>        PM_seam_edge_pmap;\ntypedef CGAL::Unique_hash_map<PM_vertex_descriptor, bool>         PM_seam_vertex_hmap;\ntypedef boost::associative_property_map<PM_seam_vertex_hmap>      PM_seam_vertex_pmap;\n\ntypedef CGAL::Seam_mesh<PMesh, PM_seam_edge_pmap, PM_seam_vertex_pmap>\n                                                                  PM_Seam_mesh;\n\ntypedef boost::graph_traits<PM_Seam_mesh>::vertex_descriptor      PM_SE_vertex_descriptor;\ntypedef boost::graph_traits<PM_Seam_mesh>::halfedge_descriptor    PM_SE_halfedge_descriptor;\n\n// SM_SEAM_MESH\ntypedef boost::graph_traits<SMesh>::edge_descriptor               SM_edge_descriptor;\n\ntypedef SMesh::Property_map<SM_edge_descriptor, bool>             SM_seam_edge_pmap;\ntypedef SMesh::Property_map<SM_vertex_descriptor, bool>           SM_seam_vertex_pmap;\n\ntypedef CGAL::Seam_mesh<SMesh, SM_seam_edge_pmap, SM_seam_vertex_pmap>\n                                                                  SM_Seam_mesh;\n\ntypedef boost::graph_traits<SM_Seam_mesh>::vertex_descriptor      SM_SE_vertex_descriptor;\ntypedef boost::graph_traits<SM_Seam_mesh>::halfedge_descriptor    SM_SE_halfedge_descriptor;\n\nint main(int, char**)\n{\n  std::cout.precision(17);\n  CGAL::IO::set_pretty_mode(std::cout);\n\n  // ***************************************************************************\n  // Default case\n  // ***************************************************************************\n\n#ifdef MVC_POLYHEDRON_MESH\n  {\n    std::cout << \" ----------- MVC POLYHEDRON -----------\" << std::endl;\n\n    std::ifstream in(CGAL::data_file_path(\"meshes/mushroom.off\"));\n    PMesh pm;\n    in >> pm;\n    if(!in || num_vertices(pm) == 0) {\n      std::cerr << \"Problem loading the input data\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    PM_halfedge_descriptor hd = PMP::longest_border(pm).first;\n\n    CGAL::Unique_hash_map<PM_vertex_descriptor, Point_2,\n                          boost::hash<PM_vertex_descriptor> > uvhm;\n    boost::associative_property_map<\n      CGAL::Unique_hash_map<PM_vertex_descriptor, Point_2,\n                            boost::hash<PM_vertex_descriptor> > > uvpm(uvhm);\n\n    // Go to default (MVC)\n    SMP::Error_code status = SMP::parameterize(pm, hd, uvpm);\n\n    if(status != SMP::OK) {\n      std::cout << \"Encountered a problem: \" << status << std::endl;\n      return EXIT_FAILURE;\n    }\n    else {\n      std::cout << \"Parameterized with MVC (POLY)!\" << std::endl;\n    }\n  }\n#endif // MVC_POLYHEDRON_MESH\n\n  // ***************************************************************************\n  // ARAP WITH POLYHEDRON_MESH\n  // ***************************************************************************\n\n#ifdef ARAP_POLYHEDRON_MESH\n  {\n    std::cout << \" ----------- ARAP POLYHEDRON -----------\" << std::endl;\n\n    std::ifstream in(CGAL::data_file_path(\"meshes/three_peaks.off\"));\n    PMesh pm;\n    in >> pm;\n    if(!in || num_vertices(pm) == 0) {\n      std::cerr << \"Problem loading the input data\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    PM_halfedge_descriptor hd = PMP::longest_border(pm).first;\n\n    // UV map\n    CGAL::Unique_hash_map<PM_vertex_descriptor, Point_2,\n                          boost::hash<PM_vertex_descriptor> > uvhm;\n    boost::associative_property_map<\n      CGAL::Unique_hash_map<PM_vertex_descriptor, Point_2,\n                            boost::hash<PM_vertex_descriptor> > > uvpm(uvhm);\n\n    // Indices map\n    typedef CGAL::dynamic_vertex_property_t<int>                                 Vertex_int_tag;\n    typedef typename boost::property_map<PMesh, Vertex_int_tag>::type            Vertex_int_map;\n    Vertex_int_map vipm = get(Vertex_int_tag(), pm);\n    CGAL::Surface_mesh_parameterization::internal::fill_index_map_of_cc(hd, pm, vipm);\n\n    // Vertex parameterized map\n    typedef CGAL::dynamic_vertex_property_t<bool>                                Vertex_bool_tag;\n    typedef typename boost::property_map<PMesh, Vertex_bool_tag>::type           Vertex_bool_map;\n    Vertex_bool_map vpm = get(Vertex_bool_tag(), pm);\n\n    // Parameterizer\n    SMP::ARAP_parameterizer_3<PMesh> parameterizer;\n    SMP::Error_code status = parameterizer.parameterize(pm, hd, uvpm, vipm, vpm);\n    SMP::Error_code status_bis = SMP::parameterize(pm, parameterizer, hd, uvpm);\n    if(status != SMP::OK || status_bis != SMP::OK) {\n      std::cout << \"Encountered a problem: \" << status << std::endl;\n      return EXIT_FAILURE;\n    }\n    else {\n      std::cout << \"Parameterized with ARAP (POLY)!\" << std::endl;\n    }\n  }\n#endif // ARAP_POLYHEDRON_MESH\n\n  // ***************************************************************************\n  // Barycentric mapping\n  // ***************************************************************************\n\n#ifdef BARY_SURF_MESH\n  {\n    std::cout << \" ----------- BARY SURFACE MESH ----------- \" << std::endl;\n\n    std::ifstream in(\"data/oni.off\");\n    SMesh sm;\n    in >> sm;\n    if(!in || num_vertices(sm) == 0) {\n      std::cerr << \"Problem loading the input data\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    SM_halfedge_descriptor hd = PMP::longest_border(sm).first;\n    assert(hd != SM_halfedge_descriptor());\n\n    // UV map\n    typedef SMesh::Property_map<SM_vertex_descriptor, Point_2>  UV_pmap;\n    UV_pmap uvpm = sm.add_property_map<SM_vertex_descriptor, Point_2>(\"h:uv\").first;\n\n    // Indices map\n    typedef boost::unordered_map<SM_vertex_descriptor, int> Indices;\n    Indices indices;\n    PMP::connected_component(face(opposite(hd, sm), sm), sm,\n                             boost::make_function_output_iterator(\n                               SMP::internal::Index_map_filler<SMesh, Indices>(sm, indices)));\n    boost::associative_property_map<Indices> vipm(indices);\n\n    // Vertex parameterized map\n    boost::unordered_set<SM_vertex_descriptor> vs;\n    SMP::internal::Bool_property_map<boost::unordered_set<SM_vertex_descriptor> > vpm(vs);\n\n    // Parameterizer\n    SMP::Barycentric_mapping_parameterizer_3<SMesh> parameterizer;\n\n    SMP::Error_code status = parameterizer.parameterize(sm, hd, uvpm, vipm, vpm);\n    SMP::Error_code status_bis = SMP::parameterize(sm, parameterizer, hd, uvpm);\n\n    if(status != SMP::OK || status_bis != SMP::OK) {\n      std::cout << \"Encountered a problem: \" << status << std::endl;\n      return EXIT_FAILURE;\n    }\n    else {\n      std::cout << \"Parameterized with Barycentric (SM)!\" << std::endl;\n    }\n  }\n#endif // BARY_SURF_MESH\n\n  // ***************************************************************************\n  // ARAP WITH SURF_MESH\n  // ***************************************************************************\n\n#ifdef ARAP_SURF_MESH\n  {\n    std::cout << \" ----------- ARAP SURFACE MESH -----------\" << std::endl;\n\n    std::ifstream in(CGAL::data_file_path(\"meshes/nefertiti.off\"));\n    SMesh sm;\n    in >> sm;\n    if(!in || num_vertices(sm) == 0) {\n      std::cerr << \"Problem loading the input data\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    // halfedge on the longest border\n    SM_halfedge_descriptor hd = PMP::longest_border(sm).first;\n\n    CGAL::Unique_hash_map<SM_vertex_descriptor, Point_2,\n                          boost::hash<SM_vertex_descriptor> > uvhm;\n    boost::associative_property_map<\n      CGAL::Unique_hash_map<SM_vertex_descriptor,\n                            Point_2,\n                            boost::hash<SM_vertex_descriptor> > > uv_pm(uvhm);\n\n    // Indices map\n    typedef boost::unordered_map<SM_vertex_descriptor, int> Indices;\n    Indices indices;\n    PMP::connected_component(face(opposite(hd, sm), sm), sm,\n                             boost::make_function_output_iterator(\n                               SMP::internal::Index_map_filler<SMesh, Indices>(sm, indices)));\n    boost::associative_property_map<Indices> vipm(indices);\n\n    // Parameterized bool pmap\n    boost::unordered_set<SM_vertex_descriptor> vs;\n    SMP::internal::Bool_property_map< boost::unordered_set<SM_vertex_descriptor> > vpm(vs);\n\n    // Parameterizer\n    SMP::ARAP_parameterizer_3<SMesh> parameterizer;\n\n    SMP::Error_code status = parameterizer.parameterize(sm, hd, uv_pm, vipm, vpm);\n    SMP::Error_code status_bis = SMP::parameterize(sm, parameterizer, hd, uv_pm);\n\n    if(status != SMP::OK || status_bis != SMP::OK) {\n      std::cout << \"Encountered a problem: \" << status << std::endl;\n      return EXIT_FAILURE;\n    }\n    else {\n      std::cout << \"Parameterized with ARAP (SM)!\" << std::endl;\n    }\n  }\n#endif // ARAP_SURF_MESH\n\n#ifdef DCM_PM_SEAM_MESH\n  {\n    std::cout << \" ----------- DCM POLYHEDRON SEAM MESH -----------\" << std::endl;\n\n    std::ifstream in(CGAL::data_file_path(\"meshes/fandisk.off\"));\n    PMesh pm;\n    in >> pm;\n    if(!in || num_vertices(pm) == 0) {\n      std::cerr << \"Problem loading the input data\" << std::endl;\n      return EXIT_FAILURE;\n    }\n    const char* selection = \"data/fandisk.dcm.selection.txt\";\n\n    PM_seam_edge_hmap seam_edge_hm(false);\n    PM_seam_edge_pmap seam_edge_pm(seam_edge_hm);\n    PM_seam_vertex_hmap seam_vertex_hm(false);\n    PM_seam_vertex_pmap seam_vertex_pm(seam_vertex_hm);\n\n    PM_Seam_mesh mesh(pm, seam_edge_pm, seam_vertex_pm);\n    PM_halfedge_descriptor pmhd = mesh.add_seams(selection);\n    if(pmhd == PM_halfedge_descriptor() ) {\n      std::cerr << \"Warning: No seams in input\" << std::endl;\n    }\n\n    // The 2D points of the uv parametrisation will be written into this map\n    // Note that this is a halfedge property map, and that the uv\n    // is only stored for the canonical halfedges representing a vertex\n    PM_UV_hmap uv_hm;\n    PM_UV_pmap uv_pm(uv_hm);\n\n    // a halfedge on the (possibly virtual) border\n    PM_SE_halfedge_descriptor hd = PMP::longest_border(mesh).first;\n\n    // Indices\n    typedef boost::unordered_map<PM_SE_vertex_descriptor, int> Indices;\n    Indices indices;\n    PMP::connected_component(face(opposite(hd, mesh), mesh), mesh,\n                             boost::make_function_output_iterator(\n                               SMP::internal::Index_map_filler<PM_Seam_mesh, Indices>(mesh, indices)));\n    boost::associative_property_map<Indices> vipm(indices);\n\n    // Parameterized\n    boost::unordered_set<PM_SE_vertex_descriptor> vs;\n    SMP::internal::Bool_property_map<boost::unordered_set<PM_SE_vertex_descriptor> > vpm(vs);\n\n    SMP::Discrete_conformal_map_parameterizer_3<PM_Seam_mesh> parameterizer;\n\n    SMP::Error_code status = parameterizer.parameterize(mesh, hd, uv_pm, vipm, vpm);\n    SMP::Error_code status_bis = SMP::parameterize(mesh, parameterizer, hd, uv_pm);\n\n    if(status != SMP::OK || status_bis != SMP::OK) {\n      std::cout << \"Encountered a problem: \" << status << std::endl;\n      return EXIT_FAILURE;\n    }\n    else {\n      std::cout << \"Parameterized with DCM (SEAM POLY)!\" << std::endl;\n    }\n  }\n#endif // DCM_PM_SEAM_MESH\n\n  // ***************************************************************************\n  // DAC WITH SEAM_MESH (SM)\n  // ***************************************************************************\n\n#ifdef DAC_SM_SEAM_MESH\n  {\n    std::cout << \" ----------- DAC SURFACE MESH SEAM MESH -----------\" << std::endl;\n\n    std::ifstream in(CGAL::data_file_path(\"meshes/bear.off\"));\n    SMesh sm;\n    in >> sm;\n    if(!in || num_vertices(sm) == 0) {\n      std::cerr << \"Problem loading the input data\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    const char* selection = \"data/bear.dac.selection.txt\";\n\n    SM_seam_edge_pmap seam_edge_pm =\n        sm.add_property_map<SM_edge_descriptor,bool>(\"e:on_seam\", false).first;\n    SM_seam_vertex_pmap seam_vertex_pm =\n        sm.add_property_map<SM_vertex_descriptor,bool>(\"v:on_seam\", false).first;\n\n    SM_Seam_mesh mesh(sm, seam_edge_pm, seam_vertex_pm);\n    SM_halfedge_descriptor smhd = mesh.add_seams(selection);\n    if(smhd == SM_halfedge_descriptor() ) {\n      std::cerr << \"Warning: No seams in input\" << std::endl;\n    }\n\n    // The 2D points of the uv parametrisation will be written into this map\n    // Note that this is a halfedge property map, and that the uv\n    // is only stored for the canonical halfedges representing a vertex\n    SM_UV_pmap uv_pm = sm.add_property_map<SM_halfedge_descriptor,\n                                           Point_2>(\"h:uv\").first;\n\n    // a halfedge on the (possibly virtual) border\n    SM_SE_halfedge_descriptor hd = PMP::longest_border(mesh).first;\n\n    // Indices\n    typedef boost::unordered_map<SM_SE_vertex_descriptor, int> Indices;\n    Indices indices;\n    PMP::connected_component(face(opposite(hd, mesh), mesh), mesh,\n                             boost::make_function_output_iterator(\n                               SMP::internal::Index_map_filler<SM_Seam_mesh, Indices>(mesh, indices)));\n    boost::associative_property_map<Indices> vipm(indices);\n\n    // Parameterized\n    boost::unordered_set<SM_SE_vertex_descriptor> vs;\n    SMP::internal::Bool_property_map<boost::unordered_set<SM_SE_vertex_descriptor> > vpm(vs);\n\n    SMP::Discrete_authalic_parameterizer_3<SM_Seam_mesh> parameterizer;\n\n    SMP::Error_code status = parameterizer.parameterize(mesh, hd, uv_pm, vipm, vpm);\n    SMP::Error_code status_bis = SMP::parameterize(mesh, parameterizer, hd, uv_pm);\n\n    if(status != SMP::OK || status_bis != SMP::OK) {\n      std::cout << \"Encountered a problem: \" << status << std::endl;\n      return EXIT_FAILURE;\n    }\n    else {\n      std::cout << \"Parameterized with DAC (SEAM SM)!\" << std::endl;\n    }\n  }\n#endif // DAC_SM_SEAM_MESH\n\n#ifdef ORBIFOLD_SM_MESH\n  {\n    std::cout << \" ----------- ORBIFOLD SURFACE MESH -----------\" << std::endl;\n\n    SMesh sm; // underlying mesh of the seam mesh\n\n    std::ifstream in(CGAL::data_file_path(\"meshes/fandisk.off\"));\n    in >> sm;\n    if(!in || num_vertices(sm) == 0) {\n      std::cerr << \"Problem loading the input data\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    const char* cone_filename = \"data/fandisk.orbifold.selection.txt\";\n\n    // Read the cones and find the corresponding vertex_descriptor in the underlying mesh 'sm'\n    std::vector<SM_vertex_descriptor> cone_sm_vds;\n    SMP::read_cones<SMesh>(sm, cone_filename, std::back_inserter(cone_sm_vds));\n\n    // Two property maps to store the seam edges and vertices\n    SM_seam_edge_pmap seam_edge_pm = sm.add_property_map<SM_edge_descriptor, bool>(\"e:on_seam\", false).first;\n    SM_seam_vertex_pmap seam_vertex_pm = sm.add_property_map<SM_vertex_descriptor, bool>(\"v:on_seam\",false).first;\n\n    // The seam mesh\n    SM_Seam_mesh mesh(sm, seam_edge_pm, seam_vertex_pm);\n\n    // Use the path provided between cones to create a seam mesh\n    SM_halfedge_descriptor smhd = mesh.add_seams(cone_filename);\n    if(smhd == SM_halfedge_descriptor() ) {\n      std::list<SM_edge_descriptor> seam_edges;\n      SMP::compute_shortest_paths_between_cones(sm, cone_sm_vds.begin(), cone_sm_vds.end(), seam_edges);\n\n      // Add the seams to the seam mesh\n      for(SM_edge_descriptor e : seam_edges) {\n        mesh.add_seam(source(e, sm), target(e, sm));\n      }\n    }\n\n    // Index map of the seam mesh (assuming a single connected component so far)\n    typedef boost::unordered_map<SM_SE_vertex_descriptor, int> Indices;\n    Indices indices;\n    boost::associative_property_map<Indices> vimap(indices);\n    int counter = 0;\n    for(SM_SE_vertex_descriptor vd : vertices(mesh)) {\n      put(vimap, vd, counter++);\n    }\n\n    // Mark the cones in the seam mesh\n    boost::unordered_map<SM_SE_vertex_descriptor, SMP::Cone_type> cmap;\n    SMP::locate_cones(mesh, cone_sm_vds.begin(), cone_sm_vds.end(), cmap);\n\n    // The 2D points of the uv parametrisation will be written into this map\n    // Note that this is a halfedge property map, and that uv values\n    // are only stored for the canonical halfedges representing a vertex\n    SM_UV_pmap uvmap = sm.add_property_map<SM_halfedge_descriptor, Point_2>(\"h:uv\").first;\n\n    // Parameterizer\n    typedef SMP::Orbifold_Tutte_parameterizer_3<SM_Seam_mesh>         Parameterizer;\n    Parameterizer parameterizer(SMP::Parallelogram, SMP::Cotangent);\n\n    // a halfedge on the (possibly virtual) border\n    // only used in output (will also be used to handle multiple connected components in the future)\n    SM_SE_halfedge_descriptor hd = PMP::longest_border(mesh).first;\n\n    SMP::Error_code status = parameterizer.parameterize(mesh, hd, cmap, uvmap, vimap);\n\n    if(status != SMP::OK) {\n      std::cout << \"Encountered a problem: \" << status << std::endl;\n      return EXIT_FAILURE;\n    }\n    else {\n      std::cout << \"Parameterized with Orbifold (SEAM SM)!\" << std::endl;\n    }\n  }\n#endif // ORBIFOLD_SM_MESH\n\n  // ***************************************************************************\n  // ITERATIVE AUTHALIC WITH SURFACE_MESH\n  // ***************************************************************************\n\n#ifdef ITERATIVE_SURF_MESH\n  {\n    std::cout << \" ----------- ITERATIVE AUTHALIC SURFACE MESH ----------- \" << std::endl;\n\n    std::ifstream in(\"data/oni.off\");\n    SMesh sm;\n    in >> sm;\n    if(!in || num_vertices(sm) == 0) {\n      std::cerr << \"Problem loading the input data\" << std::endl;\n      return EXIT_FAILURE;\n    }\n\n    SM_halfedge_descriptor hd = PMP::longest_border(sm).first;\n    assert(hd != SM_halfedge_descriptor());\n\n    // UV map\n    typedef SMesh::Property_map<SM_vertex_descriptor, Point_2>  UV_pmap;\n    UV_pmap uvpm = sm.add_property_map<SM_vertex_descriptor, Point_2>(\"h:uv\").first;\n\n    // Indices map\n    typedef boost::unordered_map<SM_vertex_descriptor, int> Indices;\n    Indices indices;\n    PMP::connected_component(face(opposite(hd, sm), sm), sm,\n                             boost::make_function_output_iterator(\n                               SMP::internal::Index_map_filler<SMesh, Indices>(sm, indices)));\n    boost::associative_property_map<Indices> vipm(indices);\n\n    // Vertex parameterized map\n    boost::unordered_set<SM_vertex_descriptor> vs;\n    SMP::internal::Bool_property_map<boost::unordered_set<SM_vertex_descriptor> > vpm(vs);\n\n    // Parameterizer\n    SMP::Iterative_authalic_parameterizer_3<SMesh> parameterizer;\n\n    double error = 0;\n    unsigned int iterations = 15;\n    SMP::Error_code status = parameterizer.parameterize(sm, hd, uvpm, vipm, vpm, iterations, error);\n    SMP::Error_code status_bis = parameterizer.parameterize(sm, uvpm, 10);\n\n    if(status != SMP::OK || status_bis != SMP::OK) {\n      std::cout << \"Encountered a problem: \" << status << std::endl;\n      return EXIT_FAILURE;\n    }\n    else {\n      std::cout << \"Parameterized with Barycentric (SM)!\" << std::endl;\n    }\n  }\n#endif // DAC_SM_SEAM_MESH\n\n  std::cout << \"Done!\" << std::endl;\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "a76f583f4f4a6b4a78caaef119fed704b60cecd5", "size": 20519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh_parameterization/test/Surface_mesh_parameterization/extensive_parameterization_test.cpp", "max_stars_repo_name": "GYuvanShankar/cgal", "max_stars_repo_head_hexsha": "ad08f020b671295e95807ccc7cfc787236beb03b", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-19T03:07:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T03:07:22.000Z", "max_issues_repo_path": "Surface_mesh_parameterization/test/Surface_mesh_parameterization/extensive_parameterization_test.cpp", "max_issues_repo_name": "arenas7307979/cgal", "max_issues_repo_head_hexsha": "ad08f020b671295e95807ccc7cfc787236beb03b", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Surface_mesh_parameterization/test/Surface_mesh_parameterization/extensive_parameterization_test.cpp", "max_forks_repo_name": "arenas7307979/cgal", "max_forks_repo_head_hexsha": "ad08f020b671295e95807ccc7cfc787236beb03b", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.425093633, "max_line_length": 114, "alphanum_fraction": 0.6362395828, "num_tokens": 5082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4149307668867298}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2014-2017.\n// Modifications copyright (c) 2014-2017 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_VINCENTY_HPP\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_VINCENTY_HPP\n\n\n#include <boost/geometry/strategies/geographic/distance.hpp>\n#include <boost/geometry/strategies/geographic/parameters.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n/*!\n\\brief Distance calculation formulae on latlong coordinates, after Vincenty, 1975\n\\ingroup distance\n\\tparam Spheroid The reference spheroid model\n\\tparam CalculationType \\tparam_calculation\n\\author See\n    - http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf\n    - http://www.icsm.gov.au/gda/gdav2.3.pdf\n\\author Adapted from various implementations to get it close to the original document\n    - http://www.movable-type.co.uk/scripts/LatLongVincenty.html\n    - http://exogen.case.edu/projects/geopy/source/geopy.distance.html\n    - http://futureboy.homeip.net/fsp/colorize.fsp?fileName=navigation.frink\n\n*/\ntemplate\n<\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void\n>\nclass vincenty\n    : public strategy::distance::geographic\n        <\n            strategy::vincenty, Spheroid, CalculationType\n        >\n{\n    typedef strategy::distance::geographic\n        <\n            strategy::vincenty, Spheroid, CalculationType\n        > base_type;\n\npublic:\n    inline vincenty()\n        : base_type()\n    {}\n\n    explicit inline vincenty(Spheroid const& spheroid)\n        : base_type(spheroid)\n    {}\n};\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename Spheroid, typename CalculationType>\nstruct tag<vincenty<Spheroid, CalculationType> >\n{\n    typedef strategy_tag_distance_point_point type;\n};\n\n\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\nstruct return_type<vincenty<Spheroid, CalculationType>, P1, P2>\n    : vincenty<Spheroid, CalculationType>::template calculation_type<P1, P2>\n{};\n\n\ntemplate <typename Spheroid, typename CalculationType>\nstruct comparable_type<vincenty<Spheroid, CalculationType> >\n{\n    typedef vincenty<Spheroid, CalculationType> type;\n};\n\n\ntemplate <typename Spheroid, typename CalculationType>\nstruct get_comparable<vincenty<Spheroid, CalculationType> >\n{\n    static inline vincenty<Spheroid, CalculationType> apply(vincenty<Spheroid, CalculationType> const& input)\n    {\n        return input;\n    }\n};\n\ntemplate <typename Spheroid, typename CalculationType, typename P1, typename P2>\nstruct result_from_distance<vincenty<Spheroid, CalculationType>, P1, P2 >\n{\n    template <typename T>\n    static inline typename return_type<vincenty<Spheroid, CalculationType>, P1, P2>::type\n        apply(vincenty<Spheroid, CalculationType> const& , T const& value)\n    {\n        return value;\n    }\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n\n// We might add a vincenty-like strategy also for point-segment distance, but to calculate the projected point is not trivial\n\n\n\n}} // namespace strategy::distance\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_VINCENTY_HPP\n", "meta": {"hexsha": "41146db9ff4661953fcb9d6bd2eb2e0ac409eca9", "size": 3547, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/geographic/distance_vincenty.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/geographic/distance_vincenty.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/strategies/geographic/distance_vincenty.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 27.7109375, "max_line_length": 125, "alphanum_fraction": 0.752184945, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.41493076053481226}}
{"text": "//\n//  dt_util.cpp\n//  Classifer_RF\n//\n//  Created by jimmy on 2017-02-16.\n//  Copyright (c) 2017 Nowhere Planet. All rights reserved.\n//\n\n#include \"dt_util.hpp\"\n#include <Eigen/QR>\n#include <iostream>\n#include <map>\n\nusing std::cout;\nusing std::endl;\nusing std::map;\n\nnamespace dt {\n    template< class T>\n    vector<T> randomDimension(const T dim, const T num)\n    {\n        assert(dim > 0);\n        assert(num > 0);\n        assert(num <= dim);\n        \n        vector<T> dims;\n        for (T i = 0; i<dim; i++) {\n            dims.push_back(i);\n        }\n        std::random_shuffle(dims.begin(), dims.end());\n        vector<T> random_dim(dims.begin(), dims.begin() + num);\n        assert(random_dim.size() > 0 && random_dim.size() <= dims.size());\n        \n        return random_dim;\n    }\n    \n    template< class vectorType>\n    void meanStd(const vector<vectorType> & labels, vectorType & mean, vectorType & sigma)\n    {\n        assert(labels.size() > 0);\n        \n        mean = vectorType::Zero(labels[0].size());\n        \n        for (int i = 0; i<labels.size(); i++) {\n            mean += labels[i];\n        }\n        mean /= labels.size();\n        \n        sigma = vectorType::Zero(labels[0].size());\n        if (labels.size() == 1) {\n            return;\n        }\n        for (int i = 0; i<labels.size(); i++) {\n            vectorType dif = labels[i] - mean;\n            for (int j = 0; j<sigma.size(); j++) {\n                sigma[j] += dif[j] * dif[j];\n            }\n        }\n        for (int j = 0; j<sigma.size(); j++) {\n            sigma[j] = sqrt(fabs(sigma[j])/labels.size());\n        }\n    }\n    \n    template<class vectorType, class intType>\n    void meanStd(const vector<vectorType> & data, const vector<intType> & indices,\n                 vectorType & mean, vectorType & sigma)\n    {\n        assert(data.size() > 0);\n        assert(indices.size() > 0);\n        \n        assert(indices.size() > 0);\n        \n        mean = vectorType::Zero(data[0].size());\n        \n        for (int i = 0; i<indices.size(); i++) {\n            int index = indices[i];\n            assert(index >= 0 && index < data.size());\n            mean += data[index];\n        }\n        mean /= indices.size();\n        \n        sigma = vectorType::Zero(data[0].size());\n        if (indices.size() == 1) {\n            return;\n        }\n        for (int i = 0; i<indices.size(); i++) {\n            vectorType dif = data[indices[i]] - mean;\n            for (int j = 0; j<sigma.size(); j++) {\n                sigma[j] += dif[j] * dif[j];\n            }\n        }\n        for (int j = 0; j<sigma.size(); j++) {\n            sigma[j] = sqrt(fabs(sigma[j])/indices.size());\n        }\n    }\n    \n    template <class intType>\n    vector<intType> balanceSamples(const vector<intType> & example_indices, const vector<intType> & labels, const int category_num)\n    {\n        assert(example_indices.size() <= labels.size());\n        \n        // step 1: count example numbers in each category\n        vector<intType> count(category_num, 0);\n        for (int i = 0; i<example_indices.size(); i++) {\n            intType idx = example_indices[i];\n            count[labels[idx]]++;\n        }\n        intType min_count = *std::min_element(count.begin(), count.end());\n        assert(min_count >= 0);\n        \n        // step 2: select the first min_count example in each category\n        count = vector<int>(category_num, 0);\n        vector<intType> balanced_indices;\n        for (int i = 0; i<example_indices.size(); i++) {\n            intType idx = example_indices[i];\n            intType cur_label = labels[idx];\n            \n            // skip this category\n            if (count[cur_label] >= min_count) {\n                continue;\n            }\n            else {\n                balanced_indices.push_back(idx);\n                count[cur_label]++;\n            }\n        }\n        return balanced_indices;\n    }\n    \n    template<class VectorType, class IntType>\n    double sumOfVariance(const vector<VectorType> & labels, const vector<IntType> & indices)\n    {\n        if (indices.size() <= 0) {\n            return 0.0;\n        }\n        assert(indices.size() > 0);\n        \n        VectorType mean = VectorType::Zero(labels[0].size());\n        \n        for (int i = 0; i<indices.size(); i++) {\n            IntType index = indices[i];\n            assert(index >= 0 && index < labels.size());\n            mean += labels[index];\n        }\n        mean /= indices.size();\n        \n        double var = 0.0;\n        for (int i = 0; i<indices.size(); i++) {\n            IntType index = indices[i];\n            assert(index >= 0 && index < labels.size());\n            VectorType dif = labels[index] - mean;\n            for (int j = 0; j<dif.size(); j++) {\n                var += dif[j] * dif[j];\n            }\n        }\n        return var;\n    }\n    \n    template<class intType>\n    intType mostCommon(const vector<intType> & data)\n    {\n        assert(data.size() > 0);\n        int max_count = 0;\n        int most_common = 0;\n        std::map<intType, int> m;\n        for (auto vi = data.begin(); vi != data.end(); vi++) {\n            m[*vi]++;\n            if (m[*vi] > max_count) {\n                max_count = m[*vi];\n                most_common = *vi;\n            }\n        }\n        return most_common;\n    }\n    \n    template <class T>\n    void meanMedianError(const vector<T> & errors,\n                                 T & mean,\n                                 T & median)\n    {\n        assert(errors.size() > 0);\n        const int dim = (int)errors[0].size();\n        mean = T::Zero(dim);\n        median = T::Zero(dim);\n        \n        vector<vector<double> > each_dim_data(dim);\n        for (int i = 0; i<errors.size(); i++) {\n            T err = errors[i].cwiseAbs();\n            mean += err;\n            for (int j = 0; j<err.size(); j++) {\n                each_dim_data[j].push_back(err[j]);\n            }\n        }\n        mean /= errors.size();\n        \n        for (int i = 0; i<each_dim_data.size(); i++) {\n            std::sort(each_dim_data[i].begin(), each_dim_data[i].end());\n            median[i] = each_dim_data[i][each_dim_data[i].size()/2];\n        }\n    }\n    \n    template vector<int> randomDimension(int dim, int num);\n    \n    template void meanStd(const vector<Eigen::VectorXd> & labels, Eigen::VectorXd & mean, Eigen::VectorXd & sigma);\n    template void meanStd(const vector<Eigen::Vector3d> & labels, Eigen::Vector3d & mean, Eigen::Vector3d & sigma);\n    \n    template void meanStd(const vector<Eigen::VectorXf> & labels, const vector<int> & indices,\n                          Eigen::VectorXf & mean, Eigen::VectorXf & sigma);\n    \n    template\n    vector<int> balanceSamples(const vector<int> & example_indices, const vector<int> & labels, const int category_num);\n    \n    template\n    double sumOfVariance(const vector<Eigen::VectorXf> & labels, const vector<int> & indices);\n    \n    template\n    int mostCommon(const vector<int> & data);\n    \n    template\n    void meanMedianError(const vector<Eigen::VectorXf> & errors, Eigen::VectorXf & mean, Eigen::VectorXf & median);\n    \n    template\n    void meanMedianError(const vector<Eigen::VectorXd> & errors, Eigen::VectorXd & mean, Eigen::VectorXd & median);\n}\n\n\n\nvector<unsigned int> DTUtil::randomDimensions(const int dimension, const int candidate_dimension)\n{\n    assert(dimension > 0);\n    assert(candidate_dimension > 0);\n    assert(candidate_dimension <= dimension);\n    \n    vector<unsigned int> dims;\n    for (unsigned int i = 0; i<dimension; i++) {\n        dims.push_back(i);\n    }\n    std::random_shuffle(dims.begin(), dims.end());\n    vector<unsigned int> random_dim(dims.begin(), dims.begin() + candidate_dimension);\n    assert(random_dim.size() > 0 && random_dim.size() <= dims.size());\n    \n    return random_dim;\n}\n\n\n\ntemplate <class T>\ndouble DTUtil::spatialVariance(const vector<T> & labels, const vector<unsigned int> & indices)\n{\n    if (indices.size() <= 0) {\n        return 0.0;\n    }\n    assert(indices.size() > 0);\n    \n    T mean = T::Zero(labels[0].size());\n    \n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < labels.size());\n        mean += labels[index];\n    }\n    mean /= indices.size();\n    \n    double var = 0.0;\n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < labels.size());\n        T dif = labels[index] - mean;\n        for (int j = 0; j<dif.size(); j++) {\n            var += dif[j] * dif[j];\n        }\n    }\n    return var;\n}\n\ntemplate<class T>\ndouble DTUtil::fullVariance(const vector<T>& labels, const vector<unsigned int> & indices)\n{\n    assert(indices.size() > 1);\n    typedef typename T::Scalar Scalar;\n    typedef typename Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> MatrixType;\n    \n    double loss = 0.0;\n    \n    const int length = (int)labels[0].size();\n    MatrixType sampled_data(indices.size(), length);\n    for (unsigned i = 0; i<indices.size(); i++) {\n        unsigned int index = indices[i];\n        assert(index >= 0 && index < labels.size());\n        sampled_data.row(i) = labels[index];\n    }    \n    \n    MatrixType centered = sampled_data.rowwise() - sampled_data.colwise().mean();\n    MatrixType cov = (centered.adjoint() * centered) / sampled_data.rows();\n    \n    Eigen::ColPivHouseholderQR<MatrixType> qr(cov);\n    if (qr.rank() == length) {\n        loss = qr.logAbsDeterminant();\n    }\n    else {\n        loss = qr.logAbsDeterminant();\n        // avoid underflow\n        if (std::isnan(loss) || std::isinf(loss)) {\n            loss = log(0.0000001);\n        }\n        //printf(\"Warning: full variance underflow, use a small number log(0.0000001) instead. Sample number %ld\\n\", indices.size());\n        //cout<<\"covariance matrix \\n\"<<cov<<endl;\n        //printf(\"logAbsDeterminant vs log(0.0000001): %lf, %lf\\n\", qr.logAbsDeterminant(), log(0.0000001));\n    }\n    \n    return loss;\n}\n\n\ntemplate <class MatrixType>\ndouble DTUtil::sumOfVariance(const vector<MatrixType> & labels, const int row_index, const vector<unsigned int> & indices)\n{\n    typedef typename MatrixType::Scalar Scalar;\n    typedef typename Eigen::Matrix<Scalar, Eigen::Dynamic, 1> ScalarVector;\n    \n    if (indices.size() <= 0) {\n        return 0.0;\n    }\n    assert(indices.size() > 0);\n    \n    ScalarVector mean = ScalarVector::Zero(labels[0].row(0).size());\n    \n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < labels.size());\n        mean += labels[index].row(row_index);\n    }\n    mean /= indices.size();\n    \n    double var = 0.0;\n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < labels.size());\n        ScalarVector dif = labels[index].row(row_index) - mean;\n        for (int j = 0; j<dif.size(); j++) {\n            var += dif[j] * dif[j];\n        }\n    }\n    return var;\n}\n\ntemplate<class Type1, class Type2>\ndouble DTUtil::spatialVariance(const vector<Type1> & labels, const vector<unsigned int> & indices, const vector<Type2> & wt)\n{\n    if (indices.size() <= 0) {\n        return 0.0;\n    }\n    assert(indices.size() > 0);\n    assert(wt.size() == labels.front().size());\n    \n    Type1 mean = Type1::Zero(labels[0].size());\n    \n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < labels.size());\n        mean += labels[index];\n    }\n    mean /= indices.size();\n    \n    double var = 0.0;\n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < labels.size());\n        Type1 dif = labels[index] - mean;\n        for (int j = 0; j<dif.size(); j++) {\n            var += dif[j] * dif[j] * fabs(double(wt[j]));\n        }\n    }\n    return var;\n}\n\ntemplate <class T>\nvoid DTUtil::meanStddev(const vector<T> & labels, const vector<unsigned int> & indices, T & mean, T & sigma)\n{\n    assert(indices.size() > 0);\n    \n    mean = T::Zero(labels[0].size());\n    \n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < labels.size());\n        mean += labels[index];\n    }\n    mean /= indices.size();\n    \n    sigma = T::Zero(labels[0].size());\n    if (indices.size() == 1) {\n        return;\n    }\n    for (int i = 0; i<indices.size(); i++) {\n        T dif = labels[indices[i]] - mean;\n        for (int j = 0; j<sigma.size(); j++) {\n            sigma[j] += dif[j] * dif[j];\n        }\n    }\n    for (int j = 0; j<sigma.size(); j++) {\n        sigma[j] = sqrt(fabs(sigma[j])/indices.size());\n    }\n}\n\ntemplate <class vectorT, class indexT>\nvectorT DTUtil::mean(const vector<vectorT> & data, const vector<indexT> & indices)\n{\n    assert(indices.size() > 0);\n    \n    vectorT m = vectorT::Zero(data[0].size());\n    \n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < data.size());\n        m += data[index];\n    }\n    m /= indices.size();\n    \n    return m;\n}\n\ntemplate <class T>\nT DTUtil::mean(const vector<T> & data)\n{\n    assert(data.size() > 0);\n    \n    T m = T::Zero(data[0].size());\n    \n    for (int i = 0; i<data.size(); i++) {\n        m += data[i];\n    }\n    m /= data.size();\n    return m;\n}\n\ntemplate <class matrixType, class vectorType>\nvoid DTUtil::rowMeanStddev(const vector<matrixType> & labels, const vector<unsigned int> & indices, const int row_index, vectorType & mean, vectorType & sigma)\n{\n    assert(indices.size() > 0);\n    \n    mean = vectorType::Zero(labels[0].row(0).size());\n    \n    for (int i = 0; i<indices.size(); i++) {\n        int index = indices[i];\n        assert(index >= 0 && index < labels.size());\n        mean += labels[index].row(row_index);\n    }\n    mean /= indices.size();\n    \n    sigma = vectorType::Zero(labels[0].row(0).size());\n    if (indices.size() == 1) {\n        return;\n    }\n    for (int i = 0; i<indices.size(); i++) {\n        vectorType dif = labels[indices[i]].row(row_index) - mean;\n        for (int j = 0; j<sigma.size(); j++) {\n            sigma[j] += dif[j] * dif[j];\n        }\n    }\n    for (int j = 0; j<sigma.size(); j++) {\n        sigma[j] = sqrt(fabs(sigma[j])/indices.size());\n    }\n}\n\n\n\ntemplate<class vectorT>\nvoid DTUtil::quartileError(const vector<vectorT> & errors, vectorT& q1, vectorT& q2, vectorT& q3)\n{\n    assert(errors.size() > 0);\n    const int dim = (int)errors[0].size();\n    \n    q1 = vectorT::Zero(dim);\n    q2 = vectorT::Zero(dim);\n    q3 = vectorT::Zero(dim);\n    \n    vector<vector<double> > each_dim_data(dim);\n    for (int i = 0; i<errors.size(); i++) {\n        vectorT err = errors[i].cwiseAbs();\n        for (int j = 0; j<err.size(); j++) {\n            each_dim_data[j].push_back(err[j]);\n        }\n    }\n    \n    for (int i = 0; i<each_dim_data.size(); i++) {\n        std::sort(each_dim_data[i].begin(), each_dim_data[i].end());\n        q1[i] = each_dim_data[i][each_dim_data[i].size()/4];\n        q2[i] = each_dim_data[i][each_dim_data[i].size()/2];\n        q3[i] = each_dim_data[i][each_dim_data[i].size()/4*3];\n    }\n}\n\ntemplate <class MatrixType>\nvoid DTUtil::matrixMeanError(const vector<MatrixType> & errors, MatrixType & mean)\n{\n    assert(errors.size() > 0);\n    \n    const int cols  = (int)errors[0].cols();\n    const int rows = (int)errors[0].rows();\n    mean  = MatrixType::Zero(rows, cols);\n    \n    for (int i = 0; i<errors.size(); i++) {\n        mean += errors[i];\n    }\n    mean /= errors.size();\n}\n\n\ndouble DTUtil::crossEntropy(const Eigen::VectorXd & prob)\n{\n    double entropy = 0.0;\n    for (int i = 0; i<prob.size(); i++) {\n        double p = prob[i];\n        if (p == 0.0) {\n            continue;\n        }\n        assert(p > 0 && p <= 1);\n        entropy += - p * std::log(p);\n    }\n    return entropy;\n}\n\ndouble DTUtil::crossEntropy(const Eigen::VectorXf& prob)\n{\n    double entropy = 0.0;\n    for (int i = 0; i<prob.size(); i++) {\n        double p = prob[i];\n        if (p == 0.0) {\n            continue;\n        }\n        assert(p > 0 && p <= 1);\n        entropy += - p * std::log(p);\n    }\n    return entropy;    \n}\n\n\ndouble DTUtil::balanceLoss(const int leftNodeSize, const int rightNodeSize)\n{\n    double dif = leftNodeSize - rightNodeSize;\n    double num = leftNodeSize + rightNodeSize;\n    double loss = fabs(dif)/num;\n    assert(loss >= 0);\n    return loss;\n}\n\nbool\nDTUtil::isSameLabel(const vector<unsigned int> & labels, const vector<unsigned int> & indices)\n{\n    assert(indices.size() >= 1);\n    unsigned label = labels[indices[0]];\n    for (int i = 1; i<indices.size(); i++) {\n        if (label != labels[indices[i]]) {\n            return false;\n        }\n    }\n    return true;\n}\n\nbool DTUtil::isSameLabel(const vector<int>& labels, const vector<int>& indices)\n{\n    assert(indices.size() >= 1);\n    int label = labels[indices[0]];\n    for (int i = 1; i<indices.size(); i++) {\n        if (label != labels[indices[i]]) {\n            return false;\n        }\n    }\n    return true;    \n}\n\nint DTUtil::minLabelNumber(const vector<unsigned int> & labels, const vector<unsigned int> & indices,\n                           const int num_category)\n{\n    vector<int> num(num_category, 0);\n    for (int i = 0; i<indices.size(); i++) {\n        int label = labels[indices[i]];\n        num[label]++;\n    }\n    return *std::min_element(num.begin(), num.end());\n}\n\nint DTUtil::minLabelNumber(const vector<VectorXi> & labels,\n                           const vector<unsigned int> & indices,\n                           const int time_step,\n                           const int num_category)\n{\n    vector<int> num(num_category, 0);\n    for (int i = 0; i<indices.size(); i++) {\n        int label = labels[indices[i]][time_step];\n        num[label]++;\n    }\n    \n    return *std::min_element(num.begin(), num.end());\n}\n\ntemplate <class integerType>\nEigen::MatrixXd DTUtil::confusionMatrix(const vector<integerType> & preds,\n                                        const vector<integerType> & labels,\n                                        const int category_num,\n                                        bool normalize)\n{\n    assert(preds.size() == labels.size());\n    assert(category_num > 0);\n    \n    Eigen::MatrixXd confusion = Eigen::MatrixXd::Zero(category_num, category_num);\n    for (int i = 0; i<preds.size(); i++) {\n        confusion(labels[i], preds[i]) += 1.0;\n    }\n    if (normalize) {\n        confusion = 1.0 / preds.size() * confusion;\n    }\n    return confusion;\n}\n\nEigen::VectorXd DTUtil::accuracyFromConfusionMatrix(const Eigen::MatrixXd & conf)\n{\n    assert(conf.rows() == conf.cols());\n    \n    Eigen::VectorXd acc = Eigen::VectorXd(conf.rows() + 1, 1);\n    Eigen::VectorXd row_sum = conf.rowwise().sum();\n    double all_sum = conf.sum();\n    double trace = conf.trace();\n    for (int r = 0; r<conf.rows(); r++) {\n        acc[r] = conf(r ,r)/row_sum[r];\n    }\n    acc[conf.rows()] = trace/all_sum;\n    return acc;\n}\n\nEigen::VectorXd DTUtil::precisionFromConfusionMatrix(const Eigen::MatrixXd & conf)\n{\n    assert(conf.rows() == conf.cols());\n    \n    Eigen::VectorXd precision = Eigen::VectorXd(conf.rows() + 1, 1);\n    Eigen::VectorXd row_sum = conf.rowwise().sum();\n    double all_sum = conf.sum();\n    double trace = conf.trace();\n    for (int r = 0; r<conf.rows(); r++) {\n        precision[r] = conf(r ,r)/row_sum[r];\n    }\n    precision[conf.rows()] = trace/all_sum;\n    return precision;\n}\n\n\n\n\ntemplate double\nDTUtil::spatialVariance(const vector<Eigen::VectorXf> & labels, const vector<unsigned int> & indices);\n\ntemplate double\nDTUtil::fullVariance(const vector<Eigen::VectorXf>& labels, const vector<unsigned int> & indices);\n\ntemplate double\nDTUtil::sumOfVariance(const vector<Eigen::MatrixXf> & labels, const int row_index, const vector<unsigned int> & indices);\n\ntemplate double\nDTUtil::spatialVariance(const vector<Eigen::VectorXf> & labels, const vector<unsigned int> & indices, const vector<int> & wt);\n\ntemplate void\nDTUtil::meanStddev(const vector<Eigen::VectorXf> & labels, const vector<unsigned int> & indices, Eigen::VectorXf & mean, Eigen::VectorXf & sigma);\n\ntemplate Eigen::VectorXf\nDTUtil::mean(const vector<Eigen::VectorXf> & data, const vector<unsigned int> & indices);\n\ntemplate Eigen::VectorXf\nDTUtil::mean(const vector<Eigen::VectorXf> & data, const vector<int> & indices);\n\ntemplate Eigen::VectorXf\nDTUtil::mean(const vector<Eigen::VectorXf> & data);\n\ntemplate void\nDTUtil::rowMeanStddev(const vector<Eigen::MatrixXf> & labels, const vector<unsigned int> & indices,\n                      const int row_index, Eigen::VectorXf & mean, Eigen::VectorXf & sigma);\n\n\n\ntemplate\nvoid DTUtil::quartileError(const vector<Eigen::VectorXf> & errors, Eigen::VectorXf& q1, Eigen::VectorXf& q2, Eigen::VectorXf& q3);\n\ntemplate void\nDTUtil::matrixMeanError(const vector<Eigen::MatrixXf> & errors, Eigen::MatrixXf & mean);\n\n\ntemplate Eigen::MatrixXd\nDTUtil::confusionMatrix(const vector<unsigned int> & preds,\n                        const vector<unsigned int> & labels,\n                        const int category_num,\n                        bool normalize);\n\ntemplate Eigen::MatrixXd\nDTUtil::confusionMatrix(const vector<int> & preds,\n                        const vector<int> & labels,\n                        const int category_num,\n                        bool normalize);\n\n\n\n\n\n", "meta": {"hexsha": "d92680b1b8af42245e54bff8338d3206068f4b6e", "size": 21324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pan_tilt_forest/dt_util/dt_util.cpp", "max_stars_repo_name": "lood339/two_point_calib", "max_stars_repo_head_hexsha": "b4b861429c92368e8e4accecc986272070fb19bc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2018-04-22T10:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T07:35:07.000Z", "max_issues_repo_path": "src/pan_tilt_forest/dt_util/dt_util.cpp", "max_issues_repo_name": "lood339/two_point_calib", "max_issues_repo_head_hexsha": "b4b861429c92368e8e4accecc986272070fb19bc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-01-18T06:33:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-02T06:11:14.000Z", "max_forks_repo_path": "src/pan_tilt_forest/dt_util/dt_util.cpp", "max_forks_repo_name": "lood339/two_point_calib", "max_forks_repo_head_hexsha": "b4b861429c92368e8e4accecc986272070fb19bc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-03-07T07:25:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T06:16:42.000Z", "avg_line_length": 30.332859175, "max_line_length": 159, "alphanum_fraction": 0.551538173, "num_tokens": 5525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.41484790633478924}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <iomanip>\n\n#include \"structures.h\"\n#include \"transformations.h\"\n#include \"relative_pose_tait_bryan_wc_jacobian.h\"\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = 0.0, rotate_y = 0.0;\nfloat translate_z = -10.0;\nfloat translate_x, translate_y = 0.0;\n\nbool initGL(int *argc, char **argv);\nvoid display();\nvoid keyboard(unsigned char key, int x, int y);\nvoid mouse(int button, int state, int x, int y);\nvoid motion(int x, int y);\nvoid reshape(int w, int h);\nvoid printHelp();\n\nbool is_loop_closure_added = false;\n\nstd::vector<Eigen::Affine3d> m_poses;\nstd::vector<Eigen::Affine3d> m_poses_desired;\nstd::vector<std::pair<int, int>> odo_edges;\n\n\nvoid calculate_cov(std::vector<Eigen::Affine3d> m_poses,\n\t\t\t\t   std::vector<Eigen::Affine3d> m_poses_desired,\n\t\t\t\t   std::vector<std::pair<int, int>> odo_edges,\n\t\t\t\t   Eigen::MatrixXd & cov_b);\n\nvoid draw_ellipse(const Eigen::Matrix3d& covar, Eigen::Vector3d& mean, Eigen::Vector3f color, float nstd  = 3)\n{\n    Eigen::LLT<Eigen::Matrix<double,3,3> > cholSolver(covar);\n    Eigen::Matrix3d transform = cholSolver.matrixL();\n\n    const double pi = 3.141592;\n    const double di = 0.02;\n    const double dj = 0.04;\n    const double du = di*2*pi;\n    const double dv = dj*pi;\n    glColor3f(color.x(), color.y(),color.z());\n\n    for (double i = 0; i < 1.0; i+=di)  //horizonal\n    {\n        for (double j = 0; j < 1.0; j+=dj)  //vertical\n        {\n            double u = i*2*pi;      //0     to  2pi\n            double v = (j-0.5)*pi;  //-pi/2 to pi/2\n\n            const Eigen::Vector3d pp0( cos(v)* cos(u),cos(v) * sin(u),sin(v));\n            const Eigen::Vector3d pp1(cos(v) * cos(u + du) ,cos(v) * sin(u + du) ,sin(v));\n            const Eigen::Vector3d pp2(cos(v + dv)* cos(u + du) ,cos(v + dv)* sin(u + du) ,sin(v + dv));\n            const Eigen::Vector3d pp3( cos(v + dv)* cos(u),cos(v + dv)* sin(u),sin(v + dv));\n            Eigen::Vector3d tp0 = transform * (nstd*pp0) + mean;\n            Eigen::Vector3d tp1 = transform * (nstd*pp1) + mean;\n            Eigen::Vector3d tp2 = transform * (nstd*pp2) + mean;\n            Eigen::Vector3d tp3 = transform * (nstd*pp3) + mean;\n\n            glBegin(GL_LINE_LOOP);\n            glVertex3dv(tp0.data());\n            glVertex3dv(tp1.data());\n            glVertex3dv(tp2.data());\n            glVertex3dv(tp3.data());\n            glEnd();\n        }\n    }\n}\n\nvoid draw_ellipse2D(const Eigen::Matrix3d& covar, Eigen::Vector3d& mean, Eigen::Vector3f color, float nstd  = 3)\n{\n    Eigen::LLT<Eigen::Matrix<double,3,3> > cholSolver(covar);\n    Eigen::Matrix3d transform = cholSolver.matrixL();\n\n    const double pi = 3.141592;\n    const double di = 0.02;\n    const double dj = 0.04;\n    const double du = di*2*pi;\n    const double dv = dj*pi;\n    glColor3f(color.x(), color.y(),color.z());\n\n    for (double i = 0; i < 1.0; i+=di) { //horizonal\n\t\tdouble u = i*2*pi;      //0     to  2pi\n\t\tconst Eigen::Vector3d pp0( cos(u), sin (u),0);\n\t\tconst Eigen::Vector3d pp1( cos(u+du), sin(u+du),0);\n\t\tEigen::Vector3d tp0 = transform * (nstd*pp0) + mean;\n\t\tEigen::Vector3d tp1 = transform * (nstd*pp1) + mean;\n\t\tglBegin(GL_LINE_LOOP);\n\t\tglVertex3dv(tp0.data());\n\t\tglVertex3dv(tp1.data());\n\t\tglEnd();\n\t}\n}\n\n\nint main(int argc, char *argv[]){\n\tTaitBryanPose p0;\n\tp0.px = 0;\n\tp0.py = 0;\n\tp0.pz = 0;\n\tp0.om = 0;\n\tp0.fi = 0;\n\tp0.ka = 0;\n\tEigen::Affine3d m = affine_matrix_from_pose_tait_bryan(p0);\n\tm_poses.push_back(m);\n\n\tTaitBryanPose p_rel_forward_x;\n\tp_rel_forward_x.px = 1.0;\n\tp_rel_forward_x.py = 0.0;\n\tp_rel_forward_x.pz = 0.0;\n\tp_rel_forward_x.om = 0.0;\n\tp_rel_forward_x.fi = 0.0;\n\tp_rel_forward_x.ka = 0.0;\n\n\tTaitBryanPose p_rel_rotate;\n\tp_rel_rotate.px = 0.0;\n\tp_rel_rotate.py = 0.0;\n\tp_rel_rotate.pz = 0.0;\n\tp_rel_rotate.om = 0.0;\n\tp_rel_rotate.fi = 0.0;\n\tp_rel_rotate.ka = 90 * M_PI/180.0;\n\n\tEigen::Affine3d m_rel;\n\n\tfor(int c = 0; c < 4; c++){\n\t\tfor(size_t i = 0 ; i < 3; i++){\n\t\t\tm_rel = affine_matrix_from_pose_tait_bryan(p_rel_forward_x);\n\t\t\tm = m * m_rel;\n\t\t\tm_poses.push_back(m);\n\t\t}\n\t\tm_rel = affine_matrix_from_pose_tait_bryan(p_rel_rotate);\n\t\tm = m * m_rel;\n\t}\n\tm_poses.pop_back();\n\tm_poses_desired = m_poses;\n\tm_poses.clear();\n\tp0.px = 0;\n\tp0.py = 0;\n\tp0.pz = 0;\n\tp0.om = 0;\n\tp0.fi = 0;\n\tp0.ka = 30 * M_PI/180;\n\tm = affine_matrix_from_pose_tait_bryan(p0);\n\tm_poses.push_back(m);\n\n\tp_rel_forward_x.px = 1.1;\n\tp_rel_forward_x.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\tp_rel_forward_x.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\tp_rel_forward_x.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\tp_rel_forward_x.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\tp_rel_forward_x.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\n\tp_rel_rotate.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\tp_rel_rotate.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\tp_rel_rotate.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\tp_rel_rotate.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\tp_rel_rotate.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\tp_rel_rotate.ka = 80 * M_PI/180.0;\n\n\n\tfor(int c = 0; c < 4; c++){\n\t\tfor(size_t i = 0 ; i < 3; i++){\n\t\t\tm_rel = affine_matrix_from_pose_tait_bryan(p_rel_forward_x);\n\t\t\tm = m * m_rel;\n\t\t\tm_poses.push_back(m);\n\t\t\tp_rel_forward_x.px += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\tp_rel_forward_x.py += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\tp_rel_forward_x.pz += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tp_rel_forward_x.om += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tp_rel_forward_x.fi += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tp_rel_forward_x.ka += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t}\n\t\tm_rel = affine_matrix_from_pose_tait_bryan(p_rel_rotate);\n\t\tm = m * m_rel;\n\t\tp_rel_rotate.px += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\tp_rel_rotate.py += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\tp_rel_rotate.pz += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\tp_rel_rotate.om += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\tp_rel_rotate.fi += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\tp_rel_rotate.ka += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t}\n\tm_poses.pop_back();\n\tfor(size_t i = 1; i < m_poses.size(); i++){\n\t\todo_edges.emplace_back(i-1,i);\n\t}\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\treturn 0;\n}\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"relative_pose_covariances\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01,\n\t\t\t10000.0);\n\tglutReshapeFunc(reshape);\n\treturn true;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\t/*glBegin(GL_LINES);\n\tglColor3f(1.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(1.0f, 0.0f, 0.0f);\n\n\tglColor3f(0.0f, 1.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 1.0f, 0.0f);\n\n\tglColor3f(0.0f, 0.0f, 1.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 1.0f);\n\tglEnd();*/\n\n\tglColor3f(1,0,0);\n\tglBegin(GL_LINES);\n\tfor(size_t i = 0; i < odo_edges.size(); i++){\n\t\tglVertex3f(m_poses[odo_edges[i].first](0,3), m_poses[odo_edges[i].first](1,3), m_poses[odo_edges[i].first](2,3) );\n\t\tglVertex3f(m_poses[odo_edges[i].second](0,3), m_poses[odo_edges[i].second](1,3), m_poses[odo_edges[i].second](2,3) );\n\t}\n\tglEnd();\n\n\tEigen::MatrixXd cov_b(m_poses.size() * 2, m_poses.size() * 2);\n\tcov_b = Eigen::MatrixXd::Zero(m_poses.size() * 2, m_poses.size() * 2);\n\tcalculate_cov( m_poses,\tm_poses_desired, odo_edges, cov_b);\n\n\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\tEigen::Vector3d mean(m_poses[i](0,3), m_poses[i](1,3), m_poses[i](2,3));\n\t\tEigen::Matrix3d cov;\n\t\tint r = i * 6;\n\t\tint c = i * 6;\n\t\tcov(0,0) = cov_b(r+0,c+0);\n\t\tcov(0,1) = cov_b(r+0,c+1);\n\t\tcov(0,2) = cov_b(r+0,c+2);\n\t\tcov(1,0) = cov_b(r+1,c+0);\n\t\tcov(1,1) = cov_b(r+1,c+1);\n\t\tcov(1,2) = cov_b(r+1,c+2);\n\t\tcov(2,0) = cov_b(r+2,c+0);\n\t\tcov(2,1) = cov_b(r+2,c+1);\n\t\tcov(2,2) = cov_b(r+2,c+2);\n\t\tdraw_ellipse2D(cov, mean, Eigen::Vector3f(1,0,0),1);\n\t\tdraw_ellipse2D(cov, mean, Eigen::Vector3f(0,1,0),2);\n\t\tdraw_ellipse2D(cov, mean, Eigen::Vector3f(0,0,1),3);\n\t}\n\tglutSwapBuffers();\n}\n\nvoid keyboard(unsigned char key, int /*x*/, int /*y*/) {\n\tswitch (key) {\n\t\tcase (27): {\n\t\t\tglutDestroyWindow(glutGetWindow());\n\t\t\treturn;\n\t\t}\n\t\tcase 'e':{\n\t\t\todo_edges.emplace_back(1, m_poses.size()-2);\n\t\t\tis_loop_closure_added = true;\n\t\t\tbreak;\n\t\t}\n\t\tcase 'n':{\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_poses[i]);\n\t\t\t\tpose.px += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.py += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.pz += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.001;\n\t\t\t\tpose.om += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.0001;\n\t\t\t\tpose.fi += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.0001;\n\t\t\t\tpose.ka += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.0001;\n\t\t\t\tm_poses[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 't':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<TaitBryanPose> poses;\n\t\t\tstd::vector<TaitBryanPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_tait_bryan_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_tait_bryan_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_tait_bryan_wc_case1(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].om,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].om,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 6;\n\t\t\t\tint ic_2 = odo_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\n\t\t\t\tfloat angle_diff = delta(3,0);\n\t\t\t\tif(fabs(angle_diff) > M_PI){\n\t\t\t\t\tangle_diff -= 2.0*M_PI;\n\t\t\t\t}\n\t\t\t\tif(fabs(angle_diff)< -M_PI){\n\t\t\t\t\tangle_diff += 2.0*M_PI;\n\t\t\t\t}\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, angle_diff);\n\n\t\t\t\tangle_diff = delta(4,0);\n\t\t\t\tif(fabs(angle_diff) > M_PI){\n\t\t\t\t\tangle_diff -= 2.0*M_PI;\n\t\t\t\t}\n\t\t\t\tif(fabs(angle_diff)< -M_PI){\n\t\t\t\t\tangle_diff += 2.0*M_PI;\n\t\t\t\t}\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, angle_diff);\n\n\t\t\t\tangle_diff = delta(5,0);\n\t\t\t\tif(fabs(angle_diff) > M_PI){\n\t\t\t\t\tangle_diff -= 2.0*M_PI;\n\t\t\t\t}\n\t\t\t\tif(fabs(angle_diff)< -M_PI){\n\t\t\t\t\tangle_diff += 2.0*M_PI;\n\t\t\t\t}\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, angle_diff);\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     1);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 1);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 1);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 1);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 1);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 1);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 6 , m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 6 , 1);\n\n\t\t\t{\n\t\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\t\tAtPA = (AtP) * matA;\n\t\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with tait bryan finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with tait bryan FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"n: add noise to poses\" << std::endl;\n\tstd::cout << \"t: optimize (Tait-Bryan)\" << std::endl;\n\tstd::cout << \"e: add edge (loop closure)\" << std::endl;\n}\n\nvoid calculate_cov(std::vector<Eigen::Affine3d> m_poses,\n\t\t\t\t   std::vector<Eigen::Affine3d> m_poses_desired,\n\t\t\t\t   std::vector<std::pair<int, int>> odo_edges,\n\t\t\t\t   Eigen::MatrixXd & cov_b)\n{\n\tEigen::MatrixXd d2sum_dbeta2(m_poses.size() * 6, m_poses.size() * 6);\n\td2sum_dbeta2 = Eigen::MatrixXd::Zero(m_poses.size() * 6, m_poses.size() * 6);\n\n\tstd::vector<TaitBryanPose> poses;\n\tstd::vector<TaitBryanPose> poses_desired;\n\n\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\tposes.push_back(pose_tait_bryan_from_affine_matrix(m_poses[i]));\n\t}\n\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\tposes_desired.push_back(pose_tait_bryan_from_affine_matrix(m_poses_desired[i]));\n\t}\n\n\tfor (size_t i = 0; i < odo_edges.size(); i++ ){\n\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\trelative_pose_tait_bryan_wc_case1(relative_pose_measurement_odo,\n\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\tposes_desired[odo_edges[i].first].om,\n\t\t\tposes_desired[odo_edges[i].first].fi,\n\t\t\tposes_desired[odo_edges[i].first].ka,\n\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\tposes_desired[odo_edges[i].second].om,\n\t\t\tposes_desired[odo_edges[i].second].fi,\n\t\t\tposes_desired[odo_edges[i].second].ka);\n\n\t\tEigen::Matrix<double, 12, 12, Eigen::RowMajor> d2sum_dbeta2i;\n\t\trelative_pose_obs_eq_tait_bryan_wc_case1_d2sum_dbeta2(\n\t\t\t\td2sum_dbeta2i,\n\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\tposes[odo_edges[i].second].ka,\n\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\tint raw = odo_edges[i].first * 6;\n\t\tint cal = odo_edges[i].first * 6;\n\t\tfor(size_t r = 0; r < 6; r++){\n\t\t\tfor(size_t c = 0; c < 6; c++){\n\t\t\t\td2sum_dbeta2(raw + r, cal + c) =\n\t\t\t\t\t\td2sum_dbeta2(raw + r, cal + c) + d2sum_dbeta2i(r,c);\n\t\t\t}\n\t\t}\n\t\traw = odo_edges[i].second * 6;\n\t\tcal = odo_edges[i].second * 6;\n\t\tfor(size_t r = 0; r < 6; r++){\n\t\t\tfor(size_t c = 0; c < 6; c++){\n\t\t\t\td2sum_dbeta2(raw + r, cal + c) =\n\t\t\t\t\t\td2sum_dbeta2(raw + r, cal + c) + d2sum_dbeta2i(r+6,c+6);\n\t\t\t}\n\t\t}\n\n\t\traw = odo_edges[i].first * 6;\n\t\tcal = odo_edges[i].second * 6;\n\t\tfor(size_t r = 0; r < 6; r++){\n\t\t\tfor(size_t c = 0; c < 6; c++){\n\t\t\t\td2sum_dbeta2(raw + r, cal + c) =\n\t\t\t\t\t\td2sum_dbeta2(raw + r, cal + c) + d2sum_dbeta2i(r,c+6);\n\t\t\t}\n\t\t}\n\t\traw = odo_edges[i].second * 6;\n\t\tcal = odo_edges[i].first * 6;\n\t\tfor(size_t r = 0; r < 6; r++){\n\t\t\tfor(size_t c = 0; c < 6; c++){\n\t\t\t\td2sum_dbeta2(raw + r, cal + c) =\n\t\t\t\t\t\td2sum_dbeta2(raw + r, cal + c) + d2sum_dbeta2i(r + 6,c);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (size_t i = 0; i < 6; i++ ){\n\t\td2sum_dbeta2(i,i) += 1000000;\n\t}\n\n\tEigen::MatrixXd d2sum_dbetadx(m_poses.size() * 12, 6 * odo_edges.size());\n\td2sum_dbetadx = Eigen::MatrixXd::Zero(m_poses.size() * 12, 6 * odo_edges.size());\n\n\tfor (int i = 0; i < odo_edges.size() ; i++)\n\t{\n\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\trelative_pose_tait_bryan_wc_case1(\n\t\t\trelative_pose_measurement_odo,\n\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\tposes_desired[odo_edges[i].first].om,\n\t\t\tposes_desired[odo_edges[i].first].fi,\n\t\t\tposes_desired[odo_edges[i].first].ka,\n\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\tposes_desired[odo_edges[i].second].om,\n\t\t\tposes_desired[odo_edges[i].second].fi,\n\t\t\tposes_desired[odo_edges[i].second].ka);\n\t\tEigen::Matrix<double, 12, 6, Eigen::RowMajor> d2sum_dbetadx_temp;\n\t\trelative_pose_obs_eq_tait_bryan_wc_case1_d2sum_dbetadx(\n\t\t\td2sum_dbetadx_temp,\n\t\t\tposes[odo_edges[i].first].px,\n\t\t\tposes[odo_edges[i].first].py,\n\t\t\tposes[odo_edges[i].first].pz,\n\t\t\tposes[odo_edges[i].first].om,\n\t\t\tposes[odo_edges[i].first].fi,\n\t\t\tposes[odo_edges[i].first].ka,\n\t\t\tposes[odo_edges[i].second].px,\n\t\t\tposes[odo_edges[i].second].py,\n\t\t\tposes[odo_edges[i].second].pz,\n\t\t\tposes[odo_edges[i].second].om,\n\t\t\tposes[odo_edges[i].second].fi,\n\t\t\tposes[odo_edges[i].second].ka,\n\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\tint raw = odo_edges[i].first * 6;\n\t\tint cal = i * 6;\n\t\tfor(size_t r = 0; r < 6; r++){\n\t\t\tfor(size_t c = 0; c < 6; c++){\n\t\t\t\td2sum_dbetadx(raw + r, cal + c) = d2sum_dbetadx_temp(r,c);\n\t\t\t}\n\t\t}\n\t\traw = odo_edges[i].second * 6;\n\t\tfor(size_t r = 0; r < 6; r++){\n\t\t\tfor(size_t c = 0; c < 6; c++){\n\t\t\t\td2sum_dbetadx(raw + r, cal + c) = d2sum_dbetadx_temp(r + 6,c);\n\t\t\t}\n\t\t}\n\t}\n\n\tEigen::MatrixXd cov_x(6 * odo_edges.size(), 6 * odo_edges.size());\n\tcov_x = Eigen::MatrixXd::Zero(6 * odo_edges.size(), 6 * odo_edges.size());\n\n\tfor(int i = 0 ; i < 6 * odo_edges.size(); i+=6){\n\t\tcov_x(i,i)     = 0.005 * 0.005;\n\t\tcov_x(i+1,i+1) = 0.05 * 0.05;\n\t\tcov_x(i+2,i+2) = 0.000000001 * 0.000000001;\n\t\tcov_x(i+3,i+3) = 0.000000001 * 0.000000001;\n\t\tcov_x(i+4,i+4) = 0.000000001 * 0.000000001;\n\t\tcov_x(i+5,i+5) = 0.01 * 0.01;\n\t}\n\tif(is_loop_closure_added){\n\t\tint i = 6 * (odo_edges.size()-1);\n\t\tcov_x(i,i)     = 0.01*0.01;\n\t\tcov_x(i+1,i+1) = 0.01*0.01;\n\t\tcov_x(i+2,i+2) = 0.01*0.01;\n\t\tcov_x(i+3,i+3) = 0.01 * 0.01;\n\t\tcov_x(i+4,i+4) = 0.01 * 0.01;\n\t\tcov_x(i+5,i+5) = 0.01 * 0.01;\n\t}\n\n\tcov_b = d2sum_dbeta2.inverse() * d2sum_dbetadx * cov_x * d2sum_dbetadx.transpose() * d2sum_dbeta2.inverse();\n}\n\n\n\n\n\n\n", "meta": {"hexsha": "27a57e9ea2e6970e2201178c8369a11beb8aef6b", "size": 24841, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/relative_pose_covariances.cpp", "max_stars_repo_name": "JanuszBedkowski/observation_equations", "max_stars_repo_head_hexsha": "ab241f571a655aebc89870f54e01cb7347382aa9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-11T13:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T22:04:00.000Z", "max_issues_repo_path": "codes/c++Examples/src/relative_pose_covariances.cpp", "max_issues_repo_name": "JanuszBedkowski/observation_equations", "max_issues_repo_head_hexsha": "ab241f571a655aebc89870f54e01cb7347382aa9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/c++Examples/src/relative_pose_covariances.cpp", "max_forks_repo_name": "JanuszBedkowski/observation_equations", "max_forks_repo_head_hexsha": "ab241f571a655aebc89870f54e01cb7347382aa9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-30T22:33:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T18:21:21.000Z", "avg_line_length": 32.7285902503, "max_line_length": 119, "alphanum_fraction": 0.6395475222, "num_tokens": 9131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.6825737214979745, "lm_q1q2_score": 0.4147749112500926}}
{"text": "#ifndef INCLUDED_numeric_rand_xform_HH\n#define INCLUDED_numeric_rand_xform_HH\n\n#include \"scheme/numeric/util.hh\"\n#include <Eigen/Geometry>\n#include <random>\n\nnamespace scheme { namespace numeric {\n\n\ntemplate<class T>\nvoid\nrand_xform(\n\tstd::mt19937 & rng,\n\tEigen::Transform<T,3,Eigen::Affine> & x,\n\tT cart_bound = 512.0\n){\n\tstd::uniform_real_distribution<> runif;\n\tstd::normal_distribution<> rnorm;\n\tEigen::Quaterniond qrand( rnorm(rng), rnorm(rng), rnorm(rng), rnorm(rng) );\n\tqrand.normalize();\n\tEigen::Matrix3d m = qrand.matrix();\n\n\tx.data()[3] = 0; x.data()[7] = 0; x.data()[11] = 0; x.data()[15] = 1;\n\tfor(int i = 0; i <  3; ++i) x.data()[i] = m.data()[i-0];\n\tfor(int i = 4; i <  7; ++i) x.data()[i] = m.data()[i-1];\n\tfor(int i = 8; i < 11; ++i) x.data()[i] = m.data()[i-2];\n\tx.data()[12] = runif(rng) * cart_bound - cart_bound/2.0;\n\tx.data()[13] = runif(rng) * cart_bound - cart_bound/2.0;\n\tx.data()[14] = runif(rng) * cart_bound - cart_bound/2.0;\n}\n\ntemplate<class T>\nvoid\nrand_xform(\n\tstd::mt19937 & rng,\n\tEigen::Transform<T,3,Eigen::AffineCompact> & x,\n\tT cart_bound = 512.0\n){\n\tstd::uniform_real_distribution<> runif;\n\tstd::normal_distribution<> rnorm;\n\tEigen::Quaterniond qrand( rnorm(rng), rnorm(rng), rnorm(rng), rnorm(rng) );\n\tqrand.normalize();\n\tEigen::Matrix3d m = qrand.matrix();\n\tfor(int i = 0; i < 9; ++i) x.data()[i] = m.data()[i];\n\n\tx.data()[ 9] = runif(rng) * cart_bound - cart_bound/2.0;\n\tx.data()[10] = runif(rng) * cart_bound - cart_bound/2.0;\n\tx.data()[11] = runif(rng) * cart_bound - cart_bound/2.0;\n}\n\n\ntemplate<class X>\nX rand_xform(\n\tstd::mt19937 & rng,\n\tscalar<X> cart_bound = 512.0\n){\n\tX x;\n\trand_xform(rng,x,cart_bound);\n\treturn x;\n}\n\ntemplate<class T>\nvoid\nrand_xform_cartnormal(\n\tstd::mt19937 & rng,\n\tEigen::Transform<T,3,Eigen::AffineCompact> & x,\n\tT const & cart_sd\n){\n\tstd::uniform_real_distribution<> runif;\n\tstd::normal_distribution<> rnorm;\n\tEigen::Quaterniond qrand( rnorm(rng), rnorm(rng), rnorm(rng), rnorm(rng) );\n\tqrand.normalize();\n\tEigen::Matrix3d m = qrand.matrix();\n\tfor(int i = 0; i < 9; ++i) x.data()[i] = m.data()[i];\n\tx.data()[ 9] = rnorm(rng) * cart_sd;\n\tx.data()[10] = rnorm(rng) * cart_sd;\n\tx.data()[11] = rnorm(rng) * cart_sd;\n}\n\ntemplate<class T>\nvoid\nrand_xform_quat(\n\tstd::mt19937 & rng,\n\tEigen::Transform<T,3,Eigen::AffineCompact> & x,\n\tdouble cart_bound, double quat_bound\n){\n\tstd::uniform_real_distribution<> runif;\n\tstd::normal_distribution<> rnorm;\n\n\tassert( quat_bound < sqrt(3.0)/2.0 );\n\n\t{ // ori part\n\t\tEigen::Quaterniond qrand( 0.0, rnorm(rng), rnorm(rng), rnorm(rng) );\n\t\tdouble scale = 1.0 - runif(rng)*runif(rng);\n\t\tdouble len = qrand.norm();\n\t\tqrand.x() *= scale * quat_bound / len;\n\t\tqrand.y() *= scale * quat_bound / len;\n\t\tqrand.z() *= scale * quat_bound / len;\n\t\tqrand.w() = sqrt( 1.0 - qrand.squaredNorm() );\n\t\tassert( fabs( qrand.norm() - 1.0) < 0.00001 );\n\n\t\tqrand.normalize();\n\t\tEigen::Matrix3d m = qrand.matrix();\n\t\tfor(int i = 0; i < 9; ++i) x.data()[i] = m.data()[i];\n\t}\n\t{ // cart part\n\t\tx.data()[ 9] = rnorm(rng);\n\t\tx.data()[10] = rnorm(rng);\n\t\tx.data()[11] = rnorm(rng);\n\t\tdouble scale = 1.0 - runif(rng)*runif(rng);\n\t\tdouble len = sqrt( x.data()[9]*x.data()[9] + x.data()[10]*x.data()[10] + x.data()[11]*x.data()[11] );\n\t\tx.data()[ 9] *= scale * cart_bound / len;\n\t\tx.data()[10] *= scale * cart_bound / len;\n\t\tx.data()[11] *= scale * cart_bound / len;\n\t}\n}\n\ntemplate<class T>\nvoid\nrand_xform_sphere(\n\tstd::mt19937 & rng,\n\tEigen::Transform<T,3,Eigen::AffineCompact> & x,\n\tT const cart_radius,\n\tT const ang_radius\n){\n\tstd::normal_distribution<> rnorm;\n\tstd::uniform_real_distribution<> runif;\n\n\tfloat ang = (1.0 - runif(rng)*runif(rng)) * ang_radius;\n\tEigen::Matrix<float,1,3> axis( rnorm(rng), rnorm(rng), rnorm(rng) );\n\taxis.normalize();\n\tEigen::AngleAxis<T> aa( ang, axis );\n\tx = Eigen::Transform<T,3,Eigen::AffineCompact> ( aa );\n\n\tEigen::AngleAxis<T> aa2( x.rotation() );\n\n\t// std::cout << ang << \" \" << ang_radius << \" \" << aa2.angle() << std::endl;\n\n\tEigen::Matrix<float,1,3> delta( 9e9, 9e9, 9e9 );\n\twhile( delta.squaredNorm() > cart_radius*cart_radius ){\n\t\tdelta = 2.0 * cart_radius * Eigen::Matrix<float,1,3>( runif(rng)-0.5, runif(rng)-0.5, runif(rng)-0.5 );\n\t}\n\n\tx.translation() = delta;\n\n}\n\n\n\n}}\n\n\n#endif\n", "meta": {"hexsha": "c4bd071dd91542024ce7fc945d9a0394f56435d9", "size": 4204, "ext": "hh", "lang": "C++", "max_stars_repo_path": "schemelib/scheme/numeric/rand_xform.hh", "max_stars_repo_name": "willsheffler/rifdock", "max_stars_repo_head_hexsha": "291d05112d52318bb07d499ce6da3e0fb9fbf9cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T07:59:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T06:32:14.000Z", "max_issues_repo_path": "schemelib/scheme/numeric/rand_xform.hh", "max_issues_repo_name": "willsheffler/rifdock", "max_issues_repo_head_hexsha": "291d05112d52318bb07d499ce6da3e0fb9fbf9cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "schemelib/scheme/numeric/rand_xform.hh", "max_forks_repo_name": "willsheffler/rifdock", "max_forks_repo_head_hexsha": "291d05112d52318bb07d499ce6da3e0fb9fbf9cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1225806452, "max_line_length": 105, "alphanum_fraction": 0.635585157, "num_tokens": 1431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.4147355153291146}}
{"text": "/*\n * Copyright 2011-2012 Mario Mulansky\n * Copyright 2012-2013 Karsten Ahnert\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n *\n * Example for self defined vector type.\n */\n\n#include <vector>\n\n#include <boost/numeric/odeint.hpp>\n\n//[my_vector\ntemplate< size_t MAX_N >\nclass my_vector\n{\n    typedef std::vector< double > vector;\n\npublic:\n    typedef vector::iterator iterator;\n    typedef vector::const_iterator const_iterator;\n\npublic:\n    my_vector( const size_t N )\n        : m_v( N )\n    {\n        m_v.reserve( MAX_N );\n    }\n\n    my_vector()\n        : m_v()\n    {\n        m_v.reserve( MAX_N );\n    }\n\n// ... [ implement container interface ]\n//]\n    const double & operator[]( const size_t n ) const\n    { return m_v[n]; }\n\n    double & operator[]( const size_t n )\n    { return m_v[n]; }\n\n    iterator begin()\n    { return m_v.begin(); }\n\n    const_iterator begin() const\n    { return m_v.begin(); }\n\n    iterator end()\n    { return m_v.end(); }\n\n    const_iterator end() const\n    { return m_v.end(); }\n\n    size_t size() const\n    { return m_v.size(); }\n\n    void resize( const size_t n )\n    { m_v.resize( n ); }\n\nprivate:\n    std::vector< double > m_v;\n\n};\n\n//[my_vector_resizeable\n// define my_vector as resizeable\n\nnamespace boost { namespace numeric { namespace odeint {\n\ntemplate<size_t N>\nstruct is_resizeable< my_vector<N> >\n{\n    typedef boost::true_type type;\n    static const bool value = type::value;\n};\n\n} } }\n//]\n\n\ntypedef my_vector<3> state_type;\n\nvoid lorenz( const state_type &x , state_type &dxdt , const double t )\n{\n    const double sigma( 10.0 );\n    const double R( 28.0 );\n    const double b( 8.0 / 3.0 );\n\n    dxdt[0] = sigma * ( x[1] - x[0] );\n    dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n    dxdt[2] = -b * x[2] + x[0] * x[1];\n}\n\nusing namespace boost::numeric::odeint;\n\nint main()\n{\n    state_type x(3);\n    x[0] = 5.0 ; x[1] = 10.0 ; x[2] = 10.0;\n\n    // make sure resizing is ON\n    BOOST_STATIC_ASSERT( is_resizeable<state_type>::value == true );\n\n    // my_vector works with range_algebra as it implements\n    // the required parts of a container interface\n    // no further work is required\n\n    integrate_const( runge_kutta4< state_type >() , lorenz , x , 0.0 , 10.0 , 0.1 );\n}\n", "meta": {"hexsha": "c16727b6afc75068425b70ed3ca7fc55593db44f", "size": 2331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/libs/numeric/odeint/examples/my_vector.cpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/libs/numeric/odeint/examples/my_vector.cpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/libs/numeric/odeint/examples/my_vector.cpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 20.2695652174, "max_line_length": 84, "alphanum_fraction": 0.616044616, "num_tokens": 684, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.6584174938590246, "lm_q1q2_score": 0.41465460955301797}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file zabrinterpolation.hpp\n    \\brief ZABR interpolation interpolation between discrete points\n*/\n\n#ifndef quantlib_zabr_interpolation_hpp\n#define quantlib_zabr_interpolation_hpp\n\n#include <ql/math/interpolations/xabrinterpolation.hpp>\n#include <ql/experimental/volatility/zabrsmilesection.hpp>\n\n#include <boost/assign/list_of.hpp>\n\nnamespace QuantLib {\n\nnamespace detail {\n\ntemplate <typename Evaluation> struct ZabrSpecs {\n    Size dimension() { return 5; }\n    Real eps() { return 0.000001; }\n    void defaultValues(std::vector<Real> &params,\n                       std::vector<bool> &paramIsFixed, const Real &forward,\n                       const Real expiryTime, const std::vector<Real>& addParams) {\n        if (params[1] == Null<Real>())\n            params[1] = 0.5;\n        if (params[0] == Null<Real>())\n            // adapt alpha to beta level\n            params[0] =\n                0.2 *\n                (params[1] < 0.9999 ? std::pow(forward, 1.0 - params[1]) : 1.0);\n        if (params[2] == Null<Real>())\n            params[2] = std::sqrt(0.4);\n        if (params[3] == Null<Real>())\n            params[3] = 0.0;\n        if (params[4] == Null<Real>())\n            params[4] = 1.0;\n    }\n    void guess(Array &values, const std::vector<bool> &paramIsFixed,\n               const Real &forward, const Real expiryTime,\n               const std::vector<Real> &r, const std::vector<Real>& addParams) {\n        Size j = 0;\n        if (!paramIsFixed[1])\n            values[1] = (1.0 - 2E-6) * r[j++] + 1E-6;\n        if (!paramIsFixed[0]) {\n            values[0] = (1.0 - 2E-6) * r[j++] + 1E-6; // lognormal vol guess\n            // adapt this to beta level\n            if (values[1] < 0.999)\n                values[0] *= std::pow(forward, 1.0 - values[1]);\n        }\n        if (!paramIsFixed[2])\n            values[2] = 1.5 * r[j++] + 1E-6;\n        if (!paramIsFixed[3])\n            values[3] = (2.0 * r[j++] - 1.0) * (1.0 - 1E-6);\n        if (!paramIsFixed[4])\n            values[4] = r[j++] * 2.0;\n    }\n    Real eps1() { return .0000001; }\n    Real eps2() { return .9999; }\n    Real dilationFactor() { return 0.001; }\n    Array inverse(const Array &y, const std::vector<bool> &,\n                  const std::vector<Real> &, const Real) {\n        Array x(5);\n        x[0] = y[0] < 25.0 + eps1() ? std::sqrt(y[0] - eps1())\n                                    : (y[0] - eps1() + 25.0) / 10.0;\n        x[1] = std::sqrt(-std::log(y[1]));\n        x[2] = std::tan(M_PI*(y[4]/5.0-0.5));\n        x[3] = std::asin(y[3] / eps2());\n        x[4] = std::tan(M_PI*(y[4]/1.9-0.5));\n        return x;\n    }\n    Array direct(const Array &x, const std::vector<bool> &,\n                 const std::vector<Real> &, const Real) {\n        Array y(5);\n        y[0] = std::fabs(x[0]) < 5.0 ? x[0] * x[0] + eps1()\n                                     : (10.0 * std::fabs(x[0]) - 25.0) + eps1();\n        y[1] = std::fabs(x[1]) < std::sqrt(-std::log(eps1()))\n                   ? std::exp(-(x[1] * x[1]))\n                   : eps1();\n        // limit nu to 5.00\n        y[2] = (std::atan(x[2])/M_PI + 0.5) * 5.0;\n        y[3] = std::fabs(x[3]) < 2.5 * M_PI\n                   ? eps2() * std::sin(x[3])\n                   : eps2() * (x[3] > 0.0 ? 1.0 : (-1.0));\n        // limit gamma to 1.9\n        y[4] = (std::atan(x[4])/M_PI + 0.5) * 1.9;\n        return y;\n    }\n    Real weight(const Real strike, const Real forward, const Real stdDev,\n                const std::vector<Real> &addParams) {\n        return blackFormulaStdDevDerivative(strike, forward, stdDev, 1.0);\n    }\n    typedef ZabrSmileSection<Evaluation> type;\n    ext::shared_ptr<type> instance(const Time t, const Real &forward,\n                                     const std::vector<Real> &params,\n                                     const std::vector<Real> &addParams) {\n        return ext::make_shared<type>(t, forward, params);\n    }\n};\n} // end namespace detail\n\n\n//! zabr smile interpolation between discrete volatility points.\ntemplate <class Evaluation> class ZabrInterpolation : public Interpolation {\n  public:\n    template <class I1, class I2>\n    ZabrInterpolation(\n        const I1 &xBegin, // x = strikes\n        const I1 &xEnd,\n        const I2 &yBegin, // y = volatilities\n        Time t,           // option expiry\n        const Real &forward, Real alpha, Real beta, Real nu, Real rho,\n        Real gamma, bool alphaIsFixed, bool betaIsFixed, bool nuIsFixed,\n        bool rhoIsFixed, bool gammaIsFixed, bool vegaWeighted = true,\n        const ext::shared_ptr<EndCriteria> &endCriteria =\n            ext::shared_ptr<EndCriteria>(),\n        const ext::shared_ptr<OptimizationMethod> &optMethod =\n            ext::shared_ptr<OptimizationMethod>(),\n        const Real errorAccept = 0.0020, const bool useMaxError = false,\n        const Size maxGuesses = 50) {\n            impl_ = ext::shared_ptr<\n                Interpolation::Impl>(new detail::XABRInterpolationImpl<\n                I1, I2,\n                detail::ZabrSpecs<Evaluation> >(\n                xBegin, xEnd, yBegin, t, forward,\n                boost::assign::list_of(alpha)(beta)(nu)(rho)(gamma),\n                boost::assign::list_of(alphaIsFixed)(betaIsFixed)(nuIsFixed)(\n                    rhoIsFixed)(gammaIsFixed),\n                vegaWeighted, endCriteria, optMethod, errorAccept, useMaxError,\n                maxGuesses));\n            coeffs_ = ext::dynamic_pointer_cast<detail::XABRCoeffHolder<\n                detail::ZabrSpecs<Evaluation> > >(impl_);\n    }\n    Real expiry() const { return coeffs_->t_; }\n    Real forward() const { return coeffs_->forward_; }\n    Real alpha() const { return coeffs_->params_[0]; }\n    Real beta() const { return coeffs_->params_[1]; }\n    Real nu() const { return coeffs_->params_[2]; }\n    Real rho() const { return coeffs_->params_[3]; }\n    Real gamma() const { return coeffs_->params_[4]; }\n    Real rmsError() const { return coeffs_->error_; }\n    Real maxError() const { return coeffs_->maxError_; }\n    const std::vector<Real> &interpolationWeights() const {\n        return coeffs_->weights_;\n    }\n    EndCriteria::Type endCriteria() { return coeffs_->XABREndCriteria_; }\n\n  private:\n    ext::shared_ptr<detail::XABRCoeffHolder<detail::ZabrSpecs<Evaluation> > > coeffs_;\n};\n\n//! no arbtrage sabr interpolation factory and traits\ntemplate<class Evaluation> class Zabr {\n  public:\n    Zabr(Time t,\n         Real forward,\n         Real alpha,\n         Real beta,\n         Real nu,\n         Real rho,\n         Real gamma,\n         bool alphaIsFixed,\n         bool betaIsFixed,\n         bool nuIsFixed,\n         bool rhoIsFixed,\n         bool gammaIsFixed,\n         bool vegaWeighted = false,\n         const ext::shared_ptr<EndCriteria>& endCriteria = ext::shared_ptr<EndCriteria>(),\n         const ext::shared_ptr<OptimizationMethod>& optMethod =\n             ext::shared_ptr<OptimizationMethod>(),\n         const Real errorAccept = 0.0020,\n         const bool useMaxError = false,\n         const Size maxGuesses = 50)\n    : t_(t), forward_(forward), alpha_(alpha), beta_(beta), nu_(nu), rho_(rho),\n      alphaIsFixed_(alphaIsFixed), betaIsFixed_(betaIsFixed), nuIsFixed_(nuIsFixed),\n      rhoIsFixed_(rhoIsFixed), gammaIsFixed_(gammaIsFixed), vegaWeighted_(vegaWeighted),\n      endCriteria_(endCriteria), optMethod_(optMethod), errorAccept_(errorAccept),\n      useMaxError_(useMaxError), maxGuesses_(maxGuesses) {}\n    template <class I1, class I2>\n    Interpolation interpolate(const I1 &xBegin, const I1 &xEnd,\n                              const I2 &yBegin) const {\n        return ZabrInterpolation<Evaluation>(\n            xBegin, xEnd, yBegin, t_, forward_, alpha_, beta_, nu_, rho_,\n            gamma_, alphaIsFixed_, betaIsFixed_, nuIsFixed_, rhoIsFixed_,\n            gammaIsFixed_, vegaWeighted_, endCriteria_, optMethod_,\n            errorAccept_, useMaxError_, maxGuesses_);\n    }\n    static const bool global = true;\n\n  private:\n    Time t_;\n    Real forward_;\n    Real alpha_, beta_, nu_, rho_, gamma_;\n    bool alphaIsFixed_, betaIsFixed_, nuIsFixed_, rhoIsFixed_, gammaIsFixed_;\n    bool vegaWeighted_;\n    const ext::shared_ptr<EndCriteria> endCriteria_;\n    const ext::shared_ptr<OptimizationMethod> optMethod_;\n    const Real errorAccept_;\n    const bool useMaxError_;\n    const Size maxGuesses_;\n};\n}\n\n#endif\n", "meta": {"hexsha": "4b4485f01c5ca1bc61a1d06d5a62fe556ea884a6", "size": 9108, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/volatility/zabrinterpolation.hpp", "max_stars_repo_name": "urgu00/QuantLib", "max_stars_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-27T17:17:12.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-27T17:17:12.000Z", "max_issues_repo_path": "ql/experimental/volatility/zabrinterpolation.hpp", "max_issues_repo_name": "urgu00/QuantLib", "max_issues_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T08:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:06:53.000Z", "max_forks_repo_path": "ql/experimental/volatility/zabrinterpolation.hpp", "max_forks_repo_name": "urgu00/QuantLib", "max_forks_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-04T15:19:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T08:24:37.000Z", "avg_line_length": 41.027027027, "max_line_length": 90, "alphanum_fraction": 0.588493632, "num_tokens": 2494, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4145213431436287}}
{"text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n#include <assert.h>\n\n#include <fstream>\n#include <iomanip>\n#include <algorithm>\n#include <tuple>\n#include <vector>\n#include <math.h>\n#include <chrono>\n#include <stdlib.h>\n#include \"matcher.h\"\n#include <Eigen/Dense>\n//delete this probably\n#include <ctime>\n#include \"boost/filesystem.hpp\"\nnamespace fs = boost::filesystem;\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace PQ\n{\n\n\nMatcher::Matcher(string code_file)\n{\n    N = 200;\n    time.resize(10);\n    nrof_matching = 0;\n    codewords = NULL;\n    description.push_back(\"minutiae similarity\");\n\n    description.push_back(\"obtaining corr\");\n\n    description.push_back(\"second order fast\");\n\n    description.push_back(\"second order original\");\n\n    dist_N = 50;\n    table_dist.resize(dist_N*dist_N);\n    max_nrof_templates = 0;\n    int n = 0;\n    for(int i=0;i<dist_N; ++i)\n    {\n        for(int j=i;j<dist_N;++j)\n        {\n            table_dist[i*dist_N+j] = sqrt((i*16.0)*(i*16.0) +  (j*16.0)*(j*16.0));\n            table_dist[j*dist_N+i] = table_dist[i*dist_N+j];\n        }\n    }\n    //    load code book\n    ifstream is;\n    is.open(code_file, ifstream::binary);\n    // get length of file:\n    is.seekg(0, ios::end);\n    int length = is.tellg();\n\n    if( length<=0 )\n    {\n        cout<<\"codebook is empty!\"<<endl;\n    }\n    is.seekg(0, ios::beg);\n\n    nrof_subs = 0;\n    nrof_clusters=0;\n    sub_dim = 0;\n\n    is.read(reinterpret_cast<char*>(&nrof_subs),sizeof(short));\n    is.read(reinterpret_cast<char*>(&nrof_clusters),sizeof(short));\n    is.read(reinterpret_cast<char*>(&sub_dim),sizeof(short));\n\n    int len = nrof_subs*nrof_clusters*sub_dim;\n    if(len<=0)\n    {\n        cout<<\"codebook is empty!\"<<endl;\n    }\n\n    codewords = new float[len];\n    float *pword = codewords;\n    for(int i=0;i<nrof_subs; ++i)\n    {\n        for(int j=0; j<nrof_clusters; ++j)\n        {\n            is.read(reinterpret_cast<char*>(pword),sizeof(float)*sub_dim);\n            pword += sub_dim;\n        }\n    }\n}\n\nint Matcher::List2List_matching(string latent_path, string rolled_path, string score_path)\n{\n    string template_file, score_file;\n\n    int nrof_latents = 0;\n    vector<fs::path> latent_template_files;\n    fs::directory_iterator end_itr;\n    for(fs::directory_iterator dir_itr(latent_path); dir_itr != end_itr; ++dir_itr)\n    {\n        if(dir_itr->path().extension() == \".dat\")\n        { \n            latent_template_files.push_back(dir_itr->path());\n            cout<<\"latent template file\"<<dir_itr->path()<<endl;\n            ++nrof_latents;\n        }\n    }\n    if(nrof_latents <= 0)\n    {\n        cout<<\"No latent templates found in directory: \"<<latent_path<<endl;\n        return -1;\n    }\n\n    register int i,j,k;\n\n    int nrof_rolled = 0;\n    vector<fs::path> rolled_template_files;\n    for(fs::directory_iterator dir_itr(rolled_path); dir_itr != end_itr; ++dir_itr)\n    {\n    if(dir_itr->path().extension() == \".dat\")\n        { \n            rolled_template_files.push_back(dir_itr->path());\n            cout<<\"rolled template file\"<<dir_itr->path()<<endl;\n            ++nrof_rolled;\n        }\n    }\n    if(nrof_rolled <= 0)\n    {\n        cout<<\"No rolled templates found in directory: \"<<rolled_path<<endl;\n        return -1;\n    }\n    cout<<\"Gallery size: \"<<nrof_rolled<<endl;\n    {\n        using namespace std::chrono;\n        vector<high_resolution_clock::time_point> t(10);\n        duration<double, std::milli> time_span;\n        t[0] = high_resolution_clock::now();\n\n        for(i=0;i<nrof_latents; ++i)\n        {\n            vector<float> scores(nrof_rolled, -1);\n            cout<<latent_template_files[i]<<endl;\n\n            LatentFPTemplate latent_FP;\n            //load latent original template and create a latent FP object\n            load_FP_template(latent_template_files[i].string(), latent_FP);\n            cout<<\"Latent minutiae templates: \"<<latent_FP.m_nrof_minu_templates<<endl;\n            cout<<\"Latent texture templates: \"<<latent_FP.m_nrof_texture_templates<<endl;\n            if(latent_FP.m_nrof_minu_templates<=0 && latent_FP.m_nrof_texture_templates<=0)\n            {\n\t\t\t\tcout<<\"No minutiae or texture templates found\"<<endl;\n                ofstream output;\n                output.open(score_path + latent_template_files[i].stem().string() + \".csv\");\n\n                output<<0<<endl;\n                output.close();\n\n                continue;\n            }\n\n            using namespace std::chrono;\n            high_resolution_clock::time_point t_start = high_resolution_clock::now();\n            int result = 0;\n\t        #pragma omp parallel for num_threads(8) schedule(static,16)\n            for(j=0;j<nrof_rolled; ++j)\n            {\n\n                RolledFPTemplate rolled_FP;\n                if(load_FP_template(rolled_template_files[j].string(), rolled_FP)<0)\n                {\n                    rolled_FP.m_nrof_minu_templates=0;\n                    rolled_FP.m_nrof_texture_templates = 0;\n                };\n\n\t\t\t\tvector<float> score;\n\t\t\t\tresult = One2One_matching_selected_templates(latent_FP,rolled_FP,score);\n                if(result == 1){\n                    continue;\n                }\n                else if(result == 2){\n                    cout<<\"Comparison failed: rolled template is empty. Skipping.\"<<endl;\n                    continue;\n                }\n\t\t\t\tfloat final_score = score[0] + score[1] + score[2] + score[28]*0.3;\n                scores[j] = final_score;\n            }\n            if(result == 1){\n                cout<<\"Matching failed: latent template is empty. Skipping.\"<<endl;\n                continue;\n            }\n            auto t_end = high_resolution_clock::now();\n            duration<double, std::milli> duration = (t_end - t_start);\n\n\t\t\tofstream output;\n\t\t\toutput.open(score_path + latent_template_files[i].stem().string() + \".csv\");\n\n\t\t\tfor(j=0;j<nrof_rolled; ++j)\n\t\t\t{\n                output<<rolled_template_files[j]<<\",\"<<std::setprecision(3)<<std::fixed<<scores[j]<<endl;\n\t\t\t}\n\t\t\toutput.close();\n        }\n        t[1] = high_resolution_clock::now();\n        time_span = t[1] - t[0];\n        cout<<\"Total matching duration (ms): \"<<time_span.count()<<endl;\n\n\t\tauto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now());\n    }\n    return 0;\n}\n\nint Matcher::One2List_matching(string latent_template_file_string, string rolled_list_file, string score_path)\n{\n\n    register int i,j,k;\n\n    fs::path latent_template_file(latent_template_file_string);\n    string score_file = score_path + latent_template_file.stem().string() + \".csv\";\n\n    int nrof_rolled = 0;\n    vector<fs::path> rolled_template_files;\n    fs::directory_iterator end_itr;\n    for(fs::directory_iterator dir_itr(rolled_list_file); dir_itr != end_itr; ++dir_itr)\n    {\n    if(dir_itr->path().extension() == \".dat\")\n        { \n            rolled_template_files.push_back(dir_itr->path());\n            ++nrof_rolled;\n        }\n    }\n    if(nrof_rolled <= 0)\n    {\n        cout<<\"No rolled templates found in directory: \"<<rolled_list_file<<endl;\n        return -1;\n    }\n\n    // Create a vector of indices\n    // Allows us to output a sorted score list for use with the GUI\n    vector<int> ind(rolled_template_files.size(), 0);\n    for(int n; n != rolled_template_files.size(); n++){\n        ind[n] = n;\n    }\n\n    {\n        using namespace std::chrono;\n        vector<high_resolution_clock::time_point> t(10);\n        duration<double, std::milli> time_span;\n        t[0] = high_resolution_clock::now();\n\n        vector<float> scores(nrof_rolled, -1);\n        cout<<\"Latent Query: \"<<latent_template_file<<endl;\n        cout<<\"Gallery size: \"<<nrof_rolled<<endl;\n        LatentFPTemplate latent_FP;\n        //load latent original template and create a latent FP object\n        load_FP_template(latent_template_file.string(), latent_FP);\n        if(latent_FP.m_nrof_minu_templates<=0 && latent_FP.m_nrof_texture_templates<=0)\n        {\n            ofstream output;\n            output.open(score_file);\n\n            output<<0<<endl;\n            output.close();\n\n        }\n\n        using namespace std::chrono;\n        high_resolution_clock::time_point t_start = high_resolution_clock::now();\n        int result = 0;\n        #pragma omp parallel for num_threads(8) schedule(static,16)\n        for(j=0;j<nrof_rolled; ++j)\n        {\n\n            RolledFPTemplate rolled_FP;\n            if(load_FP_template(rolled_template_files[j].string(), rolled_FP)<0)\n            {\n                rolled_FP.m_nrof_minu_templates=0;\n                rolled_FP.m_nrof_texture_templates = 0;\n            };\n\n            vector<float> score;\n            result = One2One_matching_selected_templates(latent_FP,rolled_FP,score);\n            if(result == 1){\n                continue;\n            }\n            else if(result == 2){\n                cout<<\"Comparison failed: rolled template is empty. Skipping.\"<<endl;\n                continue;\n            }\n            float final_score = score[0] + score[1] + score[2] + score[28]*0.3;\n            scores[j] = final_score;\n        }\n        if(result == 1){\n            cout<<\"Matching failed: latent template is empty. Exiting.\"<<endl;\n            return 1;\n        }\n        auto t_end = high_resolution_clock::now();\n        duration<double, std::milli> duration = (t_end - t_start);\n        ofstream output;\n        output.open(score_file);\n\n        // Sort scores to create rank list\n        sort(ind.begin(), ind.end(), [&](const int& a, const int& b){\n                return (scores[a] > scores[b]);\n            }\n        );\n        output<<\"filename,score\"<<endl;\n        //generate correspondence files for top 24 only\n        cout<<\"Match Results\"<<endl;\n        cout<<\"----------------\"<<endl;\n        cout<<\"Rank     Filename      Score\"<<endl;\n        for(j=0; j<24; ++j)\n        {\n            if(j >= nrof_rolled){\n                break;\n            }\n            output<<to_string(j+1)<<rolled_template_files[ind[j]]<<\",\"<<scores[ind[j]]<<endl;\n            RolledFPTemplate rolled_FP;\n            load_FP_template(rolled_template_files[ind[j]].string(), rolled_FP);\n            string latent_fname = latent_template_file.stem().string();\n            string rolled_fname = rolled_template_files[ind[j]].stem().string();\n            string corr_file = \"/LatentAFIS/scores/corr\" + latent_fname + \"_\" + rolled_fname;\n            vector<float> score;\n            One2One_matching_selected_templates(latent_FP,rolled_FP,score, true, corr_file);\n            cout<<to_string(j+1)<<\"        \"<<rolled_template_files[ind[j]].filename()<<\"       \"<<scores[ind[j]]<<endl;\n        }\n        output.close();\n        t[1] = high_resolution_clock::now();\n        time_span = t[1] - t[0];\n        cout<<\"Total matching duration (ms): \"<<time_span.count()<<endl;\n        \n    }\n    return 0;\n}\n\nint Matcher::One2One_matching_all_templates(LatentFPTemplate &latent_template, RolledFPTemplate &rolled_template, vector<float> & score)\n{\n\n    score.resize(latent_template.m_nrof_minu_templates + latent_template.m_nrof_texture_templates);\n    std::fill(score.begin(), score.end(), 0);\n\n   if(latent_template.m_nrof_minu_templates<=0 && latent_template.m_nrof_texture_templates<=0)\n   {\n        return 1;\n    }\n\n    if(rolled_template.m_nrof_minu_templates<=0 && rolled_template.m_nrof_texture_templates<=0)\n    {\n        return 2;\n    }\n    int i,j;\n\n    using namespace std::chrono;\n    vector<high_resolution_clock::time_point> t(10);\n\n    t[0] = high_resolution_clock::now();\n\n    for(i=0;i<latent_template.m_nrof_minu_templates && rolled_template.m_nrof_minu_templates; ++i)\n    {\n        float s = One2One_minutiae_matching(latent_template.m_minu_templates[i], rolled_template.m_minu_templates[0]);\n        score[i] = s;\n    }\n    t[1] = high_resolution_clock::now();\n\n    for(i=0;i<latent_template.m_nrof_texture_templates && rolled_template.m_nrof_texture_templates>0 ; ++i)\n    {\n        float s = One2One_texture_matching(latent_template.m_texture_templates[i], rolled_template.m_texture_templates[0]);\n        score[i+latent_template.m_nrof_minu_templates] = s;\n    }\n\n}\n\nint Matcher::One2One_matching_selected_templates(LatentFPTemplate &latent_template, RolledFPTemplate &rolled_template, vector<float> & score, bool save_corr, string corr_file)\n{\n    score.resize(latent_template.m_nrof_minu_templates + latent_template.m_nrof_texture_templates);\n    std::fill(score.begin(), score.end(), 0);\n    vector<int> selected_ind{27-1, 3-1, 12-1};\n\n\n    if(latent_template.m_nrof_minu_templates<=selected_ind[0] && latent_template.m_nrof_texture_templates<=0)\n    {\n        return 1;\n    }\n\n    if(rolled_template.m_nrof_minu_templates<=0 && rolled_template.m_nrof_texture_templates<=0)\n    {\n        return 2;\n    }\n    int i,j;\n\n    using namespace std::chrono;\n    vector<high_resolution_clock::time_point> t(10);\n\n    t[0] = high_resolution_clock::now();\n\n\n    for(i=0;i<selected_ind.size() && rolled_template.m_nrof_minu_templates>0; ++i)\n    {\n        int ind = selected_ind[i];\n        if(latent_template.m_nrof_minu_templates<=ind)\n            continue;\n        string one_corr_file = corr_file + \"_\" + to_string(i) + \".csv\";\n        float s = One2One_minutiae_matching(latent_template.m_minu_templates[ind], rolled_template.m_minu_templates[0], save_corr, one_corr_file);\n        score[i] = s;\n    }\n    t[1] = high_resolution_clock::now();\n\n    for(i=0;i<min(1,latent_template.m_nrof_texture_templates) && rolled_template.m_nrof_texture_templates>0 ; ++i)\n    {\n        float s = One2One_texture_matching(latent_template.m_texture_templates[i], rolled_template.m_texture_templates[0]);\n        score[i+latent_template.m_nrof_minu_templates] = s;\n    }\n\n}\n\n\nfloat Matcher::One2One_minutiae_matching(MinutiaeTemplate &latent_minu_template, MinutiaeTemplate &rolled_minu_template, bool save_corr, string corr_file)\n{\n    ++nrof_matching;\n    // step 1: compute pairwise similarity between descriptors\n\n    int n_time = 0;\n    register int i,j,k;\n\n    int des_len = rolled_minu_template.m_des_length;\n    if(des_len!=latent_minu_template.m_des_length){\n        cout<<latent_minu_template.m_des_length<<endl;\n\tcout<<rolled_minu_template.m_des_length<<endl;\n\t}\n    assert(des_len == latent_minu_template.m_des_length);\n\n    float simi = 0.0;\n\n    using namespace std::chrono;\n    vector<high_resolution_clock::time_point> t(10);\n\n    Matrix<float, Eigen::Dynamic, Eigen::Dynamic> aa =  Map<Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(latent_minu_template.m_des,latent_minu_template.m_nrof_minu,des_len);\n    Matrix<float, Eigen::Dynamic, Eigen::Dynamic> bb =  Map<Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(rolled_minu_template.m_des,rolled_minu_template.m_nrof_minu,des_len);\n\n    MatrixXf  simi_matrix=aa*bb.transpose();\n\n    for(i=0; i<latent_minu_template.m_nrof_minu; ++i)\n    {\n        for(j = 0; j<rolled_minu_template.m_nrof_minu; ++j)\n        {\n            if(simi_matrix(i,j)<0)\n                simi_matrix(i,j) = 0;\n        }\n    }\n\n    //  step 2:  similarity normalization\n    VectorXf  rolled_simi_sum = simi_matrix.colwise().sum();\n    VectorXf  latent_simi_sum = simi_matrix.rowwise().sum();\n\n    int ind_1, ind_2 ;\n    vector<float> norm_simi_matrix(latent_minu_template.m_nrof_minu*rolled_minu_template.m_nrof_minu);\n    float norm_simi=0.0;\n    for(i=0; i<latent_minu_template.m_nrof_minu; ++i)\n    {\n        ind_1 = i*rolled_minu_template.m_nrof_minu;\n        for(j = 0; j<rolled_minu_template.m_nrof_minu; ++j)\n        {\n            ind_2  = ind_1 + j;\n            norm_simi = simi_matrix(i,j)/(latent_simi_sum(i) + rolled_simi_sum(j) - simi_matrix(i,j)+0.000001); // //simi_matrix[ind_2]*\n            norm_simi_matrix[ind_2] = norm_simi;\n        }\n    }\n    // step 3: find top N correspondences using norm_simi_matrix;\n    // the sorting part can be replaced by a min-heap\n    std::vector<int> y(norm_simi_matrix.size());\n    std::iota(y.begin(), y.end(), 0);\n    auto comparator = [&norm_simi_matrix](int a, int b){ return norm_simi_matrix[a] > norm_simi_matrix[b]; };\n    std::sort(y.begin(), y.end(), comparator);\n\n    std::vector<tuple<float, int, int>>corr;\n    int topN = 120;\n    if(rolled_minu_template.m_nrof_minu*latent_minu_template.m_nrof_minu<topN)\n        topN = rolled_minu_template.m_nrof_minu*latent_minu_template.m_nrof_minu;\n    for(i=0; i<topN ; ++i)\n    {\n        ind_1 = y[i]/rolled_minu_template.m_nrof_minu; // latent minutiae  index\n        ind_2 = y[i] - ind_1*rolled_minu_template.m_nrof_minu; // rolled minutiae index\n        simi = simi_matrix(ind_1,ind_2);\n        corr.push_back(make_tuple(simi,ind_1,ind_2));\n    }\n\n     // step 4: remove false correspondences using two graph matching\n    int d_thr = 30;\n    vector<tuple<float, int, int>> corr2 = LSS_R_Fast2_Dist_eigen(corr, latent_minu_template, rolled_minu_template, d_thr);\n\n\n    vector<tuple<float, int, int>> corr3  = LSS_R_Fast2(corr2, latent_minu_template, rolled_minu_template, d_thr);\n\n    if (save_corr){\n        ofstream output;\n        output.open(corr_file);\n        for(int i = 0; i < corr3.size(); i++){\n            output<<latent_minu_template.m_minutiae[get<1>(corr3[i])].x<<\",\"<<latent_minu_template.m_minutiae[get<1>(corr3[i])].y\n                <<\",\"<<rolled_minu_template.m_minutiae[get<2>(corr3[i])].x<<\",\"<<rolled_minu_template.m_minutiae[get<2>(corr3[i])].y<<endl;\n        }\n        output.close();\n    }\n\n\n    float score = 0.0;\n\n    for(i=0; i<corr3.size(); ++i)\n    {\n        score += get<0>(corr3[i]);\n    }\n    return score;\n\n}\n\nint Matcher::One2One_matching(string latent_file, string rolled_file)\n{\n    LatentFPTemplate latent_template;\n    RolledFPTemplate rolled_template;\n    load_FP_template(latent_file,latent_template);\n    load_FP_template(rolled_file,rolled_template);\n\n    vector<float> score;\n    int ret = One2One_matching_selected_templates(latent_template, rolled_template, score);\n\n    return ret;\n}\n\nfloat Matcher::One2One_texture_matching(LatentTextureTemplate &latent_texture_template, RolledTextureTemplatePQ &rolled_texture_template)\n{\n    ++nrof_matching;\n\n    // step 1: compute pairwise similarity between descriptors\n    int n_time = 0;\n    register int i,j,k;\n\n    int des_len = rolled_texture_template.m_des_length;\n\n   float simi_matrix[MaxNRolledMinu*MaxNLatentMinu];\n   memset(simi_matrix,0,MaxNRolledMinu*MaxNLatentMinu*sizeof(float));\n\n    if(latent_texture_template.m_nrof_minu> MaxNLatentMinu)\n        latent_texture_template.m_nrof_minu = MaxNLatentMinu;\n    if(rolled_texture_template.m_nrof_minu> MaxNRolledMinu)\n        rolled_texture_template.m_nrof_minu = MaxNRolledMinu;\n\n    float simi = 0.0;\n    float *p_latent_des, *p_latent_des0, *p_rolled_des;\n\n    using namespace std::chrono;\n    vector<high_resolution_clock::time_point> t(10);\n\n    t[n_time++] = high_resolution_clock::now();\n    register float dist0=0.0, dist1= 0.0, dist2= 0, dist3=0.0, dist4 = 0.0; //, dist5, dist6,dist7, dist8;\n    register int code1 = 0, code2 = 0, code3 = 0, code4=0;\n    float *p_dist_codewords0 = NULL, *p_dist_codewords1 = NULL, *p_dist_codewords2 =NULL;\n    unsigned char *p_des0=NULL, *p_des1=NULL;\n\n    int n=0;\n    int nrof_clusters3 = nrof_clusters*3, nrof_clusters2 = nrof_clusters*2;\n    int method = 1;\n    if(method == 1)\n    {\n        for(i=0; i<latent_texture_template.m_nrof_minu; ++i)\n        {\n            p_dist_codewords0 = latent_texture_template.m_dist_codewords + i*nrof_subs*nrof_clusters;\n            for(j=0; j<rolled_texture_template.m_nrof_minu; ++j)\n            {\n                dist1 = 6.;\n                dist2 = 0.;\n                dist3 = 0.;\n                dist4 = 0.;\n                p_dist_codewords1 = p_dist_codewords0;\n                p_des0 = rolled_texture_template.m_desPQ + j* rolled_texture_template.m_des_length;\n                for(k=0; k<nrof_subs; k+=4, p_dist_codewords1+=4*nrof_clusters)\n                {\n                    code1 = *(p_des0+k);\n                    dist1 -= *(p_dist_codewords1 + code1);\n\n                    code2 = *(p_des0+k+1);\n                    dist2 -= *(p_dist_codewords1 + code2 + nrof_clusters);\n\n                    code3 = *(p_des0+k+2);\n                    dist3 -= *(p_dist_codewords1 + code3 + nrof_clusters2);\n\n                    code4 = *(p_des0+k+3);\n                    dist4 -= *(p_dist_codewords1 + code4 + nrof_clusters3);\n\n                }\n                simi_matrix[n++] = (dist1+dist2)+ (dist3+dist4);\n            }\n        }\n    }\n    else if (method==2)\n    {\n        int B1=64, B2 = 64;\n        for(i=0; i<latent_texture_template.m_nrof_minu-B1; i+=B1)\n        {\n\n            for(j=0; j<rolled_texture_template.m_nrof_minu-B2; j += B2)\n            {\n\n                for(int ii=i; ii<i+B1; ++ii)\n                {\n                    p_dist_codewords0 = latent_texture_template.m_dist_codewords + ii*nrof_subs*nrof_clusters;\n                    for(int jj=j; jj<j+B2; ++jj)\n                    {\n                       dist1 = 6.;\n                       dist2 = 0.;\n                       dist3 = 0.;\n                       dist4 = 0.;\n                       p_dist_codewords1 = p_dist_codewords0;\n                       p_des0 = rolled_texture_template.m_desPQ + jj* rolled_texture_template.m_des_length;\n\n\n                        for(k=0; k<nrof_subs; k+=4, p_dist_codewords1+=4*nrof_clusters)\n                        {\n                            code1 = *(p_des0+k);\n                            dist1 -= *(p_dist_codewords1 + code1);\n\n                            code2 = *(p_des0+k+1);\n                            dist2 -= *(p_dist_codewords1 + code2 + nrof_clusters);\n\n                            code3 = *(p_des0+k+2);\n                            dist3 -= *(p_dist_codewords1 + code3 + nrof_clusters2);\n\n                            code4 = *(p_des0+k+3);\n                            dist4 -= *(p_dist_codewords1 + code4 + nrof_clusters3);\n\n                        }\n                        simi_matrix[ii*rolled_texture_template.m_nrof_minu+jj] = (dist1+dist2)+ (dist3+dist4);\n                    }\n                }\n            }\n        }\n    }\n    else if(method == 3)\n    {\n         int B1=64, B2 = 64;\n        for(i=0; i<latent_texture_template.m_nrof_minu-B1; i+=B1)\n        {\n            p_dist_codewords0 = latent_texture_template.m_dist_codewords + i*nrof_subs*nrof_clusters;\n            for(j=0; j<rolled_texture_template.m_nrof_minu-B2; j += B2)\n            {\n                p_dist_codewords1 = p_dist_codewords0;\n                p_des0 = rolled_texture_template.m_desPQ + j* rolled_texture_template.m_des_length;\n                for(int ii=i; ii<i+B1; ++ii)\n                {\n                    p_des1 = p_des0;\n                    for(int jj=j; jj<j+B2; ++jj)\n                    {\n                       p_dist_codewords2 = p_dist_codewords1;\n                       dist1 = 6.;\n                       dist2 = 0.;\n                       dist3 = 0.;\n                       dist4 = 0.;\n\n                        for(k=0; k<nrof_subs; k+=4, p_dist_codewords2+=4*nrof_clusters)\n                        {\n                            code1 = *(p_des1+k);\n                            dist1 -= *(p_dist_codewords2 + code1);\n\n                            code2 = *(p_des1+k+1);\n                            dist2 -= *(p_dist_codewords2 + code2 + nrof_clusters);\n\n                            code3 = *(p_des1+k+2);\n                            dist3 -= *(p_dist_codewords2 + code3 + nrof_clusters2);\n\n                            code4 = *(p_des1+k+3);\n                            dist4 -= *(p_dist_codewords2 + code4 + nrof_clusters3);\n\n                        }\n                        simi_matrix[ii*rolled_texture_template.m_nrof_minu+jj] = (dist1+dist2)+ (dist3+dist4);\n                        p_des1 +=  rolled_texture_template.m_des_length;\n                    }\n                    p_dist_codewords1 += nrof_subs*nrof_clusters;\n                }\n            }\n        }\n    }\n    else if(method==4)\n    {\n        unsigned char *p_des3=NULL, *p_des2=NULL;\n        for(i=0; i<latent_texture_template.m_nrof_minu; ++i)\n        {\n            p_dist_codewords0 = latent_texture_template.m_dist_codewords + i*nrof_subs*nrof_clusters;\n            for(k=0; k<nrof_subs; ++k)\n            {\n                for(j=0; j<rolled_texture_template.m_nrof_minu-4; j+=4)\n                {\n                    n = i*rolled_texture_template.m_nrof_minu + j;\n                    p_des0 = rolled_texture_template.m_desPQ + j* rolled_texture_template.m_des_length + k;\n                    p_des1 = p_des0 + rolled_texture_template.m_des_length;\n                    p_des2 = p_des1 + rolled_texture_template.m_des_length;\n                    p_des3 = p_des2 + rolled_texture_template.m_des_length;\n\n                    dist0 -= *(p_dist_codewords0 + *p_des0);\n\n                    dist1 -= *(p_dist_codewords0 + *p_des1);\n\n                    dist2 -= *(p_dist_codewords0 + *p_des2);\n\n                    dist3 -= *(p_dist_codewords0 + *p_des3);\n\n                    simi_matrix[n] += dist0;\n                    simi_matrix[n+1] += dist1;\n                    simi_matrix[n+2] += dist2;\n                    simi_matrix[n+3] += dist3;\n                }\n            }\n        }\n    }\n    t[n_time] = high_resolution_clock::now();\n    duration<double, std::milli> time_span = t[n_time] - t[n_time-1];\n\n    time[n_time-1]+=time_span.count() ;  // minutiae similarity\n    similarity_time += time_span.count() ;\n    n_time++;\n\n//\n    std::vector<tuple<float, int, int>>tmp_corr(latent_texture_template.m_nrof_minu), corr(N);\n    float max_val;\n    float *psimi = simi_matrix;\n    int max_index;\n    for(i=0;i<latent_texture_template.m_nrof_minu; ++i)\n    {\n\n        max_index = std::distance(psimi, std::max_element(psimi, psimi+rolled_texture_template.m_nrof_minu));\n        max_val = *(psimi + max_index);\n        tmp_corr[i] = make_tuple(max_val,i,max_index);\n\n        psimi += rolled_texture_template.m_nrof_minu;\n    }\n    if(tmp_corr.size()>N)\n    {\n        std::vector<int> y(tmp_corr.size());\n        std::iota(y.begin(), y.end(), 0);\n        auto comparator = [&tmp_corr](int a, int b){ return get<0>(tmp_corr[a]) > get<0>(tmp_corr[b]); };\n        std::sort(y.begin(), y.end(), comparator);\n\n        for(i=0;i<N; ++i)\n        {\n            corr[i] = tmp_corr[y[i]];\n        }\n    }\n    else\n        corr = tmp_corr;\n    t[n_time] = high_resolution_clock::now();\n\n    time_span = t[n_time] - t[n_time-1];\n\n    time[n_time-1]+=time_span.count() ;  // obtaining initial correspondences\n    n_time++;\n\n     // step 4: remove false correspondences using two graph matching\n    int d_thr = 30;\n    vector<tuple<float, int, int>> corr2 = LSS_R_Fast2_Dist_lookup(corr, latent_texture_template, rolled_texture_template, d_thr);\n\n\n    t[n_time] = high_resolution_clock::now();\n    time_span = t[n_time] - t[n_time-1];\n    time[n_time-1]+=time_span.count() ;   // second order graph matching: distance\n    n_time++;\n\n    vector<tuple<float, int, int>> corr3  = LSS_R_Fast2(corr2, latent_texture_template, rolled_texture_template, d_thr);\n\n\n    t[n_time] = high_resolution_clock::now();\n    time_span = t[n_time] - t[n_time-1];\n    time[n_time-1]+=time_span.count() ;   // second order graph matching: original\n    n_time++;\n\n    float score = 0.0;\n\n    for(i=0; i<corr3.size(); ++i)\n    {\n        score += get<0>(corr3[i]);\n    }\n    return score;\n\n}\n\nint Matcher::load_FP_template(string tname, LatentFPTemplate & fp_template)\n{\n    fp_template.release();\n    const short Max_Nrof_Minutiae = 2*1000; // including virtual minutiae. We only consider top 1000 minutiae including both real and virtual minutiae for each template.\n    const short Max_Des_Length = 192;\n    const short Max_BlkSize = 100;\n\n    ifstream is;\n    is.open(tname, ifstream::binary);\n    // get length of file:\n    is.seekg(0, ios::end);\n    int length = is.tellg();\n\n    if( length<=0 )\n    {\n        return 1;\n    }\n    is.seekg(0, ios::beg);\n    short header[12];\n    short h,w,blkH,blkW;\n    unsigned char nrof_minu_template,nrof_texture_template;\n    short nrof_minutiae;\n\n\n    short nrof_minutiae_feature;\n    short des_len;\n    int i,j;\n\n    short x[Max_Nrof_Minutiae],y[Max_Nrof_Minutiae];\n    float ori[Max_Nrof_Minutiae];\n    float oimg[Max_BlkSize*Max_BlkSize];\n\n    float des[Max_Nrof_Minutiae*Max_Des_Length];\n\n    for(int i=0; i<12; i++){\n        is.read(reinterpret_cast<char*>(&header[i]),sizeof(short));\n    }\n\n    is.read(reinterpret_cast<char*>(&h),sizeof(short));\n    is.read(reinterpret_cast<char*>(&w),sizeof(short));\n    is.read(reinterpret_cast<char*>(&blkH),sizeof(short));\n    is.read(reinterpret_cast<char*>(&blkW),sizeof(short));\n    is.read(reinterpret_cast<char*>(&nrof_minu_template),sizeof(unsigned char));\n    if(blkH>50)\n        blkH = 50;\n    if(blkW>50)\n        blkW = 50;\n    for(i=0;i<nrof_minu_template; ++i)\n    {\n        is.read(reinterpret_cast<char*>(&nrof_minutiae),sizeof(short));\n        if(nrof_minutiae<=0)\n            continue;\n        if(nrof_minutiae>Max_Nrof_Minutiae)\n        {\n            cout<<\"Number of minutiae is larger than Max Number of Minutiae (latent):\"<< nrof_minutiae << \">\"<<Max_Nrof_Minutiae<<endl;\n            return 2;\n        }\n        if(blkH>Max_BlkSize || blkW>Max_BlkSize)\n        {\n            cout<<\"The size of the ridge flow is larger than maximum size:\"<< Max_BlkSize<<endl;\n            return 4;\n        }\n        is.read(reinterpret_cast<char*>(x),sizeof(short)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(y),sizeof(short)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(ori),sizeof(float)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(&des_len),sizeof(short));\n\n        is.read(reinterpret_cast<char*>(des),sizeof(float)*nrof_minutiae*des_len);\n\n        MinutiaeTemplate minu_template(nrof_minutiae,x,y,ori,des_len,des,blkH, blkW, oimg);\n        fp_template.add_template(minu_template);\n    }\n\n    is.read(reinterpret_cast<char*>(&nrof_texture_template),sizeof(unsigned char));\n\n   for(i=0;i<nrof_texture_template; ++i)\n    {\n        is.read(reinterpret_cast<char*>(&nrof_minutiae),sizeof(short));\n        if(nrof_minutiae<=0)\n            continue;\n        if(nrof_minutiae>Max_Nrof_Minutiae)\n        {\n            cout<<\"Number of minutiae is larger than Max Number of Minutiae:\"<< nrof_minutiae << \">\"<< Max_Nrof_Minutiae<<endl;\n            return -1;\n        }\n        is.read(reinterpret_cast<char*>(x),sizeof(short)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(y),sizeof(short)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(ori),sizeof(float)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(&des_len),sizeof(short));\n        is.read(reinterpret_cast<char*>(des),sizeof(float)*nrof_minutiae*des_len);\n\n\n        LatentTextureTemplate texture_template(nrof_minutiae,x,y,ori,des_len,des);\n        texture_template.compute_dist_to_codewords(codewords, nrof_subs,  sub_dim,  nrof_clusters);\n        fp_template.add_texture_template(texture_template);\n    }\n    is.close();\n\n    return 0;\n};\n\nint Matcher::load_FP_template(string tname, RolledFPTemplate & fp_template)\n{\n    fp_template.release();\n    const short Max_Nrof_Minutiae = 2*1000; // including virtual minutiae. We only consider top 1000 minutiae including both real and virtual minutiae for each template.\n    const short Max_Des_Length = 192;\n    const short Max_BlkSize = 100;\n\n    ifstream is;\n    is.open(tname, ifstream::binary);\n    // get length of file:\n    is.seekg(0, ios::end);\n    int length = is.tellg();\n\n    if( length<=10 )\n    {\n        return 1;\n    }\n    is.seekg(0, ios::beg);\n    short header[12];\n    short h,w,blkH,blkW;\n    unsigned char nrof_minu_template,nrof_texture_template;\n    short nrof_minutiae;\n\n\n    short nrof_minutiae_feature;\n    short des_len=96;\n    int i,j;\n\n    short x[Max_Nrof_Minutiae],y[Max_Nrof_Minutiae];\n    float ori[Max_Nrof_Minutiae];\n    float reliability[Max_Nrof_Minutiae];\n    float oimg[Max_BlkSize*Max_BlkSize];\n\n    float des[Max_Nrof_Minutiae*Max_Des_Length];\n\n    for(int i=0; i<12; i++){\n        is.read(reinterpret_cast<char*>(&header[i]),sizeof(short));\n    }\n    is.read(reinterpret_cast<char*>(&h),sizeof(short));\n    is.read(reinterpret_cast<char*>(&w),sizeof(short));\n    is.read(reinterpret_cast<char*>(&blkH),sizeof(short));\n    is.read(reinterpret_cast<char*>(&blkW),sizeof(short));\n    is.read(reinterpret_cast<char*>(&nrof_minu_template),sizeof(unsigned char));\n    if(blkH>50)\n        blkH = 50;\n    if(blkW>50)\n        blkW = 50;\n    for(i=0;i<nrof_minu_template; ++i)\n    {\n        is.read(reinterpret_cast<char*>(&nrof_minutiae),sizeof(short));\n        if(nrof_minutiae<=0)\n            continue;\n        if(nrof_minutiae>Max_Nrof_Minutiae)\n        {\n            cout<<\"Number of minutiae is larger than Max Number of Minutiae:\"<< nrof_minutiae << \">\"<< Max_Nrof_Minutiae<<endl;\n            return 2;\n        }\n        if(blkH>Max_BlkSize || blkW>Max_BlkSize)\n        {\n            cout<<\"The size of the ridge flow is larger than maximum size:\"<< Max_BlkSize<<endl;\n            return 4;\n        }\n        is.read(reinterpret_cast<char*>(x),sizeof(short)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(y),sizeof(short)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(ori),sizeof(float)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(&des_len),sizeof(short));\n\n        is.read(reinterpret_cast<char*>(des),sizeof(float)*nrof_minutiae*des_len);\n\n        MinutiaeTemplate minu_template(nrof_minutiae,x,y,ori,des_len,des,blkH, blkW, oimg);\n        fp_template.add_template(minu_template);\n    }\n\n    is.read(reinterpret_cast<char*>(&nrof_texture_template),sizeof(unsigned char));\n\n   for(i=0;i<nrof_texture_template; ++i)\n    {\n        is.read(reinterpret_cast<char*>(&nrof_minutiae),sizeof(short));\n        if(nrof_minutiae<=0)\n            continue;\n        if(nrof_minutiae>Max_Nrof_Minutiae)\n        {\n            cout<<\"Number of minutiae is larger than Max Number of Minutiae:\"<< nrof_minutiae << \">\"<< Max_Nrof_Minutiae<<endl;\n            return -1;\n        }\n        is.read(reinterpret_cast<char*>(x),sizeof(short)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(y),sizeof(short)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(ori),sizeof(float)*nrof_minutiae);\n        is.read(reinterpret_cast<char*>(&des_len),sizeof(short));\n        is.read(reinterpret_cast<char*>(des),sizeof(float)*nrof_minutiae*des_len);\n\n        RolledTextureTemplatePQ texture_template(nrof_minutiae,x,y,ori,des_len,des);\n        fp_template.add_texture_template(texture_template);\n    }\n    is.close();\n\n    return 0;\n};\n\nint Matcher::load_single_template(string tname, TextureTemplate& texture_template)\n{\n    ifstream is;\n    is.open(tname, ifstream::binary);\n    // get length of file:\n    is.seekg(0, ios::end);\n    int length = is.tellg();\n\n    if( length<=0 )\n    {\n        cout<<\"template is empty!\"<<endl;\n        return -1;\n    }\n    is.seekg(0, ios::beg);\n    short nrof_minutiae;\n    short nrof_minutiae_feature;\n    short des_len;\n\n    is.read(reinterpret_cast<char*>(&nrof_minutiae),sizeof(short));\n    is.read(reinterpret_cast<char*>(&nrof_minutiae_feature),sizeof(short));\n    is.read(reinterpret_cast<char*>(&des_len),sizeof(short));\n\n    if(nrof_minutiae_feature<3)\n        return -1; // number of minutiae feature is not sufficient.\n    texture_template.initialization(nrof_minutiae,des_len);\n\n    short *loc = new short [nrof_minutiae];\n    is.read(reinterpret_cast<char*>(loc),sizeof(short)*nrof_minutiae);\n    texture_template.set_x(loc);\n\n    is.read(reinterpret_cast<char*>(loc),sizeof(short)*nrof_minutiae);\n    texture_template.set_y(loc);\n\n    delete [] loc; loc = NULL;\n\n    float *feature = new float [nrof_minutiae];\n\n    is.read(reinterpret_cast<char*>(feature),sizeof(float)*nrof_minutiae);\n    texture_template.set_ori(feature);\n\n    for(int i=3; i<nrof_minutiae_feature; ++i)\n    {\n        // read addition features. But they are not useful here\n        is.read(reinterpret_cast<char*>(feature),sizeof(float)*nrof_minutiae);\n    }\n\n    is.read(reinterpret_cast<char*>(texture_template.m_des),sizeof(float)*nrof_minutiae*des_len);\n\n\n    is.close();\n\n    cout<<tname<<endl;\n    return 0;\n};\n\nint Matcher::load_single_PQ_template(string tname, RolledTextureTemplatePQ& minu_template)\n{\n    ifstream is;\n    is.open(tname, ifstream::binary);\n    // get length of file:\n    is.seekg(0, ios::end);\n    int length = is.tellg();\n\n    if( length<=0 )\n    {\n        cout<<\"template is empty!\"<<endl;\n        return -1;\n    }\n    is.seekg(0, ios::beg);\n    short nrof_minutiae;\n    short nrof_minutiae_feature;\n    short des_len;\n\n    is.read(reinterpret_cast<char*>(&nrof_minutiae),sizeof(short));\n    is.read(reinterpret_cast<char*>(&nrof_minutiae_feature),sizeof(short));\n    is.read(reinterpret_cast<char*>(&des_len),sizeof(short));\n\n    if(nrof_minutiae_feature<3)\n        return -1; // number of minutiae feature is not sufficient.\n    minu_template.initialization(nrof_minutiae,des_len);\n\n    short *loc = new short [nrof_minutiae];\n    is.read(reinterpret_cast<char*>(loc),sizeof(short)*nrof_minutiae);\n    minu_template.set_x(loc);\n\n    is.read(reinterpret_cast<char*>(loc),sizeof(short)*nrof_minutiae);\n    minu_template.set_y(loc);\n\n    delete [] loc; loc = NULL;\n\n     float feature[100000];\n     is.read(reinterpret_cast<char*>(feature),sizeof(float)*nrof_minutiae);\n    minu_template.set_ori(feature);\n\n    for(int i=3; i<nrof_minutiae_feature; ++i)\n    {\n        // read addition features. But they are not useful here\n        is.read(reinterpret_cast<char*>(feature),sizeof(float)*nrof_minutiae);\n    }\n\n    is.read(reinterpret_cast<char*>(minu_template.m_desPQ),sizeof(unsigned char)*nrof_minutiae*des_len);\n\n    is.close();\n\n    minu_template.init_des();\n    cout<<tname<<endl;\n    return 0;\n};\n\nMatcher::Matcher(const Matcher& orig)\n{\n\n}\n\nvector<tuple<float, int, int>>  Matcher::LSS_R_Fast2_Dist(vector<tuple<float, int, int>> &corr, SingleTemplate & latent_template, SingleTemplate & rolled_template, float d_thr)\n{\n    int num = corr.size();\n    vector<float> H(num*num);\n\n    vector<short> flag_latent(latent_template.m_nrof_minu),flag_rolled(rolled_template.m_nrof_minu);\n\n    register int i,j,k;\n\n    MinuPoint *p_latent_minutia_1, *p_latent_minutia_2, *p_rolled_minutia_1, *p_rolled_minutia_2;\n    float dist_1, dist_2, dist;\n    float dx_1, dy_1, dx_2, dy_2;\n\n    for(i=0; i<num-1; ++i)\n    {\n        p_latent_minutia_1 = & latent_template.m_minutiae[get<1>(corr[i])];\n        p_rolled_minutia_1 = & rolled_template.m_minutiae[get<2>(corr[i])];\n        for(j=i+1; j<num;++j)\n        {\n            p_latent_minutia_2 = & latent_template.m_minutiae[get<1>(corr[j])];\n            p_rolled_minutia_2 = & rolled_template.m_minutiae[get<2>(corr[j])];\n\n            dx_1 = p_latent_minutia_1->x-p_latent_minutia_2->x;\n            dx_2 = p_rolled_minutia_1->x-p_rolled_minutia_2->x;\n\n            dy_1 = p_latent_minutia_1->y-p_latent_minutia_2->y;\n            dy_2 = p_rolled_minutia_1->y-p_rolled_minutia_2->y;\n\n            dist_1 = (dx_1*dx_1)+(dy_1*dy_1);\n            dist_1 = sqrt(dist_1);\n\n\n            dist_2 = (dx_2*dx_2)+(dy_2*dy_2);\n            dist_2 = sqrt(dist_2);\n\n            dist = fabs(dist_1-dist_2);\n\n            H[i*num+j] = (30-dist)/(25.0);\n            if(H[i*num+j]>1)\n                H[i*num+j] = 1.0;\n            else if(H[i*num+j]<0)\n                H[i*num+j] = 0.0;\n\n            H[j*num+i] = H[i*num+j];\n        }\n    }\n\n    vector<float> S(num),S1(num);\n\n    float s0 = 1.0/num;\n    for(i=0; i<num; ++i)\n        S[i] = get<0>(corr[i]);\n\n\n    float sum = 0.0;\n    for(i=0;i<5 ; ++i)\n    {\n        sum = 0.0;\n        for(j=0;j<num; ++j)\n        {\n            S1[j] = 0;\n            for(k=0; k<num;++k)\n            {\n                //if(H[j*num+k])\n                S1[j] += H[j*num+k]*S[k];\n            }\n            sum += S1[j];\n        }\n        sum = 1.0/(sum+0.0001);\n        for(j=0;j<num; ++j)\n        {\n            S[j] = S1[j]*sum;\n        }\n    }\n\n    // sort the S\n    // the sorting part can be replaced by a min-heap\n    std::vector<int> y(S.size());\n    std::iota(y.begin(), y.end(), 0);\n    auto comparator = [&S](int a, int b){ return S[a] > S[b]; };\n    std::sort(y.begin(), y.end(), comparator);\n\n    vector<tuple<float, int, int>>  new_corr;\n    vector<int>  selected_ind;\n    short ind;\n    for(i=0; i<num; ++i)\n    {\n        ind = y[i];\n        if(S[ind]<0.0001)\n            break;\n        if(flag_latent[get<1>(corr[ind])] == 1 | flag_rolled[get<2>(corr[ind])] == 1)\n            continue;\n\n        if(i==0)\n        {\n            selected_ind.push_back(ind);\n            new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n            flag_latent[get<1>(corr[ind])] = 1;\n            flag_rolled[get<2>(corr[ind])] = 1;\n        }\n        else\n        {\n            int found =0;\n            for(j=0;j<selected_ind.size(); ++j)\n            {\n                if(H[ind*num+selected_ind[j]]<0.00001)\n                {\n                    found = 1;\n                    break;\n                }\n            }\n            if(found==0)\n            {\n                selected_ind.push_back(ind);\n                new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n                flag_latent[get<1>(corr[ind])] = 1;\n                flag_rolled[get<2>(corr[ind])] = 1;\n            }\n        }\n    }\n\n    return new_corr;\n};\n\nvector<tuple<float, int, int>>  Matcher::LSS_R_Fast2_Dist_lookup(vector<tuple<float, int, int>> &corr, SingleTemplate & latent_template, SingleTemplate & rolled_template, float d_thr)\n{\n    int num = corr.size();\n    float *H = new float [num*num]();\n    vector<short> flag_latent(latent_template.m_nrof_minu),flag_rolled(rolled_template.m_nrof_minu);\n\n    register int i,j,k;\n\n    MinuPoint *p_latent_minutia_1, *p_latent_minutia_2, *p_rolled_minutia_1, *p_rolled_minutia_2;\n    float dist_1, dist_2, dist;\n    int  dx_1, dy_1, dx_2, dy_2;\n\n    for(i=0; i<num-1; ++i)\n    {\n        p_latent_minutia_1 = & latent_template.m_minutiae[get<1>(corr[i])];\n        p_rolled_minutia_1 = & rolled_template.m_minutiae[get<2>(corr[i])];\n        for(j=i+1; j<num;++j)\n        {\n            p_latent_minutia_2 = & latent_template.m_minutiae[get<1>(corr[j])];\n            p_rolled_minutia_2 = & rolled_template.m_minutiae[get<2>(corr[j])];\n\n            dx_1 = p_latent_minutia_1->x-p_latent_minutia_2->x;\n            dx_2 = p_rolled_minutia_1->x-p_rolled_minutia_2->x;\n\n            dx_1 = abs(dx_1);\n            dx_2 = abs(dx_2);\n            dy_1 = p_latent_minutia_1->y-p_latent_minutia_2->y;\n            dy_2 = p_rolled_minutia_1->y-p_rolled_minutia_2->y;\n\n            dy_1 = abs(dy_1);\n            dy_2 = abs(dy_2);\n\n            if(dx_1>=dist_N | dx_2>=dist_N | dy_1>=dist_N | dy_2>=dist_N)\n                continue;\n\n            dist_1 = table_dist[dx_1*dist_N+dy_1];\n\n            dist_2 = table_dist[dx_2*dist_N+dy_2];\n\n            dist = fabs(dist_1-dist_2);\n            if(dist>d_thr)\n                continue;\n\n            H[i*num+j] = (30-dist)/(25.0);\n            if(H[i*num+j]>1)\n                H[i*num+j] = 1.0;\n            else if(H[i*num+j]<0)\n                H[i*num+j] = 0.0;\n            H[j*num+i] = H[i*num+j];\n        }\n    }\n\n    Matrix<float, Eigen::Dynamic, Eigen::Dynamic> aa =  Map<Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(H,num,num);\n\n    float sum = 0.0;\n    VectorXf b(num);\n    VectorXf c;\n    for(i=0; i<num; ++i)\n        b(i) = get<0>(corr[i]);\n    for(i=0;i<3 ; ++i)\n    {\n        c = aa*b;\n        sum = c.sum();\n        b = c*(1./(sum+0.00001));\n    }\n\n    vector<float> S(num);\n    for(i=0;i<num; ++i)\n    {\n        S[i] = b(i);\n    }\n\n    // sort S\n    std::vector<int> y(S.size());\n    std::iota(y.begin(), y.end(), 0);\n    auto comparator = [&S](int a, int b){ return S[a] > S[b]; };\n    std::sort(y.begin(), y.end(), comparator);\n\n\n    vector<tuple<float, int, int>>  new_corr;\n    vector<int>  selected_ind;\n    short ind;\n    for(i=0; i<num; ++i)\n    {\n\n        ind = y[i];\n        if(S[ind]<0.0001)\n            break;\n        if(flag_latent[get<1>(corr[ind])] == 1 | flag_rolled[get<2>(corr[ind])] == 1)\n            continue;\n\n        if(i==0)\n        {\n            selected_ind.push_back(ind);\n            new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n            flag_latent[get<1>(corr[ind])] = 1;\n            flag_rolled[get<2>(corr[ind])] = 1;\n        }\n        else\n        {\n            int found = 0;\n            for(j=0;j<selected_ind.size(); ++j)\n            {\n                if(H[ind*num+selected_ind[j]]<0.00001)\n                {\n                    found = 1;\n                    break;\n                }\n            }\n            if(found==0)\n            {\n                selected_ind.push_back(ind);\n                new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n                flag_latent[get<1>(corr[ind])] = 1;\n                flag_rolled[get<2>(corr[ind])] = 1;\n            }\n        }\n    }\n\n    delete [] H; H=NULL;\n    return new_corr;\n};\n\nvector<tuple<float, int, int>>  Matcher::LSS_R_Fast2_Dist_eigen(vector<tuple<float, int, int>> &corr, SingleTemplate & latent_template, SingleTemplate & rolled_template, float d_thr)\n{\n    int num = corr.size();\n    float *H = new float [num*num]();\n\n    vector<short> flag_latent(latent_template.m_nrof_minu),flag_rolled(rolled_template.m_nrof_minu);\n\n    register int i,j,k;\n\n    MinuPoint *p_latent_minutia_1, *p_latent_minutia_2, *p_rolled_minutia_1, *p_rolled_minutia_2;\n    float dist_1, dist_2, dist;\n    float dx_1, dy_1, dx_2, dy_2;\n\n    for(i=0; i<num-1; ++i)\n    {\n        p_latent_minutia_1 = & latent_template.m_minutiae[get<1>(corr[i])];\n        p_rolled_minutia_1 = & rolled_template.m_minutiae[get<2>(corr[i])];\n        for(j=i+1; j<num;++j)\n        {\n            p_latent_minutia_2 = & latent_template.m_minutiae[get<1>(corr[j])];\n            p_rolled_minutia_2 = & rolled_template.m_minutiae[get<2>(corr[j])];\n\n            dx_1 = p_latent_minutia_1->x-p_latent_minutia_2->x;\n            dx_2 = p_rolled_minutia_1->x-p_rolled_minutia_2->x;\n\n\n            dy_1 = p_latent_minutia_1->y-p_latent_minutia_2->y;\n            dy_2 = p_rolled_minutia_1->y-p_rolled_minutia_2->y;\n\n\n            dist_1 = (dx_1*dx_1)+(dy_1*dy_1);\n            dist_1 = sqrt(dist_1);\n\n            dist_2 = (dx_2*dx_2)+(dy_2*dy_2);\n            dist_2 = sqrt(dist_2);\n            dist = fabs(dist_1-dist_2);\n           if(dist>d_thr)\n                continue;\n\n            H[i*num+j] = (30-dist)/(25.0);\n            if(H[i*num+j]>1)\n                H[i*num+j] = 1.0;\n            else if(H[i*num+j]<0)\n                H[i*num+j] = 0.0;\n\n            H[j*num+i] = H[i*num+j];\n        }\n    }\n\n    Matrix<float, Eigen::Dynamic, Eigen::Dynamic> aa =  Map<Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(H,num,num);\n\n    float sum = 0.0;\n    VectorXf b(num);\n    VectorXf c;\n    for(i=0; i<num; ++i)\n        b(i) = get<0>(corr[i]);\n    for(i=0;i<5 ; ++i)\n    {\n        c = aa*b;\n        sum = c.sum();\n        b = c*(1./(sum+0.00001));\n    }\n\n    vector<float> S(num);\n    for(i=0;i<num; ++i)\n    {\n        S[i] = b(i);\n    }\n    // sort the S\n    // the sorting part can be replaced by a min-heap\n    std::vector<int> y(S.size());\n    std::iota(y.begin(), y.end(), 0);\n    auto comparator = [&S](int a, int b){ return S[a] > S[b]; };\n    std::sort(y.begin(), y.end(), comparator);\n\n    vector<tuple<float, int, int>>  new_corr;\n    vector<int>  selected_ind;\n    short ind;\n    for(i=0; i<num; ++i)\n    {\n\n        ind = y[i];\n        if(S[ind]<0.0001)\n            break;\n        if(flag_latent[get<1>(corr[ind])] == 1 | flag_rolled[get<2>(corr[ind])] == 1)\n            continue;\n\n        if(i==0)\n        {\n            selected_ind.push_back(ind);\n            new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n            flag_latent[get<1>(corr[ind])] = 1;\n            flag_rolled[get<2>(corr[ind])] = 1;\n        }\n        else\n        {\n            int found =0;\n            for(j=0;j<selected_ind.size(); ++j)\n            {\n                if(H[ind*num+selected_ind[j]]<0.00001)\n                {\n                    found = 1;\n                    break;\n                }\n            }\n            if(found==0)\n            {\n                selected_ind.push_back(ind);\n                new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n                flag_latent[get<1>(corr[ind])] = 1;\n                flag_rolled[get<2>(corr[ind])] = 1;\n            }\n        }\n    }\n\n     delete [] H; H=NULL;\n    return new_corr;\n};\n\nvector<tuple<float, int, int>>  Matcher::LSS_R_Fast2(vector<tuple<float, int, int>> &corr, SingleTemplate & latent_template, SingleTemplate & rolled_template, int d_thr)\n{\n    int num = corr.size();\n    vector<bool> H(num*num);\n    vector<short> flag_latent(latent_template.m_nrof_minu),flag_rolled(rolled_template.m_nrof_minu);\n\n    register int i,j,k;\n\n    MinuPoint *p_latent_minutia_1, *p_latent_minutia_2, *p_rolled_minutia_1, *p_rolled_minutia_2;\n    float dist_1, dist_2;\n    float angle_1, angle_2, angle_diff;\n    float line_angle_1, line_angle_2;\n    float dx_1,dx_2,dy_1,dy_2;\n\n\n    for(i=0; i<num-1; ++i)\n    {\n        p_latent_minutia_1 = & latent_template.m_minutiae[get<1>(corr[i])];\n        p_rolled_minutia_1 = & rolled_template.m_minutiae[get<2>(corr[i])];\n        for(j=i+1; j<num;++j)\n        {\n            p_latent_minutia_2 = & latent_template.m_minutiae[get<1>(corr[j])];\n            p_rolled_minutia_2 = & rolled_template.m_minutiae[get<2>(corr[j])];\n\n            angle_1 = p_latent_minutia_1->ori-p_latent_minutia_2->ori;\n            angle_1 = adjust_angle(angle_1);\n\n            angle_2 = p_rolled_minutia_1->ori-p_rolled_minutia_2->ori;\n            angle_2 = adjust_angle(angle_2);\n\n            angle_diff = fabs(angle_1 - angle_2);\n\n            if(angle_diff>PI)\n               angle_diff = 2*PI - angle_diff;\n\n\n\n            if(angle_diff>PI/4.)\n                continue;\n\n            dx_1 = p_latent_minutia_1->x-p_latent_minutia_2->x;\n            dy_1 = p_latent_minutia_1->y-p_latent_minutia_2->y;\n\n\n\n            line_angle_1 = -atan2(dy_1,dx_1);\n            angle_1 = p_latent_minutia_1->ori - line_angle_1;\n            angle_1 = adjust_angle(angle_1);\n\n\n            dx_2 = p_rolled_minutia_1->x-p_rolled_minutia_2->x;\n            dy_2 = p_rolled_minutia_1->y-p_rolled_minutia_2->y;\n\n            line_angle_2 = -atan2(dy_2,dx_2);\n            angle_2 = p_rolled_minutia_1->ori - line_angle_2;\n            angle_2 = adjust_angle(angle_2);\n\n            angle_diff = fabs(angle_1 - angle_2);\n\n            if(angle_diff>PI)\n               angle_diff = 2*PI - angle_diff;\n            if(angle_diff>PI/6.)\n                continue;\n\n\n\n            angle_1 = p_latent_minutia_2->ori - line_angle_1;\n            angle_1 = adjust_angle(angle_1);\n\n\n            angle_2 = p_rolled_minutia_2->ori - line_angle_2;\n            angle_2 = adjust_angle(angle_2);\n\n            angle_diff = fabs(angle_1 - angle_2);\n\n            if(angle_diff>PI)\n               angle_diff = 2*PI - angle_diff;\n            if(angle_diff>PI/6.)\n                continue;\n\n            H[i*num+j] = true;\n            H[j*num+i] = true;\n        }\n    }\n\n    vector<float> S(num),S1(num);\n\n    float s0 = 1.0/num;\n    for(i=0; i<num; ++i)\n        S[i] = s0;\n\n    float sum = 0.0;\n    for(i=0;i<5 ; ++i)\n    {\n        sum = 0.0;\n        for(j=0;j<num; ++j)\n        {\n            S1[j] = 0;\n            for(k=0; k<num;++k)\n            {\n                if(H[j*num+k])\n                   S1[j] += S[k];\n            }\n            sum += S1[j];\n        }\n        sum = 1.0/(sum+0.00001);\n        for(j=0;j<num; ++j)\n        {\n            S[j] = S1[j]*sum;\n        }\n    }\n\n    s0 = 0.0;\n\n    // sort the S\n    // the sorting part can be replaced by a min-heap\n    std::vector<int> y(S.size());\n    std::iota(y.begin(), y.end(), 0);\n    auto comparator = [&S](int a, int b){ return S[a] > S[b]; };\n    std::sort(y.begin(), y.end(), comparator);\n\n\n    vector<tuple<float, int, int>>  new_corr;\n    vector<int> selected_ind;\n    short ind;\n    for(i=0; i<num; ++i)\n    {\n        ind = y[i];\n        if(S[ind]<0.001)\n            break;\n        if(flag_latent[get<1>(corr[ind])] == 1 | flag_rolled[get<2>(corr[ind])] == 1)\n            continue;\n\n          if(i==0)\n        {\n            selected_ind.push_back(ind);\n            new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n            flag_latent[get<1>(corr[ind])] = 1;\n            flag_rolled[get<2>(corr[ind])] = 1;\n        }\n        else\n        {\n            int found =0;\n            for(j=0;j<selected_ind.size(); ++j)\n            {\n                if(!H[ind*num+selected_ind[j]])\n                {\n                    found = 1;\n                    break;\n                }\n            }\n            if(found==0)\n            {\n                selected_ind.push_back(ind);\n                new_corr.push_back(make_tuple(get<0>(corr[ind]),get<1>(corr[ind]),get<2>(corr[ind])));\n\n                flag_latent[get<1>(corr[ind])] = 1;\n                flag_rolled[get<2>(corr[ind])] = 1;\n            }\n\n        }\n    }\n\n    return new_corr;\n};\n\nfloat Matcher::adjust_angle(float angle)\n{\n    if(angle>PI)\n        angle -= 2*PI;\n    else if (angle<-PI)\n    {\n        angle += 2*PI;\n    }\n    return angle;\n}\n\nMatcher::~Matcher()\n{\n    if(codewords!=NULL)\n    {\n        delete [] codewords;\n        codewords = NULL;\n    }\n}\n}\n", "meta": {"hexsha": "a78149de310b436155aed303572a881177c11e14", "size": 53771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matching/matcher.cpp", "max_stars_repo_name": "Lupphes/MSU-LatentAFIS", "max_stars_repo_head_hexsha": "1ca5f027c4d6df7b60b975354c3456e315fdd1cd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T02:46:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T20:51:33.000Z", "max_issues_repo_path": "matching/matcher.cpp", "max_issues_repo_name": "Lupphes/MSU-LatentAFIS", "max_issues_repo_head_hexsha": "1ca5f027c4d6df7b60b975354c3456e315fdd1cd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-05-04T09:38:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-05T09:55:22.000Z", "max_forks_repo_path": "matching/matcher.cpp", "max_forks_repo_name": "Lupphes/MSU-LatentAFIS", "max_forks_repo_head_hexsha": "1ca5f027c4d6df7b60b975354c3456e315fdd1cd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2019-06-06T13:36:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T16:54:23.000Z", "avg_line_length": 32.4312424608, "max_line_length": 193, "alphanum_fraction": 0.5825630916, "num_tokens": 14998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.4144783517069335}}
{"text": "#include \"../interface/BTagWeight2011.h\"\n#include \"../interface/GlobalVariables.h\"\n\n#include <functional>\n#include <numeric>\n#include <boost/scoped_ptr.hpp>\n#include <boost/array.hpp>\n\nnamespace BAT {\n\nstd::vector<double> BjetWeights2011(const JetCollection jets, unsigned int numberOfBtags) {\n\tboost::scoped_ptr<BTagWeight2011> btagwWeight(new BTagWeight2011());\n\t//get b-jets\n\tconst JetCollection bjets(btagwWeight->getBJets(jets));\n\t//get c-jets\n\tconst JetCollection cjets(btagwWeight->getCJets(jets));\n\t//get udsg jets\n\tconst JetCollection udsgjets(btagwWeight->getUDSGJets(jets));\n\n\t//get mean scale factors\n\tdouble SF_b = btagwWeight->getAverageBScaleFactor(bjets);\n\tdouble SF_c = btagwWeight->getAverageCScaleFactor(cjets);\n\tdouble SF_udsg = btagwWeight->getAverageUDSGScaleFactor(udsgjets);\n\t//get mean efficiencies\n\tdouble mean_bJetEfficiency = btagwWeight->getAverageBEfficiency();\n\tdouble mean_cJetEfficiency = btagwWeight->getAverageCEfficiency();\n\tdouble mean_udsgJetEfficiency = btagwWeight->getAverageUDSGEfficiency(udsgjets);\n\n\tstd::vector<double> event_weights;\n\tfor (unsigned int nTag = 0; nTag <= numberOfBtags; ++nTag) { // >= 4 is our last b-tag bin!\n\t\tbtagwWeight->setNumberOfBtags(nTag, 20);\n\t\tdouble event_weight = btagwWeight->weight(bjets.size(), cjets.size(), udsgjets.size(), mean_bJetEfficiency,\n\t\t\t\tmean_cJetEfficiency, mean_udsgJetEfficiency, SF_b, SF_c, SF_udsg, numberOfBtags);\n\t\tevent_weights.push_back(event_weight);\n\t}\n\t//all weights are inclusive. To get the weight for exclusive N b-tags ones has to subtract:\n\tfor (unsigned int nTag = 0; nTag < numberOfBtags; ++nTag) {\n\t\t// w(N b-tags) = w(>= N) - w(>= N+1)\n\t\tevent_weights.at(nTag) = event_weights.at(nTag) - event_weights.at(nTag + 1);\n\t\t//last weight, >= numberOfBjets jets, stays inclusive\n\t}\n\treturn event_weights;\n}\n\nunsigned int fact2011(unsigned int n) {\n\tif (n < 1)\n\t\treturn 1;\n\tunsigned int r = 1;\n\tfor (unsigned int i = n; i > 1; i--)\n\t\tr *= i;\n\n\treturn r;\n}\n\nunsigned int comb2011(unsigned int n, unsigned int k) {\n\treturn fact2011(n) / fact2011(k) / fact2011(n - k);\n}\n\nBTagWeight2011::BTagWeight2011() :\n\t\tminNumberOfTags_(0), //\n\t\tmaxNumberOfTags_(0) {\n\n}\n\nbool BTagWeight2011::filter(unsigned int numberOfTags) const {\n\treturn (numberOfTags >= minNumberOfTags_ && numberOfTags <= maxNumberOfTags_);\n}\n\ndouble BTagWeight2011::weight(unsigned int numberOf_b_Jets, unsigned int numberOf_c_Jets, unsigned int numberOf_udsg_Jets,\n\t\tdouble mean_bJetEfficiency, double mean_cJetEfficiency, double mean_udsgJetEfficiency, double scaleFactor_b,\n\t\tdouble scaleFactor_c, double scaleFactor_udsg, unsigned int numberOfTags) const {\n\tif (!filter(numberOfTags)) {\n\t\treturn 0;\n\t}\n\n\tdouble probabilityMC = 0;\n\tdouble probabilityData = 0;\n\tfor (unsigned int b_index = 0; b_index <= numberOf_b_Jets; ++b_index)\n\t\tfor (unsigned int c_index = 0; c_index <= numberOf_c_Jets; ++c_index)\n\t\t\tfor (unsigned int udsg_index = 0; udsg_index <= numberOf_udsg_Jets; ++udsg_index) {\n\t\t\t\tunsigned int t = b_index + c_index + udsg_index;\n\t\t\t\tif (!filter(t))\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// how many equivalent ways\n\t\t\t\tunsigned int totalCombinations = comb2011(numberOf_b_Jets, b_index) * comb2011(numberOf_c_Jets, c_index)\n\t\t\t\t\t\t* comb2011(numberOf_udsg_Jets, udsg_index);\n\n\t\t\t\tprobabilityMC += 1. * totalCombinations * pow(mean_bJetEfficiency, b_index)\n\t\t\t\t\t\t* pow(1. - mean_bJetEfficiency, numberOf_b_Jets - b_index) * pow(mean_cJetEfficiency, c_index)\n\t\t\t\t\t\t* pow(1. - mean_cJetEfficiency, numberOf_c_Jets - c_index)\n\t\t\t\t\t\t* pow(mean_udsgJetEfficiency, udsg_index)\n\t\t\t\t\t\t* pow(1. - mean_udsgJetEfficiency, numberOf_udsg_Jets - udsg_index);\n\n\t\t\t\tprobabilityData += 1. * totalCombinations * pow(mean_bJetEfficiency * scaleFactor_b, b_index)\n\t\t\t\t\t\t* pow(1. - mean_bJetEfficiency * scaleFactor_b, numberOf_b_Jets - b_index)\n\t\t\t\t\t\t* pow(mean_cJetEfficiency * scaleFactor_c, c_index)\n\t\t\t\t\t\t* pow(1. - mean_cJetEfficiency * scaleFactor_c, numberOf_c_Jets - c_index)\n\t\t\t\t\t\t* pow(mean_udsgJetEfficiency * scaleFactor_udsg, udsg_index)\n\t\t\t\t\t\t* pow(1. - mean_udsgJetEfficiency * scaleFactor_udsg, numberOf_udsg_Jets - udsg_index);\n\t\t\t}\n\tif (probabilityMC == 0)\n\t\treturn 0;\n\treturn probabilityData / probabilityMC;\n}\n\nstd::vector<double> BTagWeight2011::weights(unsigned int numberOf_b_Jets, unsigned int numberOf_c_Jets,\n\t\tunsigned int numberOf_udsg_Jets, double mean_bJetEfficiency, double mean_cJetEfficiency,\n\t\tdouble mean_udsgJetEfficiency, double scaleFactor_b, double scaleFactor_c, double scaleFactor_udsg,\n\t\tunsigned int numberOfTags) const {\n\n\tstd::vector<double> event_weights;\n\tfor (unsigned index = 0; index <= numberOf_b_Jets + numberOf_c_Jets + numberOf_udsg_Jets; ++index) {\n\t\tevent_weights.push_back(0);\n\t}\n\tif (!filter(numberOfTags)) {\n\t\treturn event_weights;\n\t}\n\n\tfor (unsigned int b_index = 0; b_index <= numberOf_b_Jets; ++b_index)\n\t\tfor (unsigned int c_index = 0; c_index <= numberOf_c_Jets; ++c_index)\n\t\t\tfor (unsigned int udsg_index = 0; udsg_index <= numberOf_udsg_Jets; ++udsg_index) {\n\t\t\t\tunsigned int t = b_index + c_index + udsg_index;\n//\t\t\t\tif (!filter(t))\n//\t\t\t\t\tcontinue;\n\t\t\t\tdouble probabilityMC = 0;\n\t\t\t\tdouble probabilityData = 0;\n\t\t\t\t// how many equivalent ways\n//\t\t\t\tunsigned int totalCombinations = comb2011(numberOf_b_Jets, b_index) * comb2011(numberOf_c_Jets, c_index)\n//\t\t\t\t\t\t* comb2011(numberOf_udsg_Jets, udsg_index);\n\n\t\t\t\tprobabilityMC = pow(mean_bJetEfficiency, b_index)\n\t\t\t\t\t\t* pow(1. - mean_bJetEfficiency, numberOf_b_Jets - b_index) * pow(mean_cJetEfficiency, c_index)\n\t\t\t\t\t\t* pow(1. - mean_cJetEfficiency, numberOf_c_Jets - c_index)\n\t\t\t\t\t\t* pow(mean_udsgJetEfficiency, udsg_index)\n\t\t\t\t\t\t* pow(1. - mean_udsgJetEfficiency, numberOf_udsg_Jets - udsg_index);\n\n\t\t\t\tprobabilityData = pow(mean_bJetEfficiency * scaleFactor_b, b_index)\n\t\t\t\t\t\t* pow(1. - mean_bJetEfficiency * scaleFactor_b, numberOf_b_Jets - b_index)\n\t\t\t\t\t\t* pow(mean_cJetEfficiency * scaleFactor_c, c_index)\n\t\t\t\t\t\t* pow(1. - mean_cJetEfficiency * scaleFactor_c, numberOf_c_Jets - c_index)\n\t\t\t\t\t\t* pow(mean_udsgJetEfficiency * scaleFactor_udsg, udsg_index)\n\t\t\t\t\t\t* pow(1. - mean_udsgJetEfficiency * scaleFactor_udsg, numberOf_udsg_Jets - udsg_index);\n\n\t\t\t\tif (probabilityMC == 0)\n\t\t\t\t\tevent_weights.at(t) = 0;\n\t\t\t\telse\n\t\t\t\t\tevent_weights.at(t) = probabilityData / probabilityMC;\n\t\t\t}\n\treturn event_weights;\n}\n\nstd::vector<double> BTagWeight2011::weights(double averageScaleFactor, unsigned int numberOfTags) const {\n\tstd::vector<double> event_weights;\n\tfor (unsigned int i = 0; i < numberOfTags + 1; ++i)\n\t\tevent_weights.push_back(0);\n\tevent_weights.at(0) = pow(1 - averageScaleFactor, numberOfTags);\n\n\tif (numberOfTags > 0) {\n\t\tfor (unsigned int i = 1; i <= numberOfTags; ++i) {\n\t\t\tdouble prod = 1;\n\t\t\tfor (unsigned int j = 1; j <= numberOfTags; ++j) {\n\t\t\t\tif (j != i)\n\t\t\t\t\tprod *= 1 - averageScaleFactor;\n\t\t\t}\n\t\t\tevent_weights.at(1) += averageScaleFactor * prod;\n\t\t}\n\t}\n\n\tif (numberOfTags > 1) {\n\t\tfor (unsigned int i = 1; i <= numberOfTags; ++i) {\n\t\t\tdouble sum(0);\n\t\t\tfor (unsigned int j = 1; j <= numberOfTags; ++j) {\n\t\t\t\tif (j == i)\n\t\t\t\t\tcontinue;\n\t\t\t\tdouble prod(1);\n\t\t\t\tfor (unsigned int k = 1; k <= numberOfTags; ++k) {\n\t\t\t\t\tif (k != i && k != j)\n\t\t\t\t\t\tprod *= 1 - averageScaleFactor;\n\t\t\t\t}\n\t\t\t\tsum += averageScaleFactor * prod;\n\t\t\t}\n\t\t\tevent_weights.at(2) += averageScaleFactor * sum;\n\t\t}\n\t\tevent_weights.at(2) = event_weights.at(2) / 2;\n\t}\n\treturn event_weights;\n}\n\nJetCollection BTagWeight2011::getBJets(const JetCollection jets) const {\n\tJetCollection bjets;\n\tfor (unsigned int index = 0; index < jets.size(); ++index) {\n\t\tif (abs(jets.at(index)->partonFlavour()) == 5) //b-quark\n\t\t\tbjets.push_back(jets.at(index));\n\t}\n\treturn bjets;\n}\n\nJetCollection BTagWeight2011::getCJets(const JetCollection jets) const {\n\tJetCollection cjets;\n\tfor (unsigned int index = 0; index < jets.size(); ++index) {\n\t\tif (abs(jets.at(index)->partonFlavour()) == 4) //c-quark\n\t\t\tcjets.push_back(jets.at(index));\n\t}\n\treturn cjets;\n}\n\nJetCollection BTagWeight2011::getUDSGJets(const JetCollection jets) const {\n\tJetCollection udsgjets;\n\tfor (unsigned int index = 0; index < jets.size(); ++index) {\n\t\tif (abs(jets.at(index)->partonFlavour()) != 4 && abs(jets.at(index)->partonFlavour()) != 5) //not a c- or b-quark\n\t\t\tudsgjets.push_back(jets.at(index));\n\t}\n\treturn udsgjets;\n}\n\ndouble BTagWeight2011::getAverageBScaleFactor(const JetCollection jets, double uncertaintyFactor) const {\n\tstd::vector<double> scaleFactors;\n\n\tfor (unsigned int index = 0; index < jets.size(); ++index) {\n\t\tconst JetPointer jet(jets.at(index));\n\t\tscaleFactors.push_back(getBScaleFactor(jet, uncertaintyFactor));\n\t}\n\tdouble sumOfScaleFactors = std::accumulate(scaleFactors.begin(), scaleFactors.end(), 0.0);\n\tif (scaleFactors.size() == 0)\n\t\treturn 1.;\n\telse\n\t\treturn sumOfScaleFactors / scaleFactors.size();\n}\n\ndouble BTagWeight2011::getBScaleFactor(const JetPointer jet, double uncertaintyFactor) const {\n\tconst boost::array<double, 14> SFb_error = { { 0.0295675, 0.0295095, 0.0210867, 0.0219349, 0.0227033, 0.0204062,\n\t\t\t0.0185857, 0.0256242, 0.0383341, 0.0409675, 0.0420284, 0.0541299, 0.0578761, 0.0655432 } };\n\n\tconst boost::array<double, 14> ptbins = { { 30, 40, 50, 60, 70, 80, 100, 120, 160, 210, 260, 320, 400, 500 } };\n\n\tdouble SFb(0);\n\tdouble sf_error(0);\n\t//these numbers are for CSVM only\n\tdouble pt = jet->pt();\n\tif (pt < 30) {\n\t\tSFb = 0.6981 * (1. + 0.414063 * 30) / (1. + 0.300155 * 30);\n\t\tsf_error = 0.12;\n\t} else if (pt > 670) {\n\t\tSFb = 0.6981 * (1. + 0.414063 * 670) / (1. + 0.300155 * 670);\n\t\t//use twice the uncertainty\n\t\tsf_error = 2 * SFb_error[SFb_error.size() - 1];\n\t} else {\n\t\tSFb = 0.6981 * (1. + 0.414063 * pt) / (1. + 0.300155 * pt);\n\t\tunsigned int ptbin(0);\n\t\tfor (unsigned int bin = 0; bin < ptbins.size() + 1; ++bin) {\n\t\t\tdouble upperCut = bin + 1 < ptbins.size() ? ptbins.at(bin + 1) : 670.;\n\t\t\tdouble lowerCut = ptbins.at(bin);\n\n\t\t\tif (pt > lowerCut && pt <= upperCut) {\n\t\t\t\tptbin = bin;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tsf_error = SFb_error.at(ptbin);\n\t}\n\tSFb += sf_error * Globals::BJetSystematic * uncertaintyFactor;\n\treturn SFb;\n}\n\ndouble BTagWeight2011::getAverageCScaleFactor(const JetCollection jets) const {\n\treturn getAverageBScaleFactor(jets, 2.0); //SF_c = SF_b with twice the uncertainty\n}\n\ndouble BTagWeight2011::getCScaleFactor(const JetPointer jet) const {\n\treturn getBScaleFactor(jet, 2.0);\n}\n\ndouble BTagWeight2011::getAverageUDSGScaleFactor(const JetCollection jets) const {\n\tstd::vector<double> scaleFactors;\n\n\tfor (unsigned int index = 0; index < jets.size(); ++index) {\n\t\tconst JetPointer jet(jets.at(index));\n\t\tscaleFactors.push_back(getUDSGScaleFactor(jet));\n\t}\n\tdouble sumOfScaleFactors = std::accumulate(scaleFactors.begin(), scaleFactors.end(), 0.0);\n\tif (scaleFactors.size() == 0)\n\t\treturn 1.;\n\telse\n\t\treturn sumOfScaleFactors / scaleFactors.size();\n}\n\ndouble BTagWeight2011::getUDSGScaleFactor(const JetPointer jet) const {\n\tdouble pt = jet->pt();\n\tdouble SF_udsg_mean(0), SF_udsg_min(0), SF_udsg_max(0);\n\n\tif (pt < 20) {\n\t\treturn 0;\n\t} else if (pt > 670) {\n\t\tSF_udsg_mean = getMeanUDSGScaleFactor(670.);\n\t\tSF_udsg_min = getMinUDSGScaleFactor(670);\n\t\tSF_udsg_max = getMaxUDSGScaleFactor(670);\n\t\t//use twice the uncertainty\n\t\tSF_udsg_min -= (SF_udsg_mean - SF_udsg_min);\n\t\tSF_udsg_max += (SF_udsg_max - SF_udsg_mean);\n\t} else {\n\t\tSF_udsg_mean = getMeanUDSGScaleFactor(pt);\n\t\tSF_udsg_min = getMinUDSGScaleFactor(pt);\n\t\tSF_udsg_max = getMaxUDSGScaleFactor(pt);\n\t}\n\tif (Globals::LightJetSystematic == -1)\n\t\treturn SF_udsg_min;\n\telse if (Globals::LightJetSystematic == 1)\n\t\treturn SF_udsg_max;\n\n\treturn SF_udsg_mean;\n}\n\ndouble BTagWeight2011::getMeanUDSGScaleFactor(double jetPT) const {\n\treturn 1.04318 + 0.000848162 * jetPT - 2.5795e-06 * pow(jetPT, 2) + 1.64156e-09 * pow(jetPT, 3);\n}\n\ndouble BTagWeight2011::getMinUDSGScaleFactor(double jetPT) const {\n\treturn 0.962627 + 0.000448344 * jetPT - 1.25579e-06 * pow(jetPT, 2) + 4.82283e-10 * pow(jetPT, 3);\n}\n\ndouble BTagWeight2011::getMaxUDSGScaleFactor(double jetPT) const {\n\treturn 1.12368 + 0.00124806 * jetPT - 3.9032e-06 * pow(jetPT, 2) + 2.80083e-09 * pow(jetPT, 3);\n}\n\ndouble BTagWeight2011::getAverageBEfficiency() const {\n\tdouble discriminator_cut = 0.679; //== CSVM\n\treturn -1.73338329789 * pow(discriminator_cut, 4) + 1.26161794785 * pow(discriminator_cut, 3)\n\t\t\t+ 0.784721653518 * pow(discriminator_cut, 2) + -1.03328577451 * discriminator_cut + 1.04305075822;\n\n}\n\ndouble BTagWeight2011::getAverageCEfficiency() const {\n\tdouble discriminator_cut = 0.679; //== CSVM\n\treturn -1.5734604211 * pow(discriminator_cut, 4) + 1.52798999269 * pow(discriminator_cut, 3)\n\t\t\t+ 0.866697059943 * pow(discriminator_cut, 2) + -1.66657942274 * discriminator_cut + 0.780639301724;\n\n}\n\ndouble BTagWeight2011::getAverageUDSGEfficiency(const JetCollection jets) const {\n\tstd::vector<double> efficiencies;\n\n\tfor (unsigned int index = 0; index < jets.size(); ++index) {\n\t\tconst JetPointer jet(jets.at(index));\n\t\tdouble efficiency(0);\n\t\t//these numbers are for CSVM only\n\t\tdouble pt = jet->pt();\n\t\tif (pt < 20) {\n\t\t\tcontinue;\n\t\t} else if (pt > 670) {\n\t\t\tefficiency = getMeanUDSGEfficiency(670.);\n\t\t} else {\n\t\t\tefficiency = getMeanUDSGEfficiency(pt);\n\t\t}\n\t\tefficiencies.push_back(efficiency);\n\t}\n\tdouble sumOfEfficiencies = std::accumulate(efficiencies.begin(), efficiencies.end(), 0.0);\n\tif (efficiencies.size() == 0)\n\t\treturn 1.;\n\telse\n\t\treturn sumOfEfficiencies / efficiencies.size();\n}\n\ndouble BTagWeight2011::getMeanUDSGEfficiency(double jetPT) const {\n\treturn 0.0113428 + 5.18983e-05 * jetPT - 2.59881e-08 * pow(jetPT, 2);\n}\n\nvoid BTagWeight2011::setNumberOfBtags(unsigned int min, unsigned int max) {\n\tminNumberOfTags_ = min;\n\tmaxNumberOfTags_ = max;\n\n}\n\n}\n", "meta": {"hexsha": "2e7b93880e4ddc4bcbe4e55ca846feb58d837e02", "size": 13573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BTagWeight2011.cpp", "max_stars_repo_name": "jjacob/AnalysisSoftware", "max_stars_repo_head_hexsha": "670513bcde9c3df46077f906246e912627ee251a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BTagWeight2011.cpp", "max_issues_repo_name": "jjacob/AnalysisSoftware", "max_issues_repo_head_hexsha": "670513bcde9c3df46077f906246e912627ee251a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BTagWeight2011.cpp", "max_forks_repo_name": "jjacob/AnalysisSoftware", "max_forks_repo_head_hexsha": "670513bcde9c3df46077f906246e912627ee251a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1946666667, "max_line_length": 122, "alphanum_fraction": 0.7123701466, "num_tokens": 4256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4144783517069334}}
{"text": "/*\n *  Copyright 2007-2015 The OpenMx Project\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *       http://www.apache.org/licenses/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n */\n\n\n/***********************************************************\n*\n*  omxStateSpaceExpectation.c\n*\n*  Created: Michael D. Hunter \tDate: 2012-10-28 20:07:36\n*\n*  Contains code to calculate the objective function for a\n*   state space model.  Currently, this is done with a \n*   Kalman filter in separate Predict and Update steps.\n*   Later this could be done with one of several Kalman \n*   filter-smoothers (a forward-backward algorithm).\n*\n**********************************************************/\n\n#include \"omxExpectation.h\"\n#include \"omxBLAS.h\"\n#include \"omxFIMLFitFunction.h\"\n#include \"omxStateSpaceExpectation.h\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/LU>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <iostream>\n\n\nvoid omxCallStateSpaceExpectation(omxExpectation* ox, const char *, const char *) {\n    if(OMX_DEBUG) { mxLog(\"State Space Expectation Called.\"); }\n\tomxStateSpaceExpectation* ose = (omxStateSpaceExpectation*)(ox->argStruct);\n\t\n\tomxRecompute(ose->A, NULL);\n\tomxRecompute(ose->B, NULL);\n\tomxRecompute(ose->C, NULL);\n\tomxRecompute(ose->D, NULL);\n\tomxRecompute(ose->Q, NULL);\n\tomxRecompute(ose->R, NULL);\n\t\n\t// Probably should loop through all the data here!!!\n\tif(ose->t == NULL){\n\t\tomxKalmanPredict(ose);\n\t} else {\n\t\tomxKalmanBucyPredict(ose);\n\t}\n\tomxKalmanUpdate(ose);\n}\n\n\n\nvoid omxDestroyStateSpaceExpectation(omxExpectation* ox) {\n\t\n\tif(OMX_DEBUG) { mxLog(\"Destroying State Space Expectation.\"); }\n\t\n\tomxStateSpaceExpectation* argStruct = (omxStateSpaceExpectation*)(ox->argStruct);\n\t\n\tomxFreeMatrix(argStruct->r);\n\tomxFreeMatrix(argStruct->s);\n\tomxFreeMatrix(argStruct->z);\n\tomxFreeMatrix(argStruct->x);\n\tomxFreeMatrix(argStruct->y);\n\tomxFreeMatrix(argStruct->K);\n\tomxFreeMatrix(argStruct->P);\n\tomxFreeMatrix(argStruct->S);\n\tomxFreeMatrix(argStruct->Y);\n\tomxFreeMatrix(argStruct->Z);\n\tomxFreeMatrix(argStruct->det);\n\tomxFreeMatrix(argStruct->covInfo);\n\tomxFreeMatrix(argStruct->cov);\n\tomxFreeMatrix(argStruct->means);\n\tomxFreeMatrix(argStruct->smallC);\n\tomxFreeMatrix(argStruct->smallD);\n\tomxFreeMatrix(argStruct->smallR);\n\tomxFreeMatrix(argStruct->smallr);\n\tomxFreeMatrix(argStruct->smallK);\n\tomxFreeMatrix(argStruct->smallS);\n\tomxFreeMatrix(argStruct->smallY);\n\t\n\tdelete argStruct;\n\t\n}\n\n\nvoid omxPopulateSSMAttributes(omxExpectation *ox, SEXP algebra) {\n\tif(OMX_DEBUG) { mxLog(\"Populating State Space Attributes.  Currently this does very little!\"); }\n\t\n\t/* Initialize */\n\tomxSetExpectationComponent(ox, NULL, \"Reset\", NULL); //maybe shoulde be on ose?  after next line?\n\tomxStateSpaceExpectation* ose = (omxStateSpaceExpectation*)(ox->argStruct);\n\t\n\tif( !(ose->returnScores) ){\n\t\tif(OMX_DEBUG) { mxLog(\"Not asking for attributes, this is being skipped!\"); }\n\t\treturn;\n\t}\n\t\n\tSEXP xpred, ypred, ppred, spred, xupda, pupda, xsmoo, psmoo;\n\t// yupda, supda\n\t\n\tomxRecompute(ose->A, NULL);\n\tomxRecompute(ose->B, NULL);\n\tomxRecompute(ose->C, NULL);\n\tomxRecompute(ose->D, NULL);\n\tomxRecompute(ose->Q, NULL);\n\tomxRecompute(ose->R, NULL);\n\t\n\t\n\t// allocate matrices to be returned\n\tif(OMX_DEBUG_ALGEBRA) { mxLog(\"Allocating initial population matrices ...\"); }\n\tint nx = ose->C->cols;\n\tint ny = ose->C->rows;\n\tif(OMX_DEBUG_ALGEBRA) { mxLog(\"Find number of rows of data ...\"); }\n\t//int nt = ox->data->dataMat->rows;\n\tint nt = ox->data->numObs;\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... numObs:\\n\" << nt << std::endl; }\n\tif(OMX_DEBUG_ALGEBRA) { mxLog(\"Done Finding rows of data ...\"); }\n\tint np = ((nx+1)*nx)/2;\n\tint ns = ((ny+1)*ny)/2;\n\tRf_protect(xpred = Rf_allocMatrix(REALSXP, nt+1, nx));\n\tRf_protect(ypred = Rf_allocMatrix(REALSXP, nt+1, ny));\n\tRf_protect(ppred = Rf_allocMatrix(REALSXP, nt+1, np));\n\tRf_protect(spred = Rf_allocMatrix(REALSXP, nt+1, ns));\n\tRf_protect(xupda = Rf_allocMatrix(REALSXP, nt+1, nx));\n\t//Rf_protect(yupda = Rf_allocMatrix(REALSXP, nt+1, ny));\n\tRf_protect(pupda = Rf_allocMatrix(REALSXP, nt+1, np));\n\t//Rf_protect(supda = Rf_allocMatrix(REALSXP, nt+1, ns));\n\tRf_protect(xsmoo = Rf_allocMatrix(REALSXP, nt+1, nx));\n\tRf_protect(psmoo = Rf_allocMatrix(REALSXP, nt+1, np));\n\t\n\t\n\tif(OMX_DEBUG_ALGEBRA) { mxLog(\"Setting zeroth row ...\"); }\n\t// Set first row of xpred to x0\n\tint row = 0;\n\tfor(int col = 0; col < nx; col++){\n\t\tREAL(xpred)[col * (nt+1) + row] =\n\t\t\tomxMatrixElement(ose->x, col, 0);\n\t\tREAL(xupda)[col * (nt+1) + row] =\n\t\t\tomxMatrixElement(ose->x, col, 0);\n\t}\n\t\n\t// Set first row of ppred to vech(P0)\n\tint counter = 0;\n\tfor(int i = 0; i < ose->P->cols; i++) {\n\t\tfor(int j = i; j < ose->P->rows; j++) {\n\t\t\tREAL(ppred)[counter * (nt+1) + row] = omxMatrixElement(ose->P, j, i);\n\t\t\tREAL(pupda)[counter * (nt+1) + row] = omxMatrixElement(ose->P, j, i);\n\t\t\tcounter++;\n\t\t}\n\t}\n\t\n\tEigen::VectorXd oldDefs;\n\toldDefs.resize(ox->data->defVars.size());\n\toldDefs.setConstant(NA_REAL);\n\t\n\t// Probably should loop through all the data here!!!\n\tif(OMX_DEBUG_ALGEBRA) { mxLog(\"Beginning forward loop ...\"); }\n\tfor(row=1; row < (nt+1); row++){\n\t\tif(OMX_DEBUG_ALGEBRA) { mxLog(\"Setting first data row ...\"); }\n\t\t// Set row of data\n\t\tfor(int i = 0; i < ny; i++) {\n\t\t\tomxSetMatrixElement(ose->y, i, 0, omxDoubleDataElement(ox->data, row-1, i));\n\t\t}\n\t\t\n\t\t// handle definition variables\n\t\tint numVarsFilled = 0;\n\t\tnumVarsFilled = ox->data->handleDefinitionVarList(ox->currentState, row-1, oldDefs.data());\n\t\t\n\t\t/* Run Kalman prediction */\n\t\tif(ose->t == NULL){\n\t\t\tomxKalmanPredict(ose);\n\t\t} else {\n\t\t\tomxKalmanBucyPredict(ose);\n\t\t}\n\t\t\n\t\t// Copy latent state\n\t\tfor(int col = 0; col < nx; col++)\n\t\t\tREAL(xpred)[col * (nt+1) + row] =\n\t\t\t\tomxMatrixElement(ose->x, col, 0);\n\t\t\n\t\t// Copy latent cov\n\t\tcounter = 0;\n\t\tfor(int i = 0; i < ose->P->cols; i++) {\n\t\t\tfor(int j = i; j < ose->P->rows; j++) {\n\t\t\t\tREAL(ppred)[counter * (nt+1) + row] = omxMatrixElement(ose->P, j, i);\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Create Full observed cov prediction\n\t\tif(OMX_DEBUG_ALGEBRA) { mxLog(\"Hand prediction of full observed cov ...\"); }\n\t\tomxDSYMM(FALSE, 1.0, ose->P, ose->C, 0.0, ose->Y); // Y = C P\n\t\tomxCopyMatrix(ose->S, ose->R); // S = R\n\t\tomxDGEMM(FALSE, TRUE, 1.0, ose->Y, ose->C, 1.0, ose->S); // S = Y C^T + S THAT IS C P C^T + R\n\t\t\n\t\t// Copy observed cov\n\t\tcounter = 0;\n\t\tfor(int i = 0; i < ose->S->cols; i++) {\n\t\t\tfor(int j = i; j < ose->S->rows; j++) {\n\t\t\t\tREAL(spred)[counter * (nt+1) + row] = omxMatrixElement(ose->S, j, i);\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\t\t\n\t\t/* Run Kalman update */\n\t\tomxKalmanUpdate(ose);\n\t\t\n\t\t// Copy latent state\n\t\tfor(int col = 0; col < nx; col++)\n\t\t\tREAL(xupda)[col * (nt+1) + row] =\n\t\t\t\tomxMatrixElement(ose->x, col, 0);\n\t\t\n\t\t// Copy latent cov\n\t\tcounter = 0;\n\t\tfor(int i = 0; i < ose->P->cols; i++) {\n\t\t\tfor(int j = i; j < ose->P->rows; j++) {\n\t\t\t\tREAL(pupda)[counter * (nt+1) + row] = omxMatrixElement(ose->P, j, i);\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Copy observed means prediction\n\t\tfor(int col = 0; col < ny; col++)\n\t\t\tREAL(ypred)[col * (nt+1) + row] =\n\t\t\t\tomxMatrixElement(ose->s, col, 0);\n\t\t\n\t\t// TODO Add m2ll calculation here.\n\t\t// Probably like this\n\t\t/*m2ll = y^T S y */ // n.b. y originally is the data row but becomes the data residual!\n\t\t//omxDSYMV(1.0, S, y, 0.0, s); // s = S y\n\t\t//m2ll = omxDDOT(y, s); // m2ll = y s THAT IS y^T S y\n\t\t//m2ll += det; // m2ll = m2ll + det THAT IS m2ll = log(det(S)) + y^T S y\n\t\t// Note: this leaves off the S->cols * log(2*pi) THAT IS k*log(2*pi)\n\t}\n\t\n\t/* TODO Add Backward pass through data for Kalman smoother*/\n\t// Initialize end of smoothed latents to last updated latents\n\t// P = last updated P\n\t// x = last updated x\n\t\n\t// Copy x and P as smoothed estimates for export\n\trow = nt;\n\t// Copy latent state\n\tfor(int col = 0; col < nx; col++)\n\t\tREAL(xsmoo)[col * (nt+1) + row] =\n\t\t\tomxMatrixElement(ose->x, col, 0);\n\t\n\t// Copy latent cov\n\tcounter = 0;\n\tfor(int i = 0; i < ose->P->cols; i++) {\n\t\tfor(int j = i; j < ose->P->rows; j++) {\n\t\t\tREAL(psmoo)[counter * (nt+1) + row] = omxMatrixElement(ose->P, j, i);\n\t\t\tcounter++;\n\t\t}\n\t}\n\t\n\t// loop backwars through all data\n\tif(OMX_DEBUG_ALGEBRA) { mxLog(\"Beginning backward loop ...\"); }\n\tfor(row = nt-1; row > -1; row--){\n\t\t// handle definition variables\n\t\tint numVarsFilled = 0;\n\t\tnumVarsFilled = ox->data->handleDefinitionVarList(ox->currentState, row, oldDefs.data());\n\t\t\n\t\t// Copy Z = updated P from pupda\n\t\tcounter = 0;\n\t\tfor(int i = 0; i < nx; i++) {\n\t\t\tfor(int j = i; j < nx; j++) {\n\t\t\t\tdouble next = REAL(pupda)[counter * (nt+1) + row];\n\t\t\t\tomxSetMatrixElement(ose->Z, i, j, next);\n\t\t\t\tomxSetMatrixElement(ose->Z, j, i, next);\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Copy z = updated x from xupda\n\t\tfor(int col = 0; col < nx; col++)\n\t\t\tomxSetMatrixElement(ose->z, col, 0, REAL(xupda)[col * (nt+1) + row]);\n\t\t\n\t\t// Copy eigenExpA = predicted P from later row of ppred\n\t\tcounter = 0;\n\t\tfor(int i = 0; i < nx; i++) {\n\t\t\tfor(int j = i; j < nx; j++) {\n\t\t\t\tdouble next = REAL(ppred)[counter * (nt+1) + row + 1];\n\t\t\t\tose->eigenExpA(i, j) = next;\n\t\t\t\tose->eigenExpA(j, i) = next;\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Copy eigenPreX = predicted x from later row of xpred\n\t\tfor(int col = 0; col < nx; col++)\n\t\t\tose->eigenPreX(col, 0) =  REAL(xpred)[col * (nt+1) + row + 1];\n\t\t\n\t\t// Run Smoother\n\t\tomxRauchTungStriebelSmooth(ose);\n\t\t\n\t\t// Copy latent state to xsmoo\n\t\tfor(int col = 0; col < nx; col++)\n\t\t\tREAL(xsmoo)[col * (nt+1) + row] =\n\t\t\t\tomxMatrixElement(ose->x, col, 0);\n\t\t\n\t\t// Copy latent cov to psmoo\n\t\tcounter = 0;\n\t\tfor(int i = 0; i < ose->P->cols; i++) {\n\t\t\tfor(int j = i; j < ose->P->rows; j++) {\n\t\t\t\tREAL(psmoo)[counter * (nt+1) + row] = omxMatrixElement(ose->P, j, i);\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\n\t// TODO check on definition variable population\n\t//  I suspect this does yet work properly for def vars.\n\t\n\tRf_setAttrib(algebra, Rf_install(\"xPredicted\"), xpred);\n\tRf_setAttrib(algebra, Rf_install(\"yPredicted\"), ypred);\n\tRf_setAttrib(algebra, Rf_install(\"PPredicted\"), ppred);\n\tRf_setAttrib(algebra, Rf_install(\"SPredicted\"), spred);\n\tRf_setAttrib(algebra, Rf_install(\"xUpdated\"), xupda);\n\tRf_setAttrib(algebra, Rf_install(\"PUpdated\"), pupda);\n\tRf_setAttrib(algebra, Rf_install(\"xSmoothed\"), xsmoo);\n\tRf_setAttrib(algebra, Rf_install(\"PSmoothed\"), psmoo);\n\t\n\t\n\t/*\n\tomxMatrix *expCovInt, *expMeanInt;\n\texpCovInt = argStruct->cov;\n\texpMeanInt = argStruct->means;\n\t\n\tRf_protect(expCovExt = Rf_allocMatrix(REALSXP, expCovInt->rows, expCovInt->cols));\n\tfor(int row = 0; row < expCovInt->rows; row++)\n\t\tfor(int col = 0; col < expCovInt->cols; col++)\n\t\t\tREAL(expCovExt)[col * expCovInt->rows + row] =\n\t\t\t\tomxMatrixElement(expCovInt, row, col);\n\tif (expMeanInt != NULL && expMeanInt->rows > 0  && expMeanInt->cols > 0) {\n\t\tRf_protect(expMeanExt = Rf_allocMatrix(REALSXP, expMeanInt->rows, expMeanInt->cols));\n\t\tfor(int row = 0; row < expMeanInt->rows; row++)\n\t\t\tfor(int col = 0; col < expMeanInt->cols; col++)\n\t\t\t\tREAL(expMeanExt)[col * expMeanInt->rows + row] =\n\t\t\t\t\tomxMatrixElement(expMeanInt, row, col);\n\t} else {\n\t\tRf_protect(expMeanExt = Rf_allocMatrix(REALSXP, 0, 0));\t\t\n\t}\n\n\tRf_setAttrib(algebra, Rf_install(\"expCov\"), expCovExt);\n\tRf_setAttrib(algebra, Rf_install(\"expMean\"), expMeanExt);\n\t\n\tif(argStruct->populateRowDiagnostics){\n\t\tomxMatrix *rowLikelihoodsInt = argStruct->rowLikelihoods;\n\t\tRf_protect(rowLikelihoodsExt = Rf_allocVector(REALSXP, rowLikelihoodsInt->rows));\n\t\tfor(int row = 0; row < rowLikelihoodsInt->rows; row++)\n\t\t\tREAL(rowLikelihoodsExt)[row] = omxMatrixElement(rowLikelihoodsInt, row, 0);\n\t\tRf_setAttrib(algebra, Rf_install(\"likelihoods\"), rowLikelihoodsExt);\n\t}\n\t*/\n\t\n}\n\n\n\n\nvoid omxKalmanPredict(omxStateSpaceExpectation* ose) {\n\tif(OMX_DEBUG) { mxLog(\"Kalman Predict Called.\"); }\n\t/* Creat local copies of State Space Matrices */\n\tomxMatrix* A = ose->A;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(A, \"....State Space: A\"); }\n\tomxMatrix* B = ose->B;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(B, \"....State Space: B\"); }\n\tomxMatrix* Q = ose->Q;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(Q, \"....State Space: Q\"); }\n\tomxMatrix* u = ose->u;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(u, \"....State Space: u\"); }\n\tomxMatrix* x = ose->x;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(x, \"....State Space: x\"); }\n\tomxMatrix* z = ose->z;\n\tomxMatrix* P = ose->P;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(P, \"....State Space: P\"); }\n\t//omxMatrix* S = ose->S;\n\t//omxMatrix* Y = ose->Y;\n\tomxMatrix* Z = ose->Z;\n\n\t/* x = A x + B u */\n\tomxDGEMV(FALSE, 1.0, A, x, 0.0, z); // x = A x\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(z, \"....State Space: z = A x\"); }\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(A, \"....State Space: A\"); }\n\tomxDGEMV(FALSE, 1.0, B, u, 1.0, z); // x = B u + x THAT IS x = A x + B u\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(z, \"....State Space: z = A x + B u\"); }\n\tomxCopyMatrix(x, z); // x = z THAT IS x = A x + B u\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(x, \"....State Space: x = A x + B u\"); }\n\t\n\t/* P = A P A^T + Q */\n\tomxDSYMM(FALSE, 1.0, P, A, 0.0, Z); // Z = A P\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(Z, \"....State Space: Z = A P\"); }\n\tomxCopyMatrix(P, Q); // P = Q\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(P, \"....State Space: P = Q\"); }\n\tomxDGEMM(FALSE, TRUE, 1.0, Z, A, 1.0, P); // P = Z A^T + P THAT IS P = A P A^T + Q\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(P, \"....State Space: P = A P A^T + Q\"); }\n}\n\n\nvoid omxKalmanUpdate(omxStateSpaceExpectation* ose) {\n\t//TODO: Clean up this hack of function.\n\tif(OMX_DEBUG) { mxLog(\"Kalman Update Called.\"); }\n\t/* Creat local copies of State Space Matrices */\n\tomxMatrix* C = ose->C;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(C, \"....State Space: C\"); }\n\tomxMatrix* D = ose->D;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(D, \"....State Space: D\"); }\n\tomxMatrix* r = ose->r;\n\tomxMatrix* s = ose->s;\n\tomxMatrix* u = ose->u;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(u, \"....State Space: u\"); }\n\tomxMatrix* x = ose->x;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(x, \"....State Space: x\"); }\n\tomxMatrix* y = ose->y;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(y, \"....State Space: y\"); }\n\tomxMatrix* P = ose->P;\n\t// omxMatrix* Cov = ose->cov; //unused\n\tomxMatrix* Means = ose->means;\n\tomxMatrix* Det = ose->det;\n\t*Det->data = 0.0; // the value pointed to by Det->data is assigned to be zero\n\tomxMatrix* smallC = ose->smallC;\n\tomxMatrix* smallD = ose->smallD;\n\tomxMatrix* smallr = ose->smallr;\n\tomxMatrix* R = ose->R;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(R, \"....State Space: R on entry\"); }\n\tomxMatrix* smallR = ose->smallR;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallR, \"....State Space: small R on entry\"); }\n\tomxMatrix* smallK = ose->smallK;\n\tomxMatrix* smallS = ose->smallS;\n\tomxMatrix* smallY = ose->smallY;\n\tint ny = y->rows;\n\tint nx = x->rows;\n\tEigen::VectorXi toRemoveSS(ny);\n\tint numRemovesSS = 0;\n\tEigen::VectorXi toRemoveNoneLat(nx);\n\ttoRemoveNoneLat.setZero();\n\tEigen::VectorXi toRemoveNoneOne(1);\n\ttoRemoveNoneOne.setZero();\n\t\n\tomxMatrix* covInfo = ose->covInfo;\n\tint info = 0; // Used for computing inverse for Kalman gain\n\t\n\tomxCopyMatrix(smallS, ose->S);\n\t\n\t/* Reset/Resample aliased matrices */\n\tomxCopyMatrix(smallC, ose->C);\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallC, \"....State Space: C (Reset)\"); }\n\tomxCopyMatrix(smallD, ose->D);\n\tomxCopyMatrix(smallR, ose->R);\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallR, \"....State Space: small R (Reset)\"); }\n\tomxCopyMatrix(smallr, ose->r);\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallr, \"....State Space: r (Reset)\"); }\n\tomxCopyMatrix(smallK, ose->K);\n\tomxCopyMatrix(smallS, ose->S);\n\tomxCopyMatrix(smallY, ose->Y);\n\t\n\t/* r = r - C x - D u */\n\t/* Alternatively, create just the expected value for the data row, x. */\n\tomxDGEMV(FALSE, 1.0, smallC, x, 0.0, s); // s = C x\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(s, \"....State Space: s = C x\"); }\n\tomxDGEMV(FALSE, 1.0, D, u, 1.0, s); // s = D u + s THAT IS s = C x + D u\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(s, \"....State Space: s = C x + D u\"); }\n\tomxCopyMatrix(Means, s); // Means = s THAT IS Means = C x + D u\n\t//if(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(Means, \"....State Space: Means\"); }\n\tomxTransposeMatrix(Means);\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(Means, \"....State Space: Means\"); }\n\t\n\t//If entire data vector, y, is missing, then set residual, r, to zero.\n\t//otherwise, compute residual.\n\ttoRemoveSS.setZero();\n\tfor(int j = 0; j < y->rows; j++) {\n\t\tdouble dataValue = omxMatrixElement(y, j, 0);\n\t\tint dataValuefpclass = std::fpclassify(dataValue);\n\t\tif(dataValuefpclass == FP_NAN || dataValuefpclass == FP_INFINITE) {\n\t\t\tnumRemovesSS++;\n\t\t\ttoRemoveSS[j] = 1;\n\t\t\tomxSetMatrixElement(r, j, 0, 0.0);\n\t\t} else {\n\t\t\tomxSetMatrixElement(r, j, 0, (dataValue -  omxMatrixElement(s, j, 0)));\n\t\t}\n\t}\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(r, \"....State Space: Residual (Loop)\"); }\n\t/* Now compute the residual */\n\t//omxCopyMatrix(r, y); // r = y\n\t//omxDAXPY(-1.0, s, r); // r = r - s THAT IS r = y - (C x + D u)\n\tomxCopyMatrix(smallr, ose->r);\n\t\n\t/* Filter S Here */\n\t// N.B. if y is completely missing or completely present, leave S alone.\n\t// Otherwise, filter S.\n\tif(numRemovesSS < ny && numRemovesSS > 0) {\n\t\t//if(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallS, \"....State Space: S\"); }\n\t\tif(OMX_DEBUG) { mxLog(\"Filtering S, R, C, r, K, and Y.\"); }\n\t\tomxRemoveRowsAndColumns(smallS, numRemovesSS, numRemovesSS, toRemoveSS.data(), toRemoveSS.data());\n\t\t//if(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallS, \"....State Space: S (Filtered)\"); }\n\t\t\n\t\tomxRemoveRowsAndColumns(smallR, numRemovesSS, numRemovesSS, toRemoveSS.data(), toRemoveSS.data());\n\t\t\n\t\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallC, \"....State Space: C\"); }\n\t\tomxRemoveRowsAndColumns(smallC, numRemovesSS, 0, toRemoveSS.data(), toRemoveNoneLat.data());\n\t\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallC, \"....State Space: C (Filtered)\"); }\n\t\t\n\t\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(r, \"....State Space: r\"); }\n\t\tomxRemoveRowsAndColumns(smallr, numRemovesSS, 0, toRemoveSS.data(), toRemoveNoneOne.data());\n\t\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallr, \"....State Space: r (Filtered)\"); }\n\t\t\n\t\t//if(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallK, \"....State Space: K\"); }\n\t\tomxRemoveRowsAndColumns(smallK, numRemovesSS, 0, toRemoveSS.data(), toRemoveNoneLat.data());\n\t\t//if(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallK, \"....State Space: K (Filtered)\"); }\n\t\t\n\t\tomxRemoveRowsAndColumns(smallY, numRemovesSS, 0, toRemoveSS.data(), toRemoveNoneLat.data());\n\t}\n\tif(numRemovesSS == ny) {\n\t\tif(OMX_DEBUG_ALGEBRA) { mxLog(\"Completely missing row of data found.\"); }\n\t\tif(OMX_DEBUG_ALGEBRA) { mxLog(\"Skipping much of Kalman Update.\"); }\n\t\treturn ;\n\t}\n\t\n\t\n\t/* S = C P C^T + R */\n\tomxDSYMM(FALSE, 1.0, P, smallC, 0.0, smallY); // Y = C P\n\t//omxCopyMatrix(S, smallR); // S = R\n\tmemcpy(smallS->data, smallR->data, smallR->rows * smallR->cols * sizeof(double)); // Less safe omxCopyMatrix that keeps smallS aliased to S.\n\tomxDGEMM(FALSE, TRUE, 1.0, smallY, smallC, 1.0, smallS); // S = Y C^T + S THAT IS C P C^T + R\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallS, \"....State Space: S = C P C^T + R\"); }\n\t\n\t\n\t/* Now compute the Kalman Gain and update the error covariance matrix */\n\t/* S = S^-1 */\n\tomxDPOTRF(smallS, &info); // S replaced by the lower triangular matrix of the Cholesky factorization\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallS, \"....State Space: Cholesky of S\"); }\n\tcovInfo->data[0] = (double) info;\n\tfor(int i = 0; i < smallS->cols; i++) {\n\t\t*Det->data += log(fabs(omxMatrixElement(smallS, i, i)));\n\t}\n\t//det *= 2.0; //sum( log( abs( diag( chol(S) ) ) ) )*2\n\tomxDPOTRI(smallS, &info); // S = S^-1 via Cholesky factorization\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallS, \"....State Space: Inverse of S\"); }\n\t// If Cholesky of exp cov failed (i.e. non-positive def), Populate 1,1 element of smallS (inverse of exp cov) with NA_REAL\n\tif(covInfo->data[0] > 0) {\n\t\tomxSetMatrixElement(smallS, 0, 0, NA_REAL);\n\t}\n\t\n\t/* K = P C^T S^-1 */\n\t/* Computed as K^T = S^-1 C P */\n\tomxDSYMM(TRUE, 1.0, smallS, smallY, 0.0, smallK); // K = Y^T S THAT IS K = P C^T S^-1\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallK, \"....State Space: K^T = S^-1 C P\"); }\n\t\n\t/* x = x + K r */\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallr, \"....State Space Check Residual: r\"); }\n\tomxDGEMV(TRUE, 1.0, smallK, smallr, 1.0, x); // x = K r + x\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(x, \"....State Space: x = K r + x\"); }\n\t\n\t/* P = (I - K C) P */\n\t/* P = P - K C P */\n\tomxDGEMM(TRUE, FALSE, -1.0, smallK, smallY, 1.0, P); // P = -K Y + P THAT IS P = P - K C P\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(P, \"....State Space: P = P - K C P\"); }\n\t\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(smallS, \"....State Space: Inverse of S\"); }\n\t\n\t\n\t/*m2ll = y^T S y */ // n.b. y originally is the data row but becomes the data residual!\n\t//omxDSYMV(1.0, S, y, 0.0, s); // s = S y\n\t//m2ll = omxDDOT(y, s); // m2ll = y s THAT IS y^T S y\n\t//m2ll += det; // m2ll = m2ll + det THAT IS m2ll = log(det(S)) + y^T S y\n\t// Note: this leaves off the S->cols * log(2*pi) THAT IS k*log(2*pi)\n}\n\n\nvoid omxKalmanBucyPredict(omxStateSpaceExpectation* ose) {\n\tif(OMX_DEBUG) { mxLog(\"Kalman Bucy Predict Called.\"); }\n\t/* Creat local copies of State Space Matrices */\n\tomxMatrix* A = ose->A;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(A, \"....State Space: A\"); }\n\tomxMatrix* B = ose->B;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(B, \"....State Space: B\"); }\n\tomxMatrix* Q = ose->Q;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(Q, \"....State Space: Q\"); }\n\tomxMatrix* u = ose->u;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(u, \"....State Space: u\"); }\n\tomxMatrix* x = ose->x;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(x, \"....State Space: x\"); }\n\tomxMatrix* P = ose->P;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(P, \"....State Space: P\"); }\n\tomxMatrix* Z = ose->Z;\n\tomxMatrix* t = ose->t;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(t, \"....State Space: t\"); }\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space oldT on entrance:\\n\" << ose->oldT << std::endl; }\n\tose->deltaT = omxMatrixElement(t, 0, 0) - ose->oldT;\n\tose->oldT = omxMatrixElement(t, 0, 0);\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space oldT on exit:\\n\" << ose->oldT << std::endl; }\n\tdouble deltaT = ose->deltaT;\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space deltaT:\\n\" << deltaT << std::endl; }\n\t\n\t//EigenMatrixAdaptor eigenA(A);\n\t// intializes eigenA as an instance of EigenMatrixAdaptor class, initialized to omxMatrix A\n\t// EigenVectorAdaptor\n\t// eigenB = eigenA.exp(); // matrix exponential\n\t// for scalar multiplication\n\t// A * omxElement(B,1,4); A eigen matrix, B omxMatrix\n\t// Subtract from diagonal 1.0\n\t// A.diagonal() -= 1\n\t\n\t/* Eigen Matrix reference setting */\n\tEigen::MatrixXd &eigenExpA = ose->eigenExpA;\n\tEigen::MatrixXd &eigenIA = ose->eigenIA;\n\tEigen::MatrixXd &PSI = ose->PSI;\n\tEigen::MatrixXd &IP = ose->IP;\n\tEigen::MatrixXd &I = ose->I;\n\t\n\t\n\t/*R code for the next few lines\n\t\tldim <- nrow(x$A)\n\t\tI <- diag(1, nrow=ldim)\n\t\texpA <- as.matrix(expm(x$A * x$deltaT))\n\t\tintA <- solve(x$A) %*% (expA - I)\n\t\tx$x <- expA %*% x$x + intA %*% x$B %*% x$u\n\t*/\n\t\n\t\n\t/*  Z = A\n\t\teigenA = Z\n\t\teigenExpA = eigenA*deltaT  THAT IS eigenExpA = A*deltaT\n\t*/\n\tomxCopyMatrix(Z, A);\n\tEigenMatrixAdaptor eigenA(Z);\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space eigenA:\\n\" << eigenA << std::endl; }\n\teigenExpA = eigenA * deltaT;\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space eigenA:\\n\" << eigenA << std::endl; }\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space deltaT:\\n\" << deltaT << std::endl; }\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space eigenExpA:\\n\" << eigenExpA << std::endl; }\n\t\n\t/* eigenExpA = expm(eigenExpA)  THAT IS eigenExpA = expm(A*deltaT) */\n\teigenExpA = eigenExpA.exp();\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space eigenExpA:\\n\" << eigenExpA << std::endl; }\n\t\n\t/* eigenIA = eigenExpA - I*/\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space I:\\n\" << I << std::endl; }\n\teigenIA = eigenExpA - I;\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space expA - I:\\n\" << eigenIA << std::endl; }\n\teigenIA = eigenA.lu().solve(eigenIA);\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space A^-1 (expA - I):\\n\" << eigenIA << std::endl; }\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space eigenA:\\n\" << eigenA << std::endl; }\n\t/* eigenIA = A^-1 IA  THAT IS eigenIA = A^-1 (expm(A*deltaT) - I) */\n\t\n\t/* x = expm(A*deltaT) * x + IA * B * u */\n\tEigenMatrixAdaptor eigenx(x); //or vector\n\tEigenMatrixAdaptor eigenu(u); //or vector\n\tEigenMatrixAdaptor eigenB(B);\n\teigenx.derived() = eigenExpA * eigenx + eigenIA * eigenB * eigenu;\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space XPred:\\n\" << eigenx << std::endl; }\n\t\n\t\n\t/* SUMMARY */\n\t// EA = expm(A*deltaT)\n\t// IA = A^-1 (EA - I)\n\t// x = EA x + IA B u\n\t\n\t\n\t/*R code for the next few lines\n\t\tldim <- nrow(x$A)\n\t\tpsi <- cbind(rbind(x$A, matrix(0, nrow=ldim, ncol=ldim)), rbind(x$Q, -x$A))\n\t\tepsi <- as.matrix(expm(psi * x$deltaT)) %*% rbind(x$P, I)\n\t\tx$P <- epsi[1:ldim, ] %*% solve(epsi[(ldim+1):(2*ldim), ])\n\t*/\n\t\n\t\n\t/* PSI = block matrix\n\t-A^T  0\n\t Q    A\n\t*/\n\tEigenMatrixAdaptor eigenQ(Q);\n\tPSI << -1.0*eigenA.transpose(), Eigen::MatrixXd::Zero(A->rows, A->rows), eigenQ, eigenA;\n\tPSI = PSI * deltaT;\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space PSI:\\n\" << PSI << std::endl; }\n\t/* PSI = PSI * deltaT */\n\t/* PSI = expm(PSI) */\n\tPSI = PSI.exp();\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space expPSI*deltaT:\\n\" << PSI << std::endl; }\n\t\n\t/* IP = block matrix\n\tI\n\tP\n\t*/\n\tEigenMatrixAdaptor eigenP(P);\n\tIP << I, eigenP;\n\t//IP << eigenP, Eigen::MatrixXd::Identity(rows, rows)\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space IP:\\n\" << IP << std::endl; }\n\t\n\t/* IP = PSI IP */\n\tIP = PSI * IP;\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space Blocks:\\n\" << IP << std::endl; }\n\t\n\t/* eigenIA = block 1 of IP; eigenExpA = block 2 of IP */\n\teigenP.derived() = IP.block(0, 0, A->rows, A->cols);\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space Block1:\\n\" << eigenP << std::endl; }\n\teigenExpA = IP.block(A->rows, 0, A->rows, A->cols);\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space Block2:\\n\" << eigenExpA << std::endl; }\n\teigenP.derived() = eigenP.transpose().lu().solve(eigenExpA.transpose());\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space eigenP:\\n\" << eigenP << std::endl; }\n\t/* P = B1 B2^-1  THAT IS  solve B2^T P = B1^T for P */\n\t\n\t\n\t/* SUMMARY */\n\t// PSI = \t-A^T  0\n\t//\t\t\t Q    A\n\t// PSI = expm(PSI * deltaT)\n\t// IP = \tI\n\t// \t\t\tP\n\t// IP = PSI IP\n\t// P = IP[1] IP[2]^-1\n\t\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space eigenX\" << eigenx << std::endl; }\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(x, \"....State Space: x\"); }\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space eigenP:\\n\" << eigenP << std::endl; }\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(P, \"....State Space: P\"); }\n}\n\n\nvoid omxRauchTungStriebelSmooth(omxStateSpaceExpectation* ose) {\n\tif(OMX_DEBUG) { mxLog(\"Rauch Tung Striebel Smooth Called.\"); }\n\t/* Creat local copies of State Space Matrices */\n\tomxMatrix* A = ose->A;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(A, \"....State Space: A\"); }\n\tomxMatrix* x = ose->x;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(x, \"....State Space: x smoothed\"); }\n\tomxMatrix* z = ose->z;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(z, \"....State Space: x updated\"); }\n\tomxMatrix* P = ose->P;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(P, \"....State Space: P smoothed\"); }\n\tomxMatrix* Z = ose->Z;\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(Z, \"....State Space: P updated\"); }\n\t\n\t/* Eigen Matrix reference setting */\n\tEigen::MatrixXd &eigenPreX = ose->eigenPreX;\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space x predicted:\\n\" << eigenPreX << std::endl; }\n\tEigen::MatrixXd &eigenExpA = ose->eigenExpA;\n\tif(OMX_DEBUG_ALGEBRA) {std::cout << \"... State Space P predicted:\\n\" << eigenExpA << std::endl; }\n\tEigen::MatrixXd &eigenIA = ose->eigenIA; // Storage for Sg (RTS smoother gain matrix)\n\t\n\t/* Eigen Adaptor copies (not really copies, more like wrappers) */\n\tEigenMatrixAdaptor eigenA(A);\n\tEigenMatrixAdaptor eigenx(x);\n\tEigenMatrixAdaptor eigenz(z);\n\tEigenMatrixAdaptor eigenP(P);\n\tEigenMatrixAdaptor eigenZ(Z);\n\t\n\t\n\t/* Create the RTS Gain matrix*/\n\t// Sg = Pui * A * Ppi+1 ^-1\n\t// eigenIA = Z * A * eigenExpA^-1\n\t// Possible typo above, A should be A^T\n\teigenIA = eigenExpA.lu().solve( eigenA * eigenZ ).transpose();\n\t// try also\n\t//eigenIA = eigenExpA.ldlt().solve( eigenA.transpose() * eigenZ ).transpose();\n\t// with #include <Eigen/Cholesky>\n\t\n\t/* Smooth the latent state */\n\t// xsi = xui + Sg * (xsi+1 - xpi+1)\n\t// x = z + eigenIA * (x - eigenPreX)\n\teigenx.derived() = eigenz + eigenIA * (eigenx - eigenPreX);\n\t\n\t/* Smooth the latent covariance */\n\t// Psi = Pui + Sg * (Psi+1 - Ppi+1) * Sg^T\n\t// P = Z + eigenIA * (P - eigenExpA) * eigenIA^T\n\teigenP.derived() = eigenZ + eigenIA * (eigenP - eigenExpA) * eigenIA.transpose();\n\t\n\t// TODO add eigenPreX to struct and initialize\n}\n\n\nvoid omxInitStateSpaceExpectation(omxExpectation* ox) {\n\t\n\tSEXP rObj = ox->rObj;\n\tif(OMX_DEBUG) { mxLog(\"Initializing State Space Expectation.\"); }\n\t\t\n\tint nx, ny, nu;\n\t\n\t//SEXP slotValue;   //Used by PPML\n\t\n\t/* Create and fill expectation */\n\t//omxStateSpaceExpectation *SSMexp = (omxStateSpaceExpectation*) R_alloc(1, sizeof(omxStateSpaceExpectation));\n\tomxStateSpaceExpectation *SSMexp = new omxStateSpaceExpectation;\n\t\n\tomxState* currentState = ox->currentState;\n\t\n\t/* Set Expectation Calls and Structures */\n\tox->computeFun = omxCallStateSpaceExpectation;\n\tox->destructFun = omxDestroyStateSpaceExpectation;\n\tox->componentFun = omxGetStateSpaceExpectationComponent;\n\tox->mutateFun = omxSetStateSpaceExpectationComponent;\n\tox->populateAttrFun = omxPopulateSSMAttributes;\n\tox->argStruct = (void*) SSMexp;\n\tox->canDuplicate = false;\n\t\n\t/* Set up expectation structures */\n\tif(OMX_DEBUG) { mxLog(\"Initializing State Space Meta Data for expectation.\"); }\n\t\n\tif(OMX_DEBUG) { mxLog(\"Processing A.\"); }\n\tSSMexp->A = omxNewMatrixFromSlot(rObj, currentState, \"A\");\n\t\n\tif(OMX_DEBUG) { mxLog(\"Processing B.\"); }\n\tSSMexp->B = omxNewMatrixFromSlot(rObj, currentState, \"B\");\n\t\n\tif(OMX_DEBUG) { mxLog(\"Processing C.\"); }\n\tSSMexp->C = omxNewMatrixFromSlot(rObj, currentState, \"C\");\n\t\n\tif(OMX_DEBUG) { mxLog(\"Processing D.\"); }\n\tSSMexp->D = omxNewMatrixFromSlot(rObj, currentState, \"D\");\n\t\n\tif(OMX_DEBUG) { mxLog(\"Processing Q.\"); }\n\tSSMexp->Q = omxNewMatrixFromSlot(rObj, currentState, \"Q\");\n\t\n\tif(OMX_DEBUG) { mxLog(\"Processing R.\"); }\n\tSSMexp->R = omxNewMatrixFromSlot(rObj, currentState, \"R\");\n\t\n\tif(OMX_DEBUG) { mxLog(\"Processing initial x.\"); }\n\tSSMexp->x0 = omxNewMatrixFromSlot(rObj, currentState, \"x0\");\n\t\n\tif(OMX_DEBUG) { mxLog(\"Processing initial P.\"); }\n\tSSMexp->P0 = omxNewMatrixFromSlot(rObj, currentState, \"P0\");\n\t\n\tif(OMX_DEBUG) { mxLog(\"Processing u.\"); }\n\tSSMexp->u = omxNewMatrixFromSlot(rObj, currentState, \"u\");\n\t\n\tif(OMX_DEBUG) { mxLog(\"Processing t.\"); }\n\tSSMexp->t = omxNewMatrixFromSlot(rObj, currentState, \"t\");\n\t\n\t\n\t/* Initialize the place holder matrices used in calculations */\n\tnx = SSMexp->C->cols;\n\tny = SSMexp->C->rows;\n\tnu = SSMexp->D->cols;\n\t\n\tif(OMX_DEBUG) { mxLog(\"Processing first data row for y.\"); }\n\tSSMexp->y = omxInitMatrix(ny, 1, TRUE, currentState);\n\tfor(int i = 0; i < ny; i++) {\n\t\tomxSetMatrixElement(SSMexp->y, i, 0, omxDoubleDataElement(ox->data, 0, i));\n\t}\n\tif(OMX_DEBUG_ALGEBRA) {omxPrintMatrix(SSMexp->y, \"....State Space: y\"); }\n\t\n\t// TODO Make x0 and P0 static (if possible) to save memory\n\t// TODO Look into omxMatrix.c/h for a possible new matrix from omxMatrix function\n\tif(OMX_DEBUG) { mxLog(\"Generating static internals for resetting initial values.\"); }\n\tSSMexp->x = \tomxInitMatrix(nx, 1, TRUE, currentState);\n\tSSMexp->P = \tomxInitMatrix(nx, nx, TRUE, currentState);\n\tomxCopyMatrix(SSMexp->x, SSMexp->x0);\n\tomxCopyMatrix(SSMexp->P, SSMexp->P0);\n\t\n\tif(OMX_DEBUG) { mxLog(\"Generating internals for computation.\"); }\n\t\n\tSSMexp->covInfo = \tomxInitMatrix(1, 1, TRUE, currentState);\n\tSSMexp->det = \tomxInitMatrix(1, 1, TRUE, currentState);\n\tSSMexp->r = \tomxInitMatrix(ny, 1, TRUE, currentState);\n\tSSMexp->s = \tomxInitMatrix(ny, 1, TRUE, currentState);\n\tSSMexp->z = \tomxInitMatrix(nx, 1, TRUE, currentState);\n\tSSMexp->K = \tomxInitMatrix(ny, nx, TRUE, currentState); // Actually the tranpose of the Kalman gain\n\tSSMexp->S = \tomxInitMatrix(ny, ny, TRUE, currentState);\n\tSSMexp->Y = \tomxInitMatrix(ny, nx, TRUE, currentState);\n\tSSMexp->Z = \tomxInitMatrix(nx, nx, TRUE, currentState);\n\t\n\tSSMexp->cov = \t\tomxInitMatrix(ny, ny, TRUE, currentState);\n\tSSMexp->means = \tomxInitMatrix(1, ny, TRUE, currentState);\n\t\n\t/* Create alias matrices for missing data filtering */\n\tSSMexp->smallC = \tomxInitMatrix(ny, nx, TRUE, currentState);\n\tSSMexp->smallD = \tomxInitMatrix(ny, nu, TRUE, currentState);\n\tSSMexp->smallR = \tomxInitMatrix(ny, ny, TRUE, currentState);\n\tSSMexp->smallr = \tomxInitMatrix(ny, 1, TRUE, currentState);\n\tSSMexp->smallK = \tomxInitMatrix(ny, nx, TRUE, currentState);\n\tSSMexp->smallS = \tomxInitMatrix(ny, ny, TRUE, currentState);\n\tSSMexp->smallY = \tomxInitMatrix(ny, nx, TRUE, currentState);\n\t\n\t//SSMexp->deltaT = \tomxInitMatrix(1, 1, TRUE, currentState);\n\tSSMexp->oldT = 0.0;\n\tSSMexp->deltaT = 0.0;\n\t\n\t/* Eigen Matrix initialization */\n\tSSMexp->eigenExpA.resize(nx, nx);\n\tSSMexp->I.resize(nx, nx);\n\tSSMexp->I = Eigen::MatrixXd::Identity(nx, nx);\n\tSSMexp->eigenIA.resize(nx, nx);\n\tSSMexp->PSI.resize(2*nx, 2*nx);\n\tSSMexp->IP.resize(2*nx, nx);\n\tSSMexp->eigenPreX.resize(nx, 1);\n\t\n\t/* Population of Kalman scores*/\n\tif(OMX_DEBUG) {\n\t\tmxLog(\"Accessing Kalman score population option.\");\n\t}\n\tSSMexp->returnScores = Rf_asInteger(R_do_slot(rObj, Rf_install(\"scores\")));\n\t\n\t\n\tomxCopyMatrix(SSMexp->smallC, SSMexp->C);\n\tomxCopyMatrix(SSMexp->smallD, SSMexp->D);\n\tomxCopyMatrix(SSMexp->smallR, SSMexp->R);\n\tomxCopyMatrix(SSMexp->smallr, SSMexp->r);\n\tomxCopyMatrix(SSMexp->smallK, SSMexp->K);\n\tomxCopyMatrix(SSMexp->smallS, SSMexp->S);\n\tomxCopyMatrix(SSMexp->smallY, SSMexp->Y);\n\n}\n\n\nomxMatrix* omxGetStateSpaceExpectationComponent(omxExpectation* ox, omxFitFunction* off, const char* component) {\n\tomxStateSpaceExpectation* ose = (omxStateSpaceExpectation*)(ox->argStruct);\n\tomxMatrix* retval = NULL;\n\n\tif(strEQ(\"cov\", component)) {\n\t\tretval = ose->cov;\n\t} else if(strEQ(\"means\", component)) {\n\t\tretval = ose->means;\n\t} else if(strEQ(\"pvec\", component)) {\n\t\t// Once implemented, change compute function and return pvec\n\t} else if(strEQ(\"inverse\", component)) {\n\t\tretval = ose->smallS;\n\t} else if(strEQ(\"determinant\", component)) {\n\t\tretval = ose->det;\n\t} else if(strEQ(\"r\", component)) {\n\t\tretval = ose->r;\n\t} else if(strEQ(\"covInfo\", component)) {\n\t\tretval = ose->covInfo;\n\t}\n\t\n\treturn retval;\n}\n\nvoid omxSetStateSpaceExpectationComponent(omxExpectation* ox, omxFitFunction* off, const char* component, omxMatrix* om) {\n\tomxStateSpaceExpectation* ose = (omxStateSpaceExpectation*)(ox->argStruct);\n\t\n\tif(!strcmp(\"y\", component)) {\n\t\tfor(int i = 0; i < ose->y->rows; i++) {\n\t\t\tomxSetMatrixElement(ose->y, i, 0, omxVectorElement(om, i));\n\t\t}\n\t\t//ose->y = om;\n\t}\n\tif(!strcmp(\"Reset\", component)) {\n\t\tomxRecompute(ose->x0, NULL);\n\t\tomxRecompute(ose->P0, NULL);\n\t\tomxCopyMatrix(ose->x, ose->x0);\n\t\tomxCopyMatrix(ose->P, ose->P0);\n\t\tif(ose->t != NULL){\n\t\t\tose->oldT = 0.0;\n\t\t}\n\t}\n}\n\n\n\n", "meta": {"hexsha": "da200497ef2e64bc08f0f407a58781f2d63c0ece", "size": 35471, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/omxStateSpaceExpectation.cpp", "max_stars_repo_name": "JuKa87/OpenMx", "max_stars_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/omxStateSpaceExpectation.cpp", "max_issues_repo_name": "JuKa87/OpenMx", "max_issues_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/omxStateSpaceExpectation.cpp", "max_forks_repo_name": "JuKa87/OpenMx", "max_forks_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7575129534, "max_line_length": 141, "alphanum_fraction": 0.6525612472, "num_tokens": 12922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4144783517069334}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n// Written by Jan Bos\n// Edited  by Peter Gottschling\n\n#ifndef ITL_BICGSTAB_ELL_INCLUDE\n#define ITL_BICGSTAB_ELL_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n#include <boost/numeric/mtl/matrix/strict_upper.hpp>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/mtl/operation/orth.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/mtl/operation/size.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#include <boost/numeric/itl/itl_fwd.hpp>\n#include <boost/numeric/itl/krylov/base_solver.hpp>\n\nnamespace itl {\n\n/// Bi-Conjugate Gradient Stabilized(ell) \ntemplate < typename LinearOperator, typename Vector, \n\t   typename LeftPreconditioner, typename RightPreconditioner, \n\t   typename Iteration >\nint bicgstab_ell(const LinearOperator &A, Vector &x, const Vector &b,\n\t\t const LeftPreconditioner &L, const RightPreconditioner &R, \n\t\t Iteration& iter, size_t l)\n{\n    mtl::vampir_trace<7006> tracer;\n    using mtl::size; using mtl::irange; using mtl::imax; using mtl::mat::strict_upper;\n    typedef typename mtl::Collection<Vector>::value_type Scalar;\n    typedef typename mtl::Collection<Vector>::size_type  Size;\n\n    if (size(b) == 0) throw mtl::logic_error(\"empty rhs vector\");\n\n    const Scalar                zero= math::zero(Scalar()), one= math::one(Scalar());\n    Vector                      x0(resource(x)), y(resource(x));\n    mtl::dense_vector<Vector>   r_hat(l+1,Vector(resource(x))), u_hat(l+1,Vector(resource(x)));\n\n    // shift problem \n    x0= zero;\n    r_hat[0]= b;\n    if (two_norm(x) != zero) {\n\tr_hat[0]-= A * x;\n\tx0= x;\n\tx= zero;\n    }\n\n    Vector  r0_tilde(r_hat[0]/two_norm(r_hat[0]));\n    y= solve(L, r_hat[0]);\n    r_hat[0]= y;\n    u_hat[0]= zero;\n\n    Scalar                      rho_0(one), rho_1(zero), alpha(zero), Gamma(zero), beta(zero), omega(one); \n    mtl::mat::dense2D<Scalar>        tau(l+1, l+1);\n    mtl::dense_vector<Scalar>   sigma(l+1), gamma(l+1), gamma_a(l+1), gamma_aa(l+1);\n\n    while (! iter.finished(r_hat[0])) {\n\t++iter;\n\trho_0= -omega * rho_0;\n\n\tfor (Size j= 0; j < l; ++j) {\n\t    rho_1= dot(r0_tilde, r_hat[j]); \n\t    beta= alpha * rho_1/rho_0; rho_0= rho_1;\n\n\t    for (Size i= 0; i <= j; ++i)\n\t\tu_hat[i]= r_hat[i] - beta * u_hat[i];\n      \n\t    y= A * Vector(solve(R, u_hat[j]));\n\t    u_hat[j+1]= solve(L, y);\n\t    Gamma= dot(r0_tilde, u_hat[j+1]); \n\t    alpha= rho_0 / Gamma;\n\n\t    for (Size i= 0; i <= j; ++i)\n\t\tr_hat[i]-= alpha * u_hat[i+1];\n      \n\t    if (iter.finished(r_hat[j])) {\n\t\tx= solve(R, x);\n\t\tx+= x0;\n\t\treturn iter;\n\t    }\n\n\t    r_hat[j+1]= solve(R, r_hat[j]);\n\t    y= A * r_hat[j+1]; \n\t    r_hat[j+1]= solve(L, y);\n\t    x+= alpha * u_hat[0];\n\t}\n\n\t// mod GS (MR part)\n\tirange  i1m(1, imax);\n\tmtl::dense_vector<Vector>   r_hat_tail(r_hat[i1m]);\n\ttau[i1m][i1m]= orthogonalize_factors(r_hat_tail);\n\tfor (Size j= 1; j <= l; ++j) \n\t    gamma_a[j]= dot(r_hat[j], r_hat[0]) / tau[j][j];\n\n\tgamma[l]= gamma_a[l]; omega= gamma[l];\n\tif (omega == zero) return iter.fail(3, \"bicg breakdown #2\");\n\n\t// is this something like a tri-solve? \n\tfor (Size j= l-1; j > 0; --j) {\n\t    Scalar sum= zero;\n\t    for (Size i=j+1;i<=l;++i)\n\t\tsum += tau[j][i] * gamma[i];\n\t    gamma[j] = gamma_a[j] - sum;\n\t}\n\n\tgamma_aa[irange(1, l)]= strict_upper(tau[irange(1, l)][irange(1, l)]) * gamma[irange(2, l+1)] + gamma[irange(2, l+1)];\n\n\tx+= gamma[1] * r_hat[0];\n\tr_hat[0]-= gamma_a[l] * r_hat[l];\n\tu_hat[0]-= gamma[l] * u_hat[l];\n\tfor (Size j=1; j < l; ++j) {\n\t    u_hat[0] -= gamma[j] * u_hat[j];\n\t    x+= gamma_aa[j] * r_hat[j];\n\t    r_hat[0] -= gamma_a[j] * r_hat[j];\n\t}\n    }\n    x= solve(R, x); x+= x0; // convert to real solution and undo shift\n    return iter;\n}\n\n\n/// Solver class for BiCGStab(ell) method\n/** Methods inherited from \\ref base_solver. **/\ntemplate < typename LinearOperator, typename Preconditioner, \n\t   typename RightPreconditioner>\nclass bicgstab_ell_solver\n  : public base_solver< bicgstab_ell_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator >\n{\n    typedef base_solver< bicgstab_ell_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator > base;\n  public:\n    /// Construct solver from a linear operator; generate (left) preconditioner from it\n    explicit bicgstab_ell_solver(const LinearOperator& A, size_t l= 8) : base(A), l(l), L(A), R(A) {}\n\n    /// Construct solver from a linear operator and left preconditioner\n    bicgstab_ell_solver(const LinearOperator& A, size_t l, const Preconditioner& L) : base(A), l(l), L(L), R(A) {}\n\n    /// Construct solver from a linear operator and left preconditioner\n    bicgstab_ell_solver(const LinearOperator& A, size_t l, const Preconditioner& L, const RightPreconditioner& R) \n      : base(A), l(l), L(L), R(R) {}\n\n    /// Solve linear system approximately as specified by \\p iter\n    template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >\n    int solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const\n    {\n\treturn bicgstab_ell(this->A, x, b, L, R, iter, l);\n    }\n\n  private:\n    size_t                l;\n    Preconditioner        L;\n    RightPreconditioner   R;\n};\n\n\n\n} // namespace itl\n\n#endif // ITL_BICGSTAB_ELL_INCLUDE\n", "meta": {"hexsha": "3a1ae01fda8bf00f4b7c9872cb774878fb750e63", "size": 5842, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/krylov/bicgstab_ell.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/itl/krylov/bicgstab_ell.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/itl/krylov/bicgstab_ell.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 33.3828571429, "max_line_length": 121, "alphanum_fraction": 0.6516603903, "num_tokens": 1817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4144673025319839}}
{"text": "#include \"logisticregression.h\"\n#include \"ui_logisticregression.h\"\n\n#include <cmath>\n#include <iostream>\n#include <stdio.h>\n#include <vector>\n#include <sys/time.h>\n#include <chrono>\n#include <sys/resource.h>   // check the memory usage\n#include <stdio.h>\n#include <thread>\n#include <fstream>\n#include <sstream>\n\n#include <NTL/RR.h>\n#include <NTL/xdouble.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <NTL/BasicThreadPool.h>\n\n\n#include \"HELR/CZZ.h\"\n#include \"HELR/Params.h\"\n#include \"HELR/PubKey.h\"\n#include \"HELR/Scheme.h\"\n#include \"HELR/SchemeAlgo.h\"\n#include \"HELR/SecKey.h\"\n#include \"HELR/TestScheme.h\"\n#include \"HELR/TimeUtils.h\"\n#include \"HELR/Ring2Utils.h\"\n#include \"HELR/StringUtils.h\"\n#include \"HELR/EvaluatorUtils.h\"\n\n#include \"Database.h\"\n#include \"LRtest.h\"\n#include \"HELR.h\"\n#include <QFile>\n#include <QtDebug>\n#include <QFileDialog>\n#include \"mainwindow.h\"\nusing namespace NTL;\nusing namespace std;\n\nLogisticRegression::LogisticRegression(QWidget *parent) :\n    QWidget(parent),\n    ui(new Ui::LogisticRegression)\n{\n    ui->setupUi(this);\n    QPalette bgpal = palette();\n    bgpal.setColor (QPalette::Background, QColor (0, 0 , 0, 255));\n    bgpal.setColor (QPalette::Foreground, QColor (255,255,255,255)); setPalette (bgpal);\n}\n\nLogisticRegression::~LogisticRegression()\n{\n    delete ui;\n}\n\n\nvoid LogisticRegression::testHELR()\n{\n    /*\n    if(Argc != 3){\n        cout << \"-------------------------------------------------------------\" << endl;\n        cerr << \"Enter the File and degree of approximation \\t\"  << \"(e.g. $test edin.txt 3) \\n \";\n    }\n    */\n    //qDebug()<< QDir::currentPath();\n    //  char* filename  =  Argv[1];\n    // int polydeg = atoi(Argv[2]);  // degree of approximation polynomial\n//    char* filename = \"data/edin.txt\";\n\n    /*QFile file(filename);\n    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))\n    {\n        qDebug()<<file.errorString();\n    }else{\n        cout<<\"errorrrr\"<<endl;\n    }*/\n//    int polydeg = 3;\n    dMat  zData;\n    dMat* zTest = new dMat[5];\n    dMat* zTrain = new dMat[5];\n\n    freopen(\"mid_result.txt\",\"w\",stdout);\n    int nLine= readData(zData, filename);\n\n    cout << \"Sample the learning and test data ...\" << endl;\n    cvRandomSamplingData(zTrain, zTest, zData, filename);\n\n\n    //----------------------------------------------------------------\n    // Parameters for Logistic regression\n    //----------------------------------------------------------------\n\n    long logN= 11;\n    long logp= 28;\n    long logl= 10;\n    long logq, cBit1, cBit2;\n    int max_iter;\n\n    struct LRpar LRparams;\n    ReadLRparams(LRparams, max_iter, zTrain[0], polydeg, logp);\n\n    SetNumThreads(LRparams.dim1);\n    //SetNumThreads(4);\n\n    switch(polydeg){\n    case 3:\n        cBit1=  (LRparams.logn - LRparams.log2polyscale);          // 1st iteration\n        cBit2 =  (3*logp+ LRparams. logn - LRparams.log2polyscale);  // 2nd~ iteration\n        logq = cBit1 + (LRparams.max_iter-1)*(cBit2)+ logp + logl;                  // max-bitlength we need\n        break;\n\n    case 7:\n        cBit1=  (LRparams.logn - LRparams.log2polyscale);          // 1st iteration\n        cBit2=  (4*logp+ LRparams.logn - LRparams.log2polyscale);\n        logq= cBit1 + (LRparams.max_iter-1)*(cBit2)+ logp + logl;\n        break;\n    }\n\n\n    freopen(\"cipher training.txt\",\"w\",stdout);\n\n    cout << \"Data dimension with dummy vectors: \" << LRparams.dim1 << \", Number of lines: \" << nLine << endl;\n\n    cout << \"-------------------------------------------------------------\" << endl;\n    cout << \"Key Generation ... (logN,logp,logq, nslots)= (\" ;\n    cout << logN << \",\" << logp << \",\" << logq << \",\" << LRparams.nslots << \")\" <<endl;\n\n    auto start= chrono::steady_clock::now();\n\n    Params params(logN, logq);\n    SecKey secretKey(params);\n    PubKey publicKey(params, secretKey);\n    SchemeAux schemeaux(logN);\n    Scheme scheme(params, publicKey, schemeaux);\n    SchemeAlgo algo(scheme);\n\n    auto end = std::chrono::steady_clock::now();\n    auto diff = end - start;\n    cout << \"KeyGen time= \" << chrono::duration <double, milli> (diff).count()/1000.0 << \" s\" << endl;\n\n\n\n\n    LogReg LR(scheme, secretKey, LRparams);\n    dMat HEtheta_list;\n\n\n\n    int count = 5;\n    for(int k = 0; k < count; ++k){\n\n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << k << \"th Data Encryption ... \" << endl;\n\n        struct rusage usage;\n\n        start= chrono::steady_clock::now();\n\n        Cipher* zTrainCipher = new Cipher[LRparams.dim1];\n\n        LR.EncryptData(zTrainCipher, zTrain[k]);\n\n        end = std::chrono::steady_clock::now();\n        diff = end - start;\n        cout << \"Enc time= \"  << chrono::duration <double, milli> (diff).count()/1000.0 << \"(s), \" ;\n\n        int ret = getrusage(RUSAGE_SELF,&usage);\n        cout<< \"Mem: \" << usage.ru_maxrss/(1024)  << \"(MB)\" << endl;\n\n\n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"HE Logistic Regression ... \"  << endl;\n\n        Cipher* thetaCipher= new Cipher[LRparams.dim1];\n\n        start= chrono::steady_clock::now();\n\n        LR.HElogreg(thetaCipher, zTrainCipher, zTrain[k]);\n\n\n        end = std::chrono::steady_clock::now();\n        diff = end - start;\n        cout << \"Eval time= \"  << chrono::duration <double, milli> (diff).count()/1000.0 << \"(s), \" ;\n\n        ret = getrusage(RUSAGE_SELF,&usage);\n        cout<< \"Mem: \" << usage.ru_maxrss/(1024)  << \"(MB)\" << endl;\n\n\n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"Decryption ... \"  << endl;\n\n        dVec HEtheta(LRparams.dim1, 0.0);\n\n        CZZ* dtheta = new CZZ[LRparams.dim1];\n\n        for(int i=0; i< LRparams.dim1; ++i){\n            dtheta[i] = (scheme.decrypt(secretKey, thetaCipher[i]))[0];\n\n            conv(HEtheta[i], dtheta[i].r);\n            HEtheta[i] = scaledown(HEtheta[i], LRparams.logp);\n            cout << \"[\" << HEtheta[i] << \"] \" ;\n        }\n        cout << \": enc \" << endl;\n\n        getAUC(HEtheta, zTest[k]);\n        HEtheta_list.push_back(HEtheta);\n\n\n\n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"Compare with unenc LR \" << endl;\n        dVec mtheta(LRparams.dim1, 0.0);\n\n        for(int i= 0; i< LRparams.max_iter; i++){\n            LR_poly(mtheta, zTrain[k], LRparams);\n        }\n\n        for(int i= 0; i< LRparams.dim1; i++)\n            cout << \"[\" << mtheta[i] << \"] \" ;\n        cout << \": unenc \" << endl;\n\n        getAUC(mtheta, zTest[k]);\n\n        cout << \"MSE (HELR/non-HELR): \" << getMSE(HEtheta, mtheta) << endl;\n\n\n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"Compare with sigmoid LR \" << endl;\n        dVec mtheta_sig(LRparams.dim1, 0.0);\n\n        for(int i= 0; i< LRparams.max_iter; i++){\n            LR_sigmoid(mtheta_sig, zTrain[k], LRparams);\n        }\n\n        for(int i= 0; i< LRparams.dim1; i++)\n            cout << \"[\" << mtheta_sig[i] << \"] \" ;\n        cout << \": unenc \" << endl;\n\n        getAUC(mtheta_sig, zTest[k]);\n\n        cout << \"MSE (HELR/non-HELR): \" << getMSE(HEtheta, mtheta_sig) << endl;\n\n    }\n    ofstream fout;\n    fout.open(\"beta_HELR.txt\");\n    //! write the beta results in the text file\n    fout << \"-------------------------------------------------------------\" << endl;\n    fout << \"[\" << endl;\n    //        for(int i = 0; i < LRparams.dim1; ++i){\n    //            for(int k = 0; k < count-1; ++k){\n    //                fout << HEtheta_list[k][i] << \",\" ;\n    //            }\n    //            fout << HEtheta_list[count-1][i] << \";\" << endl;\n    //        }\n\n    for (int k=0;k<count;k++) {\n        for(int i = 0; i < LRparams.dim1-1; ++i){\n            fout << HEtheta_list[k][i] << \",\" ;\n        }\n        fout << HEtheta_list[k][LRparams.dim1-1]<<\";\";\n        fout<<\"\\n\";\n    }\n//    for(int i = 0; i < LRparams.dim1; ++i){\n//        for(int k = 0; k < count-1; ++k){\n//            fout << HEtheta_list[k][i] << \",\" ;\n//        }\n//        fout << HEtheta_list[count-1][i] << \";\" << endl;\n//    }\n    //    for(int i = 0; i < HEtheta_list.size(); ++i){\n    //        for(int k = 0; k < HEtheta_list[0].size(); ++k){\n    //            fout << HEtheta_list[i][k] << \",\" ;\n\n    //        }\n    //        //fout << HEtheta_list[i][i] << \";\" << endl;\n    //    }\n    fout << \"];\" << endl;\n    fout.close();\n\n\n    delete[] zTest;\n    delete[] zTrain;\n    ShowTxtToWindowCip();\n\n}\n\nvoid LogisticRegression::testLR()\n{\n    /*if(Argc != 2){\n        cout << \"-------------------------------------------------------------\" << endl;\n        cerr << \"Enter the File and degree of approximation \\t\"  << \"(e.g. $test edin.txt 3) \\n \";\n    }\n    cout<<\"Argc:\"<<Argc<<endl;*/\n//    filename  =  \"data/edin.txt\";\n\n    /*\n    QFile file(filename);\n    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))\n    {\n        qDebug()<<file.errorString();\n    }else{\n        cout<<\"success\"<<endl;\n    }*/\n    dMat  zData;\n    dMat* zTest = new dMat[5];\n    dMat* zTrain = new dMat[5];\n\n    int nLine= readData(zData, filename);\n    /*\n    for(int i=0;i<zData.size();++i){\n        for(int j=0;j<zData[0].size();++j){\n            cout<<zData[i][j]<<\" \";\n        }\n        cout<<endl;\n    }*/\n\n    freopen(\"plaintext training.txt\",\"w\",stdout);\n\n    cout << \"Sample the learning and test data ...\" << endl;\n    cvRandomSamplingData(zTrain, zTest, zData, filename);\n\n\n    //----------------------------------------------------------------\n    // Parameters for Logistic regression\n    //----------------------------------------------------------------\n\n    long logN= 11;\n    long logp= 28;\n    long logl= 10;\n    long logq, cBit1, cBit2;\n    int max_iter;\n    long dim ;\n\n\n    dMat mtheta3_list;\n    dMat mtheta7_list;\n    dMat mtheta_sig_list;\n\n    ofstream fout;\n    fout.open(\"beta_LR.txt\");\n\n\n    for(int k = 0; k < 5; ++k){\n\n\n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"HELR_3 \" << endl;\n\n        //int polydeg = 3;  // degree of approximation polynomial\n\n        struct LRpar LRparams;\n        ReadLRparams(LRparams, max_iter, zTrain[0], polydeg, logp);\n\n        dVec mtheta3(LRparams.dim1, 0.0);\n        for(int i= 0; i< LRparams.max_iter; i++){\n            LR_poly(mtheta3, zTrain[k], LRparams);\n        }\n\n        for(int i= 0; i< LRparams.dim1; i++)\n            cout << \"[\" << mtheta3[i] << \"] \" ;\n        cout  << endl;\n\n        getAUC(mtheta3, zTest[k]);\n        mtheta3_list.push_back(mtheta3);\n\n\n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"HELR_7 \" << endl;\n\n        polydeg = 7;  // degree of approximation polynomial\n\n        struct LRpar LRparams7;\n        ReadLRparams(LRparams7, max_iter, zTrain[0], polydeg, logp);\n\n        dVec mtheta7(LRparams7.dim1, 0.0);\n        for(int i= 0; i< LRparams7.max_iter; i++){\n            LR_poly(mtheta7, zTrain[k], LRparams7);\n        }\n\n        for(int i= 0; i< LRparams7.dim1; i++)\n            cout << \"[\" << mtheta7[i] << \"] \" ;\n        cout  << endl;\n\n        getAUC(mtheta7, zTest[k]);\n        mtheta7_list.push_back(mtheta7);\n\n        dim = LRparams7.dim1;\n\n\n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"sigmoid LR \" << endl;\n        dVec mtheta_sig(LRparams.dim1, 0.0);\n\n        for(int i= 0; i< LRparams.max_iter; i++){\n            LR_sigmoid(mtheta_sig, zTrain[k], LRparams);\n        }\n\n        for(int i= 0; i< LRparams.dim1; i++)\n            cout << \"[\" << mtheta_sig[i] << \"] \" ;\n        cout  << endl;\n\n        getAUC(mtheta_sig, zTest[k]);\n        mtheta_sig_list.push_back(mtheta_sig);\n\n\n        cout << \"-------------------------------------------------------------\" << endl;\n        cout << \"MSE (HELR/non-HELR): \" << getMSE(mtheta3, mtheta_sig) << endl;\n        cout << \"MSE (HELR/non-HELR): \" << getMSE(mtheta7, mtheta_sig) << endl;\n\n    }\n\n\n    //! write the beta results in the text file\n    fout << \"-------------------------------------------------------------\" << endl;\n    fout << \"HELR_3\" << endl<<\"[\\n\";\n\n    for (int k=0;k<5;k++) {\n        for(int i = 0; i < dim-1; ++i){\n            fout << mtheta3_list[k][i] << \",\" ;\n        }\n        fout << mtheta3_list[k][dim-1]<<\";\";\n        fout<<\"\\n\";\n    }\n    fout<<\"]\"<<endl;\n\n    /*\n    for(int i = 0; i < dim; ++i){\n        for(int k = 0; k < 4; ++k){\n            fout << mtheta3_list[k][i] << \",\" ;\n        }\n        fout << mtheta3_list[4][i] << \";\" << endl;\n    }\n    fout<<\"]\"<<endl;\n    */\n    fout << \"-------------------------------------------------------------\" << endl;\n    fout << \"HELR_7\" << endl<<\"[\";\n    for (int k=0;k<5;k++) {\n        for(int i = 0; i < dim-1; ++i){\n            fout << mtheta7_list[k][i] << \",\" ;\n        }\n        fout << mtheta7_list[k][dim-1]<<\";\";\n        fout<<\"\\n\";\n    }\n    fout<<\"]\"<<endl;\n//    for(int i = 0; i < dim; ++i){\n//        for(int k = 0; k < 4; ++k){\n//            fout << mtheta7_list[k][i] << \",\" ;\n//        }\n//        fout << mtheta7_list[4][i] << \";\" << endl;\n//    }\n//    fout << \"]\" << endl;\n\n    fout << \"-------------------------------------------------------------\" << endl;\n    fout << \"LR\" << endl<<\"[\";\n    for (int k=0;k<5;k++) {\n        for(int i = 0; i < dim-1; ++i){\n            fout << mtheta_sig_list[k][i] << \",\" ;\n        }\n        fout << mtheta_sig_list[k][dim-1]<<\";\";\n        fout<<\"\\n\";\n    }\n    fout << \"]\" << endl;\n//    for(int i = 0; i < dim; ++i){\n//        for(int k = 0; k < 4; ++k){\n//            fout << mtheta_sig_list[k][i] << \",\" ;\n//        }\n//        fout << mtheta_sig_list[4][i] << \";\" << endl;\n//    }\n//    fout<<\"]\"<<endl;\n    fout.close();\n\n    fout << \"-------------------------------------------------------------\" << endl;\n\n    delete[] zTest;\n    delete[] zTrain;\n\n    ShowTxtToWindow();\n}\n\nvoid LogisticRegression::on_pushButton_2_clicked()\n{\n    testLR();\n}\n\nvoid LogisticRegression::ShowTxtToWindow()//显示文本文件中的内容\n{\n    QString fileName = \"plaintext training.txt\";\n\n    if(!fileName.isEmpty())\n    {\n        QFile *file = new QFile;\n        file->setFileName(fileName);\n        bool ok = file->open(QIODevice::ReadOnly);\n        if(ok)\n        {\n            QTextStream in(file);\n            ui->plainResult->setText(in.readAll());\n            file->close();\n            delete file;\n        }\n        else\n        {\n            QMessageBox::information(this,\"错误信息\",\"打开文件:\" + file->errorString());\n            return;\n        }\n    }\n}\n\nvoid LogisticRegression::ShowTxtToWindowCip()\n{\n    QString fileName = \"cipher training.txt\";\n\n    if(!fileName.isEmpty())\n    {\n        QFile *file = new QFile;\n        file->setFileName(fileName);\n        bool ok = file->open(QIODevice::ReadOnly);\n        if(ok)\n        {\n            QTextStream in(file);\n            ui->cResult->setText(in.readAll());\n            file->close();\n            delete file;\n        }\n        else\n        {\n            QMessageBox::information(this,\"错误信息\",\"打开文件:\" + file->errorString());\n            return;\n        }\n    }\n}\n\nvoid LogisticRegression::on_return_2_clicked()\n{\n    MainWindow *win = new MainWindow;\n    this->hide();\n    win->show();\n}\n\nvoid LogisticRegression::on_file_clicked()\n{\n    //定义文件对话框类\n    QFileDialog *fileDialog = new QFileDialog(this);\n    //定义文件对话框标题\n    fileDialog->setWindowTitle(tr(\"选择数据集\"));\n    //设置默认文件路径\n    fileDialog->setDirectory(\".\");\n    //设置可以选择多个文件,默认为只能选择一个文件QFileDialog::ExistingFiles\n    fileDialog->setFileMode(QFileDialog::ExistingFiles);\n    //设置视图模式\n    fileDialog->setViewMode(QFileDialog::Detail);\n    //打印所有选择的文件的路径\n    QStringList fileNames;\n    if(fileDialog->exec())\n    {\n        fileNames = fileDialog->selectedFiles();\n    }\n\n    QString QString_fileNames = fileNames.join(\",\");\n\n    QString curPath = QDir::currentPath();\n    QString relPath = QString_fileNames.mid(curPath.length()+1);\n\n    QByteArray ba = relPath.toLatin1();\n    strcpy(filename,ba.data());\n    cout<<filename<<endl;\n}\n\nvoid LogisticRegression::on_comboBox_activated(const QString &arg1)\n{\n    QMap<QString, int> map_polydeg;\n    map_polydeg.insert(\"3(默认)\",3);\n    map_polydeg.insert(\"7\",7);\n    polydeg = map_polydeg[arg1];\n}\n\nvoid LogisticRegression::on_pushButton_clicked()\n{\n    testHELR();\n}\n", "meta": {"hexsha": "84100726ce6599424aed3fd5836c98f6f521b49e", "size": 16314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/logisticregression.cpp", "max_stars_repo_name": "YiJingGuo/HEBenchmark", "max_stars_repo_head_hexsha": "3154b4b638b32c97d307c598a2dd2fbf0a543de2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2019-07-27T10:32:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-17T12:32:30.000Z", "max_issues_repo_path": "src/logisticregression.cpp", "max_issues_repo_name": "YiJingGuo/HEBenchmark", "max_issues_repo_head_hexsha": "3154b4b638b32c97d307c598a2dd2fbf0a543de2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/logisticregression.cpp", "max_forks_repo_name": "YiJingGuo/HEBenchmark", "max_forks_repo_head_hexsha": "3154b4b638b32c97d307c598a2dd2fbf0a543de2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-07-28T03:57:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T09:24:52.000Z", "avg_line_length": 27.9349315068, "max_line_length": 109, "alphanum_fraction": 0.487924482, "num_tokens": 4462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.41446730253198383}}
{"text": "#include \"geodb/klee.hpp\"\n\n#include \"geodb/interval.hpp\"\n#include \"geodb/utility/range_utils.hpp\"\n\n#include <boost/functional/hash.hpp>\n\n#include <memory>\n\nnamespace geodb {\n\nnamespace {\n\nusing interval_t = interval<double>;\n\nsize_t log2_ceil(size_t value) {\n    geodb_assert(value != 0, \"invalid value\");\n\n    size_t log2 = 0;\n    value--;\n    while (value != 0) {\n        ++log2;\n        value /= 2;\n    }\n    return log2;\n}\n\nclass segment_tree {\n    struct node {\n        /// The interval that this node represents.\n        interval_t interval;\n\n        /// The current width of the union of all intervals\n        /// active in the subtree rooted at this node.\n        double union_width = 0;\n\n        /// Number of active intervals that contain this interval.\n        size_t count = 0;\n\n        /// True if this node is a leaf node.\n        bool leaf = false;\n    };\n\npublic:\n    /// Construct a new, empty segment tree from the given iterator range.\n    ///\n    /// The range must contain the Universe of endpoints, i.e. every\n    /// possible interval end point.\n    /// The points must be sorted in ascending order and must be unique.\n    /// The range must have at least two points.\n    template<typename RndIter>\n    segment_tree(RndIter begin, RndIter end)\n    {\n        reset(begin, end);\n    }\n\n    /// Replaces the structure of this tree using the points\n    /// in the given sorted range.\n    /// Has the same requirements and effects as the constructor,\n    /// but reuses the allocated memory.\n    template<typename RndIter>\n    void reset(RndIter begin, RndIter end) {\n        geodb_assert(std::distance(begin, end) >= 2,\n                     \"Must have at least two endpoints\");\n\n        // Allocate enough space for a complete binary tree.\n        size_t leaves = std::distance(begin, end) - 1;\n        size_t full_leaves = 1 << log2_ceil(leaves);\n        size_t max_size = full_leaves * 2 - 1;\n\n        m_nodes.resize(max_size);\n        build(at(0), begin, end - 1);\n    }\n\n    /// Sets the given interval to \"active\", i.e. counting it\n    /// in the calculation of the union width.\n    /// Only intervals with endpoints in the previously registered universe\n    /// can be inserted.\n    void insert(const interval_t& interval) {\n        insert(at(0), interval);\n    }\n\n    /// Removes the given interval, no longer counting it\n    /// in the calculation of the union width.\n    /// Only intervals that have previously been inserted can be removed.\n    void remove(const interval_t& interval) {\n        remove(at(0), interval);\n    }\n\n    double union_width() const {\n        return at(0).union_width;\n    }\n\nprivate:\n    /// Recursive build function.\n    /// Both begin and end are valid iterators, i.e. its an inclusive range.\n    /// All intervals [p1, p2] where p1, p2 are in the original input sequence\n    /// will be represented by leaf nodes.\n    template<typename Iter>\n    void build(node& n, Iter begin, Iter end) {\n        geodb_assert(begin != end, \"Range is empty\");\n\n        n.count = 0;\n        n.union_width = 0;\n        n.leaf = (begin + 1 == end);\n        if (n.leaf) {\n            n.interval = interval_t(*begin, *end);\n        } else {\n            node& l = left(n);\n            node& r = right(n);\n\n            Iter mid = begin + (end - begin) / 2;\n            build(l, begin, mid);\n            build(r, mid, end);\n            n.interval = interval_t(l.interval.begin(), r.interval.end());\n        }\n    }\n\n    void insert(node& n, const interval_t& interval) {\n        if (interval.contains(n.interval)) {\n            n.count += 1;\n            if (n.count == 1) {\n                n.union_width = n.interval.end() - n.interval.begin();\n            }\n        } else {\n            geodb_assert(!n.leaf, \"must not be a leaf\");\n\n            node& l = left(n);\n            node& r = right(n);\n\n            if (go_left(l.interval, interval)) {\n                insert(l, interval);\n            }\n            if (go_right(r.interval, interval)) {\n                insert(r, interval);\n            }\n            if (n.count == 0) {\n                n.union_width = l.union_width + r.union_width;\n            }\n        }\n    }\n\n    void remove(node& n, const interval_t& interval) {\n        if (interval.contains(n.interval)) {\n            n.count -= 1;\n            if (n.count == 0) {\n                n.union_width = n.leaf ? 0\n                                       : left(n).union_width + right(n).union_width;\n            }\n        } else {\n            geodb_assert(!n.leaf, \"must not be a leaf\");\n\n            node& l = left(n);\n            node& r = right(n);\n\n            if (go_left(l.interval, interval)) {\n                remove(l, interval);\n            }\n            if (go_right(r.interval, interval)) {\n                remove(r, interval);\n            }\n            if (n.count == 0) {\n                n.union_width = l.union_width + r.union_width;\n            }\n        }\n    }\n\n    bool go_left(const interval_t& left, const interval_t& interval) const {\n        return interval.begin() < left.end();\n    }\n\n    bool go_right(const interval_t& right, const interval_t& interval) const {\n        return interval.end() > right.begin();\n    }\n\n    node& left(node& n) {\n        geodb_assert(!n.leaf, \"n has no children\");\n        return at(index(n) * 2 + 1);\n    }\n\n    node& right(node& n) {\n        geodb_assert(!n.leaf, \"n has no children\");\n        return at(index(n) * 2 + 2);\n    }\n\n    node& at(size_t index) {\n        geodb_assert(index < m_nodes.size(), \"index out of bounds\");\n        return m_nodes[index];\n    }\n\n    const node& at(size_t index) const {\n        geodb_assert(index < m_nodes.size(), \"index out of bounds\");\n        return m_nodes[index];\n    }\n\n    size_t index(node& n) {\n        return &n - m_nodes.data();\n    }\n\nprivate:\n    std::vector<node> m_nodes;\n};\n\nenum event_type {\n    open, close\n};\n\nstruct event2d {\n    event_type type;\n    double x;\n    interval_t y;\n\n    event2d(event_type type, double x, const interval_t& y)\n        : type(type)\n        , x(x)\n        , y(y)\n    {}\n\n    bool operator<(const event2d& other) const {\n        if (x == other.x) {\n            return type < other.type;\n        }\n        return x < other.x;\n    }\n};\n\nstruct event3d {\n    event_type type;\n    double x;\n    rect2d r;\n\n    event3d(event_type type, double x, const rect2d& r)\n        : type(type)\n        , x(x)\n        , r(r)\n    {}\n\n    bool operator<(const event3d& other) const {\n        if (x == other.x) {\n            return type < other.type;\n        }\n        return x < other.x;\n    }\n};\n\n} // namespace\n\n/// Constructs the segment tree with the universe of all (unique)\n/// rectangle y corner points.\nstatic segment_tree build_segment_tree(const std::vector<rect2d>& rects) {\n    std::vector<double> yvalues;\n    yvalues.reserve(rects.size() * 2);\n    for (const rect2d& rect : rects) {\n        if (!rect.empty()) {\n            yvalues.push_back(rect.min().y());\n            yvalues.push_back(rect.max().y());\n        }\n    }\n\n    std::sort(yvalues.begin(), yvalues.end());\n    yvalues.erase(std::unique(yvalues.begin(), yvalues.end()), yvalues.end());\n\n    return segment_tree(yvalues.begin(), yvalues.end());\n}\n\nstatic std::vector<event2d> rectangle_events(const std::vector<rect2d>& rects) {\n    std::vector<event2d> events;\n    events.reserve(2 * rects.size());\n    for (const rect2d& rect : rects) {\n        if (!rect.empty()) {\n            interval_t y(rect.min().y(), rect.max().y());\n            events.emplace_back(open, rect.min().x(), y);\n            events.emplace_back(close, rect.max().x(), y);\n        }\n    }\n\n    std::sort(events.begin(), events.end());\n    return events;\n}\n\nstatic std::vector<event3d> rectangle_events(const std::vector<rect3d>& rects) {\n    std::vector<event3d> events;\n    events.reserve(2 * rects.size());\n    for (const rect3d& rect : rects) {\n        if (!rect.empty()) {\n            rect2d rect2(vector2d(rect.min().y(), rect.min().z()),\n                         vector2d(rect.max().y(), rect.max().z()));\n            events.emplace_back(open, rect.min().x(), rect2);\n            events.emplace_back(close, rect.max().x(), rect2);\n        }\n    }\n\n    std::sort(events.begin(), events.end());\n    return events;\n}\n\ndouble union_area(const std::vector<rect2d>& rects) {\n    if (rects.size() == 0) {\n        return 0;\n    }\n\n    segment_tree tree = build_segment_tree(rects);\n    std::vector<event2d> events = rectangle_events(rects);\n\n    double area = 0.0;\n    double lastx = 0;\n    for (const event2d& e : events) {\n        // Works even for the first iteration because tree.union_width() will be 0.\n        area += (e.x - lastx) * tree.union_width();\n        if (e.type == open) {\n            tree.insert(e.y);\n        } else {\n            tree.remove(e.y);\n        }\n        lastx = e.x;\n    }\n    return area;\n}\n\ndouble union_area(const std::vector<rect3d>& rects) {\n    if (rects.size() == 0) {\n        return 0;\n    }\n\n    std::vector<event3d> events = rectangle_events(rects);\n    std::vector<rect2d> active;\n    active.reserve(rects.size());\n\n    double area = 0;\n    double lastx = 0;\n    for (const event3d& e : events) {\n        area += (e.x - lastx) * union_area(active);\n        if (e.type == open) {\n            active.push_back(e.r);\n        } else {\n            auto pos = std::find(active.begin(), active.end(), e.r);\n            geodb_assert(pos != active.end(), \"rectangle must be active\");\n            active.erase(pos);\n        }\n        lastx = e.x;\n    }\n\n    return area;\n}\n\n} // namespace geodb\n", "meta": {"hexsha": "60a712f4a3bd08ba0afe2ca522dd6ce1dbb2a69e", "size": 9541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/geodb/klee.cpp", "max_stars_repo_name": "mbeckem/msc", "max_stars_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/geodb/klee.cpp", "max_issues_repo_name": "mbeckem/msc", "max_issues_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/geodb/klee.cpp", "max_forks_repo_name": "mbeckem/msc", "max_forks_repo_head_hexsha": "93e71ba163a7ffef4eec3e83934fa793f3f50ff6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4956772334, "max_line_length": 84, "alphanum_fraction": 0.5528770569, "num_tokens": 2354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.41446730253198383}}
{"text": "#include \"Solver.h\"\n\n#include \"RigidBodyMain.h\"\n#include \"ChronoTimer.h\"\n\n#ifndef EIGEN_NO_STATIC_ASSERT\n#define EIGEN_NO_STATIC_ASSERT\n#endif\n\n#ifdef REDMAX_PARDISO\n#include <Eigen/PardisoSupport>\n#endif\n\n#include <Eigen/SparseCholesky>\t\n#include <Eigen/OrderingMethods>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <fstream>\n#include <iomanip>\n#include <chrono>\nint count = 0;\n\nvoid Solver::loadMSparse(std::unique_ptr<StateSolve>& SS, std::unique_ptr<LinkageSystem>& LS, std::unique_ptr<State>& S)\n{\n\tint numObj = (int)LS->blocks.size();\n\n\tint index;\n\tstd::shared_ptr<Block> block;\n\tfor (int i = 0; i < LS->blocks.size(); ++i)\n\t{\n\t\tblock = LS->blocks[i].second;\n\t\tindex = block->joint->jindex;\n\n\t\tfor (int j = 0; j < 6; ++j)\n\t\t{\n\t\t\tfor (int k = 0; k < 6; ++k)\n\t\t\t{\n\t\t\t\tif (S->M[index](j, k) != 0)\n\t\t\t\t{\n\t\t\t\t\tSS->LHSlist.push_back(Eigen::Triplet<double>(index * 6 + j, index * 6 + k, S->M[index](j, k) * (1 + SS->alpha*SS->h)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Solver::computeRHS(std::unique_ptr<StateSolve>& SS, const std::unique_ptr<LinkageSystem>& LS, const std::unique_ptr<State>& S)\n{\n\tMatrix6d spcp = Matrix6d::Zero();\n\tVector6d bodyForces = Vector6d::Zero();\n\tint i;\n\tfor (int index = 0; index < LS->blocks.size(); ++index)\n\t{\n\t\tif (simtype == simType::PCG)\n\t\t\ti = S->jindex[index];\n\t\telse\n\t\t\ti = LS->blocks[index].second->joint->jindex;\n\n\t\t// Define the spatial cross product matrix\n\t\tspcp.block<3, 3>(0, 0) << Rigid::bracket3(S->v.segment<3>(i * 6));\n\t\tspcp.block<3, 3>(3, 3) << spcp.block<3, 3>(0, 0);\n\n\t\t// Define body forces\n\t\tbodyForces.segment<3>(3) << S->E[i].block<3, 3>(0, 0).transpose()*SS->grav*S->mass[i];\n\n\t\t// Compute RHS vector\n\t\tif (SS->fn.size() != 0)\n\t\t{\n\t\t\tSS->fn.segment<6>(i * 6) += S->M[i] * S->v.segment<6>(i * 6) + SS->h*(spcp.transpose()*S->M[i] * S->v.segment<6>(i * 6) + bodyForces);\n\t\t}\n\n\t\t// Compute force vector\n\t\tif (SS->f.size() != 0)\n\t\t{\n\t\t\tSS->f.segment<6>(i * 6) += spcp.transpose()*S->M[i] * S->v.segment<6>(i * 6) + bodyForces;\n\t\t}\n\t}\n}\n\nvoid Solver::pcdSaad2003(Eigen::VectorXd &result, const Eigen::VectorXd &LHSx0, const Eigen::VectorXd &b, std::unique_ptr<StateSolve> &SS, std::unique_ptr<LinkageSystem> &LS, std::unique_ptr<State> &S, std::shared_ptr<State::local_mt> lmt, double tol, int maxit)\n{\n\t//function[x, iter, xs, rs] = pcgSaad2003(A, b, tol, maxit, M, x0)\n\t//\t% pcgSaad2003 Algorithm 9.1 from[Saad 2003]\n\tstd::vector<double> rs;\n\n\tEigen::VectorXd xj = S->qdot;\n\tEigen::VectorXd rj = b - LHSx0;\n\tEigen::VectorXd zj = ConstraintJoint::computeMinv_x(rj, SS, LS, S, lmt);\n\n\t//if (zj.hasNaN())\n\t//\tstd::cout << \"minv init\" << std::endl;\n\n\tEigen::VectorXd pj = zj;\n\tdouble tolsq = tol * tol;\n\tdouble res1 = rj.dot(rj);\n\tdouble res0 = res1;\n\tEigen::VectorXd xs = xj;\n\trs.push_back(res1);\n\n\tauto start = std::chrono::steady_clock::now();\n\tEigen::VectorXd J_p;\n\tEigen::VectorXd q;\n\tEigen::VectorXd Apj;\n\tEigen::VectorXd rj1;\n\tEigen::VectorXd zj1;\n\tint j = 1;\n\tfor (; j < maxit; ++j)\n\t{\n\t\tConstraintJoint::computeJ_x(J_p, pj, SS, LS, S);\n\t\tApj = ConstraintJoint::computeJT_x(\n\t\t\tConstraintJoint::computeLHS_x(J_p, SS, LS, S),\n\t\t\tSS, LS, S, lmt);\n\n\t\t//if (J_p.hasNaN())\n\t\t//\tstd::cout << \"J * qd\" << std::endl;\n\t\t//if (Apj.hasNaN())\n\t\t//\tstd::cout << \"LHS or JT\" << std::endl;\n\n\t\tq = S->q + SS->h * pj;\n\t\t// Joint stiffness and damping\n\t\tConstraintJoint::computeStiffnessDampingJoint(Apj, pj, S->q, SS, LS, S);\n\n\t\t//if (Apj.hasNaN())\n\t\t//\tstd::cout << \"stiffdampjoint\" << std::endl;\n\n\t\tdouble aj = rj.dot(zj) / (Apj).dot(pj);\n\t\tif ((Apj).dot(pj) == 0)\n\t\t{\n\t\t\txj = S->qdot;\n\t\t\tbreak;\n\t\t}\n\t\txj = xj + aj * pj;\n\t\trj1 = rj - aj * Apj;\n\t\tres1 = rj1.dot(rj1);\n\t\trs.push_back(res1);\n\t\tif (res1 < tolsq*res0)\n\t\t\tbreak;\n\n\t\tzj1 = ConstraintJoint::computeMinv_x(rj1, SS, LS, S, lmt);\n\n\t\t//if (zj1.hasNaN())\n\t\t//\tstd::cout << \"minv\" << std::endl;\n\t\t//std::cout << j << std::endl;\n\n\t\tdouble bj = rj1.dot(zj1) / rj.dot(zj);\n\t\tpj = zj1 + bj * pj;\n\t\trj = rj1;\n\t\tzj = zj1;\n\t}\n\tauto end = std::chrono::steady_clock::now();\n\tauto diff = end - start;\n\tauto time = std::chrono::duration<double, std::nano>(diff).count();\n\ttrackLastTimestep.time_in_solve = time;\n\ttrackLastTimestep.num_iterations = j;\n\n\tif (false)//std::abs(S->t - 1.01)) < 1e-5)\n\t{\n\t\tfor (int i = 0; i < rs.size(); ++i)\n\t\t{\n\t\t\tstd::cout << rs[i] << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"---------\" << j << std::endl;\n\t}\n\tresult = xj;\n}\n\nvoid Solver::pcdSaad2003_unopt(Eigen::VectorXd & result, const Eigen::VectorXd & LHSx0, const Eigen::VectorXd & b, std::unique_ptr<StateSolve>& SS, std::unique_ptr<LinkageSystem>& LS, std::unique_ptr<State>& S, std::shared_ptr<State::local_mt> lmt, double tol, int maxit)\n{\n\t//function[x, iter, xs, rs] = pcgSaad2003(A, b, tol, maxit, M, x0)\n\t//\t% pcgSaad2003 Algorithm 9.1 from[Saad 2003]\n\tstd::vector<double> rs;\n\n\tEigen::VectorXd xj = S->qdot;\n\tEigen::VectorXd rj = b - LHSx0;\n\tEigen::VectorXd zj = ConstraintJoint::computeMinv_x(rj, SS, LS, S, lmt);\n\tEigen::VectorXd pj = zj;\n\tdouble tolsq = tol * tol;\n\tdouble res1 = rj.dot(rj);\n\tdouble res0 = res1;\n\tEigen::VectorXd xs = xj;\n\trs.push_back(res1);\n\n\tauto start = std::chrono::steady_clock::now();\n\tEigen::VectorXd J_p;\n\tEigen::VectorXd q;\n\tEigen::VectorXd Apj;\n\tEigen::VectorXd rj1;\n\tEigen::VectorXd zj1;\n\tint j = 1;\n\tfor (; j < maxit; ++j)\n\t{\n\t\tConstraintJoint::computeJ_x_unopt(J_p, pj, SS, LS, S);\n\t\tApj = ConstraintJoint::computeJT_x_unopt(\n\t\t\tConstraintJoint::computeLHS_x_unopt(J_p, SS, LS, S),\n\t\t\tSS, LS, S, lmt);\n\n\t\tq = S->q + SS->h * pj;\n\t\t// Joint stiffness and damping\n\t\tConstraintJoint::computeStiffnessDampingJoint_unopt(Apj, pj, S->q, SS, LS, S);\n\n\t\tdouble aj = rj.dot(zj) / (Apj).dot(pj);\n\t\tif ((Apj).dot(pj) == 0)\n\t\t{\n\t\t\txj = S->qdot;\n\t\t\tbreak;\n\t\t}\n\t\txj = xj + aj * pj;\n\t\trj1 = rj - aj * Apj;\n\t\tres1 = rj1.dot(rj1);\n\t\trs.push_back(res1);\n\t\tif (res1 < tolsq*res0)\n\t\t\tbreak;\n\n\t\tzj1 = ConstraintJoint::computeMinv_x_unopt(rj1, SS, LS, S, lmt);\n\t\tdouble bj = rj1.dot(zj1) / rj.dot(zj);\n\t\tpj = zj1 + bj * pj;\n\t\trj = rj1;\n\t\tzj = zj1;\n\t}\n\tauto end = std::chrono::steady_clock::now();\n\tauto diff = end - start;\n\tauto time = std::chrono::duration<double, std::nano>(diff).count();\n\ttrackLastTimestep.time_in_solve = time;\n\ttrackLastTimestep.num_iterations = j;\n\n\tif (false)\n\t{\n\t\tfor (int i = 0; i < rs.size(); ++i)\n\t\t{\n\t\t\tstd::cout << rs[i] << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"---------\" << j << std::endl;\n\t}\n\tresult = xj;\n}\n#ifdef REDMAX_PARDISO\nEigen::VectorXd Solver::solvePardiso(std::unique_ptr<StateSolve>& SS, std::unique_ptr<LinkageSystem>& LS, std::unique_ptr<State>& S)\n{\n\t//ChronoTimer ctime(\"ldlt\", 5);\n\t//ChronoTimer ltime(\"load\", 7);\n\t//ctime.tic(0);\n\t//ctime.tic(1);\n\t// Preprocessing, eliminate matrix resizing\n\t//ltime.tic(0);\n \tint constraints = ConstraintJoint::getConstraintNumReduced(LS);\n\tint additional_constraints = ConstraintJoint::getConstraintNumAdditnl(LS);\n\tint numObj = (int)LS->blocks.size();\n\n\t// Initialize containers\n\tSS->J = Eigen::MatrixXd::Zero(numObj * 6, constraints); // jacobian\n\tSS->Jd = Eigen::MatrixXd::Zero(numObj * 6, constraints); // jacobian time derivative\n\tSS->f = Eigen::VectorXd::Zero(numObj * 6); // load with fm\n\tSS->fr = Eigen::VectorXd::Zero(constraints);\n\tSS->gm = Eigen::VectorXd::Zero(additional_constraints);\n\tSS->Dmlist.clear();\n\tSS->Kmlist.clear();\n\tSS->LHSlist.clear();\n\tSS->Jlist.clear();\n\tSS->Jdlist.clear();\n\tSS->JTlist.clear();\n\tSS->LHSGlist.clear();\n\tSS->Gmlist.clear();\n\tSS->row = 0;\n\n\t// init extra constraints for joint solver\n\tfor (int i = 0; i < LS->constraints.size(); ++i)\n\t{\n\t\tLS->constraints[i]->update(SS, LS, S);\n\t}\n\t//if (SS->f.hasNaN())\n\t//\tstd::cout << \"0 f\" << std::endl;\n\n\t// Compute fn and M\n\tSS->alpha = 0;\n\tint index;\n\tdouble value;\n\tstd::shared_ptr<Block> block;\n\tMatrix6d spcp = Matrix6d::Zero();\n\tVector6d bodyForces = Vector6d::Zero();\n\tfor (int i = 0; i < LS->blocks.size(); ++i)\n\t{\n\t\tblock = LS->blocks[i].second;\n\t\tindex = block->joint->jindex;\n\n\t\tfor (int r = 0; r < 6; ++r)\n\t\t{\n\t\t\tvalue = S->M[index](r, r) * (1 + SS->alpha*SS->h);\n\t\t\tif (std::abs(value) > THRESHOLD)\n\t\t\t\tSS->LHSlist.push_back(Eigen::Triplet<double>(index * 6 + r, index * 6 + r, value));\n\t\t}\n\n\t\t// Define the spatial cross product matrix\n\t\tspcp.block<3, 3>(0, 0) << Rigid::bracket3(S->v.segment<3>(i * 6));\n\t\tspcp.block<3, 3>(3, 3) << spcp.block<3, 3>(0, 0);\n\n\t\t// Define body forces\n\t\tbodyForces.segment<3>(3) << S->E[i].block<3, 3>(0, 0).transpose()*SS->grav*S->mass[i];\n\n\t\t// Compute force vector\t\t\t\t\n\t\tSS->f.segment<6>(i * 6) += spcp.transpose()*S->M[i] * S->v.segment<6>(i * 6) + bodyForces;\n\n\t\t// Handle joint stiffness\n\t\t// update is in constraintJoint class for CG solver\n\t\tint ci = block->joint->constraint_index;\n\t\tfor (int cnum = 0; cnum < block->joint->constraintNum; ++cnum)\n\t\t{\n\t\t\tSS->fr[ci + cnum] -= block->joint->k*(S->q[ci + cnum] - block->joint->q0[cnum]);\n\n\t\t\t//if(isnan(S->q[ci + cnum]))\n\t\t\t//\tstd::cout << \"q\" << std::endl;\n\t\t}\n\t}\n\n\t// Load joint constraints\n\tConstraintJoint::update(SS, LS, S);\n\n\t// solve\n\tEigen::SparseMatrix<double> Mr(constraints, constraints);\n\tEigen::SparseMatrix<double> Mrtilde(constraints, constraints);\n\tEigen::VectorXd frtilde;\n\n\tEigen::SparseMatrix<double> J(numObj * 6, constraints);\n\tJ.setFromTriplets(SS->Jlist.begin(), SS->Jlist.end());\n\tEigen::SparseMatrix<double> JT(constraints, numObj * 6);\n\tJT.setFromTriplets(SS->JTlist.begin(), SS->JTlist.end());\n\tEigen::SparseMatrix<double> Jdot(numObj * 6, constraints);\n\tJdot.setFromTriplets(SS->Jdlist.begin(), SS->Jdlist.end());\n\n\tEigen::SparseMatrix<double> LHS(numObj * 6, numObj * 6);\n\tLHS.setFromTriplets(SS->LHSlist.begin(), SS->LHSlist.end());\n\tEigen::SparseMatrix<double> Km(numObj * 6, numObj * 6);\n\tKm.setFromTriplets(SS->Kmlist.begin(), SS->Kmlist.end());\n\tEigen::SparseMatrix<double> Dm(numObj * 6, numObj * 6);\n\tDm.setFromTriplets(SS->Dmlist.begin(), SS->Dmlist.end());\n\n\tEigen::SparseMatrix<double> KDMm(numObj * 6, numObj * 6);\n\tKDMm = LHS + SS->h * SS->h * Km + SS->h * Dm + SS->h * SS->bDm;\n\tEigen::SparseMatrix<double> KDr(constraints, constraints);\n\tKDr = SS->h * SS->Dr + SS->h * SS->h * SS->Kr;\n\n\t//Mr_sparse = 0.5*(Mr_sparse + Eigen::SparseMatrix<double>(Mr_sparse.transpose()));\n\t//Mrtilde_sparse = Mr_sparse + KDr_sparse;\n\tMr = JT * LHS * J;\n\tMrtilde = JT * KDMm * J + KDr;\n\n\tSS->fr += JT * (SS->f - LHS * (Jdot * S->qdot));\n\tfrtilde = Mr * S->qdot + SS->h * SS->fr;\n\n\t// solve for velocity\n\tauto start = std::chrono::steady_clock::now();\n\tif (additional_constraints == 0)\n\t{\n\t\tEigen::PardisoLDLT< Eigen::SparseMatrix<double>> solver;\n\t\tS->qdot = solver.compute(Mrtilde).solve(frtilde);\n\t}\n\telse\n\t{\n\t\tEigen::SparseMatrix<double> Gm(additional_constraints, numObj * 6);\n\t\tGm.setFromTriplets(SS->Gmlist.begin(), SS->Gmlist.end());\n\t\t//Eigen::SparseMatrix<double> GmT(numObj * 6, numObj * 6);\n\t\t//GmT.setFromTriplets(SS->GmTlist.begin(), SS->GmTlist.end());\n\n\t\tEigen::SparseMatrix<double> Gr = Gm * J;\n\t\t//Eigen::SparseMatrix<double> GrT = JT * GmT;\n\n\t\tstd::vector<Eigen::Triplet<double> > tripletList;\n\t\ttripletList.reserve(Mrtilde.nonZeros() + Gr.nonZeros() + Gr.nonZeros());\n\t\tfor (int k = 0; k < Mrtilde.outerSize(); ++k)\n\t\t{\n\t\t\t// Mrtilde\n\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(Mrtilde, k); it; ++it)\n\t\t\t{\n\t\t\t\ttripletList.push_back(Eigen::Triplet<double>(it.row(), it.col(), it.value()));\n\t\t\t}\n\t\t}\n\t\tfor (int k = 0; k < Gr.outerSize(); ++k)\n\t\t{\n\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(Gr, k); it; ++it)\n\t\t\t{ \n\t\t\t\t// Gr\n\t\t\t\ttripletList.push_back(Eigen::Triplet<double>(it.row() + Mrtilde.rows(), it.col(), it.value()));\n\t\t\t\t// GrT\n\t\t\t\ttripletList.push_back(Eigen::Triplet<double>(it.col(), it.row() + Mrtilde.rows(), it.value()));\n\t\t\t}\n\t\t}\n\t\tEigen::SparseMatrix<double> LHSG(constraints + additional_constraints, constraints + additional_constraints);\n\t\tLHSG.setFromTriplets(tripletList.begin(), tripletList.end());\n\n\t\tEigen::VectorXd frG = Eigen::VectorXd::Zero(constraints + additional_constraints);\n\t\tfrG.segment(0, frtilde.rows()) = frtilde;\n\t\tfrG.segment(frtilde.rows(), additional_constraints) = -SS->gm * SS->baumgarte[2];\n\n\t\tEigen::PardisoLU< Eigen::SparseMatrix<double>> solver;\n\t\tEigen::VectorXd result = solver.compute(LHSG).solve(frG);\n\t\tS->qdot = result.segment(0,constraints);\n\n\t\tif (false)//std::abs(S->t - 1.01)) < 1e-5)\n\t\t{\n\t\t\t// name of file\n\t\t\tstd::string decimals = std::to_string((int)(100 * (S->t - (int)std::floor(S->t))));\n\t\t\tif (decimals.size() == 1)\n\t\t\t\tdecimals = \"0\" + decimals;\n\t\t\tstd::string filename = \"../matricies/redmax_\" + std::to_string(LS->blocks.size()) + \"t\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\t\t//std::string filename = \"../matricies/redmax_\" + std::to_string(LS->blocks.size()) + \"Preconditioner_noblkdiag_t\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\t\tstd::ofstream outfile(filename, std::ios::out);\n\t\t\toutfile << std::setprecision(16);\n\n\t\t\t//ConstraintJoint::preprocess_preconditioner(SS, LS, S, true);\n\t\t\t//Eigen::MatrixXd preconditioner = Eigen::MatrixXd::Zero(constraints, constraints);\n\t\t\t//Eigen::VectorXd temp;\n\t\t\t//Eigen::VectorXd z;\n\t\t\t//for (int k = 0; k < constraints; ++k)\n\t\t\t//{\n\t\t\t//\ttemp = Eigen::VectorXd::Zero(constraints);\n\t\t\t//\ttemp[k] = 1.0;\n\t\t\t//\tz = ConstraintJoint::computeMinv_x(temp, SS, LS, S);\n\t\t\t//\tfor (int l = 0; l < constraints; ++l)\n\t\t\t//\t{\n\t\t\t//\t\tpreconditioner(l, k) = z[l];\n\t\t\t//\t}\n\t\t\t//}\n\n\t\t\toutfile << \"h = \" << SS->h << \";\\n\" << std::endl;\n\t\t\taddSparseToFile(outfile, \"Mr_c\", Mr);\n\t\t\taddSparseToFile(outfile, \"Mrtilde_c\", Mrtilde);\n\t\t\taddSparseToFile(outfile, \"Mm_c\", LHS);\n\t\t\taddSparseToFile(outfile, \"J_c\", J);\n\t\t\taddSparseToFile(outfile, \"Jdot_c\", Jdot);\n\n\t\t\tEigen::SparseMatrix<double> bDm = Dm + SS->bDm;\n\t\t\taddSparseToFile(outfile, \"Dm_c\", bDm);\n\t\t\t//addSparseToFile(outfile, \"MG_c\", LHSGt);\n\t\t\t//addSparseToFile(outfile, \"Gr_c\", Gr);\n\t\t\taddSparseToFile(outfile, \"Km_c\", Km);\n\t\t\taddSparseToFile(outfile, \"LHSG_c\", LHSG);\n\t\t\taddSparseToFile(outfile, \"Gm_c\", Gm);\n\t\t\taddSparseToFile(outfile, \"Dr_c\", SS->Dr);\n\t\t\taddSparseToFile(outfile, \"Kr_c\", SS->Kr);\n\t\t\taddSparseToFile(outfile, \"Jmr_c\", SS->J);\n\t\t\taddSparseToFile(outfile, \"Jdotmr_c\", SS->Jd);\n\t\t\taddVectorToFile(outfile, \"f_c\", SS->f);\n\t\t\taddVectorToFile(outfile, \"fr_c\", SS->fr);\n\t\t\taddVectorToFile(outfile, \"frG_c\", frG);\n\t\t\taddVectorToFile(outfile, \"fm_c\", SS->f);\n\t\t\taddVectorToFile(outfile, \"gm_c\", SS->gm);\n\t\t\t//addVectorToFile(outfile, \"frg_c\", frGt);\n\t\t\taddVectorToFile(outfile, \"frtilde_c\", frtilde);\n\t\t\taddVectorToFile(outfile, \"rhs_c\", frtilde);\n\t\t\t///Eigen::VectorXd qdot0 = S->qdot;\n\t\t\t//addVectorToFile(outfile, \"qdot0_c\", qdot0);\n\t\t\taddVectorToFile(outfile, \"qdot1_c\", S->qdot);\n\t\t\t//addSparseToFile(outfile, \"P_c\", preconditioner);\n\t\t\t\n\t\t\t//SS->fr += JT * (SS->f - LHS * (Jdot * S->qdot));\n\n\n\t\t\toutfile.close();\n\t\t\tstd::cout << \"Printed\" << std::endl;\n\t\t}\n\n\t}\n\tauto end = std::chrono::steady_clock::now();\n\tauto diff = end - start;\n\tauto time = std::chrono::duration<double, std::nano>(diff).count();\n\ttrackLastTimestep.time_in_solve = time;\n\n\t// update joint angles\n\tS->q = S->q + SS->h * S->qdot;\n\n\tif (false)//std::abs(S->t - 1.01)) < 1e-5)\n\t{\n\t\t// name of file\n\t\tstd::string decimals = std::to_string((int)(100 * (S->t - (int)std::floor(S->t))));\n\t\tif (decimals.size() == 1)\n\t\t\tdecimals = \"0\" + decimals;\n\t\tstd::string filename = \"../matricies/redmax_\" + std::to_string(LS->blocks.size()) + \"t\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\t//std::string filename = \"../matricies/redmax_\" + std::to_string(LS->blocks.size()) + \"Preconditioner_noblkdiag_t\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\tstd::ofstream outfile(filename, std::ios::out);\n\t\toutfile << std::setprecision(16);\n\n\t\t//ConstraintJoint::preprocess_preconditioner(SS, LS, S, true);\n\t\t//Eigen::MatrixXd preconditioner = Eigen::MatrixXd::Zero(constraints, constraints);\n\t\t//Eigen::VectorXd temp;\n\t\t//Eigen::VectorXd z;\n\t\t//for (int k = 0; k < constraints; ++k)\n\t\t//{\n\t\t//\ttemp = Eigen::VectorXd::Zero(constraints);\n\t\t//\ttemp[k] = 1.0;\n\t\t//\tz = ConstraintJoint::computeMinv_x(temp, SS, LS, S);\n\t\t//\tfor (int l = 0; l < constraints; ++l)\n\t\t//\t{\n\t\t//\t\tpreconditioner(l, k) = z[l];\n\t\t//\t}\n\t\t//}\n\n\t\toutfile << \"h = \" << SS->h << \";\\n\" << std::endl;\n\t\taddSparseToFile(outfile, \"Mr_c\", Mr);\n\t\taddSparseToFile(outfile, \"Mrtilde_c\", Mrtilde);\n\t\taddSparseToFile(outfile, \"Mm_c\", LHS);\n\n\t\tEigen::SparseMatrix<double> bDm = Dm + SS->bDm;\n\t\taddSparseToFile(outfile, \"Dm_c\", bDm);\n\t\t//addSparseToFile(outfile, \"MG_c\", LHSGt);\n\t\t//addSparseToFile(outfile, \"Gr_c\", Gr);\n\t\taddSparseToFile(outfile, \"Km_c\", Km);\n\t\taddSparseToFile(outfile, \"Dr_c\", SS->Dr);\n\t\taddSparseToFile(outfile, \"Kr_c\", SS->Kr);\n\t\taddSparseToFile(outfile, \"Jmr_c\", SS->J);\n\t\taddSparseToFile(outfile, \"Jdotmr_c\", SS->Jd);\n\t\taddVectorToFile(outfile, \"fr_c\", SS->fr);\n\t\taddVectorToFile(outfile, \"fm_c\", SS->f);\n\t\t//addVectorToFile(outfile, \"frg_c\", frGt);\n\t\taddVectorToFile(outfile, \"frtilde_c\", frtilde);\n\t\taddVectorToFile(outfile, \"rhs_c\", frtilde);\n\t\t///Eigen::VectorXd qdot0 = S->qdot;\n\t\t//addVectorToFile(outfile, \"qdot0_c\", qdot0);\n\t\taddVectorToFile(outfile, \"qdot1_c\", S->qdot);\n\t\t//addSparseToFile(outfile, \"P_c\", preconditioner);\n\n\t\toutfile.close();\n\t\tstd::cout << \"Printed\" << std::endl;\n\t}\n\n\tif (false)\n\t{\n\t\tstd::string decimals = std::to_string((int)(100 * (S->t - (int)std::floor(S->t))));\n\t\tif (decimals.size() == 1)\n\t\t\tdecimals = \"0\" + decimals;\n\t\tstd::string filename = \"../matricies/qdot\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\tstd::ofstream outfile(filename, std::ios::out);\n\t\toutfile << std::setprecision(16);\n\t\t\n\t\taddSparseToFile(outfile, \"Mrtilde_c\", Mrtilde);\n\t\taddSparseToFile(outfile, \"Mm_c\", LHS);\n\t\taddSparseToFile(outfile, \"Km_c\", Km);\n\t\taddSparseToFile(outfile, \"Jmr_c\", SS->J);\n\t\taddVectorToFile(outfile, \"qdot1_c\", S->qdot);\n\n\t\toutfile.close();\n\n\t\tstd::cout << \"Printed\" << std::endl;\n\t}\n\n\tfor (int i = 0; i < (int)LS->blocks.size(); ++i)\n\t{\n\t\t// update pos and vel\n\t\tLS->joints[LS->joint_map[i]]->update(LS, S);\n\t}\n\n\t//if (LS->blocks.size() == 603 && count < 3)\n\t//{\n\t//\tcount++;\n\t//\tfor (int i = 0; i < S->qdot.size(); ++i)\n\t//\t{\n\t//\t\tstd::cout << S->qdot[i] << \" \";\n\t//\t}\n\t//\tstd::cout << std::endl;\n\t//}\n\n\treturn S->qdot;\n}\n#endif\n\nEigen::VectorXd Solver::solvePCG(std::unique_ptr<StateSolve>& SS, std::unique_ptr<LinkageSystem>& LS, std::unique_ptr<State>& S)\n{\n\t// Preprocessing, eliminate matrix resizing\n\tint constraints = SS->Mr_dimension;\n\tint additional_constraints = SS->Gr_dimension;\n\tint numObj = (int)LS->blocks.size();\n\n\t// Initialize containers\n\tSS->f = Eigen::VectorXd::Zero(numObj * 6); // load with fm\n\tSS->fr = Eigen::VectorXd::Zero(constraints);\n\tSS->Gm = Eigen::MatrixXd::Zero(additional_constraints, numObj * 6);\n\tSS->GmT = Eigen::MatrixXd::Zero(numObj * 6, additional_constraints);\n\tSS->gm = Eigen::VectorXd::Zero(additional_constraints);\n\n\t// Precomputations for SoA\n\tConstraintJoint::preprocess_PCG(SS, LS, S);\n\n\t// load constraint RHS update and CG joint preprocessing\n\tfor (int i = 0; i < LS->constraints.size(); ++i)\n\t{\n\t\tLS->constraints[i]->updateJoint(SS, LS, S);\n\t}\n\t// Update maximal body forces (RHS)\n\tcomputeRHS(SS, LS, S);\n\n\t// preprocessing\n\tConstraintJoint::preprocess_PCG_preconditioner(SS, LS, S, true);\n\n\t/// preconditioned\n\t//Eigen::VectorXd z;\n\t//Eigen::VectorXd p;\n\t//if (simtype != redCGNoMat_noprec)\n\t//{\n\t//\tif (simtype == redCGNoMat_noblkdiag)\n\t//\t\tConstraintJoint::preprocess_PCG_preconditioner(SS, LS, S, false);\n\t//\telse\n\t//\t\tConstraintJoint::preprocess_PCG_preconditioner(SS, LS, S, true);\n\n\t//\tz = ConstraintJoint::computeMinv_x(r, SS, LS, S);\n\t//\tp = z;\n\t//}\n\t//// NOT preconditioned \n\t//else\n\t//{\n\t//\tp = r;\n\t//}\n\n\t// solve\n\tEigen::VectorXd qd = S->qdot;\t\t// initial guess is prev. sol.\n\tEigen::VectorXd J_x;\n\tEigen::VectorXd Jdot_x;\n\n\t// J and Jdot in parallel\n\tConstraintJoint::computeJ_Jdot_x(J_x, Jdot_x, qd, SS, LS, S);\n\n\tEigen::VectorXd LHSqd = ConstraintJoint::computeJT_x(\n\t\tConstraintJoint::computeLHS_x(J_x, SS, LS, S),\n\t\tSS, LS, S);\n\n\t// Joint stiffness and damping\n\tConstraintJoint::computeStiffnessDampingJoint(LHSqd, qd, S->q, SS, LS, S);\n\n\tEigen::VectorXd Mqd = ConstraintJoint::computeJT_x(\n\t\tConstraintJoint::computeM_x(J_x, SS, LS, S),\n\t\tSS, LS, S);\n\tEigen::VectorXd fr_save = SS->fr;\n\tSS->fr += ConstraintJoint::computeJT_x(\n\t\t(SS->f - ConstraintJoint::computeM_x(Jdot_x, SS, LS, S)),\n\t\tSS, LS, S);\n\tEigen::VectorXd frtilde = Mqd + SS->h * SS->fr;\n\n\t//////////////////////////////////////////////////////////////////////////\n\t// Implement Shin's refactoring so JT is only applied once!\n\t//////////////////////////////////////////////////////////////////////////\n\t// error accumulation from somewhere\n\t//// J and Jdot in parallel\n\t//ConstraintJoint::computeJ_Jdot_x(J_x, Jdot_x, qd, SS, LS, S);\n\t//Eigen::VectorXd LHSJqd = ConstraintJoint::computeLHS_x(J_x, SS, LS, S);\n\t//// Joint stiffness and damping\n\t//ConstraintJoint::computeStiffnessDampingJoint(LHSJqd, qd, S->q, SS, LS, S);\n\t//Eigen::VectorXd MJqd = ConstraintJoint::computeM_x(J_x, SS, LS, S);\n\t//Eigen::VectorXd f_MJdqd = SS->f - ConstraintJoint::computeM_x(Jdot_x, SS, LS, S);\n\t//Eigen::VectorXd Mrtilde_qdot0;\n\t//Eigen::VectorXd Mr_qdot0;\n\t//ConstraintJoint::computeJT_x_parallel(Mrtilde_qdot0, LHSJqd, Mr_qdot0, MJqd, SS->fr, f_MJdqd, SS, LS, S);\n\t//Eigen::VectorXd frtilde = Mr_qdot0 + SS->h * SS->fr;\n\n\tif (additional_constraints == 0)\n\t{\n\t\t// Mrtilde\\frtilde = qdot\n\t\tpcdSaad2003(S->qdot, LHSqd, frtilde, SS, LS, S);\n\t}\n\telse if (additional_constraints == 2)\n\t{\n\t\t// Bridge scene has one loop closing constraint\n\t\tEigen::MatrixXd GrT = Eigen::MatrixXd::Zero(constraints, 2);\n\n\t\tEigen::VectorXd Gmrow1 = SS->Gm.row(0);\n\t\tEigen::VectorXd Gmrow2 = SS->Gm.row(1);\n\t\tEigen::VectorXd GrTcol1 = ConstraintJoint::computeJT_x(Gmrow1, SS, LS, S);\n\t\tEigen::VectorXd GrTcol2 = ConstraintJoint::computeJT_x(Gmrow2, SS, LS, S);\n        \n        // Run pcg for each row of G\n        Eigen::VectorXd MiGt1;\n\t\tEigen::VectorXd MiGt2;\n\t\tpcdSaad2003(MiGt1, LHSqd, GrTcol1, SS, LS, S);\n\t\tpcdSaad2003(MiGt2, LHSqd, GrTcol2, SS, LS, S);\n\n\t\t// Form LHS and RHS\n\t\tEigen::VectorXd qdot1unc;\n\t\tpcdSaad2003(qdot1unc, LHSqd, frtilde, SS, LS, S);\n\t\tEigen::VectorXd RHS = SS->baumgarte[2] * SS->gm;\n\t\tEigen::MatrixXd LHS = Eigen::MatrixXd::Zero(2, 2);\n\t\tfor (int r = 0; r < constraints; ++r)\n\t\t{\n\t\t\tLHS(0, 0) += GrTcol1[r] * MiGt1[r];\n\t\t\tLHS(0, 1) += GrTcol1[r] * MiGt2[r];\n\t\t\tLHS(1, 0) += GrTcol2[r] * MiGt1[r];\n\t\t\tLHS(1, 1) += GrTcol2[r] * MiGt2[r];\n\n\t\t\tRHS[0] += GrTcol1[r] * qdot1unc[r];\n\t\t\tRHS[1] += GrTcol2[r] * qdot1unc[r];\n\t\t}\n\n\t\t// Solve 2-by-2 system for lambda\n\t\tEigen::VectorXd lambda = LHS.ldlt().solve(RHS);\n\n\t\t// Solve!\n\t\tEigen::VectorXd frtilde_GTlambda = frtilde;\n\t\tfor (int r = 0; r < constraints; ++r)\n\t\t{\n\t\t\tfrtilde_GTlambda[r] -= GrTcol1[r] * lambda[0] + GrTcol2[r] * lambda[1];\n\t\t}\n\t\tpcdSaad2003(S->qdot, LHSqd, frtilde_GTlambda, SS, LS, S);\n\t}\n\telse\n\t{\n\t\t// Handle larger scenes\n\t\tEigen::SparseMatrix<double> Gr = Eigen::SparseMatrix<double>(additional_constraints, constraints);\n\t\tEigen::SparseMatrix<double> GrT = Eigen::SparseMatrix<double>(constraints, additional_constraints);\n\t\tEigen::SparseMatrix<double> MiGt = Eigen::SparseMatrix<double>(constraints, additional_constraints);\n\t\tstd::vector< Eigen::Triplet<double> > Grlist;\n\t\tstd::vector< Eigen::Triplet<double> > GrTlist;\n\t\tstd::vector< Eigen::Triplet<double> > MiGtlist;\n\n\t\t// Run PCG for each row of G\n\t\tint num_joints = (int)LS->joints.size();\n#pragma omp parallel for //private(Gmrowx, GrTcolx, MiGtx)\n\t\tfor (int i = 0; i < additional_constraints; ++i)\n\t\t{\n\t\t\tEigen::VectorXd Gmrowx;\n\t\t\tEigen::VectorXd GrTcolx;\n\t\t\tEigen::VectorXd MiGtx;\n\t\t\tstd::shared_ptr<State::local_mt> lmt = std::make_shared<State::local_mt>();\n\t\t\tlmt->alpha_.resize(num_joints);\n\t\t\tlmt->Bhat_.resize(num_joints);\n\t\t\tlmt->beta_.resize(num_joints);\n\t\t\tlmt->Vdot_.resize(num_joints);\n\t\t\tlmt->ST_Bhat_.resize(num_joints);\n\n\t\t\tGmrowx = SS->Gm.row(i);\n\t\t\tGrTcolx = ConstraintJoint::computeJT_x(Gmrowx, SS, LS, S, lmt);\n\t\t\tpcdSaad2003(MiGtx, LHSqd, GrTcolx, SS, LS, S, lmt);\n\n\t\t\tfor (int j = 0; j < constraints; ++j)\n\t\t\t{\n\t\t\t\tif (std::abs(GrTcolx[j]) > THRESHOLD)\n\t\t\t\t{\n#pragma omp critical\n\t\t\t\t\tGrlist.push_back(Eigen::Triplet<double>(i, j, GrTcolx[j]));\n#pragma omp critical\n\t\t\t\t\tGrTlist.push_back(Eigen::Triplet<double>(j, i, GrTcolx[j]));\n\t\t\t\t}\n\t\t\t\tif (std::abs(MiGtx[j]) > THRESHOLD)\n\t\t\t\t{\n#pragma omp critical\n\t\t\t\t\tMiGtlist.push_back(Eigen::Triplet<double>(j, i, MiGtx[j]));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Form LHS and RHS\n\t\tEigen::VectorXd qdot1unc;\n\t\tpcdSaad2003(qdot1unc, LHSqd, frtilde, SS, LS, S);\n\t\tEigen::VectorXd RHS = SS->baumgarte[2] * SS->gm;\n\t\tEigen::SparseMatrix<double> LHS = Eigen::SparseMatrix<double>(additional_constraints, additional_constraints);\n\n\t\tGr.setFromTriplets(Grlist.begin(), Grlist.end());\n\t\tMiGt.setFromTriplets(MiGtlist.begin(), MiGtlist.end());\n\n\t\tLHS = Gr * MiGt;\n\t\tRHS += Gr * qdot1unc;\n\n\t\t// Solve x-by-x system for lambda\n#ifdef REDMAX_PARDISO\n\t\tEigen::PardisoLDLT< Eigen::SparseMatrix<double>> solver;\n        Eigen::VectorXd lambda = solver.compute(LHS).solve(RHS);\n#else\n        Eigen::SparseLU< Eigen::SparseMatrix<double>> solver;\n        solver.compute(LHS);\n        Eigen::VectorXd lambda = solver.solve(RHS);\n#endif\n\n\t\t// Solve!\n\t\tGrT.setFromTriplets(GrTlist.begin(), GrTlist.end());\n\t\tfrtilde -= GrT * lambda;\n\t\tpcdSaad2003(S->qdot, LHSqd, frtilde, SS, LS, S);\n\n\n\t\tif (false)//std::abs(S->t - 1.01)) < 1e-5)\n\t\t{\n\t\t\tstd::string decimals = std::to_string((int)(100 * (S->t - (int)std::floor(S->t))));\n\t\t\tif (decimals.size() == 1)\n\t\t\t\tdecimals = \"0\" + decimals;\n\t\t\tstd::string filename = \"../matricies/redcgSoA_\" + std::to_string(LS->blocks.size()) + \"links_t\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\t\t//std::string filename = \"../matricies/redmax_\" + std::to_string(LS->blocks.size()) + \"Preconditioner_noblkdiag_t\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\t\tstd::ofstream outfile(filename, std::ios::out);\n\t\t\toutfile << std::setprecision(16);\n\n\t\t\toutfile << \"h = \" << SS->h << \";\\n\" << std::endl;\n\t\t\t//addVectorToFile(outfile, \"MiGt1_c\", MiGt1);\n\t\t\t//addVectorToFile(outfile, \"MiGt2_c\", MiGt2);\n\t\t\t//addVectorToFile(outfile, \"GrTcol1_c\", GrTcol1);\n\t\t\t//addVectorToFile(outfile, \"GrTcol2_c\", GrTcol2);\n\t\t\taddSparseToFile(outfile, \"MiGt_p\", MiGt);\n\t\t\taddVectorToFile(outfile, \"Mrtildeqd_p\", LHSqd);\n\t\t\taddSparseToFile(outfile, \"LHS_p\", LHS);\n\t\t\taddSparseToFile(outfile, \"Gr_p\", Gr);\n\t\t\taddSparseToFile(outfile, \"Gm_p\", SS->Gm);\n\t\t\taddSparseToFile(outfile, \"GmT_p\", SS->GmT);\n\t\t\taddVectorToFile(outfile, \"gm_p\", SS->gm);\n\t\t\taddVectorToFile(outfile, \"qdot1unc_p\", qdot1unc);\n\t\t\taddVectorToFile(outfile, \"RHS_p\", RHS);\n\t\t\taddVectorToFile(outfile, \"fr_p\", SS->fr);\n\t\t\taddVectorToFile(outfile, \"lambda_p\", lambda);\n\t\t\taddVectorToFile(outfile, \"GTlambda_p\", frtilde);\n\t\t\taddVectorToFile(outfile, \"fm_p\", SS->f);\n\t\t\taddVectorToFile(outfile, \"qdot1_p\", S->qdot);\n\t\t\t//addVectorToFile(outfile, \"oJT_p\", onesJT);\n\t\t\t//addVectorToFile(outfile, \"oJ_p\", onesJ);\n\n\t\t\toutfile.close();\n\t\t\tstd::cout << \"Printed\" << std::endl;\n\t\t}\n\t}\n\n\t// update joint angles\n\tS->q = S->q + SS->h * S->qdot;\n\n\tif (false)\n\t{\n\t\tstd::string decimals = std::to_string((int)(100 * (S->t - (int)std::floor(S->t))));\n\t\tif (decimals.size() == 1)\n\t\t\tdecimals = \"0\" + decimals;\n\t\tstd::string filename = \"../matricies/pcgSoA_qdot\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\tstd::ofstream outfile(filename, std::ios::out);\n\t\toutfile << std::setprecision(16);\n\t\t//outfile << \"qdot1_p\" << \" = [\\n\";\n\t\t//for (int i = 0; i < (int)LS->blocks.size(); ++i)\n\t\t//{\n\t\t//\tEigen::VectorXd tt = LS->joints[LS->joint_map[i]]->qdot;\n\t\t//\tfor (int j = 0; j < tt.size(); j++)\n\t\t//\t{\n\t\t//\t\toutfile << tt[j] << \" \";\n\t\t//\t}\n\t\t//}\n\t\t//outfile << \"]';\\n\" << std::endl;\n\n\t\t//Eigen::VectorXd rj = frtilde_save - LHSqd;\n\t\t//Eigen::VectorXd zj = ConstraintJoint::computeMinv_x(rj, SS, LS, S);\n\t\t//Eigen::VectorXd check = ConstraintJoint::computeMinv_x(rj, SS, LS, S);\n\n\t\tEigen::VectorXd qdc = Eigen::VectorXd::Zero(S->qdot.size());\n\t\tfor (int i = 0; i < qdc.size(); ++i)\n\t\t\tqdc[i] = 1;// (((double)rand() / (RAND_MAX)) - 0.5) * 4;\n\t\tEigen::VectorXd checkc = ConstraintJoint::computeMinv_x(qdc, SS, LS, S);\n\n\t\tEigen::VectorXd MJdqd = ConstraintJoint::computeM_x(Jdot_x, SS, LS, S);\n\n\t\tEigen::VectorXd J_ones;\n\t\tEigen::VectorXd Jdot_ones;\n\t\tConstraintJoint::computeJ_Jdot_x(J_ones, Jdot_ones, qdc, SS, LS, S);\n\n\t\taddVectorToFile(outfile, \"Mrtildeqd_l\", LHSqd);\n\t\taddVectorToFile(outfile, \"frtilde_l\", frtilde);\n\t\taddVectorToFile(outfile, \"Mqd_l\", Mqd);\n\t\taddVectorToFile(outfile, \"fr_l\", fr_save);\n\t\taddVectorToFile(outfile, \"fmr_l\", SS->fr);\n\t\taddVectorToFile(outfile, \"fm_l\", SS->f);\n\t\t//addVectorToFile(outfile, \"zj_l\", zj);\n\t\taddVectorToFile(outfile, \"qdot1_l\", S->qdot);\n\t\taddVectorToFile(outfile, \"check_l\", checkc);\n\t\taddVectorToFile(outfile, \"MJdqd_l\", MJdqd);\n\t\taddVectorToFile(outfile, \"Jdqd_l\", Jdot_x);\n\t\taddVectorToFile(outfile, \"Jqd_l\", J_x);\n\t\taddVectorToFile(outfile, \"Jones_l\", J_ones);\n\t\taddVectorToFile(outfile, \"Jdones_l\", Jdot_ones);\n\n\t\toutfile.close();\n\t\tstd::cout << \"Printed\" << std::endl;\n\t}\n\n\tfor (int i = 0; i < (int)LS->blocks.size(); ++i)\n\t{\n\t\t// update pos and vel\n\t\tLS->joints[LS->joint_map[i]]->update(LS, S);\n\t}\n\treturn S->qdot;\n}\n\nEigen::VectorXd Solver::solvePCG_unopt(std::unique_ptr<StateSolve>& SS, std::unique_ptr<LinkageSystem>& LS, std::unique_ptr<State>& S)\n{\n\t// Preprocessing, eliminate matrix resizing\n\tint constraints = SS->Mr_dimension;\n\tint additional_constraints = SS->Gr_dimension;\n\tint numObj = (int)LS->blocks.size();\n\n\t// Initialize containers\n\tSS->f = Eigen::VectorXd::Zero(numObj * 6); // load with fm\n\tSS->fr = Eigen::VectorXd::Zero(constraints);\n\tSS->Gm = Eigen::MatrixXd::Zero(additional_constraints, numObj * 6);\n\tSS->GmT = Eigen::MatrixXd::Zero(numObj * 6, additional_constraints);\n\tSS->gm = Eigen::VectorXd::Zero(additional_constraints);\n\n\t// load constraint RHS update and CG joint preprocessing\n\tfor (int i = 0; i < LS->constraints.size(); ++i)\n\t{\n\t\tLS->constraints[i]->updateJoint(SS, LS, S);\n\t}\n\t// Update maximal body forces (RHS)\n\tcomputeRHS(SS, LS, S);\n\n\t// preprocessing\n\tConstraintJoint::preprocess_preconditioner_unopt(SS, LS, S, true);\n\n\t//if (simtype == redCGNoMat_noblkdiag)\n\t//\tConstraintJoint::preprocess_preconditioner_unopt(SS, LS, S, false);\n\t//else\n\t//\tConstraintJoint::preprocess_preconditioner_unopt(SS, LS, S, true);\n\n\n\t// solve\n\tEigen::VectorXd qd = S->qdot;\t\t// initial guess is prev. sol.\n\tEigen::VectorXd J_x;\n\tEigen::VectorXd Jdot_x;\n\n\t// J and Jdot in parallel\n\tConstraintJoint::computeJ_Jdot_x(J_x, Jdot_x, qd, SS, LS, S);\n\n\tEigen::VectorXd LHSqd = ConstraintJoint::computeJT_x(\n\t\tConstraintJoint::computeLHS_x(J_x, SS, LS, S),\n\t\tSS, LS, S);\n\t// Joint stiffness and damping\n\tConstraintJoint::computeStiffnessDampingJoint(LHSqd, qd, S->q, SS, LS, S);\n\n\tEigen::VectorXd Mqd = ConstraintJoint::computeJT_x(\n\t\tConstraintJoint::computeM_x(J_x, SS, LS, S),\n\t\tSS, LS, S);\n\tSS->fr += ConstraintJoint::computeJT_x(\n\t\t(SS->f - ConstraintJoint::computeM_x(Jdot_x, SS, LS, S)),\n\t\tSS, LS, S);\n\tEigen::VectorXd frtilde = Mqd + SS->h * SS->fr;\n\tEigen::VectorXd frtilde_save = frtilde;\n\n\t//////////////////////////////////////////////////////////////////////////\n\t// Implement Shin's refactoring so JT is only applied once!\n\t//////////////////////////////////////////////////////////////////////////\n\n\t// error accumulation from somewhere\n\t//// J and Jdot in parallel\n\t//ConstraintJoint::computeJ_Jdot_x(J_x, Jdot_x, qd, SS, LS, S);\n\t//Eigen::VectorXd LHSJqd = ConstraintJoint::computeLHS_x(J_x, SS, LS, S);\n\t//// Joint stiffness and damping\n\t//ConstraintJoint::computeStiffnessDampingJoint(LHSJqd, qd, S->q, SS, LS, S);\n\t//Eigen::VectorXd MJqd = ConstraintJoint::computeM_x(J_x, SS, LS, S);\n\t//Eigen::VectorXd f_MJdqd = SS->f - ConstraintJoint::computeM_x(Jdot_x, SS, LS, S);\n\t//Eigen::VectorXd Mrtilde_qdot0;\n\t//Eigen::VectorXd Mr_qdot0;\n\t//ConstraintJoint::computeJT_x_parallel(Mrtilde_qdot0, LHSJqd, Mr_qdot0, MJqd, SS->fr, f_MJdqd, SS, LS, S);\n\t//Eigen::VectorXd frtilde = Mr_qdot0 + SS->h * SS->fr;\n\n\tif (additional_constraints == 0)\n\t{\n\t\t// Mrtilde\\frtilde = qdot\n\t\tpcdSaad2003(S->qdot, LHSqd, frtilde, SS, LS, S);\n\t}\n\telse if (additional_constraints == 2)\n\t{\n\t\t// Bridge scene has one loop closing constraint\n\t\tEigen::MatrixXd GrT = Eigen::MatrixXd::Zero(constraints, 2);\n\n\t\tEigen::VectorXd Gmrow1 = SS->Gm.row(0);\n\t\tEigen::VectorXd Gmrow2 = SS->Gm.row(1);\n\t\tEigen::VectorXd GrTcol1 = ConstraintJoint::computeJT_x(Gmrow1, SS, LS, S);\n\t\tEigen::VectorXd GrTcol2 = ConstraintJoint::computeJT_x(Gmrow2, SS, LS, S);\n\n\t\t// Run pcg for each row of G\n\t\tEigen::VectorXd MiGt1;\n\t\tEigen::VectorXd MiGt2;\n\t\tpcdSaad2003(MiGt1, LHSqd, GrTcol1, SS, LS, S);\n\t\tpcdSaad2003(MiGt2, LHSqd, GrTcol2, SS, LS, S);\n\n\t\t// Form LHS and RHS\n\t\tEigen::VectorXd qdot1unc;\n\t\tpcdSaad2003(qdot1unc, LHSqd, frtilde, SS, LS, S);\n\t\tEigen::VectorXd RHS = SS->baumgarte[2] * SS->gm;\n\t\tEigen::MatrixXd LHS = Eigen::MatrixXd::Zero(2, 2);\n\t\tfor (int r = 0; r < constraints; ++r)\n\t\t{\n\t\t\tLHS(0, 0) += GrTcol1[r] * MiGt1[r];\n\t\t\tLHS(0, 1) += GrTcol1[r] * MiGt2[r];\n\t\t\tLHS(1, 0) += GrTcol2[r] * MiGt1[r];\n\t\t\tLHS(1, 1) += GrTcol2[r] * MiGt2[r];\n\n\t\t\tRHS[0] += GrTcol1[r] * qdot1unc[r];\n\t\t\tRHS[1] += GrTcol2[r] * qdot1unc[r];\n\t\t}\n\n\t\t// Solve 2-by-2 system for lambda\n\t\tEigen::VectorXd lambda = LHS.ldlt().solve(RHS);\n\n\t\t// Solve!\n\t\tEigen::VectorXd frtilde_GTlambda = frtilde;\n\t\tfor (int r = 0; r < constraints; ++r)\n\t\t{\n\t\t\tfrtilde_GTlambda[r] -= GrTcol1[r] * lambda[0] + GrTcol2[r] * lambda[1];\n\t\t}\n\t\tpcdSaad2003(S->qdot, LHSqd, frtilde_GTlambda, SS, LS, S);\n\n\t\tif (false)//std::abs(S->t - 1.01)) < 1e-5)\n\t\t{\n\t\t\tstd::string decimals = std::to_string((int)(100 * (S->t - (int)std::floor(S->t))));\n\t\t\tif (decimals.size() == 1)\n\t\t\t\tdecimals = \"0\" + decimals;\n\t\t\tstd::string filename = \"../matricies/redcg_\" + std::to_string(LS->blocks.size()) + \"links_2case_t\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\t\t//std::string filename = \"../matricies/redmax_\" + std::to_string(LS->blocks.size()) + \"Preconditioner_noblkdiag_t\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\t\tstd::ofstream outfile(filename, std::ios::out);\n\t\t\toutfile << std::setprecision(16);\n\n\t\t\toutfile << \"h = \" << SS->h << \";\\n\" << std::endl;\n\t\t\taddVectorToFile(outfile, \"MiGt1_c\", MiGt1);\n\t\t\taddVectorToFile(outfile, \"MiGt2_c\", MiGt2);\n\t\t\taddVectorToFile(outfile, \"GrTcol1_c\", GrTcol1);\n\t\t\taddVectorToFile(outfile, \"GrTcol2_c\", GrTcol2);\n\t\t\taddSparseToFile(outfile, \"LHS_c\", LHS);\n\t\t\taddSparseToFile(outfile, \"GrT_c\", GrT);\n\t\t\taddSparseToFile(outfile, \"Gm_c\", SS->Gm);\n\t\t\taddSparseToFile(outfile, \"GmT_c\", SS->GmT);\n\t\t\taddVectorToFile(outfile, \"gm_c\", SS->gm);\n\t\t\taddVectorToFile(outfile, \"qdot1unc_c\", qdot1unc);\n\t\t\taddVectorToFile(outfile, \"RHS_c\", RHS);\n\t\t\taddVectorToFile(outfile, \"fr_c\", SS->fr);\n\t\t\taddVectorToFile(outfile, \"lambda_c\", lambda);\n\t\t\taddVectorToFile(outfile, \"GTlambda_c\", frtilde_GTlambda);\n\t\t\taddVectorToFile(outfile, \"fm_c\", SS->f);\n\t\t\taddVectorToFile(outfile, \"qdot1_c\", S->qdot);\n\n\t\t\toutfile.close();\n\t\t\tstd::cout << \"Printed\" << std::endl;\n\t\t}\n\t}\n\telse\n\t{\n\t\t// Handle larger scenes\n\t\tEigen::SparseMatrix<double> Gr = Eigen::SparseMatrix<double>(additional_constraints, constraints);\n\t\tEigen::SparseMatrix<double> GrT = Eigen::SparseMatrix<double>(constraints, additional_constraints);\n\t\tEigen::SparseMatrix<double> MiGt = Eigen::SparseMatrix<double>(constraints, additional_constraints);\n\t\tstd::vector< Eigen::Triplet<double> > Grlist;\n\t\tstd::vector< Eigen::Triplet<double> > GrTlist;\n\t\tstd::vector< Eigen::Triplet<double> > MiGtlist;\n\n\t\t// Run PCG for each row of G\n\t\tint num_joints = LS->joints.size();\n#pragma omp parallel for //private(Gmrowx, GrTcolx, MiGtx)\n\t\tfor (int i = 0; i < additional_constraints; ++i)\n\t\t{\n\t\t\tEigen::VectorXd Gmrowx;\n\t\t\tEigen::VectorXd GrTcolx;\n\t\t\tEigen::VectorXd MiGtx;\n\t\t\tstd::shared_ptr<State::local_mt> lmt = std::make_shared<State::local_mt>();\n\t\t\tlmt->alpha_.resize(num_joints);\n\t\t\tlmt->Bhat_.resize(num_joints);\n\t\t\tlmt->beta_.resize(num_joints);\n\t\t\tlmt->Vdot_.resize(num_joints);\n\t\t\tlmt->ST_Bhat_.resize(num_joints);\n\n\t\t\tGmrowx = SS->Gm.row(i);\n\t\t\tGrTcolx = ConstraintJoint::computeJT_x(Gmrowx, SS, LS, S, lmt);\n\t\t\tpcdSaad2003(MiGtx, LHSqd, GrTcolx, SS, LS, S, lmt);\n\n\t\t\tfor (int j = 0; j < constraints; ++j)\n\t\t\t{\n\t\t\t\tif (std::abs(GrTcolx[j]) > THRESHOLD)\n\t\t\t\t{\n#pragma omp critical\n\t\t\t\t\tGrlist.push_back(Eigen::Triplet<double>(i, j, GrTcolx[j]));\n#pragma omp critical\n\t\t\t\t\tGrTlist.push_back(Eigen::Triplet<double>(j, i, GrTcolx[j]));\n\t\t\t\t}\n\t\t\t\tif (std::abs(MiGtx[j]) > THRESHOLD)\n\t\t\t\t{\n#pragma omp critical\n\t\t\t\t\tMiGtlist.push_back(Eigen::Triplet<double>(j, i, MiGtx[j]));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Form LHS and RHS\n\t\tEigen::VectorXd qdot1unc;\n\t\tpcdSaad2003(qdot1unc, LHSqd, frtilde, SS, LS, S);\n\t\tEigen::VectorXd RHS = SS->baumgarte[2] * SS->gm;\n\t\tEigen::SparseMatrix<double> LHS = Eigen::SparseMatrix<double>(additional_constraints, additional_constraints);\n\n\t\tGr.setFromTriplets(Grlist.begin(), Grlist.end());\n\t\tMiGt.setFromTriplets(MiGtlist.begin(), MiGtlist.end());\n\n\t\tLHS = Gr * MiGt;\n\t\tRHS += Gr * qdot1unc;\n\n\t\t// Solve x-by-x system for lambda\n#ifdef REDMAX_PARDISO\n        Eigen::PardisoLDLT< Eigen::SparseMatrix<double>> solver;\n        Eigen::VectorXd lambda = solver.compute(LHS).solve(RHS);\n#else\n        Eigen::SparseLU< Eigen::SparseMatrix<double>> solver;\n        solver.compute(LHS);\n        Eigen::VectorXd lambda = solver.solve(RHS);\n#endif\n\t\t// Solve!\n\t\tGrT.setFromTriplets(GrTlist.begin(), GrTlist.end());\n\t\tfrtilde -= GrT * lambda;\n\t\tpcdSaad2003(S->qdot, LHSqd, frtilde, SS, LS, S);\n\n\n\t\tif (false)//std::abs(S->t - 1.01)) < 1e-5)\n\t\t{\n\t\t\tstd::string decimals = std::to_string((int)(100 * (S->t - (int)std::floor(S->t))));\n\t\t\tif (decimals.size() == 1)\n\t\t\t\tdecimals = \"0\" + decimals;\n\t\t\tstd::string filename = \"../matricies/redcg_\" + std::to_string(LS->blocks.size()) + \"links_t\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\t\t//std::string filename = \"../matricies/redmax_\" + std::to_string(LS->blocks.size()) + \"Preconditioner_noblkdiag_t\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\t\tstd::ofstream outfile(filename, std::ios::out);\n\t\t\toutfile << std::setprecision(16);\n\n\t\t\toutfile << \"h = \" << SS->h << \";\\n\" << std::endl;\n\t\t\t//addVectorToFile(outfile, \"MiGt1_c\", MiGt1);\n\t\t\t//addVectorToFile(outfile, \"MiGt2_c\", MiGt2);\n\t\t\t//addVectorToFile(outfile, \"GrTcol1_c\", GrTcol1);\n\t\t\t//addVectorToFile(outfile, \"GrTcol2_c\", GrTcol2);\n\t\t\taddSparseToFile(outfile, \"MiGt_l\", MiGt);\n\t\t\taddVectorToFile(outfile, \"Mrtildeqd_l\", LHSqd);\n\t\t\taddSparseToFile(outfile, \"LHS_l\", LHS);\n\t\t\taddSparseToFile(outfile, \"Gr_l\", Gr);\n\t\t\taddSparseToFile(outfile, \"Gm_l\", SS->Gm);\n\t\t\taddSparseToFile(outfile, \"GmT_l\", SS->GmT);\n\t\t\taddVectorToFile(outfile, \"gm_l\", SS->gm);\n\t\t\taddVectorToFile(outfile, \"qdot1unc_l\", qdot1unc);\n\t\t\taddVectorToFile(outfile, \"RHS_l\", RHS);\n\t\t\taddVectorToFile(outfile, \"fr_l\", SS->fr);\n\t\t\taddVectorToFile(outfile, \"lambda_l\", lambda);\n\t\t\taddVectorToFile(outfile, \"GTlambda_l\", frtilde);\n\t\t\taddVectorToFile(outfile, \"frtilde_l\", frtilde);\n\t\t\taddVectorToFile(outfile, \"fm_l\", SS->f);\n\t\t\taddVectorToFile(outfile, \"qdot1_l\", S->qdot);\n\t\t\t//addVectorToFile(outfile, \"oJT_p\", onesJT);\n\t\t\t//addVectorToFile(outfile, \"oJ_p\", onesJ);\n\n\t\t\toutfile.close();\n\t\t\tstd::cout << \"Printed\" << std::endl;\n\t\t}\n\n\t\tif (false)//std::abs(S->t - 1.01)) < 1e-5)\n\t\t{\n\t\t\tstd::string decimals = std::to_string((int)(100 * (S->t - (int)std::floor(S->t))));\n\t\t\tif (decimals.size() == 1)\n\t\t\t\tdecimals = \"0\" + decimals;\n\t\t\tstd::string filename = \"../matricies/redcg_\" + std::to_string(LS->blocks.size()) + \"links_t\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\t\t//std::string filename = \"../matricies/redmax_\" + std::to_string(LS->blocks.size()) + \"Preconditioner_noblkdiag_t\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\t\tstd::ofstream outfile(filename, std::ios::out);\n\t\t\toutfile << std::setprecision(16);\n\n\t\t\toutfile << \"h = \" << SS->h << \";\\n\" << std::endl;\n\t\t\t//addVectorToFile(outfile, \"MiGt1_c\", MiGt1);\n\t\t\t//addVectorToFile(outfile, \"MiGt2_c\", MiGt2);\n\t\t\t//addVectorToFile(outfile, \"GrTcol1_c\", GrTcol1);\n\t\t\t//addVectorToFile(outfile, \"GrTcol2_c\", GrTcol2);\n\t\t\taddSparseToFile(outfile, \"LHS_c\", LHS);\n\t\t\taddSparseToFile(outfile, \"GrT_c\", GrT);\n\t\t\t//addSparseToFile(outfile, \"Gm_c\", SS->Gm);\n\t\t\taddSparseToFile(outfile, \"GmT_c\", SS->GmT);\n\t\t\taddVectorToFile(outfile, \"gm_c\", SS->gm);\n\t\t\taddVectorToFile(outfile, \"qdot1unc_c\", qdot1unc);\n\t\t\taddVectorToFile(outfile, \"RHS_c\", RHS);\n\t\t\taddVectorToFile(outfile, \"fr_c\", SS->fr);\n\t\t\taddVectorToFile(outfile, \"lambda_c\", lambda);\n\t\t\taddVectorToFile(outfile, \"GTlambda_c\", frtilde);\n\t\t\taddVectorToFile(outfile, \"fm_c\", SS->f);\n\t\t\taddVectorToFile(outfile, \"qdot1_c\", S->qdot);\n\n\t\t\toutfile.close();\n\t\t\tstd::cout << \"Printed\" << std::endl;\n\t\t}\n\t}\n\n\tif (false)\n\t{\n\t\tstd::string decimals = std::to_string((int)(100 * (S->t - (int)std::floor(S->t))));\n\t\tif (decimals.size() == 1)\n\t\t\tdecimals = \"0\" + decimals;\n\t\tstd::string filename = \"../matricies/pcg_qdot\" + std::to_string((int)std::floor(S->t)) + \"_\" + decimals + \".m\";\n\t\tstd::ofstream outfile(filename, std::ios::out);\n\t\toutfile << std::setprecision(16);\n\n\t\tEigen::VectorXd rj = frtilde_save - LHSqd;\n\t\tEigen::VectorXd zj = ConstraintJoint::computeMinv_x(rj, SS, LS, S);\n\t\tEigen::VectorXd check = ConstraintJoint::computeMinv_x(rj, SS, LS, S);\n\n\t\tEigen::VectorXd qdc = Eigen::VectorXd::Zero(S->qdot.size());\n\t\tfor (int i = 0; i < qdc.size(); ++i)\n\t\t\tqdc[i] = 1;// (((double)rand() / (RAND_MAX)) - 0.5) * 4;\n\t\tEigen::VectorXd checkc = ConstraintJoint::computeMinv_x(qdc, SS, LS, S);\n\n\t\taddVectorToFile(outfile, \"Mrtildeqd_l\", LHSqd);\n\t\taddVectorToFile(outfile, \"frtilde_l\", frtilde_save);\n\t\taddVectorToFile(outfile, \"Mqd_l\", Mqd);\n\t\taddVectorToFile(outfile, \"fr_l\", SS->fr);\n\t\taddVectorToFile(outfile, \"zj_l\", zj);\n\t\taddVectorToFile(outfile, \"qdot1_l\", S->qdot);\n\t\taddVectorToFile(outfile, \"check_l\", checkc);\n\n\t\toutfile.close();\n\t\tstd::cout << \"Printed\" << std::endl;\n\t}\n\n\t// update joint angles\n\tS->q = S->q + SS->h * S->qdot;\n\n\tfor (int i = 0; i < (int)LS->blocks.size(); ++i)\n\t{\n\t\t// update pos and vel\n\t\tLS->joints[LS->joint_map[i]]->update(LS, S);\n\t}\n\treturn S->qdot;\n}\n\nSolver::Solver()\n{\n\ttrackLastTimestep = SolverDataTracker();\n}\n\nEigen::VectorXd Solver::solve(std::unique_ptr<StateSolve> &SS, std::unique_ptr<LinkageSystem> &LS, std::unique_ptr<State> &S)\n{\n\tEigen::VectorXd result;\n\n\ttrackLastTimestep.num_iterations = 0;\n\tif (simtype == simType::PCG)\n\t\tresult = solvePCG(SS, LS, S);\n\telse if (simtype == simType::PCG_unopt)\n\t\tresult = solvePCG_unopt(SS, LS, S);\n#ifdef REDMAX_PARDISO\n\telse if (simtype == simType::Pardiso)\n\t\tresult = solvePardiso(SS, LS, S);\n#endif\n\telse\n\t\tstd::cerr << \"Specified simtype solver has not been set up\" << std::endl;\n\n\treturn result;\n}\n\nvoid Solver::printDenseToFile(Eigen::MatrixXd & MG, Eigen::VectorXd & f, Eigen::VectorXd & res, std::string id)\n{\n\tstd::string filename = \"../matricies/\" + id + \".m\";\n\tstd::ofstream outfile(filename, std::ios::out);\n\n\toutfile << \"MG = [\\n\";\n\tfor (int r = 0; r < MG.rows(); r++)\n\t{\n\t\tfor (int c = 0; c < MG.cols(); c++)\n\t\t{\n\t\t\toutfile << MG(r, c) << \" \";\n\t\t}\n\t\toutfile << \";\\n\";\n\t}\n\toutfile << \"];\\n\\nf = [\\n\";\n\n\tfor (int i = 0; i < f.size(); i++)\n\t{\n\t\toutfile << f[i] << \"; \";\n\t}\n\toutfile << \"];\\n\\nres = [\";\n\n\tfor (int i = 0; i < res.size(); i++)\n\t{\n\t\toutfile << res[i] << \"; \";\n\t}\n\toutfile << \"];\\n\";\n}\n\nvoid Solver::printSparseToFile(std::vector<Eigen::Triplet<double>>& MG, Eigen::VectorXd & f, Eigen::VectorXd & res)\n{\n\tstd::string filename = \"../matricies/r_sparse.m\";\n\tstd::ofstream outfile(filename, std::ios::out);\n\n\toutfile << \"i = [\\n\";\n\tfor (int i = 0; i < MG.size(); i++)\n\t{\n\t\toutfile << MG[i].row() + 1 << \" \";\n\t}\n\toutfile << \"]';\\n\\nj= [\\n\";\n\tfor (int i = 0; i < MG.size(); i++)\n\t{\n\t\toutfile << MG[i].col() + 1 << \" \";\n\t}\n\toutfile << \"]';\\n\\nv = [\\n\";\n\tfor (int i = 0; i < MG.size(); i++)\n\t{\n\t\toutfile << MG[i].value() << \" \";\n\t}\n\toutfile << \"]';\\n\" << std::endl;\n\n\toutfile << \"MG = sparse(i,j,v);\\n\" << std::endl;\n\n\toutfile << \"f = [\\n\";\n\tfor (int i = 0; i < f.size(); i++)\n\t{\n\t\toutfile << f[i] << \"; \";\n\t}\n\toutfile << \"];\\n\\nres = [\";\n\tfor (int i = 0; i < res.size(); i++)\n\t{\n\t\toutfile << res[i] << \"; \";\n\t}\n\toutfile << \"];\\n\";\n}\n\nvoid Solver::addSparseToFile(std::ofstream & outfile, std::string name, Eigen::MatrixXd &M)\n{\n\tstd::vector<int> ilist;\n\tstd::vector<int> jlist;\n\tstd::vector<double> vlist;\n\n\tfor (int r = 0; r < M.rows(); ++r)\n\t{\n\t\tfor (int c = 0; c < M.cols(); ++c)\n\t\t{\n\t\t\tif (M(r, c) != 0)\n\t\t\t{\n\t\t\t\tilist.push_back(r);\n\t\t\t\tjlist.push_back(c);\n\t\t\t\tvlist.push_back(M(r,c));\n\t\t\t}\n\t\t}\n\t}\n\n\toutfile << \"i = [\\n\";\n\tfor (int i = 0; i < ilist.size(); i++)\n\t{\n\t\toutfile << ilist[i] + 1 << \" \";\n\t}\n\toutfile << \"]';\\n\\nj= [\\n\";\n\tfor (int i = 0; i < jlist.size(); i++)\n\t{\n\t\toutfile << jlist[i] + 1 << \" \";\n\t}\n\toutfile << \"]';\\n\\nv = [\\n\";\n\tfor (int i = 0; i < vlist.size(); i++)\n\t{\n\t\toutfile << vlist[i] << \" \";\n\t}\n\toutfile << \"]';\\n\" << std::endl;\n\n\tint m = (int)M.rows();\n\tint n = (int)M.cols();\n\n\toutfile << name << \" = sparse(i,j,v,\" + std::to_string(m) + \",\" + std::to_string(n) + \");\\n\" << std::endl;\n}\n\nvoid Solver::addSparseToFile(std::ofstream & outfile, std::string name, Eigen::SparseMatrix<double>& M)\n{\n    // https://stackoverflow.com/questions/28685877/convert-an-eigen-matrix-to-triplet-form-c\n    std::string entry = \" = sparse(\";\n    outfile << \"ijv = [\" << std::endl;\n    int e = 1;\n    for(int k = 0; k < M.outerSize(); ++k) {\n        for(Eigen::SparseMatrix<double>::InnerIterator it(M,k); it; ++it) {\n            double v = it.value();\n            if(std::abs(v) > 1e-10) {\n                outfile << it.row()+1 << \" \"; // row index\n                outfile << it.col()+1 << \" \"; // col index (here it is equal to k)\n                outfile << v << std::endl;\n                entry.append(\"ijv(:,\" + std::to_string(e) + \"),\");\n                ++e;\n            }\n        }\n    }\n    outfile << \"];\" << std::endl;\n    outfile << name <<  entry + std::to_string(M.rows()) + \",\" + std::to_string(M.cols()) + \");\\n\" << std::endl;\n}\n\nvoid Solver::addVectorToFile(std::ofstream & outfile, std::string name, Eigen::VectorXd & M)\n{\n\toutfile << name << \" = [\\n\";\n\n\tfor (int i = 0; i < M.size(); i++)\n\t{\n\t\toutfile << M[i] << \" \";\n\t}\n\toutfile << \"]';\\n\" << std::endl;\n}\n\n", "meta": {"hexsha": "329de46bc014031726c401acb18c937b722714c3", "size": 46239, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/PCG/src/Solver.cpp", "max_stars_repo_name": "sueda/redmax", "max_stars_repo_head_hexsha": "0a8864e882cbb8afe471314829d591790b915e56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2019-05-09T03:25:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T07:05:35.000Z", "max_issues_repo_path": "c++/PCG/src/Solver.cpp", "max_issues_repo_name": "sueda/redmax", "max_issues_repo_head_hexsha": "0a8864e882cbb8afe471314829d591790b915e56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-13T23:17:13.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-22T10:49:52.000Z", "max_forks_repo_path": "c++/PCG/src/Solver.cpp", "max_forks_repo_name": "sueda/redmax", "max_forks_repo_head_hexsha": "0a8864e882cbb8afe471314829d591790b915e56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-05-06T02:03:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T11:01:27.000Z", "avg_line_length": 33.5795206972, "max_line_length": 271, "alphanum_fraction": 0.6319124549, "num_tokens": 16009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5428632831725051, "lm_q1q2_score": 0.4144673025319838}}
{"text": "//\n// Created by gongsf on 15/5/19.\n//\n\n#include <float.h>\n#include <boost/algorithm/string/trim.hpp>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <unordered_set>\n#include <vector>\n\nusing namespace std;\nusing namespace boost;\n\nlong unfind(vector<long>& un_father, long u) {\n  return un_father[u] == u ? u : (un_father[u] = unfind(un_father, un_father[u]));\n}\nvoid ununion(vector<long>& un_father, long u, long v) {\n  un_father[u] = v;\n}\n\nvoid fennel(int argc, char *argv[]) {\n  cout << \"fennel start !!!!!!!!!!!\" << endl;\n  string input;\n  string output;\n  int part_num = -1;\n  long vertex_num = -1;\n  long edge_num = -1;\n\n  for (int i = 0; i < argc; i++) {\n    string arg = argv[i];\n    if (arg == \"--in\") {\n      input = argv[++i];\n    } else if (arg == \"--out\") {\n      output = argv[++i];\n    } else if (arg == \"--part_num\") {\n      part_num = atoi(argv[++i]);\n    } else if (arg == \"--vertex_num\") {\n      vertex_num = atol(argv[++i]);\n    } else if (arg == \"--edge_num\") {\n      edge_num = atol(argv[++i]);\n    }\n  }\n\n  if (part_num == -1 || vertex_num == -1 || edge_num == -1) {\n    cout << \"invalie parameters\" << endl;\n    cout << part_num << endl;\n    cout << vertex_num << endl;\n    cout << edge_num << endl;\n    exit(0);\n  }\n\n  ifstream infile(input.c_str());\n  if (infile.is_open()) {\n    string line;\n    edge_num = edge_num / 2;\n    float gamma = 1.5;\n    float alpha = sqrt(part_num) * edge_num / pow(vertex_num, gamma);\n    float v = 1.1;\n    float miu = v * vertex_num / part_num;\n    vector<long> part_info = vector<long>(vertex_num, 0);\n    vector<long> vertex_num_part = vector<long>(part_num, 0);\n\n    vector<long> un_father(vertex_num);\n    vector<long> un_first(part_num, -1);\n    for (long i = 0; i < vertex_num; ++i) un_father[i] = i;\n\n    // the format each line is: u\\tv1 v2 v3 ....\n    for (long i = 0; getline(infile, line); i++) {\n      if (i % 1000 == 0) cout << i << endl;\n      trim(line);\n      long pos = line.find_first_of(\"\\t\");\n      long id = atoi(line.substr(0, pos).c_str());\n      line = line.substr(pos + 1);\n      vector<long> neighbor;\n      long to = 0;\n      for (size_t p = 0; p < line.length(); ++p) {\n        if (line[p] >= '0' && line[p] <= '9') {\n          to = to*10+(line[p] - '0');\n        }\n        if (p == line.length() -1 || line[p] == ' ') {\n          neighbor.push_back(to);\n          to = 0;\n        }\n      }\n\n      float max_score = -FLT_MAX;\n      int max_part = 0;\n      for (long i = 0; i < part_num; i++) {\n        if (vertex_num_part[i] <= miu) {\n          double delta_c = alpha * (pow(vertex_num_part[i] + 1, gamma) -\n                                    pow(vertex_num_part[i], gamma));\n          float score = 0;\n          for (long j = 0; j < neighbor.size(); j++) {\n            long nid = neighbor[j];\n            // this partition contains nid\n            if (un_first[i] >= 0 && unfind(un_father, un_first[i]) == unfind(un_father, nid)) {\n              score += 1;\n            }\n          }\n          score = score - delta_c;\n          if (max_score < score) {\n            max_score = score;\n            max_part = i;\n          }\n        }\n      }\n      if (un_first[max_part] < 0) un_first[max_part] = id;\n      ununion(un_father, id, un_first[max_part]);\n      vertex_num_part[max_part] += 1;\n      part_info[id] = max_part;\n    }\n    ofstream outfile(output.c_str());\n    for (long i = 0; i < vertex_num; i++) {\n      outfile << part_info[i] << endl;\n    }\n    outfile.close();\n  }\n  infile.close();\n}\n\nint main(int argc, char *argv[]) {\n  if (argc == 1) {\n    std::cout << \"./fennel --in [] --out [] --part_num [] --vertex_num [] \"\n                 \"--edge_num []\"\n              << std::endl;\n    return -1;\n  }\n  fennel(argc, argv);\n  return 0;\n}\n\n", "meta": {"hexsha": "f7ed5a87052471fba06f5d9f7f0f0a45f8555ad7", "size": 3750, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/fennel/fennel.cpp", "max_stars_repo_name": "Joeyzhouqihui/SubgraphMatchGPU", "max_stars_repo_head_hexsha": "b2b64a2d03d5abdbe17723d0f145fcb1bd92f740", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-10-23T05:37:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T21:17:37.000Z", "max_issues_repo_path": "lib/fennel/fennel.cpp", "max_issues_repo_name": "Joeyzhouqihui/SubgraphMatchGPU", "max_issues_repo_head_hexsha": "b2b64a2d03d5abdbe17723d0f145fcb1bd92f740", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T09:02:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-12T09:02:30.000Z", "max_forks_repo_path": "lib/fennel/fennel.cpp", "max_forks_repo_name": "Joeyzhouqihui/SubgraphMatchGPU", "max_forks_repo_head_hexsha": "b2b64a2d03d5abdbe17723d0f145fcb1bd92f740", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-10-25T15:34:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-02T03:03:32.000Z", "avg_line_length": 27.9850746269, "max_line_length": 95, "alphanum_fraction": 0.5202666667, "num_tokens": 1102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837527911056, "lm_q2_score": 0.5428632831725053, "lm_q1q2_score": 0.414467296689045}}
{"text": "// Copyright (c) 2019 herenvarno\n//\n// This software is released under the MIT License.\n// https://opensource.org/licenses/MIT\n\n#ifndef __ALL_TOPOLOGICAL_SORTS_HPP__\n#define __ALL_TOPOLOGICAL_SORTS_HPP__\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/strong_components.hpp>\n#include <boost/graph/subgraph.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <queue>\n#include <set>\n#include <stack>\n#include <unordered_map>\n#include <vector>\n\nusing namespace std;\n\nnamespace bglex {\n\n/**\n * Find all topolotical sorts in a graph\n */\ntemplate <typename G>\nvector<vector<typename G::vertex_descriptor>> all_topological_sorts(G g_) {\n\n  using namespace boost;\n  typedef typename G::vertex_descriptor VD;\n  typedef typename G::edge_descriptor ED;\n  typedef typename G::vertex_iterator VI;\n  typedef typename G::edge_iterator EI;\n  typedef typename G::in_edge_iterator IEI;\n  typedef typename G::out_edge_iterator OEI;\n\n  typedef boost::adjacency_list<vecS, vecS, bidirectionalS> BG;\n\n  // Define a aux function _ats_util()\n  std::function<void(vector<vector<BG::vertex_descriptor>> & ats, BG g,\n                     vector<BG::vertex_descriptor> & res,\n                     std::unordered_map<VD, bool> visited)>\n      _ats_util;\n  _ats_util = [&](vector<vector<BG::vertex_descriptor>> &ats, BG g,\n                  vector<BG::vertex_descriptor> &res,\n                  std::unordered_map<VD, bool> visited) {\n    bool flag = false;\n\n    BG::vertex_iterator vi, vi_end;\n    for (tie(vi, vi_end) = vertices(g); vi != vi_end; vi++) {\n      if (in_degree(*vi, g) == 0 && !visited[*vi]) {\n        res.push_back(*vi);\n        visited[*vi] = true;\n\n        BG g0;\n        copy_graph(g, g0);\n        clear_out_edges(*vi, g0);\n        _ats_util(ats, g0, res, visited);\n\n        visited[*vi] = false;\n        res.erase(res.end() - 1);\n        flag = true;\n      }\n    }\n\n    if (!flag) {\n      ats.push_back(res);\n    }\n  };\n\n  BG bg;\n  copy_graph(g_, bg);\n\n  vector<vector<VD>> ret;\n  vector<vector<BG::vertex_descriptor>> ret1;\n  std::unordered_map<BG::vertex_descriptor, bool> visited;\n  BG::vertex_iterator vi, vi_end;\n  for (tie(vi, vi_end) = vertices(bg); vi != vi_end; vi++) {\n    visited[*vi] = false;\n  }\n  vector<BG::vertex_descriptor> res;\n\n  _ats_util(ret1, bg, res, visited);\n\n  for (auto &res : ret1) {\n    vector<VD> vec;\n    for (auto &v : res) {\n      vec.push_back(v);\n    }\n    ret.push_back(vec);\n  }\n\n  return ret;\n}\n\n} // namespace bglex\n\n#endif\n", "meta": {"hexsha": "1794f383f76d8622b023c09e84d16889faf1db8a", "size": 2561, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/all_topological_sorts.hpp", "max_stars_repo_name": "herenvarno/bglex", "max_stars_repo_head_hexsha": "a08f9be87bc332dd03a59a40f733d10ac9730457", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/all_topological_sorts.hpp", "max_issues_repo_name": "herenvarno/bglex", "max_issues_repo_head_hexsha": "a08f9be87bc332dd03a59a40f733d10ac9730457", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/all_topological_sorts.hpp", "max_forks_repo_name": "herenvarno/bglex", "max_forks_repo_head_hexsha": "a08f9be87bc332dd03a59a40f733d10ac9730457", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3564356436, "max_line_length": 75, "alphanum_fraction": 0.6513080828, "num_tokens": 682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4144459252659876}}
{"text": "/********************************************************************************\n * Copyright 2016 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RWSIM_LOG_LOGEQUATIONSYSTEM_HPP_\n#define RWSIM_LOG_LOGEQUATIONSYSTEM_HPP_\n\n/**\n * @file LogEquationSystem.hpp\n *\n * \\copydoc rwsim::log::LogEquationSystem\n */\n\n#include \"SimulatorLogEntry.hpp\"\n\n#include <rw/core/Ptr.hpp>\n\n#include <Eigen/Core>\n\nnamespace rwsim { namespace log {\n\n    class LogContactSet;\n\n    //! @addtogroup rwsim_log\n\n    //! @{\n    /**\n     * @brief Log entry for a linear equation system \\f$\\mathbf{A}\\mathbf{x}=\\mathbf{b}\\f$.\n     */\n    class LogEquationSystem : public SimulatorLogEntry\n    {\n      public:\n        //! Smart pointer type of LogEquationSystem\n        typedef rw::core::Ptr< LogEquationSystem > Ptr;\n\n        //! @copydoc SimulatorLogEntry::SimulatorLogEntry\n        LogEquationSystem (SimulatorLogScope* parent);\n\n        //! @brief Destructor.\n        virtual ~LogEquationSystem ();\n\n        //! @copydoc SimulatorLogEntry::read\n        virtual void read (class rw::common::InputArchive& iarchive, const std::string& id);\n\n        //! @copydoc SimulatorLogEntry::write\n        virtual void write (class rw::common::OutputArchive& oarchive, const std::string& id) const;\n\n        //! @copydoc SimulatorLogEntry::getType\n        virtual std::string getType () const;\n\n        //! @copydoc SimulatorLogEntry::operator==\n        virtual bool operator== (const SimulatorLog& b) const;\n\n        //! @copydoc SimulatorLogEntry::getLinkedEntries\n        virtual std::list< SimulatorLogEntry::Ptr > getLinkedEntries () const;\n\n        //! @copydoc SimulatorLogEntry::autoLink\n        virtual bool autoLink ();\n\n        //! @copydoc SimulatorLogEntry::createNew\n        virtual SimulatorLogEntry::Ptr createNew (SimulatorLogScope* parent) const;\n\n        /**\n         * @brief Get the type id of this entry type.\n         * @return the type id.\n         */\n        static std::string getTypeID ();\n\n        /**\n         * @brief Set the equation system.\n         * @param A [in] the matrix.\n         * @param b [in] the right-hand-side.\n         */\n        void set (const Eigen::MatrixXd& A, const Eigen::VectorXd& b);\n\n        /**\n         * @brief Set the solution to the system.\n         * @param x [in] the solution.\n         */\n        void setSolution (const Eigen::VectorXd& x);\n\n        /**\n         * @brief Get the matrix for the linear equation system.\n         * @return a reference to the matrix.\n         */\n        const Eigen::MatrixXd& A () const;\n\n        /**\n         * @brief Get the right-hand side of the equation system.\n         * @return a reference to the right-hand side.\n         */\n        const Eigen::VectorXd& b () const;\n\n        /**\n         * @brief Get the solution.\n         * @return a reference to the solution.\n         */\n        const Eigen::VectorXd& x () const;\n\n      private:\n        Eigen::MatrixXd _A;\n        Eigen::VectorXd _x;\n        Eigen::VectorXd _b;\n    };\n    //! @}\n}}     // namespace rwsim::log\n#endif /* RWSIM_LOG_LOGEQUATIONSYSTEM_HPP_ */\n", "meta": {"hexsha": "3baab744799293db769306d240cf4383efa0c1be", "size": 3800, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWorkSim/src/rwsim/log/LogEquationSystem.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWorkSim/src/rwsim/log/LogEquationSystem.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWorkSim/src/rwsim/log/LogEquationSystem.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4049586777, "max_line_length": 100, "alphanum_fraction": 0.6023684211, "num_tokens": 857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.41442474023174586}}
{"text": "/* Copyright (C) 2010-2019, The Regents of The University of Michigan.\n All rights reserved.\n\n This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab\n under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an\n MIT-style License that can be found at \"https://github.com/h2ssh/Vulcan\".\n*/\n\n\n/**\n * \\file     histogram.cpp\n * \\author   Collin Johnson\n *\n * Definition of Histogram.\n */\n\n#include \"utils/histogram.h\"\n#include <algorithm>\n#include <boost/algorithm/clamp.hpp>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n\nnamespace vulcan\n{\nnamespace utils\n{\n\nstd::vector<HistogramBin>\n  split_data_into_bins(const std::vector<double>& data, double minValue, double maxValue, int numBins);\n\n\n/////////////// Operators /////////////////////\nstd::ostream& operator<<(std::ostream& out, const Histogram& hist)\n{\n    for (auto& bin : hist) {\n        out << '[' << bin.minValue << ',' << bin.maxValue << \"]: \" << bin.count << '\\n';\n    }\n\n    return out;\n}\n\n////////////// Histogram /////////////////////\n\nHistogram::Histogram(int numBins)\n: numBins_(numBins)\n, bins_(numBins)\n, binsAreDirty_(true)\n, minValue_(NAN)\n, maxValue_(NAN)\n{\n    assert(numBins_ > 0);\n}\n\n\nHistogram::Histogram(double minValue, double maxValue, int numBins)\n: numBins_(numBins)\n, bins_(numBins)\n, binsAreDirty_(true)\n, minValue_(minValue)\n, maxValue_(maxValue)\n{\n    assert(minValue_ < maxValue_);\n    assert(numBins_ > 0);\n}\n\n\nvoid Histogram::addValue(double value)\n{\n    values_.push_back(value);\n    binsAreDirty_ = true;\n}\n\n\nint Histogram::findValueBinIndex(double value) const\n{\n    computeHistogramIfNeeded();\n\n    auto binIt = std::find_if(bins_.begin(), bins_.end(), [value](const HistogramBin& bin) {\n        return (bin.minValue <= value) && (value <= bin.maxValue);\n    });\n\n    return (binIt == bins_.end()) ? -1 : std::distance(bins_.begin(), binIt);\n}\n\n\nHistogramBin Histogram::bin(int binIndex) const\n{\n    computeHistogramIfNeeded();\n\n    assert(binIndex >= 0);\n    assert(binIndex < numBins_);\n\n    return bins_[binIndex];\n}\n\n\nvoid Histogram::normalize(void)\n{\n    computeHistogramIfNeeded();\n\n    double total = 0.0;\n\n    for (auto& b : bins_) {\n        total += b.count;\n    }\n\n    if (total > 0.0) {\n        for (auto& b : bins_) {\n            b.count /= total;\n        }\n    }\n}\n\n\nvoid Histogram::clear(void)\n{\n    values_.clear();\n    binsAreDirty_ = true;\n}\n\n\nHistogram::const_iterator Histogram::begin(void) const\n{\n    computeHistogramIfNeeded();\n    return bins_.begin();\n}\n\n\nHistogram::const_iterator Histogram::end(void) const\n{\n    assert(!binsAreDirty_);\n    return bins_.end();\n}\n\n\nmath::UnivariateGaussianDistribution Histogram::toGaussian(void) const\n{\n    return math::UnivariateGaussianDistribution(values_.begin(), values_.end());\n}\n\n\nvoid Histogram::computeHistogramIfNeeded(void) const\n{\n    if (binsAreDirty_ && !values_.empty()) {\n        if (std::isnan(minValue_) || std::isnan(maxValue_)) {\n            minValue_ = *std::min_element(values_.begin(), values_.end());\n            maxValue_ = *std::max_element(values_.begin(), values_.end());\n        }\n\n        bins_ = split_data_into_bins(values_, minValue_, maxValue_, numBins_);\n        binsAreDirty_ = false;\n    }\n}\n\n\nstd::vector<HistogramBin>\n  split_data_into_bins(const std::vector<double>& data, double minValue, double maxValue, int numBins)\n{\n    if (data.empty() || (numBins == 0)) {\n        return std::vector<HistogramBin>();\n    }\n\n    double range = maxValue - minValue;\n    double binWidth = range / numBins;\n\n    // All bins can't be the same\n    if (binWidth == 0.0) {\n        return std::vector<HistogramBin>();\n    }\n\n    // Construct the bins\n    std::vector<HistogramBin> bins(numBins);\n    bins[0].minValue = minValue;\n    bins[0].maxValue = minValue + binWidth;\n    bins[0].count = 0;\n\n    for (int n = 1; n < numBins; ++n) {\n        bins[n].minValue = bins[n - 1].maxValue;\n        bins[n].maxValue = bins[n].minValue + binWidth;\n        bins[n].count = 0;\n    }\n\n    // Populate the bins\n    for (auto value : data) {\n        int binIdx = (value - minValue) / binWidth;\n        binIdx = boost::algorithm::clamp(binIdx, 0, numBins - 1);\n        bins[binIdx].count++;\n    }\n\n    return bins;\n}\n\n}   // namespace utils\n}   // namespace vulcan\n", "meta": {"hexsha": "3619315048853b186a070a064355de7b71283428", "size": 4310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/utils/histogram.cpp", "max_stars_repo_name": "anuranbaka/Vulcan", "max_stars_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-05T23:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T19:06:50.000Z", "max_issues_repo_path": "src/utils/histogram.cpp", "max_issues_repo_name": "anuranbaka/Vulcan", "max_issues_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-07T01:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-07T01:23:47.000Z", "max_forks_repo_path": "src/utils/histogram.cpp", "max_forks_repo_name": "anuranbaka/Vulcan", "max_forks_repo_head_hexsha": "56339f77f6cf64b5fda876445a33e72cd15ce028", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-03T07:54:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-03T07:54:16.000Z", "avg_line_length": 21.9897959184, "max_line_length": 103, "alphanum_fraction": 0.6348027842, "num_tokens": 1103, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.41442474023174586}}
{"text": "/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// (C) Copyright Ion Gaztanaga 2007-2014\r\n//\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//    (See accompanying file LICENSE_1_0.txt or copy at\r\n//          http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n// See http://www.boost.org/libs/intrusive for documentation.\r\n//\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// The option that yields to non-floating point 1/sqrt(2) alpha is taken\r\n// from the scapegoat tree implementation of the PSPP library.\r\n//\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n#ifndef BOOST_INTRUSIVE_SGTREE_HPP\r\n#define BOOST_INTRUSIVE_SGTREE_HPP\r\n\r\n#include <boost/intrusive/detail/config_begin.hpp>\r\n#include <boost/intrusive/intrusive_fwd.hpp>\r\n#include <boost/intrusive/detail/assert.hpp>\r\n#include <boost/static_assert.hpp>\r\n#include <boost/intrusive/bs_set_hook.hpp>\r\n#include <boost/intrusive/bstree.hpp>\r\n#include <boost/intrusive/detail/tree_node.hpp>\r\n#include <boost/intrusive/pointer_traits.hpp>\r\n#include <boost/intrusive/detail/mpl.hpp>\r\n#include <boost/intrusive/detail/math.hpp>\r\n#include <boost/intrusive/detail/get_value_traits.hpp>\r\n#include <boost/intrusive/sgtree_algorithms.hpp>\r\n#include <boost/intrusive/detail/key_nodeptr_comp.hpp>\r\n#include <boost/intrusive/link_mode.hpp>\r\n\r\n#include <boost/move/utility_core.hpp>\r\n#include <boost/move/adl_move_swap.hpp>\r\n\r\n#include <cstddef>\r\n#include <boost/intrusive/detail/minimal_less_equal_header.hpp>\r\n#include <boost/intrusive/detail/minimal_pair_header.hpp>   //std::pair\r\n#include <cmath>\r\n#include <cstddef>\r\n\r\n#if defined(BOOST_HAS_PRAGMA_ONCE)\r\n#  pragma once\r\n#endif\r\n\r\nnamespace boost {\r\nnamespace intrusive {\r\n\r\n/// @cond\r\n\r\nnamespace detail{\r\n\r\n/////////////////////////////////////////////////////////////\r\n//\r\n//       Halpha for fixed floating_point<false> option\r\n//\r\n/////////////////////////////////////////////////////////////\r\n\r\n//! Returns floor(log2(n)/log2(sqrt(2))) -> floor(2*log2(n))\r\n//! Undefined if N is 0.\r\n//!\r\n//! This function does not use float point operations.\r\ninline std::size_t calculate_h_sqrt2 (std::size_t n)\r\n{\r\n   std::size_t f_log2 = detail::floor_log2(n);\r\n   return (2*f_log2) + static_cast<std::size_t>(n >= detail::sqrt2_pow_2xplus1(f_log2));\r\n}\r\n\r\nstruct h_alpha_sqrt2_t\r\n{\r\n   h_alpha_sqrt2_t(void){}\r\n   std::size_t operator()(std::size_t n) const\r\n   {  return calculate_h_sqrt2(n);  }\r\n};\r\n\r\nstruct alpha_0_75_by_max_size_t\r\n{\r\n   alpha_0_75_by_max_size_t(void){}\r\n\r\n   std::size_t operator()(std::size_t max_tree_size) const\r\n   {\r\n      const std::size_t max_tree_size_limit = ((~std::size_t(0))/std::size_t(3));\r\n      return max_tree_size > max_tree_size_limit ? max_tree_size/4*3 : max_tree_size*3/4;\r\n   }\r\n};\r\n\r\n/////////////////////////////////////////////////////////////\r\n//\r\n//       Halpha for fixed floating_point<true> option\r\n//\r\n/////////////////////////////////////////////////////////////\r\n\r\nstruct h_alpha_t\r\n{\r\n   explicit h_alpha_t(float inv_minus_logalpha)\r\n      :  inv_minus_logalpha_(inv_minus_logalpha)\r\n   {}\r\n\r\n   std::size_t operator()(std::size_t n) const\r\n   {\r\n      ////////////////////////////////////////////////////////////\r\n      // This function must return \"floor(log2(1/alpha(n)))\" ->\r\n      //    floor(log2(n)/log(1/alpha)) ->\r\n      //    floor(log2(n)/-log2(alpha))\r\n      //    floor(log2(n)*(1/-log2(alpha)))\r\n      ////////////////////////////////////////////////////////////\r\n      return static_cast<std::size_t>(detail::fast_log2(float(n))*inv_minus_logalpha_);\r\n   }\r\n\r\n   private:\r\n   //Since the function will be repeatedly called\r\n   //precalculate constant data to avoid repeated\r\n   //calls to log and division.\r\n   //This will store 1/(-std::log2(alpha_))\r\n   float inv_minus_logalpha_;\r\n};\r\n\r\nstruct alpha_by_max_size_t\r\n{\r\n   explicit alpha_by_max_size_t(float alpha)\r\n      :  alpha_(alpha)\r\n   {}\r\n\r\n   float operator()(std::size_t max_tree_size) const\r\n   {  return float(max_tree_size)*alpha_;   }\r\n\r\n   private:\r\n   float alpha_;\r\n};\r\n\r\ntemplate<bool Activate, class SizeType>\r\nstruct alpha_holder\r\n{\r\n   typedef boost::intrusive::detail::h_alpha_t           h_alpha_t;\r\n   typedef boost::intrusive::detail::alpha_by_max_size_t multiply_by_alpha_t;\r\n\r\n   alpha_holder()\r\n      : max_tree_size_()\r\n   {  set_alpha(0.70711f);   } // ~1/sqrt(2)\r\n\r\n   float get_alpha() const\r\n   {  return alpha_;  }\r\n\r\n   void set_alpha(float alpha)\r\n   {\r\n      alpha_ = alpha;\r\n      inv_minus_logalpha_ = 1/(-detail::fast_log2(alpha));\r\n   }\r\n\r\n   h_alpha_t get_h_alpha_t() const\r\n   {  return h_alpha_t(inv_minus_logalpha_);  }\r\n\r\n   multiply_by_alpha_t get_multiply_by_alpha_t() const\r\n   {  return multiply_by_alpha_t(alpha_);  }\r\n\r\n   SizeType &get_max_tree_size()\r\n   {  return max_tree_size_;  }\r\n\r\n   protected:\r\n   float alpha_;\r\n   float inv_minus_logalpha_;\r\n   SizeType max_tree_size_;\r\n};\r\n\r\ntemplate<class SizeType>\r\nstruct alpha_holder<false, SizeType>\r\n{\r\n   //This specialization uses alpha = 1/sqrt(2)\r\n   //without using floating point operations\r\n   //Downside: alpha CAN't be changed.\r\n   typedef boost::intrusive::detail::h_alpha_sqrt2_t           h_alpha_t;\r\n   typedef boost::intrusive::detail::alpha_0_75_by_max_size_t  multiply_by_alpha_t;\r\n\r\n   alpha_holder()\r\n      : max_tree_size_()\r\n   {}\r\n\r\n   float get_alpha() const\r\n   {  return 0.70710677f;  }\r\n\r\n   void set_alpha(float)\r\n   {  //alpha CAN't be changed.\r\n      BOOST_INTRUSIVE_INVARIANT_ASSERT(0);\r\n   }\r\n\r\n   h_alpha_t get_h_alpha_t() const\r\n   {  return h_alpha_t();  }\r\n\r\n   multiply_by_alpha_t get_multiply_by_alpha_t() const\r\n   {  return multiply_by_alpha_t();  }\r\n\r\n   SizeType &get_max_tree_size()\r\n   {  return max_tree_size_;  }\r\n\r\n   protected:\r\n   SizeType max_tree_size_;\r\n};\r\n\r\n}  //namespace detail{\r\n\r\nstruct sgtree_defaults\r\n   : bstree_defaults\r\n{\r\n   static const bool floating_point = true;\r\n};\r\n\r\n/// @endcond\r\n\r\n//! The class template sgtree is an intrusive scapegoat tree container, that\r\n//! is used to construct intrusive sg_set and sg_multiset containers.\r\n//! The no-throw guarantee holds only, if the value_compare object\r\n//! doesn't throw.\r\n//!\r\n//! The template parameter \\c T is the type to be managed by the container.\r\n//! The user can specify additional options and if no options are provided\r\n//! default options are used.\r\n//!\r\n//! The container supports the following options:\r\n//! \\c base_hook<>/member_hook<>/value_traits<>,\r\n//! \\c floating_point<>, \\c size_type<> and\r\n//! \\c compare<>.\r\n#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)\r\ntemplate<class T, class ...Options>\r\n#else\r\ntemplate<class ValueTraits, class VoidOrKeyOfValue, class VoidOrKeyComp, class SizeType, bool FloatingPoint, typename HeaderHolder>\r\n#endif\r\nclass sgtree_impl\r\n   /// @cond\r\n   :  public bstree_impl<ValueTraits, VoidOrKeyOfValue, VoidOrKeyComp, SizeType, true, SgTreeAlgorithms, HeaderHolder>\r\n   ,  public detail::alpha_holder<FloatingPoint, SizeType>\r\n   /// @endcond\r\n{\r\n   public:\r\n   typedef ValueTraits                                               value_traits;\r\n   /// @cond\r\n   typedef bstree_impl< ValueTraits, VoidOrKeyOfValue, VoidOrKeyComp, SizeType\r\n                      , true, SgTreeAlgorithms, HeaderHolder>        tree_type;\r\n   typedef tree_type                                                 implementation_defined;\r\n\r\n   /// @endcond\r\n\r\n   typedef typename implementation_defined::pointer                  pointer;\r\n   typedef typename implementation_defined::const_pointer            const_pointer;\r\n   typedef typename implementation_defined::value_type               value_type;\r\n   typedef typename implementation_defined::key_type                 key_type;\r\n   typedef typename implementation_defined::key_of_value             key_of_value;\r\n   typedef typename implementation_defined::reference                reference;\r\n   typedef typename implementation_defined::const_reference          const_reference;\r\n   typedef typename implementation_defined::difference_type          difference_type;\r\n   typedef typename implementation_defined::size_type                size_type;\r\n   typedef typename implementation_defined::value_compare            value_compare;\r\n   typedef typename implementation_defined::key_compare              key_compare;\r\n   typedef typename implementation_defined::iterator                 iterator;\r\n   typedef typename implementation_defined::const_iterator           const_iterator;\r\n   typedef typename implementation_defined::reverse_iterator         reverse_iterator;\r\n   typedef typename implementation_defined::const_reverse_iterator   const_reverse_iterator;\r\n   typedef typename implementation_defined::node_traits              node_traits;\r\n   typedef typename implementation_defined::node                     node;\r\n   typedef typename implementation_defined::node_ptr                 node_ptr;\r\n   typedef typename implementation_defined::const_node_ptr           const_node_ptr;\r\n   typedef BOOST_INTRUSIVE_IMPDEF(sgtree_algorithms<node_traits>)    node_algorithms;\r\n\r\n   static const bool constant_time_size      = implementation_defined::constant_time_size;\r\n   static const bool floating_point          = FloatingPoint;\r\n   static const bool stateful_value_traits   = implementation_defined::stateful_value_traits;\r\n\r\n   /// @cond\r\n   private:\r\n\r\n   //noncopyable\r\n   typedef detail::alpha_holder<FloatingPoint, SizeType>    alpha_traits;\r\n   typedef typename alpha_traits::h_alpha_t                 h_alpha_t;\r\n   typedef typename alpha_traits::multiply_by_alpha_t       multiply_by_alpha_t;\r\n\r\n   BOOST_MOVABLE_BUT_NOT_COPYABLE(sgtree_impl)\r\n   BOOST_STATIC_ASSERT(((int)value_traits::link_mode != (int)auto_unlink));\r\n\r\n   enum { safemode_or_autounlink  =\r\n            (int)value_traits::link_mode == (int)auto_unlink   ||\r\n            (int)value_traits::link_mode == (int)safe_link     };\r\n\r\n   /// @endcond\r\n\r\n   public:\r\n\r\n   typedef BOOST_INTRUSIVE_IMPDEF(typename node_algorithms::insert_commit_data) insert_commit_data;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::bstree()\r\n   sgtree_impl()\r\n      :  tree_type()\r\n   {}\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::bstree(const key_compare &,const value_traits &)\r\n   explicit sgtree_impl( const key_compare &cmp, const value_traits &v_traits = value_traits())\r\n      :  tree_type(cmp, v_traits)\r\n   {}\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::bstree(bool,Iterator,Iterator,const key_compare &,const value_traits &)\r\n   template<class Iterator>\r\n   sgtree_impl( bool unique, Iterator b, Iterator e\r\n              , const key_compare &cmp     = key_compare()\r\n              , const value_traits &v_traits = value_traits())\r\n      : tree_type(cmp, v_traits)\r\n   {\r\n      if(unique)\r\n         this->insert_unique(b, e);\r\n      else\r\n         this->insert_equal(b, e);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::bstree(bstree &&)\r\n   sgtree_impl(BOOST_RV_REF(sgtree_impl) x)\r\n      :  tree_type(BOOST_MOVE_BASE(tree_type, x)), alpha_traits(x.get_alpha_traits())\r\n   {  ::boost::adl_move_swap(this->get_alpha_traits(), x.get_alpha_traits());   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::operator=(bstree &&)\r\n   sgtree_impl& operator=(BOOST_RV_REF(sgtree_impl) x)\r\n   {\r\n      this->get_alpha_traits() = x.get_alpha_traits();\r\n      return static_cast<sgtree_impl&>(tree_type::operator=(BOOST_MOVE_BASE(tree_type, x)));\r\n   }\r\n\r\n   /// @cond\r\n   private:\r\n\r\n   const alpha_traits &get_alpha_traits() const\r\n   {  return *this;  }\r\n\r\n   alpha_traits &get_alpha_traits()\r\n   {  return *this;  }\r\n\r\n   h_alpha_t get_h_alpha_func() const\r\n   {  return this->get_alpha_traits().get_h_alpha_t();  }\r\n\r\n   multiply_by_alpha_t get_alpha_by_max_size_func() const\r\n   {  return this->get_alpha_traits().get_multiply_by_alpha_t(); }\r\n\r\n   /// @endcond\r\n\r\n   public:\r\n\r\n   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\r\n   //! @copydoc ::boost::intrusive::bstree::~bstree()\r\n   ~sgtree_impl();\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::begin()\r\n   iterator begin();\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::begin()const\r\n   const_iterator begin() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::cbegin()const\r\n   const_iterator cbegin() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::end()\r\n   iterator end();\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::end()const\r\n   const_iterator end() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::cend()const\r\n   const_iterator cend() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::rbegin()\r\n   reverse_iterator rbegin();\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::rbegin()const\r\n   const_reverse_iterator rbegin() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::crbegin()const\r\n   const_reverse_iterator crbegin() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::rend()\r\n   reverse_iterator rend();\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::rend()const\r\n   const_reverse_iterator rend() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::crend()const\r\n   const_reverse_iterator crend() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::root()\r\n   iterator root();\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::root()const\r\n   const_iterator root() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::croot()const\r\n   const_iterator croot() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(iterator)\r\n   static sgtree_impl &container_from_end_iterator(iterator end_iterator);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::container_from_end_iterator(const_iterator)\r\n   static const sgtree_impl &container_from_end_iterator(const_iterator end_iterator);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::container_from_iterator(iterator)\r\n   static sgtree_impl &container_from_iterator(iterator it);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::container_from_iterator(const_iterator)\r\n   static const sgtree_impl &container_from_iterator(const_iterator it);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::key_comp()const\r\n   key_compare key_comp() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::value_comp()const\r\n   value_compare value_comp() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::empty()const\r\n   bool empty() const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::size()const\r\n   size_type size() const;\r\n\r\n   #endif   //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::swap\r\n   void swap(sgtree_impl& other)\r\n   {\r\n      //This can throw\r\n      this->tree_type::swap(static_cast<tree_type&>(other));\r\n      ::boost::adl_move_swap(this->get_alpha_traits(), other.get_alpha_traits());\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::clone_from(const bstree&,Cloner,Disposer)\r\n   //! Additional notes: it also copies the alpha factor from the source container.\r\n   template <class Cloner, class Disposer>\r\n   void clone_from(const sgtree_impl &src, Cloner cloner, Disposer disposer)\r\n   {\r\n      tree_type::clone_from(src, cloner, disposer);\r\n      this->get_alpha_traits() = src.get_alpha_traits();\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::clone_from(bstree&&,Cloner,Disposer)\r\n   //! Additional notes: it also copies the alpha factor from the source container.\r\n   template <class Cloner, class Disposer>\r\n   void clone_from(BOOST_RV_REF(sgtree_impl) src, Cloner cloner, Disposer disposer)\r\n   {\r\n      tree_type::clone_from(BOOST_MOVE_BASE(tree_type, src), cloner, disposer);\r\n      this->get_alpha_traits() = ::boost::move(src.get_alpha_traits());\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::insert_equal(reference)\r\n   iterator insert_equal(reference value)\r\n   {\r\n      node_ptr to_insert(this->get_value_traits().to_node_ptr(value));\r\n      if(safemode_or_autounlink)\r\n         BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert));\r\n      std::size_t max_tree_size = (std::size_t)this->max_tree_size_;\r\n      node_ptr p = node_algorithms::insert_equal_upper_bound\r\n         (this->tree_type::header_ptr(), to_insert, this->key_node_comp(this->key_comp())\r\n         , (size_type)this->size(), this->get_h_alpha_func(), max_tree_size);\r\n      this->tree_type::sz_traits().increment();\r\n      this->max_tree_size_ = (size_type)max_tree_size;\r\n      return iterator(p, this->priv_value_traits_ptr());\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::insert_equal(const_iterator,reference)\r\n   iterator insert_equal(const_iterator hint, reference value)\r\n   {\r\n      node_ptr to_insert(this->get_value_traits().to_node_ptr(value));\r\n      if(safemode_or_autounlink)\r\n         BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert));\r\n      std::size_t max_tree_size = (std::size_t)this->max_tree_size_;\r\n      node_ptr p = node_algorithms::insert_equal\r\n         ( this->tree_type::header_ptr(), hint.pointed_node(), to_insert, this->key_node_comp(this->key_comp())\r\n         , (std::size_t)this->size(), this->get_h_alpha_func(), max_tree_size);\r\n      this->tree_type::sz_traits().increment();\r\n      this->max_tree_size_ = (size_type)max_tree_size;\r\n      return iterator(p, this->priv_value_traits_ptr());\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::insert_equal(Iterator,Iterator)\r\n   template<class Iterator>\r\n   void insert_equal(Iterator b, Iterator e)\r\n   {\r\n      iterator iend(this->end());\r\n      for (; b != e; ++b)\r\n         this->insert_equal(iend, *b);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::insert_unique(reference)\r\n   std::pair<iterator, bool> insert_unique(reference value)\r\n   {\r\n      insert_commit_data commit_data;\r\n      std::pair<iterator, bool> ret = this->insert_unique_check\r\n         (key_of_value()(value), this->key_comp(), commit_data);\r\n      if(!ret.second)\r\n         return ret;\r\n      return std::pair<iterator, bool> (this->insert_unique_commit(value, commit_data), true);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::insert_unique(const_iterator,reference)\r\n   iterator insert_unique(const_iterator hint, reference value)\r\n   {\r\n      insert_commit_data commit_data;\r\n      std::pair<iterator, bool> ret = this->insert_unique_check\r\n         (hint, key_of_value()(value), this->key_comp(), commit_data);\r\n      if(!ret.second)\r\n         return ret.first;\r\n      return this->insert_unique_commit(value, commit_data);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::insert_unique_check(const KeyType&,KeyTypeKeyCompare,insert_commit_data&)\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   BOOST_INTRUSIVE_DOC1ST(std::pair<iterator BOOST_INTRUSIVE_I bool>\r\n      , typename detail::disable_if_convertible\r\n         <KeyType BOOST_INTRUSIVE_I const_iterator BOOST_INTRUSIVE_I \r\n         std::pair<iterator BOOST_INTRUSIVE_I bool> >::type)\r\n      insert_unique_check\r\n      (const KeyType &key, KeyTypeKeyCompare comp, insert_commit_data &commit_data)\r\n   {\r\n      std::pair<node_ptr, bool> ret =\r\n         node_algorithms::insert_unique_check\r\n            (this->tree_type::header_ptr(), key, this->key_node_comp(comp), commit_data);\r\n      return std::pair<iterator, bool>(iterator(ret.first, this->priv_value_traits_ptr()), ret.second);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::insert_unique_check(const_iterator,const KeyType&,KeyTypeKeyCompare,insert_commit_data&)\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   std::pair<iterator, bool> insert_unique_check\r\n      (const_iterator hint, const KeyType &key\r\n      ,KeyTypeKeyCompare comp, insert_commit_data &commit_data)\r\n   {\r\n      std::pair<node_ptr, bool> ret =\r\n         node_algorithms::insert_unique_check\r\n            (this->tree_type::header_ptr(), hint.pointed_node(), key, this->key_node_comp(comp), commit_data);\r\n      return std::pair<iterator, bool>(iterator(ret.first, this->priv_value_traits_ptr()), ret.second);\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::insert_unique_check(const key_type&,insert_commit_data&)\r\n   std::pair<iterator, bool> insert_unique_check\r\n      (const key_type &key, insert_commit_data &commit_data)\r\n   {  return this->insert_unique_check(key, this->key_comp(), commit_data);   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::insert_unique_check(const_iterator,const key_type&,insert_commit_data&)\r\n   std::pair<iterator, bool> insert_unique_check\r\n      (const_iterator hint, const key_type &key, insert_commit_data &commit_data)\r\n   {  return this->insert_unique_check(hint, key, this->key_comp(), commit_data);   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::insert_unique_commit\r\n   iterator insert_unique_commit(reference value, const insert_commit_data &commit_data)\r\n   {\r\n      node_ptr to_insert(this->get_value_traits().to_node_ptr(value));\r\n      if(safemode_or_autounlink)\r\n         BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert));\r\n      std::size_t max_tree_size = (std::size_t)this->max_tree_size_;\r\n      node_algorithms::insert_unique_commit\r\n         ( this->tree_type::header_ptr(), to_insert, commit_data\r\n         , (std::size_t)this->size(), this->get_h_alpha_func(), max_tree_size);\r\n      this->tree_type::sz_traits().increment();\r\n      this->max_tree_size_ = (size_type)max_tree_size;\r\n      return iterator(to_insert, this->priv_value_traits_ptr());\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::insert_unique(Iterator,Iterator)\r\n   template<class Iterator>\r\n   void insert_unique(Iterator b, Iterator e)\r\n   {\r\n      if(this->empty()){\r\n         iterator iend(this->end());\r\n         for (; b != e; ++b)\r\n            this->insert_unique(iend, *b);\r\n      }\r\n      else{\r\n         for (; b != e; ++b)\r\n            this->insert_unique(*b);\r\n      }\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::insert_before\r\n   iterator insert_before(const_iterator pos, reference value)\r\n   {\r\n      node_ptr to_insert(this->get_value_traits().to_node_ptr(value));\r\n      if(safemode_or_autounlink)\r\n         BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert));\r\n      std::size_t max_tree_size = (std::size_t)this->max_tree_size_;\r\n      node_ptr p = node_algorithms::insert_before\r\n         ( this->tree_type::header_ptr(), pos.pointed_node(), to_insert\r\n         , (size_type)this->size(), this->get_h_alpha_func(), max_tree_size);\r\n      this->tree_type::sz_traits().increment();\r\n      this->max_tree_size_ = (size_type)max_tree_size;\r\n      return iterator(p, this->priv_value_traits_ptr());\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::push_back\r\n   void push_back(reference value)\r\n   {\r\n      node_ptr to_insert(this->get_value_traits().to_node_ptr(value));\r\n      if(safemode_or_autounlink)\r\n         BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert));\r\n      std::size_t max_tree_size = (std::size_t)this->max_tree_size_;\r\n      node_algorithms::push_back\r\n         ( this->tree_type::header_ptr(), to_insert\r\n         , (size_type)this->size(), this->get_h_alpha_func(), max_tree_size);\r\n      this->tree_type::sz_traits().increment();\r\n      this->max_tree_size_ = (size_type)max_tree_size;\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::push_front\r\n   void push_front(reference value)\r\n   {\r\n      node_ptr to_insert(this->get_value_traits().to_node_ptr(value));\r\n      if(safemode_or_autounlink)\r\n         BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(to_insert));\r\n      std::size_t max_tree_size = (std::size_t)this->max_tree_size_;\r\n      node_algorithms::push_front\r\n         ( this->tree_type::header_ptr(), to_insert\r\n         , (size_type)this->size(), this->get_h_alpha_func(), max_tree_size);\r\n      this->tree_type::sz_traits().increment();\r\n      this->max_tree_size_ = (size_type)max_tree_size;\r\n   }\r\n\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::erase(const_iterator)\r\n   iterator erase(const_iterator i)\r\n   {\r\n      const_iterator ret(i);\r\n      ++ret;\r\n      node_ptr to_erase(i.pointed_node());\r\n      if(safemode_or_autounlink)\r\n         BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!node_algorithms::unique(to_erase));\r\n      std::size_t max_tree_size = this->max_tree_size_;\r\n      node_algorithms::erase\r\n         ( this->tree_type::header_ptr(), to_erase, (std::size_t)this->size()\r\n         , max_tree_size, this->get_alpha_by_max_size_func());\r\n      this->max_tree_size_ = (size_type)max_tree_size;\r\n      this->tree_type::sz_traits().decrement();\r\n      if(safemode_or_autounlink)\r\n         node_algorithms::init(to_erase);\r\n      return ret.unconst();\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::erase(const_iterator,const_iterator)\r\n   iterator erase(const_iterator b, const_iterator e)\r\n   {  size_type n;   return private_erase(b, e, n);   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::erase(const key_type &)\r\n   size_type erase(const key_type &key)\r\n   {  return this->erase(key, this->key_comp());   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::erase(const KeyType&,KeyTypeKeyCompare)\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   BOOST_INTRUSIVE_DOC1ST(size_type\r\n      , typename detail::disable_if_convertible<KeyTypeKeyCompare BOOST_INTRUSIVE_I const_iterator BOOST_INTRUSIVE_I size_type>::type)\r\n      erase(const KeyType& key, KeyTypeKeyCompare comp)\r\n   {\r\n      std::pair<iterator,iterator> p = this->equal_range(key, comp);\r\n      size_type n;\r\n      private_erase(p.first, p.second, n);\r\n      return n;\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,Disposer)\r\n   template<class Disposer>\r\n   iterator erase_and_dispose(const_iterator i, Disposer disposer)\r\n   {\r\n      node_ptr to_erase(i.pointed_node());\r\n      iterator ret(this->erase(i));\r\n      disposer(this->get_value_traits().to_value_ptr(to_erase));\r\n      return ret;\r\n   }\r\n\r\n   #if !defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)\r\n   template<class Disposer>\r\n   iterator erase_and_dispose(iterator i, Disposer disposer)\r\n   {  return this->erase_and_dispose(const_iterator(i), disposer);   }\r\n   #endif\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const_iterator,const_iterator,Disposer)\r\n   template<class Disposer>\r\n   iterator erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer)\r\n   {  size_type n;   return private_erase(b, e, n, disposer);   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const key_type &, Disposer)\r\n   template<class Disposer>\r\n   size_type erase_and_dispose(const key_type &key, Disposer disposer)\r\n   {\r\n      std::pair<iterator,iterator> p = this->equal_range(key);\r\n      size_type n;\r\n      private_erase(p.first, p.second, n, disposer);\r\n      return n;\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::erase_and_dispose(const KeyType&,KeyTypeKeyCompare,Disposer)\r\n   template<class KeyType, class KeyTypeKeyCompare, class Disposer>\r\n   BOOST_INTRUSIVE_DOC1ST(size_type\r\n      , typename detail::disable_if_convertible<KeyTypeKeyCompare BOOST_INTRUSIVE_I const_iterator BOOST_INTRUSIVE_I size_type>::type)\r\n      erase_and_dispose(const KeyType& key, KeyTypeKeyCompare comp, Disposer disposer)\r\n   {\r\n      std::pair<iterator,iterator> p = this->equal_range(key, comp);\r\n      size_type n;\r\n      private_erase(p.first, p.second, n, disposer);\r\n      return n;\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::clear\r\n   void clear()\r\n   {\r\n      tree_type::clear();\r\n      this->max_tree_size_ = 0;\r\n   }\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::clear_and_dispose\r\n   template<class Disposer>\r\n   void clear_and_dispose(Disposer disposer)\r\n   {\r\n      tree_type::clear_and_dispose(disposer);\r\n      this->max_tree_size_ = 0;\r\n   }\r\n\r\n   #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)\r\n   //! @copydoc ::boost::intrusive::bstree::merge_unique\r\n   template<class T, class ...Options2> void merge_unique(sgtree<T, Options2...> &);\r\n   #else\r\n   template<class Compare2>\r\n   void merge_unique(sgtree_impl\r\n      <ValueTraits, VoidOrKeyOfValue, Compare2, SizeType, FloatingPoint, HeaderHolder> &source)\r\n   #endif\r\n   {\r\n      node_ptr it   (node_algorithms::begin_node(source.header_ptr()))\r\n             , itend(node_algorithms::end_node  (source.header_ptr()));\r\n\r\n      while(it != itend){\r\n         node_ptr const p(it);\r\n         BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!safemode_or_autounlink || !node_algorithms::unique(p));\r\n         it = node_algorithms::next_node(it);\r\n\r\n         std::size_t max_tree1_size = this->max_tree_size_;\r\n         std::size_t max_tree2_size = source.get_max_tree_size();\r\n         if( node_algorithms::transfer_unique\r\n               ( this->header_ptr(), this->key_node_comp(this->key_comp()), this->size(), max_tree1_size\r\n               , source.header_ptr(), p, source.size(), max_tree2_size\r\n               , this->get_h_alpha_func(), this->get_alpha_by_max_size_func()) ){\r\n            this->max_tree_size_  = (size_type)max_tree1_size;\r\n            this->sz_traits().increment();\r\n            source.get_max_tree_size() = (size_type)max_tree2_size;\r\n            source.sz_traits().decrement();\r\n         }\r\n      }\r\n   }\r\n\r\n   #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)\r\n   //! @copydoc ::boost::intrusive::bstree::merge_equal\r\n   template<class T, class ...Options2> void merge_equal(sgtree<T, Options2...> &);\r\n   #else\r\n   template<class Compare2>\r\n   void merge_equal(sgtree_impl\r\n      <ValueTraits, VoidOrKeyOfValue, Compare2, SizeType, FloatingPoint, HeaderHolder> &source)\r\n   #endif\r\n   {\r\n      node_ptr it   (node_algorithms::begin_node(source.header_ptr()))\r\n             , itend(node_algorithms::end_node  (source.header_ptr()));\r\n\r\n      while(it != itend){\r\n         node_ptr const p(it);\r\n         BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(!safemode_or_autounlink || !node_algorithms::unique(p));\r\n         it = node_algorithms::next_node(it);\r\n         std::size_t max_tree1_size = this->max_tree_size_;\r\n         std::size_t max_tree2_size = source.get_max_tree_size();\r\n         node_algorithms::transfer_equal\r\n            ( this->header_ptr(), this->key_node_comp(this->key_comp()), this->size(), max_tree1_size\r\n            , source.header_ptr(), p, source.size(), max_tree2_size\r\n            , this->get_h_alpha_func(), this->get_alpha_by_max_size_func());\r\n         this->max_tree_size_  = (size_type)max_tree1_size;\r\n         this->sz_traits().increment();\r\n         source.get_max_tree_size() = (size_type)max_tree2_size;\r\n         source.sz_traits().decrement();\r\n      }\r\n   }\r\n\r\n   #ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\r\n   //! @copydoc ::boost::intrusive::bstree::count(const key_type &)const\r\n   size_type count(const key_type &key) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::count(const KeyType&,KeyTypeKeyCompare)const\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   size_type count(const KeyType& key, KeyTypeKeyCompare comp) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::lower_bound(const key_type &)\r\n   iterator lower_bound(const key_type &key);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyTypeKeyCompare)\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   iterator lower_bound(const KeyType& key, KeyTypeKeyCompare comp);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::lower_bound(const key_type &)const\r\n   const_iterator lower_bound(const key_type &key) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::lower_bound(const KeyType&,KeyTypeKeyCompare)const\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   const_iterator lower_bound(const KeyType& key, KeyTypeKeyCompare comp) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::upper_bound(const key_type &)\r\n   iterator upper_bound(const key_type &key);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyTypeKeyCompare)\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   iterator upper_bound(const KeyType& key, KeyTypeKeyCompare comp);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::upper_bound(const key_type &)const\r\n   const_iterator upper_bound(const key_type &key) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::upper_bound(const KeyType&,KeyTypeKeyCompare)const\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   const_iterator upper_bound(const KeyType& key, KeyTypeKeyCompare comp) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::find(const key_type &)\r\n   iterator find(const key_type &key);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyTypeKeyCompare)\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   iterator find(const KeyType& key, KeyTypeKeyCompare comp);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::find(const key_type &)const\r\n   const_iterator find(const key_type &key) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::find(const KeyType&,KeyTypeKeyCompare)const\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   const_iterator find(const KeyType& key, KeyTypeKeyCompare comp) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::equal_range(const key_type &)\r\n   std::pair<iterator,iterator> equal_range(const key_type &key);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyTypeKeyCompare)\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   std::pair<iterator,iterator> equal_range(const KeyType& key, KeyTypeKeyCompare comp);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::equal_range(const key_type &)const\r\n   std::pair<const_iterator, const_iterator>\r\n      equal_range(const key_type &key) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::equal_range(const KeyType&,KeyTypeKeyCompare)const\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   std::pair<const_iterator, const_iterator>\r\n      equal_range(const KeyType& key, KeyTypeKeyCompare comp) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::bounded_range(const key_type &,const key_type &,bool,bool)\r\n   std::pair<iterator,iterator> bounded_range\r\n      (const key_type &lower_key, const key_type &upper_key, bool left_closed, bool right_closed);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyTypeKeyCompare,bool,bool)\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   std::pair<iterator,iterator> bounded_range\r\n      (const KeyType& lower_key, const KeyType& upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::bounded_range(const key_type &,const key_type &,bool,bool)const\r\n   std::pair<const_iterator, const_iterator>\r\n      bounded_range(const key_type &lower_key, const key_type &upper_key, bool left_closed, bool right_closed) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::bounded_range(const KeyType&,const KeyType&,KeyTypeKeyCompare,bool,bool)const\r\n   template<class KeyType, class KeyTypeKeyCompare>\r\n   std::pair<const_iterator, const_iterator> bounded_range\r\n         (const KeyType& lower_key, const KeyType& upper_key, KeyTypeKeyCompare comp, bool left_closed, bool right_closed) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::s_iterator_to(reference)\r\n   static iterator s_iterator_to(reference value);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::s_iterator_to(const_reference)\r\n   static const_iterator s_iterator_to(const_reference value);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::iterator_to(reference)\r\n   iterator iterator_to(reference value);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::iterator_to(const_reference)const\r\n   const_iterator iterator_to(const_reference value) const;\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::init_node(reference)\r\n   static void init_node(reference value);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::unlink_leftmost_without_rebalance\r\n   pointer unlink_leftmost_without_rebalance();\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::replace_node\r\n   void replace_node(iterator replace_this, reference with_this);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::remove_node\r\n   void remove_node(reference value);\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::rebalance\r\n   void rebalance();\r\n\r\n   //! @copydoc ::boost::intrusive::bstree::rebalance_subtree\r\n   iterator rebalance_subtree(iterator root);\r\n\r\n   friend bool operator< (const sgtree_impl &x, const sgtree_impl &y);\r\n\r\n   friend bool operator==(const sgtree_impl &x, const sgtree_impl &y);\r\n\r\n   friend bool operator!= (const sgtree_impl &x, const sgtree_impl &y);\r\n\r\n   friend bool operator>(const sgtree_impl &x, const sgtree_impl &y);\r\n\r\n   friend bool operator<=(const sgtree_impl &x, const sgtree_impl &y);\r\n\r\n   friend bool operator>=(const sgtree_impl &x, const sgtree_impl &y);\r\n\r\n   friend void swap(sgtree_impl &x, sgtree_impl &y);\r\n\r\n   #endif   //#ifdef BOOST_INTRUSIVE_DOXYGEN_INVOKED\r\n\r\n   //! <b>Returns</b>: The balance factor (alpha) used in this tree\r\n   //!\r\n   //! <b>Throws</b>: Nothing.\r\n   //!\r\n   //! <b>Complexity</b>: Constant.\r\n   float balance_factor() const\r\n   {  return this->get_alpha_traits().get_alpha(); }\r\n\r\n   //! <b>Requires</b>: new_alpha must be a value between 0.5 and 1.0\r\n   //!\r\n   //! <b>Effects</b>: Establishes a new balance factor (alpha) and rebalances\r\n   //!   the tree if the new balance factor is stricter (less) than the old factor.\r\n   //!\r\n   //! <b>Throws</b>: Nothing.\r\n   //!\r\n   //! <b>Complexity</b>: Linear to the elements in the subtree.\r\n   void balance_factor(float new_alpha)\r\n   {\r\n      //The alpha factor CAN't be changed if the fixed, floating operation-less\r\n      //1/sqrt(2) alpha factor option is activated\r\n      BOOST_STATIC_ASSERT((floating_point));\r\n      BOOST_INTRUSIVE_INVARIANT_ASSERT((new_alpha > 0.5f && new_alpha < 1.0f));\r\n      if(new_alpha >= 0.5f && new_alpha < 1.0f){\r\n         float old_alpha = this->get_alpha_traits().get_alpha();\r\n         this->get_alpha_traits().set_alpha(new_alpha);\r\n         if(new_alpha < old_alpha){\r\n            this->max_tree_size_ = this->size();\r\n            this->rebalance();\r\n         }\r\n      }\r\n   }\r\n\r\n   /// @cond\r\n   private:\r\n   template<class Disposer>\r\n   iterator private_erase(const_iterator b, const_iterator e, size_type &n, Disposer disposer)\r\n   {\r\n      for(n = 0; b != e; ++n)\r\n        this->erase_and_dispose(b++, disposer);\r\n      return b.unconst();\r\n   }\r\n\r\n   iterator private_erase(const_iterator b, const_iterator e, size_type &n)\r\n   {\r\n      for(n = 0; b != e; ++n)\r\n        this->erase(b++);\r\n      return b.unconst();\r\n   }\r\n   /// @endcond\r\n};\r\n\r\n\r\n//! Helper metafunction to define a \\c sgtree that yields to the same type when the\r\n//! same options (either explicitly or implicitly) are used.\r\n#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)\r\ntemplate<class T, class ...Options>\r\n#else\r\ntemplate<class T, class O1 = void, class O2 = void\r\n                , class O3 = void, class O4 = void\r\n                , class O5 = void, class O6 = void>\r\n#endif\r\nstruct make_sgtree\r\n{\r\n   /// @cond\r\n   typedef typename pack_options\r\n      < sgtree_defaults,\r\n      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)\r\n      O1, O2, O3, O4, O5, O6\r\n      #else\r\n      Options...\r\n      #endif\r\n      >::type packed_options;\r\n\r\n   typedef typename detail::get_value_traits\r\n      <T, typename packed_options::proto_value_traits>::type value_traits;\r\n\r\n   typedef sgtree_impl\r\n         < value_traits\r\n         , typename packed_options::key_of_value\r\n         , typename packed_options::compare\r\n         , typename packed_options::size_type\r\n         , packed_options::floating_point\r\n         , typename packed_options::header_holder_type\r\n         > implementation_defined;\r\n   /// @endcond\r\n   typedef implementation_defined type;\r\n};\r\n\r\n\r\n#ifndef BOOST_INTRUSIVE_DOXYGEN_INVOKED\r\n\r\n#if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)\r\ntemplate<class T, class O1, class O2, class O3, class O4, class O5, class O6>\r\n#else\r\ntemplate<class T, class ...Options>\r\n#endif\r\nclass sgtree\r\n   :  public make_sgtree<T,\r\n      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)\r\n      O1, O2, O3, O4, O5, O6\r\n      #else\r\n      Options...\r\n      #endif\r\n      >::type\r\n{\r\n   typedef typename make_sgtree\r\n      <T,\r\n      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)\r\n      O1, O2, O3, O4, O5, O6\r\n      #else\r\n      Options...\r\n      #endif\r\n      >::type   Base;\r\n   BOOST_MOVABLE_BUT_NOT_COPYABLE(sgtree)\r\n\r\n   public:\r\n   typedef typename Base::key_compare        key_compare;\r\n   typedef typename Base::value_traits       value_traits;\r\n   typedef typename Base::iterator           iterator;\r\n   typedef typename Base::const_iterator     const_iterator;\r\n   typedef typename Base::reverse_iterator           reverse_iterator;\r\n   typedef typename Base::const_reverse_iterator     const_reverse_iterator;\r\n\r\n   //Assert if passed value traits are compatible with the type\r\n   BOOST_STATIC_ASSERT((detail::is_same<typename value_traits::value_type, T>::value));\r\n\r\n   sgtree()\r\n      :  Base()\r\n   {}\r\n\r\n   explicit sgtree(const key_compare &cmp, const value_traits &v_traits = value_traits())\r\n      :  Base(cmp, v_traits)\r\n   {}\r\n\r\n   template<class Iterator>\r\n   sgtree( bool unique, Iterator b, Iterator e\r\n         , const key_compare &cmp = key_compare()\r\n         , const value_traits &v_traits = value_traits())\r\n      :  Base(unique, b, e, cmp, v_traits)\r\n   {}\r\n\r\n   sgtree(BOOST_RV_REF(sgtree) x)\r\n      :  Base(BOOST_MOVE_BASE(Base, x))\r\n   {}\r\n\r\n   sgtree& operator=(BOOST_RV_REF(sgtree) x)\r\n   {  return static_cast<sgtree &>(this->Base::operator=(BOOST_MOVE_BASE(Base, x)));  }\r\n\r\n   template <class Cloner, class Disposer>\r\n   void clone_from(const sgtree &src, Cloner cloner, Disposer disposer)\r\n   {  Base::clone_from(src, cloner, disposer);  }\r\n\r\n   template <class Cloner, class Disposer>\r\n   void clone_from(BOOST_RV_REF(sgtree) src, Cloner cloner, Disposer disposer)\r\n   {  Base::clone_from(BOOST_MOVE_BASE(Base, src), cloner, disposer);  }\r\n\r\n   static sgtree &container_from_end_iterator(iterator end_iterator)\r\n   {  return static_cast<sgtree &>(Base::container_from_end_iterator(end_iterator));   }\r\n\r\n   static const sgtree &container_from_end_iterator(const_iterator end_iterator)\r\n   {  return static_cast<const sgtree &>(Base::container_from_end_iterator(end_iterator));   }\r\n\r\n   static sgtree &container_from_iterator(iterator it)\r\n   {  return static_cast<sgtree &>(Base::container_from_iterator(it));   }\r\n\r\n   static const sgtree &container_from_iterator(const_iterator it)\r\n   {  return static_cast<const sgtree &>(Base::container_from_iterator(it));   }\r\n};\r\n\r\n#endif\r\n\r\n} //namespace intrusive\r\n} //namespace boost\r\n\r\n#include <boost/intrusive/detail/config_end.hpp>\r\n\r\n#endif //BOOST_INTRUSIVE_SGTREE_HPP\r\n", "meta": {"hexsha": "c8cb77813d8f2fcac37cd5df0371e2e5ee702c0b", "size": 42666, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/intrusive/sgtree.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/intrusive/sgtree.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/intrusive/sgtree.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 39.4325323475, "max_line_length": 135, "alphanum_fraction": 0.6740495945, "num_tokens": 10417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.41441299646599733}}
{"text": "// Copyright 2020 Tier IV, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"detection_by_tracker/utils.hpp\"\n\n#include <boost/geometry.hpp>\n\n#include <tf2/LinearMath/Quaternion.h>\n#include <tf2/utils.h>\n\n#include <algorithm>\n#include <vector>\n\nnamespace utils\n{\nvoid toPolygon2d(\n  const autoware_perception_msgs::msg::DynamicObject & object, autoware_utils::Polygon2d & output);\nbool isClockWise(const autoware_utils::Polygon2d & polygon);\nautoware_utils::Polygon2d inverseClockWise(const autoware_utils::Polygon2d & polygon);\n\ndouble getArea(const autoware_perception_msgs::msg::Shape & shape)\n{\n  double area = 0.0;\n  if (shape.type == autoware_perception_msgs::msg::Shape::BOUNDING_BOX) {\n    area = getRectangleArea(shape.dimensions);\n  } else if (shape.type == autoware_perception_msgs::msg::Shape::CYLINDER) {\n    area = getCircleArea(shape.dimensions);\n  } else if (shape.type == autoware_perception_msgs::msg::Shape::POLYGON) {\n    area = getPolygonArea(shape.footprint);\n  }\n  return area;\n}\n\ndouble getPolygonArea(const geometry_msgs::msg::Polygon & footprint)\n{\n  double area = 0.0;\n\n  for (size_t i = 0; i < footprint.points.size(); ++i) {\n    size_t j = (i + 1) % footprint.points.size();\n    area += 0.5 * (footprint.points.at(i).x * footprint.points.at(j).y -\n                   footprint.points.at(j).x * footprint.points.at(i).y);\n  }\n\n  return area;\n}\n\ndouble getRectangleArea(const geometry_msgs::msg::Vector3 & dimensions)\n{\n  return static_cast<double>(dimensions.x * dimensions.y);\n}\n\ndouble getCircleArea(const geometry_msgs::msg::Vector3 & dimensions)\n{\n  return static_cast<double>((dimensions.x / 2.0) * (dimensions.x / 2.0) * M_PI);\n}\n\ndouble get2dIoU(\n  const autoware_perception_msgs::msg::DynamicObject & object1,\n  const autoware_perception_msgs::msg::DynamicObject & object2)\n{\n  autoware_utils::Polygon2d polygon1, polygon2;\n  toPolygon2d(object1, polygon1);\n  toPolygon2d(object2, polygon2);\n\n  std::vector<autoware_utils::Polygon2d> union_polygons;\n  std::vector<autoware_utils::Polygon2d> intersection_polygons;\n  boost::geometry::union_(polygon1, polygon2, union_polygons);\n  boost::geometry::intersection(polygon1, polygon2, intersection_polygons);\n\n  double union_area = 0.0;\n  double intersection_area = 0.0;\n  for (const auto & union_polygon : union_polygons) {\n    union_area += boost::geometry::area(union_polygon);\n  }\n  for (const auto & intersection_polygon : intersection_polygons) {\n    intersection_area += boost::geometry::area(intersection_polygon);\n  }\n  const double iou = union_area < 0.01 ? 0.0 : std::min(1.0, intersection_area / union_area);\n  return iou;\n}\n\ndouble get2dPrecision(\n  const autoware_perception_msgs::msg::DynamicObject & source_object,\n  const autoware_perception_msgs::msg::DynamicObject & target_object)\n{\n  autoware_utils::Polygon2d source_polygon, target_polygon;\n  toPolygon2d(source_object, source_polygon);\n  toPolygon2d(target_object, target_polygon);\n\n  std::vector<autoware_utils::Polygon2d> intersection_polygons;\n  boost::geometry::intersection(source_polygon, target_polygon, intersection_polygons);\n\n  double intersection_area = 0.0;\n  double source_area = 0.0;\n  for (const auto & intersection_polygon : intersection_polygons) {\n    intersection_area += boost::geometry::area(intersection_polygon);\n  }\n  source_area = boost::geometry::area(source_polygon);\n  const double precision = std::min(1.0, intersection_area / source_area);\n  return precision;\n}\n\ndouble get2dRecall(\n  const autoware_perception_msgs::msg::DynamicObject & source_object,\n  const autoware_perception_msgs::msg::DynamicObject & target_object)\n{\n  autoware_utils::Polygon2d source_polygon, target_polygon;\n  toPolygon2d(source_object, source_polygon);\n  toPolygon2d(target_object, target_polygon);\n\n  std::vector<autoware_utils::Polygon2d> intersection_polygons;\n  // boost::geometry::union_(source_polygon, target_polygon, intersection_polygons);    // 原来的\n  boost::geometry::intersection(source_polygon, target_polygon, intersection_polygons); // 我改的\n\n  double intersection_area = 0.0;\n  double target_area = 0.0;\n  for (const auto & intersection_polygon : intersection_polygons) {\n    intersection_area += boost::geometry::area(intersection_polygon);\n  }\n  target_area += boost::geometry::area(target_polygon);\n  const double recall = std::min(1.0, intersection_area / target_area);\n  return recall;\n}\n\nautoware_utils::Polygon2d inverseClockWise(const autoware_utils::Polygon2d & polygon)\n{\n  autoware_utils::Polygon2d inverted_polygon;\n  for (int i = polygon.outer().size() - 1; 0 <= i; --i) {\n    inverted_polygon.outer().push_back(polygon.outer().at(i));\n  }\n  return inverted_polygon;\n}\n\nbool isClockWise(const autoware_utils::Polygon2d & polygon)\n{\n  const int n = polygon.outer().size();\n  const double x_offset = polygon.outer().at(0).x();\n  const double y_offset = polygon.outer().at(0).y();\n  double sum = 0.0;\n  for (std::size_t i = 0; i < polygon.outer().size(); ++i) {\n    sum +=\n      (polygon.outer().at(i).x() - x_offset) * (polygon.outer().at((i + 1) % n).y() - y_offset) -\n      (polygon.outer().at(i).y() - y_offset) * (polygon.outer().at((i + 1) % n).x() - x_offset);\n  }\n\n  return sum < 0.0;\n}\n\nvoid toPolygon2d(\n  const autoware_perception_msgs::msg::DynamicObject & object, autoware_utils::Polygon2d & output)\n{\n  if (object.shape.type == autoware_perception_msgs::msg::Shape::BOUNDING_BOX) {\n    const auto & pose = object.state.pose_covariance.pose;\n    const double yaw = autoware_utils::normalizeRadian(tf2::getYaw(pose.orientation));\n    Eigen::Matrix2d rotation;\n    rotation << std::cos(yaw), -std::sin(yaw), std::sin(yaw), std::cos(yaw);\n    Eigen::Vector2d offset0, offset1, offset2, offset3;\n    offset0 = rotation *\n              Eigen::Vector2d(object.shape.dimensions.x * 0.5f, object.shape.dimensions.y * 0.5f);\n    offset1 = rotation *\n              Eigen::Vector2d(object.shape.dimensions.x * 0.5f, -object.shape.dimensions.y * 0.5f);\n    offset2 = rotation *\n              Eigen::Vector2d(-object.shape.dimensions.x * 0.5f, -object.shape.dimensions.y * 0.5f);\n    offset3 = rotation *\n              Eigen::Vector2d(-object.shape.dimensions.x * 0.5f, object.shape.dimensions.y * 0.5f);\n    output.outer().push_back(boost::geometry::make<autoware_utils::Point2d>(\n      pose.position.x + offset0.x(), pose.position.y + offset0.y()));\n    output.outer().push_back(boost::geometry::make<autoware_utils::Point2d>(\n      pose.position.x + offset1.x(), pose.position.y + offset1.y()));\n    output.outer().push_back(boost::geometry::make<autoware_utils::Point2d>(\n      pose.position.x + offset2.x(), pose.position.y + offset2.y()));\n    output.outer().push_back(boost::geometry::make<autoware_utils::Point2d>(\n      pose.position.x + offset3.x(), pose.position.y + offset3.y()));\n    output.outer().push_back(output.outer().front());\n  } else if (object.shape.type == autoware_perception_msgs::msg::Shape::CYLINDER) {\n    const auto & center = object.state.pose_covariance.pose.position;\n    const auto & radius = object.shape.dimensions.x * 0.5;\n    constexpr int n = 6;\n    for (int i = 0; i < n; ++i) {\n      Eigen::Vector2d point;\n      point.x() = std::cos(\n                    (static_cast<double>(i) / static_cast<double>(n)) * 2.0 * M_PI +\n                    M_PI / static_cast<double>(n)) *\n                    radius +\n                  center.x;\n      point.y() = std::sin(\n                    (static_cast<double>(i) / static_cast<double>(n)) * 2.0 * M_PI +\n                    M_PI / static_cast<double>(n)) *\n                    radius +\n                  center.y;\n      output.outer().push_back(\n        boost::geometry::make<autoware_utils::Point2d>(point.x(), point.y()));\n    }\n    output.outer().push_back(output.outer().front());\n  } else if (object.shape.type == autoware_perception_msgs::msg::Shape::POLYGON) {\n    const auto & pose = object.state.pose_covariance.pose;\n    for (const auto & point : object.shape.footprint.points) {\n      output.outer().push_back(boost::geometry::make<autoware_utils::Point2d>(\n        pose.position.x + point.x, pose.position.y + point.y));\n    }\n    output.outer().push_back(output.outer().front());\n  }\n  output = isClockWise(output) ? output : inverseClockWise(output);\n}\n\n}  // namespace utils\n", "meta": {"hexsha": "0ee9228e5aa924e80769c8b8a8247abc9e9cbf66", "size": 8777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "perception/object_recognition/detection/detection_by_tracker/src/utils.cpp", "max_stars_repo_name": "autocore-ai/AutowareArchitectureProposal.ac", "max_stars_repo_head_hexsha": "cd119d3531c0444a0f3e4528a1e6e9db359331e1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-09T05:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T05:53:04.000Z", "max_issues_repo_path": "perception/object_recognition/detection/detection_by_tracker/src/utils.cpp", "max_issues_repo_name": "autocore-ai/AutowareArchitectureProposal.ac", "max_issues_repo_head_hexsha": "cd119d3531c0444a0f3e4528a1e6e9db359331e1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2022-01-07T21:21:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-14T21:25:37.000Z", "max_forks_repo_path": "perception/object_recognition/detection/detection_by_tracker/src/utils.cpp", "max_forks_repo_name": "autocore-ai/AutowareArchitectureProposal.iv", "max_forks_repo_head_hexsha": "cd119d3531c0444a0f3e4528a1e6e9db359331e1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-09T00:20:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T10:23:36.000Z", "avg_line_length": 40.2614678899, "max_line_length": 100, "alphanum_fraction": 0.6980745129, "num_tokens": 2324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4143395452133816}}
{"text": "// std c\n#include <stdio.h>\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <ctime>\n\n// opencv pcl\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/core.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include \"opencv2/imgproc/imgproc.hpp\"\n\n// ros\n#include <ros/ros.h>\n#include <sensor_msgs/Image.h>\n#include <sensor_msgs/CameraInfo.h>\n#include <sensor_msgs/PointCloud2.h>\n\n// Eigen\n#include <Eigen/Dense>\n#include <Eigen/Core>\n\n// ours\n#include \"detect_3d_cuboid/matrix_utils.h\"\n#include \"detect_3d_cuboid/object_3d_util.h\"\n#include \"tictoc_profiler/profiler.hpp\"\n\nusing namespace std;\n// using namespace cv;\nusing namespace Eigen;\n\nvoid detect_3d_cuboid::set_calibration(const Matrix3d &Kalib)\n{\n\tcam_pose.Kalib = Kalib;\n\tcam_pose.invK = Kalib.inverse();\n}\n\nvoid detect_3d_cuboid::set_cam_pose(const Matrix4d &transToWolrd)\n{\n\tcam_pose.transToWolrd = transToWolrd;\n\tcam_pose.rotationToWorld = transToWolrd.topLeftCorner<3, 3>();\n\tVector3d euler_angles;\n\tquat_to_euler_zyx(Quaterniond(cam_pose.rotationToWorld), euler_angles(0), euler_angles(1), euler_angles(2));\n\tcam_pose.euler_angle = euler_angles;\n\tcam_pose.invR = cam_pose.rotationToWorld.inverse();\n\tcam_pose.projectionMatrix = cam_pose.Kalib * transToWolrd.inverse().topRows<3>(); // project world coordinate to camera\n\tcam_pose.KinvR = cam_pose.Kalib * cam_pose.invR;\n\tcam_pose.camera_yaw = cam_pose.euler_angle(2);\n\t//TODO relative measure? not good... then need to change transToWolrd.\n}\n\nvoid detect_3d_cuboid::detect_cuboid(const cv::Mat &rgb_img, const Matrix4d &transToWolrd, const MatrixXd &obj_bbox_coors,\n\t\t\t\t\t\t\t\t\t MatrixXd all_lines_raw, std::vector<ObjectSet> &all_object_cuboids)\n{\n\tset_cam_pose(transToWolrd);\n\tcam_pose_raw = cam_pose;\n\n\tcv::Mat gray_img;\n\tif (rgb_img.channels() == 3)\n\t\tcv::cvtColor(rgb_img, gray_img, cv::COLOR_BGR2GRAY);\n\telse\n\t\tgray_img = rgb_img;\n\n\tint img_width = rgb_img.cols;\n\tint img_height = rgb_img.rows;\n\n\tint num_2d_objs = obj_bbox_coors.rows();\n\tall_object_cuboids.resize(num_2d_objs);\n\n\tvector<bool> all_configs;\n\tall_configs.push_back(consider_config_1);\n\tall_configs.push_back(consider_config_2);\n\n\t// parameters for cuboid generation\n\tdouble vp12_edge_angle_thre = 15;\n\tdouble vp3_edge_angle_thre = 10;\t// 10  10  parameters\n\tdouble shorted_edge_thre = 20;\t\t// if box edge are too short. box might be too thin. most possibly wrong.\n\tbool reweight_edge_distance = true; // if want to compare with all configurations. we need to reweight\n\n\t// parameters for proposal scoring\n\tbool whether_normalize_two_errors = true;\n\tdouble weight_vp_angle = 0.8;\n\tdouble weight_skew_error = 1.5;\n\t// if also consider config2, need to weight two erros, in order to compare two configurations\n\n\talign_left_right_edges(all_lines_raw); // this should be guaranteed when detecting edges\n\tif (whether_plot_detail_images)\n\t{\n\t\tcv::Mat output_img;\n\t\tplot_image_with_edges(rgb_img, output_img, all_lines_raw, cv::Scalar(255, 0, 0));\n\t\tcv::imshow(\"Raw detected Edges\", output_img); //cv::waitKey(0);\n\t}\n\n\t// find ground-wall boundary edges\n\tVector4d ground_plane_world(0, 0, 1, 0); // treated as column vector % in my pop-up code, I use [0 0 -1 0]. here I want the normal pointing innerwards, towards the camera to match surface normal prediction\n\tVector4d ground_plane_sensor = cam_pose.transToWolrd.transpose() * ground_plane_world;\n\n\t//       int object_id=1;\n\tfor (int object_id = 0; object_id < num_2d_objs; object_id++)\n\t{\n\t\t// \t  std::cout<<\"object id  \"<<object_id<<std::endl;\n\t\tca::Profiler::tictoc(\"One 3D object total time\");\n\t\tint left_x_raw = obj_bbox_coors(object_id, 0);\n\t\tint top_y_raw = obj_bbox_coors(object_id, 1);\n\t\tint obj_width_raw = obj_bbox_coors(object_id, 2);\n\t\tint obj_height_raw = obj_bbox_coors(object_id, 3);\n\t\tint right_x_raw = left_x_raw + obj_bbox_coors(object_id, 2);\n\t\tint down_y_raw = top_y_raw + obj_height_raw;\n\n\t\tstd::vector<int> down_expand_sample_all;\n\t\tdown_expand_sample_all.push_back(0);\n\t\tif (whether_sample_bbox_height) // 2D object detection might not be accurate\n\t\t{\n\t\t\tint down_expand_sample_ranges = max(min(20, obj_height_raw - 90), 20);\n\t\t\tdown_expand_sample_ranges = min(down_expand_sample_ranges, img_height - top_y_raw - obj_height_raw - 1); // should lie inside the image  -1 for c++ index\n\t\t\tif (down_expand_sample_ranges > 10)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // if expand large margin, give more samples.\n\t\t\t\tdown_expand_sample_all.push_back(round(down_expand_sample_ranges / 2));\n\t\t\tdown_expand_sample_all.push_back(down_expand_sample_ranges);\n\t\t}\n\n\t\t// NOTE later if in video, could use previous object yaw..., also reduce search range\n\t\tdouble yaw_init = cam_pose.camera_yaw - 90.0 / 180.0 * M_PI; // yaw init is directly facing the camera, align with camera optical axis\n\t\tstd::vector<double> obj_yaw_samples;\n\t\tlinespace<double>(yaw_init - 45.0 / 180.0 * M_PI, yaw_init + 45.0 / 180.0 * M_PI, 6.0 / 180.0 * M_PI, obj_yaw_samples);\n\n\t\tMatrixXd all_configs_errors(400, 9);\n\t\tMatrixXd all_box_corners_2ds(800, 8);   // initialize a large eigen matrix\n\t\tint valid_config_number_all_height = 0; // all valid objects of all height samples\n\t\tObjectSet raw_obj_proposals;\n\t\traw_obj_proposals.reserve(100);\n\t\t// \t    int sample_down_expan_id=1;\n\t\tfor (int sample_down_expan_id = 0; sample_down_expan_id < down_expand_sample_all.size(); sample_down_expan_id++)\n\t\t{\n\t\t\tint down_expand_sample = down_expand_sample_all[sample_down_expan_id];\n\t\t\tint obj_height_expan = obj_height_raw + down_expand_sample;\n\t\t\tint down_y_expan = top_y_raw + obj_height_expan;\n\t\t\tdouble obj_diaglength_expan = sqrt(obj_width_raw * obj_width_raw + obj_height_expan * obj_height_expan);\n\n\t\t\t// sample points on the top edges, if edge is too large, give more samples. give at least 10 samples for all edges. for small object, object pose changes lots\n\t\t\tint top_sample_resolution = round(min(20, obj_width_raw / 10)); //  25 pixels\n\t\t\tstd::vector<int> top_x_samples;\n\t\t\tlinespace<int>(left_x_raw + 5, right_x_raw - 5, top_sample_resolution, top_x_samples);\n\t\t\tMatrixXd sample_top_pts(2, top_x_samples.size());\n\t\t\tfor (int ii = 0; ii < top_x_samples.size(); ii++)\n\t\t\t{\n\t\t\t\tsample_top_pts(0, ii) = top_x_samples[ii];\n\t\t\t\tsample_top_pts(1, ii) = top_y_raw;\n\t\t\t}\n\n\t\t\t// expand some small margin for distance map  [10 20]\n\t\t\tint distmap_expand_wid = min(max(min(20, obj_width_raw - 100), 10), max(min(20, obj_height_expan - 100), 10));\n\t\t\tint left_x_expan_distmap = max(0, left_x_raw - distmap_expand_wid);\n\t\t\tint right_x_expan_distmap = min(img_width - 1, right_x_raw + distmap_expand_wid);\n\t\t\tint top_y_expan_distmap = max(0, top_y_raw - distmap_expand_wid);\n\t\t\tint down_y_expan_distmap = min(img_height - 1, down_y_expan + distmap_expand_wid);\n\t\t\tint height_expan_distmap = down_y_expan_distmap - top_y_expan_distmap;\n\t\t\tint width_expan_distmap = right_x_expan_distmap - left_x_expan_distmap;\n\t\t\tVector2d expan_distmap_lefttop = Vector2d(left_x_expan_distmap, top_y_expan_distmap);\n\t\t\tVector2d expan_distmap_rightbottom = Vector2d(right_x_expan_distmap, down_y_expan_distmap);\n\n\t\t\t// find edges inside the object bounding box\n\t\t\tMatrixXd all_lines_inside_object(all_lines_raw.rows(), all_lines_raw.cols()); // first allocate a large matrix, then only use the toprows to avoid copy, alloc\n\t\t\tint inside_obj_edge_num = 0;\n\t\t\tfor (int edge_id = 0; edge_id < all_lines_raw.rows(); edge_id++)\n\t\t\t\tif (check_inside_box(all_lines_raw.row(edge_id).head<2>(), expan_distmap_lefttop, expan_distmap_rightbottom))\n\t\t\t\t\tif (check_inside_box(all_lines_raw.row(edge_id).tail<2>(), expan_distmap_lefttop, expan_distmap_rightbottom))\n\t\t\t\t\t{\n\t\t\t\t\t\tall_lines_inside_object.row(inside_obj_edge_num) = all_lines_raw.row(edge_id);\n\t\t\t\t\t\tinside_obj_edge_num++;\n\t\t\t\t\t}\n\n\t\t\t// merge edges and remove short lines, after finding object edges.  edge merge in small regions should be faster than all.\n\t\t\tdouble pre_merge_dist_thre = 20;\n\t\t\tdouble pre_merge_angle_thre = 5;\n\t\t\tdouble edge_length_threshold = 30;\n\t\t\tMatrixXd all_lines_merge_inobj;\n\t\t\tmerge_break_lines(all_lines_inside_object.topRows(inside_obj_edge_num), all_lines_merge_inobj, pre_merge_dist_thre,\n\t\t\t\t\t\t\t  pre_merge_angle_thre, edge_length_threshold);\n\n\t\t\t// compute edge angels and middle points\n\t\t\tVectorXd lines_inobj_angles(all_lines_merge_inobj.rows());\n\t\t\tMatrixXd edge_mid_pts(all_lines_merge_inobj.rows(), 2);\n\t\t\tfor (int i = 0; i < all_lines_merge_inobj.rows(); i++)\n\t\t\t{\n\t\t\t\tlines_inobj_angles(i) = std::atan2(all_lines_merge_inobj(i, 3) - all_lines_merge_inobj(i, 1), all_lines_merge_inobj(i, 2) - all_lines_merge_inobj(i, 0)); // [-pi/2 -pi/2]\n\t\t\t\tedge_mid_pts.row(i).head<2>() = (all_lines_merge_inobj.row(i).head<2>() + all_lines_merge_inobj.row(i).tail<2>()) / 2;\n\t\t\t}\n\n\t\t\t// TODO could canny or distance map outside sampling height to speed up!!!!   Then only need to compute canny onces.\n\t\t\t// detect canny edges and compute distance transform  NOTE opencv canny maybe different from matlab. but roughly same\n\t\t\tcv::Rect object_bbox = cv::Rect(left_x_expan_distmap, top_y_expan_distmap, width_expan_distmap, height_expan_distmap); //\n\t\t\tcv::Mat im_canny;\n\t\t\tcv::Canny(gray_img(object_bbox), im_canny, 80, 200); // low thre, high thre    im_canny 0 or 255   [80 200  40 100]\n\t\t\tcv::Mat dist_map;\n\t\t\tcv::distanceTransform(255 - im_canny, dist_map, cv::DIST_L2, 3); // dist_map is float datatype\n\n\t\t\tif (whether_plot_detail_images)\n\t\t\t{\n\t\t\t\tcv::imshow(\"im_canny\", im_canny);\n\t\t\t\tcv::Mat dist_map_img;\n\t\t\t\tcv::normalize(dist_map, dist_map_img, 0.0, 1.0, cv::NORM_MINMAX);\n\t\t\t\tcv::imshow(\"normalized distance map\", dist_map_img);\n\t\t\t\tcv::waitKey();\n\t\t\t}\n\n\t\t\t// Generate cuboids\n\t\t\tMatrixXd all_configs_error_one_objH(200, 9);\n\t\t\tMatrixXd all_box_corners_2d_one_objH(400, 8);\n\t\t\tint valid_config_number_one_objH = 0;\n\n\t\t\tstd::vector<double> cam_roll_samples;\n\t\t\tstd::vector<double> cam_pitch_samples;\n\t\t\tif (whether_sample_cam_roll_pitch)\n\t\t\t{\n\t\t\t\tlinespace<double>(cam_pose_raw.euler_angle(0) - 6.0 / 180.0 * M_PI, cam_pose_raw.euler_angle(0) + 6.0 / 180.0 * M_PI, 3.0 / 180.0 * M_PI, cam_roll_samples);\n\t\t\t\tlinespace<double>(cam_pose_raw.euler_angle(1) - 6.0 / 180.0 * M_PI, cam_pose_raw.euler_angle(1) + 6.0 / 180.0 * M_PI, 3.0 / 180.0 * M_PI, cam_pitch_samples);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcam_roll_samples.push_back(cam_pose_raw.euler_angle(0));\n\t\t\t\tcam_pitch_samples.push_back(cam_pose_raw.euler_angle(1));\n\t\t\t}\n\t\t\t// different from matlab. first for loop yaw, then for configurations.\n\t\t\t// \t      int obj_yaw_id=8;\n\t\t\tfor (int cam_roll_id = 0; cam_roll_id < cam_roll_samples.size(); cam_roll_id++)\n\t\t\t\tfor (int cam_pitch_id = 0; cam_pitch_id < cam_pitch_samples.size(); cam_pitch_id++)\n\t\t\t\t\tfor (int obj_yaw_id = 0; obj_yaw_id < obj_yaw_samples.size(); obj_yaw_id++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (whether_sample_cam_roll_pitch)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tMatrix4d transToWolrd_new = transToWolrd;\n\t\t\t\t\t\t\ttransToWolrd_new.topLeftCorner<3, 3>() = euler_zyx_to_rot<double>(cam_roll_samples[cam_roll_id], cam_pitch_samples[cam_pitch_id], cam_pose_raw.euler_angle(2));\n\t\t\t\t\t\t\tset_cam_pose(transToWolrd_new);\n\t\t\t\t\t\t\tground_plane_sensor = cam_pose.transToWolrd.transpose() * ground_plane_world;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdouble obj_yaw_esti = obj_yaw_samples[obj_yaw_id];\n\n\t\t\t\t\t\tVector2d vp_1, vp_2, vp_3;\n\t\t\t\t\t\tgetVanishingPoints(cam_pose.KinvR, obj_yaw_esti, vp_1, vp_2, vp_3); // for object x y z  axis\n\n\t\t\t\t\t\tMatrixXd all_vps(3, 2);\n\t\t\t\t\t\tall_vps.row(0) = vp_1;\n\t\t\t\t\t\tall_vps.row(1) = vp_2;\n\t\t\t\t\t\tall_vps.row(2) = vp_3;\n\t\t\t\t\t\t// \t\t  std::cout<<\"obj_yaw_esti  \"<<obj_yaw_esti<<\"  \"<<obj_yaw_id<<std::endl;\n\t\t\t\t\t\tMatrixXd all_vp_bound_edge_angles = VP_support_edge_infos(all_vps, edge_mid_pts, lines_inobj_angles,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  Vector2d(vp12_edge_angle_thre, vp3_edge_angle_thre));\n\t\t\t\t\t\t// \t\t  int sample_top_pt_id=15;\n\t\t\t\t\t\tfor (int sample_top_pt_id = 0; sample_top_pt_id < sample_top_pts.cols(); sample_top_pt_id++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// \t\t      std::cout<<\"sample_top_pt_id \"<<sample_top_pt_id<<std::endl;\n\t\t\t\t\t\t\tVector2d corner_1_top = sample_top_pts.col(sample_top_pt_id);\n\t\t\t\t\t\t\tbool config_good = true;\n\t\t\t\t\t\t\tint vp_1_position = 0; // 0 initial as fail,  1  on left   2 on right\n\t\t\t\t\t\t\tVector2d corner_2_top = seg_hit_boundary(vp_1, corner_1_top, Vector4d(right_x_raw, top_y_raw, right_x_raw, down_y_expan));\n\t\t\t\t\t\t\tif (corner_2_top(0) == -1)\n\t\t\t\t\t\t\t{ // vp1-corner1 doesn't hit the right boundary. check whether hit left\n\t\t\t\t\t\t\t\tcorner_2_top = seg_hit_boundary(vp_1, corner_1_top, Vector4d(left_x_raw, top_y_raw, left_x_raw, down_y_expan));\n\t\t\t\t\t\t\t\tif (corner_2_top(0) != -1) // vp1-corner1 hit the left boundary   vp1 on the right\n\t\t\t\t\t\t\t\t\tvp_1_position = 2;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse // vp1-corner1 hit the right boundary   vp1 on the left\n\t\t\t\t\t\t\t\tvp_1_position = 1;\n\n\t\t\t\t\t\t\tconfig_good = vp_1_position > 0;\n\t\t\t\t\t\t\tif (!config_good)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\tprintf(\"Configuration fails at corner 2, outside segment\\n\");\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ((corner_1_top - corner_2_top).norm() < shorted_edge_thre)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\tprintf(\"Configuration fails at edge 1-2, too short\\n\");\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// \t\t      cout<<\"corner_1/2   \"<<corner_1_top.transpose()<<\"   \"<<corner_2_top.transpose()<<endl;\n\t\t\t\t\t\t\t// \t\t      int config_ind=0; // have to consider config now.\n\t\t\t\t\t\t\tfor (int config_id = 1; config_id < 3; config_id++) // configuration one or two of matlab version\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (!all_configs[config_id - 1])\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\tVector2d corner_3_top, corner_4_top;\n\t\t\t\t\t\t\t\tif (config_id == 1)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (vp_1_position == 1) // then vp2 hit the left boundary\n\t\t\t\t\t\t\t\t\t\tcorner_4_top = seg_hit_boundary(vp_2, corner_1_top, Vector4d(left_x_raw, top_y_raw, left_x_raw, down_y_expan));\n\t\t\t\t\t\t\t\t\telse // or, then vp2 hit the right boundary\n\t\t\t\t\t\t\t\t\t\tcorner_4_top = seg_hit_boundary(vp_2, corner_1_top, Vector4d(right_x_raw, top_y_raw, right_x_raw, down_y_expan));\n\t\t\t\t\t\t\t\t\tif (corner_4_top(1) == -1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tconfig_good = false;\n\t\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at corner 4, outside segment\\n\", config_id);\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif ((corner_1_top - corner_4_top).norm() < shorted_edge_thre)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at edge 1-4, too short\\n\", config_id);\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// compute the last point in the top face\n\t\t\t\t\t\t\t\t\tcorner_3_top = lineSegmentIntersect(vp_2, corner_2_top, vp_1, corner_4_top, true);\n\t\t\t\t\t\t\t\t\tif (!check_inside_box(corner_3_top, Vector2d(left_x_raw, top_y_raw), Vector2d(right_x_raw, down_y_expan)))\n\t\t\t\t\t\t\t\t\t{ // check inside boundary. otherwise edge visibility might be wrong\n\t\t\t\t\t\t\t\t\t\tconfig_good = false;\n\t\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at corner 3, outside box\\n\", config_id);\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (((corner_3_top - corner_4_top).norm() < shorted_edge_thre) || ((corner_3_top - corner_2_top).norm() < shorted_edge_thre))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at edge 3-4/3-2, too short\\n\", config_id);\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// \t\t\t      cout<<\"corner_3/4   \"<<corner_3_top.transpose()<<\"   \"<<corner_4_top.transpose()<<endl;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (config_id == 2)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (vp_1_position == 1) // then vp2 hit the left boundary\n\t\t\t\t\t\t\t\t\t\tcorner_3_top = seg_hit_boundary(vp_2, corner_2_top, Vector4d(left_x_raw, top_y_raw, left_x_raw, down_y_expan));\n\t\t\t\t\t\t\t\t\telse // or, then vp2 hit the right boundary\n\t\t\t\t\t\t\t\t\t\tcorner_3_top = seg_hit_boundary(vp_2, corner_2_top, Vector4d(right_x_raw, top_y_raw, right_x_raw, down_y_expan));\n\t\t\t\t\t\t\t\t\tif (corner_3_top(1) == -1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tconfig_good = false;\n\t\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at corner 3, outside segment\\n\", config_id);\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif ((corner_2_top - corner_3_top).norm() < shorted_edge_thre)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at edge 2-3, too short\\n\", config_id);\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// compute the last point in the top face\n\t\t\t\t\t\t\t\t\tcorner_4_top = lineSegmentIntersect(vp_1, corner_3_top, vp_2, corner_1_top, true);\n\t\t\t\t\t\t\t\t\tif (!check_inside_box(corner_4_top, Vector2d(left_x_raw, top_y_expan_distmap), Vector2d(right_x_raw, down_y_expan_distmap)))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tconfig_good = false;\n\t\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at corner 4, outside box\\n\", config_id);\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (((corner_3_top - corner_4_top).norm() < shorted_edge_thre) || ((corner_4_top - corner_1_top).norm() < shorted_edge_thre))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at edge 3-4/4-1, too short\\n\", config_id);\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// \t\t\t      cout<<\"corner_3/4   \"<<corner_3_top.transpose()<<\"   \"<<corner_4_top.transpose()<<endl;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// compute first bottom points    computing bottom points is the same for config 1,2\n\t\t\t\t\t\t\t\tVector2d corner_5_down = seg_hit_boundary(vp_3, corner_3_top, Vector4d(left_x_raw, down_y_expan, right_x_raw, down_y_expan));\n\t\t\t\t\t\t\t\tif (corner_5_down(1) == -1)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconfig_good = false;\n\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at corner 5, outside segment\\n\", config_id);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif ((corner_3_top - corner_5_down).norm() < shorted_edge_thre)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at edge 3-5, too short\\n\", config_id);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tVector2d corner_6_down = lineSegmentIntersect(vp_2, corner_5_down, vp_3, corner_2_top, true);\n\t\t\t\t\t\t\t\tif (!check_inside_box(corner_6_down, expan_distmap_lefttop, expan_distmap_rightbottom))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconfig_good = false;\n\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at corner 6, outside box\\n\", config_id);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (((corner_6_down - corner_2_top).norm() < shorted_edge_thre) || ((corner_6_down - corner_5_down).norm() < shorted_edge_thre))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at edge 6-5/6-2, too short\\n\", config_id);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tVector2d corner_7_down = lineSegmentIntersect(vp_1, corner_6_down, vp_3, corner_1_top, true);\n\t\t\t\t\t\t\t\tif (!check_inside_box(corner_7_down, expan_distmap_lefttop, expan_distmap_rightbottom))\n\t\t\t\t\t\t\t\t{ // might be slightly different from matlab\n\t\t\t\t\t\t\t\t\tconfig_good = false;\n\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at corner 7, outside box\\n\", config_id);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (((corner_7_down - corner_1_top).norm() < shorted_edge_thre) || ((corner_7_down - corner_6_down).norm() < shorted_edge_thre))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at edge 7-1/7-6, too short\\n\", config_id);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tVector2d corner_8_down = lineSegmentIntersect(vp_1, corner_5_down, vp_2, corner_7_down, true);\n\t\t\t\t\t\t\t\tif (!check_inside_box(corner_8_down, expan_distmap_lefttop, expan_distmap_rightbottom))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconfig_good = false;\n\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at corner 8, outside box\\n\", config_id);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (((corner_8_down - corner_4_top).norm() < shorted_edge_thre) || ((corner_8_down - corner_5_down).norm() < shorted_edge_thre) || ((corner_8_down - corner_7_down).norm() < shorted_edge_thre))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tif (print_details)\n\t\t\t\t\t\t\t\t\t\tprintf(\"Configuration %d fails at edge 8-4/8-5/8-7, too short\\n\", config_id);\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tMatrixXd box_corners_2d_float(2, 8);\n\t\t\t\t\t\t\t\tbox_corners_2d_float << corner_1_top, corner_2_top, corner_3_top, corner_4_top, corner_5_down, corner_6_down, corner_7_down, corner_8_down;\n\t\t\t\t\t\t\t\t// \t\t\t  std::cout<<\"box_corners_2d_float \\n \"<<box_corners_2d_float<<std::endl;\n\t\t\t\t\t\t\t\tMatrixXd box_corners_2d_float_shift(2, 8);\n\t\t\t\t\t\t\t\tbox_corners_2d_float_shift.row(0) = box_corners_2d_float.row(0).array() - left_x_expan_distmap;\n\t\t\t\t\t\t\t\tbox_corners_2d_float_shift.row(1) = box_corners_2d_float.row(1).array() - top_y_expan_distmap;\n\n\t\t\t\t\t\t\t\tMatrixXi visible_edge_pt_ids, vps_box_edge_pt_ids;\n\t\t\t\t\t\t\t\tdouble sum_dist;\n\t\t\t\t\t\t\t\tif (config_id == 1)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tvisible_edge_pt_ids.resize(9, 2);\n\t\t\t\t\t\t\t\t\tvisible_edge_pt_ids << 1, 2, 2, 3, 3, 4, 4, 1, 2, 6, 3, 5, 4, 8, 5, 8, 5, 6;\n\t\t\t\t\t\t\t\t\tvps_box_edge_pt_ids.resize(3, 4);\n\t\t\t\t\t\t\t\t\tvps_box_edge_pt_ids << 1, 2, 8, 5, 4, 1, 5, 6, 4, 8, 2, 6; // six edges. each row represents two edges [e1_1 e1_2   e2_1 e2_2;...] of one VP\n\t\t\t\t\t\t\t\t\tvisible_edge_pt_ids.array() -= 1;\n\t\t\t\t\t\t\t\t\tvps_box_edge_pt_ids.array() -= 1; //change to c++ index\n\t\t\t\t\t\t\t\t\tsum_dist = box_edge_sum_dists(dist_map, box_corners_2d_float_shift, visible_edge_pt_ids);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tvisible_edge_pt_ids.resize(7, 2);\n\t\t\t\t\t\t\t\t\tvisible_edge_pt_ids << 1, 2, 2, 3, 3, 4, 4, 1, 2, 6, 3, 5, 5, 6;\n\t\t\t\t\t\t\t\t\tvps_box_edge_pt_ids.resize(3, 4);\n\t\t\t\t\t\t\t\t\tvps_box_edge_pt_ids << 1, 2, 3, 4, 4, 1, 5, 6, 3, 5, 2, 6; // six edges. each row represents two edges [e1_1 e1_2   e2_1 e2_2;...] of one VP\n\t\t\t\t\t\t\t\t\tvisible_edge_pt_ids.array() -= 1;\n\t\t\t\t\t\t\t\t\tvps_box_edge_pt_ids.array() -= 1;\n\t\t\t\t\t\t\t\t\tsum_dist = box_edge_sum_dists(dist_map, box_corners_2d_float_shift, visible_edge_pt_ids, reweight_edge_distance);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tdouble total_angle_diff = box_edge_alignment_angle_error(all_vp_bound_edge_angles, vps_box_edge_pt_ids, box_corners_2d_float);\n\t\t\t\t\t\t\t\tall_configs_error_one_objH.row(valid_config_number_one_objH).head<4>() = Vector4d(config_id, vp_1_position, obj_yaw_esti, sample_top_pt_id);\n\t\t\t\t\t\t\t\tall_configs_error_one_objH.row(valid_config_number_one_objH).segment<3>(4) = Vector3d(sum_dist / obj_diaglength_expan, total_angle_diff, down_expand_sample);\n\t\t\t\t\t\t\t\tif (whether_sample_cam_roll_pitch)\n\t\t\t\t\t\t\t\t\tall_configs_error_one_objH.row(valid_config_number_one_objH).segment<2>(7) = Vector2d(cam_roll_samples[cam_roll_id], cam_pitch_samples[cam_pitch_id]);\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tall_configs_error_one_objH.row(valid_config_number_one_objH).segment<2>(7) = Vector2d(cam_pose_raw.euler_angle(0), cam_pose_raw.euler_angle(1));\n\t\t\t\t\t\t\t\tall_box_corners_2d_one_objH.block(2 * valid_config_number_one_objH, 0, 2, 8) = box_corners_2d_float;\n\t\t\t\t\t\t\t\tvalid_config_number_one_objH++;\n\t\t\t\t\t\t\t\tif (valid_config_number_one_objH >= all_configs_error_one_objH.rows())\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tall_configs_error_one_objH.conservativeResize(2 * valid_config_number_one_objH, NoChange);\n\t\t\t\t\t\t\t\t\tall_box_corners_2d_one_objH.conservativeResize(4 * valid_config_number_one_objH, NoChange);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} //end of config loop\n\t\t\t\t\t\t}\t //end of top id\n\t\t\t\t\t}\t\t  //end of yaw\n\n\t\t\t// \t      std::cout<<\"valid_config_number_one_hseight  \"<<valid_config_number_one_objH<<std::endl;\n\t\t\t// \t      std::cout<<\"all_configs_error_one_objH  \\n\"<<all_configs_error_one_objH.topRows(valid_config_number_one_objH)<<std::endl;\n\t\t\t// \t      MatrixXd all_corners = all_box_corners_2d_one_objH.topRows(2*valid_config_number_one_objH);\n\t\t\t// \t      std::cout<<\"all corners   \"<<all_corners<<std::endl;\n\n\t\t\tVectorXd normalized_score;\n\t\t\tvector<int> good_proposal_ids;\n\t\t\tfuse_normalize_scores_v2(all_configs_error_one_objH.col(4).head(valid_config_number_one_objH), all_configs_error_one_objH.col(5).head(valid_config_number_one_objH),\n\t\t\t\t\t\t\t\t\t normalized_score, good_proposal_ids, weight_vp_angle, whether_normalize_two_errors);\n\n\t\t\tfor (int box_id = 0; box_id < good_proposal_ids.size(); box_id++)\n\t\t\t{\n\t\t\t\tint raw_cube_ind = good_proposal_ids[box_id];\n\n\t\t\t\tif (whether_sample_cam_roll_pitch)\n\t\t\t\t{\n\t\t\t\t\tMatrix4d transToWolrd_new = transToWolrd;\n\t\t\t\t\ttransToWolrd_new.topLeftCorner<3, 3>() = euler_zyx_to_rot<double>(all_configs_error_one_objH(raw_cube_ind, 7), all_configs_error_one_objH(raw_cube_ind, 8), cam_pose_raw.euler_angle(2));\n\t\t\t\t\tset_cam_pose(transToWolrd_new);\n\t\t\t\t\tground_plane_sensor = cam_pose.transToWolrd.transpose() * ground_plane_world;\n\t\t\t\t}\n\n\t\t\t\tcuboid *sample_obj = new cuboid();\n\t\t\t\tchange_2d_corner_to_3d_object(all_box_corners_2d_one_objH.block(2 * raw_cube_ind, 0, 2, 8), all_configs_error_one_objH.row(raw_cube_ind).head<3>(),\n\t\t\t\t\t\t\t\t\t\t\t  ground_plane_sensor, cam_pose.transToWolrd, cam_pose.invK, cam_pose.projectionMatrix, *sample_obj);\n\t\t\t\t// \t\t  sample_obj->print_cuboid();\n\t\t\t\tif ((sample_obj->scale.array() < 0).any())\n\t\t\t\t\tcontinue; // scale should be positive\n\t\t\t\tsample_obj->rect_detect_2d = Vector4d(left_x_raw, top_y_raw, obj_width_raw, obj_height_raw);\n\t\t\t\tsample_obj->edge_distance_error = all_configs_error_one_objH(raw_cube_ind, 4); // record the original error\n\t\t\t\tsample_obj->edge_angle_error = all_configs_error_one_objH(raw_cube_ind, 5);\n\t\t\t\tsample_obj->normalized_error = normalized_score(box_id);\n\t\t\t\tdouble skew_ratio = sample_obj->scale.head(2).maxCoeff() / sample_obj->scale.head(2).minCoeff();\n\t\t\t\tsample_obj->skew_ratio = skew_ratio;\n\t\t\t\tsample_obj->down_expand_height = all_configs_error_one_objH(raw_cube_ind, 6);\n\t\t\t\tif (whether_sample_cam_roll_pitch)\n\t\t\t\t{\n\t\t\t\t\tsample_obj->camera_roll_delta = all_configs_error_one_objH(raw_cube_ind, 7) - cam_pose_raw.euler_angle(0);\n\t\t\t\t\tsample_obj->camera_pitch_delta = all_configs_error_one_objH(raw_cube_ind, 8) - cam_pose_raw.euler_angle(1);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tsample_obj->camera_roll_delta = 0;\n\t\t\t\t\tsample_obj->camera_pitch_delta = 0;\n\t\t\t\t}\n\n\t\t\t\traw_obj_proposals.push_back(sample_obj);\n\t\t\t}\n\t\t} // end of differnet object height sampling\n\n\t\t// %finally rank all proposals. [normalized_error   skew_error]\n\t\tint actual_cuboid_num_small = std::min(max_cuboid_num, (int)raw_obj_proposals.size());\n\t\tVectorXd all_combined_score(raw_obj_proposals.size());\n\t\tfor (int box_id = 0; box_id < raw_obj_proposals.size(); box_id++)\n\t\t{\n\t\t\tcuboid *sample_obj = raw_obj_proposals[box_id];\n\t\t\tdouble skew_error = weight_skew_error * std::max(sample_obj->skew_ratio - nominal_skew_ratio, 0.0);\n\t\t\tif (sample_obj->skew_ratio > max_cut_skew)\n\t\t\t\tskew_error = 100;\n\t\t\tdouble new_combined_error = sample_obj->normalized_error + weight_skew_error * skew_error;\n\t\t\tall_combined_score(box_id) = new_combined_error;\n\t\t}\n\n\t\tstd::vector<int> sort_idx_small(all_combined_score.rows());\n\t\tiota(sort_idx_small.begin(), sort_idx_small.end(), 0);\n\t\tsort_indexes(all_combined_score, sort_idx_small, actual_cuboid_num_small);\n\t\tfor (int ii = 0; ii < actual_cuboid_num_small; ii++) // use sorted index\n\t\t{\n\t\t\tall_object_cuboids[object_id].push_back(raw_obj_proposals[sort_idx_small[ii]]);\n\t\t}\n\n\t\tca::Profiler::tictoc(\"One 3D object total time\");\n\t} // end of different objects\n\n\tif (whether_plot_final_images || whether_save_final_images)\n\t{\n\t\tcv::Mat frame_all_cubes_img = rgb_img.clone();\n\t\tfor (int object_id = 0; object_id < all_object_cuboids.size(); object_id++)\n\t\t\tif (all_object_cuboids[object_id].size() > 0)\n\t\t\t{\n\t\t\t\tplot_image_with_cuboid(frame_all_cubes_img, all_object_cuboids[object_id][0]);\n\t\t\t}\n\t\tif (whether_save_final_images)\n\t\t\tcuboids_2d_img = frame_all_cubes_img;\n\t\tif (whether_plot_final_images)\n\t\t{\n\t\t\tcv::imshow(\"frame_all_cubes_img\", frame_all_cubes_img);\n\t\t\tcv::waitKey(0);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "736327376db148ad3f312078104ff455c9f1face", "size": 27208, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "detect_3d_cuboid/src/box_proposal_detail.cpp", "max_stars_repo_name": "perseusdg/cube_slam", "max_stars_repo_head_hexsha": "bd08c169004a493fed2a9846f83e3f1592b39822", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "detect_3d_cuboid/src/box_proposal_detail.cpp", "max_issues_repo_name": "perseusdg/cube_slam", "max_issues_repo_head_hexsha": "bd08c169004a493fed2a9846f83e3f1592b39822", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "detect_3d_cuboid/src/box_proposal_detail.cpp", "max_forks_repo_name": "perseusdg/cube_slam", "max_forks_repo_head_hexsha": "bd08c169004a493fed2a9846f83e3f1592b39822", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.7598566308, "max_line_length": 206, "alphanum_fraction": 0.6996104087, "num_tokens": 7893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4143395397799629}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// ars::detail::area.hpp                                                     //\n//                                                                           //\n//  Copyright 2009 Erwann Rogard. Distributed under the Boost                //\n//  Software License, Version 1.0. (See accompanying file                    //\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //\n///////////////////////////////////////////////////////////////////////////////\n#ifndef BOOST_STATISTICS_DETAIL_ARS_DETAIL_AREA_HPP_ER_2009\n#define BOOST_STATISTICS_DETAIL_ARS_DETAIL_AREA_HPP_ER_2009\n#include <stdexcept>\n#include <boost/ars/detail/data.hpp>\n\nnamespace boost{\nnamespace statistics{\nnamespace detail{\nnamespace ars{\n\n// Area of the exponential tangent between two\n// 2 intersections (one of which is possibly -inf or inf).\n\ntemplate<typename T>\nT area_flat_segment(\n    const tangent_intersection<T>& a,\n    const tangent_intersection<T>& b,\n    const T& offset\n){\n    typedef constant<T> const_;\n    T mid = (a.t() + b.t()) / const_::two_;\n    return (b.z() - a.z()) * exp(mid - offset);\n}\n\ntemplate<typename T>\nT area_left_tail(\n    const data<T>& b,\n    const T& offset\n){\n    return exp( b.t() - offset) / b.dy();\n}\ntemplate<typename T>\nT area_right_tail(\n    const tangent_intersection<T>& a,\n    const point<T>& b,\n    const T& offset\n){\n    return - exp( a.t() - offset) / b.dy();\n}\n\ntemplate<typename T>\nT area_segment(\n    const tangent_intersection<T>& a,\n    const data<T>& b,\n    const T& offset\n){\n    typedef constant<T> const_;\n    // Note that b.dy() (a.z_-b.z_) == a.t_ - b.t_\n    T dt  = a.t() - b.t();\n    return exp( b.t() - offset) * (const_::one_ - exp(dt)) / b.dy();\n}\n\ntemplate<typename T>\nT area_segment_safeguarded(\n    const tangent_intersection<T>& a,\n    const data<T>& b,\n    const T& offset\n)\n{\n    typedef constant<T> const_;\n    T area;\n    if(fabs(b.dy())<const_::lmin_){\n        area = area_flat_segment(a,b,offset);\n    }else{\n        if(a.t()-b.t()>const_::lmax_){\n            // exp(a.t_-iter_.t_) = inf,\n            // so 1) not computable and 2) b negligible\n            // This alternative is computable because (in principle)\n            // exp(a.t_- offset) <inf\n            area = area_right_tail(a,b,offset);\n        }else{\n            area = area_segment(a,b,offset);\n        }\n    }\n    return area;\n}\n\n\n}// ars\n}// detail\n}// statistics\n}// boost\n\n#endif\n", "meta": {"hexsha": "f9424e8ae435c0f6b94da68a094fb48d39fc55bb", "size": 2498, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "adaptive_rejection_sampling/boost/ars/detail/area.hpp", "max_stars_repo_name": "rogard/boost_sandbox_statistics", "max_stars_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "adaptive_rejection_sampling/boost/ars/detail/area.hpp", "max_issues_repo_name": "rogard/boost_sandbox_statistics", "max_issues_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adaptive_rejection_sampling/boost/ars/detail/area.hpp", "max_forks_repo_name": "rogard/boost_sandbox_statistics", "max_forks_repo_head_hexsha": "16aacbc716a31a9f7bb6c535b1c90dc343282a23", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.152173913, "max_line_length": 79, "alphanum_fraction": 0.5424339472, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4143150941350393}}
{"text": "#include <iostream>\n#include <sstream>\n#include <time.h>\n#include <stdio.h>\n#include <fstream>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/range/adaptor/transformed.hpp>\n#include <boost/filesystem.hpp>\n\nusing namespace cv;\nusing namespace std;\nusing namespace boost::filesystem;\n\n/*\n * 原理为张正友相机标定\n */\n\nint main(int argc, char** argv)\n{\n\n    if ( argc != 2 )\n    {\n        cout<<\"Parameter input error\"<<endl;\n        return 1;\n    }\n    ofstream fout(\"/home/xc/caliberation_result.txt\");  /* 保存标定结果的文件 */\n\n    // 读取每一幅图像，从中提取出角点，然后对角点进行亚像素精确化\n    int image_count = 0;  /* 图像数量 */\n    Size image_size;      /* 图像的尺寸 */\n    Size board_size = Size(6, 4);             /* 标定板上每行、列的角点数 */\n    vector<Point2f> image_points_buf;         /* 缓存每幅图像上检测到的角点 */\n    vector<vector<Point2f>> image_points_seq; /* 保存检测到的所有角点 */\n    vector<string> filenames;\n    //获取图片路径\n    path dirPath(argv[1]);\n    if(not exists(dirPath) or not is_directory(dirPath))\n    {\n        cerr<<\"不能打开文件路径:\"<<argv[1]<<endl;\n        return false;\n    }\n\n    for(directory_entry& x:directory_iterator(dirPath))\n    {\n        string extension=x.path().extension().string();\n        boost::algorithm::to_lower(extension);\n        if(extension==\".jpg\" or extension==\".jpeg\" or extension==\".png\")\n        {\n            ++image_count;\n            cout<<\"image_count = \"<<image_count<<endl;\n            filenames.push_back(x.path().string());\n            Mat imageInput=imread(x.path().string());\n            if(image_count==1)\n            {\n                image_size.width=imageInput.cols;\n                image_size.height=imageInput.rows;\n                cout<<\"image_size.width = \"<<image_size.width<<endl;\n                cout<<\"image_size.height = \"<<image_size.height<<endl;\n            }\n            if (0 == findChessboardCorners(imageInput, board_size, image_points_buf))\n            {\n                cout << \"can not find chessboard corners!\\n\";  // 找不到角点\n                exit(1);\n            }\n            else\n            {\n                Mat view_gray;\n                cvtColor(imageInput, view_gray, CV_RGB2GRAY);  // 转灰度图\n\n                /* 亚像素精确化 */\n                // image_points_buf 初始的角点坐标向量，同时作为亚像素坐标位置的输出\n                // Size(5,5) 搜索窗口大小\n                // （-1，-1）表示没有死区\n                // TermCriteria 角点的迭代过程的终止条件, 可以为迭代次数和角点精度两者的组合\n                cornerSubPix(view_gray, image_points_buf, Size(5,5), Size(-1,-1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));\n\n                image_points_seq.push_back(image_points_buf);  // 保存亚像素角点\n\n                /* 在图像上显示角点位置 */\n                drawChessboardCorners(imageInput, board_size, image_points_buf, true); // 用于在图片中标记角点\n                namedWindow(\"Camera Calibration\",0);\n                imshow(\"Camera Calibration\", imageInput);       // 显示图片\n                waitKey(500); //暂停0.5S\n            }\n        }\n\n    }\n    cout<<\"end\"<<endl;\n    int CornerNum = board_size.width * board_size.height;  // 每张图片上总的角点数\n\n    //-------------以下是摄像机标定------------------\n\n    /*棋盘三维信息*/\n    Size square_size = Size(10, 10);         /* 实际测量得到的标定板上每个棋盘格的大小 */\n    vector<vector<Point3f>> object_points;   /* 保存标定板上角点的三维坐标 */\n\n    /*内外参数*/\n    Mat cameraMatrix = Mat(3, 3, CV_32FC1, Scalar::all(0));  /* 摄像机内参数矩阵 */\n    vector<int> point_counts;   // 每幅图像中角点的数量\n    Mat distCoeffs=Mat(1, 5, CV_32FC1,Scalar::all(0));       /* 摄像机的5个畸变系数：k1,k2,p1,p2,k3 */\n    vector<Mat> tvecsMat;      /* 每幅图像的旋转向量 */\n    vector<Mat> rvecsMat;      /* 每幅图像的平移向量 */\n\n    /* 初始化标定板上角点的三维坐标 */\n    int i, j, t;\n    for (t=0; t<image_count; t++)\n    {\n        vector<Point3f> tempPointSet;\n        for (i=0; i<board_size.height; i++)\n        {\n            for (j=0; j<board_size.width; j++)\n            {\n                Point3f realPoint;\n\n                /* 假设标定板放在世界坐标系中z=0的平面上 */\n                realPoint.x = i * square_size.width;\n                realPoint.y = j * square_size.height;\n                realPoint.z = 0;\n                tempPointSet.push_back(realPoint);\n            }\n        }\n        object_points.push_back(tempPointSet);\n    }\n\n    /* 初始化每幅图像中的角点数量，假定每幅图像中都可以看到完整的标定板 */\n    for (i=0; i<image_count; i++)\n    {\n        point_counts.push_back(board_size.width * board_size.height);\n    }\n\n    /* 开始标定 */\n    // object_points 世界坐标系中的角点的三维坐标\n    // image_points_seq 每一个内角点对应的图像坐标点\n    // image_size 图像的像素尺寸大小\n    // cameraMatrix 输出，内参矩阵\n    // distCoeffs 输出，畸变系数\n    // rvecsMat 输出，旋转向量\n    // tvecsMat 输出，位移向量\n    // 0 标定时所采用的算法\n    calibrateCamera(object_points, image_points_seq, image_size, cameraMatrix, distCoeffs, rvecsMat, tvecsMat, 0);\n\n    //------------------------标定完成------------------------------------\n\n    // -------------------对标定结果进行评价------------------------------\n\n    double total_err = 0.0;         /* 所有图像的平均误差的总和 */\n    double err = 0.0;               /* 每幅图像的平均误差 */\n    vector<Point2f> image_points2;  /* 保存重新计算得到的投影点 */\n    cerr<<\"每幅图像的标定误差：\\n\";\n\n    for (i=0;i<image_count;i++)\n    {\n        vector<Point3f> tempPointSet = object_points[i];\n\n        /* 通过得到的摄像机内外参数，对空间的三维点进行重新投影计算，得到新的投影点 */\n        projectPoints(tempPointSet, rvecsMat[i], tvecsMat[i], cameraMatrix, distCoeffs, image_points2);\n\n        /* 计算新的投影点和旧的投影点之间的误差*/\n        vector<Point2f> tempImagePoint = image_points_seq[i];\n        Mat tempImagePointMat = Mat(1, tempImagePoint.size(), CV_32FC2);\n        Mat image_points2Mat = Mat(1, image_points2.size(), CV_32FC2);\n\n        for (int j = 0 ; j < tempImagePoint.size(); j++)\n        {\n            image_points2Mat.at<Vec2f>(0,j) = Vec2f(image_points2[j].x, image_points2[j].y);\n            tempImagePointMat.at<Vec2f>(0,j) = Vec2f(tempImagePoint[j].x, tempImagePoint[j].y);\n        }\n        err = norm(image_points2Mat, tempImagePointMat, NORM_L2);\n        total_err += err/= point_counts[i];\n        cerr << \"第\" << i+1 << \"幅图像的平均误差：\" << err<< \"像素\" << endl;\n    }\n    cerr << \"总体平均误差：\" << total_err/image_count << \"像素\" <<endl <<endl;\n\n    //-------------------------评价完成---------------------------------------------\n\n    //-----------------------保存定标结果-------------------------------------------\n    Mat rotation_matrix = Mat(3,3,CV_32FC1, Scalar::all(0));  /* 保存每幅图像的旋转矩阵 */\n    fout << \"相机内参数矩阵：\" << endl;\n    fout << cameraMatrix << endl << endl;\n    fout << \"畸变系数：\\n\";\n    fout << distCoeffs << endl << endl << endl;\n    for (int i=0; i<image_count; i++)\n    {\n        cerr << \"第\" << i+1 << \"幅图像的旋转向量：\" << endl;\n        cerr << tvecsMat[i] << endl;\n\n        /* 将旋转向量转换为相对应的旋转矩阵 */\n        Rodrigues(tvecsMat[i], rotation_matrix);\n        cerr << \"第\" << i+1 << \"幅图像的旋转矩阵：\" << endl;\n        cerr << rotation_matrix << endl;\n        cerr << \"第\" << i+1 << \"幅图像的平移向量：\" << endl;\n        cerr << rvecsMat[i] << endl << endl;\n    }\n    cerr<<endl;\n\n    //--------------------标定结果保存结束-------------------------------\n\n    //----------------------显示定标结果--------------------------------\n\n    Mat mapx = Mat(image_size, CV_32FC1);\n    Mat mapy = Mat(image_size, CV_32FC1);\n    Mat R = Mat::eye(3, 3, CV_32F);\n    string imageFileName;\n    std::stringstream StrStm;\n    for (int i = 0 ; i != image_count ; i++)\n    {\n        initUndistortRectifyMap(cameraMatrix, distCoeffs, R, cameraMatrix, image_size, CV_32FC1, mapx, mapy);\n        Mat imageSource = imread(filenames[i]);\n        Mat newimage = imageSource.clone();\n        remap(imageSource, newimage, mapx, mapy, INTER_LINEAR);\n        StrStm.clear();\n        imageFileName.clear();\n        StrStm << i+1;\n        StrStm >> imageFileName;\n        imageFileName += \"_d.jpg\";\n        imwrite(imageFileName, newimage);\n        imshow(\"new\",newimage);\n    }\n    fout.close();\n    return 0;\n}", "meta": {"hexsha": "86b27f0ae8ef160d01fbc7cecd2921436ae33703", "size": 7780, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Camera_calibration/main.cpp", "max_stars_repo_name": "xccccccc/Camera_calibration", "max_stars_repo_head_hexsha": "d345a136351c9206a9d4b5c5d8af6c2d93e33e28", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-10T13:18:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T02:29:14.000Z", "max_issues_repo_path": "Camera_calibration/main.cpp", "max_issues_repo_name": "NEU-xichong/Camera_calibration", "max_issues_repo_head_hexsha": "d345a136351c9206a9d4b5c5d8af6c2d93e33e28", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Camera_calibration/main.cpp", "max_forks_repo_name": "NEU-xichong/Camera_calibration", "max_forks_repo_head_hexsha": "d345a136351c9206a9d4b5c5d8af6c2d93e33e28", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-06-12T06:47:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-15T05:12:10.000Z", "avg_line_length": 34.2731277533, "max_line_length": 141, "alphanum_fraction": 0.5453727506, "num_tokens": 2567, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4142667122064195}}
{"text": "//\n// Created by Samuel Jackson on 11/03/2016.\n//\n\n#include <Eigen/Dense>\n#include <set>\n#include \"CellMatrix.h\"\n\nusing namespace Eigen;\nusing namespace Molly;\n\n// offset indicies for neighbour cells for each cell\n// we only need to look at half the cells at one time.\n// includes 13 neighbours (half the total)\nconst size_t NUM_OFFSETS = 13;\nconst int OFFSETS[][3] {\n    {1, 0, 0},\n    {1, 1, 0},\n    {0, 1, 0},\n    {-1, 1, 0},\n    {0, 0, 1},\n    {1, 0, 1},\n    {1, 1, 1},\n    {0, 1, 1},\n    {-1, 1, 1},\n    {-1, 0, 1},\n    {-1, -1, 1},\n    {0, -1, 1},\n    {1, -1, 1}\n};\n\n\nCellMatrix::CellMatrix(const double cell_width, size_t d1, size_t d2, size_t d3)\n        : cell_width(cell_width) {\n    resize(d1, d2, d3);\n}\n\nvoid CellMatrix::resize(size_t d1, size_t d2, size_t d3) {\n    data.clear();\n    data.resize(d1*d2*d3);\n\n    for (auto iter = data.begin(); iter != data.end(); ++iter) {\n        *iter = std::make_shared<Cell>();\n    }\n\n    // update the dimensions\n    this->d1 = d1;\n    this->d2 = d2;\n    this->d3 = d3;\n\n    // reinitialise neighbours\n    create_neighbours();\n}\n\nCell_ptr CellMatrix::operator()(size_t i, size_t j, size_t k) {\n    const size_t index = i*d2*d3 + j*d3 + k;\n\n    if (index >= data.size()) {\n        std::stringstream ss;\n        ss << \"Index is out of points for matrix of size \" << d1 << \", \" << d2 << \", \" << d3;\n        throw std::runtime_error(ss.str());\n    }\n\n    return data[index];\n}\n\nCell_ptr const CellMatrix::operator()(size_t i, size_t j, size_t k) const {\n    const size_t index = i*d2*d3 + j*d3 + k;\n\n    if (index >= data.size()) {\n        std::stringstream ss;\n        ss << \"Index is out of points for matrix of size \" << d1 << \", \" << d2 << \", \" << d3;\n        throw std::runtime_error(ss.str());\n    }\n\n    return data[index];\n}\n\nvoid CellMatrix::create_neighbours() {\n    // loop over each dimension of the cell matrix\n    for(size_t i = 0; i < d1; ++i) {\n        for(size_t j = 0; j < d2; ++j) {\n            for(size_t k = 0; k < d3; ++k) {\n                // add pointers to each neighbour of a cell in the cell matrix\n                Cell_ptr cell = (*this)(i, j, k);\n                for (size_t offset_num = 0; offset_num < NUM_OFFSETS; ++offset_num) {\n                    // get offset cell indices\n                    const int x_offset = OFFSETS[offset_num][0];\n                    const int y_offset = OFFSETS[offset_num][1];\n                    const int z_offset = OFFSETS[offset_num][2];\n\n                    // correct the offsets to wrap around\n                    size_t x = (i+x_offset) % d1;\n                    size_t y = (j+y_offset) % d2;\n                    size_t z = (k+z_offset) % d3;\n\n                    //set pointer to neighbour cell\n                    Cell_ptr neighbour = (*this)(x, y, z);\n                    cell->add_neighbour(neighbour);\n                }\n            }\n        }\n    }\n}\n\nvoid CellMatrix::add_molecule(Molecule_ptr mol) {\n    Eigen::Vector3i index;\n    convert_vector_to_index(mol->r, index);\n    (*this)(index(0), index(1), index(2))->add_molecule(mol);\n}\n\nvoid CellMatrix::convert_vector_to_index(const Vector3d& vec, Vector3i& index) const {\n    index = (vec / cell_width).cast<int>();\n    index(0) = index(0) % d1;\n    index(1) = index(1) % d2;\n    index(2) = index(2) % d3;\n}\n\nvoid CellMatrix::wrap_cells() {\n    Vector3i index;\n    int i = 0;\n\n    // loop over every cell in the matrix\n    for (auto iter = data.begin(); iter != data.end(); ++iter) {\n        auto& molecules = (*iter)->get_molecules();\n\n        // check the molecules in each cell to see if they need to move\n        // to a different cell\n        for(auto mol = molecules.begin(); mol != molecules.end();) {\n            convert_vector_to_index((*mol)->r, index);\n            // check if this molecule is in the same cell\n            if(i != (index(0)*d2*d3 + index(1)*d3 + index(2))) {\n                // if it isn't then move it to the correct cell mark for removal from the current.\n                (*this)(index(0), index(1), index(2))->add_molecule(*mol);\n                // note: must update iterator after removal\n                mol = molecules.erase(mol);\n            } else {\n                // otherwise just skip to next molecule\n                ++mol;\n            }\n        }\n        ++i;\n    }\n}\n", "meta": {"hexsha": "d7070a2012b4c74173d8de959c643abf83971b14", "size": 4287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CellMatrix.cpp", "max_stars_repo_name": "samueljackson92/molly", "max_stars_repo_head_hexsha": "6799990e3479da7e5d6e3372b0200bb198af4f8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CellMatrix.cpp", "max_issues_repo_name": "samueljackson92/molly", "max_issues_repo_head_hexsha": "6799990e3479da7e5d6e3372b0200bb198af4f8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CellMatrix.cpp", "max_forks_repo_name": "samueljackson92/molly", "max_forks_repo_head_hexsha": "6799990e3479da7e5d6e3372b0200bb198af4f8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5655172414, "max_line_length": 98, "alphanum_fraction": 0.5348728715, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4142667044518142}}
{"text": "/*********************************************************************\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2014, Texas A&M University\n*  All rights reserved.\n*\n*  Redistribution and use in source and binary forms, with or without\n*  modification, are permitted provided that the following conditions\n*  are met:\n*\n*   * Redistributions of source code must retain the above copyright\n*     notice, this list of conditions and the following disclaimer.\n*   * Redistributions in binary form must reproduce the above\n*     copyright notice, this list of conditions and the following\n*     disclaimer in the documentation and/or other materials provided\n*     with the distribution.\n*   * Neither the name of the Texas A&M University nor the names of its\n*     contributors may be used to endorse or promote products derived\n*     from this software without specific prior written permission.\n*\n*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n*  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n*  POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************/\n\n\n#include \"Utils/FIRMUtils.h\"\n#include <boost/math/constants/constants.hpp>\n#include <boost/date_time.hpp>\n#include <utility>\n#include <random>\n#include <tinyxml.h>\n\n\nvoid FIRMUtils::normalizeAngleToPiRange(double &theta)\n{\n\n    while(theta > boost::math::constants::pi<double>())\n    {\n        theta -= 2*boost::math::constants::pi<double>();\n    }\n\n    while(theta < -boost::math::constants::pi<double>())\n    {\n        theta += 2*boost::math::constants::pi<double>();\n    }\n\n}\n\nint FIRMUtils::signum(const double d)\n{\n        if(d>0)\n            return 1;\n\n        if(d<0)\n            return -1;\n}\n\nint FIRMUtils::generateRandomIntegerInRange(const int floor, const int ceiling)\n{\n    //std::random_device rd; // obtain a random number from hardware\n\n    //std::mt19937 eng(rd()); // seed the generator\n\n    //std::uniform_int_distribution<> distr(floor, ceiling); // define the range\n\n    //return distr(eng);\n\n    int r = rand()%(ceiling - floor + 1) + floor;\n\n    return r;\n}\n\nvoid FIRMUtils::writeFIRMGraphToXML(const std::vector<std::pair<int,std::pair<arma::colvec,arma::mat> > > nodes, const std::vector<std::pair<std::pair<int,int>,FIRMWeight> > edgeWeights)\n{\n    TiXmlDocument doc;\n\n \tTiXmlDeclaration* decl = new TiXmlDeclaration( \"1.0\", \"\", \"\" );\n\tdoc.LinkEndChild( decl );\n\n\tTiXmlElement * Nodes = new TiXmlElement( \"Nodes\" );\n\tdoc.LinkEndChild( Nodes );\n\n\n\tfor(int i = 0; i < nodes.size(); i++)\n\t{\n        TiXmlElement * node;\n        node = new TiXmlElement( \"node\" );\n        Nodes->LinkEndChild( node );\n\n        int nodeID = nodes[i].first; // id of the node in the graph\n\n        arma::colvec xVec = nodes[i].second.first; // x,y,yaw\n\n        arma::mat cov = nodes[i].second.second; // covariance matrix\n\n        node->SetAttribute(\"id\", nodeID);\n        node->SetDoubleAttribute(\"x\", xVec(0));\n        node->SetDoubleAttribute(\"y\", xVec(1));\n        node->SetDoubleAttribute(\"theta\",xVec(2));\n        node->SetDoubleAttribute(\"c11\", cov(0,0));\n        node->SetDoubleAttribute(\"c12\", cov(0,1));\n        node->SetDoubleAttribute(\"c13\", cov(0,2));\n        node->SetDoubleAttribute(\"c21\", cov(1,0));\n        node->SetDoubleAttribute(\"c22\", cov(1,1));\n        node->SetDoubleAttribute(\"c23\", cov(1,2));\n        node->SetDoubleAttribute(\"c31\", cov(2,0));\n        node->SetDoubleAttribute(\"c32\", cov(2,1));\n        node->SetDoubleAttribute(\"c33\", cov(2,2));\n\n   }\n\n    TiXmlElement * Edges = new TiXmlElement( \"Edges\" );\n\tdoc.LinkEndChild( Edges );\n\n\tfor(int i = 0; i < edgeWeights.size(); i++)\n\t{\n        TiXmlElement * edge;\n        edge = new TiXmlElement( \"edge\" );\n        Edges->LinkEndChild( edge );\n\n        FIRMWeight w = edgeWeights[i].second;\n\n\n        edge->SetAttribute(\"startVertexID\", edgeWeights[i].first.first);\n        edge->SetAttribute(\"endVertexID\", edgeWeights[i].first.second);\n        edge->SetDoubleAttribute(\"successProb\", w.getSuccessProbability());\n        edge->SetDoubleAttribute(\"cost\", w.getCost());\n\n\n   }\n\n   // Generate time stamp for saving roadmap\n    namespace pt = boost::posix_time;\n\n    pt::ptime now = pt::second_clock::local_time();\n\n    std::string timeStamp(to_iso_string(now)) ;\n\n    std::string roadmapFileName =  \"FIRMRoadMap-\" + timeStamp + \".xml\";\n\n\tdoc.SaveFile(roadmapFileName);\n}\n\nbool FIRMUtils::readFIRMGraphFromXML(const std::string &pathToXML, std::vector<std::pair<int, arma::colvec> > &FIRMNodePosList, std::vector<std::pair<int, arma::mat> > &FIRMNodeCovarianceList, std::vector<std::pair<std::pair<int,int>,FIRMWeight> > &edgeWeights)\n{\n\n    TiXmlDocument doc(pathToXML);\n\n    bool loadOkay = doc.LoadFile();\n\n    if ( !loadOkay )\n    {\n        OMPL_INFORM(\"FIRMUtils: Could not load Graph from XML . Need to construct graph.\");\n        return false;\n    }\n\n    TiXmlNode* NodeList = 0;\n\n    TiXmlElement* nodeElement = 0;\n\n    TiXmlElement* itemElement = 0;\n\n    NodeList = doc.FirstChild( \"Nodes\" );\n\n    assert( NodeList );\n\n    nodeElement = NodeList->ToElement(); //convert NodeList to element\n\n    assert( nodeElement  );\n\n    TiXmlNode* child = 0;\n\n    while( (child = nodeElement->IterateChildren(child)))\n    {\n        assert( child );\n\n        itemElement = child->ToElement();\n\n        assert( itemElement );\n\n        double x = 0, y = 0, theta = 0, c11 = 0, c12 = 0, c13 = 0, c21 = 0, c22 = 0, c23 = 0, c31 = 0, c32 = 0, c33 = 0;\n        int id = 0;\n\n        itemElement->QueryIntAttribute(\"id\", &id) ;\n        itemElement->QueryDoubleAttribute(\"x\", &x) ;\n        itemElement->QueryDoubleAttribute(\"y\", &y) ;\n        itemElement->QueryDoubleAttribute(\"theta\", &theta) ;\n        itemElement->QueryDoubleAttribute(\"c11\", &c11) ;\n        itemElement->QueryDoubleAttribute(\"c12\", &c12) ;\n        itemElement->QueryDoubleAttribute(\"c13\", &c13) ;\n        itemElement->QueryDoubleAttribute(\"c21\", &c21) ;\n        itemElement->QueryDoubleAttribute(\"c22\", &c22) ;\n        itemElement->QueryDoubleAttribute(\"c23\", &c23) ;\n        itemElement->QueryDoubleAttribute(\"c31\", &c31) ;\n        itemElement->QueryDoubleAttribute(\"c32\", &c32) ;\n        itemElement->QueryDoubleAttribute(\"c33\", &c33) ;\n\n        arma::colvec xVec(3);\n        arma::mat cov(3,3);\n\n        xVec(0) = x;\n        xVec(1) = y;\n        xVec(2) = theta;\n\n        cov(0,0) = c11;\n        cov(0,1) = c12;\n        cov(0,2) = c13;\n        cov(1,0) = c21;\n        cov(1,1) = c22;\n        cov(1,2) = c23;\n        cov(2,0) = c31;\n        cov(2,1) = c32;\n        cov(2,2) = c33;\n\n        FIRMNodePosList.push_back(std::make_pair(id,xVec));\n        FIRMNodeCovarianceList.push_back(std::make_pair(id,cov));\n\n    }\n\n\n    //////////////////////\n    TiXmlNode* edgeList = 0;\n\n    TiXmlElement* edgeElement = 0;\n\n    TiXmlElement* itemElement2 = 0;\n\n    edgeList = doc.FirstChild( \"Edges\" );\n\n    assert( edgeList );\n\n    edgeElement = edgeList->ToElement(); //convert NodeList to element\n\n    assert( edgeElement  );\n\n    TiXmlNode* child2 = 0;\n\n    while( (child2 = edgeElement->IterateChildren(child2)))\n    {\n        assert( child2 );\n\n        itemElement2 = child2->ToElement();\n\n        assert( itemElement2 );\n\n        int startVertexID = 0, endVertexID = 0;\n        double successProb = 0, cost = 0;\n\n        itemElement2->QueryIntAttribute(\"startVertexID\", &startVertexID) ;\n        itemElement2->QueryIntAttribute(\"endVertexID\", &endVertexID) ;\n        itemElement2->QueryDoubleAttribute(\"successProb\", &successProb) ;\n        itemElement2->QueryDoubleAttribute(\"cost\", &cost) ;\n\n        FIRMWeight w(cost, successProb);\n\n        edgeWeights.push_back(std::make_pair(std::make_pair(startVertexID, endVertexID),w));\n\n    }\n\n    return true;\n}\n\ndouble FIRMUtils::degree2Radian(double deg)\n{\n    return boost::math::constants::pi<double>()*deg/180.0;\n}\n\ndouble FIRMUtils::radian2Degree(double rads)\n{\n    return rads*180.0/boost::math::constants::pi<double>();\n}\n\n", "meta": {"hexsha": "a6f523b047e94017cfa2f3d881c2409b4cb26e36", "size": 8583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/FIRMUtils.cpp", "max_stars_repo_name": "sauravag/FIRM-OMPL", "max_stars_repo_head_hexsha": "854406d4ddbad5a47c8a4411f8aac0d1424aa93d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2017-01-03T09:44:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-09T08:42:28.000Z", "max_issues_repo_path": "src/Utils/FIRMUtils.cpp", "max_issues_repo_name": "sauravag/edpl-ompl", "max_issues_repo_head_hexsha": "854406d4ddbad5a47c8a4411f8aac0d1424aa93d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-12-01T20:51:07.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-30T00:24:50.000Z", "max_forks_repo_path": "src/Utils/FIRMUtils.cpp", "max_forks_repo_name": "sauravag/FIRM-OMPL", "max_forks_repo_head_hexsha": "854406d4ddbad5a47c8a4411f8aac0d1424aa93d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-12-08T12:02:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T15:25:08.000Z", "avg_line_length": 30.3286219081, "max_line_length": 261, "alphanum_fraction": 0.633578003, "num_tokens": 2273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4142667044518141}}
{"text": "#include <kr_trackers/traj_gen.h>\n\n#include <Eigen/LU>\n\nTrajectoryGenerator::TrajectoryGenerator(unsigned int continuous_derivative_order, unsigned int minimize_derivative)\n    : N_(2 * (continuous_derivative_order + 1)), R_(minimize_derivative)\n{\n}\n\nvoid TrajectoryGenerator::setInitialConditions(const Vec3f &pos, const vec_Vec3f &derivatives)\n{\n  clearWaypoints();\n  waypoints_.push_back(pos);\n\n  initial_derivatives_.clear();\n  initial_derivatives_.resize(N_ / 2);\n  for(size_t i = 0; i < std::min(initial_derivatives_.size(), derivatives.size()); ++i)\n  {\n    initial_derivatives_[i] = derivatives[i];\n  }\n}\n\nvoid TrajectoryGenerator::addWaypoint(const Vec3f &x)\n{\n  if(waypoints_.empty())\n    setInitialConditions(x, vec_Vec3f());\n  else\n    waypoints_.push_back(x);\n}\n\nvoid TrajectoryGenerator::clearWaypoints(void)\n{\n  waypoints_.clear();\n  coefficients_.clear();\n  waypoint_times_.clear();\n  initial_derivatives_.clear();\n}\n\nstd::vector<float> TrajectoryGenerator::computeTimesTrapezoidSpeed(float v_des, float a_des) const\n{\n  std::vector<float> waypoint_times;\n  waypoint_times.reserve(waypoints_.size());\n\n  waypoint_times.push_back(0);  // First waypoint, t = 0\n\n  if(waypoints_.size() < 2)\n    return waypoint_times;\n\n  const Vec3f &initial_vel_ = initial_derivatives_[0];\n  const int initial_vel_sign = (initial_vel_.dot(waypoints_[1] - waypoints_[0]) >= 0) ? 1 : -1;\n  const float v_initial = initial_vel_sign * initial_vel_.norm();\n\n  std::vector<float> accumulated_dist;\n  accumulated_dist.reserve(waypoints_.size());\n  accumulated_dist.push_back(0);\n  for(unsigned int i = 1; i < waypoints_.size(); ++i)\n  {\n    const float dist = (waypoints_[i] - waypoints_[i - 1]).norm();\n    accumulated_dist.push_back(accumulated_dist[i - 1] + dist);\n  }\n  const float total_dist = accumulated_dist.back();\n\n  float d_accel = std::abs(v_des * v_des - v_initial * v_initial) / 2 / a_des;\n  float d_decel = v_des * v_des / 2 / a_des;\n  float d_constant = (total_dist - (d_accel + d_decel));\n  if(d_accel + d_decel > total_dist)\n  {\n    d_constant = 0;\n    d_accel = total_dist / 2 - v_initial * v_initial / 4 / a_des;\n    d_decel = total_dist - d_accel;\n  }\n  const float t_accel = std::sqrt(v_initial * v_initial + 2 * a_des * d_accel) / a_des;\n  const float t_constant = d_constant / v_des;\n  const float t_decel = std::sqrt(2 * a_des * d_decel) / a_des;\n\n  for(unsigned int i = 1; i < waypoints_.size(); ++i)\n  {\n    if(accumulated_dist[i] <= d_accel)  // Accel\n    {\n      waypoint_times.push_back((std::sqrt(v_initial * v_initial + 2 * a_des * accumulated_dist[i]) - v_initial) /\n                               a_des);\n    }\n    else if(accumulated_dist[i] <= d_accel + d_constant)  // Constant\n    {\n      waypoint_times.push_back(t_accel + (accumulated_dist[i] - d_accel) / v_des);\n    }\n    else  // Decel\n    {\n      waypoint_times.push_back(t_accel + t_constant + t_decel -\n                               std::sqrt(2 * (total_dist - accumulated_dist[i]) / a_des));\n    }\n  }\n\n  return waypoint_times;\n}\n\nstd::vector<float> TrajectoryGenerator::computeTimesConstantSpeed(float avg_speed) const\n{\n  std::vector<float> waypoint_times;\n  waypoint_times.reserve(waypoints_.size());\n\n  waypoint_times.push_back(0);  // First waypoint, t = 0\n\n  for(unsigned int i = 1; i < waypoints_.size(); ++i)\n  {\n    waypoint_times.push_back(waypoint_times[i - 1] + std::sqrt((waypoints_[i] - waypoints_[i - 1]).norm()) / avg_speed);\n  }\n  return waypoint_times;\n}\n\nconst std::vector<float> &TrajectoryGenerator::getWaypointTimes() const\n{\n  return waypoint_times_;\n}\n\nfloat TrajectoryGenerator::getTotalTime() const\n{\n  return waypoint_times_.back();\n}\n\n// From https://stackoverflow.com/a/33454406\ntemplate <typename T>\nT powInt(T x, unsigned int n)\n{\n  if(n == 0)\n    return T{1};\n\n  auto y = T{1};\n  while(n > 1)\n  {\n    if(n % 2 == 1)\n      y *= x;\n    x *= x;\n    n /= 2;\n  }\n  return x * y;\n}\n\nbool TrajectoryGenerator::calculate(const std::vector<float> &waypoint_times)\n{\n  if(waypoints_.size() < 2)\n    return false;\n\n  if(waypoint_times.size() != waypoints_.size())\n  {\n    printf(\"waypoint_times.size() != waypoints_.size()\\n\");\n    return false;\n  }\n\n  const unsigned int num_waypoints = waypoints_.size();\n  const unsigned int num_segments = num_waypoints - 1;\n  // printf(\"num_segments: %d\\n\", num_segments);\n\n  Eigen::MatrixXf A = Eigen::MatrixXf::Zero(num_segments * N_, num_segments * N_);  // Linear constraints\n  Eigen::MatrixXf Q = Eigen::MatrixXf::Zero(num_segments * N_, num_segments * N_);  // Quadratic cost matrix\n  for(unsigned int i = 0; i < num_segments; i++)\n  {\n    float seg_time = waypoint_times[i + 1] - waypoint_times[i];\n    for(unsigned int n = 0; n < N_; n++)\n    {\n      // A_0\n      if(n < N_ / 2)\n      {\n        int val = 1;\n        for(unsigned int m = 0; m < n; m++)\n          val *= (n - m);\n        A(i * N_ + n, i * N_ + n) = val;\n      }\n      // A_T\n      for(unsigned int r = 0; r < N_ / 2; r++)\n      {\n        if(r <= n)\n        {\n          int val = 1;\n          for(unsigned int m = 0; m < r; m++)\n            val *= (n - m);\n          A(i * N_ + N_ / 2 + r, i * N_ + n) = val * powInt(seg_time, n - r);\n        }\n      }\n      // Q\n      for(unsigned int r = 0; r < N_; r++)\n      {\n        if(r >= R_ && n >= R_)\n        {\n          int val = 1;\n          for(unsigned int m = 0; m < R_; m++)\n            val *= (r - m) * (n - m);\n          Q(i * N_ + r, i * N_ + n) = 2 * val * powInt(seg_time, r + n - 2 * R_ + 1) / (r + n - 2 * R_ + 1);\n        }\n      }\n    }\n  }\n  const unsigned int num_fixed_derivatives = num_waypoints - 2 + N_;\n  const unsigned int num_free_derivatives = num_waypoints * N_ / 2 - num_fixed_derivatives;\n  // printf(\"num_fixed_derivatives: %d, num_free_derivatives: %d\\n\",\n  //        num_fixed_derivatives, num_free_derivatives);\n\n  // M\n  Eigen::MatrixXf M = Eigen::MatrixXf::Zero(num_segments * N_, num_waypoints * N_ / 2);\n  M.block(0, 0, N_ / 2, N_ / 2) = Eigen::MatrixXf::Identity(N_ / 2, N_ / 2);\n  M.block(num_segments * N_ - N_ / 2, N_ / 2 + num_waypoints - 2, N_ / 2, N_ / 2) =\n      Eigen::MatrixXf::Identity(N_ / 2, N_ / 2);\n  for(unsigned int i = 0; i < num_waypoints - 2; i++)\n  {\n    M((2 * i + 1) * N_ / 2, N_ / 2 + i) = 1;\n    M((2 * i + 2) * N_ / 2, N_ / 2 + i) = 1;\n    for(unsigned int j = 1; j < N_ / 2; j++)\n    {\n      M((2 * i + 1) * N_ / 2 + j, num_fixed_derivatives - 1 + i * (N_ / 2 - 1) + j) = 1;\n      M((2 * i + 2) * N_ / 2 + j, num_fixed_derivatives - 1 + i * (N_ / 2 - 1) + j) = 1;\n    }\n  }\n  // Eigen::MatrixXf A_inv = A.inverse();\n  Eigen::MatrixXf A_inv_M = A.partialPivLu().solve(M);\n  Eigen::MatrixXf R = A_inv_M.transpose() * Q * A_inv_M;\n#if 0\n  //std::cout << \"A:\\n\" << A << std::endl;\n  std::cout << \"Q:\\n\" << Q << std::endl;\n  //std::cout << \"M:\\n\" << M << std::endl;\n  //std::cout << \"A_inv_M:\\n\" << A_inv_M << std::endl;\n  std::cout << \"R:\\n\" << R << std::endl;\n#endif\n  Eigen::MatrixXf Rpp =\n      R.block(num_fixed_derivatives, num_fixed_derivatives, num_free_derivatives, num_free_derivatives);\n  Eigen::MatrixXf Rpf = R.block(num_fixed_derivatives, 0, num_free_derivatives, num_fixed_derivatives);\n\n  // Fixed derivatives\n  Eigen::MatrixX3f Df = Eigen::MatrixX3f(num_fixed_derivatives, 3);\n  // First point\n  Df.row(0) = waypoints_[0].transpose();\n  for(unsigned int i = 1; i < N_ / 2; i++)\n  {\n    Df.row(i) = initial_derivatives_[i - 1].transpose();\n  }\n  // Middle waypoints\n  for(unsigned int i = 1; i < num_waypoints - 1; i++)\n  {\n    Df.row((N_ / 2) - 1 + i) = waypoints_[i].transpose();\n  }\n  // End point\n  Df.row(N_ / 2 + (num_waypoints - 2)) = waypoints_[num_waypoints - 1].transpose();\n  for(unsigned int i = 1; i < N_ / 2; i++)\n  {\n    Df.row((N_ / 2) + (num_waypoints - 2) + i) = Vec3f::Zero().transpose();\n  }\n  // std::cout << \"Df:\\n\" << Df << std::endl;\n  Eigen::MatrixX3f D = Eigen::MatrixX3f(num_waypoints * N_ / 2, 3);\n  D.topRows(num_fixed_derivatives) = Df;\n  if(num_waypoints > 2 && num_free_derivatives > 0)\n  {\n    Eigen::MatrixX3f Dp = -Rpp.partialPivLu().solve(Rpf * Df);\n    // std::cout << \"Dp:\\n\" << Dp << std::endl;\n    D.bottomRows(num_free_derivatives) = Dp;\n  }\n  Eigen::MatrixX3f d = M * D;\n  // std::cout << \"d:\\n\" << d << std::endl;\n  coefficients_.clear();\n  for(unsigned int i = 0; i < num_segments; i++)\n  {\n    const Eigen::MatrixX3f p = A.block(i * N_, i * N_, N_, N_).partialPivLu().solve(d.block(i * N_, 0, N_, 3));\n    // std::cout << \"p:\\n\" << p << std::endl;\n    coefficients_.push_back(p);\n  }\n  waypoint_times_ = waypoint_times;\n  return true;\n}\n\nbool TrajectoryGenerator::getCommand(const float time, Vec3f &pos, Vec3f &vel, Vec3f &acc, Vec3f &jrk) const\n{\n  if(time < 0)\n    return false;\n\n  int cur_idx = -1;\n  for(unsigned int i = 1; i < waypoint_times_.size(); i++)\n  {\n    if(time <= waypoint_times_[i])\n    {\n      cur_idx = i - 1;\n      break;\n    }\n  }\n  if(cur_idx == -1)\n    return false;\n\n  const float t_traj = time - waypoint_times_[cur_idx];\n  const Eigen::MatrixX3f &p = coefficients_[cur_idx];\n  pos = Vec3f::Zero();\n  for(unsigned int i = 0; i < p.rows(); i++)\n    pos += p.row(i).transpose() * powInt(t_traj, i);\n\n  vel = Vec3f::Zero();\n  for(unsigned int i = 1; i < p.rows(); i++)\n    vel += p.row(i).transpose() * (i * powInt(t_traj, i - 1));\n\n  acc = Vec3f::Zero();\n  for(unsigned int i = 2; i < p.rows(); i++)\n    acc += p.row(i).transpose() * (i * (i - 1) * powInt(t_traj, i - 2));\n\n  jrk = Vec3f::Zero();\n  for(unsigned int i = 3; i < p.rows(); i++)\n    jrk += p.row(i).transpose() * (i * (i - 1) * (i - 2) * powInt(t_traj, i - 3));\n\n  return true;\n}\n\nvoid TrajectoryGenerator::calcMaxPerSegment(std::vector<float> &max_vel, std::vector<float> &max_acc,\n                                            std::vector<float> &max_jrk) const\n{\n  const unsigned int num_samples_per_seg = 10;\n  for(unsigned int seg_idx = 0; seg_idx < waypoint_times_.size() - 1; ++seg_idx)\n  {\n    const float seg_start_time = waypoint_times_[seg_idx];\n    const float seg_end_time = waypoint_times_[seg_idx + 1];\n    float seg_duration = seg_end_time - seg_start_time;\n    const float dt = seg_duration / num_samples_per_seg;\n\n    float seg_max_vel = 0, seg_max_acc = 0, seg_max_jrk = 0;\n    for(unsigned int sample_idx = 0; sample_idx < num_samples_per_seg; ++sample_idx)\n    {\n      const float t_traj = sample_idx * dt;\n      const Eigen::MatrixX3f &p = coefficients_[seg_idx];\n      Vec3f vel = Vec3f::Zero();\n      for(unsigned int i = 1; i < p.rows(); i++)\n        vel += p.row(i).transpose() * (i * powInt(t_traj, i - 1));\n      if(vel.norm() > seg_max_vel)\n        seg_max_vel = vel.norm();\n\n      Vec3f acc = Vec3f::Zero();\n      for(unsigned int i = 2; i < p.rows(); i++)\n        acc += p.row(i).transpose() * (i * (i - 1) * powInt(t_traj, i - 2));\n      if(acc.norm() > seg_max_acc)\n        seg_max_acc = acc.norm();\n\n      Vec3f jrk = Vec3f::Zero();\n      for(unsigned int i = 3; i < p.rows(); i++)\n        jrk += p.row(i).transpose() * (i * (i - 1) * (i - 2) * powInt(t_traj, i - 3));\n      if(jrk.norm() > seg_max_jrk)\n        seg_max_jrk = jrk.norm();\n    }\n    // printf(\"seg idx: %d\\n\", seg_idx);\n    // printf(\"max_vel: %f\\n\", seg_max_vel);\n    // printf(\"max_acc: %f\\n\", seg_max_acc);\n    // printf(\"max_jrk: %f\\n\", seg_max_jrk);\n    max_vel.push_back(seg_max_vel);\n    max_acc.push_back(seg_max_acc);\n    max_jrk.push_back(seg_max_jrk);\n  }\n  return;\n}\n\nvoid TrajectoryGenerator::optimizeWaypointTimes(const float max_vel, const float max_acc, const float max_jrk)\n{\n  std::vector<float> segment_times;\n  for(unsigned int i = 0; i < waypoint_times_.size() - 1; ++i)\n    segment_times.push_back(waypoint_times_[i + 1] - waypoint_times_[i]);\n\n  std::vector<float> best_segment_times = segment_times;\n  float best_cost = std::numeric_limits<float>::max();\n\n  for(int traj_iter = 0; traj_iter < 20; ++traj_iter)\n  {\n    // std::cout << std::string(20, '=') << \" \" << traj_iter << \" \"\n    //           << std::string(20, '=') << \"\\n\";\n\n    for(unsigned int i = 1; i < waypoint_times_.size(); ++i)\n    {\n      waypoint_times_[i] = waypoint_times_[i - 1] + segment_times[i - 1];\n    }\n    calculate(waypoint_times_);\n\n    std::vector<float> seg_max_vel, seg_max_acc, seg_max_jrk;\n    calcMaxPerSegment(seg_max_vel, seg_max_acc, seg_max_jrk);\n\n    const float vel_cost = 1.0f, acc_cost = 0.1f, jrk_cost = 0.01f;\n    float cost = 0;\n\n    const auto rectified_square = [](float x) { return (x > 0) ? x * x : 0; };\n\n    const std::vector<float> prev_segment_times = segment_times;\n    bool done = true;\n    for(unsigned int i = 0; i < seg_max_vel.size(); ++i)\n    {\n      cost += vel_cost * rectified_square(seg_max_vel[i] - max_vel) +\n              acc_cost * rectified_square(seg_max_acc[i] - max_acc) +\n              jrk_cost * rectified_square(seg_max_jrk[i] - max_jrk);\n\n      if(seg_max_vel[i] > max_vel || seg_max_acc[i] > max_acc || seg_max_jrk[i] > max_jrk)\n      {\n        segment_times[i] *= 1.035f;\n        done = false;\n      }\n      else if(seg_max_vel[i] < 0.9f * max_vel && seg_max_acc[i] < 0.9f * max_acc && seg_max_jrk[i] < 0.9f * max_jrk)\n      {\n        segment_times[i] *= 0.966f;\n        done = false;\n      }\n    }\n\n    // std::cout << \"cost: \" << cost << \"\\n\";\n    // If no solution found, keep the \"best\" one (with lowest violations)\n    if(cost <= best_cost)\n    {\n      best_segment_times = prev_segment_times;\n      best_cost = cost;\n    }\n    if(done)\n    {\n      // std::cout << \"Early exit! num iter: \" << traj_iter << \"\\n\";\n      break;\n    }\n  }\n}\n", "meta": {"hexsha": "1416d6bd601869fb2a9cda84f2f3f4251933abe3", "size": 13463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trackers/kr_trackers/src/traj_gen.cpp", "max_stars_repo_name": "fcladera/kr_mav_control", "max_stars_repo_head_hexsha": "3e4a80f9af469df59628537876fb4e9a8f2fcd14", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T17:04:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:43:50.000Z", "max_issues_repo_path": "trackers/kr_trackers/src/traj_gen.cpp", "max_issues_repo_name": "fcladera/kr_mav_control", "max_issues_repo_head_hexsha": "3e4a80f9af469df59628537876fb4e9a8f2fcd14", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T20:28:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-29T16:51:24.000Z", "max_forks_repo_path": "trackers/kr_trackers/src/traj_gen.cpp", "max_forks_repo_name": "fcladera/kr_mav_control", "max_forks_repo_head_hexsha": "3e4a80f9af469df59628537876fb4e9a8f2fcd14", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2021-02-10T09:38:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T15:55:59.000Z", "avg_line_length": 32.598062954, "max_line_length": 120, "alphanum_fraction": 0.6009061873, "num_tokens": 4301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.6654105521116443, "lm_q1q2_score": 0.4141910165626846}}
{"text": "#include \"A_Star.h\"\n\n//#include <queue>\n//#include <stdio.h>\n//#include <math.h>\n//#include <vector>\n//#include <cassert>\n//#include <typeinfo>\n//#include <vector>\n\n#include <boost/math/constants/constants.hpp>\n#include <iostream>\n#include <vector>\n\n\nusing namespace std;\n\nint A_Star::Get_Shortest_Path(const vector<vector<int>>& array,int Max_Search_Time,bool Debug_Info_Switch){\n    //为简单，干脆把把下面数组转为链表结构的数组\n    //约定：0是可走的，1表示障碍物不可走，2表示起点，3表示终点\n//    vector<vector<int>> array={\n//        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },\n//        { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },\n//        { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },\n//        { 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 },\n//        { 0, 0, 0, 0, 0, 1, 3, 0, 0, 0 },\n//        { 0, 0, 2, 0, 0, 1, 0, 0, 0, 0 },\n//        { 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 },\n//        { 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 },\n//        { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },\n//        { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };\n    debug_info_switch=Debug_Info_Switch;\n    int Error_flag=0;\n    bool Input_OK=false;\n    Input_OK =Input_Verify(array);\n    if(!Input_OK) return Error_flag;\n    map.Build_Map(array);\n\n    //PNode *Start_node;\n//    Start_node=map.Start_node;\n    //PNode *End_node;\n//    End_node=map.End_node;\n\n    map.Start_node->G=0;\n    map.Start_node->H=H_Calculat(map.Start_node,map.End_node);\n    map.Start_node->F=map.Start_node->G+map.Start_node->H;\n    map.Start_node->open_flag=1;\n    open_List.Heap_push(make_pair(map.Start_node->F,map.Start_node));\n//   cout<<\"hello world!  \"<<Open_List->next->G<<\" , \"<<Open_List->next->H<<endl;\n\n/********** main search ****************/\n    Shortest_Path_Long=-1;\n    Count=0;\n    int Search_end_flag;\n    while(1)\n    {\n        //cout<<\"Count=  \"<<Count<<endl;\n        Search_end_flag=Search();\n        if (Search_end_flag==1)\n         {\n            if(debug_info_switch)  cout<<\" Having find the useable path !!! \"<<endl;\n            Error_flag=0;\n            break;\n         }\n        if (Count>Max_Search_Time)\n         {\n            cout<<\" Path finding timeout !!! \"<<endl;\n            Error_flag=1;\n            break;\n         }\n        if (Search_end_flag==2)\n         {\n            if(debug_info_switch)  cout<<\" Can not find the useable path !!! \"<<endl;\n            Error_flag=1;\n            break;\n         }\n\n        Count++;\n //       cout<<\"opt_node->[G,H]  \"<<opt_node->G<<\" , \"<<opt_node->H<<endl;\n    }\n    if (Error_flag==0)\n    {\n        PNode *tmp=map.End_node;\n        while(tmp)\n        {\n            //cout<<\" [\"<<tmp->x<<\" , \"<<tmp->y<<\"] -> \";\n            Shortest_Path.push_back({tmp->x,tmp->y});\n            tmp=tmp->path_before;\n            Shortest_Path_Long++;\n        }\n        reverse(Shortest_Path.begin(),Shortest_Path.end());  // \" use of undlclared identifier 'reverse' ...\"  ----it is why?  need #include <boost/math/constants/constants.hpp>\n        //for(size_t i=0;i<Shortest_Path.size()/2;i++){\n        //    swap(Shortest_Path[i],Shortest_Path[Shortest_Path.size()-1-i]);\n        //}\n\n    }\n\n    //map.Clear_Map();\n\n    return Error_flag;\n}\n\nbool A_Star::Input_Verify(const vector<vector<int>>& array){\n    int Start_Point_Count=0,End_Point_Count=0;\n    for(size_t i=0;i<array.size();i++){\n        if(array[i].size() != array[0].size()){\n            cout<<\" Fatal Wrong , The Input Must be a Mutrix !!! \"<<endl;\n            return false;\n        }\n        for(size_t j=0;j<array[i].size();j++){\n            if (array[i][j]<0 || array[i][j]>3){\n                cout<<\" Fatal Wrong , The Value in the Input Mutrix must be 0, 1, 2, 3  !!! \"<<endl;\n                return false;\n            }\n            if (array[i][j]==2) Start_Point_Count++;\n            if (array[i][j]==3) End_Point_Count++;\n        }\n    }\n    if (Start_Point_Count==1 && End_Point_Count==1) return true;\n    else{\n        if (Start_Point_Count!=1) cout<<\" Fatal Wrong , Cannot find the start point or more than one start point !!! \"<<endl;\n        if (End_Point_Count!=1) cout<<\" Fatal Wrong , Cannot find the end point or more than one end point !!! \"<<endl;\n        return false;\n    }\n}\n\n\nfloat A_Star::H_Calculat(PNode *cur,PNode *end)\n{\n    float res=float_abs(cur->x-end->x)+float_abs(cur->y-end->y);\n    return res;\n}\n\nfloat A_Star::float_abs(float x){\n    return x > 0 ? x:-x;\n}\n\n\nint A_Star::Search()\n{   \n     if (open_List.Heap_size()==0){\n         if(debug_info_switch)  cout<<\" The Open_List_Min_Heap is empty !!! \"<<endl;\n         return 2;\n     }\n     PNode *Opt_node;\n     Opt_node=open_List.Heap_top().second;\n     Opt_node->open_flag=0;\n     Opt_node->close_flag=1;\n     open_List.Heap_pop();\n    for(size_t i=0;i<Opt_node->adjacent_node.size();i++)\n    {\n        PNode* Tmp_adjacent_next_node=Opt_node->adjacent_node[i];\n        if (Tmp_adjacent_next_node->nodetype==EndPoint)       // End point has been found!!!\n        {\n            Tmp_adjacent_next_node->path_before=Opt_node;\n            return 1;\n        }\n\n\n        if (Tmp_adjacent_next_node->open_flag==0 && Tmp_adjacent_next_node->close_flag==0 && Tmp_adjacent_next_node->nodetype !=UnReachable)\n        {\n            Tmp_adjacent_next_node->path_before=Opt_node;\n            Tmp_adjacent_next_node->G=Opt_node->G+1;\n            Tmp_adjacent_next_node->H=H_Calculat(Tmp_adjacent_next_node,map.End_node);\n            Tmp_adjacent_next_node->F=Tmp_adjacent_next_node->G+Tmp_adjacent_next_node->H;\n            Tmp_adjacent_next_node->open_flag=1;    //The open_flag should be modified! --20200312\n            open_List.Heap_push(make_pair(Tmp_adjacent_next_node->F,Tmp_adjacent_next_node));\n        }\n\n        else if(Tmp_adjacent_next_node->open_flag==1 && Tmp_adjacent_next_node->close_flag==0)\n        {\n            float tmp_G=Opt_node->G+1;\n            float tmp_H=H_Calculat(Tmp_adjacent_next_node,map.End_node);\n            float tmp_F=tmp_G+tmp_H;\n            if (tmp_F<Tmp_adjacent_next_node->F){\n                //update thr f which is in open list!!!!\n                //update thr f which is in open list!!!!\n                //update thr f which is in open list!!!!\n                Tmp_adjacent_next_node->G=tmp_G;\n                Tmp_adjacent_next_node->H=tmp_H;\n                Tmp_adjacent_next_node->F=tmp_F;\n                Tmp_adjacent_next_node->path_before=Opt_node;\n                //open_List.Heap_delect(Tmp_adjacent_next_node);\n                //open_List.Heap_push(make_pair(Tmp_adjacent_next_node->F,Tmp_adjacent_next_node));\n                open_List.Heap_modify(Tmp_adjacent_next_node,Tmp_adjacent_next_node->F);\n\n            }\n            else {\n                //no action!\n            }\n\n        }\n        else if(Tmp_adjacent_next_node->open_flag==0 && Tmp_adjacent_next_node->close_flag==1)\n        {\n            // no action!\n        }\n        else if((Tmp_adjacent_next_node->open_flag==0 && Tmp_adjacent_next_node->close_flag==0 && Tmp_adjacent_next_node->nodetype ==UnReachable))\n        {\n            Tmp_adjacent_next_node->close_flag=1;\n        }\n        else {\n            cout<<\"Fatel Error!!!\"<<endl;\n             return 2;\n        }\n\n    }\n\n    return 0;\n}\n\nvoid A_Star::clear(){\n    Shortest_Path.clear();\n    open_List.Heap_clear();\n    map.Clear_Map();\n}\n", "meta": {"hexsha": "8af9fac9ccc6408afb8933978b8a057bba4c9ffb", "size": 7148, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "A_Star/A_Star.cpp", "max_stars_repo_name": "Forrest-Z/A_Star-and-Hybrid_A_Star", "max_stars_repo_head_hexsha": "75ceddf24e9275d695bc240a978bbe2d4ed7077c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-03T01:34:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T01:34:45.000Z", "max_issues_repo_path": "A_Star/A_Star.cpp", "max_issues_repo_name": "Forrest-Z/A_Star-and-Hybrid_A_Star", "max_issues_repo_head_hexsha": "75ceddf24e9275d695bc240a978bbe2d4ed7077c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "A_Star/A_Star.cpp", "max_forks_repo_name": "Forrest-Z/A_Star-and-Hybrid_A_Star", "max_forks_repo_head_hexsha": "75ceddf24e9275d695bc240a978bbe2d4ed7077c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0925925926, "max_line_length": 177, "alphanum_fraction": 0.5650531617, "num_tokens": 2129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6224593241981982, "lm_q1q2_score": 0.41419100671188724}}
{"text": "#ifndef __INTEGRATE_UTIL_HH__\n#define __INTEGRATE_UTIL_HH__\n/********************************* TRICK HEADER *******************************\nPURPOSE:\n      (Integration wapper functions)\nLIBRARY DEPENDENCY:\n      ((../src/integrate.cpp))\n*******************************************************************************/\n\n#include <armadillo>\n#include <cassert>\n#include <vector>\n#include \"Rocket_Flight_DM.hh\"\n\n#define INTEGRATE(in, diff)                         \\\n  do {                                              \\\n    double in##d_new = diff;                        \\\n    in = integrate(in##d_new, in##d, in, int_step); \\\n    in##d = in##d_new;                              \\\n  } while (0)\n\n#define INTEGRATE_MAT(in, diff)                     \\\n  do {                                              \\\n    arma::mat in##D_NEW = diff;                     \\\n    in = integrate(in##D_NEW, in##D, in, int_step); \\\n    in##D = in##D_NEW;                              \\\n  } while (0)\n\n/**\n * \\brief Integration of scalar state variable.\n * Modified Euler Midpoint method\n * Example first order lag:\n *   phid_new=(phic-phi)/tphi;\n *   phi=integrate(phid_new,phid,phi,int_step);\n *   phid=phid_new;\n */\ndouble integrate(const double &dydx_new, const double &dydx, const double &y,\n                 const double &int_step);\n\narma::mat integrate(arma::mat &DYDX_NEW, arma::mat &DYDX, arma::mat &Y,\n                    const double int_step);\ntemplate <typename T>\nvoid IntegratorRK4(std::vector<arma::vec> V_in, std::vector<arma::vec> &V_out,\n                   void (T::*fp)(std::vector<arma::vec> Var_in,\n                                 std::vector<arma::vec> &Var_out),\n                   T *ClassPointer, double int_step) {\n  {\n    std::vector<std::vector<arma::vec>> KMAT;\n    for (unsigned int i = 0; i < V_in.size(); i++) {\n      std::vector<arma::vec> KROW(4);\n      KMAT.push_back(KROW);\n    }\n\n    V_out = V_in;\n\n    ((ClassPointer)->*fp)(V_out, KMAT[0]);\n\n    for (unsigned int i = 0; i < V_in.size(); i++) {\n      V_out[i] = V_in[i] + KMAT[0][i] * 0.5 * int_step;\n    }\n\n    ((ClassPointer)->*fp)(V_out, KMAT[1]);\n\n    for (unsigned int i = 0; i < V_in.size(); i++) {\n      V_out[i] = V_in[i] + KMAT[1][i] * 0.5 * int_step;\n    }\n\n    ((ClassPointer)->*fp)(V_out, KMAT[2]);\n\n    for (unsigned int i = 0; i < V_in.size(); i++) {\n      V_out[i] = V_in[i] + KMAT[2][i] * int_step;\n    }\n\n    ((ClassPointer)->*fp)(V_out, KMAT[3]);\n\n    for (unsigned int i = 0; i < V_in.size(); i++) {\n      V_out[i] = V_in[i] +\n                 (int_step / 6.0) * (KMAT[0][i] + 2.0 * KMAT[1][i] +\n                                     2.0 * KMAT[2][i] + KMAT[3][i]);\n    }\n  }\n}\n\ntemplate <typename T>\nvoid IntegratorEuler(std::vector<arma::vec> V_in, std::vector<arma::vec> &V_out,\n                     void (T::*fp)(std::vector<arma::vec> Var_in,\n                                   std::vector<arma::vec> &Var_out),\n                     T *ClassPointer, double int_step) {\n  std::vector<arma::vec> K_TEMP;\n\n  for (unsigned int i = 0; i < V_in.size(); i++) {\n    arma::vec temp;\n    K_TEMP.push_back(temp);\n  }\n\n  ((ClassPointer)->*fp)(V_in, K_TEMP);\n\n  for (unsigned int i = 0; i < V_in.size(); i++) {\n    V_out[i] = V_in[i] + K_TEMP[i] * int_step;\n  }\n}\n#endif  // __INTEGRATE_UTIL_HH__\n", "meta": {"hexsha": "ba8ef8eced159c04841d2a56c14195f936e87530", "size": 3274, "ext": "hh", "lang": "C++", "max_stars_repo_path": "models/math/include/integrate.hh", "max_stars_repo_name": "cihuang123/Next-simulation", "max_stars_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/math/include/integrate.hh", "max_issues_repo_name": "cihuang123/Next-simulation", "max_issues_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/math/include/integrate.hh", "max_forks_repo_name": "cihuang123/Next-simulation", "max_forks_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.786407767, "max_line_length": 80, "alphanum_fraction": 0.4874770922, "num_tokens": 945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.41410619065387416}}
{"text": "#ifndef _SOT_CORE_CAUSAL_FILTER_H_\n#define _SOT_CORE_CAUSAL_FILTER_H_\n/*\n * Copyright 2017-, Rohan Budhirja, LAAS-CNRS\n *\n * This file is part of sot-torque-control.\n * sot-torque-control is free software: you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public License\n * as published by the Free Software Foundation, either version 3 of\n * the License, or (at your option) any later version.\n * sot-torque-control is distributed in the hope that it will be\n * useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License for more details.  You should\n * have received a copy of the GNU Lesser General Public License along\n * with sot-torque-control.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n/* --------------------------------------------------------------------- */\n/* --- INCLUDE --------------------------------------------------------- */\n/* --------------------------------------------------------------------- */\n#include <Eigen/Core>\n\n/** \\addtogroup Filters\n    \\section subsec_causalfilter CausalFilter\n    Filter data with an IIR or FIR filter.\n\n    Filter a data sequence, \\f$x\\f$, using a digital filter.\n    The filter is a direct form II transposed implementation\n    of the standard difference equation.\n    This means that the filter implements:\n\n    \\f$ a[0]*y[N] = b[0]*x[N] + b[1]*x[N-1] + ... + b[m-1]*x[N-(m-1)]\n    - a[1]*y[N-1] - ... - a[n-1]*y[N-(n-1)] \\f$\n\n    where \\f$m\\f$ is the degree of the numerator,\n    \\f$n\\f$ is the degree of the denominator,\n    and \\f$N\\f$ is the sample number\n\n\n */\nnamespace dynamicgraph {\nnamespace sot {\n\nclass CausalFilter {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  /** --- CONSTRUCTOR ----\n      \\param[in] timestep\n      \\param[in] xSize\n      \\param[in] filter_numerator\n      \\param[in] filter_denominator\n\n      xSize is\n  */\n  CausalFilter(const double &timestep, const int &xSize,\n               const Eigen::VectorXd &filter_numerator,\n               const Eigen::VectorXd &filter_denominator);\n\n  void get_x_dx_ddx(const Eigen::VectorXd &base_x,\n                    Eigen::VectorXd &x_output_dx_ddx);\n\n  void switch_filter(const Eigen::VectorXd &filter_numerator,\n                     const Eigen::VectorXd &filter_denominator);\n\nprivate:\n  /// sampling timestep of the input signal\n  double m_dt;\n  /// Size\n  int m_x_size;\n  /// Size of the numerator \\f$m\\f$\n  Eigen::VectorXd::Index m_filter_order_m;\n  /// Size of the denominator \\f$n\\f$\n  Eigen::VectorXd::Index m_filter_order_n;\n\n  /// Coefficients of the numerator \\f$b\\f$\n  Eigen::VectorXd m_filter_numerator;\n  /// Coefficients of the denominator \\f$a\\f$\n  Eigen::VectorXd m_filter_denominator;\n  bool m_first_sample;\n  ///\n  int m_pt_numerator;\n  int m_pt_denominator;\n  Eigen::MatrixXd m_input_buffer;\n  Eigen::MatrixXd m_output_buffer;\n}; // class CausalFilter\n} // namespace sot\n} // namespace dynamicgraph\n#endif /* _SOT_CORE_CAUSAL_FILTER_H_ */\n", "meta": {"hexsha": "8f3110d549d7c4d26dad6cfb24b6bc8ec4a32e94", "size": 3042, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/sot/core/causal-filter.hh", "max_stars_repo_name": "Rascof/sot-core", "max_stars_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T07:15:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T13:41:06.000Z", "max_issues_repo_path": "include/sot/core/causal-filter.hh", "max_issues_repo_name": "Rascof/sot-core", "max_issues_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 121.0, "max_issues_repo_issues_event_min_datetime": "2015-02-17T08:38:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T10:54:05.000Z", "max_forks_repo_path": "include/sot/core/causal-filter.hh", "max_forks_repo_name": "Rascof/sot-core", "max_forks_repo_head_hexsha": "281ed2a1b40b7945b5a3d5735f785b9004b19f87", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-07-01T16:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T15:06:58.000Z", "avg_line_length": 33.4285714286, "max_line_length": 75, "alphanum_fraction": 0.6469428008, "num_tokens": 753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4140636682076163}}
{"text": "#include <boost/math/special_functions/next.hpp>\n#include <boost/random.hpp>\n\n#include <limits>\n\n#include \"caffe/common.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/rng.hpp\"\n\nnamespace caffe {\n\ntemplate<>\nvoid caffe_cpu_gemm<float>(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,\n    const float alpha, const float* A, const float* B, const float beta,\n    float* C) {\n  int lda = (TransA == CblasNoTrans) ? K : M;\n  int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_sgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B,\n      ldb, beta, C, N);\n}\n\ntemplate<>\nvoid caffe_cpu_gemm<double>(const CBLAS_TRANSPOSE TransA,\n    const CBLAS_TRANSPOSE TransB, const int M, const int N, const int K,\n    const double alpha, const double* A, const double* B, const double beta,\n    double* C) {\n  int lda = (TransA == CblasNoTrans) ? K : M;\n  int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_dgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B,\n      ldb, beta, C, N);\n}\n\ntemplate <>\nvoid caffe_cpu_gemv<float>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const float alpha, const float* A, const float* x,\n    const float beta, float* y) {\n  cblas_sgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_gemv<double>(const CBLAS_TRANSPOSE TransA, const int M,\n    const int N, const double alpha, const double* A, const double* x,\n    const double beta, double* y) {\n  cblas_dgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\ntemplate <>\nvoid caffe_axpy<float>(const int N, const float alpha, const float* X,\n    float* Y) { cblas_saxpy(N, alpha, X, 1, Y, 1); }\n\ntemplate <>\nvoid caffe_axpy<double>(const int N, const double alpha, const double* X,\n    double* Y) { cblas_daxpy(N, alpha, X, 1, Y, 1); }\n\ntemplate <typename Dtype>\nvoid caffe_set(const int N, const Dtype alpha, Dtype* Y) {\n  if (alpha == 0) {\n    memset(Y, 0, sizeof(Dtype) * N);  // NOLINT(caffe/alt_fn)\n    return;\n  }\n  for (int i = 0; i < N; ++i) {\n    Y[i] = alpha;\n  }\n}\n\ntemplate void caffe_set<int>(const int N, const int alpha, int* Y);\ntemplate void caffe_set<float>(const int N, const float alpha, float* Y);\ntemplate void caffe_set<double>(const int N, const double alpha, double* Y);\n\ntemplate <>\nvoid caffe_add_scalar(const int N, const float alpha, float* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\ntemplate <>\nvoid caffe_add_scalar(const int N, const double alpha, double* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\ntemplate <typename Dtype>\nvoid caffe_copy(const int N, const Dtype* X, Dtype* Y) {\n  if (X != Y) {\n    if (Caffe::mode() == Caffe::GPU) {\n#ifndef CPU_ONLY\n      // NOLINT_NEXT_LINE(caffe/alt_fn)\n      CUDA_CHECK(cudaMemcpy(Y, X, sizeof(Dtype) * N, cudaMemcpyDefault));\n#else\n      NO_GPU;\n#endif\n    } else {\n      memcpy(Y, X, sizeof(Dtype) * N);  // NOLINT(caffe/alt_fn)\n    }\n  }\n}\n\ntemplate void caffe_copy<int>(const int N, const int* X, int* Y);\ntemplate void caffe_copy<unsigned int>(const int N, const unsigned int* X,\n    unsigned int* Y);\ntemplate void caffe_copy<float>(const int N, const float* X, float* Y);\ntemplate void caffe_copy<double>(const int N, const double* X, double* Y);\n\ntemplate <>\nvoid caffe_scal<float>(const int N, const float alpha, float *X) {\n  cblas_sscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_scal<double>(const int N, const double alpha, double *X) {\n  cblas_dscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<float>(const int N, const float alpha, const float* X,\n                            const float beta, float* Y) {\n  cblas_saxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<double>(const int N, const double alpha, const double* X,\n                             const double beta, double* Y) {\n  cblas_daxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_add<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsAdd(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_add<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdAdd(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sub<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsSub(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sub<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdSub(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_mul<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsMul(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_mul<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdMul(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_div<float>(const int n, const float* a, const float* b,\n    float* y) {\n  vsDiv(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_div<double>(const int n, const double* a, const double* b,\n    double* y) {\n  vdDiv(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_powx<float>(const int n, const float* a, const float b,\n    float* y) {\n  vsPowx(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_powx<double>(const int n, const double* a, const double b,\n    double* y) {\n  vdPowx(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sqr<float>(const int n, const float* a, float* y) {\n  vsSqr(n, a, y);\n}\n\ntemplate <>\nvoid caffe_sqr<double>(const int n, const double* a, double* y) {\n  vdSqr(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<float>(const int n, const float* a, float* y) {\n  vsExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<double>(const int n, const double* a, double* y) {\n  vdExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<float>(const int n, const float* a, float* y) {\n    vsAbs(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<double>(const int n, const double* a, double* y) {\n    vdAbs(n, a, y);\n}\n\nunsigned int caffe_rng_rand() {\n  return (*caffe_rng())();\n}\n\ntemplate <typename Dtype>\nDtype caffe_nextafter(const Dtype b) {\n  return boost::math::nextafter<Dtype>(\n      b, std::numeric_limits<Dtype>::max());\n}\n\ntemplate\nfloat caffe_nextafter(const float b);\n\ntemplate\ndouble caffe_nextafter(const double b);\n\ntemplate <typename Dtype>\nvoid caffe_rng_uniform(const int n, const Dtype a, const Dtype b, Dtype* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_LE(a, b);\n  boost::uniform_real<Dtype> random_distribution(a, caffe_nextafter<Dtype>(b));\n  boost::variate_generator<caffe::rng_t*, boost::uniform_real<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\ntemplate\nvoid caffe_rng_uniform<float>(const int n, const float a, const float b,\n                              float* r);\n\ntemplate\nvoid caffe_rng_uniform<double>(const int n, const double a, const double b,\n                               double* r);\n\ntemplate <typename Dtype>\nvoid caffe_rng_gaussian(const int n, const Dtype a,\n                        const Dtype sigma, Dtype* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GT(sigma, 0);\n  boost::normal_distribution<Dtype> random_distribution(a, sigma);\n  boost::variate_generator<caffe::rng_t*, boost::normal_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\ntemplate\nvoid caffe_rng_gaussian<float>(const int n, const float mu,\n                               const float sigma, float* r);\n\ntemplate\nvoid caffe_rng_gaussian<double>(const int n, const double mu,\n                                const double sigma, double* r);\n\ntemplate <typename Dtype>\nvoid caffe_rng_bernoulli(const int n, const Dtype p, int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n  boost::bernoulli_distribution<Dtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\ntemplate\nvoid caffe_rng_bernoulli<double>(const int n, const double p, int* r);\n\ntemplate\nvoid caffe_rng_bernoulli<float>(const int n, const float p, int* r);\n\ntemplate <typename Dtype>\nvoid caffe_rng_bernoulli(const int n, const Dtype p, unsigned int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n  boost::bernoulli_distribution<Dtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = static_cast<unsigned int>(variate_generator());\n  }\n}\n\ntemplate\nvoid caffe_rng_bernoulli<double>(const int n, const double p, unsigned int* r);\n\ntemplate\nvoid caffe_rng_bernoulli<float>(const int n, const float p, unsigned int* r);\n\ntemplate <>\nfloat caffe_cpu_strided_dot<float>(const int n, const float* x, const int incx,\n    const float* y, const int incy) {\n  return cblas_sdot(n, x, incx, y, incy);\n}\n\ntemplate <>\ndouble caffe_cpu_strided_dot<double>(const int n, const double* x,\n    const int incx, const double* y, const int incy) {\n  return cblas_ddot(n, x, incx, y, incy);\n}\n\ntemplate <typename Dtype>\nDtype caffe_cpu_dot(const int n, const Dtype* x, const Dtype* y) {\n  return caffe_cpu_strided_dot(n, x, 1, y, 1);\n}\n\ntemplate\nfloat caffe_cpu_dot<float>(const int n, const float* x, const float* y);\n\ntemplate\ndouble caffe_cpu_dot<double>(const int n, const double* x, const double* y);\n\ntemplate <>\nint caffe_cpu_hamming_distance<float>(const int n, const float* x,\n                                  const float* y) {\n  int dist = 0;\n  for (int i = 0; i < n; ++i) {\n    dist += __builtin_popcount(static_cast<uint32_t>(x[i]) ^\n                               static_cast<uint32_t>(y[i]));\n  }\n  return dist;\n}\n\ntemplate <>\nint caffe_cpu_hamming_distance<double>(const int n, const double* x,\n                                   const double* y) {\n  int dist = 0;\n  for (int i = 0; i < n; ++i) {\n    dist += __builtin_popcountl(static_cast<uint64_t>(x[i]) ^\n                                static_cast<uint64_t>(y[i]));\n  }\n  return dist;\n}\n\ntemplate <>\nfloat caffe_cpu_asum<float>(const int n, const float* x) {\n  return cblas_sasum(n, x, 1);\n}\n\ntemplate <>\ndouble caffe_cpu_asum<double>(const int n, const double* x) {\n  return cblas_dasum(n, x, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_scale<float>(const int n, const float alpha, const float *x,\n                            float* y) {\n  cblas_scopy(n, x, 1, y, 1);\n  cblas_sscal(n, alpha, y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_scale<double>(const int n, const double alpha, const double *x,\n                             double* y) {\n  cblas_dcopy(n, x, 1, y, 1);\n  cblas_dscal(n, alpha, y, 1);\n}\n/* changes */\n\n//calculate gamma in kernel function\n//K: dimension of data\n//S: size of all data\n//N: num of output\n//W: weights, N*K\n//X: X (input of this layer)\ntemplate <>\nfloat cal_gamma_cpu<float>(const int K, const int S, const int N, const float* W, const float* X, float* tempX1, float* tempX2){\n    srand((unsigned int)time(0));\n    float gamma = 0;\n    float temp = 0;\n    \n    //random sample S pair to calculate gamma\n    for(int i = 0;i < S;++i){\n        memset(tempX1, 0, sizeof(float) * K);\n        memset(tempX2, 0, sizeof(float) * K);\n        int s1 = rand() % S;\n        int s2 = rand() % S;\n        s2 = (s1 != s2) ? s2 : (s2 + 1) % S;\n        \n        const float* x1 = X + s1 * K;\n        const float* x2 = X + s2 * K;\n\n        caffe_cpu_gemv<float>(CblasNoTrans, N, K, 1.0, W, x1, 0.0, tempX1);\n        caffe_cpu_gemv<float>(CblasNoTrans, N, K, 1.0, W, x2, 0.0, tempX2);\n        \n        //caffe_cpu_sub<float>(K, tempX1, tempX2, tempX2);\n        caffe_cpu_axpby(K, 1.0f, tempX1, -1.0f, tempX2);\n        temp = caffe_cpu_dot<float>(K, tempX2, tempX2);\n        gamma += temp;\n    }\n    return S / gamma;\n}\n\n//output: \n//  tempX1: W*x1-W*x2\n//  tempX2: x1-x2\n//  KK: co * (x1-x2)^T * W^T  should be 1*N\ntemplate<>\nvoid cal_add_item_cpu<float>(const float co, const int N, const int K, const float* W, const float* x1, float* tempX1, \n    const float* x2, float* tempX2, const float gamma, float* KK){\n\n    memset(tempX1, 0, sizeof(float) * K);\n    memset(tempX2, 0, sizeof(float) * K);\n    \n    caffe_cpu_gemv<float>(CblasNoTrans, N, K, 1.0, W, x1, 0.0, tempX1);\n    caffe_cpu_gemv<float>(CblasNoTrans, N, K, 1.0, W, x2, 0.0, tempX2);\n    \n    float square_sum = 0;\n\n    caffe_cpu_axpby(K, -1.0f, tempX2, 1.0f, tempX1);\n    caffe_cpu_axpby(K, 1.0f, x1, 0.0f, tempX2);\n    caffe_cpu_axpby(K, -1.0f, x2, 1.0f, tempX2);\n    square_sum = caffe_cpu_dot<float>(K, tempX1, tempX1);\n\n    //calculate 2 * \\gamma * kernel\n    float kernel = 0.0f;\n    float tempGamma = gamma / 4.0f;\n    for(int i = 0;i < 5;++i){\n        float temp = (0.0 - tempGamma) * square_sum;\n        temp = exp(temp);\n        kernel += 2 * tempGamma* temp;\n        tempGamma = tempGamma * 2;\n    }\n    /*float kernel = (0.0 - gamma) * square_sum;\n    kernel = exp(kernel);\n    kernel = 2 * gamma * kernel;\n*/\n    //calculate KK <- co * kernel * X^T * W + 1 * KK\n    caffe_cpu_gemm<float>(CblasNoTrans, CblasTrans, 1, N, K, co*kernel, tempX2, W, 0.0, KK);\n}\n\ntemplate<>\nvoid cal_add_item_cpu<double>(const double co, const int N, const int K, const double* W, const double* x1, double* tempX1, \n    const double* x2, double* tempX2, const double gamma, double* KK){\n    //TODO: complete double version of this function\n}\n\n// Gradient with respect to weight for MMD\n      //N: number of output neuron\n      //K: dimension of the feature\n      //M: size of all data\n      //S: size of source data in a batch\n      //W: weight of this layer\n      //X: input of this layer\n      //gamma: gamma / learning rate\n      //delta_W: gredient of weight\n\ntemplate<>\nvoid caffe_cpu_mmd<float>(const int N, const int K, const int M, const int S, const int labeledTargetSize, \n    const float* W, const float* X, const float gamma, float* delta_W){\n    srand((unsigned int)time(0));\n    \n    //output the value of delta_W before MMD gradient\n    float sum = 0;\n    for(int i = 0;i < N;++i){\n        for(int j = 0;j < K;++j){\n            sum += (delta_W[i * N + j] > 0) ? delta_W[i*N+j] : (-1 * delta_W[i*N+j]);\n        }\n    }\n    LOG(INFO) << \"delta_W before MMD, sum = \" << sum << \", average = \" << sum / (N*K);\n\n    float *KK = new float[N];\n    float *tempX1 = new float[K];\n    float *tempX2 = new float[K];\n\n    float kernel_gamma = cal_gamma_cpu(K, M, N, W, X, tempX1, tempX2);\n    int SS = (S>(M-S)) ? S : M-S;\n    \n    for(int i = 0;i < SS;++i){\n        //random\n        int s1 = rand() % S;\n        int s2 = rand() % S;\n        if(s1 == s2){\n            s2 = (s2 + 100) % S;\n        }\n        int t1 = rand() % (M - S - labeledTargetSize);\n        int t2 = rand() % (M - S - labeledTargetSize);\n        if(t1 == t2){\n            t2 = (t2 + 100) % (M - S - labeledTargetSize);\n        }\n        t1 = t1 + S + labeledTargetSize;\n        t2 = t2 + S + labeledTargetSize;\n        \n        const float *x_s1 = X + s1 * K;\n        const float *x_s2 = X + s2 * K;\n        const float *x_t1 = X + t1 * K;\n        const float *x_t2 = X + t2 * K;\n        const float tempS = 1.0;\n\n        //calculate four items of MMD gradient\n        memset(KK, 0, sizeof(float) * N);\n        cal_add_item_cpu<float>(-1, N, K, W, x_s1, tempX1, x_s2, tempX2, kernel_gamma, KK);\n        caffe_cpu_gemm<float>(CblasNoTrans, CblasTrans, N, K, 1, tempS * gamma, KK,tempX2, 1.0, delta_W);\n\n        memset(KK, 0, sizeof(float) * N);\n        cal_add_item_cpu<float>(1, N, K, W, x_s1, tempX1, x_t2, tempX2, kernel_gamma, KK);\n        caffe_cpu_gemm<float>(CblasNoTrans, CblasTrans, N, K, 1, tempS * gamma, KK,tempX2, 1.0, delta_W);\n\n        memset(KK, 0, sizeof(float) * N);\n        cal_add_item_cpu<float>(1, N, K, W, x_s2, tempX1, x_t1, tempX2, kernel_gamma, KK);\n        caffe_cpu_gemm<float>(CblasNoTrans, CblasTrans, N, K, 1, tempS * gamma, KK,tempX2, 1.0, delta_W);\n\n        memset(KK, 0, sizeof(float) * N);\n        cal_add_item_cpu<float>(-1, N, K, W, x_t1, tempX1, x_t2, tempX2, kernel_gamma, KK);\n        caffe_cpu_gemm<float>(CblasNoTrans, CblasTrans, N, K, 1, tempS * gamma, KK,tempX2, 1.0, delta_W);\n    }\n    //output the value of delta_W after MMD gradient\n    sum = 0;\n    for(int i = 0;i < N;++i){\n        for(int j = 0;j < K;++j){\n            sum += (delta_W[i * N + j] > 0) ? delta_W[i*N+j] : (-1 * delta_W[i*N+j]);\n        }\n    }\n    LOG(INFO) << \"delta_W after MMD, sum = \" << sum << \", average = \" << sum / (N*K);\n\n    delete [] KK;\n    delete [] tempX1;\n    delete [] tempX2;\n}\n\ntemplate<>\nvoid caffe_cpu_mmd<double>(const int N, const int K, const int M, const int S, const int labeledTargetSize,\n    const double* W, const double* X, const double gamma, double* delta_W){\n    //TODO: complete the double version of this function\n}\n\n}  // namespace caffe\n", "meta": {"hexsha": "adad1ef82fede431d995e770742c08ce9302ab2c", "size": 16727, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_functions.cpp", "max_stars_repo_name": "caoyue10/icml-caffe", "max_stars_repo_head_hexsha": "cffa7c6d9f328e7d0897702723c0517433072248", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2015-09-09T07:16:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-08T13:38:13.000Z", "max_issues_repo_path": "src/caffe/util/math_functions.cpp", "max_issues_repo_name": "fengshiyu1997/icml-caffe", "max_issues_repo_head_hexsha": "cffa7c6d9f328e7d0897702723c0517433072248", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/caffe/util/math_functions.cpp", "max_forks_repo_name": "fengshiyu1997/icml-caffe", "max_forks_repo_head_hexsha": "cffa7c6d9f328e7d0897702723c0517433072248", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2016-06-30T12:56:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-16T06:35:46.000Z", "avg_line_length": 30.0845323741, "max_line_length": 128, "alphanum_fraction": 0.619836193, "num_tokens": 5254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4140636620872576}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <iomanip>\n\n#include \"../include/structures.h\"\n#include \"../include/transformations.h\"\n#include \"../../rectangular_object_with_unknown_width_height_tait_bryan_wc_jacobian.h\"\n#include \"../../rectangular_object_with_unknown_width_height_rodrigues_wc_jacobian.h\"\n#include \"../../rectangular_object_with_unknown_width_height_quaternion_wc_jacobian.h\"\n#include \"../../quaternion_constraint_jacobian.h\"\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = 0.0, rotate_y = 0.0;\nfloat translate_z = -10.0;\nfloat translate_x, translate_y = 0.0;\n\nstd::vector<std::vector<Eigen::Affine3d>> bundle_of_rays;\nstruct Rectangle{\n\tstd::vector<Eigen::Vector3d> corners_local;\n\tdouble scale_x;\n\tdouble scale_y;\n\tEigen::Affine3d pose;\n};\nRectangle rectangle;\n\nbool initGL(int *argc, char **argv);\nvoid display();\nvoid keyboard(unsigned char key, int x, int y);\nvoid mouse(int button, int state, int x, int y);\nvoid motion(int x, int y);\nvoid reshape(int w, int h);\nvoid printHelp();\n\nint main(int argc, char *argv[]){\n\n\tstd::vector<Eigen::Affine3d> br;\n\tfor(size_t i = 0; i < 25; i++){\n\t\tTaitBryanPose pose;\n\n\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 + 10;\n\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 + -5;\n\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 + -2;\n\n\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.5;\n\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.5;\n\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.5;\n\n\t\tbr.push_back(affine_matrix_from_pose_tait_bryan(pose));\n\t}\n\tbundle_of_rays.push_back(br);\n\tbr.clear();\n\tfor(size_t i = 0; i < 25; i++){\n\t\tTaitBryanPose pose;\n\n\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 + 10;\n\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 +  5;\n\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 + -2;\n\n\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.5;\n\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.5;\n\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.5;\n\n\t\tbr.push_back(affine_matrix_from_pose_tait_bryan(pose));\n\t}\n\tbundle_of_rays.push_back(br);\n\tbr.clear();\n\tfor(size_t i = 0; i < 25; i++){\n\t\tTaitBryanPose pose;\n\n\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 + 10;\n\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 +  5;\n\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 +  5;\n\n\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.5;\n\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.5;\n\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.5;\n\n\t\tbr.push_back(affine_matrix_from_pose_tait_bryan(pose));\n\t}\n\tbundle_of_rays.push_back(br);\n\tbr.clear();\n\tfor(size_t i = 0; i < 25; i++){\n\t\tTaitBryanPose pose;\n\n\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 + 10;\n\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 + -5;\n\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.01 +  5;\n\n\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.5;\n\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.5;\n\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.5;\n\n\t\tbr.push_back(affine_matrix_from_pose_tait_bryan(pose));\n\t}\n\tbundle_of_rays.push_back(br);\n\tbr.clear();\n\n\n\trectangle.scale_x = 1.0;\n\trectangle.scale_y = 1.0;\n\trectangle.pose = Eigen::Affine3d::Identity();\n\trectangle.corners_local.emplace_back(-1,-1, 0);\n\trectangle.corners_local.emplace_back( 1,-1, 0);\n\trectangle.corners_local.emplace_back( 1, 1, 0);\n\trectangle.corners_local.emplace_back(-1, 1, 0);\n\n\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\n\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"rectangular_object_with_unknown_width_height\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01,\n\t\t\t10000.0);\n\tglutReshapeFunc(reshape);\n\n\treturn true;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tglColor3f(0,1,0);\n\tglBegin(GL_LINES);\n\tfor(size_t i = 0; i < bundle_of_rays.size(); i++){\n\t\tfor(size_t j = 0; j < bundle_of_rays[i].size(); j++){\n\t\t\tEigen::Vector3d z_begin(0, 0,-100);\n\t\t\tEigen::Vector3d z_end(0, 0, 100);\n\n\t\t\tEigen::Vector3d z_begin_t = bundle_of_rays[i][j] * z_begin;\n\t\t\tEigen::Vector3d z_end_t = bundle_of_rays[i][j] * z_end;\n\n\t\t\tglVertex3f(z_begin_t.x(), z_begin_t.y(), z_begin_t.z());\n\t\t\tglVertex3f(z_end_t.x(), z_end_t.y(), z_end_t.z());\n\t\t}\n\t}\n\tglEnd();\n\n\tstd::vector<Eigen::Vector3d> corners_global;\n\tfor(size_t i = 0; i < rectangle.corners_local.size(); i++){\n\t\tEigen::Vector3d v(rectangle.corners_local[i].x() * rectangle.scale_x, rectangle.corners_local[i].y() * rectangle.scale_y, rectangle.corners_local[i].z());\n\t\tcorners_global.push_back(rectangle.pose * v);\n\t}\n\n\tglLineWidth(5);\n\tglColor3f(1,0,0);\n\tglBegin(GL_LINE_STRIP);\n\t\tfor(size_t i = 0 ; i < corners_global.size(); i++){\n\t\t\tglVertex3f(corners_global[i].x(), corners_global[i].y(), corners_global[i].z());\n\t\t}\n\t\tglVertex3f(corners_global[0].x(), corners_global[0].y(), corners_global[0].z());\n\tglEnd();\n\tglLineWidth(1);\n\tglutSwapBuffers();\n}\n\n\nvoid keyboard(unsigned char key, int /*x*/, int /*y*/) {\n\tswitch (key) {\n\t\tcase (27): {\n\t\t\tglutDestroyWindow(glutGetWindow());\n\t\t\treturn;\n\t\t}\n\t\tcase 't':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(rectangle.pose);\n\n\t\t\tfor(size_t i = 0; i < bundle_of_rays.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < bundle_of_rays[i].size(); j++){\n\t\t\t\t\tEigen::Vector3d vx(bundle_of_rays[i][j](0,0), bundle_of_rays[i][j](1,0), bundle_of_rays[i][j](2,0));\n\t\t\t\t\tEigen::Vector3d vy(bundle_of_rays[i][j](0,1), bundle_of_rays[i][j](1,1), bundle_of_rays[i][j](2,1));\n\n\t\t\t\t\tEigen::Matrix<double, 2, 1> delta;\n\t\t\t\t\trectangular_object_with_unknown_width_height_tait_bryan_wc(delta,\n\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka,\n\t\t\t\t\t\t\trectangle.corners_local[i].x(), rectangle.corners_local[i].y(), rectangle.corners_local[i].z(),\n\t\t\t\t\t\t\tbundle_of_rays[i][j](0,3), bundle_of_rays[i][j](1,3), bundle_of_rays[i][j](2,3),\n\t\t\t\t\t\t\tvx.x(), vx.y(), vx.z(), vy.x(), vy.y(), vy.z(),\n\t\t\t\t\t\t\trectangle.scale_x, rectangle.scale_y);\n\n\t\t\t\t\tEigen::Matrix<double, 2, 8> delta_jacobian;\n\t\t\t\t\trectangular_object_with_unknown_width_height_tait_bryan_wc_jacobian(delta_jacobian,\n\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka,\n\t\t\t\t\t\t\trectangle.corners_local[i].x(), rectangle.corners_local[i].y(), rectangle.corners_local[i].z(),\n\t\t\t\t\t\t\tbundle_of_rays[i][j](0,3), bundle_of_rays[i][j](1,3), bundle_of_rays[i][j](2,3),\n\t\t\t\t\t\t\tvx.x(), vx.y(), vx.z(), vy.x(), vy.y(), vy.z(),\n\t\t\t\t\t\t\trectangle.scale_x, rectangle.scale_y);\n\n\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\tfor(size_t k = 0 ; k < 8; k++){\n\t\t\t\t\t\ttripletListA.emplace_back(ir, k, -delta_jacobian(0,k));\n\t\t\t\t\t}\n\t\t\t\t\tfor(size_t k = 0 ; k < 8; k++){\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1, k, -delta_jacobian(1,k));\n\t\t\t\t\t}\n\n\t\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  1);\n\n\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta(1,0));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), 8);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(8, 8);\n\t\t\tEigen::SparseMatrix<double> AtPB(8, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t\tstd::cout << it.value() << std::endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tif(h_x.size() == 8){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(rectangle.pose);\n\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\tpose.ka += h_x[counter++];\n\t\t\t\trectangle.pose = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\trectangle.scale_x += h_x[counter++];\n\t\t\t\trectangle.scale_y += h_x[counter++];\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'r':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tTaitBryanPose pose_rand;\n\t\t\tpose_rand.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tpose_rand.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tpose_rand.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tpose_rand.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tpose_rand.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tpose_rand.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\trectangle.pose = rectangle.pose * affine_matrix_from_pose_tait_bryan(pose_rand);\n\n\n\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(rectangle.pose);\n\n\t\t\tfor(size_t i = 0; i < bundle_of_rays.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < bundle_of_rays[i].size(); j++){\n\t\t\t\t\tEigen::Vector3d vx(bundle_of_rays[i][j](0,0), bundle_of_rays[i][j](1,0), bundle_of_rays[i][j](2,0));\n\t\t\t\t\tEigen::Vector3d vy(bundle_of_rays[i][j](0,1), bundle_of_rays[i][j](1,1), bundle_of_rays[i][j](2,1));\n\n\t\t\t\t\tEigen::Matrix<double, 2, 1> delta;\n\t\t\t\t\trectangular_object_with_unknown_width_height_rodrigues_wc(delta,\n\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.sx, pose.sy, pose.sz,\n\t\t\t\t\t\t\trectangle.corners_local[i].x(), rectangle.corners_local[i].y(), rectangle.corners_local[i].z(),\n\t\t\t\t\t\t\tbundle_of_rays[i][j](0,3), bundle_of_rays[i][j](1,3), bundle_of_rays[i][j](2,3),\n\t\t\t\t\t\t\tvx.x(), vx.y(), vx.z(), vy.x(), vy.y(), vy.z(),\n\t\t\t\t\t\t\trectangle.scale_x, rectangle.scale_y);\n\n\t\t\t\t\tEigen::Matrix<double, 2, 8> delta_jacobian;\n\t\t\t\t\trectangular_object_with_unknown_width_height_rodrigues_wc_jacobian(delta_jacobian,\n\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.sx, pose.sy, pose.sz,\n\t\t\t\t\t\t\trectangle.corners_local[i].x(), rectangle.corners_local[i].y(), rectangle.corners_local[i].z(),\n\t\t\t\t\t\t\tbundle_of_rays[i][j](0,3), bundle_of_rays[i][j](1,3), bundle_of_rays[i][j](2,3),\n\t\t\t\t\t\t\tvx.x(), vx.y(), vx.z(), vy.x(), vy.y(), vy.z(),\n\t\t\t\t\t\t\trectangle.scale_x, rectangle.scale_y);\n\n\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\tfor(size_t k = 0 ; k < 8; k++){\n\t\t\t\t\t\ttripletListA.emplace_back(ir, k, -delta_jacobian(0,k));\n\t\t\t\t\t}\n\t\t\t\t\tfor(size_t k = 0 ; k < 8; k++){\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1, k, -delta_jacobian(1,k));\n\t\t\t\t\t}\n\n\t\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  1);\n\n\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta(1,0));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), 8);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(8, 8);\n\t\t\tEigen::SparseMatrix<double> AtPB(8, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t\tstd::cout << it.value() << std::endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tif(h_x.size() == 8){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(rectangle.pose);\n\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\tpose.sx += h_x[counter++];\n\t\t\t\tpose.sy += h_x[counter++];\n\t\t\t\tpose.sz += h_x[counter++];\n\t\t\t\trectangle.pose = affine_matrix_from_pose_rodrigues(pose);\n\t\t\t\trectangle.scale_x += h_x[counter++];\n\t\t\t\trectangle.scale_y += h_x[counter++];\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'q':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tTaitBryanPose pose_rand;\n\t\t\tpose_rand.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tpose_rand.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tpose_rand.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tpose_rand.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tpose_rand.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\tpose_rand.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.000001;\n\t\t\trectangle.pose = rectangle.pose * affine_matrix_from_pose_tait_bryan(pose_rand);\n\n\n\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(rectangle.pose);\n\n\t\t\tfor(size_t i = 0; i < bundle_of_rays.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < bundle_of_rays[i].size(); j++){\n\t\t\t\t\tEigen::Vector3d vx(bundle_of_rays[i][j](0,0), bundle_of_rays[i][j](1,0), bundle_of_rays[i][j](2,0));\n\t\t\t\t\tEigen::Vector3d vy(bundle_of_rays[i][j](0,1), bundle_of_rays[i][j](1,1), bundle_of_rays[i][j](2,1));\n\n\t\t\t\t\tEigen::Matrix<double, 2, 1> delta;\n\t\t\t\t\trectangular_object_with_unknown_width_height_quaternion_wc(delta,\n\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.q0, pose.q1, pose.q2, pose.q3,\n\t\t\t\t\t\t\trectangle.corners_local[i].x(), rectangle.corners_local[i].y(), rectangle.corners_local[i].z(),\n\t\t\t\t\t\t\tbundle_of_rays[i][j](0,3), bundle_of_rays[i][j](1,3), bundle_of_rays[i][j](2,3),\n\t\t\t\t\t\t\tvx.x(), vx.y(), vx.z(), vy.x(), vy.y(), vy.z(),\n\t\t\t\t\t\t\trectangle.scale_x, rectangle.scale_y);\n\n\t\t\t\t\tEigen::Matrix<double, 2, 9> delta_jacobian;\n\t\t\t\t\trectangular_object_with_unknown_width_height_quaternion_wc_jacobian(delta_jacobian,\n\t\t\t\t\t\t\tpose.px, pose.py, pose.pz, pose.q0, pose.q1, pose.q2, pose.q3,\n\t\t\t\t\t\t\trectangle.corners_local[i].x(), rectangle.corners_local[i].y(), rectangle.corners_local[i].z(),\n\t\t\t\t\t\t\tbundle_of_rays[i][j](0,3), bundle_of_rays[i][j](1,3), bundle_of_rays[i][j](2,3),\n\t\t\t\t\t\t\tvx.x(), vx.y(), vx.z(), vy.x(), vy.y(), vy.z(),\n\t\t\t\t\t\t\trectangle.scale_x, rectangle.scale_y);\n\n\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\tfor(size_t k = 0 ; k < 9; k++){\n\t\t\t\t\t\ttripletListA.emplace_back(ir, k, -delta_jacobian(0,k));\n\t\t\t\t\t}\n\t\t\t\t\tfor(size_t k = 0 ; k < 9; k++){\n\t\t\t\t\t\ttripletListA.emplace_back(ir + 1, k, -delta_jacobian(1,k));\n\t\t\t\t\t}\n\n\t\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  1);\n\n\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta(1,0));\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tint ir = tripletListB.size();\n\n\t\t\tdouble delta;\n\t\t\tquaternion_constraint(delta, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\tEigen::Matrix<double, 1, 4> jacobian;\n\t\t\tquaternion_constraint_jacobian(jacobian, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\ttripletListA.emplace_back(ir, 3 , -jacobian(0,0));\n\t\t\ttripletListA.emplace_back(ir, 4 , -jacobian(0,1));\n\t\t\ttripletListA.emplace_back(ir, 5 , -jacobian(0,2));\n\t\t\ttripletListA.emplace_back(ir, 6 , -jacobian(0,3));\n\n\t\t\ttripletListP.emplace_back(ir, ir, 1000000.0);\n\n\t\t\ttripletListB.emplace_back(ir, 0, delta);\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), 9);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(9, 9);\n\t\t\tEigen::SparseMatrix<double> AtPB(9, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t\tstd::cout << it.value() << std::endl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tif(h_x.size() == 9){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(rectangle.pose);\n\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\tpose.q0 += h_x[counter++];\n\t\t\t\tpose.q1 += h_x[counter++];\n\t\t\t\tpose.q2 += h_x[counter++];\n\t\t\t\tpose.q3 += h_x[counter++];\n\t\t\t\trectangle.pose = affine_matrix_from_pose_quaternion(pose);\n\t\t\t\trectangle.scale_x += h_x[counter++];\n\t\t\t\trectangle.scale_y += h_x[counter++];\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'n':{\n\t\t\tfor(size_t i = 0; i < bundle_of_rays.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < bundle_of_rays[i].size(); j++){\n\t\t\t\t\tTaitBryanPose pose;\n\n\t\t\t\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.05;\n\t\t\t\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.05;\n\t\t\t\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 0.05;\n\n\t\t\t\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\t\t\t\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\t\t\t\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\n\t\t\t\t\tbundle_of_rays[i][j] = bundle_of_rays[i][j] * affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t}\n\t\t\tTaitBryanPose pose;\n\n\t\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 5;\n\t\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 5;\n\t\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 5;\n\n\t\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\t\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\t\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 2;\n\n\t\t\trectangle.pose = rectangle.pose * affine_matrix_from_pose_tait_bryan(pose);\n\n\t\t\trectangle.scale_x += ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 5;\n\t\t\trectangle.scale_y += ((float(rand()%1000000))/1000000.0f - 0.5) * 2.0 * 5;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"n: modify rays\" << std::endl;\n\tstd::cout << \"t: optimize (Tait-Bryan)\" << std::endl;\n\tstd::cout << \"r: optimize (Rodrigues)\" << std::endl;\n\tstd::cout << \"q: optimize (Quaternion)\" << std::endl;\n}\n", "meta": {"hexsha": "c1e5e83ad7d3d98eed557b79e97aa9ba34638c29", "size": 22579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/rectangular_object_with_unknown_width_height.cpp", "max_stars_repo_name": "michalpelka/observation_equations", "max_stars_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codes/c++Examples/src/rectangular_object_with_unknown_width_height.cpp", "max_issues_repo_name": "michalpelka/observation_equations", "max_issues_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/c++Examples/src/rectangular_object_with_unknown_width_height.cpp", "max_forks_repo_name": "michalpelka/observation_equations", "max_forks_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4192073171, "max_line_length": 156, "alphanum_fraction": 0.6357677488, "num_tokens": 7875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4140484931784741}}
{"text": "/*\n * This file belongs to the Galois project, a C++ library for exploiting parallelism.\n * The code is being released under the terms of the 3-Clause BSD License (a\n * copy is located in LICENSE.txt at the top-level directory).\n *\n * Copyright (C) 2018, The University of Texas at Austin. All rights reserved.\n * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS\n * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF\n * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF\n * DEALING OR USAGE OF TRADE.  NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH\n * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances\n * shall University be liable for incidental, special, indirect, direct or\n * consequential damages or loss of profits, interruption of business, or\n * related expenses which may arise from use of Software or Documentation,\n * including but not limited to those resulting from defects in Software and/or\n * Documentation, or loss or inaccuracy of data of any kind.\n */\n\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <ostream>\n#include \"matrixCompletion.h\"\n#include \"galois/runtime/TiledExecutor.h\"\n#include \"galois/ParallelSTL.h\"\n#include \"galois/graphs/Graph.h\"\n#include \"Lonestar/BoilerPlate.h\"\n\n#ifdef HAS_EIGEN\n#include <Eigen/Sparse>\n#include <Eigen/Dense>\n#endif\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\nstatic const char* const name = \"Matrix Completion\";\nstatic const char* const desc =\n    \"Computes Matrix Decomposition using Stochastic \"\n    \"Gradient Descent or Alternating Least Squares\";\nstatic const char* const url = 0;\n\nenum Algo {\n  syncALS,\n  simpleALS,\n  sgdByItems,\n  sgdByEdges,\n  sgdBlockEdge,\n  sgdBlockJump,\n};\n\nenum Step { bold, bottou, intel, inverse, purdue };\n\n/*\n * Commandline options for different Algorithms\n */\nstatic cll::opt<Algo>\n    algo(\"algo\", cll::desc(\"Choose an algorithm:\"),\n         cll::values(\n             clEnumValN(Algo::syncALS, \"syncALS\", \"Alternating least squares\"),\n             clEnumValN(Algo::simpleALS, \"simpleALS\",\n                        \"Simple alternating least squares\"),\n             clEnumValN(Algo::sgdBlockEdge, \"sgdBlockEdge\",\n                        \"SGD Edge blocking (default)\"),\n             clEnumValN(Algo::sgdBlockJump, \"sgdBlockJump\",\n                        \"SGD using Block jumping \"),\n             clEnumValN(Algo::sgdByItems, \"sgdByItems\", \"Simple SGD on Items\"),\n             clEnumValN(Algo::sgdByEdges, \"sgdByEdges\", \"Simple SGD on edges\"),\n             clEnumValEnd),\n         cll::init(Algo::sgdBlockEdge));\n/*\n * Commandline options for different learning functions\n */\nstatic cll::opt<Step> learningRateFunction(\n    \"learningRateFunction\", cll::desc(\"Choose learning rate function:\"),\n    cll::values(clEnumValN(Step::intel, \"intel\", \"Intel\"),\n                clEnumValN(Step::purdue, \"purdue\", \"Purdue\"),\n                clEnumValN(Step::bottou, \"bottou\", \"Bottou\"),\n                clEnumValN(Step::bold, \"bold\", \"Bold (default)\"),\n                clEnumValN(Step::inverse, \"inverse\", \"Inverse\"), clEnumValEnd),\n    cll::init(Step::bold));\n\nstatic cll::opt<int> cutoff(\"cutoff\");\n\nstatic const unsigned ALS_CHUNK_SIZE = 4;\n\nsize_t NUM_ITEM_NODES = 0;\n\nstruct PurdueStepFunction : public StepFunction {\n  virtual std::string name() const { return \"Purdue\"; }\n  virtual LatentValue stepSize(int round) const {\n    return learningRate * 1.5 / (1.0 + decayRate * pow(round + 1, 1.5));\n  }\n};\n\nstruct IntelStepFunction : public StepFunction {\n  virtual std::string name() const { return \"Intel\"; }\n  virtual LatentValue stepSize(int round) const {\n    return learningRate * pow(decayRate, round);\n  }\n};\n\nstruct BottouStepFunction : public StepFunction {\n  virtual std::string name() const { return \"Bottou\"; }\n  virtual LatentValue stepSize(int round) const {\n    return learningRate / (1.0 + learningRate * lambda * round);\n  }\n};\n\nstruct InverseStepFunction : public StepFunction {\n  virtual std::string name() const { return \"Inverse\"; }\n  virtual LatentValue stepSize(int round) const { return 1.0 / (round + 1); }\n};\n\nstruct BoldStepFunction : public StepFunction {\n  virtual std::string name() const { return \"Bold\"; }\n  virtual bool isBold() const { return true; }\n  virtual LatentValue stepSize(int round) const { return 0.0; }\n};\n\ntemplate <typename Graph>\ndouble sumSquaredError(Graph& g) {\n  typedef typename Graph::GraphNode GNode;\n  // computing Root Mean Square Error\n  // Assuming only item nodes have edges\n  galois::GAccumulator<double> error;\n\n  galois::do_all(\n      galois::iterate(g.begin(), g.begin() + NUM_ITEM_NODES), [&](GNode n) {\n        for (auto ii = g.edge_begin(n), ei = g.edge_end(n); ii != ei; ++ii) {\n          GNode dst = g.getEdgeDst(ii);\n          LatentValue e =\n              predictionError(g.getData(n).latentVector,\n                              g.getData(dst).latentVector, g.getEdgeData(ii));\n          error += (e * e);\n        }\n      });\n  return error.reduce();\n}\n\ntemplate <typename Graph>\nsize_t countEdges(Graph& g) {\n  typedef typename Graph::GraphNode GNode;\n  galois::GAccumulator<size_t> edges;\n  galois::runtime::Fixed2DGraphTiledExecutor<Graph> executor(g);\n  std::cout << \"NUM_ITEM_NODES : \" << NUM_ITEM_NODES << \"\\n\";\n  executor.execute(g.begin(), g.begin() + NUM_ITEM_NODES,\n                   g.begin() + NUM_ITEM_NODES, g.end(), itemsPerBlock,\n                   usersPerBlock,\n                   [&](GNode src, GNode dst,\n                       typename Graph::edge_iterator edge) { edges += 1; },\n                   false); // false = no locks\n  return edges.reduce();\n}\n\ntemplate <typename Graph>\nvoid verify(Graph& g, const std::string& prefix) {\n  std::cout << countEdges(g) << \" : \" << g.sizeEdges() << \"\\n\";\n  if (countEdges(g) != g.sizeEdges()) {\n    GALOIS_DIE(\"Error: edge list of input graph probably not sorted\");\n  }\n\n  double error = sumSquaredError(g);\n  double rmse  = std::sqrt(error / g.sizeEdges());\n\n  std::cout << prefix << \"RMSE: \" << rmse << \"\\n\";\n}\n\ntemplate <typename T, unsigned Size>\nstruct ExplicitFiniteChecker {};\n\ntemplate <typename T>\nstruct ExplicitFiniteChecker<T, 4U> {\n  static_assert(std::numeric_limits<T>::is_iec559, \"Need IEEE floating point\");\n  bool isFinite(T v) {\n    union {\n      T value;\n      uint32_t bits;\n    } a = {v};\n    if (a.bits == 0x7F800000) {\n      return false; // +inf\n    } else if (a.bits == 0xFF800000) {\n      return false; // -inf\n    } else if (a.bits >= 0x7F800001 && a.bits <= 0x7FBFFFFF) {\n      return false; // signaling NaN\n    } else if (a.bits >= 0xFF800001 && a.bits <= 0xFFBFFFFF) {\n      return false; // signaling NaN\n    } else if (a.bits >= 0x7FC00000 && a.bits <= 0x7FFFFFFF) {\n      return false; // quiet NaN\n    } else if (a.bits >= 0xFFC00000 && a.bits <= 0xFFFFFFFF) {\n      return false; // quiet NaN\n    }\n    return true;\n  }\n};\n\ntemplate <typename T>\nstruct ExplicitFiniteChecker<T, 8U> {\n  static_assert(std::numeric_limits<T>::is_iec559, \"Need IEEE floating point\");\n  bool isFinite(T v) {\n    union {\n      T value;\n      uint64_t bits;\n    } a = {v};\n    if (a.bits == 0x7FF0000000000000) {\n      return false; // +inf\n    } else if (a.bits == 0xFFF0000000000000) {\n      return false; // -inf\n    } else if (a.bits >= 0x7FF0000000000001 && a.bits <= 0x7FF7FFFFFFFFFFFF) {\n      return false; // signaling NaN\n    } else if (a.bits >= 0xFFF0000000000001 && a.bits <= 0xFFF7FFFFFFFFFFFF) {\n      return false; // signaling NaN\n    } else if (a.bits >= 0x7FF8000000000000 && a.bits <= 0x7FFFFFFFFFFFFFFF) {\n      return false; // quiet NaN\n    } else if (a.bits >= 0xFFF8000000000000 && a.bits <= 0xFFFFFFFFFFFFFFFF) {\n      return false; // quiet NaN\n    }\n    return true;\n  }\n};\n\ntemplate <typename T>\nbool isFinite(T v) {\n#ifdef __FAST_MATH__\n  return ExplicitFiniteChecker<T, sizeof(T)>().isFinite(v);\n#else\n  return std::isfinite(v);\n#endif\n}\n\ndouble countFlops(size_t nnz, int rounds, int k) {\n  double flop = 0;\n  if (useExactError) {\n    // dotProduct = 2K, square = 1, sum = 1\n    flop += nnz * (2.0 * k + 1 + 1);\n  } else {\n    // Computed during gradient update: square = 1, sum = 1\n    flop += nnz * (1 + 1);\n  }\n  // dotProduct = 2K, gradient = 10K,\n  flop += rounds * (nnz * (12.0 * k));\n  return flop;\n}\n\n/*\n * Common function to execute different algorithms\n * till convergence.\n *\n * @param StepFunction to be used\n * @param Graph\n * @param fn (algorithm)\n *\n */\ntemplate <typename Graph, typename Fn>\nvoid executeUntilConverged(const StepFunction& sf, Graph& g, Fn fn) {\n  galois::GAccumulator<double> errorAccum;\n  std::vector<LatentValue> steps(updatesPerEdge);\n  LatentValue last    = -1.0;\n  unsigned deltaRound = updatesPerEdge;\n  LatentValue rate    = learningRate;\n\n  galois::StatTimer executeAlgoTimer(\"Algorithm Execution Time\");\n  galois::TimeAccumulator elapsed;\n  elapsed.start();\n\n  unsigned long lastTime = 0;\n\n  for (unsigned int round = 0;; round += deltaRound) {\n    if (fixedRounds > 0 && round >= fixedRounds)\n      break;\n    if (fixedRounds > 0)\n      deltaRound = std::min(deltaRound, fixedRounds - round);\n\n    for (unsigned i = 0; i < updatesPerEdge; ++i) {\n      // Assume that loss decreases\n      if (sf.isBold())\n        steps[i] = i == 0 ? rate : steps[i - 1] * 1.05;\n      else\n        steps[i] = sf.stepSize(round + i);\n    }\n\n    executeAlgoTimer.start();\n    fn(&steps[0], round + deltaRound, useExactError ? &errorAccum : NULL);\n    executeAlgoTimer.stop();\n    double error = useExactError ? errorAccum.reduce() : sumSquaredError(g);\n\n    elapsed.stop();\n\n    unsigned long curElapsed = elapsed.get();\n    elapsed.start();\n    unsigned long millis = curElapsed - lastTime;\n    lastTime             = curElapsed;\n\n    double gflops = countFlops(g.sizeEdges(), deltaRound, LATENT_VECTOR_SIZE) /\n                    millis / 1e6;\n\n    int curRound = round + deltaRound;\n    galois::gPrint(\"R: \", curRound, \" elapsed (ms): \", curElapsed,\n                   \" GFLOP/s: \", gflops);\n    if (useExactError) {\n      galois::gPrint(\" RMSE (R \", curRound,\n                     \"): \", std::sqrt(error / g.sizeEdges()), \"\\n\");\n    } else {\n      galois::gPrint(\" Approx. RMSE (R \", (curRound - 1),\n                     \".5): \", std::sqrt(std::abs(error / g.sizeEdges())), \"\\n\");\n    }\n\n    galois::gPrint(\"Error Change : \", std::abs((last - error) / last), \"\\n\");\n    if (!isFinite(error))\n      break;\n    if (fixedRounds <= 0 &&\n        (round >= maxUpdates || std::abs((last - error) / last) < tolerance))\n      break;\n    if (sf.isBold()) {\n      // Assume that loss decreases first round\n      if (last >= 0.0 && last < error)\n        rate = steps[deltaRound - 1] * 0.5;\n      else\n        rate = steps[deltaRound - 1] * 1.05;\n    }\n    last = error;\n  }\n}\n\n/*\n * Divides the Items and users into 2D blocks.\n * Locks each block to work on it.\n */\nstruct SGDBlockJumpAlgo {\n  bool isSgd() const { return true; }\n  typedef galois::substrate::PaddedLock<true> SpinLock;\n  static const bool precomputeOffsets = true; // false;\n\n  std::string name() const { return \"sgdBlockJumpAlgo\"; }\n\n  struct Node {\n    LatentValue latentVector[LATENT_VECTOR_SIZE];\n  };\n\n  typedef galois::graphs::LC_CSR_Graph<Node, EdgeType>\n      //    ::with_numa_alloc<true>::type\n      ::with_no_lockable<true>::type Graph;\n  typedef Graph::GraphNode GNode;\n\n  void readGraph(Graph& g) { galois::graphs::readGraph(g, inputFilename); }\n\n  size_t userIdToUserNode(size_t userId) { return userId + NUM_ITEM_NODES; }\n\n  struct BlockInfo {\n    size_t id;\n    size_t x;\n    size_t y;\n    size_t userStart;\n    size_t userEnd;\n    size_t itemStart;\n    size_t itemEnd;\n    size_t numitems;\n    size_t updates;\n    double error;\n    int* userOffsets;\n\n    std::ostream& print(std::ostream& os) {\n      os << \"id: \" << id << \" x: \" << x << \" y: \" << y\n         << \" userStart: \" << userStart << \" userEnd: \" << userEnd\n         << \" itemStart: \" << itemStart << \" itemEnd: \" << itemEnd\n         << \" updates: \" << updates << \"\\n\";\n      return os;\n    }\n  };\n\n  struct Process {\n    Graph& g;\n    SpinLock *xLocks, *yLocks;\n    BlockInfo* blocks;\n    size_t numXBlocks, numYBlocks;\n    LatentValue* steps;\n    size_t maxUpdates;\n    galois::GAccumulator<double>* errorAccum;\n\n    struct GetDst : public std::unary_function<Graph::edge_iterator, GNode> {\n      Graph* g;\n      GetDst() {}\n      GetDst(Graph* _g) : g(_g) {}\n      GNode operator()(Graph::edge_iterator ii) const {\n        return g->getEdgeDst(ii);\n      }\n    };\n\n    /**\n     * Preconditions: row and column of slice are locked.\n     *\n     * Postconditions: increments update count, does sgd update on each item\n     * and user in the slice\n     */\n    template <bool Enable = precomputeOffsets>\n    size_t runBlock(BlockInfo& si,\n                    typename std::enable_if<!Enable>::type* = 0) {\n      typedef galois::NoDerefIterator<Graph::edge_iterator> no_deref_iterator;\n      typedef boost::transform_iterator<GetDst, no_deref_iterator>\n          edge_dst_iterator;\n\n      LatentValue stepSize = steps[si.updates - maxUpdates + updatesPerEdge];\n      size_t seen          = 0;\n      double error         = 0.0;\n\n      // Set up item iterators\n      size_t itemId      = 0;\n      Graph::iterator mm = g.begin(), em = g.begin();\n      std::advance(mm, si.itemStart);\n      std::advance(em, si.itemEnd);\n\n      GetDst fn{&g};\n\n      // For each item in the range\n      for (; mm != em; ++mm, ++itemId) {\n        GNode item      = *mm;\n        Node& itemData  = g.getData(item);\n        size_t lastUser = si.userEnd + NUM_ITEM_NODES;\n\n        edge_dst_iterator start(no_deref_iterator(g.edge_begin(\n                                    item, galois::MethodFlag::UNPROTECTED)),\n                                fn);\n        edge_dst_iterator end(no_deref_iterator(g.edge_end(\n                                  item, galois::MethodFlag::UNPROTECTED)),\n                              fn);\n\n        // For each edge in the range\n        for (auto ii =\n                 std::lower_bound(start, end, si.userStart + NUM_ITEM_NODES);\n             ii != end; ++ii) {\n          GNode user = g.getEdgeDst(*ii.base());\n\n          if (user >= lastUser)\n            break;\n\n          LatentValue e = doGradientUpdate(itemData.latentVector,\n                                           g.getData(user).latentVector, lambda,\n                                           g.getEdgeData(*ii.base()), stepSize);\n          if (errorAccum)\n            error += e * e;\n          ++seen;\n        }\n      }\n\n      si.updates += 1;\n      if (errorAccum) {\n        *errorAccum += (error - si.error);\n        si.error = error;\n      }\n\n      return seen;\n    }\n\n    template <bool Enable = precomputeOffsets>\n    size_t runBlock(BlockInfo& si, typename std::enable_if<Enable>::type* = 0) {\n      LatentValue stepSize = steps[si.updates - maxUpdates + updatesPerEdge];\n      size_t seen          = 0;\n      double error         = 0.0;\n\n      // Set up item iterators\n      size_t itemId      = 0;\n      Graph::iterator mm = g.begin(), em = g.begin();\n      std::advance(mm, si.itemStart);\n      std::advance(em, si.itemEnd);\n\n      // For each item in the range\n      for (; mm != em; ++mm, ++itemId) {\n        if (si.userOffsets[itemId] < 0)\n          continue;\n\n        GNode item      = *mm;\n        Node& itemData  = g.getData(item);\n        size_t lastUser = si.userEnd + NUM_ITEM_NODES;\n\n        // For each edge in the range\n        for (auto ii = g.edge_begin(item) + si.userOffsets[itemId],\n                  ei = g.edge_end(item);\n             ii != ei; ++ii) {\n          GNode user = g.getEdgeDst(ii);\n\n          if (user >= lastUser)\n            break;\n\n          LatentValue e = doGradientUpdate(itemData.latentVector,\n                                           g.getData(user).latentVector, lambda,\n                                           g.getEdgeData(ii), stepSize);\n          if (errorAccum)\n            error += e * e;\n          ++seen;\n        }\n      }\n\n      si.updates += 1;\n      if (errorAccum) {\n        *errorAccum += (error - si.error);\n        si.error = error;\n      }\n\n      return seen;\n    }\n\n    /**\n     * Searches next slice to work on.\n     *\n     * @returns slice id to work on, x and y locks are held on the slice\n     */\n    size_t getNextBlock(BlockInfo* sp) {\n      size_t numBlocks   = numXBlocks * numYBlocks;\n      size_t nextBlockId = sp->id + 1;\n      for (size_t i = 0; i < 2 * numBlocks; ++i, ++nextBlockId) {\n        // Wrap around\n        if (nextBlockId == numBlocks)\n          nextBlockId = 0;\n\n        BlockInfo& nextBlock = blocks[nextBlockId];\n\n        if (nextBlock.updates < maxUpdates && xLocks[nextBlock.x].try_lock()) {\n          if (yLocks[nextBlock.y].try_lock()) {\n            // Return while holding locks\n            return nextBlockId;\n          } else {\n            xLocks[nextBlock.x].unlock();\n          }\n        }\n      }\n\n      return numBlocks;\n    }\n\n    void operator()(unsigned tid, unsigned total) {\n      galois::StatTimer timer(\"PerThreadTime\");\n      // TODO: Report Accumulators at the end\n      galois::GAccumulator<size_t> edgesVisited;\n      galois::GAccumulator<size_t> blocksVisited;\n      size_t numBlocks = numXBlocks * numYBlocks;\n      size_t xBlock    = (numXBlocks + total - 1) / total;\n      size_t xStart    = std::min(xBlock * tid, numXBlocks - 1);\n      size_t yBlock    = (numYBlocks + total - 1) / total;\n      size_t yStart    = std::min(yBlock * tid, numYBlocks - 1);\n      BlockInfo* sp    = &blocks[xStart + yStart + numXBlocks];\n\n      timer.start();\n\n      while (true) {\n        sp = &blocks[getNextBlock(sp)];\n        if (sp == &blocks[numBlocks])\n          break;\n        blocksVisited += 1;\n        edgesVisited += runBlock(*sp);\n\n        xLocks[sp->x].unlock();\n        yLocks[sp->y].unlock();\n      }\n\n      timer.stop();\n    }\n  };\n\n  void operator()(Graph& g, const StepFunction& sf) {\n    galois::StatTimer preProcessTimer(\"PreProcessingTime\");\n    preProcessTimer.start();\n    const size_t numUsers = g.size() - NUM_ITEM_NODES;\n    const size_t numYBlocks =\n        (NUM_ITEM_NODES + itemsPerBlock - 1) / itemsPerBlock;\n    const size_t numXBlocks = (numUsers + usersPerBlock - 1) / usersPerBlock;\n    const size_t numBlocks  = numXBlocks * numYBlocks;\n\n    SpinLock* xLocks = new SpinLock[numXBlocks];\n    SpinLock* yLocks = new SpinLock[numYBlocks];\n\n    std::cout << \"itemsPerBlock: \" << itemsPerBlock\n              << \" usersPerBlock: \" << usersPerBlock\n              << \" numBlocks: \" << numBlocks << \" numXBlocks: \" << numXBlocks\n              << \" numYBlocks: \" << numYBlocks << \"\\n\";\n\n    // Initialize\n    BlockInfo* blocks = new BlockInfo[numBlocks];\n    for (size_t i = 0; i < numBlocks; i++) {\n      BlockInfo& si = blocks[i];\n      si.id         = i;\n      si.x          = i % numXBlocks;\n      si.y          = i / numXBlocks;\n      si.updates    = 0;\n      si.error      = 0.0;\n      si.userStart  = si.x * usersPerBlock;\n      si.userEnd    = std::min((si.x + 1) * usersPerBlock, numUsers);\n      si.itemStart  = si.y * itemsPerBlock;\n      si.itemEnd    = std::min((si.y + 1) * itemsPerBlock, NUM_ITEM_NODES);\n      si.numitems   = si.itemEnd - si.itemStart;\n      if (precomputeOffsets) {\n        si.userOffsets = new int[si.numitems];\n      } else {\n        si.userOffsets = nullptr;\n      }\n    }\n\n    // Partition item edges in blocks to users according to range [userStart,\n    // userEnd)\n    if (precomputeOffsets) {\n      galois::do_all(galois::iterate(g.begin(), g.begin() + NUM_ITEM_NODES),\n                     [&](GNode item) {\n                       size_t sliceY = item / itemsPerBlock;\n                       BlockInfo* s  = &blocks[sliceY * numXBlocks];\n\n                       size_t pos = item - s->itemStart;\n                       auto ii = g.edge_begin(item), ei = g.edge_end(item);\n                       size_t offset = 0;\n                       for (size_t i = 0; i < numXBlocks; ++i, ++s) {\n                         size_t start = userIdToUserNode(s->userStart);\n                         size_t end   = userIdToUserNode(s->userEnd);\n\n                         if (ii != ei && g.getEdgeDst(ii) >= start &&\n                             g.getEdgeDst(ii) < end) {\n                           s->userOffsets[pos] = offset;\n                         } else {\n                           s->userOffsets[pos] = -1;\n                         }\n                         for (; ii != ei && g.getEdgeDst(ii) < end;\n                              ++ii, ++offset)\n                           ;\n                       }\n                     });\n    }\n    preProcessTimer.stop();\n\n    // galois::StatTimer executeTimer(\"Total Execution Time\");\n    galois::StatTimer executeTimer(\"Time\");\n    executeTimer.start();\n    executeUntilConverged(sf, g,\n                          [&](LatentValue* steps, size_t maxUpdates,\n                              galois::GAccumulator<double>* errorAccum) {\n                            Process fn{g,      xLocks,     yLocks,\n                                       blocks, numXBlocks, numYBlocks,\n                                       steps,  maxUpdates, errorAccum};\n                            galois::on_each(fn);\n                          });\n    executeTimer.stop();\n  }\n};\n\n/*\n * Simple SGD going over all the destination(users) for a given\n * source(Item)\n */\nclass SGDItemsAlgo {\n  static const bool makeSerializable = false;\n\n  struct BasicNode {\n    LatentValue latentVector[LATENT_VECTOR_SIZE];\n  };\n\n  using Node = BasicNode;\n\npublic:\n  bool isSgd() const { return true; }\n\n  typedef typename galois::graphs::LC_CSR_Graph<Node, EdgeType>\n      //::template with_numa_alloc<true>::type\n      ::template with_out_of_line_lockable<true>::type ::\n          template with_no_lockable<!makeSerializable>::type Graph;\n\n  void readGraph(Graph& g) { galois::graphs::readGraph(g, inputFilename); }\n\n  std::string name() const { return \"sgdItemsAlgo\"; }\n\n  size_t numItems() const { return NUM_ITEM_NODES; }\n\nprivate:\n  using GNode         = typename Graph::GraphNode;\n  using edge_iterator = typename Graph::edge_iterator;\n\n  struct Execute {\n    Graph& g;\n    galois::GAccumulator<unsigned>& edgesVisited;\n\n    void operator()(LatentValue* steps, int maxUpdates,\n                    galois::GAccumulator<double>* errorAccum) {\n\n      const LatentValue stepSize = steps[0];\n      galois::for_each(\n          galois::iterate(g.begin(), g.begin() + NUM_ITEM_NODES),\n          [&](GNode src, auto& ctx) {\n            for (auto ii : g.edges(src)) {\n\n              GNode dst         = g.getEdgeDst(ii);\n              LatentValue error = doGradientUpdate(\n                  g.getData(src, galois::MethodFlag::UNPROTECTED).latentVector,\n                  g.getData(dst).latentVector, lambda, g.getEdgeData(ii),\n                  stepSize);\n\n              edgesVisited += 1;\n              if (useExactError)\n                *errorAccum += error;\n            }\n          },\n          galois::wl<galois::worklists::PerSocketChunkFIFO<64>>(),\n          galois::no_pushes(), galois::loopname(\"sgdItemsAlgo\"));\n    }\n  };\n\npublic:\n  void operator()(Graph& g, const StepFunction& sf) {\n    verify(g, \"sgdItemsAlgo\");\n    galois::GAccumulator<unsigned> edgesVisited;\n\n    // galois::StatTimer executeTimer(\"Total Execution Time\");\n    galois::StatTimer executeTimer(\"Time\");\n    executeTimer.start();\n\n    Execute fn{g, edgesVisited};\n    executeUntilConverged(sf, g, fn);\n\n    executeTimer.stop();\n\n    galois::runtime::reportStat_Single(\"sgdItemsAlgo\", \"EdgesVisited\",\n                                       edgesVisited.reduce());\n  }\n};\n\n/**\n * Simple by-edge grouped by items (only one edge per item on the WL at any\n * time)\n */\nclass SGDEdgeItem {\n  static const bool makeSerializable = false;\n\n  struct BasicNode {\n    // latent vector to be learned.\n    LatentValue latentVector[LATENT_VECTOR_SIZE];\n    // if a item's update is interrupted, where to start when resuming.\n    unsigned int edge_offset;\n  };\n\n  using Node = BasicNode;\n\npublic:\n  bool isSgd() const { return true; }\n\n  typedef typename galois::graphs::LC_CSR_Graph<Node, EdgeType>\n      //::template with_numa_alloc<true>::type\n      ::template with_out_of_line_lockable<true>::type ::\n          template with_no_lockable<!makeSerializable>::type Graph;\n\n  void readGraph(Graph& g) { galois::graphs::readGraph(g, inputFilename); }\n\n  std::string name() const { return \"sgdEdgeItem\"; }\n\n  size_t numItems() const { return NUM_ITEM_NODES; }\n\nprivate:\n  using GNode         = typename Graph::GraphNode;\n  using edge_iterator = typename Graph::edge_iterator;\n\n  struct Execute {\n    Graph& g;\n    galois::GAccumulator<unsigned>& edgesVisited;\n    void operator()(LatentValue* steps, int maxUpdates,\n                    galois::GAccumulator<double>* errorAccum) {\n      const LatentValue stepSize = steps[0];\n      galois::for_each(\n          galois::iterate(g.begin(), g.begin() + NUM_ITEM_NODES),\n          [&](GNode src, auto& ctx) {\n            auto ii = g.edge_begin(src, galois::MethodFlag::UNPROTECTED);\n            auto ee = g.edge_end(src, galois::MethodFlag::UNPROTECTED);\n\n            if (ii == ee)\n              return;\n\n            // Do not need lock on the source node, since only one thread can\n            // work on a given src(item).\n            auto& srcData = g.getData(src, galois::MethodFlag::UNPROTECTED);\n            // Advance to the edge that has not been worked yet.\n            std::advance(ii, srcData.edge_offset);\n            // Take lock on the destination as multiple source may update the\n            // same destination.\n            auto& dstData = g.getData(g.getEdgeDst(ii));\n            LatentValue error =\n                doGradientUpdate(srcData.latentVector, dstData.latentVector,\n                                 lambda, g.getEdgeData(ii), stepSize);\n\n            ++srcData.edge_offset;\n            ++ii;\n\n            edgesVisited += 1;\n            if (useExactError)\n              *errorAccum += error;\n\n            if (ii == ee) {\n              // Finished the last edge.\n              // Start from the first edge.\n              srcData.edge_offset = 0;\n              return;\n            } else {\n              // More edges to work on, therefore push the current src\n              // to the worklist.\n              ctx.push(src);\n            }\n          },\n          galois::wl<galois::worklists::PerSocketChunkLIFO<8>>(),\n          galois::loopname(\"sgdEdgeItem\"));\n    }\n  };\n\npublic:\n  void operator()(Graph& g, const StepFunction& sf) {\n    verify(g, \"sgdEdgeItem\");\n    galois::GAccumulator<unsigned> edgesVisited;\n\n    // galois::StatTimer executeTimer(\"Total Execution Time\");\n    galois::StatTimer executeTimer(\"Time\");\n    executeTimer.start();\n\n    Execute fn{g, edgesVisited};\n    executeUntilConverged(sf, g, fn);\n\n    executeTimer.stop();\n\n    galois::runtime::reportStat_Single(\"sgdEdgeItem\", \"EdgesVisited\",\n                                       edgesVisited.reduce());\n  }\n};\n\n/*\n * Simple edge-wise operator\n * Use Fixed2DGraphTiledExecutor to divide Items and Users in to blocks.\n * Locks blocks (blocks may share Items or Users) to work on them.\n *\n */\nclass SGDBlockEdgeAlgo {\n  static const bool makeSerializable = false;\n\n  struct BasicNode {\n    LatentValue latentVector[LATENT_VECTOR_SIZE];\n  };\n\n  using Node = BasicNode;\n\npublic:\n  bool isSgd() const { return true; }\n\n  typedef typename galois::graphs::LC_CSR_Graph<Node, EdgeType>\n      //::template with_numa_alloc<true>::type\n      ::template with_out_of_line_lockable<true>::type ::\n          template with_no_lockable<!makeSerializable>::type Graph;\n\n  void readGraph(Graph& g) { galois::graphs::readGraph(g, inputFilename); }\n\n  std::string name() const { return \"sgdBlockEdge\"; }\n\n  size_t numItems() const { return NUM_ITEM_NODES; }\n\nprivate:\n  using GNode         = typename Graph::GraphNode;\n  using edge_iterator = typename Graph::edge_iterator;\n\n  struct Execute {\n    Graph& g;\n    galois::GAccumulator<unsigned>& edgesVisited;\n\n    void operator()(LatentValue* steps, int maxUpdates,\n                    galois::GAccumulator<double>* errorAccum) {\n      galois::runtime::Fixed2DGraphTiledExecutor<Graph> executor(g);\n      executor.execute(\n          g.begin(), g.begin() + NUM_ITEM_NODES, g.begin() + NUM_ITEM_NODES,\n          g.end(), itemsPerBlock, usersPerBlock,\n          [&](GNode src, GNode dst, edge_iterator edge) {\n            const LatentValue stepSize = steps[0];\n            LatentValue error          = doGradientUpdate(\n                g.getData(src).latentVector, g.getData(dst).latentVector,\n                lambda, g.getEdgeData(edge), stepSize);\n            edgesVisited += 1;\n            if (useExactError)\n              *errorAccum += error;\n          },\n          true // use locks\n      );\n    }\n  };\n\npublic:\n  void operator()(Graph& g, const StepFunction& sf) {\n    verify(g, \"sgdBlockEdgeAlgo\");\n    galois::GAccumulator<unsigned> edgesVisited;\n\n    // galois::StatTimer executeTimer(\"Total Execution Time\");\n    galois::StatTimer executeTimer(\"Time\");\n    executeTimer.start();\n\n    Execute fn{g, edgesVisited};\n    executeUntilConverged(sf, g, fn);\n\n    executeTimer.stop();\n\n    galois::runtime::reportStat_Single(\"sgdBlockEdgeAlgo\", \"EdgesVisited\",\n                                       edgesVisited.reduce());\n  }\n};\n\n/**\n * ALS algorithms\n */\n\n#ifdef HAS_EIGEN\n\nstruct SimpleALSalgo {\n  bool isSgd() const { return false; }\n  std::string name() const { return \"AlternatingLeastSquares\"; }\n  struct Node {\n    LatentValue latentVector[LATENT_VECTOR_SIZE];\n  };\n\n  typedef typename galois::graphs::LC_CSR_Graph<Node, EdgeType>::with_no_lockable<\n      true>::type Graph;\n  typedef Graph::GraphNode GNode;\n  // Column-major access\n  typedef Eigen::SparseMatrix<LatentValue> Sp;\n  typedef Eigen::Matrix<LatentValue, LATENT_VECTOR_SIZE, Eigen::Dynamic> MT;\n  typedef Eigen::Matrix<LatentValue, LATENT_VECTOR_SIZE, 1> V;\n  typedef Eigen::Map<V> MapV;\n\n  Sp A;\n  Sp AT;\n\n  void readGraph(Graph& g) { galois::graphs::readGraph(g, inputFilename); }\n\n  void copyToGraph(Graph& g, MT& WT, MT& HT) {\n    // Copy out\n    for (GNode n : g) {\n      LatentValue* ptr = &g.getData(n).latentVector[0];\n      MapV mapV{ptr};\n      if (n < NUM_ITEM_NODES) {\n        mapV = WT.col(n);\n      } else {\n        mapV = HT.col(n - NUM_ITEM_NODES);\n      }\n    }\n  }\n\n  void copyFromGraph(Graph& g, MT& WT, MT& HT) {\n    for (GNode n : g) {\n      LatentValue* ptr = &g.getData(n).latentVector[0];\n      MapV mapV{ptr};\n      if (n < NUM_ITEM_NODES) {\n        WT.col(n) = mapV;\n      } else {\n        HT.col(n - NUM_ITEM_NODES) = mapV;\n      }\n    }\n  }\n\n  void initializeA(Graph& g) {\n    typedef Eigen::Triplet<int> Triplet;\n    std::vector<Triplet> triplets{g.sizeEdges()};\n    auto it = triplets.begin();\n    for (auto n : g) {\n      for (auto edge : g.out_edges(n)) {\n        *it++ = Triplet(n, g.getEdgeDst(edge) - NUM_ITEM_NODES,\n                        g.getEdgeData(edge));\n      }\n    }\n    A.resize(NUM_ITEM_NODES, g.size() - NUM_ITEM_NODES);\n    A.setFromTriplets(triplets.begin(), triplets.end());\n    AT = A.transpose();\n  }\n\n  void operator()(Graph& g, const StepFunction&) {\n    galois::TimeAccumulator elapsed;\n    elapsed.start();\n\n    // Find W, H that minimize ||W H^T - A||_2^2 by solving alternating least\n    // squares problems:\n    //   (W^T W + lambda I) H^T = W^T A (solving for H^T)\n    //   (H^T H + lambda I) W^T = H^T A^T (solving for W^T)\n    MT WT{LATENT_VECTOR_SIZE, NUM_ITEM_NODES};\n    MT HT{LATENT_VECTOR_SIZE, g.size() - NUM_ITEM_NODES};\n    typedef Eigen::Matrix<LatentValue, LATENT_VECTOR_SIZE, LATENT_VECTOR_SIZE>\n        XTX;\n    typedef Eigen::Matrix<LatentValue, LATENT_VECTOR_SIZE, Eigen::Dynamic> XTSp;\n    typedef galois::substrate::PerThreadStorage<XTX> PerThrdXTX;\n\n    galois::gPrint(\"ALS::Start initializeA\\n\");\n    initializeA(g);\n    galois::gPrint(\"ALS::End initializeA\\n\");\n    galois::gPrint(\"ALS::Start copyFromGraph\\n\");\n    copyFromGraph(g, WT, HT);\n    galois::gPrint(\"ALS::End copyFromGraph\\n\");\n\n    double last = -1.0;\n    galois::StatTimer mmTime(\"MMTime\");\n    galois::StatTimer update1Time(\"UpdateTime1\");\n    galois::StatTimer update2Time(\"UpdateTime2\");\n    galois::StatTimer copyTime(\"CopyTime\");\n    galois::StatTimer totalExecTime(\"totalExecTime\");\n    galois::StatTimer totalAlgoTime(\"Time\");\n    PerThrdXTX xtxs;\n\n    totalAlgoTime.start();\n    for (unsigned round = 1;; ++round) {\n      totalExecTime.start();\n      mmTime.start();\n      // TODO parallelize this using tiled executor\n      XTSp WTA = WT * A;\n      mmTime.stop();\n\n      update1Time.start();\n      // TODO: Change to Do_all, pass ints to iterator\n      galois::for_each(\n          galois::iterate(boost::counting_iterator<int>(0),\n                          boost::counting_iterator<int>(A.outerSize())),\n          [&](int col, galois::UserContext<int>&) {\n            // Compute WTW = W^T * W for sparse A\n            XTX& WTW = *xtxs.getLocal();\n            WTW.setConstant(0);\n            for (Sp::InnerIterator it(A, col); it; ++it)\n              WTW.triangularView<Eigen::Upper>() +=\n                  WT.col(it.row()) * WT.col(it.row()).transpose();\n            for (int i = 0; i < LATENT_VECTOR_SIZE; ++i)\n              WTW(i, i) += lambda;\n            HT.col(col) =\n                WTW.selfadjointView<Eigen::Upper>().llt().solve(WTA.col(col));\n          });\n      update1Time.stop();\n\n      mmTime.start();\n      XTSp HTAT = HT * AT;\n      mmTime.stop();\n\n      update2Time.start();\n      galois::for_each(\n          galois::iterate(boost::counting_iterator<int>(0),\n                          boost::counting_iterator<int>(AT.outerSize())),\n          [&](int col, galois::UserContext<int>&) {\n            // Compute HTH = H^T * H for sparse A\n            XTX& HTH = *xtxs.getLocal();\n            HTH.setConstant(0);\n            for (Sp::InnerIterator it(AT, col); it; ++it)\n              HTH.triangularView<Eigen::Upper>() +=\n                  HT.col(it.row()) * HT.col(it.row()).transpose();\n            for (int i = 0; i < LATENT_VECTOR_SIZE; ++i)\n              HTH(i, i) += lambda;\n            WT.col(col) =\n                HTH.selfadjointView<Eigen::Upper>().llt().solve(HTAT.col(col));\n          });\n      update2Time.stop();\n\n      copyTime.start();\n      copyToGraph(g, WT, HT);\n      copyTime.stop();\n      totalExecTime.stop();\n\n      double error = sumSquaredError(g);\n      elapsed.stop();\n      std::cout << \"R: \" << round << \" elapsed (ms): \" << elapsed.get()\n                << \" RMSE (R \" << round\n                << \"): \" << std::sqrt(error / g.sizeEdges()) << \"\\n\";\n      elapsed.start();\n\n      if (fixedRounds <= 0 && round > 1 &&\n          std::abs((last - error) / last) < tolerance)\n        break;\n      if (fixedRounds > 0 && round >= fixedRounds)\n        break;\n\n      last = error;\n    }\n    totalAlgoTime.stop();\n  }\n};\n\nstruct SyncALSalgo {\n\n  bool isSgd() const { return false; }\n\n  std::string name() const { return \"SynchronousAlternatingLeastSquares\"; }\n\n  struct Node {\n    LatentValue latentVector[LATENT_VECTOR_SIZE];\n  };\n\n  static const bool NEEDS_LOCKS = false;\n  typedef typename galois::graphs::LC_CSR_Graph<Node, EdgeType> BaseGraph;\n  typedef typename std::conditional<\n      NEEDS_LOCKS,\n      typename BaseGraph::template with_out_of_line_lockable<true>::type,\n      typename BaseGraph::template with_no_lockable<true>::type>::type Graph;\n  typedef typename Graph::GraphNode GNode;\n  // Column-major access\n  typedef Eigen::SparseMatrix<LatentValue> Sp;\n  typedef Eigen::Matrix<LatentValue, LATENT_VECTOR_SIZE, Eigen::Dynamic> MT;\n  typedef Eigen::Matrix<LatentValue, LATENT_VECTOR_SIZE, 1> V;\n  typedef Eigen::Map<V> MapV;\n  typedef Eigen::Matrix<LatentValue, LATENT_VECTOR_SIZE, LATENT_VECTOR_SIZE>\n      XTX;\n  typedef Eigen::Matrix<LatentValue, LATENT_VECTOR_SIZE, Eigen::Dynamic> XTSp;\n\n  typedef galois::substrate::PerThreadStorage<XTX> PerThrdXTX;\n  typedef galois::substrate::PerThreadStorage<V> PerThrdV;\n\n  Sp A;\n  Sp AT;\n\n  void readGraph(Graph& g) { galois::graphs::readGraph(g, inputFilename); }\n\n  void copyToGraph(Graph& g, MT& WT, MT& HT) {\n    // Copy out\n    for (GNode n : g) {\n      LatentValue* ptr = &g.getData(n).latentVector[0];\n      MapV mapV{ptr};\n      if (n < NUM_ITEM_NODES) {\n        mapV = WT.col(n);\n      } else {\n        mapV = HT.col(n - NUM_ITEM_NODES);\n      }\n    }\n  }\n\n  void copyFromGraph(Graph& g, MT& WT, MT& HT) {\n    for (GNode n : g) {\n      LatentValue* ptr = &g.getData(n).latentVector[0];\n      MapV mapV{ptr};\n      if (n < NUM_ITEM_NODES) {\n        WT.col(n) = mapV;\n      } else {\n        HT.col(n - NUM_ITEM_NODES) = mapV;\n      }\n    }\n  }\n\n  void initializeA(Graph& g) {\n    typedef Eigen::Triplet<int> Triplet;\n    std::vector<Triplet> triplets{g.sizeEdges()};\n    auto it = triplets.begin();\n    for (auto n : g) {\n      for (auto edge : g.out_edges(n)) {\n        *it++ = Triplet(n, g.getEdgeDst(edge) - NUM_ITEM_NODES,\n                        g.getEdgeData(edge));\n      }\n    }\n    A.resize(NUM_ITEM_NODES, g.size() - NUM_ITEM_NODES);\n    A.setFromTriplets(triplets.begin(), triplets.end());\n    AT = A.transpose();\n  }\n\n  void update(Graph& g, size_t col, MT& WT, MT& HT, PerThrdXTX& xtxs,\n              PerThrdV& rhs) {\n    // Compute WTW = W^T * W for sparse A\n    V& r = *rhs.getLocal();\n    if (col < NUM_ITEM_NODES) {\n      r.setConstant(0);\n      // HTAT = HT * AT; r = HTAT.col(col)\n      for (Sp::InnerIterator it(AT, col); it; ++it)\n        r += it.value() * HT.col(it.row());\n      XTX& HTH = *xtxs.getLocal();\n      HTH.setConstant(0);\n      for (Sp::InnerIterator it(AT, col); it; ++it)\n        HTH.triangularView<Eigen::Upper>() +=\n            HT.col(it.row()) * HT.col(it.row()).transpose();\n      for (int i = 0; i < LATENT_VECTOR_SIZE; ++i)\n        HTH(i, i) += lambda;\n      WT.col(col) = HTH.selfadjointView<Eigen::Upper>().llt().solve(r);\n    } else {\n      col = col - NUM_ITEM_NODES;\n      r.setConstant(0);\n      // WTA = WT * A; x = WTA.col(col)\n      for (Sp::InnerIterator it(A, col); it; ++it)\n        r += it.value() * WT.col(it.row());\n      XTX& WTW = *xtxs.getLocal();\n      WTW.setConstant(0);\n      for (Sp::InnerIterator it(A, col); it; ++it)\n        WTW.triangularView<Eigen::Upper>() +=\n            WT.col(it.row()) * WT.col(it.row()).transpose();\n      for (int i = 0; i < LATENT_VECTOR_SIZE; ++i)\n        WTW(i, i) += lambda;\n      HT.col(col) = WTW.selfadjointView<Eigen::Upper>().llt().solve(r);\n    }\n  }\n\n  struct NonDetTraits {\n    typedef std::tuple<> base_function_traits;\n  };\n\n  struct Process {\n    struct LocalState {\n      LocalState(Process&, galois::PerIterAllocTy&) {}\n    };\n\n    struct DeterministicId {\n      uintptr_t operator()(size_t x) const { return x; }\n    };\n\n    typedef std::tuple<galois::per_iter_alloc, galois::intent_to_read,\n                       galois::local_state<LocalState>,\n                       galois::det_id<DeterministicId>>\n        ikdg_function_traits;\n    typedef std::tuple<galois::per_iter_alloc, galois::fixed_neighborhood,\n                       galois::local_state<LocalState>,\n                       galois::det_id<DeterministicId>>\n        add_remove_function_traits;\n    typedef std::tuple<> nondet_function_traits;\n\n    SyncALSalgo& self;\n    Graph& g;\n    MT& WT;\n    MT& HT;\n    PerThrdXTX& xtxs;\n    PerThrdV& rhs;\n\n    Process(SyncALSalgo& self, Graph& g, MT& WT, MT& HT, PerThrdXTX& xtxs,\n            PerThrdV& rhs)\n        : self(self), g(g), WT(WT), HT(HT), xtxs(xtxs), rhs(rhs) {}\n\n    void operator()(size_t col, galois::UserContext<size_t>& ctx) {\n      self.update(g, col, WT, HT, xtxs, rhs);\n    }\n  };\n\n  void operator()(Graph& g, const StepFunction&) {\n    if (!useSameLatentVector) {\n      galois::gWarn(\"Results are not deterministic with different numbers of \"\n                    \"threads unless -useSameLatentVector is true\");\n    }\n    galois::TimeAccumulator elapsed;\n    elapsed.start();\n\n    // Find W, H that minimize ||W H^T - A||_2^2 by solving alternating least\n    // squares problems:\n    //   (W^T W + lambda I) H^T = W^T A (solving for H^T)\n    //   (H^T H + lambda I) W^T = H^T A^T (solving for W^T)\n    MT WT{LATENT_VECTOR_SIZE, NUM_ITEM_NODES};\n    MT HT{LATENT_VECTOR_SIZE, g.size() - NUM_ITEM_NODES};\n\n    initializeA(g);\n    copyFromGraph(g, WT, HT);\n\n    double last = -1.0;\n    galois::StatTimer updateTime(\"UpdateTime\");\n    galois::StatTimer copyTime(\"CopyTime\");\n    galois::StatTimer totalExecTime(\"totalExecTime\");\n    galois::StatTimer totalAlgoTime(\"Time\");\n    PerThrdXTX xtxs;\n    PerThrdV rhs;\n\n    totalAlgoTime.start();\n    for (unsigned round = 1;; ++round) {\n\n      totalExecTime.start();\n      updateTime.start();\n\n      typedef galois::worklists::PerThreadChunkLIFO<ALS_CHUNK_SIZE> WL_ty;\n      galois::for_each(\n          galois::iterate(boost::counting_iterator<size_t>(0),\n                          boost::counting_iterator<size_t>(NUM_ITEM_NODES)),\n          Process(*this, g, WT, HT, xtxs, rhs), galois::wl<WL_ty>(),\n          galois::loopname(\"syncALS-users\"));\n      galois::for_each(\n          galois::iterate(boost::counting_iterator<size_t>(NUM_ITEM_NODES),\n                          boost::counting_iterator<size_t>(g.size())),\n          Process(*this, g, WT, HT, xtxs, rhs), galois::wl<WL_ty>(),\n          galois::loopname(\"syncALS-items\"));\n\n      updateTime.stop();\n\n      copyTime.start();\n      copyToGraph(g, WT, HT);\n      copyTime.stop();\n      totalExecTime.stop();\n\n      double error = sumSquaredError(g);\n      elapsed.stop();\n      std::cout << \"R: \" << round << \" elapsed (ms): \" << elapsed.get()\n                << \" RMSE (R \" << round\n                << \"): \" << std::sqrt(error / g.sizeEdges()) << \"\\n\";\n      elapsed.start();\n\n      if (fixedRounds <= 0 && round > 1 &&\n          std::abs((last - error) / last) < tolerance)\n        break;\n      if (fixedRounds > 0 && round >= fixedRounds)\n        break;\n\n      last = error;\n    } // end for\n    totalAlgoTime.stop();\n  }\n};\n\n#endif // HAS_EIGEN\n\n/**\n * Initializes latent vector with random values and returns basic graph\n * parameters.\n *\n * @tparam Graph type of g\n * @param g Graph to initialize\n * @returns number of item nodes, i.e. nodes with outgoing edges. They should\n * be the first nodes of the graph in memory\n */\n\ntemplate <typename Graph>\nsize_t initializeGraphData(Graph& g) {\n  galois::gPrint(\"initializeGraphData\\n\");\n  galois::StatTimer initTimer(\"InitializeGraph\");\n  initTimer.start();\n  double top = 1.0 / std::sqrt(LATENT_VECTOR_SIZE);\n  galois::substrate::PerThreadStorage<std::mt19937> gen;\n\n#if __cplusplus >= 201103L || defined(HAVE_CXX11_UNIFORM_INT_DISTRIBUTION)\n  std::uniform_real_distribution<LatentValue> dist(0, top);\n#else\n  std::uniform_real<LatentValue> dist(0, top);\n#endif\n\n  if (useDetInit) {\n    galois::do_all(galois::iterate(g), [&](typename Graph::GraphNode n) {\n      auto& data = g.getData(n);\n      auto val   = genVal(n);\n      for (int i = 0; i < LATENT_VECTOR_SIZE; i++) {\n        data.latentVector[i] = val;\n      }\n    });\n  } else {\n    galois::do_all(galois::iterate(g), [&](typename Graph::GraphNode n) {\n      auto& data = g.getData(n);\n\n      // all threads initialize their assignment with same generator or\n      // a thread local one\n      if (useSameLatentVector) {\n        std::mt19937 sameGen;\n        for (int i = 0; i < LATENT_VECTOR_SIZE; i++) {\n          data.latentVector[i] = dist(sameGen);\n        }\n      } else {\n        for (int i = 0; i < LATENT_VECTOR_SIZE; i++) {\n          data.latentVector[i] = dist(*gen.getLocal());\n        }\n      }\n    });\n  }\n\n\n   auto activeThreads = galois::getActiveThreads();\n   std::vector<uint32_t> largestNodeID_perThread(activeThreads);\n\n    galois::on_each([&](unsigned tid, unsigned nthreads) {\n      unsigned int block_size = g.size() / nthreads;\n      if ((g.size() % nthreads) > 0)\n        ++block_size;\n\n      uint32_t start = tid * block_size;\n      uint32_t end   = (tid + 1) * block_size;\n      if (end > g.size())\n        end = g.size();\n\n      largestNodeID_perThread[tid] = 0;\n      for (uint32_t i = start; i < end; ++i) {\n        if(std::distance(g.edge_begin(i), g.edge_end(i))) {\n          if(largestNodeID_perThread[tid] < i)\n            largestNodeID_perThread[tid] = i;\n          }\n      }\n    });\n\n    uint32_t largestNodeID = 0;\n    for(uint32_t t = 0; t < activeThreads; ++t){\n      if(largestNodeID < largestNodeID_perThread[t])\n        largestNodeID = largestNodeID_perThread[t];\n    }\n    size_t numItemNodes = largestNodeID + 1;\n\n  initTimer.stop();\n  return numItemNodes;\n}\n\nStepFunction* newStepFunction() {\n  switch (learningRateFunction) {\n  case Step::intel:\n    return new IntelStepFunction;\n  case Step::purdue:\n    return new PurdueStepFunction;\n  case Step::bottou:\n    return new BottouStepFunction;\n  case Step::inverse:\n    return new InverseStepFunction;\n  case Step::bold:\n    return new BoldStepFunction;\n  default:\n    GALOIS_DIE(\"unknown step function\");\n  }\n}\n\ntemplate <typename Graph>\nvoid writeBinaryLatentVectors(Graph& g, const std::string& filename) {\n  std::ofstream file(filename);\n  for (auto ii = g.begin(), ei = g.end(); ii != ei; ++ii) {\n    auto& v = g.getData(*ii).latentVector;\n    for (int i = 0; i < LATENT_VECTOR_SIZE; ++i) {\n      file.write(reinterpret_cast<char*>(&v[i]), sizeof(v[i]));\n    }\n  }\n  file.close();\n}\n\ntemplate <typename Graph>\nvoid writeAsciiLatentVectors(Graph& g, const std::string& filename) {\n  std::ofstream file(filename);\n  for (auto ii = g.begin(), ei = g.end(); ii != ei; ++ii) {\n    auto& v = g.getData(*ii).latentVector;\n    for (int i = 0; i < LATENT_VECTOR_SIZE; ++i) {\n      file << v[i] << \" \";\n    }\n    file << \"\\n\";\n  }\n  file.close();\n}\n\n/**\n * Run the provided algorithm (provided through the template argument).\n *\n * @param Algo algorithm to run\n */\ntemplate <typename Algo>\nvoid run() {\n  typename Algo::Graph g;\n  Algo algo;\n\n  galois::runtime::reportNumaAlloc(\"NumaAlloc0\");\n\n  // Bipartite graph in general graph data structure should be following:\n  // * items are the first m nodes\n  // * users are the next n nodes\n  // * only items have outedges\n  algo.readGraph(g);\n\n  galois::runtime::reportNumaAlloc(\"NumaAlloc1\");\n\n  // initialize latent vectors and get number of item nodes\n  NUM_ITEM_NODES = initializeGraphData(g);\n\n  galois::runtime::reportNumaAlloc(\"NumaAlloc2\");\n\n  std::cout << \"num users: \" << g.size() - NUM_ITEM_NODES\n            << \" num items: \" << NUM_ITEM_NODES\n            << \" num ratings: \" << g.sizeEdges() << \"\\n\";\n\n  std::unique_ptr<StepFunction> sf{newStepFunction()};\n  std::cout << \"latent vector size: \" << LATENT_VECTOR_SIZE\n            << \" algo: \" << algo.name() << \" lambda: \" << lambda;\n\n  if (algo.isSgd()) {\n    std::cout << \" learning rate: \" << learningRate\n              << \" decay rate: \" << decayRate\n              << \" step function: \" << sf->name();\n  }\n\n  std::cout << \"\\n\";\n\n  if (!skipVerify) {\n    verify(g, \"Initial\");\n  }\n\n  // algorithm call\n  galois::StatTimer totalTimer(\"Total Time\");\n  totalTimer.start();\n  algo(g, *sf);\n  totalTimer.stop();\n\n  if (!skipVerify) {\n    verify(g, \"Final\");\n  }\n\n  if (outputFilename != \"\") {\n    std::cout << \"Writing latent vectors to \" << outputFilename << \"\\n\";\n    switch (outputType) {\n    case OutputType::binary:\n      writeBinaryLatentVectors(g, outputFilename);\n      break;\n    case OutputType::ascii:\n      writeAsciiLatentVectors(g, outputFilename);\n      break;\n    default:\n      GALOIS_DIE(\"Invalid output type for latent vector output\");\n    }\n  }\n\n  galois::runtime::reportNumaAlloc(\"NumaAlloc\");\n}\n\nint main(int argc, char** argv) {\n  galois::SharedMemSys G;\n  LonestarStart(argc, argv, name, desc, url);\n\n  switch (algo) {\n#ifdef HAS_EIGEN\n  case Algo::syncALS:\n    run<SyncALSalgo>();\n    break;\n  case Algo::simpleALS:\n    run<SimpleALSalgo>();\n    break;\n#endif\n  case Algo::sgdByItems:\n    run<SGDItemsAlgo>();\n    break;\n  case Algo::sgdByEdges:\n    run<SGDEdgeItem>();\n    break;\n  case Algo::sgdBlockEdge:\n    run<SGDBlockEdgeAlgo>();\n    break;\n  case Algo::sgdBlockJump:\n    run<SGDBlockJumpAlgo>();\n    break;\n  default:\n    GALOIS_DIE(\"unknown algorithm\");\n    break;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "c8e70e1de2d11c286d47c17c57a21fe355a580b6", "size": 48238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lonestar/matrixcompletion/matrixCompletion.cpp", "max_stars_repo_name": "rohankadekodi/compilers_project", "max_stars_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lonestar/matrixcompletion/matrixCompletion.cpp", "max_issues_repo_name": "rohankadekodi/compilers_project", "max_issues_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-26T22:09:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-26T22:09:49.000Z", "max_forks_repo_path": "lonestar/matrixcompletion/matrixCompletion.cpp", "max_forks_repo_name": "rohankadekodi/compilers_project", "max_forks_repo_head_hexsha": "2f9455a5d0c516b9f1766afd1cdac1b86c930ec0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-26T14:46:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-09T11:32:09.000Z", "avg_line_length": 31.6938239159, "max_line_length": 85, "alphanum_fraction": 0.5951117376, "num_tokens": 13015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4140227770558919}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_SINHC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SINHC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-hyperbolic\n    Function object implementing sinhc capabilities\n\n    Returns hyperbolic cardinal sine: \\f$\\frac{\\sinh(x)}{x}\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type T\n\n    @code\n    T r = sinhc(x);\n    @endcode\n\n    is similar to:\n\n    @code\n    T r = sinh(x)/x;\n    @endcode\n\n    @see sinh\n\n  **/\n  const boost::dispatch::functor<tag::sinhc_> sinhc = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/sinhc.hpp>\n#include <boost/simd/function/simd/sinhc.hpp>\n\n#endif\n", "meta": {"hexsha": "0372e5506a804f04e97c92bc8c84cb71b584570c", "size": 1101, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/sinhc.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/function/sinhc.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/sinhc.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5882352941, "max_line_length": 100, "alphanum_fraction": 0.5676657584, "num_tokens": 256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4140227770558918}}
{"text": "#include <string.h>\n#include <math.h>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nextern \"C\" {\nvoid dsyevr_ (\n\tchar\t*jobz,\n\tchar\t*range,\n\tchar\t*uplo,\n\tint\t*n,\n\tdouble\t*a,\n\tint\t*lda,\n\tdouble\t*vl,\n\tdouble\t*vu,\n\tint\t*il,\n\tint\t*iu,\n\tdouble\t*abstol,\n\tint\t*m,\n\tdouble\t*w,\n\tdouble\t*z,\n\tint\t*ldz,\n\tint\t*isuppz,\n\tdouble\t*work,\n\tint\t*lwork,\n\tint\t*iwork,\n\tint\t*liwork,\n\tint\t*info\n);\n}\n\nusing namespace std;\n\ntemplate <class F> class Point;\n\ntemplate <class F> class PointBase {\npublic:\n\tvector<F>\tx;\n\n\n\ttemplate <class G> PointBase<F> & operator =(Point<G> const &);\n//\ttemplate <class G> PointBase<double> & operator =(PointBase<G> const &);\n\ttemplate <class G> PointBase<F> & operator +=(PointBase<G> const &);\n\n\tPointBase<F>(void) {}; \n\n\tPointBase<F>(int s) {\n\t\tx.resize(s); \n\t\tfor (int i=0; i<s; i++) x[i] = 0.;\n\t}\n\n\ttemplate <class G> PointBase<F>(PointBase<G> const & g) {\n\t\tfor (int i=0; i<g.x.size(); i++) x.push_back(g.x[i]);\n\t}\n\n\tPointBase<F> & operator *= (double d) {\n\t\tfor (int i=0; i<x.size(); i++) x[i] *= d;\n\t}\n\n\tF dotp(vector<F> const &v) const {\n\t\tF\tret = 0;\n\n\t\tfor (int i=0; i<x.size(); i++) ret += v[i]*x[i];\n\n\t\treturn\tret;\n\t}\n};\n\ntemplate <class F> template <class G> PointBase<F> & PointBase<F>::operator=(Point<G> const &f)\n{\n\tx = f.x;\n\n\treturn *this;\n}\n\ntemplate <class F> template <class G> PointBase<F> & PointBase<F>::operator +=(PointBase<G>  const & r)\n{\n\tfor (int i=0; i<x.size(); i++) x[i] += r.x[i];\n\treturn *this;\n}\n\ntemplate <class F> class Point: public PointBase<F> {\npublic:\n\tF\tchi2;\n\tvector<string>\ttypes;\n\n\tbool\tload(istream &);\n};\n\n\ntemplate <class F> bool Point<F>::load(istream & in)\n{\n\tchar\tline[BUFSIZ];\n\tthis->x.clear();\n\tstring\ts;\n\n#define CLUE\t\"    Function number\"\n\n\twhile (! in.getline(line,sizeof line).eof() && strlen(line) > 0 && strncmp(line,CLUE,sizeof(CLUE)-1)) ;\n\n\tstringstream\tparse(line);\n\n//    Function number   284    F =  1.0973091125D+00    \n\tparse >> s >> s >> s >> s >> s >> chi2;\n\n\twhile (! in.getline(line,sizeof line).eof() && strlen(line) > 0) {\n\n\t\tF\txx[5] = { FP_NAN, FP_NAN, FP_NAN, FP_NAN, FP_NAN };\n\n\t\tfor (int j=0; line[j]; j++) if (line[j] == 'D') line[j] = 'e';\n\t\tint n = sscanf(line,\"%f %f %f %f %f\",xx,xx+1,xx+2,xx+3,xx+4);\n\t\tfor (int j=0; j<n; j++) this->x.push_back(xx[j]);\n\t}\n\n\treturn !in.eof();\n}\n\nclass Select {\npublic:\n\tfloat\tchi2;\n\n\tSelect() {\n\t\tchi2\t= 1e38;\n\t}\n\n\tbool match(Point<float> const & p) const {\n\t\tif (p.chi2  > chi2) return false;\n\n\t\treturn true;\n\t}\n};\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\nint main(int argc, char ** argv)\n{\n\n\tpo::options_description desc(\"Options\");\n\tdesc.add_options()\n\t\t(\"help\", \"help message\")\n\t\t(\"chi2\", po::value<float>()->default_value(100000.0), \"select points for dimension reduction - smaller chi2 only\")\n\t\t(\"dim\", po::value<int>()->default_value(2), \"reduce to this number of dimensions\")\n\t\t(\"all\", \"map all points, not only those selected by chi2\")\n;\n\n\tpo::variables_map opt;\n\ttry { po::store(po::parse_command_line(argc, argv, desc), opt); }\n\tcatch (exception &e) {\n\t\tcerr << argv[0] << \": \" << e.what() << endl;\n\t\treturn 1;\n\t}\n\tpo::notify(opt);    \n\n\tif (opt.count(\"help\")) { cerr << desc; return 1; }\n\n\tSelect\tsel;\n\tsel.chi2 = opt[\"chi2\"].as<float>();\n\n\tint\tdimreduce = opt[\"dim\"].as<int>();\n\tbool allpoints = opt.count(\"all\");\n\n\tvector<Point<float> >\tpt;\n\tPoint<float>\t\tp;\n\n\twhile (p.load(cin)) {\n\t\tpt.push_back(p);\n\t\tif (pt.size() % 100 == 0) cerr << pt.size() << \" points read      \\r\" << flush;\n\t}\n\tcerr << pt.size() << \" points read      \" << endl;\n\n\n\tPointBase<double> sum(pt[0].x.size());\n\tvector<PointBase<float> > matched;\n\tlong nmatch = 0;\n\n\tfor (int i=0; i<pt.size(); i++) \n\t\tif (sel.match(pt[i])) {\n\t\t\tPointBase<float>\tpb = pt[i];\n\t\t\tmatched.push_back(pb);\n\t\t\tsum += pt[i];\n\t\t\tnmatch++;\n\t\t}\n\n\tcerr << nmatch << \" points match criteria\" << endl;\n\n\tPointBase<float> minusavg(sum);\n\tdouble invnmatch = 1. / nmatch;\n        minusavg *= - invnmatch;\n\n\tfor (int i=0; i<matched.size(); i++) matched[i] += minusavg;\n\n\tint\tnpar = pt[0].x.size(), npar2 = npar*npar;\n\tdouble *cov = new double[npar2]; // lower triangular\n\tvector<double>\tpar(npar);\n\t\n\tfor (int k=0; k<npar2; k++) cov[k] = 0.;\n\n\tfor (int n=0; n < nmatch; n++) {\n\t\tfor (int i=0; i<npar; i++) {\n\t\t\tpar[i] = matched[n].x[i];\n\t\t}\n\n\t\tfor (int i=0; i<npar; i++) {\n\t\t\tint\ticol = i*npar;\n\t\t\tfor (int j=i; j<npar; j++) cov[icol + j] += par[i] * par[j];\n\t\t}\n\t}\n\n\tfor (int k=0; k<npar2; k++) cov[k] *= invnmatch;\n\n\tdouble zero = 0., abstol = 0. ;\n\tint\tizero = 0,lwork = npar * 100;\n\tint\tm, *isuppz = new int[2*npar], info, liwork = 10*npar, *iwork = new int[liwork];\n\tdouble\t*w = new double[npar], *z = new double[npar2], *work = new double[lwork];\n\n\tdsyevr_(\"V\", // JOBZ\n\t\t\"A\", // RANGE\n\t\t\"L\", // UPLO\n\t\t&npar, // N\n\t\tcov, // A\n\t\t&npar, // LDA\n\t\t&zero, // VL\n\t\t&zero, // VU\n\t\t&izero, // IL\n\t\t&izero, // IU\n\t\t&abstol, \n\t\t&m, \n\t\tw,\n\t\tz,\n\t\t&npar, // LDZ\n\t\tisuppz,\n\t\twork,\n\t\t&lwork,\n\t\tiwork,\n\t\t&liwork,\n\t\t&info);\n\n\tcerr << \"dsyevr() = \" << info << endl;\n\tif (info) return 1;\n\n\tvector<float>\tevnorm(npar);\n\tfloat\tevsum = 0, evcum = 0;\n\n\tcerr << \"raw eigenvalues: \" << endl;\n\tfor (int i=0; i<npar; i++) { cerr << w[i] << \" \"; evsum += w[i]; }\n\tcerr << endl;\n\n\tcerr << \"normalized reverse cummulative: \" << endl;\n\tfor (int i=0; i<npar; i++) {\n\t\tevnorm[i] = w[npar-i-1] / evsum;\n\t\tevcum += evnorm[i];\n\t\tcerr << evcum << \" \";\n\t}\n\tcerr << endl;\n\n\tvector<vector<float> > evec(dimreduce);\n\n\tfor (int i=0; i<dimreduce; i++) {\n\t\tevec[i].resize(npar);\n\t\tint\ticol = (npar-i-1) * npar;\n\t\tfloat\tdotp = 0, norm = 0.;\n\t\tfor (int j=0; j<npar; j++) {\n\t\t\tfloat\te = evec[i][j] = z[icol+j];\n\t\t\tnorm += e*e;\n\t\t}\n\t\tnorm = 1./sqrt(norm)/sqrt(1.*npar);;\n\n\t\tcerr << \"eigenvector[\" << i << \"]:\" ;\n\t\tfor (int j=0; j<npar; j++) {\n\t\t\tcerr << evec[i][j] * norm << \" \";\n\t\t\tdotp += evec[i][j] * norm;\n\t\t}\n\t\tcerr << endl << \"dotprod with diagonal: \" << dotp << endl;\n\t}\n\n\tfor (int i=0; i<pt.size(); i++) \n\t\tif (allpoints || sel.match(pt[i])) {\n\t\t\tfor (int j=0; j<dimreduce; j++) {\n\t\t\t\tcout << pt[i].dotp(evec[j]) << \", \";\n\t\t\t}\n\t\t\tcout << pt[i].chi2;\n\t\t\tcout << endl;\n\t\t}\n\n\n\tdelete [] isuppz;\n\tdelete [] iwork;\n\tdelete [] w;\n\tdelete [] z;\n\tdelete [] work;\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "e8dc7b302baba6fdd48b02e7665affde0838d85f", "size": 6199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "saxs-ensemble-fit/core/bobyqa-logreduce.cpp", "max_stars_repo_name": "spirit01/ensemble-fit_docker_version", "max_stars_repo_head_hexsha": "6396184c9bf311ac83c012f94ad293605a32798c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-23T17:12:44.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-23T17:12:44.000Z", "max_issues_repo_path": "saxs-ensemble-fit/core/bobyqa-logreduce.cpp", "max_issues_repo_name": "spirit01/ensemble-fit_docker_version", "max_issues_repo_head_hexsha": "6396184c9bf311ac83c012f94ad293605a32798c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "saxs-ensemble-fit/core/bobyqa-logreduce.cpp", "max_forks_repo_name": "spirit01/ensemble-fit_docker_version", "max_forks_repo_head_hexsha": "6396184c9bf311ac83c012f94ad293605a32798c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6633333333, "max_line_length": 116, "alphanum_fraction": 0.569930634, "num_tokens": 2189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4140227699544498}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2019-2020, LAAS-CNRS, University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef CROCODDYL_CORE_COST_BASE_HPP_\n#define CROCODDYL_CORE_COST_BASE_HPP_\n\n#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\n\n#include \"crocoddyl/core/fwd.hpp\"\n#include \"crocoddyl/core/state-base.hpp\"\n#include \"crocoddyl/core/data-collector-base.hpp\"\n#include \"crocoddyl/core/activation-base.hpp\"\n#include \"crocoddyl/core/activations/quadratic.hpp\"\n\nnamespace crocoddyl {\n\n/**\n * @brief Abstract class for cost models\n *\n * In Crocoddyl, a cost model is defined by the scalar activation function \\f$a(\\cdot)\\f$ and by the residual function\n * \\f$\\mathbf{r}(\\cdot)\\f$ as follows: \\f[ cost = a(\\mathbf{r}(\\mathbf{x}, \\mathbf{u})), \\f] where\n * the residual function depends on the state point \\f$\\mathbf{x}\\in\\mathcal{X}\\f$, which lies in the state manifold\n * described with a `nq`-tuple, its velocity \\f$\\dot{\\mathbf{x}}\\in T_{\\mathbf{x}}\\mathcal{X}\\f$ that belongs to\n * the tangent space with `nv` dimension, and the control input \\f$\\mathbf{u}\\in\\mathbb{R}^{nu}\\f$. The residual vector\n * is defined by \\f$\\mathbf{r}\\in\\mathbb{R}^{nr}\\f$ where `nr` describes its dimension in the Euclidean space. On the\n * other hand, the activation function builds a cost value based on the definition of the residual vector. The residual\n * vector has to be specialized in a derived classes.\n *\n * The main computations are carring out in `calc` and `calcDiff` routines. `calc` computes the cost (and its residual)\n * and `calcDiff` computes the derivatives of the cost function (and its residual). Concretely speaking, `calcDiff`\n * builds a linear-quadratic approximation of the cost function with the form: \\f$\\mathbf{l_x}\\in\\mathbb{R}^{ndx}\\f$,\n * \\f$\\mathbf{l_u}\\in\\mathbb{R}^{nu}\\f$, \\f$\\mathbf{l_{xx}}\\in\\mathbb{R}^{ndx\\times ndx}\\f$,\n * \\f$\\mathbf{l_{xu}}\\in\\mathbb{R}^{ndx\\times nu}\\f$, \\f$\\mathbf{l_{uu}}\\in\\mathbb{R}^{nu\\times nu}\\f$ are the\n * Jacobians and Hessians, respectively.\n * Additionally, it is important remark that `calcDiff()` computes the derivates using the latest stored values by\n * `calc()`. Thus, we need to run first `calc()`.\n *\n * \\sa `StateAbstractTpl`, `ActivationModelAbstractTpl`, `calc()`, `calcDiff()`, `createData()`\n */\ntemplate <typename _Scalar>\nclass CostModelAbstractTpl {\n public:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef CostDataAbstractTpl<Scalar> CostDataAbstract;\n  typedef StateAbstractTpl<Scalar> StateAbstract;\n  typedef ActivationModelAbstractTpl<Scalar> ActivationModelAbstract;\n  typedef ActivationModelQuadTpl<Scalar> ActivationModelQuad;\n  typedef DataCollectorAbstractTpl<Scalar> DataCollectorAbstract;\n  typedef typename MathBase::VectorXs VectorXs;\n  typedef typename MathBase::MatrixXs MatrixXs;\n\n  /**\n   * @brief Initialize the cost model\n   *\n   * @param[in] state       State of the multibody system\n   * @param[in] activation  Activation model\n   * @param[in] nu          Dimension of control vector\n   */\n  CostModelAbstractTpl(boost::shared_ptr<StateAbstract> state, boost::shared_ptr<ActivationModelAbstract> activation,\n                       const std::size_t nu);\n\n  /**\n   * @copybrief CostModelAbstractTpl()\n   *\n   * The default `nu` value is obtained from `StateAbstractTpl::get_nv()`.\n   *\n   * @param[in] state       State of the multibody system\n   * @param[in] activation  Activation model\n   */\n  CostModelAbstractTpl(boost::shared_ptr<StateAbstract> state, boost::shared_ptr<ActivationModelAbstract> activation);\n\n  /**\n   * @copybrief CostModelAbstractTpl()\n   *\n   * We use `ActivationModelQuadTpl` as a default activation model (i.e. \\f$a=\\frac{1}{2}\\|\\mathbf{r}\\|^2\\f$)\n   *\n   * @param[in] state  State of the multibody system\n   * @param[in] nr     Dimension of residual vector\n   * @param[in] nu     Dimension of control vector\n   */\n  CostModelAbstractTpl(boost::shared_ptr<StateAbstract> state, const std::size_t nr, const std::size_t nu);\n\n  /**\n   * @copybrief CostModelAbstractTpl()\n   *\n   * We use `ActivationModelQuadTpl` as a default activation model (i.e. \\f$a=\\frac{1}{2}\\|\\mathbf{r}\\|^2\\f$).\n   * Furthermore, the default `nu` value is obtained from `StateAbstractTpl::get_nv()`.\n   *\n   * @param[in] state  State of the multibody system\n   * @param[in] nr     Dimension of residual vector\n   * @param[in] nu     Dimension of control vector\n   */\n  CostModelAbstractTpl(boost::shared_ptr<StateAbstract> state, const std::size_t nr);\n  virtual ~CostModelAbstractTpl();\n\n  /**\n   * @brief Compute the cost value and its residual vector\n   *\n   * @param[in] data  Cost data\n   * @param[in] x     State point \\f$\\mathbf{x}\\in\\mathbb{R}^{ndx}\\f$\n   * @param[in] u     Control input \\f$\\mathbf{u}\\in\\mathbb{R}^{nu}\\f$\n   */\n  virtual void calc(const boost::shared_ptr<CostDataAbstract>& data, const Eigen::Ref<const VectorXs>& x,\n                    const Eigen::Ref<const VectorXs>& u) = 0;\n\n  /**\n   * @brief Compute the Jacobian and Hessian of cost and its residual vector\n   *\n   * It computes the Jacobian and Hessian of the cost function. It assumes that `calc()` has been run first.\n   *\n   * @param[in] data  Cost data\n   * @param[in] x     State point \\f$\\mathbf{x}\\in\\mathbb{R}^{ndx}\\f$\n   * @param[in] u     Control input \\f$\\mathbf{u}\\in\\mathbb{R}^{nu}\\f$\n   */\n  virtual void calcDiff(const boost::shared_ptr<CostDataAbstract>& data, const Eigen::Ref<const VectorXs>& x,\n                        const Eigen::Ref<const VectorXs>& u) = 0;\n\n  /**\n   * @brief Create the cost data\n   *\n   * The default data contains objects to store the values of the cost, residual vector and their derivatives (first\n   * and second order derivatives). However, it is possible to specialized this function is we need to create\n   * additional data, for instance, to avoid dynamic memory allocation.\n   *\n   * @param data  Data collector\n   * @return the cost data\n   */\n  virtual boost::shared_ptr<CostDataAbstract> createData(DataCollectorAbstract* const data);\n\n  /**\n   * @copybrief calc()\n   *\n   * @param[in] data  Cost data\n   * @param[in] x     State point\n   */\n  void calc(const boost::shared_ptr<CostDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  /**\n   * @copybrief calcDiff()\n   *\n   * @param[in] data  Cost data\n   * @param[in] x     State point\n   */\n  void calcDiff(const boost::shared_ptr<CostDataAbstract>& data, const Eigen::Ref<const VectorXs>& x);\n\n  /**\n   * @brief Return the state\n   */\n  const boost::shared_ptr<StateAbstract>& get_state() const;\n\n  /**\n   * @brief Return the activation model\n   */\n  const boost::shared_ptr<ActivationModelAbstract>& get_activation() const;\n\n  /**\n   * @brief Return the dimension of the control input\n   */\n  std::size_t get_nu() const;\n\n  /**\n   * @brief Modify the cost reference\n   */\n  template <class ReferenceType>\n  void set_reference(ReferenceType ref);\n\n  /**\n   * @brief Return the cost reference\n   */\n  template <class ReferenceType>\n  ReferenceType get_reference() const;\n\n protected:\n  /**\n   * @copybrief set_reference()\n   */\n  virtual void set_referenceImpl(const std::type_info&, const void*);\n\n  /**\n   * @copybrief get_reference()\n   */\n  virtual void get_referenceImpl(const std::type_info&, void*) const;\n\n  boost::shared_ptr<StateAbstract> state_;                 //!< State description\n  boost::shared_ptr<ActivationModelAbstract> activation_;  //!< Activation model\n  std::size_t nu_;                                         //!< Control dimension\n  VectorXs unone_;                                         //!< No control vector\n};\n\ntemplate <typename _Scalar>\nstruct CostDataAbstractTpl {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef _Scalar Scalar;\n  typedef MathBaseTpl<Scalar> MathBase;\n  typedef ActivationDataAbstractTpl<Scalar> ActivationDataAbstract;\n  typedef DataCollectorAbstractTpl<Scalar> DataCollectorAbstract;\n  typedef typename MathBase::VectorXs VectorXs;\n  typedef typename MathBase::MatrixXs MatrixXs;\n\n  template <template <typename Scalar> class Model>\n  CostDataAbstractTpl(Model<Scalar>* const model, DataCollectorAbstract* const data)\n      : shared(data),\n        activation(model->get_activation()->createData()),\n        cost(Scalar(0.)),\n        Lx(model->get_state()->get_ndx()),\n        Lu(model->get_nu()),\n        Lxx(model->get_state()->get_ndx(), model->get_state()->get_ndx()),\n        Lxu(model->get_state()->get_ndx(), model->get_nu()),\n        Luu(model->get_nu(), model->get_nu()),\n        r(model->get_activation()->get_nr()),\n        Rx(model->get_activation()->get_nr(), model->get_state()->get_ndx()),\n        Ru(model->get_activation()->get_nr(), model->get_nu()) {\n    Lx.setZero();\n    Lu.setZero();\n    Lxx.setZero();\n    Lxu.setZero();\n    Luu.setZero();\n    r.setZero();\n    Rx.setZero();\n    Ru.setZero();\n  }\n  virtual ~CostDataAbstractTpl() {}\n\n  DataCollectorAbstract* shared;\n  boost::shared_ptr<ActivationDataAbstract> activation;\n  Scalar cost;\n  VectorXs Lx;\n  VectorXs Lu;\n  MatrixXs Lxx;\n  MatrixXs Lxu;\n  MatrixXs Luu;\n  VectorXs r;\n  MatrixXs Rx;\n  MatrixXs Ru;\n};\n\n}  // namespace crocoddyl\n\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n/* --- Details -------------------------------------------------------------- */\n#include \"crocoddyl/core/cost-base.hxx\"\n\n#endif  // CROCODDYL_CORE_COST_BASE_HPP_\n", "meta": {"hexsha": "0905ac5ab9e383e689d939691dd86c061814096c", "size": 9692, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crocoddyl/core/cost-base.hpp", "max_stars_repo_name": "wxmerkt/crocoddyl", "max_stars_repo_head_hexsha": "1463f5f214d1b47f95ee5f16b60ae8c421b7725c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crocoddyl/core/cost-base.hpp", "max_issues_repo_name": "wxmerkt/crocoddyl", "max_issues_repo_head_hexsha": "1463f5f214d1b47f95ee5f16b60ae8c421b7725c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crocoddyl/core/cost-base.hpp", "max_forks_repo_name": "wxmerkt/crocoddyl", "max_forks_repo_head_hexsha": "1463f5f214d1b47f95ee5f16b60ae8c421b7725c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0078431373, "max_line_length": 119, "alphanum_fraction": 0.6606479571, "num_tokens": 2518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.41402276995444975}}
{"text": "#include \"Tunneling1D.h\"\n#include <cmath>\n#include <iostream>\n// #include <gsl/gsl_errno.h>\n// #include <gsl/gsl_min.h>\n// #include <gsl/gsl_roots.h>\n#include \"GSL_Wraper.h\"\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/special_functions/bessel.hpp>\n\nusing namespace std;\nusing namespace boost::math;\n\n// typedef double (*root_func)(double,void*);\n// double find_root_gsl_wraper(root_func func, void *params, double x_max, double x_min)\n// {\n//     int status;\n//     int iter = 0, max_iter = 100;\n//     const gsl_root_fsolver_type *T = gsl_root_fsolver_brent;\n//     gsl_root_fsolver *s = gsl_root_fsolver_alloc(T);\n//     double r;\n//     double r_min = x_min;\n//     double r_max = x_max;\n\n//     gsl_function F;\n//     // struct param_initialConditions params = {this, phi0, dV0, d2V0, phi_absMin, delta_phi_cutoff};\n\n//     F.function = func;\n//     F.params = params;\n\n//     gsl_root_fsolver_set(s, &F, r_min, r_max);\n\n//     do\n//     {\n//         iter++;\n//         status = gsl_root_fsolver_iterate(s);\n//         r      = gsl_root_fsolver_root(s);\n//         r_min  = gsl_root_fsolver_x_lower(s);\n//         r_max  = gsl_root_fsolver_x_upper(s);\n//         status = gsl_root_test_interval(r_min,r_max,1e-8,1e-10);\n//     } while (status == GSL_CONTINUE && iter < max_iter);\n    \n//     gsl_root_fsolver_free(s);\n//     return r;\n// }\n\n// * function used by RungeKutta \nVD func_for_rkqc(double r, VD y, void *param)\n{\n    Tunneling1D *mod = (Tunneling1D*) param;\n    return mod->equationOfMotion(r,y);\n}\nTunneling1D::Tunneling1D(double absMin, double metaMin, ScalarFunction V_, dScalarFunction dV_, HM d2V_, double dim, double phi_eps_rel_)\n{\n    V = V_;\n    dV = dV_;\n    d2V = d2V_;\n\n    _rk_calculator.SetDOF(2);\n    _rk_calculator.SetODE(func_for_rkqc);\n    _rk_calculator.SetParams(this);\n\n    phi_absMin = absMin;\n    phi_metaMin = metaMin;\n    phi_bar = findBarrierLocation();\n    // cout<<\"Barrier at \"<<phi_bar<<endl;\n\n    rscale = findRScale();\n    // cout<<\"r-scale: \"<<rscale<<endl;\n\n    Spatial_Dim = dim;\n    alpha = dim-1;\n\n    phi_eps_rel = phi_eps_rel_;\n    phi_eps_abs = phi_eps_rel*abs(phi_absMin-phi_metaMin);\n}\nvoid Tunneling1D::SetMinima(double absMin, double metaMin)\n{\n    phi_absMin = absMin;\n    phi_metaMin = metaMin;\n}\nvoid Tunneling1D::SetPotential(ScalarFunction potential)\n{\n    V = potential;\n}\nvoid Tunneling1D::SetdPotential(dScalarFunction dpotential)\n{\n    dV = dpotential;\n}\nvoid Tunneling1D::SetHM(HM d2potential)\n{\n    d2V = d2potential;\n}\nvoid Tunneling1D::SetPhiAtBarrier(double phibar)\n{\n    phi_bar = phibar;\n}\nvoid Tunneling1D::SetSpatialDim(double dim)\n{\n    Spatial_Dim = dim;\n    alpha = Spatial_Dim - 1;\n}\nvoid Tunneling1D::SetPrecision(double eps_rel)\n{\n    phi_eps_rel = eps_rel;\n    // if (isnan(phi_absMin) || isnan(phi_metaMin))\n    // {\n    //     phi_eps_abs = NAN;\n    //     cout<<\"Please Set the Location of the Minimum First\"<<endl;\n    // }\n    // else\n    // {\n    //     phi_eps_abs = phi_eps_rel * abs(phi_absMin - phi_metaMin);\n    // }\n}\ndouble Tunneling1D::dV_from_absMin(double delta_phi)\n{\n    double phi = phi_absMin + delta_phi;\n    double T = 0;\n    double dV_f = dV({phi},&T)[0];\n\n    double dV_d = d2V({phi},&T)[0][0] * delta_phi;\n\n    double blend_factor = exp(-pow(delta_phi/phi_eps_abs,2));\n\n    return dV_f*(1-blend_factor) + dV_d*blend_factor;\n}\ndouble Tunneling1D::findBarrierLocation()\n{\n    double phi_tol = abs(phi_absMin-phi_metaMin)*1e-12;\n    double T = 0;\n    double V_meta = V({phi_metaMin},&T);\n    double phiH = phi_metaMin;\n    double phiL = phi_absMin;\n    double phiM = (phiH + phiL)/2;\n\n    double V0;\n    while (abs(phiH-phiL) > phi_tol)\n    {\n        V0 = V({phiM},&T);\n        if (V0 > V_meta)\n        {\n            phiH = phiM;\n        }\n        else\n        {\n            phiL = phiM;\n        }\n        phiM = (phiH + phiL)/2;\n    }\n    return phiM;\n}\ndouble func_for_findRScale(double x, void *params)\n{\n    Tunneling1D * mod = (Tunneling1D*)params;\n    return -mod->VvalatX(x);\n}\ndouble Tunneling1D::findRScale()\n{\n    if (std::isnan(phi_bar)) findBarrierLocation();\n    double phi_tol = abs(phi_bar - phi_metaMin)*1e-6;\n    double x1 = min(phi_bar,phi_metaMin);\n    double x2 = max(phi_bar,phi_metaMin);\n\n    double phi_bar_top = find_min_arg_gsl_wraper(func_for_findRScale,this,x2,x1,phi_tol);\n\n    if (phi_bar_top + phi_tol > x2 || phi_bar_top - phi_tol < x1)\n    {\n        cout<<\"In findRScale: No Barrier for the potential: can't find the top position.\"<<endl;\n    }\n    \n\n    double Vtop = VvalatX(phi_bar_top) - VvalatX(phi_metaMin);\n    double xtop = phi_bar_top - phi_metaMin;\n\n    if (Vtop <= 0)\n    {\n        cout<<\"In findRScale: No Barrier for the potential: non-positive barrier height.\"<<endl;\n    }\n    // This is the `time'-scale for a harmonic oscillation (Approximating the potential by a quadratic potential).\n    return abs(xtop)/sqrt(abs(2*Vtop));\n}\ntuple<double, double> Tunneling1D::exactSolution(double r, double phi0, double dV_, double d2V_)\n{\n    // ! Find phi(r) (and dphi(r)) given phi(0) assuming a quadractic potential\n    double beta = sqrt(abs(d2V_));\n    double beta_r = beta*r;\n    double nu = (alpha - 1.0)/2.0;\n\n    double phi = 0;\n    double dphi = 0;\n    double tmp;\n    if (beta_r < 1e-2)\n    {\n        // Using the expansion to approximate the Bessel function\n        double s = d2V_>0?1:-1;\n        for (int k = 1; k < 4; k++)\n        {\n            tmp = pow(beta_r/2,2*k-2)*pow(s,k)/(tgamma((k+1)*1.0)*tgamma(k+1+nu));\n            phi += tmp;\n            dphi += tmp*(2*k);\n        }\n        phi *= tgamma(nu+1)*r*r*dV_*s/4;\n        dphi *= tgamma(nu+1)*r*dV_*s/4;\n        phi += phi0;\n    }\n    else if (d2V_ > 0)\n    {\n        // cout<<\"beta_r: \"<<beta_r<<endl;\n        try\n        {\n            phi = (tgamma(nu+1)/pow(beta_r/2,nu)*cyl_bessel_i(nu,beta_r)-1)*dV_/d2V_;\n            dphi = -nu/r/pow(beta_r/2,nu)*cyl_bessel_i(nu,beta_r);\n            dphi += beta/2/pow(beta_r/2,nu)*(cyl_bessel_i(nu-1,beta_r)+cyl_bessel_i(nu+1,beta_r));\n            dphi *= tgamma(nu+1)*dV_/d2V_;\n            phi += phi0;\n        }\n        catch(const std::overflow_error& e)\n        {\n            // std::cerr << e.what() << '\\n';\n            // just ignore the overflow\n            phi = INFINITY;\n            dphi = INFINITY;\n        }\n    }\n    else\n    {\n        phi = (tgamma(nu+1)/pow(beta_r/2,nu)*cyl_bessel_j(nu,beta_r)-1)*dV_/d2V_;\n        dphi = -nu/r/pow(beta_r/2,nu)*cyl_bessel_j(nu,beta_r);\n        dphi += beta/2/pow(beta_r/2,nu)*(cyl_bessel_j(nu-1,beta_r)-cyl_bessel_j(nu+1,beta_r));\n        dphi *= tgamma(nu+1)*dV_/d2V_;\n        phi += phi0;\n    }\n    return make_tuple(phi,dphi);    \n}\nstruct param_initialConditions\n{\n    Tunneling1D *tun;\n    double phi0;\n    double dV0;\n    double d2V0;\n\n    double phi_absMin;\n    double delta_phi_cutoff;\n};\ndouble func_for_initialConditions(double r, void *params)\n{\n    param_initialConditions *mod = (param_initialConditions*)params;\n    double phi0 = mod->phi0;\n    double dV0 = mod->dV0;\n    double d2V0 = mod->d2V0;\n    double phi_absMin = mod->phi_absMin;\n    double delta_phi_cutoff = mod->delta_phi_cutoff;\n    double phir,dphir;\n    std::tie(phir,dphir) = (mod->tun)->exactSolution(r,phi0,dV0,d2V0);\n    return abs(phir - phi_absMin) - abs(delta_phi_cutoff);\n}\ntuple<double, double, double> Tunneling1D::initialConditions(double delta_phi0, double rmin, double delta_phi_cutoff)\n{\n    /* \n    * Find the initial conditions for the ODE integration.\n    * \n    * The instanton equations of motion are singular at `r=0`, \n    * so we need to start the integration at some larger radius. \n    * This function finds the value `r0` such that `phi(r0) = phi_cutoff`.\n    * If there is no such value, it returns the intial conditions at `rmin`.\n    */\n   \n    double T = 0;\n    double phi0 = phi_absMin + delta_phi0;\n    double dV0 = dV_from_absMin(delta_phi0);\n    double d2V0 = d2V({phi0},&T)[0][0];\n\n    double phi_rmin, dphi_rmin;\n    std::tie(phi_rmin, dphi_rmin) = exactSolution(rmin, phi0, dV0, d2V0);\n    if (abs(phi_rmin - phi_absMin) > abs(delta_phi_cutoff))\n    {\n        return make_tuple(rmin, phi_rmin, dphi_rmin);\n    }\n    if (sign(dphi_rmin) != sign(delta_phi0))\n    {\n        return make_tuple(rmin, phi_rmin, dphi_rmin);\n    }\n    \n    double r_cur = rmin;\n    double r_last = rmin;\n\n    double phi, dphi;\n    r_last = r_cur;\n    r_cur *= 10;\n    while (std::isfinite(r_cur))\n    {\n        std::tie(phi, dphi) = exactSolution(r_cur, phi0, dV0, d2V0);\n        if (!std::isfinite(phi))\n        {\n            r_cur = (r_last + r_cur)/2.0;\n            continue;\n        }\n        if (abs(phi - phi_absMin) > abs(delta_phi_cutoff))\n        {\n            break;\n        }\n        r_last = r_cur;\n        r_cur *= 10;\n    }\n    struct param_initialConditions params = {this, phi0, dV0, d2V0, phi_absMin, delta_phi_cutoff};\n    // cout<<\"Before root finding\"<<endl;\n    // cout<<\"r_cur=\"<<r_cur<<\" r_last=\"<<r_last<<endl;\n    double r = find_root_gsl_wraper(&func_for_initialConditions,&params,r_cur,r_last);\n    // cout<<\"After root finding\"<<endl;\n\n    std::tie(phi,dphi) = exactSolution(r,phi0,dV0,d2V0);\n    return make_tuple(r,phi,dphi);    \n}\nVD Tunneling1D::equationOfMotion(double r, VD y)\n{\n    VD res(2);\n    double T = 0;\n    res[0] = y[1];\n    res[1] = dV({y[0]},&T)[0]-alpha*y[1]/r;\n    return res;\n}\nstruct cubic_param\n{\n    double y0;\n    double dy0;\n    double y1;\n    double dy1;\n    double diff;\n};\n\ndouble cubicInterpolation(double x, void *param)\n{\n    cubic_param* mod = (cubic_param*)param;\n    double mt = 1-x;\n    double c3 = mod->y1;\n    double c2 = mod->y1 - mod->dy1/3.0;\n    double c1 = mod->y0 + mod->dy0/3.0;\n    double c0 = mod->y0;\n    return c0*pow(mt,3) + 3*c1*mt*mt*x + 3*c2*mt*x*x + c3*pow(x,3) - mod->diff;\n}\ntuple<double, VD, CONVERGENCETYPE> Tunneling1D::integrateProfile(double r0, VD y0, double dr0, double epsfrac, double epsabs, double drmin, double rmax)\n{\n    VD y_final_value = {phi_metaMin,0};\n    VD y_diff;\n    double dr_guess = dr0;\n    double dr_did,dr_next;\n    double r = r0;\n    VD y = y0;\n    VD dydr = equationOfMotion(r,y);\n    double r_cache;\n    VD y_cache;\n    VD dydr_cache;\n    VD y_scale;\n    VD y_inter(2);\n    int ysign = sign(y0[0]-phi_metaMin);\n    rmax += r0;\n\n    CONVERGENCETYPE convergQ = NONE;\n    cubic_param inter_param;\n    double x;\n    while (true)\n    {\n        y_scale = abs(y)+abs(dydr*dr_guess);\n        r_cache = r;\n        y_cache = y;\n        dydr_cache = dydr;\n        // cout<<\"\\t\\t----\"<<endl;\n        // cout<<\"\\t\\t\"<<r_cache<<\"  \"<<y_cache[0]<<\"  \"<<y_cache[1]<<\"  \"<<dydr_cache[0]<<\"  \"<<dydr_cache[1]<<\"  \"<<dr_guess<<\"  \"<<epsabs<<endl;\n        _rk_calculator._RKQC_SingleStep(r_cache,y_cache,dydr_cache,dr_guess,epsabs,y_scale,dr_did,dr_next);\n        dydr_cache = equationOfMotion(r_cache,y_cache);\n\n        y_diff = abs(y_cache-y_final_value);\n        // cout<<\"\\t\\t\"<<r_cache<<\"  \"<<y_cache[0]<<\"  \"<<y_cache[1]<<\"  \"<<ysign<<\"  \"<<dr_did<<\"  \"<<dr_next<<endl;\n        // cout<<\"\\t\\t\\t\"<<y_diff[0]<<\"/\"<<epsabs<<\"  \"<<y_diff[1]<<\"/\"<<epsabs<<endl;\n        if ( y_diff[0] < epsabs && y_diff[1] < epsabs)\n        {\n            r = r_cache;\n            y = y_cache;\n            convergQ = CONVERGED;\n            break;\n        }\n        \n        if (y_cache[1]*ysign > 0)\n        {\n            // This means the `ball` is heading back, so it will never reach the desired point.\n            convergQ = UNDERSHOOT;\n            inter_param = {y[1],dydr[1]*dr_did,y_cache[1],dydr_cache[1]*dr_did,0};\n            x = find_root_gsl_wraper(&cubicInterpolation,&inter_param,1,0);\n            r += dr_did*x;\n            y_inter[1] = cubicInterpolation(x,&inter_param);\n            inter_param = {y[0],dydr[0]*dr_did,y_cache[0],dydr_cache[0]*dr_did,0};\n            y_inter[0] = cubicInterpolation(x,&inter_param);\n            y = y_inter;\n            break;\n        }\n\n        if ((y_cache[0]-phi_metaMin)*ysign<0)\n        {\n            // Already passing the desired ending point\n            convergQ = OVERSHOOT;\n            inter_param = {y[0],dydr[0]*dr_did,y_cache[0],dydr_cache[0]*dr_did,phi_metaMin};\n            x = find_root_gsl_wraper(&cubicInterpolation,&inter_param,1,0);\n            r += dr_did*x;\n            inter_param = {y[1],dydr[1]*dr_did,y_cache[1],dydr_cache[1]*dr_did,0};\n            y_inter[1] = cubicInterpolation(x,&inter_param);\n            inter_param = {y[0],dydr[0]*dr_did,y_cache[0],dydr_cache[0]*dr_did,0};\n            y_inter[0] = cubicInterpolation(x,&inter_param);\n            y = y_inter;\n            break;\n        }\n\n        r = r_cache;\n        y = y_cache;\n        dydr = dydr_cache;\n        dr_guess = dr_next;\n    }\n    y_diff = abs(y-y_final_value);\n    if ( y_diff[0] < epsabs && y_diff[1] < epsabs)\n    {\n        convergQ = CONVERGED;\n    }\n    return make_tuple(r,y,convergQ);\n}\n\ntuple<VD, VD, VD, double> Tunneling1D::integrateAndSaveProfile(VD R, VD y0, double dr, double epsfrac, double epsabs, double drmin)\n{\n    int N = R.size();\n    double r0 = R[0];\n    VVD Yout(y0.size(),VD(N,0));\n    Yout[0][0] = y0[0];\n    Yout[1][0] = y0[1];\n    VD dydr0 = equationOfMotion(r0,y0);\n    double Rerr = NAN;\n\n    int i = 1;\n    double r = r0;\n    VD y = y0;\n    VD dydr = dydr0;\n    double r_cache;\n    VD y_cache;\n    VD dydr_cache;\n    double dr_guess = dr;\n    double dr_did,dr_next;\n    VD y_scale(2);\n    cubic_param inter_param;\n    while (i<N)\n    {\n        y_scale = abs(y)+abs(dydr*dr_guess);\n        r_cache = r;\n        y_cache = y;\n        dydr_cache = dydr;\n        _rk_calculator._RKQC_SingleStep(r_cache,y_cache,dydr_cache,dr_guess,epsabs,y_scale,dr_did,dr_next);\n        if (dr_did < drmin)\n        {\n            y_cache = y + (y_cache-y)*drmin/dr_did;\n            dr_did = drmin;\n            dr_next = drmin;\n            r_cache = r + dr_did;\n            if (!(std::isnan(Rerr)))\n            {\n                Rerr = r_cache;\n            }\n        }\n        dydr_cache = equationOfMotion(r_cache,y_cache);\n        if (r < R[i] && R[i] <= r_cache)\n        {\n            while (i < N && r < R[i] && R[i] <= r_cache)\n            {\n                double x = (R[i]-r)/dr_did;\n                inter_param = {y[0], dr_did*dydr[0], y_cache[0], dr_did*dydr_cache[0], 0};\n                Yout[0][i] = cubicInterpolation(x, &inter_param);\n                inter_param = {y[1], dr_did*dydr[1], y_cache[1], dr_did*dydr_cache[1], 0};\n                Yout[1][i] = cubicInterpolation(x, &inter_param);\n                i += 1;\n            }   \n        }\n\n        r = r_cache;\n        y = y_cache;\n        dydr = dydr_cache;\n        dr_guess = dr_next;\n    }\n    \n    return make_tuple(R,Yout[0],Yout[1],Rerr);\n}\ntuple<VD,VD,VD,double> Tunneling1D::findProfile(double xguess,double xtol,double phitol,double thinCutoff,int npoints,double rmin, double rmax, int max_interior_pts)\n{\n    double xmin = xtol*10;\n    double xmax = INFINITY;\n    double x;\n    if (!std::isnan(xguess))\n    {\n        x = xguess;\n    }\n    else\n    {\n        x = - log(abs((phi_bar-phi_absMin)/(phi_metaMin-phi_absMin)));\n    }\n    // cout<<\"Starting point: x = \"<<x<<endl;\n    double xincrease = 5.0;\n\n    rmin *= rscale;\n    double dr0 = rmin;\n    double drmin = rmin*1e-2;\n    rmax *= rscale;\n\n    double delta_phi = phi_metaMin - phi_absMin;\n    double epsabs = abs(delta_phi*phitol);\n    double epsfrac = phitol;\n    double delta_phi_cutoff = thinCutoff*delta_phi;\n\n    double rf = NAN;\n    double delta_phi0;\n    double r0_,phi0,dphi0;\n    double r0;\n    VD y0;\n    VD yf;\n    CONVERGENCETYPE ctype;\n    // cout<<\"Starting of the shooting: \"<<endl;\n    while (true)\n    {\n        // cout<<\"--------\"<<endl;\n        delta_phi0 = exp(-x)*delta_phi;\n        // cout<<\"\\tdelta_phi0=\"<<delta_phi0<<endl;\n        std::tie(r0_,phi0,dphi0) = initialConditions(delta_phi0,rmin,delta_phi_cutoff);\n        // cout<<\"\\tInitial condition: r0=\"<<r0_<<\"  phi0=\"<<phi0<<\" dphi0=\"<<dphi0<<endl;\n        if ( !std::isfinite(r0_) || !std::isfinite(x))\n        {\n            if (std::isnan(rf))\n            {\n                cerr<<\"Failed to retrieve initial conditions on the first try\"<<endl;\n            }\n            break;\n        }\n        r0 = r0_;\n        y0 = {phi0,dphi0};\n        std::tie(rf,yf,ctype) = integrateProfile(r0,y0,dr0,epsfrac,epsabs,drmin,rmax);\n        if (ctype == CONVERGED)\n        {\n            break;\n        }\n        else if (ctype == UNDERSHOOT)\n        {\n            xmin = x;\n            x = std::isfinite(xmax)?(xmin+xmax)/2:x*xincrease;\n        }\n        else if (ctype == OVERSHOOT)\n        {\n            xmax = x;\n            x = (xmin+xmax)/2;\n        }\n        \n        if (xmax-xmin < xtol)\n        {\n            break;\n        }   \n    }\n    \n    VD R(npoints);\n    for (size_t i = 0; i < npoints; i++)\n    {\n        R[i] = r0 + i*(rf-r0)/(npoints-1);\n    }\n    VD Phi_ex;\n    VD dPhi_ex;\n    double Rerr;\n    std::tie(R,Phi_ex,dPhi_ex,Rerr)=integrateAndSaveProfile(R,y0,dr0,epsfrac,epsabs,drmin);\n\n    VD R_int;\n    if (max_interior_pts < 0)\n    {\n        max_interior_pts = R.size()/2;\n    }\n    if (max_interior_pts > 0)\n    {\n        double dx0 = R[1]-R[0];\n        if (R[0]/dx0 <= max_interior_pts)\n        {\n            int n = ceil(R[0]/dx0);\n            for (size_t i = 0; i < n; i++)\n            {\n                R_int.push_back(0+i*(R[0])/(n));\n            }\n        }\n        else\n        {\n            int n = max_interior_pts;\n            double a = (R[0]/dx0 - n)*2/(n*(n+1));\n            for (size_t i = 0; i < n; i++)\n            {\n                int k = n-i;\n                R_int.push_back(R[0]-dx0*(k + a*k*(k+1)/2));\n            }\n            R_int[0] = 0.0;\n        }  \n    }\n    VD Phi_int(R_int.size(),0);\n    VD dPhi_int(R_int.size(),0);\n    Phi_int[0] = phi_absMin + delta_phi0;\n    dPhi_int[0] = 0.0;\n    double dV_ = dV_from_absMin(delta_phi0);\n    double d2V_ = d2V({Phi_int[0]},0)[0][0];\n    for (size_t i = 1; i < R_int.size(); i++)\n    {\n        std::tie(Phi_int[i],dPhi_int[i]) = exactSolution(R_int[i],Phi_int[0],dV_,d2V_);\n    }\n    VD R_final(R_int);\n    VD Phi_final(Phi_int);\n    VD dPhi_final(dPhi_int);\n\n    R_final.insert(R_final.end(),R.begin(),R.end());\n    Phi_final.insert(Phi_final.end(),Phi_ex.begin(),Phi_ex.end());\n    dPhi_final.insert(dPhi_final.end(),dPhi_ex.begin(),dPhi_ex.end());\n    \n    return make_tuple(R_final,Phi_final,dPhi_final,Rerr);\n    \n}\ndouble Tunneling1D::findAction(VD R, VD Phi, VD dPhi)\n{\n    int N = R.size();\n    double Sphere_area = pow(M_PI,Spatial_Dim/2.0)/tgamma(Spatial_Dim/2.0);\n    VD area = pow(R,alpha)*Sphere_area;\n    VD integrand(N);\n    double T = 0;\n    for (size_t i = 0; i < N; i++)\n    {\n        integrand[i] = (pow(dPhi[i],2)/2 + V({Phi[i]},&T) - V({phi_metaMin},&T))*area[i];\n    }\n    double S = Simpson(R,integrand);\n\n    // For the bulk inside the bubble interior\n    double volume = pow(R[0],Spatial_Dim)*pow(M_PI,Spatial_Dim/2.0)/tgamma(Spatial_Dim/2.0+1.0);\n    S += volume*(V({Phi[0]},&T)-V({phi_metaMin},&T));\n    return S;\n}\nstd::tuple<VD, VD> Tunneling1D::evenlySpacedPhi(VD phi, VD dphi, int npoint, int k, bool fixAbs)\n{\n    if (fixAbs)\n    {\n        phi.insert(phi.begin(),phi_absMin);\n        phi.insert(phi.end(),phi_metaMin);\n        dphi.insert(dphi.begin(),0.0);\n        dphi.insert(dphi.end(),0.0);\n    }\n    else\n    {\n        phi.insert(phi.end(),phi_metaMin);\n        dphi.insert(dphi.end(),0.0);\n    }\n    \n    // Sort phi in increasing order\n    VVD fullPhi = transpose({phi,dphi});\n    // cout<<\"fullPhi dim: (\"<<fullPhi.size()<<\",\"<<fullPhi[0].size()<<\")\"<<endl;\n    sort(fullPhi.begin(),fullPhi.end(),[](VD x1, VD x2){return x1[0]<x2[0];});\n    VVD::iterator iter = unique(fullPhi.begin(),fullPhi.end(),[](VD x1, VD x2){return x1[0]==x2[0];});\n    fullPhi.resize(distance(fullPhi.begin(),iter));\n    fullPhi=transpose(fullPhi);\n    // cout<<fullPhi[0]<<endl;\n\n    GSL_Spline_Inter inter;\n    inter.SetData(&fullPhi[1],&fullPhi[0]);\n\n    VD p;\n    if (fixAbs)\n    {\n        p = linspace(phi_absMin,phi_metaMin,npoint);\n    }\n    else\n    {\n        p = linspace(phi[0],phi_metaMin,npoint);\n    }\n\n    return make_tuple(p,inter.valAt(p));\n}", "meta": {"hexsha": "6cd058250c72b5f91d529120367e0db3b9607519", "size": 20119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Tunneling1D.cpp", "max_stars_repo_name": "ycwu1030/PhaseTransitions", "max_stars_repo_head_hexsha": "76bee3915b26025a607a71c372005ea88b3d1389", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T22:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-05T22:59:34.000Z", "max_issues_repo_path": "src/Tunneling1D.cpp", "max_issues_repo_name": "ycwu1030/PhaseTransitions", "max_issues_repo_head_hexsha": "76bee3915b26025a607a71c372005ea88b3d1389", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Tunneling1D.cpp", "max_forks_repo_name": "ycwu1030/PhaseTransitions", "max_forks_repo_head_hexsha": "76bee3915b26025a607a71c372005ea88b3d1389", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8059259259, "max_line_length": 165, "alphanum_fraction": 0.5741339033, "num_tokens": 6403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324803738429, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.4139847256796011}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_CoherentScatteringDistribution.cpp\n//! \\author Luke Kersting\n//! \\brief  The coherent photon scattering distribution definition.\n//!\n//---------------------------------------------------------------------------//\n\n// Std Lib Includes\n#include <limits>\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_CoherentScatteringDistribution.hpp\"\n#include \"Utility_PhysicalConstants.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_ContractException.hpp\"\n\nnamespace MonteCarlo{\n\n// Constructor\nCoherentScatteringDistribution::CoherentScatteringDistribution(\n\t\t    const Teuchos::RCP<const Utility::TabularOneDDistribution>&\n\t\t    form_factor_function_squared )\n  : PhotonScatteringDistribution(),\n    d_form_factor_function_squared( form_factor_function_squared )\n{\n  // Make sure the array is valid\n  testPrecondition( !form_factor_function_squared.is_null() );\n}\n\n// Evaluate the distribution\n/*! The cross section (b) differential in the scattering angle cosine is\n * returned from this function.\n */\ndouble CoherentScatteringDistribution::evaluate( \n\t\t\t           const double incoming_energy,\n\t\t\t           const double scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  const double mult = Utility::PhysicalConstants::pi*\n    Utility::PhysicalConstants::classical_electron_radius*\n    Utility::PhysicalConstants::classical_electron_radius;\n\n  const double form_factor_squared = \n    this->evaluateFormFactorSquared( incoming_energy, scattering_angle_cosine);\n\n  return mult*1e24*(1.0 + scattering_angle_cosine*scattering_angle_cosine)*\n    form_factor_squared;    \n}\n\n// Evaluate the PDF\ndouble CoherentScatteringDistribution::evaluatePDF( \n\t\t\t\t   const double incoming_energy,\n\t\t\t\t   const double scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= -1.0 );\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  return this->evaluate( incoming_energy, scattering_angle_cosine )/\n    this->evaluateIntegratedCrossSection( incoming_energy, 1e-3 );\n}\n\n// Evaluate the integrated cross section (b)\ndouble CoherentScatteringDistribution::evaluateIntegratedCrossSection( \n\t\t\t\t\t         const double incoming_energy,\n\t\t\t\t\t         const double precision ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n\n  // Evaluate the integrated cross section\n  boost::function<double (double x)> diff_cs_wrapper = \n    boost::bind<double>( &CoherentScatteringDistribution::evaluate,\n\t\t\t boost::cref( *this ),\n\t\t\t incoming_energy,\n\t\t\t _1 );\n\n  double abs_error, integrated_cs;\n\n  Utility::GaussKronrodIntegrator quadrature_gkq_set( precision );\n\n  quadrature_gkq_set.integrateAdaptively<15>( diff_cs_wrapper,\n\t\t\t\t\t     -1.0,\n\t\t\t\t\t     1.0,\n\t\t\t\t\t     integrated_cs,\n\t\t\t\t\t     abs_error );\n\n  // Make sure the integrated cross section is valid\n  testPostcondition( integrated_cs > 0.0 );\n\n  return integrated_cs;\n}\n\n// Sample an outgoing energy and direction from the distribution\nvoid CoherentScatteringDistribution::sample( \n\t\t\t\t     const double incoming_energy,\n\t\t\t\t     double& outgoing_energy,\n\t\t\t\t     double& scattering_angle_cosine ) const\n{\n  // The outgoing energy is always equal to the incoming energy\n  outgoing_energy = incoming_energy;\n\n  unsigned trial_dummy;\n\n  // Sample an outgoing direction\n  this->sampleAndRecordTrialsImpl( incoming_energy,\n\t\t\t\t   scattering_angle_cosine,\n\t\t\t\t   trial_dummy );\n}\n\n// Sample an outgoing energy and direction and record the number of trials\nvoid CoherentScatteringDistribution::sampleAndRecordTrials( \n\t\t\t\t\t    const double incoming_energy,\n\t\t\t\t\t    double& outgoing_energy,\n\t\t\t\t\t    double& scattering_angle_cosine,\n\t\t\t\t\t    unsigned& trials ) const\n{\n  // The outgoing energy is always equal to the incoming energy\n  outgoing_energy = incoming_energy;\n  \n  // Sample an outgoing direction\n  this->sampleAndRecordTrialsImpl( incoming_energy,\n\t\t\t\t   scattering_angle_cosine,\n\t\t\t\t   trials );\n}\n\n// Randomly scatter the photon\nvoid CoherentScatteringDistribution::scatterPhoton( \n\t\t\t\t     PhotonState& photon,\n\t\t\t\t     ParticleBank& bank,\n\t\t\t\t     SubshellType& shell_of_interaction ) const\n{\n  double scattering_angle_cosine;\n\n  unsigned trial_dummy;\n\n  // Sample an outgoing direction\n  this->sampleAndRecordTrialsImpl( photon.getEnergy(),\n\t\t\t\t   scattering_angle_cosine,\n\t\t\t\t   trial_dummy );\n\n  shell_of_interaction = UNKNOWN_SUBSHELL;\n\n  // Set the new direction\n  photon.rotateDirection( scattering_angle_cosine, \n\t\t\t  this->sampleAzimuthalAngle() );\n}\n\n// Randomly scatter the adjoint photon\nvoid CoherentScatteringDistribution::scatterAdjointPhoton( \n\t\t\t\t     AdjointPhotonState& adjoint_photon,\n\t\t\t\t     ParticleBank& bank,\n\t\t\t\t     SubshellType& shell_of_interaction ) const\n{\n  double scattering_angle_cosine;\n\n  unsigned trial_dummy;\n\n  // Sample an outgoing direction\n  this->sampleAndRecordTrialsImpl( adjoint_photon.getEnergy(),\n\t\t\t\t   scattering_angle_cosine,\n\t\t\t\t   trial_dummy );\n  \n  shell_of_interaction = UNKNOWN_SUBSHELL;\n\n  // Set the new direction\n  adjoint_photon.rotateDirection( scattering_angle_cosine, \n\t\t\t\t  this->sampleAzimuthalAngle() );\n}\n\n// Evaluate the form factor squared\ndouble CoherentScatteringDistribution::evaluateFormFactorSquared( \n\t\t\t\t  const double incoming_energy,\n\t\t\t\t  const double scattering_angle_cosine ) const\n{\n  // The inverse wavelength of the photon (1/cm)\n  const double inverse_wavelength = incoming_energy/\n    (Utility::PhysicalConstants::planck_constant*\n     Utility::PhysicalConstants::speed_of_light);\n\n  // The squared form factor argument\n  const double form_factor_arg_squared = ((1.0 - scattering_angle_cosine)/2.0)*\n    inverse_wavelength*inverse_wavelength;\n\n  // Make sure the squared form factor argument is valid\n  testPostcondition( form_factor_arg_squared >= 0.0 );\n\n  return d_form_factor_function_squared->evaluate( form_factor_arg_squared );\n}\n\n// Basic sampling implementation\nvoid CoherentScatteringDistribution::sampleAndRecordTrialsBasicImpl( \n\t\t\t\t\t    const double incoming_energy,\n\t\t\t\t\t    double& scattering_angle_cosine,\n\t\t\t\t\t    unsigned& trials ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n\n  // Increment the number of trials\n  ++trials;\n\n  // Use the probability mixing technique to sample an outgoing angle\n  double random_number_1 = \n    Utility::RandomNumberGenerator::getRandomNumber<double>();\n  double random_number_2 = \n    Utility::RandomNumberGenerator::getRandomNumber<double>();\n    \n  if( random_number_1 <= 0.75 )\n    scattering_angle_cosine = 2*random_number_2 - 1.0;\n  else\n  {\n    scattering_angle_cosine = pow( fabs(2*random_number_2 - 1.0), 1.0/3.0 );\n\n    if( random_number_2 < 0.5 )\n      scattering_angle_cosine *= -1.0;\n  }\n\n  // Check for roundoff error\n  if( fabs( scattering_angle_cosine ) > 1.0 )\n    scattering_angle_cosine = copysign( 1.0, scattering_angle_cosine );\n\n  // Make sure the scattering angle cosine is valid\n  testPostcondition( scattering_angle_cosine >= -1.0 );\n  testPostcondition( scattering_angle_cosine <= 1.0 );\n}\n\n// Return the form factor function squared distribution\nconst Teuchos::RCP<const Utility::TabularOneDDistribution>&\nCoherentScatteringDistribution::getFormFactorSquaredDistribution() const\n{\n  return d_form_factor_function_squared;\n}\n\n} // end MonteCarlo namespace\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_IncoherentScatteringDistribution.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "9ce4614d9127a048a33a19c6cdbfe4c20aa7030c", "size": 8070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_CoherentScatteringDistribution.cpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_CoherentScatteringDistribution.cpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_CoherentScatteringDistribution.cpp", "max_forks_repo_name": "lkersting/SCR-2123", "max_forks_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0238095238, "max_line_length": 79, "alphanum_fraction": 0.719826518, "num_tokens": 1775, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303236047049, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4137796578259198}}
{"text": "#include <boost/python/numpy.hpp>\r\n#include <boost/python/module.hpp>\r\n#include <boost/python/def.hpp>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <string>\r\n#include <numeric>\r\n#include <algorithm> \r\n#include <unistd.h>\r\n#include <cmath>\r\n#include <chrono>\r\n#include <random>\r\n#include <iostream>\r\n#include <assert.h>\r\n#include <vector>\r\n\r\nnamespace p = boost::python;\r\nnamespace np = boost::python::numpy;\r\n\r\nint n_nodes;\r\nint n_edges;\r\nint **edges;\r\nfloat *edge_weights;\r\nfloat **X;\r\n\r\nvoid gen_rand_network(int n, int m)\r\n{\r\n    int row;\r\n    n_nodes = n;\r\n    n_edges = m;\r\n    edges = (int **)malloc(n_edges*sizeof(int *));\r\n    for(int i = 0; i < n_edges; i++)\r\n        edges[i] = (int *)malloc(2*sizeof(int));\r\n\r\n    edge_weights = (float *)malloc(n_edges*sizeof(float));\r\n    assert(edges != NULL);\r\n    row = 0;\r\n    while(row < n_edges)\r\n    {\r\n        edges[row][0] = rand()%n_nodes;\r\n        edges[row][1] = rand()%n_nodes;\r\n        edge_weights[row] = 1.0;\r\n        row++;\r\n    }\r\n}\r\n\r\nvoid init_embedding(int d)\r\n{\r\n    X = (float **)malloc(n_nodes*sizeof(float *));\r\n    for(int i = 0; i < n_nodes; i++)\r\n        X[i] = (float *)malloc(d*sizeof(float));\r\n    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\r\n    std::default_random_engine generator (seed);\r\n    std::normal_distribution<float> distribution (0.0,1.0);\r\n    for (int i = 0; i < n_nodes; i++)\r\n        for(int j = 0; j < d; j++)\r\n            X[i][j] = 0.01*distribution(generator);\r\n}\r\n\r\nvoid load_network(std::string f_name, bool is_weighted)\r\n{\r\n    std::ifstream f;\r\n    int v_i, v_j, row;\r\n    float w;\r\n\r\n    f.open(f_name);\r\n    f >> n_nodes;\r\n    f >> n_edges;\r\n    edges = (int **)malloc(n_edges*sizeof(int *));\r\n    for(int i = 0; i < n_edges; i++)\r\n        edges[i] = (int *)malloc(2*sizeof(int));\r\n\r\n    edge_weights = (float *)malloc(n_edges*sizeof(float));\r\n    assert(edges != NULL);\r\n\r\n    row = 0;\r\n    if(is_weighted)\r\n    {\r\n        while(f >> v_i  >> v_j >>  w)\r\n        {\r\n            edges[row][0] = v_i;\r\n            edges[row][1] = v_j;\r\n            edge_weights[row] = w;\r\n            row++;\r\n        }\r\n    }\r\n    else\r\n    {\r\n        while(f >> v_i  >> v_j)\r\n        {\r\n            edges[row][0] = v_i;\r\n            edges[row][1] = v_j;\r\n            edge_weights[row] = 1.0;\r\n            row++;\r\n        }\r\n    }\r\n    f.close();\r\n}\r\n\r\nvoid _print_f_value(int d)\r\n{\r\n    float f1 = 0.0, f2 = 0.0;\r\n    float i_j_dot, w_ij;\r\n    int v_i, v_j;\r\n    for(int edge_id = 0; edge_id < n_edges; edge_id++)\r\n    {\r\n        v_i = edges[edge_id][0];\r\n        v_j = edges[edge_id][1];\r\n        w_ij = edge_weights[edge_id];\r\n        i_j_dot = 0.0;\r\n        for(int d_id = 0; d_id < d; d_id++)\r\n            i_j_dot += X[v_i][d_id]*X[v_j][d_id];\r\n        f1 += (w_ij - i_j_dot)*(w_ij - i_j_dot);\r\n    }\r\n    for(int node_id = 0; node_id < n_nodes; node_id++)\r\n        for(int d_id = 0; d_id < d; d_id++)\r\n            f2 += X[node_id][d_id]*X[node_id][d_id];\r\n    std::cout << \"\\t\\tObjective: \" << f1+f2 << \", f1: \" << f1 << \", f2:\" << f2 << std::endl;\r\n}\r\n\r\nvoid saveEmbToTxt(std::string of_name, int d)\r\n{\r\n    std::ofstream f;\r\n    f.open(of_name);\r\n    f << n_nodes << \" \" << d << std::endl;\r\n    for(int node_id = 0; node_id < n_nodes; node_id++)\r\n    {\r\n        f << node_id;\r\n        for(int d_id = 0; d_id < d; d_id++)\r\n            f << \" \" << X[node_id][d_id];\r\n        f << std::endl;\r\n    }\r\n    f.close();\r\n\r\n}\r\nvoid learn_embedding(std::string if_name, std::string of_name, bool verbose, bool is_weighted, int d, float eta, float regu, int max_iter)\r\n{\r\n    clock_t t;\r\n    srand(time(NULL));\r\n    t = clock();\r\n    load_network(if_name, is_weighted);\r\n    // gen_rand_network(1e3, 3e4);\r\n    init_embedding(d);\r\n    int v_i, v_j;\r\n    float i_j_dot, w_ij;\r\n    for(int iter_id = 0; iter_id < max_iter; iter_id++)\r\n    {\r\n        if(verbose)\r\n        {\r\n            if(iter_id%100 == 0)\r\n            {\r\n                std::cout << \"\\tIter id: \" << iter_id << std::endl;\r\n                _print_f_value(d);\r\n            }\r\n        }\r\n        for(int edge_id = 0; edge_id < n_edges; edge_id++)\r\n        {\r\n            v_i = edges[edge_id][0];\r\n            v_j = edges[edge_id][1];\r\n            w_ij = edge_weights[edge_id];\r\n            if(v_j <= v_i)\r\n                continue;\r\n            i_j_dot = 0;\r\n            for(int d_id = 0; d_id < d; d_id++)\r\n                i_j_dot += X[v_i][d_id]*X[v_j][d_id];\r\n            for(int d_id = 0; d_id < d; d_id++)\r\n                X[v_i][d_id] -= eta*(regu*X[v_i][d_id] - (w_ij - i_j_dot)*X[v_j][d_id]);\r\n        }\r\n    }\r\n    t = clock() - t;\r\n    t = clock();\r\n    saveEmbToTxt(of_name, d);\r\n}\r\n\r\nBOOST_PYTHON_MODULE(graphFac_ext)\r\n{\r\n    // Py_Initialize();\r\n    // Py_Initialize();\r\n    // np::initialize();\r\n    // srand(time(NULL));\r\n    p::def(\"learn_embedding\", learn_embedding);\r\n}\r\n\r\n", "meta": {"hexsha": "eb6e8c05b5b612ea3c9d44a490e97e308625acde", "size": 4874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gem/c_src/graphFac.cpp", "max_stars_repo_name": "vinnamkim/GEM-Benchmark", "max_stars_repo_head_hexsha": "8420c565531098b5b36abec340f1c5e330c4dbcc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2019-08-20T02:37:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T14:09:08.000Z", "max_issues_repo_path": "gem/c_src/graphFac.cpp", "max_issues_repo_name": "vinnamkim/GEM-Benchmark", "max_issues_repo_head_hexsha": "8420c565531098b5b36abec340f1c5e330c4dbcc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-01-28T22:52:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T00:25:50.000Z", "max_forks_repo_path": "gem/c_src/graphFac.cpp", "max_forks_repo_name": "vinnamkim/GEM-Benchmark", "max_forks_repo_head_hexsha": "8420c565531098b5b36abec340f1c5e330c4dbcc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T05:59:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-10T14:51:06.000Z", "avg_line_length": 26.4891304348, "max_line_length": 139, "alphanum_fraction": 0.504924087, "num_tokens": 1397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4137132071673004}}
{"text": "// Copyright 2004-2006 The Trustees of Indiana University.\n\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n#ifndef BOOST_GRAPH_PLOD_GENERATOR_HPP\n#define BOOST_GRAPH_PLOD_GENERATOR_HPP\n\n#include <iterator>\n#include <utility>\n#include <boost/random/uniform_int.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <vector>\n#include <map>\n#include <boost/config/no_tr1/cmath.hpp>\n#include <boost/mpl/if.hpp>\n\nnamespace boost {\n  template<typename RandomGenerator>\n  class out_directed_plod_iterator\n  {\n  public:\n    typedef std::forward_iterator_tag            iterator_category;\n    typedef std::pair<std::size_t, std::size_t>  value_type;\n    typedef const value_type&                    reference;\n    typedef const value_type*                    pointer;\n    typedef std::ptrdiff_t                       difference_type;\n\n    out_directed_plod_iterator() : gen(0), at_end(true) { }\n\n    out_directed_plod_iterator(RandomGenerator& gen, std::size_t n,\n                               double alpha, double beta,\n                               bool allow_self_loops)\n      : gen(&gen), n(n), alpha(alpha), beta(beta),\n        allow_self_loops(allow_self_loops), at_end(false), degree(0),\n        current(0, 0)\n    {\n      using std::pow;\n\n      uniform_int<std::size_t> x(0, n-1);\n      std::size_t xv = x(gen);\n      degree = (xv == 0? 0 : std::size_t(beta * pow(xv, -alpha)));\n    }\n\n    reference operator*() const { return current; }\n    pointer operator->() const { return &current; }\n\n    out_directed_plod_iterator& operator++()\n    {\n      using std::pow;\n\n      uniform_int<std::size_t> x(0, n-1);\n\n      // Continue stepping through source nodes until the\n      // (out)degree is > 0\n      while (degree == 0) {\n        // Step to the next source node. If we've gone past the\n        // number of nodes we're responsible for, we're done.\n        if (++current.first >= n) {\n          at_end = true;\n          return *this;\n        }\n\n        std::size_t xv = x(*gen);\n        degree = (xv == 0? 0 : std::size_t(beta * pow(xv, -alpha)));\n      }\n\n      do {\n        current.second = x(*gen);\n      } while (current.first == current.second && !allow_self_loops);\n      --degree;\n\n      return *this;\n    }\n\n    out_directed_plod_iterator operator++(int)\n    {\n      out_directed_plod_iterator temp(*this);\n      ++(*this);\n      return temp;\n    }\n\n    bool operator==(const out_directed_plod_iterator& other) const\n    {\n      return at_end == other.at_end;\n    }\n\n    bool operator!=(const out_directed_plod_iterator& other) const\n    {\n      return !(*this == other);\n    }\n\n  private:\n    RandomGenerator* gen;\n    std::size_t n;\n    double alpha;\n    double beta;\n    bool allow_self_loops;\n    bool at_end;\n    std::size_t degree;\n    value_type current;\n  };\n\n  template<typename RandomGenerator>\n  class undirected_plod_iterator\n  {\n    typedef std::vector<std::pair<std::size_t, std::size_t> > out_degrees_t;\n\n  public:\n    typedef std::input_iterator_tag              iterator_category;\n    typedef std::pair<std::size_t, std::size_t>  value_type;\n    typedef const value_type&                    reference;\n    typedef const value_type*                    pointer;\n    typedef std::ptrdiff_t                       difference_type;\n\n    undirected_plod_iterator()\n      : gen(0), out_degrees(), degrees_left(0), allow_self_loops(false) { }\n\n    undirected_plod_iterator(RandomGenerator& gen, std::size_t n,\n                             double alpha, double beta,\n                             bool allow_self_loops = false)\n      : gen(&gen), n(n), out_degrees(new out_degrees_t),\n        degrees_left(0), allow_self_loops(allow_self_loops)\n    {\n      using std::pow;\n\n      uniform_int<std::size_t> x(0, n-1);\n      for (std::size_t i = 0; i != n; ++i) {\n        std::size_t xv = x(gen);\n        std::size_t degree = (xv == 0? 0 : std::size_t(beta * pow(xv, -alpha)));\n        if (degree == 0) degree = 1;\n        else if (degree >= n) degree = n-1;\n        out_degrees->push_back(std::make_pair(i, degree));\n        degrees_left += degree;\n      }\n\n      next();\n    }\n\n    reference operator*() const { return current; }\n    pointer operator->() const { return &current; }\n\n    undirected_plod_iterator& operator++()\n    {\n      next();\n      return *this;\n    }\n\n    undirected_plod_iterator operator++(int)\n    {\n      undirected_plod_iterator temp(*this);\n      ++(*this);\n      return temp;\n    }\n\n    bool operator==(const undirected_plod_iterator& other) const\n    {\n      return degrees_left == other.degrees_left;\n    }\n\n    bool operator!=(const undirected_plod_iterator& other) const\n    { return !(*this == other); }\n\n  private:\n    void next()\n    {\n      std::size_t source, target;\n      while (true) {\n        /* We may get to the point where we can't actually find any\n           new edges, so we just add some random edge and set the\n           degrees left = 0 to signal termination. */\n        if (out_degrees->size() < 2) {\n          uniform_int<std::size_t> x(0, n-1);\n          current.first  = x(*gen);\n          do {\n            current.second = x(*gen);\n          } while (current.first == current.second && !allow_self_loops);\n          degrees_left = 0;\n          out_degrees->clear();\n          return;\n        }\n\n        uniform_int<std::size_t> x(0, out_degrees->size()-1);\n\n        // Select source vertex\n        source = x(*gen);\n        if ((*out_degrees)[source].second == 0) {\n          (*out_degrees)[source] = out_degrees->back();\n          out_degrees->pop_back();\n          continue;\n        }\n\n        // Select target vertex\n        target = x(*gen);\n        if ((*out_degrees)[target].second == 0) {\n          (*out_degrees)[target] = out_degrees->back();\n          out_degrees->pop_back();\n          continue;\n        } else if (source != target\n                   || (allow_self_loops && (*out_degrees)[source].second > 2)) {\n          break;\n        }\n      }\n\n      // Update degree counts\n      --(*out_degrees)[source].second;\n      --degrees_left;\n      --(*out_degrees)[target].second;\n      --degrees_left;\n      current.first  = (*out_degrees)[source].first;\n      current.second = (*out_degrees)[target].first;\n    }\n\n    RandomGenerator* gen;\n    std::size_t n;\n    shared_ptr<out_degrees_t> out_degrees;\n    std::size_t degrees_left;\n    bool allow_self_loops;\n    value_type current;\n  };\n\n\n  template<typename RandomGenerator, typename Graph>\n  class plod_iterator\n    : public mpl::if_<is_convertible<\n                        typename graph_traits<Graph>::directed_category,\n                        directed_tag>,\n                      out_directed_plod_iterator<RandomGenerator>,\n                      undirected_plod_iterator<RandomGenerator> >::type\n  {\n    typedef typename mpl::if_<\n                       is_convertible<\n                         typename graph_traits<Graph>::directed_category,\n                         directed_tag>,\n                        out_directed_plod_iterator<RandomGenerator>,\n                        undirected_plod_iterator<RandomGenerator> >::type\n      inherited;\n\n  public:\n    plod_iterator() : inherited() { }\n\n    plod_iterator(RandomGenerator& gen, std::size_t n,\n                  double alpha, double beta, bool allow_self_loops = false)\n      : inherited(gen, n, alpha, beta, allow_self_loops) { }\n  };\n\n} // end namespace boost\n\n#endif // BOOST_GRAPH_PLOD_GENERATOR_HPP\n", "meta": {"hexsha": "a9133b9d405f68171af42cb349ce7a256135e717", "size": 7596, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/graph/plod_generator.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/graph/plod_generator.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/graph/plod_generator.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 29.905511811, "max_line_length": 80, "alphanum_fraction": 0.5883359663, "num_tokens": 1852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4137123148377376}}
{"text": "#include \"common.hpp\"\n\n#include <cstdio>\n#include <cstdlib>\n#include <string>\n#include <cassert>\n#include <random>\n#include <vector>\n#include <utility>\n#include <map>\n#include <cmath>\n#include <algorithm>\n\n#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)\n\n// eigen\n#include <Eigen/Core>\n\nusing namespace Eigen;\nusing namespace std;\n\nconstexpr int BUF_SIZE = 1000;\n\nusing p_t = pair<int, int>;\nusing r_t = vector<map<p_t, double> >;\nusing mat_t = MatrixXd;\nusing vec_t = VectorXd;\nusing vec_mat_t = vector<mat_t>;\n\nstd::mt19937_64 engine;//(seed_gen());\n\nvector<int> seq(int n){\n  vector<int> v(n);\n  for(int i = 0; i < n; ++i){v[i] = i;}\n  return v;\n}\n\nvector<int> random_index(int n){\n  vector<int> res = seq(n);\n  shuffle(res.begin(), res.end(), engine);\n  return res;\n}\n\nvoid seeding(unsigned seed = 0){\n  //std::random_device seed_gen;\n  //engine = std::mt19937_64(seed_gen());\n  engine = std::mt19937_64(seed);\n}\n\nstring to_str(int x){\n  char buf[BUF_SIZE];\n  sprintf(buf, \"%d\", x);\n  return buf;\n}\n\n\nmat_t load_mat(const string& infile){\n  vector<vector<double> > mat;\n  ifstream ifs(infile);\n  string line;\n  while(getline(ifs, line)){\n    vector<double> row;\n    for(const auto& field : split(line)){\n      double x;\n      sscanf(field.c_str(), \"%lf\", &x);\n      row.push_back(x);\n    }\n    mat.push_back(row);\n  }\n  int m = mat.size();\n  assert(m > 0);\n  int n = mat[0].size();\n  mat_t res = mat_t::Zero(m, n);\n  for(int i = 0; i < m; ++i){\n    assert(n == mat[i].size());\n    for(int j = 0; j < n; ++j){\n      res(i, j) = mat[i][j];\n    }\n  }\n  return res;\n}\n\nmat_t ReadModelParameter(const string& prefix, int K, int ItrNum, const string& name){\n  char buf[BUF_SIZE];\n  sprintf(buf, \"%s_Itr%d_%s.csv\", prefix.c_str(), ItrNum, name.c_str());\n  //read_file(buf);\n\n  //mat_t tmp = load_mat(buf);\n  //fprintf(stderr, \"[%ld, %ld]\\n\", tmp.rows(), tmp.cols());\n\n  return load_mat(buf);\n}\n/*\n  ########################### Read model parameters #############################\n  # [output1]: A (N x K matrix)\n  # [output2]: B (M x K matrix)\n  # [output3]: C (M x K matrix)\n  # [output4]: D (T x K matrix)\n*/\ntuple<mat_t, mat_t, mat_t, mat_t> ReadModelParameters(const string& prefix, int K, int ItrNum){\n  mat_t A = ReadModelParameter(prefix, K, ItrNum, \"A\");\n  mat_t B = ReadModelParameter(prefix, K, ItrNum, \"B\");\n  mat_t C = ReadModelParameter(prefix, K, ItrNum, \"C\");\n  mat_t D = ReadModelParameter(prefix, K, ItrNum, \"D\");\n  return forward_as_tuple(A, B, C, D);\n}\n\n/*\n######################### Plausible deniability test ##########################\n# [input1]: A (N x K matrix)\n# [input2]: B (M x K matrix)\n# [input3]: C (M x K matrix)\n# [input4]: D (T x K matrix)\n# [input5]: N -- Number of users\n# [input6]: M -- Number of POIs\n# [input7]: T -- Number of time periods\n# [output1]: pass_test (N-dim vector)\n# [output2]: loglikeli_train (N*TraceNum-dim vector)\n# [output3]: loglikeli_verify (N*TraceNum x VUserNum matrix)\n */\n\nusing pass_test_t = vector<int>;\n\nvoid PDTest_out1(const string& _outfile,\n\t\t int N,\n\t\t int TraceNum,\n\t\t const pass_test_t& pass_test){\n  //  string outfile = _outfile + \"_\";\n  string outfile = _outfile;\n  puts(outfile.c_str());\n  FILE* fp = fopen(outfile.c_str(), \"w\");\n  rep(user_index, N){\n    rep(trace_no, TraceNum){\n      int user_trace_no = user_index * TraceNum + trace_no;\n//      fprintf(fp, \"%lf\\n\", static_cast<double>(pass_test[user_trace_no]));\n      fprintf(fp, \"%d,%d\\n\", pass_test[user_trace_no + N * TraceNum], pass_test[user_trace_no]);\n    }\n  }\n  int pass_test_sum = 0;\n  for(int i = 0; i < N * TraceNum; i++){\n    pass_test_sum += pass_test[i];\n  }\n  fprintf(fp, \"-,-,%d,%d,%lf\\n\", pass_test_sum, N * TraceNum, float(pass_test_sum) / float(N * TraceNum));\n  fclose(fp);\n}\nvoid PDTest_out2(const string& _outfile,\n\t\t int N,\n\t\t int TraceNum,\n\t\t int VUserNum,\n\t\t const mat_t& loglikeli_train,\n\t\t const mat_t& loglikeli_verify){\n  //  string outfile = _outfile + \"_\";\n  string outfile = _outfile;\n  puts(outfile.c_str());\n  FILE* fp = fopen(outfile.c_str(), \"w\");\n  rep(user_index, N){\n    rep(trace_no, TraceNum){\n      int user_trace_no = user_index * TraceNum + trace_no;\n      fprintf(fp, \"%lf\", loglikeli_train(user_trace_no, 0));\n      rep(n, VUserNum){\n\tfprintf(fp, \",%lf\", loglikeli_verify(user_trace_no,n));\n      }\n      fprintf(fp, \"\\n\");\n    }\n  }\n  fclose(fp);\n}\n\npass_test_t perform_pd_test(int N,\n\t\t\t    int TraceNum,\n\t\t\t    int VUserNum,\n\t\t\t    const vector<int>& verify_user,\n\t\t\t    const mat_t& loglikeli_train,\n\t\t\t    const mat_t& loglikeli_verify,\n\t\t\t    double ReqEps,\n\t\t\t    int Reqk){\n  /*\n  pass_test_t pass_test(N * TraceNum, 0);\n  // # For each training user\n  rep(user_index, N){\n    // # For each trace\n    rep(trace_no, TraceNum){\n      int user_trace_no = user_index * TraceNum + trace_no;\n      // # Initialization\n      int k = 0;\n      // # For each verifying user\n      rep(n, VUserNum){\n\t// # Continue if the training user is the same with the verifying user\n\tif(user_index == verify_user[n]){continue;}\n\t// # Increase k if the inequality holds with ReqEps\n\tif((loglikeli_train(user_trace_no, 0) >= loglikeli_verify(user_trace_no,n) - ReqEps) &&\n\t   (loglikeli_train(user_trace_no, 0) <= loglikeli_verify(user_trace_no,n) + ReqEps)){\n\t  ++k;\n\t}\n\t// # Break if k reaches Reqk\n\tif(k == Reqk){\n\t  pass_test[user_trace_no] = 1;\n\t  break;\n\t}\n      }\n    }\n  }\n  */\n  pass_test_t pass_test(N * TraceNum * 2, 0);\n  // # For each training user\n  int i_tra, i_ver;\n  rep(user_index, N){\n    // # For each trace\n    rep(trace_no, TraceNum){\n      int user_trace_no = user_index * TraceNum + trace_no;\n      pass_test[user_trace_no + N * TraceNum] += 1;\n      // # Find i s.t. [-(i+1)ReqEps < loglikeli_train[user_trace_no] <= -i ReqEps] --> i_tra\n      i_tra = int(loglikeli_train(user_trace_no, 0) / ReqEps);\n      // # For each verifying user\n      rep(n, VUserNum){\n\t// # Continue if the training user is the same with the verifying user\n\tif(user_index == verify_user[n]){continue;}\n\t// # Find i s.t. [-(i+1)ReqEps < loglikeli_verify[user_trace_no,n] <= -i ReqEps] --> i_ver\n\ti_ver = int(loglikeli_verify(user_trace_no,n) / ReqEps);\n\t// # Increase k if the inequality holds with ReqEps (i_tra == i_ver)\n\tif(i_tra == i_ver){\n\t  pass_test[user_trace_no + N * TraceNum] += 1;\n\t}\n\t// # Pass test (and break (optional)) if k reaches Reqk\n\tif(pass_test[user_trace_no + N * TraceNum] == Reqk){\n\t  pass_test[user_trace_no] = 1;\n//\t  break;\n\t}\n      }\n    }\n  }\n  return pass_test;\n}\n\nint str2i(const string& s){\n  int x;\n  sscanf(s.c_str(), \"%d\", &x);\n  return x;\n}\n\ndouble str2f(const string& s){\n  double x;\n  sscanf(s.c_str(), \"%lf\", &x);\n  return x;\n}\n\nusing trans_t = vector<vector<pair<int, int> > >;\nusing first_visit_t = vector<int>;\n\ntuple<trans_t, first_visit_t, mat_t> read_syn_traces(const string& infile,\n\t\t\t\t\t     int TraceNum,\n\t\t\t\t\t     int T,\n\t\t\t\t\t     int TimInsNum,\n\t\t\t\t\t     int N){\n  // init\n  trans_t trans(N * TraceNum);\n  first_visit_t first_visit(N * TraceNum, 0);\n  mat_t loglikeli_train = mat_t::Zero(N * TraceNum, 1);\n  int poi_index_prev = 0;\n  //printf(\"%s\\n\", infile.c_str());\n  ifstream ifs(infile);\n  string line;\n  getline(ifs, line); // header\n  while(getline(ifs, line)){\n    auto lst = split(line);\n    int user_index = str2i(lst[0]);\n    int trace_no = str2i(lst[1]);\n    int time_slot = str2i(lst[2]);\n    int time_ins = str2i(lst[3]);\n    int poi_index = str2i(lst[4]);\n    double ll = str2f(lst[6]);\n\n    // # (user,trace)-pair no. --> user_trace_no\n    int user_trace_no = user_index * TraceNum + trace_no;\n    if(time_slot == 0 && time_ins == 0){\n      // # Visited POI at the first time --> first_visit[user_trace_no] \n      first_visit[user_trace_no] = poi_index;\n    }else{\n      // # Transition from the previous POI to the current POI --> trans[user_trace_no]\n      trans[user_trace_no].push_back(make_pair(poi_index_prev,poi_index));\n    }\n    // # Log-likelihood for the training trace --> loglikeli_train[user_trace_no]\n    if(time_slot == T-1 && time_ins == TimInsNum-1){\n      loglikeli_train(user_trace_no, 0) = ll;\n    }\n    poi_index_prev = poi_index;\n  }\n  return forward_as_tuple(trans, first_visit, loglikeli_train);\n}\n\nmat_t calc_ll(int VUserNum,\n\t      const vector<int>& verify_user,\n\t      int T, int M,\n\t      double VisThr,\n\t      double VisitDelta,\n\t      const mat_t& A, // N * K\n\t      const mat_t& B, // M * K\n\t      const mat_t& C, // M * K\n\t      const mat_t& D, // T * K\n\t      double TransDelta,\n\t      int N,\n\t      int TraceNum,\n\t      int TimInsNum,\n\t      const first_visit_t& first_visit,\n\t      const trans_t& trans){\n  mat_t loglikeli_verify = mat_t::Zero(N*TraceNum,VUserNum);\n  rep(n, VUserNum){\n    int vn = verify_user[n];\n    printf(\"%d, %d\\n\", n, vn);\n    // # Initialization\n    mat_t time_poi_dist = mat_t::Zero(T, M);\n    mat_t time_poi_dist_sum = mat_t::Zero(T, 1);\n    mat_t prop_mat = mat_t::Zero(M, M);\n    mat_t same_trans = mat_t::Zero(T, M); //np.full((T,M), -1.0);\n    for(int i = 0; i < T; ++i)for(int j = 0; j < M; ++j){same_trans(i, j) = -1.0;}\n    mat_t trans_vec = mat_t::Zero(M, 1);\n    \n    // ################### Calculate the POI distributions ###################\n    puts(\"POI distribution\");\n    rep(t, T){\n      mat_t ad = A.row(vn).array() * D.row(t).array();\n      rep(i, M){\n\t// # Elements in a sampled visit tensor --> time_poi_dist\n\ttime_poi_dist(t,i) = (ad.array() * B.row(i).array()).sum();\n\t// # Assign VisitDelta for an element whose value is less than VisThr\n\tif(time_poi_dist(t,i) < VisThr){\n\t  time_poi_dist(t,i) = VisitDelta;\n\t}\n      }\n    }\n    // # Normalize time_poi_dist\n    rep(t, T){\n      time_poi_dist_sum(t) = time_poi_dist.row(t).sum();\n      if(time_poi_dist_sum(t) > 0){\n\ttime_poi_dist.row(t) /= time_poi_dist_sum(t);\n      }else{\n\tprintf(\"Error: All probabilities are 0 for user %d and time %d\\n\", n, t);\n\texit(1);\n      }\n    }\n    // #################### Calculate the proposal matrix ####################\n    puts(\"Proposal matrix\");\n    rep(i, M){\n      mat_t ab = A.row(vn).array() * B.row(i).array();\n      // # Elements in a sampled transition tensor (assign TransDelta for a small transition count) --> prop_mat\n      rep(j, M){\n\tprop_mat(i,j) = max((ab.array() * C.row(j).array()).sum(), TransDelta);\n      }\n      // # Normalize prop_mat\n      double row_sum = prop_mat.row(i).sum();\n      prop_mat.row(i) /= row_sum;\n    }\n    // #################### Calculate the log-likelihood #####################\n    puts(\"Calculating the log-likelihood\");\n    // # For each training user\n    rep(user_index, N){\n      // # Continue if the training user is the same with the verifying user\n      if(user_index == vn){continue;}\n      // # For each trace\n      rep(trace_no, TraceNum){\n\tint user_trace_no = user_index * TraceNum + trace_no;\n\t// # For each time slot\n\trep(t, T){\n\t  // # For each time instant\n\t  rep(ins, TimInsNum){\n\t    if(t == 0 && ins == 0){\n\t      // # Add the log-likelihood for the first POI\n\t      int poi_index = first_visit[user_trace_no];\n\t      loglikeli_verify(user_trace_no, n) = log(time_poi_dist(0,poi_index));\n\t    }else{\n\t      // # Add the log-likelihood for the subsequent POIs\n\t      int tim = t * TimInsNum + ins - 1;\n\t      int poi_index_pre = trans[user_trace_no][tim].first;\n\t      int poi_index = trans[user_trace_no][tim].second;\n\t      double trans_prob;\n\t      // # If the current POI is different from the previous POI\n\t      if(poi_index_pre != poi_index){\n\t\t// # Calculate the transition probability --> trans_prob\n\t\tdouble alpha = (time_poi_dist(t, poi_index) * prop_mat(poi_index, poi_index_pre))\n\t\t  / (time_poi_dist(t, poi_index_pre) * prop_mat(poi_index_pre, poi_index));\n\t\ttrans_prob = prop_mat(poi_index_pre,poi_index) * min(1.0, alpha);\n\t      // # If the self-transition probability for the POI at time slot t has been computed\n\t      }else if(same_trans(t,poi_index_pre) != -1.0){\n\t\t// # Use the self-transition probability --> trans_prob\n\t\ttrans_prob = same_trans(t,poi_index_pre);\n\t      // # If the self-transition probability for the POI at time slot t has NOT been computed\n\t      }else{\n\t\t// # Compute the self-transition probability for the POI --> same_trans[t,poi_index_pre]\n\t\ttrans_vec(poi_index_pre, 0) = 0;\n\t\trep(j, M){\n\t\t  if(poi_index_pre != j){\n\t\t    double alpha = (time_poi_dist(t, j) * prop_mat(j, poi_index_pre))\n\t\t      / (time_poi_dist(t, poi_index_pre) * prop_mat(poi_index_pre,j));\n\t\t    trans_vec(j, 0) = prop_mat(poi_index_pre,j) * min(1.0, alpha);\n\t\t  }\n\t\t}\n\t\tdouble row_sum = trans_vec.sum();\n\t\tsame_trans(t,poi_index_pre) = 1 - row_sum;\n\t\t// # Use the self-transition probability --> trans_prob\n\t\ttrans_prob = same_trans(t,poi_index_pre);\n\t      }\n\t      // # Add the log of the transition probability\n\t      loglikeli_verify(user_trace_no,n) += log(trans_prob);\n\t      //\n\t    }\n\t    //\n\t  }\n\t}\n      }\n    }\n    //\n  }\n  return loglikeli_verify;\n}\n\nvoid PDTest(mat_t& A,\n\t    mat_t& B,\n\t    mat_t& C,\n\t    mat_t& D,\n\t    int N,\n\t    int M,\n\t    int T,\n\t    int VUserNum,\n\t    const string& PDTestResFile,\n\t    int K,\n\t    int ItrNum,\n\t    int TraceNum,\n\t    double ReqEps,\n\t    int Reqk,\n\t    const string& SynTraceFile,\n\t    int TimInsNum,\n\t    double VisThr, double VisitDelta, double TransDelta){\n  // # Initialization\n  \n  // # Randomly assign verifying users --> verify_user\n  auto verify_user = random_index(VUserNum);\n  \n  // # Read synthesized traces --> trans, first_visit, loglikeli_train\n  trans_t trans;\n  first_visit_t first_visit;\n  mat_t loglikeli_train;\n  tie(trans, first_visit, loglikeli_train) =\n    read_syn_traces(SynTraceFile + \"_Itr\" + to_str(ItrNum) + \".csv\",\n\t\t    TraceNum, T, TimInsNum, N);\n  \n  // # Calculate the log-likelihood for each verifying user --> loglikeli_verify\n  mat_t loglikeli_verify = calc_ll(VUserNum, verify_user, T, M, VisThr, VisitDelta, A, B, C, D, TransDelta, N, TraceNum, TimInsNum, first_visit, trans);\n\n  // # Perform the PD test --> pass_test\n  pass_test_t pass_test = perform_pd_test(N,TraceNum, VUserNum,\n\t\t\t\t    verify_user, loglikeli_train, loglikeli_verify,\n\t\t\t\t    ReqEps, Reqk);\n  \n  // # Output the PD test results (pass_test)\n  PDTest_out1(PDTestResFile + \"_Itr\" + to_str(ItrNum) + \".csv\",\n\t      N, TraceNum, pass_test);\n  /*\n  // # Output the PD test results (loglikeli_train, loglikeli_verify)\n  PDTest_out2(PDTestResFile + \"_Itr\" + to_str(ItrNum) + \"_loglikeli.csv\",\n\t      N, TraceNum, VUserNum,\n\t      loglikeli_train, loglikeli_verify);\n  */\n}\n\nint main(int argc, char* argv[]){\n  if(argc < 3){\n    fprintf(stderr, \"Usage: %s [Dataset] [City] ([ReqEps (default:1.0)] [Reqk (default:10)] [VUserNum (default:-1)] [TraceNum (default:10)] [Alp (default:200)] [MaxNumTrans (default:100)] [MaxNumVisit (default:100)] [ItrNum (default:100)])\\n\", argv[0]);\n    exit(1);\n  }\n  // # Dataset (PF/FS)\n  string DataSet = argv[1];\n  // # City\n  string City = argv[2];\n\n  // # Required epsilon in plausible deniability\n  double ReqEps = 1.0;\n  if(argc >= 4){\n    sscanf(argv[3], \"%lf\", &ReqEps);\n  }\n\n  // # Required k in plausible deniability\n  int Reqk = 10;\n  if(argc >= 5){\n    sscanf(argv[4], \"%d\", &Reqk);\n  }\n\n  // # Number of users for verifying PD (-1: all)\n  int VUserNum = -1;\n  if(argc >= 6){\n    sscanf(argv[5], \"%d\", &VUserNum);\n  }\n\n  // # Number of traces per user\n  int TraceNum = 10;\n  if(argc >= 7){\n    sscanf(argv[6], \"%d\", &TraceNum);\n  }\n\n  // # Hyper-hyper parameter alpha\n  double Alp = 200;\n  string AlpStr = \"200\";\n  if(argc >= 8){\n    sscanf(argv[7], \"%lf\", &Alp);\n    AlpStr = argv[7];\n  }\n\n  // # Maximum number of transitions per user (-1: infinity)\n  int MaxNumTrans = 100;\n  if(argc >= 9){\n    sscanf(argv[8], \"%d\", &MaxNumTrans);\n  }\n\n  // # Maximum number of POI visits per user (-1: infinity)\n  int MaxNumVisit = 100;\n  if(argc >= 10){\n    sscanf(argv[9], \"%d\", &MaxNumVisit);\n  }\n\n  // # Number of iterations in Gibbs sampling\n  int ItrNum = 100;\n  if(argc >= 11){\n    sscanf(argv[10], \"%d\", &ItrNum);\n  }\n  \n  // # Data directory\n  string DataDir = \"../data/\" + DataSet + \"/\";\n\n  // # Training user index file (input)\n  string TUserIndexFile = DataDir + \"tuserindex_%s.csv\";\n  // # POI index file (input)\n  string POIIndexFile = DataDir + \"POIindex_%s.csv\";\n\n  // # Model parameter directory\n//  string ModelParameterDir = DataDir + \"PPMTF_\" + City + \"_alp\" + AlpStr + \"_mnt\" + to_str(MaxNumTrans) + \"_mnv\" + to_str(MaxNumVisit) + \"_py/\";\n  string ModelParameterDir = DataDir + \"PPMTF_\" + City + \"_alp\" + AlpStr + \"_mnt\" + to_str(MaxNumTrans) + \"_mnv\" + to_str(MaxNumVisit) + \"/\";\n  // # Prefix of the model parameter file (input)\n  string ModelParameterFile = ModelParameterDir + \"modelparameter\";\n  // # Prefix of the synthesized trace file (input)\n  string SynTraceFile = ModelParameterDir + \"syntraces\";\n\n  // # Prefix of the PD test result file (output)\n  string PDTestResFile = ModelParameterDir + \"pdtest_res\";\n\n  // # Name of the model parameter A\n  //string ParamA = \"A\";\n\n  // # Number of time slots\n  int T = -1;\n  if(DataSet.find(\"PF\") == 0){T = 30;}\n  if(DataSet.find(\"FS\") == 0){T = 12;}\n  if(T == -1){\n    fprintf(stderr, \"Wrong Dataset\\n\");\n    exit(1);\n  }\n\n  // # Number of time instants per time slot\n  int TimInsNum = -1;\n  if(DataSet.find(\"PF\") == 0){TimInsNum = 1;}\n  if(DataSet.find(\"FS\") == 0){TimInsNum = 2;}\n  assert(TimInsNum >= 0);\n\n  // # Number of columns in model parameters (A, B, C)\n  int K = 16;\n  // # Threshold for a visit count\n  double VisThr = 0;\n  // # Minimum value of a visit count\n  double VisitDelta = 0.00000001;\n  // # Minimum value of a transition count\n  double TransDelta = 0.00000001;\n\n  // #################################### Main #####################################\n  // # Fix a seed\n  seeding(1);\n\n  // # Replace XX with City\n  TUserIndexFile = string_replace(TUserIndexFile, City);\n  POIIndexFile = string_replace(POIIndexFile, City);\n\n  // # Number of training users --> N\n  int N = line_num(TUserIndexFile) - 1;\n  // # Number of POIs --> M\n  int M = line_num(POIIndexFile) - 1;\n\n  // # Number of users for verifying PD (-1: all)\n  if(VUserNum == -1){VUserNum = N-1;}\n\n  // # Read model parameters\n  mat_t A, B, C, D;\n  tie(A, B, C, D) = ReadModelParameters(ModelParameterFile, K, ItrNum);\n\n  // # Plausible deniability test\n  PDTest(A, B, C, D, N, M, T,\n\t VUserNum, PDTestResFile,\n\t K, ItrNum, TraceNum,\n\t ReqEps, Reqk,\n\t SynTraceFile,\n\t TimInsNum,\n\t VisThr, VisitDelta, TransDelta);\n  //////////////////pass_test, loglikeli_train, loglikeli_verify = PDTest(A, B, C, D, N, M, T)\n\n//  printf(\"%s\\n\", DataSet.c_str());\n//  printf(\"%s\\n\", City.c_str());\n  return 0;\n}\n", "meta": {"hexsha": "806081eef0410af3cbf0b10c47a2203a12558b4a", "size": 18504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/PDTest_Trace.cpp", "max_stars_repo_name": "gghatano/PPMTF-1", "max_stars_repo_head_hexsha": "670bff7e58150418f9e7b75e6367f0f069c454b5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-11-11T04:28:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T16:26:32.000Z", "max_issues_repo_path": "cpp/PDTest_Trace.cpp", "max_issues_repo_name": "gghatano/PPMTF-1", "max_issues_repo_head_hexsha": "670bff7e58150418f9e7b75e6367f0f069c454b5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-14T10:58:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-14T10:58:25.000Z", "max_forks_repo_path": "cpp/PDTest_Trace.cpp", "max_forks_repo_name": "gghatano/PPMTF-1", "max_forks_repo_head_hexsha": "670bff7e58150418f9e7b75e6367f0f069c454b5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-05T22:46:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T08:02:57.000Z", "avg_line_length": 30.5851239669, "max_line_length": 253, "alphanum_fraction": 0.6179204496, "num_tokens": 5574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4137123148377376}}
{"text": "//\n// Created by david on 2018-10-29.\n//\n\n#include \"matrix_recast.h\"\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <iterator>\n\n/*! \\brief Prints the content of a vector nicely */\n//template<typename Scalar_>\n//std::ostream &operator<<(std::ostream &out, const std::vector<Scalar_> &v) {\n//    if (!v.empty()) {\n////        out << \"[ \";\n//        std::copy(v.begin(), v.end(), std::ostream_iterator<Scalar_>(out, \"  \"));\n//        out << '\\n';\n//    }\n//    return out;\n//}\n\ntemplate<typename Scalar>\nmatrix_recast<Scalar>::matrix_recast(const Scalar *matrix_ptr_, int L_):matrix_ptr(matrix_ptr_), L(L_){\n    recheck_all();\n}\n\ntemplate<typename Scalar>\nvoid matrix_recast<Scalar>::prune(double threshold){\n    matrix_pruned.resize(L*L);\n    Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> matmap   (matrix_ptr,L,L);\n    Eigen::Map<Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> matpruned(matrix_pruned.data(),L,L);\n    matpruned = (matmap.array().cwiseAbs() < threshold).select(Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>::Zero(L,L), matmap);\n    recheck_all();\n    pruned = true;\n}\n\n\ntemplate<typename Scalar>\nvoid matrix_recast<Scalar>:: recheck_all(){\n    check_if_sparse();\n    check_if_hermitian();\n    check_if_real();\n}\n\n\n\n\ntemplate<typename Scalar>\nvoid matrix_recast<Scalar>::check_if_real() {\n    Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> matrix (matrix_ptr,L,L);\n    if constexpr (std::is_same<Scalar, double>::value){isReal = true;}\n    else {isReal = matrix.imag().isZero(1e-14);}\n}\n\n\ntemplate<typename Scalar>\nvoid matrix_recast<Scalar>::check_if_hermitian() {\n    Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> matrix (matrix_ptr,L,L);\n    isHermitian = matrix.isApprox(matrix.adjoint(), 1e-14);\n}\n\n\ntemplate<typename Scalar>\nvoid matrix_recast<Scalar>::check_if_sparse() {\n    Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> matrix (matrix_ptr,L,L);\n    sparcity = (matrix.array().cwiseAbs() > 1e-14 )\n                       .select(Eigen::MatrixXd::Ones(L,L),0).sum() / static_cast<double>(matrix.size());\n    isSparse =  sparcity < 0.1;\n}\n\ntemplate<typename Scalar>\nDenseMatrixProduct<double> matrix_recast<Scalar>::get_as_real_dense() {\n    if constexpr(std::is_same<Scalar, double>::value){\n        if (pruned){return DenseMatrixProduct<double>(matrix_pruned.data(),L,true);}\n        else       {return DenseMatrixProduct<double>(matrix_ptr,L,true);}\n    }else{\n//        assert(is_real and \"ERROR: The given matrix has a nonzero imaginary part. Can't convert to real.\");\n        if (not isReal){\n            double sum = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> (matrix_ptr,L,L).imag().cwiseAbs().sum();\n            std::cerr << \"WARNING: The given matrix has a nonzero imaginary part, yet converting to real. Imag sum: \" << sum << std::endl;\n        }        Eigen::MatrixXd matrix_recast;\n        if (pruned){matrix_recast = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> (matrix_pruned.data(),L,L).real();}\n        else       {matrix_recast = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> (matrix_ptr,L,L).real();}\n        return DenseMatrixProduct<double>(matrix_recast.data(),L,true);\n\n\n    }\n}\n\ntemplate<typename Scalar>\nDenseMatrixProduct<std::complex<double>> matrix_recast<Scalar>::get_as_cplx_dense() {\n    if constexpr(std::is_same<Scalar, double>::value){\n        Eigen::MatrixXcd matrix_recast(L,L);\n        matrix_recast.setZero();\n        if (pruned){matrix_recast.real() = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> (matrix_pruned.data(),L,L);}\n        else       {matrix_recast.real() = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> (matrix_ptr,L,L);}\n        return DenseMatrixProduct<std::complex<double>>(matrix_recast.data(),L,true);\n    }else{\n        return DenseMatrixProduct<std::complex<double>>(matrix_ptr,L,true);\n    }\n}\n\ntemplate<typename Scalar>\nSparseMatrixProduct<double> matrix_recast<Scalar>::get_as_real_sparse() {\n    if constexpr(std::is_same<Scalar, double>::value){\n        if(pruned){return SparseMatrixProduct<double>(matrix_pruned.data(),L,true);}\n        else      {return SparseMatrixProduct<double>(matrix_ptr,L,true);}\n    }else{\n        if (not isReal){\n            double sum = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> (matrix_ptr,L,L).imag().cwiseAbs().sum();\n            std::cerr << \"WARNING: The given matrix has a nonzero imaginary part, yet converting to real. Imag sum: \" << sum << std::endl;\n        }\n        Eigen::MatrixXd matrix_recast;\n        if(pruned){matrix_recast = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> (matrix_pruned.data(),L,L).real();}\n        else      {matrix_recast = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> (matrix_ptr,L,L).real();}\n        return SparseMatrixProduct<double>(matrix_recast.data(),L,true);\n    }\n}\n\ntemplate<typename Scalar>\nSparseMatrixProduct<std::complex<double>> matrix_recast<Scalar>::get_as_cplx_sparse() {\n    if constexpr(std::is_same<Scalar, double>::value){\n        Eigen::MatrixXcd matrix_recast(L,L);\n        matrix_recast.setZero();\n        if(pruned){matrix_recast.real() = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> (matrix_pruned.data(),L,L);}\n        else      {matrix_recast.real() = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> (matrix_ptr,L,L);}\n        return SparseMatrixProduct<std::complex<double>>(matrix_recast.data(),L,true);\n    }else{\n        if(pruned){return SparseMatrixProduct<std::complex<double>>(matrix_pruned.data(),L,true);}\n        else      {return SparseMatrixProduct<std::complex<double>>(matrix_ptr,L,true);}\n    }\n}\n\n\n\n\n\n//\n//template<typename Scalar>\n//void matrix_recast<Scalar>::convert_to_real_dense(){\n//    // READ THIS TO LEARN MORE http://atantet.github.io/ATSuite_cpp/atspectrum_8hpp_source.html\n//\n//    matrix_real_dense.clear();\n//    matrix_cplx_dense.clear();\n////    matrix_real_sparse.clear();\n////    matrix_cplx_sparse.clear();\n//\n//\n////    matrix_real_dense.L    = L;\n////    matrix_real_dense.N    = L*L;\n//    if constexpr(std::is_same<Scalar, double>::value){\n//        matrix_real_dense = DenseMatrixProduct<double>(matrix_ptr,L);\n//    }else{\n//        Eigen::MatrixXd matrix_recast = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> (matrix_ptr,L,L).real();\n//        matrix_real_dense = DenseMatrixProduct<double>(matrix_recast.data(),L);\n//    }\n//\n//}\n//\n//\n//template<typename Scalar>\n//void matrix_recast<Scalar>::convert_to_cplx_dense(){\n//    // READ THIS TO LEARN MORE http://atantet.github.io/ATSuite_cpp/atspectrum_8hpp_source.html\n//\n//    matrix_real_dense.clear();\n//    matrix_cplx_dense.clear();\n////    matrix_real_sparse.clear();\n////    matrix_cplx_sparse.clear();\n//\n//\n////    matrix_cplx_dense.L    = L;\n////    matrix_cplx_dense.N    = L*L;\n//    if constexpr(std::is_same<Scalar, double>::value){\n//        Eigen::MatrixXcd matrix_recast = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>> (matrix_ptr,L,L);\n//        matrix_cplx_dense =  DenseMatrixProduct<std::complex<double>>(matrix_recast.data(),L);\n//    }else{\n//        matrix_cplx_dense = DenseMatrixProduct<std::complex<double>>(matrix_ptr,L);\n//    }\n//}\n\n\n//template<typename Scalar>\n//void matrix_recast<Scalar>::convert_to_real_sparse(){\n    // READ THIS TO LEARN MORE http://atantet.github.io/ATSuite_cpp/atspectrum_8hpp_source.html\n\n//    matrix_real_dense.clear();\n//    matrix_cplx_dense.clear();\n//    matrix_real_sparse.clear();\n//    matrix_cplx_sparse.clear();\n//\n//    assert(isReal and \"Matrix is not real!\");\n//    Eigen::SparseMatrix<double> matrix_recast = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>>(matrix_ptr,L,L).real().sparseView();\n//    matrix_recast.makeCompressed();\n//    matrix_real_sparse.nnz = matrix_recast.nonZeros();\n//    matrix_real_sparse.L   = L;\n//    matrix_real_sparse.N   = L*L;\n//    matrix_real_sparse.irow = std::vector<int>   (matrix_recast.innerIndexPtr(), matrix_recast.innerIndexPtr() + matrix_recast.nonZeros() );\n//    matrix_real_sparse.pcol = std::vector<int>   (matrix_recast.outerIndexPtr(), matrix_recast.outerIndexPtr() + matrix_recast.outerSize() +1);\n//    matrix_real_sparse.vals = std::vector<double>(matrix_recast.valuePtr()     , matrix_recast.valuePtr()      + matrix_recast.nonZeros());\n//\n\n//}\n\n\n//template<typename Scalar>\n//void matrix_recast<Scalar>::convert_to_cplx_sparse(){\n    // READ THIS TO LEARN MORE http://atantet.github.io/ATSuite_cpp/atspectrum_8hpp_source.html\n\n\n\n//    matrix_real_dense.clear();\n//    matrix_cplx_dense.clear();\n//    matrix_real_sparse.clear();\n//    matrix_cplx_sparse.clear();\n//    assert(not isReal and \"Matrix is not cplx!\");\n//    Eigen::SparseMatrix<std::complex<double>> matrix_recast = Eigen::Map<const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>>(matrix_ptr,L,L).template cast<std::complex<double>>().sparseView();\n//    matrix_recast.makeCompressed();\n//    matrix_recast.finalize();\n//    std::cout << \"Matrix compressed: \\n\" << matrix_recast << std::endl;\n//\n//    matrix_cplx_sparse.nnz = matrix_recast.nonZeros();\n//    matrix_cplx_sparse.L   = L;\n//    matrix_cplx_sparse.N   = L*L;\n//    matrix_cplx_sparse.irow = std::vector<int>   (matrix_recast.innerIndexPtr(), matrix_recast.innerIndexPtr() + matrix_recast.nonZeros() );\n//    matrix_cplx_sparse.pcol = std::vector<int>   (matrix_recast.outerIndexPtr(), matrix_recast.outerIndexPtr() + matrix_recast.outerSize() +1);\n//    matrix_cplx_sparse.vals = std::vector<std::complex<double>>(matrix_recast.valuePtr()       , matrix_recast.valuePtr()       + matrix_recast.nonZeros());\n//\n//    std::cout << \"nonzeros : \" << matrix_recast.nonZeros() << std::endl;\n//    std::cout << \"innerSize: \" << matrix_recast.innerSize() << std::endl;\n//    std::cout << \"outerSize: \" << matrix_recast.outerSize() << std::endl;\n//    std::cout << \"irow \\n\" << matrix_cplx_sparse.irow << std::endl;\n//    std::cout << \"pcol \\n\" << matrix_cplx_sparse.pcol << std::endl;\n//    std::cout << \"vals \\n\" << matrix_cplx_sparse.vals << std::endl;\n//    auto innernnz = std::vector<int>   (matrix_recast.innerNonZeroPtr(), matrix_recast.innerNonZeroPtr() + matrix_recast.innerSize() );\n//    auto innernnz = std::vector<int>   (matrix_recast.innerNonZeroPtr(), matrix_recast.innerIndexPtr() + matrix_recast.innerSize() );\n//    std::cout << \"innernnz: \\n\" << innernnz << std::endl;\n\n//}\n\n\n\ntemplate class matrix_recast<double>;\ntemplate class matrix_recast<std::complex<double>>;", "meta": {"hexsha": "61673064331b91b4247cd5b2f4777e745755e9ce", "size": 10744, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unused/eigsolver_backup/arpack_extra/matrix_recast.cpp", "max_stars_repo_name": "DavidAce/DMRG", "max_stars_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-31T22:50:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T15:45:27.000Z", "max_issues_repo_path": "unused/eigsolver_backup/arpack_extra/matrix_recast.cpp", "max_issues_repo_name": "DavidAce/DMRG", "max_issues_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "unused/eigsolver_backup/arpack_extra/matrix_recast.cpp", "max_forks_repo_name": "DavidAce/DMRG", "max_forks_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-16T00:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-16T00:27:56.000Z", "avg_line_length": 44.3966942149, "max_line_length": 201, "alphanum_fraction": 0.680007446, "num_tokens": 2725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4137123148377376}}
{"text": "#include <iostream>\n#include <vector>\n#include <list>\n#include <set>\n#include <tuple>\n#include <unordered_map>\n#include <cstdio>\n#include <utility>\n#include <cstdlib>\n#include <map>\n#include <cmath>\n#include <ctgmath>\n#include <cstring>\n#include <functional>\n#include <cassert>\n#include <algorithm>\n#include <unordered_map>\n#include <fstream>\n#include <stdio.h>\n\n#include <boost/algorithm/string.hpp>\n#include <Eigen/Dense>\n#include \"parse_args.hh\"\n#include \"omp.h\"\n\n#define KNRM  \"\\x1B[0m\"\n#define KRED  \"\\x1B[31m\"\n#define KGRN  \"\\x1B[32m\"\n#define KYEL  \"\\x1B[33m\"\n#define KBLU  \"\\x1B[34m\"\n#define KMAG  \"\\x1B[35m\"\n#define KCYN  \"\\x1B[36m\"\n#define KWHT  \"\\x1B[37m\"\n\nusing namespace std;\nusing namespace Eigen;\n\nint D; // dimensionality\n\nunordered_map<string, VectorXd> w; // target word vectors\nunordered_map<string, VectorXd> c; // context word vectors\nunordered_map<string, double> bw; // target word biases\nunordered_map<string, double> bc; // context word biases\n\nunordered_map<string, VectorXd> grad_w; // Squared gradient for AdaGrad\nunordered_map<string, VectorXd> grad_c; \nunordered_map<string, double> grad_bw; \nunordered_map<string, double> grad_bc; \n\nstruct edge {\n  string w, c;\n  double value;\n};\nvector<edge> edges;\n\nset<string> words;\nset<string> contexts;\n\nunordered_map<string, double> pairs;\n\n\nvoid read_edges(string fname, vector<edge> &train_data){\n    ifstream train_file(fname.c_str());\n    string first, second;\n    double value;\n    while (train_file >> first >> second >> value){\n        edge e;\n        e.w = first;\n        e.c = second;\n        e.value = value;\n        //cout << e.w << \"\\t\" << e.c << \"\\t\" << e.value << endl;\n        words.insert(first);\n        contexts.insert(second);\n        train_data.push_back(e);\n    }\n    train_file.close();\n    // allocate memory for all vectors\n}  \n\nvoid load_word_vectors(string vects_fname){\n    // Initialize word vectors using pre-trained word vectors\n    fprintf(stderr, \"%sDimensionality of the word vectors = %d%s\\n\", KRED, D, KNRM);\n    fprintf(stderr, \"%sReading pre-trained vectors from %s%s\\n\", KRED, vects_fname.c_str(), KNRM);\n    unordered_map<string, VectorXd> x;\n    set<string> prewords;\n\n    FILE *fp= fopen(vects_fname.c_str(), \"r\");\n    int count = 0;\n    for (char buf[262144]; fgets(buf, sizeof(buf), fp); ) {\n        char curword[1024];\n        sscanf(buf, \"%s %[^\\n]\", curword, buf);\n        string wstr(curword);\n        if ((words.find(wstr) != words.end()) || (contexts.find(wstr) != contexts.end())){\n            x[wstr] = VectorXd::Zero(D);\n            count = 0;\n            while (1) {\n                double fval;\n                bool end = (sscanf(buf, \"%lf %[^\\n]\", &fval, buf) != 2);\n                x[wstr][count] = fval;\n                count += 1;\n            if (end) break;\n            }\n            prewords.insert(wstr);\n            assert(count == D);\n        }\n    }\n    // Copy the vectors from x to w and c.\n    for (auto y = x.begin(); y != x.end(); ++y){\n        if (words.find(y->first) != words.end())\n            w[y->first] = y->second;\n        if (contexts.find(y->first) != contexts.end())\n            c[y->first] = y->second;\n    }\n    fclose(fp);\n}\n\nvoid read_pairs(string pairs_fname){\n    fprintf(stderr, \"%sReading relational pairs from = %s%s\\n\", KRED, pairs_fname.c_str(), KNRM);\n    ifstream pairs_file(pairs_fname.c_str());\n    string first_word, second_word;\n    double value;\n    \n    while (pairs_file >> first_word >> second_word >> value){\n        //cout << first_word << \"\\t\" << second_word << \"\\t\" << value << \"\\t\" << (2 * value) << endl;\n        pairs[first_word + \"<+>\" + second_word] = value;\n    }\n    \n    /*\n    while (pairs_file >> first_word >> second_word){\n        //cout << first_word << \"\\t\" << second_word << \"\\t\" << value << endl;\n        pairs[first_word + \"<+>\" + second_word] = 1.0;\n    }\n    */\n\n    pairs_file.close();\n}\n\nvoid centralize(unordered_map<string, VectorXd> &x){\n    VectorXd mean = VectorXd::Zero(D);\n    VectorXd squared_mean = VectorXd::Zero(D);\n    for (auto w = x.begin(); w != x.end(); ++w){\n        mean += w->second;\n        squared_mean += (w->second).cwiseProduct(w->second);\n    }\n    mean = mean / ((double) x.size());\n    VectorXd sd = squared_mean - mean.cwiseProduct(mean);\n    for (int i = 0; i < D; ++i){\n        sd[i] = sqrt(sd[i]);\n    }\n    for (auto w = x.begin(); w != x.end(); ++w){\n        VectorXd tmp = VectorXd::Zero(D);\n        for (int i = 0; i < D; ++i){\n            tmp[i] = (w->second)[i] - mean[i];\n            if (sd[i] != 0)\n                tmp[i] /= sd[i];\n        }\n        w->second = tmp;\n    }\n}\n\nvoid initialize(){\n    int count_words = 0;\n    for(auto e = words.begin(); e != words.end(); ++e){\n        count_words++;\n        w[*e] = VectorXd::Random(D);\n        bw[*e] = 0;\n        grad_w[*e] = VectorXd::Zero(D);\n        grad_bw[*e] = 0;\n    }\n\n    int count_contexts = 0;\n    for(auto e = contexts.begin(); e != contexts.end(); ++e){\n        count_contexts++;\n        c[*e] = VectorXd::Random(D);\n        bc[*e] = 0;\n        grad_c[*e] = VectorXd::Zero(D);\n        grad_bc[*e] = 0;\n    }\n\n    centralize(w);\n    centralize(c);\n    fprintf(stderr, \"%sInitialization Completed...\\n%s\", KYEL, KNRM);\n}\n\ndouble f(size_t x){\n    if (x < 100)\n        return pow((x / 100.0), 0.75);\n    else\n        return 1.0;\n}\n\n\nvoid train(int epohs, double alpha, double lambda){\n    fprintf(stderr, \"%s\\nTotal ephos to train = %d\\n%s\", KGRN, epohs, KNRM);\n    fprintf(stderr, \"%sInitial learning rate = %f\\n%s\", KGRN, alpha, KNRM);\n    fprintf(stderr, \"%slambda = %f\\n%s\", KGRN, lambda, KNRM);\n    fprintf(stderr, \"%sDim = %d\\n%s\", KGRN, D, KNRM);\n\n    double total_loss, cost;\n    VectorXd gw = VectorXd::Zero(D);\n    VectorXd gc = VectorXd::Zero(D);  \n    VectorXd diff = VectorXd::Zero(D); \n\n    VectorXd one_vect = VectorXd::Zero(D);\n    for (auto i = 0; i < D; ++i)\n        one_vect[i] = 1.0;\n\n    int found_pairs = 0;\n\n    for (int t = 0; t < epohs; ++t){\n        total_loss = 0;\n        found_pairs = 0;\n        for(auto e = edges.begin(); e != edges.end(); ++e){\n            cost = w[e->w].dot(c[e->c]) + bw[e->w] + bc[e->c] - log(e->value);\n            total_loss += f(e->value) * cost * cost;\n\n            cost *= f(e->value);\n            gw = cost * c[e->c];\n            gc = cost * w[e->w];\n\n            string pair_key = e->w + \"<+>\" + e->c;\n            if (pairs.find(pair_key) != pairs.end()){\n                diff = lambda * pairs[pair_key] * (w[e->w] - c[e->c]);\n                gw += diff;\n                gc -= diff;\n                found_pairs++;\n                }\n\n            grad_w[e->w] += gw.cwiseProduct(gw);\n            grad_c[e->c] += gc.cwiseProduct(gc);\n            grad_bw[e->w] += cost * cost;\n            grad_bc[e->c] += cost * cost;\n\n            w[e->w] -= alpha * gw.cwiseProduct((grad_w[e->w] + one_vect).cwiseInverse().cwiseSqrt());\n            c[e->c] -= alpha * gc.cwiseProduct((grad_c[e->c] + one_vect).cwiseInverse().cwiseSqrt());\n\n            bw[e->w] -= (alpha * cost) / sqrt(1.0 + grad_bw[e->w]);\n            bc[e->c] -= (alpha * cost) / sqrt(1.0 + grad_bc[e->c]);                   \n        }\n        fprintf(stderr, \"Itr = %d, Loss = %f, foundPairs = %d\\n\", t, (sqrt(total_loss) / edges.size()), found_pairs);\n    }\n}\n\n\nvoid write_line(ofstream &reps_file, VectorXd vec, string label){\n    reps_file << label + \" \";\n    for (int i = 0; i < D; ++i)\n        reps_file << vec[i] << \" \";\n    reps_file << endl;\n}\n\nvoid save_model(string fname){\n    ofstream reps_file;\n    reps_file.open(fname);\n    if (!reps_file){\n        fprintf(stderr, \"%sFailed to write reps to %s\\n%s\", KRED, KNRM, fname.c_str());\n        exit(1);\n    } \n    for (auto x = words.begin(); x != words.end(); ++x){\n        if (contexts.find(*x) != contexts.end())\n             write_line(reps_file, 0.5 * (w[*x] + c[*x]), *x);\n        else\n            write_line(reps_file, w[*x], *x);     \n    }\n\n    for (auto x = contexts.begin(); x != contexts.end(); ++x){\n        if (words.find(*x) == words.end())\n            write_line(reps_file, c[*x], *x);\n    }\n    reps_file.close();\n}\n\n\nint main(int argc, char *argv[]){\n    int no_threads = 100;\n    omp_set_num_threads(no_threads);\n    setNbThreads(no_threads);\n    initParallel(); \n\n    if (argc == 1) {\n        fprintf(stderr, \"usage: ./reps --dim=dimensionality --model=model_fname \\\n                                --alpha=alpha --ephos=rounds --lmda=lambda --edges=edges_fname \\\n                                 --pretrain=pretrained_word_vectors_file (if any) \\\n                                 --pairs=pairs_file_name \\n\"); \n        return 0;\n    }\n    parse_args::init(argc, argv); \n    string edges_fname = parse_args::get<string>(\"--edges\");\n    string pretrain = parse_args::get<string>(\"--pretrain\");\n    string pairs_fname = parse_args::get<string>(\"--pairs\");\n\n    D = parse_args::get<int>(\"--dim\");\n    int epohs = parse_args::get<int>(\"--epohs\");\n    double alpha = parse_args::get<double>(\"--alpha\");\n    string model = parse_args::get<string>(\"--model\");\n    double lambda = parse_args::get<double>(\"--lmda\");\n\n    \n    read_edges(edges_fname, edges);\n    fprintf(stderr, \"%sTotal no. of target train instances = %d\\n%s\", KGRN, (int) edges.size(), KNRM);\n    fprintf(stderr, \"%sTotal no of words = %d\\n%s\", KGRN, (int) words.size(), KNRM);\n    fprintf(stderr, \"%sTotal no. of contexts = %d\\n%s\", KGRN, (int) contexts.size(), KNRM); \n    read_pairs(pairs_fname);\n    //test_code();\n    initialize();\n    if (pretrain.length() > 0){\n        load_word_vectors(pretrain);\n    } \n    train(epohs, alpha, lambda);\n    save_model(model);\n    return 0;\n\n}", "meta": {"hexsha": "782d761e2fbeae9c3f38b78cacb450f2eec2d4f0", "size": 9629, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/reps.cc", "max_stars_repo_name": "suhibani/JointReps", "max_stars_repo_head_hexsha": "50a72d916fc3d74b9064db46263ba3508037aaf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2017-03-16T03:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-02T18:21:41.000Z", "max_issues_repo_path": "src/reps.cc", "max_issues_repo_name": "suhibani/JointReps", "max_issues_repo_head_hexsha": "50a72d916fc3d74b9064db46263ba3508037aaf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-20T11:32:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-25T14:53:14.000Z", "max_forks_repo_path": "src/reps.cc", "max_forks_repo_name": "suhibani/JointReps", "max_forks_repo_head_hexsha": "50a72d916fc3d74b9064db46263ba3508037aaf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-03T14:43:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-14T10:33:22.000Z", "avg_line_length": 30.7635782748, "max_line_length": 117, "alphanum_fraction": 0.5506283103, "num_tokens": 2724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208003, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.41371204065086437}}
{"text": "/*\n boost header: numeric/odeint/gram_schmitt.hpp\n\n Copyright 2011-2013 Karsten Ahnert\n Copyright 2011 Mario Mulansky\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_ODEINT_GRAM_SCHMITT_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_GRAM_SCHMITT_HPP_INCLUDED\n\n#include <boost/throw_exception.hpp>\n#include <iterator>\n#include <algorithm>\n#include <numeric>\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\ntemplate< class Iterator , class T >\nvoid normalize( Iterator first , Iterator last , T norm )\n{\n    while( first != last ) *first++ /= norm;\n}\n\ntemplate< class Iterator , class T >\nvoid substract_vector( Iterator first1 , Iterator last1 ,\n        Iterator first2 , T val )\n{\n    while( first1 != last1 ) *first1++ -= val * ( *first2++ );\n}\n\ntemplate< size_t num_of_lyap , class StateType , class LyapType >\nvoid gram_schmidt( StateType &x , LyapType &lyap , size_t n )\n{\n    if( !num_of_lyap ) return;\n    if( ptrdiff_t( ( num_of_lyap + 1 ) * n ) != std::distance( x.begin() , x.end() ) )\n        BOOST_THROW_EXCEPTION( std::domain_error( \"renormalization() : size of state does not match the number of lyapunov exponents.\" ) );\n\n    typedef typename StateType::value_type value_type;\n    typedef typename StateType::iterator iterator;\n\n    value_type norm[num_of_lyap];\n    value_type tmp[num_of_lyap];\n    iterator first = x.begin() + n;\n    iterator beg1 = first , end1 = first + n ;\n\n    std::fill( norm , norm+num_of_lyap , 0.0 );\n\n    // normalize first vector\n    norm[0] = sqrt( std::inner_product( beg1 , end1 , beg1 , 0.0 ) );\n    normalize( beg1 , end1 , norm[0] );\n\n    beg1 += n;\n    end1 += n;\n\n    for( size_t j=1 ; j<num_of_lyap ; ++j , beg1+=n , end1+=n )\n    {\n        for( size_t k=0 ; k<j ; ++k )\n        {\n            tmp[k] = std::inner_product( beg1 , end1 , first + k*n , 0.0 );\n            //  clog << j << \" \" << k << \" \" << tmp[k] << \"\\n\";\n        }\n\n\n\n        for( size_t k=0 ; k<j ; ++k )\n            substract_vector( beg1 , end1 , first + k*n , tmp[k] );\n\n        // normalize j-th vector\n        norm[j] = sqrt( std::inner_product( beg1 , end1 , beg1 , 0.0 ) );\n        // clog << j << \" \" << norm[j] << \"\\n\";\n        normalize( beg1 , end1 , norm[j] );\n    }\n\n    for( size_t j=0 ; j<num_of_lyap ; j++ )\n        lyap[j] += log( norm[j] );\n}\n\n\n} // namespace odeint\n} // namespace numeric\n} // namespace boost\n\n#endif //BOOST_NUMERIC_ODEINT_GRAM_SCHMITT_HPP_INCLUDED\n", "meta": {"hexsha": "f5f56808bbeed7b6a1f4caa51156f65dd421a945", "size": 2541, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/gram_schmidt.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/odeint/examples/gram_schmidt.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/odeint/examples/gram_schmidt.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 28.2333333333, "max_line_length": 139, "alphanum_fraction": 0.6229830775, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4135430711203847}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n\n#include \"structures.h\"\n#include \"transformations.h\"\n#include \"cauchy.h\"\n#include \"perspective_camera_plucker_line_tait_bryan_wc_jacobian.h\"\n#include \"perspective_camera_tait_bryan_wc_jacobian.h\"\n#include \"perspective_camera_plucker_line_rodrigues_wc_jacobian.h\"\n#include \"perspective_camera_plucker_line_quaternion_wc_jacobian.h\"\n#include \"quaternion_constraint_jacobian.h\"\n\n\nstruct LinePoint{\n\tdouble u;\n\tdouble v;\n\tint index_to_line;\n};\n\nstruct Camera{\n\tEigen::Affine3d pose;\n\tstd::vector<std::pair<LinePoint, LinePoint>> uv;\n};\n\ntypedef Eigen::Matrix<double, 6, 1> PLine;\n\nstd::vector<Camera> cameras;\nPerspectiveCameraParams cam_params;\nstd::vector<std::pair<Eigen::Vector3d, Eigen::Vector3d>> lines;\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = -215, rotate_y = 273;\nfloat translate_z = -68.0;\nfloat translate_x = 4, translate_y = 30.0;\n\nbool initGL(int *argc, char **argv);\nvoid display();\nvoid keyboard(unsigned char key, int x, int y);\nvoid mouse(int button, int state, int x, int y);\nvoid motion(int x, int y);\nvoid reshape(int w, int h);\nvoid printHelp();\nPLine get_plucker_line(const Eigen::Vector3d &from, const Eigen::Vector3d &to);\n\nint main(int argc, char *argv[]){\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tcam_params.fx = 2000;\n\tcam_params.fy = 1000;\n\tcam_params.cx = 1000;\n\tcam_params.cy = 500;\n\n\tfor(int i = -50 ; i < 50; i+=20){\n\t\tCamera c;\n\t\tc.pose = Eigen::Affine3d::Identity();\n\t\tc.pose(0,3) = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1.0;\n\t\tc.pose(1,3) = i;\n\t\tc.pose(2,3) = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1.0;\n\t\tcameras.push_back(c);\n\t}\n\n\tfor(float x = 0; x <= 100; x += 5){\n\t\tEigen::Vector3d a(x, -50.0, 400);\n\t\tEigen::Vector3d b(x,  50.0, 400);\n\t\tlines.emplace_back(a,b);\n\t}\n\tfor(float y = -50; y <= 50; y += 5){\n\t\tEigen::Vector3d a(0, y, 400);\n\t\tEigen::Vector3d b(100.0, y, 400);\n\t\tlines.emplace_back(a,b);\n\t}\n\n\tfor(float x = -100; x <= 0; x += 5){\n\t\tEigen::Vector3d a(x, -50.0, 440);\n\t\tEigen::Vector3d b(x,  50.0, 440);\n\t\tlines.emplace_back(a,b);\n\t}\n\tfor(float y = -50; y <= 50; y += 5){\n\t\tEigen::Vector3d a(-100, y, 440);\n\t\tEigen::Vector3d b(0.0, y, 440);\n\t\tlines.emplace_back(a,b);\n\t}\n\n\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\tfor(size_t j = 0 ; j < lines.size(); j++){\n\t\t\tstd::pair<LinePoint, LinePoint> uv;\n\t\t\tLinePoint kp;\n\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(cameras[i].pose);\n\n\t\t\tprojection_perspective_camera_tait_bryan_wc(kp.u, kp.v, cam_params.fx, cam_params.fy, cam_params.cx, cam_params.cy, pose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka, lines[j].first.x(), lines[j].first.y(), lines[j].first.z());\n\n\t\t\tuv.first.u = kp.u;\n\t\t\tuv.first.v = kp.v;\n\t\t\tuv.first.index_to_line = j;\n\n\t\t\tprojection_perspective_camera_tait_bryan_wc(kp.u, kp.v, cam_params.fx, cam_params.fy, cam_params.cx, cam_params.cy, pose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka, lines[j].second.x(), lines[j].second.y(), lines[j].second.z());\n\n\t\t\tuv.second.u = kp.u;\n\t\t\tuv.second.v = kp.v;\n\t\t\tuv.second.index_to_line = j;\n\n\t\t\tcameras[i].uv.push_back(uv);\n\t\t}\n\t}\n\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"perspective_camera_external_orientation_plucker_line\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01,\n\t\t\t10000.0);\n\tglutReshapeFunc(reshape);\n\n\treturn true;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tfor(size_t i = 0 ; i < cameras.size(); i++){\n\t\tEigen::Affine3d m = cameras[i].pose;\n\n\t\tglBegin(GL_LINES);\n\t\t\tglColor3f(1.0f, 0.0f, 0.0f);\n\t\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\t\tglVertex3f(m(0,3) + m(0,0), m(1,3) + m(1,0), m(2,3) + m(2,0));\n\n\t\t\tglColor3f(0.0f, 1.0f, 0.0f);\n\t\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\t\tglVertex3f(m(0,3) + m(0,1), m(1,3) + m(1,1), m(2,3) + m(2,1));\n\n\t\t\tglColor3f(0.0f, 0.0f, 1.0f);\n\t\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\t\tglVertex3f(m(0,3) + m(0,2), m(1,3) + m(1,2), m(2,3) + m(2,2));\n\t\tglEnd();\n\t}\n\n\tglColor3f(0,1,0);\n\tglBegin(GL_LINES);\n\t\tfor(size_t i = 0; i < lines.size(); i++){\n\t\t\tglVertex3f(lines[i].first.x(), lines[i].first.y(), lines[i].first.z());\n\t\t\tglVertex3f(lines[i].second.x(), lines[i].second.y(), lines[i].second.z());\n\t\t}\n\tglEnd();\n\n\tglColor3f(0.8,0.8,0.8);\n\tglBegin(GL_LINE_STRIP);\n\tfor(size_t i = 0 ; i < cameras.size(); i++){\n\t\tEigen::Affine3d m = cameras[i].pose;\n\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t}\n\tglEnd();\n\n\tglutSwapBuffers();\n}\n\nvoid keyboard(unsigned char key, int /*x*/, int /*y*/) {\n\tswitch (key) {\n\t\tcase (27): {\n\t\t\tglutDestroyWindow(glutGetWindow());\n\t\t\treturn;\n\t\t}\n\t\tcase 'c':{\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tTaitBryanPose pose;\n\t\t\t\tpose.px = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1;\n\t\t\t\tpose.py = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1;\n\t\t\t\tpose.pz = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 1;\n\t\t\t\tpose.om = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.1;\n\t\t\t\tpose.fi = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.1;\n\t\t\t\tpose.ka = (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.1;\n\n\t\t\t\tEigen::Affine3d m = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\tcameras[i].pose = cameras[i].pose * m;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 't':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < cameras[i].uv.size(); j++){\n\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(cameras[i].pose);\n\n\t\t\t\t\tPLine pl = get_plucker_line(lines[cameras[i].uv[j].first.index_to_line].first, lines[cameras[i].uv[j].first.index_to_line].second);\n\t\t\t\t\tEigen::Matrix<double, 2, 1> delta;\n\t\t\t\t\tobservation_equation_perspective_camera_plucker_line_tait_bryan_wc(delta, cam_params.fx, cam_params.fy, cam_params.cx, cam_params.cy, pose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka,\n\t\t\t\t\t\t\tpl(0,0), pl(1,0), pl(2,0), pl(3,0), pl(4,0), pl(5,0),\n\t\t\t\t\t\t\tcameras[i].uv[j].first.u, cameras[i].uv[j].first.v,\n\t\t\t\t\t\t\tcameras[i].uv[j].second.u, cameras[i].uv[j].second.v);\n\n\t\t\t\t\tEigen::Matrix<double, 2, 6, Eigen::RowMajor> jacobian;\n\t\t\t\t\tobservation_equation_perspective_camera_plucker_line_tait_bryan_wc_jacobian(jacobian, cam_params.fx, cam_params.fy, cam_params.cx, cam_params.cy, pose.px, pose.py, pose.pz, pose.om, pose.fi, pose.ka,\n\t\t\t\t\t\t\tpl(0,0), pl(1,0), pl(2,0), pl(3,0), pl(4,0), pl(5,0),\n\t\t\t\t\t\t\tcameras[i].uv[j].first.u, cameras[i].uv[j].first.v,\n\t\t\t\t\t\t\tcameras[i].uv[j].second.u, cameras[i].uv[j].second.v);\n\n\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\tint ic_camera = i * 6;\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera    , -jacobian(0,0));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 1, -jacobian(0,1));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 2, -jacobian(0,2));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 3, -jacobian(0,3));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 4, -jacobian(0,4));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 5, -jacobian(0,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera    , -jacobian(1,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 1, -jacobian(1,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 2, -jacobian(1,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 3, -jacobian(1,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 4, -jacobian(1,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 5, -jacobian(1,5));\n\n\t\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  cauchy(delta(0,0), 1));\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  cauchy(delta(1,0), 1));\n\n\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta(1,0));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), cameras.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(cameras.size() * 6, cameras.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(cameras.size() * 6, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == cameras.size() * 6){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(cameras[i].pose);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\n\t\t\t\t\tcameras[i].pose = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase 'r':{\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tTaitBryanPose posetb = pose_tait_bryan_from_affine_matrix(cameras[i].pose);\n\t\t\t\tposetb.px += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.py += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.pz += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.om += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.fi += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tposetb.ka += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\t\tcameras[i].pose = affine_matrix_from_pose_tait_bryan(posetb);\n\t\t\t}\n\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < cameras[i].uv.size(); j++){\n\n\t\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(cameras[i].pose);\n\t\t\t\t\tEigen::Matrix<double, 2, 1> delta;\n\t\t\t\t\tPLine pl = get_plucker_line(lines[cameras[i].uv[j].first.index_to_line].first, lines[cameras[i].uv[j].first.index_to_line].second);\n\t\t\t\t\tobservation_equation_perspective_camera_plucker_line_rodrigues_wc(delta, cam_params.fx, cam_params.fy, cam_params.cx, cam_params.cy, pose.px, pose.py, pose.pz, pose.sx, pose.sy, pose.sz,\n\t\t\t\t\t\t\tpl(0,0), pl(1,0), pl(2,0), pl(3,0), pl(4,0), pl(5,0),\n\t\t\t\t\t\t\tcameras[i].uv[j].first.u, cameras[i].uv[j].first.v,\n\t\t\t\t\t\t\tcameras[i].uv[j].second.u, cameras[i].uv[j].second.v);\n\n\t\t\t\t\tEigen::Matrix<double, 2, 6, Eigen::RowMajor> jacobian;\n\t\t\t\t\tobservation_equation_perspective_camera_plucker_line_rodrigues_wc_jacobian(jacobian, cam_params.fx, cam_params.fy, cam_params.cx, cam_params.cy, pose.px, pose.py, pose.pz, pose.sx, pose.sy, pose.sz,\n\t\t\t\t\t\t\tpl(0,0), pl(1,0), pl(2,0), pl(3,0), pl(4,0), pl(5,0),\n\t\t\t\t\t\t\tcameras[i].uv[j].first.u, cameras[i].uv[j].first.v,\n\t\t\t\t\t\t\tcameras[i].uv[j].second.u, cameras[i].uv[j].second.v);\n\n\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\tint ic_camera = i * 6;\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera    , -jacobian(0,0));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 1, -jacobian(0,1));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 2, -jacobian(0,2));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 3, -jacobian(0,3));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 4, -jacobian(0,4));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 5, -jacobian(0,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera    , -jacobian(1,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 1, -jacobian(1,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 2, -jacobian(1,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 3, -jacobian(1,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 4, -jacobian(1,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 5, -jacobian(1,5));\n\n\t\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  cauchy(delta(0,0), 1));\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  cauchy(delta(1,0), 1));\n\n\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta(1,0));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), cameras.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(cameras.size() * 6, cameras.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(cameras.size() * 6, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == cameras.size() * 6){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(cameras[i].pose);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.sx += h_x[counter++];\n\t\t\t\t\tpose.sy += h_x[counter++];\n\t\t\t\t\tpose.sz += h_x[counter++];\n\n\t\t\t\t\tcameras[i].pose = affine_matrix_from_pose_rodrigues(pose);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'q':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\tfor(size_t j = 0; j < cameras[i].uv.size(); j++){\n\n\t\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(cameras[i].pose);\n\t\t\t\t\tEigen::Matrix<double, 2, 1> delta;\n\t\t\t\t\tPLine pl = get_plucker_line(lines[cameras[i].uv[j].first.index_to_line].first, lines[cameras[i].uv[j].first.index_to_line].second);\n\t\t\t\t\tobservation_equation_perspective_camera_plucker_line_quaternion_wc(delta, cam_params.fx, cam_params.fy, cam_params.cx, cam_params.cy, pose.px, pose.py, pose.pz, pose.q0, pose.q1, pose.q2, pose.q3,\n\t\t\t\t\t\t\tpl(0,0), pl(1,0), pl(2,0), pl(3,0), pl(4,0), pl(5,0),\n\t\t\t\t\t\t\tcameras[i].uv[j].first.u, cameras[i].uv[j].first.v,\n\t\t\t\t\t\t\tcameras[i].uv[j].second.u, cameras[i].uv[j].second.v);\n\n\t\t\t\t\tEigen::Matrix<double, 2, 7, Eigen::RowMajor> jacobian;\n\t\t\t\t\tobservation_equation_perspective_camera_plucker_line_quaternion_wc_jacobian(jacobian, cam_params.fx, cam_params.fy, cam_params.cx, cam_params.cy, pose.px, pose.py, pose.pz, pose.q0, pose.q1, pose.q2, pose.q3,\n\t\t\t\t\t\t\tpl(0,0), pl(1,0), pl(2,0), pl(3,0), pl(4,0), pl(5,0),\n\t\t\t\t\t\t\tcameras[i].uv[j].first.u, cameras[i].uv[j].first.v,\n\t\t\t\t\t\t\tcameras[i].uv[j].second.u, cameras[i].uv[j].second.v);\n\n\t\t\t\t\tint ir = tripletListB.size();\n\t\t\t\t\tint ic_camera = i * 7;\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera    , -jacobian(0,0));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 1, -jacobian(0,1));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 2, -jacobian(0,2));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 3, -jacobian(0,3));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 4, -jacobian(0,4));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 5, -jacobian(0,5));\n\t\t\t\t\ttripletListA.emplace_back(ir     , ic_camera + 6, -jacobian(0,6));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera    , -jacobian(1,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 1, -jacobian(1,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 2, -jacobian(1,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 3, -jacobian(1,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 4, -jacobian(1,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 5, -jacobian(1,5));\n\t\t\t\t\ttripletListA.emplace_back(ir + 1 , ic_camera + 6, -jacobian(1,6));\n\n\t\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  cauchy(delta(0,0), 1));\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  cauchy(delta(1,0), 1));\n\n\t\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta(0,0));\n\t\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta(1,0));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < cameras.size(); i++){\n\t\t\t\tint ic = i * 7;\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(cameras[i].pose);\n\n\t\t\t\tdouble delta;\n\t\t\t\tquaternion_constraint(delta, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\tEigen::Matrix<double, 1, 4> jacobian;\n\t\t\t\tquaternion_constraint_jacobian(jacobian, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\ttripletListA.emplace_back(ir, ic + 3 , -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 4 , -jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 5 , -jacobian(0,2));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 6 , -jacobian(0,3));\n\n\t\t\t\ttripletListP.emplace_back(ir, ir, 1000000.0);\n\n\t\t\t\ttripletListB.emplace_back(ir, 0, delta);\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), cameras.size() * 7);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(cameras.size() * 7, cameras.size() * 7);\n\t\t\tEigen::SparseMatrix<double> AtPB(cameras.size() * 7, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == cameras.size() * 7){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < cameras.size(); i++){\n\t\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(cameras[i].pose);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.q0 += h_x[counter++];\n\t\t\t\t\tpose.q1 += h_x[counter++];\n\t\t\t\t\tpose.q2 += h_x[counter++];\n\t\t\t\t\tpose.q3 += h_x[counter++];\n\n\t\t\t\t\tcameras[i].pose = affine_matrix_from_pose_quaternion(pose);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"c: add noise to cameras\" << std::endl;\n\tstd::cout << \"t: optimize cameras external orientation (Tait-Bryan)\" << std::endl;\n\tstd::cout << \"r: optimize cameras external orientation (Rodrigues)\" << std::endl;\n\tstd::cout << \"q: optimize cameras external orientation (Quaternion)\" << std::endl;\n}\n\nPLine get_plucker_line(const Eigen::Vector3d &from, const Eigen::Vector3d &to)\n{\n\tPLine plucker_line;\n\n\tEigen::Vector3d direction = (to-from);\n\tdirection/=direction.norm();\n\tEigen::Vector3d moment = from.cross(direction);\n\n\tplucker_line(0,0) = moment.x();\n\tplucker_line(1,0) = moment.y();\n\tplucker_line(2,0) = moment.z();\n\tplucker_line(3,0) = direction.x();\n\tplucker_line(4,0) = direction.y();\n\tplucker_line(5,0) = direction.z();\n\n\treturn plucker_line;\n}\n\n\n", "meta": {"hexsha": "2448597b99e3802dba3e3befd32667292b686480", "size": 23058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/perspective_camera_external_orientation_plucker_line.cpp", "max_stars_repo_name": "karolmajek/observation_equations", "max_stars_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-11T13:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T22:04:00.000Z", "max_issues_repo_path": "codes/c++Examples/src/perspective_camera_external_orientation_plucker_line.cpp", "max_issues_repo_name": "karolmajek/observation_equations", "max_issues_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/c++Examples/src/perspective_camera_external_orientation_plucker_line.cpp", "max_forks_repo_name": "karolmajek/observation_equations", "max_forks_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-30T22:33:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T18:21:21.000Z", "avg_line_length": 34.8835098336, "max_line_length": 236, "alphanum_fraction": 0.6396044757, "num_tokens": 7972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4135430549669355}}
{"text": "/*********************************************************************\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2018, Rice University\n*  All rights reserved.\n*\n*  Redistribution and use in source and binary forms, with or without\n*  modification, are permitted provided that the following conditions\n*  are met:\n*\n*   * Redistributions of source code must retain the above copyright\n*     notice, this list of conditions and the following disclaimer.\n*   * Redistributions in binary form must reproduce the above\n*     copyright notice, this list of conditions and the following\n*     disclaimer in the documentation and/or other materials provided\n*     with the distribution.\n*   * Neither the name of the Rice University nor the names of its\n*     contributors may be used to endorse or promote products derived\n*     from this software without specific prior written permission.\n*\n*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n*  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n*  POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************/\n\n/* Author: Zachary Kingston */\n\n#include <ompl/util/PPM.h>\n#include <boost/filesystem.hpp>\n\n#include \"ConstrainedPlanningCommon.h\"\n\nstatic const double pi2 = 2 * boost::math::constants::pi<double>();\n\n/** Torus manifold. */\nclass TorusConstraint : public ompl::base::Constraint\n{\npublic:\n    const double outer;\n    const double inner;\n\n    TorusConstraint(const double outer, const double inner, const std::string &maze)\n      : ompl::base::Constraint(3, 1), outer(outer), inner(inner), file_(maze)\n    {\n        ppm_.loadFile(maze.c_str());\n    }\n\n    void getStartAndGoalStates(Eigen::Ref<Eigen::VectorXd> start, Eigen::Ref<Eigen::VectorXd> goal) const\n    {\n        const double h = ppm_.getHeight() - 1;\n        const double w = ppm_.getWidth() - 1;\n\n        for (unsigned int x = 0; x <= w; ++x)\n            for (unsigned int y = 0; y <= h; ++y)\n            {\n                Eigen::Vector2d p = {x / w, y / h};\n\n                auto &c = ppm_.getPixel(x, y);\n                if (c.red == 255 && c.blue == 0 && c.green == 0)\n                    mazeToAmbient(p, start);\n\n                else if (c.green == 255 && c.blue == 0 && c.red == 0)\n                    mazeToAmbient(p, goal);\n            }\n    }\n\n    void function(const Eigen::Ref<const Eigen::VectorXd> &x, Eigen::Ref<Eigen::VectorXd> out) const override\n    {\n        Eigen::Vector3d c = {x[0], x[1], 0};\n        out[0] = (x - outer * c.normalized()).norm() - inner;\n    }\n\n    void jacobian(const Eigen::Ref<const Eigen::VectorXd> &x, Eigen::Ref<Eigen::MatrixXd> out) const override\n    {\n        const double xySquaredNorm = x[0] * x[0] + x[1] * x[1];\n        const double xyNorm = std::sqrt(xySquaredNorm);\n        const double denom = std::sqrt(x[2] * x[2] + (xyNorm - outer) * (xyNorm - outer));\n        const double c = (xyNorm - outer) * (xyNorm * xySquaredNorm) / (xySquaredNorm * xySquaredNorm * denom);\n        out(0, 0) = x[0] * c;\n        out(0, 1) = x[1] * c;\n        out(0, 2) = x[2] / denom;\n    }\n\n    void ambientToMaze(const Eigen::Ref<const Eigen::VectorXd> &x, Eigen::Ref<Eigen::VectorXd> out) const\n    {\n        Eigen::Vector3d c = {x[0], x[1], 0};\n\n        const double h = ppm_.getHeight();\n        const double w = ppm_.getWidth();\n\n        out[0] = std::atan2(x[2], c.norm() - outer) / pi2;\n        out[0] += (out[0] < 0);\n        out[0] *= h;\n        out[1] = std::atan2(x[1], x[0]) / pi2;\n        out[1] += (out[1] < 0);\n        out[1] *= w;\n    }\n\n    void mazeToAmbient(const Eigen::Ref<const Eigen::VectorXd> &x, Eigen::Ref<Eigen::VectorXd> out) const\n    {\n        Eigen::Vector2d a = x * pi2;\n\n        Eigen::Vector3d b = {std::cos(a[0]), 0, std::sin(a[0])};\n        b *= inner;\n        b[0] += outer;\n\n        double norm = std::sqrt(b[0] * b[0] + b[1] * b[1]);\n        out << std::cos(a[1]), std::sin(a[1]), 0;\n        out *= norm;\n        out[2] = b[2];\n    }\n\n    bool mazePixel(const Eigen::Ref<const Eigen::VectorXd> &x) const\n    {\n        const double h = ppm_.getHeight();\n        const double w = ppm_.getWidth();\n\n        if (x[0] < 0 || x[0] >= w || x[1] < 0 || x[1] >= h)\n            return false;\n\n        const ompl::PPM::Color &c = ppm_.getPixel(x[0], x[1]);\n        return !(c.red == 0 && c.blue == 0 && c.green == 0);\n    }\n\n    bool isValid(const ompl::base::State *state) const\n    {\n        auto &&x = *state->as<ob::ConstrainedStateSpace::StateType>();\n        Eigen::Vector2d coords;\n        ambientToMaze(x, coords);\n\n        return mazePixel(coords);\n    }\n\n    void dump(std::ofstream &file) const\n    {\n        file << outer << std::endl;\n        file << inner << std::endl;\n\n        boost::filesystem::path path(file_);\n        file << boost::filesystem::canonical(path).string() << std::endl;\n    }\n\nprivate:\n    const std::string file_;\n    ompl::PPM ppm_;\n};\n\nbool torusPlanningOnce(ConstrainedProblem &cp, enum PLANNER_TYPE planner, bool output)\n{\n    cp.setPlanner(planner);\n\n    // Solve the problem\n    ob::PlannerStatus stat = cp.solveOnce(output, \"torus\");\n\n    if (output)\n    {\n        OMPL_INFORM(\"Dumping problem information to `torus_info.txt`.\");\n        std::ofstream infofile(\"torus_info.txt\");\n        infofile << cp.type << std::endl;\n        dynamic_cast<TorusConstraint *>(cp.constraint.get())->dump(infofile);\n        infofile.close();\n    }\n\n    cp.atlasStats();\n\n    if (output)\n        cp.dumpGraph(\"torus\");\n\n    return stat;\n}\n\nbool torusPlanningBench(ConstrainedProblem &cp, std::vector<enum PLANNER_TYPE> &planners)\n{\n    cp.setupBenchmark(planners, \"torus\");\n    cp.runBenchmark();\n    return 0;\n}\n\nbool torusPlanning(bool output, enum SPACE_TYPE space, std::vector<enum PLANNER_TYPE> &planners,\n                   struct ConstrainedOptions &c_opt, struct AtlasOptions &a_opt, bool bench, double outer, double inner,\n                   const std::string &maze)\n{\n    // Create the ambient space state space for the problem.\n    auto rvss = std::make_shared<ob::RealVectorStateSpace>(3);\n\n    ob::RealVectorBounds bounds(3);\n    bounds.setLow(-(outer + inner));\n    bounds.setHigh(outer + inner);\n\n    rvss->setBounds(bounds);\n\n    // Create a shared pointer to our constraint.\n    auto constraint = std::make_shared<TorusConstraint>(outer, inner, maze);\n\n    ConstrainedProblem cp(space, rvss, constraint);\n    cp.setConstrainedOptions(c_opt);\n    cp.setAtlasOptions(a_opt);\n\n    Eigen::Vector3d start, goal;\n    constraint->getStartAndGoalStates(start, goal);\n\n    cp.setStartAndGoalStates(start, goal);\n    cp.ss->setStateValidityChecker(std::bind(&TorusConstraint::isValid, constraint, std::placeholders::_1));\n\n    if (!bench)\n        return torusPlanningOnce(cp, planners[0], output);\n    else\n        return torusPlanningBench(cp, planners);\n}\n\nauto help_msg = \"Shows this help message.\";\nauto output_msg = \"Dump found solution path (if one exists) in plain text and planning graph in GraphML to \"\n                  \"`torus_path.txt` and `torus_graph.graphml` respectively.\";\nauto bench_msg = \"Do benchmarking on provided planner list.\";\nauto outer_msg = \"Outer radius of torus.\";\nauto inner_msg = \"Inner radius of torus.\";\nauto maze_msg = \"Filename of maze image (in .ppm format) to use as obstacles on the surface of the torus.\";\n\nint main(int argc, char **argv)\n{\n    bool output, bench;\n    enum SPACE_TYPE space = PJ;\n    std::vector<enum PLANNER_TYPE> planners = {RRT};\n\n    struct ConstrainedOptions c_opt;\n    struct AtlasOptions a_opt;\n\n    double outer, inner;\n    boost::filesystem::path path(__FILE__);\n    std::string maze = (path.parent_path() / \"mazes/thick.ppm\").string();\n\n    po::options_description desc(\"Options\");\n    desc.add_options()(\"help,h\", help_msg);\n    desc.add_options()(\"output,o\", po::bool_switch(&output)->default_value(false), output_msg);\n    desc.add_options()(\"bench\", po::bool_switch(&bench)->default_value(false), bench_msg);\n    desc.add_options()(\"outer\", po::value<double>(&outer)->default_value(2), outer_msg);\n    desc.add_options()(\"inner\", po::value<double>(&inner)->default_value(1), inner_msg);\n    desc.add_options()(\"maze,m\", po::value<std::string>(&maze), maze_msg);\n\n    addSpaceOption(desc, &space);\n    addPlannerOption(desc, &planners);\n    addConstrainedOptions(desc, &c_opt);\n    addAtlasOptions(desc, &a_opt);\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n\n    if (vm.count(\"help\"))\n    {\n        std::cout << desc << std::endl;\n        return 1;\n    }\n\n    if (maze == \"\")\n    {\n        OMPL_ERROR(\"--maze is a required.\");\n        return 1;\n    }\n\n    return torusPlanning(output, space, planners, c_opt, a_opt, bench, outer, inner, maze);\n}\n", "meta": {"hexsha": "d5d6a3e99519c6e72be39afd1144994ed57d294e", "size": 9399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/constraint/ConstrainedPlanningTorus.cpp", "max_stars_repo_name": "jingxixu/ompl", "max_stars_repo_head_hexsha": "91aa14ef925e49d30980776411a76a1de719dde3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "demos/constraint/ConstrainedPlanningTorus.cpp", "max_issues_repo_name": "jingxixu/ompl", "max_issues_repo_head_hexsha": "91aa14ef925e49d30980776411a76a1de719dde3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demos/constraint/ConstrainedPlanningTorus.cpp", "max_forks_repo_name": "jingxixu/ompl", "max_forks_repo_head_hexsha": "91aa14ef925e49d30980776411a76a1de719dde3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-05T12:23:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T12:23:32.000Z", "avg_line_length": 34.5551470588, "max_line_length": 120, "alphanum_fraction": 0.6198531759, "num_tokens": 2469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581097540519, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.41336135300132854}}
{"text": "#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <utility/include_all.h>\n#include <utility/iterator.h>\n#include <utility/math.h>\n#include <utility/unit_math.h>\n#include <vector>\n  \n#ifndef TESTING\nstruct virtual_particles {\n  int32_t requiredSlices_x, requiredSlices_y, requiredSlices_z;\n  float r;\n  value_unit<float4, SI::m> p;\n  value_unit<float4, SI::m> c;\n  bool valid = false;\n\n  template <typename V, typename U> virtual_particles(U &&position, V &&volume, float spacing) {\n    p = position;\n    c = position; // float4_u<SI::m>(0., 0., 0., p.val.w);\n    float radius = pow(volume.val / (4.f / 3.f * CUDART_PI_F), 1.f / 3.f);\n    float h = p.val.w * Kernel<kernel_kind::spline4>::kernel_size();\n    valid = true;\n\n    r = spacing * radius;\n\n    auto k = static_cast<int32_t>(floor(c.val.z / r * 3. / (2. * sqrt(6.))));\n    auto j = static_cast<int32_t>(floor(c.val.y / r / sqrt(3.) - 1. / 3. * (k % 2)));\n    auto i = static_cast<int32_t>(floor((c.val.x / r - (j + k) % 2) / 2.));\n    c = value_unit<float4, SI::m>{2.f * i + ((j + k) % 2), sqrtf(3.f) * (j + 1.f / 3.f * (k % 2)),\n                                  2.f * sqrtf(6.f) / 3.f * k, 0.f};\n    c = value_unit<float4, SI::m>{c.val.x * r, c.val.y * r, c.val.z * r, 0.f};\n    // std::cout << c.val.x << \", \" << c.val.y << \", \" << c.val.z << std::endl;\n    c = value_unit<float4, SI::m>{0.f, 0.f, 0.f, 0.f};\n    requiredSlices_x = 2 * static_cast<int32_t>(ceil(h / r));\n    requiredSlices_y = 2 * static_cast<int32_t>(ceil(h / (sqrtf(3.f) * r)));\n    requiredSlices_z = 2 * static_cast<int32_t>(ceil(h / r * 3.f / (sqrtf(6.f) * 2.f)));\n  }\n  struct neighbor_it {\n    const int32_t requiredSlices_x, requiredSlices_y, requiredSlices_z;\n    const float r;\n    value_unit<float4, SI::m> p;\n    value_unit<float4, SI::m> s;\n    value_unit<float4, SI::m> c;\n    int32_t i, j, k;\n\n    neighbor_it(int32_t x_len, int32_t y_len, int32_t z_len, float r, value_unit<float4, SI::m> pos,\n                value_unit<float4, SI::m> center, int32_t _x, int32_t _y, int32_t _z)\n        : requiredSlices_x(x_len), requiredSlices_y(y_len), requiredSlices_z(z_len), r(r), p(pos), c(center), i(_x),\n          j(_y), k(_z) {\n      increment();\n    }\n\n    value_unit<float4, SI::m> operator*() { return s; }\n    bool operator==(const neighbor_it &rawIterator) const { return (k == rawIterator.k); }\n    bool operator!=(const neighbor_it &rawIterator) const { return (k != rawIterator.k); }\n\n    void increment() {\n      //using namespace math::ops;\n      bool in_range = false;\n      do {\n        i++;\n        if (i == requiredSlices_x + 1) {\n          i = -requiredSlices_x;\n          j++;\n          if (j == requiredSlices_y + 1) {\n            j = -requiredSlices_y;\n            k++;\n          }\n        }\n        float4 initial{2.f * i + ((j + k) % 2), sqrtf(3.f) * (j + 1.f / 3.f * (k % 2)), 2.f * sqrtf(6.f) / 3.f * k,\n                       0.f};\n\n        s = value_unit<float4, SI::m>{c.val.x + initial.x * r, c.val.y + initial.y * r, c.val.z + initial.z * r,\n                                      p.val.w};\n        //float dist = math::sqdistance3(p.val, s.val);\n        //dist = sqrt(dist);\n        in_range = true; // dist < (p.val.w *\n                         // Kernel<kernel_kind::spline4>::kernel_size());\n                         // s.val.w = 1. - d / (p.val.w *\n        // Kernel<kernel_kind::spline4>::kernel_size());\n      } while (k != requiredSlices_z + 1 && !(in_range));\n    }\n\n    neighbor_it &operator++() {\n      increment();\n      return (*this);\n    }\n    const neighbor_it operator++(int) {\n      auto temp(*this);\n      increment();\n      return temp;\n    }\n  };\n  neighbor_it begin() const {\n    return neighbor_it{requiredSlices_x,\n                       requiredSlices_y,\n                       requiredSlices_z,\n                       r,\n                       p,\n                       c,\n                       -requiredSlices_x,\n                       -requiredSlices_y,\n                       !valid ? requiredSlices_z + 1 : -requiredSlices_z};\n  }\n  neighbor_it end() const {\n    return neighbor_it{requiredSlices_x, requiredSlices_y, requiredSlices_z,    r, p, c,\n                       requiredSlices_x, requiredSlices_y, requiredSlices_z + 1};\n  }\n  neighbor_it cbegin() const {\n    return neighbor_it{requiredSlices_x,\n                       requiredSlices_y,\n                       requiredSlices_z,\n                       r,\n                       p,\n                       c,\n                       -requiredSlices_x,\n                       -requiredSlices_y,\n                       !valid ? requiredSlices_z + 1 : -requiredSlices_z};\n  }\n  neighbor_it cend() const {\n    return neighbor_it{requiredSlices_x, requiredSlices_y, requiredSlices_z,    r, p, c,\n                       requiredSlices_x, requiredSlices_y, requiredSlices_z + 1};\n  }\n};\n\ntemplate <typename T> auto print_val(const std::string& str, T val) {\n  std::cout << std::setw(32) << str << \" = \" << std::setw(24)\n            << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << val.val << \" -> \" << std::hexfloat\n            << val.val << std::defaultfloat << std::endl;\n};\ntemplate <> auto print_val<float>(const std::string& str, float val) {\n  std::cout << std::setw(32) << str << \" = \" << std::setw(24)\n            << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << val << \" -> \" << std::hexfloat\n            << val << std::defaultfloat << std::endl;\n};\ntemplate <> auto print_val<int32_t>(const std::string& str, int32_t val) {\n  std::cout << std::setw(32) << str << \" = \" << val << std::endl;\n};\n\n#define PRINT(x) print_val(#x, x);\n\ntemplate <kernel_kind K = kernel_kind::spline4, typename T> hostDeviceInline auto supportFromVol(T volume) {\n  auto target_neighbors = Kernel<K>::neighbor_number;\n  auto kernel_epsilon = (1.f) * powf((target_neighbors)*PI4O3_1, 1.f / 3.f) / Kernel<K>::kernel_size();\n  auto h = kernel_epsilon * math::power<ratio<1, 3>>(volume);\n  return h;\n}\n\ntemplate <typename C> auto createLUT(C func, int32_t steps, float spacing) {\n  float_u<SI::volume> volume(1.f);\n  auto h = supportFromVol(volume);\n  auto H = h * Kernel<kernel_kind::spline4>::kernel_size<float>();\n  auto step = H / (static_cast<float>(steps)) * 2.f;\n\n  auto current_position = float4_u<SI::m>{0.f, 0.f, 0.f, h.val};\n  auto center_position = float4_u<SI::m>{0.f, 0.f, 0.f, h.val};\n\n  using res_t = decltype(math::unit_get<1>(func(current_position, current_position)) * volume);\n  std::vector<res_t> LUT;\n\n  for (int32_t i = 0; i < steps; ++i) {\n    math::unit_assign<1>(current_position, H - step * static_cast<float>(i));\n    res_t density{0.f};\n    for (const auto &var : virtual_particles(center_position, volume, spacing)) {\n      if (math::unit_get<1>(var) > 0._m){\n        continue;\n\t  }\n      density += volume * math::unit_get<1>(func(current_position, var));\n    }\n    LUT.push_back(density);\n  }\n  return LUT;\n}\n\nauto createCounterLUT(int32_t steps, float spacing) {\n  float_u<SI::volume> volume(1.f);\n  auto h = supportFromVol(volume);\n  auto H = h * Kernel<kernel_kind::spline4>::kernel_size<float>();\n  auto step = H / (static_cast<float>(steps)) * 2.f;\n\n  auto current_position = float4_u<SI::m>{0.f, 0.f, 0.f, h.val};\n  auto center_position = float4_u<SI::m>{0.f, 0.f, 0.f, h.val};\n\n  std::vector<int32_t> LUT;\n\n  for (int32_t i = 0; i < steps; ++i) {\n    math::unit_assign<1>(current_position, H - step * static_cast<float>(i));\n    int32_t counter = 0;\n    for (const auto &var : virtual_particles(center_position, volume, spacing)) {\n      if (math::unit_get<1>(var) > 0._m){\n        continue;\n\t  }\n      if (spline4_kernel(current_position, var) > 0.f){\n        counter++;\n\t  }\n    }\n    LUT.push_back(counter);\n  }\n  return LUT;\n}\n\ntemplate <typename C> auto create4DLUT(C func, int32_t steps, float spacing) {\n  float_u<SI::volume> volume(1.f);\n  auto h = supportFromVol(volume);\n  auto H = h * Kernel<kernel_kind::spline4>::kernel_size<float>();\n  auto step = H / (static_cast<float>(steps)) * 2.f;\n\n  auto current_position = float4_u<SI::m>{0.f, 0.f, 0.f, h.val};\n  auto center_position = float4_u<SI::m>{0.f, 0.f, 0.f, h.val};\n\n  using res_t = decltype((func(current_position, current_position)) * volume);\n  std::vector<res_t> LUT;\n\n  for (int32_t i = 0; i < steps; ++i) {\n    math::unit_assign<1>(current_position, H - step * static_cast<float>(i));\n    res_t density{0.f};\n    for (const auto &var : virtual_particles(center_position, volume, spacing)) {\n      if (math::unit_get<1>(var) > 0._m){\n        continue;\n\t  }\n      density += volume * (func(current_position, var));\n    }\n    LUT.push_back(density);\n  }\n  return LUT;\n}\n\ntemplate <typename T> auto printLUT(const std::string& name, const std::string& type, T LUT) {\n  std::cout << \"std::vector<\" << type << \"> \" << name << \"{ \";\n  for (auto v : LUT) {\n    std::cout << std::scientific << std::setprecision(std::numeric_limits<float>::digits10 + 1)\n              << static_cast<float>(math::unit_get<1>(v).val) << \"f, \";\n  }\n  std::cout << \"};\" << std::endl;\n}\n\nauto printLUT(const std::string& name, const std::vector<int32_t>& LUT) {\n  std::cout << \"std::vector<int32_t> \" << name << \"{ \";\n  for (auto v : LUT) {\n    std::cout << v << \", \";\n  }\n  std::cout << \"};\" << std::endl;\n}\n#include <config/config.h>\n#include <fstream>\n#ifdef _WIN32\n#include <experimental/filesystem>\nnamespace fs = std::experimental::filesystem;\n#else\n#include <boost/filesystem.hpp>\nnamespace fs = boost::filesystem;\n#endif\n\ntemplate <typename T> auto writeLUT(const std::string& name, const std::string& type, const std::vector<T>& LUT) {\n  fs::path bin_dir(binaryDirectory);\n  auto file = bin_dir / \"config\" / name;\n  file.replace_extension(\"h\");\n\n  if (fs::exists(file)) {\n    if (fs::exists(__FILE__)) {\n      auto input_ts = fs::last_write_time(__FILE__);\n      auto output_ts = fs::last_write_time(file);\n      if (input_ts <= output_ts){\n        return;\n\t  }\n    }\n  }\n  std::cout << \"Writing \" << file.string() << std::endl;\n\n  std::ofstream output(file.string());\n  output << \"std::vector<\" << type << \"> \" << name << \"{ \";\n  int32_t ctr = 0;\n  for (auto v : LUT) {\n    output << std::scientific << std::setprecision(std::numeric_limits<float>::digits10 + 1)\n           << static_cast<float>(math::unit_get<1>(v).val) << \"f, \" << (ctr++ % 5 == 0 ? \"\\n\" : \"\");\n  }\n  output << \"};\" << std::endl;\n  output.close();\n}\nauto writeLUT(const std::string& name, const std::vector<int32_t>& LUT) {\n  fs::path bin_dir(binaryDirectory);\n  auto file = bin_dir / \"config\" / name;\n  file.replace_extension(\"h\");\n  if (fs::exists(file)) {\n    if (fs::exists(__FILE__)) {\n      auto input_ts = fs::last_write_time(__FILE__);\n      auto output_ts = fs::last_write_time(file);\n      if (input_ts <= output_ts){\n        return;\n\t  }\n    }\n  }\n  std::cout << \"Writing \" << file.string() << std::endl;\n  std::ofstream output(file.string());\n  int32_t ctr = 0;\n  output << \"std::vector<int32_t> \" << name << \"{ \";\n  for (auto v : LUT) {\n    output << v << \", \" << (ctr++ % 10 == 0 ? \"\\n\" : \"\");\n  }\n  output << \"};\" << std::endl;\n  output.close();\n}\n\nint main() {\n  std::cout << \"Running LUT generation program\" << std::endl;\n  using pos_t = float4_u<SI::m>;\n  bool test_spline4Kernel_LUT = false;\n  bool test_spline4Gradient_LUT = false;\n  bool test_estimateSpline4Gradient_LUT = false;\n  bool test_testSpikyGradient_LUT = false;\n\n  float_u<SI::volume> volume(1.f);\n  auto h = supportFromVol(volume);\n  auto H = h * Kernel<kernel_kind::spline4>::kernel_size<float>();\n\n  auto position = float4_u<SI::m>{H.val / 2.f, 0.f, 0.f, h.val};\n\n  float r = math::brentsMethod(\n      [=](float_u<> radius) {\n        float_u<> density = -1.f;\n        for (const auto &var : virtual_particles(position, volume, math::getValue(radius))) {\n          auto kernel = spline4_kernel(position, var);\n          density += volume * kernel;\n        }\n        return density;\n      },\n      0.7f, 1.1f, 1e-7f, 10000);\n\n  auto LUT = createLUT([](pos_t a, pos_t b) { return spline4_kernel(a, b); }, 2048, r);\n  auto spline4gradientLUT = createLUT([](pos_t a, pos_t b) { return spline4_gradient(a, b); }, 2048, r);\n  auto spikygradientLUT =\n      createLUT([](pos_t a, pos_t b) { return PressureKernel<kernel_kind::spline4>::gradient(a, b); }, 2048, r);\n  auto xbarLUT = createLUT([](pos_t a, pos_t b) { return b * spline4_kernel(a, b); }, 2048, r * 0.9f);\n  auto ctrLUT = createCounterLUT(2048, r * 0.9f);\n\n  // printLUT(\"boundaryLut\" , \"float\", LUT);\n  // printLUT(\"pressureLut\", \"float\", spikygradientLUT);\n  // printLUT(\"xbarLut\", \"float\", xbarLUT);\n  // printLUT(\"ctrLut\", ctrLUT);\n\n  writeLUT(\"boundaryLut\", \"float\", LUT);\n  writeLUT(\"pressureLut\", \"float\", spline4gradientLUT);\n  // writeLUT(\"pressureLut\", \"float\", spikygradientLUT);\n  writeLUT(\"xbarLut\", \"float\", xbarLUT);\n  writeLUT(\"ctrLut\", ctrLUT);\n\n  auto lookup = [&](float_u<SI::m> dist, float_u<SI::m> H, float_u<SI::volume> vol, auto LUT) {\n    auto step = H / (static_cast<float>(LUT.size()) + 1) * 2.f;\n    int32_t idx =\n        math::clamp(static_cast<int32_t>(LUT.size()) - math::castTo<int32_t>(floor((dist.val + H.val) / step.val)), 0, static_cast<int32_t>(LUT.size()) - 1);\n    return LUT[idx] / vol;\n  };\n  auto estimateGradient = [&](float_u<SI::m> dist, float_u<SI::m> H, float_u<SI::volume> vol, auto LUT) {\n    auto step = H / (static_cast<float>(LUT.size()) + 1) * 2.f;\n    int32_t idx =\n        math::clamp(static_cast<int32_t>(LUT.size()) - math::castTo<int32_t>(floor((dist.val + H.val) / step.val)), 1, static_cast<int32_t>(LUT.size()) - 2);\n    auto a = LUT[idx + 1] / vol;\n    auto b = LUT[idx] / vol;\n    auto ab = (b - a) / step;\n    return ab;\n  };\n  auto lookupGradient = [&](float_u<SI::m> dist, float_u<SI::m> H, float_u<SI::volume> vol, auto LUT) {\n    auto step = H / (static_cast<float>(LUT.size() + 1)) * 2.f;\n    auto h_0 = support_from_volume(float_u<SI::volume>(1.f));\n    auto h_c = support_from_volume(vol);\n\n    auto ratio = h_0 / h_c;\n    int32_t idx =\n        math::clamp(static_cast<int32_t>(LUT.size()) - math::castTo<int32_t>(floor((dist.val + H.val) / step.val)), 0, static_cast<int32_t>(LUT.size()) - 1);\n    return LUT[idx] / vol * ratio;\n  };\n\n  volume /= 10.f;\n  h = support_from_volume(volume);\n  H = h * kernelSize();\n  position = float4_u<SI::m>{0.f, 2.f, 0.f, h.val};\n\n  auto step = H / 32;\n  // test kernel LUT\n  if (test_spline4Kernel_LUT) {\n    std::cout << std::endl\n              << \"Testing LUT for \"\n              << \"spline4 kernel\" << std::endl;\n    for (float_u<SI::m> it = H; it >= -H - step; it -= step) {\n      float_u<SI::recip_3<SI::m>> kernelSum{0.f};\n      math::unit_assign<1>(position, it);\n      for (const auto &var : virtual_particles(position, volume, r)) {\n        if (math::unit_get<1>(var) > 0.0_m){\n          continue;\n\t\t}\n        kernelSum += kernel(position, var);\n      }\n\n      std::cout << std::setw(7) << std::fixed << std::setprecision(4) << it / H;\n      std::cout << \" -> \" << std::fixed << std::setprecision(4) << std::setw(18)\n                << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << math::unit_get<1>(kernelSum).val\n                << \" : \" << std::setw(18) << std::setprecision(std::numeric_limits<long double>::digits10 + 1)\n                << lookup(it, H, volume, LUT).val << \" : \" << std::setw(18)\n                << std::setprecision(std::numeric_limits<long double>::digits10 + 1)\n                << lookup(it, H, volume, LUT) / math::unit_get<1>(kernelSum) << std::endl;\n    }\n  }\n  if (test_spline4Gradient_LUT) {\n    std::cout << std::endl\n              << \"Testing LUT for \"\n              << \"spline4 gradient\" << std::endl;\n    for (float_u<SI::m> it = H; it >= -H - step; it -= step) {\n      float4_u<SI::multiply_ratios<SI::m, ratio<-4, 1>>> gradientSum{0.f, 0.f, 0.f, 0.f};\n      math::unit_assign<1>(position, it);\n      for (const auto &var : virtual_particles(position, volume, r)) {\n        if (math::unit_get<1>(var) > 0._m){\n          continue;\n\t\t}\n        gradientSum += spline4_gradient(position, var);\n      }\n\n      std::cout << std::setw(7) << std::fixed << std::setprecision(4) << it / H;\n      std::cout << \" -> \" << std::fixed << std::setprecision(4) << std::setw(18)\n                << std::setprecision(std::numeric_limits<long double>::digits10 + 1)\n                << math::unit_get<1>(gradientSum).val << \" : \" << std::setw(18)\n                << std::setprecision(std::numeric_limits<long double>::digits10 + 1)\n                << lookupGradient(it, H, volume, spline4gradientLUT).val << \" : \" << std::setw(18)\n                << std::setprecision(std::numeric_limits<long double>::digits10 + 1)\n                << lookupGradient(it, H, volume, spline4gradientLUT) / math::unit_get<1>(gradientSum) << std::endl;\n    }\n  }\n  if (test_estimateSpline4Gradient_LUT) {\n    std::cout << std::endl\n              << \"Testing LUT for \"\n              << \"estimating spline4 gradient\" << std::endl;\n    for (float_u<SI::m> it = H; it >= -H - step; it -= step) {\n      float4_u<SI::SI_Unit<SI::m, ratio<-4, 1>>> gradientSum{0.f, 0.f, 0.f, 0.f};\n      math::unit_assign<1>(position, it);\n      for (const auto &var : virtual_particles(position, volume, r)) {\n        if (math::unit_get<1>(var) > 0._m){\n          continue;\n\t\t}\n        gradientSum += spline4_gradient(position, var);\n      }\n\n      std::cout << std::setw(7) << std::fixed << std::setprecision(4) << it / H;\n      std::cout << \" -> \" << std::fixed << std::setprecision(4) << std::setw(18)\n                << std::setprecision(std::numeric_limits<long double>::digits10 + 1)\n                << math::unit_get<1>(gradientSum).val << \" : \" << std::setw(18)\n                << std::setprecision(std::numeric_limits<long double>::digits10 + 1)\n                << estimateGradient(it, H, volume, LUT).val << \" : \" << std::setw(18)\n                << std::setprecision(std::numeric_limits<long double>::digits10 + 1)\n                << estimateGradient(it, H, volume, LUT) / math::unit_get<1>(gradientSum) << std::endl;\n    }\n  }\n  if (test_testSpikyGradient_LUT) {\n    std::cout << std::endl\n              << \"Testing LUT for \"\n              << \"spiky gradient\" << std::endl;\n    for (float_u<SI::m> it = H; it >= -H - step; it -= step) {\n      float4_u<SI::SI_Unit<SI::m, ratio<-4, 1>>> gradientSum{0.f, 0.f, 0.f, 0.f};\n      math::unit_assign<1>(position, it);\n      for (const auto &var : virtual_particles(position, volume, r)) {\n        if (math::unit_get<1>(var) > 0._m){\n          continue;\n\t\t}\n        gradientSum += PressureKernel<kernel_kind::spline4>::gradient(position, var);\n      }\n\n      std::cout << std::setw(7) << std::fixed << std::setprecision(4) << it / H;\n      std::cout << \" -> \" << std::fixed << std::setprecision(4) << std::setw(18)\n                << std::setprecision(std::numeric_limits<long double>::digits10 + 1)\n                << math::unit_get<1>(gradientSum).val << \" : \" << std::setw(18)\n                << std::setprecision(std::numeric_limits<long double>::digits10 + 1)\n                << lookupGradient(it, H, volume, spikygradientLUT).val << \" : \" << std::setw(18)\n                << std::setprecision(std::numeric_limits<long double>::digits10 + 1)\n                << lookupGradient(it, H, volume, spikygradientLUT) / math::unit_get<1>(gradientSum) << std::endl;\n    }\n  }\n  // getchar();\n}\n#else\nstruct mem {\n  int *x, *y, *z, *w;\n};\n\nint main() {\n  mem arrays;\n  cache_arrays((m_01, x));\n  cache_arrays((m_02, x), (m_03, y));\n\n  float4_u<SI::m> test_x;\n  float4_u<SI::velocity> test_v;\n  float_u<SI::s> test_s;\n  test_x + test_v *test_s;\n  test_x = test_v * test_s;\n  std::cout << SI::is_same_unit<decltype(test_x)::unit, decltype(test_v * test_s)::unit>::value << std::endl;\n\n  using Tuple1 = decltype(test_x)::unit;\n  using Tuple2 = decltype(test_v * test_s)::unit;\n\n  std::cout << typeid(Tuple1).name() << std::endl;\n  std::cout << typeid(Tuple2).name() << std::endl;\n  std::cout << typeid(SI::flatten2<Tuple2>::type).name() << std::endl;\n\n  // constexpr auto s1 = std::tuple_size<Tuple1>::value;\n  // constexpr auto s2 = std::tuple_size<Tuple2>::value;\n\n  return 0;\n}\n#endif", "meta": {"hexsha": "e6ff088423c7e147ea5adf2459ccc8bfdce05c0e", "size": 20163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "metaCode/LUTCode/Source.cpp", "max_stars_repo_name": "all-in-one-of/openMaelstrom", "max_stars_repo_head_hexsha": "4e293eccecf9991135890c72e54e5b41dde297d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "metaCode/LUTCode/Source.cpp", "max_issues_repo_name": "all-in-one-of/openMaelstrom", "max_issues_repo_head_hexsha": "4e293eccecf9991135890c72e54e5b41dde297d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "metaCode/LUTCode/Source.cpp", "max_forks_repo_name": "all-in-one-of/openMaelstrom", "max_forks_repo_head_hexsha": "4e293eccecf9991135890c72e54e5b41dde297d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6129666012, "max_line_length": 157, "alphanum_fraction": 0.5784853444, "num_tokens": 6186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8397339596505965, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.41330709210186883}}
{"text": "#define GLM_ENABLE_EXPERIMENTAL 1\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <Halide.h>\n#include <fstream>\n#include <glm/ext.hpp>\n#include <glm/glm.hpp>\n#include <halide_image_io.h>\n#include <iostream>\n#include <stdio.h>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <ImfRgbaFile.h>\n#include <ImfStringAttribute.h>\n#include <ImfMatrixAttribute.h>\n#include <ImfArray.h>\n#include <algorithm>\n#include <ImfNamespace.h>\n#include <tuple>\n#include <math.h>\n\nnamespace IMF = OPENEXR_IMF_NAMESPACE;\n\nusing namespace IMF;\nusing namespace IMATH_NAMESPACE;\n\nusing std::string;\nusing std::stringstream;\nusing std::vector;\n\nusing namespace std;\nusing namespace Halide;\nusing namespace Halide::Tools;\nusing namespace Eigen;\n\nusing Vector4h = Matrix<Halide::Expr, 4, 1>;\nusing Matrix4h = Matrix<Halide::Expr, 4, 4>;\n\nVar x, y, c;\n\nstruct Point\n{\n    float x;\n    float y;\n    float z;\n    uint16_t r;\n    uint16_t g;\n    uint16_t b;\n};\n\nMatrix4h read4x4MatFromCSV(string csvFile)\n{\n    Matrix4h transfMat;\n    ifstream in(csvFile);\n    vector<float> floatVec;\n    if (in)\n    {\n        string line;\n        while (getline(in, line))\n        {\n            stringstream sep(line);\n            string field;\n            while (getline(sep, field, ','))\n            {\n                float val = stod(field);\n                floatVec.push_back(val);\n            }\n        }\n    }\n    transfMat << floatVec[0], floatVec[1], floatVec[2], floatVec[3],\n        floatVec[4], floatVec[5], floatVec[6], floatVec[7],\n        floatVec[8], floatVec[9], floatVec[10], floatVec[11],\n        floatVec[12], floatVec[13], floatVec[14], floatVec[15];\n    return transfMat;\n}\n\nostream &operator<<(ostream &os, const Matrix4h &m)\n{\n    os << m(0, 0) << \" \" << m(0, 1) << \" \" << m(0, 2) << \" \" << m(0, 3) << \"\\n\"\n       << m(1, 0) << \" \" << m(1, 1) << \" \" << m(1, 2) << \" \" << m(1, 3) << \"\\n\"\n       << m(2, 0) << \" \" << m(2, 1) << \" \" << m(2, 2) << \" \" << m(2, 3) << \"\\n\"\n       << m(3, 0) << \" \" << m(3, 1) << \" \" << m(3, 2) << \" \" << m(3, 3) << endl;\n    return os;\n}\n\nvoid saveImageEXR(Expr result, int width, int height, const char fileName[])\n{\n    result = cast<float>(result);\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y) = result;\n    Buffer<float> output(width, height);\n    byteResult.compile_jit(target);\n    byteResult.realize(output);\n\n    Array2D<Rgba> pixels;\n    pixels.resizeErase(height, width);\n    for (int row{0}; row < height; row++)\n    {\n        for (int col{0}; col < width; col++)\n        {\n            pixels[row][col].r = output(col, row);\n            pixels[row][col].g = output(col, row);\n            pixels[row][col].b = output(col, row);\n        }\n    }\n    RgbaOutputFile file(fileName, width, height, WRITE_RGBA);\n    file.setFrameBuffer(&pixels[0][0], 1, width);\n    file.writePixels(height);\n}\n\nvoid saveImageRaw(Expr result, size_t width, size_t height, const string &basename)\n{\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y) = cast<uint8_t>(result);\n    byteResult.compile_jit(target);\n    Buffer<uint8_t> output(width, height);\n    byteResult.realize(output);\n    stringstream filename;\n    filename << basename;\n    save_image(output, filename.str());\n}\n\nvoid saveImage(Expr result, size_t width, size_t height, const string &basename)\n{\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y) = cast<uint8_t>(clamp(result, 0.0f, 1.0f) * 255.0f);\n    byteResult.compile_jit(target);\n    Buffer<uint8_t> output(width, height);\n    byteResult.realize(output);\n    stringstream filename;\n    filename << basename;\n    save_image(output, filename.str());\n}\n\nostream &operator<<(ostream &os, const Vector4h &v)\n{\n    os << v(0) << \"\\n\"\n       << v(1) << \"\\n\"\n       << v(2) << \"\\n\"\n       << v(3) << endl;\n    return os;\n}\n\nVector4h makeAxBzCLine(Vector4h a, Vector4h b)\n{\n    Vector4h result;\n    result(0) = a(2) - b(2);\n    result(1) = b(0) - a(0);\n    result(2) = a(0) * b(2) - b(0) * a(2);\n    result(3) = 1.0f;\n    return result;\n}\n\nVector4h cross3(Vector4h a, Vector4h b)\n{\n    Vector4h res;\n    res(0) = a(1) * b(2) - a(2) * b(1);\n    res(1) = a(2) * b(0) - a(0) * b(2);\n    res(2) = a(0) * b(1) - a(1) * b(0);\n    res(3) = 0;\n    return res;\n}\n\nExpr dot3(Vector4h a, Vector4h b)\n{\n    Expr res;\n    res = a(0) * b(0) + a(1) * b(1) + a(2) * b(2);\n    return res;\n}\n\ntuple<Vector4h, Vector4h> pluckerLine(Vector4h p1, Vector4h p2)\n{\n    Vector4h l;\n    Vector4h l_dash;\n    l = p1(3) * p2 - p2(3) * p1;\n    l(3) = 0;\n    l_dash = cross3(p1, p2);\n    return {l, l_dash};\n}\n\nVector4h pluckerPlane(Vector4h l, Vector4h l_dash, Vector4h pluckPt)\n{\n    Vector4h u;\n    u = -pluckPt(3) * l_dash + cross3(pluckPt, l);\n    u(3) = dot3(pluckPt, l_dash);\n    return u;\n}\n\nVector4h intersectionLinePlane(Vector4h l, Vector4h l_dash, Vector4h plPlane)\n{\n    Vector4h intersection;\n    intersection = -plPlane(3) * l + cross3(plPlane, l_dash);\n    intersection(3) = dot3(plPlane, l);\n    return intersection;\n}\n\ntemplate <typename Function>\nvoid writeBufferToXYZFile(Buffer<float> &buffer, Buffer<uint8_t> &color, string filename, string deliminator, Function condFunc)\n{\n    std::vector<Point> points;\n    for (int j = 0; j < buffer.height(); j++)\n    {\n        for (int i = 0; i < buffer.width(); i++)\n        {\n            const auto x = buffer(i, j, 0);\n            const auto y = buffer(i, j, 1);\n            const auto z = buffer(i, j, 2);\n            uint8_t r = color(i, j, 0);\n            uint8_t g = color(i, j, 1);\n            uint8_t b = color(i, j, 2);\n            if (condFunc(x, y, z))\n            {\n                continue;\n            }\n            points.push_back({x, y, z, r, g, b});\n        }\n    }\n    std::ofstream outFile;\n    outFile.open(filename);\n    outFile << points.size() << \"\\n\";\n    const auto d = deliminator;\n    for (const auto &point : points)\n    {\n        outFile << point.x << d << point.y << d << point.z << d << point.r << d << point.g << d << point.b << \"\\n\";\n    }\n}\n\nvoid writeXYZ(Expr xs, Expr ys, Expr zs, int width, int height, string filename)\n{\n    Target target = get_host_target();\n    Func result;\n    result(x, y, c) = 0.0f;\n    result(x, y, 0) = xs;\n    result(x, y, 1) = ys;\n    result(x, y, 2) = zs;\n\n    Buffer<float> output(width, height, 3);\n    result.compile_jit(target);\n    result.realize(output);\n\n    std::vector<Point> points;\n    for (int j = 0; j < output.height(); j++)\n    {\n        for (int i = 0; i < output.width(); i++)\n        {\n            const auto x = output(i, j, 0);\n            const auto y = output(i, j, 1);\n            const auto z = output(i, j, 2);\n            uint16_t zero = 0;\n            points.push_back(Point{x, y, z, zero, zero, zero});\n        }\n    }\n    std::ofstream outFile;\n    outFile.open(filename);\n    outFile << points.size() << \"\\n\";\n    const auto d = \";\";\n    for (const auto &point : points)\n    {\n        outFile << point.x << d << point.y << d << point.z << d << point.r << d << point.g << d << point.b << \"\\n\";\n    }\n}\n\nvoid debugImageEXR(Expr channel1Expr, Expr channel2Expr, Expr channel3Expr, int width, int height, const char fileName[])\n{\n    channel1Expr = cast<float>(channel1Expr);\n    channel2Expr = cast<float>(channel2Expr);\n    channel3Expr = cast<float>(channel3Expr);\n    Target target = get_host_target();\n    Func byteResult;\n    byteResult(x, y, c) = 0.0f;\n    byteResult(x, y, 0) = channel1Expr;\n    byteResult(x, y, 1) = channel2Expr;\n    byteResult(x, y, 2) = channel3Expr;\n    Buffer<float> output(width, height, 3);\n    byteResult.compile_jit(target);\n    byteResult.realize(output);\n\n    Array2D<Rgba> pixels;\n    pixels.resizeErase(height, width);\n    for (int row{0}; row < height; row++)\n    {\n        for (int col{0}; col < width; col++)\n        {\n            pixels[row][col].r = output(col, row, 0);\n            pixels[row][col].g = output(col, row, 1);\n            pixels[row][col].b = output(col, row, 2);\n        }\n    }\n    RgbaOutputFile file(fileName, width, height, WRITE_RGBA);\n    file.setFrameBuffer(&pixels[0][0], 1, width);\n    file.writePixels(height);\n}\n\nint main(int argc, char **argv)\n{\n    const string LEFTCAM_SCAN_PNG = \"images/scan/left-cam-tilt.png\";\n    const string RIGHTCAM_SCAN_PNG = \"images/scan/right-cam-tilt.png\";\n    const string DEBUG_PNG = \"images/debug/debug.png\";\n    const string CAM_MAT_PATH = \"matrices/camera-matrix.csv\";\n    const string INV_CAM_MAT_PATH = \"matrices/inv-camera-matrix.csv\";\n    const string TRANSF_LEFTCAM_PROJ_PATH = \"matrices/transf-leftcam-proj.csv\";\n    const string TRANSF_RIGHTCAM_PROJ_PATH = \"matrices/transf-rightcam-proj.csv\";\n    const string POINTCLOUD_LEFTCAM = \"pointclouds/left-cam.txt\";\n\n    Buffer<uint8_t> leftCamScan = load_image(LEFTCAM_SCAN_PNG);\n    Buffer<uint8_t> rightCamScan = load_image(RIGHTCAM_SCAN_PNG);\n    const int HEIGHT = leftCamScan.height();\n    const int WIDTH = leftCamScan.width();\n\n    Expr leftCamScanRed = leftCamScan(x, y, 0);\n    Expr leftCamScanFilterRed = leftCamScanRed * (leftCamScanRed > 80.0f);\n    Expr rightCamScanRed = rightCamScan(x, y, 0);\n    Expr rightCamScanFilterRed = rightCamScanRed * (rightCamScanRed > 80.0f);\n\n    // read matrices\n    Matrix4h camMat = read4x4MatFromCSV(CAM_MAT_PATH);\n    Matrix4h invCamMat = read4x4MatFromCSV(INV_CAM_MAT_PATH);\n    Matrix4h transfLeftCamProj = read4x4MatFromCSV(TRANSF_LEFTCAM_PROJ_PATH);\n    Matrix4h transfRightCamProj = read4x4MatFromCSV(TRANSF_RIGHTCAM_PROJ_PATH);\n\n    // define 3 points on projector to define laser scan\n    Vector4h projPt1{0.0f, 0.0f, 0.0f, 1.0f};\n    Vector4h projPt2{0.0f, 1.0f, 0.0f, 1.0f};\n    Vector4h projPt3{0.0f, 0.0f, 1.0f, 1.0f};\n\n    Vector4h projPt1_lcFrame = transfLeftCamProj * projPt1;\n    Vector4h projPt2_lcFrame = transfLeftCamProj * projPt2;\n    Vector4h projPt3_lcFrame = transfLeftCamProj * projPt3;\n\n    Vector4h projPt1_rcFrame = transfRightCamProj * projPt1;\n    Vector4h projPt2_rcFrame = transfRightCamProj * projPt2;\n    Vector4h projPt3_rcFrame = transfRightCamProj * projPt3;\n\n    const auto [projLine_lcFrame, projLineDash_lcFrame] = pluckerLine(projPt1_lcFrame, projPt2_lcFrame);\n    Vector4h projPlane_lcFrame = pluckerPlane(projLine_lcFrame, projLineDash_lcFrame, projPt3_lcFrame);\n\n    const auto [projLine_rcFrame, projLineDash_rcFrame] = pluckerLine(projPt1_rcFrame, projPt2_rcFrame);\n    Vector4h projPlane_rcFrame = pluckerPlane(projLine_rcFrame, projLineDash_rcFrame, projPt3_rcFrame);\n\n    Vector4h px_lc{x, y, 1.0f, 1.0f};\n    Vector4h norm1_lc = invCamMat * px_lc;\n    norm1_lc(3) = 1.0f;\n    Vector4h norm2_lc = norm1_lc * 2.0f;\n    norm2_lc(3) = 1.0f;\n\n    Vector4h px_rc{x, y, 1.0f, 1.0f};\n    Vector4h norm1_rc = invCamMat * px_rc;\n    norm1_rc(3) = 1.0f;\n    Vector4h norm2_rc = norm1_lc * 2.0f;\n    norm2_rc(3) = 1.0f;\n\n    const auto [pixelLine_lc, pixelLineDash_lc] = pluckerLine(norm1_lc, norm2_lc);\n    Vector4h intersection_lc = intersectionLinePlane(pixelLine_lc, pixelLineDash_lc, projPlane_lcFrame);\n\n    const auto [pixelLine_rc, pixelLineDash_rc] = pluckerLine(norm1_rc, norm2_rc);\n    Vector4h intersection_rc = intersectionLinePlane(pixelLine_rc, pixelLineDash_rc, projPlane_rcFrame);\n\n    intersection_lc *= leftCamScanFilterRed > 0;\n    intersection_lc /= intersection_lc(3);\n    debugImageEXR(intersection_lc(0), intersection_lc(1), intersection_lc(2), WIDTH, HEIGHT, \"images/debug/intersection-lc.exr\");\n    writeXYZ(intersection_lc(0), intersection_lc(1), intersection_lc(2), WIDTH, HEIGHT, POINTCLOUD_LEFTCAM);\n\n    intersection_rc *= rightCamScanFilterRed > 0;\n    intersection_rc /= intersection_rc(3);\n    writeXYZ(intersection_rc(0), intersection_rc(1), intersection_rc(2), WIDTH, HEIGHT, \"pointclouds/right-cam.txt\");\n\n    //Func result;\n    //result(x, y, c) = 0.0f;\n    //result(x, y, 0) = intersection(0);\n    //result(x, y, 1) = intersection(1);\n    //result(x, y, 2) = intersection(2);\n\n    //Buffer<float> output(WIDTH, HEIGHT, 3);\n    //result.realize(output);\n\n    //std::vector<Point> points;\n    //for (int j = 0; j < output.height(); j++)\n    //{\n    //for (int i = 0; i < output.width(); i++)\n    //{\n    //const auto x = output(i, j, 0);\n    //const auto y = output(i, j, 1);\n    //const auto z = output(i, j, 2);\n    //uint16_t zero = 0;\n    //points.push_back(Point{x, y, z, zero, zero, zero});\n    //}\n    //}\n    //std::ofstream outFile;\n    //outFile.open(POINTCLOUD_LEFTCAM);\n    //outFile << points.size() << \"\\n\";\n    //const auto d = \";\";\n    //for (const auto &point : points)\n    //{\n    //outFile << point.x << d << point.y << d << point.z << d << point.r << d << point.g << d << point.b << \"\\n\";\n    //}\n    /*\n    const float FOCAL_LEN = 36.1;\n    const float PX_DIM = 10 * 10e-6;\n    const bool POINT_CLOUD_GLOBAL_FRAME = true;\n    const bool POINT_CLOUD_PROJ_FRAME = true;\n    const string PROJECTOR_X_PNG = \"images/x-val-img.png\";\n    const string TRANSF_MAT_WORLD_TO_PROJ_CSV = \"matrices/transf-world-proj.csv\";\n    const string TRANSF_PROJ_CAM_CSV = \"matrices/transf-proj-cam.csv\";\n    const string INV_CAM_MAT_CSV = \"matrices/inv-cam-mat.csv\";\n    const string SAVE_DEPTH_IMAGE = \"images/depth_img.png\";\n    const string SAVE_XYZ_PROJ = \"pointclouds/proj.txt\";\n    const string SAVE_XYZ_WORLD = \"pointclouds/world.txt\";\n    const string NO_PROJECTOR_PNG = \"images/no-projector.png\";\n\n    Halide::Buffer<uint8_t> input = load_image(PROJECTOR_X_PNG);\n    const int HEIGHT = input.height();\n    const int WIDTH = input.width();\n\n    Matrix4h InvK = read4x4MatFromCSV(INV_CAM_MAT_CSV);\n    Matrix4h transMatProjToCam = read4x4MatFromCSV(TRANSF_PROJ_CAM_CSV);\n    Matrix4h transMatWorldToProj = read4x4MatFromCSV(TRANSF_MAT_WORLD_TO_PROJ_CSV);\n\n    cout << \"Tranformation Matrix World to Projector\" << endl;\n    cout << transMatWorldToProj << endl;\n\n    Vector4h px{x, y, 1.0f, 0.0f};\n\n    Vector4h normCam1 = InvK * px;\n    normCam1(3) = 1.0f;\n    Vector4h normCam2 = 2 * normCam1;\n    normCam2(3) = 1.0f;\n\n    Vector4h pointCam1 = transMatProjToCam * normCam1;\n    pointCam1 = pointCam1 / pointCam1(3);\n    Vector4h pointCam2 = transMatProjToCam * normCam2;\n    pointCam2 /= pointCam2(3);\n\n    const auto [camLine, camLineDash] = pluckerLine(pointCam1, pointCam2);\n    //Vector4h cameraLine = makeAxBzCLine(pointCam1, pointCam2);\n\n    Vector4h pxProj{input(x, y) / 255.0f * 1920.0f, 0.0f, 1.0f, 0.0f};\n    Vector4h normProj1 = InvK * pxProj;\n    normProj1 = normProj1 / normProj1(2);\n    normProj1(3) = 1.0f;\n    Vector4h normProj2{0.0f, 0.0f, 0.0f, 1.0f};\n    Vector4h normProj3{0.0f, 1.0f, 0.0f, 1.0f};\n\n    const auto [projLine, projLineDash] = pluckerLine(normProj2, normProj3);\n    Vector4h ProjPlane = pluckerPlane(projLine, projLineDash, normProj1);\n    Vector4h intersection = intersectionLinePlane(camLine, camLineDash, ProjPlane);\n    intersection = intersection / intersection(3);\n    intersection *= (input(x, y) > 0); // does this make sense?\n\n    Expr depth = intersection(3);\n\n    saveImage(depth, input.width(), input.height(), SAVE_DEPTH_IMAGE);\n\n    Halide::Buffer<uint8_t> color = load_image(NO_PROJECTOR_PNG);\n\n    if (POINT_CLOUD_PROJ_FRAME)\n    {\n        Func result;\n        result(x, y, c) = 0.0f;\n        result(x, y, 0) = intersection(0);\n        result(x, y, 1) = intersection(1);\n        result(x, y, 2) = intersection(2);\n\n        Buffer<float> output(input.width(), input.height(), 3);\n        result.realize(output);\n        writeBufferToXYZFile(output, color, SAVE_XYZ_PROJ, \";\", conditionProjector);\n    }\n      */\n\n    return 0;\n}\n", "meta": {"hexsha": "e9ec27ab754ac8dca171d76d4de5061317119d98", "size": 15532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "laser-scanning-stereo/cpp/scan-matching/scanMatching.cpp", "max_stars_repo_name": "olaals/prosjektoppgave", "max_stars_repo_head_hexsha": "048c5c01cf428846c76b1c27abd4c0f451056e03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "laser-scanning-stereo/cpp/scan-matching/scanMatching.cpp", "max_issues_repo_name": "olaals/prosjektoppgave", "max_issues_repo_head_hexsha": "048c5c01cf428846c76b1c27abd4c0f451056e03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "laser-scanning-stereo/cpp/scan-matching/scanMatching.cpp", "max_forks_repo_name": "olaals/prosjektoppgave", "max_forks_repo_head_hexsha": "048c5c01cf428846c76b1c27abd4c0f451056e03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6302521008, "max_line_length": 129, "alphanum_fraction": 0.629474633, "num_tokens": 4878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4132593332414179}}
{"text": "/** \\file   cmr_spirit_recon.cpp\n    \\brief  Implement some functionalities commonly used in cmr applications for spirit recon\n    \\author Hui Xue\n*/\n\n#include \"cmr_spirit_recon.h\"\n\n#include \"mri_core_utility.h\"\n#include \"mri_core_spirit.h\"\n#include \"hoNDArray_reductions.h\"\n#include \"hoNDFFT.h\"\n#include \"hoSPIRIT2DOperator.h\"\n#include \"hoLsqrSolver.h\"\n#include \"hoSPIRIT2DTDataFidelityOperator.h\"\n#include \"hoWavelet2DTOperator.h\"\n#include \"hoGdSolver.h\"\n#include <boost/make_shared.hpp>\n\nnamespace Gadgetron { \n\n    template <typename T> \n    void perform_spirit_recon_linear_2DT(const Gadgetron::hoNDArray<T>& kspace, size_t startE1, size_t endE1, const Gadgetron::hoNDArray<T>& kerIm, \n                                const Gadgetron::hoNDArray<T>& kspaceInitial, Gadgetron::hoNDArray<T>& res, size_t iter_max, double iter_thres, bool print_iter)\n    {\n        try\n        {\n            size_t RO = kspace.get_size(0);\n            size_t E1 = kspace.get_size(1);\n            size_t CHA = kspace.get_size(2);\n            size_t N = kspace.get_size(3);\n            size_t S = kspace.get_size(4);\n\n            size_t ref_N = kerIm.get_size(4);\n            size_t ref_S = kerIm.get_size(5);\n\n            if(startE1>=E1) startE1 = 0;\n            if(endE1>=E1) startE1 = 0;\n            if(startE1>endE1)\n            {\n                startE1 = 0;\n                endE1 = E1 - 1;\n            }\n\n            long long num = N*S;\n\n            hoNDArray<T> ker_Shifted(kerIm);\n            Gadgetron::hoNDFFT<typename realType<T>::Type>::instance()->ifftshift2D(kerIm, ker_Shifted);\n\n            hoNDArray<T> kspace_Shifted;\n            kspace_Shifted = kspace;\n            Gadgetron::hoNDFFT<typename realType<T>::Type>::instance()->ifftshift2D(kspace, kspace_Shifted);\n\n            hoNDArray<T> kspace_initial_Shifted;\n            bool hasInitial = false;\n            if ( kspaceInitial.dimensions_equal(&kspace) )\n            {\n                kspace_initial_Shifted = kspaceInitial;\n                Gadgetron::hoNDFFT<typename realType<T>::Type>::instance()->ifftshift2D(kspaceInitial, kspace_initial_Shifted);\n                hasInitial = true;\n            }\n\n            res = kspace;\n\n#ifdef USE_OMP\n            int numThreads = (int)num;\n            if (numThreads > omp_get_num_procs()) numThreads = omp_get_num_procs();\n            GDEBUG_CONDITION_STREAM(print_iter, \"numThreads : \" << numThreads);\n#endif // USE_OMP\n\n            long long ii;\n\n            std::vector<size_t> dim(3, 1);\n            dim[0] = RO;\n            dim[1] = E1;\n            dim[2] = CHA;\n\n#pragma omp parallel default(none) private(ii) shared(num, N, S, RO, E1, CHA, dim, startE1, endE1, ref_N, ref_S, kspace, res, kspace_Shifted, ker_Shifted, kspace_initial_Shifted, hasInitial, iter_max, iter_thres, print_iter) num_threads(numThreads) if(num>1)\n            {\n                boost::shared_ptr< hoSPIRIT2DOperator< T > > oper(new hoSPIRIT2DOperator< T >(&dim));\n                hoSPIRIT2DOperator< T >& spirit = *oper;\n                spirit.use_non_centered_fft_ = true;\n                spirit.no_null_space_ = false;\n\n                if (ref_N == 1 && ref_S == 1)\n                {\n                    boost::shared_ptr<hoNDArray<T> > ker(new hoNDArray< T >(RO, E1, CHA, CHA, ker_Shifted.begin()));\n                    spirit.set_forward_kernel(*ker, false);\n                }\n\n                hoLsqrSolver< T > cgSolver;\n                cgSolver.set_tc_tolerance((float)iter_thres);\n                cgSolver.set_max_iterations( (unsigned int)iter_max);\n                cgSolver.set_output_mode(print_iter ? hoLsqrSolver< T >::OUTPUT_VERBOSE : hoLsqrSolver< T >::OUTPUT_SILENT);\n                cgSolver.set_encoding_operator(oper);\n\n                hoNDArray< T > b(RO, E1, CHA);\n                hoNDArray< T > unwarppedKSpace(RO, E1, CHA);\n\n#pragma omp for\n                for (ii = 0; ii < num; ii++)\n                {\n                    size_t s = ii / N;\n                    size_t n = ii - s*N;\n\n                    // check whether the kspace is undersampled\n                    bool undersampled = false;\n                    for (size_t e1 = startE1; e1 <= endE1; e1++)\n                    {\n                        if ((std::abs(kspace(RO / 2, e1, CHA - 1, n, s)) == 0)\n                            && (std::abs(kspace(RO / 2, e1, 0, n, s)) == 0))\n                        {\n                            undersampled = true;\n                            break;\n                        }\n                    }\n\n                    T* pKpaceShifted = &(kspace_Shifted(0, 0, 0, n, s));\n                    T* pRes = &(res(0, 0, 0, n, s));\n\n                    if (!undersampled)\n                    {\n                        memcpy(pRes, pKpaceShifted, sizeof(T)*RO*E1*CHA);\n                        continue;\n                    }\n\n                    long long kernelN = n;\n                    if (kernelN >= (long long)ref_N) kernelN = (long long)ref_N - 1;\n\n                    long long kernelS = s;\n                    if (kernelS >= (long long)ref_S) kernelS = (long long)ref_S - 1;\n\n                    boost::shared_ptr< hoNDArray< T > > acq(new hoNDArray< T >(RO, E1, CHA, pKpaceShifted));\n                    spirit.set_acquired_points(*acq);\n\n                    boost::shared_ptr< hoNDArray<T> > initialAcq;\n                    if ( hasInitial )\n                    {\n                        initialAcq = boost::shared_ptr< hoNDArray<T> >(new hoNDArray<T>(RO, E1, CHA, &kspace_initial_Shifted(0, 0, 0, n, s)));\n                        cgSolver.set_x0(initialAcq);\n                    }\n                    else\n                    {\n                        cgSolver.set_x0(acq);\n                    }\n\n                    if (ref_N == 1 && ref_S == 1)\n                    {\n                        spirit.compute_righ_hand_side(*acq, b);\n                        cgSolver.solve(&unwarppedKSpace, &b);\n                    }\n                    else\n                    {\n                        T* pKer = &(ker_Shifted(0, 0, 0, kernelN, kernelS));\n                        boost::shared_ptr<hoNDArray< T > > ker(new hoNDArray< T >(RO, E1, CHA, CHA, pKer));\n                        spirit.set_forward_kernel(*ker, false);\n\n                        spirit.compute_righ_hand_side(*acq, b);\n                        cgSolver.solve(&unwarppedKSpace, &b);\n                    }\n\n                    // restore the acquired points\n                    spirit.restore_acquired_kspace(*acq, unwarppedKSpace);\n                    memcpy(pRes, unwarppedKSpace.begin(), unwarppedKSpace.get_number_of_bytes());\n                }\n            }\n\n            Gadgetron::hoNDFFT<typename realType<T>::Type>::instance()->fftshift2D(res, kspace_Shifted);\n            res = kspace_Shifted;\n        }\n        catch(...)\n        {\n            GADGET_THROW(\"Exceptions happened in perform_spirit_recon_linear_2DT(...) ... \");\n        }\n    }\n\n    template EXPORTCMR void perform_spirit_recon_linear_2DT(const Gadgetron::hoNDArray< std::complex<float> >& kspace, size_t startE1, size_t endE1, const Gadgetron::hoNDArray< std::complex<float> >& kerIm, const Gadgetron::hoNDArray< std::complex<float> >& kspaceInitial, Gadgetron::hoNDArray< std::complex<float> >& res, size_t iter_max, double iter_thres, bool print_iter);\n    template EXPORTCMR void perform_spirit_recon_linear_2DT(const Gadgetron::hoNDArray< std::complex<double> >& kspace, size_t startE1, size_t endE1, const Gadgetron::hoNDArray< std::complex<double> >& kerIm, const Gadgetron::hoNDArray< std::complex<double> >& kspaceInitial, Gadgetron::hoNDArray< std::complex<double> >& res, size_t iter_max, double iter_thres, bool print_iter);\n\n    // ---------------------------------------------------------------------\n\n    template <typename T> \n    class sCB : public hoGdSolverCallBack< hoNDArray< T >, hoWavelet2DTOperator< T > >\n    {\n    public:\n        typedef hoGdSolverCallBack< hoNDArray<T>, hoWavelet2DTOperator<T> > BaseClass;\n\n        sCB() : BaseClass() {}\n        virtual ~sCB() {}\n\n        void execute(const hoNDArray<T>& b, hoNDArray<T>& x)\n        {\n            typedef hoSPIRIT2DTDataFidelityOperator<T> SpiritOperType;\n            SpiritOperType* pOper = dynamic_cast<SpiritOperType*> (this->solver_->oper_system_);\n            pOper->restore_acquired_kspace(x);\n        }\n    };\n\n    template <typename T> \n    void perform_spirit_recon_non_linear_2DT(const Gadgetron::hoNDArray<T>& kspace, const Gadgetron::hoNDArray<T>& kerIm, \n                                            const Gadgetron::hoNDArray<T>& coil_map, const Gadgetron::hoNDArray<T>& kspaceLinear, Gadgetron::hoNDArray<T>& res, \n                                            size_t iter_max, double iter_thres, double data_fidelity_lamda, double image_reg_lamda, double reg_N_weighting_ratio, \n                                            bool reg_use_coil_sen_map, bool reg_with_approx_coeff, const std::string& wav_name, bool print_iter)\n    {\n        size_t RO = kspace.get_size(0);\n        size_t E1 = kspace.get_size(1);\n        size_t CHA = kspace.get_size(2);\n        size_t N = kspace.get_size(3);\n        size_t S = kspace.get_size(4);\n\n        size_t ref_N = kerIm.get_size(4);\n        size_t ref_S = kerIm.get_size(5);\n\n        res = kspace;\n\n        size_t s;\n\n        for (s=0; s<S; s++)\n        {\n            boost::shared_ptr< hoNDArray< T > > coilMap;\n\n            bool hasCoilMap = false;\n            if (coil_map.get_size(0) == RO && coil_map.get_size(1) == E1 && coil_map.get_size(2)==CHA)\n            {\n                if (ref_N < N)\n                {\n                    coilMap = boost::shared_ptr< hoNDArray< T > >(new hoNDArray< T >(RO, E1, CHA, const_cast<T*>(coil_map.begin()) ));\n                }\n                else\n                {\n                    coilMap = boost::shared_ptr< hoNDArray< T > >(new hoNDArray< T >(RO, E1, CHA, ref_N, const_cast<T*>(coil_map.begin()) ));\n                }\n\n                hasCoilMap = true;\n            }\n\n            size_t s_used = s;\n            if(s_used>=ref_S) s_used = ref_S;\n\n            boost::shared_ptr<hoNDArray< T > > ker(new hoNDArray< T >(RO, E1, CHA, CHA, ref_N, const_cast<T*>(kerIm.begin())+s_used*RO*E1*CHA*CHA*ref_N) );\n            boost::shared_ptr<hoNDArray< T > > acq(new hoNDArray< T >(RO, E1, CHA, N, const_cast<T*>(kspace.begin())+s*RO*E1*CHA*N) );\n            hoNDArray< T > kspaceInitial(RO, E1, CHA, N, const_cast<T*>(kspaceLinear.begin())+s*RO*E1*CHA*N );\n            hoNDArray< T > res2DT(RO, E1, CHA, N, res.begin()+s*RO*E1*CHA*N );\n\n            if (data_fidelity_lamda > 0)\n            {\n                GDEBUG_STREAM(\"Start the NonLinear SPIRIT data fidelity iteration - regularization strength : \"\n                    << image_reg_lamda\n                    << \" - number of iteration : \"                      << iter_max\n                    << \" - proximity across cha : \"                     << false\n                    << \" - redundant dimension weighting ratio : \"      << reg_N_weighting_ratio\n                    << \" - using coil sen map : \"                       << reg_use_coil_sen_map\n                    << \" - with approx coeff : \"                        << reg_with_approx_coeff\n                    << \" - iter thres : \"                               << iter_thres\n                    << \" - wavelet name : \"                             << wav_name\n                    );\n\n                typedef hoGdSolver< hoNDArray< T >, hoWavelet2DTOperator< T > > SolverType;\n                SolverType solver;\n                solver.iterations_ = iter_max;\n                solver.set_output_mode(print_iter ? SolverType::OUTPUT_VERBOSE : SolverType::OUTPUT_SILENT);\n                solver.grad_thres_ = iter_thres;\n                solver.proximal_strength_ratio_ = image_reg_lamda;\n\n                boost::shared_ptr< hoNDArray< T > > x0 = boost::make_shared< hoNDArray< T > >(kspaceInitial);\n                solver.set_x0(x0);\n\n                // parallel imaging term\n                std::vector<size_t> dims;\n                acq->get_dimensions(dims);\n                hoSPIRIT2DTDataFidelityOperator< T > spirit(&dims);\n                spirit.set_forward_kernel(*ker, false);\n                spirit.set_acquired_points(*acq);\n\n                // image reg term\n                hoWavelet2DTOperator< T > wav3DOperator(&dims);\n                wav3DOperator.set_acquired_points(*acq);\n                wav3DOperator.scale_factor_first_dimension_ = 1;\n                wav3DOperator.scale_factor_second_dimension_ = 1;\n                wav3DOperator.scale_factor_third_dimension_ = reg_N_weighting_ratio;\n                wav3DOperator.with_approx_coeff_ = reg_with_approx_coeff;\n                wav3DOperator.change_coeffcients_third_dimension_boundary_ = true;\n                wav3DOperator.proximity_across_cha_ = false;\n                wav3DOperator.no_null_space_ = true;\n                wav3DOperator.input_in_kspace_ = true;\n                wav3DOperator.select_wavelet(wav_name);\n\n                if (reg_use_coil_sen_map && hasCoilMap)\n                {\n                    wav3DOperator.coil_map_ = *coilMap;\n                }\n\n                // set operators\n\n                solver.oper_system_ = &spirit;\n                solver.oper_reg_ = &wav3DOperator;\n\n                solver.solve(*acq, res2DT);\n            }\n            else\n            {\n                GDEBUG_STREAM(\"Start the NonLinear SPIRIT iteration with regularization strength : \"\n                    << image_reg_lamda\n                    << \" - number of iteration : \" << iter_max\n                    << \" - proximity across cha : \" << false\n                    << \" - redundant dimension weighting ratio : \" << reg_N_weighting_ratio\n                    << \" - using coil sen map : \" << reg_use_coil_sen_map\n                    << \" - with approx coeff : \"  << reg_with_approx_coeff\n                    << \" - iter thres : \" << iter_thres\n                    << \" - wavelet name : \" << wav_name\n                    );\n\n                typedef hoGdSolver< hoNDArray< T >, hoWavelet2DTOperator< T > > SolverType;\n                SolverType solver;\n                solver.iterations_ = iter_max;\n                solver.set_output_mode(print_iter ? SolverType::OUTPUT_VERBOSE : SolverType::OUTPUT_SILENT);\n                solver.grad_thres_ = iter_thres;\n                solver.proximal_strength_ratio_ = image_reg_lamda;\n\n                boost::shared_ptr< hoNDArray< T > > x0 = boost::make_shared< hoNDArray< T > >(kspaceInitial);\n                solver.set_x0(x0);\n\n                // parallel imaging term\n                std::vector<size_t> dims;\n                acq->get_dimensions(dims);\n\n                hoSPIRIT2DTOperator< T > spirit(&dims);\n                spirit.set_forward_kernel(*ker, false);\n                spirit.set_acquired_points(*acq);\n                spirit.no_null_space_ = true;\n                spirit.use_non_centered_fft_ = false;\n\n                // image reg term\n                std::vector<size_t> dim;\n                acq->get_dimensions(dim);\n\n                hoWavelet2DTOperator< T > wav3DOperator(&dim);\n                wav3DOperator.set_acquired_points(*acq);\n                wav3DOperator.scale_factor_first_dimension_ = 1;\n                wav3DOperator.scale_factor_second_dimension_ = 1;\n                wav3DOperator.scale_factor_third_dimension_ = reg_N_weighting_ratio;\n                wav3DOperator.with_approx_coeff_ = reg_with_approx_coeff;\n                wav3DOperator.change_coeffcients_third_dimension_boundary_ = true;\n                wav3DOperator.proximity_across_cha_ = false;\n                wav3DOperator.no_null_space_ = true;\n                wav3DOperator.input_in_kspace_ = true;\n                wav3DOperator.select_wavelet(wav_name);\n\n                if (reg_use_coil_sen_map && hasCoilMap)\n                {\n                    wav3DOperator.coil_map_ = *coilMap;\n                }\n\n                // set operators\n                solver.oper_system_ = &spirit;\n                solver.oper_reg_ = &wav3DOperator;\n\n                // set call back\n                sCB<T> cb;\n                cb.solver_ = &solver;\n                solver.call_back_ = &cb;\n\n                hoNDArray< T > b(kspaceInitial);\n                Gadgetron::clear(b);\n\n                solver.solve(b, res2DT);\n                // if (!debug_folder_full_path_.empty()) gt_exporter_.export_array_complex(res2DT, debug_folder_full_path_ + \"spirit_nl_2DT_res\");\n\n                spirit.restore_acquired_kspace(*acq, res2DT);\n\n                // if (!debug_folder_full_path_.empty()) gt_exporter_.export_array_complex(res2DT, debug_folder_full_path_ + \"spirit_nl_2DT_res_restored\");\n            }\n        }\n    }\n\n    template EXPORTCMR void perform_spirit_recon_non_linear_2DT(const Gadgetron::hoNDArray< std::complex<float> >& kspace, const Gadgetron::hoNDArray< std::complex<float> >& kerIm, \n        const Gadgetron::hoNDArray< std::complex<float> >& coilMap, const Gadgetron::hoNDArray< std::complex<float> >& kspaceInitial, Gadgetron::hoNDArray< std::complex<float> >& res, \n        size_t iter_max, double iter_thres, double data_fidelity_lamda, double image_reg_lamda, double reg_N_weighting_ratio, \n        bool reg_use_coil_sen_map, bool reg_with_approx_coeff, const std::string& wav_name, bool print_iter);\n\n    template EXPORTCMR void perform_spirit_recon_non_linear_2DT(const Gadgetron::hoNDArray< std::complex<double> >& kspace, const Gadgetron::hoNDArray< std::complex<double> >& kerIm, \n        const Gadgetron::hoNDArray< std::complex<double> >& coilMap, const Gadgetron::hoNDArray< std::complex<double> >& kspaceInitial, Gadgetron::hoNDArray< std::complex<double> >& res, \n        size_t iter_max, double iter_thres, double data_fidelity_lamda, double image_reg_lamda, double reg_N_weighting_ratio, \n        bool reg_use_coil_sen_map, bool reg_with_approx_coeff, const std::string& wav_name, bool print_iter);\n}\n", "meta": {"hexsha": "1a099a747fd98d52bf419b1d156d3855aaf121a5", "size": 17951, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolboxes/cmr/cmr_spirit_recon.cpp", "max_stars_repo_name": "roopchansinghv/gadgetron", "max_stars_repo_head_hexsha": "fb6c56b643911152c27834a754a7b6ee2dd912da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-22T21:06:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T21:06:36.000Z", "max_issues_repo_path": "toolboxes/cmr/cmr_spirit_recon.cpp", "max_issues_repo_name": "apd47/gadgetron", "max_issues_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolboxes/cmr/cmr_spirit_recon.cpp", "max_forks_repo_name": "apd47/gadgetron", "max_forks_repo_head_hexsha": "073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.625974026, "max_line_length": 380, "alphanum_fraction": 0.5511113587, "num_tokens": 4482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.41325932684134725}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2018 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n#include \"CxxStd.hpp\"\n\n#include \"NewtonEulerDS.hpp\"\n#include \"BlockVector.hpp\"\n#include \"BlockMatrix.hpp\"\n#include <boost/math/quaternion.hpp>\n\n#include <iostream>\n//#define DEBUG_NOCOLOR\n//#define DEBUG_BEGIN_END_ONLY\n// #define DEBUG_STDOUT\n// #define DEBUG_MESSAGES\n#include <debug.h>\n\n\nvoid computeRotationMatrix(double q0, double q1, double q2, double q3,\n                           SP::SimpleMatrix rotationMatrix)\n{\n\n  /* Brute force version by multiplication of quaternion\n   */\n  // ::boost::math::quaternion<double>    quatQ(q0, q1, q2, q3);\n  // ::boost::math::quaternion<double>    quatcQ(q0, -q1, -q2, -q3);\n  // ::boost::math::quaternion<double>    quatx(0, 1, 0, 0);\n  // ::boost::math::quaternion<double>    quaty(0, 0, 1, 0);\n  // ::boost::math::quaternion<double>    quatz(0, 0, 0, 1);\n  // ::boost::math::quaternion<double>    quatBuff;\n  // quatBuff = quatQ * quatx * quatcQ;\n  // rotationMatrix->setValue(0, 0, quatBuff.R_component_2());\n  // rotationMatrix->setValue(1, 0, quatBuff.R_component_3());\n  // rotationMatrix->setValue(2, 0, quatBuff.R_component_4());\n  // quatBuff = quatQ * quaty * quatcQ;\n  // rotationMatrix->setValue(0, 1, quatBuff.R_component_2());\n  // rotationMatrix->setValue(1, 1, quatBuff.R_component_3());\n  // rotationMatrix->setValue(2, 1, quatBuff.R_component_4());\n  // quatBuff = quatQ * quatz * quatcQ;\n  // rotationMatrix->setValue(0, 2, quatBuff.R_component_2());\n  // rotationMatrix->setValue(1, 2, quatBuff.R_component_3());\n  // rotationMatrix->setValue(2, 2, quatBuff.R_component_4());\n\n  /* direct computation https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation */\n  rotationMatrix->setValue(0, 0,     q0*q0 +q1*q1 -q2*q2 -q3*q3);\n  rotationMatrix->setValue(0, 1, 2.0*(q1*q2        - q0*q3));\n  rotationMatrix->setValue(0, 2, 2.0*(q1*q3        + q0*q2));\n\n  rotationMatrix->setValue(1, 0, 2.0*(q1*q2        + q0*q3));\n  rotationMatrix->setValue(1, 1,     q0*q0 -q1*q1 +q2*q2 -q3*q3);\n  rotationMatrix->setValue(1, 2, 2.0*(q2*q3        - q0*q1));\n\n  rotationMatrix->setValue(2, 0, 2.0*(q1*q3        - q0*q2));\n  rotationMatrix->setValue(2, 1, 2.0*(q2*q3         + q0*q1));\n  rotationMatrix->setValue(2, 2,     q0*q0 -q1*q1 -q2*q2 +q3*q3);\n}\n\nstatic\nvoid computeJacobianConvectedVectorInBodyFrame(double q0, double q1, double q2, double q3,\n                                               SP::SimpleMatrix jacobian, SP::SiconosVector v)\n{\n\n  /* This routine compute the jacobian with respect to p of R^T(p)v */\n  jacobian->zero();\n\n  double v0 = v->getValue(0);\n  double v1 = v->getValue(1);\n  double v2 = v->getValue(2);\n\n  jacobian->setValue(0,3, q0*v0+q3*v1-q2*v2);\n  jacobian->setValue(0,4, q1*v0+q2*v1+q3*v2);\n  jacobian->setValue(0,5,-q2*v0+q1*v1-q0*v2);\n  jacobian->setValue(0,6,-q3*v0+q0*v1+q1*v2);\n\n  jacobian->setValue(1,3,-q3*v0+q0*v1+q1*v2);\n  jacobian->setValue(1,4, q2*v0-q1*v1+q0*v2);\n  jacobian->setValue(1,5, q1*v0+q2*v1+q3*v2);\n  jacobian->setValue(1,6,-q0*v0-q3*v1+q2*v2);\n\n  jacobian->setValue(2,3, q2*v0-q1*v1+q0*v2);\n  jacobian->setValue(2,4, q3*v0-q0*v1-q1*v2);\n  jacobian->setValue(2,5, q0*v0+q3*v1-q2*v2);\n  jacobian->setValue(2,6, q1*v0+q2*v1+q3*v2);\n\n\n  *jacobian *=2.0;\n}\n\n\nvoid rotateAbsToBody(double q0, double q1, double q2, double q3, SiconosVector& v)\n{\n  DEBUG_BEGIN(\"::rotateAbsToBody(double q0, double q1, double q2, double q3, SiconosVector& v )\\n\");\n  DEBUG_EXPR(v.display(););\n  DEBUG_PRINTF(\"( q0 = %16.12e,  q1 = %16.12e,  q2= %16.12e,  q3= %16.12e )\\n\", q0,q1,q2,q3);\n  assert(v.size()==3);\n\n  // First way. Using the rotation matrix\n  // SP::SimpleMatrix rotationMatrix(new SimpleMatrix(3,3));\n  // SiconosVector tmp(3);\n  // ::computeRotationMatrix(q0,q1,q2,q3, rotationMatrix);\n  // prod(*rotationMatrix, v, tmp);\n  // v = tmp;\n  // return;\n\n  // Second way. Using the transpose of the rotation matrix\n  // SP::SimpleMatrix rotationMatrix(new SimpleMatrix(3,3));\n  // SiconosVector tmp(3);\n  // ::computeRotationMatrix(q0,-q1,-q2,-q3, rotationMatrix);\n  // prod(v, *rotationMatrix, tmp);\n  // v = tmp;\n\n  // Third way. cross product and axis angle\n  // see http://www.geometrictools.com/Documentation/RotationIssues.pdf\n  // SP::SiconosVector axis(new SiconosVector(3));\n  // double angle = ::axisAngleFromQuaternion(q0,q1,q2,q3, axis);\n  // SiconosVector t(3), tmp(3);\n  // cross_product(*axis,v,t);\n  // cross_product(*axis,t,tmp);\n  // v += sin(angle)*t + (1.0-cos(angle))*tmp;\n\n  // Direct computation with cross product\n  // Works only with unit quaternion\n  SiconosVector t(3), tmp(3);\n  SiconosVector qvect(3);\n  qvect(0)=q1;\n  qvect(1)=q2;\n  qvect(2)=q3;\n  cross_product(qvect,v,t);\n  t *= 2.0;\n  cross_product(qvect,t,tmp);\n  v += tmp;\n  v += q0*t;\n  DEBUG_EXPR(v.display(););\n  DEBUG_END(\"::rotateAbsToBody(double q0, double q1, double q2, double q3, SP::SiconosVector v )\\n\");\n}\n\nvoid rotateAbsToBody(double q0, double q1, double q2, double q3, SP::SiconosVector v)\n{\n  ::rotateAbsToBody(q0, q1, q2, q3, *v);\n}\n\nvoid rotateAbsToBody(double q0, double q1, double q2, double q3, SP::SimpleMatrix m)\n{\n  DEBUG_BEGIN(\"::rotateAbsToBody(double q0, double q1, double q2, double q3, SP::SimpleMatrix m )\\n\");\n  DEBUG_EXPR(m->display(););\n  DEBUG_PRINTF(\"( q0 = %16.12e,  q1 = %16.12e,  q2= %16.12e,  q3= %16.12e )\\n\", q0,q1,q2,q3);\n\n  // Direct computation with cross product for each column\n  assert(m->size(0) == 3 && \"::rotateAbsToBody(double q0, double q1, double q2, double q3, SP::SimpleMatrix m ) m must have 3 rows\");\n  SiconosVector v(3);\n  SiconosVector t(3), tmp(3);\n  SiconosVector qvect(3);\n  qvect(0)=q1;\n  qvect(1)=q2;\n  qvect(2)=q3;\n  for(unsigned int j = 0; j < m->size(1); j++)\n  {\n    v(0) = m->getValue(0,j);\n    v(1) = m->getValue(1,j);\n    v(2) = m->getValue(2,j);\n    cross_product(qvect,v,t);\n    t *= 2.0;\n    cross_product(qvect,t,tmp);\n    v += tmp;\n    v += q0*t;\n    m->setValue(0,j,v(0));\n    m->setValue(1,j,v(1));\n    m->setValue(2,j,v(2));\n  }\n  DEBUG_EXPR(m->display(););\n  DEBUG_END(\"::rotateAbsToBody(double q0, double q1, double q2, double q3, SP::SimpleMatrix m )\\n\");\n}\n\n\nvoid rotateAbsToBody(SP::SiconosVector q, SP::SiconosVector v)\n{\n  DEBUG_BEGIN(\"::rotateAbsToBody(SP::SiconosVector q, SP::SiconosVector v )\\n\");\n  ::rotateAbsToBody(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6), v);\n  DEBUG_END(\"::rotateAbsToBody(SP::SiconosVector q, SP::SiconosVector v )\\n\");\n}\n\nvoid rotateAbsToBody(SP::SiconosVector q, SP::SimpleMatrix m)\n{\n  DEBUG_BEGIN(\"::rotateAbsToBody(SP::SiconosVector q, SP::SimpleMatrix m )\\n\");\n  ::rotateAbsToBody(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6),m);\n  DEBUG_END(\"::rotateAbsToBody(SP::SiconosVector q, SP::SimpleMatrix m)\\n\");\n}\n\nvoid changeFrameAbsToBody(const SiconosVector& q, SiconosVector& v)\n{\n  DEBUG_BEGIN(\"::changeFrameAbsToBody(const SiconosVector& q, SiconosVector& v )\\n\");\n  ::rotateAbsToBody(q.getValue(3),-q.getValue(4),-q.getValue(5),-q.getValue(6), v);\n  DEBUG_END(\"::changeFrameAbsToBody(const SiconosVector& q, SiconosVector& v )\\n\");\n}\nvoid changeFrameAbsToBody(SP::SiconosVector q, SP::SiconosVector v)\n{\n  DEBUG_BEGIN(\"::changeFrameAbsToBody(SP::SiconosVector q, SP::SiconosVector v )\\n\");\n  ::rotateAbsToBody(q->getValue(3),-q->getValue(4),-q->getValue(5),-q->getValue(6), v);\n  DEBUG_END(\"::changeFrameAbsToBody(SP::SiconosVector q, SP::SiconosVector v )\\n\");\n}\nvoid changeFrameAbsToBody(SP::SiconosVector q, SP::SimpleMatrix m)\n{\n  DEBUG_BEGIN(\"::changeFrameAbsToBody(SP::SiconosVector q, SP::SimpleMatrix m )\\n\");\n  ::rotateAbsToBody(q->getValue(3),-q->getValue(4),-q->getValue(5),-q->getValue(6), m);\n  DEBUG_END(\"::changeFrameAbsToBody(SP::SiconosVector q, SP::SimpleMatrix m )\\n\");\n}\n\nvoid changeFrameBodyToAbs(const SiconosVector& q, SiconosVector& v)\n{\n  DEBUG_BEGIN(\"::changeFrameBodyToAbs(const SiconosVector& q, SiconosVector& v )\\n\");\n  ::rotateAbsToBody(q.getValue(3),q.getValue(4),q.getValue(5),q.getValue(6), v);\n  DEBUG_END(\"::changeFrameBodyToAbs(const SiconosVector& q, SiconosVector& v )\\n\");\n}\nvoid changeFrameBodyToAbs(SP::SiconosVector q, SP::SiconosVector v)\n{\n  DEBUG_BEGIN(\"::changeFrameBodyToAbs(SP::SiconosVector q, SP::SiconosVector v )\\n\");\n  ::rotateAbsToBody(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6), *v);\n  DEBUG_END(\"::changeFrameBodyToAbs(SP::SiconosVector q, SP::SiconosVector v )\\n\");\n}\nvoid changeFrameBodyToAbs(SP::SiconosVector q, SP::SimpleMatrix m)\n{\n  DEBUG_BEGIN(\"::changeFrameBodyToAbs(SP::SiconosVector q, SP::SimpleMatrix m )\\n\");\n  ::rotateAbsToBody(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6), m);\n  DEBUG_END(\"::changeFrameBodyToAbs(SP::SiconosVector q, SP::SimpleMatrix m )\\n\");\n}\n\n\n\nvoid computeRotationMatrix(SP::SiconosVector q, SP::SimpleMatrix rotationMatrix)\n{\n  ::computeRotationMatrix(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6),\n                          rotationMatrix);\n}\nvoid computeRotationMatrixTransposed(SP::SiconosVector q, SP::SimpleMatrix rotationMatrix)\n{\n  ::computeRotationMatrix(q->getValue(3),-q->getValue(4),-q->getValue(5),-q->getValue(6),\n                          rotationMatrix);\n}\n\ndouble axisAngleFromQuaternion(double q0, double q1, double q2, double q3, SP::SiconosVector axis)\n{\n  DEBUG_BEGIN(\"axisAngleFromQuaternion(double q0, double q1, double q2, double q3, SP::SiconosVector axis )\\n\");\n  double angle = acos(q0) *2.0;\n  //double f = sin( angle *0.5);\n  double f = sqrt(1-q0*q0); // cheaper than sin ?\n  if(f !=0.0)\n  {\n    axis->setValue(0, q1/f);\n    axis->setValue(1, q2/f);\n    axis->setValue(2, q3/f);\n  }\n  else\n  {\n    axis->zero();\n  }\n  DEBUG_PRINTF(\"angle= %12.8e\\n\", angle);\n  DEBUG_EXPR(axis->display(););\n  DEBUG_END(\"axisAngleFromQuaternion(double q0, double q1, double q2, double q3, SP::SiconosVector axis )\\n\");\n  return angle;\n}\n\ndouble axisAngleFromQuaternion(SP::SiconosVector q, SP::SiconosVector axis)\n{\n  double angle = ::axisAngleFromQuaternion(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6),axis);\n  return angle;\n}\n\nvoid rotationVectorFromQuaternion(double q0, double q1, double q2, double q3, SP::SiconosVector rotationVector)\n{\n  DEBUG_BEGIN(\"rotationVectorFromQuaternion(double q0, double q1, double q2, double q3, SP::SiconosVector rotationVector )\\n\");\n\n  rotationVector->setValue(0, q1);\n  rotationVector->setValue(1, q2);\n  rotationVector->setValue(2, q3);\n\n  double norm_v = sqrt(q1*q1+q2*q2+q3*q3);\n  assert(norm_v <= M_PI);  /* it should be called for a unit quaternion */\n  if(norm_v < 1e-12)\n  {\n    rotationVector->setValue(0, 0.0);\n    rotationVector->setValue(1, 0.0);\n    rotationVector->setValue(2, 0.0);\n  }\n  else\n  {\n    *rotationVector *=  2.0 * asin(norm_v)/norm_v;\n  }\n  DEBUG_EXPR(rotationVector->display(););\n  DEBUG_END(\"rotationVectorFromQuaternion(double q0, double q1, double q2, double q3, SP::SiconosVector rotationVector )\\n\");\n}\n\nvoid rotationVectorFromQuaternion(SP::SiconosVector q, SP::SiconosVector rotationVector)\n{\n  ::rotationVectorFromQuaternion(q->getValue(3),q->getValue(4),q->getValue(5),q->getValue(6), rotationVector);\n}\n\n\nvoid quaternionFromAxisAngle(SP::SiconosVector axis, double angle, SP::SiconosVector q)\n{\n  q->setValue(3,cos(angle/2.0));\n  q->setValue(4,axis->getValue(0)* sin(angle *0.5));\n  q->setValue(5,axis->getValue(1)* sin(angle *0.5));\n  q->setValue(6,axis->getValue(2)* sin(angle *0.5));\n}\n\nstatic\ndouble sin_x(double x)\n{\n  if(std::abs(x) <= 1e-3)\n  {\n    return 1.0 + x*x / 3.0 + pow(x,4) * 2.0 / 15.0 + pow(x,6) * 17.0 / 315.0 + pow(x,8) * 62.0 / 2835.0;\n  }\n  else\n  {\n    return sin(x)/x;\n  }\n}\n\nvoid quaternionFromRotationVector(SP::SiconosVector rotationVector, SP::SiconosVector q)\n{\n  double angle = sqrt(rotationVector->getValue(0)*rotationVector->getValue(0)+\n               rotationVector->getValue(1)*rotationVector->getValue(1)+\n               rotationVector->getValue(2)*rotationVector->getValue(2));\n\n  double f = 0.5 * sin_x(angle *0.5);\n\n  q->setValue(3,cos(angle/2.0));\n  q->setValue(4,rotationVector->getValue(0)* f);\n  q->setValue(5,rotationVector->getValue(1)* f);\n  q->setValue(6,rotationVector->getValue(2)* f);\n}\n\n\n\nvoid normalizeq(SP::SiconosVector q)\n{\n  double normq = sqrt(q->getValue(3) * q->getValue(3) +\n                      q->getValue(4) * q->getValue(4) +\n                      q->getValue(5) * q->getValue(5) +\n                      q->getValue(6) * q->getValue(6));\n  assert(normq > 0);\n  normq = 1.0 / normq;\n  q->setValue(3, q->getValue(3) * normq);\n  q->setValue(4, q->getValue(4) * normq);\n  q->setValue(5, q->getValue(5) * normq);\n  q->setValue(6, q->getValue(6) * normq);\n}\n\n\nvoid computeT(SP::SiconosVector q, SP::SimpleMatrix T)\n{\n  DEBUG_BEGIN(\"computeT(SP::SiconosVector q, SP::SimpleMatrix T)\\n\")\n  //  std::cout <<\"\\n NewtonEulerDS::computeT(SP::SiconosVector q)\\n  \" <<std::endl;\n  double q0 = q->getValue(3) / 2.0;\n  double q1 = q->getValue(4) / 2.0;\n  double q2 = q->getValue(5) / 2.0;\n  double q3 = q->getValue(6) / 2.0;\n  T->setValue(3, 3, -q1);\n  T->setValue(3, 4, -q2);\n  T->setValue(3, 5, -q3);\n  T->setValue(4, 3, q0);\n  T->setValue(4, 4, -q3);\n  T->setValue(4, 5, q2);\n  T->setValue(5, 3, q3);\n  T->setValue(5, 4, q0);\n  T->setValue(5, 5, -q1);\n  T->setValue(6, 3, -q2);\n  T->setValue(6, 4, q1);\n  T->setValue(6, 5, q0);\n  DEBUG_END(\"computeT(SP::SiconosVector q, SP::SimpleMatrix T)\\n\")\n\n}\n\n// From a set of data; Mass filled-in directly from a siconosMatrix -\n// This constructor leads to the minimum NewtonEuler System form: \\f$ M\\ddot q = p \\f$\n/*\nQ0 : contains the center of mass coordinate, and the quaternion initial. (dim(Q0)=7)\nTwist0 : contains the initial velocity of center of mass and the omega initial. (dim(VTwist0)=6)\n*/\nNewtonEulerDS::NewtonEulerDS():\n  DynamicalSystem(13),\n  _hasConstantFExt(false),\n  _hasConstantMExt(false),\n  _isMextExpressedInInertialFrame(false),\n  _nullifyMGyr(false),\n  _computeJacobianFIntqByFD(false),\n  _computeJacobianFInttwistByFD(false),\n  _computeJacobianMIntqByFD(false),\n  _computeJacobianMInttwistByFD(false),\n  _epsilonFD(sqrt(std::numeric_limits< double >::epsilon()))\n{\n  /* common code for constructors\n   * would be better to use delagation of constructors in c++11\n   */\n  _init();\n}\n\n\nNewtonEulerDS::NewtonEulerDS(SP::SiconosVector Q0, SP::SiconosVector Twist0,\n                             double  mass, SP::SiconosMatrix inertialMatrix):\n  DynamicalSystem(13),\n  _hasConstantFExt(false),\n  _hasConstantMExt(false),\n  _isMextExpressedInInertialFrame(false),\n  _nullifyMGyr(false),\n  _computeJacobianFIntqByFD(false),\n  _computeJacobianFInttwistByFD(false),\n  _computeJacobianMIntqByFD(false),\n  _computeJacobianMInttwistByFD(false),\n  _epsilonFD(sqrt(std::numeric_limits< double >::epsilon()))\n\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::NewtonEulerDS(SP::SiconosVector Q0, SP::SiconosVector Twist0,double  mass, SP::SiconosMatrix inertialMatrix)\\n\");\n\n  /* common code for constructors\n   * would be better to use delegation of constructors in c++11\n   */\n  _init();\n\n  // Initial conditions\n  _q0 = Q0;\n  _twist0 = Twist0;\n  resetToInitialState();\n\n  _scalarMass = mass;\n  if(inertialMatrix)\n    _I = inertialMatrix;\n  updateMassMatrix();\n\n  _T->zero();\n  _T->setValue(0, 0, 1.0);\n  _T->setValue(1, 1, 1.0);\n  _T->setValue(2, 2, 1.0);\n  computeT();\n\n  DEBUG_END(\"NewtonEulerDS::NewtonEulerDS(SP::SiconosVector Q0, SP::SiconosVector Twist0,double  mass, SP::SiconosMatrix inertialMatrix)\\n\");\n}\n\nvoid NewtonEulerDS::_init()\n{\n  // --- NEWTONEULER INHERITED CLASS MEMBERS ---\n  // -- Memory allocation for vector and matrix members --\n\n  _qDim = 7;\n  _ndof = 6;\n  _n = _qDim + _ndof;\n\n\n  _zeroPlugin();\n\n  // Current state\n  _q.reset(new SiconosVector(_qDim));\n  _twist.reset(new SiconosVector(_ndof));\n  _dotq.reset(new SiconosVector(_qDim));\n\n  /** \\todo lazy Memory allocation */\n  _p.resize(3);\n  _p[1].reset(new SiconosVector(_ndof)); // Needed in NewtonEulerR\n\n\n  _massMatrix.reset(new SimpleMatrix(_ndof, _ndof));\n  _massMatrix->zero();\n  _T.reset(new SimpleMatrix(_qDim, _ndof));\n\n  _scalarMass = 1.;\n  _I.reset(new SimpleMatrix(3, 3));\n  _I->eye();\n  updateMassMatrix();\n\n  _wrench.reset(new SiconosVector(_ndof));\n  _mGyr.reset(new SiconosVector(3,0.0));\n\n  /** The follwing jacobian are always allocated since we have always\n   * Gyroscopical forces that has non linear forces\n   * This should be remove if the integration is explicit or _nullifyMGyr(false) is set to true ?\n   */\n\n  _jacobianMGyrtwist.reset(new SimpleMatrix(3, _ndof));\n  _jacobianWrenchTwist.reset(new SimpleMatrix(_ndof, _ndof));\n\n\n  //We initialize _z with a null vector of size 1, since z is required in plug-in functions call.\n  _z.reset(new SiconosVector(1));\n\n}\n\nvoid NewtonEulerDS::updateMassMatrix()\n{\n  // _massMatrix->zero();\n  // _massMatrix->setValue(0, 0, _scalarMass);\n  // _massMatrix->setValue(1, 1, _scalarMass);\n  // _massMatrix->setValue(2, 2, _scalarMass);\n\n  _massMatrix->eye();\n  * _massMatrix *=  _scalarMass;\n\n  Index dimIndex(2);\n  dimIndex[0] = 3;\n  dimIndex[1] = 3;\n  Index startIndex(4);\n  startIndex[0] = 0;\n  startIndex[1] = 0;\n  startIndex[2] = 3;\n  startIndex[3] = 3;\n  setBlock(_I, _massMatrix, dimIndex, startIndex);\n\n}\n\nvoid NewtonEulerDS::_zeroPlugin()\n{\n  _pluginFExt.reset(new PluggedObject());\n  _pluginMExt.reset(new PluggedObject());\n  _pluginFInt.reset(new PluggedObject());\n  _pluginMInt.reset(new PluggedObject());\n  _pluginJacqFInt.reset(new PluggedObject());\n  _pluginJactwistFInt.reset(new PluggedObject());\n  _pluginJacqMInt.reset(new PluggedObject());\n  _pluginJactwistMInt.reset(new PluggedObject());\n}\n\n// Destructor\nNewtonEulerDS::~NewtonEulerDS()\n{\n}\n\nvoid NewtonEulerDS::setInertia(double ix, double iy, double iz)\n{\n  _I->zero();\n\n  (*_I)(0, 0) = ix;\n  (*_I)(1, 1) = iy;\n  (*_I)(2, 2) = iz;\n\n  updateMassMatrix();\n}\n\nvoid NewtonEulerDS::initializeNonSmoothInput(unsigned int level)\n{\n  DEBUG_PRINTF(\"NewtonEulerDS::initializeNonSmoothInput(unsigned int level) for level = %i\\n\",level);\n\n  if(!_p[level])\n  {\n    if(level == 0)\n    {\n      _p[level].reset(new SiconosVector(_qDim));\n    }\n    else\n      _p[level].reset(new SiconosVector(_ndof));\n  }\n\n#ifdef DEBUG_MESSAGES\n  DEBUG_PRINT(\"display() after initialization\");\n  display();\n#endif\n}\n\n\n\nvoid NewtonEulerDS::initRhs(double time)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::initRhs(double time)\\n\");\n  // dim\n  _n = _qDim + 6;\n\n  _x0.reset(new SiconosVector(*_q0, *_twist0));\n\n  _x[0].reset(new SiconosVector(*_q, *_twist));\n\n  if (!_acceleration)\n    _acceleration.reset(new SiconosVector(6));\n\n  // Compute _dotq\n  computeT();\n  prod(*_T, *_twist, *_dotq, true);\n  _x[1].reset(new SiconosVector(*_dotq, *_acceleration));\n\n\n  // Nothing to do for the initialization of the wrench\n\n\n  // Everything concerning rhs and its jacobian is handled in initRhs and computeXXX related functions.\n  _rhsMatrices.resize(numberOfRhsMatrices);\n\n  if(!_p[2])\n    _p[2].reset(new SiconosVector(6));\n\n\n  init_inverse_mass();\n\n  computeRhs(time);\n\n  /** \\warning the derivative of T w.r.t to q is neglected */\n  _rhsMatrices[jacobianXBloc00].reset(new SimpleMatrix(_qDim, _qDim, Siconos::ZERO));\n\n\n  _rhsMatrices[jacobianXBloc01].reset(new SimpleMatrix(*_T));\n  bool flag1 = false, flag2 = false;\n  if(_jacobianWrenchq)\n  {\n    // Solve MjacobianX(1,0) = jacobianFL[0]\n    computeJacobianqForces(time);\n\n    _rhsMatrices[jacobianXBloc10].reset(new SimpleMatrix(*_jacobianWrenchq));\n    _inverseMass->PLUForwardBackwardInPlace(*_rhsMatrices[jacobianXBloc10]);\n    flag1 = true;\n  }\n\n  if(_jacobianWrenchTwist)\n  {\n    // Solve MjacobianX(1,1) = jacobianFL[1]\n    computeJacobianvForces(time);\n    _rhsMatrices[jacobianXBloc11].reset(new SimpleMatrix(*_jacobianWrenchTwist));\n    _inverseMass->PLUForwardBackwardInPlace(*_rhsMatrices[jacobianXBloc11]);\n    flag2 = true;\n  }\n\n  if(!_rhsMatrices[zeroMatrix])\n    _rhsMatrices[zeroMatrix].reset(new SimpleMatrix(6, 6, Siconos::ZERO));\n\n  if(!_rhsMatrices[zeroMatrixqDim])\n    _rhsMatrices[zeroMatrixqDim].reset(new SimpleMatrix(6, _qDim, Siconos::ZERO));\n\n  if(flag1 && flag2)\n    _jacxRhs.reset(new BlockMatrix(_rhsMatrices[jacobianXBloc00], _rhsMatrices[jacobianXBloc01],\n                                   _rhsMatrices[jacobianXBloc10], _rhsMatrices[jacobianXBloc11]));\n  else if(flag1)  // flag2 = false\n    _jacxRhs.reset(new BlockMatrix(_rhsMatrices[jacobianXBloc00], _rhsMatrices[jacobianXBloc01],\n                                   _rhsMatrices[jacobianXBloc10], _rhsMatrices[zeroMatrix]));\n  else if(flag2)  // flag1 = false\n    _jacxRhs.reset(new BlockMatrix(_rhsMatrices[jacobianXBloc00], _rhsMatrices[jacobianXBloc01],\n                                   _rhsMatrices[zeroMatrixqDim], _rhsMatrices[jacobianXBloc11]));\n  else\n    _jacxRhs.reset(new BlockMatrix(_rhsMatrices[jacobianXBloc00], _rhsMatrices[jacobianXBloc01],\n                                   _rhsMatrices[zeroMatrixqDim], _rhsMatrices[zeroMatrix]));\n  DEBUG_EXPR(display(););\n  DEBUG_END(\"NewtonEulerDS::initRhs(double time)\\n\");\n}\n\nvoid NewtonEulerDS::resetToInitialState()\n{\n  // set q and q[1] to q0 and Twist0\n  if(_q0)\n  {\n    *_q = *_q0;\n  }\n  else\n    RuntimeException::selfThrow(\"NewtonEulerDS::resetToInitialState - initial position _q0 is null\");\n\n\n  if(_twist0)\n  {\n    *_twist = *_twist0;\n  }\n  else\n    RuntimeException::selfThrow(\"NewtonEulerDS::resetToInitialState - initial twist _twist0 is null\");\n}\n\nvoid NewtonEulerDS::init_inverse_mass()\n{\n  if(_massMatrix && !_inverseMass)\n    {\n      updateMassMatrix();\n      _inverseMass.reset(new SimpleMatrix(*_massMatrix));\n    }\n}\n\nvoid NewtonEulerDS::update_inverse_mass()\n{\n  if(_massMatrix && _inverseMass)\n    {\n      updateMassMatrix();\n      *_inverseMass = *_massMatrix;\n    }\n}\n\nvoid NewtonEulerDS::computeFExt(double time)\n{\n  // computeFExt(time, _fExt);\n\n  if(_pluginFExt->fPtr)\n  {\n    ((FExt_NE)_pluginFExt->fPtr)(time, &(*_fExt)(0), _qDim, &(*_q0)(0));  // parameter z are assumed to be equal to q0\n  }\n\n}\n\nvoid NewtonEulerDS::computeFExt(double time, SP::SiconosVector fExt)\n{\n  /* if the pointer has been set to an external vector\n   * after setting the plugin, we do not call the plugin */\n  if(_hasConstantFExt)\n  {\n    if(fExt != _fExt)\n      *fExt = *_fExt;\n  }\n  else\n  {\n    if(_pluginFExt->fPtr)\n    {\n      ((FExt_NE)_pluginFExt->fPtr)(time, &(*fExt)(0), _qDim, &(*_q0)(0));  // parameter z are assumed to be equal to q0\n    }\n  }\n}\n\n/** This function has been added to avoid Swig director to wrap _MExt into numpy.array\n * when we call  NewtonEulerDS::computeMExt(double time, SP::SiconosVector q, SP::SiconosVector mExt)\n *  that calls in turn computeMExt(time, q, _mExt);\n */\nstatic\nvoid computeMExt_internal(double time, bool hasConstantMExt,\n                          unsigned int qDim, SP::SiconosVector q0,\n                          SP::PluggedObject pluginMExt, SP::SiconosVector mExt_attributes,\n                          SP::SiconosVector mExt)\n{\n  /* if the pointer has been set to an external vector\n   * after setting the plugin, we do not call the plugin */\n  if(hasConstantMExt)\n  {\n    if(mExt != mExt_attributes)\n      *mExt = *mExt_attributes;\n  }\n  else if(pluginMExt->fPtr)\n    ((FExt_NE)pluginMExt->fPtr)(time, &(*mExt)(0), qDim, &(*q0)(0));  // parameter z are assumed to be equal to q0\n\n}\n\n\nvoid NewtonEulerDS::computeMExt(double time)\n{\n  DEBUG_BEGIN(\"N3ewtonEulerDS::computeMExt(double time)\\n\");\n  computeMExt_internal(time,_hasConstantMExt,\n                       _qDim, _q0,\n                       _pluginMExt, _mExt, _mExt);\n  DEBUG_END(\"NewtonEulerDS::computeMExt(double time)\\n\");\n}\n\n\n\nvoid NewtonEulerDS::computeMExt(double time, SP::SiconosVector mExt)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeMExt(double time, SP::SiconosVector mExt)\\n\");\n  computeMExt_internal(time, _hasConstantMExt,\n                       _qDim, _q0, _pluginMExt, _mExt, mExt);\n  DEBUG_END(\"NewtonEulerDS::computeMExt(double time, SP::SiconosVector mExt)\\n\");\n}\n\n\n\nvoid NewtonEulerDS::computeJacobianMExtqExpressedInInertialFrameByFD(double time, SP::SiconosVector q)\n{\n\n  DEBUG_BEGIN(\"NewtonEulerDS::computeJacobianMExtqExpressedInInertialFrameByFD(...)\\n\");\n\n  /* The computation of Jacobian of R^T mExt is somehow very rough since the pertubation\n   * that we apply to q  that gives qeps does not provide a unit quaternion. The rotation\n   * is computed assuming that the quaternion is unit (see rotateAbsToBody(double q0, double\n   * q1, double q2, double q3, SP::SiconosVector v)).\n   */\n\n  SP::SiconosVector mExt(new SiconosVector(3));\n  computeMExt(time, mExt);\n  if(_isMextExpressedInInertialFrame)\n    ::changeFrameAbsToBody(q,mExt);\n  DEBUG_EXPR(q->display());\n  DEBUG_EXPR(mExt->display(););\n\n  double mExt0 = mExt->getValue(0);\n  double mExt1 = mExt->getValue(1);\n  double mExt2 = mExt->getValue(2);\n\n  SP::SiconosVector qeps(new SiconosVector(*q));\n  _jacobianMExtq->zero();\n  (*qeps)(3) += _epsilonFD;\n  for(int j =3; j < 7; j++)\n  {\n    computeMExt(time, mExt);\n    if(_isMextExpressedInInertialFrame)\n      ::changeFrameAbsToBody(qeps,mExt);\n    DEBUG_EXPR(mExt->display(););\n    _jacobianMExtq->setValue(0,j, (mExt->getValue(0) - mExt0)/_epsilonFD);\n    _jacobianMExtq->setValue(1,j, (mExt->getValue(1) - mExt1)/_epsilonFD);\n    _jacobianMExtq->setValue(2,j, (mExt->getValue(2) - mExt2)/_epsilonFD);\n    (*qeps)(j) -= _epsilonFD;\n    if(j<6)(*qeps)(j+1) += _epsilonFD;\n  }\n  DEBUG_EXPR(_jacobianMExtq->display(););\n  DEBUG_END(\"NewtonEulerDS::computeJacobianMExtqExpressedInInertialFrameByFD(...)\\n\");\n\n}\n\nvoid NewtonEulerDS::computeJacobianMExtqExpressedInInertialFrame(double time, SP::SiconosVector q)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeJacobianMExtqExpressedInInertialFrame(...)\\n\");\n  bool isMextExpressedInInertialFrame_save = _isMextExpressedInInertialFrame;\n  _isMextExpressedInInertialFrame=false;\n  SP::SiconosVector mExt(new SiconosVector(3));\n  computeMExt(time, mExt);\n  if(_isMextExpressedInInertialFrame)\n    ::changeFrameAbsToBody(q,mExt);\n  DEBUG_EXPR(q->display());\n  DEBUG_EXPR(mExt->display());\n\n  _isMextExpressedInInertialFrame=isMextExpressedInInertialFrame_save;\n\n  double q0 = q->getValue(3);\n  double q1 = q->getValue(4);\n  double q2 = q->getValue(5);\n  double q3 = q->getValue(6);\n\n  computeJacobianConvectedVectorInBodyFrame(q0, q1,  q2,  q3, _jacobianMExtq, mExt);\n\n  DEBUG_EXPR(_jacobianMExtq->display());\n\n  // SP::SimpleMatrix jacobianMExtqtmp (new SimpleMatrix(*_jacobianMExtq));\n  // computeJacobianMExtqExpressedInInertialFrameByFD(time, q);\n\n  // std::cout << \"#################  \" << (*jacobianMExtqtmp- *_jacobianMExtq).normInf() << std::endl;\n  // assert((*jacobianMExtqtmp- *_jacobianMExtq).normInf()< 1e-10);\n\n  // DEBUG_EXPR(_jacobianMExtq->display(););\n  DEBUG_END(\"NewtonEulerDS::computeJacobianMExtqExpressedInInertialFrame(...)\\n\");\n\n}\nvoid NewtonEulerDS::computeFInt(double time, SP::SiconosVector q, SP::SiconosVector v)\n{\n  computeFInt(time,  q,  v, _fInt);\n}\n\nvoid NewtonEulerDS::computeFInt(double time, SP::SiconosVector q, SP::SiconosVector v, SP::SiconosVector fInt)\n{\n  if(_pluginFInt->fPtr)\n    ((FInt_NE)_pluginFInt->fPtr)(time, &(*q)(0), &(*v)(0), &(*fInt)(0), _qDim,  &(*_q0)(0));// parameter z are assumed to be equal to q0\n}\n\n\n\nvoid NewtonEulerDS::computeMInt(double time, SP::SiconosVector q, SP::SiconosVector v)\n{\n   DEBUG_BEGIN(\"NewtonEulerDS::computeMInt(double time, SP::SiconosVector q, SP::SiconosVector v)\\n\");\n   computeMInt(time, q, v, _mInt);\n   DEBUG_END(\"NewtonEulerDS::computeMInt(double time, SP::SiconosVector q, SP::SiconosVector v)\\n\");\n}\n\nvoid NewtonEulerDS::computeMInt(double time, SP::SiconosVector q, SP::SiconosVector v, SP::SiconosVector mInt)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeMInt(double time, SP::SiconosVector q, SP::SiconosVector v, SP::SiconosVector mInt)\\n\");\n  if(_pluginMInt->fPtr)\n    ((FInt_NE)_pluginMInt->fPtr)(time, &(*q)(0), &(*v)(0), &(*mInt)(0), _qDim,  &(*_q0)(0));// parameter z are assumed to be equal to q0\n  DEBUG_END(\"NewtonEulerDS::computeMInt(double time, SP::SiconosVector q, SP::SiconosVector v, SP::SiconosVector mInt)\\n\");\n}\n\n\nvoid NewtonEulerDS::computeJacobianFIntq(double time)\n{\n  computeJacobianFIntq(time, _q, _twist);\n}\nvoid NewtonEulerDS::computeJacobianFIntv(double time)\n{\n  computeJacobianFIntv(time, _q, _twist);\n}\n\nvoid NewtonEulerDS::computeJacobianFIntq(double time, SP::SiconosVector q, SP::SiconosVector twist)\n{\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianFIntq(...) starts\");\n  if(_pluginJacqFInt->fPtr)\n    ((FInt_NE)_pluginJacqFInt->fPtr)(time, &(*q)(0), &(*twist)(0), &(*_jacobianFIntq)(0, 0), _qDim,  &(*_q0)(0));\n  else if(_computeJacobianFIntqByFD)\n    computeJacobianFIntqByFD(time, q, twist);\n  DEBUG_EXPR(_jacobianFIntq->display(););\n  DEBUG_END(\"NewtonEulerDS::computeJacobianFIntq(...)\");\n}\n\nvoid NewtonEulerDS::computeJacobianFIntqByFD(double time, SP::SiconosVector q, SP::SiconosVector twist)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeJacobianFIntqByFD(...)\\n\");\n  SP::SiconosVector fInt(new SiconosVector(3));\n  computeFInt(time, q, twist, fInt);\n\n  double fInt0 = fInt->getValue(0);\n  double fInt1 = fInt->getValue(1);\n  double fInt2 = fInt->getValue(2);\n\n  SP::SiconosVector qeps(new SiconosVector(*q));\n  _jacobianFIntq->zero();\n  (*qeps)(0) += _epsilonFD;\n  for(int j =0; j < 7; j++)\n  {\n    computeFInt(time, qeps, twist, fInt);\n    _jacobianFIntq->setValue(0,j, (fInt->getValue(0) - fInt0)/_epsilonFD);\n    _jacobianFIntq->setValue(1,j, (fInt->getValue(1) - fInt1)/_epsilonFD);\n    _jacobianFIntq->setValue(2,j, (fInt->getValue(2) - fInt2)/_epsilonFD);\n    (*qeps)(j) -= _epsilonFD;\n    if(j<6)(*qeps)(j+1) += _epsilonFD;\n  }\n  DEBUG_END(\"NewtonEulerDS::computeJacobianFIntqByFD(...)\\n\");\n\n\n}\n\nvoid NewtonEulerDS::computeJacobianFIntv(double time, SP::SiconosVector q, SP::SiconosVector twist)\n{\n  if(_pluginJactwistFInt->fPtr)\n    ((FInt_NE)_pluginJactwistFInt->fPtr)(time, &(*q)(0), &(*twist)(0), &(*_jacobianFInttwist)(0, 0), _qDim,  &(*_q0)(0));\n  else if(_computeJacobianFInttwistByFD)\n    computeJacobianFIntvByFD(time, q, twist);\n}\n\nvoid NewtonEulerDS::computeJacobianFIntvByFD(double time, SP::SiconosVector q, SP::SiconosVector twist)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeJacobianFIntvByFD(...)\\n\");\n  SP::SiconosVector fInt(new SiconosVector(3));\n  computeFInt(time, q, twist, fInt);\n\n  double fInt0 = fInt->getValue(0);\n  double fInt1 = fInt->getValue(1);\n  double fInt2 = fInt->getValue(2);\n\n  SP::SiconosVector veps(new SiconosVector(*twist));\n  _jacobianFInttwist->zero();\n\n  (*veps)(0) += _epsilonFD;\n  for(int j =0; j < 6; j++)\n  {\n    computeFInt(time, q, veps, fInt);\n    _jacobianFInttwist->setValue(0,j, (fInt->getValue(0) - fInt0)/_epsilonFD);\n    _jacobianFInttwist->setValue(1,j, (fInt->getValue(1) - fInt1)/_epsilonFD);\n    _jacobianFInttwist->setValue(2,j, (fInt->getValue(2) - fInt2)/_epsilonFD);\n    (*veps)(j) -= _epsilonFD;\n    if(j<5)(*veps)(j+1) += _epsilonFD;\n  }\n\n  DEBUG_END(\"NewtonEulerDS::computeJacobianFIntvByFD(...)\\n\");\n\n\n}\nvoid NewtonEulerDS::computeJacobianMGyrtwistByFD(double time, SP::SiconosVector q, SP::SiconosVector twist)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeJacobianMGyrvByFD(...)\\n\");\n  SP::SiconosVector mGyr(new SiconosVector(3));\n  computeMGyr(twist, mGyr);\n\n  double mGyr0 = mGyr->getValue(0);\n  double mGyr1 = mGyr->getValue(1);\n  double mGyr2 = mGyr->getValue(2);\n\n  SP::SiconosVector veps(new SiconosVector(*twist));\n  _jacobianMGyrtwist->zero();\n\n\n  (*veps)(0) += _epsilonFD;\n  for(int j =0; j < 6; j++)\n  {\n    computeMGyr(veps, mGyr);\n    _jacobianMGyrtwist->setValue(3,j, (mGyr->getValue(0) - mGyr0)/_epsilonFD);\n    _jacobianMGyrtwist->setValue(4,j, (mGyr->getValue(1) - mGyr1)/_epsilonFD);\n    _jacobianMGyrtwist->setValue(5,j, (mGyr->getValue(2) - mGyr2)/_epsilonFD);\n    (*veps)(j) -= _epsilonFD;\n    if(j<5)(*veps)(j+1) += _epsilonFD;\n  }\n  DEBUG_EXPR(_jacobianMGyrtwist->display());\n  DEBUG_END(\"NewtonEulerDS::computeJacobianMGyrvByFD(...)\\n\");\n\n\n}\nvoid NewtonEulerDS::computeJacobianMIntq(double time)\n{\n  computeJacobianMIntq(time, _q, _twist);\n}\nvoid NewtonEulerDS::computeJacobianMIntv(double time)\n{\n  computeJacobianMIntv(time, _q, _twist);\n}\n\nvoid NewtonEulerDS::computeJacobianMIntq(double time, SP::SiconosVector q, SP::SiconosVector twist)\n{\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianMIntq(...) starts\");\n  if(_pluginJacqMInt->fPtr)\n    ((FInt_NE)_pluginJacqMInt->fPtr)(time, &(*q)(0), &(*twist)(0), &(*_jacobianMIntq)(0, 0), _qDim,  &(*_q0)(0));\n  else if(_computeJacobianMIntqByFD)\n    computeJacobianMIntqByFD(time, q, twist);\n  DEBUG_EXPR(_jacobianMIntq->display());\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianMIntq(...) ends\");\n\n}\n\nvoid NewtonEulerDS::computeJacobianMIntqByFD(double time, SP::SiconosVector q, SP::SiconosVector twist)\n{\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianMIntqByFD(...) starts\\n\");\n\n  SP::SiconosVector mInt(new SiconosVector(3));\n  computeMInt(time, q, twist, mInt);\n  double mInt0 = mInt->getValue(0);\n  double mInt1 = mInt->getValue(1);\n  double mInt2 = mInt->getValue(2);\n\n  SP::SiconosVector qeps(new SiconosVector(*q));\n\n  (*qeps)(0) += _epsilonFD;\n  for(int j =0; j < 7; j++)\n  {\n    computeMInt(time, qeps, twist, mInt);\n    _jacobianMIntq->setValue(0,j, (mInt->getValue(0) - mInt0)/_epsilonFD);\n    _jacobianMIntq->setValue(1,j, (mInt->getValue(1) - mInt1)/_epsilonFD);\n    _jacobianMIntq->setValue(2,j, (mInt->getValue(2) - mInt2)/_epsilonFD);\n    (*qeps)(j) -= _epsilonFD;\n    if(j<6)(*qeps)(j+1) += _epsilonFD;\n  }\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianMIntqByFD(...) ends\\n\");\n}\n\nvoid NewtonEulerDS::computeJacobianMIntv(double time, SP::SiconosVector q, SP::SiconosVector twist)\n{\n  if(_pluginJactwistMInt->fPtr)\n    ((FInt_NE)_pluginJactwistMInt->fPtr)(time, &(*q)(0), &(*twist)(0), &(*_jacobianMInttwist)(0, 0), _qDim,  &(*_q0)(0));\n  else if(_computeJacobianMInttwistByFD)\n    computeJacobianMIntvByFD(time,  q, twist);\n}\n\nvoid NewtonEulerDS::computeJacobianMIntvByFD(double time, SP::SiconosVector q, SP::SiconosVector twist)\n{\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianMIntvByFD(...) starts\\n\");\n\n  SP::SiconosVector mInt(new SiconosVector(3));\n  computeMInt(time, q, twist, mInt);\n  double mInt0 = mInt->getValue(0);\n  double mInt1 = mInt->getValue(1);\n  double mInt2 = mInt->getValue(2);\n\n  SP::SiconosVector veps(new SiconosVector(*twist));\n\n  (*veps)(0) += _epsilonFD;\n  for(int j =0; j < 6; j++)\n  {\n    computeMInt(time, q, veps, mInt);\n    _jacobianMInttwist->setValue(0,j, (mInt->getValue(0) - mInt0)/_epsilonFD);\n    _jacobianMInttwist->setValue(1,j, (mInt->getValue(1) - mInt1)/_epsilonFD);\n    _jacobianMInttwist->setValue(2,j, (mInt->getValue(2) - mInt2)/_epsilonFD);\n    (*veps)(j) -= _epsilonFD;\n    if(j<5)(*veps)(j+1) += _epsilonFD;\n  }\n  DEBUG_PRINT(\"NewtonEulerDS::computeJacobianMIntvByFD(...) ends\\n\");\n}\n\n\nvoid NewtonEulerDS::computeRhs(double time)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeRhs(double time)\");\n  *_acceleration = *(_p[2]); // Warning: r/p update is done in Interactions/Relations\n\n  computeForces(time, _q, _twist);\n  *_acceleration += *_wrench;\n  DEBUG_EXPR(_wrench->display(););\n\n  if(_inverseMass)\n    _inverseMass->PLUForwardBackwardInPlace(*_acceleration);\n\n\n   // Compute _dotq\n  computeT();\n  prod(*_T, *_twist, *_dotq, true);\n\n  _x[1]->setBlock(0, *_dotq);\n  _x[1]->setBlock(_qDim, *_acceleration);\n\n}\n\nvoid NewtonEulerDS::computeJacobianRhsx(double time)\n{\n  if(_jacobianWrenchq)\n  {\n    SP::SiconosMatrix bloc10 = _jacxRhs->block(1, 0);\n    computeJacobianqForces(time);\n    *bloc10 = *_jacobianWrenchq;\n    _inverseMass->PLUForwardBackwardInPlace(*bloc10);\n  }\n  if(_jacobianWrenchTwist)\n  {\n    SP::SiconosMatrix bloc11 = _jacxRhs->block(1, 1);\n    computeJacobianvForces(time);\n    *bloc11 = *_jacobianWrenchTwist;\n    _inverseMass->PLUForwardBackwardInPlace(*bloc11);\n  }\n\n}\n\nvoid NewtonEulerDS::computeForces(double time)\n{\n  computeForces(time, _q, _twist);\n}\n\n\n/** This function has been added to avoid Swig director to wrap _mGyr into numpy.array\n * when we call  NewtonEulerDS::computeMGyr(SP::SiconosVector twist) that calls in turn\n * computeMGyr(twist, _mGyr)\n */\nstatic\nvoid computeMGyr_internal(SP::SiconosMatrix I ,SP::SiconosVector twist, SP::SiconosVector mGyr)\n{\n  if(I)\n  {\n    DEBUG_EXPR(I->display());\n    DEBUG_EXPR(twist->display());\n    SiconosVector omega(3);\n    SiconosVector iomega(3);\n    omega.setValue(0, twist->getValue(3));\n    omega.setValue(1, twist->getValue(4));\n    omega.setValue(2, twist->getValue(5));\n    prod(*I, omega, iomega, true);\n    cross_product(omega, iomega, *mGyr);\n  }\n}\nvoid NewtonEulerDS::computeMGyr(SP::SiconosVector twist, SP::SiconosVector mGyr)\n{\n  // computation of \\Omega times I \\Omega (MGyr is in the l.h.s of the equation of motion)\n  DEBUG_BEGIN(\"NewtonEulerDS::computeMGyr(SP::SiconosVector twist, SP::SiconosVector mGyr)\\n\");\n\n   ::computeMGyr_internal(_I, twist, mGyr);\n\n  DEBUG_END(\"NewtonEulerDS::computeMGyr(SP::SiconosVector twist, SP::SiconosVector mGyr)\\n\");\n\n}\nvoid NewtonEulerDS::computeMGyr(SP::SiconosVector twist)\n{\n  /*computation of \\Omega times I \\Omega*/\n  //DEBUG_BEGIN(\"NewtonEulerDS::computeMGyr(SP::SiconosVector twist)\\n\");\n  ::computeMGyr_internal(_I , twist, _mGyr);\n  //DEBUG_END(\"NewtonEulerDS::computeMGyr(SP::SiconosVector twist)\\n\");\n\n}\n\n\nvoid NewtonEulerDS::computeForces(double time, SP::SiconosVector q, SP::SiconosVector twist)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeForces(double time, SP::SiconosVector q, SP::SiconosVector twist)\\n\")\n\n  if(_wrench)\n  {\n    _wrench->zero();\n\n    // External wrench\n\n    if(_fExt)\n    {\n      computeFExt(time);\n      assert(!isnan(_fExt->vector_sum()));\n      _wrench->setBlock(0, *_fExt);\n    }\n    if(_mExt)\n    {\n      computeMExt(time);\n      assert(!isnan(_mExt->vector_sum()));\n      if(_isMextExpressedInInertialFrame) {\n        SP::SiconosVector mExt(std11::make_shared<SiconosVector>(*_mExt));\n        ::changeFrameAbsToBody(q,mExt);\n        _wrench->setBlock(3, *mExt);\n      }\n      else\n        _wrench->setBlock(3, *_mExt);\n    }\n\n    // Internal wrench\n\n    if(_fInt)\n    {\n      computeFInt(time, q, twist);\n      assert(!isnan(_fInt->vector_sum()));\n      _wrench->setValue(0, _wrench->getValue(0) - _fInt->getValue(0));\n      _wrench->setValue(1, _wrench->getValue(1) - _fInt->getValue(1));\n      _wrench->setValue(2, _wrench->getValue(2) - _fInt->getValue(2));\n\n    }\n\n    if(_mInt)\n    {\n      computeMInt(time, q , twist);\n      assert(!isnan(_mInt->vector_sum()));\n      _wrench->setValue(3, _wrench->getValue(3) - _mInt->getValue(0));\n      _wrench->setValue(4, _wrench->getValue(4) - _mInt->getValue(1));\n      _wrench->setValue(5, _wrench->getValue(5) - _mInt->getValue(2));\n    }\n\n    // Gyroscopical effect\n    if(!_nullifyMGyr)\n    {\n      computeMGyr(twist);\n      assert(!isnan(_mGyr->vector_sum()));\n      _wrench->setValue(3, _wrench->getValue(3) - _mGyr->getValue(0));\n      _wrench->setValue(4, _wrench->getValue(4) - _mGyr->getValue(1));\n      _wrench->setValue(5, _wrench->getValue(5) - _mGyr->getValue(2));\n    }\n    DEBUG_EXPR(_wrench->display());\n    DEBUG_END(\"NewtonEulerDS::computeForces(double time, SP::SiconosVector q, SP::SiconosVector twist)\\n\")\n\n  }\n  else\n  {\n    RuntimeException::selfThrow(\"NewtonEulerDS::computeForces _wrench is null\");\n  }\n  // else nothing.\n}\n\nvoid NewtonEulerDS::computeJacobianqForces(double time)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeJacobianqWrench(double time) \\n\");\n  if(_jacobianWrenchq)\n  {\n    _jacobianWrenchq->zero();\n    if(_jacobianFIntq)\n    {\n      computeJacobianFIntq(time);\n      _jacobianWrenchq->setBlock(0,0,-1.0 * *_jacobianFIntq);\n    }\n    if(_jacobianMIntq)\n    {\n      computeJacobianMIntq(time);\n    }\n    if(_isMextExpressedInInertialFrame && _mExt)\n    {\n      computeJacobianMExtqExpressedInInertialFrame(time, _q);\n      _jacobianWrenchq->setBlock(3,0,1.0* *_jacobianMExtq);\n    }\n    DEBUG_EXPR(_jacobianWrenchq->display(););\n  }\n  else\n  {\n    RuntimeException::selfThrow(\"NewtonEulerDS::computeJacobianqForces _jacobianWrenchq is null\");\n  }\n  //else nothing.\n  DEBUG_END(\"NewtonEulerDS::computeJacobianqForces(double time) \\n\");\n}\n\nvoid NewtonEulerDS::computeJacobianvForces(double time)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeJacobiantwistForces(double time) \\n\");\n  if(_jacobianWrenchTwist)\n  {\n    _jacobianWrenchTwist->zero();\n    if(_jacobianFInttwist)\n    {\n      computeJacobianFIntv(time);\n      _jacobianWrenchTwist->setBlock(0,0,-1.0 * *_jacobianFInttwist);\n    }\n    if(_jacobianMInttwist)\n    {\n      computeJacobianMIntv(time);\n      _jacobianWrenchTwist->setBlock(3,0,-1.0 * *_jacobianMInttwist);\n    }\n    if(!_nullifyMGyr)\n    {\n      if(_jacobianMGyrtwist)\n      {\n        //computeJacobianMGyrtwistByFD(time,_q,_twist);\n        computeJacobianMGyrtwist(time);\n        _jacobianWrenchTwist->setBlock(3,0,-1.0 * *_jacobianMGyrtwist);\n      }\n    }\n  }\n  //else nothing.\n  DEBUG_END(\"NewtonEulerDS::computeJacobiantwistForces(double time) \\n\");\n}\n\nvoid NewtonEulerDS::computeJacobianMGyrtwist(double time)\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeJacobianMGyrtwist(double time) \\n\");\n  if(_jacobianMGyrtwist)\n  {\n    //Omega /\\ I \\Omega:\n    _jacobianMGyrtwist->zero();\n    SiconosVector omega(3);\n    omega.setValue(0, _twist->getValue(3));\n    omega.setValue(1, _twist->getValue(4));\n    omega.setValue(2, _twist->getValue(5));\n    SiconosVector Iomega(3);\n    prod(*_I, omega, Iomega, true);\n    SiconosVector ei(3);\n    SiconosVector Iei(3);\n    SiconosVector ei_Iomega(3);\n    SiconosVector omega_Iei(3);\n\n    /*See equation of DevNotes.pdf, equation with label eq:NE_nablaFL1*/\n    for(int i = 0; i < 3; i++)\n    {\n      ei.zero();\n      ei.setValue(i, 1.0);\n      prod(*_I, ei, Iei, true);\n      cross_product(omega, Iei, omega_Iei);\n      cross_product(ei, Iomega, ei_Iomega);\n      for(int j = 0; j < 3; j++)\n        _jacobianMGyrtwist->setValue(j, 3 + i, ei_Iomega.getValue(j) + omega_Iei.getValue(j));\n    }\n    // Check if Jacobian is valid. Warning to the transpose operation in\n    // _jacobianMGyrtwist->setValue(3 + j, 3 + i, ei_Iomega.getValue(j) + omega_Iei.getValue(j));\n  }\n  //else nothing.\n  DEBUG_EXPR(_jacobianMGyrtwist->display());\n  // _jacobianMGyrtwist->display();\n  // SP::SimpleMatrix jacobianMGyrtmp (new SimpleMatrix(*_jacobianMGyrtwist));\n  // computeJacobianMGyrtwistByFD(time, _q, _twist);\n  // jacobianMGyrtmp->display();\n  // std::cout << \"#################  \" << (*jacobianMGyrtmp - *_jacobianMGyrtwist).normInf() << std::endl;\n  // assert((*jacobianMGyrtmp - *_jacobianMGyrtwist).normInf()< 1e-10);\n  DEBUG_END(\"NewtonEulerDS::computeJacobianMGyrtwist(double time) \\n\");\n}\n\n\nvoid NewtonEulerDS::display() const\n{\n  std::cout << \"=====> NewtonEuler System display (number: \" << _number << \").\" <<std::endl;\n  std::cout << \"- _ndof : \" << _ndof <<std::endl;\n  std::cout << \"- _qDim : \" << _qDim <<std::endl;\n  std::cout << \"- _n : \" << _n <<std::endl;\n  std::cout << \"- q \" <<std::endl;\n  if(_q) _q->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"- q0 \" <<std::endl;\n  if(_q0) _q0->display();\n  std::cout << \"- twist \" <<std::endl;\n  if(_twist) _twist->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"- twist0 \" <<std::endl;\n  if(_twist0) _twist0->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"- dotq \" <<std::endl;\n  if(_dotq) _dotq->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"- p[0] \" <<std::endl;\n  if(_p[0]) _p[0]->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"- p[1] \" <<std::endl;\n  if(_p[1]) _p[1]->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"- p[2] \" <<std::endl;\n  if(_p[2]) _p[2]->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"mass :\" <<  _scalarMass <<std::endl;\n  std::cout << \"Inertia :\" <<std::endl;\n  if(_I) _I->display();\n  else std::cout << \"-> NULL\" <<std::endl;\n  std::cout << \"===================================== \" <<std::endl;\n}\n\n// --- Functions for memory handling ---\nvoid NewtonEulerDS::initMemory(unsigned int steps)\n{\n  DynamicalSystem::initMemory(steps);\n\n  if(steps == 0)\n    std::cout << \"Warning : NewtonEulerDS::initMemory with size equal to zero\" <<std::endl;\n  else\n  {\n    _qMemory.setMemorySize(steps, _qDim);\n    _twistMemory.setMemorySize(steps, _ndof);\n    _forcesMemory.setMemorySize(steps, _ndof);\n    _dotqMemory.setMemorySize(steps, _qDim);\n    //    swapInMemory(); Useless, done in osi->initializeWorkVectorsForDS\n  }\n}\n\nvoid NewtonEulerDS::swapInMemory()\n{\n  //  _xMemory->swap(_x[0]);\n  _qMemory.swap(*_q);\n  _twistMemory.swap(*_twist);\n  _dotqMemory.swap(*_dotq);\n  _forcesMemory.swap(*_wrench);\n}\n\nvoid NewtonEulerDS::resetAllNonSmoothParts()\n{\n  if(_p[1])\n    _p[1]->zero();\n  else\n    _p[1].reset(new SiconosVector(_ndof));\n}\nvoid NewtonEulerDS::resetNonSmoothPart(unsigned int level)\n{\n  if(_p[level])\n    _p[level]->zero();\n}\n\n\nvoid NewtonEulerDS::computeT()\n{\n  ::computeT(_q,_T);\n}\n\n\n\nvoid NewtonEulerDS::computeTdot()\n{\n  if(!_Tdot)\n  {\n    _Tdot.reset(new SimpleMatrix(_qDim, _ndof));\n    _Tdot->zero();\n  }\n\n  ::computeT(_dotq,_Tdot);\n}\n\n\nvoid NewtonEulerDS::normalizeq()\n{\n  ::normalizeq(_q);\n}\n\nvoid NewtonEulerDS::setComputeJacobianFIntqFunction(const std::string&  pluginPath, const std::string&  functionName)\n{\n  //    Plugin::setFunction(&computeJacobianFIntqPtr, pluginPath,functionName);\n  _pluginJacqFInt->setComputeFunction(pluginPath, functionName);\n  if(!_jacobianFIntq)\n    _jacobianFIntq.reset(new SimpleMatrix(3, _qDim));\n  if(!_jacobianWrenchq)\n    _jacobianWrenchq.reset(new SimpleMatrix(_ndof, _qDim));\n}\nvoid NewtonEulerDS::setComputeJacobianFIntvFunction(const std::string&  pluginPath, const std::string&  functionName)\n{\n  //    Plugin::setFunction(&computeJacobianFIntvPtr, pluginPath,functionName);\n  _pluginJactwistFInt->setComputeFunction(pluginPath, functionName);\n  if(!_jacobianFInttwist)\n    _jacobianFInttwist.reset(new SimpleMatrix(3, _ndof));\n\n}\nvoid NewtonEulerDS::setComputeJacobianFIntqFunction(FInt_NE fct)\n{\n  _pluginJacqFInt->setComputeFunction((void *)fct);\n  if(!_jacobianFIntq)\n    _jacobianFIntq.reset(new SimpleMatrix(3, _qDim));\n  if(!_jacobianWrenchq)\n    _jacobianWrenchq.reset(new SimpleMatrix(_ndof, _qDim));\n}\nvoid NewtonEulerDS::setComputeJacobianFIntvFunction(FInt_NE fct)\n{\n  _pluginJactwistFInt->setComputeFunction((void *)fct);\n  if(!_jacobianFInttwist)\n    _jacobianFInttwist.reset(new SimpleMatrix(3, _ndof));\n  if(!_jacobianWrenchTwist)\n    _jacobianWrenchTwist.reset(new SimpleMatrix(_ndof, _ndof));\n}\n\nvoid NewtonEulerDS::setComputeJacobianMIntqFunction(const std::string&  pluginPath, const std::string&  functionName)\n{\n  _pluginJacqMInt->setComputeFunction(pluginPath, functionName);\n  if(!_jacobianMIntq)\n    _jacobianMIntq.reset(new SimpleMatrix(3, _qDim));\n  if(!_jacobianWrenchq)\n    _jacobianWrenchq.reset(new SimpleMatrix(_ndof, _qDim));\n\n}\nvoid NewtonEulerDS::setComputeJacobianMIntvFunction(const std::string&  pluginPath, const std::string&  functionName)\n{\n  _pluginJactwistMInt->setComputeFunction(pluginPath, functionName);\n  if(!_jacobianMInttwist)\n    _jacobianMInttwist.reset(new SimpleMatrix(3, _ndof));\n  if(!_jacobianWrenchTwist)\n    _jacobianWrenchTwist.reset(new SimpleMatrix(_ndof, _ndof));\n}\nvoid NewtonEulerDS::setComputeJacobianMIntqFunction(FInt_NE fct)\n{\n  _pluginJacqMInt->setComputeFunction((void *)fct);\n  if(!_jacobianMIntq)\n    _jacobianMIntq.reset(new SimpleMatrix(3, _qDim));\n  if(!_jacobianWrenchq)\n    _jacobianWrenchq.reset(new SimpleMatrix(_ndof, _qDim));\n}\nvoid NewtonEulerDS::setComputeJacobianMIntvFunction(FInt_NE fct)\n{\n  _pluginJactwistMInt->setComputeFunction((void *)fct);\n  if(!_jacobianMInttwist)\n    _jacobianMInttwist.reset(new SimpleMatrix(3, _ndof));\n  if(!_jacobianWrenchTwist)\n    _jacobianWrenchTwist.reset(new SimpleMatrix(_ndof, _ndof));\n}\n\n\ndouble NewtonEulerDS::computeKineticEnergy()\n{\n  DEBUG_BEGIN(\"NewtonEulerDS::computeKineticEnergy()\\n\");\n  assert(_twist);\n  assert(_massMatrix);\n  DEBUG_EXPR(_twist->display());\n  DEBUG_EXPR(_massMatrix->display());\n\n  SiconosVector tmp(6);\n  prod(*_massMatrix, *_twist, tmp, true);\n  double K =0.5*inner_prod(tmp,*_twist);\n\n  DEBUG_PRINTF(\"Kinetic Energy = %e\\n\", K);\n  DEBUG_END(\"NewtonEulerDS::computeKineticEnergy()\\n\");\n  return K;\n}\nvoid NewtonEulerDS::setBoundaryConditions(SP::BoundaryCondition newbd)\n{\n  if(!_boundaryConditions)\n  {\n    std::cout << \"Warning : NewtonEulerDS::setBoundaryConditions. old boundary conditions were pre-existing\" <<std::endl;\n  }\n  _boundaryConditions = newbd;\n  _reactionToBoundaryConditions.reset(new SiconosVector(_boundaryConditions->velocityIndices()->size()));\n\n};\n\nSP::SiconosVector NewtonEulerDS::linearVelocity(bool absoluteRef) const\n{\n  // Short-cut: return the _twist 6-vector without modification, first\n  // 3 components are the expected linear velocity.\n  if (absoluteRef)\n    return _twist;\n\n  SP::SiconosVector v(std11::make_shared<SiconosVector>(3));\n  linearVelocity(absoluteRef, *v);\n  return v;\n}\n\nvoid NewtonEulerDS::linearVelocity(bool absoluteRef, SiconosVector &v) const\n{\n  v(0) = (*_twist)(0);\n  v(1) = (*_twist)(1);\n  v(2) = (*_twist)(2);\n\n  /* See _twist: linear velocity is in absolute frame */\n  if (!absoluteRef)\n    changeFrameAbsToBody(*_q, v);\n}\n\nSP::SiconosVector NewtonEulerDS::angularVelocity(bool absoluteRef) const\n{\n  SP::SiconosVector w(std11::make_shared<SiconosVector>(3));\n  angularVelocity(absoluteRef, *w);\n  return w;\n}\n\nvoid NewtonEulerDS::angularVelocity(bool absoluteRef, SiconosVector &w) const\n{\n  w(0) = (*_twist)(3);\n  w(1) = (*_twist)(4);\n  w(2) = (*_twist)(5);\n\n  /* See _twist: angular velocity is in relative frame */\n  if (absoluteRef)\n    changeFrameBodyToAbs(*_q, w);\n}\n\nvoid computeExtForceAtPos(SP::SiconosVector q, bool isMextExpressedInInertialFrame,\n                          SP::SiconosVector force, bool forceAbsRef,\n                          SP::SiconosVector pos, bool posAbsRef,\n                          SP::SiconosVector fExt, SP::SiconosVector mExt,\n                          bool accumulate)\n{\n  assert(!!fExt && fExt->size() == 3);\n  assert(!!force && force->size() == 3);\n  if (pos)\n    assert(!!mExt && mExt->size() == 3);\n\n  SiconosVector abs_frc(*force), local_frc(*force);\n\n  if (forceAbsRef) {\n    if (pos)\n      changeFrameAbsToBody(*q, local_frc);\n  } else\n    changeFrameBodyToAbs(*q, abs_frc);\n\n  if (pos) {\n    assert(!!mExt && mExt->size() >= 3);\n    SiconosVector moment(3);\n    if (posAbsRef) {\n      SiconosVector local_pos(*pos);\n      local_pos(0) -= (*q)(0);\n      local_pos(1) -= (*q)(1);\n      local_pos(2) -= (*q)(2);\n      changeFrameAbsToBody(*q, local_pos);\n      cross_product(local_pos, local_frc, moment);\n    }\n    else {\n      cross_product(*pos, local_frc, moment);\n    }\n\n    if (isMextExpressedInInertialFrame)\n      changeFrameBodyToAbs(*q, moment);\n\n    if (accumulate)\n      *mExt = *mExt + moment;\n    else\n      *mExt = moment;\n  }\n\n  if (accumulate)\n    *fExt += *fExt + abs_frc;\n  else\n    *fExt = abs_frc;\n}\n\nvoid NewtonEulerDS::addExtForceAtPos(SP::SiconosVector force, bool forceAbsRef,\n                                     SP::SiconosVector pos, bool posAbsRef)\n{\n  assert(!!_fExt && _fExt->size() == 3);\n  assert(!!force && force->size() == 3);\n  if (pos)\n    assert(!!_mExt && _mExt->size() == 3);\n\n  computeExtForceAtPos(_q, _isMextExpressedInInertialFrame,\n                       force, forceAbsRef,\n                       pos, posAbsRef,\n                       _fExt, _mExt, true);\n}\n", "meta": {"hexsha": "338d8ec284d9f5cad1370ebc3de808025fb3b37b", "size": 51871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/modelingTools/NewtonEulerDS.cpp", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/modelingTools/NewtonEulerDS.cpp", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/modelingTools/NewtonEulerDS.cpp", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0389129092, "max_line_length": 143, "alphanum_fraction": 0.6814790538, "num_tokens": 17211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4132593268413472}}
{"text": "#include \"utils.h\"\n\n#include <fstream>\n#include <iostream>\n#include <ctime>\n#include <thread>\n\n#include <boost/algorithm/string.hpp>\n#include <boost/format.hpp>\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nstruct Pair {\n    size_t i;\n    size_t j;\n};\n\nvoid reset_columns(MatrixXd& weights,\n                   std::uniform_real_distribution<double_t>& udouble_dist,\n                   std::mt19937& random_engine) {\n#ifdef NO_RESET\n    return;\n#endif\n    if (weights.cols() < 2) return;\n\n    double max_sim = -1;\n    Pair max_indexes;\n    for (size_t i = 0; i < weights.cols() - 1; ++i) {\n        for(size_t j = i + 1; j < weights.cols(); ++j) {\n            VectorXd normalized_column_i = weights.col(i).normalized();\n            VectorXd normalized_column_j = weights.col(j).normalized();\n            double sim = normalized_column_i.dot(normalized_column_j);\n            if (sim > max_sim) {\n                max_indexes.i = i;\n                max_indexes.j = j;\n                max_sim = sim;\n            }\n        }\n    }\n\n    if (max_sim > 0.9 && weights.col(max_indexes.i).norm() > 1) {\n        weights.col(max_indexes.j) += weights.col(max_indexes.i);\n        for(int i = 0; i < weights.rows(); ++i) {\n            weights(i, max_indexes.i) = udouble_dist(random_engine);\n        }\n    }\n}\n\nvoid train_with_features(std::string data_file_path,\n                         std::string features_file_path,\n                         std::string noise_file_path,\n                         int n_steps, double eta_0, double iter_power,\n                         size_t l_dimensions, size_t k_dimensions,\n                         std::string output_file_path,\n                         std::string objective_output_file_path,\n                         double *elapsed_time) {\n    auto random_engine = std::mt19937(std::time(0));\n    time_t start = std::time(0);\n    // Data loading\n    std::fstream data_file_input;\n    data_file_input.open(data_file_path, std::ios::in);\n    std::string line;\n    std::vector<std::string> tokens;\n    getline(data_file_input, line);\n    boost::split(tokens, line, boost::is_any_of(\",\"));\n    size_t data_size = stoul(tokens[0]);\n    size_t n_samples = stoul(tokens[1]);\n\n    std::vector<size_t> start_indexes(n_samples);\n    std::vector<size_t> permutation(n_samples);\n    std::vector<int> data(data_size + n_samples);\n    long n_data = 0;\n    long n_noise = 0;\n    for (size_t i = 0, data_index = 0; i < n_samples; ++i) {\n        getline(data_file_input, line);\n        boost::split(tokens, line, boost::is_any_of(\",\"));\n        start_indexes[i] = data_index;\n        permutation[i] = i;\n        for (size_t j = 0; j < tokens.size(); ++j) {\n            data[data_index + j] = stoi(tokens[j]);\n        }\n        if (data[data_index] == 0) {\n            ++n_noise;\n        } else {\n            ++n_data;\n        }\n        data[data_index + tokens.size()] = -1;\n        data_index += tokens.size() + 1;\n    }\n\n    size_t n_items;\n    size_t m_features;\n    Matrix<double, Dynamic, Dynamic, RowMajor> features;\n    masterthesis::readFeatureFileBoost(\n            features_file_path, n_items, m_features, features);\n\n    std::fstream noise_file_input;\n    noise_file_input.open(noise_file_path, std::ios::in);\n    getline(noise_file_input, line);\n    boost::split(tokens, line, boost::is_any_of(\",\"));\n    VectorXd a_weights(m_features);\n    for (size_t i = 0; i < m_features; ++i) {\n        a_weights(i) = stod(tokens[i]);\n    }\n    getline(noise_file_input, line);\n    boost::split(tokens, line, boost::is_any_of(\",\"));\n    RowVectorXd noise_utilities(n_items);\n    for (size_t i = 0; i < n_items; ++i) {\n        noise_utilities(i) = stod(tokens[i]);\n    }\n\n\n    // Calculate constant quantities.\n    double nu = ((float)n_noise) / ((float)n_data);\n    double log_nu = log(nu);\n    double logz_noise = 0;\n    for (size_t i = 0; i < n_items; ++i) {\n        logz_noise += masterthesis::log1exp(noise_utilities[i]);\n    }\n\n    // Initialize parameters.\n    std::uniform_real_distribution<double_t> udouble_dist(0, 1e-3);\n    MatrixXd b_weights(m_features, l_dimensions);\n    MatrixXd c_weights(m_features, k_dimensions);\n    double n_logz = 0;\n\n    for (size_t i = 0; i < m_features; ++i) {\n        for (size_t j = 0; j < l_dimensions; ++j) {\n            b_weights(i, j) = udouble_dist(random_engine);\n        }\n        for (size_t j = 0; j < k_dimensions; ++j) {\n            c_weights(i, j) = udouble_dist(random_engine);\n        }\n    }\n    VectorXd item_utilities = features*a_weights;\n    for (size_t i = 0; i < n_items; ++i) {\n        n_logz -= masterthesis::log1exp(item_utilities[i]);\n    }\n\n    std::vector<double> objectives(n_steps);\n    VectorXd a_gradient(m_features);\n    MatrixXd b_weights_gradient(m_features, l_dimensions);\n    MatrixXd c_weights_gradient(m_features, k_dimensions);\n\n#ifdef ADAGRAD\n    // for adagrad\n    VectorXd g_a_weights = VectorXd::Constant(m_features, 1e-2);\n    MatrixXd g_b_weights = MatrixXd::Constant(m_features, l_dimensions, 1e-2);\n    MatrixXd g_c_weights = MatrixXd::Constant(m_features, k_dimensions, 1e-2);\n    double g_n_logz = 1e-2;\n#endif\n    // initialize all entries of g_a_weights, g_b_weights, g_c_weights to 1e-2\n    for (size_t iter = 0; iter < n_steps; ++iter) {\n#ifdef COMPUTE_OBJ\n        double objective = 0;\n        for (size_t sub_iter = 0; sub_iter < n_samples; ++sub_iter) {\n            size_t start_idx = start_indexes[sub_iter];\n            size_t end_idx;\n            if (sub_iter == n_samples - 1) {\n                end_idx = data_size + n_samples - 1;\n            } else {\n                end_idx = start_indexes[sub_iter + 1] - 1;\n            }\n            int label = data[start_idx];\n            double p_model = n_logz;\n            double p_noise = -logz_noise;\n\n            size_t set_size = end_idx - start_idx - 1;\n            if (set_size > 0) {\n                Matrix<double, Dynamic, Dynamic, RowMajor> sub_feature_matrix(set_size, m_features);\n                for (size_t i = start_idx + 1; i < end_idx; ++i) {\n                    RowVectorXd feature_row = features.row(data[i]);\n                    sub_feature_matrix.row(i - start_idx - 1) = feature_row;\n                    p_model += feature_row.dot(a_weights);\n                    p_noise += noise_utilities[data[i]];\n                }\n\n                MatrixXd div_weights_slice(set_size, l_dimensions);\n                MatrixXd coh_weights_slice(set_size, k_dimensions);\n                div_weights_slice.noalias() = sub_feature_matrix * b_weights;\n                coh_weights_slice.noalias() = sub_feature_matrix * c_weights;\n                p_model -= div_weights_slice.sum();\n                p_model += div_weights_slice.colwise().maxCoeff().sum();\n                p_model += coh_weights_slice.sum();\n                p_model -= coh_weights_slice.colwise().maxCoeff().sum();\n            }\n            if (label == 1) {\n                objective -= masterthesis::log1exp(log_nu + p_noise - p_model);\n            } else {\n                objective -= masterthesis::log1exp(p_model - log_nu - p_noise);\n            }\n        }\n#ifdef PRINT_DEBUG\n        std::cout << objective << std::endl;\n#endif\n        objectives[iter] = objective;\n#endif\n        shuffle(std::begin(permutation), std::end(permutation), random_engine);\n        for (size_t sub_iter = 0; sub_iter < n_samples; ++sub_iter) {\n            if (sub_iter % 1000 == 0) {\n                reset_columns(b_weights, udouble_dist, random_engine);\n                reset_columns(c_weights, udouble_dist, random_engine);\n            }\n            size_t start_idx = start_indexes[permutation[sub_iter]];\n            size_t end_idx;\n            if (permutation[sub_iter] == n_samples - 1) {\n                end_idx = data_size + n_samples - 1;\n            } else {\n                end_idx = start_indexes[permutation[sub_iter] + 1] - 1;\n            }\n            int label = data[start_idx];\n            double p_model = n_logz;\n            double p_noise = -logz_noise;\n\n            size_t set_size = end_idx - start_idx - 1;\n            a_gradient.setZero();\n            if (set_size > 0) {\n                Matrix<double, Dynamic, Dynamic, RowMajor> sub_feature_matrix(set_size, m_features);\n                MatrixXd div_weights_slice(set_size, l_dimensions);\n                MatrixXd coh_weights_slice(set_size, k_dimensions);\n                for (size_t i = start_idx + 1; i < end_idx; ++i) {\n                    RowVectorXd feature_row = features.row(data[i]);\n                    sub_feature_matrix.row(i - start_idx - 1) = feature_row;\n                    a_gradient += feature_row.transpose();\n                    p_model += feature_row.dot(a_weights);\n                    p_noise += noise_utilities[data[i]];\n                }\n                div_weights_slice.noalias() = sub_feature_matrix * b_weights;\n                coh_weights_slice.noalias() = sub_feature_matrix * c_weights;\n                p_model -= div_weights_slice.sum();\n                p_model += coh_weights_slice.sum();\n\n                for (size_t i = 0; i < l_dimensions; ++i) {\n                    int index;\n                    p_model += div_weights_slice.col(i).maxCoeff(&index);\n                    b_weights_gradient.col(i) = features.row(data[start_idx + 1 + index]).transpose();\n                }\n                for (size_t i = 0; i < k_dimensions; ++i) {\n                    int index;\n                    p_model -= coh_weights_slice.col(i).maxCoeff(&index);\n                    c_weights_gradient.col(i) = features.row(data[start_idx + 1 + index]).transpose();\n                }\n            }\n#ifdef ADAGRAD\n            double learning_rate = eta_0;\n            double tfactor = (label - masterthesis::expit(p_model - p_noise - log_nu));\n            double tfactor_sq = tfactor * tfactor;\n            double step = learning_rate * tfactor;\n#else\n            double learning_rate = eta_0 * pow((iter * n_samples) + sub_iter + 1, -iter_power);\n            double step = learning_rate * (label - masterthesis::expit(p_model - p_noise - log_nu));\n#endif\n            if (set_size > 0) {\n                b_weights_gradient.colwise() -= a_gradient;\n                c_weights_gradient.colwise() -= a_gradient;\n                c_weights_gradient *= -1;\n#ifdef ADAGRAD\n                g_a_weights += tfactor_sq*(a_gradient.cwiseProduct(a_gradient));\n                g_b_weights += tfactor_sq*(b_weights_gradient.cwiseProduct(b_weights_gradient));\n                g_c_weights += tfactor_sq*(c_weights_gradient.cwiseProduct(c_weights_gradient));\n                // element-wise division\n                a_weights += step*(a_gradient.array() / g_a_weights.cwiseSqrt().array()).matrix();\n                b_weights += step*(b_weights_gradient.array() / g_b_weights.cwiseSqrt().array()).matrix();\n                c_weights += step*(c_weights_gradient.array() / g_c_weights.cwiseSqrt().array()).matrix();\n#else\n                a_weights += step*a_gradient;\n                b_weights += step*b_weights_gradient;\n                c_weights += step*c_weights_gradient;\n#endif\n                for (size_t i = 0; i < m_features; ++i) {\n                    for (size_t j = 0; j < l_dimensions; ++j) {\n                        if (b_weights(i, j) < 0) {\n                            b_weights(i, j) = udouble_dist(random_engine);\n                        }\n                    }\n                    for (size_t j = 0; j < k_dimensions; ++j) {\n                        if (c_weights(i, j) < 0) {\n                            c_weights(i, j) = udouble_dist(random_engine);\n                        }\n                    }\n                }\n            }\n#ifdef ADAGRAD\n            g_n_logz += tfactor_sq;\n            n_logz += step / std::sqrt(g_n_logz);\n#else\n            n_logz += step;\n#endif\n        }\n    }\n\n    std::fstream output_file(output_file_path, std::ios::out);\n\n    output_file << n_logz << std::endl;\n    for (size_t i = 0; i < m_features - 1; ++i) {\n        output_file << a_weights[i] << \",\";\n    }\n    output_file << a_weights[m_features - 1] << std::endl;\n\n    for (size_t i = 0; i < m_features; ++i) {\n        if (l_dimensions > 0) {\n            for (size_t j = 0; j < l_dimensions - 1; ++j) {\n                output_file << b_weights(i, j) << \",\";\n            }\n            output_file << b_weights(i, l_dimensions - 1) << std::endl;\n        }\n    }\n\n    for (size_t i = 0; i < m_features; ++i) {\n        if (k_dimensions > 0) {\n            for (size_t j = 0; j < k_dimensions - 1; ++j) {\n                output_file << c_weights(i, j) << \",\";\n            }\n            output_file << c_weights(i, k_dimensions - 1) << std::endl;\n        }\n    }\n\n    output_file.close();\n#ifdef COMPUTE_OBJ\n    std::fstream objective_output_file(\n            objective_output_file_path, std::ios::out);\n\n    for (size_t i = 0; i < n_steps; ++i) {\n        objective_output_file << objectives[i] << std::endl;\n    }\n    std::cout << \"Fold final objective: \" << objectives[n_steps - 1] << std::endl;\n    objective_output_file.close();\n#endif\n    time_t end = std::time(0);\n    double elapsed = std::difftime(end, start);\n    *elapsed_time = elapsed;\n#ifdef PRINT_DEBUG\n    std::cout << \"Fold finished, took: \" << elapsed << \"s.\" << std::endl;\n#endif\n}\n\nstatic const int total_threads = 4;\n\nint main(int argc, char* argv[]) {\n    int fold_number = std::stoi(argv[1]);\n    int l_dimensions = std::stoi(argv[2]);\n    int k_dimensions = std::stoi(argv[3]);\n    char* feature_set = argv[4];\n    char* dataset_name = argv[5];\n    double noise_factor = std::stod(argv[6]);\n    int iterations = std::stoi(argv[7]);\n    double eta_0 = std::stod(argv[8]);\n    std::vector<double> times(fold_number);\n    std::thread thread_pool[total_threads];\n    int used_threads = 0;\n#ifdef ADAGRAD\n    short uses_adagrad = 1;\n#else\n    short uses_adagrad = 0;\n#endif\n    time_t start = std::time(0);\n    for (int i = 1; i <= fold_number; ++i) {\n        if (used_threads == total_threads) {\n            for(size_t j = 0; j < used_threads; ++j) {\n                thread_pool[j].join();\n            }\n            used_threads = 0;\n        }\n        thread_pool[used_threads] = std::thread(train_with_features,\n            (boost::format(\n                    \"/home/diegob/workspace/master-thesis-2015/data/path_set_%1%_nce_data_features_%2%_fold_%3%_noise_%4%.csv\") %\n             dataset_name % feature_set % i % noise_factor).str(),\n            (boost::format(\n                    \"/home/diegob/workspace/master-thesis-2015/data/path_set_%1%_nce_features_%2%.csv\") %\n             dataset_name % feature_set).str(),\n            (boost::format(\n                    \"/home/diegob/workspace/master-thesis-2015/data/path_set_%1%_nce_noise_features_%2%_fold_%3%.csv\") %\n             dataset_name % feature_set % i).str(),\n            iterations, eta_0, 0.1,\n            l_dimensions,\n            k_dimensions,\n            (boost::format(\n                    \"/home/diegob/workspace/master-thesis-2015/data/models/path_set_%1%_nce_out_features_%2%_l_dim_%3%_k_dim_%4%_fold_%5%_iter_%6%_eta_%7%_adagrad_%8%_noise_%9%.csv\") %\n             dataset_name % feature_set % l_dimensions % k_dimensions % i % iterations % eta_0 % uses_adagrad % noise_factor).str(),\n            (boost::format(\n                    \"/home/diegob/workspace/master-thesis-2015/data/models/path_set_%1%_nce_objective_features_%2%_l_dim_%3%_k_dim_%4%_fold_%5%_iter_%6%_eta_%7%_adagrad_%8%_noise_%9%.csv\") %\n             dataset_name % feature_set % l_dimensions % k_dimensions % i % iterations % eta_0 % uses_adagrad % noise_factor).str(),\n            &times[i-1]\n        );\n        ++used_threads;\n    }\n    for(size_t j = 0; j < used_threads; ++j) {\n        thread_pool[j].join();\n    }\n    time_t end = std::time(0);\n    double total_time = std::difftime(end, start);\n    std::fstream times_output_file(\n            (boost::format(\n                    \"/home/diegob/workspace/master-thesis-2015/data/models/path_set_%1%_nce_timing_features_%2%_l_dim_%3%_k_dim_%4%_iter_%5%_eta_%6%_adagrad_%7%_noise_%8%.csv\") %\n             dataset_name % feature_set % l_dimensions % k_dimensions % iterations % eta_0 % uses_adagrad % noise_factor).str(),\n            std::ios::out);\n    times_output_file << total_time << std::endl;\n    for (size_t i = 0; i < fold_number; ++i) {\n        times_output_file << times[i] << std::endl;\n    }\n    times_output_file.close();\n}\n", "meta": {"hexsha": "81de4accae102846e6cbfdf001b90a967eb95cf6", "size": 16372, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppsrc/train_general_fast.cpp", "max_stars_repo_name": "dballesteros7/master-thesis-2015", "max_stars_repo_head_hexsha": "8c0bf9a6eef172fc8167a30780ae0666f8ea2d88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cppsrc/train_general_fast.cpp", "max_issues_repo_name": "dballesteros7/master-thesis-2015", "max_issues_repo_head_hexsha": "8c0bf9a6eef172fc8167a30780ae0666f8ea2d88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppsrc/train_general_fast.cpp", "max_forks_repo_name": "dballesteros7/master-thesis-2015", "max_forks_repo_head_hexsha": "8c0bf9a6eef172fc8167a30780ae0666f8ea2d88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.424691358, "max_line_length": 190, "alphanum_fraction": 0.5698143171, "num_tokens": 4082, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.41325932684134714}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2016 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n\n/*!\\file\n  C++ input file, D1MinusLinearOSI-Time-Stepping version\n  T. Schindler, V. Acary\n\n  Slider-crank simulation with a D1MinusLinearOSI-Time-Stepping scheme\n\n  see Flores/Leine/Glocker : Modeling and analysis of planar rigid multibody systems with\n  translational clearance joints based on the non-smooth dynamics approach\n  */\n#include \"SiconosKernel.hpp\"\n#include <boost/numeric/ublas/matrix.hpp>\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n  try\n  {\n    // ================= Creation of the model =======================\n\n    // parameters according to Table 1\n    unsigned int nDof = 3; // degrees of freedom for robot arm\n    double t0 = 0.0;         // initial computation time\n    double T = 0.2;       // final computation time\n    //T=0.00375;\n    double h = 1e-5;       // time step : do not decrease, because of strong penetrations\n\n    // geometrical characteristics\n    double l1 = 0.1530;\n    double l2 = 0.3060;\n    double a = 0.05;\n    double b = 0.025;\n    double c = 0.001;\n\n    // contact parameters\n    double e1 = 0.4;\n    double e2 = 0.4;\n    double e3 = 0.4;\n    double e4 = 0.4;\n    // e1 = 0.1;\n    // e2 = 0.1;\n    // e3 = 0.1;\n    // e4 = 0.1;\n    //double mu1 = 0.01;\n    //double mu2 = 0.01;\n    //double mu3 = 0.01;\n    //double mu4 = 0.01;\n\n    // initial conditions\n    SP::SiconosVector q0(new SiconosVector(nDof));\n    SP::SiconosVector v0(new SiconosVector(nDof));\n    q0->zero();\n    v0->zero();\n    (*v0)(0) = 150.;\n    (*v0)(1) = -75.;\n\n    // t0 = 7e-5;\n    // (*q0)(0)=  1.129178e-02;\n    // (*q0)(1)= -5.777764e-03;\n    // (*q0)(2)=  0.000000e+00;\n\n    // (*v0)(0) = 1.971606e+02 ;\n    // (*v0)(1) = -1.064301e+02;\n\n    // -------------------------\n    // --- Dynamical systems ---\n    // -------------------------\n    cout << \"====> Model loading ...\" << endl << endl;\n\n    SP::LagrangianDS slider(new LagrangianDS(q0, v0, \"SliderCrankPlugin:mass\"));\n    slider->setComputeFGyrFunction(\"SliderCrankPlugin\", \"FGyr\");\n    slider->setComputeJacobianFGyrqFunction(\"SliderCrankPlugin\", \"jacobianFGyrq\");\n    slider->setComputeJacobianFGyrqDotFunction(\"SliderCrankPlugin\", \"jacobianFGyrqDot\");\n    slider->setComputeFIntFunction(\"SliderCrankPlugin\", \"FInt\");\n    slider->setComputeJacobianFIntqFunction(\"SliderCrankPlugin\", \"jacobianFIntq\");\n    slider->setComputeJacobianFIntqDotFunction(\"SliderCrankPlugin\", \"jacobianFIntqDot\");\n\n    // -------------------\n    // --- Interactions---\n    // -------------------\n    // -- corner 1 --\n    SP::NonSmoothLaw nslaw1(new NewtonImpactNSL(e1));\n    SP::Relation relation1(new LagrangianScleronomousR(\"SliderCrankPlugin:g1\", \"SliderCrankPlugin:W1\", \"SliderCrankPlugin:W1dot\"));\n    SP::Interaction inter1(new Interaction(nslaw1, relation1));\n\n    // -- corner 2 --\n    SP::NonSmoothLaw nslaw2(new NewtonImpactNSL(e2));\n    SP::Relation relation2(new LagrangianScleronomousR(\"SliderCrankPlugin:g2\", \"SliderCrankPlugin:W2\", \"SliderCrankPlugin:W2dot\"));\n    SP::Interaction inter2(new Interaction(nslaw2, relation2));\n\n    // -- corner 3 --\n    SP::NonSmoothLaw nslaw3(new NewtonImpactNSL(e3));\n    SP::Relation relation3(new LagrangianScleronomousR(\"SliderCrankPlugin:g3\", \"SliderCrankPlugin:W3\", \"SliderCrankPlugin:W3dot\"));\n    SP::Interaction inter3(new Interaction(nslaw3, relation3));\n\n    // -- corner 4 --\n    SP::NonSmoothLaw nslaw4(new NewtonImpactNSL(e4));\n    SP::Relation relation4(new LagrangianScleronomousR(\"SliderCrankPlugin:g4\", \"SliderCrankPlugin:W4\", \"SliderCrankPlugin:W4dot\"));\n    SP::Interaction inter4(new Interaction(nslaw4, relation4));\n\n    // -------------\n    // --- Model ---\n    // -------------\n    SP::NonSmoothDynamicalSystem sliderWithClearance(new NonSmoothDynamicalSystem(t0, T));\n    sliderWithClearance->insertDynamicalSystem(slider);\n    sliderWithClearance->link(inter1, slider);\n    sliderWithClearance->link(inter2, slider);\n    sliderWithClearance->link(inter3, slider);\n    sliderWithClearance->link(inter4, slider);\n\n    // ----------------\n    // --- Simulation ---\n    // ----------------\n    SP::D1MinusLinearOSI OSI(new D1MinusLinearOSI(D1MinusLinearOSI::halfexplicit_velocity_level));\n    SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));\n    SP::OneStepNSProblem impact(new LCP());\n    SP::OneStepNSProblem force(new LCP());\n\n    SP::TimeSteppingD1Minus s(new TimeSteppingD1Minus(sliderWithClearance, t, 2));\n    s->insertIntegrator(OSI);\n    s->insertNonSmoothProblem(impact, SICONOS_OSNSP_TS_VELOCITY);\n    s->insertNonSmoothProblem(force, SICONOS_OSNSP_TS_VELOCITY + 1);\n\n\n    // =========================== End of model definition ===========================\n\n    // ================================= Computation =================================\n\n    int N = ceil((T - t0) / h) + 1; // Number of time steps\n\n    // --- Get the values to be plotted ---\n    // -> saved in a matrix dataPlot\n    unsigned int outputSize = 35;\n    SimpleMatrix dataPlot(N + 1, outputSize);\n\n    SP::SiconosVector q = slider->q();\n    SP::SiconosVector v = slider->velocity();\n    int k =0;\n    // computation for a first consistent output\n    inter1->computeOutput(t0,0);\n    inter2->computeOutput(t0,0);\n    inter3->computeOutput(t0,0);\n    inter4->computeOutput(t0,0);\n    \n    dataPlot(k, 0) = sliderWithClearance->t0();\n    dataPlot(k, 1) = (*q)(0) / (2.*M_PI); // crank revolution\n    dataPlot(k, 2) = (*q)(1);\n    dataPlot(k, 3) = (*q)(2);\n    dataPlot(k, 4) = (*v)(0);\n    dataPlot(k, 5) = (*v)(1);\n    dataPlot(k, 6) = (*v)(2);\n    // std::cout << \"(*q)(0)= \" << (*q)(0)<< std::endl;\n    // std::cout << \"(*q)(1)= \" << (*q)(1)<< std::endl;\n\n\n    dataPlot(k, 7) = (l1 * sin((*q)(0)) + l2 * sin((*q)(1)) - a * sin((*q)(2)) + b * cos((*q)(2)) - b) / c; // y corner 1 (normalized)\n    dataPlot(k, 8) = (l1 * sin((*q)(0)) + l2 * sin((*q)(1)) + a * sin((*q)(2)) + b * cos((*q)(2)) - b) / c; // y corner 2 (normalized)\n    dataPlot(k, 9) = (l1 * sin((*q)(0)) + l2 * sin((*q)(1)) - a * sin((*q)(2)) - b * cos((*q)(2)) + b) / (c); // y corner 3 (normalized)\n    dataPlot(k, 10) = (l1 * sin((*q)(0)) + l2 * sin((*q)(1)) + a * sin((*q)(2)) - b * cos((*q)(2)) + b) / (c); // y corner 4 (normalized)\n\n\n    dataPlot(k, 11) = (l1 * cos((*q)(0)) + l2 * cos((*q)(1)) - l2) / l1; // x slider (normalized)\n    dataPlot(k, 12) = (l1 * sin((*q)(0)) + l2 * sin((*q)(1))) / c; // y slider (normalized)\n\n    dataPlot(k, 13) = (*inter1->y(0))(0) ; // g1\n    dataPlot(k, 14) = (*inter2->y(0))(0) ; // g2\n    dataPlot(k, 15) = (*inter3->y(0))(0) ; // g3\n    dataPlot(k, 16) = (*inter4->y(0))(0) ; // g4\n    dataPlot(k, 17) = (*inter1->y(1))(0) ; // dot g1\n    dataPlot(k, 18) = (*inter2->y(1))(0) ; // dot g2\n    dataPlot(k, 19) = (*inter3->y(1))(0) ; // dot g3\n    dataPlot(k, 20) = (*inter4->y(1))(0) ; // dot g4\n    dataPlot(k, 21) = (*inter1->lambda(1))(0) ; // lambda1\n    dataPlot(k, 22) = (*inter2->lambda(1))(0) ; // lambda2\n    dataPlot(k, 23) = (*inter3->lambda(1))(0) ; // lambda3\n    dataPlot(k, 24) = (*inter4->lambda(1))(0) ; // lambda4\n    dataPlot(k, 25) = 0;\n    dataPlot(k, 26) = 0;\n    dataPlot(k, 27) = (*inter1->lambda(2))(0) ; // lambda1_{k+1}^-\n    dataPlot(k, 28) = (*inter2->lambda(2))(0) ; // lambda1_{k+1}^-\n    dataPlot(k, 29) = (*inter3->lambda(2))(0) ; // lambda1_{k+1}^-\n    dataPlot(k, 30) = (*inter4->lambda(2))(0) ; // lambda1_{k+1}^-\n\n    // not yet allocated \n    // dataPlot(k, 31) = ( inter1->lambdaMemory(2).getSiconosVector(0) )(0) ; // lambda1old\n    // dataPlot(k, 32) = ( inter2->lambdaMemory(2).getSiconosVector(0) )(0) ; // lambda1old\n    // dataPlot(k, 33) = ( inter3->lambdaMemory(2).getSiconosVector(0) )(0) ; // lambda1old\n    // dataPlot(k, 34) = ( inter4->lambdaMemory(2).getSiconosVector(0) )(0) ; // lambda1old\n\n\n\n\n\n    // --- Time loop ---\n    cout << \"====> Start computation ... \" << endl << endl;\n\n    // ==== Simulation loop - Writing without explicit event handling =====\n    k++;\n    boost::progress_display show_progress(N);\n\n    boost::timer time;\n    time.restart();\n\n\n//    while ((s->hasNextEvent()) && (k <= 271))\n    while ((s->hasNextEvent()))\n    {\n\n      // std::cout <<\"=====================================================\" <<std::endl;\n      // std::cout <<\"=====================================================\" <<std::endl;\n      // std::cout <<\"=====================================================\" <<std::endl;\n      // std::cout <<\"Iteration k = \" << k <<std::endl;\n      // std::cout <<\"s->nextTime() = \" <<s->nextTime()  <<std::endl;\n      // std::cout <<\"=====================================================\" <<std::endl;\n\n\n      s->advanceToEvent();\n\n      // --- Get values to be plotted ---\n      dataPlot(k, 0) = s->nextTime();\n      dataPlot(k, 1) = (*q)(0) / (2.*M_PI); // crank revolution\n      dataPlot(k, 2) = (*q)(1);\n      dataPlot(k, 3) = (*q)(2);\n      dataPlot(k, 4) = (*v)(0);\n      dataPlot(k, 5) = (*v)(1);\n      dataPlot(k, 6) = (*v)(2);\n      dataPlot(k, 7) = (l1 * sin((*q)(0)) + l2 * sin((*q)(1)) - a * sin((*q)(2)) + b * cos((*q)(2)) - b) / c; // y corner 1 (normalized)\n      dataPlot(k, 8) = (l1 * sin((*q)(0)) + l2 * sin((*q)(1)) + a * sin((*q)(2)) + b * cos((*q)(2)) - b) / c; // y corner 2 (normalized)\n      dataPlot(k, 9) = (l1 * sin((*q)(0)) + l2 * sin((*q)(1)) - a * sin((*q)(2)) - b * cos((*q)(2)) + b) / (c); // y corner 3 (normalized)\n      dataPlot(k, 10) = (l1 * sin((*q)(0)) + l2 * sin((*q)(1)) + a * sin((*q)(2)) - b * cos((*q)(2)) + b) / (c); // y corner 4 (normalized)\n      dataPlot(k, 11) = (l1 * cos((*q)(0)) + l2 * cos((*q)(1)) - l2) / l1; // x slider (normalized)\n      dataPlot(k, 12) = (l1 * sin((*q)(0)) + l2 * sin((*q)(1))) / c; // y slider (normalized)\n      dataPlot(k, 13) = (*inter1->y(0))(0) ; // g1\n      dataPlot(k, 14) = (*inter2->y(0))(0) ; // g2\n      dataPlot(k, 15) = (*inter3->y(0))(0) ; // g3\n      dataPlot(k, 16) = (*inter4->y(0))(0) ; // g4\n      dataPlot(k, 17) = (*inter1->y(1))(0) ; // dot g1\n      dataPlot(k, 18) = (*inter2->y(1))(0) ; // dot g2\n      dataPlot(k, 19) = (*inter3->y(1))(0) ; // dot g3\n      dataPlot(k, 20) = (*inter4->y(1))(0) ; // dot g4\n      dataPlot(k, 21) = (*inter1->lambda(1))(0) ; // Lambda1 (impulse)\n      dataPlot(k, 22) = (*inter2->lambda(1))(0) ; // Lambda2\n      dataPlot(k, 23) = (*inter3->lambda(1))(0) ; // Lambda3\n      dataPlot(k, 24) = (*inter4->lambda(1))(0) ; // Lambda4\n      dataPlot(k, 25) = 0;\n      dataPlot(k, 26) = 0;\n      dataPlot(k, 27) = (*inter1->lambda(2))(0) ; // lambda1_{k+1}^- (nonimpulsive force)\n      dataPlot(k, 28) = (*inter2->lambda(2))(0) ; // lambda1_{k+1}^-\n      dataPlot(k, 29) = (*inter3->lambda(2))(0) ; // lambda1_{k+1}^-\n      dataPlot(k, 30) = (*inter4->lambda(2))(0) ; // lambda1_{k+1}^-\n\n\n\n      dataPlot(k, 31) = ( inter1->lambdaMemory(2).getSiconosVector(0) )(0) ; // lambda1_k^+\n      dataPlot(k, 32) = ( inter2->lambdaMemory(2).getSiconosVector(0) )(0) ; // lambda2_k^+\n      dataPlot(k, 33) = ( inter3->lambdaMemory(2).getSiconosVector(0) )(0) ; // lambda3_k^+\n      dataPlot(k, 34) = ( inter4->lambdaMemory(2).getSiconosVector(0) )(0) ; // lambda4_k^+\n\n      // std::cout << \"dataPlot(k, 27)\" << dataPlot(k, 27)  << std::endl;\n      // std::cout << \"dataPlot(k, 31)\" << dataPlot(k, 31)  << std::endl;\n\n\n\n      // std::cout <<\" q->display()\" <<  std::endl;\n      // q->display();\n      // std::cout <<\" v->display()\" <<  std::endl;\n      // v->display();\n\n\n      s->processEvents();\n      ++show_progress;\n      k++;\n    }\n\n    cout << endl << \"End of computation - Number of iterations done: \" << k - 1 << endl;\n    cout << \"Computation Time \" << time.elapsed()  << endl;\n\n    // --- Output files ---\n    cout << \"====> Output file writing ...\" << endl;\n    dataPlot.resize(k, outputSize);\n    ioMatrix::write(\"result.dat\", \"ascii\", dataPlot, \"noDim\");\n    double error=0.0, eps=1e-11;\n    if ((error=ioMatrix::compareRefFile(dataPlot,\n                                        \"SliderCrankD1MinusLinearOSIVelocityLevel.ref\",\n                                        eps)) >= 0.0\n        && error > eps)\n      return 1;\n    \n  }\n\n  catch (SiconosException e)\n  {\n    cout << e.report() << endl;\n  }\n  catch (...)\n  {\n    cout << \"Exception caught in SliderCrankD1MinusLinear.cpp\" << endl;\n  }\n}\n", "meta": {"hexsha": "4fa40cb162c1d2be1707b42a9174675d08989233", "size": 12839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/Mechanics/SliderCrank/SliderCrankD1MinusLinearVelocityLevel.cpp", "max_stars_repo_name": "bremond/siconos", "max_stars_repo_head_hexsha": "8deea56ff6779379f4f69e0376d24a81562a42d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Mechanics/SliderCrank/SliderCrankD1MinusLinearVelocityLevel.cpp", "max_issues_repo_name": "bremond/siconos", "max_issues_repo_head_hexsha": "8deea56ff6779379f4f69e0376d24a81562a42d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/Mechanics/SliderCrank/SliderCrankD1MinusLinearVelocityLevel.cpp", "max_forks_repo_name": "bremond/siconos", "max_forks_repo_head_hexsha": "8deea56ff6779379f4f69e0376d24a81562a42d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3742138365, "max_line_length": 139, "alphanum_fraction": 0.5467715554, "num_tokens": 4329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4132593204412764}}
{"text": "/*\n * Copyright (c) 2012, Markus Achtelik, ASL, ETH Zurich, Switzerland\n * You can contact the author at <acmarkus at ethz dot ch>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#include <msf_core/similaritytransform.h>\n\n#include <Eigen/Eigenvalues>\n\nnamespace msf_core {\nnamespace similarity_transform {\nFrom6DoF::From6DoF() { }\n\nvoid From6DoF::AddMeasurement(const PosePair & measurement) {\n  measurements_.push_back(measurement);\n}\n\nvoid From6DoF::AddMeasurement(const Pose & pose1, const Pose & pose2) {\n  AddMeasurement(PosePair(pose1, pose2));\n}\n\nbool From6DoF::Compute(Pose & pose, double *scale, double *cond, double eps) {\n  const int n = 4;  // Number of parameters we need to optimize.\n  const int m = measurements_.size();\n\n  if (m < 2)\n    return false;\n\n  Matrix4 M(Matrix4::Zero());  // Quaternion outer sum matrix.\n  // Matrix collecting the measurements for position and scale.\n  Eigen::Matrix<double, Eigen::Dynamic, n> A;\n  A.resize(m * 3, Eigen::NoChange);\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> b;\n  b.resize(m * 3, Eigen::NoChange);\n\n  for (int i = 0; i < m; i++) {\n    // Quaternion averaging.\n    const PosePair & pp = measurements_[i];\n    const Eigen::Quaterniond q1 = GeometryMsgsToEigen(\n        pp.first.pose.orientation);\n    const Eigen::Quaterniond q2 = GeometryMsgsToEigen(\n        pp.second.pose.orientation);\n    Eigen::Quaterniond q(q1.inverse() * q2);\n    M += q.coeffs() * q.coeffs().transpose();  // Order is x y z w here !!!\n\n        //\n    const Vector3 t1 = GeometryMsgsToEigen(pp.first.pose.position);\n    const Vector3 t2 = GeometryMsgsToEigen(pp.second.pose.position);\n\n    A.block<3, 3>(i * 3, 0) = Eigen::Matrix<double, 3, 3>::Identity() * -1;\n    A.block<3, 1>(i * 3, 3) = q1.inverse() * t2;\n    b.block<3, 1>(i * 3, 0) = q1.inverse() * t1;\n  }\n\n  // Mean quaternion.\n  Eigen::SelfAdjointEigenSolver < Eigen::Matrix<double, 4, 4> > q_solver(M);\n  // Eigenvalues/vectors are sorted in increasing order here ...\n  Eigen::Quaterniond q_mean = Eigen::Quaterniond(\n      q_solver.eigenvectors().col(3));\n\n  // Mean position and scale.\n  Matrix4 A_hat = A.transpose() * A;\n  Matrix4 S_hat(Matrix4::Zero());\n  Vector4 b_hat = A.transpose() * b;\n\n  Eigen::JacobiSVD<Matrix4> svd(A_hat,\n                                Eigen::ComputeFullU | Eigen::ComputeFullV);\n  for (int i = 0; i < n; i++) {\n    if (svd.singularValues()[i] < eps)\n      S_hat(i, i) = 0;\n    else\n      S_hat(i, i) = 1 / svd.singularValues()[i];\n  }\n  if (cond)\n    *cond = svd.singularValues()[0] / svd.singularValues()[n - 1];\n\n  Vector4 x = svd.matrixV() * S_hat * svd.matrixU().transpose() * b_hat;\n  if (scale)\n    *scale = x[3];\n\n  pose.pose.position = EigenToGeometryMsgs(x.block<3, 1>(0, 0));\n  pose.pose.orientation = EigenToGeometryMsgs(q_mean);\n\n  return true;\n}\n}\n}  // namespace msf_core\n", "meta": {"hexsha": "f6e43a11728022ef4d596731dcfbaf304f707182", "size": 3325, "ext": "cc", "lang": "C++", "max_stars_repo_path": "dependencies/ethzasl_msf/msf_core/src/similaritytransform.cc", "max_stars_repo_name": "sahibdhanjal/astrobee", "max_stars_repo_head_hexsha": "5bc4e6e58adcf1bc7e1c3719ced736063bba276c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 772.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T23:59:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:15:09.000Z", "max_issues_repo_path": "dependencies/ethzasl_msf/msf_core/src/similaritytransform.cc", "max_issues_repo_name": "sahibdhanjal/astrobee", "max_issues_repo_head_hexsha": "5bc4e6e58adcf1bc7e1c3719ced736063bba276c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 121.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T01:53:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-06T10:18:23.000Z", "max_forks_repo_path": "dependencies/ethzasl_msf/msf_core/src/similaritytransform.cc", "max_forks_repo_name": "sahibdhanjal/astrobee", "max_forks_repo_head_hexsha": "5bc4e6e58adcf1bc7e1c3719ced736063bba276c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 397.0, "max_forks_repo_forks_event_min_datetime": "2015-01-06T10:51:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T05:12:22.000Z", "avg_line_length": 33.25, "max_line_length": 78, "alphanum_fraction": 0.6646616541, "num_tokens": 962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4131540487156097}}
{"text": "// This file is part of PoseEstimation.\n// This file is a modified version of p3p.m <http://rpg.ifi.uzh.ch/software_datasets.html>,\n// see 3-Clause BSD license below.\n// Copyright (c) 2021, Eijiro Shibusawa <phd_kimberlite@yahoo.co.jp>\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this\n//    list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright notice,\n//    this list of conditions and the following disclaimer in the documentation\n//    and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Copyright (c) 2011, Laurent Kneip, ETH Zurich\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above copyright\n//       notice, this list of conditions and the following disclaimer in the\n//       documentation and/or other materials provided with the distribution.\n//     * Neither the name of ETH Zurich nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL ETH ZURICH BE LIABLE FOR ANY\n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef P3P_HPP_\n#define P3P_HPP_\n\n#include <Eigen/Dense>\n\nclass P3PTest;\n\nnamespace P3P\n{\ntemplate <typename FloatType>\nclass P3P {\n\tfriend ::P3PTest;\n\nprivate:\n\ttypedef Eigen::Matrix<std::complex<FloatType>, 4, 1> CMatrix_4x1;\n\ttypedef Eigen::Matrix<FloatType, 3, 1> Matrix_3x1;\n\ttypedef Eigen::Matrix<FloatType, 3, 3> Matrix_3x3;\n\ttypedef Eigen::Matrix<FloatType, 3, 3, Eigen::RowMajor> Matrix_3x3R;\n\ttypedef Eigen::Matrix<FloatType, 4, 1> Matrix_4x1;\n\ttypedef Eigen::Matrix<FloatType, 4, 4> Matrix_4x4;\n\tconst static FloatType m_eps;\n\npublic:\n\t// x = R'*(X - t) =>  x = R*X + t\n\tstatic void convertPose(FloatType *R, FloatType *t)\n\t{\n\t\tEigen::Map<Matrix_3x3R> mR1(R);\n\t\tEigen::Map<Matrix_3x1> mt1(t);\n\t\tMatrix_3x3 mR2 = mR1.transpose();\n\t\tMatrix_3x1 mt2 = -mR2*mt1;\n\t\tmR1 = mR2;\n\t\tmt1 = mt2;\n\t}\n\n\t// x = R'*(X - t)\n\tbool getMatrix(const FloatType *p2dn, const FloatType *p3d, int &nSols, std::vector<FloatType> &Ps)\n\t{\n\t\t// check degenerate case\n\t\tif (checkColinearity(p3d))\n\t\t{\n\t\t\tnSols = 0;\n\t\t\tPs.resize(0);\n\t\t\treturn false;\n\t\t}\n\n\t\t// select P1, f1 and compute T matrix, N matrix\n\t\tselectP1(p2dn, p3d);\n\t\ttransformCoordinate();\n\n\t\t// compute constraints\n\t\tgetConstraints();\n\n\t\t// compute real roots for the constraints\n\t\tgetRealRoot();\n\t\tif (m_realRoots.empty())\n\t\t{\n\t\t\tnSols = 0;\n\t\t\tPs.resize(0);\n\t\t\treturn true;\n\t\t}\n\n\t\t// compute poses corresponding to the real root\n\t\tgetPoses(nSols, Ps);\n\n\t\treturn true;\n\t}\n\nprivate:\n\tinline void getConstraints()\n\t{\n\t\tFloatType pcotn[2] = {m_p[1], m_p[0] * m_phi[0] / m_phi[1] - m_d12 * m_b}; // numerator of Eq. 9\n\t\tFloatType pcotd[2] = {m_p[1] * m_phi[0] / m_phi[1], -m_p[0] +  m_d12}; // denominator of Eq. 9\n\t\tFloatType pcotn2[3] = {}, pcotd2[3] = {}, pcotnd[3] = {}; // nume^2, denom^2, nume*denom\n\t\tpolynomialMultiplication1(pcotn, pcotn, pcotn2);\n\t\tpolynomialMultiplication1(pcotd, pcotd, pcotd2);\n\t\tpolynomialMultiplication1(pcotn, pcotd, pcotnd);\n\t\tFloatType pcotd2n2[3] = {}; // denom^2 + nume^2\n\t\tpcotd2n2[0] = pcotd2[0] + pcotn2[0];\n\t\tpcotd2n2[1] = pcotd2[1] + pcotn2[1];\n\t\tpcotd2n2[2] = pcotd2[2] + pcotn2[2];\n\n\t\tFloatType pcos1[] = {-m_phi[1] * m_phi[1] * m_p[1] * m_p[1], 0, 0}; // term 1 of l.h.s of Eq.10, I think f_2^2 in original equation is phi_2^2\n\t\tpcos1[2] = -pcos1[0];\n\t\tpolynomialMultiplication2(pcos1, pcotd2n2, m_as);\n\n\t\tFloatType p12 = m_p[0] * m_p[0];\n\t\tFloatType p122 = 2 * m_p[0] * m_p[1];\n\t\tFloatType p22 = m_p[1] * m_p[1];\n\t\tm_as[2] -= (p12 * pcotd2[0]); // term 1 of r.h.s of Eq.10\n\t\tm_as[3] -= (p12 * pcotd2[1]);\n\t\tm_as[4] -= (p12 * pcotd2[2]);\n\t\tm_as[1] += (p122 * pcotnd[0]); // term 2 of r.h.s of Eq.10\n\t\tm_as[2] += (p122 * pcotnd[1]);\n\t\tm_as[3] += (p122 * pcotnd[2]);\n\t\tm_as[0] -= (p22 * pcotn2[0]); // term 3 of r.h.s of Eq.10\n\t\tm_as[1] -= (p22 * pcotn2[1]);\n\t\tm_as[2] -= (p22 * pcotn2[2]);\n\t}\n\n\tvoid getPoses(int &nSols, std::vector<FloatType> &Ps)\n\t{\n\t\tnSols = 0;\n\t\tPs.resize((3 + 9) * m_realRoots.size());\n\t\tfor (size_t k = 0; k < m_realRoots.size(); k++)\n\t\t{\n\t\t\tnSols++;\n\t\t\tconst FloatType cos_theta = m_realRoots[k];\n\t\t\tconst FloatType sin_theta = std::sqrt(1 - (cos_theta * cos_theta));\n\t\t\tconst FloatType cot_alpha =\n\t\t\t\t(m_phi[0] * m_p[0] / m_phi[1] + cos_theta * m_p[1] - m_d12 * m_b) /\n\t\t\t\t(m_phi[0] * m_p[1] * cos_theta / m_phi[1] - m_p[0] + m_d12); // Eq. 9\n\t\t\tconst FloatType sin_alpha = std::sqrt(1 / (cot_alpha * cot_alpha + 1));\n\t\t\tFloatType cos_alpha = std::sqrt(1 - (sin_alpha * sin_alpha));\n\t\t\tif (cot_alpha < 0)\n\t\t\t{\n\t\t\t\tcos_alpha = -cos_alpha;\n\t\t\t}\n\n\t\t\tFloatType *pC = &(Ps[(3 + 9) * k]);\n\t\t\tEigen::Map<Matrix_3x1> mC(pC); // Eq. 5\n\t\t\tmC[0] = cos_alpha;\n\t\t\tmC[1] = sin_alpha * cos_theta;\n\t\t\tmC[2] = sin_alpha * sin_theta;\n\n\t\t\tEigen::Map<Matrix_3x3R> mR(pC + 3); // Eq. 6\n\t\t\tmR(0,0) = -mC[0];\n\t\t\tmR(0,1) = -mC[1];\n\t\t\tmR(0,2) = -mC[2];\n\t\t\tmR(1, 0) = sin_alpha;\n\t\t\tmR(1, 1) = -cos_alpha * cos_theta;\n\t\t\tmR(1, 2) = -cos_alpha * sin_theta;\n\t\t\tmR(2, 0) = 0;\n\t\t\tmR(2, 1) = -sin_theta;\n\t\t\tmR(2, 2) = cos_theta;\n\n\t\t\tmC *= (m_d12 * (sin_alpha * m_b + cos_alpha));\n\t\t\tmC = m_mP1 + m_mN.transpose() * mC; // Eq. 12\n\t\t\tmR = m_mN.transpose() * mR.transpose() * m_mT; // Eq. 13\n\t\t}\n\t}\n\n\tinline void getRealRoot()\n\t{\n\t\tm_realRoots.resize(0);\n\t\tMatrix_4x4 mCom; // companion matrix\n\t\tmCom.setZero();\n\t\tmCom(1, 0) = mCom(2, 1) = mCom(3, 2) = 1;\n\t\tmCom(0, 3) = -m_as[4] / m_as[0];\n\t\tmCom(1, 3) = -m_as[3] / m_as[0];\n\t\tmCom(2, 3) = -m_as[2] / m_as[0];\n\t\tmCom(3, 3) = -m_as[1] / m_as[0];\n\t\tEigen::EigenSolver<Matrix_4x4> eig(mCom, false);\n\t\tCMatrix_4x1 mSols = eig.eigenvalues();\n\n\t\tfor (int k = 0; k < 4; k++)\n\t\t{\n\t\t\tif (std::abs(mSols[k].imag()) < m_eps)\n\t\t\t{\n\t\t\t\tm_realRoots.push_back(mSols[k].real());\n\t\t\t}\n\t\t}\n\t}\n\n\tinline void selectP1(const FloatType *f, const FloatType *P)\n\t{\n\t\tconst FloatType *f1 = f;\n\t\tconst FloatType *f2 = f1 + 3;\n\t\tconst FloatType *f3 = f2 + 3;\n\t\t// compute 3rd row of T\n\t\tFloatType T3[3] = {f1[1] * f2[2] - f1[2] * f2[1], f1[2] * f2[0] - f1[0] * f2[2], f1[0] * f2[1] - f1[1] * f2[0]};\n\t\tFloatType sign = T3[0] * f3[0] + T3[1] * f3[1] + T3[2] * f3[2];\n\t\tif (sign > 0)\n\t\t{\n\t\t\tm_f[0] = f + 3;\n\t\t\tm_f[1] = f;\n\t\t\tm_P[0] = P + 3;\n\t\t\tm_P[1] = P;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_f[0] = f;\n\t\t\tm_f[1] = f + 3;\n\t\t\tm_P[0] = P;\n\t\t\tm_P[1] = P + 3;\n\t\t}\n\t\tm_f[2] = f + 6;\n\t\tm_P[2] = P + 6;\n\t\tm_mP1[0] = m_P[0][0];\n\t\tm_mP1[1] = m_P[0][1];\n\t\tm_mP1[2] = m_P[0][2];\n\t}\n\n\tvoid transformCoordinate()\n\t{\n\t\t// compute T matrix\n\t\tm_mT(0, 0) = m_f[0][0];\n\t\tm_mT(0, 1) = m_f[0][1];\n\t\tm_mT(0, 2) = m_f[0][2];\n\t\tm_mT(1, 0) = m_f[1][0];\n\t\tm_mT(1, 1) = m_f[1][1];\n\t\tm_mT(1, 2) = m_f[1][2];\n\t\tFloatType cos_beta = m_mT.row(0).dot(m_mT.row(1));\n\t\tm_mT.row(2) = m_mT.row(0).cross(m_mT.row(1));\n\t\tm_mT.row(1) = m_mT.row(2).cross(m_mT.row(0));\n\t\tm_mT.rowwise().normalize();\n\n\t\t// compute N matrix\n\t\tm_mN(0, 0) = m_P[1][0] - m_P[0][0];\n\t\tm_mN(0, 1) = m_P[1][1] - m_P[0][1];\n\t\tm_mN(0, 2) = m_P[1][2] - m_P[0][2];\n\t\tm_d12 = m_mN.row(0).norm();\n\t\tm_mN(1, 0) = m_P[2][0] - m_P[0][0];\n\t\tm_mN(1, 1) = m_P[2][1] - m_P[0][1];\n\t\tm_mN(1, 2) = m_P[2][2] - m_P[0][2];\n\t\tm_mN.row(2) = m_mN.row(0).cross(m_mN.row(1));\n\t\tm_mN.row(1) = m_mN.row(2).cross(m_mN.row(0));\n\t\tm_mN.rowwise().normalize();\n\n\t\t// compute b\n\t\tm_b = std::sqrt((1 / (1 - (cos_beta * cos_beta))) - 1); // Eq. 3\n\t\tif (cos_beta < 0)\n\t\t{\n\t\t\tm_b = -m_b;\n\t\t}\n\n\t\t// compute phis\n\t\tMatrix_3x1 tmp(m_f[2]);\n\t\ttmp = m_mT * tmp;\n\t\tm_phi[0] = tmp[0] / tmp[2]; // Eq. 8\n\t\tm_phi[1] = tmp[1] / tmp[2]; // Eq. 8\n\n\t\t// compute ps\n\t\ttmp[0] = m_P[2][0];\n\t\ttmp[1] = m_P[2][1];\n\t\ttmp[2] = m_P[2][2];\n\t\ttmp = m_mN * (tmp - m_mP1); // Eq. 2\n\t\tm_p[0] = tmp[0];\n\t\tm_p[1] = tmp[1];\n\t}\n\nprivate:\n\tstatic inline bool checkColinearity(const FloatType *p)\n\t{\n\t\tFloatType p12[3] = {p[3] - p[0], p[4] - p[1], p[5] - p[2]};\n\t\tFloatType p13[3] = {p[6] - p[0], p[7] - p[1], p[8] - p[2]};\n\t\tFloatType pcross[] = {p12[2] * p13[1] - p12[1] * p13[2], p12[0] * p13[2] - p12[2] * p13[0], p12[1] * p13[0] - p12[0] * p13[1]};\n\t\tFloatType ncross = std::sqrt(pcross[0] * pcross[0] + pcross[1] * pcross[1] + pcross[2] * pcross[2]);\n\t\treturn (ncross < m_eps);\n\t}\n\n\t// 1st order polynomial multiplication\n\t// (ax + b) * (cx + d) = (acx^2 + (ad + bc)x + bd)\n\t// p1 = [x 1]\n\t// p2 = [x 1]\n\t// p3 = [x^2 x 1]\n\tstatic inline void polynomialMultiplication1(const FloatType *p1, const FloatType *p2, FloatType *p3)\n\t{\n\t\tp3[0] = (p1[0])*(p2[0]);\t\t\t\t\t// x^2\n\t\tp3[1] = (p1[0])*(p2[1]) + (p1[1])*(p2[0]);\t// x\n\t\tp3[2] = (p1[1])*(p2[1]);\t\t\t\t\t// 1\n\t}\n\n\t// 2nd order polynomial multiplication\n\t// (ax^2 + bx + c) * (dx^2 + ex + f) = (adx^4 + (ae + bd)x^3 + (af + be + cd)x^2 + (bf + ce)x + cf\n\t// p1 = [x^2 x 1]\n\t// p2 = [x^2 x 1]\n\t// p3 = [x^4 x^3 x^2 x 1]\n\tstatic inline void polynomialMultiplication2(const FloatType *p1, const FloatType *p2, FloatType *p3)\n\t{\n\t\tp3[0] = (p1[0])*(p2[0]);\t\t\t\t\t\t\t\t\t\t// x^4\n\t\tp3[1] = (p1[0])*(p2[1]) + (p1[1])*(p2[0]);\t\t\t\t\t\t// x^3\n\t\tp3[2] = (p1[0])*(p2[2]) + (p1[1])*(p2[1]) + (p1[2])*(p2[0]);\t// x^2\n\t\tp3[3] = (p1[1])*(p2[2]) + (p1[2])*(p2[1]);\t\t\t\t\t\t// x\n\t\tp3[4] = (p1[2])*(p2[2]);\t\t\t\t\t\t\t\t\t\t// 1\n\t}\n\nprivate:\n\tconst FloatType *m_f[3]; // pointer to 2D feature vector\n\tconst FloatType *m_P[3]; // pointer to 3D feature vector\n\tMatrix_3x1 m_mP1;\n\tMatrix_3x3 m_mT;\n\tMatrix_3x3 m_mN;\n\tFloatType m_phi[2];\n\tFloatType m_p[2];\n\tFloatType m_b;\n\tFloatType m_d12;\n\tFloatType m_as[5]; // coefficient of 4th order polynomial\n\tstd::vector<FloatType> m_realRoots; // real root for cos_theta polynomial\n};\n\ntemplate <typename FloatType>\nconst FloatType P3P<FloatType>::m_eps = 1E-7;\n}\n\n#endif // P3P_HPP_", "meta": {"hexsha": "3a48c4abd77e6592ce83164eef649840966c1748", "size": 11512, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/P3P.hpp", "max_stars_repo_name": "eshibusawa/PoseEstimation", "max_stars_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/P3P.hpp", "max_issues_repo_name": "eshibusawa/PoseEstimation", "max_issues_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/P3P.hpp", "max_forks_repo_name": "eshibusawa/PoseEstimation", "max_forks_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2716763006, "max_line_length": 144, "alphanum_fraction": 0.6203961084, "num_tokens": 4575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4131540487156096}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2018 Yaghyavardhan Singh Khangarot, Hyderabad, India.\n// Contributed and/or modified by Yaghyavardhan Singh Khangarot,\n//   as part of Google Summer of Code 2018 program.\n\n// This file was modified by Oracle on 2018.\n// Modifications copyright (c) 2018 Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DISCRETE_FRECHET_DISTANCE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DISCRETE_FRECHET_DISTANCE_HPP\n\n#include <algorithm>\n\n#ifdef BOOST_GEOMETRY_DEBUG_FRECHET_DISTANCE\n#include <iostream>\n#endif\n\n#include <iterator>\n#include <utility>\n#include <vector>\n#include <limits>\n\n#include <boost/geometry/algorithms/detail/throw_on_empty_input.hpp>\n#include <boost/geometry/algorithms/not_implemented.hpp>\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/tag.hpp>\n#include <boost/geometry/core/tags.hpp>\n#include <boost/geometry/core/point_type.hpp>\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/strategies/distance_result.hpp>\n#include <boost/geometry/util/range.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace discrete_frechet_distance\n{\n\ntemplate <typename size_type1 , typename size_type2,typename result_type>\nclass coup_mat\n{\npublic:\n    coup_mat(size_type1 w, size_type2 h)\n        : m_data(w * h,-1), m_width(w), m_height(h)\n    {}\n\n    result_type & operator()(size_type1 i, size_type2 j)\n    {\n        BOOST_GEOMETRY_ASSERT(i < m_width && j < m_height);\n        return m_data[j * m_width + i];\n    }\n\nprivate:\n    std::vector<result_type> m_data;\n    size_type1 m_width;\n    size_type2 m_height;\n};\n\nstruct linestring_linestring\n{\n    template <typename Linestring1, typename Linestring2, typename Strategy>\n    static inline typename distance_result\n        <\n            typename point_type<Linestring1>::type,\n            typename point_type<Linestring2>::type,\n            Strategy\n        >::type apply(Linestring1 const& ls1, Linestring2 const& ls2, Strategy const& strategy)\n    {\n        typedef typename distance_result\n            <\n                typename point_type<Linestring1>::type,\n                typename point_type<Linestring2>::type,\n                Strategy\n            >::type result_type;\n        typedef typename boost::range_size<Linestring1>::type size_type1;\n        typedef typename boost::range_size<Linestring2>::type size_type2;\n\n\n        boost::geometry::detail::throw_on_empty_input(ls1);\n        boost::geometry::detail::throw_on_empty_input(ls2);\n\n        size_type1 const a = boost::size(ls1);\n        size_type2 const b = boost::size(ls2);\n\n\n        //Coupling Matrix CoupMat(a,b,-1);\n        coup_mat<size_type1,size_type2,result_type> coup_matrix(a,b);\n\n        result_type const not_feasible = -100;\n        //findin the Coupling Measure\n        for (size_type1 i = 0 ; i < a ; i++ )\n        {\n            for(size_type2 j=0;j<b;j++)\n            {\n                result_type dis = strategy.apply(range::at(ls1,i), range::at(ls2,j));\n                if(i==0 && j==0)\n                    coup_matrix(i,j) = dis;\n                else if(i==0 && j>0)\n                    coup_matrix(i,j) =\n                        (std::max)(coup_matrix(i,j-1), dis);\n                else if(i>0 && j==0)\n                    coup_matrix(i,j) =\n                        (std::max)(coup_matrix(i-1,j), dis);\n                else if(i>0 && j>0)\n                    coup_matrix(i,j) =\n                        (std::max)((std::min)(coup_matrix(i,j-1),\n                                              (std::min)(coup_matrix(i-1,j),\n                                                         coup_matrix(i-1,j-1))),\n                                   dis);\n                else\n                    coup_matrix(i,j) = not_feasible;\n            }\n        }\n\n        #ifdef BOOST_GEOMETRY_DEBUG_FRECHET_DISTANCE\n        //Print CoupLing Matrix\n        for(size_type i = 0; i <a; i++)\n        {\n            for(size_type j = 0; j <b; j++)\n            std::cout << coup_matrix(i,j) << \" \";\n            std::cout << std::endl;\n        }\n        #endif\n\n        return coup_matrix(a-1,b-1);\n    }\n};\n\n}} // namespace detail::frechet_distance\n#endif // DOXYGEN_NO_DETAIL\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\ntemplate\n<\n    typename Geometry1,\n    typename Geometry2,\n    typename Tag1 = typename tag<Geometry1>::type,\n    typename Tag2 = typename tag<Geometry2>::type\n>\nstruct discrete_frechet_distance : not_implemented<Tag1, Tag2>\n{};\n\ntemplate <typename Linestring1, typename Linestring2>\nstruct discrete_frechet_distance\n    <\n        Linestring1,\n        Linestring2,\n        linestring_tag,\n        linestring_tag\n    >\n    : detail::discrete_frechet_distance::linestring_linestring\n{};\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\n/*!\n\\brief Calculate discrete Frechet distance between two geometries (currently\n       works for LineString-LineString) using specified strategy.\n\\ingroup discrete_frechet_distance\n\\tparam Geometry1 \\tparam_geometry\n\\tparam Geometry2 \\tparam_geometry\n\\tparam Strategy A type fulfilling a DistanceStrategy concept\n\\param geometry1 Input geometry\n\\param geometry2 Input geometry\n\\param strategy Distance strategy to be used to calculate Pt-Pt distance\n\n\\qbk{distinguish,with strategy}\n\\qbk{[include reference/algorithms/discrete_frechet_distance.qbk]}\n\n\\qbk{\n[heading Available Strategies]\n\\* [link geometry.reference.strategies.strategy_distance_pythagoras Pythagoras (cartesian)]\n\\* [link geometry.reference.strategies.strategy_distance_haversine Haversine (spherical)]\n[/ \\* more (currently extensions): Vincenty\\, Andoyer (geographic) ]\n\n[heading Example]\n[discrete_frechet_distance_strategy]\n[discrete_frechet_distance_strategy_output]\n}\n*/\ntemplate <typename Geometry1, typename Geometry2, typename Strategy>\ninline typename distance_result\n        <\n            typename point_type<Geometry1>::type,\n            typename point_type<Geometry2>::type,\n            Strategy\n        >::type\ndiscrete_frechet_distance(Geometry1 const& geometry1,\n                          Geometry2 const& geometry2,\n                          Strategy const& strategy)\n{\n    return dispatch::discrete_frechet_distance\n            <\n                Geometry1, Geometry2\n            >::apply(geometry1, geometry2, strategy);\n}\n\n// Algorithm overload using default Pt-Pt distance strategy\n\n/*!\n\\brief Calculate discrete Frechet distance between two geometries (currently\n       work for LineString-LineString).\n\\ingroup discrete_frechet_distance\n\\tparam Geometry1 \\tparam_geometry\n\\tparam Geometry2 \\tparam_geometry\n\\param geometry1 Input geometry\n\\param geometry2 Input geometry\n\n\\qbk{[include reference/algorithms/discrete_frechet_distance.qbk]}\n\n\\qbk{\n[heading Example]\n[discrete_frechet_distance]\n[discrete_frechet_distance_output]\n}\n*/\ntemplate <typename Geometry1, typename Geometry2>\ninline typename distance_result\n        <\n            typename point_type<Geometry1>::type,\n            typename point_type<Geometry2>::type\n        >::type\ndiscrete_frechet_distance(Geometry1 const& geometry1, Geometry2 const& geometry2)\n{\n    typedef typename strategy::distance::services::default_strategy\n              <\n                  point_tag, point_tag,\n                  typename point_type<Geometry1>::type,\n                  typename point_type<Geometry2>::type\n              >::type strategy_type;\n\n    return discrete_frechet_distance(geometry1, geometry2, strategy_type());\n}\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DISCRETE_FRECHET_DISTANCE_HPP\n", "meta": {"hexsha": "70a0c1d11dfe0c6c80640e916c7f1b74fb745576", "size": 7844, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/discrete_frechet_distance.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/discrete_frechet_distance.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/algorithms/discrete_frechet_distance.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 31.376, "max_line_length": 95, "alphanum_fraction": 0.6661142274, "num_tokens": 1788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154240079185319, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4131540487156096}}
{"text": "/*\n * Copyright (c) 2018, The Robot Studio\n *  All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *\t* Redistributions of source code must retain the above copyright notice, this\n *\t  list of conditions and the following disclaimer.\n *\n *\t* Redistributions in binary form must reproduce the above copyright notice,\n *\t  this list of conditions and the following disclaimer in the documentation\n *\t  and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/**\n * @file odometry.cpp\n * @author Cyril Jourdan\n * @date Nov 26, 2018\n * @version 0.1.0\n * @brief File for the odometry of the holonomic base with 3 wheels\n * With help of website https://bharat-robotics.github.io/blog/kinematic-analysis-of-holonomic-robot\n *\n * Contact: cyril.jourdan@therobotstudio.com\n * Created on : Nov 26, 2018\n */\n\n/*** Includes ***/\n#include \"ros/ros.h\"\n#include <sensor_msgs/JointState.h>\n#include <tf/transform_broadcaster.h>\n#include <nav_msgs/Odometry.h>\n#include <osa_msgs/MotorDataMultiArray.h>\n//#include <Eigen/Dense>\n\nusing namespace std;\n\n/*** Variables ***/\nosa_msgs::MotorDataMultiArray motor_data_array;\n\n//to wait for the msg from both posture and anglesArmDescription topics\nbool motor_data_array_arrived = false;\n\n/*** Callback functions ***/\nvoid motorDataArrayCallback(const osa_msgs::MotorDataMultiArrayConstPtr& data)\n{\n\tmotor_data_array = *data;\n\tmotor_data_array_arrived = true;\n}\n\n/*** Main ***/\nint main (int argc, char** argv)\n{\n\t// Initialize ROS\n\tros::init(argc, argv, \"osa_r2p1_odometry_node\");\n\tros::NodeHandle nh(\"~\");\n\n\t//Subscribers\n\tros::Subscriber sub_motor_data_array = nh.subscribe(\"/foldy_base/motor_data_array\", 10, motorDataArrayCallback);\n\n\t//Publishers\n\tros::Publisher odom_pub = nh.advertise<nav_msgs::Odometry>(\"odom\", 10);\n\n\t// initial position\n\tdouble x = 0.0;\n\tdouble y = 0.0;\n\tdouble th = 0.0;\n\n\t// velocity\n\tdouble vx = 0.0;\n\tdouble vy = 0.0;\n\tdouble vth = 0.0;\n\n\t// motor position\n\tint curr_mot_enc_pos[3] = {0};\n\tint prev_mot_enc_pos[3] = {0};\n\tint diff_mot_enc_pos[3] = {0};\n\n\tdouble wheel_lin_vel[3] = {0}; //V1, V2, V3\n\n\tconst double gear_ratio = 28/1;\n\tconst double enc_tic_per_motor_turn = 1000*4; //multiply by 4 for the quadrate encoder\n\tconst double enc_tic_per_shaft_turn = enc_tic_per_motor_turn*gear_ratio;\n\tconst double robot_base_radius = 0.29; //in meters\n\tconst double swedish_wheel_radius = 0.0625;\n\n\tros::Time curr_time;\n\tros::Time prev_time;\n\tcurr_time = ros::Time::now();\n\tprev_time = ros::Time::now();\n\tdouble dt = 0.0;\n\n\tdouble delta_x = 0.0;\n\tdouble delta_y = 0.0;\n\tdouble delta_th = 0.0;\n\n\ttf::TransformBroadcaster broadcaster;\n\tros::Rate loop_rate(20);\n\n\t//const double degree = M_PI/180;\n\n\t// message declarations\n\tgeometry_msgs::TransformStamped odom_trans;\n\todom_trans.header.frame_id = \"odom\";\n\todom_trans.child_frame_id = \"dummy_link\";\n\n\t//grasp first position before starting the loop\n\tif(ros::ok())\n\t{\n\t\tros::spinOnce();\n\n\t\tif(motor_data_array_arrived)\n\t\t{\n\t\t\tprev_time = ros::Time::now();\n\n\t\t\tfor(int i=0; i<3; i++) prev_mot_enc_pos[i] = motor_data_array.motor_data.at(i).position; //fill the prev values\n\n\t\t\tmotor_data_array_arrived = false;\n\t\t}\n\t}\n\n\twhile(ros::ok())\n\t{\n\t\tros::spinOnce();\n\n\t\tif(motor_data_array_arrived)\n\t\t{\n\t\t\t// time calculation\n\t\t\tcurr_time = ros::Time::now();\n\t\t\tdt = (curr_time - prev_time).toSec();\n\n\t\t\t// encoder position\n\t\t\tfor(int i=0; i<3; i++)\n\t\t\t{\n\t\t\t\tcurr_mot_enc_pos[i] = motor_data_array.motor_data.at(i).position;\n\t\t\t\tdiff_mot_enc_pos[i] = curr_mot_enc_pos[i] - prev_mot_enc_pos[i];\n\n\t\t\t\t//Explaination : enc_tic_per_shaft_turn is done in 2*Pi. So an angle theta is done in 2*Pi*diff_enc/enc_tic_per_shaft_turn\n\t\t\t\t// v = d/t so d = theta*r = 2*Pi*r*diff_enc/enc_tic_per_shaft_turn\n\t\t\t\t// then just divide by dt to get the linear velocity of the wheel\n\t\t\t\twheel_lin_vel[i] = (2*M_PI*swedish_wheel_radius*diff_mot_enc_pos[i])/(enc_tic_per_shaft_turn*dt);\n\t\t\t\t\n\t\t\t\t//ROS_INFO(\"Motor %d: enc=%d, diff_enc=%d, lin_vel=%f\", i, curr_mot_enc_pos[i], diff_mot_enc_pos[i], curr_mot_enc_pos[2]);\n\t\t\t}\n\n\t\t\t//ROS_INFO(\"enc1=%d, enc2=%d, enc3=%d\", curr_mot_enc_pos[0], curr_mot_enc_pos[1], curr_mot_enc_pos[2]);\n\n\t\t\t//calculation of theta_dot which is the variable vth here\n\t\t\tvth = -(wheel_lin_vel[0]+wheel_lin_vel[1]+wheel_lin_vel[2])/(3*robot_base_radius);\n\t\t\tdelta_th = vth*dt;\n\n\t\t\t//ROS_INFO(\"delta_th=%f\", delta_th);\n\n\t\t\tvx = -2*(-cos(delta_th)*wheel_lin_vel[0] + cos(M_PI/3-delta_th)*wheel_lin_vel[1]  + cos(M_PI/3+delta_th)*wheel_lin_vel[2])/3; //multiply by -1 to change X direction\n\t\t\tvy = 2*(-sin(delta_th)*wheel_lin_vel[0] - sin(M_PI/3-delta_th)*wheel_lin_vel[1]  + sin(M_PI/3+delta_th)*wheel_lin_vel[2])/3;\n\n\t\t\tdelta_x = vx*dt;\n\t\t\tdelta_y = vy*dt;\n\n\t\t\t//accumulated position rotated by delta_th and final angle, this will drift over time with the accumulated errors\n\t\t\t//The angle of Pi/6 is because of the convention of having a wheel on the X axis as opposed to the Y axis\n\t\t\tx += cos(th-M_PI/6)*delta_x - sin(th-M_PI/6)*delta_y;\n\t\t\ty += sin(th-M_PI/6)*delta_x + cos(th-M_PI/6)*delta_y;\n\t\t\tth += delta_th;\n\n\t\t\tROS_DEBUG(\"vth=%f, delta_th=%f, vx=%f, vy=%f, delta_x=%f, delta_y=%f, x=%f, y=%f, th=%f\", vth, delta_th, vx, vy, delta_x, delta_y, x, y, th);\n\t\t\t//ROS_INFO(\"vx=%f, delta_x=%f, x=%f\", vx, delta_x, x);\n\t\t\t//ROS_INFO(\"dx=%f\", delta_x);\n\t\t\t\n\t\t\tgeometry_msgs::Quaternion odom_quat;\n\t\t\todom_quat = tf::createQuaternionMsgFromRollPitchYaw(0,0,th);\n\n\t\t\t// update transform\n\t\t\todom_trans.header.stamp = curr_time;\n\t\t\todom_trans.transform.translation.x = x;\n\t\t\todom_trans.transform.translation.y = y;\n\t\t\todom_trans.transform.translation.z = 0.0;\n\t\t\todom_trans.transform.rotation = tf::createQuaternionMsgFromYaw(th);\n\n\t\t\t// filling the odometry\n\t\t\tnav_msgs::Odometry odom;\n\t\t\todom.header.stamp = curr_time;\n\t\t\todom.header.frame_id = \"odom\";\n\t\t\todom.child_frame_id = \"dummy_link\";\n\n\t\t\t// position\n\t\t\todom.pose.pose.position.x = x;\n\t\t\todom.pose.pose.position.y = y;\n\t\t\todom.pose.pose.position.z = 0.0;\n\t\t\todom.pose.pose.orientation = odom_quat;\n\n\t\t\t// velocity\n\t\t\todom.twist.twist.linear.x = vx;\n\t\t\todom.twist.twist.linear.y = vy;\n\t\t\todom.twist.twist.linear.z = 0.0;\n\t\t\todom.twist.twist.angular.x = 0.0;\n\t\t\todom.twist.twist.angular.y = 0.0;\n\t\t\todom.twist.twist.angular.z = vth;\n\n\t\t\t// publishing the odometry and the new tf\n\t\t\tbroadcaster.sendTransform(odom_trans);\n\t\t\todom_pub.publish(odom);\n\n\t\t\tmotor_data_array_arrived = false;\n\n\t\t\tprev_time = curr_time;\n\t\t\tprev_mot_enc_pos[0] = curr_mot_enc_pos[0];\n\t\t\tprev_mot_enc_pos[1] = curr_mot_enc_pos[1];\n\t\t\tprev_mot_enc_pos[2] = curr_mot_enc_pos[2];\n\n\t\t\tloop_rate.sleep();\n\t\t}\n\t}\n\n\treturn 0;\n}\n", "meta": {"hexsha": "fdbe0facf2c86bae3bf05b9b120e6446ede88401", "size": 7458, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "airp1_foldy_base_apps/src/odometry.cpp", "max_stars_repo_name": "TheRobotStudio/osa_airp1_foldy_base_robot", "max_stars_repo_head_hexsha": "f30bafb9864059fea138ed4fd27e43a7bf429e80", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "airp1_foldy_base_apps/src/odometry.cpp", "max_issues_repo_name": "TheRobotStudio/osa_airp1_foldy_base_robot", "max_issues_repo_head_hexsha": "f30bafb9864059fea138ed4fd27e43a7bf429e80", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "airp1_foldy_base_apps/src/odometry.cpp", "max_forks_repo_name": "TheRobotStudio/osa_airp1_foldy_base_robot", "max_forks_repo_head_hexsha": "f30bafb9864059fea138ed4fd27e43a7bf429e80", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7105263158, "max_line_length": 167, "alphanum_fraction": 0.7115848753, "num_tokens": 2196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.41315029525335994}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <algorithm>\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Polyhedron_3.h>\n\n//for obj export\n#include <CGAL/IO/print_wavefront.h>\n\n// Simplification function\n#include <CGAL/Surface_mesh_simplification/edge_collapse.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/property_map.h>\n\n// Stop-condition policy\n#include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Count_stop_predicate.h>\n#include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Edge_length_cost.h>\n#include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Midpoint_placement.h>\n\n#include<CGAL/Polyhedron_incremental_builder_3.h>\n\n\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/algorithm/string/trim.hpp>\n\n\n#include <scm/core.h>\n#include <scm/core/math.h>\n\ntypedef CGAL::Simple_cartesian<double> Kernel;\ntypedef CGAL::Polyhedron_3<Kernel> Surface_mesh;\ntypedef Surface_mesh::HalfedgeDS HalfedgeDS;\n\ntypedef boost::graph_traits<Surface_mesh>::vertex_descriptor vertex_descriptor;\n\n\ntypedef CGAL::Surface_mesh<Kernel::Point_3> GMesh;\ntypedef GMesh::Vertex_index vertex_index;\n\nnamespace SMS = CGAL::Surface_mesh_simplification ;\n\n\nstruct GVertex\n{\n  Kernel::Point_3 v_pos;\n  Kernel::Point_2 t_coord;\n  Kernel::Point_3 normal;\n};\n\nchar* getCmdOption(char ** begin, char ** end, const std::string & option) {\n  char ** itr = std::find(begin, end, option);\n  if (itr != end && ++itr != end) {\n      return *itr;\n  }\n  return 0;\n}\n\nbool cmdOptionExists(char** begin, char** end, const std::string& option) {\n  return std::find(begin, end, option) != end;\n}\n\n\n// // A modifier creating a triangle with the incremental builder.\n// template<class HDS>\n// class polyhedron_builder : public CGAL::Modifier_base<HDS> {\n\n// public:\n//   std::vector<double> &coords;\n//   std::vector<int>    &tris;\n\n//   polyhedron_builder( std::vector<double> &_coords, std::vector<int> &_tris ) : coords(_coords), tris(_tris) {}\n\n//   void operator()( HDS& hds) {\n//     typedef typename HDS::Vertex   Vertex;\n//     typedef typename Vertex::Point Point;\n \n//     // create a cgal incremental builder\n//     CGAL::Polyhedron_incremental_builder_3<HDS> B( hds, true);\n//     B.begin_surface( coords.size()/3, tris.size()/3 );\n   \n//     // add the polyhedron vertices\n//     for( int i=0; i<(int)coords.size(); i+=3 ){\n//       B.add_vertex( Point( coords[i+0], coords[i+1], coords[i+2] ) );\n//     }\n   \n//     // add the polyhedron triangles\n//     for( int i=0; i<(int)tris.size(); i+=3 ){\n//       B.begin_facet();\n//       B.add_vertex_to_facet( tris[i+0] );\n//       B.add_vertex_to_facet( tris[i+1] );\n//       B.add_vertex_to_facet( tris[i+2] );\n//       B.end_facet();\n//     }\n   \n//     // finish up the surface\n//     B.end_surface();\n//     }\n// };\n\n//custom function to build a mesh of type Surface Mesh\nvoid build_surface_mesh (GMesh &_gmesh, \n              std::vector<GVertex> &_vertices){\n\n  //to store refs to vertices while the mesh is being built\n  std::vector<vertex_index> v_indices;\n\n  //add vertex positions, record indexes \n  for (int i = 0; i < (int)_vertices.size(); i+=3){\n    vertex_index v1 = _gmesh.add_vertex(_vertices[i].v_pos);\n    vertex_index v2 = _gmesh.add_vertex(_vertices[i+1].v_pos);\n    vertex_index v3 = _gmesh.add_vertex(_vertices[i+2].v_pos);\n\n    //add face \n    _gmesh.add_face(v1, v2, v3);\n\n    // v_indices.push_back(v);\n    v_indices.insert(v_indices.end(), {v1, v2, v3});\n  }\n\n  //add faces\n  // for (int i = 0; i < (int)_vertices.size(); i+=3){\n  //   _gmesh.add_face(v_indices[_tris[i+0]],v_indices[_tris[i+1]], v_indices[_tris[i+2]]);\n  // }\n\n  //create a property map for adding normals\n  //ref: https://doc.cgal.org/4.7/Surface_mesh/index.html#sectionSurfaceMesh_properties\n  GMesh::Property_map<vertex_index, Kernel::Point_3> normal;\n  bool created;\n  boost::tie(normal, created) = \n    _gmesh.add_property_map<vertex_index, Kernel::Point_3>(\"v:normal\", Kernel::Point_3(0,0,0));\n  assert(created);\n\n  //add normals\n  for (int i = 0; i < (int)v_indices.size(); ++i)\n  {\n    normal[v_indices[i]] = _vertices[i].normal;\n    std::cout << normal[v_indices[i]] << std::endl;\n  }\n\n\n\n  // uint32_t num_normals = 0;\n  // BOOST_FOREACH( vertex_index vi, _gmesh.vertices()) { \n  //   normal[vi] = Kernel::Point_3(_normals[num_normals+0], _normals[num_normals+1], _normals[num_normals+2]);\n  //   std::cout << normal[vi] << std::endl;\n  //   num_normals+=3;\n  // }\n\n}\n\n//parses a face string like \"f  2//1  8//1  4//1 \" into 3 given arrays\nvoid parse_face_string (std::string face_string, uint32_t (&index)[3], uint32_t (&coord)[3], uint32_t (&normal)[3]){\n\n  //split by space into faces\n  std::vector<std::string> faces;\n  boost::algorithm::trim(face_string);\n  boost::algorithm::split(faces, face_string, boost::algorithm::is_any_of(\" \"), boost::algorithm::token_compress_on);\n\n  for (int i = 0; i < 3; ++i)\n  {\n    //split by / for indices\n    std::vector<std::string> inds;\n    boost::algorithm::split(inds, faces[i], [](char c){return c == '/';}, boost::algorithm::token_compress_off);\n\n    for (int j = 0; j < (int)inds.size(); ++j)\n    {\n      uint32_t idx = 0;\n      //parse value from string\n      if (inds[j] != \"\"){\n        idx = (uint32_t)stoi(inds[j]);\n      }\n      if (j == 0){index[i] = idx;}\n      else if (j == 1){coord[i] = idx;}\n      else if (j == 2){normal[i] = idx;}\n      \n    }\n  }\n}\n\n\n// load obj function from vt_obj_loader/Utils.h\nvoid load_obj(const std::string& filename, \n              std::vector<GVertex>& vertices){\n\n  std::vector<Kernel::Point_3> v;\n  std::vector<uint32_t> vindices;\n  std::vector<Kernel::Point_3> n;\n  std::vector<uint32_t> nindices;\n  std::vector<Kernel::Point_2> t;\n  std::vector<uint32_t> tindices;\n\n  FILE *file = fopen(filename.c_str(), \"r\");\n\n  if (0 != file) {\n\n    while (true) {\n      char line[128];\n      int32_t l = fscanf(file, \"%s\", line);\n\n      if (l == EOF) break;\n      if (strcmp(line, \"v\") == 0) {\n        double vx, vy, vz;\n        fscanf(file, \"%lf %lf %lf\\n\", &vx, &vy, &vz);\n        v.push_back(Kernel::Point_3(vx,vy,vz));\n      } \n      else if (strcmp(line, \"vn\") == 0) {\n        float nx, ny, nz;\n        fscanf(file, \"%f %f %f\\n\", &nx, &ny, &nz);\n        n.push_back(Kernel::Point_3(nx,ny,nz));\n      } \n      else if (strcmp(line, \"vt\") == 0) {\n        float tx, ty;\n        fscanf(file, \"%f %f\\n\", &tx, &ty);\n        t.push_back(Kernel::Point_2(tx,ty));\n      } \n      else if (strcmp(line, \"f\") == 0) {\n        fgets(line, 128, file);\n        std::string face_string = line; \n        uint32_t index[3];\n        uint32_t coord[3];\n        uint32_t normal[3];\n\n        parse_face_string(face_string, index, coord, normal);\n\n        vindices.insert(vindices.end(), {index[0], index[1], index[2]});\n        tindices.insert(tindices.end(), {coord[0], coord[1], coord[2]});\n        nindices.insert(nindices.end(), {normal[0], normal[1], normal[2]});\n      }\n    }\n\n    fclose(file);\n\n    std::cout << \"positions: \" << v.size() << std::endl;\n    std::cout << \"normals: \" << n.size() << std::endl;\n    std::cout << \"coords: \" << t.size() << std::endl;\n    std::cout << \"faces: \" << vindices.size() << std::endl;\n\n  }\n\n  //read from indices arrays to construct list of vertices in open GL style\n  //http://www.opengl-tutorial.org/beginners-tutorials/tutorial-7-model-loading/\n  for (int i = 0; i < (int)vindices.size(); ++i)\n  {\n    Kernel::Point_3 newv;\n    Kernel::Point_2 newt;\n    Kernel::Point_3 newn;\n\n    //guard against empty arrays \n    if (v.size() == 0) {newv = Kernel::Point_3(0,0,0);}\n    else {newv = v[vindices[i]-1];}\n\n    if (t.size() == 0) {newt = Kernel::Point_2(0,0,0);}\n    else {newt = t[tindices[i]-1];}\n\n    if (n.size() == 0) {newn = Kernel::Point_3(0,0,0);}\n    else {newn = n[nindices[i]-1];}\n\n    GVertex new_Vertex = {newv, newt, newn};\n    vertices.push_back(new_Vertex);\n  }\n\n}\n\n// void output_obj (GMesh &gmesh, const std::string& filename, std::vector<double>& v, std::vector<int>& vindices) {\n//   // https://doc.cgal.org/4.9/Surface_mesh/index.html\n\n//     typedef typename HDS::Vertex   Vertex;\n//     typedef typename Vertex::Point Point;\n  \n//   std::cout << \"all vertices \" << std::endl;\n//   // The vertex iterator type is a nested type of the Vertex_range\n//   GMesh::Vertex_range::iterator  vb, ve;\n//   GMesh::Vertex_range r = gmesh.vertices();\n//   // The iterators can be accessed through the C++ range API\n//   vb = r.begin(); \n//   ve = r.end();\n//   // or the boost Range API\n//   vb = boost::begin(r);\n//   ve = boost::end(r);\n//   // or with boost::tie, as the CGAL range derives from std::pair\n//   for(boost::tie(vb, ve) = gmesh.vertices(); vb != ve; ++vb){\n//     Point p = gmesh.point(*vb);\n//     std::cout << p << std::endl;\n//           // std::cout << *vb << std::endl;\n//   }\n// }\n\n\nint main( int argc, char** argv ) \n{\n  std::string obj_filename = \"dino.obj\";\n  if (cmdOptionExists(argv, argv+argc, \"-f\")) {\n    obj_filename = std::string(getCmdOption(argv, argv + argc, \"-f\"));\n  }\n  else {\n    std::cout << \"Please provide a obj filename using -f <filename.obj>\" << std::endl;\n    return 1;\n  }\n  std::string out_filename = \"data/simplified_mesh.obj\";\n  if (cmdOptionExists(argv, argv+argc, \"-o\")) {\n    out_filename = std::string(getCmdOption(argv, argv + argc, \"-o\"));\n  }\n\n\n  //load OBJ into vertex array\n  std::vector<GVertex> vertices;\n  load_obj( obj_filename, vertices);\n\n  if (vertices.size() == 0 ) {\n    std::cout << \"didnt find any vertices\" << std::endl;\n    return 1;\n  }\n  std::cout << \"Mesh loaded (\" << vertices.size() << \" vertices)\" << std::endl;\n\n  // print loaded obj info\n  // std::cout << \"points\" << std::endl;\n  // for (int i = 0; i < points.size(); i+=3)\n  // {\n  //   std::cout << points[i] << \" \"  << points[i+1] << \" \"  << points[i+2] << std::endl;\n  // }\n  // std::cout << \"faces\" << std::endl;\n  // for (int i = 0; i < tris.size(); i+=3)\n  // {\n  //   std::cout << tris[i] << \" \"  << tris[i+1] << \" \"  << tris[i+2] << std::endl;\n  // }\n  // std::cout << \"normals\" << std::endl;\n  // for (int i = 0; i < normals.size(); i+=3)\n  // {\n  //   std::cout << normals[i] << \" \"  << normals[i+1] << \" \"  << normals[i+2] << std::endl;\n  // }\n  // std::cout << \"norm indexes\" << std::endl;\n  // for (int i = 0; i < n_inds.size(); i+=3)\n  // {\n  //   std::cout << n_inds[i] << \" \"  << n_inds[i+1] << \" \"  << n_inds[i+2] << std::endl;\n  // }\n\n\n  //create a mesh from vectors\n  GMesh gmesh;\n  build_surface_mesh(gmesh, vertices);\n\n  if (gmesh.is_valid(true)){\n    std::cout << \"mesh valid\\n\";\n  }\n\n\n\n  if (!CGAL::is_triangle_mesh(gmesh)){\n    std::cerr << \"Input geometry is not triangulated.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  // This is a stop predicate (defines when the algorithm terminates).\n  // In this example, the simplification stops when the number of undirected edges\n  // left in the surface mesh drops below the specified number (1000)\n  SMS::Count_stop_predicate<Surface_mesh> stop(300);\n\n  std::cout << \"Starting simplification\" << std::endl;\n  \n  // This the actual call to the simplification algorithm.\n  // The surface mesh and stop conditions are mandatory arguments.\n  // The index maps are needed because the vertices and edges\n  // of this surface mesh lack an \"id()\" field.\n  // int r = SMS::edge_collapse\n  //           (gmesh\n  //           ,stop\n  //            ,CGAL::parameters::halfedge_index_map  (get(CGAL::halfedge_external_index  ,gmesh)) \n  //            // ,CGAL::parameters::vertex_index_map(get(CGAL::vertex_external_index,gmesh)) \n  //                              // .halfedge_index_map  (get(CGAL::halfedge_external_index  ,gmesh)) \n  //            //                   .get_cost (SMS::Edge_length_cost <Surface_mesh>())\n  //            //                   .get_placement(SMS::Midpoint_placement<Surface_mesh>())\n  //           );\n  \n  // std::cout << \"\\nFinished...\\n\" << (gmesh.size_of_halfedges()/2) << \" final edges.\\n\" ;\n        \n\n  // output_obj(gmesh,\"bla\", points, tris);\n\n  //write to file\n  std::ofstream ofs(out_filename);\n  ofs << gmesh;\n  // CGAL::print_polyhedron_wavefront(ofs, gmesh);\n  ofs.close();\n  std::cout << \"Simplified mesh was written to \" << out_filename << std::endl;\n\n  \n  return EXIT_SUCCESS ;      \n}", "meta": {"hexsha": "de4ee1683005ac4c471eece87f9a5fe4e33e3186", "size": 12282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/mesh_simplification/main.cpp", "max_stars_repo_name": "gary444/lamure", "max_stars_repo_head_hexsha": "0b57a70d8496cd9632873628dc4064e09c57fef7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "apps/mesh_simplification/main.cpp", "max_issues_repo_name": "gary444/lamure", "max_issues_repo_head_hexsha": "0b57a70d8496cd9632873628dc4064e09c57fef7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apps/mesh_simplification/main.cpp", "max_forks_repo_name": "gary444/lamure", "max_forks_repo_head_hexsha": "0b57a70d8496cd9632873628dc4064e09c57fef7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4923076923, "max_line_length": 117, "alphanum_fraction": 0.6102426315, "num_tokens": 3688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.41311463723602043}}
{"text": "#ifndef EDGE_PLANE_IDENTITY_HPP\n#define EDGE_PLANE_IDENTITY_HPP\n\n#include <Eigen/Dense>\n#include <g2o/core/base_binary_edge.h>\n#include <g2o/types/slam3d_addons/vertex_plane.h>\n\nnamespace g2o {\n\n/**\n * @brief A modified version of g2o::EdgePlane. This class takes care of flipped plane normals.\n *\n */\nclass EdgePlaneIdentity : public BaseBinaryEdge<4, Eigen::Vector4d, VertexPlane, VertexPlane> {\npublic:\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  EdgePlaneIdentity() : BaseBinaryEdge<4, Eigen::Vector4d, VertexPlane, VertexPlane>() {\n    _information.setIdentity();\n    _error.setZero();\n  }\n  void computeError() {\n    const VertexPlane* v1 = static_cast<const VertexPlane*>(_vertices[0]);\n    const VertexPlane* v2 = static_cast<const VertexPlane*>(_vertices[1]);\n\n    Eigen::Vector4d p1 = v1->estimate().toVector();\n    Eigen::Vector4d p2 = v2->estimate().toVector();\n\n    if(p1.dot(p2) < 0.0) {\n      p2 = -p2;\n    }\n\n    _error = (p2 - p1) - _measurement;\n  }\n  virtual bool read(std::istream& is) override {\n    Eigen::Vector4d v;\n    for(int i = 0; i < 4; ++i) {\n      is >> v[i];\n    }\n\n    setMeasurement(v);\n    for(int i = 0; i < information().rows(); ++i) {\n      for(int j = i; j < information().cols(); ++j) {\n        is >> information()(i, j);\n        if(i != j) {\n          information()(j, i) = information()(i, j);\n        }\n      }\n    }\n\n    return true;\n  }\n\n  virtual bool write(std::ostream& os) const override {\n    for(int i = 0; i < 4; ++i) {\n      os << _measurement[i] << \" \";\n    }\n\n    for(int i = 0; i < information().rows(); ++i) {\n      for(int j = i; j < information().cols(); ++j) {\n        os << \" \" << information()(i, j);\n      };\n    }\n    return os.good();\n  }\n\n  virtual void setMeasurement(const Eigen::Vector4d& m) override {\n    _measurement = m;\n  }\n\n  virtual int measurementDimension() const override {\n    return 4;\n  }\n};\n\n}  // namespace g2o\n\n#endif  // EDGE_PLANE_PARALLEL_HPP\n", "meta": {"hexsha": "33f4e280717ba96896214105788059194ed6868e", "size": 1923, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/g2o/edge_plane_identity.hpp", "max_stars_repo_name": "hyunbeen99/kuuve_slam", "max_stars_repo_head_hexsha": "afc7861ba69d656f08c4df73ed15f7721004ba87", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-04T01:44:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T01:44:31.000Z", "max_issues_repo_path": "include/g2o/edge_plane_identity.hpp", "max_issues_repo_name": "hyunbeen99/kuuve_slam", "max_issues_repo_head_hexsha": "afc7861ba69d656f08c4df73ed15f7721004ba87", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/g2o/edge_plane_identity.hpp", "max_forks_repo_name": "hyunbeen99/kuuve_slam", "max_forks_repo_head_hexsha": "afc7861ba69d656f08c4df73ed15f7721004ba87", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-04T01:44:33.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-04T01:44:33.000Z", "avg_line_length": 24.6538461538, "max_line_length": 95, "alphanum_fraction": 0.6047841914, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.41311462966777435}}
{"text": "#include <boost/proto/proto.hpp>\n#include <boost/proto/context/default.hpp>\n#include <boost/mpl/int.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/cmath.hpp>\n#include <type_traits>\n\nstruct x_var {};\n\ntemplate <int v>\nstruct derivative_constant\n{\n\tusing result_type = int;\n\tstatic const int value = v;\n\n\ttemplate <typename ...Args>\n\tresult_type operator()(const Args&... a) const { return v; }\n\n\toperator result_type() const { return v; }\n};\n\ntemplate <int V>\nusing derivative_constant_terminal = typename boost::proto::terminal<derivative_constant<V>>::type;\n\nstruct derivative_grammar;\n\ntemplate<typename Expr>\nstruct derivative_expr;\n\nnamespace derivative_detail\n{\n\tstruct optimize\n\t\t: boost::proto::switch_<struct optimize_cases_>\n\t{};\n\n\tstruct expr_generator\n\t{\n\t\tBOOST_PROTO_CALLABLE()\n\t\tBOOST_PROTO_USE_BASIC_EXPR()\n\n\t\ttemplate<typename Sig>\n\t\tstruct result;\n\n\t\ttemplate<typename This, typename Expr>\n\t\tstruct result<This(Expr)>\n\t\t{\n\t\t\ttypedef derivative_expr<Expr> type;\n\t\t};\n\n\t\ttemplate<typename This, typename Expr>\n\t\tstruct result<This(Expr &)>\n\t\t{\n\t\t\ttypedef derivative_expr<Expr> type;\n\t\t};\n\n\t\ttemplate<typename This, typename Expr>\n\t\tstruct result<This(Expr const &)>\n\t\t{\n\t\t\ttypedef derivative_expr<Expr> type;\n\t\t};\n\n\t\ttemplate<typename Expr>\n\t\tderivative_expr<Expr> operator ()(Expr const &e) const\n\t\t{\n\t\t\tderivative_expr<Expr> that = { e };\n\t\t\treturn that;\n\t\t}\n\t};\n\n}\n\nstruct domain\n\t: boost::proto::domain< derivative_detail::expr_generator, derivative_grammar >\n{\n\ttemplate< typename T >\n\tstruct as_child\n\t\t: proto_base_domain::as_expr< T >\n\t{};\n};\n\ntemplate< int Exp >\nstruct pow_fun\n{\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename T>\n\tstruct result<This(T)>\n\t{\n\t\tusing type = T;\n\t\tBOOST_FORCEINLINE static type apply(const T& t) { using std::pow; return pow(t, Exp); }\n\t};\n\n\ttemplate <typename This, typename Units, typename T>\n\tstruct result<This(boost::units::quantity<Units,T>)>\n\t{\n\t\tusing type = decltype(boost::units::pow<Exp>(std::declval<boost::units::quantity<Units,T>>()));\n\t\tBOOST_FORCEINLINE static type apply(const boost::units::quantity<Units,T>& t) { using boost::units::pow; return pow<Exp>(t); }\n\t};\n\n\ttemplate <typename T>\n\tBOOST_FORCEINLINE typename result<pow_fun<Exp>(T)>::type operator()(const T& d) const\n\t{\n\t\treturn result<pow_fun<Exp>(T)>::apply(d);\n\t}\n};\n\ntemplate< int Exp, typename Arg >\nBOOST_FORCEINLINE typename boost::proto::result_of::make_expr<boost::proto::tag::function, pow_fun< Exp >, Arg>::type const pow(Arg arg)\n{\n\treturn boost::proto::make_expr<boost::proto::tag::function>(pow_fun<Exp>(), arg);\n}\n\nstruct sin_fun\n{\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename T>\n\tstruct result<This(T)>\n\t{\n\t\tusing type = T;\n\n\t\tBOOST_FORCEINLINE static type apply(const T& t) { using std::sin; return sin(t); }\n\t};\n\n\ttemplate <typename This, typename Units, typename T>\n\tstruct result<This(boost::units::quantity<Units, T>)>\n\t{\n\t\tusing type = decltype(boost::units::sin(std::declval<boost::units::quantity<Units, T>>()));\n\t\tBOOST_FORCEINLINE static type apply(const boost::units::quantity<Units, T>& t) { using boost::units::sin; return sin(t); }\n\t};\n\n\ttemplate <typename T>\n\tBOOST_FORCEINLINE typename result<sin_fun(T)>::type operator()(const T& d) const\n\t{\n\t\treturn result<sin_fun(T)>::apply(d);\n\t}\n};\n\ntemplate< typename Arg >\nBOOST_FORCEINLINE typename boost::proto::result_of::make_expr<boost::proto::tag::function, sin_fun, Arg>::type const sin(Arg arg)\n{\n\treturn boost::proto::make_expr<boost::proto::tag::function>(sin_fun(), arg);\n}\n\nstruct cos_fun\n{\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename T>\n\tstruct result<This(T)>\n\t{\n\t\tusing type = T;\n\n\t\tBOOST_FORCEINLINE static type apply(const T& t) { using std::cos; return cos(t); }\n\t};\n\n\ttemplate <typename This, typename Units, typename T>\n\tstruct result<This(boost::units::quantity<Units, T>)>\n\t{\n\t\tusing type = decltype(boost::units::cos(std::declval<boost::units::quantity<Units, T>>()));\n\t\tBOOST_FORCEINLINE static type apply(const boost::units::quantity<Units, T>& t) { using boost::units::cos; return cos(t); }\n\t};\n\n\ttemplate <typename T>\n\tBOOST_FORCEINLINE typename result<cos_fun(T)>::type operator()(const T& d) const\n\t{\n\t\treturn result<cos_fun(T)>::apply(d);\n\t}\n};\n\ntemplate< typename Arg >\nBOOST_FORCEINLINE typename boost::proto::result_of::make_expr<boost::proto::tag::function, cos_fun, Arg>::type const cos(Arg arg)\n{\n\treturn boost::proto::make_expr<boost::proto::tag::function>(cos_fun(), arg);\n}\n\nstruct exp_fun\n{\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename T>\n\tstruct result<This(T)>\n\t{\n\t\tusing type = T;\n\n\t\tBOOST_FORCEINLINE static type apply(const T& t) { using std::exp; return exp(t); }\n\t};\n\n\ttemplate <typename This, typename Units, typename T>\n\tstruct result<This(boost::units::quantity<Units, T>)>\n\t{\n\t\tusing type = decltype(boost::units::exp(std::declval<boost::units::quantity<Units, T>>()));\n\t\tBOOST_FORCEINLINE static type apply(const boost::units::quantity<Units, T>& t) { using boost::units::exp; return exp(t); }\n\t};\n\n\ttemplate <typename T>\n\tBOOST_FORCEINLINE typename result<exp_fun(T)>::type operator()(const T& d) const\n\t{\n\t\treturn result<exp_fun(T)>::apply(d);\n\t}\n};\n\ntemplate< typename Arg >\nBOOST_FORCEINLINE typename boost::proto::result_of::make_expr<boost::proto::tag::function, exp_fun, Arg>::type const exp(Arg arg)\n{\n\treturn boost::proto::make_expr<boost::proto::tag::function>(exp_fun(), arg);\n}\n\nstruct tan_fun\n{\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename T>\n\tstruct result<This(T)>\n\t{\n\t\tusing type = T;\n\n\t\tBOOST_FORCEINLINE static type apply(const T& t) { using std::tan; return tan(t); }\n\t};\n\n\ttemplate <typename This, typename Units, typename T>\n\tstruct result<This(boost::units::quantity<Units, T>)>\n\t{\n\t\tusing type = decltype(boost::units::tan(std::declval<boost::units::quantity<Units, T>>()));\n\t\tBOOST_FORCEINLINE static type apply(const boost::units::quantity<Units, T>& t) { using boost::units::tan; return tan(t); }\n\t};\n\n\ttemplate <typename T>\n\tBOOST_FORCEINLINE typename result<tan_fun(T)>::type operator()(const T& d) const\n\t{\n\t\treturn result<tan_fun(T)>::apply(d);\n\t}\n};\n\ntemplate< typename Arg >\nBOOST_FORCEINLINE typename boost::proto::result_of::make_expr<boost::proto::tag::function, tan_fun, Arg>::type const tan(Arg arg)\n{\n\treturn boost::proto::make_expr<boost::proto::tag::function>(tan_fun(), arg);\n}\n\nstruct sqrt_fun\n{\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename T>\n\tstruct result<This(T)>\n\t{\n\t\tusing type = T;\n\n\t\tBOOST_FORCEINLINE static type apply(const T& t) { using std::sqrt; using std::abs; return sqrt(abs(t)); }\n\t};\n\n\ttemplate <typename This, typename Units, typename T>\n\tstruct result<This(boost::units::quantity<Units, T>)>\n\t{\n\t\tusing type = decltype(boost::units::root<2>(std::declval<boost::units::quantity<Units, T>>()));\n\t\tBOOST_FORCEINLINE static type apply(const boost::units::quantity<Units, T>& t) { using boost::units::abs; return boost::units::root<2>(abs(t)); }\n\t};\n\n\ttemplate <typename T>\n\tBOOST_FORCEINLINE typename result<sqrt_fun(T)>::type operator()(const T& d) const\n\t{\n\t\treturn result<sqrt_fun(T)>::apply(d);\n\t}\n};\n\ntemplate< typename Arg >\nBOOST_FORCEINLINE typename boost::proto::result_of::make_expr<boost::proto::tag::function, sqrt_fun, Arg>::type const sqrt(Arg arg)\n{\n\treturn boost::proto::make_expr<boost::proto::tag::function>(sqrt_fun(), arg);\n}\n\nstruct log_fun\n{\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename T>\n\tstruct result<This(T)>\n\t{\n\t\tusing type = T;\n\n\t\tBOOST_FORCEINLINE static type apply(const T& t) { using std::log; return log(t); }\n\t};\n\n\ttemplate <typename This, typename Units, typename T>\n\tstruct result<This(boost::units::quantity<Units, T>)>\n\t{\n\t\tusing type = decltype(boost::units::log(std::declval<boost::units::quantity<Units, T>>()));\n\t\tBOOST_FORCEINLINE static type apply(const boost::units::quantity<Units, T>& t) { using boost::units::log; return log(t); }\n\t};\n\n\ttemplate <typename T>\n\tBOOST_FORCEINLINE typename result<log_fun(T)>::type operator()(const T& d) const\n\t{\n\t\treturn result<log_fun(T)>::apply(d);\n\t}\n};\n\ntemplate< typename Arg >\nBOOST_FORCEINLINE typename boost::proto::result_of::make_expr<boost::proto::tag::function, log_fun, Arg>::type const log(Arg arg)\n{\n\treturn boost::proto::make_expr<boost::proto::tag::function>(log_fun(), arg);\n}\n\ntemplate <typename T>\nstruct evaluation_context : boost::proto::callable_context<evaluation_context<T> const> {\n\tT value;\n\n\texplicit evaluation_context(T value)\n\t\t: value(value)\n\t{}\n\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename Tag, int V>\n\tstruct result<This(Tag, derivative_constant<V>)>\n\t{\n\t\tusing type = double;\n\t};\n\n\ttemplate <typename This, typename Tag, int V>\n\tstruct result<This(Tag, const derivative_constant<V>&)>\n\t{\n\t\tusing type = double;\n\t};\n\n\ttemplate <typename This, typename Tag>\n\tstruct result<This(Tag, x_var)>\n\t{\n\t\tusing type = T;\n\t};\n\n\ttemplate <typename This, typename Tag>\n\tstruct result<This(Tag, const x_var&)>\n\t{\n\t\tusing type = T;\n\t};\n\n\ttemplate <int V>\n\tBOOST_FORCEINLINE double operator()(boost::proto::tag::terminal, derivative_constant<V>) const\n\t{\n\t\treturn V;\n\t}\n\n\tBOOST_FORCEINLINE T operator()(boost::proto::tag::terminal, x_var) const\n\t{\n\t\treturn value;\n\t}\n};\n\ntemplate<typename Expr>\nstruct derivative_expr : boost::proto::extends<Expr, derivative_expr<Expr>, domain> \n{\n\ttypedef boost::proto::extends<Expr, derivative_expr<Expr>, domain> base_type;\n\n\tderivative_expr(Expr const& expr = Expr())\n\t\t: base_type(expr)\n\t{}\n\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename T>\n\tstruct result<This(T)>\n\t{\n\t\tusing raw_type = typename boost::proto::result_of::eval<Expr, evaluation_context<T>>::type;\n\t\tusing type = typename boost::remove_const<typename boost::remove_reference<raw_type>::type>::type;\n\t};\n\t\n\ttemplate <typename T>\n\tBOOST_FORCEINLINE typename result<derivative_expr(T)>::type operator()(T d) const\n\t{\n\t\tevaluation_context<T> context(d);\n\t\treturn boost::proto::eval(*this, context);\n\t}\n};\n\n//! Constants\nstruct constant_rule : boost::proto::callable\n{\n\tusing result_type = derivative_expr <boost::proto::terminal<derivative_constant<0>>::type>;\n\n\tBOOST_FORCEINLINE result_type operator()() const\n\t{\n\t\treturn result_type();\n\t}\n};\n\n//! Derivative Variable\nstruct derivative_variable_rule : boost::proto::callable\n{\n\tusing result_type = derivative_expr <boost::proto::terminal<derivative_constant<1>>::type>;\n\n\tBOOST_FORCEINLINE result_type operator()() const\n\t{\n\t\treturn result_type();\n\t}\n};\n\n//! Addition\n\nnamespace derivative_detail {\n\n\ttemplate<typename Tag>\n\tstruct make_optimized_binary\n\t{\n\t\tBOOST_PROTO_CALLABLE();\n\t\tBOOST_PROTO_POLY_FUNCTION();\n\n\t\tusing Domain = boost::proto::domainns_::deduce_domain;\n\n\t\ttemplate<typename Sig>\n\t\tstruct result;\n\n\t\ttemplate<typename This, typename A0, typename A1>\n\t\tstruct result<This(A0, A1)>\n\t\t{\n\t\t\tusing raw_type = typename boost::proto::result_of::make_expr<Tag, Domain, A0, A1>::type;\n\n\t\t\tusing type = typename boost::result_of<optimize(raw_type)>::type;\n\t\t};\n\n\t\t/// Construct an expression node with tag type \\c Tag\n\t\t/// and in the domain \\c Domain.\n\t\t///\n\t\t/// \\return <tt>proto::make_expr\\<Tag, Domain\\>(a0,...aN)</tt>\n\t\ttemplate<typename A0, typename A1>\n\t\tBOOST_FORCEINLINE\n\t\ttypename result<make_optimized_binary<Tag>(A0,A1)>::type const operator ()(A0 const &a0, A1 const& a1) const\n\t\t{\n\t\t\tauto result = optimize()(boost::proto::detail::make_expr_<Tag, Domain, A0 const, A1 const>()(a0, a1));\n\t\t\t//boost::proto::display_expr(result, std::cout);\n\t\t\treturn result;\n\t\t}\n\n\t\t/// INTERNAL ONLY\n\t\t///\n\t\ttemplate<typename A0, typename A1>\n\t\tstruct impl\n\t\t\t: boost::proto::detail::make_expr_<Tag, Domain, A0, A1>\n\t\t{};\n\t};\n\t\t\n\tstruct optimize_cases_\n\t{\n\t\ttemplate <typename Tag, int D = 0>\n\t\tstruct case_ : boost::proto::not_<boost::proto::_> {};\n\n\t\ttemplate <int D>\n\t\tstruct case_<boost::proto::tag::plus, D>\n\t\t\t: boost::proto::or_\n\t\t\t  <\n\t\t\t\tboost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::plus, boost::proto::_, boost::proto::terminal<derivative_constant<0>> >\n\t\t\t\t,\toptimize(boost::proto::_left)\n\t\t\t\t>\n\t\t\t\t, boost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::plus, boost::proto::terminal<derivative_constant<0>>, boost::proto::_ >\n\t\t\t\t,\toptimize(boost::proto::_right)\n\t\t\t\t>\n\t\t\t\t, boost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::plus, boost::proto::_, boost::proto::_ >\n\t\t\t\t,\tmake_optimized_binary<boost::proto::tag::plus>(optimize(boost::proto::_left), optimize(boost::proto::_right))\n\t\t\t\t>\n\t\t\t\t, boost::proto::otherwise<boost::proto::_expr>\n\t\t\t  >\n\t\t{};\n\n\t\ttemplate <int D>\n\t\tstruct case_<boost::proto::tag::minus, D>\n\t\t\t: boost::proto::or_\n\t\t\t  <\n\t\t\t\tboost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::minus, boost::proto::_, boost::proto::terminal<derivative_constant<0>> >\n\t\t\t\t,\toptimize(boost::proto::_left)\n\t\t\t\t>\n\t\t\t\t, boost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::minus, boost::proto::terminal<derivative_constant<0>>, boost::proto::_ >\n\t\t\t\t,\tboost::proto::_make_negate(optimize(boost::proto::_right))\n\t\t\t\t>\n\t\t\t\t, boost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::minus, boost::proto::_, boost::proto::_ >\n\t\t\t\t,\tboost::proto::call<make_optimized_binary<boost::proto::tag::minus>(optimize(boost::proto::_left), optimize(boost::proto::_right))>\n\t\t\t\t>\n\t\t\t\t, boost::proto::otherwise<boost::proto::_expr>\n\t\t\t  >\n\t\t{};\n\t\t\n\t\ttemplate <int D>\n\t\tstruct case_<boost::proto::tag::multiplies, D>\n\t\t\t: boost::proto::or_\n\t\t\t  <\n\t\t\t\tboost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::multiplies, boost::proto::_, boost::proto::terminal<derivative_constant<0>> >\n\t\t\t\t,\tconstant_rule()\n\t\t\t\t>\n\t\t\t\t, boost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::multiplies, boost::proto::terminal<derivative_constant<0>>, boost::proto::_ >\n\t\t\t\t,\tconstant_rule()\n\t\t\t\t>\n\t\t\t\t, boost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::multiplies, boost::proto::_, boost::proto::terminal<derivative_constant<1>> >\n\t\t\t\t,\toptimize(boost::proto::_left)\n\t\t\t\t>\n\t\t\t\t, boost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::multiplies, boost::proto::terminal<derivative_constant<1>>, boost::proto::_ >\n\t\t\t\t,\toptimize(boost::proto::_right)\n\t\t\t\t>\n\t\t\t\t, boost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::multiplies, boost::proto::_, boost::proto::_ >\n\t\t\t\t,\tboost::proto::call<make_optimized_binary<boost::proto::tag::multiplies>(optimize(boost::proto::_left), optimize(boost::proto::_right))>\n\t\t\t\t>\n\t\t\t\t, boost::proto::otherwise<boost::proto::_expr>\n\t\t\t  >\n\t\t{};\n\n\t\ttemplate <int D>\n\t\tstruct case_<boost::proto::tag::divides, D>\n\t\t\t: boost::proto::or_\n\t\t\t  <\n\t\t\t\tboost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::divides, boost::proto::terminal<derivative_constant<0>>, boost::proto::_ >\n\t\t\t\t,\tconstant_rule()\n\t\t\t\t>\n\t\t\t\t, boost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::divides, boost::proto::_, boost::proto::terminal<derivative_constant<1>> >\n\t\t\t\t,\toptimize(boost::proto::_left)\n\t\t\t\t>\n\t\t\t\t, boost::proto::when\n\t\t\t\t<\n\t\t\t\t\tboost::proto::binary_expr< boost::proto::tag::divides, boost::proto::_, boost::proto::_ >\n\t\t\t\t,\tboost::proto::call<make_optimized_binary<boost::proto::tag::divides>(optimize(boost::proto::_left), optimize(boost::proto::_right))>\n\t\t\t\t>\n\t\t\t\t, boost::proto::otherwise<boost::proto::_expr>\n\t\t\t  >\n\t\t{};\n\t\t\n\t\ttemplate <int D>\n\t\tstruct case_<boost::proto::tag::function, D>\n\t\t\t: boost::proto::when\n\t\t      <\n\t\t\t\tboost::proto::_\n\t\t\t  , boost::proto::_make_function(boost::proto::_left, optimize(boost::proto::_right))\n\t\t\t  >\n\t\t{};\n\t};\n\n\ttemplate <typename T1, typename T2>\n\tstruct plus\n\t{\n\t\tusing type = decltype(std::declval<T1>() + std::declval<T2>());\n\t};\n\n\ttemplate <typename T1>\n\tstruct plus<T1, derivative_constant<0>>\n\t{\n\t\tusing type = T1;\n\t};\n\n\ttemplate <typename T2>\n\tstruct plus<derivative_constant<0>, T2>\n\t{\n\t\tusing type = T2;\n\t};\n\n}//! namespace derivative_detail;\n\nnamespace boost {\n\tnamespace proto {\n\t\ttemplate<typename Tag>\n\t\tstruct is_callable<derivative_detail::make_optimized_binary<Tag> >\n\t\t\t: mpl::true_\n\t\t{};\n} }\n\nstruct addition_rule : boost::proto::callable\n{\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename T1, typename T2>\n\tstruct result<This(T1, T2)>\n\t{\n\tprivate:\n\t\tusing t1_t = typename boost::remove_const<typename boost::remove_reference<T1>::type>::type;\n\t\tusing t2_t = typename boost::remove_const<typename boost::remove_reference<T2>::type>::type;\n\n\tpublic:\n\t\tusing raw_type = typename derivative_detail::plus<t1_t, t2_t>::type;\n\t\tusing type = typename boost::result_of<derivative_detail::optimize(raw_type)>::type;\n\t};\n\n\ttemplate <typename T1, typename T2>\n\ttypename result<addition_rule(T1, T2)>::type operator()(const T1& t1, const T2& t2) const\n\t{\n\t\treturn derivative_detail::optimize()(t1 + t2);\n\t}\n};\n\n//! Subtraction\n\nnamespace derivative_detail {\n\n\ttemplate <typename T1, typename T2>\n\tstruct minus\n\t{\n\t\tusing type = decltype(std::declval<T1>() - std::declval<T2>());\n\t};\n\n\ttemplate <typename T1>\n\tstruct minus<T1, derivative_constant<0>>\n\t{\n\t\tusing type = T1;\n\t};\n\n\ttemplate <typename T2>\n\tstruct minus<derivative_constant<0>, T2>\n\t{\n\t\tusing type = decltype(-std::declval<T2>());\n\t};\n\n}//! namespace derivative_detail;\n\nstruct subtraction_rule : boost::proto::callable\n{\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename T1, typename T2>\n\tstruct result<This(T1, T2)>\n\t{\n\tprivate:\n\t\tusing t1_t = typename boost::remove_const<typename boost::remove_reference<T1>::type>::type;\n\t\tusing t2_t = typename boost::remove_const<typename boost::remove_reference<T2>::type>::type;\n\n\tpublic:\n\t\tusing raw_type = typename derivative_detail::minus<t1_t, t2_t>::type;\n\t\tusing type = typename boost::result_of<derivative_detail::optimize(raw_type)>::type;\n\t};\n\n\ttemplate <typename T1, typename T2>\n\ttypename result<subtraction_rule(T1, T2)>::type operator()(const T1& t1, const T2& t2) const\n\t{\n\t\treturn derivative_detail::optimize()(t1 - t2);\n\t}\n};\n\n//! Multiplication\nnamespace derivative_detail {\n\n\ttemplate <typename T1, typename T2>\n\tstruct multiplies\n\t{\n\t\tusing type = decltype(std::declval<T1>() * std::declval<T2>());\n\t};\n\n\ttemplate <typename T1>\n\tstruct multiplies<T1, derivative_constant<0>>\n\t{\n\t\tusing type = derivative_constant<0>;\n\t};\n\n\ttemplate <typename T2>\n\tstruct multiplies<derivative_constant<0>, T2>\n\t{\n\t\tusing type = derivative_constant<0>;\n\t};\n\t\n\ttemplate <typename T1>\n\tstruct multiplies<T1, derivative_constant<1>>\n\t{\n\t\tusing type = T1;\n\t};\n\n\ttemplate <typename T2>\n\tstruct multiplies<derivative_constant<1>, T2>\n\t{\n\t\tusing type = T2;\n\t};\n\n\ttemplate <typename Arg1, typename dArg1, typename Arg2, typename dArg2>\n\tstruct product_rule_result_helper\n\t{\n\t\tusing termA = decltype(std::declval<dArg1>() * std::declval<Arg2>());\n\t\tusing termB = decltype(std::declval<Arg1>() * std::declval<dArg2>());\n\t\tusing otermA = typename boost::result_of<optimize(termA)>::type;\n\t\tusing otermB = typename boost::result_of<optimize(termB)>::type;\n\t\tusing type = decltype(std::declval<otermA>() + std::declval<otermB>());\n\t};\n\t\n}//! namespace derivative_detail;\n\nstruct product_rule : boost::proto::callable\n{\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename Arg1, typename dArg1, typename Arg2, typename dArg2>\n\tstruct result<This(Arg1, dArg1, Arg2, dArg2)>\n\t{\n\tprivate:\n\n\t\tusing arg1_t = typename boost::remove_const<typename boost::remove_reference<Arg1>::type>::type;\n\t\tusing darg1_t = typename boost::remove_const<typename boost::remove_reference<dArg1>::type>::type;\n\t\tusing arg2_t = typename boost::remove_const<typename boost::remove_reference<Arg2>::type>::type;\n\t\tusing darg2_t = typename boost::remove_const<typename boost::remove_reference<dArg2>::type>::type;\n\t\tusing raw_type = typename derivative_detail::product_rule_result_helper<arg1_t, darg1_t, arg2_t, darg2_t>::type;\n\n\tpublic:\n\t\tusing type = typename boost::result_of<derivative_detail::optimize(raw_type)>::type;\n\t};\n\n\ttemplate <typename Arg1, typename dArg1, typename Arg2, typename dArg2>\n\ttypename result<product_rule(Arg1, dArg1, Arg2, dArg2)>::type operator()(const Arg1& a1, const dArg1& da1, const Arg2& a2, const dArg2& da2) const\n\t{\n\t\tusing result_type = typename result<product_rule(Arg1, dArg1, Arg2, dArg2)>::type;\n\t\tderivative_detail::optimize opt;\n\t\tauto result = opt(opt(da1 * a2) + opt(a1 * da2));\n\t\treturn result;\n\t}\n};\n\n//! Division\nstruct quotient_rule : boost::proto::callable\n{\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename Arg1, typename dArg1, typename Arg2, typename dArg2>\n\tstruct result<This(Arg1, dArg1, Arg2, dArg2)>\n\t{\n\tprivate:\n\t\tusing termA_t = decltype(std::declval<dArg1>() * std::declval<Arg2>());\n\t\tusing otermA_t = typename boost::result_of<derivative_detail::optimize(termA_t)>::type;\n\t\tusing termB_t = decltype(std::declval<dArg2>() * std::declval<Arg1>());\n\t\tusing otermB_t = typename boost::result_of<derivative_detail::optimize(termB_t)>::type;\n\n\t\tusing num_t = typename boost::result_of<derivative_detail::optimize(decltype(std::declval<otermA_t>() - std::declval<otermB_t>()))>::type;\n\t\tusing denom_t = typename boost::result_of<derivative_detail::optimize(decltype(std::declval<Arg2>() * std::declval<Arg2>()))>::type;\n\t\tusing raw_type = decltype(std::declval<num_t>() / std::declval<denom_t>());\n\tpublic:\n\n\t\tusing type = typename boost::result_of<derivative_detail::optimize(raw_type)>::type;\n\t};\n\n\ttemplate <typename Arg1, typename dArg1, typename Arg2, typename dArg2>\n\ttypename result<quotient_rule(Arg1, dArg1, Arg2, dArg2)>::type operator()(const Arg1& a1, const dArg1& da1, const Arg2& a2, const dArg2& da2) const\n\t{\n\t\tusing result_type = typename result<quotient_rule(Arg1, dArg1, Arg2, dArg2)>::type;\n\t\tderivative_detail::optimize opt;\n\t\tauto result = opt( opt(opt(da1 * a2) - opt(da2 * a1)) / opt(a2 * a2) );\n\t\treturn result;\n\t}\n};\n\nnamespace derivative_detail\n{\n\ttemplate <typename Fn, typename Arg, typename dArg>\n\tstruct chain_rule_result_helper;\n\n\ttemplate <int Exp, typename Arg, typename dArg>\n\tstruct chain_rule_result_helper<pow_fun<Exp>, Arg, dArg>\n\t{\n\t\tusing type = decltype(static_cast<double>(Exp) * pow<Exp - 1>(std::declval<Arg>()) * std::declval<dArg>());\n\n\t\tstatic type apply(const Arg& arg, const dArg& darg)\n\t\t{\n\t\t\treturn static_cast<double>(Exp) * pow<Exp - 1>(arg) * darg;\n\t\t}\n\t};\n\n\ttemplate <typename Arg, typename dArg>\n\tstruct chain_rule_result_helper<pow_fun<2>, Arg, dArg>\n\t{\n\t\tusing type = decltype(2 * std::declval<Arg>() * std::declval<dArg>());\n\n\t\tstatic type apply(const Arg& arg, const dArg& darg)\n\t\t{\n\t\t\treturn 2 * arg * darg;\n\t\t}\n\t};\n\n\ttemplate <typename Arg, typename dArg>\n\tstruct chain_rule_result_helper<pow_fun<1>, Arg, dArg>\n\t{\n\t\tusing type = dArg;\n\n\t\tstatic type apply(const Arg& arg, const dArg& darg)\n\t\t{\n\t\t\treturn darg;\n\t\t}\n\t};\n\n\ttemplate <typename Arg, typename dArg>\n\tstruct chain_rule_result_helper<cos_fun, Arg, dArg>\n\t{\n\t\tusing type = decltype( -1.0 * sin( std::declval<Arg>() ) * std::declval<dArg>() );\n\n\t\tstatic type apply(const Arg& arg, const dArg& darg)\n\t\t{\n\t\t\tusing std::sin;\n\t\t\treturn -1.0 * sin(arg) * darg;\n\t\t}\n\t};\n\t\n\ttemplate <typename Arg, typename dArg>\n\tstruct chain_rule_result_helper<sin_fun, Arg, dArg>\n\t{\n\t\tusing type = decltype(cos(std::declval<Arg>()) * std::declval<dArg>());\n\n\t\tstatic type apply(const Arg& arg, const dArg& darg)\n\t\t{\n\t\t\tusing std::cos;\n\t\t\treturn cos(arg) * darg;\n\t\t}\n\t};\n\n\ttemplate <typename Arg, typename dArg>\n\tstruct chain_rule_result_helper<exp_fun, Arg, dArg>\n\t{\n\t\tusing type = decltype(exp(std::declval<Arg>()) * std::declval<dArg>());\n\n\t\tstatic type apply(const Arg& arg, const dArg& darg)\n\t\t{\n\t\t\tusing std::exp;\n\t\t\treturn exp(arg) * darg;\n\t\t}\n\t};\n\n\ttemplate <typename Arg, typename dArg>\n\tstruct chain_rule_result_helper<tan_fun, Arg, dArg>\n\t{\n\t\tusing type = decltype(sec(std::declval<Arg>()) * sec(std::declval<Arg>()) * std::declval<dArg>());\n\n\t\tstatic type apply(const Arg& arg, const dArg& darg)\n\t\t{\n\t\t\tusing std::cos;\n\t\t\tauto r = cos(arg);\n\t\t\treturn (1.0 / (r * r)) * darg;\n\t\t}\n\t};\n\n\ttemplate <typename Arg, typename dArg>\n\tstruct chain_rule_result_helper<log_fun, Arg, dArg>\n\t{\n\t\tusing type = decltype( (1.0 / std::declval<Arg>()) * std::declval<dArg>());\n\n\t\tstatic type apply(const Arg& arg, const dArg& darg)\n\t\t{\n\t\t\tusing std::log;\n\t\t\treturn (1.0 / arg) * darg;\n\t\t}\n\t};\n\t\n\ttemplate <typename Arg, typename dArg>\n\tstruct chain_rule_result_helper<sqrt_fun, Arg, dArg>\n\t{\n\t\tusing type = decltype((0.5 / sqrt(std::declval<Arg>())) * std::declval<dArg>());\n\n\t\tstatic type apply(const Arg& arg, const dArg& darg)\n\t\t{\n\t\t\tusing std::sqrt;\n\t\t\treturn (0.5 / sqrt(arg)) * darg;\n\t\t}\n\t};\n\n}//! namespace derivative_detail;\n\n//! Chain rule\nstruct chain_rule : boost::proto::callable\n{\n\ttemplate <typename Sig>\n\tstruct result;\n\n\ttemplate <typename This, typename Fn, typename Arg, typename dArg>\n\tstruct result<This(Fn, Arg, dArg)>\n\t{\n\tprivate:\n\t\tusing fn_t = typename boost::remove_const<typename boost::remove_reference<Fn>::type>::type;\n\t\tusing arg_t = typename boost::remove_const<typename boost::remove_reference<Arg>::type>::type;\n\t\tusing darg_t = typename boost::remove_const<typename boost::remove_reference<dArg>::type>::type;\n\t\tusing raw_type = typename derivative_detail::chain_rule_result_helper<fn_t, arg_t, darg_t>::type;\n\n\tpublic:\n\n\t\tusing type = typename boost::result_of<derivative_detail::optimize(raw_type)>::type;\n\t};\n\n\ttemplate <typename Fn, typename Arg, typename dArg>\n\ttypename result<chain_rule(Fn, Arg, dArg)>::type operator() (const Fn&, const Arg& arg, const dArg& darg) const\n\t{\n\t\tauto result = derivative_detail::optimize()(derivative_detail::chain_rule_result_helper<Fn, Arg, dArg>::apply(arg, darg));\n\t\t//boost::proto::display_expr(result, std::cout);\n\t\treturn result;\n\t}\n};\n\nstruct get_value\n\t: boost::proto::when<boost::proto::terminal<boost::proto::_>, boost::proto::_value>\n{};\n\nstruct derivative_grammar\n\t: boost::proto::switch_<struct cases_>\n{};\n\nstruct cases_\n{\n\ttemplate <typename Tag, int D=0>\n\tstruct case_ : boost::proto::not_<boost::proto::_> {};\n\n\ttemplate <int D>\n\tstruct case_<boost::proto::tag::terminal, D>\n\t\t: boost::proto::or_\n\t\t  <\n\t\t\tboost::proto::when\n\t\t\t<\n\t\t\t\tboost::proto::terminal<x_var>\n\t\t\t,\tderivative_variable_rule()\n\t\t\t>\n\t\t  , boost::proto::when\n\t\t\t<\n\t\t\t\tboost::proto::terminal<boost::proto::_>\n\t\t\t,\tconstant_rule()\n\t\t\t>\n\t\t  >\n\t{};\n\n\ttemplate <int D>\n\tstruct case_<boost::proto::tag::function, D>\n\t\t: boost::proto::when\n\t\t  <\n\t\t\tboost::proto::_\n\t\t  ,\tchain_rule(get_value(boost::proto::_left), boost::proto::_right, derivative_grammar(boost::proto::_right))\n\t\t  >\n\t{};\n\n\ttemplate <int D>\n\tstruct case_<boost::proto::tag::divides, D>\n\t\t: boost::proto::when\n\t\t  <\n\t\t\tboost::proto::_\n\t\t  ,\tquotient_rule(boost::proto::_left, derivative_grammar(boost::proto::_left), boost::proto::_right, derivative_grammar(boost::proto::_right))\n\t\t  >\n\t{};\n\n\ttemplate <int D>\n\tstruct case_<boost::proto::tag::multiplies, D>\n\t\t: boost::proto::when\n\t\t  <\n\t\t\tboost::proto::_\n\t\t  ,\tproduct_rule(boost::proto::_left, derivative_grammar(boost::proto::_left), boost::proto::_right, derivative_grammar(boost::proto::_right))\n\t\t  >\n\t{};\n\n\ttemplate <int D>\n\tstruct case_<boost::proto::tag::plus, D>\n\t\t: boost::proto::when\n\t\t  <\n\t\t\tboost::proto::_\n\t\t  ,\taddition_rule(derivative_grammar(boost::proto::_left), derivative_grammar(boost::proto::_right))\n\t\t  >\n\t{};\n\n\ttemplate <int D>\n\tstruct case_<boost::proto::tag::minus, D>\n\t\t: boost::proto::when\n\t\t  <\n\t\t\tboost::proto::_\n\t\t  ,\tsubtraction_rule(derivative_grammar(boost::proto::_left), derivative_grammar(boost::proto::_right))\n\t\t  >\n\t{};\n};\n", "meta": {"hexsha": "5789d13567eefa958a7b995e184b9e11a5997b4e", "size": 27771, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geometry_test/derivative.hpp", "max_stars_repo_name": "brandon-kohn/Geometrix", "max_stars_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geometry_test/derivative.hpp", "max_issues_repo_name": "brandon-kohn/Geometrix", "max_issues_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry_test/derivative.hpp", "max_forks_repo_name": "brandon-kohn/Geometrix", "max_forks_repo_head_hexsha": "e107e13b469632c7d12cb236bd4fb8b17ff928e3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9386317907, "max_line_length": 148, "alphanum_fraction": 0.6936012387, "num_tokens": 7680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.41301223722272534}}
{"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__OPTIM_HPP_\n#define SMOOTH__OPTIM_HPP_\n\n/**\n * @file\n * @brief Non-linear least squares optimization on Manifolds.\n */\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#include <iostream>\n#include <numeric>\n\n#include \"concepts.hpp\"\n#include \"diff.hpp\"\n#include \"internal/lmpar.hpp\"\n#include \"internal/lmpar_sparse.hpp\"\n#include \"internal/utils.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief Optimization options.\n */\nstruct MinimizeOptions\n{\n  /// relative parameter tolerance for convergence\n  double ptol{1e-6};\n  /// relative function tolerance for convergence\n  double ftol{1e-6};\n  /// maximum number of iterations\n  std::size_t max_iter{1000};\n  /// solver verbosity level\n  int verbosity{0};\n};\n\n/**\n * @brief Find a minimum of the non-linear least-squares problem\n *\n * \\f[\n *  \\min_{x} \\sum_i \\| f(x)_i \\|^2\n * \\f]\n *\n * @tparam Diff differentiation method to use in solver (see diff::Type in diff.hpp)\n * @param f residuals to minimize\n * @param x reference tuple of arguments to f\n * @param opts solver options\n *\n * All arguments in x as well as the return type \\f$f(x)\\f$ must satisfy\n * the Manifold concept.\n */\ntemplate<diff::Type Diff, typename _F, typename _Wrt>\nvoid minimize(_F && f, _Wrt && x, const MinimizeOptions & opts = MinimizeOptions{})\n{\n  // evaluate residuals and jacobian at initial point\n  auto [r, J] = diff::dr<Diff>(f, x);\n\n  // extract some properties from jacobian\n  static constexpr bool is_sparse =\n    std::is_base_of_v<Eigen::SparseMatrixBase<decltype(J)>, decltype(J)>;\n  static constexpr int Nx = decltype(J)::ColsAtCompileTime;\n  const int nx            = J.cols();\n\n  // scaling parameters\n  Eigen::Matrix<double, Nx, 1> d(nx);\n  if constexpr (is_sparse) {\n    d = (Eigen::Matrix<double, 1, -1>::Ones(J.rows()) * J.cwiseProduct(J)).cwiseSqrt().transpose();\n  } else {\n    d = J.colwise().stableNorm().transpose();\n  }\n\n  // ensure scaling parameters are non-zero\n  for (auto i = 0u; i != d.size(); ++i) {\n    if (d[i] == 0) { d[i] = 1; }\n  }\n\n  double r_norm = r.stableNorm();\n  double Delta = 100. * d.stableNorm();  // TODO for Rn arguments we should multiply with norm(x)\n\n  for (auto i = 0u; i != opts.max_iter; ++i) {\n    // calculate step a via LM parameter algorithm\n    Eigen::Matrix<double, Nx, 1> a(nx);\n    double lambda;\n    if constexpr (is_sparse) {\n      std::tie(lambda, a) = detail::lmpar_sparse(J, d, r, Delta);\n    } else {\n      std::tie(lambda, a) = detail::lmpar(J, d, r, Delta);\n    }\n\n    // evaluate function and jacobian at x + a\n    auto x_plus_a               = utils::tuple_plus(x, a);\n    const auto [r_cand, J_cand] = diff::dr<Diff>(f, x_plus_a);\n\n    const double r_cand_norm = r_cand.stableNorm();\n    const double Da_norm     = d.cwiseProduct(a).stableNorm();\n\n    // calculate actual to predicted reduction\n    const double act_red  = 1. - Eigen::numext::abs2(r_cand_norm / r_norm);\n    const double fra2     = Eigen::numext::abs2((J * a).stableNorm() / r_norm);\n    const double fra3     = Eigen::numext::abs2(std::sqrt(lambda) * Da_norm / r_norm);\n    const double pred_red = fra2 + 2. * fra3;\n    const double rho      = act_red / pred_red;\n\n    // update trust region following Moré (1978)\n    if (rho < 0.25) {\n      double mu;\n      if (r_cand_norm <= r_norm) {\n        mu = 0.5;\n      } else if (r_cand_norm <= 10 * r_norm) {\n        const double gamma = -fra2 - fra3;\n        mu                 = std::clamp(gamma / (2. * gamma + act_red), 0.1, 0.5);\n      } else {\n        mu = 0.1;\n      }\n      Delta *= mu;\n    } else if ((lambda == 0 && rho < 0.75) || rho > 0.75) {\n      Delta = 2 * Da_norm;\n    }\n\n    //// TAKE STEP IF SUCCESSFUL ////\n\n    if (rho > 1e-4) {\n      x      = x_plus_a;\n      r      = r_cand;\n      J      = J_cand;\n      r_norm = r_cand_norm;\n\n      // update scaling\n      if constexpr (is_sparse) {\n        d = d.cwiseMax((Eigen::Matrix<double, 1, -1>::Ones(J.rows()) * J.cwiseProduct(J))\n                         .cwiseSqrt()\n                         .transpose());\n      } else {\n        d = d.cwiseMax(J.colwise().stableNorm().transpose());\n      }\n    }\n\n    //// PRINT STATUS ////\n    \n    // TODO Pretty-print solver steps\n    if (opts.verbosity > 0) { std::cout << \"Step \" << i << \": \" << r.sum() << std::endl; }\n\n    //// CHECK FOR CONVERGENCE ////\n\n    // function tolerance\n    if (std::abs(act_red) < opts.ftol && pred_red < opts.ftol && rho <= 2.) { break; }\n\n    // parameter tolerance\n    // TODO a.size() should be norm(x) for non-angle states\n    if (Da_norm < opts.ptol * a.size()) { break; }\n  }\n}\n\n/**\n * @brief Find a minimum of the non-linear least-squares problem\n *\n * \\f[\n *  \\min_{x} \\sum_i \\| f(x)_i \\|^2\n * \\f]\n *\n * @param f residuals to minimize\n * @param x reference tuple of arguments to f\n * @param opts solver options\n *\n * All arguments in x as well as the return type \\f$f(x)\\f$ must satisfy\n * the Manifold concept.\n */\ntemplate<typename _F, typename _Wrt>\nvoid minimize(_F && f, _Wrt && x, const MinimizeOptions & opts = MinimizeOptions{})\n{\n  minimize<diff::Type::DEFAULT>(std::forward<_F>(f), std::forward<_Wrt>(x), opts);\n}\n\n}  // namespace smooth\n\n#endif  // SMOOTH__OPTIM_HPP_\n", "meta": {"hexsha": "1505807a9454aac71a1432e7e7218e009e2abc9d", "size": 6402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/optim.hpp", "max_stars_repo_name": "NamDinhRobotics/smooth", "max_stars_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T10:28:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T10:28:18.000Z", "max_issues_repo_path": "include/smooth/optim.hpp", "max_issues_repo_name": "NamDinhRobotics/smooth", "max_issues_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smooth/optim.hpp", "max_forks_repo_name": "NamDinhRobotics/smooth", "max_forks_repo_head_hexsha": "137008de5d68af459db2c7802e05cdabd166c424", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5369458128, "max_line_length": 99, "alphanum_fraction": 0.6366760387, "num_tokens": 1768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370111, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.41295563440679484}}
{"text": "#pragma once\n\n#include <boost/intrusive/list.hpp>\n#include <boost/intrusive/slist.hpp>\n#include <boost/intrusive/options.hpp>\n#include \"litiv/3rdparty/sospd/submodular-functions.hpp\"\n\nnamespace sospd {\n\n    enum class UBfn {\n        chen,\n        cvpr14,\n    };\n\n    enum class FlowAlgorithm {\n        bidirectional,\n        source,\n        parametric\n    };\n\n    struct SubmodularIBFSParams {\n        SubmodularIBFSParams() = default;\n        SubmodularIBFSParams(sospd::FlowAlgorithm _alg) : alg(_alg) {}\n        sospd::FlowAlgorithm alg = sospd::FlowAlgorithm::bidirectional;\n        sospd::UBfn ub = sospd::UBfn::cvpr14;\n        std::vector<bool> fixedVars;\n    };\n\n    template<typename ValueType, typename IndexType>\n    class SubmodularIBFS;\n\n    template<typename ValueType, typename IndexType>\n    class FlowSolver {\n    public:\n        FlowSolver() = default;\n        virtual ~FlowSolver() = default;\n        virtual void Solve(SubmodularIBFS<ValueType,IndexType>* energy) = 0;\n        FlowSolver(const FlowSolver&) = delete;\n        FlowSolver(FlowSolver&&) = delete;\n        FlowSolver& operator=(const FlowSolver&) = delete;\n        FlowSolver& operator=(FlowSolver&&) = delete;\n    };\n\n    template<typename ValueType, typename IndexType>\n    std::unique_ptr<FlowSolver<ValueType,IndexType>> GetSolver(const SubmodularIBFSParams& params);\n\n    /** Graph structure and algorithm for sum-of-submodular IBFS\n     */\n    template<typename ValueType, typename IndexType>\n    class SoSGraph {\n        static_assert(std::is_arithmetic<ValueType>::value,\"value type must be arithmetic\");\n        static_assert(std::is_integral<IndexType>::value,\"index type must be integral\");\n        public:\n            typedef ValueType REAL;\n            typedef IndexType NodeId;\n            typedef IndexType CliqueId;\n            typedef std::vector<CliqueId> NeighborList;\n            enum class NodeState : char {\n                S, T, S_orphan, T_orphan, N\n            };\n            class IBFSEnergyTableClique;\n            typedef std::tuple<sospd::UBfn,std::string,sospd::UpperBoundFunction<ValueType,IndexType>> UBParam;\n            static const std::vector<UBParam> ubParamList;\n\n            SoSGraph()\n                : m_num_nodes(0),\n                s(NodeId(-1)),\n                t(NodeId(-1)),\n                m_num_cliques(0)\n            { }\n\n            /** Add n new nodes to the base set V\n             *\n             * \\return Index of first created node\n             */\n            NodeId AddNode(IndexType n = 1);\n\n            /** Add weights to s-i and i-t edges, respectively\n             */\n            void AddTerminalWeights(NodeId n, REAL sCap, REAL tCap);\n\n            /** Zero the capacities on the s-i and i-t edges\n             */\n            void ClearTerminals();\n\n            // Add Clique defined by nodes and energy table given\n            IBFSEnergyTableClique& AddClique(const std::vector<NodeId>& nodes, const std::vector<REAL>& energyTable);\n\n            /* Clique: abstract base class for user-defined clique functions\n             *\n             * Clique stores the list of nodes associated with a clique.\n             * Actual functionality is provided by the user writing a derived\n             * class with Clique as the base, and which implements the\n             * ComputeEnergy and ExchangeCapacity functions\n             */\n            class Clique {\n                public:\n                typedef std::vector<NodeId> NodeVec;\n                Clique() : m_nodes(), m_alpha_Ci() { }\n                Clique(const NodeVec& nodes)\n                    : m_nodes(nodes),\n                    m_alpha_Ci(nodes.size(), 0)\n                { }\n                ~Clique() = default;\n\n                // Returns the energy of the given labeling for this clique function\n                virtual REAL ComputeEnergy(const std::vector<int>& labels) const = 0;\n\n                const NodeVec& Nodes() const { return m_nodes; }\n                IndexType Size() const { return IndexType(m_nodes.size()); }\n                std::vector<REAL>& AlphaCi() { return m_alpha_Ci; }\n                const std::vector<REAL>& AlphaCi() const { return m_alpha_Ci; }\n                IndexType GetIndex(NodeId i) const {\n                    return IndexType(std::find(this->m_nodes.begin(), this->m_nodes.end(), i) - this->m_nodes.begin());\n                }\n\n                protected:\n                NodeVec m_nodes; // The list of nodes in the clique\n                std::vector<REAL> m_alpha_Ci; // The reparameterization variables for this clique\n\n            };\n            /*\n             * IBFSEnergyTableClique: stores energy as a list of 2^k values for each subset\n             */\n            class IBFSEnergyTableClique : public Clique {\n                public:\n                    typedef uint32_t Assignment;\n\n                    IBFSEnergyTableClique() : Clique(), m_energy(), m_alpha_energy(), m_min_tight_set() { }\n                    IBFSEnergyTableClique(const std::vector<NodeId>& nodes, const std::vector<REAL>& energy)\n                        : Clique(nodes),\n                        m_energy(energy),\n                        m_alpha_energy(energy),\n                        m_min_tight_set(nodes.size(), (1u << nodes.size()) - 1)\n                    {\n                        ASSERT(nodes.size() <= 31);\n                    }\n\n                    virtual REAL ComputeEnergy(const std::vector<int>& labels) const;\n                    REAL ComputeAlphaEnergy(const std::vector<int>& labels) const;\n                    REAL ExchangeCapacity(IndexType u_idx, IndexType v_idx) const;\n                    bool NonzeroCapacity(IndexType u_idx, IndexType v_idx) const;\n                    void NormalizeEnergy(std::vector<REAL>& psi, REAL& constantTerm);\n\n                    void Push(IndexType u_idx, IndexType v_idx, REAL delta);\n                    void ComputeMinTightSets();\n                    std::vector<REAL>& EnergyTable() { return m_energy; }\n                    const std::vector<REAL>& EnergyTable() const { return m_energy; }\n                    std::vector<REAL>& AlphaEnergy() { return m_alpha_energy; }\n                    const std::vector<REAL>& AlphaEnergy() const { return m_alpha_energy; }\n\n                    void ResetAlpha();\n\n                protected:\n                    std::vector<REAL> m_energy;\n                    std::vector<REAL> m_alpha_energy;\n                    std::vector<Assignment> m_min_tight_set;\n\n            };\n            struct ArcIterator {\n                NodeId source;\n                typename NeighborList::iterator cIter;\n                IndexType cliqueIdx;\n                IndexType cliqueSize;\n                SoSGraph* graph;\n\n                bool operator!=(const ArcIterator& a) {\n                    return (cIter != a.cIter) || (cliqueIdx != a.cliqueIdx);\n                }\n                bool operator==(const ArcIterator& a) {\n                    return !(*this != a);\n                }\n                bool operator<(const ArcIterator& a) {\n                    ASSERT(source == a.source);\n                    return (cIter == a.cIter) ? (source < a.source) : (cIter < a.cIter);\n                }\n\n                ArcIterator& operator++() {\n                    //ASSERT(*cIter < static_cast<int>(graph->m_cliques.size()));\n                    cliqueIdx++;\n                    if (cliqueIdx == cliqueSize) {\n                        cliqueIdx = IndexType(0);\n                        cIter++;\n                        if (cIter != graph->m_neighbors[source].end())\n                            cliqueSize = graph->m_cliques[*cIter].Size();\n                        else\n                            cliqueSize = IndexType(0);\n                    }\n                    //ASSERT(cIter == graph->m_neighbors[source].end() || *cIter < static_cast<int>(graph->m_cliques.size()));\n                    //ASSERT(cIter == graph->m_neighbors[source].end() || cliqueIdx < static_cast<int>(graph->m_cliques[*cIter].Nodes().size()));\n                    return *this;\n                }\n                NodeId Source() const {\n                    return source;\n                }\n                NodeId Target() const {\n                    //ASSERT(*cIter < static_cast<int>(graph->m_cliques.size()));\n                    //ASSERT(cliqueIdx < static_cast<int>(graph->m_cliques[*cIter].Nodes().size()));\n                    return graph->m_cliques[*cIter].Nodes()[cliqueIdx];\n                }\n                IndexType SourceIdx() const { return graph->m_cliques[*cIter].GetIndex(source); }\n                IndexType TargetIdx() const { return cliqueIdx; }\n                CliqueId cliqueId() const { return *cIter; }\n                ArcIterator Reverse() const {\n                    auto newSource = Target();\n                    auto newCIter = std::find(graph->m_neighbors[newSource].begin(), graph->m_neighbors[newSource].end(), *cIter);\n                    auto newCliqueIdx = graph->GetCliques()[*newCIter].GetIndex(source);\n                    return {newSource, newCIter, newCliqueIdx, graph->m_cliques[*newCIter].Size(), graph};\n                }\n            };\n\n            typedef boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> ListHook;\n            typedef boost::intrusive::slist_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> OrphanListHook;\n            struct Node : public ListHook, OrphanListHook {\n                NodeId id;\n                NodeState state;\n                IndexType dis;\n                ArcIterator parent_arc;\n                NodeId parent;\n                NeighborList cliques;\n                explicit Node(NodeId _id)\n                    : id(_id)\n                    , state(NodeState::N)\n                    , dis(std::numeric_limits<IndexType>::max())\n                    , parent_arc()\n                    , parent()\n                    , cliques() { }\n            };\n\n            typedef boost::intrusive::list<Node> NodeQueue;\n            typedef boost::intrusive::slist<Node, boost::intrusive::base_hook<OrphanListHook>, boost::intrusive::cache_last<true>> OrphanList;\n\n            ArcIterator ArcsBegin(NodeId i) {\n                auto cIter = m_neighbors[i].begin();\n                if (cIter == m_neighbors[i].end())\n                    return ArcsEnd(i);\n                return {i, cIter, 0, m_cliques[*cIter].Size(), this};\n            }\n            ArcIterator ArcsEnd(NodeId i) {\n                auto& neighborList = m_neighbors[i];\n                return {i, neighborList.end(), 0, 0, this};\n            }\n\n            typedef std::vector<IBFSEnergyTableClique> CliqueVec;\n\n            NodeId NumNodes() const { return m_num_nodes; }\n            NodeId GetS() const { return s; }\n            NodeId GetT() const { return t; }\n            Node& node(NodeId i) { return m_nodes[i]; }\n            const Node& node(NodeId i) const { return m_nodes[i]; }\n            IBFSEnergyTableClique& clique(CliqueId c) { return m_cliques[c]; }\n            const IBFSEnergyTableClique& clique(CliqueId c) const { return m_cliques[c]; }\n            const std::vector<REAL>& GetC_si() const { return m_c_si; }\n            const std::vector<REAL>& GetC_it() const { return m_c_it; }\n            const std::vector<REAL>& GetPhi_si() const { return m_phi_si; }\n            const std::vector<REAL>& GetPhi_it() const { return m_phi_it; }\n            CliqueId GetNumCliques() const { return m_num_cliques; }\n            const CliqueVec& GetCliques() const { return m_cliques; }\n            CliqueVec& GetCliques() { return m_cliques; }\n            const std::vector<NeighborList>& GetNeighbors() const { return m_neighbors; }\n            std::vector<Node>& GetNodes() { return m_nodes; }\n            const std::vector<Node>& GetNodes() const { return m_nodes; }\n\n            REAL ResCap(const ArcIterator& arc, bool forwardArc);\n            bool NonzeroCap(const ArcIterator& arc, bool forwardArc);\n            void Push(ArcIterator& arc, bool forwardArc, REAL delta);\n\n            void ResetFlow();\n            typedef void(*BoundFn)(int, const std::vector<REAL>&, std::vector<REAL>&);\n            struct NormStats {\n                double L1 = 0;\n                double L2 = 0;\n                double LInfty = 0;\n            };\n            template<BoundFn fn>\n            void UpperBoundCliques(const std::vector<bool>& fixedVars, NormStats* stats);\n            void UpperBoundCliques(sospd::UBfn ub, NormStats* stats = 0);\n            void UpperBoundCliques(sospd::UBfn ub, const std::vector<bool>& fixedVars, const std::vector<int>& labels, NormStats* stats = 0);\n\n            NodeId m_num_nodes;\n            NodeId s,t;\n            std::vector<REAL> m_c_si;\n            std::vector<REAL> m_c_it;\n            std::vector<REAL> m_phi_si;\n            std::vector<REAL> m_phi_it;\n\n            CliqueId m_num_cliques;\n            CliqueVec m_cliques;\n            std::vector<NeighborList> m_neighbors;\n\n        protected:\n            std::vector<Node> m_nodes;\n    };\n\n} // namespace sospd\n\ntemplate<typename V, typename I>\nconst std::vector<typename sospd::SoSGraph<V,I>::UBParam> sospd::SoSGraph<V,I>::ubParamList = {\n    UBParam{ sospd::UBfn::chen, \"chen\", sospd::ChenUpperBound<REAL> },\n    UBParam{ sospd::UBfn::cvpr14, \"cvpr14\", sospd::UpperBoundCVPR14<REAL> },\n};\n\ntemplate<typename V, typename I>\ninline typename sospd::SoSGraph<V,I>::NodeId sospd::SoSGraph<V,I>::AddNode(I n) {\n    ASSERT(n >= I(1));\n    ASSERT(s == I(-1));\n    NodeId first_node = m_num_nodes;\n    for(I i = 0; i < n; ++i) {\n        m_nodes.push_back(Node(m_num_nodes));\n        m_c_si.push_back(0);\n        m_c_it.push_back(0);\n        m_phi_si.push_back(0);\n        m_phi_it.push_back(0);\n        m_neighbors.push_back(NeighborList());\n        m_num_nodes++;\n    }\n    return first_node;\n}\n\ntemplate<typename V, typename I>\ninline void sospd::SoSGraph<V,I>::AddTerminalWeights(NodeId n, REAL sCap, REAL tCap) {\n    m_c_si[n] += sCap;\n    m_c_it[n] += tCap;\n}\n\ntemplate<typename V, typename I>\ninline void sospd::SoSGraph<V,I>::ClearTerminals() {\n    for (NodeId i = 0; i < m_num_nodes; ++i) {\n        m_c_si[i] = m_c_it[i] = 0;\n        m_phi_si[i] = m_phi_it[i] = 0;\n    }\n}\n\ntemplate<typename V, typename I>\ninline typename sospd::SoSGraph<V,I>::IBFSEnergyTableClique& sospd::SoSGraph<V,I>::AddClique(const std::vector<NodeId>& nodes, const std::vector<REAL>& energyTable) {\n    ASSERT(s == I(-1));\n    m_cliques.emplace_back(nodes, energyTable);\n    for (NodeId i : nodes) {\n        ASSERT(0 <= i && i < m_num_nodes);\n        m_neighbors[i].push_back(m_num_cliques);\n    }\n    return m_cliques[m_num_cliques++];\n}\n\ntemplate<typename V, typename I>\ninline void sospd::SoSGraph<V,I>::ResetFlow() {\n    // Initialize source, sink (only do once)\n    if (s == I(-1)) {\n        s = m_num_nodes; t = m_num_nodes + 1;\n        m_nodes.push_back(Node(s));\n        m_nodes.push_back(Node(t));\n    }\n    // reset distance, state and parent\n    for (I i = 0; i < m_num_nodes + 2; ++i) {\n        Node& node = m_nodes[i];\n        node.dis = std::numeric_limits<I>::max();\n        node.state = NodeState::N;\n        node.parent = i;\n        m_phi_si[i] = m_phi_it[i] = 0;\n    }\n\n    // Reset Clique parameters\n    for (I cid = 0; cid < m_num_cliques; ++cid) {\n        auto& c = m_cliques[cid];\n        c.ResetAlpha();\n        c.ComputeMinTightSets();\n    }\n\n}\n\ntemplate<typename V, typename I>\ninline typename sospd::SoSGraph<V,I>::REAL sospd::SoSGraph<V,I>::ResCap(const ArcIterator& arc, bool forwardArc) {\n    ASSERT(arc.cliqueId() >= 0 && arc.cliqueId() < I(m_cliques.size()));\n    if (forwardArc)\n        return m_cliques[arc.cliqueId()].ExchangeCapacity(arc.SourceIdx(), arc.TargetIdx());\n    else\n        return m_cliques[arc.cliqueId()].ExchangeCapacity(arc.TargetIdx(), arc.SourceIdx());\n}\n\ntemplate<typename V, typename I>\ninline bool sospd::SoSGraph<V,I>::NonzeroCap(const ArcIterator& arc, bool forwardArc) {\n    if (forwardArc)\n        return m_cliques[arc.cliqueId()].NonzeroCapacity(arc.SourceIdx(), arc.TargetIdx());\n    else\n        return m_cliques[arc.cliqueId()].NonzeroCapacity(arc.TargetIdx(), arc.SourceIdx());\n}\n\ntemplate<typename V, typename I>\ninline void sospd::SoSGraph<V,I>::IBFSEnergyTableClique::NormalizeEnergy(std::vector<REAL>& psi, REAL& constantTerm) {\n    ASSERT(false /* Should not be calling this function*/);\n    const I n = I(this->m_nodes.size());\n    ASSERT(sospd::CheckSubmodular((int)n,m_energy));\n    const Assignment num_assignments = 1u << n;\n    REAL allOnes = m_energy[num_assignments - 1];\n    constantTerm += allOnes;\n    psi.resize(n);\n    Assignment assgn = num_assignments - 1; // The all 1 assignment\n    for (I i = 0; i < n; ++i) {\n        Assignment next_assgn = assgn ^ (1u << i);\n        psi[i] = (m_energy[assgn] - m_energy[next_assgn]);\n        assgn = next_assgn;\n    }\n\n    for (Assignment a = 0; a < num_assignments; ++a) {\n        m_energy[a] -= allOnes;\n        for (I i = 0; i < n; ++i) {\n            if (!(a & (1u << i))) m_energy[a] += psi[i];\n        }\n        ASSERT(m_energy[a] >= V(0));\n        m_alpha_energy[a] = m_energy[a];\n    }\n    ComputeMinTightSets();\n    ASSERT(sospd::CheckSubmodular((int)n,m_energy));\n}\n\ntemplate<typename V, typename I>\ninline typename sospd::SoSGraph<V,I>::REAL sospd::SoSGraph<V,I>::IBFSEnergyTableClique::ComputeEnergy(const std::vector<int>& labels) const {\n    Assignment assgn = 0;\n    for (I i = 0; i < I(this->m_nodes.size()); ++i) {\n        NodeId n = this->m_nodes[i];\n        if (labels[n] == 1) {\n            assgn |= 1u << i;\n        }\n    }\n    return m_energy[assgn];\n}\n\ntemplate<typename V, typename I>\ninline typename sospd::SoSGraph<V,I>::REAL sospd::SoSGraph<V,I>::IBFSEnergyTableClique::ComputeAlphaEnergy(const std::vector<int>& labels) const {\n    Assignment assgn = 0;\n    for (I i = 0; i < I(this->m_nodes.size()); ++i) {\n        NodeId n = this->m_nodes[i];\n        if (labels[n] == 1) {\n            assgn |= 1u << i;\n        }\n    }\n    return m_alpha_energy[assgn];\n}\n\ntemplate<typename V, typename I>\ninline typename sospd::SoSGraph<V,I>::REAL sospd::SoSGraph<V,I>::IBFSEnergyTableClique::ExchangeCapacity(I u_idx, I v_idx) const {\n    const I n = I(this->m_nodes.size());\n    ASSERT(u_idx < n);\n    ASSERT(v_idx < n);\n    REAL min_energy = std::numeric_limits<REAL>::max();\n    Assignment num_assgns = 1u << n;\n    const Assignment bound = num_assgns-1;\n    const Assignment u_mask = 1u << u_idx;\n    const Assignment v_mask = 1u << v_idx;\n    const Assignment uv_mask = u_mask | v_mask;\n    const Assignment subset_mask = bound & ~uv_mask;\n    // Terrible bit-hacks to optimize the living hell out of this function\n    // Iterate over all assignments without u_idx or v_idx set\n    Assignment assgn = subset_mask;\n    do {\n        Assignment u_sep = assgn | u_mask;\n        REAL energy = m_alpha_energy[u_sep];\n        if (energy < min_energy) min_energy = energy;\n        assgn = ((assgn - 1) & subset_mask);\n    } while (assgn != subset_mask);\n\n    return min_energy;\n}\n\ntemplate<typename V, typename I>\ninline void sospd::SoSGraph<V,I>::IBFSEnergyTableClique::Push(I u_idx, I v_idx, REAL delta) {\n    ASSERT(u_idx < this->m_nodes.size());\n    ASSERT(v_idx < this->m_nodes.size());\n    Clique::m_alpha_Ci[u_idx] += delta;\n    Clique::m_alpha_Ci[v_idx] -= delta;\n    const I n = I(this->m_nodes.size());\n    Assignment num_assgns = 1u << n;\n    const Assignment bound = num_assgns-1;\n    const Assignment u_mask = 1u << u_idx;\n    const Assignment v_mask = 1u << v_idx;\n    const Assignment uv_mask = u_mask | v_mask;\n    const Assignment subset_mask = bound & ~uv_mask;\n    // Terrible bit-hacks to optimize the living hell out of this function\n    // Iterate over all assignments without u_idx or v_idx set\n    Assignment assgn = subset_mask;\n    do {\n        Assignment u_sep = assgn | u_mask;\n        Assignment v_sep = assgn | v_mask;\n        m_alpha_energy[u_sep] -= delta;\n        m_alpha_energy[v_sep] += delta;\n        assgn = ((assgn - 1) & subset_mask);\n    } while (assgn != subset_mask);\n\n    ComputeMinTightSets();\n}\n\ntemplate<typename V, typename I>\ninline void sospd::SoSGraph<V,I>::IBFSEnergyTableClique::ComputeMinTightSets() {\n    I n = I(this->m_nodes.size());\n    Assignment num_assgns = 1u << n;\n    const Assignment bound = num_assgns-1;\n    for (auto& a : m_min_tight_set)\n        a = bound;\n    for (Assignment assgn = bound-1; assgn >= 1; --assgn) {\n        if (m_alpha_energy[assgn] == 0) {\n            for (I i = 0; i < n; ++i) {\n                //ASSERT(m_alpha_energy[m_min_tight_set[i] & assgn] == 0);\n                //ASSERT(m_alpha_energy[m_min_tight_set[i] | assgn] == 0);\n                if ((assgn & (1u << i)) != 0)\n                    m_min_tight_set[i] = assgn;\n            }\n        }\n    }\n}\n\ntemplate<typename V, typename I>\ninline bool sospd::SoSGraph<V,I>::IBFSEnergyTableClique::NonzeroCapacity(I u_idx, I v_idx) const {\n    Assignment min_set = m_min_tight_set[u_idx];\n    return (min_set & (1u << v_idx)) != 0;\n}\n\ntemplate<typename V, typename I>\ninline void sospd::SoSGraph<V,I>::IBFSEnergyTableClique::ResetAlpha() {\n    for (auto& a : this->m_alpha_Ci) {\n        a = 0;\n    }\n    const I n = I(this->m_nodes.size());\n    const Assignment num_assignments = 1u << n;\n    for (Assignment a = 0; a < num_assignments; ++a) {\n        m_alpha_energy[a] = m_energy[a];\n    }\n}\n\ntemplate<typename V, typename I>\ntemplate<typename sospd::SoSGraph<V,I>::BoundFn UB>\ninline void sospd::SoSGraph<V,I>::UpperBoundCliques(const std::vector<bool>& fixedVars, NormStats* stats) {\n    std::vector<REAL> psi;\n    //int nCliques = m_cliques.size();\n    I cliquesDone = 0;\n    /*\n     *std::cout << \"Upper Bounding Cliques: \";\n     *std::cout.flush();\n     */\n    for (auto& c : m_cliques) {\n        /*\n         *if (cliquesDone % (nCliques/10) == 0) {\n         *    std::cout << \".\";\n         *    std::cout.flush();\n         *}\n         */\n        cliquesDone++;\n        auto& newEnergy = c.AlphaEnergy();\n        I k = I(c.Size());\n        psi.resize(k);\n        // Compute upper bound g of clique energy\n        UB(k, c.EnergyTable(), newEnergy);\n\n        if (!fixedVars.empty()) {\n            I fixedSet = 0;\n            for (I i = 0; i < k; ++i)\n                fixedSet |= (fixedVars[c.Nodes()[i]] << i);\n            sospd::ZeroMarginalSet(k, newEnergy, fixedSet);\n        }\n\n        if (stats) {\n            stats->L1 += sospd::DiffL1(c.EnergyTable(), newEnergy);\n            stats->L2 += sospd::DiffL2(c.EnergyTable(), newEnergy);\n            stats->LInfty += sospd::DiffLInfty(c.EnergyTable(), newEnergy);\n        }\n        // Modify g, find psi so that g'(S) = g(S) + psi(S) >= 0\n        sospd::Normalize(k, newEnergy, psi);\n        /*\n         *AddLinear(k, c.EnergyTable(), psi);\n         */\n\n        auto& alpha_Ci = c.AlphaCi();\n        for (I i = 0; i < k; ++i) {\n            alpha_Ci[i] = -psi[i];\n            m_phi_it[c.Nodes()[i]] += psi[i];\n        }\n        c.ComputeMinTightSets();\n    }\n    /*\n     *std::cout << \"\\n\";\n     *std::cout << \"L1: \" << diffL1 << \"\\tL2: \" << diffL2 << \"\\tLInfty: \" << diffLInfty << \"\\n\";\n     */\n}\n\ntemplate<typename V, typename I>\ninline void sospd::SoSGraph<V,I>::UpperBoundCliques(sospd::UBfn ub, NormStats* stats) {\n    UpperBoundCliques(ub, std::vector<bool>{}, std::vector<int>{}, stats);\n}\n\ntemplate<typename V, typename I>\ninline void sospd::SoSGraph<V,I>::UpperBoundCliques(sospd::UBfn ub, const std::vector<bool>& fixedVars, const std::vector<int>& /*labels*/, NormStats* stats) {\n    switch(ub) {\n        case sospd::UBfn::chen:\n            UpperBoundCliques<sospd::ChenUpperBound>(fixedVars, stats);\n            break;\n        case sospd::UBfn::cvpr14:\n            UpperBoundCliques<sospd::UpperBoundCVPR14>(fixedVars, stats);\n            break;\n    }\n}\n", "meta": {"hexsha": "595014ca294c280f8de6082310b490a91975ec1b", "size": 23820, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdparty/sospd/include/litiv/3rdparty/sospd/sos-graph.hpp", "max_stars_repo_name": "jpjodoin/litiv", "max_stars_repo_head_hexsha": "435556bea20d60816aff492f50587b1a2d748b21", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 97.0, "max_stars_repo_stars_event_min_datetime": "2015-10-16T04:32:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:04:02.000Z", "max_issues_repo_path": "3rdparty/sospd/include/litiv/3rdparty/sospd/sos-graph.hpp", "max_issues_repo_name": "jpjodoin/litiv", "max_issues_repo_head_hexsha": "435556bea20d60816aff492f50587b1a2d748b21", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2016-07-01T16:37:02.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-10T06:09:39.000Z", "max_forks_repo_path": "3rdparty/sospd/include/litiv/3rdparty/sospd/sos-graph.hpp", "max_forks_repo_name": "jpjodoin/litiv", "max_forks_repo_head_hexsha": "435556bea20d60816aff492f50587b1a2d748b21", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-11-17T05:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T09:30:28.000Z", "avg_line_length": 39.7, "max_line_length": 166, "alphanum_fraction": 0.570193115, "num_tokens": 6058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4129556271649658}}
{"text": "// ---------------------------------------------------------------------\n//\n// Copyright (c) 2016 - 2021 by the IBAMR developers\n// All rights reserved.\n//\n// This file is part of IBAMR.\n//\n// IBAMR is free software and is distributed under the 3-clause BSD\n// license. The full text of the license can be found in the file\n// COPYRIGHT at the top level directory of IBAMR.\n//\n// ---------------------------------------------------------------------\n\n// Taylor Couette flow (2D)\n// See Sec. 4.2 of \"An immersed interface method for discrete surfaces\"\n//  by Ebrahim M. Kolahdouz et al., Journal of Computational Physics 400 (2020) 108854\n// This code was run with a tight solver/preconditioner tolerance\n// through the command line flag: -stokes_ksp_rtol 1.0e-10 -ksp_rtol 1.0e-10\n\n// This code was tested against the commit 57fb379454ea3f8f50c476f10226cb6b520a11a0\n// which is currently on branch iim-1 at https://github.com/drwells/IBAMR\n\n// Headers for basic SAMRAI objects\n#include <BergerRigoutsos.h>\n#include <CartesianGridGeometry.h>\n#include <LoadBalancer.h>\n#include <StandardTagAndInitialize.h>\n\n// Headers for basic libMesh objects\n#include <libmesh/boundary_info.h>\n#include <libmesh/boundary_mesh.h>\n#include <libmesh/dof_map.h>\n#include <libmesh/equation_systems.h>\n#include <libmesh/exodusII_io.h>\n#include <libmesh/mesh.h>\n#include <libmesh/mesh_generation.h>\n#include <libmesh/mesh_triangle_interface.h>\n\n// Headers for application-specific algorithm/data structure objects\n#include <ibamr/IBExplicitHierarchyIntegrator.h>\n#include <ibamr/IIMethod.h>\n#include <ibamr/INSCollocatedHierarchyIntegrator.h>\n#include <ibamr/INSStaggeredHierarchyIntegrator.h>\n\n#include <ibtk/AppInitializer.h>\n#include <ibtk/IndexUtilities.h>\n#include <ibtk/LEInteractor.h>\n#include <ibtk/ibtk_utilities.h>\n#include <ibtk/libmesh_utilities.h>\n#include <ibtk/muParserCartGridFunction.h>\n#include <ibtk/muParserRobinBcCoefs.h>\n\n#include <boost/multi_array.hpp>\n\n// Set up application namespace declarations\n#include <ibamr/app_namespaces.h>\n\n// Elasticity model data.\nnamespace ModelData\n{\n// Tether (penalty) force functions.\n\nstatic double kappa_s = 1.0e6;\nstatic double fac = 0.0;\nstatic double eta_s = 0.0;\nstatic double Re = 0.0;\nstatic double MU = 0.0;\nstatic double L = 0.0;\nstatic double x_loc = 0.0;\nstatic double y_loc_max = 2.0;\nstatic double y_loc_min = -2.0;\nstatic double R1 = 0.0;\nstatic double R2 = 0.0;\nstatic double OMEGA1 = 0.0;\nstatic double OMEGA2 = 0.0;\nstatic double AA = 0.0;\nstatic double BB = 0.0;\nstatic double shift = 0.0;\nvoid\ntether_force_function_inner(VectorValue<double>& F,\n                            const VectorValue<double>& /*n*/,\n                            const VectorValue<double>& /*N*/,\n                            const TensorValue<double>& /*FF*/,\n                            const libMesh::Point& x,\n                            const libMesh::Point& X,\n                            Elem* const /*elem*/,\n                            const unsigned short /*side*/,\n                            const vector<const vector<double>*>& /*var_data*/,\n                            const vector<const vector<VectorValue<double> >*>& /*grad_var_data*/,\n                            double time,\n                            void* /*ctx*/)\n{\n    F(0) = kappa_s * (X(0) * cos(OMEGA1 * time) - X(1) * sin(OMEGA1 * time) - x(0));\n    F(1) = kappa_s * (X(0) * sin(OMEGA1 * time) + X(1) * cos(OMEGA1 * time) - x(1));\n\n    return;\n} // tether_force_function\n\n} // namespace ModelData\nusing namespace ModelData;\n\nvoid velocity_convergence(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                          const int u_idx,\n                          const double data_time,\n                          const string& data_dump_dirname);\n\nvoid compute_velocity_profile(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                              const int u_idx,\n                              const double data_time,\n                              const string& data_dump_dirname);\n\nvoid compute_pressure_profile(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                              const int p_idx,\n                              const double data_time,\n                              const string& data_dump_dirname);\n\nvoid pressure_convergence(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                          const int p_idx,\n                          const double data_time,\n                          const string& data_dump_dirname);\n\nvoid postprocess_data(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                      Pointer<INSHierarchyIntegrator> navier_stokes_integrator,\n                      Mesh& mesh,\n                      EquationSystems* equation_systems,\n                      const int iteration_num,\n                      const double loop_time,\n                      const string& data_dump_dirname);\n\n/*******************************************************************************\n * For each run, the input filename and restart information (if needed) must   *\n * be given on the command line.  For non-restarted case, command line is:     *\n *                                                                             *\n *    executable <input file name>                                             *\n *                                                                             *\n * For restarted run, command line is:                                         *\n *                                                                             *\n *    executable <input file name> <restart directory> <restart number>        *\n *                                                                             *\n *******************************************************************************/\nint\nmain(int argc, char* argv[])\n{\n    // Initialize libMesh, PETSc, MPI, and SAMRAI.\n    LibMeshInit init(argc, argv);\n    SAMRAI_MPI::setCommunicator(PETSC_COMM_WORLD);\n    SAMRAI_MPI::setCallAbortInSerialInsteadOfExit();\n    SAMRAIManager::startup();\n\n    PetscOptionsSetValue(nullptr, \"-ksp_rtol\", \"1e-10\");\n    PetscOptionsSetValue(nullptr, \"-stokes_ksp_atol\", \"1e-10\");\n\n    { // cleanup dynamically allocated objects prior to shutdown\n\n        // Parse command line options, set some standard options from the input\n        // file, initialize the restart database (if this is a restarted run),\n        // and enable file logging.\n        Pointer<AppInitializer> app_initializer = new AppInitializer(argc, argv, \"IB.log\");\n        Pointer<Database> input_db = app_initializer->getInputDatabase();\n\n        // Setup user-defined kernel function.\n\n        // Get various standard options set in the input file.\n        const bool dump_viz_data = app_initializer->dumpVizData();\n        const int viz_dump_interval = app_initializer->getVizDumpInterval();\n        const bool uses_visit = dump_viz_data && app_initializer->getVisItDataWriter();\n        const bool uses_exodus = dump_viz_data && !app_initializer->getExodusIIFilename().empty();\n        const string inner_exodus_filename = app_initializer->getExodusIIFilename(\"inner\");\n\n        const bool dump_restart_data = app_initializer->dumpRestartData();\n        const int restart_dump_interval = app_initializer->getRestartDumpInterval();\n        const string restart_dump_dirname = app_initializer->getRestartDumpDirectory();\n\n        const bool dump_postproc_data = app_initializer->dumpPostProcessingData();\n        const int postproc_data_dump_interval = app_initializer->getPostProcessingDataDumpInterval();\n        const string postproc_data_dump_dirname = app_initializer->getPostProcessingDataDumpDirectory();\n        if (dump_postproc_data && (postproc_data_dump_interval > 0) && !postproc_data_dump_dirname.empty())\n        {\n            Utilities::recursiveMkdir(postproc_data_dump_dirname);\n        }\n\n        const bool dump_timer_data = app_initializer->dumpTimerData();\n        const int timer_dump_interval = app_initializer->getTimerDumpInterval();\n\n        // Create a simple FE mesh.\n        Mesh mesh_interior(init.comm(), NDIM);\n        const double dx = input_db->getDouble(\"DX\");\n        MU = input_db->getDouble(\"MU\");\n        fac = input_db->getDouble(\"FAC\");\n        Re = input_db->getDouble(\"Re\");\n        shift = input_db->getDouble(\"SHIFT\");\n        L = input_db->getDouble(\"L\");\n        const double mfac = input_db->getDouble(\"MFAC\");\n        const double ds = mfac * dx;\n        string elem_type = input_db->getString(\"ELEM_TYPE\");\n        R1 = input_db->getDouble(\"R1\");         // radius of the inner circle\n        R2 = input_db->getDouble(\"R2\");         // radius of the outer circle\n        OMEGA1 = input_db->getDouble(\"OMEGA1\"); // radius of the inner circle\n        OMEGA2 = input_db->getDouble(\"OMEGA2\"); // radius of the outer circle\n\n        AA = input_db->getDouble(\"AA\"); // radius of the inner circle\n        BB = input_db->getDouble(\"BB\"); // radius of the outer circle\n\n#ifdef LIBMESH_HAVE_TRIANGLE\n        const int num_circum_nodes1 = ceil(2.0 * M_PI * R1 / ds);\n        for (int k = 0; k < num_circum_nodes1; ++k)\n        {\n            const double theta1 = 2.0 * M_PI * static_cast<double>(k) / static_cast<double>(num_circum_nodes1);\n            mesh_interior.add_point(libMesh::Point(R1 * cos(theta1), R1 * sin(theta1)));\n        }\n        TriangleInterface inner_triangle(mesh_interior);\n        inner_triangle.triangulation_type() = TriangleInterface::GENERATE_CONVEX_HULL;\n        inner_triangle.elem_type() = Utility::string_to_enum<ElemType>(elem_type);\n        inner_triangle.desired_area() = 1.5 * sqrt(3.0) / 4.0 * ds * ds;\n        inner_triangle.insert_extra_points() = true;\n        inner_triangle.smooth_after_generating() = true;\n        inner_triangle.triangulate();\n#else\n        TBOX_ERROR(\"ERROR: libMesh appears to have been configured without support for Triangle,\\n\"\n                   << \"       but Triangle is required for TRI3 or TRI6 elements.\\n\");\n#endif\n\n        // Ensure nodes on the surface are on the analytic boundary.\n        MeshBase::element_iterator el_end1 = mesh_interior.elements_end();\n        for (MeshBase::element_iterator el = mesh_interior.elements_begin(); el != el_end1; ++el)\n        {\n            Elem* const elem = *el;\n            for (unsigned int side = 0; side < elem->n_sides(); ++side)\n            {\n                const bool at_mesh_bdry = !elem->neighbor_ptr(side);\n                if (!at_mesh_bdry) continue;\n                for (unsigned int k = 0; k < elem->n_nodes(); ++k)\n                {\n                    if (!elem->is_node_on_side(k, side)) continue;\n                    Node& n = elem->node_ref(k);\n                    n = R1 * n.unit();\n                }\n            }\n        }\n        mesh_interior.prepare_for_use();\n\n        BoundaryMesh boundary_mesh_interior(mesh_interior.comm(), mesh_interior.mesh_dimension() - 1);\n        BoundaryInfo& boundary_info = mesh_interior.get_boundary_info();\n        boundary_info.sync(boundary_mesh_interior);\n        boundary_mesh_interior.prepare_for_use();\n\n        bool use_boundary_mesh = true;\n        Mesh& inner_mesh = use_boundary_mesh ? boundary_mesh_interior : mesh_interior;\n\n        kappa_s = input_db->getDouble(\"KAPPA_S\");\n        eta_s = input_db->getDouble(\"ETA_S\");\n\n        // Create major algorithm and data objects that comprise the\n        // application.  These objects are configured from the input database\n        // and, if this is a restarted run, from the restart database.\n        Pointer<INSHierarchyIntegrator> navier_stokes_integrator = new INSStaggeredHierarchyIntegrator(\n            \"INSStaggeredHierarchyIntegrator\",\n            app_initializer->getComponentDatabase(\"INSStaggeredHierarchyIntegrator\"));\n        Pointer<IBStrategy> ib_ops;\n        ib_ops = new IIMethod(\"IIMethod\",\n                              app_initializer->getComponentDatabase(\"IIMethod\"),\n                              &inner_mesh,\n                              app_initializer->getComponentDatabase(\"GriddingAlgorithm\")->getInteger(\"max_levels\"));\n        Pointer<IBHierarchyIntegrator> time_integrator =\n            new IBExplicitHierarchyIntegrator(\"IBHierarchyIntegrator\",\n                                              app_initializer->getComponentDatabase(\"IBHierarchyIntegrator\"),\n                                              ib_ops,\n                                              navier_stokes_integrator);\n\n        Pointer<CartesianGridGeometry<NDIM> > grid_geometry = new CartesianGridGeometry<NDIM>(\n            \"CartesianGeometry\", app_initializer->getComponentDatabase(\"CartesianGeometry\"));\n        Pointer<PatchHierarchy<NDIM> > patch_hierarchy = new PatchHierarchy<NDIM>(\"PatchHierarchy\", grid_geometry);\n        Pointer<StandardTagAndInitialize<NDIM> > error_detector =\n            new StandardTagAndInitialize<NDIM>(\"StandardTagAndInitialize\",\n                                               time_integrator,\n                                               app_initializer->getComponentDatabase(\"StandardTagAndInitialize\"));\n        Pointer<BergerRigoutsos<NDIM> > box_generator = new BergerRigoutsos<NDIM>();\n        Pointer<LoadBalancer<NDIM> > load_balancer =\n            new LoadBalancer<NDIM>(\"LoadBalancer\", app_initializer->getComponentDatabase(\"LoadBalancer\"));\n        Pointer<GriddingAlgorithm<NDIM> > gridding_algorithm =\n            new GriddingAlgorithm<NDIM>(\"GriddingAlgorithm\",\n                                        app_initializer->getComponentDatabase(\"GriddingAlgorithm\"),\n                                        error_detector,\n                                        box_generator,\n                                        load_balancer);\n\n        // Configure the IBFE solver.\n\n        std::vector<int> vars(NDIM);\n        for (unsigned int d = 0; d < NDIM; ++d) vars[d] = d;\n        vector<SystemData> sys_data(1, SystemData(IIMethod::VELOCITY_SYSTEM_NAME, vars));\n        Pointer<IIMethod> ibfe_ops = ib_ops;\n        ibfe_ops->initializeFEEquationSystems();\n\n        EquationSystems* inner_equation_systems = ibfe_ops->getFEDataManager()->getEquationSystems();\n        IIMethod::LagSurfaceForceFcnData tether_force_inner_data(tether_force_function_inner, sys_data);\n\n        ibfe_ops->registerLagSurfaceForceFunction(tether_force_inner_data);\n\n        // Create Eulerian initial condition specification objects.\n\n        Pointer<CartGridFunction> u_init = new muParserCartGridFunction(\n            \"u_init\", app_initializer->getComponentDatabase(\"VelocityInitialConditions\"), grid_geometry);\n        navier_stokes_integrator->registerVelocityInitialConditions(u_init);\n\n        Pointer<CartGridFunction> p_init = new muParserCartGridFunction(\n            \"p_init\", app_initializer->getComponentDatabase(\"PressureInitialConditions\"), grid_geometry);\n\n        if (input_db->keyExists(\"ForcingFunction\"))\n        {\n            Pointer<CartGridFunction> f_fcn = new muParserCartGridFunction(\n                \"f_fcn\", app_initializer->getComponentDatabase(\"ForcingFunction\"), grid_geometry);\n            time_integrator->registerBodyForceFunction(f_fcn);\n        }\n\n        // Create Eulerian boundary condition specification objects (when necessary).\n        vector<RobinBcCoefStrategy<NDIM>*> u_bc_coefs(NDIM, static_cast<RobinBcCoefStrategy<NDIM>*>(NULL));\n        const bool periodic_domain = grid_geometry->getPeriodicShift().min() > 0;\n        if (!periodic_domain)\n        {\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                ostringstream bc_coefs_name_stream;\n                bc_coefs_name_stream << \"u_bc_coefs_\" << d;\n                const string bc_coefs_name = bc_coefs_name_stream.str();\n                ostringstream bc_coefs_db_name_stream;\n                bc_coefs_db_name_stream << \"VelocityBcCoefs_\" << d;\n                const string bc_coefs_db_name = bc_coefs_db_name_stream.str();\n                u_bc_coefs[d] = new muParserRobinBcCoefs(\n                    bc_coefs_name, app_initializer->getComponentDatabase(bc_coefs_db_name), grid_geometry);\n            }\n            navier_stokes_integrator->registerPhysicalBoundaryConditions(u_bc_coefs);\n        }\n\n        // Set up visualization plot file writers.\n\n        Pointer<VisItDataWriter<NDIM> > visit_data_writer = app_initializer->getVisItDataWriter();\n        if (uses_visit)\n        {\n            time_integrator->registerVisItDataWriter(visit_data_writer);\n        }\n        std::unique_ptr<ExodusII_IO> inner_exodus_io(uses_exodus ? new ExodusII_IO(inner_mesh) : NULL);\n\n        // Initialize hierarchy configuration and data on all patches.\n        ibfe_ops->initializeFEData();\n        time_integrator->initializePatchHierarchy(patch_hierarchy, gridding_algorithm);\n\n        // Deallocate initialization objects.\n        app_initializer.setNull();\n\n        // Write out initial visualization data.\n        int iteration_num = time_integrator->getIntegratorStep();\n        double loop_time = time_integrator->getIntegratorTime();\n        if (dump_viz_data)\n        {\n            pout << \"\\n\\nWriting visualization files...\\n\\n\";\n            if (uses_visit)\n            {\n                time_integrator->setupPlotData();\n                visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n            }\n            if (uses_exodus)\n            {\n                inner_exodus_io->write_timestep(\n                    inner_exodus_filename, *inner_equation_systems, iteration_num / viz_dump_interval + 1, loop_time);\n            }\n        }\n\n        // Main time step loop.\n        double loop_time_end = time_integrator->getEndTime();\n        double dt = 0.0;\n        while (!MathUtilities<double>::equalEps(loop_time, loop_time_end) && time_integrator->stepsRemaining())\n        {\n            iteration_num = time_integrator->getIntegratorStep();\n            loop_time = time_integrator->getIntegratorTime();\n\n            pout << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"At beginning of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n\n            dt = time_integrator->getMaximumTimeStepSize();\n            time_integrator->advanceHierarchy(dt);\n            loop_time += dt;\n\n            pout << \"\\n\";\n            pout << \"At end       of timestep # \" << iteration_num << \"\\n\";\n            pout << \"Simulation time is \" << loop_time << \"\\n\";\n            pout << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n            pout << \"\\n\";\n\n            VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n            Pointer<hier::Variable<NDIM> > u_var = time_integrator->getVelocityVariable();\n            Pointer<VariableContext> current_ctx = time_integrator->getCurrentContext();\n            const int u_idx = var_db->mapVariableAndContextToIndex(u_var, current_ctx);\n\n            const Pointer<hier::Variable<NDIM> > p_var = time_integrator->getPressureVariable();\n            const Pointer<VariableContext> p_ctx = time_integrator->getCurrentContext();\n            const int p_idx = var_db->mapVariableAndContextToIndex(p_var, p_ctx);\n\n            // At specified intervals, write visualization and restart files,\n            // print out timer data, and store hierarchy data for post\n            // processing.\n            iteration_num += 1;\n            const bool last_step = !time_integrator->stepsRemaining();\n            if (dump_viz_data && (iteration_num % viz_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting visualization files...\\n\\n\";\n                if (uses_visit)\n                {\n                    time_integrator->setupPlotData();\n                    visit_data_writer->writePlotData(patch_hierarchy, iteration_num, loop_time);\n                }\n                if (uses_exodus)\n                {\n                    inner_exodus_io->write_timestep(inner_exodus_filename,\n                                                    *inner_equation_systems,\n                                                    iteration_num / viz_dump_interval + 1,\n                                                    loop_time);\n                }\n            }\n            if (dump_restart_data && (iteration_num % restart_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting restart files...\\n\\n\";\n                RestartManager::getManager()->writeRestartFile(restart_dump_dirname, iteration_num);\n            }\n            if (dump_timer_data && (iteration_num % timer_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting timer data...\\n\\n\";\n                TimerManager::getManager()->print(plog);\n            }\n\n            postprocess_data(patch_hierarchy,\n                             navier_stokes_integrator,\n                             inner_mesh,\n                             inner_equation_systems,\n                             iteration_num,\n                             loop_time,\n                             postproc_data_dump_dirname);\n\n            if (dump_postproc_data && (iteration_num % postproc_data_dump_interval == 0 || last_step))\n            {\n                pout << \"\\nWriting state data...\\n\\n\";\n\n                compute_velocity_profile(patch_hierarchy, u_idx, loop_time, postproc_data_dump_dirname);\n                compute_pressure_profile(patch_hierarchy, p_idx, loop_time, postproc_data_dump_dirname);\n            }\n        }\n\n        // Determine the accuracy of the computed solution.\n        pout << \"\\n\"\n             << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\"\n             << \"Computing error norms.\\n\\n\";\n        VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase();\n        const int finest_ln = patch_hierarchy->getFinestLevelNumber();\n        HierarchyMathOps hier_math_ops(\"hier_math_ops\", patch_hierarchy);\n        hier_math_ops.resetLevels(finest_ln, finest_ln);\n        Pointer<hier::Variable<NDIM> > u_var = time_integrator->getVelocityVariable();\n        const Pointer<VariableContext> u_ctx = time_integrator->getCurrentContext();\n        const int u_idx = var_db->mapVariableAndContextToIndex(u_var, u_ctx);\n        const int u_cloned_idx = var_db->registerClonedPatchDataIndex(u_var, u_idx);\n\n        const Pointer<hier::Variable<NDIM> > p_var = time_integrator->getPressureVariable();\n        const Pointer<VariableContext> p_ctx = time_integrator->getCurrentContext();\n\n        const int p_idx = var_db->mapVariableAndContextToIndex(p_var, p_ctx);\n        const int p_cloned_idx = var_db->registerClonedPatchDataIndex(p_var, p_idx);\n\n        pressure_convergence(patch_hierarchy, p_idx, loop_time, postproc_data_dump_dirname);\n\n        velocity_convergence(patch_hierarchy, u_idx, loop_time, postproc_data_dump_dirname);\n\n        const int coarsest_ln = 0;\n        for (int ln = coarsest_ln; ln <= finest_ln; ++ln)\n        {\n            patch_hierarchy->getPatchLevel(ln)->allocatePatchData(u_cloned_idx, loop_time);\n            patch_hierarchy->getPatchLevel(ln)->allocatePatchData(p_cloned_idx, loop_time);\n        }\n        u_init->setDataOnPatchHierarchy(u_cloned_idx, u_var, patch_hierarchy, loop_time);\n        p_init->setDataOnPatchHierarchy(p_cloned_idx, p_var, patch_hierarchy, loop_time - 0.5 * dt);\n\n        hier_math_ops.setPatchHierarchy(patch_hierarchy);\n        hier_math_ops.resetLevels(coarsest_ln, finest_ln);\n        const int wgt_sc_idx = hier_math_ops.getSideWeightPatchDescriptorIndex();\n        HierarchySideDataOpsReal<NDIM, double> hier_sc_data_ops(patch_hierarchy, coarsest_ln, finest_ln);\n        hier_sc_data_ops.subtract(u_idx, u_idx, u_cloned_idx);\n        pout << std::setprecision(16) << \"Error in the Eulerian u at time \" << loop_time << \":\\n\"\n             << \"  L2-norm:  \" << hier_sc_data_ops.L2Norm(u_idx, wgt_sc_idx) << \"\\n\"\n             << \"  max-norm: \" << hier_sc_data_ops.maxNorm(u_idx, wgt_sc_idx) << \"\\n\"\n             << \"+++++++++++++++++++++++++++++++++++++++++++++++++++\\n\";\n\n        pout << \" MU = \" << MU << \"\\n\"\n             << \"  dx:  \" << dx << \"\\n\"\n             << \"  dt: \" << dt << \"\\n\";\n\n        if (input_db->getBool(\"USE_VELOCITY_JUMP_CONDITIONS\"))\n            pout << \" Using the jump condition\"\n                 << \"\\n\";\n        else\n            pout << \" Using regular IB\"\n                 << \"\\n\";\n\n        if (dump_viz_data && uses_visit)\n        {\n            time_integrator->setupPlotData();\n            visit_data_writer->writePlotData(patch_hierarchy, iteration_num + 1, loop_time);\n        }\n\n        // Cleanup Eulerian boundary condition specification objects (when\n        // necessary).\n        for (unsigned int d = 0; d < NDIM; ++d) delete u_bc_coefs[d];\n\n    } // cleanup dynamically allocated objects prior to shutdown\n\n    SAMRAIManager::shutdown();\n    return 0;\n} // main\n\nvoid\nvelocity_convergence(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                     const int u_idx,\n                     const double /*data_time*/,\n                     const string& /*data_dump_dirname*/)\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = patch_hierarchy->getFinestLevelNumber();\n\n    HierarchyMathOps hier_math_ops(\"hier_math_ops\", patch_hierarchy);\n    hier_math_ops.resetLevels(finest_ln, finest_ln);\n    const int wgt_cc_idx = hier_math_ops.getCellWeightPatchDescriptorIndex();\n    const double X_min[2] = { -0.45 * L, -0.45 * L };\n    const double X_max[2] = { 0.45 * L, 0.45 * L };\n\n    double u_Eulerian_L2_norm = 0.0;\n    double u_Eulerian_max_norm = 0.0;\n    int N_max = 0;\n    vector<double> pos_values;\n    for (int ln = finest_ln; ln >= coarsest_ln; --ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);\n        for (PatchLevel<NDIM>::Iterator p(level); p; p++)\n        {\n            Pointer<Patch<NDIM> > patch = level->getPatch(p());\n            const Box<NDIM>& patch_box = patch->getBox();\n            const CellIndex<NDIM>& patch_lower = patch_box.lower();\n            const CellIndex<NDIM>& patch_upper = patch_box.upper();\n\n            const Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry();\n            const double* const patch_x_lower = patch_geom->getXLower();\n            const double* const patch_x_upper = patch_geom->getXUpper();\n\n            const double* const patch_dx = patch_geom->getDx();\n\n            // Entire box containing the required data.\n            Box<NDIM> box(IndexUtilities::getCellIndex(\n                              &X_min[0], patch_x_lower, patch_x_upper, patch_dx, patch_lower, patch_upper),\n                          IndexUtilities::getCellIndex(\n                              &X_max[0], patch_x_lower, patch_x_upper, patch_dx, patch_lower, patch_upper));\n            // Part of the box on this patch\n            Box<NDIM> trim_box = patch_box * box;\n            BoxList<NDIM> iterate_box_list = trim_box;\n\n            // Trim the box covered by the finer region\n            BoxList<NDIM> covered_boxes;\n            if (ln < finest_ln)\n            {\n                BoxArray<NDIM> refined_region_boxes;\n                Pointer<PatchLevel<NDIM> > next_finer_level = patch_hierarchy->getPatchLevel(ln + 1);\n                refined_region_boxes = next_finer_level->getBoxes();\n                refined_region_boxes.coarsen(next_finer_level->getRatioToCoarserLevel());\n                for (int i = 0; i < refined_region_boxes.getNumberOfBoxes(); ++i)\n                {\n                    const Box<NDIM> refined_box = refined_region_boxes[i];\n                    const Box<NDIM> covered_box = trim_box * refined_box;\n                    covered_boxes.unionBoxes(covered_box);\n                }\n            }\n            iterate_box_list.removeIntersections(covered_boxes);\n\n            // Loop over the boxes and store the location and interpolated value.\n            Pointer<SideData<NDIM, double> > u_data = patch->getPatchData(u_idx);\n            const Pointer<CellData<NDIM, double> > wgt_cc_data = patch->getPatchData(wgt_cc_idx);\n\n            for (BoxList<NDIM>::Iterator lit(iterate_box_list); lit; lit++)\n            {\n                const Box<NDIM>& iterate_box = *lit;\n                for (Box<NDIM>::Iterator bit(iterate_box); bit; bit++)\n                {\n                    const CellIndex<NDIM>& lower_idx = *bit;\n\n                    const double yu = patch_x_lower[1] + patch_dx[1] * (lower_idx(1) - patch_lower(1) + 0.5);\n                    const double xu = patch_x_lower[0] + patch_dx[0] * (lower_idx(0) - patch_lower(0));\n\n                    const double yv = patch_x_lower[1] + patch_dx[1] * (lower_idx(1) - patch_lower(1));\n                    const double xv = patch_x_lower[0] + patch_dx[0] * (lower_idx(0) - patch_lower(0) + 0.5);\n\n                    double u_ex, v_ex;\n                    if (sqrt(xu * xu + yu * yu) < R1)\n                    {\n                        u_ex = -OMEGA1 * yu;\n                    }\n                    else if (sqrt(xu * xu + yu * yu) > R2)\n                    {\n                        u_ex = 0.0;\n                    }\n                    else\n                    {\n                        u_ex = -yu * (AA + BB / (xu * xu + yu * yu));\n                    }\n\n                    if (sqrt(xv * xv + yv * yv) < R1)\n                    {\n                        v_ex = OMEGA1 * xv;\n                    }\n                    else if (sqrt(xv * xv + yv * yv) > R2)\n                    {\n                        v_ex = 0.0;\n                    }\n                    else\n                    {\n                        v_ex = xv * (AA + BB / (xv * xv + yv * yv));\n                    }\n\n                    const double u0 = (*u_data)(SideIndex<NDIM>(lower_idx, 0, SideIndex<NDIM>::Lower));\n                    const double v0 = (*u_data)(SideIndex<NDIM>(lower_idx, 1, SideIndex<NDIM>::Lower));\n                    N_max += 1;\n                    u_Eulerian_L2_norm += std::abs(u0 - u_ex) * std::abs(u0 - u_ex) * (*wgt_cc_data)(lower_idx);\n                    u_Eulerian_L2_norm += std::abs(v0 - v_ex) * std::abs(v0 - v_ex) * (*wgt_cc_data)(lower_idx);\n\n                    u_Eulerian_max_norm = std::max(u_Eulerian_max_norm, std::abs(u0 - u_ex));\n                    u_Eulerian_max_norm = std::max(u_Eulerian_max_norm, std::abs(v0 - v_ex));\n                }\n            }\n        }\n    }\n\n    SAMRAI_MPI::sumReduction(&N_max, 1);\n    SAMRAI_MPI::sumReduction(&u_Eulerian_L2_norm, 1);\n    SAMRAI_MPI::maxReduction(&u_Eulerian_max_norm, 1);\n\n    u_Eulerian_L2_norm = sqrt(u_Eulerian_L2_norm);\n\n    pout << \" u_Eulerian_L2_norm = \" << u_Eulerian_L2_norm << \"\\n\\n\";\n    pout << \" u_Eulerian_max_norm = \" << u_Eulerian_max_norm << \"\\n\\n\";\n\n    return;\n} // velocity_convergence\n\nvoid\npressure_convergence(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                     const int p_idx,\n                     const double /*data_time*/,\n                     const string& /*data_dump_dirname*/)\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = patch_hierarchy->getFinestLevelNumber();\n\n    HierarchyMathOps hier_math_ops(\"hier_math_ops\", patch_hierarchy);\n    hier_math_ops.resetLevels(finest_ln, finest_ln);\n    const int wgt_cc_idx = hier_math_ops.getCellWeightPatchDescriptorIndex();\n\n    const double X_min[2] = { -0.45 * L, -0.45 * L };\n    const double X_max[2] = { 0.45 * L, 0.45 * L };\n    // vector<double> pos_values;\n    double p_Eulerian_L2_norm = 0.0;\n    double p_Eulerian_max_norm = 0.0;\n    int N_max = 0;\n    for (int ln = finest_ln; ln >= coarsest_ln; --ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);\n        for (PatchLevel<NDIM>::Iterator p(level); p; p++)\n        {\n            Pointer<Patch<NDIM> > patch = level->getPatch(p());\n            const Box<NDIM>& patch_box = patch->getBox();\n            const CellIndex<NDIM>& patch_lower = patch_box.lower();\n            const CellIndex<NDIM>& patch_upper = patch_box.upper();\n\n            const Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry();\n            const double* const patch_x_lower = patch_geom->getXLower();\n            const double* const patch_x_upper = patch_geom->getXUpper();\n            const double* const patch_dx = patch_geom->getDx();\n\n            // Entire box containing the required data.\n            Box<NDIM> box(IndexUtilities::getCellIndex(\n                              &X_min[0], patch_x_lower, patch_x_upper, patch_dx, patch_lower, patch_upper),\n                          IndexUtilities::getCellIndex(\n                              &X_max[0], patch_x_lower, patch_x_upper, patch_dx, patch_lower, patch_upper));\n            // Part of the box on this patch\n            Box<NDIM> trim_box = patch_box * box;\n            BoxList<NDIM> iterate_box_list = trim_box;\n\n            // Trim the box covered by the finer region\n            BoxList<NDIM> covered_boxes;\n            if (ln < finest_ln)\n            {\n                BoxArray<NDIM> refined_region_boxes;\n                Pointer<PatchLevel<NDIM> > next_finer_level = patch_hierarchy->getPatchLevel(ln + 1);\n                refined_region_boxes = next_finer_level->getBoxes();\n                refined_region_boxes.coarsen(next_finer_level->getRatioToCoarserLevel());\n                for (int i = 0; i < refined_region_boxes.getNumberOfBoxes(); ++i)\n                {\n                    const Box<NDIM> refined_box = refined_region_boxes[i];\n                    const Box<NDIM> covered_box = trim_box * refined_box;\n                    covered_boxes.unionBoxes(covered_box);\n                }\n            }\n            iterate_box_list.removeIntersections(covered_boxes);\n\n            // Loop over the boxes and store the location and interpolated value.\n            const Pointer<CellData<NDIM, double> > p_data = patch->getPatchData(p_idx);\n            const Pointer<CellData<NDIM, double> > wgt_cc_data = patch->getPatchData(wgt_cc_idx);\n            for (BoxList<NDIM>::Iterator lit(iterate_box_list); lit; lit++)\n            {\n                const Box<NDIM>& iterate_box = *lit;\n                for (Box<NDIM>::Iterator bit(iterate_box); bit; bit++)\n                {\n                    const CellIndex<NDIM>& cell_idx = *bit;\n\n                    const double y = patch_x_lower[1] + patch_dx[1] * (cell_idx(1) - patch_lower(1) + 0.5);\n                    const double x = patch_x_lower[0] + patch_dx[0] * (cell_idx(0) - patch_lower(0) + 0.5);\n\n                    const double p1 = (*p_data)(cell_idx);\n                    double p_ex_qp;\n\n                    N_max += 1;\n                    if (sqrt(x * x + y * y) <= R1 - fac * patch_dx[0])\n                    {\n                        p_ex_qp = 0.5 * OMEGA1 * OMEGA1 * (x * x + y * y) + shift; // p1;\n                    }\n                    else if (sqrt(x * x + y * y) > (R1 - fac * patch_dx[0]) &&\n                             sqrt(x * x + y * y) < (R1 + fac * patch_dx[0]))\n                    {\n                        p_ex_qp = p1;\n                    }\n                    else\n                    {\n                        p_ex_qp = 0.5 * AA * AA * (x * x + y * y) - 0.5 * BB * BB / (x * x + y * y) +\n                                  AA * BB * log(x * x + y * y) + 0.5 * OMEGA1 * OMEGA1 * R1 * R1 -\n                                  (0.5 * AA * AA * (R1 * R1) - 0.5 * BB * BB / (R1 * R1) + AA * BB * log(R1 * R1)) +\n                                  shift;\n                    }\n\n                    p_Eulerian_L2_norm += std::abs(p1 - p_ex_qp) * std::abs(p1 - p_ex_qp) * (*wgt_cc_data)(cell_idx);\n                    p_Eulerian_max_norm = std::max(p_Eulerian_max_norm, std::abs(p1 - p_ex_qp));\n                }\n            }\n        }\n    }\n    SAMRAI_MPI::sumReduction(&N_max, 1);\n    SAMRAI_MPI::sumReduction(&p_Eulerian_L2_norm, 1);\n    SAMRAI_MPI::maxReduction(&p_Eulerian_max_norm, 1);\n\n    p_Eulerian_L2_norm = sqrt(p_Eulerian_L2_norm);\n\n    pout << \" p_Eulerian_L2_norm = \" << p_Eulerian_L2_norm << \"\\n\";\n    pout << \" p_Eulerian_max_norm = \" << p_Eulerian_max_norm << \"\\n\\n\";\n\n    return;\n} // pressure_convergence\n\nvoid\npostprocess_data(Pointer<PatchHierarchy<NDIM> > /*patch_hierarchy*/,\n                 Pointer<INSHierarchyIntegrator> /*navier_stokes_integrator*/,\n                 Mesh& mesh,\n                 EquationSystems* equation_systems,\n                 const int /*iteration_num*/,\n                 const double loop_time,\n                 const string& /*data_dump_dirname*/)\n{\n    const unsigned int dim = mesh.mesh_dimension();\n    double F_integral[NDIM];\n    for (unsigned int d = 0; d < NDIM; ++d) F_integral[d] = 0.0;\n\n    System& x_system = equation_systems->get_system(IIMethod::COORDS_SYSTEM_NAME);\n    System& U_system = equation_systems->get_system(IIMethod::VELOCITY_SYSTEM_NAME);\n    NumericVector<double>* x_vec = x_system.solution.get();\n    NumericVector<double>& X0_vec = x_system.get_vector(\"INITIAL_COORDINATES\");\n    NumericVector<double>* x_ghost_vec = x_system.current_local_solution.get();\n    x_vec->localize(*x_ghost_vec);\n    NumericVector<double>* U_vec = U_system.solution.get();\n    NumericVector<double>* U_ghost_vec = U_system.current_local_solution.get();\n    U_vec->localize(*U_ghost_vec);\n    const DofMap& dof_map = x_system.get_dof_map();\n    std::vector<std::vector<unsigned int> > dof_indices(NDIM);\n\n    std::unique_ptr<FEBase> fe(FEBase::build(dim, dof_map.variable_type(0)));\n    std::unique_ptr<QBase> qrule = QBase::build(QGAUSS, dim, SEVENTH);\n    fe->attach_quadrature_rule(qrule.get());\n    const vector<double>& JxW = fe->get_JxW();\n    const vector<libMesh::Point>& q_point = fe->get_xyz();\n    const vector<vector<double> >& phi = fe->get_phi();\n    const vector<vector<VectorValue<double> > >& dphi = fe->get_dphi();\n    const std::vector<std::vector<double> >& dphi_dxi = fe->get_dphidxi();\n\n    std::vector<double> U_qp_vec(NDIM);\n    std::vector<const std::vector<double>*> var_data(1);\n    var_data[0] = &U_qp_vec;\n    std::vector<const std::vector<libMesh::VectorValue<double> >*> grad_var_data;\n    void* force_fcn_ctx = NULL;\n\n    TensorValue<double> FF_qp;\n    boost::multi_array<double, 2> x_node, X_node, U_node, P_o_node, P_j_node;\n    VectorValue<double> F_qp, U_qp, x_qp, X_qp, N, n;\n\n    const MeshBase::const_element_iterator el_begin = mesh.active_local_elements_begin();\n    const MeshBase::const_element_iterator el_end = mesh.active_local_elements_end();\n    for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)\n    {\n        Elem* const elem = *el_it;\n        fe->reinit(elem);\n        for (unsigned int d = 0; d < NDIM; ++d)\n        {\n            dof_map.dof_indices(elem, dof_indices[d], d);\n        }\n        get_values_for_interpolation(x_node, *x_ghost_vec, dof_indices);\n        get_values_for_interpolation(X_node, X0_vec, dof_indices);\n        get_values_for_interpolation(U_node, *U_ghost_vec, dof_indices);\n\n        const unsigned int n_qp = qrule->n_points();\n        for (unsigned int qp = 0; qp < n_qp; ++qp)\n        {\n            interpolate(x_qp, qp, x_node, phi);\n            interpolate(X_qp, qp, X_node, phi);\n            jacobian(FF_qp, qp, x_node, dphi);\n            interpolate(U_qp, qp, U_node, phi);\n\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                U_qp_vec[d] = U_qp(d);\n            }\n            tether_force_function_inner(\n                F_qp, n, N, FF_qp, x_qp, q_point[qp], elem, 0, var_data, grad_var_data, loop_time, force_fcn_ctx);\n\n            for (int d = 0; d < NDIM; ++d)\n            {\n                F_integral[d] += F_qp(d) * JxW[qp];\n            }\n        }\n    }\n    SAMRAI_MPI::sumReduction(F_integral, NDIM);\n\n    {\n        double WSS_L2_norm = 0.0, WSS_max_norm = 0.0;\n        double U_L2_norm = 0.0, U_max_norm = 0.0;\n        double P_L2_norm = 0.0, P_max_norm = 0.0;\n        double disp_L2_norm = 0.0, disp_max_norm = 0.0;\n        System& U_system = equation_systems->get_system<System>(IIMethod::VELOCITY_SYSTEM_NAME);\n        System& WSS_system = equation_systems->get_system<System>(IIMethod::WSS_OUT_SYSTEM_NAME);\n        System& P_o_system = equation_systems->get_system<System>(IIMethod::PRESSURE_OUT_SYSTEM_NAME);\n        System& P_j_system = equation_systems->get_system<System>(IIMethod::PRESSURE_JUMP_SYSTEM_NAME);\n\n        NumericVector<double>* U_vec = U_system.solution.get();\n        NumericVector<double>* U_ghost_vec = U_system.current_local_solution.get();\n        U_vec->localize(*U_ghost_vec);\n        DofMap& U_dof_map = U_system.get_dof_map();\n        std::vector<std::vector<unsigned int> > U_dof_indices(NDIM);\n\n        NumericVector<double>* WSS_vec = WSS_system.solution.get();\n        NumericVector<double>* WSS_ghost_vec = WSS_system.current_local_solution.get();\n        WSS_vec->localize(*WSS_ghost_vec);\n        DofMap& WSS_dof_map = WSS_system.get_dof_map();\n        std::vector<std::vector<unsigned int> > WSS_dof_indices(NDIM);\n        std::unique_ptr<FEBase> fe(FEBase::build(dim, WSS_dof_map.variable_type(0)));\n\n        NumericVector<double>* P_o_vec = P_o_system.solution.get();\n        NumericVector<double>* P_o_ghost_vec = P_o_system.current_local_solution.get();\n        P_o_vec->localize(*P_o_ghost_vec);\n        DofMap& P_o_dof_map = P_o_system.get_dof_map();\n        std::vector<unsigned int> P_o_dof_indices;\n\n        NumericVector<double>* P_j_vec = P_j_system.solution.get();\n        NumericVector<double>* P_j_ghost_vec = P_j_system.current_local_solution.get();\n        P_j_vec->localize(*P_j_ghost_vec);\n        DofMap& P_j_dof_map = P_j_system.get_dof_map();\n        std::vector<unsigned int> P_j_dof_indices;\n\n        VectorValue<double> U_qp, WSS_qp;\n        double P_o_qp, P_j_qp;\n        VectorValue<double> tau1, tau2;\n        int qp_tot = 0;\n        boost::multi_array<double, 2> U_node, WSS_node;\n        boost::multi_array<double, 1> P_o_node, P_j_node;\n        const MeshBase::const_element_iterator el_begin = mesh.active_local_elements_begin();\n        const MeshBase::const_element_iterator el_end = mesh.active_local_elements_end();\n        for (MeshBase::const_element_iterator el_it = el_begin; el_it != el_end; ++el_it)\n        {\n            Elem* const elem = *el_it;\n            // fe->reinit(elem);\n            for (unsigned int d = 0; d < NDIM; ++d)\n            {\n                dof_map.dof_indices(elem, dof_indices[d], d);\n                U_dof_map.dof_indices(elem, U_dof_indices[d], d);\n                WSS_dof_map.dof_indices(elem, WSS_dof_indices[d], d);\n            }\n            P_j_dof_map.dof_indices(elem, P_j_dof_indices);\n            P_o_dof_map.dof_indices(elem, P_o_dof_indices);\n            const int n_qp = qrule->n_points();\n            get_values_for_interpolation(U_node, *U_ghost_vec, U_dof_indices);\n            get_values_for_interpolation(WSS_node, *WSS_ghost_vec, WSS_dof_indices);\n            get_values_for_interpolation(P_j_node, *P_j_ghost_vec, P_j_dof_indices);\n            get_values_for_interpolation(P_o_node, *P_o_ghost_vec, P_o_dof_indices);\n            get_values_for_interpolation(x_node, *x_ghost_vec, dof_indices);\n            get_values_for_interpolation(X_node, X0_vec, dof_indices);\n\n            for (int qp = 0; qp < n_qp; ++qp)\n            {\n                interpolate(x_qp, qp, x_node, phi);\n                interpolate(X_qp, qp, X_node, phi);\n                interpolate(U_qp, qp, U_node, phi);\n                interpolate(WSS_qp, qp, WSS_node, phi);\n                interpolate(P_o_qp, qp, P_o_node, phi);\n                interpolate(P_j_qp, qp, P_j_node, phi);\n                double P_i_qp = -(P_j_qp - P_o_qp);\n                interpolate(&tau1(0), qp, x_node, dphi_dxi);\n\n                tau2 = VectorValue<double>(0.0, 0.0, 1.0);\n\n                n = tau1.cross(tau2);\n                n = n.unit();\n\n                double ex_wss[NDIM];\n                double ex_U[NDIM];\n                ex_U[0] = (-x_qp(1) / sqrt(x_qp(0) * x_qp(0) + x_qp(1) * x_qp(1))) * R1 * OMEGA1;\n                ex_U[1] = (x_qp(0) / sqrt(x_qp(0) * x_qp(0) + x_qp(1) * x_qp(1))) * R1 * OMEGA1;\n\n                ex_wss[0] = (-x_qp(1) / sqrt(x_qp(0) * x_qp(0) + x_qp(1) * x_qp(1))) * MU * (AA - BB / (R1 * R1));\n                ex_wss[1] = (x_qp(0) / sqrt(x_qp(0) * x_qp(0) + x_qp(1) * x_qp(1))) * MU * (AA - BB / (R1 * R1));\n                libMesh::Point X = q_point[qp];\n\n                double p_ex_qp = 0.5 * OMEGA1 * OMEGA1 * R1 * R1 + shift;\n                qp_tot += 1;\n                for (unsigned int d = 0; d < NDIM; ++d)\n                {\n                    U_L2_norm += (U_qp(d) - ex_U[d]) * (U_qp(d) - ex_U[d]) * JxW[qp];\n                    U_max_norm = std::max(U_max_norm, std::abs(U_qp(d) - ex_U[d]));\n\n                    WSS_L2_norm += (WSS_qp(d) - ex_wss[d]) * (WSS_qp(d) - ex_wss[d]) * JxW[qp];\n                    WSS_max_norm = std::max(WSS_max_norm, std::abs(WSS_qp(d) - ex_wss[d]));\n                }\n                P_L2_norm += std::abs(P_i_qp - p_ex_qp) * std::abs(P_i_qp - p_ex_qp) * JxW[qp];\n                P_max_norm = std::max(P_max_norm, std::abs(P_i_qp - p_ex_qp));\n\n                disp_L2_norm += (X_qp(0) * cos(OMEGA1 * loop_time) - X_qp(1) * sin(OMEGA1 * loop_time) - x_qp(0)) *\n                                (X_qp(0) * cos(OMEGA1 * loop_time) - X_qp(1) * sin(OMEGA1 * loop_time) - x_qp(0)) *\n                                JxW[qp];\n                disp_L2_norm += (X_qp(0) * sin(OMEGA1 * loop_time) + X_qp(1) * cos(OMEGA1 * loop_time) - x_qp(1)) *\n                                (X_qp(0) * sin(OMEGA1 * loop_time) + X_qp(1) * cos(OMEGA1 * loop_time) - x_qp(1)) *\n                                JxW[qp];\n\n                disp_max_norm =\n                    std::max(disp_max_norm,\n                             std::abs(X_qp(0) * cos(OMEGA1 * loop_time) - X_qp(1) * sin(OMEGA1 * loop_time) - x_qp(0)));\n                disp_max_norm =\n                    std::max(disp_max_norm,\n                             std::abs(X_qp(0) * sin(OMEGA1 * loop_time) + X_qp(1) * cos(OMEGA1 * loop_time) - x_qp(1)));\n            }\n        }\n\n        SAMRAI_MPI::sumReduction(&qp_tot, 1);\n        SAMRAI_MPI::sumReduction(&WSS_L2_norm, 1);\n        SAMRAI_MPI::maxReduction(&WSS_max_norm, 1);\n        SAMRAI_MPI::sumReduction(&U_L2_norm, 1);\n        SAMRAI_MPI::maxReduction(&U_max_norm, 1);\n        SAMRAI_MPI::sumReduction(&disp_L2_norm, 1);\n        SAMRAI_MPI::maxReduction(&disp_max_norm, 1);\n        SAMRAI_MPI::sumReduction(&P_L2_norm, 1);\n        SAMRAI_MPI::maxReduction(&P_max_norm, 1);\n\n        U_L2_norm = sqrt(U_L2_norm);\n        WSS_L2_norm = sqrt(WSS_L2_norm);\n        disp_L2_norm = sqrt(disp_L2_norm);\n        P_L2_norm = sqrt(P_L2_norm);\n\n        pout << \" Lagrangian WSS_L2_norm = \" << WSS_L2_norm << \"\\n\\n\";\n        pout << \" Lagrangian WSS_max_norm = \" << WSS_max_norm << \"\\n\\n\";\n\n        pout << \" Lagrangian U_L2_norm = \" << U_L2_norm << \"\\n\\n\";\n        pout << \" Lagrangian U_max_norm = \" << U_max_norm << \"\\n\\n\";\n\n        pout << \" Lagrangian disp_L2_norm = \" << disp_L2_norm << \"\\n\\n\";\n        pout << \" Lagrangian disp_max_norm = \" << disp_max_norm << \"\\n\\n\";\n\n        pout << \"Lagrangian P_L2_norm = \" << P_L2_norm << \"\\n\\n\";\n        pout << \"Lagrangian P_max_norm = \" << P_max_norm << \"\\n\\n\";\n    }\n\n    return;\n} // postprocess_data\n\nvoid\ncompute_velocity_profile(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                         const int u_idx,\n                         const double data_time,\n                         const string& data_dump_dirname)\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = patch_hierarchy->getFinestLevelNumber();\n\n    const double X_min[2] = { x_loc, -0.5 * L };\n    const double X_max[2] = { x_loc, 0.5 * L };\n    vector<double> pos_values;\n    for (int ln = finest_ln; ln >= coarsest_ln; --ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);\n        for (PatchLevel<NDIM>::Iterator p(level); p; p++)\n        {\n            Pointer<Patch<NDIM> > patch = level->getPatch(p());\n            const Box<NDIM>& patch_box = patch->getBox();\n            const CellIndex<NDIM>& patch_lower = patch_box.lower();\n            const CellIndex<NDIM>& patch_upper = patch_box.upper();\n\n            const Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry();\n            const double* const patch_x_lower = patch_geom->getXLower();\n            const double* const patch_x_upper = patch_geom->getXUpper();\n\n            const double* const patch_dx = patch_geom->getDx();\n\n            const bool inside_patch = x_loc >= patch_x_lower[0] && x_loc <= patch_x_upper[0] &&\n                                      !(patch_x_upper[1] < y_loc_min || patch_x_lower[1] > y_loc_max);\n            if (!inside_patch) continue;\n\n            // Entire box containing the required data.\n            Box<NDIM> box(IndexUtilities::getCellIndex(\n                              &X_min[0], patch_x_lower, patch_x_upper, patch_dx, patch_lower, patch_upper),\n                          IndexUtilities::getCellIndex(\n                              &X_max[0], patch_x_lower, patch_x_upper, patch_dx, patch_lower, patch_upper));\n            // Part of the box on this patch\n            Box<NDIM> trim_box = patch_box * box;\n            BoxList<NDIM> iterate_box_list = trim_box;\n\n            // Trim the box covered by the finer region\n            BoxList<NDIM> covered_boxes;\n            if (ln < finest_ln)\n            {\n                BoxArray<NDIM> refined_region_boxes;\n                Pointer<PatchLevel<NDIM> > next_finer_level = patch_hierarchy->getPatchLevel(ln + 1);\n                refined_region_boxes = next_finer_level->getBoxes();\n                refined_region_boxes.coarsen(next_finer_level->getRatioToCoarserLevel());\n                for (int i = 0; i < refined_region_boxes.getNumberOfBoxes(); ++i)\n                {\n                    const Box<NDIM> refined_box = refined_region_boxes[i];\n                    const Box<NDIM> covered_box = trim_box * refined_box;\n                    covered_boxes.unionBoxes(covered_box);\n                }\n            }\n            iterate_box_list.removeIntersections(covered_boxes);\n\n            // Loop over the boxes and store the location and interpolated value.\n            Pointer<SideData<NDIM, double> > u_data = patch->getPatchData(u_idx);\n            for (BoxList<NDIM>::Iterator lit(iterate_box_list); lit; lit++)\n            {\n                const Box<NDIM>& iterate_box = *lit;\n                for (Box<NDIM>::Iterator bit(iterate_box); bit; bit++)\n                {\n                    const CellIndex<NDIM>& lower_idx = *bit;\n                    CellIndex<NDIM> upper_idx = lower_idx;\n                    upper_idx(0) += 1;\n                    const double y = patch_x_lower[1] + patch_dx[1] * (lower_idx(1) - patch_lower(1) + 0.5);\n                    const double x0 = patch_x_lower[0] + patch_dx[0] * (lower_idx(0) - patch_lower(0));\n                    const double x1 = x0 + patch_dx[0];\n                    const double u0 = (*u_data)(SideIndex<NDIM>(lower_idx, 0, SideIndex<NDIM>::Lower));\n                    const double u1 = (*u_data)(SideIndex<NDIM>(upper_idx, 0, SideIndex<NDIM>::Lower));\n                    pos_values.push_back(y);\n                    pos_values.push_back(u0 + (u1 - u0) * (x_loc - x0) / (x1 - x0));\n                }\n            }\n        }\n    }\n\n    const int nprocs = SAMRAI_MPI::getNodes();\n    const int rank = SAMRAI_MPI::getRank();\n    vector<int> data_size(nprocs, 0);\n    data_size[rank] = static_cast<int>(pos_values.size());\n    SAMRAI_MPI::sumReduction(&data_size[0], nprocs);\n    int offset = 0;\n    offset = std::accumulate(&data_size[0], &data_size[rank], offset);\n    int size_array = 0;\n    size_array = std::accumulate(&data_size[0], &data_size[0] + nprocs, size_array);\n\n    // Write out the result in a file.\n    string file_name = data_dump_dirname + \"/\" + \"u_y_\";\n    char temp_buf[128];\n    sprintf(temp_buf, \"%.8f\", data_time);\n    file_name += temp_buf;\n\n    MPI_Status status;\n    MPI_Offset mpi_offset;\n    MPI_File file;\n    MPI_File_open(MPI_COMM_WORLD, file_name.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &file);\n\n    // First write the total size of the array.\n    if (rank == 0)\n    {\n        mpi_offset = 0;\n        MPI_File_seek(file, mpi_offset, MPI_SEEK_SET);\n        MPI_File_write(file, &size_array, 1, MPI_INT, &status);\n    }\n\n    mpi_offset = sizeof(double) * offset + sizeof(int);\n    MPI_File_seek(file, mpi_offset, MPI_SEEK_SET);\n    MPI_File_write(file, &pos_values[0], data_size[rank], MPI_DOUBLE, &status);\n    MPI_File_close(&file);\n\n    return;\n} // compute_velocity_profile\n\nvoid\ncompute_pressure_profile(Pointer<PatchHierarchy<NDIM> > patch_hierarchy,\n                         const int p_idx,\n                         const double data_time,\n                         const string& data_dump_dirname)\n{\n    const int coarsest_ln = 0;\n    const int finest_ln = patch_hierarchy->getFinestLevelNumber();\n\n    const double X_min[2] = { x_loc, -0.5 * L };\n    const double X_max[2] = { x_loc, 0.5 * L };\n    vector<double> pos_values;\n    for (int ln = finest_ln; ln >= coarsest_ln; --ln)\n    {\n        Pointer<PatchLevel<NDIM> > level = patch_hierarchy->getPatchLevel(ln);\n        for (PatchLevel<NDIM>::Iterator p(level); p; p++)\n        {\n            Pointer<Patch<NDIM> > patch = level->getPatch(p());\n            const Box<NDIM>& patch_box = patch->getBox();\n            const CellIndex<NDIM>& patch_lower = patch_box.lower();\n            const CellIndex<NDIM>& patch_upper = patch_box.upper();\n\n            const Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry();\n            const double* const patch_x_lower = patch_geom->getXLower();\n            const double* const patch_x_upper = patch_geom->getXUpper();\n\n            const double* const patch_dx = patch_geom->getDx();\n\n            const bool inside_patch = x_loc >= patch_x_lower[0] && x_loc <= patch_x_upper[0] &&\n                                      !(patch_x_upper[1] < y_loc_min || patch_x_lower[1] > y_loc_max);\n            if (!inside_patch) continue;\n\n            // Entire box containing the required data.\n            Box<NDIM> box(IndexUtilities::getCellIndex(\n                              &X_min[0], patch_x_lower, patch_x_upper, patch_dx, patch_lower, patch_upper),\n                          IndexUtilities::getCellIndex(\n                              &X_max[0], patch_x_lower, patch_x_upper, patch_dx, patch_lower, patch_upper));\n            // Part of the box on this patch\n            Box<NDIM> trim_box = patch_box * box;\n            BoxList<NDIM> iterate_box_list = trim_box;\n\n            // Trim the box covered by the finer region\n            BoxList<NDIM> covered_boxes;\n            if (ln < finest_ln)\n            {\n                BoxArray<NDIM> refined_region_boxes;\n                Pointer<PatchLevel<NDIM> > next_finer_level = patch_hierarchy->getPatchLevel(ln + 1);\n                refined_region_boxes = next_finer_level->getBoxes();\n                refined_region_boxes.coarsen(next_finer_level->getRatioToCoarserLevel());\n                for (int i = 0; i < refined_region_boxes.getNumberOfBoxes(); ++i)\n                {\n                    const Box<NDIM> refined_box = refined_region_boxes[i];\n                    const Box<NDIM> covered_box = trim_box * refined_box;\n                    covered_boxes.unionBoxes(covered_box);\n                }\n            }\n            iterate_box_list.removeIntersections(covered_boxes);\n\n            // Loop over the boxes and store the location and interpolated value.\n\n            const Pointer<CellData<NDIM, double> > p_data = patch->getPatchData(p_idx);\n\n            for (BoxList<NDIM>::Iterator lit(iterate_box_list); lit; lit++)\n            {\n                const Box<NDIM>& iterate_box = *lit;\n                for (Box<NDIM>::Iterator bit(iterate_box); bit; bit++)\n                {\n                    const CellIndex<NDIM>& lower_idx = *bit;\n                    CellIndex<NDIM> upper_idx = lower_idx;\n                    upper_idx(0) += 1;\n\n                    const double y = patch_x_lower[1] + patch_dx[1] * (lower_idx(1) - patch_lower(1) + 0.5);\n                    const double x0 = patch_x_lower[0] + patch_dx[0] * (lower_idx(0) - patch_lower(0) + 0.5);\n\n                    const double x1 = x0 + patch_dx[0];\n                    const double p0 = (*p_data)(lower_idx);\n                    const double p1 = (*p_data)(upper_idx);\n                    pos_values.push_back(y);\n                    pos_values.push_back(p0 + (p1 - p0) * (x_loc - x0) / (x1 - x0));\n                }\n            }\n        }\n    }\n\n    const int nprocs = SAMRAI_MPI::getNodes();\n    const int rank = SAMRAI_MPI::getRank();\n    vector<int> data_size(nprocs, 0);\n    data_size[rank] = static_cast<int>(pos_values.size());\n    SAMRAI_MPI::sumReduction(&data_size[0], nprocs);\n    int offset = 0;\n    offset = std::accumulate(&data_size[0], &data_size[rank], offset);\n    int size_array = 0;\n    size_array = std::accumulate(&data_size[0], &data_size[0] + nprocs, size_array);\n\n    // Write out the result in a file.\n    string file_name = data_dump_dirname + \"/\" + \"p_\";\n    char temp_buf[128];\n    sprintf(temp_buf, \"%.8f\", data_time);\n    file_name += temp_buf;\n\n    MPI_Status status;\n    MPI_Offset mpi_offset;\n    MPI_File file;\n    MPI_File_open(MPI_COMM_WORLD, file_name.c_str(), MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &file);\n\n    // First write the total size of the array.\n    if (rank == 0)\n    {\n        mpi_offset = 0;\n        MPI_File_seek(file, mpi_offset, MPI_SEEK_SET);\n        MPI_File_write(file, &size_array, 1, MPI_INT, &status);\n    }\n\n    mpi_offset = sizeof(double) * offset + sizeof(int);\n    MPI_File_seek(file, mpi_offset, MPI_SEEK_SET);\n    MPI_File_write(file, &pos_values[0], data_size[rank], MPI_DOUBLE, &status);\n    MPI_File_close(&file);\n\n    return;\n} // compute_pressure_profile\n", "meta": {"hexsha": "c86abf51b29b3563445c8bb1dea877ee3cdf5cf3", "size": 57927, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/IIM/taylor_couette_2d.cpp", "max_stars_repo_name": "akashdhruv/IBAMR", "max_stars_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/IIM/taylor_couette_2d.cpp", "max_issues_repo_name": "akashdhruv/IBAMR", "max_issues_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T17:54:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-30T17:54:49.000Z", "max_forks_repo_path": "tests/IIM/taylor_couette_2d.cpp", "max_forks_repo_name": "akashdhruv/IBAMR", "max_forks_repo_head_hexsha": "a2b47946d795fb5a40c181b43e44a6ec387585a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-30T03:40:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-30T03:40:20.000Z", "avg_line_length": 47.2102689487, "max_line_length": 120, "alphanum_fraction": 0.5839073316, "num_tokens": 14114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.41292931065970173}}
{"text": "﻿#include \"camview.h\"\n#include \"gldrow.h\"\n#include \"workspace.h\"\n#include <QtMath>\n\n#include <Eigen/Geometry>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include \"MultipleViewTriangulation.h\"\n#include <iostream>\n#include \"easytool.h\"\n\nusing namespace Eigen;\n\nCamView::CamView(QWidget *parent) : QOpenGLWidget(parent),\n                                    m_model(0),\n                                    m_camera(20.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f),\n                                    m_program(0)\n{\n}\n\nCamView::~CamView()\n{\n    makeCurrent();\n\n    delete m_model;\n    delete m_program;\n\n    doneCurrent();\n}\n\nvoid CamView::initializeGL()\n{\n    initializeOpenGLFunctions();\n    m_program = new QOpenGLShaderProgram(this);\n    m_program->addShaderFromSourceFile(QOpenGLShader::Vertex, \":/shader/shader.vert\");\n    m_program->addShaderFromSourceFile(QOpenGLShader::Fragment, \":/shader/shader.frag\");\n    m_program->link();\n\n    // glEnable(GL_TEXTURE_2D);\n    // glShadeModel(GL_SMOOTH);\n    glClearColor(0.0, 0.0, 0.0, 0.0);\n    //glClearDepth(1.0);\n    glEnable(GL_DEPTH_TEST);\n    // glDepthFunc(GL_LEQUAL);\n    // glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);\n\n    cameraInit(80, 30, 6.0f);\n\n    QString applicationDirPath = QCoreApplication::applicationDirPath();\n    loadModel(applicationDirPath + \"/../resource/3d/f15/drone.obj\");\n}\n\nvoid CamView::loadModel(QString filename)\n{\n    makeCurrent();\n    if (m_model != 0)\n    {\n        delete m_model;\n    }\n    m_model = new Model(filename, this);\n    doneCurrent();\n}\n\nvoid CamView::updateGL()\n{\n}\n\n#define TRAN_SIZE 1000\nvoid CamView::paintGL()\n{\n\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n    glMatrixMode(GL_MODELVIEW);\n    glLoadIdentity();\n\n    gluLookAt(eye[0], eye[1], eye[2],\n              center[0], center[1], center[2],\n              up[0], up[1], up[2]);\n\n    if (cs_show_model == Qt::CheckState::Checked)\n    {\n        glPushMatrix();\n        QMatrix4x4 view; // = m_camera.view();\n        view.lookAt(\n            QVector3D(eye[0], eye[1], eye[2]),\n            QVector3D(center[0], center[1], center[2]),\n            QVector3D(up[0], up[1], up[2]));\n        QMatrix4x4 model;\n        if (size == 3)\n        {\n            view.translate(Xr[1](0, 0) / TRAN_SIZE, Xr[1](1, 0) / TRAN_SIZE, Xr[1](2, 0) / TRAN_SIZE);\n            view.rotate(-pos[0](0, 0) * ARC_TO_DEG, 1, 0, 0);\n            view.rotate(-pos[0](1, 0) * ARC_TO_DEG, 0, 1, 0);\n            view.rotate(-pos[0](2, 0) * ARC_TO_DEG, 0, 0, 1);\n        }\n\n        m_program->bind();\n        m_program->setUniformValue(\"view\", view);\n        m_program->setUniformValue(\"model\", m_modelMat);\n        m_program->setUniformValue(\"projection\", m_projectionMat);\n\n        if (m_model != 0)\n        {\n            m_model->draw(this);\n        }\n        m_program->release();\n        glPopMatrix();\n    }\n    /*网格*/\n    glPushMatrix();\n    GLDrow::DrowGrid();\n    glPopMatrix();\n\n    //坐标轴显示\n    if (cs_show_axis == Qt::CheckState::Checked)\n    {\n        glColor3f(1.0, 0.0, 0.0);\n        GLDrow::DrowArrow(0, 0, 0, 0.8, 0, 0, 0.006);\n        glColor3f(0.0, 1.0, 0.0);\n        GLDrow::DrowArrow(0, 0, 0, 0.0, 0.8, 0, 0.006);\n        glColor3f(0.0, 0.0, 1.0);\n        GLDrow::DrowArrow(0, 0, 0, 0, 0, 0.8, 0.006);\n    }\n\n    if (isClearTrajectoryList)\n    {\n        isClearTrajectoryList = false;\n        trajectoryList.clear();\n    }\n\n    for (int pm = 0; pm < size; pm++)\n    {\n        glPushMatrix();\n\n        glTranslatef(Xr[pm](0, 0) / TRAN_SIZE, Xr[pm](1, 0) / TRAN_SIZE, Xr[pm](2, 0) / TRAN_SIZE);\n        if (pm == 1 && size == 3)\n            trajectoryList.append(Vector3d(Xr[pm](0, 0) / TRAN_SIZE, Xr[pm](1, 0) / TRAN_SIZE, Xr[pm](2, 0) / TRAN_SIZE));\n        glColor3f(1.0, 0.0, 0.0);\n        GLDrow::drawSphere();\n        glPopMatrix();\n    }\n\n    if (cs_show_cam == Qt::CheckState::Checked)\n        for (int i = 0; i < vision_param.CamNum; i++)\n        {\n            /*相机*/\n            glPushMatrix();\n            Matrix33d RR = vision_param.RGND;//.transpose();\n            Vector3d  TT = -vision_param.TGND;\n            vision_param.RTGND = EasyTool::getRT44d(RR,TT);\n            Matrix44d R_T = EasyTool::getRT44d(vision_param.R[i], vision_param.T[i]);\n            //R_T = R_T.inverse();\n            //vision_param.RTGND = vision_param.RTGND.inverse();\n\n            //R_T = R_T * vision_param.RTGND;\n            R_T = vision_param.RTGND * R_T;\n            //R_T = R_T.inverse();\n\n            Matrix33d R_;\n            Vector3d T_;\n            EasyTool::RT44d(R_T, R_, T_);\n\n            Vector3d v = R_.eulerAngles(0, 1, 2);\n\n            glRotatef(v(0, 0) * ARC_TO_DEG, 1, 0, 0);\n            glRotatef(v(1, 0) * ARC_TO_DEG, 0, 1, 0);\n            glRotatef(v(2, 0) * ARC_TO_DEG, 0, 0, 1);\n\n            glTranslatef(\n                T_(0, 0) / TRAN_SIZE,\n                T_(1, 0) / TRAN_SIZE,\n                T_(2, 0) / TRAN_SIZE);\n\n            // glBegin(GL_LINES);\n            // glColor3f(0.0, 0.0, 1.0);\n            // glVertex3f(0.0, 0.0, 0.0);\n            // glVertex3f(0.0, 0.0, 10.0);\n            // glEnd();\n\n            GLDrow::DrowCam();\n            glPopMatrix();\n        }\n\n    if (cs_show_trajectory == Qt::CheckState::Checked)\n    {\n        glColor3f(1.0, 0.0, 0.0);\n        for (int i = 0; i < trajectoryList.size(); i++)\n        {\n            glBegin(GL_POINTS);\n            glVertex3f(trajectoryList.at(i)[0], trajectoryList.at(i)[1], trajectoryList.at(i)[2]);\n            glEnd();\n        }\n    }\n\n    //Plan\n    if (cs_show_plan == Qt::CheckState::Checked)\n        if (ppList.size() >= 2)\n        {\n            for (int i = 0; i < ppList.size() - 1; i++)\n            {\n                if (ppList.at(i + 1)->state == PLAN_POINT_STATE_WAIT)\n                    glColor3f(1.0, 1.0, 0.0);\n                else if (ppList.at(i + 1)->state == PLAN_POINT_STATE_GOING)\n                    glColor3f(0.0, 1.0, 1.0);\n                else if (ppList.at(i + 1)->state == PLAN_POINT_STATE_ARRIVE)\n                    glColor3f(1.0, 0.0, 1.0);\n\n                GLDrow::DrowArrow(\n                    ppList.at(i)->mpd->x, ppList.at(i)->mpd->y, ppList.at(i)->mpd->z,\n                    ppList.at(i + 1)->mpd->x, ppList.at(i + 1)->mpd->y, ppList.at(i + 1)->mpd->z,\n                    0.003);\n            }\n        }\n\n    QMetaObject::invokeMethod(this, \"update\", Qt::QueuedConnection);\n    view_fps_1s++;\n}\n\nvoid CamView::resizeGL(int w, int h)\n{\n    glViewport(0, 0, w, h);\n    glMatrixMode(GL_PROJECTION);\n    glLoadIdentity();\n    gluPerspective(45.0f, w / float(h), 1.0f, 1000.0f);\n\n    cameraTurn(yawCam, pitchCam, farCam);\n\n    m_projectionMat.setToIdentity();\n    m_projectionMat.perspective(45.0f, w / float(h), 1.0f, 1000.0f);\n\n    //DBG(\"resizeGL\");\n}\n\nvoid CamView::setAngle(float rol, float pit, float yaw)\n{\n    this->rol = rol;\n    this->pit = pit;\n    this->yaw = yaw;\n}\n\nvoid CamView::setPlan(QList<PlanPoint *> list)\n{\n    ppList = list;\n}\n\nvoid CamView::setPosition(Vector3d *Xr, int size, Vector3d *pos)\n{\n    // this->px = x;\n    // this->py = y;\n    // this->pz = z;\n    this->Xr = Xr;\n    this->size = size;\n    this->pos = pos;\n    point_fps_1s++;\n}\n\nvoid CamView::cameraInit(double yaw, double pitch, double R_long)\n{\n\n    yawCam = yaw;\n    pitchCam = pitch;\n    farCam = R_long;\n}\n\nvoid CamView::cameraTurn(double yaw, double pitch, double R_long)\n{\n\n    // if (pitch > 90)\n    //     pitch = 90;\n    // else if (pitch < -90)\n    //     pitch = -90;\n\n    double angle_yaw = yaw * M_PI / 180;\n    double angle_pitch = pitch * M_PI / 180;\n\n    Vector3d v(0, 1, 0);       //{ { 0 }, { 1 }, { 0 } };\n    Vector3d v_top(0, 0, 1);   // { { 0 }, { 0 }, { 1 } };\n    Vector3d yaw_k(0, 0, 1);   // { { 0 }, { 0 }, { 1 } };\n    Vector3d pitch_k(1, 0, 0); // { { 1 }, { 0 }, { 0 } };\n\n    Matrix3d E;\n    E << 1, 0, 0,\n        0, 1, 0,\n        0, 0, 1;\n\n    Matrix3d G_yaw;\n    G_yaw << 0, -yaw_k[2], yaw_k[1],\n        yaw_k[2], 0, -yaw_k[0],\n        -yaw_k[1], yaw_k[0], 0;\n\n    v = E * qCos(angle_yaw) * v + (1 - qCos(angle_yaw)) * yaw_k * yaw_k.transpose() * v + qSin(angle_yaw) * G_yaw * v;\n    pitch_k = E * qCos(angle_yaw) * pitch_k + (1 - qCos(angle_yaw)) * yaw_k * yaw_k.transpose() * pitch_k + qSin(angle_yaw) * G_yaw * pitch_k;\n\n    Matrix3d G_pitch;\n    G_pitch << 0, -pitch_k[2], pitch_k[1],\n        pitch_k[2], 0, -pitch_k[0],\n        -pitch_k[1], pitch_k[0], 0;\n\n    v = E * qCos(angle_pitch) * v + (1 - qCos(angle_pitch)) * pitch_k * pitch_k.transpose() * v + qSin(angle_pitch) * G_pitch * v;\n    v = v * R_long;\n\n    pitch_k << 1, 0, 0;\n\n    v_top = E * qCos(angle_yaw) * v_top + (1 - qCos(angle_yaw)) * yaw_k * yaw_k.transpose() * v_top + qSin(angle_yaw) * G_yaw * v_top;\n    pitch_k = E * qCos(angle_yaw) * pitch_k + (1 - qCos(angle_yaw)) * yaw_k * yaw_k.transpose() * pitch_k + qSin(angle_yaw) * G_yaw * pitch_k;\n\n    G_pitch << 0, -pitch_k[2], pitch_k[1],\n        pitch_k[2], 0, -pitch_k[0],\n        -pitch_k[1], pitch_k[0], 0;\n\n    v_top = E * qCos(angle_pitch) * v_top + (1 - qCos(angle_pitch)) * pitch_k * pitch_k.transpose() * v_top + qSin(angle_pitch) * G_pitch * v_top;\n\n    eye[0] = v[0];\n    eye[1] = v[1];\n    eye[2] = v[2];\n    center[0] = 0;\n    center[1] = 0;\n    center[2] = 0;\n    up[0] = v_top[0];\n    up[1] = v_top[1];\n    up[2] = v_top[2];\n\n    //DBG(\"yawCam:%0.2f\\tpitchCam:%0.2f\\tfarCam:%0.2f\\t\",yaw,pitch,R_long);\n}\n\nvoid CamView::mousePressEvent(QMouseEvent *event)\n{\n    if (event->buttons() == Qt::LeftButton)\n    { //如果鼠标按下的是左键\n        clickX = event->globalX();\n        clickY = event->globalY();\n        //DBG(\"LeftButton %d %d\",event->globalX(),event->globalY());\n    }\n    else if (event->buttons() == Qt::RightButton)\n    { //如果鼠标按下的是右键\n        //DBG(\"RightButton %d %d\",event->globalX(),event->globalY());\n    }\n}\n\nvoid CamView::mouseMoveEvent(QMouseEvent *event)\n{\n    if (event->buttons() == Qt::LeftButton)\n    { //如果鼠标按下的是左键\n        //DBG(\"mouseMoveEvent %d %d\",event->globalX(),event->globalY());\n\n        if (clickX != event->globalX())\n        {\n            yawCam += (clickX - event->globalX()) * 1.0;\n            clickX = event->globalX();\n        }\n\n        if (clickY != event->globalY())\n        {\n            pitchCam -= (clickY - event->globalY()) * 1.0;\n            clickY = event->globalY();\n        }\n\n        cameraTurn(yawCam, pitchCam, farCam);\n    }\n}\n\nvoid CamView::mouseReleaseEvent(QMouseEvent *event)\n{\n}\n\nvoid CamView::mouseDoubleClickEvent(QMouseEvent *event)\n{\n}\n\nvoid CamView::wheelEvent(QWheelEvent *event)\n{\n\n    //DBG(\"wheelEvent %d\",event->delta());\n\n    if (event->delta() > 0)\n    {\n        farCam -= 0.1 * 3;\n    }\n    else\n    {\n        farCam += 0.1 * 3;\n    }\n\n    cameraTurn(yawCam, pitchCam, farCam);\n}\n", "meta": {"hexsha": "c48f527bd71286ec7f10cdb2519ca1bfb2f70905", "size": 10659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/drow/camview.cpp", "max_stars_repo_name": "mfkiwl/GLMocap", "max_stars_repo_head_hexsha": "72de3cc11256d0d8567e86b8a2487ffc81fc984e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-10-30T03:33:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-30T05:01:30.000Z", "max_issues_repo_path": "src/drow/camview.cpp", "max_issues_repo_name": "mfkiwl/GLMocap", "max_issues_repo_head_hexsha": "72de3cc11256d0d8567e86b8a2487ffc81fc984e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/drow/camview.cpp", "max_forks_repo_name": "mfkiwl/GLMocap", "max_forks_repo_head_hexsha": "72de3cc11256d0d8567e86b8a2487ffc81fc984e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5426356589, "max_line_length": 146, "alphanum_fraction": 0.5347593583, "num_tokens": 3543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4129293106597016}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_FUN_GAMMA_P_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_GAMMA_P_HPP\n\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/fun/is_nan.hpp>\n#include <stan/math/prim/err.hpp>\n#include <stan/math/prim/scal/fun/boost_policy.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Return the value of the normalized, lower-incomplete gamma function\n * applied to the specified argument.\n *\n * <p>This function is defined, including error conditions, as follows\n   \\f[\n   \\mbox{gamma\\_p}(a, z) =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } a\\leq 0 \\textrm{ or } z < 0\\\\\n     P(a, z) & \\mbox{if } a > 0, z \\geq 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } a = \\textrm{NaN or } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{gamma\\_p}(a, z)}{\\partial a} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } a\\leq 0 \\textrm{ or } z < 0\\\\\n     \\frac{\\partial\\, P(a, z)}{\\partial a} & \\mbox{if } a > 0, z \\geq 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } a = \\textrm{NaN or } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   \\frac{\\partial\\, \\mbox{gamma\\_p}(a, z)}{\\partial z} =\n   \\begin{cases}\n     \\textrm{error} & \\mbox{if } a\\leq 0 \\textrm{ or } z < 0\\\\\n     \\frac{\\partial\\, P(a, z)}{\\partial z} & \\mbox{if } a > 0, z \\geq 0 \\\\[6pt]\n     \\textrm{NaN} & \\mbox{if } a = \\textrm{NaN or } z = \\textrm{NaN}\n   \\end{cases}\n   \\f]\n\n   \\f[\n   P(a, z)=\\frac{1}{\\Gamma(a)}\\int_0^zt^{a-1}e^{-t}dt\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, P(a, z)}{\\partial a} =\n -\\frac{\\Psi(a)}{\\Gamma^2(a)}\\int_0^zt^{a-1}e^{-t}dt\n   + \\frac{1}{\\Gamma(a)}\\int_0^z (a-1)t^{a-2}e^{-t}dt\n   \\f]\n\n   \\f[\n   \\frac{\\partial \\, P(a, z)}{\\partial z} = \\frac{z^{a-1}e^{-z}}{\\Gamma(a)}\n   \\f]\n   *\n   * @param z first argument\n   * @param a second argument\n   * @return value of the normalized, lower-incomplete gamma function\n   * applied to z and a\n   * @throws std::domain_error if either argument is not positive or\n   * if z is at a pole of the function\n */\ninline double gamma_p(double z, double a) {\n  if (is_nan(z)) {\n    return not_a_number();\n  }\n  if (is_nan(a)) {\n    return not_a_number();\n  }\n  check_positive(\"gamma_p\", \"first argument (z)\", z);\n  check_nonnegative(\"gamma_p\", \"second argument (a)\", a);\n  return boost::math::gamma_p(z, a, boost_policy_t());\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "9cfc1b36ccc0a34f4bbb3236f489fa92c7a34db7", "size": 2389, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/fun/gamma_p.hpp", "max_stars_repo_name": "christophernhill/math", "max_stars_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/scal/fun/gamma_p.hpp", "max_issues_repo_name": "christophernhill/math", "max_issues_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/scal/fun/gamma_p.hpp", "max_forks_repo_name": "christophernhill/math", "max_forks_repo_head_hexsha": "dc41aba296d592c7099be15eed6ba136d0f140b3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4938271605, "max_line_length": 79, "alphanum_fraction": 0.5985768104, "num_tokens": 915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.41290897217811545}}
{"text": "// Created by Zhiliang Zhou on 2020\n// this is a simplified version of spconv\n//\n// original spconv was implemented by Yan Yan, https://github.com/traveller59/spconv\n// -------------------------------------------------------------------\n// Copyright 2019 Yan Yan\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n#include \"spconv_utils/box_iou.h\"\n#include <boost/geometry.hpp>\n\nnamespace spconv{\n\n\ntemplate <typename DType>\npy::array_t<DType>\nrbbox_iou(py::array_t<DType> box_corners,\n          py::array_t<DType> qbox_corners,\n          py::array_t<DType> standup_iou,\n          DType standup_thresh) {\n\n    namespace bg = boost::geometry;\n    typedef bg::model::point<DType, 2, bg::cs::cartesian> point_t;\n    typedef bg::model::polygon<point_t> polygon_t;\n    polygon_t poly, qpoly;\n    std::vector<polygon_t> poly_inter, poly_union;\n    DType inter_area, union_area;\n    auto box_corners_r = box_corners.template unchecked<3>();\n    auto qbox_corners_r = qbox_corners.template unchecked<3>();\n    auto standup_iou_r = standup_iou.template unchecked<2>();\n    auto N = box_corners_r.shape(0);\n    auto K = qbox_corners_r.shape(0);\n    py::array_t<DType> overlaps = zeros<DType>({int(N), int(K)});\n    auto overlaps_rw = overlaps.template mutable_unchecked<2>();\n    if (N == 0 || K == 0) {\n        return overlaps;\n    }\n    for (int k = 0; k < K; ++k) {\n        for (int n = 0; n < N; ++n) {\n            if (standup_iou_r(n, k) <= standup_thresh)\n                continue;\n            bg::append(poly, point_t(box_corners_r(n, 0, 0), box_corners_r(n, 0, 1)));\n            bg::append(poly, point_t(box_corners_r(n, 1, 0), box_corners_r(n, 1, 1)));\n            bg::append(poly, point_t(box_corners_r(n, 2, 0), box_corners_r(n, 2, 1)));\n            bg::append(poly, point_t(box_corners_r(n, 3, 0), box_corners_r(n, 3, 1)));\n            bg::append(poly, point_t(box_corners_r(n, 0, 0), box_corners_r(n, 0, 1)));\n            bg::append(qpoly,\n                       point_t(qbox_corners_r(k, 0, 0), qbox_corners_r(k, 0, 1)));\n            bg::append(qpoly,\n                       point_t(qbox_corners_r(k, 1, 0), qbox_corners_r(k, 1, 1)));\n            bg::append(qpoly,\n                       point_t(qbox_corners_r(k, 2, 0), qbox_corners_r(k, 2, 1)));\n            bg::append(qpoly,\n                       point_t(qbox_corners_r(k, 3, 0), qbox_corners_r(k, 3, 1)));\n            bg::append(qpoly,\n                       point_t(qbox_corners_r(k, 0, 0), qbox_corners_r(k, 0, 1)));\n\n            bg::intersection(poly, qpoly, poly_inter);\n\n            if (!poly_inter.empty()) {\n                inter_area = bg::area(poly_inter.front());\n                bg::union_(poly, qpoly, poly_union);\n                if (!poly_union.empty()) {\n                    union_area = bg::area(poly_union.front());\n                    overlaps_rw(n, k) = inter_area / union_area;\n                }\n                poly_union.clear();\n            }\n            poly.clear();\n            qpoly.clear();\n            poly_inter.clear();\n        }\n    }\n    return overlaps;\n}\n\n\ntemplate <typename DType>\npy::array_t<DType> rbbox_intersection(py::array_t<DType> box_corners,\n                                      py::array_t<DType> qbox_corners,\n                                      py::array_t<DType> standup_iou,\n                                      DType standup_thresh) {\n    namespace bg = boost::geometry;\n    typedef bg::model::point<DType, 2, bg::cs::cartesian> point_t;\n    typedef bg::model::polygon<point_t> polygon_t;\n    polygon_t poly, qpoly;\n    std::vector<polygon_t> poly_inter, poly_union;\n    DType inter_area, union_area;\n    auto box_corners_r = box_corners.template unchecked<3>();\n    auto qbox_corners_r = qbox_corners.template unchecked<3>();\n    auto standup_iou_r = standup_iou.template unchecked<2>();\n    auto N = box_corners_r.shape(0);\n    auto K = qbox_corners_r.shape(0);\n    py::array_t<DType> overlaps = zeros<DType>({int(N), int(K)});\n    auto overlaps_rw = overlaps.template mutable_unchecked<2>();\n    if (N == 0 || K == 0) {\n        return overlaps;\n    }\n    for (int k = 0; k < K; ++k) {\n        for (int n = 0; n < N; ++n) {\n            if (standup_iou_r(n, k) <= standup_thresh)\n                continue;\n            bg::append(poly, point_t(box_corners_r(n, 0, 0), box_corners_r(n, 0, 1)));\n            bg::append(poly, point_t(box_corners_r(n, 1, 0), box_corners_r(n, 1, 1)));\n            bg::append(poly, point_t(box_corners_r(n, 2, 0), box_corners_r(n, 2, 1)));\n            bg::append(poly, point_t(box_corners_r(n, 3, 0), box_corners_r(n, 3, 1)));\n            bg::append(poly, point_t(box_corners_r(n, 0, 0), box_corners_r(n, 0, 1)));\n            bg::append(qpoly,\n                       point_t(qbox_corners_r(k, 0, 0), qbox_corners_r(k, 0, 1)));\n            bg::append(qpoly,\n                       point_t(qbox_corners_r(k, 1, 0), qbox_corners_r(k, 1, 1)));\n            bg::append(qpoly,\n                       point_t(qbox_corners_r(k, 2, 0), qbox_corners_r(k, 2, 1)));\n            bg::append(qpoly,\n                       point_t(qbox_corners_r(k, 3, 0), qbox_corners_r(k, 3, 1)));\n            bg::append(qpoly,\n                       point_t(qbox_corners_r(k, 0, 0), qbox_corners_r(k, 0, 1)));\n\n            bg::intersection(poly, qpoly, poly_inter);\n\n            if (!poly_inter.empty()) {\n                inter_area = bg::area(poly_inter.front());\n                overlaps_rw(n, k) = inter_area;\n            }\n            poly.clear();\n            qpoly.clear();\n            poly_inter.clear();\n        }\n    }\n    return overlaps;\n}\n\n// Explicitly instantiate templates\ntemplate py::array_t<double> rbbox_iou<double>(\n        py::array_t<double> box_corners,\n        py::array_t<double> qbox_corners,\n        py::array_t<double> standup_iou,\n        double standup_thresh);\n\ntemplate py::array_t<float> rbbox_iou<float>(\n        py::array_t<float> box_corners,\n        py::array_t<float> qbox_corners,\n        py::array_t<float> standup_iou,\n        float standup_thresh);\n\ntemplate py::array_t<double> rbbox_intersection<double>(\n        py::array_t<double> box_corners,\n        py::array_t<double> qbox_corners,\n        py::array_t<double> standup_iou,\n        double standup_thresh);\n\ntemplate py::array_t<float> rbbox_intersection<float>(\n        py::array_t<float> box_corners,\n        py::array_t<float> qbox_corners,\n        py::array_t<float> standup_iou,\n        float standup_thresh);\n\n}  // namespace spconv", "meta": {"hexsha": "89001701d8e5026c110191b03b34d22c9fb3c425", "size": 6955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/spconv_utils/src/box_iou.cpp", "max_stars_repo_name": "masszhou/spconv_lite", "max_stars_repo_head_hexsha": "16f59cd99a9c360d0cfd47d9f5c1db8033ea3b07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-01-21T15:23:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T13:45:29.000Z", "max_issues_repo_path": "components/spconv_utils/src/box_iou.cpp", "max_issues_repo_name": "masszhou/spconv_lite", "max_issues_repo_head_hexsha": "16f59cd99a9c360d0cfd47d9f5c1db8033ea3b07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-12T03:48:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T03:48:47.000Z", "max_forks_repo_path": "components/spconv_utils/src/box_iou.cpp", "max_forks_repo_name": "masszhou/spconv_lite", "max_forks_repo_head_hexsha": "16f59cd99a9c360d0cfd47d9f5c1db8033ea3b07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-01-23T03:03:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T13:57:27.000Z", "avg_line_length": 41.3988095238, "max_line_length": 86, "alphanum_fraction": 0.583465133, "num_tokens": 1852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.41290897217811545}}
{"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_CHOLESKY_LPDF_HPP\n#define STAN_MATH_PRIM_MAT_PROB_MULTI_NORMAL_CHOLESKY_LPDF_HPP\n\n#include <stan/math/prim/mat/fun/columns_dot_product.hpp>\n#include <stan/math/prim/mat/fun/columns_dot_self.hpp>\n#include <stan/math/prim/mat/fun/dot_product.hpp>\n#include <stan/math/prim/mat/fun/dot_self.hpp>\n#include <stan/math/prim/mat/fun/log.hpp>\n#include <stan/math/prim/mat/fun/log_determinant.hpp>\n#include <stan/math/prim/mat/fun/mdivide_left_spd.hpp>\n#include <stan/math/prim/mat/fun/mdivide_left_tri_low.hpp>\n#include <stan/math/prim/mat/fun/multiply.hpp>\n#include <stan/math/prim/mat/fun/subtract.hpp>\n#include <stan/math/prim/mat/fun/sum.hpp>\n#include <stan/math/prim/mat/meta/vector_seq_view.hpp>\n#include <stan/math/prim/scal/err/check_size_match.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/max_size_mvt.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/meta/return_type.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\n  namespace math {\n    /**\n     * The log of the multivariate normal density for the given y, mu, and\n     * a Cholesky factor L of the variance matrix.\n     * Sigma = LL', a square, semi-positive definite matrix.\n     *\n     *\n     * @param y A scalar vector\n     * @param mu The mean vector of the multivariate normal distribution.\n     * @param L The Cholesky decomposition of a variance matrix\n     * of the multivariate normal distribution\n     * @return The log of the multivariate normal density.\n     * @throw std::domain_error if LL' is not square, not symmetric,\n     * or not semi-positive definite.\n     * @tparam T_y Type of scalar.\n     * @tparam T_loc Type of location.\n     * @tparam T_covar Type of scale.\n     */\n    template <bool propto,\n              typename T_y, typename T_loc, typename T_covar>\n    typename return_type<T_y, T_loc, T_covar>::type\n    multi_normal_cholesky_lpdf(const T_y& y,\n                              const T_loc& mu,\n                              const T_covar& L) {\n      static const char* function(\"multi_normal_cholesky_lpdf\");\n      typedef typename scalar_type<T_covar>::type T_covar_elem;\n      typedef typename return_type<T_y, T_loc, T_covar>::type lp_type;\n      lp_type lp(0.0);\n\n\n      vector_seq_view<T_y> y_vec(y);\n      vector_seq_view<T_loc> mu_vec(mu);\n      size_t size_vec = max_size_mvt(y, mu);\n\n      int size_y = y_vec[0].size();\n      int size_mu = mu_vec[0].size();\n      if (size_vec > 1) {\n        int size_y_old = size_y;\n        int size_y_new;\n        for (size_t i = 1, size_ = length_mvt(y); i < size_; i++) {\n          int size_y_new = y_vec[i].size();\n          check_size_match(function,\n                           \"Size of one of the vectors of \"\n                           \"the random variable\", size_y_new,\n                           \"Size of another vector of the \"\n                           \"random variable\", size_y_old);\n          size_y_old = size_y_new;\n        }\n        int size_mu_old = size_mu;\n        int size_mu_new;\n        for (size_t i = 1, size_ = length_mvt(mu); i < size_; i++) {\n          int size_mu_new = mu_vec[i].size();\n          check_size_match(function,\n                           \"Size of one of the vectors of \"\n                           \"the location variable\", size_mu_new,\n                           \"Size of another vector of the \"\n                           \"location variable\", size_mu_old);\n          size_mu_old = size_mu_new;\n        }\n        (void) size_y_old;\n        (void) size_y_new;\n        (void) size_mu_old;\n        (void) size_mu_new;\n      }\n\n      check_size_match(function,\n                       \"Size of random variable\", size_y,\n                       \"size of location parameter\", size_mu);\n      check_size_match(function,\n                       \"Size of random variable\", size_y,\n                       \"rows of covariance parameter\", L.rows());\n      check_size_match(function,\n                       \"Size of random variable\", size_y,\n                       \"columns of covariance parameter\", L.cols());\n\n      for (size_t i = 0; i < size_vec; i++) {\n        check_finite(function, \"Location parameter\", mu_vec[i]);\n        check_not_nan(function, \"Random variable\", y_vec[i]);\n      }\n\n      if (size_y == 0)\n        return lp;\n\n      if (include_summand<propto>::value)\n        lp += NEG_LOG_SQRT_TWO_PI * size_y * size_vec;\n\n      if (include_summand<propto, T_covar_elem>::value)\n        lp -= L.diagonal().array().log().sum() * size_vec;\n\n      if (include_summand<propto, T_y, T_loc, T_covar_elem>::value) {\n        lp_type sum_lp_vec(0.0);\n        for (size_t i = 0; i < size_vec; i++) {\n          Eigen::Matrix<typename return_type<T_y, T_loc>::type,\n                        Eigen::Dynamic, 1> y_minus_mu(size_y);\n          for (int j = 0; j < size_y; j++)\n            y_minus_mu(j) = y_vec[i](j)-mu_vec[i](j);\n          Eigen::Matrix<typename return_type<T_y, T_loc, T_covar>::type,\n                        Eigen::Dynamic, 1>\n            half(mdivide_left_tri_low(L, y_minus_mu));\n          // FIXME: this code does not compile. revert after fixing subtract()\n          // Eigen::Matrix<typename\n          //               boost::math::tools::promote_args<T_covar,\n          //                 typename value_type<T_loc>::type,\n          //                 typename value_type<T_y>::type>::type>::type,\n          //               Eigen::Dynamic, 1>\n          //   half(mdivide_left_tri_low(L, subtract(y, mu)));\n          sum_lp_vec += dot_self(half);\n        }\n        lp -= 0.5*sum_lp_vec;\n      }\n      return lp;\n    }\n\n    template <typename T_y, typename T_loc, typename T_covar>\n    inline\n    typename return_type<T_y, T_loc, T_covar>::type\n    multi_normal_cholesky_lpdf(const T_y& y, const T_loc& mu,\n                               const T_covar& L) {\n      return multi_normal_cholesky_lpdf<false>(y, mu, L);\n    }\n\n  }\n}\n#endif\n", "meta": {"hexsha": "983c1140d8ac83fd7561830088d1714369fd7f8d", "size": 6117, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/multi_normal_cholesky_lpdf.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/multi_normal_cholesky_lpdf.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/multi_normal_cholesky_lpdf.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5099337748, "max_line_length": 78, "alphanum_fraction": 0.6045447115, "num_tokens": 1520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4129089721781154}}
{"text": "#pragma once\n#include <boost/range/adaptor/reversed.hpp>\n\n#include \"applications/heat_equation.hpp\"\n#include \"datastructures/double_tree_view.hpp\"\n#include \"spacetime/linear_form.hpp\"\n\nnamespace applications {\nnamespace ErrorEstimator {\nusing datastructures::DoubleTreeVector;\nusing space::HierarchicalBasisFn;\nusing spacetime::LinearFormBase;\nusing Time::ThreePointWaveletFn;\n\nstruct GlobalError {\n  double error;         // e_\\delta\n  double error_Yprime;  // \\eqsim ||g - Bu||_{Y'}\n  double error_t0;      // ||\\gamma_0u - u0||_L2\n};\n\nGlobalError ComputeGlobalError(const Eigen::VectorXd &g_min_Bu,\n                               const Eigen::VectorXd &PY_g_min_Bu,\n                               const Eigen::VectorXd &G_u_dd_dd,\n                               const Eigen::VectorXd &u0, HeatEquation &heat,\n                               const Eigen::VectorXd &u_dd_dd,\n                               LinearFormBase<ThreePointWaveletFn> &u0_lf);\n\n// Computes \\|u_t - \\gamma_t u_delta\\|_{L_2(\\Omega)} using interpolation on u_t.\ndouble ComputeTraceError(\n    double t, std::function<double(double, double)> u_t,\n    DoubleTreeVector<ThreePointWaveletFn, HierarchicalBasisFn> *u_delta);\n\ndouble ComputeLocalErrors(\n    DoubleTreeVector<ThreePointWaveletFn, HierarchicalBasisFn> *residual_dd_dd,\n    bool mean_zero = true);\n}  // namespace ErrorEstimator\n}  // namespace applications\n", "meta": {"hexsha": "a784dd242622d27c88c9938354813214a511df5a", "size": 1386, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/applications/error_estimator.hpp", "max_stars_repo_name": "rvanvenetie/spacetime", "max_stars_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/applications/error_estimator.hpp", "max_issues_repo_name": "rvanvenetie/spacetime", "max_issues_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/applications/error_estimator.hpp", "max_forks_repo_name": "rvanvenetie/spacetime", "max_forks_repo_head_hexsha": "b516419be2a59115d9b2d853aeea9fcd4f125c94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4736842105, "max_line_length": 80, "alphanum_fraction": 0.6832611833, "num_tokens": 337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.4128527426408086}}
{"text": "#include <algorithm>\n#include <boost/bind.hpp>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <gazebo/gazebo.hh>\n#include <gazebo/common/Plugin.hh>\n#include <gazebo/physics/physics.hh>\n#include <gazebo/common/common.hh>\n#include <iostream>\n#include <vector>\n\n#define L 0.04 // distance between body center and wheel center\n#define r 0.01905 // wheel radius\n\n#define pi30 0.1047197551196597705355242034774843062905347323976457118988037109375 // long double thirty = 30; long double mOne = -1; printf(\"%1.70Lf\\n\", (long double) acos(mOne) / thirty);\n#define pi12 1.5707963267948965579989817342720925807952880859375 // long double two = 2; long double mOne = -1; printf(\"%1.70Lf\\n\", (long double) acos(mOne) / two);\n#define pi 3.141592653589793115997963468544185161590576171875 // long double mOne = -1; printf(\"%1.70Lf\\n\", (long double) acos(mOne));\n#define pi2 6.28318530717958623199592693708837032318115234375 // long double two = 2; long double mOne = -1; printf(\"%1.70Lf\\n\", (long double) two * acos(mOne));\n#define sqrt3 1.732050807568877193176604123436845839023590087890625 // long double three = 3; printf(\"%1.70Lf\\n\", (long double) sqrt(three));\n#define sqrt32 0.8660254037844385965883020617184229195117950439453125 // long double two = 2; long double three = 3; printf(\"%1.70Lf\\n\", (sqrt(three) / two));\n#define Vmax 1.0 // set by experiments (m/s)\n#define omegamax 50.0 // set by experiments (rad/s)\n#define P 5.0 // PID\n#define I 0.0005 // PID\n#define stopDistance 0.001\n#define stopAngle pi30\n\ndouble Vx;\ndouble Vy;\ndouble Vxm;\ndouble Vym;\ndouble Vxw;\ndouble Vyw;\ndouble VxAbs;\ndouble VyAbs;\ndouble VxmTarget;\ndouble VymTarget;\ndouble VxwTarget;\ndouble VywTarget;\ndouble omegap;\ndouble Vback;\ndouble Vleft;\ndouble Vright;\ndouble VbackTarget;\ndouble VleftTarget;\ndouble VrightTarget;\ndouble omegapL;\ndouble omegapLVxm2;\ndouble sqrtVym2;\ndouble Vxm2;\ndouble Vback3;\ndouble Vleft3;\ndouble Vright3;\ndouble VxTarget;\ndouble VyTarget;\ndouble omegapTarget;\ndouble x = 0;\ndouble y = 0;\ndouble xm = 0;\ndouble ym = 0;\ndouble xOffset = 0;\ndouble yOffset = 0;\ndouble xTarget = 0;\ndouble yTarget = 0;\ndouble xw = 0;\ndouble yw = 0;\ndouble xError;\ndouble yError;\ndouble xErrorI;\ndouble yErrorI;\ndouble theta = 0;\ndouble thetaError;\ndouble thetaErrorI;\ndouble thetaOffset = 0;\ndouble thetaTarget = 0;\ndouble timeElapsed = 0;\ndouble timeLast;\ndouble timeNow = 0;\ndouble backAngleElapsed;\ndouble backAngleLast;\ndouble backAngleNow = 0;\ndouble leftAngleElapsed;\ndouble leftAngleLast;\ndouble leftAngleNow = 0;\ndouble rightAngleElapsed;\ndouble rightAngleLast;\ndouble rightAngleNow = 0;\ndouble phi;\ndouble Vlow;\ndouble Vhigh;\ndouble scale;\n\nclass Point {\n\n    public: double x;\n\n    public: double y;\n\n    private: static double w;\n\n    public: void offset(double x, double y) {\n        this->x += x;\n        this->y += y;\n    }\n\n    public: void rotate(double theta) {\n              w = (std::cos(theta) * this->y) + (std::sin(theta) * this->x);\n        this->x = (std::cos(theta) * this->x) - (std::sin(theta) * this->y);\n        this->y = w;\n    }\n\n    public: Point() {}\n\n    public: Point(const Point& p) {\n        x = p.x;\n        y = p.y;\n    }\n\n    public: Point(double x, double y) {\n        this->x = x;\n        this->y = y;\n    }\n\n    public: Point(Point p, double xOffset, double yOffset) {\n        x = p.x + xOffset;\n        y = p.y + yOffset;\n    }\n};\n\nstd::vector<Point> points;\nstd::vector<double> angles;\n\nenum Movements {\n    MOVEMENT_DIRECT,\n    MOVEMENT_DIRECT_M,\n    MOVEMENT_DIRECT_W,\n    MOVEMENT_NONE,\n    MOVEMENT_ABSOLUTE_M,\n    MOVEMENT_ABSOLUTE_W,\n    MOVEMENT_BEZIER_W\n};\nMovements movement = MOVEMENT_NONE;\n\nlong long binomialCoefficient_c;\nlong long binomialCoefficient_i;\n\n/**\n * source:\n * https://en.wikipedia.org/wiki/Binomial_coefficient\n * @param n the number that goes above\n * @param k the number that goes below\n * @return\n */\nlong long binomialCoefficient(long long n, long long k) {\n    if ((k < 0) || (k > n))\n        return 0;\n    if ((k == 0) || (k == n))\n        return 1;\n    k = std::min(k, n - k);// take advantage of symmetry\n    binomialCoefficient_c = 1;\n    for (long binomialCoefficient_i = 0;\n     binomialCoefficient_i < k; binomialCoefficient_i++)\n        binomialCoefficient_c = binomialCoefficient_c\n         * (n - binomialCoefficient_i) / (binomialCoefficient_i + 1);\n    return binomialCoefficient_c;\n}\n\ndouble Bezier_t;\ndouble Bezier_step;\nlong long Bezier_nT;\nlong long Bezier_nR;\nlong long Bezier_i;\ndouble Bezier_B;\ndouble Bezier_pX;\ndouble Bezier_pY;\ndouble Bezier_pTheta;\n\ndouble Bezier_B_(double Bezier_n) {\n    return ((double) binomialCoefficient(Bezier_n, Bezier_i))\n         * std::pow((double) Bezier_t, (double) Bezier_i)\n         * std::pow(1.0 - Bezier_t, (double) (Bezier_n - Bezier_i));\n}\n\nvoid Bezier() {\n    Bezier_pX = 0;\n    Bezier_pY = 0;\n    for (Bezier_i = 0; Bezier_i <= Bezier_nT; Bezier_i++) {\n        Bezier_B = Bezier_B_(Bezier_nT);\n        Bezier_pX += points[Bezier_i].x * Bezier_B;\n        Bezier_pY += points[Bezier_i].y * Bezier_B;\n    }\n    Bezier_pTheta = 0;\n    for (Bezier_i = 0; Bezier_i <= Bezier_nR; Bezier_i++) {\n        Bezier_pTheta += angles[Bezier_i] * Bezier_B_(Bezier_nR);\n    }\n}\n\n/**\n * Resets the error values used by the PID controller.\n *\n * Should be used after a movement command if another one is fired\n * before or immediately after the previous one\n * and a continuous movement is not desired.\n */\nvoid resetErrors() {\n    xErrorI = 0;\n    yErrorI = 0;\n    thetaErrorI = 0;\n}\n\n/**\n * Calculates the mobile platform's velocities\n * relative to the mobile platform's frame\n * from the wheels velocities.\n */\nvoid forwardKinematicsMobile() {\n    Vleft3 = Vleft / 3.0;\n    Vback3 = Vback / 3.0;\n    Vright3 = Vright / 3.0;\n    Vxm = (2 * Vback3) - Vleft3 - Vright3;\n    Vym = (sqrt3 * Vright3) - (sqrt3 * Vleft3);\n    omegap = (Vleft3 + Vback3 + Vright3) / L;\n}\n\n/**\n * Calculates the mobile platform's velocities\n * relative to the world's frame\n * from the wheels velocities.\n *\n * Also runs forwardKinematicsMobile().\n */\nvoid forwardKinematicsWorld() {\n    forwardKinematicsMobile();\n    Vxw = (std::cos(theta) * Vxm) - (std::sin(theta) * Vym);\n    Vyw = (std::cos(theta) * Vym) + (std::sin(theta) * Vxm);\n}\n\n/**\n * Generates a pseudo random number between 0 and maximumValue, inclusive.\n * @param maximumValue\n * @return\n */\ndouble getRandom(double maximumValue) {\n    return (((double) std::rand()) / ((double) RAND_MAX)) * maximumValue;\n}\n\n/**\n * Calculates the wheels velocities\n * from the mobile platform's velocities\n * relative to the mobile platform's frame.\n */\nvoid inverseKinematicsMobile() {\n    omegapL = omegap * L;\n    sqrtVym2 = sqrt32 * Vym;\n    Vxm2 = Vxm / 2.0;\n    omegapLVxm2 = omegapL - Vxm2;\n    Vleft  = omegapLVxm2 - sqrtVym2;\n    Vback  = omegapL + Vxm;\n    Vright = omegapLVxm2 + sqrtVym2;\n}\n\n/**\n * Calculates the wheels velocities\n * from the mobile platform's velocities\n * relative to the mobile platform's frame.\n *\n * Also runs inverseKinematicsMobile().\n */\nvoid inverseKinematicsWorld() {\n    Vxm = (std::cos(theta) * Vxw) + (std::sin(theta) * Vyw);\n    Vym = (std::cos(theta) * Vyw) - (std::sin(theta) * Vxw);\n    inverseKinematicsMobile();\n}\n\nbool isStopPose() {\n    return (std::abs(xError) < stopDistance)\n     && (std::abs(yError) < stopDistance)\n     && (std::abs(thetaError) < stopAngle);\n}\n\ndouble normalizeRadian(double radian) {\n    radian = fmod(radian, pi2);\n    if (radian < 0) radian += pi2;\n    return radian;\n}\n\nnamespace gazebo {\n\n    class OmniPlatformPlugin : public ModelPlugin {\n\n        private: physics::JointPtr backJoint;\n\n        private: physics::JointPtr leftJoint;\n\n        // Pointer to the model\n        private: physics::ModelPtr model;\n\n        private: physics::JointPtr rightJoint;\n\n        // Pointer to the update event connection\n        private: event::ConnectionPtr updateConnection;\n\n        private: physics::WorldPtr world;\n\n        /**\n         * Movement for desired pose in mobile platform's frame.\n         *\n         * Translates the desired pose in the mobile platform's frame\n         * to the world's frame and moves according to the world's frame.\n         * Keep in mind that how the mobile platform reaches the target theta\n         * will affect the platform's position in it's own frame,\n         * and that position can't be predicted. Also remember\n         * that you can change the value of the platform's pose in either frame.\n         * To be executed by the communications module.\n         *\n         * @param x\n         * @param y\n         * @param theta\n         */\n        public: void fireMovementAbsoluteM(double x, double y, double theta) {\n            // distance to be traversed in the mobile platform's frame\n            xTarget = x - xm;\n            yTarget = y - ym;\n            // distance rotated to the direction\n            // to be traversed in the world's frame\n            x = (std::cos(theta) * xTarget) - (std::sin(theta) * yTarget);\n            y = (std::cos(theta) * yTarget) + (std::sin(theta) * xTarget);\n            // rotated distance added to current world's frame position\n            xTarget = xw + x;\n            yTarget = yw + y;\n            thetaTarget = theta;\n            movement = MOVEMENT_ABSOLUTE_W;\n            updateIndicator();\n        }\n\n        /**\n         * Random movement for desired pose in mobile platform's frame\n         *\n         * At the end of the movement, the mobile platform's x, y and theta\n         * will be the same as the parameters. However, the position\n         * in the world frame will depend on how theta will vary\n         * from it's current value to the target value, and can't be predicted.\n         * It's preferred to use fireMovementPoseM(),\n         * unless you know what you're doing.\n         * To be executed by the communications module.\n         *\n         * @param x\n         * @param y\n         * @param theta\n         */\n        public: void fireMovementAbsoluteMRaw(double x, double y, double theta) {\n            xTarget = x;\n            yTarget = y;\n            thetaTarget = theta;\n            movement = MOVEMENT_ABSOLUTE_M;\n            updateIndicator();\n        }\n\n        /**\n         * Movement for desired pose in world frame.\n         *\n         * To be executed by the communications module.\n         *\n         * @param x\n         * @param y\n         * @param theta\n         */\n        public: void fireMovementAbsoluteW(double x, double y, double theta) {\n            xTarget = x;\n            yTarget = y;\n            thetaTarget = theta;\n            movement = MOVEMENT_ABSOLUTE_W;\n            updateIndicator();\n        }\n\n        /**\n         * Incremental movement based on two Bézier curves\n         * relative to the platform's frame.\n         *\n         * The curve may be translated such that the first control point\n         * and angle coincides with the current platform's position and angle.\n         *\n         * The Bézier function's <code>t</code> variable, by default, iterates\n         * between 0 and 1 to generate the curve. <code>t</code>'s step value\n         * is defined by the user, and influences the time the platform\n         * will take to execute the movement, which is equal to the step value\n         * divided by the iteration time. If the movement time is too short\n         * (which depends on the movement length and complexity), the platform\n         * will make it's best effort to execute the movement. Therefore,\n         * the longer the movement time (the shorter the step value), the closer\n         * the platform will be to the desired movement.\n         *\n         * The platform's angle is also controlled by a Bézier curve. However,\n         * the algorithm has been modified to be one dimensional, which means\n         * its input are control values instead of control points.\n         * If a constant angle is desired, input a vector with a single value\n         * equal to the angle.\n         *\n         * @param step Bézier funcion's <code>t</code> variable's increment value.\n         * @param points control points for the translation movement\n         * @param angles control angles for the rotation movement\n         * @param offsetT whether to offset the control points to the starting platform's position\n         * @param offsetR whether to offset the control angles to the starting platform's angle\n         */\n        public: void fireMovementBezierM(std::vector<Point> * points,\n                std::vector<double> * angles, double step,\n                bool offsetT, bool offsetR) {\n            if (points->empty() || angles->empty()) return;\n            ::points.clear();\n            ::angles.clear();\n            Bezier_nT = points->size() - 1;\n            Bezier_nR = angles->size() - 1;\n            for (Bezier_i = 0; Bezier_i <= Bezier_nT; Bezier_i++) {\n                ::points.push_back(Point(points->at(Bezier_i)));\n                ::points[Bezier_i].offset(-xw, -yw);\n                ::points[Bezier_i].rotate(theta);\n                ::points[Bezier_i].offset(xw, yw);\n            }\n            if (offsetT) {\n                xOffset = xw - ::points[0].x;\n                yOffset = yw - ::points[0].y;\n            } else {\n                xOffset = 0;\n                yOffset = 0;\n            }\n            for (Bezier_i = 0; Bezier_i <= Bezier_nT; Bezier_i++) {\n                ::points[Bezier_i].offset(xOffset, yOffset);\n            }\n            if (offsetR) {\n                thetaOffset = pi - normalizeRadian((*angles)[0] + pi - theta);\n            } else {\n                thetaOffset = 0;\n            }\n            for (Bezier_i = 0; Bezier_i <= Bezier_nR; Bezier_i++) {\n                ::angles.push_back(angles->at(Bezier_i) + thetaOffset);\n            }\n            Bezier_t = 0;\n            Bezier_step = step;\n            movement = MOVEMENT_BEZIER_W;\n            updateIndicator();\n        }\n\n        /**\n         * Incremental movement based on two Bézier curves relative to the world's frame.\n         *\n         * The curve may be translated such that the first control point\n         * and angle coincides with the current platform's position and angle.\n         *\n         * The Bézier function's <code>t</code> variable, by default, iterates\n         * between 0 and 1 to generate the curve. <code>t</code>'s step value\n         * is defined by the user, and influences the time the platform\n         * will take to execute the movement, which is equal to the step value\n         * divided by the iteration time. If the movement time is too short\n         * (which depends on the movement length and complexity), the platform\n         * will make it's best effort to execute the movement. Therefore,\n         * the longer the movement time (the shorter the step value), the closer\n         * the platform will be to the desired movement.\n         *\n         * The platform's angle is also controlled by a Bézier curve. However,\n         * the algorithm has been modified to be one dimensional, which means\n         * its input are control values instead of control points.\n         * If a constant angle is desired, input a vector with a single value\n         * equal to the angle.\n         *\n         * @param step Bézier funcion's <code>t</code> variable's increment value.\n         * @param points control points for the translation movement\n         * @param angles control angles for the rotation movement\n         * @param offsetT whether to offset the control points to the starting platform's position\n         * @param offsetR whether to offset the control angles to the starting platform's angle\n         */\n        public: void fireMovementBezierW(std::vector<Point> * points,\n                std::vector<double> * angles, double step,\n                bool offsetT, bool offsetR) {\n            if (points->empty() || angles->empty()) return;\n            ::points.clear();\n            ::angles.clear();\n            Bezier_nT = points->size() - 1;\n            Bezier_nR = angles->size() - 1;\n            if (offsetT) {\n                xOffset = xw - (*points)[0].x;\n                yOffset = yw - (*points)[0].y;\n            } else {\n                xOffset = 0;\n                yOffset = 0;\n            }\n            if (offsetR) {\n                thetaOffset = pi - normalizeRadian((*angles)[0] + pi - theta);\n            } else {\n                thetaOffset = 0;\n            }\n            for (Bezier_i = 0; Bezier_i <= Bezier_nT; Bezier_i++) {\n                ::points.push_back(Point(points->at(Bezier_i), xOffset, yOffset));\n            }\n            for (Bezier_i = 0; Bezier_i <= Bezier_nR; Bezier_i++) {\n                ::angles.push_back(angles->at(Bezier_i) + thetaOffset);\n            }\n            Bezier_t = 0;\n            Bezier_step = step;\n            movement = MOVEMENT_BEZIER_W;\n            updateIndicator();\n        }\n\n        /**\n         * Moves the platform with fixed translation and rotation speeds\n         * relative to the mobile platform's frame but translated\n         * to the world's frame. This results in a world's frame movement\n         * rotated according to the initial angle between frames.\n         *\n         * To be executed by the communications module.\n         *\n         * @param Vleft\n         * @param Vback\n         * @param Vright\n         */\n        public: void fireMovementDirectHybrid(double Vxm, double Vym, double omegap) {\n            VxTarget = (std::cos(theta) * Vxm) - (std::sin(theta) * Vym);\n            VyTarget = (std::cos(theta) * Vym) + (std::sin(theta) * Vxm);\n            omegapTarget = omegap;\n            movement = MOVEMENT_DIRECT_W;\n        }\n\n        /**\n         * Moves the platform with fixed translation and rotation speeds,\n         * relative to the mobile platform's frame. Does not transform\n         * the speeds from the mobile platform's frame to the world frame.\n         * This means that random changes in the platform's angle\n         * will not change it's movement, as the mobile platform's frame\n         * rotates with the platform.\n         *\n         * To be executed by the communications module.\n         *\n         * @param Vleft\n         * @param Vback\n         * @param Vright\n         */\n        public: void fireMovementDirectMobile(double Vxm, double Vym, double omegap) {\n            VxTarget = Vxm;\n            VyTarget = Vym;\n            omegapTarget = omegap;\n            movement = MOVEMENT_DIRECT_M;\n        }\n\n        /**\n         * Sets the wheels' speeds, in m/s.\n         *\n         * To be executed by the communications module.\n         * @param Vleft\n         * @param Vback\n         * @param Vright\n         */\n        public: void fireMovementDirectWheel(double Vleft, double Vback, double Vright) {\n            VleftTarget  = Vleft ;\n            VbackTarget  = Vback ;\n            VrightTarget = Vright;\n            movement = MOVEMENT_DIRECT;\n        }\n\n        /**\n         * Moves the platform with fixed translation and rotation speeds,\n         * relative to the world's frame.\n         *\n         * To be executed by the communications module.\n         *\n         * @param Vleft\n         * @param Vback\n         * @param Vright\n         */\n        public: void fireMovementDirectWorld(double Vxw, double Vyw, double omegap) {\n            VxTarget     = Vxw   ;\n            VyTarget     = Vyw   ;\n            omegapTarget = omegap;\n            movement = MOVEMENT_DIRECT_W;\n        }\n\n        /**\n         * Movement of a given distance and angle of rotation\n         * in the mobile platform's frame\n         *\n         * Translates the movement in the mobile platform's frame\n         * to the world's frame and moves according to the world's frame.\n         * Keep in mind that how the mobile platform reaches the target theta\n         * will affect the platform's position in it's own frame,\n         * and that position can't be predicted. Also remember\n         * that you can change the value of the platform's pose in either frame.\n         * To be executed by the communications module.\n         *\n         * @param x\n         * @param y\n         * @param theta\n         */\n        public: void fireMovementRelativeM(double x, double y, double theta) {\n            // distance to be traversed in the mobile platform's frame\n            xTarget = x;\n            yTarget = y;\n            // distance rotated to the direction\n            // to be traversed in the world's frame\n            x = (std::cos(theta) * xTarget) - (std::sin(theta) * yTarget);\n            y = (std::cos(theta) * yTarget) + (std::sin(theta) * xTarget);\n            // rotated distance added to current world's frame position\n            xTarget = xw + x;\n            yTarget = yw + y;\n            thetaTarget = normalizeRadian(::theta + theta);\n            movement = MOVEMENT_ABSOLUTE_W;\n            updateIndicator();\n        }\n\n        /**\n         * Random movement of a given distance and angle of rotation\n         * in the mobile platform's frame\n         *\n         * At the end of the movement, the mobile platform will have traversed\n         * in x and y and rotated by theta, relative to its frame.\n         * However, the position in the world frame will depend\n         * on how theta will vary from it's current value to the target value,\n         * and can't be predicted. It's preferred to use fireMovementPoseM(),\n         * unless you know what you're doing.\n         * To be executed by the communications module.\n         *\n         * @param x\n         * @param y\n         * @param theta\n         */\n        public: void fireMovementRelativeMRaw(double x, double y, double theta) {\n            xTarget = xm + x;\n            yTarget = ym + y;\n            thetaTarget = normalizeRadian(::theta + theta);\n            movement = MOVEMENT_ABSOLUTE_M;\n            updateIndicator();\n        }\n\n        /**\n         * Movement of a given distance and angle of rotation\n         * relative to the world frame.\n         *\n         * To be executed by the communications module.\n         *\n         * @param x\n         * @param y\n         * @param theta\n         */\n        public: void fireMovementRelativeW(double x, double y, double theta) {\n            xTarget = xw + x;\n            yTarget = yw + y;\n            thetaTarget = normalizeRadian(::theta + theta);\n            movement = MOVEMENT_ABSOLUTE_W;\n            updateIndicator();\n        }\n\n        public: void Load(physics::ModelPtr _parent, sdf::ElementPtr /*_sdf*/) {\n            // Store the pointer to the model\n            this->model = _parent;\n\n            this-> leftJoint = model->GetJoint(\"left_joint\");\n            this-> backJoint = model->GetJoint(\"back_joint\");\n            this->rightJoint = model->GetJoint(\"right_joint\");\n\n            this->world = _parent->GetWorld();\n            //this->indicator = this->world->GetModel(\"wood_cube_2_5cm\");\n            //this->indicatorPose.reset(new math::Pose());\n            //this->indicator->SetGravityMode(false);\n            //this->indicator->Fini();\n\n            std::srand(std::time(0));\n\n            // Listen to the update event. This event is broadcast every\n            // simulation iteration.\n            this->updateConnection = event::Events::ConnectWorldUpdateBegin(\n                    boost::bind(&OmniPlatformPlugin::OnUpdate, this, _1));\n        }\n\n        private: void odometry() {\n            timeLast = timeNow;\n            timeNow = this->world->GetSimTime().Double();\n            timeElapsed = timeNow - timeLast;\n            Vleft  = this-> leftJoint->GetVelocity(0) * r;\n            Vback  = this-> backJoint->GetVelocity(0) * r;\n            Vright = this->rightJoint->GetVelocity(0) * r;\n            theta = normalizeRadian(model->GetRelativePose().rot.GetYaw()); // simulation theta\n            forwardKinematicsWorld();\n            xm += Vxm * timeElapsed;\n            ym += Vym * timeElapsed;\n            xw += Vxw * timeElapsed;\n            //xw = model->GetRelativePose().pos.x; // simulation x\n            yw += Vyw * timeElapsed;\n            //yw = model->GetRelativePose().pos.y; // simulation y\n        }\n\n        // Called by the world update start event\n        public: void OnUpdate(const common::UpdateInfo & /*_info*/) {\n            odometry();\n            switch (movement) {\n                case MOVEMENT_ABSOLUTE_M:\n                    xError = xTarget - xm;\n                    yError = yTarget - ym;\n                    // method parameter: theta plus shift to place thetaTarget at pi\n                    thetaError = pi - normalizeRadian(theta + pi - thetaTarget);\n                    if (isStopPose()) {\n                        movement = MOVEMENT_NONE;\n                        break;\n                    }\n                    xErrorI += xError;\n                    yErrorI += yError;\n                    thetaErrorI += thetaError;\n                    Vxm = (xError * P) + (xErrorI * I);\n                    Vym = (yError * P) + (yErrorI * I);\n                    VxAbs = std::abs(Vxm);\n                    VyAbs = std::abs(Vym);\n                    if ((VxAbs > Vmax) || (VyAbs > Vmax)) {\n                        scale = Vmax / ((VxAbs > VyAbs) ? VxAbs : VyAbs);\n                        Vxm *= scale;\n                        Vym *= scale;\n                    }\n                    omegap = (thetaError * P) + (thetaErrorI * I);\n                    if (omegap > omegamax) {\n                        omegap = omegamax;\n                    }\n                    inverseKinematicsMobile();\n                    break;\n                case MOVEMENT_BEZIER_W:\n                    if (Bezier_t <= 1) {\n                        Bezier();\n                        xTarget = Bezier_pX;\n                        yTarget = Bezier_pY;\n                        thetaTarget = normalizeRadian(Bezier_pTheta);\n                        Bezier_t += Bezier_step;\n                        updateIndicator();\n                    } else {\n                        movement = MOVEMENT_NONE;\n                    }\n                    // break; // fall through intended\n                case MOVEMENT_ABSOLUTE_W:\n                    xError = xTarget - xw;\n                    yError = yTarget - yw;\n                    // method parameter: theta plus shift to place thetaTarget at pi\n                    thetaError = pi - normalizeRadian(theta + pi - thetaTarget);\n                    if (isStopPose() && (movement == MOVEMENT_ABSOLUTE_W)) {\n                        movement = MOVEMENT_NONE;\n                        break;\n                    }\n                    xErrorI += xError;\n                    yErrorI += yError;\n                    thetaErrorI += thetaError;\n                    Vxw = (xError * P) + (xErrorI * I);\n                    Vyw = (yError * P) + (yErrorI * I);\n                    VxAbs = std::abs(Vxw);\n                    VyAbs = std::abs(Vyw);\n                    if ((VxAbs > Vmax) || (VyAbs > Vmax)) {\n                        scale = Vmax / ((VxAbs > VyAbs) ? VxAbs : VyAbs);\n                        Vxw *= scale;\n                        Vyw *= scale;\n                    }\n                    omegap = (thetaError * P) + (thetaErrorI * I);\n                    if (omegap > omegamax) {\n                        omegap = omegamax;\n                    }\n                    inverseKinematicsWorld();\n                    break;\n                case MOVEMENT_DIRECT:\n                    Vleft  = VleftTarget ;\n                    Vback  = VbackTarget ;\n                    Vright = VrightTarget;\n                    break;\n                case MOVEMENT_DIRECT_M:\n                    Vxm    = VxTarget    ;\n                    Vym    = VyTarget    ;\n                    omegap = omegapTarget;\n                    inverseKinematicsMobile();\n                    break;\n                case MOVEMENT_DIRECT_W:\n                    Vxw    = VxTarget    ;\n                    Vyw    = VyTarget    ;\n                    omegap = omegapTarget;\n                    inverseKinematicsWorld();\n                    break;\n                default:\n                    xErrorI = 0;\n                    yErrorI = 0;\n                    thetaErrorI = 0;\n                    Vleft = 0;\n                    Vback = 0;\n                    Vright = 0;\n            }\n             leftJoint->SetVelocity(0, Vleft / r);\n             backJoint->SetVelocity(0, Vback / r);\n            rightJoint->SetVelocity(0, Vright / r);\n        }\n\n        /**\n         * Simulation purposes only.\n         */\n        private: void updateIndicator() {\n//            indicatorPose->Set(xTarget, yTarget, 0.05, 0, 0, thetaTarget);\n//            indicator->SetRelativePose(*indicatorPose);\n        }\n    };\n\n    // Register this plugin with the simulator\n    GZ_REGISTER_MODEL_PLUGIN(OmniPlatformPlugin)\n}\n\n// C++ bug: when things are declared as 'static' or 'const',\n// they lose their references, and it's only possible to read from them\n// to restore their references, they must be decladed again like this:\ndouble Point::w;\n", "meta": {"hexsha": "9c8fe5bab102166f5981348562d854ecab9035f7", "size": 29037, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugin/template/main.cc", "max_stars_repo_name": "pxalcantara/OpenBase", "max_stars_repo_head_hexsha": "05dfe70f8efb207b20a9f2b79d7883473ce044cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 92.0, "max_stars_repo_stars_event_min_datetime": "2017-05-08T20:15:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T22:08:37.000Z", "max_issues_repo_path": "plugin/template/main.cc", "max_issues_repo_name": "dupeljan/OpenBase", "max_issues_repo_head_hexsha": "05dfe70f8efb207b20a9f2b79d7883473ce044cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2017-01-08T00:05:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T13:05:56.000Z", "max_forks_repo_path": "plugin/template/main.cc", "max_forks_repo_name": "dupeljan/OpenBase", "max_forks_repo_head_hexsha": "05dfe70f8efb207b20a9f2b79d7883473ce044cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49.0, "max_forks_repo_forks_event_min_datetime": "2017-05-08T20:16:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T14:07:59.000Z", "avg_line_length": 35.8924598269, "max_line_length": 189, "alphanum_fraction": 0.5647277611, "num_tokens": 7007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.4127408248254962}}
{"text": "#include \"conex/supernodal_solver.h\"\n#include \"conex/clique_ordering.h\"\n\n#include <iostream>\n#include <map>\n\n#include <Eigen/Dense>\n\nnamespace conex {\n\nusing Eigen::MatrixXd;\nusing Eigen::MatrixXi;\nusing Eigen::VectorXd;\nusing Eigen::VectorXi;\nusing Permutation = Eigen::PermutationMatrix<-1>;\nusing T = TriangularMatrixOperations;\nusing std::vector;\n\nnamespace {\n\nvector<int> Relabel(const vector<int>& x, const vector<int>& labels) {\n  vector<int> y;\n  for (auto& xi : x) {\n    y.push_back(labels.at(xi));\n  }\n  return y;\n}\n\nint GetMax(const std::vector<Clique>& cliques) {\n  int max = cliques.at(0).at(0);\n  for (const auto& c : cliques) {\n    for (const auto ci : c) {\n      if (ci > max) {\n        max = ci;\n      }\n    }\n  }\n  return max;\n}\n\nclass TriangularMatrixColumnOperations {\n public:\n  TriangularMatrixColumnOperations(T::Matrix* mat) : mat_(mat) {\n    dense_size = mat_->supernode_size.at(0);\n  }\n  void NextColumn() {\n    supernode_column_++;\n    column++;\n    dense_size--;\n    if (supernode_column_ >= mat_->supernode_size.at(supernode_index_)) {\n      supernode_index_++;\n      supernode_column_ = 0;\n      dense_size = mat_->supernode_size.at(supernode_index_);\n    }\n  }\n\n  void Rescale(double scale) {\n    mat_->supernodes.at(supernode_index_).col(supernode_column_).array() *=\n        scale;\n    mat_->separator.at(supernode_index_).row(supernode_column_).array() *=\n        scale;\n  }\n\n  double Diagonal() {\n    return mat_->supernodes.at(supernode_index_)(supernode_column_,\n                                                 supernode_column_);\n  }\n\n  // Applies the operation b = b - L.col(i) * y (i)\n  void SubtractWeightedColumn(VectorXd* b, double y) {\n    b->segment(column, dense_size) -= y * mat_->supernodes.at(supernode_index_)\n                                              .col(supernode_column_)\n                                              .tail(dense_size);\n\n    int offset = mat_->supernode_size.at(supernode_index_);\n    for (int i = 0; i < mat_->separator.at(supernode_index_).cols(); i++) {\n      int row = mat_->path.at(supernode_index_).at(offset + i);\n      (*b)(row) -=\n          y * mat_->separator.at(supernode_index_)(supernode_column_, i);\n    }\n  }\n\n  std::vector<int> NonzeroRows() {\n    std::vector<int> y;\n    for (int i = 1; i < dense_size; i++) {\n      y.push_back(column + i);\n    }\n    int offset = mat_->supernode_size.at(supernode_index_);\n    for (int i = 0; i < mat_->separator.at(supernode_index_).cols(); i++) {\n      int row = mat_->path.at(supernode_index_).at(offset + i);\n      y.push_back(row);\n    }\n    return y;\n  }\n\n  // double DotProduct(const Eigen::MatrixXd& x) {\n  //  double y = 0;\n  //  mat_->supernodes.at(supernode_index_).col(supernode_column_).tail(dense_size).dot(\n  //      x.segment(column, dense_size);\n  //}\n\n private:\n  int supernode_index_ = 0;\n  int dense_size = 0;\n  int column = 0;\n  int supernode_column_ = 0;\n  SparseTriangularMatrix* mat_;\n};\n\ntemplate <typename T>\nint LookupSuperNode(const T& o, int index, int start) {\n  for (int j = static_cast<int>(o.snodes.size()) - 1; j >= 0; j--) {\n    if (o.snodes.at(j).size() > 0) {\n      if (index >= o.snodes.at(j).at(0)) {\n        return j;\n      }\n    }\n  }\n  throw \"Sparse matrix is malformed: invalid supernode partition.\";\n}\n\ndouble Get(const SparseTriangularMatrix& o, int i, int j) {\n  if (j > i) {\n    return 0;\n  }\n  // Find the supernode that owns the column.\n  int node = LookupSuperNode(o, j, 0);\n\n  // Apply offsets.\n  int offset_i = i - o.path.at(node).at(0);\n  int offset_j = j - o.path.at(node).at(0);\n  if ((offset_i < o.supernode_size.at(node)) &&\n      (offset_j < o.supernode_size.at(node))) {\n    return o.supernodes.at(node)(offset_i, offset_j);\n  }\n  for (size_t k = o.supernode_size.at(node); k < o.path.at(node).size(); k++) {\n    if (i == o.path.at(node).at(k)) {\n      return o.separator.at(node)(offset_j, k - o.supernode_size.at(node));\n    }\n  }\n  return 0;\n}\n\nclass LowerTriangularSuperNodal {\n  // We partition matrix into\n  //\n  // SN1  R1\n  // R1   SN2  R2\n  // R1   R2   SN3\n  //\n  // Where R1 is sparse.\n public:\n  LowerTriangularSuperNodal(SparseTriangularMatrix* mat)\n      : supernodes_(mat->supernodes),\n        supernode_size_(mat->supernode_size),\n        path_(mat->path),\n        separator_(mat->separator) {\n    Init();\n  }\n\n  void Init() {\n    // for (int j = static_cast<int>(path_.size()) - 1; j >= 0; j--) {\n    //   supernodes_.at(j).resize(supernode_size_.at(j), supernode_size_.at(j));\n    //   separator_.at(j).resize(supernode_size_.at(j),  path_.at(j).size() -\n    //   supernode_size_.at(j));\n    // }\n  }\n\n  // The smallest super-node less than i.\n  int LookupSuperNode(int index, int start) const {\n    for (int j = static_cast<int>(path_.size()) - 1; j >= 0; j--) {\n      if (index >= path_.at(j).at(0)) {\n        return j;\n      }\n    }\n    throw \"Sparse matrix is malformed: invalid supernode partition.\";\n  }\n\n  double Get(int i, int j) const {\n    if (j > i) {\n      return 0;\n    }\n    // Find the supernode that owns the column.\n    int node = LookupSuperNode(j, 0);\n\n    // Apply offsets.\n    int offset_i = i - path_.at(node).at(0);\n    int offset_j = j - path_.at(node).at(0);\n    if ((offset_i < supernode_size_.at(node)) &&\n        (offset_j < supernode_size_.at(node))) {\n      return supernodes_.at(node)(offset_i, offset_j);\n    }\n    for (size_t k = supernode_size_.at(node); k < path_.at(node).size(); k++) {\n      if (i == path_.at(node).at(k)) {\n        return separator_.at(node)(offset_j, k - supernode_size_.at(node));\n      }\n    }\n    return 0;\n  }\n\n  void Increment(double val, int i, int j, int supernode_index = -1) {\n    if (val == 0) {\n      return;\n    }\n    assert(j <= i);\n\n    int node = supernode_index;\n    // Find the supernode that owns storage for column j.\n    if (node == -1) {\n      node = LookupSuperNode(j, 0);\n    }\n\n    // Apply offsets.\n    int offset_i = i - path_.at(node).at(0);\n    int offset_j = j - path_.at(node).at(0);\n\n    // i is also in the supernode.\n    if ((offset_i < supernode_size_.at(node)) &&\n        (offset_j < supernode_size_.at(node))) {\n      supernodes_.at(node)(offset_i, offset_j) += val;\n      return;\n    }\n\n    // i is in a separator.\n    for (size_t k = supernode_size_.at(node); k < path_.at(node).size(); k++) {\n      if (i == path_.at(node).at(k)) {\n        separator_.at(node)(offset_j, k - supernode_size_.at(node)) += val;\n        return;\n      }\n    }\n\n    throw \"Specified entry of sparse matrix is not accesible.\";\n  }\n\n public:\n  using MapT = Eigen::Map<Eigen::MatrixXd>;\n  std::vector<MapT>& supernodes_;\n  std::vector<int>& supernode_size_;\n  std::vector<Clique>& path_;\n  std::vector<MapT>& separator_;\n};\n\nstd::vector<int> ResidualSize(std::vector<Clique>& path) {\n  std::vector<int> y;\n  for (size_t j = 0; j < path.size() - 1; j++) {\n    std::vector<int> temp;\n    IntersectionOfSorted(path.at(j), path.at(j + 1), &temp);\n    y.push_back(path.at(j).size() - temp.size());\n  }\n  y.push_back(path.back().size());\n  return y;\n}\n\n}  // namespace\n\nvoid IntersectionOfSorted(const std::vector<int>& v1,\n                          const std::vector<int>& v2, std::vector<int>* v3) {\n  v3->clear();\n  std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(),\n                        back_inserter(*v3));\n}\n\nSparseTriangularMatrix GetFillInPattern(\n    int N, const std::vector<Clique>& cliques_input) {\n  auto mat = MakeSparseTriangularMatrix(N, cliques_input);\n\n  for (int j = static_cast<int>(mat.path.size()) - 1; j >= 0; j--) {\n    // Initialize columns of super nodes.\n    mat.supernodes.at(j).setConstant(1);\n    mat.separator.at(j).setConstant(1);\n\n    // Update other columns: the (seperator, seperator) components.\n    int index = 0;\n    auto s_s = mat.workspace_.seperator_diagonal.at(j);\n    int n = mat.path.at(j).size();\n    for (int i = mat.supernode_size.at(j); i < n; i++) {\n      for (int k = i; k < n; k++) {\n        *s_s.at(index++) += 1;\n      }\n    }\n  }\n  return mat;\n}\n\nstd::vector<Clique> Permute(std::vector<Clique>& path,\n                            std::vector<int>& permutation) {\n  auto y = path;\n  for (size_t i = 0; i < path.size(); i++) {\n    for (size_t j = 0; j < path.at(i).size(); j++) {\n      y.at(i).at(j) = permutation.at(path.at(i).at(j));\n    }\n  }\n  return y;\n}\n\nvoid Sort(std::vector<Clique>* path) {\n  for (size_t i = 0; i < path->size(); i++) {\n    std::sort(path->at(i).begin(), path->at(i).end());\n  }\n}\n\n// Want A B  C  D  E\n//   Add A_i \\cap A_k\n//    to all A_j for i < j < k.\n//\nvoid RunningIntersectionClosure(std::vector<Clique>* path) {\n  if (path->size() < 2) {\n    return;\n  }\n  int n = path->size();\n  for (int i = 0; i < n - 2; i++) {\n    for (int j = n - 1; j > i + 1; j--) {\n      std::vector<int> temp;\n      IntersectionOfSorted(path->at(i), path->at(j), &temp);\n      if (temp.size() == 0) {\n        continue;\n      }\n      for (int k = j - 1; k > i; k--) {\n        path->at(k) = UnionOfSorted(path->at(k), temp);\n      }\n    }\n  }\n}\n\nEigen::MatrixXd TriangularMatrixOperations::ToDense(\n    const SparseTriangularMatrix& mat) {\n  MatrixXd y(mat.N, mat.N);\n  for (int i = 0; i < mat.N; i++) {\n    for (int j = 0; j < mat.N; j++) {\n      y(i, j) = Get(mat, i, j);\n    }\n  }\n  return y;\n}\n\nvoid TriangularMatrixOperations::SetConstant(SparseTriangularMatrix* mat,\n                                             double val) {\n  for (auto& n : mat->supernodes) {\n    n.array() = val;\n  }\n  for (auto& n : mat->separator) {\n    n.array() = val;\n  }\n}\n\nSparseTriangularMatrix MakeSparseTriangularMatrix(\n    int N, const std::vector<Clique>& path_) {\n  auto path = path_;\n  Sort(&path);\n  RunningIntersectionClosure(&path);\n  auto supernode_size = ResidualSize(path);\n  return SparseTriangularMatrix(N, path, supernode_size);\n}\n\nvoid T::CholeskyInPlace(SparseTriangularMatrix* C) {\n  TriangularMatrixColumnOperations col(C);\n  LowerTriangularSuperNodal mat(C);\n  double sqrt_d = std::sqrt(col.Diagonal());\n  col.Rescale(1.0 / sqrt_d);\n\n  // i: a supernode\n  for (int i = 0; i < C->N - 1; i++) {\n    // Substract col(2:n) c(2:n)^T\n    auto indices = col.NonzeroRows();\n    for (size_t k = 0; k < indices.size(); k++) {\n      double weight = -mat.Get(indices.at(k), i);\n      // Decrement column k\n      for (size_t j = k; j < indices.size(); j++) {\n        mat.Increment(weight * mat.Get(indices.at(j), i), indices.at(j),\n                      indices.at(k));\n      }\n    }\n    col.NextColumn();\n    double sqrt_d = std::sqrt(col.Diagonal());\n    col.Rescale(1.0 / sqrt_d);\n  }\n}\n\n// Apply L  inverse.\n// 1\n// 1  1\n// 1  1  1\n\n// L\n// B in\nVectorXd T::ApplyInverseOfTranspose(SparseTriangularMatrix* mat,\n                                    const VectorXd& b) {\n  assert(b.rows() == mat->N);\n  int n = b.rows();\n  VectorXd y(n);\n  auto res = b;\n  LowerTriangularSuperNodal L(mat);\n\n  y(n - 1) = res(n - 1) / L.Get(n - 1, n - 1);\n  for (int i = n - 2; i >= 0; i--) {\n    for (int j = 0; j < i + 1; j++) {\n      res(j) = res(j) - L.Get(i + 1, j) * y(i + 1);\n    }\n    y(i) = res(i) / L.Get(i, i);\n  }\n  return y;\n}\n\nVectorXd T::ApplyInverse(SparseTriangularMatrix* mat, const VectorXd& b) {\n  assert(b.rows() == mat->N);\n  int n = b.rows();\n  VectorXd y(n);\n  auto res = b;\n  LowerTriangularSuperNodal L(mat);\n\n  TriangularMatrixColumnOperations col(mat);\n  y(0) = res(0) / col.Diagonal();\n  for (int i = 1; i < n; i++) {\n    // Iterate over non-zero entries of column.\n    // for (int j = i; j < n; j++) {\n    //   res(j) = res(j) - L.Get(j, i - 1) * y(i - 1);\n    // }\n    col.SubtractWeightedColumn(&res, y(i - 1));\n\n    col.NextColumn();\n    y(i) = res(i) / col.Diagonal();\n  }\n  return y;\n}\n\nstd::vector<int> UnionOfSorted(const std::vector<int>& x1,\n                               const std::vector<int>& x2) {\n  std::vector<int> y;\n  set_union(x1.begin(), x1.end(), x2.begin(), x2.end(), inserter(y, y.end()));\n  return y;\n}\n\nMatrixData GetData(const vector<vector<int>>& cliques, int init) {\n  vector<vector<int>> separators;\n  vector<vector<int>> supernodes;\n  MatrixData d;\n  d.cliques = cliques;\n  Sort(&d.cliques);\n  auto& order = d.clique_order;\n\n  PickCliqueOrder(d.cliques, init, &order, &supernodes, &separators);\n\n  d.permutation.resize(GetMax(cliques) + 1);\n  d.permutation_inverse.resize(GetMax(cliques) + 1);\n  int i = 0;\n  for (auto& e : order) {\n    for (auto& sn_ii : supernodes.at(e)) {\n      d.permutation_inverse.at(i) = sn_ii;\n      d.permutation.at(sn_ii) = i;\n      i++;\n    }\n  }\n\n  auto& separators_ = d.separators;\n  auto& supernodes_ = d.supernodes;\n\n  supernodes_.resize(order.size());\n  separators_.resize(order.size());\n\n  i = 0;\n\n  for (auto e : order) {\n    supernodes_.at(i) = Relabel(supernodes.at(e), d.permutation);\n    separators_.at(i) = Relabel(separators.at(e), d.permutation);\n    i++;\n  }\n\n  Sort(&separators_);\n  Sort(&supernodes_);\n\n  int cnt = 0;\n  auto& supernode_size = d.supernode_size;\n  supernode_size.resize(order.size());\n  for (auto& si : supernode_size) {\n    si = supernodes_.at(cnt).size();\n    cnt++;\n  }\n  d.N = std::accumulate(supernode_size.begin(), supernode_size.end(), 0);\n  for (size_t i = 0; i < d.cliques.size(); i++) {\n    d.cliques.at(i) = UnionOfSorted(supernodes_.at(i), separators_.at(i));\n  }\n  return d;\n}\n\n}  // namespace conex\n", "meta": {"hexsha": "db062e0bb169c72ddd3736fbff37edab21847528", "size": 13253, "ext": "cc", "lang": "C++", "max_stars_repo_path": "conex/supernodal_solver.cc", "max_stars_repo_name": "ToyotaResearchInstitute/conex", "max_stars_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-02-08T08:02:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T21:53:22.000Z", "max_issues_repo_path": "conex/supernodal_solver.cc", "max_issues_repo_name": "ToyotaResearchInstitute/conex", "max_issues_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conex/supernodal_solver.cc", "max_forks_repo_name": "ToyotaResearchInstitute/conex", "max_forks_repo_head_hexsha": "181a4a9b77d7331464fffc7afc45fe8be29168d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T16:02:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T11:25:46.000Z", "avg_line_length": 27.2695473251, "max_line_length": 88, "alphanum_fraction": 0.5871878065, "num_tokens": 4052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.41271188911595724}}
{"text": "// graph-tool -- a general graph modification and manipulation thingy\n//\n// Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de>\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 3\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// you should have received a copy of the GNU General Public License\n// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n#ifndef GRAPH_CLUSTERING_HH\n#define GRAPH_CLUSTERING_HH\n\n#include \"config.h\"\n\n#include <unordered_set>\n#include <boost/mpl/if.hpp>\n\n#ifdef HAVE_SPARSEHASH\n#include SPARSEHASH_INCLUDE(dense_hash_set)\n#endif\n\n#ifndef __clang__\n#include <ext/numeric>\nusing __gnu_cxx::power;\n#else\ntemplate <class Value>\nValue power(Value value, int n)\n{\n    return pow(value, n);\n}\n#endif\n\nnamespace graph_tool\n{\nusing namespace boost;\n\n#ifdef HAVE_SPARSEHASH\nusing google::dense_hash_set;\n#else\nusing std::unordered_set;\n#endif\n\n// calculates the number of triangles to which v belongs\ntemplate <class Graph>\npair<int,int>\nget_triangles(typename graph_traits<Graph>::vertex_descriptor v, const Graph &g)\n{\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n\n#ifdef HAVE_SPARSEHASH\n    typedef dense_hash_set<vertex_t, std::hash<vertex_t>> set_t;\n#else\n    typedef unordered_set<vertex_t> set_t;\n#endif\n\n    set_t neighbour_set;\n\n#ifdef HAVE_SPARSEHASH\n     neighbour_set.set_empty_key(numeric_limits<vertex_t>::max());\n     neighbour_set.resize(out_degree(v, g));\n#endif\n\n    size_t triangles = 0;\n\n    typename graph_traits<Graph>::adjacency_iterator n, n_end;\n    for (tie(n, n_end) = adjacent_vertices(v, g); n != n_end; ++n)\n    {\n        if (*n == v) // no self-loops\n            continue;\n        neighbour_set.insert(*n);\n    }\n\n    for (tie(n, n_end) = adjacent_vertices(v, g); n != n_end; ++n)\n    {\n        typename graph_traits<Graph>::adjacency_iterator n2, n2_end;\n        for (tie(n2, n2_end) = adjacent_vertices(*n, g); n2 != n2_end; ++n2)\n        {\n            if (*n2 == *n) // no self-loops\n                continue;\n            if (neighbour_set.find(*n2) != neighbour_set.end())\n                ++triangles;\n        }\n    }\n\n    size_t k = out_degree(v, g);\n    return make_pair(triangles/2,(k*(k-1))/2);\n}\n\n\n// retrieves the global clustering coefficient\nstruct get_global_clustering\n{\n    template <class Graph>\n    void operator()(const Graph& g, double& c, double& c_err) const\n    {\n        size_t triangles = 0, n = 0;\n        pair<size_t, size_t> temp;\n\n        int i, N = num_vertices(g);\n\n        #pragma omp parallel for default(shared) private(i,temp) \\\n            schedule(runtime) if (N > 100) reduction(+:triangles, n)\n        for (i = 0; i < N; ++i)\n        {\n            typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);\n            if (v == graph_traits<Graph>::null_vertex())\n                continue;\n\n            temp = get_triangles(v, g);\n            triangles += temp.first;\n            n += temp.second;\n        }\n        c = double(triangles) / n;\n\n        // \"jackknife\" variance\n        c_err = 0.0;\n        double cerr = 0.0;\n\n        #pragma omp parallel for default(shared) private(i,temp) \\\n            schedule(runtime) if (N > 100) reduction(+:cerr)\n        for (i = 0; i < N; ++i)\n        {\n            typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);\n            if (v == graph_traits<Graph>::null_vertex())\n                continue;\n\n            temp = get_triangles(v, g);\n            double cl = double(triangles - temp.first) / (n - temp.second);\n\n            cerr += power(c - cl, 2);\n        }\n        c_err = sqrt(cerr);\n    }\n};\n\n// sets the local clustering coefficient to a property\nstruct set_clustering_to_property\n{\n    template <class Graph, class ClustMap>\n    void operator()(const Graph& g, ClustMap clust_map) const\n    {\n        typedef typename property_traits<ClustMap>::value_type c_type;\n        typename get_undirected_graph<Graph>::type ug(g);\n        int i, N = num_vertices(g);\n\n        #pragma omp parallel for default(shared) private(i) schedule(runtime) if (N > 100)\n        for (i = 0; i < N; ++i)\n        {\n            typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);\n            if (v == graph_traits<Graph>::null_vertex())\n                continue;\n\n            pair<size_t,size_t> triangles = get_triangles(v,ug); // get from ug\n            double clustering = (triangles.second > 0) ?\n                double(triangles.first)/triangles.second :\n                0.0;\n\n            clust_map[v] = c_type(clustering);\n        }\n    }\n\n    template <class Graph>\n    struct get_undirected_graph\n    {\n        typedef typename mpl::if_\n           <std::is_convertible<typename graph_traits<Graph>::directed_category,\n                                directed_tag>,\n            const UndirectedAdaptor<Graph>,\n            const Graph& >::type type;\n    };\n};\n\n} //graph-tool namespace\n\n#endif // GRAPH_CLUSTERING_HH\n", "meta": {"hexsha": "a18a244633e7c4f9a7dbf4763df440e2baed2e2f", "size": 5340, "ext": "hh", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/clustering/graph_clustering.hh", "max_stars_repo_name": "johankaito/fufuka", "max_stars_repo_head_hexsha": "32a96ecf98ce305c2206c38443e58fdec88c788d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-04T19:41:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-04T19:41:53.000Z", "max_issues_repo_path": "graph-tool/src/graph/clustering/graph_clustering.hh", "max_issues_repo_name": "johankaito/fufuka", "max_issues_repo_head_hexsha": "32a96ecf98ce305c2206c38443e58fdec88c788d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graph-tool/src/graph/clustering/graph_clustering.hh", "max_forks_repo_name": "johankaito/fufuka", "max_forks_repo_head_hexsha": "32a96ecf98ce305c2206c38443e58fdec88c788d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0217391304, "max_line_length": 90, "alphanum_fraction": 0.6264044944, "num_tokens": 1314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629465, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.41271188911595713}}
{"text": "//////////////////////////////////////////////////////////////////////////////\n///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand\n///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI\n///\n///          Distributed under the Boost Software License, Version 1.0\n///                 See accompanying file LICENSE.txt or copy at\n///                     http://www.boost.org/LICENSE_1_0.txt\n//////////////////////////////////////////////////////////////////////////////\n#ifndef NT2_TOOLBOX_ELLIPTIC_FUNCTION_SCALAR_ELLIK_HPP_INCLUDED\n#define NT2_TOOLBOX_ELLIPTIC_FUNCTION_SCALAR_ELLIK_HPP_INCLUDED\n#include <boost/math/special_functions.hpp>\n#include <nt2/sdk/constant/eps_related.hpp>\n#include <nt2/sdk/constant/digits.hpp>\n#include <nt2/sdk/constant/real.hpp>\n\n#include <nt2/include/functions/is_ltz.hpp>\n#include <nt2/include/functions/sqrt.hpp>\n#include <nt2/include/functions/tan.hpp>\n#include <nt2/include/functions/atan.hpp>\n#include <nt2/include/functions/log.hpp>\n#include <nt2/include/functions/average.hpp>\n\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is arithmetic_\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ellik_, tag::cpu_,\n                       (A0)(A1),\n                       (arithmetic_<A0>)(arithmetic_<A1>)\n                      )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::ellik_(tag::arithmetic_,tag::arithmetic_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0,class A1>\n    struct result<This(A0,A1)> :\n      std::tr1::result_of<meta::floating(A0,A1)>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      typedef typename NT2_RETURN_TYPE(2)::type type;\n      return ellik(type(a0), type(a1));\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is double\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ellik_, tag::cpu_,\n                       (A0)(A1),\n                       (double_<A0>)(double_<A1>)\n                      )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::ellik_(tag::double_,tag::double_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0,class A1>\n    struct result<This(A0,A1)> :\n      std::tr1::result_of<meta::floating(A0,A1)>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      typedef typename NT2_RETURN_TYPE(2)::type type;\n      if (a1>One<A1>()||(is_ltz(a1))) return Nan<type>();\n      if (is_eqz(a1))  return type(a0);\n      return boost::math::ellint_1(nt2::sqrt(a1), a0);\n    }\n  };\n} }\n\n/////////////////////////////////////////////////////////////////////////////\n// Implementation when type A0 is float\n/////////////////////////////////////////////////////////////////////////////\nNT2_REGISTER_DISPATCH(tag::ellik_, tag::cpu_,\n                       (A0)(A1),\n                       (float_<A0>)(float_<A1>)\n                      )\n\nnamespace nt2 { namespace ext\n{\n  template<class Dummy>\n  struct call<tag::ellik_(tag::float_,tag::float_),\n              tag::cpu_, Dummy> : callable\n  {\n    template<class Sig> struct result;\n    template<class This,class A0,class A1>\n    struct result<This(A0,A1)> :\n      std::tr1::result_of<meta::floating(A0,A1)>{};\n\n    NT2_FUNCTOR_CALL(2)\n    {\n      typedef typename NT2_RETURN_TYPE(2)::type type;\n      if (a1>One<A1>()||(is_ltz(a1))) return Nan<type>();\n      if (is_eqz(a1))  return a0;\n      type phi = nt2::abs(a0);\n      type m = a1;\n      type a = 1.0;\n      type b = oneminus(m);\n      if( is_eqz(b) )   return nt2::log(nt2::tan(nt2::average(Pio_2<type>(),phi)));\n      b = nt2::sqrt(b);\n      type c = nt2::sqrt(m);\n      int d = 1;\n      type t = nt2::tan(phi);\n      int mod = (phi + Pio_2<type>())/Pi<type>();\n      while( nt2::abs(c) > nt2::abs(a)*Eps<type>() )\n      {\n        type temp = b/a;\n        phi += nt2::atan(t*temp) + mod*Pi<type>();\n        mod = (phi + Pio_2<type>())/Pi<type>();\n        t = t*oneplus(temp)/( oneminus(temp*t*t));\n        c = average(a,-b);\n        temp = nt2::sqrt(a*b);\n        a = average(a,b);\n        b = temp;\n        d += d;\n      }\n      type temp = (atan(t) + mod * Pi<type>())/(d * a);\n      if( is_ltz(a0) )  temp = -temp;\n      return temp;\n    }\n  };\n} }\n\n#endif\n// modified by jt the 26/12/2010", "meta": {"hexsha": "cff34f0cd2dd6ec0129c7fec1ae46053d66c8388", "size": 4531, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/elliptic/include/nt2/toolbox/elliptic/function/scalar/ellik.hpp", "max_stars_repo_name": "brycelelbach/nt2", "max_stars_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T03:35:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:35:10.000Z", "max_issues_repo_path": "modules/elliptic/include/nt2/toolbox/elliptic/function/scalar/ellik.hpp", "max_issues_repo_name": "brycelelbach/nt2", "max_issues_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/elliptic/include/nt2/toolbox/elliptic/function/scalar/ellik.hpp", "max_forks_repo_name": "brycelelbach/nt2", "max_forks_repo_head_hexsha": "73d7e8dd390fa4c8d251c6451acdae65def70e0b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8134328358, "max_line_length": 83, "alphanum_fraction": 0.5087177224, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4127118733318411}}
{"text": "#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <boost/tuple/tuple.hpp>\n\n#include <CGAL/Cartesian.h>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n\n#include <CGAL/function_objects.h>\n\n#include <CGAL/AABB_tree.h>\n#include <CGAL/AABB_traits.h>\n\n#include <CGAL/AABB_face_graph_triangle_primitive.h>\n#include <CGAL/Polyhedron_3.h>\n\n\n#include <CGAL/Timer.h>\n\n#include <CGAL/Random.h>\n#include <CGAL/point_generators_3.h>\n#include <CGAL/algorithm.h>\n\n\nconst std::size_t elements = 50000;\nconst int runs = 10;\n\ntemplate<typename Tree>\nstruct FilterP {\n  const Tree* t;\n\n  template<typename T>\n  bool operator()(const T& tt) { return !t->do_intersect(tt); }\n};\n\n\ntemplate<typename ForwardIterator, typename Tree>\nstd::size_t intersect(ForwardIterator b, ForwardIterator e, const Tree& tree, long& counter) {\n      typedef\n        typename Tree::AABB_traits::template Intersection_and_primitive_id<typename ForwardIterator::value_type>::Type\n        Obj_type;\n\n  std::vector<Obj_type> v;\n  // bad educated guess\n  v.reserve(elements);\n  for(; b != e; ++b) {\n    tree.all_intersections(*b, std::back_inserter(v));\n    boost::optional<Obj_type> o = tree.any_intersection(*b);\n    if(o)\n      ++counter;\n  }\n\n  return v.size();\n}\n\ntemplate<typename K>\nboost::tuple<std::size_t, std::size_t, std::size_t, long> test(const char* name) {\n  typedef typename K::FT FT;\n  typedef typename K::Ray_3 Ray;\n  typedef typename K::Line_3 Line;\n  typedef typename K::Point_3 Point;\n  typedef typename K::Segment_3 Segment;\n  typedef CGAL::Polyhedron_3<K> Polyhedron;\n\n  typedef CGAL::AABB_face_graph_triangle_primitive<Polyhedron> Primitive;\n  typedef CGAL::AABB_traits<K, Primitive> Traits;\n  typedef CGAL::AABB_tree<Traits> Tree;\n\n  std::ifstream ifs(name);\n\n  Polyhedron polyhedron;\n  ifs >> polyhedron;\n\n  // Random seeded to 23, cube size equal to the magic number 2\n  CGAL::Random r(23);\n  CGAL::Random_points_in_cube_3<Point, CGAL::Creator_uniform_3<FT, Point> > g( 2., r);\n\n  std::vector<Point> points;\n  points.reserve(elements * 2);\n  std::copy_n(g, elements * 2, std::back_inserter(points));\n\n  // generate a bunch of happy random primitives\n  std::vector<Line> lines;\n  lines.reserve(elements);\n\n  // forward\n  for(std::size_t i = 0; i < points.size(); i += 2)\n  {\n    lines.push_back(Line(points[i], points[i + 1]));\n  }\n\n  std::vector<Ray> rays;\n  rays.reserve(elements);\n\n  // backwards\n  for(std::size_t i = points.size(); i != 0; i -= 2)\n  {\n    rays.push_back(Ray(points[i - 1], points[i - 2]));\n  }\n\n  std::vector<Segment> segments;\n  segments.reserve(elements);\n  // from both sides\n  for(std::size_t i = 0, j = points.size() - 1; i < j; ++i, --j)\n  {\n    segments.push_back(Segment(points[i], points[j]));\n  }\n\n  Tree tree(faces(polyhedron).first, faces(polyhedron).second, polyhedron);\n\n  // filter all primitives that do not intersect\n\n  FilterP<Tree> p = { &tree };\n\n  lines.erase(std::remove_if(lines.begin(), lines.end(), p), lines.end());\n\n  rays.erase(std::remove_if(rays.begin(), rays.end(), p), rays.end());\n\n  segments.erase(std::remove_if(segments.begin(), segments.end(), p), segments.end());\n\n  boost::tuple<std::size_t, std::size_t, std::size_t, long> tu;\n\n    {\n      CGAL::Timer t;\n      t.start();\n\n      for(int i = 0; i < runs; ++i)\n      {\n        long counter = 0L;\n        tu = boost::make_tuple(intersect(lines.begin(), lines.end(), tree, counter),\n                               intersect(rays.begin(), rays.end(), tree, counter),\n                               intersect(segments.begin(), segments.end(), tree, counter),\n                               // cant use counter here\n                               0);\n        boost::get<3>(tu) = counter;\n      }\n      std::cout << t.time();\n    }\n\n  return tu;\n}\n\nint main()\n{\n  const char* filename = \"./data/finger.off\";\n\n  std::cout << \"| Simple cartesian float kernel | \";\n  boost::tuple<std::size_t, std::size_t, std::size_t, long> t1 = test<CGAL::Simple_cartesian<float> >(filename);\n  std::cout << \" | \" << std::endl;\n\n  std::cout << \"| Cartesian float kernel | \";\n  boost::tuple<std::size_t, std::size_t, std::size_t, long> t2 = test<CGAL::Cartesian<float> >(filename);\n  std::cout << \" | \" << std::endl;\n\n  std::cout << \"| Simple cartesian double kernel |\";\n  boost::tuple<std::size_t, std::size_t, std::size_t, long> t3 = test<CGAL::Simple_cartesian<double> >(filename);\n  std::cout << \" | \" << std::endl;\n\n  std::cout << \"| Cartesian double kernel |\";\n  boost::tuple<std::size_t, std::size_t, std::size_t, long> t4 = test<CGAL::Cartesian<double> >(filename);\n  std::cout << \" | \" << std::endl;\n\n  std::cout << \"| Epic kernel |\";\n  boost::tuple<std::size_t, std::size_t, std::size_t, long> t5 = test<CGAL::Exact_predicates_inexact_constructions_kernel>(filename);\n  std::cout << \" | \" << std::endl;\n\n  std::size_t a, b, c;\n  long d;\n\n  boost::tie(a, b, c, d) = t5;\n  std::cout << a << \" \" << b << \" \" << c << \" \" << d << std::endl;\n\n  boost::tie(a, b, c, d) = t4;\n  std::cout << a << \" \" << b << \" \" << c << \" \" << d << std::endl;\n\n  boost::tie(a, b, c, d) = t3;\n  std::cout << a << \" \" << b << \" \" << c << \" \" << d << std::endl;\n\n  boost::tie(a, b, c, d) = t2;\n  std::cout << a << \" \" << b << \" \" << c << \" \" << d << std::endl;\n\n  boost::tie(a, b, c, d) = t1;\n  std::cout << a << \" \" << b << \" \" << c << \" \" << d << std::endl;\n  return 0;\n}\n", "meta": {"hexsha": "73c8f7faba3abcb5246556b40de22f53aead0cd7", "size": 5392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AABB_tree/test/AABB_tree/aabb_any_all_benchmark.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T09:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-04T05:00:23.000Z", "max_issues_repo_path": "AABB_tree/test/AABB_tree/aabb_any_all_benchmark.cpp", "max_issues_repo_name": "antoniospg/cgal", "max_issues_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-10T13:32:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T12:23:20.000Z", "max_forks_repo_path": "AABB_tree/test/AABB_tree/aabb_any_all_benchmark.cpp", "max_forks_repo_name": "antoniospg/cgal", "max_forks_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T15:26:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-21T15:26:25.000Z", "avg_line_length": 28.8342245989, "max_line_length": 133, "alphanum_fraction": 0.6159124629, "num_tokens": 1588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.41271085738109664}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/experimental/models/mcgaussian1dnonstandardswaptionengine.hpp>\n#include <ql/rebatedexercise.hpp>\n\n// #include <boost/math/special_functions/laguerre.hpp>\n\nnamespace QuantLib {\n\nnamespace {\nReal basis0(const Real x) { return 1; }\nReal basis1(const Real x) { return x; }\nReal basis2(const Real x) { return x * x; }\n}\n\nGaussian1dNonstandardSwaptionPathPricer::\n    Gaussian1dNonstandardSwaptionPathPricer(\n        const boost::shared_ptr<Gaussian1dModel> &model,\n        const NonstandardSwaption::arguments *arguments,\n        const Handle<YieldTermStructure> &discount, const Handle<Quote> &oas)\n    : model_(model), arguments_(arguments), discount_(discount), oas_(oas) {\n\n    // basis functions for ls regression\n    basis_.push_back(boost::function1<Real, Real>(&basis0));\n    basis_.push_back(boost::function1<Real, Real>(&basis1));\n    basis_.push_back(boost::function1<Real, Real>(&basis2));\n\n    // minimum alive exercise index\n    Date today = Settings::instance().evaluationDate();\n    minIdxAlive_ =\n        std::upper_bound(arguments_->exercise->dates().begin(),\n                         arguments_->exercise->dates().end(), today) -\n        arguments_->exercise->dates().begin();\n}\n\nvoid Gaussian1dNonstandardSwaptionPathPricer::initExerciseIndices(\n    const Path &path) const {\n    // initialize the indices corresponding to the exercise dates\n    if (exerciseIdx_.size() == 0) {\n        for (Size i = 0, j = minIdxAlive_;\n             i < path.length() && j < arguments_->exercise->dates().size();\n             ++i) {\n            if (close(\n                    model_->stateProcess()->time(arguments_->exercise->date(j)),\n                    path.time(i))) {\n                exerciseIdx_.push_back(i);\n                ++j;\n            }\n        }\n        QL_REQUIRE(exerciseIdx_.size() ==\n                       arguments_->exercise->dates().size() - minIdxAlive_,\n                   \"did not find all future exercise dates (\"\n                       << arguments_->exercise->dates().size() - minIdxAlive_\n                       << \") in path times grid, only matched \"\n                       << exerciseIdx_.size() << \" dates and grid times.\");\n    }\n}\n\nReal Gaussian1dNonstandardSwaptionPathPricer::state(const Path &path,\n                                                    Size t) const {\n    initExerciseIndices(path);\n    return path[exerciseIdx_[t - 1]];\n}\n\nstd::vector<boost::function1<Real, Real> >\nGaussian1dNonstandardSwaptionPathPricer::basisSystem() const {\n    return basis_;\n}\n\nReal Gaussian1dNonstandardSwaptionPathPricer::operator()(const Path &path,\n                                                         Size t) const {\n\n    initExerciseIndices(path);\n\n    // in the following we have to use a standardized state\n    Real state = (path[exerciseIdx_[t - 1]] -\n                  model_->stateProcess()->expectation(\n                      0.0, 0.0, path.time(exerciseIdx_[t - 1]))) /\n                 model_->stateProcess()->stdDeviation(\n                     0.0, 0.0, path.time(exerciseIdx_[t - 1]));\n\n    // price all cashflows that belong to the exercise into right\n    // and return the deflated NPV\n    boost::shared_ptr<RebatedExercise> rebatedExercise =\n        boost::dynamic_pointer_cast<RebatedExercise>(arguments_->exercise);\n    Date exDate = arguments_->exercise->date(minIdxAlive_ + (t - 1));\n    boost::shared_ptr<NonstandardSwap> swap = arguments_->swap;\n    Schedule fixedSchedule = swap->fixedSchedule();\n    Schedule floatingSchedule = swap->floatingSchedule();\n    Size j1 = std::upper_bound(fixedSchedule.dates().begin(),\n                               fixedSchedule.dates().end(), exDate - 1) -\n              fixedSchedule.dates().begin();\n    Size k1 = std::upper_bound(floatingSchedule.dates().begin(),\n                               floatingSchedule.dates().end(), exDate - 1) -\n              floatingSchedule.dates().begin();\n\n    // this is more or less copied from gaussian1dnonstandardswaptionengine.cpp\n    Real floatingLegNpv = 0.0;\n    for (Size l = k1; l < arguments_->floatingCoupons.size(); l++) {\n        Real zSpreadDf =\n            oas_.empty()\n                ? 1.0\n                : std::exp(-oas_->value() *\n                           (model_->termStructure()->dayCounter().yearFraction(\n                               exDate, arguments_->floatingPayDates[l])));\n        Real amount;\n        if (arguments_->floatingIsRedemptionFlow[l])\n            amount = arguments_->floatingCoupons[l];\n        else\n            amount = arguments_->floatingNominal[l] *\n                     arguments_->floatingAccrualTimes[l] *\n                     (arguments_->floatingGearings[l] *\n                          model_->forwardRate(\n                              arguments_->floatingFixingDates[l], exDate, state,\n                              arguments_->swap->iborIndex()) +\n                      arguments_->floatingSpreads[l]);\n        floatingLegNpv +=\n            amount *\n            model_->deflatedZerobond(arguments_->floatingPayDates[l], exDate,\n                                     state, discount_, discount_) *\n            zSpreadDf;\n    }\n    Real fixedLegNpv = 0.0;\n    for (Size l = j1; l < arguments_->fixedCoupons.size(); l++) {\n        Real zSpreadDf =\n            oas_.empty()\n                ? 1.0\n                : std::exp(-oas_->value() *\n                           (model_->termStructure()->dayCounter().yearFraction(\n                               exDate, arguments_->fixedPayDates[l])));\n        fixedLegNpv +=\n            arguments_->fixedCoupons[l] *\n            model_->deflatedZerobond(arguments_->fixedPayDates[l], exDate,\n                                     state, discount_, discount_) *\n            zSpreadDf;\n    }\n    Real rebate = 0.0;\n    Real zSpreadDf = 1.0;\n    Date rebateDate = exDate;\n    if (rebatedExercise != NULL) {\n        rebate = rebatedExercise->rebate(minIdxAlive_ + (t - 1));\n        rebateDate = rebatedExercise->rebatePaymentDate(minIdxAlive_ + (t - 1));\n        zSpreadDf =\n            oas_.empty()\n                ? 1.0\n                : std::exp(-oas_->value() *\n                           (model_->termStructure()->dayCounter().yearFraction(\n                               exDate, rebateDate)));\n    }\n    Real exerciseValue =\n        std::max(((arguments_->type == VanillaSwap::Payer ? 1.0 : -1.0) *\n                      (floatingLegNpv - fixedLegNpv) +\n                  rebate *\n                      model_->deflatedZerobond(rebateDate, exDate, state,\n                                               discount_, discount_) *\n                      zSpreadDf),\n                 0.0);\n\n    return exerciseValue;\n}\n\n} // namespace QuantLib\n", "meta": {"hexsha": "526620ce70d3ac175aabd6724b6fe240a4dd2c2f", "size": 7474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/mcgaussian1dnonstandardswaptionengine.cpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/experimental/models/mcgaussian1dnonstandardswaptionengine.cpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/experimental/models/mcgaussian1dnonstandardswaptionengine.cpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 41.5222222222, "max_line_length": 80, "alphanum_fraction": 0.5816162697, "num_tokens": 1702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.41270474686468245}}
{"text": "/*\n * CurrentFlowGroupCloseness.cpp\n *\n *      Author: gstoszek\n */\n\n#include \"CurrentFlowGroupCloseness.h\"\n#include \"Centrality.h\"\n#include \"../algebraic/CSRMatrix.h\"\n#include \"../numerics/LAMG/Lamg.h\"\n#include \"../auxiliary/Log.h\"\n#include <chrono>\n#include <stdlib.h>\n#include <cmath>\n#include <algorithm>\n#include \"EffectiveResistanceDistance.h\"\n#include \"ERDLevel.h\"\n#include \"../components/ConnectedComponents.h\"\n#include <armadillo>\n\nnamespace NetworKit {\n\n   CurrentFlowGroupCloseness::CurrentFlowGroupCloseness(Graph& G,const count k, const count CB,const double epsilon) : G(G),k(k),CB(CB),epsilon(epsilon){\n     if (G.isDirected()) throw std::runtime_error(\"Graph is directed graphs!\");\n     ConnectedComponents cc(G);\n     cc.run();\n     if (cc.getPartition().numberOfSubsets() > 1) throw std::runtime_error(\"Graph has more then one component!\");\n     if(k>=G.numberOfNodes()) throw std::runtime_error(\"Size of Group greater then number of nodes!\");\n\n     auto start = std::chrono::high_resolution_clock::now();\n     auto end = std::chrono::high_resolution_clock::now();\n     std::chrono::duration<double> diff;\n\n     numberOfCoarsedNodes=0;\n     S.resize(k);\n     n=G.numberOfNodes();\n\n     end = std::chrono::high_resolution_clock::now();\n     diff = end-start;\n     std::cout << \"Constructor finished in \" << diff.count() << \"(s)\" << \"\\n\\n\";\n           std::cout << \"Number of Nodes=\" << G.numberOfNodes() << \"\\n\";\n   }\n\n   void CurrentFlowGroupCloseness::run() {\n     bool coarse;\n     count ID;\n     count minDegree;\n     auto start = std::chrono::high_resolution_clock::now();\n     auto end = std::chrono::high_resolution_clock::now();\n     std::chrono::duration<double> diff;\n     std::vector<std::tuple<count,count,count>> c_indices;\n     arma::Mat<double> L;\n     ID=0;\n     if(CB>0){\n       ID++;\n       minDegree=1;\n       mergePeripheralNodes();\n       ID++;\n       minDegree=updateMinDegree();\n       coarse=true;\n       while((minDegree<CB)&&(coarse)){\n         c_indices=coarsingIndices(minDegree, false);\n         coarseGraph(c_indices,ID);\n         ID++;\n         minDegree=updateMinDegree();\n\n         if(!(c_indices.size()>1)||!(G.numberOfNodes()>k)){\n           coarse=false;\n         }\n        }\n      }\n      end = std::chrono::high_resolution_clock::now();\n      diff = end-start;\n      std::cout << \"Coarsening \" << diff.count() << \"(s)\" << \"\\n\\n\";\n      std::cout << \"Laplacian size afvoidter coarsening\" << L.n_rows << \"\\n\";\n      start = std::chrono::high_resolution_clock::now();\n      /*changed\n      //ERD.computeFromLaplacian(vecOfNodes,L);\n      */\n      L=computePinvOfLaplacian();\n      end = std::chrono::high_resolution_clock::now();\n      diff = end-start;\n      std::cout << \"Initial EffectiveResistanceDistanceMatrix finished in \" << diff.count() << \"(s)\" << \"\\n\\n\";\n      //greedy();\n      //std::cout<<\"Level:\" <<ID<<\" with the value: \" << CFGCC << \"\\n\";\n      start = std::chrono::high_resolution_clock::now();\n      /*\n      if(CB>1){\n        ID=LevelList[LevelList.size()-1].getID();\n        std::cout<<\"ID=\"<<ID<<\"\\n\";\n        while(ID>1){\n          uncoarseEfffectiveResistanceDistanceMatrix(ID);\n          //greedy();\n          //std::cout<<\"Level:\" <<ID<<\" with the value: \" << CFGCC << \"\\n\";\n          ID--;\n        }\n      }\n      */\n      end = std::chrono::high_resolution_clock::now();\n      diff = end-start;\n      std::cout << \"Uncoarsening in \" << diff.count() << \"(s)\" << \"\\n\\n\";\n      start = std::chrono::high_resolution_clock::now();\n      greedy(L);\n      end = std::chrono::high_resolution_clock::now();\n      diff = end-start;\n      std::cout << \"Greedy in \" << diff.count() << \"(s)\" << \"\\n\\n\";\n    }\n    std::vector<node> CurrentFlowGroupCloseness::getNodesofGroup(){\n      return S;\n    }\n    double CurrentFlowGroupCloseness::getCFGCC() {\n      return CFGCC;\n    }\n    void CurrentFlowGroupCloseness::greedy(arma::Mat<double> L){\n      count sampleSize;\n      node s,v,w;\n      double centrality,prevCFGCC,bestMarginalGain,distance;\n      std::vector<bool> V;\n      std::vector<node> vecOfNodes,vecOfSamples, vecOfPeriphs;\n      std::vector<count> reverse;\n      std::vector<double> mindst, dst, bst, zeroVec, marginalGain;\n\n      vecOfSamples.resize(0);\n      vecOfPeriphs.resize(0);\n      vecOfNodes = G.nodes();\n      reverse.resize(G.upperNodeIdBound());\n      for(count i=0;i<vecOfNodes.size();i++){\n        reverse[vecOfNodes[i]]=i;\n      }\n\n      for(count i=0;i<vecOfNodes.size();i++){\n        v=vecOfNodes[i];\n        if(vecOfPeripheralNodes[v])\n          vecOfPeriphs.push_back(v);\n        else{\n          vecOfSamples.push_back(v);\n        }\n      }\n      sampleSize=(count)(log(vecOfSamples.size())/(2*epsilon*epsilon));\n      if(sampleSize>vecOfSamples.size()){\n        sampleSize=vecOfSamples.size();\n      }\n      CFGCC=n*n*n;\n      prevCFGCC=CFGCC;\n      V.resize(G.numberOfNodes(),true);\n      mindst.resize(G.numberOfNodes(),n*n);\n      zeroVec.resize(G.numberOfNodes(),0.);\n      marginalGain.resize(G.numberOfNodes(),CFGCC);\n      for(count i=0;i<k;i++){\n        std::random_shuffle (vecOfSamples.begin(), vecOfSamples.end());\n        bestMarginalGain=0.;\n        for (count j=0; j<vecOfSamples.size();j++) {\n          v=vecOfSamples[j];\n          if(V[v] && (bestMarginalGain<marginalGain[v])){\n            dst=mindst;\n            centrality = 0.;\n            for (count l = 0; l < sampleSize; l++) {\n              w=vecOfSamples[l];\n              distance=L(reverse[v],reverse[v])+L(reverse[w],reverse[w])-2*L(reverse[v],reverse[w]);\n              if (distance< mindst[w]){\n                dst[w]=distance;\n              }\n              centrality +=dst[w];\n            }\n            centrality*=((double)(vecOfSamples.size()+numberOfCoarsedNodes)/(double)(sampleSize));\n            for (count l = 0 ; l < vecOfPeriphs.size(); l++) {\n              w=vecOfPeriphs[l];\n              distance=L(reverse[v],reverse[v])+L(reverse[w],reverse[w])-2*L(reverse[v],reverse[w]);\n              if (distance< mindst[w]){\n                dst[w]=distance;\n              }\n              centrality += dst[w];\n            }\n            marginalGain[v]=prevCFGCC-centrality;\n            if (centrality < CFGCC) {\n              CFGCC = centrality;\n              bst=dst;\n              s = v;\n              bestMarginalGain=marginalGain[v];\n            }\n            //std::cout<<\"c(\"<<v<<\")\"<<centrality<<\"\\n\";\n          }\n        }\n        S[i]=s;\n        V[s]=false;\n        mindst=bst;\n        prevCFGCC=CFGCC;\n      }\n     CFGCC = (double)(n)/CFGCC;\n    }\n    count CurrentFlowGroupCloseness::updateMinDegree(){\n      bool search;\n      count min;\n      count i;\n      std::vector<node> vecOfNodes;\n      node v;\n      search=true;\n      min=n;\n      i=0;\n      vecOfNodes=G.nodes();\n      while((i<vecOfNodes.size())&&(search)){\n        v=vecOfNodes[i];\n        if((G.degree(v)<min) && (G.degree(v)>1)){\n          min=G.degree(v);\n          if(min==2){\n            search=false;\n          }\n        }\n        i++;\n      }\n      return min;\n    }\n    std::vector<std::tuple<count,count,count>> CurrentFlowGroupCloseness::coarsingIndices(count courseningDegree, bool Random){\n        bool search;\n        count c_i,s_i,w_i,l;\n        node c,s,w;\n        std::vector<bool> vecOfFreeNodes;\n        std::vector<node> vecOfNodes, vecOfCoarseNodes, vecOfNeighbours;\n        std::vector<std::tuple<count,count,count>> indices;\n\n        vecOfCoarseNodes.resize(0);\n        vecOfFreeNodes.resize(G.upperNodeIdBound(),true);\n\n        vecOfNodes=G.nodes();\n        for(count i=0;i<vecOfNodes.size();i++){\n          c=vecOfNodes[i];\n          if(G.degree(c)==courseningDegree){\n            vecOfCoarseNodes.push_back(i);\n          }\n        }\n        if(Random){\n          std::random_shuffle (vecOfCoarseNodes.begin(), vecOfCoarseNodes.end());\n        }\n        for(count i=0;i<vecOfCoarseNodes.size();i++){\n          c=vecOfCoarseNodes[i];\n          if(vecOfFreeNodes[c]){\n            search=true;\n            l=0;\n            vecOfNeighbours=G.neighbors(c);\n            while((search)&&(l<vecOfNeighbours.size())){\n              s=vecOfNeighbours[l];\n              if(vecOfFreeNodes[s]){\n                l++;\n                while((search)&&(l<vecOfNeighbours.size())){\n                  w=vecOfNeighbours[l];\n                  if(vecOfFreeNodes[w]){\n                    vecOfFreeNodes[s]=false;\n                    vecOfFreeNodes[c]=false;\n                    vecOfFreeNodes[w]=false;\n                    search=false;\n                    indices.push_back(std::make_tuple(c,s,w));\n                  }\n                  else{\n                    l++;\n                  }\n                }\n              }\n              else{\n                l++;\n              }\n            }//End while\n          }\n        }\n        return indices;\n      }\n    /**************************************************************************\n    void CurrentFlowGroupCloseness::uncoarseEfffectiveResistanceDistanceMatrix(count ID){\n      bool search;\n      count l,j;\n      node c,s,w;\n      double edgeWeightcs,edgeWeightcw,edgeWeightsw;\n      std::vector<std::tuple<node,node,count,double,double,double>> vecOfTriangles;\n      std::tuple<node,node,count,double,double,double> triangle;\n\n      vecOfTriangles=LevelList[ID-1].getVecOfTriangles();\n      for(count i=0;i<vecOfTriangles.size();i++){\n        j=vecOfTriangles.size()-1-i;\n        triangle=vecOfTriangles[j];\n        ERD.uncoarseTriangle(vecOfNodes,triangle);\n        c=std::get<0>(triangle);\n        s=std::get<1>(triangle);\n        w=std::get<2>(triangle);\n        edgeWeightcs=std::get<3>(triangle);\n        edgeWeightcw=std::get<4>(triangle);\n        edgeWeightsw=1./edgeWeightcs+1./edgeWeightsw;\n        edgeWeightsw=1./edgeWeightsw;\n        //vecOfNodes.push_back(c);\n        //Adj[s].push_back (c);\n        //Adj[c].push_back(s);\n        if(std::get<4>(triangle)>0){\n          //Adj[c].push_back (w);\n          //Adj[w].push_back(c);\n        }\n        if(!(std::get<5>(triangle)==edgeWeightsw)){\n          search = true;\n          l= 0;\n          while((l<Adj[s].size())&&(search)){\n            if(Adj[s][l]==w){\n              Adj[s].erase(Adj[s].begin()+l);\n              search=false;\n            }\n            else{\n              l++;\n            }\n          }//end while\n          search = true;\n          l= 0;\n          while((l<Adj[w].size())&&(search)){\n            if(Adj[w][l]==s){\n                Adj[w].erase(Adj[w].begin()+l);\n                search=false;\n              }\n          else{\n            l++;\n          }\n          }//end while\n        }//end if\n        numberOfCoarsedNodes--;\n      }//end for\n    }\n    /***************************************************************************/\n    void CurrentFlowGroupCloseness::mergePeripheralNodes(){\n      bool search;\n      count l;\n      node c,s,w;\n      double edgeWeightcs,edgeWeightss,edgeWeightsw;\n      std::vector<node> vecOfNodes,vecOfSupernodes;\n      std::vector<std::pair<node,node>> mapping;\n      std::vector<std::tuple<node,node,node,double,double,double>> vecOfTriangles;\n\n      vecOfNodes=G.nodes();\n      vecOfSupernodes.resize(0);\n      mapping.resize(0);\n      vecOfTriangles.resize(0);\n      for(count c_i=0;c_i<vecOfNodes.size();c_i++){\n        c=vecOfNodes[c_i];\n        if(G.degree(c)==1){\n          s=G.randomNeighbor(c);\n          if(std::find(vecOfSupernodes.begin(), vecOfSupernodes.end(), s) == vecOfSupernodes.end()){\n            vecOfSupernodes.push_back(s);\n            mapping.push_back (std::make_pair(s,c));\n            vecOfPeripheralNodes[c]=true;\n          }\n          else{\n            search = true;\n            l= 0;\n            while(search){\n              if(vecOfSupernodes[l]==s){\n                w=mapping[l].second;\n                search=false;\n              }\n              l++;\n            }//end while\n            edgeWeightcs=G.weight(c,s);\n            edgeWeightsw=G.weight(s,w);\n            edgeWeightsw=1./edgeWeightcs+1./edgeWeightsw;\n            edgeWeightsw=1./edgeWeightsw;\n            G.setWeight(s,w,edgeWeightsw);\n            G.removeNode(c);\n            vecOfTriangles.push_back(std::make_tuple(c,s,w,edgeWeightcs,0.,edgeWeightsw));\n          }//end else\n        }\n      }\n      ERDLevel Level(1,vecOfTriangles);\n      LevelList.push_back(Level);\n    }\n    /***************************************************************************/\n    void CurrentFlowGroupCloseness::coarseGraph(std::vector<std::tuple<count,count,count>> matchings,count ID){\n      bool search;\n      count a,l,c_i,s_i,w_i;\n      node c,s,w;\n      double edgeWeightcs,edgeWeightcw,edgeWeightsw;\n      std::vector<node> vecOfNodes;\n      std::vector<std::tuple<node,node,node,double,double,double>> vecOfTriangles;\n\n      vecOfNodes=G.nodes();\n      vecOfTriangles.resize(0);\n\n      for(count i=0;i<matchings.size();i++){\n        search=false;\n        c=std::get<0>(matchings[i]);\n        s=std::get<1>(matchings[i]);\n        w_i=std::get<2>(matchings[i]);\n        w=vecOfNodes[w_i];\n        edgeWeightcs=G.weight(c,s);\n        edgeWeightcw=G.weight(c,w);\n        edgeWeightsw=1./edgeWeightcs+1/edgeWeightcw;\n        edgeWeightsw=1./edgeWeightsw;\n        edgeWeightsw+=G.weight(s,w);\n        G.setWeight(s,w,edgeWeightsw);\n        vecOfTriangles.push_back(std::make_tuple(c,s,w,edgeWeightcs,edgeWeightcw,edgeWeightsw));\n        G.removeNode(c);\n        numberOfCoarsedNodes++;\n      }\n      /*\n      arma::uvec indices(vecOfNodes.size()-matchings.size());\n      a=0;\n      l=0;\n      for(count i=0;i<vecOfNodes.size();i++){\n        if(std::get<0>(matchings[l])==i){\n          if(l<matchings.size()-1)\n            l++;\n        }\n        else{\n          indices(a)=i;\n          a++;\n        }\n      }\n      for(count i=0;i<matchings.size();i++){\n        vecOfNodes.erase(vecOfNodes.begin()+std::get<0>(matchings[i])-i);\n      }\n      L=L.submat(indices, indices);\n      */\n      ERDLevel Level(ID,vecOfTriangles);\n      LevelList.push_back(Level);\n    }\n\n    arma::Mat<double> CurrentFlowGroupCloseness::computePinvOfLaplacian(){\n      node v;\n      node w;\n      count n;\n      double factor;\n      std::vector<node> vecOfNodes;\n      vecOfNodes=G.nodes();\n      n=vecOfNodes.size();\n      arma::Mat<double> L(n,n);\n      L.zeros();\n      for(count i=0;i<n;i++){\n        v=vecOfNodes[i];\n        for(count j=i+1;j<n;j++){\n          w=vecOfNodes[j];\n          if(G.hasEdge(v,w)){\n            L(i,j)=-G.weight(v,w);\n            L(j,i)=-G.weight(v,w);\n            L(i,i)+=G.weight(v,w);\n            L(j,j)+=G.weight(v,w);\n          }\n        }\n      }\n      arma::Mat<double> J(n,n);\n      factor=1./n;\n      J.fill(factor);\n      L= L+J;\n      L=arma::inv_sympd(L);\n      L= L-J;\n      return L;\n    }\n} /* namespace NetworKit*/\n", "meta": {"hexsha": "908ad39d512b5c3ef0da1bd6c0513ef948c993ca", "size": 14753, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "networkit/cpp/coarsening/CurrentFlowGroupCloseness.cpp", "max_stars_repo_name": "gstoszek/networkit", "max_stars_repo_head_hexsha": "5f4e7b9a0f8a431465911209d41e0c73f9bf0df0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "networkit/cpp/coarsening/CurrentFlowGroupCloseness.cpp", "max_issues_repo_name": "gstoszek/networkit", "max_issues_repo_head_hexsha": "5f4e7b9a0f8a431465911209d41e0c73f9bf0df0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "networkit/cpp/coarsening/CurrentFlowGroupCloseness.cpp", "max_forks_repo_name": "gstoszek/networkit", "max_forks_repo_head_hexsha": "5f4e7b9a0f8a431465911209d41e0c73f9bf0df0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8574610245, "max_line_length": 153, "alphanum_fraction": 0.5322985156, "num_tokens": 3748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4127047468646824}}
{"text": "// This file is part of LatNet Builder.\n//\n// Copyright (C) 2012-2021  The LatNet Builder author's, supervised by Pierre L'Ecuyer, Universite de Montreal.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"latbuilder/SizeParam.h\"\n#include \"latbuilder/Util.h\"\n#include \"latticetester/Util.h\"\n#include \"latticetester/IntFactor.h\"\n#include <NTL/GF2XFactoring.h>\n\nnamespace LatBuilder {\n\n//===============================================================================================================\ntemplate<>\nSizeParam<LatticeType::ORDINARY,EmbeddingType::MULTILEVEL>::SizeParam(uInteger primeBase, Level maxLevel):\n   BasicSizeParam<SizeParam<LatticeType::ORDINARY,EmbeddingType::MULTILEVEL>>(primeBase == 0 ? 0 : intPow(primeBase, maxLevel)),\n   m_base(primeBase),\n   m_maxLevel(maxLevel)\n{\n   if (primeBase >= 2 and LatticeTester::IntFactor<std::int64_t>::isPrime(primeBase, 0) == LatticeTester::COMPOSITE)\n      throw std::invalid_argument(\"SizeParam: primeBase is not prime\");\n}\n\ntemplate<>\nSizeParam<LatticeType::POLYNOMIAL,EmbeddingType::MULTILEVEL>::SizeParam(Polynomial primeBase, Level maxLevel):\n   BasicSizeParam<SizeParam<LatticeType::POLYNOMIAL,EmbeddingType::MULTILEVEL>>(IsZero(primeBase) ? Polynomial(0) : intPow(primeBase, maxLevel)),\n   m_base(primeBase),\n   m_maxLevel(maxLevel)\n{\n   if ( !IterIrredTest(primeBase))\n      throw std::invalid_argument(\"SizeParam: primeBase is not prime\");\n\n}\n\ntemplate<>\nSizeParam<LatticeType::DIGITAL,EmbeddingType::MULTILEVEL>::SizeParam(uInteger primeBase, Level maxLevel):\n   BasicSizeParam<SizeParam<LatticeType::DIGITAL,EmbeddingType::MULTILEVEL>>(primeBase == 0 ? 0 : intPow(primeBase, maxLevel)),\n   m_base(primeBase),\n   m_maxLevel(maxLevel)\n{\n   if (primeBase >= 2 and LatticeTester::IntFactor<std::int64_t>::isPrime(primeBase, 0) == LatticeTester::COMPOSITE)\n      throw std::invalid_argument(\"SizeParam: primeBase is not prime\");\n}\n\n//===================================================================================================================\n\ntemplate<>\nSizeParam<LatticeType::ORDINARY,EmbeddingType::MULTILEVEL>::SizeParam(uInteger numPoints):\n   BasicSizeParam<SizeParam<LatticeType::ORDINARY,EmbeddingType::MULTILEVEL>>(numPoints)\n{\n   if (numPoints == 0) {\n      m_base = 0;\n      m_maxLevel = 0;\n   }\n   else if (numPoints == 1) {\n      m_base = 1;\n      m_maxLevel = 0;\n   }\n   else {\n      const auto factors = primeFactorsMap(numPoints);\n      if (factors.size() != 1)\n         throw std::runtime_error(\"not an integer power of a prime base\");\n      const auto& factor = *factors.begin();\n      m_base = factor.first;\n      m_maxLevel = factor.second;\n   }\n}\n\ntemplate<>\nSizeParam<LatticeType::POLYNOMIAL,EmbeddingType::MULTILEVEL>::SizeParam(Polynomial modulus):\n   BasicSizeParam<SizeParam<LatticeType::POLYNOMIAL,EmbeddingType::MULTILEVEL>>(modulus)\n{\n   if (IsZero(modulus)) {\n      m_base = Polynomial(0);\n      m_maxLevel = 0;\n   }\n   else {\n      NTL::vector< NTL::Pair< Polynomial, long > > factors ;\n      CanZass(factors, modulus); // calls \"Cantor/Zassenhaus\" algorithm from <NTL/GF2XFactoring.h>\n      if (factors.size() != 1)\n         throw std::runtime_error(\"not an integer power of a prime base\");\n      const auto& factor = *factors.begin();\n      m_base = factor.a; // = factor.first\n      m_maxLevel = factor.b; // = factor.second\n   }\n}\n\ntemplate<>\nSizeParam<LatticeType::DIGITAL,EmbeddingType::MULTILEVEL>::SizeParam(uInteger numPoints):\n   BasicSizeParam<SizeParam<LatticeType::DIGITAL,EmbeddingType::MULTILEVEL>>(numPoints)\n{\n   if (numPoints == 0) {\n      m_base = 0;\n      m_maxLevel = 0;\n   }\n   else if (numPoints == 1) {\n      m_base = 1;\n      m_maxLevel = 0;\n   }\n   else {\n      const auto factors = primeFactorsMap(numPoints);\n      if (factors.size() != 1)\n         throw std::runtime_error(\"not an integer power of a prime base\");\n      const auto& factor = *factors.begin();\n      m_base = factor.first;\n      m_maxLevel = factor.second;\n   }\n}\n\n//=======================================================================================================================\n\ntemplate<>\nSizeParam<LatticeType::ORDINARY,EmbeddingType::MULTILEVEL>::size_type\nSizeParam<LatticeType::ORDINARY,EmbeddingType::MULTILEVEL>::numPointsOnLevel(Level level) const\n{\n   if (level > maxLevel())\n      throw std::invalid_argument(\"level > maxLevel\");\n   return base() == 0 ? 0 : intPow(base(), level);\n}\n\ntemplate<>\nSizeParam<LatticeType::POLYNOMIAL,EmbeddingType::MULTILEVEL>::size_type\nSizeParam<LatticeType::POLYNOMIAL,EmbeddingType::MULTILEVEL>::numPointsOnLevel(Level level) const\n{\n   if (level > maxLevel())\n      throw std::invalid_argument(\"level > maxLevel\");\n   return IsZero(base())  ? 0 : intPow( 2, deg(base())*level );\n}\n\ntemplate<>\nSizeParam<LatticeType::DIGITAL,EmbeddingType::MULTILEVEL>::size_type\nSizeParam<LatticeType::DIGITAL,EmbeddingType::MULTILEVEL>::numPointsOnLevel(Level level) const\n{\n   if (level > maxLevel())\n      throw std::invalid_argument(\"level > maxLevel\");\n   return base() == 0 ? 0 : intPow(base(), level);\n}\n//========================================================================================================================\n\ntemplate<>\nsize_t\nSizeParam<LatticeType::ORDINARY,EmbeddingType::MULTILEVEL>::totient() const\n{ return base() == 0 ? 0 : (base() - 1) * this->numPoints() / base(); }\n\ntemplate<>\nsize_t\nSizeParam<LatticeType::POLYNOMIAL,EmbeddingType::MULTILEVEL>::totient() const\n{ return IsZero(base()) == 0 ? 0 : (intPow(2,deg(base())) - 1) * this->numPoints() / intPow(2,deg(base())); }\n\n//=========================================================================================================================\n\ntemplate<LatticeType LR>\nvoid\nSizeParam<LR,EmbeddingType::MULTILEVEL>::normalize(Real& merit) const\n{ merit /= this->numPoints(); }\n\ntemplate<LatticeType LR>\nvoid\nSizeParam<LR,EmbeddingType::MULTILEVEL>::normalize(RealVector& merit) const\n{\n   if (merit.size() != maxLevel() + 1)\n      throw std::logic_error(\"merit vector size and maximum level do not match\");\n   for (Level level = 0; level < merit.size(); level++)\n      merit[level] /= numPointsOnLevel(level);\n}\n//===========================================================================================================================\ntemplate<LatticeType LR>\nstd::ostream&\nSizeParam<LR,EmbeddingType::MULTILEVEL>::format(std::ostream& os) const\n{ os << base(); if (maxLevel() != 1) os << \"^\" << maxLevel(); return os; }\n//===========================================================================================================================\n\ntemplate class SizeParam<LatticeType::ORDINARY,EmbeddingType::MULTILEVEL>;\ntemplate class SizeParam<LatticeType::POLYNOMIAL,EmbeddingType::MULTILEVEL>;\ntemplate class SizeParam<LatticeType::DIGITAL,EmbeddingType::MULTILEVEL>;\n\n}\n\n", "meta": {"hexsha": "337fff68f664ba60257f90cfe3a69b70391ef067", "size": 7321, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LatBuilder/SizeParam-EMBEDDED.cc", "max_stars_repo_name": "YochevedDarmon/latnetbuilder", "max_stars_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LatBuilder/SizeParam-EMBEDDED.cc", "max_issues_repo_name": "YochevedDarmon/latnetbuilder", "max_issues_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LatBuilder/SizeParam-EMBEDDED.cc", "max_forks_repo_name": "YochevedDarmon/latnetbuilder", "max_forks_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3298429319, "max_line_length": 145, "alphanum_fraction": 0.6265537495, "num_tokens": 1846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660687, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4127047403242568}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <complex>\n#include <cstdlib>\n#include <ctime>\nusing namespace std;\nusing namespace arma;\n\nint main() {\n\t// Input: sizeCells of lattice in z direction and # of k-points in the direction of kPointVec\n\tint sizeCells = 5;\n\tint k_points_max=1+19*1;\n\trowvec kPointVec(3); // Defined below\n\n\t// Parameters for the Hamiltonian and data structures (Don't need to change those)\n\tdouble tHopping = 1;\n\tdouble deltatHopping = 0.4; \n\tcomplex<double> spinOrbitCoupling(0,1); \n\n\t// Misc\n\tdouble delta = 0.01; // small number for numerical comparisons\n\tint index =0;\n\tconst complex<double> ii(0, 1);\n\n\t// Geometry\n\tdouble latVecNorm=1/sqrt(2); // cubic cell size a = 1\n\tdouble sublatVecNorm=sqrt(3)/4;\n\tint nSites=3*sizeCells;\n\n\trowvec dummyVec(3), dummyVec2(3), dummyVec3(3), dummyVec4(3);\n\tcx_mat dummyMat(2,2);\n\tmat sublatOne(nSites, 4); // Sites at origin of a unit cell\n\tmat sublatTwo(nSites, 4); // Sites at sublatVec in a unit cell\n\trowvec sublatVec(3); // 2nd lattice site within a unit cell\n\trowvec latVec1(3), latVec2(3), latVec3(3), latVec4(3), latVec5(3); // lattice vectors\n\trowvec bulklatVec1(3), bulklatVec2(3), bulklatVec3(3), GVec1(3), GVec2(3);\n\tsublatVec << 0.25 << 0.25 << 0.25; \n\tbulklatVec1 << 0 << 0.5 << 0.5;\n\tbulklatVec2 << 0.5 << 0 << 0.5;\n\tbulklatVec3 << 0.5 << 0.5 << 0;\n\n\t// Variables below are needed for periodic b.c.s\n\t// Unit cell\n\tlatVec1 << 0.5 << -0.5 << 0;\n\tlatVec2 << 0 << 0.5 << -0.5;\n\tlatVec3 << 1 << 1 << 1;\n\t// Two more atoms from sublattice One within the primary unit cell\n\tlatVec4 << 0 << 0.5 << 0.5;\n\tlatVec5 << 0.5 << 1 << 0.5;\n\t// Reciprocal lattice vectors for slab\n\tGVec1 << 4*M_PI/3 << -2*M_PI/3 << -2*M_PI/3;\n\tGVec2 << 2*M_PI/3 << 2*M_PI/3 << -4*M_PI/3;\n\n\t// Define Pauli matrices\n\tcx_mat unity(2,2), sigma_x(2,2), sigma_y(2,2), sigma_z(2,2); // Pauli matrices  \n\tmat dummy_unity(2,2), dummy_sigma_x(2,2), dummy_sigma_y(2,2), dummy_sigma_z(2,2);\n\tdummy_unity(0,0)=1; dummy_unity(1,1)=1; dummy_sigma_x(1,0)=1; dummy_sigma_x(0,1)=1;\n\tdummy_sigma_y(0,1)=-1; dummy_sigma_y(1,0)=1; dummy_sigma_z(0,0)=1; dummy_sigma_z(1,1)=-1;\n\tunity.set_real(dummy_unity);\n\tsigma_x.set_real(dummy_sigma_x);\n\tsigma_y.set_imag(dummy_sigma_y);\n\tsigma_z.set_real(dummy_sigma_z);\n\n\t// Set up data structures for the slab\n\tcx_mat Hamiltonian(4*nSites,4*nSites);\n\tHamiltonian.zeros();\n\tvec eigvals(4*nSites);\n\tcx_mat eigvecs(4*nSites,4*nSites);\n\tmat bandstructure(k_points_max,4*nSites);\n\n\t// Set up primary unit cell of the slab\n\tfor (int k=0; k<sizeCells; k++) {\n\t\tdummyVec=k*latVec3;\n\t\tsublatOne(index,0)=99; sublatOne(index+1,0)=99; sublatOne(index+2,0)=99;\n\t\tsublatOne(index,span(1,3))=dummyVec;\n\t\tsublatOne(index+1,span(1,3))=(dummyVec+latVec4);\n\t\tsublatOne(index+2,span(1,3))=(dummyVec+latVec5);\n\t\tsublatTwo(index,0)=99; sublatTwo(index+1,0)=99; sublatTwo(index+2,0)=99;\n\t\tsublatTwo(index,span(1,3))=(dummyVec+sublatVec);\n\t\tsublatTwo(index+1,span(1,3))=(dummyVec+latVec4+sublatVec);\n\t\tsublatTwo(index+2,span(1,3))=(dummyVec+latVec5+sublatVec);\n\t\tindex=index+3;\n\t}\n\n\t// Loop over k-points\n\tfor (int m=0; m<k_points_max; m++ ){\n\t\tkPointVec=GVec1*m/20;\n\n\t\t// Set up the Hamiltonian in a different way (results equivalent)\n\t\tfor (int n=0; n<nSites; n++){\n\t\t\t// Go over unit cells in width (i,j; periodic), height (k) and across sites in each cell (l)\n\t\t\tfor (int i=-2; i<3; i++) {\n\t\t\t\tfor (int j=-2; j<3; j++) {\n\t\t\t\t\tfor (int k=0; k<sizeCells; k++) {\n\t\t\t\t\t\tfor (int l=0; l<3; l++) {\n\t\t\t\t\t\t\tswitch(l) {\n\t\t\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\t\t\tdummyVec=i*latVec1+j*latVec2+k*latVec3-sublatOne(n,span(1,3));\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\t\t\tdummyVec=i*latVec1+j*latVec2+k*latVec3+latVec4-sublatOne(n,span(1,3));\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\t\t\tdummyVec=i*latVec1+j*latVec2+k*latVec3+latVec5-sublatOne(n,span(1,3));\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\tcout << \"Error, l should be 0,1,2\" << endl;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdummyVec2=dummyVec+sublatVec; // used to find hoppings between sublattices\n\t\t\t\t\t\t\tindex=3*k+l; // used when have a site within primary cell \n\t\t\t\t\t\t\tdummyVec3=i*latVec1+j*latVec2; // used if have an atom outside primary cell\n\t\t\t\t\t\t\tdummyVec4=dummyVec+sublatOne(n,span(1,3))-sublatTwo(n,span(1,3));\n\n\t\t\t\t\t\t\t// Set up nearest neighbour hoppings (between sublattices)\n\t\t\t\t\t\t\t// Set up hoppings into sublatOne\n\t\t\t\t\t\t\tif (dot(dummyVec2, dummyVec2) < sublatVecNorm*sublatVecNorm+delta) {\n\t\t\t\t\t\t\t\t// hopping to the n-th site from along [111] within the primary cell\n\t\t\t\t\t\t\t\tif (dot(dummyVec, dummyVec) < delta) {\n\t\t\t\t\t\t\t\t\tHamiltonian(span(4*n+0,4*n+1),span(4*index+2,4*index+3))+=(tHopping+deltatHopping)*unity;\n\t\t\t\t\t\t\t\t\tif (n != index || i!=0 || j!=0) {cout << \"Error for deltatHopping\" << endl; }\n\t\t\t\t\t\t\t\t\t// hopping in other directions\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif (i==0 && j==0) {\n\t\t\t\t\t\t\t\t\t\t// Hoppings withing the primary cell\n\t\t\t\t\t\t\t\t\t\tHamiltonian(span(4*n+0,4*n+1),span(4*index+2,4*index+3))+=tHopping*unity;\n\t\t\t\t\t\t\t\t\t\tif (i!=0 || j!=0 || n==index) {cout << \"Error for tHopping within primary cell\" << endl; }\n\t\t\t\t\t\t\t\t\t\t// hopping to sublatOne from outside the primary cell\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t// hoppings from sublatTwo of index to sublatOne of n\n\t\t\t\t\t\t\t\t\t\tHamiltonian(span(4*n+0,4*n+1),span(4*index+2,4*index+3))+=tHopping*exp(ii*dot(dummyVec3,kPointVec))*unity;\n\t\t\t\t\t\t\t\t\t\tif (n == index) {cout << \"Error for tHopping\" << endl; }\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Set up hoppings into sublatTwo\n\t\t\t\t\t\t\tif (dot(dummyVec4, dummyVec4) < sublatVecNorm*sublatVecNorm+delta) {\n\t\t\t\t\t\t\t\t// hopping to the n-th site from along [111] within the primary cell\n\t\t\t\t\t\t\t\tif (dot(dummyVec4+sublatVec,dummyVec4+sublatVec) < delta) {\n\t\t\t\t\t\t\t\t\tHamiltonian(span(4*n+2,4*n+3),span(4*index+0,4*index+1))+=(tHopping+deltatHopping)*unity;\n\t\t\t\t\t\t\t\t\tif (n != index || i!=0 || j!=0) {cout << \"Error for deltatHopping\" << endl; }\n\t\t\t\t\t\t\t\t\t// hopping in other directions\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif (i==0 && j==0) {\n\t\t\t\t\t\t\t\t\t\t// Hoppings withing the primary cell\n\t\t\t\t\t\t\t\t\t\tHamiltonian(span(4*n+2,4*n+3),span(4*index+0,4*index+1))+=tHopping*unity;\n\t\t\t\t\t\t\t\t\t\tif (i!=0 || j!=0 || n==index) {cout << \"Error for tHopping within primary cell\" << endl; }\n\t\t\t\t\t\t\t\t\t\t// hopping to sublatTwo from outside the primary cell\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t// hoppings from sublatOne of index to sublatTwo of n\n\t\t\t\t\t\t\t\t\t\tHamiltonian(span(4*n+2,4*n+3),span(4*index+0,4*index+1))+=tHopping*exp(ii*dot(dummyVec3,kPointVec))*unity;\n\t\t\t\t\t\t\t\t\t\tif (n == index) {cout << \"Error for tHopping\" << endl; }\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif ( (dot(dummyVec,dummyVec) < latVecNorm*latVecNorm+delta)  && \n\t\t\t\t\t\t\t\t\t(dot(dummyVec,dummyVec) > sublatVecNorm*sublatVecNorm+delta) ) { \n\t\t\t\t\t\t\t\t// Matrix elements are direction-dependent\n\t\t\t\t\t\t\t\tif ( (dummyVec(0) > 0 && dummyVec(1) > 0) || (dummyVec(0) > 0 &&\n\t\t\t\t\t\t\t\t\t\t\tdummyVec(2) > 0) || (dummyVec(1) > 0 && dummyVec(2) > 0) ) {\n\t\t\t\t\t\t\t\t\tdummyVec = cross(sublatVec, dummyVec-sublatVec);\n\t\t\t\t\t\t\t\t} else if ( (dummyVec(1) < 0 && dummyVec(2) < 0) || (dummyVec(0) > 0 &&\n\t\t\t\t\t\t\t\t\t\t\tdummyVec(1) < 0) || (dummyVec(0) > 0 && dummyVec(2) < 0) ) {\n\t\t\t\t\t\t\t\t\tdummyVec = cross(-bulklatVec1+sublatVec, dummyVec+bulklatVec1-sublatVec);\n\t\t\t\t\t\t\t\t} else if ( (dummyVec(0) < 0 && dummyVec(1) > 0) || (dummyVec(0) < 0 &&\n\t\t\t\t\t\t\t\t\t\t\tdummyVec(2) < 0) || (dummyVec(1) > 0 && dummyVec(2) < 0) ) {\n\t\t\t\t\t\t\t\t\tdummyVec = cross(-bulklatVec2+sublatVec, dummyVec+bulklatVec2-sublatVec);\n\t\t\t\t\t\t\t\t} else if ( (dummyVec(0) < 0 && dummyVec(2) > 0) || (dummyVec(1) < 0 &&\n\t\t\t\t\t\t\t\t\t\t\tdummyVec(2) > 0) || (dummyVec(0) < 0 && dummyVec(1) < 0) ) {\n\t\t\t\t\t\t\t\t\tdummyVec = cross(-bulklatVec3+sublatVec, dummyVec+bulklatVec3-sublatVec);\n\t\t\t\t\t\t\t\t} else {cout << \"Error in NNN hopping\" << endl; }\n\t\t\t\t\t\t\t\tdummyMat=dummyVec(0)*sigma_x+dummyVec(1)*sigma_y+dummyVec(2)*sigma_z;\n\t\t\t\t\t\t\t\tif (i==0 && j==0) {\n\t\t\t\t\t\t\t\t\tHamiltonian(span(4*n,4*n+1),span(4*index,4*index+1))+=spinOrbitCoupling*dummyMat;\n\t\t\t\t\t\t\t\t\t// Minus sign because for sublatTwo dummyVec is minus that of sublatOne\n\t\t\t\t\t\t\t\t\tHamiltonian(span(4*n+2,4*n+3),span(4*index+2,4*index+3))+= -1.0*spinOrbitCoupling*dummyMat;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Hoppings within sublatOne\n\t\t\t\t\t\t\t\t\tHamiltonian(span(4*n,4*n+1),span(4*index,4*index+1))+=exp(ii*dot(dummyVec3, kPointVec))*spinOrbitCoupling*dummyMat;\n\t\t\t\t\t\t\t\t\t// Hoppings within sublatTwo\n\t\t\t\t\t\t\t\t\tHamiltonian(span(4*n+2,4*n+3),span(4*index+2,4*index+3))+= -1.0*exp(ii*dot(dummyVec3,kPointVec))*spinOrbitCoupling*dummyMat;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}  \n\n\t\t// abs returns a matrix, max returns a vector, 2nd max - largest value\n\t\tif (max(max(abs(Hamiltonian-Hamiltonian.t()))) > delta ) {\n\t\t\tcout << \"Error, Hamiltonian is not Hermitian by at least \" << delta << endl;\n\t\t}\n\n\t\teig_sym(eigvals, eigvecs, Hamiltonian);\n\t\tbandstructure.row(m)=eigvals.t();\n\t\tcout << endl;\n\t//\tHamiltonian.save(\"Hamiltonian.txt\", arma_ascii);\n\t\tcout << \"Calculated k-point\";\n\t\tkPointVec.print();\n\t\tHamiltonian.zeros();\n\t}\n\n\tbandstructure.save(\"output_bs.txt\", raw_ascii);\n\t//sublatOne.save(\"output.txt\",raw_ascii);\n\t//sublatTwo.save(\"output2.txt\",raw_ascii);\n}\n\n", "meta": {"hexsha": "c1963e20774f5d44e5dadc3620b9e0db9cdb880c", "size": 9006, "ext": "cc", "lang": "C++", "max_stars_repo_path": "slab.cc", "max_stars_repo_name": "qftphys/Microscopic-tight-binding-model-of-a-topological-insulator-slab.", "max_stars_repo_head_hexsha": "6bdd27c5a4e3f66a90f03f26ac6af775b7a372a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-28T14:03:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-30T00:50:39.000Z", "max_issues_repo_path": "slab.cc", "max_issues_repo_name": "qftphys/Microscopic-tight-binding-model-of-a-topological-insulator-slab.", "max_issues_repo_head_hexsha": "6bdd27c5a4e3f66a90f03f26ac6af775b7a372a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slab.cc", "max_forks_repo_name": "qftphys/Microscopic-tight-binding-model-of-a-topological-insulator-slab.", "max_forks_repo_head_hexsha": "6bdd27c5a4e3f66a90f03f26ac6af775b7a372a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-01-25T13:29:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-11T07:51:38.000Z", "avg_line_length": 42.8857142857, "max_line_length": 133, "alphanum_fraction": 0.6225849434, "num_tokens": 3228, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8519527944504226, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.41266896637590805}}
{"text": "/**\n * MIT License\n *\n * Copyright (c) 2018 Parsiad Azimzadeh\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#ifndef MFHOWARDS_BELLMAN_EQ_FROM_LAMBDAS_HPP\n#define MFHOWARDS_BELLMAN_EQ_FROM_LAMBDAS_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/Sparse>\n\n#include <functional>       // std::function\n#include <initializer_list> // std::initializer_list\n#include <limits>           // std::numeric_limits\n#include <utility>          // std::forward\n\nnamespace mfhowards {\nnamespace {\ntemplate <typename CtrlT> class bellman_eq_from_lambdas;\n}\n} // namespace mfhowards\n\nnamespace Eigen {\nnamespace internal {\ntemplate <typename CtrlT>\nstruct traits<mfhowards::bellman_eq_from_lambdas<CtrlT>>\n    : public Eigen::internal::traits<Eigen::SparseMatrix<double>> {};\n} // namespace internal\n} // namespace Eigen\n\nnamespace mfhowards {\nnamespace {\ntemplate <typename CtrlT>\nclass bellman_eq_from_lambdas\n    : public Eigen::EigenBase<bellman_eq_from_lambdas<CtrlT>> {\n\npublic:\n  typedef double Scalar;\n  typedef double RealScalar;\n  typedef int StorageIndex;\n\n  enum {\n    ColsAtCompileTime = Eigen::Dynamic,\n    MaxColsAtCompileTime = Eigen::Dynamic,\n    IsRowMajor = false\n  };\n\nprivate:\n  typedef std::function<Scalar(int, int, CtrlT)> FA;\n  typedef std::function<Scalar(int, CtrlT)> Fb;\n\n  int n;\n  std::vector<CtrlT> ctrl_set;\n  FA A;\n  Fb b;\n  CtrlT *curr_ctrls;\n\n  template <typename Rhs>\n  using Helper = Eigen::Product<bellman_eq_from_lambdas<CtrlT>, Rhs,\n                                Eigen::AliasFreeProduct>;\n\npublic:\n  int rows() const { return n; }\n  int cols() const { return n; }\n\n  template <typename Rhs>\n  Helper<Rhs> operator*(const Eigen::MatrixBase<Rhs> &x) const {\n    return Helper<Rhs>(*this, x.derived());\n  }\n\n  template <typename T>\n  bellman_eq_from_lambdas(const int n, T &&ctrl_set, FA A, Fb b)\n      : ctrl_set(std::forward<T>(ctrl_set)) {\n    this->n = n;\n    this->A = A;\n    this->b = b;\n    curr_ctrls = new CtrlT[n];\n  }\n\n  bellman_eq_from_lambdas(const int n, std::initializer_list<CtrlT> list, FA A,\n                          Fb b)\n      : bellman_eq_from_lambdas(n, std::vector<CtrlT>(list), A, b) {}\n\n  ~bellman_eq_from_lambdas() { delete[] curr_ctrls; }\n\n  bellman_eq_from_lambdas(const bellman_eq_from_lambdas &) = delete;\n  bellman_eq_from_lambdas &operator=(const bellman_eq_from_lambdas &) = delete;\n\n  void improve(const Eigen::VectorXd &x) {\n    Eigen::VectorXd best =\n        Eigen::VectorXd::Ones(rows()) * std::numeric_limits<double>::infinity();\n    for (auto c : ctrl_set) {\n      for (int i = 0; i < rows(); ++i) {\n        double tmp = 0;\n        for (int j = 0; j < cols(); ++j) {\n          tmp += A(i, j, c) * x(j) - b(i, c);\n        }\n        if (tmp < best(i)) {\n          best(i) = tmp;\n          curr_ctrls[i] = c;\n        }\n      }\n    }\n  }\n\n  Eigen::VectorXd rhs() const {\n    Eigen::VectorXd rhs(rows());\n    for (int i = 0; i < rows(); ++i) {\n      rhs(i) = b(i, curr_ctrls[i]);\n    }\n    return rhs;\n  }\n\n  template <typename, typename, typename, typename, int>\n  friend class Eigen::internal::generic_product_impl;\n};\n} // namespace\n} // namespace mfhowards\n\nnamespace Eigen {\nnamespace internal {\ntemplate <typename CtrlT, typename Rhs>\nstruct generic_product_impl<mfhowards::bellman_eq_from_lambdas<CtrlT>, Rhs,\n                            SparseShape, DenseShape, GemvProduct>\n    : generic_product_impl_base<\n          mfhowards::bellman_eq_from_lambdas<CtrlT>, Rhs,\n          generic_product_impl<mfhowards::bellman_eq_from_lambdas<CtrlT>,\n                               Rhs>> {\n\n  typedef\n      typename Product<mfhowards::bellman_eq_from_lambdas<CtrlT>, Rhs>::Scalar\n          Scalar;\n\n  template <typename Dest>\n  static void\n  scaleAndAddTo(Dest &dst, const mfhowards::bellman_eq_from_lambdas<CtrlT> &lhs,\n                const Rhs &rhs, const Scalar &) {\n    for (int i = 0; i < lhs.rows(); ++i) {\n      for (int j = 0; j < lhs.cols(); ++j) {\n        dst(i) += lhs.A(i, j, lhs.curr_ctrls[i]) * rhs(j);\n      }\n    }\n  }\n};\n} // namespace internal\n} // namespace Eigen\n\n#endif\n", "meta": {"hexsha": "ea32ff4a5cde734d2b2813f99c7de3b6e5070578", "size": 5137, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mfhowards/src/bellman_eq_from_lambdas.hpp", "max_stars_repo_name": "parsiad/matrix-free-policy-iteration", "max_stars_repo_head_hexsha": "3d990a6f202e92667d3c5dd965194a98a733805b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-18T15:38:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-23T19:15:02.000Z", "max_issues_repo_path": "mfhowards/src/bellman_eq_from_lambdas.hpp", "max_issues_repo_name": "parsiad/matrix-free-policy-iteration", "max_issues_repo_head_hexsha": "3d990a6f202e92667d3c5dd965194a98a733805b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mfhowards/src/bellman_eq_from_lambdas.hpp", "max_forks_repo_name": "parsiad/matrix-free-policy-iteration", "max_forks_repo_head_hexsha": "3d990a6f202e92667d3c5dd965194a98a733805b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2176470588, "max_line_length": 80, "alphanum_fraction": 0.6673155538, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521105, "lm_q2_score": 0.6370308013713525, "lm_q1q2_score": 0.412667417908967}}
{"text": "//=======================================================================\n// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file bounded_degree_mst.hpp\n * @brief\n * @author Piotr Godlewski\n * @version 1.0\n * @date 2013-06-03\n */\n#ifndef PAAL_BOUNDED_DEGREE_MST_HPP\n#define PAAL_BOUNDED_DEGREE_MST_HPP\n\n\n#include \"paal/iterative_rounding/bounded_degree_min_spanning_tree/bounded_degree_mst_oracle.hpp\"\n#include \"paal/iterative_rounding/ir_components.hpp\"\n#include \"paal/iterative_rounding/iterative_rounding.hpp\"\n#include \"paal/lp/lp_row_generation.hpp\"\n\n#include <boost/bimap.hpp>\n#include <boost/range/as_array.hpp>\n#include <boost/graph/connected_components.hpp>\n\nnamespace paal {\nnamespace ir {\n\nnamespace {\nstruct bounded_degree_mst_compare_traits {\n    static const double EPSILON;\n};\n\nconst double bounded_degree_mst_compare_traits::EPSILON = 1e-10;\n}\n\n/**\n * @class bounded_degree_mst\n * @brief The class for solving the Bounded Degree MST problem using Iterative\n* Rounding.\n *\n * @tparam Graph input graph\n * @tparam DegreeBounds map from Graph vertices to degree bounds\n * @tparam CostMap map from Graph edges to costs\n * @tparam VertexIndex map from Graph vertices to indices\n * @tparam SpanningTreeOutputIterator\n * @tparam Oracle separation oracle\n */\ntemplate <typename Graph, typename DegreeBounds, typename CostMap,\n          typename VertexIndex, typename SpanningTreeOutputIterator,\n          typename Oracle = paal::lp::random_violated_separation_oracle>\nclass bounded_degree_mst {\n  public:\n    /**\n     * Constructor.\n     */\n    bounded_degree_mst(const Graph & g, const DegreeBounds & deg_bounds,\n                    CostMap cost_map, VertexIndex index,\n                    SpanningTreeOutputIterator result_spanning_tree, Oracle oracle = Oracle{}) :\n              m_g(g), m_cost_map(cost_map), m_index(index), m_deg_bounds(deg_bounds),\n              m_result_spanning_tree(result_spanning_tree),\n              m_compare(bounded_degree_mst_compare_traits::EPSILON),\n              m_oracle(oracle)\n    {}\n\n    using Edge = typename boost::graph_traits<Graph>::edge_descriptor;\n    using Vertex = typename boost::graph_traits<Graph>::vertex_descriptor;\n\n    using EdgeMap = boost::bimap<Edge, lp::col_id>;\n    using VertexMap = std::unordered_map<lp::row_id, Vertex>;\n\n    using EdgeMapOriginal = std::vector<std::pair<lp::col_id, Edge>>;\n\n    using ErrorMessage = boost::optional<std::string>;\n\n    /**\n     * Checks if the input graph is connected.\n     */\n    ErrorMessage check_input_validity() {\n        // Is g connected?\n        std::vector<int> components(num_vertices(m_g));\n        int num = boost::connected_components(m_g, &components[0]);\n\n        if (num > 1) {\n            return ErrorMessage{ \"The graph is not connected.\" };\n        }\n\n        return ErrorMessage{};\n    }\n\n    /**\n     * @brief\n     *\n     * @tparam LP\n     * @param lp\n     *\n     * @return\n     */\n    template <typename LP>\n    auto get_find_violation(LP & lp) {\n        using candidate = bdmst_violation_checker::Candidate;\n        return m_oracle([&](){return m_violation_checker.get_violation_candidates(*this, lp);},\n                        [&](candidate c){return m_violation_checker.check_violation(c, *this);},\n                        [&](candidate c){return m_violation_checker.add_violated_constraint(c, *this, lp);});\n    }\n\n    /**\n     * Returns the input graph.\n     */\n    const Graph &get_graph() const { return m_g; }\n\n    /**\n     * Returns the vertex index.\n     */\n    const VertexIndex &get_index() const { return m_index; }\n\n    /**\n     * Removes an LP column and the graph edge corresponding to it.\n     */\n    void remove_column(lp::col_id col_id) {\n        auto ret = m_edge_map.right.erase(col_id);\n        assert(ret == 1);\n    }\n\n    /**\n     * Binds a graph edge to a LP column.\n     */\n    void bind_edge_to_col(Edge e, lp::col_id col) {\n        m_edge_map_original.push_back(\n            typename EdgeMapOriginal::value_type(col, e));\n        m_edge_map.insert(typename EdgeMap::value_type(e, col));\n    }\n\n    /**\n     * Returns the cost of a given edge.\n     */\n    decltype(get(std::declval<CostMap>(), std::declval<Edge>()))\n        get_cost(Edge e) {\n        return get(m_cost_map, e);\n    }\n\n    /**\n     * Returns the degree bound of a vertex.\n     */\n    decltype(std::declval<DegreeBounds>()(get(std::declval<VertexIndex>(),\n                                              std::declval<Vertex>())))\n        get_degree_bound(Vertex v) {\n        return m_deg_bounds(get(m_index, v));\n    }\n\n    /**\n     * Returns the LP column corresponding to an edge, if it wasn't deleted from\n     * the LP.\n     */\n    boost::optional<lp::col_id> edge_to_col(Edge e) const {\n        auto i = m_edge_map.left.find(e);\n        if (i != m_edge_map.left.end()) {\n            return i->second;\n        } else {\n            return boost::none;\n        }\n    }\n\n    /**\n     * Returns a bimap between edges and LP column IDs.\n     */\n    const EdgeMap &get_edge_map() const { return m_edge_map; }\n\n    /**\n     * Returns a mapping between LP column IDs and edges in the original graph.\n     */\n    const EdgeMapOriginal &get_original_edges_map() const {\n        return m_edge_map_original;\n    }\n\n    /**\n     * Adds an edge to the result spanning tree.\n     */\n    void add_to_result_spanning_tree(Edge e) {\n        *m_result_spanning_tree = e;\n        ++m_result_spanning_tree;\n    }\n\n    /**\n     * Returns the double comparison object.\n     */\n    utils::compare<double> get_compare() const {\n        return m_compare;\n    }\n\n    /**\n     * Binds a graph vertex to an LP row.\n     */\n    void bind_vertex_to_row(Vertex v, lp::row_id row) {\n        m_vertex_map.insert(typename VertexMap::value_type(row, v));\n    }\n\n    /**\n     * Unbinds the graph vertex from its corresponding (deleted) LP row.\n     */\n    void remove_row(lp::row_id row_id) {\n        auto ret = m_vertex_map.erase(row_id);\n        assert(ret == 1);\n    }\n\n    /**\n     * Returns the graph vertex corresponding to a given LP row,\n     *        unless the row doen't correspond to any vertex.\n     */\n    boost::optional<Vertex> row_to_vertex(lp::row_id row) {\n        auto i = m_vertex_map.find(row);\n        if (i != m_vertex_map.end()) {\n            return i->second;\n        } else {\n            return boost::none;\n        }\n    }\n\n  private:\n    Edge col_to_edge(lp::col_id col) {\n        auto i = m_edge_map.right.find(col);\n        assert(i != m_edge_map.right.end());\n        return i->second;\n    }\n\n    const Graph &m_g;\n    CostMap m_cost_map;\n    VertexIndex m_index;\n    const DegreeBounds &m_deg_bounds;\n    SpanningTreeOutputIterator m_result_spanning_tree;\n    bdmst_violation_checker m_violation_checker;\n\n    EdgeMapOriginal m_edge_map_original;\n    EdgeMap m_edge_map;\n    VertexMap m_vertex_map;\n\n    const utils::compare<double>   m_compare;\n\n    Oracle m_oracle;\n};\n\nnamespace detail {\n/**\n * @brief Creates a bounded_degree_mst object. Non-named version.\n *\n * @tparam Oracle\n * @tparam Graph\n * @tparam DegreeBounds\n * @tparam CostMap\n * @tparam VertexIndex\n * @tparam SpanningTreeOutputIterator\n * @param g\n * @param degBoundMap\n * @param cost_map\n * @param vertex_index\n * @param result_spanning_tree\n * @param oracle\n *\n * @return bounded_degree_mst object\n */\ntemplate <typename Oracle = lp::random_violated_separation_oracle,\n          typename Graph,\n          typename DegreeBounds, typename CostMap, typename VertexIndex,\n          typename SpanningTreeOutputIterator>\nbounded_degree_mst<Graph, DegreeBounds, CostMap, VertexIndex, SpanningTreeOutputIterator, Oracle>\nmake_bounded_degree_mst(const Graph & g, const DegreeBounds & deg_bounds,\n                      CostMap cost_map, VertexIndex vertex_index,\n                      SpanningTreeOutputIterator result_spanning_tree,\n                      Oracle oracle = Oracle()) {\n    return bounded_degree_mst<Graph, DegreeBounds, CostMap, VertexIndex,\n                SpanningTreeOutputIterator, Oracle>(g, deg_bounds, cost_map, vertex_index,\n                    result_spanning_tree, oracle);\n}\n} // detail\n\n/**\n * Creates a bounded_degree_mst object. Named version.\n * The returned object can be used to check input validity or to get a lower\n* bound on the\n * optimal solution cost.\n *\n * @tparam Oracle\n * @tparam Graph\n * @tparam DegreeBounds\n * @tparam SpanningTreeOutputIterator\n * @tparam P\n * @tparam T\n * @tparam R\n * @param g\n * @param deg_bounds\n * @param params\n * @param result_spanning_tree\n * @param oracle\n *\n * @return bounded_degree_mst object\n */\ntemplate <typename Oracle = lp::random_violated_separation_oracle,\n          typename Graph,\n          typename DegreeBounds, typename SpanningTreeOutputIterator,\n          typename P, typename T, typename R>\nauto\nmake_bounded_degree_mst(const Graph & g,\n                      const DegreeBounds & deg_bounds,\n                      const boost::bgl_named_params<P, T, R> & params,\n                      SpanningTreeOutputIterator result_spanning_tree,\n                      Oracle oracle = Oracle())\n        -> bounded_degree_mst<Graph, DegreeBounds,\n                decltype(choose_const_pmap(get_param(params, boost::edge_weight), g, boost::edge_weight)),\n                decltype(choose_const_pmap(get_param(params, boost::vertex_index), g, boost::vertex_index)),\n                SpanningTreeOutputIterator, Oracle> {\n\n    return detail::make_bounded_degree_mst(g, deg_bounds,\n                choose_const_pmap(get_param(params, boost::edge_weight), g, boost::edge_weight),\n                choose_const_pmap(get_param(params, boost::vertex_index), g, boost::vertex_index),\n                result_spanning_tree, oracle);\n}\n\n/**\n * Creates a bounded_degree_mst object. All default parameters.\n * The returned object can be used to check input validity or to get a lower\n* bound on the\n * optimal solution cost.\n *\n * @tparam Oracle\n * @tparam Graph\n * @tparam DegreeBounds\n * @tparam SpanningTreeOutputIterator\n * @param g\n * @param deg_bounds\n * @param result_spanning_tree\n * @param oracle\n *\n * @return bounded_degree_mst object\n */\ntemplate <typename Oracle = lp::random_violated_separation_oracle,\n          typename Graph, typename DegreeBounds, typename SpanningTreeOutputIterator>\nauto\nmake_bounded_degree_mst(const Graph & g, const DegreeBounds & deg_bounds,\n                      SpanningTreeOutputIterator result_spanning_tree,\n                      Oracle oracle = Oracle()) ->\n        decltype(make_bounded_degree_mst(g, deg_bounds, boost::no_named_parameters(), result_spanning_tree, oracle)) {\n    return make_bounded_degree_mst(g, deg_bounds, boost::no_named_parameters(), result_spanning_tree, oracle);\n}\n\n/**\n * Round Condition of the IR Bounded Degree MST algorithm.\n */\nstruct bdmst_round_condition {\n    /**\n     * Constructor. Takes epsilon used in double comparison.\n     */\n    bdmst_round_condition(double epsilon =\n                              bounded_degree_mst_compare_traits::EPSILON)\n        : m_round_zero(epsilon) {}\n\n    /**\n     * Checks if a given column of the LP can be rounded to 0.\n     * If the column is rounded, the corresponding edge is removed from the\n     * graph.\n     */\n    template <typename Problem, typename LP>\n    boost::optional<double> operator()(Problem &problem, const LP &lp,\n                                       lp::col_id col) {\n        auto ret = m_round_zero(problem, lp, col);\n        if (ret) {\n            problem.remove_column(col);\n        }\n        return ret;\n    }\n\n  private:\n    round_condition_equals<0> m_round_zero;\n};\n\n/**\n * Relax Condition of the IR Bounded Degree MST algorithm.\n */\nstruct bdmst_relax_condition {\n    /**\n     * Checks if a given row of the LP corresponds to a degree bound and can be\n     * relaxed.\n     * If the row degree is not greater than the corresponding degree bound + 1,\n     * it is relaxed\n     * and the degree bound is deleted from the problem.\n     */\n    template <typename Problem, typename LP>\n    bool operator()(Problem &problem, const LP &lp, lp::row_id row) {\n        auto vertex = problem.row_to_vertex(row);\n        if (vertex) {\n            auto ret = (lp.get_row_degree(row) <=\n                        problem.get_degree_bound(*vertex) + 1);\n            if (ret) {\n                problem.remove_row(row);\n            }\n            return ret;\n        } else\n            return false;\n    }\n};\n\n/**\n * Initialization of the IR Bounded Degree MST algorithm.\n */\nstruct bdmst_init {\n    /**\n     * Initializes the LP: variables for edges, degree bound constraints\n     * and constraint for all edges.\n     */\n    template <typename Problem, typename LP>\n    void operator()(Problem &problem, LP &lp) {\n        lp.set_lp_name(\"bounded degree minimum spanning tree\");\n        lp.set_optimization_type(lp::MINIMIZE);\n\n        add_variables(problem, lp);\n        add_degree_bound_constraints(problem, lp);\n        add_all_set_equality(problem, lp);\n    }\n\n  private:\n    /**\n     * Adds a variable to the LP for each edge in the input graph.\n     * Binds the LP columns to edges.\n     */\n    template <typename Problem, typename LP>\n    void add_variables(Problem & problem, LP & lp) {\n        for (auto e : boost::as_array(edges(problem.get_graph()))) {\n            auto col = lp.add_column(problem.get_cost(e), 0, 1);\n            problem.bind_edge_to_col(e, col);\n        }\n    }\n\n    /**\n     * Adds a degree bound constraint to the LP for each vertex in the input\n     * graph\n     * and binds vertices to rows.\n     */\n    template <typename Problem, typename LP>\n    void add_degree_bound_constraints(Problem &problem, LP &lp) {\n        auto const &g = problem.get_graph();\n\n        for (auto v : boost::as_array(vertices(g))) {\n            lp::linear_expression expr;\n\n            for (auto e : boost::as_array(out_edges(v, g))) {\n                expr += *(problem.edge_to_col(e));\n            }\n\n            auto row =\n                lp.add_row(std::move(expr) <= problem.get_degree_bound(v));\n            problem.bind_vertex_to_row(v, row);\n        }\n    }\n\n    /**\n     * Adds an equality constraint to the LP for the set of all edges in the\n     * input graph.\n     */\n    template <typename Problem, typename LP>\n    void add_all_set_equality(Problem &problem, LP &lp) {\n        lp::linear_expression expr;\n        for (auto col : lp.get_columns()) {\n            expr += col;\n        }\n        lp.add_row(std::move(expr) == num_vertices(problem.get_graph()) - 1);\n    }\n};\n\n/**\n * Set Solution component of the IR Bounded Degree MST algorithm.\n */\nstruct bdmst_set_solution {\n    /**\n     * Constructor. Takes epsilon used in double comparison.\n     */\n    bdmst_set_solution(double epsilon =\n                           bounded_degree_mst_compare_traits::EPSILON)\n        : m_compare(epsilon) {}\n\n    /**\n     * Creates the result spanning tree form the LP (all edges corresponding to\n     * columns with value 1).\n     */\n    template <typename Problem, typename GetSolution>\n    void operator()(Problem & problem, const GetSolution & solution) {\n        for (auto col_and_edge : problem.get_original_edges_map()) {\n            if (m_compare.e(solution(col_and_edge.first), 1)) {\n                problem.add_to_result_spanning_tree(col_and_edge.second);\n            }\n        }\n    }\n\nprivate:\n    const utils::compare<double>   m_compare;\n};\n\ntemplate <typename Init = bdmst_init,\n          typename RoundCondition = bdmst_round_condition,\n          typename RelaxContition = bdmst_relax_condition,\n          typename SetSolution = bdmst_set_solution,\n          typename SolveLPToExtremePoint = ir::row_generation_solve_lp<>,\n          typename ResolveLpToExtremePoint = ir::row_generation_solve_lp<>>\nusing bdmst_ir_components =\n    IRcomponents<Init, RoundCondition, RelaxContition, SetSolution,\n                 SolveLPToExtremePoint, ResolveLpToExtremePoint>;\n\nnamespace detail {\n/**\n * @brief Solves the Bounded Degree MST problem using Iterative Rounding.\n* Non-named version.\n *\n * @tparam Oracle\n * @tparam Graph\n * @tparam DegreeBounds\n * @tparam CostMap\n * @tparam VertexIndex\n * @tparam SpanningTreeOutputIterator\n * @tparam IRcomponents\n * @tparam Visitor\n * @param g\n * @param degBoundMap\n * @param cost_map\n * @param vertex_index\n * @param result_spanning_tree\n * @param components\n * @param oracle\n * @param visitor\n *\n * @return solution status\n */\ntemplate <typename Oracle = lp::random_violated_separation_oracle,\n          typename Graph,\n          typename DegreeBounds, typename CostMap, typename VertexIndex,\n          typename SpanningTreeOutputIterator,\n          typename IRcomponents = bdmst_ir_components<>,\n          typename Visitor = trivial_visitor>\nIRResult bounded_degree_mst_iterative_rounding(\n        const Graph & g,\n        const DegreeBounds & deg_bounds,\n        CostMap cost_map,\n        VertexIndex vertex_index,\n        SpanningTreeOutputIterator result_spanning_tree,\n        IRcomponents components = IRcomponents(),\n        Oracle oracle = Oracle(),\n        Visitor visitor = Visitor()) {\n\n    auto bdmst = make_bounded_degree_mst(g, deg_bounds, cost_map, vertex_index, result_spanning_tree, oracle);\n    return solve_iterative_rounding(bdmst, std::move(components), std::move(visitor));\n}\n} // detail\n\n/**\n * @brief Solves the Bounded Degree MST problem using Iterative Rounding. Named\n* version.\n *\n * @tparam Oracle\n * @tparam Graph\n * @tparam DegreeBounds\n * @tparam SpanningTreeOutputIterator\n * @tparam IRcomponents\n * @tparam Visitor\n * @tparam P\n * @tparam T\n * @tparam R\n * @param g\n * @param deg_bounds\n * @param result_spanning_tree\n * @param params\n * @param components\n * @param oracle\n * @param visitor\n *\n * @return solution status\n */\ntemplate <typename Oracle = lp::random_violated_separation_oracle,\n          typename Graph,\n          typename DegreeBounds, typename SpanningTreeOutputIterator,\n          typename IRcomponents = bdmst_ir_components<>,\n          typename Visitor = trivial_visitor, typename P, typename T,\n          typename R>\nIRResult bounded_degree_mst_iterative_rounding(\n            const Graph & g,\n            const DegreeBounds & deg_bounds,\n            const boost::bgl_named_params<P, T, R> & params,\n            SpanningTreeOutputIterator result_spanning_tree,\n            IRcomponents components = IRcomponents(),\n            Oracle oracle = Oracle(),\n            Visitor visitor = Visitor()) {\n\n        return detail::bounded_degree_mst_iterative_rounding(g, deg_bounds,\n                    choose_const_pmap(get_param(params, boost::edge_weight), g, boost::edge_weight),\n                    choose_const_pmap(get_param(params, boost::vertex_index), g, boost::vertex_index),\n                    std::move(result_spanning_tree), std::move(components),\n                    std::move(oracle), std::move(visitor));\n}\n\n/**\n * @brief Solves the Bounded Degree MST problem using Iterative Rounding. All\n* default parameters.\n *\n * @tparam Oracle\n * @tparam Graph\n * @tparam DegreeBounds\n * @tparam SpanningTreeOutputIterator\n * @tparam IRcomponents\n * @tparam Visitor\n * @param g\n * @param deg_bounds\n * @param result_spanning_tree\n * @param components\n * @param oracle\n * @param visitor\n *\n * @return solution status\n */\ntemplate <typename Oracle = lp::random_violated_separation_oracle, typename Graph,\n          typename DegreeBounds, typename SpanningTreeOutputIterator,\n          typename IRcomponents = bdmst_ir_components<>,\n          typename Visitor = trivial_visitor>\nIRResult bounded_degree_mst_iterative_rounding(\n            const Graph & g,\n            const DegreeBounds & deg_bounds,\n            SpanningTreeOutputIterator result_spanning_tree,\n            IRcomponents components = IRcomponents(),\n            Oracle oracle = Oracle(),\n            Visitor visitor = Visitor()) {\n\n        return bounded_degree_mst_iterative_rounding(g, deg_bounds,\n                    boost::no_named_parameters(), std::move(result_spanning_tree),\n                    std::move(components), std::move(oracle), std::move(visitor));\n}\n\n} //! ir\n} //! paal\n#endif // PAAL_BOUNDED_DEGREE_MST_HPP\n", "meta": {"hexsha": "e9d50a8a8a71c2ba263f02ae27a1aa03b06ac2d7", "size": 20271, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/iterative_rounding/bounded_degree_min_spanning_tree/bounded_degree_mst.hpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/paal/iterative_rounding/bounded_degree_min_spanning_tree/bounded_degree_mst.hpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/paal/iterative_rounding/bounded_degree_min_spanning_tree/bounded_degree_mst.hpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 31.8226059655, "max_line_length": 118, "alphanum_fraction": 0.6475260224, "num_tokens": 4610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4124529369692353}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG, www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also tools/license/license.mtl.txt in the distribution.\n//\n// Author Marc Hartung\n\n#ifndef MTL_MATRIX_EIGENVALUE_INCLUDE\n#define MTL_MATRIX_EIGENVALUE_INCLUDE\n\n#include <cmath>\n#include <complex>\n#include <utility>\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/operation/qr_givens.hpp>\n#include <boost/numeric/mtl/operation/misc.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/mtl/vector/dense_vector.hpp>\n\nnamespace mtl { namespace mat {\n\n\n/// Solver class for general eigenvalues\n/** Not yet tested for complex matrices. **/\ntemplate <typename Matrix>\nclass eigenvalue_solver {\n    \n    typedef typename Collection<Matrix>::value_type   value_type;\n    typedef typename Collection<Matrix>::size_type    size_type;  \n        \npublic:\n    \n    /** \\brief Constructor needs a sqare-matrix as input\n     * \\param MTL-Matrix type\n     *  \n     */\n    eigenvalue_solver(const Matrix& IN) : ncols(num_cols(IN)), nrows(num_rows(IN)) {\n\tzero= math::zero(IN[0][0]);\n\tone= math::one(IN[0][0]);\n\tR = hessenberg(IN);\n\tI = Matrix(ncols,nrows);\n\tI = one;\n\t\n\t//Standartwert Initialisierung:\n\t\n\tmaxIteration = 20*ncols*ncols;\n\teps = 1.0e-8;\n    }\n    \n    \n    /** \\brief Changes the zero-tolerance\n     *  \\param value_type of allowed distance to zero\n     */\n    void setTolerance(value_type in) {\n\teps = in;\n    }\n    \n    /** \\brief Changes the number of allowed iterations\n     * \\param size_type variable of maximum allowed iterations\n     */    \n    void setMaxIteration(size_type in) {\n\tmaxIteration = in;\n    }\n    \n    /** \\brief Starts the calculation of eigenvalues.\n     */\n    void calc() {\n\tvalue_type singleCont;\n\tstd::complex<value_type> compCont;\n\tsize_type size, allIt = 0;\n\tfor(size_type i=ncols-1;i>0 && i<ncols && allIt<=maxIteration;i--) {\n\t    size = i+1; // verkleinert die Matrix-Dimensionen\n\t    irange r(0,size);\n\t    singleCont = std::abs(R[i][i-1])+1;\n\t    compCont = getComplex2x2EW(i) + 1;\n\t    while( allIt < maxIteration  && std::abs(R[i][i-1])>eps) {\n\t\tif(isRealEW(i)) { \n\t\t    if(std::abs(R[i][i-1])<singleCont) { //SingleShift\n\t\t\tsingleCont = std::abs(R[i][i-1]);\n\t\t\tsingleShift(r);\n\t\t    }\n\t\t    else { //DoubleShift\n\t\t\tsingleCont = std::abs(R[i][i-1]);\n\t\t\tdoubleShift(r);\n\t\t    }\n\t\t    allIt++;\n\t\t}\n\t\telse {\n\t\t    if(std::abs(compCont-getComplex2x2EW(i))>eps) {\n\t\t\tcompCont = getComplex2x2EW(i);\n\t\t\tdoubleShift(r);\n\t\t\tallIt++;\n\t\t    }\n\t\t    else {\n\t\t\ti--;\n\t\t\tbreak;\n\t\t    }\t\t    \n\t\t}\n \t    }\n\t}\n    }\n    \n    \n    /** \\brief Returner for the calculated eigenvalues\n     * \n     * Before using get_eigenvalues() you have to use calc()!\n     * \\param dense_vector<complex<value_type>> of eigenvalues\n     */    \n    dense_vector<std::complex<value_type> > get_eigenvalues() \n    {\n\tusing mtl::conj;\n\tdense_vector<std::complex<double> > res(ncols, 0.0);\n\tsize_type i;\n\tfor(i=ncols-1;i>0 && i<ncols;i--) {\n\t    if(std::abs(R[i][i-1])<eps || isRealEW(i)) { // wenn ein reeller EW\n\t\tres[i] = R[i][i];\n\t    }\n\t    else { // wenn zwei konjungiert komplexe EW\n\n\t\tstd::complex<value_type> ews = getComplex2x2EW(i);\n\t\tres[i-1] = ews;\n\t\tres[i] = conj(ews);\n\t\ti--;\n\t    }\n\t}\n\tif(i==0) { // zur Vermeidung von Zugriffsfehler\n\t    res[0] = R[0][0];\n\t}    \n\treturn res;\n    }\n          \n    \n    \nprivate:\n    Matrix R, I;\n    size_type ncols, nrows, maxIteration;\n    value_type zero, one, eps;\n    \n    \n    bool isRealEW(size_type k) {\n\tif(std::abs(sqrt(square(R[k-1][k-1]+R[k][k])/4.0+R[k-1][k]*R[k][k-1]-R[k-1][k-1]*R[k][k])) >= 0.0) {\n\t    return true;\n\t}\n\treturn false;\n    }\n    \n    /** \\brief Calculates real eigenvalues of a 2x2-matrix defined by col/row k arround the diagonal of the input-matrix\n     * \n     * First entry of the pair is the eigenvalue closer to the (kxk)-entry (Wilkinson-shift for single shifting)\n     */\n    std::pair<value_type, value_type> get2x2EW(const size_type k) {\n\tstd::pair<value_type, value_type> res;\n\tvalue_type front, back, comparator;\n\t\n\tfront = (R[k-1][k-1]+R[k][k])/2.0;\n\tback = sqrt(square(R[k-1][k-1]+R[k][k])/4.0+R[k-1][k]*R[k][k-1]-R[k-1][k-1]*R[k][k]);\n\tcomparator = R[k][k]-front;\n\t\n\tif( std::abs(comparator-back) < std::abs(comparator+back) ) {\n\t    res.first = front+back;\n\t    res.second = front-back;\n\t}\n\telse {\n\t    res.first = front-back;\n\t    res.second = front+back;\n\t}\n\treturn res;\n    }\n    \n    \n    /** \\brief Calculates a complex eigenvalue of a 2x2-matrix defined by col/row k arround the diagonal of the input-matrix\n     * \n     */\n    std::complex<value_type> getComplex2x2EW(const size_type k) {\n\tstd::complex<value_type> res;\n\tres = square(R[k-1][k-1]+R[k][k])/4.0+R[k-1][k]*R[k][k-1]-R[k-1][k-1]*R[k][k];\n\tres = sqrt(res);\n\tres += (R[k-1][k-1]+R[k][k])/2.0;\n\treturn res;\n    }\n    \n    /** \\brief Performes a double shift for submatrix defined by range r\n     */\n    \n    void doubleShift(irange r) \n    {\n\tusing mtl::conj;\n\tvalue_type s,t;\n\t\n\tif(isRealEW(r.finish()-1)) {\n\t    std::pair<value_type, value_type> ews = get2x2EW(r.finish()-1);\n\t    s = ews.first+ews.second;\n\t    t = ews.first*ews.second;\n\t}    \n\telse {\n\t    std::complex<value_type> ew = getComplex2x2EW(r.finish()-1);\n\t    s = 2.0*ew.real();\n\t    t = std::abs(ew*conj(ew));\n\t}\n\t\n\tMatrix RIter(R[r][r]*R[r][r] - s*R[r][r] + t*I[r][r]);\n\t\n\tqr_givens_solver<Matrix> QR(RIter);\n\tQR.setTolerance(eps);\n\tQR.calc();\n\t\n\tRIter = R[r][r];\n\tR[r][r] = (QR.getQ()) * RIter * trans(QR.getQ());\n\t\n    }\n    \n    \n    \n     /** \\brief Performes a single shift for submatrix defined by range r\n     */\n    void singleShift(irange r) {\n\tvalue_type sh = get2x2EW(r.finish()-1).first;\n\tif(!(std::abs(sh) >= 0.0)) {\n\t    sh = R[r.finish()-1][r.finish()-1];\n\t}\n\tMatrix RIter(R[r][r] - sh*I[r][r]);\t\t//Shift wird abgezogen\n\t\n\tqr_givens_solver<Matrix> QR(RIter);\t\t//QR-Zerlegung\n\tQR.setTolerance(eps);\n\tQR.calc();\n\t\n\tR[r][r] = ((QR.getR())*trans(QR.getQ())) + sh*I[r][r];\t//QR-Iteration mit dem Rückshift\n\t\n    }\n\n};\n\n/// Calculation of eigenvalues of general matrix A\n/** Not yet tested for complex matrices. **/\ntemplate <typename Matrix>\ndense_vector<std::complex<typename Collection<Matrix>::value_type> >\ninline eigenvalues(const Matrix& A)\n{\n    eigenvalue_solver<Matrix> s(A);\n    s.calc();\n    return s.get_eigenvalues();\n} \n\n\n}} // namespace mtl::matrix\n\n#endif // MTL_MATRIX_EIGENVALUE_INCLUDE\n", "meta": {"hexsha": "870c4a8e348d71178d60e69793689272bf41499e", "size": 6731, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/mtl/operation/eigenvalue.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/mtl/operation/eigenvalue.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/mtl/operation/eigenvalue.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 26.1906614786, "max_line_length": 124, "alphanum_fraction": 0.6186302184, "num_tokens": 2086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.41241922136121895}}
{"text": "/* Copyright (c) 2017, Julian Straub <jstraub@csail.mit.edu>\n * Licensed under the MIT license. See the license file LICENSE.\n */\n// g++ -Wall -std=c++1z -I /usr/include/eigen3/ main.cpp -o test \n#include <random>\n#include <cmath>\n#include <iostream>\n#include <Eigen/Dense>\n#include \"vmf.hpp\"\n#include \"vmfPrior.hpp\"\n#include \"sample.hpp\"\n\nint main() {\n\n  std::mt19937 rnd(1);\n\n  vMF<float,3> vmfA(Eigen::Vector3f(0,0,1), 100);\n  vMF<float,3> vmfB(Eigen::Vector3f(0,1,0), 100);\n  vMF<float,3> vmfC(Eigen::Vector3f(1,0,0), 100);\n  vMF<float,3> vmfD(Eigen::Vector3f(-1,0,0),100);\n  vMF<float,3> vmfO(Eigen::Vector3f(1,0,0),10);\n\n  size_t N=30;\n  std::vector<std::vector<Eigen::Vector3f>> x;\n  for (size_t i=0; i<N; ++i) {\n    x.push_back(std::vector<Eigen::Vector3f>());\n    for (size_t j=0; j<N; ++j) {\n      if (i<N/2 && j<N/2) \n        x[i].push_back(vmfA.sample(rnd));\n      if (i>=N/2 && j<N/2) \n        x[i].push_back(vmfB.sample(rnd));\n      if (i>=N/2 && j>=N/2) \n        x[i].push_back(vmfC.sample(rnd));\n      if (i<N/2 && j>=N/2) \n        x[i].push_back(vmfD.sample(rnd));\n      if (N/3 < i && i< 2*N/3 && N/3 < j && j < 2*N/3)\n        x[i].back() = vmfO.sample(rnd);\n    }\n  }\n  std::cout << \"have \" << x.size() << \" input data\" << std::endl;\n\n  std::vector<Eigen::Vector3f> xSum(1, Eigen::Vector3f::Zero());\n  std::vector<std::vector<uint32_t>> z(x.size());\n  for (size_t i=0; i<x.size(); ++i) \n    for (size_t j=0; j<x[i].size(); ++j)  {\n      xSum[0] += x[i][j];\n      z[i].push_back(0);\n    }\n  std::vector<float> counts(1, x.size()*x.size());\n  std::vector<vMF<float,3>> vmfs;\n  vMFprior<float> base(Eigen::Vector3f(0,0,1), .1, 0.0);\n  float logAlpha = log(10.);\n  float lambda = .1;\n\n  vmfs.push_back(base.sample(rnd));\n  for (size_t it=0; it<10000; ++it) {\n    // sample labels | parameters\n    size_t K = vmfs.size();\n    for (size_t i=0; i<x.size(); ++i) {\n      for (size_t j=0; j<x[i].size(); ++j) {\n        Eigen::VectorXf logPdfs(K+1);\n        Eigen::VectorXf pdfs(K+1);\n\n        Eigen::VectorXf neighNs = Eigen::VectorXf::Zero(K);\n        if (i+1<N) neighNs[z[i+1][j]] ++;\n        if (i>=1)  neighNs[z[i-1][j]] ++;\n        if (j+1<N) neighNs[z[i][j+1]] ++;\n        if (j>=1)  neighNs[z[i][j-1]] ++;\n\n//        if (i+1<N) neighNs[z[i+1][j]] += x[i+1][j].dot(x[i][j]);\n//        if (i>=1)  neighNs[z[i-1][j]] += x[i-1][j].dot(x[i][j]);\n//        if (j+1<N) neighNs[z[i][j+1]] += x[i][j+1].dot(x[i][j]);\n//        if (j>=1)  neighNs[z[i][j-1]] += x[i][j-1].dot(x[i][j]);\n\n//        if (i+1<N) neighNs[z[i+1][j]] += vmfs[z[i+1][j]].mu_.dot(x[i][j]);\n//        if (i>=1)  neighNs[z[i-1][j]] += vmfs[z[i-1][j]].mu_.dot(x[i][j]);\n//        if (j+1<N) neighNs[z[i][j+1]] += vmfs[z[i][j+1]].mu_.dot(x[i][j]);\n//        if (j>=1)  neighNs[z[i][j-1]] += vmfs[z[i][j-1]].mu_.dot(x[i][j]);\n\n//        if (i+1<N) neighNs[z[i+1][j]] += vmfs[z[i+1][j]].mu_.dot(vmfs[z[i][j]].mu_);\n//        if (i>=1)  neighNs[z[i-1][j]] += vmfs[z[i-1][j]].mu_.dot(vmfs[z[i][j]].mu_);\n//        if (j+1<N) neighNs[z[i][j+1]] += vmfs[z[i][j+1]].mu_.dot(vmfs[z[i][j]].mu_);\n//        if (j>=1)  neighNs[z[i][j-1]] += vmfs[z[i][j-1]].mu_.dot(vmfs[z[i][j]].mu_);\n\n        for (size_t k=0; k<K; ++k) {\n          logPdfs[k] = lambda*(neighNs[k]-4);\n          if (z[i][j] == k) {\n            // TODO what if last in cluster\n            logPdfs[k] += log(counts[k]-1)+vmfs[k].logPdf(x[i][j]);\n          } else {\n            logPdfs[k] += log(counts[k])+vmfs[k].logPdf(x[i][j]);\n          }\n        }\n        logPdfs[K] = logAlpha + base.logMarginal(x[i][j]);\n        logPdfs = logPdfs.array() - logSumExp<float>(logPdfs);\n        pdfs = logPdfs.array().exp();\n        size_t zPrev = z[i][j];\n        z[i][j] = sampleDisc(pdfs, rnd);\n        //      std::cout << z[i] << \" \" << K << \": \" << pdfs.transpose() << std::endl;\n        if (z[i][j] == K) {\n          vmfs.push_back(base.posterior(x[i][j],1).sample(rnd));\n          counts.push_back(0);\n          xSum.push_back(Eigen::Vector3f::Zero());\n          K++;\n        }\n        if (zPrev != z[i][j]) {\n          counts[zPrev] --;\n          counts[z[i][j]] ++;\n          xSum[zPrev] -= x[i][j];\n          xSum[z[i][j]] += x[i][j];\n        }\n      }\n    }\n//    std::cout << \"sample parameters\" << std::endl;\n    // sample parameters | labels\n//    for (size_t i=0; i<x.size(); ++i) {\n//      xSum[z[i]] += x[i]; // TODO: can fold in above as well\n//    }\n    for (size_t k=0; k<K; ++k) {\n      if (counts[k] > 0) {\n        vmfs[k] = base.posterior(xSum[k],counts[k]).sample(rnd);\n      }\n    }\n    std::cout << \"counts \" << K << \": \";\n    for (size_t k=0; k<K; ++k) if (counts[k] > 0) std::cout << counts[k] << \" \";\n    std::cout << \"\\ttaus: \" ;\n    for (size_t k=0; k<K; ++k) if (counts[k] > 0) std::cout << vmfs[k].tau_ << \" \";\n    std::cout << std::endl;\n  }\n  return 0;\n}\n", "meta": {"hexsha": "6a1f4ecaab4dc335f95ccf4ad795964b1c0dee0c", "size": 4809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/dpvmf/mainMRFDPvMF.cpp", "max_stars_repo_name": "jstraub/tdp", "max_stars_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-17T19:25:47.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-17T19:25:47.000Z", "max_issues_repo_path": "experiments/dpvmf/mainMRFDPvMF.cpp", "max_issues_repo_name": "jstraub/tdp", "max_issues_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-02T06:04:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-02T06:04:06.000Z", "max_forks_repo_path": "experiments/dpvmf/mainMRFDPvMF.cpp", "max_forks_repo_name": "jstraub/tdp", "max_forks_repo_head_hexsha": "dcab53662be5b88db1538cf831707b07ab96e387", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-09-17T18:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-11T12:52:57.000Z", "avg_line_length": 36.4318181818, "max_line_length": 87, "alphanum_fraction": 0.4874194219, "num_tokens": 1848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.41232493745016413}}
{"text": "#include \"NoiseModel2.h\"\n#include <iostream>\n#include <DNest4/code/Distributions/Cauchy.h>\n#include <DNest4/code/Utils.h>\n#include <Eigen/Sparse>\n\nnamespace CorrelatedNoise\n{\n\nNoiseModel2::NoiseModel2(int _ny, int _nx)\n:ny(_ny)\n,nx(_nx)\n,n(ny*nx)\n{\n\n}\n\n\nvoid NoiseModel2::from_prior(DNest4::RNG& rng)\n{\n    DNest4::Cauchy cauchy(0.0, 5.0);\n\n    // Fairly generic priors\n    do\n    {\n        coeff0 = cauchy.generate(rng);\n    }while(std::abs(coeff0) >= 100.0);\n    coeff0 = exp(coeff0);\n\n    do\n    {\n        coeff1 = cauchy.generate(rng);\n    }while(std::abs(coeff1) >= 100.0);\n    coeff1 = exp(coeff1);\n\n    correlation_logit = 5.0*rng.randn();\n}\n\ndouble NoiseModel2::perturb(DNest4::RNG& rng)\n{\n    double logH = 0.0;\n\n    DNest4::Cauchy cauchy(0.0, 5.0);\n\n    int which = rng.rand_int(3);\n\n    if(which == 0)\n    {\n        coeff0 = log(coeff0);\n        logH += cauchy.perturb(coeff0, rng);\n        if(std::abs(coeff0) >= 100.0)\n        {\n            coeff0 = 1.0;\n            return -1E300;\n        }\n        coeff0 = exp(coeff0);\n    }\n    else if(which == 1)\n    {\n        coeff1 = log(coeff1);\n        logH += cauchy.perturb(coeff1, rng);\n        if(std::abs(coeff1) >= 100.0)\n        {\n            coeff1 = 1.0;\n            return -1E300;\n        }\n        coeff1 = exp(coeff1);\n    }\n    else\n    {\n        logH -= -0.5*pow(correlation_logit/5.0, 2);\n        correlation_logit += 5.0*rng.randh();\n        logH += -0.5*pow(correlation_logit/5.0, 2);\n    }\n\n    return logH;\n}\n\n// More complete log likelihood\ndouble NoiseModel2::log_likelihood(const Eigen::MatrixXd& data,\n                                   const Eigen::MatrixXd& model,\n                                   const Eigen::MatrixXd& sigma_map) const\n{\n    // Convert from logit\n    double alpha = 0.25*exp(correlation_logit)/(1.0 + exp(correlation_logit));\n\n    // Find min of model\n    double min = 1E300;\n    for(int i=0; i<ny; ++i)\n        for(int j=0; j<nx; ++j)\n            if(model(i, j) < min)\n                min = model(i, j);\n\n    // Flatten data and turn it into standardised residuals\n    Eigen::VectorXd ys(n);\n    int k = 0;\n    double extra_log_determinant = 0.0;\n    double sd;\n    int num_non_masked = 0;\n    for(int i=0; i<ny; ++i)\n    {\n        for(int j=0; j<nx; ++j)\n        {\n            sd = sqrt(coeff0*coeff0 + coeff1*(model(i, j) - min)\n                                    + pow(sigma_map(i, j), 2));\n            if(sigma_map(i, j) < 1E100)\n            {\n                ys(k++) = (data(i, j) - model(i, j))/sd;\n                extra_log_determinant += 2*log(sd);\n                ++num_non_masked;\n            }\n            else\n            {\n                // Masked pixels\n                ys(k++) = 0.0;\n            }\n        }\n    }\n\n    double logL = -0.5*num_non_masked*log(2.0*M_PI) - 0.5*extra_log_determinant;\n\n    std::vector<Eigen::Triplet<double>> triplets;\n    int k1, k2;\n    for(int i=0; i<ny; ++i)\n    {\n        for(int j=0; j<nx; ++j)\n        {\n            // Here\n            k1 = j + i*nx;\n            triplets.emplace_back(k1, k1, 1.0);\n\n            // Pixel up\n            if(i > 0)\n            {\n                k2 = j + (i-1)*nx;\n//                std::cout << k1 << ' ' << k2 << std::endl;\n                triplets.emplace_back(k1, k2, -alpha);\n            }\n\n            // Pixel down\n            if(i < ny - 1)\n            {\n                k2 = j + (i+1)*nx;\n//                std::cout << k1 << ' ' << k2 << std::endl;\n                triplets.emplace_back(k1, k2, -alpha);\n            }\n\n            // Pixel left\n            if(j > 0)\n            {\n                k2 = (j-1) + i*nx;\n//                std::cout << k1 << ' ' << k2 << std::endl;\n                triplets.emplace_back(k1, k2, -alpha);\n            }\n\n            // Pixel right\n            if(j < nx - 1)\n            {\n                k2 = (j+1) + i*nx;\n//                std::cout << k1 << ' ' << k2 << std::endl;\n                triplets.emplace_back(k1, k2, -alpha);\n            }\n\n        }\n    }\n\n    // Make the sparse precision matrix\n    Eigen::SparseMatrix<double> sparse_mat(n, n);\n    sparse_mat.setFromTriplets(triplets.begin(), triplets.end());\n\n    // Term in the exponential\n    logL += -0.5*ys.transpose()*sparse_mat*ys;\n\n    // Use LDLT for log determinant\n    Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> ldlt;\n    ldlt.compute(sparse_mat);\n    Eigen::VectorXd D = ldlt.vectorD();\n\n    // log det of C, not of anything else!!!\n    double log_det = 0.0;\n    for(int i=0; i<n; ++i)\n        log_det += -log(D(i));\n    logL += -0.5*log_det;\n\n    if(std::isnan(logL) || std::isinf(logL))\n        logL = -1E300;\n\n    return logL;\n}\n\nvoid NoiseModel2::print(std::ostream& out) const\n{\n    out << coeff0 << ' ' << coeff1 << ' ' << correlation_logit;\n}\n\nstd::string NoiseModel2::description()\n{\n    return \"coeff0, coeff1, correlation_logit, \";\n}\n\nstd::ostream& operator << (std::ostream& out, const NoiseModel2& m)\n{\n    m.print(out);\n    return out;\n}\n\n} // namespace CorrelatedNoise\n\n", "meta": {"hexsha": "b1e0576d2bf67ed24288b0f7bef2a7b9ce51dc2c", "size": 4993, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NoiseModel2.cpp", "max_stars_repo_name": "eggplantbren/CorrelatedNoise", "max_stars_repo_head_hexsha": "af326f9c092e76c24f707164c581e340e6ff2cf3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-16T20:05:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T20:05:48.000Z", "max_issues_repo_path": "NoiseModel2.cpp", "max_issues_repo_name": "eggplantbren/CorrelatedNoise", "max_issues_repo_head_hexsha": "af326f9c092e76c24f707164c581e340e6ff2cf3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NoiseModel2.cpp", "max_forks_repo_name": "eggplantbren/CorrelatedNoise", "max_forks_repo_head_hexsha": "af326f9c092e76c24f707164c581e340e6ff2cf3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8899521531, "max_line_length": 80, "alphanum_fraction": 0.4874824755, "num_tokens": 1500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321889812553, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.41225536838587246}}
{"text": "/* Siconos-Kernel, Copyright INRIA 2005-2012.\n * Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n * Siconos is a free software; you can redistribute it and/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n * Siconos is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with Siconos; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n *\n * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr\n */\n\n#ifndef __determinant__\n#define __determinant__\n\n\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n\nnamespace ublas = boost::numeric::ublas;\n\n\ntemplate<class matrix_T>\ndouble determinant(ublas::matrix_expression<matrix_T> const& mat_r)\n{\n  double det = 1.0;\n\n  matrix_T mLu(mat_r());\n  ublas::permutation_matrix<std::size_t> pivots(mat_r().size1());\n\n  int is_singular = lu_factorize(mLu, pivots);\n\n  if (!is_singular)\n  {\n    for (std::size_t i=0; i < pivots.size(); ++i)\n    {\n      if (pivots(i) != i)\n        det *= -1.0;\n\n      det *= mLu(i,i);\n    }\n  }\n  else\n    det = 0.0;\n\n  return det;\n}\n\n\n#endif\n", "meta": {"hexsha": "c8de61323ea5a7338b1b237aa0e4294b65be9dfc", "size": 1706, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost_contribs/determinant.hpp", "max_stars_repo_name": "siconos/siconos-deb", "max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "externals/boost_contribs/determinant.hpp", "max_issues_repo_name": "siconos/siconos-deb", "max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "externals/boost_contribs/determinant.hpp", "max_forks_repo_name": "siconos/siconos-deb", "max_forks_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0793650794, "max_line_length": 78, "alphanum_fraction": 0.7133645955, "num_tokens": 466, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4122420936489222}}
{"text": "/*\n Copyright (C) 2017 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n#include <boost/make_shared.hpp>\n#include <ql/math/interpolations/bilinearinterpolation.hpp>\n#include <ql/math/interpolations/linearinterpolation.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/yield/forwardcurve.hpp>\n#include <qle/termstructures/blackvariancesurfacemoneyness.hpp>\n\nusing namespace std;\n\nnamespace QuantExt {\n\nBlackVarianceSurfaceMoneyness::BlackVarianceSurfaceMoneyness(\n    const Calendar& cal, const Handle<Quote>& spot, const std::vector<Time>& times, const std::vector<Real>& moneyness,\n    const std::vector<std::vector<Handle<Quote> > >& blackVolMatrix, const DayCounter& dayCounter, bool stickyStrike)\n    : BlackVarianceTermStructure(0, cal), stickyStrike_(stickyStrike), spot_(spot), dayCounter_(dayCounter),\n      moneyness_(moneyness), quotes_(blackVolMatrix) {\n\n    QL_REQUIRE(times.size() == blackVolMatrix.front().size(), \"mismatch between times vector and vol matrix colums\");\n    QL_REQUIRE(moneyness_.size() == blackVolMatrix.size(), \"mismatch between moneyness vector and vol matrix rows\");\n\n    QL_REQUIRE(times[0] >= 0, \"cannot have times[0] < 0\");\n\n    if (stickyStrike) {\n        // we don't want to know if the spot has changed - we take a copy here\n        spot_ = Handle<Quote>(boost::make_shared<SimpleQuote>(spot->value()));\n    } else {\n        registerWith(spot_);\n    }\n\n    Size j, i;\n    // internally times_ is one bigger than the input \"times\"\n    times_ = std::vector<Time>(times.size() + 1);\n    times_[0] = 0.0;\n    variances_ = Matrix(moneyness_.size(), times.size() + 1);\n    for (i = 0; i < moneyness_.size(); i++) {\n        variances_[i][0] = 0.0;\n    }\n    for (j = 1; j <= times.size(); j++) {\n        times_[j] = times[j - 1];\n        QL_REQUIRE(times_[j] > times_[j - 1], \"dates must be sorted unique!\");\n        for (i = 0; i < moneyness_.size(); i++) {\n            variances_[i][j] = 0.0;\n            registerWith(blackVolMatrix[i][j - 1]);\n        }\n    }\n\n    varianceSurface_ =\n        Bilinear().interpolate(times_.begin(), times_.end(), moneyness_.begin(), moneyness_.end(), variances_);\n    notifyObservers();\n}\n\nvoid BlackVarianceSurfaceMoneyness::update() {\n    TermStructure::update();\n    LazyObject::update();\n}\n\nvoid BlackVarianceSurfaceMoneyness::performCalculations() const {\n    for (Size j = 1; j < variances_.columns(); j++) {\n        for (Size i = 0; i < variances_.rows(); i++) {\n            Real vol = quotes_[i][j - 1]->value();\n            variances_[i][j] = times_[j] * vol * vol;\n        }\n    }\n    varianceSurface_.update();\n}\n\nReal BlackVarianceSurfaceMoneyness::blackVarianceImpl(Time t, Real strike) const {\n\n    calculate();\n\n    if (t == 0.0)\n        return 0.0;\n\n    return blackVarianceMoneyness(t, moneyness(t, strike));\n}\n\nReal BlackVarianceSurfaceMoneyness::blackVarianceMoneyness(Time t, Real m) const {\n    if (t <= times_.back())\n        return varianceSurface_(t, m, true);\n    else\n        return varianceSurface_(times_.back(), m, true) * t / times_.back();\n}\n\nBlackVarianceSurfaceMoneynessSpot::BlackVarianceSurfaceMoneynessSpot(\n    const Calendar& cal, const Handle<Quote>& spot, const std::vector<Time>& times, const std::vector<Real>& moneyness,\n    const std::vector<std::vector<Handle<Quote> > >& blackVolMatrix, const DayCounter& dayCounter, bool stickyStrike)\n    : BlackVarianceSurfaceMoneyness(cal, spot, times, moneyness, blackVolMatrix, dayCounter, stickyStrike) {}\n\nReal BlackVarianceSurfaceMoneynessSpot::moneyness(Time, Real strike) const {\n    if (strike == Null<Real>() || strike == 0)\n        return 1.0;\n    else\n        return strike / spot_->value();\n}\n\nBlackVarianceSurfaceMoneynessForward::BlackVarianceSurfaceMoneynessForward(\n    const Calendar& cal, const Handle<Quote>& spot, const std::vector<Time>& times, const std::vector<Real>& moneyness,\n    const std::vector<std::vector<Handle<Quote> > >& blackVolMatrix, const DayCounter& dayCounter,\n    const Handle<YieldTermStructure>& forTS, const Handle<YieldTermStructure>& domTS, bool stickyStrike)\n    : BlackVarianceSurfaceMoneyness(cal, spot, times, moneyness, blackVolMatrix, dayCounter, stickyStrike),\n      forTS_(forTS), domTS_(domTS) {\n\n    if (!stickyStrike) {\n        QL_REQUIRE(!forTS_.empty(), \"foreign discount curve required for atmf surface\");\n        QL_REQUIRE(!domTS_.empty(), \"foreign discount curve required for atmf surface\");\n        registerWith(forTS_);\n        registerWith(domTS_);\n    } else {\n        for (Size i = 0; i < times_.size(); i++) {\n            Time t = times_[i];\n            Real fwd = spot_->value() * forTS_->discount(t) / domTS_->discount(t);\n            forwards_.push_back(fwd);\n        }\n        forwardCurve_ = Linear().interpolate(times_.begin(), times_.end(), forwards_.begin());\n    }\n}\n\nReal BlackVarianceSurfaceMoneynessForward::moneyness(Time t, Real strike) const {\n    Real fwd;\n    if (strike == Null<Real>() || strike == 0)\n        return 1.0;\n    else {\n        if (stickyStrike_)\n            fwd = forwardCurve_(t, true);\n        else\n            fwd = spot_->value() * forTS_->discount(t) / domTS_->discount(t);\n        return strike / fwd;\n    }\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "d9d402d7c51556a3b7a083c35a5d7176d13f8408", "size": 5890, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/blackvariancesurfacemoneyness.cpp", "max_stars_repo_name": "paul-giltinan/Engine", "max_stars_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantExt/qle/termstructures/blackvariancesurfacemoneyness.cpp", "max_issues_repo_name": "paul-giltinan/Engine", "max_issues_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/qle/termstructures/blackvariancesurfacemoneyness.cpp", "max_forks_repo_name": "paul-giltinan/Engine", "max_forks_repo_head_hexsha": "49b6e142905ca2cce93c2ae46e9ac69380d9f7a1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5302013423, "max_line_length": 119, "alphanum_fraction": 0.6775891341, "num_tokens": 1582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743168019989179, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4120647175871202}}
{"text": "#include \"TimeIntegrator.h\"\n\n#include <exception>\n#include <Eigen/Dense>\n#include <cinder/Log.h>\n\nnamespace ar\n{\n    \n    void TimeIntegrator_Newmark1::performStep(real deltaT, const VectorX & mass, const MatrixX & damping, const MatrixX & stiffness, const VectorX & load)\n    {\n        assertSize(mass);\n        assertSize(damping);\n        assertSize(stiffness);\n        assertSize(load);\n\n        prevU = currentU;\n        prevUDot = currentUDot;\n\n        MatrixX massMatrix = mass.asDiagonal();\n        MatrixX A = getMatrixPartA(stiffness, damping, mass, load, deltaT, theta);\n        VectorX b \n            = getMatrixPartB(stiffness, damping, mass, load, deltaT, theta) * prevU\n            + getMatrixPartC(stiffness, damping, mass, load, deltaT, theta) * prevUDot\n            + getMatrixPartD(stiffness, damping, mass, load, deltaT, theta);\n        currentU = solveDense(A, b);\n\n        currentUDot = computeUdot(currentU, prevU, prevUDot, deltaT, theta);\n    }\n    \n    void TimeIntegrator_Newmark2::performStep(real deltaT, const VectorX & mass, const MatrixX & damping, const MatrixX & stiffness, const VectorX & load)\n    {\n        assertSize(mass);\n        assertSize(damping);\n        assertSize(stiffness);\n        assertSize(load);\n\n        prevU = currentU;\n        prevUDot = currentUDot;\n        prevUDotDot = currentUDotDot;\n\n        CI_LOG_V(\"prevU: \" << prevU.transpose());\n        CI_LOG_V(\"prevUDot: \" << prevUDot.transpose());\n        CI_LOG_V(\"prevUDotDot: \" << prevUDotDot.transpose());\n\n        MatrixX massMatrix = mass.asDiagonal();\n        MatrixX A = (4 / (deltaT*deltaT)) * massMatrix + (2 / deltaT) * damping + stiffness;\n        VectorX b = load\n            + massMatrix * ((4 / (deltaT*deltaT)) * (prevU + prevUDot) + prevUDotDot)\n            + damping * ((2 / deltaT) * prevU + prevUDot);\n        currentU = solveDense(A, b);\n        CI_LOG_V(\"A:\\n\" << A);\n        CI_LOG_V(\"b:\\n\" << b.transpose());\n        CI_LOG_V(\"solution:\\n\" << currentU.transpose());\n\n        currentUDot = (2 / deltaT) * (currentU - prevU) - prevUDot;\n        currentUDotDot = (4 / (deltaT*deltaT)) * (currentU - prevU - deltaT * prevUDot) - prevUDotDot;\n    }\n    \n    void TimeIntegrator_ExplicitCentralDifferences::performStep(real deltaT, const VectorX & mass, const MatrixX & damping, const MatrixX & stiffness, const VectorX & load)\n    {\n        assertSize(mass);\n        assertSize(damping);\n        assertSize(stiffness);\n        assertSize(load);\n\n        prevPrevU = prevU;\n        prevU = currentU;\n\n        MatrixX massMatrix = mass.asDiagonal();\n        MatrixX A = (1 / (deltaT*deltaT)) * massMatrix + (1 / (2 * deltaT)) * damping;\n        VectorX b = load\n            + ((2 / (deltaT*deltaT)) * massMatrix - stiffness) * prevU\n            + ((-1 / (deltaT*deltaT)) * massMatrix + (1 / (2 * deltaT)) * damping) * prevPrevU;\n        currentU = solveDense(A, b);\n    }\n\n    void TimeIntegrator_ImplicitLinearAcceleration::performStep(real deltaT, const VectorX & mass, const MatrixX & damping, const MatrixX & stiffness, const VectorX & load)\n    {\n        assertSize(mass);\n        assertSize(damping);\n        assertSize(stiffness);\n        assertSize(load);\n\n        prevU = currentU;\n        prevUDot = currentUDot;\n        prevUDotDot = currentUDotDot;\n\n        MatrixX massMatrix = mass.asDiagonal();\n        MatrixX A = (massMatrix + (deltaT/2)*damping + (deltaT*deltaT/6)*stiffness);\n        VectorX b = ((-deltaT / 2) * damping - (deltaT*deltaT / 3) *  stiffness) * prevUDotDot\n            - stiffness * prevU\n            - damping * prevUDot\n            - deltaT * stiffness * prevUDot\n            + load;\n        currentUDotDot = solveDense(A, b);\n\n        currentUDot = prevUDot + (deltaT / 2) * (currentUDotDot + prevUDotDot);\n        currentU = prevU + deltaT * prevUDot + (deltaT*deltaT / 6)*(currentUDotDot + 2 * prevUDotDot);\n    }\n\n    void TimeIntegrator_Newmark3::performStep(real deltaT, const VectorX & mass, const MatrixX & damping, const MatrixX & stiffness, const VectorX & load)\n    {\n        assertSize(mass);\n        assertSize(damping);\n        assertSize(stiffness);\n        assertSize(load);\n\n        prevU = currentU;\n        prevUDot = currentUDot;\n        prevUDotDot = currentUDotDot;\n\n        MatrixX massMatrix = mass.asDiagonal();\n        MatrixX A = ((6 / (deltaT*deltaT))*massMatrix + (3 / deltaT)*damping + stiffness);\n        VectorX b = load\n            + (3 * massMatrix + (deltaT / 2) * damping) * prevUDotDot\n            + ((6 / deltaT) * massMatrix + 3 * damping) * prevUDot;\n        VectorX diffX = solveDense(A, b);\n\n        currentU = prevU + diffX;\n        currentUDot = -2 * prevUDot - (deltaT / 2)*prevUDotDot + (3 / deltaT) * diffX;\n        MatrixX invMassMatrix = mass.cwiseInverse().asDiagonal();\n        currentUDotDot = -invMassMatrix * (damping * currentUDot + stiffness * currentU - load);\n    }\n\n    void TimeIntegrator_HHTalpha::performStep(real deltaT, const VectorX & mass, const MatrixX & damping, const MatrixX & stiffness, const VectorX & load)\n    {\n        assertSize(mass);\n        assertSize(damping);\n        assertSize(stiffness);\n        assertSize(load);\n\n        prevU = currentU;\n        prevUDot = currentUDot;\n        prevUDotDot = currentUDotDot;\n\n        MatrixX massMatrix = mass.asDiagonal();\n        MatrixX A = massMatrix + (deltaT * (1 - alpha) * gamma) * damping + (deltaT * deltaT * (1 - alpha) * beta) * stiffness;\n        VectorX b = load\n            - ((deltaT * (1 - alpha) * (1 - gamma)) * damping + ((deltaT * deltaT) * (1 - alpha) * (0.5f - gamma)) * stiffness) * prevUDotDot\n            - (damping + (deltaT * (1 - alpha)) * stiffness) * prevUDot\n            - stiffness * prevU;\n        currentUDotDot = solveDense(A, b);\n\n        currentU = prevU + deltaT * prevUDot + deltaT * deltaT*((0.5f - beta)*prevUDotDot + beta * currentUDotDot);\n        currentUDot = prevUDot + deltaT * ((1 - gamma)*prevUDotDot + gamma * currentUDotDot);\n    }\n\n}\n", "meta": {"hexsha": "ee146a3a38417f039872bc294b63d4490bc5a229", "size": 5963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ActionReconstructionLib/TimeIntegrator2.cpp", "max_stars_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_stars_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-03-08T18:28:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T20:32:56.000Z", "max_issues_repo_path": "ActionReconstructionLib/TimeIntegrator2.cpp", "max_issues_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_issues_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ActionReconstructionLib/TimeIntegrator2.cpp", "max_forks_repo_name": "shamanDevel/SparseSurfaceConstraints", "max_forks_repo_head_hexsha": "88357ff847369a45b9f16f9f44159196138f9147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-26T01:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-18T13:32:46.000Z", "avg_line_length": 39.7533333333, "max_line_length": 172, "alphanum_fraction": 0.6037229582, "num_tokens": 1694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.41198082790069357}}
{"text": "/*\n\nPart of Aalto University Game Tools. See LICENSE.txt for licensing info.\n\n*/\n\n#ifndef GENERIC_DENSITY_FOREST_LINEAR_H\n#define GENERIC_DENSITY_FOREST_LINEAR_H\n\n\n\n\n#include <Eigen/Eigen>\n#include <memory>\n#include <list>\n#include <deque>\n#include <omp.h>\n#include <algorithm>\n#include \"ProbUtils.hpp\"\n#include \"MathUtils.h\"\n\n#include <exception>\n\nclass ZeroKeyVectorException : std::exception\n{\npublic:\n\tconst char* what() const throw() // my call to the std exception class function (doesn't nessasarily have to be virtual).\n\t{\n\t\treturn \"The key vector does not match normal.\"; // my error message\n\t}\n};\n\n\n\ntypedef float generic_density_forest_scalar;\ntypedef Eigen::Matrix<generic_density_forest_scalar, Eigen::Dynamic, Eigen::Dynamic> generic_density_forest_matrix;\ntypedef Eigen::Matrix<generic_density_forest_scalar, Eigen::Dynamic, 1> generic_density_forest_vector;\n\ntemplate<typename first_type>\nstatic bool second_is_smaller(const std::pair<first_type, generic_density_forest_scalar>& first, const std::pair<first_type, generic_density_forest_scalar>& second) {\n\treturn first.second < second.second;\n}\n\ntemplate<typename data_type>\nstatic bool is_in_array(const data_type elements[], int end_idx, const data_type element) {\n\tfor (int i = 0; i < end_idx; i++) {\n\t\tif (elements[i] == element) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nenum Covariance_computation_mode\n{\n\tAXIS_ALIGNED, FULL\n};\n\nenum Split_Optimization_Mode\n{\n\tsoINFO_GAIN, soKMEANS\n};\n\n\ntemplate<typename DataType>\nclass GenericDensityNode\n{\n\n\ttypedef GenericDensityNode<DataType>* NodePointer;\n\ttypedef std::unique_ptr<GenericDensityNode<DataType> > UniqueNodePointer;\nprivate:\n\n\tgeneric_density_forest_vector left_mean_;\n\tgeneric_density_forest_vector right_mean_;\n\n\tgeneric_density_forest_matrix left_cov_;\n\tgeneric_density_forest_matrix right_cov_;\n\npublic:\n\tstatic const int MAX_SAMPLES_FOR_INFO_GAIN_MEASURING = 256;\n\n\tgeneric_density_forest_vector separating_normal_;\n\tgeneric_density_forest_scalar separating_bias_;\n\tstd::pair<generic_density_forest_vector, generic_density_forest_matrix> gaussian_model_;\n\n\t//Parameters for regressor use.\n\tgeneric_density_forest_matrix regressor_mean_;\n\tgeneric_density_forest_vector regressand_mean_;\n\tgeneric_density_forest_matrix regressand_cov_cholesky_;\n\tgeneric_density_forest_matrix regression_;\n\n\tCovariance_computation_mode covariance_computation_mode_;\n\n\tNodePointer parent_;\n\tUniqueNodePointer left_child_;\n\tUniqueNodePointer right_child_;\n\n\tSplit_Optimization_Mode split_mode;\n\tstd::list<std::unique_ptr<DataType> > data_items_;\n\n\tconst generic_density_forest_vector* (*get_key_vector_)(const DataType& datum);\n\n\tvoid copy_data(GenericDensityNode<DataType>& other) {\n\t\tseparating_bias_ = other.separating_bias_;\n\t\tseparating_normal_ = other.separating_normal_;\n\t\tgaussian_model_ = other.gaussian_model_;\n\t\tregressor_mean_ = other.regressor_mean_;\n\t\tregressand_mean_ = other.regressand_mean_;\n\t\tregressand_cov_cholesky_ = other.regressand_cov_cholesky_;\n\t\tregression_ = other.regression_;\n\t\tget_key_vector_ = other.get_key_vector_;\n\t\tcovariance_computation_mode_ = other.covariance_computation_mode_;\n\t\tsplit_mode = other.split_mode;\n\n\t\tstd::list<std::unique_ptr<DataType> >::iterator iter = other.data_items_.begin();\n\n\t\twhile (iter != other.data_items_.end()) {\n\t\t\tdata_items_.push_back(std::unique_ptr<DataType>(new DataType));\n\t\t\t*(data_items_.back()) = **iter;\n\t\t\titer++;\n\t\t}\n\n\t}\n\n\tGenericDensityNode() {\n\t\tparent_ = nullptr;\n\t\tleft_child_ = UniqueNodePointer(nullptr);\n\t\tright_child_ = UniqueNodePointer(nullptr);\n\t\tgaussian_model_ = std::make_pair<generic_density_forest_vector, generic_density_forest_matrix>(generic_density_forest_vector::Zero(0), generic_density_forest_matrix::Zero(0, 0));\n\t\tseparating_bias_ = std::numeric_limits<generic_density_forest_scalar>::quiet_NaN();\n\t\tseparating_normal_ = generic_density_forest_vector::Zero(0);\n\t\tregressor_mean_ = generic_density_forest_vector::Zero(0);\n\t\tregressand_mean_ = generic_density_forest_vector::Zero(0);\n\t\tregressand_cov_cholesky_ = generic_density_forest_matrix::Zero(0, 0);\n\t\tregression_ = generic_density_forest_matrix::Zero(0, 0);\n\t\tcovariance_computation_mode_ = AXIS_ALIGNED;\n\t\tsplit_mode = soINFO_GAIN;\n\t\tget_key_vector_ = nullptr;\n\t}\n\n\tGenericDensityNode(GenericDensityNode<DataType>& other) {\n\t\tparent_ = nullptr;\n\t\tleft_child_ = UniqueNodePointer(nullptr);\n\t\tright_child_ = UniqueNodePointer(nullptr);\n\t\tcopy_data(other);\n\t}\n\n\tGenericDensityNode<DataType> operator=(GenericDensityNode<DataType>& other) {\n\t\tparent_ = nullptr;\n\t\tleft_child_ = UniqueNodePointer(nullptr);\n\t\tright_child_ = UniqueNodePointer(nullptr);\n\t\tcopy_data(other);\n\n\t\treturn *this;\n\t}\n\n\tvoid build_empty_tree(int depth, int data_dimension, const generic_density_forest_vector* (*key_vector_function)(const DataType&)) {\n\n\t\tget_key_vector_ = key_vector_function;\n\t\tseparating_bias_ *= 0;\n\t\tseparating_normal_ = generic_density_forest_vector::Zero(data_dimension);\n\t\tleft_mean_ = generic_density_forest_vector::Zero(data_dimension);\n\t\tright_mean_ = generic_density_forest_vector::Zero(data_dimension);\n\n\t\tif (covariance_computation_mode_ == Covariance_computation_mode::FULL) {\n\t\t\tleft_cov_ = generic_density_forest_matrix::Zero(data_dimension, data_dimension);\n\t\t\tright_cov_ = generic_density_forest_matrix::Zero(data_dimension, data_dimension);\n\t\t}\n\n\t\tif (covariance_computation_mode_ == Covariance_computation_mode::AXIS_ALIGNED) {\n\t\t\tleft_cov_ = generic_density_forest_matrix::Zero(data_dimension, 1);\n\t\t\tright_cov_ = generic_density_forest_matrix::Zero(data_dimension, 1);\n\t\t}\n\n\t\tgaussian_model_.first = generic_density_forest_vector::Zero(data_dimension);\n\t\tgaussian_model_.second = generic_density_forest_matrix::Zero(data_dimension, data_dimension);\n\n\t\tif (depth < 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tUniqueNodePointer tmp = UniqueNodePointer(new GenericDensityNode<DataType>());\n\t\ttmp->get_key_vector_ = get_key_vector_;\n\t\tsetLeftChild(tmp);\n\t\tleft_child_->build_empty_tree(depth - 1, data_dimension, key_vector_function);\n\t\ttmp = UniqueNodePointer(new GenericDensityNode<DataType>());\n\t\ttmp->get_key_vector_ = get_key_vector_;\n\t\tsetRightChild(tmp);\n\t\tright_child_->build_empty_tree(depth - 1, data_dimension, key_vector_function);\n\n\t}\n\n\tvoid setLeftChild(UniqueNodePointer& newLeftChild) {\n\n\t\tif (newLeftChild.get()) {\n\t\t\tif (left_child_.get()) {\n\t\t\t\tleft_child_->parent_ = nullptr;\n\t\t\t}\n\t\t\tleft_child_ = std::move(newLeftChild);\n\t\t\tleft_child_->parent_ = this;\n\t\t}\n\t\telse {\n\t\t\tleft_child_ = UniqueNodePointer(nullptr);\n\t\t}\n\n\t}\n\n\tvoid setRightChild(UniqueNodePointer& newRightChild) {\n\n\t\tif (newRightChild.get()) {\n\t\t\tif (right_child_.get()) {\n\t\t\t\tright_child_->parent_ = nullptr;\n\t\t\t}\n\t\t\tright_child_ = std::move(newRightChild);\n\t\t\tright_child_->parent_ = this;\n\t\t}\n\t\telse {\n\t\t\tright_child_ = UniqueNodePointer(nullptr);\n\t\t}\n\t}\n\n\tbool is_empty_leaf(void) {\n\t\tif (!hasChildren()) {\n\n\t\t\tif (data_items_.size() == 0) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t}\n\t\treturn false;\n\t}\n\n\tNodePointer get_leaf(const generic_density_forest_vector &key_vector) {\n\t\tNodePointer node = this;\n\t\tNodePointer prev_node = node;\n\t\twhile (node) {\n\t\t\tprev_node = node;\n\n\t\t\tif (node->left_or_right(key_vector)) {\n\t\t\t\tnode = node->right_child_.get();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnode = node->left_child_.get();\n\t\t\t}\n\n\t\t}\n\t\treturn prev_node;\n\t}\n\n\tNodePointer get_leaf(const DataType& datum) {\n\t\tconst generic_density_forest_vector &key_vector = *(get_key_vector_(datum));\n\t\treturn get_leaf(key_vector);\n\t}\n\n\tvoid form_regression_parameters(int regressor_dim) {\n\n\t\tint regressand_dim = gaussian_model_.first.size() - regressor_dim;\n\n\t\tassert(regressand_dim > 0);\n\n\t\tregressor_mean_ = gaussian_model_.first.tail(regressor_dim);\n\t\tregressand_mean_ = gaussian_model_.first.head(regressand_dim);\n\n\t\tgeneric_density_forest_matrix cov_xy = gaussian_model_.second.topRightCorner(regressand_dim, regressor_dim);\n\t\tgeneric_density_forest_matrix cov_yy = gaussian_model_.second.bottomRightCorner(regressor_dim, regressor_dim);\n\t\tgeneric_density_forest_matrix cov_yy_inv = invert_positive_definite(cov_yy);\n\n\t\tregression_ = cov_xy*cov_yy_inv;\n\n\t\tregressand_cov_cholesky_ = gaussian_model_.second.topLeftCorner(regressand_dim, regressand_dim) - cov_xy*cov_yy_inv*cov_xy.transpose();\n\t\tregressand_cov_cholesky_ = make_invertable_positive_definite(regressand_cov_cholesky_).llt().matrixL();\n\n\t}\n\n\tbool hasChildren() {\n\t\tif (right_child_.get() && left_child_.get()) {\n\t\t\treturn true;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tgeneric_density_forest_scalar information_gain(std::list<DataType* >& left_data, std::list<DataType* >& right_data) {\n\n\t\tif (left_data.size() == 0 || right_data.size() == 0) {\n\t\t\treturn -std::numeric_limits<generic_density_forest_scalar>::infinity();\n\t\t}\n\n\t\tconst generic_density_forest_vector& tmp_key_vector = *get_key_vector_(**left_data.begin());\n\t\tint data_dim = tmp_key_vector.size();\n\n\t\tif (left_cov_.rows() != data_dim || right_cov_.rows() != data_dim) {\n\n\t\t\tif (covariance_computation_mode_ == Covariance_computation_mode::FULL) {\n\t\t\t\tleft_cov_ = generic_density_forest_matrix::Zero(data_dim, data_dim);\n\t\t\t\tright_cov_ = generic_density_forest_matrix::Zero(data_dim, data_dim);\n\t\t\t}\n\n\t\t\tif (covariance_computation_mode_ == Covariance_computation_mode::AXIS_ALIGNED) {\n\t\t\t\tleft_cov_ = generic_density_forest_matrix::Zero(data_dim, 1);\n\t\t\t\tright_cov_ = generic_density_forest_matrix::Zero(data_dim, 1);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tleft_cov_ *= 0;\n\t\t\tright_cov_ *= 0;\n\t\t}\n\n\t\tif (left_mean_.size() != data_dim || right_mean_.size() != data_dim) {\n\t\t\tleft_mean_ = generic_density_forest_vector::Zero(data_dim);\n\t\t\tright_mean_ = generic_density_forest_vector::Zero(data_dim);\n\t\t}\n\t\telse {\n\t\t\tleft_mean_ *= 0;\n\t\t\tright_mean_ *= 0;\n\t\t}\n\n\t\tint left_size = 0;\n\t\tint right_size = 0;\n\n\t\tfor (DataType* datum : left_data) {\n\t\t\tconst generic_density_forest_vector& sample_key_vector = *get_key_vector_(*datum);\n\t\t\tleft_mean_ += sample_key_vector;\n\t\t\tleft_size++;\n\t\t}\n\t\tleft_mean_ /= (generic_density_forest_scalar)left_size;\n\n\t\tfor (DataType* datum : right_data) {\n\t\t\tconst generic_density_forest_vector& sample_key_vector = *get_key_vector_(*datum);\n\t\t\tright_mean_ += sample_key_vector;\n\t\t\tright_size++;\n\t\t}\n\t\tright_mean_ /= (generic_density_forest_scalar)right_size;\n\n\t\tgeneric_density_forest_vector diff;\n\n\t\tfor (DataType* datum : left_data) {\n\t\t\tconst generic_density_forest_vector& sample_key_vector = *get_key_vector_(*datum);\n\t\t\tdiff = sample_key_vector - left_mean_;\n\t\t\tif (covariance_computation_mode_ == Covariance_computation_mode::FULL) {\n\t\t\t\tleft_cov_ += diff*diff.transpose();\n\t\t\t}\n\n\t\t\tif (covariance_computation_mode_ == Covariance_computation_mode::AXIS_ALIGNED) {\n\t\t\t\tleft_cov_ += diff.cwiseAbs2();\n\t\t\t}\n\t\t}\n\t\tleft_cov_ /= (generic_density_forest_scalar)left_size;\n\n\t\tfor (DataType* datum : right_data) {\n\t\t\tconst generic_density_forest_vector& sample_key_vector = *get_key_vector_(*datum);\n\t\t\tdiff = sample_key_vector - right_mean_;\n\n\t\t\tif (covariance_computation_mode_ == Covariance_computation_mode::FULL) {\n\t\t\t\tright_cov_ += diff*diff.transpose();\n\t\t\t}\n\n\t\t\tif (covariance_computation_mode_ == Covariance_computation_mode::AXIS_ALIGNED) {\n\t\t\t\tright_cov_ += diff.cwiseAbs2();\n\t\t\t}\n\t\t}\n\t\tright_cov_ /= (generic_density_forest_scalar)right_size;\n\n\t\tint joint_size = left_size + right_size;\n\n\t\tgeneric_density_forest_scalar info_gain = (generic_density_forest_scalar)0;\n\t\tif (covariance_computation_mode_ == Covariance_computation_mode::FULL) {\n\t\t\tinfo_gain -= (generic_density_forest_scalar)left_size / (generic_density_forest_scalar)joint_size*log_determinant_positive_definite(left_cov_);\n\t\t\tassert(finiteNumber(info_gain));\n\t\t\tinfo_gain -= (generic_density_forest_scalar)right_size / (generic_density_forest_scalar)joint_size*log_determinant_positive_definite(right_cov_);\n\t\t\tassert(finiteNumber(info_gain));\n\t\t}\n\n\t\tif (covariance_computation_mode_ == Covariance_computation_mode::AXIS_ALIGNED) {\n\t\t\tfor (int i = 0; i < left_cov_.size(); i++) {\n\t\t\t\tleft_cov_(i) = std::max(std::numeric_limits<generic_density_forest_scalar>::min(), left_cov_(i));\n\t\t\t}\n\t\t\tinfo_gain -= (generic_density_forest_scalar)left_size / (generic_density_forest_scalar)joint_size*(left_cov_.array().log().sum());\n\t\t\t//assert(finiteNumber(info_gain));\n\t\t\tfor (int i = 0; i < right_cov_.size(); i++) {\n\t\t\t\tright_cov_(i) = std::max(std::numeric_limits<generic_density_forest_scalar>::min(), right_cov_(i));\n\t\t\t}\n\t\t\tinfo_gain -= (generic_density_forest_scalar)right_size / (generic_density_forest_scalar)joint_size*(right_cov_.array().log().sum());\n\t\t\t//assert(finiteNumber(info_gain));\n\t\t}\n\n\t\treturn info_gain;\n\n\t}\n\n\n\n\n\t//generic_density_forest_scalar information_gain_maximum_separation(std::vector<DataType*> left_data, std::vector<DataType*> right_data){\n\n\t//\tgeneric_density_forest_scalar margin = std::numeric_limits<generic_density_forest_scalar>::infinity();\n\t//\tgeneric_density_forest_scalar current_margin = std::numeric_limits<generic_density_forest_scalar>::infinity();\n\n\t//\tfor (DataType* datum : left_data){\n\t//\t\tcurrent_margin = std::abs(separating_bias_ + separating_normal_.dot(*get_key_vector_(*datum)));\n\t//\t\tmargin = std::min(margin,current_margin);\n\t//\t}\n\n\t//\tfor (DataType* datum : right_data){\n\t//\t\tcurrent_margin = std::abs(separating_bias_ + separating_normal_.dot(*get_key_vector_(*datum)));\n\t//\t\tmargin = std::min(margin,current_margin);\n\t//\t}\n\n\t//\treturn margin*left_data.size()*right_data.size();\n\n\t//}\n\n\n\t////Obsolete\n\t//std::vector<std::pair<DataType*,generic_density_forest_scalar> > project_data(std::vector<DataType*>& data, generic_density_forest_vector& start, generic_density_forest_vector& direction){\n\t//\tstd::vector<std::pair<DataType*,generic_density_forest_scalar> > data_with_projection;\n\t//\tdata_with_projection.reserve(data.size());\n\t//\tfor (int i = 0; i < (int)data.size(); i++){\n\t//\t\tconst generic_density_forest_vector* location = get_key_vector_(*(data[i]));\n\t//\t\tgeneric_density_forest_scalar alpha = projection_of_point_to_line(*(location),start,direction);\n\t//\t\tdata_with_projection.push_back(std::make_pair(data[i],alpha));\n\t//\t}\n\t//\treturn data_with_projection;\n\t//}\n\n\t////Obsolete\n\t////It is assumed that the <gaussian_model_> is computed.\n\t//void get_separating_hyper_plane_perpendicular_to_first_principal_axis(std::vector<DataType*>& data){\n\n\t//\tint data_dim = (*get_key_vector_(*data[0])).size();\n\n\t//\tif (data.size() < 2){\n\t//\t\tseparating_normal_ = generic_density_forest_vector::Zero(data_dim);\n\t//\t\tseparating_bias_ = 0;\n\t//\t\treturn;\n\t//\t}\n\n\t//\tseparating_normal_ = get_principal_axes(gaussian_model_.second).col(0);\n\n\t//\tleft_cov_ = generic_density_forest_matrix::Zero(data_dim,1);\n\t//\tright_cov_ = generic_density_forest_matrix::Zero(data_dim,1);\n\t//\tleft_mean_ = generic_density_forest_vector::Zero(data_dim);\n\t//\tright_mean_ = generic_density_forest_vector::Zero(data_dim);\n\n\t//\t//Project the data to the first principal axis of the data.\n\t//\tstd::vector<std::pair<DataType*,generic_density_forest_scalar> > data_with_projection = project_data(data,gaussian_model_.first,separating_normal_);\n\n\t//\t//Sort\n\t//\tstd::sort(data_with_projection.begin(),data_with_projection.end(),second_is_smaller<DataType*>);\n\n\n\t//\tint left_size = 0;\n\t//\tint right_size = data.size();\n\t//\tgeneric_density_forest_scalar joint_size = (generic_density_forest_scalar)(left_size + right_size);\n\t//\tright_mean_ = gaussian_model_.first;\n\t//\tright_cov_ = gaussian_model_.second.diagonal();\n\n\t//\tgeneric_density_forest_scalar max_info_gain = -std::numeric_limits<generic_density_forest_scalar>::infinity();\n\t//\tgeneric_density_forest_scalar current_info_gain = -std::numeric_limits<generic_density_forest_scalar>::infinity();\n\t//\tint max_gain_index = 0; // The index of the first element that should be left on the \n\n\t//\tgeneric_density_forest_vector left_square_sum = left_mean_*0;\n\t//\tright_mean_ *= (generic_density_forest_scalar)right_size;\n\t//\tgeneric_density_forest_vector right_square_sum = right_mean_*0;\n\t//\tfor (int i = 0; i < (int)data.size();i++){\n\t//\t\tright_square_sum += get_key_vector_(*data[i])->cwiseAbs2();\n\t//\t}\n\n\t//\t//NB! left_mean_ and right_mean_ are actually used to store the sum instead of mean in this loop!!!\n\t//\tfor (int i = 0; i < (int)data_with_projection.size()-1; i++){\n\t//\t\tcurrent_info_gain = 0;\n\n\t//\t\tconst generic_density_forest_vector* location = get_key_vector_(*(data_with_projection[i].first));\n\t//\t\tleft_square_sum += location->cwiseAbs2();\n\t//\t\tleft_mean_ += *location;\n\t//\t\tright_square_sum -= location->cwiseAbs2();\n\t//\t\tright_mean_ -= *location;\n\n\t//\t\tleft_size++;\n\t//\t\tright_size--;\n\n\t//\t\tleft_cov_ = left_square_sum - (left_mean_.cwiseAbs2())/(generic_density_forest_scalar)left_size;\n\t//\t\tleft_cov_ /= (generic_density_forest_scalar)left_size;\n\t//\t\tright_cov_ = right_square_sum - (right_mean_.cwiseAbs2())/(generic_density_forest_scalar)right_size;\n\t//\t\tright_cov_ /= (generic_density_forest_scalar)right_size;\n\n\t//\t\tfor (int i = 0; i < left_cov_.size(); i++){\n\t//\t\t\tleft_cov_(i) = std::max(std::numeric_limits<generic_density_forest_scalar>::min(),left_cov_(i));\n\t//\t\t}\n\t//\t\tcurrent_info_gain -= (generic_density_forest_scalar)left_size/(generic_density_forest_scalar)joint_size*(left_cov_.array().log().sum());\n\t//\t\tfor (int i = 0; i < right_cov_.size(); i++){\n\t//\t\t\tright_cov_(i) = std::max(std::numeric_limits<generic_density_forest_scalar>::min(),right_cov_(i));\n\t//\t\t}\n\t//\t\tcurrent_info_gain -= (generic_density_forest_scalar)right_size/(generic_density_forest_scalar)joint_size*(right_cov_.array().log().sum());\n\n\t//\t\tif (current_info_gain > max_info_gain){\n\t//\t\t\tmax_info_gain = current_info_gain;\n\t//\t\t\tmax_gain_index = i;\n\t//\t\t}\n\n\t//\t}\n\n\t//\tconst generic_density_forest_vector* location1 = get_key_vector_(*(data_with_projection[max_gain_index].first));\n\t//\tconst generic_density_forest_vector* location2 = get_key_vector_(*(data_with_projection[max_gain_index+1].first));\n\t//\tgeneric_density_forest_scalar bias1 = -location1->dot(separating_normal_);\n\t//\tgeneric_density_forest_scalar bias2 = -location2->dot(separating_normal_);\n\n\t//\tseparating_bias_ = bias1 + (bias2-bias1)*sampleUniform<generic_density_forest_scalar>();\n\n\n\t//}\n\n\tstd::vector<DataType*> compute_gaussian_models(void) {\n\n\t\tstd::vector<DataType*> data;\n\n\t\tif (!hasChildren()) {\n\t\t\tfor (const std::unique_ptr<DataType>& tmp : data_items_) {\n\t\t\t\tdata.push_back(tmp.get());\n\t\t\t}\n\t\t\tassert(data.size() > 0);\n\t\t}\n\t\telse {\n\t\t\tstd::vector<DataType*> tmp_data = left_child_->compute_gaussian_models();\n\t\t\tfor (DataType* datum : tmp_data) {\n\t\t\t\tdata.push_back(datum);\n\t\t\t}\n\t\t\tassert(data.size() > 0);\n\n\t\t\ttmp_data = right_child_->compute_gaussian_models();\n\t\t\tfor (DataType* datum : tmp_data) {\n\t\t\t\tdata.push_back(datum);\n\t\t\t}\n\t\t\tassert(data.size() > 0);\n\t\t}\n\n\t\tassert(data.size() > 0);\n\n\t\t//Build a gaussian model of all the incoming data\n\t\tconst generic_density_forest_vector& tmp_key_vector = *get_key_vector_(*(data[0]));\n\t\tgaussian_model_.first = tmp_key_vector * 0;\n\t\tgaussian_model_.second = generic_density_forest_matrix::Zero(gaussian_model_.first.size(), gaussian_model_.first.size());\n\n\t\tfor (size_t i = 0; i < data.size(); i++) {\n\t\t\tconst generic_density_forest_vector& sample_key_vector = *get_key_vector_(*(data[i]));\n\t\t\tgaussian_model_.first += sample_key_vector;\n\t\t}\n\t\tgaussian_model_.first /= (generic_density_forest_scalar)data.size();\n\n\t\tgeneric_density_forest_vector diff;\n\t\tfor (size_t i = 0; i < data.size(); i++) {\n\t\t\tconst generic_density_forest_vector& sample_key_vector = *get_key_vector_(*(data[i]));\n\t\t\tdiff = sample_key_vector - gaussian_model_.first;\n\t\t\tgaussian_model_.second += diff*diff.transpose();\n\t\t}\n\t\tgaussian_model_.second /= (generic_density_forest_scalar)data.size();\n\n\t\treturn data;\n\n\t}\n\n\n\tvoid build_tree(int tries, int minimum_data_in_leaf, std::list<std::unique_ptr<DataType> > data) {\n\n\t\tdata_items_.clear();\n\n\t\tUniqueNodePointer tmp = UniqueNodePointer(nullptr);\n\t\tsetLeftChild(tmp);\n\t\ttmp = UniqueNodePointer(nullptr);\n\t\tsetRightChild(tmp);\n\n\n\t\t//If the split breaks too few data points away, this branch is ready.\n\t\tif (data.size() <= (unsigned)minimum_data_in_leaf) {\n\n\t\t\tdata_items_ = std::move(data);\n\n\t\t\treturn;\n\n\t\t}\n\n\t\tif (split_mode == soKMEANS)\n\t\t{\n\t\t\t//split plane through kmeans with 2 clusters and downsampling of data\n\t\t\tconst generic_density_forest_vector& vect_tmp = *get_key_vector_(**data.begin());\n\t\t\tint keyDim = vect_tmp.size();\n\t\t\tgeneric_density_forest_vector mean[2], sum[2];\n\t\t\tfloat w[2];\n\t\t\tfor (int i = 0; i < 2; i++)\n\t\t\t{\n\t\t\t\tmean[i] = generic_density_forest_vector(keyDim);\n\t\t\t\tsum[i] = generic_density_forest_vector(keyDim);\n\t\t\t\tmean[i].setZero();\n\t\t\t\tsum[i].setZero();\n\t\t\t\tw[i] = 0;\n\t\t\t}\n\t\t\tint nSamples = std::min(tries, (int)data.size());\n\n\t\t\tint counter = 0;\n\t\t\t//first init clusters randomly\n\t\t\tfor (std::unique_ptr<DataType>& datum : data)\n\t\t\t{\n\t\t\t\tconst generic_density_forest_vector &key = *get_key_vector_(*datum);\n\t\t\t\tint clusterIdx;\n\t\t\t\tif (w[0] == 0)\n\t\t\t\t\tclusterIdx = 0;\n\t\t\t\telse if (w[1] == 0)\n\t\t\t\t\tclusterIdx = 1;\n\t\t\t\telse\n\t\t\t\t\tclusterIdx = AaltoGames::rand01();\n\t\t\t\tsum[clusterIdx] += key;\n\t\t\t\tw[clusterIdx]++;\n\t\t\t\tcounter++;\n\t\t\t\tif (counter == nSamples) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int i = 0; i < 2; i++)\n\t\t\t{\n\t\t\t\tif (w[i] != 0)\n\t\t\t\t\tmean[i] = sum[i] / w[i];\n\t\t\t\tsum[i].setZero();\n\t\t\t\tw[i] = 0;\n\t\t\t}\n\n\t\t\t//now do the k-means iteration\n\t\t\tconst int kMeansIter = 3;\n\t\t\tfor (int iter = 0; iter < kMeansIter; iter++)\n\t\t\t{\n\t\t\t\tcounter = 0;\n\t\t\t\tfor (std::unique_ptr<DataType>& datum : data)\n\t\t\t\t{\n\t\t\t\t\tconst generic_density_forest_vector &key = *get_key_vector_(*datum);\n\t\t\t\t\tint clusterIdx;\n\t\t\t\t\tfloat dist0 = (key - mean[0]).norm();\n\t\t\t\t\tfloat dist1 = (key - mean[1]).norm();\n\t\t\t\t\tif (dist0 < dist1)\n\t\t\t\t\t\tclusterIdx = 0;\n\t\t\t\t\telse if (dist1 < dist0)\n\t\t\t\t\t\tclusterIdx = 1;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (w[0] == 0)\n\t\t\t\t\t\t\tclusterIdx = 0;\n\t\t\t\t\t\telse if (w[1] == 0)\n\t\t\t\t\t\t\tclusterIdx = 1;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tclusterIdx = AaltoGames::rand01();\n\t\t\t\t\t}\n\t\t\t\t\tsum[clusterIdx] += key;\n\t\t\t\t\tw[clusterIdx]++;\n\t\t\t\t\tcounter++;\n\t\t\t\t\tif (counter == nSamples) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < 2; i++)\n\t\t\t\t{\n\t\t\t\t\tif (w[i] != 0)\n\t\t\t\t\t\tmean[i] = sum[i] / w[i];\n\t\t\t\t\tsum[i].setZero();\n\t\t\t\t\tw[i] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::pair<generic_density_forest_scalar, generic_density_forest_vector> hyper_plane;\n\t\t\thyper_plane.second = (mean[1] - mean[0]).normalized();\n\t\t\tseparating_normal_ = hyper_plane.second;\n\t\t\thyper_plane.first = -separating_normal_.dot(((generic_density_forest_scalar)0.5)*(mean[0] + mean[1]));\n\t\t\tseparating_bias_ = hyper_plane.first;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::pair<generic_density_forest_scalar, generic_density_forest_vector> hyper_plane = get_separating_hyperplane(data);\n\t\t\tseparating_bias_ = hyper_plane.first;\n\t\t\tseparating_normal_ = hyper_plane.second;\n\n\t\t\tstd::list<DataType* > left_samples;\n\t\t\tstd::list<DataType* > right_samples;\n\n\t\t\tif (data.size() > MAX_SAMPLES_FOR_INFO_GAIN_MEASURING)\n\t\t\t\tdivide_data_sampled(data, left_samples, right_samples, MAX_SAMPLES_FOR_INFO_GAIN_MEASURING);\n\t\t\telse\n\t\t\t\tdivide_data_info(data, left_samples, right_samples);\n\n\t\t\tgeneric_density_forest_scalar max_information_gain = information_gain(left_samples, right_samples);\n\t\t\t//generic_density_forest_scalar max_information_gain = information_gain_maximum_separation(separated_data.first,separated_data.second);\n\t\t\tfor (int i = 0; i < tries; i++) {\n\n\t\t\t\tstd::pair<generic_density_forest_scalar, generic_density_forest_vector> tmp_plane = get_separating_hyperplane(data);\n\t\t\t\tseparating_bias_ = tmp_plane.first;\n\t\t\t\tseparating_normal_ = tmp_plane.second;\n\t\t\t\tif (data.size() > MAX_SAMPLES_FOR_INFO_GAIN_MEASURING)\n\t\t\t\t\tdivide_data_sampled(data, left_samples, right_samples, MAX_SAMPLES_FOR_INFO_GAIN_MEASURING);\n\t\t\t\telse\n\t\t\t\t\tdivide_data_info(data, left_samples, right_samples);\n\n\t\t\t\tgeneric_density_forest_scalar tmp_information_gain = information_gain(left_samples, right_samples);\n\t\t\t\t//generic_density_forest_scalar tmp_information_gain = information_gain_maximum_separation(separated_data.first,separated_data.second);\n\n\t\t\t\tif (tmp_information_gain > max_information_gain) {\n\t\t\t\t\tmax_information_gain = tmp_information_gain;\n\t\t\t\t\thyper_plane = tmp_plane;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tseparating_bias_ = hyper_plane.first;\n\t\t\tseparating_normal_ = hyper_plane.second;\n\n\t\t\t//std::pair<std::vector<DataType*>,std::vector<DataType*> > separated_data;\n\t\t\t//get_separating_hyper_plane_perpendicular_to_first_principal_axis(data);\n\n\t\t}\n\n\t\tstd::list<std::unique_ptr<DataType> > left_data;\n\t\tstd::list<std::unique_ptr<DataType> > right_data;\n\t\tdivide_data(data, left_data, right_data);\n\n\n\t\t//If the split breaks too few data points away, this branch is ready.\n\t\tif (left_data.size() == 0 || right_data.size() == 0) {\n\n\t\t\tdata_items_.clear();\n\t\t\tfor (std::unique_ptr<DataType>& datum : left_data) {\n\t\t\t\tstd::unique_ptr<DataType> tmp_ptr = std::unique_ptr<DataType>(nullptr);\n\t\t\t\tdatum.swap(tmp_ptr);\n\t\t\t\tdata_items_.push_back(std::move(tmp_ptr));\n\t\t\t}\n\n\t\t\tfor (std::unique_ptr<DataType>& datum : right_data) {\n\t\t\t\tstd::unique_ptr<DataType> tmp_ptr = std::unique_ptr<DataType>(nullptr);\n\t\t\t\tdatum.swap(tmp_ptr);\n\t\t\t\tdata_items_.push_back(std::move(tmp_ptr));\n\t\t\t}\n\n\t\t\treturn;\n\n\t\t}\n\n\n\t\ttmp = UniqueNodePointer(new GenericDensityNode<DataType>());\n\t\ttmp->get_key_vector_ = get_key_vector_;\n\t\tsetLeftChild(tmp);\n\t\tleft_child_->build_tree(tries, minimum_data_in_leaf, std::move(left_data));\n\n\t\ttmp = UniqueNodePointer(new GenericDensityNode<DataType>());\n\t\ttmp->get_key_vector_ = get_key_vector_;\n\t\tsetRightChild(tmp);\n\t\tright_child_->build_tree(tries, minimum_data_in_leaf, std::move(right_data));\n\n\n\t}\n\n\tvoid add_sample(int tries, int minimum_data_in_leaf, int maximum_data_in_leaf, std::unique_ptr<DataType> datum) {\n\n\n\n\t\tdata_items_.push_back(std::move(datum));\n\n\n\t\tif ((int)data_items_.size() > maximum_data_in_leaf) {\n\t\t\tstd::list<std::unique_ptr<DataType> > new_data_items = std::move(data_items_);\n\t\t\tdata_items_.clear();\n\t\t\tbuild_tree(tries, minimum_data_in_leaf, std::move(new_data_items));\n\t\t}\n\n\n\n\n\t}\n\n\t////Obsolete\n\t//void fill_tree(int tries, int minimum_data_in_leaf, std::vector<DataType*>& data){\n\n\t//\tdata_items_.clear();\n\n\t//\t//Build a gaussian model of all the incoming data\n\t//\tgaussian_model_.first = *get_key_vector_(*(data[0])) * 0;\n\t//\tgaussian_model_.second = generic_density_forest_matrix::Zero(gaussian_model_.first.size(),gaussian_model_.first.size());\n\n\t//\tfor (size_t i = 0; i < data.size(); i++){\n\t//\t\tgaussian_model_.first += *get_key_vector_(*(data[i]));\n\t//\t}\n\t//\tgaussian_model_.first /= (generic_density_forest_scalar)data.size();\n\n\t//\tgeneric_density_forest_vector diff;\n\t//\tfor (size_t i = 0; i < data.size(); i++){\n\t//\t\tdiff = *get_key_vector_(*(data[i])) - gaussian_model_.first;\n\t//\t\tgaussian_model_.second += diff*diff.transpose();\n\t//\t}\n\t//\tgaussian_model_.second /= (generic_density_forest_scalar)data.size();\n\n\n\n\n\t//\t//If the split breaks too few data points away, this branch is ready.\n\t//\tif (data.size() < (unsigned)minimum_data_in_leaf){\n\n\t//\t\tleft_child_.reset();\n\t//\t\tright_child_.reset();\n\n\t//\t\tdata_items_.clear();\n\t//\t\tdata_item_pointers_.clear();\n\t//\t\tif (data_storage_mode_ == Storage_mode::COPY){\n\t//\t\t\tdata_items_.reserve(data.size());\n\t//\t\t\tfor (size_t i = 0; i < data.size(); i++){\n\t//\t\t\t\tdata_items_.push_back(std::move(*data[i]));\n\t//\t\t\t}\n\t//\t\t}\n\n\t//\t\tif (data_storage_mode_ == Storage_mode::POINTER){\n\t//\t\t\tdata_item_pointers_.reserve(data.size());\n\t//\t\t\tfor (size_t i = 0; i < data.size(); i++){\n\t//\t\t\t\tdata_item_pointers_.push_back(data[i]);\n\t//\t\t\t}\n\t//\t\t}\n\n\t//\t\treturn;\n\n\t//\t}\n\n\n\t//\tstd::pair<generic_density_forest_scalar,generic_density_forest_vector> hyper_plane = get_separating_hyperplane(data);\n\t//\tseparating_bias_ = hyper_plane.first;\n\t//\tseparating_normal_ = hyper_plane.second;\n\n\t//\tstd::pair<std::vector<DataType*>,std::vector<DataType*> > separated_data;\n\t//\tdivide_data(data,separated_data.first,separated_data.second);\n\n\t//\tgeneric_density_forest_scalar max_information_gain = information_gain(separated_data.first,separated_data.second);\n\t//\t//generic_density_forest_scalar max_information_gain = information_gain_maximum_separation(separated_data.first,separated_data.second);\n\t//\tfor (int i = 0; i < tries; i++){\n\n\t//\t\tstd::pair<generic_density_forest_scalar,generic_density_forest_vector> tmp_plane = get_separating_hyperplane(data);\n\t//\t\tseparating_bias_ = tmp_plane.first;\n\t//\t\tseparating_normal_ = tmp_plane.second;\n\n\t//\t\tdivide_data(data,separated_data.first,separated_data.second);\n\n\t//\t\tgeneric_density_forest_scalar tmp_information_gain = information_gain(separated_data.first,separated_data.second);\n\t//\t\t//generic_density_forest_scalar tmp_information_gain = information_gain_maximum_separation(separated_data.first,separated_data.second);\n\n\t//\t\tif (tmp_information_gain > max_information_gain){\n\t//\t\t\tmax_information_gain = tmp_information_gain;\n\t//\t\t\thyper_plane = tmp_plane;\n\t//\t\t}\n\n\t//\t}\n\n\t//\tseparating_bias_ = hyper_plane.first;\n\t//\tseparating_normal_ = hyper_plane.second;\n\n\t//\tdivide_data(data,separated_data.first,separated_data.second);\n\n\t//\tleft_child_->fill_tree(tries,minimum_data_in_leaf,separated_data.first);\n\t//\tright_child_->fill_tree(tries,minimum_data_in_leaf,separated_data.second);\n\n\n\t//}\n\n\tstd::pair<generic_density_forest_scalar, generic_density_forest_vector> get_separating_hyperplane(const std::list<std::unique_ptr<DataType> >& data) {\n\n\t\tif (data.size() < 1) {\n\t\t\tthrow ZeroKeyVectorException();\n\t\t\treturn std::make_pair(0, generic_density_forest_vector::Zero(0));\n\t\t}\n\n\t\tconst generic_density_forest_vector& tmp_key_vect = *get_key_vector_(**data.begin());\n\t\tgeneric_density_forest_vector normal = generic_density_forest_vector::Random(tmp_key_vect.size());\n\t\tnormal.normalize();\n\n\t\tint tmp_idx_1 = rand() % data.size();\n\t\tint tmp_idx_2 = rand() % data.size();\n\t\twhile (tmp_idx_2 == tmp_idx_1) {\n\t\t\ttmp_idx_2 = rand() % data.size();\n\t\t}\n\n\t\tDataType* element1 = nullptr;\n\t\tDataType* element2 = nullptr;\n\n\t\t//if (data.size() <= 1){\n\t\t//\tstd::cout << \"Too few elements.\";\n\t\t//}\n\n\t\tint counter = 0;\n\t\tfor (const std::unique_ptr<DataType>& datum : data) {\n\n\t\t\tif (counter == tmp_idx_1) {\n\t\t\t\telement1 = datum.get();\n\t\t\t}\n\n\t\t\tif (counter == tmp_idx_2) {\n\t\t\t\telement2 = datum.get();\n\t\t\t}\n\n\t\t\tif (element1 && element2) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcounter++;\n\t\t}\n\n\t\t//generic_density_forest_vector first_random_element = -*get_key_vector_(*(data[tmp_idx_1]));\n\t\t//generic_density_forest_vector second_random_element = -*get_key_vector_(*(data[tmp_idx_2]));\n\n\t\t//std::cout << element1 << \" \" << element2 << std::endl;\n\n\t\tconst generic_density_forest_vector key_vect1 = *get_key_vector_(*element1);\n\t\tconst generic_density_forest_vector key_vect2 = *get_key_vector_(*element2);\n\t\tgeneric_density_forest_scalar bias_1 = normal.dot(-key_vect1);\n\t\tgeneric_density_forest_scalar bias_2 = normal.dot(-key_vect2);\n\n\t\tgeneric_density_forest_scalar bias = bias_1 + (bias_2 - bias_1)*sampleUniform<generic_density_forest_scalar>();\n\n\t\treturn std::make_pair(bias, normal);\n\n\t}\n\n\t//True signals right, false signals left.\n\tbool left_or_right(const generic_density_forest_vector& datum) {\n\n\t\tgeneric_density_forest_scalar decision = 0;\n\n\t\tif (separating_normal_.size() == 0) {\n\t\t\tif (AaltoGames::rand01() == 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tif (datum.size() != separating_normal_.size()) {\n\t\t\tthrow ZeroKeyVectorException();\n\t\t}\n\n\t\tdecision = separating_normal_.dot(datum) + separating_bias_;\n\n\t\tif (decision > 0) {\n\t\t\treturn true;\n\t\t}\n\t\telse if (decision < 0) {\n\t\t\treturn false;\n\t\t}\n\t\telse {\n\t\t\tif (AaltoGames::rand01() == 0) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\n\n\t}\n\n\t//The data will be split to left and right data, which are stored to <left_data> and <right_data>.\n\tvoid divide_data_info(std::list<std::unique_ptr<DataType> >& data, std::list<DataType* >& left_data, std::list<DataType* >& right_data) {\n\n\t\tleft_data.clear();;\n\t\tright_data.clear();\n\n\t\tfor (const std::unique_ptr<DataType>& datum : data) {\n\n\t\t\tDataType* datum_ptr = datum.get();\n\t\t\tconst generic_density_forest_vector& key_vector = *get_key_vector_(*datum_ptr);\n\n\t\t\tif (left_or_right(key_vector)) {\n\t\t\t\tright_data.push_back(datum_ptr);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tleft_data.push_back(datum_ptr);\n\t\t\t}\n\t\t}\n\n\t}\n\n\t//The data will be split to left and right data, which are stored to <left_data> and <right_data>.\n\tvoid divide_data(std::list<std::unique_ptr<DataType> >& data, std::list<std::unique_ptr<DataType> >& left_data, std::list<std::unique_ptr<DataType> >& right_data) {\n\n\t\tleft_data.clear();;\n\t\tright_data.clear();\n\n\t\twhile (data.size() > 0) {\n\t\t\tstd::unique_ptr<DataType> datum = std::unique_ptr<DataType>(nullptr);\n\t\t\tdatum.swap(data.back());\n\t\t\tdata.pop_back();\n\n\t\t\tconst generic_density_forest_vector& key_vect = *get_key_vector_(*datum);\n\n\t\t\tif (left_or_right(key_vect)) {\n\t\t\t\tright_data.push_back(std::move(datum));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tleft_data.push_back(std::move(datum));\n\t\t\t}\n\t\t}\n\n\t\tdata.clear();\n\n\t}\n\n\t//The data will be split to left and right data, which are stored to <left_data> and <right_data>.\n\tvoid divide_data_sampled(std::list<std::unique_ptr<DataType> >& data, std::list<DataType* >& left_data, std::list<DataType* >& right_data, int nSamples) {\n\n\t\tleft_data.clear();;\n\t\tright_data.clear();\n\n\t\tif (data.size() < 1) {\n\t\t\treturn;\n\t\t}\n\n\t\twhile ((int)(right_data.size() + left_data.size()) < nSamples) {\n\n\t\t\tint idx = AaltoGames::randInt(0, (int)data.size() - 1);\n\n\t\t\tstd::list<std::unique_ptr<DataType> >::iterator iter = data.begin();\n\n\t\t\tint counter = 0;\n\t\t\twhile (counter < idx && iter != data.end()) {\n\t\t\t\titer++;\n\t\t\t\tcounter++;\n\t\t\t}\n\n\t\t\tif (iter == data.end()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstd::unique_ptr<DataType>& datum = *iter;\n\n\t\t\t//try{\n\t\t\tconst generic_density_forest_vector& key_vect = *get_key_vector_(*datum);\n\n\t\t\tif (left_or_right(key_vect)) {\n\t\t\t\tright_data.push_back(datum.get());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tleft_data.push_back(datum.get());\n\t\t\t}\n\t\t\t//}\n\t\t\t//catch (std::exception e){\n\t\t\t//\tstd::cout << data.size() << \" \" << left_data.size() << \" \" << right_data.size() << std::endl;\n\t\t\t//\tstd::cout << counter << std::endl;\n\t\t\t//\tstd::cout << datum << std::endl;\n\t\t\t//\tstd::cout << datum.get()->state_ << std::endl;\n\t\t\t//\tstd::cout << datum.get()->control_ << std::endl;\n\t\t\t//\tstd::cout << datum.get()->future_state_ << std::endl;\n\t\t\t//\tstd::cout << datum.get()->key_vector_ << std::endl;\n\t\t\t//}\n\n\t\t}\n\n\t}\n\n\n};\n\ntemplate<typename DataType>\nclass GenericDensityTree {\n\n\ttypedef GenericDensityNode<DataType>* NodePointer;\n\ttypedef GenericDensityTree* TreePointer;\n\ttypedef std::unique_ptr<GenericDensityNode<DataType> > UniqueNodePointer;\n\n\npublic:\n\n\tUniqueNodePointer root_;\n\t//std::list<DensityNode > mNodes; //This is just a container to hold the nodes.\n\n\tGenericDensityTree() {\n\t\t//mNodes.clear();\n\t\troot_ = UniqueNodePointer(new GenericDensityNode<DataType>());\n\t}\n\n\tGenericDensityTree(GenericDensityTree& otherTree) {\n\n\t\troot_ = UniqueNodePointer(new GenericDensityNode<DataType>(*(otherTree.root_)));\n\n\t\tstd::vector<GenericDensityNode<DataType>* > nodesOther;\n\t\tnodesOther.push_back(&(*(otherTree.root_)));\n\n\t\tstd::vector<GenericDensityNode<DataType>* > nodes;\n\t\tnodes.push_back(&(*root_));\n\n\t\twhile (nodes.size() > 0) {\n\t\t\tNodePointer nodeOther = nodesOther.back();\n\t\t\tnodesOther.pop_back();\n\n\t\t\tNodePointer node = nodes.back();\n\t\t\tnodes.pop_back();\n\n\t\t\tUniqueNodePointer newLeft = UniqueNodePointer(nullptr);\n\t\t\tif (nodeOther->left_child_.get()) {\n\t\t\t\tnewLeft = UniqueNodePointer(new GenericDensityNode<DataType>(*(nodeOther->left_child_.get())));\n\t\t\t}\n\t\t\tUniqueNodePointer newRight = UniqueNodePointer(nullptr);\n\t\t\tif (nodeOther->right_child_.get()) {\n\t\t\t\tnewRight = UniqueNodePointer(new GenericDensityNode<DataType>(*(nodeOther->right_child_.get())));\n\t\t\t}\n\n\t\t\tnode->setLeftChild(newLeft);\n\t\t\tnode->setRightChild(newRight);\n\n\t\t\tif (nodeOther->left_child_.get()) {\n\t\t\t\tnodesOther.push_back(nodeOther->left_child_.get());\n\t\t\t\tnodes.push_back(node->left_child_.get());\n\t\t\t}\n\n\t\t\tif (nodeOther->right_child_.get()) {\n\t\t\t\tnodesOther.push_back(nodeOther->right_child_.get());\n\t\t\t\tnodes.push_back(node->right_child_.get());\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tGenericDensityTree operator=(GenericDensityTree& otherTree) {\n\n\t\tif (&otherTree == this) {\n\t\t\treturn *this;\n\t\t}\n\n\t\troot_ = UniqueNodePointer(new GenericDensityNode<DataType>(*(otherTree.root_)));\n\n\t\tstd::vector<GenericDensityNode<DataType>* > nodesOther;\n\t\tnodesOther.push_back(&(*(otherTree.root_)));\n\n\t\tstd::vector<GenericDensityNode<DataType>* > nodes;\n\t\tnodes.push_back(&(*root_));\n\n\t\twhile (nodes.size() > 0) {\n\t\t\tNodePointer nodeOther = nodesOther.back();\n\t\t\tnodesOther.pop_back();\n\n\t\t\tNodePointer node = nodes.back();\n\t\t\tnodes.pop_back();\n\n\t\t\tUniqueNodePointer newLeft = UniqueNodePointer(nullptr);\n\t\t\tif (nodeOther->left_child_.get()) {\n\t\t\t\tnewLeft = UniqueNodePointer(new GenericDensityNode<DataType>(*(nodeOther->left_child_)));\n\t\t\t}\n\t\t\tUniqueNodePointer newRight = UniqueNodePointer(nullptr);\n\t\t\tif (nodeOther->right_child_.get()) {\n\t\t\t\tnewRight = UniqueNodePointer(new GenericDensityNode<DataType>(*(nodeOther->right_child_)));\n\t\t\t}\n\n\t\t\tnode->setLeftChild(newLeft);\n\t\t\tnode->setRightChild(newRight);\n\n\t\t\tif (nodeOther->left_child_.get()) {\n\t\t\t\tnodesOther.push_back(nodeOther->left_child_.get());\n\t\t\t\tnodes.push_back(node->left_child_.get());\n\t\t\t}\n\n\t\t\tif (nodeOther->right_child_.get()) {\n\t\t\t\tnodesOther.push_back(nodeOther->right_child_.get());\n\t\t\t\tnodes.push_back(node->right_child_.get());\n\t\t\t}\n\n\t\t}\n\n\t\treturn *this;\n\t}\n\n\n\n\tDataType* get_random() {\n\n\t\tNodePointer node = root_.get();\n\t\tNodePointer next = root_.get();\n\n\t\twhile (next) {\n\t\t\tnode = next;\n\t\t\tif (rand() % 2 == 0) {\n\t\t\t\tnext = node->left_child_.get();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnext = node->right_child_.get();\n\t\t\t}\n\t\t}\n\n\t\tDataType* nearest = nullptr;\n\n\t\tif (node->data_items_.size() > 0) {\n\n\t\t\tint rand_idx = rand() % node->data_items_.size();\n\t\t\tstd::list<std::unique_ptr<DataType> >::iterator iter = node->data_items_.begin();\n\n\t\t\twhile (rand_idx > 0 && iter != node->data_items_.end()) {\n\t\t\t\trand_idx--;\n\t\t\t\titer++;\n\t\t\t}\n\n\t\t\tif (iter == node->data_items_.end()) {\n\t\t\t\titer--;\n\t\t\t}\n\n\t\t\tnearest = iter->get();\n\n\t\t}\n\n\t\treturn nearest;\n\n\t}\n\n\n\tDataType* get_approximate_nearest(const DataType& datum) {\n\n\t\tNodePointer node = root_->get_leaf(datum);\n\n\t\tgeneric_density_forest_scalar nearest_dist = std::numeric_limits<generic_density_forest_scalar>::infinity();\n\t\tgeneric_density_forest_scalar current_dist = std::numeric_limits<generic_density_forest_scalar>::infinity();\n\n\t\tconst generic_density_forest_vector& key_vector = *(node->get_key_vector_(datum));\n\n\t\tDataType* nearest = nullptr;\n\n\t\tfor (const std::unique_ptr<DataType>& tmp : node->data_items_) {\n\t\t\tconst generic_density_forest_vector& data_key_vector = *(node->get_key_vector_(*tmp));\n\t\t\tcurrent_dist = (key_vector - data_key_vector).norm();\n\n\t\t\tif (current_dist < nearest_dist) {\n\t\t\t\tnearest_dist = current_dist;\n\t\t\t\tnearest = tmp.get();\n\t\t\t}\n\t\t}\n\n\t\treturn nearest;\n\n\t}\n\n\tstd::vector<DataType*> get_neighborhood(const DataType& datum) {\n\n\t\tNodePointer node = root_->get_leaf(datum);\n\t\tstd::vector<DataType*> neighbors;\n\n\n\t\tfor (const std::unique_ptr<DataType>& tmp : node->data_items_) {\n\n\t\t\tneighbors.push_back(tmp.get());\n\n\t\t}\n\n\n\t\treturn neighbors;\n\n\t}\n\n\n\tint get_neighborhood(const DataType& datum, DataType* data_ptr_array[], int max_end_index) {\n\n\t\tNodePointer node = root_->get_leaf(datum);\n\t\tint end_idx = 0;\n\n\t\tif (node->data_storage_mode_ == Storage_mode::COPY) {\n\t\t\tfor (const std::unique_ptr<DataType>& tmp : node->data_items_) {\n\t\t\t\tdata_ptr_array[end_idx] = tmp.get();\n\t\t\t\tend_idx++;\n\t\t\t\tif (max_end_index == end_idx) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn end_idx;\n\n\t}\n\n\n\tvoid rebuild_tree(int tries, int minimum_data_in_leaf, int remember_instances = -1) {\n\t\tstd::list<std::unique_ptr<DataType> > data;\n\n\t\tstd::vector<NodePointer> nodes_to_visit;\n\t\tnodes_to_visit.push_back(root_.get());\n\n\t\twhile (nodes_to_visit.size() > 0) {\n\t\t\tNodePointer node = nodes_to_visit.back();\n\t\t\tnodes_to_visit.pop_back();\n\t\t\tif (node) {\n\t\t\t\tnodes_to_visit.push_back(node->left_child_.get());\n\t\t\t\tnodes_to_visit.push_back(node->right_child_.get());\n\n\t\t\t\tfor (std::unique_ptr<DataType>& tmp : node->data_items_) {\n\t\t\t\t\tdata.push_back(std::move(tmp));\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tif (remember_instances > 0) {\n\t\t\twhile (remember_instances < (int)data.size()) {\n\n\t\t\t\tstd::list<std::unique_ptr<DataType> >::iterator iter = data.begin();\n\t\t\t\tint rand_idx = rand() % data.size();\n\n\t\t\t\twhile (rand_idx > 0) {\n\t\t\t\t\trand_idx--;\n\n\t\t\t\t\titer++;\n\n\t\t\t\t\tif (iter == data.end()) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\tif (iter == data.end()) {\n\t\t\t\t\titer--;\n\t\t\t\t}\n\n\n\t\t\t\tdata.erase(iter);\n\n\n\t\t\t}\n\t\t}\n\n\t\tconst generic_density_forest_vector* (*key_vector_fun)(const DataType& datum) = root_->get_key_vector_;\n\n\t\tUniqueNodePointer tmp = UniqueNodePointer(new GenericDensityNode<DataType>());\n\t\ttmp->get_key_vector_ = key_vector_fun;\n\t\troot_.swap(tmp);\n\n\t\t//std::cout << \"Tree has nodes: \" << data.size() << std::endl;\n\n\t\troot_->build_tree(tries, minimum_data_in_leaf, std::move(data));\n\n\t}\n\n\n\t//Assuming that data_ptr_array has room for k pointers.\n\tvoid get_up_to_k_nearest(const DataType& datum, DataType* data_ptr_array[], int k) {\n\t\tgeneric_density_forest_vector key_vector = *(root_->get_key_vector_(datum));\n\t\tget_up_to_k_nearest(key_vector, data_ptr_array, k);\n\t}\n\n\tvoid get_up_to_k_nearest(const generic_density_forest_vector &key_vector, DataType* data_ptr_array[], int k, bool findInSibling = false) {\n\n\t\tNodePointer node = root_->get_leaf(key_vector);\n\t\tif (findInSibling)\n\t\t{\n\t\t\tif (node->parent_ != nullptr)\n\t\t\t{\n\t\t\t\tNodePointer left = node->parent_->left_child_.get();\n\t\t\t\tNodePointer right = node->parent_->right_child_.get();\n\t\t\t\tnode = left == node ? right : left;\n\t\t\t\tnode = node->get_leaf(key_vector);\n\t\t\t}\n\t\t}\n\n\t\tauto first_is_closer = [&](DataType* datum1, DataType* datum2) {\n\t\t\tif (!datum1 && !datum2) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (datum1 && !datum2) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (!datum1 && datum2) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tconst generic_density_forest_vector& key_vect1 = *(root_->get_key_vector_(*datum1));\n\t\t\tconst generic_density_forest_vector& key_vect2 = *(root_->get_key_vector_(*datum2));\n\n\t\t\tfloat dist_to_1 = (key_vector - key_vect1).norm();\n\t\t\tfloat dist_to_2 = (key_vector - key_vect2).norm();\n\t\t\treturn dist_to_1 < dist_to_2;\n\t\t};\n\n\n\t\tfor (const std::unique_ptr<DataType>& tmp : node->data_items_) {\n\t\t\tDataType* ptr = tmp.get();\n\n\t\t\tbool is_in_array_already = false;\n\t\t\tfor (int i = 0; i < k; i++) {\n\t\t\t\tif (data_ptr_array[i]) {\n\t\t\t\t\tif (*data_ptr_array[i] == *ptr) {\n\t\t\t\t\t\tis_in_array_already = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (is_in_array_already) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (first_is_closer(ptr, data_ptr_array[k - 1])) {\n\t\t\t\tdata_ptr_array[k - 1] = ptr;\n\t\t\t\tstd::sort(data_ptr_array, &(data_ptr_array[k]), first_is_closer);\n\t\t\t}\n\n\t\t}\n\n\n\t}\n\n\n\n\t//DataType* get_approximate_nearest(const DataType& datum){\n\n\t//\tNodePointer node = get_leaf(datum);\n\n\t//\treturn &(node->data_items_[rand()%node->data_items_.size()]);\n\n\t//}\n\n\n\n\tvoid remove_empty_leaf(NodePointer node) {\n\n\t\tif (!(node->is_empty_leaf())) {\n\t\t\treturn;\n\t\t}\n\n\t\t//Node is root\n\t\tif (!(node->parent_)) {\n\t\t\treturn;\n\t\t}\n\n\t\tNodePointer grand_parent = nullptr;\n\t\tNodePointer parent = node->parent_;\n\t\tif (parent) {\n\t\t\tgrand_parent = parent->parent_;\n\t\t}\n\t\tUniqueNodePointer sibling = nullptr;\n\t\tif (parent->left_child_.get() == node) {\n\t\t\tsibling = std::move(parent->right_child_);\n\t\t}\n\t\telse {\n\t\t\tsibling = std::move(parent->left_child_);\n\t\t}\n\n\n\t\t//The sibling should become the new root\n\t\tif (!grand_parent) {\n\t\t\tsibling->parent_ = nullptr;\n\t\t\troot_ = std::move(sibling);\n\t\t\treturn;\n\t\t}\n\n\t\tassert(root_->hasChildren());\n\n\t\t//The sibling replaces parent\n\t\tif (grand_parent->left_child_.get() == parent) {\n\t\t\tgrand_parent->setLeftChild(sibling);\n\t\t\tassert(grand_parent->hasChildren());\n\t\t}\n\t\telse {\n\t\t\tgrand_parent->setRightChild(sibling);\n\t\t\tassert(grand_parent->hasChildren());\n\t\t}\n\n\t}\n\n\n\tstd::vector<DataType*> find_data_item_in_tree_exhaustive_search(const DataType& datum) {\n\n\t\tstd::vector<NodePointer> nodes;\n\t\tnodes.push_back(root_.get());\n\n\t\tstd::vector<DataType*> data_items;\n\n\t\twhile (nodes.size() > 0) {\n\n\t\t\tNodePointer node = nodes[nodes.size() - 1];\n\t\t\tnodes.pop_back();\n\n\t\t\tif (node) {\n\t\t\t\tNodePointer tmp_ptr = node->left_child_.get();\n\t\t\t\tif (tmp_ptr) {\n\t\t\t\t\tnodes.push_back(tmp_ptr);\n\t\t\t\t}\n\n\t\t\t\ttmp_ptr = node->right_child_.get();\n\t\t\t\tif (tmp_ptr) {\n\t\t\t\t\tnodes.push_back(tmp_ptr);\n\t\t\t\t}\n\n\n\t\t\t}\n\n\t\t\tstd::list<std::unique_ptr<DataType> >::iterator iter = node->data_items_.begin();\n\n\t\t\twhile (iter != node->data_items_.end()) {\n\n\t\t\t\tif ((**iter) == datum) {\n\t\t\t\t\tdata_items.push_back((*iter).get());\n\t\t\t\t}\n\n\t\t\t\titer++;\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn data_items;\n\n\t}\n\n\n\tvoid remove_data_point(const DataType& datum) {\n\n\t\tstd::vector<NodePointer> nodes;\n\t\tnodes.push_back(root_.get());\n\n\t\tstd::vector<NodePointer> leaves;\n\n\t\twhile (nodes.size() > 0) {\n\n\t\t\tNodePointer node = nodes[nodes.size() - 1];\n\t\t\tnodes.pop_back();\n\n\t\t\tif (node) {\n\t\t\t\tbool has_child = false;\n\t\t\t\tNodePointer tmp_ptr = node->left_child_.get();\n\t\t\t\tif (tmp_ptr) {\n\t\t\t\t\tnodes.push_back(tmp_ptr);\n\t\t\t\t\thas_child = true;\n\t\t\t\t}\n\n\t\t\t\ttmp_ptr = node->right_child_.get();\n\t\t\t\tif (tmp_ptr) {\n\t\t\t\t\tnodes.push_back(tmp_ptr);\n\t\t\t\t\thas_child = true;\n\t\t\t\t}\n\n\t\t\t\tif (!has_child) {\n\t\t\t\t\tleaves.push_back(node);\n\t\t\t\t}\n\n\n\t\t\t}\n\n\t\t\tstd::list<std::unique_ptr<DataType> >::iterator iter = node->data_items_.begin();\n\n\t\t\twhile (iter != node->data_items_.end()) {\n\n\t\t\t\tif ((**iter) == datum) {\n\t\t\t\t\titer = node->data_items_.erase(iter);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\titer++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tfor (NodePointer ptr : leaves) {\n\t\t\tremove_empty_leaf(ptr);\n\t\t}\n\n\n\t}\n\n\tvoid build_tree_copying(int tries, int minimum_data_in_leaf, std::vector<DataType >& data) {\n\n\t\tstd::list<std::unique_ptr<DataType> > tmp;\n\n\t\tfor (unsigned i = 0; i < data.size(); i++) {\n\t\t\ttmp.push_back(std::unique_ptr<DataType>(new DataType));\n\t\t\t*(tmp.back()) = data[i];\n\t\t}\n\n\t\troot_->build_tree(tries, minimum_data_in_leaf, std::move(tmp));\n\n\t}\n\n\tvoid add_sample(int tries, int minimum_data_in_leaf, int maximum_data_in_leaf, DataType datum) {\n\n\t\tNodePointer node = root_->get_leaf(datum);\n\n\t\tstd::unique_ptr<DataType> datum_ptr = std::unique_ptr<DataType>(new DataType());\n\t\t*datum_ptr = datum;\n\n\t\tnode->add_sample(tries, minimum_data_in_leaf, maximum_data_in_leaf, std::move(datum_ptr));\n\n\t}\n\n\tgeneric_density_forest_vector sample_conditioned(const generic_density_forest_vector& regressor) {\n\n\t\tgeneric_density_forest_vector key = root_->gaussian_model_.first*std::numeric_limits<generic_density_forest_scalar>::quiet_NaN();\n\t\tkey.tail(regressor.size()) = regressor;\n\n\t\tNodePointer node = root_.get();\n\n\t\twhile (node->hasChildren()) {\n\n\n\n\t\t\tkey.head(node->regressand_mean_.size()) = node->regressand_mean_ + node->regression_*(regressor - node->regressor_mean_);\n\t\t\tkey.head(node->regressand_mean_.size()) += node->regressand_cov_cholesky_*BoxMuller<generic_density_forest_scalar>(node->regressand_mean_.size());\n\n\n\t\t\tif (node->left_or_right(key)) {\n\t\t\t\tnode = node->right_child_.get();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnode = node->left_child_.get();\n\t\t\t}\n\n\n\n\t\t}\n\n\t\treturn key;\n\n\t}\n\n\n\tvoid form_regression(int regressor_dim) {\n\n\t\troot_->compute_gaussian_models();\n\n\t\tstd::vector<NodePointer> nodes;\n\t\tnodes.push_back(root_.get());\n\n\t\twhile (nodes.size() > 0) {\n\n\t\t\tNodePointer node = nodes[nodes.size() - 1];\n\t\t\tnodes.pop_back();\n\n\t\t\tif (node) {\n\t\t\t\tnode->form_regression_parameters(regressor_dim);\n\t\t\t\tnodes.push_back(node->left_child_.get());\n\t\t\t\tnodes.push_back(node->right_child_.get());\n\t\t\t}\n\n\t\t}\n\n\t}\n\n};\n\ntemplate<typename DataType>\nclass GenericDensityForest {\n\n\ttypedef GenericDensityNode<DataType>* NodePointer;\n\ttypedef GenericDensityTree<DataType>* TreePointer;\n\nprivate:\n\npublic:\n\n\tstd::vector<GenericDensityTree<DataType> > forest_;\n\n\tGenericDensityForest() {\n\t\tforest_.push_back(GenericDensityTree<DataType>());\n\t}\n\n\tGenericDensityForest(unsigned int numberOfTrees) {\n\t\tfor (unsigned int treeNum = 0; treeNum < numberOfTrees; treeNum++) {\n\t\t\tforest_.push_back(GenericDensityTree<DataType>());\n\t\t}\n\t}\n\n\tGenericDensityForest(GenericDensityForest& other) {\n\t\tforest_ = other.forest_;\n\t}\n\n\tGenericDensityForest<DataType> operator=(const GenericDensityForest<DataType>& other) {\n\t\tforest_ = other.forest_;\n\t\treturn *this;\n\t}\n\n\tvoid set_key_vector_function(const generic_density_forest_vector* (*key_vector_function)(const DataType&)) {\n\t\tfor (size_t i = 0; i < forest_.size(); i++) {\n\t\t\tforest_[i].root_->get_key_vector_ = key_vector_function;\n\t\t}\n\t}\n\n\n\tvoid set_split_optimization_mode(Split_Optimization_Mode mode) {\n\t\tfor (size_t i = 0; i < forest_.size(); i++) {\n\t\t\tforest_[i].root_->split_mode = mode;\n\t\t}\n\t}\n\n\tvoid add_sample(int tries, int minimum_data_in_leaf, int maximum_data_in_leaf, DataType datum) {\n\t\tfor (size_t i = 0; i < forest_.size(); i++) {\n\t\t\tforest_[i].add_sample(tries, minimum_data_in_leaf, maximum_data_in_leaf, datum);\n\t\t}\n\t}\n\n\tDataType* get_approximate_nearest(const DataType& datum) {\n\n\t\tstd::vector<DataType*> nearest_ones(forest_.size(), nullptr);\n\n\t\t//#pragma omp parallel for\n\t\tfor (size_t i = 0; i < (int)forest_.size(); i++) {\n\t\t\tnearest_ones[i] = forest_[i].get_approximate_nearest(datum);\n\t\t}\n\n\t\tNodePointer random_node = forest_[0].root_.get();\n\t\tconst generic_density_forest_vector& key_vector = *(random_node->get_key_vector_(datum));\n\n\t\tint nearest_idx = 0;\n\t\tgeneric_density_forest_scalar nearest_dist = std::numeric_limits<generic_density_forest_scalar>::infinity();\n\t\tgeneric_density_forest_scalar current_dist = std::numeric_limits<generic_density_forest_scalar>::infinity();\n\n\t\tfor (size_t i = 0; i < nearest_ones.size(); i++) {\n\n\t\t\tif (nearest_ones[i]) {\n\n\t\t\t\tconst generic_density_forest_vector& comparison_key_vector = *(random_node->get_key_vector_(*(nearest_ones[i])));\n\t\t\t\tcurrent_dist = (key_vector - comparison_key_vector).norm();\n\n\t\t\t\tif (current_dist < nearest_dist) {\n\t\t\t\t\tnearest_dist = current_dist;\n\t\t\t\t\tnearest_idx = i;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\treturn nearest_ones[nearest_idx];\n\n\n\t}\n\n\tstd::vector<DataType*> get_neighborhood(const DataType& datum) {\n\n\t\tstd::vector<DataType*> nearest_ones;\n\n\t\tfor (size_t i = 0; i < (int)forest_.size(); i++) {\n\t\t\tstd::vector<DataType*> nearest_ones_tree;\n\t\t\tnearest_ones_tree = forest_[i].get_neighborhood(datum);\n\t\t\tfor (size_t j = 0; j < nearest_ones_tree.size(); j++) {\n\t\t\t\tnearest_ones.push_back(nearest_ones_tree[j]);\n\t\t\t}\n\t\t}\n\n\t\treturn nearest_ones;\n\n\t}\n\n\t//Assuming that data_ptr_array has room for k pointers.\n\tint get_up_to_k_nearest(const DataType& datum, DataType* data_ptr_array[], int k) {\n\t\tconst generic_density_forest_vector& key_vector = *forest_[0].root_->get_key_vector_(datum);\n\t\treturn get_up_to_k_nearest(key_vector, data_ptr_array, k);\n\t}\n\n\tint get_up_to_k_nearest(const generic_density_forest_vector &key_vector, DataType* data_ptr_array[], int k) {\n\n\t\tfor (int i = 0; i < k; i++) {\n\t\t\tdata_ptr_array[i] = nullptr;\n\t\t}\n\n\t\tif (k == 0) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tfor (size_t i = 0; i < (int)forest_.size(); i++) {\n\t\t\tforest_[i].get_up_to_k_nearest(key_vector, data_ptr_array, k);\n\t\t\tforest_[i].get_up_to_k_nearest(key_vector, data_ptr_array, k, true);  //for robustness against splits that leave a child with only few samples, also search the sibling\n\t\t}\n\n\t\tint found_count = 0;\n\n\t\tfor (int i = 0; i < k; i++) {\n\t\t\tif (data_ptr_array[i]) {\n\t\t\t\tfound_count++;\n\t\t\t}\n\t\t}\n\n\t\treturn found_count;\n\n\t}\n\n\n\tint get_neighborhood(const DataType& datum, DataType* nearest_ones[], int max_amount) {\n\n\t\tint end_idx = 0;\n\n\t\tfor (size_t i = 0; i < (int)forest_.size(); i++) {\n\t\t\tend_idx += forest_[i].get_neighborhood(datum, &nearest_ones[end_idx], max_amount - end_idx);\n\t\t}\n\n\t\treturn end_idx;\n\n\t}\n\n\n\t//DataType* get_approximate_nearest(const DataType& datum){\n\n\n\t//\treturn forest_[rand()%forest_.size()].get_approximate_nearest(datum);\n\n\n\t//}\n\n\n\tvoid build_forest(int tries, int minimum_data_in_leaf, std::vector<std::unique_ptr<DataType> > data) {\n\t\tfor (int i = 0; i < (int)forest_.size(); i++) {\n\t\t\tGenericDensityTree<DataType>& tree = forest_[i];\n\t\t\ttree.root_->build_tree(tries, minimum_data_in_leaf, data);\n\t\t}\n\t}\n\n\tvoid build_forest_copying(int tries, int minimum_data_in_leaf, std::vector<DataType >& data) {\n\t\tfor (int i = 0; i < (int)forest_.size(); i++) {\n\t\t\tGenericDensityTree<DataType>& tree = forest_[i];\n\t\t\ttree.build_tree_copying(tries, minimum_data_in_leaf, data);\n\t\t}\n\t}\n\n\n\tgeneric_density_forest_vector sample_conditioned(const generic_density_forest_vector& regressor) {\n\n\t\treturn forest_[rand() % forest_.size()].sample_conditioned(regressor);\n\n\t}\n\n\tvoid form_regressions(int regressor_dim) {\n\t\tfor (int i = 0; i < (int)forest_.size(); i++) {\n\t\t\tGenericDensityTree<DataType>& tree = forest_[i];\n\t\t\ttree.form_regression(regressor_dim);\n\t\t}\n\n\t}\n\n\tvoid claim_ownership_of_forest(GenericDensityForest<DataType>& other_forest) {\n\t\tforest_ = std::move(other_forest.forest_);\n\t}\n\n\tvoid claim_ownership_of_tree(GenericDensityTree<DataType>& tree, size_t number_of_trees_in_this_forest) {\n\t\tif (forest_.size() < number_of_trees_in_this_forest) {\n\t\t\tforest_.push_back(std::move(tree));\n\t\t\treturn;\n\t\t}\n\n\t\tif (forest_.size() > number_of_trees_in_this_forest) {\n\t\t\tforest_.pop_back();\n\t\t}\n\n\t\tint swap_idx = rand() % forest_.size();\n\t\t//forest_[swap_idx].root_.reset();\n\t\t//forest_[swap_idx].root_ = std::move(tree.root_);\n\t\tforest_[swap_idx].root_.swap(tree.root_);\n\t}\n\n\tvoid remove_data_point(DataType datum) {\n\t\tfor (int i = 0; i < (int)forest_.size(); i++) {\n\t\t\tGenericDensityTree<DataType>& tree = forest_[i];\n\t\t\ttree.remove_data_point(datum);\n\t\t}\n\t}\n\n\tDataType* get_random() {\n\t\treturn forest_[rand() % forest_.size()].get_random();\n\t}\n\n\tbool forest_ready_to_use(void) {\n\n\t\tif (forest_.size() == 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (forest_[0].root_->separating_normal_.size() == 0 && forest_[0].root_->data_items_.size() == 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n};\n\n#endif", "meta": {"hexsha": "863f879bdd1dcd45fd3f36c7dbedd020a9d05858", "size": 53614, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "SCA/src/GenericDensityForest.hpp", "max_stars_repo_name": "JooseRajamaeki/TVCG18", "max_stars_repo_head_hexsha": "ddc73f422c267b1c38ede3ba20046efff46a6d74", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-09-23T09:00:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T11:10:49.000Z", "max_issues_repo_path": "SCA/src/GenericDensityForest.hpp", "max_issues_repo_name": "JooseRajamaeki/TVCG18", "max_issues_repo_head_hexsha": "ddc73f422c267b1c38ede3ba20046efff46a6d74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SCA/src/GenericDensityForest.hpp", "max_forks_repo_name": "JooseRajamaeki/TVCG18", "max_forks_repo_head_hexsha": "ddc73f422c267b1c38ede3ba20046efff46a6d74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.639957265, "max_line_length": 191, "alphanum_fraction": 0.7103928078, "num_tokens": 14585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744850834648, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.41198082790069357}}
{"text": "// Copyright 2019 the Autoware Foundation\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Co-developed by Tier IV, Inc. and Apex.AI, Inc.\n\n#ifndef OPTIMIZATION__NEWTONS_METHOD_OPTIMIZER_HPP_\n#define OPTIMIZATION__NEWTONS_METHOD_OPTIMIZER_HPP_\n\n#include <optimization/optimizer.hpp>\n#include <optimization/optimization_problem.hpp>\n#include <optimization/optimizer_options.hpp>\n#include <optimization/line_search/line_search.hpp>\n#include <Eigen/Core>\n#include <Eigen/SVD>\n#include <limits>\n#include <memory>\n#include <cmath>\n#include <iostream>\n\nnamespace autoware\n{\nnamespace common\n{\nnamespace optimization\n{\n/// Optimizer using the Newton method with line search\ntemplate<typename LineSearchT>\nclass OPTIMIZATION_PUBLIC NewtonsMethodOptimizer\n  : public Optimizer<NewtonsMethodOptimizer<LineSearchT>>\n{\npublic:\n  using StepT = float_t;\n\n  /// Constructor to initialize the line search method\n  ///\n  /// @param[in]  line_searcher  An instance of a line search class.\n  /// @param[in]  options        Options to be used for this optimization.\n  ///\n  explicit NewtonsMethodOptimizer(\n    const LineSearchT & line_searcher,\n    const OptimizationOptions & options)\n  : m_line_searcher{line_searcher}, m_options{options} {}\n\n  /// Solves `x_out` for an objective `optimization_problem` and an initial value `x0`\n  ///\n  /// @param      optimization_problem  optimization_problem optimization objective\n  /// @param      x0                    initial value\n  /// @param      x_out                 optimized value\n  ///\n  /// @tparam     OptimizationProblemT  Optimization problem type. Must be an implementation of\n  ///                                   `common::optimization::OptimizationProblem`.\n  /// @tparam     DomainValueT          Type of the parameter\n  /// @tparam     EigenSolverT          Type of eigen solver to be used internallt for solving the\n  ///                                   necessary linear equations. By default set to `Eigen::LDLT`.\n  ///\n  /// @return     Summary of this optimization.\n  ///\n  template<typename OptimizationProblemT, typename DomainValueT, typename EigenSolverT>\n  OptimizationSummary solve_(\n    OptimizationProblemT & optimization_problem,\n    const DomainValueT & x0, DomainValueT & x_out)\n  {\n    // Get types from the method's templated parameter\n    using Value = typename OptimizationProblemT::Value;\n    using Jacobian = typename OptimizationProblemT::Jacobian;\n    using Hessian = typename OptimizationProblemT::Hessian;\n    TerminationType termination_type{TerminationType::NO_CONVERGENCE};\n    Value score_previous{0.0};\n    Jacobian jacobian{Jacobian{}.setZero()};\n    Hessian hessian{Hessian{}.setZero()};\n    DomainValueT opt_direction{DomainValueT{}.setZero()};\n\n    if (!x0.allFinite()) {   // Early exit for invalid input.\n      return OptimizationSummary{0.0, TerminationType::FAILURE, 0UL};\n    }\n\n    // Initialize\n    x_out = x0;\n\n    // Get score, Jacobian and Hessian (pre-computed using evaluate)\n    optimization_problem.evaluate(x_out, ComputeMode{}.set_score().set_jacobian().set_hessian());\n    score_previous = optimization_problem(x_out);\n    optimization_problem.jacobian(x_out, jacobian);\n    optimization_problem.hessian(x_out, hessian);\n\n    // Early exit if the initial solution is good enough.\n    if (jacobian.template lpNorm<Eigen::Infinity>() <= m_options.gradient_tolerance()) {\n      // As there's no newton solution yet, jacobian can be a good substitute.\n      return OptimizationSummary{jacobian.norm(), TerminationType::CONVERGENCE, 0UL};\n    }\n    // rubis t0\n    auto start_time = omp_get_wtime();\n\n    // Iterate until convergence, error, or maximum number of iterations\n    auto nr_iterations = 0UL;\n    for (; nr_iterations < m_options.max_num_iterations(); ++nr_iterations) {\n      if (!x_out.allFinite() || !jacobian.allFinite() || !hessian.allFinite()) {\n        termination_type = TerminationType::FAILURE;\n        break;\n      }\n\n      // rubis\n      if(!para_init) {\n        // Eigen::initParallel();\n        omp_set_num_threads(1);\n        Eigen::setNbThreads(1);\n        para_init = true;\n        auto n = Eigen::nbThreads();\n        std::cerr << \"Eigen nbThreads: \" << n << std::endl;\n        // #pragma omp parallel\n        // {  std::cerr << \"Hello World from thread\" <<  omp_get_thread_num() << std::endl; }\n        std::cerr << \"rubis\" << std::endl;\n      }\n      if(!rt_init) {\n\n      }\n      \n\n      // Find decent direction using Newton's method\n      EigenSolverT solver(hessian);\n      opt_direction = solver.solve(-jacobian);\n\n      // Check if there was a problem during Eigen's solve()\n      if (!opt_direction.allFinite()) {\n        termination_type = TerminationType::FAILURE;\n        break;\n      }\n      // Calculate and apply step length\n      // TODO(zozen): with guarnteed sufficient decrease as in [More, Thuente 1994]\n      // would need partial results passed to optimization_problem before call, as in:\n      // computeStepLengthMT (x0, x_delta, x_delta_norm, transformation_epsilon_/2, ...\n      // and would pre-compute score/jacobian/hessian as during init in evaluate!\n      // also needs the sign to know the direction of optimization?\n      const auto step = m_line_searcher.compute_next_step(\n        x_out, opt_direction,\n        optimization_problem);\n      const auto prev_x_norm = x_out.norm();\n      x_out += step;\n\n      // Check change in parameter relative to the parameter value\n      // tolerance added to the norm for stability when the norm is close to 0\n      // (Inspired from https://github.com/ceres-solver/ceres-solver/blob/4362a2169966e08394252098\n      // c80d1f26764becd0/include/ceres/tiny_solver.h#L244)\n      const auto parameter_tolerance =\n        m_options.parameter_tolerance() * (prev_x_norm + m_options.parameter_tolerance());\n      if (step.norm() <= parameter_tolerance) {\n        termination_type = TerminationType::CONVERGENCE;\n        break;\n      }\n\n      // Update value, Jacobian and Hessian (pre-computed using evaluate)\n      optimization_problem.evaluate(x_out, ComputeMode{}.set_score().set_jacobian().set_hessian());\n      const auto score = optimization_problem(x_out);\n      optimization_problem.jacobian(x_out, jacobian);\n      optimization_problem.hessian(x_out, hessian);\n\n      // Check if the max-norm of the gradient is small enough.\n      if (jacobian.template lpNorm<Eigen::Infinity>() <= m_options.gradient_tolerance()) {\n        termination_type = TerminationType::CONVERGENCE;\n        break;\n      }\n\n      // Check change in cost function.\n      if (std::fabs(score - score_previous) <=\n        (m_options.function_tolerance() * std::fabs(score_previous)))\n      {\n        termination_type = TerminationType::CONVERGENCE;\n        break;\n      }\n      score_previous = score;\n    }\n\n    // rubis t1\n    auto end_time = omp_get_wtime();\n    auto response_time = (end_time - start_time) * 1e3;\n    std::cerr << \"ndt: \" << response_time << std::endl;\n\n    // Returning summary consisting of the following three values:\n    // estimated_distance_to_optimum, convergence_tolerance_criteria_met, number_of_iterations_made\n    return OptimizationSummary{opt_direction.norm(), termination_type, nr_iterations};\n  }\n\nprivate:\n  // initialize on construction\n  LineSearchT m_line_searcher;\n  OptimizationOptions m_options;\n  bool para_init = false;\n  bool rt_init = false;\n};\n}  // namespace optimization\n}  // namespace common\n}  // namespace autoware\n\n#endif  // OPTIMIZATION__NEWTONS_METHOD_OPTIMIZER_HPP_\n", "meta": {"hexsha": "21555e10199c0dbfd794cc56529bb2f4f24cd54b", "size": 8005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/optimization/include/optimization/newtons_method_optimizer.hpp", "max_stars_repo_name": "rubis-lab/autoware_rubis", "max_stars_repo_head_hexsha": "498ec5ff4c448d456fa0c6fe2f17e02fbd13ddb9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/optimization/include/optimization/newtons_method_optimizer.hpp", "max_issues_repo_name": "rubis-lab/autoware_rubis", "max_issues_repo_head_hexsha": "498ec5ff4c448d456fa0c6fe2f17e02fbd13ddb9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/optimization/include/optimization/newtons_method_optimizer.hpp", "max_forks_repo_name": "rubis-lab/autoware_rubis", "max_forks_repo_head_hexsha": "498ec5ff4c448d456fa0c6fe2f17e02fbd13ddb9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.859223301, "max_line_length": 100, "alphanum_fraction": 0.6920674578, "num_tokens": 1849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4117833208212965}}
{"text": "/**  \n * Copyright (c) 2009 Carnegie Mellon University. \n *     All rights reserved.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http://www.graphlab.ml.cmu.edu\n *\n */\n\n\n/**\n * \\file\n * This code iplements the NMF algorithm described in the paper:\n * Lee, D..D., and Seung, H.S., (2001), 'Algorithms for Non-negative Matrix\n * Factorization', Adv. Neural Info. Proc. Syst. 13, 556-562.\n */\n\n#include <graphlab/util/stl_util.hpp>\n#include <graphlab.hpp>\n\n#include <Eigen/Dense>\n#include \"eigen_serialization.hpp\"\n#include <graphlab/macros_def.hpp>\n#include <graphlab/util/timer.hpp>\n#include \"stats.hpp\"\n\ntypedef Eigen::VectorXd vec;\ntypedef Eigen::MatrixXd mat_type;\n\n//when using negative node id range, we are not allowed to use\n//0 and 1 so we add 2.\nconst static int SAFE_NEG_OFFSET=2;\nconst double epsilon = 1e-16;\nstatic bool debug;\nint iter = 0;\n\nbool isuser(uint node){\n  return ((int)node) >= 0;\n}\n/** \n * \\ingroup toolkit_matrix_pvecization\n *\n * \\brief the vertex data type which contains the latent pvec.\n *\n * Each row and each column in the matrix corresponds to a different\n * vertex in the SGD graph.  Associated with each vertex is a pvec\n * (vector) of latent parameters that represent that vertex.  The goal\n * of the SGD algorithm is to find the values for these latent\n * parameters such that the non-zero entries in the matrix can be\n * predicted by taking the dot product of the row and column pvecs.\n */\nstruct vertex_data {\n  /**\n   * \\brief A shared \"constant\" that specifies the number of latent\n   * values to use.\n   */\n  static size_t NLATENT;\n  /** \\brief The latent pvec for this vertex */\n  vec pvec;\n\n  double train_rmse;\n  double validation_rmse;\n  /** \n   * \\brief Simple default constructor which randomizes the vertex\n   *  data \n   */\n  vertex_data() { if (debug) pvec = vec::Ones(NLATENT); else randomize(); train_rmse = validation_rmse = 0; } \n  /** \\brief Randomizes the latent pvec */\n  void randomize() { pvec.resize(NLATENT); pvec.setRandom(); }\n  /** \\brief Save the vertex data to a binary archive */\n  void save(graphlab::oarchive& arc) const { \n    arc << pvec << train_rmse << validation_rmse;\n  }\n  /** \\brief Load the vertex data from a binary archive */\n  void load(graphlab::iarchive& arc) { \n    arc >> pvec >>train_rmse >> validation_rmse;\n  }\n}; // end of vertex data\n\n\n/**\n * \\brief The edge data stores the entry in the matrix.\n *\n * In addition the edge data nmfo stores the most recent error estimate.\n */\nstruct edge_data : public graphlab::IS_POD_TYPE {\n  /**\n   * \\brief The type of data on the edge;\n   *\n   * \\li *Train:* the observed value is correct and used in training\n   * \\li *Validate:* the observed value is correct but not used in training\n   * \\li *Predict:* The observed value is not correct and should not be\n   *        used in training.\n   */\n  enum data_role_type { TRAIN, VALIDATE, PREDICT  };\n\n  /** \\brief the observed value for the edge */\n  float weight;\n\n  /** \\brief The train/validation/test designation of the edge */\n  data_role_type role;\n\n  /** \\brief basic initialization */\n  edge_data(float weight = 0, data_role_type role = PREDICT) :\n    weight(weight), role(role) { }\n\n}; // end of edge data\n\n\n\n/**\n * \\brief The graph type is defined in terms of the vertex and edge\n * data.\n */ \ntypedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;\n\n\n\ndouble extract_l2_error(const graph_type::edge_type & edge);\n\n\n/**\n * \\brief Given a vertex and an edge return the other vertex in the\n * edge.\n */\ninline graph_type::vertex_type\nget_other_vertex(graph_type::edge_type& edge, \n    const graph_type::vertex_type& vertex) {\n  return vertex.id() == edge.source().id()? edge.target() : edge.source();\n}; // end of get_other_vertex\n\n\nclass gather_type {\n  public:\n    vec pvec;\n    double training_rmse;\n    double validation_rmse;\n    gather_type() { training_rmse = validation_rmse = 0; }\n    gather_type(const vec & _pvec, double _train_rmse, double _validation_rmse){ pvec = _pvec; training_rmse = _train_rmse; validation_rmse = _validation_rmse; }\n    void reset(){ pvec = vec::Zero(vertex_data::NLATENT); training_rmse = 0; validation_rmse = 0; }\n    void save(graphlab::oarchive& arc) const { arc << pvec << training_rmse << validation_rmse; }\n    void load(graphlab::iarchive& arc) { arc >> pvec >> training_rmse >> validation_rmse; }  \n    gather_type& operator+=(const gather_type& other) {\n      pvec += other.pvec;\n      training_rmse += other.training_rmse;\n      validation_rmse += other.validation_rmse;\n      return *this;\n    } \n\n};\n\ngather_type x1;\ngather_type x2;\ngather_type * px;\n\n\nbool isuser_node(const graph_type::vertex_type& vertex){\n  return isuser(vertex.id());\n}\n/**\n * SGD vertex program type\n */ \nclass nmf_vertex_program :\n  public graphlab::ivertex_program<graph_type, gather_type, gather_type>,\n  public graphlab::IS_POD_TYPE{\n    public:\n      /** The convergence tolerance */\n      static double TOLERANCE;\n      static double MAXVAL;\n      static double MINVAL;\n      static bool debug;\n      static size_t MAX_UPDATES;\n\n      /** compute a missing value based on NMF algorithm */\n      static float nmf_predict(const vertex_data& user, \n          const vertex_data& movie, \n          const float rating, \n          double & prediction){\n\n        prediction = user.pvec.dot(movie.pvec);\n        //truncate prediction to allowed values\n        prediction = std::min((double)prediction, nmf_vertex_program::MAXVAL);\n        prediction = std::max((double)prediction, nmf_vertex_program::MINVAL);\n        //return the squared error\n        float err = rating - prediction;\n        assert(!std::isnan(err));\n        return err*err; \n\n      }\n\n\n      /** The set of edges to gather along */\n      edge_dir_type gather_edges(icontext_type& context, \n          const vertex_type& vertex) const { \n        //UNUSED \n        return graphlab::ALL_EDGES; \n      }; // end of gather_edges \n\n      /** The gather function computes XtX and Xy */\n      gather_type gather(icontext_type& context, const vertex_type& vertex, \n          edge_type& edge) const {\n\n        if (edge.data().role == edge_data::TRAIN || edge.data().role == edge_data::VALIDATE){\n          const vertex_type other_vertex = get_other_vertex(edge, vertex);\n          double prediction = 0;\n          double rmse = nmf_predict(vertex.data(), other_vertex.data(), edge.data().weight, prediction);\n          if (prediction == 0)\n            logstream(LOG_FATAL)<<\"Got into numerical error!\" << std::endl;\n          if (edge.data().role == edge_data::TRAIN)\n            return gather_type(other_vertex.data().pvec * (edge.data().weight / prediction), rmse, 0);\n          else //validation\n            return gather_type(vec::Zero(vertex_data::NLATENT), 0, rmse);\n\n        }\n        return gather_type(vec::Zero(vertex_data::NLATENT), 0, 0);\n      } // end of gather function\n\n      void apply(icontext_type& context, vertex_type& vertex,\n          const gather_type& sum) {\n        vertex_data& vdata = vertex.data();  \n        if (vdata.pvec.sum() != 0){\n          for (uint i=0; i< vertex_data::NLATENT; i++){\n            vdata.pvec[i] *= sum.pvec[i] / px->pvec[i];\n            ASSERT_NE(px->pvec[i] , 0);\n            if (vdata.pvec[i] < epsilon)\n              vdata.pvec[i] = epsilon;\n          }\n        }\n        vdata.train_rmse = sum.training_rmse;\n        vdata.validation_rmse = sum.validation_rmse;\n      }\n\n      edge_dir_type scatter_edges(icontext_type& context,\n          const vertex_type& vertex) const { \n        //UNUSED \n        return graphlab::ALL_EDGES; \n      }; // end of scatter edges\n\n      void scatter(icontext_type& context, const vertex_type& vertex, \n          edge_type& edge) const {\n        //we do not schedule any more neighbors to run\n      } \n      static void verify_rows(graph_type::vertex_type& vertex){\n        if (isuser(vertex.id()) && vertex.num_out_edges() == 0)\n          logstream(LOG_FATAL)<<\"NMF algorithm can not work when the row \" << vertex.id() << \" of the matrix contains all zeros\" << std::endl;\n      }\n\n      static gather_type pre_iter(const graph_type::vertex_type & vertex){\n        gather_type ret;\n        ret.pvec = vertex.data().pvec;\n        ret.training_rmse = vertex.data().train_rmse;\n        ret.validation_rmse = vertex.data().validation_rmse;\n        return ret;\n      }\n\n\n      static graphlab::empty signal_left(icontext_type& context,\n          const vertex_type& vertex) {\n        if(vertex.num_out_edges() > 0) context.signal(vertex);\n        return graphlab::empty();\n      } // end of signal_left \n\n      static graphlab::empty signal_right(icontext_type& context,\n          const vertex_type& vertex) {\n        if(vertex.num_in_edges() > 0) context.signal(vertex);\n        return graphlab::empty();\n      } // end of signal_left \n\n  }; // end of nmf vertex program\n\ngather_type count_edges(nmf_vertex_program::icontext_type & context, const graph_type::edge_type& edge) {\n  gather_type ret;\n  if (edge.data().role == edge_data::TRAIN){\n    ret.training_rmse = 1;\n  }\n  else if (edge.data().role == edge_data::VALIDATE){\n    ret.validation_rmse = 1;\n  }\n  if (edge.data().weight < 0)\n    logstream(LOG_FATAL)<<\"Found a negative entry in matirx row \" << edge.source().id() << \" with value: \" << edge.data().weight << std::endl;\n  return ret;\n}\n\n\nstruct prediction_saver {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  /* save the linear model, using the format:\n     nodeid) factor1 factor2 ... factorNLATENT \\n\n     */\n  std::string save_vertex(const vertex_type& vertex) const {\n    return \"\";\n  }\n  std::string save_edge(const edge_type& edge) const {\n    if (edge.data().role != edge_data::PREDICT)\n      return \"\";\n\n    std::stringstream strm;\n    const double prediction = \n      edge.source().data().pvec.dot(edge.target().data().pvec);\n    strm << edge.source().id() << '\\t' \n      << -edge.target().id()-SAFE_NEG_OFFSET << '\\t'\n      << prediction << '\\n';\n    return strm.str();\n  }\n}; // end of prediction_saver\n\nstruct linear_model_saver_U {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  /* save the linear model, using the format:\n     nodeid) factor1 factor2 ... factorNLATENT \\n\n     */\n  std::string save_vertex(const vertex_type& vertex) const {\n    if (vertex.num_out_edges() > 0){\n      std::string ret = boost::lexical_cast<std::string>(vertex.id()) + \") \";\n      for (uint i=0; i< vertex_data::NLATENT; i++)\n        ret += boost::lexical_cast<std::string>(vertex.data().pvec[i]) + \" \";\n      ret += \"\\n\";\n      return ret;\n    }\n    else return \"\";\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\";\n  }\n}; \n\nstruct linear_model_saver_V {\n  typedef graph_type::vertex_type vertex_type;\n  typedef graph_type::edge_type   edge_type;\n  /* save the linear model, using the format:\n     nodeid) factor1 factor2 ... factorNLATENT \\n\n     */\n  std::string save_vertex(const vertex_type& vertex) const {\n    if (vertex.num_out_edges() == 0){\n      std::string ret = boost::lexical_cast<std::string>(-vertex.id()-SAFE_NEG_OFFSET) + \") \";\n      for (uint i=0; i< vertex_data::NLATENT; i++)\n        ret += boost::lexical_cast<std::string>(vertex.data().pvec[i]) + \" \";\n      ret += \"\\n\";\n      return ret;\n    }\n    else return \"\";\n  }\n  std::string save_edge(const edge_type& edge) const {\n    return \"\";\n  }\n}; \n\n\n\n/**\n * \\brief The graph loader function is a line parser used for\n * distributed graph construction.\n */\ninline bool graph_loader(graph_type& graph, \n    const std::string& filename,\n    const std::string& line) {\n  ASSERT_FALSE(line.empty()); \n\n // Parse the line\n  std::stringstream strm(line);\n  graph_type::vertex_id_type source_id(-1), target_id(-1);\n  float weight(0);\n  strm >> source_id >> target_id;\n\n  if (source_id == graph_type::vertex_id_type(-1) || target_id == graph_type::vertex_id_type(-1)){\n    logstream(LOG_WARNING)<<\"Failed to read input line: \"<< line << \" in file: \"  << filename << \" (or node id is -1). \" << std::endl;\n    return true;\n  }\n\n  // Determine the role of the data\n  edge_data::data_role_type role = edge_data::TRAIN;\n  if(boost::ends_with(filename,\".validate\")) role = edge_data::VALIDATE;\n  else if(boost::ends_with(filename, \".predict\")) role = edge_data::PREDICT;\n \n  // for test files (.predict) no need to read the actual rating value.\n  if(role == edge_data::TRAIN || role == edge_data::VALIDATE){\n    strm >> weight;\n    if (weight < nmf_vertex_program::MINVAL || weight > nmf_vertex_program::MAXVAL)\n      logstream(LOG_FATAL)<<\"Rating values should be between \" << nmf_vertex_program::MINVAL << \" and \" << nmf_vertex_program::MAXVAL << \". Got value: \" << weight << \" [ user: \" << source_id << \" to item: \" <<target_id << \" ] \" << std::endl; \n  }\n  target_id = -(graphlab::vertex_id_type(target_id + SAFE_NEG_OFFSET));\n\n  // Create an edge and add it to the graph\n  graph.add_edge(source_id, target_id, edge_data(weight, role)); \n  return true; // successful load\n} // end of graph_loader\n\n\n\n\n\n\nsize_t vertex_data::NLATENT = 20;\ndouble nmf_vertex_program::TOLERANCE = 1e-3;\nsize_t nmf_vertex_program::MAX_UPDATES = -1;\ndouble nmf_vertex_program::MAXVAL = 1e+100;\ndouble nmf_vertex_program::MINVAL = -1e+100;\nbool nmf_vertex_program::debug = false;\n\n\n/**\n * \\brief The engine type used by the ALS matrix factorization\n * algorithm.\n *\n * The ALS matrix factorization algorithm currently uses the\n * synchronous engine.  However we plan to add support for alternative\n * engines in the future.\n */\ntypedef graphlab::omni_engine<nmf_vertex_program> engine_type;\n\nint main(int argc, char** argv) {\n  global_logger().set_log_level(LOG_INFO);\n  global_logger().set_log_to_console(true);\n\n  // Parse command line options -----------------------------------------------\n  const std::string description = \n    \"Compute the ALS factorization of a matrix.\";\n  graphlab::command_line_options clopts(description);\n  std::string input_dir;\n  std::string predictions;\n  std::string exec_type = \"synchronous\";\n  clopts.attach_option(\"matrix\", input_dir,\n      \"The directory containing the matrix file\");\n  clopts.add_positional(\"matrix\");\n  clopts.attach_option(\"D\", vertex_data::NLATENT,\n      \"Number of latent parameters to use.\");\n  clopts.attach_option(\"engine\", exec_type, \n      \"The engine type synchronous or asynchronous\");\n  clopts.attach_option(\"max_iter\", nmf_vertex_program::MAX_UPDATES,\n      \"The maxumum number of udpates allowed for a vertex\");\n  clopts.attach_option(\"debug\", nmf_vertex_program::debug, \n      \"debug - additional verbose info\"); \n  clopts.attach_option(\"maxval\", nmf_vertex_program::MAXVAL, \"max allowed value\");\n  clopts.attach_option(\"minval\", nmf_vertex_program::MINVAL, \"min allowed value\");\n  clopts.attach_option(\"predictions\", predictions,\n      \"The prefix (folder and filename) to save predictions.\");\n\n  if(!clopts.parse(argc, argv) || input_dir == \"\") {\n    std::cout << \"Error in parsing command line arguments.\" << std::endl;\n    clopts.print_description();\n    return EXIT_FAILURE;\n  }\n  debug = nmf_vertex_program::debug;\n  \n  graphlab::mpi_tools::init(argc, argv);\n  graphlab::distributed_control dc;\n\n  dc.cout() << \"Loading graph.\" << std::endl;\n  graphlab::timer timer; \n  graph_type graph(dc, clopts);  \n  graph.load(input_dir, graph_loader); \n  dc.cout() << \"Loading graph. Finished in \" \n    << timer.current_time() << std::endl;\n  dc.cout() << \"Finalizing graph.\" << std::endl;\n  timer.start();\n  graph.finalize();\n  dc.cout() << \"Finalizing graph. Finished in \" \n    << timer.current_time() << std::endl;\n\n  if (!graph.num_edges() || !graph.num_vertices())\n     logstream(LOG_FATAL)<< \"Failed to load graph. Check your input path: \" << input_dir << std::endl;     \n\n\n\n  dc.cout() \n    << \"========== Graph statistics on proc \" << dc.procid() \n    << \" ===============\"\n    << \"\\n Num vertices: \" << graph.num_vertices()\n    << \"\\n Num edges: \" << graph.num_edges()\n    << \"\\n Num replica: \" << graph.num_replicas()\n    << \"\\n Replica to vertex ratio: \" \n    << float(graph.num_replicas())/graph.num_vertices()\n    << \"\\n --------------------------------------------\" \n    << \"\\n Num local own vertices: \" << graph.num_local_own_vertices()\n    << \"\\n Num local vertices: \" << graph.num_local_vertices()\n    << \"\\n Replica to own ratio: \" \n    << (float)graph.num_local_vertices()/graph.num_local_own_vertices()\n    << \"\\n Num local edges: \" << graph.num_local_edges()\n    //<< \"\\n Begin edge id: \" << graph.global_eid(0)\n    << \"\\n Edge balance ratio: \" \n    << float(graph.num_local_edges())/graph.num_edges()\n    << std::endl;\n\n  dc.cout() << \"Creating engine\" << std::endl;\n  engine_type engine(dc, graph, exec_type, clopts);\n\n\n  // Run the NMF ---------------------------------------------------------\n  dc.cout() << \"Running NMF\" << std::endl;\n  dc.cout() << \"(C) Code by Danny Bickson, CMU \" << std::endl;\n  dc.cout() << \"Please send bug reports to danny.bickson@gmail.com\" << std::endl;\n  dc.cout() << \"Time   Training    Validation\" <<std::endl;\n  dc.cout() << \"       RMSE        RMSE \" <<std::endl;\n  timer.start();\n\n  gather_type edge_count = engine.map_reduce_edges<gather_type>(count_edges);\n  dc.cout()<<\"Training edges: \" << edge_count.training_rmse << \" validation edges: \" << edge_count.validation_rmse << std::endl;\n\n  graphlab::vertex_set left = graph.select(isuser_node);\n  graphlab::vertex_set right = ~left;\n  graph.transform_vertices(nmf_vertex_program::verify_rows, left);\n\n  graphlab::timer mytimer; mytimer.start();\n\n  for (uint j=0; j< nmf_vertex_program::MAX_UPDATES; j++){\n    x1 = graph.map_reduce_vertices<gather_type>(nmf_vertex_program::pre_iter,right);\n    px = &x1;\n    for (int i=0; i< (int)vertex_data::NLATENT; i++)\n      ASSERT_NE(px->pvec[i], 0);\n    \n    dc.cout()<< std::setw(8) << mytimer.current_time() << \" \" << sqrt(x1.training_rmse/edge_count.training_rmse);\n    if (edge_count.validation_rmse > 0)\n      dc.cout() << \" \" << std::setw(8) << sqrt(x1.validation_rmse/edge_count.validation_rmse) << std::endl;\n    else dc.cout() << std::endl;\n    engine.map_reduce_vertices<graphlab::empty>(nmf_vertex_program::signal_left);\n    engine.start();\n    x1.reset();\n\n    x2 = graph.map_reduce_vertices<gather_type>(nmf_vertex_program::pre_iter,left);\n    px = &x2;\n\n    engine.map_reduce_vertices<graphlab::empty>(nmf_vertex_program::signal_right);\n    engine.start();\n    x2.reset();\n  }\n\n  const double runtime = timer.current_time();\n  dc.cout() << \"----------------------------------------------------------\"\n    << std::endl\n    << \"Final Runtime (seconds):   \" << runtime \n                                        << std::endl\n                                        << \"Updates executed: \" << engine.num_updates() << std::endl\n                                        << \"Update Rate (updates/second): \" \n                                          << engine.num_updates() / runtime << std::endl;\n\n\n  // Make predictions ---------------------------------------------------------\n  if(!predictions.empty()) {\n    std::cout << \"Saving predictions\" << std::endl;\n    const bool gzip_output = false;\n    const bool save_vertices = false;\n    const bool save_edges = true;\n    const size_t threads_per_machine = 1;\n    //save the predictions\n    graph.save(predictions, prediction_saver(),\n        gzip_output, save_vertices, \n        save_edges, threads_per_machine);\n    //save the linear model\n    graph.save(predictions + \".U\", linear_model_saver_U(),\n        gzip_output, save_edges, save_vertices, threads_per_machine);\n    graph.save(predictions + \".V\", linear_model_saver_V(),\n        gzip_output, save_edges, save_vertices, threads_per_machine);\n\n  }\n\n  graphlab::mpi_tools::finalize();\n  return EXIT_SUCCESS;\n} // end of main\n\n\n\n", "meta": {"hexsha": "c8e5f51a37e1caeda82b4004fde60aed45812eec", "size": 20354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/collaborative_filtering/nmf.cpp", "max_stars_repo_name": "coreyp1/graphlab", "max_stars_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T11:46:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T22:45:55.000Z", "max_issues_repo_path": "toolkits/collaborative_filtering/nmf.cpp", "max_issues_repo_name": "coreyp1/graphlab", "max_issues_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolkits/collaborative_filtering/nmf.cpp", "max_forks_repo_name": "coreyp1/graphlab", "max_forks_repo_head_hexsha": "637be90021c5f83ab7833ca15c48e76039057969", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T12:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-16T16:48:40.000Z", "avg_line_length": 35.2755632582, "max_line_length": 242, "alphanum_fraction": 0.6478824801, "num_tokens": 5117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4117430341590912}}
{"text": "#pragma once\n#include <boost/serialization/vector.hpp>\n#include <cmath>\n#include <iostream>\n\n#include <tbb/concurrent_vector.h>\n#include <tbb/concurrent_unordered_map.h>\n#include <tbb/parallel_sort.h>\n#include <tbb/parallel_for_each.h>\n\n#include \"BasisJz.hpp\"\n#include \"AbstractBasis1D.hpp\"\n\nnamespace edlib\n{\ntemplate<typename UINT>\nclass Basis1D final\n\t: public AbstractBasis1D<UINT>\n{\nprivate:\n\ttbb::concurrent_vector<std::pair<UINT, uint32_t>> rpts_; //Representatives\n\n\tint checkState(UINT s) \n\t{\n\t\tUINT sr = s;\n\t\tconst auto N = this->getN();\n\t\tconst auto k = this->getK();\n\n\t\tfor(uint32_t r = 1; r <= N; r++)\n\t\t{\n\t\t\tsr = this->rotl(s, r);\n\t\t\tif(sr < s)\n\t\t\t{\n\t\t\t\treturn -1; //s is not a representative\n\t\t\t}\n\t\t\telse if(sr == s)\n\t\t\t{\n\t\t\t\t/* s is smller than rotl(s,1), rot(s, 2), ..., rot(s, r-1)\n\t\t\t\t * when we fall in this else if clause. As rot(s,r) == s,\n\t\t\t\t * s is the smallest among rotl(s, 1), ..., rotl(s, N-1).\n\t\t\t\t */\n\t\t\t\tif((k % (N/r)) != 0)\n\t\t\t\t\treturn -1; //this representative is not allowed for k\n\t\t\t\treturn r;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\n\tvoid constructBasisFull()\n\t{\n\t\t// insert 0\n\t\t{\n\t\t\tUINT s = 0;\n\t\t\tint r = checkState(s);\n\t\t\tif(r > 0)\n\t\t\t{\n\t\t\t\trpts_.emplace_back(s,r);\n\t\t\t}\n\t\t}\n\n\t\t// iterate over all odd numbers\n\t\tconst uint32_t N = this->getN();\n\t\ttbb::parallel_for(UINT(1), (UINT(1)<<UINT(N)), UINT(2), [&](UINT s)\n\t\t{\n\t\t\tint r = checkState(s);\n\t\t\tif(r > 0)\n\t\t\t{\n\t\t\t\trpts_.emplace_back(s,r);\n\t\t\t}\n\t\t});\n\t\ttbb::parallel_sort(rpts_.begin(), rpts_.end());\n\t}\n\n\tvoid constructBasisJz()\n\t{\n\t\tconst uint32_t n = this->getN();\n\t\tconst uint32_t nup = n/2;\n\n\t\tBasisJz<UINT> basis(n,nup);\n\n\t\ttbb::parallel_for_each(basis.begin(), basis.end(), [&](UINT s)\n\t\t{\n\t\t\tint r = checkState(s);\n\t\t\tif(r > 0)\n\t\t\t{\n\t\t\t\trpts_.emplace_back(s,r);\n\t\t\t}\n\t\t});\n\t\ttbb::parallel_sort(rpts_.begin(), rpts_.end());\n\t}\n\npublic:\n\tBasis1D(uint32_t N, uint32_t k, bool useU1)\n\t\t: AbstractBasis1D<UINT>(N, k)\n\t{\n\t\tassert( (!useU1) || (N % 2 == 0));\n\t\tif(useU1)\n\t\t{\n\t\t\tconstructBasisJz();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconstructBasisFull();\n\t\t}\n\t}\n\n\tBasis1D(const Basis1D& ) = default;\n\tBasis1D(Basis1D&& ) = default;\n\n\tBasis1D& operator=(const Basis1D& ) = default;\n\tBasis1D& operator=(Basis1D&& ) = default;\n\n\t~Basis1D() = default;\n\n\tuint32_t stateIdx(UINT rep) const\n\t{\n\t\tauto comp = [](const std::pair<UINT, uint32_t>& v1, UINT v2)\n\t\t{\n\t\t\treturn v1.first < v2;\n\t\t};\n\t\tauto iter = lower_bound(rpts_.begin(), rpts_.end(), rep, comp);\n\t\tif((iter == rpts_.end()) || (iter->first != rep))\n\t\t{\n\t\t\treturn getDim();\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn distance(rpts_.begin(), iter);\n\t\t}\n\t}\n\n\ttbb::concurrent_vector<std::pair<UINT,uint32_t>> getRepresentatives() const\n\t{\n\t\treturn rpts_;\n\t}\n\n\tstd::size_t getDim() const override\n\t{\n\t\treturn rpts_.size();\n\t}\n\n\tUINT getNthRep(uint32_t n) const override\n\t{\n\t\treturn rpts_[n].first;\n\t}\n\n\tinline uint32_t rotRpt(uint32_t n) const\n\t{\n\t\treturn rpts_[n].second;\n\t}\n\n\tstd::pair<int, double> hamiltonianCoeff(UINT bSigma, int aidx) const override\n\t{\n\t\tusing std::sqrt;\n\t\tusing std::pow;\n\n\t\tconst auto k = this->getK();\n\t\tdouble expk = (k == 0)?1.0:-1.0;\n\n\t\tUINT bRep;\n\t\tint bRot;\n\t\tstd::tie(bRep, bRot) = this->findMinRots(bSigma);\n\n\t\tauto bidx = stateIdx(bRep);\n\n\t\tif(bidx >= getDim())\n\t\t{\n\t\t\treturn std::make_pair(-1, 0.0);\n\t\t}\n\n\t\tdouble Na = 1.0/rpts_[aidx].second;\n\t\tdouble Nb = 1.0/rpts_[bidx].second;\n\n\t\treturn std::make_pair(bidx, sqrt(Nb/Na)*pow(expk, bRot));\n\t}\n\n\tstd::vector<std::pair<UINT, double>> basisVec(uint32_t n) const override\n\t{\n\t\tconst auto k = this->getK();\n\t\tconst double expk = (k == 0)?1.0:-1.0;\n\t\tstd::vector<std::pair<UINT,double>> res;\n\n\t\tauto rep = rpts_[n].first;\n\t\tdouble norm = 1.0/sqrt(rpts_[n].second);\n\t\tfor(uint32_t r = 0; r < rpts_[n].second; r++)\n\t\t{\n\t\t\tres.emplace_back( this->rotl(rep, r), pow(expk, r)*norm);\n\t\t}\n\t\treturn res;\n\t}\n};\n} // namespace edlib\n", "meta": {"hexsha": "86c0e3b024c1f51586d3829701c27ca778e606ec", "size": 3796, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/edlib/Basis/Basis1D.hpp", "max_stars_repo_name": "chaeyeunpark/ExactDiagonalization", "max_stars_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-24T08:47:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T08:47:05.000Z", "max_issues_repo_path": "include/edlib/Basis/Basis1D.hpp", "max_issues_repo_name": "chaeyeunpark/ExactDiagonalization", "max_issues_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-28T19:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-28T19:02:14.000Z", "max_forks_repo_path": "include/edlib/Basis/Basis1D.hpp", "max_forks_repo_name": "chaeyeunpark/ExactDiagonalization", "max_forks_repo_head_hexsha": "c93754e724486cc68453399c5dda6a2dadf45cb8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-22T18:59:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-22T18:59:11.000Z", "avg_line_length": 19.5670103093, "max_line_length": 78, "alphanum_fraction": 0.6109062171, "num_tokens": 1350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4116988779367988}}
{"text": "/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu>                    \n * Licensed under the MIT license. See the license file LICENSE.                \n */\n\n#include <iostream>\n#include <stdint.h>\n#include <vector>\n#include <Eigen/Dense>\n\n#include <boost/shared_ptr.hpp>\n\n#include <dpMM/dpMM.hpp>\n#include <dpMM/cat.hpp>\n#include <dpMM/dir.hpp>\n#include <dpMM/niw.hpp>\n#include <dpMM/sampler.hpp>\n#include <dpMM/clGMMData.hpp>\n#include <dpMM/niwSphere.hpp>\n\nusing namespace Eigen;\nusing std::endl; using std::cout;\nusing boost::shared_ptr;\n\n/* Dirichlet Mixture using ClGMMData for data storage - should be FAST */\ntemplate <class H, class T>\nclass DirMMcld : public DpMM<T>\n{\n  uint32_t K_;\n  Dir<Cat<T>,T> dir_;\n  Cat<T> pi_;\n#ifdef CUDA\n  SamplerGpu<T>* sampler_;\n#else \n  Sampler<T>* sampler_;\n#endif\n  Matrix<T,Dynamic,Dynamic> pdfs_;\n//  Cat cat_;\n  shared_ptr<BaseMeasure<T> > theta0_;\n  vector<shared_ptr<BaseMeasure<T> > > thetas_;\n\n  shared_ptr<ClGMMData<T> > cld_;\n  \npublic:\n  DirMMcld(const Dir<Cat<T>,T>& alpha, const shared_ptr<BaseMeasure<T> >& theta);\n  DirMMcld(const Dir<Cat<T>,T>& alpha, const vector<shared_ptr<BaseMeasure<T> > >& thetas);\n  ~DirMMcld();\n\n  void initialize(const shared_ptr<ClGMMData<T> >& cld);\n  void initialize(const Matrix<T,Dynamic,Dynamic>& x)\n    {cout<<\"not supported\"<<endl; assert(false);};\n\n  void sampleLabels();\n  void sampleParameters();\n\n  double logJoint();\n  const VectorXu& z(){return (cld_->z());};\n  const VectorXu& labels(){return (cld_->z());};\n  const VectorXu& getLabels(){return (cld_->z());};\n  const Matrix<T,Dynamic,1>& counts(){return cld_->counts();};\n  const Matrix<T,Dynamic,Dynamic>& means(){return cld_->means();};\n\n  virtual uint32_t getK() const { return K_;};\n\n  Matrix<T,Dynamic,1> getCounts();\n\nprivate: \n};\n\n// --------------------------------------- impl -------------------------------\n\ntemplate <class H, class T>\nDirMMcld<H,T>::DirMMcld(const Dir<Cat<T>,T>& alpha, \n    const shared_ptr<BaseMeasure<T> >& theta) \n  : K_(alpha.K_), dir_(alpha), pi_(dir_.sample()), theta0_(theta)\n{};\n\ntemplate <class H, class T>\nDirMMcld<H,T>::DirMMcld(const Dir<Cat<T>,T>& alpha, \n    const vector<shared_ptr<BaseMeasure<T> > >& thetas) :\n  K_(alpha.K_), dir_(alpha), pi_(dir_.sample()), //cat_(dir_.sample()),\n  thetas_(thetas)\n{};\n\ntemplate <class H, class T>\nDirMMcld<H,T>::~DirMMcld()\n{\n  if (sampler_ != NULL) delete sampler_;\n};\n\ntemplate <class H, class T>\nMatrix<T,Dynamic,1> DirMMcld<H,T>::getCounts()\n{\n  return counts();\n};\n\n\n//template <class H, class T>\n//void DirMMcld<H,T>::initialize(const Matrix<T,Dynamic,Dynamic>& x)\n//{\n//\n//};\n\ntemplate <class H, class T>\nvoid DirMMcld<H,T>::initialize(const shared_ptr<ClGMMData<T> >& cld)\n{\n  cld_ = cld;\n  assert(cld_->K() == K_);\n\n  cout<<\"init\"<<endl;\n  // randomly init labels from prior\n  cout<<\"sample pi\"<<endl;\n  pi_ = dir_.sample(); \n  cout<<\"init pi=\"<<pi_.pdf().transpose()<<endl;\n#ifdef CUDA\n  sampler_ = new SamplerGpu<T>(cld_->N(),K_,dir_.pRndGen_);\n#else \n  sampler_ = new Sampler<T>(dir_.pRndGen_);\n#endif\n  //TODO: use sampler for this\n  //pi_.sample(*(cld_->z()));\n  pdfs_.setZero(cld_->N(),K_);\n  for(uint32_t i=0; i<cld_->N(); ++i)\n    pdfs_.row(i) = pi_.pdf();\n  sampler_->sampleDiscPdf(pdfs_,(cld_->z()));\n//  cout<<z->transpose()<<endl;\n  assert((cld->z().array() < K_).all());\n  // init the parameters\n  if(thetas_.size() == 0)\n  {\n    cout<<\"creating thetas\"<<endl;\n    for (uint32_t k=0; k<K_; ++k)\n      thetas_.push_back(shared_ptr<BaseMeasure<T> >(theta0_->copy()));\n  }\n//  cld_->update(K_);\n//  for(uint32_t k=0; k<K_; ++k)\n//    thetas_[k]->posterior(cld_,k);\n//  for (uint32_t k=0; k<K_; ++k)\n//    thetas_[k].initialize(x_,z_);\n};\n\ntemplate <class H, class T>\nvoid DirMMcld<H,T>::sampleLabels()\n{\n  // obtain posterior categorical under labels\n  pi_ = dir_.posterior(*(cld_->z())).sample();\n//  cout<<pi_.pdf().transpose()<<endl;\n  \n  for(uint32_t i=0; i<cld_->N(); ++i)\n  {\n    //TODO: could buffer this better\n    // compute categorical distribution over label z_i\n    VectorXd logPdf_z = pi_.pdf().array().log();\n    for(uint32_t k=0; k<K_; ++k)\n    {\n//      cout<<thetas_[k].logLikelihood(cld_->x()->col(i))<<\" \";\n      // TODO this does waste time since we are doing Log_p for all x on CPU\n      logPdf_z[k] += thetas_[k]->logLikelihood(*(cld_->x()),i);\n    }\n//    cout<<endl;\n    // make pdf sum to 1. and exponentiate\n    pdfs_.row(i) = (logPdf_z.array()-logSumExp(logPdf_z)).exp().matrix().transpose();\n//    cout<<pi_.pdf().transpose()<<endl;\n//    cout<<pdf.transpose()<<\" |.|=\"<<pdf.sum();\n//    cout<<\" z_i=\"<<z_[i]<<endl;\n  }\n  // sample z_i\n  sampler_->sampleDiscPdf(pdfs_,cld_->z());\n//    cout<<pdfs_<<endl;\n//  cout<<\" z=\"<<(*(cld_->z())).transpose()<<endl;\n};\n\n// specialization of the sampling function to run on GPU\ntemplate<>\nvoid DirMMcld<NiwSphere<float>,float>::sampleLabels()\n{\n//  cout<<\"sampling specialized to DirMMcld<NiwSphere,float>\"<<endl;\n  // obtain posterior categorical under labels\n//  pi_ = dir_.posterior(*(cld_->z())).sample();\n  pi_ = dir_.posteriorFromCounts(cld_->counts()).sample();\n//  cout<<pi_.pdf().transpose()<<endl;\n  vector<Matrix<float,Dynamic,Dynamic> > Sigmas(K_,\n      Matrix<float,Dynamic,Dynamic>::Zero(cld_->D(),cld_->D()));\n  Matrix<float,Dynamic,1> logNormalizers(K_);\n  for(uint32_t k=0; k<K_; ++k)\n  {\n    Sigmas[k] = dynamic_cast<NiwSphere<float>* >(\n        thetas_[k].get())->normalS_.Sigma();\n    logNormalizers(k) = -0.5* dynamic_cast<NiwSphere<float>* >(\n        thetas_[k].get())->normalS_.logDetSigma();\n  }\n//  cout<<logNormalizers.transpose()<<endl;\n  cld_->sampleGMMpdf(pi_.pdf(), Sigmas, logNormalizers, sampler_);\n};\n\ntemplate<>\nvoid DirMMcld<NiwSphere<double>,double>::sampleLabels()\n{\n//  cout<<\"sampling specialized to DirMMcld<NiwSphere,double>\"<<endl;\n  // obtain posterior categorical under labels\n//  pi_ = dir_.posterior(*(cld_->z())).sample();\n  pi_ = dir_.posteriorFromCounts(cld_->counts()).sample();\n//  cout<<pi_.pdf().transpose()<<endl;\n  vector<Matrix<double,Dynamic,Dynamic> > Sigmas(K_,\n      Matrix<double,Dynamic,Dynamic>::Zero(cld_->D(),cld_->D()));\n  Matrix<double,Dynamic,1> logNormalizers(K_);\n  for(uint32_t k=0; k<K_; ++k)\n  {\n    Sigmas[k] = dynamic_cast<NiwSphere<double>* >(\n        thetas_[k].get())->normalS_.Sigma();\n    logNormalizers(k) = -0.5* dynamic_cast<NiwSphere<double>* >(\n        thetas_[k].get())->normalS_.logDetSigma();\n  }\n//  cout<<logNormalizers.transpose()<<endl;\n\n  cld_->sampleGMMpdf(pi_.pdf(), Sigmas, logNormalizers, sampler_);\n};\n\n\ntemplate <class H, class T>\nvoid DirMMcld<H,T>::sampleParameters()\n{\n  cld_->update(K_);\n  for(uint32_t k=0; k<K_; ++k)\n    thetas_[k]->posterior(cld_,k);\n};\n\ntemplate <class H, class T>\ndouble DirMMcld<H,T>::logJoint()\n{\n  double logJoint = dir_.logPdf(pi_);\n  for (uint32_t k=0; k<K_; ++k)\n    logJoint += thetas_[k]->logPdfUnderPrior();\n  for (uint32_t i=0; i<cld_->N(); ++i)\n    logJoint += thetas_[(cld_->z())(i)]->logLikelihood(*(cld_->x()),i);\n  return logJoint;\n};\n\n", "meta": {"hexsha": "0d68adb1f2e9877b7c393305541d78f3c313f55c", "size": 7003, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/dirMMcld.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/dpMM/dirMMcld.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dpMM/dirMMcld.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 29.4243697479, "max_line_length": 91, "alphanum_fraction": 0.6378694845, "num_tokens": 2160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.737158174177441, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4115753077382431}}
{"text": "\n#include \"lietorch_cpu.h\"\n#include <Eigen/Dense>\n\n#include <iostream>\n#include \"common.h\"\n#include \"dispatch.h\"\n\n#include \"so3.h\"\n#include \"rxso3.h\"\n#include \"se3.h\"\n#include \"sim3.h\"\n\n\ntemplate <typename Group, typename scalar_t>\nvoid exp_forward_kernel(const scalar_t* a_ptr, scalar_t* X_ptr, int batch_size) {\n    // exponential map forward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n    \n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Tangent a(a_ptr + i*Group::K);\n            Eigen::Map<Data>(X_ptr + i*Group::N) = Group::Exp(a).data();\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid exp_backward_kernel(const scalar_t* grad, const scalar_t* a_ptr, scalar_t* da, int batch_size) {\n    // exponential map backward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Grad = Eigen::Matrix<scalar_t,1,Group::K>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Tangent a(a_ptr + i*Group::K);\n            Grad dX(grad + i*Group::N);\n            Eigen::Map<Grad>(da + i*Group::K) = dX * Group::left_jacobian(a);\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid log_forward_kernel(const scalar_t* X_ptr, scalar_t* a_ptr, int batch_size) {\n    // logarithm map forward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Tangent a = Group(X_ptr + i*Group::N).Log();\n            Eigen::Map<Tangent>(a_ptr + i*Group::K) = a;\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid log_backward_kernel(const scalar_t* grad, const scalar_t* X_ptr, scalar_t* dX, int batch_size) {\n    // logarithm map backward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Grad = Eigen::Matrix<scalar_t,1,Group::K>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Tangent a = Group(X_ptr + i*Group::N).Log();\n            Grad da(grad + i*Group::K);\n            Eigen::Map<Grad>(dX + i*Group::N) = da * Group::left_jacobian_inverse(a);\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid inv_forward_kernel(const scalar_t* X_ptr, scalar_t* Y_ptr, int batch_size) {\n    // group inverse forward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group X(X_ptr + i*Group::N);\n            Eigen::Map<Data>(Y_ptr + i*Group::N) = X.inv().data();\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid inv_backward_kernel(const scalar_t* grad, const scalar_t* X_ptr, scalar_t *dX, int batch_size) {\n    // group inverse backward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Grad = Eigen::Matrix<scalar_t,1,Group::K>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group Y = Group(X_ptr + i*Group::N).inv();\n            Grad dY(grad + i*Group::N);\n            Eigen::Map<Grad>(dX + i*Group::N) = -dY * Y.Adj();\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid mul_forward_kernel(const scalar_t* X_ptr, const scalar_t* Y_ptr, scalar_t* Z_ptr, int batch_size) {\n    // group multiplication forward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group Z = Group(X_ptr + i*Group::N) * Group(Y_ptr + i*Group::N);\n            Eigen::Map<Data>(Z_ptr + i*Group::N) = Z.data();\n        }\n    });\n}\n\ntemplate <class Group, typename scalar_t>\nvoid mul_backward_kernel(const scalar_t* grad, const scalar_t* X_ptr, const scalar_t* Y_ptr, scalar_t* dX, scalar_t* dY, int batch_size) {\n    // group multiplication backward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Grad = Eigen::Matrix<scalar_t,1,Group::K>;\n    using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Grad dZ(grad + i*Group::N);\n            Group X(X_ptr + i*Group::N);        \n            Eigen::Map<Grad>(dX + i*Group::N) = dZ;\n            Eigen::Map<Grad>(dY + i*Group::N) = dZ * X.Adj();\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid adj_forward_kernel(const scalar_t* X_ptr, const scalar_t* a_ptr, scalar_t* b_ptr, int batch_size) {\n    // adjoint forward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group X(X_ptr + i*Group::N);\n            Tangent a(a_ptr + i*Group::K);\n            Eigen::Map<Tangent>(b_ptr + i*Group::K) = X.Adj(a);\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid adj_backward_kernel(const scalar_t* grad, const scalar_t* X_ptr, const scalar_t* a_ptr, scalar_t* dX, scalar_t* da, int batch_size) {\n    // adjoint backward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Grad = Eigen::Matrix<scalar_t,1,Group::K>;\n    using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group X(X_ptr + i*Group::N);\n            Grad db(grad + i*Group::K);\n\n            Tangent a(a_ptr + i*Group::K);\n            Tangent b = X.Adj() * a;\n\n            Eigen::Map<Grad>(da + i*Group::K) = db * X.Adj();\n            Eigen::Map<Grad>(dX + i*Group::N) = -db * Group::adj(b);\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid adjT_forward_kernel(const scalar_t* X_ptr, const scalar_t* a_ptr, scalar_t* b_ptr, int batch_size) {\n    // adjoint forward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group X(X_ptr + i*Group::N);\n            Tangent a(a_ptr + i*Group::K);\n            Eigen::Map<Tangent>(b_ptr + i*Group::K) = X.AdjT(a);\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid adjT_backward_kernel(const scalar_t* grad, const scalar_t* X_ptr, const scalar_t* a_ptr, scalar_t* dX, scalar_t* da, int batch_size) {\n    // adjoint backward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Grad = Eigen::Matrix<scalar_t,1,Group::K>;\n    using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group X(X_ptr + i*Group::N);        \n            Tangent db(grad + i*Group::K);\n            Grad a(a_ptr + i*Group::K);\n\n            Eigen::Map<Tangent>(da + i*Group::K) = X.Adj(db);\n            Eigen::Map<Grad>(dX + i*Group::N) = -a * Group::adj(X.Adj(db));\n        }\n    });\n}\n\n\ntemplate <typename Group, typename scalar_t>\nvoid act_forward_kernel(const scalar_t* X_ptr, const scalar_t* p_ptr, scalar_t* q_ptr, int batch_size) {\n    // action on point forward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n    using Point = Eigen::Matrix<scalar_t,3,1>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group X(X_ptr + i*Group::N);\n            Point p(p_ptr + i*3);\n            Eigen::Map<Point>(q_ptr + i*3) = X * p;\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid act_backward_kernel(const scalar_t* grad, const scalar_t* X_ptr, const scalar_t* p_ptr, scalar_t* dX, scalar_t* dp, int batch_size) {\n    // adjoint backward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Grad = Eigen::Matrix<scalar_t,1,Group::K>;\n    using Point = Eigen::Matrix<scalar_t,3,1>;\n    using PointGrad = Eigen::Matrix<scalar_t,1,3>;\n    using Transformation = Eigen::Matrix<scalar_t,4,4>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group X(X_ptr + i*Group::N);\n            Point p(p_ptr + i*3);\n            PointGrad dq(grad + i*3);\n\n            Eigen::Map<PointGrad>(dp + i*3) = dq * X.Matrix().template block<3,3>(0,0);\n            Eigen::Map<Grad>(dX + i*Group::N) = dq * Group::act_jacobian(X*p);\n        }\n    });\n}\n\n\n// template <typename Group, typename scalar_t>\n// void tovec_backward_kernel(const scalar_t* grad, const scalar_t* X_ptr, scalar_t* dX, int batch_size) {\n//     // group inverse forward kernel\n//     using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n//     using Grad = Eigen::Matrix<scalar_t,1,Group::N>;\n\n//     at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n//         for (int64_t i=start; i<end; i++) {\n//             Group X(X_ptr + i*Group::N);\n//             Grad g(grad + i*Group::N);\n//             Eigen::Map<Grad>(dX + i*Group::N) = g * X.vec_jacobian();\n//         }\n//     });\n// }\n\n// template <typename Group, typename scalar_t>\n// void fromvec_backward_kernel(const scalar_t* grad, const scalar_t* X_ptr, scalar_t* dX, int batch_size) {\n//     // group inverse forward kernel\n//     using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n//     using Grad = Eigen::Matrix<scalar_t,1,Group::N>;\n\n//     at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n//         for (int64_t i=start; i<end; i++) {\n//             Group X(X_ptr + i*Group::N);\n//             Grad g(grad + i*Group::N);\n//             Eigen::Map<Grad>(dX + i*Group::N) = g * X.vec_jacobian();\n//         }\n//     });\n// }\n\n\ntemplate <typename Group, typename scalar_t>\nvoid act4_forward_kernel(const scalar_t* X_ptr, const scalar_t* p_ptr, scalar_t* q_ptr, int batch_size) {\n    // action on homogeneous point forward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n    using Point = Eigen::Matrix<scalar_t,4,1>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group X(X_ptr + i*Group::N);\n            Point p(p_ptr + i*4);\n            Eigen::Map<Point>(q_ptr + i*4) = X.act4(p);\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid act4_backward_kernel(const scalar_t* grad, const scalar_t* X_ptr, const scalar_t* p_ptr, scalar_t* dX, scalar_t* dp, int batch_size) {\n    // action on homogeneous point backward kernel\n\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Grad = Eigen::Matrix<scalar_t,1,Group::K>;\n    using Point = Eigen::Matrix<scalar_t,4,1>;\n    using PointGrad = Eigen::Matrix<scalar_t,1,4>;\n    using Transformation = Eigen::Matrix<scalar_t,4,4>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group X(X_ptr + i*Group::N);\n            Point p(p_ptr + i*4);\n            PointGrad dq(grad + i*4);\n\n            Eigen::Map<PointGrad>(dp + i*4) = dq * X.Matrix4x4();\n            const Point q = X.act4(p);\n            Eigen::Map<Grad>(dX + i*Group::N) = dq * Group::act4_jacobian(q);\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid as_matrix_forward_kernel(const scalar_t* X_ptr, scalar_t* T_ptr, int batch_size) {\n    // group inverse forward kernel\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n    using Matrix4 = Eigen::Matrix<scalar_t,4,4,Eigen::RowMajor>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group X(X_ptr + i*Group::N);\n            Eigen::Map<Matrix4>(T_ptr + i*16) = X.Matrix4x4();\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid orthogonal_projector_kernel(const scalar_t* X_ptr, scalar_t* P_ptr, int batch_size) {\n    // group inverse forward kernel\n    using Proj = Eigen::Matrix<scalar_t,Group::N,Group::N,Eigen::RowMajor>;\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group X(X_ptr + i*Group::N);\n            Eigen::Map<Proj>(P_ptr + i*Group::N*Group::N) = X.orthogonal_projector();\n        }\n    });\n}\n\ntemplate <typename Group, typename scalar_t>\nvoid jleft_forward_kernel(const scalar_t* X_ptr, const scalar_t* a_ptr, scalar_t* b_ptr, int batch_size) {\n    // left-jacobian inverse action\n    using Tangent = Eigen::Matrix<scalar_t,Group::K,1>;\n    using Data = Eigen::Matrix<scalar_t,Group::N,1>;\n\n    at::parallel_for(0, batch_size, 1, [&](int64_t start, int64_t end) {\n        for (int64_t i=start; i<end; i++) {\n            Group X(X_ptr + i*Group::N);\n            Tangent a(a_ptr + i*Group::K);\n            Tangent b = Group::left_jacobian_inverse(X.Log()) * a;\n            Eigen::Map<Tangent>(b_ptr + i*Group::K) = b;\n        }\n    });\n}\n\n// unary operations\n\ntorch::Tensor exp_forward_cpu(int group_id, torch::Tensor a) {\n    int batch_size = a.size(0);\n    torch::Tensor X;\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, a.type(), \"exp_forward_kernel\", ([&] {\n        X = torch::zeros({batch_size, group_t::N}, a.options());\n        exp_forward_kernel<group_t, scalar_t>(\n            a.data_ptr<scalar_t>(), \n            X.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return X;\n}\n\nstd::vector<torch::Tensor> exp_backward_cpu(int group_id, torch::Tensor grad, torch::Tensor a) {\n    int batch_size = a.size(0);\n    torch::Tensor da = torch::zeros(a.sizes(), grad.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, a.type(), \"exp_backward_kernel\", ([&] {\n        exp_backward_kernel<group_t, scalar_t>(\n            grad.data_ptr<scalar_t>(), \n            a.data_ptr<scalar_t>(), \n            da.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return {da};\n}\n\ntorch::Tensor log_forward_cpu(int group_id, torch::Tensor X) {\n    int batch_size = X.size(0);\n    torch::Tensor a;\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"log_forward_kernel\", ([&] {\n        a = torch::zeros({batch_size, group_t::K}, X.options());\n        log_forward_kernel<group_t, scalar_t>(\n            X.data_ptr<scalar_t>(), \n            a.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return a;\n}\n\nstd::vector<torch::Tensor> log_backward_cpu(int group_id, torch::Tensor grad, torch::Tensor X) {\n    int batch_size = X.size(0);\n    torch::Tensor dX = torch::zeros(X.sizes(), grad.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"log_backward_kernel\", ([&] {\n        log_backward_kernel<group_t, scalar_t>(\n            grad.data_ptr<scalar_t>(), \n            X.data_ptr<scalar_t>(), \n            dX.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return {dX};\n}\n\ntorch::Tensor inv_forward_cpu(int group_id, torch::Tensor X) {\n    int batch_size = X.size(0);\n    torch::Tensor Y = torch::zeros_like(X);\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"inv_forward_kernel\", ([&] {\n        inv_forward_kernel<group_t, scalar_t>(\n            X.data_ptr<scalar_t>(), \n            Y.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return Y;\n}\n\nstd::vector<torch::Tensor> inv_backward_cpu(int group_id, torch::Tensor grad, torch::Tensor X) {\n    int batch_size = X.size(0);\n    torch::Tensor dX = torch::zeros(X.sizes(), grad.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"inv_backward_kernel\", ([&] {\n        inv_backward_kernel<group_t, scalar_t>(\n            grad.data_ptr<scalar_t>(), \n            X.data_ptr<scalar_t>(), \n            dX.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return {dX};\n}\n\n// binary operations\ntorch::Tensor mul_forward_cpu(int group_id, torch::Tensor X, torch::Tensor Y) {\n    int batch_size = X.size(0);\n    torch::Tensor Z = torch::zeros_like(X);\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"mul_forward_kernel\", ([&] {\n        mul_forward_kernel<group_t, scalar_t>(\n            X.data_ptr<scalar_t>(), \n            Y.data_ptr<scalar_t>(), \n            Z.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return Z;\n}\n\nstd::vector<torch::Tensor> mul_backward_cpu(int group_id, torch::Tensor grad, torch::Tensor X, torch::Tensor Y) {\n    int batch_size = X.size(0);\n    torch::Tensor dX = torch::zeros(X.sizes(), grad.options());\n    torch::Tensor dY = torch::zeros(Y.sizes(), grad.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"mul_backward_kernel\", ([&] {\n        mul_backward_kernel<group_t, scalar_t>(\n            grad.data_ptr<scalar_t>(), \n            X.data_ptr<scalar_t>(), \n            Y.data_ptr<scalar_t>(), \n            dX.data_ptr<scalar_t>(), \n            dY.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return {dX, dY};\n}\n\ntorch::Tensor adj_forward_cpu(int group_id, torch::Tensor X, torch::Tensor a) {\n    int batch_size = X.size(0);\n    torch::Tensor b = torch::zeros(a.sizes(), a.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"adj_forward_kernel\", ([&] {\n        adj_forward_kernel<group_t, scalar_t>(\n            X.data_ptr<scalar_t>(), \n            a.data_ptr<scalar_t>(), \n            b.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return b;\n}\n\nstd::vector<torch::Tensor> adj_backward_cpu(int group_id, torch::Tensor grad, torch::Tensor X, torch::Tensor a) {\n    int batch_size = X.size(0);\n    torch::Tensor dX = torch::zeros(X.sizes(), grad.options());\n    torch::Tensor da = torch::zeros(a.sizes(), grad.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"adj_backward_kernel\", ([&] {\n        adj_backward_kernel<group_t, scalar_t>(\n            grad.data_ptr<scalar_t>(), \n            X.data_ptr<scalar_t>(), \n            a.data_ptr<scalar_t>(), \n            dX.data_ptr<scalar_t>(), \n            da.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return {dX, da};\n}\n\n\ntorch::Tensor adjT_forward_cpu(int group_id, torch::Tensor X, torch::Tensor a) {\n    int batch_size = X.size(0);\n    torch::Tensor b = torch::zeros(a.sizes(), a.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"adjT_forward_kernel\", ([&] {\n        adjT_forward_kernel<group_t, scalar_t>(\n            X.data_ptr<scalar_t>(), \n            a.data_ptr<scalar_t>(), \n            b.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return b;\n}\n\nstd::vector<torch::Tensor> adjT_backward_cpu(int group_id, torch::Tensor grad, torch::Tensor X, torch::Tensor a) {\n    int batch_size = X.size(0);\n    torch::Tensor dX = torch::zeros(X.sizes(), grad.options());\n    torch::Tensor da = torch::zeros(a.sizes(), grad.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"adjT_backward_kernel\", ([&] {\n        adjT_backward_kernel<group_t, scalar_t>(\n            grad.data_ptr<scalar_t>(), \n            X.data_ptr<scalar_t>(), \n            a.data_ptr<scalar_t>(), \n            dX.data_ptr<scalar_t>(), \n            da.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return {dX, da};\n}\n\n\ntorch::Tensor act_forward_cpu(int group_id, torch::Tensor X, torch::Tensor p) {\n    int batch_size = X.size(0);\n    torch::Tensor q = torch::zeros(p.sizes(), p.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"act_forward_kernel\", ([&] {\n        act_forward_kernel<group_t, scalar_t>(\n            X.data_ptr<scalar_t>(), \n            p.data_ptr<scalar_t>(), \n            q.data_ptr<scalar_t>(),\n            batch_size);\n    }));\n\n    return q;\n}\n\nstd::vector<torch::Tensor> act_backward_cpu(int group_id, torch::Tensor grad, torch::Tensor X, torch::Tensor p) {\n    int batch_size = X.size(0);\n    torch::Tensor dX = torch::zeros(X.sizes(), grad.options());\n    torch::Tensor dp = torch::zeros(p.sizes(), grad.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"act_backward_kernel\", ([&] {\n        act_backward_kernel<group_t, scalar_t>(\n            grad.data_ptr<scalar_t>(), \n            X.data_ptr<scalar_t>(), \n            p.data_ptr<scalar_t>(), \n            dX.data_ptr<scalar_t>(), \n            dp.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return {dX, dp};\n}\n\n\ntorch::Tensor act4_forward_cpu(int group_id, torch::Tensor X, torch::Tensor p) {\n    int batch_size = X.size(0);\n    torch::Tensor q = torch::zeros(p.sizes(), p.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"act4_forward_kernel\", ([&] {\n        act4_forward_kernel<group_t, scalar_t>(\n            X.data_ptr<scalar_t>(), \n            p.data_ptr<scalar_t>(), \n            q.data_ptr<scalar_t>(),\n            batch_size);\n    }));\n\n    return q;\n}\n\nstd::vector<torch::Tensor> act4_backward_cpu(int group_id, torch::Tensor grad, torch::Tensor X, torch::Tensor p) {\n    int batch_size = X.size(0);\n    torch::Tensor dX = torch::zeros(X.sizes(), grad.options());\n    torch::Tensor dp = torch::zeros(p.sizes(), grad.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"act4_backward_kernel\", ([&] {\n        act4_backward_kernel<group_t, scalar_t>(\n            grad.data_ptr<scalar_t>(), \n            X.data_ptr<scalar_t>(), \n            p.data_ptr<scalar_t>(), \n            dX.data_ptr<scalar_t>(), \n            dp.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return {dX, dp};\n}\n\n\ntorch::Tensor as_matrix_forward_cpu(int group_id, torch::Tensor X) {\n    int batch_size = X.size(0);\n    torch::Tensor T4x4 = torch::zeros({X.size(0), 4, 4}, X.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"as_matrix_forward_kernel\", ([&] {\n        as_matrix_forward_kernel<group_t, scalar_t>(\n            X.data_ptr<scalar_t>(), \n            T4x4.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return T4x4;\n}\n\n\ntorch::Tensor orthogonal_projector_cpu(int group_id, torch::Tensor X) {\n    int batch_size = X.size(0);\n    torch::Tensor P;\n    \n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"orthogonal_projector_kernel\", ([&] {\n        P = torch::zeros({X.size(0), group_t::N, group_t::N}, X.options());\n        orthogonal_projector_kernel<group_t, scalar_t>(X.data_ptr<scalar_t>(), P.data_ptr<scalar_t>(), batch_size);\n    }));\n\n    return P;\n}\n\n\n\ntorch::Tensor jleft_forward_cpu(int group_id, torch::Tensor X, torch::Tensor a) {\n    int batch_size = X.size(0);\n    torch::Tensor b = torch::zeros(a.sizes(), a.options());\n\n    DISPATCH_GROUP_AND_FLOATING_TYPES(group_id, X.type(), \"jleft_forward_kernel\", ([&] {\n        jleft_forward_kernel<group_t, scalar_t>(\n            X.data_ptr<scalar_t>(), \n            a.data_ptr<scalar_t>(), \n            b.data_ptr<scalar_t>(), \n            batch_size);\n    }));\n\n    return b;\n}", "meta": {"hexsha": "3a388a12d09f294bd333b2197447d27a3b5a336b", "size": 23475, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lietorch/src/lietorch_cpu.cpp", "max_stars_repo_name": "mli0603/lietorch", "max_stars_repo_head_hexsha": "9d8130bec3d01825591b505808bedbb0dffd4b72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 360.0, "max_stars_repo_stars_event_min_datetime": "2021-03-23T06:00:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:30:32.000Z", "max_issues_repo_path": "lietorch/src/lietorch_cpu.cpp", "max_issues_repo_name": "mli0603/lietorch", "max_issues_repo_head_hexsha": "9d8130bec3d01825591b505808bedbb0dffd4b72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2021-04-09T15:23:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:28:24.000Z", "max_forks_repo_path": "lietorch/src/lietorch_cpu.cpp", "max_forks_repo_name": "mli0603/lietorch", "max_forks_repo_head_hexsha": "9d8130bec3d01825591b505808bedbb0dffd4b72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2021-03-25T13:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-09T02:37:28.000Z", "avg_line_length": 35.7305936073, "max_line_length": 139, "alphanum_fraction": 0.6080511182, "num_tokens": 6600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.41156100401999834}}
{"text": "#include \"urrp.h\"\n#include <boost/math/special_functions/digamma.hpp>\nusing namespace std;\n\ninline double square(double x)\n{\n  return x * x;\n}\n\ninline double digamma(double x)\n{\n  if(x==0.0)\n  {\n    return 0.0;\n  } else {\n    return boost::math::digamma(x);\n  }\n}\n\nvoid URRP::init_model()\n{\n  for(vector<rating*>::iterator it=trainratings.begin(); it != trainratings.end(); it++)\n  {\n    int user = (*it)->user;\n    int item = (*it)->item;\n    int rating = (*it)->value;\n    vector< pair<int,int> >* words = &((*it)->words);\n\n    //init attitude and topic\n    int attitude = rand() % K;\n    (*it)->attitude = attitude;\n    (*muk)[user][attitude]++;\n    (*ckvs)[attitude][item][rating]++;\n    (*mu)[user]++;\n    (*ckv)[attitude][item]++;\n\n    int topic = rand() % K;\n    for(vector< pair<int,int> >::iterator it2=words->begin(); it2 != words->end(); it2++)\n    {\n      (*it2).second = topic;\n      (*nuk)[user][topic]++;\n      (*nkw)[topic][(*it2).first]++;\n      (*nu)[user]++;\n      (*nk)[topic]++;\n      topic = rand() % K;\n    }\n  }\n}\n\nvoid URRP::sample_attitudes(bool with_topic)\n{\n  double* p = new double[K];\n  for(vector<rating*>::iterator it=trainratings.begin(); it != trainratings.end(); it++)\n  {\n    int user = (*it)->user;\n    int item = (*it)->item;\n    int rating = (*it)->value;\n\n    //delete related attitude and topic for this rating;\n    int current_attitude = (*it)->attitude;\n    (*muk)[user][current_attitude]--;\n    (*ckvs)[current_attitude][item][rating]--;\n    (*mu)[user]--;\n    (*ckv)[current_attitude][item]--;\n\n    int k=0;\n    //#pragma omp parallel for\n    for(k=0; k<K; k++)\n    {\n      if(with_topic)\n        p[k] = ((*nuk)[user][k] + (*muk)[user][k] + alpha[k]) / ((*nu)[user] + (*mu)[user] + sum_alpha) * (((*ckvs)[k][item][rating] + lambda[rating]) / ((*ckv)[k][item] + sum_lambda));\n      else\n        p[k] = ((*muk)[user][k] + alpha[k]) / ((*mu)[user] + sum_alpha) * (((*ckvs)[k][item][rating] + lambda[rating]) / ((*ckv)[k][item] + sum_lambda));\n    }\n\n    for(k=1; k<K; k++)\n      p[k] += p[k-1];\n\n    double randdouble = (rand() * 1.0 / RAND_MAX) * p[K-1];\n    for(k=0; k<K; k++)\n    {\n      if(randdouble <= p[k])\n      {\n        break;\n      }\n    }\n    (*it)->attitude = k;\n    (*muk)[user][k]++;\n    (*ckvs)[k][item][rating]++;\n    (*mu)[user]++;\n    (*ckv)[k][item]++;\n  }\n  delete[] p;\n}\n\nvoid URRP::sample_topics(bool with_attitude)\n{\n  double* p = new double[K];\n  for(vector<rating*>::iterator it=trainratings.begin(); it != trainratings.end(); it++)\n  {\n    int user = (*it)->user;\n    vector< pair<int,int> >* words = &((*it)->words);\n\n    for(vector< pair<int,int> >::iterator it2=words->begin(); it2 != words->end(); it2++)\n    {\n      int w = (*it2).first;\n      int current_topic = (*it2).second;\n      (*nuk)[user][current_topic]--;\n      (*nkw)[current_topic][w]--;\n      (*nu)[user]--;\n      (*nk)[current_topic]--;\n      int k=0;\n      for(k=0; k<K; k++)\n      {\n        if(with_attitude)\n          p[k] = (((*nuk)[user][k] + (*muk)[user][k] + alpha[k]) / ((*nu)[user] + (*mu)[user] + sum_alpha) * (((*nkw)[k][w] + beta[w]) / ((*nk)[k] + sum_beta)));\n        else\n          p[k] = (((*nuk)[user][k] + alpha[k]) / ((*nu)[user] + sum_alpha) * (((*nkw)[k][w] + beta[w]) / ((*nk)[k] + sum_beta)));\n      }\n      for(k=1; k<K; k++)\n        p[k] += p[k-1];\n\n      double randdouble = (rand() * 1.0 / RAND_MAX) * p[K-1];\n      for(k=0; k<K; k++)\n      {\n        if(randdouble <= p[k])\n        {\n          break;\n        }\n      }\n      (*it2).second = k;\n      (*nuk)[user][k]++;\n      (*nkw)[k][w]++;\n      (*nu)[user]++;\n      (*nk)[k]++;\n    }\n  }\n  delete[] p;\n}\n\nvoid URRP::readout_topic_theta(bool with_attitude)\n{\n  int u,k;\n#pragma omp parallel for collapse(2)\n  for(u=0; u<nUsers; u++)\n    for(k=0; k<K; k++)\n      if(with_attitude)\n        (*theta)[u][k] = ((*nuk)[u][k] + (*muk)[u][k] + alpha[k]) / ((*nu)[u] + (*mu)[u] + sum_alpha);\n      else\n        (*theta)[u][k] = ((*nuk)[u][k] + alpha[k]) / ((*nu)[u] + sum_alpha);\n}\n\nvoid URRP::readout_attitude_theta(bool with_topic)\n{\n  int u,k;\n#pragma omp parallel for collapse(2)\n  for(u=0; u<nUsers; u++)\n    for(k=0; k<K; k++)\n      if(with_topic)\n        (*theta)[u][k] = ((*nuk)[u][k] + (*muk)[u][k] + alpha[k]) / ((*nu)[u] + (*mu)[u] + sum_alpha);\n      else\n        (*theta)[u][k] = ((*muk)[u][k] + alpha[k]) / ((*mu)[u] + sum_alpha);\n}\n\nvoid URRP::readout_phi()\n{\n  int k,w;\n#pragma omp parallel for collapse(2)\n  for(k=0; k<K; k++)\n    for(w=0; w<nWords; w++)\n      (*phi)[k][w] = ((*nkw)[k][w] + beta[w]) / ((*nk)[k] + sum_beta);\n}\n\nvoid URRP::readout_xi()\n{\n  int v,k,s;\n#pragma omp parallel for collapse(3)\n  for(k=0; k<K; k++)\n    for(v=0; v<nItems; v++)\n      for(s=0; s<S; s++)\n        (*xi)[k][v][s] = ((*ckvs)[k][v][s] + lambda[s]) / ((*ckv)[k][v] + sum_lambda);\n}\n\nvoid URRP::update_alpha_by_topic()\n{\n  int k,u;\n  double ak, numerator, denominator;\n  //update alpha\n  for (k = 0; k < K; k++) {\n    ak = alpha[k];\n    numerator = 0, denominator = 0;\n    #pragma omp parallel for reduction (+:numerator,denominator)\n    for (u = 0; u < nUsers; u++) {\n      numerator += digamma((*nuk)[u][k] + ak) - digamma(ak);\n      denominator += digamma((*nu)[u] + sum_alpha) - digamma(sum_alpha);\n      //numerator += digamma((*nuk)[u][k] + (*muk)[u][k] + ak) - digamma(ak);\n      //denominator += digamma(get_nu(u) + get_mu(u) + sum_alpha) - digamma(sum_alpha);\n    }\n    if (numerator != 0)\n      alpha[k] = ak * (numerator / denominator);\n  }\n  sum_alpha = 0;\n  for (k = 0; k < K; k++)\n  {\n    sum_alpha += alpha[k];\n  }\n}\n\nvoid URRP::update_alpha(bool with_topic)\n{\n  int k,u;\n  double ak, numerator, denominator;\n  //update alpha\n  for (k = 0; k < K; k++) {\n    ak = alpha[k];\n    numerator = 0, denominator = 0;\n    #pragma omp parallel for reduction (+:numerator,denominator)\n    for (u = 0; u < nUsers; u++) {\n      if (with_topic)\n      {\n        numerator += digamma((*nuk)[u][k] + (*muk)[u][k] + ak) - digamma(ak);\n        denominator += digamma((*nu)[u] + (*mu)[u] + sum_alpha) - digamma(sum_alpha);\n      }\n      else\n      {\n        numerator += digamma((*muk)[u][k] + ak) - digamma(ak);\n        denominator += digamma((*mu)[u] + sum_alpha) - digamma(sum_alpha);\n      }\n    }\n    if (numerator != 0)\n      alpha[k] = ak * (numerator / denominator);\n  }\n  sum_alpha = 0;\n  for (k = 0; k < K; k++)\n  {\n    sum_alpha += alpha[k];\n  }\n}\n\nvoid URRP::update_beta()\n{\n  int k,w;\n  double betaw, numerator, denominator;\n  //update beta\n  for (w = 0; w < nWords; w++) {\n    betaw = beta[w];\n    numerator = 0, denominator = 0;\n    //#pragma omp parallel for reduction (+:numerator,denominator)\n    for (k = 0; k < K; k++) {\n      numerator += digamma((*nkw)[k][w] + betaw) - digamma(betaw);\n      denominator += digamma((*nk)[k] + sum_beta) - digamma(sum_beta);\n    }\n    if (numerator != 0)\n      beta[w] = betaw * (numerator / denominator);\n  }\n  double tmp_sum_beta = 0;\n  //#pragma omp parallel for reduction (+:tmp_sum_beta)\n  for (w = 0; w < nWords; w++)\n  {\n    tmp_sum_beta += beta[w];\n  }\n  sum_beta = tmp_sum_beta;\n\n}\n\nvoid URRP::update_lambda()\n{\n  int v,k,s;\n  double lambdas, numerator, denominator;\n  //update lambda\n  for (s = 0; s < S; s++) {\n    lambdas = lambda[s];\n    numerator = 0, denominator = 0;\n    #pragma omp parallel for collapse(2) reduction (+:numerator,denominator)\n    for(k=0; k<K; k++)\n      for(v=0; v<nItems; v++)\n      {\n        numerator += digamma((*ckvs)[k][v][s] + lambdas) - digamma(lambdas);\n        denominator += digamma((*ckv)[k][v] + sum_lambda) - digamma(sum_lambda);\n      }\n    if (numerator != 0)\n      lambda[s] = lambdas * (numerator / denominator);\n  }\n  sum_lambda = 0;\n  for (s = 0; s < S; s++)\n  {\n    sum_lambda += lambda[s];\n  }\n}\n\nvoid URRP::evaluate(int iter)\n{\n  double train_err = 0.0;\n  double validate_err = 0.0;\n  double test_err = 0.0;\n  double test_ste = 0.0;\n  size_t i;\n\n  #pragma omp parallel for reduction (+:validate_err)\n  for(i=0; i<trainratings.size(); i++)\n  {\n    train_err += square(predict_with_expect(trainratings[i]) - trainratings[i]->value - 1);\n  }\n\n  #pragma omp parallel for reduction (+:validate_err)\n  for(i=0; i<validratings.size(); i++)\n  {\n    validate_err += square(predict_with_expect(validratings[i]) - validratings[i]->value - 1);\n  }\n\n  #pragma omp parallel for reduction (+:test_err,test_ste)\n  for(i=0; i<testratings.size(); i++)\n  {\n    double err = square(predict_with_expect(testratings[i]) - testratings[i]->value - 1);\n    test_err += err;\n    test_ste += err*err;\n  }\n  train_err /= trainratings.size();\n  validate_err /= validratings.size();\n  test_err /= testratings.size();\n  test_ste /= testratings.size();\n  test_ste = sqrt((test_ste-test_err*test_err)/testratings.size());\n\n  if(test_err < current_best)\n  {\n    current_best = test_err;\n    current_best_ste = test_ste;\n  }\n\n  double delta = validate_err - prev_mse;\n  printf(\"\\nRecommend: Iter %d, Train MSE: %.4lf, Validation MSE: %.4lf, Test MSE: %.4lf (%.2lf), validate_mse_delta: %.4lf\\n\", iter, train_err, validate_err, test_err, test_ste, delta);\n  printf(\"\\nCurrent best MSE:\\t%.4lf (%.2lf)\\n\", current_best, current_best_ste);\n  prev_mse = validate_err;\n  fflush(stdout);\n}\n\n/// Train a model\nvoid URRP::train()\n{\n  init_model();\n  readout_attitude_theta(false);\n  readout_xi();\n  evaluate(0);\n  // learn topic distribution by lda\n  for(int i=1; i<=burn_in; i++)\n  {\n    sample_topics(false);\n    if (i % 10 == 0)\n    {\n      printf(\"LDA stage: iter %d\\n\", i);\n      fflush(stdout);\n    }\n  }\n  readout_topic_theta(false);\n  readout_phi();\n  topic_words();\n  for (int iter = 0; iter <= max_iter; iter++) {\n    // sample topic and attitude for all words and ratings\n    sample_attitudes(false);\n    sample_topics(false);\n    // update hyper-parameters\n    update_alpha(true);\n    update_beta();\n    update_lambda();\n    // get statistics after burn-in\n    if (iter % sample_lag == 0)\n    {\n      readout_attitude_theta(false);\n      readout_phi();\n      readout_xi();\n      evaluate(iter);\n    }\n  }\n  topic_words();\n}\n\nbool word_prob_com(pair<int, double> p1, pair<int, double> p2)\n{\n  return p1.second > p2.second;\n}\n\nvoid URRP::topic_words()\n{\n  map<int, string> * id2word = &(corp->id2word);\n  for(int k=0; k<K; k++)\n  {\n    vector< pair<int, double> > topic_words;\n    for(int w=0; w<nWords; w++)\n    {\n      topic_words.push_back(make_pair(w, (*phi)[k][w]));\n    }\n    sort(topic_words.begin(), topic_words.end(), word_prob_com);\n    printf(\"\\nTopic %d:\", k+1);\n    for(int i=0; i<10; i++)\n    {\n      printf(\" %s(%.4lf)\", (*id2word)[topic_words[i].first].c_str(), (*phi)[k][topic_words[i].first]);\n    }\n  }\n  printf(\"\\n\");\n  fflush(stdout);\n}\n\n// Predict a particular rating given the current parameter values\ndouble URRP::predict_with_expect(rating* vi)\n{\n  int user = vi->user;\n  int item = vi->item;\n  double pred = 0.0;\n  double ps = 0.0;\n  for(int s=0; s<S; s++)\n  {\n    ps = 0.0;\n    for(int k=0; k<K; k++)\n    {\n      ps += (*theta)[user][k] * (*xi)[k][item][s];\n    }\n    pred += ps * (s+1);\n  }\n  return pred;\n}\n\n// Predict a particular rating given the current parameter values\ndouble URRP::predict_with_most_prob(rating* vi)\n{\n  int user = vi->user;\n  int item = vi->item;\n  double pred = 0.0;\n  double most_prob = 0.0;\n  double ps = 0.0;\n  for(int s=0; s<S; s++)\n  {\n    ps = 0.0;\n    for(int k=0; k<K; k++)\n    {\n      ps += (*theta)[user][k] * (*xi)[k][item][s];\n    }\n    if(ps > most_prob)\n    {\n      pred = s+1;\n      most_prob = ps;\n    }\n  }\n  return pred;\n}\n", "meta": {"hexsha": "8f8f4ef6e84849039e6275398edde0a312867db0", "size": 11476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "baseline/urrp/urrp.cpp", "max_stars_repo_name": "bit-jmm/cctr", "max_stars_repo_head_hexsha": "780f9e6824804a273829bdb28baa888bcd8e2bc5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "baseline/urrp/urrp.cpp", "max_issues_repo_name": "bit-jmm/cctr", "max_issues_repo_head_hexsha": "780f9e6824804a273829bdb28baa888bcd8e2bc5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "baseline/urrp/urrp.cpp", "max_forks_repo_name": "bit-jmm/cctr", "max_forks_repo_head_hexsha": "780f9e6824804a273829bdb28baa888bcd8e2bc5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7887640449, "max_line_length": 186, "alphanum_fraction": 0.5485360753, "num_tokens": 3717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.4115609941186594}}
{"text": "#include \"policy.hpp\"\n#include \"helpers.hpp\"\n#include <ctime>\n#include <sys/time.h>\n#include <boost/math/distributions.hpp>\n#include <stdlib.h>\n\ntemplate <class Policy>\ndouble timePolicy(Policy& pol, int arms, int horizon, bool gaussian, RandUnif& urandom, RandNorm& nrandom)\n{\n\n  int trials = 1;\n  static double mean_rewards[] = {0.6, 0.1, 0.7, 0.45, 0.43, 0.32, 0.8, 0.93, 0.4, 0.5};  \n  clock_t timing = clock();\n  for (int tr= 1; tr <= trials; ++tr)\n  {\n    Table rewards(arms, vector<double>(horizon, 0));\n    for (int a = 0; a < arms; ++a)\n    {\n      double mu = mean_rewards[a];\n      for (int t = 0; t < horizon; ++t)\n      {\n        rewards[a][t] = gaussian ? (mu + nrandom()) : (urandom() < mu ? 1 : 0);\n      }\n    }\n    for (int t = 1; t <= horizon; ++t)\n    {\n      int arm = pol.choosearm(t);\n\n      pol.totalsampled[arm] += 1;\n      double outcome = rewards[arm][pol.sample_index[arm]];\n      pol.totalrewards[arm] += outcome;\n      pol.sample_index[arm]++;\n      pol.totalscore += outcome;\n    }\n  }\n  timing = clock() - timing;\n  return ((double)timing)/CLOCKS_PER_SEC;\n}\n\nint main(int argc, char** argv)\n{\n  timeval tv;\n  gettimeofday(&tv,NULL);\n\n  boost::mt19937 seed(tv.tv_sec);\n  boost::uniform_real<> dist(0.0,1.0);\n  boost::normal_distribution<> normdist(0.0,1.0);\n  boost::uniform_int<> idist(1,1000000);\n  RandomSampleHelper bh(tv.tv_sec);\n  RandUnif urandom(seed,dist);\n  RandNorm nrandom(seed,normdist);\n  int horizon = 1000;\n  int arms = 10;\n\n  vector<double> uniforms(horizon, 0);\n  IDSPolicy idsBer(horizon, uniforms,  arms, false, 1000);\n  IDSPolicy idsGauss(horizon, uniforms, arms, true, 1000);\n  InterestingPolicy nitpBer(horizon, arms, 1, 0, false);\n  InterestingPolicy nitpBer3(horizon, arms, 1, 0, false, 3);\n  InterestingPolicy nitpGauss(horizon, arms, 1, 0, true);\n  \n  ThompsonPolicy tompBer(bh, horizon, arms, false);\n  ThompsonPolicy tompGauss(bh, horizon, arms, true);\n  BayesUCBPolicy bucbBer(horizon, arms, false);\n  BayesUCBPolicy bucbGauss(horizon, arms, true);\n\n  cout << \"TOM:\" << timePolicy(tompBer, arms, horizon, false, urandom, nrandom) << endl;\n  cout << \"BUCB:\" << timePolicy(bucbBer, arms, horizon, false, urandom, nrandom) << endl;\n  cout << \"IDS:\" << timePolicy(idsBer, arms, horizon, false, urandom, nrandom) << endl;\n  cout << \"OURS-1:\" << timePolicy(nitpBer, arms, horizon, false, urandom, nrandom) << endl;\n  cout << \"OURS-3:\" <<  timePolicy(nitpBer3, arms, horizon, false, urandom, nrandom) << endl;\n  \n  cout << endl << \"Gaussian!\" << endl;\n  cout << \"TOM:\" << timePolicy(tompGauss, arms, horizon, true, urandom, nrandom) << endl;\n  cout << \"BUCB:\" << timePolicy(bucbGauss, arms, horizon, true, urandom, nrandom) << endl;\n  cout << \"IDS:\" << timePolicy(idsGauss, arms, horizon, true, urandom, nrandom) << endl;\n  cout << \"OURS-1:\" << timePolicy(nitpGauss, arms, horizon, true, urandom, nrandom) << endl;\n}\n", "meta": {"hexsha": "4e101dbf4b95d602852b7478426d8a891395e9c0", "size": 2871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/time_policies.cpp", "max_stars_repo_name": "gutin/FastGittins", "max_stars_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T12:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T16:14:34.000Z", "max_issues_repo_path": "cpp/time_policies.cpp", "max_issues_repo_name": "gutin/FastGittins", "max_issues_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/time_policies.cpp", "max_forks_repo_name": "gutin/FastGittins", "max_forks_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T02:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T02:40:39.000Z", "avg_line_length": 35.8875, "max_line_length": 106, "alphanum_fraction": 0.6450714037, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.41153362068002475}}
{"text": "#include <iostream>\n#include <fstream>\n#include <Eigen/Eigen>\n//include the bie header files\n#include \"material.hh\"\n#include \"precomputed_kernel.hh\"\n#include \"bimat_interface.hh\"\n#include \"infinite_boundary.hh\"\n//include the fem header files\n#include \"mesh_Generated_multi_faults.hpp\"\n#include \"bcdof.hpp\"\n#include \"bcdof_ptr.hpp\"\n#include \"cal_ke.hpp\"\n#include \"cal_fe_global_const_ke.hpp\"\n#include \"mapglobal.hpp\"\n#include \"Slip_Weakening_reg.hpp\"\n#include \"Slip_Weakening.hpp\"\n#include \"cal_slip_sliprate.hpp\"\n#include \"time_advance.hpp\"\n#include \"BIE_correct.hpp\"\n#include \"igl/list_to_matrix.h\"\n#include <omp.h>\nusing namespace Eigen;\nusing namespace std;\n\ntypedef Eigen::Matrix<int, -1, -1,RowMajor> MatrixXi_rm;\n\nvoid read_matrix(std::string fileName, Eigen::MatrixXd &outputMat);\n\ndouble time_fem=0;\ndouble time_bie;\nint main() {\n     time_fem = 0.0;\n    // Domain Size\n    double x_min = -30e3;\n    double x_max = 30e3;\n    double y_min = -0.5e3;\n    double y_max = 0.5e3;\n    int dim = 2.0;\n    double dx = 3.125;\n    double dy = 3.125;\n    int nx_el = (x_max-x_min)/dx;\n    int ny = (y_max-y_min)/dy;\n    MatrixXd Node = MatrixXd::Zero((nx_el+1)*(ny+1),2);\n    MatrixXi_rm Element(nx_el*ny,4); Element.setZero();\n    ArrayXi BIE_top_surf_nodes = ArrayXi::Zero((nx_el+1),1);\n    ArrayXi BIE_bot_surf_nodes = ArrayXi::Zero((nx_el+1),1);\n    int num_faults = 5;\n    // Mesh\n    // Position of the fault : y_pos, x_left, x_right\n    MatrixXd fault_pos(num_faults,3);\n    fault_pos << 0.0,  -30.0e3 ,30.0e3,\n                 0.3e3, 3.0e3, 30.0e3,\n                 0.3e3, -30.0e3, -3.0e3,\n                 -0.3e3, 3.0e3, 30.0e3,\n                 -0.3e3, -30.0e3, -3.0e3;\n\n//    MatrixXd fault_pos;\n//    read_matrix(\"fault_pos.txt\", fault_pos);\n//    int num_faults = fault_pos.rows();\n    cout<<\"test_mat=\"<<\"\\n\"<<fault_pos<<\"\\n\"<<\"rows=\"<<fault_pos.rows()<<\"\\n\";\n    std::vector<std::vector<int>> fault_nodes(num_faults*2);\n    mesh_Generated_multi_faults(x_min,x_max,y_min,y_max,dx,dy,nx_el,ny,Node, Element,BIE_top_surf_nodes, BIE_bot_surf_nodes,fault_pos, fault_nodes);\n    \n    int n_nodes = Node.rows();\n    int n_el = Element.rows();\n    int Ndofn = 2;\n    int Nnel = Element.cols();\n    // Material\n    double density = 2670.0;\n    double v_s =3.464e3;\n    double v_p = 6.0e3;\n    double G= pow(v_s,2)*density;\n    double Lambda = pow(v_p,2)*density-2.0*G;\n    double E  = G*(3.0*Lambda+2.0*G)/(Lambda+G);\n    double nu = Lambda/(2.0*(Lambda+G));\n    // Time\n    double alpha = 0.4;\n    double dt = alpha*dx/v_p;\n    dt = 0.0002;\n    // Reyleigh Damping\n    double beta =0.1;\n    double q = beta*dt;\n    double time_run = 6.0;\n    int numt = time_run/dt;\n    //numt = 1;\n    //numt = 200;\n    //numt = 3;\n    //numt =4;\n    VectorXd time = dt*VectorXd::LinSpaced(numt,1,numt);\n    // Slip weakening friction parameters\n    double Dc = 0.2;\n    double mu_d= 0.2;\n    double mu_s = 0.6;\n    // Intialization\n    // disp velocity current and next time step (new)\n    VectorXd u_n = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd v_n = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd u_new = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd v_new = VectorXd::Zero(n_nodes*Ndofn,1);\n    VectorXd a_n = VectorXd::Zero(n_nodes*Ndofn,1);\n    // slip and slip-rate\n    std::vector<Eigen::Array<double, -1, 1> > delt_u_n(num_faults);\n    std::vector<Eigen::Array<double, -1, 1> > delt_v_n(num_faults);\n    std::vector<Eigen::Array<double, -1, 1> > T_c(num_faults);\n    std::vector<Eigen::Array<double, -1, 1> > T_0(num_faults);\n    std::vector<Eigen::Array<double, -1, 1> > tau_s(num_faults);\n\n\n    // Vector containing number of elements on each faults (nx)\n    std::vector<int> nx_faults(num_faults);\n    for (int i=0;i<num_faults;i++)\n    {\n        nx_faults[i] =fault_nodes[2*i].size();\n    }\n    \n    \n    for (int i=0;i<num_faults;i++)\n    {\n        delt_u_n[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);\n        delt_v_n[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);\n        T_c[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);\n        T_0[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);\n       // tau_s[i] = ArrayXd::Zero(Ndofn*(nx_faults[i]),1);\n        tau_s[i] = 0.6*ArrayXd::Ones((nx_faults[i]),1)*50.0e6;\n    }\n    VectorXd F_ext_global = VectorXd::Zero(n_nodes*Ndofn,1);\n    // Setting intial stress on the fault\n    for (int j=0; j<num_faults;j++)\n    {\n        for (int i=0; i<nx_faults[j]; i++)\n        {\n            T_0[j](2*i+1) = -50.0e6;\n            T_c[j](2*i+1) = T_0[j](2*i+1);\n        }\n        if (j==0)\n        {\n            VectorXd x = VectorXd::LinSpaced(nx_faults[j], fault_pos(j,1), fault_pos(j,2));\n            for (int i=0 ; i<nx_faults[j]; i++)\n            {\n                if ((x(i)<=(fault_pos(j,1)+fault_pos(j,2))/2+0.2e3)&&(x(i)>=(fault_pos(j,1)+fault_pos(j,2))/2-0.2e3))\n                {\n                    T_0[j](2*i) = 31.0e6;\n                    T_c[j](2*i) = T_0[j](2*i);\n                }\n                else\n                {\n                    T_0[j](2*i) = 20.0e6;\n                    T_c[j](2*i) = T_0[j](2*i);\n                }\n            }\n        }\n        else\n        {\n            for (int i=0 ; i<nx_faults[j]; i++)\n            {\n                T_0[j](2*i) = 20.0e6;\n            }\n        }\n    }\n    // Get the index degree of freedome for each element\n    VectorXi index_el = VectorXi::Zero(Ndofn*Nnel,1);\n    MatrixXi index_store = MatrixXi::Zero(Nnel*Ndofn,n_el);\n    for (int i=0;i<n_el;i++)\n    {\n        bcdof(Element.row(i),dim,index_el);\n        index_store.col(i) = index_el;\n    }\n    VectorXi BIE_top_surf_index = VectorXi::Zero(Ndofn*(BIE_top_surf_nodes.size()),1);\n    VectorXi BIE_bot_surf_index = VectorXi::Zero(Ndofn*(BIE_bot_surf_nodes.size()),1);\n    \n    std::vector<Eigen::ArrayXi> Fault_surf_index(num_faults*2);\n    for (int i=0; i <num_faults*2; i++)\n    {\n        Fault_surf_index[i] = ArrayXi::Zero(Ndofn*(fault_nodes[i].size()),1);\n    }\n  \n    // Getting the faults DOF index\n    for (int i=0; i<num_faults*2;i++)\n    {\n        bcdof_ptr(fault_nodes[i], dim, Fault_surf_index[i].data());\n    }\n    bcdof(BIE_top_surf_nodes,dim,BIE_top_surf_index);\n    bcdof(BIE_bot_surf_nodes,dim,BIE_bot_surf_index);\n    // Calculating the Global Mass Vector (lumped mass)\n    // Element mass\n    double M=density*dx*dy*1.0;\n    VectorXd M_el_vec = M/4*VectorXd::Ones(Nnel*Ndofn,1);\n    VectorXd M_global_vec=VectorXd::Zero(n_nodes*Ndofn,1);\n    for (int i=0 ; i<n_el;i++)\n    {\n        index_el = index_store.col(i);\n        mapglobal(index_el,M_global_vec,M_el_vec);\n    }\n    // Element matrix\n    MatrixXd ke = MatrixXd::Zero(8,8);\n    MatrixXd coord = MatrixXd::Zero(4,2);\n    VectorXi Element_0= Element.row(0);\n    coord.row(0) = Node.row(Element_0(0));\n    coord.row(1) = Node.row(Element_0(1));\n    coord.row(2) = Node.row(Element_0(2));\n    coord.row(3) = Node.row(Element_0(3));\n    cal_ke (coord,E,nu,ke);\n    // BIE part initiation\n    // Setting up the material property for the BIE code\n    Material BIE_top_mat = Material(E,nu,density);\n    Material BIE_bot_mat = Material(E,nu,density);\n    double length = x_max-x_min;\n    // infinte bc BIE call infinite_boundary.cc\n    PrecomputedKernel h11(\"kernels/nu_.25_h11.dat\");\n    PrecomputedKernel h12(\"kernels/nu_.25_k12.dat\");\n    PrecomputedKernel h22(\"kernels/nu_.25_h22.dat\");\n    InfiniteBoundary BIE_inf_top(length,nx_el+1,1.0,&BIE_top_mat,&h11,&h12,&h22);\n    InfiniteBoundary BIE_inf_bot(length,nx_el+1,-1.0,&BIE_bot_mat,&h11,&h12,&h22);\n    // BIE setting time step\n    BIE_inf_top.setTimeStep(dt);\n    BIE_inf_bot.setTimeStep(dt);\n    // BIE initialization\n    BIE_inf_top.init();\n    BIE_inf_bot.init();\n    printf(\"ready to start\\n\");\n    // Output\n    ofstream file;\n    file.open(\"results/num_nodes_fault.bin\",ios::binary);\n    file.write((char*)(nx_faults.data()),nx_faults.size()*sizeof(int));\n    file.close();\n    \n    for (int i=0;i<num_faults;i++)\n    {\n        std::string slip = \"results/slip_\"+std::to_string(i)+\".bin\";\n        file.open(slip);\n        file.close();\n        std::string slip_rate = \"results/slip_rate_\"+std::to_string(i)+\".bin\";\n        file.open(slip_rate);\n        file.close();\n        std::string shear = \"results/shear_\"+std::to_string(i)+\".bin\";\n        file.open(shear);\n        file.close();\n    }\n    double start = omp_get_wtime();\n\n    // Main time loop\n    for (int j=0;j<numt;j++)\n    {\n        // Compute the global internal force\n        VectorXd fe_global= VectorXd::Zero(n_nodes*Ndofn,1);\n        cal_fe_global_const_ke(n_nodes, n_el, index_store, q, u_n, v_n, Ndofn, ke, fe_global);\n        // Friction subroutine\n        VectorXd F_total = F_ext_global-fe_global;\n        for (int i=0 ; i<num_faults; i++)\n        {\n            VectorXd F_fault = VectorXd::Zero(Ndofn*(nx_faults[i]),1);\n            Slip_Weakening(M_global_vec, Fault_surf_index[2*i], Fault_surf_index[2*i+1], fe_global, dt, dx, dy, nx_faults[i]-1, delt_v_n[i], delt_u_n[i], T_0[i], tau_s[i], mu_s, mu_d, Dc, Ndofn, M, F_fault, T_c[i]);\n            mapglobal(Fault_surf_index[2*i],F_total,-F_fault);\n            mapglobal(Fault_surf_index[2*i+1],F_total,F_fault);\n        }\n        \n        // Central Difference Time integration\n        time_advance(u_n, v_n, F_total, M_global_vec, dt);\n        // Get the slip and slip rate\n        \n        for (int i=0; i<num_faults; i++)\n        {\n            cal_slip_slip_rate(u_n, v_n,  Fault_surf_index[2*i], Fault_surf_index[2*i+1] , Ndofn, nx_faults[i]-1, delt_u_n[i], delt_v_n[i]);\n        }\n        // Correct the BIE surf nodes solutions from FEM with the BIE solution\n        BIE_correct(BIE_top_surf_index, BIE_bot_surf_index, fe_global, Ndofn, nx_el, dx, BIE_inf_top, BIE_inf_bot, u_n, v_n);\n        \n//        VectorXd delt_u_n_out = delt_u_n[0];\n//        VectorXd delt_v_n_out = delt_v_n[0];\n//        VectorXd T_c_out = T_c[0];\n//        file.open(\"results/slip_main.bin\",ios::binary | ios::app);\n//        file.write((char*)(delt_u_n[0].data()),delt_u_n[0].size()*sizeof(double));\n//        file.close();\n//        file.open(\"results/slip_rate_main.bin\",ios::binary | ios::app);\n//        file.write((char*)(delt_v_n[0].data()),delt_v_n[0].size()*sizeof(double));\n//        file.close();\n//        file.open(\"results/shear_main.bin\",ios::binary | ios::app);\n//        file.write((char*)(T_c[0].data()),T_c[0].size()*sizeof(double));\n//        file.close();\n        //\n        if (j%4==3)\n        {\n        for (int i=0;i<num_faults;i++)\n        {\n            std::string slip = \"results/slip_\"+std::to_string(i)+\".bin\";\n            file.open(slip,ios::binary | ios::app);\n            file.write((char*)(delt_u_n[i].data()),delt_u_n[i].size()*sizeof(double));\n            file.close();\n            \n            std::string slip_rate = \"results/slip_rate_\"+std::to_string(i)+\".bin\";\n            file.open(slip_rate,ios::binary | ios::app);\n            file.write((char*)(delt_v_n[i].data()),delt_v_n[i].size()*sizeof(double));\n            file.close();\n            \n            std::string shear = \"results/shear_\"+std::to_string(i)+\".bin\";\n            file.open(shear,ios::binary | ios::app);\n            file.write((char*)(T_c[i].data()),T_c[i].size()*sizeof(double));\n            file.close();\n        }\n        }\n        printf(\"Simulation time = %f\\n\",time(j));\n      //  double end_t = omp_get_wtime();\n       // std::cout<<\"time_cpu_t=\"<<end_t-start<<std::endl;\n    //   std::cout<<\"time_fem=\"<< time_fem<<std::endl;\n    //   std::cout<<\"time_bie=\"<< time_bie<<std::endl;\n    }\n    double end = omp_get_wtime();\n    std::cout<<\"time_cpu=\"<<end-start<<std::endl;\n    return 0;\n}\n\nvoid read_matrix(std::string fileName, Eigen::MatrixXd &outputMat) {\n    fstream cin;\n    cin.open(fileName.c_str());\n    if (cin.fail())\n    {\n        std::cerr << \"Failed to open file: \" << fileName << std::endl;\n        std::cin.get(); }\n    string s;\n    vector <vector <double> > matrix;\n    while (getline(cin, s)) {\n        stringstream input(s);\n        double temp;\n        vector <double> currentLine;\n        while (input >> temp)\n            currentLine.push_back(temp);\n        matrix.push_back(currentLine);\n    }\n    if (!igl::list_to_matrix(matrix, outputMat))\n    { std::cerr << \"list tom matrix error\" << std::endl; std::cin.get();\n        //return false;\n    }\n}\n", "meta": {"hexsha": "73995fdad0f8e7e82bf72ff5641240bd8eff1c57", "size": 12271, "ext": "cc", "lang": "C++", "max_stars_repo_path": "simulations/parallel_faults/parallel_fault_run_reg_3_125m.cc", "max_stars_repo_name": "XiaoMaResearch/hybrid_FEM_SBI", "max_stars_repo_head_hexsha": "32fcf1e21a7f78907e01585d892777c11ff1c21e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-04-12T19:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T07:12:57.000Z", "max_issues_repo_path": "simulations/parallel_faults/parallel_fault_run_reg_3_125m.cc", "max_issues_repo_name": "XiaoMaResearch/hybrid_FEM_SBI", "max_issues_repo_head_hexsha": "32fcf1e21a7f78907e01585d892777c11ff1c21e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulations/parallel_faults/parallel_fault_run_reg_3_125m.cc", "max_forks_repo_name": "XiaoMaResearch/hybrid_FEM_SBI", "max_forks_repo_head_hexsha": "32fcf1e21a7f78907e01585d892777c11ff1c21e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-07T07:23:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-07T07:23:58.000Z", "avg_line_length": 36.6298507463, "max_line_length": 215, "alphanum_fraction": 0.5924537528, "num_tokens": 3818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4115049378232469}}
{"text": "//  Copyright John Maddock 2006, 2007.\n//  Copyright Paul A. Bristow 2006, 2007.\n\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_STATS_NORMAL_HPP\n#define BOOST_STATS_NORMAL_HPP\n\n// http://en.wikipedia.org/wiki/Normal_distribution\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3661.htm\n// Also:\n// Weisstein, Eric W. \"Normal Distribution.\"\n// From MathWorld--A Wolfram Web Resource.\n// http://mathworld.wolfram.com/NormalDistribution.html\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/special_functions/erf.hpp> // for erf/erfc.\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n\n#include <utility>\n\nnamespace boost{ namespace math{\n\ntemplate <class RealType = double, class Policy = policies::policy<> >\nclass normal_distribution\n{\npublic:\n   typedef RealType value_type;\n   typedef Policy policy_type;\n\n   normal_distribution(RealType l_mean = 0, RealType sd = 1)\n      : m_mean(l_mean), m_sd(sd)\n   { // Default is a 'standard' normal distribution N01.\n     static const char* function = \"boost::math::normal_distribution<%1%>::normal_distribution\";\n\n     RealType result;\n     detail::check_scale(function, sd, &result, Policy());\n     detail::check_location(function, l_mean, &result, Policy());\n   }\n\n   RealType mean()const\n   { // alias for location.\n      return m_mean;\n   }\n\n   RealType standard_deviation()const\n   { // alias for scale.\n      return m_sd;\n   }\n\n   // Synonyms, provided to allow generic use of find_location and find_scale.\n   RealType location()const\n   { // location.\n      return m_mean;\n   }\n   RealType scale()const\n   { // scale.\n      return m_sd;\n   }\n\nprivate:\n   //\n   // Data members:\n   //\n   RealType m_mean;  // distribution mean or location.\n   RealType m_sd;    // distribution standard deviation or scale.\n}; // class normal_distribution\n\ntypedef normal_distribution<double> normal;\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4127)\n#endif\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> range(const normal_distribution<RealType, Policy>& /*dist*/)\n{ // Range of permissible values for random variable x.\n  if (std::numeric_limits<RealType>::has_infinity)\n  { \n     return std::pair<RealType, RealType>(-std::numeric_limits<RealType>::infinity(), std::numeric_limits<RealType>::infinity()); // - to + infinity.\n  }\n  else\n  { // Can only use max_value.\n    using boost::math::tools::max_value;\n    return std::pair<RealType, RealType>(-max_value<RealType>(), max_value<RealType>()); // - to + max value.\n  }\n}\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> support(const normal_distribution<RealType, Policy>& /*dist*/)\n{ // This is range values for random variable x where cdf rises from 0 to 1, and outside it, the pdf is zero.\n  if (std::numeric_limits<RealType>::has_infinity)\n  { \n     return std::pair<RealType, RealType>(-std::numeric_limits<RealType>::infinity(), std::numeric_limits<RealType>::infinity()); // - to + infinity.\n  }\n  else\n  { // Can only use max_value.\n   using boost::math::tools::max_value;\n   return std::pair<RealType, RealType>(-max_value<RealType>(),  max_value<RealType>()); // - to + max value.\n  }\n}\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\ntemplate <class RealType, class Policy>\ninline RealType pdf(const normal_distribution<RealType, Policy>& dist, const RealType& x)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   RealType sd = dist.standard_deviation();\n   RealType mean = dist.mean();\n\n   static const char* function = \"boost::math::pdf(const normal_distribution<%1%>&, %1%)\";\n\n   RealType result = 0;\n   if(false == detail::check_scale(function, sd, &result, Policy()))\n   {\n      return result;\n   }\n   if(false == detail::check_location(function, mean, &result, Policy()))\n   {\n      return result;\n   }\n   if((boost::math::isinf)(x))\n   {\n     return 0; // pdf + and - infinity is zero.\n   }\n   // Below produces MSVC 4127 warnings, so the above used instead.\n   //if(std::numeric_limits<RealType>::has_infinity && abs(x) == std::numeric_limits<RealType>::infinity())\n   //{ // pdf + and - infinity is zero.\n   //  return 0;\n   //}\n   if(false == detail::check_x(function, x, &result, Policy()))\n   {\n      return result;\n   }\n\n   RealType exponent = x - mean;\n   exponent *= -exponent;\n   exponent /= 2 * sd * sd;\n\n   result = exp(exponent);\n   result /= sd * sqrt(2 * constants::pi<RealType>());\n\n   return result;\n} // pdf\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const normal_distribution<RealType, Policy>& dist, const RealType& x)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   RealType sd = dist.standard_deviation();\n   RealType mean = dist.mean();\n   static const char* function = \"boost::math::cdf(const normal_distribution<%1%>&, %1%)\";\n   RealType result = 0;\n   if(false == detail::check_scale(function, sd, &result, Policy()))\n   {\n      return result;\n   }\n   if(false == detail::check_location(function, mean, &result, Policy()))\n   {\n      return result;\n   }\n   if((boost::math::isinf)(x))\n   {\n     if(x < 0) return 0; // -infinity\n     return 1; // + infinity\n   }\n   // These produce MSVC 4127 warnings, so the above used instead.\n   //if(std::numeric_limits<RealType>::has_infinity && x == std::numeric_limits<RealType>::infinity())\n   //{ // cdf +infinity is unity.\n   //  return 1;\n   //}\n   //if(std::numeric_limits<RealType>::has_infinity && x == -std::numeric_limits<RealType>::infinity())\n   //{ // cdf -infinity is zero.\n   //  return 0;\n   //}\n   if(false == detail::check_x(function, x, &result, Policy()))\n   {\n     return result;\n   }\n   RealType diff = (x - mean) / (sd * constants::root_two<RealType>());\n   result = boost::math::erfc(-diff, Policy()) / 2;\n   return result;\n} // cdf\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const normal_distribution<RealType, Policy>& dist, const RealType& p)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   RealType sd = dist.standard_deviation();\n   RealType mean = dist.mean();\n   static const char* function = \"boost::math::quantile(const normal_distribution<%1%>&, %1%)\";\n\n   RealType result = 0;\n   if(false == detail::check_scale(function, sd, &result, Policy()))\n      return result;\n   if(false == detail::check_location(function, mean, &result, Policy()))\n      return result;\n   if(false == detail::check_probability(function, p, &result, Policy()))\n      return result;\n\n   result= boost::math::erfc_inv(2 * p, Policy());\n   result = -result;\n   result *= sd * constants::root_two<RealType>();\n   result += mean;\n   return result;\n} // quantile\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const complemented2_type<normal_distribution<RealType, Policy>, RealType>& c)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   RealType sd = c.dist.standard_deviation();\n   RealType mean = c.dist.mean();\n   RealType x = c.param;\n   static const char* function = \"boost::math::cdf(const complement(normal_distribution<%1%>&), %1%)\";\n\n   RealType result = 0;\n   if(false == detail::check_scale(function, sd, &result, Policy()))\n      return result;\n   if(false == detail::check_location(function, mean, &result, Policy()))\n      return result;\n   if((boost::math::isinf)(x))\n   {\n     if(x < 0) return 1; // cdf complement -infinity is unity.\n     return 0; // cdf complement +infinity is zero\n   }\n   // These produce MSVC 4127 warnings, so the above used instead.\n   //if(std::numeric_limits<RealType>::has_infinity && x == std::numeric_limits<RealType>::infinity())\n   //{ // cdf complement +infinity is zero.\n   //  return 0;\n   //}\n   //if(std::numeric_limits<RealType>::has_infinity && x == -std::numeric_limits<RealType>::infinity())\n   //{ // cdf complement -infinity is unity.\n   //  return 1;\n   //}\n   if(false == detail::check_x(function, x, &result, Policy()))\n      return result;\n\n   RealType diff = (x - mean) / (sd * constants::root_two<RealType>());\n   result = boost::math::erfc(diff, Policy()) / 2;\n   return result;\n} // cdf complement\n\ntemplate <class RealType, class Policy>\ninline RealType quantile(const complemented2_type<normal_distribution<RealType, Policy>, RealType>& c)\n{\n   BOOST_MATH_STD_USING  // for ADL of std functions\n\n   RealType sd = c.dist.standard_deviation();\n   RealType mean = c.dist.mean();\n   static const char* function = \"boost::math::quantile(const complement(normal_distribution<%1%>&), %1%)\";\n   RealType result = 0;\n   if(false == detail::check_scale(function, sd, &result, Policy()))\n      return result;\n   if(false == detail::check_location(function, mean, &result, Policy()))\n      return result;\n   RealType q = c.param;\n   if(false == detail::check_probability(function, q, &result, Policy()))\n      return result;\n   result = boost::math::erfc_inv(2 * q, Policy());\n   result *= sd * constants::root_two<RealType>();\n   result += mean;\n   return result;\n} // quantile\n\ntemplate <class RealType, class Policy>\ninline RealType mean(const normal_distribution<RealType, Policy>& dist)\n{\n   return dist.mean();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType standard_deviation(const normal_distribution<RealType, Policy>& dist)\n{\n   return dist.standard_deviation();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType mode(const normal_distribution<RealType, Policy>& dist)\n{\n   return dist.mean();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType median(const normal_distribution<RealType, Policy>& dist)\n{\n   return dist.mean();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType skewness(const normal_distribution<RealType, Policy>& /*dist*/)\n{\n   return 0;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis(const normal_distribution<RealType, Policy>& /*dist*/)\n{\n   return 3;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis_excess(const normal_distribution<RealType, Policy>& /*dist*/)\n{\n   return 0;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType entropy(const normal_distribution<RealType, Policy> & dist)\n{\n   using std::log;\n   RealType arg = constants::two_pi<RealType>()*constants::e<RealType>()*dist.standard_deviation()*dist.standard_deviation();\n   return log(arg)/2;\n}\n\n} // namespace math\n} // namespace boost\n\n// This include must be at the end, *after* the accessors\n// for this distribution have been defined, in order to\n// keep compilers that support two-phase lookup happy.\n#include <boost/math/distributions/detail/derived_accessors.hpp>\n\n#endif // BOOST_STATS_NORMAL_HPP\n\n\n", "meta": {"hexsha": "f555192bcaa70d5cf613e8fdec31fb66c6fc58cb", "size": 10768, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/distributions/normal.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 310.0, "max_stars_repo_stars_event_min_datetime": "2017-02-02T09:14:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T06:50:11.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/distributions/normal.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 157.0, "max_issues_repo_issues_event_min_datetime": "2019-02-06T05:04:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T21:50:28.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/distributions/normal.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 54.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T06:55:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T01:12:20.000Z", "avg_line_length": 31.8579881657, "max_line_length": 149, "alphanum_fraction": 0.6866641902, "num_tokens": 2737, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.41142012494863184}}
{"text": "#include \"rememberBoostHistogram.h\"\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <boost/lexical_cast.hpp>\n#include \"sgcu/sgcu.hpp\"\n#include \"utils.hpp\"\n\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\n\nnamespace SG{\n\n//using namespace boost::accumulators;\n\n// build a histogram for a data vector\ntemplate <typename T>\nvoid getHistogram(std::vector<T> const & data, histogram_type & hist)\n{\n\t// create a boost accumulator\n\tacc myAccumulator( boost::accumulators::tag::density::num_bins = data.size()/10.0, boost::accumulators::tag::density::cache_size = data.size()-2);\n\t// fill accumulator\n\tfor (unsigned int j = 0; j < data.size(); ++j){\n\t\tmyAccumulator(data[j]);\n\t}\n\t// do the boost histogram\n\thist = boost::accumulators::density(myAccumulator);\n}\n\nunsigned int rememberBoostHistogram::size() const\n{\n\tunsigned int thisSize = values.size();\n\tif (indices.size() < thisSize)\n\t\tthisSize = indices.size();\n\treturn thisSize;\n}\n\nvoid rememberBoostHistogram::clear()\n{\n\tvalues.clear();\n\tindices.clear();\n}\n\nvoid rememberBoostHistogram::rememberThisHistogram(histogram_type& hist)\n{\n\tclear();\n\tfor (unsigned int i = 0; i < (unsigned int) hist.size(); ++i)\n\t{\n\t\tindices.push_back(hist[i].first);\n\t\tvalues.push_back(hist[i].second);\n\t}\n}\n\nvoid rememberBoostHistogram::operator()(histogram_type& hist)\n{\n\trememberThisHistogram(hist);\n}\n\nrememberBoostHistogram::rememberBoostHistogram()\n{\n}\n\nrememberBoostHistogram::rememberBoostHistogram(histogram_type& hist)\n{\n\trememberThisHistogram(hist);\n}\n\ndouble computeArea(struct rememberBoostHistogram const & data)\n{\n\tdouble area = 0.0;\n\tfor (unsigned int i = 0; i < data.size(); ++i)\n\t{\n\t\tarea += data.values[i];\n\t}\n\treturn area;\n}\n\nvoid getFitHistogramOwn(struct rememberBoostHistogram const & dataOrg, struct rememberBoostHistogram& fit)\n{\n\t// NOTE: this implicitly assumes all histogram values to be positive. true for a histograms, not necessarily true for all inputs!\n\tif ( computeArea(dataOrg) == 0.0 )\n\t{\n\t\tfit = dataOrg;\n\t\treturn;\n\t}\n\n\tconst bool doDebugOutput = false;\n\n\tstruct rememberBoostHistogram data = dataOrg;\n\tif (doDebugOutput) saveHistogramToFile(data, \"comparisonValsNormalization3.txt\");\n\n\t// make sure the histogram is normalized to 1.0\n\tnormalizeHistogramAreaTo(data, 1.0);\n\n\tif (doDebugOutput) saveHistogramToFile(data, \"comparisonValsNormalization3Renorm.txt\");\n\n\tunsigned int lastIndex = computeLastIndex(data);\n\n\t//\tcerr << \"new: setting last entry of histogram to zero\" << endl;\n\tdata.values[data.size()-1] = 0.0;\n\n\tstruct rememberBoostHistogram dataBkp = data;\n\tstruct rememberBoostHistogram dataRenormalizedBkp = data;\n\n\tsmoothHistogram(data);\n\n\tif (doDebugOutput) saveHistogramToFile(data, \"comparisonValsNormalization3Smoothed.txt\");\n\n\tunsigned int firstIndex = getFirstIndex(data, lastIndex);\n\n\t// do not consider values from before the tail to fit the tail!\n\teraseEverythingButTail(data, firstIndex);\n\teraseEverythingButTail(dataBkp, firstIndex);\n\n\tdouble areaBefore = computeArea(dataBkp);\n\tnormalizeHistogramAreaTo(data, areaBefore);\n\n\tif (doDebugOutput) saveHistogramToFile(data, \"comparisonValsNormalization3SmoothedRenorm.txt\");\n\n\tdouble scalingFactor = 0.0;\n\tdouble exponent = 0.0;\n\tobtainFitParameters(data, firstIndex, lastIndex, dataRenormalizedBkp, scalingFactor, exponent);\n\n\tgenerateActualFit(data, scalingFactor, exponent, fit);\n\n\tmergeOriginalAndFit(dataRenormalizedBkp, firstIndex, lastIndex, fit);\n\n\tif (doDebugOutput) saveHistogramToFile(fit, \"comparisonValsNormalization3Fitted.txt\");\n}\n\nvoid getFitHistogramOwn(const std::vector<double>& data, struct rememberBoostHistogram& fit)\n{\n\t// do a histogram\n\tacc myAccumulator( boost::accumulators::tag::density::num_bins = 100, boost::accumulators::tag::density::cache_size = data.size());\n\tfor (unsigned int i = 0; i < data.size(); ++i)\n\t{\n\t\tmyAccumulator(data[i]);\n\t}\n\thistogram_type hist = boost::accumulators::density(myAccumulator);\n\tstruct rememberBoostHistogram histNew(hist);\n\n\tgetFitHistogramOwn(histNew, fit);\n}\n\n\nvoid outputHistogram(histogram_type const & hist, std::string fileName)\n{\n\tstd::ofstream raus;\n\traus.open(fileName.c_str());\n\tif ( (! raus.is_open()) || (! raus.good()) )\n\t{\n\t\tstd::cerr << \"Failed to open file \" << fileName << \" for histogram output.\" << endl;\n\t\tthrow -1;\n\t}\n\n\tfor (unsigned int i = 0; i < (unsigned int) hist.size(); ++i)\n\t{\n\t\traus << hist[i].first << \" \" << hist[i].second << endl;\n\t}\n\n\tif (! raus.good() )\n\t{\n\t\tstd::cerr << \"Failed to write histogram to file \" << fileName << endl;\n\t\tthrow -1;\n\t}\n\traus.close();\n\n}\n\nvoid outputRememberHistogram(rememberBoostHistogram const & fit, std::string fileName)\n{\n\tstd::ofstream raus;\n\traus.open(fileName.c_str());\n\tif ( (! raus.is_open()) || (! raus.good()) )\n\t{\n\t\tstd::cerr << \"Failed to open file \" << fileName << \" for rememberBoostHistogram output.\" << endl;\n\t\tthrow -1;\n\t}\n\n\tfor (unsigned int i = 0; i < fit.size(); ++i)\n\t{\n\t\traus << fit.indices[i] << \" \" << fit.values[i] << endl;\n\t}\n\traus.close();\n\n\tif (! raus.good() )\n\t{\n\t\tstd::cerr << \"Failed to write rememberBoostHistogram to file \" << fileName << endl;\n\t\tthrow -1;\n\t}\n\traus.close();\n}\n\n// TODO: check if both outputs are actually used!\n// for a fixed segmentation threshold: compute histograms for each metric from the clusters found in all pseudo experiments\nvoid computeAndOutputHistogramsFromClusters(std::string folderName, unsigned int n, std::vector<std::vector<double> > & relevanceComparisonVals,\n\t\tstd::string searchStringSegmentationThreshold,\n\t\tstd::vector<std::vector<struct rememberBoostHistogram > >& histsAllSegmentationsAllRelevances)\n{\n\t\thistsAllSegmentationsAllRelevances[n].resize(relevanceComparisonVals.size());\n\t\tfor (unsigned int j = 0; j < relevanceComparisonVals.size(); ++j)\t// for all metrics\n\t\t{\n\t\t\t// create a histogram from all clusters that match this segmentation and metric\n\t\t\tacc myAcc(boost::accumulators::tag::density::num_bins = 100, boost::accumulators::tag::density::cache_size = relevanceComparisonVals[j].size());\n\t\t\tfor (unsigned int i = 0; i < relevanceComparisonVals[j].size(); ++i)\n\t\t\t{\n\t\t\t\tmyAcc(relevanceComparisonVals[j][i]);\n\t\t\t}\n\t\t\thistogram_type hist = boost::accumulators::density(myAcc);\n\t\t\toutputHistogram(hist, folderName + \"/hist_Size\" + searchStringSegmentationThreshold + \"_Metric\" + boost::lexical_cast<std::string>(j) + \".txt\");\n\n\t\t\tstruct rememberBoostHistogram data(hist);\n\t\t\tstruct rememberBoostHistogram fit;\n\t\t\t// compute a fit that approximates the tail of the observed data\n\t\t\tgetFitHistogramOwn(data, fit);\n\t\t\toutputRememberHistogram(fit, folderName + \"/hist_Size\" + searchStringSegmentationThreshold + \"_Metric\" + boost::lexical_cast<std::string>(j) + \"fit.txt\");\n\n\t\t\thistsAllSegmentationsAllRelevances[n][j] = fit;\n\t\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvoid saveHistogramToFile(struct rememberBoostHistogram const & data, std::string const & fileName)\n{\n\tstd::ofstream raus(fileName.c_str());\n\tif (! raus.good())\n\t{\n\t\tstd::cerr << \"Failed to open file \" << fileName << \" for output of histogram data\" << std::endl;\n\t\tthrow (-1);\n\t}\n\tfor (unsigned int i = 0; i < data.size(); ++i)\n\t{\n\t\traus << data.indices[i] << \" \" << data.values[i] << endl;\n\t\tif (! raus.good())\n\t\t{\n\t\t\tstd::cerr << \"Failed to write histogram data entry \" << i << \" of \" << data.size() << \" to file \" << fileName << std::endl;\n\t\t\tthrow (-2);\n\t\t}\n\t}\n\tif (! raus.good())\n\t{\n\t\tstd::cerr << \"Failed to write last of \" << data.size() << \" histogram data entries to file \" << fileName << std::endl;\n\t\tthrow (-2);\n\t}\n\traus.close();\n}\n\n\n\nvoid normalizeHistogramAreaTo(struct rememberBoostHistogram & data, double targetValue)\n{\n\tdouble area = computeArea(data);\n\tdouble rescaleFactor = 0.0;\n\tif (area != 0.0)\n\t{\n\t\trescaleFactor = targetValue/area;\n\t\tfor (unsigned int i = 0; i < data.size(); ++i)\n\t\t{\n\t\t\tdata.values[i] *= rescaleFactor;\n\t\t}\n\t}\n}\n\nunsigned int computeLastIndex(struct rememberBoostHistogram const & data)\n{\n\tunsigned int lastIndex = 0;\n\tunsigned int notZeroIndex = 0;\n\tunsigned int notZeroIndexBefore = 0;\n\tfor (unsigned int i = 0; i < data.size(); ++i)\n\t{\n\t\tif (data.values[i] > 0.0)\n\t\t{\n\t\t\tlastIndex = notZeroIndexBefore;\n\t\t\tnotZeroIndexBefore = notZeroIndex;\n\t\t\tnotZeroIndex = i;\n\t\t}\n\t}\n\tif (lastIndex == 0)\n\t{\n\t\tlastIndex = notZeroIndexBefore;\n\t}\n\tif (lastIndex == 0)\n\t{\n\t\tlastIndex = notZeroIndex;\n\t}\n\tif (lastIndex == 0)\n\t{\n\t\tlastIndex = data.size();\n\t}\n\treturn lastIndex;\n}\n\nvoid smoothHistogram(struct rememberBoostHistogram & data)\n{\n\t// NOTE: I just noted that the number of smoothings correlates with the size of the vector.\n\t// This has been intentional, but it hasn't been checked if this scales to less or more entries.\n\tfor (unsigned int i = 0; i < 0.75*data.size(); ++i)\n\t\tsmoothNoEnds(data.values);\n\tfor (unsigned int i = 0; i < 0.25*data.size(); ++i)\n\t\tsgcu::smooth(data.values);\n}\n\n\n\ndouble evaluateFitL2(const std::vector<double>& data, const std::vector<double>& fit){\n\tif (data.size() != fit.size()){\n\t\tcerr << \"evaluateFitL2 cannot compare data and fit of different size, data: \" << data.size() << \" and fit: \" << fit.size() << endl;\n\t\treturn std::numeric_limits<double>::max();\n\t}\n\n\tdouble diffSum = 0.0;\n\tfor (unsigned int i = 0; i < data.size(); ++i){\n\t\tdouble diff = data[i] - fit[i];\n\t\tdiffSum += (diff*diff);\n\t}\n\treturn diffSum;\n}\n\nvoid obtainFitParameters(struct rememberBoostHistogram & data, unsigned int firstIndex, unsigned int lastIndex,\n\t\tstruct rememberBoostHistogram const & dataRenormalizedBkp,\n\t\tdouble & scalingFactorFitFinal, double & exponent)\n{\n\t// evaluate when each value of the smoothed right flanc is below half of its value - store the distance in x\n\t//cout << \"maxIndex = \" << maxIndex << endl;\n\t//cout << \"firstIndex = \" << firstIndex << endl;\n\t//cout << \"lastIndex = \" << lastIndex << endl;\n\tunsigned int num = 0;\n\tdouble howLongUntilBelowHalf = 0.0;\n\tfor (unsigned int i = firstIndex; i < lastIndex; ++i){\n\t\tdouble currentY100 = data.values[i];\n\t\tif (currentY100 <= 0.0)\n\t\t\tbreak;\n\t\tdouble currentX = data.indices[i];\n\t\tfor (unsigned int j = i+1; j < data.size(); ++j){\n\t//\t\tfor (unsigned int j = i+1; j < lastIndex; ++j){\t// this was the default\n\t\t\tdouble currentY = data.values[j];\n\t\t\tif (currentY <= 0.5*currentY100){\n\t\t\t\tif (currentY > 0.0){\n\t\t\t\t\tdouble distance = data.indices[j] - currentX;\n\t\t\t\t\t//cout << i << \" \" << j << \" distance: \" << distance << \"    histjfirst = \" << data.indices[j] << \" currentX = \" << currentX << \" currentY100 = \" << currentY100 << \" currentY = \" << currentY << endl;\n\t\t\t\t\thowLongUntilBelowHalf += distance;\n\t\t\t\t\t++num;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t//cout << \"nowLongUntil = \" << howLongUntilBelowHalf << endl;\n\t//cout << \"num = \" << num << endl;\n\tif (num != 0){\n\t\thowLongUntilBelowHalf /= static_cast<double>(num);\n\t}\n\n\tdouble stepSize = data.indices[1] - data.indices[0];\n\n\t//cout << \"Mean x distance until y value is below half of its starting value: \" << howLongUntilBelowHalf << endl;\n\thowLongUntilBelowHalf  -= 0.5*stepSize;\n\t//cout << \"x distance corrected for stepsize: \" << howLongUntilBelowHalf << endl;\n\t//double\n\texponent = -1.0/howLongUntilBelowHalf;\n\t//cout << \"exponent of fit: \" << exponent << endl;\n\n\tdouble minDistance = std::numeric_limits<double>::max();\n\t//double\n\tscalingFactorFitFinal = 0.0;\n\n\tstd::vector<double> histValsFitComparison = dataRenormalizedBkp.values;\n\tfor (unsigned int j = 0; j < firstIndex; ++j){\n\t\thistValsFitComparison[j] = 0.0;\n\t}\n\tfor (unsigned int j = lastIndex; j < histValsFitComparison.size(); ++j){\n\t\thistValsFitComparison[j] = 0.0;\n\t}\n\n\tstd::vector<double> fitVals = histValsFitComparison;\n\tfor (unsigned int i = firstIndex; i < lastIndex; ++i){\n\t\tdouble startingXValue = data.indices[i];\n\t\tdouble expectedStartingValue = data.values[i];\n\t\tdouble plainStartingValue = pow(2.0, exponent*startingXValue);\n\t\tdouble scalingFactorFit = expectedStartingValue/plainStartingValue;\n\n\t\tfor (unsigned int j = firstIndex; j < lastIndex; ++j){\n\t\t\tdouble currentX = data.indices[j];\n\t\t\tfitVals[j] = scalingFactorFit*pow(2.0, exponent*currentX);\n\t\t}\n\n\t\tdouble distance = evaluateFitL2(histValsFitComparison, fitVals);\n\t\t//cout << \"index \" << i << \" distance \" << distance << endl;\n\t\tif (distance < minDistance){\n\t\t\tminDistance = distance;\n\t\t\tscalingFactorFitFinal = scalingFactorFit;\n\t\t}\n\t}\n\n\t//cout << \"scalingfactor: \" << scalingFactorFitFinal << endl;\n}\n\n\n\nvoid generateActualFit(struct rememberBoostHistogram const & data, double scalingFactor, double exponent,\n\t\tstruct rememberBoostHistogram& fit, double longerFactor, double finerFactor)\n{\n\tdouble stepSize = data.indices[1] - data.indices[0];\n\tunsigned int targetSize = data.size()*longerFactor*finerFactor;\n\tfit.clear();\n\tfit.indices.resize(targetSize);\n\tfit.values.resize(targetSize);\n\tdouble startIndex = data.indices[0];\n\tfor (unsigned int i = 0; i < targetSize; ++i){\n\t\tfit.indices[i] = startIndex+stepSize*(static_cast<double>(i)/finerFactor);\n\t}\n\tfor (unsigned int i = 0; i < targetSize; ++i){\n\t\tfit.values[i] = scalingFactor*pow(2.0, exponent*fit.indices[i]);\n\t}\n}\n\n\nvoid mergeOriginalAndFit(struct rememberBoostHistogram const & dataRenormalizedBkp, unsigned int firstIndex,\n\t\tunsigned int lastIndex, struct rememberBoostHistogram& fit, double finerFactor)\n{\n\tunsigned int firstIndexFiner = static_cast<unsigned int>(static_cast<double>(firstIndex)*finerFactor+0.5);\n\tunsigned int lastIndexFiner = static_cast<unsigned int>(static_cast<double>(lastIndex)*finerFactor+0.5);\n\n\t// only start using the fit when you don't trust the actual distribution anymore:\n//\tdouble shiftBack = 0.8;\t// default\n\tdouble shiftBack = 0.6;\n\n\tunsigned int startReallyUsingIt = ((1.0-shiftBack)*firstIndex + shiftBack*lastIndex);\n\tunsigned int startReallyUsingItFiner = ((1.0-shiftBack)*firstIndexFiner + shiftBack*lastIndexFiner)-0.55*finerFactor;\n\n\tdouble area2 = 0.0;\n\tfor (unsigned int i = startReallyUsingIt; i < dataRenormalizedBkp.size(); ++i){\n\t\tarea2 += dataRenormalizedBkp.values[i];\n\t}\n\n\tdouble areaFit = 0.0;\n\tfor (unsigned int i = startReallyUsingItFiner; i < fit.values.size(); ++i){\n\t\tareaFit += fit.values[i];\n\t}\n\tdouble rescalingFactor2 = 1.0/finerFactor;\n\tif (areaFit != 0.0)\n\t\trescalingFactor2 = area2/areaFit;\n\n\tfor (unsigned int i = 0; i < startReallyUsingItFiner; ++i){\n\t\tfit.values[i] = 0.0;\n\t}\n\tfor (unsigned int i = startReallyUsingItFiner; i < fit.size(); ++i){\n\t\tfit.values[i] *= rescalingFactor2;\n\t}\n\tfor (unsigned int i = 0; i < startReallyUsingIt; ++i){\n\t\tfit.values[static_cast<unsigned int>(static_cast<double>(i)*finerFactor+0.5)] = dataRenormalizedBkp.values[i];\n\t}\n\n\t// make sure the histogram is normalized to 1.0\n\tnormalizeHistogramAreaTo(fit, 1.0);\n}\n\nunsigned int getFirstIndex(struct rememberBoostHistogram const & data, unsigned int lastIndex)\n{\n\tunsigned int maxIndex = (std::max_element(data.values.begin(), data.values.end())-data.values.begin());\n\treturn static_cast<unsigned int>((2.0*maxIndex+1.0*lastIndex)/3.0);\n}\n\nvoid eraseEverythingButTail(struct rememberBoostHistogram & data, unsigned int firstIndex)\n{\n\tfor (unsigned int i = 0; i < firstIndex; ++i)\n\t{\n\t\tdata.values[i] = 0.0;\n\t}\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n} // end of namespace SG\n", "meta": {"hexsha": "780d2072c66fedbcac55e51dd78fbce87056e63a", "size": 15028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rememberBoostHistogram.cpp", "max_stars_repo_name": "sgeisselsoeder/multiscale", "max_stars_repo_head_hexsha": "d5a95898a6515132e380c5b6806c4f212d18cb0d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rememberBoostHistogram.cpp", "max_issues_repo_name": "sgeisselsoeder/multiscale", "max_issues_repo_head_hexsha": "d5a95898a6515132e380c5b6806c4f212d18cb0d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rememberBoostHistogram.cpp", "max_forks_repo_name": "sgeisselsoeder/multiscale", "max_forks_repo_head_hexsha": "d5a95898a6515132e380c5b6806c4f212d18cb0d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1951219512, "max_line_length": 204, "alphanum_fraction": 0.7002262443, "num_tokens": 4074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.4113107923890842}}
{"text": "//  Copyright John Maddock 2007.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Note that this file contains quickbook mark-up as well as code\r\n// and comments, don't change any of the special comment mark-ups!\r\n\r\n#include <iostream>\r\n\r\n//[policy_eg_7\r\n\r\n#include <boost/math/distributions.hpp>\r\n\r\nnamespace {\r\n\r\nusing namespace boost::math::policies;\r\n\r\ntypedef policy<\r\n   // return infinity and set errno rather than throw:\r\n   overflow_error<errno_on_error>,\r\n   // Don't promote double -> long double internally:\r\n   promote_double<false>,\r\n   // Return the closest integer result for discrete quantiles:\r\n   discrete_quantile<integer_round_nearest>\r\n> my_policy;\r\n\r\nBOOST_MATH_DECLARE_DISTRIBUTIONS(double, my_policy)\r\n\r\n} // close namespace my_namespace\r\n\r\nint main()\r\n{\r\n   //\r\n   // Start with something we know will overflow:\r\n   //\r\n   normal norm(10, 2);\r\n   errno = 0;\r\n   std::cout << \"Result of quantile(norm, 0) is: \" \r\n      << quantile(norm, 0) << std::endl;\r\n   std::cout << \"errno = \" << errno << std::endl;\r\n   errno = 0;\r\n   std::cout << \"Result of quantile(norm, 1) is: \" \r\n      << quantile(norm, 1) << std::endl;\r\n   std::cout << \"errno = \" << errno << std::endl;\r\n   //\r\n   // Now try a discrete distribution:\r\n   //\r\n   binomial binom(20, 0.25);\r\n   std::cout << \"Result of quantile(binom, 0.05) is: \" \r\n      << quantile(binom, 0.05) << std::endl;\r\n   std::cout << \"Result of quantile(complement(binom, 0.05)) is: \" \r\n      << quantile(complement(binom, 0.05)) << std::endl;\r\n}\r\n\r\n//] ends quickbook imported section\r\n\r\n", "meta": {"hexsha": "c56a7288b4247f613963a94ea50fa0ece29412d2", "size": 1701, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/policy_eg_7.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/math/example/policy_eg_7.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/example/policy_eg_7.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 29.3275862069, "max_line_length": 69, "alphanum_fraction": 0.6431510876, "num_tokens": 461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4112872797488411}}
{"text": "#include <armadillo>\n#include <iostream>\n#include <cmath>\n#include \"LowPassFilter.hpp\"\n#include \"LowPassFilter.cpp\"\n#include <ros/ros.h>\n#include \"std_msgs/String.h\"\n#include <sigproc_lib/sigproc_lib.h>\n#include \"sigproc_lib/sigproc.h\"\n\nusing namespace arma;\nusing namespace as64_;\n\nclass GDMP\n{\npublic:\n\n  int BFs, NSamples, extra_train, Ns, id, window;\n  double tNyq, dt, Tend;\n  double y0, dy0, g, y0d_hat, gd_hat, Ry0d_hat, Rgd_hat;\n  double az, bz, K, D, k, ks, kt;\n\n  mat c, h, psi, w;\n  mat y, dy, ddy, y_smoothed, Ry_smoothed;\n  mat Ry, Rdy, Rddy;\n\n  GDMP();\n  ~GDMP();\n  void training(mat y_desired,mat dy_desired,mat ddy_desired, vec timed);\n  mat find_reference_desired(mat y_desired,mat dy_desired,mat ddy_desired, vec timed);\n  void calculate_centers(vec timed);\n  void generate_weights(mat fp_des);\n  void run_solution(double goal, CanonicalStructure cs, double ts, double main_time, double extra_time, int extra_samples);\n  void run_reverse_solution(double goal, CanonicalStructure cs, double ts, double main_time, double extra_time, int extra_samples);\n  double fNyquistFunc(double *original, int size, double fs, double T);\n  vec run_solution_dt(double t_now, double goal, double ts, int i, double f_prev, double df_prev, double ddf_prev );\n  vec init_solution_dt(double goal, CanonicalStructure cs, double main_time, int extra_samples, double t_now, int i );\n  vec init_Rsolution_dt(double goal, CanonicalStructure cs, double main_time, int extra_samples, double t_now, int i);\n  vec run_Rsolution_dt(double t_now, double goal, double ts, int i, double f_prev, double df_prev, double ddf_prev );\n\n};\n\nGDMP::GDMP()\n{\n  std::cout << \"/* Constructor of GDMP */\" << '\\n';\n}\n\nGDMP::~GDMP()\n{\n  std::cout << \"/* Deconstructor of GDMP */\" << '\\n';\n}\n\nvoid GDMP::training(mat y_desired,mat dy_desired,mat ddy_desired, vec timed)\n{\n  std::cout << \"/* Start of Training */\" << '\\n';\n\n  NSamples = y_desired.n_cols;\n  dt = timed(3)-timed(2);\n  Tend = timed(NSamples-1);\n  extra_train = ceil(NSamples/2);\n\n  /* Reference Desired*/\n  mat mat_refD(size(y_desired));\n  mat_refD = find_reference_desired(y_desired, dy_desired, ddy_desired, timed);\n\n  /* Calculate centers h psi */\n  calculate_centers(timed);\n\n  /* Generate weights */\n  generate_weights(mat_refD.row(0));\n\n  std::cout << \"/* End of Training */\" << '\\n';\n}\n\nmat GDMP::find_reference_desired(mat y_desired,mat dy_desired,mat ddy_desired, vec timed)\n{\n  cout<<\"Reference Desired Checked\"<<endl;\n\n  ks = 1;\n  kt = 1;\n  y0 = y_desired(0);\n  dy0 = dy_desired(0);\n  g =  y_desired(NSamples-1);\n\n  /* sig y_desired to 0*/\n  mat tsig = linspace(-Tend-extra_train*dt,extra_train*dt,NSamples+extra_train);\n  mat sig = 1-1/(1+exp(-0.08/dt*tsig));\n\n  double y_scaled_ext[NSamples+extra_train], dy_ext[NSamples+extra_train], ddy_ext[NSamples+extra_train], timed_ext[NSamples+extra_train];\n\n  for (int i = 0; i < NSamples; i++)\n  {\n    y_scaled_ext[i] = sig(i)*(y_desired[i] - y0);\n    dy_ext[i] = sig(i)*dy_desired[i];\n    ddy_ext[i] = sig(i)*ddy_desired[i];\n    timed_ext[i] = timed(i);\n  }\n\n  for (int i = NSamples;i<NSamples+extra_train;i++)\n  {\n    y_scaled_ext[i] = sig(i)*(y_desired[NSamples-1] - y0);\n    dy_ext[i] = sig(i)*dy_desired(NSamples-1);\n    ddy_ext[i] = sig(i)*ddy_desired(NSamples-1);\n    timed_ext[i] = i*dt ;\n  }\n\n  /* original signal */\n  double fd_original_scaled[NSamples+extra_train];\n  double fd_filtered[NSamples];\n\n  vec fd_original_ext(3*NSamples+extra_train);\n  vec fd_filtered_ext(3*NSamples+extra_train);\n\n  /* find original scaled */\n  for (int i = 0; i < NSamples+extra_train; i++)\n  {\n    fd_original_scaled[i] = ks*(y_scaled_ext[i]-y0) + y0; //basically is ext too\n  }\n\n  /* extent before filter */\n  for (int i = 0; i < NSamples; i++)\n  {\n    fd_original_ext(i) = fd_original_scaled[0];\n  }\n  for (int i = 0; i < NSamples+extra_train; i++)\n  {\n    fd_original_ext( i + NSamples ) = fd_original_scaled[i] ;\n  }\n  for (int i = 2*NSamples+extra_train; i < 3*NSamples+extra_train; i++)\n  {\n    fd_original_ext(i) = fd_original_scaled[NSamples+extra_train-1];\n  }\n\n  double  tau = Tend, a = 10, b = a/4;\n\n  /* Nyquist - fc */\n  double fNyquist;\n  fNyquist = fNyquistFunc(fd_original_scaled, NSamples+extra_train, 1/dt, Tend + extra_train*dt );\n\n  BFs = ceil(Tend*fNyquist + extra_train*dt*fNyquist);\n\n  std::cout << fNyquist << '\\n';\n  cout<<BFs<<endl;\n  std::cout << Tend*fNyquist << '\\n';\n  std::cout << extra_train*dt*fNyquist << '\\n';\n\n  tNyq = 1/fNyquist;\n//  Ns = ceil(NSamples/BFs);\n\n  /* Lowpass Filter */\n  // LowPassFilter lpf((1/(2*tNyq)), dt);\n  // for(int i = 0; i < 3*NSamples+extra_train; i++)\n  // {\n  // \t\tfd_filtered_ext[i] = lpf.update(fd_original_ext[i]) ; //Update with 1.0 as input value.\n  // }\n\n  std::cout << \"Filtering...\";\n\n  arma::vec filter_coeff = spl_::fir1(100 /*filter order*/, fNyquist*dt /*normalized cutoff Frequency*/);\n  fd_filtered_ext = arma::conv(fd_original_ext, filter_coeff.t(), \"same\");\n  std::cout << \"[DONE]!\\n\";\n\n  /* keep specific fd_filtered size of NSamples */\n  for (int i = 0; i < NSamples+extra_train; i++)\n  {\n    fd_filtered[i] = fd_filtered_ext(i + NSamples) + y0;\n  }\n\n  /* A to return in once Reference y,dy,ddy */\n  mat A(3,NSamples+extra_train); //3 y,dy,ddy not because of DIM\n  for (int i = 0; i < NSamples+extra_train; i++)\n  {\n    A(0,i) = fd_filtered[i];\n    A(1,i) = ks*kt*dy_ext[i];\n    A(2,i) = ks*pow(kt,2)*ddy_ext[i];\n  }\n\n  /* Printed in files for CHECK*/\n  ofstream myFile;\n\n  std::ostringstream oss,oss2;\n\n  oss << \"CHECK/fd_ori\" << id <<\".log\";\n  myFile.open((oss.str()).c_str());\n  for (int i = 0; i < NSamples+extra_train; i++)\n    myFile<<fd_original_scaled[i]<<endl;\n  myFile.close();\n\n  oss2 << \"CHECK/fd_filtered\" << id <<\".log\";\n  myFile.open((oss2.str()).c_str());\n  for (int i = 0; i < NSamples+extra_train; i++)\n    myFile<<fd_filtered[i]<<endl;\n  myFile.close();\n\n  // oss << \"CHECK/drefD\" << id <<\".log\";\n  // myFile.open((oss.str()).c_str());\n  // myFile<<A.row(1)<<endl;\n  // myFile.close();\n  //\n  // oss << \"CHECK/ddrefD\" << id <<\".log\";\n  // myFile.open((oss.str()).c_str());\n  // myFile<<A.row(2)<<endl;\n  // myFile.close();\n\n  return A;\n}\n\n/* Calculate centers of kernels */\nvoid GDMP::calculate_centers(vec timed)\n{\n  c.set_size(1,BFs);\n\n  for (int idx = 0; idx<BFs; idx++)\n  {\n    c(idx) = (idx)*tNyq;\n  }\n\n  /* ext time for extra train*/\n  vec timed_ext_train(NSamples+extra_train);\n  for (int i = 0; i <NSamples; i++ )\n    timed_ext_train(i) = timed(i);\n  for (int i = 0; i < extra_train; i++ )\n    timed_ext_train(i+NSamples) =  (i+1)*dt + timed(NSamples-1) ;\n\n  /* Sincs == psi */\n  psi.set_size(BFs , NSamples + extra_train);\n  double x;\n  for (int b = 0; b < BFs ; b++)\n  {\n    for (int i = 0; i <NSamples+ extra_train; i++ )\n    {\n      x = ((timed_ext_train(i) - c(b))/tNyq);\n      if (x != 0)\n        psi(b,i) = sin(M_PI*x)/(M_PI*x);\n      else\n        psi(b,i) = 1;\n    }\n  }\n\n}\n\n/* Weights */\nvoid GDMP::generate_weights(mat fp_des)\n{\n  std::cout << \"/* start generate weights */\" << '\\n';\n\n  mat scaled_fp_d = fp_des.t() - y0*ones(NSamples+extra_train);\n\n  w.set_size(BFs ,1);\n  /* weights for BFs*/\n  // !! DERIVATE WITH 0 ?\n  if ( g == y0 )\n  {\n    for (int idx = 0; idx<BFs; idx++)\n    {\n        w(idx) = 1;\n    }\n  }\n  else\n  {\n    for (int idx = 0; idx<BFs; idx++)\n    {\n        w(idx) = scaled_fp_d(round(c(idx)/dt))/(g - y0);\n    }\n  }\n\n}\n\n\nvec GDMP::init_solution_dt(double goal, CanonicalStructure cs, double main_time, int extra_samples, double t_now, int i)\n{\n  /* Set size = NSamples + extra samples\n      extra samples oq from extra time to run\n  */\n  y.set_size(1,NSamples+extra_samples);\n  dy.set_size(1,NSamples+extra_samples);\n  ddy.set_size(1,NSamples+extra_samples);\n\n  az = 10;\n  bz = az/4;\n\n  K = az*bz/pow(cs.taf,2);\n  D = (az + cs.dtaf)/cs.taf;\n\n  k = goal - y0;\n\n  /* Init fp*/\n  double s = 0.0 ;\n  for (int l = 0; l < BFs ; l++)\n  {\n    s = s + w(l)*psi(l,i);\n  }\n\n  /* Declare double mat vec fp d dd */\n  double fp =  k*s + y0;\n  double dfp = 0;\n  double ddfp = 0;\n\n  y0d_hat = fp;\n\n  /* needed to get gd_hat */\n  s = 0.0 ;\n  for (int l = 0; l < BFs ; l++)\n  {\n    s = s + w(l)*psi(l,NSamples-1);\n  }\n\n  gd_hat = k*s + y0;\n\n  // // !! DERIVATE WITH 0 ?\n  // if (gd_hat == y0d_hat)\n  // {\n  // }\n  // else\n  // {\n  //   ks = (goal - y0) / (gd_hat - y0d_hat);\n  // }\n  ks = 1;\n\n  /* Ref compute*/\n  double y_ref  = ks*(fp - y0d_hat) + y0;\n  double dy_ref  = ks*dfp ;\n  double ddy_ref  = ks*ddfp ;\n\n  /* first time loop i = 0*/\n\n  // y dy ddy: only them are stored\n  y(i) = y0;\n  dy(i) = 0; //dy0;\n  double fs = ddy_ref + D*dy_ref + K*(y_ref-goal);\n  ddy(i) = K*(goal-y(i)) - D*dy(i) + fs;\n\n  vec info_back(3);\n  info_back(0)  = fp;\n  info_back(1)  = dfp;\n  info_back(2)  = ddfp;\n\n  return info_back;\n}\n\n vec GDMP::run_solution_dt(double t_now, double goal, double ts, int i, double f_prev, double df_prev, double ddf_prev )\n {\n     double fp  ;\n     double dfp  ;\n     double ddfp ;\n\n     /* Compute fp */\n     if (i > (NSamples-1))\n     {\n         fp = f_prev  ; //same as prev or (NSamples-1)\n         dfp = df_prev ;\n         ddfp = df_prev;\n     }\n     else\n     {\n         double s = 0.0 ;\n         for (int l = 0; l < BFs ; l++)\n         {\n           s = s + w(l)*psi(l,i);\n         }\n         fp = k*s + y0;\n         dfp =  (fp - f_prev)/ts;\n         ddfp = (dfp - df_prev)/ts;\n     }\n\n     /* Compute refs */\n     double y_ref  = ks*(fp - y0d_hat) + y0;\n     double dy_ref  = ks*dfp ;\n     double ddy_ref  = ks*ddfp ;\n\n     /* Euler Solution dt*/\n     dy(i) = ddy(i-1)*ts + dy(i-1);\n     y(i) = dy(i)*ts + y(i-1);\n\n     /* dynamical system */\n     double fs = ddy_ref + D*dy_ref + K*(y_ref-goal);\n     ddy(i) = K*(goal-y(i)) - D*dy(i) + fs;\n\n     /* keep it for next loop dt*/\n     vec info_back(3);\n     info_back(0)  = fp;\n     info_back(1)  = dfp;\n     info_back(2)  = ddfp;\n\n     return info_back;\n }\n\n\nvec GDMP::init_Rsolution_dt(double goal, CanonicalStructure cs, double main_time, int extra_samples, double t_now, int i)\n{\n  /* Set size = NSamples + extra samples\n      extra samples oq from extra time to run\n  */\n  Ry.set_size(1,NSamples+extra_samples);\n  Rdy.set_size(1,NSamples+extra_samples);\n  Rddy.set_size(1,NSamples+extra_samples);\n\n\n\n  /* Swap gd,y0 */\n  double Ry0 = goal;\n  double Rgoal = y0;\n\n  /* Swap gd,y0 hats */\n  Ry0d_hat = Ry0; //gd_hat;\n  Rgd_hat = Rgoal; //y0d_hat;\n\n  /* init Rfp */\n  double Rfp = gd_hat;\n  double Rdfp = 0;\n  double Rddfp = 0;\n\n  /* Ref compute */\n  double Ry_ref  = ks*(Rfp - Ry0d_hat) + Ry0;\n  double Rdy_ref  = ks*Rdfp ;\n  double Rddy_ref  = ks*Rddfp ;\n\n  /* Init R solutions dt */\n  Ry(i) = goal;\n  Rdy(i) = 0; //Ry0;\n  double Rfs = Rddy_ref + D*Rdy_ref + K*(Ry_ref-Rgoal);\n  Rddy(i) = K*(Rgoal-Ry(i)) - D*Rdy(i) + Rfs;\n\n/* keep it for the nect loop dt */\n vec info_back(3);\n info_back(0)  = Rfp;\n info_back(1)  = Rdfp;\n info_back(2)  = Rddfp;\n\n return info_back;\n}\n\nvec GDMP::run_Rsolution_dt(double t_now, double goal, double ts, int i, double f_prev, double df_prev, double ddf_prev )\n{\n    double Rfp  ;\n    double Rdfp  ;\n    double Rddfp ;\n    double Ry0 = goal;\n    double Rgoal = y0;\n\n    /* Compute Rfp */\n    if (i > (NSamples-1))\n    {\n        Rfp = f_prev  ; //same as prev or (NSamples-1)\n        Rdfp = df_prev ;\n        Rddfp = df_prev;\n    }\n    else\n    {\n        double s = 0.0 ;\n        for (int l = 0; l < BFs ; l++)\n        {\n          s = s + w(l)*psi(l,NSamples - i );\n        }\n\n        Rfp = k*s + y0;\n        Rdfp =  (Rfp - f_prev)/ts;\n        Rddfp = (Rdfp - df_prev)/ts;\n    }\n\n    /* Compute R refs */\n    double Ry_ref  = ks*(Rfp - Ry0d_hat) + Ry0;\n    double Rdy_ref  = ks*Rdfp ;\n    double Rddy_ref  = ks*Rddfp ;\n\n    /* Euler Solution dt*/\n    Rdy(i) = Rddy(i-1)*ts + Rdy(i-1);\n    Ry(i) = Rdy(i)*ts + Ry(i-1);\n\n    /* Dynamical system dt*/\n    double Rfs = Rddy_ref + D*Rdy_ref + K*(Ry_ref-Rgoal);\n    Rddy(i) = K*(Rgoal-Ry(i)) - D*Rdy(i) + Rfs;\n\n    /* keep it for the nect loop dt */\n    vec info_back(3);\n    info_back(0)  = Rfp;\n    info_back(1)  = Rdfp;\n    info_back(2)  = Rddfp;\n\n    return info_back;\n}\n\n/* fNyquist Function*/\ndouble GDMP::fNyquistFunc(double *original, int size, double fs, double T)\n{\n  int L;\n  L = (size % 2) == 0 ? size : size+1;\n\n  vec signal_in(size);\n  // cx_vec signal_xf(size);\n  //\n  // cx_mat XF_in(1,int(l1/2+1));\n  // vec A1(size);\n  //\n  double f[int(L/2)];\n  for ( int i = 0; i < (L/2); i++ )\n      f[i] = fs*i/L;\n  // complex<double> epi;\n  // double EdXF = 0;\n  // double  img_EdXF = 0;\n  for (int i = 0; i<size ; i++)\n    signal_in(i) = original[i];\n\n  cx_vec P2(size);\n  P2 = fft(signal_in) ;\n\n  cx_vec Fd_original(int(L/2));\n  for ( int i = 0; i < (L/2); i++ )\n      Fd_original(i) = P2(i);\n\n  double EdD = 0;\n  for ( int i = 0; i < (L/2); i++)\n  {\n    if (f[i] < 40)\n      EdD += abs(pow(Fd_original(i),2));\n  }\n\n  double h = 0.001;\n  double EdDesired = (1-h)*EdD;\n  double energy_inter = 0;\n\n  int i = -1;\n  while( energy_inter < EdDesired)\n  {\n    i++;\n    energy_inter = energy_inter + abs(pow(Fd_original(i),2));\n  }\n  // cout<<i<<endl;\n  double fNyq ;\n\n  if ( i < 0)\n  {\n      fNyq = 2*f[1];\n  }\n  else\n  {\n      fNyq = 2*f[i];\n  }\n  return fNyq;\n}\n", "meta": {"hexsha": "24580e421ac8b1373147c750d7e4f6a27c707c3b", "size": 13115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GDMP.cpp", "max_stars_repo_name": "despargy/KukaImplementation-kinetic", "max_stars_repo_head_hexsha": "3a9ab106b117acfc6478fbf3e60e49b7e94b2722", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-21T12:49:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-21T12:49:27.000Z", "max_issues_repo_path": "src/GDMP.cpp", "max_issues_repo_name": "despargy/KukaImplementation-kinetic", "max_issues_repo_head_hexsha": "3a9ab106b117acfc6478fbf3e60e49b7e94b2722", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GDMP.cpp", "max_forks_repo_name": "despargy/KukaImplementation-kinetic", "max_forks_repo_head_hexsha": "3a9ab106b117acfc6478fbf3e60e49b7e94b2722", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2421441774, "max_line_length": 138, "alphanum_fraction": 0.5915364087, "num_tokens": 4498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8289387998695209, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.4112314236242987}}
{"text": "// (C) Copyright Renaud Detry   2007-2015.\n// Distributed under the GNU General Public License and under the\n// BSD 3-Clause License (See accompanying file LICENSE.txt).\n\n/** @file */\n\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n\n\n#define CGAL_EIGEN3_ENABLED\n\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/pca_estimate_normals.h>\n#include <CGAL/jet_estimate_normals.h>\n#include <CGAL/mst_orient_normals.h>\n#include <CGAL/property_map.h>\n#include <CGAL/IO/read_off_points.h>\n#include <CGAL/IO/read_xyz_points.h>\n#include <CGAL/IO/write_xyz_points.h>\n\n#include <CGAL/trace.h>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/IO/Polyhedron_iostream.h>\n#include <CGAL/Surface_mesh_default_triangulation_3.h>\n#include <CGAL/make_surface_mesh.h>\n#include <CGAL/Implicit_surface_3.h>\n#include <CGAL/IO/output_surface_facets_to_polyhedron.h>\n#include <CGAL/Poisson_reconstruction_function.h>\n#include <CGAL/Point_with_normal_3.h>\n#include <CGAL/property_map.h>\n#include <CGAL/IO/read_xyz_points.h>\n#include <CGAL/compute_average_spacing.h>\n\n\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/AABB_tree.h>\n#include <CGAL/AABB_traits.h>\n#include <CGAL/Polyhedron_3.h>\n#include <CGAL/AABB_polyhedron_triangle_primitive.h>\n#include <CGAL/property_map.h>\n#include <CGAL/IO/read_off_points.h>\n#include <CGAL/IO/read_xyz_points.h>\n#include <CGAL/IO/write_xyz_points.h>\n#include <CGAL/IO/Polyhedron_iostream.h>\n\n#include <CGAL/squared_distance_3.h>\n#include <CGAL/Point_with_normal_3.h>\n\n#endif\n\n#include <vector>\n#include <fstream>\n#include <utility> // defines std::pair\n#include <list>\n#include <boost/filesystem.hpp>\n#include <trimesh/TriMesh.h>\n\n#include <nuklei/KernelCollection.h>\n#include <nuklei/ObservationIO.h>\n\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n\n\nnamespace meshing_types {\n  // Types\n  typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\n  \n  typedef Kernel::FT FT;\n  typedef Kernel::Point_3 Point;\n  typedef CGAL::Point_with_normal_3<Kernel> Point_with_normal;\n  typedef Kernel::Sphere_3 Sphere;\n  typedef std::vector<Point_with_normal> PointList;\n  typedef CGAL::Polyhedron_3<Kernel> Polyhedron;\n  typedef CGAL::Poisson_reconstruction_function<Kernel> Poisson_reconstruction_function;\n  typedef CGAL::Surface_mesh_default_triangulation_3 STr;\n  typedef CGAL::Surface_mesh_complex_2_in_triangulation_3<STr> C2t3;\n  typedef CGAL::Implicit_surface_3<Kernel, Poisson_reconstruction_function> Surface_3;\n  \n  // Types\n  \n  typedef Kernel::Vector_3 Vector;\n  \n  // Point with normal vector stored in a std::pair.\n  typedef std::pair<Point, Vector> PointVectorPair;\n}\n\ntypedef CGAL::Polyhedron_3< CGAL::Simple_cartesian<double> > SimplePolyhedron;\n\nnamespace view_types {\n  typedef CGAL::Simple_cartesian<double> K;\n  typedef K::Point_3 Point;\n  typedef K::Plane_3 Plane;\n  typedef K::Vector_3 Vector;\n  typedef K::Segment_3 Segment;\n  typedef K::Line_3 Line;\n  typedef SimplePolyhedron Polyhedron;\n  typedef CGAL::AABB_polyhedron_triangle_primitive<K,Polyhedron> Primitive;\n  typedef CGAL::AABB_traits<K, Primitive> Traits;\n  typedef CGAL::AABB_tree<Traits> Tree;\n  typedef Tree::Object_and_primitive_id Object_and_primitive_id;\n  typedef Tree::Primitive_id Primitive_id;\n  \n  \n  typedef CGAL::Point_with_normal_3<K> Point_with_normal;\n  typedef std::vector<Point_with_normal> PointList;\n}\n\n#endif\n\nnamespace nuklei {\n  \n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n  static void buildAABBTree(decoration<int>& deco, const int aabbKey,\n                            SimplePolyhedron& poly)\n  {\n    using namespace view_types;\n    \n    boost::shared_ptr<Tree> tree(new Tree);\n    \n    // constructs AABB tree\n    tree.reset(new Tree(poly.facets_begin(),poly.facets_end()));\n    tree->accelerate_distance_queries();\n    \n    if (deco.has_key(aabbKey)) deco.erase(aabbKey);\n    deco.insert(aabbKey, tree);\n  }\n#endif\n  \n  void KernelCollection::buildMesh()\n  {\n    NUKLEI_TRACE_BEGIN();\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n    \n    boost::shared_ptr<SimplePolyhedron> poly(new SimplePolyhedron);\n    \n    {\n      using namespace meshing_types;\n      \n      std::list<PointVectorPair> points;\n      \n      {\n        for (nuklei::KernelCollection::const_iterator i = as_const(*this).begin(); i != as_const(*this).end(); ++i)\n        {\n          nuklei::Vector3 v = i->getLoc();\n          Point p(v.X(),v.Y(),v.Z());\n          points.push_back(std::make_pair(p, Vector()));\n        }\n      }\n      \n      const int nb_neighbors = 16;\n      CGAL::jet_estimate_normals(points.begin(), points.end(),\n                                 CGAL::First_of_pair_property_map<PointVectorPair>(),\n                                 CGAL::Second_of_pair_property_map<PointVectorPair>(),\n                                 nb_neighbors);\n      \n      std::list<PointVectorPair>::iterator unoriented_points_begin =\n      CGAL::mst_orient_normals(points.begin(), points.end(),\n                               CGAL::First_of_pair_property_map<PointVectorPair>(),\n                               CGAL::Second_of_pair_property_map<PointVectorPair>(),\n                               nb_neighbors);\n      \n      // Optional: delete points with an unoriented normal\n      // if you plan to call a reconstruction algorithm that expects oriented normals.\n      points.erase(unoriented_points_begin, points.end());\n      \n      // Optional: after erase(), use Scott Meyer's \"swap trick\" to trim excess capacity\n      std::list<PointVectorPair>(points).swap(points);\n      \n      if (0)\n      {\n        std::ofstream stream(\"/tmp/xyz_points_and_normals.xyz\");\n        if (!stream ||\n            !CGAL::write_xyz_points_and_normals(stream,\n                                                points.begin(), points.end(),\n                                                CGAL::First_of_pair_property_map<PointVectorPair>(),\n                                                CGAL::Second_of_pair_property_map<PointVectorPair>()))\n          std::cerr << \"Error writing temp file\" << std::endl;\n      }\n      \n      // Poisson options\n      FT sm_angle = 20.0; // Min triangle angle in degrees.\n      FT sm_radius = 30; // Max triangle size w.r.t. point set average spacing.\n      FT sm_distance = 0.05; // Surface Approximation error w.r.t. point set average spacing.\n      \n      // Reads the point set file in points[].\n      // Note: read_xyz_points_and_normals() requires an iterator over points\n      // + property maps to access each point's position and normal.\n      // The position property map can be omitted here as we use iterators over Point_3 elements.\n      PointList pl;\n      \n      for (std::list<PointVectorPair>::const_iterator i = points.begin(); i != points.end(); ++i)\n      {\n        pl.push_back(Point_with_normal(i->first, i->second));\n      }\n      \n      // Creates implicit function from the read points using the default solver.\n      // Note: this method requires an iterator over points\n      // + property maps to access each point's position and normal.\n      // The position property map can be omitted here as we use iterators over Point_3 elements.\n      Poisson_reconstruction_function function(\n                                               pl.begin(), pl.end(),\n#if CGAL_VERSION_NR < 1040300000\n                                               CGAL::make_normal_of_point_with_normal_pmap(pl.begin())\n#else\n                                               CGAL::make_normal_of_point_with_normal_pmap(PointList::value_type())\n#endif\n                                               );\n      \n      // Computes the Poisson indicator function f()\n      // at each vertex of the triangulation.\n      if ( ! function.compute_implicit_function() )\n        NUKLEI_THROW(\"Mesh construction error.\");\n      \n      // Computes average spacing\n      FT average_spacing = CGAL::compute_average_spacing(pl.begin(), pl.end(),\n                                                         6 /* knn = 1 ring */);\n      \n      // Gets one point inside the implicit surface\n      // and computes implicit function bounding sphere radius.\n      Point inner_point = function.get_inner_point();\n      Sphere bsphere = function.bounding_sphere();\n      FT radius = std::sqrt(bsphere.squared_radius());\n      \n      // Defines the implicit surface: requires defining a\n      // conservative bounding sphere centered at inner point.\n      FT sm_sphere_radius = 5.0 * radius;\n      FT sm_dichotomy_error = sm_distance*average_spacing/1000.0; // Dichotomy error must be << sm_distance\n      Surface_3 surface(function,\n                        Sphere(inner_point,sm_sphere_radius*sm_sphere_radius),\n                        sm_dichotomy_error/sm_sphere_radius);\n      \n      // Defines surface mesh generation criteria\n      CGAL::Surface_mesh_default_criteria_3<STr> criteria(sm_angle,  // Min triangle angle (degrees)\n                                                          sm_radius*average_spacing,  // Max triangle size\n                                                          sm_distance*average_spacing); // Approximation error\n      \n      // Generates surface mesh with manifold option\n      STr tr; // 3D Delaunay triangulation for surface mesh generation\n      C2t3 c2t3(tr); // 2D complex in 3D Delaunay triangulation\n      CGAL::make_surface_mesh(c2t3,                                 // reconstructed mesh\n                              surface,                              // implicit surface\n                              criteria,                             // meshing criteria\n                              CGAL::Manifold_with_boundary_tag());  // require manifold mesh\n      \n      if(tr.number_of_vertices() == 0)\n        NUKLEI_THROW(\"Mesh construction error.\");\n      \n      Polyhedron output_mesh;\n      CGAL::output_surface_facets_to_polyhedron(c2t3, output_mesh);\n      std::stringstream stream;\n      stream << output_mesh;\n      CGAL::scan_OFF(stream, *poly, true /* verbose */);\n      if(!stream || !poly->is_valid() || poly->empty())\n      {\n        NUKLEI_THROW(\"Cannot convert mesh.\");\n      }\n    }\n    \n    if (deco_.has_key(MESH_KEY)) deco_.erase(MESH_KEY);\n    deco_.insert(MESH_KEY, poly);\n    \n    buildAABBTree(deco_, AABBTREE_KEY, *poly);\n#else\n    NUKLEI_THROW(\"This function requires the partial view build of Nuklei. See http://nuklei.sourceforge.net/doxygen/group__install.html\");\n#endif\n    NUKLEI_TRACE_END();\n  }\n  \n  void KernelCollection::writeMeshToOffFile(const std::string& filename) const\n  {\n    NUKLEI_TRACE_BEGIN();\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n    if (!deco_.has_key(MESH_KEY))\n      NUKLEI_THROW(\"Undefined mesh. Call buildMesh() first.\");\n    std::ofstream out(filename.c_str());\n    out << *deco_.get< boost::shared_ptr<SimplePolyhedron> >(MESH_KEY);\n#else\n    NUKLEI_THROW(\"This function requires the partial view build of Nuklei. See http://nuklei.sourceforge.net/doxygen/group__install.html\");\n#endif\n    NUKLEI_TRACE_END();\n  }\n\n  void KernelCollection::writeMeshToPlyFile(const std::string& filename) const\n  {\n    NUKLEI_TRACE_BEGIN();\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n    boost::filesystem::path offfile =\n    boost::filesystem::unique_path(\"/tmp/nuklei-%%%%-%%%%-%%%%-%%%%.off\");\n    boost::filesystem::path plyfile =\n    boost::filesystem::unique_path(\"/tmp/nuklei-%%%%-%%%%-%%%%-%%%%.ply\");\n    writeMeshToOffFile(offfile.native());\n    boost::shared_ptr<trimesh::TriMesh> mesh(trimesh::TriMesh::read(offfile.native()));\n    mesh->write(plyfile.native());\n    boost::filesystem::copy_file(plyfile, filename);\n#else\n    NUKLEI_THROW(\"This function requires the partial view build of Nuklei. See http://nuklei.sourceforge.net/doxygen/group__install.html\");\n#endif\n    NUKLEI_TRACE_END();\n  }\n\n  void KernelCollection::readMeshFromOffFile(const std::string& filename)\n  {\n    NUKLEI_TRACE_BEGIN();\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n    boost::shared_ptr<SimplePolyhedron> poly(new SimplePolyhedron);\n    std::ifstream in(filename.c_str());\n    CGAL::scan_OFF(in, *poly, true /* verbose */);\n    if(!in || !poly->is_valid() || poly->empty())\n    {\n      NUKLEI_THROW(\"Cannot read mesh.\");\n    }\n    if (deco_.has_key(MESH_KEY)) deco_.erase(MESH_KEY);\n    deco_.insert(MESH_KEY, poly);\n    buildAABBTree(deco_, AABBTREE_KEY, *poly);\n#else\n    NUKLEI_THROW(\"This function requires the partial view build of Nuklei. See http://nuklei.sourceforge.net/doxygen/group__install.html\");\n#endif\n    NUKLEI_TRACE_END();\n  }\n\n  void KernelCollection::readMeshFromPlyFile(const std::string& filename)\n  {\n    NUKLEI_TRACE_BEGIN();\n#ifdef NUKLEI_HAS_PARTIAL_VIEW\n    boost::filesystem::path offfile =\n    boost::filesystem::unique_path(\"/tmp/nuklei-%%%%-%%%%-%%%%-%%%%.off\");\n    boost::filesystem::path plyfile =\n    boost::filesystem::unique_path(\"/tmp/nuklei-%%%%-%%%%-%%%%-%%%%.ply\");\n    boost::filesystem::copy_file(filename, plyfile);\n    boost::shared_ptr<trimesh::TriMesh> mesh(trimesh::TriMesh::read(plyfile.native()));\n    mesh->write(offfile.native());\n    readMeshFromOffFile(offfile.native());\n#else\n    NUKLEI_THROW(\"This function requires the partial view build of Nuklei. See http://nuklei.sourceforge.net/doxygen/group__install.html\");\n#endif\n    NUKLEI_TRACE_END();\n  }\n\n}\n\n", "meta": {"hexsha": "e139065937c348168d76a88f48be4f4121fe67e1", "size": 13161, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libnuklei/kernel/KernelCollectionMesh.cpp", "max_stars_repo_name": "chungying/nuklei", "max_stars_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libnuklei/kernel/KernelCollectionMesh.cpp", "max_issues_repo_name": "chungying/nuklei", "max_issues_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libnuklei/kernel/KernelCollectionMesh.cpp", "max_forks_repo_name": "chungying/nuklei", "max_forks_repo_head_hexsha": "23db2a55a1b3260cf913d0ac10b3b27c000ae1a6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4824561404, "max_line_length": 139, "alphanum_fraction": 0.6633994377, "num_tokens": 3156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8558511616741042, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.4112182347669392}}
{"text": "#include \"collisionDetectionWrapper/Distance.h\"\n#include \"collisionDetectionWrapper/CTCD.h\"\n#include \"Collision.h\"\n#include \"DataConversion.h\"\n#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\n\n\nbool insidebox (const Eigen::Vector3d q, const Eigen::MatrixXd &V1, const Eigen::MatrixXd &V2)\n{\n     Eigen::MatrixXd V(V1.rows()+ V2.rows(), 3);\n     V << V1, V2;\n     Eigen::Vector3d min = V.colwise().minCoeff();\n     Eigen::Vector3d max = V.colwise().maxCoeff();\n     \n     bool inside = true;\n     for (int i = 0; i < 3; i++)\n     {\n         if (q(i) < min(i) || q(i) > max(i))\n             inside = false;\n     }\n \n     return inside;\n}\n\nAABB *buildAABB(std::vector<std::pair<int, BoundingBox> > &boxes)\n{\n    if (boxes.size() == 0)\n        return nullptr;\n    if (boxes.size() == 1)\n    {\n        AABBLeaf *result = new AABBLeaf;\n        result->face = boxes[0].first;\n        result->bbox = boxes[0].second;\n        return result;\n    }\n    else\n    {\n        double mincentroids[3];\n        double maxcentroids[3];\n        BoundingBox enclosing;\n        for (int j = 0; j < 3; j++)\n        {\n            mincentroids[j] = std::numeric_limits<double>::infinity();\n            maxcentroids[j] = -std::numeric_limits<double>::infinity();\n            enclosing.mins[j] = std::numeric_limits<double>::infinity();\n            enclosing.maxs[j] = -std::numeric_limits<double>::infinity();\n        }\n        for (int i = 0; i < boxes.size(); i++)\n        {\n            for (int j = 0; j < 3; j++)\n            {\n                double centroid = 0.5*(boxes[i].second.mins[j] + boxes[i].second.maxs[j]);\n                mincentroids[j] = std::min(mincentroids[j], centroid);\n                maxcentroids[j] = std::max(maxcentroids[j], centroid);\n                enclosing.mins[j] = std::min(enclosing.mins[j], boxes[i].second.mins[j]);\n                enclosing.maxs[j] = std::max(enclosing.maxs[j], boxes[i].second.maxs[j]);\n            }\n        }\n\n        int splitaxis = 0;\n        double bestdist = 0;\n        for (int j = 0; j < 3; j++)\n        {\n            double dist = maxcentroids[j] - mincentroids[j];\n            if (dist > bestdist)\n            {\n                bestdist = dist;\n                splitaxis = j;\n            }\n        }\n\n        std::sort(boxes.begin(), boxes.end(),\n            [splitaxis](const std::pair<int, BoundingBox> &b1, const std::pair<int, BoundingBox> &b2) -> bool\n        {\n            double c1 = 0.5*(b1.second.mins[splitaxis] + b1.second.maxs[splitaxis]);\n            double c2 = 0.5*(b2.second.mins[splitaxis] + b2.second.maxs[splitaxis]);\n            return c1 < c2;\n        }\n        );\n\n        std::vector<std::pair<int, BoundingBox> > leftboxes;\n        std::vector<std::pair<int, BoundingBox> > rightboxes;\n        for (int i = 0; i < boxes.size() / 2; i++)\n            leftboxes.push_back(boxes[i]);\n        for (int i = boxes.size() / 2; i < boxes.size(); i++)\n            rightboxes.push_back(boxes[i]);\n        AABB *left = buildAABB(leftboxes);\n        AABB *right = buildAABB(rightboxes);\n        AABBNode *result = new AABBNode;\n        result->bbox = enclosing;\n        result->left = left;\n        result->right = right;\n        return result;\n    }\n}\n\nBoundingBox wrapTriangle(const Eigen::MatrixXd &Vstart, const Eigen::MatrixXd &Vend, const Eigen::MatrixXi &F, int face, double padding)\n{\n    BoundingBox bb;\n    for (int j = 0; j < 3; j++)\n    {\n        bb.mins[j] = std::numeric_limits<double>::infinity();\n        bb.maxs[j] = -std::numeric_limits<double>::infinity();\n    }\n    for (int j = 0; j < 3; j++)\n    {\n        Eigen::Vector3d vert1 = Vstart.row(F(face, j)).transpose();\n        Eigen::Vector3d vert2 = Vend.row(F(face, j)).transpose();\n        for (int k = 0; k < 3; k++)\n        {\n            bb.mins[k] = std::min(bb.mins[k], vert1[k]-padding);\n            bb.maxs[k] = std::max(bb.maxs[k], vert1[k]+padding);\n            bb.mins[k] = std::min(bb.mins[k], vert2[k]-padding);\n            bb.maxs[k] = std::max(bb.maxs[k], vert2[k]+padding);\n        }\n    }\n    return bb;\n}\n\nAABB *buildAABB(const Eigen::MatrixXd &Vstart, const Eigen::MatrixXd &Vend, const Eigen::MatrixXi &F, double padding)\n{\n    std::vector<std::pair<int, BoundingBox> > boxes;\n    int nfaces = F.rows();\n    for (int i = 0; i < nfaces; i++)\n    {\n        BoundingBox bb = wrapTriangle(Vstart, Vend, F, i, padding);\n        boxes.push_back(std::pair<int, BoundingBox>(i, bb));\n    }\n    return buildAABB(boxes);\n}\n\n", "meta": {"hexsha": "cd805aa3814a3a3f706f624906be4a0466ecde43", "size": 4468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Collision.cpp", "max_stars_repo_name": "csyzzkdcz/effective-garbanzo", "max_stars_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Collision.cpp", "max_issues_repo_name": "csyzzkdcz/effective-garbanzo", "max_issues_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Collision.cpp", "max_forks_repo_name": "csyzzkdcz/effective-garbanzo", "max_forks_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3432835821, "max_line_length": 136, "alphanum_fraction": 0.5405102954, "num_tokens": 1247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.41115396484662464}}
{"text": "//===- odla_dnnl_unary.cc ---------------------------------------------===//\n//\n// Copyright (C) 2019-2021 Alibaba Group Holding Limited.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//   http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// =============================================================================\n\n#include <Eigen/Core>\n\n#include \"odla_dnnl.h\"\n\nenum class alg_unary_eltwise {\n  isnan,\n  isinf,\n  isinf_pos,\n  isinf_neg,\n  abs,\n  acos,\n  asin,\n  atan,\n  ceil,\n  cos,\n  cosh,\n  sin,\n  sinh,\n  log,\n  tan,\n  tanh,\n  sqrt,\n  neg,\n  acosh,\n  asinh,\n  atanh,\n  reciprocal,\n  sign,\n  logic_not,\n};\n\nstatic void unary_eltwise_logic(alg_unary_eltwise alg, void* dst,\n                                const void* data, int n) {\n  const bool* data_t = static_cast<const bool*>(data);\n  Eigen::Map<const Eigen::Array<bool, Eigen::Dynamic, 1>> in(data_t, n);\n  bool* dst_t = static_cast<bool*>(dst);\n  Eigen::Map<Eigen::Array<bool, Eigen::Dynamic, 1>> out(dst_t, n);\n  switch (alg) {\n    case alg_unary_eltwise::logic_not:\n      out = !in;\n      break;\n    default:\n      assert(0);\n  }\n}\n\ntemplate <typename T>\nstatic void unary_eltwise_T(alg_unary_eltwise alg, void* dst, const void* input,\n                            int n) {\n  const T* input_t = static_cast<const T*>(input);\n  Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>> in(input_t, n);\n  T* dst_t = static_cast<T*>(dst);\n  Eigen::Map<Eigen::Array<T, Eigen::Dynamic, 1>> out(dst_t, n);\n  switch (alg) {\n    case alg_unary_eltwise::abs:\n      out = in.abs();\n      break;\n    case alg_unary_eltwise::neg:\n      out = -in;\n      break;\n    case alg_unary_eltwise::sign:\n      out = (0 < in).select(1, in);\n      out = (0 > out).select(-1, out);\n      break;\n    case alg_unary_eltwise::ceil:\n      out = in.ceil();\n      break;\n    case alg_unary_eltwise::log:\n      out = in.log();\n      break;\n    case alg_unary_eltwise::sqrt:\n      out = in.sqrt();\n      break;\n    case alg_unary_eltwise::reciprocal:\n      out = in.pow(-1);\n      break;\n    case alg_unary_eltwise::sin:\n      out = in.sin();\n      break;\n    case alg_unary_eltwise::cos:\n      out = in.cos();\n      break;\n    case alg_unary_eltwise::tan:\n      out = in.tan();\n      break;\n    case alg_unary_eltwise::acos:\n      out = in.acos();\n      break;\n    case alg_unary_eltwise::asin:\n      out = in.asin();\n      break;\n    case alg_unary_eltwise::asinh:\n      out = in.asinh();\n      break;\n    case alg_unary_eltwise::atan:\n      out = in.atan();\n      break;\n    case alg_unary_eltwise::atanh:\n      out = in.atanh();\n      break;\n    case alg_unary_eltwise::sinh:\n      out = in.sinh();\n      break;\n    case alg_unary_eltwise::tanh:\n      out = in.tanh();\n      break;\n    case alg_unary_eltwise::cosh:\n      out = in.cosh();\n      break;\n    case alg_unary_eltwise::acosh:\n      out = in.acosh();\n      break;\n    default:\n      assert(0);\n  }\n}\n\ntemplate <typename T>\nstatic void unary_eltwise_bool(alg_unary_eltwise alg, void* dst,\n                               const void* input, int n) {\n  const T* input_t = static_cast<const T*>(input);\n  Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>> in(input_t, n);\n  bool* dst_t = static_cast<bool*>(dst);\n  Eigen::Map<Eigen::Array<bool, Eigen::Dynamic, 1>> out(dst_t, n);\n  switch (alg) {\n    case alg_unary_eltwise::isnan:\n      out = in.isNaN();\n      break;\n    case alg_unary_eltwise::isinf:\n      out = in.isInf();\n      break;\n    case alg_unary_eltwise::isinf_neg:\n      out = in.isInf() && (in < 0);\n      break;\n    case alg_unary_eltwise::isinf_pos:\n      out = in.isInf() && (in > 0);\n      break;\n    default:\n      assert(0);\n  }\n}\n\nbool is_unary_bool(alg_unary_eltwise alg) {\n  return (alg == alg_unary_eltwise::isnan || alg == alg_unary_eltwise::isinf ||\n          alg == alg_unary_eltwise::isinf_neg ||\n          alg == alg_unary_eltwise::isinf_pos ||\n          alg == alg_unary_eltwise::logic_not);\n}\n\nbool is_unary_logic(alg_unary_eltwise alg) {\n  return (alg == alg_unary_eltwise::logic_not);\n}\n\nstatic odla_value odla_unary_eltwise(alg_unary_eltwise alg, odla_value input,\n                                     const odla_value_id value_id) {\n  // Extract type and size\n  auto elem_type = input->elem_type;\n  bool ret_bool = is_unary_bool(alg);\n  if (ret_bool) {\n    elem_type = ODLA_BOOL;\n  }\n  int n = GetTotalElements(input->shape);\n  // Prepare destination memory\n  dnnl::memory dst_mem;\n  dnnl::memory::desc dst_md = getMemoryDesc({elem_type, input->shape});\n  dst_mem = dnnl::memory(dst_md, g_comp->eng);\n  auto v = CreateValue(dst_mem, input->shape, value_id);\n  v->elem_type = elem_type;\n  // Create lambda operation\n  auto op = [alg, ret_bool, input, dst_mem, n] {\n    void* dst = dst_mem.get_data_handle();\n    const void* data = input->mem.get_data_handle();\n    if (is_unary_logic(alg)) {\n      unary_eltwise_logic(alg, dst, data, n);\n    } else if (input->elem_type == ODLA_FLOAT32) {\n      ret_bool ? unary_eltwise_bool<float>(alg, dst, data, n)\n               : unary_eltwise_T<float>(alg, dst, data, n);\n    } else if (input->elem_type == ODLA_FLOAT64) {\n      ret_bool ? unary_eltwise_bool<double>(alg, dst, data, n)\n               : unary_eltwise_T<double>(alg, dst, data, n);\n    } else if (input->elem_type == ODLA_UINT8) {\n      ret_bool ? unary_eltwise_bool<uint8_t>(alg, dst, data, n)\n               : unary_eltwise_T<uint8_t>(alg, dst, data, n);\n    } else if (input->elem_type == ODLA_UINT16) {\n      ret_bool ? unary_eltwise_bool<uint16_t>(alg, dst, data, n)\n               : unary_eltwise_T<uint16_t>(alg, dst, data, n);\n    } else if (input->elem_type == ODLA_UINT32) {\n      ret_bool ? unary_eltwise_bool<uint32_t>(alg, dst, data, n)\n               : unary_eltwise_T<uint32_t>(alg, dst, data, n);\n    } else if (input->elem_type == ODLA_UINT64) {\n      ret_bool ? unary_eltwise_bool<uint64_t>(alg, dst, data, n)\n               : unary_eltwise_T<uint64_t>(alg, dst, data, n);\n    } else {\n      assert(0);\n    }\n  };\n  // Postprocess\n  add_op(op);\n  InterpretIfNeeded();\n  return v;\n}\n\nodla_value odla_Abs(odla_value input, const odla_value_id value_id) {\n  return unary_eltwise_op(dnnl::algorithm::eltwise_abs, input, 0.f, 0.f,\n                          value_id);\n}\n\nodla_value odla_IsNaN(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::isnan, input, value_id);\n}\n\nodla_value odla_IsInf(odla_value input, odla_bool detect_pos,\n                      odla_bool detect_neg, const odla_value_id value_id) {\n  if (detect_pos != 0 && detect_neg != 0) {\n    return odla_unary_eltwise(alg_unary_eltwise::isinf, input, value_id);\n  }\n  if (detect_pos != 0) {\n    return odla_unary_eltwise(alg_unary_eltwise::isinf_pos, input, value_id);\n  }\n  return odla_unary_eltwise(alg_unary_eltwise::isinf_neg, input, value_id);\n}\n\nodla_value odla_Cos(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::cos, input, value_id);\n}\n\nodla_value odla_Sin(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::sin, input, value_id);\n}\n\nodla_value odla_Tan(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::tan, input, value_id);\n}\n\nodla_value odla_Tanh(odla_value input, const odla_value_id value_id) {\n  return unary_eltwise_op(dnnl::algorithm::eltwise_tanh, input, 0.f, 0.f,\n                          value_id);\n}\n\nodla_value odla_ACos(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::acos, input, value_id);\n}\n\nodla_value odla_ACosh(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::acosh, input, value_id);\n}\n\nodla_value odla_ASin(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::asin, input, value_id);\n}\n\nodla_value odla_ASinh(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::asinh, input, value_id);\n}\n\nodla_value odla_ATan(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::atan, input, value_id);\n}\n\nodla_value odla_ATanh(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::atanh, input, value_id);\n}\n\nodla_value odla_Sinh(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::sinh, input, value_id);\n}\n\nodla_value odla_Cosh(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::cosh, input, value_id);\n}\n\nodla_value odla_Ceil(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::ceil, input, value_id);\n}\n\nodla_value odla_Neg(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::neg, input, value_id);\n}\n\nodla_value odla_Reciprocal(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::reciprocal, input, value_id);\n}\n\nodla_value odla_Sign(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::sign, input, value_id);\n}\n\nodla_value odla_Not(odla_value input, const odla_value_id value_id) {\n  return odla_unary_eltwise(alg_unary_eltwise::logic_not, input, value_id);\n}", "meta": {"hexsha": "b86036874a80ca1dfea3b8af511841708c4a7f5a", "size": 9777, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ODLA/platforms/dnnl/odla_dnnl_unary.cc", "max_stars_repo_name": "alishenli/heterogeneity-aware-lowering-and-optimization", "max_stars_repo_head_hexsha": "9cb7549ba3f566f4b19ccc1c4edf513ebeb118da", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 192.0, "max_stars_repo_stars_event_min_datetime": "2020-09-19T00:21:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T05:38:24.000Z", "max_issues_repo_path": "ODLA/platforms/dnnl/odla_dnnl_unary.cc", "max_issues_repo_name": "alishenli/heterogeneity-aware-lowering-and-optimization", "max_issues_repo_head_hexsha": "9cb7549ba3f566f4b19ccc1c4edf513ebeb118da", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 349.0, "max_issues_repo_issues_event_min_datetime": "2020-09-19T22:27:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:34:17.000Z", "max_forks_repo_path": "ODLA/platforms/dnnl/odla_dnnl_unary.cc", "max_forks_repo_name": "alishenli/heterogeneity-aware-lowering-and-optimization", "max_forks_repo_head_hexsha": "9cb7549ba3f566f4b19ccc1c4edf513ebeb118da", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 75.0, "max_forks_repo_forks_event_min_datetime": "2020-09-19T00:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:53:12.000Z", "avg_line_length": 31.8469055375, "max_line_length": 80, "alphanum_fraction": 0.6675871944, "num_tokens": 2846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.752012562644147, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4111539587692746}}
{"text": "/*\nCopyright 2013 Daniel Ricão Canelhas\n\nRedistribution and use in source and binary forms, with or without \nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, \nthis list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, \nthis list of conditions and the following disclaimer in the documentation and/or \nother materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors \nmay be used to endorse or promote products derived from this software without \nspecific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE \nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL \nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR \nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER \nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, \nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \n*/\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <iostream>\n#include <limits>\n#include <vector>\n#include <stdio.h>\n\n#include <opencv2/core/core.hpp>\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#define EPS 1e-4 // Threshold value on the change in parameters as a termination criteria.\n#define HUBER_LOSS 0.80 //Huber loss function parameter, to redunce the influence of outliers \n#define PAUSE_BETWEEN true //should we pause between each image pyramid?\n\ntemplate <class T>\nT Interpolate(cv::Mat &image, float y,float x)\n{\n  float xd, yd;  \n  float k1 = modff(x,&xd);\n  float k2 = modff(y,&yd);\n  int xi = int(xd);\n  int yi = int(yd);\n\n  int f1 = xi < image.rows-1;  // Check that pixels to the right  \n  int f2 = yi < image.cols-1; // and to down direction exist.\n\n  T px1 = image.at<T>(yi  , xi);\n  T px2 = image.at<T>(yi  , xi+1);\n  T px3 = image.at<T>(yi+1, xi);\n  T px4 = image.at<T>(yi+1, xi+1);      \n  \n  // Interpolate pixel intensity.\n  T interpolated_value = \n  (1.0-k1)*(1.0-k2)*px1 +\n  (f1 ? ( k1*(1.0-k2)*px2 ):0) +\n  (f2 ? ( (1.0-k1)*k2*px3 ):0) +            \n  ((f1 && f2) ? ( k1*k2*px4 ):0);\n\n  return interpolated_value;\n}\n\nvoid Align(cv::Mat &source, cv::Mat &target, int max_iterations, Eigen::Matrix3f &transformation)\n{\n\n  // Find the 2-D similarity transform that best aligns the two images (uniform scale, rotation and translation)\n  cv::Mat debug;\n  \n  cv::Mat source_gradient_row;    // Gradient of I in X direction.\n  cv::Mat source_gradient_col;    // Gradient of I in Y direction.\n  cv::Mat steepest_descent;       // Steepest descent images.\n\n  // Here we will store matrices.\n  Eigen::Matrix3f W;        // Current value of warp W(x,p)\n  Eigen::Matrix3f dW;       // Warp update.\n  Eigen::Vector3f X;        // Point in coordinate frame of source.\n  Eigen::Vector3f Z;        // Point in coordinate frame of target.\n\n  Eigen::Matrix4f H;        // Approximate Hessian.\n  Eigen::Vector4f b;        // Vector in the right side of the system of linear equations.\n  Eigen::Vector4f delta_p;  // Parameter update value.\n  \n  // Create images.\n  source_gradient_row = cv::Mat(source.rows, source.cols, CV_32FC1);\n  source_gradient_col = cv::Mat(source.rows, source.cols, CV_32FC1);\n  steepest_descent =    cv::Mat(source.rows, source.cols, CV_32FC4);\n\n  //The \"magic number\" appearing at the end in the following is simply the inverse \n  //of the absolute sum of the weights in the matrix representing the Scharr filter.\n  cv::Scharr(source, source_gradient_row, -1, 0, 1, 1.0/32.0); \n  cv::Scharr(source, source_gradient_col, -1, 1, 0, 1.0/32.0);   \n  \n  H = Eigen::Matrix4f::Zero();\n  float h00 = 0.0, h01 = 0.0, h02 = 0.0, h03 = 0.0; \n  float h10 = 0.0, h11 = 0.0, h12 = 0.0, h13 = 0.0; \n  float h20 = 0.0, h21 = 0.0, h22 = 0.0, h23 = 0.0; \n  float h30 = 0.0, h31 = 0.0, h32 = 0.0, h33 = 0.0;\n\n  #pragma omp parallel for \\\n  reduction(+:h00,h01,h02,h03,h10,h11,h12,h13,h20,h21,h22,h23,h30,h31,h32,h33)\n  for(int row=0; row<source.rows; row++)//\n  {\n    #pragma unroll\n    for(int col=0; col<source.cols; col++) //\n    {\n      // Evaluate image gradient\n      Eigen::Matrix<float,1,2> image_jacobian;\n      image_jacobian << source_gradient_row.at<float>(row,col),\n                        source_gradient_col.at<float>(row,col);\n\n      // printf(\"image jacobian = %f, %f\", image_jacobian(0),image_jacobian(1));\n\n\n      Eigen::Matrix<float,2,4> warp_jacobian;\n      warp_jacobian <<  1, 0 , row,  row,\n                        0, 1 , -col, col;\n\n      Eigen::Vector4f Jacobian = (image_jacobian*warp_jacobian).transpose();                          \n\n      for(int dim = 0; dim<4; ++dim)\n      steepest_descent.at<cv::Vec4f>(row, col)[dim] = Jacobian(dim);\n\n      Eigen::Matrix4f Hpart = Jacobian*Jacobian.transpose();\n\n      h00+=Hpart(0,0); h01+=Hpart(0,1); h02+=Hpart(0,2); h03+=Hpart(0,3); \n      h10+=Hpart(1,0); h11+=Hpart(1,1); h12+=Hpart(1,2); h13+=Hpart(1,3); \n      h20+=Hpart(2,0); h21+=Hpart(2,1); h22+=Hpart(2,2); h23+=Hpart(2,3); \n      h30+=Hpart(3,0); h31+=Hpart(3,1); h32+=Hpart(3,2); h33+=Hpart(3,3); \n    }\n  }\n\n\n//This is the \"inverse compositional\" method, this means the \n// Hessian approximation need only be computed\n//once, and remains constant for all iterations.\n  \n  float alpha = 1e-4;\n  H <<\n  h00+alpha ,h01      ,h02      ,h03,\n  h10       ,h11+alpha,h12      ,h13,\n  h20       ,h21      ,h22+alpha,h23,\n  h30       ,h31      ,h32      ,h33+alpha;\n\n  W = transformation;\n\n  // Iterate\n  int iter=0; // number of current iteration\n  while(iter < max_iterations)\n  {\n    target.copyTo(debug);\n    iter++; // Increment iteration counter\n\n    uint pixel_count = 0; // Count of processed pixels\n    \n    float b0=0.0, b1=0.0, b2=0.0, b3=0.0;\n    float mean_error = 0.0;\n        \n    #pragma omp parallel for \\\n    reduction(+:mean_error, pixel_count, b0, b1, b2, b3)\n    for(int row=0; row<source.rows; row++)\n    {\n      #pragma unroll\n      for(int col=0; col<source.cols; col++)\n      {\n        // Set vector X with pixel coordinates (u,v,1)\n        X = Eigen::Vector3f(row, col, 1.0);\n        Z = W*X;\n        \n        float row2 = Z(0);\n        float col2 = Z(1);\n\n        // Get the nearest integer pixel coords (u2i;v2i).\n        int row2i = int(floor(row2));\n        int col2i = int(floor(col2));\n\n        if(row2i>=0 && row2i<target.rows && // check if pixel is inside I.\n          col2i>=0 && col2i<target.cols)\n        {\n          pixel_count++;\n\n          // Calculate intensity of a transformed pixel with sub-pixel accuracy\n          // using bilinear interpolation.\n          float I2 = Interpolate<float>(target, row2, col2);\n          \n          debug.at<float>(row2i,col2i) = source.at<float>(row,col);\n\n          // Calculate image difference D = I(W(x,p))-T(x).\n          float D =  source.at<float>(row, col) -I2;\n\n          // Update mean error value.\n          mean_error += fabsf(D);\n\n          // Add a term to b matrix.\n\n          Eigen::Vector4f db;\n          db << steepest_descent.at<cv::Vec4f>(row, col)[0],\n                steepest_descent.at<cv::Vec4f>(row, col)[1],\n                steepest_descent.at<cv::Vec4f>(row, col)[2],\n                steepest_descent.at<cv::Vec4f>(row, col)[3];\n         \n          db *= (fabsf(D) < HUBER_LOSS) ? D : D*HUBER_LOSS/fabsf(D);\n\n          if(!std::isnan(db.dot(db))) \n          {\n            b0 += db(0); \n            b1 += db(1); \n            b2 += db(2); \n            b3 += db(3); \n\n          }\n        } \n      }\n    }\n    std::cout<< \"residual:\" << mean_error/pixel_count << \"\\n\"; \n\n    cv::imshow(\"Debug\", debug);\n    cv::waitKey(24);\n    \n    b = Eigen::Vector4f(b0,b1,b2,b3);\n\n    \n    delta_p = H.ldlt().solve(b);\n\n    Eigen::Matrix2f skew;\n    skew << 0.0, -1.0, \n            1.0,  0.0;\n\n    // Rodrigues' formula:\n    Eigen::Matrix2f R = Eigen::Matrix2f::Identity() + sinf(delta_p(2))*skew +  (1-cosf(delta_p(2)))*(skew*skew.transpose() - Eigen::Matrix2f::Identity());\n    \n    Eigen::Matrix3f T;\n    T << R(0,0)+delta_p(3), R(0,1),             delta_p(0),\n         R(1,0),            R(1,1)+delta_p(3),  delta_p(1),\n            0.0,                          0.0,          1;\n \n    dW = T*W;\n    W = dW;\n\n    // Check termination critera.\n    if(delta_p.norm()<=EPS)\n      {      \n        transformation = W;\n        std::cout << \"Terminated in \" << iter << \" iterations.\" <<std::endl;\n        return;\n      }\n  } // iteration\n  std::cout << \"Maximum iterations reached (\" << iter << \").\" <<std::endl;\n  transformation = W;\n  return;\n}//function\n\nint main(int argc, char **argv)\n{\n  //Reading images\n  cv::Mat img_src_c = cv::imread(argv[1], CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR ); // Read the file\n  cv::Mat img_trg_c = cv::imread(argv[2], CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR ); // Read the OHTER file\n  \n  float x_offset = 0;\n  float y_offset = 0;\n  if(argc == 5)\n  {\n    x_offset = atof(argv[3]);\n    y_offset = atof(argv[4]);\n  }\n\n\n  //convert images to float representation\n  cv::Mat img_src_f; img_src_c.convertTo(img_src_f, CV_32F);\n  cv::Mat img_trg_f; img_trg_c.convertTo(img_trg_f, CV_32F);\n\n  //rescale to unit\n  img_src_f/=255;\n  img_trg_f/=255;\n\n  //containers for low-pass filtered imates\n  cv::Mat img_src_blur;\n  cv::Mat img_trg_blur;\n\n\n  //Create a scale-space pyramid by low-pass filtering and downsampling all the way to quarter-size images\n\n  float sigma = 0.95; //computed from filter size n=3 in [sigma = 0.3(n/2 - 1) + 0.8]\n  cv::GaussianBlur(img_src_f, img_src_blur, cv::Size(3,3), sigma);\n  cv::GaussianBlur(img_trg_f, img_trg_blur, cv::Size(3,3), sigma);\n  cv::Mat img_src_half;\n  cv::Mat img_trg_half;\n  cv::resize(img_src_blur, img_src_half, cv::Size(0,0), 0.5, 0.5);\n  cv::resize(img_trg_blur, img_trg_half, cv::Size(0,0), 0.5, 0.5);\n\n  cv::GaussianBlur(img_src_half, img_src_blur, cv::Size(3,3), sigma);\n  cv::GaussianBlur(img_trg_half, img_trg_blur, cv::Size(3,3), sigma);\n  cv::Mat img_src_quarter;\n  cv::Mat img_trg_quarter;\n  cv::resize(img_src_blur, img_src_quarter, cv::Size(0,0), 0.5, 0.5);\n  cv::resize(img_trg_blur, img_trg_quarter, cv::Size(0,0), 0.5, 0.5);\n  \n  cv::GaussianBlur(img_src_quarter, img_src_blur, cv::Size(3,3), sigma);\n  cv::GaussianBlur(img_trg_quarter, img_trg_blur, cv::Size(3,3), sigma);\n  cv::Mat img_src_eigth;\n  cv::Mat img_trg_eigth;\n  cv::resize(img_src_blur, img_src_eigth, cv::Size(0,0), 0.5, 0.5);\n  cv::resize(img_trg_blur, img_trg_eigth, cv::Size(0,0), 0.5, 0.5);\n\n\n  //offset \n  Eigen::Matrix3f initial_guess;\n\n  initial_guess <<\n   1.0,  0.0,  x_offset/8,\n   0.0,  1.0,  y_offset/8,\n   0,      0,    1;\n  std::cout << \"W:\" << std::endl;\n  std::cout << initial_guess << std::endl;\n\n\n  Align(img_src_eigth, img_trg_eigth, 160, initial_guess);\n  \n  #if PAUSE_BETWEEN\n    cv::waitKey();\n  #endif\n\n  initial_guess(0,2) *= 2;\n  initial_guess(1,2) *= 2;\n  Align(img_src_quarter, img_trg_quarter, 80, initial_guess);\n  \n  #if PAUSE_BETWEEN\n    cv::waitKey();\n  #endif\n\n  initial_guess(0,2) *= 2;\n  initial_guess(1,2) *= 2;\n  Align(img_src_half, img_trg_half, 40, initial_guess);\n  \n  #if PAUSE_BETWEEN\n    cv::waitKey();\n  #endif\n\n  initial_guess(0,2) *= 2;\n  initial_guess(1,2) *= 2;\n  Align(img_src_f, img_trg_f, 20, initial_guess);\n  \n  cv::waitKey();\n  std::cout << initial_guess << std::endl;\n  \n\n\n  return 0;\n}\n", "meta": {"hexsha": "fab80d9b8103f3eae6dacd8327745df0effe7b84", "size": 11845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/align.cpp", "max_stars_repo_name": "dcanelhas/sim2-alignment", "max_stars_repo_head_hexsha": "29c140b9c14c9366ce6d110e50fadc1bcec27d0f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-01-17T22:32:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T05:13:34.000Z", "max_issues_repo_path": "src/align.cpp", "max_issues_repo_name": "dcanelhas/sim2-alignment", "max_issues_repo_head_hexsha": "29c140b9c14c9366ce6d110e50fadc1bcec27d0f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/align.cpp", "max_forks_repo_name": "dcanelhas/sim2-alignment", "max_forks_repo_head_hexsha": "29c140b9c14c9366ce6d110e50fadc1bcec27d0f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-01-18T12:52:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-26T06:41:14.000Z", "avg_line_length": 32.9027777778, "max_line_length": 154, "alphanum_fraction": 0.6279442803, "num_tokens": 3766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4111247101436736}}
{"text": "/**\n* This file is part of Intrinsic3D.\n*\n* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n* Copyright (c) 2019, Technical University of Munich. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions are met:\n*\n*    * Redistributions of source code must retain the above copyright\n*      notice, this list of conditions and the following disclaimer.\n*    * Redistributions in binary form must reproduce the above copyright\n*      notice, this list of conditions and the following disclaimer in the\n*      documentation and/or other materials provided with the distribution.\n*    * Neither the name of NVIDIA CORPORATION nor the names of its\n*      contributors may be used to endorse or promote products derived\n*      from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS \"AS IS\" AND ANY\n* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include <nv/rgbd/processing.h>\n\n#include <iostream>\n\n#include <Eigen/Geometry>\n#include <opencv2/imgproc.hpp>\n\nnamespace nv\n{\n\n    void threshold(cv::Mat &depth, float depth_min, float depth_max)\n\t{\n        cv::threshold(depth, depth, static_cast<double>(depth_min), 0.0, cv::THRESH_TOZERO);\n        cv::threshold(depth, depth, static_cast<double>(depth_max), 0.0, cv::THRESH_TOZERO_INV);\n\t}\n\n\n\tcv::Mat computeVertexMap(const Mat3f &K, const cv::Mat &depth)\n\t{\n\t\tif (depth.empty() || depth.type() != CV_32FC1)\n\t\t\treturn cv::Mat();\n\n\t\tfloat cx = K(0, 2);\n\t\tfloat cy = K(1, 2);\n\t\tfloat fx_inv = 1.0f / K(0, 0);\n\t\tfloat fy_inv = 1.0f / K(1, 1);\n\n        cv::Mat vertex_map = cv::Mat::zeros(depth.size(), CV_32FC3);\n\t\tfor (int y = 0; y < depth.rows; ++y)\n\t\t{\n\t\t\tfor (int x = 0; x < depth.cols; ++x)\n\t\t\t{\n\t\t\t\tfloat d = depth.at<float>(y, x);\n\t\t\t\tfloat x0 = (float(x) - cx) * fx_inv;\n\t\t\t\tfloat y0 = (float(y) - cy) * fy_inv;\n                vertex_map.at<cv::Vec3f>(y, x) = cv::Vec3f(x0 * d, y0 * d, d);\n\t\t\t}\n\t\t}\n        return vertex_map;\n\t}\n\n\n    cv::Mat computeNormals(const cv::Mat &vertex_map, float depth_threshold)\n\t{\n        if (vertex_map.empty() || vertex_map.type() != CV_32FC3)\n\t\t\treturn cv::Mat();\n\n        int w = vertex_map.cols;\n        int h = vertex_map.rows;\n\t\tcv::Mat normals = cv::Mat::zeros(h, w, CV_32FC3);\n        const float* ptr_vert = reinterpret_cast<const float*>(vertex_map.data);\n\n\t\t// depth threshold to avoid computing properties over depth-discontinuities\n        for (int y = 1; y < h - 1; ++y)\n\t\t{\n            for (int x = 1; x < w - 1; ++x)\n\t\t\t{\n                size_t off = static_cast<size_t>((y*w + x) * 3);\n                Vec3f vert(ptr_vert[off], ptr_vert[off + 1], ptr_vert[off + 2]);\n                if (vert[2] == 0.0f)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// determine tangent vectors\n                size_t off_x0 = static_cast<size_t>((y*w + x - 1) * 3);\n                Vec3f vert_x0(ptr_vert[off_x0], ptr_vert[off_x0 + 1], ptr_vert[off_x0 + 2]);\n                size_t off_x1 = static_cast<size_t>((y*w + x + 1) * 3);\n                Vec3f vert_x1(ptr_vert[off_x1], ptr_vert[off_x1 + 1], ptr_vert[off_x1 + 2]);\n                size_t off_y0 = static_cast<size_t>(((y - 1)*w + x) * 3);\n                Vec3f vert_y0(ptr_vert[off_y0], ptr_vert[off_y0 + 1], ptr_vert[off_y0 + 2]);\n                size_t off_y1 = static_cast<size_t>(((y + 1)*w + x) * 3);\n                Vec3f vert_y1(ptr_vert[off_y1], ptr_vert[off_y1 + 1], ptr_vert[off_y1 + 2]);\n                if (vert_x0[2] == 0.0f || vert_x1[2] == 0.0f || vert_y0[2] == 0.0f || vert_y1[2] == 0.0f)\n\t\t\t\t\tcontinue;\n\n                Vec3f tangent_x = vert_x1 - vert_x0;\n                Vec3f tangent_y = vert_y1 - vert_y0;\n                if (tangent_x.norm() < depth_threshold && tangent_y.norm() < depth_threshold)\n\t\t\t\t{\n\t\t\t\t\t// compute normal using cross product\n                    Vec3f n = (tangent_y.cross(tangent_x)).normalized();\n\t\t\t\t\tnormals.at<cv::Vec3f>(y, x) = cv::Vec3f(n[0], n[1], n[2]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn normals;\n\t}\n\n\n    cv::Mat computeNormals(const Mat3f &K, const cv::Mat &depth, float depth_threshold)\n\t{\n        cv::Mat vertex_map = computeVertexMap(K, depth);\n        cv::Mat normals = computeNormals(vertex_map, depth_threshold);\n\t\treturn normals;\n\t}\n\n\n    cv::Mat resizeDepth(const Camera &input_cam, const cv::Mat &input_depth, const Camera &output_cam)\n\t{\n        if (input_depth.empty() || input_depth.type() != CV_32FC1)\n\t\t\treturn cv::Mat();\n        int w = output_cam.width();\n        int h = output_cam.height();\n        if (input_depth.cols == w && input_depth.rows == h)\n\t\t{\n\t\t\t// TODO check if intrinsics of both cameras are the same\n            return input_depth.clone();\n\t\t}\n\n        const Mat3f input_K = input_cam.intrinsics();\n        const Mat3f output_K = output_cam.intrinsics();\n\n        float in_cx = input_K(0, 2);\n        float in_cy = input_K(1, 2);\n        float in_fx = input_K(0, 0);\n        float in_fy = input_K(1, 1);\n\n        float out_cx = output_K(0, 2);\n        float out_cy = output_K(1, 2);\n        float out_fx_inv = 1.0f / output_K(0, 0);\n        float out_fy_inv = 1.0f / output_K(1, 1);\n\n        cv::Mat depth_out = cv::Mat::zeros(h, w, CV_32FC1);\n\t\tfor (int y = 0; y < h; ++y)\n\t\t{\n\t\t\tfor (int x = 0; x < w; ++x)\n\t\t\t{\n\t\t\t\t// compute lookup coordinates for input depth\n                float x0 = (float(x) - out_cx) * out_fx_inv;\n                float y0 = (float(y) - out_cy) * out_fy_inv;\n\t\t\t\t// 3d point (depth and color are registered/aligned -> depth value shouldn't matter)\n\t\t\t\tVec3f p(x0, y0, 1.0f);\n\t\t\t\t// project 3d point into depth image\n\t\t\t\tVec2f p2;\n                p2[0] = (in_fx * p[0] / p[2]) + in_cx;\n                p2[1] = (in_fy * p[1] / p[2]) + in_cy;\n\t\t\t\tVec2i p2i = (p2 + Vec2f::Constant(0.5f)).cast<int>();\n                if (p2i[0] < 0 || p2i[1] < 0 || p2i[0] >= input_depth.cols || p2i[1] >= input_depth.rows)\n\t\t\t\t\tcontinue;\n                // lookup depth in input depth (using linear interpolation)\n                float d_in = interpolate<float>(input_depth, p2[0], p2[1], 0);\n\t\t\t\t// check depth and store it\n                if (d_in == 0.0f)\n\t\t\t\t\tcontinue;\n                depth_out.at<float>(y, x) = d_in;\n\t\t\t}\n\t\t}\n\n        return depth_out;\n\t}\n\n\n    cv::Mat erodeDiscontinuities(const cv::Mat &depth_in, int window_size, float max_depth_diff)\n\t{\n        if (depth_in.empty() || depth_in.type() != CV_32FC1)\n\t\t\treturn cv::Mat();\n\n        if (window_size <= 0)\n\t\t{\n\t\t\t// no erosion -> return copy of input depth\n            return depth_in.clone();\n\t\t}\n\n\t\t// valid depth values\n        int h = depth_in.rows;\n        int w = depth_in.cols;\n        const float* ptr_in = reinterpret_cast<const float*>(depth_in.data);\n        cv::Mat depth_out = depth_in.clone();\n        float* ptr_out = reinterpret_cast<float*>(depth_out.data);\n\n\t\tfor (int y = 0; y < h; ++y)\n\t\t{\n\t\t\tfor (int x = 0; x < w; ++x)\n\t\t\t{\n                size_t idx = static_cast<size_t>(y*w + x);\n                float d_ref = ptr_in[idx];\n                if (d_ref == 0.0f)\n\t\t\t\t{\n                    ptr_out[idx] = 0.0f;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tbool valid = true;\n                for (int v = std::max(0, y - window_size); v <= std::min(y + window_size, h - 1); ++v)\n\t\t\t\t{\n                    for (int u = std::max(0, x - window_size); u <= std::min(x + window_size, w - 1); ++u)\n\t\t\t\t\t{\n                        size_t off = static_cast<size_t>(v*w + u);\n                        float d = ptr_in[off];\n                        if (d == 0.0f || std::abs(d - d_ref) > max_depth_diff)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvalid = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!valid)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!valid)\n                    ptr_out[idx] = 0.0f;\n\t\t\t}\n\t\t}\n        return depth_out;\n\t}\n\n\n\ttemplate<typename T>\n\tT interpolate(const cv::Mat &img, float x, float y, int channel)\n\t{\n\t\tint w = img.cols;\n\t\tint h = img.rows;\n        T val_cur = static_cast<T>(0.0);\n        const T* ptr_img = reinterpret_cast<const T*>(img.data);\n\t\tint nc = img.channels();\n\n\t\t//bilinear interpolation\n\t\tint x0 = static_cast<int>(std::floor(x));\n\t\tint y0 = static_cast<int>(std::floor(y));\n\t\tint x1 = x0 + 1;\n\t\tint y1 = y0 + 1;\n\n        float x1_weight = x - static_cast<float>(x0);\n        float y1_weight = y - static_cast<float>(y0);\n        float x0_weight = 1.0f - x1_weight;\n        float y0_weight = 1.0f - y1_weight;\n\n\t\tif (x0 < 0 || x0 >= w)\n            x0_weight = 0.0f;\n\t\tif (x1 < 0 || x1 >= w)\n            x1_weight = 0.0f;\n\t\tif (y0 < 0 || y0 >= h)\n            y0_weight = 0.0f;\n\t\tif (y1 < 0 || y1 >= h)\n            y1_weight = 0.0f;\n        float w00 = x0_weight * y0_weight;\n        float w10 = x1_weight * y0_weight;\n        float w01 = x0_weight * y1_weight;\n        float w11 = x1_weight * y1_weight;\n\n        float sumWeights = w00 + w10 + w01 + w11;\n        float sum = 0.0f;\n        if (w00 > 0.0f)\n            sum += static_cast<float>(ptr_img[(y0*w + x0) * nc + channel]) * w00;\n        if (w01 > 0.0f)\n            sum += static_cast<float>(ptr_img[(y1*w + x0) * nc + channel]) * w01;\n        if (w10 > 0.0f)\n            sum += static_cast<float>(ptr_img[(y0*w + x1) * nc + channel]) * w10;\n        if (w11 > 0.0f)\n            sum += static_cast<float>(ptr_img[(y1*w + x1) * nc + channel]) * w11;\n\n        if (sumWeights > 0.0f)\n            val_cur = static_cast<T>(sum / sumWeights);\n\n        return val_cur;\n\t}\n\ttemplate unsigned char interpolate(const cv::Mat &img, float x, float y, int channel);\n\ttemplate unsigned short interpolate(const cv::Mat &img, float x, float y, int channel);\n\ttemplate int interpolate(const cv::Mat &img, float x, float y, int channel);\n\ttemplate float interpolate(const cv::Mat &img, float x, float y, int channel);\n\ttemplate double interpolate(const cv::Mat &img, float x, float y, int channel);\n\n\n\tVec3b interpolateRGB(const cv::Mat &color, float x, float y)\n\t{\n\t\t// lookup color using bilinear interpolation\n\t\tunsigned char r = interpolate<unsigned char>(color, x, y, 2);\n\t\tunsigned char g = interpolate<unsigned char>(color, x, y, 1);\n\t\tunsigned char b = interpolate<unsigned char>(color, x, y, 0);\n\t\treturn Vec3b(r, g, b);\n\t}\n\n} // namespace nv\n", "meta": {"hexsha": "aad91506042b0395cb8a3a91af0cc414b7a3c06a", "size": 10779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libintrinsic3d/src/rgbd/processing.cpp", "max_stars_repo_name": "dazinovic/intrinsic3d", "max_stars_repo_head_hexsha": "4e5ea3b3d81b4174f33765e1d3dd0b24c2716c06", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 370.0, "max_stars_repo_stars_event_min_datetime": "2019-01-03T23:22:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T12:40:03.000Z", "max_issues_repo_path": "libintrinsic3d/src/rgbd/processing.cpp", "max_issues_repo_name": "jtpils/intrinsic3d", "max_issues_repo_head_hexsha": "3f94bc59dba6d77981aad1c8f38531706e51078f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2019-02-13T10:15:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-10T10:22:47.000Z", "max_forks_repo_path": "libintrinsic3d/src/rgbd/processing.cpp", "max_forks_repo_name": "jtpils/intrinsic3d", "max_forks_repo_head_hexsha": "3f94bc59dba6d77981aad1c8f38531706e51078f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 66.0, "max_forks_repo_forks_event_min_datetime": "2019-02-28T06:19:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:06:35.000Z", "avg_line_length": 35.4572368421, "max_line_length": 106, "alphanum_fraction": 0.5871602189, "num_tokens": 3242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4110511547325763}}
{"text": "/**\n *          Copyright Matthias Walter 2010.\n * Distributed under the Boost Software License, Version 1.0.\n *    (See accompanying file LICENSE_1_0.txt or copy at\n *          http://www.boost.org/LICENSE_1_0.txt)\n **/\n\n#ifndef VIOLATOR_SEARCH_HPP_\n#define VIOLATOR_SEARCH_HPP_\n\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n\n#include \"algorithm.hpp\"\n#include \"matroid.hpp\"\n#include \"signing.hpp\"\n#include \"logger.hpp\"\n\nnamespace unimod\n{\n  namespace detail\n  {\n\n    inline matroid_element_set find_smallest_irregular_minor(const decomposed_matroid* decomposition, bool collect_extra_elements = true)\n    {\n      if (decomposition->is_leaf())\n      {\n        const decomposed_matroid_leaf* leaf = (decomposed_matroid_leaf*) decomposition;\n\n        if (leaf->is_regular())\n          return matroid_element_set();\n\n        matroid_element_set result;\n        std::copy(leaf->elements().begin(), leaf->elements().end(), std::inserter(result, result.end()));\n        if (collect_extra_elements)\n          std::copy(leaf->extra_elements().begin(), leaf->extra_elements().end(), std::inserter(result, result.end()));\n        return result;\n      }\n      else\n      {\n        const decomposed_matroid_separator* separator = (decomposed_matroid_separator*) decomposition;\n\n        matroid_element_set first_elements = find_smallest_irregular_minor(separator->first(), collect_extra_elements);\n        matroid_element_set second_elements = find_smallest_irregular_minor(separator->second(), collect_extra_elements);\n        if (first_elements.empty())\n          return second_elements;\n        else if (second_elements.empty())\n          return first_elements;\n        else\n          return (first_elements.size() < second_elements.size()) ? first_elements : second_elements;\n      }\n    }\n\n    template <typename InputIterator, typename OutputIterator1, typename OutputIterator2>\n    std::pair <OutputIterator1, OutputIterator2> split_elements(InputIterator first, InputIterator beyond, OutputIterator1 rows,\n        OutputIterator2 columns)\n    {\n      for (; first != beyond; ++first)\n      {\n        if (*first > 0)\n          *columns++ = *first;\n        else\n          *rows++ = *first;\n      }\n      return std::make_pair(rows, columns);\n    }\n\n    template <typename MatrixType>\n    void create_indirect_matroid(const MatrixType& input_matrix, const matroid_element_set& row_elements, const matroid_element_set& column_elements,\n        integer_matroid& sub_matroid, submatrix_indices& sub_indices)\n    {\n      sub_matroid.resize(row_elements.size(), column_elements.size());\n      submatrix_indices::vector_type row_vector(row_elements.size());\n      submatrix_indices::vector_type column_vector(column_elements.size());\n\n      size_t index = row_elements.size() - 1;\n      for (matroid_element_set::const_iterator iter = row_elements.begin(); iter != row_elements.end(); ++iter)\n      {\n        sub_matroid.name1(index) = *iter;\n        row_vector[index] = -1 - *iter;\n        --index;\n      }\n\n      index = 0;\n      for (matroid_element_set::const_iterator iter = column_elements.begin(); iter != column_elements.end(); ++iter)\n      {\n        sub_matroid.name2(index) = *iter;\n        column_vector[index] = -1 + *iter;\n        ++index;\n      }\n\n      sub_indices.rows = submatrix_indices::indirect_array_type(row_vector.size(), row_vector);\n      sub_indices.columns = submatrix_indices::indirect_array_type(column_vector.size(), column_vector);\n\n    }\n\n    class violator_strategy\n    {\n    public:\n      violator_strategy(const integer_matrix& input_matrix, const matroid_element_set& row_elements, const matroid_element_set& column_elements,\n          logger& log) :\n        _input_matrix(input_matrix), _row_elements(row_elements), _column_elements(column_elements), _log(log)\n      {\n        if (log.is_progressive() || _log.is_verbose())\n        {\n          std::cout << \"\\nMatrix is NOT totally unimodular. Searching the violating submatrix...\\n\" << std::endl;\n        }\n      }\n\n      /**\n       * Destructor\n       */\n\n      virtual ~violator_strategy()\n      {\n\n      }\n\n      virtual void search() = 0;\n\n      inline void create_matrix(submatrix_indices& indices) const\n      {\n        integer_matroid sub_matroid;\n        create_indirect_matroid(_input_matrix, _row_elements, _column_elements, sub_matroid, indices);\n      }\n\n    protected:\n\n      virtual void shrink(const matroid_element_set& row_elements, const matroid_element_set& column_elements)\n      {\n#ifndef NDEBUG\n        typedef boost::numeric::ublas::matrix_indirect <const integer_matrix, submatrix_indices::indirect_array_type> indirect_matrix_t;\n\n        integer_matroid matroid;\n        submatrix_indices sub_indices;\n\n        create_indirect_matroid(_input_matrix, row_elements, column_elements, matroid, sub_indices);\n        indirect_matrix_t sub_matrix(_input_matrix, sub_indices.rows, sub_indices.columns);\n\n        if (is_totally_unimodular(sub_matrix))\n        {\n          std::cout << \"submatrix is t.u., but should not:\" << std::endl;\n          matrix_print(sub_matrix);\n\n          assert (false);\n        }\n#endif\n\n        _row_elements = row_elements;\n        _column_elements = column_elements;\n\n      }\n\n      inline bool test(const matroid_element_set& row_elements, const matroid_element_set& column_elements)\n      {\n        typedef boost::numeric::ublas::matrix_indirect <const integer_matrix, submatrix_indices::indirect_array_type> indirect_matrix_t;\n\n        integer_matroid matroid;\n        submatrix_indices sub_indices;\n\n        create_indirect_matroid(_input_matrix, row_elements, column_elements, matroid, sub_indices);\n        indirect_matrix_t sub_matrix(_input_matrix, sub_indices.rows, sub_indices.columns);\n\n        /// Signing test\n\n        decomposed_matroid* decomposition;\n        integer_matrix matrix(sub_matrix);\n\n        if (_log.is_progressive() || _log.is_verbose())\n        {\n          std::cout << \"Testing a \" << row_elements.size() << \" x \" << column_elements.size() << \" submatrix.\" << std::endl;\n        }\n\n        if (!is_signed_matrix(matrix))\n        {\n          if (_log.is_progressive() || _log.is_verbose())\n          {\n            std::cout << \"Submatrix did not pass the signing test. It is NOT totally unimodular.\\n\" << std::endl;\n          }\n          shrink(row_elements, column_elements);\n          return false;\n        }\n\n        /// Remove sign from matrix\n        support_matrix(matrix);\n\n        /// Matroid decomposition\n        bool is_tu;\n        boost::tie(is_tu, decomposition) = decompose_binary_matroid(matroid, matrix, matroid_element_set(), true, _log);\n\n        if (is_tu)\n        {\n          if (_log.is_progressive() || _log.is_verbose())\n          {\n            std::cout << \"\\nSubmatrix is totally unimodular.\\n\" << std::endl;\n          }\n          delete decomposition;\n          return true;\n        }\n\n        matroid_element_set rows, columns, elements = detail::find_smallest_irregular_minor(decomposition);\n        delete decomposition;\n\n        detail::split_elements(elements.begin(), elements.end(), std::inserter(rows, rows.end()), std::inserter(columns, columns.end()));\n\n        if (_log.is_progressive() || _log.is_verbose())\n        {\n          if (rows.size() < row_elements.size() || columns.size() < column_elements.size())\n          {\n            std::cout << \"\\nThe \" << row_elements.size() << \" x \" << column_elements.size() << \" submatrix is NOT totally unimodular. A \"\n                << rows.size() << \" x \" << columns.size() << \" non-totally unimodular submatrix was identified, too.\\n\" << std::endl;\n          }\n          else\n          {\n            std::cout << \"\\nThe \" << row_elements.size() << \" x \" << column_elements.size() << \" submatrix is NOT totally unimodular.\\n\" << std::endl;\n\n          }\n        }\n\n        if (rows.size() < row_elements.size() || columns.size() < column_elements.size())\n          shrink(rows, columns);\n        else\n          shrink(row_elements, column_elements);\n\n        return false;\n      }\n\n      inline bool test_forbidden(const matroid_element_set& forbidden_elements)\n      {\n        /// Setup rows and columns\n        matroid_element_set rows, columns;\n        for (matroid_element_set::const_iterator iter = _row_elements.begin(); iter != _row_elements.end(); ++iter)\n        {\n          if (forbidden_elements.find(*iter) == forbidden_elements.end())\n          {\n            rows.insert(*iter);\n          }\n        }\n        for (matroid_element_set::const_iterator iter = _column_elements.begin(); iter != _column_elements.end(); ++iter)\n        {\n          if (forbidden_elements.find(*iter) == forbidden_elements.end())\n          {\n            columns.insert(*iter);\n          }\n        }\n\n        return test(rows, columns);\n      }\n\n    protected:\n      const integer_matrix& _input_matrix;\n      matroid_element_set _row_elements;\n      matroid_element_set _column_elements;\n      logger& _log;\n    };\n\n    class single_violator_strategy: public violator_strategy\n    {\n    public:\n      single_violator_strategy(const integer_matrix& input_matrix, const matroid_element_set& row_elements,\n          const matroid_element_set& column_elements, logger& log) :\n        violator_strategy(input_matrix, row_elements, column_elements, log)\n      {\n\n      }\n\n      /**\n       * Destructor\n       */\n\n      virtual ~single_violator_strategy()\n      {\n\n      }\n\n      virtual void search()\n      {\n        std::vector <int> all_elements;\n        std::copy(_row_elements.begin(), _row_elements.end(), std::back_inserter(all_elements));\n        std::copy(_column_elements.begin(), _column_elements.end(), std::back_inserter(all_elements));\n\n        for (std::vector <int>::const_iterator iter = all_elements.begin(); iter != all_elements.end(); ++iter)\n        {\n          if (_row_elements.find(*iter) == _row_elements.end() && _column_elements.find(*iter) == _column_elements.end())\n            continue;\n\n          matroid_element_set rows(_row_elements);\n          matroid_element_set columns(_column_elements);\n          rows.erase(*iter);\n          columns.erase(*iter);\n          test(rows, columns);\n        }\n      }\n    };\n\n    class greedy_violator_strategy: public violator_strategy\n    {\n    public:\n      greedy_violator_strategy(const integer_matrix& input_matrix, const matroid_element_set& row_elements,\n          const matroid_element_set& column_elements, logger& log) :\n        violator_strategy(input_matrix, row_elements, column_elements, log)\n      {\n\n      }\n\n      /**\n       * Destructor\n       */\n\n      virtual ~greedy_violator_strategy()\n      {\n\n      }\n\n      /**\n       * Tests minors given in a vector of sets.\n       *\n       * @param bundles Vector of Sets containing the removed elements.\n       * @return true iff a test failed, i.e. the submatrix was not totally unimodular.\n       */\n\n      bool test_bundles(const std::vector <matroid_element_set>& bundles)\n      {\n        for (std::vector <matroid_element_set>::const_iterator bundle_iter = bundles.begin(); bundle_iter != bundles.end(); ++bundle_iter)\n        {\n          if (!test_forbidden(*bundle_iter))\n          {\n            return true;\n          }\n        }\n        return false;\n      }\n\n      virtual void search()\n      {\n        for (float rate = 0.8f; rate > 0.02f; rate *= 0.5f)\n        {\n          size_t row_amount, column_amount;\n          if (rate > 0.04f)\n          {\n            row_amount = int(_row_elements.size() * rate);\n            column_amount = int(_column_elements.size() * rate);\n            if (row_amount == 0 || column_amount == 0)\n            {\n              row_amount = 1;\n              column_amount = 1;\n              rate = 0.03f;\n            }\n          }\n          else\n          {\n            row_amount = 1;\n            column_amount = 1;\n          }\n\n          if (_log.is_progressive() || _log.is_verbose())\n            std::cout << \"\\nGreedy loop starting, forbidden sets will have size \" << row_amount << \" and \" << column_amount << std::endl;\n\n          typedef std::vector <matroid_element_set::value_type> matroid_element_vector;\n          matroid_element_vector shuffled_rows, shuffled_columns;\n          std::copy(_row_elements.begin(), _row_elements.end(), std::back_inserter(shuffled_rows));\n          std::copy(_column_elements.begin(), _column_elements.end(), std::back_inserter(shuffled_columns));\n\n          std::random_shuffle(shuffled_rows.begin(), shuffled_rows.end());\n          std::random_shuffle(shuffled_columns.begin(), shuffled_columns.end());\n\n          std::vector <matroid_element_set> bundles;\n\n          for (matroid_element_vector::const_iterator iter = shuffled_rows.begin(); iter + row_amount <= shuffled_rows.end(); iter += row_amount)\n          {\n            bundles.push_back(matroid_element_set());\n            std::copy(iter, iter + row_amount, std::inserter(bundles.back(), bundles.back().end()));\n          }\n\n          for (matroid_element_vector::const_iterator iter = shuffled_columns.begin(); iter + column_amount <= shuffled_columns.end(); iter\n              += column_amount)\n          {\n            bundles.push_back(matroid_element_set());\n            std::copy(iter, iter + column_amount, std::inserter(bundles.back(), bundles.back().end()));\n          }\n\n          if (test_bundles(bundles))\n          {\n            rate *= 2.0f;\n          }\n        }\n      }\n    };\n\n  }\n}\n\n#endif /* VIOLATOR_SEARCH_HPP_ */\n", "meta": {"hexsha": "e711664ee3acb2da928d544ff4b1825783faf9c8", "size": 13428, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "unimodularity-library-1.2c/src/violator_search.hpp", "max_stars_repo_name": "vios-fish/CompetitiveProgramming", "max_stars_repo_head_hexsha": "6953f024e4769791225c57ed852cb5efc03eb94b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-05T21:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-08T01:33:12.000Z", "max_issues_repo_path": "src/violator_search.hpp", "max_issues_repo_name": "vbraun/unimodularity-library", "max_issues_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/violator_search.hpp", "max_forks_repo_name": "vbraun/unimodularity-library", "max_forks_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1679389313, "max_line_length": 150, "alphanum_fraction": 0.6263032469, "num_tokens": 2936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4110511474443969}}
{"text": "#include <MeshFEM/MeshIO.hh>\n#include <MeshFEM/MSHFieldWriter.hh>\n#include <MeshFEM/LinearElasticity.hh>\n#include <MeshFEM/Materials.hh>\n#include <MeshFEM/PeriodicHomogenization.hh>\n#include <MeshFEM/OrthotropicHomogenization.hh>\n#include <MeshFEM/GlobalBenchmark.hh>\n#include <MeshFEM/TensorProjection.hh>\n#include <vector>\n#include <queue>\n#include <iostream>\n#include <iomanip>\n#include <memory>\n#include <cmath>\n\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n\nnamespace po = boost::program_options;\nusing namespace std;\nusing namespace PeriodicHomogenization;\n\n[[ noreturn ]] void usage(int exitVal, const po::options_description &visible_opts) {\n    cout << \"Usage: PeriodicHomogenization_cli [options] mesh\" << endl;\n    cout << visible_opts << endl;\n    exit(exitVal);\n}\n\npo::variables_map parseCmdLine(int argc, const char *argv[])\n{\n    po::options_description hidden_opts(\"Hidden Arguments\");\n    hidden_opts.add_options()\n        (\"mesh\",       po::value<string>(),                     \"input mesh\")\n        ;\n    po::positional_options_description p;\n    p.add(\"mesh\",                1);\n\n    po::options_description visible_opts;\n    visible_opts.add_options()(\"help\", \"Produce this help message\")\n        (\"material,m\", po::value<string>(),                \"base material\")\n        (\"degree,d\",   po::value<int>()->default_value(2), \"degree of finite elements\")\n        (\"m2mstress,M\",po::value<string>(),                \"Dump macroscopic to microscopic stress tensors to specified file\")\n        (\"fieldOutput,o\",po::value<string>(),              \"Dump fluctuation stress and strain fields to specified msh file\")\n        (\"centerFluctuationDisplacements,c\",               \"Shift each fluctuation displacement so that it averages to zero\")\n        (\"fullDegreeFieldOutput,D\",                        \"Output full-degree nodal fields (don't do piecewise linear subsample)\")\n        (\"distanceToIsotropy\",                             \"Output the distance to the closest isotropic tensor\")\n        (\"distanceToMaterial\", po::value<string>(),        \"Output the distance to a particular material\")\n        (\"ignorePeriodicMismatch\",                         \"Ignore mismatched nodes on the periodic faces (useful for voxel grids)\")\n        (\"manualPeriodicVertices\", po::value<string>(),    \"Manually specify identified periodic vertices using a hacky file format (see PeriodicCondition constructor)\")\n        (\"orthotropicCell,O\",                              \"Analyze the orthotropic symmetry base cell only\")\n        ;\n\n    po::options_description cli_opts;\n    cli_opts.add(visible_opts).add(hidden_opts);\n\n    po::variables_map vm;\n    try {\n        po::store(po::command_line_parser(argc, argv).\n                  options(cli_opts).positional(p).run(), vm);\n        po::notify(vm);\n    }\n    catch (std::exception &e) {\n        cout << \"Error: \" << e.what() << endl << endl;\n        usage(1, visible_opts);\n    }\n\n    bool fail = false;\n    if (vm.count(\"mesh\") == 0) {\n        cout << \"Error: must specify input mesh\" << endl;\n        fail = true;\n    }\n\n    int d = vm[\"degree\"].as<int>();\n    if (d < 1 || d > 2) {\n        cout << \"Error: FEM Degree must be 1 or 2\" << endl;\n        fail = true;\n    }\n\n    if (fail || vm.count(\"help\"))\n        usage(fail, visible_opts);\n\n    return vm;\n}\n\ntemplate<size_t _N>\nusing HMG = LinearElasticity::HomogenousMaterialGetter<Materials::Constant>::template Getter<_N>;\n\ntemplate<size_t _N, size_t _FEMDegree>\nvoid execute(const po::variables_map &args,\n             const vector<MeshIO::IOVertex> &inVertices,\n             const vector<MeshIO::IOElement> &inElements) {\n    auto &mat = HMG<_N>::material;\n    if (args.count(\"material\")) mat.setFromFile(args[\"material\"].as<string>());\n\n    typedef LinearElasticity::Mesh<_N, _FEMDegree, HMG> Mesh;\n    typedef LinearElasticity::Simulator<Mesh> Simulator;\n    Simulator sim(inElements, inVertices);\n    typedef typename Simulator::ETensor ETensor;\n    typedef typename Simulator::VField  VField;\n\n    BENCHMARK_START_TIMER_SECTION(\"Cell Problems\");\n    std::vector<VField> w_ij;\n    std::unique_ptr<PeriodicCondition<_N>> pc;\n    if (args.count(\"manualPeriodicVertices\"))\n        pc = Future::make_unique<PeriodicCondition<_N>>(sim.mesh(), args[\"manualPeriodicVertices\"].as<string>());\n    if (args.count(\"orthotropicCell\") == 0) {\n        solveCellProblems(w_ij, sim, 1e-7, args.count(\"ignorePeriodicMismatch\"), std::move(pc));\n    }\n    else {\n        auto systems = PeriodicHomogenization::Orthotropic::solveCellProblems(w_ij, sim, 1e-7);\n    }\n\n    BENCHMARK_STOP_TIMER_SECTION(\"Cell Problems\");\n\n    BENCHMARK_START_TIMER_SECTION(\"Compute Tensor\");\n    // ETensor Eh = homogenizedElasticityTensor(w_ij, sim);\n    ETensor Eh;\n    if (args.count(\"orthotropicCell\") == 0)   Eh = homogenizedElasticityTensorDisplacementForm(w_ij, sim);\n    else Eh = PeriodicHomogenization::Orthotropic::homogenizedElasticityTensorDisplacementForm(w_ij, sim);\n    BENCHMARK_STOP_TIMER_SECTION(\"Compute Tensor\");\n\n    cout << setprecision(16);\n    cout << \"Homogenized elasticity tensor:\" << endl;\n    cout << Eh << endl << endl;\n\n    auto eigs = Eh.computeEigenstrains();\n    cout << \"Minimum Eh eigenvalue \" << eigs.lambdas[0] << \" for eigenstrain: \"\n         << eigs.strains.col(0).transpose() << endl;\n\n    cout << \"Intermediate Eh eigenvalue \" << eigs.lambdas[1] << \" for eigenstrain: \"\n         << eigs.strains.col(1).transpose() << endl;\n\n    cout << \"Max Eh eigenvalue \" << eigs.lambdas[2] << \" for eigenstrain: \"\n         << eigs.strains.col(2).transpose() << endl;\n\n    ETensor S = Eh.inverse();\n    cout << \"Homogenized compliance tensor:\" << endl;\n    cout << S << endl;\n    vector<Real> moduli(flatLen(_N));\n\n    // Shear moduli are multiplied by 4 in flattened compliance tensor...\n    for (size_t i = 0; i < flatLen(_N); ++i)\n        moduli[i] = ((i < _N) ? 1.0 : 0.25) / S.D(i, i);\n\n    vector<Real> poisson;\n    if (_N == 2) poisson = { -S.D(0, 1) / S.D(1, 1),   // v_yx\n                             -S.D(1, 0) / S.D(0, 0) }; // v_xy\n    else         poisson = { -S.D(0, 1) / S.D(1, 1),   // v_yx\n                             -S.D(0, 2) / S.D(2, 2),   // v_zx\n                             -S.D(1, 2) / S.D(2, 2),   // v_zy\n                             -S.D(1, 0) / S.D(0, 0),   // v_xy\n                             -S.D(2, 0) / S.D(0, 0),   // v_xz\n                             -S.D(2, 1) / S.D(1, 1) }; // v_zy\n\n    if (_N == 2)  {\n        cout << \"Approximate Young moduli:\\t\"  << moduli[0] << \"\\t\" << moduli[1] << endl;\n        cout << \"Approximate shear modulus:\\t\" << moduli[2] << endl;\n\n        cout << \"v_yx, v_xy:\\t\" << poisson[0] << \"\\t\" << poisson[1] << endl;\n    }\n    else {\n        cout << \"Approximate Young moduli:\\t\" << moduli[0] << \"\\t\" << moduli[1] << \"\\t\"\n             << moduli[2] << endl;\n        cout << \"Approximate shear moduli:\\t\" << moduli[3] << \"\\t\" << moduli[4] << \"\\t\"\n             << moduli[5] << endl;\n\n        cout << \"v_yx, v_zx, v_zy:\\t\" << poisson[0] << \"\\t\" << poisson[1] << \"\\t\" << poisson[2] << endl;\n        cout << \"v_xy, v_xz, v_yz:\\t\" << poisson[3] << \"\\t\" << poisson[4] << \"\\t\" << poisson[5] << endl;\n    }\n\n    cout << \"Anisotropy:\\t\" << Eh.anisotropy() << endl;\n\n    if (args.count(\"m2mstress\")) {\n        string mpath = args[\"m2mstress\"].as<string>();\n        ofstream mfile(mpath);\n        ofstream gfile(\"gtensors.txt\");\n        mfile << setprecision(16);\n        gfile << setprecision(16);\n        if (!mfile.is_open()) throw runtime_error(\"Failed to open output file \" + mpath);\n        auto G = macroStrainToMicroStrainTensors(w_ij, sim);\n        for (size_t ei = 0; ei < sim.mesh().numElements(); ++ei) {\n            G.at(ei).writeUnflattened(gfile); gfile << endl;\n            auto F = mat.getTensor().doubleContract(G.at(ei).doubleContract(S));\n            F.writeUnflattened(mfile);\n            mfile << endl;\n        }\n    }\n\n    if (args.count(\"fieldOutput\")) {\n        bool linearSubsampleFields = args.count(\"fullDegreeFieldOutput\") == 0;\n        MSHFieldWriter writer(args[\"fieldOutput\"].as<string>(), sim.mesh(),\n                              linearSubsampleFields);\n        if (args.count(\"centerFluctuationDisplacements\")) {\n            for (size_t i = 0; i < w_ij.size(); ++i) {\n                auto &w = w_ij[i];\n                VectorND<_N> total(VectorND<_N>::Zero());\n                for (size_t ii = 0; ii < w.domainSize(); ++ii) total += w(ii);\n                total *= 1.0 / w.domainSize();\n                for (size_t ii = 0; ii < w.domainSize(); ++ii) w(ii) -= total;\n            }\n        }\n        for (size_t i = 0; i < w_ij.size(); ++i) {\n            writer.addField(\"load_ij \" + to_string(i), sim.dofToNodeField(sim.constantStrainLoad(-Simulator::SMatrix::CanonicalBasis(i))), DomainType::PER_NODE);\n            writer.addField(\"w_ij \" + to_string(i), w_ij[i], DomainType::PER_NODE);\n            if ((Simulator::Strain::Deg == 0) || linearSubsampleFields) {\n                // Output constant (average) strain when we're outputting piecewise\n                // linear solutions.\n                writer.addField(\"strain w_ij \" + to_string(i),\n                        sim.averageStrainField(w_ij[i]), DomainType::PER_ELEMENT);\n            }\n            else {\n                // Output full-degree per-element strain. (Wasteful since\n                // strain fields are of degree - 1, but Gmsh/MSHFieldWriter\n                // only supports full-degree ElementNodeData).\n                auto strainField = sim.strainField(w_ij[i]);\n                typedef SymmetricMatrixInterpolant<typename Simulator::SMatrix,\n                                               _N, _FEMDegree> UpsampledStrain;\n                vector<UpsampledStrain> upsampledStrainField;\n                upsampledStrainField.reserve(strainField.size());\n                for (const auto s: strainField)\n                    upsampledStrainField.emplace_back(s);\n                writer.addField(\"strain w_ij \" + to_string(i),\n                                upsampledStrainField, DomainType::PER_ELEMENT);\n            }\n        }\n    }\n\n    if (args.count(\"distanceToIsotropy\")) {\n        auto isoFit = closestIsotropicTensor(Eh);\n        cout << endl;\n        cout << \"(Sq Rel Frob) Distance to Isotropy:\\t\" << (isoFit - Eh).frobeniusNormSq() / isoFit.frobeniusNormSq() << endl;\n        cout << \"Closest isotropic tensor:\" << endl << isoFit << endl;\n        cout << endl;\n    }\n\n    if (args.count(\"distanceToMaterial\")) {\n        Materials::Constant<_N> targetMat(args.at(\"distanceToMaterial\").as<string>());\n        auto tgtE = targetMat.getTensor();\n        cout << \"(Sq Rel Frob) Distance to Specified Tensor:\\t\" << (Eh - tgtE).frobeniusNormSq() / tgtE.frobeniusNormSq() << endl;\n    }\n\n    BENCHMARK_REPORT();\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/*! Program entry point\n//  @param[in]  argc    Number of arguments\n//  @param[in]  argv    Argument strings\n//  @return     status  (0 on success)\n*///////////////////////////////////////////////////////////////////////////////\nint main(int argc, const char *argv[])\n{\n    po::variables_map args = parseCmdLine(argc, argv);\n\n    vector<MeshIO::IOVertex>  inVertices;\n    vector<MeshIO::IOElement> inElements;\n    string meshPath = args[\"mesh\"].as<string>();\n    auto type = load(meshPath, inVertices, inElements, MeshIO::FMT_GUESS,\n                     MeshIO::MESH_GUESS);\n\n    // Infer dimension from mesh type.\n    size_t dim;\n    if      (type == MeshIO::MESH_TET) dim = 3;\n    else if (type == MeshIO::MESH_TRI) dim = 2;\n    else    throw std::runtime_error(\"Mesh must be triangle or tet.\");\n\n    // Look up and run appropriate homogenizer instantiation.\n    int deg = args[\"degree\"].as<int>();\n    auto exec = (dim == 3) ? ((deg == 2) ? execute<3, 2> : execute<3, 1>)\n                           : ((deg == 2) ? execute<2, 2> : execute<2, 1>);\n\n    exec(args, inVertices, inElements);\n\n    return 0;\n}\n", "meta": {"hexsha": "7dea0ae66232751735f3fd958adf39f2199d12af", "size": 11978, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/bin/PeriodicHomogenization_cli.cc", "max_stars_repo_name": "pbedenbaugh/MeshFEM", "max_stars_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "src/bin/PeriodicHomogenization_cli.cc", "max_issues_repo_name": "pbedenbaugh/MeshFEM", "max_issues_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "src/bin/PeriodicHomogenization_cli.cc", "max_forks_repo_name": "pbedenbaugh/MeshFEM", "max_forks_repo_head_hexsha": "742d609d4851582ffb9c5616774fc2ef489e2f88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 43.3985507246, "max_line_length": 169, "alphanum_fraction": 0.5768909668, "num_tokens": 3170, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370422, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4110464966909596}}
{"text": "#include<iostream>\n#include\"basis.hpp\"\n#include\"operators.hpp\"\n#include\"diag.h\"\n#include\"tpoperators.hpp\"\n#include\"files.hpp\"\n#include\"timeev.hpp\"\n#include\"ETH.hpp\"\n#include <boost/program_options.hpp>\nint main(int argc, char *argv[])\n{\n  using namespace Eigen;\nusing namespace std;\nusing namespace Many_Body;\n  using Fermi_HubbardBasis= TensorProduct<ElectronBasis, ElectronBasis>;\n   using HolsteinBasis= TensorProduct<ElectronBasis, PhononBasis>;\n  using Mat= Operators::Mat;\n  using boost::program_options::value;\n   size_t M{};\n  size_t L{};\n  double t0{};\n  double omega{};\n  double gamma{};\n  double dt{};\n  double tot{};\n  bool PB{};\n  std::string dirname=\"\";\n  std::string filename={};\n  try\n  {\n    boost::program_options::options_description desc{\"Options\"};\n    desc.add_options()\n      (\"help,h\", \"Help screen\")\n      (\"L\", value(&L)->default_value(4), \"L\")\n      (\"M,m\", value(&M)->default_value(2), \"M\")\n      (\"t\", value(&t0)->default_value(1.), \"t0\")\n      (\"gam\", value(&gamma)->default_value(1.), \"gamma\")\n      (\"omg\", value(&omega)->default_value(1.), \"omega\")\n      (\"dir\", value(&dirname)->default_value(\"\"), \"dirname\")\n    (\"dt\", value(&dt)->default_value(0.1), \"dt\")\n      (\"tot\", value(&tot)->default_value(1.), \"tot\")\n    (\"pb\", value(&PB)->default_value(true), \"PB\");\n  \n\n\n    boost::program_options::variables_map vm;\n    boost::program_options::store(parse_command_line(argc, argv, desc), vm);\n    boost::program_options::notify(vm);\n\n    if (vm.count(\"help\"))\n      {std::cout << desc << '\\n'; return 0;}\n    else{\n      if (vm.count(\"L\"))\n      {      std::cout << \"L: \" << vm[\"L\"].as<size_t>() << '\\n';\n\tfilename+=\"L\"+std::to_string(vm[\"L\"].as<size_t>());\n      }\n     if (vm.count(\"M\"))\n      {\n\tstd::cout << \"M: \" << vm[\"M\"].as<size_t>() << '\\n';\n\tfilename+=\"M\"+std::to_string(vm[\"M\"].as<size_t>());\n      }\n      if (vm.count(\"t\"))\n      {\n\tstd::cout << \"t0: \" << vm[\"t\"].as<double>() << '\\n';\n\tfilename+=\"t0\"+std::to_string(vm[\"t\"].as<double>()).substr(0, 3);\n      }\n       if (vm.count(\"omg\"))\n      {\n\tstd::cout << \"omega: \" << vm[\"omg\"].as<double>() << '\\n';\n\tfilename+=\"omega\"+std::to_string(vm[\"omg\"].as<double>()).substr(0, 3);\n      }\n       if (vm.count(\"gam\"))\n      {\n\tstd::cout << \"gamma: \" << vm[\"gam\"].as<double>() << '\\n';\n\tfilename+=\"gam\"+std::to_string(vm[\"gam\"].as<double>()).substr(0, 4);\n      }\n       if (vm.count(\"dt\"))\n      {\n\tstd::cout << \"dt: \" << vm[\"dt\"].as<double>() << '\\n';\n\tfilename+=\"dt\"+std::to_string(vm[\"dt\"].as<double>()).substr(0, 4);\n      }\n       if (vm.count(\"tot\"))\n      {\n\tstd::cout << \"total time: \" << vm[\"tot\"].as<double>() << '\\n';\n\tfilename+=\"tot\"+std::to_string(vm[\"tot\"].as<double>()).substr(0, 3);\n      }\n       if (vm.count(\"pb\"))\n      {\n\tstd::cout << \"PB: \" << vm[\"pb\"].as<bool>() << '\\n';\n\tfilename+=\"PB\"+std::to_string(vm[\"pb\"].as<bool>());\n      }\n    }\n  }\n  catch (const boost::program_options::error &ex)\n  {\n    std::cerr << ex.what() << '\\n';\n    return 0;\n  }\n\n  //std::vector<int> ee(L, 0);\n  // ee[L-1]=1;\n\n  ElectronState estate1(L, 1);\n  ElectronBasis e( L, 1);\n  \n  //  std::cout<< e<<std::endl;\nstd::vector<size_t> es(L, 0);\n      es[0]=1;\n      ElectronState aa(es);\n  PhononBasis ph(L, M);\n  //       std::cout<< ph<<std::endl;\n      HolsteinBasis TP(e, ph);\n      std::vector<size_t> state(L, 0);\n      //std::fill(state.begin(), state.end(), 1);\n  BosonState b2(state, M);\n \n     auto it3=TP.lbasis.find(aa.GetId());\n     auto it4=TP.rbasis.find(b2.GetId());\n     size_t StateNr= Position(*it4)*TP.lbasis.dim +Position(*it3);\n     //       std::cout<< TP << std::endl;\n     //    std::cout<< b2.GetId()<<std::endl;\n     // \tstd::cout<< b2.GetId()<<std::endl;\n      std::cout<<\"state nr \"<< StateNr<<std::endl;                \n         Eigen::VectorXcd inistate(TP.dim);\n\t double para=1;\n\t \n \t Mat O0=Operators::NumberOperatore_1(TP, e, para, 0,  PB);\n\t Mat O1=Operators::NumberOperatore_1(TP, e, para, 1,  PB);\n\t Mat Nph0=Operators::NumberOperatorph_1(TP, ph, para, 0,  PB);\n\t Mat Nph1=Operators::NumberOperatorph_1(TP, ph, para, 1,  PB);\n\t Mat X0=std::sqrt(1./2)*(Operators::BosonDOperator_1(TP, ph, para,0,  PB)+Operators::BosonCOperator_1(TP, ph, para,0,  PB));\n\t Mat X1=std::sqrt(1./2)*(Operators::BosonDOperator_1(TP, ph, para,1,  PB)+Operators::BosonCOperator_1(TP, ph, para,1,  PB));\n\t Mat P0=std::sqrt(1./2)*(Operators::BosonCOperator_1(TP, ph, para,0,  PB)-Operators::BosonDOperator_1(TP, ph, para,0,  PB));\n\t Mat P1=std::sqrt(1./2)*(Operators::BosonCOperator_1(TP, ph, para,1,  PB)-Operators::BosonDOperator_1(TP, ph, para,1,  PB));\n\t Mat Q1=X0-X1;\n\t Mat QP1=P0-P1;\n\t Mat Q2=Q1*(X0-X1);\n\t Mat QP2=QP1*(P0-P1);\n\t Mat Q3=Q2*(X0-X1);\n\t Mat QP3=QP2*(P0-P1);\n\t Mat Q4=Q3*(X0-X1);\n\t Mat QP4=QP3*(P0-P1);\n\t //\t \n   inistate.setZero();\n\n   inistate[StateNr]=1;\n   \t          Eigen::VectorXcd i0=inistate;\n\t\t  std::cout<<\"dim \" <<e.dim << std::endl;\n\t\t  \n           std::cout<< TP.dim << std::endl;     \n      Mat EK=Operators::EKinOperatorL(TP, e, t0, PB);\n      Mat Ebdag=Operators::NBosonCOperator(TP, ph, gamma, PB);\n      Mat Eb=Operators::NBosonDOperator(TP, ph, gamma, PB);\n      Mat Eph=Operators::NumberOperator(TP, ph, omega,  PB);\n      \n      //Mat E=Operators::NumberOperatore(TP, e, 1, false);\n      //    std::cout<< HH << std::xbendl;\n      Eigen::VectorXd eigenVals(TP.dim);\n      Mat H=EK+Eph  +Ebdag + Eb;\n      // making one Hamiltonian with infinite chem pot on one site\n       double mu=100000;\n       Eigen::VectorXd eigenVals_mit_pot(TP.dim);\n       Mat H_mit_pot=H+Operators::NumberOperatore_1(TP, e, mu, 1,  PB);\n      //    \n \n    Eigen::MatrixXd HH=Eigen::MatrixXd(H);\n        Eigen::MatrixXd HH_mit_pot=Eigen::MatrixXd(H_mit_pot);\n     Eigen::MatrixXd H_cop=Eigen::MatrixXd(H);\n     Eigen::MatrixXd H_mit_pot_cop=Eigen::MatrixXd(H_mit_pot);\n    //        std::cout<< HH<<std::endl;\n        Eigen::MatrixXd N=Eigen::MatrixXd(Eph);\n\t\n     Many_Body::diagMat(HH, eigenVals);\n     Many_Body::diagMat(HH_mit_pot, eigenVals_mit_pot);\n         Eigen::VectorXd energy(TP.dim);\n\t std::vector<double> ek_vec;\n    \t   std::vector<double> n0_vec;\n\t   std::vector<double> n1_vec;\n\t   std::vector<double> nph0_vec;\n\t   std::vector<double> nph1_vec;\n\t   std::vector<double> x0_vec;\n\t   std::vector<double> x1_vec;\n\t   std::vector<double> p0_vec;\n\t   std::vector<double> p1_vec;\n\t   std::vector<double> q1_vec;\n\t   std::vector<double> qp1_vec;\n\t   std::vector<double> q2_vec;\n\t   std::vector<double> qp2_vec;\n\t   std::vector<double> q3_vec;\n\t   std::vector<double> qp3_vec;\n\t   std::vector<double> q4_vec;\n\t   std::vector<double> qp4_vec;\n\t   std::vector<double> ensvec_vec;\n\t   //\t   Eigen::MatrixXd PHD2=HH.adjoint()*N.selfadjointView<Lower>()*HH;\n\t   std::cout<< \"eigenVals(0) \"<<eigenVals(0)<<std::endl;\n\t   //\t    std::cout<< \"eigenValseigenVals_mit_pot(0) \"<<eigenVals_mit_pot(0)<<std::endl;\n     Eigen::MatrixXcd evExp=TimeEv::EigenvalExponent(eigenVals, dt);\n   Eigen::MatrixXcd cEVec=HH.cast<std::complex<double>>();\n    Eigen::MatrixXcd cEVec_mit_pot=HH_mit_pot.cast<std::complex<double>>();\n   Eigen::VectorXcd newIn=cEVec_mit_pot.col(0);\n   //\n     \n   \n      //\n   int i=0;\n\n   // O=H;\n   std::complex<double> E_in=(newIn.adjoint()*(H_cop*newIn))(0);\n   std::complex<double> X_in=(newIn.adjoint()*(X0*newIn))(0);\n      std::complex<double> n_in=(newIn.adjoint()*(O0*newIn))(0);\n           std::complex<double> N_in=(newIn.adjoint()*(Nph0*newIn))(0);\n   std::cout<< \" init energy \"<<E_in<<std::endl;\n   std::cout<< \" init n site 0 \"<<n_in<<std::endl;\n   std::cout<< \" init N site 0 \"<<N_in<<std::endl;\n      std::cout<< \" init X site 0 \"<<X_in<<std::endl;\n        while(i*dt<tot)\n       {\n\n       \t \n  \t   \t std::complex<double> ek=(newIn.adjoint()*(EK*newIn))(0);\n   \t  \t std::complex<double> n0=(newIn.adjoint()*(O0*newIn))(0);\n \t\t std::complex<double> nph0=(newIn.adjoint()*(Nph0*newIn))(0);\n \t\t std::complex<double> nph1=(newIn.adjoint()*(Nph1*newIn))(0);\n \t\t std::complex<double> e0=(newIn.adjoint()*(H_cop*newIn))(0);\n \t\t std::complex<double> n1=(newIn.adjoint()*(O1*newIn))(0);\n \t\t std::complex<double> x0=(newIn.adjoint()*(X0*newIn))(0);\n \t\t std::complex<double> x1=(newIn.adjoint()*(X1*newIn))(0);\n \t\t std::complex<double> p0=std::complex<double>(0,1)*(newIn.adjoint()*(P0*newIn))(0);\n \t\t std::complex<double> p1=std::complex<double>(0,1)*(newIn.adjoint()*(P1*newIn))(0);\n \t\t std::complex<double> q1=(newIn.adjoint()*(Q1*newIn))(0);\n \t\t std::complex<double> qp1=std::complex<double>(0,1)*(newIn.adjoint()*(QP1*newIn))(0);\n \t\t std::complex<double> q2=(newIn.adjoint()*(Q2*newIn))(0);\n \t\t std::complex<double> qp2=std::complex<double>(0,1)*std::complex<double>(0,1)*(newIn.adjoint()*(QP2*newIn))(0);\n \t\t std::complex<double> q3=(newIn.adjoint()*(Q3*newIn))(0);\n \t\t std::complex<double> qp3=std::complex<double>(0,1)*std::complex<double>(0,1)*std::complex<double>(0,1)*(newIn.adjoint()*(QP3*newIn))(0);\n \t\t std::complex<double> q4=(newIn.adjoint()*(Q4*newIn))(0);\n \t\t std::complex<double> qp4=std::complex<double>(0,1)*std::complex<double>(0,1)*std::complex<double>(0,1)*std::complex<double>(0,1)*(newIn.adjoint()*(QP4*newIn))(0);\n\t\t ek_vec.push_back(real(ek));\n \t\t n0_vec.push_back(real(n0));\n \t\t n1_vec.push_back(real(n1));\n \t\t nph0_vec.push_back(real(nph0));\n \t\t nph1_vec.push_back(real(nph1));\n \t\t x0_vec.push_back(real(x0));\n \t\t x1_vec.push_back(real(x1));\n \t\t p0_vec.push_back(real(p0));\n \t\t p1_vec.push_back(real(p1));\n \t\t q1_vec.push_back(real(q1));\n \t\t qp1_vec.push_back(real(qp1));\n \t\t q2_vec.push_back(real(q2));\n \t\t qp2_vec.push_back(real(qp2));\n \t\t q3_vec.push_back(real(q3));\n \t\t qp3_vec.push_back(real(qp3));\n \t\t q4_vec.push_back(real(q4));\n \t\t qp4_vec.push_back(real(qp4));\n \t\t //\t std::complex<double> c=(inistate.adjoint()*(newIn))(0);\n  \n\n   \t\t\t// \toutputVals(i)=real(c);\n   \t\t\t// \toutputVals2(i)=real(c2);\n        \t\t// outputTime(i)=i*dt;\n \t\t std::cout<< std::setprecision(8)<< \" ene \"<< E_in-e0<< \" partcle \"<<n0 +n1<<\"  \" << x0 <<x1 << \"  \" << p0 << \"  \"  << p1 <<\"  \"<< \" dt \"<< i*dt<< std::endl;\n \t //\t  \t BOOST_CHECK(std::abs(real(c2)-real(c))<Many_Body::err);\n \t TimeEv::timeev_exact(newIn, cEVec, evExp);\n   \t i++;\n \t     \t             }\n\n //std::cout<< MatrixXd(OBS2) << std::endl;\n // Eigen::MatrixXd OBS22=HH.adjoint()*(OBS2.selfadjointView<Lower>())*HH;\n // Eigen::VectorXd diagobs2=OBS22.diagonal();\n \tstd::cout<< n0_vec.size()<< \"  i \"<< i << std::endl;\n // std::cout<<diagobs2(0)<<std::endl; \n   filename+=\".bin\";\n   bin_write(dirname+\"/ek\"+filename, ek_vec);\n         bin_write(dirname+\"/n0\"+filename, n0_vec);\n \t   bin_write(dirname+\"/n1\"+filename, n1_vec);\n \t   bin_write(dirname+\"/nph0\"+filename, nph0_vec);\n \t   bin_write(dirname+\"/nph1\"+filename, nph1_vec);\n \t     bin_write(dirname+\"/x0\"+filename, x0_vec);\n \t     bin_write(dirname+\"/x1\"+filename, x1_vec);\n \t       bin_write(dirname+\"/p0\"+filename, p0_vec);\n \t         bin_write(dirname+\"/p1\"+filename, p1_vec);\n \t\t bin_write(dirname+\"/q1\"+filename, q1_vec);\n \t\t bin_write(dirname+\"/qp1\"+filename, qp1_vec);\n \t\t bin_write(dirname+\"/q2\"+filename, q2_vec);\n \t\t bin_write(dirname+\"/qp2\"+filename, qp2_vec);\n \t\t bin_write(dirname+\"/q3\"+filename, q3_vec);\n \t\t bin_write(dirname+\"/qp3\"+filename, qp3_vec);\n \t\t bin_write(dirname+\"/q4\"+filename, q4_vec);\n \t\t bin_write(dirname+\"/qp4\"+filename, qp4_vec);\n  return 0;\n}\n \n", "meta": {"hexsha": "bac343573b0c75660f6e4ceb4ab0234fd231e3f8", "size": 11250, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/holsttimeexactpol.cpp", "max_stars_repo_name": "jansendavid/many-body-lib", "max_stars_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/holsttimeexactpol.cpp", "max_issues_repo_name": "jansendavid/many-body-lib", "max_issues_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/holsttimeexactpol.cpp", "max_forks_repo_name": "jansendavid/many-body-lib", "max_forks_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3959044369, "max_line_length": 166, "alphanum_fraction": 0.6000888889, "num_tokens": 3751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085808877581, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.41104649143095984}}
{"text": "#ifndef STAN_MATH_TORSTEN_PKMODEL_PRED_PREDSS_ONECPT_HPP\n#define STAN_MATH_TORSTEN_PKMODEL_PRED_PREDSS_ONECPT_HPP\n\n#include <stan/math/torsten/PKModel/Pred/PolyExp.hpp>\n#include <stan/math/torsten/PKModel/functors/check_mti.hpp>\n#include <stan/math/torsten/PKModel/ModelParameters.hpp>\n#include <stan/math/prim/mat/fun/Eigen.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <iostream>\n#include <vector>\n#include <limits>\n\nnamespace torsten {\n\nstruct PredSS_oneCpt {\n  PredSS_oneCpt() { }\n\n  /**\n   * One compartment model with first-order absorption.\n   * Calculate amount in each compartment at the end of a steady-state dosing interval\n   * or during a steady-state constant input (if ii=0)\n   *\n   * If the initial time equals the time of the event, than the code does\n   * not run the ode integrator, and sets the predicted amount equal to the\n   * initial condition. This can happen when we are dealing with events that\n   * occur simultaneously. The change to the predicted amount caused by bolus\n   * dosing events is handled later in the main Pred function.\n   *\n   * @tparam T_time type of scalar for time\n   * @tparam T_amt type of scalar for amount\n   * @tparam T_rate type of scalar for rate\n   * @tparam T_ii type of scalar for interdose interval\n   * @tparam T_parameters type of scalar for model parameters\n   * @tparam T_addParm type of scalar for additional model parameters\n   * @param[in] parameter model parameters at current event\n   * @param[in] rate\n   * @param[in] ii interdose interval\n   * @param[in] cmt compartment in which the event occurs\n   * @return an eigen vector that contains predicted amount in each compartment\n   *   at the current event.\n   */\n  template<typename T_time, typename T_amt, typename T_rate, typename T_ii,\n           typename T_parameters, typename T_biovar, typename T_tlag>\n  Eigen::Matrix<typename boost::math::tools::promote_args<T_amt, T_rate,\n    T_ii, T_parameters>::type, 1, Eigen::Dynamic>\n  operator()(const ModelParameters<T_time, T_parameters, T_biovar,\n             T_tlag>& parameter,\n             const T_amt& amt,\n             const T_rate& rate,\n             const T_ii& ii,\n             const int& cmt) const {\n    typedef typename boost::math::tools::promote_args<T_amt, T_rate,\n      T_ii, T_parameters>::type scalar;\n\n    double inf = std::numeric_limits<double>::max();  // \"infinity\"\n\n    T_parameters CL = parameter.get_RealParameters(false)[0],\n      V2 = parameter.get_RealParameters(false)[1],\n      ka = parameter.get_RealParameters(false)[2],\n      k10 = CL/V2;\n\n    std::vector<scalar> alpha(2, 0);\n    alpha[0] = k10;\n    alpha[1] = ka;\n\n    Eigen::Matrix<scalar, 1, Eigen::Dynamic> pred\n      = Eigen::Matrix<scalar, 1, Eigen::Dynamic>::Zero(2);\n    std::vector<scalar> a(2, 0);\n    if (rate == 0) {  // bolus dose\n      if (cmt == 1) {\n        a[0] = 0;\n        a[1] = 1;\n        pred(0) = PolyExp(ii, amt, 0, 0, ii, true, a, alpha, 2);\n        a[0] = ka / (ka - alpha[0]);\n        a[1] = -a[0];\n        pred(1) = PolyExp(ii, amt, 0, 0, ii, true, a, alpha, 2);\n      } else {  // cmt=2\n        a[0] = 1;\n        pred(1) = PolyExp(ii, amt, 0, 0, ii, true, a, alpha, 1);\n      }\n    } else if (ii > 0) {  // multiple truncated infusions\n      double delta = unpromote(amt / rate);\n      static const char* function(\"Steady State Event\");\n      check_mti(amt, delta, ii, function);\n\n      if (cmt == 1) {\n        a[0] = 0;\n        a[1] = 1;\n        pred(0) = PolyExp(ii, 0, rate, amt / rate, ii, true, a, alpha, 2);\n        a[0] = ka / (ka - alpha[0]);\n        a[1] = -a[0];\n        pred(1) = PolyExp(ii, 0, rate, amt / rate, ii, true, a, alpha, 2);\n      } else {  // cmt = 2\n        a[0] = 1;\n        pred(1) = PolyExp(ii, 0, rate, amt / rate, ii, true, a, alpha, 1);\n      }\n    } else {  // constant infusion\n      if (cmt == 1) {\n        a[0] = 0;\n        a[1] = 1;\n        pred(0) = PolyExp(0, 0, rate, inf, 0, true, a, alpha, 2);\n        a[0] = ka / (ka - alpha[0]);\n        a[1] = -a[0];\n        pred(1) = PolyExp(0, 0, rate, inf, 0, true, a, alpha, 2);\n      } else {  // cmt = 2\n        a[0] = 1;\n        pred(1) = PolyExp(0, 0, rate, inf, 0, true, a, alpha, 1);\n      }\n    }\n    return pred;\n  }\n};\n\n}\n#endif\n", "meta": {"hexsha": "e6d6135423e874366e8931c9c88747bbf43f2fed", "size": 4212, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/PKModel/Pred/PredSS_oneCpt.hpp", "max_stars_repo_name": "csetraynor/Torsten", "max_stars_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/PKModel/Pred/PredSS_oneCpt.hpp", "max_issues_repo_name": "csetraynor/Torsten", "max_issues_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/PKModel/Pred/PredSS_oneCpt.hpp", "max_forks_repo_name": "csetraynor/Torsten", "max_forks_repo_head_hexsha": "55b59b8068e2a539346f566ec698c755a9e3536c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3103448276, "max_line_length": 86, "alphanum_fraction": 0.611348528, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031738057795403, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.4109973728808291}}
{"text": "/*\n * ConvolutionMeasure.cpp\n *\n *  Created on: 31.08.2017\n *      Author: thies\n */\n\n#include <base/Norm.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/timer.h>\n#include <measurements/ConvolutionMeasure.h>\n#include <measurements/SensorValues.h>\n#include <stddef.h>\n#include <cmath>\n#include <iostream>\n#include <string>\n#include <vector>\n\nnamespace wavepi {\nnamespace measurements {\n\nusing namespace dealii;\nusing namespace wavepi::base;\n\ntemplate <int dim>\nConvolutionMeasure<dim>::ConvolutionMeasure(std::shared_ptr<SpaceTimeMesh<dim>> mesh,\n                                            std::shared_ptr<SensorDistribution<dim>> points,\n                                            std::shared_ptr<Norm<DiscretizedFunction<dim>>> norm,\n                                            std::shared_ptr<LightFunction<dim>> delta_shape, double delta_scale_space,\n                                            double delta_scale_time)\n    : mesh(mesh),\n      sensor_distribution(points),\n      norm(norm),\n      delta_shape(delta_shape),\n      delta_scale_space(delta_scale_space),\n      delta_scale_time(delta_scale_time) {\n  AssertThrow(mesh && delta_shape && norm, ExcNotInitialized());\n}\n\ntemplate <int dim>\nConvolutionMeasure<dim>::ConvolutionMeasure(std::shared_ptr<SpaceTimeMesh<dim>> mesh,\n                                            std::shared_ptr<SensorDistribution<dim>> points,\n                                            std::shared_ptr<Norm<DiscretizedFunction<dim>>> norm)\n    : mesh(mesh),\n      sensor_distribution(points),\n      norm(norm),\n      delta_shape(),\n      delta_scale_space(0.0),\n      delta_scale_time(0.0) {\n  AssertThrow(mesh && norm, ExcNotInitialized());\n}\n\ntemplate <int dim>\nstd::vector<std::vector<std::pair<size_t, double>>> ConvolutionMeasure<dim>::compute_jobs() const {\n  std::vector<std::vector<std::pair<size_t, double>>> jobs(mesh->length());\n\n  size_t sensor_offset = 0;\n  for (size_t mti = 0; mti < sensor_distribution->get_times().size(); mti++) {\n    double mtime = sensor_distribution->get_times()[mti];\n\n    for (size_t ti = 0; ti < mesh->get_times().size(); ti++) {\n      double t = mesh->get_time(ti);\n\n      if (t < mtime - delta_scale_time) continue;\n      if (t > mtime + delta_scale_time) break;\n\n      double factor = 0.0;\n\n      if (ti > 0) factor += (t - mesh->get_time(ti - 1)) / 2;\n\n      if (ti + 1 < mesh->get_times().size()) factor += (mesh->get_time(ti + 1) - t) / 2;\n\n      // norm correction\n      factor *= delta_scale_time * pow(delta_scale_space, dim);\n\n      for (size_t msi = 0; msi < sensor_distribution->get_points_per_time(mti).size(); msi++)\n        jobs[ti].emplace_back(msi + sensor_offset, factor);\n    }\n\n    sensor_offset += sensor_distribution->get_points_per_time(mti).size();\n  }\n\n  return jobs;\n}\n\ntemplate <int dim>\nSensorValues<dim> ConvolutionMeasure<dim>::evaluate(const DiscretizedFunction<dim>& field) {\n  AssertThrow(delta_shape && delta_scale_space > 0 && delta_scale_time > 0, ExcNotInitialized());\n  AssertThrow(sensor_distribution && sensor_distribution->size(), ExcNotInitialized());\n  AssertThrow(mesh == field.get_mesh(), ExcMessage(\"ConvolutionMeasure called with different meshes\"));\n  AssertThrow(*norm == *field.get_norm(), ExcMessage(\"ConvolutionMeasure called with different norms\"));\n\n  LightFunctionWrapper wrapper(delta_shape, delta_scale_space, delta_scale_time);\n  SensorValues<dim> res(sensor_distribution);\n\n  auto jobs = compute_jobs();\n\n  for (size_t ji = 0; ji < jobs.size(); ji++) {\n    auto dof = field.get_mesh()->get_dof_handler(ji);\n    Vector<double> interp_shape(dof->n_dofs());\n\n    wrapper.set_time(mesh->get_time(ji));\n\n    for (size_t k = 0; k < jobs[ji].size(); k++) {\n      wrapper.set_offset((*sensor_distribution)[jobs[ji][k].first]);\n\n      interp_shape = 0.0;\n      VectorTools::interpolate(*dof, wrapper, interp_shape);\n      mesh->get_constraint_matrix(ji)->distribute(interp_shape);\n\n      res[jobs[ji][k].first] +=\n          jobs[ji][k].second * mesh->get_mass_matrix(ji)->matrix_scalar_product(interp_shape, field[ji]);\n    }\n  }\n\n  return res;\n}\n\ntemplate <int dim>\nSensorValues<dim> ConvolutionMeasure<dim>::zero() {\n  return SensorValues<dim>(sensor_distribution);\n}\n\ntemplate <int dim>\nDiscretizedFunction<dim> ConvolutionMeasure<dim>::adjoint(const SensorValues<dim>& measurements) {\n  AssertThrow(delta_shape && delta_scale_space > 0 && delta_scale_time > 0, ExcNotInitialized());\n  AssertThrow(mesh && sensor_distribution && sensor_distribution->size(), ExcNotInitialized());\n\n  DiscretizedFunction<dim> res(mesh);\n  auto jobs = compute_jobs();\n\n  LightFunctionWrapper wrapper(delta_shape, delta_scale_space, delta_scale_time);\n\n  for (size_t ji = 0; ji < jobs.size(); ji++) {\n    auto dof_handler = mesh->get_dof_handler(ji);\n    wrapper.set_time(mesh->get_time(ji));\n    Vector<double> tmp(dof_handler->n_dofs());\n\n    for (size_t i = 0; i < jobs[ji].size(); i++) {\n      size_t sensor_idx = jobs[ji][i].first;\n\n      wrapper.set_offset((*sensor_distribution)[sensor_idx]);\n\n      tmp = 0.0;\n\n      // interpolate makes sense if the forward measurement operator also uses the interpolation.\n      VectorTools::interpolate(*dof_handler, wrapper, tmp);\n      mesh->get_constraint_matrix(ji)->distribute(tmp);\n\n      res[ji].add(jobs[ji][i].second * measurements[sensor_idx], tmp);\n    }\n  }\n\n  res.set_norm(norm);\n\n  // res has coefficients in there, not dot products.\n  res.dot_mult_mass_and_transform_inverse();\n\n  return res;\n}\n\ntemplate <int dim>\nvoid ConvolutionMeasure<dim>::declare_parameters(ParameterHandler& prm) {\n  prm.enter_subsection(\"ConvolutionMeasure\");\n  {\n    prm.declare_entry(\"radius space\", \"0.2\", Patterns::Double(0), \"scaling of shape function in spatial variables\");\n    prm.declare_entry(\"radius time\", \"0.2\", Patterns::Double(0), \"scaling of shape function in time variable\");\n    prm.declare_entry(\"shape\", \"hat\", Patterns::Selection(\"hat|constant\"),\n                      \"shape of the delta approximating function. \");\n  }\n  prm.leave_subsection();\n}\n\ntemplate <int dim>\nvoid ConvolutionMeasure<dim>::get_parameters(ParameterHandler& prm) {\n  prm.enter_subsection(\"ConvolutionMeasure\");\n  {\n    auto shape_desc = prm.get(\"shape\");\n\n    if (shape_desc == \"hat\")\n      delta_shape = std::make_shared<HatShape>();\n    else if (shape_desc == \"constant\")\n      delta_shape = std::make_shared<ConstShape>();\n    else\n      AssertThrow(false, ExcMessage(\"Unknown delta shape: \" + shape_desc));\n\n    delta_scale_space = prm.get_double(\"radius space\");\n    delta_scale_time  = prm.get_double(\"radius time\");\n\n    AssertThrow(delta_scale_space * delta_scale_time > 0.0,\n                ExcMessage(\"sensor radii in time and space have to be positive!\"));\n  }\n  prm.leave_subsection();\n}\n\ntemplate class ConvolutionMeasure<1>;\ntemplate class ConvolutionMeasure<2>;\ntemplate class ConvolutionMeasure<3>;\n\n}  // namespace measurements\n} /* namespace wavepi */\n", "meta": {"hexsha": "9497ba1f8c9ad5c93691e6fee11baa5189bcc5c5", "size": 6926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/measurements/ConvolutionMeasure.cpp", "max_stars_repo_name": "thiesgerken/wavepi", "max_stars_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/measurements/ConvolutionMeasure.cpp", "max_issues_repo_name": "thiesgerken/wavepi", "max_issues_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/measurements/ConvolutionMeasure.cpp", "max_forks_repo_name": "thiesgerken/wavepi", "max_forks_repo_head_hexsha": "5af37946dcc1910ad1cccdc76d2e2f546eeafec4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2871287129, "max_line_length": 118, "alphanum_fraction": 0.6728270286, "num_tokens": 1652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342624, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.4109973632373875}}
{"text": "﻿/* This file is part of the KDE project\n   Copyright (C) 1998-2002 The KSpread Team <calligra-devel@kde.org>\n   Copyright (C) 2005 Tomas Mecir <mecirt@gmail.com>\n   Copyright 2007 Sascha Pfau <MrPeacock@gmail.com>\n   Copyright (C) 2010 Carlos Licea <carlos@kdab.com>\n   Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).\n     Contact: Suresh Chande suresh.chande@nokia.com\n\n   This library is free software; you can redistribute it and/or\n   modify it under the terms of the GNU Library General Public\n   License as published by the Free Software Foundation; only\n   version 2 of the License.\n\n   This library is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n   Library General Public License for more details.\n\n   You should have received a copy of the GNU Library General Public License\n   along with this library; see the file COPYING.LIB.  If not, write to\n   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n   Boston, MA 02110-1301, USA.\n*/\n\n// built-in math functions\n#include \"MathModule.h\"\n\n// needed for RANDBINOM and so\n#include <math.h>\n#include <qmath.h>\n\n#include \"SheetsDebug.h\"\n#include \"FunctionModuleRegistry.h\"\n#include \"Function.h\"\n#include \"FunctionRepository.h\"\n#include \"ValueCalc.h\"\n#include \"ValueConverter.h\"\n\n// needed for SUBTOTAL:\n#include \"Cell.h\"\n#include \"Sheet.h\"\n#include \"RowColumnFormat.h\"\n#include \"RowFormatStorage.h\"\n\n// needed by MDETERM and MINVERSE\n// Don't show this warning: it's an issue in eigen\n#ifdef __GNUC__\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n\n#ifdef ENABLE_EIGEN\n#include <Eigen/LU>\n#endif\n\nusing namespace Calligra::Sheets;\n\n// RANDBINOM and RANDNEGBINOM won't support arbitrary precision\n\n// prototypes\nValue func_abs(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_ceil(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_ceiling(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_count(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_counta(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_countblank(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_countif(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_countifs(valVector args, ValueCalc *calc, FuncExtra *e);\nValue func_cur(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_div(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_eps(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_even(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_exp(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_fact(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_factdouble(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_fib(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_floor(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_gamma(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_gcd(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_int(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_inv(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_kproduct(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_lcm(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_ln(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_log2(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_log10(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_logn(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_max(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_maxa(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_mdeterm(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_min(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_mina(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_minverse(valVector args, ValueCalc* calc, FuncExtra*);\nValue func_mmult(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_mod(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_mround(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_mult(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_multinomial(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_munit(valVector args, ValueCalc* calc, FuncExtra*);\nValue func_odd(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_pow(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_quotient(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_product(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_rand(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_randbetween(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_randbernoulli(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_randbinom(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_randexp(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_randnegbinom(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_randnorm(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_randpoisson(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_rootn(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_round(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_rounddown(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_roundup(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_seriessum(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_sign(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_sqrt(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_sqrtpi(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_subtotal(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_sum(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_suma(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_sumif(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_sumifs(valVector args, ValueCalc *calc, FuncExtra *);     //here\nValue func_sumsq(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_transpose(valVector args, ValueCalc *calc, FuncExtra *);\nValue func_trunc(valVector args, ValueCalc *calc, FuncExtra *);\n\n\n// Value func_multipleOP (valVector args, ValueCalc *calc, FuncExtra *);\n\n\nCALLIGRA_SHEETS_EXPORT_FUNCTION_MODULE(\"kspreadmathmodule.json\", MathModule)\n\n\nMathModule::MathModule(QObject* parent, const QVariantList&)\n        : FunctionModule(parent)\n{\n    Function *f;\n\n    /*\n      f = new Function (\"MULTIPLEOPERATIONS\", func_multipleOP);\n    add(f);\n    */\n\n    // functions that don't take array parameters\n    f = new Function(\"ABS\",           func_abs);\n    add(f);\n    f = new Function(\"CEIL\",          func_ceil);\n    add(f);\n    f = new Function(\"CEILING\",       func_ceiling);\n    f->setParamCount(1, 3);\n    add(f);\n    f = new Function(\"CUR\",           func_cur);\n    add(f);\n    f = new Function(\"EPS\",           func_eps);\n    f->setParamCount(0);\n    add(f);\n    f = new Function(\"EVEN\",          func_even);\n    add(f);\n    f = new Function(\"EXP\",           func_exp);\n    add(f);\n    f = new Function(\"FACT\",          func_fact);\n    add(f);\n    f = new Function(\"FACTDOUBLE\",    func_factdouble);\n    f->setAlternateName(\"COM.SUN.STAR.SHEET.ADDIN.ANALYSIS.GETFACTDOUBLE\");\n    add(f);\n    f = new Function(\"FIB\",           func_fib);  // Calligra Sheets-specific, like Quattro-Pro's FIB\n    add(f);\n    f = new Function(\"FLOOR\",         func_floor);\n    f->setParamCount(1, 3);\n    add(f);\n    f = new Function(\"GAMMA\",         func_gamma);\n    add(f);\n    f = new Function(\"INT\",           func_int);\n    add(f);\n    f = new Function(\"INV\",           func_inv);\n    add(f);\n    f = new Function(\"LN\",            func_ln);\n    add(f);\n    f = new Function(\"LOG\",           func_logn);\n    f->setParamCount(1, 2);\n    add(f);\n    f = new Function(\"LOG2\",          func_log2);\n    add(f);\n    f = new Function(\"LOG10\",         func_log10);\n    add(f);\n    f = new Function(\"LOGN\",          func_logn);\n    f->setParamCount(2);\n    add(f);\n    f = new Function(\"MOD\",           func_mod);\n    f->setParamCount(2);\n    add(f);\n    f = new Function(\"MROUND\",        func_mround);\n    f->setAlternateName(\"COM.SUN.STAR.SHEET.ADDIN.ANALYSIS.GETMROUND\");\n    f->setParamCount(2);\n    add(f);\n    f = new Function(\"MULTINOMIAL\",   func_multinomial);\n    f->setAlternateName(\"COM.SUN.STAR.SHEET.ADDIN.ANALYSIS.GETMULTINOMIAL\");\n    f->setParamCount(1, -1);\n    add(f);\n    f = new Function(\"ODD\",           func_odd);\n    add(f);\n    f = new Function(\"POW\",         func_pow);\n    f->setParamCount(2);\n    add(f);\n    f = new Function(\"POWER\",         func_pow);\n    f->setParamCount(2);\n    add(f);\n    f = new Function(\"QUOTIENT\",      func_quotient);\n    f->setAlternateName(\"COM.SUN.STAR.SHEET.ADDIN.ANALYSIS.GETQUOTIENT\");\n    f->setParamCount(2);\n    add(f);\n    f = new Function(\"RAND\",          func_rand);\n    f->setParamCount(0);\n    add(f);\n    f = new Function(\"RANDBERNOULLI\", func_randbernoulli);\n    add(f);\n    f = new Function(\"RANDBETWEEN\",   func_randbetween);\n    f->setAlternateName(\"COM.SUN.STAR.SHEET.ADDIN.ANALYSIS.GETRANDBETWEEN\");\n    f->setParamCount(2);\n    add(f);\n    f = new Function(\"RANDBINOM\",     func_randbinom);\n    f->setParamCount(2);\n    add(f);\n    f = new Function(\"RANDEXP\",       func_randexp);\n    add(f);\n    f = new Function(\"RANDNEGBINOM\",  func_randnegbinom);\n    f->setParamCount(2);\n    add(f);\n    f = new Function(\"RANDNORM\",      func_randnorm);\n    f->setParamCount(2);\n    add(f);\n    f = new Function(\"RANDPOISSON\",   func_randpoisson);\n    add(f);\n    f = new Function(\"ROOTN\",         func_rootn);\n    f->setParamCount(2);\n    add(f);\n    f = new Function(\"ROUND\",         func_round);\n    f->setParamCount(1, 2);\n    add(f);\n    f = new Function(\"ROUNDDOWN\",     func_rounddown);\n    f->setParamCount(1, 2);\n    add(f);\n    f = new Function(\"ROUNDUP\",       func_roundup);\n    f->setParamCount(1, 2);\n    add(f);\n    f = new Function(\"SIGN\",          func_sign);\n    add(f);\n    f = new Function(\"SQRT\",          func_sqrt);\n    add(f);\n    f = new Function(\"SQRTPI\",        func_sqrtpi);\n    f->setAlternateName(\"COM.SUN.STAR.SHEET.ADDIN.ANALYSIS.GETSQRTPI\");\n    add(f);\n    f = new Function(\"TRUNC\",         func_trunc);\n    f->setParamCount(1, 2);\n    add(f);\n\n    // functions that operate over arrays\n    f = new Function(\"COUNT\",         func_count);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"COUNTA\",        func_counta);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"COUNTBLANK\",    func_countblank);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"COUNTIF\",       func_countif);\n    f->setParamCount(2);\n    f->setAcceptArray();\n    f->setNeedsExtra(true);\n    add(f);\n    f = new Function(\"COUNTIFS\",         func_countifs);\n    f->setParamCount(2, -1);\n    f->setAcceptArray();\n    f->setNeedsExtra(true);\n    add(f);\n    f = new Function(\"DIV\",           func_div);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"G_PRODUCT\",     func_kproduct);  // Gnumeric compatibility\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"GCD\",           func_gcd);\n    f->setAlternateName(\"COM.SUN.STAR.SHEET.ADDIN.ANALYSIS.GETGCD\");\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"KPRODUCT\",      func_kproduct);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"LCM\",           func_lcm);\n    f->setAlternateName(\"COM.SUN.STAR.SHEET.ADDIN.ANALYSIS.GETLCM\");\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"MAX\",           func_max);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"MAXA\",          func_maxa);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"MDETERM\",          func_mdeterm);\n    f->setParamCount(1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"MIN\",           func_min);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"MINA\",          func_mina);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"MINVERSE\",         func_minverse);\n    f->setParamCount(1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"MMULT\",          func_mmult);\n    f->setParamCount(2);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"MULTIPLY\",      func_product);   // same as PRODUCT\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"MUNIT\",         func_munit);\n    f->setParamCount(1);\n    add(f);\n    f = new Function(\"PRODUCT\",       func_product);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"SERIESSUM\",     func_seriessum);\n    f->setParamCount(3, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"SUM\",           func_sum);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"SUMA\",          func_suma);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"SUBTOTAL\",      func_subtotal);\n    f->setParamCount(2);\n    f->setAcceptArray();\n    f->setNeedsExtra(true);\n    add(f);\n    f = new Function(\"SUMIF\",         func_sumif);\n    f->setParamCount(2, 3);\n    f->setAcceptArray();\n    f->setNeedsExtra(true);\n    add(f);\n    f = new Function(\"SUMIFS\",         func_sumifs);\n    f->setParamCount(3, -1);\n    f->setAcceptArray();\n    f->setNeedsExtra(true);\n    add(f);\n    f = new Function(\"SUMSQ\",         func_sumsq);\n    f->setParamCount(1, -1);\n    f->setAcceptArray();\n    add(f);\n    f = new Function(\"TRANSPOSE\",     func_transpose);\n    f->setParamCount(1);\n    f->setAcceptArray();\n    add(f);\n}\n\nQString MathModule::descriptionFileName() const\n{\n    return QString(\"math.xml\");\n}\n\n\n// Function: SQRT\nValue func_sqrt(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value arg = args[0];\n    if (calc->gequal(arg, Value(0.0)))\n        return calc->sqrt(arg);\n    else\n        return Value::errorVALUE();\n}\n\n// Function: SQRTPI\nValue func_sqrtpi(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    // sqrt (val * PI)\n    Value arg = args[0];\n    if (calc->gequal(arg, Value(0.0)))\n        return calc->sqrt(calc->mul(args[0], calc->pi()));\n    else\n        return Value::errorVALUE();\n}\n\n// Function: ROOTN\nValue func_rootn(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->pow(args[0], calc->div(Value(1), args[1]));\n}\n\n// Function: CUR\nValue func_cur(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->pow(args[0], Value(1.0 / 3.0));\n}\n\n// Function: ABS\nValue func_abs(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->abs(args[0]);\n}\n\n// Function: exp\nValue func_exp(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->exp(args[0]);\n}\n\n// Function: ceil\nValue func_ceil(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->roundUp(args[0], Value(0));\n}\n\n// Function: ceiling\nValue func_ceiling(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value number = args[0];\n    Value res;\n    if (args.count() >= 2)\n        res = args[1];\n    else\n        res = calc->gequal(number, Value(0.0)) ? Value(1.0) : Value(-1.0);\n    bool mode = (args.count() >= 3) ? calc->isZero (args[2]) : true;\n\n    // short-circuit, and allow CEILING(0;0) to give 0 (which is correct)\n    // instead of DIV0 error\n    if (calc->isZero(number))\n        return Value(0.0);\n\n    if (calc->isZero(res))\n        return Value::errorDIV0();\n\n    Value d = calc->div(number, res);\n    if (calc->greater(Value(0), d))\n        return Value::errorNUM();\n\n    Value rud = calc->roundDown(d);\n    if (calc->approxEqual(rud, d))\n        d = calc->mul(rud, res);\n    else\n    {\n        // positive number or mode is 0 - round up\n        if ((!mode) || calc->gequal (number, Value(0))) rud = calc->roundUp(d);\n        d = calc->mul (rud, res);\n    }\n\n    return d;\n}\n\n// Function: FLOOR\nValue func_floor(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if (calc->approxEqual(args[0], Value(0.0)))\n        return Value(0);\n    Number number = args[0].asFloat();\n\n    Number significance;\n    if (args.count() >= 2) { // we have the optional \"significance\" argument\n        significance = args[1].asFloat();\n        // Sign of number and significance must match.\n        if (calc->gequal(args[0], Value(0.0)) != calc->gequal(args[1], Value(0.0)))\n            return Value::errorVALUE();\n    } else // use 1 or -1, depending on the sign of the first argument\n        significance = calc->gequal(args[0], Value(0.0)) ? 1.0 : -1.0;\n    if (calc->approxEqual(Value(significance), Value(0.0)))\n        return Value(0);\n\n    const bool mode = (args.count() == 3) ? (args[2].asFloat() != 0.0) : false;\n\n    Number result;\n    if (mode) // round towards zero\n        result = ((int)(number / significance)) * significance;\n    else { // round towards negative infinity\n        result = number / significance; // always positive, because signs match\n        if (calc->gequal(args[0], Value(0.0))) // positive values\n            result = floor(result) * significance;\n        else // negative values\n            result = ceil(result) * significance;\n    }\n    return Value(result);\n}\n\n// Function: GAMMA\nValue func_gamma(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->GetGamma(args[0]);\n}\n\n// Function: ln\nValue func_ln(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if ((args [0].isNumber() == false) || args[0].asFloat() <= 0)\n        return Value::errorNUM();\n    return calc->ln(args[0]);\n}\n\n// Function: LOGn\nValue func_logn(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if (args [0].isError())\n        return args [0];\n    if (args [0].isEmpty())\n        return Value::errorNUM();\n    if (args [0].isNumber() == false)\n        return Value::errorVALUE();\n    if (args[0].asFloat() <= 0)\n        return Value::errorNUM();\n    if (args.count() == 2) {\n        if (args [1].isError())\n            return args [1];\n        if (args [1].isEmpty())\n            return Value::errorNUM();\n        if (args [1].isNumber() == false)\n            return Value::errorVALUE();\n        if (args [1].asFloat() <= 0)\n            return Value::errorNUM();\n        return calc->log(args[0], args[1]);\n    } else\n        return calc->log(args[0]);\n}\n\n// Function: LOG2\nValue func_log2(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->log(args[0], Value(2.0));\n}\n\n// Function: LOG10\nValue func_log10(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if (args [0].isError())\n        return args [0];\n    if ((args [0].isNumber() == false) || (args[0].asFloat() <= 0))\n        return Value::errorNUM();\n    return calc->log(args[0]);\n}\n\n// Function: sum\nValue func_sum(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->sum(args, false);\n}\n\n// Function: suma\nValue func_suma(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->sum(args, true);\n}\n\n// Function: SUMIF\nValue func_sumif(valVector args, ValueCalc *calc, FuncExtra *e)\n{\n    Value checkRange = args[0];\n    QString condition = calc->conv()->asString(args[1]).asString();\n    Condition cond;\n    calc->getCond(cond, Value(condition));\n\n    if (args.count() == 3) {\n        Cell sumRangeStart(e->regions[2].firstSheet(), e->regions[2].firstRange().topLeft());\n        return calc->sumIf(sumRangeStart, checkRange, cond);\n    } else {\n        return calc->sumIf(checkRange, cond);\n    }\n}\n\n//Function: SUMIFS\nValue func_sumifs(valVector args, ValueCalc *calc, FuncExtra *e)\n{\n    int lim = (int) (args.count()-1)/2;\n\n    QList<Value> c_Range;\n    QStringList condition;\n    QList<Condition> cond;\n\n    c_Range.append(args.value(0));           //first element - range to be operated on\n\n    for (int i = 1; i < args.count(); i += 2) {\n        c_Range.append(args[i]);\n        condition.append(calc->conv()->asString(args[i+1]).asString());\n        Condition c;\n        calc->getCond(c, Value(condition.last()));\n        cond.append(c);\n    }\n    Cell sumRangeStart(e->sheet, e->ranges[2].col1, e->ranges[2].row1);\n    return calc->sumIfs(sumRangeStart, c_Range, cond, lim);\n}\n\n// Function: product\nValue func_product(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->product(args, Value(0.0));\n}\n\n// Function: seriessum\nValue func_seriessum(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    double fX = calc->conv()->asFloat(args[0]).asFloat();\n    double fN = calc->conv()->asFloat(args[1]).asFloat();\n    double fM = calc->conv()->asFloat(args[2]).asFloat();\n\n    if (fX == 0.0 && fN == 0.0)\n        return Value::errorNUM();\n\n    double res = 0.0;\n\n    if (fX != 0.0) {\n\n        for (unsigned int i = 0 ; i < args[3].count(); i++) {\n            res += args[3].element(i).asFloat() * pow(fX, fN);\n            fN += fM;\n        }\n    }\n\n    return Value(res);\n}\n\n// Function: kproduct\nValue func_kproduct(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->product(args, Value(1.0));\n}\n\n// Function: DIV\nValue func_div(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value val = args[0];\n    for (int i = 1; i < args.count(); ++i) {\n        val = calc->div(val, args[i]);\n        if (val.isError())\n            return val;\n    }\n    return val;\n}\n\n// Function: SUMSQ\nValue func_sumsq(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value res;\n    calc->arrayWalk(args, res, calc->awFunc(\"sumsq\"), Value(0));\n    return res;\n}\n\n// Function: MAX\nValue func_max(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value m = calc->max(args, false);\n    return m.isEmpty() ? Value(0.0) : m;\n}\n\n// Function: MAXA\nValue func_maxa(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value m = calc->max(args);\n    return m.isEmpty() ? Value(0.0) : m;\n}\n\n// Function: MIN\nValue func_min(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value m = calc->min(args, false);\n    return m.isEmpty() ? Value(0.0) : m;\n}\n\n// Function: MINA\nValue func_mina(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value m = calc->min(args, true);\n    return m.isEmpty() ? Value(0.0) : m;\n}\n\n// Function: INT\nValue func_int(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->conv()->asInteger(args[0]);\n}\n\n// Function: QUOTIENT\nValue func_quotient(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if (calc->isZero(args[1]))\n        return Value::errorDIV0();\n\n    double res = calc->conv()->toFloat(calc->div(args[0], args[1]));\n    if (res < 0)\n        res = ceil(res);\n    else\n        res = floor(res);\n\n    return Value(res);\n}\n\n\n// Function: eps\nValue func_eps(valVector, ValueCalc *calc, FuncExtra *)\n{\n    return calc->eps();\n}\n\nValue func_randexp(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    // -1 * d * log (random)\n    return calc->mul(calc->mul(args[0], Value(-1)), calc->random());\n}\n\nValue func_randbinom(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    // this function will not support arbitrary precision\n\n    double d  = numToDouble(calc->conv()->toFloat(args[0]));\n    int    tr = calc->conv()->toInteger(args[1]);\n\n    if (d < 0 || d > 1)\n        return Value::errorVALUE();\n\n    if (tr < 0)\n        return Value::errorVALUE();\n\n    // taken from gnumeric\n    double x = pow(1 - d, tr);\n    double r = (double) rand() / (RAND_MAX + 1.0);\n    double t = x;\n    int i = 0;\n\n    while (r > t) {\n        x *= (((tr - i) * d) / ((1 + i) * (1 - d)));\n        i++;\n        t += x;\n    }\n\n    return Value(i);\n}\n\nValue func_randnegbinom(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    // this function will not support arbitrary precision\n\n    double d  = numToDouble(calc->conv()->toFloat(args[0]));\n    int    f = calc->conv()->toInteger(args[1]);\n\n    if (d < 0 || d > 1)\n        return Value::errorVALUE();\n\n    if (f < 0)\n        return Value::errorVALUE();\n\n\n    // taken from Gnumeric\n    double x = pow(d, f);\n    double r = (double) rand() / (RAND_MAX + 1.0);\n    double t = x;\n    int i = 0;\n\n    while (r > t) {\n        x *= (((f + i) * (1 - d)) / (1 + i)) ;\n        i++;\n        t += x;\n    }\n\n    return Value(i);\n}\n\nValue func_randbernoulli(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value rnd = calc->random();\n    return Value(calc->greater(rnd, args[0]) ? 1.0 : 0.0);\n}\n\nValue func_randnorm(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value mu = args[0];\n    Value sigma = args[1];\n\n    //using polar form of the Box-Muller transformation\n    //refer to http://www.taygeta.com/random/gaussian.html for more info\n\n    Value x1, x2, w;\n    do {\n        // x1,x2 = 2 * random() - 1\n        x1 = calc->random(2.0);\n        x2 = calc->random(2.0);\n        x1 = calc->sub(x1, 1);\n        x1 = calc->sub(x2, 1);\n        w = calc->add(calc->sqr(x1), calc->sqr(x2));\n    } while (calc->gequal(w, Value(1.0)));    // w >= 1.0\n\n    //sqrt ((-2.0 * log (w)) / w) :\n    w = calc->sqrt(calc->div(calc->mul(Value(-2.0), calc->ln(w)), w));\n    Value res = calc->mul(x1, w);\n\n    res = calc->add(calc->mul(res, sigma), mu);    // res*sigma + mu\n    return res;\n}\n\nValue func_randpoisson(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if (calc->lower(args[0], Value(0)))\n        return Value::errorVALUE();\n\n    // taken from Gnumeric...\n    Value x = calc->exp(calc->mul(Value(-1), args[0]));     // e^(-A)\n    Value r = calc->random();\n    Value t = x;\n    int i = 0;\n\n    while (calc->greater(r, t)) {    // r > t\n        x = calc->mul(x, calc->div(args[0], i + 1));    // x *= (A/(i+1))\n        t = calc->add(t, x);     //t += x\n        i++;\n    }\n\n    return Value(i);\n}\n\n// Function: rand\nValue func_rand(valVector, ValueCalc *calc, FuncExtra *)\n{\n    return calc->random();\n}\n\n// Function: RANDBETWEEN\nValue func_randbetween(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value v1 = args[0];\n    Value v2 = args[1];\n    if (calc->greater(v2, v1)) {\n        v1 = args[1];\n        v2 = args[0];\n    }\n    return calc->add(v1, calc->random(calc->sub(v2, v1)));\n}\n\n// Function: POW\nValue func_pow(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->pow(args[0], args[1]);\n}\n\n// Function: MOD\nValue func_mod(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->mod(args[0], args[1]);\n}\n\n// Function: fact\nValue func_fact(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if (args[0].isInteger() || args[0].asInteger() > 0)\n        return calc->fact(args[0]);\n    else\n        return Value::errorNUM();\n}\n\n// Function: FACTDOUBLE\nValue func_factdouble(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if (args[0].isInteger() || args[0].asInteger() > 0)\n        return calc->factDouble(args[0]);\n    else\n        return Value::errorNUM();\n}\n\n// Function: MULTINOMIAL\nValue func_multinomial(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    // (a+b+c)! / a!b!c!  (any number of params possible)\n    Value num = Value(0), den = Value(1);\n    for (int i = 0; i < args.count(); ++i) {\n        num = calc->add(num, args[i]);\n        den = calc->mul(den, calc->fact(args[i]));\n    }\n    num = calc->fact(num);\n    return calc->div(num, den);\n}\n\n// Function: sign\nValue func_sign(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return Value(calc->sign(args[0]));\n}\n\n// Function: INV\nValue func_inv(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return calc->mul(args[0], -1);\n}\n\n// Function: MROUND\nValue func_mround(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value d = args[0];\n    Value m = args[1];\n\n    // signs must be the same\n    if ((calc->greater(d, Value(0)) && calc->lower(m, Value(0)))\n            || (calc->lower(d, Value(0)) && calc->greater(m, Value(0))))\n        return Value::errorVALUE();\n\n    int sign = 1;\n\n    if (calc->lower(d, Value(0))) {\n        sign = -1;\n        d = calc->mul(d, Value(-1));\n        m = calc->mul(m, Value(-1));\n    }\n\n    // from gnumeric:\n    Value mod = calc->mod(d, m);\n    Value div = calc->sub(d, mod);\n\n    Value result = div;\n    if (calc->gequal(mod, calc->div(m, Value(2))))  // mod >= m/2\n        result = calc->add(result, m);      // result += m\n    result = calc->mul(result, sign);     // add the sign\n\n    return result;\n}\n\n// Function: ROUNDDOWN\nValue func_rounddown(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if (args.count() == 2) {\n        if (calc->greater(args[0], 0.0))\n            return calc->roundDown(args[0], args[1]);\n        else\n            return calc->roundUp(args[0], args[1]);\n    }\n\n    if (calc->greater(args[0], 0.0))\n        return calc->roundDown(args[0], 0);\n    else\n        return calc->roundUp(args[0], 0);\n}\n\n// Function: ROUNDUP\nValue func_roundup(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if (args.count() == 2) {\n        if (calc->greater(args[0], 0.0))\n            return calc->roundUp(args[0], args[1]);\n        else\n            return calc->roundDown(args[0], args[1]);\n    }\n\n    if (calc->greater(args[0], 0.0))\n        return calc->roundUp(args[0], 0);\n    else\n        return calc->roundDown(args[0], 0);\n}\n\n// Function: ROUND\nValue func_round(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if (args.count() == 2)\n        return calc->round(args[0], args[1]);\n    return calc->round(args[0], 0);\n}\n\n// Function: EVEN\nValue func_even(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if (calc->greater(args[0], 0.0)) {\n        const Value value = calc->roundUp(args[0], 0);\n        return calc->isZero(calc->mod(value, Value(2))) ? value : calc->add(value, Value(1));\n    } else {\n        const Value value = calc->roundDown(args[0], 0);\n        return calc->isZero(calc->mod(value, Value(2))) ? value : calc->sub(value, Value(1));\n    }\n}\n\n// Function: ODD\nValue func_odd(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    if (calc->gequal(args[0], Value(0))) {\n        const Value value = calc->roundUp(args[0], 0);\n        return calc->isZero(calc->mod(value, Value(2))) ? calc->add(value, Value(1)) : value;\n    } else {\n        const Value value = calc->roundDown(args[0], 0);\n        return calc->isZero(calc->mod(value, Value(2))) ? calc->add(value, Value(-1)) : value;\n    }\n}\n\nValue func_trunc(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Q_UNUSED(calc)\n    Number result = args[0].asFloat();\n    if (args.count() == 2)\n        result = result * ::qPow(10, (int)args[1].asInteger());\n    result = (args[0].asFloat() < 0) ? -(qint64)(-result) : (qint64)result;\n    if (args.count() == 2)\n        result = result * ::qPow(10, -(int)args[1].asInteger());\n    return Value(result);\n}\n\n// Function: COUNT\nValue func_count(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return Value(calc->count(args, false));\n}\n\n// Function: COUNTA\nValue func_counta(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    return Value(calc->count(args));\n}\n\n// Function: COUNTBLANK\nValue func_countblank(valVector args, ValueCalc *, FuncExtra *)\n{\n    int cnt = 0;\n    for (int i = 0; i < args.count(); ++i)\n        if (args[i].isArray()) {\n            int rows = args[i].rows();\n            int cols = args[i].columns();\n            for (int r = 0; r < rows; ++r)\n                for (int c = 0; c < cols; ++c)\n                    if (args[i].element(c, r).isEmpty())\n                        cnt++;\n        } else if (args[i].isEmpty())\n            cnt++;\n    return Value(cnt);\n}\n\n// Function: COUNTIF\nValue func_countif(valVector args, ValueCalc *calc, FuncExtra *e)\n{\n    // the first parameter must be a reference\n    if ((e->ranges[0].col1 == -1) || (e->ranges[0].row1 == -1))\n        return Value::errorNA();\n\n    Value range = args[0];\n    QString condition = calc->conv()->asString(args[1]).asString();\n\n    Condition cond;\n    calc->getCond(cond, Value(condition));\n\n    return Value(calc->countIf(range, cond));\n}\n\n// Function: COUNTIFS\nValue func_countifs(valVector args, ValueCalc *calc, FuncExtra *e)\n{\n    // the first parameter must be a reference\n    if ((e->ranges[0].col1 == -1) || (e->ranges[0].row1 == -1))\n        return Value::errorNA();\n\n    int lim = (int) (args.count()-1)/2; \n\n    QList<Value> c_Range;\n    QStringList condition;\n    QList<Condition> cond;\n\n    for (int i = 0; i < args.count(); i += 2) {\n        c_Range.append(args[i]);\n        condition.append(calc->conv()->asString(args[i+1]).asString());\n        Condition c;\n        calc->getCond(c, Value(condition.last()));\n        cond.append(c);\n    }\n    Cell cntRangeStart(e->sheet, e->ranges[2].col1, e->ranges[2].row1);\n    return calc->countIfs(cntRangeStart, c_Range, cond, lim);\n}\n\n// Function: FIB\nValue func_fib(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    /*\n    Lucas' formula for the nth Fibonacci number F(n) is given by\n\n             ((1+sqrt(5))/2)^n - ((1-sqrt(5))/2)^n\n      F(n) = ------------------------------------- .\n                             sqrt(5)\n\n    */\n    Value n = args[0];\n    if (!n.isNumber())\n        return Value::errorVALUE();\n\n    if (!calc->greater(n, Value(0.0)))\n        return Value::errorNUM();\n\n    Value s = calc->sqrt(Value(5.0));\n    // u1 = ((1+sqrt(5))/2)^n\n    Value u1 = calc->pow(calc->div(calc->add(Value(1), s), Value(2)), n);\n    // u2 = ((1-sqrt(5))/2)^n\n    Value u2 = calc->pow(calc->div(calc->sub(Value(1), s), Value(2)), n);\n\n    Value result = calc->div(calc->sub(u1, u2), s);\n    return result;\n}\n\nstatic Value func_gcd_helper(const Value &val, ValueCalc *calc)\n{\n    Value res(0);\n    if (!val.isArray())\n        return val;\n    for (uint row = 0; row < val.rows(); ++row)\n        for (uint col = 0; col < val.columns(); ++col) {\n            Value v = val.element(col, row);\n            if (v.isArray())\n                v = func_gcd_helper(v, calc);\n            res = calc->gcd(res, calc->roundDown(v));\n        }\n    return res;\n}\n\n// Function: GCD\nValue func_gcd(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value result = Value(0);\n    for (int i = 0; i < args.count(); ++i) {\n        if (args[i].isArray()) {\n            result = calc->gcd(result, func_gcd_helper(args[i], calc));\n        } else {\n            if (args[i].isNumber() && args[i].asInteger() >= 0) {\n                result = calc->gcd(result, calc->roundDown(args[i]));\n            } else {\n                return Value::errorNUM();\n            }\n        }\n    }\n    return result;\n}\n\nstatic Value func_lcm_helper(const Value &val, ValueCalc *calc)\n{\n    Value res = Value(0);\n    if (!val.isArray())\n        return val;\n    for (unsigned int row = 0; row < val.rows(); ++row)\n        for (unsigned int col = 0; col < val.columns(); ++col) {\n            Value v = val.element(col, row);\n            if (v.isArray())\n                v = func_lcm_helper(v, calc);\n            res = calc->lcm(res, calc->roundDown(v));\n        }\n    return res;\n}\n\n// Function: lcm\nValue func_lcm(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Value result = Value(0);\n    for (int i = 0; i < args.count(); ++i) {\n        if (args[i].isArray()) {\n            result = calc->lcm(result, func_lcm_helper(args[i], calc));\n        } else {\n            if (args[i].isNumber() == false) {\n                return Value::errorNUM();\n            } else {\n                // its a number\n                if (args[i].asInteger() < 0) {\n                    return Value::errorNUM();\n                } else if (args[i].asInteger() == 0) {\n                    return Value(0);\n                } else { // number > 0\n                    result = calc->lcm(result, calc->roundDown(args[i]));\n                }\n            }\n        }\n    }\n    return result;\n}\n\n#ifdef ENABLE_EIGEN\nstatic Eigen::MatrixXd convert(const Value& matrix, ValueCalc *calc)\n{\n    const int rows = matrix.rows(), cols = matrix.columns();\n    Eigen::MatrixXd eMatrix(rows, cols);\n    for (int row = 0; row < rows; ++row) {\n        for (int col = 0; col < cols; ++col) {\n            eMatrix(row, col) = numToDouble(calc->conv()->toFloat(matrix.element(col, row)));\n        }\n    }\n    return eMatrix;\n}\n\nstatic Value convert(const Eigen::MatrixXd& eMatrix)\n{\n    const int rows = eMatrix.rows(), cols = eMatrix.cols();\n    Value matrix(Value::Array);\n    for (int row = 0; row < rows; ++row) {\n        for (int col = 0; col < cols; ++col) {\n            matrix.setElement(col, row, Value(eMatrix(row, col)));\n        }\n    }\n    return matrix;\n}\n#endif\n\n// Function: MDETERM\nValue func_mdeterm(valVector args, ValueCalc* calc, FuncExtra*)\n{\n    Value matrix = args[0];\n    if (matrix.columns() != matrix.rows() || matrix.rows() < 1)\n        return Value::errorVALUE();\n#ifdef ENABLE_EIGEN\n    const Eigen::MatrixXd eMatrix = convert(matrix, calc);\n\n    return Value(eMatrix.determinant());\n#else\n    return Value::errorVALUE();\n#endif\n}\n\n// Function: MINVERSE\nValue func_minverse(valVector args, ValueCalc* calc, FuncExtra*)\n{\n    Value matrix = args[0];\n    if (matrix.columns() != matrix.rows() || matrix.rows() < 1)\n        return Value::errorVALUE();\n#ifdef ENABLE_EIGEN\n    Eigen::MatrixXd eMatrix = convert(matrix, calc);\n    Eigen::FullPivLU<Eigen::MatrixXd> lu(eMatrix);\n    if (lu.isInvertible()) {\n        Eigen::MatrixXd eMatrixInverse = lu.inverse();\n        return convert(eMatrixInverse);\n    } else\n#endif\n        return Value::errorDIV0();\n}\n\n// Function: mmult\nValue func_mmult(valVector args, ValueCalc *calc, FuncExtra *)\n{\n#ifdef ENABLE_EIGEN\n    const Eigen::MatrixXd eMatrix1 = convert(args[0], calc);\n    const Eigen::MatrixXd eMatrix2 = convert(args[1], calc);\n\n    if (eMatrix1.cols() != eMatrix2.rows())    // row/column counts must match\n        return Value::errorVALUE();\n\n    return convert(eMatrix1 * eMatrix2);\n#else\n    return Value::errorVALUE();\n#endif\n}\n\n// Function: MUNIT\nValue func_munit(valVector args, ValueCalc* calc, FuncExtra*)\n{\n    const int dim = calc->conv()->asInteger(args[0]).asInteger();\n    if (dim < 1)\n        return Value::errorVALUE();\n    Value result(Value::Array);\n    for (int row = 0; row < dim; ++row)\n        for (int col = 0; col < dim; ++col)\n            result.setElement(col, row, Value(col == row ? 1 : 0));\n    return result;\n}\n\n// Function: SUBTOTAL\n// This function requires access to the Sheet and so on, because\n// it needs to check whether cells contain the SUBTOTAL formula or not ...\n// Cells containing a SUBTOTAL formula must be ignored.\nValue func_subtotal(valVector args, ValueCalc *calc, FuncExtra *e)\n{\n    int function = calc->conv()->asInteger(args[0]).asInteger();\n    Value range = args[1];\n    int r1 = -1, c1 = -1, r2 = -1, c2 = -1;\n    if (e) {\n        r1 = e->ranges[1].row1;\n        c1 = e->ranges[1].col1;\n        r2 = e->ranges[1].row2;\n        c2 = e->ranges[1].col2;\n    }\n\n    // exclude manually hidden rows. http://tools.oasis-open.org/issues/browse/OFFICE-2030\n    bool excludeHiddenRows = false;\n    if(function > 100) {\n        excludeHiddenRows = true;\n        function = function % 100; // translate e.g. 106 to 6.\n    }\n\n    // run through the cells in the selected range\n    Value empty;\n    if ((r1 > 0) && (c1 > 0) && (r2 > 0) && (c2 > 0)) {\n        for (int r = r1; r <= r2; ++r) {\n            const bool setAllEmpty = excludeHiddenRows && e->sheet->rowFormats()->isHidden(r);\n            for (int c = c1; c <= c2; ++c) {\n                // put an empty value to all cells in a hidden row\n                if(setAllEmpty) {\n                    range.setElement(c - c1, r - r1, empty);\n                    continue;\n                }\n                Cell cell(e->sheet, c, r);\n                // put an empty value to the place of all occurrences of the SUBTOTAL function\n                if (!cell.isDefault() && cell.isFormula() && cell.userInput().indexOf(\"SUBTOTAL\", 0, Qt::CaseInsensitive) != -1)\n                    range.setElement(c - c1, r - r1, empty);\n            }\n        }\n    }\n\n    // Good. Now we can execute the necessary function on the range.\n    Value res;\n    QSharedPointer<Function> f;\n    valVector a;\n    switch (function) {\n    case 1: // Average\n        res = calc->avg(range, false);\n        break;\n    case 2: // Count\n        res = Value(calc->count(range, false));\n        break;\n    case 3: // CountA\n        res = Value(calc->count(range));\n        break;\n    case 4: // MAX\n        res = calc->max(range, false);\n        break;\n    case 5: // Min\n        res = calc->min(range, false);\n        break;\n    case 6: // Product\n        res = calc->product(range, Value(0.0), false);\n        break;\n    case 7: // StDev\n        res = calc->stddev(range, false);\n        break;\n    case 8: // StDevP\n        res = calc->stddevP(range, false);\n        break;\n    case 9: // Sum\n        res = calc->sum(range, false);\n        break;\n    case 10: // Var\n        f = FunctionRepository::self()->function(\"VAR\");\n        if (!f) return Value::errorVALUE();\n        a.resize(1);\n        a[0] = range;\n        res = f->exec(a, calc, 0);\n        break;\n    case 11: // VarP\n        f = FunctionRepository::self()->function(\"VARP\");\n        if (!f) return Value::errorVALUE();\n        a.resize(1);\n        a[0] = range;\n        res = f->exec(a, calc, 0);\n        break;\n    default:\n        return Value::errorVALUE();\n    }\n    return res;\n}\n\n// Function: TRANSPOSE\nValue func_transpose(valVector args, ValueCalc *calc, FuncExtra *)\n{\n    Q_UNUSED(calc);\n    Value matrix = args[0];\n    const int cols = matrix.columns();\n    const int rows = matrix.rows();\n\n    Value transpose(Value::Array);\n    for (int row = 0; row < rows; ++row) {\n        for (int col = 0; col < cols; ++col) {\n            if (!matrix.element(col, row).isEmpty())\n                transpose.setElement(row, col, matrix.element(col, row));\n        }\n    }\n    return transpose;\n}\n\n/*\nCommented out.\nAbsolutely no idea what this thing is supposed to do.\nTo anyone who would enable this code: it still uses koscript calls - you need\nto convert it to the new style prior to uncommenting.\n\n// Function: MULTIPLEOPERATIONS\nValue func_multipleOP (valVector args, ValueCalc *calc, FuncExtra *)\n{\n  if (gCell)\n  {\n    context.setValue( new KSValue( ((Interpreter *) context.interpreter() )->cell()->value().asFloat() ) );\n    return true;\n  }\n\n  gCell = ((Interpreter *) context.interpreter() )->cell();\n\n  QValueList<KSValue::Ptr>& args = context.value()->listValue();\n  QValueList<KSValue::Ptr>& extra = context.extraData()->listValue();\n\n  if ( !KSUtil::checkArgumentsCount( context, 5, \"MULTIPLEOPERATIONS\", true ) )\n  {\n    gCell = 0;\n    return false;\n  }\n\n  // 0: cell must contain formula with double/int result\n  // 0, 1, 2, 3, 4: must contain integer/double\n  for (int i = 0; i < 5; ++i)\n  {\n    if ( !KSUtil::checkType( context, args[i], KSValue::DoubleType, true ) )\n    {\n      gCell = 0;\n      return false;\n    }\n  }\n\n  //  ((Interpreter *) context.interpreter() )->document()->emitBeginOperation();\n\n  double oldCol = args[1]->doubleValue();\n  double oldRow = args[3]->doubleValue();\n  debugSheets <<\"Old values: Col:\" << oldCol <<\", Row:\" << oldRow;\n\n  Cell * cell;\n  Sheet * sheet = ((Interpreter *) context.interpreter() )->sheet();\n\n  Point point( extra[1]->stringValue() );\n  Point point2( extra[3]->stringValue() );\n  Point point3( extra[0]->stringValue() );\n\n  if ( ( args[1]->doubleValue() != args[2]->doubleValue() )\n       || ( args[3]->doubleValue() != args[4]->doubleValue() ) )\n  {\n    cell = Cell( sheet, point.pos.x(), point.pos.y() );\n    cell->setValue( args[2]->doubleValue() );\n    debugSheets <<\"Setting value\" << args[2]->doubleValue() <<\" on cell\" << point.pos.x()\n              << \", \" << point.pos.y() << endl;\n\n    cell = Cell( sheet, point2.pos.x(), point.pos.y() );\n    cell->setValue( args[4]->doubleValue() );\n    debugSheets <<\"Setting value\" << args[4]->doubleValue() <<\" on cell\" << point2.pos.x()\n              << \", \" << point2.pos.y() << endl;\n  }\n\n  Cell * cell1 = Cell( sheet, point3.pos.x(), point3.pos.y() );\n  cell1->calc( false );\n\n  double d = cell1->value().asFloat();\n  debugSheets <<\"Cell:\" << point3.pos.x() <<\";\" << point3.pos.y() <<\" with value\"\n            << d << endl;\n\n  debugSheets <<\"Resetting old values\";\n\n  cell = Cell( sheet, point.pos.x(), point.pos.y() );\n  cell->setValue( oldCol );\n\n  cell = Cell( sheet, point2.pos.x(), point2.pos.y() );\n  cell->setValue( oldRow );\n\n  cell1->calc( false );\n\n  // ((Interpreter *) context.interpreter() )->document()->emitEndOperation();\n\n  context.setValue( new KSValue( (double) d ) );\n\n  gCell = 0;\n  return true;\n}\n\n*/\n\n//AFA #include \"math.moc\"\n", "meta": {"hexsha": "fb9394d81fb89f5ea952f47fb53cb10f4e5cee56", "size": 44484, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/3rdparty/sheets/functions/math.cpp", "max_stars_repo_name": "afarcat/QtSheetView", "max_stars_repo_head_hexsha": "6d5ef3418238e9402c5a263a6f499557cc7215bf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/3rdparty/sheets/functions/math.cpp", "max_issues_repo_name": "afarcat/QtSheetView", "max_issues_repo_head_hexsha": "6d5ef3418238e9402c5a263a6f499557cc7215bf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/3rdparty/sheets/functions/math.cpp", "max_forks_repo_name": "afarcat/QtSheetView", "max_forks_repo_head_hexsha": "6d5ef3418238e9402c5a263a6f499557cc7215bf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1178063643, "max_line_length": 128, "alphanum_fraction": 0.5992042083, "num_tokens": 12598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737869342623, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.41099736323738745}}
{"text": "#include <string>\n#include <vector>\n//#include <math.h>\n#include <cmath>\n#include <armadillo>\n\nusing namespace arma;\n\n#include \"tree_utils.h\"\n#include \"tree.h\"\n#include \"cont_models.h\"\n#include \"constants.h\" // for PI and E\n\n\nvoid calc_vcv(Tree * tree, mat & vcv) {\n    int numlvs = tree->getExternalNodeCount();\n    vcv = mat(numlvs,numlvs);\n    int count = 0;\n    for (int i=0; i < numlvs; i++) {\n        int count2 = 0;\n        for (int j=0; j < numlvs; j++) {\n            if (i != j) {\n                Node * a = getMRCA_forVCV(tree->getExternalNode(i),tree->getExternalNode(j));\n                double length = get_length_to_root(a);\n                vcv(count,count2) = length;\n            } else {\n                double length = get_length_to_root(tree->getExternalNode(i));\n                vcv(count,count2) = length;\n            }\n            count2 += 1;\n        }\n        count += 1;\n    }\n}\n\n/*\n * get the MRCA\n * this calculates the typical algorithm for MRCA\n * can be a little slow, so probably best to use\n * getMRCAFromPath_forVCV\n */\nNode * getMRCA_forVCV(Node * curn1,Node * curn2) {\n    Node * mrca = NULL;\n    //get path to root for first node\n    vector<Node *> path1;\n    Node * parent = curn1;\n    path1.push_back(parent);\n    while (parent != NULL) {\n        path1.push_back(parent);\n        if (parent->getParent() != NULL) {\n            parent = parent->getParent();\n        } else {\n            break;\n        }\n    }\n    //find first match between this node and the first one\n    parent = curn2;\n    bool x = true;\n    while (x == true) {\n        int psize = path1.size();\n        for (int i = 0; i < psize; i++) {\n            if (parent == path1.at(i)) {\n                mrca = parent;\n                x = false;\n                break;\n            }\n        }\n        parent = parent->getParent();\n    }\n    return mrca;\n}\n\n/*\n * this saves a great deal of time as it takes the already\n * obtained path and finds the match with the second node\n */\n\nNode * getMRCAFromPath_forVCV(vector<Node *> * path1,Node * curn2) {\n    Node * mrca = NULL;\n    Node * parent = curn2;\n    bool x = true;\n    while (x == true) {\n        int psize = path1->size();\n        for (int i = 0; i < psize; i++) {\n            if (parent == path1->at(i)) {\n                mrca = parent;\n                x = false;\n                break;\n            }\n        }\n        parent = parent->getParent();\n    }\n    return mrca;\n}\n\n\n/*\n   calculate the maximum likelihood for the ancestral state and the rate\n   calc_bm_like only calculates the rate and solves for the anc state\n#http://en.wikipedia.org/wiki/Multivariate_normal_distribution#Non-degenerate_case\nx should be a vector\nmu should be a vector\nsigma should be vcv with sigma already applied\n */\ndouble norm_pdf_multivariate(rowvec & x, rowvec & mu, mat & sigma) {\n    unsigned int size = x.n_cols;\n    if (size == mu.n_cols && sigma.n_rows == size && sigma.n_cols == size) {\n        double DET = det(sigma);\n        if (DET == 0) {\n            cerr << \"The covariance matrix can't be singular\" << endl;\n            exit(0);\n        }\n        double norm_const = 1.0/ ( pow((2*PI),double(size)/2) * pow(DET,1.0/2) );\n        mat x_mu = (mat) x - mu;\n        mat tm = (x_mu * inv(sigma) * trans(x_mu));\n        double big1 = tm(0,0);\n        double result = pow(E, -0.5 * big1);\n        double final = norm_const * result;\n        return final;\n    } else {\n        cerr << \"The dimensions of the input don't match\" << endl;\n        exit(0);\n    }\n}\n\ndouble norm_log_pdf_multivariate(rowvec & x, rowvec & mu, mat & sigma) {\n    unsigned int size = x.n_cols;\n    if (size == mu.n_cols && sigma.n_rows == size && sigma.n_cols == size) {\n        double DET;\n        double sign;\n        log_det(DET,sign,sigma);\n        if (DET == 0) {\n            cerr << \"The covariance matrix can't be singular\" << endl;\n            exit(0);\n        }\n        mat U; vec s; mat V;\n        svd(U, s, V, sigma,\"dc\");\n        mat diagD (s.size(),s.size());\n        diagD.zeros();\n        diagD.diag() = 1./s;\n        mat invC2 = V*diagD*trans(U);\n        rowvec ancA = x - mu;\n        double final = -.5 * (dot(invC2*trans(ancA),ancA))-0.5 * DET -0.5 * (size * log(2*PI));\n        return final;\n    } else {\n        cerr << \"The dimensions of the input don't match\" << endl;\n        exit(0);\n    }\n}\n\n/**\n * assumes that the characters are in get_cont_char and that the \n * results will be in assocDoubleVector as val and valse\n */\nvoid calc_square_change_anc_states(Tree * tree, int index) {\n    int df = 0;\n    int count = 0;\n    map<Node *,int> nodenum;\n    for (int i=0; i < tree->getInternalNodeCount(); i++) {\n        nodenum[tree->getInternalNode(i)] = count;\n        count += 1;\n        df += 1;\n        (*tree->getInternalNode(i)->getDoubleVector(\"val\"))[index] = 0.0;\n    }\n    df -= 1;\n    mat fullMcp(df+1,df+1);\n    vec fullVcp(df+1);\n    fullMcp.fill(0.0);\n    fullVcp.fill(0.0);\n    calc_postorder_square_change(tree->getRoot(),nodenum,&fullMcp,&fullVcp,index);\n    mat b = chol(fullMcp);\n    vec mle;\n    mat x = solve(trimatl(b.t())*b,fullVcp);\n    count = 0;\n    for (int i=0; i < tree->getInternalNodeCount(); i++) {\n        (*tree->getInternalNode(i)->getDoubleVector(\"val\"))[index] = x(nodenum[tree->getInternalNode(i)],0);\n        count += 1;\n    }\n}\n\nvoid calc_postorder_square_change(Node * node,map<Node *,int> & nodenum,\n    mat * fullMcp, mat * fullVcp, int index) {\n    for (int i=0; i < node->getChildCount(); i++) {\n        calc_postorder_square_change(node->getChild(i),nodenum,fullMcp,fullVcp,index);    \n    }\n    if (node->getChildCount() > 0) {\n        int nni = nodenum[node];\n        for (int j=0; j < node->getChildCount(); j++) {\n            double tbl = 2./node->getChild(j)->getBL();\n            (*fullMcp)(nni,nni) += tbl;\n            if (node->getChild(j)->getChildCount() == 0) {\n                (*fullVcp)[nni] += (*node->getChild(j)->getDoubleVector(\"val\"))[index] * tbl;\n            } else {\n                int nnj = nodenum[node->getChild(j)];\n                (*fullMcp)(nni,nnj) -= tbl;\n                (*fullMcp)(nnj,nni) -= tbl;\n                (*fullMcp)(nnj,nnj) += tbl;\n            }\n        }\n    }\n}\n\ndouble calc_bm_node_postorder(Node * node, int nch, double sigma){\n    double node_like = 0.;\n    for (int i=0;i<node->getChildCount();i++){\n        if(node->getChild(i)->isInternal()){\n           node_like += calc_bm_node_postorder(node->getChild(i),nch,sigma);\n        }\n    }\n    if (node->isInternal()){\n        double ch1 = (*node->getChild(0)->getDoubleVector(\"val\"))[nch];\n        double ch2 = (*node->getChild(1)->getDoubleVector(\"val\"))[nch];\n        double ch = ch1 - ch2;\n        double bl1 = node->getChild(0)->getBL(); \n        double bl2 = node->getChild(1)->getBL();\n        double bl = bl1 + bl2;\n        double cur_like = ((-0.5)* ((log(2*M_PI*sigma))+(log(bl))+(pow(ch,2)/(sigma*bl))));\n        node_like += cur_like;\n        if (node->isRoot() == false){\n            (*node->getDoubleVector(\"val\"))[nch] = ((bl2*ch1)+(bl1*ch2))/(bl);\n            node->setBL(node->getBL()+((bl1*bl2)/(bl1+bl2)));\n        }\n    }\n    return node_like;\n}\n\ndouble calc_bm_prune(Tree * tr, double sigma){\n    int nchar = (*tr->getRoot()->getDoubleVector(\"val\")).size();\n    double tlike = 0;\n    map<Node *, double> oldlen;\n    for (int i=0;i<tr->getNodeCount();i++){oldlen[tr->getNode(i)] = tr->getNode(i)->getBL();}\n    for (int i=0;i<nchar;i++){\n        for (int j=0;j<tr->getNodeCount();j++){tr->getNode(j)->setBL(oldlen[tr->getNode(j)]);}\n        tlike += calc_bm_node_postorder(tr->getRoot(),i,sigma);\n    }\n    return tlike;\n}\n\n\n", "meta": {"hexsha": "a99fa9cc0618fd5f355b2939578b4bcfbcea8762", "size": 7629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phyx-1.01/src/cont_models.cpp", "max_stars_repo_name": "jlanga/smsk_selection", "max_stars_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-18T05:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T10:22:33.000Z", "max_issues_repo_path": "src/phyx-1.01/src/cont_models.cpp", "max_issues_repo_name": "jlanga/smsk_selection", "max_issues_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T07:26:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-08T13:59:48.000Z", "max_forks_repo_path": "src/phyx-1.01/src/cont_models.cpp", "max_forks_repo_name": "jlanga/smsk_orthofinder", "max_forks_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-18T05:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:23:31.000Z", "avg_line_length": 31.7875, "max_line_length": 108, "alphanum_fraction": 0.545812033, "num_tokens": 2194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5621765008857982, "lm_q1q2_score": 0.4109839536767613}}
{"text": "\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <vector>\n#include <algorithm>\n#include <math.h>\n\n#include \"NRGclasses.hpp\"\n#include \"NRGfunctions.hpp\"\nusing namespace std;\n\n//////////////\n\nint CNRGarray::NumBlocks(){\n  \n  return((int)(QNumbers.size()/NQNumbers));\n\n}\n\n\n//////////////\ndouble CNRGarray::EniBlockj(int i, int j){\n\n  // returns the energy of the i-th state in block j\n\n  double aux=0.0;\n  \n  if ( (2*j-2)<BlockBegEnd.size() )\n    {\n      if ( (BlockBegEnd[2*j-2]+(i-1))<dEn.size() )\n\t{\n\t  aux=dEn[BlockBegEnd[2*j-2]+(i-1)];\n\t}\n    }\n  \n  return(aux);\n\n}\n//////////////\n\n//////////////\nvoid CNRGarray::PrintQNumbers(){\n\n\n  int ii;\n  cout << \"Qnumbers : \" << endl;\n  for (ii=0;ii<QNumbers.size();ii++)\n    {\n      cout << fixed << QNumbers[ii] << \"  \";\n      if ((ii+1) % NQNumbers == 0) cout << endl;\n    }\n  cout << endl;\n  cout << resetiosflags (ios_base::floatfield);\n\n\n}\n\n\n//////////////\nvoid CNRGarray::PrintEn(){\n\n\n  int ii;\n  int iblock,pos_in_block;\n  for (ii=0;ii<dEn.size();ii++){\n    iblock=GetBlockFromSt(ii,pos_in_block);\n    cout << \"En = \" << dEn[ii] << \" ---| \" ;\n    for (int iQn=0;iQn<NQNumbers;iQn++){\n      cout << GetQNumber(iblock,iQn) << \"  \";\n    }\n    if (ii<Kept.size()){if(Kept[ii]){cout << \"(K)\";}}\n    cout << \">_N= \";\n    cout << Nshell << endl;\n  }\n}\n\n//////////////\nvoid CNRGarray::PrintBlockQNumbers(int iblock){\n\n  cout << \"Block no. \" << iblock << \" : \";\n  for (int ii=0;ii<NQNumbers;ii++) \n    cout << fixed << GetQNumber(iblock,ii) << \" \";  \n  cout << endl;\n  cout << resetiosflags (ios_base::floatfield);\n\n}\n\n//////////////\nvoid CNRGarray::PrintBlockEn(int iblock){\n\n  PrintBlockQNumbers(iblock);\n\n  int iBeg=GetBlockLimit(iblock,0);\n  int iEnd=GetBlockLimit(iblock,1);\n  cout << \" dEn : \" << endl;\n  if (dEn.size()>0)\n    {\n      for (int ii=iBeg;ii<=iEnd;ii++) \n\tcout << ii << \" : \" << scientific << dEn[ii] << endl;  \n    }\n  //end if\n  cout << resetiosflags (ios_base::floatfield);\n  cout << \"Kept States: \"<< endl;\n  if (Kept.size()>0){\n    for (int ii=iBeg;ii<=iEnd;ii++){\n      cout << Kept[ii] << \" \";\n    }\n    cout << endl;\n  }\n  // end if\n\n}\n\n//////////////\nvoid CNRGarray::PrintBlock(int iblock){\n\n  PrintBlockEn(iblock);\n\n  int iBeg=GetBlockLimitEigv(iblock,0);\n  int iEnd=GetBlockLimitEigv(iblock,1);\n\n  int NstBl=GetBlockLimit(iblock,1)-GetBlockLimit(iblock,0)+1;\n  cout << \" dEigVec (rows): \" << endl;;\n  if (dEigVec.size()>0){\n    int i1=1;\n    for (int ii=iBeg;ii<=iEnd;ii++){\n      cout << scientific << dEigVec[ii] << \"  \";\n      if (i1%NstBl==0) cout << endl;\n//       // complex\n//       cout << scientific << cEigVec[ii] << \"  \";\n//       if (i1%NstBl==0) cout << endl;\n      i1++;\n    }\n  } else if (cEigVec.size()>0){\n    int i1=1;\n    for (int ii=iBeg;ii<=iEnd;ii++){\n      // complex\n      cout << scientific << cEigVec[ii] << \"  \";\n      if (i1%NstBl==0) cout << endl;\n      i1++;\n    }\n  } \n  //end if\n  \n  cout << resetiosflags (ios_base::floatfield);\n\n}\n\n\n//////////////\nvoid CNRGarray::PrintAll(){\n\n\n  int ii;\n  //void CNRGarray::PrintQNumbers();\n\n  PrintQNumbers();\n\n  cout << \" Any totalS QNs? = \" << totalS << endl;\n  if (Sqnumbers.size()>0){\n    cout << \"  totalS QNs positions : \";\n    for (ii=0;ii<Sqnumbers.size();ii++)\n      cout << Sqnumbers[ii] << \" \";\n    cout << endl;\n  }\n  cout << \"dEn : \" << endl;\n  for (ii=0;ii<dEn.size();ii++)\n    cout << scientific << dEn[ii] << \" \";\n  cout << endl;\n\n  cout << \"dEigVec (rows): \" << endl;\n  for (ii=0;ii<dEigVec.size();ii++)\n    cout << scientific << dEigVec[ii] << \" \";\n  cout << endl;\n  for (ii=0;ii<cEigVec.size();ii++)\n    cout << scientific << cEigVec[ii] << \" \";\n  cout << endl;\n\n\n  cout << \"BlockBegEnd : \" << endl;\n  for (ii=0;ii<BlockBegEnd.size();ii+=2)\n    cout << BlockBegEnd[ii] << \" \"<< BlockBegEnd[ii+1] << \", \";\n  cout << endl;\n\n  cout << \"Size Blocks : \" << endl;\n  for (ii=0;ii<NumBlocks();ii++)\n    cout << GetBlockSize(ii) << \" \";\n  cout << endl;\n\n  cout << \"Child States (size= \"<< ChildStates.size() <<\" ):\"<< endl;\n  // Why clear?\n  //ChildStates.clear();\n  if (ChildStates.size()>0){\n    for (ii=0;ii<ChildStates.size();ii++){\n      if (ChildStates[ii].size()>0){\n\tfor (int jj=0;jj<ChildStates[ii].size();jj++){\n\t  cout << ChildStates[ii][jj] << \" \";\n\t}\n      cout << endl;\n      }\n      // end if\n    }\n    cout << endl;\n  }\n  // end if\n\n\n  cout << \"Kept States (size= \"<< Kept.size() <<\" ):\"<< endl;\n  if (Kept.size()>0){\n    for (ii=0;ii<Kept.size();ii++){\n      cout << Kept[ii] << \" \";\n    }\n    cout << endl;\n  }\n  // end if\n\n\n\n\n\n  cout << resetiosflags (ios_base::floatfield);\n}\n//////////////\nint CNRGarray::Nstates(){\n\n  // Changing this:\n  //return(BlockBegEnd[NQNumbers*(NumBlocks()-1)+1]-BlockBegEnd[0]+1);\n  return(BlockBegEnd.back()-BlockBegEnd.front()+1);\n  \n}\n\n//////////////\nvoid CNRGarray::SetE0zero(){\n\n  double Emin=*min_element(dEn.begin(),dEn.end());\n  cout <<  \"Emin = \" << Emin << endl;\n\n  for (int ii=0;ii<dEn.size();ii++) dEn[ii]-=Emin;\n\n}\n\n//////////////\nvoid CNRGarray::SetDegen(){\n\n  // int nst,ii;\n\n  // Search for near-degeneracies in the spectrum\n  // and set the energy of the states to be the same  \n  int ii=0;\n  while ( ii<dEn.size() ){\n    for (int jj=ii+1;jj<dEn.size();jj++){\n//     if (fabs(dEn[ii]-dEn[ii-1])<1.0E-10) nst=iDegen[ii-1]+1;\n//     else nst=1;\n//     iDegen.push_back(nst);\n      if (dEqualPrec(dEn[jj],dEn[ii],MyEPS)){ \n\tif (dEn[jj]>dEn[ii])\n\t  dEn[jj]=dEn[ii];\n\telse\n\t  dEn[ii]=dEn[jj];\n      }\n      //end if equal\n    }\n    // end for loop in jj\n    ii++;\n  }\n  // end while loop\n}\n\n///////////////////////\nvoid CNRGarray::FilterQNumbers(){\n\n  int equal=0;\n  int ii,i1;\n\n  vector<double>::iterator qnums_iter,qnums_iter2,qnums_ii1,qnums_ii2;\n\n  for (qnums_iter=QNumbers.begin(); qnums_iter<QNumbers.end(); \n       qnums_iter+=NQNumbers)\n    {\n\n      //cout << \" QN1 = \" << (*qnums_iter) << \" , \" << *(qnums_iter+1)<< endl;\n      ii=1;\n      qnums_iter2=qnums_iter+ii*NQNumbers;\n      while (qnums_iter2<QNumbers.end())\n\t{\n\t  //cout << \" QN2 = \" << (*qnums_iter2) << \" , \" << *(qnums_iter2+1)<< endl;\n\t  equal=1;\n\t  i1=0;\n\t  for (qnums_ii2=qnums_iter2;\n\t       qnums_ii2<qnums_iter2+NQNumbers;qnums_ii2++)\n\t    {\n\t      qnums_ii1=qnums_iter+i1;\n\t      if ( (*qnums_ii2==*qnums_ii1)&&(equal==1) ) equal=1;\n\t      else equal=0;\n\t      i1++;\n\t    }\n\t  if (equal==1)\n\t    {\n\t      //cout << \"Found equal \" << endl;\n\t      QNumbers.erase(qnums_iter2,qnums_iter2+NQNumbers);\n\t      ii--;\n\t    }\n\t  ii++;\n\t  qnums_iter2=qnums_iter+ii*NQNumbers;\n\t}\n    }\n\n}\n\n//////////////\nvoid CNRGarray::ClearAll(){\n\n  QNumbers.clear();\n  dEn.clear();\n  dEigVec.clear();\n  iDegen.clear(); \n\n  BlockBegEnd.clear();\n  \n  ChildStates.clear();\n\n  Kept.clear();\n\n}\n\n//////////////\ndouble CNRGarray::GetQNumber(int iblock, int whichqn){\n\n  int iq=iblock*NQNumbers+whichqn;\n\n  if (QNumbers.size()>0)      \n     return(QNumbers[iq]);\n  else\n     return(0.0);\n\n}\n\n//////////////\nint CNRGarray::GetBlockLimit(int iblock, int whichlimit){\n\n  if(iblock<0)\n    return(0);\n  else\n    return(BlockBegEnd[2*iblock+whichlimit]);\n  \n}\n\n//////////////\nint CNRGarray::GetBlockSize(int iblock){\n\n  return(BlockBegEnd[2*iblock+1]-BlockBegEnd[2*iblock]+1);\n  \n}\n\n//////////////\nint CNRGarray::GetBlockSize(int iblock, bool kp){\n\n  int Nstkp=0;\n\n  if (Kept.size()<=BlockBegEnd[2*iblock+1]) return(0);\n\n  for (int ii=BlockBegEnd[2*iblock];ii<=BlockBegEnd[2*iblock+1];ii++){\n\n    if (Kept[ii]==kp) Nstkp++;\n\n  }\n\n  return(Nstkp);\n  \n}\n\n//////////////\nint CNRGarray::GetBlockFromSt(int ist,int &pos_in_block){\n\n  // Find which block ist belongs to:\n  // FInds iblock such that \n  // BlockBegEnd[2*iblock]<=ist<=BlockBegEnd[2*iblock+1]\n\n  int iblock=0;\n\n  while (ist>BlockBegEnd[2*iblock+1]) {iblock++;}\n\n  pos_in_block=ist-BlockBegEnd[2*iblock];\n\n  // if state is not there (holes in BlockBegEnd, pos_in_block is negative.\n\n\n  return(iblock);\n}\n/////////////\nint CNRGarray::GetBlockLimitEigv(int iblock, int whichlimit){\n\n  // Returns position in dEigVec corresponding to block iblock\n\n  int posEig=0;\n  int NstBl=0;\n\n  for (int ii=0;ii<iblock;ii++)\n    {\n      NstBl=GetBlockSize(ii);\n      posEig+=NstBl*NstBl;\n    }\n\n  NstBl=GetBlockSize(iblock);\n  posEig+=whichlimit*(NstBl*NstBl - 1);\n\n  return(posEig);\n\n}\n\n/////////////\ndouble CNRGarray::GetBlockEmin(int iblock){\n\n  double Emin = *min_element(dEn.begin()+GetBlockLimit(iblock,0),\n\t\t\t     dEn.begin()+GetBlockLimit(iblock,1)+1);\n\n  return(Emin);\n}\n\n/////////////\ndouble CNRGarray::GetBlockEmax(int iblock){\n\n  double Emax = *max_element(\n\t\t\t     dEn.begin()+GetBlockLimit(iblock,0),\n\t\t\t     dEn.begin()+GetBlockLimit(iblock,1)+1);\n  \n  return(Emax);\n}\n\n/////////////\n/////////////\n\n// bool GTEcut (double E, double Ecut) {\n//   return (E>Ecut);\n// }\n\n\nint CNRGarray::GetBlockEcutPos(int iblock,double Ecut){\n\n\n  vector<double>::iterator FindEnGTEcut=dEn.begin()+GetBlockLimit(iblock,0);\n\n   while ( (*FindEnGTEcut<=Ecut)\n \t  &&(FindEnGTEcut<=dEn.begin()+GetBlockLimit(iblock,1)) )\n//  to allow close-by states to be retained (did not work)\n//   while ( ( dLTPrec(*FindEnGTEcut,Ecut,0.01/fabs(Ecut)) )\n// \t  &&(FindEnGTEcut<=dEn.begin()+GetBlockLimit(iblock,1)) )\n    {FindEnGTEcut++;}\n\n//   =find_if(dEn.begin()+GetBlockLimit(iblock,0),\n// \t      dEn.begin()+GetBlockLimit(iblock,1),\n// \t      GTEcut); // doesnt work\n\n  \n  return((int)(FindEnGTEcut-dEn.begin()));\n}\n\n\n/////////////\nvoid CNRGarray::SetKept(int Ncutoff){\n\n  // New (2019)\n\n  SetDegen();\n\n  //\n\n  double dEcut=Ecut(Ncutoff);\n\n  Kept.clear();\n  vector<double>::iterator it;\n\n  cout << \"SetKept: Ncutoff = \" << Ncutoff \n       << \" Ecut = \" << dEcut << endl;\n\n  int Nkept=0;\n  int Ndisc=0;\n\n  for (it=dEn.begin();it<dEn.end();it++){\n    if ((*it)<=dEcut){\n      Kept.push_back(true); Nkept++;\n    }else{Kept.push_back(false);Ndisc++;}\n\n  }\n\n\n  cout << \"SetKept: Nkept = \" << Nkept << \" Ndisc = \" << Ndisc << endl;\n\n\n}\n////////////\nbool CNRGarray::CheckKept(int ist, bool kp){\n  //\n  // Checks if Keep[ist] matches kp\n\n\n  if (Kept.size()<=ist){return(false);}\n  else{\n    if (Kept[ist]==kp) return(true);\n    else return(false);\n  }\n}\n\nbool CNRGarray::CheckKept(int iblock, int istbl, bool kp){\n\n  int ist=GetBlockLimit(iblock,0)+istbl;\n\n  return(CheckKept(ist,kp));\n}\n\n\n/////////////\nint CNRGarray::GetBlockFromQNumbers(double *qnums){\n\n  // uses predicate \"dEqual\" defined NRGfunctions.hpp\n\n  vector <double>::iterator it=QNumbers.begin()-1;\n  bool ok=false;\n\n  // watch out for false alarms\n  while (!ok)\n   {\n  it = search (it+1, QNumbers.end(), qnums, qnums+NQNumbers,dEqual);\n  \n    ok=(((int)(it-QNumbers.begin()))%NQNumbers==0)||((int)(it-QNumbers.end())==0)?true:false;\n   }\n\n  //return (int(it-QNumbers.begin())/NQNumbers);\n  // Adding safeguards\n  int ibl=(int)(it-QNumbers.begin())/NQNumbers;\n  if (ibl>NumBlocks()-1){\n    //cout << \"GetBlockFromQNumbers: ibl larger than NumBlocks()-1. Returning -1\" << endl;\n    ibl=-1;\n  }\n\n  return (ibl);\n\n  // Adding safeguards\n\n\n}\n\n\n///////////// April 08\ndouble CNRGarray::GetQNumberFromSt(int ist, int whichqn){\n\n  int pos=0;\n  int ibl=GetBlockFromSt(ist,pos);\n\n  return(GetQNumber(ibl,whichqn));\n\n}\n/////////////\nboost::numeric::ublas::matrix<double> CNRGarray::EigVec2BLAS(int iblock){\n\n  // Converts the section in dEigVec corresponding to block iblock to uBLAS\n  // Format: each eigenvector in a ROW!\n\n  \n  int Nst=GetBlockSize(iblock);\n  int pos=GetBlockLimitEigv(iblock,0);\n\n  //cout << \"NstBlock = \" << Nst << \"  Pos in dEigVec = \" << pos << endl;\n\n  boost::numeric::ublas::matrix<double> Maux(Nst,Nst);\n\n//   copy(dEigVec.begin()+pos,dEigVec.begin()+pos+Nst*Nst,\n// \t   Maux.begin2());\n\n  // Let me try this:\n\n  vector<double>::iterator it;\n\n  it=dEigVec.begin()+pos;\n  for (int ii=0;ii<Nst;ii++)\n    {\n      for (int jj=0;jj<Nst;jj++)\n\t{\n\t  Maux(ii,jj)=*it;\n\t  it++;\n\t}\n    }\n\n  //return(boost::numeric::ublas::trans(Maux)); // In Columns\n  return(Maux);          // In Rows\n  \n\n}\n/////////////\nboost::numeric::ublas::matrix<complex<double> > CNRGarray::cEigVec2BLAS(int iblock){\n\n  // Converts the section in cEigVec corresponding to block iblock to uBLAS\n  // Format: each eigenvector in a ROW! COMPLEX MATRIX\n\n  \n  int Nst=GetBlockSize(iblock);\n  int pos=GetBlockLimitEigv(iblock,0);\n\n  //cout << \"NstBlock = \" << Nst << \"  Pos in dEigVec = \" << pos << endl;\n\n  boost::numeric::ublas::matrix<complex<double> > Maux(Nst,Nst);\n\n//   copy(dEigVec.begin()+pos,dEigVec.begin()+pos+Nst*Nst,\n// \t   Maux.begin2());\n\n  // Let me try this:\n\n  vector<complex<double> >::iterator it;\n\n  it=cEigVec.begin()+pos;\n  for (int ii=0;ii<Nst;ii++)\n    {\n      for (int jj=0;jj<Nst;jj++)\n\t{\n\t  Maux(ii,jj)=*it;\n\t  it++;\n\t}\n    }\n\n  //return(boost::numeric::ublas::trans(Maux)); // In Columns\n  return(Maux);          // In Rows\n \n}\n///////\n\n\n///////////// April 09\ndouble CNRGarray::GetEigVecComponent(int ist,int istbasis){\n\n  // For \"uncut\" vectors only!\n  // A CNRGbasisarray version for this one and for\n  // GetBlockLimitEigv should do the job\n  // in cut objects.\n  // \n\n  if (dEigVec.size()==0){\n    cout << \"GetEigVecComponent error: No dEigVec. Return 0.\" << endl;\n    return(0.0);\n  }\n\n  int posBl;\n  int posBlbasis;\n  int ibl=GetBlockFromSt(ist,posBl);\n  int ibl_basis=GetBlockFromSt(istbasis,posBlbasis);\n  int bl_size=GetBlockSize(ibl);\n  int ieigv0=GetBlockLimitEigv(ibl,0);\n\n  if (ibl==ibl_basis){\n    vector<double>::iterator it;\n    it=dEigVec.begin()+ieigv0+posBl*bl_size+posBlbasis;\n\n    return(*it);\n  }\n  else{return(0.0);}\n\n}\n\n\n/////////////\ndouble CNRGarray::Ecut(int Ncut){\n\n  vector<double> Eaux=dEn;\n  double aux,aux2;\n\n  sort(Eaux.begin(),Eaux.end());\n\n  \n  //  if (Ncut>Eaux.size()) aux=Eaux.back();\n  //  else aux=Eaux[Ncut];\n\n// Let's try this\n  if ( Ncut>=(Eaux.size()-1) ) aux=Eaux.back();\n  else{\n    aux=Eaux[Ncut-1]; // state Ncut\n    aux2=Eaux[Ncut];  // state Ncut+1\n    cout << \" CNRGarray::Ecut : Original Ecut = \"<< aux \n\t << \" Ecut+1 = \" << aux2 << endl;\n    //check for near-degenerate levels\n    int ii=1;\n//     while ( (aux2>0.0)&&(fabs((aux2-aux)/aux)<0.001)\n    while ( (aux2>0.0)&&(fabs((aux2-aux)/aux)<0.01)\n\t    &&(ii<Eaux.size()) ){aux2=Eaux[Ncut+ii];ii++;}\n    if (ii>1) {aux=Eaux[Ncut+ii-2];aux2=Eaux[Ncut+ii-1];}\n    cout << \" CNRGarray::Ecut : New Ecut = \"<< aux \n\t << \" New Ecut+1 = \" << aux2 \n         << \" Nkept = \" << Ncut+ii-1 << endl;\n  }\n\n  return(aux);\n}\n\n\n\n///////////// May 08\nint CNRGarray::GetiGS(){\n\n  // returns *position* of the minimum element in dEn \n\n  vector<double>::iterator it=min_element(dEn.begin(),dEn.end());\n\n  int iGS=0;\n  while (it>dEn.begin()){it--;iGS++;}\n\n\n  return(iGS);\n\n}\n\nvoid CNRGarray::SaveQSParameters(){\n\n  cout << \"Saving in old format \" << endl;\n\n  // outstream\n  ofstream OutFile;\n  char arqname[32];\n  char CNsites[8];\n  \n  sprintf(CNsites,\"%d\",Nshell);\n\n  //\n  // Saving QS parameters\n  //\n\n  strcpy(arqname,\"DataQSN\");\n  strcat(arqname,CNsites);\n  strcat(arqname,\".dat\");\n\n  cout << \"File is \" << arqname << endl;\n\n  OutFile.open(arqname);\n\n  int iGS=GetiGS();\n  int pos=0;\n  int blockGS=GetBlockFromSt(iGS,pos);\n\n  cout << \" Nsites \" << Nshell+1 << \" Nstates \" << Nstates() \n       << \" iGS = \" << iGS << \" BlockGS = \" << blockGS\n       << \" NumQSblocks = \" << NumBlocks()\n       << endl;\n\n  OutFile << Nshell+1 << \" \" << Nstates() \n       << \" \" << iGS << \" \" << blockGS\n       << \" \" << NumBlocks()\n       << endl;\n\n  for (int iblock=0;iblock<NumBlocks();iblock++)\n    {\n      OutFile << fixed << GetQNumber(iblock,0) << \"  \" << GetQNumber(iblock,1) << endl; \n    }\n  OutFile << resetiosflags (ios_base::floatfield);\n  for (int iblock=0;iblock<NumBlocks();iblock++)\n    {\n      OutFile << GetBlockLimit(iblock,0) << \"  \" << GetBlockLimit(iblock,1) << endl; \n    }\n\n  OutFile.close();\n\n  //\n  // Saving Energies\n  //\n\n  strcpy(arqname,\"DataEQSN\");\n  strcat(arqname,CNsites);\n  strcat(arqname,\".bin\");\n\n  // Using C format...\n  FILE *pFile;\n  \n  pFile=fopen(arqname,\"wb\");\n  fwrite (&dEn[0], sizeof(double), dEn.size() ,pFile); \n  fclose(pFile);\n\n\n  \n\n}\n//\n\nvoid CNRGarray::SaveBin(char arqname[]){\n\n  vector<double>::iterator dit;\n  vector<int>::iterator iit;\n  vector<bool>::iterator boolit;\n  vector<complex<double> >::iterator cit;\n\n\n  ofstream OutFile;\n  double daux;\n  int iaux;\n  bool auxbool;\n\n  complex<double> caux;\n\n  OutFile.open(arqname, ios::out | ios::binary);\n\n  if (!OutFile){cout << \"SaveBin: Cannot save data in \" << arqname << endl; return;}\n\n\n  // Save Nshell\n  OutFile.write((char*)&Nshell, sizeof(int));\n  // Save NQNumbers\n  OutFile.write((char*)&NQNumbers, sizeof(int));\n  // Save QNumbers\n  iaux=QNumbers.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(dit=QNumbers.begin();dit<QNumbers.end();dit++){\n    daux=*dit;\n    OutFile.write(reinterpret_cast<char*>(&daux), sizeof(double));\n  }\n  // Save dEn\n  iaux=dEn.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(dit=dEn.begin();dit<dEn.end();dit++){ \n    // (&(*dit)) is weird but it is right...\n    OutFile.write(reinterpret_cast<char*>(&(*dit)), sizeof(double));\n  }\n  // Save dEigVec\n  iaux=dEigVec.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(dit=dEigVec.begin();dit<dEigVec.end();dit++){ \n    // (&(*dit)) is weird but it is right...\n    OutFile.write(reinterpret_cast<char*>(&(*dit)), sizeof(double));\n  }\n  // Save cEigVec\n  iaux=cEigVec.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(cit=cEigVec.begin();cit<cEigVec.end();cit++){ \n    // (&(*cit)) is weird but it is right...\n    OutFile.write(reinterpret_cast<char*>(&(*cit)), sizeof(complex<double> ));\n  }\n  // Save BlockBegEnd\n  iaux=BlockBegEnd.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(iit=BlockBegEnd.begin();iit<BlockBegEnd.end();iit++){ \n    OutFile.write(reinterpret_cast<char*>(&(*iit)), sizeof(int));\n  }\n  // Save iDegen\n  iaux=iDegen.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(iit=iDegen.begin();iit<iDegen.end();iit++){ \n    OutFile.write(reinterpret_cast<char*>(&(*iit)), sizeof(int));\n  }\n  // Save Kept\n  iaux=Kept.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(boolit=Kept.begin();boolit<Kept.end();boolit++){ \n    //OutFile.write(reinterpret_cast<char*>(&(*boolit)), sizeof(bool));\n    auxbool=*boolit;\n    OutFile.write((char*)&auxbool, sizeof(bool));\n  }\n  // Save totalS,Sqnumbers\n  OutFile.write((char*)&totalS, sizeof(bool));\n  iaux=Sqnumbers.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(iit=Sqnumbers.begin();iit<Sqnumbers.end();iit++){ \n    OutFile.write(reinterpret_cast<char*>(&(*iit)), sizeof(int));\n  }\n\n\n  OutFile.close();\n  \n  if (!OutFile.good()){cout << \"SaveBin: error saving\" << endl;}\n\n\n}\n///\n\nvoid CNRGarray::ReadBin(char arqname[]){\n\n  // outstream\n  ifstream InFile;\n\n  InFile.open(arqname, ios::in | ios::binary);\n\n  ReadBinInStream(InFile);\n\n  InFile.close();\n\n  if (!InFile.good()){cout << \"ReadBin: error reading\" << endl;}\n\n\n}\n///\n\nvoid CNRGarray::ReadBinInStream(ifstream &InFile){\n\n  int isize,iaux, iaux2;\n  double daux;\n  bool boolaux;\n  complex<double> caux;\n\n\n  // Read Nshell\n  InFile.read((char*)&Nshell, sizeof(int));\n  // Read NQNumbers\n  InFile.read((char*)&NQNumbers, sizeof(int));\n  // Read QNumbers\n  QNumbers.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    InFile.read(reinterpret_cast<char*>(&daux), sizeof(double));\n    QNumbers.push_back(daux);\n  }\n  // Read dEn\n  dEn.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    InFile.read(reinterpret_cast<char*>(&daux), sizeof(double));\n    dEn.push_back(daux);\n  }\n  // Read dEigVec\n  dEigVec.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    InFile.read(reinterpret_cast<char*>(&daux), sizeof(double));\n    dEigVec.push_back(daux);\n  }\n  // Read cEigVec\n  cEigVec.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    InFile.read(reinterpret_cast<char*>(&caux), sizeof(complex<double> ));\n    cEigVec.push_back(caux);\n  }\n  // Read BlockBegEnd\n  BlockBegEnd.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    InFile.read(reinterpret_cast<char*>(&iaux2), sizeof(int));\n    BlockBegEnd.push_back(iaux2);\n  }\n  // Read iDegen\n  iDegen.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    InFile.read(reinterpret_cast<char*>(&iaux2), sizeof(int));\n    iDegen.push_back(iaux2);\n  }\n  // Read Kept\n  Kept.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    //InFile.read(reinterpret_cast<char*>(&boolaux), sizeof(bool));\n    InFile.read((char*)(&boolaux), sizeof(bool));\n    Kept.push_back(boolaux);\n  }\n  // Read totalS,Sqnumbers\n  InFile.read((char*)&totalS, sizeof(bool));\n  Sqnumbers.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    InFile.read(reinterpret_cast<char*>(&iaux2), sizeof(int));\n    Sqnumbers.push_back(iaux2);\n  }\n\n\n}\n\n//////////////\ndouble CNRGarray::PartitionFuncTeq0(){\n\n  // Works only for Q,Sz basis (not anymore)\n  // 04/2010: Including 2S+1 degeneracy factor for SU(2) symmetries\n  //\n\n  double sum=0.0;\n\n//   vector<double>::iterator dit;\n\n//   for (dit=dEn.begin();dit<dEn.end();dit++){\n//     if (dEqualPrec(abs((*dit)),0.0,1e-10)) sum+=1.0;\n//   }\n\n  for (int ibl=0;ibl<NumBlocks();ibl++){\n    double Si=0.0;\n    if (totalS){\n      Si=GetQNumber(ibl,Sqnumbers[0]); // only a single SU(2) for now\n    }\n    \n    for (int ist=GetBlockLimit(ibl,0);ist<=GetBlockLimit(ibl,1);ist++){\n      if ( dEqualPrec(abs(dEn[ist]),0.0,1e-10) ) sum+=2.0*Si+1.0;\n    }\n    // end loop in states\n  }\n  // end loop in blocks\n\n//\n return(sum);\n\n\n}\n\n\n\n//////////////\ndouble CNRGarray::PartitionFunc(double betabar){\n\n  // Works only for Q,Sz basis (not anymore)\n  // 04/2010: Including 2S+1 degeneracy factor for SU(2) symmetries\n  //\n\n\n  double sum=0.0;\n\n//   vector<double>::iterator dit;\n\n//   for (dit=dEn.begin();dit<dEn.end();dit++){\n//     sum+=exp(-betabar*(*dit));\n//   }\n\n\n  for (int ibl=0;ibl<NumBlocks();ibl++){\n    double Si=0.0;\n    if (totalS){\n      Si=GetQNumber(ibl,Sqnumbers[0]); // only a single SU(2) for now\n    }\n    \n    for (int ist=GetBlockLimit(ibl,0);ist<=GetBlockLimit(ibl,1);ist++){\n      sum+=(2.0*Si+1.0)*exp(-betabar*(dEn[ist]));\n    }\n    // end loop in states\n  }\n  // end loop in blocks\n\n  return(sum);\n}\n\n\n//////////////\n//////////////\ndouble CNRGarray::PartitionFuncDisc(double betabar){\n\n\n  double sum=0.0;\n\n  if (Kept.size()==0){\n    cout << \"PartitionFuncDisc: Kept not defined. Returning -1.0 \" << endl;\n    return(-1.0);\n  }\n  \n  for (int ibl=0;ibl<NumBlocks();ibl++){\n    double Si=0.0;\n    if (totalS){\n      Si=GetQNumber(ibl,Sqnumbers[0]); // only a single SU(2) for now\n    }\n    \n    for (int ist=GetBlockLimit(ibl,0);ist<=GetBlockLimit(ibl,1);ist++){\n      if (Kept[ist]==false)\n\tsum+=(2.0*Si+1.0)*exp(-betabar*(dEn[ist]));\n    }\n    // end loop in states\n  }\n  // end loop in blocks\n\n  return(sum);\n}\n\n\n//////////////\n\nvoid CNRGarray::SetEigVecToOne(){\n\n  // Sets eigenvectors to (1 0 0, 0 1 0, 0 0 1... on each block in the basis)\n  // Creates an \"uncut\" dEigVec with Nbl x Nbl block components \n  dEigVec.clear();\n\n  for(int ibl=0;ibl<NumBlocks();ibl++){\n    // within each block\n    int ist0=GetBlockLimit(ibl,0);\n    int istF=GetBlockLimit(ibl,1);\n    for (int ist1=ist0;ist1<=istF;ist1++){\n      for (int ist2=ist0;ist2<=istF;ist2++){\n\tif (ist1==ist2)\n\t  dEigVec.push_back(1.0); // diagonal\n\telse\n\t  dEigVec.push_back(0.0); // off-diagonal\n      }\n    }\n    // end loops in block states\n  }\n  // end block loops\n\n}\n\n///////////////\n\n\nboost::numeric::ublas::matrix<double> CNRGarray::ExpEi2BLAS(int iblock, double betabar){\n\n\n  int Nst1=GetBlockSize(iblock);\n\n  int ist=GetBlockLimit(iblock,0);\n\n  // NO NEED! \n//   double Si=0.0;\n//   if (totalS){\n//     Si=GetQNumber(iblock,Sqnumbers[0]); \n//     // only a single SU(2) for now\n//   }\n\n  boost::numeric::ublas::matrix<double> dMatAux(Nst1,Nst1);\n\n  for (int ii=0;ii<Nst1;ii++){\n    for (int jj=0;jj<Nst1;jj++){\n      if (ii==jj)\n\t// WRONG\n// \tdMatAux(ii,jj)=(2.0*Si+1.0)*exp(-betabar*dEn[ist]);\n\tdMatAux(ii,jj)=exp(-betabar*dEn[ist]);\n      else dMatAux(ii,jj)=0.0;\n    }\n    ist++;\n  }\n  // end loop\n\n  return(dMatAux);\n\n}\n//\n\n///////////////\n\nbool CNRGarray::CheckComplex(){\n\n  bool result=false;\n\n  if ( (cEigVec.size()>0)&&(dEigVec.size()==0) ) result=true;\n\n  return(result);\n\n}\n\n\n///////////////\n\n//////////////////////////////////////////////////\n//////////////////////////////////////////////////\n//                                              //\n//                                              //\n//     Class CNRGbasisarray functions           //\n//                                              //\n//                                              //\n//////////////////////////////////////////////////\n//////////////////////////////////////////////////\n\n\n//////////////\n//void CNRGbasisarray::ClearVecsBasis(){\nvoid CNRGbasisarray::ClearAll(){\n\n  CNRGarray::ClearAll();\n\n  iType.clear();\n  StCameFrom.clear();\n  BlockBegEndBC.clear();\n  BlockBegEndEigVec.clear();\n  \n  StCameFromQNumbers.clear(); \n\n}\n//////////////\nvoid CNRGbasisarray::PrintAll(){\n\n  CNRGarray::PrintAll();\n\n  cout << \"Type : \" << endl;\n  for (int ii=0;ii<iType.size();ii++)\n    cout << iType[ii] << \" \";\n  cout << endl;\n\n  cout << \"StCameFrom : \" << endl;\n  for (int ii=0;ii<StCameFrom.size();ii++)\n    cout << StCameFrom[ii] << \" \";\n  cout << endl;\n\n  cout << \"iDegen : \" << endl;\n  for (int ii=0;ii<iDegen.size();ii++)\n    cout << iDegen[ii] << \" \";\n  cout << endl;\n  \n  cout << \"BlockBegEndBC : \" << endl;\n  for (int ii=0;ii<BlockBegEndBC.size();ii+=2)\n    cout << BlockBegEndBC[ii] << \" \"<< BlockBegEndBC[ii+1] << \", \";\n  cout << endl;\n\n  cout << \"BlockBegEndEigVec : \" << endl;\n  for (int ii=0;ii<BlockBegEndEigVec.size();ii++)\n    cout << BlockBegEndEigVec[ii] << \" \";\n  cout << endl;\n\n  cout << \"StCameFromQNumbers : \" << endl;\n  for (int ii=0;ii<StCameFromQNumbers.size();ii++)\n    {\n      if ( (ii%NQNumbers_stcf==0) ) cout << ii/NQNumbers_stcf << \": \";\n      //cout << ii << \" -  \" << StCameFromQNumbers[ii] << \" \";\n      cout << StCameFromQNumbers[ii] << \" \";\n      if ( ((ii+1)%NQNumbers_stcf==0) ) cout << endl;\n    }\n\n}\n///////////////////\n//////////////\nvoid CNRGbasisarray::PrintBlockBasis(int iblock){\n\n  CNRGarray::PrintBlockQNumbers(iblock);\n\n  int iBeg=GetBlockLimit(iblock,0);\n  int iEnd=GetBlockLimit(iblock,1);\n  cout << \" Beg: \" << iBeg << \" End: \" << iEnd << endl;\n  for (int ii=iBeg;ii<=iEnd;ii++){\n    cout << ii << \" \";\n    if (dEn.size()>0)\n      cout << scientific << \"Eold = \" << dEn[ii] << \"  \"; \n    if (iType.size()>0)\n      cout << fixed << \"type = \" << iType[ii] << \"  \";\n    if (StCameFrom.size()>0)  \n      cout << fixed << \"StCFrom = \" << StCameFrom[ii]  << \"  \";\n    if (iDegen.size()>ii)\n      cout << fixed << \"iDeg = \" << iDegen[ii] << \"  \";\n    cout << resetiosflags (ios_base::floatfield);\n    if (StCameFromQNumbers.size()>0)\n      {\n\tcout << \"SCF_QNbrs: \";\n\tfor (int jj=ii*NQNumbers_stcf;jj<(ii+1)*NQNumbers_stcf;jj++)\n\t  cout << StCameFromQNumbers[jj] << \" \";\n      }\n    cout << endl;\n\n  }\n  // end loop in ii\n\n}\n/////////////\nvoid  CNRGbasisarray::SetSCFfromdEn(){\n\n  // Sets StCameFrom\n\n  StCameFrom.clear();\n  for (int ii=0;ii<dEn.size();ii++) StCameFrom.push_back(ii);\n\n\n\n}\n\n/////////////\n\n//////////////\nint CNRGbasisarray::GetBlockSizeBC(int iblock){\n\n  if(BlockBegEndBC.size()==0){return(GetBlockSize(iblock));}\n\n  return(BlockBegEndBC[2*iblock+1]-BlockBegEndBC[2*iblock]+1);\n  \n}\n\n//////////////\nint CNRGbasisarray::GetBlockFromStBC(int ist,int &pos_in_block){\n\n  // Find which block ist belongs in the BC structure:\n  // FInds iblock such that \n  // BlockBegEnd[2*iblock]<=ist<=BlockBegEnd[2*iblock+1]\n\n  \n  if (BlockBegEndBC.size()==0){\n    int auxst=CNRGarray::GetBlockFromSt(ist,pos_in_block);\n    return(auxst);\n  }\n  else{\n\n    int iblock=0;\n    \n    while (ist>BlockBegEndBC[2*iblock+1]) {iblock++;}\n    \n    pos_in_block=ist-BlockBegEndBC[2*iblock];\n\n    return(iblock);\n  }\n  // end if else\n}\n\n\n\n//////////////\nvoid CNRGbasisarray::SetBlockBegEndEigVec(){\n\n  BlockBegEndEigVec.clear();\n\n  int Nbls=(int)BlockBegEndBC.size()/2;\n  if (Nbls==0) return;\n\n  int aux=0;\n  for (int ibl=0;ibl<Nbls;ibl++)\n    {\n      BlockBegEndEigVec.push_back(aux);\n      aux+=GetBlockSizeBC(ibl)*GetBlockSizeBC(ibl)-1;\n      BlockBegEndEigVec.push_back(aux);\n      aux++;\n    }\n\n}\n\n\n\n\n/////////////\nvoid CNRGbasisarray::RemoveBlock(int iblock){\n\n  // Checks StCameFrom\n\n  if ( (dEn.size()==0)||( (dEigVec.size()==0)&&(cEigVec.size()==0) )\n       ||(StCameFrom.size()==0) ){\n      cout << \"Cant remove block: \" << iblock << endl;\n      return;\n    }\n  //CNRGbasisarray::PrintAll();\n\n  // Erase elements in dEn, dEigVec, StCameFrom, Kept\n\n  dEn.erase(dEn.begin()+GetBlockLimit(iblock,0),\n\t    dEn.begin()+GetBlockLimit(iblock,1)+1);\n\n  StCameFrom.erase(StCameFrom.begin()+GetBlockLimit(iblock,0),\n\t\t   StCameFrom.begin()+GetBlockLimit(iblock,1)+1);\n\n\n  Kept.erase(Kept.begin()+GetBlockLimit(iblock,0),\n\t    Kept.begin()+GetBlockLimit(iblock,1)+1);\n\n\n  // Watch out\n  if (dEigVec.size()>0)\n  dEigVec.erase(dEigVec.begin()+BlockBegEndEigVec[2*iblock],\n\t\tdEigVec.begin()+BlockBegEndEigVec[2*iblock+1]+1);\n\n  if (cEigVec.size()>0)\n  cEigVec.erase(cEigVec.begin()+BlockBegEndEigVec[2*iblock],\n\t\tcEigVec.begin()+BlockBegEndEigVec[2*iblock+1]+1);\n\n\n  // Erase elements in QNumbers\n\n  QNumbers.erase(QNumbers.begin()+NQNumbers*iblock,\n\t\t QNumbers.begin()+NQNumbers*(iblock+1));\n\n\n  // Re-arrange BlockBegEnd\n  // Re-arrange BlockBegEndEigVec\n\n  for (int ibl1=iblock;ibl1<NumBlocks();ibl1++)\n    {\n      int Size_next=GetBlockSize(ibl1+1);\n      BlockBegEnd[2*ibl1+1]=BlockBegEnd[2*ibl1]+Size_next-1;\n      BlockBegEnd[2*ibl1+2]=BlockBegEnd[2*ibl1]+Size_next;\n\n\n      int Size_next2=Size_next*Size_next;\n      BlockBegEndEigVec[2*ibl1+1]=BlockBegEndEigVec[2*ibl1]+Size_next2-1;\n      BlockBegEndEigVec[2*ibl1+2]=BlockBegEndEigVec[2*ibl1]+Size_next2;\n\n    }\n  BlockBegEnd.pop_back();\n  BlockBegEnd.pop_back();\n\n  BlockBegEndEigVec.pop_back();\n  BlockBegEndEigVec.pop_back();\n\n  // Erase elements in BlockBegEndBC\n\n  BlockBegEndBC.erase(BlockBegEndBC.begin()+2*iblock,\n\t\t      BlockBegEndBC.begin()+2*(iblock+1));\n\n}\n\n/////////////\n\n\n/////////////\nvoid CNRGbasisarray::RemoveState(int ist){\n\n  // Now it does cut egenvectors as well!!\n\n  // Checks vectors\n\n  if ( (dEn.size()==0)||(StCameFrom.size()==0) )\n    return;\n\n\n\n  int pos_in_bl;\n  int iblock=CNRGarray::GetBlockFromSt(ist,pos_in_bl);\n  int bl_size=CNRGarray::GetBlockSize(iblock);\n  int bl_sizeBC=GetBlockSizeBC(iblock);\n\n\n  if (BlockBegEnd[2*iblock]==\n      BlockBegEnd[2*iblock+1]) CNRGbasisarray::RemoveBlock(iblock);\n  else{\n\n    dEn.erase(dEn.begin()+ist);\n\n    StCameFrom.erase(StCameFrom.begin()+ist);\n\n    Kept.erase(Kept.begin()+ist);\n\n\n    // This doesn't work: \n    //       vector<double>::iterator it=dEigVec.begin()+GetBlockLimitEigv(iblock,0)+bl_size*pos_in_bl;\n\n    //       dEigVec.erase(it,it+bl_size);\n    //\n    //\n    // bl_size should be the original block size but\n    // no information on the original block length is available anymore.\n    //\n    // Needs a \"BlockBegEndBC\" or something.\n    //\n    // But we won't be needing the eigenvectors to generate the basis anyway.\n    //\n\n    // Now this should work:\n\n    vector<double>::iterator it=dEigVec.begin()+\n      BlockBegEndEigVec[2*iblock]+bl_sizeBC*pos_in_bl;\n\n    vector<complex<double> >::iterator cit=cEigVec.begin()+\n      BlockBegEndEigVec[2*iblock]+bl_sizeBC*pos_in_bl;\n\n\n//     if (it+bl_sizeBC>dEigVec.end()){\n    if ( (it+bl_sizeBC>dEigVec.end())&&(cit+bl_sizeBC>cEigVec.end()) ) {\n      cout << \" Ops, Problems in removing eigvec! \";\n      cout << \"Removing section of EigVec. bl_sizeBC = \" << bl_sizeBC;\n      cout << \" BegEigVec at : \" << BlockBegEndEigVec[2*iblock];\n      cout << \" EndEigVec at : \" << BlockBegEndEigVec[2*iblock+1];\n      cout << \" bl_sizeBC*pos_in_bl : \" << bl_sizeBC*pos_in_bl;\n      cout << endl;\n      exit(0);\n    }\n\n\n    if (it+bl_sizeBC<=dEigVec.end())\n      dEigVec.erase(it,it+bl_sizeBC);\n    if (cit+bl_sizeBC<=cEigVec.end())\n      cEigVec.erase(cit,cit+bl_sizeBC);\n\n\n    //Update BlockBegEnd\n    //Update BlockBegEndEigVec\n    BlockBegEnd[2*iblock+1]-=1;\n    BlockBegEndEigVec[2*iblock+1]-=bl_sizeBC;\n\n    for (int ibl1=iblock+1;ibl1<NumBlocks();ibl1++){\n      BlockBegEnd[2*ibl1]-=1;\n      BlockBegEnd[2*ibl1+1]-=1;\n\n      BlockBegEndEigVec[2*ibl1]-=bl_sizeBC;\n      BlockBegEndEigVec[2*ibl1+1]-=bl_sizeBC;\n    }\n\n  }\n\n}\n\n\n/////////////\nvoid CNRGbasisarray::RemoveStatesFromBlock(int iblock, int ist1,int ist2){\n\n  // Now it does cut egenvectors as well!!\n  // Similar as RemoveState but does that in blocks\n\n  // Checks vectors\n\n  if ( (dEn.size()==0)||(StCameFrom.size()==0) )\n    return;\n\n  int NstGone=ist2-ist1+1;\n\n  // Make sure that ist1 and ist2 belong to iblock\n  int pos_in_bl[2];\n  int ibl_check1=CNRGarray::GetBlockFromSt(ist1,pos_in_bl[0]);\n  int ibl_check2=CNRGarray::GetBlockFromSt(ist2,pos_in_bl[1]);\n  if ( (ibl_check1!=iblock)||(ibl_check2!=iblock) ){\n    cout << \" Error in RemoveStatesFromBlock: ist1, ist2  are not within block \" << endl;\n    return;\n  }\n\n  int bl_size=CNRGarray::GetBlockSize(iblock);\n  int bl_sizeBC=GetBlockSizeBC(iblock);\n\n\n  if (BlockBegEnd[2*iblock]==\n      BlockBegEnd[2*iblock+1]) CNRGbasisarray::RemoveBlock(iblock);\n  else{\n\n    dEn.erase(dEn.begin()+ist1,dEn.begin()+ist2+1); // Check if works\n\n    StCameFrom.erase(StCameFrom.begin()+ist1,StCameFrom.begin()+ist2+1);\n\n    Kept.erase(Kept.begin()+ist1,Kept.begin()+ist2+1);\n    //\n    // Now the tricky part: the eigenvector\n    //\n\n    //\n    // Iterator set at begining of first vector \n    //\n    vector<double>::iterator it=dEigVec.begin()+\n      BlockBegEndEigVec[2*iblock]+bl_sizeBC*pos_in_bl[0];\n    vector<complex<double> >::iterator cit=cEigVec.begin()+\n      BlockBegEndEigVec[2*iblock]+bl_sizeBC*pos_in_bl[0];\n   \n//     if (it+bl_sizeBC>dEigVec.end()){\n    if ( (it+bl_sizeBC>dEigVec.end())&&(cit+bl_sizeBC>cEigVec.end()) ){\n      cout << \" Ops, Problems in removing eigvec! \";\n      cout << \"Removing section of EigVec. bl_sizeBC = \" << bl_sizeBC;\n      cout << \" BegEigVec at : \" << BlockBegEndEigVec[2*iblock];\n      cout << \" EndEigVec at : \" << BlockBegEndEigVec[2*iblock+1];\n      cout << \" bl_sizeBC*pos_in_bl[0] : \" << bl_sizeBC*pos_in_bl[0];\n      cout << endl;\n      return;\n    }\n\n    if (it+bl_sizeBC<=dEigVec.end())\n      dEigVec.erase(it,it+bl_sizeBC*NstGone); // Should work\n\n    if (cit+bl_sizeBC<=cEigVec.end())\n      cEigVec.erase(cit,cit+bl_sizeBC*NstGone); // Should work\n\n\n    // Re-struct\n    //Update BlockBegEnd\n    //Update BlockBegEndEigVec\n    BlockBegEnd[2*iblock+1]-=NstGone;\n    BlockBegEndEigVec[2*iblock+1]-=bl_sizeBC*NstGone;\n   \n    for (int ibl1=iblock+1;ibl1<NumBlocks();ibl1++){\n      BlockBegEnd[2*ibl1]-=NstGone;\n      BlockBegEnd[2*ibl1+1]-=NstGone;\n       \n      BlockBegEndEigVec[2*ibl1]-=bl_sizeBC*NstGone;\n      BlockBegEndEigVec[2*ibl1+1]-=bl_sizeBC*NstGone;\n    }\n\n  }\n  // If not RemoveBlock\n\n}\n///////////// April 09\nint CNRGbasisarray::GetBlockLimitEigv(int iblock, int whichlimit){\n\n  // Returns position in dEigVec corresponding to block iblock\n  // USES BlockBegEndEigVec if available!!\n\n\n  if (BlockBegEndEigVec.size()==0){\n    return(CNRGarray::GetBlockLimitEigv(iblock,whichlimit));\n  }\n  else{\n//    cout << \"Overloaded GetBlockLimitEigv (CNRGbasisarray)\" << endl;\n    return(BlockBegEndEigVec[2*iblock+whichlimit]);\n  }\n\n}\n///////////////\n///////////// April 09\ndouble CNRGbasisarray::GetEigVecComponent(int ist,int istbasis){\n\n  // Overloads in the case of \"cut\" vectors\n  // For \"uncut\" vectors only!\n  // A CNRGbasisarray version for this one and for\n  // GetBlockLimitEigv should do the job\n  // in cut objects.\n  // \n\n  if  (dEigVec.size()==0){\n    cout << \"GetEigVecComponent: No dEigVec. Return 0.\" << endl;\n    return(0.0);\n  }\n\n\n  int posBl;\n  int posBlbasis;\n  int ibl=GetBlockFromSt(ist,posBl);\n  int iblbasis=GetBlockFromStBC(istbasis,posBlbasis);\n  int bl_sizeBC=GetBlockSizeBC(ibl);\n\n  //  cout << \"GetEigVecComponent: Using overloaded version\" << endl;\n\n  if (ibl==iblbasis){\n    int ieigv0=GetBlockLimitEigv(ibl,0);\n    vector<double>::iterator it;\n    it=dEigVec.begin()+ieigv0+posBl*bl_sizeBC+posBlbasis;\n    return(*it);\n  }\n  else{return(0.0);}\n\n}\n\n\n\n///////////////\n///////////////\nboost::numeric::ublas::matrix<double> CNRGbasisarray::EigVecCut2BLAS(int iblock){\n\n  // Converts the section in dEigVec corresponding to block iblock to uBLAS\n  // Format: each eigenvector in a ROW!\n\n  \n  int Nst=GetBlockSize(iblock);\n  int pos=BlockBegEndEigVec[2*iblock];\n\n  int NstBC=GetBlockSizeBC(iblock);\n\n  //cout << \"NstBlock = \" << Nst << \"  Pos in dEigVec = \" << pos << endl;\n\n  boost::numeric::ublas::matrix<double> Maux(Nst,NstBC);\n\n\n  // Let me try this:\n\n  vector<double>::iterator it;\n\n  it=dEigVec.begin()+pos;\n  for (int ii=0;ii<Nst;ii++){\n    for (int jj=0;jj<NstBC;jj++){\n      Maux(ii,jj)=*it;\n      it++;\n    }\n  }\n  //return(boost::numeric::ublas::trans(Maux)); // In Columns\n  return(Maux);          // In Rows\n  \n}\n/// Now the complex one\nboost::numeric::ublas::matrix<complex<double> > CNRGbasisarray::cEigVecCut2BLAS(int iblock){\n\n  // Converts the section in cEigVec corresponding to block iblock to uBLAS\n  // Format: each eigenvector in a ROW!\n\n  \n  int Nst=GetBlockSize(iblock);\n  int pos=BlockBegEndEigVec[2*iblock];\n\n  int NstBC=GetBlockSizeBC(iblock);\n\n  //cout << \"NstBlock = \" << Nst << \"  Pos in dEigVec = \" << pos << endl;\n\n  boost::numeric::ublas::matrix<complex<double> > Maux(Nst,NstBC);\n\n  vector<complex<double> >::iterator it;\n\n  it=cEigVec.begin()+pos;\n  for (int ii=0;ii<Nst;ii++){\n    for (int jj=0;jj<NstBC;jj++){\n      Maux(ii,jj)=*it;\n      it++;\n    }\n  }\n  //return(boost::numeric::ublas::trans(Maux)); // In Columns\n  return(Maux);          // In Rows (complex)\n  \n}\n\n\n///////////////\nboost::numeric::ublas::matrix<double> CNRGbasisarray::EigVecCut2BLAS(int iblock, \n\t\t\t\t\t\t\t\t     bool kp){\n\n  // Converts the section in dEigVec corresponding to block iblock to uBLAS\n  // Format: each eigenvector in a ROW!\n\n  // The assumption: NO CUTTING WAS DONE in the basisarray object\n\n  \n  int Nst=GetBlockSize(iblock);\n  int pos=BlockBegEndEigVec[2*iblock];\n\n  int NstBC=GetBlockSizeBC(iblock); // Should be equal to Nst\n\n  int Nstkp=CNRGarray::GetBlockSize(iblock,kp);\n\n  //cout << \"NstBlock = \" << Nst << \"  Pos in dEigVec = \" << pos << endl;\n\n  boost::numeric::ublas::matrix<double> Maux(Nstkp,Nstkp);\n  // if Nst != NstBC, then we will hake a problem here: \n  // this matrix will not be square\n\n  vector<double>::iterator it;\n\n  it=dEigVec.begin()+pos;\n  int istkp=0;\n  for (int ii=0;ii<Nst;ii++){\n    int jstkp=0;\n    for (int jj=0;jj<NstBC;jj++){\n      if (CheckKept(iblock,ii,kp)){\n\tMaux(istkp,jstkp)=*it;\n\tjstkp++;\n      }\n      // if state kept==kp\n      it++;\n    }\n    // end loop in components\n    if (CheckKept(iblock,ii,kp)){istkp++;}\n  }\n  // end loop in states\n\n\n  //return(boost::numeric::ublas::trans(Maux)); // In Columns\n  return(Maux);          // In Rows\n  \n\n}\n\n\n\n///////////////\n///////////////\n///////////////\n///////////////\n///////////// April 08\ndouble CNRGbasisarray::GetStCameFromQNumberFromSt(int ist, int whichqn){\n\n  int stcf=StCameFrom[ist];\n\n  return(StCameFromQNumbers[NQNumbers_stcf*ist+whichqn]);\n\n}\n/////////////\n\n\n///////////////\n///////////// June 08\n/////////////\nvoid CNRGbasisarray::CopyBlock(int iblock,int NoCopies){\n\n  // Checks StCameFrom\n\n  if ( (NoCopies<1)||(NoCopies>100) )\n    {\n      cout << \" CopyBlock : NoCopies not valid \" << endl;\n      return;\n    }\n\n\n  // Set iDegen if not set yet\n  if (iDegen.size()==0)\n    for (int ii=0;ii<Nstates();ii++) iDegen.push_back(0);\n\n  // Set iType if not set yet\n  if (iType.size()==0)\n    for (int ii=0;ii<Nstates();ii++) iType.push_back(0);\n\n  \n\n  int BlSize=GetBlockSize(iblock);\n\n  vector<double> dAux;\n  vector<int> iAux,iAux2;\n\n//   cout << \" Bl Size = \" << BlSize \n//        << \" Limit 0: \" << GetBlockLimit(iblock,0)\n//        << \" Limit 1: \" << GetBlockLimit(iblock,1)\n//        << endl;\n\n\n  dAux.assign(dEn.begin()+GetBlockLimit(iblock,0),\n \t      dEn.begin()+GetBlockLimit(iblock,1)+1);\n\n  iAux.assign(iType.begin()+GetBlockLimit(iblock,0),\n \t      iType.begin()+GetBlockLimit(iblock,1)+1);\n\n  iAux2.assign(StCameFrom.begin()+GetBlockLimit(iblock,0),\n \t      StCameFrom.begin()+GetBlockLimit(iblock,1)+1);\n\n\n\n  for (int ic=1;ic<=NoCopies;ic++)\n    {\n      // Copy to dEn\n      dEn.insert(dEn.begin()+GetBlockLimit(iblock,1)+1,dAux.begin(),dAux.end());\n      // Copy to iType\n      iType.insert(iType.begin()+GetBlockLimit(iblock,1)+1,iAux.begin(),iAux.end());\n      // Copy to StCameFrom\n      StCameFrom.insert(StCameFrom.begin()+GetBlockLimit(iblock,1)+1,iAux2.begin(),iAux2.end());\n\n      // Update iDegen\n\n      iDegen.insert(iDegen.begin()+GetBlockLimit(iblock,1)+1,BlSize,ic);\n\n      // Re-arrange BlockBegEnd, Get ready for next copy\n      BlockBegEnd[2*iblock+1]+=BlSize;\n      for (int ibl1=iblock+1;ibl1<NumBlocks();ibl1++)\n\t{\n\t  BlockBegEnd[2*ibl1]+=BlSize;\n\t  BlockBegEnd[2*ibl1+1]+=BlSize;\n\t}\n      // end loop in blocks\n\n    }\n  iAux.clear();\n  dAux.clear();\n\n}\n\n///////////////\n/////////////\n///////////// September 08\n/////////////\nvoid CNRGbasisarray::SetLastQNumber(vector<double> InputVec){\n\n  // Based on the iDegen values, add QNumber and rearrange\n  // dEn, QNumbers and BlockBegEnd. Good for phonons.\n  // It will re-order the blocks according with iDegen values\n  // (it may come down to a single state per block)\n\n\n  if (InputVec.size()!=Nstates()){\n    cout << \"SetLastQNumber : Input vec size does not match\" << endl; \n    return;\n  }\n\n  // assume it is the latest qn\n\n  vector<double> auxdEn;\n  vector<double> auxQNumbers;\n  vector<int> auxBlockBegEnd;\n  vector<int> auxiDegen;\n\n  vector<int> auxiType;\n  vector<int> auxStCameFrom;\n\n  vector<double>::iterator it0;\n  vector<double>::iterator it1;\n\n  vector<int>::iterator it_ideg;\n\n\n\n  double *auxdQN=new double [NQNumbers];\n\n\n  int NoBlocksOri=NumBlocks(); // will increase QNumbers so need this one\n  int Nadded=0;\n\n  // Add new blocks to QNumbers\n\n  auxQNumbers=QNumbers;\n\n  auxdQN[0]=0.0;\n  for (int ibl=0;ibl<NoBlocksOri;ibl++){\n    int ist0=GetBlockLimit(ibl,0);\n    int ist1=GetBlockLimit(ibl,1);\n      \n    for (int ist=ist0;ist<=ist1;ist++){\n      it0=QNumbers.begin()+(ibl+Nadded)*NQNumbers;\n      it1=QNumbers.begin()+(ibl+Nadded+1)*NQNumbers;\n      // \t  auxdQN[0]=(double)iDegen[ist];\n      auxdQN[0]=InputVec[ist];\n      QNumbers[(Nadded*NQNumbers)+((ibl+1)*NQNumbers)-1]=auxdQN[0];\n      if (ist<ist1)\n\t{QNumbers.insert(it0,it0,it1);Nadded++;}\n    }\n    // end loop in states\n  }\n  // end loop in blocks\n\n  FilterQNumbers();\n\n  // Update Block structure\n\n  auxdEn.clear();\n  auxiDegen.clear();\n  auxBlockBegEnd.clear();\n  auxiType.clear();\n  auxStCameFrom.clear();\n\n  Nadded=0;\n\n  // Loop in new block structure\n  for (int ibl=0;ibl<NumBlocks();ibl++){\n    for (int iqn=0;iqn<NQNumbers;iqn++){auxdQN[iqn]=GetQNumber(ibl,iqn);}\n\n    // Loop in the old block structure      \n    auxBlockBegEnd.push_back(Nadded);\n    for (int ibl1=0;ibl1<NoBlocksOri;ibl1++){\n      bool ok_match=true;\n\t\n      int ist0=GetBlockLimit(ibl1,0);\n      int ist1=GetBlockLimit(ibl1,1);\n\t\n      for (int iqn=0;iqn<NQNumbers-1;iqn++)\n\tif(dNEqual(auxdQN[iqn],auxQNumbers[ibl1*NQNumbers+iqn]))\n\t  ok_match=false;\n      if (ok_match){\n\t//cout << \" Blocks Match: \" << \" ibl1= \" << ibl1 << \" ibl= \" << ibl  << endl;\n\tfor (int ist=ist0;ist<=ist1;ist++){\n\t  // \t\t  if (dEqual(auxdQN[NQNumbers-1],(double)iDegen[ist]))\n\t  if (dEqual(auxdQN[NQNumbers-1],InputVec[ist])){\n\n\t    if (ist<dEn.size()) auxdEn.push_back(dEn[ist]);\n\t    if (ist<iDegen.size()) auxiDegen.push_back(iDegen[ist]);\n\t    if (ist<iType.size()) auxiType.push_back(iType[ist]);\n\t    if (ist<StCameFrom.size()) auxStCameFrom.push_back(StCameFrom[ist]);\n\t    \n\t    Nadded++;\n\t    //cout << \" Adding ist = \" << ist << \" to block \" << ibl << endl;\n\t  }\n\t}\n\t// end loop in ist in matchin blocks\n      }\n      // if match\n    }\n    // loop in old blocks\n\n    auxBlockBegEnd.push_back(Nadded-1);\n  }\n  // loop in new blocks\n\n  // Update other vectors\n  dEn.clear();\n  BlockBegEnd.clear();\n  iDegen.clear();\n  iType.clear();\n  StCameFrom.clear();\n\n  dEn=auxdEn;\n  BlockBegEnd=auxBlockBegEnd;\n  iDegen=auxiDegen;\n\n  iType=auxiType;\n  StCameFrom=auxStCameFrom;\n\n  delete[] auxdQN;\n\n}\n\n///////////\n\n\n//\n/////////////\n///////////// February 09\n/////////////\n\n\nvoid CNRGbasisarray::SaveBin(char arqname[]){\n\n  CNRGarray::SaveBin(arqname);\n\n  vector<double>::iterator dit;\n  vector<int>::iterator iit;\n\n  ofstream OutFile(arqname, ios::out | ios::binary | ios::app);\n  double daux;\n  int iaux;\n\n  if (!OutFile){cout << \"SaveBin: Cannot save data in \" << arqname << endl; return;}\n\n  // Save iType\n  iaux=iType.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(iit=iType.begin();iit<iType.end();iit++){ \n    OutFile.write(reinterpret_cast<char*>(&(*iit)), sizeof(int));\n  }\n\n  // Save StCameFrom\n  iaux=StCameFrom.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(iit=StCameFrom.begin();iit<StCameFrom.end();iit++){ \n    OutFile.write(reinterpret_cast<char*>(&(*iit)), sizeof(int));\n  }\n\n  // Save BlockBegEndBC\n  iaux=BlockBegEndBC.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(iit=BlockBegEndBC.begin();iit<BlockBegEndBC.end();iit++){ \n    OutFile.write(reinterpret_cast<char*>(&(*iit)), sizeof(int));\n  }\n\n  // Save BlockBegEndEigVec\n  iaux=BlockBegEndEigVec.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(iit=BlockBegEndEigVec.begin();iit<BlockBegEndEigVec.end();iit++){ \n    OutFile.write(reinterpret_cast<char*>(&(*iit)), sizeof(int));\n  }\n  // Save NQNumbers_stcf\n  OutFile.write((char*)&NQNumbers_stcf, sizeof(int));\n  // Save QNumbers_stcf\n  iaux=StCameFromQNumbers.size();\n  OutFile.write((char*)&iaux, sizeof(int));\n  for(dit=StCameFromQNumbers.begin();dit<StCameFromQNumbers.end();dit++){\n    daux=*dit;\n    OutFile.write(reinterpret_cast<char*>(&daux), sizeof(double));\n  }\n\n  OutFile.close();\n\n  if (!OutFile.good()){cout << \"SaveBin: error saving\" << endl;}\n\n\n}\n///\n\nvoid CNRGbasisarray::ReadBin(char arqname[]){\n\n  // ifstream\n  ifstream InFile;\n\n  InFile.open(arqname, ios::in | ios::binary);\n  //InFile.seekg(0,ios::beg);\n\n  if (!InFile){cout << \"ReadBin: Cannot read data in \" << arqname << endl; return;}\n\n  CNRGbasisarray::ReadBinInStream(InFile);\n\n  InFile.close();\n\n  if (!InFile.good()){cout << \"ReadBin: overall error reading\" << endl;}\n\n\n}\n\n/////\nvoid CNRGbasisarray::ReadBinInStream(ifstream &InFile){\n\n\n  int isize,iaux, iaux2;\n  double daux;\n\n\n  CNRGarray::ReadBinInStream(InFile);\n  \n   // Read iType\n  iType.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    InFile.read(reinterpret_cast<char*>(&iaux2), sizeof(int));\n    iType.push_back(iaux2);\n  }\n  // Read StCameFrom\n  StCameFrom.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    InFile.read(reinterpret_cast<char*>(&iaux2), sizeof(int));\n    StCameFrom.push_back(iaux2);\n  }\n  // Read BlockBegEndBC BlockBegEigVec\n  BlockBegEndBC.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    InFile.read(reinterpret_cast<char*>(&iaux2), sizeof(int));\n    BlockBegEndBC.push_back(iaux2);\n  }\n  // Read BlockBegEndEigVec\n  BlockBegEndEigVec.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    InFile.read(reinterpret_cast<char*>(&iaux2), sizeof(int));\n    BlockBegEndEigVec.push_back(iaux2);\n  }\n  // Read NQNumbers_stcf\n  InFile.read((char*)&NQNumbers_stcf, sizeof(int));\n  // Read QNumbers_stcf\n  StCameFromQNumbers.clear();\n  InFile.read((char*)&isize, sizeof(int));\n  for(iaux=0;iaux<isize;iaux++){\n    InFile.read(reinterpret_cast<char*>(&daux), sizeof(double));\n    StCameFromQNumbers.push_back(daux);\n  }\n\n\n}\n/////////////\n\n\n\n///////////////\n", "meta": {"hexsha": "2bb43a29a1a6e8ce251ddd857e9ca65b6b32cb56", "size": 47903, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NRGarrayClass.cpp", "max_stars_repo_name": "lgds/NRG_USP", "max_stars_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-21T20:58:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-20T01:21:41.000Z", "max_issues_repo_path": "src/NRGarrayClass.cpp", "max_issues_repo_name": "lgds/NRG_USP", "max_issues_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NRGarrayClass.cpp", "max_forks_repo_name": "lgds/NRG_USP", "max_forks_repo_head_hexsha": "ff66846e92498aa429cce6fc5793bec23ad03eb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0413660414, "max_line_length": 103, "alphanum_fraction": 0.6033233827, "num_tokens": 15753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4109839536767612}}
{"text": "//---------------------------------------------------------------------------//\n//  MIT License\n//\n//  Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n//  Copyright (c) 2020-2021 Nikita Kaskov <nemo@nil.foundation>\n\n//\n//  Permission is hereby granted, free of charge, to any person obtaining a copy\n//  of this software and associated documentation files (the \"Software\"), to deal\n//  in the Software without restriction, including without limitation the rights\n//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n//  copies of the Software, and to permit persons to whom the Software is\n//  furnished to do so, subject to the following conditions:\n//\n//  The above copyright notice and this permission notice shall be included in all\n//  copies or substantial portions of the Software.\n//\n//  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n//  SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#include <boost/filesystem/path.hpp>\n\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark.hpp>\n\nnamespace nil {\n    namespace filecoin {\n        template<typename SchemeType>\n        struct scheme_params {\n            typedef SchemeType scheme_type;\n        };\n\n        template<typename CurveType>\n        struct scheme_params<crypto3::zk::snark::r1cs_gg_ppzksnark<CurveType>> {\n            typedef CurveType curve_type;\n            typedef typename curve_type::template g1_type<> g1_type;\n\n            typedef crypto3::zk::snark::r1cs_gg_ppzksnark<CurveType> scheme_type;\n            typedef typename scheme_type::verifying_key_type verifying_key_type;\n\n            verifying_key_type vk;\n\n            // Elements of the form ((tau^i * t(tau)) / delta) for i between 0 and\n            // m-2 inclusive. Never contains points at infinity.\n            std::vector<typename g1_type::value_type> h;\n\n            // Elements of the form (beta * u_i(tau) + alpha v_i(tau) + w_i(tau)) / delta\n            // for all auxiliary inputs. Variables can never be unconstrained, so this\n            // never contains points at infinity.\n            std::vector<typename g1_type::value_type> l;\n\n            // QAP \"A\" polynomials evaluated at tau in the Lagrange basis. Never contains\n            // points at infinity: polynomials that evaluate to zero are omitted from\n            // the CRS and the prover can deterministically skip their evaluation.\n            std::vector<typename g1_type::value_type> a;\n\n            // QAP \"B\" polynomials evaluated at tau in the Lagrange basis. Needed\n            // in G1 and G2 for C/B queries, respectively. Never contains points at\n            // infinity for the same reason as the \"A\" polynomials.\n            std::vector<typename g1_type::value_type> b_g1;\n            std::vector<typename g1_type::value_type> b_g2;\n        };\n    }    // namespace filecoin\n}    // namespace nil\n", "meta": {"hexsha": "4386a767f1dae20be02a2a420389dc0477ad155f", "size": 3334, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/crypto/scheme_params.hpp", "max_stars_repo_name": "NilFoundation/crypto3-fil-proofs", "max_stars_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/crypto/scheme_params.hpp", "max_issues_repo_name": "NilFoundation/crypto3-fil-proofs", "max_issues_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-06T13:07:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T12:38:09.000Z", "max_forks_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/crypto/scheme_params.hpp", "max_forks_repo_name": "NilFoundation/crypto3-fil-proofs", "max_forks_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6285714286, "max_line_length": 89, "alphanum_fraction": 0.6526694661, "num_tokens": 750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8152324713956856, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.41080067275195803}}
{"text": "#include <cmath>\n#include <iostream>\n\n#include <Eigen/Cholesky>\n#include <Eigen/LU>\n#include <Eigen/SVD>\n\n#include \"drake/solvers/fast_qp.h\"\n#include \"drake/solvers/gurobi_qp.h\"\n\n#define MAX_CONSTRS 1000\n#define MAX_STATE 1000\n#define MAX_ITER 10\n\n// TODO(jwnimmer-tri) Someone with gurobi needs to fix these.\n// NOLINTNEXTLINE(build/namespaces)\nusing namespace Eigen;\n// NOLINTNEXTLINE(build/namespaces)\nusing namespace std;\n\n// template <typename tA, typename tB, typename tC, typename tD, typename tE,\n// typename tF, typename tG>\n// int fastQPThatTakesQinv(vector< MatrixBase<tA>* > QinvblkDiag, const\n// MatrixBase<tB>& f, const MatrixBase<tC>& Aeq, const MatrixBase<tD>& beq,\n// const MatrixBase<tE>& Ain, const MatrixBase<tF>& bin, set<int>& active,\n// MatrixBase<tG>& x)\nint fastQPThatTakesQinv(vector<MatrixXd*> QinvblkDiag, const VectorXd& f,\n                        const MatrixXd& Aeq, const VectorXd& beq,\n                        const MatrixXd& Ain, const VectorXd& bin,\n                        // TODO(#2274) Fix NOLINTNEXTLINE(runtime/references).\n                        set<int>& active, VectorXd& x) {\n  int i, d;\n  int iterCnt = 0;\n\n  int M_in = bin.size();\n  int M = Aeq.rows();\n  int N = Aeq.cols();\n\n  if (f.rows() != N) {\n    cerr << \"size of f (\" << f.rows() << \" by \" << f.cols()\n         << \") doesn't match cols of Aeq (\" << Aeq.rows() << \" by \"\n         << Aeq.cols() << \")\" << endl;\n    return 2;\n  }\n  if (beq.rows() != M) {\n    cerr << \"size of beq doesn't match rows of Aeq\" << endl;\n    return 2;\n  }\n  if (Ain.cols() != N) {\n    cerr << \"cols of Ain doesn't match cols of Aeq\" << endl;\n    return 2;\n  }\n  if (bin.rows() != Ain.rows()) {\n    cerr << \"bin rows doesn't match Ain rows\" << endl;\n    return 2;\n  }\n  if (x.rows() != N) {\n    cerr << \"x doesn't match Aeq\" << endl;\n    return 2;\n  }\n  int n_active = active.size();\n\n  MatrixXd Aact = MatrixXd(n_active, N);\n  VectorXd bact = VectorXd(n_active);\n\n  MatrixXd QinvAteq(N, M);\n  VectorXd minusQinvf(N);\n\n  // calculate a bunch of stuff that is constant during each iteration\n  int startrow = 0;\n  //  for (typename vector< MatrixBase<tA>* >::iterator\n  //  iterQinv=QinvblkDiag.begin(); iterQinv!=QinvblkDiag.end(); iterQinv++) {\n  //    MatrixBase<tA> *thisQinv = *iterQinv;\n  for (vector<MatrixXd*>::iterator iterQinv = QinvblkDiag.begin();\n       iterQinv != QinvblkDiag.end(); iterQinv++) {\n    MatrixXd* thisQinv = *iterQinv;\n    int numRow = thisQinv->rows();\n    int numCol = thisQinv->cols();\n\n    if (numRow == 1 || numCol == 1) {  // it's a vector\n      d = numRow * numCol;\n      if (M > 0)\n        QinvAteq.block(startrow, 0, d, M) =\n            thisQinv->asDiagonal() *\n            Aeq.block(0, startrow, M, d)\n                .transpose();  // Aeq.transpose().block(startrow, 0, d, N)\n      minusQinvf.segment(startrow, d) =\n          -thisQinv->cwiseProduct(f.segment(startrow, d));\n      startrow = startrow + d;\n    } else {  // potentially dense matrix\n      d = numRow;\n      if (numRow != numCol) {\n        cerr << \"Q is not square! \" << numRow << \"x\" << numCol << \"\\n\";\n        return -2;\n      }\n      if (M > 0)\n        QinvAteq.block(startrow, 0, d, M) = thisQinv->operator*(\n            Aeq.block(0, startrow, M, d)\n                .transpose());  // Aeq.transpose().block(startrow, 0, d, N)\n      minusQinvf.segment(startrow, d) =\n          -thisQinv->operator*(f.segment(startrow, d));\n      startrow = startrow + d;\n    }\n    if (startrow > N) {\n      cerr << \"Q is too big!\" << endl;\n      return -2;\n    }\n  }\n  if (startrow != N) {\n    cerr << \"Q is the wrong size.  Got \" << startrow << \"by\" << startrow\n         << \" but needed \" << N << \"by\" << N << endl;\n    return -2;\n  }\n\n  MatrixXd A;\n  VectorXd b;\n  MatrixXd QinvAt;\n  VectorXd lam, lamIneq;\n  VectorXd violated(M_in);\n  VectorXd violation;\n\n  while (1) {\n    iterCnt++;\n\n    n_active = active.size();\n    Aact.resize(n_active, N);\n    bact.resize(n_active);\n\n    i = 0;\n    for (set<int>::iterator iter = active.begin(); iter != active.end();\n         iter++) {\n      if (*iter < 0 || *iter >= Ain.rows()) {\n        return -3;  // active set is invalid.  exit quietly, because this is\n                    // expected behavior in normal operation (e.g. it means I\n                    // should immediately kick out to Gurobi)\n      }\n      Aact.row(i) = Ain.row(*iter);\n      bact(i++) = bin(*iter);\n    }\n\n    A.resize(Aeq.rows() + Aact.rows(), N);\n    b.resize(beq.size() + bact.size());\n    A << Aeq, Aact;\n    b << beq, bact;\n\n    if (A.rows() > 0) {\n      // Solve H * [x;lam] = [-f;b] using Schur complements, H = [Q, At';A, 0];\n      QinvAt.resize(QinvAteq.rows(), QinvAteq.cols() + Aact.rows());\n\n      if (n_active > 0) {\n        startrow = 0;\n        for (vector<MatrixXd*>::iterator iterQinv = QinvblkDiag.begin();\n             iterQinv != QinvblkDiag.end(); iterQinv++) {\n          MatrixXd* thisQinv = (*iterQinv);\n          d = thisQinv->rows();\n          int numCol = thisQinv->cols();\n\n          if (numCol == 1) {  // it's a vector\n            QinvAt.block(startrow, 0, d, M + n_active)\n                << QinvAteq.block(startrow, 0, d, M),\n                thisQinv->asDiagonal() *\n                    Aact.block(0, startrow, n_active, d).transpose();\n          } else {  // it's a matrix\n            QinvAt.block(startrow, 0, d, M + n_active)\n                << QinvAteq.block(startrow, 0, d, M),\n                thisQinv->operator*(\n                    Aact.block(0, startrow, n_active, d).transpose());\n          }\n\n          startrow = startrow + d;\n        }\n      } else {\n        QinvAt = QinvAteq;\n      }\n\n      lam.resize(QinvAt.cols());\n      lam =\n          -(A * QinvAt).ldlt().solve(b + (f.transpose() * QinvAt).transpose());\n      x = minusQinvf - QinvAt * lam;\n      lamIneq = lam.tail(lam.size() - M);\n    } else {\n      x = minusQinvf;\n      lamIneq.resize(0);\n    }\n\n    if (Ain.rows() == 0) {\n      active.clear();\n      break;\n    }\n\n    set<int> new_active;\n\n    violation = Ain * x - bin;\n    for (i = 0; i < M_in; i++)\n      if (violation(i) >= 1e-6) new_active.insert(i);\n\n    bool all_pos_mults = true;\n    for (i = 0; i < n_active; i++) {\n      if (lamIneq(i) < 0) {\n        all_pos_mults = false;\n        break;\n      }\n    }\n    if (new_active.empty() && all_pos_mults) {\n      // existing active was AOK\n      break;\n    }\n\n    i = 0;\n    set<int>::iterator iter = active.begin(), tmp;\n    while (iter != active.end()) {  // to accommodating inloop erase\n      tmp = iter++;\n      if (lamIneq(i++) < 0) {\n        active.erase(tmp);\n      }\n    }\n    active.insert(new_active.begin(), new_active.end());\n\n    if (iterCnt > MAX_ITER) {\n      // Default to calling this method\n      //      cout << \"FastQP max iter reached.\" << endl;\n      //       mexErrMsgIdAndTxt(\"Drake:approximateIKmex:Error\", \"Max iter\n      //       reached. Problem is likely infeasible\");\n      return -1;\n    }\n  }\n  return iterCnt;\n}\n\n// template <typename tA, typename tB, typename tC, typename tD, typename tE,\n// typename tF, typename tG>\n// int fastQP(vector< MatrixBase<tA>* > QblkDiag, const MatrixBase<tB>& f, const\n// MatrixBase<tC>& Aeq, const MatrixBase<tD>& beq, const MatrixBase<tE>& Ain,\n// const MatrixBase<tF>& bin, set<int>& active, MatrixBase<tG>& x)\nint fastQP(vector<MatrixXd*> QblkDiag, const VectorXd& f, const MatrixXd& Aeq,\n           const VectorXd& beq, const MatrixXd& Ain, const VectorXd& bin,\n           // TODO(#2274) Fix NOLINTNEXTLINE(runtime/references).\n           set<int>& active, VectorXd& x) {\n  /* min 1/2 * x'QblkDiag'x + f'x s.t A x = b, Ain x <= bin\n   * using active set method.  Iterative solve a linearly constrained\n   * quadratic minimization problem where linear constraints include\n   * Ain(active,:)x == bin(active).  Quit if all dual variables associated\n   * with these equations are positive (i.e. they satisfy KKT conditions).\n   *\n   * Note:\n   * fails if QP is infeasible.\n   * active == initial rows of Ain to treat as equations.\n   * Frank Permenter - June 6th 2013\n   *\n   * @retval  if feasible then iterCnt, else -1 for infeasible, -2 for input\n   *error\n   */\n\n  int N = f.rows();\n\n  MatrixXd* Qinv = new MatrixXd[QblkDiag.size()];\n  vector<MatrixXd*> Qinvmap;\n\n#define REG 1e-13\n  // calculate a bunch of stuff that is constant during each iteration\n  int startrow = 0;\n  // typedef typename vector< MatrixBase<tA> >::iterator Qiterator;\n\n  int i = 0;\n  for (vector<MatrixXd*>::iterator iterQ = QblkDiag.begin();\n       iterQ != QblkDiag.end(); iterQ++) {\n    MatrixXd* thisQ = *iterQ;\n    int numRow = thisQ->rows();\n    int numCol = thisQ->cols();\n\n    if (numCol == 1) {  // it's a vector\n      VectorXd Qdiag_mod =\n          thisQ->operator+(VectorXd::Constant(numRow, REG));  // regularize\n      Qinv[i] = Qdiag_mod.cwiseInverse();\n      Qinvmap.push_back(&Qinv[i]);\n      startrow = startrow + numRow;\n    } else {  // potentially dense matrix\n      if (numRow != numCol) {\n        if (numRow == 1)\n          cerr << \"diagonal Q's must be set as column vectors\" << endl;\n        else\n          cerr << \"Q is not square! \" << numRow << \"x\" << numCol << endl;\n        return -2;\n      }\n\n      MatrixXd Q_mod =\n          thisQ->operator+(REG * MatrixXd::Identity(numRow, numRow));\n      Qinv[i] = Q_mod.inverse();\n      Qinvmap.push_back(&Qinv[i]);\n      startrow = startrow + numRow;\n    }\n    // cout << \"Qinv{\" << i << \"} = \" << Qinv[i] << endl;\n    if (startrow > N) {\n      cerr << \"Q is too big!\" << endl;\n      return -2;\n    }\n    i++;\n  }\n  if (startrow != N) {\n    cerr << \"Q is the wrong size.  Got \" << startrow << \"by\" << startrow\n         << \" but needed \" << N << \"by\" << N << endl;\n    return -2;\n  }\n\n  int info = fastQPThatTakesQinv(Qinvmap, f, Aeq, beq, Ain, bin, active, x);\n\n  delete[] Qinv;\n  return info;\n}\n\n/* Example call (allocate inequality matrix, call function, resize inequalites:\n  VectorXd binBnd = VectorXd(2*N);\n  AinBnd.setZero();\n  int numIneq = boundToIneq(ub, lb, AinBnd, binBnd);\n  AinBnd.resize(numIneq, N);\n  binBnd.resize(numIneq);\n*/\n/*\nint boundToIneq(const VectorXd& uB, const VectorXd& lB, MatrixXd& Ain, VectorXd&\nbin)\n{\n    int rCnt = 0;\n    int cCnt = 0;\n\n    if (uB.rows()+lB.rows() > A.rows() ) {\n        cerr << \"not enough memory allocated\";\n    }\n\n    if (uB.rows()+lB.rows() > b.rows() ) {\n        cerr << \"not enough memory allocated\";\n    }\n\n    for (int i = 0; i < lB.rows(); i++ ) {\n        if (!isinf(lB(i))) {\n            cout << lB(i);\n            cout << i;\n            Ain(rCnt, cCnt++) = -1;// lB(i);\n            bin(rCnt++) = -lB(i);\n        }\n    }\n    cCnt = 0;\n    for (int i = 0; i < uB.rows(); i++ ) {\n        if (!isinf(uB(i))) {\n            Ain(rCnt, cCnt++) = 1;// uB(i);\n            bin(rCnt++) = uB(i);\n        }\n    }\n\n    // resizing inside function all causes exception (why??)\n    // A.resize(rCnt, uB.rows());\n    return rCnt;\n}\n*/\n\ntemplate <typename DerivedA, typename DerivedB>\nint myGRBaddconstrs(GRBmodel* model, MatrixBase<DerivedA> const& A,\n                    MatrixBase<DerivedB> const& b, char sense,\n                    double sparseness_threshold = 1e-14) {\n  int i, j, nnz, error = 0;\n  /*\n    // todo: it seems like I should just be able to do something like this:\n    SparseMatrix<double, RowMajor> sparseAeq(Aeq.sparseView());\n    sparseAeq.makeCompressed();\n    error = GRBaddconstrs(\n        model, nq_con, sparseAeq.nonZeros(), sparseAeq.InnerIndices(),\n        sparseAeq.OuterStarts(), sparseAeq.Values(), beq.data(), NULL);\n  */\n\n  int* cind = new int[A.cols()];\n  double* cval = new double[A.cols()];\n  for (i = 0; i < A.rows(); i++) {\n    nnz = 0;\n    for (j = 0; j < A.cols(); j++) {\n      if (abs(A(i, j)) > sparseness_threshold) {\n        cval[nnz] = A(i, j);\n        cind[nnz++] = j;\n      }\n    }\n    error = GRBaddconstr(model, nnz, cind, cval, sense, b(i), NULL);\n    if (error) break;\n  }\n\n  delete[] cind;\n  delete[] cval;\n  return error;\n}\n\n// template <typename tA, typename tB, typename tC, typename tD, typename tE>\n// GRBmodel* gurobiQP(GRBenv *env, vector< MatrixBase<tA>* > QblkDiag, VectorXd&\n// f, const MatrixBase<tB>& Aeq, const MatrixBase<tC>& beq, const\n// MatrixBase<tD>& Ain, const MatrixBase<tE>& bin, VectorXd& lb, VectorXd& ub,\n// set<int>& active, VectorXd& x)\nGRBmodel* gurobiQP(GRBenv* env, vector<MatrixXd*> QblkDiag,\n                   // TODO(#2274) Fix NOLINTNEXTLINE(runtime/references).\n                   VectorXd& f,\n                   const MatrixXd& Aeq, const VectorXd& beq,\n                   const MatrixXd& Ain, const VectorXd& bin,\n                   // TODO(#2274) Fix NOLINTNEXTLINE(runtime/references).\n                   VectorXd& lb, VectorXd& ub, set<int>& active, VectorXd& x,\n                   double active_set_slack_tolerance) {\n  // Note: f, lb, and ub are VectorXd instead of const MatrixBase templates\n  // because i want to be able to call f.data() on them\n\n  // NOTE:  this allocates memory for a new GRBmodel and returns it. (you should\n  // delete this object when you're done with it)\n  // NOTE:  by convention here, the active set indices correspond to Ain, bin\n  // first, then lb, then ub.\n\n  GRBmodel* model = NULL;\n\n  int method;\n  GRBgetintparam(env, \"method\", &method);\n\n  int i, j, nparams = f.rows(), Qi, Qj;\n  double* lbdata = NULL, * ubdata = NULL;\n  if (lb.rows() == nparams) lbdata = lb.data();\n  if (ub.rows() == nparams) ubdata = ub.data();\n  CGE(GRBnewmodel(env, &model, \"QP\", nparams, NULL, lbdata, ubdata, NULL, NULL),\n      env);\n\n  int startrow = 0, d;\n  for (vector<MatrixXd*>::iterator iterQ = QblkDiag.begin();\n       iterQ != QblkDiag.end(); iterQ++) {\n    MatrixXd* Q = *iterQ;\n\n    // WARNING:  If there are no constraints, then Gurobi clearly solves a\n    // different problem: min 1/2 x'Qx + f'x\n    // This is very strange; see the solveWGUROBI method in QuadraticProgram\n    if (method == 2)  //&& (Aeq.rows()+Ain.rows()>0))\n      *Q = .5 * (*Q);\n\n    if (Q->rows() == 1 || Q->cols() == 1) {  // it's a vector\n      d = Q->rows() * Q->cols();\n      for (i = 0; i < d; i++) {\n        Qi = i + startrow;\n        double& qval = Q->operator()(i);\n        CGE(GRBaddqpterms(model, 1, &Qi, &Qi, &qval), env);\n      }\n      startrow = startrow + d;\n    } else {  // potentially dense matrix\n      d = Q->rows();\n      if (d != Q->cols()) {\n        cerr << \"Q is not square! \" << Q->rows() << \"x\" << Q->cols() << \"\\n\";\n        return NULL;\n      }\n\n      for (i = 0; i < d; i++)\n        for (j = 0; j < d; j++) {\n          Qi = i + startrow;\n          Qj = j + startrow;\n          double& qval = Q->operator()(i, j);\n          CGE(GRBaddqpterms(model, 1, &Qi, &Qj, &qval), env);\n        }\n      startrow = startrow + d;\n    }\n    if (startrow > nparams) {\n      cerr << \"Q is too big!\" << endl;\n      return NULL;\n    }\n  }\n\n  CGE(GRBsetdblattrarray(model, \"Obj\", 0, nparams, f.data()), env);\n\n  if (Aeq.rows() > 0)\n    CGE(myGRBaddconstrs(model, Aeq, beq, GRB_EQUAL, 1e-18), env);\n  if (Ain.rows() > 0)\n    CGE(myGRBaddconstrs(model, Ain, bin, GRB_LESS_EQUAL, 1e-18), env);\n\n  CGE(GRBupdatemodel(model), env);\n  CGE(GRBoptimize(model), env);\n\n  CGE(GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, nparams, x.data()), env);\n\n  VectorXd slack(Ain.rows());\n  CGE(GRBgetdblattrarray(model, \"Slack\", Aeq.rows(), Ain.rows(), slack.data()),\n      env);\n\n  int offset = 0;\n  active.clear();\n  for (int k = 0; k < Ain.rows(); k++) {\n    if (slack(k) < active_set_slack_tolerance) active.insert(k);\n  }\n  offset = Ain.rows();\n  if (lb.rows() == nparams) {\n    for (int k = 0; k < nparams; k++) {\n      if (x(k) - lb(k) < active_set_slack_tolerance) active.insert(offset + k);\n    }\n  }\n  if (ub.rows() == nparams) {\n    for (int k = 0; k < nparams; k++) {\n      if (ub(k) - x(k) < active_set_slack_tolerance) {\n        active.insert(offset + k + nparams);\n      }\n    }\n  }\n\n  return model;\n}\n\nGRBmodel* gurobiActiveSetQP(GRBenv* env, vector<MatrixXd*> QblkDiag,\n                            // TODO(#2274) NOLINTNEXTLINE(runtime/references).\n                            VectorXd& f,\n                            const MatrixXd& Aeq,\n                            const VectorXd& beq, const MatrixXd& Ain,\n                            const VectorXd& bin,\n                            // TODO(#2274) NOLINTNEXTLINE(runtime/references).\n                            VectorXd& lb, VectorXd& ub,\n                            // TODO(#2274) NOLINTNEXTLINE(runtime/references).\n                            int*& vbasis, int vbasis_len,\n                            // TODO(#2274) NOLINTNEXTLINE(runtime/references).\n                            int*& cbasis, int cbasis_len,\n                            // TODO(#2274) NOLINTNEXTLINE(runtime/references).\n                            VectorXd& x) {\n  // NOTE:  this allocates memory for a new GRBmodel and returns it. (you should\n  // delete this object when you're done with it)\n  // NOTE:  by convention here, the active set indices correspond to Ain, bin\n  // first, then lb, then ub.\n  GRBmodel* model = NULL;\n\n  int method;\n  GRBgetintparam(env, \"method\", &method);\n  if (!(method == 0 || method == 1)) {\n    cerr << \"gurobiActiveSetQP: method should be 0 or 1\" << endl;\n    return NULL;\n  }\n\n  int i, j, nparams = f.rows(), Qi, Qj;\n  double* lbdata = NULL, * ubdata = NULL;\n  if (lb.rows() == nparams) lbdata = lb.data();\n  if (ub.rows() == nparams) ubdata = ub.data();\n  CGE(GRBnewmodel(env, &model, \"QP\", nparams, NULL, lbdata, ubdata, NULL, NULL),\n      env);\n\n  int startrow = 0, d;\n  for (vector<MatrixXd*>::iterator iterQ = QblkDiag.begin();\n       iterQ != QblkDiag.end(); iterQ++) {\n    MatrixXd* Q = *iterQ;\n\n    *Q = .5 * (*Q);\n\n    if (Q->rows() == 1 || Q->cols() == 1) {  // it's a vector\n      d = Q->rows() * Q->cols();\n      for (i = 0; i < d; i++) {\n        Qi = i + startrow;\n        double& qval = Q->operator()(i);\n        CGE(GRBaddqpterms(model, 1, &Qi, &Qi, &qval), env);\n      }\n      startrow = startrow + d;\n    } else {  // potentially dense matrix\n      d = Q->rows();\n      if (d != Q->cols()) {\n        cerr << \"Q is not square! \" << Q->rows() << \"x\" << Q->cols() << \"\\n\";\n        return NULL;\n      }\n\n      for (i = 0; i < d; i++)\n        for (j = 0; j < d; j++) {\n          Qi = i + startrow;\n          Qj = j + startrow;\n          double& qval = Q->operator()(i, j);\n          CGE(GRBaddqpterms(model, 1, &Qi, &Qj, &qval), env);\n        }\n      startrow = startrow + d;\n    }\n    if (startrow > nparams) {\n      cerr << \"Q is too big!\" << endl;\n      return NULL;\n    }\n  }\n\n  CGE(GRBsetdblattrarray(model, \"Obj\", 0, nparams, f.data()), env);\n\n  if (Aeq.rows() > 0)\n    CGE(myGRBaddconstrs(model, Aeq, beq, GRB_EQUAL, 1e-18), env);\n  if (Ain.rows() > 0)\n    CGE(myGRBaddconstrs(model, Ain, bin, GRB_LESS_EQUAL, 1e-18), env);\n\n  CGE(GRBupdatemodel(model), env);\n\n  int numvars;\n  CGE(GRBgetintattr(model, \"NumVars\", &numvars), env);\n  if (numvars == vbasis_len) {\n    CGE(GRBsetintattrarray(model, \"VBasis\", 0, numvars, vbasis), env);\n  } else {\n    delete[] vbasis;\n    vbasis = new int[numvars];\n  }\n\n  int numconstr;\n  CGE(GRBgetintattr(model, \"NumConstrs\", &numconstr), env);\n  if (numconstr == cbasis_len) {\n    CGE(GRBsetintattrarray(model, \"CBasis\", 0, numconstr, cbasis), env);\n  } else {\n    delete[] cbasis;\n    cbasis = new int[numconstr];\n  }\n  CGE(GRBoptimize(model), env);\n\n  CGE(GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, nparams, x.data()), env);\n\n  CGE(GRBgetintattrarray(model, \"VBasis\", 0, numvars, vbasis), env);\n  CGE(GRBgetintattrarray(model, \"CBasis\", 0, numconstr, cbasis), env);\n\n  return model;\n}\n\n", "meta": {"hexsha": "b4ac5f2169eb8ca701f95dc07b741333a61d9000", "size": 19548, "ext": "cc", "lang": "C++", "max_stars_repo_path": "solvers/qp.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "solvers/qp.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solvers/qp.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 32.2042833608, "max_line_length": 80, "alphanum_fraction": 0.5568856149, "num_tokens": 6096, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.41069735619847875}}
{"text": "/*  This file is part of libDAI - http://www.libdai.org/\n *\n *  Copyright (c) 2006-2011, The libDAI authors. All rights reserved.\n *\n *  Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.\n */\n\n\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <numeric>\n#include <cmath>\n#include <cstdlib>\n#include <cstring>\n#include <boost/program_options.hpp>\n#include <dai/util.h>\n#include <dai/alldai.h>\n\n\nusing namespace std;\nusing namespace dai;\nnamespace po = boost::program_options;\n\n\nstd::vector<Real> calcDists( const vector<Factor> &x, const vector<Factor> &y ) {\n    vector<Real> errs;\n    errs.reserve( x.size() );\n    DAI_ASSERT( x.size() == y.size() );\n    for( size_t i = 0; i < x.size(); i++ )\n        errs.push_back( dist( x[i], y[i], DISTTV ) );\n    return errs;\n}\n\n\n/// Wrapper class for DAI approximate inference algorithms\nclass TestDAI {\n    protected:\n        /// Stores a pointer to an InfAlg object, managed by this class\n        InfAlg          *obj;\n        /// Stores the name of the InfAlg algorithm\n        string          name;\n        /// Stores the total variation distances of the variable marginals\n        vector<Real>    varErr;\n        /// Stores the total variation distances of the factor marginals\n        vector<Real>    facErr;\n\n    public:\n        /// Stores the variable marginals\n        vector<Factor>  varMarginals;\n        /// Stores the factor marginals\n        vector<Factor>  facMarginals;\n        /// Stores all marginals\n        vector<Factor>  allMarginals;\n        /// Stores the logarithm of the partition sum\n        Real            logZ;\n        /// Stores the maximum difference in the last iteration\n        Real            maxdiff;\n        /// Stores the computation time (in seconds)\n        double          time;\n        /// Stores the number of iterations needed\n        size_t          iters;\n        /// Does the InfAlg support logZ()?\n        bool            has_logZ;\n        /// Does the InfAlg support maxDiff()?\n        bool            has_maxdiff;\n        /// Does the InfAlg support Iterations()?\n        bool            has_iters;\n\n        /// Construct from factor graph \\a fg, name \\a _name, and set of properties \\a opts\n        TestDAI( const FactorGraph &fg, const string &_name, const PropertySet &opts ) : obj(NULL), name(_name), varErr(), facErr(), varMarginals(), facMarginals(), allMarginals(), logZ(0.0), maxdiff(0.0), time(0), iters(0U), has_logZ(false), has_maxdiff(false), has_iters(false) {\n            double tic = toc();\n\n            if( name == \"LDPC\" ) {\n                // special case: simulating a Low Density Parity Check code\n                Real zero[2] = {1.0, 0.0};\n                for( size_t i = 0; i < fg.nrVars(); i++ )\n                    varMarginals.push_back( Factor(fg.var(i), zero) );\n                allMarginals = varMarginals;\n                logZ = 0.0;\n                maxdiff = 0.0;\n                iters = 1;\n                has_logZ = false;\n                has_maxdiff = false;\n                has_iters = false;\n            } else\n                // create a corresponding InfAlg object\n                obj = newInfAlg( name, fg, opts );\n\n            // Add the time needed to create the object\n            time += toc() - tic;\n        }\n\n        /// Destructor\n        ~TestDAI() {\n            if( obj != NULL )\n                delete obj;\n        }\n\n        /// Identify\n        string identify() const {\n            if( obj != NULL )\n                return obj->identify();\n            else\n                return \"NULL\";\n        }\n\n        /// Run the algorithm and store its results\n        void doDAI() {\n            double tic = toc();\n            if( obj != NULL ) {\n                // Initialize\n                obj->init();\n                // Run\n                obj->run();\n                // Record the time\n                time += toc() - tic;\n\n                // Store logarithm of the partition sum (if supported)\n                try {\n                    logZ = obj->logZ();\n                    has_logZ = true;\n                } catch( Exception &e ) {\n                    if( e.getCode() == Exception::NOT_IMPLEMENTED )\n                        has_logZ = false;\n                    else\n                        throw;\n                }\n\n                // Store maximum difference encountered in last iteration (if supported)\n                try {\n                    maxdiff = obj->maxDiff();\n                    has_maxdiff = true;\n                } catch( Exception &e ) {\n                    if( e.getCode() == Exception::NOT_IMPLEMENTED )\n                        has_maxdiff = false;\n                    else\n                        throw;\n                }\n\n                // Store number of iterations needed (if supported)\n                try {\n                    iters = obj->Iterations();\n                    has_iters = true;\n                } catch( Exception &e ) {\n                    if( e.getCode() == Exception::NOT_IMPLEMENTED )\n                        has_iters = false;\n                    else\n                        throw;\n                }\n\n                // Store variable marginals\n                varMarginals.clear();\n                for( size_t i = 0; i < obj->fg().nrVars(); i++ )\n                    varMarginals.push_back( obj->beliefV( i ) );\n\n                // Store factor marginals\n                facMarginals.clear();\n                for( size_t I = 0; I < obj->fg().nrFactors(); I++ )\n                    try {\n                        facMarginals.push_back( obj->beliefF( I ) );\n                    } catch( Exception &e ) {\n                        if( e.getCode() == Exception::BELIEF_NOT_AVAILABLE )\n                            facMarginals.push_back( Factor( obj->fg().factor(I).vars(), INFINITY ) );\n                        else\n                            throw;\n                    }\n\n                // Store all marginals calculated by the method\n                allMarginals = obj->beliefs();\n            };\n        }\n\n        /// Calculate total variation distance of variable and factor marginals with respect to those in \\a varMargs and \\a facMargs\n        void calcErrors( const vector<Factor>& varMargs, const vector<Factor>& facMargs ) {\n            varErr = calcDists( varMarginals, varMargs );\n            facErr = calcDists( facMarginals, facMargs );\n        }\n\n        /// Return maximum variable error\n        Real maxVarErr() {\n            return( *max_element( varErr.begin(), varErr.end() ) );\n        }\n\n        /// Return average variable error\n        Real avgVarErr() {\n            return( accumulate( varErr.begin(), varErr.end(), 0.0 ) / varErr.size() );\n        }\n\n        /// Return maximum factor error\n        Real maxFacErr() {\n            return( *max_element( facErr.begin(), facErr.end() ) );\n        }\n\n        /// Return average factor error\n        Real avgFacErr() {\n            return( accumulate( facErr.begin(), facErr.end(), 0.0 ) / facErr.size() );\n        }\n};\n\n\n/// Clips a real number: if the absolute value of \\a x is less than \\a minabs, return \\a minabs, else return \\a x\nReal clipReal( Real x, Real minabs ) {\n    if( abs(x) < minabs )\n        return minabs;\n    else\n        return x;\n}\n\n\n/// Which marginals to outpu (none, only variable, only factor, variable and factor, all)\nDAI_ENUM(MarginalsOutputType,NONE,VAR,FAC,VARFAC,ALL);\n\n\n/// Main function\nint main( int argc, char *argv[] ) {\n    // Variables to store command line options\n    // Filename of factor graph\n    string filename;\n    // Filename for aliases\n    string aliases;\n    // Approximate Inference methods to use\n    vector<string> methods;\n    // Which marginals to output\n    MarginalsOutputType marginals;\n    // Output number of iterations?\n    bool report_iters = true;\n    // Output calculation time?\n    bool report_time = true;\n\n    // Define required command line options\n    po::options_description opts_required(\"Required options\");\n    opts_required.add_options()\n        (\"filename\", po::value< string >(&filename), \"Filename of factor graph\")\n        (\"methods\", po::value< vector<string> >(&methods)->multitoken(), \"DAI methods to perform\")\n    ;\n\n    // Define allowed command line options\n    po::options_description opts_optional(\"Allowed options\");\n    opts_optional.add_options()\n        (\"help\", \"Produce help message\")\n        (\"aliases\", po::value< string >(&aliases), \"Filename for aliases\")\n        (\"marginals\", po::value< MarginalsOutputType >(&marginals), \"Output marginals? (NONE/VAR/FAC/VARFAC/ALL, default=NONE)\")\n        (\"report-time\", po::value< bool >(&report_time), \"Output calculation time (default==1)?\")\n        (\"report-iters\", po::value< bool >(&report_iters), \"Output iterations needed (default==1)?\")\n    ;\n\n    // Define all command line options\n    po::options_description cmdline_options;\n    cmdline_options.add(opts_required).add(opts_optional);\n\n    // Parse command line\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, cmdline_options), vm);\n    po::notify(vm);\n\n    // Display help message if necessary\n    if( vm.count(\"help\") || !(vm.count(\"filename\") && vm.count(\"methods\")) ) {\n        cout << \"This program is part of libDAI - http://www.libdai.org/\" << endl << endl;\n        cout << \"Usage: ./testdai --filename <filename.fg> --methods <method1> [<method2> <method3> ...]\" << endl << endl;\n        cout << \"Reads factor graph <filename.fg> and performs the approximate inference algorithms\" << endl;\n        cout << \"<method*>, reporting for each method:\" << endl;\n        cout << \"  o the calculation time needed, in seconds (if report-time == 1);\" << endl;\n        cout << \"  o the number of iterations needed (if report-iters == 1);\" << endl;\n        cout << \"  o the maximum (over all variables) total variation error in the variable marginals;\" << endl;\n        cout << \"  o the average (over all variables) total variation error in the variable marginals;\" << endl;\n        cout << \"  o the maximum (over all factors) total variation error in the factor marginals;\" << endl;\n        cout << \"  o the average (over all factors) total variation error in the factor marginals;\" << endl;\n        cout << \"  o the error (difference) of the logarithm of the partition sums;\" << endl << endl;\n        cout << \"All errors are calculated by comparing the results of the current method with\" << endl; \n        cout << \"the results of the first method (the base method). If marginals==VAR, additional\" << endl;\n        cout << \"output consists of the variable marginals, if marginals==FAC, the factor marginals\" << endl;\n        cout << \"if marginals==VARFAC, both variable and factor marginals, and if marginals==ALL, all\" << endl;\n        cout << \"marginals calculated by the method are reported.\" << endl << endl;\n        cout << \"<method*> should be a list of one or more methods, seperated by spaces, in the format:\" << endl << endl;\n        cout << \"    name[key1=val1,key2=val2,key3=val3,...,keyn=valn]\" << endl << endl;\n        cout << \"where name should be the name of an algorithm in libDAI (or an alias, if an alias\" << endl;\n        cout << \"filename is provided), followed by a list of properties (surrounded by rectangular\" << endl;\n        cout << \"brackets), where each property consists of a key=value pair and the properties are\" << endl;\n        cout << \"seperated by commas. If an alias file is specified, alias substitution is performed.\" << endl;\n        cout << \"This is done by looking up the name in the alias file and substituting the alias\" << endl;\n        cout << \"by its corresponding method as defined in the alias file. Properties are parsed from\" << endl;\n        cout << \"left to right, so if a property occurs repeatedly, the right-most value is used.\" << endl << endl;\n        cout << opts_required << opts_optional << endl;\n#ifdef DAI_DEBUG\n        cout << \"Note: this is a debugging build of libDAI.\" << endl << endl;\n#endif\n        cout << \"Example:  ./testdai --filename testfast.fg --aliases aliases.conf --methods JTREE_HUGIN BP_SEQFIX BP_PARALL[maxiter=5]\" << endl;\n        return 1;\n    }\n\n    try {\n        // Read aliases\n        map<string,string> Aliases;\n        if( !aliases.empty() )\n            Aliases = readAliasesFile( aliases );\n\n        // Read factor graph\n        FactorGraph fg;\n        fg.ReadFromFile( filename.c_str() );\n\n        // Declare variables used for storing variable factor marginals and log partition sum of base method\n        vector<Factor> varMarginals0;\n        vector<Factor> facMarginals0;\n        Real logZ0 = 0.0;\n\n        // Output header\n        cout.setf( ios_base::scientific );\n        cout.precision( 3 );\n        cout << \"# \" << filename << endl;\n        cout.width( 39 );\n        cout << left << \"# METHOD\" << \"\\t\";\n        if( report_time )\n            cout << right << \"SECONDS  \" << \"\\t\";\n        if( report_iters )\n            cout << \"ITERS\" << \"\\t\";\n        cout << \"MAX VAR ERR\" << \"\\t\";\n        cout << \"AVG VAR ERR\" << \"\\t\";\n        cout << \"MAX FAC ERR\" << \"\\t\";\n        cout << \"AVG FAC ERR\" << \"\\t\";\n        cout << \"LOGZ ERROR\" << \"\\t\";\n        cout << \"MAXDIFF\" << \"\\t\";\n        cout << endl;\n\n        // For each method...\n        for( size_t m = 0; m < methods.size(); m++ ) {\n            // Parse method\n            pair<string, PropertySet> meth = parseNameProperties( methods[m], Aliases );\n\n            // Construct object for running the method\n            TestDAI testdai(fg, meth.first, meth.second );\n\n            // Run the method\n            testdai.doDAI();\n\n            // For the base method, store its variable marginals and logarithm of the partition sum\n            if( m == 0 ) {\n                varMarginals0 = testdai.varMarginals;\n                facMarginals0 = testdai.facMarginals;\n                logZ0 = testdai.logZ;\n            }\n\n            // Calculate errors relative to base method\n            testdai.calcErrors( varMarginals0, facMarginals0 );\n\n            // Output method name\n            cout.width( 39 );\n            cout << left << methods[m] << \"\\t\";\n            // Output calculation time, if requested\n            if( report_time )\n                cout << right << testdai.time << \"\\t\";\n            // Output number of iterations, if requested\n            if( report_iters ) {\n                if( testdai.has_iters ) {\n                    cout << testdai.iters << \"\\t\";\n                } else {\n                    cout << \"N/A  \\t\";\n                }\n            }\n\n            // If this is not the base method\n            if( m > 0 ) {\n                cout.setf( ios_base::scientific );\n                cout.precision( 3 );\n\n                // Output maximum error in variable marginals\n                Real mev = clipReal( testdai.maxVarErr(), 1e-9 );\n                cout << mev << \"\\t\";\n\n                // Output average error in variable marginals\n                Real aev = clipReal( testdai.avgVarErr(), 1e-9 );\n                cout << aev << \"\\t\";\n\n                // Output maximum error in factor marginals\n                Real mef = clipReal( testdai.maxFacErr(), 1e-9 );\n                if( mef == INFINITY )\n                    cout << \"N/A       \\t\";\n                else\n                    cout << mef << \"\\t\";\n\n                // Output average error in factor marginals\n                Real aef = clipReal( testdai.avgFacErr(), 1e-9 );\n                if( aef == INFINITY )\n                    cout << \"N/A       \\t\";\n                else\n                    cout << aef << \"\\t\";\n\n                // Output error in log partition sum\n                if( testdai.has_logZ ) {\n                    cout.setf( ios::showpos );\n                    Real le = clipReal( testdai.logZ - logZ0, 1e-9 );\n                    cout << le << \"\\t\";\n                    cout.unsetf( ios::showpos );\n                } else\n                    cout << \"N/A       \\t\";\n\n                // Output maximum difference in last iteration\n                if( testdai.has_maxdiff ) {\n                    Real md = clipReal( testdai.maxdiff, 1e-9 );\n                    if( dai::isnan( mev ) )\n                        md = mev;\n                    if( dai::isnan( aev ) )\n                        md = aev;\n                    if( md == INFINITY )\n                        md = 1.0;\n                    cout << md << \"\\t\";\n                } else\n                    cout << \"N/A    \\t\";\n            }\n            cout << endl;\n\n            // Output marginals, if requested\n            if( marginals == MarginalsOutputType::VAR || marginals == MarginalsOutputType::VARFAC )\n                for( size_t i = 0; i < testdai.varMarginals.size(); i++ )\n                    cout << \"# \" << testdai.varMarginals[i] << endl;\n            if( marginals == MarginalsOutputType::FAC || marginals == MarginalsOutputType::VARFAC )\n                for( size_t I = 0; I < testdai.facMarginals.size(); I++ )\n                    cout << \"# \" << testdai.facMarginals[I] << endl;\n            if( marginals == MarginalsOutputType::ALL )\n                for( size_t I = 0; I < testdai.allMarginals.size(); I++ )\n                    cout << \"# \" << testdai.allMarginals[I] << endl;\n        }\n\n        return 0;\n    } catch( string &s ) {\n        // Abort with error message\n        cerr << \"Exception: \" << s << endl;\n        return 2;\n    }\n}\n", "meta": {"hexsha": "b40efe0377582a61f7e784f3009072c9b8745b7b", "size": 17391, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/testdai.cpp", "max_stars_repo_name": "chang-liang/HadoopBNEM", "max_stars_repo_head_hexsha": "dd90a70786271ebf5b0beda2484f8e476ab4a97a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T18:56:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T20:30:50.000Z", "max_issues_repo_path": "tests/testdai.cpp", "max_issues_repo_name": "chang-liang/HadoopBNEM", "max_issues_repo_head_hexsha": "dd90a70786271ebf5b0beda2484f8e476ab4a97a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-01-18T08:17:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-28T18:08:38.000Z", "max_forks_repo_path": "tests/testdai.cpp", "max_forks_repo_name": "chang-liang/HadoopBNEM", "max_forks_repo_head_hexsha": "dd90a70786271ebf5b0beda2484f8e476ab4a97a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2015-04-07T07:38:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T22:18:58.000Z", "avg_line_length": 40.3503480278, "max_line_length": 281, "alphanum_fraction": 0.5273992295, "num_tokens": 4033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592641, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4106372515801443}}
{"text": "#ifndef FSTCRITERIONMULTINOMBHATTACHARYYA_H\n#define FSTCRITERIONMULTINOMBHATTACHARYYA_H\n\n/*!======================================================================\n   Feature Selection Toolbox 3 source code\n   ---------------------------------------\n\t\n   \\file    criterion_multinom_bhattacharyya.hpp\n   \\brief   Implements Bhattacharyya distance based on multinomial model to serve as feature selection criterion\n   \\author  Petr Somol (somol@utia.cas.cz) with collaborators, see Contacts at http://fst.utia.cz\n   \\date    March 2011\n   \\version 3.1.0.beta\n   \\note    FST3 was developed using gcc 4.3 and requires\n   \\note    \\li Boost library (http://www.boost.org/, tested with versions 1.33.1 and 1.44),\n   \\note    \\li (\\e optionally) LibSVM (http://www.csie.ntu.edu.tw/~cjlin/libsvm/, \n                tested with version 3.00)\n   \\note    Note that LibSVM is required for SVM related tools only,\n            as demonstrated in demo12t.cpp, demo23.cpp, demo25t.cpp, demo32t.cpp, etc.\n\n*/ /* \n=========================================================================\nCopyright:\n  * FST3 software (with exception of any externally linked libraries) \n    is copyrighted by Institute of Information Theory and Automation (UTIA), \n    Academy of Sciences of the Czech Republic.\n  * FST3 source codes as presented here do not contain code of third parties. \n    FST3 may need linkage to external libraries to exploit its functionality\n    in full. For details on obtaining and possible usage restrictions \n    of external libraries follow their original sources (referenced from\n    FST3 documentation wherever applicable).\n  * FST3 software is available free of charge for non-commercial use. \n    Please address all inquires concerning possible commercial use \n    of FST3, or if in doubt, to FST3 maintainer (see http://fst.utia.cz)\n  * Derivative works based on FST3 are permitted as long as they remain\n    non-commercial only.\n  * Re-distribution of FST3 software is not allowed without explicit\n    consent of the copyright holder.\nDisclaimer of Warranty:\n  * FST3 software is presented \"as is\", without warranty of any kind, \n    either expressed or implied, including, but not limited to, the implied \n    warranties of merchantability and fitness for a particular purpose. \n    The entire risk as to the quality and performance of the program \n    is with you. Should the program prove defective, you assume the cost \n    of all necessary servicing, repair or correction.\nLimitation of Liability:\n  * The copyright holder will in no event be liable to you for damages, \n    including any general, special, incidental or consequential damages \n    arising out of the use or inability to use the code (including but not \n    limited to loss of data or data being rendered inaccurate or losses \n    sustained by you or third parties or a failure of the program to operate \n    with any other programs).\n========================================================================== */\n\n#include <boost/smart_ptr.hpp>\n#include <iostream>\n#include <sstream>\n#include <cmath>\n#include \"error.hpp\"\n#include \"global.hpp\"\n#include \"criterion_multinom.hpp\"\n#include \"model_multinom.hpp\"\n\n/*============== Template parameter type naming conventions ==============\n--------- Numeric types: -------------------------------------------------\nDATATYPE - data sample values - usually real numbers (but may be integers\n          in text processing etc.)\nREALTYPE - must be real numbers - for representing intermediate results of \n          calculations like mean, covariance etc.\nIDXTYPE - index values for enumeration of data samples - (nonnegative) integers, \n          extent depends on numbers of samples in data\nDIMTYPE - index values for enumeration of features (dimensions), or classes (not \n          class sizes) - (nonnegative) integers, usually lower extent than IDXTYPE, \n          but be aware of expressions like _classes*_features*_features ! \n          in linearized representations of feature matrices for all classes\nBINTYPE - feature selection marker type - represents ca. <10 different feature \n          states (selected, deselected, sel./desel. temporarily 1st nested loop, 2nd...)\nRETURNTYPE - criterion value: real value, but may be extended in future to support \n          multiple values \n--------- Class types: ---------------------------------------------------\nSUBSET       - class of class type Subset \nCLASSIFIER   - class implementing interface defined in abstract class Classifier \nEVALUATOR    - class implementing interface defined in abstract class Sequential_Step \nDISTANCE     - class implementing interface defined in abstract class Distance \nDATAACCESSOR - class implementing interface defined in abstract class Data_Accessor \nINTERVALCONTAINER - class of class type TIntervaller \nCONTAINER    - STL container of class type TInterval  \n========================================================================== */\n\nnamespace FST {\n\n//! Implements Bhattacharyya distance based on multinomial model to serve as feature selection criterion\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nclass Criterion_Multinomial_Bhattacharyya : public Criterion_Multinomial<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> {\npublic:\n\ttypedef Criterion_Multinomial<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> parent;\n\ttypedef boost::shared_ptr<DATAACCESSOR> PDataAccessor;\n\ttypedef boost::shared_ptr<SUBSET> PSubset;\n\tCriterion_Multinomial_Bhattacharyya() {_IB_computed=false; notify(\"Criterion_Multinomial_Bhattacharyya constructor.\");}\n\tvirtual ~Criterion_Multinomial_Bhattacharyya() {notify(\"Criterion_Multinomial_Bhattacharyya destructor.\");}\n\n\tvirtual bool evaluate(RETURNTYPE &result, const PSubset sub);\n\tvirtual bool initialize(PDataAccessor da); \n\n\tCriterion_Multinomial_Bhattacharyya* clone() const;\n\tCriterion_Multinomial_Bhattacharyya* sharing_clone() const {throw fst_error(\"Criterion_Multinomial_Bhattacharyya::sharing_clone() not supported, use Criterion_Multinomial_Bhattacharyya::clone() instead.\");}\n\tCriterion_Multinomial_Bhattacharyya* stateless_clone() const {throw fst_error(\"Criterion_Multinomial_Bhattacharyya::stateless_clone() not supported, use Criterion_Multinomial_Bhattacharyya::clone() instead.\");}\n\t\n\tvirtual std::ostream& print(std::ostream& os) const {os << \"Criterion_Multinomial_Bhattacharyya()\"; return os;}\nprivate:\n\tCriterion_Multinomial_Bhattacharyya(const Criterion_Multinomial_Bhattacharyya& cmb); // copy-constructor\nprivate:\n\tbool _IB_computed;\n};\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nCriterion_Multinomial_Bhattacharyya<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::Criterion_Multinomial_Bhattacharyya(const Criterion_Multinomial_Bhattacharyya& cmb) :\n\tCriterion_Multinomial<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>(cmb),\n\t_IB_computed(cmb._IB_computed)\n{\n\tnotify(\"Criterion_Multinomial_Bhattacharyya copy-constructor.\");\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nCriterion_Multinomial_Bhattacharyya<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>* Criterion_Multinomial_Bhattacharyya<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::clone() const\n{\n\tCriterion_Multinomial_Bhattacharyya<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> *clone=new Criterion_Multinomial_Bhattacharyya<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>(*this);\n\tclone->set_cloned();\n\treturn clone;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Criterion_Multinomial_Bhattacharyya<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::evaluate(RETURNTYPE &result, PSubset sub)\n{\n\tnotify(\"Criterion_Multinomial_Bhattacharyya::evaluate().\");\n\tassert(parent::_model);\n\tassert(parent::get_n()>0);\n\tassert(sub);\n\tif(sub->get_d_raw()==0) return false;\n\tDIMTYPE _d = sub->get_d_raw();\n\tDIMTYPE f;\n\n\tif(_d==1) {// general form of Bhattacharyya unusable, return Indivdual Bhattacharyya\n\t\tif(!_IB_computed) {\n\t\t\tparent::_model->denarrow();\n\t\t\tparent::_model->compute_theta();\n\t\t\tparent::_model->compute_IB();\n\t\t\t_IB_computed=true;\t\n\t\t}\n\t\tif(!sub->getFirstFeature(f)) return false; assert(f>=0 && f<parent::_model->get_n());\n\t\tresult = parent::_model->get_IB()[f]; // individual Bhatt - higher values denote better terms\n\t\tbool b=sub->getNextFeature(f); // just to finish the loop inside sub (to prevent future asserts in sub->set_forward_mode etc.)\n\t\tassert(b==false);\n\t} else {\n\t\tparent::_model->narrow_to(sub);\n\t\tparent::_model->compute_theta();\n\t\tREALTYPE doc_avg_length = parent::_model->get_doc_avg_length(); // valid after compute_theta() call\n\t\tDIMTYPE _classes=parent::_model->get_classes();\n\t\t\n\t\tREALTYPE *tmpoint1, *tmpoint2;\n\t\tRETURNTYPE thetasum;\n\t\tRETURNTYPE value=0.0;\n\t\tDIMTYPE c1,c2;\n#ifdef DEBUG\n\t\t{\n\t\t\tostringstream sos; sos << \"d=\"<<_d<<\", doc_avg_length=\"<<doc_avg_length<<std::endl;\n\t\t\tsyncout::print(std::cout,sos);\n\t\t}\n#endif\n\t\tfor(c1=0;c1<_classes;c1++) for(c2=c1+1;c2<_classes;c2++) // for class pair c1,c2\n\t\t{\n\t\t\ttmpoint1=&(parent::_model->get_theta()[c1*_d]);\n\t\t\ttmpoint2=&(parent::_model->get_theta()[c2*_d]);\n\t\t\tthetasum=0.0;\n\t\t\tfor(f=0;f<_d;f++) \n\t\t\t{\n\t\t\t\tthetasum+=sqrt(tmpoint1[f]*tmpoint2[f]);\n#ifdef DEBUG\n\t\t\t\t{\n\t\t\t\t\tostringstream sos; sos << \"classes<\"<<c1<<\",\"<<c2<<\">: feat \"<<f<<\".thetasum=\"<<thetasum<<\", tmpoint1[i=\"<<f<<\"]=\"<< tmpoint1[f]<< \", tmpoint2[i=\"<<f<<\"]=\"<< tmpoint2[f]<<std::endl;\n\t\t\t\t\tsyncout::print(std::cout,sos);\n\t\t\t\t}\n#endif\n\t\t\t}\n\t\t\tvalue+= (double)log(thetasum) * parent::_model->get_Pc(c1) * parent::_model->get_Pc(c2); // weighted\n\t\t}\n\t\tresult = (-doc_avg_length)*value;\n#ifdef DEBUG\n\t\t{\n\t\t\tostringstream sos; sos << \"result=\"<<result<<std::endl<<std::endl;\n\t\t\tsyncout::print(std::cout,sos);\n\t\t}\n#endif\n\t}\n\treturn true;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Criterion_Multinomial_Bhattacharyya<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::initialize(PDataAccessor da)\n{\n\tnotify(\"Criterion_Multinomial_Bhattacharyya::initialize().\");\n\tparent::initialize(da);\n\t_IB_computed=false;\n\treturn true; \n}\n\n\n//----------------------------------------------------------------------------\n\n/*! \\brief Implements individual Mutual Information based on multinomial model to serve as feature selection criterion in Best Individual Feature setting (feature ranking) only\n    \\note Can be used to evaluate single features only ! */\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nclass Criterion_Multinomial_MI : public Criterion_Multinomial<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> {\npublic:\n\ttypedef Criterion_Multinomial<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR> parent;\n\ttypedef boost::shared_ptr<DATAACCESSOR> PDataAccessor;\n\ttypedef boost::shared_ptr<SUBSET> PSubset;\n\tCriterion_Multinomial_MI() {_MI_computed=false; notify(\"Criterion_Multinomial_MI constructor.\");}\n\tvirtual ~Criterion_Multinomial_MI() {notify(\"Criterion_Multinomial_MI destructor.\");}\n\n\tvirtual bool evaluate(RETURNTYPE &result, const PSubset sub);\n\tvirtual bool initialize(PDataAccessor da); \nprivate:\n\tbool _MI_computed;\n};\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Criterion_Multinomial_MI<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::evaluate(RETURNTYPE &result, PSubset sub)\n{\n\tnotify(\"Criterion_Multinomial_MI::evaluate().\");\n\tassert(parent::_model);\n\tassert(parent::get_n()>0);\n\tassert(sub);\n\tif(sub->get_d_raw()==0) return false;\n\tDIMTYPE _d = sub->get_d_raw();\n\tDIMTYPE f;\n\n\tassert(_d==1);\n\t\n\tif(!_MI_computed) {\n\t\tparent::_model->denarrow();\n\t\tparent::_model->compute_theta();\n\t\tparent::_model->compute_MI();\n\t\t_MI_computed=true;\t\n\t}\n\tif(!sub->getFirstFeature(f)) return false; assert(f>=0 && f<parent::_model->get_n());\n\tresult = parent::_model->get_MI()[f]; // individual Bhatt - higher values denote better terms\n\tbool b=sub->getNextFeature(f); // just to finish the loop inside sub (to prevent future asserts in sub->set_forward_mode etc.)\n\tassert(b==false);\n\treturn true;\n}\n\ntemplate<class RETURNTYPE, typename DATATYPE, typename REALTYPE, typename IDXTYPE, typename DIMTYPE, class SUBSET, class DATAACCESSOR>\nbool Criterion_Multinomial_MI<RETURNTYPE,DATATYPE,REALTYPE,IDXTYPE,DIMTYPE,SUBSET,DATAACCESSOR>::initialize(PDataAccessor da)\n{\n\tnotify(\"Criterion_Multinomial_MI::initialize().\");\n\tparent::initialize(da);\n\t_MI_computed=false;\n\treturn true; \n}\n\n} // namespace\n#endif // FSTCRITERIONMULTINOMBHATTACHARYYA_H ///:~\n", "meta": {"hexsha": "6df68f08b3012a88a26bc2cf0beb8654f7e3e9e3", "size": 13110, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "extern/FST3lib/_src_criteria/criterion_multinom_bhattacharyya.hpp", "max_stars_repo_name": "boussaffawalid/FeatureSelection", "max_stars_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-07-07T20:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-23T06:46:02.000Z", "max_issues_repo_path": "extern/FST3lib/_src_criteria/criterion_multinom_bhattacharyya.hpp", "max_issues_repo_name": "boussaffawalid/FeatureSelection", "max_issues_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T08:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-10T08:57:35.000Z", "max_forks_repo_path": "extern/FST3lib/_src_criteria/criterion_multinom_bhattacharyya.hpp", "max_forks_repo_name": "boussaffawalid/FeatureSelection", "max_forks_repo_head_hexsha": "9768a044c0c0dc2c4a2dc0f6e65413d19e92766c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-04-13T13:11:19.000Z", "max_forks_repo_forks_event_max_datetime": "2017-02-26T08:18:47.000Z", "avg_line_length": 49.8479087452, "max_line_length": 223, "alphanum_fraction": 0.7334858886, "num_tokens": 3355, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4105057691299082}}
{"text": "/* Copyright (C) 2017 IBM Corp.\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific\n * language governing permissions and limitations under the License. \n */\n\n/* TDMatrixParams.cpp - Parameters for trapdoor sampling\n */\n#include <stdexcept>\n#include <NTL/vector.h>\n#include \"utils/tools.h\"\n#include \"utils/timing.h\"\n#include \"TDMatrixParams.h\"\n#include <stdexcept>\n#include <sys/stat.h>\n#include <unistd.h>\n\n//#define DEBUGPRINT\n//#define DEBUG\n\nNTL_CLIENT\n\n// A static table of small co-prime factors (6-7.5 bits)\nlong TDMatrixParams::smallFactors[TDMATRIX_NUM_SMALL_FACTORS]\n    = { TDMATRIX_SMALL_FACTORS }; // TDMATRIX_SMALL_FACTORS list in TDMatrix.h\n\n\n// Calculate the sigmaX value. This value must be large enough so\n// that sigmaX*I - r*maxFactor * (R/I)*(R^t|I) is positive definite.\n// We compute an upper bound s on the singular values of R, then set\n// sigmaX = r*maxFactor * s^2.\nlong getsigmaXVal(long wLen, long mBar, long maxFactor, long r)\n{\n  double s = r*(sqrt(wLen)+sqrt(mBar)+6);\n  double sigmaZ = r*maxFactor;\n  long val = ceil(sigmaZ*sigmaZ * s*s);\n\n#ifdef DEBUG\n  cout << \"sigmaX val=\" << val << endl;\n#endif // DEBUG\n\n  return val;\n}\n\n// lower bound the dimension to get sec bits of security\nlong mBound(long qBits, long errBits, long sec)\n{\n  return ceil((qBits-errBits)*(sec+110)/7.2);\n}\n\nlong mbarBound(long qBits, long n, long sec)\n{\n  return ceil((2+sqrt(sec))*sqrt(n*qBits));\n}\n\nlong get_qBits(long kFactors, long e)\n{\n  assert(kFactors>0 && e>0);\n  if (kFactors > TDMATRIX_NUM_SMALL_FACTORS)\n    kFactors = TDMATRIX_NUM_SMALL_FACTORS;\n\n  double logProd = log(TDMatrixParams::smallFactors[0]);\n  for (long i=1; i<kFactors; i++)\n    logProd += log(TDMatrixParams::smallFactors[i]);\n\n  return ceil(logProd*e/log(2.0));\n}\n\n// For each factor f_i, initialize zz_p context for F_i=f_i^e, and also\n// compute f_i^{-1} mod F_j for all i<j. Returns max the largest factor\nstatic long setFactors(mat_zz_p& fInv, Vec<zz_pContext>& zzp_context,\n                       const vec_l factors, long e)\n{\n    FHE_TIMER_START;\n    long kFactors = factors.length();\n\n    // For each factor f_i, initialize zz_p context for F_i=f_i^e,\n    // and also compute f_i^{-1} mod F_j for all i<j\n    zzp_context.SetLength(kFactors);\n    fInv.SetDims(kFactors,kFactors);\n\n    NTL::zz_pPush ppush; // backup NTL's current modulus\n    long maxFactor = 0;\n    for (long j=kFactors-1; j>=0; j--)\n    {\n        if (factors[j]>maxFactor) maxFactor = factors[j];\n\n        long f2e = NTL::power_long(factors[j],e);\n        // FIXME: check that this fits in a single-precision integer\n        NTL::zz_p::init(f2e);\n        zzp_context[j].save(); // save the current zz_p::modulus()\n        for (long i=j-1; i>=0; i--)\n        {\n            fInv[i][j] = NTL::inv(conv<zz_p>(factors[i])); // f_i^{-1} mod F_j\n        }\n    }\n    return maxFactor;\n}\n\n// Initialize the parameters for a modulus q with kk factors,\n// each factor is an e-th power of an even smaller number.\nvoid TDMatrixParams::init(long nn, long kk, long ee, long mm, long rr)\n{\n    FHE_TIMER_START;\n\n    assert(kk <= TDMATRIX_NUM_SMALL_FACTORS);\n    factors.SetLength(kk);\n    for (long i=0; i<kk; i++)\n      factors[i] = smallFactors[i];\n    kFactors = kk;\n\n    e = ee;\n    r = rr;\n    n = nn;\n    wLen = nn*kk*ee;\n\n    if (mm > 0) { // caller supplied a value for m\n      m = mm;\n      mBar = m - wLen;      \n      if (mBar < nn) { // check that mBar is not too tiny\n        mBar = nn;\n\tm = mBar + wLen;\n      }\n    }\n    else { // compute m, mBar using security formulas\n      long qBits = get_qBits(kk,ee);\n      m = mBound(qBits, /*errBits=*/7, /*sec=*/80);\n      mBar = mbarBound(qBits, n, /*sec=*/80);\n      if (m < mBar+wLen) m = mBar+wLen;\n      else               mBar = m - wLen;\n    }\n\n    // For each factor f_i, initialize zz_p context for F_i=f_i^e,\n    // and also compute f_i^{-1} mod F_j for all i<j\n    maxFactor = setFactors(fInv, zzp_context, factors, e);\n\n    sigmaX = getsigmaXVal(wLen, mBar, maxFactor, r);//ceil(2*r*r*r*m*maxFactor);\n    // The Gaussian parameter from which we can sample with a trapdoor\n\n    //initialize stash\n    stash.SetLength(kFactors);\n    for (long i = 0; i < kFactors; i++)\n      stash[i].init(factors[i]);\n\n    cout << \"TDMatrixParams::init: sigmaX=\"<<sigmaX<<\", mBar=\"<<mBar;\n    cout << \", |q|=\"<<NTL::NumBits(this->getQ())<<endl;\n}\n\n//returns the produce of all the factors to the power of e, output = product(factors)^e\nZZ TDMatrixParams::getQ() const\n{\n    FHE_TIMER_START;\n    ZZ q = to_ZZ(1L);\n    for (long i=0; i<factors.length(); i++) // product of factors\n        q *= factors[i];\n\n    return NTL::power(q,e);  // return product^e\n}\n\n//outputs the different parameters in the class p into the stream s\nostream& operator<<(ostream &s, const TDMatrixParams& p)\n{\n    s << \"[\" << p.n        << \" \"\n      << p.m        << \" \"\n      << p.mBar     << \" \"\n      << p.e        << \" \"\n      << p.r        << \"\\n \"\n      << p.factors  << \"]\";\n    return s;\n}\n\n//This function gets an input streams and sets the different parameters in p from this stream\nistream& operator>>(istream &s, TDMatrixParams& p)\n{\n    seekPastChar(s, '[');  // this function is defined in tools.cpp\n    s >> p.n;\n    s >> p.m;\n    s >> p.mBar;\n    s >> p.e;\n    s >> p.r;\n    s >> p.factors;\n\n    p.wLen = p.n * p.kFactors * p.e;\n\n    p.maxFactor = setFactors(p.fInv, p.zzp_context, p.factors, p.e);\n    p.sigmaX = getsigmaXVal(p.wLen, p.mBar, p.maxFactor, p.r);\n\n    seekPastChar(s, ']');  // this function is defined in tools.cpp\n    return s;\n}\n\n// binary I/O - write all the variables to the file. The handle of the open file is an input to the function The function returns the number of items written\nlong TDMatrixParams::writeToFile(FILE* handle) const\n{\n    FHE_TIMER_START;\n    #ifdef DEBUGPRINT\n    char cwd[1024];\n    getcwd(cwd, sizeof(cwd));\n    cout << \"write TDMatrixParams, current directory = \" << cwd << endl;\n    #endif\n\n    long count = fwrite(&n, sizeof(n), 1, handle);\n    count += fwrite(&m, sizeof(m), 1, handle);\n    count += fwrite(&mBar, sizeof(mBar), 1, handle);\n    count += fwrite(&e, sizeof(e), 1, handle);\n    count += fwrite(&r, sizeof(r), 1, handle);\n    count += fwrite(&kFactors, sizeof(kFactors), 1, handle);\n    count += fwrite(factors.elts(), sizeof(long), factors.length(), handle);\n\n    return count;\n}\n\n//Binary IO - reads the class parameters from the file. The open file handle\n//is provided as input to the function, and the number of items read is\n//returned by the function.\nlong TDMatrixParams::readFromFile(FILE* handle)\n{\n    FHE_TIMER_START;\n    long count = 0;\n\n#ifdef DEBUGPRINT\n    char cwd[1024];\n    getcwd(cwd, sizeof(cwd));\n    cout << \"read TDMatrixParams from current directory = \" << cwd << endl;\n#endif\n\n    count += fread(&n, sizeof(n), 1, handle);\n    count += fread(&m, sizeof(m), 1, handle);\n    count += fread(&mBar, sizeof(mBar), 1, handle);\n    count += fread(&e, sizeof(e), 1, handle);\n    count += fread(&r, sizeof(r), 1, handle);\n    count += fread(&kFactors, sizeof(kFactors), 1, handle);\n\n    factors.SetLength(kFactors);\n    count += fread(factors.elts(), sizeof(long), factors.length(), handle);\n\n    //initialize stash\n    stash.SetLength(kFactors);\n    for (long i = 0; i < kFactors; i++)\n      stash[i].init(factors[i]);\n\n    wLen = n * kFactors * e;\n\n    maxFactor = setFactors(fInv, zzp_context, factors, e);\n    sigmaX = getsigmaXVal(wLen, mBar, maxFactor, r);\n\n    return count;\n}\n\n//check if all the variables in the two classes are equal if Yes, return true. Else, false.\n\nbool operator==(const TDMatrixParams& p, const TDMatrixParams& q)\n{\n    return (p.n == q.n && p.m == q.m && p.mBar == q.mBar && p.e == q.e\n            && p.r == q.r && p.wLen == q.wLen && p.kFactors == q.kFactors\n            && p.factors == q.factors);\n}\n\n#if 0\n// Deprecated, kept for debuging purposes\nTDMatrixParams::TDMatrixParams(vec_l &vFactors, long lm,long rSigma,long llogQ,long lq, long nIn, long eL)\n{\n    FHE_TIMER_START;\n    factors = vFactors;\n    r = rSigma;\n    kFactors = llogQ;\n    n = nIn;\n    m = lm;//SMS.NumCols();\n    mBar = m - n*(kFactors*eL);\n    wLen = n*kFactors*eL;\n    e = eL;\n\n    // For each factor f_i, initialize zz_p context for F_i=f_i^e,\n    // and also compute f_i^{-1} mod F_j for all i<j\n    maxFactor = setFactors(fInv, zzp_context, factors, e);\n\n    sigmaX = getsigmaXVal(wLen, mBar, maxFactor, r);\n    // The Gaussian parameter from which we can sample with a trapdoor\n\n    stash.SetLength(kFactors);\n    for (long i = 0; i < kFactors; i++)\n      stash[i].init(factors[i]);\n}\n#endif\n", "meta": {"hexsha": "42ac93e673b44c9287e16da6b325233681594cc9", "size": 9002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TDMatrixParams.cpp", "max_stars_repo_name": "shaih/BPobfus", "max_stars_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-25T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T03:19:43.000Z", "max_issues_repo_path": "TDMatrixParams.cpp", "max_issues_repo_name": "shaih/BPobfus", "max_issues_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TDMatrixParams.cpp", "max_forks_repo_name": "shaih/BPobfus", "max_forks_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-12-23T04:03:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-12T07:42:29.000Z", "avg_line_length": 30.9347079038, "max_line_length": 157, "alphanum_fraction": 0.6323039325, "num_tokens": 2627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4105057616094567}}
{"text": "#include <iostream>\n#include \"PhaseSpace.h\"\n#include <math.h>\n#include <vector>\n#include \"statistics.h\"\n//#include \"data_processing.h\"\n//#include \"using_gnuplot.h\"\n//#include \"cpp_dec_float.hpp\"\n//#include \"gnuplot_i.hpp\"\n//#include \"gnuplot-iostream.h\"\n//#include <boost/tuple/tuple.hpp>\nusing namespace std;\n\nPhaseSpace::PhaseSpace(double hWidthC, double hHeightC, double VzDistC, double zDistC, double chirpC, double bC, double pulseEnergyC, double intensityMultiplierC,\n\t\t\t\t\t   double hDepthC, double hDepthVelC, double VxDistC, double xDistC, double chirpTC, double bTC, double VzCC, double zCC, double VxCC, double xCC)\n\t: hWidth(hWidthC), hHeight(hHeightC), VzDist(VzDistC), zDist(zDistC), chirp(chirpC), b(bC), pulseEnergy(pulseEnergyC), intensityMultiplier(intensityMultiplierC),\n\t  hDepth(hDepthC), hDepthVel(hDepthVelC), VxDist(VxDistC), xDist(xDistC), chirpT(chirpTC), bT(bTC), VzC(VzCC), zC(zCC), VxC(VxCC), xC(zCC) {}\n\nPhaseSpace::PhaseSpace(vector<PhaseSpace> spaces) : hWidth(0), hHeight(0), VzDist(0), zDist(0), chirp(0), b(0), pulseEnergy(0), intensityMultiplier(0), hDepth(0), hDepthVel(0), VxDist(0), xDist(0), chirpT(0), bT(0), VzC(0), zC(0), VxC(0), xC(0)\n{\n\tfor (int i = 0; i < splitNumber; i++)\n\t{\n\t\tVzC += spaces[i].VzC * spaces[i].intensityMultiplier;\n\t\t//DEBUGGING cout << spaces[i].intensityMultiplier << endl;\n\t\tzC += spaces[i].zC * spaces[i].intensityMultiplier;\n\t\txC += spaces[i].xC * spaces[i].intensityMultiplier;\n\t\tintensityMultiplier += spaces[i].intensityMultiplier;\n\t\tpulseEnergy += spaces[i].pulseEnergy;\n\t\t//spaces[i].print();\n\t}\n\t//this.VzC = taskPool.reduce!\"a + b\"(0.0, std.algorithm.map!\"a.VzC\"(spaces))*this.intensityRatio;\n\t//int maxSize = sizeof(spaces[]);\n\n\t//for (PhaseSpace space : spaces[splitNumber]){\n\t//\tVzC += space.VzC*space.intensityMultiplier;\n\t//\tzC += space.zC*space.intensityMultiplier;\n\t//\txC += space.xC*space.intensityMultiplier;\n\t//}\n\t//this.zC = taskPool.reduce!\"a + b\"(0.0, std.algorithm.map!\"a.zC\"(spaces));\n\n\t//Recalculation from single variable change\n\t//HWIDTH BASED RECALCULATION\n\t//hWidth = spaces[0].hWidth; (Shown not to be accurate/gives wrong results)\n\thWidth = originalHWidth + (spaces[0].hWidth - originalHWidth) * splitNumber;\n\thHeight = spaces[0].hHeight * splitNumber; //If you add a * 1/chirp here sometimes it doesn't process it for some reason, a 1/chirp isn't needed here anyway but its an odd mystery why its only sometimes processed\n\tzDist = spaces[0].zDist;\n\tVzDist = zDist * hHeight / hWidth;\n\tchirp = VzDist * sqrt((1 / pow(zDist, 2)) - (1 / pow(hWidth, 2)));\n\tb = chirp * pow(zDist / VzDist, 2);\n\thDepth = spaces[0].hDepth;\n\thDepthVel = spaces[0].hDepthVel;\n\tVxDist = spaces[0].VxDist;\n\txDist = spaces[0].xDist;\n\tchirpT = spaces[0].chirpT;\n\tbT = spaces[0].bT;\n\n\t//pulseEnergy = taskPool.reduce!\"a + b\"(0.0, std.algorithm.map!\"a.totalPulseEnergy\"(spaces));\n\t//intensityMultiplier = taskPool.reduce!\"a + b\"(0.0, std.algorithm.map!\"a.intensityRatio\"(spaces));\n}\n\nvector<PhaseSpace> PhaseSpace::split()\n{\n\tvector<PhaseSpace> splitSpaces;\n\toriginalHWidth = hWidth;\n\t//phaseSpaces.length = to!int(spaces);\n\tdouble intensityMultipliers[splitNumber];\n\tfor (int i = 0; i < splitNumber; i++)\n\t{\n\t\tintensityMultipliers[i] = get_intensity(splitNumber, i + 1);\n\t}\n\tdouble splitHHeight = 0;\n\tdouble splitVzDist = 0;\n\tdouble splitB = 0;\n\tdouble splitZDist = 0;\n\tdouble splitChirp = 0;\n\tsplitHHeight = hHeight / splitNumber;\n\tsplitVzDist = VzDist / splitNumber;\n\t//b = chirp * pow(zDist / VzDist, 2);\n\tsplitB = zDist * sqrt((1 / pow(splitVzDist, 2)) - (1 / pow(splitHHeight, 2)));\n\tsplitZDist = splitB / (sqrt((1 / pow(splitVzDist, 2)) - (1 / pow(splitHHeight, 2))));\n\tsplitChirp = splitVzDist * sqrt((1 / pow(zDist, 2)) - (1 / pow(hWidth, 2)));\n\t//i, ref elem; phaseSpaces\n\n\tfor (int j = 0; j < splitNumber; j++)\n\t{\n\t\tsplitSpaces.push_back(PhaseSpace(hWidth, splitHHeight, splitVzDist, splitZDist, splitChirp, splitB, pulseEnergy * intensityMultipliers[j], intensityMultipliers[j],\n\t\t\t\t\t\t\t\t\t\t hDepth, hDepthVel, VxDist, xDist, chirpT, bT, hHeight - (hHeight * 2 / splitNumber) * (double(j) + 0.5), (hHeight - (hHeight * 2 / splitNumber) * (double(j) + 0.5)) / chirp, VxC, xC));\n\t}\n\tphaseSpaces += splitNumber;\n\treturn splitSpaces;\n}\n\nvector<PhaseSpace> PhaseSpace::shatter(vector<vector<double>> spectroTable)\n{\n\tint spaces = spectroTable.size();\n\tvector<PhaseSpace> shatteredPulses;\n\tdouble newVzDist = VzDist / spaces;\n\tdouble newChirp = newVzDist * sqrt((1 / pow(zDist, 2)) - (1 / pow(hWidth, 2)));\n\tdouble newB = newChirp * pow(zDist / newVzDist, 2);\n\tfor (int i = 0; i < spaces; i++)\n\t{\n\t\t//cout << spectroTable[i][1] << endl;\n\t\tshatteredPulses.push_back(PhaseSpace(hWidth, hHeight / spaces, newVzDist, zDist, newChirp, newB, pulseEnergy * spectroTable[i][1 / baseTotal], intensityMultiplier * spectroTable[i][1],\n\t\t\t\t\t\t\t\t\t\t\t hDepth, hDepthVel, VxDist, xDist, chirpT, bT, hHeight + (spectroTable[i][0] / 1117), zC, VxC, xC));\n\t}\n\treturn shatteredPulses;\n}\n\ndouble PhaseSpace::intensity(double x, double y)\n{\n\tdouble negTwohWidthsq = -2 * hWidth * hWidth;\n\tdouble twoVzIntDistsq = 2 * VzDist * VzDist;\n\tdouble twoPIhWidthVzIntDist = 2 * M_PI * (hWidth * VzDist);\n\treturn exp((x * x / (negTwohWidthsq)) - ((y - chirp * x) * (y - chirp * x) / (twoVzIntDistsq))) / (twoPIhWidthVzIntDist);\n}\n\ndouble PhaseSpace::get_intensity(double numSections, double sectionNum)\n{\n\t//Gets intensity % proportionally to 1 (like if its gets .5 its 50% of total intensity)\n\t//search with xSearch & ySearch = +- 5.803*hWidth or hHeight to get the total intensity of the phase space (equal to 1)\n\tdouble ySearchLB = -catchFactor * hHeight + ((catchFactor * hHeight * 2.0 / numSections) * (sectionNum - 1));\n\tdouble ySearchUB = catchFactor * hHeight - (catchFactor * hHeight * 2.0 / numSections) * (numSections - sectionNum);\n\tdouble xSearchLB = -catchFactor * hWidth;\n\tdouble xSearchUB = catchFactor * hWidth;\n\n\t//Convert to intensity_integration parameters\n\tdouble xHalfRange = (xSearchUB - xSearchLB) / 2;\n\tdouble yHalfRange = (ySearchUB - ySearchLB) / 2;\n\n\tdouble xOffset = (xSearchUB + xSearchLB) / 2;\n\tdouble yOffset = (ySearchUB + ySearchLB) / 2;\n\n\treturn intensity_integration(xHalfRange, yHalfRange, xOffset, yOffset);\n}\n\ndouble PhaseSpace::x_integration(double xLeftLim, double xRightLim)\n{\n\tdouble accuracyY = 2 * hHeight / 199;\n\tdouble accuracyX = (xRightLim - xLeftLim) / 199;\n\tdouble x = xLeftLim;\n\tdouble y = -hHeight + accuracyY / 2;\n\n\tdouble intensityValue = 0;\n\n\twhile (y < hHeight)\n\t{\n\t\twhile (x < xRightLim)\n\t\t{\n\t\t\tintensityValue += accuracyX * accuracyY * intensity(x - xC, y);\n\t\t\tx += accuracyX;\n\t\t}\n\t\ty += accuracyY;\n\t\tdouble x = xLeftLim;\n\t}\n\treturn intensityValue;\n}\n\ndouble PhaseSpace::intensity_integration(double xHalfRange, double yHalfRange, double xOffset, double yOffset)\n{\n\tdouble accuracyY = 2 * yHalfRange / 199;\n\tdouble accuracyX = 2 * xHalfRange / 199;\n\tdouble x = -xHalfRange + xOffset + accuracyX / 2;\n\tdouble y = -yHalfRange + yOffset + accuracyY / 2;\n\n\tdouble intensityValue = 0;\n\n\twhile (y < yHalfRange + yOffset)\n\t{\n\t\twhile (x < xHalfRange + xOffset)\n\t\t{\n\t\t\tintensityValue += accuracyX * accuracyY * intensity(x, y);\n\t\t\tx += accuracyX;\n\t\t}\n\t\ty += accuracyY;\n\t\tx = -xHalfRange + xOffset + accuracyX / 2;\n\t}\n\treturn intensityValue;\n}\n\nvoid PhaseSpace::grid_integration(double xHalfRange, double yHalfRange, double xOffset, double yOffset, double grid[modelingXRange][modelingYRange], double xGridHalfRange, double yGridHalfRange)\n{\n\tdouble accuracyY = 2 * yHalfRange / 199;\n\tdouble accuracyX = 2 * xHalfRange / 199;\n\tdouble x = -xHalfRange + xOffset + accuracyX / 2;\n\tdouble y = -yHalfRange + yOffset + accuracyY / 2;\n\n\tdouble intensityValue = 0;\n\n\twhile (y < yHalfRange + yOffset)\n\t{\n\t\twhile (x < xHalfRange + xOffset)\n\t\t{\n\t\t\tgrid[int(map(x, -xGridHalfRange, xGridHalfRange, 0, double(modelingXRange) - 1) + 0.5)][int(map(y, -yGridHalfRange, yGridHalfRange, 0, double(modelingYRange) - 1) + 0.5)] += accuracyX * accuracyY * intensity(x, y);\n\t\t\tx += accuracyX;\n\t\t}\n\t\ty += accuracyY;\n\t\tx = -xHalfRange + xOffset + accuracyX / 2;\n\t}\n}\n\nPhaseSpace PhaseSpace::evolution(double dist)\n{ //--To deal with processing we might need to make our own math functions. (less/more digits of accuracy)\n\t//A divided by 1E6 was found in D code. Reason is unknown.\n\tdouble postTime = dist / 164.35;\n\tb += postTime;\n\tbT += postTime;\n\n\tif (chirp > 0)\n\t{\n\t\tVzDist = sqrt(1 / ((1 / pow(hHeight, 2)) + pow((b / zDist), 2)));\n\t}\n\tif (chirpT > 0)\n\t{\n\t\tVxDist = sqrt(1 / ((1 / pow(hDepthVel, 2)) + pow((bT / xDist), 2)));\n\t}\n\tif (chirp < 0)\n\t{\n\t\tzDist = b / (sqrt((1 / pow(VzDist, 2)) - (1 / pow(hHeight, 2))));\n\t}\n\tif (chirpT < 0)\n\t{\n\t\txDist = bT / (sqrt((1 / pow(VxDist, 2)) - (1 / pow(hDepthVel, 2))));\n\t}\n\n\t//VzDist = sqrt(1/((1/pow(hHeight,2))+pow((b/zDist),2)));\n\t//VxDist = sqrt(1/((1/pow(hDepthVel,2))+pow((bT/xDist),2)));\n\n\tchirp = b * pow(VzDist / zDist, 2);\n\tchirpT = bT * pow(VxDist / xDist, 2);\n\thWidth = sqrt(1 / ((1 / pow(zDist, 2)) - pow(chirp / VzDist, 2)));\n\thDepth = sqrt(1 / ((1 / pow(xDist, 2)) - pow(chirpT / VxDist, 2)));\n\n\tzC += VzC * postTime;\n\txC += hDepthVel * postTime;\n\treturn *this;\n}\n\nPhaseSpace PhaseSpace::RFLens(double power)\n{\n\tdouble tempSlope = VzC / zC;\n\ttempSlope -= sqrt(power) * RF_LENS_COEFFICIENT;\n\tVzC = tempSlope * zC;\n\n\tchirp -= sqrt(power) * RF_LENS_COEFFICIENT;\n\tzDist = sqrt(1 / ((1 / pow(hWidth, 2)) + pow(chirp / VzDist, 2)));\n\tb = chirp * pow(zDist / VzDist, 2);\n\thHeight = sqrt(1 / ((1 / pow(VzDist, 2)) - pow(b / zDist, 2)));\n\treturn *this;\n}\n\nPhaseSpace PhaseSpace::mag_lens(double power)\n{\n\t//A divided by 1E12 for power was found in D code. Reason is unknown.\n\t//double tempSlope = VxC / xC;\n\t//tempSlope -= pow(power, 2) * MAG_LENS_COEFFICIENT;\n\t//VxC = tempSlope * xC;\n\t//xC = VxC / tempSlope;\n\n\tchirpT -= pow(power, 2) * MAG_LENS_COEFFICIENT;\n\txDist = sqrt(1 / ((1 / pow(hDepth, 2)) + pow(chirpT / VxDist, 2)));\n\tbT = chirpT * pow(xDist / VxDist, 2);\n\thDepthVel = sqrt(1 / ((1 / pow(VxDist, 2)) - pow(bT / xDist, 2)));\n\treturn *this;\n}\n\nPhaseSpace PhaseSpace::spectroscopy_function()\n{\n\txC = xC + 7172.99042634 * VzC;\n\treturn *this;\n}\n\n//Accessor methods\ndouble PhaseSpace::getHWidth() { return hWidth; }\ndouble PhaseSpace::getHHeight() { return hHeight; }\ndouble PhaseSpace::getVzDist() { return VzDist; }\ndouble PhaseSpace::getZDist() { return zDist; }\ndouble PhaseSpace::getChirp() { return chirp; }\ndouble PhaseSpace::getB() { return b; }\ndouble PhaseSpace::getIntensityMultiplier() { return intensityMultiplier; }\ndouble PhaseSpace::getVzC() { return VzC; }\ndouble PhaseSpace::getZC() { return zC; }\n\n//Longitudinal accessor methods\ndouble PhaseSpace::getHDepth() { return hDepth; }\ndouble PhaseSpace::getHDepthVel() { return hDepthVel; }\ndouble PhaseSpace::getVxDist() { return VxDist; }\ndouble PhaseSpace::getXDist() { return xDist; }\ndouble PhaseSpace::getChirpT() { return chirpT; }\ndouble PhaseSpace::getBT() { return bT; }\ndouble PhaseSpace::getVxC() { return VxC; }\ndouble PhaseSpace::getXC() { return xC; }", "meta": {"hexsha": "71e085d21eda6824a3d85a4a3fb4065d5ed2671d", "size": 10950, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++/PhaseSpace.cpp", "max_stars_repo_name": "ZovcIfzm/EELS-Simulator", "max_stars_repo_head_hexsha": "32a355420a87dcd4b9fd0515da1ae655d72ffb18", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-07-30T20:53:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-26T10:11:16.000Z", "max_issues_repo_path": "C++/PhaseSpace.cpp", "max_issues_repo_name": "ZovcIfzm/EELS-simulator", "max_issues_repo_head_hexsha": "32a355420a87dcd4b9fd0515da1ae655d72ffb18", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C++/PhaseSpace.cpp", "max_forks_repo_name": "ZovcIfzm/EELS-simulator", "max_forks_repo_head_hexsha": "32a355420a87dcd4b9fd0515da1ae655d72ffb18", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-02-24T03:04:50.000Z", "max_forks_repo_forks_event_max_datetime": "2018-02-24T03:04:50.000Z", "avg_line_length": 37.6288659794, "max_line_length": 244, "alphanum_fraction": 0.6838356164, "num_tokens": 3659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.410423298554374}}
{"text": "// Copyright (c) 2014, Paul Furgale, Jérôme Maye and Jörn Rehder, Autonomous Systems Lab, ETH Zurich, Switzerland\n// Copyright (c) 2014, Thomas Schneider, Skybotix AG, Switzerland\n// Copyright (c) 2016, Luc Oth\n// Copyright (C) 2016 ETH Zurich, Wyss Zurich, Zurich Eye\n// All rights reserved.\n//\n// Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above copyright\n//       notice, this list of conditions and the following disclaimer in the\n//       documentation and/or other materials provided with the distribution.\n//     * Neither the name of the ETH Zurich, Wyss Zurich, Zurich Eye nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL ETH Zurich, Wyss Zurich, Zurich Eye BE LIABLE FOR ANY\n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Derived from https://github.com/ethz-asl/kalibr/ (2016)\n\n#include <ze/splines/bspline.hpp>\n#include <Eigen/Cholesky>\n#include <Eigen/LU>\n#include <Eigen/QR>\n#include <boost/tuple/tuple.hpp>\n\nnamespace ze {\n\nBSpline::BSpline(int spline_order)\n  : spline_order_(spline_order)\n{\n  CHECK_GE(spline_order_, 2)\n      << \"The B-spline order must be greater than or equal to 2\";\n}\n\nBSpline::~BSpline()\n{\n}\n\nint BSpline::spline_order() const\n{\n  return spline_order_;\n}\n\nint BSpline::dimension() const\n{\n  return coefficients_.rows();\n}\n\nint BSpline::polynomialDegree() const\n{\n  return spline_order_ - 1;\n}\n\nvoid BSpline::setKnotsAndCoefficients(const std::vector<real_t>& knots,\n                                      const MatrixX& coefficients)\n{\n  //std::cout << \"setting \" << knots.size() << \" knots\\n\";\n  // This will throw an exception if it is an invalid knot sequence.\n  verifyKnotSequence(knots);\n\n  // Check if the number of coefficients matches the number of knots.\n  CHECK_EQ(numCoefficientsRequired(numValidTimeSegments(knots.size())), coefficients.cols())\n       <<  \"A B-spline of order \" << spline_order_ << \" requires \"\n       << numCoefficientsRequired(numValidTimeSegments(knots.size()))\n       << \" coefficients for the \" << numValidTimeSegments(knots.size())\n       << \" time segments defined by \" << knots.size() << \" knots\";\n\n  knots_ = knots;\n  coefficients_ = coefficients;\n\n  initializeBasisMatrices();\n}\n\nvoid BSpline::initializeBasisMatrices()\n{\n  basis_matrices_.resize(numValidTimeSegments());\n\n  for(unsigned i = 0; i < basis_matrices_.size(); i++)\n  {\n    basis_matrices_[i] = M(spline_order_,i + spline_order_ - 1);\n  }\n}\n\nMatrixX BSpline::M(int k, int i)\n{\n  CHECK_GE(k, 1) << \"The parameter k must be greater than or equal to 1\";\n  // \\todo: redo these checks.\n  CHECK_GE(i, 0) << \"The parameter i must be greater than or equal to 0\";\n  CHECK_LT(i, (int)knots_.size())\n      << \"The parameter i must be less than the number of time segments\";\n  if(k == 1)\n  {\n    // The base-case for recursion.\n    MatrixX M(1,1);\n    M(0,0) = 1;\n    return M;\n  }\n  else\n  {\n    MatrixX M_km1 = M(k-1,i);\n    // The recursive equation for M\n    // M_k = [ M_km1 ] A  + [  0^T  ] B\n    //       [  0^T  ]      [ M_km1 ]\n    //        -------        -------\n    //         =: M1          =: M2\n    //\n    //     = M1 A + M2 B\n    MatrixX M1 = MatrixX::Zero(M_km1.rows() + 1, M_km1.cols());\n    MatrixX M2 = MatrixX::Zero(M_km1.rows() + 1, M_km1.cols());\n\n    M1.topRightCorner(M_km1.rows(),M_km1.cols()) = M_km1;\n    M2.bottomRightCorner(M_km1.rows(),M_km1.cols()) = M_km1;\n\n    MatrixX A = MatrixX::Zero(k-1, k);\n    for(int idx = 0; idx < A.rows(); idx++)\n    {\n      int j = i - k + 2 + idx;\n      real_t d0 = d_0(k, i, j);\n      A(idx, idx  ) = 1.0 - d0;\n      A(idx, idx+1) = d0;\n    }\n\n    MatrixX B = MatrixX::Zero(k-1, k);\n    for(int idx = 0; idx < B.rows(); idx++)\n    {\n      int j = i - k + 2 + idx;\n      real_t d1 = d_1(k, i, j);\n      B(idx, idx  ) = -d1;\n      B(idx, idx+1) = d1;\n    }\n\n    MatrixX M_k;\n\n    return M_k = M1 * A + M2 * B;\n  }\n}\n\nreal_t BSpline::d_0(int k, int i, int j)\n{\n  CHECK_LE(j+k-1.0, (int)knots_.size()) <<  \"Index out of range with k=\" << k\n                                        << \", i=\" << i << \", and j=\" << j;\n  CHECK_LT(0, (int)knots_.size()) <<  \"Index out of range with k=\" << k\n                                  << \", i=\" << i << \", and j=\" << j;\n  CHECK_LE(j, (int)knots_.size()) <<  \"Index out of range with k=\" << k\n                                  << \", i=\" << i << \", and j=\" << j;\n  CHECK_LE(i, (int)knots_.size()) <<  \"Index out of range with k=\" << k\n                                  << \", i=\" << i << \", and j=\" << j;\n\n  real_t denom = knots_[j+k-1] - knots_[j];\n  if(denom <= 0.0)\n  {\n    return 0.0;\n  }\n\n  real_t numerator = knots_[i] - knots_[j];\n\n  return numerator/denom;\n}\n\nreal_t BSpline::d_1(int k, int i, int j)\n{\n  CHECK_LE(j+k-1.0, (int)knots_.size()) <<  \"Index out of range with k=\"\n                                        << k << \", i=\" << i << \", and j=\" << j;\n  CHECK_LT(0, (int)knots_.size()) <<  \"Index out of range with k=\"\n                                  << k << \", i=\" << i << \", and j=\" << j;\n  CHECK_LE(j, (int)knots_.size()) <<  \"Index out of range with k=\"\n                                  << k << \", i=\" << i << \", and j=\" << j;\n  CHECK_LE(i, (int)knots_.size()) <<  \"Index out of range with k=\"\n                                  << k << \", i=\" << i << \", and j=\" << j;\n  real_t denom = knots_[j+k-1] - knots_[j];\n  if(denom <= 0.0)\n  {\n    return 0.0;\n  }\n\n  real_t numerator = knots_[i+1] - knots_[i];\n\n  return numerator/denom;\n}\n\nvoid BSpline::setKnotVectorAndCoefficients(const VectorX& knots,\n                                           const MatrixX& coefficients)\n{\n  std::vector<real_t> k(knots.size());\n  for(unsigned i = 0; i < k.size(); i++)\n  {\n    k[i] = knots(i);\n  }\n\n  setKnotsAndCoefficients(k, coefficients);\n}\n\nconst std::vector<real_t> BSpline::knots() const\n{\n  return knots_;\n}\n\nVectorX BSpline::knotVector() const\n{\n  VectorX k(knots_.size());\n  for(unsigned i = 0; i < knots_.size(); i++)\n  {\n    k(i) = knots_[i];\n  }\n\n  return k;\n}\n\nconst MatrixX& BSpline::coefficients() const\n{\n  return coefficients_;\n}\n\nvoid BSpline::verifyKnotSequence(const std::vector<real_t>& knots)\n{\n  CHECK_GE((int)knots.size(), minimumKnotsRequired())\n      << \"The sequence does not contain enough knots to define an active time sequence \"\n      << \"for a B-spline of order \" << spline_order_\n      << \". At least \" << minimumKnotsRequired()\n      << \" knots are required\";\n\n  for(unsigned i = 1; i < knots_.size(); i++)\n  {\n    CHECK_LE(knots[i-1], knots[i])\n        << \"The knot sequence must be nondecreasing. Knot \" << i\n        << \" was not greater than or equal to knot \" << (i-1);\n  }\n}\n\nint BSpline::numValidTimeSegments(int numKnots) const\n{\n  int nv = numKnots - 2*spline_order_ + 1;\n  return std::max(nv,0);\n}\n\nint BSpline::numValidTimeSegments() const\n{\n  return numValidTimeSegments(knots_.size());\n}\n\nint BSpline::minimumKnotsRequired() const\n{\n  return numKnotsRequired(1);\n}\n\nint BSpline::numCoefficientsRequired(int num_time_segments) const\n{\n  return num_time_segments + spline_order_ - 1;\n}\n\nint BSpline::numKnotsRequired(int num_time_segments) const\n{\n  return numCoefficientsRequired(num_time_segments) + spline_order_;\n}\n\nreal_t BSpline::t_min() const\n{\n  CHECK_GE((int)knots_.size(), minimumKnotsRequired())\n      << \"The B-spline is not well initialized\";\n  return knots_[spline_order_ - 1];\n}\n\nreal_t BSpline::t_max() const\n{\n  CHECK_GE((int)knots_.size(), minimumKnotsRequired())\n      << \"The B-spline is not well initialized\";\n  return knots_[knots_.size() - spline_order_];\n}\n\nstd::pair<real_t,int> BSpline::computeTIndex(real_t t) const\n{\n  CHECK_GE(t, t_min()) << \"The time is out of range by \" << (t - t_min());\n\n  //// HACK - avoids numerical problems on initialisation\n  if (std::abs(t_max() - t) < 1e-10)\n  {\n    t = t_max();\n  }\n  //// \\HACK\n\n  CHECK_LE(t, t_max())\n      << \"The time is out of range by \" << (t_max() - t);\n  std::vector<real_t>::const_iterator i;\n  if(t == t_max())\n  {\n    // This is a special case to allow us to evaluate the spline at the boundary of the\n    // interval. This is not stricly correct but it will be useful when we start doing\n    // estimation and defining knots at our measurement times.\n    i = knots_.end() - spline_order_;\n  }\n  else\n  {\n    i = std::upper_bound(knots_.begin(), knots_.end(), t);\n  }\n  //CHECK_NE(i, knots_.end()) << \"Something very bad has happened in computeTIndex(\" << t << \")\";\n\n  // Returns the index of the knot segment this time lies on and the width of this knot segment.\n  return std::make_pair(*i - *(i-1),(i - knots_.begin()) - 1);\n\n}\n\nstd::pair<real_t,int> BSpline::computeUAndTIndex(real_t t) const\n{\n  std::pair<real_t,int> ui = computeTIndex(t);\n\n  int index = ui.second;\n  real_t denom = ui.first;\n\n  if(denom <= 0.0)\n  {\n    // The case of duplicate knots.\n    //std::cout << \"Duplicate knots\\n\";\n    return std::make_pair(0, index);\n  }\n  else\n  {\n    real_t u = (t - knots_[index])/denom;\n\n    return std::make_pair(u, index);\n  }\n}\n\nint dmul(int i, int derivative_order)\n{\n  if(derivative_order == 0)\n  {\n    return 1;\n  }\n  else if(derivative_order == 1)\n  {\n    return i;\n  }\n  else\n  {\n    return i * dmul(i-1,derivative_order-1) ;\n  }\n}\n\nVectorX BSpline::computeU(real_t uval,\n                          int segmentIndex,\n                          int derivativeOrder) const\n{\n  VectorX u = VectorX::Zero(spline_order_);\n  real_t delta_t = knots_[segmentIndex+1] - knots_[segmentIndex];\n  real_t multiplier = 0.0;\n  if(delta_t > 0.0)\n  {\n    multiplier = 1.0/pow(delta_t, derivativeOrder);\n  }\n\n  real_t uu = 1.0;\n  for(int i = derivativeOrder; i < spline_order_; i++)\n  {\n    u(i) = multiplier * uu * dmul(i,derivativeOrder) ;\n    uu = uu * uval;\n  }\n\n  return u;\n}\n\nVectorX BSpline::eval(real_t t) const\n{\n  return evalD(t,0);\n}\n\nconst MatrixX& BSpline::basisMatrixFromKnotIndex(int knot_index) const\n{\n  return basis_matrices_[basisMatrixIndexFromStartingKnotIndex(knot_index)];\n}\n\nVectorX BSpline::evalD(real_t t, int derivative_order) const\n{\n  CHECK_GE(derivative_order, 0) << \"To integrate, use the integral function\";\n  // Returns the normalized u value and the lower-bound time index.\n  std::pair<real_t,int> ui = computeUAndTIndex(t);\n  VectorX u = computeU(ui.first, ui.second, derivative_order);\n\n  int bidx = ui.second - spline_order_ + 1;\n\n  // Evaluate the spline (or derivative) in matrix form.\n  //\n  // [c_0 c_1 c_2 c_3] * B^T * u\n  // spline coefficients\n\n  VectorX rv = coefficients_.block(0,bidx,coefficients_.rows(),spline_order_)\n               * basis_matrices_[bidx].transpose() * u;\n\n  return rv;\n}\n\nVectorX BSpline::evalDAndJacobian(real_t t,\n                                  int derivative_order,\n                                  MatrixX* Jacobian,\n                                  VectorXi* coefficient_indices) const\n{\n  CHECK_GE(derivative_order, 0) << \"To integrate, use the integral function\";\n  // Returns the normalized u value and the lower-bound time index.\n  std::pair<real_t,int> ui = computeUAndTIndex(t);\n  VectorX u = computeU(ui.first, ui.second, derivative_order);\n\n  int bidx = ui.second - spline_order_ + 1;\n\n  // Evaluate the spline (or derivative) in matrix form.\n  //\n  // [c_0 c_1 c_2 c_3] * B^T * u\n  // spline coefficients\n\n  // The spline value\n  VectorX Bt_u = basis_matrices_[bidx].transpose() * u;\n  VectorX v = coefficients_.block(0,bidx,coefficients_.rows(),spline_order_) * Bt_u;\n\n  if(Jacobian)\n  {\n    // The Jacobian\n    Jacobian->resize(coefficients_.rows(), Bt_u.size() * coefficients_.rows());\n    MatrixX one = MatrixX::Identity(coefficients_.rows(), coefficients_.rows());\n    for(int i = 0; i < Bt_u.size(); i++)\n    {\n      Jacobian->block(0, i*coefficients_.rows(),\n                      coefficients_.rows(),\n                      coefficients_.rows()) = one * Bt_u[i];\n    }\n  }\n\n  if(coefficient_indices)\n  {\n    int D = coefficients_.rows();\n    *coefficient_indices = VectorXi::LinSpaced(spline_order_ * D,\n                                              bidx * D,\n                                              (bidx + spline_order_) * D - 1);\n  }\n\n  return v;\n}\n\nstd::pair<VectorX, MatrixX> BSpline::evalDAndJacobian(real_t t,\n                                                      int derivative_order) const\n{\n  std::pair<VectorX, MatrixX> rv;\n\n  rv.first = evalDAndJacobian(t, derivative_order, &rv.second, NULL);\n\n  return rv;\n}\n\nMatrixX BSpline::localBasisMatrix(real_t t, int derivative_order) const\n{\n  return Phi(t,derivative_order);\n}\n\nMatrixX BSpline::localCoefficientMatrix(real_t t) const\n{\n  std::pair<real_t,int> ui = computeTIndex(t);\n  int bidx = ui.second - spline_order_ + 1;\n\n  return coefficients_.block(0,bidx,coefficients_.rows(),spline_order_);\n}\n\nVectorX BSpline::localCoefficientVector(real_t t) const\n{\n\n  std::pair<real_t,int> ui = computeTIndex(t);\n  int bidx = ui.second - spline_order_ + 1;\n  VectorX c(spline_order_ * coefficients_.rows());\n  for(int i = 0; i < spline_order_; i++)\n  {\n    c.segment(i*coefficients_.rows(), coefficients_.rows()) = coefficients_.col(i + bidx);\n  }\n\n  return c;\n}\n\nVectorXi BSpline::localCoefficientVectorIndices(real_t t) const\n{\n  std::pair<real_t,int> ui = computeTIndex(t);\n  int bidx = ui.second - spline_order_ + 1;\n  int D = coefficients_.rows();\n\n  return VectorXi::LinSpaced(spline_order_*D,bidx*D,(bidx + spline_order_)*D - 1);\n}\n\nVectorXi BSpline::localVvCoefficientVectorIndices(real_t t) const\n{\n  std::pair<real_t,int> ui = computeTIndex(t);\n  int bidx = ui.second - spline_order_ + 1;\n\n  return VectorXi::LinSpaced(spline_order_,bidx,(bidx + spline_order_) - 1);\n}\n\nMatrixX BSpline::Phi(real_t t, int derivative_order) const\n{\n  CHECK_GE(derivative_order, 0) << \"To integrate, use the integral function\";\n  std::pair<real_t,int> ui = computeUAndTIndex(t);\n\n  VectorX u = computeU(ui.first, ui.second, derivative_order);\n\n  int bidx = ui.second - spline_order_ + 1;\n\n  u = basis_matrices_[bidx].transpose() * u;\n\n  MatrixX Phi = MatrixX::Zero(coefficients_.rows(),\n                              spline_order_*coefficients_.rows());\n  MatrixX one = MatrixX::Identity(Phi.rows(), Phi.rows());\n  for(int i = 0; i < spline_order_; i++)\n  {\n    Phi.block(0,Phi.rows()*i,Phi.rows(),Phi.rows()) = one * u(i);\n  }\n\n  return Phi;\n}\n\nvoid BSpline::setCoefficientVector(const VectorX& c)\n{\n  CHECK_GE(c.size(), coefficients_.rows() * coefficients_.cols())\n      << \"The coefficient vector is the wrong size. The vector must contain all vector-valued coefficients stacked up into one column.\";\n  for(int i = 0; i < coefficients_.cols(); i++)\n  {\n    coefficients_.col(i) = c.segment(i * coefficients_.rows(),coefficients_.rows());\n  }\n}\n\nVectorX BSpline::coefficientVector()\n{\n  VectorX c(coefficients_.rows() * coefficients_.cols());\n  for(int i = 0; i < coefficients_.cols(); i++)\n  {\n    c.segment(i * coefficients_.rows(),coefficients_.rows()) = coefficients_.col(i);\n  }\n  return c;\n}\n\nvoid BSpline::setCoefficientMatrix(const MatrixX& coefficients)\n{\n  CHECK_EQ(coefficients_.rows(), coefficients.rows())\n      << \"The new coefficient matrix must match the size of the existing coefficient matrix\";\n  CHECK_EQ(coefficients_.cols(), coefficients.cols())\n      << \"The new coefficient matrix must match the size of the existing coefficient matrix\";\n  coefficients_ = coefficients;\n}\n\nconst MatrixX& BSpline::basisMatrix(int i) const\n{\n  CHECK_LE(i, numValidTimeSegments()) << \"index out of range\";\n  CHECK_LE(0, numValidTimeSegments()) << \"index out of range\";\n  return basis_matrices_[i];\n}\n\n\nstd::pair<real_t,real_t> BSpline::timeInterval() const\n{\n  return std::make_pair(t_min(), t_max());\n}\n\nstd::pair<real_t,real_t> BSpline::timeInterval(int i) const\n{\n  CHECK_GE((int)knots_.size(), minimumKnotsRequired()) << \"The B-spline is not well initialized\";\n  CHECK_LE(i, numValidTimeSegments()) << \"index out of range\";\n  CHECK_LT(0, numValidTimeSegments()) << \"index out of range\";\n  return std::make_pair(knots_[spline_order_ + i - 1],knots_[spline_order_ + i]);\n}\n\nvoid BSpline::initSpline(real_t t_0, real_t t_1,\n                         const VectorX& p_0,\n                         const VectorX& p_1)\n{\n  CHECK_EQ(p_0.size(), p_1.size())\n      << \"The coefficient vectors should be the same size\";\n  CHECK_GT(t_1, t_0) << \"Time must be increasing from t_0 to t_1\";\n\n  // Initialize the spline so that it interpolates the two points\n  // and moves between them with a constant velocity.\n\n  // How many knots are required for one time segment?\n  int K = numKnotsRequired(1);\n  // How many coefficients are required for one time segment?\n  int C = numCoefficientsRequired(1);\n  // What is the vector coefficient dimension\n  int D = p_0.size();\n\n  // Initialize a uniform knot sequence\n  real_t dt = t_1 - t_0;\n  std::vector<real_t> knots(K);\n  for(int i = 0; i < K; i++)\n  {\n    knots[i] = t_0 + (i - spline_order_ + 1) * dt;\n  }\n  // Set the knots and zero the coefficients\n  setKnotsAndCoefficients(knots, MatrixX::Zero(D,C));\n\n  // Now we have to solve an Ax = b linear system to determine the correct coefficient vectors.\n  int coefficientDim = C * D;\n  // We always need an even number of constraints.\n  int constraintsRequired = C + (C & 0x1);\n  int constraintSize = constraintsRequired * D;\n\n  MatrixX A = MatrixX::Zero(constraintSize, coefficientDim);\n  VectorX b = VectorX::Zero(constraintSize);\n\n  // Add the position constraints.\n  int brow = 0;\n  int bcol = 0;\n  A.block(brow,bcol,D,coefficientDim) = Phi(t_min(),0);\n  b.segment(brow,D) = p_0;\n  brow += D;\n  A.block(brow,bcol,D,coefficientDim) = Phi(t_max(),0);\n  b.segment(brow,D) = p_1;\n  brow += D;\n\n  if(spline_order_ > 2)\n  {\n    // At the very minimum we have to add velocity constraints.\n    VectorX v = (p_1 - p_0)/dt;\n    A.block(brow,bcol,D,coefficientDim) = Phi(t_min(),1);\n    b.segment(brow,D) = v;\n    brow += D;\n    A.block(brow,bcol,D,coefficientDim) = Phi(t_max(),1);\n    b.segment(brow,D) = v;\n    brow += D;\n\n    if(spline_order_ > 4)\n    {\n      // Now we add the constraint that all higher-order derivatives are zero.\n      int derivativeOrder = 2;\n      VectorX z = VectorX::Zero(D);\n      while(brow < A.rows())\n      {\n        A.block(brow,bcol,D,coefficientDim) = Phi(t_min(),derivativeOrder);\n        b.segment(brow,D) = z;\n        brow += D;\n        A.block(brow,bcol,D,coefficientDim) = Phi(t_max(),derivativeOrder);\n        b.segment(brow,D) = z;\n        brow += D;\n        ++derivativeOrder;\n      }\n    }\n  }\n\n  // Now we solve the Ax=b system\n  if(A.rows() != A.cols())\n  {\n    // The system is over constrained. This happens for odd ordered splines.\n    b = (A.transpose() * b).eval();\n    A = (A.transpose() * A).eval();\n  }\n\n  // Solve for the coefficient vector.\n  VectorX c = A.householderQr().solve(b);\n  // ldlt doesn't work for this problem. It may be because the ldlt decomposition\n  // requires the matrix to be positive or negative semidefinite\n  // http://eigen.tuxfamily.org/dox-devel/TutorialLinearAlgebra.html#TutorialLinAlgRankRevealing\n  // which may imply that it is symmetric. Our A matrix is only symmetric in the over-constrained case.\n  //VectorX c = A.ldlt().solve(b);\n  setCoefficientVector(c);\n}\n\nvoid BSpline::addCurveSegment(real_t t, const VectorX& p_1)\n{\n  CHECK_GT(t, t_max())\n      << \"The new time must be past the end of the last valid segment\";\n  CHECK_EQ(p_1.size(), coefficients_.rows()) << \"Invalid coefficient vector size\";\n\n  // Get the final valid time interval.\n  int NT = numValidTimeSegments();\n  std::pair<real_t, real_t> interval_km1 = timeInterval(NT-1);\n\n  VectorX p_0;\n\n  // Store the position of the spline at the  end of the interval.\n  // We will use these as constraints as we don't want them to change.\n  p_0 = eval(interval_km1.second);\n\n  // Retool the knot vector.\n  real_t du;\n  int km1;\n  std::tie(du,km1) = computeTIndex(interval_km1.first);\n\n  // leave knots km1 and k alone but retool the other knots.\n  real_t dt = t - knots_[km1 + 1];\n  real_t kt = t;\n\n  // add another knot.\n  std::vector<real_t> knots(knots_);\n  knots.push_back(0.0);\n  // space the further knots uniformly.\n  for(unsigned k = km1 + 2; k < knots.size(); k++)\n  {\n    knots[k] = kt;\n    kt += dt;\n  }\n  // Tack on an new, uninitialized coefficient column.\n  MatrixX c(coefficients_.rows(), coefficients_.cols() + 1);\n  c.topLeftCorner(coefficients_.rows(), coefficients_.cols()) = coefficients_;\n  setKnotsAndCoefficients(knots,c);\n\n  // Now, regardless of the order of the spline, we should only have to add\n  // a single knot and coefficient vector.\n  // In this case, we should solve for the last two coefficient vectors\n  // (i.e., the new one and the one before the new one).\n\n  // Get the time interval of the new time segment.\n  real_t t_0, t_1;\n  std::tie(t_0,t_1) = timeInterval(NT);\n\n  // what is the coefficient dimension?\n  int D = coefficients_.rows();\n  // How many vector-valued coefficients are required? In this case, 2.\n  // We will leave the others fixed.\n  int C = 2;\n  // Now we have to solve an Ax = b linear system to determine the\n  // correct coefficient vectors.\n  int coefficientDim = C * D;\n  // We always need an even number of constraints.\n  int constraintsRequired = 2;\n  int constraintSize = constraintsRequired * D;\n\n  MatrixX A = MatrixX::Zero(constraintSize, coefficientDim);\n  VectorX b = VectorX::Zero(constraintSize);      // Build the A matrix.\n\n  int phiBlockColumnOffset = D * std::max(0,(spline_order_ - 2));\n  VectorX fixedCoefficients = localCoefficientVector(t_0).segment(0,\n                                                                  phiBlockColumnOffset);\n\n  // Add the position constraints.\n  int brow = 0;\n  int bcol = 0;\n  MatrixX P;\n  P = Phi(t_0,0);\n  A.block(brow,bcol,D,coefficientDim) = P.block(0, phiBlockColumnOffset,\n                                                D, coefficientDim);\n  b.segment(brow,D) = p_0 - P.block(0,0,D,phiBlockColumnOffset) * fixedCoefficients;\n  brow += D;\n\n  P = Phi(t_1,0);\n  A.block(brow,bcol,D,coefficientDim) = P.block(0,phiBlockColumnOffset,\n                                                D, coefficientDim);\n  b.segment(brow,D) = p_1 - P.block(0,0,D,phiBlockColumnOffset) * fixedCoefficients;;\n  brow += D;\n\n  // Add regularization constraints (keep the coefficients small)\n  //A.block(brow,bcol,coefficientDim,coefficientDim) = 1e-4 * MatrixX::Identity(coefficientDim, coefficientDim);\n  //b.segment(brow,coefficientDim) = VectorX::Zero(coefficientDim);\n  //brow += coefficientDim;\n\n  // Now we solve the Ax=b system\n  if(A.rows() != A.cols())\n  {\n    // The system is over constrained. This happens for odd ordered splines.\n    b = (A.transpose() * b).eval();\n    A = (A.transpose() * A).eval();\n  }\n\n  VectorX cstar = A.householderQr().solve(b);\n  coefficients_.col(coefficients_.cols() - 2) = cstar.head(D);\n  coefficients_.col(coefficients_.cols() - 1) = cstar.tail(D);\n}\n\n\nvoid BSpline::removeCurveSegment()\n{\n  if(knots_.size() > 0 && coefficients_.cols() > 0)\n  {\n    knots_.erase(knots_.begin());\n    coefficients_ = coefficients_.block(0,\n                                        1,\n                                        coefficients_.rows(),\n                                        coefficients_.cols() - 1).eval();\n  }\n}\n\nvoid BSpline::setLocalCoefficientVector(real_t t, const VectorX& c)\n{\n  CHECK_EQ(c.size(), spline_order_ * coefficients_.rows())\n      << \"The local coefficient vector is the wrong size\";\n  std::pair<real_t,int> ui = computeTIndex(t);\n  int bidx = ui.second - spline_order_ + 1;\n  for(int i = 0; i < spline_order_; i++)\n  {\n    coefficients_.col(i + bidx) = c.segment(i * coefficients_.rows(),\n                                            coefficients_.rows());\n  }\n\n}\n\nvoid BSpline::initSpline2(const VectorX& times,\n                          const MatrixX& interpolation_points,\n                          int num_segments,\n                          real_t lambda)\n{\n  CHECK_EQ(times.size(), interpolation_points.cols())\n      << \"The number of times and the number of interpolation points must be equal\";\n  CHECK_GE(times.size(), 2) << \"There must be at least two times\";\n  CHECK_GE(num_segments, 1) << \"There must be at least one time segment\";\n  for(int i = 1; i < times.size(); i++)\n  {\n    CHECK_LE(times[i-1], times[i])\n        << \"The time sequence must be nondecreasing. time \" << i\n        << \" was not greater than or equal to time \" << (i-1);\n  }\n\n  // Initialize the spline so that it interpolates the N points\n\n  // How many knots are required for one time segment?\n  int K = numKnotsRequired(num_segments);\n  // How many coefficients are required for one time segment?\n  int C = numCoefficientsRequired(num_segments);\n  // What is the vector coefficient dimension\n  int D = interpolation_points.rows();\n\n  // Initialize a uniform knot sequence\n  real_t dt = (times[times.size() - 1] - times[0]) / num_segments;\n  std::vector<real_t> knots(K);\n  for(int i = 0; i < K; i++)\n  {\n    knots[i] = times[0] + (i - spline_order_ + 1) * dt;\n  }\n  // Set the knots and zero the coefficients\n  setKnotsAndCoefficients(knots, MatrixX::Zero(D,C));\n\n  // Now we have to solve an Ax = b linear system to determine the correct coefficient vectors.\n  int coefficientDim = C * D;\n\n  int numConstraints = (knots.size() - 2 * spline_order_ + 2) + interpolation_points.cols();\n  int constraintSize = numConstraints * D;\n\n  MatrixX A = MatrixX::Zero(constraintSize, coefficientDim);\n  VectorX b = VectorX::Zero(constraintSize);\n\n  int brow = 0;\n  //int bcol = 0;\n  // Now add the regularization constraint.\n  //A.block(brow,bcol,coefficientDim,coefficientDim) = 1e-1* MatrixX::Identity(coefficientDim, coefficientDim);\n  //b.segment(brow,coefficientDim) = VectorX::Zero(coefficientDim);\n  //brow += coefficientDim;\n  for(int i = spline_order_ - 1; i < (int)knots.size() - spline_order_ + 1; i++)\n  {\n    VectorXi coeffIndices = localCoefficientVectorIndices(knots[i]);\n\n    A.block(brow,coeffIndices[0],D,coeffIndices.size()) = lambda * Phi(knots[i],2);\n    b.segment(brow,D) = VectorX::Zero(D);\n    brow += D;\n  }\n\n  // Add the position constraints.\n  for(int i = 0; i < interpolation_points.cols(); i++)\n  {\n    VectorXi coeffIndices = localCoefficientVectorIndices(times[i]);\n    A.block(brow,coeffIndices[0],D,coeffIndices.size()) = Phi(times[i],0);\n\n    b.segment(brow,D) = interpolation_points.col(i);\n    brow += D;\n  }\n\n  // Now we solve the Ax=b system\n  //if(A.rows() != A.cols())\n  //  {\n  // The system is over constrained. This happens for odd ordered splines.\n  b = (A.transpose() * b).eval();\n  A = (A.transpose() * A).eval();\n  //  }\n\n  // Solve for the coefficient vector.\n  VectorX c = A.ldlt().solve(b);\n  // ldlt doesn't work for this problem. It may be because the ldlt decomposition\n  // requires the matrix to be positive or negative semidefinite\n  // http://eigen.tuxfamily.org/dox-devel/TutorialLinearAlgebra.html#TutorialLinAlgRankRevealing\n  // which may imply that it is symmetric. Our A matrix is only symmetric in the over-constrained case.\n  // VectorX c = A.ldlt().solve(b);\n  setCoefficientVector(c);\n}\n\nvoid BSpline::initSpline3(const VectorX& times,\n                          const MatrixX& interpolation_points,\n                          int num_segments,\n                          real_t lambda)\n{\n  CHECK_EQ(times.size(), interpolation_points.cols())\n      << \"The number of times and the number of interpolation points must be equal\";\n  CHECK_GE(times.size(), 2) << \"There must be at least two times\";\n  CHECK_GE(num_segments, 1) << \"There must be at least one time segment\";\n  for(int i = 1; i < times.size(); i++)\n  {\n    CHECK_LE(times[i-1], times[i])\n        <<  \"The time sequence must be nondecreasing. time \" << i\n        << \" was not greater than or equal to time \" << (i-1);\n  }\n\n  // How many knots are required for one time segment?\n  int K = numKnotsRequired(num_segments);\n  // How many coefficients are required for one time segment?\n  int C = numCoefficientsRequired(num_segments);\n  // What is the vector coefficient dimension\n  int D = interpolation_points.rows();\n\n  // Initialize a uniform knot sequence\n  real_t dt = (times[times.size() - 1] - times[0]) / num_segments;\n  std::vector<real_t> knots(K);\n  for(int i = 0; i < K; i++)\n  {\n    knots[i] = times[0] + (i - spline_order_ + 1) * dt;\n  }\n\n  setKnotsAndCoefficients(knots, MatrixX::Zero(D,C));\n\n  // Now we have to solve an Ax = b linear system to determine the correct coefficient vectors.\n  int coefficientDim = C * D;\n\n  int numConstraints = interpolation_points.cols();\n  int constraintSize = numConstraints * D;\n\n  MatrixX A = MatrixX::Zero(constraintSize, coefficientDim);\n  VectorX b = VectorX::Zero(constraintSize);\n\n  int brow = 0;\n  // Add the position constraints.\n  for(int i = 0; i < interpolation_points.cols(); i++)\n  {\n    VectorXi coeffIndices = localCoefficientVectorIndices(times[i]);\n\n    A.block(brow,coeffIndices[0],D,coeffIndices.size()) = Phi(times[i],0);\n\n    b.segment(brow,D) = interpolation_points.col(i);\n    brow += D;\n  }\n\n  b = (A.transpose() * b).eval();\n  A = (A.transpose() * A).eval();\n\n  // Add the motion constraint.\n  VectorX W = VectorX::Constant(D,lambda);\n\n  A += curveQuadraticIntegralDiag(W, 2);\n\n  VectorX c = A.ldlt().solve(b);\n  setCoefficientVector(c);\n\n}\n\nvoid BSpline::addCurveSegment2(real_t t,\n                               const VectorX& p_1,\n                               real_t lambda)\n{\n  CHECK_GT(t, t_max())\n      << \"The new time must be past the end of the last valid segment\";\n  CHECK_EQ(p_1.size(), coefficients_.rows())\n      << \"Invalid coefficient vector size\";\n\n  // Get the final valid time interval.\n  int NT = numValidTimeSegments();\n  std::pair<real_t, real_t> interval_km1 = timeInterval(NT-1);\n\n  VectorX p_0;\n\n  // Store the position of the spline at the  end of the interval.\n  // We will use these as constraints as we don't want them to change.\n  p_0 = eval(interval_km1.second);\n\n  // Retool the knot vector.\n  real_t du;\n  int km1;\n  std::tie(du,km1) = computeTIndex(interval_km1.first);\n\n  // leave knots km1 and k alone but retool the other knots.\n  real_t dt = t - knots_[km1 + 1];\n  real_t kt = t;\n\n  // add another knot.\n  std::vector<real_t> knots(knots_);\n  knots.push_back(0.0);\n  // space the further knots uniformly.\n  for(unsigned k = km1 + 2; k < knots.size(); k++)\n  {\n    knots[k] = kt;\n    kt += dt;\n  }\n  // Tack on an new, uninitialized coefficient column.\n  MatrixX c(coefficients_.rows(), coefficients_.cols() + 1);\n  c.topLeftCorner(coefficients_.rows(), coefficients_.cols()) = coefficients_;\n  setKnotsAndCoefficients(knots,c);\n\n  // Now, regardless of the order of the spline, we should only have to\n  // add a single knot and coefficient vector.\n  // In this case, we should solve for the last two coefficient\n  // vectors (i.e., the new one and the one before the\n  // new one).\n\n  // Get the time interval of the new time segment.\n  real_t t_0, t_1;\n  std::tie(t_0,t_1) = timeInterval(NT);\n\n  // what is the coefficient dimension?\n  int D = coefficients_.rows();\n  // How many vector-valued coefficients are required? In this case, 2.\n  // We will leave the others fixed.\n  int C = 2;\n  // Now we have to solve an Ax = b linear system to determine the correct\n  // coefficient vectors.\n  int coefficientDim = C * D;\n  // We always need an even number of constraints.\n  int constraintsRequired = 2 + 2;\n  int constraintSize = constraintsRequired * D;\n\n  MatrixX A = MatrixX::Zero(constraintSize, coefficientDim);\n  VectorX b = VectorX::Zero(constraintSize);      // Build the A matrix.\n\n  int phiBlockColumnOffset = D * std::max(0,(spline_order_ - 2));\n  VectorX fixedCoefficients = localCoefficientVector(t_0).segment(0,\n                                                                  phiBlockColumnOffset);\n\n  // Add the position constraints.\n  int brow = 0;\n  int bcol = 0;\n  MatrixX P;\n  P = Phi(t_0,0);\n  A.block(brow,bcol,D,coefficientDim) = P.block(0, phiBlockColumnOffset,\n                                                D, coefficientDim);\n  b.segment(brow,D) = p_0 - P.block(0,0,D,phiBlockColumnOffset) * fixedCoefficients;\n  brow += D;\n\n  P = Phi(t_1,0);\n  A.block(brow,bcol,D,coefficientDim) = P.block(0, phiBlockColumnOffset,\n                                                D, coefficientDim);\n  b.segment(brow,D) = p_1 - P.block(0,0,D,phiBlockColumnOffset) * fixedCoefficients;;\n  brow += D;\n\n\n  // Add regularization constraints (keep the acceleration small)\n  P = Phi(t_0,2);\n  A.block(brow,bcol,D,coefficientDim) = lambda * P.block(0, phiBlockColumnOffset,\n                                                         D, coefficientDim);\n  b.segment(brow,D) = VectorX::Zero(D);\n  brow += D;\n\n  P = Phi(t_1,2);\n  A.block(brow,bcol,D,coefficientDim) = lambda * P.block(0, phiBlockColumnOffset,\n                                                         D, coefficientDim);\n  b.segment(brow,D) = VectorX::Zero(D);\n  brow += D;\n\n  //A.block(brow,bcol,coefficientDim,coefficientDim) = 1e-4 * MatrixX::Identity(coefficientDim, coefficientDim);\n  //b.segment(brow,coefficientDim) = VectorX::Zero(coefficientDim);\n  //brow += coefficientDim;\n\n  // Now we solve the Ax=b system\n  if(A.rows() != A.cols())\n  {\n    // The system is over constrained. This happens for odd ordered splines.\n    b = (A.transpose() * b).eval();\n    A = (A.transpose() * A).eval();\n  }\n\n  VectorX cstar = A.householderQr().solve(b);\n  coefficients_.col(coefficients_.cols() - 2) = cstar.head(D);\n  coefficients_.col(coefficients_.cols() - 1) = cstar.tail(D);\n}\n\nMatrixX BSpline::Vi(int segment_index) const\n{\n  CHECK_LT(segment_index, numValidTimeSegments())\n      << \"Segment index out of bounds\";\n  CHECK_LT(0, numValidTimeSegments())\n      << \"Segment index out of bounds\";\n\n  VectorX vals(spline_order_*2);\n  for (int i = 0; i < vals.size(); ++i)\n  {\n    vals[i] = 1.0/(i + 1.0);\n  }\n\n  MatrixX V(spline_order_,spline_order_);\n  for(int r = 0; r < V.rows(); r++)\n  {\n    for(int c = 0; c < V.cols(); c++)\n    {\n      V(r,c) = vals[r + c];\n    }\n  }\n\n  real_t t_0,t_1;\n  std::tie(t_0,t_1) = timeInterval(segment_index);\n\n  V *= t_1 - t_0;\n\n  return V;\n}\n\nVectorX BSpline::evalIntegral(real_t t1, real_t t2) const\n{\n  if(t1 > t2)\n  {\n    return -evalIntegral(t2,t1);\n  }\n\n  std::pair<real_t,int> u1 = computeTIndex(t1);\n  std::pair<real_t,int> u2 = computeTIndex(t2);\n\n  VectorX integral = VectorX::Zero(coefficients_.rows());\n\n  // LHS remainder.\n  real_t lhs_remainder = t1 - knots_[u1.second];\n  if(lhs_remainder > 1e-16 && u1.first > 1e-16)\n  {\n    lhs_remainder /= u1.first;\n    VectorX v(spline_order_);\n    real_t du = lhs_remainder;\n    for(int i = 0; i < spline_order_; i++)\n    {\n      v(i) = du/(i + 1.0);\n      du *= lhs_remainder;\n    }\n    int bidx = basisMatrixIndexFromStartingKnotIndex(u1.second);\n    integral -= u1.first * coefficients_.block(0,\n                                               bidx,coefficients_.rows(),\n                                               spline_order_)\n                * basis_matrices_[bidx].transpose() * v;\n  }\n\n  // central time segments.\n  VectorX v = VectorX::Zero(spline_order_);\n  for(int i = 0; i < spline_order_; i++)\n  {\n    v(i) = 1.0/(i + 1.0);\n  }\n\n  for(int s = u1.second; s < u2.second; s++)\n  {\n    int bidx = basisMatrixIndexFromStartingKnotIndex(s);\n    integral += (knots_[s+1] - knots_[s])\n        * coefficients_.block(0, bidx, coefficients_.rows(), spline_order_)\n        * basis_matrices_[bidx].transpose() * v;\n  }\n\n  // RHS remainder.\n  real_t rhs_remainder = t2 - knots_[u2.second];\n  if(rhs_remainder > 1e-16 && u2.first > 1e-16)\n  {\n    rhs_remainder /= u2.first;\n\n    VectorX v(spline_order_);\n    real_t du = rhs_remainder;\n    for(int i = 0; i < spline_order_; i++)\n    {\n      v(i) = du / (i + 1.0);\n      du *= rhs_remainder;\n    }\n\n    int bidx = basisMatrixIndexFromStartingKnotIndex(u2.second);\n    integral += u2.first\n                * coefficients_.block(0,bidx,coefficients_.rows(),spline_order_)\n                * basis_matrices_[bidx].transpose()\n                * v;\n  }\n\n  return integral;\n}\n\nint BSpline::basisMatrixIndexFromStartingKnotIndex(int starting_knot_index) const\n{\n  return starting_knot_index - spline_order_ + 1;\n}\n\nint BSpline::startingKnotIndexFromBasisMatrixIndex(int basis_matrix_index) const\n{\n  return spline_order_ + basis_matrix_index - 1;\n}\n\n\nMatrixX BSpline::Bij(int segment_index, int column_index) const\n{\n  CHECK_LE(segment_index, (int)basis_matrices_.size()) << \"Out of range\";\n  CHECK_LT(0, (int)basis_matrices_.size()) << \"Out of range\";\n  CHECK_LE(column_index, spline_order_) << \"Out of range\";\n  CHECK_LT(0, spline_order_) << \"Out of range\";\n  int D = coefficients_.rows();\n  MatrixX B = MatrixX::Zero(spline_order_*D,D);\n  for(int i = 0; i < D; i++)\n  {\n    B.block(i*spline_order_,i,spline_order_,1) = basis_matrices_[segment_index].col(column_index);\n  }\n\n  return B;\n}\n\nMatrixX BSpline::Mi(int segment_index) const\n{\n  CHECK_LE(segment_index, (int)basis_matrices_.size()) << \"Out of range\";\n  CHECK_LT(0, (int)basis_matrices_.size()) << \"Out of range\";\n  int D = coefficients_.rows();\n  MatrixX M = MatrixX::Zero(spline_order_*D,spline_order_*D);\n\n  for(int j = 0; j < spline_order_; j++)\n  {\n    M.block(0,j*D,D*spline_order_, D) = Bij(segment_index,j);\n  }\n\n  return M;\n}\n\nVectorX BSpline::getLocalBiVector(real_t t, int derivative_order) const\n{\n  VectorX ret = VectorX::Zero(spline_order_);\n  getLocalBiInto(t, ret, derivative_order);\n\n  return ret;\n}\n\nvoid BSpline::getLocalBiInto(real_t t, VectorX& ret, int derivative_order) const\n{\n  int si = segmentIndex(t);\n  VectorX lu = u(t, derivative_order);\n  for(int j = 0; j < spline_order_; j++) {\n    ret[j] = lu.dot(basis_matrices_[si].col(j));\n  }\n}\n\nVectorX BSpline::getLocalCumulativeBiVector(real_t t, int derivative_order) const\n{\n  VectorX bi = getLocalBiVector(t, derivative_order);\n  int maxIndex = bi.rows() - 1;\n  // tildeB(i) = np.sum(bi[i+1:]) :\n  for(int i = 1; i <= maxIndex; i ++)\n  {\n    real_t sum = 0;\n    for(int j = maxIndex; j > i; j--)\n    {\n      sum += bi[j];\n    }\n    bi[i] += sum;\n  }\n  if (derivative_order == 0)\n  {\n    bi[0] = 1; // the sum of k successive spline basis functions is always 1\n  }\n  else\n  {\n    bi[0] = 0;\n  }\n  return bi;\n}\n\nint BSpline::segmentIndex(real_t t) const\n{\n  std::pair<real_t,int> ui = computeTIndex(t);\n\n  return basisMatrixIndexFromStartingKnotIndex(ui.second);\n}\n\nMatrixX BSpline::U(real_t t, int derivative_order) const\n{\n  VectorX uvec = u(t,derivative_order);\n  int D = coefficients_.rows();\n  MatrixX Umat = MatrixX::Zero(spline_order_ * D, D);\n\n  for(int i = 0; i < D; i++)\n  {\n    Umat.block(i*spline_order_,i,spline_order_,1) = uvec;\n  }\n\n  return Umat;\n}\n\nVectorX BSpline::u(real_t t, int derivative_order) const\n{\n  std::pair<real_t,int> ui = computeUAndTIndex(t);\n\n  return computeU(ui.first, ui.second, derivative_order);\n}\n\nMatrixX BSpline::Di(int segment_index) const\n{\n  int D = coefficients_.rows();\n  MatrixX fullD = MatrixX::Zero(spline_order_*D, spline_order_*D);\n\n  MatrixX subD = Dii(segment_index);\n\n  for(int d = 0; d < D; d++)\n  {\n    fullD.block(d*spline_order_,d*spline_order_,spline_order_,spline_order_) = subD;\n  }\n\n  return fullD;\n}\n\nMatrixX BSpline::Dii(int segment_index) const\n{\n  CHECK_LE(segment_index, (int)basis_matrices_.size()) << \"Out of range\";\n  CHECK_LT(0, (int)basis_matrices_.size()) << \"Out of range\";\n  real_t t_0,t_1;\n  std::tie(t_0,t_1) = timeInterval(segment_index);\n  real_t dt = t_1 - t_0;\n\n  real_t recip_dt = 0.0;\n  if(dt > 0)\n  {\n    recip_dt = 1.0/dt;\n  }\n  MatrixX D = MatrixX::Zero(spline_order_,spline_order_);\n  for(int i = 0; i < spline_order_ - 1; i++)\n  {\n    D(i,i+1) = (i+1.0) * recip_dt;\n  }\n\n  return D;\n}\n\nMatrixX BSpline::segmentQuadraticIntegral(const MatrixX& W,\n                                          int segment_idx,\n                                          int derivative_order) const\n{\n  int D = coefficients_.rows();\n  //CHECK_GE(segmentIndex, (int)basisMatrices_.size()) << \"Out of range\";\n  CHECK_LT(0, (int)basis_matrices_.size()) << \"Out of range\";\n  CHECK_EQ(W.rows(), D)\n      <<\"W must be a square matrix the size of a single vector-valued coefficient\";\n  CHECK_EQ(W.cols(), D)\n      << \"W must be a square matrix the size of a single vector-valued coefficient\";\n\n  int N = D * spline_order_;\n  MatrixX Q;// = MatrixX::Zero(N,N);\n  MatrixX Dm = Dii(segment_idx);\n  MatrixX V = Vi(segment_idx);\n  MatrixX M = Mi(segment_idx);\n\n  // Calculate the appropriate derivative version of V\n  // using the matrix multiplication version of the derivative.\n  for(int i = 0; i < derivative_order; i++)\n  {\n    V = (Dm.transpose() * V * Dm).eval();\n  }\n\n  MatrixX WV = MatrixX::Zero(N,N);\n\n  for(int r = 0; r < D; r++)\n  {\n    for(int c = 0; c < D; c++)\n    {\n      CHECK_GE(1e-14, std::abs(W(r,c) - W(c,r))) << \"W must be symmetric\";\n      //std::cout << \"Size WV: \" << WV.rows() << \", \" << WV.cols() << std::endl;\n      //std::cout << \"Size V: \" << V.rows() << \", \" << V.cols() << std::endl;\n      WV.block(spline_order_*r,\n               spline_order_*c,\n               spline_order_,\n               spline_order_) = W(r,c) * V;\n    }\n  }\n\n  Q = M.transpose() * WV * M;\n\n  return Q;\n}\n\nMatrixX BSpline::segmentQuadraticIntegralDiag(const VectorX& Wdiag,\n                                              int segment_idx,\n                                              int derivative_order) const\n{\n  int D = coefficients_.rows();\n  //CHECK_GE(segmentIndex, (int)basisMatrices_.size()) << \"Out of range\";\n  CHECK_LT(0, (int)basis_matrices_.size()) << \"Out of range\";\n  CHECK_EQ(Wdiag.size(), D) << \"Wdiag must be the length of a single vector-valued coefficient\";\n\n  int N = D * spline_order_;\n  MatrixX Q;// = MatrixX::Zero(N,N);\n  MatrixX Dm = Dii(segment_idx);\n  MatrixX V = Vi(segment_idx);\n  MatrixX M = Mi(segment_idx);\n\n  // Calculate the appropriate derivative version of V\n  // using the matrix multiplication version of the derivative.\n  for(int i = 0; i < derivative_order; i++)\n  {\n    V = (Dm.transpose() * V * Dm).eval();\n  }\n\n  MatrixX WV = MatrixX::Zero(N,N);\n\n  for(int d = 0; d < D; d++)\n  {\n    //std::cout << \"Size WV: \" << WV.rows() << \", \" << WV.cols() << std::endl;\n    //std::cout << \"Size V: \" << V.rows() << \", \" << V.cols() << std::endl;\n    WV.block(spline_order_*d, spline_order_*d,spline_order_,spline_order_) = Wdiag(d) * V;\n  }\n\n  Q = M.transpose() * WV * M;\n\n  return Q;\n}\n\nMatrixX BSpline::curveQuadraticIntegral(const MatrixX& W,\n                                        int derivative_order) const\n{\n  int D = coefficients_.rows();\n  CHECK_EQ(W.rows(), D)\n      << \"W must be a square matrix the size of a single vector-valued coefficient\";\n  CHECK_EQ(W.cols(), D)\n      << \"W must be a square matrix the size of a single vector-valued coefficient\";\n  int N = coefficients_.cols();\n\n  MatrixX Q = MatrixX::Zero(D*N, D*N);\n\n  int QiSize = spline_order_ * D;\n  for(int s = 0; s < numValidTimeSegments(); s++)\n  {\n    Q.block(s*D,s*D,QiSize,QiSize) += segmentQuadraticIntegral(W, s, derivative_order);\n  }\n\n  return Q;\n}\n\nMatrixX BSpline::curveQuadraticIntegralDiag(const VectorX& Wdiag,\n                                            int derivative_order) const\n{\n  int D = coefficients_.rows();\n  CHECK_EQ(Wdiag.size(), D)\n      << \"Wdiag must be the length of a single vector-valued coefficient\";\n  int N = coefficients_.cols();\n\n  MatrixX Q = MatrixX::Zero(D*N, D*N);\n\n  int QiSize = spline_order_ * D;\n  for(int s = 0; s < numValidTimeSegments(); s++)\n  {\n    Q.block(s*D,s*D,QiSize,QiSize) += segmentQuadraticIntegralDiag(Wdiag,\n                                                                   s,\n                                                                   derivative_order);\n  }\n\n  return Q;\n}\n\nint BSpline::coefficientVectorLength() const\n{\n  return coefficients_.rows() * coefficients_.cols();\n}\n\nvoid BSpline::initConstantSpline(real_t t_min,\n                                 real_t t_max,\n                                 int num_segments,\n                                 const VectorX& constant)\n{\n  CHECK_GT(t_max, t_min) << \"The max time is less than the min time\";\n  CHECK_GE(num_segments, 1) << \"There must be at least one segment\";\n  CHECK_GE(constant.size(), 1)\n      << \"The constant vector must be of at least length 1\";\n\n  int K = numKnotsRequired(num_segments);\n  int C = numCoefficientsRequired(num_segments);\n  real_t dt = (t_max - t_min) / (real_t)num_segments;\n\n  real_t minTime = t_min - (spline_order_ - 1)*dt;\n  real_t maxTime = t_max + (spline_order_ - 1)*dt;\n  VectorX knotVector = VectorX::LinSpaced(K,minTime,maxTime);\n  // std::cout << \"K: \" << K << std::endl;\n  // std::cout << \"S: \" << numSegments << std::endl;\n  // std::cout << \"segTime: \" << t_min << \", \" << t_max << std::endl;\n  // std::cout << \"dt: \" << dt << std::endl;\n  // std::cout << \"time: \" << minTime << \", \" << maxTime << std::endl;\n  // std::cout << \"order: \" << splineOrder_ << std::endl;\n  // std::cout << knotVector.transpose() << std::endl;\n  MatrixX coeff(constant.size(),C);\n  for(int i = 0; i < C; i++)\n  {\n    coeff.col(i) = constant;\n  }\n\n  setKnotVectorAndCoefficients(knotVector,coeff);\n}\n\nint BSpline::numCoefficients() const\n{\n  return coefficients_.rows() * coefficients_.cols();\n}\n\nEigen::Map<VectorX> BSpline::vvCoefficientVector(int i)\n{\n  CHECK_LE(i, coefficients_.cols()) << \"Index out of range\";\n  CHECK_LT(0, coefficients_.cols()) << \"Index out of range\";\n  return Eigen::Map<VectorX>(&coefficients_(0,i),coefficients_.rows());\n}\n\nEigen::Map<const VectorX> BSpline::vvCoefficientVector(int i) const\n{\n  CHECK_LE(i, coefficients_.cols()) << \"Index out of range\";\n  CHECK_LT(0, coefficients_.cols()) << \"Index out of range\";\n  return Eigen::Map<const VectorX>(&coefficients_(0,i),coefficients_.rows());\n}\n\nint BSpline::numVvCoefficients() const\n{\n  return coefficients_.cols();\n}\n\n}  // namespace ze\n", "meta": {"hexsha": "1b7bff9b9d624456a5667dd48b64b5f0246659ca", "size": 46840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ze_splines/src/bspline.cpp", "max_stars_repo_name": "rockenbf/ze_oss", "max_stars_repo_head_hexsha": "ee04158e2d51acb07a267196f618e9afbc3ffd83", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-09-27T07:41:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T20:44:28.000Z", "max_issues_repo_path": "ze_splines/src/bspline.cpp", "max_issues_repo_name": "rockenbf/ze_oss", "max_issues_repo_head_hexsha": "ee04158e2d51acb07a267196f618e9afbc3ffd83", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-18T15:53:06.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-21T03:10:06.000Z", "max_forks_repo_path": "ze_splines/src/bspline.cpp", "max_forks_repo_name": "rockenbf/ze_oss", "max_forks_repo_head_hexsha": "ee04158e2d51acb07a267196f618e9afbc3ffd83", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2016-11-05T07:51:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-13T02:26:08.000Z", "avg_line_length": 31.1022576361, "max_line_length": 136, "alphanum_fraction": 0.6306789069, "num_tokens": 13232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4104232985543739}}
{"text": "\n#include <NTL/vec_lzz_p.h>\n\nNTL_START_IMPL\n\n\n// NOTE: the signature for this is in lzz_p.h\nvoid conv(vec_zz_p& x, const vec_ZZ& a)\n{\n   long i, n;\n\n   n = a.length();\n   x.SetLength(n);\n\n   VectorConv(n, x.elts(), a.elts());\n}\n\n// NOTE: the signature for this is in lzz_p.h\nvoid conv(vec_zz_p& x, const Vec<long>& a)\n{\n   long i, n;\n\n   n = a.length();\n   x.SetLength(n);\n\n   VectorConv(n, x.elts(), a.elts());\n}\n\n\n\n\nvoid InnerProduct(zz_p& x, const vec_zz_p& a, const vec_zz_p& b)\n{\n   long n = min(a.length(), b.length());\n   long i;\n\n   long accum, t;\n   long p = zz_p::modulus();\n   mulmod_t pinv = zz_p::ModulusInverse();\n\n   const zz_p *ap = a.elts();\n   const zz_p *bp = b.elts();\n\n   accum = 0;\n   for (i = 0; i < n; i++) {\n      t = MulMod(rep(ap[i]), rep(bp[i]), p, pinv);\n      accum = AddMod(accum, t, p);\n   }\n\n   x.LoopHole() = accum;\n}\n\nvoid InnerProduct(zz_p& x, const vec_zz_p& a, const vec_zz_p& b,\n                  long offset)\n{\n   if (offset < 0) LogicError(\"InnerProduct: negative offset\");\n   if (NTL_OVERFLOW(offset, 1, 0)) ResourceError(\"InnerProduct: offset too big\");\n\n   long n = min(a.length(), b.length()+offset);\n   long i;\n\n   long accum, t;\n   long p = zz_p::modulus();\n   mulmod_t pinv = zz_p::ModulusInverse();\n\n\n   const zz_p *ap = a.elts();\n   const zz_p *bp = b.elts();\n\n   accum = 0;\n   for (i = offset; i < n; i++) {\n      t = MulMod(rep(ap[i]), rep(bp[i-offset]), p, pinv);\n      accum = AddMod(accum, t, p);\n   }\n\n   x.LoopHole() = accum;\n}\n\nlong CRT(vec_ZZ& gg, ZZ& a, const vec_zz_p& G)\n{\n   long n = gg.length();\n   if (G.length() != n) LogicError(\"CRT: vector length mismatch\");\n\n   long p = zz_p::modulus();\n\n   ZZ new_a;\n   mul(new_a, a, p);\n\n   long a_inv;\n   a_inv = rem(a, p);\n   a_inv = InvMod(a_inv, p);\n\n   long p1;\n   p1 = p >> 1;\n\n   ZZ a1;\n   RightShift(a1, a, 1);\n\n   long p_odd = (p & 1);\n\n   long modified = 0;\n\n   long h;\n\n   ZZ g;\n   long i;\n   for (i = 0; i < n; i++) {\n      if (!CRTInRange(gg[i], a)) {\n         modified = 1;\n         rem(g, gg[i], a);\n         if (g > a1) sub(g, g, a);\n      }\n      else\n         g = gg[i];\n   \n      h = rem(g, p);\n      h = SubMod(rep(G[i]), h, p);\n      h = MulMod(h, a_inv, p);\n      if (h > p1)\n         h = h - p;\n   \n      if (h != 0) {\n         modified = 1;\n   \n         if (!p_odd && g > 0 && (h == p1))\n            MulSubFrom(g, a, h);\n         else\n            MulAddTo(g, a, h);\n      }\n\n      gg[i] = g;\n   }\n\n   a = new_a;\n\n   return modified;\n}\n\n\n\nvoid mul(vec_zz_p& x, const vec_zz_p& a, zz_p b)\n{\n   long n = a.length();\n   x.SetLength(n);\n\n   long i;\n\n   if (n <= 1) {\n\n      for (i = 0; i < n; i++)\n         mul(x[i], a[i], b);\n\n   }\n   else {\n \n      long p = zz_p::modulus();\n      mulmod_t pinv = zz_p::ModulusInverse();\n      long bb = rep(b);\n      mulmod_precon_t bpinv = PrepMulModPrecon(bb, p, pinv);\n      \n      \n      const zz_p *ap = a.elts();\n      zz_p *xp = x.elts();\n\n      for (i = 0; i < n; i++)\n         xp[i].LoopHole() = MulModPrecon(rep(ap[i]), bb, p, bpinv);\n\n   }\n}\n\nvoid mul(vec_zz_p& x, const vec_zz_p& a, long b_in)\n{\n   zz_p b;\n   b = b_in;\n   mul(x, a, b);\n}\n\n\n\nvoid add(vec_zz_p& x, const vec_zz_p& a, const vec_zz_p& b)\n{\n   long n = a.length();\n   if (b.length() != n) LogicError(\"vector add: dimension mismatch\");\n\n   long p = zz_p::modulus();\n\n   x.SetLength(n);\n\n   const zz_p *ap = a.elts();\n   const zz_p *bp = b.elts();\n   zz_p *xp = x.elts();\n\n   long i;\n   for (i = 0; i < n; i++)\n      xp[i].LoopHole() = AddMod(rep(ap[i]), rep(bp[i]), p);\n}\n\nvoid sub(vec_zz_p& x, const vec_zz_p& a, const vec_zz_p& b)\n{\n   long n = a.length();\n   if (b.length() != n) LogicError(\"vector sub: dimension mismatch\");\n\n   long p = zz_p::modulus();\n\n   x.SetLength(n);\n\n\n   const zz_p *ap = a.elts();\n   const zz_p *bp = b.elts();\n   zz_p *xp = x.elts();\n\n   long i;\n   for (i = 0; i < n; i++)\n      xp[i].LoopHole() = SubMod(rep(ap[i]), rep(bp[i]), p);\n}\n\nvoid clear(vec_zz_p& x)\n{\n   long n = x.length();\n\n\n   zz_p *xp = x.elts();\n\n   long i;\n   for (i = 0; i < n; i++)\n      clear(xp[i]);\n}\n\nvoid negate(vec_zz_p& x, const vec_zz_p& a)\n{\n   long n = a.length();\n   long p = zz_p::modulus();\n\n   x.SetLength(n);\n\n\n   const zz_p *ap = a.elts();\n   zz_p *xp = x.elts();\n\n\n   long i;\n   for (i = 0; i < n; i++)\n      xp[i].LoopHole() = NegateMod(rep(ap[i]), p);\n}\n\n\nlong IsZero(const vec_zz_p& a)\n{\n   long n = a.length();\n\n\n   const zz_p *ap = a.elts();\n\n   long i;\n   for (i = 0; i < n; i++)\n      if (!IsZero(ap[i]))\n         return 0;\n\n   return 1;\n}\n\nvec_zz_p operator+(const vec_zz_p& a, const vec_zz_p& b)\n{\n   vec_zz_p res;\n   add(res, a, b);\n   NTL_OPT_RETURN(vec_zz_p, res);\n}\n\nvec_zz_p operator-(const vec_zz_p& a, const vec_zz_p& b)\n{\n   vec_zz_p res;\n   sub(res, a, b);\n   NTL_OPT_RETURN(vec_zz_p, res);\n}\n\n\nvec_zz_p operator-(const vec_zz_p& a)\n{\n   vec_zz_p res;\n   negate(res, a);\n   NTL_OPT_RETURN(vec_zz_p, res);\n}\n\n\nzz_p operator*(const vec_zz_p& a, const vec_zz_p& b)\n{\n   zz_p res;\n   InnerProduct(res, a, b);\n   return res;\n}\n\n\nvoid VectorCopy(vec_zz_p& x, const vec_zz_p& a, long n)\n{\n   if (n < 0) LogicError(\"VectorCopy: negative length\");\n   if (NTL_OVERFLOW(n, 1, 0)) ResourceError(\"overflow in VectorCopy\");\n\n   long m = min(n, a.length());\n\n   x.SetLength(n);\n\n\n   const zz_p *ap = a.elts();\n   zz_p *xp = x.elts();\n\n  \n   long i;\n\n   for (i = 0; i < m; i++)\n      xp[i] = ap[i];\n\n   for (i = m; i < n; i++)\n      clear(xp[i]);\n}\n\n\nvoid random(vec_zz_p& x, long n)\n{\n   x.SetLength(n);\n   VectorRandom(n, x.elts());\n}\n\nNTL_END_IMPL\n", "meta": {"hexsha": "fd509a9da205fc59c54b2af4f778ffc73f7e5d23", "size": 5504, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/vec_lzz_p.cpp", "max_stars_repo_name": "dklee0501/PLDI_20_242_artifact_publication", "max_stars_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 160.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T09:32:19.000Z", "max_issues_repo_path": "homomorphic_evaluation/ntl-11.3.2/src/vec_lzz_p.cpp", "max_issues_repo_name": "dklee0501/Lobster", "max_issues_repo_head_hexsha": "f2b73df9165c76e8b521d8ebd639d68321e3862b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2016-12-26T07:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T16:34:31.000Z", "max_forks_repo_path": "LibSource/ExtendedNTL/src/vec_lzz_p.cpp", "max_forks_repo_name": "ekzyis/CrypTool-2", "max_forks_repo_head_hexsha": "1af234b4f74486fbfeb3b3c49228cc36533a8c89", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2016-10-10T17:56:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:56:39.000Z", "avg_line_length": 16.987654321, "max_line_length": 81, "alphanum_fraction": 0.5256177326, "num_tokens": 1949, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635841117624, "lm_q2_score": 0.6406358617010351, "lm_q1q2_score": 0.4104142941109565}}
{"text": "/**\n * @file set_cover_example.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2014-02-17\n */\n//! [Set Cover Example]\n#include <iostream>\n#include <vector>\n#include <iterator>\n\n#include <boost/range/irange.hpp>\n\n#include \"paal/greedy/set_cover/set_cover.hpp\"\n\nint main() {\n    std::vector<std::vector<int>> set_to_elements = {\n        { 1, 2 },\n        { 3, 4, 5, 6 },\n        { 7, 8, 9, 10, 11, 12, 13, 0 },\n        { 1, 3, 5, 7, 9, 11, 13 },\n        { 2, 4, 6, 8, 10, 12, 0 }\n    };\n    std::vector<int> costs = { 1, 1, 1, 1, 1 };\n    auto sets = boost::irange(0, 5);\n    std::vector<int> result;\n    auto element_index = [](int el){return el;};\n    auto cost = paal::greedy::set_cover(sets,\n                                        [&](int set){return costs[set];},\n                                        [&](int set){return set_to_elements[set];},\n                                        back_inserter(result),\n                                        element_index);\n    std::cout << \"Cost: \" << cost << std::endl;\n}\n//! [Set Cover Example]\n", "meta": {"hexsha": "264f728af863210fe85aef00c988d15a58735cf7", "size": 1063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/greedy/set_cover_example.cpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/greedy/set_cover_example.cpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/greedy/set_cover_example.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 28.7297297297, "max_line_length": 83, "alphanum_fraction": 0.4816556914, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.41040482902742437}}
{"text": "#include \"optimiser.hpp\"\n#include \"logger.hpp\"\n#include \"scf.hpp\"\n#include \"atom.hpp\"\n#include \"integrals.hpp\"\n#include <vector>\n#include <Eigen/Core>\n#include <iomanip>\n\ndouble rfo(Vector& dx, Vector& grad, Matrix& hessian, double alpha, double stepsize) {\n\t\n\tVector step; \n\tstd::pair<double, double> results = rfo_prime(step, grad, hessian, alpha); \n\tVector m_dy; \n\tdouble m_expect; \n\tdouble step_norm = step.norm(); \n\tif (step_norm > stepsize) {\n\t\tdouble v = alpha; \n\t\tint niter = 0; \n\t\tdouble ndy_last = 0.0; \n\t\t\n\t\tdouble m_ndy = step_norm; \n\t\tm_dy = step; \n\t\tm_expect = results.first; \n\t\t\n\t\twhile(niter < 100) {\n\t\t\tv += (1-step_norm / stepsize) * step_norm / results.second; \n\t\t\tresults = rfo_prime(step, grad, hessian, v); \n\t\t\tstep_norm = step.norm(); \n\t\t\t\n\t\t\tif (fabs(step_norm - stepsize)/stepsize < 0.001) {\n\t\t\t\tm_dy = step;\n\t\t\t\tm_expect = results.first;\n\t\t\t\tbreak; \n\t\t\t}\n\t\t\telse if (niter > 10 && fabs(ndy_last - step_norm)/step_norm < 0.001) {\n\t\t\t\tm_dy = step;\n\t\t\t\tm_expect = results.first;\n\t\t\t\tbreak; \t\n\t\t\t}\n\t\t\t\n\t\t\tniter++; \n\t\t\tndy_last = step_norm; \n\t\t\tif (step_norm < m_ndy) {\n\t\t\t\tm_ndy = step_norm;\n\t\t\t\tm_dy = step;\n\t\t\t\tm_expect = results.first; \n\t\t\t}\t\n\t\t}\n\t} else {\n\t\tm_dy = step; \n\t\tm_expect = results.first; \n\t}\n\t\n\tdx = m_dy; \n\treturn m_expect; \n}\n\ndouble trust_newton(Vector& dx, Vector& grad, Matrix& hessian, double stepsize) {\n\tEigenSolver hsolve(hessian); \n\tVector gtilde = hsolve.eigenvectors().transpose() * grad; \n\tVector step = Vector::Zero(hessian.rows());\n\tfor (int i = 0; i < hessian.rows(); i++) {\n\t\tdouble eival = hsolve.eigenvalues()[i]; \n\t\tif (fabs(eival) > 1e-12)\n\t\t\tstep[i] = - gtilde[i] / eival; \n\t}\n\t\n\tdx = hsolve.eigenvectors() * step; \n\t\n\tMatrix ident = Matrix::Identity(hessian.rows(), hessian.cols()); \n\tif (dx.norm() > stepsize) {\n\t\tdouble eimin = hsolve.eigenvalues()[0]; \n\t\tdouble factor = eimin < 0 ? 1.0 : 0.0; \n\t\tdouble mu = (factor + 0.9)*eimin;\n\t\t\n\t\tMatrix hshift = hsolve.eigenvalues().asDiagonal();\n\t\tfor (int i = 0; i < hshift.rows(); i++) {\n\t\t\tdouble hii = hshift(i, i) - mu;\n\t\t\thshift(i, i) = 1.0 / (hii * hii); \n\t\t}\n\t\t\n\t\tdouble delta = gtilde.transpose() * hshift * gtilde;\n\t\tdelta = sqrt(delta) - stepsize; \n\t\t\n\t\tfor (int i = 1; i < 9; i++) {\n\t\t\tdouble new_mu = (factor + 0.1) * i * eimin; \n\n\t\t\tfor (int i = 0; i < hshift.rows(); i++) {\n\t\t\t\tdouble hii = hsolve.eigenvalues()[i] - new_mu;\n\t\t\t\thshift(i, i) = 1.0 / (hii * hii); \n\t\t\t}\n\t\t\n\t\t\tdouble new_delta = gtilde.transpose() * hshift * gtilde;\n\t\t\tnew_delta = sqrt(new_delta) - stepsize; \n\t\t\t\n\t\t\tif (fabs(new_delta) < fabs(delta)) {\n\t\t\t\tmu = new_mu;\n\t\t\t\tdelta = new_delta;\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i < hessian.rows(); i++) {\n\t\t\tdouble eival = hsolve.eigenvalues()[i]; \n\t\t\tif (fabs(eival - mu) > 1e-12)\n\t\t\t\tstep[i] = - gtilde[i] / (eival - mu); \n\t\t\telse step[i] = 0.0; \n\t\t}\n\t\t\n\t}\n\t\n\tdx = hsolve.eigenvectors() * step; \n\tdouble expect = -grad.dot(dx) + dx.transpose() * hessian * dx; \n\t\n\treturn expect; \n}\n\nstd::pair<double, double> rfo_prime(Vector& dy, Vector &grad, Matrix& hessian, double alpha) {\n\t\n\tint ndim = hessian.rows();\n\tint eival = 2; \n\t\n\tMatrix augH = Matrix::Zero(ndim+1, ndim+1); \n\taugH.block(0, 0, ndim, ndim) = hessian; \n\taugH.block(ndim, 0, 1, ndim) = -grad.transpose();\n\taugH.block(0, ndim, ndim, 1) = -grad; \n\t\n\tMatrix B = alpha * Matrix::Identity(ndim+1, ndim+1);\n\tB(ndim, ndim) = 1.0; \n\n\tGeneralizedEigenSolver solver(augH, B); \n\tdouble lmin = solver.eigenvalues()[eival]; \n\tVector step = solver.eigenvectors().block(0, eival, ndim, 1);\n\tstd::cout << solver.eigenvectors() << std::endl << std::endl;\n\tdouble vmin = solver.eigenvectors()(ndim, eival); \n\tif (fabs(vmin) > 1e-12)\n\t\tstep /= vmin;\n\t\n\tdouble nu = alpha * lmin; \n\tEigenSolver hsolve(hessian); \n\tconst Matrix& hvec = hsolve.eigenvectors();\n\tconst Vector& heig = hsolve.eigenvalues(); \n\tdouble dyprime2 = 0.0;\n\tdouble dy2 = 0.0; \n\tdouble dotp, denom; \n\tfor (int i = 0; i < hessian.cols(); i++) {\n\t\tdotp = hvec.col(i).dot(grad); \n\t\tdotp *= dotp; \n\t\tdenom = heig[i] - nu; \n\t\tdyprime2 += dotp / (denom * denom * denom);\n\t\tdy2 += dotp / (denom * denom); \n\t}\n\tdouble expect = 1 + alpha * step.dot(step); \n\tdyprime2 *= 2.0 * lmin / expect; \n\texpect *= 0.5 * lmin; \n\tdouble dyprime = 0.5 * dyprime2 / sqrt(dy2); \n\t\n\tdy = step; \n\tstd::pair<double, double> results = {expect, dyprime}; \n\treturn results; \n\t\n}\n\n\n\nvoid RHFOptimiser::optimise() {\n\tLogger& log = mol->control->log;\n\tlog.title(\"GEOMETRY OPTIMIZATION\"); \n\tlog.initIterationOpt();\n\tint MAXITER = cmd.get_option<int>(\"maxiter\");\n\tdouble CONVERGE = cmd.get_option<double>(\"gradconverge\");  \n\t\n\tVector dx = Vector::Zero(3*mol->getNActiveAtoms()); \n\t\n\tbool converged = false;\n\tVector grad;\n\tMatrix hessian; \n\tcalc.iter = 0;\n\tdouble trust = cmd.get_option<double>(\"trust\"); \n\tdouble trust_ratio;\n\tdouble expect = 0.0;\n\tdouble step_norm = 0.0;\n\twhile (!converged && calc.iter < MAXITER) {\n\t\tcalc(dx, grad, hessian); \n\t\tif (calc.iter > 1) {\n\t\t\n\t\t\ttrust_ratio = calc.delta_e / expect; \n\t\t\t\n\t\t\tdouble stepnorm = dx.norm();\n\t\t\tif (trust_ratio > 0.75 && 1.25*stepnorm > trust) trust *= 2.0;\n\t\t\telse if (trust_ratio < 0.25) trust = 0.25*stepnorm; \n\t\t}\n\t\t\n\t\tmol->control->log.optg_dump(calc.iter, grad, dx, mol, \n\t\t\t\t\t\t\t\thessian, trust, calc.delta_e, calc.grad_norm,\n\t\t\t\t\t\t\t\tstep_norm, calc.energy, expect); \n\t\t\n\t\tconverged = (calc.grad_norm < CONVERGE) || (fabs(calc.delta_e) < CONVERGE / 1000.0); \n\t\tif (!converged) {\n\t\t\texpect = trust_newton(dx, grad, hessian, trust); \n\t\t\tstep_norm = dx.norm();\n\t\t}\n\t}\n\t\n\tif (calc.iter < MAXITER) {\n\t\tlog.print(\"Converged geometry:\\n\");\n\t\tfor (int i = 0; i <mol->getNAtoms(); i++) log.print(mol->getAtom(i));\n\t\tlog.result(\"HF Energy\", calc.energy, \"Hartree\");\n\t\t\n\t\tif (cmd.get_option<bool>(\"freq\")) frequencies(hessian); \n\t\t\n\t} else {\n\t\tlog.result(\"Geometry optimisation failed to converge.\");\n\t\tlog.print(\"Last trial geometry\\n\"); \n\t\tfor (int i = 0; i <mol->getNAtoms(); i++) log.print(mol->getAtom(i));\n\t}\n}\n\nvoid RHFOptimiser::frequencies(Matrix& hessian) {\n\t\n\tint natom = hessian.rows(); \n\t\n\t// form mass-weighted hessian\n\tint row = 0; \n\tdouble mi, mj; \n\tMatrix mass_hessian = hessian; \n\t\n\tstd::vector<int> activeAtoms = mol->getActiveList(); \n\tfor (int i : activeAtoms) {\n\t\tmi = mol->getAtom(i).getMass(); \n\t\tmi = sqrt(mi); \n\t\t\n\t\tfor (int xyz = 0; xyz < 3; xyz++) {\n\t\t\t\n\t\t\tint col = 0; \n\t\t\tfor (int j : activeAtoms) {\n\t\t\t\tmj = mol->getAtom(j).getMass();\n\t\t\t\tmj = sqrt(mj); \n\t\t\t\t\n\t\t\t\tfor (int abc = 0; abc < 3; abc++) {\n\t\t\t\t\tmass_hessian(row, col) /= mi * mj; \n\t\t\t\t\tcol++;\t\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\trow++;\n\t\t}\n\t}\n\t\n\tEigenSolver hsolve(mass_hessian); \n\tVector freqs = hsolve.eigenvalues(); \n\tMatrix modes = hsolve.eigenvectors(); \n\t\n\tint nimaginary = 0; \n\tfor (int i = 0; i < hessian.rows(); i++) {\n\t\tif (freqs[i] < -1e-4) {\n\t\t\tfreqs[i] = -sqrt(-freqs[i]); \n\t\t\tnimaginary++; \n\t\t} else if (freqs[i] < 1e-4) {\n\t\t\tfreqs[i] = 0.0; \n\t\t} else freqs[i] = sqrt(freqs[i]); \n\t\tfreqs[i] /= (2.0 * M_PI);  \n\t\tfreqs[i] *= Logger::TOWAVENUMBERS; \n\t}\n\t\n\tmol->control->log.frequencies(freqs, modes, cmd.get_option<bool>(\"modes\"));  \n\t\n}\n\nvoid RHFOptimiser::exponents() { \n\t\n\tint nexp = mol->getBasis().getNExps(); \n\t\n\tLogger& log = mol->control->log;\n\tlog.title(\"EXPONENT OPTIMIZATION\"); \n\tlog.initIterationOpt();\n\tint MAXITER = cmd.get_option<int>(\"maxiter\");\n\tdouble CONVERGE = cmd.get_option<double>(\"gradconverge\"); \n\tbool withmp2 = cmd.get_option<bool>(\"mp2\");  \n\t\n\tstd::string active = cmd.get_option<std::string>(\"active\"); \n\tstd::vector<int> activex;\n\tif (active == \"all\") {\n\t\tfor (int i = 0; i < nexp; i++) activex.push_back(i); \n\t} else {\n\t\tsize_t pos = active.find(',');\n\t\tstd::string token; \n\t\twhile (pos != std::string::npos) {\n\t\t\ttoken = active.substr(0, pos);\n\t\t\tactivex.push_back(std::stoi(token)-1);\n\t\t\tactive.erase(0, pos+1);\n\t\t\tpos = active.find(',');\n\t\t}\n\t\tactivex.push_back(std::stoi(active) - 1);\n\t\t\n\t\tnexp = activex.size(); \n\t}\n\t\n\tint orbital = cmd.get_option<int>(\"orbital\"); \n\tbool momap = cmd.get_option<bool>(\"momap\"); \n\tVector mocoeffs; \n\t\n\tbool converged = false;\n\tMatrix xhessian;\n\tVector xgrad; \n\tVector dxx = Vector::Zero(nexp); \n\tint iter = 0;\n\tdouble trust = cmd.get_option<double>(\"trust\"); \n\tdouble trust_ratio, delta_e, grad_norm;\n\tdouble energy = 0.0;\n\tdouble expect = 0.0; \n\tdouble step_norm = 0.0;  \n\twhile (!converged && iter < MAXITER) {\n\t\t\n\t\tIntegralEngine ints(mol, false);\n\t\tFock f(cmd, ints, mol);\n\t\tSCF hf(cmd, mol, f); \n\t\thf.rhf(false); \n\t\tdelta_e = hf.getEnergy() - energy;\n\t\tenergy = hf.getEnergy();\n\t\t\n\t\tif (withmp2) {\n\t\t\tMP2 mp2obj(f);\n\t\t\tmp2obj.tensormp2(false);\n\t\t\tenergy += mp2obj.getEnergy();\n\t\t\tdelta_e += mp2obj.getEnergy(); \n\t\t}\n\t\t \n\t\txgrad = f.compute_xgrad(energy, xhessian, activex, cmd); \n\t\tgrad_norm = xgrad.norm();\n\t\tif (momap) \n\t\t\tmocoeffs = f.getCP().col(orbital); \n\t\t\n\t\tif (iter > 1) {\n\t\t\n\t\t\ttrust_ratio = delta_e / expect; \n\t\t\t\n\t\t\tstep_norm = dxx.norm();\n\t\t\tif (trust_ratio > 0.75 && 1.25*step_norm > trust) trust *= 2.0;\n\t\t\telse if (trust_ratio < 0.25) trust = 0.25*step_norm; \n\t\t}\n\t\t\n\t\tmol->control->log.optx_dump(iter++, xgrad, dxx, mol, \n\t\t\t\t\t\t\t\txhessian, trust, delta_e, grad_norm,\n\t\t\t\t\t\t\t\tstep_norm, energy, expect, activex); \n\t\t\n\t\tconverged = (grad_norm < CONVERGE) || (fabs(delta_e) < CONVERGE / 1000.0);  \n\t\tif (!converged) {\n\t\t\texpect = trust_newton(dxx, xgrad, xhessian, trust); \n\t\t\t\n\t\t\tdouble currexp, newexp;\n\t\t\tint ctr = 0;\n\t\t\tfor (int i : activex) {\n\t\t\t\tcurrexp = mol->getBasis().getExp(i); \n\t\t\t\tnewexp = currexp + dxx[ctr++]; \n\t\t\t\tnewexp = newexp <= 0.0 ? currexp / 10.0 : newexp; \n\t\t\t\tmol->getBasis().setExp(i, newexp);  \n\t\t\t}\n\t\t}\n\t\t\t\n\t}\n\t\n\tif (calc.iter < MAXITER) {\n\t\tlog.print(\"Converged exponents:\\n\");\n\t\t\n\t\tfor (int i : activex)\n\t\t\tlog.print(std::to_string(i) + \": \" + std::to_string(mol->getBasis().getExp(i))); \n\t\t\n\t\tlog.result(\"HF Energy\", energy, \"Hartree\");\n\t\t\n\t\tif (momap) {\n\t\t\tstd::string mapfile = cmd.get_option<std::string>(\"mapfile\");\n\t\t\tlog.mo_map(mocoeffs, mol, cmd.get_option<int>(\"fineness\"), mapfile);\n\t\t} \n\t\t\n\t} else {\n\t\tlog.result(\"Exponent optimisation failed to converge.\");\n\t\tlog.print(\"Last trial exponents\\n\"); \n\t\t\n\t\tfor (int i : activex)\n\t\t\tlog.print(std::to_string(i) + \": \" + std::to_string(mol->getBasis().getExp(i)));\n\t}\n\n}\n\ndouble RHFCalculator::operator()(const Vector& dx, Vector& grad, Matrix& hessian) {\n\t\t\n\tint offset = 0;\n\tint natoms = mol->getNAtoms();\n\t\n\tstd::vector<int> activeAtoms = mol->getActiveList(); \n\tfor (int i : activeAtoms) {\n\t\tAtom& a = mol->getAtom(i); \n\t\ta.translate(dx[offset], dx[offset+1], dx[offset+2]); \n\t\toffset += 3; \n\t}\n\tmol->updateBasisPositions(); \n\tmol->calcEnuc(); \n\t\t\n\tIntegralEngine ints(mol, false);\n\tFock f(cmd, ints, mol);\n\tSCF hf(cmd, mol, f); \n\thf.rhf(false); \n\tenergy = hf.getEnergy();\n\t\t\n\tstd::vector<Atom> atomlist; \n\tfor (int i = 0; i < natoms; i++) atomlist.push_back(mol->getAtom(i));\n\t\n\t//f.compute_forces(atomlist, mol->getNel()/2);\n\tf.compute_hessian(atomlist, mol->getNel()/2); \n\tMatrix g = f.getForces().transpose(); \n\tVector full_grad = Eigen::Map<Vector>(g.data(), g.cols()*g.rows());\n\t\n\t//f.compute_hessian_numeric(atomlist, mol->getNel()/2, cmd); \n\tif (natoms == activeAtoms.size()) {\n\t\thessian = f.getHessian(); \n\t\tgrad = full_grad; \n\t} else {\n\t\tMatrix& full_hessian = f.getHessian(); \n\n\t\t// Restrict to only active atoms\n\t\tint nactive = activeAtoms.size(); \n\t\tgrad = Vector::Zero(3*nactive);\n\t\tMatrix temphessian = Matrix::Zero(3*nactive, 3*natoms);\n\t\tint row = 0; \n\t\tfor (int i : activeAtoms) {\n\t\t\tgrad.segment(row, 3) = full_grad.segment(3*i, 3); \n\t\t\ttemphessian.block(row, 0, 3, 3*natoms) = full_hessian.block(3*i, 0, 3, 3*natoms); \n\t\t\trow += 3; \n\t\t}\n\t\n\t\trow = 0; \n\t\thessian = Matrix::Zero(3*nactive, 3*nactive); \n\t\tfor (int j : activeAtoms) {\n\t\t\thessian.block(0, row, 3*nactive, 3) = temphessian.block(0, 3*j, 3*nactive, 3); \n\t\t\trow += 3; \n\t\t}\n\t\n\t}\n\t\n\tdelta_e = energy - old_e; \n\tgrad_norm = grad.norm(); \n\told_e = energy; \n\titer++;\n\t\n\treturn energy; \n\t\n}\n", "meta": {"hexsha": "0593ac3950ffc2cbd1ac1f2d7d891e61700ce3f7", "size": 11783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/optimiser.cpp", "max_stars_repo_name": "robashaw/gamma", "max_stars_repo_head_hexsha": "26fba31be640c9bc429f8c22d5c61c0f8e9215e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-09-13T10:35:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:20:54.000Z", "max_issues_repo_path": "src/optimiser.cpp", "max_issues_repo_name": "robashaw/gamma", "max_issues_repo_head_hexsha": "26fba31be640c9bc429f8c22d5c61c0f8e9215e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/optimiser.cpp", "max_forks_repo_name": "robashaw/gamma", "max_forks_repo_head_hexsha": "26fba31be640c9bc429f8c22d5c61c0f8e9215e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.2427616927, "max_line_length": 94, "alphanum_fraction": 0.6132563863, "num_tokens": 4019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5544704649604274, "lm_q1q2_score": 0.4104048226715611}}
{"text": "// Copyright (c) Prevail Verifier contributors.\n// SPDX-License-Identifier: MIT\n#pragma once\n\n#include <climits>\n#include <iostream>\n#include <sstream>\n#include <string>\n\n#include <boost/functional/hash.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <utility>\n\n#include \"debug.hpp\"\nusing boost::multiprecision::cpp_int;\n\nnamespace crab {\n\nclass z_number final {\n  private:\n    cpp_int _n{nullptr};\n\n  public:\n    z_number() = default;\n    explicit z_number(cpp_int n) : _n(std::move(n)) {}\n    explicit z_number(const std::string& s) { _n = cpp_int(s); }\n\n    z_number(signed long long int n) { _n = n; }\n    z_number(unsigned long long int n) { _n = n; }\n    z_number(int n) { _n = n; }\n    z_number(unsigned int n) { _n = n; }\n    z_number(long n) { _n = n; }\n\n    // overloaded typecast operators\n    explicit operator long() const {\n        if (!fits_slong()) {\n            CRAB_ERROR(\"z_number \", _n.str(), \" does not fit into a signed long integer\");\n        } else {\n            return (long)_n;\n        }\n    }\n\n    explicit operator int() const {\n        if (!fits_sint()) {\n            CRAB_ERROR(\"z_number \", _n.str(), \" does not fit into a signed integer\");\n        } else {\n            return (int)_n;\n        }\n    }\n\n    explicit operator cpp_int() const { return _n; }\n\n    [[nodiscard]] std::size_t hash() const {\n        boost::hash<std::string> hasher;\n        return hasher(_n.str());\n    }\n\n    [[nodiscard]] bool fits_sint() const {\n        return ((_n >= INT_MIN) && (_n <= INT_MAX));\n    }\n\n    [[nodiscard]] bool fits_slong() const {\n        return ((_n >= LONG_MIN) && (_n <= LONG_MAX));\n    }\n\n    z_number operator+(const z_number& x) const {\n        return z_number(_n + x._n);\n    }\n\n    z_number operator+(int x) const { return operator+(z_number(x)); }\n\n    z_number operator*(const z_number& x) const { return z_number(_n * x._n); }\n\n    z_number operator*(int x) const { return operator*(z_number(x)); }\n\n    z_number operator-(const z_number& x) const { return z_number(_n - x._n); }\n\n    z_number operator-(int x) const { return operator-(z_number(x)); }\n\n    z_number operator-() const { return z_number(-_n); }\n\n    z_number operator/(const z_number& x) const {\n        if (x._n.is_zero()) {\n            CRAB_ERROR(\"z_number: division by zero [1]\");\n        } else {\n            return z_number(_n / x._n);\n        }\n    }\n\n    z_number operator/(int x) const { return operator/(z_number(x)); }\n\n    z_number operator%(const z_number& x) const {\n        if (x._n.is_zero()) {\n            CRAB_ERROR(\"z_number: division by zero [2]\");\n        } else {\n            return z_number(_n % x._n);\n        }\n    }\n\n    z_number operator%(int x) const { return operator%(z_number(x)); }\n\n    z_number& operator+=(const z_number& x) {\n        _n += x._n;\n        return *this;\n    }\n\n    z_number& operator+=(int x) { return operator+=(z_number(x)); }\n\n    z_number& operator*=(const z_number& x) {\n        _n *= x._n;\n        return *this;\n    }\n\n    z_number& operator*=(int x) { return operator*=(z_number(x)); }\n\n    z_number& operator-=(const z_number& x) {\n        _n -= x._n;\n        return *this;\n    }\n\n    z_number& operator-=(int x) { return operator-=(z_number(x)); }\n\n    z_number& operator/=(const z_number& x) {\n        if (x._n.is_zero()) {\n            CRAB_ERROR(\"z_number: division by zero [3]\");\n        } else {\n            _n /= x._n;\n            return *this;\n        }\n    }\n\n    z_number& operator/=(int x) { return operator/=(z_number(x)); }\n\n    z_number& operator%=(const z_number& x) {\n        if (x._n.is_zero()) {\n            CRAB_ERROR(\"z_number: division by zero [4]\");\n        } else {\n            _n %= x._n;\n            return *this;\n        }\n    }\n\n    z_number& operator%=(int x) { return operator%=(z_number(x)); }\n\n    z_number& operator--() & {\n        _n--;\n        return *this;\n    }\n\n    z_number& operator++() & {\n        _n++;\n        return *this;\n    }\n\n    z_number operator++(int) & {\n        z_number r(*this);\n        ++(*this);\n        return r;\n    }\n\n    z_number operator--(int) & {\n        z_number r(*this);\n        --(*this);\n        return r;\n    }\n\n    bool operator==(const z_number& x) const {\n        return (_n == x._n);\n    }\n\n    bool operator==(int x) const { return operator==(z_number(x)); }\n\n    bool operator!=(const z_number& x) const { return (_n != x._n); }\n\n    bool operator!=(int x) const { return operator!=(z_number(x)); }\n\n    bool operator<(const z_number& x) const { return (_n < x._n); }\n\n    bool operator<(int x) const { return operator<(z_number(x)); }\n\n    bool operator<=(const z_number& x) const { return (_n <= x._n); }\n\n    bool operator<=(int x) const { return operator<=(z_number(x)); }\n\n    bool operator>(const z_number& x) const { return (_n > x._n); }\n\n    bool operator>(int x) const { return operator>(z_number(x)); }\n\n    bool operator>=(const z_number& x) const { return (_n >= x._n); }\n\n    bool operator>=(int x) const { return operator>=(z_number(x)); }\n\n    z_number operator&(const z_number& x) const { return z_number(_n & x._n); }\n\n    z_number operator&(int x) const { return z_number(_n & x); }\n\n    z_number operator|(const z_number& x) const { return z_number(_n | x._n); }\n\n    z_number operator|(int x) const { return z_number(_n | x); }\n\n    z_number operator^(const z_number& x) const { return z_number(_n ^ x._n); }\n\n    z_number operator^(int x) const { return z_number(_n ^ x); }\n\n    z_number operator<<(z_number x) const {\n        if (!x.fits_sint()) {\n            CRAB_ERROR(\"z_number \", x._n.str(), \" does not fit into an int\");\n        }\n        return z_number(_n << (int)x);\n    }\n\n    z_number operator<<(int x) const { return z_number(_n << x); }\n\n    z_number operator>>(z_number x) const {\n        if (!x.fits_sint()) {\n            CRAB_ERROR(\"z_number \", x._n.str(), \" does not fit into an int\");\n        }\n        return z_number(_n >> (int)x);\n    }\n\n    z_number operator>>(int x) const { return z_number(_n >> x); }\n\n    [[nodiscard]] z_number fill_ones() const {\n        if (_n.is_zero()) {\n            return z_number((signed long long)0);\n        }\n\n        z_number result;\n        for (result = 1; result < *this; result = result * 2 + 1)\n            ;\n        return result;\n    }\n\n    friend std::ostream& operator<<(std::ostream& o, const z_number& z) {\n        return o << z._n.str();\n    }\n\n}; // class z_number\n\nusing number_t = z_number;\n\ninline std::size_t hash_value(const z_number& z) { return z.hash(); }\n\n} // namespace crab\n", "meta": {"hexsha": "371356588078d49b7e1925916c103dc64e47ddfa", "size": 6519, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/crab_utils/bignums_boost.hpp", "max_stars_repo_name": "poornagmsft/ebpf-verifier", "max_stars_repo_head_hexsha": "fe3449e0c1cb379e6886d24ae84a20131ba91d5e", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/crab_utils/bignums_boost.hpp", "max_issues_repo_name": "poornagmsft/ebpf-verifier", "max_issues_repo_head_hexsha": "fe3449e0c1cb379e6886d24ae84a20131ba91d5e", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/crab_utils/bignums_boost.hpp", "max_forks_repo_name": "poornagmsft/ebpf-verifier", "max_forks_repo_head_hexsha": "fe3449e0c1cb379e6886d24ae84a20131ba91d5e", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6081632653, "max_line_length": 90, "alphanum_fraction": 0.5635833717, "num_tokens": 1764, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4104048163156974}}
{"text": "/*\n *  ft_calib.cpp\n *\n *  Modified By Chuan QIN, July 2019\n * \tLogs: \n * \t\t* Remove the require for IMU sensor, the TF of manipulator is used instead.\n *    * The base frame's inclination to ground is not required, only the local gravity acceleration is required (usually 9.81)\n *    * In order to accelerate the calibration SVD process, the force and torque are calibrated separately\n * \n * \n * \tOriginal file infomation:\n *  Created on: Sep 26, 2012\n *  Authors:   Francisco Viña\n *            fevb <at> kth.se\n */\n\n/* Copyright (c) 2012, Francisco Viña, CVAP, KTH\n   All rights reserved.\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are met:\n      * Redistributions of source code must retain the above copyright\n        notice, this list of conditions and the following disclaimer.\n      * Redistributions in binary form must reproduce the above copyright\n        notice, this list of conditions and the following disclaimer in the\n        documentation and/or other materials provided with the distribution.\n      * Neither the name of KTH nor the\n        names of its contributors may be used to endorse or promote products\n        derived from this software without specific prior written permission.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n   DISCLAIMED. IN NO EVENT SHALL KTH BE LIABLE FOR ANY\n   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include <ros/ros.h>\n#include <force_torque_sensor_calib/ft_calib.h>\n#include <Eigen/Dense>\n#include \"tf2_eigen/tf2_eigen.h\"\n\nnamespace Calibration{\n\nFTCalib::FTCalib(double m_local_gravitational_acceleration):m_local_gravitational_acceleration(m_local_gravitational_acceleration)\n{\n\tm_num_meas = 0;\n}\n\nFTCalib::~FTCalib(){\n\n}\n\nvoid FTCalib::addMeasurement(const geometry_msgs::TransformStamped &tf_sensor_to_base,\n\t\tconst geometry_msgs::WrenchStamped &ft_raw)\n{\n\tif(tf_sensor_to_base.header.frame_id != ft_raw.header.frame_id)\n\t{\n\t\tROS_ERROR(\"TF's source frame (%s) is not the same as the ft raw expressed frame (%s)!\",\n\t\t\t\ttf_sensor_to_base.header.frame_id.c_str(), ft_raw.header.frame_id.c_str());\n\t\treturn;\n\t}\n\n\tm_num_meas++;\n\n\tEigen::Matrix<double, 3,6> A_force = getForceMeasurementMatrix(tf_sensor_to_base);\n\tEigen::Matrix<double, 3,6> A_biased_torque = getBiasedTorqueMeasurementMatrix(ft_raw);\n\t\n\tEigen::Vector3d measured_force, measured_torque;\n\tmeasured_force(0) = ft_raw.wrench.force.x;\n\tmeasured_force(1) = ft_raw.wrench.force.y;\n\tmeasured_force(2) = ft_raw.wrench.force.z;\n\n\tmeasured_torque(0) = ft_raw.wrench.torque.x;\n\tmeasured_torque(1) = ft_raw.wrench.torque.y;\n\tmeasured_torque(2) = ft_raw.wrench.torque.z;\n\n\tif(m_num_meas==1)\n\t{\n\t\tstacked_A_force = A_force;\n\t\tstacked_A_biased_torque = A_biased_torque;\n\t\tstacked_measured_force = measured_force;\n\t\tstacked_measured_torque = measured_torque;\n\t}\n\n\telse\n\t{\n\t\tEigen::MatrixXd stacked_A_force_tmp = stacked_A_force;\n\t\tEigen::MatrixXd stacked_A_biased_torque_tmp = stacked_A_biased_torque;\n\t\t\n\t\tEigen::VectorXd stacked_measured_force_tmp = stacked_measured_force;\n\t\tEigen::VectorXd stacked_measured_torque_tmp = stacked_measured_torque;\n\n\t\tstacked_A_force.resize(m_num_meas*3, 6);\n\t\tstacked_A_biased_torque.resize(m_num_meas*3, 6);\n\n\t\tstacked_measured_force.resize(m_num_meas*3);\n\t\tstacked_measured_torque.resize(m_num_meas*3);\n\n\t\tstacked_A_force.topRows((m_num_meas-1)*3) = stacked_A_force_tmp;\n\t\tstacked_A_biased_torque.topRows((m_num_meas-1)*3) = stacked_A_biased_torque_tmp;\n\t\tstacked_measured_force.topRows((m_num_meas-1)*3) = stacked_measured_force_tmp;\n\t\tstacked_measured_torque.topRows((m_num_meas-1)*3) = stacked_measured_torque_tmp;\n\t\t\n\n\t\tstacked_A_force.bottomRows(3) = A_force;\n\t\tstacked_A_biased_torque.bottomRows(3) = A_biased_torque;\n\t\tstacked_measured_force.bottomRows(3) = measured_force;\n\t\tstacked_measured_torque.bottomRows(3) = measured_torque;\n\t}\n\n\n}\nEigen::Matrix<double, 3,6> FTCalib::getForceMeasurementMatrix(const geometry_msgs::TransformStamped &tf_sensor_to_base){\n\tEigen::Matrix<double, 3, 6> A_force; // the force measurement matrix\n\t// [fx, fy, fz]^t = A_force * [g_x_in_base * m, g_y_in_base * m, g_z_in_base * m, f_bias_x, f_bias_y, f_bias_z]^t\n\n\tEigen::Matrix3d R_sensor_to_base; // rotation from sensor frame to base frame\n\n\t// translate from geometry_msgs::TransformStamped to eigen matrix\n\tEigen::Quaternion<double> q;\n\tEigen::fromMsg(tf_sensor_to_base.transform.rotation, q);\n\tq.normalize();\n\tR_sensor_to_base = q.toRotationMatrix();\n\n\tA_force.block<3,3>(0,0) = R_sensor_to_base;\n\tA_force.block<3,3>(0,3).setIdentity();\n\treturn A_force;\n}\n\nEigen::Matrix<double, 3, 6> FTCalib::getBiasedTorqueMeasurementMatrix(const geometry_msgs::WrenchStamped &ft_raw){\n\tEigen::Matrix<double, 3, 6> A_torque_biased; // the torque measurement matrix, which is biased because the force measurement is not unbiased\n\t// [tx, ty, tz]^t = A_torque * [x_center, y_center, z_center, t_bias_x, t_bias_y, t_bias_z]\n\tgeometry_msgs::Vector3 force = ft_raw.wrench.force;\n\tA_torque_biased << \t\t\t0,\t force.z,\t force.y,\t 1,\t 0,\t 0,\n\t\t\t\t\t\t force.z, \t\t\t\t\t0,   force.x,\t 0,\t 1,\t 0,\n\t\t\t\t\t\t force.y, \t force.x,\t\t\t\t\t0,\t 0,\t 0,\t 1;\n\treturn A_torque_biased;\n}\n\n// Least squares to estimate the FT sensor parameters\nEigen::VectorXd FTCalib::getCalib()\n{\n\tEigen::VectorXd force_calib_params(6); //[g_x_in_base * mass, g_y_in_base * mass, g_z_in_base * mass, f_bias_x, f_bias_y, f_bias_z]\n\n\tforce_calib_params = stacked_A_force.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(stacked_measured_force);\n\n\tEigen::MatrixXd unbiased_stacked_A_torque = stacked_A_biased_torque;\n\tEigen::Matrix<double,3,6> bias_matrix; \n\tEigen::Vector3d force_bias = force_calib_params.segment<3>(3);\n\tbias_matrix << \t\t\t\t\t\t0,\tforce_bias(2),\tforce_bias(1),\t0,\t0,\t0,\n\t\t\t\t\t\t\t\tforce_bias(2),\t\t\t\t\t\t\t0,\tforce_bias(0),\t0,\t0,\t0,\n\t\t\t\t\t\t\t\tforce_bias(1), \tforce_bias(0), \t\t\t\t\t\t\t0,\t0,\t0,\t0;\n\n\tfor(int i=0; i<m_num_meas; i++){\n\t\tunbiased_stacked_A_torque.block<3,6>(i*3,0) -= bias_matrix;\n\t}\n\n\tEigen::VectorXd torque_calib_params(6); //[x_center_in_sensor_frame, y_center_in_sensor_frame, z_center_in_sensor_frame, t_bias_x, t_bias_y, t_bias_z] \n\ttorque_calib_params = unbiased_stacked_A_torque.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(stacked_measured_torque);\n\n\t// ft_calib_params: [mass, \n\t//\t\t\t\t\t\t\t\t\t g_x_in_base, g_y_in_base, g_z_in_base,\n\t//\t\t\t\t\t\t\t\t\t x_center_in_sensor_frame, y_center_in_sensor_frame, z_center_in_sensor_frame, \n\t//\t\t\t\t\t\t\t\t\t f_bias_x, f_bias_y, f_bias_z, \n\t//\t\t\t\t\t\t\t\t\t t_bias_x, t_bias_y, t_bias_z]\n\tEigen::VectorXd ft_calib_params;\n\tft_calib_params.resize(13);\n\tft_calib_params(0) = force_calib_params.head<3>().norm() / m_local_gravitational_acceleration; //mass\n\tft_calib_params(1) = force_calib_params(0) / ft_calib_params(0); //g_x_in_base\n\tft_calib_params(2) = force_calib_params(1) / ft_calib_params(0); //g_y_in_base\n\tft_calib_params(3) = force_calib_params(2) / ft_calib_params(0); //g_z_in_base\n\n\tft_calib_params(4) = torque_calib_params(0); //x_center_in_sensor_frame\n\tft_calib_params(5) = torque_calib_params(1); //y_center_in_sensor_frame\n\tft_calib_params(6) = torque_calib_params(2); //z_center_in_sensor_frame\n\n\tft_calib_params(7) = force_calib_params(3); // f_bias_x\n\tft_calib_params(8) = force_calib_params(4); // f_bias_y\n\tft_calib_params(9) = force_calib_params(5); // f_bias_z\n\n\tft_calib_params(10) = torque_calib_params(3); //t_bias_x\n\tft_calib_params(11) = torque_calib_params(4); //t_bias_y\n\tft_calib_params(12) = torque_calib_params(5); //t_bias_z\n\t \n\treturn ft_calib_params;\n}\n\n\n\n}\n", "meta": {"hexsha": "01f90d511e7ac854a3b304a22d85b870a99c184d", "size": 8146, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "force_torque_sensor_calib/src/ft_calib.cpp", "max_stars_repo_name": "GITAI/force_torque_tools", "max_stars_repo_head_hexsha": "c5e2fd1e466cb718833f27d583bd91e4068d7da9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "force_torque_sensor_calib/src/ft_calib.cpp", "max_issues_repo_name": "GITAI/force_torque_tools", "max_issues_repo_head_hexsha": "c5e2fd1e466cb718833f27d583bd91e4068d7da9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "force_torque_sensor_calib/src/ft_calib.cpp", "max_forks_repo_name": "GITAI/force_torque_tools", "max_forks_repo_head_hexsha": "c5e2fd1e466cb718833f27d583bd91e4068d7da9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3502538071, "max_line_length": 152, "alphanum_fraction": 0.7548490056, "num_tokens": 2338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743505760727, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.41040481631569736}}
{"text": "#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET\r\n#define EIGEN_SUPERLU_SUPPORT\r\n\r\n\r\n#include \"Debug.h\"\r\n#include \"SolverEigen.h\"\r\n#include \"SolverPetsc.h\"\r\n#include \"SolverTime.h\"\r\n#include \"ComputerTime.h\"\r\n#include \"util.h\"\r\n\r\n//#include <Eigen/SuperLUSupport>\r\n#include <Eigen/SparseExtra>\r\n#include <Eigen/IterativeSolvers>\r\n\r\n\r\n\r\nextern SolverTime      solverTime;\r\nextern ComputerTime    computerTime;\r\n\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n\r\n\r\nSolverEigen::SolverEigen()\r\n{\r\n  STABILISED = false;\r\n  \r\n  update_precond = 1;\r\n\r\n  if (debug) cout << \" SolverEigen constructor\\n\\n\";\r\n}\r\n\r\n\r\nSolverEigen::~SolverEigen()\r\n{\r\n  if (debug)  cout << \" SolverEigen destructor\\n\\n\";\r\n\r\n  free();\r\n}\r\n\r\n\r\nint SolverEigen::initialise(int p1, int p2, int p3)\r\n{\r\n   nRow = nCol = p3;\r\n\r\n   soln.resize(nRow);\r\n   soln.setZero();\r\n\r\n   rhsVec   = soln;\r\n   solnPrev = soln;\r\n\r\n  return 0;\r\n}\r\n\r\n\r\nint SolverEigen::setSolverAndParameters()\r\n{\r\n    ///////////////////////\r\n    // Create the linear solver and set various options\r\n    ///////////////////////\r\n\r\n\r\n    ///////////////////////\r\n    //Set operators. Here the matrix that defines the linear system\r\n    //also serves as the preconditioning matrix.\r\n    ///////////////////////\r\n\r\n    return 0;\r\n}\r\n\r\n\r\nvoid SolverEigen::zeroMtx()\r\n{\r\n  //cout << \" nRow = \" << nRow << endl;\r\n  //printVector(rhsVec);\r\n\r\n  //cout << \" nRow = \" << nRow << endl;\r\n  //cout << mtx << endl;\r\n  //mtx.setZero();\r\n  mtx *= 0.0;\r\n  rhsVec.setZero();\r\n  //cout << \" nRow = \" << nRow << endl;\r\n\r\n  return;\r\n}\r\n\r\n\r\n\r\nint SolverEigen::free()\r\n{\r\n  return 0;\r\n}\r\n\r\n\r\nvoid SolverEigen::printInfo()\r\n{\r\n  //cout << \"Eigen solver:  nRow = \" << nRow << \"\\n\";\r\n  //cout << \"               nnz  = \" <<  << \"\\n\\n\"; \r\n  //printVector(rhsVec);\r\n  //rhsVec.setZero();\r\n  //cout << \" nRow = \" << nRow << endl;\r\n  //cout << mtx << endl;\r\n\r\n  return;\r\n}\r\n\r\n\r\nvoid SolverEigen::printMatrixPatternToFile()\r\n{\r\n    /*\r\n    ofstream fout(\"matrix-pattern2.dat\");\r\n\r\n    if(fout.fail())\r\n    {\r\n      cout << \" Could not open the Output file\" << endl;\r\n      exit(1);\r\n    }\r\n\r\n    fout << totalDOF << setw(10) << totalDOF << endl;\r\n\r\n    for(int k=0; k<mtx.outerSize(); ++k)\r\n    for(SparseMatrixXd::InnerIterator it(mtx,k); it; ++it)\r\n      printf(\"%9d \\t %9d \\n\", it.row(), it.col());\r\n\r\n    //for(int ii=0;ii<nRow;ii++)\r\n      //for(int jj=0;jj<nRow;jj++)\r\n        //printf(\"%5d \\t %5d \\t %12.6f \\n\",mtx.coeffRef(ii,jj));\r\n\r\n    fout.close();\r\n    */\r\n\r\n   FILE * pFile;\r\n   int n;\r\n   char name [100];\r\n\r\n   cout << mtx.nonZeros() << endl;\r\n   //pFile = fopen (\"Stokes.dat\",\"w\");\r\n   pFile = fopen (\"Poisson.dat\",\"w\");\r\n\r\n    fprintf(pFile, \"%9d \\t %9d \\t %9d \\n\", nRow, nCol, 0 );\r\n\r\n    for(int k=0; k<mtx.outerSize(); ++k)\r\n    for(SparseMatrixXd::InnerIterator it(mtx,k); it; ++it)\r\n      fprintf(pFile, \"%9d \\t %9d \\t %20.16f \\n\", it.row(), it.col(), it.value());\r\n\r\n   fclose (pFile);\r\n\r\n   pFile = fopen (\"rhsVec.dat\",\"w\");\r\n\r\n    for(int k=0; k<nRow; ++k)\r\n      fprintf(pFile, \"%9d \\t %14.8f \\n\", k, rhsVec(k));\r\n\r\n   fclose (pFile);\r\n\r\n   pFile = fopen (\"refsoln.dat\",\"w\");\r\n\r\n    for(int k=0; k<nRow; ++k)\r\n      fprintf(pFile, \"%9d \\t %14.8f \\n\", k, soln(k));\r\n\r\n   fclose (pFile);\r\n  return;\r\n}\r\n\r\n  \r\n\r\nvoid SolverEigen::printMatrix(int dig, int dig2, bool gfrmt, int indent, bool interactive)\r\n{\r\n  printInfo();\r\n  \r\n  cout << mtx << endl;\r\n  printf(\"\\n\\n\");\r\n\r\n  return;\r\n}\r\n\r\ndouble SolverEigen::giveMatrixCoefficient(int row, int col)\r\n{ \r\n  return  mtx.coeff(row,col);\r\n}\r\n\r\n\r\n\r\nint SolverEigen::factorise()\r\n{\r\n  char fct[] = \"SolverEigen::factorise\";\r\n\r\n  if (currentStatus != ASSEMBLY_OK) { prgWarning(1,fct,\"assemble matrix first!\"); return 1; }\r\n\r\n  if (checkIO)\r\n  {\r\n    // search for \"nan\" entries in matrix coefficients\r\n\r\n    //if (prgNAN(mtx.x.x,NE)) prgError(1,fct,\"nan matrix coefficient!\");\r\n  }\r\n\r\n  computerTime.go(fct);\r\n\r\n  currentStatus = FACTORISE_OK;\r\n  \r\n  solverTime.total     -= solverTime.factorise;\r\n  solverTime.factorise += computerTime.stop(fct);\r\n  solverTime.total     += solverTime.factorise;\r\n\r\n  return 0;\r\n}\r\n\r\n\r\nint  SolverEigen::solve()\r\n{\r\n  char fct[] = \"SolverEigen::solve\";\r\n\r\n  time_t tstart, tend;\r\n\r\n  if (currentStatus != FACTORISE_OK) { prgWarning(1,fct,\"factorise matrix first!\"); return 1; }\r\n  \r\n\r\n  //algoType = 1;\r\n  \r\n  //cout << mtx << endl;\r\n\r\n//#ifdef EIGEN_PARALLELIZE\r\n//#ifdef EIGEN_HAS_OPENMP\r\n//printf(\"Eigen parallellize is on \\n\");\r\n//#else\r\n//printf(\"Eigen parallellize is off \\n\");\r\n//#endif\r\n  \r\n  if(algoType == 1)\r\n  {\r\n    //cout << \" Solving with Eigen::SimplicialLDLT \" << endl;\r\n\r\n    SimplicialLDLT<SparseMatrix<double> > solver;\r\n\r\n    //SuperLU<SparseMatrixXd > solver;\r\n    tstart = time(0);\r\n  \r\n    solver.compute(mtx);\r\n\r\n    soln = solver.solve(rhsVec);\r\n\r\n    //printVector(soln);\r\n    //\r\n    //computeConditionNumber();\r\n\r\n    //VectorXd x0 = VectorXd::LinSpaced(nRow, 0.0, 1.0);\r\n\r\n    //double  cond = myCondNum(mtx, x0, 50, solver);\r\n\r\n    //printf(\"\\n Matrix condition number = %12.6E \\n\\n\\n\", cond);\r\n\r\n    //soln = solver.solveWithGuess(rhsVec, soln);\r\n    //cout << solver.info() << '\\t' << solver.error() << '\\t' << solver.iterations() << endl;\r\n    tend = time(0);\r\n    //printf(\"It took %8.4f second(s) \\n \", difftime(tend, tstart) );\r\n  }\r\n \r\n  if( algoType == 2 )\r\n  {\r\n    cout << \" Solving with Eigen::BiCGSTAB \" << endl;\r\n\r\n    BiCGSTAB<SparseMatrixXd, IncompleteLUT<double> > solver;\r\n\r\n    solver.preconditioner().setDroptol(1.0e-3);\r\n    solver.preconditioner().setFillfactor(3);\r\n    \r\n    //BiCGSTAB<SparseMatrixXd> solver;\r\n\r\n    //GMRES<SparseMatrixXd, IncompleteLUT<double> > solver;\r\n\r\n    //GMRES<SparseMatrixXd> solver;\r\n\r\n    //ConjugateGradient<SparseMatrixXd, Lower, IncompleteLUT<double> >   solver;\r\n\r\n    \r\n    //solver.set_restart(100);\r\n    //solver.setEigenv(10);\r\n\r\n    solver.setMaxIterations(2000);\r\n    solver.setTolerance(1.0e-10);\r\n\r\n    tstart = time(0);\r\n  \r\n    //cout << \" iiiiiiiiiiiiiii \" << endl;\r\n    solver.compute(mtx);\r\n    //cout << \" iiiiiiiiiiiiiii \" << endl;\r\n \r\n    soln = solver.solve(rhsVec);\r\n  \r\n    //printf(\"\\n\\n\");\r\n    //printVector(soln);\r\n\r\n    //soln = solver.solveWithGuess(rhsVec, soln);\r\n\r\n    tend = time(0); \r\n    printf(\"It took %8.4f second(s) \\n \", difftime(tend, tstart) );\r\n\r\n    cout << solver.info() << '\\t' << solver.error() << '\\t' << solver.iterations() << endl;\r\n  }\r\n\r\n  solnPrev = soln;\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\nint SolverEigen::factoriseAndSolve()\r\n{\r\n  if(currentStatus != ASSEMBLY_OK)\r\n  {\r\n    cerr << \" assemble matrix first! \" << endl;\r\n    return 1;\r\n  }\r\n  \r\n  factorise();\r\n\r\n  return solve();\r\n}\r\n\r\n\r\n\r\nint SolverEigen::assembleMatrixAndVector(vector<int>& row, vector<int>& col, MatrixXd& Klocal, VectorXd& Flocal)\r\n{\r\n  int ii, jj;\r\n  for(ii=0;ii<row.size();ii++)\r\n  {\r\n    rhsVec[row[ii]] += Flocal(ii);\r\n    for(jj=0;jj<col.size();jj++)\r\n    {\r\n      mtx.coeffRef(row[ii], col[jj]) += Klocal(ii,jj);\r\n    }\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\n\r\nint SolverEigen::assembleMatrixAndVector(int start, int c1, vector<int>& vec1, vector<int>& vec2, MatrixXd& Klocal, VectorXd& Flocal)\r\n{\r\n  // subroutine for mixed formulation\r\n  // vec1 - for variable 'u'\r\n  // vec2 - for variable 'p'\r\n\r\n  int ii, jj, aa, bb, size1, size2;\r\n\r\n  //printVector(vec1);\r\n  //printVector(vec2);\r\n  \r\n  size1 = vec1.size();\r\n  size2 = vec2.size();\r\n\r\n  for(ii=0;ii<size1;ii++)\r\n  {\r\n    rhsVec[vec1[ii]] += Flocal(ii);\r\n    for(jj=0;jj<size1;jj++)\r\n       mtx.coeffRef(vec1[ii], vec1[jj]) += Klocal(ii, jj);\r\n\r\n    for(jj=0;jj<size2;jj++)\r\n    {\r\n       aa = start + vec2[jj];\r\n       bb = size1 + jj;\r\n       mtx.coeffRef(vec1[ii], aa) += Klocal(ii, bb);\r\n       mtx.coeffRef(aa, vec1[ii]) += Klocal(bb, ii);\r\n    }\r\n  }\r\n\r\n  for(ii=0;ii<size2;ii++)\r\n  {\r\n    aa = start + vec2[ii];\r\n    rhsVec[aa] += Flocal(size1+ii);\r\n  }\r\n\r\n  if(STABILISED)\r\n  {\r\n    for(ii=0;ii<size2;ii++)\r\n    {\r\n      aa = start + vec2[ii];\r\n      bb = size1 + ii;\r\n      for(jj=0;jj<size2;jj++)\r\n      {\r\n        mtx.coeffRef(aa, start+vec2[jj]) += Klocal(bb, size1+jj);\r\n      }\r\n    }\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\n\r\nint SolverEigen::assembleMatrixAndVector(int start, int c1, vector<int>& forAssy, MatrixXd& Klocal, VectorXd& Flocal)\r\n{\r\n  int ii, jj, aa, bb, size1, r, c;\r\n\r\n  size1 = forAssy.size();\r\n\r\n  /*\r\n  for(ii=0;ii<size1;ii++)\r\n  {\r\n    rhsVec[forAssy[ii]] += Flocal(ii);\r\n\r\n    for(jj=0;jj<size1;jj++)\r\n      mtx.coeffRef(forAssy[ii], forAssy[jj]) += Klocal(ii, jj);\r\n  }\r\n  */\r\n\r\n  for(ii=0; ii<size1; ii++)\r\n  {\r\n    aa = forAssy[ii];\r\n    if( aa != -1 )\r\n    {\r\n      r = start + aa;\r\n      rhsVec[r] += Flocal(ii);\r\n\r\n      for(jj=0; jj<size1; jj++)\r\n      {\r\n        bb = forAssy[jj];\r\n        if( bb != -1 )\r\n          mtx.coeffRef(r, start+bb) += Klocal(ii,jj);\r\n      }\r\n    }\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\nint SolverEigen::assembleVector(int start, int c1, vector<int>& vec1, VectorXd& Flocal)\r\n{\r\n  int ii, jj;\r\n\r\n  for(ii=0;ii<vec1.size();ii++)\r\n  {\r\n    rhsVec[vec1[ii]] += Flocal(ii);\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\nint SolverEigen::assembleMatrixAndVectorCutFEM(int start, int c1, vector<int>& grid2cutfem_DOF, vector<int>& forAssy, MatrixXd& Klocal, VectorXd& Flocal)\r\n{\r\n  int ii, jj, size1, r;\r\n\r\n  //printVector(vec1);\r\n  //printVector(vec2);\r\n\r\n/*\r\n  size1 = grid2cutfem_DOF.size();\r\n\r\n  for(ii=0;ii<size1;ii++)\r\n  {\r\n    r = start+forAssy[grid2cutfem_DOF[ii]];\r\n\r\n    rhsVec[r] += Flocal(ii);\r\n\r\n    for(jj=0;jj<size1;jj++)\r\n      mtx.coeffRef(r, start+forAssy[grid2cutfem_DOF[jj]]) += Klocal(ii, jj);\r\n  }\r\n*/\r\n//\r\n  size1 = grid2cutfem_DOF.size();\r\n\r\n  for(ii=0;ii<size1;ii++)\r\n  {\r\n    r = forAssy[grid2cutfem_DOF[ii]];\r\n\r\n    rhsVec[r] += Flocal(ii);\r\n\r\n    for(jj=0;jj<size1;jj++)\r\n      mtx.coeffRef(r, forAssy[grid2cutfem_DOF[jj]]) += Klocal(ii, jj);\r\n  }\r\n//\r\n\r\n/*\r\n  size1 = grid2cutfem_DOF.size();\r\n\r\n  for(ii=0;ii<size1;ii++)\r\n  {\r\n    r = forAssy[ii];\r\n\r\n    rhsVec[r] += Flocal(ii);\r\n\r\n    for(jj=0;jj<size1;jj++)\r\n      mtx.coeffRef(r, forAssy[jj]) += Klocal(ii, jj);\r\n  }\r\n*/\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\nint SolverEigen::assembleMatrixAndVectorCutFEM2(int start1, int start2, vector<int>& grid2cutfem_DOF, \r\n     vector<int>& forAssy1, vector<int>& forAssy2, MatrixXd& Klocal, VectorXd& Flocal1, VectorXd& Flocal2)\r\n{\r\n  // to assemble coupling matrices arriving from \r\n  // jump conditions in the gradients across an interface\r\n\r\n  int ii, jj, size1, kk, r, c;\r\n\r\n  //printVector(vec1);\r\n  //printVector(vec2);\r\n  \r\n  size1 = grid2cutfem_DOF.size();\r\n\r\n  for(ii=0;ii<size1;ii++)\r\n  {\r\n    // force vector for domain #2\r\n    r = start2 + forAssy2[grid2cutfem_DOF[ii]];\r\n\r\n    rhsVec[r] += Flocal2(ii);\r\n\r\n    // force vector for domain #1\r\n    r = start1 + forAssy1[grid2cutfem_DOF[ii]];\r\n\r\n    rhsVec[r] += Flocal1(ii);\r\n\r\n    // coupling matrix\r\n    for(jj=0;jj<size1;jj++)\r\n    {\r\n      c = start2 + forAssy2[grid2cutfem_DOF[jj]];\r\n      mtx.coeffRef(r, c) += Klocal(ii, jj);\r\n      mtx.coeffRef(c, r) += Klocal(ii, jj);\r\n    }\r\n  }\r\n\r\n  return 0;\r\n}\r\n\r\n\r\n\r\nint SolverEigen::assembleMatrixAndVectorCutFEM3(int start1, int start2, vector<int>& row, vector<int>& col, \r\n     vector<int>& forAssy1, vector<int>& forAssy2, MatrixXd& Klocal, VectorXd& Flocal1)\r\n{\r\n \r\n  return 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "258ff68dac79eaf2498024c6034e21cc78f18ff9", "size": 11216, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mySolvers/SolverEigen.cpp", "max_stars_repo_name": "chennachaos/mpap", "max_stars_repo_head_hexsha": "99d02bc9075b72b899a167d1bbc2bf73584b85bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-30T16:45:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T23:27:29.000Z", "max_issues_repo_path": "src/mySolvers/SolverEigen.cpp", "max_issues_repo_name": "chennachaos/mpap", "max_issues_repo_head_hexsha": "99d02bc9075b72b899a167d1bbc2bf73584b85bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-11-22T12:57:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-04T22:01:42.000Z", "max_forks_repo_path": "src/mySolvers/SolverEigen.cpp", "max_forks_repo_name": "chennachaos/mpap", "max_forks_repo_head_hexsha": "99d02bc9075b72b899a167d1bbc2bf73584b85bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3188405797, "max_line_length": 154, "alphanum_fraction": 0.5605385164, "num_tokens": 3453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.6370308082623217, "lm_q1q2_score": 0.41039124028789237}}
{"text": "/*!\n *\n * \\file interpolation.hpp\n *\n * \\brief File containing n-dimensional interpolation functions\n *        for linear and cubic order.\n *\n *\n */\n#pragma once\n#include <array>\n#include <cmath>\n#include <utility>\n\n#include <Eigen/Dense>\n#include <pybind11/numpy.h>\n#include <pybind11/pybind11.h>\n\n/*! \\brief Namespace containing interpolation functionality for\n *         interpolating n-dimensional data using linear or cubic\n *         interpolation\n */\nnamespace interpolation\n{\n/*! \\brief Struct for interpolation data\n *\n *  The Data struct is a simple wrapper of the std::array that allows\n *  you to have arrays of arrays. The idea is that for example for cubic\n *  interpolation, you need in 1D 4 data points, in 2D 4x4 data points etc.\n *  In 1D this array contains the necessary points for a given x. In 2D\n *  This array contains arrays for a given constant y whose interpolation\n *  results can then again be used for constant x, etc.\n *\n *  @tparam Func   The interpolation function for which to use the data.\n *                 This determines how many data points are needed. E.g.\n *                 cubic interpolation requires 4 points. The function must\n *                 provide the value NUMBER_OF_VALUES.\n *  @tparam Dim    The dimensionality of the data to interpolate. E.g. for\n *                 2 dimensional data, the result would be an array of arrays.\n */\ntemplate <typename Func, int Dim>\nstruct Data\n{\n    /*! \\brief array of Dim-1 dimensional nested arrays.\n     */\n    std::array<Data<Func, Dim - 1>, Func::NUMBER_OF_VALUES> data;\n\n    /*! \\brief function to access this n-dimensional data\n     *\n     *  @param[in] index_0 the first index of the n-dimensional position\n     *                     for which to look up the value\n     *  @param[in] indices further indices depending on dimensionality,\n     *                     i.e. Dim-1 indices for Dim-dimensional data.\n     *\n     *  @returns The value in the Dim-dimensional data structure at the\n     *           given position\n     *\n     */\n    template <typename... Indices>\n    typename Func::VALUE_TYPE operator()(size_t index_0,\n                                         Indices... indices) const\n    {\n        return data[index_0](indices...);\n    }\n\n    /*! \\brief function to access this n-dimensional data\n     *\n     *  @param[in] index_0 the first index of the n-dimensional position\n     *                     for which to look up the value\n     *  @param[in] indices further indices depending on dimensionality,\n     *                     i.e. Dim-1 indices for Dim-dimensional data.\n     *\n     *  @returns A reference to the value in the Dim-dimensional data structure\n     *           at the given position\n     *\n     */\n    template <typename... Indices>\n    typename Func::VALUE_TYPE& operator()(size_t index_0, Indices... indices)\n    {\n        return data[index_0](indices...);\n    }\n};\n\n/*! \\brief 1D specialization of data\n *\n *  While all other Data<Func, Dim> structs contain arrays of Data<func,\n *  Dim-1>, the struct for 1D only contains an array of values of the\n *  value type the interpolation function works with. As such it works as\n *  a recursion stop.\n *\n *  @tparam Func   The interpolation function for which to use the data.\n *                 This determines how many data points are needed. E.g.\n *                 cubic interpolation requires 4 points.\n */\ntemplate <typename Func>\nstruct Data<Func, 1>\n{\n    /*! \\brief Look-up type for nested arrays for the case of 1D.\n     *\n     *  In this special case of 1D the type is simply an array with the\n     *  number of values and type defined by the interpolation function Func.\n     *  E.g. for cubic<double> it would be std::array<double, 4>.\n     */\n    std::array<typename Func::VALUE_TYPE, Func::NUMBER_OF_VALUES> data;\n\n    /*! \\brief function to access this 1-dimensional data\n     *\n     *  @param[in] index the index of the 1-dimensional position for which to\n     *                   look up the value\n     *\n     *  @returns The value in the 1-dimensional data structure at the\n     *           given position\n     *\n     */\n    typename Func::VALUE_TYPE operator()(size_t index) const\n    {\n        return data[index];\n    }\n\n    /*! \\brief function to access this 1-dimensional data\n     *\n     *  @param[in] index the index of the 1-dimensional position for which to\n     *                   look up the value\n     *\n     *  @returns A reference to the value in the 1-dimensional data structure at\n     *           the given position\n     *\n     */\n    typename Func::VALUE_TYPE& operator()(size_t index) { return data[index]; }\n};\n\n/*! \\brief Cause a compile error for the illegal zero dimensional case\n */\ntemplate <typename Func>\nstruct Data<Func, 0>;\n\n/*! \\brief 1D linear interpolation\n *\n *  @tparam T   The datatype to use for the interpolation. E.g.\n *              float/double/etc.\n */\ntemplate <typename T>\nstruct linear\n{\n    /*! \\brief The data type this function is operating with, e.g. for float\n     *         images, it is float.\n     */\n    typedef T VALUE_TYPE;\n    /*! \\brief The number of datapoints required to perform the interpolation.\n     *         Linear interpolation needs two datapoints.\n     */\n    static constexpr int NUMBER_OF_VALUES = 2;\n\n    /*! \\brief Compute the linear interpolation of the given points and\n     * position.\n     *\n     *  Given 2 values, and a position in the interval [0, 1], this function\n     *  returns the interpolated value using simple linear interpolation.\n     *\n     *  \\note This function operates in double mode. The result is cast to the\n     *        set template type T. NO rounding to nearest etc. is performed for\n     *        e.g. integers.\n     *\n     *  @param[in] p   The 2 values to interpolate\n     *  @param[in] x   The position in the interval [0, 1] to interpolate\n     *\n     *  @returns   The result of the interpolation\n     */\n    T operator()(const Data<linear<T>, 1>& p, double x)\n    {\n        return static_cast<T>(p(0) * (1 - x) + p(1) * x);\n    }\n};\n\n/*! \\brief 1D cubic interpolation\n *\n *  @tparam T   The datatype to use for the interpolation. E.g.\n *              float/double/etc.\n */\ntemplate <typename T>\nstruct cubic\n{\n    /*! \\brief The data type this function is operating with, e.g. for float\n     *         images, it is float.\n     */\n    typedef T VALUE_TYPE;\n    /*! \\brief The number of datapoints required to perform the interpolation.\n     *         Cubic interpolation needs four datapoints.\n     */\n    static constexpr int NUMBER_OF_VALUES = 4;\n\n    /*! \\brief Compute the cubic interpolation of the given points and position.\n     *\n     *  Given 4 values, and a position in the interval [0, 1], this function\n     *  returns the interpolated value using a uniform Catmull-Rom spline.\n     *\n     *  \\note This function operates in double mode. The result is cast to the\n     *        set template type T. NO rounding to nearest etc. is performed for\n     *        e.g. integers.\n     *\n     *  @param[in] p   The 4 values to interpolate\n     *  @param[in] x   The position in the interval [0, 1] to interpolate\n     *\n     *  @returns   The result of the interpolation\n     */\n    T operator()(const Data<cubic<T>, 1>& p, double x)\n    {\n        return static_cast<T>(\n            p(1) + 0.5 * x *\n                       (p(2) - p(0) +\n                        x * (2.0 * p(0) - 5.0 * p(1) + 4.0 * p(2) - p(3) +\n                             x * (3.0 * (p(1) - p(2)) + p(3) - p(0)))));\n    }\n};\n\n\n/*! \\brief Namespace containing implementation details for the interpolation\n *         functionality.\n */\nnamespace detail\n{\n/*! \\brief Function to extract data from a pybind11 array using\n *         a std::array for indexing\n *\n *  Additional function required to realize the variadic indexing using\n *  the std::array.\n *\n *  @param[in] image          The image from which to extract a value\n *  @param[in] array_indices  The location of the data point to extract\n *\n *  @returns                  The value at the given position\n *\n *  @tparam T                 The data type of the image\n *  @tparam Dim               The dimensions of the image\n *  @tparam I                 Template parameter for unpacking the std::array\n */\ntemplate <typename T, int Dim, std::size_t... I>\nT get_image_value_impl(\n    const pybind11::detail::unchecked_reference<T, Dim>& image,\n    const std::array<int, Dim>& array_indices, std::index_sequence<I...>)\n{\n    return image(array_indices[I]...);\n}\n\n/*! \\brief Function to extract data from a pybind11 array using\n *         a std::array for indexing\n *  @param[in] image          The image from which to extract a value\n *  @param[in] array_indices  The location of the data point to extract\n *\n *  @returns                  The value at the given position\n *\n *  @tparam T                 The data type of the image\n *  @tparam Dim               The dimensions of the image\n */\ntemplate <typename T, int Dim>\nT get_image_value(const pybind11::detail::unchecked_reference<T, Dim>& image,\n                  const std::array<int, Dim>& array_indices)\n{\n    return get_image_value_impl<T, Dim>(image, array_indices,\n                                std::make_index_sequence<Dim>{});\n}\n\n/*! \\brief Apply Func to the given data and position.\n *\n * This function works by realising that the n-dimensional interpolation can\n * be broken down into a list of (n-1)-dimensional interpolations that are\n * interpolated via a 1D interpolation. This recursive call to\n * lower-dimensional interpolation is realized with recursive template\n * programming.\n *\n *  @param[in] indices   Indices used to unpack the array p to call the\n *                       lower dimensional interpolation on each sub-array\n *                       (for 2D and higher dimensional data).\n *  @param[in] chunk     N-dimensional array data for the interpolation.\n *                       Needs the right number of points in each dimension,\n *                       e.g. 4 for cubic interpolation. Should be nested\n *                       arrays in C order.\n *  @param[in] x         The first coordinate value of the N-dimensional\n *                       position at which to interpolate\n *  @param[in] xs        The last N-1 coordinate values of the N-dimensional\n *                       position. One argument for each dimension.\n *\n *  @returns             The interpolation value\n *\n *  @tparam Func         The interpolation order func\n *  @tparam Ts           The type of the position coordinate values. This is\n *                       enforced to be double\n *  @tparam I            Needed only to unpack array into separate\n *                       function calls.\n */\ntemplate <typename Func, typename... Ts, std::size_t... I>\nstatic typename Func::VALUE_TYPE\napply_func_impl(std::index_sequence<I...> indices,\n                const Data<Func, sizeof...(Ts) + 1>& chunk, double x, Ts... xs)\n{\n    if constexpr (sizeof...(Ts) > 0)\n    {\n        return apply_func_impl<Func>(\n            indices,\n            {{apply_func_impl(indices, std::get<I>(chunk.data), xs...)...}}, x);\n    }\n    else\n    {\n        return Func()(chunk, x);\n    }\n}\n\n/*! \\brief Extract interpolation patch from given data around given position.\n *\n *  This function uses variadic templates to iterate over n-dimensional\n *  data using the given boundary function.\n *\n *  @param[in,out] chunk           N-dimensional array data for the\n *                                 interpolation. Needs the right number of\n *                                 points in each dimension, e.g. 4 for cubic\n *                                 interpolation.\n *  @param[in] image               The image from which to extract the data.\n *  @param[in] lower_corner        Lower corner of the sub-cube to extract from\n *                                 the image into the given chunk.\n *  @param[in] background_value    The background value to use in case the value\n *                                 is outside the image domain (might be ignored\n *                                 depending on the boundary function used)\n *  @param[in] loop_indices        The loop indices of all the for loops to\n *                                 fill the n-dimensional chunk\n *\n *  @tparam Func                   The interpolation order func\n *  @tparam BoundaryFunc           The boundary type to use. E.g.\n *                                 ConstantBoundary\n *  @tparam Dim                    The dimensionality of the given image\n */\ntemplate <typename Func, typename BoundaryFunc, int Dim, typename... Ts>\nstatic void extract_impl(\n    Data<Func, Dim>& chunk,\n    const pybind11::detail::unchecked_reference<typename Func::VALUE_TYPE, Dim>&\n        image,\n    const std::array<int, Dim>& lower_corner,\n    typename Func::VALUE_TYPE background_value, Ts... loop_indices)\n{\n    for (int i = 0; i < Func::NUMBER_OF_VALUES; ++i)\n    {\n        if constexpr (Dim == sizeof...(Ts) + 1)\n        {\n            std::array<int, Dim> voxel_position{{loop_indices..., i}};\n\n            for (int l = 0; l < Dim; ++l)\n            {\n                voxel_position[l] += lower_corner[l];\n            }\n            chunk(loop_indices..., i) =\n                BoundaryFunc::template apply<typename Func::VALUE_TYPE, Dim>(image, voxel_position, background_value);\n        }\n        else\n        {\n            extract_impl<Func, BoundaryFunc, Dim>(chunk, image, lower_corner,\n                                                  background_value,\n                                                  loop_indices..., i);\n        }\n    }\n}\n}; // namespace detail\n\n/*! \\brief Struct for dealing with n-dimensional image boundaries by\n *         returning a constant values for coordinates out of bounds.\n */\nstruct ConstantBoundary\n{\n    /*! \\brief Apply the constant boundary to the given image and position.\n     *\n     *  @param[in] image            The image to sample\n     *  @param[in] voxel_position   The position at which to sample\n     *  @param[in] background_value The background value to use if the given\n     *                              position is out of bounds\n     *\n     *  @returns                    The value at the given position using the\n     *                              rules defined by ConstantBoundary for\n     *                              positions outside of the given image.\n     *\n     *  @tparam T                   The data type of the given image\n     *  @tparam Dim                 The dimensions of the given image\n     */\n    template <typename T, int Dim>\n    static T apply(const pybind11::detail::unchecked_reference<T, Dim>& image,\n                   const std::array<int, Dim>& voxel_position,\n                   T background_value)\n    {\n        for (int l = 0; l < Dim; ++l)\n        {\n            if (voxel_position[l] < 0 || voxel_position[l] >= image.shape(l))\n            {\n                return background_value;\n            }\n        }\n        return detail::get_image_value<T, Dim>(image, voxel_position);\n    }\n};\n\n/*! \\brief Apply Func to the given data and position.\n *\n *  @param[in] chunk  N-dimensional array data for the interpolation. Needs\n *                    the right number of points in each dimension, e.g. 4\n *                    for cubic interpolation. Should be nested arrays in C\n *                    order.\n *  @param[in] x      The first coordinate value of the N-dimensional\n *                    position at which to interpolate\n *  @param[in] xs     The last N-1 coordinate values of the N-dimensional\n *                    position. One argument for each dimension.\n *\n *  @returns          The interpolation value\n *\n *  @tparam Func       The interpolation order func\n *  @tparam Ts        The type of the position coordinate values. This is\n *                    enforced to be double\n */\ntemplate <typename Func, typename... Ts>\nstatic typename Func::VALUE_TYPE\napply_func(const Data<Func, sizeof...(Ts) + 1>& chunk, double x, Ts... xs)\n{\n    return detail::apply_func_impl(\n        std::make_index_sequence<Func::NUMBER_OF_VALUES>{}, chunk, x, xs...);\n}\n\n/*! \\brief Extract interpolation patch from given data around given position.\n *\n *  Different interpolation schemes require a different number of points\n *  to operate. This function takes the appropriate chunk and fills it with\n *  data based on the information of the function given.\n *\n *  @param[in,out] chunk           N-dimensional array data for the\n *                                 interpolation. Needs the right number of\n *                                 points in each dimension, e.g. 4 for cubic\n *                                 interpolation.\n *  @param[in] image               The image from which to extract the data.\n *  @param[in, out] point_floored  The point in the image where to interpolate\n *                                 floored. Will point to the lower corner of\n *                                 the data grid used for the interpolation at\n *                                 the end.\n *  @param[in] background_value    The background value to use in case the value\n *                                 is outside the image domain (might be ignored\n *                                 depending on the boundary function used)\n *  @tparam Func                    The interpolation order func\n *  @tparam BoundaryFunc           The boundary type to use. E.g.\n *                                 ConstantBoundary\n *  @tparam Dim                    The dimensionality of the given image\n */\ntemplate <typename Func, typename BoundaryFunc, int Dim>\nstatic void\nextract(Data<Func, Dim>& chunk,\n        const pybind11::detail::unchecked_reference<typename Func::VALUE_TYPE,\n                                                    Dim>& image,\n        std::array<int, Dim>& point_floored,\n        typename Func::VALUE_TYPE background_value)\n{\n    for (size_t l = 0; l < Dim; ++l)\n    {\n        point_floored[l] -= (Func::NUMBER_OF_VALUES - 2) / 2;\n    }\n\n    detail::extract_impl<Func, BoundaryFunc, Dim>(chunk, image, point_floored,\n                                                  background_value);\n}\n\n}; // namespace interpolation\n", "meta": {"hexsha": "f5370a2b184527801b6b528f586ad806f7263424", "size": 18132, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/affine_transform/interpolation.hpp", "max_stars_repo_name": "NOhs/affine_transform_nd", "max_stars_repo_head_hexsha": "3f90c7a4d72616e7a6e7bf1b5cff8b7990ed40ec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-09T15:19:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-09T15:19:17.000Z", "max_issues_repo_path": "include/affine_transform/interpolation.hpp", "max_issues_repo_name": "NOhs/affine_transform_nd", "max_issues_repo_head_hexsha": "3f90c7a4d72616e7a6e7bf1b5cff8b7990ed40ec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2019-07-22T20:09:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-27T08:12:20.000Z", "max_forks_repo_path": "include/affine_transform/interpolation.hpp", "max_forks_repo_name": "NOhs/affine_transform_nd", "max_forks_repo_head_hexsha": "3f90c7a4d72616e7a6e7bf1b5cff8b7990ed40ec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-22T21:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-22T21:12:40.000Z", "avg_line_length": 39.161987041, "max_line_length": 118, "alphanum_fraction": 0.5939223472, "num_tokens": 4013, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863695, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4103912225305505}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\n *    All rights reserved.\n *\n *    Redistribution and use in source and binary forms, with or without modification, are\n *    permitted provided that the following conditions are met:\n *      - Redistributions of source code must retain the above copyright notice, this list of\n *        conditions and the following disclaimer.\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\n *        conditions and the following disclaimer in the documentation and/or other materials\n *        provided with the distribution.\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\n *        may be used to endorse or promote products derived from this software without specific\n *        prior written permission.\n *\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *    Changelog\n *      YYMMDD    Author            Comment\n *      110117    E. Iorfida        File created.\n *      110128    E. Iorfida        Added boolean variable that sets the necessity of\n *                                  Newton-Raphson method, particularly in unit test.\n *      110202    J. Melman         Renamed certain parameters and added comments to clarify the\n *                                  code more.\n *      110203    E. Iorfida        Changed some variables names and modified punctuation.\n *      110205    J. Melman         Removed the trailing underscores in some public variables. Some\n *                                  comment rephrasing. Changed and added some notes.\n *      110212    J. Melman         Added a reference to my own thesis.\n *      110214    E. Iorfida        Deleted temporary centralBodyRadius, replaced by an element of\n *                                  GeometricShapes.\n *      120326    D. Dirkx          Changed raw pointers to shared pointers.\n *      120508    P. Musegaas       The gravitational parameter is now passed as double.\n *      120530    P. Musegaas       Complete revision. Removed class structure, made it a free\n *                                  function. Added two functions for propagating a gravity assist\n *                                  (powered and unpowered).\n *      120625    P. Musegaas       Minor changes.\n *      120703    T. Secretin       Minor layout changes.\n *      120704    P. Musegaas       Minor change. Reduced negligence of velocity effect from 1 cm/s\n *                                  to 1 micrometer/second.\n *      120713    P. Musegaas       Fixed various bugs (case with both bending + velocity effect\n *                                  was wrong, limit cases failed, rootfinder not ideal, all for\n *                                  original deltaV calculation function). Added iteration on\n *                                  pericenter radius instead of eccentricity. Improved efficiency.\n *      120813    P. Musegaas       Changed code to new root finding structure.\n *\n *    References\n *      References for deltaV computation function:\n *          Melman J. Trajectory optimization for a mission to Neptune and Triton, MSc thesis\n *              report, Delft University of Technology, 2007.\n *          Musegaas, P., Optimization of Space Trajectories Including Multiple Gravity Assists and\n *              Deep Space Maneuvers, MSc thesis report, Delft University of Technology, 2012.\n *              [unpublished so far].\n *      Reference for unpowered gravity assist propagation function:\n *          Conway, B.A., Spacecraft Trajectory Optimization, Chapter 7, Cambridge University\n *              Press, 2010.\n *      Reference for powered gravity assist propagation function:\n *          Musegaas, P., Optimization of Space Trajectories Including Multiple Gravity Assists and\n *              Deep Space Maneuvers, MSc thesis report, Delft University of Technology, 2012.\n *              [unpublished so far].\n *\n *    Notes\n *      Gravity assist and swing-by are two different words for the same thing. The delta-V that is\n *      computed for a powered swing-by has not been proven to be the optimum (lowest) to achieve\n *      the desired geometry of incoming and outgoing hyperbolic legs. Some literature research will\n *      have to be done to look at the alternatives.\n *\n *      Note that the exact implementation of Newton Raphson as root finder should be updated if\n *      someone would want to use a different root finding technique.\n *\n *      Note that by default a velocity effect deltaV of less than 1 micrometer/second is deemed\n *      negligable in this code. This value can be set though.\n *\n */\n\n#include <cmath>\n\n#include <boost/bind.hpp>\n\n#include <Eigen/Dense>\n\n#include \"Tudat/Mathematics/BasicMathematics/linearAlgebra.h\"\n\n#include \"Tudat/Astrodynamics/MissionSegments/gravityAssist.h\"\n#include \"Tudat/Mathematics/BasicMathematics/functionProxy.h\"\n\nnamespace tudat\n{\nnamespace mission_segments\n{\n\nusing namespace root_finders;\n\n//! Calculate deltaV of a gravity assist.\ndouble gravityAssist( const double centralBodyGravitationalParameter,\n                      const Eigen::Vector3d& centralBodyVelocity,\n                      const Eigen::Vector3d& incomingVelocity,\n                      const Eigen::Vector3d& outgoingVelocity,\n                      const double smallestPeriapsisDistance,\n                      const bool useEccentricityInsteadOfPericenter,\n                      const double speedTolerance,\n                      RootFinderPointer rootFinder )\n{\n    using basic_mathematics::UnivariateProxyPointer;\n    using basic_mathematics::UnivariateProxy;\n\n    // Compute incoming and outgoing hyperbolic excess velocity.\n    const Eigen::Vector3d incomingHyperbolicExcessVelocity\n            = incomingVelocity - centralBodyVelocity;\n    const Eigen::Vector3d outgoingHyperbolicExcessVelocity\n            = outgoingVelocity - centralBodyVelocity;\n\n    // Compute absolute values of the hyperbolic excess velocities.\n    const double absoluteIncomingExcessVelocity = incomingHyperbolicExcessVelocity.norm( );\n    const double absoluteOutgoingExcessVelocity = outgoingHyperbolicExcessVelocity.norm( );\n\n    // Compute bending angle.\n    double bendingAngle = linear_algebra::computeAngleBetweenVectors(\n                            incomingHyperbolicExcessVelocity, outgoingHyperbolicExcessVelocity );\n\n    // Compute maximum achievable bending angle.\n    const double maximumBendingAngle =\n            std::asin( 1.0 / ( 1.0 + ( smallestPeriapsisDistance *\n                                       absoluteIncomingExcessVelocity *\n                                       absoluteIncomingExcessVelocity /\n                                       centralBodyGravitationalParameter ) ) ) +\n            std::asin( 1.0 / ( 1.0 + ( smallestPeriapsisDistance *\n                                       absoluteOutgoingExcessVelocity *\n                                       absoluteOutgoingExcessVelocity /\n                                       centralBodyGravitationalParameter ) ) );\n\n    // Initialize bending effect deltaV, which is zero, unless extra bending angle is required.\n    double bendingEffectDeltaV = 0.0;\n\n    // Initialize velocity effect delta V parameter.\n    double velocityEffectDeltaV = 0.0;\n\n    // Check if an additional bending angle is required. If so, the additional bending angle\n    // maneuver has to be performed. Also the pericenter radius will be the minimum pericenter\n    // radius to obtain the largest possible bending angle 'for free'. Hence no root finding is\n    // required for this case. As noted above, this may not be ideal for all cases. (for cases\n    // in which the excess velocities are relatively small)\n    if ( bendingAngle > maximumBendingAngle )\n    {\n        // Compute required extra bending angle that cannot be delivered by an unpowered swing-by.\n        const double extraBendingAngle = bendingAngle - maximumBendingAngle;\n\n        // Compute necessary delta-V due to bending-effect.\n        bendingEffectDeltaV = 2.0 * std::min( absoluteIncomingExcessVelocity,\n                                              absoluteOutgoingExcessVelocity ) *\n                                    std::sin( extraBendingAngle / 2.0 );\n\n        // This means the pericenter radius is now equal to the smallest pericenter radius, to\n        // ensure the largest possible bending angle.\n        const double pericenterRadius = smallestPeriapsisDistance;\n\n        // Compute semi-major axis of hyperbolic legs.\n        const double incomingSemiMajorAxis = -1.0 * centralBodyGravitationalParameter /\n                                             absoluteIncomingExcessVelocity /\n                                             absoluteIncomingExcessVelocity;\n        const double outgoingSemiMajorAxis = -1.0 * centralBodyGravitationalParameter /\n                                             absoluteOutgoingExcessVelocity /\n                                             absoluteOutgoingExcessVelocity;\n\n        // Compute incoming hyperbolic leg eccentricity.\n        const double incomingEccentricity = 1 - pericenterRadius / incomingSemiMajorAxis;\n\n        // Compute outgoing hyperbolic leg eccentricity.\n        const double outgoingEccentricity = 1 - pericenterRadius / outgoingSemiMajorAxis;\n\n        // Compute incoming and outgoing velocities at periapsis.\n        const double incomingVelocityAtPeriapsis = absoluteIncomingExcessVelocity *\n                std::sqrt( ( incomingEccentricity + 1.0 ) / ( incomingEccentricity - 1.0 ) );\n        const double outgoingVelocityAtPeriapsis = absoluteOutgoingExcessVelocity *\n                std::sqrt( ( outgoingEccentricity + 1.0 ) / ( outgoingEccentricity - 1.0 ) );\n\n        // Compute necessary delta-V due to velocity-effect.\n        velocityEffectDeltaV = std::fabs( incomingVelocityAtPeriapsis -\n                                          outgoingVelocityAtPeriapsis );\n    }\n\n    else if ( ( std::fabs( absoluteIncomingExcessVelocity - absoluteOutgoingExcessVelocity )\n                <= speedTolerance ) )\n    {\n        // In this case no maneuver has to be performed. Hence no iteration is performed, and the\n        // delta V is simply kept at 0.0.\n    }\n\n    // Here the required maneuver to patch the incoming and outgoing excess velocities is\n    // calculated. In this implementation, the eccentricity will be used as iteration parameter.\n    else if ( useEccentricityInsteadOfPericenter )\n    {\n        // Compute semi-major axis of hyperbolic legs.\n        const double incomingSemiMajorAxis = -1.0 * centralBodyGravitationalParameter /\n                                             absoluteIncomingExcessVelocity /\n                                             absoluteIncomingExcessVelocity;\n        const double outgoingSemiMajorAxis = -1.0 * centralBodyGravitationalParameter /\n                                             absoluteOutgoingExcessVelocity /\n                                             absoluteOutgoingExcessVelocity;\n\n        // Set the gravity assist function with the variables to perform root finder calculations.\n        EccentricityFindingFunctions eccentricityFindingFunctions( incomingSemiMajorAxis,\n                                                                   outgoingSemiMajorAxis,\n                                                                   bendingAngle );\n\n        // Create an object containing the function of which we whish to obtain the root from.\n        UnivariateProxyPointer rootFunction = boost::make_shared< UnivariateProxy >(\n                    boost::bind( &EccentricityFindingFunctions::\n                                 computeIncomingEccentricityFunction,\n                                 eccentricityFindingFunctions, _1 ) );\n\n        // Add the first derivative of the root function.\n        rootFunction->addBinding( -1, boost::bind(\n                                      &EccentricityFindingFunctions::\n                                      computeFirstDerivativeIncomingEccentricityFunction,\n                                      eccentricityFindingFunctions, _1 ) );\n\n        // Initialize incoming eccentricity.\n        double incomingEccentricity = TUDAT_NAN;\n\n        // Set initial guess of the variable computed in Newton-Rapshon method.\n        if ( ( absoluteOutgoingExcessVelocity / absoluteIncomingExcessVelocity ) < 100.0 )\n        {\n            // In these cases the very low estimate (which is given under else) may in some cases\n            // result in no convergence. Hence a higher value of 1.01 is necessary. This will not\n            // result in 'going through' 1.0 as mentioned below, because the eccentricity in these\n            // cases is always high!\n            incomingEccentricity = rootFinder->execute( rootFunction, 1.0 + 1.0e-2 );\n        }\n\n        else\n        {\n            // This is set to a value that is close to 1.0. This is more robust than higher values,\n            // because for those higher values Newton Raphson sometimes 'goes through' 1.0. This\n            // results in NaN values for the derivative of the eccentricity finding function.\n            incomingEccentricity = rootFinder->execute( rootFunction, 1.0 + 1.0e-10 );\n        }\n\n        // Compute outgoing hyperbolic leg eccentricity.\n        const double outgoingEccentricity = 1.0 - ( incomingSemiMajorAxis /\n                                                    outgoingSemiMajorAxis ) *\n                                            ( 1.0 - incomingEccentricity );\n\n        // Compute incoming and outgoing velocities at periapsis.\n        const double incomingVelocityAtPeriapsis = absoluteIncomingExcessVelocity *\n                std::sqrt( ( incomingEccentricity + 1.0 ) / ( incomingEccentricity - 1.0 ) );\n        const double outgoingVelocityAtPeriapsis = absoluteOutgoingExcessVelocity *\n                std::sqrt( ( outgoingEccentricity + 1.0 ) / ( outgoingEccentricity - 1.0 ) );\n\n        // Compute necessary delta-V due to velocity-effect.\n        velocityEffectDeltaV = std::fabs( incomingVelocityAtPeriapsis -\n                                          outgoingVelocityAtPeriapsis );\n    }\n\n    // Here the required maneuver to patch the incoming and outgoing excess velocities is\n    // calculated. In this implementation, the pericenter radius will be used as iteration\n    // parameter.\n    else\n    {\n        // Compute semi-major axis of hyperbolic legs. This is the absolute semi major axis, because\n        // it will otherwisely result in the root of a negative function for various cases during\n        // the rootfinding process.\n        const double absoluteIncomingSemiMajorAxis = 1.0 * centralBodyGravitationalParameter /\n                                                     absoluteIncomingExcessVelocity /\n                                                     absoluteIncomingExcessVelocity;\n        const double absoluteOutgoingSemiMajorAxis = 1.0 * centralBodyGravitationalParameter /\n                                                     absoluteOutgoingExcessVelocity /\n                                                     absoluteOutgoingExcessVelocity;\n\n        // Set the gravity assist function with the variables to perform root finder calculations.\n        PericenterFindingFunctions pericenterFindingFunctions( absoluteIncomingSemiMajorAxis,\n                                                               absoluteOutgoingSemiMajorAxis,\n                                                               bendingAngle);\n\n        // Create an object containing the function of which we whish to obtain the root from.\n        UnivariateProxyPointer rootFunction = boost::make_shared< UnivariateProxy >(\n                    boost::bind( &PericenterFindingFunctions::computePericenterRadiusFunction,\n                                 pericenterFindingFunctions, _1 ) );\n\n        // Add the first derivative of the root function.\n        rootFunction->addBinding( -1, boost::bind( &PericenterFindingFunctions::\n                                                   computeFirstDerivativePericenterRadiusFunction,\n                                                   pericenterFindingFunctions, _1 ) );\n\n        // Set pericenter radius based on result of Newton-Raphson root-finding algorithm.\n        const double pericenterRadius = rootFinder->execute( rootFunction,\n                                                             smallestPeriapsisDistance );\n\n        // Compute incoming hyperbolic leg eccentricity.\n        const double incomingEccentricity = 1.0 + pericenterRadius / absoluteIncomingSemiMajorAxis;\n\n        // Compute outgoing hyperbolic leg eccentricity.\n        const double outgoingEccentricity = 1.0 + pericenterRadius / absoluteOutgoingSemiMajorAxis;\n\n        // Compute incoming and outgoing velocities at periapsis.\n        const double incomingVelocityAtPeriapsis = absoluteIncomingExcessVelocity *\n                std::sqrt( ( incomingEccentricity + 1.0 ) / ( incomingEccentricity - 1.0 ) );\n        const double outgoingVelocityAtPeriapsis = absoluteOutgoingExcessVelocity *\n                std::sqrt( ( outgoingEccentricity + 1.0 ) / ( outgoingEccentricity - 1.0 ) );\n\n        // Compute necessary delta-V due to velocity-effect.\n        velocityEffectDeltaV = std::fabs( incomingVelocityAtPeriapsis -\n                                          outgoingVelocityAtPeriapsis );\n    }\n\n    // Compute and return the total delta-V.\n    return bendingEffectDeltaV + velocityEffectDeltaV;\n}\n\n//! Propagate an unpowered gravity assist.\nEigen::Vector3d gravityAssist( const double centralBodyGravitationalParameter,\n                               const Eigen::Vector3d& centralBodyVelocity,\n                               const Eigen::Vector3d& incomingVelocity,\n                               const double rotationAngle,\n                               const double pericenterRadius )\n{\n    // Calculate the incoming velocity.\n    const Eigen::Vector3d relativeIncomingVelocity = incomingVelocity - centralBodyVelocity;\n    const double absoluteRelativeIncomingVelocity = relativeIncomingVelocity.norm( );\n\n    // Calculate the eccentricity and bending angle.\n    const double eccentricity = 1.0 + pericenterRadius / centralBodyGravitationalParameter *\n                            absoluteRelativeIncomingVelocity * absoluteRelativeIncomingVelocity;\n    const double bendingAngle = 2.0 * std::asin ( 1.0 / eccentricity );\n\n    // Calculate the unit vectors.\n    const Eigen::Vector3d unitVector1 = relativeIncomingVelocity /\n                                        absoluteRelativeIncomingVelocity;\n    const Eigen::Vector3d unitVector2 = unitVector1.cross( centralBodyVelocity ).normalized( );\n    const Eigen::Vector3d unitVector3 = unitVector1.cross( unitVector2 );\n\n    // Calculate the relative outgoing velocity.\n    const Eigen::Vector3d relativeOutgoingVelocity = absoluteRelativeIncomingVelocity *\n            ( std::cos( bendingAngle ) * unitVector1 + std::sin( bendingAngle ) *\n              std::cos( rotationAngle ) * unitVector2 + std::sin( bendingAngle ) *\n              std::sin( rotationAngle ) * unitVector3 );\n\n    // Add the relative outgoing velocity to the swing-by body velocity and return it.\n    return centralBodyVelocity + relativeOutgoingVelocity;\n}\n\n//! Propagate a powered gravity assist.\nEigen::Vector3d gravityAssist( const double centralBodyGravitationalParameter,\n                               const Eigen::Vector3d& centralBodyVelocity,\n                               const Eigen::Vector3d& incomingVelocity,\n                               const double rotationAngle,\n                               const double pericenterRadius,\n                               const double deltaV )\n{\n    // Calculate the incoming velocity.\n    const Eigen::Vector3d relativeIncomingVelocity = incomingVelocity - centralBodyVelocity;\n    const double absoluteRelativeIncomingVelocity = relativeIncomingVelocity.norm( );\n\n    // Calculate the incoming eccentricity and bending angle.\n    const double incomingEccentricity = 1.0 + pericenterRadius /\n                                        centralBodyGravitationalParameter *\n                                        absoluteRelativeIncomingVelocity *\n                                        absoluteRelativeIncomingVelocity;\n    const double incomingBendingAngle = std::asin ( 1.0 / incomingEccentricity );\n\n    // Calculate the pericenter velocities.\n    const double incomingPericenterVelocity = std::sqrt( absoluteRelativeIncomingVelocity *\n                                                         absoluteRelativeIncomingVelocity *\n                                                         ( incomingEccentricity + 1.0 ) /\n                                                         ( incomingEccentricity - 1.0 ) );\n    const double outgoingPericenterVelocity = incomingPericenterVelocity + deltaV;\n\n    // Calculate magnitude of the absolute relative outgoing velocity.\n    const double absoluteRelativeOutgoingVelocity =\n            std::sqrt( outgoingPericenterVelocity * outgoingPericenterVelocity -\n                       2.0 * centralBodyGravitationalParameter / pericenterRadius );\n\n    // Calculate the remaining bending angles.\n    const double outgoingBendingAngle =\n            std::asin ( 1.0 / ( 1.0 + absoluteRelativeOutgoingVelocity *\n                                absoluteRelativeOutgoingVelocity * pericenterRadius /\n                                centralBodyGravitationalParameter ) );\n    const double bendingAngle = incomingBendingAngle + outgoingBendingAngle;\n\n    // Calculate the unit vectors.\n    const Eigen::Vector3d unitVector1 = relativeIncomingVelocity /\n                                        absoluteRelativeIncomingVelocity;\n    const Eigen::Vector3d unitVector2 = unitVector1.cross( centralBodyVelocity ).normalized( );\n    const Eigen::Vector3d unitVector3 = unitVector1.cross( unitVector2 );\n\n    // Calculate the relative outgoing velocity.\n    const Eigen::Vector3d relativeOutgoingVelocity = absoluteRelativeOutgoingVelocity *\n            ( std::cos( bendingAngle ) * unitVector1 + std::sin( bendingAngle ) *\n              std::cos( rotationAngle ) * unitVector2 + std::sin( bendingAngle ) *\n              std::sin( rotationAngle ) * unitVector3 );\n\n    // Add the relative outgoing velocity to the swing-by body velocity and return it.\n    return centralBodyVelocity + relativeOutgoingVelocity;\n}\n\n//! Compute pericenter radius function.\ndouble PericenterFindingFunctions::computePericenterRadiusFunction( const double pericenterRadius )\n{\n    return std::asin( absoluteIncomingSemiMajorAxis_ / ( absoluteIncomingSemiMajorAxis_ +\n                                                         pericenterRadius ) ) +\n           std::asin( absoluteOutgoingSemiMajorAxis_ / ( absoluteOutgoingSemiMajorAxis_ +\n                                                         pericenterRadius ) ) - bendingAngle_;\n}\n\n//! Compute first-derivative of the pericenter radius function.\ndouble PericenterFindingFunctions::computeFirstDerivativePericenterRadiusFunction(\n        const double pericenterRadius )\n{\n    return -absoluteIncomingSemiMajorAxis_ / ( absoluteIncomingSemiMajorAxis_ + pericenterRadius )\n            / std::sqrt( ( pericenterRadius + 2.0 * absoluteIncomingSemiMajorAxis_ )\n                         * pericenterRadius ) -\n           absoluteOutgoingSemiMajorAxis_ / ( absoluteOutgoingSemiMajorAxis_ + pericenterRadius )\n            / std::sqrt( ( pericenterRadius + 2.0 * absoluteOutgoingSemiMajorAxis_ ) *\n                         pericenterRadius );\n}\n\n//! Compute incoming eccentricity function.\ndouble EccentricityFindingFunctions::computeIncomingEccentricityFunction(\n        const double incomingEccentricity )\n{\n    return std::asin( 1.0 / incomingEccentricity )\n            + std::asin( 1.0 / ( 1.0 - incomingSemiMajorAxis_ / outgoingSemiMajorAxis_ *\n                                 ( 1.0 - incomingEccentricity ) ) ) - bendingAngle_;\n}\n\n//! Compute first-derivative of the incoming eccentricity function.\ndouble EccentricityFindingFunctions::computeFirstDerivativeIncomingEccentricityFunction(\n        const double incomingEccentricity )\n{\n    const double eccentricitySquareMinusOne_ = incomingEccentricity * incomingEccentricity - 1.0;\n    const double semiMajorAxisRatio_ = incomingSemiMajorAxis_ / outgoingSemiMajorAxis_ ;\n    const double bParameter_ = 1.0 - semiMajorAxisRatio_ * ( 1.0 - incomingEccentricity );\n\n    return -1.0 / ( incomingEccentricity * std::sqrt( eccentricitySquareMinusOne_ ) ) -\n            semiMajorAxisRatio_ / ( bParameter_ * std::sqrt( bParameter_ * bParameter_ - 1.0 ) );\n}\n\n} // namespace mission_segments\n} // namespace tudat\n", "meta": {"hexsha": "9ef863823b955fbeaad56ace9091c5ceff917911", "size": 25417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/MissionSegments/gravityAssist.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/MissionSegments/gravityAssist.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/MissionSegments/gravityAssist.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 56.9887892377, "max_line_length": 100, "alphanum_fraction": 0.6419719086, "num_tokens": 5126, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.6370307806984444, "lm_q1q2_score": 0.4103912138278615}}
{"text": "/*\n * Copyright (c) 2013-2015 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef ALLSOL_AFFINE_HPP\n#define ALLSOL_AFFINE_HPP\n\n#include <iostream>\n#include <list>\n#include <kv/interval.hpp>\n#include <kv/rdouble.hpp>\n#include <kv/interval-vector.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <kv/matrix-inversion.hpp>\n#include <kv/affine.hpp>\n#include <kv/lp.hpp>\n\n\n#ifndef USE_TRIM\n#define USE_TRIM 1\n#endif\n\n#ifndef USE_SUMABS\n#define USE_SUMABS 0\n#endif\n\n#ifndef USE_LP\n#define USE_LP 0\n#endif\n\n#ifndef USE_FI\n#define USE_FI 1\n#endif\n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\nnamespace allsol_affine_sub {\n\n// return index of I_i which has maximum width\n\ntemplate <class T> int search_maxwidth (const ub::vector< interval<T> >& I) {\n\tint s = I.size();\n\tint i, mi;\n\tT m, tmp;\n\n\tm = 0.;\n\tfor (i=0; i<s; i++) {\n\t\ttmp = width(I(i));\n\t\tif (tmp > m) {\n\t\t\tm = tmp; mi = i;\n\t\t}\n\t}\n\n\treturn mi;\n}\n\n// return max width(I_i) / width(J_i)\n\ntemplate <class T> T widthratio_max (const ub::vector< interval<T> >& I, const ub::vector< interval<T> >& J) {\n\tint s = I.size();\n\tint i;\n\tT tmp, r;\n\n\tr = 0.;\n\n\tfor (i=0; i<s; i++) {\n\t\ttmp = width(I(i)) / width(J(i));\n\t\tif (tmp > r) r = tmp;\n\t}\n\n\treturn r;\n}\n\n// return min width(I_i) / width(J_i)\n\ntemplate <class T> T widthratio_min (const ub::vector< interval<T> >& I, const ub::vector< interval<T> >& J) {\n\tint s = I.size();\n\tint i;\n\tT tmp, r;\n\n\tr = std::numeric_limits<T>::max();\n\n\tfor (i=0; i<s; i++) {\n\t\ttmp = width(I(i)) / width(J(i));\n\t\tif (tmp < r) r = tmp;\n\t}\n\n\treturn r;\n}\n\n} // namespace allsol_affine_sub\n\n\n// find all solution of f in I\n\ntemplate <class T, class F> std::list< ub::vector< interval<T> > >\nallsol_affine(F f, const ub::vector< interval<T> >& I, int verbose=1)\n{\n\tstd::list< ub::vector < interval<T> > > targets;\n\ttargets.push_back(I);\n\treturn allsol_list_affine(f, targets, verbose);\n}\n\n\n// find all solution of f in targets (list of intervals)\n\ntemplate <class T, class F> std::list< ub::vector< interval<T> > >\nallsol_list_affine(F f, std::list< ub::vector< interval<T> > > targets, int verbose=1)\n{\n\tint s = (targets.front()).size();\n\tub::vector< interval<T> > I, fc, fi, C, CK, K, mvf, I1, I2;\n\tub::matrix< interval<T> > fdi, M;\n\tub::matrix<T> L, R, E;\n\tstd::list< ub::vector< interval<T> > > solutions, solutions_big;\n\ttypename std::list< ub::vector< interval<T> > >::iterator p, p2;\n\tint i, j, k, mi;\n\tT tmp;\n\tbool r, M_calculated, flag, flag2;\n\tint count_ne_test = 0;\n\tint count_ex_test = 0;\n\tint count_unknown = targets.size();\n\tint count_ne = 0;\n\tint count_ex = 0;\n\tub::vector< affine<T> > ax, ay, ak;\n\tub::vector< interval<T> > IR;\n\tT trim_tmp;\n\tinterval<T> trim_I;\n\taffine<T> sum_abs;\n\tub::vector< ub::vector<T> > ay2;\n\tinterval<T> I_tmp;\n\tT lp_tmp;\n\tub::vector< interval<T> > objfunc_I;\n\tub::vector<T> objfunc;\n\tstd::list< ub::vector<T> > constraints;\n\tub::vector<T> c_tmp;\n\tint ep_size, lp_size;\n\tbool lp_flag;\n\tT lp_return;\n\n\tE = ub::identity_matrix<T>(s);\n\tL.resize(s,s);\n\n\twhile (!targets.empty()) {\n\t\tif (verbose >= 2) {\n\t\t\tstd::cout << \"ne_test: \" << count_ne_test << \", ex_test: \" << count_ex_test << \", unknown: \" << count_unknown << \", ne: \" << count_ne << \", ex: \" << count_ex << \"    \\r\" << std::flush;\n\t\t}\n\n\t\tI = targets.front();\n\t\ttargets.pop_front();\n\t\tcount_unknown--;\n\n\t\t// non-existence test\n\n\t\tcount_ne_test++;\n\n#if USE_FI == 1\n\t\ttry {\n\t\t\tfi = f(I);\n\t\t}\n\t\tcatch (std::domain_error& e) {\n\t\t\tgoto label;\n\t\t}\n\n\t\tif (!zero_in(fi)) {\n\t\t\tcount_ne++;\n\t\t\tcontinue;\n\t\t}\n#endif\n\n\t\taffine<T>::maxnum() = 0;\n\t\tax = I;\n\t\ttry {\n\t\t\tay = f(ax);\n\t\t}\n\t\tcatch (std::domain_error& e) {\n\t\t\tgoto label;\n\t\t}\n\n\t\tfi = to_interval(ay);\n\t\tif (!zero_in(fi)) {\n\t\t\tcount_ne++;\n\t\t\tcontinue;\n\t\t}\n\n#if USE_SUMABS == 1\n\t\tsum_abs = 0.;\n\t\tfor (i=0; i<s; i++) {\n\t\t\tsum_abs += abs(ay(i));\n\t\t}\n\t\tif (to_interval(sum_abs).lower() > 0.) {\n\t\t\tcount_ne++;\n\t\t\tcontinue;\n\t\t}\n#endif\n\n#if USE_LP == 1\n#if USE_LP_FAST == 1\n\t\tep_size = 2 * s;\n\t\tlp_size = 1 + ep_size * 2;\n\t\tay2.resize(s + ep_size);\n\t\tfor (i=0; i<s; i++) {\n\t\t\tay2(i).resize(lp_size);\n\t\t\tfor (j=s + 1; j < lp_size; j++) {\n\t\t\t\tay2(i)(j) = 0.;\n\t\t\t}\n\t\t\tI_tmp = ay(i).get_mid();\n\t\t\tfor (j=1; j <= s; j++) {\n\t\t\t\ttmp = ay(i).get_coef(j);\n\t\t\t\tay2(i)(j) = tmp;\n\t\t\t\tI_tmp -= tmp;\n\t\t\t}\n\t\t\tlp_tmp = ay(i).get_err();\n\t\t\trop<T>::begin();\n\t\t\tfor (j=s+1; j <= affine<T>::maxnum(); j++) {\n\t\t\t\ttmp = ay(i).get_coef(j);\n\t\t\t\tif (tmp < 0.) tmp = -tmp;\n\t\t\t\tlp_tmp = rop<T>::add_up(lp_tmp, tmp);\n\t\t\t}\n\t\t\trop<T>::end();\n\t\t\tI_tmp -= lp_tmp;\n\t\t\trop<T>::begin();\n\t\t\tlp_tmp = rop<T>::add_up(lp_tmp, rad(I_tmp));\n\t\t\trop<T>::end();\n\t\t\tay2(i)(s + 1 + i) = lp_tmp;\n\t\t\tay2(i)(0) = I_tmp.lower();\n\t\t\tif (ay2(i)(0) > 0.) {\n\t\t\t\tfor (j=0; j<lp_size; j++) {\n\t\t\t\t\tay2(i)(j) = -ay2(i)(j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#else\n\t\tep_size = affine<T>::maxnum() + s;\n\t\tlp_size = 1 + ep_size * 2;\n\t\tay2.resize(s + ep_size);\n\t\tfor (i=0; i<s; i++) {\n\t\t\tay2(i).resize(lp_size);\n\t\t\tfor (j=affine<T>::maxnum() + 1; j < lp_size; j++) {\n\t\t\t\tay2(i)(j) = 0.;\n\t\t\t}\n\t\t\tI_tmp = ay(i).get_mid();\n\t\t\tfor (j=1; j <= affine<T>::maxnum(); j++) {\n\t\t\t\ttmp = ay(i).get_coef(j);\n\t\t\t\tay2(i)(j) = tmp;\n\t\t\t\tI_tmp -= tmp;\n\t\t\t}\n\t\t\tlp_tmp = ay(i).get_err();\n\t\t\tI_tmp -= lp_tmp;\n\t\t\trop<T>::begin();\n\t\t\tlp_tmp = rop<T>::add_up(lp_tmp, rad(I_tmp));\n\t\t\trop<T>::end();\n\t\t\tay2(i)(affine<T>::maxnum() + 1 + i) = lp_tmp;\n\t\t\tay2(i)(0) = I_tmp.lower();\n\t\t\tif (ay2(i)(0) > 0.) {\n\t\t\t\tfor (j=0; j<lp_size; j++) {\n\t\t\t\t\tay2(i)(j) = -ay2(i)(j);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n#endif\n\t\tfor (i=0; i<ep_size; i++) {\n\t\t\tay2(s + i).resize(lp_size);\n\t\t\tay2(s + i)(0) = -2.;\n\t\t\tfor (j=1; j<lp_size; j++) {\n\t\t\t\tay2(s + i)(j) = 0.;\n\t\t\t}\n\t\t\tay2(s + i)(1 + i) = 1.;\n\t\t\tay2(s + i)(ep_size + 1 + i) = 1.;\n\t\t}\n\t\tobjfunc_I.resize(lp_size);\n\t\tfor (j=0; j<lp_size; j++) objfunc_I(j) = 0.;\n\t\tfor (i=0; i<s + ep_size; i++) {\n\t\t\tfor (j=0; j<lp_size; j++) {\n\t\t\t\tobjfunc_I(j) -= ay2(i)(j);\n\t\t\t}\n\t\t}\n\t\tobjfunc.resize(lp_size);\n\t\tfor (j=0; j<lp_size; j++) {\n\t\t\tobjfunc(j) = objfunc_I(j).lower();\n\t\t}\n\n\t\tlp_flag = true;\n\t\tconstraints.clear();\n\t\tfor (i=0; i<s + ep_size; i++) {\n\t\t\tc_tmp.resize(lp_size);\n\t\t\tfor (j=0; j<lp_size; j++) {\n\t\t\t\tc_tmp(j) = ay2(i)(j);\n\t\t\t}\n\t\t\t/*\n\t\t\tif (c_tmp(0) >= 0.) {\n\t\t\t\tlp_flag = false;\n\t\t\t}\n\t\t\t*/\n\t\t\tconstraints.push_back(c_tmp);\n\t\t}\n\n\t\tif (lp_flag) {\n\t\t\tlp_return = lp_minimize_verified(objfunc, constraints, -1);\n\t\t\tif (lp_return > 0.) {\n\t\t\t\tcount_ne++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\t\n#endif\n\n#if USE_TRIM == 1\n\t\tIR = I;\n\t\tflag = false;\n\t\tflag2 = false;\n\t\tfor (i=0; i<s; i++) {\n\t\t\ttrim_tmp = rad(ay(i));\n\t\t\tfor (j=0; j<s; j++) {\n\t\t\t\ttmp = ay(i).get_coef(j+1);\n\t\t\t\tif (tmp == 0.) continue;\n\t\t\t\tif (tmp < 0.) tmp = -tmp;\n\t\t\t\trop<T>::begin();\n\t\t\t\ttmp = rop<T>::sub_up(trim_tmp, tmp);\n\t\t\t\trop<T>::end();\n\t\t\t\ttrim_I = ax(j).get_mid() - (ay(i).get_mid() + tmp * interval<T>(-1., 1.)) * ax(j).get_coef(j+1) / ay(i).get_coef(j+1);\n\t\t\t\tif (overlap(IR(j), trim_I)) {\n\t\t\t\t\tif (!subset(IR(j), trim_I)) {\n\t\t\t\t\t\tIR(j) = intersect(IR(j), trim_I);\n\t\t\t\t\t\tflag2 = true;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tflag = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (flag == true) break;\n\t\t}\n\n\t\tif (flag == true) {\n\t\t\tcount_ne++;\n\t\t\tcontinue;\n\t\t}\n#endif\n\n\t\t// existence test\n\n\t\tfor (i=0; i<s; i++) {\n\t\t\tfor (j=0; j<s; j++) {\n\t\t\t\tL(i, j) = ay(i).get_coef(j+1) / ax(j).get_coef(j+1);\n\t\t\t}\n\t\t}\n\n\t\tcount_ex_test++;\n\n\t\tr = invert(L, R);\n\t\tif (!r) goto label;\n\n\t\tak = ax - prod(R, ay);\n\t\tK = to_interval(ak);\n\n\t\tif (!overlap(K, I)) {\n\t\t\tcount_ne++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (proper_subset(K, I)) {\n\t\t\t// check whether the solution is already found or not\n\t\t\tflag = true;\n\t\t\tp = solutions.begin();\n\t\t\tp2 = solutions_big.begin();\n\t\t\twhile (p != solutions.end()) {\n\t\t\t\tif (overlap(K, *p)) {\n\t\t\t\t\tif (subset(K, *p2)||subset(*p, I)) {\n\t\t\t\t\t\tflag = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\taffine<T>::maxnum() = 0;\n\t\t\t\t\t\tax = K;\n\t\t\t\t\t\tay = f(ax);\n\t\t\t\t\t\t#if 0\n\t\t\t\t\t\tfor (i=0; i<s; i++) {\n\t\t\t\t\t\t\tfor (j=0; j<s; j++) {\n\t\t\t\t\t\t\t\tL(i, j) = ay(i).get_coef(j+1) / ax(j).get_coef(j+1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tinvert(L, R);\n\t\t\t\t\t\t#endif\n\t\t\t\t\t\tak = ax - prod(R, ay);\n\t\t\t\t\t\tI1 = to_interval(ak);\n\t\t\t\t\t\tK = intersect(K, I1);\n\t\t\t\t\t\tif (subset(K, *p2)) {\n\t\t\t\t\t\t\tflag2 = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!overlap(K, *p)) {\n\t\t\t\t\t\t\tflag2 = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (flag2 == true) {\n\t\t\t\t\t\tflag = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t/* never reach? */\n\t\t\t\t\t\tstd::cout << \"two overlap intervals includes different solutions\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tp++;\n\t\t\t\tp2++;\n\t\t\t}\n\t\t\tif (flag) { // new solution found\n\t\t\t\tif (verbose >= 1) std::cout << I << \"(ex)\\n\";\n\t\t\t\tsolutions_big.push_back(I);\n\t\t\t\t// iterative refinement\n\t\t\t\twhile (1) {\n\t\t\t\t\taffine<T>::maxnum() = 0;\n\t\t\t\t\tax = K;\n\t\t\t\t\tay = f(ax);\n\t\t\t\t\t#if 0\n\t\t\t\t\tfor (i=0; i<s; i++) {\n\t\t\t\t\t\tfor (j=0; j<s; j++) {\n\t\t\t\t\t\t\tL(i, j) = ay(i).get_coef(j+1) / ax(j).get_coef(j+1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tr = invert(L, R);\n\t\t\t\t\t#endif\n\t\t\t\t\tak = ax - prod(R, ay);\n\t\t\t\t\tI1 = to_interval(ak);\n\t\t\t\t\tI1 = intersect(K, I1);\n\t\t\t\t\ttmp = allsol_affine_sub::widthratio_min(I1, K);\n\t\t\t\t\tK = I1;\n\t\t\t\t\tif (tmp > 0.9) break;\n\t\t\t\t}\n\t\t\t\tsolutions.push_back(K);\n\t\t\t\tcount_ex++;\n\t\t\t\tif (verbose >= 1) std::cout << K << \"(ex:improved)\\n\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\t// check the case that solution may exist near boundary.\n\t\t// If so, use K as next interval\n\t\tif (allsol_affine_sub::widthratio_max(K, I) < 0.9) {\n\t\t\ttargets.push_back(K);\n\t\t\tcount_unknown++;\n\t\t\tcontinue;\n\t\t}\n\n#if USE_TRIM == 1\n\t\tif (!overlap(IR, K)) {\n\t\t\tcount_ne++;\n\t\t\tcontinue;\n\t\t} else {\n\t\t\tI = intersect(IR, K);\n\t\t}\n#else\n\t\tI = intersect(I, K);\n#endif\n\n\t\tlabel:\n\n\t\t// divide interval\n\n\t\tmi = allsol_affine_sub::search_maxwidth(I);\n\n\t\ttmp = mid(I(mi));\n\t\tif (tmp == I(mi).lower() || tmp == I(mi).upper()) {\n\t\t\tstd::cout << \"too small interval (may be multiple root?):\\n\" << I << \"\\n\";\n\t\t\tcontinue;\n\t\t}\n\n\t\tI1 = I; I2 = I;\n\t\tI1(mi).assign(I1(mi).lower(), tmp);\n\t\tI2(mi).assign(tmp, I2(mi).upper());\n\t\ttargets.push_back(I1);\n\t\ttargets.push_back(I2);\n\t\tcount_unknown += 2;\n\t}\n\n\tif (verbose >= 1) {\n\t\t\tstd::cout << \"ne_test: \" << count_ne_test << \", ex_test: \" << count_ex_test << \", ne: \" << count_ne << \", ex: \" << count_ex << \"    \\n\";\n\t}\n\n\treturn solutions;\n}\n\n} // namespace kv\n\n#endif // ALLSOL_AFFINE_HPP\n", "meta": {"hexsha": "702e11eddcab9a20e73dad0d136c801fb4282835", "size": 10135, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/allsol-affine.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "src/interval/kv/allsol-affine.hpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "src/interval/kv/allsol-affine.hpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 20.6415478615, "max_line_length": 187, "alphanum_fraction": 0.5366551554, "num_tokens": 3658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.6334102636778401, "lm_q1q2_score": 0.41032204004308115}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file mcgaussian1dnonstandardswaptionengine.hpp\n    \\brief Monte Carlo engine for bermudan (non standard) swaptions\n           in a gaussian 1d model\n*/\n\n#ifndef quantlib_mc_gaussian1d_nonstandardswaption_engine_hpp\n#define quantlib_mc_gaussian1d_nonstandardswaption_engine_hpp\n\n#include <ql/pricingengines/genericmodelengine.hpp>\n#include <ql/pricingengines/mclongstaffschwartzengine.hpp>\n#include <ql/experimental/models/longstaffschwartzproxypathpricer.hpp>\n#include <ql/termstructures/yield/flatforward.hpp>\n#include <ql/instruments/nonstandardswaption.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\n/*! All fixed coupons with start date greater or equal to the\n    respective option expiry are considered to be part of the\n    exercise into right.\n\n    \\warning Cash settled swaptions are not supported\n*/\n\ntemplate <class RNG = PseudoRandom, class S = Statistics>\nclass McGaussian1dNonstandardSwaptionEngine\n    : public MCLongstaffSchwartzEngine<\n          GenericModelEngine<Gaussian1dModel, NonstandardSwaption::arguments,\n                             NonstandardSwaption::results>,\n          SingleVariate, RNG, S> {\n\n  public:\n    typedef MCLongstaffSchwartzEngine<\n        GenericModelEngine<Gaussian1dModel, NonstandardSwaption::arguments,\n                           NonstandardSwaption::results>,\n        SingleVariate, RNG, S> base_class;\n\n    /*! proxy function */\n    struct LsFunction : NonstandardSwaption::Proxy::ProxyFunction {\n        Real operator()(const Real state) const {\n            Real tmp = 0.0;\n            if (state > cutoff) {\n                for (Size i = 0; i < coeffItm.size(); ++i)\n                    tmp += coeffItm[i] * v[i](state);\n            } else {\n                for (Size i = 0; i < coeffOtm.size(); ++i)\n                    tmp += coeffOtm[i] * v[i](state);\n            }\n            return std::max(tmp, 0.0); // continuation value is always positive\n        }\n        Array coeffItm, coeffOtm;\n        Real cutoff;\n        std::vector<boost::function1<Real, Real> > v;\n    };\n\n    McGaussian1dNonstandardSwaptionEngine(\n        const boost::shared_ptr<Gaussian1dModel> &model,\n        const Handle<Quote>\n            &oas, // continuously compounded w.r.t. yts daycounter\n        const Handle<YieldTermStructure> &discountCurve,\n        Size timeSteps, Size timeStepsPerYear, bool brownianBridge,\n        bool antitheticVariate, Size requiredSamples, Real requiredTolerance,\n        Size maxSamples, BigNatural seed, Size nCalibrationSamples,\n        bool generateProxy);\n\n    void calculate() const;\n    void reset() const;\n\n  protected:\n    boost::shared_ptr<LongstaffSchwartzPathPricer<Path> > lsmPathPricer() const;\n\n  private:\n    boost::shared_ptr<Gaussian1dModel> model_;\n    Handle<Quote> oas_;\n    Handle<YieldTermStructure> discountCurve_;\n    bool generateProxy_;\n    mutable boost::shared_ptr<NonstandardSwaption::Proxy> proxy_;\n};\n\n//! factory\n\ntemplate <class RNG = PseudoRandom, class S = Statistics>\nclass MakeMcGaussian1dNonstandardSwaptionEngine {\n  public:\n    MakeMcGaussian1dNonstandardSwaptionEngine(\n        const boost::shared_ptr<Gaussian1dModel> &model);\n    MakeMcGaussian1dNonstandardSwaptionEngine &withSteps(Size steps);\n    MakeMcGaussian1dNonstandardSwaptionEngine &withStepsPerYear(Size steps);\n    MakeMcGaussian1dNonstandardSwaptionEngine &\n    withBrownianBridge(bool b = true);\n    MakeMcGaussian1dNonstandardSwaptionEngine &\n    withAntitheticVariate(bool b = true);\n    MakeMcGaussian1dNonstandardSwaptionEngine &withSamples(Size samples);\n    MakeMcGaussian1dNonstandardSwaptionEngine &\n    withAbsoluteTolerance(Real tolerance);\n    MakeMcGaussian1dNonstandardSwaptionEngine &withMaxSamples(Size samples);\n    MakeMcGaussian1dNonstandardSwaptionEngine &withSeed(BigNatural seed);\n    MakeMcGaussian1dNonstandardSwaptionEngine &\n    withCalibrationSamples(Size calibrationSamples);\n    MakeMcGaussian1dNonstandardSwaptionEngine &\n    withOas(const Handle<Quote> &oas);\n    MakeMcGaussian1dNonstandardSwaptionEngine &\n    withDiscount(const Handle<YieldTermStructure> &discount);\n    MakeMcGaussian1dNonstandardSwaptionEngine &withProxy(bool b = true);\n    // conversion to pricing engine\n    operator boost::shared_ptr<PricingEngine>() const;\n\n  private:\n    boost::shared_ptr<Gaussian1dModel> model_;\n    Handle<Quote> oas_;\n    Handle<YieldTermStructure> discount_;\n    bool brownianBridge_, antithetic_;\n    Size steps_, stepsPerYear_, samples_, calibrationSamples_, maxSamples_;\n    Real tolerance_;\n    BigNatural seed_;\n    bool generateProxy_;\n};\n\n//! Path Pricer\n\nclass Gaussian1dNonstandardSwaptionPathPricer\n    : public EarlyExercisePathPricer<Path> {\n  public:\n    Gaussian1dNonstandardSwaptionPathPricer(\n        const boost::shared_ptr<Gaussian1dModel> &model,\n        const NonstandardSwaption::arguments *arguments,\n        const Handle<YieldTermStructure> &discount, const Handle<Quote> &oas);\n    Real operator()(const Path &path, Size t) const;\n    Real state(const Path &path, Size t) const;\n    std::vector<boost::function1<Real, Real> > basisSystem() const;\n    std::vector<boost::function1<Real, Real> > basisSystem2() const;\n\n  private:\n    void initExerciseIndices(const Path &path) const;\n    const boost::shared_ptr<Gaussian1dModel> model_;\n    const NonstandardSwaption::arguments *arguments_;\n    const Handle<YieldTermStructure> discount_;\n    const Handle<Quote> oas_;\n    std::vector<boost::function1<Real, Real> > basis_, basis2_;\n    mutable std::vector<Size> exerciseIdx_;\n    Size minIdxAlive_;\n};\n\n// implementation\n\ntemplate <class RNG, class S>\nMcGaussian1dNonstandardSwaptionEngine<RNG, S>::\n    McGaussian1dNonstandardSwaptionEngine(\n        const boost::shared_ptr<Gaussian1dModel> &model,\n        const Handle<Quote>\n            &oas, // continuously compounded w.r.t. yts daycounter\n        const Handle<YieldTermStructure> &discountCurve,\n        Size timeSteps, Size timeStepsPerYear, bool brownianBridge,\n        bool antitheticVariate, Size requiredSamples, Real requiredTolerance,\n        Size maxSamples, BigNatural seed, Size nCalibrationSamples,\n        bool generateProxy)\n    : MCLongstaffSchwartzEngine<\n          GenericModelEngine<Gaussian1dModel, NonstandardSwaption::arguments,\n                             NonstandardSwaption::results>,\n          SingleVariate, RNG, S>(\n          model->stateProcess(), timeSteps, timeStepsPerYear, brownianBridge,\n          antitheticVariate, false, requiredSamples, requiredTolerance,\n          maxSamples, seed, nCalibrationSamples),\n      model_(model), oas_(oas), discountCurve_(discountCurve),\n      generateProxy_(generateProxy) {\n\n    if (!oas_.empty())\n        this->registerWith(oas_);\n    if (!discountCurve_.empty())\n        this->registerWith(discountCurve_);\n}\n\ntemplate <class RNG, class S>\nvoid McGaussian1dNonstandardSwaptionEngine<RNG, S>::calculate() const {\n// a lazy object is not thread safe, neither is the caching\n// in gsrprocess. therefore we trigger computations here such\n// that neither lazy object recalculation nor write access\n// during caching occurs in the parallized loop in MonteCarloModel\n#ifdef _OPENMP\n    boost::shared_ptr<LongstaffSchwartzPathPricer<Path> > tmp =\n        this->lsmPathPricer();\n    tmp->calibrate();\n    model_->numeraire(1.0);\n    tmp->operator()(this->pathGenerator()->next().value);\n#endif\n    // continue with usual calculations\n    base_class::calculate();\n    // transform the deflated values into plain ones\n    this->results_.value *= model_->numeraire(0.0, 0.0, discountCurve_);\n    this->results_.errorEstimate *= model_->numeraire(0.0, 0.0, discountCurve_);\n    if (generateProxy_) {\n        // generate proxy\n        this->proxy_ = boost::make_shared<NonstandardSwaption::Proxy>();\n        Date today = Settings::instance().evaluationDate();\n        // original evaluation date\n        // open expiry dates\n        std::vector<Date>::const_iterator start =\n            std::upper_bound(this->arguments_.exercise->dates().begin(),\n                             this->arguments_.exercise->dates().end(), today);\n        for (std::vector<Date>::const_iterator i = start;\n             i != this->arguments_.exercise->dates().end(); ++i) {\n            this->proxy_->expiryDates.push_back(*i);\n        }\n        // model\n        this->proxy_->model = model_;\n        // discount curve (may be empty)\n        this->proxy_->discount = discountCurve_;\n        // oas (may be empty)\n        this->proxy_->oas = oas_;\n        // regression functions for values\n        for (int i = 0; i < static_cast<int>(this->proxy_->expiryDates.size());\n             ++i) {\n            boost::shared_ptr<LsFunction> lsTmp =\n                boost::make_shared<LsFunction>();\n            boost::shared_ptr<LongstaffSchwartzProxyPathPricer> pathPricer =\n                boost::dynamic_pointer_cast<LongstaffSchwartzProxyPathPricer>(\n                    this->pathPricer_);\n            lsTmp->coeffItm = pathPricer->coefficientsItm()[i];\n            lsTmp->coeffOtm = pathPricer->coefficientsOtm()[i];\n            lsTmp->cutoff = pathPricer->cutoff();\n            lsTmp->v = pathPricer->basisSystem();\n            this->proxy_->regression.push_back(lsTmp);\n        }\n        this->results_.proxy = this->proxy_;\n    }\n}\n\ntemplate <class RNG, class S>\nvoid McGaussian1dNonstandardSwaptionEngine<RNG, S>::reset() const {\n    base_class::reset();\n    this->proxy_ = boost::shared_ptr<NonstandardSwaption::Proxy>();\n}\n\ntemplate <class RNG, class S>\nboost::shared_ptr<LongstaffSchwartzPathPricer<Path> >\nMcGaussian1dNonstandardSwaptionEngine<RNG, S>::lsmPathPricer() const {\n\n    // reduced grid which only contains the exercise times and 0\n    std::vector<Real> exerciseTimes;\n    exerciseTimes.push_back(0.0);\n    for (Size i = 0; i < this->arguments_.exercise->dates().size(); ++i) {\n        Time tmp =\n            model_->stateProcess()->time(this->arguments_.exercise->date(i));\n        if (tmp > 0.0) {\n            exerciseTimes.push_back(tmp);\n        }\n    }\n    TimeGrid exerciseGrid =\n        TimeGrid(exerciseTimes.begin(), exerciseTimes.end());\n    boost::shared_ptr<Gaussian1dNonstandardSwaptionPathPricer>\n        earlyExercisePricer =\n            boost::make_shared<Gaussian1dNonstandardSwaptionPathPricer>(\n                model_, &this->arguments_, discountCurve_, oas_);\n    // we work with deflated npvs produced in the early exercise pricer\n    // so we pass a dummyCurve, which produces discount factors of 1.0 always\n    boost::shared_ptr<YieldTermStructure> dummyCurve =\n        boost::make_shared<FlatForward>(0, NullCalendar(), 0.0,\n                                        Actual365Fixed());\n    if (generateProxy_) {\n        return boost::make_shared<LongstaffSchwartzProxyPathPricer>(\n            exerciseGrid, earlyExercisePricer, dummyCurve);\n    } else {\n        return boost::make_shared<LongstaffSchwartzPathPricer<Path> >(\n            exerciseGrid, earlyExercisePricer, dummyCurve);\n    }\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::\n    MakeMcGaussian1dNonstandardSwaptionEngine(\n        const boost::shared_ptr<Gaussian1dModel> &model)\n    : model_(model), oas_(Handle<Quote>()),\n      discount_(Handle<YieldTermStructure>()), brownianBridge_(false),\n      antithetic_(false), steps_(Null<Size>()), stepsPerYear_(Null<Size>()),\n      samples_(Null<Size>()), calibrationSamples_(Null<Size>()),\n      maxSamples_(Null<Size>()), tolerance_(Null<Real>()), seed_(0),\n      generateProxy_(false) {}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S> &\nMakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::withSteps(Size steps) {\n    steps_ = steps;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S> &\nMakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::withStepsPerYear(\n    Size steps) {\n    stepsPerYear_ = steps;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S> &\nMakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::withBrownianBridge(\n    bool brownianBridge) {\n    brownianBridge_ = brownianBridge;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S> &\nMakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::withAntitheticVariate(\n    bool b) {\n    antithetic_ = b;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S> &\nMakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::withSamples(Size samples) {\n    QL_REQUIRE(tolerance_ == Null<Real>(), \"tolerance already set\");\n    samples_ = samples;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S> &\nMakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::withCalibrationSamples(\n    Size samples) {\n    calibrationSamples_ = samples;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S> &\nMakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::withAbsoluteTolerance(\n    Real tolerance) {\n    QL_REQUIRE(samples_ == Null<Size>(), \"number of samples already set\");\n    QL_REQUIRE(RNG::allowsErrorEstimate, \"chosen random generator policy \"\n                                         \"does not allow an error estimate\");\n    tolerance_ = tolerance;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S> &\nMakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::withMaxSamples(\n    Size samples) {\n    maxSamples_ = samples;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S> &\nMakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::withSeed(BigNatural seed) {\n    seed_ = seed;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S> &\nMakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::withOas(\n    const Handle<Quote> &oas) {\n    oas_ = oas;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S> &\nMakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::withDiscount(\n    const Handle<YieldTermStructure> &discount) {\n    discount_ = discount;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S> &\nMakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::withProxy(bool b) {\n    generateProxy_ = b;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcGaussian1dNonstandardSwaptionEngine<RNG, S>::\noperator boost::shared_ptr<PricingEngine>() const {\n    QL_REQUIRE(steps_ != Null<Size>() || stepsPerYear_ != Null<Size>(),\n               \"number of steps not given\");\n    QL_REQUIRE(steps_ == Null<Size>() || stepsPerYear_ == Null<Size>(),\n               \"number of steps overspecified\");\n    return boost::shared_ptr<PricingEngine>(\n        new McGaussian1dNonstandardSwaptionEngine<RNG, S>(\n            model_, oas_, discount_, steps_, stepsPerYear_, brownianBridge_,\n            antithetic_, samples_, tolerance_, maxSamples_, seed_,\n            calibrationSamples_, generateProxy_));\n}\n\n} // namespace QuantLib\n\n#endif\n", "meta": {"hexsha": "c75a6d0fcf59c700ebcec4337e0c01ba3fbf1139", "size": 16013, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/mcgaussian1dnonstandardswaptionengine.hpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/experimental/models/mcgaussian1dnonstandardswaptionengine.hpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/experimental/models/mcgaussian1dnonstandardswaptionengine.hpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 38.8665048544, "max_line_length": 80, "alphanum_fraction": 0.7051770437, "num_tokens": 4053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8539127492339909, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.41028686892020183}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <ql/exercise.hpp>\n#include <ql/pricingengines/blackformula.hpp>\n#include <ql/time/calendars/nullcalendar.hpp>\n#include <qle/models/fxeqoptionhelper.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantExt {\n\nFxEqOptionHelper::FxEqOptionHelper(const Period& maturity, const Calendar& calendar, const Real strike,\n                                   const Handle<Quote> spot, const Handle<Quote> volatility,\n                                   const Handle<YieldTermStructure>& domesticYield,\n                                   const Handle<YieldTermStructure>& foreignYield,\n                                   BlackCalibrationHelper::CalibrationErrorType errorType)\n    : BlackCalibrationHelper(volatility, errorType), termStructure_(domesticYield), hasMaturity_(true),\n      maturity_(maturity), calendar_(calendar), strike_(strike), spot_(spot), foreignYield_(foreignYield) {\n    registerWith(spot_);\n    registerWith(foreignYield_);\n}\n\nFxEqOptionHelper::FxEqOptionHelper(const Date& exerciseDate, const Real strike, const Handle<Quote> spot,\n                                   const Handle<Quote> volatility, const Handle<YieldTermStructure>& domesticYield,\n                                   const Handle<YieldTermStructure>& foreignYield,\n                                   BlackCalibrationHelper::CalibrationErrorType errorType)\n    : BlackCalibrationHelper(volatility, errorType), termStructure_(domesticYield), hasMaturity_(false),\n      exerciseDate_(exerciseDate), strike_(strike), spot_(spot), foreignYield_(foreignYield) {\n    registerWith(spot_);\n    registerWith(foreignYield_);\n}\n\nvoid FxEqOptionHelper::performCalculations() const {\n    if (hasMaturity_)\n        exerciseDate_ = calendar_.advance(termStructure_->referenceDate(), maturity_);\n    tau_ = termStructure_->timeFromReference(exerciseDate_);\n    atm_ = spot_->value() * foreignYield_->discount(tau_) / termStructure_->discount(tau_);\n    effStrike_ = strike_;\n    if (effStrike_ == Null<Real>())\n        effStrike_ = atm_;\n    type_ = effStrike_ >= atm_ ? Option::Call : Option::Put;\n    boost::shared_ptr<StrikedTypePayoff> payoff(new PlainVanillaPayoff(type_, effStrike_));\n    boost::shared_ptr<Exercise> exercise = boost::make_shared<EuropeanExercise>(exerciseDate_);\n    option_ = boost::shared_ptr<VanillaOption>(new VanillaOption(payoff, exercise));\n    BlackCalibrationHelper::performCalculations();\n}\n\nReal FxEqOptionHelper::modelValue() const {\n    calculate();\n    option_->setPricingEngine(engine_);\n    return option_->NPV();\n}\n\nReal FxEqOptionHelper::blackPrice(Real volatility) const {\n    calculate();\n    const Real stdDev = volatility * std::sqrt(tau_);\n    return blackFormula(type_, effStrike_, atm_, stdDev, termStructure_->discount(tau_));\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "f3ce9037d24fbc0dbd6c6d0c244e1d9746fcf912", "size": 3524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/models/fxeqoptionhelper.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/models/fxeqoptionhelper.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/models/fxeqoptionhelper.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 45.7662337662, "max_line_length": 115, "alphanum_fraction": 0.7196367764, "num_tokens": 784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.4102750180121374}}
{"text": "#include <mvp/Core/ConvexPolygon.h>\n\n#include <boost/foreach.hpp>\n\nnamespace mvp {\nnamespace core {\n\nConvexPolygon::ConvexPolygon(VertexList pts) {\n  // Algorithm is the 'giftwrap' algorithm http://www.cse.unsw.edu.au/~lambert/java/3d/giftwrap.html\n  // Probably not the most efficient implementation...\n  VW_ASSERT(pts.size() >= 3, vw::ArgumentErr() << \"Need at least 3 points to construct a polygon!\");\n\n  vw::Vector2 end = pts[0];\n  BOOST_FOREACH(vw::Vector2 const& v, pts) {\n    if (end.y() < v.y()) {\n      end = v;\n    }\n  }\n\n  bool done = false;\n  vw::Vector2 curr = end;\n\n  while (!done) {\n    bool found_next = false;\n    BOOST_FOREACH(vw::Vector2 const& next, pts) {\n      if (curr != next) {\n        found_next = true;\n        BOOST_FOREACH(vw::Vector2 const& pt, pts) {\n          if (circulation_direction(curr, next, pt) > 0 && pt != next) {\n            found_next = false;\n            break;\n          }\n        }\n        if (found_next) {\n          curr = next;\n          break;\n        }\n      }\n    }\n\n    VW_ASSERT(found_next, vw::LogicErr() << \"Unable to construct convex hull\");\n\n    m_vertices.push_back(curr);\n    if (curr == end) {\n      done = true;\n    }\n  }\n}\n\nConvexPolygon::ConvexPolygon(vw::BBox2 const& bbox) : m_vertices(4) {\n  m_vertices[0] = bbox.max();\n  m_vertices[1] = vw::Vector2(bbox.max().x(), bbox.min().y());\n  m_vertices[2] = bbox.min();\n  m_vertices[3] = vw::Vector2(bbox.min().x(), bbox.max().y());\n}\n\nvw::BBox2 ConvexPolygon::bounding_box() const {\n  vw::BBox2 bbox;\n\n  BOOST_FOREACH(vw::Vector2 const& v, m_vertices) {\n    bbox.grow(v);\n  }\n\n  return bbox;\n}\n\nbool ConvexPolygon::contains(vw::Vector2 const& pt) const {\n  // Use solution 3 from http://paulbourke.net/geometry/insidepoly/\n  for (VertexList::const_iterator curr = m_vertices.begin(); curr != m_vertices.end(); curr++) {\n    VertexList::const_iterator next = curr;\n    if (++next == m_vertices.end()) {\n      next = m_vertices.begin();\n    }\n\n    double circulation = circulation_direction(*curr, *next, pt);\n\n    // Round to zero if close... (assume colinear)\n    circulation = circulation * circulation < 1e-6 ? 0 : circulation;\n\n    if (circulation > 0) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nbool ConvexPolygon::intersects(ConvexPolygon const& other) const {\n  // Algorithm from http://www.gpwiki.org/index.php/Polygon_Collision\n  // Straight up dumb check, no optimizations attempted...\n\n  for (VertexList::const_iterator cursor = m_vertices.begin(); cursor != m_vertices.end(); cursor++) {\n    VertexList::const_iterator next = cursor;\n    if (++next == m_vertices.end()) {\n      next = m_vertices.begin();\n    }\n\n    vw::Vector2 dir = *next - *cursor;\n    vw::Vector2 perp_dir(-dir[1], dir[0]);\n\n    double poly1_min = std::numeric_limits<double>::max();\n    double poly1_max = std::numeric_limits<double>::min();\n    BOOST_FOREACH(vw::Vector2 const& v, m_vertices) {\n      double res = dot_prod(perp_dir, v);\n      poly1_min = std::min(res, poly1_min);\n      poly1_max = std::max(res, poly1_max);\n    }\n\n    double poly2_min = std::numeric_limits<double>::max();\n    double poly2_max = std::numeric_limits<double>::min();\n    BOOST_FOREACH(vw::Vector2 const& v, other.m_vertices) {\n      double res = dot_prod(perp_dir, v);\n      poly2_min = std::min(res, poly2_min);\n      poly2_max = std::max(res, poly2_max);\n    }\n\n    if (poly1_min > poly2_max || poly1_max < poly2_min) {\n      return false;\n    }\n  }\n\n  return true;  \n}\n\n}} // namespace core,mvp\n", "meta": {"hexsha": "4b8e8b8583645e0eb7dede5ec9b1f77cc69fabcc", "size": 3483, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/mvp/Core/ConvexPolygon.cc", "max_stars_repo_name": "NeoGeographyToolkit/MultipleViewPipeline", "max_stars_repo_head_hexsha": "c2ad4ebb7555a1157616389466c7075e0c61292a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-05-13T22:52:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T12:09:44.000Z", "max_issues_repo_path": "src/mvp/Core/ConvexPolygon.cc", "max_issues_repo_name": "NeoGeographyToolkit/MultipleViewPipeline", "max_issues_repo_head_hexsha": "c2ad4ebb7555a1157616389466c7075e0c61292a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mvp/Core/ConvexPolygon.cc", "max_forks_repo_name": "NeoGeographyToolkit/MultipleViewPipeline", "max_forks_repo_head_hexsha": "c2ad4ebb7555a1157616389466c7075e0c61292a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T02:11:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T18:35:20.000Z", "avg_line_length": 27.6428571429, "max_line_length": 102, "alphanum_fraction": 0.6233132357, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.41027501801213734}}
{"text": "#ifndef MANUALPHASE_HPP\n#define MANUALPHASE_HPP\n\n#include <set>\n#include <cmath>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\nnamespace raisim\n{\n    constexpr int n_gait = 9;\n\n    template<typename T>\n    class ManualPhase\n    {\n    public:\n        ManualPhase()\n        {\n            for (int i = 0; i < n_gait; ++i)\n            {\n                TIME[i] = UNIT[i] * unit_time_;\n                STANCE_TIME[i] = DUTY_UNIT[i] * unit_time_ / (UNIT[i] / 2.0);\n            }\n\n            reset();\n        }\n\n        Eigen::Matrix<T, Eigen::Dynamic, 1> get_raw_phase()\n        {\n            phase_raw_.setZero();\n            for (int i = 0; i < 4; ++i)\n            {\n                phase_raw_[i] = std::atan2(q_[2 * i + 1], q_[2 * i]);\n            }\n            return phase_raw_;\n        }\n\n        Eigen::Matrix<T, 4, 1> get_omega()\n        {\n            return omega_;\n        }\n\n        int get_hold_leg()\n        {\n            // not implemented in manual phase\n            return -1;\n        }\n\n        bool get_transition_status()\n        {\n            // not implemented in manual phase\n            return false;\n        }\n\n        inline void three_leg_mode(int leg)\n        {\n            // not implemented in manual phase\n            ;\n        }\n\n        inline void change_gait(int gait_idx)\n        {\n            target_gait_idx_ = gait_idx;\n        }\n\n        inline void change_gait_()\n        {\n            if (target_gait_idx_ != gait_idx_ && std::fabs(phase_scalar_) <= dt_ / 2.0)\n            {\n                gait_idx_ = target_gait_idx_;\n            }\n        }\n\n        inline int get_gait_index()\n        {\n            return gait_idx_;            \n        }\n\n        inline T get_stance_time()\n        {\n            return STANCE_TIME[gait_idx_];\n        }\n\n        inline void reset()\n        {\n            unit_ = UNIT[0];\n            time_ = TIME[0];\n            duty_unity_ = DUTY_UNIT[0];\n            stance_time_ = STANCE_TIME[0];\n            \n            q_ << 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0;\n            q_dot_.setZero();\n\n            phase_raw_ << - M_PI / 2.0, - M_PI / 2.0, - M_PI / 2.0, - M_PI / 2.0;\n            phase_ = {0.0, 0.0, 0.0, 0.0};\n            omega_ << - M_PI / unit_time_, - M_PI / unit_time_, - M_PI / unit_time_, - M_PI / unit_time_;\n\n            phase_scalar_ = 0.0;\n        }\n\n        inline void step()\n        {\n            if (phase_scalar_ > TIME[gait_idx_])\n            {\n                phase_scalar_ = 0.0;\n            }\n            change_gait_();\n\n            get_q_and_q_dot();\n\n            phase_scalar_ += dt_;\n        }\n\n        inline void get_q_and_q_dot()\n        {\n            if (gait_idx_ == 0)\n            {\n                T theta = - phase_scalar_ / unit_time_ * M_PI + M_PI;\n                for (int i = 0; i < 4; ++i)\n                {\n                    q_[2 * i] = std::cos(theta);\n                    q_[2 * i + 1] = std::sin(theta);\n                }\n                omega_.setConstant(- M_PI / unit_time_);\n            }\n\n            if (gait_idx_ == 1)\n            {\n                T theta_fast = - phase_scalar_ / unit_time_ * M_PI + M_PI;\n                T theta_slow = - phase_scalar_ / unit_time_ * M_PI / 3;\n\n                if (phase_scalar_ / unit_time_ < 3)\n                {\n                    // 0, 3\n                    q_[0] = std::cos(theta_slow);\n                    q_[1] = std::sin(theta_slow);\n                    q_[6] = std::cos(theta_slow);\n                    q_[7] = std::sin(theta_slow);\n\n                    omega_[0] = - M_PI / unit_time_ / 3;\n                    omega_[3] = - M_PI / unit_time_ / 3;\n\n                    // 1, 2\n                    q_[2] = std::cos(theta_fast);\n                    q_[3] = std::sin(theta_fast);\n                    q_[4] = std::cos(theta_fast);\n                    q_[5] = std::sin(theta_fast);\n\n                    omega_[1] = - M_PI / unit_time_;\n                    omega_[2] = - M_PI / unit_time_;\n                }\n                else\n                {\n                    theta_fast += M_PI;\n                    theta_slow += M_PI;\n\n                    // 0, 3\n                    q_[0] = std::cos(theta_fast);\n                    q_[1] = std::sin(theta_fast);\n                    q_[6] = std::cos(theta_fast);\n                    q_[7] = std::sin(theta_fast);\n\n                    omega_[0] = - M_PI / unit_time_;\n                    omega_[3] = - M_PI / unit_time_;\n\n                    // 1, 2\n                    q_[2] = std::cos(theta_slow);\n                    q_[3] = std::sin(theta_slow);\n                    q_[4] = std::cos(theta_slow);\n                    q_[5] = std::sin(theta_slow);\n\n                    omega_[1] = - M_PI / unit_time_ / 3;\n                    omega_[2] = - M_PI / unit_time_ / 3;\n                }\n            }\n\n            if (gait_idx_ == 2)\n            {\n                T theta_fast = - phase_scalar_ / unit_time_ * M_PI + M_PI;\n                T theta_slow = - phase_scalar_ / unit_time_ * M_PI / 2 - M_PI / 2;\n\n                // 0, 3\n                q_[0] = std::cos(theta_slow);\n                q_[1] = std::sin(theta_slow);\n                q_[6] = std::cos(theta_slow);\n                q_[7] = std::sin(theta_slow);\n\n                omega_[0] = - M_PI / unit_time_ / 2;\n                omega_[3] = - M_PI / unit_time_ / 2;\n\n                // 1, 2\n                q_[2] = std::cos(theta_fast);\n                q_[3] = std::sin(theta_fast);\n                q_[4] = std::cos(theta_fast);\n                q_[5] = std::sin(theta_fast);\n\n                omega_[1] = - M_PI / unit_time_;\n                omega_[2] = - M_PI / unit_time_;\n            }\n\n            if (gait_idx_ == 3)\n            {\n                T theta_fast = - phase_scalar_ / unit_time_ * M_PI + M_PI;\n                T theta_slow = - phase_scalar_ / unit_time_ * M_PI / 2 - M_PI;\n\n                // 0, 3\n                q_[0] = std::cos(theta_fast);\n                q_[1] = std::sin(theta_fast);\n                q_[6] = std::cos(theta_fast);\n                q_[7] = std::sin(theta_fast);\n\n                omega_[0] = - M_PI / unit_time_;\n                omega_[3] = - M_PI / unit_time_;\n\n                // 1, 2\n                q_[2] = std::cos(theta_slow);\n                q_[3] = std::sin(theta_slow);\n                q_[4] = std::cos(theta_slow);\n                q_[5] = std::sin(theta_slow);\n\n                omega_[0] = - M_PI / unit_time_ / 2;\n                omega_[3] = - M_PI / unit_time_ / 2;\n            }\n\n            if (gait_idx_ == 4)\n            {\n                T theta_fast = - phase_scalar_ / unit_time_ * M_PI + M_PI;\n                T theta_slow = - phase_scalar_ / unit_time_ * M_PI / 3.0 + M_PI;\n\n                // 0, 3\n                q_[0] = std::cos(theta_fast);\n                q_[1] = std::sin(theta_fast);\n                q_[6] = std::cos(theta_fast);\n                q_[7] = std::sin(theta_fast);\n\n                omega_[0] = - M_PI / unit_time_;\n                omega_[3] = - M_PI / unit_time_;\n\n                // 1, 2\n                q_[2] = std::cos(theta_slow);\n                q_[3] = std::sin(theta_slow);\n                q_[4] = std::cos(theta_slow);\n                q_[5] = std::sin(theta_slow);\n\n                omega_[0] = - M_PI / unit_time_ / 3;\n                omega_[3] = - M_PI / unit_time_ / 3;\n            }\n\n            if (gait_idx_ == 5)\n            {\n                T theta_fast = - phase_scalar_ / unit_time_ * M_PI + M_PI;\n                T theta_slow = - phase_scalar_ / unit_time_ * M_PI / 3.0 + M_PI * 2.0 / 3.0;\n\n                // 0, 3\n                q_[0] = std::cos(theta_slow);\n                q_[1] = std::sin(theta_slow);\n                q_[6] = std::cos(theta_slow);\n                q_[7] = std::sin(theta_slow);\n\n                omega_[0] = - M_PI / unit_time_ / 3;\n                omega_[3] = - M_PI / unit_time_ / 3;\n\n                // 1, 2\n                q_[2] = std::cos(theta_fast);\n                q_[3] = std::sin(theta_fast);\n                q_[4] = std::cos(theta_fast);\n                q_[5] = std::sin(theta_fast);\n\n                omega_[1] = - M_PI / unit_time_;\n                omega_[2] = - M_PI / unit_time_;\n            }\n\n            if (gait_idx_ == 6)\n            {\n                T theta_1 = - phase_scalar_ / unit_time_ * M_PI / 2.0 + M_PI;\n                T theta_2 = - phase_scalar_ / unit_time_ * M_PI / 2.0 + M_PI / 2.0;\n\n                // 0, 3\n                q_[0] = std::cos(theta_1);\n                q_[1] = std::sin(theta_1);\n                q_[6] = std::cos(theta_1);\n                q_[7] = std::sin(theta_1);\n\n                omega_[0] = - M_PI / unit_time_ / 2;\n                omega_[3] = - M_PI / unit_time_ / 2;\n\n                // 1, 2\n                q_[2] = std::cos(theta_2);\n                q_[3] = std::sin(theta_2);\n                q_[4] = std::cos(theta_2);\n                q_[5] = std::sin(theta_2);\n\n                omega_[0] = - M_PI / unit_time_ / 2;\n                omega_[3] = - M_PI / unit_time_ / 2;\n            }\n\n            if (gait_idx_ == 7)\n            {\n                if (phase_scalar_ / unit_time_ < 2.0)\n                {\n                    T theta_1 = - phase_scalar_ / unit_time_ * M_PI + M_PI;\n\n                    // 0, 3\n                    q_[0] = std::cos(theta_1);\n                    q_[1] = std::sin(theta_1);\n                    q_[6] = std::cos(theta_1);\n                    q_[7] = std::sin(theta_1);\n\n                    omega_[0] = - M_PI / unit_time_;\n                    omega_[3] = - M_PI / unit_time_;\n                }\n                else\n                {\n                    T theta_1 = - (phase_scalar_ / unit_time_ - 2.0) * M_PI / 2.0 + M_PI;\n                    \n                    // 0, 3\n                    q_[0] = std::cos(theta_1);\n                    q_[1] = std::sin(theta_1);\n                    q_[6] = std::cos(theta_1);\n                    q_[7] = std::sin(theta_1);\n\n                    omega_[0] = - M_PI / unit_time_ / 2.0;\n                    omega_[3] = - M_PI / unit_time_ / 2.0;\n                }\n\n                if (phase_scalar_ / unit_time_ < 3.0 || phase_scalar_ / unit_time_ >= 5.0)\n                {\n                    T theta_2 = phase_scalar_ / unit_time_ < 3.0 ? - (phase_scalar_ / unit_time_ + 1.0) * M_PI / 2.0 + M_PI :  - (phase_scalar_ / unit_time_ - 5.0) * M_PI / 2.0 + M_PI;\n                    \n                    // 1, 2\n                    q_[2] = std::cos(theta_2);\n                    q_[3] = std::sin(theta_2);\n                    q_[4] = std::cos(theta_2);\n                    q_[5] = std::sin(theta_2);\n\n                    omega_[1] = - M_PI / unit_time_ / 2.0;\n                    omega_[2] = - M_PI / unit_time_ / 2.0;\n                }\n                if (phase_scalar_ / unit_time_ >= 3.0 && phase_scalar_ / unit_time_ < 5.0)\n                {\n                    T theta_2 = - (phase_scalar_ / unit_time_ - 3.0) * M_PI + M_PI;\n                    \n                    // 1, 2\n                    q_[2] = std::cos(theta_2);\n                    q_[3] = std::sin(theta_2);\n                    q_[4] = std::cos(theta_2);\n                    q_[5] = std::sin(theta_2);\n\n                    omega_[1] = - M_PI / unit_time_;\n                    omega_[2] = - M_PI / unit_time_;\n                }\n            }\n\n            if (gait_idx_ == 8)\n            {\n                T theta_1 = phase_scalar_ / unit_time_ < 2.0 ?  - (phase_scalar_ / unit_time_) * M_PI + M_PI : - (phase_scalar_ / unit_time_ - 2.0) * M_PI / 2.0 + M_PI;\n                T theta_2 = phase_scalar_ / unit_time_ < 4.0 ?  - (phase_scalar_ / unit_time_) * M_PI / 2.0 + M_PI : - (phase_scalar_ / unit_time_ - 4.0) * M_PI + M_PI;\n\n                T omega_1 = phase_scalar_ / unit_time_ < 2.0 ? - M_PI / unit_time_ : - M_PI / unit_time_ / 2.0;\n                T omega_2 = phase_scalar_ / unit_time_ < 4.0 ? - M_PI / unit_time_ / 2.0 : - M_PI / unit_time_;\n\n                // 0, 3\n                q_[0] = std::cos(theta_1);\n                q_[1] = std::sin(theta_1);\n                q_[6] = std::cos(theta_1);\n                q_[7] = std::sin(theta_1);\n\n                omega_[0] = omega_1;\n                omega_[3] = omega_1;\n\n                // 1, 2\n                q_[2] = std::cos(theta_2);\n                q_[3] = std::sin(theta_2);\n                q_[4] = std::cos(theta_2);\n                q_[5] = std::sin(theta_2);\n\n                omega_[0] = omega_2;\n                omega_[3] = omega_2;\n            }\n        }\n\n        Eigen::Matrix<T, 8, 1> get_status()\n        {\n            return q_;\n        }\n\n        Eigen::Matrix<T, 8, 1> get_velocity()\n        {\n            // not implemented in manual phase\n            return q_dot_;\n        }\n\n    private:\n        int gait_idx_ = 0;\n        int prev_gait_idx_ = 0;\n        int target_gait_idx_ = 0;\n\n        T phase_scalar_ = 0.0;\n        T dt_ = 0.01;\n        T unit_time_ = 0.15;\n\n        std::array<T, n_gait> UNIT = {2.0, 6.0, 4.0, 4.0, 6.0, 6.0, 4.0, 6.0, 6.0};\n        std::array<T, n_gait> DUTY_UNIT = {1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 2.0, 3.0, 3.0};\n        std::array<T, n_gait> TIME;\n        std::array<T, n_gait> STANCE_TIME;\n\n        T unit_, duty_unity_, time_, stance_time_;\n\n        Eigen::Matrix<T, 8, 1> q_;\n        Eigen::Matrix<T, 8, 1> q_dot_;\n\n        Eigen::Matrix<T, 4, 1> phase_raw_; // -pi to +pi\n        std::array<T, 4> phase_; // 0 to 2 * pi\n        Eigen::Matrix<T, 4, 1> omega_;\n    };\n}\n\n#endif", "meta": {"hexsha": "603fc96c27d46bd0f8770e75157eefc30c2d5497", "size": 13427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ManualPhase.hpp", "max_stars_repo_name": "ZJU-XMech/PhaseGuidedControl", "max_stars_repo_head_hexsha": "f8a35ae8e1f903e948710b50681d2aa59046150e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T07:37:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:45:42.000Z", "max_issues_repo_path": "src/ManualPhase.hpp", "max_issues_repo_name": "ZJU-XMech/PhaseGuidedControl", "max_issues_repo_head_hexsha": "f8a35ae8e1f903e948710b50681d2aa59046150e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ManualPhase.hpp", "max_forks_repo_name": "ZJU-XMech/PhaseGuidedControl", "max_forks_repo_head_hexsha": "f8a35ae8e1f903e948710b50681d2aa59046150e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-21T09:33:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T09:33:25.000Z", "avg_line_length": 32.1220095694, "max_line_length": 184, "alphanum_fraction": 0.403142921, "num_tokens": 3818, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7956581000631541, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.4102571624988982}}
{"text": "//\n// This file is part of the libWetHair open source project\n//\n// The code is licensed solely for academic and non-commercial use under the\n// terms of the Clear BSD License. The terms of the Clear BSD License are\n// provided below. Other licenses may be obtained by contacting the faculty\n// of the Columbia Computer Graphics Group or a Columbia University licensing officer.\n//\n// The Clear BSD License\n//\n// Copyright 2017 Yun (Raymond) Fei, Henrique Teles Maia, Christopher Batty,\n// Changxi Zheng, and Eitan Grinspun\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted (subject to the limitations in the disclaimer\n// below) provided that the following conditions are met:\n//\n// * Redistributions of source code must retain the above copyright notice, this\n//  list of conditions and the following disclaimer.\n//\n// * Redistributions in binary form must reproduce the above copyright notice,\n//  this list of conditions and the following disclaimer in the documentation\n//  and/or other materials provided with the distribution.\n//\n// * Neither the name of the copyright holder nor the names of its contributors may be used\n//  to endorse or promote products derived from this software without specific\n//  prior written permission.\n//\n// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS\n// LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n// DAMAGE.\n\n#include \"CTCD.h\"\n#include <vector>\n#include \"rpoly.h\"\n#include <Eigen/Geometry>\n#include <iostream>\n\nusing namespace Eigen;\nusing namespace std;\n\nbool TimeInterval::overlap(const TimeInterval &t1, const TimeInterval &t2)\n{\n    return !(t1.l > t2.u || t2.l > t1.u);\n}\n\nbool TimeInterval::overlap(const std::vector<TimeInterval> &intervals)\n{\n    for(std::vector<TimeInterval>::const_iterator it1 = intervals.begin(); it1 != intervals.end(); ++it1)\n    {\n        std::vector<TimeInterval>::const_iterator it2 = it1;\n        for(++it2; it2 != intervals.end(); ++it2)\n            if(!overlap(*it1, *it2))\n                return false;\n    }\n    return true;\n}\n\nTimeInterval TimeInterval::intersect(const std::vector<TimeInterval> &intervals)\n{\n    TimeInterval isect(0.0, 1.0);\n    for(std::vector<TimeInterval>::const_iterator it = intervals.begin(); it != intervals.end(); ++it)\n    {\n        isect.l = max(it->l, isect.l);\n        isect.u = min(it->u, isect.u);\n    }\n    return isect;\n}\n\nint CTCD::getQuadRoots(double a, double b, double c, double &t0, double &t1) {\n    int roots = 0;\n    int sign = 1;\n\n    if (b < 0)\n        sign = -1;\n\n    double D = b * b - 4 * a * c;\n    if (D >= 0)\n    {\n        roots = 2;\n        double q = -0.5 * (b + sign * sqrt(D));\n        t0 = q / a;\n        t1 = c / q;\n        if (t0 > t1)\n            std::swap(t1, t0);\n    }\n    return roots;\n}\n\n\nvoid CTCD::checkInterval(double t1, double t2, double * op, int degree, vector<TimeInterval> &intervals, bool pos)\n{\n    // clamp values\n    t1 = max(0.0, t1);\n    t2 = max(0.0, t2);\n    t1 = min(1.0, t1);\n    t2 = min(1.0, t2);\n\n    double tmid = (t2 + t1) / 2;\n    double f = op[0];\n    for(int i=1; i<=degree; i++)\n    {\n        f *= tmid;\n        f += op[i];\n    }\n\n    if (pos && f >= 0)\n        intervals.push_back(TimeInterval(t1, t2));\n    else if (!pos && f <= 0)\n        intervals.push_back(TimeInterval(t1, t2));\n}\n\nbool CTCD::couldHaveRoots(double *op, int degree, bool pos) {\n    double result = 0;\n    if ((pos && op[0] > 0) || (!pos && op[0] < 0))\n        result = op[0];\n    for (int i = 1; i < degree; i++)\n    {\n        result *= 1.0;\n        if ((pos && op[i] > 0) || (!pos && op[i] < 0))\n            result += op[i];\n    }\n    result *= 1.0;\n    result += op[degree];\n    return !((pos && result < 0) || (!pos && result > 0));\n}\n\n\n\nvoid CTCD::findIntervals(double *op, int n, vector<TimeInterval> & intervals, bool pos)\n{\n    int roots=0;\n    int reducedDegree=n;\n\n    if(n>6)\n    {\n        assert(!\"Polynomials of degree > 6 not supported\");\n        return;\n    }\n\n    double time[6];\n    // We don't care one bit about these imaginary roots\n    double zeroi[6];\n\n    // normalize\n    double maxval = 0;\n    for(int i=0; i<=n; i++)\n    maxval = std::max(maxval, fabs(op[i]));\n    if(maxval != 0)    \n    for(int i=0; i<=n; i++)\n        op[i] /= maxval;\n\n    for (int i = 0; i < n; i++)\n    {\n        if (op[i] == 0)\n            reducedDegree--;\n        else\n            break;\n    }\n\n    if (reducedDegree < n)\n    {\n        for (int i = 0; i <= reducedDegree; i++)\n            op[i] = op[i + n - reducedDegree];\n    }\n\n    if (reducedDegree > 2) {\n        if (!couldHaveRoots(op, reducedDegree, pos))\n            return;\n\n        RootFinder rf;\n\n        roots = rf.rpoly(op, reducedDegree, time, zeroi);\n    }\n    else if (reducedDegree == 2)\n    {\n        roots = getQuadRoots(op[0], op[1], op[2], time[0], time[1]);\n    }\n    else if (reducedDegree == 1)\n    {\n        time[0] = -op[1] / op[0];\n        roots = 1;\n    }\n    else\n    {\n        // both points stationary -- check if colliding at t=0\n        if ((!pos && op[0] <= 0) || (pos && op[0] >= 0))\n            intervals.push_back(TimeInterval(0, 1.0));\n        return;\n    }\n\n    // check intervals\n    if (roots > 0)\n    {\n        std::sort(time, time + roots);\n        if (time[0] >= 0)\n            checkInterval(0, time[0], op, reducedDegree, intervals, pos);\n        for (int i = 0; i < roots - 1; i++) {\n            if (!((time[i] < 0 && time[i + 1] < 0) || (time[i] > 1.0 && time[i + 1] > 1.0)))\n                checkInterval(time[i], time[i + 1], op, reducedDegree, intervals, pos);\n        }\n        if (time[roots - 1] <= 1.0)\n            checkInterval(time[roots - 1], 1.0, op, reducedDegree, intervals, pos);\n    }\n    else\n    {\n        checkInterval(0.0, 1.0, op, reducedDegree, intervals, pos);\n    }\n}\n\nvoid CTCD::barycentricPoly3D(const Vector3d &x10,\n                             const Vector3d &x20,\n                             const Vector3d &x30,\n                             const Vector3d &v10,\n                             const Vector3d &v20,\n                             const Vector3d &v30,\n                             vector<TimeInterval> &result)\n{\n    // alpha > 0\n    double A = x10.dot(x10);\n    double B = 2 * x10.dot(v10);\n    double C = (v10).dot(v10);\n    // e0.e1\n    double D = (x20).dot(x10);\n    double E = (x20).dot(v10) + (v20).dot(x10);\n    double F = (v20).dot(v10);\n    //(q0-q1).e0\n    double G = (x30).dot(x20);\n    double H = (x30).dot(v20) + (v30).dot(x20);\n    double I = (v30).dot(v20);\n    //(q0-q1).e1\n    double J = (x30).dot(x10);\n    double K = (x30).dot(v10) + (v30).dot(x10);\n    double L = (v30).dot(v10);\n\n    double op[5];\n\n    op[0] = F * L - C * I;\n    op[1] = F * K + E * L - C * H - B * I;\n    op[2] = F * J + D * L + E * K - C * G - A * I - B * H;\n    op[3] = D * K + E * J - A * H - B * G;\n    op[4] = D * J - A * G;\n\n    findIntervals(op, 4, result, true);\n}\n\nvoid CTCD::planePoly3D(const Vector3d &x10,\n                       const Vector3d &x20,\n                       const Vector3d &x30,\n                       const Vector3d &v10,\n                       const Vector3d &v20,\n                       const Vector3d &v30,\n                       vector<TimeInterval> &result)\n{\n    double op[4];\n    op[0] = v10.dot(v20.cross(v30));\n    op[1] = x10.dot(v20.cross(v30)) + v10.dot(x20.cross(v30)) + v10.dot(v20.cross(x30));\n    op[2] = x10.dot(x20.cross(v30)) + x10.dot(v20.cross(x30)) + v10.dot(x20.cross(x30));\n    op[3] = x10.dot(x20.cross(x30));\n    findIntervals(op, 3, result, true);\n}\n\nvoid CTCD::distancePoly3D(const Vector3d &x10,\n                          const Vector3d &x20,\n                          const Vector3d &x30,\n                          const Vector3d &v10,\n                          const Vector3d &v20,\n                          const Vector3d &v30,\n                          double minDSquared,\n                          vector<TimeInterval> &result)\n{\n    double A = v10.dot(v20.cross(v30));\n    double B = x10.dot(v20.cross(v30)) + v10.dot(x20.cross(v30)) + v10.dot(v20.cross(x30));\n    double C = x10.dot(x20.cross(v30)) + x10.dot(v20.cross(x30)) + v10.dot(x20.cross(x30));\n    double D = x10.dot(x20.cross(x30));\n    Vector3d E = x20.cross(x30);\n    Vector3d F = x20.cross(v30) + v20.cross(x30);\n    Vector3d G = v20.cross(v30);\n\n    double op[7];\n    op[0] = A * A;\n    op[1] = 2 * A * B;\n    op[2] = B * B + 2 * A * C - G.dot(G) * minDSquared;\n    op[3] = 2 * A * D + 2 * B * C - 2 * G.dot(F) * minDSquared;\n    op[4] = 2 * B * D + C * C - (2 * G.dot(E) + F.dot(F)) * minDSquared;\n    op[5] = 2 * C * D - 2 * F.dot(E) * minDSquared;\n    op[6] = D * D - E.dot(E) * minDSquared;\n    findIntervals(op, 6, result, false);\n}\n\nbool CTCD::edgeEdgeCTCD(const Eigen::Vector3d &q0start,\n                        const Eigen::Vector3d &p0start,\n                        const Eigen::Vector3d &q1start,\n                        const Eigen::Vector3d &p1start,\n                        const Eigen::Vector3d &q0end,\n                        const Eigen::Vector3d &p0end,\n                        const Eigen::Vector3d &q1end,\n                        const Eigen::Vector3d &p1end,\n                        double eta,\n                        double &t)\n{\n    double minD = eta * eta;\n\n    // time intervals during which v is colinear with the edge, on the side of e1 towards e2, and on the side of e2 towards e1\n    std::vector<TimeInterval> rawcoplane, a0, a1, b0, b1;\n\n    Vector3d x10 = p0start - p1start;\n    Vector3d x20 = p0start - q0start;\n    Vector3d x30 = p1start - q1start;\n\n    Vector3d vp0 = p0end-p0start;\n    Vector3d vp1 = p1end-p1start;\n    Vector3d vq0 = q0end-q0start;\n    Vector3d vq1 = q1end-q1start;\n\n    Vector3d v10 = vp0 - vp1;\n    Vector3d v20 = vp0 - vq0;\n    Vector3d v30 = vp1 - vq1;\n\n    distancePoly3D(x10, x20, x30, v10, v20, v30, minD, rawcoplane);\n\n    // check for parallel edges\n    std::vector<TimeInterval> coplane;\n    std::vector<TimeInterval> parallel;\n\n    for(size_t i=0; i<rawcoplane.size(); i++)\n    {\n        double midt = (rawcoplane[i].u + rawcoplane[i].l) / 2;\n        x10 = (q0start - p0start) + midt * (vq0 - vp0);\n        x20 = (q1start - p1start) + midt * (vq1 - vp1);\n\n        if (x10.cross(x20).norm() < 1e-8)\n        {\n            // handle parallel edges via VertexEdgeCTCD\n            // parallel.push_back(rawcoplane[i]);\n            // std::cout << \"parallel edges detected! in CTCD, edgeEdgeCTCD\" <<std::endl;\n            // std::exit( EXIT_FAILURE ); \n\n            // [H] my attempt to rectify parallel edge collisions\n            if( vertexEdgeCTCD( q0start, q1start, p1start, q0end, q1end, p1end, eta, t ) ){\n                return true;\n            }\n            else{\n                return vertexEdgeCTCD( p0start, q1start, p1start, p0end, q1end, p1end, eta, t );\n            }\n\n        }\n        else\n    {\n            coplane.push_back(rawcoplane[i]);\n    }\n    }\n\n    if(coplane.empty())\n        return false;\n\n    x10 = p1start - q1start;\n    v10 = vp1 - vq1;\n    x20 = p0start - q0start;\n    v20 = vp0 - vq0;\n    x30 = q0start - q1start;\n    v30 = vq0 - vq1;\n    barycentricPoly3D(x10, x20, x30, v10, v20, v30, a0);\n    if(a0.empty())\n        return false;\n\n    x20 = q0start - p0start;\n    v20 = vq0 - vp0;\n    x30 = p0start - q1start;\n    v30 = vp0 - vq1;\n    barycentricPoly3D(x10, x20, x30, v10, v20, v30, a1);\n    if(a1.empty())\n        return false;\n\n    x10 = p0start - q0start;\n    v10 = vp0 - vq0;\n    x20 = p1start - q1start;\n    v20 = vp1 - vq1;\n    x30 = q1start - q0start;\n    v30 = vq1 - vq0;\n    barycentricPoly3D(x10, x20, x30, v10, v20, v30, b0);\n    if(b0.empty())\n        return false;\n\n    //x10 = p0 - q0;\n    //v10 = vp0 - vq0;\n    x20 = q1start - p1start;\n    v20 = vq1 - vp1;\n    x30 = p1start - q0start;\n    v30 = vp1 - vq0;\n\n    barycentricPoly3D(x10, x20, x30, v10, v20, v30, b1);\n    if(b1.empty())\n        return false;\n\n    // check intervals for overlap\n    bool col = false;\n    double mint = 1.0;\n    for (int i = 0; i < (int) coplane.size(); i++)\n    {\n        for (int j = 0; j < (int) a0.size(); j++)\n        {\n            for (int k = 0; k < (int) a1.size(); k++)\n            {\n                for (int l = 0; l < (int) b0.size(); l++)\n                {\n                    for (int m = 0; m < (int) b1.size(); m++)\n                    {   \n                        vector<TimeInterval> intervals;\n                        intervals.push_back(coplane[i]);\n                        intervals.push_back(a0[j]);\n                        intervals.push_back(a1[k]);\n                        intervals.push_back(b0[l]);\n                        intervals.push_back(b1[m]);\n                        if (TimeInterval::overlap(intervals) )\n                        {\n                            TimeInterval isect = TimeInterval::intersect(intervals);\n                bool skip = false;\n                for(int p = 0; p < (int)parallel.size(); p++)\n                {\n                vector<TimeInterval> pcheck;\n                pcheck.push_back(isect);\n                pcheck.push_back(parallel[p]);\n                if(TimeInterval::overlap(pcheck) )\n                {\n                    skip = true;\n                    break;\n                }\n                }\n                if(!skip)\n                {\n                                mint = min(mint, isect.l);\n                                col = true;\n                }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    if(col)\n    {\n        t = mint;\n        return true;\n    }\n    return false;\n}\n\nbool CTCD::vertexFaceCTCD(const Vector3d &q0start,\n                          const Vector3d &q1start,\n                          const Vector3d &q2start,\n                          const Vector3d &q3start,\n                          const Vector3d &q0end,\n                          const Vector3d &q1end,\n                          const Vector3d &q2end,\n                          const Vector3d &q3end,\n                          double eta, double &t)\n{\n    double minD = eta * eta;\n    Vector3d v0 = q0end - q0start;\n    Vector3d v1 = q1end - q1start;\n    Vector3d v2 = q2end - q2start;\n    Vector3d v3 = q3end - q3start;\n\n    // time intervals during which v is colinear with the edge, on the side of e1 towards e2, and on the side of e2 towards e1\n    vector<TimeInterval> coplane, e1, e2, e3;\n\n    // check p.((axb)xb)\n    Vector3d x10 = q0start - q1start;\n    Vector3d v10 = v0 - v1;\n    Vector3d x20 = (q3start - q1start).cross(q2start - q1start);\n    Vector3d v20 = (v3 - v1).cross(v2 - v1);\n    Vector3d x30 = q3start - q1start;\n    Vector3d v30 = v3 - v1;\n    planePoly3D(x10, x20, x30, v10, v20, v30, e1);\n\n    if(e1.empty())\n        return false;\n\n    x10 = q0start - q2start;\n    v10 = v0 - v2;\n    x20 = (q1start - q2start).cross(q3start - q2start);\n    v20 = (v1 - v2).cross(v3 - v2);\n    x30 = q1start - q2start;\n    v30 = v1 - v2;\n    planePoly3D(x10, x20, x30, v10, v20, v30, e2);\n\n    if(e2.empty())\n        return false;\n\n    x10 = q0start - q3start;\n    v10 = v0 - v3;\n    x20 = (q2start - q3start).cross(q1start - q3start);\n    v20 = (v2 - v3).cross(v1 - v3);\n    x30 = q2start - q3start;\n    v30 = v2 - v3;\n    planePoly3D(x10, x20, x30, v10, v20, v30, e3);\n\n    if(e3.empty())\n        return false;\n\n    x10 = q0start - q1start;\n    x20 = q2start - q1start;\n    x30 = q3start - q1start;\n    v10 = v0 - v1;\n    v20 = v2 - v1;\n    v30 = v3 - v1;\n    distancePoly3D(x10, x20, x30, v10, v20, v30, minD, coplane);\n\n    if(coplane.empty())\n        return false;\n\n    bool col = false;\n    double mint = 1.0;\n    for (int i = 0; i < (int) coplane.size(); i++)\n    {\n        for (int j = 0; j < (int) e1.size(); j++)\n        {\n            for (int k = 0; k < (int) e2.size(); k++)\n            {\n                for (int l = 0; l < (int) e3.size(); l++)\n                {\n                    vector<TimeInterval> intervals;\n                    intervals.push_back(coplane[i]);\n                    intervals.push_back(e1[j]);\n                    intervals.push_back(e2[k]);\n                    intervals.push_back(e3[l]);\n                    if(TimeInterval::overlap(intervals))\n                    {\n                        mint = std::min(TimeInterval::intersect(intervals).l, mint);\n                        col = true;\n                    }\n                }\n            }\n        }\n    }\n\n    if(col)\n    {\n        t = mint;\n        return true;\n    }\n    return false;\n}\n\n\nbool CTCD::vertexEdgeCTCD(const Vector3d &q0start,\n                          const Vector3d &q1start,\n                          const Vector3d &q2start,\n                          const Vector3d &q0end,\n                          const Vector3d &q1end,\n                          const Vector3d &q2end,\n                          double eta,\n                          double &t)\n{\n    double op[5];\n    double minD = eta*eta;\n    Vector3d v0 = q0end-q0start;\n    Vector3d v1 = q1end-q1start;\n    Vector3d v2 = q2end-q2start;\n\n    // time intervals during which v is colinear with the edge, on the side of e1 towards e2, and on the side of e2 towards e1\n    vector<TimeInterval> colin, e1, e2;\n\n    Vector3d ab = q2start - q1start;\n    Vector3d ac = q0start - q1start;\n    Vector3d cb = q2start - q0start;\n    Vector3d vab = v2 - v1;\n    Vector3d vac = v0 - v1;\n    Vector3d vcb = v2 - v0;\n\n    double c = ab.dot(ac);\n    double b = ac.dot(vab) + ab.dot(vac);\n    double a = vab.dot(vac);\n    op[0] = a;\n    op[1] = b;\n    op[2] = c;\n    findIntervals(op, 2, e1, true);\n    if(e1.empty())\n        return false;\n\n    c = ab.dot(cb);\n    b = cb.dot(vab) + ab.dot(vcb);\n    a = vab.dot(vcb);\n\n    op[0] = a;\n    op[1] = b;\n    op[2] = c;\n    findIntervals(op, 2, e2, true);\n    if(e2.empty())\n        return false;\n\n    double A = ab.dot(ab);\n    double B = 2 * ab.dot(vab);\n    double C = vab.dot(vab);\n    double D = ac.dot(ac);\n    double E = 2 * ac.dot(vac);\n    double F = vac.dot(vac);\n    double G = ac.dot(ab);\n    double H = vab.dot(ac) + vac.dot(ab);\n    double I = vab.dot(vac);\n    op[4] = A * D - G * G - minD * A;\n    op[3] = B * D + A * E - 2 * G * H - minD * B;\n    op[2] = B * E + A * F + C * D - H * H - 2 * G * I - minD * C;\n    op[1] = B * F + C * E - 2 * H * I;\n    op[0] = C * F - I * I;\n    findIntervals(op, 4, colin, false);\n    if(colin.empty())\n        return false;\n\n    double mint = 1.0;\n    bool col = false;\n    for (int i = 0; i < (int) colin.size(); i++)\n    {\n        for (int j = 0; j < (int) e1.size(); j++)\n        {\n            for (int k = 0; k < (int) e2.size(); k++)\n            {\n                vector<TimeInterval> intervals;\n                intervals.push_back(colin[i]);\n                intervals.push_back(e1[j]);\n                intervals.push_back(e2[k]);\n                if(TimeInterval::overlap(intervals))\n                {\n                    mint = std::min(TimeInterval::intersect(intervals).l, mint);\n                    col = true;\n                }\n            }\n        }\n    }\n\n    if(col)\n    {\n        t = mint;\n        return true;\n    }\n    return false;\n}\n\nbool CTCD::vertexVertexCTCD(const Vector3d &q1start,\n                            const Vector3d &q2start,\n                            const Vector3d &q1end,\n                            const Vector3d &q2end,\n                            double eta, double &t)\n{\n    int roots = 0;\n    double min_d = eta*eta;\n    double t1 = 0, t2 = 0;\n    Vector3d v1 = q1end-q1start;\n    Vector3d v2 = q2end-q2start;\n\n    // t^2 term\n    double a = v1.dot(v1) + v2.dot(v2) - 2 * v1.dot(v2);\n    // t term\n    double b = 2 * (v1.dot(q1start) - v2.dot(q1start) - v1.dot(q2start) + v2.dot(q2start));\n    // current distance - min_d\n    double c = q1start.dot(q1start) + q2start.dot(q2start) - 2 * q1start.dot(q2start) - min_d;\n    if (a != 0)\n    {\n        roots = getQuadRoots(a, b, c, t1, t2);\n    }\n    else if (b != 0)\n    {\n        t1 = -c / b;\n        roots = 1;\n    }\n    else\n    {\n        if(c<=0)\n        {\n            t = 0;\n            return true;\n        }\n        return false;\n    }\n\n    double op[3];\n    op[0] = a;\n    op[1] = b;\n    op[2] = c;\n    vector<TimeInterval> interval;\n\n    if (roots == 2)\n    {\n        checkInterval(0, t1, op, 2, interval, false);\n        if(!interval.empty())\n        {\n            t = 0;\n            return true;\n        }\n        checkInterval(t1, t2, op, 2, interval, false);\n        if(!interval.empty())\n        {\n            t = t1;\n            return true;\n        }\n        checkInterval(t2, 1.0, op, 2, interval, false);\n        if(!interval.empty())\n        {\n            t = t2;\n            return true;\n        }\n        return false;\n    }\n    else if (roots == 1)\n    {\n        checkInterval(0, t1, op, 2, interval, false);\n        if(!interval.empty())\n        {\n            t = 0;\n            return true;\n        }\n        checkInterval(t1, 1.0, op, 2, interval, false);\n        if(!interval.empty())\n        {\n            t = t1;\n            return true;\n        }\n        return false;\n    }\n    checkInterval(0, 1.0, op, 2, interval, false);\n    if(!interval.empty())\n    {\n        t = 0;\n        return true;\n    }\n    return false;\n}\n\nbool CTCD::checkEEContact( const Eigen::Vector3d &q0start,\n                                const Eigen::Vector3d &p0start,\n                                const Eigen::Vector3d &q1start,\n                                const Eigen::Vector3d &p1start,\n                                const Eigen::Vector3d &q0end,\n                                const Eigen::Vector3d &p0end,\n                                const Eigen::Vector3d &q1end,\n                                const Eigen::Vector3d &p1end,\n                                double eta,\n                                double &t)\n{\n\n    if( edgeEdgeCTCD( q0start, p0start, q1start, p1start, q0end, p0end, q1end, p1end, eta, t) )\n    {           \n        return true;\n    }\n\n    // Edge-edge vertices\n    if( vertexEdgeCTCD(q0start, q1start, p1start, q0end, q1end, p1end, eta, t) )\n    {\n        return true;\n    }\n    if( vertexEdgeCTCD(p0start, q1start, p1start, p0end, q1end, p1end, eta, t) )\n    {\n        return true;\n    }\n    if( vertexEdgeCTCD(q1start, q0start, p0start, q1end, q0end, p0end, eta, t) )\n    {\n        return true;\n    }\n    if( vertexEdgeCTCD(p1start, q0start, p0start, p1end, q0end, p0end, eta, t) )\n    {\n        return true;\n    }\n\n    // edge vertex-edge vertex\n    if( vertexVertexCTCD(q0start, q1start, q0end, q1end, eta, t) )\n    {\n        return true;\n    }\n    if( vertexVertexCTCD(q0start, p1start, q0end, p1end, eta, t) )\n    {\n        return true;\n    }\n    if( vertexVertexCTCD(p0start, q1start, p0end, q1end, eta, t) )\n    {\n        return true;\n    }\n    if( vertexVertexCTCD(p0start, p1start, p0end, p1end, eta, t) )\n    {\n        return true;\n    }\n    return false;       \n}\n\ntemplate<typename ComparableT>\nEIGEN_STRONG_INLINE ComparableT clamp( const ComparableT x, const ComparableT l, const ComparableT u )\n{\n    return ( x > u ) ? u : ( ( x > l ) ? x : l );\n}\n\n// Adapted from Christer Ericson, \"Real Time Collision Detection\"\n// Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and\n// S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared\n// distance between between S1(s) and S2(t).\n// TODO: Explore behavior in degenerate case more closely.\ndouble CTCD::ClosestPtSegmentSegment( const Vector3d& p1, const Vector3d& q1, const Vector3d& p2, const Vector3d& q2,\n        double& s, double& t, Vector3d& c1, Vector3d& c2 )\n{\n    double EPSILON = 1.0e-12;\n\n    Vector3d d1 = q1 - p1; // Direction vector of segment S1\n    Vector3d d2 = q2 - p2; // Direction vector of segment S2\n    Vector3d r = p1 - p2;\n    double a = d1.dot( d1 ); // Squared length of segment S1, always nonnegative\n    double e = d2.dot( d2 ); // Squared length of segment S2, always nonnegative\n    double f = d2.dot( r );\n\n    // Check if either or both segments degenerate into points\n    if ( a <= EPSILON && e <= EPSILON )\n    {\n        // Both segments degenerate into points\n        s = t = 0.0;\n        c1 = p1;\n        c2 = p2;\n        return ( c1 - c2 ).dot( c1 - c2 );\n    }\n    if ( a <= EPSILON )\n    {\n        // First segment degenerates into a point\n        s = 0.0;\n        t = f / e; // s = 0 => t = (b*s + f) / e = f / e\n        t = clamp( t, 0.0, 1.0 );\n    }\n    else\n    {\n        double c = d1.dot( r );\n        if ( e <= EPSILON )\n        {\n            // Second segment degenerates into a point\n            t = 0.0;\n            s = clamp( -c / a, 0.0, 1.0 ); // t = 0 => s = (b*t - c) / a = -c / a\n        }\n        else\n        {\n            // The general nondegenerate case starts here\n            double b = d1.dot( d2 );\n            double denom = a * e - b * b; // Always nonnegative\n\n            // If segments not parallel, compute closest point on L1 to L2, and\n            // clamp to segment S1. Else pick arbitrary s (here 0)\n            if ( denom != 0.0 )\n            {\n                s = clamp( ( b * f - c * e ) / denom, 0.0, 1.0 );\n            }\n            else\n                s = 0.0;\n\n            // Compute point on L2 closest to S1(s) using\n            // t = Dot((P1+D1*s)-P2,D2) / Dot(D2,D2) = (b*s + f) / e\n            t = ( b * s + f ) / e;\n\n            // If t in [0,1] done. Else clamp t, recompute s for the new value\n            // of t using s = Dot((P2+D2*t)-P1,D1) / Dot(D1,D1)= (t*b - c) / a\n            // and clamp s to [0, 1]\n            if ( t < 0.0 )\n            {\n                t = 0.0;\n                s = clamp( -c / a, 0.0, 1.0 );\n            }\n            else if ( t > 1.0 )\n            {\n                t = 1.0;\n                s = clamp( ( b - c ) / a, 0.0, 1.0 );\n            }\n        }\n    }\n\n    c1 = p1 + d1 * s;\n    c2 = p2 + d2 * t;\n    return ( c1 - c2 ).dot( c1 - c2 );\n}\n\n", "meta": {"hexsha": "65c32001bec9021b382528d971c7842415de9219", "size": 26561, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libWetHair/Core/CTCD.cpp", "max_stars_repo_name": "a554b554/fiber_sim", "max_stars_repo_head_hexsha": "c19feebe437427e56907627b3ab369de7d7e4592", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-26T17:54:51.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-26T17:54:51.000Z", "max_issues_repo_path": "libWetHair/Core/CTCD.cpp", "max_issues_repo_name": "a554b554/fiber_sim", "max_issues_repo_head_hexsha": "c19feebe437427e56907627b3ab369de7d7e4592", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libWetHair/Core/CTCD.cpp", "max_forks_repo_name": "a554b554/fiber_sim", "max_forks_repo_head_hexsha": "c19feebe437427e56907627b3ab369de7d7e4592", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.080407701, "max_line_length": 126, "alphanum_fraction": 0.503369602, "num_tokens": 8114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.629774621301746, "lm_q1q2_score": 0.4102067632281143}}
{"text": "//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Copyright 2004 The Trustees of Indiana University\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#ifndef BOOST_GRAPH_SEQUENTIAL_VERTEX_COLORING_HPP\n#define BOOST_GRAPH_SEQUENTIAL_VERTEX_COLORING_HPP\n\n#include <vector>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/limits.hpp>\n\n#ifdef BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS\n#  include <iterator>\n#endif\n\n/* This algorithm is to find coloring of a graph\n\n   Algorithm:\n   Let G = (V,E) be a graph with vertices (somehow) ordered v_1, v_2, ...,\n   v_n. For k = 1, 2, ..., n the sequential algorithm assigns v_k to the\n   smallest possible color.\n\n   Reference:\n\n   Thomas F. Coleman and Jorge J. More, Estimation of sparse Jacobian\n   matrices and graph coloring problems. J. Numer. Anal. V20, P187-209, 1983\n\n   v_k is stored as o[k] here.\n\n   The color of the vertex v will be stored in color[v].\n   i.e., vertex v belongs to coloring color[v] */\n\nnamespace boost {\n  template <class VertexListGraph, class OrderPA, class ColorMap>\n  typename property_traits<ColorMap>::value_type\n  sequential_vertex_coloring(const VertexListGraph& G, OrderPA order,\n                             ColorMap color)\n  {\n    typedef graph_traits<VertexListGraph> GraphTraits;\n    typedef typename GraphTraits::vertex_descriptor Vertex;\n    typedef typename property_traits<ColorMap>::value_type size_type;\n\n    size_type max_color = 0;\n    const size_type V = num_vertices(G);\n\n    // We need to keep track of which colors are used by\n    // adjacent vertices. We do this by marking the colors\n    // that are used. The mark array contains the mark\n    // for each color. The length of mark is the\n    // number of vertices since the maximum possible number of colors\n    // is the number of vertices.\n    std::vector<size_type> mark(V,\n                                std::numeric_limits<size_type>::max BOOST_PREVENT_MACRO_SUBSTITUTION());\n\n    //Initialize colors\n    typename GraphTraits::vertex_iterator v, vend;\n    for (boost::tie(v, vend) = vertices(G); v != vend; ++v)\n      put(color, *v, V-1);\n\n    //Determine the color for every vertex one by one\n    for ( size_type i = 0; i < V; i++) {\n      Vertex current = get(order,i);\n      typename GraphTraits::adjacency_iterator v, vend;\n\n      //Mark the colors of vertices adjacent to current.\n      //i can be the value for marking since i increases successively\n      for (boost::tie(v,vend) = adjacent_vertices(current, G); v != vend; ++v)\n        mark[get(color,*v)] = i;\n\n      //Next step is to assign the smallest un-marked color\n      //to the current vertex.\n      size_type j = 0;\n\n      //Scan through all useable colors, find the smallest possible\n      //color that is not used by neighbors.  Note that if mark[j]\n      //is equal to i, color j is used by one of the current vertex's\n      //neighbors.\n      while ( j < max_color && mark[j] == i )\n        ++j;\n\n      if ( j == max_color )  //All colors are used up. Add one more color\n        ++max_color;\n\n      //At this point, j is the smallest possible color\n      put(color, current, j);  //Save the color of vertex current\n    }\n\n    return max_color;\n  }\n\n  template<class VertexListGraph, class ColorMap>\n  typename property_traits<ColorMap>::value_type\n  sequential_vertex_coloring(const VertexListGraph& G, ColorMap color)\n  {\n    typedef typename graph_traits<VertexListGraph>::vertex_descriptor\n      vertex_descriptor;\n    typedef typename graph_traits<VertexListGraph>::vertex_iterator\n      vertex_iterator;\n\n    std::pair<vertex_iterator, vertex_iterator> v = vertices(G);\n#ifndef BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS\n    std::vector<vertex_descriptor> order(v.first, v.second);\n#else\n    std::vector<vertex_descriptor> order;\n    order.reserve(std::distance(v.first, v.second));\n    while (v.first != v.second) order.push_back(*v.first++);\n#endif\n    return sequential_vertex_coloring\n             (G,\n              make_iterator_property_map\n              (order.begin(), identity_property_map(),\n               graph_traits<VertexListGraph>::null_vertex()),\n              color);\n  }\n}\n\n#endif\n", "meta": {"hexsha": "10805d700f61d90a91f96d25878dad99cfb47f53", "size": 4544, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/graph/sequential_vertex_coloring.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/graph/sequential_vertex_coloring.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/graph/sequential_vertex_coloring.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 36.352, "max_line_length": 104, "alphanum_fraction": 0.6683538732, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.4101776450642032}}
{"text": "#include \"teca_tc_wind_radii.h\"\n\n#include \"teca_cartesian_mesh.h\"\n#include \"teca_array_collection.h\"\n#include \"teca_variant_array.h\"\n#include \"teca_metadata.h\"\n#include \"teca_coordinate_util.h\"\n#include \"teca_table.h\"\n#include \"teca_programmable_algorithm.h\"\n#include \"teca_saffir_simpson.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n\n#if defined(TECA_HAS_BOOST)\n#include <boost/program_options.hpp>\n#endif\n\n#if defined(TECA_HAS_MPI)\n#include <mpi.h>\n#endif\n\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\n//#define TECA_DEBUG\n\n// PIMPL idiom hides internals\nclass teca_tc_wind_radii::internals_t\n{\npublic:\n    internals_t();\n    ~internals_t();\n\n    void clear();\n\n    teca_algorithm_output_port storm_pipeline_port; // pipeline that serves up tracks\n    teca_metadata metadata;                         // cached metadata\n    const_p_teca_table storm_table;                 // data structures that enable\n    unsigned long number_of_storms;                 // random access into tracks\n    std::vector<unsigned long> storm_counts;\n    std::vector<unsigned long> storm_offsets;\n    std::vector<unsigned long> storm_ids;\n\npublic:\n    template <typename NT_MESH, typename NT_WIND>\n    static int locate_critical_ids(\n        NT_MESH *rad,               // bin centers\n        NT_WIND *wind,              // wind speed at centers (max, avg, etc)\n        unsigned int n_bins,        // length of profile arrays\n        NT_MESH core_rad_max,       // max allowed distance to peak\n        NT_WIND *crit_wind,         // speeds to calculate radius at\n        unsigned int n_crit,        // number of critical values\n        unsigned int *crit_ids,     // index of critical wind\n        unsigned int &peak_id);     // index of peak wind\n\n    // given two points (x1,y1), (x2,y2) defining a line\n    // and a thrid point defining a horizontal line (*, yc)\n    // compute the x value, (xc, yc)  where the lines\n    // intersect.\n    template <typename NT_MESH>\n    static int compute_crossing(\n        NT_MESH x1, NT_MESH y1, NT_MESH x2,\n        NT_MESH y2, NT_MESH yc, NT_MESH &xc);\n\n    // given the set of critical ids from locate critical ids\n    // compute linear aproximation of the intersections with\n    // critical wind speeds.\n    template <typename NT_MESH, typename NT_WIND>\n    static int compute_crossings(NT_MESH *rad, NT_WIND *wind,\n        NT_WIND *crit_wind, unsigned int n_crit, unsigned int *crit_ids,\n        NT_MESH *rcross);\n\n    template <typename NT_MESH, typename NT_WIND>\n    static NT_WIND compute_wind_speed(\n            NT_MESH x, NT_MESH y, NT_WIND u, NT_WIND v);\n\n    // initialize the vector with the default speeds to compute\n    // radius at. These are the transitions of the Saffir-Simpson\n    // scale.\n    static void init_critical_wind_speeds(\n        std::vector<double> &critical_wind_speeds);\n\n    // binning operators, used to map Cartesian mesh onto\n    // a radial mesh.\n    template<typename NT> class bin_average;\n    template<typename NT> class bin_max;\n\n    // mapping functions. overloads are used to get around\n    // the fact that templates with more than one argument\n    // are difficult to use inside of the dispatch macro\n    template<typename NT_MESH, typename NT_WIND,\n        template<typename> class bin_operation_t>\n    static p_teca_variant_array_impl<NT_WIND>\n    compute_radial_profile(NT_MESH storm_x, NT_MESH storm_y,\n        const NT_MESH *mesh_x, const NT_MESH *mesh_y,\n        const NT_WIND *wind_u, const NT_WIND *wind_v,\n        unsigned long nx, unsigned long ny, int number_of_bins,\n        NT_MESH bin_width, NT_MESH max_radius,\n        p_teca_variant_array_impl<NT_MESH> &rad_all,\n        p_teca_variant_array_impl<NT_WIND> &wind_all);\n\n    template<typename NT_MESH, typename NT_WIND>\n    static p_teca_variant_array_impl<NT_WIND>\n    compute_average_radial_profile(NT_MESH storm_x, NT_MESH storm_y,\n        const NT_MESH *mesh_x, const NT_MESH *mesh_y,\n        const NT_WIND *wind_u, const NT_WIND *wind_v,\n        unsigned long nx, unsigned long ny, int number_of_bins,\n        NT_MESH bin_width, NT_MESH max_radius,\n        p_teca_variant_array_impl<NT_MESH> &rad_all,\n        p_teca_variant_array_impl<NT_WIND> &wind_all)\n    {\n        return compute_radial_profile<NT_MESH, NT_WIND, bin_average>(\n            storm_x, storm_y, mesh_x, mesh_y, wind_u, wind_v, nx, ny,\n            number_of_bins, bin_width, max_radius, rad_all, wind_all);\n    }\n\n    template<typename NT_MESH, typename NT_WIND>\n    static p_teca_variant_array_impl<NT_WIND>\n    compute_max_radial_profile(NT_MESH storm_x, NT_MESH storm_y,\n        const NT_MESH *mesh_x, const NT_MESH *mesh_y,\n        const NT_WIND *wind_u, const NT_WIND *wind_v,\n        unsigned long nx, unsigned long ny, int number_of_bins,\n        NT_MESH bin_width, NT_MESH max_radius,\n        p_teca_variant_array_impl<NT_MESH> &rad_all,\n        p_teca_variant_array_impl<NT_WIND> &wind_all)\n    {\n        return compute_radial_profile<NT_MESH, NT_WIND, bin_max>(\n            storm_x, storm_y, mesh_x, mesh_y, wind_u, wind_v, nx, ny,\n            number_of_bins, bin_width, max_radius, rad_all, wind_all);\n    }\n\n    // function generate Python code to plot the radial profile\n    // used for debuging only\n    template<typename NT_MESH, typename NT_WIND>\n    static void plot_radial_profile(std::ostream &ostr,\n        unsigned long track_id, unsigned int k,\n        p_teca_variant_array_impl<NT_MESH> rad_all,\n        p_teca_variant_array_impl<NT_WIND> wind_all,\n        p_teca_variant_array_impl<NT_MESH> rad,\n        p_teca_variant_array_impl<NT_WIND> wind,\n        const std::vector<NT_WIND> &crit_wind,\n        const std::vector<unsigned int> &crit_ids,\n        unsigned int peak_id,\n        p_teca_variant_array_impl<NT_MESH> rcross);\n\n};\n\ntemplate<typename NT>\nclass teca_tc_wind_radii::internals_t::bin_average\n{\npublic:\n    bin_average() = delete;\n    bin_average(int nbins) : m_nbins(nbins)\n    {\n        m_vals = teca_variant_array_impl<NT>::New(nbins, NT());\n        m_pvals = m_vals->get();\n\n        m_count = teca_int_array::New(nbins, 0);\n        m_pcount = m_count->get();\n    }\n\n    void operator()(int bin, NT val)\n    {\n        m_pvals[bin] += val;\n        m_pcount[bin] += 1;\n    }\n\n    p_teca_variant_array_impl<NT> get_bin_values()\n    {\n        for (int i = 0; i < m_nbins; ++i)\n            m_pvals[i] = m_pcount[i] ? m_pvals[i]/m_pcount[i] : m_pvals[i];\n        return m_vals;\n    }\n\nprivate:\n    p_teca_variant_array_impl<NT> m_vals;\n    NT *m_pvals;\n    p_teca_int_array m_count;\n    int *m_pcount;\n    int m_nbins;\n};\n\n\ntemplate<typename NT>\nclass teca_tc_wind_radii::internals_t::bin_max\n{\npublic:\n    bin_max() = delete;\n    bin_max(int nbins)\n    {\n        m_vals = teca_variant_array_impl<NT>::New(nbins, NT());\n        m_pvals = m_vals->get();\n    }\n\n    void operator()(int bin, NT val)\n    { m_pvals[bin] = std::max(m_pvals[bin], val); }\n\n    p_teca_variant_array_impl<NT> get_bin_values()\n    { return m_vals; }\n\nprivate:\n    p_teca_variant_array_impl<NT> m_vals;\n    NT *m_pvals;\n};\n\n\n// --------------------------------------------------------------------------\nteca_tc_wind_radii::internals_t::internals_t() : number_of_storms(0)\n{}\n\n// --------------------------------------------------------------------------\nteca_tc_wind_radii::internals_t::~internals_t()\n{}\n\n// --------------------------------------------------------------------------\nvoid teca_tc_wind_radii::internals_t::clear()\n{\n    this->metadata.clear();\n    this->storm_table = nullptr;\n    this->number_of_storms = 0;\n    this->metadata.clear();\n    this->storm_counts.clear();\n    this->storm_offsets.clear();\n    this->storm_ids.clear();\n}\n\n// --------------------------------------------------------------------------\ntemplate <typename NT_MESH, typename NT_WIND>\nNT_WIND teca_tc_wind_radii::internals_t::compute_wind_speed(\n    NT_MESH x, NT_MESH y, NT_WIND u, NT_WIND v)\n{\n#if defined(AZIMUTHAL_PROFILE)\n    // azimuthal wind speed\n    NT_MESH theta = std::atan2(y, x);\n    NT_WIND w = std::fabs(-u*std::sin(theta) + v*std::cos(theta));\n#else\n    (void)x;\n    (void)y;\n    NT_WIND uu = u*u;\n    NT_WIND vv = v*v;\n    NT_WIND w = std::sqrt(uu + vv);\n#endif\n    return w;\n}\n\n// --------------------------------------------------------------------------\ntemplate <typename NT_MESH>\nint teca_tc_wind_radii::internals_t::compute_crossing(NT_MESH x1,\n    NT_MESH y1, NT_MESH x2, NT_MESH y2, NT_MESH yc, NT_MESH &xc)\n{\n    NT_MESH D = x1 - x2;\n#if defined(TECA_DEBUG)\n    if (std::fabs(D) <= NT_MESH(1.0e-6))\n    {\n        TECA_ERROR(\"cooincident points. cannot compute slope intercept\")\n        xc = x2;\n        return -1;\n    }\n#endif\n    NT_MESH m = (y1 - y2)/D;\n    NT_MESH b = (x1*y2 - x2*y1)/D;\n    xc = (yc - b)/m;\n    return 0;\n}\n\n// --------------------------------------------------------------------------\ntemplate <typename NT_MESH, typename NT_WIND>\nint teca_tc_wind_radii::internals_t::compute_crossings(NT_MESH *rad,\n    NT_WIND *wind, NT_WIND *crit_wind, unsigned int n_crit,\n    unsigned int *crit_ids, NT_MESH *rcross)\n{\n    // zero out outputs\n    memset(rcross, 0, n_crit*sizeof(NT_MESH));\n\n    // for each critical speed where a radial crossing was detected\n    // solve for the interecpt of the linear approximtion of the\n    // radial profile and the horizontal line definied by the critical\n    // wind value\n    for (unsigned int i = 0; i < n_crit; ++i)\n    {\n        if (crit_ids[i])\n        {\n            // by construction we know crossing is in between these ids\n            // the ids name 2 points defining a line guaranteed to intercect\n            // the horizontal line defined by the critical wind speed\n            unsigned int q2 = crit_ids[i];\n            unsigned int q1 = q2-1;\n\n            compute_crossing<NT_MESH>(\n                rad[q1], wind[q1], rad[q2], wind[q2],\n                crit_wind[i], rcross[i]);\n        }\n    }\n\n    return 0;\n}\n\n// --------------------------------------------------------------------------\ntemplate <typename NT_MESH, typename NT_WIND>\nint teca_tc_wind_radii::internals_t::locate_critical_ids(\n    NT_MESH *rad, NT_WIND *wind, unsigned int n_bins, NT_MESH core_rad_max,\n    NT_WIND *crit_wind, unsigned int n_crit, unsigned int *crit_ids,\n    unsigned int &peak_id)\n{\n    // first zero out everything\n    for (unsigned int i = 0; i < n_crit; ++i)\n        crit_ids[i] = 0;\n\n    // locate the peak wind and peak rad\n    peak_id = 0;\n    for (unsigned int i = 1; i < n_bins; ++i)\n        peak_id = wind[i] > wind[peak_id] ? i : peak_id;\n\n    // peak wind speed should be close to the storm center\n    // inheritted from the GFDL algorithm requirements\n    if (rad[peak_id] > core_rad_max)\n    {\n        TECA_WARNING(\"Peak wind speed is outside of the core \"\n            << rad[peak_id] << \" > \" << core_rad_max)\n        peak_id = std::numeric_limits<unsigned int>::max();\n        return -1;\n    }\n\n    // locate the critical values\n    for (unsigned int i = 0; i < n_crit; ++i)\n    {\n        // skip when search is impossible\n        if (crit_wind[i] >= wind[peak_id])\n            continue;\n\n        // find the first less or equal to the critical value\n        // from the peak\n        for (unsigned int j = peak_id; (j < n_bins) && !crit_ids[i]; ++j)\n            crit_ids[i] = wind[j] < crit_wind[i] ? j : 0;\n    }\n\n    return 0;\n}\n\n// --------------------------------------------------------------------------\ntemplate<typename NT_MESH, typename NT_WIND,\n    template<typename> class bin_operation_t>\np_teca_variant_array_impl<NT_WIND>\nteca_tc_wind_radii::internals_t::compute_radial_profile(NT_MESH storm_x,\n    NT_MESH storm_y, const NT_MESH *mesh_x, const NT_MESH *mesh_y,\n    const NT_WIND *wind_u, const NT_WIND *wind_v, unsigned long nx,\n    unsigned long ny, int number_of_bins, NT_MESH bin_width,\n    NT_MESH max_radius, p_teca_variant_array_impl<NT_MESH> &rad_all,\n    p_teca_variant_array_impl<NT_WIND> &wind_all)\n{\n#if defined(TECA_DEBUG)\n    unsigned long nxy = nx*ny;\n\n    rad_all = teca_variant_array_impl<NT_MESH>::New();\n    rad_all->reserve(nxy);\n\n    wind_all = teca_variant_array_impl<NT_WIND>::New();\n    wind_all->reserve(nxy);\n#else\n    (void)rad_all;\n    (void)wind_all;\n#endif\n\n    // construct an instance of the binning operator\n    bin_operation_t<NT_WIND> bin_op(number_of_bins);\n\n    // for each grid point compute radial distance to storm center\n    for (unsigned long j = 0; j < ny; ++j)\n    {\n        unsigned long q = j*nx;\n        NT_MESH y = mesh_y[j] - storm_y;\n        NT_MESH yy = y*y;\n        for (unsigned long i = 0; i < nx; ++i)\n        {\n            // radius\n            NT_MESH x = mesh_x[i] - storm_x;\n            NT_MESH xx = x*x;\n            NT_MESH r = std::sqrt(xx + yy);\n\n            if (r <= max_radius)\n            {\n                // compute wind speed at the grid point\n                NT_WIND w = teca_tc_wind_radii::internals_t::\n                    compute_wind_speed(x, y, wind_u[q+i], wind_v[q+i]);\n\n                // sample it onto the discrete radial mesh\n                unsigned int bin = static_cast<unsigned int>(r/bin_width);\n                bin_op(bin, w);\n\n#if defined(TECA_DEBUG)\n                rad_all->append(r);\n                wind_all->append(w);\n#endif\n            }\n        }\n    }\n\n    return bin_op.get_bin_values();\n}\n\n// --------------------------------------------------------------------------\nvoid teca_tc_wind_radii::internals_t::init_critical_wind_speeds(\n    std::vector<double> &critical_wind_speeds)\n{\n    // critical wind speeds are the thresholds of Saffir-Simpson\n    // scale, starting at tropical depression -1 up to cat 5 storm\n    double wind_crit_mps[6] = {\n        teca_saffir_simpson::get_upper_bound_mps<double>(-1),\n        teca_saffir_simpson::get_upper_bound_mps<double>(0),\n        teca_saffir_simpson::get_upper_bound_mps<double>(1),\n        teca_saffir_simpson::get_upper_bound_mps<double>(2),\n        teca_saffir_simpson::get_upper_bound_mps<double>(3),\n        teca_saffir_simpson::get_upper_bound_mps<double>(4)};\n\n    critical_wind_speeds.assign(wind_crit_mps, wind_crit_mps + 6);\n}\n\n// --------------------------------------------------------------------------\ntemplate<typename NT_MESH, typename NT_WIND>\nvoid teca_tc_wind_radii::internals_t::plot_radial_profile(\n    std::ostream &ostr, unsigned long storm_id, unsigned int k,\n    p_teca_variant_array_impl<NT_MESH> rad_all,\n    p_teca_variant_array_impl<NT_WIND> wind_all,\n    p_teca_variant_array_impl<NT_MESH> rad,\n    p_teca_variant_array_impl<NT_WIND> wind,\n    const std::vector<NT_WIND> &crit_wind,\n    const std::vector<unsigned int> &crit_ids,\n    unsigned int peak_id,\n    p_teca_variant_array_impl<NT_MESH> rcross)\n{\n    // generate Python code that can plot the radial profile\n    ostr << \"rad_all = [\";\n    rad_all->to_stream(ostr);\n    ostr << \"]\" << endl;\n\n    ostr << \"wind_all = [\";\n    wind_all->to_stream(ostr);\n    ostr << \"]\" << endl;\n\n    ostr << \"rad = [\";\n    rad->to_stream(ostr);\n    ostr << \"]\" << endl;\n\n    ostr << \"wind = [\";\n    wind->to_stream(ostr);\n    ostr << \"]\" << endl;\n\n    ostr << \"rcross = [\";\n    rcross->to_stream(ostr);\n    ostr << \"]\" << endl;\n\n    unsigned int n_crit_vals = crit_wind.size();\n    ostr << \"crit_wind_req = [\" << crit_wind[0];\n    for (unsigned int i = 1; i < n_crit_vals; ++i)\n        ostr << \", \" << crit_wind[i];\n    ostr << \"]\" << endl;\n\n    ostr << \"crit_rad = [\" << rad->get(crit_ids[0]);\n    for (unsigned int i = 1; i < n_crit_vals; ++i)\n        ostr << \", \" << rad->get(crit_ids[i]);\n    ostr << \"]\" << endl;\n\n    ostr << \"crit_wind_got = [\" << wind->get(crit_ids[0]);\n    for (unsigned int i = 1; i < n_crit_vals; ++i)\n        ostr << \", \" << wind->get(crit_ids[i]);\n    ostr << \"]\" << endl;\n\n    ostr << \"peak_rad = \" << rad->get(peak_id) << endl\n        << \"peak_wind = \" << wind->get(peak_id) << endl;\n\n    ostr << \"dom = [0, max(rad_all)]\" << endl\n        << \"rng = [0, 1.1*max(\" << crit_wind.back()\n        << \", \" << wind->get(peak_id) << \")]\" << endl;\n\n    ostr << \"fig = mpl.figure()\" << endl;\n\n    // crit vals\n    for (unsigned int i = 0; i < n_crit_vals; ++i)\n        ostr << \"mpl.plot(dom, [crit_wind_req[\" << i << \"]\"\n            << \", crit_wind_req[\" << i << \"]], 'r--', alpha=0.5)\"\n            << endl;\n\n    // scatter plot of inputs\n    ostr << \"mpl.plot(rad_all, wind_all, '.', markerfacecolor='none',\"\n        << \" markeredgecolor='#000000', alpha=0.15)\" << endl;\n\n    // line plot wind profile\n    ostr << \"mpl.plot(rad, wind, 'k-', linewidth=2)\" << endl\n        << \"mpl.plot(rad, wind, 'k.')\" << endl;\n\n    // critical radii\n    for (unsigned int i = 0; i < n_crit_vals; ++i)\n        ostr << \"mpl.plot([rcross[\" << i << \"]]*2, [0, crit_wind_req[\" << i << \"]],\"\n            << \" 'b--', alpha=0.5)\" << endl;\n\n    ostr << \"mpl.plot(crit_rad, crit_wind_got, 'b+',\"\n        << \" markerfacecolor='none', markeredgewidth=2)\" << endl;\n\n    ostr << \"mpl.plot(rcross, crit_wind_req, 'bo',\"\n        << \" markerfacecolor='y', markeredgewidth=2)\" << endl;\n\n    // peak raddii\n    ostr << \"mpl.plot([peak_rad]*2, [0, peak_wind],\"\n        << \" 'b--', alpha=0.5)\" << endl;\n\n    ostr << \"mpl.plot(peak_rad, peak_wind, 'b^',\"\n        << \" markerfacecolor='none', markeredgewidth=2)\" << endl;\n\n    // format the plot\n    ostr << \"ax = mpl.gca()\" << endl\n        << \"yl = ax.get_ylim()\" << endl\n        << \"xl = ax.get_xlim()\" << endl\n        << \"yl = [0, yl[1]]\" << endl\n        << \"xl = [0, int(xl[1])]\" << endl\n        << \"mpl.title('radial profile track=\" << storm_id << \" step=\" << k << \"')\" << endl\n        << \"mpl.xlabel('dist to storm center in deg lat')\" << endl\n        << \"mpl.ylabel('wind speed in m/s')\" << endl\n        << \"mpl.grid(True)\" << endl\n        << \"mpl.xlim(dom)\" << endl\n        << \"mpl.ylim(rng)\" << endl;\n\n    // save it\n    ostr << \"mpl.savefig('radial_wind_profile_\"\n        << std::setfill('0') << std::setw(5) << storm_id << \"_\"\n        << std::setfill('0') << std::setw(5) << k << \".png')\"\n        << endl;\n\n    ostr << \"mpl.close(fig)\" << endl\n        << \"sys.stderr.write('*')\" << endl;\n}\n\n\n// --------------------------------------------------------------------------\nteca_tc_wind_radii::teca_tc_wind_radii() : storm_id_column(\"track_id\"),\n    storm_x_coordinate_column(\"lon\"), storm_y_coordinate_column(\"lat\"),\n    storm_wind_speed_column(\"surface_wind\"), storm_time_column(\"time\"),\n    wind_u_variable(\"UBOT\"), wind_v_variable(\"VBOT\"),\n    critical_wind_speeds({\n        teca_saffir_simpson::get_upper_bound_mps<double>(-1),\n        teca_saffir_simpson::get_upper_bound_mps<double>(0),\n        teca_saffir_simpson::get_upper_bound_mps<double>(1),\n        teca_saffir_simpson::get_upper_bound_mps<double>(2),\n        teca_saffir_simpson::get_upper_bound_mps<double>(3),\n        teca_saffir_simpson::get_upper_bound_mps<double>(4)}),\n    search_radius(6.0), core_radius(std::numeric_limits<double>::max()),\n    number_of_radial_bins(32), profile_type(PROFILE_AVERAGE)\n{\n    this->set_number_of_input_connections(1);\n    this->set_number_of_output_ports(1);\n\n    this->internals = new teca_tc_wind_radii::internals_t;\n}\n\n// --------------------------------------------------------------------------\nteca_tc_wind_radii::~teca_tc_wind_radii()\n{\n    delete this->internals;\n}\n\n#if defined(TECA_HAS_BOOST)\n// --------------------------------------------------------------------------\nvoid teca_tc_wind_radii::get_properties_description(const std::string &prefix,\n    options_description &global_opts)\n{\n    options_description opts(\"Options for \"\n        + (prefix.empty()?\"teca_tc_wind_radii\":prefix));\n\n    opts.add_options()\n        TECA_POPTS_GET(std::string, prefix, storm_id_column,\n            \"name of the column containing unique ids of the storms\")\n        TECA_POPTS_GET(std::string, prefix, storm_x_coordinate_column,\n            \"name of the column to create storm x coordinates from\")\n        TECA_POPTS_GET(std::string, prefix, storm_y_coordinate_column,\n            \"name of the column to create storm y coordinates from\")\n        TECA_POPTS_GET(std::string, prefix, storm_time_column,\n            \"name of the column to create storm times from\")\n        TECA_POPTS_GET(std::string, prefix, wind_u_variable,\n            \"name of the variable containing u component of wind\")\n        TECA_POPTS_GET(std::string, prefix, wind_v_variable,\n            \"name of the variable containing v component of wind\")\n        TECA_POPTS_GET(double, prefix, search_radius,\n            \"defines the radius of the search space in deg lat\")\n        TECA_POPTS_GET(double, prefix, core_radius,\n            \"defines the radius inside which the core is expected in deg lat\")\n        TECA_POPTS_MULTI_GET(std::vector<double>, prefix, critical_wind_speeds,\n            \"sets the wind speeds to compute radii at\")\n        TECA_POPTS_GET(int, prefix, number_of_radial_bins,\n            \"sets the number of bins to discretize in the radial direction\")\n        TECA_POPTS_GET(int, prefix, profile_type,\n            \"determines how profile values are computed. for PROFILE_MAX=0 \"\n            \"the max wind speed over each interval is used, for PROFILE_AVERAGE=1 \"\n            \"the average wind speed over the interval is used.\")\n        ;\n\n    this->teca_algorithm::get_properties_description(prefix, opts);\n\n    global_opts.add(opts);\n}\n\n// --------------------------------------------------------------------------\nvoid teca_tc_wind_radii::set_properties(const std::string &prefix,\n    variables_map &opts)\n{\n    this->teca_algorithm::set_properties(prefix, opts);\n\n    TECA_POPTS_SET(opts, std::string, prefix, storm_id_column)\n    TECA_POPTS_SET(opts, std::string, prefix, storm_x_coordinate_column)\n    TECA_POPTS_SET(opts, std::string, prefix, storm_y_coordinate_column)\n    TECA_POPTS_SET(opts, std::string, prefix, storm_time_column)\n    TECA_POPTS_SET(opts, std::string, prefix, wind_u_variable)\n    TECA_POPTS_SET(opts, std::string, prefix, wind_v_variable)\n    TECA_POPTS_SET(opts, std::vector<double>, prefix, critical_wind_speeds)\n    TECA_POPTS_SET(opts, double, prefix, search_radius)\n    TECA_POPTS_SET(opts, double, prefix, core_radius)\n    TECA_POPTS_SET(opts, int, prefix, number_of_radial_bins)\n    TECA_POPTS_SET(opts, int, prefix, profile_type)\n}\n#endif\n\n// --------------------------------------------------------------------------\nvoid teca_tc_wind_radii::set_input_connection(unsigned int id,\n        const teca_algorithm_output_port &port)\n{\n    if (id == 0)\n        this->internals->storm_pipeline_port = port;\n    else\n        this->teca_algorithm::set_input_connection(0, port);\n}\n\n// --------------------------------------------------------------------------\nvoid teca_tc_wind_radii::set_modified()\n{\n    // clear cached metadata before forwarding on to\n    // the base class.\n    this->internals->clear();\n    teca_algorithm::set_modified();\n}\n\n// --------------------------------------------------------------------------\nteca_metadata teca_tc_wind_radii::teca_tc_wind_radii::get_output_metadata(\n    unsigned int port, const std::vector<teca_metadata> &input_md)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id()\n        << \"teca_tc_wind_radii::get_output_metadata\" << endl;\n#endif\n    (void)port;\n    (void)input_md;\n\n    if (this->internals->storm_table)\n        return this->internals->metadata;\n\n    // execute the pipeline that retruns table of tracks\n    const_p_teca_dataset storm_data;\n\n    p_teca_programmable_algorithm capture_storm_data\n        = teca_programmable_algorithm::New();\n\n    capture_storm_data->set_name(\"capture_storm_data\");\n    capture_storm_data->set_input_connection(this->internals->storm_pipeline_port);\n\n    capture_storm_data->set_execute_callback(\n        [&storm_data] (unsigned int, const std::vector<const_p_teca_dataset> &in_data,\n     const teca_metadata &) -> const_p_teca_dataset\n     {\n         storm_data = in_data[0];\n         return nullptr;\n     });\n\n    capture_storm_data->update();\n\n    int rank = 0;\n#if defined(TECA_HAS_MPI)\n    MPI_Comm comm = this->get_communicator();\n    int is_init = 0;\n    MPI_Initialized(&is_init);\n    if (is_init)\n        MPI_Comm_rank(comm, &rank);\n#endif\n    // validate the table\n    if (rank == 0)\n    {\n        // did the pipeline run successfully\n        const_p_teca_table storm_table =\n            std::dynamic_pointer_cast<const teca_table>(storm_data);\n\n        if (!storm_table)\n        {\n            TECA_FATAL_ERROR(\"metadata pipeline failure\")\n        }\n\n        // column need to build random access data structures\n        const_p_teca_variant_array storm_ids =\n            storm_table->get_column(this->storm_id_column);\n\n        if (!storm_ids)\n        {\n            TECA_FATAL_ERROR(\"storm index column \\\"\"\n            << this->storm_id_column << \"\\\" not found\")\n        }\n        // these columns are needed to compute the storm size\n        else\n        if (!storm_table->has_column(this->storm_x_coordinate_column))\n        {\n            TECA_FATAL_ERROR(\"storm x coordinates column \\\"\"\n                << this->storm_x_coordinate_column << \"\\\" not found\")\n        }\n        else\n        if (!storm_table->has_column(this->storm_y_coordinate_column))\n        {\n            TECA_FATAL_ERROR(\"storm y coordinates column \\\"\"\n                << this->storm_y_coordinate_column << \"\\\" not found\")\n        }\n        else\n        if (!storm_table->has_column(this->storm_wind_speed_column))\n        {\n            TECA_FATAL_ERROR(\"storm wind speed column \\\"\"\n                << this->storm_wind_speed_column << \"\\\" not found\")\n        }\n        else\n        if (!storm_table->has_column(this->storm_time_column))\n        {\n            TECA_FATAL_ERROR(\"storm time column \\\"\"\n                << this->storm_time_column << \"\\\" not found\")\n        }\n        // things are ok, take a reference\n        else\n        {\n            this->internals->storm_table = storm_table;\n        }\n    }\n\n    // distribute the table to all processes\n#if defined(TECA_HAS_MPI)\n    if (is_init)\n    {\n        teca_binary_stream bs;\n        if (this->internals->storm_table && (rank == 0))\n            this->internals->storm_table->to_stream(bs);\n        bs.broadcast(comm);\n        if (bs && (rank != 0))\n        {\n           p_teca_table tmp = teca_table::New();\n           tmp->from_stream(bs);\n           this->internals->storm_table = tmp;\n        }\n    }\n#endif\n\n    // build random access data structures\n    const_p_teca_variant_array storm_ids =\n        this->internals->storm_table->get_column(this->storm_id_column);\n\n    TEMPLATE_DISPATCH_I(const teca_variant_array_impl,\n        storm_ids.get(),\n\n        const NT *pstorm_ids = dynamic_cast<TT*>(storm_ids.get())->get();\n\n        teca_coordinate_util::get_table_offsets(pstorm_ids,\n            this->internals->storm_table->get_number_of_rows(),\n            this->internals->number_of_storms, this->internals->storm_counts,\n            this->internals->storm_offsets, this->internals->storm_ids);\n        )\n\n    // must have at least one time storm\n    if (this->internals->number_of_storms < 1)\n    {\n        TECA_FATAL_ERROR(\"Invalid index \\\"\" << this->storm_id_column << \"\\\"\")\n        this->internals->clear();\n        return teca_metadata();\n    }\n\n    // report about the number of storms to the executive and tell\n    // how it can request a specific storm\n    this->internals->metadata.clear();\n\n    this->internals->metadata.set(\n        \"number_of_storms\", this->internals->number_of_storms);\n\n    this->internals->metadata.set(\n        \"index_initializer_key\", std::string(\"number_of_storms\"));\n\n    this->internals->metadata.set(\n        \"index_request_key\", std::string(\"storm_id\"));\n\n    return this->internals->metadata;\n}\n\n// --------------------------------------------------------------------------\nstd::vector<teca_metadata> teca_tc_wind_radii::get_upstream_request(\n    unsigned int port, const std::vector<teca_metadata> &input_md,\n    const teca_metadata &request)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id()\n        << \" teca_tc_wind_radii::get_upstream_request\" << endl;\n#endif\n    (void)port;\n    (void)input_md;\n\n    // get the mesh bounds\n    teca_metadata mesh_coords;\n    input_md[0].get(\"coordinates\", mesh_coords);\n\n    const_p_teca_variant_array mesh_x = mesh_coords.get(\"x\");\n\n    unsigned long mesh_ext[6];\n    input_md[0].get(\"whole_extent\", mesh_ext, 6);\n\n    double mesh_x0, mesh_x1;\n    mesh_x->get(mesh_ext[0], mesh_x0);\n    mesh_x->get(mesh_ext[1], mesh_x1);\n\n    // get id of storm id being requested\n    unsigned long map_id = 0;\n    request.get(\"storm_id\", map_id);\n\n    // get the storm track data, location and time\n    unsigned long id_ofs = this->internals->storm_offsets[map_id];\n    unsigned long n_ids = this->internals->storm_counts[map_id];\n\n    const_p_teca_variant_array\n    x_coordinates = this->internals->storm_table->get_column\n            (this->storm_x_coordinate_column);\n\n    const_p_teca_variant_array\n    y_coordinates = this->internals->storm_table->get_column\n            (this->storm_y_coordinate_column);\n\n    const_p_teca_variant_array\n    times = this->internals->storm_table->get_column\n            (this->storm_time_column);\n\n    // construct the base request\n     std::vector<std::string> arrays\n         ({this->wind_u_variable, this->wind_v_variable});\n\n    teca_metadata base_req;\n    base_req.set(\"arrays\", arrays);\n\n    std::vector<teca_metadata> up_reqs(n_ids, base_req);\n\n    // request the tile of dimension search radius centered on the\n    // storm at this instant\n    unsigned long n_incomplete = 0;\n    TEMPLATE_DISPATCH_FP(const teca_variant_array_impl,\n        x_coordinates.get(),\n        // for each point in track compute the bounding box needed\n        // for the wind profile\n        const NT *px = static_cast<TT*>(x_coordinates.get())->get();\n        const NT *py = static_cast<TT*>(y_coordinates.get())->get();\n        for (unsigned long i = 0; i < n_ids; ++i)\n        {\n            // TODO account for poleward longitude convergence\n            NT x = px[i+id_ofs];\n            NT y = py[i+id_ofs];\n            NT r = static_cast<NT>(this->search_radius);\n\n            NT x0 = x - r;\n            NT x1 = x + r;\n            NT y0 = y - r;\n            NT y1 = y + r;\n\n            // TODO -- implment periodic bc\n            if ((x0 < NT(mesh_x0)) || (x1 > NT(mesh_x1)))\n            {\n                TECA_WARNING(\"In track \" << map_id << \" point \" << i <<\n                    \" requires data across periodic boundary on [\"\n                    << x0 << \", \" << x1 << \", \" << y0 << \", \" << y1 << \"]\")\n\n                // clamp to the valid bounds\n                x0 = std::max(NT(mesh_x0), x0);\n                x1 = std::min(NT(mesh_x1), x1);\n\n                ++n_incomplete;\n            }\n\n            // request the needed subset\n            std::vector<double> bounds({x0, x1, y0, y1, 0.0, 0.0});\n            up_reqs[i].set(\"bounds\", bounds);\n        }\n        )\n\n    // give a summary of incomplete profiles\n    if (n_incomplete)\n    {\n        TECA_WARNING(\"Profiles for \" << n_incomplete << \" of \" << n_ids\n            << \" (\" << ((double)n_incomplete)/n_ids << \") in track \" << map_id\n            << \" are incomplete\")\n    }\n\n    // request the specific time needed\n    TEMPLATE_DISPATCH(const teca_variant_array_impl,\n        times.get(),\n        const NT *pt = static_cast<TT*>(times.get())->get();\n        for (unsigned long i = 0; i < n_ids; ++i)\n            up_reqs[i].set(\"time\", pt[i+id_ofs]);\n        )\n\n#ifdef TECA_DEBUG\n   for (unsigned long i = 0; i < n_ids; ++i)\n   {\n       cerr << \"map_id=\" << map_id << \" req \" << i << \" = \";\n       up_reqs[i].to_stream(cerr);\n       cerr << endl;\n   }\n#endif\n\n    return up_reqs;\n}\n\n// --------------------------------------------------------------------------\nconst_p_teca_dataset teca_tc_wind_radii::execute(unsigned int port,\n    const std::vector<const_p_teca_dataset> &input_data,\n    const teca_metadata &request)\n{\n#ifdef TECA_DEBUG\n    cerr << teca_parallel_id()\n        << \" teca_tc_wind_radii::execute\" << endl;\n    cout << \"import matplotlib.pyplot as mpl\" << endl\n        << \"import sys\" << endl;\n#endif\n    (void)port;\n\n    // get id of storm id being requested\n    unsigned long storm_id = 0;\n    if (request.get(\"storm_id\", storm_id))\n    {\n        TECA_FATAL_ERROR(\"Failed to get the storm id\")\n        return nullptr;\n    }\n\n    // for random access into the specific track\n    unsigned long ofs = this->internals->storm_offsets[storm_id];\n    unsigned long npts = this->internals->storm_counts[storm_id];\n\n    // get storm track positions\n    const_p_teca_variant_array storm_x =\n        this->internals->storm_table->get_column(this->storm_x_coordinate_column);\n\n    const_p_teca_variant_array storm_y =\n        this->internals->storm_table->get_column(this->storm_y_coordinate_column);\n\n    // allocate output columns\n    unsigned int n_crit_vals = this->critical_wind_speeds.size();\n    std::vector<p_teca_double_array> crit_radii(n_crit_vals);\n\n    for (unsigned int i = 0; i < n_crit_vals; ++i)\n        crit_radii[i] = teca_double_array::New(npts, 0.0);\n\n    p_teca_double_array peak_radius = teca_double_array::New(npts, 0.0);\n    p_teca_double_array peak_wind = teca_double_array::New(npts, 0.0);\n\n    // compute radius at each point in time along the storm track\n    NESTED_TEMPLATE_DISPATCH_FP(const teca_variant_array_impl,\n        storm_x.get(), _STORM,\n\n        // get the storm centers\n        const NT_STORM *pstorm_x = static_cast<TT_STORM*>(storm_x.get())->get();\n        const NT_STORM *pstorm_y = static_cast<TT_STORM*>(storm_y.get())->get();\n\n        // for each time instance in the storm compute the storm radius\n        for (unsigned long k = 0; k < npts; ++k)\n        {\n            // get the kth mesh\n            const_p_teca_cartesian_mesh mesh\n                = std::dynamic_pointer_cast<const teca_cartesian_mesh>(input_data[k]);\n\n            if (!mesh)\n            {\n                TECA_FATAL_ERROR(\"input \" << k << \" is empty or not a cartesian mesh\")\n                return nullptr;\n            }\n\n            // and mesh coords.\n            const_p_teca_variant_array mesh_x = mesh->get_x_coordinates();\n            const_p_teca_variant_array mesh_y = mesh->get_y_coordinates();\n\n            double t = 0.0;\n            mesh->get_time(t);\n\n            NESTED_TEMPLATE_DISPATCH_FP(const teca_variant_array_impl,\n                mesh_x.get(), _MESH,\n\n                const NT_MESH *pmesh_x = static_cast<TT_MESH*>(mesh_x.get())->get();\n                const NT_MESH *pmesh_y = static_cast<TT_MESH*>(mesh_y.get())->get();\n\n                unsigned long nx = mesh_x->size();\n                unsigned long ny = mesh_y->size();\n\n                // construct radial discretization\n                p_teca_variant_array_impl<NT_MESH> radius =\n                    teca_variant_array_impl<NT_MESH>::New(this->number_of_radial_bins);\n\n                NT_MESH max_radius = static_cast<NT_MESH>(this->search_radius);\n\n                NT_MESH dr = max_radius/static_cast<NT_MESH>(this->number_of_radial_bins);\n                NT_MESH dr_half = dr/NT_MESH(2);\n\n                NT_MESH *pr = radius->get();\n\n                for (int i = 0; i < this->number_of_radial_bins; ++i)\n                    pr[i] = dr_half + static_cast<NT_MESH>(i)*dr;\n\n                // get the wind components on the input mesh\n                const_p_teca_variant_array wind_u =\n                    mesh->get_point_arrays()->get(this->wind_u_variable);\n\n                const_p_teca_variant_array wind_v =\n                    mesh->get_point_arrays()->get(this->wind_v_variable);\n\n                NESTED_TEMPLATE_DISPATCH_FP(const teca_variant_array_impl,\n                    wind_u.get(), _WIND,\n\n                    const NT_WIND *pwu = static_cast<TT_WIND*>(wind_u.get())->get();\n                    const NT_WIND *pwv = static_cast<TT_WIND*>(wind_v.get())->get();\n\n                    // get the kth storm center\n                    NT_MESH sx = static_cast<NT_MESH>(pstorm_x[k+ofs]);\n                    NT_MESH sy = static_cast<NT_MESH>(pstorm_y[k+ofs]);\n\n                    // compute the radial profile\n                    p_teca_variant_array_impl<NT_MESH> rad_all;\n                    p_teca_variant_array_impl<NT_WIND> wind_all;\n                    p_teca_variant_array_impl<NT_WIND> wind;\n\n                    switch (this->profile_type)\n                    {\n                    case PROFILE_AVERAGE:\n                        wind = teca_tc_wind_radii::internals_t::compute_average_radial_profile\n                                (sx,sy, pmesh_x, pmesh_y, pwu, pwv, nx, ny,\n                                this->number_of_radial_bins, dr, max_radius,\n                                rad_all, wind_all);\n                        break;\n                    case PROFILE_MAX:\n                        wind = teca_tc_wind_radii::internals_t::compute_max_radial_profile\n                                (sx,sy, pmesh_x, pmesh_y, pwu, pwv, nx, ny,\n                                this->number_of_radial_bins, dr, max_radius,\n                                rad_all, wind_all);\n                        break;\n                    default:\n                        TECA_FATAL_ERROR(\"Invalid profile type \\\"\" << this->profile_type << \"\\\"\")\n                        return nullptr;\n                    }\n\n                    // allocate temp for results\n                    unsigned int peak_id = 0;\n                    std::vector<unsigned int> crit_ids(n_crit_vals, 0u);\n                    std::vector<NT_WIND> crit_wind(\n                        this->critical_wind_speeds.begin(),\n                        this->critical_wind_speeds.end());\n\n                    // compute the offsets of the critical radii\n                    NT_WIND *pw = wind->get();\n                    teca_tc_wind_radii::internals_t::locate_critical_ids(\n                        pr, pw, this->number_of_radial_bins,\n                        static_cast<NT_MESH>(this->core_radius),\n                        crit_wind.data(), n_crit_vals, crit_ids.data(),\n                        peak_id);\n\n                    // compute the intercepts with the critical wind speeds\n                    p_teca_variant_array_impl<NT_MESH> rcross =\n                        teca_variant_array_impl<NT_MESH>::New(n_crit_vals, NT_MESH());\n                    NT_MESH *prcross = rcross->get();\n                    teca_tc_wind_radii::internals_t::compute_crossings(pr, pw,\n                        crit_wind.data(), n_crit_vals, crit_ids.data(), prcross);\n\n                    // record critical radii\n                    for (unsigned int i = 0; i < n_crit_vals; ++i)\n                            crit_radii[i]->set(k, prcross[i]);\n\n                    // record peak radius and peak wind speed\n                    peak_radius->set(k,\n                        peak_id == std::numeric_limits<unsigned int>::max() ?\n                        0 : pr[peak_id]);\n\n                    peak_wind->set(k,\n                        peak_id == std::numeric_limits<unsigned int>::max() ?\n                        0 : pw[peak_id]);\n\n#if defined(TECA_DEBUG)\n                    teca_tc_wind_radii::internals_t::plot_radial_profile(\n                        std::cout, storm_id, k, rad_all, wind_all, radius,\n                        wind, crit_wind, crit_ids, peak_id, rcross);\n#endif\n                    )\n                )\n        }\n        )\n\n    // pass the storm track through\n    p_teca_table output = teca_table::New();\n    output->copy(this->internals->storm_table, ofs, npts+ofs-1);\n\n    // add the critial radii\n    for (unsigned int i = 0; i < n_crit_vals; ++i)\n    {\n        std::ostringstream oss;\n        oss << \"wind_radius_\" << i;\n        output->append_column(oss.str(), crit_radii[i]);\n    }\n\n    // add the peak radii and wind speed\n    output->append_column(\"peak_radius\", peak_radius);\n    output->append_column(\"peak_wind_speed\", peak_wind);\n\n    // add the critical wind speed values to the metadata\n    output->get_metadata().set(\n        \"critical_wind_speeds\", this->critical_wind_speeds);\n\n    return output;\n}\n", "meta": {"hexsha": "ca531ae1c341b1b811cab77d05ab0c0b4fa2e66e", "size": 40081, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "alg/teca_tc_wind_radii.cxx", "max_stars_repo_name": "LBL-EESA/TECA", "max_stars_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T14:22:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T05:02:25.000Z", "max_issues_repo_path": "alg/teca_tc_wind_radii.cxx", "max_issues_repo_name": "LBL-EESA/TECA", "max_issues_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 476.0, "max_issues_repo_issues_event_min_datetime": "2016-11-28T18:06:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-25T05:31:42.000Z", "max_forks_repo_path": "alg/teca_tc_wind_radii.cxx", "max_forks_repo_name": "LBL-EESA/TECA", "max_forks_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2017-04-25T18:15:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-28T18:16:05.000Z", "avg_line_length": 35.8827215756, "max_line_length": 97, "alphanum_fraction": 0.5950450338, "num_tokens": 9930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4101776372206061}}
{"text": "/*\n* The MIT License (MIT)\n*\n* Copyright 2020 Barbara Barros Carlos, Tommaso Sartor\n*\n* This file is part of crazyflie_nmpc.\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in all\n* copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n* SOFTWARE.\n*/\n\n\n#include <ros/ros.h>\n#include <std_srvs/Empty.h>\n\n// msgs\n#include <std_msgs/String.h>\n#include <geometry_msgs/PointStamped.h>\n#include <geometry_msgs/Twist.h>\n// crazyflie\n#include <crazyflie_controller/CrazyflieState.h>\n#include <crazyflie_controller/PropellerSpeeds.h>\n#include <crazyflie_controller/CrazyflieStateStamped.h>\n#include <crazyflie_controller/PropellerSpeedsStamped.h>\n#include <crazyflie_controller/CrazyflieOpenloopTraj.h>\n#include <crazyflie_controller/GenericLogData.h>\n\n// Dynamic reconfirgure\n#include <dynamic_reconfigure/server.h>\n#include <boost/thread.hpp>\n#include \"boost/thread/mutex.hpp\"\n// crazyflie\n#include <crazyflie_controller/crazyflie_paramsConfig.h>\n\n// Matrices and vectors\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Geometry>\n\n// standard\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <ios>\n\n// acados\n#include \"acados/utils/print.h\"\n#include \"acados_c/ocp_nlp_interface.h\"\n#include \"acados_c/external_function_interface.h\"\n#include \"acados/ocp_nlp/ocp_nlp_constraints_bgh.h\"\n#include \"acados/ocp_nlp/ocp_nlp_cost_ls.h\"\n\n// blasfeo\n#include \"blasfeo/include/blasfeo_d_aux.h\"\n#include \"blasfeo/include/blasfeo_d_aux_ext_dep.h\"\n\n// crazyflie specific\n#include \"crazyflie_model/crazyflie_model.h\"\n#include \"acados_solver_crazyflie.h\"\n\n// global data\nocp_nlp_in * nlp_in;\nocp_nlp_out * nlp_out;\nocp_nlp_solver * nlp_solver;\nvoid * nlp_opts;\nocp_nlp_plan * nlp_solver_plan;\nocp_nlp_config * nlp_config;\nocp_nlp_dims * nlp_dims;\n\nexternal_function_param_casadi * forw_vde_casadi;\n\nusing namespace Eigen;\nusing std::ofstream;\nusing std::cout;\nusing std::endl;\nusing std::fixed;\nusing std::showpos;\n\n// acados dims\n\n// Number of intervals in the horizon\n#define N 50\n// Number of differential state variables\n#define NX 13\n// Number of control inputs\n#define NU 4\n// Number of measurements/references on nodes 0..N-1\n#define NY 17\n// Number of measurements/references on node N\n#define NYN 13\n// Constants\n#define pi  3.14159265358979323846\n#define g0 9.80665\n\n#define WEIGHT_MATRICES 0\n#define SET_WEIGHTS 0\n#define FIXED_U0 0\n#define CONTROLLER 1\n#define PUB_OPENLOOP_TRAJ 0\n\nclass NMPC\n\t{\n\tenum systemStates{\n\t\txq = 0,\n\t\tyq = 1,\n\t\tzq = 2,\n\t\tqw = 3,\n\t\tqx = 4,\n\t\tqy = 5,\n\t\tqz = 6,\n\t\tvbx = 7,\n\t\tvby = 8,\n\t\tvbz = 9,\n\t\twx = 10,\n\t\twy = 11,\n\t\twz = 12\n\t};\n\n\tenum controlInputs{\n\t\tw1 = 0,\n\t\tw2 = 1,\n\t\tw3 = 2,\n\t\tw4 = 3\n\t};\n\n\tenum reference_mode{\n\t\tRegulation = 0,\n\t\tTracking = 1,\n\t\tPosition_Hold = 2\n\t};\n\n\tstruct euler{\n\t\tdouble phi;\n\t\tdouble theta;\n\t\tdouble psi;\n\t};\n\n\tstruct solver_output{\n\t\tdouble status, KKT_res, cpu_time;\n\t\tdouble u0[NU];\n\t\tdouble u1[NU];\n\t\tdouble x1[NX];\n\t\tdouble x2[NX];\n\t\tdouble x4[NX];\n\t\tdouble xi[NU];\n\t\tdouble ui[NU];\n\t};\n\n\tstruct solver_input{\n\t\tdouble x0[NX];\n\t\tdouble yref[(NY*N)];\n\t\tdouble yref_e[NYN];\n\t\tdouble W[NY*NY];\n\t\tdouble WN[NX*NX];\n\t};\n\n\tros::Publisher p_motvel;\n\tros::Publisher p_bodytwist;\n\t// trajectory\n\tros::Publisher p_ol_traj;\n\n\tros::Subscriber s_estimator;\n\n\tros::Subscriber s_imu_sub;\n\tros::Subscriber s_eRaptor_sub;\n\tros::Subscriber s_euler_sub;\n\tros::Subscriber s_motors;\n\n\t// Variables for joy callback\n\tdouble joy_roll,joy_pitch,joy_yaw;\n\tdouble joy_thrust;\n\n\tunsigned int k,i,j,ii;\n\n\tfloat uss,Ct,mq;\n\n\t// Variables of the nmpc control process\n\tdouble x0_sign[NX];\n\tdouble yref_sign[(NY*N)+NY];\n\n\t// Variables for dynamic reconfigure\n\tdouble xq_des, yq_des, zq_des;\n\n\t// Variables for dynamic reconfigure\n\tdouble Wdiag_xq,Wdiag_yq,Wdiag_zq;\n\tdouble Wdiag_qw,Wdiag_qx,Wdiag_qy,Wdiag_qz;\n\tdouble Wdiag_vbx,Wdiag_vby,Wdiag_vbz;\n\tdouble Wdiag_wx,Wdiag_wy,Wdiag_wz;\n\tdouble Wdiag_w1,Wdiag_w2,Wdiag_w3,Wdiag_w4;\n\tdouble WN_factor;\n\n\t// acados struct\n\tsolver_input acados_in;\n\tsolver_output acados_out;\n\tint acados_status;\n\n\treference_mode policy;\n\n\t// Variable for storing the optimal trajectory\n\tstd::vector<std::vector<double>> precomputed_traj;\n\tint N_STEPS,iter;\n\npublic:\n\n\tNMPC(ros::NodeHandle& n, const std::string& ref_traj)\n\t\t{\n\n\t\tint status = 0;\n\t\tdouble WN_factor = 50;\n\n\t\tstatus = acados_create();\n\n\t\tif (status){\n\t\t\tROS_INFO_STREAM(\"acados_create() returned status \" << status << \". Exiting.\" << endl);\n\t\t\texit(1);\n\t\t}\n\n\t\t// publisher for the real robot inputs (thrust, roll, pitch, yawrate)\n\t\tp_bodytwist = n.advertise<geometry_msgs::Twist>(\"/crazyflie/cmd_vel\", 1);\n\n\t\t// publisher for the control inputs of acados (motor speeds to be applied)\n\t\tp_motvel = n.advertise<crazyflie_controller::PropellerSpeedsStamped>(\"/crazyflie/acados_motvel\", 1);\n\n\t\t// solution\n\t\tp_ol_traj = n.advertise<crazyflie_controller::CrazyflieOpenloopTraj>(\"/cf_mpc/openloop_traj\", 2);\n\n\t\t// subscriber of estimator state\n\t\ts_estimator = n.subscribe(\"/cf_estimator/state_estimate\", 5, &NMPC::iteration, this);\n\n\t\t// Initializing control inputs\n\t\tfor(unsigned int i=0; i < NU; i++) acados_out.u0[i] = 0.0;\n\n\t\t// Steady-state control input value\n\t\t// (Kg)\n\t\tmq = 33e-3;\n\t\t// (N/kRPM^2)\n\t\tCt = 3.25e-4;\n\t\t// steady state prop speed (kRPM)\n\t\tuss = sqrt((mq*g0)/(4*Ct));\n\n\t\tconst char * c = ref_traj.c_str();\n\n\t\t// Pre-load the trajectory\n\t\tN_STEPS = readDataFromFile(c, precomputed_traj);\n\t\tif (N_STEPS == 0){\n\t\t\tROS_WARN(\"Cannot load CasADi optimal trajectory!\");\n\t\t}\n\t\telse{\n\t\t\tROS_INFO_STREAM(\"Number of steps of selected trajectory: \" << N_STEPS << endl);\n\t\t}\n\t\t// Initialize dynamic reconfigure options\n\t\txq_des = 0;\n\t\tyq_des = 0;\n\t\tzq_des = 0;\n\n\t\t// Set number of trajectory iterations to zero initially\n\t\titer = 0;\n\n\t\t// Set weight matrix values\n\t\tWdiag_xq\t= 120.0 ;\n\t\tWdiag_yq\t= 100.0 ;\n\t\tWdiag_zq\t= 100.0 ;\n\t\tWdiag_qw\t= 1.0e-3;\n\t\tWdiag_qx\t= 1.0e-3;\n\t\tWdiag_qy\t= 1.0e-3;\n\t\tWdiag_qz\t= 1.0e-3;\n\t\tWdiag_vbx\t= 7e-1  ;\n\t\tWdiag_vby\t= 1.0   ;\n\t\tWdiag_vbz\t= 4.0   ;\n\t\tWdiag_wx\t= 1.0e-5;\n\t\tWdiag_wy\t= 1.0e-5;\n\t\tWdiag_wz\t= 10.0  ;\n\t\tWdiag_w1\t= 0.06  ;\n\t\tWdiag_w2\t= 0.06  ;\n\t\tWdiag_w3\t= 0.06  ;\n\t\tWdiag_w4\t= 0.06  ;\n\t\t}\n\n\tvoid run()\n\t\t{\n\t\tROS_DEBUG(\"Setting up the dynamic reconfigure panel and server\");\n\n\t\t\tdynamic_reconfigure::Server<crazyflie_controller::crazyflie_paramsConfig> server;\n\t\t\tdynamic_reconfigure::Server<crazyflie_controller::crazyflie_paramsConfig>::CallbackType f;\n\t\t\tf = boost::bind(&NMPC::callback_dynamic_reconfigure, this, _1, _2);\n\t\t\tserver.setCallback(f);\n\n\t\tros::spin();\n\t\t}\n\n\tvoid callback_dynamic_reconfigure(crazyflie_controller::crazyflie_paramsConfig &config, uint32_t level)\n\t\t{\n\t\tif (level && CONTROLLER)\n\t\t\t{\n\t\t\tif(config.enable_traj_tracking)\n\t\t\t\t{\n\t\t\t\tROS_INFO_STREAM(\"Tracking trajectory\");\n\t\t\t\tconfig.enable_regulation = false;\n\t\t\t\tpolicy = Tracking;\n\t\t\t\t}\n\t\t\tif(config.enable_regulation)\n\t\t\t\t{\n\t\t\t\tconfig.enable_traj_tracking = false;\n\t\t\t\txq_des = config.xq_des;\n\t\t\t\tyq_des = config.yq_des;\n\t\t\t\tzq_des = config.zq_des;\n\t\t\t\tpolicy = Regulation;\n\t\t\t\t}\n\t\t\t\tROS_INFO_STREAM(\n\t\t\t\t\tfixed << showpos << \"Quad status\" << endl\n\t\t\t\t\t<< \"NMPC for regulation: \" <<  (config.enable_regulation?\"ON\":\"off\") << endl\n\t\t\t\t\t<< \"NMPC trajectory tracker: \" <<  (config.enable_traj_tracking?\"ON\":\"off\") << endl\n\t\t\t\t\t<< \"Current regulation point: \" << xq_des << \", \" << yq_des << \", \" << zq_des << endl\n\t\t\t\t);\n\t\t\t}\n\n\t\tif (level && WEIGHT_MATRICES)\n\t\t {\n\t\t\t\tROS_INFO(\"Changing the weight of NMPC matrices!\");\n\t\t\t\tWdiag_xq\t= config.Wdiag_xq;\n\t\t\t\tWdiag_yq\t= config.Wdiag_yq;\n\t\t\t\tWdiag_zq\t= config.Wdiag_zq;\n\t\t\t\tWdiag_qw\t= config.Wdiag_qw;\n\t\t\t\tWdiag_qx\t= config.Wdiag_qx;\n\t\t\t\tWdiag_qy\t= config.Wdiag_qy;\n\t\t\t\tWdiag_qz\t= config.Wdiag_qz;\n\t\t\t\tWdiag_vbx\t= config.Wdiag_vbx;\n\t\t\t\tWdiag_vby\t= config.Wdiag_vby;\n\t\t\t\tWdiag_vbz\t= config.Wdiag_vbz;\n\t\t\t\tWdiag_wx\t= config.Wdiag_wx;\n\t\t\t\tWdiag_wy\t= config.Wdiag_wy;\n\t\t\t\tWdiag_wz\t= config.Wdiag_wz;\n\t\t\t\tWdiag_w1\t= config.Wdiag_w1;\n\t\t\t\tWdiag_w2\t= config.Wdiag_w2;\n\t\t\t\tWdiag_w3\t= config.Wdiag_w3;\n\t\t\t\tWdiag_w4\t= config.Wdiag_w4;\n\t\t }\n\t\t}\n\n\tint readDataFromFile(const char* fileName, std::vector<std::vector<double>> &data)\n\t\t{\n\t\tstd::ifstream file(fileName);\n\t\tstd::string line;\n\t\tint num_of_steps = 0;\n\n\t\tif (file.is_open())\n\t\t\t{\n\t\t\twhile(getline(file, line)){\n\t\t\t\t++num_of_steps;\n\t\t\t\tstd::istringstream linestream( line );\n\t\t\t\tstd::vector<double> linedata;\n\t\t\t\tdouble number;\n\n\t\t\t\twhile( linestream >> number ){\n\t\t\t\t\tlinedata.push_back( number );\n\t\t\t\t}\n\t\t\t\tdata.push_back( linedata );\n\t\t\t}\n\n\t\t\tfile.close();\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\treturn 0;\n\t\t\t}\n\n\t\treturn num_of_steps;\n\t\t}\n\n\teuler quatern2euler(Quaterniond* q)\n\t\t{\n\n\t\teuler angle;\n\n\t\tdouble R11 = 2*(q->w()*q->w()+q->x()*q->x())-1;\n\t\tdouble R21 = 2*(q->x()*q->y()-q->w()*q->z());\n\t\tdouble R31 = 2*(q->x()*q->z()+q->w()*q->y());\n\t\tdouble R32 = 2*(q->y()*q->z()-q->w()*q->x());\n\t\tdouble R33 = 2*(q->w()*q->w()+q->z()*q->z())-1;\n\n\t\tdouble phi\t = atan2(R32, R33);\n\t\tdouble theta = -asin(R31);\n\t\tdouble psi\t = atan2(R21, R11);\n\n\t\tangle.phi\t\t = phi;\n\t\tangle.theta  = theta;\n\t\tangle.psi\t   = psi;\n\n\t\treturn angle;\n\t\t}\n\n\tdouble deg2Rad(double deg)\n\t\t{\n\t\treturn deg / 180.0 * pi;\n\t\t}\n\n\tdouble rad2Deg(double rad)\n\t\t{\n\t\treturn rad * 180.0 / pi;\n\t\t}\n\n\tvoid nmpcReset()\n\t\t{\n\t\tacados_free();\n\t\t}\n\n\tint krpm2pwm(double Krpm)\n\t\t{\n\t\tint pwm = ((Krpm*1000)-4070.3)/0.2685;\n\t\treturn pwm;\n\t\t}\n\n\tvoid iteration(const crazyflie_controller::CrazyflieStateStampedPtr& msg)\n\t\t{\n\t\t\ttry{\n\t\t\t\t\tswitch(policy){\n\n\t\t\t\t\t  case Regulation:\n\t\t\t\t\t  {\n\t\t\t\t\t    // Update regulation point\n\t\t\t\t\t    for (k = 0; k < N+1; k++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t  yref_sign[k * NY + 0] = xq_des; // xq\n\t\t\t\t\t\t\t  yref_sign[k * NY + 1] = yq_des;\t// yq\n\t\t\t\t\t\t\t  yref_sign[k * NY + 2] = zq_des;\t// zq\n\t\t\t\t\t\t\t  yref_sign[k * NY + 3] = 1.00;\t\t// qw\n\t\t\t\t\t\t\t  yref_sign[k * NY + 4] = 0.00;\t\t// qx\n\t\t\t\t\t\t\t  yref_sign[k * NY + 5] = 0.00;\t\t// qy\n\t\t\t\t\t\t\t  yref_sign[k * NY + 6] = 0.00;\t\t// qz\n\t\t\t\t\t\t\t  yref_sign[k * NY + 7] = 0.00;\t\t// vbx\n\t\t\t\t\t\t\t  yref_sign[k * NY + 8] = 0.00;\t\t// vby\n\t\t\t\t\t\t\t  yref_sign[k * NY + 9] = 0.00;\t\t// vbz\n\t\t\t\t\t\t\t  yref_sign[k * NY + 10] = 0.00;\t// wx\n\t\t\t\t\t\t\t  yref_sign[k * NY + 11] = 0.00;\t// wy\n\t\t\t\t\t\t\t  yref_sign[k * NY + 12] = 0.00;\t// wz\n\t\t\t\t\t\t\t  yref_sign[k * NY + 13] = uss;\t\t// w1\n\t\t\t\t\t\t\t  yref_sign[k * NY + 14] = uss;\t\t// w2\n\t\t\t\t\t\t\t  yref_sign[k * NY + 15] = uss;\t\t// w3\n\t\t\t\t\t\t\t  yref_sign[k * NY + 16] = uss;\t\t// w4\n\t\t\t\t\t    }\n\t\t\t\t\t    break;\n\t\t\t\t\t  }\n\n\t\t\t\t\t  case Tracking:\n\t\t\t\t\t  {\n\t\t\t\t\t    if(iter < N_STEPS-N)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t// Update reference\n\t\t\t\t\t\t \t\t\tfor (k = 0; k < N+1; k++)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t \t\t      yref_sign[k * NY + 0] = precomputed_traj[iter + k][xq];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 1] = precomputed_traj[iter + k][yq];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 2] = precomputed_traj[iter + k][zq];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 3] = precomputed_traj[iter + k][qw];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 4] = precomputed_traj[iter + k][qx];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 5] = precomputed_traj[iter + k][qy];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 6] = precomputed_traj[iter + k][qz];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 7] = precomputed_traj[iter + k][vbx];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 8] = precomputed_traj[iter + k][vby];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 9] = precomputed_traj[iter + k][vbz];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 10] = precomputed_traj[iter + k][wx];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 11] = precomputed_traj[iter + k][wy];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 12] = precomputed_traj[iter + k][wz];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 13] = precomputed_traj[iter + k][13];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 14] = precomputed_traj[iter + k][14];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 15] = precomputed_traj[iter + k][15];\n\t\t\t\t\t\t\t\t      yref_sign[k * NY + 16] = precomputed_traj[iter + k][16];\n\t\t\t\t\t \t\t\t\t}\n\t\t\t\t\t\t\t\t\t++iter;\n\t\t\t\t\t\t\t//cout << iter << endl;\n\t\t\t\t\t    }\n\t\t\t \t    else policy = Position_Hold;\n\t\t\t\t    break;\n\t\t\t\t\t  }\n\n\t\t\t\t\t  case Position_Hold:\n\t\t\t\t\t  \t{\n\t\t\t\t\t\t    ROS_INFO(\"Holding last position of the trajectory.\");\n\t\t\t\t\t\t    // Get last point of tracketory and hold\n\t\t\t\t\t\t    for (k = 0; k < N+1; k++)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 0] = precomputed_traj[N_STEPS-1][xq];\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 1] = precomputed_traj[N_STEPS-1][yq];\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 2] = precomputed_traj[N_STEPS-1][zq];\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 3] = 1.00;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 4] = 0.00;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 5] = 0.00;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 6] = 0.00;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 7] = 0.00;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 8] = 0.00;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 9] = 0.00;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 10] = 0.00;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 11] = 0.00;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 12] = 0.00;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 13] = uss;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 14] = uss;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 15] = uss;\n\t\t\t\t\t\t\t\t    yref_sign[k * NY + 16] = uss;\n\t\t\t\t\t\t      }\n\t\t\t\t\t  }\n\t\t\t\t\t  break;\n\t\t\t\t\t}\n\n\t\t\t// --- Set Weights\n\t\t\tfor (ii = 0; ii < ((NY)*(NY)); ii++) {\n\t\t\t\tacados_in.W[ii] = 0.0;\n\t\t\t}\n\t\t\tfor (ii = 0; ii < ((NX)*(NX)); ii++) {\n\t\t\t\tacados_in.WN[ii] = 0.0;\n\t\t\t}\n\n\t\t\tacados_in.W[0+0*(NU+NX)]   = Wdiag_xq;\n\t\t\tacados_in.W[1+1*(NU+NX)]   = Wdiag_yq;\n\t\t\tacados_in.W[2+2*(NU+NX)]   = Wdiag_zq;\n\t\t\tacados_in.W[3+3*(NU+NX)]   = Wdiag_qw;\n\t\t\tacados_in.W[4+4*(NU+NX)]   = Wdiag_qx;\n\t\t\tacados_in.W[5+5*(NU+NX)]   = Wdiag_qy;\n\t\t\tacados_in.W[6+6*(NU+NX)]   = Wdiag_qz;\n\t\t\tacados_in.W[7+7*(NU+NX)]   = Wdiag_vbx;\n\t\t\tacados_in.W[8+8*(NU+NX)]   = Wdiag_vby;\n\t\t\tacados_in.W[9+9*(NU+NX)]   = Wdiag_vbz;\n\t\t\tacados_in.W[10+10*(NU+NX)] = Wdiag_wx;\n\t\t\tacados_in.W[11+11*(NU+NX)] = Wdiag_wy;\n\t\t\tacados_in.W[12+12*(NU+NX)] = Wdiag_wz;\n\t\t\tacados_in.W[13+13*(NU+NX)] = Wdiag_w1;\n\t\t\tacados_in.W[14+14*(NU+NX)] = Wdiag_w2;\n\t\t\tacados_in.W[15+15*(NU+NX)] = Wdiag_w3;\n\t\t\tacados_in.W[16+16*(NU+NX)] = Wdiag_w4;\n\n\t\t\tacados_in.WN[0+0*(NX)]   = Wdiag_xq*WN_factor;\n\t\t\tacados_in.WN[1+1*(NX)]   = Wdiag_yq*WN_factor;\n\t\t\tacados_in.WN[2+2*(NX)]   = Wdiag_zq*WN_factor;\n\t\t\tacados_in.WN[3+3*(NX)]   = Wdiag_qw*WN_factor;\n\t\t\tacados_in.WN[4+4*(NX)]   = Wdiag_qx*WN_factor;\n\t\t\tacados_in.WN[5+5*(NX)]   = Wdiag_qy*WN_factor;\n\t\t\tacados_in.WN[6+6*(NX)]   = Wdiag_qz*WN_factor;\n\t\t\tacados_in.WN[7+7*(NX)]   = Wdiag_vbx*WN_factor;\n\t\t\tacados_in.WN[8+8*(NX)]   = Wdiag_vby*WN_factor;\n\t\t\tacados_in.WN[9+9*(NX)]   = Wdiag_vbz*WN_factor;\n\t\t\tacados_in.WN[10+10*(NX)] = Wdiag_wx*WN_factor;\n\t\t\tacados_in.WN[11+11*(NX)] = Wdiag_wy*WN_factor;\n\t\t\tacados_in.WN[12+12*(NX)] = Wdiag_wz*WN_factor;\n\n\t\t\t// --- Read Estimate\n\t\t\t// position\n\t\t\tacados_in.x0[xq] = msg->pos.x;\n\t\t\tacados_in.x0[yq] = msg->pos.y;\n\t\t\tacados_in.x0[zq] = msg->pos.z;\n\n\t\t\t// quaternion\n\t\t\tacados_in.x0[qw] = msg->quat.w;\n\t\t\tacados_in.x0[qx] = msg->quat.x;\n\t\t\tacados_in.x0[qy] = msg->quat.y;\n\t\t\tacados_in.x0[qz] = msg->quat.z;\n\n\t\t\t// body velocities\n\t\t\tacados_in.x0[vbx] = msg->vel.x;\n\t\t\tacados_in.x0[vby] = msg->vel.y;\n\t\t\tacados_in.x0[vbz] = msg->vel.z;\n\n\t\t\t// rates\n\t\t\tacados_in.x0[wx] = msg->rates.x;\n\t\t\tacados_in.x0[wy] = msg->rates.y;\n\t\t\tacados_in.x0[wz] = msg->rates.z;\n\n\t\t\t// --- acados NMPC\n\t\t\tocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, \"lbx\", acados_in.x0);\n\t\t\tocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, \"ubx\", acados_in.x0);\n\n\t\t\tfor (i = 0; i < N; i++) {\n\t    \tfor (j = 0; j < NY; ++j) acados_in.yref[i*NY + j] = yref_sign[i*NY + j];\n\t\t\t}\n\n\t\t\tfor (i = 0; i < NYN; i++) acados_in.yref_e[i] = yref_sign[N*NY + i];\n\n\t\t\tfor (ii = 0; ii < N; ii++)\n\t\t\t\t{\n\t\t\t\tocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, ii, \"yref\", acados_in.yref + ii*NY);\n\t\t\t\t}\n\t\t\tocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, \"yref\", acados_in.yref_e);\n\n\t\t\t#if SET_WEIGHTS\n\t\t\tfor (ii = 0; ii < N; ii++)\n\t\t\t\t{\n\t\t\t\tocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, ii, \"W\", acados_in.W);\n\t\t\t\t}\n\t\t\t\tocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, \"W\", acados_in.WN);\n\t\t\t#endif\n\n\t\t\t// set constraints\n\t\t\t#if FIXED_U0\n\t\t\t\tocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, \"lbu\", acados_out.u1);\n\t\t\t\tocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, \"ubu\", acados_out.u1);\n\t\t\t#endif\n\n\t\t\t// call solver\n\t\t\tacados_status = acados_solve();\n\n\t\t\t// assign output signals\n\t\t\tacados_out.status = acados_status;\n\t\t\tacados_out.KKT_res = (double)nlp_out->inf_norm_res;\n\t\t\tacados_out.cpu_time = (double)nlp_out->total_time;\n\n\t\t\t// get solution\n\t\t\tocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, 0, \"u\", (void *)acados_out.u0);\n\n\t\t\t// get solution at stage N = 1\n\t\t\tocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, 1, \"u\", (void *)acados_out.u1);\n\n\t\t\t// get solution at stage N = 4 which compensates 60 ms delay\n\t\t\tocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, 4, \"x\", (void *)acados_out.x4);\n\n\t\t\t// publish acados output\n\t\t\tcrazyflie_controller::PropellerSpeedsStamped propellerspeeds;\n\t\t\tpropellerspeeds.header.stamp = ros::Time::now();\n\n\t\t\tif (FIXED_U0 == 1) {\n\t\t\t\tpropellerspeeds.w1 =  acados_out.u1[w1];\n\t\t\t\tpropellerspeeds.w2 =  acados_out.u1[w2];\n\t\t\t\tpropellerspeeds.w3 =  acados_out.u1[w3];\n\t\t\t\tpropellerspeeds.w4 =  acados_out.u1[w4];\n\t\t\t} else {\n\t\t\t\tpropellerspeeds.w1 =  acados_out.u0[w1];\n\t\t\t\tpropellerspeeds.w2 =  acados_out.u0[w2];\n\t\t\t\tpropellerspeeds.w3 =  acados_out.u0[w3];\n\t\t\t\tpropellerspeeds.w4 =  acados_out.u0[w4];\n\t\t\t}\n\t\t\tp_motvel.publish(propellerspeeds);\n\n\t\t\t// Select the set of optimal states to calculate the real cf control inputs\n\t\t\tQuaterniond q_acados_out;\n\t\t\tq_acados_out.w() = acados_out.x4[qw];\n\t\t\tq_acados_out.x() = acados_out.x4[qx];\n\t\t\tq_acados_out.y() = acados_out.x4[qy];\n\t\t\tq_acados_out.z() = acados_out.x4[qz];\n\t\t\tq_acados_out.normalize();\n\n\t\t\t// Convert acados output quaternion to desired euler angles\n\t\t\teuler eu_imu;\n\t\t\teu_imu = quatern2euler(&q_acados_out);\n\n\t\t\t// Publish real control inputs\n\t\t\tgeometry_msgs::Twist bodytwist;\n\n\t\t\t// linear_x -> pitch\n\t\t\tbodytwist.linear.x  = 1.0*rad2Deg(eu_imu.theta);\n\t\t\t// linear_y -> roll\n\t\t\tbodytwist.linear.y  = -1.0*rad2Deg(eu_imu.phi);\n\t\t\t// linear_z -> thrust\n\t\t\tbodytwist.linear.z  = krpm2pwm(\n\t\t\t\t(acados_out.u1[w1]+acados_out.u1[w2]+acados_out.u1[w3]+acados_out.u1[w4])/4\n\t\t\t);\n\t\t\t// angular_z -> yaw rate\n\t\t\tbodytwist.angular.z = rad2Deg(acados_out.x4[wz]);\n\n\t\t\tp_bodytwist.publish(bodytwist);\n\n\t\t\t// --- Publish openloop\n\t\t\t#if PUB_OPENLOOP_TRAJ\n\n\t\t\tcrazyflie_controller::CrazyflieOpenloopTraj traj_msg;\n\t\t\ttraj_msg.header.stamp = ros::Time::now();\n\t\t\ttraj_msg.cpu_time = acados_out.cpu_time;\n\n\t\t\tfor(ii=0; ii< N; ii++)\n\t\t\t\t{\n\t\t\t\tocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, \"x\", (void *)(acados_out.xi));\n\t\t\t\tocp_nlp_out_get(nlp_config, nlp_dims, nlp_out, ii, \"u\", (void *)(acados_out.ui));\n\n\t\t\t\tcrazyflie_controller::CrazyflieState crazyflie_state;\n\t\t\t\tcrazyflie_controller::PropellerSpeeds crazyflie_control;\n\n\t\t\t\tcrazyflie_state.pos.x    = acados_out.xi[xq];\n\t\t\t\tcrazyflie_state.pos.y    = acados_out.xi[yq];\n\t\t\t\tcrazyflie_state.pos.z    = acados_out.xi[zq];\n\t\t\t\tcrazyflie_state.vel.x    = acados_out.xi[vbx];\n\t\t\t\tcrazyflie_state.vel.y    = acados_out.xi[vby];\n\t\t\t\tcrazyflie_state.vel.z    = acados_out.xi[vbz];\n\t\t\t\tcrazyflie_state.quat.w   = acados_out.xi[qw];\n\t\t\t\tcrazyflie_state.quat.x   = acados_out.xi[qx];\n\t\t\t\tcrazyflie_state.quat.y   = acados_out.xi[qy];\n\t\t\t\tcrazyflie_state.quat.z   = acados_out.xi[qz];\n\t\t\t\tcrazyflie_state.rates.x  = acados_out.xi[wx];\n\t\t\t\tcrazyflie_state.rates.y  = acados_out.xi[wy];\n\t\t\t\tcrazyflie_state.rates.z  = acados_out.xi[wz];\n\n\t\t\t\tcrazyflie_control.w1 = acados_out.ui[w1];\n\t\t\t\tcrazyflie_control.w2 = acados_out.ui[w2];\n\t\t\t\tcrazyflie_control.w3 = acados_out.ui[w3];\n\t\t\t\tcrazyflie_control.w4 = acados_out.ui[w4];\n\n\t\t\t\ttraj_msg.states.push_back(crazyflie_state);\n\t\t\t\ttraj_msg.controls.push_back(crazyflie_control);\n\t\t\t\t}\n\n\t\t\tp_ol_traj.publish(traj_msg);\n\t\t\t#endif\n\t\t\t}\n\n\t\tcatch (int acados_status)\n\t\t\t{\n\t\t\tROS_INFO_STREAM(\"An exception occurred. Exception Nr. \" << acados_status << endl);\n\t\t\t}\n\t\t}\n\t};\n\nint main(int argc, char **argv)\n{\n\tros::init(argc, argv, \"cf_nmpc\");\n\n\tros::NodeHandle n(\"~\");\n\n\tstd::string ref_traj;\n\tn.getParam(\"ref_traj\", ref_traj);\n\n\tNMPC nmpc(n,ref_traj);\n\tnmpc.run();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "e9eaff325b173f490d02d88635b18fe8c6b0e4e0", "size": 20830, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "crazyflie_controller/src/acados_mpc.cpp", "max_stars_repo_name": "bcbarbara/crazy", "max_stars_repo_head_hexsha": "d01f10b8b08056e4dd6fbaf34ebca5e5c6306e20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2020-01-23T14:07:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T05:00:48.000Z", "max_issues_repo_path": "crazyflie_controller/src/acados_mpc.cpp", "max_issues_repo_name": "bcbarbara/crazy", "max_issues_repo_head_hexsha": "d01f10b8b08056e4dd6fbaf34ebca5e5c6306e20", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-04-16T09:48:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-04T10:50:49.000Z", "max_forks_repo_path": "crazyflie_controller/src/acados_mpc.cpp", "max_forks_repo_name": "bcbarbara/crazy", "max_forks_repo_head_hexsha": "d01f10b8b08056e4dd6fbaf34ebca5e5c6306e20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2020-01-23T14:07:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T14:45:42.000Z", "avg_line_length": 28.3401360544, "max_line_length": 104, "alphanum_fraction": 0.6393662986, "num_tokens": 7325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.4101776372206061}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2006 Klaus Spanderen\n Copyright (C) 2010 Kakhkhor Abdijalilov\n \n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file lsmbasissystem.cpp\n    \\brief utility classes for longstaff schwartz early exercise Monte Carlo\n*/\n// lsmbasissystem.hpp\n\n#include <ql/math/integrals/gaussianquadratures.hpp>\n#include <ql/methods/montecarlo/lsmbasissystem.hpp>\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-local-typedefs\"\n#endif\n\n#include <boost/bind.hpp>\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))\n#pragma GCC diagnostic pop\n#endif\n\n#include <set>\n#include <numeric>\n\nnamespace QuantLib {\n    namespace {\n\n        // makes typing a little easier\n        typedef std::vector<boost::function1<Real, Real> > VF_R;\n        typedef std::vector<boost::function1<Real, Array> > VF_A;\n        typedef std::vector<std::vector<Size> > VV;\n        Real (GaussianOrthogonalPolynomial::*ptr_w)(Size, Real) const =\n            &GaussianOrthogonalPolynomial::weightedValue;\n\n        // pow(x, order)\n        class MonomialFct : public std::unary_function<Real, Real> {\n          public:\n            explicit MonomialFct(Size order): order_(order) {}\n            inline Real operator()(const Real x) const {\n                Real ret = 1.0;\n                for(Size i=0; i<order_; ++i)\n                    ret *= x;\n                return ret;\n            }\n          private:\n            const Size order_;\n        };\n\n        /* multiplies [Real -> Real] functors\n           to create [Array -> Real] functor */\n        class MultiDimFct : public std::unary_function<Real, Array> {\n          public:\n            explicit MultiDimFct(const VF_R& b): b_(b) {\n                QL_REQUIRE(b_.size()>0, \"zero size basis\");\n            }\n            inline Real operator()(const Array& a) const {\n                #if defined(QL_EXTRA_SAFETY_CHECKS)\n                QL_REQUIRE(b_.size()==a.size(), \"wrong argument size\");\n                #endif\n                Real ret = b_[0].operator()(a[0]);\n                for(Size i=1; i<b_.size(); ++i)\n                    ret *= b_[i].operator()(a[i]);\n                return ret;\n            }\n          private:\n            const VF_R b_;\n        };\n\n        // check size and order of tuples\n        void check_tuples(const VV& v, Size dim, Size order) {\n            for(Size i=0; i<v.size(); ++i) {\n                QL_REQUIRE(dim==v[i].size(), \"wrong tuple size\");\n                QL_REQUIRE(order==std::accumulate(v[i].begin(), v[i].end(), 0u),\n                    \"wrong tuple order\");\n            }\n        }\n\n        // build order N+1 tuples from order N tuples\n        VV next_order_tuples(const VV& v) {\n            const Size order = std::accumulate(v[0].begin(), v[0].end(), 0u);\n            const Size dim = v[0].size();\n\n            check_tuples(v, dim, order);\n\n            // the set of unique tuples\n            std::set<std::vector<Size> > tuples;\n            std::vector<Size> x;\n            for(Size i=0; i<dim; ++i) {\n                // increase i-th value in every tuple by 1\n                for(Size j=0; j<v.size(); ++j) {\n                    x = v[j];\n                    x[i] += 1;\n                    tuples.insert(x);\n                }\n            }\n\n            VV ret(tuples.begin(), tuples.end());\n            return ret;\n        }\n    } \n\n    // LsmBasisSystem static methods\n\n    VF_R LsmBasisSystem::pathBasisSystem(Size order, PolynomType polyType) {\n        VF_R ret(order+1);\n        for (Size i=0; i<=order; ++i) {\n            switch (polyType) {\n              case Monomial:\n                ret[i] = MonomialFct(i);\n                break;\n              case Laguerre:\n                ret[i] = boost::bind(ptr_w, GaussLaguerrePolynomial(), i, _1);\n                break;\n              case Hermite:\n                ret[i] = boost::bind(ptr_w, GaussHermitePolynomial(), i, _1);\n                break;\n              case Hyperbolic:\n                ret[i] = boost::bind(ptr_w, GaussHyperbolicPolynomial(), i, _1);\n                break;\n              case Legendre:\n                ret[i] = boost::bind(ptr_w, GaussLegendrePolynomial(), i, _1);\n                break;\n              case Chebyshev:\n                ret[i] = boost::bind(ptr_w, GaussChebyshevPolynomial(), i, _1);\n                break;\n              case Chebyshev2nd:\n                ret[i] = boost::bind(ptr_w,GaussChebyshev2ndPolynomial(),i, _1);\n                break;\n              default:\n                QL_FAIL(\"unknown regression type\");\n            }\n        }\n        return ret;\n    }\n\n    VF_A LsmBasisSystem::multiPathBasisSystem(Size dim, Size order,\n                                              PolynomType polyType) {\n        QL_REQUIRE(dim>0, \"zero dimension\");\n        // get single factor basis\n        VF_R pathBasis = pathBasisSystem(order, polyType);\n        VF_A ret;\n        // 0-th order term\n        VF_R term(dim, pathBasis[0]);\n        ret.push_back(MultiDimFct(term));\n        // start with all 0 tuple\n        VV tuples(1, std::vector<Size>(dim));\n        // add multi-factor terms\n        for(Size i=1; i<=order; ++i) {\n            tuples = next_order_tuples(tuples);\n            // now we have all tuples of order i\n            // for each tuple add the corresponding term\n            for(Size j=0; j<tuples.size(); ++j) {\n                for(Size k=0; k<dim; ++k)\n                    term[k] = pathBasis[tuples[j][k]];\n                ret.push_back(MultiDimFct(term));\n            }\n        }\n        return ret;\n    }\n}\n", "meta": {"hexsha": "3b7c6bb28dd946c007d28988fa6e8808b4ce5cae", "size": 6358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/methods/montecarlo/lsmbasissystem.cpp", "max_stars_repo_name": "grandtiger/quantlib", "max_stars_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-07-19T11:17:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-07-19T11:17:48.000Z", "max_issues_repo_path": "ql/methods/montecarlo/lsmbasissystem.cpp", "max_issues_repo_name": "grandtiger/quantlib", "max_issues_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T18:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-17T18:49:22.000Z", "max_forks_repo_path": "ql/methods/montecarlo/lsmbasissystem.cpp", "max_forks_repo_name": "grandtiger/quantlib", "max_forks_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5195530726, "max_line_length": 87, "alphanum_fraction": 0.5401069519, "num_tokens": 1556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.41017762937700897}}
{"text": "#include <iostream>\n#include <chrono>\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n#include \"source/setup.h\"\n#include \"server/query.h\"\n#include \"client/verify_intersection.h\"\n#include \"client/verify_tree.h\"\n#include \"client/verify_union.h\"\n#include \"client/verify_subset.h\"\n#include \"client/verify_difference.h\"\n\n#define NODEBUG\n#define SET_SIZE 10000\n#define SETS_NO 32\n\n\nvoid test_intersection(int round, int size, int intersection_size, Key *k) {\n    using namespace std::chrono;\n    high_resolution_clock::time_point t1, t3;\n    high_resolution_clock::time_point t2, t4;\n    t3 = high_resolution_clock::now();\n    //generate sets\n    DataStructure *dataStructure = new DataStructure(SETS_NO, k); //TODO memleak\n    for (int i = 1; i <= intersection_size; i++) {\n        NTL::ZZ_p j = NTL::random_ZZ_p();\n        for (int set_index = 0; set_index < dataStructure->m; set_index++) {\n            dataStructure->insert(set_index, j, k->get_public_key(), k->get_secret_key());\n        }\n    }\n    std::cout << size << \"\\t\";\n    for (int set_index = 0; set_index < dataStructure->m; set_index++)\n        for (int i = 1; i <= size - intersection_size; i++) {\n            NTL::ZZ_p j = NTL::random_ZZ_p();\n            dataStructure->insert(set_index, j, k->get_public_key(), k->get_secret_key());\n        }\n    t4 = high_resolution_clock::now();\n    auto duration = duration_cast<milliseconds>(t4 - t3).count();\n    std::cout << duration << \"\\t\";\n\n    //query intersection\n    std::vector<int> v;\n    for (int set_index = 0; set_index < dataStructure->m; set_index++)\n        v.push_back(set_index);\n\n    t3 = high_resolution_clock::now();\n    Intersection *intersection = new Intersection(v, k->get_public_key(), dataStructure);\n    intersection->intersect();\n    t1 = high_resolution_clock::now();\n    intersection->subset_witness();\n    t2 = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(t2 - t1).count();\n    std::cout << duration << \"\\t\";\n\n    t1 = high_resolution_clock::now();\n    intersection->completeness_witness();\n    t2 = high_resolution_clock::now();\n    t4 = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(t2 - t1).count();\n    std::cout << duration << \"\\t\";\n    duration = duration_cast<milliseconds>(t4 - t3).count();\n    std::cout << duration << \"\\n\";\n//    log_info(\"Intersection query time:\\t%d\", duration);\n    //verify tree\n    //verify intersection\n    t1 = high_resolution_clock::now();\n    VerifyTree *verifyTree = new VerifyTree;\n    verifyTree->verifyTree(dataStructure, v);\n//    log_info(\"Tree verification result:\\t%x\", verifyTree->verifiedtree);\n    VerifyIntersection *verifyIntersection = new VerifyIntersection(k->get_public_key(),\n                                                                    intersection->I, intersection->W, intersection->Q,\n                                                                    dataStructure->AuthD, dataStructure->m, v);\n    bool b = verifyIntersection->verify_intersection();\n    t2 = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(t2 - t1).count();\n    delete verifyIntersection;\n    delete verifyTree;\n    delete intersection;\n    delete dataStructure;\n//    log_info(\"Intersection verification time:\\t%d\", duration);\n//    log_info(\"Intersection verification result:\\t%x\", b);\n}\n\nvoid test_union(int round, int size, int intersection_size, Key *k) {\n    using namespace std::chrono;\n    high_resolution_clock::time_point t1, t3;\n    high_resolution_clock::time_point t2, t4;\n    t3 = high_resolution_clock::now();\n    //generate sets\n    DataStructure *dataStructure = new DataStructure(SETS_NO, k);\n\n    for (int i = 1; i <= intersection_size; i++) {\n        NTL::ZZ_p j = NTL::random_ZZ_p();\n        for (int set_index = 0; set_index < dataStructure->m; set_index++) {\n            dataStructure->insert(set_index, j, k->get_public_key(), k->get_secret_key());\n        }\n    }\n\n    std::cout << size << \"\\t\";\n    for (int set_index = 0; set_index < dataStructure->m; set_index++)\n        for (int i = 1; i <= size - intersection_size; i++) {\n            NTL::ZZ_p j = NTL::random_ZZ_p();\n            dataStructure->insert(set_index, j, k->get_public_key(), k->get_secret_key());\n        }\n\n    t4 = high_resolution_clock::now();\n    auto duration = duration_cast<milliseconds>(t4 - t3).count();\n    std::cout << duration << \"\\t\";\n\n    //query intersection\n    std::vector<int> v;\n    for (int set_index = 0; set_index < dataStructure->m; set_index++)\n        v.push_back(set_index);\n    t3 = high_resolution_clock::now();\n    Union *un = new Union(v, k->get_public_key(), dataStructure);\n    t1 = high_resolution_clock::now();\n    un->unionSets();\n    t2 = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(t2 - t1).count();\n    std::cout << duration << \"\\t\";\n    t4 = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(t4 - t3).count();\n    std::cout << duration << \"\\t\";\n    t1 = high_resolution_clock::now();\n    VerifyTree *verifyTree = new VerifyTree;\n    verifyTree->verifyTree(dataStructure, v);\n    VerifyUnion *verifyUnion = new VerifyUnion(k->get_public_key(), un->U, un->tree, dataStructure->m, un->set_indices);\n    bool b = verifyUnion->verify_union();\n    t2 = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(t2 - t1).count();\n    std::cout << duration << \"\\n\";\n    delete verifyTree;\n    delete verifyUnion;\n    delete un;\n    delete dataStructure;\n//    log_info(\"Union verification time:\\t%d\", duration);\n    log_info(\"Union verification result:\\t%x\", b);\n}\n\nvoid test_union2(int round, int size, int intersection_size, Key *k) {\n    using namespace std::chrono;\n    high_resolution_clock::time_point t1, t3;\n    high_resolution_clock::time_point t2, t4;\n    t3 = high_resolution_clock::now();\n    //generate sets\n    DataStructure *dataStructure = new DataStructure(SETS_NO, k);\n\n    for (int i = 1; i <= intersection_size; i++) {\n        NTL::ZZ_p j = NTL::random_ZZ_p();\n        for (int set_index = 0; set_index < dataStructure->m; set_index++) {\n            dataStructure->insert(set_index, j, k->get_public_key(), k->get_secret_key());\n        }\n    }\n\n    std::cout << size << \"\\t\";\n    for (int set_index = 0; set_index < dataStructure->m; set_index++) {\n        for (int i = 1; i <= size - intersection_size; i++) {\n            NTL::ZZ_p j = NTL::random_ZZ_p();\n            dataStructure->insert(set_index, j, k->get_public_key(), k->get_secret_key());\n        }\n    }\n\n\n    t4 = high_resolution_clock::now();\n    auto duration = duration_cast<milliseconds>(t4 - t3).count();\n    std::cout << duration << \"\\t\";\n\n    //query intersection\n    std::vector<int> v;\n    for (int set_index = 0; set_index < dataStructure->m; set_index++)\n        v.push_back(set_index);\n    t3 = high_resolution_clock::now();\n    Union2 *un = new Union2(v, k->get_public_key(), dataStructure);\n    un->unionSets();\n    t1 = high_resolution_clock::now();\n    un->membership_witness();\n    t2 = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(t2 - t1).count();\n    std::cout << duration << \"\\t\";\n\n    t1 = high_resolution_clock::now();\n    un->superset_witness();\n    t2 = high_resolution_clock::now();\n    t4 = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(t2 - t1).count();\n    std::cout << duration << \"\\t\";\n    duration = duration_cast<milliseconds>(t4 - t3).count();\n    std::cout << duration << \"\\t\";\n    t1 = high_resolution_clock::now();\n    VerifyTree *verifyTree = new VerifyTree;\n    verifyTree->verifyTree(dataStructure, v);\n    VerifyUnion2 *verifyUnion = new VerifyUnion2(k->get_public_key(), un->U, un->W1, un->W2, dataStructure->AuthD,\n                                               dataStructure->m, v, un->set_indices);\n    verifyUnion->verify_union();\n    t2 = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(t2 - t1).count();\n    std::cout << duration << \"\\n\";\n    bool b = verifyUnion->membershipwitness and verifyUnion->membershipwitness;\n    delete verifyTree;\n    delete verifyUnion;\n    delete un;\n    delete dataStructure;\n    log_info(\"Union verification time:\\t%d\", duration);\n    log_info(\"Union verification result:\\t%x\", b);\n}\n\nvoid test_difference(int round, int size, int intersection_size, Key *k) {\n    using namespace std::chrono;\n    high_resolution_clock::time_point t1, t3;\n    high_resolution_clock::time_point t2, t4;\n    t3 = high_resolution_clock::now();\n    //generate sets\n    DataStructure *dataStructure = new DataStructure(SETS_NO, k);\n\n    for (int i = 1; i <= intersection_size; i++) {\n        NTL::ZZ_p j = NTL::random_ZZ_p();\n        for (int set_index = 0; set_index < dataStructure->m; set_index++) {\n            dataStructure->insert(set_index, j, k->get_public_key(), k->get_secret_key());\n        }\n    }\n\n    std::cout << size << \"\\t\";\n    for (int set_index = 0; set_index < dataStructure->m; set_index++)\n        for (int i = 1; i <= size - intersection_size; i++) {\n            NTL::ZZ_p j = NTL::random_ZZ_p();\n            dataStructure->insert(set_index, j, k->get_public_key(), k->get_secret_key());\n        }\n\n    t4 = high_resolution_clock::now();\n    auto duration = duration_cast<milliseconds>(t4 - t3).count();\n    std::cout << duration << \"\\t\";\n\n    //query intersection\n    int index[2];\n    index[0] = 0;\n    index[1] = 1;\n    t1 = high_resolution_clock::now();\n    Difference *difference = new Difference(index, k->get_public_key(), dataStructure);\n    difference->difference();\n    difference->witness();\n    t2 = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(t2 - t1).count();\n\n    std::cout << duration << \"\\t\";\n    t1 = high_resolution_clock::now();\n    VerifyDifference *verifyDifference = new VerifyDifference(k->get_public_key(), dataStructure, difference->D,\n                                                              difference->I, difference->W, difference->Wd,\n                                                              difference->Q, difference->index);\n    verifyDifference->verify_difference();\n    duration = duration_cast<milliseconds>(t2 - t1).count();\n    std::cout << duration << \"\\n\";\n    bool b = verifyDifference->verified_witness;\n//    log_info(\"Difference verification result:\\t%x\", b);\n    delete verifyDifference;\n    delete difference;\n    delete dataStructure;\n}\n\nvoid test_subset(int round, int size, int intersection_size, Key *k) {\n    using namespace std::chrono;\n    high_resolution_clock::time_point t1, t2;\n    DataStructure *dataStructure = new DataStructure(SETS_NO, k);\n\n    for (int i = 1; i <= intersection_size; i++) {\n        NTL::ZZ_p j = NTL::random_ZZ_p();\n        for (int set_index = 0; set_index < dataStructure->m; set_index++) {\n            dataStructure->insert(set_index, j, k->get_public_key(), k->get_secret_key());\n        }\n    }\n\n    std::cout << size << \"\\t\";\n    for (int set_index = 0; set_index < dataStructure->m; set_index++)\n        for (int i = 1; i <= size - intersection_size; i++) {\n            NTL::ZZ_p j = NTL::random_ZZ_p();\n            dataStructure->insert(set_index, j, k->get_public_key(), k->get_secret_key());\n            dataStructure->insert(0, j, k->get_public_key(), k->get_secret_key());\n        }\n    t1 = high_resolution_clock::now();\n    Subset *subset = new Subset(0, 1, k->get_public_key(), dataStructure);\n    subset->subset();\n    t2 = high_resolution_clock::now();\n    auto duration = duration_cast<milliseconds>(t2 - t1).count();\n    std::cout << duration << \"\\t\";\n    t1 = high_resolution_clock::now();\n    if (subset->answer)\n        subset->positiveWitness();\n    else\n        subset->negativeWitness();\n    t2 = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(t2 - t1).count();\n    std::cout << duration << \"\\t\";\n    t1 = high_resolution_clock::now();\n    VerifySubset *verifySubset = new VerifySubset(k->get_public_key(), dataStructure, subset->Q, subset->W,\n                                                  subset->answer,\n                                                  subset->index[0], subset->index[1], subset->y);\n    verifySubset->verify_subset();\n    t2 = high_resolution_clock::now();\n    duration = duration_cast<milliseconds>(t2 - t1).count();\n    std::cout << duration << \"\\n\";\n    bool b = verifySubset->verified_subset;\n//    log_info(\"Subset verification result:\\t%x\", b);\n    delete verifySubset;\n    delete subset;\n    delete dataStructure;\n}\n\nint main() {\n    using namespace std::chrono;\n    high_resolution_clock::time_point t1 = high_resolution_clock::now();\n    NTL::ZZ p = NTL::conv<NTL::ZZ>(\"16798108731015832284940804142231733909759579603404752749028378864165570215949\");\n    NTL::ZZ_p::init(p);\n    Key *k = new Key(p);\n    high_resolution_clock::time_point t2 = high_resolution_clock::now();\n    auto duration = duration_cast<milliseconds>(t2 - t1).count();\n    log_info(\"Key generation time:\\t%d\", duration);\n//    std::cerr<<\"size\\tsetup\\tsubet\\tcompleteness\\ttotal\\n\";\n    for (int test_size = 10; test_size <= 10; test_size +=500)\n//        for(int i = 0; i < 10; i++)\n            test_intersection(0, test_size, test_size / 10, k);\n\n//   std::cerr<<\"size\\tsetup\\tmembership\\tsuperset_witness\\ttotal\\n\";\n//   for (int test_size = 10; test_size <= 10; test_size +=100)\n//       for(int i = 0; i < 10; i++)\n//           test_union2(0, test_size, test_size/10, k);\n//    for (int test_size = 0; test_size <= 400; test_size +=200)\n//        for(int i = 0; i < 10; i++)\n//            test_subset(i, test_size, test_size / 10, k);\n//    for (int test_size = 0; test_size <= 400; test_size +=200)\n//        for(int i = 0; i < 10; i++)\n//            test_difference(i, test_size, test_size / 10, k);\n    delete k;\n    return 0;\n}\n", "meta": {"hexsha": "0071d60ec4cab21a338475e2cb31e5d75cf120aa", "size": 13786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "mahzoun/setops", "max_stars_repo_head_hexsha": "9966c208c7ca6789a08341b03ea19051ab60861d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-11-08T14:45:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T22:06:51.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "mahzoun/SetOps", "max_issues_repo_head_hexsha": "9966c208c7ca6789a08341b03ea19051ab60861d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "mahzoun/SetOps", "max_forks_repo_head_hexsha": "9966c208c7ca6789a08341b03ea19051ab60861d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2754491018, "max_line_length": 120, "alphanum_fraction": 0.6279558973, "num_tokens": 3580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8267117940706734, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.4101266197892946}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file mcfxtarfengine.hpp\n    \\brief Monte Carlo engine for FX Tarf\n*/\n\n#ifndef quantlib_pricingengines_mc_fxtarf_hpp\n#define quantlib_pricingengines_mc_fxtarf_hpp\n\n#include <ql/experimental/fx/fxtarfengine.hpp>\n#include <ql/event.hpp>\n#include <ql/pricingengines/mcsimulation.hpp>\n#include <ql/processes/blackscholesprocess.hpp>\n#include <ql/math/generallinearleastsquares.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\nnamespace {\n\n// raw data for proxy estimation\n// the data vector is organized as follows\n// level 0 = openFixings (e.g. 6 5 4 3 2 1 = Indices 5 ... 0)\n// level 1 = accumulated amount buckets\n//    [ previously accumuated amount = a(0), a(1) ]\n//    [ a(1), a(2) ]\n//    ...\n//    [ a(n-1), a(n) = target ]\n// level 2 = vector of pairs (spot, npv), sorted asc by spot values\n\ntypedef std::vector<std::vector<std::vector<std::pair<Real, Real> > > >\n    ProxyData;\n\n// regression function basis\nReal basis0(const double) { return 1; }\nReal basis1(const double x) { return x; }\nReal basis2(const double x) { return x * x; }\n\n} // empty namespace\n\ntemplate <class RNG = PseudoRandom, class S = Statistics>\nclass McFxTarfEngine : public FxTarfEngine,\n                       public McSimulation<SingleVariate, RNG, S> {\n  public:\n    /*! proxy function giving a function spot => npv for one segment\n        (bucket accumulated amount, number of open fixings)\n        the function is given by two quadratic polynomials on intervals\n        (-\\infty,cutoff] and (cutoff,\\infty).\n        Only the ascending (long calls) or descending (long puts) branch\n        is used and then extrapolated flat.\n        For calls the extrapolation below the given lowerCutoff is done\n        linear (for puts above this value).\n    */\n    class QuadraticProxyFunction : public FxTarf::Proxy::ProxyFunction {\n      public:\n        QuadraticProxyFunction(Option::Type type, const Real cutoff,\n                               const Real a1, const Real b1, const Real c1,\n                               const Real a2, const Real b2, const Real c2,\n                               const Real lowerCutoff, const Real coreRegionMin,\n                               const Real coreRegionMax);\n        Real operator()(const Real spot) const;\n        std::pair<Real, Real> coreRegion() const {\n            return std::make_pair(coreRegionMin_, coreRegionMax_);\n        }\n\n      private:\n        Option::Type type_;\n        const Real a1_, b1_, c1_, a2_, b2_, c2_;\n        const Real cutoff_, lowerCutoff_;\n        const Real coreRegionMin_, coreRegionMax_;\n        int flatExtrapolationType1_,\n            flatExtrapolationType2_; // +1 = right, -1 = left\n        Real extrapolationPoint1_, extrapolationPoint2_;\n    };\n\n    /*! typedefs */\n    typedef typename McSimulation<SingleVariate, RNG, S>::path_generator_type\n        path_generator_type;\n    typedef typename McSimulation<SingleVariate, RNG, S>::path_pricer_type\n        path_pricer_type;\n    typedef typename McSimulation<SingleVariate, RNG, S>::stats_type stats_type;\n\n    //! constructor\n    McFxTarfEngine(\n        const boost::shared_ptr<GeneralizedBlackScholesProcess> &process,\n        Size timeSteps, Size timeStepsPerYears, bool brownianBridge,\n        bool antitheticVariate, Size requiredSamples, Real requiredTolerance,\n        Size maxSamples, BigNatural seed,\n        const Handle<YieldTermStructure> discount, const bool generateProxy);\n\n    void calculate() const;\n    void reset();\n\n  protected:\n    // McSimulation Interface\n    TimeGrid timeGrid() const;\n    boost::shared_ptr<path_generator_type> pathGenerator() const;\n    boost::shared_ptr<path_pricer_type> pathPricer() const;\n    // data members\n    boost::shared_ptr<GeneralizedBlackScholesProcess> process_;\n    Size timeSteps_, timeStepsPerYear_;\n    Size requiredSamples_, maxSamples_;\n    Real requiredTolerance_;\n    bool brownianBridge_;\n    BigNatural seed_;\n    bool generateProxy_;\n    mutable std::vector<Real> fixingTimes_, discounts_;\n    // proxy information generated by the engine\n    mutable boost::shared_ptr<FxTarf::Proxy> proxy_;\n    // simulation data on which the proxy is estimated\n    mutable ProxyData data_;\n    // bucket limits for collected data\n    mutable std::vector<Real> accBucketLimits_;\n};\n\n//! Proxy function\ntemplate <class RNG, class S>\nMcFxTarfEngine<RNG, S>::QuadraticProxyFunction::QuadraticProxyFunction(\n    Option::Type type, const Real cutoff, const Real a1, const Real b1,\n    const Real c1, const Real a2, const Real b2, const Real c2,\n    const Real lowerCutoff, const Real coreRegionMin, const Real coreRegionMax)\n    : type_(type), cutoff_(cutoff), a1_(a1), b1_(b1), c1_(c1), a2_(a2), b2_(b2),\n      c2_(c2), lowerCutoff_(lowerCutoff), coreRegionMin_(coreRegionMin),\n      coreRegionMax_(coreRegionMax) {\n    QL_REQUIRE((type == Option::Call && lowerCutoff_ <= cutoff) ||\n                   (type == Option::Put && lowerCutoff_ >= cutoff),\n               \"lowerCutoff (\" << lowerCutoff_\n                               << \") must be less or equal (call) or greater \"\n                                  \"equal (put) than cutoff (\"\n                               << cutoff\n                               << \") for type \"\n                               << type_);\n    // for calls we want ascending, for puts descending functions\n    if (close(a1_, 0.0)) {\n        // for minspot = maxspot a constant function with a=b=0\n        // is constructed, so this requirement must be dropped\n        // QL_REQUIRE(b1_ > 0.0, \"for a call and a1=0 b (\"\n        //                           << b1_ << \") must be positive\");\n    } else {\n        extrapolationPoint1_ = -b1_ / (2.0 * a1_);\n        flatExtrapolationType1_ =\n            (type_ == Option::Call ? 1 : -1) * (a1_ > 0.0 ? -1 : 1);\n    }\n    if (close(a2_, 0.0)) {\n        // for minspot = maxspot a constant function with a=b=0\n        // is constructed, so this requirement must be dropped\n        // QL_REQUIRE(b2_ > 0.0, \"for a call and a2=0 b (\"\n        //                           << b2_ << \") must be positive\");\n    } else {\n        extrapolationPoint2_ = -b2_ / (2.0 * a2_);\n        flatExtrapolationType2_ =\n            (type_ == Option::Call ? 1 : -1) * (a2_ > 0.0 ? -1 : 1);\n    }\n}\n\ntemplate <class RNG, class S>\nReal McFxTarfEngine<RNG, S>::QuadraticProxyFunction::\noperator()(const Real spot) const {\n    Real x = spot;\n    if (spot <= cutoff_) {\n        if (spot <= lowerCutoff_ && type_ == Option::Call &&\n            flatExtrapolationType1_ == 1) {\n            // linear extrapolation instead of quadratic outside lowerCutoff\n            // if flat extrapolation is to the right)\n            return (2.0 * a1_ * lowerCutoff_ + b1_) * spot + c1_ -\n                   a1_ * lowerCutoff_ * lowerCutoff_;\n        }\n        x = flatExtrapolationType1_ *\n            std::min(flatExtrapolationType1_ * extrapolationPoint1_,\n                     flatExtrapolationType1_ * x);\n        Real tmp = a1_ * x * x + b1_ * x + c1_;\n        // ensure global monotonicity\n        // if (type_ == Option::Put) {\n        //     Real ct = flatExtrapolationType2_ *\n        //               std::min(flatExtrapolationType2_ *\n        //               extrapolationPoint2_,\n        //                        flatExtrapolationType2_ * cutoff_);\n        //     tmp = std::max(a2_ * ct * ct + b2_ * ct + c2_, tmp);\n        // }\n        return tmp;\n    } else {\n        if (spot >= lowerCutoff_ && type_ == Option::Put &&\n            flatExtrapolationType2_ == -1) {\n            // linear extrapolation instead of quadratic outside lowerCutoff if\n            // flat extrapolation is to the left\n            return (2.0 * a2_ * lowerCutoff_ + b2_) * spot + c2_ -\n                   a2_ * lowerCutoff_ * lowerCutoff_;\n        }\n        x = flatExtrapolationType2_ *\n            std::min(flatExtrapolationType2_ * extrapolationPoint2_,\n                     flatExtrapolationType2_ * x);\n        Real tmp = a2_ * x * x + b2_ * x + c2_;\n        // ensure global monotonicity\n        // if (type_ == Option::Call) {\n        //     Real ct = flatExtrapolationType1_ *\n        //               std::min(flatExtrapolationType1_ *\n        //               extrapolationPoint1_,\n        //                        flatExtrapolationType1_ * cutoff_);\n        //     tmp = std::max(a1_ * ct * ct + b1_ * ct + c1_, tmp);\n        // }\n        return tmp;\n    }\n}\n\n//! Monte Carlo fx-tarf engine factory\ntemplate <class RNG = PseudoRandom, class S = Statistics>\nclass MakeMcFxTarfEngine {\n  public:\n    MakeMcFxTarfEngine(\n        const boost::shared_ptr<GeneralizedBlackScholesProcess> &);\n    // named parameters\n    MakeMcFxTarfEngine &withSteps(Size steps);\n    MakeMcFxTarfEngine &withStepsPerYear(Size steps);\n    MakeMcFxTarfEngine &withBrownianBridge(bool b = true);\n    MakeMcFxTarfEngine &withAntitheticVariate(bool b = true);\n    MakeMcFxTarfEngine &withSamples(Size samples);\n    MakeMcFxTarfEngine &withAbsoluteTolerance(Real tolerance);\n    MakeMcFxTarfEngine &withMaxSamples(Size samples);\n    MakeMcFxTarfEngine &withSeed(BigNatural seed);\n    MakeMcFxTarfEngine &\n    withDiscount(const Handle<YieldTermStructure> &discount);\n    MakeMcFxTarfEngine &withProxy(bool b = true);\n    // conversion to pricing engine\n    operator boost::shared_ptr<PricingEngine>() const;\n\n  private:\n    boost::shared_ptr<GeneralizedBlackScholesProcess> process_;\n    bool brownianBridge_, antithetic_;\n    Size steps_, stepsPerYear_, samples_, maxSamples_;\n    Real tolerance_;\n    BigNatural seed_;\n    Handle<YieldTermStructure> discount_;\n    bool generateProxy_;\n};\n\n//! Path Pricer\nclass FxTarfPathPricer : public PathPricer<Path> {\n  public:\n    FxTarfPathPricer(const std::vector<Real> &fixingTimes,\n                     const std::vector<Real> &discounts,\n                     const Real accumulatedAmount, const Real sourceNominal,\n                     const Real target, const FxTarf *instrument,\n                     ProxyData &data, const std::vector<Real> &accBucketLimits,\n                     const Date lastPaymentDate,\n                     const Handle<YieldTermStructure> &discount,\n                     const bool generateProxy);\n    Real operator()(const Path &path) const;\n\n  private:\n    const std::vector<Real> &fixingTimes_, &discounts_;\n    const Real accumulatedAmount_, sourceNominal_, target_;\n    const FxTarf *instrument_;\n    mutable std::vector<Size> fixingIndices_;\n    ProxyData &data_;\n    const std::vector<Real> &accBucketLimits_;\n    const Date lastPaymentDate_;\n    const Handle<YieldTermStructure> discount_;\n    const bool generateProxy_;\n};\n\n// Implementation\n\ntemplate <class RNG, class S>\nMcFxTarfEngine<RNG, S>::McFxTarfEngine(\n    const boost::shared_ptr<GeneralizedBlackScholesProcess> &process,\n    Size timeSteps, Size timeStepsPerYear, bool brownianBridge,\n    bool antitheticVariate, Size requiredSamples, Real requiredTolerance,\n    Size maxSamples, BigNatural seed, const Handle<YieldTermStructure> discount,\n    const bool generateProxy)\n    : FxTarfEngine(discount),\n      McSimulation<SingleVariate, RNG, S>(antitheticVariate, false),\n      process_(process), timeSteps_(timeSteps),\n      timeStepsPerYear_(timeStepsPerYear), requiredSamples_(requiredSamples),\n      maxSamples_(maxSamples), requiredTolerance_(requiredTolerance),\n      brownianBridge_(brownianBridge), seed_(seed),\n      generateProxy_(generateProxy) {\n    QL_REQUIRE(timeSteps != Null<Size>() || timeStepsPerYear != Null<Size>(),\n               \"no time steps provided\");\n    QL_REQUIRE(timeSteps == Null<Size>() || timeStepsPerYear == Null<Size>(),\n               \"both time steps and time steps per year were provided\");\n    QL_REQUIRE(timeSteps != 0, \"timeSteps must be positive, \"\n                                   << timeSteps << \" not allowed\");\n    QL_REQUIRE(timeStepsPerYear != 0, \"timeStepsPerYear must be positive, \"\n                                          << timeStepsPerYear\n                                          << \" not allowed\");\n    QL_REQUIRE(!discount_.empty(), \"no discount curve given\");\n    registerWith(process_);\n}\n\ntemplate <class RNG, class S> void McFxTarfEngine<RNG, S>::reset() {\n    FxTarfEngine::reset();\n    fixingTimes_.clear();\n    discounts_.clear();\n    proxy_ = boost::shared_ptr<FxTarf::Proxy>();\n    data_.clear();\n    accBucketLimits_.clear();\n}\n\ntemplate <class RNG, class S> void McFxTarfEngine<RNG, S>::calculate() const {\n\n    Date today = Settings::instance().evaluationDate();\n\n    // handle the trivial cases\n    FxTarfEngine::calculate();\n\n    // are we already done, i.e. has the base engine set the npv ?\n    if (results_.value != Null<Real>())\n        return;\n\n    // we have at least one fixing left which is tommorow or later\n    for (Size i = 0; i < arguments_.openFixingDates.size(); ++i) {\n        fixingTimes_.push_back(process_->time(arguments_.openFixingDates[i]));\n        discounts_.push_back(\n            discount_->discount(arguments_.openPaymentDates[i]));\n    }\n\n    // prepare the data container on which the proxy pricing is estimated\n    // later\n\n    // we use a number of heuristics in the following\n    // number of buckets for accumulated amounts\n    // which are merged though if the data in the buckets\n    // does not meet the requirement below\n    Size nAccBuckets = 5;\n    // first the data points per accumulated amount bucket should\n    // be more than the total number of data points divided by dFactor\n    Size dFactor = 10;\n    // then (spot,npv) pairs are divided into two segments (for calls)\n    // [spotMin,spotMin+relCutoff*(spotMax-spotMin)) and\n    // [spotMin+relCutoff*(spotMax-spotMin,spotMax]\n    // for puts we use 1.0-relCutoff to divide the intervall instead\n    Real relCutoff = 0.80;\n    // we require minCutoffRatio*(1.0-relCutoff)*totalNoDataPoints\n    // to be still in the smaller (spot,npv) segment, otherwise\n    // the cutoff will be lowered (calls) by a factor of\n    // cutoffShrinkFactor until we reach this critical size\n    Real minCutoffRatio = 0.25;\n    Real cutoffShrinkFactor = 0.99;\n    // on the lower bound (for calls) a lowerCutoff is determined\n    // such that more than 1-minLowerExtr points are above this\n    // cutoff. Below this threshhold, a linear extrapolation is\n    // used.\n    Real minLowerExtr = 0.05;\n    // if the intersection of the two quadratic functions lies\n    // within (1-smoothInt)*cutoff, (1+smoothInt)*cutoff\n    // the cutoff is moved to the intersection points\n    Real smoothInt = 0.05;\n    // the \"trusted\" region (aka core region) is defined by chopping\n    // off the lower and upper coreCutoff part of the data\n    Real coreCutoff = 0.001;\n\n    // this is the minimum number of points required for regression\n    Size minRegPoints = 3;\n\n    if (generateProxy_) {\n        // create the buckets\n        for (Size i = 0; i < nAccBuckets; ++i) {\n            accBucketLimits_.push_back(\n                static_cast<Real>(i) / static_cast<Real>(nAccBuckets) *\n                    (arguments_.target - arguments_.accumulatedAmount) +\n                arguments_.accumulatedAmount);\n        }\n\n        // we set the first bucket limit to zero, which does not change\n        // anything, but leaves no room that the given accumulated amount\n        // is below the first limit\n        accBucketLimits_[0] = 0.0;\n\n        // initialize the data container\n        for (Size i1 = 0; i1 < fixingTimes_.size(); ++i1) {\n            std::vector<std::vector<std::pair<Real, Real> > > level1Tmp;\n            for (Size i2 = 0; i2 < nAccBuckets; ++i2) {\n                level1Tmp.push_back(std::vector<std::pair<Real, Real> >(0));\n            }\n            data_.push_back(level1Tmp);\n        }\n    }\n\n    // do the main calculation using the mc machinery\n    McSimulation<SingleVariate, RNG, S>::calculate(\n        requiredTolerance_, requiredSamples_, maxSamples_);\n    results_.value =\n        this->mcModel_->sampleAccumulator().mean() + unsettledAmountNpv_;\n    if (RNG::allowsErrorEstimate)\n        results_.errorEstimate =\n            this->mcModel_->sampleAccumulator().errorEstimate();\n\n    if (!generateProxy_)\n        return;\n\n    // create the proxy object and initialize the members\n    proxy_ = boost::make_shared<FxTarf::Proxy>();\n    proxy_->origEvalDate = today;\n    proxy_->openFixingDates = arguments_.openFixingDates;\n    proxy_->accBucketLimits = accBucketLimits_;\n    proxy_->lastPaymentDate = arguments_.schedule.dates().back();\n    for (Size i = 0; i < proxy_->openFixingDates.size(); ++i) {\n        std::vector<boost::shared_ptr<FxTarf::Proxy::ProxyFunction> > fctVecTmp(\n            accBucketLimits_.size());\n        proxy_->functions.push_back(fctVecTmp);\n    }\n\n    // do the regression on appropriately merged data sets\n    for (Size i = 0; i < arguments_.openFixingDates.size(); ++i) {\n        // get the data for the specific number of open fixing times\n        std::vector<std::vector<std::pair<Real, Real> > > &tmp = data_[i];\n\n        // how many data points do we have over all\n        // accumulated amount buckets ?\n        Size numberOfDataPoints = 0;\n        for (Size j = 0; j < tmp.size(); ++j)\n            numberOfDataPoints += tmp[j].size();\n\n        // merge data if pieces are too small\n        Size k0 = 0, k0Before = 0;\n        do {\n            std::vector<std::pair<Real, Real> > xTmp;\n            Real spotMin = QL_MAX_REAL, spotMax = QL_MIN_REAL;\n            do {\n                std::vector<std::pair<Real, Real> > xTmp2(xTmp.size() +\n                                                          tmp[k0].size());\n                std::merge(xTmp.begin(), xTmp.end(), tmp[k0].begin(),\n                           tmp[k0].end(), xTmp2.begin());\n                xTmp.swap(xTmp2);\n                if (tmp[k0].size() > 0) {\n                    if (tmp[k0].front().first < spotMin)\n                        spotMin = tmp[k0].front().first;\n                    if (tmp[k0].back().first > spotMax)\n                        spotMax = tmp[k0].back().first;\n                }\n                k0++;\n            } while (dFactor * xTmp.size() < numberOfDataPoints);\n\n            // count the number of remaining data points ...\n            Size remainingDataPoints = 0;\n            for (Size j = k0; j < tmp.size(); ++j)\n                remainingDataPoints += tmp[j].size();\n\n            // ... and join the rest of data if they are to few\n            if (dFactor * remainingDataPoints < numberOfDataPoints) {\n                for (Size j = k0; j < tmp.size(); ++j) {\n                    std::vector<std::pair<Real, Real> > xTmp2(xTmp.size() +\n                                                              tmp[j].size());\n                    std::merge(xTmp.begin(), xTmp.end(), tmp[j].begin(),\n                               tmp[j].end(), xTmp2.begin());\n                    xTmp.swap(xTmp2);\n                    if (tmp[j].size() > 0) {\n                        if (tmp[j].front().first < spotMin)\n                            spotMin = tmp[j].front().first;\n                        if (tmp[j].back().first > spotMax)\n                            spotMax = tmp[j].back().first;\n                    }\n                }\n                k0 = tmp.size();\n            }\n\n            // we rearrange the data to get two segments for the spot\n            bool isCall = arguments_.longPositionType == Option::Call;\n            Real relCutoffTmp = isCall ? relCutoff : 1.0 - relCutoff;\n            std::vector<Real> xTmp1, xTmp2, yTmp1, yTmp2;\n            Real cutoff = spotMin + relCutoffTmp * (spotMax - spotMin);\n\n            // we want a certain percentage of data still in the smaller\n            // data set, otherwise we lower the cutoff\n            Size minDataSegment =\n                static_cast<Size>((1.0 - relCutoffTmp) * minCutoffRatio *\n                                  xTmp.size()) +\n                1;\n            Size sizeA, sizeB, criticalSize;\n            do {\n                sizeA = std::upper_bound(xTmp.begin(), xTmp.end(),\n                                         std::make_pair(cutoff, 0.0)) -\n                        xTmp.begin();\n                sizeB = xTmp.size() - sizeA;\n                criticalSize = isCall ? sizeB : sizeA;\n                if (((isCall && relCutoffTmp > 0.5) ||\n                     (!isCall && relCutoffTmp < 0.5)) &&\n                    (criticalSize < minDataSegment ||\n                     criticalSize < minRegPoints)) {\n                    if (isCall)\n                        relCutoffTmp *= cutoffShrinkFactor;\n                    else\n                        relCutoffTmp /= std::min(cutoffShrinkFactor, 1.0);\n                    cutoff = spotMin + relCutoffTmp * (spotMax - spotMin);\n                }\n            } while (\n                ((isCall && relCutoffTmp > 0.5) ||\n                 (!isCall && relCutoffTmp < 0.5)) &&\n                (criticalSize < minDataSegment || criticalSize < minRegPoints));\n\n            // copy the data to the final vectors used for the regression\n            for (Size ii = 0; ii < xTmp.size(); ++ii) {\n                if (xTmp[ii].first <= cutoff) {\n                    xTmp1.push_back(xTmp[ii].first);\n                    yTmp1.push_back(xTmp[ii].second);\n                } else {\n                    xTmp2.push_back(xTmp[ii].first);\n                    yTmp2.push_back(xTmp[ii].second);\n                }\n            }\n\n            // determine lower cutoff (in terms of calls), below which we\n            // extrapolate linear\n            Real lowerCutoff =\n                xTmp[static_cast<int>(xTmp.size() * (isCall\n                                                         ? minLowerExtr\n                                                         : 1.0 - minLowerExtr))]\n                    .first;\n            // determine the core (trusted) region\n            Real coreRegionMin =\n                xTmp[static_cast<int>(xTmp.size() * coreCutoff)].first;\n            Real coreRegionMax =\n                xTmp[static_cast<int>(xTmp.size() * (1.0 - coreCutoff))].first;\n\n            // the function object\n            boost::shared_ptr<FxTarf::Proxy::ProxyFunction> fct;\n\n            // if minSpot = cutoff = maxSpot (this may happen at t = 0) we\n            // just return a constant function being the average over all\n            // data points\n            if (std::fabs(spotMax - spotMin) < QL_EPSILON) {\n                Real avg = 0.0;\n                for (Size i = 0; i < xTmp1.size(); ++i)\n                    avg += yTmp1[i];\n                for (Size i = 0; i < xTmp2.size(); ++i)\n                    avg += yTmp2[i];\n                avg /= static_cast<double>(xTmp1.size() + xTmp2.size());\n                fct = boost::shared_ptr<QuadraticProxyFunction>(\n                    new QuadraticProxyFunction(\n                        arguments_.longPositionType, cutoff, 0.0, 0.0, avg, 0.0,\n                        0.0, avg, -QL_MAX_REAL, spotMin, spotMax));\n            } else {\n\n                // final sanity check before regression\n                QL_REQUIRE(xTmp1.size() >= 3,\n                           \"too few points for regression in set 1 (\"\n                               << xTmp1.size() << \")\");\n                QL_REQUIRE(xTmp2.size() >= 3,\n                           \"too few points for regression in set 2 (\"\n                               << xTmp2.size() << \")\");\n\n                // regression\n                std::vector<boost::function<Real(Real)> > v;\n                v.push_back(&basis0);\n                v.push_back(&basis1);\n                v.push_back(&basis2);\n\n                GeneralLinearLeastSquares ls1(xTmp1, yTmp1, v);\n                Array result1 = ls1.coefficients();\n\n                GeneralLinearLeastSquares ls2(xTmp2, yTmp2, v);\n                Array result2 = ls2.coefficients();\n\n                // check if the cutoff should be moved to the intersection\n                // point of the two overlapping functions\n                Real a1 = result1[2];\n                Real b1 = result1[1];\n                Real c1 = result1[0];\n                Real a2 = result2[2];\n                Real b2 = result2[1];\n                Real c2 = result2[0];\n                if (close(a1, a2)) {\n                    if (!close(b1, b2)) {\n                        Real tmp = -(c1 - c2) / (b1 - b2);\n                        if (fabs((tmp - cutoff) / cutoff) < smoothInt) {\n                            cutoff = tmp;\n                        }\n                    }\n                } else {\n                    Real tmp1 =\n                        (-(b1 - b2) + std::sqrt((b1 - b2) * (b1 - b2) -\n                                                4.0 * (a1 - a2) * (c1 - c2))) /\n                        (2.0 * (a1 - a2));\n                    Real tmp2 =\n                        (-(b1 - b2) - std::sqrt((b1 - b2) * (b1 - b2) -\n                                                4.0 * (a1 - a2) * (c1 - c2))) /\n                        (2.0 * (a1 - a2));\n                    if (fabs((tmp1 - cutoff) / cutoff) < smoothInt)\n                        cutoff = tmp1;\n                    if (fabs((tmp2 - cutoff) / cutoff) < smoothInt)\n                        cutoff = tmp2;\n                }\n\n                // make sure that lower cutoff is still left from cutoff\n                lowerCutoff = std::min(lowerCutoff, cutoff);\n\n                fct = boost::shared_ptr<QuadraticProxyFunction>(\n                    new QuadraticProxyFunction(\n                        arguments_.longPositionType, cutoff, a1, b1, c1, a2, b2,\n                        c2, lowerCutoff, coreRegionMin, coreRegionMax));\n            }\n\n            // store the proxy function, please note that\n            // due to merging we may have the same function for several\n            // accumulated amount segments\n            for (Size kk = k0Before; kk < k0; ++kk) {\n                proxy_->functions[i][kk] = fct;\n            }\n            k0Before = k0;\n        } while (k0 < tmp.size()); // do-while over accumulated amount buckets\n    }                              // for openFixingTimes\n\n    // set proxy information generated during simulation as result\n\n    results_.proxy = this->proxy_;\n\n    // clear the collected data\n\n    data_.clear();\n}\n\ntemplate <class RNG, class S>\nTimeGrid McFxTarfEngine<RNG, S>::timeGrid() const {\n    if (timeSteps_ != Null<Size>()) {\n        return TimeGrid(fixingTimes_.begin(), fixingTimes_.end(), timeSteps_);\n    } else if (timeStepsPerYear_ != Null<Size>()) {\n        Size steps = static_cast<Size>(timeStepsPerYear_ * fixingTimes_.back());\n        return TimeGrid(fixingTimes_.begin(), fixingTimes_.end(),\n                        std::max<Size>(steps, 1));\n    } else {\n        QL_FAIL(\"time steps not specified\");\n    }\n}\n\ntemplate <class RNG, class S>\nboost::shared_ptr<typename McFxTarfEngine<RNG, S>::path_generator_type>\nMcFxTarfEngine<RNG, S>::pathGenerator() const {\n    TimeGrid grid = timeGrid();\n    typename RNG::rsg_type gen =\n        RNG::make_sequence_generator(grid.size() - 1, seed_);\n    return boost::make_shared<path_generator_type>(process_, grid, gen,\n                                                   brownianBridge_);\n}\n\ntemplate <class RNG, class S>\nboost::shared_ptr<typename McFxTarfEngine<RNG, S>::path_pricer_type>\nMcFxTarfEngine<RNG, S>::pathPricer() const {\n    return boost::shared_ptr<FxTarfPathPricer>(new FxTarfPathPricer(\n        fixingTimes_, discounts_, arguments_.accumulatedAmount,\n        arguments_.sourceNominal, arguments_.target, arguments_.instrument,\n        this->data_, this->accBucketLimits_, arguments_.schedule.dates().back(),\n        this->discount_, this->generateProxy_));\n}\n\ntemplate <class RNG, class S>\ninline MakeMcFxTarfEngine<RNG, S>::MakeMcFxTarfEngine(\n    const boost::shared_ptr<GeneralizedBlackScholesProcess> &process)\n    : process_(process), brownianBridge_(false), antithetic_(false),\n      steps_(Null<Size>()), stepsPerYear_(Null<Size>()), samples_(Null<Size>()),\n      maxSamples_(Null<Size>()), tolerance_(Null<Real>()), seed_(0),\n      discount_(process->riskFreeRate()), generateProxy_(false) {}\n\ntemplate <class RNG, class S>\ninline MakeMcFxTarfEngine<RNG, S> &\nMakeMcFxTarfEngine<RNG, S>::withSteps(Size steps) {\n    steps_ = steps;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcFxTarfEngine<RNG, S> &\nMakeMcFxTarfEngine<RNG, S>::withStepsPerYear(Size steps) {\n    stepsPerYear_ = steps;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcFxTarfEngine<RNG, S> &\nMakeMcFxTarfEngine<RNG, S>::withBrownianBridge(bool brownianBridge) {\n    brownianBridge_ = brownianBridge;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcFxTarfEngine<RNG, S> &\nMakeMcFxTarfEngine<RNG, S>::withAntitheticVariate(bool b) {\n    antithetic_ = b;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcFxTarfEngine<RNG, S> &\nMakeMcFxTarfEngine<RNG, S>::withSamples(Size samples) {\n    QL_REQUIRE(tolerance_ == Null<Real>(), \"tolerance already set\");\n    samples_ = samples;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcFxTarfEngine<RNG, S> &\nMakeMcFxTarfEngine<RNG, S>::withAbsoluteTolerance(Real tolerance) {\n    QL_REQUIRE(samples_ == Null<Size>(), \"number of samples already set\");\n    QL_REQUIRE(RNG::allowsErrorEstimate, \"chosen random generator policy \"\n                                         \"does not allow an error estimate\");\n    tolerance_ = tolerance;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcFxTarfEngine<RNG, S> &\nMakeMcFxTarfEngine<RNG, S>::withMaxSamples(Size samples) {\n    maxSamples_ = samples;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcFxTarfEngine<RNG, S> &\nMakeMcFxTarfEngine<RNG, S>::withSeed(BigNatural seed) {\n    seed_ = seed;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcFxTarfEngine<RNG, S> &MakeMcFxTarfEngine<RNG, S>::withDiscount(\n    const Handle<YieldTermStructure> &discount) {\n    discount_ = discount;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcFxTarfEngine<RNG, S> &\nMakeMcFxTarfEngine<RNG, S>::withProxy(bool b) {\n    generateProxy_ = b;\n    return *this;\n}\n\ntemplate <class RNG, class S>\ninline MakeMcFxTarfEngine<RNG, S>::\noperator boost::shared_ptr<PricingEngine>() const {\n    QL_REQUIRE(steps_ != Null<Size>() || stepsPerYear_ != Null<Size>(),\n               \"number of steps not given\");\n    QL_REQUIRE(steps_ == Null<Size>() || stepsPerYear_ == Null<Size>(),\n               \"number of steps overspecified\");\n    return boost::shared_ptr<PricingEngine>(new McFxTarfEngine<RNG, S>(\n        process_, steps_, stepsPerYear_, brownianBridge_, antithetic_, samples_,\n        tolerance_, maxSamples_, seed_, discount_, generateProxy_));\n}\n\n} // namespace QuantLib\n#endif\n", "meta": {"hexsha": "4311d4bf072e6df8f164c7ae151c3633ff655a98", "size": 31432, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/fx/mcfxtarfengine.hpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/experimental/fx/mcfxtarfengine.hpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/experimental/fx/mcfxtarfengine.hpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 41.4123847167, "max_line_length": 80, "alphanum_fraction": 0.5887948587, "num_tokens": 7843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8267117855317474, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.4101266155531861}}
{"text": "/*\n *            Copyright 2009-2020 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n// Third party includes\n#include <boost/math/constants/constants.hpp>\n\n// VOTCA includes\n#include <votca/tools/constants.h>\n\n// Local VOTCA includes\n#include <votca/xtp/orbitals.h>\n\n// Local private VOTCA includes\n#include \"spectrum.h\"\n\nnamespace votca {\nnamespace xtp {\n\nvoid Spectrum::ParseOptions(const tools::Property& options) {\n\n  // orbitals file or pure DFT output\n  orbfile_ = options.ifExistsReturnElseReturnDefault<std::string>(\n      \".input\", job_name_ + \".orb\");\n\n  output_file_ = options.ifExistsReturnElseReturnDefault<std::string>(\n      \".output\", job_name_ + \"_spectrum.dat\");\n\n  n_pt_ = options.get(\".points\").as<Index>();\n  lower_ = options.get(\".lower\").as<double>();\n  upper_ = options.get(\".upper\").as<double>();\n  fwhm_ = options.get(\".fwhm\").as<double>();\n\n  spectrum_type_ = options.get(\".type\").as<std::string>();\n  minexc_ = options.get(\".minexc\").as<Index>();\n  maxexc_ = options.get(\".maxexc\").as<Index>();\n  shiftby_ = options.get(\".shift\").as<double>();\n}\n\nbool Spectrum::Run() {\n  log_.setReportLevel(Log::current_level);\n  log_.setMultithreading(true);\n\n  log_.setCommonPreface(\"\\n... ...\");\n\n  XTP_LOG(Log::error, log_)\n      << \"Calculating absorption spectrum plot \" << orbfile_ << std::flush;\n\n  Orbitals orbitals;\n  // load the QM data from serialized orbitals object\n  XTP_LOG(Log::error, log_)\n      << \" Loading QM data from \" << orbfile_ << std::flush;\n  orbitals.ReadFromCpt(orbfile_);\n\n  // check if orbitals contains singlet energies and transition dipoles\n  if (!orbitals.hasBSESinglets()) {\n    throw std::runtime_error(\n        \"BSE singlet energies not stored in QM data file!\");\n  }\n\n  if (!orbitals.hasTransitionDipoles()) {\n    throw std::runtime_error(\n        \"BSE transition dipoles not stored in QM data file!\");\n  }\n\n  const Eigen::VectorXd BSESingletEnergies =\n      orbitals.BSESinglets().eigenvalues() * tools::conv::hrt2ev;\n  const std::vector<Eigen::Vector3d>& TransitionDipoles =\n      orbitals.TransitionDipoles();\n  Eigen::VectorXd osc = orbitals.Oscillatorstrengths();\n\n  if (maxexc_ > Index(TransitionDipoles.size())) {\n    maxexc_ = Index(TransitionDipoles.size()) - 1;\n  }\n\n  Index n_exc = maxexc_ - minexc_ + 1;\n  XTP_LOG(Log::error, log_)\n      << \" Considering \" << n_exc << \" excitation with max energy \"\n      << BSESingletEnergies(maxexc_) << \" eV / min wave length \"\n      << evtonm(BSESingletEnergies[maxexc_ - 1]) << \" nm\" << std::flush;\n\n  /*\n   *\n   * For a single excitation, broaden by Lineshape function L(v-W)\n   *    eps(v) = f * L(v-W)\n   *\n   * where\n   *       v: energy\n   *       f: oscillator strength in dipole-length gauge\n   *       W: excitation energy\n   *\n   * Lineshape function depend on FWHM and can be\n   *\n   *      Gaussian\n   *          L(v-W) = 1/(sqrt(2pi)sigma) * exp(-0.5 (v-W)^2/sigma^2\n   *\n   *\n   *            with sigma: derived from FWHM (FWHM/2.3548)\n   *\n   *     Lorentzian\n   *          L(v-W) = 1/pi * 0.5 FWHM/( (v-w)^2 + 0.25*FWHM^2 )\n   *\n   * Full spectrum is superposition of individual spectra.\n   *\n   *  Alternatively, one can calculate the imaginary part of the\n   *  frequency-dependent dielectric function\n   *\n   *   IM(eps(v)) ~ 1/v^2 * W^2 * |td|^2 * L(v-W)\n   *              = 1/v^2 * W   * f      * L(v-W)\n   *\n   *\n   */\n\n  std::ofstream ofs(output_file_, std::ofstream::out);\n\n  if (spectrum_type_ == \"energy\") {\n    ofs << \"# E(eV)    epsGaussian    IM(eps)Gaussian   epsLorentz    \"\n           \"Im(esp)Lorentz\\n\";\n    for (Index i_pt = 0; i_pt <= n_pt_; i_pt++) {\n\n      double e = (lower_ + double(i_pt) * (upper_ - lower_) / double(n_pt_));\n\n      double eps_Gaussian = 0.0;\n      double imeps_Gaussian = 0.0;\n      double eps_Lorentzian = 0.0;\n      double imeps_Lorentzian = 0.0;\n\n      for (Index i_exc = minexc_; i_exc <= maxexc_; i_exc++) {\n        eps_Gaussian +=\n            osc[i_exc] *\n            Gaussian(e, BSESingletEnergies(i_exc) + shiftby_, fwhm_);\n        imeps_Gaussian += osc[i_exc] * BSESingletEnergies(i_exc) *\n                          Gaussian(e, BSESingletEnergies(i_exc), fwhm_);\n        eps_Lorentzian +=\n            osc[i_exc] * Lorentzian(e, BSESingletEnergies(i_exc), fwhm_);\n        imeps_Lorentzian += osc[i_exc] * BSESingletEnergies(i_exc) *\n                            Lorentzian(e, BSESingletEnergies(i_exc), fwhm_);\n      }\n\n      ofs << e << \"    \" << eps_Gaussian << \"   \" << imeps_Gaussian << \"   \"\n          << eps_Lorentzian << \"   \" << imeps_Lorentzian << std::endl;\n    }\n\n    XTP_LOG(Log::error, log_)\n        << \" Spectrum in energy range from  \" << lower_ << \" to \" << upper_\n        << \" eV and with broadening of FWHM \" << fwhm_\n        << \" eV written to file  \" << output_file_ << std::flush;\n  }\n\n  if (spectrum_type_ == \"wavelength\") {\n\n    ofs << \"# lambda(nm)    epsGaussian    IM(eps)Gaussian   epsLorentz    \"\n           \"Im(esp)Lorentz\\n\";\n    for (Index i_pt = 0; i_pt <= n_pt_; i_pt++) {\n\n      double lambda =\n          (lower_ + double(i_pt) * (upper_ - lower_) / double(n_pt_));\n      double eps_Gaussian = 0.0;\n      double imeps_Gaussian = 0.0;\n      double eps_Lorentzian = 0.0;\n      double imeps_Lorentzian = 0.0;\n\n      for (Index i_exc = minexc_; i_exc <= maxexc_; i_exc++) {\n        double exc_lambda = nmtoev(BSESingletEnergies(i_exc) + shiftby_);\n        eps_Gaussian += osc[i_exc] * Gaussian(lambda, exc_lambda, fwhm_);\n        imeps_Gaussian +=\n            osc[i_exc] * exc_lambda * Gaussian(lambda, exc_lambda, fwhm_);\n        eps_Lorentzian += osc[i_exc] * Lorentzian(lambda, exc_lambda, fwhm_);\n        imeps_Lorentzian +=\n            osc[i_exc] * exc_lambda * Lorentzian(lambda, exc_lambda, fwhm_);\n      }\n\n      ofs << lambda << \"    \" << eps_Gaussian << \"   \" << imeps_Gaussian\n          << \"   \" << eps_Lorentzian << \"   \" << imeps_Lorentzian << std::endl;\n    }\n    XTP_LOG(Log::error, log_)\n        << \" Spectrum in wavelength range from  \" << lower_ << \" to \" << upper_\n        << \" nm and with broadening of FWHM \" << fwhm_\n        << \" nm written to file  \" << output_file_ << std::flush;\n  }\n\n  ofs.close();\n  return true;\n}\n\ndouble Spectrum::Lorentzian(double x, double center, double fwhm) {\n  return 0.5 * fwhm / (std::pow(x - center, 2) + 0.25 * fwhm * fwhm) /\n         boost::math::constants::pi<double>();\n}\n\ndouble Spectrum::Gaussian(double x, double center, double fwhm) {\n  // FWHM = 2*sqrt(2 ln2) sigma = 2.3548 sigma\n  double sigma = fwhm / 2.3548;\n  return std::exp(-0.5 * std::pow((x - center) / sigma, 2)) / sigma /\n         sqrt(2.0 * boost::math::constants::pi<double>());\n}\n\ndouble Spectrum::evtonm(double eV) { return 1241.0 / eV; }\n\ndouble Spectrum::evtoinvcm(double eV) { return 8065.73 * eV; }\n\ndouble Spectrum::nmtoinvcm(double nm) { return 1241.0 * 8065.73 / nm; }\n\ndouble Spectrum::invcmtonm(double invcm) { return 1.0e7 / invcm; }\n\ndouble Spectrum::nmtoev(double nm) { return 1241.0 / nm; }\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "be83c10ac687dfac62a9a0a50043eaac79167199", "size": 7583, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/tools/spectrum.cc", "max_stars_repo_name": "rubengerritsen/xtp", "max_stars_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/tools/spectrum.cc", "max_issues_repo_name": "rubengerritsen/xtp", "max_issues_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/tools/spectrum.cc", "max_forks_repo_name": "rubengerritsen/xtp", "max_forks_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7022222222, "max_line_length": 79, "alphanum_fraction": 0.6132137676, "num_tokens": 2280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.41004541425490093}}
{"text": "#pragma once\n\n/**************************************************************************\n * Combination of domains:\n *\n * (1) reduced product of two arbitrary domains with only lattice\n *     operations.\n *\n * (2) reduced product of two arbitrary domains with all operations.\n *\n * The reduction in (1) and (2) is simply done by making bottom the\n * abstract state if one of them is bottom.\n *\n * (3) reduced product of two numerical domains. The reduction is done\n *     via a special push operation that must be defined by the\n *     domains. This is often more precise than (2).\n **************************************************************************/\n\n#include <crab/domains/abstract_domain.hpp>\n#include <crab/domains/abstract_domain_specialized_traits.hpp>\n#include <crab/support/stats.hpp>\n\n#include <boost/optional.hpp>\n#include <algorithm>\n\nnamespace crab {\nnamespace domains {\n\n// Reduced product of two arbitrary domains with only lattice\n// operations.\ntemplate <typename Domain1, typename Domain2> class basic_domain_product2 {\n\npublic:\n  using basic_domain_product2_t = basic_domain_product2<Domain1, Domain2>;\n  using first_type = Domain1;\n  using second_type = Domain2;\n\nprivate:\n  bool m_is_bottom;\n  Domain1 m_first;\n  Domain2 m_second;\n\n  void canonicalize() {\n    if (!m_is_bottom) {\n      m_is_bottom = m_first.is_bottom() || m_second.is_bottom();\n      if (m_is_bottom) {\n        m_first.set_to_bottom();\n        m_second.set_to_bottom();\n      }\n    }\n  }\n\npublic:\n  basic_domain_product2() : m_is_bottom(false) {\n    m_first.set_to_top();\n    m_second.set_to_top();\n  }\n\n  basic_domain_product2(Domain1 &&first, Domain2 &&second,\n                        bool &&apply_reduction = true)\n      : m_is_bottom(false), m_first(std::move(first)),\n        m_second(std::move(second)) {\n    if (apply_reduction) {\n      // we don't apply normalization when widening\n      canonicalize();\n    }\n  }\n\n  basic_domain_product2(const basic_domain_product2_t &other) = default;\n  basic_domain_product2(basic_domain_product2_t &&other) = default;\n  basic_domain_product2_t &\n  operator=(const basic_domain_product2_t &other) = default;\n  basic_domain_product2_t &operator=(basic_domain_product2_t &&other) = default;\n\n  basic_domain_product2_t make_top() const {\n    Domain1 dom1;\n    Domain2 dom2;\n    dom1.set_to_top();\n    dom2.set_to_top();\n    return basic_domain_product2_t(std::move(dom1), std::move(dom2));\n  }\n\n  basic_domain_product2_t make_bottom() const {\n    Domain1 dom1;\n    Domain2 dom2;\n    dom1.set_to_bottom();\n    dom2.set_to_bottom();\n    return basic_domain_product2_t(std::move(dom1), std::move(dom2));\n  }\n\n  void set_to_top() {\n    m_is_bottom = false;\n    m_first.set_to_top();\n    m_second.set_to_top();\n  }\n\n  void set_to_bottom() {\n    m_is_bottom = true;\n    m_first.set_to_bottom();\n    m_second.set_to_bottom();\n  }\n\n  bool is_bottom() const {\n    // canonicalize();\n    // return m_is_bottom;\n    if (m_is_bottom) {\n      return true;\n    } else {\n      return m_first.is_bottom() || m_second.is_bottom();\n    }\n  }\n\n  bool is_top() const {\n    return (m_first.is_top() && m_second.is_top());\n  }\n\n  Domain1 &first() {\n    canonicalize();\n    return m_first;\n  }\n\n  Domain2 &second() {\n    canonicalize();\n    return m_second;\n  }\n\n  const Domain1 &first() const { return m_first; }\n\n  const Domain2 &second() const { return m_second; }\n\n  bool operator<=(const basic_domain_product2_t &other) const {\n    if (is_bottom()) {\n      return true;\n    } else if (other.is_bottom()) {\n      return false;\n    } else {\n      return (m_first <= other.m_first) && (m_second <= other.m_second);\n    }\n  }\n\n  bool operator==(const basic_domain_product2_t &other) const {\n    return (operator<=(other) && other.operator<=(*this));\n  }\n\n  void operator|=(const basic_domain_product2_t &other) {\n    if (is_bottom()) {\n      *this = other;\n    } else if (other.is_bottom()) {\n      return;\n    } else {\n      m_first |= other.m_first;\n      m_second |= other.m_second;\n    }\n  }\n\n  basic_domain_product2_t\n  operator|(const basic_domain_product2_t &other) const {\n    if (is_bottom()) {\n      return other;\n    } else if (other.is_bottom()) {\n      return *this;\n    } else {\n      return basic_domain_product2_t(m_first | other.m_first,\n                                     m_second | other.m_second);\n    }\n  }\n\n  basic_domain_product2_t\n  operator||(const basic_domain_product2_t &other) const {\n    return basic_domain_product2_t(m_first || other.m_first,\n                                   m_second || other.m_second,\n                                   false /* do not apply reduction */);\n  }\n\n  basic_domain_product2_t\n  operator&(const basic_domain_product2_t &other) const {\n    if (is_bottom() || other.is_top()) {\n      return *this;\n    } else if (other.is_bottom() || is_top()) {\n      return other;\n    } else {\n      return basic_domain_product2_t(m_first & other.m_first,\n                                     m_second & other.m_second);\n    }\n  }\n\n  basic_domain_product2_t\n  operator&&(const basic_domain_product2_t &other) const {\n    if (is_bottom() || other.is_top()) {\n      return *this;\n    } else if (other.is_bottom() || is_top()) {\n      return other;\n    } else {\n      return basic_domain_product2_t(m_first && other.m_first,\n                                     m_second && other.m_second);\n    }\n  }\n\n  void write(crab::crab_os &o) const {\n    if (is_bottom()) {\n      o << \"_|_\";\n    } else {\n      o << \"(\" << m_first << \", \" << m_second << \")\";\n    }\n  }\n\n  friend crab::crab_os &operator<<(crab::crab_os &o,\n                                   basic_domain_product2_t &dom) {\n    dom.write(o);\n    return o;\n  }\n\n  std::string domain_name() const {\n    std::string name =\n        \"Product(\" + m_first.domain_name() + \",\" + m_second.domain_name() + \")\";\n    return name;\n  }\n\n}; // class basic_domain_product2\n\n// Reduced product of two arbitrary domains with all operations.\ntemplate <typename Number, typename VariableName, typename Domain1,\n          typename Domain2>\nclass domain_product2 final\n    : public abstract_domain_api<\n          domain_product2<Number, VariableName, Domain1, Domain2>> {\npublic:\n  using domain_product2_t =\n      domain_product2<Number, VariableName, Domain1, Domain2>;\n  using abstract_domain_t = abstract_domain_api<domain_product2_t>;\n  using first_type = Domain1;\n  using second_type = Domain2;\n\n  using typename abstract_domain_t::disjunctive_linear_constraint_system_t;\n  using typename abstract_domain_t::interval_t;\n  using typename abstract_domain_t::linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_t;\n  using typename abstract_domain_t::linear_expression_t;\n  using typename abstract_domain_t::reference_constraint_t;\n  using typename abstract_domain_t::variable_or_constant_t;\n  using typename abstract_domain_t::variable_t;\n  using typename abstract_domain_t::variable_vector_t;\n  using typename abstract_domain_t::variable_or_constant_vector_t;  \n  using number_t = Number;\n  using varname_t = VariableName;\n\nprivate:\n  using basic_domain_product2_t = basic_domain_product2<Domain1, Domain2>;\n\n  basic_domain_product2_t m_product;\n\n  domain_product2(basic_domain_product2_t &&product)\n      : m_product(std::move(product)) {}\n\n  // Reduce operation\n  void reduce() {\n    if (m_product.first().is_bottom() ||\n        m_product.second().is_bottom()) {\n      m_product.set_to_bottom();\n    }\n  }\n\npublic:\n  domain_product2_t make_top() const override {\n    basic_domain_product2_t dom_prod;\n    return domain_product2_t(dom_prod.make_top());\n  }\n\n  domain_product2_t make_bottom() const override {\n    basic_domain_product2_t dom_prod;\n    return domain_product2_t(dom_prod.make_bottom());\n  }\n\n  void set_to_top() override {\n    basic_domain_product2_t dom_prod;\n    domain_product2_t dom(dom_prod.make_top());\n    std::swap(*this, dom);\n  }\n\n  void set_to_bottom() override {\n    basic_domain_product2_t dom_prod;\n    domain_product2_t dom(dom_prod.make_bottom());\n    std::swap(*this, dom);\n  }\n\n  domain_product2() : m_product() {}\n\n  domain_product2(const domain_product2_t &other) : m_product(other.m_product) {}\n\n  domain_product2(const domain_product2_t &&other)\n      : m_product(std::move(other.m_product)) {}\n\n  domain_product2_t &operator=(const domain_product2_t &other) {\n    if (this != &other)\n      m_product = other.m_product;\n    return *this;\n  }\n\n  domain_product2_t &operator=(const domain_product2_t &&other) {\n    if (this != &other)\n      m_product = std::move(other.m_product);\n    return *this;\n  }\n\n  bool is_bottom() const override { return m_product.is_bottom(); }\n\n  bool is_top() const override { return m_product.is_top(); }\n\n  Domain1 &first() { return m_product.first(); }\n  const Domain1 &first() const { return m_product.first(); }\n\n  Domain2 &second() { return m_product.second(); }\n  const Domain2 &second() const { return m_product.second(); }\n\n  bool operator<=(const domain_product2_t &other) const override {\n    return (m_product <= other.m_product);\n  }\n\n  bool operator==(const domain_product2_t &other) const {\n    return (m_product == other.m_product);\n  }\n\n  void operator|=(const domain_product2_t &other) override {\n    m_product |= other.m_product;\n  }\n\n  domain_product2_t operator|(const domain_product2_t &other) const override {\n    return domain_product2_t(m_product | other.m_product);\n  }\n\n  domain_product2_t operator&(const domain_product2_t &other) const override {\n    return domain_product2_t(m_product & other.m_product);\n  }\n\n  domain_product2_t operator||(const domain_product2_t &other) const override {\n    return domain_product2_t(m_product || other.m_product);\n  }\n\n  domain_product2_t widening_thresholds(\n      const domain_product2_t &other,\n      const iterators::thresholds<number_t> &ts) const override {\n    bool apply_reduction = false;\n    return domain_product2_t(basic_domain_product2_t(\n        std::move(m_product.first().widening_thresholds(\n            other.m_product.first(), ts)),\n        std::move(m_product.second().widening_thresholds(\n            other.m_product.second(), ts)),\n        std::move(apply_reduction)));\n  }\n\n  domain_product2_t operator&&(const domain_product2_t &other) const override {\n    return domain_product2_t(m_product && other.m_product);\n  }\n\n  void assign(const variable_t &x, const linear_expression_t &e) override {\n    m_product.first().assign(x, e);\n    m_product.second().assign(x, e);\n  }\n\n  void apply(arith_operation_t op, const variable_t &x, const variable_t &y,\n             const variable_t &z) override {\n    m_product.first().apply(op, x, y, z);\n    m_product.second().apply(op, x, y, z);\n    reduce();\n  }\n\n  void apply(arith_operation_t op, const variable_t &x, const variable_t &y,\n             Number k) override {\n    m_product.first().apply(op, x, y, k);\n    m_product.second().apply(op, x, y, k);\n    reduce();\n  }\n\n  void select(const variable_t &lhs, const linear_constraint_t &cond,\n\t      const linear_expression_t &e1,  const linear_expression_t &e2) override {\n    m_product.first().select(lhs, cond, e1, e2);\n    m_product.second().select(lhs, cond, e1, e2);\n    reduce();\n  }  \n\n  void backward_assign(const variable_t &x, const linear_expression_t &e,\n                       const domain_product2_t &invariant) override {\n    m_product.first().backward_assign(x, e, invariant.first());\n    m_product.second().backward_assign(x, e, invariant.second());\n    reduce();\n  }\n\n  void backward_apply(arith_operation_t op, const variable_t &x,\n                      const variable_t &y, Number k,\n                      const domain_product2_t &invariant) override {\n    m_product.first().backward_apply(op, x, y, k, invariant.first());\n    m_product.second().backward_apply(op, x, y, k, invariant.second());\n    reduce();\n  }\n\n  void backward_apply(arith_operation_t op, const variable_t &x,\n                      const variable_t &y, const variable_t &z,\n                      const domain_product2_t &invariant) override {\n    m_product.first().backward_apply(op, x, y, z, invariant.first());\n    m_product.second().backward_apply(op, x, y, z, invariant.second());\n    reduce();\n  }\n\n  void operator+=(const linear_constraint_system_t &csts) override {\n    m_product.first() += csts;\n    m_product.second() += csts;\n    reduce();\n  }\n\n  void operator-=(const variable_t &v) override {\n    m_product.first() -= v;\n    m_product.second() -= v;\n  }\n\n  // cast operators\n\n  void apply(int_conv_operation_t op, const variable_t &dst,\n             const variable_t &src) override {\n    m_product.first().apply(op, dst, src);\n    m_product.second().apply(op, dst, src);\n    reduce();\n  }\n\n  // bitwise operators\n\n  void apply(bitwise_operation_t op, const variable_t &x, const variable_t &y,\n             const variable_t &z) override {\n    m_product.first().apply(op, x, y, z);\n    m_product.second().apply(op, x, y, z);\n    reduce();\n  }\n\n  void apply(bitwise_operation_t op, const variable_t &x, const variable_t &y,\n             Number k) override {\n    m_product.first().apply(op, x, y, k);\n    m_product.second().apply(op, x, y, k);\n    reduce();\n  }\n\n  // array operators\n\n  virtual void array_init(const variable_t &a,\n                          const linear_expression_t &elem_size,\n                          const linear_expression_t &lb_idx,\n                          const linear_expression_t &ub_idx,\n                          const linear_expression_t &val) override {\n    m_product.first().array_init(a, elem_size, lb_idx, ub_idx, val);\n    m_product.second().array_init(a, elem_size, lb_idx, ub_idx, val);\n    reduce();\n  }\n\n  virtual void array_load(const variable_t &lhs, const variable_t &a,\n                          const linear_expression_t &elem_size,\n                          const linear_expression_t &i) override {\n\n    m_product.first().array_load(lhs, a, elem_size, i);\n    m_product.second().array_load(lhs, a, elem_size, i);\n    reduce();\n  }\n\n  virtual void array_store(const variable_t &a,\n                           const linear_expression_t &elem_size,\n                           const linear_expression_t &i,\n                           const linear_expression_t &val,\n                           bool is_strong_update) override {\n    m_product.first().array_store(a, elem_size, i, val, is_strong_update);\n    m_product.second().array_store(a, elem_size, i, val, is_strong_update);\n    reduce();\n  }\n\n  virtual void array_store_range(const variable_t &a,\n                                 const linear_expression_t &elem_size,\n                                 const linear_expression_t &i,\n                                 const linear_expression_t &j,\n                                 const linear_expression_t &val) override {\n    m_product.first().array_store_range(a, elem_size, i, j, val);\n    m_product.second().array_store_range(a, elem_size, i, j, val);\n    reduce();\n  }\n\n  virtual void array_assign(const variable_t &lhs,\n                            const variable_t &rhs) override {\n    m_product.first().array_assign(lhs, rhs);\n    m_product.second().array_assign(lhs, rhs);\n    reduce();\n  }\n\n  // backward array operations\n\n  virtual void\n  backward_array_init(const variable_t &a, const linear_expression_t &elem_size,\n                      const linear_expression_t &lb_idx,\n                      const linear_expression_t &ub_idx,\n                      const linear_expression_t &val,\n                      const domain_product2_t &invariant) override {\n    m_product.first().backward_array_init(a, elem_size, lb_idx, ub_idx,\n                                               val, invariant.first());\n    m_product.second().backward_array_init(a, elem_size, lb_idx, ub_idx,\n                                                val, invariant.second());\n    reduce();\n  }\n\n  virtual void\n  backward_array_load(const variable_t &lhs, const variable_t &a,\n                      const linear_expression_t &elem_size,\n                      const linear_expression_t &i,\n                      const domain_product2_t &invariant) override {\n\n    m_product.first().backward_array_load(lhs, a, elem_size, i,\n                                               invariant.first());\n    m_product.second().backward_array_load(lhs, a, elem_size, i,\n                                                invariant.second());\n    reduce();\n  }\n\n  virtual void backward_array_store(\n      const variable_t &a, const linear_expression_t &elem_size,\n      const linear_expression_t &i, const linear_expression_t &val,\n      bool is_strong_update, const domain_product2_t &invariant) override {\n    m_product.first().backward_array_store(\n        a, elem_size, i, val, is_strong_update, invariant.first());\n    m_product.second().backward_array_store(\n        a, elem_size, i, val, is_strong_update, invariant.second());\n    reduce();\n  }\n\n  virtual void backward_array_store_range(\n      const variable_t &a, const linear_expression_t &elem_size,\n      const linear_expression_t &i, const linear_expression_t &j,\n      const linear_expression_t &val,\n      const domain_product2_t &invariant) override {\n    m_product.first().backward_array_store_range(a, elem_size, i, j, val,\n                                                      invariant.first());\n    m_product.second().backward_array_store_range(a, elem_size, i, j, val,\n                                                       invariant.second());\n    reduce();\n  }\n\n  virtual void\n  backward_array_assign(const variable_t &lhs, const variable_t &rhs,\n                        const domain_product2_t &invariant) override {\n    m_product.first().backward_array_assign(lhs, rhs, invariant.first());\n    m_product.second().backward_array_assign(lhs, rhs, invariant.second());\n    reduce();\n  }\n\n  // region/reference operators\n  virtual void region_init(const variable_t &reg) override {\n    m_product.first().region_init(reg);\n    m_product.second().region_init(reg);\n    reduce();\n  }\n\n  virtual void region_copy(const variable_t &lhs_reg,\n                           const variable_t &rhs_reg) override {\n    m_product.first().region_copy(lhs_reg, rhs_reg);\n    m_product.second().region_copy(lhs_reg, rhs_reg);\n    reduce();\n  }\n\n  virtual void region_cast(const variable_t &src_reg,\n                           const variable_t &dst_reg) override {\n    m_product.first().region_cast(src_reg, dst_reg);\n    m_product.second().region_cast(src_reg, dst_reg);\n    reduce();\n  }\n  \n  virtual void ref_make(const variable_t &ref, const variable_t &reg,\n\t\t\tconst variable_or_constant_t &size,\n\t\t\tconst allocation_site &as) override {\n    m_product.first().ref_make(ref, reg, size, as);\n    m_product.second().ref_make(ref, reg, size, as);\n    reduce();\n  }\n\n  virtual void ref_free(const variable_t &reg, const variable_t &ref) override {\n    m_product.first().ref_free(reg, ref);\n    m_product.second().ref_free(reg, ref);\n    reduce();\n  }\n  \n  virtual void ref_load(const variable_t &ref, const variable_t &reg,\n                        const variable_t &res) override {\n    m_product.first().ref_load(ref, reg, res);\n    m_product.second().ref_load(ref, reg, res);\n    reduce();\n  }\n\n  virtual void ref_store(const variable_t &ref, const variable_t &reg,\n                         const variable_or_constant_t &val) override {\n    m_product.first().ref_store(ref, reg, val);\n    m_product.second().ref_store(ref, reg, val);\n    reduce();\n  }\n\n  virtual void ref_gep(const variable_t &ref1, const variable_t &reg1,\n                       const variable_t &ref2, const variable_t &reg2,\n                       const linear_expression_t &offset) override {\n    m_product.first().ref_gep(ref1, reg1, ref2, reg2, offset);\n    m_product.second().ref_gep(ref1, reg1, ref2, reg2, offset);\n    reduce();\n  }\n\n  virtual void\n  ref_load_from_array(const variable_t &lhs, const variable_t &ref,\n                      const variable_t &region,\n                      const linear_expression_t &index,\n                      const linear_expression_t &elem_size) override {\n    m_product.first().ref_load_from_array(lhs, ref, region, index,\n                                               elem_size);\n    m_product.second().ref_load_from_array(lhs, ref, region, index,\n                                                elem_size);\n    reduce();\n  }\n\n  virtual void ref_store_to_array(const variable_t &ref,\n                                  const variable_t &region,\n                                  const linear_expression_t &index,\n                                  const linear_expression_t &elem_size,\n                                  const linear_expression_t &val) override {\n    m_product.first().ref_store_to_array(ref, region, index, elem_size,\n                                              val);\n    m_product.second().ref_store_to_array(ref, region, index, elem_size,\n                                               val);\n    reduce();\n  }\n\n  virtual void ref_assume(const reference_constraint_t &cst) override {\n    m_product.first().ref_assume(cst);\n    m_product.second().ref_assume(cst);\n    reduce();\n  }\n\n  void ref_to_int(const variable_t &reg, const variable_t &ref_var,\n                  const variable_t &int_var) override {\n    m_product.first().ref_to_int(reg, ref_var, int_var);\n    m_product.second().ref_to_int(reg, ref_var, int_var);\n    reduce();\n  }\n\n  void int_to_ref(const variable_t &int_var, const variable_t &reg,\n                  const variable_t &ref_var) override {\n    m_product.first().int_to_ref(int_var, reg, ref_var);\n    m_product.second().int_to_ref(int_var, reg, ref_var);\n    reduce();\n  }\n  void select_ref(const variable_t &lhs_ref, const variable_t &lhs_rgn,\n\t\t  const variable_t &cond,\n\t\t  const variable_or_constant_t &ref1,\n\t\t  const boost::optional<variable_t> &rgn1,\n\t\t  const variable_or_constant_t &ref2,\n\t\t  const boost::optional<variable_t> &rgn2) override {\n    m_product.first().select_ref(lhs_ref, lhs_rgn, cond, ref1, rgn1, ref2, rgn2);\n    m_product.second().select_ref(lhs_ref, lhs_rgn, cond, ref1, rgn1, ref2, rgn2);\n    reduce();\n  }\n\n  boolean_value is_null_ref(const variable_t &ref) override {\n    return m_product.first().is_null_ref(ref) & m_product.second().is_null_ref(ref);\n  }\n\n  bool get_allocation_sites(const variable_t &ref,\n\t\t\t    std::vector<allocation_site> &out) override {\n    std::vector<allocation_site> s1, s2;\n    bool b1 = m_product.first().get_allocation_sites(ref, s1);\n    bool b2 = m_product.first().get_allocation_sites(ref, s2);\n    if (b1 && b2) {\n      std::sort(s1.begin(), s1.end());\n      std::sort(s2.begin(), s2.end());\n      std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),\n\t\t\t    std::back_inserter(out));\n      return true;\n    } else if (b1) {\n      out.assign(s1.begin(), s1.end());\n      return true;\n    } else if (b2) {\n      out.assign(s2.begin(), s2.end());\n      return true;\n    }\n    return false;\n  }\n\n  bool get_tags(const variable_t &rgn, const variable_t &ref,\n\t\tstd::vector<uint64_t> &out) override {\n    std::vector<uint64_t> s1, s2;\n    bool b1 = m_product.first().get_tags(rgn, ref, s1);\n    bool b2 = m_product.first().get_tags(rgn, ref, s2);\n    if (b1 && b2) {\n      std::sort(s1.begin(), s1.end());\n      std::sort(s2.begin(), s2.end());\n      std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),\n\t\t\t    std::back_inserter(out));\n      return true;\n    } else if (b1) {\n      out.assign(s1.begin(), s1.end());\n      return true;\n    } else if (b2) {\n      out.assign(s2.begin(), s2.end());\n      return true;\n    }\n    return false;\n  }\n  \n  // boolean operators\n  virtual void assign_bool_cst(const variable_t &lhs,\n                               const linear_constraint_t &rhs) override {\n    m_product.first().assign_bool_cst(lhs, rhs);\n    m_product.second().assign_bool_cst(lhs, rhs);\n    reduce();\n  }\n\n  virtual void assign_bool_ref_cst(const variable_t &lhs,\n                                   const reference_constraint_t &rhs) override {\n    m_product.first().assign_bool_ref_cst(lhs, rhs);\n    m_product.second().assign_bool_ref_cst(lhs, rhs);\n    reduce();\n  }\n\n  virtual void assign_bool_var(const variable_t &lhs, const variable_t &rhs,\n                               bool is_not_rhs) override {\n    m_product.first().assign_bool_var(lhs, rhs, is_not_rhs);\n    m_product.second().assign_bool_var(lhs, rhs, is_not_rhs);\n    reduce();\n  }\n\n  virtual void apply_binary_bool(bool_operation_t op, const variable_t &x,\n                                 const variable_t &y,\n                                 const variable_t &z) override {\n    m_product.first().apply_binary_bool(op, x, y, z);\n    m_product.second().apply_binary_bool(op, x, y, z);\n    reduce();\n  }\n\n  virtual void assume_bool(const variable_t &v, bool is_negated) override {\n    m_product.first().assume_bool(v, is_negated);\n    m_product.second().assume_bool(v, is_negated);\n    reduce();\n  }\n\n  virtual void select_bool(const variable_t &lhs, const variable_t &cond,\n\t\t\t   const variable_t &b1, const variable_t &b2) override {\n    m_product.first().select_bool(lhs, cond, b1, b2);\n    m_product.second().select_bool(lhs, cond, b1, b2);\n    reduce();\n  }\n  \n  // backward boolean operators\n  virtual void backward_assign_bool_cst(const variable_t &lhs,\n                                        const linear_constraint_t &rhs,\n                                        const domain_product2_t &inv) override {\n    m_product.first().backward_assign_bool_cst(lhs, rhs, inv.first());\n    m_product.second().backward_assign_bool_cst(lhs, rhs, inv.second());\n    reduce();\n  }\n\n  virtual void\n  backward_assign_bool_ref_cst(const variable_t &lhs,\n                               const reference_constraint_t &rhs,\n                               const domain_product2_t &inv) override {\n    m_product.first().backward_assign_bool_ref_cst(lhs, rhs, inv.first());\n    m_product.second().backward_assign_bool_ref_cst(lhs, rhs,\n                                                         inv.second());\n    reduce();\n  }\n\n  virtual void backward_assign_bool_var(const variable_t &lhs,\n                                        const variable_t &rhs, bool is_not_rhs,\n                                        const domain_product2_t &inv) override {\n    m_product.first().backward_assign_bool_var(lhs, rhs, is_not_rhs,\n                                                    inv.first());\n    m_product.second().backward_assign_bool_var(lhs, rhs, is_not_rhs,\n                                                     inv.second());\n    reduce();\n  }\n\n  virtual void\n  backward_apply_binary_bool(bool_operation_t op, const variable_t &x,\n                             const variable_t &y, const variable_t &z,\n                             const domain_product2_t &inv) override {\n    m_product.first().backward_apply_binary_bool(op, x, y, z, inv.first());\n    m_product.second().backward_apply_binary_bool(op, x, y, z,\n                                                       inv.second());\n    reduce();\n  }\n\n  virtual void forget(const variable_vector_t &variables) override {\n    m_product.first().forget(variables);\n    m_product.second().forget(variables);\n  }\n\n  virtual void project(const variable_vector_t &variables) override {\n    m_product.first().project(variables);\n    m_product.second().project(variables);\n  }\n\n  virtual void expand(const variable_t &var,\n                      const variable_t &new_var) override {\n    m_product.first().expand(var, new_var);\n    m_product.second().expand(var, new_var);\n  }\n\n  virtual void normalize() override {\n    m_product.first().normalize();\n    m_product.second().normalize();\n  }\n\n  virtual void minimize() override {\n    m_product.first().minimize();\n    m_product.second().minimize();\n  }\n\n  virtual interval_t operator[](const variable_t &v) override {\n    return m_product.first()[v] & m_product.second()[v];\n  }\n\n  virtual linear_constraint_system_t\n  to_linear_constraint_system() const override {\n    linear_constraint_system_t csts;\n    // XXX: We might add redundant constraints.\n    csts += m_product.first().to_linear_constraint_system();\n    csts += m_product.second().to_linear_constraint_system();\n    return csts;\n  }\n\n  virtual disjunctive_linear_constraint_system_t\n  to_disjunctive_linear_constraint_system() const override {\n    disjunctive_linear_constraint_system_t csts;\n    // XXX: We might add redundant constraints.\n    csts += m_product.first().to_disjunctive_linear_constraint_system();\n    csts += m_product.second().to_disjunctive_linear_constraint_system();\n    return csts;\n  }\n\n  virtual void rename(const variable_vector_t &from,\n                      const variable_vector_t &to) override {\n    m_product.first().rename(from, to);\n    m_product.second().rename(from, to);\n  }\n\n  /* begin intrinsics operations */\n  void intrinsic(std::string name,\n\t\t const variable_or_constant_vector_t &inputs,\n                 const variable_vector_t &outputs) override {\n    m_product.first().intrinsic(name, inputs, outputs);\n    m_product.second().intrinsic(name, inputs, outputs);\n  }\n\n  void backward_intrinsic(std::string name,\n\t\t\t  const variable_or_constant_vector_t &inputs,\n                          const variable_vector_t &outputs,\n                          const domain_product2_t &invariant) override {\n    m_product.first().backward_intrinsic(name, inputs, outputs,\n\t\t\t\t\t invariant.first());\n    m_product.second().backward_intrinsic(name, inputs, outputs,\n\t\t\t\t\t  invariant.second());\n  }\n  /* end intrinsics operations */\n\n  void write(crab::crab_os &o) const override { m_product.write(o); }\n\n  std::string domain_name() const override {\n    return m_product.domain_name();\n  }\n\n}; // class domain_product2\n\nnamespace reduced_product_impl {\nclass default_params {\npublic:\n  enum { left_propagate_equalities = 1 };\n  enum { right_propagate_equalities = 1 };\n  enum { left_propagate_inequalities = 1 };\n  enum { right_propagate_inequalities = 1 };\n  enum { left_propagate_intervals = 1 };\n  enum { right_propagate_intervals = 1 };\n  enum { disable_reduction = 0 };\n  enum { apply_reduction_only_add_constraint = 0 };\n};\n\nclass term_dbm_params {\npublic:\n  enum { left_propagate_equalities = 1 };\n  enum { right_propagate_equalities = 1 };\n  enum { left_propagate_inequalities = 0 };\n  enum { right_propagate_inequalities = 0 };\n  enum { left_propagate_intervals = 0 };\n  enum { right_propagate_intervals = 0 };\n  enum { disable_reduction = 0 };\n  enum { apply_reduction_only_add_constraint = 1 };\n};\n} // namespace reduced_product_impl\n\n// This domain is similar to domain_product2 but it combines two\n// numerical domains and it defines a more precise, customizable\n// reduction operation.\ntemplate <typename Domain1, typename Domain2,\n          class Params = reduced_product_impl::default_params>\nclass reduced_numerical_domain_product2 final\n    : public abstract_domain_api<\n          reduced_numerical_domain_product2<Domain1, Domain2, Params>> {\n\npublic:\n  using reduced_numerical_domain_product2_t =\n      reduced_numerical_domain_product2<Domain1, Domain2, Params>;\n  using abstract_domain_t =\n      abstract_domain_api<reduced_numerical_domain_product2_t>;\n  using typename abstract_domain_t::disjunctive_linear_constraint_system_t;\n  using typename abstract_domain_t::interval_t;\n  using typename abstract_domain_t::linear_constraint_system_t;\n  using typename abstract_domain_t::linear_constraint_t;\n  using typename abstract_domain_t::linear_expression_t;\n  using typename abstract_domain_t::reference_constraint_t;\n  using typename abstract_domain_t::variable_or_constant_t;\n  using typename abstract_domain_t::variable_t;\n  using typename abstract_domain_t::variable_vector_t;\n  using typename abstract_domain_t::variable_or_constant_vector_t;  \n  using number_t = typename Domain1::number_t;\n  using varname_t = typename Domain1::varname_t;\n\n  static_assert(std::is_same<number_t, typename Domain2::number_t>::value,\n                \"Domain1 and Domain2 must have same type for number_t\");\n  static_assert(std::is_same<varname_t, typename Domain2::varname_t>::value,\n                \"Domain1 and Domain2 must have same type for varname_t\");\n\nprivate:\n  using domain_product2_t =\n      domain_product2<number_t, varname_t, Domain1, Domain2>;\n\n  domain_product2_t m_product;\n\n  reduced_numerical_domain_product2(const domain_product2_t &product)\n      : m_product(product) {}\n\n  linear_constraint_system_t to_linear_constraints(const variable_t &v,\n                                                   interval_t i) const {\n    linear_constraint_system_t csts;\n    if (i.lb().is_finite() && i.ub().is_finite()) {\n      auto lb = *(i.lb().number());\n      auto ub = *(i.ub().number());\n      if (lb == ub) {\n        csts += (v == lb);\n      } else {\n        csts += (v >= lb);\n        csts += (v <= ub);\n      }\n    } else if (i.lb().is_finite()) {\n      auto lb = *(i.lb().number());\n      csts += (v >= lb);\n    } else if (i.ub().is_finite()) {\n      auto ub = *(i.ub().number());\n      csts += (v <= ub);\n    }\n    return csts;\n  }\n\n  void reduce_variable(const variable_t &v) {\n    crab::CrabStats::count(domain_name() + \".count.reduce\");\n    crab::ScopedCrabStats __st__(domain_name() + \".reduce\");\n\n    if (!is_bottom() && !Params::disable_reduction) {\n\n      // We just propagate from one domain to another.  We could\n      // propagate in the other direction ... and repeat it\n      // computing a fixpoint+narrowing of descending iterations.\n\n      Domain1 &inv1 = m_product.first();\n      Domain2 &inv2 = m_product.second();\n\n      //////\n      // propagate interval constraints between domains\n      //////\n      if (Params::left_propagate_intervals) {\n        interval_t i1 = inv1[v];\n        if (!i1.is_top())\n          inv2 += to_linear_constraints(v, i1);\n      }\n      if (Params::right_propagate_intervals) {\n        interval_t i2 = inv2[v];\n        if (!i2.is_top())\n          inv1 += to_linear_constraints(v, i2);\n      }\n\n      //////\n      // propagate other constraints expressed by the domains\n      //////\n      if ((Params::left_propagate_equalities ||\n           Params::left_propagate_inequalities) &&\n          (Params::right_propagate_equalities ||\n           Params::right_propagate_inequalities)) {\n        linear_constraint_system_t csts1, csts2, filtered_csts1, filtered_csts2;\n        bool propagate_only_equalities;\n\n        propagate_only_equalities = !Params::left_propagate_inequalities;\n        crab::domains::reduced_domain_traits<Domain1>::extract(\n            inv1, v, csts1, propagate_only_equalities);\n\n        propagate_only_equalities = !Params::right_propagate_inequalities;\n        crab::domains::reduced_domain_traits<Domain2>::extract(\n            inv2, v, csts2, propagate_only_equalities);\n\n        // filter out those redundant constraints (i.e.,\n        // constraints that the other domain already knows about)\n\n        for (auto &c1 : csts1) {\n          if (std::find_if(csts2.begin(), csts2.end(),\n                           [c1](const linear_constraint_t &c2) {\n                             return c2.equal(c1);\n                           }) == csts2.end()) {\n            filtered_csts1 += c1;\n          }\n        }\n\n        {\n          std::string k(domain_name() + \".count.reduce.equalities_from_\" +\n                        m_product.first().domain_name());\n          crab::CrabStats::uset(k, crab::CrabStats::get(k) +\n                                       filtered_csts1.size());\n        }\n        inv2 += filtered_csts1;\n\n        for (auto &c2 : csts2) {\n          if (std::find_if(csts1.begin(), csts1.end(),\n                           [c2](const linear_constraint_t &c1) {\n                             return c1.equal(c2);\n                           }) == csts1.end()) {\n            filtered_csts2 += c2;\n          }\n        }\n        {\n          std::string k(domain_name() + \".count.reduce.equalities_from_\" +\n                        m_product.second().domain_name());\n          crab::CrabStats::uset(k, crab::CrabStats::get(k) + csts2.size());\n        }\n        inv1 += filtered_csts2;\n      } else if (Params::left_propagate_equalities ||\n                 Params::left_propagate_inequalities) {\n        linear_constraint_system_t csts1;\n        const bool propagate_only_equalities =\n            !Params::left_propagate_inequalities;\n        crab::domains::reduced_domain_traits<Domain1>::extract(\n            inv1, v, csts1, propagate_only_equalities);\n        std::string k(domain_name() + \".count.reduce.equalities_from_\" +\n                      m_product.first().domain_name());\n        crab::CrabStats::uset(k, crab::CrabStats::get(k) + csts1.size());\n        inv2 += csts1;\n      } else if (Params::right_propagate_equalities ||\n                 Params::right_propagate_inequalities) {\n        linear_constraint_system_t csts2;\n        const bool propagate_only_equalities =\n            !Params::right_propagate_inequalities;\n        crab::domains::reduced_domain_traits<Domain2>::extract(\n            inv2, v, csts2, propagate_only_equalities);\n        std::string k(domain_name() + \".count.reduce.equalities_from_\" +\n                      m_product.second().domain_name());\n        crab::CrabStats::uset(k, crab::CrabStats::get(k) + csts2.size());\n        inv1 += csts2;\n      }\n    }\n  }\n\npublic:\n  reduced_numerical_domain_product2_t make_top() const override {\n    domain_product2_t dom_prod;\n    return reduced_numerical_domain_product2_t(dom_prod.make_top());\n  }\n\n  reduced_numerical_domain_product2_t make_bottom() const override {\n    domain_product2_t dom_prod;\n    return reduced_numerical_domain_product2_t(dom_prod.make_bottom());\n  }\n\n  void set_to_top() override {\n    domain_product2_t dom_prod;\n    reduced_numerical_domain_product2_t abs(dom_prod.make_top());\n    std::swap(*this, abs);\n  }\n\n  void set_to_bottom() override {\n    domain_product2_t dom_prod;\n    reduced_numerical_domain_product2_t abs(dom_prod.make_bottom());\n    std::swap(*this, abs);\n  }\n\n  reduced_numerical_domain_product2() : m_product() {}\n\n  reduced_numerical_domain_product2(\n      const reduced_numerical_domain_product2_t &other)\n    : m_product(other.m_product) {}\n\n  reduced_numerical_domain_product2(\n      reduced_numerical_domain_product2_t &&other)\n    : m_product(std::move(other.m_product)) {}\n\n  \n  reduced_numerical_domain_product2_t &\n  operator=(const reduced_numerical_domain_product2_t &other) {\n    if (this != &other) {\n      m_product = other.m_product;\n    }\n    return *this;\n  }\n\n  reduced_numerical_domain_product2_t &\n  operator=(reduced_numerical_domain_product2_t &&other) {\n    if (this != &other) {\n      m_product = std::move(other.m_product);\n    }\n    return *this;\n  }\n  \n  bool is_bottom() const override { return m_product.is_bottom(); }\n\n  bool is_top() const override { return m_product.is_top(); }\n\n  bool\n  operator<=(const reduced_numerical_domain_product2_t &other) const override {\n    return m_product <= other.m_product;\n  }\n\n  void operator|=(const reduced_numerical_domain_product2_t &other) override {\n    CRAB_LOG(\"combined-domain\", crab::outs()\n                                    << \"============ JOIN ==================\";\n             crab::outs() << *this << \"\\n----------------\";\n             crab::outs() << other << \"\\n----------------\";);\n    m_product |= other.m_product;\n    CRAB_LOG(\"reduced-dom\", crab::outs() << *this << \"\\n----------------\\n\";);\n  }\n\n  reduced_numerical_domain_product2_t\n  operator|(const reduced_numerical_domain_product2_t &other) const override {\n    reduced_numerical_domain_product2_t res(m_product | other.m_product);\n    CRAB_LOG(\"combined-domain\", crab::outs()\n                                    << \"============ JOIN ==================\";\n             crab::outs() << *this << \"\\n----------------\";\n             crab::outs() << other << \"\\n----------------\";\n             crab::outs() << res << \"\\n================\\n\");\n    return res;\n  }\n\n  reduced_numerical_domain_product2_t\n  operator&(const reduced_numerical_domain_product2_t &other) const override {\n    reduced_numerical_domain_product2_t res(m_product & other.m_product);\n    CRAB_LOG(\"combined-domain\", crab::outs()\n                                    << \"============ MEET ==================\";\n             crab::outs() << *this << \"\\n----------------\";\n             crab::outs() << other << \"\\n----------------\\n\";);\n    return res;\n  }\n\n  reduced_numerical_domain_product2_t\n  operator||(const reduced_numerical_domain_product2_t &other) const override {\n    reduced_numerical_domain_product2_t res(m_product || other.m_product);\n    CRAB_LOG(\"combined-domain\",\n             crab::outs() << \"============ WIDENING ==================\";\n             crab::outs() << *this << \"\\n----------------\";\n             crab::outs() << other << \"\\n----------------\\n\";);\n    return res;\n  }\n\n  reduced_numerical_domain_product2_t widening_thresholds(\n      const reduced_numerical_domain_product2_t &other,\n      const iterators::thresholds<number_t> &ts) const override {\n    reduced_numerical_domain_product2_t res(\n        m_product.widening_thresholds(other.m_product, ts));\n    CRAB_LOG(\"combined-domain\",\n             crab::outs() << \"============ WIDENING ==================\";\n             crab::outs() << *this << \"\\n----------------\";\n             crab::outs() << other << \"\\n----------------\\n\";);\n    return res;\n  }\n\n  reduced_numerical_domain_product2_t\n  operator&&(const reduced_numerical_domain_product2_t &other) const override {\n    reduced_numerical_domain_product2_t res(m_product && other.m_product);\n    CRAB_LOG(\"combined-domain\",\n             crab::outs() << \"============ NARROWING ==================\";\n             crab::outs() << *this << \"\\n----------------\";\n             crab::outs() << other << \"\\n----------------\\n\";);\n    return res;\n  }\n\n  void set(const variable_t &v, interval_t x) {\n    m_product.first().set(v, x);\n    m_product.second().set(v, x);\n  }\n\n  interval_t operator[](const variable_t &v) override {\n    return m_product.first()[v] & m_product.second()[v];\n  }\n\n  void operator+=(const linear_constraint_system_t &csts) override {\n    m_product += csts;\n    if (!is_bottom()) {\n      for (auto const &cst : csts) {\n\tfor (auto const &v : cst.variables()) {\n\t  reduce_variable(v);\n\t  if (is_bottom()) {\n\t    return;\n\t  }\n\t}\n      }\n    }\n    CRAB_LOG(\"combined-domain\", crab::outs() << \"Added constraints \" << csts\n                                             << \"=\" << *this << \"\\n\");\n  }\n\n  void operator-=(const variable_t &v) override { m_product -= v; }\n\n  void assign(const variable_t &x, const linear_expression_t &e) override {\n    m_product.assign(x, e);\n    if (!Params::apply_reduction_only_add_constraint) {\n      reduce_variable(x);\n    }\n    CRAB_LOG(\"combined-domain\", crab::outs()\n                                    << x << \":=\" << e << \"=\" << *this << \"\\n\");\n  }\n\n  void apply(arith_operation_t op, const variable_t &x, const variable_t &y,\n             const variable_t &z) override {\n    m_product.apply(op, x, y, z);\n    if (!Params::apply_reduction_only_add_constraint) {\n      reduce_variable(x);\n    }\n    CRAB_LOG(\"combined-domain\",\n             crab::outs() << x << \":=\" << y << op << z << \"=\" << *this << \"\\n\");\n  }\n\n  void apply(arith_operation_t op, const variable_t &x, const variable_t &y,\n             number_t k) override {\n    m_product.apply(op, x, y, k);\n    if (!Params::apply_reduction_only_add_constraint) {\n      reduce_variable(x);\n    }\n    CRAB_LOG(\"combined-domain\",\n             crab::outs() << x << \":=\" << y << op << k << \"=\" << *this << \"\\n\");\n  }\n\n  void backward_assign(\n      const variable_t &x, const linear_expression_t &e,\n      const reduced_numerical_domain_product2_t &invariant) override {\n    m_product.backward_assign(x, e, invariant.m_product);\n    if (!Params::apply_reduction_only_add_constraint) {\n      // reduce the variables in the right-hand side\n      for (auto const &v : e.variables())\n        reduce_variable(v);\n    }\n  }\n\n  void backward_apply(\n      arith_operation_t op, const variable_t &x, const variable_t &y,\n      number_t k,\n      const reduced_numerical_domain_product2_t &invariant) override {\n    m_product.backward_apply(op, x, y, k, invariant.m_product);\n    if (!Params::apply_reduction_only_add_constraint) {\n      // reduce the variables in the right-hand side\n      reduce_variable(y);\n    }\n  }\n\n  void backward_apply(\n      arith_operation_t op, const variable_t &x, const variable_t &y,\n      const variable_t &z,\n      const reduced_numerical_domain_product2_t &invariant) override {\n    m_product.backward_apply(op, x, y, z, invariant.m_product);\n    if (!Params::apply_reduction_only_add_constraint) {\n      // reduce the variables in the right-hand side\n      reduce_variable(y);\n      reduce_variable(z);\n    }\n  }\n\n  // cast operators\n\n  void apply(int_conv_operation_t op, const variable_t &dst,\n             const variable_t &src) override {\n    m_product.apply(op, dst, src);\n    if (!Params::apply_reduction_only_add_constraint) {\n      reduce_variable(dst);\n    }\n  }\n\n  // bitwise operators\n\n  void apply(bitwise_operation_t op, const variable_t &x, const variable_t &y,\n             const variable_t &z) override {\n    m_product.apply(op, x, y, z);\n    if (!Params::apply_reduction_only_add_constraint) {\n      reduce_variable(x);\n    }\n  }\n\n  void apply(bitwise_operation_t op, const variable_t &x, const variable_t &y,\n             number_t k) override {\n    m_product.apply(op, x, y, k);\n    if (!Params::apply_reduction_only_add_constraint) {\n      reduce_variable(x);\n    }\n  }\n\n  void select(const variable_t &lhs, const linear_constraint_t &cond,\n\t      const linear_expression_t &e1,  const linear_expression_t &e2) override {\n    m_product.select(lhs, cond, e1, e2);\n    if (!Params::apply_reduction_only_add_constraint) {\n      reduce_variable(lhs);\n    }\n  }\n  \n  /// reduced_numerical_domain_product2 implements only standard\n  /// abstract operations of a numerical domain so it is intended to be\n  /// used as a leaf domain in the hierarchy of domains.\n  BOOL_OPERATIONS_NOT_IMPLEMENTED(reduced_numerical_domain_product2_t)\n  ARRAY_OPERATIONS_NOT_IMPLEMENTED(reduced_numerical_domain_product2_t)\n  REGION_AND_REFERENCE_OPERATIONS_NOT_IMPLEMENTED(\n      reduced_numerical_domain_product2_t)\n\n  void rename(const variable_vector_t &from,\n              const variable_vector_t &to) override {\n    m_product.rename(from, to);\n  }\n\n  /* begin intrinsics operations */\n  void intrinsic(std::string name,\n\t\t const variable_or_constant_vector_t &inputs,\n                 const variable_vector_t &outputs) override {\n    m_product.intrinsic(name, inputs, outputs);\n  }\n\n  void backward_intrinsic(\n      std::string name,\n      const variable_or_constant_vector_t &inputs,\n      const variable_vector_t &outputs,\n      const reduced_numerical_domain_product2_t &invariant) override {\n    m_product.backward_intrinsic(name, inputs, outputs,\n\t\t\t\t invariant.m_product);\n  }\n  /* end intrinsics operations */\n\n  void forget(const variable_vector_t &variables) override {\n    m_product.forget(variables);\n  }\n\n  void project(const variable_vector_t &variables) override {\n    m_product.project(variables);\n  }\n\n  void expand(const variable_t &var, const variable_t &new_var) override {\n    m_product.expand(var, new_var);\n  }\n\n  void normalize() override { m_product.normalize(); }\n\n  void minimize() override { m_product.minimize(); }\n\n  void write(crab_os &o) const override { m_product.write(o); }\n\n  linear_constraint_system_t to_linear_constraint_system() const override {\n    return m_product.to_linear_constraint_system();\n  }\n\n  disjunctive_linear_constraint_system_t\n  to_disjunctive_linear_constraint_system() const override {\n    return m_product.to_disjunctive_linear_constraint_system();\n  }\n\n  std::string domain_name() const override {\n    const Domain1 &dom1 = m_product.first();\n    const Domain2 &dom2 = m_product.second();\n\n    std::string name =\n        \"ReducedProduct(\" + dom1.domain_name() + \",\" + dom2.domain_name() + \")\";\n    return name;\n  }\n\n}; // class reduced_numerical_domain_product2\n\n\ntemplate <typename Number, typename VariableName, typename Domain1,\n          typename Domain2>\nstruct abstract_domain_traits<\n    domain_product2<Number, VariableName, Domain1, Domain2>> {\n  using number_t = Number;\n  using varname_t = VariableName;\n};\n\ntemplate <typename Domain1, typename Domain2, class Params>\nstruct abstract_domain_traits<\n    reduced_numerical_domain_product2<Domain1, Domain2, Params>> {\n  using number_t = typename Domain1::number_t;\n  using varname_t = typename Domain1::varname_t;\n};\n\n} // end namespace domains\n} // namespace crab\n", "meta": {"hexsha": "c0857124cdcfd757d3d080451e266bff99c24d8a", "size": 48565, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/combined_domains.hpp", "max_stars_repo_name": "LinerSu/crab", "max_stars_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crab/domains/combined_domains.hpp", "max_issues_repo_name": "LinerSu/crab", "max_issues_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/crab/domains/combined_domains.hpp", "max_forks_repo_name": "LinerSu/crab", "max_forks_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8385939742, "max_line_length": 84, "alphanum_fraction": 0.6384433234, "num_tokens": 11195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.6261241702517976, "lm_q1q2_score": 0.410045410389194}}
{"text": "// MIT License\n//\n// Copyright (c) 2018 Lennart Braun\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <algorithm>\n#include <array>\n#include <cassert>\n#include <cstdint>\n#include <boost/asio.hpp>\n#include <botan/blake2b.h>\n#include <botan/hex.h>\n#include \"ot_co15.hpp\"\n#include \"util/threading.hpp\"\n\n\nOT_CO15::OT_CO15(Connection& connection) : connection_(connection)\n{\n}\n\n\nvoid OT_CO15::send_0(Sender_SharedState& state,\n                     std::array<uint8_t, curve25519_ge_byte_size>& message_out)\n{\n    // sample y <- Zp\n    curve25519::sc_random(state.y);\n\n    // S = y*G\n    curve25519::x25519_ge_scalarmult_base(&state.S, state.y);\n\n    curve25519::ge_p3_tobytes(message_out.data(), &state.S);\n}\n\nstd::pair<bytes_t, bytes_t> OT_CO15::send_1(const Sender_SharedState& state,\n                                            const std::array<uint8_t, curve25519_ge_byte_size>& message_in)\n{\n    curve25519::ge_p3 R;\n    // assert R in GG\n    if (!x25519_ge_frombytes_vartime(&R, message_in.data()))\n        std::terminate();\n\n    auto hash(Botan::Blake2b(128));\n\n    auto output = std::make_pair<>(bytes_t(16), bytes_t(16));\n    assert(output.first.size() == hash.output_length());\n    assert(output.second.size() == hash.output_length());\n\n    std::array<uint8_t, 3*curve25519_ge_byte_size> hash_input;\n    curve25519::ge_p3_tobytes(hash_input.data(), &state.S);\n    curve25519::ge_p3_tobytes(hash_input.data() + 32, &R);\n\n    // j = 0:\n    // y*R\n    curve25519::ge_p2 a_times_R_p2;\n    curve25519::x25519_ge_scalarmult(&a_times_R_p2, state.y, &R);\n    curve25519::x25519_ge_tobytes(hash_input.data() + 64, &a_times_R_p2);\n\n    // H(S, R, y*R)\n    hash.update(hash_input.data(), hash_input.size());\n    hash.final(output.first.data());\n\n\n    // j = 1:\n    // y*(R - S)\n    {\n        curve25519::ge_cached S_cached;\n        curve25519::x25519_ge_p3_to_cached(&S_cached, &state.S);\n\n        curve25519::ge_p1p1 R_minus_S_p1p1;\n        curve25519::x25519_ge_sub(&R_minus_S_p1p1, &R, &S_cached);\n\n        curve25519::ge_p3 R_minus_S_p3;\n        curve25519::x25519_ge_p1p1_to_p3(&R_minus_S_p3, &R_minus_S_p1p1);\n\n        curve25519::ge_p2 y_times_R_minus_S_p2;\n        curve25519::x25519_ge_scalarmult(&y_times_R_minus_S_p2, state.y, &R_minus_S_p3);\n        curve25519::x25519_ge_tobytes(hash_input.data() + 64, &y_times_R_minus_S_p2);\n\n    }\n\n    // H(S, R, y*(R - S))\n    hash.update(hash_input.data(), hash_input.size());\n    hash.final(output.second.data());\n\n    return output;\n}\n\nvoid OT_CO15::recv_0(Receiver_State& state, bool choice)\n{\n    state.choice = choice;\n    // sample b <- Zp\n    curve25519::sc_random(state.x);\n}\n\n\nvoid OT_CO15::recv_1(Receiver_SharedState& sstate,\n                     const std::array<uint8_t, curve25519_ge_byte_size>& message_in)\n{\n    // recv S\n    auto res = curve25519::x25519_ge_frombytes_vartime(&sstate.S, message_in.data());\n    // assert S in GG\n    if (res == 0)\n        std::terminate();\n}\n\n\nvoid OT_CO15::recv_2(Receiver_State& state, const Receiver_SharedState& sstate,\n                     std::array<uint8_t, curve25519_ge_byte_size>& message_out)\n{\n    curve25519::x25519_ge_scalarmult_base(&state.R, state.x);\n    // FIXME: not constant time\n    if (state.choice == 1)\n    {\n        curve25519::ge_p1p1 R_p1p1;\n        curve25519::ge_cached S_cached;\n        curve25519::x25519_ge_p3_to_cached(&S_cached, &sstate.S);\n        curve25519::x25519_ge_add(&R_p1p1, &state.R, &S_cached);\n        curve25519::x25519_ge_p1p1_to_p3(&state.R, &R_p1p1);\n    }\n\n    curve25519::ge_p3_tobytes(message_out.data(), &state.R);\n}\n\nbytes_t OT_CO15::recv_3(const Receiver_State& state, const Receiver_SharedState& sstate)\n{\n    // k_R = H_(S, R, y*S)\n\n    bytes_t hash_output(16);\n\n    std::array<uint8_t, 3*curve25519_ge_byte_size> hash_input;\n    curve25519::ge_p3_tobytes(hash_input.data(), &sstate.S);\n    curve25519::ge_p3_tobytes(hash_input.data() + 32, &state.R);\n\n    curve25519::ge_p2 y_times_S;\n    curve25519::x25519_ge_scalarmult(&y_times_S, state.x, &sstate.S);\n    curve25519::x25519_ge_tobytes(hash_input.data() + 64, &y_times_S);\n\n    auto hash(Botan::Blake2b(128));\n    assert(hash_output.size() == hash.output_length());\n    hash.update(hash_input.data(), hash_input.size());\n    hash.final(hash_output.data());\n\n    return hash_output;\n}\n\n\nstd::vector<std::pair<bytes_t, bytes_t>> OT_CO15::send(size_t number_ots)\n{\n    Sender_SharedState state;\n    std::array<uint8_t, curve25519_ge_byte_size> msg_s0;\n    std::vector<std::array<uint8_t, curve25519_ge_byte_size>> msgs_r1(number_ots);\n    std::vector<std::pair<bytes_t, bytes_t>> output(number_ots);\n\n    send_0(state, msg_s0);\n\n    auto fut_send_msg_s0 = connection_.async_send(msg_s0.data(), msg_s0.size());\n    auto fut_recv_msg_r1 = connection_.async_recv(reinterpret_cast<uint8_t*>(msgs_r1.data()), msgs_r1.size() * curve25519_ge_byte_size);\n\n    auto msg_r1_size = fut_recv_msg_r1.get();\n    assert(msg_r1_size == msgs_r1.size() * curve25519_ge_byte_size);\n\n    for (size_t i = 0; i < number_ots; ++i)\n    {\n        output[i] = send_1(state, msgs_r1[i]);\n    }\n\n    auto msg_s0_size = fut_send_msg_s0.get();\n    assert(msg_s0_size == msg_s0.size());\n\n    return output;\n}\n\nstd::vector<bytes_t> OT_CO15::recv(const std::vector<bool>& choices)\n{\n    auto number_ots = choices.size();\n    std::vector<Receiver_State> states(number_ots);\n    Receiver_SharedState sstate;\n    std::array<uint8_t, curve25519_ge_byte_size> msg_s0;\n    std::vector<std::array<uint8_t, curve25519_ge_byte_size>> msgs_r1(number_ots);\n    std::vector<bytes_t> output(number_ots);\n\n    auto fut_recv_msg_s0 = connection_.async_recv(msg_s0.data(), msg_s0.size());\n\n    for (size_t i = 0; i < number_ots; ++i)\n    {\n        recv_0(states[i], choices[i]);\n    }\n\n    auto msg_s0_size = fut_recv_msg_s0.get();\n    assert(msg_s0_size == msg_s0.size());\n\n    recv_1(sstate, msg_s0);\n\n    for (size_t i = 0; i < number_ots; ++i)\n    {\n        recv_2(states[i], sstate, msgs_r1[i]);\n    }\n\n    auto fut_send_msg_r1 = connection_.async_send(reinterpret_cast<uint8_t*>(msgs_r1.data()), msgs_r1.size() * curve25519_ge_byte_size);\n\n    for (size_t i = 0; i < number_ots; ++i)\n    {\n        output[i] = recv_3(states[i], sstate);\n    }\n\n    auto msg_r1_size = fut_send_msg_r1.get();\n    assert(msg_r1_size == msgs_r1.size() * curve25519_ge_byte_size);\n\n    return output;\n}\n\n\nstd::pair<bytes_t, bytes_t> OT_CO15::send()\n{\n    Sender_SharedState state;\n    std::array<uint8_t, curve25519_ge_byte_size> msg_s0;\n    std::array<uint8_t, curve25519_ge_byte_size> msg_r1;\n\n    send_0(state, msg_s0);\n    connection_.send(msg_s0.data(), msg_s0.size());\n    connection_.recv(msg_r1.data(), msg_r1.size());\n    return send_1(state, msg_r1);\n}\n\n\nbytes_t OT_CO15::recv(bool choice)\n{\n    Receiver_State state;\n    Receiver_SharedState sstate;\n    std::array<uint8_t, curve25519_ge_byte_size> msg_s0;\n    std::array<uint8_t, curve25519_ge_byte_size> msg_r1;\n\n    recv_0(state, choice);\n    connection_.recv(msg_s0.data(), msg_s0.size());\n    recv_1(sstate, msg_s0);\n    recv_2(state, sstate, msg_r1);\n    connection_.send(msg_r1.data(), msg_r1.size());\n    return recv_3(state, sstate);\n}\n\n\nstd::vector<std::pair<bytes_t, bytes_t>> OT_CO15::parallel_send(size_t number_ots, size_t number_threads, boost::asio::thread_pool& thread_pool)\n{\n    Sender_SharedState sstate;\n    std::array<uint8_t, curve25519_ge_byte_size> msg_s0;\n    std::vector<std::array<uint8_t, curve25519_ge_byte_size>> msgs_r1(number_ots);\n    std::vector<std::pair<bytes_t, bytes_t>> output(number_ots);\n\n    send_0(sstate, msg_s0);\n\n    auto fut_send_msg_s0 = connection_.async_send(msg_s0.data(), msg_s0.size());\n    auto fut_recv_msg_r1 = connection_.async_recv(reinterpret_cast<uint8_t*>(msgs_r1.data()), msgs_r1.size() * curve25519_ge_byte_size);\n\n    auto msg_r1_size = fut_recv_msg_r1.get();\n    assert(msg_r1_size == msgs_r1.size() * curve25519_ge_byte_size);\n\n    compute(thread_pool, number_ots, number_threads, [this, &sstate, &msgs_r1, &output](size_t index){ output[index] = send_1(sstate, msgs_r1[index]); });\n\n    auto msg_s0_size = fut_send_msg_s0.get();\n    assert(msg_s0_size == msg_s0.size());\n\n    return output;\n}\n\n\nstd::vector<bytes_t> OT_CO15::parallel_recv(const std::vector<bool>& choices, size_t number_threads, boost::asio::thread_pool& thread_pool)\n{\n    auto number_ots = choices.size();\n    std::vector<Receiver_State> states(number_ots);\n    Receiver_SharedState sstate;\n    std::array<uint8_t, curve25519_ge_byte_size> msg_s0;\n    std::vector<std::array<uint8_t, curve25519_ge_byte_size>> msgs_r1(number_ots);\n    std::vector<bytes_t> output(number_ots);\n\n    auto fut_recv_msg_s0 = connection_.async_recv(msg_s0.data(), msg_s0.size());\n\n    compute(thread_pool, number_ots, number_threads, [this, &states, &choices](size_t index){ recv_0(states[index], choices[index]); });\n\n    auto msg_s0_size = fut_recv_msg_s0.get();\n    assert(msg_s0_size == msg_s0.size());\n\n    recv_1(sstate, msg_s0);\n\n    compute(thread_pool, number_ots, number_threads, [this, &states, &sstate, &msgs_r1](size_t index){ recv_2(states[index], sstate, msgs_r1[index]); });\n\n    auto fut_send_msg_r1 = connection_.async_send(reinterpret_cast<uint8_t*>(msgs_r1.data()), msgs_r1.size() * curve25519_ge_byte_size);\n\n    compute(thread_pool, number_ots, number_threads, [this, &states, &sstate, &output](size_t index){ output[index] = recv_3(states[index], sstate); });\n\n    auto msg_r1_size = fut_send_msg_r1.get();\n    assert(msg_r1_size == msgs_r1.size() * curve25519_ge_byte_size);\n\n    return output;\n}\n", "meta": {"hexsha": "cba3cfe7d55ff1145bd01194b2d59c7221c4ee52", "size": 10573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ot/ot_co15.cpp", "max_stars_repo_name": "lenerd/libparty", "max_stars_repo_head_hexsha": "5afd551303dbb9141f722d3540a81946feedc6e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-06-06T21:44:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-06T21:44:34.000Z", "max_issues_repo_path": "src/ot/ot_co15.cpp", "max_issues_repo_name": "lenerd/libparty", "max_issues_repo_head_hexsha": "5afd551303dbb9141f722d3540a81946feedc6e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ot/ot_co15.cpp", "max_forks_repo_name": "lenerd/libparty", "max_forks_repo_head_hexsha": "5afd551303dbb9141f722d3540a81946feedc6e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8878205128, "max_line_length": 154, "alphanum_fraction": 0.6974368675, "num_tokens": 3063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8397339837155239, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.4100281607139131}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2014 Master IMAFA - Polytech'Nice Sophia - Université de Nice Sophia Antipolis\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/experimental/exoticoptions/analyticholderextensibleoptionengine.hpp>\n#include <ql/math/distributions/bivariatenormaldistribution.hpp>\n#include <ql/exercise.hpp>\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\n    AnalyticHolderExtensibleOptionEngine::AnalyticHolderExtensibleOptionEngine(\n             const boost::shared_ptr<GeneralizedBlackScholesProcess>& process)\n    : process_(process) {\n        registerWith(process_);\n    }\n\n    void AnalyticHolderExtensibleOptionEngine::calculate() const {\n        //Spot\n        Real S = process_->x0();\n        Real r = riskFreeRate();\n        Real b = r - dividendYield();\n        Real X1 = strike();\n        Real X2 = arguments_.secondStrike;\n        Time T2 = secondExpiryTime();\n        Time t1 = firstExpiryTime();\n        Real A = arguments_.premium;\n\n\n        Real z1 = this->z1();\n\n        Real z2 = this->z2();\n\n        Real rho = sqrt(t1 / T2);\n\n\n        boost::shared_ptr<PlainVanillaPayoff> payoff =\n            boost::dynamic_pointer_cast<PlainVanillaPayoff>(arguments_.payoff);\n\n        //QuantLib requires sigma * sqrt(T) rather than just sigma/volatility\n        Real vol = volatility();\n\n        //calculate dividend discount factor assuming continuous compounding (e^-rt)\n        DiscountFactor growth = dividendDiscount(t1);\n        //calculate payoff discount factor assuming continuous compounding\n        DiscountFactor discount = riskFreeDiscount(t1);\n        Real result = 0;\n        Real minusInf=-std::numeric_limits<Real>::infinity();\n\n        Real y1 = this->y1(payoff->optionType()),\n             y2 = this->y2(payoff->optionType());\n        if (payoff->optionType() == Option::Call) {\n            //instantiate payoff function for a call\n            boost::shared_ptr<PlainVanillaPayoff> vanillaCallPayoff =\n                boost::make_shared<PlainVanillaPayoff>(Option::Call, X1);\n            Real BSM = BlackScholesCalculator(vanillaCallPayoff, S, growth, vol*sqrt(t1), discount).value();\n            result = BSM\n                + S*exp((b - r)*T2)*M2(y1, y2, minusInf, z1, rho)\n                - X2*exp(-r*T2)*M2(y1 - vol*sqrt(t1), y2 - vol*sqrt(t1), minusInf, z1 - vol*sqrt(T2), rho)\n                - S*exp((b - r)*t1)*N2(y1, z2) + X1*exp(-r*t1)*N2(y1 - vol*sqrt(t1), z2 - vol*sqrt(t1))\n                - A*exp(-r*t1)*N2(y1 - vol*sqrt(t1), y2 - vol*sqrt(t1));\n        } else {\n            //instantiate payoff function for a call\n            boost::shared_ptr<PlainVanillaPayoff> vanillaPutPayoff =\n                boost::make_shared<PlainVanillaPayoff>(Option::Put, X1);\n            result = BlackScholesCalculator(vanillaPutPayoff, S, growth, vol*sqrt(t1), discount).value()\n                - S*exp((b - r)*T2)*M2(y1, y2, minusInf, -z1, rho)\n                + X2*exp(-r*T2)*M2(y1 - vol*sqrt(t1), y2 - vol*sqrt(t1), minusInf, -z1 + vol*sqrt(T2), rho)\n                + S*exp((b - r)*t1)*N2(z2, y2) - X1*exp(-r*t1)*N2(z2 - vol*sqrt(t1), y2 - vol*sqrt(t1))\n                - A*exp(-r*t1)*N2(y1 - vol*sqrt(t1), y2 - vol*sqrt(t1));\n        }\n        this->results_.value = result;\n    }\n\n    Real AnalyticHolderExtensibleOptionEngine::I1Call() const {\n        Real Sv = process_->x0();\n        Real A = arguments_.premium;\n\n        if(A==0)\n        {\n            return 0;\n        }\n        else\n        {\n            BlackScholesCalculator bs = bsCalculator(Sv, Option::Call);\n            Real ci = bs.value();\n            Real dc = bs.delta();\n\n            Real yi = ci - A;\n            //da/ds = 0\n            Real di = dc - 0;\n            Real epsilon = 0.001;\n\n            //Newton-Raphson process\n            while (std::fabs(yi) > epsilon){\n                Sv = Sv - yi / di;\n\n                bs = bsCalculator(Sv, Option::Call);\n                ci = bs.value();\n                dc = bs.delta();\n\n                yi = ci - A;\n                di = dc - 0;\n            }\n            return Sv;\n        }\n    }\n\n    Real AnalyticHolderExtensibleOptionEngine::I2Call() const {\n        Real Sv = process_->x0();\n        Real X1 = strike();\n        Real X2 = arguments_.secondStrike;\n        Real A = arguments_.premium;\n        Time T2 = secondExpiryTime();\n        Time t1 = firstExpiryTime();\n        Real r=riskFreeRate();\n\n        Real val=X1-X2*std::exp(-r*(T2-t1));\n        if(A< val){\n            return std::numeric_limits<Real>::infinity();\n        } else {\n            BlackScholesCalculator bs = bsCalculator(Sv, Option::Call);\n            Real ci = bs.value();\n            Real dc = bs.delta();\n\n            Real yi = ci - A - Sv + X1;\n            //da/ds = 1\n            Real di = dc - 1;\n            Real epsilon = 0.001;\n\n            //Newton-Raphson process\n            while (std::fabs(yi) > epsilon){\n                Sv = Sv - yi / di;\n\n                bs = bsCalculator(Sv, Option::Call);\n                ci = bs.value();\n                dc = bs.delta();\n\n                yi = ci - A - Sv + X1;\n                di = dc - 1;\n            }\n            return Sv;\n        }\n    }\n\n    Real AnalyticHolderExtensibleOptionEngine::I1Put() const {\n        Real Sv = process_->x0();\n        //Srtike\n        Real X1 = strike();\n        //Premium\n        Real A = arguments_.premium;\n\n        BlackScholesCalculator bs = bsCalculator(Sv, Option::Put);\n        Real pi = bs.value();\n        Real dc = bs.delta();\n\n        Real yi = pi - A + Sv - X1;\n        //da/ds = 1\n        Real di = dc - 1;\n        Real epsilon = 0.001;\n\n        //Newton-Raphson prosess\n        while (std::fabs(yi) > epsilon){\n            Sv = Sv - yi / di;\n\n            bs = bsCalculator(Sv, Option::Put);\n            pi = bs.value();\n            dc = bs.delta();\n\n            yi = pi - A + Sv - X1;\n            di = dc - 1;\n        }\n        return Sv;\n    }\n\n    Real AnalyticHolderExtensibleOptionEngine::I2Put() const {\n        Real Sv = process_->x0();\n        Real A = arguments_.premium;\n        if(A==0){\n            return std::numeric_limits<Real>::infinity();\n        }\n        else{\n            BlackScholesCalculator bs = bsCalculator(Sv, Option::Put);\n            Real pi = bs.value();\n            Real dc = bs.delta();\n\n            Real yi = pi - A;\n            //da/ds = 0\n            Real di = dc - 0;\n            Real epsilon = 0.001;\n\n            //Newton-Raphson prosess\n            while (std::fabs(yi) > epsilon){\n                Sv = Sv - yi / di;\n\n                bs = bsCalculator(Sv, Option::Put);\n                pi = bs.value();\n                dc = bs.delta();\n\n                yi = pi - A;\n                di = dc - 0;\n            }\n            return Sv;\n        }\n    }\n\n\n    BlackScholesCalculator AnalyticHolderExtensibleOptionEngine::bsCalculator(\n                                    Real spot, Option::Type optionType) const {\n        //Real spot = process_->x0();\n        Real vol;\n        DiscountFactor growth;\n        DiscountFactor discount;\n        Real X2 = arguments_.secondStrike;\n        Time T2 = secondExpiryTime();\n        Time t1 = firstExpiryTime();\n        Time t = T2 - t1;\n\n        //payoff\n        boost::shared_ptr<PlainVanillaPayoff > vanillaPayoff =\n            boost::make_shared<PlainVanillaPayoff>(optionType, X2);\n\n        //QuantLib requires sigma * sqrt(T) rather than just sigma/volatility\n        vol = volatility() * std::sqrt(t);\n        //calculate dividend discount factor assuming continuous compounding (e^-rt)\n        growth = dividendDiscount(t);\n        //calculate payoff discount factor assuming continuous compounding\n        discount = riskFreeDiscount(t);\n\n        BlackScholesCalculator bs(vanillaPayoff, spot, growth, vol, discount);\n        return bs;\n    }\n\n    Real AnalyticHolderExtensibleOptionEngine::M2(Real a, Real b, Real c, Real d, Real rho) const {\n        BivariateCumulativeNormalDistributionDr78 CmlNormDist(rho);\n        return CmlNormDist(b, d) - CmlNormDist(a, d) - CmlNormDist(b, c) + CmlNormDist(a,c);\n    }\n\n    Real AnalyticHolderExtensibleOptionEngine::N2(Real a, Real b) const {\n        CumulativeNormalDistribution  NormDist;\n        return NormDist(b) - NormDist(a);\n    }\n\n    Real AnalyticHolderExtensibleOptionEngine::strike() const {\n        boost::shared_ptr<PlainVanillaPayoff> payoff =\n            boost::dynamic_pointer_cast<PlainVanillaPayoff>(arguments_.payoff);\n        QL_REQUIRE(payoff, \"non-plain payoff given\");\n        return payoff->strike();\n    }\n\n    Time AnalyticHolderExtensibleOptionEngine::firstExpiryTime() const {\n        return process_->time(arguments_.exercise->lastDate());\n    }\n\n    Time AnalyticHolderExtensibleOptionEngine::secondExpiryTime() const {\n        return process_->time(arguments_.secondExpiryDate);\n    }\n\n    Volatility AnalyticHolderExtensibleOptionEngine::volatility() const {\n        return process_->blackVolatility()->blackVol(firstExpiryTime(), strike());\n    }\n    Rate AnalyticHolderExtensibleOptionEngine::riskFreeRate() const {\n        return process_->riskFreeRate()->zeroRate(firstExpiryTime(), Continuous,\n            NoFrequency);\n    }\n    Rate AnalyticHolderExtensibleOptionEngine::dividendYield() const {\n        return process_->dividendYield()->zeroRate(firstExpiryTime(),\n            Continuous, NoFrequency);\n    }\n\n    DiscountFactor AnalyticHolderExtensibleOptionEngine::dividendDiscount(Time t) const {\n        return process_->dividendYield()->discount(t);\n    }\n\n    DiscountFactor AnalyticHolderExtensibleOptionEngine::riskFreeDiscount(Time t) const {\n        return process_->riskFreeRate()->discount(t);\n    }\n\n    Real AnalyticHolderExtensibleOptionEngine::y1(Option::Type type) const {\n        Real S = process_->x0();\n        Real I2 = (type == Option::Call) ? I2Call() : I2Put();\n\n        Real b = riskFreeRate() - dividendYield();\n        Real vol = volatility();\n        Time t1 = firstExpiryTime();\n\n        return (log(S / I2) + (b + pow(vol, 2) / 2)*t1) / (vol*sqrt(t1));\n    }\n\n    Real AnalyticHolderExtensibleOptionEngine::y2(Option::Type type) const {\n        Real S = process_->x0();\n        Real I1 = (type == Option::Call) ? I1Call() : I1Put();\n\n        Real b = riskFreeRate() - dividendYield();\n        Real vol = volatility();\n        Time t1 = firstExpiryTime();\n\n        return (log(S / I1) + (b + pow(vol, 2) / 2)*t1) / (vol*sqrt(t1));\n    }\n\n    Real AnalyticHolderExtensibleOptionEngine::z1() const {\n        Real S = process_->x0();\n        Real X2 = arguments_.secondStrike;\n        Real b = riskFreeRate() - dividendYield();\n        Real vol = volatility();\n        Time T2 = secondExpiryTime();\n\n        return (log(S / X2) + (b + pow(vol, 2) / 2)*T2) / (vol*sqrt(T2));\n    }\n\n    Real AnalyticHolderExtensibleOptionEngine::z2() const {\n        Real S = process_->x0();\n        Real X1 = strike();\n\n        Real b = riskFreeRate() - dividendYield();\n        Real vol = volatility();\n        Time t1 = firstExpiryTime();\n\n        return (log(S / X1) + (b + pow(vol, 2) / 2)*t1) / (vol*sqrt(t1));\n    }\n\n}\n", "meta": {"hexsha": "440f8934473e765d5737b04a2054d0fdb9daf2d9", "size": 11760, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLib/ql/experimental/exoticoptions/analyticholderextensibleoptionengine.cpp", "max_stars_repo_name": "frannuca/quantlib", "max_stars_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantLib/ql/experimental/exoticoptions/analyticholderextensibleoptionengine.cpp", "max_issues_repo_name": "frannuca/quantlib", "max_issues_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/ql/experimental/exoticoptions/analyticholderextensibleoptionengine.cpp", "max_forks_repo_name": "frannuca/quantlib", "max_forks_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-24T04:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T04:54:18.000Z", "avg_line_length": 34.7928994083, "max_line_length": 108, "alphanum_fraction": 0.5761054422, "num_tokens": 3040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4100105008297031}}
{"text": "#include <cstdint>\n#include <cmath>\n#include <array>\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <iterator>\n#include <charconv>\n#include <random>\n#include <boost/container/flat_map.hpp>\n#include <boost/program_options.hpp>\n#include <omp.h>\n#include <nlohmann/json.hpp>\n#include <OpenImageIO/imageio.h>\n\n#define BRDF_SAMPLING_RES_THETA_H       90\n#define BRDF_SAMPLING_RES_THETA_D       90\n#define BRDF_SAMPLING_RES_PHI_D         360\n\n#define RED_SCALE (1.0/1500.0)\n#define GREEN_SCALE (1.15/1500.0)\n#define BLUE_SCALE (1.66/1500.0)\n\n\n// Read BRDF data\nbool read_brdf(const char *filename, double* &brdf)\n{\n\tFILE *f = fopen(filename, \"rb\");\n\tif (!f)\n\t\treturn false;\n\n\tint dims[3];\n\tfread(dims, sizeof(int), 3, f);\n\tint n = dims[0] * dims[1] * dims[2];\n\tif (n != BRDF_SAMPLING_RES_THETA_H *\n\t\t BRDF_SAMPLING_RES_THETA_D *\n\t\t BRDF_SAMPLING_RES_PHI_D / 2) \n\t{\n\t\tfprintf(stderr, \"Dimensions don't match\\n\");\n\t\tfclose(f);\n\t\treturn false;\n\t}\n\n\tbrdf = (double*) malloc (sizeof(double)*3*n);\n\tfread(brdf, sizeof(double), 3*n, f);\n\n\tfclose(f);\n\treturn true;\n}\n\n// Lookup theta_half index\n// This is a non-linear mapping!\n// In:  [0 .. pi/2]\n// Out: [0 .. 89]\ninline int theta_half_index(double theta_half)\n{\n\tif (theta_half <= 0.0)\n\t\treturn 0;\n\tdouble theta_half_deg = ((theta_half / (M_PI/2.0))*BRDF_SAMPLING_RES_THETA_H);\n\tdouble temp = theta_half_deg*BRDF_SAMPLING_RES_THETA_H;\n\ttemp = sqrt(temp);\n\tint ret_val = (int)temp;\n\tif (ret_val < 0) ret_val = 0;\n\tif (ret_val >= BRDF_SAMPLING_RES_THETA_H)\n\t\tret_val = BRDF_SAMPLING_RES_THETA_H-1;\n\treturn ret_val;\n}\n\n\n\n\ninline int theta_diff_index(double theta_diff)\n{\n\tint tmp = int(theta_diff / (M_PI * 0.5) * BRDF_SAMPLING_RES_THETA_D);\n\tif (tmp < 0)\n\t\treturn 0;\n\telse if (tmp < BRDF_SAMPLING_RES_THETA_D - 1)\n\t\treturn tmp;\n\telse\n\t\treturn BRDF_SAMPLING_RES_THETA_D - 1;\n}\n\ninline int phi_diff_index(double phi_diff)\n{\n\t// Because of reciprocity, the BRDF is unchanged under\n\t// phi_diff -> phi_diff + M_PI\n\tif (phi_diff < 0.0)\n\t\tphi_diff += M_PI;\n\n\t// In: phi_diff in [0 .. pi]\n\t// Out: tmp in [0 .. 179]\n\tint tmp = int(phi_diff / M_PI * BRDF_SAMPLING_RES_PHI_D / 2);\n\tif (tmp < 0)\t\n\t\treturn 0;\n\telse if (tmp < BRDF_SAMPLING_RES_PHI_D / 2 - 1)\n\t\treturn tmp;\n\telse\n\t\treturn BRDF_SAMPLING_RES_PHI_D / 2 - 1;\n}\n\ndouble gamma( double v ) {\n  return v / (v + 0.155 ) * 1.019;\n}\n\nint main( int argc, char *argv[] ) {\n  boost::program_options::options_description options(\"オプション\");\n  options.add_options()\n    (\"help,h\",    \"ヘルプを表示\")\n    (\"input,i\", boost::program_options::value<std::string>(), \"入力ファイル\")\n    (\"output,o\", boost::program_options::value<std::string>(), \"出力ファイル\");\n  boost::program_options::variables_map params;\n  boost::program_options::store( boost::program_options::parse_command_line( argc, argv, options ), params );\n  boost::program_options::notify( params );\n  if( params.count(\"help\") || !params.count(\"input\") || !params.count(\"output\") ) {\n    std::cout << options << std::endl;\n    return !params.count( \"help\" );\n  }\n  double* brdf;\n  if ( !read_brdf( params[ \"input\" ].as< std::string >().c_str(), brdf ) ) {\n    std::cerr <<  \"Unable to read \" << params[ \"input\" ].as< std::string >() << std::endl;\n    return 1;\n  }\n  double max = 0.0;\n  std::vector< float > v;\n  v.reserve( BRDF_SAMPLING_RES_THETA_D * BRDF_SAMPLING_RES_THETA_H * 3 );\n  double sum = 0.0;\n  for( unsigned int i = 0; i != BRDF_SAMPLING_RES_THETA_D; ++i ) {\n    double theta_diff = double( BRDF_SAMPLING_RES_THETA_D - i - 1 ) / double( BRDF_SAMPLING_RES_THETA_D ) * M_PI / 2.0;\n    for( unsigned int j = 0; j != BRDF_SAMPLING_RES_THETA_H; ++j ) {\n      double theta_half = double( j ) / double( BRDF_SAMPLING_RES_THETA_H ) * M_PI / 2.0;\n      int ind = phi_diff_index(M_PI/2) +\n        theta_diff_index(theta_diff) * BRDF_SAMPLING_RES_PHI_D / 2 +\n        theta_half_index(theta_half) * BRDF_SAMPLING_RES_PHI_D / 2 *\n        BRDF_SAMPLING_RES_THETA_D;\n      auto red_val = gamma( std::max( brdf[ind] * RED_SCALE, 0.0 ) );\n      auto green_val = gamma( std::max( brdf[ind + BRDF_SAMPLING_RES_THETA_H*BRDF_SAMPLING_RES_THETA_D*BRDF_SAMPLING_RES_PHI_D/2] * GREEN_SCALE, 0.0 ) );\n      auto blue_val = gamma( std::max( brdf[ind + BRDF_SAMPLING_RES_THETA_H*BRDF_SAMPLING_RES_THETA_D*BRDF_SAMPLING_RES_PHI_D] * BLUE_SCALE, 0.0 ) );\n      max = std::max( std::max( std::max( max, red_val ), green_val ), blue_val );\n      sum += red_val + green_val + blue_val;\n      v.push_back( red_val );\n      v.push_back( green_val );\n      v.push_back( blue_val );\n    }\n  }\n  double average = sum / ( BRDF_SAMPLING_RES_THETA_D * BRDF_SAMPLING_RES_THETA_H * 3 );\n  std::vector< uint8_t > image;\n  image.reserve( BRDF_SAMPLING_RES_THETA_D * BRDF_SAMPLING_RES_THETA_H * 3 );\n  for( unsigned int i = 0; i != BRDF_SAMPLING_RES_THETA_D; ++i ) {\n    for( unsigned int j = 0; j != BRDF_SAMPLING_RES_THETA_H; ++j ) {\n      int index = i * BRDF_SAMPLING_RES_THETA_H * 3 + j * 3;\n      std::cout << v[ index ]/(average*2) << \" \" << v[ index + 1 ]/(average*2) << \" \" << v[ index + 2 ]/(average*2) << std::endl;\n      image.push_back( uint8_t( std::min( std::max( v[ index ]/(average*2), 0.0  ), 1.0 ) * 255.0 ) );\n      image.push_back( uint8_t( std::min( std::max( v[ index + 1 ]/(average*2), 0.0  ), 1.0 ) * 255.0 ) );\n      image.push_back( uint8_t( std::min( std::max( v[ index + 2 ]/(average*2), 0.0  ), 1.0 ) * 255.0 ) );\n    }\n  }\n  using namespace OIIO_NAMESPACE;\n  ImageOutput *out = ImageOutput::create( params[ \"output\" ].as< std::string >() );\n  if ( !out ) {\n    std::cerr << \"Unable to open output file\" << std::endl;\n    return -1;\n  }\n  ImageSpec spec ( BRDF_SAMPLING_RES_THETA_H, BRDF_SAMPLING_RES_THETA_D, 3, TypeDesc::UINT8);\n  out->open( params[ \"output\" ].as< std::string >(), spec );\n  out->write_image( TypeDesc::UINT8, image.data() );\n  out->close();\n  return 0;\n}\n\n\n", "meta": {"hexsha": "6245c3916527d7df16f05bc709cf1eb245a8316f", "size": 5813, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/brdf2image.cpp", "max_stars_repo_name": "Fadis/shader-samples-2020", "max_stars_repo_head_hexsha": "916554161f63f62b33c85ffc8731ad003ef6cccb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-02-23T18:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T17:13:22.000Z", "max_issues_repo_path": "src/brdf2image.cpp", "max_issues_repo_name": "Fadis/shader-samples-2020", "max_issues_repo_head_hexsha": "916554161f63f62b33c85ffc8731ad003ef6cccb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/brdf2image.cpp", "max_forks_repo_name": "Fadis/shader-samples-2020", "max_forks_repo_head_hexsha": "916554161f63f62b33c85ffc8731ad003ef6cccb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9941520468, "max_line_length": 153, "alphanum_fraction": 0.6585239979, "num_tokens": 1919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.41001050082970303}}
{"text": "/*  Copyright (c) 2013, Abdullah A. Hassan <voodooattack@hotmail.com>\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n *  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n *\n *  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided with the distribution.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n *  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n *  OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n *  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef NOISEMODULES_H\n#define NOISEMODULES_H\n\n#include \"config.hpp\"\n\n#ifdef NOISE_DIR_IS_LIBNOISE\n#include <libnoise/noise.h>\n#else\n#include <noise/noise.h>\n#endif\n\n#include <boost/multi_array.hpp>\n\nnamespace ADWIF\n{\n  class HeightMapModule: public noise::module::Module\n  {\n  public:\n    inline static double cubicInterpolate (const double p[4], double x) {\n      return p[1] + 0.5 * x*(p[2] - p[0] + x*(2.0*p[0] - 5.0*p[1] +\n      4.0*p[2] - p[3] + x*(3.0*(p[1] - p[2]) + p[3] - p[0])));\n    }\n\n    inline static double bicubicInterpolate (const double p[4][4], double x, double y) {\n      double arr[4];\n      arr[0] = cubicInterpolate(p[0], y);\n      arr[1] = cubicInterpolate(p[1], y);\n      arr[2] = cubicInterpolate(p[2], y);\n      arr[3] = cubicInterpolate(p[3], y);\n      return cubicInterpolate(arr, x);\n    }\n\n    HeightMapModule(const boost::multi_array<double, 2> & heightMap,\n                    int cellSizeX, int cellSizeY): Module(0), myHeightmap(heightMap),\n                    myCellSizeX(cellSizeX), myCellSizeY(cellSizeY) { }\n\n    virtual int GetSourceModuleCount() const { return 0; }\n\n    virtual double GetValue(double x, double y, double z) const;\n\n    int myCellSizeX, myCellSizeY;\n    const boost::multi_array<double, 2> myHeightmap;\n  };\n\n}\n\n#endif // NOISEMODULES_H\n", "meta": {"hexsha": "8b41b19ac97a3ced2fbe214a0efc6797ace80cce", "size": 2688, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "noisemodules.hpp", "max_stars_repo_name": "voodooattack/ADWIF", "max_stars_repo_head_hexsha": "5267400362f66986ab138e376807720584f52811", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-05-24T17:51:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-07T09:33:35.000Z", "max_issues_repo_path": "noisemodules.hpp", "max_issues_repo_name": "voodooattack/ADWIF", "max_issues_repo_head_hexsha": "5267400362f66986ab138e376807720584f52811", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "noisemodules.hpp", "max_forks_repo_name": "voodooattack/ADWIF", "max_forks_repo_head_hexsha": "5267400362f66986ab138e376807720584f52811", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-27T14:47:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T05:39:56.000Z", "avg_line_length": 40.1194029851, "max_line_length": 146, "alphanum_fraction": 0.7072172619, "num_tokens": 688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.40997793859819387}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2015 Peter Caspers\n Copyright (C) 2015 Roland Lichters\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/experimental/models/betaetacore.hpp>\n\n#include <ql/errors.hpp>\n#include <ql/math/modifiedbessel.hpp>\n#include <ql/math/integrals/gausslobattointegral.hpp>\n#include <ql/math/integrals/segmentintegral.hpp>\n#include <ql/math/interpolations/bilinearinterpolation.hpp>\n#include <ql/math/interpolations/bicubicsplineinterpolation.hpp>\n#include <ql/methods/finitedifferences/meshers/concentrating1dmesher.hpp>\n\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/make_shared.hpp>\n\n#include <iostream>\n\nnamespace QuantLib {\n\nBetaEtaCore::BetaEtaCore(const Array &times, const Array &alpha,\n                         const Array &kappa, const Real &beta, const Real &eta)\n    : times_(times), alpha_(alpha), kappa_(kappa), beta_(beta), eta_(eta),\n      ghPoints_(8), prob_y_0_cutoff(1E-6), kappa_cutoff(1E-6) {\n\n    QL_REQUIRE(beta > 0.0, \"beta (\" << beta << \") must be positive\");\n    QL_REQUIRE(eta >= 0.0 && eta <= 1.0, \" eta (\" << eta\n                                                  << \") must be in [0,1]\");\n    QL_REQUIRE(alpha.size() == times.size() + 1,\n               \"alpha size (\" << alpha.size()\n                              << \") must be equal to times size (\"\n                              << times.size() << \") plus one\");\n    QL_REQUIRE(kappa.size() == 1 || kappa.size() == times.size() + 1,\n               \"kappa size (\" << kappa.size()\n                              << \") must be equal to times size (\"\n                              << times.size() << \") plus one or equal to one\");\n    for (Size i = 0; i < times.size(); ++i) {\n        QL_REQUIRE(times[i] > 0.0, \"time #\" << i << \" (\" << times[i]\n                                            << \") must be positive\");\n        if (i < times.size() - 1) {\n            QL_REQUIRE(times[i] < times[i + 1],\n                       \"times must be strictly increasing, #\"\n                           << i << \" and #\" << (i + 1) << \" are \" << times[i]\n                           << \" and \" << times[i + 1] << \" respectively\");\n        }\n    }\n\n    // integrator and fallback to compute M directly in terms of x\n    integrator_ = boost::make_shared<GaussLobattoIntegral>(10000, 1E-8, 1E-8);\n    integrator2_ = boost::make_shared<SegmentIntegral>(250);\n\n    // integrator to compute M for case eta = 1\n    ghIntegrator_ = boost::make_shared<GaussHermiteIntegration>(ghPoints_);\n\n    // integrator and fallback to tabulate M\n    preIntegrator_ =\n        boost::make_shared<GaussLobattoIntegral>(10000, 1E-8, 1E-8);\n    preIntegrator2_ = boost::make_shared<SegmentIntegral>(250);\n\n    // tabulation data\n    etaSize_ = detail::eta_pre_size;\n    uSize_ = detail::u_pre_size;\n    SuSize_ = detail::Su_pre_size;\n    vSize_ = detail::v_pre_size;\n    y0Size_ = detail::y0_pre_size;\n\n    eta_pre_ = std::vector<Real>(detail::eta_pre, detail::eta_pre + etaSize_);\n    u_pre_ = std::vector<Real>(detail::u_pre, detail::u_pre + uSize_);\n    Su_pre_ = std::vector<Real>(detail::Su_pre, detail::Su_pre + SuSize_);\n    v_pre_ = std::vector<Real>(detail::v_pre, detail::v_pre + vSize_);\n    y0_pre_ = std::vector<Real>(detail::y0_pre, detail::y0_pre + y0Size_);\n\n    // interpolation of tabulated data\n    for (Size i = 0; i < etaSize_; ++i) {\n        boost::shared_ptr<Matrix> zTmp =\n            boost::make_shared<Matrix>(Su_pre_.size(), u_pre_.size());\n        boost::shared_ptr<Matrix> z2Tmp =\n            boost::make_shared<Matrix>(v_pre_.size(), y0_pre_.size());\n        for (Size uu = 0; uu < uSize_; ++uu)\n            for (Size vv = 0; vv < SuSize_; ++vv)\n                (*zTmp)[vv][uu] = detail::M_pre[i][uu][vv];\n        for (Size vv = 0; vv < vSize_; ++vv)\n            for (Size yy = 0; yy < y0Size_; ++yy)\n                (*z2Tmp)[yy][vv] = detail::p_pre[i][yy][vv];\n        M_datasets_.push_back(zTmp);\n        p_datasets_.push_back(z2Tmp);\n        boost::shared_ptr<BilinearInterpolation> tmp =\n            boost::make_shared<BilinearInterpolation>(\n                u_pre_.begin(), u_pre_.end(), Su_pre_.begin(), Su_pre_.end(),\n                *(M_datasets_[i]));\n        boost::shared_ptr<BilinearInterpolation> tmp2 =\n            boost::make_shared<BilinearInterpolation>(\n                v_pre_.begin(), v_pre_.end(), y0_pre_.begin(), y0_pre_.end(),\n                *(p_datasets_[i]));\n        tmp->enableExtrapolation();\n        tmp2->enableExtrapolation();\n        M_surfaces_.push_back(tmp);\n        p_surfaces_.push_back(tmp2);\n    }\n};\n\n// integrand to compute M directly in terms of x\nclass BetaEtaCore::mIntegrand1 {\n    const BetaEtaCore *model_;\n    const Real t0_, x0_, t_;\n\n  public:\n    mIntegrand1(const BetaEtaCore *model, const Real t0, const Real x0,\n                const Real t)\n        : model_(model), t0_(t0), x0_(x0), t_(t) {}\n    Real operator()(Real x) const {\n        return model_->p(t0_, x0_, t_, x) *\n               exp(-model_->lambda(t_) * (x - x0_));\n    }\n};\n\n// integrand to compute prob_y_0 (directly in terms of x, eta < 0.5)\nclass BetaEtaCore::pIntegrand1 {\n    const BetaEtaCore *model_;\n    const Real t0_, x0_, t_;\n\n  public:\n    pIntegrand1(const BetaEtaCore *model, const Real t0, const Real x0,\n                const Real t)\n        : model_(model), t0_(t0), x0_(x0), t_(t) {}\n    Real operator()(Real x) const { return model_->p(t0_, x0_, t_, x); }\n};\n\n// integrand to precompute M, 0 < eta < 1, eta != 0.5\nclass BetaEtaCore::mIntegrand2 {\n    const BetaEtaCore *model_;\n    const Real S_, u0_;\n\n  public:\n    mIntegrand2(const BetaEtaCore *model, const Real S, const Real u0)\n        : model_(model), S_(S), u0_(u0) {}\n    Real operator()(Real u) const {\n        if (close(u, 0))\n            return 0.0;\n        Real eta = model_->eta();\n        return model_->p_y_core1(\n                   S_ * std::pow(1.0 - eta, 2.0 * eta) *\n                       std::pow(u0_, 2.0 - 2.0 * eta),\n                   std::pow(u0_, 1.0 - eta) * std::pow(1.0 - eta, eta - 1.0),\n                   std::pow(u, 1.0 - eta) * std::pow(1.0 - eta, eta - 1.0),\n                   eta) *\n               exp(-(u - u0_));\n    }\n};\n\n// integrand to precompute prob_y_0 (eta < 0.5)\nclass BetaEtaCore::pIntegrand2 {\n    const BetaEtaCore *model_;\n    const Real v_, y0_;\n\n  public:\n    pIntegrand2(const BetaEtaCore *model, const Real v, const Real y0)\n        : model_(model), v_(v), y0_(y0) {}\n    Real operator()(Real y) const {\n        return model_->p_y_core0(v_, y0_, y, model_->eta());\n    }\n};\n\n// integrand to compute M, eta = 1\nclass BetaEtaCore::mIntegrand3 {\n    const BetaEtaCore *model_;\n    const Real v_, y0_, lambda_;\n\n  public:\n    mIntegrand3(const BetaEtaCore *model, const Real v, const Real y0,\n                const Real lambda)\n        : model_(model), v_(v), y0_(y0), lambda_(lambda) {}\n    Real operator()(Real z) const {\n        Real beta = model_->beta();\n        Real y = M_SQRT2 * std::sqrt(v_) * z + y0_ - beta * v_ / 2.0;\n        return exp(-lambda_ * (exp(beta * y) - exp(beta * y0_)) / beta) *\n               exp(-z * z);\n    }\n};\n\nconst Real BetaEtaCore::M(const Time t0, const Real x0, const Real t,\n                          const bool useTabulation) const {\n\n    // since we are assuming a reflecting barrier we can\n    // return M = 0 for all eta when y is negative or zero\n    if (x0 <= -1.0 / beta_)\n        return 0.0;\n\n    Real lambda = this->lambda(t);\n    Real v = this->tau(t0, t);\n\n    // for zero volatility we obviously have M = 0\n    if (close(v, 0.0))\n        return 0.0;\n\n    // without the reflecting barrier at y=0 we could write\n    // M = 0.5 *lambda * lambda * v for eta = 0\n    // with the reflecting barrier assumed here, we do not\n    // have a closed form solution\n\n    if (close(eta_, 0.5)) {\n        return M_eta_05(t0, x0, t);\n    }\n    if (close(eta_, 1.0)) {\n        return M_eta_1(t0, x0, t);\n    }\n\n    Real result;\n    if (useTabulation) {\n        result = M_tabulated(t0, x0, t);\n    } else {\n        Real s = std::sqrt(tau(t0, t));\n        if (close(s, 0.0))\n            return 0.0;\n        mIntegrand1 in(this, t0, x0, t);\n        std::pair<Real, Real> d = detail::domain(\n            in, x0, 1E-10, 1E-12, 1E-6, 1.1, -1.0 / beta_, QL_MAX_REAL);\n        Real a = d.first;\n        Real b = d.second;\n        try {\n            result = std::log(integrator_->operator()(in, a, b));\n        } catch (...) {\n            try {\n                result = std::log(integrator2_->operator()(in, a, b));\n            } catch (...) {\n                QL_FAIL(\"could not compute M(\" << t0 << \",\" << x0 << \",\" << t\n                                               << \"), tried integration over \"\n                                               << a << \"...\" << b);\n            }\n        }\n    }\n\n    Real singularProb = prob_y_0(t0, x0, t, useTabulation);\n    Real singularTerm = 0.0;\n    singularTerm = singularProb * exp(-lambda * (-1.0 / beta_ - x0));\n\n    // only take the singular term into account if numerically significant\n    if (singularTerm > std::exp(result) * QL_EPSILON) {\n        result = std::log(std::exp(result) + singularTerm);\n    }\n\n    return result;\n};\n\nconst Real BetaEtaCore::M_eta_1(const Real t0, const Real x0,\n                                const Real t) const {\n    if (x0 < -1.0 / beta_)\n        return 0.0;\n    Real lambda = this->lambda(t);\n\n    Real y0 = y(x0, 1.0);\n    Real v = this->tau(t0, t);\n    Real result = M_1_SQRTPI *\n                  ghIntegrator_->operator()(mIntegrand3(this, v, y0, lambda));\n    return std::log(result);\n}\n\nconst Real BetaEtaCore::M_eta_05(const Real t0, const Real x0,\n                                 const Real t) const {\n    if (x0 < -1.0 / beta_)\n        return 0.0;\n    Real lambda = this->lambda(t);\n    Real v = this->tau(t0, t);\n    return (1.0 + beta_ * x0) * lambda * lambda * v /\n           (2.0 + beta_ * lambda * v);\n}\n\nconst Real BetaEtaCore::M_tabulated(const Real t0, const Real x0,\n                                    const Real t) const {\n\n    Real vraw = this->tau(t0, t);\n    Real lambda = this->lambda(t);\n\n    if (close(eta_, 0.5) || close(eta_, 1.0)) {\n        return M(t0, x0, t);\n    }\n\n    Real u0 = lambda / beta_ * std::fabs(1.0 + beta_ * x0);\n    Real Su = vraw * beta_ * beta_ /\n              std::pow(1.0 + beta_ * x0, 2.0 - 2.0 * eta_) *\n              std::pow(u0, 2.0 - 0.5 * eta_);\n\n    int etaIdx = std::upper_bound(eta_pre_.begin(), eta_pre_.end(), eta_) -\n                 eta_pre_.begin();\n\n    Real eta_weight_1 =\n        (etaIdx < static_cast<int>(eta_pre_.size()) ? eta_pre_[etaIdx] - eta_\n                                                    : 1.0 - eta_) /\n        (etaIdx < static_cast<int>(eta_pre_.size())\n             ? (eta_pre_[etaIdx] - eta_pre_[etaIdx - 1])\n             : (1.0 - eta_pre_[etaIdx - 1]));\n\n    Real eta_weight_2 = (eta_ - eta_pre_[etaIdx - 1]) /\n                        (etaIdx < static_cast<int>(eta_pre_.size())\n                             ? (eta_pre_[etaIdx] - eta_pre_[etaIdx - 1])\n                             : (1.0 - eta_pre_[etaIdx - 1]));\n\n    Real result_eta_lower = M_surfaces_[etaIdx - 1]->operator()(u0, Su);\n\n    Real result_eta_higher;\n    if (etaIdx < static_cast<int>(eta_pre_.size())) {\n        result_eta_higher = M_surfaces_[etaIdx]->operator()(u0, Su);\n    } else {\n        result_eta_higher = M_eta_1(t0, x0, t);\n    }\n\n    Real result =\n        (result_eta_lower * eta_weight_1 + result_eta_higher * eta_weight_2);\n\n    if (u0 > u_pre_.back() || Su > Su_pre_.back())\n        QL_FAIL(\"tabulated value lookup (\"\n                << u0 << \",\" << Su\n                << \") would require extrapolation, bounds are u0_max=\"\n                << u_pre_.back() << \" and Su_max=\" << Su_pre_.back());\n\n    return result;\n}\n\nconst Real BetaEtaCore::M(const Real u0, const Real Su) const {\n    Real res;\n    if (close(Su, 0.0)) {\n        res = 1.0;\n    } else {\n        QL_REQUIRE(!close(eta_, 1.0), \"M(u0,Su) is only defined for eta < 1\");\n        mIntegrand2 ig(this, Su / std::pow(u0, 2.0 - 0.5 * eta_), u0);\n        std::pair<Real, Real> d =\n            detail::domain(ig, u0, 1E-10, 1E-12, 1E-6, 1.1, 1E-10, QL_MAX_REAL);\n        try {\n            res = preIntegrator_->operator()(ig, d.first, d.second);\n        } catch (...) {\n            try {\n                res = preIntegrator2_->operator()(ig, d.first, d.second);\n            } catch (...) {\n                QL_FAIL(\"could not compute M(\" << u0 << \",\" << Su\n                                               << \"), tried integration over \"\n                                               << d.first << \"...\" << d.second);\n            }\n        }\n    }\n    Real a = close(res, 0.0) ? -50.0 : std::log(res);\n    return a;\n}\n\nconst Real BetaEtaCore::p_y_core0(const Real v, const Real y0, const Real y,\n                                  const Real eta) const {\n    QL_REQUIRE(!close(eta, 1.0), \"eta must not be one in p_y_core0\");\n    if (close(y, 0.0) || close(y0, 0.0)) // i.e. x, x0 = -1/beta\n        return 0.0;\n    Real nu = 1.0 / (2.0 - 2.0 * eta);\n    // 0.0 <= eta < 0.5\n    if (eta < 0.5) {\n        return std::pow(y0 / y, nu) * y / v *\n               modifiedBesselFunction_i_exponentiallyWeighted(-nu, y0 * y / v) *\n               exp(-(y - y0) * (y - y0) / (2.0 * v));\n    }\n    // 0.5 <= eta < 1.0\n    return std::pow(y0 / y, nu) * y / v *\n           modifiedBesselFunction_i_exponentiallyWeighted(nu, y0 * y / v) *\n           exp(-(y - y0) * (y - y0) / (2.0 * v));\n}\n\nconst Real BetaEtaCore::p_y_core1(const Real v, const Real y0, const Real y,\n                                  const Real eta) const {\n    QL_REQUIRE(!close(eta, 1.0), \"eta must not be one in p_y_core1\");\n    return p_y_core0(v, y0, y, eta) * std::pow(y, eta / (eta - 1.0));\n}\n\nconst Real BetaEtaCore::p_y(const Real v, const Real y0, const Real y,\n                            const Real eta) const {\n    // eta = 1.0\n    if (close(eta, 1.0)) {\n        return exp(-beta_ * y) / std::sqrt(2.0 * M_PI * v) *\n               exp(-0.5 * (y - y0 + 0.5 * beta_ * v) *\n                   (y - y0 + 0.5 * beta_ * v) / v);\n    }\n    // eta < 1.0\n    return p_y_core1(v, y0, y, eta) * std::pow(1.0 - eta, eta / (eta - 1.0)) *\n           std::pow(beta_, eta / (eta - 1.0));\n}\n\nconst Real BetaEtaCore::p(const Time t0, const Real x0, const Real t,\n                          const Real x) const {\n    if (x <= -1.0 / beta_)\n        return 0.0;\n    // to avoid numerical instabilities when eta is close to\n    // but not equal to one we interpolate the density between the largest\n    // stable value for eta and one. Since the tabulation should be\n    // stable w.r.t. the spanned eta grid, we use the largest grid value\n    // from there as the cutoff value (which would typically be something\n    // close to 0.99).\n    Real v = this->tau(t0, t);\n    if (eta_ <= eta_pre_.back()) {\n        Real y0 = this->y(x0, eta_);\n        Real y = this->y(x, eta_);\n        return p_y(v, y0, y, eta_);\n    } else {\n        Real y0a = this->y(x0, eta_pre_.back());\n        Real ya = this->y(x, eta_pre_.back());\n        Real y0b = this->y(x0, 1.0);\n        Real yb = this->y(x, 1.0);\n        return 0.5 * (p_y(v, y0a, ya, eta_pre_.back()) + p_y(v, y0b, yb, 1.0));\n    }\n};\n\nconst Real BetaEtaCore::prob_y_0(const Real v, const Real y0) const {\n    if (close(v, 0.0) || eta_ > eta_pre_.back())\n        return 0.0;\n    if (eta_ >= 0.5) {\n        Real nu = 1.0 / (2.0 - 2.0 * eta_);\n        Real res = boost::math::gamma_q(nu, y0 * y0 / (2.0 * v));\n        return res;\n    }\n    // eta < 0.5\n    pIntegrand2 inC(this, v, y0);\n    std::pair<Real, Real> d =\n        detail::domain(inC, y0, 1E-10, 1E-12, 1E-6, 1.1, 0.0, QL_MAX_REAL);\n    Real a = d.first;\n    Real b = d.second;\n    Real result;\n    try {\n        result = 1.0 - integrator_->operator()(inC, a, b);\n    } catch (...) {\n        try {\n            result = 1.0 - integrator2_->operator()(inC, a, b);\n        } catch (...) {\n            QL_FAIL(\"could not compute prob_y_0(\"\n                    << v << \",\" << y0 << \"), tried integration over \" << a\n                    << \"...\" << b);\n        }\n    }\n    return result;\n}\n\nconst Real BetaEtaCore::prob_y_0_tabulated(const Real v, const Real y0) const {\n    if (close(v, 0.0) || eta_ > eta_pre_.back())\n        return 0.0;\n    int etaIdx = std::upper_bound(eta_pre_.begin(), eta_pre_.end(), eta_) -\n                 eta_pre_.begin();\n\n    // weight formulas are more general than needed because\n    // etaIdx < eta_pre_.size() by the condition above\n    Real eta_weight_1 =\n        (etaIdx < static_cast<int>(eta_pre_.size()) ? eta_pre_[etaIdx] - eta_\n                                                    : 1.0 - eta_) /\n        (etaIdx < static_cast<int>(eta_pre_.size())\n             ? (eta_pre_[etaIdx] - eta_pre_[etaIdx - 1])\n             : (1.0 - eta_pre_[etaIdx - 1]));\n\n    Real eta_weight_2 = (eta_ - eta_pre_[etaIdx - 1]) /\n                        (etaIdx < static_cast<int>(eta_pre_.size())\n                             ? (eta_pre_[etaIdx] - eta_pre_[etaIdx - 1])\n                             : (1.0 - eta_pre_[etaIdx - 1]));\n\n    Real result_eta_lower = p_surfaces_[etaIdx - 1]->operator()(v, y0);\n    Real result_eta_higher = p_surfaces_[etaIdx]->operator()(v, y0);\n    Real result =\n        (result_eta_lower * eta_weight_1 + result_eta_higher * eta_weight_2);\n\n    // if (v > v_pre_.back() || y0 > y0_pre_.back())\n    //     QL_FAIL(\"tabulated value lookup (\"\n    //             << v << \",\" << y0\n    //             << \") would require extrapolation, bounds are v_max=\"\n    //             << v_pre_.back() << \" and y0_max=\" << y0_pre_.back());\n\n    return result;\n}\n\nconst Real BetaEtaCore::prob_y_0(const Time t0, const Real x0, const Time t,\n                                 bool useTabulation) const {\n    Real v = tau(t0, t);\n    Real y0 = y(x0, eta_);\n    Real result;\n    if (useTabulation) {\n        result = prob_y_0_tabulated(v, y0);\n    } else {\n        result = prob_y_0(v, y0);\n    }\n    // TODO ...\n    if(result < prob_y_0_cutoff)\n        result = 0.0;\n    return result;\n};\n\nnamespace detail {\n\nconst void\nbetaeta_tabulate(betaeta_tabulation_type type, std::ostream &out,\n                 const Real eta_min, const Real eta_max, const Real u0_min,\n                 const Real u0_max, const Real Su_min, const Real Su_max,\n                 const Size u_size, const Size Su_size, const Size eta_size,\n                 const Real c_u, const Real density_u, const Real c_Su,\n                 const Real density_Su, const Real c_e, const Real density_e) {\n\n    Concentrating1dMesher um(u0_min, u0_max, u_size,\n                             std::make_pair(c_u, density_u), true);\n    Concentrating1dMesher sum(Su_min, Su_max, Su_size,\n                              std::make_pair(c_Su, density_Su), true);\n    Concentrating1dMesher em(eta_min, eta_max, eta_size,\n                             std::make_pair(c_e, density_e), true);\n\n    out.precision(8);\n    if (type == Cpp_M || type == Cpp_p) {\n\n        out << \"/* -*- mode: c++; tab-width: 4; indent-tabs-mode:\"\n            << \"nil; c-basic-offset: 4 -*- */\\n\"\n            << \"\\n \"\n            << \"/*\\n\"\n            << \" Copyright (C) 2015 Peter Caspers\\n\"\n            << \" Copyright (C) 2015 Roland Lichters\\n\"\n            << \"\\n\"\n            << \" This file is part of QuantLib, a \"\n               \"free-software/open-source \"\n               \"library\\n\"\n            << \" for financial quantitative analysts and developers - \"\n               \"http://quantlib.org/\\n\"\n            << \"\\n\"\n            << \" QuantLib is free software: you can redistribute it and/or \"\n               \"modify it\\n\"\n            << \" under the terms of the QuantLib license.  You should have \"\n               \"received a\\n\"\n            << \" copy of the license along with this program; if not, \"\n               \"please \"\n               \"email\\n\"\n            << \" <quantlib-dev@lists.sf.net>. The license is also \"\n               \"available \"\n               \"online at\\n\"\n            << \" <http://quantlib.org/license.shtml>.\\n\"\n            << \"\\n\"\n            << \" This program is distributed in the hope that it will be \"\n               \"useful, but WITHOUT\\n\"\n            << \" ANY WARRANTY; without even the implied warranty of \"\n               \"MERCHANTABILITY or FITNESS\\n\"\n            << \" FOR A PARTICULAR PURPOSE.  See the license for more \"\n               \"details.\\n\"\n            << \"*/\\n\\n\";\n\n        out << \"// this file was generated by \"\n               \"QuantLib::detail::betaeta_tabulate\\n\"\n               \"// using the following parameters:\\n\";\n        if (type == Cpp_M) {\n            out << \"// u0_min = \" << u0_min << \" u0_max = \" << u0_max << \"\\n\";\n            out << \"// Su_min = \" << Su_min << \" Su_max = \" << Su_max << \"\\n\";\n            out << \"// u_size = \" << u_size << \" Su_size = \" << Su_size\n                << \" eta_size = \" << eta_size << \"\\n\";\n            out << \"// c_u = \" << c_u << \" density_u = \" << density_u << \"\\n\";\n            out << \"// c_Su = \" << c_Su << \" density_Su = \" << density_Su\n                << \"\\n\";\n            out << \"// c_e = \" << c_e << \" density_e = \" << density_e << \"\\n\\n\";\n            out << \"namespace QuantLib {\\n\"\n                << \"namespace detail {\\n\\n\";\n            out << \"extern \\\"C\\\" const double eta_pre[] = {\";\n            for (Size i = 0; i < em.size() - 1; ++i)\n                out << em.location(i) << (i < em.size() - 2 ? \",\" : \"};\\n\\n\");\n            out << \"extern \\\"C\\\" const double u_pre[] = {\";\n            for (Size i = 0; i < um.size(); ++i)\n                out << um.location(i) << (i < um.size() - 1 ? \",\" : \"};\\n\\n\");\n            out << \"extern \\\"C\\\" const double Su_pre[] = {\";\n            for (int i = 0; i < static_cast<int>(sum.size()); ++i)\n                out << (i == -1 ? 0.0 : sum.location(i))\n                    << (i < static_cast<int>(sum.size()) - 1 ? \",\" : \"};\\n\\n\");\n            out << \"extern \\\"C\\\" const double M_pre[][\" << um.size() << \"][\"\n                << (sum.size()) << \"] = {\\n\";\n        } else {\n            out << \"// y0_min = \" << u0_min << \" y0_max = \" << u0_max << \"\\n\";\n            out << \"// v_min = \" << Su_min << \" v_max = \" << Su_max << \"\\n\";\n            out << \"// y0_size = \" << u_size << \" v_size = \" << Su_size\n                << \" eta_size = \" << eta_size << \"\\n\";\n            out << \"// c_y0 = \" << c_u << \" density_y0 = \" << density_u << \"\\n\";\n            out << \"// c_v = \" << c_Su << \" density_v = \" << density_Su\n                << \"\\n\";\n            out << \"// c_e = \" << c_e << \" density_e = \" << density_e << \"\\n\\n\";\n            out << \"// note that the eta grid is taken from \"\n                   \"betaetatabulation.cpp\\n\\n\";\n            out << \"namespace QuantLib {\\n\"\n                << \"namespace detail {\\n\\n\";\n            out << \"extern \\\"C\\\" const double y0_pre[] = {\";\n            for (Size i = 0; i < um.size(); ++i)\n                out << um.location(i) << (i < um.size() - 1 ? \",\" : \"};\\n\\n\");\n            out << \"extern \\\"C\\\" const double v_pre[] = {\";\n            for (int i = 0; i < static_cast<int>(sum.size()); ++i)\n                out << (i == -1 ? 0.0 : sum.location(i))\n                    << (i < static_cast<int>(sum.size()) - 1 ? \",\" : \"};\\n\\n\");\n            out << \"extern \\\"C\\\" const double p_pre[][\" << um.size() << \"][\"\n                << (sum.size()) << \"] = {\\n\";\n        }\n    }\n\n    Array times;\n    Array alpha(1, 0.01);\n    Array kappa(1, 0.01);\n\n    if (type == Cpp_M || type == Cpp_p) {\n        for (Size e = 0; e < eta_size - 1; ++e) {\n            Real eta = em.location(e);\n            BetaEtaCore core(times, alpha, kappa, 1.0, eta);\n            out << \"// ========================  eta=\" << eta << \"\\n\";\n            out << \"{ \";\n            for (Size i = 0; i < um.size(); ++i) {\n                Real u0 = um.location(i);\n                if (type == Cpp_M) {\n                    out << \"// eta=\" << eta << \" u0=\" << u0 << \"\\n\";\n                } else {\n                    out << \"// eta=\" << eta << \" y0=\" << u0 << \"\\n\";\n                }\n                out << \"{\";\n                for (int j = 0; j < static_cast<int>(sum.size()); ++j) {\n                    Real v = j == -1 ? 0.0 : sum.location(j);\n                    Real lres;\n                    if (type == Cpp_M) {\n                        lres = core.M(u0, v);\n                    } else {\n                        lres = core.prob_y_0(v, u0);\n                    }\n                    out << lres\n                        << (j < static_cast<int>(sum.size()) - 1 ? \",\" : \"}\");\n                }\n                out << (i < um.size() - 1 ? \",\\n\" : \"}\");\n            }\n            out << (e < eta_size - 2 ? \",\\n\" : \"};\\n\");\n        }\n        out << \"} // namespace detail\\n\"\n            << \"} // namespace QuantLib\\n\";\n    }\n\n    if (type == GnuplotEUV) {\n        for (Size e = 0; e < eta_size - 1; ++e) {\n            Real eta = em.location(e);\n            BetaEtaCore core(times, alpha, kappa, 1.0, eta);\n            for (Size i = 0; i < um.size(); ++i) {\n                Real u0 = um.location(i);\n                for (int j = 0; j < static_cast<int>(sum.size()); ++j) {\n                    Real v = j == -1 ? 0.0 : sum.location(j);\n                    Real lres = core.M(u0, v);\n                    out << eta << \" \" << u0 << \" \" << v << \" \" << lres << \"\\n\";\n                }\n                out << \"\\n\";\n            }\n        }\n    }\n\n    if (type == GnuplotUEV) {\n        for (Size i = 0; i < um.size(); ++i) {\n            Real u0 = um.location(i);\n            for (Size e = 0; e < eta_size - 1; ++e) {\n                Real eta = em.location(e);\n                BetaEtaCore core(times, alpha, kappa, 1.0, eta);\n                for (int j = 0; j < static_cast<int>(sum.size()); ++j) {\n                    Real v = j == -1 ? 0.0 : sum.location(j);\n                    Real lres = core.M(u0, v);\n                    out << u0 << \" \" << eta << \" \" << v << \" \" << lres << \"\\n\";\n                }\n                out << \"\\n\";\n            }\n        }\n    }\n\n    if (type == GnuplotVEU) {\n        for (int j = 0; j < static_cast<int>(sum.size()); ++j) {\n            Real v = j == -1 ? 0.0 : sum.location(j);\n            for (Size e = 0; e < eta_size - 1; ++e) {\n                Real eta = em.location(e);\n                BetaEtaCore core(times, alpha, kappa, 1.0, eta);\n                for (Size i = 0; i < um.size(); ++i) {\n                    Real u0 = um.location(i);\n                    Real lres = core.M(u0, v);\n                    out << v << \" \" << eta << \" \" << u0 << \" \" << lres << \"\\n\";\n                }\n                out << \"\\n\";\n            }\n        }\n    }\n\n    if (type == GnuplotP) {\n        for (Size e = 0; e < eta_size - 1; ++e) {\n            Real eta = em.location(e);\n            for (Size i = 0; i < um.size(); ++i) {\n                Real u0 = um.location(i);\n                for (int j = 0; j < static_cast<int>(sum.size()); ++j) {\n                    Real v = j == -1 ? 0.0 : sum.location(j);\n                    BetaEtaCore core(times, alpha, kappa, 1.0, eta);\n                    Real lres = core.prob_y_0(v, u0);\n                    out << eta << \" \" << v << \" \" << u0 << \" \" << lres << \"\\n\";\n                }\n                out << \"\\n\";\n            }\n        }\n    }\n}\n\n} // namespace detail\n\n} // namespace QuantLib\n", "meta": {"hexsha": "90db56609aa642dd0dbadc98f3670f1ce4a49cad", "size": 27970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/experimental/models/betaetacore.cpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "ql/experimental/models/betaetacore.cpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "ql/experimental/models/betaetacore.cpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 39.3943661972, "max_line_length": 80, "alphanum_fraction": 0.490275295, "num_tokens": 8092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.4099779385981938}}
{"text": "//==================================================================================================\n/*!\n  @file\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_GAMMA_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_GAMMA_HPP_INCLUDED\n\n#include <boost/simd/function/std.hpp>\n#include <boost/config.hpp>\n#include <boost/simd/arch/common/detail/generic/gamma_kernel.hpp>\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/pi.hpp>\n#include <boost/simd/constant/three.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/copysign.hpp>\n#include <boost/simd/function/floor.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_even.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/sinpi.hpp>\n#include <boost/simd/function/stirling.hpp>\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <cmath>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n  using bs::std_tag;\n  BOOST_DISPATCH_OVERLOAD ( gamma_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT\n    {\n      if (is_eqz(a0)) return copysign(Inf<A0>(), a0);\n      #ifndef BOOST_SIMD_NO_INVALIDS\n      if( is_nan(a0) || (a0 == Minf<A0>()) ) return Nan<A0>();\n      if (a0 == Inf<A0>()) return a0;\n      #endif\n\n      A0 x = a0;\n      if (inftest(a0)) return Inf<A0>();\n      A0 q = bs::abs(x);\n      if(x < A0(-33.0))\n      {\n//        return std::tgamma(a0);\n        A0 st = stirling(q);\n        A0 p =  floor(q);\n        auto iseven =  is_even((int32_t)p);\n        if (p == q) return Nan<A0>();\n        A0 z = q - p;\n        if( z > Half<A0>() )\n        {\n          p += One<A0>();\n          z = q - p;\n        }\n        z = q*sinpi(z);\n        if( is_eqz(z) ) return Nan<A0>();\n        st = Pi<A0>()/(bs::abs(z)*st);\n        return iseven  ? -st : st;\n      }\n      A0 z = One<A0>();\n      while( x >= Three<A0>() )\n      {\n        x -= One<A0>();\n        z *= x;\n      }\n      while( is_ltz(x) )\n      {\n        z /= x;\n        x += One<A0>();\n      }\n      while( x < Two<A0>() )\n      {\n        if( is_eqz(x)) return Nan<A0>();\n        z /= x;\n        x +=  One<A0>();\n      }\n      if( x == Two<A0>() ) return(z);\n      x -= Two<A0>();\n      return z*detail::gamma_kernel<A0>::gamma1(x);\n    }\n  private:\n    static BOOST_FORCEINLINE bool inftest(const float a0)\n    {\n      return a0 > 35.4f;\n    }\n    static BOOST_FORCEINLINE bool inftest(const double a0)\n    {\n      return a0 > 171.624;\n    }\n\n  };\n  BOOST_DISPATCH_OVERLOAD ( gamma_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::std_tag\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const std_tag &, A0 a0) const BOOST_NOEXCEPT\n    {\n      return std::tgamma(a0);\n    }\n  };\n} } }\n\n\n#endif\n", "meta": {"hexsha": "7eb7907f7ddc208995103e4ff090fc637444afbc", "size": 3558, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/gamma.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/scalar/function/gamma.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/scalar/function/gamma.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 28.9268292683, "max_line_length": 100, "alphanum_fraction": 0.523608769, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506418255927, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.409977932749312}}
{"text": "/*\n * Copyright 2018, LAAS-CNRS\n * Author: Steve Tonneau\n */\n\n#ifndef BEZIER_COM_TRAJ_DEFINITIONS_H\n#define BEZIER_COM_TRAJ_DEFINITIONS_H\n\n#include <hpp/centroidal-dynamics/centroidal_dynamics.hh>\n#include <ndcurves/bezier_curve.h>\n#include <Eigen/Dense>\n\nnamespace bezier_com_traj {\n\ntypedef double value_type;\ntypedef Eigen::Matrix<value_type, 3, 3> Matrix3;\ntypedef Eigen::Matrix<value_type, 6, 3> Matrix63;\ntypedef Eigen::Matrix<value_type, 3, 9> Matrix39;\ntypedef Eigen::Matrix<value_type, Eigen::Dynamic, 3> MatrixX3;\ntypedef Eigen::Matrix<value_type, Eigen::Dynamic, Eigen::Dynamic> MatrixXX;\ntypedef centroidal_dynamics::Vector3 Vector3;\ntypedef centroidal_dynamics::Vector6 Vector6;\ntypedef centroidal_dynamics::VectorX VectorX;\n\ntypedef Eigen::Ref<Vector3> Ref_vector3;\ntypedef Eigen::Ref<VectorX> Ref_vectorX;\ntypedef Eigen::Ref<MatrixX3> Ref_matrixX3;\ntypedef Eigen::Ref<MatrixXX> Ref_matrixXX;\n\ntypedef const Eigen::Ref<const Vector3>& Cref_vector3;\ntypedef const Eigen::Ref<const Vector6>& Cref_vector6;\ntypedef const Eigen::Ref<const VectorX>& Cref_vectorX;\ntypedef const Eigen::Ref<const MatrixXX>& Cref_matrixXX;\ntypedef const Eigen::Ref<const MatrixX3>& Cref_matrixX3;\n\ntypedef Matrix63 matrix6_t;\ntypedef Vector6 point6_t;\ntypedef Matrix3 matrix3_t;\ntypedef Vector3 point3_t;\n\ntypedef Eigen::Vector3d point_t;\ntypedef const Eigen::Ref<const point_t>& point_t_tC;\n\n/**\n * @brief waypoint_t a waypoint is composed of a  6*3 matrix that depend\n * on the variable x, and of a 6d vector independent of x, such that\n * each control point of the target bezier curve is given by pi = wix * x + wis\n */\ntypedef std::pair<matrix6_t, point6_t> waypoint6_t;\ntypedef std::pair<matrix3_t, point3_t> waypoint3_t;\ntypedef std::pair<Matrix39, point3_t> waypoint9_t;\nstruct waypoint_t;  // forward declaration\n\ntypedef ndcurves::bezier_curve<double, double, true, point_t> bezier_t;\ntypedef ndcurves::bezier_curve<double, double, true, waypoint_t> bezier_wp_t;\ntypedef ndcurves::bezier_curve<double, double, true, point6_t> bezier6_t;\n\ntypedef std::vector<std::pair<double, int> > T_time;\ntypedef T_time::const_iterator CIT_time;\n\ntypedef std::pair<double, point3_t> coefs_t;\n\n}  // end namespace bezier_com_traj\n\n#endif\n", "meta": {"hexsha": "9f3c6474b7bcc92889e8fdb4d391514bcef511a8", "size": 2222, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/hpp/bezier-com-traj/definitions.hh", "max_stars_repo_name": "nim65s/hpp-bezier-com-traj", "max_stars_repo_head_hexsha": "7cb25463a353cd917468af12e5b325c8366af66e", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-09-17T13:06:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-09T22:52:40.000Z", "max_issues_repo_path": "include/hpp/bezier-com-traj/definitions.hh", "max_issues_repo_name": "nim65s/hpp-bezier-com-traj", "max_issues_repo_head_hexsha": "7cb25463a353cd917468af12e5b325c8366af66e", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-01-16T10:02:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-16T17:14:00.000Z", "max_forks_repo_path": "include/hpp/bezier-com-traj/definitions.hh", "max_forks_repo_name": "nim65s/hpp-bezier-com-traj", "max_forks_repo_head_hexsha": "7cb25463a353cd917468af12e5b325c8366af66e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-02-04T14:36:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-20T15:42:17.000Z", "avg_line_length": 33.6666666667, "max_line_length": 79, "alphanum_fraction": 0.7893789379, "num_tokens": 610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4098830604180583}}
{"text": "#define PY_ARRAY_UNIQUE_SYMBOL phist_PyArray_API\n#define NO_IMPORT_ARRAY\n\n#include <string>\n#include <cmath>\n\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n\n\n#include <boost/array.hpp>\n\n\n\n#include <vigra/numpy_array.hxx>\n#include <vigra/numpy_array_converters.hxx>\n\n#include \"seglib/histogram/histogram.hxx\"\n#include \"seglib/histogram/histogram_python.hxx\"\n\nnamespace python = boost::python;\n\nnamespace histogram {\n\n\n\n\n    vigra::NumpyAnyArray labelHistogram(\n        vigra::NumpyArray<3, vigra::Multiband<LabelType>  >         img,\n        const LabelType                                             nLabels,\n        const size_t                                                r,\n        //output\n        vigra::NumpyArray<4, float >    res = vigra::NumpyArray<4, float >()\n    ){ \n        const size_t nChannels=img.shape(2);\n        // allocate output\n        typedef typename vigra::NumpyArray<4, float >::difference_type Shape4;\n        Shape4 shape(img.shape(0),img.shape(1),nChannels,nLabels);\n        res.reshapeIfEmpty(shape);\n        std::fill(res.begin(),res.end(),0.0);\n\n\n        // coordinate in the res array (pixel wise histogram)\n        // (x,y,c,bin)\n        Shape4 histCoord;\n        const vigra::TinyVector<float, 2>  radius1(r+1,r+1);\n  \n        vigra::TinyVector<int,2>  start,end,c;\n\n        for(histCoord[0]=0;histCoord[0]<img.shape(0);++histCoord[0])\n        for(histCoord[1]=0;histCoord[1]<img.shape(1);++histCoord[1]){\n\n\n            for(int d=0;d<2;++d){\n                start[d]   = std::max(int(0),            int(histCoord[d]) - int(r));\n                end[d]     = std::min(int(img.shape(d)), int(histCoord[d] + (r+1) )); \n            }\n\n\n            for(c[0]=start[0];c[0]<end[0];++c[0])\n            for(c[1]=start[1];c[1]<end[1];++c[1]){\n\n                // iterate over all channels\n                for(histCoord[2]=0;histCoord[2]<nChannels;++histCoord[2] ){\n\n                    const LabelType label = img(c[0],c[1],histCoord[2]);\n\n                   \n                    histCoord[3] = label;\n\n                    /*\n                    std::cout<<\"\\n\\n” channel \"<<histCoord[2]<<\"\\n\";\n                    std::cout<<\"value \"<< value<<\"\\n\";\n                    std::cout<<\"mi \" << min(histCoord[2])<<\"\\n\";\n                    std::cout<<\"ma \" << max(histCoord[2])<<\"\\n\";\n                    std::cout<<\"fa \" << fac[histCoord[2]]<<\"\\n\";\n                    */\n\n                    PHIST_ASSERT_OP(histCoord[3],<,nLabels);\n                    // increment hist\n                    res(histCoord[0],histCoord[1],histCoord[2],histCoord[3])+=1.0;\n                }\n            }\n        }\n\n        // normalize\n\n        for(histCoord[0]=0;histCoord[0]<img.shape(0);++histCoord[0])\n        for(histCoord[1]=0;histCoord[1]<img.shape(1);++histCoord[1])\n        for(histCoord[2]=0;histCoord[2]<img.shape(2);++histCoord[2]){\n\n            float sum=0.0;\n            for(histCoord[3]=0;histCoord[3]<nLabels;++histCoord[3]){\n                sum+=res(histCoord[0],histCoord[1],histCoord[2],histCoord[3]);\n            }\n            for(histCoord[3]=0;histCoord[3]<nLabels;++histCoord[3]){\n                res(histCoord[0],histCoord[1],histCoord[2],histCoord[3])/=sum;\n            }\n        }\n        return res;\n    }\n\n\n\n    vigra::NumpyAnyArray labelSimHistogram(\n        vigra::NumpyArray<3, vigra::Multiband<LabelType>  >         img,\n        vigra::NumpyArray<3, float  >                               labelSim,\n        const LabelType                                             nLabels,\n        const size_t                                                r,\n        //output\n        vigra::NumpyArray<4, float >    res = vigra::NumpyArray<4, float >()\n    ){ \n        const size_t nChannels=img.shape(2);\n        // allocate output\n        typedef typename vigra::NumpyArray<4, float >::difference_type Shape4;\n        Shape4 shape(img.shape(0),img.shape(1),nChannels,nLabels);\n        res.reshapeIfEmpty(shape);\n        std::fill(res.begin(),res.end(),0.0);\n\n        PHIST_ASSERT_OP(labelSim.shape(0),==,labelSim.shape(1));\n        PHIST_ASSERT_OP(labelSim.shape(0),==,nLabels);\n        PHIST_ASSERT_OP(labelSim.shape(2),==,img.shape(2));\n        // coordinate in the res array (pixel wise histogram)\n        // (x,y,c,bin)\n        Shape4 histCoord;\n        const vigra::TinyVector<float, 2>  radius1(r+1,r+1);\n  \n        vigra::TinyVector<int,2>  start,end,c;\n\n        for(histCoord[0]=0;histCoord[0]<img.shape(0);++histCoord[0])\n        for(histCoord[1]=0;histCoord[1]<img.shape(1);++histCoord[1]){\n\n\n            for(int d=0;d<2;++d){\n                start[d]   = std::max(int(0),            int(histCoord[d]) - int(r));\n                end[d]     = std::min(int(img.shape(d)), int(histCoord[d] + (r+1) )); \n            }\n\n\n            for(c[0]=start[0];c[0]<end[0];++c[0])\n            for(c[1]=start[1];c[1]<end[1];++c[1]){\n\n                // iterate over all channels\n                for(histCoord[2]=0;histCoord[2]<nChannels;++histCoord[2] ){\n\n                    const LabelType label = img(c[0],c[1],histCoord[2]);\n\n                   \n                    histCoord[3] = label;\n\n                    /*\n                    std::cout<<\"\\n\\n” channel \"<<histCoord[2]<<\"\\n\";\n                    std::cout<<\"value \"<< value<<\"\\n\";\n                    std::cout<<\"mi \" << min(histCoord[2])<<\"\\n\";\n                    std::cout<<\"ma \" << max(histCoord[2])<<\"\\n\";\n                    std::cout<<\"fa \" << fac[histCoord[2]]<<\"\\n\";\n                    */\n\n                    PHIST_ASSERT_OP(histCoord[3],<,nLabels);\n                    // increment hist\n\n\n\n                    for(size_t ll = 0 ;ll<nLabels;++ll){\n                        const float sim = labelSim(label,ll,histCoord[2]);\n                        res(histCoord[0],histCoord[1],histCoord[2],ll)+=sim;\n                    }\n\n                    \n                }\n            }\n        }\n\n        // normalize\n\n        for(histCoord[0]=0;histCoord[0]<img.shape(0);++histCoord[0])\n        for(histCoord[1]=0;histCoord[1]<img.shape(1);++histCoord[1])\n        for(histCoord[2]=0;histCoord[2]<img.shape(2);++histCoord[2]){\n\n            float sum=0.0;\n            for(histCoord[3]=0;histCoord[3]<nLabels;++histCoord[3]){\n                sum+=res(histCoord[0],histCoord[1],histCoord[2],histCoord[3]);\n            }\n            for(histCoord[3]=0;histCoord[3]<nLabels;++histCoord[3]){\n                res(histCoord[0],histCoord[1],histCoord[2],histCoord[3])/=sum;\n            }\n        }\n        return res;\n    }\n\n\n\n\n\n    void moveMe(\n        vigra::NumpyArray<2, float  >           globalFeatures,\n        vigra::NumpyArray<1, vigra::Int64  >    batchIndex,\n        vigra::NumpyArray<1, vigra::Int64  >    minCenterIndex,         \n        vigra::NumpyArray<1, float  >           centerCount,   \n        vigra::NumpyArray<2, float  >           centers\n    ){\n\n        const size_t batchSize = batchIndex.shape(0);\n        const size_t nFeatures = globalFeatures.shape(1);\n        for(size_t bi=0;bi<batchSize;++bi){\n            const size_t ci = minCenterIndex(bi);\n            centerCount(ci)+=1.0;\n            const float rate = 1.0/centerCount(ci);\n            for(size_t f=0;f<nFeatures;++f){\n                centers(ci,f)*=(1.0-rate);\n                centers(ci,f)+=rate*globalFeatures(batchIndex(bi),f);\n            }\n        }\n    }\n\n\n\n\n    void histDist(\n        vigra::NumpyArray<2, float  > samples,\n        vigra::NumpyArray<2, float  > centers,\n        vigra::NumpyArray<2, float  > distances,\n        const std::string distType \n    ){\n\n        // renormalize centers \n\n\n\n\n        const size_t nSamples  = samples.shape(0);\n        const size_t nFeatures = samples.shape(1);\n        const size_t nCenters  = centers.shape(0);\n        \n\n\n\n        if(distType==std::string(\"bhattacharyya\")){\n\n            // bhattacharyya dist may shift centers\n            for(size_t c=0;c<nCenters;++c){\n\n                float minV=std::numeric_limits<float>::infinity();\n                for(size_t f=0;f<nFeatures;++f){\n                    minV=std::min(minV,centers(c,f));\n                }\n                if (minV<0.000001f){\n                    for(size_t f=0;f<nFeatures;++f){\n                        centers(c,f)-=minV;\n                    }\n                }\n                float sum=0;\n                for(size_t f=0;f<nFeatures;++f){\n                    sum+=centers(c,f);\n                }\n                if(sum>0.999999){\n                    for(size_t f=0;f<nFeatures;++f){\n                        centers(c,f)/=sum;\n                    }\n                }\n\n            }\n\n\n            for(size_t s=0;s<nSamples;++s)\n            for(size_t c=0;c<nCenters;++c){\n                // compute distace\n\n                float sum=0.0;\n                for(size_t f=0;f<nFeatures;++f){\n                    \n\n                    const float sv=samples(s,f);\n                    const float cv=samples(c,f);\n                    PHIST_ASSERT_OP(sv , > , -0.0000001);\n                    PHIST_ASSERT_OP(cv , > , -0.0000001);\n                    PHIST_ASSERT_OP(sv , < , 1.0000001);\n                    PHIST_ASSERT_OP(cv , < , 1.0000001);\n                    sum+=std::sqrt(samples(s,f)*centers(c,f));\n                }\n                PHIST_ASSERT_OP(sum , <= , 1.0001);\n                sum=std::min(sum,0.9999999f);\n                distances(s,c)=(1.0f - sum);\n                //std::cout<<\"distances \"<<distances(s,c)<<\"\\n\";\n            }\n        }\n        else if(distType==std::string(\"chi2\")){\n            for(size_t s=0;s<nSamples;++s)\n            for(size_t c=0;c<nCenters;++c){\n                // compute distace\n\n                float sum=0.0;\n                for(size_t f=0;f<nFeatures;++f){\n                    const float sv=samples(s,f);\n                    const float cv=samples(c,f);\n\n                    sum+=std::pow(sv-cv,2)/(sv+cv);\n                }\n                distances(s,c)=0.5*sum;\n                //std::cout<<\"distances \"<<distances(s,c)<<\"\\n\";\n            }\n        }\n        else{\n            PHIST_ASSERT_OP(0,==,1);\n        }\n    }\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n    \n\n\n    void export_label_histogram(){\n\n\n\n        python::def(\"_label_histogram_\",vigra::registerConverters(&labelHistogram),\n            (\n                python::arg(\"img\"),\n                python::arg(\"nLabels\"),\n                python::arg(\"r\"),\n                python::arg(\"out\")=python::object()\n            )\n        );\n\n        python::def(\"_label_sim_histogram_\",vigra::registerConverters(&labelSimHistogram),\n            (\n                python::arg(\"img\"),\n                python::arg(\"labelSim\"),\n                python::arg(\"nLabels\"),\n                python::arg(\"r\"),\n                python::arg(\"out\")=python::object()\n            )\n        );\n\n\n        python::def(\"moveMe\",vigra::registerConverters(&moveMe),\n            (\n                python::arg(\"globalFeatures\"),\n                python::arg(\"batchIndex\"),\n                python::arg(\"minCenterIndex\"),\n                python::arg(\"centerCount\"),\n                python::arg(\"centers\")\n            )\n        );\n\n        python::def(\"histDist\",vigra::registerConverters(&histDist),\n            (\n                python::arg(\"samples\"),\n                python::arg(\"centers\"),\n                python::arg(\"distances\"),\n                python::arg(\"distType\")=std::string(\"bhattacharyya\")\n            )\n        );\n\n    }\n\n}", "meta": {"hexsha": "e6c881f1fb26cac6d36830b97fd1b655191a7738", "size": 11385, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/python/histogram/py_label_histogram.cxx", "max_stars_repo_name": "DerThorsten/seglib", "max_stars_repo_head_hexsha": "4655079e390e301dd93e53f5beed6c9737d6df9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/python/histogram/py_label_histogram.cxx", "max_issues_repo_name": "DerThorsten/seglib", "max_issues_repo_head_hexsha": "4655079e390e301dd93e53f5beed6c9737d6df9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/python/histogram/py_label_histogram.cxx", "max_forks_repo_name": "DerThorsten/seglib", "max_forks_repo_head_hexsha": "4655079e390e301dd93e53f5beed6c9737d6df9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9375, "max_line_length": 90, "alphanum_fraction": 0.4706192358, "num_tokens": 2912, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4098787554327262}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2009 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <complex>\n#include <iostream>\n#include <iomanip>\n#include <cstdlib>\n#include <cmath>\n\n#include <boost/timer.hpp>\n\n#include \"dune/common/stdstreams.hh\"\n#include \"dune/grid/sgrid.hh\"\n#include \"dune/grid/uggrid.hh\"\n#include \"dune/grid/common/gridinfo.hh\"\n\n#include \"fem/assemble.hh\"\n#include \"fem/embedded_errorest.hh\"\n#include \"fem/istlinterface.hh\"\n#include \"fem/functional_aux.hh\"\n#include \"fem/hierarchicspace.hh\"\n#include \"fem/lagrangespace.hh\"\n#include \"fem/iterate_grid.hh\"\n#include \"fem/hierarchicErrorEstimator.hh\"\n#include \"linalg/trivialpreconditioner.hh\"\n#include \"linalg/direct.hh\"\n#include \"linalg/triplet.hh\"\n#include \"linalg/mumps_solve.hh\"\n\n#include \"io/vtk.hh\"\n#include \"io/amira.hh\"\n\n#include \"mg/pcg.hh\"\n#include \"mg/apcg.hh\"\n\n#include \"utilities/kaskopt.hh\"\n\n#include \"poisson.hh\"\n#include \"amiramesh.hh\"\n\nint problemNo = 1;\n\n\nbool compareAbs(const double x1, const double  x2)\n  {\n    return fabs(x1)>fabs(x2);\n  }\n\nint main(int argc, char *argv[])\n  {\n    int verbosity = 1;\n    bool dump = false;\n    boost::property_tree::ptree *pt = GetKaskadeOptions(argc, argv, verbosity, dump);\n\n    std::cout << \"Start cascadic multigrid test program\" << std::endl;\n\n    int  direct, refs, order, onlyLowerTriangle = false, maxAdaptSteps;\n    SolverType directType;\n    IterateType iterateType = IterateType::PCG;\n    MatrixProperties property;\n    std::string empty, problem, functional, geoFile;\n\n\tproblem = GetParameter(pt, \"problem\", empty);\n\trefs = GetParameter(pt, problem+\".refs\", 0),\n    order =  GetParameter(pt, problem+\".order\", 1),\n    maxAdaptSteps = GetParameter(pt, problem+\".maxAdaptSteps\", 10);\n    geoFile = GetParameter(pt, problem+\".geoFile\", empty);\n    functional = GetParameter(pt, problem+\".functional\", empty);\n    problemNo = GetParameter(pt, \"names.functional.\"+functional, 1);\n    std::cout << \"selected problem \" << problem << \", functional=\" <<\n                 functional << \"(\" << problemNo <<  \"), geoFile=\" <<\n                 geoFile << std::endl;\n\n    std::string s(\"names.type.\");\n    s += GetParameter(pt, \"solver.type\", empty);\n    direct = GetParameter(pt, s, 0);\n\n    s = \"names.direct.\" + GetParameter(pt, \"solver.direct\", empty);\n    directType = static_cast<SolverType>(GetParameter(pt, s, 2));\n\n\ts = \"names.iterate.\" + GetParameter(pt, \"solver.iterate\", empty);\n\titerateType = static_cast<IterateType>(GetParameter(pt, s, 0));\n\n    property = MatrixProperties::POSITIVEDEFINITE;\n\n    if (((property == MatrixProperties::SYMMETRIC)||(property == MatrixProperties::POSITIVEDEFINITE))&&\n        ((directType == DirectType::MUMPS)||(directType == DirectType::PARDISO)))\n      {\n        onlyLowerTriangle = true;\n      }\n\n    int const dim = 3;\n    int k;\n    typedef Dune::UGGrid<dim> Grid;\n    Grid *grid = new Grid(20000);\n    Dune::GridFactory<Grid> factory(grid);\n\n    DuneAmiraMesh<dim,dim,Grid> mesh(geoFile.c_str());\n    mesh.InsertUGGrid(factory);\n\t    \n//    std::auto_ptr<Grid> grid( factory.createGrid() );\n    grid = factory.createGrid();\n    // the coarse grid will be refined refs times\n    for (k=0; k<refs; k++)\n      {\n        grid->globalRefine(1);\n\t  }\n    // some information on the refined mesh\n    std::cout << \"Grid: \" << grid->size(0) << \" tetrahedra, \" << std::endl;\n    std::cout << \"      \" << grid->size(1) << \" triangles, \" << std::endl;\n    std::cout << \"      \" << grid->size(1) << \" edges, \" << std::endl;\n    std::cout << \"      \" << grid->size(dim) << \" points\" << std::endl;\n    // a gridmanager is constructed \n    // as connector between geometric and algebraic information\n    GridManager<Grid> gridManager(grid);    \n\n    typedef Grid::LeafGridView LeafView;\n    // construction of finite element space for the scalar solution T\n    typedef FEFunctionSpace<ContinuousLagrangeMapper<double,LeafView> > H1Space;\n\n    H1Space temperatureSpace(gridManager,gridManager.grid().leafView(),\n                             order);\n    typedef boost::fusion::vector<H1Space const*> Spaces;\n    Spaces spaces(&temperatureSpace);\n    // VariableDescription<int spaceId, int components, int Id>\n    // spaceId: number of associated FEFunctionSpace\n    // components: number of components in this variable\n    // Id: number of this variable\n    typedef boost::fusion::vector<VariableDescription<0,1,0> >\n      VariableDescriptions;\n    std::string varNames[1] = { \"T\" };\n    typedef VariableSetDescription<Spaces,VariableDescriptions> VariableSet;\n    VariableSet variableSet(spaces,varNames);\n\n    typedef PoissonFunctional<double,VariableSet> Functional;\n    Functional F;\n    typedef VariationalFunctionalAssembler<LinearizationAt<Functional> > GOP;\n    typedef GOP::TestVariableRepresentation<>::type Rhs;\n    GOP gop(gridManager.signals,spaces);\n\n    typedef FEFunctionSpace<ContinuousHierarchicExtensionMapper<double,LeafView> > H1ExSpace;\n    H1ExSpace spaceEx(gridManager,gridManager.grid().leafView(), order+1);\n\n    typedef boost::fusion::vector<H1Space const*,H1ExSpace const*> H1ExSpaces;\n    H1ExSpaces exSpaces(&temperatureSpace,&spaceEx);\n\n    typedef boost::fusion::vector<VariableDescription<1,1,0> > ExVariableDescriptions;\n    typedef VariableSetDescription<H1ExSpaces,ExVariableDescriptions> ExVariableSet;\n    std::string exVarNames[2] = { \"l\", \"e\"};\n    ExVariableSet exVariableSet(exSpaces, exVarNames);\n\n    typedef HierarchicErrorEstimator<LinearizationAt<Functional>,ExVariableSet> ErrorEstimator;\n    typedef VariationalFunctionalAssembler<ErrorEstimator> EstGOP;\n\n    EstGOP estGop(gridManager.signals,exSpaces);\n\ttypedef EstGOP::AnsatzVariableRepresentation<> Ansatz;\n\ttypedef EstGOP::TestVariableRepresentation<> Test;\n\n\ttypedef VariableSet::Grid::Traits::LeafIndexSet IS ;\n\tIS const& is = gridManager.grid().leafIndexSet();\n\n    VariableSet::VariableSet x(variableSet), dx(variableSet), tmp(variableSet);\n\n    double rTolX = GetParameter(pt, problem+\".rTolX\", 1.0e-4),\n           aTolX = GetParameter(pt, problem+\".aTolX\", 1.0-2),\n           minRefine = GetParameter(pt, problem+\".minRefine\", 0.0);\n    std::vector<std::pair<double,double> > tolX(variableSet.noOfVariables);\n    std::vector<std::pair<double,double> > tolXC(variableSet.noOfVariables);\n    for (int i=0; i<tolX.size(); ++i)\n      {\n        tolX[i] = std::make_pair(aTolX,rTolX);\n        tolXC[i] = std::make_pair(aTolX/100,rTolX/100);\n     }\n\tstd::cout << \"rTolX = \" << rTolX << \", aTolX = \" << aTolX <<\n\t             \", minRefine = \" << minRefine << std::endl ;\n\n\tIoOptions options;\n\toptions.outputType = IoOptions::ascii;\n\n    int refSteps = 0;\n    bool accurate = false;\n\tint iteSteps = GetParameter(pt, \"solver.iteMax\", 1000);\n\tint verbose = GetParameter(pt, \"solver.verbose\", 1);\n\tdouble iteEps = GetParameter(pt, \"solver.iteEps\", 1.0e-6);\n\ttypedef GOP::TestVariableRepresentation<>::type LinearSpace;\n\tDune::InverseOperatorResult res;\n\tdouble errNorm;\n\n\tsize_t size = variableSet.degreesOfFreedom(0,1);\n\tdouble gamma = 1.0, d = dim;\n\tdouble beta = 1.0/sqrt(d*gamma);\n\tdouble alpha = (d*gamma-1.0)/(d*(1.0+gamma));\n\tdouble qk = 1.0, dNk = size, zk = 0.0;\n\tdouble requested = sqrt(1-beta*beta)*tolX[0].first;\n\tdouble safety = 1.0;\n\tdouble yk = pow(dNk,alpha);\nprintf(\"gamma=%e, d=%e, beta=%e, alpha=%e, requested=%e, safety=%e\\n\",\n       gamma,d,beta,alpha,requested,safety);\n//printf(\"    %10ld %e   %e   %e   %e\\n\", size, qk, dNk, yk, zk);\n    do\n      {\n\t\ttypedef GOP::AnsatzVariableRepresentation<>::type Sol;\n\t\tSol solution(GOP::AnsatzVariableRepresentation<>::init(gop));\n\t\tSol hilfe(GOP::AnsatzVariableRepresentation<>::init(gop));\n\t\tsolution = 0;\n\t\thilfe = 0;\n\t\tgop.assemble(linearization(F,x));\n\t\tRhs rhs(GOP::TestVariableRepresentation<>::rhs(gop));\n\t\tAssembledGalerkinOperator<GOP,0,1,0,1> A(gop, onlyLowerTriangle);\n\t\tAssembledGalerkinOperator<GOP,0,1,0,1>::matrix_type tri(A.getmat());\n\n        if (direct)\n          {\n            directInverseOperator(A,directType,property).applyscaleadd(-1.0,rhs,solution);\n\t\t  }\n\t\telse\n\t\t  {\n\t\t\tswitch (iterateType)\n\t\t\t  {\n\t\t\t   case IterateType::CG:\n\t\t\t     {\n\t\t\t\t   JacobiPreconditioner<GOP,0,1,0> jacobi(gop,1.0);\n\t\t\t\t   Dune::CGSolver<LinearSpace> cg(A,jacobi,iteEps,iteSteps,verbose);\n\t\t\t\t   cg.apply(hilfe,rhs,res);\n\t\t\t     }\n\t\t\t     break;\n\t\t\t   case IterateType::PCG:\n\t\t\t     {\n\t\t\t       JacobiPreconditioner<GOP,0,1,0> jacobi(gop,1.0);\n\t\t\t       Kaskade7::NMIIIPCGSolver<LinearSpace> pcg(A,jacobi,iteEps,iteSteps,verbose);\n\t\t\t       pcg.apply(hilfe,rhs,res);\n\t\t\t     }\n\t\t\t     break;\n\t\t\t   case IterateType::APCG:\n\t\t\t     {\n    \t\t\t   int addedIterations = GetParameter(pt, \"solver.APCG.addedIterations\", 10);\n\t\t\t       JacobiPreconditioner<GOP,0,1,0> jacobiPCG(gop,1.0);\n\t\t\t       Kaskade7::NMIIIAPCGSolver<LinearSpace> apcg(A,jacobiPCG,iteEps,iteSteps,verbose,addedIterations);\n\t\t\t       apcg.apply(hilfe,rhs,res);\n\t\t\t     }\n\t\t\t     break;\n\t\t\t  default:\n\t\t\t    std::cout << \"Solver not available\" << std::endl;\n\t\t\t    throw -111;\n\t\t\t  }\n\t\t\tsolution.axpy(-1,hilfe);\n\t\t  }\n        dx.data = solution.data;\nprintf(\"Solved!\\n\");\n\n\t\tstd::ostringstream fn;\n\t\tfn << \"graph3d/cmg-grid\";\n\t\tfn.width(3);\n\t\tfn.fill('0');\n\t\tfn.setf(std::ios_base::right,std::ios_base::adjustfield);\n\t\tfn << refSteps;\n\t\tfn.flush();\n\t    LeafView leafView = gridManager.grid().leafView();\n\t    writeVTKFile(leafView,variableSet,x,fn.str(),options,order);\n\n        // Do hierarchical error estimation. Remember to provide the very same underlying problem to the\n        // error estimator functional as has been used to compute dx (do not modify x!).\n        if (!tolX.empty())\n          {\n\t        tmp *= 0 ;\n\t        estGop.assemble(ErrorEstimator(LinearizationAt<Functional>(F,x),dx));\n\t\t    int const estNvars = ErrorEstimator::AnsatzVars::noOfVariables;\n\t\t    int const estNeq = ErrorEstimator::TestVars::noOfVariables;\n\t\t    size_t  estNnz = estGop.nnz(0,estNeq,0,estNvars,false);\n\t\t    size_t  estSize = exVariableSet.degreesOfFreedom(0,estNvars);\n\n\t\t    std::vector<int> estRidx(estNnz), estCidx(estNnz);\n\t\t    std::vector<double> estData(estNnz), estRhs(estSize), estSolVec(estSize);\n\t\t    estGop.toSequence(0,estNeq,estRhs.begin());\n\n\t\t  // iterative solution of error estimator\n\n\t\t    AssembledGalerkinOperator<EstGOP> E(estGop);\n\t\t    Dune::InverseOperatorResult estRes;\n\t\t    Test::type estRhside(Test::rhs(estGop) ) ;\n\t\t    Ansatz::type estSol(Ansatz::init(estGop) ) ;\n\t\t    estSol = 1.0 ;\n\t\t    JacobiPreconditioner<EstGOP> jprec(estGop, 1.0);\n\t\t    jprec.apply(estSol,estRhside); //single Jacobi iteration\n\t\t    estSol.write(estSolVec.begin());\n\t  \n\t  // Transfer error indicators to cells.\n\t\t    std::vector<double> errorDistribution(is.size(0),0.0);\n\t\t    typedef VariableSet::GridView::Codim<0>::Iterator CellIterator ;\n\t\t    double maxErr = 0.0;\n\t\t    for (CellIterator ci=variableSet.gridView.begin<0>(); ci!=variableSet.gridView.end<0>(); ++ci)\n\t\t      {\n\t\t\t\ttypedef H1ExSpace::Mapper::GlobalIndexRange GIR;\n\t\t\t\tdouble err = 0;\n\t\t\t\tGIR gix = spaceEx.mapper().globalIndices(*ci);\n\t\t\t\tfor (GIR::iterator j=gix.begin(); j!=gix.end(); ++j)\n\t\t\t\t  err += fabs(boost::fusion::at_c<0>(estSol.data)[*j]);\n\t\t\t\terrorDistribution[is.index(*ci)] = err;\n\t\t\t\tif (fabs(err)>maxErr) maxErr = fabs(err);\n\t\t      }\n\t\t  \n\t\t    double errLevel = 0.5*maxErr;\n\n\t  \t    errLevel = 0.5*maxErr;\n\t\t    if (minRefine>0.0)\n\t\t      {\n\t\t    \tstd::vector<double> eSort(errorDistribution);\n\t  \t    \tstd::sort(eSort.begin(),eSort.end(),compareAbs);\n\t  \t    \tint minRefineIndex = minRefine*(eSort.size()-1);\n\t  \t    \tdouble minErrLevel = fabs(eSort[minRefineIndex])+1.0e-15;\n\t  \t    \tif (minErrLevel<errLevel)\n\t  \t    \t  errLevel = minErrLevel;\n\t  \t      }\n\n\t\t    errNorm = 0 ;\n\t\t    for (k=0; k < estRhs.size() ; k++ )\n\t\t      errNorm +=  fabs(estRhs[k]*estSolVec[k]) ;\n\n\t        if (errNorm<requested)\n\t          accurate = true ;\n\t        else\n\t          {\n\n\t  // Refine mesh.\n\t\n\t\t\t\tint noToRefine = 0;\n\t\t\t\tdouble alphaSave = 1.0 ;\n\t\t\t\tstd::vector<bool> toRefine( is.size(0), false ) ; //for adaptivity in compression\n\t\t\t\tstd::vector< std::vector<bool> > refinements;\n\t\t\t\tfor (CellIterator ci=variableSet.gridView.begin<0>(); ci!=variableSet.gridView.end<0>(); ++ci)\n\t\t\t\t  if (fabs(errorDistribution[is.index(*ci)]) >= alphaSave*errLevel)\n\t\t\t\t\t{\n\t\t\t\t\t  noToRefine++;\n\t\t\t\t\t  toRefine[is.index(*ci)] = true ;\n\t\t\t\t\t  gridManager.mark(1,*ci);\n\t\t\t\t\t}\n\t\n\t\t\t\trefinements.push_back(toRefine);\n\t\t\t\taccurate = !gridManager.adaptAtOnce(); \n\t          }\n        }\n        // apply the Newton correction here\n       x += dx;\n        \n        \n//           { // Compute spatial error estimate\n//     \t\t   std::vector<double> norm2, error2;\n//     \t\t   norm2.resize(1);\n//     \t\t   error2.resize(1);\n//             tmp = x;\n//             projectHierarchically(variableSet,tmp);\n//             tmp -= x;\n// \n//           // perform mesh adaptation\n//             accurate = embeddedErrorEstimator(variableSet, tmp, x, scal, tolX, gridManager, norm2, error2);\n//             printf(\" %e %e\\n\", norm2[0], error2[0]);\n//             if (!accurate)\n//               {\n//                 nnz = gop.nnz(0,1,0,1,onlyLowerTriangle);\n//                 size = variableSet.degreesOfFreedom(0,1);\n// \t\t\t\tridx.resize(nnz);\n// \t\t\t\tcidx.resize(nnz);\n// \t\t\t\tdata.resize(nnz);\n// \t\t\t\trhs.resize(size);\n// \t\t\t\tsol.resize(size);\n//               }\n//           }\n        refSteps++;\n\n        printf(\"%3d %10ld %5d   %e   %e\\n\", refSteps, size, res.iterations, errNorm,\n               iteEps);\n\n        size = variableSet.degreesOfFreedom(0,1);\n\t    qk = size/dNk;\n\t\tdNk = size;\n\t    yk += pow(dNk,alpha);\n\t    zk = pow(dNk,alpha)*(pow(errNorm/requested,d*alpha)-pow(qk,alpha))/(pow(qk,alpha)-1.0);\n        iteEps = safety*beta*errNorm*yk/(yk+zk);\n\n//        printf(\"  %10ld %e   %e   %e\\n\", size, yk, zk, yk+zk);\n\n        if (refSteps>maxAdaptSteps) break;\n// \n// \t\tstd::ostringstream fn;\n// \t\tfn << \"graph3d/cmg-grid\";\n// \t\tfn.width(3);\n// \t\tfn.fill('0');\n// \t\tfn.setf(std::ios_base::right,std::ios_base::adjustfield);\n// \t\tfn << refSteps;\n// \t\tfn.flush();\n// \t    LeafView leafView = gridManager.grid().leafView();\n// \t    writeVTKFile(leafView,variableSet,x,fn.str(),options,order);\n\n      } while (!accurate);     \n\n    std::cout << \"End cmgtest\" << std::endl;\n  }\n", "meta": {"hexsha": "4a47bd588d8e7fed65d8764b34ee9ffad4619823", "size": 15019, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Kaskade/tutorial/cmg/cmgtest3d.cpp", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/tutorial/cmg/cmgtest3d.cpp", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:36.000Z", "max_forks_repo_path": "Kaskade/tutorial/cmg/cmgtest3d.cpp", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 36.9017199017, "max_line_length": 110, "alphanum_fraction": 0.6148878088, "num_tokens": 4222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.734119526900183, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.40987874893708626}}
{"text": "/*\n * This file is a part of\n *\n * ============================================\n * ###   Pteros molecular modeling library  ###\n * ============================================\n *\n * (C) 2009-2018, Semen Yesylevskyy\n *\n * All works, which use Pteros, should cite the following papers:\n *  \n *  1.  Semen O. Yesylevskyy, \"Pteros 2.0: Evolution of the fast parallel\n *      molecular analysis library for C++ and python\",\n *      Journal of Computational Chemistry, 2015, 36(19), 1480–1488.\n *      doi: 10.1002/jcc.23943.\n *\n *  2.  Semen O. Yesylevskyy, \"Pteros: Fast and easy to use open-source C++\n *      library for molecular analysis\",\n *      Journal of Computational Chemistry, 2012, 33(19), 1632–1636.\n *      doi: 10.1002/jcc.22989.\n *\n * This is free software distributed under Artistic License:\n * http://www.opensource.org/licenses/artistic-license-2.0.php\n *\n*/\n\n\n#include \"pteros/core/system.h\"\n#include \"pteros/core/pteros_error.h\"\n#include \"pteros/core/distance_search.h\"\n#include \"pteros/core/force_field.h\"\n#include <cmath>\n#include <functional>\n#include \"pteros/core/logging.h\"\n#include <boost/algorithm/string.hpp>\n\nusing namespace std;\nusing namespace pteros;\nusing namespace Eigen;\n\nVector3f get_shift_coefs(int alpha, float r1, float rc){\n    Vector3f res;\n    res(0) = -(( (alpha+4)*rc - (alpha+1)*r1 )/( pow(rc,alpha+2)*pow(rc-r1,2) ));\n    res(1) = ( (alpha+3)*rc - (alpha+1)*r1 )/( pow(rc,alpha+2)*pow(rc-r1,3) );\n    res(2) = 1.0/pow(rc,alpha) - (res(0)/3.0)*pow(rc-r1,3) - (res(1)/4.0)*pow(rc-r1,4);\n    return res;\n}\n\n\n// Plain LJ kernel\nfloat LJ_en_kernel(float C6, float C12, float r, const Force_field& ff){\n    float r_inv = 1.0/r;\n    float tmp = r_inv*r_inv; // (1/r)^2\n    tmp = tmp*tmp*tmp; // (1/r)^6\n    return C12*tmp*tmp-C6*tmp;\n}\n\n// Cutoff LJ kernel\nfloat LJ_en_kernel_cutoff(float C6, float C12, float r, const Force_field& ff){\n    if(r>ff.rvdw) return 0.0;\n    float r_inv = 1.0/r;\n    float tmp = r_inv*r_inv; // (1/r)^2\n    tmp = tmp*tmp*tmp; // (1/r)^6\n    return C12*tmp*tmp-C6*tmp;\n}\n\n// Shifted LJ kernel\nfloat LJ_en_kernel_shifted(float C6, float C12, float r, const Force_field& ff){\n    if(r>ff.rvdw) return 0.0;\n\n    float val12 = pow(r,-12)\n            -(ff.shift_12(0)/3.0)*pow(r-ff.rvdw_switch,3)\n            -(ff.shift_12(1)/4.0)*pow(r-ff.rvdw_switch,4)\n            -ff.shift_12(2);\n    float val6 = pow(r,-6)\n            -(ff.shift_6(0)/3.0)*pow(r-ff.rvdw_switch,3)\n            -(ff.shift_6(1)/4.0)*pow(r-ff.rvdw_switch,4)\n            -ff.shift_6(2);\n\n    return C12*val12 - C6*val6;\n}\n\n\n#define ONE_4PI_EPS0      138.935456\n\n// Plane Coulomb kernel\nfloat Coulomb_en_kernel(float q1, float q2, float r, const Force_field& ff){\n    return ff.coulomb_prefactor*q1*q2/r;\n}\n\n// Cutoff Coulomb kernel\nfloat Coulomb_en_kernel_cutoff(float q1, float q2, float r, const Force_field& ff){\n    if(r>ff.rcoulomb) return 0.0;\n    return ff.coulomb_prefactor*q1*q2/r;\n}\n\n\n// Reaction field Coulomb kernel\nfloat Coulomb_en_kernel_rf(float q1, float q2, float r, const Force_field& ff){\n    return ff.coulomb_prefactor*q1*q2*(1.0/r + ff.k_rf*r*r - ff.c_rf);\n}\n\n// Shifted Coulomb kernel\nfloat Coulomb_en_kernel_shifted(float q1, float q2, float r, const Force_field& ff){\n    return ff.coulomb_prefactor*q1*q2*( 1.0/r\n                                     -(ff.shift_1(0)/3.0)*pow(r-ff.rcoulomb_switch,3)\n                                     -(ff.shift_1(1)/4.0)*pow(r-ff.rcoulomb_switch,4)\n                                     -ff.shift_1(2)\n                                     );\n}\n\n\n\n#define LOWER(s) boost::algorithm::to_lower_copy(string(s))\n\nvoid Force_field::setup_kernels(){\n    using namespace placeholders;\n\n    LOG()->debug(\"Coulomb type: {}\",coulomb_type);\n    LOG()->debug(\"Coulomb modifier: {}\",coulomb_modifier);\n    LOG()->debug(\"VdW type: {}\",vdw_type);\n    LOG()->debug(\"VdW modifier: {}\",vdw_modifier);\n\n    // Set Coulomb prefactor\n    coulomb_prefactor = ONE_4PI_EPS0 / epsilon_r;\n\n    // Set Coulomb kernel\n    if(LOWER(coulomb_type)==\"reaction-field\"){\n        // In case of reaction field precompute constanst\n        if(epsilon_rf){\n            k_rf = (1.0/(rcoulomb*rcoulomb*rcoulomb))\n                    * (epsilon_rf-epsilon_r) / (2.0*epsilon_rf+epsilon_r);\n        } else {\n            // for epsilon_rf = 0 (which means inf)\n            k_rf = 0.5/(rcoulomb*rcoulomb*rcoulomb);\n        }\n        c_rf = (1.0/rcoulomb) + k_rf*rcoulomb*rcoulomb;\n\n        // Set coulomb kernel pointer\n        coulomb_kernel_ptr = &Coulomb_en_kernel_rf;\n        LOG()->debug(\"\\tCoulomb kernel: reaction_field\");\n\n    } else if( ( LOWER(coulomb_type)==\"cut-off\"\n                 && LOWER(coulomb_modifier)== \"potential-shift\"\n               )\n              || LOWER(coulomb_type)==\"shift\"\n              || LOWER(coulomb_type)==\"pme\") {\n        // Compute shift constants for power 1\n        shift_1 = get_shift_coefs(1,rcoulomb_switch,rcoulomb);\n\n        coulomb_kernel_ptr = &Coulomb_en_kernel_shifted;\n        LOG()->debug(\"\\tCoulomb kernel: shifted\");\n\n    } else if(LOWER(coulomb_type)==LOWER(\"cut-off\")) {\n        // In other cases set plain Coulomb interaction\n        coulomb_kernel_ptr = &Coulomb_en_kernel_cutoff;\n        LOG()->debug(\"\\tCoulomb kernel: cutoff\");\n    } else {\n        coulomb_kernel_ptr = &Coulomb_en_kernel;\n        LOG()->debug(\"\\tCoulomb kernel: plain\");\n    }\n\n    // Set LJ kernel\n    if(LOWER(vdw_type)== \"shift\"){\n        // Compute shift constants for powers 6 and 12\n        shift_6 = get_shift_coefs(6,rvdw_switch,rvdw);\n        shift_12 = get_shift_coefs(12,rvdw_switch,rvdw);\n\n        LJ_kernel_ptr = &LJ_en_kernel_shifted;\n        LOG()->debug(\"\\tLJ kernel: shifted\");\n\n    } else if(LOWER(vdw_type)== \"cut-off\") {\n        LJ_kernel_ptr = &LJ_en_kernel_cutoff;\n        LOG()->debug(\"\\tLJ kernel: cutoff\");\n\n    } else {\n        LJ_kernel_ptr = &LJ_en_kernel;\n        LOG()->debug(\"\\tLJ kernel: plain\");\n    }\n}\n\n\nVector2f Force_field::pair_energy(int at1, int at2, float r, float q1, float q2, int type1, int type2)\n{\n    float c6,c12;\n    // indexes have to be in increasing order\n    if(at1>at2){\n        std::swap(at1,at2);\n        std::swap(q1,q2);\n        std::swap(type1,type2);\n    }\n    // Check is the pair is excluded\n    if(exclusions[at1].count(at2)) return {0,0};\n    // Check if this pair is 1-4 pair\n    auto it = LJ14_pairs.find(at1*natoms+at2);\n    if(it==std::end(LJ14_pairs)){\n        // normal pair\n        c6 = LJ_C6(type1,type2);\n        c12 = LJ_C12(type1,type2);\n        return {coulomb_kernel_ptr(q1,q2,r,*this), LJ_kernel_ptr(c6,c12,r,*this)};\n    } else {\n        // 1-4 pair\n        c6 = LJ14_interactions[it->second](0);\n        c12 = LJ14_interactions[it->second](1);\n        return {coulomb_kernel_ptr(q1,q2,r,*this)*fudgeQQ, LJ_kernel_ptr(c6,c12,r,*this)};\n    }\n}\n\nfloat Force_field::get_cutoff(){\n    return std::min(rcoulomb,rvdw);\n}\n\nForce_field::Force_field():  ready(false) {}\n\nForce_field::Force_field(const Force_field &other){\n    exclusions = other.exclusions;\n    LJ_C6 = other.LJ_C6;\n    LJ_C12 = other.LJ_C12;\n    LJ14_interactions = other.LJ14_interactions;\n    LJ14_pairs = other.LJ14_pairs;\n    fudgeQQ = other.fudgeQQ;\n    rcoulomb = other.rcoulomb;\n    epsilon_r = other.epsilon_r;\n    epsilon_rf = other.epsilon_rf;\n    rcoulomb_switch = other.rcoulomb_switch;\n    rvdw_switch = other.rvdw_switch;\n    rvdw = other.rvdw;\n    coulomb_type = other.coulomb_type;\n    coulomb_modifier = other.coulomb_modifier;\n    vdw_type = other.vdw_type;\n    vdw_modifier = other.vdw_modifier;\n\n    ready = other.ready;\n\n    if(ready) setup_kernels();\n}\n\nForce_field &Force_field::operator=(Force_field other){    \n    exclusions = other.exclusions;\n    LJ_C6 = other.LJ_C6;\n    LJ_C12 = other.LJ_C12;\n    LJ14_interactions = other.LJ14_interactions;\n    LJ14_pairs = other.LJ14_pairs;\n    fudgeQQ = other.fudgeQQ;\n    rcoulomb = other.rcoulomb;\n    epsilon_r = other.epsilon_r;\n    epsilon_rf = other.epsilon_rf;\n    rcoulomb_switch = other.rcoulomb_switch;\n    rvdw_switch = other.rvdw_switch;\n    rvdw = other.rvdw;\n    coulomb_type = other.coulomb_type;\n    coulomb_modifier = other.coulomb_modifier;\n    vdw_type = other.vdw_type;\n    vdw_modifier = other.vdw_modifier;\n\n    ready = other.ready;\n\n    if(ready) setup_kernels();\n\n    return *this;\n}\n\nvoid Force_field::clear(){    \n    exclusions.clear();\n    LJ_C6.fill(0.0);\n    LJ_C12.fill(0.0);\n    LJ14_interactions.clear();\n    LJ14_pairs.clear();\n    fudgeQQ = 0.0;\n\n    ready = false;\n}\n\n", "meta": {"hexsha": "92d99eb8ece9aed31b9d027103e76a23c4818da1", "size": 8480, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/force_field.cpp", "max_stars_repo_name": "confitarlaburra/pteros2.0", "max_stars_repo_head_hexsha": "25de81f39bc8948a37e10e3b389d58ca71195d8d", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-19T14:36:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-19T14:36:10.000Z", "max_issues_repo_path": "src/core/force_field.cpp", "max_issues_repo_name": "confitarlaburra/pteros2.0", "max_issues_repo_head_hexsha": "25de81f39bc8948a37e10e3b389d58ca71195d8d", "max_issues_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/force_field.cpp", "max_forks_repo_name": "confitarlaburra/pteros2.0", "max_forks_repo_head_hexsha": "25de81f39bc8948a37e10e3b389d58ca71195d8d", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9489051095, "max_line_length": 102, "alphanum_fraction": 0.6233490566, "num_tokens": 2581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195152660688, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.40987874244144623}}
{"text": "/*! @file pitts_tensortrain_from_dense.hpp\n* @brief conversion of a dense tensor to the tensor-train format (based on a hopefully faster TSQR algorithm)\n* @author Melven Roehrig-Zoellner <Melven.Roehrig-Zoellner@DLR.de>\n* @date 2020-06-19\n* @copyright Deutsches Zentrum fuer Luft- und Raumfahrt e. V. (DLR), German Aerospace Center\n*\n**/\n\n// include guard\n#ifndef PITTS_TENSORTRAIN_FROM_DENSE_HPP\n#define PITTS_TENSORTRAIN_FROM_DENSE_HPP\n\n// includes\n#include \"pitts_parallel.hpp\"\n#include \"pitts_tensortrain.hpp\"\n#include \"pitts_multivector.hpp\"\n#include \"pitts_multivector_tsqr.hpp\"\n#include \"pitts_multivector_transform.hpp\"\n#include \"pitts_tensor2.hpp\"\n#include \"pitts_tensor2_eigen_adaptor.hpp\"\n#include \"pitts_timer.hpp\"\n#include <limits>\n#include <numeric>\n#pragma GCC push_options\n#pragma GCC optimize(\"no-unsafe-math-optimizations\")\n#include <Eigen/Dense>\n#pragma GCC pop_options\n\n//! namespace for the library PITTS (parallel iterative tensor train solvers)\nnamespace PITTS\n{\n  //! calculate tensor-train decomposition of a tensor stored in fully dense format\n  //!\n  //! Passing a large enough buffer in work helps to avoid costly reallocations + later page-faults for large data.\n  //!\n  //! @warning To reduce memory overhead, this function will overwrite the input arguments with temporary data.\n  //!          Please pass a copy of the data if you still need it!\n  //!\n  //! @tparam T         underlying data type (double, complex, ...)\n  //!\n  //! @param X              input tensor, overwritten and modified output, dimension must be (size/lastDim, lastDim) where lastDim = dimensions.back()\n  //! @param dimensions     tensor dimensions, input is interpreted in Fortran storage order (first index changes the fastest)\n  //! @param work           buffer for temporary data, will be resized and modified\n  //! @param rankTolerance  approximation accuracy, used to reduce the TTranks of the resulting tensor train\n  //! @param maxRank        maximal TTrank (bond dimension), unbounded by default\n  //! @param mpiGlobal      (experimental) perform a MPI parallel decomposition, this assumes that the data is distributed on the MPI processes and dimensions specify the local dimensions\n  //! @return               resulting tensor train\n  //!\n  template<typename T>\n  TensorTrain<T> fromDense(MultiVector<T>& X, MultiVector<T>& work, const std::vector<int>& dimensions, T rankTolerance = std::sqrt(std::numeric_limits<T>::epsilon()), int maxRank = -1, bool mpiGlobal = false)\n  {\n    // timer\n    const auto timer = PITTS::timing::createScopedTimer<TensorTrain<T>>();\n\n    // abort early for zero dimensions\n    if( dimensions.size() == 0 )\n    {\n      if( X.rows()*X.cols() !=  0 )\n        throw std::out_of_range(\"Mismatching dimensions in TensorTrain<T>::fromDense\");\n      return TensorTrain<T>{dimensions};\n    }\n\n    const auto totalSize = std::accumulate(begin(dimensions), end(dimensions), (std::ptrdiff_t)1, std::multiplies<std::ptrdiff_t>());\n    const auto nDims = dimensions.size();\n    if( X.rows() != totalSize/dimensions[nDims-1] || X.cols() != dimensions[nDims-1] )\n      throw std::out_of_range(\"Mismatching dimensions in TensorTrain<T>::fromDense\");\n\n    bool root = true;\n    if( mpiGlobal )\n    {\n      const auto& [iProc,nProcs] = internal::parallel::mpiProcInfo();\n      root = iProc == 0;\n    }\n\n    TensorTrain<T> result(dimensions);\n\n    // actually convert to tensor train format\n    Tensor2<T> tmpR;\n    using EigenMatrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n    Eigen::BDCSVD<EigenMatrix> svd;\n    for(int iDim = nDims-1; iDim > 0; iDim--)\n    {\n      if( root )\n        std::cout << \"iDim: \" << iDim << \", matrix dimensions: \" << X.rows() << \" x \" << X.cols() << \"\\n\";\n      // calculate QR decomposition\n      block_TSQR(X, tmpR, 0, mpiGlobal);\n//std::cout << \"tmpR:\\n\" << ConstEigenMap(tmpR) << \"\\n\";\n\n      // calculate SVD of R\n      svd.compute(ConstEigenMap(tmpR), Eigen::ComputeThinU | Eigen::ComputeThinV);\n      //Eigen::JacobiSVD<EigenMatrix> svd(ConstEigenMap(tmpR), Eigen::ComputeThinU | Eigen::ComputeThinV);\n      svd.setThreshold(rankTolerance);\n      if( root )\n        std::cout << \"singular values: \" << svd.singularValues().transpose() << \"\\n\";\n\n      // copy V to the TT sub-tensor\n      svd.setThreshold(rankTolerance);\n      int rank = svd.rank();\n      if( maxRank > 0 )\n        rank = std::min(maxRank, rank);\n      auto& subT = result.editableSubTensors()[iDim];\n      subT.resize(rank, dimensions[iDim], X.cols()/dimensions[iDim]);\n      for(int i = 0; i < subT.r1(); i++)\n        for(int j = 0; j < subT.n(); j++)\n          for(int k = 0; k < subT.r2(); k++)\n            subT(i,j,k) = svd.matrixV()(j+subT.n()*k, i);\n\n      tmpR.resize(X.cols(), rank);\n      EigenMap(tmpR) = svd.matrixV().leftCols(rank);\n\n      const auto nextDim = dimensions[iDim-1];\n      transform(X, tmpR, work, {X.rows()/nextDim, rank*nextDim});\n      std::swap(X, work);\n    }\n    // last sub-tensor is now in X\n    auto& lastSubT = result.editableSubTensors()[0];\n    lastSubT.resize(1, dimensions[0], X.cols()/dimensions[0]);\n    for(int i = 0; i < lastSubT.n(); i++)\n      for(int j = 0; j < lastSubT.r2(); j++)\n        lastSubT(0, i, j) = X(0, i+j*dimensions[0]);\n\n    // make sure we swap X and work back: prevents problems where the reserved space in X is used again later AND the data does only fit into memory once ;)\n    if( nDims % 2 == 0 )\n      std::swap(X, work);\n\n    return result;\n  }\n\n}\n\n\n#endif // PITTS_TENSORTRAIN_FROM_DENSE_HPP\n", "meta": {"hexsha": "d0485473c8d6a33b1329b7d1289710a801f3302c", "size": 5508, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pitts_tensortrain_from_dense.hpp", "max_stars_repo_name": "melven/pitts", "max_stars_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-31T08:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T14:48:49.000Z", "max_issues_repo_path": "src/pitts_tensortrain_from_dense.hpp", "max_issues_repo_name": "melven/pitts", "max_issues_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pitts_tensortrain_from_dense.hpp", "max_forks_repo_name": "melven/pitts", "max_forks_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4135338346, "max_line_length": 209, "alphanum_fraction": 0.663761801, "num_tokens": 1488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4098423005068695}}
{"text": "#ifndef DEFINING_ELEMENT_X8346D3\r\n#define DEFINING_ELEMENT_X8346D3\r\n// #define e 2.71828\r\n// #define pi 3.14159\r\n#include <bits/stdc++.h>\r\n// #include <Eigen/Eigen>\r\n\r\n// using namespace Eigen;\r\nusing namespace std;\r\n\r\nclass matrix\r\n{\r\npublic:\r\n    float **data;\r\n    int shape[2];\r\n\r\n    matrix()\r\n    {\r\n        this->shape[0] = 0;\r\n        this->shape[1] = 0;\r\n    }\r\n\r\n    matrix(int a, int b)\r\n    {\r\n        this->shape[0] = a;\r\n        this->shape[1] = b;\r\n        this->data = (float **)malloc(sizeof(float *) * a);\r\n        for (int i = 0; i < a; i++)\r\n        {\r\n            this->data[i] = (float *)malloc(sizeof(float) * b);\r\n        }\r\n        for (int i = 0; i < a; i++)\r\n        {\r\n            for (int j = 0; j < b; j++)\r\n            {\r\n                this->data[i][j] = 0;\r\n            }\r\n        }\r\n    }\r\n\r\n    void print()\r\n    {\r\n        printf(\"\\n{ \");\r\n        printf(\"Class : matrix , shape = [ %d , %d ] \\n\", this->shape[0], this->shape[1]);\r\n        printf(\"  [ \\n\");\r\n        for (int i = 0; i < this->shape[0]; i++)\r\n        {\r\n            printf(\"   [ \");\r\n            for (int j = 0; j < this->shape[1]; j++)\r\n            {\r\n                if (j == this->shape[1] - 1)\r\n                {\r\n                    printf(\"%f \", data[i][j]);\r\n                }\r\n                else\r\n                {\r\n                    printf(\"%f , \", data[i][j]);\r\n                }\r\n            }\r\n            if (i == this->shape[0] - 1)\r\n                printf(\" ]\\n\");\r\n            else\r\n            {\r\n                printf(\" ] ,\\n\");\r\n            }\r\n        }\r\n        printf(\"  ] \\n}\\n\", this->shape[0], this->shape[1]);\r\n    }\r\n\r\n    friend matrix operator>=(matrix const m, float const &n)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                if (m.data[i][j] >= n)\r\n                    res.data[i][j] = 1;\r\n                else\r\n                    res.data[i][j] = 0;\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n\r\n    friend matrix operator<=(matrix const m, float const &n)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                if (m.data[i][j] <= n)\r\n                    res.data[i][j] = 1;\r\n                else\r\n                    res.data[i][j] = 0;\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n\r\n    friend matrix operator>(matrix const m, float const &n)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                if (m.data[i][j] > n)\r\n                    res.data[i][j] = 1;\r\n                else\r\n                    res.data[i][j] = 0;\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n\r\n    friend matrix operator<(matrix const m, float const &n)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                if (m.data[i][j] > n)\r\n                    res.data[i][j] = 1;\r\n                else\r\n                    res.data[i][j] = 0;\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n\r\n    friend int operator==(matrix const m, matrix const &n)\r\n    {\r\n        if (m.shape[0] != n.shape[0] || m.shape[1] != n.shape[1])\r\n        {\r\n            return 0;\r\n        }\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                if (m.data[i][j] != n.data[i][j])\r\n                {\r\n                    return 0;\r\n                }\r\n            }\r\n        }\r\n        return 1;\r\n    }\r\n\r\n    friend int operator!=(matrix const m, matrix const &n)\r\n    {\r\n        if (m.shape[0] != n.shape[0] || m.shape[1] != n.shape[1])\r\n        {\r\n            return 1;\r\n        }\r\n\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                if (m.data[i][j] != n.data[i][j])\r\n                {\r\n                    return 1;\r\n                }\r\n            }\r\n        }\r\n        return 0;\r\n    }\r\n\r\n    matrix operator()(int index)\r\n    {\r\n        matrix res(shape[0], 1);\r\n        for (int i = 0; i < shape[0]; i++)\r\n        {\r\n            res.data[i][0] = this->data[i][index];\r\n        }\r\n        return res;\r\n    }\r\n\r\n    matrix operator()(int index1, int index2, int axis = 0)\r\n    {\r\n        if (axis == 0)\r\n        {\r\n            if (!((index1 >= 0 && index1 < shape[0]) && (index2 >= 0 && index2 < shape[0]) && index1 < index2))\r\n            {\r\n                fprintf(stderr, \"enter correct indexing and axis , m.shape = [%d  %d ]\", shape[0], shape[1]);\r\n                exit(1);\r\n            }\r\n            matrix res(index2 - index1, shape[1]);\r\n            for (int i = index1; i < index2; i++)\r\n            {\r\n                for (int j = 0; j < shape[1]; j++)\r\n                {\r\n                    res.data[i - index1][j] = data[i][j];\r\n                }\r\n            }\r\n\r\n            return res;\r\n        }\r\n        else if (axis == 1)\r\n        {\r\n            if (!((index1 >= 0 && index1 < shape[1]) && (index2 >= 0 && index2 < shape[1]) && index1 < index2))\r\n            {\r\n                fprintf(stderr, \"enter correct indexing and axis , m.shape = [%d  %d ]\", shape[0], shape[1]);\r\n                exit(1);\r\n            }\r\n            matrix res(shape[0], index2 - index1);\r\n\r\n            for (int i = 0; i < shape[0]; i++)\r\n            {\r\n                for (int j = index1; j < index2; j++)\r\n                {\r\n                    res.data[i][j - index1] = data[i][j];\r\n                }\r\n            }\r\n\r\n            return res;\r\n        }\r\n    }\r\n\r\n    friend matrix operator/(matrix const m1, matrix const m2)\r\n    {\r\n        if (m1.shape[0] == m2.shape[0] && m1.shape[1] == m2.shape[1])\r\n        {\r\n            matrix res(m1.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] / m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] == 1 && m1.shape[1] != 1 && m2.shape[0] != 1 && m2.shape[1] != 1 && m1.shape[1] == m2.shape[1])\r\n        {\r\n            matrix res(m2.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m2.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m2.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[0][j] / m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n\r\n        else if (m1.shape[0] != 1 && m1.shape[1] == 1 && m2.shape[0] != 1 && m2.shape[1] != 1 && m1.shape[0] == m2.shape[0])\r\n        {\r\n            matrix res(m2.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m2.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m2.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][0] / m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] == 1 && m2.shape[1] != 1 && m1.shape[1] == m2.shape[1])\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] + m2.data[0][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] != 1 && m2.shape[1] == 1 && m1.shape[0] == m2.shape[0])\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] / m2.data[i][0];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] == 1 && m2.shape[1] == 1)\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] / m2.data[0][0];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] == 1 && m1.shape[1] == 1 && m2.shape[0] != 1 && m2.shape[1] != 1)\r\n        {\r\n            matrix res(m2.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m2.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m2.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[0][0] / m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else\r\n        {\r\n            fprintf(stderr, \"cannot divide element wise ,dimensions mismatched m1.shape = [%d , %d] and m2.shape = [%d , %d]\", m1.shape[0], m1.shape[1], m2.shape[0], m2.shape[1]);\r\n            exit(1);\r\n        }\r\n    }\r\n\r\n    friend matrix operator/(float const &n, matrix const m)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                res.data[i][j] = n / (m.data[i][j]);\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n\r\n    friend matrix operator/(matrix const m, float const &n)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                res.data[i][j] = (m.data[i][j]) / n;\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n\r\n    // friend matrix operator+(matrix const m1, matrix const m2)\r\n    // {\r\n    //     if (m1.shape[0] == m2.shape[0] && m1.shape[1] == m2.shape[1])\r\n    //     {\r\n    //         matrix res(m1.shape[0], m2.shape[1]);\r\n    //         for (int i = 0; i < m1.shape[0]; i++)\r\n    //         {\r\n    //             for (int j = 0; j < m1.shape[1]; j++)\r\n    //             {\r\n    //                 res.data[i][j] = m1.data[i][j] + m2.data[i][j];\r\n    //             }\r\n    //         }\r\n    //         return res;\r\n    //     }\r\n    // }\r\n\r\n    friend matrix operator+(matrix const m1, matrix const m2)\r\n    {\r\n        if (m1.shape[0] == m2.shape[0] && m1.shape[1] == m2.shape[1])\r\n        {\r\n            matrix res(m1.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] + m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] == 1 && m1.shape[1] != 1 && m2.shape[0] != 1 && m2.shape[1] != 1 && m1.shape[1] == m2.shape[1])\r\n        {\r\n            matrix res(m2.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m2.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m2.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[0][j] + m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n\r\n        else if (m1.shape[0] != 1 && m1.shape[1] == 1 && m2.shape[0] != 1 && m2.shape[1] != 1 && m1.shape[0] == m2.shape[0])\r\n        {\r\n            matrix res(m2.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m2.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m2.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][0] + m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] == 1 && m2.shape[1] != 1 && m1.shape[1] == m2.shape[1])\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] + m2.data[0][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] != 1 && m2.shape[1] == 1 && m1.shape[0] == m2.shape[0])\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] + m2.data[i][0];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] != 1 && m2.shape[1] == 1 && m1.shape[0] == m2.shape[0])\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] + m2.data[i][0];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] == 1 && m2.shape[1] == 1)\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] + m2.data[0][0];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] == 1 && m1.shape[1] == 1 && m2.shape[0] != 1 && m2.shape[1] != 1)\r\n        {\r\n            matrix res(m2.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m2.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m2.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[0][0] + m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[1] != 1 && m2.shape[0] == 1 && m2.shape[1] == 1)\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] + m2.data[0][0];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        // else if (m1.shape[0] == 1 && m1.shape[1] != 1 && m2.shape[0] == 1 && m2.shape[1] == 1)\r\n        // {\r\n        //     matrix res(m2.shape[0], m2.shape[1]);\r\n        //     for (int i = 0; i < m2.shape[0]; i++)\r\n        //     {\r\n        //         for (int j = 0; j < m2.shape[1]; j++)\r\n        //         {\r\n        //             res.data[i][j] = m1.data[0][0] + m2.data[i][j];\r\n        //         }\r\n        //     }\r\n        //     return res;\r\n        // }\r\n\r\n        else\r\n        {\r\n            fprintf(stderr, \"cannot add dimensions mismatched m1.shape = [%d , %d] and m2.shape = [%d , %d]\", m1.shape[0], m1.shape[1], m2.shape[0], m2.shape[1]);\r\n            exit(1);\r\n        }\r\n    }\r\n\r\n    friend matrix operator+(float const &n, matrix const m)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                res.data[i][j] = m.data[i][j] + n;\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n\r\n    friend matrix operator+(matrix const m, float const &n)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                res.data[i][j] = m.data[i][j] + n;\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n\r\n    friend matrix operator-(matrix const m1, matrix const m2)\r\n    {\r\n        if (m1.shape[0] == m2.shape[0] && m1.shape[1] == m2.shape[1])\r\n        {\r\n            matrix res(m1.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] - m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] == 1 && m1.shape[1] != 1 && m2.shape[0] != 1 && m2.shape[1] != 1 && m1.shape[1] == m2.shape[1])\r\n        {\r\n            matrix res(m2.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m2.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m2.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[0][j] - m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n\r\n        else if (m1.shape[0] != 1 && m1.shape[1] == 1 && m2.shape[0] != 1 && m2.shape[1] != 1 && m1.shape[0] == m2.shape[0])\r\n        {\r\n            matrix res(m2.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m2.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m2.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][0] - m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] == 1 && m2.shape[1] != 1 && m1.shape[1] == m2.shape[1])\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] - m2.data[0][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] != 1 && m2.shape[1] == 1 && m1.shape[0] == m2.shape[0])\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] - m2.data[i][0];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] == 1 && m2.shape[1] == 1)\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] - m2.data[0][0];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] == 1 && m1.shape[1] == 1 && m2.shape[0] != 1 && m2.shape[1] != 1)\r\n        {\r\n            matrix res(m2.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m2.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m2.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[0][0] - m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else\r\n        {\r\n            fprintf(stderr, \"cannot subtract ,dimensions mismatched m1.shape = [%d , %d] and m2.shape = [%d , %d]\", m1.shape[0], m1.shape[1], m2.shape[0], m2.shape[1]);\r\n            exit(1);\r\n        }\r\n    }\r\n\r\n    friend matrix operator-(matrix const m, float const &n)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                res.data[i][j] = m.data[i][j] - n;\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n\r\n    friend matrix operator-(float const &n, matrix const m)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                res.data[i][j] = n - m.data[i][j];\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n\r\n    friend matrix operator*(matrix const m1, matrix const m2)\r\n    {\r\n        if (m1.shape[0] == m2.shape[0] && m1.shape[1] == m2.shape[1])\r\n        {\r\n            matrix res(m1.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] + m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] == 1 && m1.shape[1] != 1 && m2.shape[0] != 1 && m2.shape[1] != 1 && m1.shape[1] == m2.shape[1])\r\n        {\r\n            matrix res(m2.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m2.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m2.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[0][j] * m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n\r\n        else if (m1.shape[0] != 1 && m1.shape[1] == 1 && m2.shape[0] != 1 && m2.shape[1] != 1 && m1.shape[0] == m2.shape[0])\r\n        {\r\n            matrix res(m2.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m2.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m2.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][0] * m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] == 1 && m2.shape[1] != 1 && m1.shape[1] == m2.shape[1])\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] * m2.data[0][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] != 1 && m2.shape[1] == 1 && m1.shape[0] == m2.shape[0])\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] * m2.data[i][0];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] != 1 && m1.shape[1] != 1 && m2.shape[0] == 1 && m2.shape[1] == 1)\r\n        {\r\n            matrix res(m1.shape[0], m1.shape[1]);\r\n            for (int i = 0; i < m1.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m1.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[i][j] * m2.data[0][0];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else if (m1.shape[0] == 1 && m1.shape[1] == 1 && m2.shape[0] != 1 && m2.shape[1] != 1)\r\n        {\r\n            matrix res(m2.shape[0], m2.shape[1]);\r\n            for (int i = 0; i < m2.shape[0]; i++)\r\n            {\r\n                for (int j = 0; j < m2.shape[1]; j++)\r\n                {\r\n                    res.data[i][j] = m1.data[0][0] * m2.data[i][j];\r\n                }\r\n            }\r\n            return res;\r\n        }\r\n        else\r\n        {\r\n            fprintf(stderr, \"cannot multiple element wise, dimensions mismatched m1.shape = [%d , %d] and m2.shape = [%d , %d]\", m1.shape[0], m1.shape[1], m2.shape[0], m2.shape[1]);\r\n            exit(1);\r\n        }\r\n    }\r\n\r\n    friend matrix operator*(float const &n, matrix const m)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                res.data[i][j] = m.data[i][j] * n;\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n\r\n    friend matrix operator*(matrix const m, float const &n)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                res.data[i][j] = m.data[i][j] * n;\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n\r\n    friend matrix operator^(matrix const m, float const &n)\r\n    {\r\n        matrix res(m.shape[0], m.shape[1]);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                res.data[i][j] = pow(m.data[i][j], n);\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n    matrix T()\r\n    {\r\n        matrix m1(this->shape[1], this->shape[0]);\r\n\r\n        for (int i = 0; i < shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < shape[1]; j++)\r\n            {\r\n                m1.data[j][i] = this->data[i][j];\r\n            }\r\n        }\r\n        return m1;\r\n    }\r\n};\r\n\r\nmatrix randn(int a, int b)\r\n{\r\n    matrix m(a, b);\r\n    srand(time(0));\r\n    for (int i = 0; i < m.shape[0]; i++)\r\n    {\r\n        for (int j = 0; j < m.shape[1]; j++)\r\n        {\r\n            m.data[i][j] = 2 * (rand() / (float)RAND_MAX) - 1;\r\n        }\r\n    }\r\n    return m;\r\n}\r\n\r\nvoid print(matrix m)\r\n{\r\n    printf(\"\\n{ \");\r\n    printf(\"Class : matrix , shape = [ %d , %d ] \\n\", m.shape[0], m.shape[1]);\r\n    printf(\"  [ \\n\");\r\n    for (int i = 0; i < m.shape[0]; i++)\r\n    {\r\n        printf(\"   [ \");\r\n        for (int j = 0; j < m.shape[1]; j++)\r\n        {\r\n            if (j == m.shape[1] - 1)\r\n            {\r\n                printf(\"%f \", m.data[i][j]);\r\n            }\r\n            else\r\n            {\r\n                printf(\"%f , \", m.data[i][j]);\r\n            }\r\n        }\r\n        if (i == m.shape[0] - 1)\r\n            printf(\" ]\\n\");\r\n        else\r\n        {\r\n            printf(\" ] ,\\n\");\r\n        }\r\n    }\r\n    printf(\"  ] \\n}\", m.shape[0], m.shape[1]);\r\n}\r\n\r\nmatrix take_matrix(char *path)\r\n{\r\n    FILE *fp;\r\n    fp = fopen(path, \"r\");\r\n    int dim1, dim2;\r\n    fscanf(fp, \"%d %d\", &dim1, &dim2);\r\n    matrix X(dim1, dim2);\r\n    for (int i = 0; i < dim1; i++)\r\n    {\r\n        for (int j = 0; j < dim2; j++)\r\n        {\r\n            fscanf(fp, \"%f\", &X.data[i][j]);\r\n        }\r\n    }\r\n\r\n    return X;\r\n}\r\n\r\nmatrix zeros(int a, int b)\r\n{\r\n    matrix m(a, b);\r\n    for (int i = 0; i < a; i++)\r\n    {\r\n        for (int j = 0; j < b; j++)\r\n        {\r\n            m.data[i][j] = 0;\r\n        }\r\n    }\r\n    return m;\r\n}\r\n\r\nmatrix dot(matrix m1, matrix m2)\r\n{\r\n    if (m1.shape[1] != m2.shape[0])\r\n    {\r\n        fprintf(stderr, \"ERROR : Dimensions Mismatch in performing dot product m1.shape = [%d ,%d]  and  m2.shape = [%d ,%d]\\n\", m1.shape[0], m1.shape[1], m2.shape[0], m2.shape[1]);\r\n        exit(1);\r\n    }\r\n    matrix multi(m1.shape[0], m2.shape[1]);\r\n\r\n    for (int i = 0; i < m1.shape[0]; ++i)\r\n    {\r\n        for (int j = 0; j < m2.shape[1]; ++j)\r\n        {\r\n            for (int k = 0; k < m1.shape[1]; ++k)\r\n            {\r\n                multi.data[i][j] += m1.data[i][k] * m2.data[k][j];\r\n            }\r\n        }\r\n    }\r\n    return multi;\r\n}\r\n\r\nmatrix abs(matrix m)\r\n{\r\n    matrix res(m.shape[0], m.shape[1]);\r\n    for (int i = 0; i < m.shape[0]; i++)\r\n    {\r\n        for (int j = 0; j < m.shape[1]; j++)\r\n        {\r\n            if (m.data[i][j] > 0)\r\n                res.data[i][j] = m.data[i][j];\r\n            else\r\n                res.data[i][j] = -1 * m.data[i][j];\r\n        }\r\n    }\r\n    return res;\r\n}\r\n\r\nmatrix exp(matrix m)\r\n{\r\n    matrix res(m.shape[0], m.shape[1]);\r\n    for (int i = 0; i < m.shape[0]; i++)\r\n    {\r\n        for (int j = 0; j < m.shape[1]; j++)\r\n        {\r\n            res.data[i][j] = pow(2.71828, m.data[i][j]);\r\n        }\r\n    }\r\n    return res;\r\n}\r\n\r\nmatrix log(matrix m)\r\n{\r\n    matrix res(m.shape[0], m.shape[1]);\r\n    for (int i = 0; i < m.shape[0]; i++)\r\n    {\r\n        for (int j = 0; j < m.shape[1]; j++)\r\n        {\r\n            if (m.data[i][j] < 0)\r\n            {\r\n                fprintf(stderr, \"Domain error in log\");\r\n                exit(1);\r\n            }\r\n            else if (m.data[i][j] == 0)\r\n                res.data[i][j] = 0;\r\n            else\r\n                res.data[i][j] = log(m.data[i][j]);\r\n        }\r\n    }\r\n    return res;\r\n}\r\n\r\nfloat sum(matrix m)\r\n{\r\n\r\n    float sum = 0;\r\n    for (int i = 0; i < m.shape[0]; i++)\r\n    {\r\n        for (int j = 0; j < m.shape[1]; j++)\r\n        {\r\n            sum += m.data[i][j];\r\n        }\r\n    }\r\n    return sum;\r\n}\r\n\r\nmatrix m_sum(matrix m, int axis = -1)\r\n{\r\n    if (axis == 0)\r\n    {\r\n        matrix res(1, m.shape[1]);\r\n        for (int i = 0; i < m.shape[1]; i++)\r\n        {\r\n            float sum = 0;\r\n            for (int j = 0; j < m.shape[0]; j++)\r\n            {\r\n                sum = sum + m.data[j][i];\r\n            }\r\n            res.data[0][i] = sum;\r\n        }\r\n        return res;\r\n    }\r\n    else if (axis == 1)\r\n    {\r\n        matrix res(m.shape[0], 1);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            float sum = 0;\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                sum = sum + m.data[i][j];\r\n            }\r\n            res.data[i][0] = sum;\r\n        }\r\n        return res;\r\n    }\r\n    else\r\n    {\r\n        matrix res = zeros(1, 1);\r\n        for (int i = 0; i < m.shape[0]; i++)\r\n        {\r\n            for (int j = 0; j < m.shape[1]; j++)\r\n            {\r\n                res.data[0][0] += m.data[i][j];\r\n            }\r\n        }\r\n        return res;\r\n    }\r\n}\r\n\r\nmatrix sigmoid(matrix m)\r\n{\r\n    matrix res(m.shape[0], m.shape[1]);\r\n    for (int i = 0; i < m.shape[0]; i++)\r\n    {\r\n        for (int j = 0; j < m.shape[1]; j++)\r\n        {\r\n            res.data[i][j] = 1.0 / (1.0 + pow(2.71828, -1 * m.data[i][j]));\r\n        }\r\n    }\r\n    return res;\r\n}\r\n\r\nmatrix tanh(matrix m)\r\n{\r\n    matrix res(m.shape[0], m.shape[1]);\r\n    for (int i = 0; i < m.shape[0]; i++)\r\n    {\r\n        for (int j = 0; j < m.shape[1]; j++)\r\n        {\r\n            res.data[i][j] = tanh(m.data[i][j]);\r\n        }\r\n    }\r\n    return res;\r\n}\r\nmatrix relu(matrix m)\r\n{\r\n    matrix res(m.shape[0], m.shape[1]);\r\n    for (int i = 0; i < m.shape[0]; i++)\r\n    {\r\n        for (int j = 0; j < m.shape[1]; j++)\r\n        {\r\n            if (m.data[i][j] >= 0)\r\n            {\r\n                res.data[i][j] = m.data[i][j];\r\n            }\r\n            else\r\n            {\r\n                res.data[i][j] = 0;\r\n            }\r\n        }\r\n    }\r\n    return res;\r\n}\r\n\r\nmatrix normalize(matrix m)\r\n{\r\n    matrix res(m.shape[0], m.shape[1]);\r\n    for (int i = 0; i < m.shape[0]; i++)\r\n    {\r\n        float max = m.data[i][0];\r\n        float min = m.data[i][0];\r\n        for (int j = 0; j < m.shape[1]; j++)\r\n        {\r\n            if (max < m.data[i][j])\r\n            {\r\n                max = m.data[i][j];\r\n            }\r\n            if (min > m.data[i][j])\r\n            {\r\n                min = m.data[i][j];\r\n            }\r\n        }\r\n\r\n        for (int j = 0; j < m.shape[1]; j++)\r\n        {\r\n            res.data[i][j] = (m.data[i][j] - min) / (max - min);\r\n        }\r\n    }\r\n    return res;\r\n}\r\n#endif\r\n\r\n// matrix cost(matrix Y, matrix A_L)\r\n// {\r\n//     float m = Y.shape[1];\r\n//     matrix cost = -1 * m_sum(Y * log(A_L) + (1 - Y) * log(1 - A_L), 1) / m;\r\n//     return cost;\r\n// }\r\n\r\n// int main()\r\n// {\r\n//     matrix m1 = randn(3, 5);\r\n//     print(m1);\r\n//     matrix m2 = sigmoid(m1);\r\n//     print(m2);\r\n//     print(1 - m2);\r\n//     print(log(m2));\r\n// }\r\n\r\n// int main()\r\n// {\r\n//     clock_t start, end;\r\n//     float time;\r\n//     printf(\"Matrix : Computing....\\n\");\r\n//     for (int i = 10; i <= 1000; i += 20)\r\n//     {\r\n//         start = clock();\r\n//         matrix m1 = randn(i, i), m2 = randn(i, i);\r\n//         matrix m3 = dot(m1, m2.T());\r\n//         end = clock();\r\n//         float time = (float)(end - start) / CLOCKS_PER_SEC;\r\n//         printf(\"%f\\n\", time);\r\n\r\n//         //     start = clock();\r\n//         //     MatrixXf m4 = MatrixXf::Random(i, i), m5 = MatrixXf::Random(i, i);\r\n//         //     MatrixXf temp = m4 * m5;\r\n//         //     end = clock();\r\n//         //     time = (float)(end - start) / CLOCKS_PER_SEC;\r\n//         //     printf(\"%f\", time);\r\n//         // }\r\n//     }\r\n// }\r\n\r\n// class test\r\n// {\r\n// private:\r\n//     matrix A = zeros(0, 0), B = zeros(0, 0);\r\n\r\n// public:\r\n//     void get_data(matrix X, matrix Y)\r\n//     {\r\n//         this->A = X;\r\n//         this->B = Y;\r\n//     }\r\n\r\n//     void print_a_b()\r\n//     {\r\n//         this->A.print();\r\n//         this->B.print();\r\n//     }\r\n// };\r\n\r\n// int main()\r\n// {\r\n//     test t;\r\n//     matrix m1=zeros(10 ,4),m2=randn(10,3);\r\n//     t.get_data(m1,m2);\r\n//     t.print_a_b();\r\n//}\r\n\r\n// int main()\r\n// {\r\n// matrix m = randn(100, 100);\r\n// matrix m1 = sigmoid(m);\r\n// matrix m2 = log(m1);\r\n// for (int i = 0; i < 100; i++)\r\n// {\r\n//     for (int j = 0; j < 100; j++)\r\n//     {\r\n//         if (!(m1.data[i][j] < 1 && m1.data[i][j] > 0))\r\n//         {\r\n//             printf(\"Error\");\r\n//         }\r\n//     }\r\n// }\r\n\r\n// float ans;\r\n// ans = 1 / (1 + pow(2.71828, 14));\r\n// printf(\"%f\",ans );\r\n\r\n// printf(\"%f\",log(0.001));\r\n// }\r\n\r\n// int main()\r\n// {\r\n//     matrix m = randn(10, 6);\r\n//     matrix m2 = m(2, 4, 1);\r\n//     m.print();\r\n//     m2.print();\r\n// }", "meta": {"hexsha": "d44061ddbc51d3e477302c42dc21e80149e3d81d", "size": 33406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Matrix_lib/matrix.cpp", "max_stars_repo_name": "Naval-surange/Kratos", "max_stars_repo_head_hexsha": "0c198ed2508f429b62b3b7664e3bbc174806c5bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-07T13:49:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-07T13:49:07.000Z", "max_issues_repo_path": "Matrix_lib/matrix.cpp", "max_issues_repo_name": "Naval-surange/Kratos", "max_issues_repo_head_hexsha": "0c198ed2508f429b62b3b7664e3bbc174806c5bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Matrix_lib/matrix.cpp", "max_forks_repo_name": "Naval-surange/Kratos", "max_forks_repo_head_hexsha": "0c198ed2508f429b62b3b7664e3bbc174806c5bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8480138169, "max_line_length": 182, "alphanum_fraction": 0.3439202538, "num_tokens": 10066, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4098422930795862}}
{"text": "/******************************************************************************\nCopyright (c) 2021 Dmitriy Korchemkin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n******************************************************************************/\n\n#ifndef POLYNOMIALS_ROOTS_HPP\n#define POLYNOMIALS_ROOTS_HPP\n\n#include <Eigen/Dense>\n#include <iosfwd>\n\n#include \"polynomials/assert.hpp\"\n#include \"polynomials/types.hpp\"\n\n#ifndef CERES_PUBLIC_JET_H\nnamespace ceres {\ntemplate <typename Scalar, int N> struct Jet;\n}\n#endif\n\nnamespace polynomials {\n\ntemplate <typename Scalar> struct RealRootFilter {\n  std::optional<Scalar> operator()(const std::complex<Scalar> &c,\n                                   const Scalar &tolerance) const {\n    using std::abs;\n    const auto re = c.real();\n    const auto im = c.imag();\n    const auto abs_re = abs(re);\n    const auto abs_im = abs(im);\n    if (abs_im < abs_re * tolerance)\n      return re;\n    return std::nullopt;\n  }\n\n  std::optional<Scalar> operator()(const std::complex<Scalar> &c) const {\n    const auto re = c.real();\n    const auto im = c.imag();\n    if (im == Scalar(0.))\n      return re;\n    return std::nullopt;\n  }\n};\n\ntemplate <typename Scalar> struct PositiveRealRootFilter {\n  std::optional<Scalar> operator()(const std::complex<Scalar> &c) const {\n    auto real = rrf(c);\n    if (!real)\n      return std::nullopt;\n    if (*real >= Scalar(0.))\n      return real;\n    return std::nullopt;\n  }\n\n  std::optional<Scalar> operator()(const std::complex<Scalar> &c,\n                                   const Scalar &tolerance) const {\n    auto real = rrf(c, tolerance);\n    if (!real)\n      return std::nullopt;\n    if (*real >= Scalar(0.))\n      return real;\n    return std::nullopt;\n  }\n\n  RealRootFilter<Scalar> rrf;\n};\n\ntemplate <typename Polynomial,\n          bool fixed_degree = Polynomial::DegreeAtCompileTime != Dynamic>\nstruct QuotientRingMulXImpl;\n\ntemplate <typename Polynomial>\nstruct QuotientRingMulX : public QuotientRingMulXImpl<Polynomial> {\n  using Base = QuotientRingMulXImpl<Polynomial>;\n\n  template <typename... Args> QuotientRingMulX(Args... args) : Base(args...) {}\n};\n\ntemplate <typename Polynomial> struct QuotientRingMulXImpl<Polynomial, true> {\n  static constexpr Index DegreeAtCompileTime = Polynomial::DegreeAtCompileTime;\n  static constexpr Index MaxDegreeAtCompileTime =\n      Polynomial::MaxDegreeAtCompileTime;\n  using Scalar = typename Polynomial::Scalar;\n\n  using CompanionMatrix =\n      Eigen::Matrix<Scalar, DegreeAtCompileTime, DegreeAtCompileTime>;\n  using ComplexRoots = typename CompanionMatrix::EigenvaluesReturnType;\n  using RealRoots =\n      Eigen::Matrix<Scalar, Eigen::Dynamic, 1, 0, DegreeAtCompileTime, 1>;\n\n  QuotientRingMulXImpl(const Polynomial &p) {\n    const Scalar lead_term = p[DegreeAtCompileTime];\n    matrix\n        .template bottomLeftCorner<DegreeAtCompileTime - 1,\n                                   DegreeAtCompileTime - 1>()\n        .setIdentity();\n    matrix.col(DegreeAtCompileTime - 1) =\n        -p.coeffs().template head<DegreeAtCompileTime>() *\n        (Scalar(1.) / lead_term);\n    matrix.row(0).template head<DegreeAtCompileTime - 1>().setZero();\n  }\n\n  operator CompanionMatrix() const { return matrix; }\n\n  ComplexRoots complex_roots() const { return matrix.eigenvalues(); }\n\n  template <typename Op, typename... Args>\n  RealRoots filter_roots(Args... args) const {\n    Index count_valid = 0;\n    Scalar rr[DegreeAtCompileTime];\n    const auto roots = complex_roots();\n    const Op filter;\n    for (Index i = 0; i < DegreeAtCompileTime; ++i) {\n      auto real = filter(roots[i], args...);\n      if (!real)\n        continue;\n      rr[count_valid++] = *real;\n    }\n    return Eigen::Map<const RealRoots>(rr, count_valid, 1);\n  }\n\n  template <typename... Args> RealRoots real_roots(Args... args) const {\n    return filter_roots<RealRootFilter<Scalar>, Args...>(args...);\n  }\n\n  template <typename... Args>\n  RealRoots positive_real_roots(Args... args) const {\n    return filter_roots<PositiveRealRootFilter<Scalar>, Args...>(args...);\n  }\n\nprivate:\n  CompanionMatrix matrix;\n};\n\ntemplate <typename Polynomial> struct QuotientRingMulXImpl<Polynomial, false> {\n  static constexpr Index DegreeAtCompileTime = Polynomial::DegreeAtCompileTime;\n  static constexpr Index MaxDegreeAtCompileTime =\n      Polynomial::MaxDegreeAtCompileTime;\n  using Scalar = typename Polynomial::Scalar;\n\n  using CompanionMatrix =\n      Eigen::Matrix<Scalar, DegreeAtCompileTime, DegreeAtCompileTime, 0,\n                    MaxDegreeAtCompileTime, MaxDegreeAtCompileTime>;\n  using ComplexRoots = typename CompanionMatrix::EigenvaluesReturnType;\n  using RealRoots =\n      Eigen::Matrix<Scalar, Eigen::Dynamic, 1, 0, MaxDegreeAtCompileTime, 1>;\n\n  QuotientRingMulXImpl(const Polynomial &p) {\n    const Index degree = p.degree();\n    matrix.resize(degree, degree);\n    const Scalar lead_term = p[degree];\n    matrix.bottomLeftCorner(degree - 1, degree - 1).setIdentity();\n    matrix.col(DegreeAtCompileTime - 1) =\n        -p.coeffs().head(degree) * (Scalar(1.) / lead_term);\n    matrix.row(0).head(degree - 1).setZero();\n  }\n\n  operator CompanionMatrix() const { return matrix; }\n\n  ComplexRoots complex_roots() const { return matrix.eigenvalues(); }\n\n  RealRoots real_roots() const {\n    Index count_real = 0;\n    const Index degree = dim();\n    Eigen::Matrix<Scalar, MaxDegreeAtCompileTime, 1> rr(degree, 1);\n\n    const auto roots = complex_roots();\n\n    for (Index i = 0; i < degree; ++i) {\n      auto im = roots[i].imag();\n      if (im != Scalar(0.))\n        continue;\n      auto re = roots[i].real();\n      rr[count_real++] = re;\n    }\n    return Eigen::Map<const RealRoots>(rr, count_real, 1);\n  }\n\n  RealRoots real_roots(const Scalar &tolerance) const {\n    Index count_real = 0;\n    const Index degree = dim();\n    Eigen::Matrix<Scalar, MaxDegreeAtCompileTime, 1> rr(degree, 1);\n\n    const auto roots = complex_roots();\n\n    for (Index i = 0; i < degree; ++i) {\n      auto re = roots[i].real();\n      auto are = std::abs(re);\n      auto aim = std::abs(roots[i].imag);\n      if (!(aim < tolerance * are))\n        continue;\n      rr[count_real++] = re;\n    }\n    return Eigen::Map<const RealRoots>(rr, count_real, 1);\n  }\n\n  Index dim() const { return matrix.rows(); }\n\nprivate:\n  CompanionMatrix matrix;\n};\n\ntemplate <typename Poly, template <typename> typename Algo, typename Scalar>\nstruct RootFinder {\n  using Algorithm = Algo<Poly>;\n  using ComplexRoots = typename Algorithm::ComplexRoots;\n  using RealRoots = typename Algorithm::RealRoots;\n\n  template <typename... Args>\n  static RealRoots real_roots(const Poly &p, Args... args) {\n    return Algorithm(p).real_roots(args...);\n  }\n\n  template <typename... Args>\n  static RealRoots positive_real_roots(const Poly &p, Args... args) {\n    return Algorithm(p).positive_real_roots(args...);\n  }\n\n  template <typename... Args>\n  static ComplexRoots complex_roots(const Poly &p, Args... args) {\n    return Algorithm(p).complex_roots(args...);\n  }\n};\n\ntemplate <typename Poly, template <typename> typename Algo, typename Scalar,\n          int N>\nstruct RootFinder<Poly, Algo, ceres::Jet<Scalar, N>> {\n  using ScalarPoly = DensePoly<Scalar, Poly::DegreeAtCompileTime,\n                               Poly::MaxDegreeAtCompileTime>;\n  using ScalarRootFinder = RootFinder<ScalarPoly, Algo>;\n  using ScalarAlgorithm = Algo<ScalarPoly>;\n  using ScalarComplexRoots = typename ScalarAlgorithm::ComplexRoots;\n  using ScalarRealRoots = typename ScalarAlgorithm::RealRoots;\n  using Jet = ceres::Jet<Scalar, N>;\n  using ComplexJet = ceres::Jet<typename ScalarComplexRoots::Scalar, N>;\n\n  using JetComplexRoots = Eigen::Matrix<ComplexJet, Poly::DegreeAtCompileTime,\n                                        1, 0, Poly::MaxDegreeAtCompileTime, 1>;\n  using JetRealRoots =\n      Eigen::Matrix<Jet, Eigen::Dynamic, 1, 0, Poly::MaxDegreeAtCompileTime, 1>;\n\n  static ScalarPoly cast(const Poly &p) {\n    ScalarPoly sp(p.degree());\n    const Index num_coeffs = p.degree() + 1;\n    for (Index i = 0; i < num_coeffs; ++i)\n      sp.coeffs()[i] = p.coeffs()[i].a;\n    return sp;\n  }\n\n  template <typename T>\n  static ceres::Jet<T, N>\n  process_root(const Poly &poly, const ScalarPoly &scalar_poly, const T &root) {\n    ceres::Jet<T, N> res;\n    res.a = root;\n    res.v.setZero();\n    const T denom(-scalar_poly.df(root));\n    const auto &coeffs = poly.coeffs();\n    const Index num_coeffs = coeffs.size();\n    T root_pow = T(1.);\n    for (Index i = 0; i < num_coeffs; ++i) {\n      // dx / da_k = -x^k / f'\n      // dx / dp_i = \\sum_k dx / da_k da_k / dp_i\n      // dx / dp = (\\sum_k -x^k [da_k / dp]) / f'\n\n      res.v += root_pow * coeffs[i].v;\n      root_pow *= root;\n    }\n    res.v /= denom;\n    return res;\n  }\n\n  template <typename... Args>\n  static JetComplexRoots complex_roots(const Poly &p, Args... args) {\n    const ScalarPoly scalar = cast(p);\n    const ScalarComplexRoots scalar_roots =\n        ScalarRootFinder::complex_roots(scalar, args...);\n    const Index num_roots = scalar_roots.size();\n    JetComplexRoots jet(num_roots);\n    for (Index i = 0; i < num_roots; ++i)\n      jet[i] = process_root(p, scalar, scalar_roots[i]);\n    return jet;\n  }\n\n  template <typename... Args>\n  static JetRealRoots real_roots(const Poly &p, Args... args) {\n    const ScalarPoly scalar = cast(p);\n    const ScalarRealRoots scalar_roots =\n        ScalarRootFinder::real_roots(scalar, args...);\n    const Index num_real_roots = scalar_roots.size();\n    JetRealRoots jet(num_real_roots);\n    for (Index i = 0; i < num_real_roots; ++i)\n      jet[i] = process_root(p, scalar, scalar_roots[i]);\n    return jet;\n  }\n\n  template <typename... Args>\n  static JetRealRoots positive_real_roots(const Poly &p, Args... args) {\n    const ScalarPoly scalar = cast(p);\n    const ScalarRealRoots scalar_roots =\n        ScalarRootFinder::positive_real_roots(scalar, args...);\n    const Index num_real_roots = scalar_roots.size();\n    JetRealRoots jet(num_real_roots);\n    for (Index i = 0; i < num_real_roots; ++i)\n      jet[i] = process_root(p, scalar, scalar_roots[i]);\n    return jet;\n  }\n};\n\n} // namespace polynomials\n\n#endif\n", "meta": {"hexsha": "703887d23fa87d7f43a190caeefe52af9f3223da", "size": 11098, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/polynomials/src/roots.hpp", "max_stars_repo_name": "DmitriyKorchemkin/polynomials", "max_stars_repo_head_hexsha": "4be10df5309b3301a48beac9ee578fb930743606", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-13T10:46:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T10:46:55.000Z", "max_issues_repo_path": "include/polynomials/src/roots.hpp", "max_issues_repo_name": "DmitriyKorchemkin/polynomials", "max_issues_repo_head_hexsha": "4be10df5309b3301a48beac9ee578fb930743606", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/polynomials/src/roots.hpp", "max_forks_repo_name": "DmitriyKorchemkin/polynomials", "max_forks_repo_head_hexsha": "4be10df5309b3301a48beac9ee578fb930743606", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7325227964, "max_line_length": 80, "alphanum_fraction": 0.6673274464, "num_tokens": 2842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4098422930795862}}
{"text": "#include <fstream>\n#include <unordered_map>\n\n#include <boost/format.hpp>\n\n#include \"local_push.h\"\n#include \"file_serialization.h\"\n#include \"util/log.h\"\nusing boost::format;\n\ndouble cal_rmax(double c, double epsilon) {\n    return (1 - c) * epsilon;\n}\n\ndouble cal_rmax(DirectedG &g, double c, double epsilon, double delta) {\n    // calculate r_max\n    int m, n;\n    m = num_edges(g);\n    n = num_vertices(g);\n    double d = double(m) / double(n);\n    // cout << d << endl;\n    double a = (1 - c) * pow(d, 2) * pow(epsilon, 2) / (c * log(2 / delta));\n    // cout << pow(a,1.0/3.0) << endl;\n    return pow(a, 1.0 / 3.0);\n}\n\nvoid LocalPush::push(NodePair &pab, double inc) {\n    // the actually action of push\n    n_push++;\n    R[pab] += inc;\n    // cout << pab.first << \" \" << pab.second << endl ;\n    if (fabs(R[pab]) > r_max) {\n        // Q.insert(pab);\n        if (marker[pab] == false) {\n            Q.push(pab);\n            marker[pab] = true;\n        }\n    }\n}\n\nLocalPush::LocalPush(DirectedG &g, string gName_, double c_, double epsilon_, size_t n_) {\n    // init data members\n    /* init data memebrs */\n    g_name = gName_;\n    c = c_;\n    // r_max = r_max_;\n    epsilon = epsilon_;\n    r_max = cal_rmax(c, epsilon);\n    n = n_;\n    string path = get_edge_list_path(gName_);\n    n_push = 0;\n    cpu_time = -1; // set the init value\n\n\n    // check the local puah exits\n    // string data_path =get_file_path_base() + \".P\";\n    // cout << \"data path \" << data_path << endl;\n    // if(file_exists(data_path)){ // local push from start\n    //     cout << \"file exisis..\" << endl;\n    //     load();\n    // }else{ // file exists\n    //     /* init the P and R */\n    //     cout << \"file not exists, compute from scratch\" << endl;\n    //     for(int i=0;i<n;i++){\n    //         NodePair np(i,i);\n    //         R.insert({np,1});\n    //         Q.push(np);\n    //         marker[np] = true;\n    //     }\n    // }\n}\n\nFull_LocalPush::Full_LocalPush(DirectedG &g, string name, double c_, double r_max_, size_t n_) : LocalPush(g, name, c_,\n                                                                                                           r_max_, n_) {\n    string data_path = get_file_path_base() + \".P\";\n    cout << \"data path \" << data_path << endl;\n    if (file_exists(data_path)) { // local push from start\n        cout << \"file exisis..\" << endl;\n        load();\n    } else { // file exists\n        /* init the P and R */\n        P.add(n);\n        R.add(n);\n        marker.add(n);\n\n        cout << \"file not exists, compute from scratch\" << endl;\n        for (int i = 0; i < n; i++) {\n            NodePair np(i, i);\n            // R.insert({np,1});\n            R[np] = 1;\n            Q.push(np);\n            marker[np] = true;\n        }\n    }\n}\n\nReduced_LocalPush::Reduced_LocalPush(DirectedG &g, string name, double c_, double r_max_, size_t n_) : LocalPush(g,\n                                                                                                                 name,\n                                                                                                                 c_,\n                                                                                                                 r_max_,\n                                                                                                                 n_) {\n    string data_path = get_file_path_base() + \".P\";\n    // cout << \"data path \" << data_path << endl;\n    if (file_exists(data_path)) { // local push from start\n        // cout << \"file exisis..\" << endl;\n        load();\n        // cout << g_name << \" \" << r_max << \" \" << c << \" \" << n << endl;\n    } else { // file exists\n        /* init the P and R */\n        P.add(n);\n        R.add(n);\n        marker.add(n);\n\n        cout << \"file not exists, compute from scratch!!!\" << endl;\n        for (int i = 0; i < n; i++) {\n            NodePair np(i, i);\n            // R.insert({np,1});\n            R[np] = 1;\n            Q.push(np);\n            marker[np] = true;\n        }\n    }\n}\n\nvoid Reduced_LocalPush::push_to_neighbors(DirectedG &g, NodePair &np, double current_residual) {\n    // the push method using reduced linear system\n    // out-neighbros of a,b\n    DirectedG::out_edge_iterator\n            outi_iter,\n            outi_end,\n            outj_iter,\n            outj_end;\n    bool is_singleton = np.first == np.second ? true : false;\n    // /* only push to partial pairs*/\n    size_t out_degree_i = out_degree(np.first, g);\n    size_t out_degree_j = out_degree(np.second, g);\n\n    tie(outi_iter, outi_end) = out_edges(np.first, g);\n    tie(outj_iter, outj_end) = out_edges(np.second, g);// init the iterator\n    /*the indicator whether the position is common neighbor */\n    vector<bool> outs_i_common(out_degree_i, false);\n    vector<bool> outs_j_common(out_degree_j, false);\n    // cout << \"------\" << endl;\n\n    tie(outi_iter, outi_end) = out_edges(np.first, g);\n    if (is_singleton) {\n        /* starting push for singleton nodes*/\n        for (; outi_iter != outi_end; outi_iter++) {\n            tie(outj_iter, outj_end) = out_edges(np.second, g);// init the iterator\n            auto out_a = target(*outi_iter, g); // out-neighbor\n            for (; outj_iter != outj_end; outj_iter++) {\n                auto out_b = target(*outj_iter, g);\n                auto indegree_a = in_degree(out_a, g);\n                auto indegree_b = in_degree(out_b, g);\n                auto total_in = indegree_a * indegree_b;\n                if (out_a < out_b) { // only push to partial pairs for a < b\n                    NodePair pab(out_a, out_b); // the node-pair to be pushed to\n                    double inc = c * current_residual / total_in;\n                    push(pab, inc); // do the push action\n                }\n            }\n        }\n    } else {\n        /* mark the common neighbors */\n        size_t i, j;\n        for (i = 0; i < out_degree_i; i++) {\n            auto a = target(*(outi_iter + i), g);\n            for (j = 0; j < out_degree_j; j++) {\n                auto b = target(*(outj_iter + j), g);\n                if (a == b) {\n                    outs_i_common[i] = true;\n                    outs_j_common[j] = true;\n                    break;\n                }\n            }\n        }\n        /* starting push for non-singleton nodes*/\n        auto i_begin_iter = outi_iter; // mark the begining iterator\n        for (; outi_iter != outi_end; outi_iter++) {\n            tie(outj_iter, outj_end) = out_edges(np.second, g);// init the iterator\n            auto j_begin = outj_iter;\n            bool is_i_common = outs_i_common[outi_iter - i_begin_iter];// indicator of whether i is a common neighbor\n            for (; outj_iter != outj_end; outj_iter++) {\n                bool is_j_common = outs_j_common[outj_iter - j_begin];\n                auto out_a = target(*outi_iter, g); // out-neighbor\n                auto out_b = target(*outj_iter, g);\n                auto indegree_a = in_degree(out_a, g);\n                auto indegree_b = in_degree(out_b, g);\n                auto total_in = indegree_a * indegree_b;\n                double inc = c * current_residual / total_in;\n                if (out_a == out_b) { //don't push to singleton nodes\n                    continue;\n                }\n                bool oa_less_ob = out_a < out_b ? true : false;\n                // cout << \"i com :\" << is_i_common << \" j com: \" << is_j_common << endl;\n                if (!oa_less_ob) {\n                    swap(out_a, out_b);\n                }\n                NodePair pab(out_a, out_b);\n                if (!is_i_common) {\n                    // i is not common neighbonr\n                    push(pab, inc);\n                } else {\n                    // i is a common neighbor\n                    if (is_j_common) {\n                        if (oa_less_ob) {\n                            push(pab, 2 * inc); // push twice for two commons\n                        }\n                    } else {// notmal case\n                        push(pab, inc);\n                    }\n                }\n            }\n        }\n    }\n    // cout << \"------\" << endl;\n}\n\nvoid Full_LocalPush::push_to_neighbors(DirectedG &g, NodePair &np, double current_residual) {\n    DirectedG::out_edge_iterator\n            outi_iter,\n            outi_end,\n            outj_iter,\n            outj_end;\n\n    tie(outi_iter, outi_end) = out_edges(np.first, g);\n    for (; outi_iter != outi_end; outi_iter++) {\n        auto out_a = target(*outi_iter, g); // out-neighbor\n        tie(outj_iter, outj_end) = out_edges(np.second, g);\n        for (; outj_iter != outj_end; outj_iter++) {\n            auto out_b = target(*outj_iter, g);\n            if (out_a == out_b) {\n                continue;\n            }\n            auto indegree_a = in_degree(out_a, g);\n            auto indegree_b = in_degree(out_b, g);\n            auto total_in = indegree_a * indegree_b;\n            NodePair pab(out_a, out_b);\n            double inc = c * current_residual / total_in;\n            push(pab, inc);\n        }\n    }\n}\n\ndouble Full_LocalPush::how_much_residual_to_push(DirectedG &g, NodePair &np) {\n    return R[np];\n}\n\ndouble Reduced_LocalPush::how_much_residual_to_push(DirectedG &g, NodePair &np) {\n    // determine the residual value for current pair to push\n    double r = R[np];\n    if (np.first == np.second) { //singleton node\n        return r - r_max / (1 - c); // singleton nodes do not need to push all residual as 1\n        // return r;\n        // return 1;\n    }\n    /* check whether np forms a self-loop */\n    if (edge(np.first, np.second, g).second == true &&\n        edge(np.second, np.first, g).second == true) { // check whether exists reverse edge\n        auto in_deg_a = in_degree(np.first, g);\n        auto in_deg_b = in_degree(np.second, g);\n        double alpha = c / (in_deg_a * in_deg_b);\n        int k = ceil(log(r_max / fabs(r)) / log(alpha));\n        double residual_to_push = (1 - pow(alpha, k)) * r / (1 - alpha);\n        return residual_to_push;\n    } else {\n        auto push_residual = r;\n        return push_residual;\n        // optimize for neighbor-loop\n        // double current_max = 0;\n        // double max_m = 0;\n        // double alpha_i;\n        // double alpha_0;\n        // DirectedG::out_edge_iterator out_a_it, out_a_end;\n        // DirectedG::out_edge_iterator out_b_it, out_b_end;\n        // alpha_0 = c / (in_degree(np.first,g) * in_degree(np.second,g));\n        // tie(out_a_it, out_a_end) = out_edges(np.first,g);\n        // for(;out_a_it != out_a_end; out_a_it ++){\n        //     tie(out_b_it, out_b_end) = out_edges(np.second,g);\n        //     auto out_a = target(*out_a_it,g);\n        //     auto in_a = in_degree(out_a,g);\n        //     bool out_a_to_first = edge(out_a,np.first,g).second ;// whether there is a reverse link from  out_a to np.first\n        //     for(;out_b_it!=out_b_end;out_b_it ++){\n        //         auto out_b = target(*out_b_it,g);\n        //         auto in_b = in_degree(out_b,g);\n        //         double current_alpha_i = c / (in_a * in_b);\n        //         bool out_b_to_second = edge(out_b,np.second,g).second;// whether there is a reverse link from out_b to np.second \n        //         if(out_a_to_first && out_b_to_second){ // is a neighbor-loop\n        //             NodePair bnp(out_a, out_b);\n        //             double m = fabs(R[bnp] + r * current_alpha_i);\n        //             if(m > r_max && m > current_max){\n        //                 current_max = m;\n        //                 alpha_i = current_alpha_i;\n        //                 // if(fabs(r_x) > current_max){\n        //                 //     current_max = r_x;\n        //                 // }\n        //             }\n        //         }\n        //     }\n        // }\n        // if(current_max > 0){ // if there is any self lop\n        //     int k = int(ceil(log(r_max / (alpha_0 * current_max))/ log(alpha_0 * alpha_i))) + 1;\n        //     double r_x= 0; // the residual to be pushed\n        //     r_x = r + alpha_0 * current_max * (1 - pow(alpha_0 * alpha_i, k)) / (1 - alpha_0 * alpha_i); \n        //     // cout << \"neighbor loop..\" << r_x << endl;\n        //     return r_x;\n        // }else{\n        //     return r;\n        // }\n    }\n\n\n    // // non-singleton nodes\n\n    // // compute optimal value to push\n    // double sum_airi =  0;\n    // double sum_ai_square = 0;\n    // DirectedG::out_edge_iterator out_a_it, out_a_end;\n    // DirectedG::out_edge_iterator out_b_it, out_b_end;\n    // for(;out_a_it != out_a_end; out_a_it ++){\n    //     auto out_a = target(*out_a_it,g);\n    //     auto in_a = in_degree(out_a,g);\n    //     for(;out_b_it!=out_b_end;out_b_it ++){\n    //         auto out_b = target(*out_b_it,g);\n    //         auto in_b = in_degree(out_b,g);\n    //         double alpha = c / (in_a * in_b);\n    //         sum_airi += alpha * R[NodePair(out_a, out_b)];\n    //         sum_ai_square += pow(alpha,2);\n    //     }\n    // }\n    // r = (r - sum_airi) / (1 + sum_ai_square);\n\n    /* determine the residual to push by computing the maximum overlapping interval */\n    // cout << \"current r \" << r << endl;\n    // auto out_deg_a = out_degree(np.first,g);\n    // auto out_deg_b = out_degree(np.second,g);\n    // auto total_out = out_deg_a * out_deg_b;\n    // double start[total_out+1];\n    // double end[total_out+1];\n    // size_t i = 0;\n    // if(edge(np.first,np.second,g).second == true && edge(np.second, np.first,g).second == true){\n    //     // self loop\n    //     double alpha = c / (in_degree(np.first,g) * in_degree(np.second,g));\n    //     start[i] = (r_max -r ) / (alpha - 1);\n    //     end[i] = (-r_max - r) / (alpha - 1);\n    // }else{\n    //     double alpha = c / (in_degree(np.first,g) * in_degree(np.second,g));\n    //     start[i] = r-r_max;\n    //     end[i] = r + r_max;\n    // }\n\n    // i++;\n\n    // DirectedG::out_edge_iterator out_a_it, out_a_end;\n    // DirectedG::out_edge_iterator out_b_it, out_b_end;\n    // for(;out_a_it != out_a_end; out_a_it ++){\n    //     auto out_a = target(*out_a_it,g);\n    //     auto in_a = in_degree(out_a,g);\n    //     for(;out_b_it!=out_b_end;out_b_it ++){\n    //         auto out_b = target(*out_b_it,g);\n    //         auto in_b = in_degree(out_b,g);\n    //         double alpha = c / (in_a * in_b);\n    //         double r_i = R[NodePair(out_a, out_b)];\n    //         auto current_start = - (r_max + r_i) / alpha;\n    //         auto current_end = (r_max - r_i) / alpha;\n    //         if(current_start > end[0] || current_end < start[0]){\n    //             // filter out the nodes that conflicts with source node\n    //             continue;\n    //         }else{\n    //             if(current_start < start[0]){\n    //                 current_start = start[0];\n    //             }\n    //             if(current_end > end[0]){\n    //                 current_end = end[0];\n    //             }\n    //             start[i] = current_start;\n    //             end[i] = current_end;\n    //             i ++;\n    //         }\n    //     }\n    // }\n    // // for(i = 0; i< total_out +1;i++){\n    // //     int a;\n    // //     cout << \"lower bound: \" << start[i] << \" upper bound: \"<< end[i] << endl;\n    // //     cin >> a;\n    // // }\n\n    // double push_residual = findMaxInterval(start, end, i); // i is the length \n}\n\nvoid LocalPush::local_push(DirectedG &g) { // local push given current P and R\n    // cout << r_max << endl;\n    auto start = std::chrono::high_resolution_clock::now();\n    double sum_of_est = 0;\n\n    while (!Q.empty()) {\n        NodePair np = Q.front();\n        Q.pop();\n        marker[np] = false;\n\n        double residual_to_push = how_much_residual_to_push(g, np);\n        sum_of_est += residual_to_push;\n\n        R[np] -= residual_to_push;\n        P[np] += residual_to_push;\n        push_to_neighbors(g, np, residual_to_push); // push residuals to neighbros of np\n    }\n    auto finish = std::chrono::high_resolution_clock::now();\n    std::chrono::duration<double> elapsed = finish - start;\n#ifdef OUTPUT\n    if (cpu_time == -1) {\n        cpu_time = elapsed.count();\n        mem_size = getValue();\n    }\n#endif\n}\n\nvoid LocalPush::save() {\n    // save data to disk\n    // save P\n    string p_path = get_file_path_base() + \".P\";\n    P.save(p_path);\n    // FILE *outP = fopen(p_path.c_str(), \"wb\");\n    // cout << \"saving P to \" << p_path << endl;\n    // P.serialize(FileSerializer(), outP);\n    // fclose(outP);\n    //save R\n    string r_path = get_file_path_base() + \".R\";\n    R.save(r_path);\n    // FILE *outR = fopen(r_path.c_str(), \"wb\");\n    // cout << \"saving R to \" << r_path << endl;\n    // R.serialize(FileSerializer(), outR);\n    // fclose(outR);\n\n    ofstream out;\n    // // save meta info\n    string meta_path = get_file_path_base() + \".meta\";\n    out.open(meta_path);\n    out << g_name << endl;\n    out << n << endl;\n    out << epsilon << endl;\n    out << c << endl;\n    out << cpu_time << endl;\n    out << mem_size << endl;\n    auto p_size = P.size();\n    auto r_size = R.size();\n    out << p_size << endl;\n    out << r_size << endl;\n    out << double(p_size) / (n * n) << endl;\n    out << double(r_size) / (n * n) << endl;\n    out.close();\n\n    // // save the experimental data\n    // string exp_path =get_file_path_base()+\".exp\";\n    // out.open(exp_path);\n    // out << n << endl;\n    // cout << c << endl;\n    // cout << epsilon << endl;\n    // out.close();\n    // save exp data\n    cout << \"save complete\" << endl;\n\n}\n\nvoid LocalPush::load() {\n    // load existing local push data\n    // load P\n    string p_path = get_file_path_base() + \".P\";\n    P.load(p_path);\n    // FILE *inP = fopen(p_path.c_str(), \"rb\");\n    // cout << \"loading P to \" << p_path << endl;\n    // P.unserialize(FileSerializer(), inP);\n    // fclose(inP);\n    //load R\n    string r_path = get_file_path_base() + \".R\";\n    R.load(r_path);\n    // FILE *inR = fopen(r_path.c_str(), \"rb\");\n    // cout << \"loading R to \" << r_path << endl;\n    // R.unserialize(FileSerializer(), inR);\n    // fclose(inR);\n\n    string meta_path = get_file_path_base() + \".meta\";\n    ifstream in;\n    in.open(meta_path);\n    in >> g_name >> n >> epsilon >> c >> cpu_time >> mem_size;\n    r_max = cal_rmax(c, epsilon);\n    marker.add(n); // initialize marker\n    in.close();\n}\n\nvoid LocalPush::show() {\n    // cout << P.size() << endl;\n    // for(auto &item:P){\n    //     cout << \"(\" << item.first.first << \",\" << item.first.second << \"): \" << item.second << endl;\n    // }\n}\n\nstring Reduced_LocalPush::get_file_path_base() {\n    // return the file path, exluding the suffix\n    return LOCAL_PUSH_DIR + str(format(\"RLP_%s-%.3f-%.6f\") % g_name % c % epsilon);\n}\n\nstring Full_LocalPush::get_file_path_base() {\n    // return the file path, exluding the suffix\n    return LOCAL_PUSH_DIR + str(format(\"FLP_%s-%.3f-%.6f\") % g_name % c % epsilon);\n}\n\ndouble Full_LocalPush::query_P(unsigned long a, unsigned long b) {\n    return P.query(a, b);\n}\n\ndouble Full_LocalPush::query_R(DirectedG::vertex_descriptor a, DirectedG::vertex_descriptor b) {\n    return R.query(a, b);\n}\n\nvoid Full_LocalPush::insert(DirectedG::vertex_descriptor u, DirectedG::vertex_descriptor v, DirectedG &g) {\n    DirectedG::vertex_iterator v_it, v_end;\n    tie(v_it, v_end) = vertices(g);\n    auto in_deg_v = in_degree(v, g);\n    for (; v_it != v_end; v_it++) {\n        auto a = *v_it;\n        if (a != v) {\n            update_residual(u, v, a, g, in_deg_v);\n        } else {\n            // a == v\n            R[NodePair(a, a)] = 1 - P.query(a, a);\n        }\n    }\n}\n\nvoid Full_LocalPush::update_residual(DirectedG::vertex_descriptor u, DirectedG::vertex_descriptor v,\n                                     DirectedG::vertex_descriptor a, DirectedG &g, int in_deg_v) {\n    // 1st: accumulate estimates\n    DirectedG::in_edge_iterator in_a_it, in_a_end;\n    tie(in_a_it, in_a_end) = in_edges(a, g);\n    float estimation_sum = 0;\n    for (; in_a_it != in_a_end; in_a_it++) {\n        auto ina = source(*in_a_it, g);\n        estimation_sum += P.query(u, ina);\n    }\n\n    // 2nd: update residual\n    auto np = NodePair(v, a);\n    float left_part = c * estimation_sum / (in_deg_v + 1) / in_degree(a, g);\n    float right_part = (P.query(v, a) + R.query(v, a)) / in_deg_v;\n    R[np] = left_part - right_part;\n    // 3rd: update queue\n    if (fabs(R[np]) > r_max) {\n        if (!marker[np]) {\n            Q.push(np);\n            marker[np] = true;\n        }\n    }\n}\n\nvoid LocalPush::insert(DirectedG::vertex_descriptor u, DirectedG::vertex_descriptor v,\n                       DirectedG &g) {\n    // insert edge(u,v) to g, noted we assume g is already updated, and we just update P and R\n    DirectedG::vertex_iterator v_it, v_end;\n    tie(v_it, v_end) = vertices(g);\n    for (; v_it != v_end; v_it++) {\n        auto a = *v_it;\n//        auto in_deg_v = in_degree(v, g); // the new degree of v\n        if (a > v) {\n            update_residual(g, v, a);\n        } else if (a < v) {\n            update_residual(g, a, v);\n        } else {\n            // a == v\n            R[NodePair(a, a)] = 1 - P[NodePair(a, a)];\n        }\n    }\n//    local_push(g);\n}\n\nvoid LocalPush::remove(DirectedG::vertex_descriptor u, DirectedG::vertex_descriptor v,\n                       DirectedG &g) {\n    // remove edge(a,b) to g, noted we assume g is already updated, and we just update P and R\n}\n\ndouble LocalPush::query_P(DirectedG::vertex_descriptor a, DirectedG::vertex_descriptor b) {\n    if (a > b) {\n        return P[NodePair(b, a)];\n    } else {\n        return P[NodePair(a, b)];\n    }\n}\n\ndouble LocalPush::query_R(DirectedG::vertex_descriptor a, DirectedG::vertex_descriptor b) {\n    if (a > b) {\n        return R[NodePair(b, a)];\n    } else {\n        return R[NodePair(a, b)];\n    }\n}\n\nvoid Reduced_LocalPush::update_residual(DirectedG &g, DirectedG::vertex_descriptor a, DirectedG::vertex_descriptor b) {\n    // cout << \"-----\" << endl;\n    // cout << \"updating residual \"<< a << \" \" << b << endl;\n    NodePair np(a, b); // a < b\n    PairMarker indicator; // the indicator of in-neighbors of (a,b)\n    DirectedG::in_edge_iterator in_a_it, in_a_end, in_b_it, in_b_end;\n    tie(in_a_it, in_a_end) = in_edges(a, g);\n    auto in_deg_a = in_degree(a, g);\n    auto in_deg_b = in_degree(b, g);\n    if (in_deg_a * in_deg_b > 0) {\n//        cout << format(\"in_deg_a:%s, in_deg_b:%s\") % in_deg_a % in_deg_b << endl;\n        double sum_neighbor_residuals = 0;\n        for (; in_a_it != in_a_end; in_a_it++) {\n            tie(in_b_it, in_b_end) = in_edges(b, g);\n            for (; in_b_it != in_b_end; in_b_it++) {\n                auto ina = source(*in_a_it, g);\n                auto inb = source(*in_b_it, g);\n                // indicator[NodePair(min(ina,inb), max(ina,inb))] = true;\n                sum_neighbor_residuals += P[NodePair(min(ina, inb), max(ina, inb))];\n            }\n        }\n        // for(auto& item:indicator){\n        //     // cout << \"collect neighbor P (\" << item.first.first\n        //     //     << \",\" << item.first.second <<\"): \" << P[item.first]  << endl;\n        //     sum_neighbor_residuals += P[item.first]; // item.first is the node pair\n        // }\n        R[np] = c * sum_neighbor_residuals / (in_deg_a * in_deg_b) - P[np];\n        // cout << \"neighbros residuals \" << sum_neighbor_residuals << endl;\n        // cout << \" new residual \" << R[np] <<  \" its current estimates \" << P[np] << endl;\n        if (fabs(R[NodePair(a, b)]) > r_max) {\n            if (marker[np] == false) {\n                Q.push(np);\n                marker[np] = true;\n            }\n        }\n    }\n}\n\n// dynamic update support: deleting and inserting edge, time complexity: O(E)\nvoid Reduced_LocalPush::update_residuals_by_deleting_edge(DirectedG &g, DirectedG::vertex_descriptor u,\n                                                          DirectedG::vertex_descriptor v) {\n    // udpate residual when an edge (u,v) is removed from G\n    // assumption: G has not been updated, (u,v) exists in G\n    // a: the iterated node over G\n    // v: the node whose in-neighbor is changed\n    DirectedG::vertex_iterator v_begin, v_end, v_it;\n    tie(v_begin, v_end) = vertices(g);\n    for (v_it = v_begin; v_it != v_end; v_it++) {\n        auto a = *v_it;\n        if (a != v && in_degree(a, g) != 0) {\n            NodePair np = a < v ? NodePair(a, v) : NodePair(v, a); // the node pair to be updated\n\n            DirectedG::in_edge_iterator in_a_iter, in_a_begin, in_a_end;\n            double P_av = P.query(np.first, np.second); // current P(a,v)\n            auto &R_av_ref = R[np]; // current R(a,v)\n            double updated_R = P_av + R_av_ref;\n\n            if (in_degree(v, g) == 1) {\n                // u is the only in-neighbor of v\n                updated_R = -P_av;\n            } else {\n                tie(in_a_begin, in_a_end) = in_edges(a, g);\n                double u_contrib = 0;\n                //iterate over a's in-neighbors\n                for (in_a_iter = in_a_begin; in_a_iter != in_a_end; in_a_iter++) {\n                    auto a_prime = source(*in_a_iter, g);\n                    double contrib = 0;\n                    if (a_prime > u) {\n                        contrib = c * P.query(u, a_prime);\n                    } else if (a_prime < u) {\n                        contrib = c * P.query(a_prime, u);\n                    } else if (a_prime == u) {\n                        contrib = c * sqrt(2) * P.query(a_prime, u);\n                    }\n                    u_contrib += contrib;\n                }\n                u_contrib = u_contrib / (in_degree(v, g) * in_degree(a, g));\n                updated_R = updated_R - u_contrib;\n                updated_R = updated_R * ((in_degree(v, g)) / (in_degree(v, g) - 1.0));\n                updated_R -= P_av;\n            }\n            R_av_ref = updated_R;\n\n            if (fabs(updated_R) / sqrt(2) > r_max) {\n                if (!marker[np]) {\n                    Q.push(np);\n                    marker[np] = true;\n                }\n            }\n        }\n    }\n}\n\n\nvoid Reduced_LocalPush::update_residuals_by_adding_edge(DirectedG &g, DirectedG::vertex_descriptor u,\n                                                        DirectedG::vertex_descriptor v) {\n    // update the residual when an edge (u,v) is inserted to g\n    // node a: the iterated node over G\n    // node v: whose in-neighbor has changed (u added)\n    // assumption: g has not been updated, (u,v) does not exist in g\n    DirectedG::vertex_iterator v_begin, v_end, v_it;\n    tie(v_begin, v_end) = vertices(g);\n    for (v_it = v_begin; v_it != v_end; v_it++) { // ignore the starting node 0\n        auto a = *v_it;\n\n        if (a != v && in_degree(a, g) != 0) {\n            double u_contrib = 0; // the amount of R^{'} related to u\n            NodePair np = a < v ? NodePair(a, v) : NodePair(v, a); // the node pair to be updated\n\n            auto &residual_ref = R[np];\n            auto scaled_rest =\n                    (in_degree(v, g) / (in_degree(v, g) + 1.0)) * (residual_ref + P.query(np.first, np.second));\n\n            // iterate over a's in-neighbors\n            DirectedG::in_edge_iterator in_a_iter, in_a_begin, in_a_end;\n            tie(in_a_begin, in_a_end) = in_edges(a, g);\n            for (in_a_iter = in_a_begin; in_a_iter != in_a_end; in_a_iter++) {\n                auto a_prime = source(*in_a_iter, g);\n                double contrib = 0;\n                if (a_prime > u) {\n                    contrib = c * P.query(u, a_prime);\n                } else if (a_prime < u) {\n                    contrib = c * P.query(a_prime, u);\n                } else if (a_prime == u) {\n                    contrib = c * sqrt(2) * P.query(a_prime, u);\n                }\n                u_contrib += contrib;\n            }\n            u_contrib = u_contrib / ((in_degree(v, g) + 1.0) * in_degree(a, g));\n\n            auto updated_residual = u_contrib + scaled_rest - P.query(np.first, np.second);\n            residual_ref = updated_residual;\n\n            if (fabs(updated_residual) / sqrt(2) > r_max) {\n                if (!marker[np]) {\n                    Q.push(np);\n                    marker[np] = true;\n                }\n            }\n        }\n    }\n}\n\nvoid Reduced_LocalPush::update_edges(DirectedG &g, vector<NodePair> edges, char update_type = '+') {\n    // update G by a set of edges\n    if (update_type == '+') {\n        for (auto &e: edges) {\n            int s = e.first;\n            int t = e.second;\n            update_residuals_by_adding_edge(g, s, t);\n            add_edge(s, t, g);\n        }\n    } else if (update_type == '-') {\n        for (auto &e: edges) {\n            int s = e.first;\n            int t = e.second;\n\n            if (edge(s, t, g).second) {\n                update_residuals_by_deleting_edge(g, s, t);\n                remove_edge(s, t, g);\n            }\n        }\n    } else {\n        cout << \"Please indicate the edge update type\" << endl;\n        return;\n    }\n    log_info(\"finish updating residuals...\");\n    Reduced_LocalPush::local_push(g);\n}", "meta": {"hexsha": "039a005681768e1194026045e8e173db0cf09e53", "size": 28929, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "APS/local_push.cpp", "max_stars_repo_name": "RapidsAtHKUST/SimRank", "max_stars_repo_head_hexsha": "3a601b08f9a3c281e2b36b914e06aba3a3a36118", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-04-14T23:17:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T12:34:04.000Z", "max_issues_repo_path": "APS/local_push.cpp", "max_issues_repo_name": "RapidsAtHKUST/SimRank", "max_issues_repo_head_hexsha": "3a601b08f9a3c281e2b36b914e06aba3a3a36118", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "APS/local_push.cpp", "max_forks_repo_name": "RapidsAtHKUST/SimRank", "max_forks_repo_head_hexsha": "3a601b08f9a3c281e2b36b914e06aba3a3a36118", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-17T16:26:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-17T16:26:50.000Z", "avg_line_length": 37.8156862745, "max_line_length": 132, "alphanum_fraction": 0.5115973591, "num_tokens": 7612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4098422930795862}}
{"text": "// Copyright (c) 2020 fortiss GmbH\n//\n// Authors: Julian Bernhard, Klemens Esterle, Patrick Hart and\n// Tobias Kessler\n//\n// This work is licensed under the terms of the MIT license.\n// For a copy, see <https://opensource.org/licenses/MIT>.\n\n#ifndef BARK_MODELS_DYNAMIC_INTEGRATION_HPP_\n#define BARK_MODELS_DYNAMIC_INTEGRATION_HPP_\n#include <Eigen/Core>\n\n#include \"bark/geometry/angle.hpp\"\n#include \"bark/models/dynamic/dynamic_model.hpp\"\n\nnamespace bark {\nnamespace models {\nnamespace dynamic {\n\ninline State euler_int(const DynamicModel& model,\n                const State &x,\n                const Input &u,\n                float dt) {\n  State new_x = x + dt * model.StateSpaceModel(x, u);\n  new_x(StateDefinition::THETA_POSITION) =\n      geometry::Norm0To2PI(new_x(StateDefinition::THETA_POSITION));\n  return new_x;\n}\n\ninline State rk4(const DynamicModel& model, const State& x, const Input& u,\n                 float dt) {\n  State k0 = dt * model.StateSpaceModel(x, u);\n  State k1 = dt * model.StateSpaceModel(x + k0 / 2, u);\n  State k2 = dt * model.StateSpaceModel(x + k1 / 2, u);\n  State k3 = dt * model.StateSpaceModel(x + k2, u);\n  return x + 1.0 / 6.0 * (k0 + 2 * k1 + 2 * k2 + k3);\n}\n\n}  // namespace dynamic\n}  // namespace models\n}  // namespace bark\n\n#endif  // BARK_MODELS_DYNAMIC_INTEGRATION_HPP_\n", "meta": {"hexsha": "0434cf785489d154062143e59068541677bce1a6", "size": 1313, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bark/models/dynamic/integration.hpp", "max_stars_repo_name": "BastianHofmann/bark", "max_stars_repo_head_hexsha": "fd4f4cd2b2a8292c383a11970fb3cab926191c55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bark/models/dynamic/integration.hpp", "max_issues_repo_name": "BastianHofmann/bark", "max_issues_repo_head_hexsha": "fd4f4cd2b2a8292c383a11970fb3cab926191c55", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bark/models/dynamic/integration.hpp", "max_forks_repo_name": "BastianHofmann/bark", "max_forks_repo_head_hexsha": "fd4f4cd2b2a8292c383a11970fb3cab926191c55", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8409090909, "max_line_length": 75, "alphanum_fraction": 0.6778370145, "num_tokens": 365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.40984228565230274}}
{"text": "#pragma once\n#ifndef CANNON_PHYSICS_RK4_INTEGRATOR_H\n#define CANNON_PHYSICS_RK4_INTEGRATOR_H \n\n/*!\n * \\file cannon/physics/rk4_integrator.hpp\n * \\brief File containing RK4Integrator class definition.\n */\n\n#include <functional>\n\n#include <Eigen/Dense>\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/external/eigen/eigen_algebra.hpp>\n\nusing namespace Eigen;\nusing namespace boost::numeric::odeint;\n\nnamespace cannon {\n  namespace physics {\n\n    /*!\n     * \\brief Class representing a fourth-order Runge-Kutta integrator.\n     */\n    class RK4Integrator {\n      public:\n        using system_type = std::function<void(const VectorXd&, VectorXd&, double)>;\n\n        RK4Integrator() = delete;\n\n        /*!\n         * \\brief Constructor taking the system to integrate, state dimension,\n         * and timestep for integration.\n         */\n        RK4Integrator(system_type system, unsigned int state_dim, double\n            dt) : system_(system), state_dim_(state_dim), dt_(dt) {\n          state_ = VectorXd::Zero(state_dim_); \n        }\n\n        /*!\n         * \\brief Perform a single integration step using the timestep of this\n         * integrator.\n         *\n         * \\returns The new state, post-integration.\n         */\n        const VectorXd& step();\n\n        /*!\n         * \\brief Set the state of the system being integrated.\n         *\n         * \\param state The state to set.\n         */\n        void set_state(const VectorXd& state);\n\n        /*!\n         * \\brief Get the current state of the system being integrated.\n         *\n         * \\returns The current state.\n         */\n        VectorXd get_state() const;\n\n        /*!\n         * \\brief Set the current time for the system being integrated.\n         *\n         * \\param t The time to set.\n         */\n        void set_time(double t);\n\n        /*!\n         * \\brief Get the current time in the system being integrated.\n         *\n         * \\returns The current time.\n         */\n        double get_time() const;\n\n      private:\n        //using stepper_type = runge_kutta4<VectorXd, double, VectorXd, double, vector_space_algebra>;\n        using stepper_type = runge_kutta_dopri5<VectorXd, double, VectorXd, double, vector_space_algebra>;\n\n        system_type system_; //!< The system to be integrated\n        stepper_type stepper_; //!< Internal ODEInt stepper\n\n        unsigned int state_dim_; //!< State dimension of the system being integrated\n        VectorXd state_; //!< Current state of the system being integrated\n\n        double dt_; //!< Integration timestep\n        double t_ = 0.0; //!< Current time in the integrated system\n\n    };\n\n  } // namespace physics\n} // namespace cannon\n\n#endif /* ifndef CANNON_PHYSICS_RK4_INTEGRATOR_H */\n", "meta": {"hexsha": "85aac90a20ac66157a23b649d2dfca50274e3253", "size": 2736, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/physics/rk4_integrator.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/physics/rk4_integrator.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/physics/rk4_integrator.hpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8, "max_line_length": 106, "alphanum_fraction": 0.6235380117, "num_tokens": 606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.6224593312018545, "lm_q1q2_score": 0.4098381253954863}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RWLIBS_ALGORTIHMS_KDTREEQ_HPP_\n#define RWLIBS_ALGORTIHMS_KDTREEQ_HPP_\n\n#include \"KDTree.hpp\"\n\n#include <rw/common/InputArchive.hpp>\n#include <rw/common/OutputArchive.hpp>\n#include <rw/common/Serializable.hpp>\n#include <rw/core/Ptr.hpp>\n#include <rw/core/macros.hpp>\n#include <rw/math/Math.hpp>\n#include <rw/math/MetricUtil.hpp>\n#include <rw/math/Q.hpp>\n\n#include <algorithm>\n#include <boost/numeric/conversion/cast.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <float.h>\n#include <list>\n#include <map>\n#include <queue>\n#include <vector>\n\nnamespace rwlibs { namespace algorithms {\n\n    /** \\addtogroup algorithms */\n    /*@{*/\n\n    /**\n     * @brief a space partitioning structure for organizing points in k-dimensional space.\n     * Used for searches involving multi.dimensional search keys, including nearest\n     * neighbor and range search.\n     *\n     * This KDTree implementation takes any value type but the key is constrained to a\n     * rw::math::Q\n     */\n    template< class VALUE_TYPE > class KDTreeQ : public rw::common::Serializable\n    {\n      private:\n        struct TreeNode;\n\n      public:\n        typedef rw::core::Ptr< KDTreeQ< VALUE_TYPE > > Ptr;\n\n        typedef rw::math::Q KEY;\n\n        //! a struct for the node in the tree\n        struct KDNode\n        {\n            KDNode (rw::math::Q k, VALUE_TYPE val) : key (k), value (val) {}\n            rw::math::Q key;\n            VALUE_TYPE value;\n\n            // template<class T>\n            // T valueAs() { return boost::any_cast<T>(value); }\n            // template<class T>\n            // T valueAs() const { return boost::any_cast<T>(value); }\n        };\n\n        struct KDResult\n        {\n            KDResult (KDNode* node, double d) : n (node), dist (d) {}\n            KDNode* n;\n            double dist;\n        };\n\n        typedef KDNode Node;\n        typedef KDResult Result;\n        typedef VALUE_TYPE Value;\n\n        /**\n         * @brief Constructor\n         * @param dim [in] the dimension of the keys in the KDTreeQ\n         */\n        KDTreeQ (size_t dim) :\n            _dim (dim), _nrOfNodes (0), _root (NULL), _nodes (new std::vector< TreeNode* > ())\n        {}\n\n        /**\n         * @brief destructor\n         */\n        virtual ~KDTreeQ ()\n        {\n            delete _root;\n            delete _nodes;\n        };\n\n        /**\n         * @brief Builds a KDTreeQ from a list of key values and nodes. This method is more\n         * efficient than creating an empty KDTreeQ and then inserting nodes\n         * @param nodes [in] a list of KDNode's\n         * @return if build succesfull then a pointer to a KD-tree is returned else NULL\n         */\n        static KDTreeQ* buildTree (std::vector< KDNode >& nodes);\n\n        /**\n         * @brief Builds a KDTreeQ from a list of key values and nodes. This method is more\n         * efficient than creating an empty KDTreeQ and then inserting nodes\n         * @param nodes [in] a list of KDNode's\n         * @return if build succesfull then a pointer to a KD-tree is returned else NULL\n         */\n        static KDTreeQ* buildTree (const std::vector< KDNode* >& nodes);\n\n        /**\n         * @brief gets the number of dimensions that this KDTreeQ supports\n         * @return the nr of dimensions of this KD-Tree\n         */\n        size_t getDimensions () const { return _dim; };\n\n        /**\n         * @brief adds a key value pair to the KDTreeQ.\n         * @param key [in] must be the same length as the dimensionality of the KDTreeQ\n         * @param val [in] value that is to be stored at the keys position\n         */\n        void addNode (const rw::math::Q& key, VALUE_TYPE val);\n\n        /**\n         * @brief remove the node with key nnkey\n         * @param nnkey [in] the key of the node to remove\n         * @return\n         */\n        void removeNode (const rw::math::Q& nnkey);\n\n        /**\n         * @brief finds the KDNode with key equal to nnkey\n         * @param nnkey [in] the key that is to be found\n         * @return KDNode with key equal to nnkey if existing, else NULL\n         */\n        KDNode* search (const rw::math::Q& nnkey);\n\n        /**\n         * @brief finds the KDNode with the key closest too nnkey\n         * @param nnkey [in] the key to which the nearest neighbor is found\n         * @return the nearest neighbor to nnkey\n         */\n        KDNode& nnSearch (const rw::math::Q& nnkey);\n\n        /**\n         * @brief finds all neighbors in the hyperelipse with radius radi and center in nnkey.\n         * @param nnkey [in] the center of the hyperelipse\n         * @param radi [in] the radius of the hyperelipse in euclidean 2-norm\n         * @param nodes [out] a container for all nodes that is found within the hyperelipse\n         */\n        void nnSearchElipse (const rw::math::Q& nnkey, const rw::math::Q& radi,\n                             std::list< const KDNode* >& nodes);\n\n        /**\n         * @brief finds all neighbors in the hyperelipse with radius radi and center in nnkey.\n         * @param nnkey [in] the center of the hyperelipse\n         * @param radi [in] the radius of the hyperelipse in euclidean 2-norm\n         * @param nodes [out] a container for all nodes that is found within the hyperelipse\n         */\n        void nnSearchElipseRect (const rw::math::Q& nnkey, const rw::math::Q& radi,\n                                 std::list< const KDNode* >& nodes);\n\n        /**\n         * @brief finds all neighbors in the hyperrectangle defined by the lower bound and the\n         * upper bound\n         */\n        void nnSearchRect (const rw::math::Q& low, const rw::math::Q& upp,\n                           std::list< const KDNode* >& nodes);\n\n      private:\n        size_t _dim;\n        size_t _nrOfNodes;\n        TreeNode* _root;\n        std::vector< TreeNode* >* _nodes;\n\n      public:\n        void read (rw::common::InputArchive& iarchive, const std::string& id)\n        {\n            std::string name, data;\n            int dim, nrNodes;\n            boost::uint64_t rootId;\n            iarchive.read (dim, \"dim\");\n            iarchive.read (nrNodes, \"nrNodes\");\n            rootId = iarchive.readUInt64 (\"rootId\");\n\n            std::vector< TreeNode* >* nodes = new std::vector< TreeNode* > (nrNodes);\n            std::vector< int > idToNodeIdx (nrNodes);\n            std::map< boost::uint64_t, boost::tuple< TreeNode*, boost::uint64_t, boost::uint64_t > >\n                toNode;\n            for (int i = 0; i < nrNodes; i++) {\n                (*nodes)[i]    = new TreeNode ();\n                TreeNode& node = *(*nodes)[i];\n\n                boost::uint64_t id = iarchive.readUInt64 (\"id\");\n                node._axis         = iarchive.readInt (\"axis\");\n                node._deleted      = iarchive.readBool (\"del\");\n\n                boost::uint64_t leftId  = iarchive.readUInt64 (\"left\");\n                boost::uint64_t rightId = iarchive.readUInt64 (\"right\");\n\n                iarchive.read (node._kdnode->key, \"Q\");\n                iarchive.read (node._kdnode->value, \"value\");\n\n                toNode[id]     = boost::make_tuple (&node, leftId, rightId);\n                idToNodeIdx[i] = static_cast< int > (id);\n            }\n            toNode[0] =\n                boost::make_tuple ((TreeNode*) NULL, (boost::uint64_t) 0, (boost::uint64_t) 0);\n\n            // finally travel through nodes and set the correct left/right values\n            for (int i = 0; i < nrNodes; i++) {\n                TreeNode& node = *(*nodes)[i];\n\n                boost::tuple< TreeNode*, boost::uint64_t, boost::uint64_t > val =\n                    toNode[idToNodeIdx[i]];\n                const boost::uint64_t leftIdx = boost::get< 1 > (val);\n                node._left                    = boost::get< 0 > (toNode[leftIdx]);\n                node._right                   = boost::get< 0 > (toNode[boost::get< 2 > (val)]);\n            }\n            TreeNode* root = boost::get< 0 > (toNode[rootId]);\n            _dim           = root->_kdnode->key.size ();\n            _root          = root;\n            _nodes         = nodes;\n        }\n\n        void write (rw::common::OutputArchive& oarchive, const std::string& id) const\n        {\n            oarchive.write (_dim, \"dim\");\n            oarchive.write ((int) _nodes->size (), \"nrNodes\");\n            oarchive.write ((boost::uint64_t) _root, \"rootId\");\n            RW_ASSERT (_nrOfNodes == _nodes->size ());\n            for (std::size_t i = 0; i < _nodes->size (); i++) {\n                const TreeNode& node = *(*_nodes)[i];\n                oarchive.write ((boost::uint64_t) &node, \"id\");\n                oarchive.write ((int) node._axis, \"axis\");\n                oarchive.write (node._deleted, \"del\");\n                oarchive.write ((boost::uint64_t) node._left, \"left\");\n                oarchive.write ((boost::uint64_t) node._right, \"right\");\n\n                oarchive.write (node._kdnode->key, \"Q\");\n                oarchive.write (node._kdnode->value, \"value\");\n            }\n        }\n\n        /*\n                static void save(RWOutputArchive& archive);\n                static KDTreeQ* load(RWInputArchive& archive){\n\n                }\n\n                static void save(KDTreeQ* tree, ValueSerializer& serializer, const std::string&\n           filename); static KDTreeQ* load(ValueSerializer& serializer, const std::string&\n           filename);\n                */\n\n      private:\n        //! default constructor\n        KDTreeQ () :\n            _dim (0), _nrOfNodes (0), _root (NULL), _nodes (new std::vector< TreeNode* > ())\n        {}\n\n        //! constructor\n        KDTreeQ (TreeNode* root, std::vector< TreeNode* >* nodes) :\n            _dim (root->_kdnode->key.size ()), _nrOfNodes (nodes->size ()), _root (root),\n            _nodes (nodes)\n        {}\n\n        /**\n         * @brief Internal representation of a KD Tree Node. To save processing time when deleting\n         * TreeNodes, a boolean is kept that say if the node is deleted or not. If deleted all\n         * rutines kan skip the node and forward the call to its children.\n         */\n        struct TreeNode\n        {\n          public:\n            TreeNode () :\n                _left (NULL), _right (NULL), _kdnode (NULL), _deleted (false), _axis (0){};\n\n            TreeNode (KDNode* node) :\n                _left (NULL), _right (NULL), _kdnode (node), _deleted (false), _axis (0){};\n\n            TreeNode (TreeNode* left, TreeNode* right, KDNode* node) :\n                _left (left), _right (right), _kdnode (node), _deleted (false), _axis (0){};\n\n            static void swap (TreeNode& n1, TreeNode& n2)\n            {\n                std::swap (n1._left, n2._left);\n                std::swap (n1._right, n2._right);\n                std::swap (n1._kdnode, n2._kdnode);\n            }\n\n            TreeNode *_left, *_right;\n            KDNode* _kdnode;\n            bool _deleted;          //\n            unsigned char _axis;    // the splitting axis\n        };\n        /*\n                struct SimpleCompare {\n                private:\n                    size_t _dim;\n                public:\n                    SimpleCompare(size_t dim):_dim(dim){};\n\n                    bool operator()(const TreeNode& e1, const TreeNode& e2) {\n                        RW_ASSERT(e1._kdnode);\n                        RW_ASSERT(e2._kdnode);\n                        return e1._kdnode->key[_dim] < e2._kdnode->key[_dim] ;\n                    }\n                };\n        */\n        struct SimpleCompare2\n        {\n          private:\n            size_t _dim;\n\n          public:\n            SimpleCompare2 (size_t dim) : _dim (dim){};\n\n            bool operator() (const TreeNode* e1, const TreeNode* e2)\n            {\n                return e1->_kdnode->key[_dim] < e2->_kdnode->key[_dim];\n            }\n        };\n\n        static TreeNode* buildBalancedRec (std::vector< TreeNode* >& tNodes, int startIdx,\n                                           int endIdx, size_t depth, size_t nrOfDims)\n        {\n            if (endIdx <= startIdx)\n                return NULL;\n\n            // std::cout << \"RecBuild(\" << startIdx << \",\" << endIdx << \")\" << std::endl;\n            size_t len = endIdx - startIdx;\n            size_t dim = depth % nrOfDims;\n\n            // the compare func can\n            std::sort (tNodes.begin () + startIdx, tNodes.begin () + endIdx, SimpleCompare2 (dim));\n            // check sorting is okay\n            for (int i = startIdx; i < endIdx - 1; i++)\n                if (tNodes[i]->_kdnode->key[dim] > tNodes[i + 1]->_kdnode->key[dim])\n                    RW_WARN (\" sort not working!\" << i);\n            size_t medianIdx = startIdx + len / 2;\n            TreeNode* mNode  = tNodes[medianIdx];\n            mNode->_axis     = 0xFF & dim;\n            mNode->_left =\n                buildBalancedRec (tNodes, startIdx, (int) medianIdx, depth + 1, nrOfDims);\n            mNode->_right =\n                buildBalancedRec (tNodes, (int) (medianIdx + 1), endIdx, depth + 1, nrOfDims);\n            return mNode;\n        }\n\n        void nnSearchRec (const rw::math::Q& nnkey, TreeNode* node, rw::math::Q& min,\n                          rw::math::Q& max, KDResult& out)\n        {\n            using namespace rw::math;\n            if (node == NULL)\n                return;\n            size_t axis = node->_axis;\n            // std::cout << \"nnSearchRec(\"<< axis << \")\" << std::endl;\n\n            Q& key = node->_kdnode->key;\n            double distSqr (MetricUtil::dist2Sqr (nnkey, key));\n            // std::cout << \"le\" << std::endl;\n\n            // if this node is closer than any other then update out\n            if (distSqr < out.dist && !node->_deleted) {\n                out.dist = distSqr;\n                out.n    = node->_kdnode;\n            }\n            // stop if the distance is very small\n            if (distSqr < kdtree_epsilon)\n                return;\n            // std::cout << \"1\" << std::endl;\n            // call nnSearch recursively with closerNode,\n            // closestNode and closestDistSqr is updated\n            bool isLeftClosest = nnkey (axis) < key (axis);\n            if (isLeftClosest) {\n                // std::cout << \"left\" << std::endl;\n                // left is closest, backup split value and make the recursive call\n                double maxTmp = max (axis);\n                max (axis)    = key (axis);\n                nnSearchRec (nnkey, node->_left, min, max, out);\n                // undo the change of max\n                max (axis) = maxTmp;\n            }\n            else {\n                // std::cout << \"right\" << std::endl;\n                // right is closest, backup split value and make the recursive call\n                double minTmp = min (axis);\n                min (axis)    = key (axis);\n                nnSearchRec (nnkey, node->_right, min, max, out);\n                // undo the change of max\n                min (axis) = minTmp;\n            }\n            // std::cout << \"2\" << std::endl;\n\n            // next check if fartherNode split plane lies closer than closestDistSqr\n            if (Math::sqr (nnkey (axis) - key (axis)) >= out.dist)\n                return;\n            // std::cout << \"3\" << std::endl;\n\n            bool isLeftFarthest = !isLeftClosest;\n            // if closest point in hyperrect of farther node is closer than closest\n            // then call nnSearch recursively with farther node\n            if (isLeftFarthest) {\n                double maxTmp       = max (axis);\n                max (axis)          = key (axis);\n                rw::math::Q closest = Math::clampQ (nnkey, min, max);\n                if (MetricUtil::dist2Sqr (nnkey, closest) < out.dist)\n                    nnSearchRec (nnkey, node->_left, min, max, out);\n                // undo the change of max\n                max (axis) = maxTmp;\n            }\n            else {\n                double minTmp       = min (axis);\n                min (axis)          = key (axis);\n                rw::math::Q closest = Math::clampQ (nnkey, min, max);\n                if (MetricUtil::dist2Sqr (nnkey, closest) < out.dist)\n                    nnSearchRec (nnkey, node->_right, min, max, out);\n                // undo the change of max\n                min (axis) = minTmp;\n            }\n        };\n\n        void nnSearchElipseRec (const rw::math::Q& nnkey, TreeNode* node, rw::math::Q& min,\n                                rw::math::Q& max, double maxRadiSqr,\n                                std::list< const KDNode* >& nodes)\n        {\n            using namespace rw::math;\n            if (node == NULL)\n                return;\n            size_t axis = node->_axis;\n            // std::cout << \"nnSearchRec(\"<< axis << \")\" << std::endl;\n\n            Q& key = node->_kdnode->key;\n            double distSqr (MetricUtil::dist2Sqr (nnkey, key));\n\n            // if this node is closer than any other then update out\n            if (distSqr < maxRadiSqr && !node->_deleted) {\n                nodes.push_back (node->_kdnode);\n            }\n            // stop if the distance is very small\n            if (distSqr < kdtree_epsilon)\n                return;\n\n            // call nnSearch recursively with closerNode,\n            // closestNode and closestDistSqr is updated\n            bool isLeftClosest = nnkey (axis) < key (axis);\n            if (isLeftClosest) {\n                // left is closest, backup split value and make the recursive call\n                double maxTmp = max (axis);\n                max (axis)    = key (axis);\n                nnSearchElipseRec (nnkey, node->_left, min, max, maxRadiSqr, nodes);\n                // undo the change of max\n                max (axis) = maxTmp;\n            }\n            else {\n                // right is closest, backup split value and make the recursive call\n                double minTmp = min (axis);\n                min (axis)    = key (axis);\n                nnSearchElipseRec (nnkey, node->_right, min, max, maxRadiSqr, nodes);\n                // undo the change of max\n                min (axis) = minTmp;\n            }\n\n            // next check if fartherNode split plane lies closer than closestDistSqr\n            if (Math::sqr (nnkey (axis) - key (axis)) >= maxRadiSqr)\n                return;\n\n            bool isLeftFarthest = !isLeftClosest;\n            // if closest point in hyperrect of farther node is closer than closest\n            // then call nnSearch recursively with farther node\n            if (isLeftFarthest) {\n                double maxTmp       = max (axis);\n                max (axis)          = key (axis);\n                rw::math::Q closest = Math::clampQ (nnkey, min, max);\n                if (MetricUtil::dist2Sqr (nnkey, closest) < maxRadiSqr)\n                    nnSearchElipseRec (nnkey, node->_left, min, max, maxRadiSqr, nodes);\n                // undo the change of max\n                max (axis) = maxTmp;\n            }\n            else {\n                double minTmp       = min (axis);\n                min (axis)          = key (axis);\n                rw::math::Q closest = Math::clampQ (nnkey, min, max);\n                if (MetricUtil::dist2Sqr (nnkey, closest) < maxRadiSqr)\n                    nnSearchElipseRec (nnkey, node->_right, min, max, maxRadiSqr, nodes);\n                // undo the change of max\n                min (axis) = minTmp;\n            }\n        };\n    };\n\n    template< class T >\n    KDTreeQ< T >* KDTreeQ< T >::buildTree (std::vector< typename KDTreeQ< T >::KDNode >& nodes)\n    {\n        if (nodes.size () == 0)\n            return NULL;\n\n        // create all tree nodes in a list\n        std::vector< TreeNode* >* tNodes = new std::vector< TreeNode* > (nodes.size ());\n        // copy the KDNodes into the tree nodes\n        for (unsigned int i = 0; i < tNodes->size (); i++) {\n            (*tNodes)[i]          = new TreeNode ();\n            (*tNodes)[i]->_kdnode = new KDTreeQ< T >::KDNode (nodes[i]);\n        }\n\n        // create a simple median balanced tree\n        size_t nrOfDims = nodes.front ().key.size ();\n        TreeNode* root  = buildBalancedRec (*tNodes, 0, (int) tNodes->size (), 0, nrOfDims);\n        return new KDTreeQ< T > (root, tNodes);\n    }\n\n    template< class T >\n    KDTreeQ< T >*\n    KDTreeQ< T >::buildTree (const std::vector< typename KDTreeQ< T >::KDNode* >& nodes)\n    {\n        if (nodes.size () == 0)\n            return NULL;\n\n        // create all tree nodes in a list\n        std::vector< TreeNode* >* tNodes = new std::vector< TreeNode* > (nodes.size ());\n\n        // copy the KDNodes into the tree nodes\n        int i = 0;\n        for (KDNode* n : nodes) {\n            (*tNodes)[i]          = new TreeNode ();\n            (*tNodes)[i]->_kdnode = n;\n            i++;\n        }\n\n        // create a simple median balanced tree\n        size_t nrOfDims      = nodes.front ()->key.size ();\n        const int tNodesSize = boost::numeric_cast< int > (tNodes->size ());\n        TreeNode* root       = buildBalancedRec (*tNodes, 0, tNodesSize, 0, nrOfDims);\n\n        return new KDTreeQ< T > (root, tNodes);\n    }\n\n    template< class T >\n    typename KDTreeQ< T >::KDNode* KDTreeQ< T >::search (const rw::math::Q& nnkey)\n    {\n        TreeNode* tmpNode = _root;\n        for (size_t lev = 0; tmpNode != NULL; lev = (lev + 1) % _dim) {\n            rw::math::Q& key = tmpNode->_kdnode->key;\n            if (nnkey (lev) == key (lev) && !(tmpNode->_deleted) && (nnkey == key)) {\n                return tmpNode->_kdnode;\n            }\n            else if (nnkey (lev) > key (lev)) {\n                tmpNode = tmpNode->_right;\n            }\n            else {\n                tmpNode = tmpNode->_left;\n            }\n        }\n        return NULL;\n    }\n\n    template< class T >\n    typename KDTreeQ< T >::KDNode& KDTreeQ< T >::nnSearch (const rw::math::Q& nnkey)\n    {\n        // std::cout << \"nnSearch \" << _dim << std::endl;\n\n        RW_ASSERT (nnkey.size () == _dim);\n        if (_root == NULL)\n            RW_THROW (\"KDTreeQ has no data!\");\n\n        rw::math::Q min (_dim), max (_dim);\n        KDResult result (NULL, DBL_MAX);\n        for (size_t i = 0; i < _dim; i++) {\n            min (i) = -DBL_MAX;\n            max (i) = DBL_MAX;\n        }\n        // std::cout << \"nnSearchRec\" << std::endl;\n        nnSearchRec (nnkey, _root, min, max, result);\n        if (result.n == NULL)\n            RW_THROW (\"KDTreeQ has no data!\");\n        return *result.n;\n    }\n\n    template< class T > void KDTreeQ< T >::removeNode (const rw::math::Q& nnkey)\n    {\n        TreeNode* tmpNode = _root;\n        for (size_t lev = 0; tmpNode != NULL; lev = (lev + 1) % _dim) {\n            rw::math::Q& key = tmpNode->_kdnode->key;\n            if (nnkey (lev) == key (lev) && !(tmpNode->_deleted) && (nnkey == key)) {\n                tmpNode->_deleted = true;\n                return;\n            }\n            else if (nnkey (lev) > key (lev)) {\n                tmpNode = tmpNode->_right;\n            }\n            else {\n                tmpNode = tmpNode->_left;\n            }\n        }\n    }\n\n    template< class T >\n    void KDTreeQ< T >::nnSearchElipse (const rw::math::Q& nnkey, const rw::math::Q& radi,\n                                       std::list< const KDNode* >& nodes)\n    {\n        // typedef std::pair<TreeNode*,size_t> QElem;\n        using namespace rw::math;\n        std::queue< TreeNode* > unhandled;\n        unhandled.push (_root);\n        double distSqr  = MetricUtil::norm2Sqr (radi);\n        double distRadi = sqrt (distSqr);\n        Q low (_dim), upp (_dim);\n        for (size_t i = 0; i < _dim; i++) {\n            low (i) = nnkey (i) - distRadi;\n            upp (i) = nnkey (i) + distRadi;\n        }\n\n        nnSearchElipseRec (nnkey, _root, low, upp, distSqr, nodes);\n    }\n\n    template< class T >\n    void KDTreeQ< T >::nnSearchElipseRect (const rw::math::Q& nnkey, const rw::math::Q& radi,\n                                           std::list< const KDNode* >& nodes)\n    {\n        // typedef std::pair<TreeNode*,size_t> QElem;\n        using namespace rw::math;\n        std::queue< TreeNode* > unhandled;\n        unhandled.push (_root);\n        double distSqr  = MetricUtil::norm2Sqr (radi);\n        double distRadi = sqrt (distSqr);\n        Q low (_dim), upp (_dim);\n        for (size_t i = 0; i < _dim; i++) {\n            low (i) = nnkey (i) - distRadi;\n            upp (i) = nnkey (i) + distRadi;\n        }\n\n        while (!unhandled.empty ()) {\n            // std::cout << \"unhandled size: \" << unhandled.size() << std::endl;\n            TreeNode* n = unhandled.front ();\n            unhandled.pop ();\n\n            unsigned char axis = n->_axis;\n            rw::math::Q& key   = n->_kdnode->key;\n\n            // std::cout << \"Axis: \" << axis << std::endl;\n\n            // if the key is in range then add it to the result\n            size_t j;\n            for (j = 0; j < _dim && low[j] <= key[j] && upp[j] >= key[j]; j++)\n                ;\n            // std::cout << j << \"==\" << _dim << \" k:\" << key << std::endl;\n            if (j == _dim) {    // this is in range if\n                double dist = MetricUtil::dist2Sqr (nnkey, key);\n                // std::cout << \"Dist: \" << dist << \" < \" << distSqr << std::endl;\n                if (dist < distSqr)\n                    nodes.push_back (n->_kdnode);\n            }\n\n            // add the children to the unhandled queue if the current dimension\n            if ((low (axis) <= key (axis)) && (n->_left != NULL))\n                unhandled.push (n->_left);\n            if ((upp (axis) > key (axis)) && (n->_right != NULL))\n                unhandled.push (n->_right);\n        }\n    }\n\n    template< class T >\n    void KDTreeQ< T >::nnSearchRect (const rw::math::Q& low, const rw::math::Q& upp,\n                                     std::list< const KDNode* >& nodes)\n    {\n        // typedef std::pair<TreeNode*,size_t> QElem;\n        std::queue< TreeNode* > unhandled;\n        unhandled.push (_root);\n\n        // std::cout << \"nnSearchRect: \"<< std::endl;\n        // std::cout << \"- low bound: \"<< low << std::endl;\n        // std::cout << \"- upp bound: \"<< upp << std::endl;\n\n        while (!unhandled.empty ()) {\n            // std::cout << \"unhandled size: \" << unhandled.size() << std::endl;\n            TreeNode* n = unhandled.front ();\n            unhandled.pop ();\n\n            unsigned char axis = n->_axis;\n            rw::math::Q& key   = n->_kdnode->key;\n\n            // std::cout << \"Axis: \" << axis << std::endl;\n\n            // if the key   is in range then add it to the result\n            size_t j;\n            for (j = 0; j < _dim && low[j] <= key[j] && key[j] <= upp[j]; j++)\n                ;\n\n            // std::cout << j << \"==\" << _dim << \" k:\" << key << std::endl;\n            if (j == _dim && n->_deleted == false)    // this is in range\n                nodes.push_back (n->_kdnode);\n\n            // add the children to the unhandled queue if the current dimension\n            if ((low (axis) <= key (axis)) && (n->_left != NULL))\n                unhandled.push (n->_left);\n\n            if ((upp (axis) > key (axis)) && (n->_right != NULL))\n                unhandled.push (n->_right);\n        }\n    }\n\n    template< class T > void KDTreeQ< T >::addNode (const rw::math::Q& nnkey, T val)\n    {\n        // first test if root is empty. if it is add value as root\n        if (_root == NULL) {\n            _nodes->push_back (new TreeNode (new KDNode (nnkey, val)));\n            _root = _nodes->back ();\n            return;\n        }\n\n        // else find the parent in which this is to be inserted\n        TreeNode* tmpNode = _root;\n        // find the leaf in which to insert the new value\n        for (size_t lev = 0; tmpNode != NULL; lev = (lev + 1) % _dim) {\n            KEY& key = tmpNode->_kdnode->key;\n\n            if (nnkey (lev) > key (lev)) {\n                if (tmpNode->_right == NULL) {\n                    TreeNode* node = new TreeNode (new KDNode (nnkey, val));\n                    node->_axis    = static_cast< unsigned char > ((lev + 1) % _dim);\n                    _nodes->push_back (node);\n                    tmpNode->_right = _nodes->back ();\n                    return;\n                }\n                tmpNode = tmpNode->_right;\n            }\n            else {\n                if (tmpNode->_left == NULL) {\n                    TreeNode* node = new TreeNode (new KDNode (nnkey, val));\n                    node->_axis    = static_cast< unsigned char > ((lev + 1) % _dim);\n                    _nodes->push_back (node);\n                    tmpNode->_left = _nodes->back ();\n                    return;\n                }\n                tmpNode = tmpNode->_left;\n            }\n        }\n    }\n\n    /**@}*/\n\n}}    // namespace rwlibs::algorithms\n\n#endif\n", "meta": {"hexsha": "73851a0a3431be710728e67739f2b15206551d68", "size": 29445, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rwlibs/algorithms/kdtree/KDTreeQ.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rwlibs/algorithms/kdtree/KDTreeQ.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rwlibs/algorithms/kdtree/KDTreeQ.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9484126984, "max_line_length": 100, "alphanum_fraction": 0.5023942944, "num_tokens": 7327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584174871563662, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.40983810870695736}}
{"text": "//    Copyright 2017 Rainer Gemulla\n// \n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n// \n//        http://www.apache.org/licenses/LICENSE-2.0\n// \n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n/** \\file\n *\n * Illustrates matrix factorization with parallel SGD. We first create factors and then a data matrix\n * from these factors. This process ensures that we know the best factorization of the input.\n * These matrices are distributed across a cluster. We then try to reconstruct the factors\n * using PSGD.\n *\n * Run with: psgd\n * (make sure to use a production build, otherwise it will be slow)\n */\n#include <iostream>\n#include <sstream>\n\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/random/uniform_real.hpp>\n\n#include <util/evaluation.h>\n\n#include <mpi2/mpi2.h>\n#include <mf/mf.h>\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\nusing namespace std;\nusing namespace mf;\nusing namespace mpi2;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\n// type of SGD\ntypedef UpdateTruncate<UpdateNzslL2> Update;\ntypedef UpdateLock<Update> UpdateL;\ntypedef RegularizeNone Regularize;\ntypedef SumLoss<NzslLoss, L2Loss> Loss;\ntypedef NzslLoss TestLoss;\n\nMPI2_TYPE_TRAITS(UpdateL);\n\nint main(int argc, char* argv[]) {\n\t// initialize mf library and mpi2\n\tboost::mpi::communicator& world = mfInit(argc, argv);\n\n\t// parameters for the factorization\n\tmf_size_type size1 = 10000;\n\tmf_size_type size2 = 10000;\n\tmf_size_type nnz = 1000000;\n\tdouble sigma = sqrt(10); // standard deviation\n\tdouble lambda = 1/sigma/sigma;\n\tmf_size_type r = 10;\n\n\t// parameters for distribution\n\tint tasks = 4;\n\n\t// parameters for SGD\n\tdouble eps0 = 0.01;\n\tmf_size_type epochs = 20;\n\tSgdOrder order = SGD_ORDER_WOR;\n\tPsgdShuffle shuffle = PSGD_SHUFFLE_PARALLEL;\n\tUpdate update = Update(UpdateNzslL2(lambda), -10*sigma, 10*sigma); // truncate for numerical stability\n\tUpdateL updateLock = UpdateL(update, size1, size2); // with locking\n\tRegularize regularize;\n\tLoss loss((NzslLoss()), L2Loss(lambda));\n\tTestLoss testLoss;\n\tmf_size_type testNnz = nnz/100;\n\tBalanceType balanceType = BALANCE_NONE;\n\tBalanceMethod balanceMethod = BALANCE_OPTIMAL;\n\n\t// start mf library\n\tmfStart();\n\n\tif (world.rank() == 0)\n\t{\n#ifndef NDEBUG\n\t\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n#endif\n\t\tLOG4CXX_INFO(logger, \"Using \" << tasks << \" parallel tasks\");\n\n\t\t// TODO: distribute matrix generation\n\t\t// generate original factors by sampling from a normal(0,sigma) distribution\n\t\tRandom32 random; // note: this takes a default seed (not randomized!)\n\t\tDenseMatrix wIn(size1, r);\n\t\tDenseMatrixCM hIn(r, size2);\n\t\tgenerateRandom(wIn, random, boost::normal_distribution<>(0, sigma));\n\t\tgenerateRandom(hIn, random, boost::normal_distribution<>(0, sigma));\n\n\t\t// generate a sparse matrix by selecting random entries from the generated factors\n\t\t// and add small Gaussian noise\n\t\tSparseMatrix v;\n\t\tgenerateRandom(v, nnz, wIn, hIn, random);\n\t\taddRandom(v, random, boost::normal_distribution<>(0, 0.1));\n\t\tLOG4CXX_INFO(logger, \"Data matrix: \"\n\t\t\t<< v.size1() << \" x \" << v.size2() << \", \" << v.nnz() << \" nonzeros\");\n\t\tLOG4CXX_INFO(logger, \"Loss with original factors: \" << loss((FactorizationData<>(v, wIn, hIn))));\n\n\t\t// create a test matrix (without noise)\n\t\tSparseMatrix vTest;\n\t\tgenerateRandom(vTest, testNnz, wIn, hIn, random);\n\t\tLOG4CXX_INFO(logger, \"Test matrix: \"\n\t\t\t<< v.size1() << \" x \" << v.size2() << \", \" << vTest.nnz() << \" nonzeros\");\n\n\t\t// take a small sample and remove empty rows/columns\n\t\tProjectedSparseMatrix Vsample;\n\t\tprojectRandomSubmatrix(random, v, Vsample, v.size1()/5, v.size2()/5);\n\t\tprojectFrequent(Vsample, 0);\n\t\tLOG4CXX_INFO(logger, \"Sample matrix: \"\n\t\t\t<< Vsample.data.size1() << \" x \" << Vsample.data.size2()\n\t\t\t<< \", \" << Vsample.data.nnz() << \" nonzeros\");\n\n\t\t// generate initial factors by sampling from a uniform[-0.5,0.5] distribution\n\t\tDenseMatrix w(size1, r);\n\t\tDenseMatrixCM h(r, size2);\n\t\tgenerateRandom(w, random, boost::uniform_real<>(-0.5, 0.5));\n\t\tgenerateRandom(h, random, boost::uniform_real<>(-0.5, 0.5));\n\n\t\t// initialize\n\t\tTimer t;\n\t\tPsgdRunner psgdRunner(random);\n\t\tPsgdJob<Update,Regularize> psgdJob(v, w, h, update, regularize, order, tasks, shuffle);\n\t\tPsgdJob<UpdateL,Regularize> psgdJobLock(v, w, h, updateLock, regularize, order, tasks, shuffle);\n\t\tParallelDecayAuto<Update,Regularize,Loss> decay(psgdJob, loss, Vsample, eps0, tasks);\n\t\tTrace trace;\n\n\t\t// print the test loss\n\t\tFactorizationData<> testData(vTest, w, h);\n\t\tLOG4CXX_INFO(logger, \"Initial test loss: \" << testLoss(testData));\n\n\t\t// run PSGD to try to reconstruct the original factors\n\t\tt.start();\n//\t\tpsgdRunner.run(psgdJob, loss, epochs, decay, trace, balanceType, balanceMethod, &testData, &testLoss);\n\t\tpsgdRunner.run(psgdJobLock, loss, epochs, decay, trace, balanceType, balanceMethod, &testData, &testLoss);\n\n\t\tt.stop();\n\t\tLOG4CXX_INFO(logger, \"Total time: \" << t);\n\n\t\t// print the test loss\n\t\tLOG4CXX_INFO(logger, \"Final test loss: \" << testLoss(testData));\n\n\t\t// write trace to an R file\n\t\tLOG4CXX_INFO(logger, \"Writing trace to \" << \"/tmp/psgd-trace.R\");\n\t\ttrace.toRfile(\"/tmp/psgd-trace.R\", \"psgd\");\n\t}\n\n\tmfStop();\n\tmfFinalize();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "6495b2113ee5575de283e1f7a2b307ac73ef40dc", "size": 5707, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/mf/psgd.cc", "max_stars_repo_name": "Hui-Li/DSGDPP", "max_stars_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T11:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T23:03:55.000Z", "max_issues_repo_path": "examples/mf/psgd.cc", "max_issues_repo_name": "Hui-Li/DSGDPP", "max_issues_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/mf/psgd.cc", "max_forks_repo_name": "Hui-Li/DSGDPP", "max_forks_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-10-27T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T15:10:56.000Z", "avg_line_length": 35.0122699387, "max_line_length": 108, "alphanum_fraction": 0.7135097249, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.40981563427376}}
{"text": "//  Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#define BOOST_ENABLE_ASSERT_HANDLER\n#define BOOST_MATH_MAX_SERIES_ITERATION_POLICY INT_MAX\n// for consistent behaviour across compilers/platforms:\n#define BOOST_MATH_PROMOTE_DOUBLE_POLICY false\n// overflow to infinity is OK, we treat these as zero error as long as the sign is correct!\n#define BOOST_MATH_OVERFLOW_ERROR_POLICY ignore_error\n\n#include <iostream>\n#include <ctime>\n#include <boost/multiprecision/mpfr.hpp>\n#include <boost/multiprecision/cpp_bin_float.hpp>\n#include <boost/math/special_functions/hypergeometric_1F1.hpp>\n#include <boost/math/special_functions/hypergeometric_pFq.hpp>\n#include <boost/math/special_functions/relative_difference.hpp>\n\n#include <boost/random.hpp>\n#include <set>\n#include <fstream>\n#include <boost/iostreams/tee.hpp>\n#include <boost/iostreams/stream.hpp>\n\nusing boost::multiprecision::mpfr_float;\n\nnamespace boost {\n   //\n   // We convert assertions into exceptions, so we can log them and continue:\n   //\n   void assertion_failed(char const * expr, char const *, char const * file, long line)\n   {\n      std::ostringstream oss;\n      oss << file << \":\" << line << \" Assertion failed: \" << expr;\n      throw std::runtime_error(oss.str());\n   }\n\n}\n\ntypedef boost::multiprecision::cpp_bin_float_quad test_type;\n\nint main()\n{\n   using std::floor;\n   using std::ceil;\n   try {\n      test_type a_start, a_end;\n      test_type b_start, b_end;\n      test_type a_mult, b_mult;\n\n      std::cout << \"Enter range for parameter a: \";\n      std::cin >> a_start >> a_end;\n      std::cout << \"Enter range for parameter b: \";\n      std::cin >> b_start >> b_end;\n      std::cout << \"Enter multiplier for a parameter: \";\n      std::cin >> a_mult;\n      std::cout << \"Enter multiplier for b parameter: \";\n      std::cin >> b_mult;\n\n      double error_limit = 200;\n      double time_limit = 10.0;\n\n      for (test_type a = a_start; a < a_end; a_start < 0 ? a /= a_mult : a *= a_mult)\n      {\n         for (test_type b = b_start; b < b_end; b_start < 0 ? b /= b_mult : b *= b_mult)\n         {\n            test_type z_mult = 2;\n            test_type last_good = 0;\n            test_type bad = 0;\n            try {\n               for (test_type z = 1; z < 1e10; z *= z_mult, z_mult *= 2)\n               {\n                  // std::cout << \"z = \" << z << std::endl;\n                  std::uintmax_t max_iter = 1000;\n                  test_type calc = boost::math::tools::function_ratio_from_forwards_recurrence(boost::math::detail::hypergeometric_1F1_recurrence_a_and_b_coefficients<test_type>(a, b, z), std::numeric_limits<test_type>::epsilon() * 2, max_iter);\n                  test_type reference = (test_type)(boost::math::hypergeometric_pFq_precision({ mpfr_float(a) }, { mpfr_float(b) }, mpfr_float(z), 50, time_limit) / boost::math::hypergeometric_pFq_precision({ mpfr_float(a + 1) }, { mpfr_float(b + 1) }, mpfr_float(z), std::numeric_limits<test_type>::digits10 * 2, time_limit));\n                  double err = (double)boost::math::epsilon_difference(reference, calc);\n\n                  if (err < error_limit)\n                  {\n                     last_good = z;\n                     break;\n                  }\n                  else\n                  {\n                     bad = z;\n                  }\n               }\n            }\n            catch (const std::exception& e)\n            {\n               std::cout << \"Unexpected exception: \" << e.what() << std::endl;\n               std::cout << \"For a = \" << a << \" b = \" << b << \" z = \" << bad * z_mult / 2 << std::endl;\n            }\n            test_type z_limit;\n            if (0 == bad)\n               z_limit = 1;  // Any z is large enough\n            else if (0 == last_good)\n               z_limit = std::numeric_limits<test_type > ::infinity();\n            else\n            {\n               //\n               // At this stage last_good and bad should bracket the edge of the domain, bisect to narrow things down:\n               //\n               z_limit = last_good == 0 ? 0 : boost::math::tools::bisect([&a, b, error_limit, time_limit](test_type z)\n               {\n                  std::uintmax_t max_iter = 1000;\n                  test_type calc = boost::math::tools::function_ratio_from_forwards_recurrence(boost::math::detail::hypergeometric_1F1_recurrence_a_and_b_coefficients<test_type>(a, b, z), std::numeric_limits<test_type>::epsilon() * 2, max_iter);\n                  test_type reference = (test_type)(boost::math::hypergeometric_pFq_precision({ mpfr_float(a) }, { mpfr_float(b) }, mpfr_float(z), 50, time_limit + 20) / boost::math::hypergeometric_pFq_precision({ mpfr_float(a + 1) }, { mpfr_float(b + 1) }, mpfr_float(z), std::numeric_limits<test_type>::digits10 * 2, time_limit + 20));\n                  test_type err = boost::math::epsilon_difference(reference, calc);\n                  return err < error_limit ? 1 : -1;\n               }, bad, last_good, boost::math::tools::equal_floor()).first;\n               z_limit = floor(z_limit + 2);  // Give ourselves some headroom!\n            }\n            // std::cout << \"z_limit = \" << z_limit << std::endl;\n            //\n            // Now over again for backwards recurrence domain at the same points:\n            //\n            bad = z_limit > 1e10 ? 1e10 : z_limit;\n            last_good = 0;\n            z_mult = 1.1;\n            for (test_type z = bad; z > 1; z /= z_mult, z_mult *= 2)\n            {\n               // std::cout << \"z = \" << z << std::endl;\n               try {\n                  std::uintmax_t max_iter = 1000;\n                  test_type calc = boost::math::tools::function_ratio_from_backwards_recurrence(boost::math::detail::hypergeometric_1F1_recurrence_a_and_b_coefficients<test_type>(a, b, z), std::numeric_limits<test_type>::epsilon() * 2, max_iter);\n                  test_type reference = (test_type)(boost::math::hypergeometric_pFq_precision({ mpfr_float(a) }, { mpfr_float(b) }, mpfr_float(z), 50, time_limit) / boost::math::hypergeometric_pFq_precision({ mpfr_float(a - 1) }, { mpfr_float(b - 1) }, mpfr_float(z), std::numeric_limits<test_type>::digits10 * 2, time_limit));\n                  test_type err = boost::math::epsilon_difference(reference, calc);\n\n                  if (err < error_limit)\n                  {\n                     last_good = z;\n                     break;\n                  }\n                  else\n                  {\n                     bad = z;\n                  }\n               }\n               catch (const std::exception& e)\n               {\n                  bad = z;\n                  std::cout << \"Unexpected exception: \" << e.what() << std::endl;\n                  std::cout << \"For a = \" << a << \" b = \" << b << \" z = \" << z << std::endl;\n               }\n            }\n            test_type lower_z_limit;\n            if (last_good < 1)\n               lower_z_limit = 0;\n            else if (last_good >= bad)\n            {\n               std::uintmax_t max_iter = 1000;\n               test_type z = bad;\n               test_type calc = boost::math::tools::function_ratio_from_forwards_recurrence(boost::math::detail::hypergeometric_1F1_recurrence_a_and_b_coefficients<test_type>(a, b, z), std::numeric_limits<test_type>::epsilon() * 2, max_iter);\n               test_type reference = (test_type)(boost::math::hypergeometric_pFq_precision({ mpfr_float(a) }, { mpfr_float(b) }, mpfr_float(z), 50, time_limit) / boost::math::hypergeometric_pFq_precision({ mpfr_float(a + 1) }, { mpfr_float(b + 1) }, mpfr_float(z), std::numeric_limits<test_type>::digits10 * 2, time_limit));\n               test_type err = boost::math::epsilon_difference(reference, calc);\n               if (err < error_limit)\n               {\n                  lower_z_limit = bad;   //  Both forwards and backwards iteration work!!!\n               }\n               else\n                  throw std::runtime_error(\"Internal logic failed!\");\n            }\n            else\n            {\n               //\n               // At this stage last_good and bad should bracket the edge of the domain, bisect to narrow things down:\n               //\n               lower_z_limit = last_good == 0 ? 0 : boost::math::tools::bisect([&a, b, error_limit, time_limit](test_type z)\n               {\n                  std::uintmax_t max_iter = 1000;\n                  test_type calc = boost::math::tools::function_ratio_from_backwards_recurrence(boost::math::detail::hypergeometric_1F1_recurrence_a_and_b_coefficients<test_type>(a, b, z), std::numeric_limits<test_type>::epsilon() * 2, max_iter);\n                  test_type reference = (test_type)(boost::math::hypergeometric_pFq_precision({ mpfr_float(a) }, { mpfr_float(b) }, mpfr_float(z), 50, time_limit + 20) / boost::math::hypergeometric_pFq_precision({ mpfr_float(a - 1) }, { mpfr_float(b - 1) }, mpfr_float(z), std::numeric_limits<test_type>::digits10 * 2, time_limit + 20));\n                  test_type err = boost::math::epsilon_difference(reference, calc);\n                  return err < error_limit ? 1 : -1;\n               }, last_good, bad, boost::math::tools::equal_floor()).first;\n               z_limit = ceil(z_limit - 2);  // Give ourselves some headroom!\n            }\n\n            std::cout << std::setprecision(std::numeric_limits<test_type>::max_digits10) << \"{ \" << a << \", \" << b << \", \" << lower_z_limit << \", \" << z_limit << \"},\" << std::endl;\n         }\n      }\n   }\n   catch (const std::exception& e)\n   {\n      std::cout << \"Unexpected exception: \" << e.what() << std::endl;\n   }\n   return 0;\n}\n\n", "meta": {"hexsha": "cb4e637b04fbc38a2cc1717518c4d4131a18e199", "size": 9689, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/hypergeometric_1F1_map_neg_b_fwd_recurrence.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "tools/hypergeometric_1F1_map_neg_b_fwd_recurrence.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "tools/hypergeometric_1F1_map_neg_b_fwd_recurrence.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 49.9432989691, "max_line_length": 337, "alphanum_fraction": 0.5697182372, "num_tokens": 2394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.40981562828708934}}
{"text": "/**\n * \\file\n * \\author Thomas Fischer\n * \\date   2010-03-17\n * \\brief  Implementation of analytical geometry functions.\n *\n * \\copyright\n * Copyright (c) 2012-2022, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include \"AnalyticalGeometry.h\"\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n\n#include \"BaseLib/StringTools.h\"\n#include \"MathLib/GeometricBasics.h\"\n#include \"PointVec.h\"\n#include \"Polyline.h\"\n\nextern double orient2d(double*, double*, double*);\nextern double orient2dfast(double*, double*, double*);\n\nnamespace ExactPredicates\n{\ndouble getOrientation2d(MathLib::Point3d const& a, MathLib::Point3d const& b,\n                        MathLib::Point3d const& c)\n{\n    return orient2d(const_cast<double*>(a.getCoords()),\n                    const_cast<double*>(b.getCoords()),\n                    const_cast<double*>(c.getCoords()));\n}\n\ndouble getOrientation2dFast(MathLib::Point3d const& a,\n                            MathLib::Point3d const& b,\n                            MathLib::Point3d const& c)\n{\n    return orient2dfast(const_cast<double*>(a.getCoords()),\n                        const_cast<double*>(b.getCoords()),\n                        const_cast<double*>(c.getCoords()));\n}\n}  // namespace ExactPredicates\n\nnamespace GeoLib\n{\nOrientation getOrientation(MathLib::Point3d const& p0,\n                           MathLib::Point3d const& p1,\n                           MathLib::Point3d const& p2)\n{\n    double const orientation = ExactPredicates::getOrientation2d(p0, p1, p2);\n    if (orientation > 0)\n    {\n        return CCW;\n    }\n    if (orientation < 0)\n    {\n        return CW;\n    }\n    return COLLINEAR;\n}\n\nOrientation getOrientationFast(MathLib::Point3d const& p0,\n                               MathLib::Point3d const& p1,\n                               MathLib::Point3d const& p2)\n{\n    double const orientation =\n        ExactPredicates::getOrientation2dFast(p0, p1, p2);\n    if (orientation > 0)\n    {\n        return CCW;\n    }\n    if (orientation < 0)\n    {\n        return CW;\n    }\n    return COLLINEAR;\n}\n\nbool parallel(Eigen::Vector3d v, Eigen::Vector3d w)\n{\n    const double eps(std::numeric_limits<double>::epsilon());\n    double const eps_squared = eps * eps;\n\n    // check degenerated cases\n    if (v.squaredNorm() < eps_squared)\n    {\n        return false;\n    }\n\n    if (w.squaredNorm() < eps_squared)\n    {\n        return false;\n    }\n\n    v.normalize();\n    w.normalize();\n\n    bool parallel(true);\n    if (std::abs(v[0] - w[0]) > eps)\n    {\n        parallel = false;\n    }\n    if (std::abs(v[1] - w[1]) > eps)\n    {\n        parallel = false;\n    }\n    if (std::abs(v[2] - w[2]) > eps)\n    {\n        parallel = false;\n    }\n\n    if (!parallel)\n    {\n        parallel = true;\n        // change sense of direction of v_normalised\n        v *= -1.0;\n        // check again\n        if (std::abs(v[0] - w[0]) > eps)\n        {\n            parallel = false;\n        }\n        if (std::abs(v[1] - w[1]) > eps)\n        {\n            parallel = false;\n        }\n        if (std::abs(v[2] - w[2]) > eps)\n        {\n            parallel = false;\n        }\n    }\n\n    return parallel;\n}\n\nbool lineSegmentIntersect(GeoLib::LineSegment const& s0,\n                          GeoLib::LineSegment const& s1,\n                          GeoLib::Point& s)\n{\n    GeoLib::Point const& pa{s0.getBeginPoint()};\n    GeoLib::Point const& pb{s0.getEndPoint()};\n    GeoLib::Point const& pc{s1.getBeginPoint()};\n    GeoLib::Point const& pd{s1.getEndPoint()};\n\n    if (!isCoplanar(pa, pb, pc, pd))\n    {\n        return false;\n    }\n\n    auto const a =\n        Eigen::Map<Eigen::Vector3d const>(s0.getBeginPoint().getCoords());\n    auto const b =\n        Eigen::Map<Eigen::Vector3d const>(s0.getEndPoint().getCoords());\n    auto const c =\n        Eigen::Map<Eigen::Vector3d const>(s1.getBeginPoint().getCoords());\n    auto const d =\n        Eigen::Map<Eigen::Vector3d const>(s1.getEndPoint().getCoords());\n\n    Eigen::Vector3d const v = b - a;\n    Eigen::Vector3d const w = d - c;\n    Eigen::Vector3d const qp = c - a;\n    Eigen::Vector3d const pq = a - c;\n\n    double const eps = std::numeric_limits<double>::epsilon();\n    double const squared_eps = eps * eps;\n    // handle special cases here to avoid computing intersection numerical\n    if (qp.squaredNorm() < squared_eps || (d - a).squaredNorm() < squared_eps)\n    {\n        s = pa;\n        return true;\n    }\n    if ((c - b).squaredNorm() < squared_eps ||\n        (d - b).squaredNorm() < squared_eps)\n    {\n        s = pb;\n        return true;\n    }\n\n    auto isLineSegmentIntersectingAB =\n        [&v](Eigen::Vector3d const& ap, std::size_t i)\n    {\n        // check if p is located at v=(a,b): (ap = t*v, t in [0,1])\n        return 0.0 <= ap[i] / v[i] && ap[i] / v[i] <= 1.0;\n    };\n\n    if (parallel(v, w))\n    {  // original line segments (a,b) and (c,d) are parallel\n        if (parallel(pq, v))\n        {  // line segment (a,b) and (a,c) are also parallel\n            // Here it is already checked that the line segments (a,b) and (c,d)\n            // are parallel. At this point it is also known that the line\n            // segment (a,c) is also parallel to (a,b). In that case it is\n            // possible to express c as c(t) = a + t * (b-a) (analog for the\n            // point d). Since the evaluation of all three coordinate equations\n            // (x,y,z) have to lead to the same solution for the parameter t it\n            // is sufficient to evaluate t only once.\n\n            // Search id of coordinate with largest absolute value which is will\n            // be used in the subsequent computations. This prevents division by\n            // zero in case the line segments are parallel to one of the\n            // coordinate axis.\n            std::size_t i_max(std::abs(v[0]) <= std::abs(v[1]) ? 1 : 0);\n            i_max = std::abs(v[i_max]) <= std::abs(v[2]) ? 2 : i_max;\n            if (isLineSegmentIntersectingAB(qp, i_max))\n            {\n                s = pc;\n                return true;\n            }\n            Eigen::Vector3d const ad = d - a;\n            if (isLineSegmentIntersectingAB(ad, i_max))\n            {\n                s = pd;\n                return true;\n            }\n            return false;\n        }\n        return false;\n    }\n\n    // general case\n    const double sqr_len_v(v.squaredNorm());\n    const double sqr_len_w(w.squaredNorm());\n\n    Eigen::Matrix2d mat;\n    mat(0, 0) = sqr_len_v;\n    mat(0, 1) = -v.dot(w);\n    mat(1, 1) = sqr_len_w;\n    mat(1, 0) = mat(0, 1);\n\n    Eigen::Vector2d rhs{v.dot(qp), w.dot(pq)};\n\n    rhs = mat.partialPivLu().solve(rhs);\n\n    // no theory for the following tolerances, determined by testing\n    // lower tolerance: little bit smaller than zero\n    const double l(-1.0 * std::numeric_limits<float>::epsilon());\n    // upper tolerance a little bit greater than one\n    const double u(1.0 + std::numeric_limits<float>::epsilon());\n    if (rhs[0] < l || u < rhs[0] || rhs[1] < l || u < rhs[1])\n    {\n        return false;\n    }\n\n    // compute points along line segments with minimal distance\n    GeoLib::Point const p0(a[0] + rhs[0] * v[0], a[1] + rhs[0] * v[1],\n                           a[2] + rhs[0] * v[2]);\n    GeoLib::Point const p1(c[0] + rhs[1] * w[0], c[1] + rhs[1] * w[1],\n                           c[2] + rhs[1] * w[2]);\n\n    double const min_dist(std::sqrt(MathLib::sqrDist(p0, p1)));\n    double const min_seg_len(\n        std::min(std::sqrt(sqr_len_v), std::sqrt(sqr_len_w)));\n    if (min_dist < min_seg_len * 1e-6)\n    {\n        s[0] = 0.5 * (p0[0] + p1[0]);\n        s[1] = 0.5 * (p0[1] + p1[1]);\n        s[2] = 0.5 * (p0[2] + p1[2]);\n        return true;\n    }\n\n    return false;\n}\n\nbool lineSegmentsIntersect(const GeoLib::Polyline* ply,\n                           GeoLib::Polyline::SegmentIterator& seg_it0,\n                           GeoLib::Polyline::SegmentIterator& seg_it1,\n                           GeoLib::Point& intersection_pnt)\n{\n    std::size_t const n_segs(ply->getNumberOfSegments());\n    // Neighbouring segments always intersects at a common vertex. The algorithm\n    // checks for intersections of non-neighbouring segments.\n    for (seg_it0 = ply->begin(); seg_it0 != ply->end() - 2; ++seg_it0)\n    {\n        seg_it1 = seg_it0 + 2;\n        std::size_t const seg_num_0 = seg_it0.getSegmentNumber();\n        for (; seg_it1 != ply->end(); ++seg_it1)\n        {\n            // Do not check first and last segment, because they are\n            // neighboured.\n            if (!(seg_num_0 == 0 && seg_it1.getSegmentNumber() == n_segs - 1))\n            {\n                if (lineSegmentIntersect(*seg_it0, *seg_it1, intersection_pnt))\n                {\n                    return true;\n                }\n            }\n        }\n    }\n    return false;\n}\n\nvoid rotatePoints(Eigen::Matrix3d const& rot_mat,\n                  std::vector<GeoLib::Point*>& pnts)\n{\n    rotatePoints(rot_mat, pnts.begin(), pnts.end());\n}\n\nEigen::Matrix3d computeRotationMatrixToXY(Eigen::Vector3d const& n)\n{\n    Eigen::Matrix3d rot_mat = Eigen::Matrix3d::Zero();\n    // check if normal points already in the right direction\n    if (n[0] == 0 && n[1] == 0)\n    {\n        rot_mat(1, 1) = 1.0;\n\n        if (n[2] > 0)\n        {\n            // identity matrix\n            rot_mat(0, 0) = 1.0;\n            rot_mat(2, 2) = 1.0;\n        }\n        else\n        {\n            // rotate by pi about the y-axis\n            rot_mat(0, 0) = -1.0;\n            rot_mat(2, 2) = -1.0;\n        }\n\n        return rot_mat;\n    }\n\n    // sqrt (n_1^2 + n_3^2)\n    double const h0(std::sqrt(n[0] * n[0] + n[2] * n[2]));\n\n    // In case the x and z components of the normal are both zero the rotation\n    // to the x-z-plane is not required, i.e. only the rotation in the z-axis is\n    // required. The angle is either pi/2 or 3/2*pi. Thus the components of\n    // rot_mat are as follows.\n    if (h0 < std::numeric_limits<double>::epsilon())\n    {\n        rot_mat(0, 0) = 1.0;\n        if (n[1] > 0)\n        {\n            rot_mat(1, 2) = -1.0;\n            rot_mat(2, 1) = 1.0;\n        }\n        else\n        {\n            rot_mat(1, 2) = 1.0;\n            rot_mat(2, 1) = -1.0;\n        }\n        return rot_mat;\n    }\n\n    double const h1(1 / n.norm());\n\n    // general case: calculate entries of rotation matrix\n    rot_mat(0, 0) = n[2] / h0;\n    rot_mat(0, 1) = 0;\n    rot_mat(0, 2) = -n[0] / h0;\n    rot_mat(1, 0) = -n[1] * n[0] / h0 * h1;\n    rot_mat(1, 1) = h0 * h1;\n    rot_mat(1, 2) = -n[1] * n[2] / h0 * h1;\n    rot_mat(2, 0) = n[0] * h1;\n    rot_mat(2, 1) = n[1] * h1;\n    rot_mat(2, 2) = n[2] * h1;\n\n    return rot_mat;\n}\n\nEigen::Matrix3d rotatePointsToXY(std::vector<GeoLib::Point*>& pnts)\n{\n    return rotatePointsToXY(pnts.begin(), pnts.end(), pnts.begin(), pnts.end());\n}\n\nstd::unique_ptr<GeoLib::Point> triangleLineIntersection(\n    MathLib::Point3d const& a, MathLib::Point3d const& b,\n    MathLib::Point3d const& c, MathLib::Point3d const& p,\n    MathLib::Point3d const& q)\n{\n    auto const va = Eigen::Map<Eigen::Vector3d const>(a.getCoords());\n    auto const vb = Eigen::Map<Eigen::Vector3d const>(b.getCoords());\n    auto const vc = Eigen::Map<Eigen::Vector3d const>(c.getCoords());\n    auto const vp = Eigen::Map<Eigen::Vector3d const>(p.getCoords());\n    auto const vq = Eigen::Map<Eigen::Vector3d const>(q.getCoords());\n\n    Eigen::Vector3d const pq = vq - vp;\n    Eigen::Vector3d const pa = va - vp;\n    Eigen::Vector3d const pb = vb - vp;\n    Eigen::Vector3d const pc = vc - vp;\n\n    double u = pq.cross(pc).dot(pb);\n    if (u < 0)\n    {\n        return nullptr;\n    }\n    double v = pq.cross(pa).dot(pc);\n    if (v < 0)\n    {\n        return nullptr;\n    }\n    double w = pq.cross(pb).dot(pa);\n    if (w < 0)\n    {\n        return nullptr;\n    }\n\n    const double denom(1.0 / (u + v + w));\n    u *= denom;\n    v *= denom;\n    w *= denom;\n    return std::make_unique<GeoLib::Point>(u * a[0] + v * b[0] + w * c[0],\n                                           u * a[1] + v * b[1] + w * c[1],\n                                           u * a[2] + v * b[2] + w * c[2]);\n}\n\nvoid computeAndInsertAllIntersectionPoints(GeoLib::PointVec& pnt_vec,\n                                           std::vector<GeoLib::Polyline*>& plys)\n{\n    auto computeSegmentIntersections =\n        [&pnt_vec](GeoLib::Polyline& poly0, GeoLib::Polyline& poly1)\n    {\n        for (auto seg0_it(poly0.begin()); seg0_it != poly0.end(); ++seg0_it)\n        {\n            for (auto seg1_it(poly1.begin()); seg1_it != poly1.end(); ++seg1_it)\n            {\n                GeoLib::Point s(0.0, 0.0, 0.0, pnt_vec.size());\n                if (lineSegmentIntersect(*seg0_it, *seg1_it, s))\n                {\n                    std::size_t const id(\n                        pnt_vec.push_back(new GeoLib::Point(s)));\n                    poly0.insertPoint(seg0_it.getSegmentNumber() + 1, id);\n                    poly1.insertPoint(seg1_it.getSegmentNumber() + 1, id);\n                }\n            }\n        }\n    };\n\n    for (auto it0(plys.begin()); it0 != plys.end(); ++it0)\n    {\n        auto it1(it0);\n        ++it1;\n        for (; it1 != plys.end(); ++it1)\n        {\n            computeSegmentIntersections(*(*it0), *(*it1));\n        }\n    }\n}\n\nstd::tuple<std::vector<GeoLib::Point*>, Eigen::Vector3d>\nrotatePolygonPointsToXY(GeoLib::Polygon const& polygon_in)\n{\n    // 1 copy all points\n    std::vector<GeoLib::Point*> polygon_points;\n    polygon_points.reserve(polygon_in.getNumberOfPoints());\n    for (std::size_t k(0); k < polygon_in.getNumberOfPoints(); k++)\n    {\n        polygon_points.push_back(new GeoLib::Point(*(polygon_in.getPoint(k))));\n    }\n\n    // 2 rotate points\n    auto [plane_normal, d_polygon] = GeoLib::getNewellPlane(polygon_points);\n    Eigen::Matrix3d const rot_mat =\n        GeoLib::computeRotationMatrixToXY(plane_normal);\n    GeoLib::rotatePoints(rot_mat, polygon_points);\n\n    // 3 set z coord to zero\n    std::for_each(polygon_points.begin(), polygon_points.end(),\n                  [](GeoLib::Point* p) { (*p)[2] = 0.0; });\n\n    return {polygon_points, plane_normal};\n}\n\nstd::vector<MathLib::Point3d> lineSegmentIntersect2d(\n    GeoLib::LineSegment const& ab, GeoLib::LineSegment const& cd)\n{\n    GeoLib::Point const& a{ab.getBeginPoint()};\n    GeoLib::Point const& b{ab.getEndPoint()};\n    GeoLib::Point const& c{cd.getBeginPoint()};\n    GeoLib::Point const& d{cd.getEndPoint()};\n\n    double const orient_abc(getOrientation(a, b, c));\n    double const orient_abd(getOrientation(a, b, d));\n\n    // check if the segment (cd) lies on the left or on the right of (ab)\n    if ((orient_abc > 0 && orient_abd > 0) ||\n        (orient_abc < 0 && orient_abd < 0))\n    {\n        return std::vector<MathLib::Point3d>();\n    }\n\n    // check: (cd) and (ab) are on the same line\n    if (orient_abc == 0.0 && orient_abd == 0.0)\n    {\n        double const eps(std::numeric_limits<double>::epsilon());\n        if (MathLib::sqrDist2d(a, c) < eps && MathLib::sqrDist2d(b, d) < eps)\n        {\n            return {{a, b}};\n        }\n        if (MathLib::sqrDist2d(a, d) < eps && MathLib::sqrDist2d(b, c) < eps)\n        {\n            return {{a, b}};\n        }\n\n        // Since orient_ab and orient_abd vanish, a, b, c, d are on the same\n        // line and for this reason it is enough to check the x-component.\n        auto isPointOnSegment = [](double q, double p0, double p1)\n        {\n            double const t((q - p0) / (p1 - p0));\n            return 0 <= t && t <= 1;\n        };\n\n        // check if c in (ab)\n        if (isPointOnSegment(c[0], a[0], b[0]))\n        {\n            // check if a in (cd)\n            if (isPointOnSegment(a[0], c[0], d[0]))\n            {\n                return {{a, c}};\n            }\n            // check b == c\n            if (MathLib::sqrDist2d(b, c) < eps)\n            {\n                return {{b}};\n            }\n            // check if b in (cd)\n            if (isPointOnSegment(b[0], c[0], d[0]))\n            {\n                return {{b, c}};\n            }\n            // check d in (ab)\n            if (isPointOnSegment(d[0], a[0], b[0]))\n            {\n                return {{c, d}};\n            }\n            std::stringstream err;\n            err.precision(std::numeric_limits<double>::digits10);\n            err << ab << \" x \" << cd;\n            OGS_FATAL(\n                \"The case of parallel line segments ({:s}) is not handled yet. \"\n                \"Aborting.\",\n                err.str());\n        }\n\n        // check if d in (ab)\n        if (isPointOnSegment(d[0], a[0], b[0]))\n        {\n            // check if a in (cd)\n            if (isPointOnSegment(a[0], c[0], d[0]))\n            {\n                return {{a, d}};\n            }\n            // check if b==d\n            if (MathLib::sqrDist2d(b, d) < eps)\n            {\n                return {{b}};\n            }\n            // check if b in (cd)\n            if (isPointOnSegment(b[0], c[0], d[0]))\n            {\n                return {{b, d}};\n            }\n            // d in (ab), b not in (cd): check c in (ab)\n            if (isPointOnSegment(c[0], a[0], b[0]))\n            {\n                return {{c, d}};\n            }\n\n            std::stringstream err;\n            err.precision(std::numeric_limits<double>::digits10);\n            err << ab << \" x \" << cd;\n            OGS_FATAL(\n                \"The case of parallel line segments ({:s}) is not handled yet. \"\n                \"Aborting.\",\n                err.str());\n        }\n        return std::vector<MathLib::Point3d>();\n    }\n\n    // precondition: points a, b, c are collinear\n    // the function checks if the point c is onto the line segment (a,b)\n    auto isCollinearPointOntoLineSegment = [](MathLib::Point3d const& a,\n                                              MathLib::Point3d const& b,\n                                              MathLib::Point3d const& c)\n    {\n        if (b[0] - a[0] != 0)\n        {\n            double const t = (c[0] - a[0]) / (b[0] - a[0]);\n            return 0.0 <= t && t <= 1.0;\n        }\n        if (b[1] - a[1] != 0)\n        {\n            double const t = (c[1] - a[1]) / (b[1] - a[1]);\n            return 0.0 <= t && t <= 1.0;\n        }\n        if (b[2] - a[2] != 0)\n        {\n            double const t = (c[2] - a[2]) / (b[2] - a[2]);\n            return 0.0 <= t && t <= 1.0;\n        }\n        return false;\n    };\n\n    if (orient_abc == 0.0)\n    {\n        if (isCollinearPointOntoLineSegment(a, b, c))\n        {\n            return {{c}};\n        }\n        return std::vector<MathLib::Point3d>();\n    }\n\n    if (orient_abd == 0.0)\n    {\n        if (isCollinearPointOntoLineSegment(a, b, d))\n        {\n            return {{d}};\n        }\n        return std::vector<MathLib::Point3d>();\n    }\n\n    // check if the segment (ab) lies on the left or on the right of (cd)\n    double const orient_cda(getOrientation(c, d, a));\n    double const orient_cdb(getOrientation(c, d, b));\n    if ((orient_cda > 0 && orient_cdb > 0) ||\n        (orient_cda < 0 && orient_cdb < 0))\n    {\n        return std::vector<MathLib::Point3d>();\n    }\n\n    // at this point it is sure that there is an intersection and the system of\n    // linear equations will be invertible\n    // solve the two linear equations (b-a, c-d) (t, s)^T = (c-a) simultaneously\n    Eigen::Matrix2d mat;\n    mat(0, 0) = b[0] - a[0];\n    mat(0, 1) = c[0] - d[0];\n    mat(1, 0) = b[1] - a[1];\n    mat(1, 1) = c[1] - d[1];\n    Eigen::Vector2d rhs{c[0] - a[0], c[1] - a[1]};\n\n    rhs = mat.partialPivLu().solve(rhs);\n    if (0 <= rhs[1] && rhs[1] <= 1.0)\n    {\n        return {MathLib::Point3d{std::array<double, 3>{\n            {c[0] + rhs[1] * (d[0] - c[0]), c[1] + rhs[1] * (d[1] - c[1]),\n             c[2] + rhs[1] * (d[2] - c[2])}}}};\n    }\n    return std::vector<MathLib::Point3d>();  // parameter s not in the valid\n                                             // range\n}\n\nvoid sortSegments(MathLib::Point3d const& seg_beg_pnt,\n                  std::vector<GeoLib::LineSegment>& sub_segments)\n{\n    double const eps(std::numeric_limits<double>::epsilon());\n\n    auto findNextSegment =\n        [&eps](MathLib::Point3d const& seg_beg_pnt,\n               std::vector<GeoLib::LineSegment>& sub_segments,\n               std::vector<GeoLib::LineSegment>::iterator& sub_seg_it)\n    {\n        if (sub_seg_it == sub_segments.end())\n        {\n            return;\n        }\n        // find appropriate segment for the given segment begin point\n        auto act_beg_seg_it = std::find_if(\n            sub_seg_it, sub_segments.end(),\n            [&seg_beg_pnt, &eps](GeoLib::LineSegment const& seg)\n            {\n                return MathLib::sqrDist(seg_beg_pnt, seg.getBeginPoint()) <\n                           eps ||\n                       MathLib::sqrDist(seg_beg_pnt, seg.getEndPoint()) < eps;\n            });\n        if (act_beg_seg_it == sub_segments.end())\n        {\n            return;\n        }\n        // if necessary correct orientation of segment, i.e. swap beg and\n        // end\n        if (MathLib::sqrDist(seg_beg_pnt, act_beg_seg_it->getEndPoint()) <\n            MathLib::sqrDist(seg_beg_pnt, act_beg_seg_it->getBeginPoint()))\n        {\n            std::swap(act_beg_seg_it->getBeginPoint(),\n                      act_beg_seg_it->getEndPoint());\n        }\n        assert(sub_seg_it != sub_segments.end());\n        // exchange segments within the container\n        if (sub_seg_it != act_beg_seg_it)\n        {\n            std::swap(*sub_seg_it, *act_beg_seg_it);\n        }\n    };\n\n    // find start segment\n    auto seg_it = sub_segments.begin();\n    findNextSegment(seg_beg_pnt, sub_segments, seg_it);\n\n    while (seg_it != sub_segments.end())\n    {\n        MathLib::Point3d& new_seg_beg_pnt(seg_it->getEndPoint());\n        seg_it++;\n        if (seg_it != sub_segments.end())\n        {\n            findNextSegment(new_seg_beg_pnt, sub_segments, seg_it);\n        }\n    }\n}\n\nEigen::Matrix3d compute2DRotationMatrixToX(Eigen::Vector3d const& v)\n{\n    Eigen::Matrix3d rot_mat = Eigen::Matrix3d::Zero();\n    const double cos_theta = v[0];\n    const double sin_theta = v[1];\n    rot_mat(0, 0) = rot_mat(1, 1) = cos_theta;\n    rot_mat(0, 1) = sin_theta;\n    rot_mat(1, 0) = -sin_theta;\n    rot_mat(2, 2) = 1.0;\n    return rot_mat;\n}\n\nEigen::Matrix3d compute3DRotationMatrixToX(Eigen::Vector3d const& v)\n{\n    // a vector on the plane\n    Eigen::Vector3d yy = Eigen::Vector3d::Zero();\n    auto const eps = std::numeric_limits<double>::epsilon();\n    if (std::abs(v[0]) > 0.0 && std::abs(v[1]) + std::abs(v[2]) < eps)\n    {\n        yy[2] = 1.0;\n    }\n    else if (std::abs(v[1]) > 0.0 && std::abs(v[0]) + std::abs(v[2]) < eps)\n    {\n        yy[0] = 1.0;\n    }\n    else if (std::abs(v[2]) > 0.0 && std::abs(v[0]) + std::abs(v[1]) < eps)\n    {\n        yy[1] = 1.0;\n    }\n    else\n    {\n        for (unsigned i = 0; i < 3; i++)\n        {\n            if (std::abs(v[i]) > 0.0)\n            {\n                yy[i] = -v[i];\n                break;\n            }\n        }\n    }\n    // z\"_vec\n    Eigen::Vector3d const zz = v.cross(yy).normalized();\n    // y\"_vec\n    yy = zz.cross(v).normalized();\n\n    Eigen::Matrix3d rot_mat;\n    rot_mat.row(0) = v;\n    rot_mat.row(1) = yy;\n    rot_mat.row(2) = zz;\n    return rot_mat;\n}\n\n}  // end namespace GeoLib\n", "meta": {"hexsha": "0fc29e46ddf10bc9be9a68fe7aa3d6161a540bfe", "size": 23358, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GeoLib/AnalyticalGeometry.cpp", "max_stars_repo_name": "garibay-j/ogs", "max_stars_repo_head_hexsha": "33340f22e9dbe0b7ccc60f0c828c2a528737c81e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GeoLib/AnalyticalGeometry.cpp", "max_issues_repo_name": "garibay-j/ogs", "max_issues_repo_head_hexsha": "33340f22e9dbe0b7ccc60f0c828c2a528737c81e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GeoLib/AnalyticalGeometry.cpp", "max_forks_repo_name": "garibay-j/ogs", "max_forks_repo_head_hexsha": "33340f22e9dbe0b7ccc60f0c828c2a528737c81e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8153034301, "max_line_length": 80, "alphanum_fraction": 0.5178953678, "num_tokens": 6766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.40981562828708934}}
{"text": "/* Copyright (C) 2017 IBM Corp.\n *  Licensed under the Apache License, Version 2.0 (the \"License\"); \n * you may not use this file except in compliance with the License. \n * You may obtain a copy of the License at\n *     http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, \n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific\n * language governing permissions and limitations under the License. \n */\n/*****************************************************************************\n * TDMatrix.cpp - Matrixes with trapdoors,\n *   implementing the Efficient algorithm SampleD - Algorithm 3 from MP12.\n *****************************************************************************/\n#include <stdexcept>\n#include <ctime>\n#include <NTL/mat_ZZ.h>\n#include <NTL/mat_lzz_p.h>\n#include <iostream>\n#include <fstream>\n\nNTL_CLIENT\n#include \"utils/timing.h\"\n#include \"TDMatrix.h\"\n#include \"mat_l.h\"\n\n//#define DEBUGPRINT\n//#define DEBUG\n//#define PRINTDOT //show how program progresses\n\n// A static variable for debugging purposes\nstd::atomic<int> TDMatrix::maxSample(0); // keep the largest sample ever drawn\n\n/***** Some local functions *****/\n\n// Compute the covariance matrix sigmaP = sigmaX*I - sigmaG*[R/I]*(R^t|I)\nstatic void\ncomputeCovarianceMatrix(mat_l& covMat,const mat_l& R,long sigmaG,long sigmaX);\n\n// Multiply a vector by the G matrix modulo the current NTL modulus, y=G*x.\n// G is and n-by-m matrix with m=n*e*numOfFactors, and is defind by means\n// of the vector of factors and the exponent e, each row of G is mostly zero,\n// except for a progression\n//    ( 1, f1,...,f1^e,  (f1^e f2), (f1^e f2^2), ..., (f1^e...fk^{e-1}) )\ntemplate<class T>\nvoid multByG(vec_zz_p &y, const Vec<T> &x,\n             long n, const vec_l& factors, long e)\n{\n    FHE_TIMER_START;\n    long k = factors.length();\n    long m = n*k*e;\n\n    assert(x.length()==m);\n    y.SetLength(n);\n\n    for (long row=0; row<n; row++)   // Multiply x by next row of G\n    {\n        long index = row*k*e;      // first non-zero entry in this row\n        zz_p val = to_zz_p(1L);  // value in current entry of G\n        y[row] = to_zz_p(0L);    // accumulated sum\n        for (long f=0; f<k; f++)     // go over all the factors\n        {\n            zz_p fact = to_zz_p(factors[f]); // convert to zz_p\n            for (long i=0; i<e; i++)    // use each factor e times\n            {\n                zz_p addedTerm = val;\n                addedTerm *= x[index++];  // update sum, advance index\n                y[row] += addedTerm;\n                val *= fact;              // compute next entry in this row of G\n            }\n        } // end of current factor\n    } // end of current row\n}\n// Explicit instantiations for Vec<long> and Vec<zz_p>\ntemplate void multByG<zz_p>(vec_zz_p &y, const Vec<zz_p> &x,\n                            long n, const vec_l& factors, long e);\ntemplate void multByG<long>(vec_zz_p &y, const Vec<long> &x,\n                            long n, const vec_l& factors, long e);\n\n\n// Choose a (pseudo)random A with a trapdoor R s.t. A*[R/I]=G\n// A=(aBar| aPrime ) with aPrime=G-aBar*R isn't computed explicitly here\nvoid TDMatrix::initTDmatrix(TDMatrixParams& prms, const CRTmatrix* abar)\n{\n    FHE_TIMER_START;\n    params = &prms;\n\n    if (abar)   // aBar is specified by the caller\n        aBarCRT = *abar;\n    else        // Choose aBar at random\n        randomFill(aBarCRT, prms.n, prms.mBar, prms);\n\n    mat_l sigmaP;\n    do\n    {\n        // Choose R as a random small matrix\n        setSmall(trapDoorMatR, params->mBar,params->wLen, params->r);\n\n        // Compute the covariance matrix sigmaP = sigmaX*I - sigmaG*[R/I]*(R^t|I)\n\n        computeCovarianceMatrix(sigmaP, trapDoorMatR,\n                                /*sigmaG=*/prms.r *prms.maxFactor, prms.sigmaX);\n\n#ifdef DEBUGPRINT\n        long minVal =0;\n        long maxVal=0;\n        for (long i = 0; i < sigmaP.NumCols(); i++)\n            for (long j = 0; j < sigmaP.NumRows(); j++)\n            {\n                if (sigmaP[i][j] < minVal)\n                    minVal = sigmaP[i][j];\n                if (sigmaP[i][j] > maxVal)\n                    maxVal = sigmaP[i][j];\n             }\n\n        ZZ q = prms.getQ();\n        cout << \"minVal=\" << minVal << endl;\n        cout << \"maxVal=\" << maxVal << endl;\n        cout << \"q=\" << q << endl;\n        cout << \"after computeCovarianceMatrix\"  << endl;\n#endif // DEBUGPRINT\n    }\n    while (!(gaussSamp.InitSampler(sigmaP)));  // error, try again\n\n#ifdef DEBUGPRINT\n        cout << \"after gaussSamp.InitSampler\"  << endl;\n#endif // DEBUGPRINT\n}\n\n\n// Compute the covariance matrix sigmaP = sigmaX*I - sigmaG*[R/I]*(R^t|I)\n// Note that [R/I]*(R^t|I) is a block matrix with this form:\n//    RR = ( R^2 | R^t )\n//         (  R  |  I  )\nvoid computeCovarianceMatrix(mat_l& covMat, const mat_l& R, long sigmaG,long sigmaX)\n{\n\n    FHE_TIMER_START;\n\n    long mBar = R.NumRows();\n    long wLen = R.NumCols();\n    long m = mBar + wLen;\n\n    covMat.SetDims(m,m); // allocate space\n\n    mat_l tmp(INIT_SIZE, mBar, mBar);\n    square(tmp, R);   // Set the top-left mBar-by-mBar as R*R^t\n\n    // Reset the top-left to sigmaX*I - sigmaG*R*R^t\n    for (long i=0; i<mBar; i++) for (long j=0; j<mBar; j++)\n        {\n            if (i==j)\n                covMat[i][j] = sigmaX - sigmaG*tmp[i][j];\n            else\n                covMat[i][j] = -sigmaG*tmp[i][j];\n        }\n\n    // Set the top-right ro -sigmaG*R^t and the bootom-left to -sigmaG*R\n    for (long i=0; i<mBar; i++) for (long j=0; j<wLen; j++)\n        {\n            covMat[i][j+mBar] = covMat[j+mBar][i] = -sigmaG * R[i][j];\n        }\n\n    // Finally set the bottom-right to (sigmaX-sigmaG)*I;\n    for (long i=mBar; i<m; i++) for (long j=mBar; j<m; j++)\n        {\n            if (i==j) covMat[i][j] = sigmaX -sigmaG;\n            else      covMat[i][j] = 0;\n        }\n}\n\n\n// Compute A explicitly, A = ( aBar | G - aBar*R )\nvoid TDMatrix::getA(CRTmatrix& A) const\n{\n    FHE_TIMER_START;\n    A.params = params;\n\n    long n = params->n;\n    long m = params->m;\n    long kFactors = params->kFactors;\n    long mBar = params->mBar;\n\n    // Compute A modulo each factor separately\n\n    zz_pPush ppush; // backup NTL's current modulus\n    A.SetLength(kFactors);\n    for (long f=0; f<kFactors; f++)\n    {\n        params->zzp_context[f].restore();\n        mat_zz_p& aMod = A[f];\n        const mat_zz_p& aBarMod = aBarCRT[f];\n\n        aMod.SetDims(n,m); // allocate space\n\n        // Copy aBar\n        for (long i=0; i<n; i++) for (long j=0; j<mBar; j++)\n            {\n                aMod[i][j] = aBarMod[i][j];\n            }\n\n        // Compute aBar * R\n        mat_zz_p tmp;\n        mat_zz_p rMod;\n        conv(rMod, trapDoorMatR); // conver to zz_p format\n        mul(tmp, aBarMod, rMod); // tmp = aBar * R (mod P_f)\n\n        // Copy -aBar*R to left part of A\n        for (long i=0; i<n; i++) for (long j=mBar; j<m; j++)\n            {\n                aMod[i][j] = -tmp[i][j-mBar];\n            }\n\n        // Add G to left part of A\n        for (long i=0; i<n; i++)    // one row at a time\n        {\n            // Add (1, f1, f1^2, ..., f1^e...fk^{e-1}) to each row\n\n            long index = (i * kFactors * params->e) + mBar; // 1st index to add to\n\n            zz_p val = to_zz_p(1L);      // The value to add to the next entry\n            for (long j=0; j < kFactors; j++)\n                for (long ei=0; ei<params->e; ei++, index++)\n                {\n                    aMod[i][index] += val;\n                    val *= params->factors[j];// Change value to add before next entry\n                }\n        }\n    }\n\n}\n\n/** sampleWithTrapdoor - Implementation of Efficient algorithm SampleD -\n * Algorithm 3 from MP12. Choose p at random and z to match the needed\n * solution. This debugging function also returns p and z.\n **/\nint TDMatrix::sampleWithTrapdoor(vec_l &xOut, vec_l& p, vec_l& z,\n                                 Vec<vec_zz_p>& U) const\n{\n    FHE_TIMER_START;\n    long mBar = params->mBar;\n    long m = params->m;\n    long n = params->n;\n    long e = params->e;\n    long kFactors = params->kFactors;\n\n    //choose perturbation P from (0,sigma)\n\n    Vec<double> zeroVector(INIT_SIZE, m);\n    clear(zeroVector);\n\n    gaussSamp.SampleDiscreteGaussian(p, zeroVector);\n#ifdef DEBUGPRINT\n    cout << \"\\np = \" << p << endl;\n#endif\n    // Split the pertubation vector in two\n    vec_l p1(INIT_SIZE, mBar);\n    for (long i = 0; i < mBar; i++)\n        p1[i] = p[i];\n\n    vec_l p2(INIT_SIZE, params->wLen);\n    for (long i = mBar; i < m; i++)\n        p2[i - mBar] = p[i];\n\n    //compute wBar and w\n\n    /* We need to compute v = u-A*p = u-wBar-w (in CRT representation), where\n     *\n     *    A*p = (Abar| Aprime ) * [p1/p2] = Abar*p1 + Aprime*p2\n     *        = Abar*p1 + (G-Abar*R)*p2   = Abar*(p1-R*p2) +  G*p2\n     *                                      \\___wBar____/    \\_w_/\n     */\n\n    // p1-R*p2 is computed over the integers, stored in p1\n    vec_l tmp(INIT_SIZE, mBar);\n    mul(tmp, trapDoorMatR, p2); // R*p2\n    p1 -= tmp;                  // p1-R*p2\n\n    // All other vectors are computed modulo each of the factors\n\n    // FIXME: There's room for parallelization here, but in our case we have\n    // thousands of calls to sampleWithTrapdoor that can be run in parallel,\n    // so there is no reason to parallelize also at this lower level.\n\n    zz_pPush push; // backup NTL's current modulus\n\n    Vec<vec_zz_p> vVec = U; // allocate space and initialize v=u\n    vec_zz_p wMod, wBarMod;\n    for (long iE = 0; iE < kFactors; iE++)\n    {\n        params->zzp_context[iE].restore();\n\n        // Compute Abar*(p1-R*p2) modulo the current factor\n        const mat_zz_p& aBarMod = aBarCRT[iE];\n        mul(wBarMod, aBarMod, conv<vec_zz_p>(p1));  // wBar = Abar*(p1-R*p2)\n        // convert p1-R*p2 to vec_zz_p and multiply by aBar modulo each factor\n\n        vVec[iE] -= wBarMod; // u - wBar\n\n        multByG(wMod, p2, n, params->factors, e); // w = G*p2\n        vVec[iE] -= wMod;    // u - wBar - w\n    }\n\n    // Now that we computed v modulo all the primes, sample z s.t. G*z=v\n\n    sampleG(z, vVec, params);\n#ifdef DEBUGPRINT\n    cout << \"z = \" << z << endl;\n#endif\n    // finally, return x = p + [R/I]*z = p + [R*z / z]\n\n    xOut = p;\n    mul(tmp, trapDoorMatR, z); // add R*z to top mBar entries\n#ifdef DEBUGPRINT\n    cout << \"R*z = \" << tmp << endl;\n#endif\n    for (long i=0; i<mBar; i++)\n    {\n      xOut[i] += tmp[i];\n      long absX = abs(xOut[i]);\n      if (absX > TDMatrix::maxSample) TDMatrix::maxSample.store(absX);\n         // not quite thread-safe, the stored value may not be the maximum\n    }\n\n    // add z to bottom m-mBar entries\n    for (long i = mBar; i< params->m; i++)\n    {\n      xOut[i] += z[i - mBar];\n      long absX = abs(xOut[i]);\n      if (absX > TDMatrix::maxSample) TDMatrix::maxSample.store(absX);\n         // not quite thread-safe, the stored value may not be the maximum\n    }\n    return 0;\n}\n\n//Write TDMatrix different parameters to file. The handle to the open\n//file is sent as input to the function. returns number of items read by\n//the function\nlong TDMatrix::writeToFile(FILE* handle)\n{\n    FHE_TIMER_START;\n    long count = 0;\n\n    count += params->writeToFile(handle); // write the params\n    count += aBarCRT.writeToFile(handle); // write the Abar matrix\n\n    long numRows = trapDoorMatR.NumRows();\n    long numCols = trapDoorMatR.NumCols();\n    count += fwrite(&numRows,sizeof(long),1,handle);\n    count += fwrite(&numCols,sizeof(long),1,handle);\n    for (long i = 0; i < numRows; i++)  // write the rows of R, one at a time\n    {\n        count+= fwrite(trapDoorMatR[i].elts(), sizeof(long), numCols, handle);\n        // each row is implemented as a C vector\n    }\n\n    count += gaussSamp.writeToFile(handle); // write the DGaussSampler\n\n    return count;\n}\n\n//Read the TDMatrix parameters from a flie. The handle to the open file is\n//received as input to this function, as well as a pointer to the TDMatrixParams\n//if the pointer is not provided and params as not been initialized before, an\n//error occurs, as a pointer to this structure is needed\n//returns number of items read by the function\n\nlong TDMatrix::readFromFile(FILE* handle, TDMatrixParams* prmBuf)\n{\n    FHE_TIMER_START;\n    assert(params != NULL || prmBuf != NULL); // some pointer must be provided\n    long count=0;\n\n    // If buffer is given, make params point to it and don't overwrite from iput\n    if (prmBuf != NULL)\n    {\n        TDMatrixParams p;\n        count += p.readFromFile(handle);\n        assert(p == *prmBuf); // sanity check\n        params = prmBuf;      // point to given params\n    }\n    else\n        count += params->readFromFile(handle); // overwrite params from input\n\n    count += aBarCRT.readFromFile(handle,prmBuf); // read the Abar matrix\n\n    long numRows,numCols;\n    count += fread(&numRows,sizeof(long),1,handle);\n    count += fread(&numCols,sizeof(long),1,handle);\n    trapDoorMatR.SetDims(numRows,numCols);\n    for (long i = 0; i < numRows; i++)  // write the rows of R, one at a time\n    {\n        count+= fread(trapDoorMatR[i].elts(), sizeof(long), numCols, handle);\n        // each row is implemented as a C vector\n    }\n\n    count += gaussSamp.readFromFile(handle); // read the DGaussSampler\n\n    return count;\n}\n\n// operator==, //compares all variables in TDMatrix\nbool operator==(const TDMatrix& A, const TDMatrix& B)\n{\n    FHE_TIMER_START;\n    if (A.getParams() != B.getParams())\n        return false;\n\n    if (A.getABar() != B.getABar())\n        return false;\n\n    if (A.getR() != B.getR())\n        return false;\n\n    return true;\n}\n\n#ifdef DEBUG\nstatic void printTrapdoor(const mat_l& td, const TDMatrixParams& params)\n{\n    FHE_TIMER_START;\n    double maxR = 0;\n    double AvgR=1;\n    //  long TotalItems;\n\n    for (long i=0; i < params.mBar; i++)\n        for (long j=0; j < params.wLen; j++)\n        {\n            if (abs(td[i][j]) > maxR)\n                maxR = abs(td[i][j]);\n            AvgR *= (double)(i*params.wLen+j)/(i*params.wLen+j+1);\n            AvgR+=(double)abs(td[i][j]) /(i*params.wLen+j+1);\n        }\n    cout << \"maxR = \" << maxR << \", AvgR = \" << AvgR << \"\\n\";\n\n    mat_l rSquare;\n    //how large is R^2?\n    square(rSquare,td);\n    //  cout << \"trapDoorMatR=\" << td << \"rSquare= \" << rSquare << \"\\n\";\n\n    maxR = 0;\n    AvgR=1;\n    for (long i=0; i < params.mBar; i++)\n        for (long j=0; j < params.mBar; j++)\n        {\n            if (abs(rSquare[i][j]) > maxR)\n                maxR = abs(rSquare[i][j]);\n            AvgR *= (double)(i*params.wLen+j)/(i*params.wLen+j+1);\n            AvgR+=(double)abs(rSquare[i][j]) /(i*params.wLen+j+1);\n        }\n    cout << \"maxRSquare = \" << maxR << \", AvgRSquare = \" << AvgR << \"\\n\";\n}\n#endif //DEBUG\n", "meta": {"hexsha": "ac78bf757c338e1c989ae10831985a7b6263c10c", "size": 14846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TDMatrix.cpp", "max_stars_repo_name": "shaih/BPobfus", "max_stars_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-09-25T14:37:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T03:19:43.000Z", "max_issues_repo_path": "TDMatrix.cpp", "max_issues_repo_name": "shaih/BPobfus", "max_issues_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TDMatrix.cpp", "max_forks_repo_name": "shaih/BPobfus", "max_forks_repo_head_hexsha": "9c116312a8c9c0bc47a1c4b20e771c60c2510c6e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-12-23T04:03:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-12T07:42:29.000Z", "avg_line_length": 32.6285714286, "max_line_length": 86, "alphanum_fraction": 0.5682338677, "num_tokens": 4338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.6001883592602051, "lm_q1q2_score": 0.409672817482086}}
{"text": "#ifndef MATHTOOLBOX_BAYESIAN_OPTIMIZATION_HPP\n#define MATHTOOLBOX_BAYESIAN_OPTIMIZATION_HPP\n\n#include <Eigen/Core>\n#include <memory>\n#include <utility>\n\nnamespace mathtoolbox\n{\n    class GaussianProcessRegressor;\n\n    namespace optimization\n    {\n        enum class KernelType\n        {\n            ArdSquaredExp,\n            ArdMatern52\n        };\n\n        /// \\brief An optimizer class for managing Bayesian optimization iterations\n        ///\n        /// \\details This optimizer solves a maximization problem with a black-box function.\n        class BayesianOptimizer\n        {\n        public:\n            BayesianOptimizer(const std::function<double(const Eigen::VectorXd&)>& f,\n                              const Eigen::VectorXd&                               lower_bound,\n                              const Eigen::VectorXd&                               upper_bound,\n                              const KernelType& kernel_type = KernelType::ArdMatern52);\n\n            /// \\brief Perform a single step of the Bayesian optimization algorithm\n            /// \\return Newly observed data point\n            std::pair<Eigen::VectorXd, double> Step();\n\n            /// \\brief Calculate the function value\n            /// \\return Evaluated function value\n            double EvaluatePoint(const Eigen::VectorXd& x) const;\n\n            /// \\brief Predict the mean value\n            /// \\return Predicted mean value\n            double PredictMean(const Eigen::VectorXd& x) const;\n\n            /// \\brief Predict the standard deviation value\n            /// \\return Predicted standard deviation value\n            double PredictStdev(const Eigen::VectorXd& x) const;\n\n            /// \\brief Calculate the acquisition function value at the point\n            /// \\return Acquisition function value at the point\n            double CalcAcquisitionValue(const Eigen::VectorXd& x) const;\n\n            /// \\brief Retrieve the optimizer found so far\n            /// \\return Optimizer found so far\n            Eigen::VectorXd GetCurrentOptimizer() const;\n\n            /// \\brief Get the observed data points and their values\n            std::pair<Eigen::MatrixXd, Eigen::VectorXd> GetData() const;\n\n        private:\n            const std::function<double(const Eigen::VectorXd&)> m_f;\n\n            const Eigen::VectorXd m_lower_bound;\n            const Eigen::VectorXd m_upper_bound;\n\n            const KernelType m_kernel_type;\n\n            Eigen::MatrixXd m_X;\n            Eigen::VectorXd m_y;\n\n            std::shared_ptr<GaussianProcessRegressor> m_regressor;\n\n            void AddDataEntry(const Eigen::VectorXd& x_new, const double y_new);\n            void ConstructSurrogateFunction();\n        };\n    } // namespace optimization\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_BAYESIAN_OPTIMIZATION_HPP\n", "meta": {"hexsha": "8b5bfd06a74f52bf9c18b92e8f8e7736e80f4b32", "size": 2798, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/bayesian-optimization.hpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "include/mathtoolbox/bayesian-optimization.hpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "include/mathtoolbox/bayesian-optimization.hpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 35.8717948718, "max_line_length": 95, "alphanum_fraction": 0.6065046462, "num_tokens": 538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.40967280973104375}}
{"text": "// Linear Models\n//\n// Special Naming Convention:\n//\n// All mathematical matrix variables are named by captial letters\n// (e.g. X means input feature dataset). Vectors are named by lowercase\n// (e.g. w means weights vector). These variables are always from Eigen.\n//\n// The key feature of this linear model is it was implemented by\n// advanced and efficient c++ matrix library Eigen, but only for the\n// training stage. After that, the weights are stored in normal c++\n// array for fast predicting and robust interface.\n//\n// @author: Bingqing Qu\n//\n// Copyright (C) 2014-2015  Bingqing Qu <sylar.qu@gmail.com>\n//\n// @license: See LICENSE at root directory\n\n#ifndef OPENLINEAR_LINEAR_H_\n#define OPENLINEAR_LINEAR_H_\n\n#include <assert.h>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <memory>\n#include <algorithm>\n#include <exception>\n#include <stdexcept>\n#include <Eigen/SparseCore>\n#include <Eigen/Core>\n#include <stdio.h>\n#include <stdarg.h>\nnamespace oplin{\n\n// Define Eigen vector and matrix types we will use\ntypedef Eigen::SparseMatrix<double, Eigen::RowMajor> SpRowMatrix;\ntypedef Eigen::SparseMatrix<double, Eigen::ColMajor> SpColMatrix;\ntypedef Eigen::SparseVector<double, Eigen::RowMajor> SpRowVector;\ntypedef Eigen::SparseVector<double, Eigen::ColMajor> SpColVector;\ntypedef Eigen::Matrix<double, Eigen::Dynamic, 1      , Eigen::ColMajor> ColVector;\ntypedef Eigen::Matrix<double, 1      , Eigen::Dynamic, Eigen::RowMajor> RowVector;\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMatrix;\ntypedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> ColMatrix;\n\n// smart pointers\ntypedef std::shared_ptr<SpColMatrix> SpColMatrixPtr;\ntypedef std::shared_ptr<ColMatrix> ColMatrixPtr;\ntypedef std::shared_ptr<ColVector> ColVectorPtr;\n\n//\nvoid VOUT(const char* fmt, ...);\n// very very light-weight and useful structure for <key,value> pair storage\ntemplate <class K, class V>\nstruct KeyValue\n{\n    K i;\n    V v;\n};\n/// Dataset parameters\nstruct Dataset\n{\n    /** number of samples */\n    size_t n_samples;\n    /** number of classes */\n    size_t n_classes;\n    /** feature dimension */\n    size_t dimension;\n    /** targets */\n    std::vector<double> y;\n    /** target labels */\n    std::vector<double> labels;\n    /**\n     * features w.r.t order of y\n     * dimension is dimension * n_samples\n     */\n    SpColMatrixPtr X;\n    double bias;\n    Dataset() : bias(-1.){}\n\n};\nenum FormulaType\n{\n    L1R_LR,\n    L2R_LR\n\n};\nenum SolverType\n{\n    GD,\n    SGD,\n    L_BFGS,\n    TRON\n};\n\n/// Parameters for training\nstruct Parameter\n{\n    /** define the solver type for training model */\n    int solver_type;\n    /** define the objective function for solving */\n    int problem_type;\n    /**\n     * relative tolerance between two continuous iterations\n     * for training stop criteria\n     */\n    double rela_tol;\n    /** absolute loss tolerance for iterative method */\n    double abs_tol;\n    /** learning rate for iterative method */\n    double learning_rate;\n    /** maximum iteration for iterative method */\n    size_t max_epoch;\n    /** C */\n    // std::vector<double> C;\n    double base_C;\n    std::vector<KeyValue<double,double> > adjust_C;\n\n    Parameter() : solver_type(0.), problem_type(0.){}\n};\ntypedef std::shared_ptr<Parameter> ParamPtr;\ntypedef std::shared_ptr<Dataset> DatasetPtr;\n\n\n/// Model Parameters\n///\n/// An important note here is the key part of model - weights:\n/// the representation of weight during training phase is an Eigen\n/// dense matrix under consideration of the matrix manipultion\n/// in fomulas. But finally converted to a normal c++ array as storage.\n/// The consideration here is firstly, the low level c++ array is though\n/// not safe in memory, I can validate the memory after training and\n/// once the double* is stored, no other manipulation should have\n/// previlige to modify it until it will be released by constructor.\n/// All in all, the segmentation fault will not happen here under the\n/// help of class encapsulation.\n///\n/// Secondly, the performance should have not much difference with\n/// vector but slightly better. The linear model always means fast in\n/// industry and that \"slightly\" is good for all users.\n///\nstruct Model\n{\n    /** number of classes */\n    size_t n_classes;\n    /** dimension of feature */\n    size_t dimension;\n    /** define a bias, 0 if no bias setting */\n    double bias;\n    /** labels of classes */\n    std::vector<double> labels;\n    Model() : W_(NULL),bias_values_(NULL){}\n    // destructor must be called for double*\n    ~Model()\n    {\n        delete [] W_;\n        delete [] bias_values_;\n    }\n    void set_bias_values(double* vals)\n    {\n        if(bias_values_)\n            delete [] bias_values_;\n        bias_values_ = vals;\n    }\n    void set_weights(double* w)\n    {\n        if(W_)\n            delete [] W_;\n        W_ = w;\n    }\n// I encapsulate the two pointers to avoid wrong reference in productive env.\nprivate:\n    double* W_;\n    double* bias_values_;\n    /** weights */\n\n    friend class LinearBase;\n};\n\ntypedef std::vector<KeyValue<size_t,double> > FeatureVector;\n// symbolic links for short implementation views\n// typedef std::shared_ptr<Model> ModelPtr;\n\n// the current design keep model to only one owner to avoid wrong reference in\n// productive env.\ntypedef std::unique_ptr<Model> ModelUniPtr;\n\n\n/// Base class for linear models\n///\n///\n///\nclass LinearBase\n{\nprotected:\n    // model instance\n    ModelUniPtr model_;\n    bool trained_;\n    void predict_WTx(const FeatureVector, std::vector<double>&);\n    void preprocess_data(const DatasetPtr, std::vector<size_t>&,\n                         std::vector<size_t>&, std::vector<size_t>&);\npublic:\n\n    LinearBase(void);\n    explicit LinearBase(ModelUniPtr);\n    virtual ~LinearBase(void){};\n\n    virtual bool is_trained();\n    virtual size_t get_n_classes();\n    virtual std::vector<double> get_labels();\n    virtual void load_model(ModelUniPtr);\n    virtual ModelUniPtr export_model();\n    virtual void export_model_to_file(const std::string&);\n    virtual void train(const DatasetPtr, const ParamPtr) = 0;\n    virtual double predict(const FeatureVector);\n    virtual double predict_proba(const FeatureVector, std::vector<double>&);\n};\n\n} // oplin\n// using namespace oplin;\n// using namespace oplin::model;\n#endif //OPENLINEAR_LINEAR_H_\n", "meta": {"hexsha": "7c04f5dd0371229e7562160e843d37a859162c3a", "size": 6364, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/linear.hpp", "max_stars_repo_name": "Jetpie/OpenLinear", "max_stars_repo_head_hexsha": "c501ab26bd53bcfd781d0aae22bb75392629000f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-04-07T12:37:50.000Z", "max_stars_repo_stars_event_max_datetime": "2015-07-02T01:38:30.000Z", "max_issues_repo_path": "include/linear.hpp", "max_issues_repo_name": "Jetpie/OpenLinear", "max_issues_repo_head_hexsha": "c501ab26bd53bcfd781d0aae22bb75392629000f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/linear.hpp", "max_forks_repo_name": "Jetpie/OpenLinear", "max_forks_repo_head_hexsha": "c501ab26bd53bcfd781d0aae22bb75392629000f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4107142857, "max_line_length": 89, "alphanum_fraction": 0.6915461974, "num_tokens": 1482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.782662489091802, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.40966147313980295}}
{"text": "#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <type_traits>\n#include <chrono>\nusing namespace std;\n\n\n#include <libsnark/gadgetlib1/gadgets/basic_gadgets.hpp>\n#include <libsnark/common/default_types/r1cs_ppzksnark_pp.hpp>\n#include <libff/common/utils.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libsnark/relations/constraint_satisfaction_problems/r1cs/examples/r1cs_examples.hpp>\n#include <boost/optional.hpp>\n#include <libff/algebra/curves/mnt/mnt4/mnt4_init.hpp>\n#include <libff/algebra/curves/mnt/mnt6/mnt6_init.hpp>\n#include <libsnark/gadgetlib1/gadgets/pairing/weierstrass_precomputation.hpp>\nusing namespace libsnark;\n\n#include \"gadget.hpp\"\n\n// Timer utility functions\n\nchrono::high_resolution_clock::time_point my_start, my_end;\n\nvoid\nmy_timer_start ()\n{\n  my_start = chrono::high_resolution_clock::now ();\n}\n\nint\nmy_timer_end ()\n{\n  my_end = chrono::high_resolution_clock::now ();\n  return std::chrono::duration_cast < std::chrono::milliseconds >\n    (my_end - my_start).count ();\n}\n\n\n// Function from pay-to-sudoku\nvoid\nconvertBytesToVector (const unsigned char *bytes, std::vector < bool > &v)\n{\n  int\n    numBytes = v.size () / 8;\n  unsigned char\n    c;\n  for (int i = 0; i < numBytes; i++)\n    {\n      c = bytes[i];\n\n      for (int j = 0; j < 8; j++)\n\t{\n\t  v.at ((i * 8) + j) = ((c >> (7 - j)) & 1);\n\t}\n    }\n}\n\nvoid\nconvertBytesVectorToBytes (const std::vector < unsigned char >&v,\n\t\t\t   unsigned char *bytes)\n{\n  for (size_t i = 0; i < v.size (); i++)\n    {\n      bytes[i] = v.at (i);\n    }\n}\n\n\nvoid\nconvertBytesVectorToVector (const std::vector < unsigned char >&bytes,\n\t\t\t    std::vector < bool > &v)\n{\n  v.resize (bytes.size () * 8);\n  unsigned char\n  bytesArr[bytes.size ()];\n  convertBytesVectorToBytes (bytes, bytesArr);\n  convertBytesToVector (bytesArr, v);\n}\n\ntemplate < typename ppT >\n  bool run_r1cs_ppzksnark (const r1cs_example < libff::Fr < ppT > >&example)\n{\n  libff::print_header (\"R1CS ppzkSNARK Generator\");\n  r1cs_ppzksnark_keypair < ppT > keypair =\n    r1cs_ppzksnark_generator < ppT > (example.constraint_system);\n \n  libff::print_header (\"R1CS ppzkSNARK Prover\");\n  r1cs_ppzksnark_proof < ppT > proof =\n    r1cs_ppzksnark_prover < ppT > (keypair.pk, example.primary_input,\n\t\t\t\t   example.auxiliary_input);\n \n\n  libff::print_header (\"R1CS ppzkSNARK Verifier\");\n  const bool\n    ans =\n    r1cs_ppzksnark_verifier_strong_IC < ppT > (keypair.vk,\n\t\t\t\t\t       example.primary_input, proof);\n  printf (\"* The verification result is: %s\\n\", (ans ? \"PASS\" : \"FAIL\"));\n  \n  return ans;\n}\n\ntemplate < typename ppT > r1cs_example < libff::Fr < ppT >> gen_BLS_example ()\n{\n  typedef\n    libff::Fr <\n    ppT >\n    FieldT;\n\n  protoboard < FieldT > pb;\n\n  fair_auditing_gadget < ppT > g (pb);\n  const int\n    num_inputs = g.num_input_variables ();\n  g.generate_r1cs_constraints ();\n  \n  auto\n    cs = pb.get_constraint_system ();\n\n  auto\n    sigma = FieldT::random_element () * libff::G1 < other_curve < ppT >>::one ();\n  auto\n    gen = FieldT::random_element () * libff::G2 < other_curve < ppT >>::one ();\n  auto\n    M = sigma;\n  auto\n    y = gen;\n\n  libff::bit_vector\n    r;\n  libff::bit_vector\n    ad;\n\n  const\n    vector <\n    uint8_t >\n  r8bit =\n    { 206, 64, 25, 10, 245, 205, 246, 107, 191, 157, 114, 181, 63, 40, 95,\n134, 6, 178, 210, 43, 243, 10, 217, 251, 246, 248, 0, 21, 86, 194, 100, 94 };\n  const\n    vector <\n    uint8_t >\n  ad8bit =\n    { 253, 199, 66, 55, 24, 155, 80, 121, 138, 60, 36, 201, 186, 221, 164,\n65, 194, 53, 192, 159, 252, 7, 194, 24, 200, 217, 57, 55, 45, 204, 71, 9 };\n\n  convertBytesVectorToVector (r8bit, r);\n  convertBytesVectorToVector (ad8bit, ad);\n\n  g.generate_r1cs_witness (M, y, gen, ad, sigma, r);\n\n  cout << \"Num constraints \" << cs.num_constraints () << endl;\n\n  return r1cs_example < FieldT > (std::move (cs),\n\t\t\t\t  std::move (pb.primary_input ()),\n\t\t\t\t  std::move (pb.auxiliary_input ()));\n}\n\nvoid\nsingle_test ()\n{\n  libff::init_mnt4_params ();\n  default_r1cs_ppzksnark_pp::init_public_params ();\n\n  r1cs_example < libff::Fr < default_r1cs_ppzksnark_pp > >example =\n    gen_BLS_example < default_r1cs_ppzksnark_pp > ();\n\n\n  bool\n    it_works = run_r1cs_ppzksnark < default_r1cs_ppzksnark_pp > (example);\n  cout << endl;\n  cout << (it_works ? \"It works!\" : \"It failed.\") << endl;\n}\n\nvoid\nbenchmark (int numReps)\n{\n\n  libff::init_mnt4_params ();\n  default_r1cs_ppzksnark_pp::init_public_params ();\n\n  typedef default_r1cs_ppzksnark_pp\n    ppT;\n\n  r1cs_example < libff::Fr < default_r1cs_ppzksnark_pp > >example =\n    gen_BLS_example < default_r1cs_ppzksnark_pp > ();\n\n  int\n    keygen_t,\n    prov_t,\n    ver_t;\n  keygen_t = prov_t = ver_t = 0;\n\n  for (auto i = 1; i <= numReps; i++)\n    {\n      // Key generation\n      my_timer_start ();\n      r1cs_ppzksnark_keypair < ppT > keypair =\n\tr1cs_ppzksnark_generator < ppT > (example.constraint_system);\n      keygen_t += my_timer_end ();\n\n      // Proof\n      my_timer_start ();\n      r1cs_ppzksnark_proof < ppT > proof =\n\tr1cs_ppzksnark_prover < ppT > (keypair.pk, example.primary_input,\n\t\t\t\t       example.auxiliary_input);\n      prov_t += my_timer_end ();\n\n      // Verification\n      my_timer_start ();\n      r1cs_ppzksnark_verifier_strong_IC < ppT > (keypair.vk,\n\t\t\t\t\t\t example.primary_input,\n\t\t\t\t\t\t proof);\n      ver_t += my_timer_end ();\n    }\n\n  cout << \"Avg Keygen Time: \" << keygen_t / numReps << \" millis\" << endl;\n  cout << \"Avg Proving Time: \" << prov_t / numReps << \" millis\" << endl;\n  cout << \"Avg Verification Time: \" << ver_t / numReps << \" millis\" << endl;\n}\n\n\nint\nmain (int argc, char **argv)\n{\n  single_test();\n\n  //benchmark (100);\n\n  return 0;\n\n}\n", "meta": {"hexsha": "058bd4177937e2030de0e7361dd7e9d7f53f1b3f", "size": 5650, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "duyuefeng0708/libsnark-tutorial", "max_stars_repo_head_hexsha": "8f84e069cac4bff4604291c8d9e40a41ff935953", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-01T09:07:33.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-01T09:07:33.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "duyuefeng0708/zkcsp-test", "max_issues_repo_head_hexsha": "8f84e069cac4bff4604291c8d9e40a41ff935953", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "duyuefeng0708/zkcsp-test", "max_forks_repo_head_hexsha": "8f84e069cac4bff4604291c8d9e40a41ff935953", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0425531915, "max_line_length": 94, "alphanum_fraction": 0.6543362832, "num_tokens": 1858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4096614678329149}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG, www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also tools/license/license.mtl.txt in the distribution.\n\n#ifndef MTL_VECTOR_MAKE_SPARSE_INCLUDE\n#define MTL_VECTOR_MAKE_SPARSE_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/operation/size.hpp>\n#include <boost/numeric/mtl/operation/update.hpp>\n#include <boost/numeric/mtl/matrix/compressed2D.hpp>\n#include <boost/numeric/mtl/matrix/inserter.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n\nnamespace mtl { namespace vector {\n\n// Commands in Matlab\n// S = sparse(i,j,s,m,n,nzmax)\n// S = sparse(i,j,s,m,n)\n// S = sparse(i,j,s)\n// S = sparse(m,n)\n\ntemplate <typename SizeVector, typename ValueVector>\nstruct make_sparse_trait\n{\n    typedef typename Collection<SizeVector>::value_type  size_type;\n    typedef typename Collection<ValueVector>::value_type value_type;\n    typedef matrix::parameters<row_major, index::c_index, mtl::non_fixed::dimensions, false, size_type> paras;\n    typedef matrix::compressed2D<value_type, paras>   type;\n};\n\n/// Generates an \\p m by \\p n matrix from the vectors \\p rows, \\p cols, and \\p values.\n/** A sparse matrix is created (compressed2D). The value type is the same as the element type\n    of the value vector and the size type the same as the entries of the vectors with the row indices.\n    Zero entries in \\p values are ignored. Entries with same coordinates are added.\n    Same as <a href=\"http://www.mathworks.de/de/help/matlab/ref/sparse.html\">Matlab's sparse</a> function besides that it is zero-indexed.\n **/\ntemplate <typename SizeVector1, typename SizeVector2, typename ValueVector>\ninline typename make_sparse_trait<SizeVector1, ValueVector>::type\nmake_sparse(const SizeVector1& rows, const SizeVector2& cols, const ValueVector& values,\n\t    std::size_t m, std::size_t n)\n{\n    MTL_THROW_IF(size(rows) != size(cols), incompatible_size());\n    MTL_THROW_IF(size(rows) != size(values), incompatible_size());\n\n    typedef make_sparse_trait<SizeVector1, ValueVector> traits;\n    typedef typename traits::type       matrix_type;\n    typedef typename traits::value_type value_type;\n    typedef typename traits::size_type  size_type;\n\n    size_type               ms(m), ns(n);  // shouldn't be needed :-!\n    matrix_type             A(ms, ns);\n    matrix::inserter<matrix_type, update_plus<value_type> > ins(A, size_type(size(rows) / m + 1));\n\n    for (std::size_t i= 0; i < size(rows); i++)\n\tif (values[i] != value_type(0))\n\t    ins[rows[i]][cols[i]] << values[i];\n    return A;\n}\n\n/// Generates an \\p m by \\p n matrix from the vectors \\p rows, \\p cols, and \\p values.\n/** A sparse matrix is created (compressed2D). The value type is the same as the element type\n    of the value vector and the size type the same as the entries of the vectors with the row indices.\n    Zero entries in \\p values are ignored. Entries with same coordinates are added. Last parameter\n    is ignored and can be omitted.\n    Same as <a href=\"http://www.mathworks.de/de/help/matlab/ref/sparse.html\">Matlab's sparse</a> function besides that it is zero-indexed.\n **/\ntemplate <typename SizeVector1, typename SizeVector2, typename ValueVector>\ninline typename make_sparse_trait<SizeVector1, ValueVector>::type\nmake_sparse(const SizeVector1& rows, const SizeVector2& cols, const ValueVector& values,\n\t    std::size_t m, std::size_t n, std::size_t)\n{\n    return make_sparse(rows, cols, values, m, n);\n}\n\n/// Generates a matrix from the vectors \\p rows, \\p cols, and \\p values.\n/** A sparse matrix is created (compressed2D). \n    The number of rows/columns is one plus the maximum of the entries of \\p rows and \\p cols.\n    The value type is the same as the element type\n    of the value vector and the size type the same as the entries of the vectors with the row indices.\n    Zero entries in \\p values are ignored. Entries with same coordinates are added.\n    Same as <a href=\"http://www.mathworks.de/de/help/matlab/ref/sparse.html\">Matlab's sparse</a> function besides that it is zero-indexed.\n **/\ntemplate <typename SizeVector1, typename SizeVector2, typename ValueVector>\ninline typename make_sparse_trait<SizeVector1, ValueVector>::type\nmake_sparse(const SizeVector1& rows, const SizeVector2& cols, const ValueVector& values)\n{\n    return make_sparse(rows, cols, values, max(rows)+1, max(cols)+1);\n}\n\n/// Generates an empty \\p m by \\p n matrix.\n/** A sparse matrix is created (compressed2D<double>). \n    Same as <a href=\"http://www.mathworks.de/de/help/matlab/ref/sparse.html\">Matlab's sparse</a> function besides that it is zero-indexed.\n **/\ninline matrix::compressed2D<double> make_sparse(std::size_t m, std::size_t n)\n{\n    return matrix::compressed2D<double>(m, n);\n}\n\n\n\n\n\n} // namespace :vector\n\n    using vector::make_sparse;\n\n} // namespace mtl\n\n#endif // MTL_VECTOR_MAKE_SPARSE_INCLUDE\n", "meta": {"hexsha": "fef68f3c33ebd6be47b96f1366dfc6e779d100c8", "size": 5145, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/make_sparse.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/operation/make_sparse.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/operation/make_sparse.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2352941176, "max_line_length": 138, "alphanum_fraction": 0.7271137026, "num_tokens": 1297, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.40958493765697795}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n/* sample.cpp - implementing various sampling routines */\n#include <vector>\n#include <NTL/ZZX.h>\n#include <NTL/ZZ_pX.h>\n#include <NTL/BasicThreadPool.h>\n#include \"NumbTh.h\"\n#include \"FHEContext.h\"\n#include \"sample.h\"\n#include \"norms.h\"\n\n#include \"powerful.h\"\n// only used in experimental Hwt sampler\n\nNTL_CLIENT\n\n// Sample a degree-(n-1) poly, with only Hwt nonzero coefficients\nvoid sampleHWt(zzX &poly, long n, long Hwt)\n{\n  if (n<=0) n=lsize(poly); if (n<=0) return;\n  if (Hwt>=n) {\n#ifdef DEBUG_PRINTOUT\n    std::cerr << \"Hwt=\"<<Hwt<<\">=n=\"<<n<<\", is this ok?\\n\";\n#endif\n    Hwt = n-1;\n  }\n  poly.SetLength(n); // allocate space\n  for (long i=0; i<n; i++) poly[i] = 0;\n\n  long i=0;\n  while (i<Hwt) {  // continue until exactly Hwt nonzero coefficients\n    long u = NTL::RandomBnd(n);  // The next coefficient to choose\n    if (poly[u]==0) { // if we didn't choose it already\n      long b = NTL::RandomBits_long(2)&2; // b random in {0,2}\n      poly[u] = b-1;                      //   random in {-1,1}\n\n      i++; // count another nonzero coefficient\n    }\n  }\n}\n// Sample a degree-(n-1) ZZX, with only Hwt nonzero coefficients\nvoid sampleHWt(ZZX &poly, long n, long Hwt)\n{\n  zzX pp;\n  sampleHWt(pp, n, Hwt);\n  convert(poly, pp);\n}\n\n// Sample a degree-(n-1) poly, with -1/0/+1 coefficients.\n// Each coefficients is +-1 with probability prob/2 each,\n// and 0 with probability 1-prob. By default, pr[nonzero]=1/2.\nvoid sampleSmall(zzX &poly, long n, double prob)\n{\n  if (n<=0) n=lsize(poly); if (n<=0) return;\n  //OLD: assert(prob>3.05e-5 && prob<=1); // prob must be in [2^{-15},1/2]\n  helib::assertTrue<helib::InvalidArgument>(prob > 3.05e-5, \"prob must be greater than 2^{-15}\");\n  helib::assertTrue<helib::InvalidArgument>(prob <= 1, \"prob must be less than or equal to 1\");\n  poly.SetLength(n);\n\n  constexpr long bitSize=16;\n  constexpr long hiMask = (1<<(bitSize-1)); // top bit = 2^15\n  constexpr long loMask = hiMask-1;         // bottom 15 bits\n\n  long threshold = round(hiMask*prob); // threshold/2^15 = Pr[nonzero]\n\n  NTL_EXEC_RANGE(n, first, last)\n  for (long i=first; i<last; i++) {\n    long u = NTL::RandomBits_long(bitSize); // a random 16-bit number\n    long uLo = u & loMask; // bottom 15 bits\n    long uHi = u & hiMask; // top bit\n\n    // with probability threshold/2^15, choose between +-1\n    if (uLo<threshold) { // compare low 15 bits to threshold\n      poly[i] = (uHi>>(bitSize-2))-1; // topBit*2 - 1 \\in {+-1}\n    }\n\n    // with probability 1-prob, set to zero\n    else poly[i] = 0;\n  }\n  NTL_EXEC_RANGE_END\n}\nvoid sampleSmall(ZZX &poly, long n, double prob)\n{  \n  zzX pp;\n  sampleSmall(pp, n, prob);\n  convert(poly.rep, pp);\n  poly.normalize();\n}\n\n// Choose a vector of continuous Gaussians\nvoid sampleGaussian(std::vector<double> &dvec, long n, double stdev)\n{\n  static double const Pi=4.0*atan(1.0);  // Pi=3.1415..\n  static double const bignum = LONG_MAX; // convert to double\n  // THREADS: C++11 guarantees these are initialized only once\n\n  if (n<=0) n=lsize(dvec); if (n<=0) return;\n  dvec.resize(n, 0.0);        // allocate space for n variables\n\n  // Uses the Box-Muller method to get two Normal(0,stdev^2) variables\n  for (long i=0; i<n; i+=2) {\n    // r1, r2 are \"uniform in (0,1)\"\n    double r1 = (1+NTL::RandomBnd(LONG_MAX))/(bignum+1);\n    double r2 = (1+NTL::RandomBnd(LONG_MAX))/(bignum+1);\n    double theta=2*Pi*r1;\n    double rr= sqrt(-2.0*log(r2))*stdev;\n    if (rr > 8*stdev) // sanity-check, trancate at 8 standard deviations\n      rr = 8*stdev;\n\n    // Generate two Gaussians RV's\n    dvec[i] = rr*cos(theta);\n    if (i+1 < n)\n      dvec[i+1] = rr*sin(theta);\n  }\n}\n\n// Sample a degree-(n-1) ZZX, with rounded Gaussian coefficients\nvoid sampleGaussian(zzX &poly, long n, double stdev)\n{\n  if (n<=0) n=lsize(poly); if (n<=0) return;\n  std::vector<double> dvec;\n  sampleGaussian(dvec, n, stdev); // sample continuous Gaussians\n\n  // round and copy to coefficients of poly\n  clear(poly);\n  poly.SetLength(n); // allocate space for degree-(n-1) polynomial\n  for (long i=0; i<n; i++)\n    poly[i] = long(round(dvec[i])); // round to nearest integer\n}\n// Sample a degree-(n-1) ZZX, with rounded Gaussian coefficients\nvoid sampleGaussian(ZZX &poly, long n, double stdev)\n{\n  zzX pp;\n  sampleGaussian(pp, n, stdev);\n  convert(poly.rep, pp);\n  poly.normalize();\n}\n#if 0\nvoid sampleGaussian(ZZX &poly, long n, double stdev)\n{\n  static double const Pi=4.0*atan(1.0); // Pi=3.1415..\n  static long const bignum = 0xfffffff;\n  // THREADS: C++11 guarantees these are initialized only once\n\n  if (n<=0) n=deg(poly)+1; if (n<=0) return;\n  poly.SetMaxLength(n); // allocate space for degree-(n-1) polynomial\n  for (long i=0; i<n; i++) SetCoeff(poly, i, ZZ::zero());\n\n  // Uses the Box-Muller method to get two Normal(0,stdev^2) variables\n  for (long i=0; i<n; i+=2) {\n    double r1 = (1+RandomBnd(bignum))/((double)bignum+1);\n    double r2 = (1+RandomBnd(bignum))/((double)bignum+1);\n    double theta=2*Pi*r1;\n    double rr= sqrt(-2.0*log(r2))*stdev;\n\n    //OLD: assert(rr < 8*stdev); // sanity-check, no more than 8 standard deviations\n    helib::assertTrue(rr < 8*stdev, \"no more than 8 standard deviations\");\n\n    // Generate two Gaussians RV's, rounded to integers\n    long x = (long) floor(rr*cos(theta) +0.5);\n    SetCoeff(poly, i, x);\n    if (i+1 < n) {\n      x = (long) floor(rr*sin(theta) +0.5);\n      SetCoeff(poly, i+1, x);\n    }\n  }\n  poly.normalize(); // need to call this after we work on the coeffs\n}\n#endif\n\n// Sample a degree-(n-1) zzX, with coefficients uniform in [-B,B]\nvoid sampleUniform(zzX& poly, long n, long B)\n{\n  //OLD: assert (B>0);\n  helib::assertTrue<helib::InvalidArgument>(B>0l, \"Invalid coefficient interval\");\n  if (n<=0) n=lsize(poly); if (n<=0) return;\n  poly.SetLength(n); // allocate space for degree-(n-1) polynomial\n\n  for (long i = 0; i < n; i++)\n    poly[i] = NTL::RandomBnd(2*B +1) - B;\n}\n\n// Sample a degree-(n-1) ZZX, with coefficients uniform in [-B,B]\nvoid sampleUniform(ZZX& poly, long n, const ZZ& B)\n{\n  //OLD: assert (B>0);\n  helib::assertTrue<helib::InvalidArgument>(static_cast<bool>(B>0l), \"Invalid coefficient interval\");\n  if (n<=0) n=deg(poly)+1; if (n<=0) return;\n  clear(poly);\n  poly.SetMaxLength(n); // allocate space for degree-(n-1) polynomial\n\n  ZZ UB = 2*B +1;\n  for (long i = n-1; i >= 0; i--) {\n    ZZ tmp = RandomBnd(UB) - B;\n    SetCoeff(poly, i, tmp);\n  }\n}\n\n\n/********************************************************************\n * Below are versions of the sampling routines that sample modulo\n * X^m-1 and then reduce mod Phi_m(X). The exception is when m is\n * a power of two, where we still sample directly mod Phi_m(X).\n ********************************************************************/\ndouble sampleHWt(zzX &poly, const FHEcontext& context, long Hwt)\n{\n  const PAlgebra& palg = context.zMStar;\n  double retval;\n\n  if (palg.getPow2() == 0) { // not power of two\n    long m = palg.getM();\n    sampleHWt(poly, m, Hwt);\n    reduceModPhimX(poly, palg);\n    retval = context.noiseBoundForHWt(Hwt, m);\n  }\n  else { // power of two\n    long phim = palg.getPhiM();\n    sampleHWt(poly, phim, Hwt);\n    retval = context.noiseBoundForHWt(Hwt, phim);\n  }\n\n  return retval;\n}\n\n\ndouble sampleHWtBoundedEffectiveBound(const FHEcontext& context, long Hwt)\n{\n#if FFT_IMPL // is there any implementation of canonicalEmbedding?\n  const PAlgebra& palg = context.zMStar;\n\n  long deg_bnd = (palg.getPow2() == 0) ? palg.getM() : palg.getPhiM();\n\n  long log_deg_bnd = long(log(double(deg_bnd))/log(2.0) + 0.5) + 1;\n  //  sqrt(2) * deg_bnd  <= 2^{log_deg_bnd} <= 2*sqrt(2) * deg_bnd\n\n  // we use log_deg_bnd as in index into the erfc_inverse table\n  // so that we get a noise bound that should be satisfied\n  // with probablity at least 1/sqrt(2).\n\n  //OLD: assert(log_deg_bnd < ERFC_INVERSE_SIZE);\n  helib::assertTrue(log_deg_bnd < ERFC_INVERSE_SIZE, \"log_deg_bnd must be less than ERFC_INVERSE_SIZE\");\n  double scale = erfc_inverse[log_deg_bnd];\n  double bound = scale * sqrt(double(Hwt));\n    \n  return bound;\n#else\n  const PAlgebra& palg = context.zMStar;\n  double retval;\n\n  if (palg.getPow2() == 0) { // not power of two\n    long m = palg.getM();\n    retval = context.noiseBoundForHWt(Hwt, m);\n  }\n  else { // power of two\n    long phim = palg.getPhiM();\n    retval = context.noiseBoundForHWt(Hwt, phim);\n  }\n  return retval;\n#endif\n}\n\n#if 1\ndouble sampleHWtBounded(zzX &poly, const FHEcontext& context, long Hwt)\n{\n#if FFT_IMPL // is there any implementation of canonicalEmbedding?\n  double bound = sampleHWtBoundedEffectiveBound(context, Hwt);\n  const PAlgebra& palg = context.zMStar;\n    \n  double val;\n  long count = 0;\n  do {\n    sampleHWt(poly, context, Hwt);\n    val = embeddingLargestCoeff(poly,palg);\n    //cerr << \"****** \" << (val/bound) << \"\\n\";\n  }\n  while (++count<1000 && val>bound); // repeat until <= bound\n\n  if (val>bound) {\n    std::stringstream ss;\n    ss << \"Error: sampleSmallBounded, after \"\n         << count<<\" trials, still val=\"<<val\n         << '>'<<\"bound=\"<<bound;\n    throw helib::RuntimeError(ss.str());\n  }\n  return bound;\n#else\n  return sampleHWt(poly, context, Hwt);\n#endif\n   \n}\n\n#elif 0\n\n// Experimental version\n\nstatic ZZ \ncalculate_matrix_norm(const zzX& try_poly, const FHEcontext& context)\n{\n  const RecryptData& rcData = context.rcData;\n  const PowerfulDCRT* p2dConv = rcData.p2dConv;\n  const PAlgebra& palg = context.zMStar;\n  long phim = palg.getPhiM();\n  long m = palg.getM();\n  const ZZX& PhimX = palg.getPhimX();\n\n  ZZX poly;\n  convert(poly, try_poly);\n\n  IndexSet iset = IndexSet( context.ctxtPrimes.first(), \n                            min( context.ctxtPrimes.first()+3, \n                                context.ctxtPrimes.last() ) );\n  // use a smaller prime set for powerful conversions\n  // right now, we just use the first 3  ctxt primes\n   \n  ZZ retval {0};\n\n  for (long i: range(phim)) {\n    if (i%300 == 0) cerr << \".\";\n    Vec<ZZ> basis_vec;\n    basis_vec.SetLength(phim);\n    basis_vec[i] = 1;\n\n    ZZX basis_poly;\n    p2dConv->powerfulToZZX(basis_poly, basis_vec, iset);\n\n    basis_poly = basis_poly*poly;\n\n    // reduce basis_poly mod X^m-1, which is enough for ZZXtoPowerful\n    long d = basis_poly.rep.length();\n\n    if (d > m) {\n      for (long j: range(m, d)) {\n        basis_poly.rep[j-m] += basis_poly.rep[j];\n      }\n      basis_poly.rep.SetLength(m);\n      basis_poly.normalize();\n    }\n    \n    p2dConv->ZZXtoPowerful(basis_vec, basis_poly, iset);\n\n    for (long j: range(phim)) {\n      retval += basis_vec[j]*basis_vec[j];\n    }\n  }\n\n  return retval;\n}\n\ndouble sampleHWtBounded(zzX &poly, const FHEcontext& context, long Hwt)\n{\n#if FFT_IMPL // is there any implementation of canonicalEmbedding?\n  double bound = sampleHWtBoundedEffectiveBound(context, Hwt);\n  const PAlgebra& palg = context.zMStar;\n    \n\n  ZZ best_matrix_norm;\n  zzX best_poly;\n\n  cerr << \"*** starting trials\\n\";\n\n  for (long trials = 0; trials < 20; trials++) {\n\n    zzX try_poly;\n\n    double val;\n    long count = 0;\n    do {\n      sampleHWt(try_poly, context, Hwt);\n      val = embeddingLargestCoeff(try_poly,palg);\n      //cerr << \"****** \" << (val/bound) << \"\\n\";\n    }\n    while (++count<1000 && val>bound); // repeat until <= bound\n\n    if (val>bound) {\n      std::stringstream ss;\n      ss << \"Error: sampleSmallBounded, after \"\n\t   << count<<\" trials, still val=\"<<val\n\t   << '>'<<\"bound=\"<<bound;\n      throw helib::RuntimeError(ss.str());\n    }\n\n    ZZ try_matrix_norm = calculate_matrix_norm(try_poly, context);\n\n    if (trials == 0 || try_matrix_norm < best_matrix_norm) {\n      best_matrix_norm = try_matrix_norm;\n      best_poly = try_poly; \n    }\n\n    cerr << try_matrix_norm << \"\\n\";\n  }\n\n  cerr << \"*** ending trials\\n\";\n\n  return bound;\n#else\n  return sampleHWt(poly, context, Hwt);\n#endif\n   \n}\n\n#else\n\nvoid sampleHWtAlt(zzX& poly, const FHEcontext& context, long Hwt)\n{\n  const RecryptData& rcData = context.rcData;\n  const PowerfulDCRT* p2dConv = rcData.p2dConv;\n  const PAlgebra& palg = context.zMStar;\n  long phim = palg.getPhiM();\n  long m = palg.getM();\n\n  Vec<ZZ> pwrfl;\n  pwrfl.SetLength(phim);\n\n  for (long i=0; i<Hwt; ) {  // continue until exactly Hwt nonzero coefficients\n    long u = RandomBnd(phim);  // The next coefficient to choose\n    if (pwrfl[u]==0) { // if we didn't choose it already\n      long b = RandomBits_long(2)&2; // b random in {0,2}\n      pwrfl[u] = b-1;                      //   random in {-1,1}\n      i++; // count another nonzero coefficient\n    }\n  }\n\n  ZZX poly1;\n  p2dConv->powerfulToZZX(poly1, pwrfl);\n\n  convert(poly, poly1);\n}\n\n// Experimental version\n\ndouble sampleHWtBounded(zzX &poly, const FHEcontext& context, long Hwt)\n{\n#if FFT_IMPL // is there any implementation of canonicalEmbedding?\n  double bound = sampleHWtBoundedEffectiveBound(context, Hwt);\n  const PAlgebra& palg = context.zMStar;\n    \n  double val;\n  long count = 0;\n  do {\n    sampleHWtAlt(poly, context, Hwt);\n    val = embeddingLargestCoeff(poly,palg);\n    //cerr << \"****** \" << (val/bound) << \"\\n\";\n  }\n  while (++count<1000 && val>bound); // repeat until <= bound\n\n  if (val>bound) {\n    std::stringstream ss;\n    ss << \"Error: sampleSmallBounded, after \"\n         << count<<\" trials, still val=\"<<val\n         << '>'<<\"bound=\"<<bound;\n    throw helib::RuntimeError(ss.str());\n  }\n  return bound;\n#else\n  return sampleHWt(poly, context, Hwt);\n#endif\n   \n}\n\n\n#endif\n\n\ndouble sampleSmall(zzX &poly, const FHEcontext& context)\n{\n  const PAlgebra& palg = context.zMStar;\n  double retval;\n\n  if (palg.getPow2() == 0) { // not power of two\n    long m = palg.getM();\n    long phim = palg.getPhiM();\n    sampleSmall(poly, m, phim/(2.0*m)); // nonzero with prob phi(m)/2m\n    // FIXME: does this probability make sense?  What is the goal there??\n    reduceModPhimX(poly, palg);\n    retval = context.noiseBoundForSmall(phim/(2.0*m), m);\n  }\n  else { // power of two\n    long phim = palg.getPhiM();\n    sampleSmall(poly, phim);\n    retval = context.noiseBoundForSmall(0.5, phim);\n  }\n\n  return retval;\n}\n\n\n\n// Same as above, but ensure the result is not too much larger than typical\ndouble sampleSmallBounded(zzX &poly, const FHEcontext& context)\n{\n#if FFT_IMPL // is there any implementation of canonicalEmbedding?\n  const PAlgebra& palg = context.zMStar;\n  long m = palg.getM();\n  long phim = palg.getPhiM();\n  // experimental bound, Pr[l-infty(canonical-embedding)>bound]<5%\n  double bound = (1+sqrt(phim*log(phim)))*0.85;\n  double val;\n  long count = 0;\n  do {\n    sampleSmall(poly, context);\n    val = embeddingLargestCoeff(poly,palg);\n  }\n  while (++count<1000 && val>bound); // repeat until <= bound\n  if (val>bound) {\n    std::stringstream ss;\n    ss << \"Error: sampleSmallBounded, after \"\n         << count<<\" trials, still val=\"<<val\n         << '>'<<\"bound=\"<<bound;\n    throw helib::RuntimeError(ss.str());\n  }\n  return bound;\n#else\n#warning \"No FFT, sampleSmallBounded degenerates to sampleSmall\"\n  return sampleSmall(poly, context);\n#endif\n}\n\ndouble sampleGaussian(zzX &poly, const FHEcontext& context, double stdev)\n{\n  const PAlgebra& palg = context.zMStar;\n  double retval;\n\n  if (palg.getPow2() == 0) { // not power of two\n    long m = palg.getM();\n    sampleGaussian(poly, m, stdev);\n    reduceModPhimX(poly, palg);\n    retval = context.noiseBoundForGaussian(stdev, m);\n  }\n  else { // power of two\n    long phim = palg.getPhiM();\n    sampleGaussian(poly, phim, stdev);\n    retval = context.noiseBoundForGaussian(stdev, phim);\n  }\n\n  return retval;\n}\n// Same as above, but ensure the result is not too much larger than typical\ndouble sampleGaussianBounded(zzX &poly, const FHEcontext& context, double stdev)\n{\n#if FFT_IMPL // is there any implementation of canonicalEmbedding?\n  const PAlgebra& palg = context.zMStar;\n  long m = palg.getM();\n  long phim = palg.getPhiM();  \n  // experimental bound, Pr[l-infty(canonical-embedding)>bound]<5%\n  double bound\n    = stdev*1.15*(2+((palg.getPow2()==0)?\n                     sqrt(m*log(phim)) : sqrt(phim*log(phim))));\n  double val;\n  long count = 0;\n  do {\n    sampleGaussian(poly, context, stdev);\n    val = embeddingLargestCoeff(poly,palg);\n  }\n  while (++count<1000 && val>bound); // repeat until <=bound\n  if (val>bound) {\n    std::stringstream ss;\n    ss << \"Error: sampleGaussianBounded, after \"\n         << count<<\" trials, still val=\"<<val\n         << '>'<<\"bound=\"<<bound;\n    throw helib::RuntimeError(ss.str());\n  }\n  return bound;\n#else\n#warning \"No FFT, sampleGaussianBounded degenerates to sampleGaussian\"\n  return sampleGaussian(poly, context, stdev);\n#endif\n}\n\n\n\ndouble sampleUniform(zzX &poly, const FHEcontext& context, long B)\n{\n  const PAlgebra& palg = context.zMStar;\n  double retval;\n\n  if (palg.getPow2() == 0) { // not power of two\n    long m = palg.getM();\n    sampleUniform(poly, m, B);\n    reduceModPhimX(poly, palg);\n    retval = context.noiseBoundForUniform(B, m);\n  }\n  else { // power of two\n    long phim = palg.getPhiM();\n    sampleUniform(poly, phim, B);\n    retval = context.noiseBoundForUniform(B, phim);\n  }\n\n  return retval;\n}\n\nxdouble sampleUniform(ZZX &poly, const FHEcontext& context, const ZZ& B)\n{\n  const PAlgebra& palg = context.zMStar;\n  xdouble retval;\n\n  if (palg.getPow2() == 0) { // not power of two\n    long m = palg.getM();\n    sampleUniform(poly, m, B);\n    NTL::rem(poly, poly, palg.getPhimX());\n    retval = context.noiseBoundForUniform(conv<xdouble>(B), m);\n  }\n  else {// power of two\n    long phim = palg.getPhiM();\n    sampleUniform(poly, phim, B);\n    retval = context.noiseBoundForUniform(conv<xdouble>(B), phim);\n  }\n\n  return retval;\n}\n\n\n// Helper functions, return a bound B such that for random noise\n// terms we have Pr[|canonicalEmbed(noise)|_{\\infty} > B] < epsilon.\n// (The default is epsilon = 2^{-40}.)\ndouble boundFreshNoise(long m, long phim, double sigma, double epsilon)\n{\n  // The various constants in this function were determined experimentally.\n\n  /* We begin by computing the standard deviation of the magnitude of\n   * f(zeta), where f = sampleSmallBounded * sampleGaussian(sigma)\n   *                 +  sampleSmall * sampleGaussianBounded(sigma)\n   *                 + sampleGaussian(sigma)\n   * and zeta is an m'th root-of-unity, which we approximate as:\n   */\n  double stdev = (sigma+0.1)*0.54*(1+(is2power(m)? sqrt(phim*m): phim));\n\n  /* Then we use the following rules:\n   *      Pr[|f(zeta)| > stdev] = 0.644\n   *      Pr[|f(zeta)| > 2*stdev] = 0.266\n   *      Pr[|f(zeta)| > 3*stdev] = 9.04e-2\n   *      Pr[|f(zeta)| > 4*stdev] = 2.76e-2\n   *      Pr[|f(zeta)| > 5*stdev] = 7.89e-3\n   *      Pr[|f(zeta)| > 6*stdev] = 2.16e-3\n   *      Pr[|f(zeta)| > n*stdev] = 2.16e-3 * 4^{6-n} for n>6\n   *\n   * We return the smallest number of standard deviations n satifying\n   *      Pr[|f(zeta)|>(n stdev)] = epsilon / phi(m)\n   */\n  epsilon /= phim;\n\n  if (epsilon >= 1.87e-3) { // use the values from above\n    if (epsilon >= 0.64)        { return stdev; }\n    else if (epsilon >= 0.26)   { return 2*stdev; }\n    else if (epsilon >= 8.52e-2) { return 3*stdev; }\n    else if (epsilon >= 2.54e-2) { return 4*stdev; }\n    else if (epsilon >= 7.06e-3) { return 5*stdev; }\n    else                         { return 6*stdev; }\n  }\n  long num = 7;\n  for (double prob=(1.87e-3)/4; prob>epsilon; prob /= 4)\n    num++;\n\n  return stdev * num;\n}\ndouble boundRoundingNoise(long m, long phim, long p2r, double epsilon)\n{\n  // The various constants in this function were determined experimentally.\n\n  /* We begin by computing the standard deviation of the magnitude of\n   * f(zeta), where\n   *          f= sampleSmallBounded*sampleUniform(p) +sampleUniform(p),\n   * and zeta is an m'th root-of-unity, which we approximate as:\n   */\n  double stdev = (2*p2r+1)*(phim-2)/8.0;\n\n  /* Then we use the following rules:\n   *      Pr[|f(zeta)| > stdev] = 0.514\n   *      Pr[|f(zeta)| > 2*stdev] = 0.194\n   *      Pr[|f(zeta)| > 3*stdev] = 6.7e-2\n   *      Pr[|f(zeta)| > 4*stdev] = 2.23e-2\n   *      Pr[|f(zeta)| > 5*stdev] = 7.21e-3\n   *      Pr[|f(zeta)| > 6*stdev] = 2.31e-3\n   *      Pr[|f(zeta)| > 7*stdev] = 7.25e-4\n   *      Pr[|f(zeta)| > n*stdev] = 7.25e-4 * 3.3^{7-n} for n>5\n   *\n   * We return the smallest number of standard deviations n satifying\n   *      Pr[|f(zeta)|>(n stdev)] = epsilon / phi(m)\n   */\n  epsilon /= phim;\n\n  if (epsilon >= 7.25e-4) { // use the values from above\n    if (epsilon >= 0.514)        { return stdev; }\n    else if (epsilon >= 0.194)   { return 2*stdev; }\n    else if (epsilon >= 6.7e-2)  { return 3*stdev; }\n    else if (epsilon >= 2.23e-2) { return 4*stdev; }\n    else if (epsilon >= 7.21e-3) { return 5*stdev; }\n    else if (epsilon >= 2.31e-3) { return 6*stdev; }\n    else                         { return 7*stdev; }\n  }\n  long num = 8;\n  for (double prob=(7.25e-4)/3.2; prob>epsilon; prob /= 3.2)\n    num++;\n\n  return stdev * num;\n}\n", "meta": {"hexsha": "2946ef01e9535fc38ebea8ccaafdb26f964a9dfb", "size": 21393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sample.cpp", "max_stars_repo_name": "leekt216/HElib", "max_stars_repo_head_hexsha": "d2700ba62d2399213b5293686e715d01ad65e6c0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-22T01:55:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-22T01:55:27.000Z", "max_issues_repo_path": "src/sample.cpp", "max_issues_repo_name": "leekt216/HElib", "max_issues_repo_head_hexsha": "d2700ba62d2399213b5293686e715d01ad65e6c0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-05-16T09:26:15.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-16T09:26:15.000Z", "max_forks_repo_path": "src/sample.cpp", "max_forks_repo_name": "leekt216/HElib", "max_forks_repo_head_hexsha": "d2700ba62d2399213b5293686e715d01ad65e6c0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-02-01T11:34:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-27T14:49:27.000Z", "avg_line_length": 30.3016997167, "max_line_length": 104, "alphanum_fraction": 0.6287570701, "num_tokens": 6745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.66192288918838, "lm_q1q2_score": 0.40958493247696826}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file   GaussianConditional.cpp\n * @brief  Conditional Gaussian Base class\n * @author Christian Potthast, Frank Dellaert\n */\n\n#include <gtsam/linear/linearExceptions.h>\n#include <gtsam/linear/GaussianConditional.h>\n#include <gtsam/linear/VectorValues.h>\n#include <gtsam/linear/Sampler.h>\n\n#include <boost/format.hpp>\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-variable\"\n#endif\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n\n#include <functional>\n#include <list>\n#include <string>\n\n// In Wrappers we have no access to this so have a default ready\nstatic std::mt19937_64 kRandomNumberGenerator(42);\n\nusing namespace std;\n\nnamespace gtsam {\n\n  /* ************************************************************************* */\n  GaussianConditional::GaussianConditional(\n    Key key, const Vector& d, const Matrix& R, const SharedDiagonal& sigmas) :\n  BaseFactor(key, R, d, sigmas), BaseConditional(1) {}\n\n  /* ************************************************************************ */\n  GaussianConditional::GaussianConditional(Key key, const Vector& d,\n                                           const Matrix& R, Key parent1,\n                                           const Matrix& S,\n                                           const SharedDiagonal& sigmas)\n      : BaseFactor(key, R, parent1, S, d, sigmas), BaseConditional(1) {}\n\n  /* ************************************************************************ */\n  GaussianConditional::GaussianConditional(Key key, const Vector& d,\n                                           const Matrix& R, Key parent1,\n                                           const Matrix& S, Key parent2,\n                                           const Matrix& T,\n                                           const SharedDiagonal& sigmas)\n      : BaseFactor(key, R, parent1, S, parent2, T, d, sigmas),\n        BaseConditional(1) {}\n\n  /* ************************************************************************ */\n  GaussianConditional GaussianConditional::FromMeanAndStddev(\n      Key key, const Matrix& A, Key parent, const Vector& b, double sigma) {\n    // |Rx + Sy - d| = |x-(Ay + b)|/sigma\n    const Matrix R = Matrix::Identity(b.size(), b.size());\n    const Matrix S = -A;\n    const Vector d = b;\n    return GaussianConditional(key, d, R, parent, S,\n                               noiseModel::Isotropic::Sigma(b.size(), sigma));\n  }\n\n  /* ************************************************************************ */\n  GaussianConditional GaussianConditional::FromMeanAndStddev(\n      Key key, const Matrix& A1, Key parent1, const Matrix& A2, Key parent2,\n      const Vector& b, double sigma) {\n    // |Rx + Sy + Tz - d| = |x-(A1 y + A2 z + b)|/sigma\n    const Matrix R = Matrix::Identity(b.size(), b.size());\n    const Matrix S = -A1;\n    const Matrix T = -A2;\n    const Vector d = b;\n    return GaussianConditional(key, d, R, parent1, S, parent2, T,\n                               noiseModel::Isotropic::Sigma(b.size(), sigma));\n  }\n\n  /* ************************************************************************ */\n  void GaussianConditional::print(const string &s, const KeyFormatter& formatter) const {\n    cout << s << \" p(\";\n    for (const_iterator it = beginFrontals(); it != endFrontals(); ++it) {\n      cout << (boost::format(\"%1%\") % (formatter(*it))).str()\n           << (nrFrontals() > 1 ? \" \" : \"\");\n    }\n\n    if (nrParents()) {\n      cout << \" |\";\n      for (const_iterator it = beginParents(); it != endParents(); ++it) {\n        cout << \" \" << (boost::format(\"%1%\") % (formatter(*it))).str();\n      }\n    }\n    cout << \")\" << endl;\n\n    cout << formatMatrixIndented(\"  R = \", R()) << endl;\n    for (const_iterator it = beginParents() ; it != endParents() ; ++it) {\n      cout << formatMatrixIndented((boost::format(\"  S[%1%] = \")%(formatter(*it))).str(), getA(it))\n        << endl;\n    }\n    cout << formatMatrixIndented(\"  d = \", getb(), true) << \"\\n\";\n    if (model_)\n      model_->print(\"  Noise model: \");\n    else\n      cout << \"  No noise model\" << endl;\n  }\n\n  /* ************************************************************************* */\n  bool GaussianConditional::equals(const GaussianFactor& f, double tol) const {\n    if (const GaussianConditional* c = dynamic_cast<const GaussianConditional*>(&f)) {\n      // check if the size of the parents_ map is the same\n      if (parents().size() != c->parents().size())\n        return false;\n\n      // check if R_ and d_ are linear independent\n      for (DenseIndex i = 0; i < Ab_.rows(); i++) {\n        list<Vector> rows1, rows2;\n        rows1.push_back(Vector(R().row(i)));\n        rows2.push_back(Vector(c->R().row(i)));\n\n        // check if the matrices are the same\n        // iterate over the parents_ map\n        for (const_iterator it = beginParents(); it != endParents(); ++it) {\n          const_iterator it2 = c->beginParents() + (it - beginParents());\n          if (*it != *(it2))\n            return false;\n          rows1.push_back(row(getA(it), i));\n          rows2.push_back(row(c->getA(it2), i));\n        }\n\n        Vector row1 = concatVectors(rows1);\n        Vector row2 = concatVectors(rows2);\n        if (!linear_dependent(row1, row2, tol))\n          return false;\n      }\n\n      // check if sigmas are equal\n      if ((model_ && !c->model_) || (!model_ && c->model_)\n        || (model_ && c->model_ && !model_->equals(*c->model_, tol)))\n        return false;\n\n      return true;\n    } else {\n      return false;\n    }\n  }\n\n  /* ************************************************************************* */\n  VectorValues GaussianConditional::solve(const VectorValues& x) const {\n    // Concatenate all vector values that correspond to parent variables\n    const Vector xS = x.vector(KeyVector(beginParents(), endParents()));\n\n    // Update right-hand-side\n    const Vector rhs = d() - S() * xS;\n\n    // Solve matrix\n    const Vector solution = R().triangularView<Eigen::Upper>().solve(rhs);\n\n    // Check for indeterminant solution\n    if (solution.hasNaN()) {\n      throw IndeterminantLinearSystemException(keys().front());\n    }\n\n    // Insert solution into a VectorValues\n    VectorValues result;\n    DenseIndex vectorPosition = 0;\n    for (const_iterator frontal = beginFrontals(); frontal != endFrontals(); ++frontal) {\n      result.emplace(*frontal, solution.segment(vectorPosition, getDim(frontal)));\n      vectorPosition += getDim(frontal);\n    }\n\n    return result;\n  }\n\n  /* ************************************************************************* */\n  VectorValues GaussianConditional::solveOtherRHS(\n    const VectorValues& parents, const VectorValues& rhs) const {\n    // Concatenate all vector values that correspond to parent variables\n    Vector xS = parents.vector(KeyVector(beginParents(), endParents()));\n\n    // Instead of updating getb(), update the right-hand-side from the given rhs\n    const Vector rhsR = rhs.vector(KeyVector(beginFrontals(), endFrontals()));\n    xS = rhsR - S() * xS;\n\n    // Solve Matrix\n    Vector soln = R().triangularView<Eigen::Upper>().solve(xS);\n\n    // Scale by sigmas\n    if (model_)\n      soln.array() *= model_->sigmas().array();\n\n    // Insert solution into a VectorValues\n    VectorValues result;\n    DenseIndex vectorPosition = 0;\n    for (const_iterator frontal = beginFrontals(); frontal != endFrontals(); ++frontal) {\n      result.emplace(*frontal, soln.segment(vectorPosition, getDim(frontal)));\n      vectorPosition += getDim(frontal);\n    }\n\n    return result;\n  }\n\n  /* ************************************************************************* */\n  void GaussianConditional::solveTransposeInPlace(VectorValues& gy) const {\n    Vector frontalVec = gy.vector(KeyVector(beginFrontals(), endFrontals()));\n    frontalVec = R().transpose().triangularView<Eigen::Lower>().solve(frontalVec);\n\n    // Check for indeterminant solution\n    if (frontalVec.hasNaN()) throw IndeterminantLinearSystemException(this->keys().front());\n\n    for (const_iterator it = beginParents(); it!= endParents(); it++)\n      gy[*it].noalias() += -1.0 * getA(it).transpose() * frontalVec;\n\n    // Scale by sigmas\n    if (model_)\n      frontalVec.array() *= model_->sigmas().array();\n\n    // Write frontal solution into a VectorValues\n    DenseIndex vectorPosition = 0;\n    for (const_iterator frontal = beginFrontals(); frontal != endFrontals(); ++frontal) {\n      gy[*frontal] = frontalVec.segment(vectorPosition, getDim(frontal));\n      vectorPosition += getDim(frontal);\n    }\n  }\n\n  /* ************************************************************************ */\n  JacobianFactor::shared_ptr GaussianConditional::likelihood(\n      const VectorValues& frontalValues) const {\n    // Error is |Rx - (d - Sy - Tz - ...)|^2\n    // so when we instantiate x (which has to be completely known) we beget:\n    // |Sy + Tz + ... - (d - Rx)|^2\n    // The noise model just transfers over!\n\n    // Get frontalValues as vector\n    const Vector x =\n        frontalValues.vector(KeyVector(beginFrontals(), endFrontals()));\n\n    // Copy the augmented Jacobian matrix:\n    auto newAb = Ab_;\n\n    // Restrict view to parent blocks\n    newAb.firstBlock() += nrFrontals_;\n\n    // Update right-hand-side (last column)\n    auto last = newAb.matrix().cols() - 1;\n    const auto RR = R().triangularView<Eigen::Upper>();\n    newAb.matrix().col(last) -= RR * x;\n\n    // The keys now do not include the frontal keys:\n    KeyVector newKeys;\n    newKeys.reserve(nrParents());\n    for (auto&& key : parents()) newKeys.push_back(key);\n\n    // Hopefully second newAb copy below is optimized out...\n    return boost::make_shared<JacobianFactor>(newKeys, newAb, model_);\n  }\n\n  /* **************************************************************************/\n  JacobianFactor::shared_ptr GaussianConditional::likelihood(\n      const Vector& frontal) const {\n    if (nrFrontals() != 1)\n      throw std::invalid_argument(\n          \"GaussianConditional Single value likelihood can only be invoked on \"\n          \"single-variable conditional\");\n    VectorValues values;\n    values.insert(keys_[0], frontal);\n    return likelihood(values);\n  }\n\n  /* ************************************************************************ */\n  VectorValues GaussianConditional::sample(const VectorValues& parentsValues,\n                                           std::mt19937_64* rng) const {\n    if (nrFrontals() != 1) {\n      throw std::invalid_argument(\n          \"GaussianConditional::sample can only be called on single variable \"\n          \"conditionals\");\n    }\n    if (!model_) {\n      throw std::invalid_argument(\n          \"GaussianConditional::sample can only be called if a diagonal noise \"\n          \"model was specified at construction.\");\n    }\n    VectorValues solution = solve(parentsValues);\n    Key key = firstFrontalKey();\n    const Vector& sigmas = model_->sigmas();\n    solution[key] += Sampler::sampleDiagonal(sigmas, rng);\n    return solution;\n  }\n\n  VectorValues GaussianConditional::sample(std::mt19937_64* rng) const {\n    if (nrParents() != 0)\n      throw std::invalid_argument(\n          \"sample() can only be invoked on no-parent prior\");\n    VectorValues values;\n    return sample(values);\n  }\n\n  /* ************************************************************************ */\n  VectorValues GaussianConditional::sample() const {\n    return sample(&kRandomNumberGenerator);\n  }\n\n  VectorValues GaussianConditional::sample(const VectorValues& given) const {\n    return sample(given, &kRandomNumberGenerator);\n  }\n\n  /* ************************************************************************ */\n#ifdef GTSAM_ALLOW_DEPRECATED_SINCE_V42\n  void GTSAM_DEPRECATED\n  GaussianConditional::scaleFrontalsBySigma(VectorValues& gy) const {\n    DenseIndex vectorPosition = 0;\n    for (const_iterator frontal = beginFrontals(); frontal != endFrontals(); ++frontal) {\n      gy[*frontal].array() *= model_->sigmas().segment(vectorPosition, getDim(frontal)).array();\n      vectorPosition += getDim(frontal);\n    }\n  }\n#endif\n\n}  // namespace gtsam\n", "meta": {"hexsha": "6199f91a75dea3f4acca87982ae4f3625bb446a1", "size": 12470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/GaussianConditional.cpp", "max_stars_repo_name": "magicbycalvin/gtsam", "max_stars_repo_head_hexsha": "df7fb47d55c850cb52542ed38dd5089a3154bebd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gtsam/linear/GaussianConditional.cpp", "max_issues_repo_name": "magicbycalvin/gtsam", "max_issues_repo_head_hexsha": "df7fb47d55c850cb52542ed38dd5089a3154bebd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/linear/GaussianConditional.cpp", "max_forks_repo_name": "magicbycalvin/gtsam", "max_forks_repo_head_hexsha": "df7fb47d55c850cb52542ed38dd5089a3154bebd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7878787879, "max_line_length": 99, "alphanum_fraction": 0.5601443464, "num_tokens": 2778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.409584924223436}}
{"text": "/*    Copyright (c) 2010-2016, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n\n#include <boost/make_shared.hpp>\n#include <boost/bind.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include \"Tudat/Astrodynamics/Aerodynamics/flightConditions.h\"\n#include \"Tudat/Astrodynamics/Ephemerides/frameManager.h\"\n#include \"Tudat/Astrodynamics/Gravitation/sphericalHarmonicsGravityField.h\"\n#include \"Tudat/Astrodynamics/ReferenceFrames/aerodynamicAngleCalculator.h\"\n#include \"Tudat/Astrodynamics/ReferenceFrames/referenceFrameTransformations.h\"\n#include \"Tudat/SimulationSetup/accelerationSettings.h\"\n#include \"Tudat/SimulationSetup/createAccelerationModels.h\"\n#include \"Tudat/SimulationSetup/createFlightConditions.h\"\n\nnamespace tudat\n{\n\nnamespace simulation_setup\n{\n\nusing namespace aerodynamics;\nusing namespace gravitation;\nusing namespace basic_astrodynamics;\nusing namespace electro_magnetism;\nusing namespace ephemerides;\n\n//! Function to add to double-returning functions.\ndouble evaluateDoubleFunctions(\n        const boost::function< double( ) >& function1,\n        const boost::function< double( ) >& function2 )\n{\n    return function1( ) + function2( );\n}\n\n\n//! Function to create central gravity acceleration model.\nboost::shared_ptr< CentralGravitationalAccelerationModel3d > createCentralGravityAcceleratioModel(\n        const boost::shared_ptr< Body > bodyUndergoingAcceleration,\n        const boost::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const bool useCentralBodyFixedFrame )\n{\n    // Declare pointer to return object.\n    boost::shared_ptr< CentralGravitationalAccelerationModel3d > accelerationModelPointer;\n\n    // Check if body is endowed with a gravity field model (i.e. is capable of exerting\n    // gravitation acceleration).\n    if( bodyExertingAcceleration->getGravityFieldModel( ) == NULL )\n    {\n        throw std::runtime_error(\n                    std::string( \"Error, gravity field model not set when making central \") +\n                    \" gravitational acceleration of \" + nameOfBodyExertingAcceleration + \" on \" +\n                    nameOfBodyUndergoingAcceleration );\n    }\n    else\n    {\n        boost::function< double( ) > gravitationalParameterFunction;\n\n        // Set correct value for gravitational parameter.\n        if( useCentralBodyFixedFrame == 0  ||\n                bodyUndergoingAcceleration->getGravityFieldModel( ) == NULL )\n        {\n            gravitationalParameterFunction =\n                    boost::bind( &gravitation::GravityFieldModel::getGravitationalParameter,\n                                 bodyExertingAcceleration->getGravityFieldModel( ) );\n        }\n        else\n        {\n            boost::function< double( ) > gravitationalParameterOfBodyExertingAcceleration =\n                    boost::bind( &gravitation::GravityFieldModel::getGravitationalParameter,\n                                 bodyExertingAcceleration->getGravityFieldModel( ) );\n            boost::function< double( ) > gravitationalParameterOfBodyUndergoingAcceleration =\n                    boost::bind( &gravitation::GravityFieldModel::getGravitationalParameter,\n                                 bodyUndergoingAcceleration->getGravityFieldModel( ) );\n            gravitationalParameterFunction =\n                    boost::bind( &evaluateDoubleFunctions,\n                                 gravitationalParameterOfBodyExertingAcceleration,\n                                 gravitationalParameterOfBodyUndergoingAcceleration );\n        }\n\n        // Create acceleration object.\n        accelerationModelPointer =\n                boost::make_shared< CentralGravitationalAccelerationModel3d >(\n                    boost::bind( &Body::getPosition, bodyUndergoingAcceleration ),\n                    gravitationalParameterFunction,\n                    boost::bind( &Body::getPosition, bodyExertingAcceleration ),\n                    useCentralBodyFixedFrame );\n    }\n\n\n    return accelerationModelPointer;\n}\n\n//! Function to create spherical harmonic gravity acceleration model.\nboost::shared_ptr< gravitation::SphericalHarmonicsGravitationalAccelerationModelXd >\ncreateSphericalHarmonicsGravityAcceleration(\n        const boost::shared_ptr< Body > bodyUndergoingAcceleration,\n        const boost::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const boost::shared_ptr< AccelerationSettings > accelerationSettings,\n        const bool useCentralBodyFixedFrame )\n{\n    // Declare pointer to return object\n    boost::shared_ptr< SphericalHarmonicsGravitationalAccelerationModelXd > accelerationModel;\n\n    // Dynamic cast acceleration settings to required type and check consistency.\n    boost::shared_ptr< SphericalHarmonicAccelerationSettings > sphericalHarmonicsSettings =\n            boost::dynamic_pointer_cast< SphericalHarmonicAccelerationSettings >(\n                accelerationSettings );\n    if( sphericalHarmonicsSettings == NULL )\n    {\n        throw std::runtime_error(\n                    std::string( \"Error, acceleration settings inconsistent \") +\n                    \" making sh gravitational acceleration of \" + nameOfBodyExertingAcceleration +\n                    \" on \" + nameOfBodyUndergoingAcceleration );\n    }\n    else\n    {\n        // Get pointer to gravity field of central body and cast to required type.\n        boost::shared_ptr< SphericalHarmonicsGravityField > sphericalHarmonicsGravityField =\n                boost::dynamic_pointer_cast< SphericalHarmonicsGravityField >(\n                    bodyExertingAcceleration->getGravityFieldModel( ) );\n\n        boost::shared_ptr< RotationalEphemeris> rotationalEphemeris =\n                bodyExertingAcceleration->getRotationalEphemeris( );\n        if( sphericalHarmonicsGravityField == NULL )\n        {\n            throw std::runtime_error(\n                        std::string( \"Error, spherical harmonic gravity field model not set when \")\n                        + \" making sh gravitational acceleration of \" +\n                        nameOfBodyExertingAcceleration +\n                        \" on \" + nameOfBodyUndergoingAcceleration );\n        }\n        else\n        {\n            if( rotationalEphemeris == NULL )\n            {\n                throw std::runtime_error( \"Warning when making spherical harmonic acceleration on body \" +\n                                          nameOfBodyUndergoingAcceleration + \", no rotation model found for \" +\n                                          nameOfBodyExertingAcceleration );\n            }\n\n            if( rotationalEphemeris->getTargetFrameOrientation( ) !=\n                    sphericalHarmonicsGravityField->getFixedReferenceFrame( ) )\n            {\n                throw std::runtime_error( \"Warning when making spherical harmonic acceleration on body \" +\n                                          nameOfBodyUndergoingAcceleration + \", rotation model found for \" +\n                                          nameOfBodyExertingAcceleration + \" is incompatible, frames are: \" +\n                                          rotationalEphemeris->getTargetFrameOrientation( ) + \" and \" +\n                                          sphericalHarmonicsGravityField->getFixedReferenceFrame( ) );\n            }\n\n            boost::function< double( ) > gravitationalParameterFunction;\n\n            // Check if mutual acceleration is to be used.\n            if( useCentralBodyFixedFrame == false ||\n                    bodyUndergoingAcceleration->getGravityFieldModel( ) == NULL )\n            {\n                gravitationalParameterFunction =\n                        boost::bind( &SphericalHarmonicsGravityField::getGravitationalParameter,\n                                     sphericalHarmonicsGravityField );\n            }\n            else\n            {\n                // Create function returning summed gravitational parameter of the two bodies.\n                boost::function< double( ) > gravitationalParameterOfBodyExertingAcceleration =\n                        boost::bind( &gravitation::GravityFieldModel::getGravitationalParameter,\n                                     sphericalHarmonicsGravityField );\n                boost::function< double( ) > gravitationalParameterOfBodyUndergoingAcceleration =\n                        boost::bind( &gravitation::GravityFieldModel::getGravitationalParameter,\n                                     bodyUndergoingAcceleration->getGravityFieldModel( ) );\n                gravitationalParameterFunction =\n                        boost::bind( &evaluateDoubleFunctions,\n                                     gravitationalParameterOfBodyExertingAcceleration,\n                                     gravitationalParameterOfBodyUndergoingAcceleration );\n            }\n\n            // Create acceleration object.\n            accelerationModel =\n                    boost::make_shared< SphericalHarmonicsGravitationalAccelerationModelXd >\n                    ( boost::bind( &Body::getPosition, bodyUndergoingAcceleration ),\n                      gravitationalParameterFunction,\n                      sphericalHarmonicsGravityField->getReferenceRadius( ),\n                      boost::bind( &SphericalHarmonicsGravityField::getCosineCoefficients,\n                                   sphericalHarmonicsGravityField,\n                                   sphericalHarmonicsSettings->maximumDegree_,\n                                   sphericalHarmonicsSettings->maximumOrder_ ),\n                      boost::bind( &SphericalHarmonicsGravityField::getSineCoefficients,\n                                   sphericalHarmonicsGravityField,\n                                   sphericalHarmonicsSettings->maximumDegree_,\n                                   sphericalHarmonicsSettings->maximumOrder_ ),\n                      boost::bind( &Body::getPosition, bodyExertingAcceleration ),\n                      boost::bind( &Body::getCurrentRotationToGlobalFrame,\n                                   bodyExertingAcceleration ), useCentralBodyFixedFrame );\n        }\n    }\n    return accelerationModel;\n}\n\n\n//! Function to create a third body central gravity acceleration model.\nboost::shared_ptr< gravitation::ThirdBodyCentralGravityAcceleration >\ncreateThirdBodyCentralGravityAccelerationModel(\n        const boost::shared_ptr< Body > bodyUndergoingAcceleration,\n        const boost::shared_ptr< Body > bodyExertingAcceleration,\n        const boost::shared_ptr< Body > centralBody,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const std::string& nameOfCentralBody )\n{\n    // Declare pointer to return object.\n    boost::shared_ptr< ThirdBodyCentralGravityAcceleration > accelerationModelPointer;\n\n    // Create acceleration object.\n    accelerationModelPointer =  boost::make_shared< ThirdBodyCentralGravityAcceleration >(\n                boost::dynamic_pointer_cast< CentralGravitationalAccelerationModel3d >(\n                    createCentralGravityAcceleratioModel( bodyUndergoingAcceleration,\n                                                          bodyExertingAcceleration,\n                                                          nameOfBodyUndergoingAcceleration,\n                                                          nameOfBodyExertingAcceleration, 0 ) ),\n                boost::dynamic_pointer_cast< CentralGravitationalAccelerationModel3d >(\n                    createCentralGravityAcceleratioModel( centralBody, bodyExertingAcceleration,\n                                                          nameOfCentralBody,\n                                                          nameOfBodyExertingAcceleration, 0 ) ), nameOfCentralBody );\n\n    return accelerationModelPointer;\n}\n\n\n//! Function to create an aerodynamic acceleration model.\nboost::shared_ptr< aerodynamics::AerodynamicAcceleration > createAerodynamicAcceleratioModel(\n        const boost::shared_ptr< Body > bodyUndergoingAcceleration,\n        const boost::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration )\n{\n    // Check existence of required environment models\n    if( bodyUndergoingAcceleration->getAerodynamicCoefficientInterface( ) == NULL )\n    {\n        throw std::runtime_error( \"Error when making aerodynamic acceleration, body \" +\n                                  nameOfBodyUndergoingAcceleration +\n                                  \"has no aerodynamic coefficients.\" );\n    }\n\n    if( bodyExertingAcceleration->getAtmosphereModel( ) == NULL )\n    {\n        throw std::runtime_error(  \"Error when making aerodynamic acceleration, central body \" +\n                                   nameOfBodyExertingAcceleration + \" has no atmosphere model.\");\n    }\n\n    if( bodyExertingAcceleration->getShapeModel( ) == NULL )\n    {\n        throw std::runtime_error( \"Error when making aerodynamic acceleration, central body \" +\n                                  nameOfBodyExertingAcceleration + \" has no shape model.\" );\n    }\n\n    // Retrieve flight conditions; create object if not yet extant.\n    boost::shared_ptr< FlightConditions > bodyFlightConditions =\n            bodyUndergoingAcceleration->getFlightConditions( );\n    if( bodyFlightConditions == NULL )\n    {\n        bodyUndergoingAcceleration->setFlightConditions(\n                    createFlightConditions( bodyUndergoingAcceleration,\n                                            bodyExertingAcceleration,\n                                            nameOfBodyUndergoingAcceleration,\n                                            nameOfBodyExertingAcceleration ) );\n        bodyFlightConditions = bodyUndergoingAcceleration->getFlightConditions( );\n    }\n\n    // Retrieve frame in which aerodynamic coefficients are defined.\n    boost::shared_ptr< aerodynamics::AerodynamicCoefficientInterface > aerodynamicCoefficients =\n            bodyUndergoingAcceleration->getAerodynamicCoefficientInterface( );\n    reference_frames::AerodynamicsReferenceFrames accelerationFrame;\n    if( aerodynamicCoefficients->getAreCoefficientsInAerodynamicFrame( ) )\n    {\n        accelerationFrame = reference_frames::aerodynamic_frame;\n    }\n    else\n    {\n        accelerationFrame = reference_frames::body_frame;\n    }\n\n    // Create function to transform from frame of aerodynamic coefficienrs to that of propagation.\n    boost::function< Eigen::Vector3d( const Eigen::Vector3d& ) > toPropagationFrameTransformation;\n    toPropagationFrameTransformation =\n            reference_frames::getAerodynamicForceTransformationFunction(\n                bodyFlightConditions->getAerodynamicAngleCalculator( ),\n                accelerationFrame,\n                boost::bind( &Body::getCurrentRotationToGlobalFrame, bodyExertingAcceleration ),\n                reference_frames::inertial_frame );\n\n    boost::function< Eigen::Vector3d( ) > coefficientFunction =\n            boost::bind( &AerodynamicCoefficientInterface::getCurrentForceCoefficients,\n                         aerodynamicCoefficients );\n    boost::function< Eigen::Vector3d( ) > coefficientInPropagationFrameFunction =\n            boost::bind( static_cast< Eigen::Vector3d(&)(\n                             const boost::function< Eigen::Vector3d( ) >,\n                             const boost::function< Eigen::Vector3d( const Eigen::Vector3d& ) > ) >(\n                             &reference_frames::transformVector ),\n                         coefficientFunction, toPropagationFrameTransformation );\n\n    // Create acceleration model.\n    return boost::make_shared< AerodynamicAcceleration >(\n                coefficientInPropagationFrameFunction,\n                boost::bind( &FlightConditions::getCurrentDensity, bodyFlightConditions ),\n                boost::bind( &FlightConditions::getCurrentAirspeed, bodyFlightConditions ),\n                boost::bind( &Body::getBodyMass, bodyUndergoingAcceleration ),\n                boost::bind( &AerodynamicCoefficientInterface::getReferenceArea,\n                             aerodynamicCoefficients ),\n                aerodynamicCoefficients->getAreCoefficientsInNegativeAxisDirection( ) );\n}\n\n//! Function to create a cannonball radiation pressure acceleration model.\nboost::shared_ptr< CannonBallRadiationPressureAcceleration >\ncreateCannonballRadiationPressureAcceleratioModel(\n        const boost::shared_ptr< Body > bodyUndergoingAcceleration,\n        const boost::shared_ptr< Body > bodyExertingAcceleration,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration )\n{\n    // Retrieve radiation pressure interface\n    if( bodyUndergoingAcceleration->getRadiationPressureInterfaces( ).count(\n                nameOfBodyExertingAcceleration ) == 0 )\n    {\n        throw std::runtime_error(\n                    \"Error when making radiation pressure, no radiation pressure interface found  in \" +\n                    nameOfBodyUndergoingAcceleration +\n                    \" for body \" + nameOfBodyExertingAcceleration );\n    }\n    boost::shared_ptr< RadiationPressureInterface > radiationPressureInterface =\n            bodyUndergoingAcceleration->getRadiationPressureInterfaces( ).at(\n                nameOfBodyExertingAcceleration );\n\n    // Create acceleration model.\n    return boost::make_shared< CannonBallRadiationPressureAcceleration >(\n                boost::bind( &Body::getPosition, bodyExertingAcceleration ),\n                boost::bind( &Body::getPosition, bodyUndergoingAcceleration ),\n                boost::bind( &RadiationPressureInterface::getCurrentRadiationPressure, radiationPressureInterface ),\n                boost::bind( &RadiationPressureInterface::getRadiationPressureCoefficient, radiationPressureInterface ),\n                boost::bind( &RadiationPressureInterface::getArea, radiationPressureInterface ),\n                boost::bind( &Body::getBodyMass, bodyUndergoingAcceleration ) );\n\n}\n\n\n//! Function to create acceleration model object.\nboost::shared_ptr< AccelerationModel< Eigen::Vector3d > > createAccelerationModel(\n        const boost::shared_ptr< Body > bodyUndergoingAcceleration,\n        const boost::shared_ptr< Body > bodyExertingAcceleration,\n        const boost::shared_ptr< AccelerationSettings > accelerationSettings,\n        const std::string& nameOfBodyUndergoingAcceleration,\n        const std::string& nameOfBodyExertingAcceleration,\n        const boost::shared_ptr< Body > centralBody,\n        const std::string& nameOfCentralBody )\n{\n    // Declare pointer to return object.\n    boost::shared_ptr< AccelerationModel< Eigen::Vector3d > > accelerationModelPointer;\n\n    // Switch to call correct acceleration model type factory function.\n    switch( accelerationSettings->accelerationType_ )\n    {\n    case central_gravity:\n        // Check if body is a single-body central gravity acceleration (use third-body if not)\n        if( nameOfCentralBody == nameOfBodyExertingAcceleration ||\n                isFrameInertial( nameOfCentralBody ) )\n        {\n            // Check if gravitational parameter to use is sum of gravitational paramater of the\n            // two bodies.\n            bool useCentralBodyFixedFrame = 0;\n            if( nameOfCentralBody == nameOfBodyExertingAcceleration )\n            {\n                useCentralBodyFixedFrame = 1;\n            }\n\n            accelerationModelPointer = createCentralGravityAcceleratioModel(\n                        bodyUndergoingAcceleration,\n                        bodyExertingAcceleration,\n                        nameOfBodyUndergoingAcceleration,\n                        nameOfBodyExertingAcceleration, useCentralBodyFixedFrame );\n        }\n        // Create third body central gravity acceleration\n        else\n        {\n\n            accelerationModelPointer = createThirdBodyCentralGravityAccelerationModel(\n                        bodyUndergoingAcceleration,\n                        bodyExertingAcceleration,\n                        centralBody,\n                        nameOfBodyUndergoingAcceleration,\n                        nameOfBodyExertingAcceleration,\n                        nameOfCentralBody );\n        }\n        break;\n    case spherical_harmonic_gravity:\n        if( nameOfCentralBody == nameOfBodyExertingAcceleration ||\n                isFrameInertial( nameOfCentralBody ) )\n        {\n            // Check if gravitational parameter to use is sum of gravitational paramater of the\n            // two bodies.\n            bool useCentralBodyFixedFrame = 0;\n            if( nameOfCentralBody == nameOfBodyExertingAcceleration )\n            {\n                useCentralBodyFixedFrame = 1;\n            }\n\n            accelerationModelPointer = createSphericalHarmonicsGravityAcceleration(\n                        bodyUndergoingAcceleration,\n                        bodyExertingAcceleration,\n                        nameOfBodyUndergoingAcceleration,\n                        nameOfBodyExertingAcceleration,\n                        accelerationSettings, useCentralBodyFixedFrame );\n\n        }\n        else\n        {\n            throw std::runtime_error(\n                        \"Error, cannot yet make third body spherical harmonic acceleration.\" );\n\n        }\n        break;\n    case aerodynamic:\n        accelerationModelPointer = createAerodynamicAcceleratioModel(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration );\n        break;\n    case cannon_ball_radiation_pressure:\n        accelerationModelPointer = createCannonballRadiationPressureAcceleratioModel(\n                    bodyUndergoingAcceleration,\n                    bodyExertingAcceleration,\n                    nameOfBodyUndergoingAcceleration,\n                    nameOfBodyExertingAcceleration );\n        break;\n    default:\n        throw std::runtime_error(\n                    std::string( \"Error, acceleration model \") +\n                    boost::lexical_cast< std::string >( accelerationSettings->accelerationType_ ) +\n                    \" not recognized when making acceleration model of\" +\n                    nameOfBodyExertingAcceleration + \" on \" +\n                    nameOfBodyUndergoingAcceleration );\n        break;\n    }\n    return accelerationModelPointer;\n}\n\n//! Function to create a set of acceleration models from a map of bodies and acceleration model\n//! types.\nAccelerationMap createAccelerationModelsMap(\n        const NamedBodyMap& bodyMap,\n        const SelectedAccelerationMap& selectedAccelerationPerBody,\n        const std::map< std::string, std::string >& centralBodies )\n{\n    // Declare return map.\n    AccelerationMap accelerationModelMap;\n\n    // Iterate over all bodies which are undergoing acceleration\n    for( SelectedAccelerationMap::const_iterator bodyIterator =\n         selectedAccelerationPerBody.begin( ); bodyIterator != selectedAccelerationPerBody.end( );\n         bodyIterator++ )\n    {\n        boost::shared_ptr< Body > currentCentralBody;\n\n        // Retrieve name of body undergoing acceleration.\n        std::string bodyUndergoingAcceleration = bodyIterator->first;\n\n        // Retrieve name of current central body.\n        std::string currentCentralBodyName = centralBodies.at( bodyUndergoingAcceleration );\n\n        if( !isFrameInertial( currentCentralBodyName ) )\n        {\n            if( bodyMap.count( currentCentralBodyName ) == 0 )\n            {\n                throw std::runtime_error(\n                            std::string( \"Error, could not find non-inertial central body \") +\n                            currentCentralBodyName + \" of \" + bodyUndergoingAcceleration +\n                            \" when making acceleration model.\" );\n            }\n            else\n            {\n                currentCentralBody = bodyMap.at( currentCentralBodyName );\n            }\n        }\n\n        // Check if body undergoing acceleration is included in bodyMap\n        if( bodyMap.count( bodyUndergoingAcceleration ) ==  0 )\n        {\n            throw std::runtime_error(\n                        std::string( \"Error when making acceleration models, requested forces\" ) +\n                        \"acting on body \" + bodyUndergoingAcceleration  +\n                        \", but no such body found in map of bodies\" );\n        }\n\n        // Declare map of acceleration models acting on current body.\n        SingleBodyAccelerationMap mapOfAccelerationsForBody;\n\n        // Retrieve list of required acceleration model types and bodies exerting accelerationd on\n        // current body.\n        std::map< std::string, std::vector< boost::shared_ptr< AccelerationSettings > > >\n                accelerationsForBody = bodyIterator->second;\n\n        // Iterate over all bodies exerting an acceleration\n        for( std::map< std::string, std::vector< boost::shared_ptr< AccelerationSettings > > >::\n             iterator body2Iterator = accelerationsForBody.begin( );\n             body2Iterator != accelerationsForBody.end( ); body2Iterator++ )\n        {\n            // Retrieve name of body exerting acceleration.\n            std::string bodyExertingAcceleration = body2Iterator->first;\n\n            // Check if body exerting acceleration is included in bodyMap\n            if( bodyMap.count( bodyExertingAcceleration ) ==  0 )\n            {\n                throw std::runtime_error(\n                            std::string( \"Error when making acceleration models, requested forces \")\n                            + \"acting on body \" + bodyUndergoingAcceleration  + \" due to body \" +\n                            bodyExertingAcceleration +\n                            \", but no such body found in map of bodies\" );\n            }\n\n            // Retrieve list of accelerations due to current body.\n            std::vector< boost::shared_ptr< AccelerationSettings > > accelerationList =\n                    body2Iterator->second;\n\n            for( unsigned int i = 0; i < accelerationList.size( ); i++ )\n            {\n                // Create acceleration model.\n                mapOfAccelerationsForBody[ bodyExertingAcceleration ].push_back(\n                            createAccelerationModel( bodyMap.at( bodyUndergoingAcceleration ),\n                                                     bodyMap.at( bodyExertingAcceleration ),\n                                                     accelerationList.at( i ),\n                                                     bodyUndergoingAcceleration,\n                                                     bodyExertingAcceleration,\n                                                     currentCentralBody,\n                                                     currentCentralBodyName ) );\n            }\n        }\n\n        // Put acceleration models on current body in return map.\n        accelerationModelMap[ bodyUndergoingAcceleration ] = mapOfAccelerationsForBody;\n    }\n\n    return accelerationModelMap;\n}\n\n//! Function to create acceleration models from a map of bodies and acceleration model types.\nbasic_astrodynamics::AccelerationMap createAccelerationModelsMap(\n        const NamedBodyMap& bodyMap,\n        const SelectedAccelerationMap& selectedAccelerationPerBody,\n        const std::vector< std::string >& propagatedBodies,\n        const std::vector< std::string >& centralBodies )\n{\n    if( centralBodies.size( ) != propagatedBodies.size( ) )\n    {\n        throw std::runtime_error( \"Error, number of propagated bodies must equal number of central bodies\" );\n    }\n\n    std::map< std::string, std::string > centralBodyMap;\n    for( unsigned int i = 0; i < propagatedBodies.size( ); i++ )\n    {\n        centralBodyMap[ propagatedBodies.at( i ) ] = centralBodies.at( i );\n    }\n\n    return createAccelerationModelsMap( bodyMap, selectedAccelerationPerBody, centralBodyMap );\n}\n\n\n} // namespace simulation_setup\n\n} // namespace tudat\n", "meta": {"hexsha": "b706db8925ba33b17b4dbd1398201a7084bf24e1", "size": 28402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/SimulationSetup/createAccelerationModels.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/SimulationSetup/createAccelerationModels.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/SimulationSetup/createAccelerationModels.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 48.8006872852, "max_line_length": 120, "alphanum_fraction": 0.6334765157, "num_tokens": 5305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.40955455857365075}}
{"text": "#include <frovedis.hpp>\n#include <frovedis/ml/graph/graph.hpp>\n#include <boost/program_options.hpp>\n\nusing namespace boost;\nusing namespace frovedis;\nusing namespace std;\n\ntemplate <class T>\nvoid call_pagerank(const std::string& data_p,\n                   const std::string& out_p,\n                   bool if_prep,\n                   double df, \n                   double epsilon, \n                   size_t niter,\n                   double thr) { \n  graph<T> gr;\n  time_spent t(INFO);\n  if(if_prep) gr = read_edgelist<T>(data_p);\n  else {\n    auto mat = make_crs_matrix_load<T>(data_p);\n    gr = graph<T>(mat);\n  }\n  t.show(\"data loading time: \");\n  //gr.debug_print();\n  auto res = gr.pagerank(df, epsilon, niter, thr);\n  t.show(\"pagerank computation time: \");\n  make_dvector_scatter(res).saveline(out_p);\n  std::cout << \"ranks: \"; debug_print_vector(res, 5);\n}\n\nint main(int argc, char* argv[]){\n    frovedis::use_frovedis use(argc, argv);\n    using namespace boost::program_options;\n    \n    options_description opt(\"option\");\n    opt.add_options()\n        (\"help,h\", \"produce help message\")\n        (\"input,i\" , value<std::string>(), \"input data path containing either edgelist or adjacency matrix data\") \n        (\"dtype,t\" , value<std::string>(), \"input data type (int, float or double) [default: int]\") \n        (\"output,o\" , value<std::string>(), \"output data path to save ranking scores\")\n        (\"dfactor,d\", value<double>(), \"damping factor (default: 0.15)\") \n        (\"epsilon,e\", value<double>(), \"convergence threshold (default: 1E-4)\")\n        (\"threshold,l\", value<double>(), \"threshold forn shrink version (default: 0.4)\")\n        (\"max_iter,k\", value<size_t>(), \"maximum no. of iterations (default: 100)\") \n        (\"verbose\", \"set loglevel to DEBUG\")\n        (\"verbose2\", \"set loglevel to TRACE\")\n        (\"prepare,p\" , \"whether to generate the CRS matrix from original edgelist file \");\n                \n    variables_map argmap;\n    store(command_line_parser(argc,argv).options(opt).allow_unregistered().\n          run(), argmap);\n    notify(argmap);                \n                \n    bool if_prep = 0; // true if prepare data from raw dataset\n    std::string data_p, out_p, dtype = \"int\";\n    size_t niter = 100;\n    double epsilon = 1e-4; \n    double df = 0.15;\n    double thr = 0.4;\n\n    if(argmap.count(\"help\")){\n      std::cerr << opt << std::endl;\n      exit(1);\n    }\n    if(argmap.count(\"input\")){\n      data_p = argmap[\"input\"].as<std::string>();\n    } else {\n      std::cerr << \"input path is not specified\" << std::endl;\n      std::cerr << opt << std::endl;\n      exit(1);\n    }    \n    if(argmap.count(\"output\")){\n      out_p = argmap[\"output\"].as<std::string>();\n    } else {\n      std::cerr << \"output path is not specified\" << std::endl;\n      std::cerr << opt << std::endl;\n      exit(1);\n    }    \n    if(argmap.count(\"prepare\")){\n      if_prep = true;\n    }\n    if(argmap.count(\"dtype\")){\n      dtype = argmap[\"dtype\"].as<std::string>();\n    }    \n    if(argmap.count(\"dfactor\")){\n       df = argmap[\"dfactor\"].as<double>();\n    }\n    if(argmap.count(\"epsilon\")){\n       epsilon = argmap[\"epsilon\"].as<double>();\n    }\n    if(argmap.count(\"threshold\")){\n       thr = argmap[\"threshold\"].as<double>();\n    }\n    if(argmap.count(\"max_iter\")){\n       niter = argmap[\"max_iter\"].as<size_t>();\n    }\n    if(argmap.count(\"verbose\")){\n      set_loglevel(DEBUG);\n    }\n    if(argmap.count(\"verbose2\")){\n      set_loglevel(TRACE);\n    }\n\n    try {\n      if (dtype == \"int\") {\n        call_pagerank<int>(data_p, out_p, if_prep, df, epsilon, niter, thr);\n      }      \n      else if (dtype == \"float\") {\n        call_pagerank<float>(data_p, out_p, if_prep, df, epsilon, niter, thr);\n      }      \n      else if (dtype == \"double\") {\n        call_pagerank<double>(data_p, out_p, if_prep, df, epsilon, niter, thr);\n      }      \n      else {\n        std::cerr << \"Supported dtypes are only int, float and double!\\n\";\n        std::cerr << opt << std::endl;\n        exit(1);\n      }\n    }\n    catch (std::exception& e) {\n      std::cout << \"exception caught: \" << e.what() << std::endl; \n    }\n    return 0;\n}\n\n", "meta": {"hexsha": "59a5250e68afc41656e2aafcb43a20ef27bef4aa", "size": 4140, "ext": "cc", "lang": "C++", "max_stars_repo_path": "samples/graph/pagerank.cc", "max_stars_repo_name": "XpressAI/frovedis", "max_stars_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 63.0, "max_stars_repo_stars_event_min_datetime": "2018-06-21T14:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T11:24:36.000Z", "max_issues_repo_path": "samples/graph/pagerank.cc", "max_issues_repo_name": "XpressAI/frovedis", "max_issues_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-22T14:01:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-27T16:11:05.000Z", "max_forks_repo_path": "samples/graph/pagerank.cc", "max_forks_repo_name": "XpressAI/frovedis", "max_forks_repo_head_hexsha": "bda0f2c688fb832671c5b542dd8df1c9657642ff", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-08-23T15:59:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T06:47:22.000Z", "avg_line_length": 32.5984251969, "max_line_length": 114, "alphanum_fraction": 0.5640096618, "num_tokens": 1100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4094929198978481}}
{"text": "#include \"ukf.h\"\n#include <Eigen/Dense>\n#include <cmath>\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\n/**\n * Initializes Unscented Kalman filter\n */\nUKF::UKF() {\n  // if this is false, laser measurements will be ignored (except during init)\n  use_laser_ = true;\n\n  // if this is false, radar measurements will be ignored (except during init)\n  use_radar_ = true;\n\n  // initial state vector\n  x_ = VectorXd(5);\n\n  // initial covariance matrix\n  P_ = MatrixXd(5, 5);\n\n  // Process noise standard deviation longitudinal acceleration in m/s^2\n  std_a_ = 2.0;\n\n  // Process noise standard deviation yaw acceleration in rad/s^2\n  std_yawdd_ = 1.0;\n\n  /**\n   * DO NOT MODIFY measurement noise values below.\n   * These are provided by the sensor manufacturer.\n   */\n\n  // Laser measurement noise standard deviation position1 in m\n  std_laspx_ = 0.15;\n\n  // Laser measurement noise standard deviation position2 in m\n  std_laspy_ = 0.15;\n\n  // Radar measurement noise standard deviation radius in m\n  std_radr_ = 0.3;\n\n  // Radar measurement noise standard deviation angle in rad\n  std_radphi_ = 0.03;\n\n  // Radar measurement noise standard deviation radius change in m/s\n  std_radrd_ = 0.3;\n\n  /**\n   * End DO NOT MODIFY section for measurement noise values \n   */\n\n  /**\n   * TODO: Complete the initialization. See ukf.h for other member properties.\n   * Hint: one or more values initialized above might be wildly off...\n   */\n  is_initialized_ = false;\n  n_x_ = 5;\n  n_aug_ = 7;\n  lambda_ = 3 - n_x_;\n\n  weights_ = VectorXd(2 * n_aug_ + 1);\n  weights_.fill(1 / (2 * (lambda_ + n_aug_)));\n  weights_(0) = lambda_ / (lambda_ + n_aug_);\n}\n\nUKF::~UKF() {}\n\nvoid UKF::ProcessMeasurement(MeasurementPackage meas_package) {\n  /**\n   * TODO: Complete this function! Make sure you switch between lidar and radar\n   * measurements.\n   */\n  if (!is_initialized_) {\n    // set the state with the initial location and zero velocity\n    // Must determine what sensor this is first\n    if (meas_package.sensor_type_ == MeasurementPackage::SensorType::LASER) {\n      x_ << meas_package.raw_measurements_[0],\n          meas_package.raw_measurements_[1], 0, 0, 0;\n      P_ << std_laspx_ * std_laspx_, 0, 0, 0, 0,\n            0, std_laspy_ * std_laspy_, 0, 0, 0,\n            0, 0, 1, 0, 0,\n            0, 0, 0, 1, 0,\n            0, 0, 0, 0, 1;\n    } else if (meas_package.sensor_type_ ==\n               MeasurementPackage::SensorType::RADAR) {\n      const double rho = meas_package.raw_measurements_(0);\n      const double phi = meas_package.raw_measurements_(1);\n      const double rhodot = meas_package.raw_measurements_(2);\n      const double x = rho * cos(phi);\n      const double y = rho * sin(phi);\n      const double vx = rhodot * cos(phi);\n      const double vy = rhodot * sin(phi);\n      const double v = rhodot; // std::sqrt(vx * vx + vy * vy);\n      x_ << x, y, v, rho, rhodot;\n      P_ << std_radr_* std_radr_, 0, 0, 0, 0,\n            0, std_radr_ * std_radr_, 0, 0, 0,\n            0, 0, std_radrd_ * std_radrd_, 0, 0,\n            0, 0, 0, std_radphi_ * std_radphi_, 0,\n            0, 0, 0, 0, std_radphi_ * std_radphi_;\n    }\n\n    time_us_ = meas_package.timestamp_;\n    is_initialized_ = true;\n    return;\n  }\n\n  // compute the time elapsed between the current and previous measurements\n  // dt - expressed in seconds\n  const float dt = (meas_package.timestamp_ - time_us_) / 1000000.0;\n  time_us_ = meas_package.timestamp_;\n\n  // Predict the next states and covariance matrix\n  Prediction(dt);\n\n  // Update the next states and covariance matrix\n  if (meas_package.sensor_type_ == MeasurementPackage::SensorType::LASER) {\n    UpdateLidar(meas_package);\n  } else if (meas_package.sensor_type_ ==\n             MeasurementPackage::SensorType::RADAR) {\n    UpdateRadar(meas_package);\n  }\n}\n\nvoid UKF::Prediction(double delta_t) {\n  /**\n   * TODO: Complete this function! Estimate the object's location. \n   * Modify the state vector, x_. Predict sigma points, the state, \n   * and the state covariance matrix.\n   */\n\n  // Step #1 - Create augmented mean vector, augmented state covariance\n  VectorXd x_aug = VectorXd(n_aug_);\n  x_aug.setZero(n_aug_);\n  x_aug.head(5) = x_;\n\n  MatrixXd P_aug = MatrixXd(n_aug_, n_aug_);\n  P_aug.setZero(n_aug_, n_aug_);\n  P_aug.topLeftCorner(5, 5) = P_;\n  P_aug.bottomRightCorner(2, 2) << std_a_ * std_a_, 0, 0,\n      std_yawdd_ * std_yawdd_;\n\n  // Step #2 - Create square root matrix\n  MatrixXd A = P_aug.llt().matrixL();\n\n  // Step #3 - Create augmented sigma points\n  MatrixXd Xsig_aug = MatrixXd(n_aug_, 2 * n_aug_ + 1);\n  Xsig_aug.col(0) = x_aug;\n  Xsig_aug.middleCols(1, n_aug_) =\n      (std::sqrt(lambda_ + n_aug_) * A.array()).colwise() + x_aug.array();\n  Xsig_aug.middleCols(n_aug_ + 1, n_aug_) =\n      (-std::sqrt(lambda_ + n_aug_) * A.array()).colwise() + x_aug.array();\n\n  // Step #4 - Predict sigma points\n  Xsig_pred_ = MatrixXd(n_x_, 2 * n_aug_ + 1);\n  for (int i = 0; i < Xsig_aug.cols(); i++) {\n    const float px = Xsig_aug(0, i);\n    const float py = Xsig_aug(1, i);\n    const float v = Xsig_aug(2, i);\n    const float yaw = Xsig_aug(3, i);\n    const float yaw_rate = Xsig_aug(4, i);\n    const float nu_accel = Xsig_aug(5, i);\n    const float nu_yaw_accel = Xsig_aug(6, i);\n    VectorXd vec(n_x_);\n    VectorXd noise_vec(n_x_);\n    noise_vec << 0.5 * delta_t * delta_t * std::cos(yaw) * nu_accel,\n        0.5 * delta_t * delta_t * std::sin(yaw) * nu_accel, delta_t * nu_accel,\n        0.5 * delta_t * delta_t * nu_yaw_accel, delta_t * nu_yaw_accel;\n    // avoid division by zero\n    if (std::abs(yaw_rate) <= 1e-10) {\n      vec << v * std::cos(yaw) * delta_t, v * std::sin(yaw) * delta_t, 0, 0, 0;\n    } else {\n      vec << (v / yaw_rate) *\n                 (std::sin(yaw + yaw_rate * delta_t) - std::sin(yaw)),\n          (v / yaw_rate) *\n              (-std::cos(yaw + yaw_rate * delta_t) + std::cos(yaw)),\n          0, yaw_rate * delta_t, 0;\n    }\n    // write predicted sigma points into right column\n    Xsig_pred_.col(i) = Xsig_aug.col(i).head(n_x_) + vec + noise_vec;\n  }\n\n  // Step #5 - Now predict state mean and covariance\n  x_ = Xsig_pred_ * weights_;\n\n  P_ = (Xsig_pred_.array().colwise() - x_.array());\n  P_ = P_ * weights_.asDiagonal() * P_.transpose();\n}\n\nvoid UKF::UpdateLidar(MeasurementPackage meas_package) {\n  /**\n   * TODO: Complete this function! Use lidar data to update the belief \n   * about the object's position. Modify the state vector, x_, and \n   * covariance, P_.\n   * You can also calculate the lidar NIS, if desired.\n   */\n  // Note that the LiDAR noise profile is linear, so we can simply\n  // use the standard linear Kalman filter here\n  // Taken directly from the previous assignments\n\n  // New - define measurement matrix\n  MatrixXd H;\n  H.setZero(2, n_x_);\n  H(0, 0) = H(1, 1) = 1;  // Select out the position elements only\n  VectorXd z_pred = H * x_;\n  const VectorXd z = meas_package.raw_measurements_;\n\n  // Calculate residual vector y\n  const VectorXd y = z - z_pred;\n\n  // New - define measurement noise matrix\n  R_.setZero(2, 2);\n  R_ << std_laspx_ * std_laspx_, 0, 0, std_laspy_ * std_laspy_;\n\n  // Create innovation covariance matrix S\n  MatrixXd S = H * P_ * H.transpose() + R_;\n\n  // Create Kalman gain matrix K\n  MatrixXd K = P_ * H.transpose() * S.inverse();\n\n  // Create new estimate for states and covariance\n  x_ = x_ + (K * y);\n  MatrixXd I = MatrixXd::Identity(x_.size(), x_.size());\n  P_ = (I - K * H) * P_;\n\n  // Calculate NIS for LiDAR\n  NIS_lidar_ = y.transpose() * S.inverse() * y;\n}\n\nvoid UKF::UpdateRadar(MeasurementPackage meas_package) {\n  /**\n   * TODO: Complete this function! Use radar data to update the belief \n   * about the object's position. Modify the state vector, x_, and \n   * covariance, P_.\n   * You can also calculate the radar NIS, if desired.\n   */\n  // Step #1 - Create matrix for sigma points in measurement space\n  MatrixXd Zsig = MatrixXd(3, 2 * n_aug_ + 1);\n\n  // Step #2 - Transform sigma points into measurement space\n  Zsig.row(0) = ((Xsig_pred_.row(0).array() * Xsig_pred_.row(0).array()) +\n                 (Xsig_pred_.row(1).array() * Xsig_pred_.row(1).array()))\n                    .sqrt();\n  for (int i = 0; i < Zsig.cols(); i++) {\n    Zsig(1, i) = std::atan2(Xsig_pred_(1, i), Xsig_pred_(0, i));\n  }\n  Zsig.row(2) = ((Xsig_pred_.row(0).array() * Xsig_pred_.row(2).array() *\n                  Xsig_pred_.row(3).array().cos()) +\n                 (Xsig_pred_.row(1).array() * Xsig_pred_.row(2).array() *\n                  Xsig_pred_.row(3).array().sin())) /\n                Zsig.row(0).array();\n\n  // Step #3 - Create and run final update method\n  // mean predicted measurement\n  const int n_z = 3;\n  VectorXd z_pred = VectorXd(n_z);\n\n  // measurement covariance matrix S\n  MatrixXd S = MatrixXd(n_z, n_z);\n\n  // Step #4 - Calculate mean predicted measurement\n  z_pred = Zsig * weights_;\n\n  // Step #5 - Create measurement covariance matrix R and\n  // calculate innovation covariance matrix S\n  R_.setZero(n_z, n_z);\n  R_ << std_radr_ * std_radr_, 0, 0, 0, std_radphi_ * std_radphi_, 0, 0, 0,\n      std_radrd_ * std_radrd_;\n\n  S = (Zsig.array().colwise() - z_pred.array());\n  S = S * weights_.asDiagonal() * S.transpose() + R_;\n\n  // Step #6 - Calculate Cross Correlation Matrix\n  MatrixXd Tc = MatrixXd(n_x_, n_z);\n  Tc = (Xsig_pred_.array().colwise() - x_.array()).matrix() *\n       weights_.asDiagonal() *\n       (Zsig.array().colwise() - z_pred.array()).matrix().transpose();\n\n  // Step #7 - Calculate Kalman gain K\n  const MatrixXd K = Tc * S.inverse();\n\n  // Step #8 - Update state mean and covariance matrix\n  const VectorXd z = meas_package.raw_measurements_;\n  const VectorXd y = z - z_pred;\n  x_ = x_ + (K * y);\n  P_ = P_ - K * S * K.transpose();\n\n  // Calculate NIS for Radar\n  NIS_radar_ = y.transpose() * S.inverse() * y;\n}", "meta": {"hexsha": "e3d163620e0a5ba49450e8ad3deb45a9067932bb", "size": 9764, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SFND_Kalman_Filter/SFND_Unscented_Kalman_Filter/src/ukf.cpp", "max_stars_repo_name": "KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree", "max_stars_repo_head_hexsha": "2c6d26bee670abe2c63034d26556f99f6d77925b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T07:13:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T18:42:13.000Z", "max_issues_repo_path": "SFND_Kalman_Filter/SFND_Unscented_Kalman_Filter/src/ukf.cpp", "max_issues_repo_name": "KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree", "max_issues_repo_head_hexsha": "2c6d26bee670abe2c63034d26556f99f6d77925b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SFND_Kalman_Filter/SFND_Unscented_Kalman_Filter/src/ukf.cpp", "max_forks_repo_name": "KU-AIRS-SPARK/Udacity_Sensor_Fusion_Nanodegree", "max_forks_repo_head_hexsha": "2c6d26bee670abe2c63034d26556f99f6d77925b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-09-29T05:27:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T18:26:53.000Z", "avg_line_length": 33.6689655172, "max_line_length": 79, "alphanum_fraction": 0.6388775092, "num_tokens": 2977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.40949291989784803}}
{"text": "/**\n * @file \n * @author Denise Ratasich\n * @date 05.09.2013\n *\n * @brief Configuration for ROS node.\n */\n\n#include <Eigen/Core>\n#include <string>\n#include <stdexcept>\n#include \"estimation/models.h\"\n#include \"configuration/configuration.h\"\n\nusing namespace estimation;\nusing namespace Eigen;\n\n// private functions\nstd::string getMethod();\n\n// models\n#if METHOD == EXTENDED_KALMAN_FILTER  ||\t\\\n  METHOD == UNSCENTED_KALMAN_FILTER  ||\t\t\\\n  METHOD == PARTICLE_FILTER_SIR\nvoid f(VectorXd& x, const VectorXd& u);\nvoid h(VectorXd& z, const VectorXd& x);\n#endif\n#if METHOD == EXTENDED_KALMAN_FILTER\nvoid df(MatrixXd& A, const VectorXd& x, const VectorXd& u);\nvoid dh(MatrixXd& H, const VectorXd& x);\n#endif\n\n// public functions for the ROS node\nint getEstimatePeriod(void)\n{\n  return ESTIMATION_PERIOD;\n}\n\nvoid initEstimatorFactory(EstimatorFactory& factory)\n{\n  factory.addParam(\"method\", getMethod());\n\n#ifdef WINDOW_SIZE\n  factory.addParam(\"window-size\", WINDOW_SIZE);\n#endif\n#ifdef WEIGHTING_COEFFICIENTS\n  VectorXd wc(VECTOR_SIZE(WEIGHTING_COEFFICIENTS));\n  CODE_ASSIGN_VALUES_TO_VECTOR(wc, WEIGHTING_COEFFICIENTS);\n  factory.addParam(\"weighting-coefficients\", wc);\n#endif\n\n#ifdef STATE_TRANSITION_MODEL\n  #if METHOD == KALMAN_FILTER\n  MatrixXd stm(MATRIX_ROWS(STATE_TRANSITION_MODEL),\n\t       MATRIX_COLS(STATE_TRANSITION_MODEL));\n  CODE_ASSIGN_VALUES_TO_MATRIX(stm, STATE_TRANSITION_MODEL);\n  #elif METHOD == EXTENDED_KALMAN_FILTER  ||\t\\\n    METHOD == UNSCENTED_KALMAN_FILTER  ||\t\\\n    METHOD == PARTICLE_FILTER_SIR\n  func_f stm = f;\n  #endif\n  factory.addParam(\"state-transition-model\", stm);\n#endif\n#ifdef PROCESS_NOISE_COVARIANCE\n  MatrixXd pnc(MATRIX_ROWS(PROCESS_NOISE_COVARIANCE),\n\t       MATRIX_COLS(PROCESS_NOISE_COVARIANCE));\n  CODE_ASSIGN_VALUES_TO_MATRIX(pnc, PROCESS_NOISE_COVARIANCE);\n  factory.addParam(\"process-noise-covariance\", pnc);\n#endif\n#ifdef OBSERVATION_MODEL\n  #if METHOD == KALMAN_FILTER\n  MatrixXd om(MATRIX_ROWS(OBSERVATION_MODEL),\n\t       MATRIX_COLS(OBSERVATION_MODEL));\n  CODE_ASSIGN_VALUES_TO_MATRIX(om, OBSERVATION_MODEL);\n  #elif METHOD == EXTENDED_KALMAN_FILTER  ||\t\\\n    METHOD == UNSCENTED_KALMAN_FILTER  ||\t\\\n    METHOD == PARTICLE_FILTER_SIR\n  func_h om = h;\n  #endif\n  factory.addParam(\"observation-model\", om);\n#endif\n#ifdef MEASUREMENT_NOISE_COVARIANCE\n  MatrixXd mnc(MATRIX_ROWS(MEASUREMENT_NOISE_COVARIANCE),\n\t       MATRIX_COLS(MEASUREMENT_NOISE_COVARIANCE));\n  CODE_ASSIGN_VALUES_TO_MATRIX(mnc, MEASUREMENT_NOISE_COVARIANCE);\n  factory.addParam(\"measurement-noise-covariance\", mnc);\n#endif\n#ifdef CONTROL_INPUT_MODEL \n  MatrixXd cim(MATRIX_ROWS(CONTROL_INPUT_MODEL),\n\t       MATRIX_COLS(CONTROL_INPUT_MODEL));\n  CODE_ASSIGN_VALUES_TO_MATRIX(cim, CONTROL_INPUT_MODEL);\n  factory.addParam(\"control-input-model\", cim);\n#endif\n#ifdef INITIAL_STATE\n  VectorXd is(VECTOR_SIZE(INITIAL_STATE));\n  CODE_ASSIGN_VALUES_TO_VECTOR(is, INITIAL_STATE);\n  factory.addParam(\"initial-state\", is);\n#endif\n#ifdef INITIAL_ERROR_COVARIANCE\n  MatrixXd iec(MATRIX_ROWS(INITIAL_ERROR_COVARIANCE),\n\t       MATRIX_COLS(INITIAL_ERROR_COVARIANCE));\n  CODE_ASSIGN_VALUES_TO_MATRIX(iec, INITIAL_ERROR_COVARIANCE);\n  factory.addParam(\"initial-error-covariance\", iec);\n#endif\n\n#ifdef STATE_SIZE\n  factory.addParam(\"state-size\", STATE_SIZE);\n#endif\n#ifdef MEASUREMENT_SIZE\n  factory.addParam(\"measurement-size\", MEASUREMENT_SIZE);\n#endif\n#ifdef CONTROL_SIZE\n  factory.addParam(\"control-input-size\", CONTROL_SIZE);\n#endif\n\n#ifdef STATE_TRANSITION_MODEL_JACOBIAN\n  func_df stmj = df;\n  factory.addParam(\"state-transition-model-jacobian\", stmj);\n#endif\n#ifdef OBSERVATION_MODEL_JACOBIAN\n  func_dh omj = dh;\n  factory.addParam(\"observation-model-jacobian\", omj);\n#endif\n\n// SIR\n#ifdef STATE_BOUNDS\n  MatrixXd sb(MATRIX_ROWS(STATE_BOUNDS),\n\t      MATRIX_COLS(STATE_BOUNDS));\n  CODE_ASSIGN_VALUES_TO_MATRIX(sb, STATE_BOUNDS);\n  factory.addParam(\"state-bounds\", sb);\n#endif\n#ifdef NUMBER_OF_PARTICLES\n  factory.addParam(\"number-of-particles\", NUMBER_OF_PARTICLES);\n#endif\n\n// Confidence-Weighted Averaging\n#ifdef IGNORE_ZERO_VARIANCE_VALUES\n  factory.addParam(\"ignore-zero-variance-values\", 0);\n#endif\n}\n\n// implementation of private functions\nstd::string getMethod()\n{\n#if METHOD == MOVING_MEDIAN\n  return \"MovingMedian\";\n#elif METHOD == MOVING_AVERAGE\n  return \"MovingAverage\";\n#elif METHOD == KALMAN_FILTER\n  return \"KalmanFilter\";\n#elif METHOD == EXTENDED_KALMAN_FILTER\n  return \"ExtendedKalmanFilter\";\n#elif METHOD == UNSCENTED_KALMAN_FILTER\n  return \"UnscentedKalmanFilter\";\n#elif METHOD == PARTICLE_FILTER_SIR\n  return \"ParticleFilterSIR\";\n#elif METHOD == CONFIDENCE_WEIGHTED_AVERAGING\n  return \"ConfidenceWeightedAveraging\";\n#endif\n}\n\n// implementation of models\n#if METHOD == EXTENDED_KALMAN_FILTER  ||\t\\\n  METHOD == UNSCENTED_KALMAN_FILTER  ||\t\t\\\n  METHOD == PARTICLE_FILTER_SIR\nvoid f(VectorXd& x, const VectorXd& u)\n{\n  if (x.size() != STATE_SIZE)\n    throw std::runtime_error(\"Applying state transition model failed, state vector has invalid size.\");\n\n  // create state vector for result, i.e. the a priori state estimate;\n  // copying must be done, because x occurs on the right-hand side,\n  // e.g.: x[0] = x[1]; x[1] = x[0]; is different to x_apriori[0] =\n  // x[1]; x_apriori[1] = x[0];!!\n  VectorXd x_apriori(x.size());\n\n  try\n  {\n    // assign formulas of the state transition model (from the\n    // configuration header) to vector x, i.e. calculate a priori state\n    // estimate\n    CODE_ASSIGN_FORMULAS_TO_VECTOR(x_apriori, STATE_TRANSITION_MODEL);\n  }\n  catch (std::exception& e)\n  {\n    std::string additionalInfo = \"Applying state transition model failed. \";\n    throw std::runtime_error(additionalInfo + e.what());\n  }\n\n  // copy back, x will then represent the a priori state estimate\n  x = x_apriori;\n}\n\nvoid h(VectorXd& z, const VectorXd& x)\n{\n  if (z.size() != MEASUREMENT_SIZE)\n    throw std::runtime_error(\"Applying observation model failed, measurement vector has invalid size.\");\n\n  try\n  {\n    // z doesn't occur on the right-hand side, so no copying necessary\n    CODE_ASSIGN_FORMULAS_TO_VECTOR(z, OBSERVATION_MODEL);\n  }\n  catch (std::exception& e)\n  {\n    std::string additionalInfo = \"Applying observation model failed. \";\n    throw std::runtime_error(additionalInfo + e.what());\n  }\n}\n#endif\n\n#if METHOD == EXTENDED_KALMAN_FILTER\nvoid df(MatrixXd& A, const VectorXd& x, const VectorXd& u)\n{\n  try\n  {\n    CODE_ASSIGN_FORMULAS_TO_MATRIX(A, STATE_TRANSITION_MODEL_JACOBIAN);\n  }\n  catch (std::exception& e)\n  {\n    std::string additionalInfo = \"Applying Jacobian of state transition model failed. \";\n    throw std::runtime_error(additionalInfo + e.what());\n  }\n}\n\nvoid dh(MatrixXd& H, const VectorXd& x)\n{\n  try\n  {\n    CODE_ASSIGN_FORMULAS_TO_MATRIX(H, OBSERVATION_MODEL_JACOBIAN);\n  }\n  catch (std::exception& e)\n  {\n    std::string additionalInfo = \"Applying Jacobian of observation model failed. \";\n    throw std::runtime_error(additionalInfo + e.what());\n  }\n}\n#endif\n", "meta": {"hexsha": "e13d384981dc34e9939ef6d528d3947fd590fc95", "size": 6915, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sf_filter/filter/src/configuration/configuration.cpp", "max_stars_repo_name": "tuw-cpsg/sf-pkg", "max_stars_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T09:47:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T16:01:11.000Z", "max_issues_repo_path": "sf_filter/filter/src/configuration/configuration.cpp", "max_issues_repo_name": "ros-agriculture/sf-pkg", "max_issues_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T04:59:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-13T14:39:24.000Z", "max_forks_repo_path": "sf_filter/filter/src/configuration/configuration.cpp", "max_forks_repo_name": "tuw-cpsg/sf-pkg", "max_forks_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-17T21:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T17:00:28.000Z", "avg_line_length": 28.9330543933, "max_line_length": 104, "alphanum_fraction": 0.7467823572, "num_tokens": 1849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4094552564874355}}
{"text": "/*\n * Copyright 2011-2013 Mario Mulansky\n * Copyright 2012 Karsten Ahnert\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n *\n * Example for the lorenz system with a 3D point type\n*/\n\n#include <iostream>\n#include <cmath>\n\n#include <boost/operators.hpp>\n\n#include <boost/numeric/odeint.hpp>\n\n\n//[point3D\nclass point3D :\n    boost::additive1< point3D ,\n    boost::additive2< point3D , double ,\n    boost::multiplicative2< point3D , double > > >\n{\npublic:\n\n    double x , y , z;\n\n    point3D()\n        : x( 0.0 ) , y( 0.0 ) , z( 0.0 )\n    { }\n\n    point3D( const double val )\n        : x( val ) , y( val ) , z( val )\n    { }\n\n    point3D( const double _x , const double _y , const double _z  )\n        : x( _x ) , y( _y ) , z( _z )\n    { }\n\n    point3D& operator+=( const point3D &p )\n    {\n        x += p.x; y += p.y; z += p.z;\n        return *this;\n    }\n\n    point3D& operator*=( const double a )\n    {\n        x *= a; y *= a; z *= a;\n        return *this;\n    }\n\n};\n//]\n\n//[point3D_abs_div\n// only required for steppers with error control\npoint3D operator/( const point3D &p1 , const point3D &p2 )\n{\n    return point3D( p1.x/p2.x , p1.y/p2.y , p1.z/p1.z );\n}\n\npoint3D abs( const point3D &p )\n{\n    return point3D( std::abs(p.x) , std::abs(p.y) , std::abs(p.z) );\n}\n//]\n\n//[point3D_norm\n// also only for steppers with error control\nnamespace boost { namespace numeric { namespace odeint {\ntemplate<>\nstruct vector_space_norm_inf< point3D >\n{\n    typedef double result_type;\n    double operator()( const point3D &p ) const\n    {\n        using std::max;\n        using std::abs;\n        return max( max( abs( p.x ) , abs( p.y ) ) , abs( p.z ) );\n    }\n};\n} } }\n//]\n\nstd::ostream& operator<<( std::ostream &out , const point3D &p )\n{\n    out << p.x << \" \" << p.y << \" \" << p.z;\n    return out;\n}\n\n//[point3D_main\nconst double sigma = 10.0;\nconst double R = 28.0;\nconst double b = 8.0 / 3.0;\n\nvoid lorenz( const point3D &x , point3D &dxdt , const double t )\n{\n    dxdt.x = sigma * ( x.y - x.x );\n    dxdt.y = R * x.x - x.y - x.x * x.z;\n    dxdt.z = -b * x.z + x.x * x.y;\n}\n\nusing namespace boost::numeric::odeint;\n\nint main()\n{\n\n    point3D x( 10.0 , 5.0 , 5.0 );\n    // point type defines it's own operators -> use vector_space_algebra !\n    typedef runge_kutta_dopri5< point3D , double , point3D ,\n                                double , vector_space_algebra > stepper;\n    int steps = integrate_adaptive( make_controlled<stepper>( 1E-10 , 1E-10 ) , lorenz , x ,\n                                    0.0 , 10.0 , 0.1 );\n    std::cout << x << std::endl;\n    std::cout << \"steps: \" << steps << std::endl;\n}\n//]\n", "meta": {"hexsha": "4e8b74a4e400d57018050a902fd3b1b3d18ba4cf", "size": 2716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/examples/lorenz_point.cpp", "max_stars_repo_name": "cooparation/caffe-android", "max_stars_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/examples/lorenz_point.cpp", "max_issues_repo_name": "cooparation/caffe-android", "max_issues_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "boost/boost_1_56_0/libs/numeric/odeint/examples/lorenz_point.cpp", "max_forks_repo_name": "cooparation/caffe-android", "max_forks_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 22.6333333333, "max_line_length": 92, "alphanum_fraction": 0.5651693667, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4092859617797498}}
{"text": "// Copyright 2019 Erik Teichmann <kontakt.teichmann@gmail.com>\n\n#ifndef INCLUDE_SAM_SYSTEM_EULER_SYSTEM_HPP_\n#define INCLUDE_SAM_SYSTEM_EULER_SYSTEM_HPP_\n\n#include <vector>\n\n#include <boost/numeric/odeint/integrate/null_observer.hpp>\n\n#include \"./generic_system.hpp\"\n\nnamespace sam {\n\n/*! \\brief A system that is integrated with an Euler method of order O(dt).\n *\n * A system that is integrated with an Euler method of order O(dt). The Euler\n * method is defined as\n * \\f[ x_{n+1} = x_{n} + f_n dt, \\f]\n * where \\f$ f_n \\f$ is the derivative at timestep \\f$ n \\f$.\n */\ntemplate<typename ODE, typename state_type = std::vector<double>>\nclass EulerSystem: public GenericSystem<ODE, state_type> {\n public:\n  template<typename... Ts>\n  explicit EulerSystem(unsigned int system_size, unsigned int dimension,\n                       Ts... parameters);\n\n  template<typename observer_type = boost::numeric::odeint::null_observer>\n  void Integrate(double dt, unsigned int number_steps,\n                 observer_type observer\n                     = boost::numeric::odeint::null_observer());\n\n private:\n  template<typename system_type, typename observer_type>\n  double EulerMethod(system_type system, state_type& x, double t, double dt,\n                     unsigned int number_steps, observer_type observer);\n};\n\n// Implementation\n\ntemplate<typename ODE, typename state_type>\ntemplate<typename... Ts>\nEulerSystem<ODE, state_type>::EulerSystem(unsigned int system_size,\n                                          unsigned int dimension,\n                                          Ts... parameters)\n      : GenericSystem<ODE, state_type>(system_size, dimension, parameters...) {}\n\ntemplate<typename ODE, typename state_type>\ntemplate<typename observer_type>\nvoid EulerSystem<ODE, state_type>::Integrate(double dt,\n                                             unsigned int number_steps,\n                                             observer_type observer) {\n    this->t_ = EulerMethod(*(this->ode_), this->x_, this->t_, dt, number_steps,\n                           observer);\n}\n\ntemplate<typename ODE, typename state_type>\ntemplate<typename system_type, typename observer_type>\ndouble EulerSystem<ODE, state_type>::EulerMethod(system_type system,\n                                                 state_type& x, double t,\n                                                 double dt,\n                                                 unsigned int number_steps,\n                                                 observer_type observer) {\n  observer(x, t);\n  for (unsigned int i = 0; i < number_steps; ++i) {\n    // TODO(boundter): copy the value? how to best initialize?\n    state_type dx = x;\n    system(x, dx, t);\n    // TODO(boundter): Rather use iterators\n    for (size_t j = 0; j < x.size(); ++j) x[j] += dx[j]*dt;\n    t += dt;\n    observer(x, t);\n  }\n  return t;\n}\n\n}  // namespace sam\n\n#endif  // INCLUDE_SAM_SYSTEM_EULER_SYSTEM_HPP_\n", "meta": {"hexsha": "3ed9911acd16fd050ba5395d8b6295c271d35457", "size": 2920, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sam/system/euler_system.hpp", "max_stars_repo_name": "boundter/SAM", "max_stars_repo_head_hexsha": "658b822e6b3eb01f478a6181ff526cfc8f32aa5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sam/system/euler_system.hpp", "max_issues_repo_name": "boundter/SAM", "max_issues_repo_head_hexsha": "658b822e6b3eb01f478a6181ff526cfc8f32aa5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/sam/system/euler_system.hpp", "max_forks_repo_name": "boundter/SAM", "max_forks_repo_head_hexsha": "658b822e6b3eb01f478a6181ff526cfc8f32aa5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5, "max_line_length": 80, "alphanum_fraction": 0.6171232877, "num_tokens": 616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4092859536173254}}
{"text": "#include \"Mbr.h\"\n#include <iostream>\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n#include <vector>\n#include <iterator>\n#include <string>\n#include <limits>\n#include <algorithm>\n#include <math.h>\nusing namespace std;\nMbr::Mbr()\n{\n}\n\nMbr::Mbr(float x1, float y1, float x2, float y2)\n{\n    this->x1 = x1;\n    this->y1 = y1;\n    this->x2 = x2;\n    this->y2 = y2;\n}\n\nvoid Mbr::update(Point point)\n{\n    update(point.x, point.y);\n}\n\nvoid Mbr::update(float x, float y)\n{\n    if (x < x1)\n    {\n        x1 = x;\n    }\n    if (y < y1)\n    {\n        y1 = y;\n    }\n    if (x > x2)\n    {\n        x2 = x;\n    }\n    if (y > y2)\n    {\n        y2 = y;\n    }\n}\n\nvoid Mbr::update(Mbr mbr)\n{\n    if (mbr.x1 < x1)\n    {\n        x1 = mbr.x1;\n    }\n    if (mbr.y1 < y1)\n    {\n        y1 = mbr.y1;\n    }\n    if (mbr.x2 > x2)\n    {\n        x2 = mbr.x2;\n    }\n    if (mbr.y2 > y2)\n    {\n        y2 = mbr.y2;\n    }\n}\n\nbool Mbr::contains(Point point)\n{\n    if (x1 > point.x || point.x > x2 || y1 > point.y || point.y > y2)\n    {\n        return false;\n    }\n    else\n    {\n        return true;\n    }\n}\n\nbool Mbr::strict_contains(Point point)\n{\n    if (x1 < point.x && point.x < x2 && y1 < point.y && point.y < y2)\n    {\n        return true;\n    }\n    else\n    {\n        return false;\n    }\n}\n\nbool Mbr::interact(Mbr mbr)\n{\n    if ((x1 <= mbr.x1 && mbr.x1 <= x2 && y1 <= mbr.y1 && mbr.y1 <= y2) || (x1 <= mbr.x1 && mbr.x1 <= x2 && y1 <= mbr.y2 && mbr.y2 <= y2) || (x1 <= mbr.x2 && mbr.x2 <= x2 && y1 <= mbr.y1 && mbr.y1 <= y2) || (x1 <= mbr.x2 && mbr.x2 <= x2 && y1 <= mbr.y2 && mbr.y2 <= y2))\n    {\n        return true;\n    }\n    if ((mbr.x1 <= x1 && x1 <= mbr.x2 && mbr.y1 <= y1 && y1 <= mbr.y2) || (mbr.x1 <= x1 && x1 <= mbr.x2 && mbr.y1 <= y2 && y2 <= mbr.y2) || (mbr.x1 <= x2 && x2 <= mbr.x2 && mbr.y1 <= y1 && y1 <= mbr.y2) || (mbr.x1 <= x2 && x2 <= mbr.x2 && mbr.y1 <= y2 && y2 <= mbr.y2))\n    {\n        return true;\n    }\n    return false;\n}\n\nvector<Mbr> Mbr::get_mbrs(vector<Point> dataset, float area, int num, float ratio)\n{\n\n    vector<Mbr> mbrs;\n    srand(time(0));\n    int maxInt = numeric_limits<int>::max();\n    float x = sqrt(area * ratio);\n    float y = sqrt(area / ratio);\n    int i = 0;\n    int length = dataset.size();\n    while (i < num)\n    {\n        int index = rand() % length;\n        Point point = dataset[index];\n        if (point.x + x <= 1 && point.y + y <= 1)\n        {\n            Mbr mbr(point.x, point.y, point.x + x, point.y + y);\n            mbrs.push_back(mbr);\n            i++;\n        }\n    }\n\n    return mbrs;\n}\n\nfloat Mbr::cal_dist(Point point)\n{\n    if (this->contains(point))\n    {\n        return 0;\n    }\n    else\n    {\n        float dist;\n        if (point.x < x1)\n        {\n            if (point.y < y1)\n            {\n                dist = sqrt(pow((point.x - x1), 2) + pow((point.y - y1), 2));\n            }\n            else if (point.y <= y2)\n            {\n                dist = x1 - point.x;\n            }\n            else\n            {\n                dist = sqrt(pow((point.x - x1), 2) + pow((point.y - y2), 2));\n            }\n        }\n        else if (point.x <= x2)\n        {\n            if (point.y < y1)\n            {\n                dist = y1 - point.y;\n            }\n            else\n            {\n                dist = point.y - y2;\n            }\n        }\n        else\n        {\n            if (point.y < y1)\n            {\n                dist = sqrt(pow((point.x - x2), 2) + pow((point.y - y1), 2));\n            }\n            else if (point.y <= y2)\n            {\n                dist = point.x - x2;\n            }\n            else\n            {\n                dist = sqrt(pow((point.x - x2), 2) + pow((point.y - y2), 2));\n            }\n        }\n        return dist;\n    }\n}\n\nvoid Mbr::print()\n{\n    cout << \"(x1=\" << x1 << \" y1=\" << y1 << \" x2=\" << x2 << \" y2=\" << y2 << \")\" << endl;\n}\n\nvector<Point> Mbr::get_corner_points()\n{\n    vector<Point> result;\n    Point point1(0, x1, y1);\n    Point point2(0, x2, y1);\n    Point point3(0, x1, y2);\n    Point point4(0, x2, y2);\n    result.push_back(point1);\n    result.push_back(point2);\n    result.push_back(point3);\n    result.push_back(point4);\n    return result;\n}\n\nMbr Mbr::get_mbr(Point point, float knnquerySide)\n{\n    float x1 = point.x - knnquerySide;\n    float x2 = point.x + knnquerySide;\n    float y1 = point.y - knnquerySide;\n    float y2 = point.y + knnquerySide;\n\n    x1 = x1 < 0 ? 0 : x1;\n    y1 = y1 < 0 ? 0 : y1;\n\n    x2 = x2 > 1 ? 1 : x2;\n    y2 = y2 > 1 ? 1 : y2;\n\n    Mbr mbr(x1, y1, x2, y2);\n    return mbr;\n}\n\nvoid Mbr::clean()\n{\n    x1 = 0;\n    x2 = 0;\n    y1 = 0;\n    y2 = 0;\n}\n\nstring Mbr::get_self()\n{\n    return to_string(x1) + \",\" + to_string(y1) + \",\" + to_string(x2) + \",\" + to_string(y2) + \"\\n\";\n}", "meta": {"hexsha": "5e57e2761cd1a14f17888c5ce580c00480aa4f50", "size": 4719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "entities/Mbr.cpp", "max_stars_repo_name": "TerkaSlaninakova/RSMI", "max_stars_repo_head_hexsha": "2120937e2a1866564c51e18ca97f71e21f40f518", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "entities/Mbr.cpp", "max_issues_repo_name": "TerkaSlaninakova/RSMI", "max_issues_repo_head_hexsha": "2120937e2a1866564c51e18ca97f71e21f40f518", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "entities/Mbr.cpp", "max_forks_repo_name": "TerkaSlaninakova/RSMI", "max_forks_repo_head_hexsha": "2120937e2a1866564c51e18ca97f71e21f40f518", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3405172414, "max_line_length": 269, "alphanum_fraction": 0.4367450731, "num_tokens": 1618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4092859536173254}}
{"text": "/**\n * Some part of the source code is from the Rodinia benchmark suite.\n * Link quoted in the README of the original implementation: http://weather.unisys.com/hurricane/\n */\n\n#include <boost/math/special_functions/next.hpp>\n#include <boost/program_options.hpp>\n#include <iostream>\n#include <tuple>\n\n#include \"../device_hopper/core.h\"\n\n#include <omp.h>\n#include <sys/mman.h>\n\n#define RODINIA_NN_EPSILON 10e-05\n#define REPOSITORY_PATH std::string(std::getenv(\"PLASTICITY_ROOT\"))\n#define PREFERRED_DEVICE CPU\n\nusing namespace device_hopper;\n\ntypedef struct latLong\n{\n    float lat;\n    float lng;\n} LatLong;\n\nvoid gen_data(struct latLong *locations, int numRecods) {\n    for (size_t record_i = 0; record_i < numRecods; ++record_i) {\n        locations[record_i].lat = ((float) (7 + rand() % 63)) + ((float) rand() / (float) 0x7fffffff);\n        locations[record_i].lng = ((float) (rand() % 358)) + ((float) rand() / (float) 0x7fffffff);\n    }\n}\n\nbool verifyResults(\n        float* ocl_recordDistances,\n        int numRecords,\n        struct latLong *locations,\n        float latitude,\n        float longitude) {\n\n    float *ref_distances = (float *)malloc(sizeof(float) * numRecords);\n\n    // calculate distances on CPU\n    omp_set_num_threads(4);\n#pragma omp parallel for\n    for (int i = 0; i < numRecords; i++) {\n        const struct latLong location = locations[i];\n        ref_distances[i] = (float) sqrt((latitude  - location.lat) * (latitude  - location.lat) +\n                                        (longitude - location.lng) * (longitude - location.lng));\n    }\n\n    // compare to ocl result\n    bool results_are_correct = true;\n    float largest_difference = 0;\n    float current_difference = 0;\n    for (int i = 0; i < numRecords; i++) {\n        current_difference = abs(ref_distances[i] - ocl_recordDistances[i]);\n        if (current_difference > largest_difference) largest_difference = current_difference;\n        if (current_difference > RODINIA_NN_EPSILON) {\n            if (results_are_correct) {\n                    std::cout << \"Distance mismatch at index \" << i << \" by: \" <<\n                              abs(ref_distances[i] - ocl_recordDistances[i]) << \"\\n\";\n                    std::cout << \"OCL: \" << std::setprecision(10) << ocl_recordDistances[i] << \"\\n\";\n                    std::cout << \"Ref: \" << std::setprecision(10) << ref_distances[i] << \"\\n\";\n                    //std::cout << \"Record: \" << records[i].recString << std::endl;\n                    results_are_correct = false;\n            }\n        }\n    }\n    std::cout << \"Largest epsilon: \" << largest_difference << std::endl;\n\n    free(ref_distances);\n    return results_are_correct;\n}\n\nDEVICE_HOPPER_MAIN(int argc, char* argv[]) {\n    DEVICE_HOPPER_SETUP\n\n    // Parse CLI parameters\n    boost::program_options::options_description desc(\"Options\");\n    desc.add_options() (\"problem-size\", boost::program_options::value<long>(), \"Sample count\");\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);\n    size_t problem_size = 0;\n    if (vm.count(\"problem-size\") == 0) {\n        std::cerr << \"Error: Problem size is missing.\" << std::endl;\n        std::exit(EXIT_FAILURE);\n    } else {\n        // This parameter is passed to the application by the Python scripts that automate the experiments.\n        problem_size = vm[\"problem-size\"].as<long>();\n    }\n\n    // TODO The data paths are currently all hard coded\n    // Choose the problem size\n    std::string data_dir;\n    std::string data_file;\n    int numRecords = 0;\n    if (problem_size == 1) {\n        data_dir = \"small\";\n        data_file = \"list81920k_4.txt\";\n        numRecords = 81920 * 1000;\n    } else if (problem_size == 2) {\n        data_dir = \"medium\";\n        data_file = \"list148480k_8.txt\";\n        numRecords = 148480 * 1000;\n    } else if (problem_size == 3) {\n        data_dir = \"large\";\n        data_file = \"list368640k_8.txt\";\n        numRecords = 368640 * 1000;\n    } else {\n        std::cerr << \"Error: Unknown problem size\" << std::endl;\n        std::exit(EXIT_FAILURE);\n    }\n    // TODO this is currently not used\n    std::string benchmark_data_root = REPOSITORY_PATH + \"/benchmarks/input_data/rodinia/nn/\" + data_dir;\n\n    // Allocate input buffer\n    struct latLong *locations = (struct latLong *) device_hopper::malloc(numRecords, sizeof(struct latLong));\n\n    // Load input data\n    gen_data(locations, numRecords);\n\n    // Allocate output buffer\n    float *recordDistances = (float *) device_hopper::malloc(numRecords, sizeof(float));\n\n    // Default kernel parameters\n    float latitude=30.0;\n    float longitude=90.0;\n\n    // Create parallel for\n    parallel_for pf(0, numRecords, [=]DEVICE_HOPPER_LAMBDA() {\n        int i = GET_ITERATION();\n        struct latLong *latLong = locations+i;\n        if (i < numRecords) { // Not necessary with our programming model\n            float *dist = recordDistances + i;\n            *dist = (float) sqrt((latitude-latLong->lat)  * (latitude-latLong->lat) +\n                                 (longitude-latLong->lng) * (longitude-latLong->lng));\n        }\n    });\n    // Register buffers and describe accesses\n    pf.add_buffer_access_patterns(\n        device_hopper::buf(locations,       direction::IN,  pattern::SUCCESSIVE_SUBSECTIONS(pf.batch_size)),\n        device_hopper::buf(recordDistances, direction::OUT, pattern::SUCCESSIVE_SUBSECTIONS(pf.batch_size)));\n    // Add scalar kernel parameters\n    pf.add_scalar_parameters(latitude, longitude, numRecords);\n    // Set optional tuning parameters and call run()\n    pf.opt_set_batch_size(256).opt_set_simple_indices(true).opt_set_is_idempotent(true).run();\n\n    // Check if the results are correct\n    if (!verifyResults(\n            recordDistances,\n            numRecords,\n            locations,\n            latitude,\n            longitude)) {\n        // Do not change these messages and the return codes.\n        // The Python scripts that automate the experiments expect them.\n        std::cout << \"Error: The results are incorrect\" << std::endl;\n        return EXIT_FAILURE;\n    } else {\n        std::cout << \"Info: The results are correct\" << std::endl;\n    }\n\n    free(locations);\n    free(recordDistances);\n\n    return EXIT_SUCCESS;\n}", "meta": {"hexsha": "05511f6a020471bbe2b9e3ba5a41d6ee59425be2", "size": 6294, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmarks/rodinia_nn.cpp", "max_stars_repo_name": "paulmetzger/Device-Hopping-Paper", "max_stars_repo_head_hexsha": "323acf941080760990ad58b4ed7418462a3c8e0c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmarks/rodinia_nn.cpp", "max_issues_repo_name": "paulmetzger/Device-Hopping-Paper", "max_issues_repo_head_hexsha": "323acf941080760990ad58b4ed7418462a3c8e0c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/rodinia_nn.cpp", "max_forks_repo_name": "paulmetzger/Device-Hopping-Paper", "max_forks_repo_head_hexsha": "323acf941080760990ad58b4ed7418462a3c8e0c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-08T22:51:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T22:51:16.000Z", "avg_line_length": 37.2426035503, "max_line_length": 109, "alphanum_fraction": 0.6283762313, "num_tokens": 1529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4092506972322911}}
{"text": "#include \"IntervalTreeVisitor.h\"\n#include \"Logger.h\"\n#include <exception>\n#include <boost/lexical_cast.hpp>\n#include \"HydLaError.h\"\n\nnamespace hydla\n{\nnamespace interval\n{\n\nusing namespace hydla::symbolic_expression;\n\nitvd IntervalTreeVisitor::pi = kv::constants<itvd>::pi();\nitvd IntervalTreeVisitor::e = kv::constants<itvd>::e();\n\n\n\nIntervalTreeVisitor::IntervalTreeVisitor()\n{\n}\n\n\nitvd IntervalTreeVisitor::get_interval_value(const node_sptr& node, itvd *t, parameter_map_t *map)\n{\n  time_interval = t;\n  parameter_map = map;\n  HYDLA_LOGGER_DEBUG_VAR(get_infix_string(node));\n  accept(node);\n  if(current_value.is_integer)\n    return itvd(current_value.integer);\n  else\n    return current_value.interval_value;\n}\n\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Plus> node)\n{\n  accept(node->get_lhs());\n  IntervalOrInteger lhs = current_value;\n  accept(node->get_rhs());\n  IntervalOrInteger rhs = current_value;\n  current_value = lhs + rhs;\n  // HYDLA_LOGGER_DEBUG(\"Plus : \", current_value.interval_value);\n  return;\n}\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Subtract> node)\n{\n  accept(node->get_lhs());\n  IntervalOrInteger lhs = current_value;\n  accept(node->get_rhs());\n  IntervalOrInteger rhs = current_value;\n  current_value = lhs - rhs;\n  // HYDLA_LOGGER_DEBUG(\"Subtract : \", current_value.interval_value);\n  return;\n}\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Times> node)\n{\n  accept(node->get_lhs());\n  IntervalOrInteger lhs = current_value;\n  accept(node->get_rhs());\n  IntervalOrInteger rhs = current_value;\n  current_value = lhs * rhs;\n  // HYDLA_LOGGER_DEBUG(\"Times : \", current_value.interval_value);\n  return;\n}\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Divide> node)\n{\n  accept(node->get_lhs());\n  IntervalOrInteger lhs = current_value;\n  accept(node->get_rhs());\n  IntervalOrInteger rhs = current_value;\n  current_value = lhs / rhs;\n  // HYDLA_LOGGER_DEBUG(\"Divide : \", current_value.interval_value);\n  return;\n}\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Power> node)\n{\n  accept(node->get_lhs());\n  IntervalOrInteger lhs = current_value;\n  accept(node->get_rhs());\n  IntervalOrInteger rhs = current_value;\n\n  itvd base;\n  if(lhs.is_integer)\n    base = itvd(lhs.integer);\n  else\n    base = lhs.interval_value;\n  // TODO: avoid string comparison\n  if(rhs.is_integer)\n  {\n    current_value.interval_value = pow(base, rhs.integer);\n  }\n  else if(get_infix_string(node->get_rhs()) == \"1/2\")\n  {\n    current_value.interval_value = sqrt(base);\n  }\n  else if(get_infix_string(node->get_rhs()) == \"-1/2\")\n  {\n    HYDLA_LOGGER_DEBUG_VAR(base);\n    current_value.interval_value = 1/sqrt(base);\n  }\n  else\n  {\n    current_value.interval_value = pow(base, rhs.interval_value);\n  }\n\n  current_value.is_integer = false;\n  // HYDLA_LOGGER_DEBUG(\"Power : \", current_value.interval_value);\n  return;\n}\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Negative> node)\n{\n  accept(node->get_child());\n  current_value = -current_value;\n}\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Positive> node)\n{\n  accept(node->get_child());\n}\n\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Pi> node)\n{\n  current_value.interval_value = pi;\n  current_value.is_integer = false;\n  // HYDLA_LOGGER_DEBUG(\"Pi : \", current_value.interval_value);\n  return;\n}\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::E> node)\n{\n  current_value.interval_value = e;\n  current_value.is_integer = false;\n  // HYDLA_LOGGER_DEBUG(\"E : \", current_value.interval_value);\n  return;\n}\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Number> node)\n{\n  std::string number_str = node->get_number();\n\n  // try translation to int\n  try\n  {\n    int integer = boost::lexical_cast<int>(number_str);\n    current_value.is_integer = true;\n    current_value.integer = integer;\n    // HYDLA_LOGGER_DEBUG(\"Number : \", current_value.integer);\n    // HYDLA_LOGGER_NODE_VALUE;\n    return;\n  }\n  catch(const boost::bad_lexical_cast &e)\n  {\n    // do nothing\n  }\n\n  itvd itv = itvd(number_str);\n  current_value.interval_value = itv;\n  current_value.is_integer = false;\n  // HYDLA_LOGGER_DEBUG(\"Number : \", current_value.interval_value);\n  return;\n}\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Float> node)\n{\n  current_value.interval_value = itvd(node->get_number());\n  current_value.is_integer = false;\n  // HYDLA_LOGGER_DEBUG(\"Float : \", current_value.interval_value);\n  return;\n}\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Function> node)\n{\n  std::string name = node->get_name();\n  itvd arg;\n  if(name == \"sin\")\n  {\n    if(node->get_arguments_size() != 1)\n    {\n      invalid_node(*node);\n    }\n    accept(node->get_argument(0));\n    \n    if(current_value.is_integer)\n    {\n      arg = itvd(current_value.integer);\n    }\n    else\n    {\n      arg = current_value.interval_value;\n    }\n\n    current_value.interval_value = sin(arg);\n    current_value.is_integer = false;\n    // HYDLA_LOGGER_DEBUG(\"Sin : \", current_value.interval_value);\n  }\n  else if(name == \"cos\")\n  {\n    if(node->get_arguments_size() != 1)\n    {\n      invalid_node(*node); \n    }\n    accept(node->get_argument(0));\n\n    if(current_value.is_integer)\n    {\n      arg = itvd(current_value.integer);\n    }\n    else\n    {\n      arg = current_value.interval_value;\n    }\n    \n    current_value.interval_value = cos(arg);\n    current_value.is_integer = false;\n    // HYDLA_LOGGER_DEBUG(\"Cos : \", current_value.interval_value);\n  }\n  else if(name == \"tan\")\n  {\n    if(node->get_arguments_size() != 1)\n    {\n      invalid_node(*node);\n    }\n    accept(node->get_argument(0));\n\n    if(current_value.is_integer)\n    {\n      arg = itvd(current_value.integer);\n    }\n    else\n    {\n      arg = current_value.interval_value;\n    }\n    \n    current_value.interval_value = tan(arg);\n    current_value.is_integer = false;\n  }\n  else if(name == \"log\")\n  {\n    HYDLA_LOGGER_DEBUG_VAR(get_infix_string(node));\n    if(node->get_arguments_size() != 1)\n    {\n      invalid_node(*node);\n    }\n    accept(node->get_argument(0));\n\n    if(current_value.is_integer)\n    {\n      arg = itvd(current_value.integer);\n    }\n    else\n    {\n      arg = current_value.interval_value;\n    }\n    \n    current_value.interval_value = log(arg);\n    current_value.is_integer = false;\n    // HYDLA_LOGGER_DEBUG(\"Log : \", current_value.interval_value);\n  }\n  else if(name == \"sinh\")\n  {\n    if(node->get_arguments_size() != 1)\n    {\n      invalid_node(*node);\n    }\n    accept(node->get_argument(0));\n\n    if(current_value.is_integer)\n    {\n      arg = itvd(current_value.integer);\n    }\n    else\n    {\n      arg = current_value.interval_value;\n    }\n    \n    current_value.interval_value = sinh(arg);\n    current_value.is_integer = false;\n  }\n  else if(name == \"cosh\")\n  {\n    if(node->get_arguments_size() != 1)\n    {\n      invalid_node(*node);\n    }\n    accept(node->get_argument(0));\n\n    if(current_value.is_integer)\n    {\n      arg = itvd(current_value.integer);\n    }\n    else\n    {\n      arg = current_value.interval_value;\n    }\n    \n    current_value.interval_value = cosh(arg);\n    current_value.is_integer = false;\n  }\n  else if(name == \"tanh\")\n  {\n    if(node->get_arguments_size() != 1)\n    {\n      invalid_node(*node);\n    }\n    accept(node->get_argument(0));\n\n    if(current_value.is_integer)\n    {\n      arg = itvd(current_value.integer);\n    }\n    else\n    {\n      arg = current_value.interval_value;\n    }\n    \n    current_value.interval_value = tanh(arg);\n    current_value.is_integer = false;\n  }\n  else\n  {\n    invalid_node(*node);\n  }\n  return;\n}\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::SymbolicT> node)\n{\n  if(time_interval == nullptr)invalid_node(*node);\n  current_value.interval_value = *time_interval;\n  current_value.is_integer = false;\n  // HYDLA_LOGGER_DEBUG(\"SymbolicT : \", current_value.interval_value);\n  return;\n}\n\nvoid IntervalTreeVisitor::visit(boost::shared_ptr<hydla::symbolic_expression::Parameter> node)\n{\n  if(parameter_map == nullptr)invalid_node(*node);\n  parameter_t param(node->get_name(),\n                    node->get_differential_count(),\n                    node->get_phase_id());\n  auto param_it = parameter_map->find(param);\n  if(param_it == parameter_map->end())invalid_node(*node);\n\n  range_t range = param_it->second;;\n\n  if(range.unique())\n  {\n    accept(range.get_unique_value().get_node());\n  }\n  else\n  {\n    value_t lower_value = (range.get_lower_bound()).value;\n    accept(lower_value.get_node());\n    itvd lower_itvd;\n    if(current_value.is_integer)\n      lower_itvd = itvd(current_value.integer);\n    else\n      lower_itvd = current_value.interval_value;\n\n    value_t uppper_value = (range.get_upper_bound()).value;\n    accept(uppper_value.get_node());\n    itvd upper_itvd;\n    if(current_value.is_integer)\n      upper_itvd = itvd(current_value.integer);\n    else\n      upper_itvd = current_value.interval_value;\n\n    current_value.interval_value = itvd(lower_itvd.lower(), upper_itvd.upper());\n    current_value.is_integer = false;\n  }\n}\n\n\nvoid IntervalTreeVisitor::invalid_node(symbolic_expression::Node &node)\n{\n  throw HYDLA_ERROR(\"invalid node: \" + node.get_string());\n}\n\nvoid IntervalTreeVisitor::debug_print(std::string str, itvd x)\n{\n  std::cout << str << x << \"\\n\";\n}\n\n\n#define DEFINE_INVALID_NODE(NODE_NAME)                                \\\n  void IntervalTreeVisitor::visit(boost::shared_ptr<NODE_NAME> node)  \\\n{                                                                \\\n  HYDLA_LOGGER_DEBUG(\"\");                                        \\\n  invalid_node(*node);                                           \\\n}\n\n\nDEFINE_INVALID_NODE(Variable)\nDEFINE_INVALID_NODE(Differential)\n\nDEFINE_INVALID_NODE(ConstraintDefinition)\nDEFINE_INVALID_NODE(ProgramDefinition)\nDEFINE_INVALID_NODE(ConstraintCaller)\nDEFINE_INVALID_NODE(ProgramCaller)\nDEFINE_INVALID_NODE(Constraint)\nDEFINE_INVALID_NODE(Ask)\nDEFINE_INVALID_NODE(Tell)\n\nDEFINE_INVALID_NODE(Equal)\nDEFINE_INVALID_NODE(UnEqual)\n\nDEFINE_INVALID_NODE(Less)\nDEFINE_INVALID_NODE(LessEqual)\n\nDEFINE_INVALID_NODE(Greater)\nDEFINE_INVALID_NODE(GreaterEqual)\n\nDEFINE_INVALID_NODE(LogicalAnd)\nDEFINE_INVALID_NODE(LogicalOr)\n\nDEFINE_INVALID_NODE(Weaker)\nDEFINE_INVALID_NODE(Parallel)\n\nDEFINE_INVALID_NODE(Always)\n\nDEFINE_INVALID_NODE(Previous)\n\nDEFINE_INVALID_NODE(Print)\nDEFINE_INVALID_NODE(PrintPP)\nDEFINE_INVALID_NODE(PrintIP)\nDEFINE_INVALID_NODE(Scan)\nDEFINE_INVALID_NODE(Exit)\nDEFINE_INVALID_NODE(Abort)\nDEFINE_INVALID_NODE(SVtimer)\n\nDEFINE_INVALID_NODE(Not)\n\nDEFINE_INVALID_NODE(UnsupportedFunction)\n\nDEFINE_INVALID_NODE(ImaginaryUnit)\nDEFINE_INVALID_NODE(Infinity)\nDEFINE_INVALID_NODE(True)\nDEFINE_INVALID_NODE(False)\n\nDEFINE_INVALID_NODE(ProgramList)\nDEFINE_INVALID_NODE(ConditionalProgramList)\nDEFINE_INVALID_NODE(ExpressionList)\nDEFINE_INVALID_NODE(ConditionalExpressionList)\nDEFINE_INVALID_NODE(EachElement)\nDEFINE_INVALID_NODE(DifferentVariable)\nDEFINE_INVALID_NODE(ExpressionListElement)\nDEFINE_INVALID_NODE(ExpressionListCaller)\nDEFINE_INVALID_NODE(ExpressionListDefinition)\nDEFINE_INVALID_NODE(ProgramListElement)\nDEFINE_INVALID_NODE(ProgramListCaller)\nDEFINE_INVALID_NODE(ProgramListDefinition)\nDEFINE_INVALID_NODE(Range)\nDEFINE_INVALID_NODE(Union)\nDEFINE_INVALID_NODE(Intersection)\nDEFINE_INVALID_NODE(SumOfList)\nDEFINE_INVALID_NODE(MulOfList)\nDEFINE_INVALID_NODE(SizeOfList)\n\n\n} // namespace interval\n} // namespace hydla\n", "meta": {"hexsha": "c4788c6ce9aa5d067b6f553b224992776aa4d48e", "size": 11665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/interval/IntervalTreeVisitor.cpp", "max_stars_repo_name": "takafumihoriuchi/HyLaGI", "max_stars_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T07:11:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T07:11:09.000Z", "max_issues_repo_path": "src/interval/IntervalTreeVisitor.cpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interval/IntervalTreeVisitor.cpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8191489362, "max_line_length": 98, "alphanum_fraction": 0.7077582512, "num_tokens": 2792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.40919377937218904}}
{"text": "#ifndef GENERATER_H\n#define GENERATER_H\n#include <array>\n#include <boost/range/adaptor/indexed.hpp>\n#include <boost/range/adaptor/reversed.hpp>\n#include <string>\n#include <unordered_map>\n\n#include \"geoutil.hpp\"\nconst double PI = 3.1415926535897932384626;\nbool computeSweep(const Polygon_2& in, const FT offset, const Direction_2& dir,\n                  bool counter_clockwise, std::vector<Point_2>* waypoints) {\n  waypoints->clear();\n  if (in.is_clockwise_oriented()) return false;\n  Line_2 sweep(Point_2(0.0, 0.0), dir);\n  std::vector<Point_2> sorted_pts = sortVerticesToLine(in, sweep);\n  sweep = Line_2(sorted_pts.front(), dir);\n  Vector_2 offset_vector = sweep.perpendicular(sorted_pts.front()).to_vector();\n  offset_vector = offset * offset_vector /\n                  std::sqrt(CGAL::to_double(offset_vector.squared_length()));\n  const CGAL::Aff_transformation_2<K> kOffset(CGAL::TRANSLATION, offset_vector);\n  Segment_2 sweep_segment;\n  bool intersect = false;\n  bool has_sweep_segment =\n      findSweepSegment(in, sweep, &sweep_segment, intersect);\n  if (intersect == true) {\n    waypoints->clear();\n    return false;\n  }\n  while (has_sweep_segment == true) {\n    // cout << \"inter: \" << intersect << endl;\n    if (intersect == true) {\n      waypoints->clear();\n      return false;\n    }\n    // Align sweep segment.\n    if (counter_clockwise) sweep_segment = sweep_segment.opposite();\n    // Connect previous sweep.\n    waypoints->push_back(sweep_segment.source());\n    if (!sweep_segment.is_degenerate())\n      waypoints->push_back(sweep_segment.target());\n    // Offset sweep.\n    sweep = sweep.transform(kOffset);\n    has_sweep_segment = findSweepSegment(in, sweep, &sweep_segment, intersect);\n    Segment_2 prev_sweep_segment =\n        counter_clockwise ? sweep_segment.opposite() : sweep_segment;\n    if (!has_sweep_segment &&\n        !((!waypoints->empty() &&\n           *std::prev(waypoints->end(), 1) == sorted_pts.back()) ||\n          (waypoints->size() > 1 &&\n           *std::prev(waypoints->end(), 2) == sorted_pts.back()))) {\n      sweep = Line_2(sorted_pts.back(), dir);\n      has_sweep_segment =\n          findSweepSegment(in, sweep, &sweep_segment, intersect);\n      // Do not add super close sweep.\n      if (CGAL::squared_distance(sweep_segment, prev_sweep_segment) < 0.1)\n        break;\n    }\n    // Swap directions.\n    counter_clockwise = !counter_clockwise;\n  }\n  return true;\n}\nbool computeConvexSweep(Polygon_2& in, FT offset, vector<Point_2>* waypoints) {\n  Polygon_2 convexhull;\n  CGAL::convex_hull_2(in.vertices_begin(), in.vertices_end(),\n                      std::back_inserter(convexhull));\n  simplifyPolygon(convexhull);\n  Direction_2 bestdir = getBestEdgeDirection(convexhull);\n\n  bool counter_clockwise = true;\n  return computeSweep(in, offset, bestdir, counter_clockwise, waypoints);\n}\n/*\ncalculate total length of waypoints\n*/\ndouble CalculatePathlength(const vector<Point_2> waypoints) {\n  int sz = waypoints.size();\n  if (sz < 2)\n    return 0;\n  else {\n    double pathlength = 0;\n    for (int i = 0; i < sz - 1; i++) {\n      pathlength += distance(waypoints[i], waypoints[i + 1]);\n    }\n    return pathlength;\n  }\n}\n/*\nfind SecondOptimaldir in all sweepdir\n*/\nbool computeSecondOptimalSweep(const Polygon_2& in, const FT offset,\n                               Direction_2* SecondOptimaldir) {\n  Polygon_2 convexhull;\n  CGAL::convex_hull_2(in.vertices_begin(), in.vertices_end(),\n                      std::back_inserter(convexhull));\n  simplifyPolygon(convexhull);\n  bool counter_clockwise = true;\n  Direction_2 dir;\n  bool hasAcceptableSweep = false;\n  double min_distance = std::numeric_limits<double>::max();\n  for (EdgeConstIterator edge = convexhull.edges_begin();\n       edge != convexhull.edges_end(); ++edge) {\n    double Vdistance = std::numeric_limits<double>::min();\n    // if not has intersection\n    vector<Point_2> waypoints;\n    if (computeSweep(in, offset, edge->direction(), counter_clockwise,\n                     &waypoints) == true) {\n      for (VertexIterator V = convexhull.vertices_begin();\n           V != convexhull.vertices_end(); V++) {\n        Line_2 edgeLine(edge->source(), edge->target());\n        Vdistance = max(Vdistance,\n                        CGAL::to_double(CGAL::squared_distance(*V, edgeLine)));\n      }\n      hasAcceptableSweep = true;\n      if (min_distance > Vdistance + eps) {\n        min_distance = Vdistance;\n        dir = edge->direction();\n      }\n    }\n    //    cout << \"hello\" << endl;\n  }\n  if (hasAcceptableSweep == false) return false;\n  *SecondOptimaldir = dir;\n  return true;\n}\n/*\ntry to compute a bestsweep ,otherwise second optimal sweeps;\n*/\nbool ComputeAllSweep(const Polygon_2& in, double footprint_width,\n                     double horizontalOverwrap,\n                     vector<vector<Point_2> >* cluster_sweeps,\n                     Direction_2& Dir) {\n  FT offset = footprint_width * (1 - horizontalOverwrap);\n  bool counter_clockwise = true;\n  vector<Point_2> sweep;\n  // compute bestdir\n  Polygon_2 convexhull;\n  CGAL::convex_hull_2(in.vertices_begin(), in.vertices_end(),\n                      std::back_inserter(convexhull));\n  simplifyPolygon(convexhull);\n  Direction_2 bestdir = getBestEdgeDirection(convexhull);\n  if (computeSweep(in, offset, bestdir, counter_clockwise, &sweep) == false) {\n    // can not generate a no-insert zigzag path\n    if (computeSecondOptimalSweep(in, offset, &bestdir) == false) {\n      cluster_sweeps->clear();\n      return false;\n    }\n  }\n  // compute cluster_waypoints\n  computeSweep(in, offset, bestdir, counter_clockwise, &sweep);\n  cluster_sweeps->push_back(sweep);  // counter_clockwise\n\n  std::reverse(sweep.begin(), sweep.end());\n  cluster_sweeps->push_back(sweep);  // reverse\n  computeSweep(in, offset, bestdir, !counter_clockwise, &sweep);\n  cluster_sweeps->push_back(sweep);  // clockwise\n  std::reverse(sweep.begin(), sweep.end());\n  cluster_sweeps->push_back(sweep);  // reverse\n  Dir = bestdir;\n  return true;\n}\n\n#endif\n", "meta": {"hexsha": "1ca9e6d634e30a63d7b5bf8fa1a86ab6f9ca3327", "size": 5982, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "uvacpp/generater.hpp", "max_stars_repo_name": "cytuslee/uvacpp", "max_stars_repo_head_hexsha": "16785fb581da3063dd8ba88c5a3e126f221a125c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "uvacpp/generater.hpp", "max_issues_repo_name": "cytuslee/uvacpp", "max_issues_repo_head_hexsha": "16785fb581da3063dd8ba88c5a3e126f221a125c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "uvacpp/generater.hpp", "max_forks_repo_name": "cytuslee/uvacpp", "max_forks_repo_head_hexsha": "16785fb581da3063dd8ba88c5a3e126f221a125c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2545454545, "max_line_length": 80, "alphanum_fraction": 0.6668338348, "num_tokens": 1556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.40919377310809524}}
{"text": "//===- conv.cc ------------------------------------------------------------===//\n//\n//                       The CIM Hardware Simulator Project\n//\n// See LICENSE.TXT for details.\n//\n//===----------------------------------------------------------------------===//\n#include \"conv.hh\"\n#include \"diagnostic/msgHandling.hh\"\n#include <Eigen/Dense>\n\nnamespace cimHW {\n\nenum class AutoPadType {\n  NOTSET = 0,\n  VALID = 1,\n  SAME_UPPER = 2,\n  SAME_LOWER = 3,\n};\n\ninline AutoPadType StringToAutoPadType(const std::string& str) {\n  if (str == \"NOTSET\") {  // in onnx spec, default value is \"NOTSET\"\n    return AutoPadType::NOTSET;\n  }\n  if (str == \"VALID\") {\n    return AutoPadType::VALID;\n  }\n  if (str == \"SAME_UPPER\") {\n    return AutoPadType::SAME_UPPER;\n  }\n  if (str == \"SAME_LOWER\") {\n    return AutoPadType::SAME_LOWER;\n  }\n  // default, use NOTSET\n  return AutoPadType::NOTSET;\n}\n\ndim_type computePadAndOutputShape(\n    const int in_dim,\n    const int kernel,\n    const int stride,\n    const int dilation,\n    AutoPadType pad_type,\n    int* pad_head,\n    int* pad_tail)\n{\n  const int dkernel = dilation * (kernel - 1) + 1;\n  int out_dim = 0;\n  if (pad_type == AutoPadType::NOTSET)\n  {\n    out_dim = static_cast<int>(static_cast<float>(in_dim + *pad_head + *pad_tail - dkernel) / stride + 1);\n  }\n  else\n  {\n    switch (pad_type) {\n      // VALID is nopad\n      case AutoPadType::VALID:\n        *pad_head = 0;\n        *pad_tail = 0;\n        out_dim = (in_dim - dkernel) / stride + 1;\n        break;\n      case AutoPadType::SAME_UPPER:\n      case AutoPadType::SAME_LOWER:\n      {\n        assert(dilation == 1 && \"Dilation not supported for AutoPadType::SAME_UPPER or AutoPadType::SAME_LOWER.\");\n        int legacy_target_size = (in_dim + stride - 1) / stride;\n        int pad_needed = (legacy_target_size - 1) * stride + kernel - in_dim;\n        out_dim = (in_dim + pad_needed - dkernel) / stride + 1;\n\n        // pad the extra to the end if SAME_UPPER, or to the begining if SAME_LOWER\n        *pad_head = (pad_type == AutoPadType::SAME_LOWER)? (pad_needed + 1) / 2 : pad_needed / 2;\n        *pad_tail = pad_needed - *pad_head;\n      }\n      break;\n      default:\n        assert(false && \"pad type not supported.\");\n    }\n  }\n  return out_dim;\n}\n\n// fetch all posible data cubes (along with kernel height and width) used to do matmul with kernel matrix\nvoid im2col(const float *data_im, const int channels, const int height, const int width,\n            const int kernel_h, const int kernel_w,\n            const int pad_t, const int pad_b,\n            const int pad_l, const int pad_r,\n            const int stride_h, const int stride_w,\n            const int dilation_h, const int dilation_w,\n            float *data_col)\n{\n  auto is_a_ge_zero_and_a_lt_b = [](int a, int b) { return static_cast<unsigned>(a) < static_cast<unsigned>(b); };\n  auto get_conv_output_size = [](const int intput_size,\n                                 const int kernel_size,\n                                 const int pad_begin,\n                                 const int pad_end,\n                                 const int stride_step,\n                                 const int dilation_rate)\n  {\n    return (intput_size + pad_begin + pad_end - (dilation_rate * (kernel_size - 1) + 1)) / stride_step + 1;\n  };\n\n  const int output_h = get_conv_output_size(height, kernel_h, pad_t, pad_b, stride_h, dilation_h);\n  const int output_w = get_conv_output_size(width, kernel_w, pad_l, pad_r, stride_w, dilation_w);\n  const int channel_size = height * width;\n\n  for (int channel = channels; channel--; data_im += channel_size)\n  {\n    for (int kernel_row = 0; kernel_row < kernel_h; kernel_row++)\n    {\n      for (int kernel_col = 0; kernel_col < kernel_w; kernel_col++)\n      {\n        int input_row = -pad_t + kernel_row * dilation_h;\n        for (int output_rows = output_h; output_rows; output_rows--)\n        {\n          if (!is_a_ge_zero_and_a_lt_b(input_row, height))\n          {\n            for (int output_cols = output_w; output_cols; output_cols--)\n            {\n              *(data_col++) = 0;\n            }\n          }\n          else\n          {\n            int input_col = -pad_l + kernel_col * dilation_w;\n            for (int output_col = output_w; output_col; output_col--)\n            {\n              if (is_a_ge_zero_and_a_lt_b(input_col, width))\n              {\n                *(data_col++) = data_im[input_row * width + input_col];\n              }\n              else\n              {\n                *(data_col++) = 0;\n              }\n              input_col += stride_w;\n            } // output_col loop\n          }\n          input_row += stride_h;\n        } // output_rows loop\n      } // kernel_col loop\n    } // kernel_row loop\n  } // channel loop\n}\n\n// fetch all posible data cubes (along with kernel D1, D2, D3....Dd) used to do matmul with kernel matrix\nvoid im2colNd(const float* data_img, const int* im_shape, const int* col_shape,\n              const int* m_kernel_shape, const int N,\n              const int* pad,\n              const int* stride,\n              const int* dilation,\n              float* data_col,\n              const int padding_value = 0)\n{\n  int kernel_size = 1;\n  for (int i = 0; i < N; ++i) {\n    kernel_size *= m_kernel_shape[i];\n  }\n  int channels_col = col_shape[0];\n  std::vector<int> d_offset(N, 0);\n  std::vector<int> d_iter(N, 0);\n  for (int c_col = 0; c_col < channels_col; ++c_col) {\n    // Loop over spatial axes in reverse order to compute a per-axis offset.\n    int offset = c_col;\n    for (int d_i = N - 1; d_i >= 0; --d_i) {\n      if (d_i < N - 1) {\n        offset /= m_kernel_shape[d_i + 1];\n      }\n      d_offset[d_i] = offset % m_kernel_shape[d_i];\n    }\n    for (bool incremented = true; incremented;) {\n      // Loop over spatial axes in forward order to compute the indices in the\n      // image and column, and whether the index lies in the padding.\n      int index_col = c_col;\n      int index_im = c_col / kernel_size;\n      bool is_padding = false;\n      for (int d_i = 0; d_i < N; ++d_i) {\n        int d = d_iter[d_i];\n        int d_im = d * stride[d_i] - pad[d_i] + d_offset[d_i] * dilation[d_i];\n        is_padding |= d_im < 0 || d_im >= im_shape[d_i + 1];\n        index_col *= col_shape[d_i + 1];\n        index_col += d;\n        index_im *= im_shape[d_i + 1];\n        index_im += d_im;\n      }\n      if (is_padding) {\n        data_col[index_col] = padding_value;\n      } else {\n        data_col[index_col] = data_img[index_im];\n      }\n      // Loop over spatial axes in reverse order to choose an index,\n      // like counting.\n      incremented = false;\n      for (int d_i = N - 1; d_i >= 0; --d_i) {\n        int d_max = col_shape[d_i + 1];\n        if (d_iter[d_i] == d_max - 1) {\n          d_iter[d_i] = 0;\n        } else {  // d_iter[d_i] < d_max - 1\n          ++d_iter[d_i];\n          incremented = true;\n          break;\n        }\n      }\n    }  // while(incremented) {\n  }    // for (int c = 0; c < channels_col; ++c) {\n}\n\ncimHWConvOp::cimHWConvOp(\n  const std::string &configFilePath,\n  const_element_type* input_X_, const_dim_type input_X_ndim_, const_dim_type* input_X_dims_,\n  const_element_type* input_W_, const_dim_type input_W_ndim_, const_dim_type* input_W_dims_,\n  const_element_type* input_B_, const_dim_type input_B_ndim_, const_dim_type* input_B_dims_,\n  element_type* output_Y_, const_dim_type output_Y_ndim_, const_dim_type* output_Y_dims_,\n  const char* auto_pad_,\n  const_dim_type* dilations_, const_dim_type number_of_dilations_,\n  const_dim_type group_,\n  const_dim_type* kernel_shape_, const_dim_type number_of_kernel_shape_,\n  const_dim_type* pads_, const_dim_type number_of_pads_,\n  const_dim_type* strides_, const_dim_type number_of_strides_)\n  : cimHWOp(\"Conv\")\n  , m_cimCU(configFilePath)\n  , m_input_X(input_X_)\n  , m_input_W(input_W_)\n  , m_input_B(input_B_)\n  , m_output_Y(output_Y_)\n{\n  verbose1(opName());\n\n  // input validation\n  if(input_X_ndim_ <= 2)\n    error(\"Minimum dimension of X is 3\");\n  if(input_W_ndim_ <= 2)\n    error(\"Minimum dimension of W is 3\");\n\n  m_NInputs = input_X_dims_[0];\n  if(m_NInputs != 1)\n    error(\"Only support 1 batch now\");\n\n  // basic property of conv\n  m_Channel       = input_X_dims_[1];\n  m_OutputChannel = input_W_dims_[0];\n  m_input_X_shape = std::vector<dim_type>(input_X_dims_, input_X_dims_ + input_X_ndim_);\n  m_input_W_shape = std::vector<dim_type>(input_W_dims_, input_W_dims_ + input_W_ndim_);\n  if(m_Channel != input_W_dims_[1])\n    error(\"Channel of X and W is not consistent\");\n\n  // check kernel related properties\n  // find out kernel shape, which is the shape excludes M and C from weights\n  m_kernel_shape  = std::vector<dim_type>(input_W_dims_ + 2, input_W_dims_ + input_W_ndim_);\n  m_input_B_shape = std::vector<dim_type>(input_B_dims_, input_B_dims_ + input_B_ndim_);\n  // check dilation\n  m_dilations = std::vector<dim_type>(dilations_, dilations_ + number_of_dilations_);\n  if (m_dilations.empty()) {\n    m_dilations.resize(m_kernel_shape.size(), 1);\n  }\n  // check group\n  m_group = group_;\n  // check pads\n  m_pads = std::vector<dim_type>(pads_, pads_ + number_of_pads_);\n  if (m_pads.empty()) {\n    m_pads.resize(m_kernel_shape.size() * 2, 0);\n  }\n  // check strides\n  m_strides = std::vector<dim_type>(strides_, strides_ + number_of_strides_);\n  if (m_strides.empty()) {\n    m_strides.resize(m_kernel_shape.size(), 1);\n  }\n\n  // infer the shape of output and output_Y from input\n  m_image_shape = std::vector<dim_type>(input_X_dims_ + 2, input_X_dims_ + input_X_ndim_);\n  m_output_Y_shape = std::vector<dim_type> ({m_NInputs, m_OutputChannel});\n  for(int i=0; i< m_image_shape.size(); i++) {\n    m_output_Y_shape.push_back(computePadAndOutputShape(m_image_shape[i], m_kernel_shape[i], m_strides[i], m_dilations[i],\n                                                        StringToAutoPadType(std::string(auto_pad_)),\n                                                        &m_pads[i], &m_pads[ m_image_shape.size()+i]));\n  }\n  for(int i=2; i<m_output_Y_shape.size(); i++)\n    m_output_shape.push_back(m_output_Y_shape[i]);\n}\n\nvoid cimHWConvOp::simulate()\n{\n  // calculate the size of each tensor\n  dim_type m_input_size  = std::accumulate( m_image_shape.cbegin()  ,  m_image_shape.cend()  , 1, std::multiplies<dim_type>());\n  dim_type m_weight_size = std::accumulate(m_input_W_shape.cbegin() , m_input_W_shape.cend() , 1, std::multiplies<dim_type>());\n  dim_type m_kernel_size = std::accumulate(m_kernel_shape.cbegin()  , m_kernel_shape.cend()  , 1, std::multiplies<dim_type>());\n  dim_type m_output_size = std::accumulate(m_output_shape.cbegin()  , m_output_shape.cend()  , 1, std::multiplies<dim_type>());\n\n  // calculate the extended number for easy use\n  const dim_type X_offset      = m_Channel / m_group * m_input_size;\n  const dim_type W_offset      = m_weight_size / m_group;\n  const dim_type kernel_offset = m_kernel_size * m_Channel / m_group;\n  const dim_type kernel_dim    = m_Channel / m_group * m_kernel_size;\n  const dim_type kernel_rank   = m_kernel_shape.size();\n\n  std::vector<dim_type> col_buffer_shape;\n  // Pointwise convolutions can use the original input tensor in place,\n  // otherwise a temporary buffer is required for the im2col transform.\n  // Todo: pointwise conv can do inplace gemm without dataCube and col_buffer\n  //if (kernel_size != 1/* || !HasStridesOneAndNoPadding()*/) {\n  if (kernel_rank != 2) {\n    // only used in in2colNd\n    col_buffer_shape.reserve(1 + m_output_shape.size());\n    col_buffer_shape.push_back(kernel_dim);\n    col_buffer_shape.insert(col_buffer_shape.end(), m_output_shape.begin(), m_output_shape.end());\n  }\n  //}\n\n  // Object is to get matrix product N*M(output_channels) x dataCubes(output_image_size) = kernel * dataCubes\n  MatrixXfRowMajor result = MatrixXfRowMajor::Zero(m_OutputChannel, m_output_size);\n  // prepare dataCubes = dataCubes(output_image_size) x (kernel_size), column-major\n  MatrixXfRowMajor dataCubes = MatrixXfRowMajor::Zero(kernel_dim, m_output_size);\n  for (int group_id = 0; group_id < m_group; ++group_id)\n  {\n    // apply im2col for conv2d\n    if (kernel_rank == 2) {\n\n      im2col(m_input_X + group_id * X_offset, m_Channel / m_group,  m_image_shape[0],  m_image_shape[1],\n               m_kernel_shape[0], m_kernel_shape[1],\n               m_pads[0], m_pads[2],\n               m_pads[1], m_pads[3],\n               m_strides[0], m_strides[1],\n               m_dilations[0], m_dilations[1],\n               dataCubes.data());\n    }\n    else\n    // otherwise, apply im2colNd, including conv1d and more than conv3d\n    {\n      im2colNd(m_input_X + group_id * X_offset, m_input_X_shape.data() + 1, col_buffer_shape.data(),\n              m_kernel_shape.data(), kernel_rank,\n              m_pads.data(),\n              m_strides.data(),\n              m_dilations.data(),\n              dataCubes.data());\n    }\n\n    // prepare kernel =  M(output_channels)/group x (kernel_size)\n    Eigen::Map<const MatrixXfRowMajor> kernel(m_input_W + group_id * W_offset + group_id * kernel_offset, m_OutputChannel / m_group, kernel_dim);\n    // send datacube and each kernel by row to ComputeUnit\n    for(int i=0; i<kernel.rows(); i++)\n      result.block(group_id * m_OutputChannel / m_group, 0, m_OutputChannel / m_group, m_output_size).row(i) = \n                   m_cimCU.compute(dataCubes, kernel.row(i).transpose());\n  }\n\n  // finally, plus bias to every kernel\n  if(m_input_B != nullptr)\n  {\n    MatrixXfRowMajor bias_mat(m_OutputChannel, m_output_size);\n    bias_mat.colwise() = Eigen::Map<const Eigen::VectorXf>(m_input_B, m_input_B_shape[0]);\n    result += bias_mat;\n  }\n\n  // copy back to output\n  memcpy(m_output_Y, result.data(), sizeof(numType) * m_OutputChannel * m_output_size);\n  verbose1(\"\\n\");\n}\n\n}  // namespace cimHW", "meta": {"hexsha": "452941f3cf3c1f2cfad878c613222a5848a403f7", "size": 13747, "ext": "cc", "lang": "C++", "max_stars_repo_path": "skysim/onnc-cimHW/lib/conv.cc", "max_stars_repo_name": "ONNC/ONNC-CIM", "max_stars_repo_head_hexsha": "dd15eae6b22b39dcd2bff179e14ad0eda40e4338", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-05T02:26:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T10:37:20.000Z", "max_issues_repo_path": "skysim/onnc-cimHW/lib/conv.cc", "max_issues_repo_name": "ONNC/ONNC-CIM", "max_issues_repo_head_hexsha": "dd15eae6b22b39dcd2bff179e14ad0eda40e4338", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "skysim/onnc-cimHW/lib/conv.cc", "max_forks_repo_name": "ONNC/ONNC-CIM", "max_forks_repo_head_hexsha": "dd15eae6b22b39dcd2bff179e14ad0eda40e4338", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-11T10:39:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T10:39:01.000Z", "avg_line_length": 38.5070028011, "max_line_length": 145, "alphanum_fraction": 0.629082709, "num_tokens": 3691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.40913457617726984}}
{"text": "#include <emscripten/bind.h>\n\n#include <array>\n#include <queue>\n#include <boost/algorithm/string/split.hpp>       \n#include <boost/algorithm/string.hpp>  \n#include <boost/range/adaptor/reversed.hpp>\n\n#include <CGAL/Arr_conic_traits_2.h>\n#include <CGAL/CORE_algebraic_number_traits.h>\n#include <CGAL/IO/io.h>\n#include <CGAL/Quotient.h>\n#include <CGAL/Simple_cartesian.h>\n#include <CGAL/Bounded_kernel.h>\n\n#include <CGAL/Exact_predicates_exact_constructions_kernel.h>\n\n#include <CGAL/Advancing_front_surface_reconstruction.h>\n#include <CGAL/Aff_transformation_3.h>\n#include <CGAL/Alpha_shape_2.h>\n#include <CGAL/Alpha_shape_3.h>\n#include <CGAL/Alpha_shape_cell_base_3.h>\n#include <CGAL/Alpha_shape_face_base_2.h>\n#include <CGAL/Alpha_shape_vertex_base_2.h>\n#include <CGAL/Alpha_shape_vertex_base_3.h>\n#include <CGAL/Arr_segment_traits_2.h>\n#include <CGAL/Arr_polyline_traits_2.h>\n#include <CGAL/Arrangement_2.h>\n#include <CGAL/Boolean_set_operations_2.h>\n#include <CGAL/Complex_2_in_triangulation_3.h>\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Delaunay_triangulation_3.h>\n#include <CGAL/Polygon_triangulation_decomposition_2.h>\n#include <CGAL/exude_mesh_3.h>\n#include <CGAL/linear_least_squares_fitting_3.h>\n#include <CGAL/make_mesh_3.h>\n#include <CGAL/make_surface_mesh.h>\n#include <CGAL/minkowski_sum_3.h>\n#include <CGAL/perturb_mesh_3.h>\n#include <CGAL/IO/facets_in_complex_2_to_triangle_mesh.h>\n#include <CGAL/Implicit_surface_3.h>\n#include <CGAL/Gps_traits_2.h>\n#include <CGAL/Labeled_mesh_domain_3.h>\n#include <CGAL/Mesh_complex_3_in_triangulation_3.h>\n#include <CGAL/Mesh_criteria_3.h>\n#include <CGAL/Mesh_triangulation_3.h>\n#include <CGAL/Polygon_mesh_processing/bbox.h>\n#include <CGAL/Polygon_mesh_processing/clip.h>\n#include <CGAL/Polygon_mesh_processing/corefinement.h>\n#include <CGAL/Polygon_mesh_processing/detect_features.h>\n#include <CGAL/Polygon_mesh_processing/extrude.h>\n#include <CGAL/Polygon_mesh_processing/orientation.h>\n#include <CGAL/Polygon_mesh_processing/polygon_mesh_to_polygon_soup.h>\n#include <CGAL/Polygon_mesh_processing/polygon_soup_to_polygon_mesh.h>\n#include <CGAL/Polygon_mesh_processing/random_perturbation.h>\n#include <CGAL/Polygon_mesh_processing/remesh.h>\n#include <CGAL/Polygon_mesh_processing/repair_polygon_soup.h>\n#include <CGAL/Polygon_mesh_processing/repair_self_intersections.h>\n#include <CGAL/Polygon_mesh_processing/smooth_mesh.h>\n#include <CGAL/Polygon_mesh_processing/smooth_shape.h>\n#include <CGAL/Polygon_mesh_processing/transform.h>\n#include <CGAL/Polygon_mesh_processing/triangulate_faces.h>\n#include <CGAL/Polygon_mesh_slicer.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/Polygon_with_holes_2.h>\n#include <CGAL/Projection_traits_xy_3.h>\n#include <CGAL/Projection_traits_xz_3.h>\n#include <CGAL/Projection_traits_yz_3.h>\n#include <CGAL/Subdivision_method_3/subdivision_methods_3.h>\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/Surface_mesh_default_triangulation_3.h>\n#include <CGAL/Unique_hash_map.h>\n#include <CGAL/approximated_offset_2.h>\n#include <CGAL/boost/graph/Named_function_parameters.h>\n#include <CGAL/boost/graph/convert_nef_polyhedron_to_polygon_mesh.h>\n#include <CGAL/cartesian_homogeneous_conversion.h>\n#include <CGAL/convex_hull_3.h>\n#include <CGAL/create_offset_polygons_2.h>\n#include <CGAL/create_offset_polygons_from_polygon_with_holes_2.h>\n#include <CGAL/create_straight_skeleton_2.h>\n#include <CGAL/create_straight_skeleton_from_polygon_with_holes_2.h>\n#include <CGAL/intersections.h>\n#include <CGAL/minkowski_sum_2.h>\n#include <CGAL/offset_polygon_2.h>\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;\n\ntypedef Kernel::FT FT;\ntypedef Kernel::RT RT;\ntypedef Kernel::Line_3 Line;\ntypedef Kernel::Plane_3 Plane;\ntypedef Kernel::Point_2 Point_2;\ntypedef Kernel::Point_3 Point;\ntypedef Kernel::Segment_3 Segment;\ntypedef Kernel::Triangle_3 Triangle;\ntypedef Kernel::Vector_2 Vector_2;\ntypedef Kernel::Vector_3 Vector;\ntypedef Kernel::Direction_3 Direction;\ntypedef Kernel::Aff_transformation_3 Transformation;\ntypedef std::vector<Point> Points;\ntypedef std::vector<Point_2> Point_2s;\ntypedef CGAL::Surface_mesh<Point> Surface_mesh;\ntypedef Surface_mesh::Halfedge_index Halfedge_index;\ntypedef Surface_mesh::Face_index Face_index;\ntypedef Surface_mesh::Vertex_index Vertex_index;\ntypedef CGAL::Arr_segment_traits_2<Kernel> Traits_2;\ntypedef CGAL::Arrangement_2<Traits_2> Arrangement_2;\ntypedef Traits_2::X_monotone_curve_2 Segment_2;\n\ntypedef std::array<FT, 3> Triple;\ntypedef std::vector<Triple> Triples;\n\ntypedef std::array<double, 3> DoubleTriple;\ntypedef std::vector<DoubleTriple> DoubleTriples;\n\ntypedef std::array<FT, 4> Quadruple;\n\ntypedef std::vector<std::size_t> Polygon;\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel Kernel_2;\ntypedef CGAL::Polygon_2<Kernel_2> Polygon_2;\ntypedef CGAL::Polygon_with_holes_2<Kernel_2> Polygon_with_holes_2;\ntypedef CGAL::Straight_skeleton_2<Kernel_2> Straight_skeleton_2;\n\ntypedef CGAL::General_polygon_set_2<CGAL::Gps_segment_traits_2<Kernel>> General_polygon_set_2;\n\nnamespace std {\n\ntemplate <typename K> struct hash<CGAL::Plane_3<K> > {\n  std::size_t operator() (const CGAL::Plane_3<K>& plane) const {\n    // FIX: We can do better than this.\n    return 1;\n  }\n};\n\n}\n\n#ifndef TEST_ONLY\n\ndouble time_base = -1;\n\ndouble now(void) {\n  timeval t;\n  gettimeofday(&t, NULL);\n  double time = t.tv_sec + (t.tv_usec * 0.000001);\n  if (time_base == -1) {\n    time_base = time;\n  }\n  return time - time_base;\n}\n\nFT to_FT(const std::string& v) {\n  std::istringstream i(v);\n  FT ft;\n  i >> ft;\n  return ft;\n}\n\nFT to_FT(const double v) {\n  return FT(v);\n}\n\nvoid Polygon__push_back(Polygon* polygon, std::size_t index) {\n  polygon->push_back(index);\n}\n\ntypedef std::vector<Polygon> Polygons;\n\nstruct Triple_array_traits\n{\n  struct Equal_3\n  {\n    bool operator()(const Triple& p, const Triple& q) const {\n      return (p == q);\n    }\n  };\n  struct Less_xyz_3\n  {\n    bool operator()(const Triple& p, const Triple& q) const {\n      return std::lexicographical_compare(p.begin(), p.end(), q.begin(), q.end());\n    }\n  };\n  Equal_3 equal_3_object() const { return Equal_3(); }\n  Less_xyz_3 less_xyz_3_object() const { return Less_xyz_3(); }\n};\n\nconst Surface_mesh* FromPolygonSoupToSurfaceMesh(emscripten::val fill) {\n  Triples triples;\n  Polygons polygons;\n  // Workaround for emscripten::val() bindings.\n  Triples* triples_ptr = &triples;\n  Polygons* polygons_ptr = &polygons;\n  fill(triples_ptr, polygons_ptr);\n  CGAL::Polygon_mesh_processing::repair_polygon_soup(triples, polygons, CGAL::parameters::geom_traits(Triple_array_traits()));\n  CGAL::Polygon_mesh_processing::orient_polygon_soup(triples, polygons);\n  Surface_mesh* mesh = new Surface_mesh();\n  CGAL::Polygon_mesh_processing::polygon_soup_to_polygon_mesh(triples, polygons, *mesh);\n  assert(CGAL::Polygon_mesh_processing::triangulate_faces(*mesh) == true);\n  return mesh;\n}\n\nvoid FromSurfaceMeshToPolygonSoup(const Surface_mesh* mesh, const Transformation* transformation, bool triangulate, emscripten::val emit_polygon, emscripten::val emit_point) {\n  if (triangulate) {\n    // Note: Destructive update.\n    Surface_mesh working_copy(*mesh);\n    CGAL::Polygon_mesh_processing::triangulate_faces(working_copy.faces(), working_copy);\n    return FromSurfaceMeshToPolygonSoup(&working_copy, transformation, false, emit_polygon, emit_point);\n  }\n  Points points;\n  Polygons polygons;\n  CGAL::Polygon_mesh_processing::polygon_mesh_to_polygon_soup(*mesh, points, polygons);\n  for (const auto& polygon : polygons) {\n    emit_polygon();\n    for (const auto& index : polygon) {\n      const auto p = points[index].transform(*transformation);\n      emit_point(CGAL::to_double(p.x().exact()), CGAL::to_double(p.y().exact()), CGAL::to_double(p.z().exact()));\n    }\n  }\n}\n\nconst Surface_mesh* FromFunctionToSurfaceMesh(double radius, double angular_bound, double radius_bound, double distance_bound, double error_bound, emscripten::val function) {\n  typedef CGAL::Surface_mesh_default_triangulation_3 Tr;\n  // c2t3\n  typedef CGAL::Complex_2_in_triangulation_3<Tr> C2t3;\n  typedef Tr::Geom_traits GT;\n  typedef GT::Sphere_3 Sphere_3;\n  typedef GT::Point_3 Point_3;\n  typedef GT::FT FT;\n  typedef FT (*Function)(Point_3);\n  typedef CGAL::Implicit_surface_3<GT, Function> Surface_3;\n  typedef CGAL::Surface_mesh<Point_3> Epick_Surface_mesh;\n\n  Tr tr;            // 3D-Delaunay triangulation\n  C2t3 c2t3 (tr);   // 2D-complex in 3D-Delaunay triangulation\n  // defining the surface\n  auto op = [&](const Point_3& p) { return FT(function(CGAL::to_double(p.x()), CGAL::to_double(p.y()), CGAL::to_double(p.z())).as<double>()); };\n  Surface_3 surface(op,             // pointer to function\n                    Sphere_3(CGAL::ORIGIN, radius * radius)); // bounding sphere\n  CGAL::Surface_mesh_default_criteria_3<Tr> criteria(angular_bound,  // angular bound\n                                                     radius_bound,  // radius bound\n                                                     distance_bound); // distance bound\n  // meshing surface\n  CGAL::make_surface_mesh(c2t3, surface, criteria, CGAL::Manifold_tag());\n  Epick_Surface_mesh epick_mesh;\n  CGAL::facets_in_complex_2_to_triangle_mesh(c2t3, epick_mesh);\n\n  Surface_mesh* epeck_mesh = new Surface_mesh();\n  copy_face_graph(epick_mesh, *epeck_mesh);\n  return epeck_mesh;\n}\n\nstruct TriangularSurfaceMeshBuilder {\n  typedef std::array<std::size_t,3> Facet;\n\n  Surface_mesh& mesh;\n\n  template < typename PointIterator>\n  TriangularSurfaceMeshBuilder(Surface_mesh& mesh, PointIterator b, PointIterator e) : mesh(mesh) {\n    for(; b!=e; ++b) {\n      boost::graph_traits<Surface_mesh>::vertex_descriptor v;\n      v = add_vertex(mesh);\n      mesh.point(v) = *b;\n    }\n  }\n\n  TriangularSurfaceMeshBuilder& operator=(const Facet f) {\n    typedef boost::graph_traits<Surface_mesh>::vertex_descriptor vertex_descriptor;\n    typedef boost::graph_traits<Surface_mesh>::vertices_size_type size_type;\n    mesh.add_face(vertex_descriptor(static_cast<size_type>(f[0])),\n                  vertex_descriptor(static_cast<size_type>(f[1])),\n                  vertex_descriptor(static_cast<size_type>(f[2])));\n    return *this;\n  }\n\n  TriangularSurfaceMeshBuilder& operator*() { return *this; }\n  TriangularSurfaceMeshBuilder& operator++() { return *this; }\n  TriangularSurfaceMeshBuilder operator++(int) { return *this; }\n};\n\nconst Surface_mesh* FromPointsToSurfaceMesh(emscripten::val fill_triples) {\n  Surface_mesh* mesh = new Surface_mesh();\n  std::vector<Triple> triples;\n  std::vector<Triple>* triples_ptr = &triples;\n  fill_triples(triples_ptr);\n  std::vector<Point> points;\n  for (const auto& triple : triples) {\n    points.emplace_back(Point{ triple[0], triple[1], triple[2] });\n  }\n  TriangularSurfaceMeshBuilder builder(*mesh, points.begin(), points.end());\n  CGAL::advancing_front_surface_reconstruction(points.begin(),\n                                               points.end(),\n                                               builder);\n  return mesh;\n}\n\nvoid FitPlaneToPoints(emscripten::val fill_triples, emscripten::val emit_plane) {\n  typedef CGAL::Epick::Plane_3 Plane;\n  typedef CGAL::Epick::Point_3 Point;\n  DoubleTriples triples;\n  std::vector<DoubleTriple>* triples_ptr = &triples;\n  fill_triples(triples_ptr);\n  std::vector<Point> points;\n  for (const auto& triple : triples) {\n    points.emplace_back(Point{ triple[0], triple[1], triple[2] });\n  }\n  Plane plane;\n  if (points.size() > 0) {\n    linear_least_squares_fitting_3(points.begin(), points.end(), plane, CGAL::Dimension_tag<0>());\n    emit_plane(CGAL::to_double(plane.a()), CGAL::to_double(plane.b()), CGAL::to_double(plane.c()), CGAL::to_double(plane.d()));\n  }\n}\n\nconst Surface_mesh* SubdivideSurfaceMesh(const Surface_mesh* input, int method, int iterations) {\n  typedef boost::graph_traits<Surface_mesh>::edge_descriptor edge_descriptor;\n\n  Surface_mesh* mesh = new Surface_mesh(*input);\n\n  CGAL::Polygon_mesh_processing::triangulate_faces(*mesh);\n  switch (method) {\n    case 0:\n      CGAL::Subdivision_method_3::CatmullClark_subdivision(*mesh, CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n      break;\n    // case 1:\n    //   CGAL::Subdivision_method_3::DooSabin_subdivision(*mesh, CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n    //   break;\n    // case 2:\n    //  CGAL::Subdivision_method_3::DQQ(*mesh, CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n    //  break;\n    case 3:\n      CGAL::Subdivision_method_3::Loop_subdivision(*mesh, CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n      break;\n    //case 4:\n    //  CGAL::Subdivision_method_3::PQQ(*mesh, CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n    //  break;\n    //case 5:\n    //  CGAL::Subdivision_method_3::PTQ(*mesh, CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n    //  break;\n    //case 6:\n    //  CGAL::Subdivision_method_3::Sqrt3(*mesh, CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n    //  break;\n    case 7:\n      CGAL::Subdivision_method_3::Sqrt3_subdivision(*mesh, CGAL::Polygon_mesh_processing::parameters::number_of_iterations(iterations));\n      break;\n  }\n\n  return mesh;\n}\n\nconst Surface_mesh* ReverseFaceOrientationsOfSurfaceMesh(const Surface_mesh* input, const Transformation* transformation) {\n  Surface_mesh* mesh = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, *mesh, CGAL::parameters::all_default());\n  CGAL::Polygon_mesh_processing::reverse_face_orientations(mesh->faces(), *mesh);\n  return mesh;\n}\n\nbool IsBadSurfaceMesh(const Surface_mesh* input) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::triangulate_faces(mesh);\n  if (CGAL::Polygon_mesh_processing::does_self_intersect(mesh, CGAL::parameters::all_default())) {\n    std::vector<std::pair<Surface_mesh::Face_index, Surface_mesh::Face_index>> face_pairs;\n    CGAL::Polygon_mesh_processing::self_intersections(mesh, std::back_inserter(face_pairs));\n    for (const auto& pair : face_pairs) {\n      std::cout << \"Intersection between: \" << pair.first << \" and \" << pair.second << std::endl;\n    }\n    std::cout << std::setprecision(20) << mesh << std::endl;\n    return true;\n  }\n\n  for (const Vertex_index vertex : vertices(mesh)) {\n    if (CGAL::Polygon_mesh_processing::is_non_manifold_vertex(vertex, mesh)) {\n      std::cout << \"Non-manifold vertex \" << vertex << std::endl;\n      return true;\n    }\n  }\n\n  return false;\n}\n\nconst Surface_mesh* RemeshSurfaceMesh(const Surface_mesh* input, emscripten::val get_length) {\n  typedef boost::graph_traits<Surface_mesh>::edge_descriptor edge_descriptor;\n\n  Surface_mesh* mesh = new Surface_mesh(*input);\n\n  CGAL::Polygon_mesh_processing::triangulate_faces(*mesh);\n\n  double edge_length;\n\n  while (edge_length = get_length().as<double>(), edge_length > 0) {\n    CGAL::Polygon_mesh_processing::split_long_edges(edges(*mesh), edge_length, *mesh);\n  }\n\n  return mesh;\n}\n\nconst Surface_mesh* TransformSurfaceMesh(const Surface_mesh* input, double m00, double m01, double m02, double m03, double m10, double m11, double m12, double m13, double m20, double m21, double m22, double m23, double hw) {\n  Surface_mesh* output = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(Transformation(FT(m00), FT(m01), FT(m02), FT(m03), FT(m10), FT(m11), FT(m12), FT(m13), FT(m20), FT(m21), FT(m22), FT(m23), FT(hw)), *output, CGAL::parameters::all_default());\n  return output;\n}\n\nconst Surface_mesh* TransformSurfaceMeshByTransform(const Surface_mesh* input, const Transformation* transform) {\n  Surface_mesh* output = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, *output, CGAL::parameters::all_default());\n  return output;\n}\n\nvoid compute_angle(double a, RT& sin_alpha, RT& cos_alpha, RT& w) {\n  // Convert angle to radians.\n  double radians = a * M_PI / 180.0;\n  CGAL::rational_rotation_approximation(radians, sin_alpha, cos_alpha, w, RT(1), RT(1000));\n}\n\nconst Surface_mesh* BendSurfaceMesh(const Surface_mesh* input, const Transformation* transform, double degreesPerMm) {\n  Surface_mesh* c = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, *c, CGAL::parameters::all_default());\n  CGAL::Polygon_mesh_processing::triangulate_faces(*c);\n  \n  // This does not look very efficient.\n  // CHECK: Figure out deformations.\n  for (const Surface_mesh::Vertex_index vertex : c->vertices()) {\n    if (c->is_removed(vertex)) {\n      continue;\n    }\n    Point& point = c->point(vertex);\n    FT lx = point.x();\n    FT ly = point.y();\n    FT radians = ((90 - lx * degreesPerMm) * CGAL_PI) / 180.0;\n    FT radius = ly;\n    RT sin_alpha, cos_alpha, w;\n    CGAL::rational_rotation_approximation(CGAL::to_double(radians.exact()), sin_alpha, cos_alpha, w, RT(1), RT(1000));\n    FT cx = (cos_alpha * radius) / w;\n    FT cy = (sin_alpha * radius) / w;\n    point = Point(cx, cy, point.z());\n  }\n\n  if (CGAL::Polygon_mesh_processing::does_self_intersect(*c, CGAL::parameters::all_default())) {\nstd::cout << \"Bend: Removing self intersections\" << std::endl;\n    CGAL::Polygon_mesh_processing::experimental::remove_self_intersections(*c, CGAL::parameters::preserve_genus(false));\n    if (CGAL::Polygon_mesh_processing::does_self_intersect(*c, CGAL::parameters::all_default())) {\nstd::cout << \"Bend: Removing self intersections failed\" << std::endl;\n    }\n  }\n\n  return c;\n}\n\nconst Surface_mesh* TwistSurfaceMesh(const Surface_mesh* input, const Transformation* transform, double degreesPerMm) {\n  Surface_mesh* c = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, *c, CGAL::parameters::all_default());\n  CGAL::Polygon_mesh_processing::triangulate_faces(*c);\n  \n  // This does not look very efficient.\n  // CHECK: Figure out deformations.\n  for (const Surface_mesh::Vertex_index vertex : c->vertices()) {\n    if (c->is_removed(vertex)) {\n      continue;\n    }\n    Point& point = c->point(vertex);\n    double a = CGAL::to_double(point.z()) * degreesPerMm;\n    RT sin_alpha, cos_alpha, w;\n    compute_angle(a, sin_alpha, cos_alpha, w);\n    Transformation transformation(\n        cos_alpha, sin_alpha, 0, 0,\n        -sin_alpha, cos_alpha, 0, 0,\n        0, 0, w,  0,\n        w);\n    point = point.transform(transformation);\n  }\n  return c;\n}\n\nconst Surface_mesh* PushSurfaceMesh(const Surface_mesh* input, const Transformation* transform, double force, double minimum_distance, double scale) {\n  Surface_mesh* c = new Surface_mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, *c, CGAL::parameters::all_default());\n  Point origin(0, 0, 0);\n  for (const Surface_mesh::Vertex_index vertex : c->vertices()) {\n    if (c->is_removed(vertex)) {\n      continue;\n    }\n    Point& point = c->point(vertex);\n    Vector vector = Vector(origin, point);\n    double distance = sqrt(CGAL::to_double(vector.squared_length())) * scale;\n    FT effect;\n    if ((distance - minimum_distance) <= 1.0) {\n      effect = 1.0;\n    } else {\n      effect = 1.0 - (1.0 / (distance - minimum_distance));\n    }\n    point += vector * (force * effect);\n  }\n  return c;\n}\n\nVector unitVector(const Vector& vector);\nVector NormalOfSurfaceMeshFacet(const Surface_mesh& mesh, Face_index facet);\n\nconst Surface_mesh* GrowSurfaceMesh(const Surface_mesh* input, const Transformation* transformation, double amount) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, mesh, CGAL::parameters::all_default());\n\n  Surface_mesh* result = new Surface_mesh(mesh);\n  for (const Surface_mesh::Vertex_index vertex : mesh.vertices()) {\n    const Surface_mesh::Halfedge_index start = mesh.halfedge(vertex);\n    Surface_mesh::Halfedge_index edge = start;\n    std::vector<Vector> normals;\n    Vector average = CGAL::NULL_VECTOR;\n    do {\n      Surface_mesh::Face_index facet = mesh.face(edge);\n      Vector unit = unitVector(NormalOfSurfaceMeshFacet(mesh, facet));\n      if (std::find(normals.begin(), normals.end(), unit) == normals.end()) {\n        normals.push_back(unit);\n        average += unit;\n      }\n      edge = mesh.next_around_target(edge);\n    } while (edge != start);\n\n    Point& point = result->point(vertex);\n    Vector offset = average * (amount / normals.size());\n    point += offset;\n  }\n  return result;\n}\n\nvoid Surface_mesh__EachFace(const Surface_mesh* mesh, emscripten::val op) {\n  for (const auto& face_index : mesh->faces()) {\n    if (!mesh->is_removed(face_index)) {\n      op(std::size_t(face_index));\n    }\n  }\n}\n\nvoid addTriple(Triples* triples, double x, double y, double z) {\n  triples->emplace_back(Triple{ x, y, z });\n}\n\nvoid addDoubleTriple(DoubleTriples* triples, double x, double y, double z) {\n  triples->emplace_back(DoubleTriple{ x, y, z });\n}\n\nvoid fillQuadruple(Quadruple* q, double x, double y, double z, double w) {\n  (*q)[0] = to_FT(x);\n  (*q)[1] = to_FT(y);\n  (*q)[2] = to_FT(z);\n  (*q)[3] = to_FT(w);\n}\n\nvoid fillExactQuadruple(Quadruple* q, const std::string& a, const std::string& b, const std::string& c, const std::string& d) {\n  (*q)[0] = to_FT(a);\n  (*q)[1] = to_FT(b);\n  (*q)[2] = to_FT(c);\n  (*q)[3] = to_FT(d);\n}\n\nvoid addPoint(Points* points, double x, double y, double z) {\n  points->emplace_back(Point{ x, y, z });\n}\n\nvoid addExactPoint(Points* points, const std::string& x, const std::string& y, const std::string& z) {\n  points->emplace_back(Point{ to_FT(x), to_FT(y), to_FT(z) });\n}\n\nvoid addPoint_2(Point_2s* points, double x, double y) {\n  points->emplace_back(Point_2{ x, y });\n}\n\nstd::size_t Surface_mesh__halfedge_to_target(const Surface_mesh* mesh, std::size_t halfedge_index) {\n  return std::size_t(mesh->target(Halfedge_index(halfedge_index)));\n}\n\nstd::size_t Surface_mesh__halfedge_to_face(const Surface_mesh* mesh, std::size_t halfedge_index) {\n  return std::size_t(mesh->face(Halfedge_index(halfedge_index)));\n}\n\nstd::size_t Surface_mesh__halfedge_to_next_halfedge(const Surface_mesh* mesh, std::size_t halfedge_index) {\n  return std::size_t(mesh->next(Halfedge_index(halfedge_index)));\n}\n\nstd::size_t Surface_mesh__halfedge_to_prev_halfedge(const Surface_mesh* mesh, std::size_t halfedge_index) {\n  return std::size_t(mesh->prev(Halfedge_index(halfedge_index)));\n}\n\nstd::size_t Surface_mesh__halfedge_to_opposite_halfedge(const Surface_mesh* mesh, std::size_t halfedge_index) {\n  return std::size_t(mesh->opposite(Halfedge_index(halfedge_index)));\n}\n\nstd::size_t Surface_mesh__vertex_to_halfedge(const Surface_mesh* mesh, std::size_t vertex_index) {\n  return std::size_t(mesh->halfedge(Vertex_index(vertex_index)));\n}\n\nstd::size_t Surface_mesh__face_to_halfedge(const Surface_mesh* mesh, std::size_t face_index) {\n  return std::size_t(mesh->halfedge(Face_index(face_index)));\n}\n\nconst Point& Surface_mesh__vertex_to_point(const Surface_mesh* mesh, std::size_t vertex_index) {\n  return mesh->point(Vertex_index(vertex_index));\n}\n\nconst std::size_t Surface_mesh__add_exact(Surface_mesh* mesh, std::string x, std::string y, std::string z) {\n  std::size_t index(mesh->add_vertex(Point{to_FT(x), to_FT(y), to_FT(z)}));\n  assert(index == std::size_t(Vertex_index(index)));\n  return index;\n}\n\nconst std::size_t Surface_mesh__add_vertex(Surface_mesh* mesh, float x, float y, float z) {\n  std::size_t index(mesh->add_vertex(Point{x, y, z}));\n  assert(index == std::size_t(Vertex_index(index)));\n  return index;\n}\n\nconst std::size_t Surface_mesh__add_face(Surface_mesh* mesh) {\n  std::size_t index(mesh->add_face());\n  assert(index == std::size_t(Face_index(index)));\n  return index;\n}\n\nconst std::size_t Surface_mesh__add_face_vertices(Surface_mesh* mesh, emscripten::val next_vertex) {\n  std::vector<Vertex_index> vertices;\n  for (;;) {\n    Vertex_index vertex(next_vertex().as<std::size_t>());\n    if (!vertices.empty()) {\n      if (vertex == vertices[0]) {\n        break;\n      } else if (vertex == vertices.back()) {\n        std::cout << \"Duplicate vertex in add face.\" << std::endl;\n        continue;\n      }\n    }\n    vertices.push_back(vertex);\n  }\n  if (vertices.size() < 3) {\n    return -1;\n  } else {\n    auto facet = mesh->add_face(vertices);\n    if (!mesh->is_valid(facet)) {\n      std::cout << \"Invalid face\" << facet << std::endl;\n      return -1;\n    }\n    const auto facet_normal = CGAL::Polygon_mesh_processing::compute_face_normal(facet, *mesh);\n    if (facet_normal == CGAL::NULL_VECTOR) {\n      std::cout << \"Adding degenerate face/facet\" << facet << std::endl;\n      std::cout << \"Adding degenerate face/mesh\" << *mesh << std::endl;\n      return -1;\n    }\n    std::size_t index(facet);\n    std::vector<Surface_mesh::Face_index> degenerate_faces;\n    CGAL::Polygon_mesh_processing::degenerate_faces(mesh->faces(), *mesh, std::back_inserter(degenerate_faces));\n    if (degenerate_faces.size() > 0) {\n      for (const Surface_mesh::Face_index face : degenerate_faces) {\n        std::cout << \"Degenerate face\" << face << std::endl;\n      }\n      return -1;\n    }\n    if (CGAL::Polygon_mesh_processing::face_area(facet, *mesh) == 0) {\n      std::cout << \"Zero area face:\" << facet << std::endl;\n      return -1;\n    }\n    return index;\n  }\n}\n\nconst std::size_t Surface_mesh__add_edge(Surface_mesh* mesh) {\n  std::size_t index(mesh->add_edge());\n  assert(index == std::size_t(Halfedge_index(index)));\n  return index;\n}\n\nvoid Surface_mesh__set_edge_target(Surface_mesh* mesh, std::size_t edge, std::size_t target) {\n  mesh->set_target(Halfedge_index(edge), Vertex_index(target));\n}\n\nvoid Surface_mesh__set_edge_next(Surface_mesh* mesh, std::size_t edge, std::size_t next) {\n  mesh->set_next(Halfedge_index(edge), Halfedge_index(next));\n}\n\nvoid Surface_mesh__set_edge_face(Surface_mesh* mesh, std::size_t edge, std::size_t face) {\n  mesh->set_face(Halfedge_index(edge), Face_index(face));\n}\n\nvoid Surface_mesh__set_face_edge(Surface_mesh* mesh, std::size_t face, std::size_t edge) {\n  mesh->set_halfedge(Face_index(face), Halfedge_index(edge));\n}\n\nvoid Surface_mesh__set_vertex_edge(Surface_mesh* mesh, std::size_t face, std::size_t edge) {\n  mesh->set_halfedge(Vertex_index(face), Halfedge_index(edge));\n}\n\nvoid Surface_mesh__set_vertex_halfedge_to_border_halfedge(Surface_mesh* mesh, std::size_t edge) {\n  return mesh->set_vertex_halfedge_to_border_halfedge(Halfedge_index(edge));\n}\n\nvoid Surface_mesh__collect_garbage(Surface_mesh* mesh) {\n  mesh->collect_garbage();\n}\n\ntemplate<typename MAP>\nstruct Project\n{\n  Project(MAP map, Vector vector): map(map), vector(vector) {}\n\n  template<typename VD, typename T>\n  void operator()(const T&, VD vd) const\n  {\n    put(map, vd, get(map, vd) + vector);\n  }\n\n  MAP map;\n  Vector vector;\n};\n\nPlane unitPlane(const Plane& p) { \n  Vector normal = p.orthogonal_vector();\n  // We can handle the axis aligned planes exactly.\n  if (normal.direction() == Vector(0, 0, 1).direction()) {\n    return Plane(p.point(), Vector(0, 0, 1));\n  } else if (normal.direction() == Vector(0, 0, -1).direction()) {\n    return Plane(p.point(), Vector(0, 0, -1));\n  } else if (normal.direction() == Vector(0, 1, 0).direction()) {\n    return Plane(p.point(), Vector(0, 1, 0));\n  } else if (normal.direction() == Vector(0, -1, 0).direction()) {\n    return Plane(p.point(), Vector(0, -1, 0));\n  } else if (normal.direction() == Vector(1, 0, 0).direction()) {\n    return Plane(p.point(), Vector(1, 0, 0));\n  } else if (normal.direction() == Vector(-1, 0, 0).direction()) {\n    return Plane(p.point(), Vector(-1, 0, 0));\n  } else {\n    // But the general case requires an approximation.\n    Vector unit_normal = normal / CGAL_NTS approximate_sqrt(normal.squared_length());\n    return Plane(p.point(), unit_normal);\n  }\n}\n\nVector unitVector(const Vector& vector) { \n  // We can handle the axis aligned planes exactly.\n  if (vector.direction() == Vector(0, 0, 1).direction()) {\n    return Vector(0, 0, 1);\n  } else if (vector.direction() == Vector(0, 0, -1).direction()) {\n    return Vector(0, 0, -1);\n  } else if (vector.direction() == Vector(0, 1, 0).direction()) {\n    return Vector(0, 1, 0);\n  } else if (vector.direction() == Vector(0, -1, 0).direction()) {\n    return Vector(0, -1, 0);\n  } else if (vector.direction() == Vector(1, 0, 0).direction()) {\n    return Vector(1, 0, 0);\n  } else if (vector.direction() == Vector(-1, 0, 0).direction()) {\n    return Vector(-1, 0, 0);\n  } else {\n    // But the general case requires an approximation.\n    Vector unit_vector = vector / CGAL_NTS approximate_sqrt(vector.squared_length());\n    return unit_vector;\n  }\n}\n\nPlane PlaneOfSurfaceMeshFacet(const Surface_mesh& mesh, Face_index facet) {\n  const auto h = mesh.halfedge(facet);\n  const Plane plane(mesh.point(mesh.source(h)),\n                    mesh.point(mesh.source(mesh.next(h))),\n                    mesh.point(mesh.source(mesh.next(mesh.next(h)))));\n  return plane;\n}\n\nbool SomePlaneOfSurfaceMesh(Plane& plane, const Surface_mesh& mesh) {\n  for (const auto& facet : mesh.faces()) {\n    plane = PlaneOfSurfaceMeshFacet(mesh, facet);\n    return true;\n  }\n  return false;\n}\n\nVector NormalOfSurfaceMeshFacet(const Surface_mesh& mesh, Face_index facet) {\n  const auto h = mesh.halfedge(facet);\n  return CGAL::normal(mesh.point(mesh.source(h)),\n                      mesh.point(mesh.source(mesh.next(h))),\n                      mesh.point(mesh.source(mesh.next(mesh.next(h)))));\n}\n\nVector SomeNormalOfSurfaceMesh(const Surface_mesh& mesh) {\n  for (const auto& facet : mesh.faces()) {\n    return NormalOfSurfaceMeshFacet(mesh, facet);\n  }\n  return CGAL::NULL_VECTOR;\n}\n\nclass SurfaceMeshAndTransform {\n  public:\n   SurfaceMeshAndTransform() : fill_(nullptr) {};\n   SurfaceMeshAndTransform(emscripten::val* fill) : fill_(fill) {};\n\n   emscripten::val* fill_;\n   const Surface_mesh* mesh_;\n   const Transformation* transform_;\n\n   void set_mesh(const Surface_mesh* mesh) { mesh_ = mesh; }\n   void set_transform(const Transformation* transform) { transform_ = transform; }\n   bool fill(const Surface_mesh*& mesh, const Transformation*& transform) {\n     SurfaceMeshAndTransform* self = this;\n     if ((*fill_)(self).as<bool>()) {\n       mesh = mesh_;\n       transform = transform_;\n       return true;\n     } else {\n       return false;\n     }\n   }\n};\n\nconst Surface_mesh* LoftBetweenCongruentSurfaceMeshes(bool closed, emscripten::val fill) {\n  SurfaceMeshAndTransform admit(&fill);\n\n  const Surface_mesh* a;\n  const Surface_mesh* b;\n  const Transformation* a_transform;\n  const Transformation* b_transform;\n\n  if (!admit.fill(a, a_transform) || !admit.fill(b, b_transform)) {\n    return nullptr;\n  }\n\n  Surface_mesh* loft = new Surface_mesh();\n  const Surface_mesh* base = a;\n\n  std::unordered_map<Vertex_index, Vertex_index> base_map;\n  std::unordered_map<Vertex_index, Vertex_index> a_map;\n  std::unordered_map<Vertex_index, Vertex_index> b_map;\n\n  // Build the base of the wall.\n  for (const auto h : a->halfedges()) {\n    if (a->is_border(h)) {\n      auto a_source = a->source(h);\n      a_map[a_source] = loft->add_vertex(a->point(a_source).transform(*a_transform));\n    }\n  }\n\n  if (closed) {\n    base = a;\n    base_map = a_map;\n  } else {\n    // Build the lower cap.\n    for (auto face : a->faces()) {\n      std::vector<Vertex_index> loft_vertices;\n      Halfedge_index start = a->halfedge(face);\n      Halfedge_index h = start;\n      do {\n        Vertex_index a_vertex = a->source(h);\n        auto a_vertex_it = a_map.find(a_vertex);\n        Vertex_index loft_vertex;\n        if (a_vertex_it == a_map.end()) {\n          loft_vertex = loft->add_vertex(a->point(a_vertex).transform(*a_transform));\n          a_map[a_vertex] = loft_vertex;\n        } else {\n          loft_vertex = a_vertex_it->second;\n        }\n        loft_vertices.push_back(loft_vertex);\n        // Walk backward, so that the face is reversed.\n        h = a->prev(h);\n      } while (h != start);\n      loft->add_face(loft_vertices);\n    }\n  }\n\n  bool closing = false;\n\n  // Extend the wall, step by step.\n  for (;;) {\n    std::vector<Halfedge_index> base_edges;\n    for (const auto h : a->halfedges()) {\n      base_edges.push_back(h);\n    }\n    for (const auto h : base_edges) {\n      if (a->is_border(h)) {\n        auto a_source = a->source(h);\n        auto b_source_it = b_map.find(a_source);\n        Vertex_index b_source;\n        if (b_source_it == b_map.end()) {\n          b_source = loft->add_vertex(b->point(a_source).transform(*b_transform));\n          b_map[a_source] = b_source;\n        } else {\n          b_source = b_source_it->second;\n        }\n        auto a_target = a->target(h);\n        auto b_target_it = b_map.find(a_target);\n        Vertex_index b_target;\n        if (b_target_it == b_map.end()) {\n          b_target = loft->add_vertex(b->point(a_target).transform(*b_transform));\n          b_map[a_target] = b_target;\n        } else {\n          b_target = b_target_it->second;\n        }\n        auto face = loft->add_face(b_target, a_map[a_target], a_map[a_source], b_source);\n      }\n    }\n\n    const Surface_mesh* next;\n    if (closing) {\n      // We just finished closing off the final walls.\n      break;\n    } else if (admit.fill(next, b_transform)) {\n      // Continue with the next wall.\n      a = b;\n      b = next;\n      a_map = b_map;\n      b_map.clear();\n      continue;\n    } else if (closed) {\n      // We need to build a wall back to the base.\n      a = b;\n      b = base;\n      a_map = b_map;\n      b_map = base_map;\n      closing = true;\n      continue;\n    } else {\n      // Build the upper cap.\n      for (auto face : b->faces()) {\n        std::vector<Vertex_index> loft_vertices;\n        Halfedge_index start = b->halfedge(face);\n        Halfedge_index h = start;\n        do {\n          Vertex_index b_vertex = b->source(h);\n          auto b_vertex_it = b_map.find(b_vertex);\n          Vertex_index loft_vertex;\n          if (b_vertex_it == b_map.end()) {\n            loft_vertex = loft->add_vertex(b->point(b_vertex).transform(*b_transform));\n            b_map[b_vertex] = loft_vertex;\n          } else {\n            loft_vertex = b_vertex_it->second;\n          }\n          loft_vertices.push_back(loft_vertex);\n          h = b->next(h);\n        } while (h != start);\n        loft->add_face(loft_vertices);\n      }\n      break;\n    }\n  }\n\n  CGAL::Polygon_mesh_processing::triangulate_faces(*loft);\n  return loft;\n}\n\nclass SurfaceMeshQuery {\n typedef CGAL::AABB_face_graph_triangle_primitive<Surface_mesh> Primitive;\n typedef CGAL::AABB_traits<Kernel, Primitive> Traits;\n typedef CGAL::AABB_tree<Traits> Tree;\n typedef boost::optional<Tree::Intersection_and_primitive_id<Point>::Type> Point_intersection;\n typedef boost::optional<Tree::Intersection_and_primitive_id<Segment>::Type> Segment_intersection;\n\n public:\n  SurfaceMeshQuery(Surface_mesh* mesh) {\n    tree_.reset(new Tree(faces(*mesh).first, faces(*mesh).second, *mesh));\n  }\n\n  bool isIntersectingPointApproximate(double x, double y, double z) {\n    return tree_->do_intersect(Point(x, y, z));\n  }\n\n  void clipSegmentApproximate(double source_x, double source_y, double source_z, double target_x, double target_y, double target_z, emscripten::val emit_segment) {\n    Segment segment_query(Point(source_x, source_y, source_z), Point(target_x, target_y, target_z));\n    std::list<Segment_intersection> intersections;\n    tree_->all_intersections(segment_query, std::back_inserter(intersections));\n    for (const auto& intersection : intersections) {\n      if (!intersection) {\n        continue;\n      }\n      // Note: intersection->second is the intersected face index.\n      if (const Segment* segment = boost::get<Segment>(&intersection->first)) {\n        const auto& source = segment->source();\n        const auto& target = segment->target();\n        emit_segment(CGAL::to_double(source.x().exact()),\n                     CGAL::to_double(source.y().exact()),\n                     CGAL::to_double(source.z().exact()),\n                     CGAL::to_double(target.x().exact()),\n                     CGAL::to_double(target.y().exact()),\n                     CGAL::to_double(target.z().exact()));\n      }\n    }\n  }\n\n private:\n  std::unique_ptr<Tree> tree_;\n};\n\nvoid SeparateSurfaceMesh(const Surface_mesh* input, bool keep_volumes, bool keep_cavities_in_volumes, bool keep_cavities_as_volumes, emscripten::val emit_mesh) {\n  std::vector<Surface_mesh> meshes;\n  std::vector<Surface_mesh> cavities;\n  std::vector<Surface_mesh> volumes;\n  CGAL::Polygon_mesh_processing::split_connected_components(*input, meshes);\n\n  // CHECK: Can we leverage volume_connected_components() here?\n  for (auto& mesh : meshes) {\n    // CHECK: Do we have an expensive move here?\n    if (CGAL::Polygon_mesh_processing::is_outward_oriented(mesh)) {\n      volumes.push_back(mesh);\n    } else {\n      cavities.push_back(mesh);\n    }\n  }\n\n  if (keep_volumes) {\n    for (auto& mesh : volumes) {\n      if (keep_cavities_in_volumes) {\n        CGAL::Side_of_triangle_mesh<Surface_mesh, Kernel> inside(mesh);\n        for (auto& cavity : cavities) {\n          for (const auto vertex : cavity.vertices()) {\n            if (inside(cavity.point(vertex)) == CGAL::ON_BOUNDED_SIDE) {\n              // Include the cavity in the mesh.\n              mesh.join(cavity);\n            }\n            // A single test is sufficient.\n            break;\n          }\n        }\n      }\n      Surface_mesh* output = new Surface_mesh(mesh);\n      emit_mesh(output);\n    }\n  }\n\n  if (keep_cavities_as_volumes) {\n    for (auto& mesh : cavities) {\n      CGAL::Polygon_mesh_processing::reverse_face_orientations(mesh);\n      Surface_mesh* output = new Surface_mesh(mesh);\n      emit_mesh(output);\n    }\n  }\n}\n\nbool admitVector(Vector& vector, emscripten::val fill_vector) {\n  Quadruple q;\n  Quadruple* qp = &q;\n  if (fill_vector(qp).as<bool>()) {\n    vector = Vector(q[0], q[1], q[2]);\n    return true;\n  }\n  return false;\n}\n\nVector estimateTriangleNormals(const std::vector<Triangle>& triangles)\n{\n  Vector estimate(0, 0, 0);\n  for(const Triangle& triangle : triangles) {\n    estimate += unitVector(CGAL::Polygon_mesh_processing::internal::triangle_normal(\n          triangle[0], triangle[1], triangle[2], Kernel()));\n  }\n  return estimate;\n}\n\nvoid computeCentroidOfSurfaceMesh(Point& centroid, const Surface_mesh& mesh) {\n  std::vector<Triangle> triangles;\n  for (const auto& facet : mesh.faces()) {\n    if (mesh.is_removed(facet)) {\n      continue;\n    }\n    const auto h = mesh.halfedge(facet);\n    triangles.push_back(Triangle(mesh.point(mesh.source(h)), mesh.point(mesh.source(mesh.next(h))), mesh.point(mesh.source(mesh.next(mesh.next(h))))));\n  }\n  centroid = CGAL::centroid(triangles.begin(), triangles.end(), CGAL::Dimension_tag<2>());\n}\n\nvoid ComputeCentroidOfSurfaceMesh(const Surface_mesh* input, const Transformation* transformation, emscripten::val emit_normal) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, mesh, CGAL::parameters::all_default());\n  Point centroid;\n  computeCentroidOfSurfaceMesh(centroid, mesh);\n  std::ostringstream x; x << centroid.x().exact(); std::string xs = x.str();\n  std::ostringstream y; y << centroid.y().exact(); std::string ys = y.str();\n  std::ostringstream z; z << centroid.z().exact(); std::string zs = z.str();\n  emit_normal(CGAL::to_double(centroid.x().exact()), CGAL::to_double(centroid.y().exact()), CGAL::to_double(centroid.z().exact()), xs, ys, zs);\n}\n\nvoid computeNormalOfSurfaceMesh(Vector& normal, const Surface_mesh& mesh) {\n  std::vector<Triangle> triangles;\n  for (const auto& facet : mesh.faces()) {\n    if (mesh.is_removed(facet)) {\n      continue;\n    }\n    const auto h = mesh.halfedge(facet);\n    triangles.push_back(Triangle(mesh.point(mesh.source(h)), mesh.point(mesh.source(mesh.next(h))), mesh.point(mesh.source(mesh.next(mesh.next(h))))));\n  }\n  Plane plane;\n  linear_least_squares_fitting_3(triangles.begin(), triangles.end(), plane, CGAL::Dimension_tag<2>());\n  normal = plane.orthogonal_vector();\n  if (CGAL::scalar_product(normal, estimateTriangleNormals(triangles)) < 0) {\n    normal = -normal;\n  }\n}\n\nvoid ComputeNormalOfSurfaceMesh(const Surface_mesh* input, const Transformation* transformation, emscripten::val emit_normal) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, mesh, CGAL::parameters::all_default());\n  Vector normal;\n  computeNormalOfSurfaceMesh(normal, mesh);\n  std::ostringstream x; x << normal.x().exact(); std::string xs = x.str();\n  std::ostringstream y; y << normal.y().exact(); std::string ys = y.str();\n  std::ostringstream z; z << normal.z().exact(); std::string zs = z.str();\n  emit_normal(CGAL::to_double(normal.x().exact()), CGAL::to_double(normal.y().exact()), CGAL::to_double(normal.z().exact()), xs, ys, zs);\n}\n\nconst Surface_mesh* ExtrusionOfSurfaceMesh(const Surface_mesh* input, const Transformation* transformation, double height, double depth, emscripten::val fill_normal) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, mesh, CGAL::parameters::all_default());\n\n  // Default to a vertical extrusion.\n  Vector normal;\n\n  // Infer a normal from the best-fit plane of the mesh.\n  if (!admitVector(normal, fill_normal)) {\n    CGAL::Polygon_mesh_processing::triangulate_faces(mesh);\n    computeNormalOfSurfaceMesh(normal, mesh);\n  }\n\n  Vector up;\n  Vector down;\n  // Could we precisely align with z-up, extrude, and then realign?\n  // Probably not, since if we could, we wouldn't need to.\n  if (normal.direction() == Vector(0, 0, 1).direction()) {\n    // Handle vertical extrusion precisely.\n    up = Vector(0, 0, 1) * height;\n    down = Vector(0, 0, 1) * depth;\n  } else if (normal.direction() == Vector(0, 0, -1).direction()) {\n    // Handle vertical extrusion precisely.\n    up = Vector(0, 0, -1) * height;\n    down = Vector(0, 0, -1) * depth;\n  } else if (normal.direction() == Vector(0, 1, 0).direction()) {\n    // Handle vertical extrusion precisely.\n    up = Vector(0, 1, 0) * height;\n    down = Vector(0, 1, 0) * depth;\n  } else if (normal.direction() == Vector(0, -1, 0).direction()) {\n    // Handle vertical extrusion precisely.\n    up = Vector(0, -1, 0) * height;\n    down = Vector(0, -1, 0) * depth;\n  } else if (normal.direction() == Vector(1, 0, 0).direction()) {\n    // Handle vertical extrusion precisely.\n    up = Vector(1, 0, 0) * height;\n    down = Vector(1, 0, 0) * depth;\n  } else if (normal.direction() == Vector(-1, 0, 0).direction()) {\n    // Handle vertical extrusion precisely.\n    up = Vector(-1, 0, 0) * height;\n    down = Vector(-1, 0, 0) * depth;\n  } else {\n    // Generally we need a unit normal, unfortunately this requires an approximation.\n    double length = sqrt(CGAL::to_double(normal.squared_length()));\n    up = normal * (height / length);\n    down = normal * (depth / length);\n  }\n\n  Surface_mesh* extruded_mesh = new Surface_mesh();\n\n  typedef typename boost::property_map<Surface_mesh, CGAL::vertex_point_t>::type VPMap;\n  Project<VPMap> top(get(CGAL::vertex_point, *extruded_mesh), up);\n  Project<VPMap> bottom(get(CGAL::vertex_point, *extruded_mesh), down);\n  CGAL::Polygon_mesh_processing::extrude_mesh(mesh, *extruded_mesh, bottom, top);\n  return extruded_mesh;\n}\n\ntemplate<typename MAP>\nstruct ProjectToPlane\n{\n  ProjectToPlane(MAP map, Vector vector, Plane plane): map(map), vector(vector), plane(plane) {}\n\n  template<typename VD, typename T>\n  void operator()(const T&, VD vd) const\n  {\n    Line line(get(map, vd), vector);\n    auto result = CGAL::intersection(Line(get(map, vd), vector), plane);\n    if (result) {\n      if (Point* point = boost::get<Point>(&*result)) {\n        put(map, vd, *point);\n      }\n    }\n  }\n\n  MAP map;\n  Vector vector;\n  Plane plane;\n};\n\nconst Surface_mesh* ExtrusionToPlaneOfSurfaceMesh(\n    const Surface_mesh* input,\n    const Transformation* transformation,\n    double high_x, double high_y, double high_z,\n    double high_plane_x, double high_plane_y, double high_plane_z,\n    double high_plane_w, double low_x, double low_y, double low_z,\n    double low_plane_x, double low_plane_y, double low_plane_z, double low_plane_w) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, mesh, CGAL::parameters::all_default());\n  \n  Surface_mesh* extruded_mesh = new Surface_mesh();\n\n  typedef typename boost::property_map<Surface_mesh, CGAL::vertex_point_t>::type VPMap;\n  ProjectToPlane<VPMap> top(get(CGAL::vertex_point, *extruded_mesh), Vector(high_x, high_y, high_z), Plane(high_plane_x, high_plane_y, high_plane_z, high_plane_w));\n  ProjectToPlane<VPMap> bottom(get(CGAL::vertex_point, *extruded_mesh), Vector(low_x, low_y, low_z), Plane(low_plane_x, low_plane_y, low_plane_z, low_plane_w));\n\n  CGAL::Polygon_mesh_processing::extrude_mesh(mesh, *extruded_mesh, bottom, top);\n\n  return extruded_mesh;\n}\n\nconst Surface_mesh::Vertex_index ensureVertex(Surface_mesh& mesh, std::map<Point, Vertex_index>& vertices, const Point& point) {\n  auto it = vertices.find(point);\n  if (it == vertices.end()) {\n    Surface_mesh::Vertex_index new_vertex = mesh.add_vertex(point);\n    vertices[point] = new_vertex;\n    return new_vertex;\n  }\n  return it->second;\n}\n\nvoid convertArrangementToPolygonsWithHoles(const Arrangement_2& arrangement, std::vector<Polygon_with_holes_2>& out) {\n  std::queue<Arrangement_2::Face_const_handle> undecided;\n  CGAL::Unique_hash_map<Arrangement_2::Face_const_handle, bool> positive_faces;\n  CGAL::Unique_hash_map<Arrangement_2::Face_const_handle, bool> negative_faces;\n\n  for (Arrangement_2::Face_const_iterator face = arrangement.faces_begin(); face != arrangement.faces_end(); ++face) {\n    if (!face->has_outer_ccb()) {\n      negative_faces[face] = true;\n    } else {\n      undecided.push(face);\n    }\n  }\n\n  while (!undecided.empty()) {\n    Arrangement_2::Face_const_handle face = undecided.front();\n    undecided.pop();\n    if (positive_faces[face]) {\n      for (Arrangement_2::Hole_const_iterator hole = face->holes_begin(); hole != face->holes_end(); ++hole) {\n        positive_faces[(*hole)->twin()->face()] = false;\n        negative_faces[(*hole)->twin()->face()] = true;\n      }\n      continue;\n    }\n    if (negative_faces[face]) {\n      for (Arrangement_2::Hole_const_iterator hole = face->holes_begin(); hole != face->holes_end(); ++hole) {\n        positive_faces[(*hole)->twin()->face()] = true;\n        negative_faces[(*hole)->twin()->face()] = false;\n      }\n      continue;\n    }\n    bool decided = false;\n    Arrangement_2::Ccb_halfedge_const_circulator start = face->outer_ccb();\n    Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n    do {\n      if (negative_faces[edge->twin()->face()]) {\n        positive_faces[face] = true;\n        negative_faces[face] = false;\n        decided = true;\n        break;\n      }\n    } while (++edge != start);\n    if (!decided) {\n      edge = start;\n      do {\n        if (positive_faces[edge->twin()->face()]) {\n          positive_faces[face] = false;\n          negative_faces[face] = true;\n          decided = true;\n          break;\n        }\n      } while (++edge != start);\n    }\n    undecided.push(face);\n  }\n\n  for (Arrangement_2::Face_const_iterator face = arrangement.faces_begin(); face != arrangement.faces_end(); ++face) {\n    if (!positive_faces[face]) {\n      continue;\n    }\n    Polygon_2 polygon_boundary;\n\n    Arrangement_2::Ccb_halfedge_const_circulator start = face->outer_ccb();\n    Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n    do {\n      if (edge->source()->point() == edge->target()->point()) {\n        // Skip zero length edges.\n        continue;\n      }\n      polygon_boundary.push_back(edge->source()->point());\n    } while (++edge != start);\n\n    std::vector<Polygon_2> polygon_holes;\n    for (Arrangement_2::Hole_const_iterator hole = face->holes_begin(); hole != face->holes_end(); ++hole) {\n      Polygon_2 polygon_hole;\n      Arrangement_2::Ccb_halfedge_const_circulator start = *hole;\n      Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n      do {\n        if (edge->source()->point() == edge->target()->point()) {\n          // Skip zero length edges.\n          continue;\n        }\n        polygon_hole.push_back(edge->source()->point());\n      } while (++edge != start);\n\n      if (polygon_hole.orientation() == CGAL::Sign::POSITIVE) {\n        polygon_hole.reverse_orientation();\n      }\n      polygon_holes.push_back(polygon_hole);\n    }\n    out.push_back(Polygon_with_holes_2(polygon_boundary, polygon_holes.begin(), polygon_holes.end()));\n  }\n}\n\nvoid PlanarSurfaceMeshToPolygonSet(const Plane& plane, const Surface_mesh& mesh, General_polygon_set_2& set) {\n  typedef CGAL::Arr_segment_traits_2<Kernel>            Traits_2;\n  typedef Traits_2::Point_2                             Point_2;\n  typedef Traits_2::X_monotone_curve_2                  Segment_2;\n  typedef CGAL::Arrangement_2<Traits_2>                 Arrangement_2;\n  typedef Arrangement_2::Vertex_handle                  Vertex_handle;\n  typedef Arrangement_2::Halfedge_handle                Halfedge_handle;\n\n  Arrangement_2 arrangement;\n\n  std::set<std::vector<Kernel::FT>> segments;\n\n  // Construct the border.\n  for (const Surface_mesh::Edge_index edge : mesh.edges()) {\n    if (!mesh.is_border(edge)) {\n      continue;\n    }\n    Segment_2 segment {\n          plane.to_2d(mesh.point(mesh.source(mesh.halfedge(edge)))),\n          plane.to_2d(mesh.point(mesh.target(mesh.halfedge(edge))))\n        };\n    insert(arrangement, segment);\n  }\n\n  std::vector<Polygon_with_holes_2> polygons;\n  convertArrangementToPolygonsWithHoles(arrangement, polygons);\n  for (const auto& polygon : polygons) {\n    set.join(polygon);\n  }\n}\n\n// This handles potentially overlapping facets.\nvoid PlanarSurfaceMeshFacetsToPolygonSet(const Plane& plane, const Surface_mesh& mesh, General_polygon_set_2& set) {\n  typedef CGAL::Arr_segment_traits_2<Kernel>            Traits_2;\n  typedef Traits_2::Point_2                             Point_2;\n  typedef Traits_2::X_monotone_curve_2                  Segment_2;\n  typedef CGAL::Arrangement_2<Traits_2>                 Arrangement_2;\n  typedef Arrangement_2::Vertex_handle                  Vertex_handle;\n  typedef Arrangement_2::Halfedge_handle                Halfedge_handle;\n\n  std::set<std::vector<Kernel::FT>> segments;\n\n  for (const auto& facet : mesh.faces()) {\n    const auto& start = mesh.halfedge(facet);\n    if (mesh.is_removed(start)) {\n      continue;\n    }\n    // Do we really need an arrangement here?\n    Arrangement_2 arrangement;\n    Halfedge_index edge = start;\n    do {\n      Segment_2 segment {\n            plane.to_2d(mesh.point(mesh.source(edge))),\n            plane.to_2d(mesh.point(mesh.target(edge)))\n          };\n      insert(arrangement, segment);\n      edge = mesh.next(edge);\n    } while (edge != start);\n    // The arrangement shouldn't produce polygons with holes, so this might be simplified.\n    std::vector<Polygon_with_holes_2> polygons;\n    convertArrangementToPolygonsWithHoles(arrangement, polygons);\n    for (const auto& polygon : polygons) {\n      set.join(polygon);\n    }\n  }\n}\n\nbool IsPlanarSurfaceMesh(Plane& plane, const Surface_mesh& a) {\n  if (CGAL::is_closed(a)) return false;\n  if (a.number_of_vertices() < 3) return false;\n  if (!SomePlaneOfSurfaceMesh(plane, a)) return false;\n  for (const auto& vertex : a.vertices()) {\n    if (!plane.has_on(a.point(vertex))) return false;\n  }\n  return true;\n}\n\nbool IsCoplanarSurfaceMesh(Plane& plane, const Surface_mesh& a) {\n  if (CGAL::is_closed(a)) return false;\n  if (a.number_of_vertices() < 3) return false;\n  for (const auto& vertex : a.vertices()) {\n    if (!plane.has_on(a.point(vertex))) return false;\n  }\n  return true;\n}\n\nconst Surface_mesh* PolygonsWithHolesToSurfaceMesh(const Plane& plane, std::vector<Polygon_with_holes_2>& polygons) {\n  Surface_mesh* c = new Surface_mesh();\n  CGAL::Polygon_triangulation_decomposition_2<Kernel> triangulate;\n  std::map<Point, Vertex_index> vertices;\n  for (const auto& polygon : polygons) {\n    std::vector<Polygon_2> triangles;\n    triangulate(polygon, std::back_inserter(triangles));\n    for (const auto& triangle : triangles) {\n      c->add_face(ensureVertex(*c, vertices, plane.to_3d(triangle[0])),\n                  ensureVertex(*c, vertices, plane.to_3d(triangle[1])),\n                  ensureVertex(*c, vertices, plane.to_3d(triangle[2])));\n    }\n  }\n  return c;\n}\n\nconst Surface_mesh* GeneralPolygonSetToSurfaceMesh(const Plane& plane, General_polygon_set_2& set) {\n  Surface_mesh* c = new Surface_mesh();\n  std::vector<Polygon_with_holes_2> polygons;\n  set.polygons_with_holes(std::back_inserter(polygons));\n  return PolygonsWithHolesToSurfaceMesh(plane, polygons);\n}\n\nconst Surface_mesh* DifferenceOfCoplanarSurfaceMeshes(const Plane& plane, const Surface_mesh* a, const Surface_mesh* b) {\n  General_polygon_set_2 set;\n  General_polygon_set_2 subtract;\n  PlanarSurfaceMeshToPolygonSet(plane, *a, set);\n  PlanarSurfaceMeshToPolygonSet(plane, *b, subtract);\n  set.difference(subtract);\n  return GeneralPolygonSetToSurfaceMesh(plane, set);\n}\n\nconst Surface_mesh* UnionOfCoplanarSurfaceMeshes(const Plane& plane, const Surface_mesh* a, const Surface_mesh* b) {\n  General_polygon_set_2 set;\n  General_polygon_set_2 add;\n  PlanarSurfaceMeshToPolygonSet(plane, *a, set);\n  PlanarSurfaceMeshToPolygonSet(plane, *b, add);\n  set.join(add);\n  return GeneralPolygonSetToSurfaceMesh(plane, set);\n}\n\nconst Surface_mesh* IntersectionOfCoplanarSurfaceMeshes(const Plane& plane, const Surface_mesh* a, const Surface_mesh* b) {\n  General_polygon_set_2 set;\n  General_polygon_set_2 clip;\n  PlanarSurfaceMeshToPolygonSet(plane, *a, set);\n  PlanarSurfaceMeshToPolygonSet(plane, *b, clip);\n  set.intersection(clip);\n  return GeneralPolygonSetToSurfaceMesh(plane, set);\n}\n\nvoid SurfaceMeshSectionToPolygonSet(const Plane& plane, const Surface_mesh& a, General_polygon_set_2& set) {\n  typedef std::vector<Point> Polyline_type;\n  typedef std::list<Polyline_type> Polylines;\n  CGAL::Polygon_mesh_slicer<Surface_mesh, Kernel> slicer(a);\n  Polylines polylines;\n  slicer(plane, std::back_inserter(polylines));\n  for (const auto& polyline : polylines) {\n    std::size_t length = polyline.size();\n    if (length < 3 || polyline.front() != polyline.back()) {\n      continue;\n    }\n    Polygon_2 polygon;\n    // Skip the duplicated last point in the polyline.\n    for (std::size_t nth = 0; nth < length - 1; nth++) {\n      polygon.push_back(plane.to_2d(polyline[nth]));\n    }\n    if (polygon.orientation() == CGAL::Sign::NEGATIVE) {\n      polygon.reverse_orientation();\n    }\n    set.join(polygon);\n  }\n}\n\nconst double kExtrusionMinimum = 10000.0;\nconst double kExtrusionMinimumSquared = kExtrusionMinimum * kExtrusionMinimum;\n\nconst double kIota = 10e-5;\n\nconst Surface_mesh* DifferenceOfSurfaceMeshes(const Surface_mesh* a, const Transformation* a_transform, const Surface_mesh* b, const Transformation* b_transform) {\n  if (a_transform) {\n    Surface_mesh transformed(*a);\n    CGAL::Polygon_mesh_processing::transform(*a_transform, transformed, CGAL::parameters::all_default());\n    return DifferenceOfSurfaceMeshes(&transformed, nullptr, b, b_transform);\n  } else if (b_transform) {\n    Surface_mesh transformed(*b);\n    CGAL::Polygon_mesh_processing::transform(*b_transform, transformed, CGAL::parameters::all_default());\n    return DifferenceOfSurfaceMeshes(a, a_transform, &transformed, nullptr);\n  }\n  Plane plane;\n  if (IsPlanarSurfaceMesh(plane, *a)) {\n    if (IsCoplanarSurfaceMesh(plane, *b)) {\n      return DifferenceOfCoplanarSurfaceMeshes(plane, a, b);\n    } else {\n      // Difference with the section of the other.\n      General_polygon_set_2 set;\n      General_polygon_set_2 other;\n      PlanarSurfaceMeshToPolygonSet(plane, *a, set);\n      SurfaceMeshSectionToPolygonSet(plane, *b, other);\n      set.difference(other);\n      return GeneralPolygonSetToSurfaceMesh(plane, set);\n    }\n  } else if (IsPlanarSurfaceMesh(plane, *b)) {\n    return a;\n  }\n  double x = 0, y = 0, z = 0;\n  Surface_mesh* c = new Surface_mesh();\n  for (int shift = 0x11; ; shift++) {\n    Surface_mesh working_a(*a);\n    Surface_mesh working_b(*b);\n    if (x != 0 || y != 0 || z != 0) {\n      std::cout << \"Note: Shifting difference by x=\" << x << \" y=\" << y << \" z=\" << z << std::endl;\n      Transformation translation(CGAL::TRANSLATION, Vector(x, y, z));\n      CGAL::Polygon_mesh_processing::transform(translation, working_b, CGAL::parameters::all_default());\n    }\n    if (CGAL::Polygon_mesh_processing::corefine_and_compute_difference(\n        working_a, working_b, *c,\n        CGAL::Polygon_mesh_processing::parameters::throw_on_self_intersection(true),\n        CGAL::Polygon_mesh_processing::parameters::throw_on_self_intersection(true),\n        CGAL::Polygon_mesh_processing::parameters::throw_on_self_intersection(true))) {\n      return c;\n    }\n    const double direction = ((shift & (1 << 3)) ? -1 : 1) * (shift >> 4);\n    if (shift & (1 << 0)) {\n      x = kIota * direction;\n    } else {\n      x = 0;\n    }\n    if (shift & (1 << 1)) {\n      y = kIota * direction;\n    } else {\n      y = 0;\n    }\n    if (shift & (1 << 2)) {\n      z = kIota * direction;\n    } else {\n      z = 0;\n    }\n  }\n}\n\nconst Surface_mesh* IntersectionOfSurfaceMeshes(const Surface_mesh* a, const Transformation* a_transform, const Surface_mesh* b, const Transformation* b_transform) {\n  if (a_transform) {\n    Surface_mesh transformed(*a);\n    CGAL::Polygon_mesh_processing::transform(*a_transform, transformed, CGAL::parameters::all_default());\n    return IntersectionOfSurfaceMeshes(&transformed, nullptr, b, b_transform);\n  } else if (b_transform) {\n    Surface_mesh transformed(*b);\n    CGAL::Polygon_mesh_processing::transform(*b_transform, transformed, CGAL::parameters::all_default());\n    return IntersectionOfSurfaceMeshes(a, a_transform, &transformed, nullptr);\n  }\n  Plane plane;\n  if (IsPlanarSurfaceMesh(plane, *a)) {\n    if (IsCoplanarSurfaceMesh(plane, *b)) {\n      return IntersectionOfCoplanarSurfaceMeshes(plane, a, b);\n    } else {\n      // Difference with the section of the other.\n      General_polygon_set_2 set;\n      General_polygon_set_2 other;\n      PlanarSurfaceMeshToPolygonSet(plane, *a, set);\n      SurfaceMeshSectionToPolygonSet(plane, *b, other);\n      set.intersection(other);\n      return GeneralPolygonSetToSurfaceMesh(plane, set);\n    }\n  } else if (IsPlanarSurfaceMesh(plane, *b)) {\n    return new Surface_mesh();\n  }\n  double x = 0, y = 0, z = 0;\n  Surface_mesh* c = new Surface_mesh();\n  for (int shift = 0x11; ; shift++) {\n    Surface_mesh working_a(*a);\n    Surface_mesh working_b(*b);\n    if (x != 0 || y != 0 || z != 0) {\n      std::cout << \"Note: Shifting intersection x=\" << x << \" y=\" << y << \" z=\" << z << std::endl;\n      Transformation translation(CGAL::TRANSLATION, Vector(x, y, z));\n      CGAL::Polygon_mesh_processing::transform(translation, working_b, CGAL::parameters::all_default());\n    }\n    if (CGAL::Polygon_mesh_processing::corefine_and_compute_intersection(\n        working_a, working_b, *c,\n        CGAL::Polygon_mesh_processing::parameters::throw_on_self_intersection(true),\n        CGAL::Polygon_mesh_processing::parameters::throw_on_self_intersection(true),\n        CGAL::Polygon_mesh_processing::parameters::throw_on_self_intersection(true))) {\n      return c;\n    }\n    const double direction = ((shift & (1 << 3)) ? -1 : 1) * (shift >> 4);\n    if (shift & (1 << 0)) {\n      x = kIota * direction;\n    } else {\n      x = 0;\n    }\n    if (shift & (1 << 1)) {\n      y = kIota * direction;\n    } else {\n      y = 0;\n    }\n    if (shift & (1 << 2)) {\n      z = kIota * direction;\n    } else {\n      z = 0;\n    }\n  }\n}\n\nconst Surface_mesh* UnionOfSurfaceMeshes(const Surface_mesh* a, const Transformation* a_transform, const Surface_mesh* b, const Transformation* b_transform) {\n  if (a_transform) {\n    Surface_mesh transformed(*a);\n    CGAL::Polygon_mesh_processing::transform(*a_transform, transformed, CGAL::parameters::all_default());\n    return UnionOfSurfaceMeshes(&transformed, nullptr, b, b_transform);\n  } else if (b_transform) {\n    Surface_mesh transformed(*b);\n    CGAL::Polygon_mesh_processing::transform(*b_transform, transformed, CGAL::parameters::all_default());\n    return UnionOfSurfaceMeshes(a, a_transform, &transformed, nullptr);\n  }\n  Plane plane;\n  if (IsPlanarSurfaceMesh(plane, *a)) {\n    if (IsCoplanarSurfaceMesh(plane, *b)) {\n      return UnionOfCoplanarSurfaceMeshes(plane, a, b);\n    } else {\n      // Difference with the section of the other.\n      General_polygon_set_2 set;\n      General_polygon_set_2 other;\n      PlanarSurfaceMeshToPolygonSet(plane, *a, set);\n      SurfaceMeshSectionToPolygonSet(plane, *b, other);\n      set.join(other);\n      return GeneralPolygonSetToSurfaceMesh(plane, set);\n    }\n  } else if (IsPlanarSurfaceMesh(plane, *b)) {\n    return a;\n  }\n  double x = 0, y = 0, z = 0;\n  Surface_mesh* c = new Surface_mesh();\n  for (int shift = 0x11; ; shift++) {\n    Surface_mesh working_a(*a);\n    Surface_mesh working_b(*b);\n    if (x != 0 || y != 0 || z != 0) {\n      std::cout << \"Note: Shifting union by x=\" << x << \" y=\" << y << \" z=\" << z << std::endl;\n      Transformation translation(CGAL::TRANSLATION, Vector(x, y, z));\n      CGAL::Polygon_mesh_processing::transform(translation, working_b, CGAL::parameters::all_default());\n    }\n    if (CGAL::Polygon_mesh_processing::corefine_and_compute_union(\n        working_a, working_b, *c,\n        CGAL::Polygon_mesh_processing::parameters::throw_on_self_intersection(true),\n        CGAL::Polygon_mesh_processing::parameters::throw_on_self_intersection(true),\n        CGAL::Polygon_mesh_processing::parameters::throw_on_self_intersection(true))) {\n      return c;\n    }\n    const double direction = ((shift & (1 << 3)) ? -1 : 1) * (shift >> 4);\n    if (shift & (1 << 0)) {\n      x = kIota * direction;\n    } else {\n      x = 0;\n    }\n    if (shift & (1 << 1)) {\n      y = kIota * direction;\n    } else {\n      y = 0;\n    }\n    if (shift & (1 << 2)) {\n      z = kIota * direction;\n    } else {\n      z = 0;\n    }\n  }\n}\n\nvoid admitPlane(Plane& plane, emscripten::val fill_plane) {\n  Quadruple q;\n  Quadruple* qp = &q;\n  fill_plane(qp);\n  plane = Plane(q[0], q[1], q[2], q[3]);\n}\n\nbool didAdmitPlane(Plane& plane, emscripten::val fill_plane) {\n  Quadruple q;\n  Quadruple* qp = &q;\n  bool result = fill_plane(qp).as<bool>();\n  if (result) {\n    plane = Plane(q[0], q[1], q[2], q[3]);\n    return true;\n  } else {\n    return false;\n  }\n}\n\n// FIX: The case where we take a section coplanar with a surface with a hole in it.\n// CHECK: Should this produce Polygons_with_holes?\nvoid SectionOfSurfaceMesh(const Surface_mesh* input, const Transformation* transform, std::size_t plane_count, emscripten::val get_transform, emscripten::val emit_mesh, bool profile) {\n  // We could possibly be clever and transform the plane and output?\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, mesh, CGAL::parameters::all_default());\n\n  typedef Traits_2::X_monotone_curve_2 Segment_2;\n  typedef std::vector<Point> Polyline_type;\n  typedef std::list<Polyline_type> Polylines;\n\n  CGAL::Polygon_mesh_slicer<Surface_mesh, Kernel> slicer(mesh);\n\n  bool has_last_gps = false;\n  General_polygon_set_2 last_gps;\n\n  for (std::size_t nth_plane = 0; nth_plane < plane_count; nth_plane++) {\n    Quadruple q;\n    Quadruple* qp =  &q;\n    Plane plane(0, 0, 1, 0);\n    const Transformation* section_transform = get_transform(nth_plane).as<const Transformation*>(emscripten::allow_raw_pointers());\n    plane = plane.transform(*section_transform);\n    if (profile) {\n      // We need the 2d forms to be interoperable.\n      plane = unitPlane(plane);\n    }\n    Arrangement_2 arrangement;\n    Polylines polylines;\n    slicer(plane, std::back_inserter(polylines));\n    for (const auto& polyline : polylines) {\n      for (std::size_t nth = 1; nth < polyline.size(); nth++) {\n        Segment_2 segment { plane.to_2d(polyline[nth - 1]), plane.to_2d(polyline[nth]) };\n        insert(arrangement, segment);\n      }\n    }\n    std::vector<Polygon_with_holes_2> polygons;\n    convertArrangementToPolygonsWithHoles(arrangement, polygons);\n\n    if (profile) {\n      // Clip each section to the previous section, allowing overhangs to be eliminated.\n      General_polygon_set_2 this_gps;\n      for (const auto& polygon : polygons) {\n        this_gps.join(polygon);\n      }\n      if (has_last_gps) {\n        this_gps.intersection(last_gps);\n        polygons.clear();\n        this_gps.polygons_with_holes(std::back_inserter(polygons));\n      }\n      last_gps = this_gps;\n      has_last_gps = true;\n    }\n\n    const Surface_mesh* r = PolygonsWithHolesToSurfaceMesh(plane, polygons);\n    emit_mesh(r);\n  }\n}\n\nPlane ensureFacetPlane(Surface_mesh& mesh, std::unordered_map<Face_index, Plane>& facet_to_plane, std::unordered_set<Plane>& planes, Face_index facet) {\n  auto it = facet_to_plane.find(facet);\n  if (it == facet_to_plane.end()) {\n    Plane facet_plane = PlaneOfSurfaceMeshFacet(mesh, facet);\n    // We canonicalize the planes so that the 2d projections match.\n    auto canonical_plane = planes.find(facet_plane);\n    if (canonical_plane == planes.end()) {\n      planes.insert(facet_plane);\n      facet_to_plane[facet] = facet_plane;\n      return facet_plane;\n    } else {\n      facet_to_plane[facet] = *canonical_plane;\n      if (*canonical_plane != facet_plane) {\n        std::cout << \"QQ/ensureFacetPlane/mismatch\" << std::endl;\n      }\n      return *canonical_plane;\n    }\n  } else {\n    return it->second;\n  }\n}\n\nvoid OutlineSurfaceMesh(const Surface_mesh* input, const Transformation* transform, emscripten::val emit_approximate_segment) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, mesh, CGAL::parameters::all_default());\n\n  std::unordered_set<Plane> planes;\n  std::unordered_map<Face_index, Plane> facet_to_plane;\n\n  // FIX: Make this more efficient.\n  for (const auto& facet : mesh.faces()) {\n    const auto& start = mesh.halfedge(facet);\n    if (mesh.is_removed(start)) {\n      continue;\n    }\n    const Plane facet_plane = ensureFacetPlane(mesh, facet_to_plane, planes, facet);\n    Halfedge_index edge = start;\n    do {\n      bool corner = false;\n      const auto& opposite_facet = mesh.face(mesh.opposite(edge));\n      if (opposite_facet == mesh.null_face()) {\n        corner = true;\n      } else {\n        const Plane opposite_facet_plane = ensureFacetPlane(mesh, facet_to_plane, planes, opposite_facet);\n        if (facet_plane != opposite_facet_plane) {\n          corner = true;\n        }\n      }\n      if (corner) {\n        Point s = mesh.point(mesh.source(edge));\n        Point t = mesh.point(mesh.target(edge));\n        emit_approximate_segment(CGAL::to_double(s.x().exact()), CGAL::to_double(s.y().exact()), CGAL::to_double(s.z().exact()), CGAL::to_double(t.x().exact()), CGAL::to_double(t.y().exact()), CGAL::to_double(t.z().exact()));\n      }\n      const auto& next = mesh.next(edge);\n      edge = next;\n    } while (edge != start);\n  }\n}\n\nconst Surface_mesh* ProjectionToPlaneOfSurfaceMesh(\n    const Surface_mesh* input,\n    const Transformation* transformation,\n    double direction_x, double direction_y, double direction_z,\n    double plane_x, double plane_y, double plane_z, double plane_w) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transformation, mesh, CGAL::parameters::all_default());\n\n  Surface_mesh* projected_mesh = new Surface_mesh(mesh);\n  auto& input_map = mesh.points();\n  auto& output_map = projected_mesh->points();\n\n  Plane plane(plane_x, plane_y, plane_z, plane_w);\n  Vector vector(direction_x, direction_y, direction_z);\n\n  // Squash the mesh.\n  for (auto& vertex : mesh.vertices()) {\n    auto result = CGAL::intersection(Line(get(input_map, vertex), get(input_map, vertex) + vector), plane);\n    if (result) {\n      if (Point* point = boost::get<Point>(&*result)) {\n        put(output_map, vertex, *point);\n      }\n    }\n  }\n\n  // Simplify the projection.\n  General_polygon_set_2 set;\n  PlanarSurfaceMeshFacetsToPolygonSet(plane, *projected_mesh, set);\n  return GeneralPolygonSetToSurfaceMesh(plane, set);\n}\n\nvoid WireframeSurfaceMesh(const Surface_mesh* input, const Transformation* transform, emscripten::val emit_approximate_segment) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, mesh, CGAL::parameters::all_default());\n\n  for (const auto& edge : mesh.edges()) {\n    if (mesh.is_removed(edge)) {\n      continue;\n    }\n    const auto& halfedge = mesh.halfedge(edge);\n    Point s = mesh.point(mesh.source(halfedge));\n    Point t = mesh.point(mesh.target(halfedge));\n    emit_approximate_segment(CGAL::to_double(s.x().exact()), CGAL::to_double(s.y().exact()), CGAL::to_double(s.z().exact()),\n                             CGAL::to_double(t.x().exact()), CGAL::to_double(t.y().exact()), CGAL::to_double(t.z().exact()));\n  }\n}\n\ndouble FT__to_double(const FT& ft) {\n  return CGAL::to_double(ft);\n}\n\nclass Surface_mesh_explorer {\n public:\n  Surface_mesh_explorer(emscripten::val& emit_point, emscripten::val& emit_edge, emscripten::val& emit_face)\n    : emit_point_(emit_point), emit_edge_(emit_edge), emit_face_(emit_face) {}\n\n  std::map<std::int32_t, std::int32_t> facet_to_face;\n\n  const std::int32_t mapFacetToFace(std::int32_t facet) {\n    std::int32_t face = (std::int32_t)facet;\n    std::set<std::int32_t> seen;\n    for (;;) {\n      seen.insert(face);\n      std::int32_t next_face = facet_to_face[face];\n      if (next_face == face) {\n        break;\n      }\n      if (seen.find(next_face) != seen.end()) {\n        // This should be impossible.\n        std::cout << \"EE/m/cycle\" << std::endl;\n        return face;\n      }\n      face = next_face;\n    }\n    return face;\n  }\n\n  void Explore(const Surface_mesh& mesh) {\n    // Publish the vertices.\n    for (const auto& vertex : mesh.vertices()) {\n      if (mesh.is_removed(vertex)) {\n        continue;\n      }\n      const auto& p = mesh.point(vertex);\n      std::ostringstream x; x << p.x().exact(); std::string xs = x.str();\n      std::ostringstream y; y << p.y().exact(); std::string ys = y.str();\n      std::ostringstream z; z << p.z().exact(); std::string zs = z.str();\n      emit_point_((std::int32_t)vertex, CGAL::to_double(p.x().exact()), CGAL::to_double(p.y().exact()), CGAL::to_double(p.z().exact()),\n                  xs, ys, zs);\n    }\n\n    facet_to_face[mesh.null_face()] = -1;\n\n    for (const auto& facet : mesh.faces()) {\n      // Initially each facet is an individual face.\n      facet_to_face[(std::int32_t)facet] = (std::int32_t)facet;\n    }\n\n    // FIX: Make this more efficient.\n    for (const auto& facet : mesh.faces()) {\n      const auto& start = mesh.halfedge(facet);\n      if (mesh.is_removed(start)) {\n        continue;\n      }\n      const Plane facet_plane = PlaneOfSurfaceMeshFacet(mesh, facet);\n      std::int32_t face = mapFacetToFace(facet);\n      Halfedge_index edge = start;\n      do {\n        const auto& opposite_facet = mesh.face(mesh.opposite(edge));\n        if (opposite_facet != mesh.null_face()) {\n          const Plane opposite_facet_plane = PlaneOfSurfaceMeshFacet(mesh, opposite_facet);\n          if (facet_plane == opposite_facet_plane) {\n            std::int32_t opposite_face = mapFacetToFace(opposite_facet);\n            if (opposite_face < face) {\n              facet_to_face[face] = opposite_face;\n              face = opposite_face;\n            } else {\n              facet_to_face[opposite_face] = face;\n            }\n          } else {\n          }\n        }\n        const auto& next = mesh.next(edge);\n        edge = next;\n      } while (edge != start);\n    }\n\n    std::map<std::int32_t, Surface_mesh::Vertex_index> facet_to_vertex;\n\n    // Publish the half-edges.\n    for (const auto& edge : mesh.halfedges()) {\n      if (mesh.is_removed(edge)) {\n        continue;\n      }\n      const auto& next = mesh.next(edge);\n      const auto& source = mesh.source(edge);\n      const auto& opposite = mesh.opposite(edge);\n      const auto& facet = mesh.face(edge);\n      facet_to_vertex[facet] = source;\n      std::int32_t face = mapFacetToFace(facet);\n      emit_edge_((std::int32_t)edge,\n                 (std::int32_t)source,\n                 (std::int32_t)next,\n                 (std::int32_t)opposite,\n                 (std::int32_t)facet,\n                 (std::int32_t)face,\n                 face);\n    }\n\n    // Publish the faces.\n    for (const auto& entry : facet_to_face) {\n      const auto& facet = entry.first;\n      const auto& face = entry.second;\n      if (face == -1 || facet != face) {\n        continue;\n      }\n      const Plane plane = PlaneOfSurfaceMeshFacet(mesh, Surface_mesh::Face_index(facet));\n      const auto a = plane.a().exact();\n      const auto b = plane.b().exact();\n      const auto c = plane.c().exact();\n      const auto d = plane.d().exact();\n      std::ostringstream x; x << a; std::string xs = x.str();\n      std::ostringstream y; y << b; std::string ys = y.str();\n      std::ostringstream z; z << c; std::string zs = z.str();\n      std::ostringstream w; w << d; std::string ws = w.str();\n      const double xd = CGAL::to_double(a);\n      const double yd = CGAL::to_double(b);\n      const double zd = CGAL::to_double(c);\n      const double ld = std::sqrt(xd * xd + yd * yd + zd * zd);\n      const double wd = CGAL::to_double(d);\n      // Normalize the approximate plane normal.\n      emit_face_(facet, xd / ld, yd / ld, zd / ld, wd, xs, ys, zs, ws);\n    }\n  }\n\n private:\n  emscripten::val& emit_point_;\n  emscripten::val& emit_edge_;\n  emscripten::val& emit_face_;\n};\n\nvoid Surface_mesh__explore(const Surface_mesh* mesh, emscripten::val emit_point, emscripten::val emit_edge, emscripten::val emit_face) {\n  Surface_mesh_explorer explorer(emit_point, emit_edge, emit_face);\n  explorer.Explore(*mesh);\n}\n\nstd::string SerializeSurfaceMesh(const Surface_mesh* mesh) {\n  // CHECK: We assume the mesh is compact.\n\n  std::ostringstream s;\n  // stream << *mesh;\n\n  s << mesh->number_of_vertices() << \"\\n\";\n  for (const Vertex_index vertex : mesh->vertices()) {\n    const Point& p = mesh->point(vertex);\n    s << p.x().exact() << \" \" << p.y().exact() << \" \" << p.z().exact() << \"\\n\";\n  }\n  s << \"\\n\";\n\n  s << mesh->number_of_faces() << \"\\n\";\n  for (const Face_index facet : mesh->faces()) {\n    const auto& start = mesh->halfedge(facet);\n    std::size_t edge_count = 0;\n    {\n      Halfedge_index edge = start;\n      do {\n        edge_count++;\n        edge = mesh->next(edge);\n      } while (edge != start);\n    }\n    s << edge_count;\n    {\n      Halfedge_index edge = start;\n      do {\n        s << \" \" << std::size_t(mesh->source(edge));\n        edge = mesh->next(edge);\n      } while (edge != start);\n    }\n    s << \"\\n\";\n  }\n\n  return s.str();\n}\n\nconst Surface_mesh* DeserializeSurfaceMesh(std::string serialization) {\n  Surface_mesh* mesh = new Surface_mesh();\n  std::istringstream s(serialization);\n\n  std::size_t number_of_vertices;\n\n  s >> number_of_vertices;\n\n  for (std::size_t vertex = 0; vertex < number_of_vertices; vertex++) {\n    FT x;\n    s >> x;\n\n    FT y;\n    s >> y;\n\n    FT z;\n    s >> z;\n\n    mesh->add_vertex(Point{ x, y, z });\n  }\n\n  std::size_t number_of_facets;\n\n  s >> number_of_facets;\n\n  for (std::size_t facet = 0; facet < number_of_facets; facet++) {\n    std::size_t number_of_vertices;\n    s >> number_of_vertices;\n    std::vector<Vertex_index> vertices;\n    for (std::size_t nth = 0; nth < number_of_vertices; nth++) {\n      std::size_t vertex;\n      s >> vertex;\n\n      vertices.push_back(Vertex_index(vertex));\n    }\n    mesh->add_face(vertices);\n  }\n\n  return mesh;\n}\n\nbool Surface_mesh__triangulate_faces(Surface_mesh *mesh) {\n  return CGAL::Polygon_mesh_processing::triangulate_faces(mesh->faces(), *mesh);\n}\n\nconst Surface_mesh* ComputeConvexHullAsSurfaceMesh(emscripten::val fill) {\n  Points points;\n  Points* points_ptr = &points;\n  fill(points_ptr);\n  Surface_mesh* mesh = new Surface_mesh();\n  // compute convex hull of non-collinear points\n  CGAL::convex_hull_3(points.begin(), points.end(), *mesh);\n  return mesh;\n}\n\nconst Surface_mesh* ComputeAlphaShapeAsSurfaceMesh(int component_limit, emscripten::val fill) {\n  typedef CGAL::Alpha_shape_vertex_base_3<Kernel>      Vb;\n  typedef CGAL::Alpha_shape_cell_base_3<Kernel>        Fb;\n  typedef CGAL::Triangulation_data_structure_3<Vb,Fb>  Tds;\n  typedef CGAL::Delaunay_triangulation_3<Kernel,Tds>   Triangulation_3;\n  typedef CGAL::Alpha_shape_3<Triangulation_3>         Alpha_shape_3;\n  typedef Kernel::Point_3                              Point;\n  typedef Alpha_shape_3::Alpha_iterator                Alpha_iterator;\n\n  Points points;\n  Points* points_ptr = &points;\n  fill(points_ptr);\n  Alpha_shape_3 alpha_shape(points.begin(), points.end());\n  Alpha_iterator optimizer = alpha_shape.find_optimal_alpha(component_limit);\n  alpha_shape.set_alpha(*optimizer);\n\n  Surface_mesh* mesh = new Surface_mesh();\n\n  std::vector<Alpha_shape_3::Facet > Facets;\n  alpha_shape.get_alpha_shape_facets(std::back_inserter(Facets), Alpha_shape_3::REGULAR);\n  for (auto i = 0; i < Facets.size(); i++) {\n    //checks for exterior cells\n    if (alpha_shape.classify(Facets[i].first) != Alpha_shape_3::EXTERIOR) {\n      Facets[i] = alpha_shape.mirror_facet(Facets[i]);\n    }\n\n    CGAL_assertion(alpha_shape.classify(Facets[i].first) == Alpha_shape_3::EXTERIOR);\n\n    // gets indices of alpha shape and gets consistent orientation\n    int indices[3] = { (Facets[i].second + 1) % 4, (Facets[i].second + 2) % 4, (Facets[i].second + 3) % 4 };\n    if (Facets[i].second % 2 == 0) {\n      std::swap(indices[0], indices[1]);\n    }\n\n    // adds data to cgal mesh\n    for (auto j = 0; j < 3; ++j) {\n      mesh->add_vertex(Facets[i].first->vertex(indices[j])->point());\n    }\n    auto v0 = static_cast<boost::graph_traits<Surface_mesh>::vertex_descriptor>(3 * i);\n    auto v1 = static_cast<boost::graph_traits<Surface_mesh>::vertex_descriptor>(3 * i + 1);\n    auto v2 = static_cast<boost::graph_traits<Surface_mesh>::vertex_descriptor>(3 * i + 2);\n    mesh->add_face(v0, v1, v2);\n  }\n\n  return mesh;\n}\n\nvoid ComputeAlphaShape2AsPolygonSegments(size_t component_limit, double alpha, bool regularized, emscripten::val fill, emscripten::val emit) {\n  typedef CGAL::Alpha_shape_vertex_base_2<Kernel>                    VertexBase;\n  typedef CGAL::Alpha_shape_face_base_2<Kernel>                      FaceBase;\n  typedef CGAL::Triangulation_data_structure_2<VertexBase, FaceBase> TriangulationData;\n  typedef CGAL::Delaunay_triangulation_2<Kernel, TriangulationData>  Triangulation_2;\n  typedef CGAL::Alpha_shape_2<Triangulation_2>                       Alpha_shape_2;\n  typedef Alpha_shape_2::Alpha_shape_edges_iterator                  Alpha_shape_edges_iterator;\n\n  Point_2s points;\n  Point_2s* points_ptr = &points;\n  fill(points_ptr);\n\n  Alpha_shape_2 alpha_shape(points.begin(), points.end(), FT(alpha), regularized ? Alpha_shape_2::REGULARIZED : Alpha_shape_2::GENERAL);\n\n  if (component_limit > 0) {\n    auto optimizer = alpha_shape.find_optimal_alpha(component_limit);\n    alpha_shape.set_alpha(*optimizer);\n  }\n\n  Alpha_shape_edges_iterator it;\n  for (it = alpha_shape.alpha_shape_edges_begin(); it != alpha_shape.alpha_shape_edges_end(); ++it) {\n    const auto& segment = alpha_shape.segment(*it);\n    const auto& s = segment.source();\n    const auto& t = segment.target();\n    emit(CGAL::to_double(s.x().exact()), CGAL::to_double(s.y().exact()), CGAL::to_double(t.x().exact()), CGAL::to_double(t.y().exact()));\n  }\n}\n\ntemplate<class Kernel, class Container>\nvoid print_polygon (const CGAL::Polygon_2<Kernel, Container>& P)\n{\n  typename CGAL::Polygon_2<Kernel, Container>::Vertex_const_iterator vit;\n  std::cout << \"[ \" << P.size() << \" vertices:\";\n  for (vit = P.vertices_begin(); vit != P.vertices_end(); ++vit)\n    std::cout << \" (\" << *vit << ')';\n  std::cout << \" ]\" << std::endl;\n}\n\ntemplate<class Kernel, class Container>\nvoid print_polygon_with_holes(const CGAL::Polygon_with_holes_2<Kernel, Container> & pwh)\n{\n  if (! pwh.is_unbounded()) {\n    std::cout << \"{ Outer boundary = \";\n    print_polygon (pwh.outer_boundary());\n  } else\n    std::cout << \"{ Unbounded polygon.\" << std::endl;\n  typename CGAL::Polygon_with_holes_2<Kernel,Container>::Hole_const_iterator hit;\n  unsigned int k = 1;\n  std::cout << \" \" << pwh.number_of_holes() << \" holes:\" << std::endl;\n  for (hit = pwh.holes_begin(); hit != pwh.holes_end(); ++hit, ++k) {\n    std::cout << \" Hole #\" << k << \" = \";\n    print_polygon (*hit);\n  }\n  std::cout << \" }\" << std::endl;\n}\n\nvoid OffsetOfPolygonWithHoles(double initial, double step, double limit, std::size_t hole_count, emscripten::val fill_plane, emscripten::val fill_boundary, emscripten::val fill_hole, emscripten::val emit_polygon, emscripten::val emit_point) {\n  typedef CGAL::Gps_segment_traits_2<Kernel> Traits;\n  Plane plane;\n  admitPlane(plane, fill_plane);\n  plane = unitPlane(plane);\n\n  Polygon_with_holes_2 insetting_boundary;\n  std::vector<Polygon_2> holes;\n\n  for (std::size_t nth = 0; nth < hole_count; nth++) {\n    Points points;\n    Points* points_ptr = &points;\n    fill_hole(points_ptr, nth);\n    Polygon_2 hole;\n    for (const auto& point : points) {\n      hole.push_back(plane.to_2d(point));\n    }\n    if (hole.orientation() == CGAL::Sign::POSITIVE) {\n      hole.reverse_orientation();\n    }\n    if (!hole.is_simple()) {\n      std::cout << \"Hole is not simple\" << std::endl;\n      return;\n    }\n    holes.push_back(hole);\n  }\n\n  Polygon_2 boundary;\n\n  {\n    Points points;\n    Points* points_ptr = &points;\n    fill_boundary(points_ptr);\n    for (const auto& point : points) {\n      boundary.push_back(plane.to_2d(point));\n    }\n    if (boundary.orientation() == CGAL::Sign::NEGATIVE) {\n      boundary.reverse_orientation();\n    }\n    if (!boundary.is_simple()) {\n      std::cout << \"Boundary is not simple\" << std::endl;\n      return;\n    }\n\n    // Stick a box around the boundary (which will now form a hole).\n    CGAL::Bbox_2 bb = boundary.bbox();\n    bb.dilate(10);\n\n    Polygon_2 frame;\n    frame.push_back(Point_2(bb.xmin(), bb.ymin()));\n    frame.push_back(Point_2(bb.xmax(), bb.ymin()));\n    frame.push_back(Point_2(bb.xmax(), bb.ymax()));\n    frame.push_back(Point_2(bb.xmin(), bb.ymax()));\n    if (frame.orientation() == CGAL::Sign::NEGATIVE) {\n      frame.reverse_orientation();\n    }\n\n    std::vector<Polygon_2> boundaries { boundary };\n\n    insetting_boundary = Polygon_with_holes_2(frame, holes.begin(), holes.end());\n  }\n\n  double offset = initial;\n\n  for (;;) {\n    CGAL::General_polygon_set_2<Traits> boundaries;\n\n    Polygon_2 tool;\n    for (double a = 0; a < CGAL_PI * 2; a += CGAL_PI / 16) {\n      tool.push_back(Point_2(sin(-a) * offset, cos(-a) * offset));\n    }\n    if (tool.orientation() == CGAL::Sign::NEGATIVE) {\n      std::cout << \"Reverse tool\" << std::endl;\n      tool.reverse_orientation();\n    }\n\n    // This computes the offsetting of the holes.\n    Polygon_with_holes_2 inset_boundary = CGAL::minkowski_sum_2(insetting_boundary, tool);\n\n    Polygon_with_holes_2 offset_boundary = CGAL::minkowski_sum_2(boundary, tool);\n\n    boundaries.join(CGAL::General_polygon_set_2<Traits>(offset_boundary));\n\n    // We just extract the holes, which are the offset holes.\n    for (auto hole = inset_boundary.holes_begin(); hole != inset_boundary.holes_end(); ++hole) {\n      if (hole->orientation() == CGAL::Sign::NEGATIVE) {\n        Polygon_2 boundary = *hole;\n        boundary.reverse_orientation();\n        boundaries.difference(CGAL::General_polygon_set_2<Traits>(boundary));\n      } else {\n        boundaries.difference(CGAL::General_polygon_set_2<Traits>(*hole));\n      }\n    }\n\n    bool emitted = false;\n\n    std::vector<Traits::Polygon_with_holes_2> polygons;\n    boundaries.polygons_with_holes(std::back_inserter(polygons));\n\n    for (const Traits::Polygon_with_holes_2& polygon : polygons) {\n      const auto& outer = polygon.outer_boundary();\n      emit_polygon(false);\n      for (auto vertex = outer.vertices_begin(); vertex != outer.vertices_end(); ++vertex) {\n        auto p = plane.to_3d(Point_2(CGAL::to_double(vertex->x().exact()), CGAL::to_double(vertex->y().exact())));\n        std::ostringstream x; x << p.x().exact();\n        std::ostringstream y; y << p.y().exact();\n        std::ostringstream z; z << p.z().exact();\n        emit_point(CGAL::to_double(p.x().exact()), CGAL::to_double(p.y().exact()), CGAL::to_double(p.z().exact()), x.str(), y.str(), z.str());\n        emitted = true;\n      }\n      for (auto hole = polygon.holes_begin(); hole != polygon.holes_end(); ++hole) {\n        emit_polygon(true);\n        for (auto vertex = hole->vertices_begin(); vertex != hole->vertices_end(); ++vertex) {\n          auto p = plane.to_3d(Point_2(CGAL::to_double(vertex->x().exact()), CGAL::to_double(vertex->y().exact())));\n          std::ostringstream x; x << p.x().exact();\n          std::ostringstream y; y << p.y().exact();\n          std::ostringstream z; z << p.z().exact();\n          emit_point(CGAL::to_double(p.x().exact()), CGAL::to_double(p.y().exact()), CGAL::to_double(p.z().exact()), x.str(), y.str(), z.str());\n          emitted = true;\n        }\n      }\n    }\n\n    if (!emitted) {\n      break;\n    }\n    if (step <= 0) {\n      break;\n    }\n    offset += step;\n    if (limit <= 0) {\n      continue;\n    }\n    if (offset >= limit) {\n      break;\n    }\n  }\n}\n\nvoid InsetOfPolygonWithHoles(double initial, double step, double limit, std::size_t hole_count, emscripten::val fill_plane, emscripten::val fill_boundary, emscripten::val fill_hole, emscripten::val emit_polygon, emscripten::val emit_point) {\n  typedef CGAL::Gps_segment_traits_2<Kernel> Traits;\n  Plane plane;\n  admitPlane(plane, fill_plane);\n  plane = unitPlane(plane);\n\n  Polygon_with_holes_2 insetting_boundary;\n\n  {\n    Points points;\n    Points* points_ptr = &points;\n    fill_boundary(points_ptr);\n    Polygon_2 boundary;\n    for (const auto& point : points) {\n      boundary.push_back(plane.to_2d(point));\n    }\n    if (boundary.orientation() == CGAL::Sign::POSITIVE) {\n      boundary.reverse_orientation();\n    }\n    if (!boundary.is_simple()) {\n      std::cout << \"Boundary is not simple\" << std::endl;\n      return;\n    }\n\n    // Stick a box around the boundary (which will now form a hole).\n    CGAL::Bbox_2 bb = boundary.bbox();\n    bb.dilate(10);\n\n    Polygon_2 frame;\n    frame.push_back(Point_2(bb.xmin(), bb.ymin()));\n    frame.push_back(Point_2(bb.xmax(), bb.ymin()));\n    frame.push_back(Point_2(bb.xmax(), bb.ymax()));\n    frame.push_back(Point_2(bb.xmin(), bb.ymax()));\n    if (frame.orientation() == CGAL::Sign::NEGATIVE) {\n      frame.reverse_orientation();\n    }\n\n    std::vector<Polygon_2> boundaries { boundary };\n\n    insetting_boundary = Polygon_with_holes_2(frame, boundaries.begin(), boundaries.end());\n  }\n\n  std::vector<Polygon_2> holes;\n  for (std::size_t nth = 0; nth < hole_count; nth++) {\n    Points points;\n    Points* points_ptr = &points;\n    fill_hole(points_ptr, nth);\n    Polygon_2 hole;\n    for (const auto& point : points) {\n      hole.push_back(plane.to_2d(point));\n    }\n    if (hole.orientation() == CGAL::Sign::NEGATIVE) {\n      hole.reverse_orientation();\n    }\n    if (!hole.is_simple()) {\n      std::cout << \"Hole is not simple\" << std::endl;\n      return;\n    }\n    holes.push_back(hole);\n  }\n\n  double offset = initial;\n\n  for (;;) {\n    CGAL::General_polygon_set_2<Traits> boundaries;\n\n    Polygon_2 tool;\n    for (double a = 0; a < CGAL_PI * 2; a += CGAL_PI / 16) {\n      tool.push_back(Point_2(sin(-a) * offset, cos(-a) * offset));\n    }\n    if (tool.orientation() == CGAL::Sign::NEGATIVE) {\n      std::cout << \"Reverse tool\" << std::endl;\n      tool.reverse_orientation();\n    }\n\n    Polygon_with_holes_2 inset_boundary = CGAL::minkowski_sum_2(insetting_boundary, tool);\n\n    // We just extract the holes, which are the inset boundary.\n    for (auto hole = inset_boundary.holes_begin(); hole != inset_boundary.holes_end(); ++hole) {\n      if (hole->orientation() == CGAL::Sign::NEGATIVE) {\n        Polygon_2 boundary = *hole;\n        boundary.reverse_orientation();\n        boundaries.join(CGAL::General_polygon_set_2<Traits>(boundary));\n      } else {\n        boundaries.join(CGAL::General_polygon_set_2<Traits>(*hole));\n      }\n    }\n\n    for (const auto& hole : holes) {\n      Polygon_with_holes_2 offset_hole = CGAL::minkowski_sum_2(hole, tool);\n      boundaries.difference(CGAL::General_polygon_set_2<Traits>(offset_hole));\n    }\n\n    bool emitted = false;\n\n    std::vector<Traits::Polygon_with_holes_2> polygons;\n    boundaries.polygons_with_holes(std::back_inserter(polygons));\n\n    for (const Traits::Polygon_with_holes_2& polygon : polygons) {\n      const auto& outer = polygon.outer_boundary();\n      emit_polygon(false);\n      for (auto edge = outer.edges_begin(); edge != outer.edges_end(); ++edge) {\n        if (edge->source() == edge->target()) {\n          std::cout << \"QQ/skip zero length edge\" << std::endl;\n          continue;\n        }\n        auto p = plane.to_3d(Point_2(CGAL::to_double(edge->source().x().exact()), CGAL::to_double(edge->source().y().exact())));\n        std::ostringstream x; x << p.x().exact();\n        std::ostringstream y; y << p.y().exact();\n        std::ostringstream z; z << p.z().exact();\n        emit_point(CGAL::to_double(p.x().exact()), CGAL::to_double(p.y().exact()), CGAL::to_double(p.z().exact()), x.str(), y.str(), z.str());\n        emitted = true;\n      }\n      for (auto hole = polygon.holes_begin(); hole != polygon.holes_end(); ++hole) {\n        emit_polygon(true);\n        for (auto edge = hole->edges_begin(); edge != hole->edges_end(); ++edge) {\n          if (edge->source() == edge->target()) {\n            std::cout << \"QQ/skip zero length edge\" << std::endl;\n            continue;\n          }\n          auto p = plane.to_3d(Point_2(CGAL::to_double(edge->source().x().exact()), CGAL::to_double(edge->source().y().exact())));\n          std::ostringstream x; x << p.x().exact();\n          std::ostringstream y; y << p.y().exact();\n          std::ostringstream z; z << p.z().exact();\n          emit_point(CGAL::to_double(p.x().exact()), CGAL::to_double(p.y().exact()), CGAL::to_double(p.z().exact()), x.str(), y.str(), z.str());\n          emitted = true;\n        }\n      }\n    }\n\n    if (!emitted) {\n      break;\n    }\n    if (step <= 0) {\n      break;\n    }\n    offset += step;\n    if (limit <= 0) {\n      continue;\n    }\n    if (offset >= limit) {\n      break;\n    }\n  }\n}\n\ntemplate <typename P>\nbool admitPolygonWithHoles(std::size_t nth_polygon, const Plane& plane, P& polygon, emscripten::val fill_boundary, emscripten::val fill_hole) {\n  Points points;\n  Points* points_ptr = &points;\n  fill_boundary(points_ptr, nth_polygon);\n  if (points.size() == 0) {\n    return false;\n  }\n  Polygon_2 boundary;\n  for (const auto& point : points) {\n    boundary.push_back(plane.to_2d(point));\n  }\n    if (boundary.orientation() == CGAL::Sign::NEGATIVE) {\n    boundary.reverse_orientation();\n  }\n  if (!boundary.is_simple()) {\n    std::cout << \"Boundary is not simple\" << std::endl;\n    return false;\n  }\n\n  std::vector<Polygon_2> holes;\n  for (;;) {\n    Points points;\n    Points* points_ptr = &points;\n    fill_hole(points_ptr, nth_polygon, holes.size());\n    if (points.size() == 0) {\n      break;\n    }\n    Polygon_2 hole;\n    for (const auto& point : points) {\n      hole.push_back(plane.to_2d(point));\n    }\n    if (hole.orientation() == CGAL::Sign::POSITIVE) {\n      hole.reverse_orientation();\n    }\n    if (!hole.is_simple()) {\n      std::cout << \"Hole is not simple\" << std::endl;\n      return false;\n    }\n    holes.push_back(hole);\n  }\n\n  polygon = P(boundary, holes.begin(), holes.end());\n  return true;\n}\n\ntemplate <typename P>\nvoid admitPolygonsWithHoles(const Plane& plane, std::vector<P>& polygons, emscripten::val fill_boundary, emscripten::val fill_hole) {\n  for (;;) {\n    Polygon_with_holes_2 polygon;\n    if (!admitPolygonWithHoles(polygons.size(), plane, polygon, fill_boundary, fill_hole)) {\n      return;\n    }\n    polygons.push_back(polygon);\n  }\n}\n\nvoid emitPlane(const Plane& plane, emscripten::val& emit_plane) {\n  const auto a = plane.a().exact();\n  const auto b = plane.b().exact();\n  const auto c = plane.c().exact();\n  const auto d = plane.d().exact();\n  std::ostringstream x; x << a; std::string xs = x.str();\n  std::ostringstream y; y << b; std::string ys = y.str();\n  std::ostringstream z; z << c; std::string zs = z.str();\n  std::ostringstream w; w << d; std::string ws = w.str();\n  const double xd = CGAL::to_double(a);\n  const double yd = CGAL::to_double(b);\n  const double zd = CGAL::to_double(c);\n  const double ld = std::sqrt(xd * xd + yd * yd + zd * zd);\n  const double wd = CGAL::to_double(d);\n  // Normalize the approximate plane normal.\n  emit_plane(xd / ld, yd / ld, zd / ld, wd, xs, ys, zs, ws);\n}\n\ntemplate <typename P>\nvoid emitPolygonsWithHoles(const Plane& plane, const std::vector<P>& polygons, emscripten::val& emit_polygon, emscripten::val& emit_point) {\n  for (const P& polygon : polygons) {\n    // std::cout << \"QQ/emitPolygonsWithHoles: \" << std::endl;\n    // print_polygon_with_holes(polygon);\n    const auto& outer = polygon.outer_boundary();\n    emit_polygon(false);\n    for (auto edge = outer.edges_begin(); edge != outer.edges_end(); ++edge) {\n      if (edge->source() == edge->target()) {\n        // Skip zero length edges.\n        std::cout << \"QQ/skip zero length edge\" << std::endl;\n        continue;\n      }\n      auto p = plane.to_3d(Point_2(CGAL::to_double(edge->source().x().exact()), CGAL::to_double(edge->source().y().exact())));\n      auto p2 = plane.to_3d(Point_2(CGAL::to_double(edge->target().x().exact()), CGAL::to_double(edge->target().y().exact())));\n      if (p == p2) {\n        // This produced a zero length edge in 3 space.\n        // CHECK: For some mysterious reason this might not be a zero length edge in 2 space.\n        // std::cout << \"QQ/dup\" << std::endl;\n        continue;\n      }\n      std::ostringstream x; x << p.x().exact();\n      std::ostringstream y; y << p.y().exact();\n      std::ostringstream z; z << p.z().exact();\n      emit_point(CGAL::to_double(p.x().exact()), CGAL::to_double(p.y().exact()), CGAL::to_double(p.z().exact()), x.str(), y.str(), z.str());\n    }\n    for (auto hole = polygon.holes_begin(); hole != polygon.holes_end(); ++hole) {\n      emit_polygon(true);\n      for (auto edge = hole->edges_begin(); edge != hole->edges_end(); ++edge) {\n        if (edge->source() == edge->target()) {\n          // Skip zero length edges.\n          std::cout << \"QQ/skip zero length edge\" << std::endl;\n          continue;\n        }\n        auto p = plane.to_3d(Point_2(CGAL::to_double(edge->source().x().exact()), CGAL::to_double(edge->source().y().exact())));\n        std::ostringstream x; x << p.x().exact();\n        std::ostringstream y; y << p.y().exact();\n        std::ostringstream z; z << p.z().exact();\n        emit_point(CGAL::to_double(p.x().exact()), CGAL::to_double(p.y().exact()), CGAL::to_double(p.z().exact()), x.str(), y.str(), z.str());\n      }\n    }\n  }\n}\n\nconst int kAdd = 1;\nconst int kCut = 2;\nconst int kClip = 3;\n\nvoid BooleansOfPolygonsWithHoles(const Plane& plane, emscripten::val get_operation, emscripten::val fill_boundary, emscripten::val fill_hole, emscripten::val emit_polygon, emscripten::val emit_point) {\n  typedef CGAL::Gps_segment_traits_2<Kernel> Traits;\n\n  std::vector<Traits::Polygon_with_holes_2> input;\n  std::vector<Traits::Polygon_with_holes_2> output;\n\n  admitPolygonsWithHoles(plane, input, fill_boundary, fill_hole);\n\n  CGAL::General_polygon_set_2<Traits> set;\n  int nthOperation = 0;\n  for (const auto& polygon : input) {\n    switch (get_operation(nthOperation++).as<int>()) {\n      case kAdd:\n        set.join(polygon);\n        break;\n      case kCut:\n        set.difference(polygon);\n        break;\n      case kClip:\n        set.intersection(polygon);\n        break;\n    }\n  }\n  set.polygons_with_holes(std::back_inserter(output));\n\n  emitPolygonsWithHoles(plane, output, emit_polygon, emit_point);\n}\n\nvoid BooleansOfPolygonsWithHolesApproximate(double x, double y, double z, double w, emscripten::val get_operation, emscripten::val fill_boundary, emscripten::val fill_hole, emscripten::val emit_polygon, emscripten::val emit_point) {\n  BooleansOfPolygonsWithHoles(Plane(to_FT(x), to_FT(y), to_FT(z), to_FT(w)), get_operation, fill_boundary, fill_hole, emit_polygon, emit_point);\n}\n\nvoid BooleansOfPolygonsWithHolesExact(std::string a, std::string b, std::string c, std::string d, emscripten::val get_operation, emscripten::val fill_boundary, emscripten::val fill_hole, emscripten::val emit_polygon, emscripten::val emit_point) {\n  BooleansOfPolygonsWithHoles(Plane(to_FT(a), to_FT(b), to_FT(c), to_FT(d)), get_operation, fill_boundary, fill_hole, emit_polygon, emit_point);\n}\n\nvoid convertSurfaceMeshFacesToArrangements(Surface_mesh& mesh, std::unordered_map<Plane, Arrangement_2>& arrangements) {\n  std::unordered_set<Plane> planes;\n  std::unordered_map<Face_index, Plane> facet_to_plane;\n\n  // FIX: Make this more efficient.\n  for (const auto& facet : mesh.faces()) {\n    const auto& start = mesh.halfedge(facet);\n    if (mesh.is_removed(start)) {\n      continue;\n    }\n    const Plane facet_plane = ensureFacetPlane(mesh, facet_to_plane, planes, facet);\n    Arrangement_2& arrangement = arrangements[facet_plane];\n    Halfedge_index edge = start;\n    do {\n      bool corner = false;\n      const auto& opposite_facet = mesh.face(mesh.opposite(edge));\n      if (opposite_facet == mesh.null_face()) {\n        corner = true;\n      } else {\n        const Plane opposite_facet_plane = ensureFacetPlane(mesh, facet_to_plane, planes, opposite_facet);\n        if (facet_plane != opposite_facet_plane) {\n          corner = true;\n        }\n      }\n      if (corner) {\n        Point_2 s = facet_plane.to_2d(mesh.point(mesh.source(edge)));\n        Point_2 t = facet_plane.to_2d(mesh.point(mesh.target(edge)));\n\n        Segment_2 segment { s, t };\n        insert(arrangement, segment);\n      }\n      const auto& next = mesh.next(edge);\n      edge = next;\n    } while (edge != start);\n  }\n}\n\nvoid emitArrangementsAsPolygonsWithHoles(const std::unordered_map<Plane, Arrangement_2>& arrangements, emscripten::val emit_plane, emscripten::val emit_polygon, emscripten::val emit_point) {\n  for (const auto& entry : arrangements) {\n    const Plane& plane = entry.first;\n    const Arrangement_2& arrangement = entry.second;\n    std::vector<Polygon_with_holes_2> polygons;\n    convertArrangementToPolygonsWithHoles(arrangement, polygons);\n    emitPlane(plane, emit_plane);\n    emitPolygonsWithHoles(plane, polygons, emit_polygon, emit_point);\n  }\n}\n\nvoid ArrangePolygonsWithHoles(std::size_t count, emscripten::val fill_plane, emscripten::val fill_boundary, emscripten::val fill_hole, emscripten::val emit_plane, emscripten::val emit_polygon, emscripten::val emit_point) {\n  std::unordered_map<Plane, Arrangement_2> arrangements;\n\n  for (std::size_t nth_polygon = 0; nth_polygon < count; nth_polygon++) {\n    Plane plane;\n    admitPlane(plane, fill_plane);\n    plane = unitPlane(plane);\n    Arrangement_2& arrangement = arrangements[plane];\n    Polygon_with_holes_2 polygon;\n    admitPolygonWithHoles(nth_polygon, plane, polygon, fill_boundary, fill_hole);\n    for (auto it = polygon.outer_boundary().edges_begin(); it != polygon.outer_boundary().edges_end(); ++it) {\n      insert(arrangement, *it);\n    }\n    for (auto hole = polygon.holes_begin(); hole != polygon.holes_end(); ++hole) {\n      for (auto it = hole->edges_begin(); it != hole->edges_end(); ++it) {\n        insert(arrangement, *it);\n      }\n    }\n  }\n\n  emitArrangementsAsPolygonsWithHoles(arrangements, emit_plane, emit_polygon, emit_point);\n}\n\n// FIX: Accept exact plane.\nvoid ArrangePaths(Plane plane, bool do_triangulate, emscripten::val fill, emscripten::val emit_polygon, emscripten::val emit_point) {\n  typedef CGAL::Arr_segment_traits_2<Kernel>            Traits_2;\n  typedef Traits_2::Point_2                             Point_2;\n  typedef Traits_2::X_monotone_curve_2                  Segment_2;\n  typedef CGAL::Arrangement_2<Traits_2>                 Arrangement_2;\n  typedef Arrangement_2::Vertex_handle                  Vertex_handle;\n  typedef Arrangement_2::Halfedge_handle                Halfedge_handle;\n\n  Arrangement_2 arrangement;\n\n  std::set<std::vector<Kernel::FT>> segments;\n\n  for (;;) {\n    Points points;\n    auto* p = &points;\n    fill(p);\n    if (points.empty()) {\n      break;\n    }\n    Point_2s point_2s;\n    for (const auto& point : points) {\n      auto point_2 = plane.to_2d(point);\n      point_2s.push_back(point_2);\n    }\n    for (std::size_t i = 0; i + 1 < point_2s.size(); i += 2) {\n      if (segments.find({ point_2s[i].x(), point_2s[i].y(), point_2s[i + 1].x(), point_2s[i + 1].y() }) != segments.end()) {\n        continue;\n      }\n      if (point_2s[i] == point_2s[i + 1]) {\n        // Skip zero length segments.\n        continue;\n      }\n      // Add the segment\n      Segment_2 segment { point_2s[i], point_2s[i + 1] };\n      insert(arrangement, segment);\n\n      // Remember the edges we've inserted.\n      segments.insert({ point_2s[i].x(), point_2s[i].y(), point_2s[i + 1].x(), point_2s[i + 1].y() });\n      // In both directions.\n      segments.insert({ point_2s[i + 1].x(), point_2s[i + 1].y(), point_2s[i].x(), point_2s[i].y() });\n    }\n  }\n\n  std::queue<Arrangement_2::Face_const_handle> undecided;\n  CGAL::Unique_hash_map<Arrangement_2::Face_const_handle, bool> positive_faces;\n  CGAL::Unique_hash_map<Arrangement_2::Face_const_handle, bool> negative_faces;\n\n  for (Arrangement_2::Face_iterator face = arrangement.faces_begin(); face != arrangement.faces_end(); ++face) {\n    if (!face->has_outer_ccb()) {\n      negative_faces[face] = true;\n    } else {\n      undecided.push(face);\n    }\n  }\n\n  while (!undecided.empty()) {\n    Arrangement_2::Face_const_handle face = undecided.front();\n    undecided.pop();\n    if (positive_faces[face]) {\n      for (Arrangement_2::Hole_const_iterator hole = face->holes_begin(); hole != face->holes_end(); ++hole) {\n        negative_faces[(*hole)->twin()->face()] = true;\n        positive_faces[(*hole)->twin()->face()] = false;\n      }\n      continue;\n    }\n    if (negative_faces[face]) {\n      for (Arrangement_2::Hole_const_iterator hole = face->holes_begin(); hole != face->holes_end(); ++hole) {\n        positive_faces[(*hole)->twin()->face()] = true;\n        negative_faces[(*hole)->twin()->face()] = false;\n      }\n      continue;\n    }\n    bool decided = false;\n    Arrangement_2::Ccb_halfedge_const_circulator start = face->outer_ccb();\n    Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n    do {\n      if (negative_faces[edge->twin()->face()]) {\n        positive_faces[face] = true;\n        decided = true;\n        break;\n      }\n    } while (++edge != start);\n    if (!decided) {\n      edge = start;\n      do {\n        if (positive_faces[edge->twin()->face()]) {\n          negative_faces[face] = true;\n          decided = true;\n          break;\n        }\n      } while (++edge != start);\n    }\n    undecided.push(face);\n  }\n\n  if (do_triangulate) {\n    CGAL::Polygon_triangulation_decomposition_2<Kernel> triangulate;\n    for (Arrangement_2::Face_iterator face = arrangement.faces_begin(); face != arrangement.faces_end(); ++face) {\n      if (!positive_faces[face] || !face->has_outer_ccb()) {\n        continue;\n      }\n      Arrangement_2::Ccb_halfedge_const_circulator start = face->outer_ccb();\n      Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n      Polygon_2 polygon;\n      do {\n        polygon.push_back(edge->source()->point());\n      } while (++edge != start);\n  \n      std::vector<Polygon_2> holes;\n      for (Arrangement_2::Hole_iterator hole = face->holes_begin(); hole != face->holes_end(); ++hole) {\n        Polygon_2 polygon;\n        Arrangement_2::Ccb_halfedge_const_circulator start = *hole;\n        Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n        do {\n          polygon.push_back(edge->source()->point());\n        } while (++edge != start);\n        holes.push_back(polygon);\n      }\n      Polygon_with_holes_2 polygon_with_holes(polygon, holes.begin(), holes.end());\n      std::vector<Polygon_2> triangles;\n      triangulate(polygon_with_holes, std::back_inserter(triangles));\n      for (const auto& triangle : triangles) {\n        emit_polygon(false);\n        for (const auto& p2 : triangle) {\n          Point p3 = plane.to_3d(p2);\n          auto e3 = p3;\n          std::ostringstream x; x << e3.x().exact();\n          std::ostringstream y; y << e3.y().exact();\n          std::ostringstream z; z << e3.z().exact();\n          emit_point(CGAL::to_double(p3.x().exact()), CGAL::to_double(p3.y().exact()), CGAL::to_double(p3.z().exact()), x.str(), y.str(), z.str());\n        }\n      }\n    }\n  } else {\n    for (Arrangement_2::Face_iterator face = arrangement.faces_begin(); face != arrangement.faces_end(); ++face) {\n      if (!positive_faces[face] || !face->has_outer_ccb()) {\n        continue;\n      }\n      Arrangement_2::Ccb_halfedge_const_circulator start = face->outer_ccb();\n      Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n      // Can we build Polygon_with_holes_2 here?\n      emit_polygon(false);\n      do {\n        Point p3 = plane.to_3d(edge->source()->point());\n        auto e3 = p3;\n        std::ostringstream x; x << e3.x().exact();\n        std::ostringstream y; y << e3.y().exact();\n        std::ostringstream z; z << e3.z().exact();\n        emit_point(CGAL::to_double(p3.x().exact()), CGAL::to_double(p3.y().exact()), CGAL::to_double(p3.z().exact()), x.str(), y.str(), z.str());\n      } while (++edge != start);\n  \n      // Emit holes\n      for (Arrangement_2::Hole_iterator hole = face->holes_begin(); hole != face->holes_end(); ++hole) {\n        emit_polygon(true);\n        Arrangement_2::Ccb_halfedge_const_circulator start = *hole;\n        Arrangement_2::Ccb_halfedge_const_circulator edge = start;\n        do {\n          Point p3 = plane.to_3d(edge->source()->point());\n          auto e3 = p3;\n          std::ostringstream x; x << e3.x().exact();\n          std::ostringstream y; y << e3.y().exact();\n          std::ostringstream z; z << e3.z().exact();\n          emit_point(CGAL::to_double(p3.x().exact()), CGAL::to_double(p3.y().exact()), CGAL::to_double(p3.z().exact()), x.str(), y.str(), z.str());\n        } while (++edge != start);\n      }\n    }\n  }\n}\n\nvoid ArrangePathsApproximate(double x, double y, double z, double w, bool triangulate, emscripten::val fill, emscripten::val emit_polygon, emscripten::val emit_point) {\n  ArrangePaths(Plane(x, y, z, w), triangulate, fill, emit_polygon, emit_point);\n}\n\nvoid ArrangePathsExact(std::string x, std::string y, std::string z, std::string w, bool triangulate, emscripten::val fill, emscripten::val emit_polygon, emscripten::val emit_point) {\n  ArrangePaths(Plane(to_FT(x), to_FT(y), to_FT(z), to_FT(w)), triangulate, fill, emit_polygon, emit_point);\n}\n\nvoid FromSurfaceMeshToPolygonsWithHoles(const Surface_mesh* input, const Transformation* transform, emscripten::val emit_plane, emscripten::val emit_polygon, emscripten::val emit_point) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, mesh, CGAL::parameters::all_default());\n   \n  // std::cout << \"QQ/fsmtpwh\" << std::endl;\n  std::unordered_map<Plane, Arrangement_2> arrangements;\n  convertSurfaceMeshFacesToArrangements(mesh, arrangements);\n  emitArrangementsAsPolygonsWithHoles(arrangements, emit_plane, emit_polygon, emit_point);\n}\n\nbool computeFitPolygon(const Polygon_with_holes_2& space, const Polygon_with_holes_2& shape, Point_2& picked) {\n  Polygon_with_holes_2 insetting_boundary;\n\n  {\n    // Stick a box around the boundary (which will now form a hole).\n    CGAL::Bbox_2 bb = space.outer_boundary().bbox();\n    // 10 is wrong -- it should be a dilated boundary box of shape.\n    bb.dilate(10);\n\n    Polygon_2 frame;\n    frame.push_back(Point_2(bb.xmin(), bb.ymin()));\n    frame.push_back(Point_2(bb.xmax(), bb.ymin()));\n    frame.push_back(Point_2(bb.xmax(), bb.ymax()));\n    frame.push_back(Point_2(bb.xmin(), bb.ymax()));\n    if (frame.orientation() == CGAL::Sign::NEGATIVE) {\n      frame.reverse_orientation();\n    }\n\n    std::vector<Polygon_2> boundaries { space.outer_boundary() };\n\n    insetting_boundary = Polygon_with_holes_2(frame, boundaries.begin(), boundaries.end());\n  }\n\n  std::vector<Polygon_2> holes;\n  for (auto it = space.holes_begin(); it != space.holes_end(); ++it) {\n    Polygon_2 hole = *it;\n    if (hole.orientation() == CGAL::Sign::NEGATIVE) {\n      hole.reverse_orientation();\n    }\n    if (!hole.is_simple()) {\n      std::cout << \"Hole is not simple\" << std::endl;\n      return false;\n    }\n    holes.push_back(hole);\n  }\n\n  General_polygon_set_2 boundaries;\n\n  Polygon_with_holes_2 inset_boundary = CGAL::minkowski_sum_2(insetting_boundary, shape);\n\n  // We just extract the holes, which are the inset boundary.\n  for (auto hole = inset_boundary.holes_begin(); hole != inset_boundary.holes_end(); ++hole) {\n    if (hole->orientation() == CGAL::Sign::NEGATIVE) {\n      Polygon_2 boundary = *hole;\n      boundary.reverse_orientation();\n      boundaries.join(General_polygon_set_2(boundary));\n    } else {\n      boundaries.join(General_polygon_set_2(*hole));\n    }\n  }\n\n  for (const auto& hole : holes) {\n    Polygon_with_holes_2 offset_hole = CGAL::minkowski_sum_2(hole, shape);\n    boundaries.difference(General_polygon_set_2(offset_hole));\n  }\n\n  std::vector<Polygon_with_holes_2> polygons;\n  boundaries.polygons_with_holes(std::back_inserter(polygons));\n\n  std::vector<Point_2> points;\n  for (const auto& polygon : polygons) {\n    points.insert(std::end(points), polygon.outer_boundary().vertices_begin(), polygon.outer_boundary().vertices_end());\n    for (const auto& point : polygon.outer_boundary()) {\n      points.push_back(point);\n    }\n    for (auto hole = polygon.holes_begin(); hole != polygon.holes_end(); ++hole) {\n      points.insert(std::end(points), hole->vertices_begin(), hole->vertices_end());\n    }\n  }\n\n  // Just pick the first point for now.\n\n  picked = points[0];\n\n  return true;\n}\n\nconst Surface_mesh* MinkowskiDifferenceOfSurfaceMeshes(const Surface_mesh* input_mesh, const Transformation* input_transform, const Surface_mesh* offset_mesh, const Transformation* offset_transform) {\n  typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron;\n\n  Nef_polyhedron input_nef(*input_mesh);\n  input_nef.transform(*input_transform);\n  Nef_polyhedron input_nef_boundary = input_nef.boundary();\n  Nef_polyhedron offset_nef(*offset_mesh);\n  offset_nef.transform(*offset_transform);\n  // Subtract the shell of the nef.\n  Nef_polyhedron outer_nef = input_nef - minkowski_sum_3(input_nef_boundary, offset_nef);\n\n  std::vector<Surface_mesh> input_meshes;\n  CGAL::Polygon_mesh_processing::split_connected_components(*input_mesh, input_meshes);\n\n  // Unfortunately minkowski sum doesn't do cavities, so let's do them here and cut them out.\n\n  for (const Surface_mesh& hole : input_meshes) {\n    if (!CGAL::Polygon_mesh_processing::does_bound_a_volume(hole)) {\n      continue;\n    }\n    if (CGAL::Polygon_mesh_processing::is_outward_oriented(hole)) {\n      // Not a cavity.\n      continue;\n    }\n    Nef_polyhedron input_nef(hole);\n    Nef_polyhedron input_nef_boundary = input_nef.boundary();\n    // Add the shell of the nef.\n    Nef_polyhedron result_nef = input_nef + minkowski_sum_3(input_nef_boundary, offset_nef);\n    outer_nef -= result_nef;\n  }\n\n  Surface_mesh* result_mesh = new Surface_mesh;\n  CGAL::convert_nef_polyhedron_to_polygon_mesh(outer_nef, *result_mesh);\n  return result_mesh;\n}\n\nconst Surface_mesh* MinkowskiSumOfSurfaceMeshes(const Surface_mesh* input_mesh, const Transformation* input_transform, const Surface_mesh* offset_mesh, const Transformation* offset_transform) {\n  typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron;\n\n  Nef_polyhedron input_nef(*input_mesh);\n  input_nef.transform(*input_transform);\n  Nef_polyhedron input_nef_boundary = input_nef.boundary();\n  Nef_polyhedron offset_nef(*offset_mesh);\n  offset_nef.transform(*offset_transform);\n  // Add the shell of the nef.\n  Nef_polyhedron outer_nef = input_nef + minkowski_sum_3(input_nef_boundary, offset_nef);\n\n  std::vector<Surface_mesh> input_meshes;\n  CGAL::Polygon_mesh_processing::split_connected_components(*input_mesh, input_meshes);\n\n  // Unfortunately minkowski sum doesn't do cavities, so let's do them here and cut them out.\n\n  for (const Surface_mesh& hole : input_meshes) {\n    if (!CGAL::Polygon_mesh_processing::does_bound_a_volume(hole)) {\n      continue;\n    }\n    if (CGAL::Polygon_mesh_processing::is_outward_oriented(hole)) {\n      // Not a cavity.\n      continue;\n    }\n    Nef_polyhedron input_nef(hole);\n    Nef_polyhedron input_nef_boundary = input_nef.boundary();\n    // Subtract the shell of the nef.\n    Nef_polyhedron result_nef = input_nef - minkowski_sum_3(input_nef_boundary, offset_nef);\n    outer_nef -= result_nef;\n  }\n\n  Surface_mesh* result_mesh = new Surface_mesh;\n  CGAL::convert_nef_polyhedron_to_polygon_mesh(outer_nef, *result_mesh);\n  return result_mesh;\n}\n\nconst Surface_mesh* MinkowskiShellOfSurfaceMeshes(const Surface_mesh* input_mesh, const Transformation* input_transform, const Surface_mesh* offset_mesh, const Transformation* offset_transform) {\n  typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron;\n\n  Nef_polyhedron input_nef(*input_mesh);\n  input_nef.transform(*input_transform);\n  Nef_polyhedron input_nef_boundary = input_nef.boundary();\n  Nef_polyhedron offset_nef(*offset_mesh);\n  offset_nef.transform(*offset_transform);\n  // Take the shell of the nef.\n  Nef_polyhedron outer_nef = minkowski_sum_3(input_nef_boundary, offset_nef);\n\n  std::vector<Surface_mesh> input_meshes;\n  CGAL::Polygon_mesh_processing::split_connected_components(*input_mesh, input_meshes);\n\n  // Unfortunately minkowski sum doesn't do cavities, so let's do them here and cut them out.\n\n  for (const Surface_mesh& hole : input_meshes) {\n    if (!CGAL::Polygon_mesh_processing::does_bound_a_volume(hole)) {\n      continue;\n    }\n    if (CGAL::Polygon_mesh_processing::is_outward_oriented(hole)) {\n      // Not a cavity.\n      continue;\n    }\n    Nef_polyhedron input_nef(hole);\n    Nef_polyhedron input_nef_boundary = input_nef.boundary();\n    // Take the shell of the nef.\n    Nef_polyhedron result_nef = minkowski_sum_3(input_nef_boundary, offset_nef);\n    outer_nef += result_nef;\n  }\n\n  Surface_mesh* result_mesh = new Surface_mesh;\n  CGAL::convert_nef_polyhedron_to_polygon_mesh(outer_nef, *result_mesh);\n  return result_mesh;\n}\n\nbool Surface_mesh__is_closed(const Surface_mesh* mesh) {\n  return CGAL::is_closed(*mesh);\n}\n\nbool Surface_mesh__is_valid_halfedge_graph(const Surface_mesh* mesh) {\n  return CGAL::is_valid_halfedge_graph(*mesh);\n}\n\nbool Surface_mesh__is_valid_face_graph(const Surface_mesh* mesh) {\n  return CGAL::is_valid_face_graph(*mesh);\n}\n\nbool Surface_mesh__is_valid_polygon_mesh(const Surface_mesh* mesh) {\n  return CGAL::is_valid_polygon_mesh(*mesh);\n}\n\nvoid Surface_mesh__bbox(const Surface_mesh* input, const Transformation* transform, emscripten::val emit) {\n  Surface_mesh mesh(*input);\n  CGAL::Polygon_mesh_processing::transform(*transform, mesh, CGAL::parameters::all_default());\n  CGAL::Bbox_3 box = CGAL::Polygon_mesh_processing::bbox(mesh);\n  emit(box.xmin(), box.ymin(), box.zmin(), box.xmax(), box.ymax(), box.zmax());\n}\n\nconst Transformation* Transformation__identity() {\n  return new Transformation(CGAL::IDENTITY);\n}\n\nconst Transformation* Transformation__compose(const Transformation* a, const Transformation* b) {\n  return new Transformation(*a * *b);\n}\n\nconst Transformation* Transformation__inverse(const Transformation* a) {\n  return new Transformation(a->inverse());\n}\n\nvoid Transformation__to_exact(const Transformation* t, emscripten::val put) {\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 4; j++) { \n      auto value = t->cartesian(i, j).exact();\n      std::ostringstream serialization;\n      serialization << value;\n      put(serialization.str());\n    }\n  }\n\n  auto value = t->cartesian(3, 3).exact();\n  std::ostringstream serialization;\n  serialization << value;\n  put(serialization.str());\n}\n\nvoid Transformation__to_approximate(const Transformation* t, emscripten::val put) {\n  for (int i = 0; i < 3; i++) {\n    for (int j = 0; j < 4; j++) { \n      FT value = t->cartesian(i, j);\n      put(CGAL::to_double(value.exact()));\n    }\n  }\n\n  FT value = t->cartesian(3, 3);\n  put(CGAL::to_double(value.exact()));\n}\n\nFT get_double(emscripten::val get) {\n  return to_FT(get().as<double>());\n}\n\nFT get_string(emscripten::val get) {\n  return to_FT(get().as<std::string>());\n}\n\nconst Transformation* Transformation__from_exact(emscripten::val get) {\n  Transformation* t = new Transformation(\n    get_string(get), get_string(get), get_string(get), get_string(get),\n    get_string(get), get_string(get), get_string(get), get_string(get),\n    get_string(get), get_string(get), get_string(get), get_string(get),\n    get_string(get));\n  return t;\n}\n\nconst Transformation* Transformation__from_approximate(emscripten::val get) {\n  Transformation* t = new Transformation(\n    get_double(get), get_double(get), get_double(get), get_double(get),\n    get_double(get), get_double(get), get_double(get), get_double(get),\n    get_double(get), get_double(get), get_double(get), get_double(get),\n    get_double(get));\n  return t;\n}\n\nconst Transformation* Transformation__translate(double x, double y, double z) {\n  return new Transformation(CGAL::TRANSLATION, Vector(x, y, z));\n}\n\nconst Transformation* Transformation__scale(double x, double y, double z) {\n  return new Transformation(\n    x, 0, 0, 0,\n    0, y, 0, 0,\n    0, 0, z, 0,\n    1);\n}\n\nconst Transformation* Transformation__rotate_x(double a) {\n  RT sin_alpha, cos_alpha, w;\n  compute_angle(a, sin_alpha, cos_alpha, w);\n  double r = a * CGAL_PI / 180;\n  return new Transformation(\n      w, 0, 0, 0,\n      0, cos_alpha, -sin_alpha, 0,\n      0, sin_alpha, cos_alpha,  0,\n      w);\n}\n\nconst Transformation* Transformation__rotate_y(double a) {\n  RT sin_alpha, cos_alpha, w;\n  compute_angle(a, sin_alpha, cos_alpha, w);\n  return new Transformation(\n      cos_alpha, 0, -sin_alpha, 0,\n      0, w, 0, 0,\n      sin_alpha, 0, cos_alpha,  0,\n      w);\n}\n\nconst Transformation* Transformation__rotate_z(double a) {\n  RT sin_alpha, cos_alpha, w;\n  compute_angle(a, sin_alpha, cos_alpha, w);\n  return new Transformation(\n      cos_alpha, sin_alpha, 0, 0,\n      -sin_alpha, cos_alpha, 0, 0,\n      0, 0, w,  0,\n      w);\n}\n\n#else // TEST_ONLY\n\nstruct TestException : public std::exception {\n  const char* what () const throw () {\n    return \"MyException\";\n  }\n};\n\nvoid test() {\n#if 1\n  try {\n    std::cout << \"Thrown\" << std::endl;\n    throw TestException();\n  } catch(TestException& e) {\n    std::cout << \"Caught\" << std::endl;\n  }\n#endif\n  std::cout << \"Done\" << std::endl;\n}\n\n#endif\n\nusing emscripten::select_const;\nusing emscripten::select_overload;\n\nEMSCRIPTEN_BINDINGS(module) {\n#ifdef TEST_ONLY\n  emscripten::function(\"test\", &test, emscripten::allow_raw_pointers());\n#else\n  \n  emscripten::class_<Transformation>(\"Transformation\").constructor<>();\n  emscripten::function(\"Transformation__compose\", &Transformation__compose, emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__identity\", &Transformation__identity, emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__inverse\", &Transformation__inverse, emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__from_approximate\", &Transformation__from_approximate, emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__from_exact\", &Transformation__from_exact, emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__to_approximate\", &Transformation__to_approximate, emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__to_exact\", &Transformation__to_exact, emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__translate\", &Transformation__translate, emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__scale\", &Transformation__scale, emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__rotate_x\", &Transformation__rotate_x, emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__rotate_y\", &Transformation__rotate_y, emscripten::allow_raw_pointers());\n  emscripten::function(\"Transformation__rotate_z\", &Transformation__rotate_z, emscripten::allow_raw_pointers());\n\n  emscripten::class_<Polygon_2>(\"Polygon_2\").constructor<>();\n  emscripten::class_<Polygon_with_holes_2>(\"Polygon_with_holes_2\").constructor<>();\n\n  emscripten::class_<SurfaceMeshAndTransform>(\"SurfaceMeshAndTransform\")\n    .constructor<>()\n    .function(\"set_mesh\", &SurfaceMeshAndTransform::set_mesh, emscripten::allow_raw_pointers())\n    .function(\"set_transform\", &SurfaceMeshAndTransform::set_transform, emscripten::allow_raw_pointers());\n\n  emscripten::class_<Triples>(\"Triples\")\n    .constructor<>()\n    .function(\"push_back\", select_overload<void(const Triple&)>(&Triples::push_back))\n    .function(\"size\", select_overload<size_t()const>(&Triples::size));\n\n  emscripten::function(\"addTriple\", &addTriple, emscripten::allow_raw_pointers());\n\n  emscripten::class_<DoubleTriples>(\"DoubleTriples\")\n    .constructor<>()\n    .function(\"push_back\", select_overload<void(const DoubleTriple&)>(&DoubleTriples::push_back))\n    .function(\"size\", select_overload<size_t()const>(&DoubleTriples::size));\n\n  emscripten::function(\"addDoubleTriple\", &addDoubleTriple, emscripten::allow_raw_pointers());\n\n  emscripten::class_<Quadruple>(\"Quadruple\").constructor<>();\n  emscripten::function(\"fillQuadruple\", &fillQuadruple, emscripten::allow_raw_pointers());\n  emscripten::function(\"fillExactQuadruple\", &fillExactQuadruple, emscripten::allow_raw_pointers());\n\n  emscripten::function(\"addPoint\", &addPoint, emscripten::allow_raw_pointers());\n  emscripten::function(\"addExactPoint\", &addExactPoint, emscripten::allow_raw_pointers());\n\n  emscripten::class_<Points>(\"Points\")\n    .constructor<>()\n    .function(\"push_back\", select_overload<void(const Point&)>(&Points::push_back))\n    .function(\"size\", select_overload<size_t()const>(&Points::size));\n\n  emscripten::function(\"addPoint_2\", &addPoint_2, emscripten::allow_raw_pointers());\n\n  emscripten::class_<Point_2s>(\"Point_2s\")\n    .constructor<>()\n    .function(\"push_back\", select_overload<void(const Point&)>(&Points::push_back))\n    .function(\"size\", select_overload<size_t()const>(&Points::size));\n\n  emscripten::class_<Polygon>(\"Polygon\")\n    .constructor<>()\n    .function(\"size\", select_overload<size_t()const>(&Polygon::size));\n\n  emscripten::function(\"Polygon__push_back\", &Polygon__push_back, emscripten::allow_raw_pointers());\n\n  emscripten::class_<Polygons>(\"Polygons\")\n    .constructor<>()\n    .function(\"push_back\", select_overload<void(const Polygon&)>(&Polygons::push_back))\n    .function(\"size\", select_overload<size_t()const>(&Polygons::size));\n\n  emscripten::class_<Face_index>(\"Face_index\").constructor<std::size_t>();\n  emscripten::class_<Halfedge_index>(\"Halfedge_index\").constructor<std::size_t>();\n  emscripten::class_<Vertex_index>(\"Vertex_index\").constructor<std::size_t>();\n\n  emscripten::class_<Surface_mesh>(\"Surface_mesh\")\n    .constructor<>()\n    .function(\"add_vertex_1\", (Vertex_index (Surface_mesh::*)(const Point&))&Surface_mesh::add_vertex)\n    .function(\"add_edge_2\", (Halfedge_index (Surface_mesh::*)(Vertex_index, Vertex_index))&Surface_mesh::add_edge)\n    .function(\"add_face_3\", (Face_index (Surface_mesh::*)(Vertex_index, Vertex_index, Vertex_index))&Surface_mesh::add_face)\n    .function(\"add_face_4\", (Face_index (Surface_mesh::*)(Vertex_index, Vertex_index, Vertex_index, Vertex_index))&Surface_mesh::add_face)\n    .function(\"is_valid\", select_overload<bool(bool)const>(&Surface_mesh::is_valid))\n    .function(\"is_empty\", &Surface_mesh::is_empty)\n    .function(\"number_of_vertices\", &Surface_mesh::number_of_vertices)\n    .function(\"number_of_halfedges\", &Surface_mesh::number_of_halfedges)\n    .function(\"number_of_edges\", &Surface_mesh::number_of_edges)\n    .function(\"number_of_faces\", &Surface_mesh::number_of_faces)\n    .function(\"has_garbage\", &Surface_mesh::has_garbage);\n\n  emscripten::function(\"Surface_mesh__EachFace\", &Surface_mesh__EachFace, emscripten::allow_raw_pointers());\n  emscripten::function(\"LoftBetweenCongruentSurfaceMeshes\", &LoftBetweenCongruentSurfaceMeshes, emscripten::allow_raw_pointers());\n  emscripten::function(\"ExtrusionOfSurfaceMesh\", &ExtrusionOfSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"ExtrusionToPlaneOfSurfaceMesh\", &ExtrusionToPlaneOfSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"ProjectionToPlaneOfSurfaceMesh\", &ProjectionToPlaneOfSurfaceMesh, emscripten::allow_raw_pointers());\n\n  emscripten::function(\"Surface_mesh__halfedge_to_target\", &Surface_mesh__halfedge_to_target, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__halfedge_to_face\", &Surface_mesh__halfedge_to_face, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__halfedge_to_next_halfedge\", &Surface_mesh__halfedge_to_next_halfedge, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__halfedge_to_prev_halfedge\", &Surface_mesh__halfedge_to_prev_halfedge, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__halfedge_to_opposite_halfedge\", &Surface_mesh__halfedge_to_opposite_halfedge, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__vertex_to_halfedge\", &Surface_mesh__vertex_to_halfedge, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__face_to_halfedge\", &Surface_mesh__face_to_halfedge, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__vertex_to_point\", &Surface_mesh__vertex_to_point, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__collect_garbage\", &Surface_mesh__collect_garbage, emscripten::allow_raw_pointers());\n\n  emscripten::function(\"Surface_mesh__add_vertex\", &Surface_mesh__add_vertex, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__add_exact\", &Surface_mesh__add_exact, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__add_face\", &Surface_mesh__add_face, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__add_face_vertices\", &Surface_mesh__add_face_vertices, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__add_edge\", &Surface_mesh__add_edge, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__set_edge_target\", &Surface_mesh__set_edge_target, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__set_edge_next\", &Surface_mesh__set_edge_next, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__set_edge_face\", &Surface_mesh__set_edge_face, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__set_face_edge\", &Surface_mesh__set_face_edge, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__set_vertex_edge\", &Surface_mesh__set_vertex_edge, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__set_vertex_halfedge_to_border_halfedge\", &Surface_mesh__set_vertex_halfedge_to_border_halfedge, emscripten::allow_raw_pointers());\n\n  emscripten::class_<Point>(\"Point\")\n    .constructor<float, float, float>()\n    .function(\"hx\", &Point::hx)\n    .function(\"hy\", &Point::hy)\n    .function(\"hz\", &Point::hz)\n    .function(\"hw\", &Point::hw)\n    .function(\"x\", &Point::x)\n    .function(\"y\", &Point::y)\n    .function(\"z\", &Point::z);\n\n  emscripten::class_<SurfaceMeshQuery>(\"SurfaceMeshQuery\")\n    .constructor<Surface_mesh*>();\n\n  emscripten::function(\"SerializeSurfaceMesh\", &SerializeSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"DeserializeSurfaceMesh\", &DeserializeSurfaceMesh, emscripten::allow_raw_pointers());\n\n  emscripten::function(\"FromPolygonSoupToSurfaceMesh\", &FromPolygonSoupToSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"DifferenceOfSurfaceMeshes\", &DifferenceOfSurfaceMeshes, emscripten::allow_raw_pointers());\n  emscripten::function(\"IntersectionOfSurfaceMeshes\", &IntersectionOfSurfaceMeshes, emscripten::allow_raw_pointers());\n  emscripten::function(\"UnionOfSurfaceMeshes\", &UnionOfSurfaceMeshes, emscripten::allow_raw_pointers());\n  emscripten::function(\"SeparateSurfaceMesh\", &SeparateSurfaceMesh, emscripten::allow_raw_pointers());\n\n  emscripten::function(\"TwistSurfaceMesh\", &TwistSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"BendSurfaceMesh\", &BendSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"PushSurfaceMesh\", &PushSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"OutlineSurfaceMesh\", &OutlineSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"WireframeSurfaceMesh\", &WireframeSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"FromSurfaceMeshToPolygonsWithHoles\", &FromSurfaceMeshToPolygonsWithHoles, emscripten::allow_raw_pointers());\n  emscripten::function(\"ComputeCentroidOfSurfaceMesh\", &ComputeCentroidOfSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"ComputeNormalOfSurfaceMesh\", &ComputeNormalOfSurfaceMesh, emscripten::allow_raw_pointers());\n\n  emscripten::function(\"BooleansOfPolygonsWithHolesApproximate\", &BooleansOfPolygonsWithHolesApproximate);\n  emscripten::function(\"BooleansOfPolygonsWithHolesExact\", &BooleansOfPolygonsWithHolesExact);\n\n  emscripten::function(\"ReverseFaceOrientationsOfSurfaceMesh\", &ReverseFaceOrientationsOfSurfaceMesh, emscripten::allow_raw_pointers());\n\n  emscripten::function(\"IsBadSurfaceMesh\", &IsBadSurfaceMesh, emscripten::allow_raw_pointers());\n\n  emscripten::function(\"FT__to_double\", &FT__to_double, emscripten::allow_raw_pointers());\n\n\n  emscripten::function(\"Surface_mesh__explore\", &Surface_mesh__explore, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__triangulate_faces\", &Surface_mesh__triangulate_faces, emscripten::allow_raw_pointers());\n\n  emscripten::function(\"FromPointsToSurfaceMesh\", &FromPointsToSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"FitPlaneToPoints\", &FitPlaneToPoints, emscripten::allow_raw_pointers());\n  emscripten::function(\"RemeshSurfaceMesh\", &RemeshSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"SubdivideSurfaceMesh\", &SubdivideSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"TransformSurfaceMesh\", &TransformSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"TransformSurfaceMeshByTransform\", &TransformSurfaceMeshByTransform, emscripten::allow_raw_pointers());\n  emscripten::function(\"FromSurfaceMeshToPolygonSoup\", &FromSurfaceMeshToPolygonSoup, emscripten::allow_raw_pointers());\n  emscripten::function(\"FromFunctionToSurfaceMesh\", &FromFunctionToSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"ComputeConvexHullAsSurfaceMesh\", &ComputeConvexHullAsSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"ComputeAlphaShapeAsSurfaceMesh\", &ComputeAlphaShapeAsSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"ComputeAlphaShape2AsPolygonSegments\", &ComputeAlphaShape2AsPolygonSegments, emscripten::allow_raw_pointers());\n  emscripten::function(\"OffsetOfPolygonWithHoles\", &OffsetOfPolygonWithHoles, emscripten::allow_raw_pointers());\n  emscripten::function(\"InsetOfPolygonWithHoles\", &InsetOfPolygonWithHoles, emscripten::allow_raw_pointers());\n  emscripten::function(\"MinkowskiDifferenceOfSurfaceMeshes\", &MinkowskiDifferenceOfSurfaceMeshes, emscripten::allow_raw_pointers());\n  emscripten::function(\"MinkowskiShellOfSurfaceMeshes\", &MinkowskiShellOfSurfaceMeshes, emscripten::allow_raw_pointers());\n  emscripten::function(\"MinkowskiSumOfSurfaceMeshes\", &MinkowskiSumOfSurfaceMeshes, emscripten::allow_raw_pointers());\n  emscripten::function(\"GrowSurfaceMesh\", &GrowSurfaceMesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__is_closed\", &Surface_mesh__is_closed, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__is_valid_halfedge_graph\", &Surface_mesh__is_valid_halfedge_graph, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__is_valid_face_graph\", &Surface_mesh__is_valid_face_graph, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__is_valid_polygon_mesh\", &Surface_mesh__is_valid_polygon_mesh, emscripten::allow_raw_pointers());\n  emscripten::function(\"Surface_mesh__bbox\", &Surface_mesh__bbox, emscripten::allow_raw_pointers());\n  emscripten::function(\"ArrangePathsApproximate\", &ArrangePathsApproximate, emscripten::allow_raw_pointers());\n  emscripten::function(\"ArrangePathsExact\", &ArrangePathsExact, emscripten::allow_raw_pointers());\n  emscripten::function(\"ArrangePolygonsWithHoles\", &ArrangePolygonsWithHoles, emscripten::allow_raw_pointers());\n  emscripten::function(\"SectionOfSurfaceMesh\", &SectionOfSurfaceMesh, emscripten::allow_raw_pointers());\n#endif\n}\n", "meta": {"hexsha": "ca62090ab51fd701b2428c609e6b573667642ea7", "size": 133101, "ext": "cc", "lang": "C++", "max_stars_repo_path": "algorithm/cgal/cgal.cc", "max_stars_repo_name": "jsxcad/JSxCAD", "max_stars_repo_head_hexsha": "fa788d9ddbd196fa591d91977ba20dc7ec645db5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-03-06T05:44:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T15:21:40.000Z", "max_issues_repo_path": "algorithm/cgal/cgal.cc", "max_issues_repo_name": "jsxcad/JSxCAD", "max_issues_repo_head_hexsha": "fa788d9ddbd196fa591d91977ba20dc7ec645db5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 85.0, "max_issues_repo_issues_event_min_datetime": "2019-03-18T01:13:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T10:26:50.000Z", "max_forks_repo_path": "algorithm/cgal/cgal.cc", "max_forks_repo_name": "jsxcad/JSxCAD", "max_forks_repo_head_hexsha": "fa788d9ddbd196fa591d91977ba20dc7ec645db5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T05:35:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T08:14:12.000Z", "avg_line_length": 39.1128416103, "max_line_length": 246, "alphanum_fraction": 0.6872224852, "num_tokens": 35280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8244619091240701, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.4090104657502651}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_POSE2D_HPP_\n#define RW_MATH_POSE2D_HPP_\n\n#if !defined(SWIG)\n#include <rw/math/Transform2D.hpp>\n\n#include <Eigen/Core>\n#endif\nnamespace rw { namespace math {\n\n    /** @addtogroup math */\n    /*@{*/\n\n    /**\n     * @brief A Pose3D @f$ \\mathbf{x}\\in \\mathbb{R}^6 @f$ describes a position\n     * and orientation in 3-dimensions.\n     *\n     * @f$ {\\mathbf{x}} = \\left[\n     *  \\begin{array}{c}\n     *  x \\\\\n     *  y \\\\\n     *  z \\\\\n     *  \\theta k_x \\\\\n     *  \\theta k_y \\\\\n     *  \\theta k_z\n     *  \\end{array}\n     *  \\right]\n     *  @f$\n     *\n     * where @f$ (x,y,z)@f$ is the 3d position and @f$ (\\theta k_x, \\theta k_y,\n     * \\theta k_z)@f$ describes the orientation in equal angle axis (EAA)\n     * format.\n     */\n    template< class T = double >\n\n    class Pose2D\n    {\n      public:\n        //! @brief Zero-initialized Pose2D.\n        Pose2D () : _pos (0, 0), _theta (0) {}\n\n        /**\n         * @brief Constructor.\n         * @param pos [in] the position.\n         * @param theta [in] the angle.\n         */\n        Pose2D (rw::math::Vector2D< T > pos, T theta) : _pos (pos), _theta (theta) {}\n\n        /**\n         * @brief Constructor.\n         * @param x [in] the value of the first position dimension.\n         * @param y [in] the value of the second position dimension.\n         * @param theta [in] the angle.\n         */\n        Pose2D (T x, T y, T theta) : _pos (x, y), _theta (theta) {}\n\n        /**\n         * @brief Constructor.\n         * @param transform [in] a 2D transform giving the pose.\n         */\n        Pose2D (const rw::math::Transform2D< T >& transform) :\n            _pos (transform.P ()), _theta (\n                                       // Sigh.\n                                       atan2 (transform.R () (1, 0), transform.R () (0, 0)))\n        {}\n\n        /**\n         * @brief Get the first dimension of the position vector.\n         * @return the position in the first dimension.\n         */\n        T& x () { return _pos[0]; }\n\n        /**\n         * @brief Get the second dimension of the position vector.\n         * @return the position in the second dimension.\n         */\n        T& y () { return _pos[1]; }\n\n        /**\n         * @brief Get the angle.\n         * @return the angle.\n         */\n        T& theta () { return _theta; }\n\n        /**\n         * @brief Get the position vector.\n         * @return the position.\n         */\n        rw::math::Vector2D< T >& getPos () { return _pos; }\n\n        //! @copydoc x()\n        T x () const { return _pos[0]; }\n\n        //! @copydoc y()\n        T y () const { return _pos[1]; }\n\n        //! @copydoc theta()\n        T theta () const { return _theta; }\n\n        //! @copydoc getPos()\n        const rw::math::Vector2D< T >& getPos () const { return _pos; }\n\n#if !defined(SWIG)\n        /**\n         * @brief Returns reference to vector element (x,y,theta)\n         *\n         * @param i [in] index in the vector \\f$i\\in \\{0,1,2\\} \\f$\n         *\n         * @return const reference to element\n         */\n        const T& operator() (size_t i) const\n        {\n            if (i < 2)\n                return _pos[i];\n            return _theta;\n        }\n\n        /**\n         * @brief Returns reference to vector element\n         *\n         * @param i [in] index in the vector \\f$i\\in \\{0,1\\} \\f$\n         *\n         * @return reference to element\n         */\n        T& operator() (size_t i)\n        {\n            if (i < 2)\n                return _pos[i];\n            return _theta;\n        }\n\n        /**\n         * @brief Returns reference to vector element\n         * @param i [in] index in the vector \\f$i\\in \\{0,1,2\\} \\f$\n         * @return const reference to element\n         */\n        const T& operator[] (size_t i) const\n        {\n            if (i < 2)\n                return _pos[i];\n            return _theta;\n        }\n\n        /**\n         * @brief Returns reference to vector element\n         * @param i [in] index in the vector \\f$i\\in \\{0,1,2\\} \\f$\n         * @return reference to element\n         */\n        T& operator[] (size_t i)\n        {\n            if (i < 2)\n                return _pos[i];\n            return _theta;\n        }\n#else\n        ARRAYOPERATOR (T);\n#endif\n        /**\n         * @brief The transform corresponding to the pose.\n         * @param pose [in] the pose.\n         * @return equivalent 2D transform.\n         */\n        static rw::math::Transform2D< T > transform (const Pose2D< T >& pose)\n        {\n            return rw::math::Transform2D< T > (rw::math::Vector2D< T > (pose.x (), pose.y ()),\n                                               rw::math::Rotation2D< T > (pose.theta ()));\n        }\n#if !defined(SWIG)\n        /**\n         * @brief Ouputs EAA to stream\n         * @param os [in/out] stream to use\n         * @param eaa [in] equivalent axis-angle\n         * @return the resulting stream\n         */\n        friend std::ostream& operator<< (std::ostream& os, const Pose2D< T >& pose)\n        {\n            return os << \" Ppse2D { x: \" << pose.x () << \", y: \" << pose.y ()\n                      << \", th: \" << pose.theta () << \"}\";\n        }\n#else\n        TOSTRING (rw::math::Pose2D< T >);\n#endif\n\n        /**\n         * @brief return a Eigen vector of (x, y, theta).\n         * @return Eigen vector.\n         */\n        // template<class T>\n        Eigen::Matrix< T, 3, 1 > e () const\n        {\n            Eigen::Matrix< T, 3, 1 > vec;\n            vec (0) = _pos (0);\n            vec (1) = _pos (1);\n            vec (2) = _theta;\n            return vec;\n        }\n\n      private:\n        rw::math::Vector2D< T > _pos;\n        T _theta;\n    };\n\n#if !defined(SWIG)\n    extern template class rw::math::Pose2D< double >;\n    extern template class rw::math::Pose2D< float >;\n#else\n    SWIG_DECLARE_TEMPLATE (Pose2Dd, rw::math::Pose2D< double >);\n    SWIG_DECLARE_TEMPLATE (Pose2Df, rw::math::Pose2D< float >);\n#endif\n    using Pose2Dd = Pose2D< double >;\n    using Pose2Df = Pose2D< float >;\n\n    /*@}*/\n}}    // namespace rw::math\n\nnamespace rw { namespace common {\n    class OutputArchive;\n    class InputArchive;\n    namespace serialization {\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::Pose2D\n         */\n        template<>\n        void write (const rw::math::Pose2D< double >& sobject, rw::common::OutputArchive& oarchive,\n                    const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::write\n         * @relatedalso rw::math::Pose2D\n         */\n        template<>\n        void write (const rw::math::Pose2D< float >& sobject, rw::common::OutputArchive& oarchive,\n                    const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Pose2D\n         */\n        template<>\n        void read (rw::math::Pose2D< double >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n        /**\n         * @copydoc rw::common::serialization::read\n         * @relatedalso rw::math::Pose2D\n         */\n        template<>\n        void read (rw::math::Pose2D< float >& sobject, rw::common::InputArchive& iarchive,\n                   const std::string& id);\n\n    }    // namespace serialization\n}}       // namespace rw::common\n\n#endif /* POSE2D_HPP_ */\n", "meta": {"hexsha": "5f9dd2904f5b95e77c7230922c6eb0b6619cd2bf", "size": 8172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/Pose2D.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/Pose2D.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/math/Pose2D.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9340659341, "max_line_length": 99, "alphanum_fraction": 0.4938815467, "num_tokens": 2125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.4089413254121543}}
{"text": "/* tsne.cc\n   Jeremy Barnes, 15 January 2010\n   Copyright (c) 2010 Jeremy Barnes.  All rights reserved.\n\n   Implementation of the t-SNE algorithm.\n*/\n\n#include \"tsne.h\"\n#include \"jml/stats/distribution.h\"\n#include \"jml/stats/distribution_ops.h\"\n#include \"jml/stats/distribution_simd.h\"\n#include \"jml/algebra/matrix_ops.h\"\n#include \"jml/arch/simd_vector.h\"\n#include <boost/tuple/tuple.hpp>\n#include \"jml/algebra/lapack.h\"\n#include <cmath>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/variate_generator.hpp>\n#include \"jml/utils/worker_task.h\"\n#include <boost/timer.hpp>\n#include \"jml/arch/timers.h\"\n#include \"jml/arch/sse2.h\"\n#include \"jml/arch/sse2_log.h\"\n#include \"jml/arch/cache.h\"\n#include \"jml/utils/guard.h\"\n#include <boost/bind.hpp>\n#include \"jml/utils/environment.h\"\n\nusing namespace std;\n\nnamespace ML {\n\ntemplate<typename Float>\nstruct V2D_Job {\n    const boost::multi_array<Float, 2> & X;\n    boost::multi_array<Float, 2> & D;\n    const Float * sum_X;\n    int i0, i1;\n    \n    V2D_Job(const boost::multi_array<Float, 2> & X,\n            boost::multi_array<Float, 2> & D,\n            const Float * sum_X,\n            int i0, int i1)\n        : X(X), D(D), sum_X(sum_X), i0(i0), i1(i1)\n    {\n    }\n\n    void operator () ()\n    {\n        int d = X.shape()[1];\n        \n        if (d == 2) {\n            unsigned i = i0;\n            for (;  i + 4 <= i1;  i += 4) {\n                D[i + 0][i + 0] = 0.0f;\n                D[i + 1][i + 1] = 0.0f;\n                D[i + 2][i + 2] = 0.0f;\n                D[i + 3][i + 3] = 0.0f;\n                \n                for (unsigned j = 0;  j < i;  ++j) {\n                    for (unsigned ii = 0;  ii < 4;  ++ii) {\n                        Float XXT\n                            = (X[i + ii][0] * X[j][0])\n                            + (X[i + ii][1] * X[j][1]);\n                        Float val = sum_X[i + ii] + sum_X[j] - 2.0f * XXT;\n                        D[i + ii][j] = val;\n                    }\n                }\n                \n                // finish off the diagonal\n                for (unsigned ii = 0;  ii < 4;  ++ii) {\n                    for (unsigned j = i;  j < i + ii;  ++j) {\n                        Float XXT\n                            = (X[i + ii][0] * X[j][0])\n                            + (X[i + ii][1] * X[j][1]);\n                        Float val = sum_X[i + ii] + sum_X[j] - 2.0f * XXT;\n                        D[i + ii][j] = val;\n                    }\n                }\n            }\n            for (;  i < i1;  ++i) {\n                D[i][i] = 0.0f;\n                \n                for (unsigned j = 0;  j < i;  ++j) {\n                    Float XXT = (X[i][0] * X[j][0]) + (X[i][1]) * (X[j][1]);\n                    Float val = sum_X[i] + sum_X[j] - 2.0f * XXT;\n                    D[i][j] = val;\n                }\n            }\n        }\n        else if (d < 8) {\n            for (unsigned i = i0;  i < i1;  ++i) {\n                D[i][i] = 0.0f;\n                for (unsigned j = 0;  j < i;  ++j) {\n                    float XXT = 0.0;\n                    for (unsigned k = 0;  k < d;  ++k)\n                        XXT += X[i][k] * X[j][k];\n                    \n                    Float val = sum_X[i] + sum_X[j] - 2.0f * XXT;\n                    D[i][j] = val;\n                }\n            }\n        }\n        else {\n            for (unsigned i = i0;  i < i1;  ++i) {\n                D[i][i] = 0.0f;\n                for (unsigned j = 0;  j < i;  ++j) {\n                    // accum in double precision for accuracy\n                    Float XXT = SIMD::vec_dotprod_dp(&X[i][0], &X[j][0], d);\n                    Float val = sum_X[i] + sum_X[j] - 2.0f * XXT;\n                    D[i][j] = val;\n                }\n            }\n        }\n    }\n};\n\ntemplate<typename Float>\nvoid\nvectors_to_distances(const boost::multi_array<Float, 2> & X,\n                     boost::multi_array<Float, 2> & D,\n                     bool fill_upper)\n{\n    // again, ||y_i - y_j||^2 \n    //     = sum_d ( y_id - y_jd )^2\n    //     = sum_d ( y_id^2 + y_jd^2 - 2 y_id y_jd)\n    //     = sum_d ( y_id^2) + sum_d(y_jd^2) - 2 sum_d(y_id y_jd)\n    //     = ||y_i||^2 + ||y_j||^2 - 2 sum_d(y_id y_jd)\n    \n    int n = X.shape()[0];\n\n    if (D.shape()[0] != n || D.shape()[1] != n)\n        throw Exception(\"D matrix should be square with (n x n) shape\");\n    \n    int d = X.shape()[1];\n\n    distribution<Float> sum_X(n);\n\n    if (d < 16) {\n        for (unsigned i = 0;  i < n;  ++i) {\n            double total = 0.0;  // accum in double precision for accuracy\n            for (unsigned j = 0;  j < d;  ++j)\n                total += X[i][j] * X[i][j];\n            sum_X[i] = total;\n        }\n    }\n    else {\n        for (unsigned i = 0;  i < n;  ++i)\n            sum_X[i] = SIMD::vec_dotprod_dp(&X[i][0], &X[i][0], d);\n    }\n    \n    Worker_Task & worker = Worker_Task::instance(num_threads() - 1);\n\n    int group;\n    {\n        int parent = -1;  // no parent group\n        group = worker.get_group(NO_JOB, \"\", parent);\n        Call_Guard guard(boost::bind(&Worker_Task::unlock_group,\n                                     boost::ref(worker),\n                                     group));\n        \n        int chunk_size = 64;\n        \n        for (int i = n;  i > 0;  i -= chunk_size) {\n            int i0 = max(0, i - chunk_size);\n            int i1 = i;\n            \n            worker.add(V2D_Job<Float>(X, D, &sum_X[0], i0, i1),\n                       \"\", group);\n        }\n    }\n    \n    worker.run_until_finished(group);\n\n    if (fill_upper)\n        copy_lower_to_upper(D);\n}\n\nvoid\nvectors_to_distances(const boost::multi_array<float, 2> & X,\n                     boost::multi_array<float, 2> & D,\n                     bool fill_upper)\n{\n    return vectors_to_distances<float>(X, D, fill_upper);\n}\n\nvoid\nvectors_to_distances(const boost::multi_array<double, 2> & X,\n                     boost::multi_array<double, 2> & D,\n                     bool fill_upper)\n{\n    return vectors_to_distances<double>(X, D, fill_upper);\n}\n\ntemplate<typename Float>\ndouble\nperplexity(const distribution<Float> & p)\n{\n    double total = 0.0;\n    for (unsigned i = 0;  i < p.size();  ++i)\n        if (p[i] != 0.0) total -= p[i] * log(p[i]);\n    return exp(total);\n}\n\n/** Compute the perplexity and the P for a given value of beta. */\ntemplate<typename Float>\nstd::pair<double, distribution<Float> >\nperplexity_and_prob(const distribution<Float> & D, double beta = 1.0,\n                    int i = -1)\n{\n    distribution<Float> P(D.size());\n    SIMD::vec_exp(&D[0], -beta, &P[0], D.size());\n    if (i != -1) P[i] = 0;\n    double tot = P.total();\n\n    if (!isfinite(tot) || tot == 0) {\n#if 0\n        cerr << \"beta = \" << beta << endl;\n        cerr << \"D = \" << D << endl;\n        cerr << \"tot = \" << tot << endl;\n        cerr << \"i = \" << i << endl;\n        cerr << \"P = \" << P << endl;\n#endif\n        throw Exception(\"non-finite total for perplexity\");\n    }\n\n    double H = log(tot) + beta * D.dotprod(P) / tot;\n    P *= 1.0 / tot;\n\n    if (!isfinite(P.total())) {\n#if 0\n        cerr << \"beta = \" << beta << endl;\n        cerr << \"D = \" << D << endl;\n        cerr << \"tot = \" << tot << endl;\n        cerr << \"i = \" << i << endl;\n#endif\n        throw Exception(\"non-finite total for perplexity\");\n    }\n\n\n    return make_pair(H, P);\n}\n\nstd::pair<double, distribution<float> >\nperplexity_and_prob(const distribution<float> & D, double beta,\n                    int i)\n{\n    return perplexity_and_prob<float>(D, beta, i);\n}\n\nstd::pair<double, distribution<double> >\nperplexity_and_prob(const distribution<double> & D, double beta,\n                    int i)\n{\n    return perplexity_and_prob<double>(D, beta, i);\n}\n\n\n/** Calculate the beta for a single point.\n    \n    \\param Di     The i-th row of the D matrix, for which we want to calculate\n                  the probabilities.\n    \\param i      Which row number it is.\n\n    \\returns      The i-th row of the P matrix, which has the distances in D\n                  converted to probabilities with the given perplexity.\n */\nstd::pair<distribution<float>, double>\nbinary_search_perplexity(const distribution<float> & Di,\n                         double required_perplexity,\n                         int i,\n                         double tolerance = 1e-5)\n{\n    double betamin = -INFINITY, betamax = INFINITY;\n    double beta = 1.0;\n\n    distribution<float> P;\n    double log_perplexity;\n    double log_required_perplexity = log(required_perplexity);\n\n    boost::tie(log_perplexity, P) = perplexity_and_prob(Di, beta, i);\n\n    bool verbose = false;\n\n    if (verbose)\n        cerr << \"iter currperp targperp     diff toleranc   betamin     beta  betamax\" << endl;\n    \n    for (unsigned iter = 0;  iter != 50;  ++iter) {\n        if (verbose) \n            cerr << format(\"%4d %8.4f %8.4f %8.4f %8.4f  %8.4f %8.4f %8.4f\\n\",\n                           iter,\n                           log_perplexity, log_required_perplexity,\n                           fabs(log_perplexity - log_required_perplexity),\n                           tolerance,\n                           betamin, beta, betamax);\n        \n        if (fabs(log_perplexity - log_required_perplexity) < tolerance)\n            break;\n\n        if (log_perplexity > log_required_perplexity) {\n            betamin = beta;\n            if (!isfinite(betamax))\n                beta *= 2;\n            else beta = (beta + betamax) * 0.5;\n        }\n        else {\n            betamax = beta;\n            if (!isfinite(betamin))\n                beta /= 2;\n            else beta = (beta + betamin) * 0.5;\n        }\n        \n        boost::tie(log_perplexity, P) = perplexity_and_prob(Di, beta, i);\n    }\n\n    return make_pair(P, beta);\n}\n\nstruct Distance_To_Probabilities_Job {\n\n    boost::multi_array<float, 2> & D;\n    double tolerance;\n    double perplexity;\n    boost::multi_array<float, 2> & P;\n    distribution<float> & beta;\n    int i0;\n    int i1;\n\n    Distance_To_Probabilities_Job(boost::multi_array<float, 2> & D,\n                                  double tolerance,\n                                  double perplexity,\n                                  boost::multi_array<float, 2> & P,\n                                  distribution<float> & beta,\n                                  int i0,\n                                  int i1)\n        : D(D), tolerance(tolerance), perplexity(perplexity),\n          P(P), beta(beta), i0(i0), i1(i1)\n    {\n    }\n\n    void operator () ()\n    {\n        int n = D.shape()[0];\n\n        for (unsigned i = i0;  i < i1;  ++i) {\n            //cerr << \"i = \" << i << endl;\n            //if (i % 250 == 0)\n            //    cerr << \"P-values for point \" << i << \" of \" << n << endl;\n            \n            distribution<float> D_row(&D[i][0], &D[i][0] + n);\n            distribution<float> P_row;\n\n            try {\n                boost::tie(P_row, beta[i])\n                    = binary_search_perplexity(D_row, perplexity, i, tolerance);\n            } catch (const std::exception & exc) {\n                P_row = D_row;\n                P_row[i] = 1000000;\n                P_row = (P_row == P_row.min());\n                std::fill(P_row.begin(), P_row.end(), 1.0);\n                P_row[i] = 0.0;\n                P_row.normalize();\n            }\n            \n            if (P_row.size() != n)\n                throw Exception(\"P_row has the wrong size\");\n            if (P_row[i] != 0.0) {\n                cerr << \"i = \" << i << endl;\n                //cerr << \"D_row = \" << D_row << endl;\n                //cerr << \"P_row = \" << P_row << endl;\n                cerr << \"P_row.total() = \" << P_row.total() << endl;\n                cerr << \"P_row[i] = \" << P_row[i] << endl;\n                throw Exception(\"P_row diagonal entry was not zero\");\n            }\n\n            std::copy(P_row.begin(), P_row.end(), &P[i][0]);\n        }\n    }\n};\n\n\n/* Given a matrix of distances, convert to probabilities */\nboost::multi_array<float, 2>\ndistances_to_probabilities(boost::multi_array<float, 2> & D,\n                           double tolerance,\n                           double perplexity)\n{\n    int n = D.shape()[0];\n    if (D.shape()[1] != n)\n        throw Exception(\"D is not square\");\n\n    boost::multi_array<float, 2> P(boost::extents[n][n]);\n    distribution<float> beta(n, 1.0);\n\n    Worker_Task & worker = Worker_Task::instance(num_threads() - 1);\n\n    int group;\n    {\n        int parent = -1;  // no parent group\n        group = worker.get_group(NO_JOB, \"\", parent);\n        Call_Guard guard(boost::bind(&Worker_Task::unlock_group,\n                                     boost::ref(worker),\n                                     group));\n        \n        int chunk_size = 64;\n        \n        for (int i = 0;  i < n;  i += chunk_size) {\n            int i0 = i;\n            int i1 = min(n, i + chunk_size);\n            \n            worker.add(Distance_To_Probabilities_Job\n                       (D, tolerance, perplexity, P, beta, i0, i1),\n                       \"\", group);\n        }\n    }\n\n    worker.run_until_finished(group);\n\n    cerr << \"mean sigma is \" << sqrt(1.0 / beta).mean() << endl;\n\n    return P;\n}\n\nboost::multi_array<float, 2>\npca(boost::multi_array<float, 2> & coords, int num_dims)\n{\n    // TODO: normalize the input coordinates (especially if it seems to be\n    // ill conditioned)\n\n    int nx = coords.shape()[0];\n    int nd = coords.shape()[1];\n\n    int nvalues = std::min(nd, nx);\n\n    int ndr = std::min(nvalues, num_dims);\n\n    if (ndr < num_dims)\n        throw Exception(\"svd_reduction: num_dims not low enough\");\n        \n    distribution<float> svalues(nvalues);\n    boost::multi_array<float, 2> lvectorsT(boost::extents[nvalues][nd]);\n    boost::multi_array<float, 2> rvectors(boost::extents[nx][nvalues]);\n\n    int res = LAPack::gesdd(\"S\", nd, nx,\n                            coords.data(), nd,\n                            &svalues[0],\n                            &lvectorsT[0][0], nd,\n                            &rvectors[0][0], nvalues);\n    \n    // If some vectors are singular, ignore them\n    // TODO: do...\n        \n    if (res != 0)\n        throw Exception(\"gesdd returned non-zero\");\n        \n    boost::multi_array<float, 2> result(boost::extents[nx][ndr]);\n    for (unsigned i = 0;  i < nx;  ++i)\n        std::copy(&rvectors[i][0], &rvectors[i][0] + ndr, &result[i][0]);\n\n    return result;\n}\n\ndouble calc_D_row(float * Di, int n)\n{\n    unsigned i = 0;\n\n    double total = 0.0;\n\n    if (false) ;\n    else if (n >= 8) {\n        using namespace SIMD;\n\n        v2df rr = vec_splat(0.0);\n        \n        v4sf one = vec_splat(1.0f);\n\n        __builtin_prefetch(Di + i + 0, 1, 3);\n        __builtin_prefetch(Di + i + 16, 1, 3);\n        __builtin_prefetch(Di + i + 32, 1, 3);\n\n        for (; i + 16 <= n;  i += 16) {\n            __builtin_prefetch(Di + i + 48, 1, 3);\n\n            v4sf xxxx0 = __builtin_ia32_loadups(Di + i + 0);\n            v4sf xxxx1 = __builtin_ia32_loadups(Di + i + 4);\n            xxxx0      = xxxx0 + one;\n            xxxx1      = xxxx1 + one;\n            xxxx0      = one / xxxx0;\n            v4sf xxxx2 = __builtin_ia32_loadups(Di + i + 8);\n            xxxx1      = one / xxxx1;\n            __builtin_ia32_storeups(Di + i + 0, xxxx0);\n            xxxx2      = xxxx2 + one;\n            v2df xx0a, xx0b;  vec_f2d(xxxx0, xx0a, xx0b);\n            __builtin_ia32_storeups(Di + i + 4, xxxx1);\n            xx0a       = xx0a + xx0b;\n            rr         = rr + xx0a;\n            v4sf xxxx3 = __builtin_ia32_loadups(Di + i + 12);\n            v2df xx1a, xx1b;  vec_f2d(xxxx1, xx1a, xx1b);\n            xxxx2      = one / xxxx2;\n            xx1a       = xx1a + xx1b;\n            __builtin_ia32_storeups(Di + i + 8, xxxx2);\n            rr         = rr + xx1a;\n            v2df xx2a, xx2b;  vec_f2d(xxxx2, xx2a, xx2b);\n            xxxx3      = xxxx3 + one;\n            xx2a       = xx2a + xx2b;\n            xxxx3      = one / xxxx3;\n            rr         = rr + xx2a;\n            v2df xx3a, xx3b;  vec_f2d(xxxx3, xx3a, xx3b);\n            __builtin_ia32_storeups(Di + i + 12, xxxx3);\n            xx3a       = xx3a + xx3b;\n            rr         = rr + xx3a;\n        }\n\n        for (; i + 4 <= n;  i += 4) {\n            v4sf xxxx0 = __builtin_ia32_loadups(Di + i + 0);\n            xxxx0      = xxxx0 + one;\n            xxxx0      = one / xxxx0;\n            __builtin_ia32_storeups(Di + i + 0, xxxx0);\n\n            v2df xx0a, xx0b;\n            vec_f2d(xxxx0, xx0a, xx0b);\n\n            rr      = rr + xx0a;\n            rr      = rr + xx0b;\n        }\n\n        double results[2];\n        *(v2df *)results = rr;\n\n        total = (results[0] + results[1]);\n    }\n    \n    for (;  i < n;  ++i) {\n        Di[i] = 1.0f / (1.0f + Di[i]);\n        total += Di[i];\n    }\n\n    return total;\n}\n\nnamespace {\n\nEnv_Option<bool> PROFILE_TSNE(\"PROFILE_TSNE\", false);\n\ndouble t_v2d = 0.0, t_D = 0.0, t_dY = 0.0, t_update = 0.0;\ndouble t_recenter = 0.0, t_cost = 0.0, t_PmQxD = 0.0, t_clu = 0.0;\ndouble t_stiffness = 0.0;\nstruct AtEnd {\n    ~AtEnd()\n    {\n        if (!PROFILE_TSNE) return;\n\n        cerr << \"tsne core profile:\" << endl;\n        cerr << \"  v2d:        \" << t_v2d << endl;\n        cerr << \"  stiffness:\" << t_stiffness << endl;\n        cerr << \"    D         \" << t_D << endl;\n        cerr << \"    (P-Q)D    \" << t_PmQxD << endl;\n        cerr << \"    clu       \" << t_clu << endl;\n        cerr << \"  dY:         \" << t_dY << endl;\n        cerr << \"  update:     \" << t_update << endl;\n        cerr << \"  recenter:   \" << t_recenter << endl;\n        cerr << \"  cost:       \" << t_cost << endl;\n    }\n} atend;\n\n} // file scope\n\nstruct Calc_D_Job {\n\n    boost::multi_array<float, 2> & D;\n    int i0;\n    int i1;\n    double * d_totals;\n\n    Calc_D_Job(boost::multi_array<float, 2> & D,\n               int i0,\n               int i1,\n               double * d_totals)\n        : D(D), i0(i0), i1(i1), d_totals(d_totals)\n    {\n    }\n\n    void operator () ()\n    {\n        for (unsigned i = i0;  i < i1;  ++i) {\n            d_totals[i] = 2.0 * calc_D_row(&D[i][0], i);\n            D[i][i] = 0.0f;\n        }\n    }\n};\n\ndouble calc_stiffness_row(float * Di, const float * Pi, float qfactor,\n                          float min_prob, int n, bool calc_costs)\n{\n    double cost = 0.0;\n\n    unsigned i = 0;\n\n    if (false) ;\n    else if (true) {\n        using namespace SIMD;\n\n        v4sf mmmm = vec_splat(min_prob);\n        v4sf ffff = vec_splat(qfactor);\n\n        v2df total = vec_splat(0.0);\n\n        for (; i + 4 <= n;  i += 4) {\n\n            v4sf dddd0 = __builtin_ia32_loadups(Di + i + 0);\n            v4sf pppp0 = __builtin_ia32_loadups(Pi + i + 0);\n            v4sf qqqq0 = __builtin_ia32_maxps(mmmm, dddd0 * ffff);\n            v4sf ssss0 = (pppp0 - qqqq0) * dddd0;\n            __builtin_ia32_storeups(Di + i + 0, ssss0);\n            if (JML_LIKELY(!calc_costs)) continue;\n\n            v4sf pqpq0  = pppp0 / qqqq0;\n            v4sf lpq0   = sse2_logf_unsafe(pqpq0);\n            v4sf cccc0  = pppp0 * lpq0;\n            cccc0 = cccc0 + cccc0;\n\n            v2df cc0a, cc0b;\n            vec_f2d(cccc0, cc0a, cc0b);\n\n            total   = total + cc0a;\n            total   = total + cc0b;\n        }\n\n        double results[2];\n        *(v2df *)results = total;\n        \n        cost = results[0] + results[1];\n    }\n\n    for (;  i < n;  ++i) {\n        float d = Di[i];\n        float p = Pi[i];\n        float q = std::max(min_prob, d * qfactor);\n        Di[i] = (p - q) * d;\n        if (calc_costs) cost += 2.0 * p * logf(p / q);\n    }\n\n    return cost;\n}\n\nstruct Calc_Stiffness_Job {\n\n    boost::multi_array<float, 2> & D;\n    const boost::multi_array<float, 2> & P;\n    float min_prob;\n    float qfactor;\n    double * costs;\n    int i0, i1;\n\n    Calc_Stiffness_Job(boost::multi_array<float, 2> & D,\n                       const boost::multi_array<float, 2> & P,\n                       float min_prob,\n                       float qfactor,\n                       double * costs,\n                       int i0, int i1)\n        : D(D), P(P), min_prob(min_prob),\n          qfactor(qfactor), costs(costs), i0(i0), i1(i1)\n    {\n    }\n\n    void operator () ()\n    {\n        for (unsigned i = i0;  i < i1;  ++i) {\n            double cost \n                = calc_stiffness_row(&D[i][0], &P[i][0],\n                                     qfactor, min_prob, i,\n                                     costs);\n            if (costs) costs[i] = cost;\n        }\n    }\n};\n\ndouble tsne_calc_stiffness(boost::multi_array<float, 2> & D,\n                           const boost::multi_array<float, 2> & P,\n                           float min_prob,\n                           bool calc_cost)\n{\n    boost::timer t;\n\n    int n = D.shape()[0];\n    if (D.shape()[1] != n)\n        throw Exception(\"D has wrong shape\");\n\n    if (P.shape()[0] != n || P.shape()[1] != n)\n        throw Exception(\"P has wrong shape\");\n\n    double d_totals[n];\n\n    Worker_Task & worker = Worker_Task::instance(num_threads() - 1);\n\n    int group;\n    {\n        int parent = -1;  // no parent group\n        group = worker.get_group(NO_JOB, \"\", parent);\n        Call_Guard guard(boost::bind(&Worker_Task::unlock_group,\n                                     boost::ref(worker),\n                                     group));\n        \n        int chunk_size = 64;\n        \n        for (int i = n;  i > 0;  i -= chunk_size) {\n            int i0 = max(0, i - chunk_size);\n            int i1 = i;\n            \n            worker.add(Calc_D_Job(D, i0, i1, d_totals),\n                       \"\", group);\n        }\n    }\n    \n    worker.run_until_finished(group);\n\n    double d_total_offdiag = SIMD::vec_sum(d_totals, n);\n\n    t_D += t.elapsed();  t.restart();\n    \n    // Cost accumulated for each row\n    double row_costs[n];\n\n    // Q matrix: q_{i,j} = d_{ij} / sum_{k != l} d_{kl}\n    float qfactor = 1.0 / d_total_offdiag;\n\n    {\n        int parent = -1;  // no parent group\n        group = worker.get_group(NO_JOB, \"\", parent);\n        Call_Guard guard(boost::bind(&Worker_Task::unlock_group,\n                                     boost::ref(worker),\n                                     group));\n        \n        int chunk_size = 64;\n        \n        for (int i = n;  i > 0;  i -= chunk_size) {\n            int i0 = max(0, i - chunk_size);\n            int i1 = i;\n            \n            worker.add(Calc_Stiffness_Job\n                       (D, P, min_prob, qfactor,\n                        (calc_cost ? row_costs : (double *)0), i0, i1),\n                       \"\", group);\n        }\n    }\n\n    worker.run_until_finished(group);\n\n    double cost = 0.0;\n    if (calc_cost) cost = SIMD::vec_sum(row_costs, n);\n\n    t_PmQxD += t.elapsed();  t.restart();\n    \n    copy_lower_to_upper(D);\n    \n    t_clu += t.elapsed();  t.restart();\n\n    return cost;\n}\n\ninline void\ncalc_dY_rows_2d(boost::multi_array<float, 2> & dY,\n                const boost::multi_array<float, 2> & PmQxD,\n                const boost::multi_array<float, 2> & Y,\n                int i, int n)\n{\n#if 1\n    using namespace SIMD;\n\n    v4sf totals01 = vec_splat(0.0f), totals23 = totals01;\n    v4sf four = vec_splat(4.0f);\n\n    for (unsigned j = 0;  j < n;  ++j) {\n        //v4sf ffff = { PmQxD[i + 0][j], PmQxD[i + 1][j],\n        //              PmQxD[i + 2][j], PmQxD[i + 3][j] };\n        // TODO: expand inplace\n\n        v4sf ffff01 = { PmQxD[i + 0][j], PmQxD[i + 0][j],\n                        PmQxD[i + 1][j], PmQxD[i + 1][j] };\n        v4sf ffff23 = { PmQxD[i + 2][j], PmQxD[i + 2][j],\n                        PmQxD[i + 3][j], PmQxD[i + 3][j] };\n\n        // TODO: load once and shuffle into position\n        v4sf yjyj   = { Y[j][0], Y[j][1], Y[j][0], Y[j][1] };\n\n        ffff01 = ffff01 * four;\n        ffff23 = ffff23 * four;\n        \n        v4sf yi01   = __builtin_ia32_loadups(&Y[i][0]);\n        v4sf yi23   = __builtin_ia32_loadups(&Y[i + 2][0]);\n\n        v4sf xxxx01 = ffff01 * (yi01 - yjyj);\n        v4sf xxxx23 = ffff23 * (yi23 - yjyj);\n        \n        totals01 += xxxx01;\n        totals23 += xxxx23;\n    }\n\n    __builtin_ia32_storeups(&dY[i][0], totals01);\n    __builtin_ia32_storeups(&dY[i + 2][0], totals23);\n\n#else\n    enum { b = 4 };\n\n    float totals[b][2];\n    for (unsigned ii = 0;  ii < b;  ++ii)\n        totals[ii][0] = totals[ii][1] = 0.0f;\n            \n    for (unsigned j = 0;  j < n;  ++j) {\n        float Yj0 = Y[j][0];\n        float Yj1 = Y[j][1];\n        \n        for (unsigned ii = 0;  ii < b;  ++ii) {\n            float factor = 4.0f * PmQxD[i + ii][j];\n            totals[ii][0] += factor * (Y[i + ii][0] - Yj0);\n            totals[ii][1] += factor * (Y[i + ii][1] - Yj1);\n        }\n    }\n    \n    for (unsigned ii = 0;  ii < b;  ++ii) {\n        dY[i + ii][0] = totals[ii][0];\n        dY[i + ii][1] = totals[ii][1];\n    }\n#endif\n}\n\ninline void\ncalc_dY_row_2d(float * dYi, const float * PmQxDi,\n               const boost::multi_array<float, 2> & Y,\n               int i,\n               int n)\n{\n    float total0 = 0.0f, total1 = 0.0f;\n    for (unsigned j = 0;  j < n;  ++j) {\n        float factor = 4.0f * PmQxDi[j];\n        total0 += factor * (Y[i][0] - Y[j][0]);\n        total1 += factor * (Y[i][1] - Y[j][1]);\n    }\n    \n    dYi[0] = total0;\n    dYi[1] = total1;\n}\n\n\nstruct Calc_Gradient_Job {\n    boost::multi_array<float, 2> & dY;\n    const boost::multi_array<float, 2> & Y;\n    const boost::multi_array<float, 2> & PmQxD;\n    int i0, i1;\n\n    Calc_Gradient_Job(boost::multi_array<float, 2> & dY,\n                      const boost::multi_array<float, 2> & Y,\n                      const boost::multi_array<float, 2> & PmQxD,\n                      int i0,\n                      int i1)\n        : dY(dY),\n          Y(Y),\n          PmQxD(PmQxD),\n          i0(i0),\n          i1(i1)\n    {\n    }\n    \n    void operator () ()\n    {\n        int n = Y.shape()[0];\n        int d = Y.shape()[1];\n\n        if (d == 2) {\n            unsigned i = i0;\n            \n            for (;  i + 4 <= i1;  i += 4)\n                calc_dY_rows_2d(dY, PmQxD, Y, i, n);\n            \n            for (; i < i1;  ++i)\n                calc_dY_row_2d(&dY[i][0], &PmQxD[i][0], Y, i, n);\n        }\n        else {\n            for (unsigned i = i0;  i < i1;  ++i) {\n                for (unsigned k = 0;  k < d;  ++k) {\n                    float Yik = Y[i][k];\n                    float total = 0.0;\n                    for (unsigned j = 0;  j < n;  ++j) {\n                        float factor = 4.0f * PmQxD[i][j];\n                        float Yjk = Y[j][k];\n                        total += factor * (Yik - Yjk);\n                    }\n                    dY[i][k] = total;\n                }\n            }\n        }\n    }\n};\n\n\nvoid tsne_calc_gradient(boost::multi_array<float, 2> & dY,\n                        const boost::multi_array<float, 2> & Y,\n                        const boost::multi_array<float, 2> & PmQxD)\n{\n    // Gradient\n    // Implements formula 5 in (Van der Maaten and Hinton, 2008)\n    // dC/dy_i = 4 * sum_j ( (p_ij - q_ij)(y_i - y_j)d_ij )\n\n    \n    int n = Y.shape()[0];\n    int d = Y.shape()[1];\n    \n    if (dY.shape()[0] != n || dY.shape()[1] != d)\n        throw Exception(\"dY matrix has wrong shape\");\n\n    if (PmQxD.shape()[0] != n || PmQxD.shape()[1] != n)\n        throw Exception(\"PmQxD matrix has wrong shape\");\n\n    Worker_Task & worker = Worker_Task::instance(num_threads() - 1);\n\n    int group;\n    {\n        int parent = -1;  // no parent group\n        group = worker.get_group(NO_JOB, \"\", parent);\n        Call_Guard guard(boost::bind(&Worker_Task::unlock_group,\n                                     boost::ref(worker),\n                                     group));\n        \n        int chunk_size = 64;\n        \n        for (unsigned i = 0;  i < n;  i += chunk_size) {\n            int i0 = i;\n            int i1 = min(i0 + chunk_size, n);\n            \n            worker.add(Calc_Gradient_Job(dY, Y, PmQxD, i0, i1),\n                       \"\", group);\n        }\n    }\n    \n    worker.run_until_finished(group);\n}\n\nvoid tsne_update(boost::multi_array<float, 2> & Y,\n                 boost::multi_array<float, 2> & dY,\n                 boost::multi_array<float, 2> & iY,\n                 boost::multi_array<float, 2> & gains,\n                 bool first_iter,\n                 float momentum,\n                 float eta,\n                 float min_gain)\n{\n    int n = Y.shape()[0];\n    int d = Y.shape()[1];\n\n    // Implement scheme in Jacobs, 1988.  If we go in the same direction as\n    // last time, we increase the learning speed of the parameter a bit.\n    // If on the other hand the direction changes, we reduce exponentially\n    // the rate.\n    \n    for (unsigned i = 0;  !first_iter && i < n;  ++i) {\n        // We use != here as we gradients in dY are the negatives of what\n        // we want.\n        for (unsigned j = 0;  j < d;  ++j) {\n            if (dY[i][j] * iY[i][j] < 0.0f)\n                gains[i][j] = gains[i][j] + 0.2f;\n            else gains[i][j] = gains[i][j] * 0.8f;\n            gains[i][j] = std::max(min_gain, gains[i][j]);\n        }\n    }\n\n    for (unsigned i = 0;  i < n;  ++i)\n        for (unsigned j = 0;  j < d;  ++j)\n            iY[i][j] = momentum * iY[i][j] - (eta * gains[i][j] * dY[i][j]);\n    Y = Y + iY;\n}\n    \ntemplate<typename Float>\nvoid recenter_about_origin(boost::multi_array<Float, 2> & Y)\n{\n    int n = Y.shape()[0];\n    int d = Y.shape()[1];\n\n    // Recenter Y values about the origin\n    double Y_means[d];\n    std::fill(Y_means, Y_means + d, 0.0);\n    for (unsigned i = 0;  i < n;  ++i)\n        for (unsigned j = 0;  j < d;  ++j)\n            Y_means[j] += Y[i][j];\n    \n    Float n_recip = 1.0f / n;\n    \n    for (unsigned i = 0;  i < n;  ++i)\n        for (unsigned j = 0;  j < d;  ++j)\n            Y[i][j] -= Y_means[j] * n_recip;\n}\n\nboost::multi_array<float, 2>\ntsne(const boost::multi_array<float, 2> & probs,\n     int num_dims,\n     const TSNE_Params & params,\n     const TSNE_Callback & callback)\n{\n    int n = probs.shape()[0];\n    if (n != probs.shape()[1])\n        throw Exception(\"probabilities were the wrong shape\");\n\n    int d = num_dims;\n\n    boost::mt19937 rng;\n    boost::normal_distribution<float> norm;\n\n    boost::variate_generator<boost::mt19937,\n                             boost::normal_distribution<float> >\n        randn(rng, norm);\n\n    double min_perp = INFINITY;\n    double max_perp = 0.0;\n    double total_perp = 0.0;\n    double total_log_perp = 0.0;\n\n    for (unsigned i = 0;  i < n;  ++i) {\n        distribution<float> P_row(&probs[i][0], &probs[i][0] + n);\n        double perp = perplexity(P_row);\n        min_perp = std::min(min_perp, perp);\n        max_perp = std::max(max_perp, perp);\n        total_perp += perp;\n        total_log_perp += log(perp);\n    }\n    \n    cerr << \"input perplexity: min \" << min_perp\n         << \" max: \" << max_perp << \" average: \" << total_perp / n\n         << \" avg log: \" << total_log_perp / n\n         << \" total log: \" << total_log_perp << endl;\n        \n\n    boost::multi_array<float, 2> Y(boost::extents[n][d]);\n    for (unsigned i = 0;  i < n;  ++i)\n        for (unsigned j = 0;  j < d;  ++j)\n            Y[i][j] = 0.01 * randn();\n\n    // Symmetrize and probabilize P\n    boost::multi_array<float, 2> P = probs + transpose(probs);\n\n    // TODO: symmetric so only need to total the upper diagonal\n    double sumP = 0.0;\n    for (unsigned i = 0;  i < n;  ++i)\n        sumP += 2.0 * SIMD::vec_sum_dp(&P[i][0], i);\n    \n    // Factor that P should be multiplied by in all calculations\n    // We boost it by 4 in early iterations to force the clusters to be\n    // spread apart\n    float pfactor = 4.0 / sumP;\n\n    // TODO: do we need this?   P = Math.maximum(P, 1e-12);\n    for (unsigned i = 0;  i < n;  ++i)\n        for (unsigned j = 0;  j < n;  ++j)\n            P[i][j] = std::max((i != j) * pfactor * P[i][j], 1e-12f);\n\n    Timer timer;\n\n    // Pseudo-distance array for reduced space.  Q = D * qfactor\n    boost::multi_array<float, 2> D(boost::extents[n][n]);\n\n    // Probabilitiy density array\n    //boost::multi_array<float, 2> Q(boost::extents[n][n]);\n\n    // Stiffness array\n    //boost::multi_array<float, 2> PmQxD(boost::extents[n][n]);\n\n    // Y delta\n    boost::multi_array<float, 2> dY(boost::extents[n][d]);\n\n    // Last change in Y; so that we can see if we're going in the same dir\n    boost::multi_array<float, 2> iY(boost::extents[n][d]);\n\n    // Per-variable factors to multiply the gradient by to improve convergence\n    boost::multi_array<float, 2> gains(boost::extents[n][d]);\n    std::fill(gains.data(), gains.data() + gains.num_elements(), 1.0f);\n\n    if (callback\n        && !callback(-1, INFINITY, \"init\")) return Y;\n    \n    for (int iter = 0;  iter < params.max_iter;  ++iter) {\n\n        boost::timer t;\n\n        /*********************************************************************/\n        // Pairwise affinities Qij\n        // Implements formula 4 in (Van der Maaten and Hinton, 2008)\n        // q_{ij} = d_{ij} / sum_{k,l, k != l} d_{kl}\n        // where d_{ij} = 1 / (1 + ||y_i - y_j||^2)\n\n        // TODO: these will all be symmetric; we could save lots of work by\n        // using upper/lower diagonal matrices.\n\n        vectors_to_distances(Y, D, false /* fill_upper */);\n\n        t_v2d += t.elapsed();  t.restart();\n        \n        if (callback\n            && !callback(iter, INFINITY, \"v2d\")) return Y;\n\n        // Do we calculate the cost?\n        bool calc_cost = (iter + 1) % 100 == 0 || iter == params.max_iter - 1;\n\n        double cost = tsne_calc_stiffness(D, P, params.min_prob, calc_cost);\n\n        if (callback\n            && !callback(iter, INFINITY, \"stiffness\")) return Y;\n\n        t_stiffness += t.elapsed();  t.restart();\n\n        // D is now the stiffness\n        const boost::multi_array<float, 2> & stiffness = D;\n\n        \n        /*********************************************************************/\n        // Gradient\n        // Implements formula 5 in (Van der Maaten and Hinton, 2008)\n        // dC/dy_i = 4 * sum_j ( (p_ij - q_ij)(y_i - y_j)d_ij )\n\n        tsne_calc_gradient(dY, Y, stiffness);\n\n        t_dY += t.elapsed();  t.restart();\n\n        if (callback\n            && !callback(iter, INFINITY, \"gradient\")) return Y;\n\n\n        /*********************************************************************/\n        // Update\n\n        float momentum = (iter < 20\n                          ? params.initial_momentum\n                          : params.final_momentum);\n\n        tsne_update(Y, dY, iY, gains, iter == 0, momentum, params.eta,\n                    params.min_gain);\n\n        if (callback\n            && !callback(iter, INFINITY, \"update\")) return Y;\n\n        t_update += t.elapsed();  t.restart();\n\n\n        /*********************************************************************/\n        // Recenter about the origin\n\n        recenter_about_origin(Y);\n\n        if (callback\n            && !callback(iter, INFINITY, \"recenter\")) return Y;\n\n        t_recenter += t.elapsed();  t.restart();\n\n\n        /*********************************************************************/\n        // Calculate cost\n\n        if ((iter + 1) % 100 == 0 || iter == params.max_iter - 1) {\n            cerr << format(\"iteration %4d cost %6.3f  \",\n                           iter + 1, cost)\n                 << timer.elapsed() << endl;\n            timer.restart();\n        }\n        \n        t_cost += t.elapsed();  t.restart();\n\n        // Stop lying about P values if we're finished\n        if (iter == 100) {\n            for (unsigned i = 0;  i < n;  ++i)\n                for (unsigned j = 0;  j < n;  ++j)\n                    P[i][j] *= 0.25f;\n        }\n    }\n\n    return Y;\n}\n\n} // namespace ML\n", "meta": {"hexsha": "4b3799e5182f8dc79a04c012a251676073baf36c", "size": 35582, "ext": "cc", "lang": "C++", "max_stars_repo_path": "jml/tsne/tsne.cc", "max_stars_repo_name": "etnrlz/rtbkit", "max_stars_repo_head_hexsha": "0d9cd9e2ee2d7580a27453ad0a2d815410d87091", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 737.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T01:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T10:09:23.000Z", "max_issues_repo_path": "jml/tsne/tsne.cc", "max_issues_repo_name": "TuanTranEngineer/rtbkit", "max_issues_repo_head_hexsha": "502d06acc3f8d90438946b6ae742190f2f4b4fbb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T16:01:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-22T19:02:37.000Z", "max_forks_repo_path": "jml/tsne/tsne.cc", "max_forks_repo_name": "TuanTranEngineer/rtbkit", "max_forks_repo_head_hexsha": "502d06acc3f8d90438946b6ae742190f2f4b4fbb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 329.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T06:54:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T22:21:02.000Z", "avg_line_length": 30.2310960068, "max_line_length": 95, "alphanum_fraction": 0.4670057894, "num_tokens": 10376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059609645724, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.4089412287519742}}
{"text": "#include \"caffe2/operators/pow_op.h\"\n#include \"caffe2/utils/eigen_utils.h\"\n#include \"caffe2/utils/math.h\"\n// definition of NumericTypes and SameTypeAsInput is in below header file\n//#include \"caffe2/operators/elementwise_op.h\"\n#include <Eigen/Core>\n\nnamespace caffe2 {\n\n#define EIGEN_POW(x, y) (x.pow(y))\n\nstruct EigenPowFunctor {\n  template <int b_is_scalar, typename T1, typename T2, typename R>\n  inline void\n  Run(size_t n, const T1* a, const T2* b, T2 e, R* out, CPUContext*) {\n    // NOLINTNEXTLINE(modernize-use-nullptr)\n    if (b == NULL) {\n      EigenVectorArrayMap<R>(out, n) =\n          EIGEN_POW((ConstEigenVectorArrayMap<T1>(a, n)), (e));\n    } else {\n      if (b_is_scalar) {\n        if (b[0] == -1.) {\n          EigenVectorArrayMap<R>(out, n) =\n              ConstEigenVectorArrayMap<T1>(a, n).inverse();\n        // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)\n        } else if (b[0] == 0.5) {\n          EigenVectorArrayMap<R>(out, n) =\n              ConstEigenVectorArrayMap<T1>(a, n).sqrt();\n        // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)\n        } else if (b[0] == -0.5) {\n          EigenVectorArrayMap<R>(out, n) =\n              ConstEigenVectorArrayMap<T1>(a, n).rsqrt();\n        // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)\n        } else if (b[0] == 2.) {\n          EigenVectorArrayMap<R>(out, n) =\n              ConstEigenVectorArrayMap<T1>(a, n).square();\n        } else {\n          EigenVectorArrayMap<R>(out, n) =\n              EIGEN_POW((ConstEigenVectorArrayMap<T1>(a, n)), (b[0]));\n        }\n      } else {\n        EigenVectorArrayMap<R>(out, n) = EIGEN_POW(\n            (ConstEigenVectorArrayMap<T1>(a, n)),\n            (ConstEigenVectorArrayMap<T2>(b, n)));\n      }\n    }\n  }\n  template <typename T1, typename T2, typename R>\n  void RunWithBroadcast(\n      const T1* a,\n      const T2* b,\n      R* out,\n      size_t pre,\n      size_t n,\n      CPUContext*) {\n    EigenArrayMap<R>(out, n, pre) = EIGEN_POW(\n        (ConstEigenArrayMap<T1>(a, n, pre)),\n        (ConstEigenVectorArrayMap<T2>(b, n)).rowwise().replicate(pre));\n    /*\n    //below code only allows elementary ops, such as +, -, * and /,\n    //and does not allow operations, such as pow, exp and log\n    EIGEN_POW(\n       (ConstEigenArrayMap<T>(a, n, pre).colwise()),\n       (ConstEigenVectorArrayMap<T>(b, n)));\n     */\n  }\n  template <typename T1, typename T2, typename R>\n  void RunWithBroadcast2(\n      const T1* a,\n      const T2* b,\n      R* out,\n      size_t pre,\n      size_t n,\n      size_t post,\n      CPUContext*) {\n    for (auto i = 0U; i < pre; ++i) {\n      EigenArrayMap<R>(out + i * n * post, post, n) = EIGEN_POW(\n          (ConstEigenArrayMap<T1>(a + i * n * post, post, n)),\n          (Eigen::Map<const Eigen::Array<T2, 1, Eigen::Dynamic>>(b, n))\n              .colwise()\n              .replicate(post));\n      /*\n      //below code only allows elementary ops, such as +, -, * and /,\n      //and does not allow for operations, such as pow, exp and log\n      EIEGN_POW(\n        (ConstEigenArrayMap<T>(a + i * n * post, post, n).rowwise()),\n        (Eigen::Map<const Eigen::Array<T, 1, Eigen::Dynamic>>(b, n)));\n      */\n    }\n  }\n};\n\n// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)\nREGISTER_CPU_OPERATOR(\n    Pow,\n    PowOp<\n        TensorTypes<float> /*NumericTypes*/,\n        CPUContext,\n        EigenPowFunctor,\n        SameTypeAsInput>)\n\n// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)\nOPERATOR_SCHEMA(Pow)\n    .NumInputs(1, 2)\n    .NumOutputs(1)\n    .AllowInplace({{0, 0}, {1, 0}})\n    .IdenticalTypeAndShapeOfInput(0)\n    .SetDoc(R\"DOC(\nThe *Pow* op takes an input data tensor $X$ and an exponent parameter *exponent*, which can be a scalar or another tensor. As output, it produces a single output data tensor $Y$, where the function $f(x) = x^{exponent}$ has been applied to $X$ elementwise.\n\nGithub Links:\n\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pow_op.h\n- https://github.com/pytorch/pytorch/blob/master/caffe2/operators/pow_op.cc\n\n\n<details>\n\n<summary> <b>Example</b> </summary>\n\n**Code**\n\n```\n\nworkspace.ResetWorkspace()\n\nop = core.CreateOperator(\n    \"Pow\",\n    [\"X\", \"exponent\"],\n    [\"Y\"],\n    broadcast=1\n)\n\nworkspace.FeedBlob(\"X\", np.array([1,2,3,4,5,6]).astype(np.float32))\nprint(\"X: \", workspace.FetchBlob(\"X\"))\n\nworkspace.FeedBlob(\"exponent\", np.array([2]).astype(np.float32))\nprint(\"exponent: \", workspace.FetchBlob(\"exponent\"))\n\nworkspace.RunOperatorOnce(op)\nprint(\"Y: \", workspace.FetchBlob(\"Y\"))\n\n```\n\n**Result**\n\n```\n\nX:  [1. 2. 3. 4. 5. 6.]\nexponent:  [2.]\nY:  [ 1.  4.  9. 16. 25. 36.]\n\n```\n\n</details>\n\n\n)DOC\")\n    .Input(0, \"X\", \"Input data blob to be operated on.\")\n    .Input(1, \"exponent\", \"Exponent blob containing the exponent(s) for calculation. Do not use if setting exponent via argument.\")\n    .Output(0, \"Y\", \"Output data blob with the same shape as the input.\")\n    .Arg(\"exponent\", \"The exponent of the power function. Do not use if setting exponent via input.\")\n    .Arg(\"axis\", \"*(type: int; default: -1)*\")\n    .Arg(\"broadcast\", \"*(type: bool; default: False)*\");\n\nclass GetPowGradient : public GradientMakerBase {\n  using GradientMakerBase::GradientMakerBase;\n  vector<OperatorDef> GetGradientDefs() override {\n    ArgumentHelper arg_helper(def_);\n    if (arg_helper.HasArgument(\"exponent\")) { // second input is a scalar\n      // function f(w,a) = w^a\n      // gradient operator with respect to first input tensor\n      // df/dw = a * w^(a-1) (all operations are component-wise)\n      float exponent = arg_helper.GetSingleArgument<float>(\"exponent\", 0.0);\n      Argument scale_arg;\n      scale_arg.set_name(\"scale\");\n      scale_arg.set_f(exponent);\n      Argument pow_arg;\n      pow_arg.set_name(\"exponent\");\n      if (I(0) != O(0)) {\n        pow_arg.set_f(exponent - 1);\n      } else {\n        LOG(WARNING) << \"In-place Pow gradient, possible loss of precision\";\n        constexpr float kEps = 1e-12f;\n        CAFFE_ENFORCE(std::fabs(exponent) > kEps);\n        pow_arg.set_f((exponent - 1) / exponent);\n      }\n      return vector<OperatorDef>{CreateOperatorDef(\n                                     \"Pow\",\n                                     \"\",\n                                     std::vector<string>{I(0)},\n                                     std::vector<string>{GI(0)},\n                                     std::vector<Argument>{pow_arg}),\n                                 CreateOperatorDef(\n                                     \"Mul\",\n                                     \"\",\n                                     std::vector<string>{GI(0), GO(0)},\n                                     std::vector<string>{GI(0)}),\n                                 CreateOperatorDef(\n                                     \"Scale\",\n                                     \"\",\n                                     std::vector<string>{GI(0)},\n                                     std::vector<string>{GI(0)},\n                                     std::vector<Argument>{scale_arg})};\n      /*\n      // Alternative gradient computation\n      return vector<OperatorDef>{CreateOperatorDef(\n                                     \"Div\",\n                                     \"\",\n                                     std::vector<string>{O(0), I(0)},\n                                     std::vector<string>{GI(0)}),\n                                 CreateOperatorDef(\n                                     \"Mul\",\n                                     \"\",\n                                     std::vector<string>{GI(0), GO(0)},\n                                     std::vector<string>{GI(0)}),\n                                 CreateOperatorDef(\n                                     \"Scale\",\n                                     \"\",\n                                     std::vector<string>{GI(0)},\n                                     std::vector<string>{GI(0)},\n                                     std::vector<Argument>{scale_arg})};\n      */\n    } else { // second input is a tensor\n      CAFFE_ENFORCE(\n          Def().input(0) != Def().output(0) &&\n              Def().input(1) != Def().output(0),\n          \"Gradient computation cannot be carried out if Pow uses in-place \"\n          \"computation: \",\n          ProtoDebugString(Def()));\n      vector<OperatorDef> grad_ops;\n      Argument one_arg;\n      one_arg.set_name(\"value\");\n      one_arg.set_f(1);\n      Argument broadcast, axis, axis_str, order;\n      bool bflag = ArgumentHelper::HasArgument(Def(), \"broadcast\");\n\n      if (bflag) {\n        if (ArgumentHelper::HasArgument(Def(), \"broadcast\")) {\n          broadcast = GetArgument(Def(), \"broadcast\");\n        } else {\n          broadcast = MakeArgument<int>(\"broadcast\", 0);\n        }\n        if (ArgumentHelper::HasArgument(Def(), \"axis\")) {\n          axis = GetArgument(Def(), \"axis\");\n        } else {\n          axis = MakeArgument<int>(\"axis\", -1);\n        }\n        if (ArgumentHelper::HasArgument(Def(), \"axis_str\")) {\n          axis_str = GetArgument(Def(), \"axis_str\");\n        } else {\n          axis_str = MakeArgument<string>(\"axis_str\", \"\");\n        }\n        if (ArgumentHelper::HasArgument(Def(), \"order\")) {\n          order = GetArgument(Def(), \"order\");\n        } else {\n          order = MakeArgument<string>(\"order\", \"NCHW\");\n        }\n      }\n\n      // function f(w,a) = w^a\n      // gradient operator with respect to first input tensor\n      // df/dw = a * w^(a-1) (all operations are component-wise)\n      grad_ops.push_back(CreateOperatorDef(\n          \"ConstantFill\",\n          \"\",\n          std::vector<string>{I(1)},\n          std::vector<string>{GI(1)},\n          std::vector<Argument>{one_arg}));\n      grad_ops.push_back(CreateOperatorDef(\n          \"Sub\",\n          \"\",\n          std::vector<string>{I(1), GI(1)},\n          std::vector<string>{GI(1)}));\n      if (bflag) {\n        grad_ops.push_back(CreateOperatorDef(\n            \"Pow\",\n            \"\",\n            std::vector<string>{I(0), GI(1)},\n            std::vector<string>{GI(0)},\n            vector<Argument>{broadcast, axis, axis_str, order}));\n      } else {\n        grad_ops.push_back(CreateOperatorDef(\n            \"Pow\",\n            \"\",\n            std::vector<string>{I(0), GI(1)},\n            std::vector<string>{GI(0)}));\n      }\n\n      grad_ops.push_back(CreateOperatorDef(\n          \"Mul\",\n          \"\",\n          std::vector<string>{GI(0), GO(0)},\n          std::vector<string>{GI(0)}));\n      if (bflag) {\n        grad_ops.push_back(CreateOperatorDef(\n            \"Mul\",\n            \"\",\n            std::vector<string>{GI(0), I(1)},\n            std::vector<string>{GI(0)},\n            vector<Argument>{broadcast, axis, axis_str, order}));\n      } else {\n        grad_ops.push_back(CreateOperatorDef(\n            \"Mul\",\n            \"\",\n            std::vector<string>{GI(0), I(1)},\n            std::vector<string>{GI(0)}));\n      }\n      /*\n      // Alternative gradient computation (no broadcast support)\n      grad_ops.push_back(CreateOperatorDef(\n                           \"Div\",\n                           \"\",\n                           std::vector<string>{O(0), I(0)},\n                           std::vector<string>{GI(0)}));\n      grad_ops.push_back(CreateOperatorDef(\n                           \"Mul\",\n                           \"\",\n                           std::vector<string>{GI(0), GO(0)},\n                           std::vector<string>{GI(0)}));\n      grad_ops.push_back(CreateOperatorDef(\n                           \"Mul\",\n                           \"\",\n                           std::vector<string>{GI(0), I(1)},\n                           std::vector<string>{GI(0)}));\n      */\n      // gradient operator for with respect to second input tensor\n      // df/da =  w^a * ln w (all operations are component-wise)\n      /*\n      // reset GI(1) to zero\n      Argument zero_arg;\n      zero_arg.set_name(\"value\");\n      zero_arg.set_f(0);\n      grad_ops.push_back(CreateOperatorDef(\n          \"ConstantFill\",\n          \"\",\n          std::vector<string>{I(1)},\n          std::vector<string>{GI(1)},\n          std::vector<Argument>{zero_arg}));\n      */\n      grad_ops.push_back(CreateOperatorDef(\n          \"Log\",\n          \"\",\n          std::vector<string>{I(0)},\n          std::vector<string>{GI(1) + \"_autogen_pre_red\"}));\n      grad_ops.push_back(CreateOperatorDef(\n          \"Mul\",\n          \"\",\n          std::vector<string>{GI(1) + \"_autogen_pre_red\", O(0)},\n          std::vector<string>{GI(1) + \"_autogen_pre_red\"}));\n      if (bflag) {\n        grad_ops.push_back(CreateOperatorDef(\n            \"Mul\",\n            \"\",\n            std::vector<string>{GI(1) + \"_autogen_pre_red\", GO(0)},\n            std::vector<string>{GI(1) + \"_autogen_pre_red\"}));\n        grad_ops.push_back(CreateOperatorDef(\n            \"SumReduceLike\",\n            \"\",\n            vector<string>{GI(1) + \"_autogen_pre_red\", I(1)},\n            vector<string>{GI(1)},\n            vector<Argument>{axis, axis_str, order}));\n      } else {\n        grad_ops.push_back(CreateOperatorDef(\n            \"Mul\",\n            \"\",\n            std::vector<string>{GI(1) + \"_autogen_pre_red\", GO(0)},\n            std::vector<string>{GI(1)}));\n      }\n\n      return grad_ops;\n    }\n  }\n\n  // Argument `shape` is no longer needed in backprop.\n  bool CopyArguments() const override {\n    return false;\n  }\n};\n\n// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)\nREGISTER_GRADIENT(Pow, GetPowGradient);\n\n} // namespace caffe2\n", "meta": {"hexsha": "740481beb32aa2218a77f51316b745564d1143ca", "size": 13462, "ext": "cc", "lang": "C++", "max_stars_repo_path": "caffe2/operators/pow_op.cc", "max_stars_repo_name": "Gamrix/pytorch", "max_stars_repo_head_hexsha": "b5b158a6c6de94dfb983b447fa33fea062358844", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "caffe2/operators/pow_op.cc", "max_issues_repo_name": "Gamrix/pytorch", "max_issues_repo_head_hexsha": "b5b158a6c6de94dfb983b447fa33fea062358844", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "caffe2/operators/pow_op.cc", "max_forks_repo_name": "Gamrix/pytorch", "max_forks_repo_head_hexsha": "b5b158a6c6de94dfb983b447fa33fea062358844", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9662337662, "max_line_length": 256, "alphanum_fraction": 0.5173822612, "num_tokens": 3345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4087324355855454}}
{"text": "/*\nCopyright 2017 InitialDLab\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n#include <iostream>\n#include <algorithm>\n\n#include <boost/geometry/geometry.hpp>\n#include <boost/geometry/geometries/point.hpp>\n\n#include \"hilbert/hilbert.h\"\n\nnamespace bg = boost::geometry;\nnamespace bm = ::boost::mpl;\nnamespace bmp = ::boost::mpl::placeholders;\n\nvoid test_2d()\n{\n    hilbert::HilbertValueComputer<unsigned int, 2, 8> hvc;\n\n    /*\n    using point_t = bg::model::point<int, 2, bg::cs::cartesian>;\n    std::cerr << \"here\" << std::endl;\n    int x,y;\n    while(std::cin >> x >> y)\n    {\n        auto hv = hvc(point_t(x,y));\n        for(auto & p : hv.values)\n            std::cout << p << ' ';\n        std::cout << std::endl;\n    }\n    return 0;\n    */\n\n    using point_t = bg::model::point<int, 2, bg::cs::cartesian>;\n    std::vector<point_t> v;\n    int DIM_SIZE = (1LL << 8);\n    for(int i = 0; i < DIM_SIZE; ++i)\n    {\n        for(int j = 0; j < DIM_SIZE; ++j)\n        {\n            v.push_back(point_t(i,j));\n        }\n    }\n\n    std::sort(v.begin(), v.end(), [&](point_t const& p1, point_t const& p2)->bool{\n        return hvc(p1) < hvc(p2);\n    });\n\n    /*\n    for(auto & p : v)\n    {\n        auto hv = hvc(p);\n        for(auto & i : hv.values)\n            std::cerr << i << ' ';\n        std::cerr << std::endl;\n    }\n    */\n\n    for(auto iter = v.begin(); iter != --v.end(); )\n    {\n        std::cout << iter->get<0>() << ' ' << iter->get<1>() << std::endl;\n        ++iter;\n        std::cout << iter->get<0>() << ' ' << iter->get<1>() << std::endl;\n        std::cout << std::endl;\n    }\n}\nvoid test_3d()\n{\n    std::cerr << \"building lookup\" << std::endl;\n    hilbert::HilbertValueComputer<unsigned int, 3, 4> hvc;\n\n\n    std::cerr << \"generating data\" << std::endl;\n    using point_t = bg::model::point<int, 3, bg::cs::cartesian>;\n    std::vector<point_t> v;\n    int DIM_SIZE = (1LL << 4);\n    for(int i = 0; i < DIM_SIZE; ++i)\n    {\n        for(int j = 0; j < DIM_SIZE; ++j)\n        {\n            for(int k = 0; k < DIM_SIZE; ++k)\n            {\n                v.push_back(point_t(i,j,k));\n            }\n        }\n    }\n\n    std::cerr << \"sorting data\" << std::endl;\n    std::sort(v.begin(), v.end(), [&](point_t const& p1, point_t const& p2)->bool{\n        return hvc(p1) < hvc(p2);\n    });\n\n    /*\n    for(auto & p : v)\n    {\n        auto hv = hvc(p);\n        for(auto & i : hv.values)\n            std::cerr << i << ' ';\n        std::cerr << std::endl;\n    }\n    */\n\n    std::cerr << \"saving\" << std::endl;\n    for(auto iter = v.begin(); iter != --v.end(); )\n    {\n        std::cout << iter->get<0>() << ' ' << iter->get<1>() << ' ' << iter->get<2>() << std::endl;\n        ++iter;\n        std::cout << iter->get<0>() << ' ' << iter->get<1>() << ' ' << iter->get<2>() << std::endl;\n        std::cout << std::endl;\n    }\n\n    std::cerr << \"done\" << std::endl;\n}\n\nstruct printer\n{\n    template <typename V>\n    void operator () (V)\n    {\n        using T0 = typename bm::at_c<V, 0>::type;\n        std::cout << T0::dim << ' ' << T0::x << ' ' << T0::y << ' ' << T0::z << ' ';\n        using T = typename bm::at_c<V, 1>::type;\n        std::cout << T::x << ' ' << T::y << ' ' << T::z << std::endl;\n    }\n};\n\nint main()\n{\n    //test_2d();\n    test_3d();\n    //bm::for_each<hilbert::three_d::HilbertRecursionBase<0, false, false, false>>(printer());\n    return 0;\n}\n", "meta": {"hexsha": "c295292fa0c218ffa0d22ffda7777ae2354d99b6", "size": 4334, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test_hilbert.cpp", "max_stars_repo_name": "InitialDLab/SampleIndex", "max_stars_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-09-30T22:34:57.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-18T21:21:35.000Z", "max_issues_repo_path": "test_hilbert.cpp", "max_issues_repo_name": "InitialDLab/SONAR-SamplingIndex", "max_issues_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test_hilbert.cpp", "max_forks_repo_name": "InitialDLab/SONAR-SamplingIndex", "max_forks_repo_head_hexsha": "c83d6f53f8419cdb78f49935f41eb39447918ced", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5131578947, "max_line_length": 99, "alphanum_fraction": 0.5507614213, "num_tokens": 1258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286833, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4087324291821003}}
{"text": "/***************************************************************************\n *   Copyright (C) 2007 by Marco Correia                                   *\n *   mvc@di.fct.unl.pt                                                     *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n ***************************************************************************/\n\n#include <casper/kernel.h>\n#include <casper/cp/set.h>\n#include <casper/cp/int.h>\n#include <casper/util/options.h>\n\n#include <boost/math/special_functions/factorials.hpp>\n#include <iostream>\n\nusing namespace Casper;\nusing namespace Casper::CP;\n//using namespace std;\n\n#if 0\n/**\n * Computes the set of all n-ary sums of the elements in a set domain variable.\n * \\note needs testing\n */\ntemplate<class Arg1,class Arg2>\nstruct NSumsEqual : IFilter\n{\n\ttypedef typename DomView<Set<int>,Arg1>::Dom\tDomX;\n\ttypedef typename DomView<Set<int>,Arg2>::Dom\tDomY;\n\n\tNSumsEqual(CPSolver& solver,const Arg1& xx, const Arg2& yy, const uint& n) :\n\t\t\t\t  IFilter(solver),x(solver,xx),y(solver,yy),n(n) {}\n\n\tbool execute();\n\tvoid attach(INotifiable* f)\n\t{\tx->attachOnDomain(f); y->attachOnDomain(f);\t}\n\tvoid detach(INotifiable* f)\n\t{\tx->detachOnDomain(f); y->detachOnDomain(f);\t}\n\n\tCost cost() const\n\t{\treturn quadraticLo;\t}\n\n\ttemplate<class Iteration>\n\tList<int> getSums(Iteration it, uint tsize);\n\ttemplate<class Iteration>\n\tList<int> getSumsSorted(Iteration it, uint tsize);\n\n\tDomView<Set<int>,Arg1>\t\t\tx;\n\tDomView<Set<int>,Arg2>\t\t\ty;\n\tconst uint\t\t\t\t\t\tn;\n};\n\ntemplate<class Arg1,class Arg2>\ntemplate<class Iteration>\nList<int> NSumsEqual<Arg1,Arg2>::getSums(Iteration it, uint tsize)\n{\n\tList<int> ret;\n\tif (tsize == 1)\n\t{\n\t\tfor ( ; it.valid(); it.iterate())\n\t\t\tret.pushBack(it.value());\n\t\treturn ret;\n\t}\n\tuint c = 0;\n\tList<int> sums_1(getSums(it,tsize-1));\n\tfor (List<int>::Iterator vit = sums_1.begin(); vit != sums_1.end(); ++vit)\n\t{\n\t\tIteration iit(it);\n\t\tfor (uint i = 0; iit.valid() and i < tsize-1; ++i)\n\t\t\tiit.iterate();\n\t\tfor (uint i = 0; iit.valid() and i < c; ++i)\n\t\t\tiit.iterate();\n\t\tfor ( ; iit.valid(); iit.iterate())\n\t\t\tret.pushBack(iit.value()+*vit);\n\t\t++c;\n\t}\n\treturn ret;\n}\n\ntemplate<class Arg1,class Arg2>\ntemplate<class Iteration>\nList<int> NSumsEqual<Arg1,Arg2>::getSumsSorted(Iteration it, uint tsize)\n{\n\tList<int> sumsUnsorted(getSums(it,tsize));\n\tstd::set<int> sumsV(sumsUnsorted.begin(),sumsUnsorted.end());\n\tList<int> ret(sumsV.begin(),sumsV.end());\n\treturn ret;\n}\n\ntemplate<class Arg1,class Arg2>\nbool NSumsEqual<Arg1,Arg2>::execute()\n{\n//\tstd::cout << \"begin: \" << *x << \" \" << *y << std::endl;\n\tif (x->inSize() >= n)\n\t\tif (!Detail::setSafeInsertRange(*y,makeIt(getSumsSorted(makeInIt(*x),n))))\n\t\t\treturn false;\n\n\tif (x->inSize()+x->possSize() >= n)\n\t\tif (!Detail::setSafeEraseRange(*y,makeDiffIt(makePossIt(*y),\n\t\t\t\t\t\t\t\t\t\t  makeIt(getSumsSorted(makeLUBIt(*x),n)))))\n\t\t\treturn false;\n//\tstd::cout << \"end: \" << *x << \" \" << *y << std::endl;\n\t// not sure if processing \"in y\" events makes sense. ignoring for now.\n\n\t// if an element r is removed from y then we remove from x.poss all e such that\n\t// e+s=r where s is a possible (n-1) sum already in x.in\n/*\tstd::set<int> inSums_1(getSums(makeInIt(*x),n-1));\n\tfor(typename DomX::PIterator pit = x->beginPoss(); pit != x->endPoss(); )\n\t{\n\t\tfor (std::set<int>::iterator it = inSums_1.begin(); it != inSums_1.end(); ++it)\n\t\t\tfor (yLUBDIt = y->lubDeltas().beginFrom(yLUBDeltasIt);\n\t\t\t\t\tyLUBDIt != y->lubDeltas().end(); ++yLUBDIt)\n\t\t\t\tfor (typename DomX::DeltasIterator dit = yLUBDIt->begin();\n\t\t\t\t\t\tdit != yLUBDIt->end(); ++dit)\n\t\t\t\t\tif (*it + *pit == *dit)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x->safeErase(pit++))\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\tgoto next;\n\t\t\t\t\t}\n\t\t++pit;\n\t\tnext:;\n\t}\n\tyLUBDeltasIt = y->lubDeltas().end();*/\n\treturn true;\n}\n\ntemplate<class Arg1,class Arg2>\nFilter nSumsEqual(const Arg1& a1, const Arg2& a2, const uint& n)\n{ return new (getState(a1,a2).getHeap()) NSumsEqual<Arg1,Arg2>(getState(a1,a2),a1,a2,n); }\n#endif\n\n\n\ntemplate<class Arg1,class Arg2>\nstruct SortSubsetsWithSameSum : IFilter\n{\n\ttypedef typename DomView<Set<int>,Arg1>::Dom\tDomX;\n\ttypedef typename DomView<Set<int>,Arg2>::Dom\tDomY;\n\n\tSortSubsetsWithSameSum(Solver& solver,const Arg1& xx, const Arg2& yy) :\n\t\t\t\t  IFilter(solver),x(solver,xx),y(solver,yy) {}\n\n\tbool execute();\n\tvoid attach(INotifiable* f)\n\t{\tx->attachOnGLB(f); y->attachOnGLB(f);\t}\n\tvoid detach(INotifiable* f)\n\t{\tx->detachOnGLB(f); y->detachOnGLB(f);\t}\n\n\tCost cost() const\n\t{\treturn quadraticLo;\t}\n\n\tstruct Cmp {\n\t\tbool operator()(const Util::StdPair<int>& s1,const Util::StdPair<int>& s2) const\n\t\t{\n\t\t\tif (s1.first < s2.first)\n\t\t\t\treturn true;\n\t\t\tif (s1.first > s2.first)\n\t\t\t\treturn false;\n\t\t\treturn s1.second < s2.second;\n\t\t}\n\t};\n\n\ttypedef Util::StdList<Util::StdPair<int> > Sums;\n\ttypedef std::set<Util::StdPair<int>,Cmp> AllSums;\n\n\ttemplate<class Iteration>\n\tSums getSums(Iteration it, const Sums&, uint tsize);\n\ttemplate<class Iteration>\n\tAllSums getSums(Iteration it, uint tsize);\n\n\tDomView<Set<int>,Arg1>\t\t\tx;\n\tDomView<Set<int>,Arg2>\t\t\ty;\n};\n\ntemplate<class Arg1,class Arg2>\ntemplate<class Iteration>\ntypename SortSubsetsWithSameSum<Arg1,Arg2>::Sums\nSortSubsetsWithSameSum<Arg1,Arg2>::getSums(Iteration it,const Sums& sums_1,\n\t\t\t\t\t\t\t\t\t\t\t\tuint tsize)\n{\n\tassert(tsize>1);\n\tSums ret;\n\tuint c = 0;\n\tfor (Sums::Iterator vit = sums_1.begin(); vit != sums_1.end(); ++vit)\n\t{\n\t\tIteration iit(it);\n\t\tfor (uint i = 0; iit.valid() and i < tsize-1; ++i)\n\t\t\tiit.iterate();\n\t\tfor (uint i = 0; iit.valid() and i < c; ++i)\n\t\t\tiit.iterate();\n\t\tfor ( ; iit.valid(); iit.iterate())\n\t\t\tret.pushBack(Util::StdPair<int>(iit.value()+vit->first,iit.value()));\n\t\t++c;\n\t}\n\treturn ret;\n}\n\ntemplate<class Arg1,class Arg2>\ntemplate<class Iteration>\ntypename SortSubsetsWithSameSum<Arg1,Arg2>::AllSums\nSortSubsetsWithSameSum<Arg1,Arg2>::getSums(Iteration it,uint tsize)\n{\n\tAllSums all;\n\n\tSums* xold = new Sums();\n\tfor (Iteration iit(it) ; iit.valid(); iit.iterate())\n\t{\n\t\txold->pushBack(Util::StdPair<int>(iit.value(),iit.value()));\n\t\tall.insert(Util::StdPair<int>(iit.value(),iit.value()));\n\t}\n\n\tfor (uint i = 2; i <= tsize; ++i)\n\t{\n\t\tSums* xnew = new Sums(getSums(it,*xold,i));\n\t\tall.insert(xnew->begin(),xnew->end());\n\t\tdelete xold;\n\t\txold = xnew;\n\t}\n\tdelete xold;\n\treturn all;\n}\n\ntemplate<class Arg1,class Arg2>\nbool SortSubsetsWithSameSum<Arg1,Arg2>::execute()\n{\n\tAllSums sumsx(getSums(makeInIt(*x),x->inSize()));\n\tAllSums sumsy(getSums(makeInIt(*y),y->inSize()));\n\ttypename AllSums::iterator itx = sumsx.begin();\n\ttypename AllSums::iterator ity = sumsy.begin();\n\n/*\tstd::cout << \"xin: \" << x->in() << std::endl;\n\tstd::cout << \"sumsx: \";\n\tprint(sumsx.begin(),sumsx.end());\n\tstd::cout << std::endl;\n*/\n\twhile (itx != sumsx.end() and ity != sumsy.end())\n\t{\n\t\tif (itx->first < ity->first)\n\t\t\t++itx;\n\t\tif (ity->first < itx->first)\n\t\t\t++ity;\n\t\tif (itx->first == ity->first)\n\t\t{\n\t\t\tif (itx->second > ity->second)\n\t\t\t{\n\t\t//\t\tstd::cout << \"failing\\n\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ttypename AllSums::iterator next(itx);\n\t\t\t++next;\n\t\t\tif (next != sumsx.end() and next->first == ity->first)\n\t\t\t\t++itx;\n\t\t\telse\n\t\t\t\t++ity;\n\t\t}\n\t}\n\treturn true;\n}\n\ntemplate<class Arg1,class Arg2>\nFilter sortSubsetsWithSameSum(const Arg1& a1, const Arg2& a2)\n{ return new (getState(a1,a2).getHeap()) SortSubsetsWithSameSum<Arg1,Arg2>(getState(a1,a2),a1,a2); }\n\nstruct GreedyLabeling : IGoal\n{\n\tGreedyLabeling(Store& store,const VarArray<IntSet>& vars) : IGoal(),store(store),\n\t\t\tvars(vars) {}\n\tGoal execute()\n\t{\n\t\t// select maximum unassigned number\n\t\tint maxn = limits<int>::min();\n\t\tfor (uint i = 0; i < vars.size(); ++i)\n\t\t\tfor (SetFD<int>::PIterator it = vars[i].domain().beginPoss();\n\t\t\t\t\tit != vars[i].domain().endPoss(); ++it)\n\t\t\t\tif (*it > maxn)\n\t\t\t\t\tmaxn = *it;\n\n\t\t// find the set with the smallest sum\n\t\tint mins = limits<int>::max();\n\t\tint minidx = -1;\n\t\tfor (uint i = 0; i < vars.size(); ++i)\n\t\t{\n\t\t\tuint sumIn = 0;\n\t\t\tif (vars[i].domain().findInPoss(maxn)!=vars[i].domain().endPoss())\n\t\t\t{\n\t\t\t\tfor (SetFD<int>::IIterator it = vars[i].domain().beginIn();\n\t\t\t\t\t\tit != vars[i].domain().endIn(); ++it)\n\t\t\t\t\tsumIn += *it;\n\t\t\t\tif (sumIn < mins)\n\t\t\t\t{\n\t\t\t\t\tmins = sumIn;\n\t\t\t\t\tminidx = i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (minidx<0)\n\t\t\treturn succeed();\n\t\treturn Goal(store,\n\t\t\t\t(post(store,member(maxn,vars[minidx])) or post(store,notMember(maxn,vars[minidx]))) and\n\t\t\t\tGoal(this));\n\t}\n\tStore& store;\n\tVarArray<IntSet> vars;\n};\n\nGoal greedyLabeling(Store& store,VarArray<IntSet> vars)\n{\treturn new (store) GreedyLabeling(store,vars);\t}\n\nvoid partition(uint nvalues, uint nsets, int optimum = -2)\n{\n\tSolver solver;\n\tIntSetVarArray vars(solver,nsets,range(1,nvalues));\n\n//\tfor (uint i = 0; i < vars.count(); ++i)\n//\t\tcout << vars[i].pDomain() << \" \" << \"A\" << endl;\n\n#if 1\n\tfor (uint i = 0; i < vars.count(); i++)\n\t\tfor (uint j = i+1; j < vars.count(); j++)\n\t\t\tsolver.post( disjoint(vars(i),vars(j)) );\n\t/*solver.post(unionEqual(vars,Var<IntSet>(solver,\n\t\t\t\t\t\tList<int>(range(1,nvalues).begin(),range(1,nvalues).end()),\n\t\t\t\t\t\tList<int>())));*/\n\n\tVarArray<IntSet> avars(solver,nsets,range(1,nvalues));\n\tavars[0] = vars[0];\n\tfor (uint i = 0; i < nsets-1; i++)\n\t\tsolver.post( unionEqual(avars(i),vars(i+1),avars(i+1)) );\n\tsolver.post(avars(nsets-1)==Var<IntSet>(solver,\n\t\t\t\t\t\tUtil::StdList<int>(range(1,nvalues).begin(),range(1,nvalues).end()),\n\t\t\t\t\t\tUtil::StdList<int>()) );\n\n#else\n\tsolver.post(partition(vars));\n#endif\n\n\tconst uint total = nvalues/2.0*(2+(nvalues-1));\n\tIntVar maxSums(solver,std::ceil(((float)total)/nsets),total);\n\n\tif (optimum==-2)\n\t{\n\t\tconst float magicNumberF = ((float)total)/nsets;\n\t\tconst uint magicNumber = (int)magicNumberF;\n\t\tif (magicNumber!=magicNumberF)\t{\n\t\t\tstd::cout << \"trivially impossible!\\n\";\n\t\t\treturn;\n\t\t}\n\n\t\tfor (uint p = 0; p < nsets; ++p)\n\t\t\tsolver.post(sumEqual(vars[p],magicNumber));\n\t}\n\telse\n\tif (optimum==-1)\n\t{\n\t\t// at least one element per set so that we can\n\t\t// enforce symmetry breaking constraints below\n\n\t\tIntVarArray sums(solver,nsets,1,total);\n\t\tfor (uint p = 0; p < nsets; ++p)\n\t\t\tsolver.post(sumEqual(vars[p],sums[p]));\n\t\tsolver.post(max(sums)==maxSums);\n\t\tsolver.setExplorer(bbMinimize(solver,maxSums));\n\t}\n\telse\n\t\tfor (uint p = 0; p < nsets; ++p)\n\t\t{\n\t\t\tIntVar s(solver,1,total);\n\t\t\tsolver.post(sumEqual(vars[p],s));\n\t\t\tsolver.post(s<=optimum);\n\t\t}\n\n\t// symmetry breaking: sets are interchangeable\n#if 1\n\tfor (uint p = 1; p < nsets; ++p)\n\t\tsolver.post(min(vars[p])>min(vars[p-1]));\n#else\n\tfor (uint p1 = 0; p1 < nsets; ++p1)\n\t\tfor (uint p2 = p1+1; p2 < nsets; ++p2)\n\t\t\tsolver.post( sortSubsetsWithSameSum(vars[p1],vars[p2]));\n#endif\n\n//\tbool ret = solver.solve( label( vars, selectVarFFRR(vars) ) );\n\tbool ret = solver.solve( greedyLabeling(solver,vars) );\n\n\tif (optimum==-2 or optimum>=0)\n\t\tstd::cout << ret << std::endl << vars << std::endl;\n\telse\n\t\twhile (ret)\n\t\t{\n\t\t\tstd::cout << vars << \" : \" << maxSums << \" optimimum=\"\n\t\t\t\t\t\t<< ((float)total)/nsets << std::endl;\n\t\t\tret = solver.next();\n\t\t}\n\tstd::cout << solver.getStats() << std::endl\n\t\t\t\t << solver.getCPUTimer() << std::endl;\n}\n\n\nint main(int argc, char** argv)\n{\n\tif (argc != 3 and argc != 4)\n\t{\n\t\tstd::cout << \"usage: \" << argv[0] << \" nvalues nsets [optimum]\\n\";\n\t\tstd::cout << \"set optimum=-2 for perfect partition, optimum=-1 for minimization\\n\";\n\t\treturn 1;\n\t}\n\t::partition(atoi(argv[1]),atoi(argv[2]),argc==3?-1:atoi(argv[3]));\n}\n", "meta": {"hexsha": "1a756cbf84cef1ee79642d8b9a7a779dd2689f08", "size": 11569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/cp/set/partition.cpp", "max_stars_repo_name": "marcovc/casper", "max_stars_repo_head_hexsha": "752ad1c9ecb9408b0a3719a2c8727b87e2d158cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-20T17:04:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-20T17:04:06.000Z", "max_issues_repo_path": "examples/cp/set/partition.cpp", "max_issues_repo_name": "marcovc/casper", "max_issues_repo_head_hexsha": "752ad1c9ecb9408b0a3719a2c8727b87e2d158cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/cp/set/partition.cpp", "max_forks_repo_name": "marcovc/casper", "max_forks_repo_head_hexsha": "752ad1c9ecb9408b0a3719a2c8727b87e2d158cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0121065375, "max_line_length": 100, "alphanum_fraction": 0.6203647679, "num_tokens": 3735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.40859222519062155}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <Eigen/Core>\n#include \"components/RelatednessComponent/LapackEigenDecomposition.hpp\"\n#include <iostream>\n#include \"config/config.hpp\"\n#if HAVE_CLAPACK\n\t#include \"clapack.h\"\n#else\n\nextern \"C\" {\n\t/*\n\t*  function dsyev_ (see http://www.netlib.org/clapack/what/double/dsyev.c)\n\n\t-- LAPACK driver routine (version 3.0) --\t\n\t\tUniv. of Tennessee, Univ. of California Berkeley, NAG Ltd.,\t \n\t\tCourant Institute, Argonne National Lab, and Rice University\t  \n\t\tJune 30, 1999\t\n\n\n\t*\n\t* Arguments:\n\t*\n\tJOBZ\t(input) CHARACTER*1\t  \n\t\t\t= 'N':\tCompute eigenvalues only;\t\n\t\t\t= 'V':\tCompute eigenvalues and eigenvectors.\t\n\n\tUPLO\t(input) CHARACTER*1\t  \n\t\t\t= 'U':\tUpper triangle of A is stored;\t \n\t\t\t= 'L':\tLower triangle of A is stored.\t \n\n\tN\t\t(input) INTEGER\t  \n\t\t\tThe order of the matrix A.\tN >= 0.\t  \n\n\tA\t\t(input/output) DOUBLE PRECISION array, dimension (LDA, N)\t\n\t\t\tOn entry, the symmetric matrix A.  If UPLO = 'U', the\t\n\t\t\tleading N-by-N upper triangular part of A contains the\t \n\t\t\tupper triangular part of the matrix A.\tIf UPLO = 'L',\t \n\t\t\tthe leading N-by-N lower triangular part of A contains\t \n\t\t\tthe lower triangular part of the matrix A.\t \n\t\t\tOn exit, if JOBZ = 'V', then if INFO = 0, A contains the   \n\t\t\torthonormal eigenvectors of the matrix A.\t\n\t\t\tIf JOBZ = 'N', then on exit the lower triangle (if UPLO='L')   \n\t\t\tor the upper triangle (if UPLO='U') of A, including the\t  \n\t\t\tdiagonal, is destroyed.\t  \n\n\tLDA\t\t(input) INTEGER\t  \n\t\t\tThe leading dimension of the array A.  LDA >= max(1,N).\t  \n\n\tW\t\t(output) DOUBLE PRECISION array, dimension (N)\t \n\t\t\tIf INFO = 0, the eigenvalues in ascending order.   \n\n\tWORK\t(workspace/output) DOUBLE PRECISION array, dimension (LWORK)   \n\t\t\tOn exit, if INFO = 0, WORK(1) returns the optimal LWORK.   \n\n\tLWORK\t(input) INTEGER\t  \n\t\t\tThe length of the array WORK.  LWORK >= max(1,3*N-1).\t\n\t\t\tFor optimal efficiency, LWORK >= (NB+2)*N,\t \n\t\t\twhere NB is the blocksize for DSYTRD returned by ILAENV.   \n\n\t\t\tIf LWORK = -1, then a workspace query is assumed; the routine\t\n\t\t\tonly calculates the optimal size of the WORK array, returns\t  \n\t\t\tthis value as the first entry of the WORK array, and no error\t\n\t\t\tmessage related to LWORK is issued by XERBLA.\t\n\n\tINFO\t(output) INTEGER   \n\t\t\t= 0:  successful exit\t\n\t\t\t< 0:  if INFO = -i, the i-th argument had an illegal value\t \n\t\t\t> 0:  if INFO = i, the algorithm failed to converge; i\t \n\t\t\t\t  off-diagonal elements of an intermediate tridiagonal\t \n\t\t\t\t  form did not converge to zero.\n\t*/\n\tint dsyev_(char *jobz, char *uplo, int *n, double *a,\n\t\t int *lda, double *w, double *work, int *lwork, \n\t\tint *info) ;\n}\n\n#endif\n\n#include <vector>\n\nnamespace lapack\n{\n\tvoid compute_eigendecomposition( Eigen::MatrixXd const& matrix, Eigen::VectorXd* eigenvalues, Eigen::MatrixXd* eigenvectors ) {\n\t\tint N = matrix.cols() ;\n\t\tassert( matrix.rows() == N ) ;\n\t\t*eigenvectors = matrix ;\n\t\tint LDA = eigenvectors->outerStride() ;\n\t\tint LWORK = -1 ;\n\t\tint info = 0 ;\n\t\tchar JOBZ = 'V' ;\n\t\tchar UPLO = 'L' ;\n\t\tdouble work_size ;\n\t\tdsyev_( &JOBZ, &UPLO, &N, 0, &LDA, 0, &work_size, &LWORK, &info ) ;\n\t\tLWORK = work_size + 32 ;\n\t\tstd::vector< double > workspace( work_size ) ;\n\t\tdsyev_( &JOBZ, &UPLO, &N, eigenvectors->data(), &LDA, eigenvalues->data(), &workspace[0], &LWORK, &info ) ;\n\t\tif( info != 0 ) {\n\t\t\tstd::cerr << \"!! compute_eigendecomposition(): info = \" << info << \".\\n\" ;\n\t\t\tif( info < 0 ) {\n\t\t\t\tassert( 0 ) ;\n\t\t\t}\n\t\t}\n\t}\n}\n\n#if !HAVE_CLAPACK\nextern \"C\" {\n/*\n *\tfunction dsyevr_ (see http://www.netlib.org/clapack/what/double/dsyevr.c)\n\n\tArguments\t\n\t=========\t\n\n\tJOBZ\t(input) CHARACTER*1\t  \n\t\t\t= 'N':\tCompute eigenvalues only;\t\n\t\t\t= 'V':\tCompute eigenvalues and eigenvectors.\t\n\n\tRANGE\t(input) CHARACTER*1\t  \n\t\t\t= 'A': all eigenvalues will be found.\t\n\t\t\t= 'V': all eigenvalues in the half-open interval (VL,VU]   \n\t\t\t\t   will be found.\t\n\t\t\t= 'I': the IL-th through IU-th eigenvalues will be found.\t\n   ********* For RANGE = 'V' or 'I' and IU - IL < N - 1, DSTEBZ and\t  \n   ********* DSTEIN are called\t \n\n\tUPLO\t(input) CHARACTER*1\t  \n\t\t\t= 'U':\tUpper triangle of A is stored;\t \n\t\t\t= 'L':\tLower triangle of A is stored.\t \n\n\tN\t\t(input) INTEGER\t  \n\t\t\tThe order of the matrix A.\tN >= 0.\t  \n\n\tA\t\t(input/output) DOUBLE PRECISION array, dimension (LDA, N)\t\n\t\t\tOn entry, the symmetric matrix A.  If UPLO = 'U', the\t\n\t\t\tleading N-by-N upper triangular part of A contains the\t \n\t\t\tupper triangular part of the matrix A.\tIf UPLO = 'L',\t \n\t\t\tthe leading N-by-N lower triangular part of A contains\t \n\t\t\tthe lower triangular part of the matrix A.\t \n\t\t\tOn exit, the lower triangle (if UPLO='L') or the upper\t \n\t\t\ttriangle (if UPLO='U') of A, including the diagonal, is\t  \n\t\t\tdestroyed.\t \n\n\tLDA\t\t(input) INTEGER\t  \n\t\t\tThe leading dimension of the array A.  LDA >= max(1,N).\t  \n\n\tVL\t\t(input) DOUBLE PRECISION   \n\tVU\t\t(input) DOUBLE PRECISION   \n\t\t\tIf RANGE='V', the lower and upper bounds of the interval to\t  \n\t\t\tbe searched for eigenvalues. VL < VU.\t\n\t\t\tNot referenced if RANGE = 'A' or 'I'.\t\n\n\tIL\t\t(input) INTEGER\t  \n\tIU\t\t(input) INTEGER\t  \n\t\t\tIf RANGE='I', the indices (in ascending order) of the\t\n\t\t\tsmallest and largest eigenvalues to be returned.   \n\t\t\t1 <= IL <= IU <= N, if N > 0; IL = 1 and IU = 0 if N = 0.\t\n\t\t\tNot referenced if RANGE = 'A' or 'V'.\t\n\n\tABSTOL\t(input) DOUBLE PRECISION   \n\t\t\tThe absolute error tolerance for the eigenvalues.\t\n\t\t\tAn approximate eigenvalue is accepted as converged\t \n\t\t\twhen it is determined to lie in an interval [a,b]\t\n\t\t\tof width less than or equal to\t \n\n\t\t\t\t\tABSTOL + EPS *\t max( |a|,|b| ) ,\t\n\n\t\t\twhere EPS is the machine precision.\t If ABSTOL is less than\t  \n\t\t\tor equal to zero, then\tEPS*|T|\t will be used in its place,\t  \n\t\t\twhere |T| is the 1-norm of the tridiagonal matrix obtained\t \n\t\t\tby reducing A to tridiagonal form.\t \n\n\t\t\tSee \"Computing Small Singular Values of Bidiagonal Matrices\t  \n\t\t\twith Guaranteed High Relative Accuracy,\" by Demmel and\t \n\t\t\tKahan, LAPACK Working Note #3.\t \n\n\t\t\tIf high relative accuracy is important, set ABSTOL to\t\n\t\t\tDLAMCH( 'Safe minimum' ).  Doing so will guarantee that\t  \n\t\t\teigenvalues are computed to high relative accuracy when\t  \n\t\t\tpossible in future releases.  The current code does not\t  \n\t\t\tmake any guarantees about high relative accuracy, but\t\n\t\t\tfurutre releases will. See J. Barlow and J. Demmel,\t  \n\t\t\t\"Computing Accurate Eigensystems of Scaled Diagonally\t\n\t\t\tDominant Matrices\", LAPACK Working Note #7, for a discussion   \n\t\t\tof which matrices define their eigenvalues to high relative\t  \n\t\t\taccuracy.\t\n\n\tM\t\t(output) INTEGER   \n\t\t\tThe total number of eigenvalues found.\t0 <= M <= N.   \n\t\t\tIf RANGE = 'A', M = N, and if RANGE = 'I', M = IU-IL+1.\t  \n\n\tW\t\t(output) DOUBLE PRECISION array, dimension (N)\t \n\t\t\tThe first M elements contain the selected eigenvalues in   \n\t\t\tascending order.   \n\n\tZ\t\t(output) DOUBLE PRECISION array, dimension (LDZ, max(1,M))\t \n\t\t\tIf JOBZ = 'V', then if INFO = 0, the first M columns of Z\t\n\t\t\tcontain the orthonormal eigenvectors of the matrix A   \n\t\t\tcorresponding to the selected eigenvalues, with the i-th   \n\t\t\tcolumn of Z holding the eigenvector associated with W(i).\t\n\t\t\tIf JOBZ = 'N', then Z is not referenced.   \n\t\t\tNote: the user must ensure that at least max(1,M) columns are\t\n\t\t\tsupplied in the array Z; if RANGE = 'V', the exact value of M\t\n\t\t\tis not known in advance and an upper bound must be used.   \n\n\tLDZ\t\t(input) INTEGER\t  \n\t\t\tThe leading dimension of the array Z.  LDZ >= 1, and if\t  \n\t\t\tJOBZ = 'V', LDZ >= max(1,N).   \n\n\tISUPPZ\t(output) INTEGER array, dimension ( 2*max(1,M) )   \n\t\t\tThe support of the eigenvectors in Z, i.e., the indices\t  \n\t\t\tindicating the nonzero elements in Z. The i-th eigenvector\t \n\t\t\tis nonzero only in elements ISUPPZ( 2*i-1 ) through\t  \n\t\t\tISUPPZ( 2*i ).\t \n   ********* Implemented only for RANGE = 'A' or 'I' and IU - IL = N - 1   \n\n\tWORK\t(workspace/output) DOUBLE PRECISION array, dimension (LWORK)   \n\t\t\tOn exit, if INFO = 0, WORK(1) returns the optimal LWORK.   \n\n\tLWORK\t(input) INTEGER\t  \n\t\t\tThe dimension of the array WORK.  LWORK >= max(1,26*N).\t  \n\t\t\tFor optimal efficiency, LWORK >= (NB+6)*N,\t \n\t\t\twhere NB is the max of the blocksize for DSYTRD and DORMTR\t \n\t\t\treturned by ILAENV.\t  \n\n\t\t\tIf LWORK = -1, then a workspace query is assumed; the routine\t\n\t\t\tonly calculates the optimal size of the WORK array, returns\t  \n\t\t\tthis value as the first entry of the WORK array, and no error\t\n\t\t\tmessage related to LWORK is issued by XERBLA.\t\n\n\tIWORK\t(workspace/output) INTEGER array, dimension (LIWORK)   \n\t\t\tOn exit, if INFO = 0, IWORK(1) returns the optimal LWORK.\t\n\n\tLIWORK\t(input) INTEGER\t  \n\t\t\tThe dimension of the array IWORK.  LIWORK >= max(1,10*N).\t\n\n\t\t\tIf LIWORK = -1, then a workspace query is assumed; the\t \n\t\t\troutine only calculates the optimal size of the IWORK array,   \n\t\t\treturns this value as the first entry of the IWORK array, and\t\n\t\t\tno error message related to LIWORK is issued by XERBLA.\t  \n\n\tINFO\t(output) INTEGER   \n\t\t\t= 0:  successful exit\t\n\t\t\t< 0:  if INFO = -i, the i-th argument had an illegal value\t \n\t\t\t> 0:  Internal error   \n*/\n\tint dsyevr_(\n\t\tchar *jobz, char *range, char *uplo, int *n, \n\t\tdouble *a, int *lda,\n\t\tdouble *vl, double *vu,\n\t\tint *il,\n\t\tint *iu,\n\t\tdouble *abstol,\n\t\tint *m, double *w, \n\t\tdouble *z__, int *ldz,\n\t\tint *isuppz,\n\t\tdouble *work, int *lwork, int *iwork, int *liwork, int *info\n\t) ;\n\n\tdouble dlamch_( char *cmach ) ;\n}\n#endif\n\nnamespace lapack {\n\tvoid compute_eigendecomposition(\n\t\tEigen::MatrixXd const& input_matrix,\n\t\tEigen::VectorXd* eigenvalues,\n\t\tEigen::MatrixXd* eigenvectors,\n\t\tdouble minimum_eigenvalue,\n\t\tdouble maximum_eigenvalue\n\t) {\n\t\tassert( input_matrix.rows() == input_matrix.cols() ) ;\n\t\tassert( eigenvalues ) ;\n\t\tassert( eigenvectors ) ;\n\t\tassert( minimum_eigenvalue == minimum_eigenvalue ) ;\n\t\tassert( maximum_eigenvalue == maximum_eigenvalue ) ;\n\t\tassert( minimum_eigenvalue < maximum_eigenvalue ) ;\n\n\t\tEigen::MatrixXd matrix = input_matrix ;\n\t\tint N = matrix.cols() ;\n\t\tassert( matrix.rows() == N ) ;\n\t\tint M_LDA = matrix.outerStride() ;\n\t\tint EV_LDA = eigenvectors->outerStride() ;\n\t\tint info = 0 ;\n\t\tchar RANGE = 'V' ;\n\t\tchar JOBZ = 'V' ;\n\t\tchar UPLO = 'L' ;\n\t\tdouble ABSTOL = dlamch_( const_cast< char* >( \"Safe minimum\" ) ) ;\n\t\tint number_of_eigenvalues ; // numbers of eigenvectors that are computed\n\n\t\t// set up workspaces\n\t\tint LWORK = -1 ;\n\t\tdouble work_size ;\n\t\tint LIWORK = -1 ;\n\t\tint iwork_size ;\n\n\t\tdsyevr_(\n\t\t\t&JOBZ, &RANGE, &UPLO, &N,\n\t\t\tmatrix.data(), &M_LDA,\n\t\t\t&minimum_eigenvalue, &maximum_eigenvalue,\n\t\t\t0, 0,\n\t\t\t&ABSTOL,\n\t\t\t&number_of_eigenvalues, eigenvalues->data(),\n\t\t\teigenvectors->data(), &EV_LDA,\n\t\t\t0,\n\t\t\t&work_size, &LWORK, &iwork_size, &LIWORK, &info\n\t\t) ;\n\t\tassert( info == 0 ) ;\n\t\tLWORK = work_size + 32 ;\n\t\tLIWORK = iwork_size + 32 ;\n\t\tstd::vector< double > workspace( work_size ) ;\n\t\tstd::vector< int > iworkspace( iwork_size ) ;\n\n\t\t// Now compute the decomposition.\n\t\teigenvalues->resize( input_matrix.cols() ) ;\n\t\teigenvectors->resize( input_matrix.cols(), input_matrix.cols() ) ;\n\t\t\n\t\tdsyevr_(\n\t\t\t&JOBZ, &RANGE, &UPLO, &N,\n\t\t\tconst_cast< double* >( matrix.data() ), &M_LDA,\n\t\t\t&minimum_eigenvalue, &maximum_eigenvalue,\n\t\t\t0, 0,\n\t\t\t&ABSTOL,\n\t\t\t&number_of_eigenvalues, eigenvalues->data(),\n\t\t\teigenvectors->data(), &EV_LDA,\n\t\t\t0,\n\t\t\t&workspace[0],\n\t\t\t&LWORK,\n\t\t\t&iworkspace[0],\n\t\t\t&LIWORK,\n\t\t\t&info\n\t\t) ;\n\t\tif( info != 0 ) {\n\t\t\tstd::cerr << \"!! compute_eigendecomposition(): info = \" << info << \".\\n\" ;\n\t\t\tif( info < 0 ) {\n\t\t\t\tassert( 0 ) ;\n\t\t\t}\n\t\t} else {\n\t\t\teigenvalues->resize( number_of_eigenvalues ) ;\n\t\t\teigenvectors->resize( eigenvectors->rows(), number_of_eigenvalues ) ;\n\t\t}\n\t}\n}\n\nnamespace lapack {\n\tvoid compute_eigendecomposition(\n\t\tEigen::MatrixXd const& input_matrix,\n\t\tEigen::VectorXd* eigenvalues,\n\t\tEigen::MatrixXd* eigenvectors,\n\t\tint number_of_eigenvalues\n\t) {\n\t\tassert( input_matrix.rows() == input_matrix.cols() ) ;\n\t\tassert( number_of_eigenvalues > 0 ) ;\n\t\tassert( eigenvalues ) ;\n\t\tassert( eigenvectors ) ;\n\t\tassert( number_of_eigenvalues <= input_matrix.cols() ) ;\n\t\t\n\t\tEigen::MatrixXd matrix = input_matrix ;\n\t\tint N = matrix.cols() ;\n\t\tassert( matrix.rows() == N ) ;\n\t\tint M_LDA = matrix.outerStride() ;\n\t\tint EV_LDA = eigenvectors->outerStride() ;\n\t\tint info = 0 ;\n\t\tchar RANGE = 'I' ;\n\t\tchar JOBZ = 'V' ;\n\t\tchar UPLO = 'L' ;\n\t\tdouble ABSTOL = dlamch_( const_cast< char* >( \"Safe minimum\" ) ) ;\n\t\tint IL = 1;\n\t\tint IU = number_of_eigenvalues + 1 ;\n\n\t\t// set up workspaces\n\t\tint LWORK = -1 ;\n\t\tdouble work_size ;\n\t\tint LIWORK = -1 ;\n\t\tint iwork_size ;\n\n\t\tdsyevr_(\n\t\t\t&JOBZ, &RANGE, &UPLO, &N,\n\t\t\tmatrix.data(), &M_LDA,\n\t\t\t0, 0,\n\t\t\t&IL, &IU,\n\t\t\t&ABSTOL,\n\t\t\t&number_of_eigenvalues, eigenvalues->data(),\n\t\t\teigenvectors->data(), &EV_LDA,\n\t\t\t0,\n\t\t\t&work_size, &LWORK, &iwork_size, &LIWORK, &info\n\t\t) ;\n\t\tassert( info == 0 ) ;\n\t\tLWORK = work_size + 32 ;\n\t\tLIWORK = iwork_size + 32 ;\n\t\tstd::vector< double > workspace( work_size ) ;\n\t\tstd::vector< int > iworkspace( iwork_size ) ;\n\n\t\t// compute the decomposition\n\t\teigenvalues->resize( number_of_eigenvalues ) ;\n\t\teigenvectors->resize( input_matrix.cols(), number_of_eigenvalues ) ;\n\t\t\n\t\tdsyevr_(\n\t\t\t&JOBZ, &RANGE, &UPLO, &N,\n\t\t\tconst_cast< double* >( matrix.data() ), &M_LDA,\n\t\t\t0, 0,\n\t\t\t&IL, &IU,\n\t\t\t&ABSTOL,\n\t\t\t&number_of_eigenvalues, eigenvalues->data(),\n\t\t\teigenvectors->data(), &EV_LDA,\n\t\t\t0,\n\t\t\t&workspace[0],\n\t\t\t&LWORK,\n\t\t\t&iworkspace[0],\n\t\t\t&LIWORK,\n\t\t\t&info\n\t\t) ;\n\t\tif( info != 0 ) {\n\t\t\tstd::cerr << \"!! compute_eigendecomposition(): info = \" << info << \".\\n\" ;\n\t\t\tif( info < 0 ) {\n\t\t\t\tassert( 0 ) ;\n\t\t\t}\n\t\t} else {\n\t\t\teigenvalues->resize( number_of_eigenvalues ) ;\n\t\t\teigenvectors->resize( eigenvectors->rows(), number_of_eigenvalues ) ;\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "a8b9271c64bf326dbb4134d2e37f62fae6f58fe5", "size": 13782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "components/RelatednessComponent/src/LapackEigenDecomposition.cpp", "max_stars_repo_name": "CreRecombinase/qctool", "max_stars_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-04-21T05:42:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T14:59:43.000Z", "max_issues_repo_path": "components/RelatednessComponent/src/LapackEigenDecomposition.cpp", "max_issues_repo_name": "CreRecombinase/qctool", "max_issues_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-09T16:11:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T11:18:56.000Z", "max_forks_repo_path": "components/RelatednessComponent/src/LapackEigenDecomposition.cpp", "max_forks_repo_name": "gavinband/qctool", "max_forks_repo_head_hexsha": "8d8adb45151c91f953fe4a9af00498073b1132ba", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2009345794, "max_line_length": 128, "alphanum_fraction": 0.6483093891, "num_tokens": 4378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.40855121150241913}}
{"text": "#ifndef SETTINGS_HPP\n#define SETTINGS_HPP\n\n#include <boost/lexical_cast.hpp>\n#include <clstatphys/ensemble/hybrid_monte_carlo.hpp>\n#include <clstatphys/physics/todalattice.hpp>\n#include <common/settings_common.hpp>\n\nusing EnsemblerOrigin = ensemble::HybridMonteCarlo; \nusing Hamiltonian = hamiltonian::TodaLattice;\n\nclass Ensembler : public EnsemblerOrigin{\npublic:\n  template<class Hamiltonian>\n  Ensembler(\n            int num_particles, double temperture, double dt_relax, \n            double relax_time, int total_accept, int initial_relax_time,\n            Hamiltonian hamiltonian)\n    : EnsemblerOrigin(num_particles, temperture, dt_relax, relax_time, total_accept),\n      initial_relax_time_(initial_relax_time) {hamiltonian_ = hamiltonian;}\n  \n  template<class Rand>\n  void set_initial_state(std::vector<double> & z, Rand & mt){\n    int counter = 0;\n    for(int step = 0; step < initial_relax_time_; ++step) EnsemblerOrigin::montecarlo(z, counter, hamiltonian_, mt);\n  }\n\nprivate:\n  int initial_relax_time_;\n  Hamiltonian hamiltonian_;\n}; //end Ensembler definition\n\nstruct Settings : public SettingsCommon{\n  int total_accept = 10;\n  double initial_relax_time = 10;\n  double relax_time = 10;\n  double dt_relax = 0.1;\n  double temperture = 1.0;\n\n  double J = 1.0; //interaction constant;\n  double alpha = 1.0; //interaction constant;\n\n  Settings(int argc, char **argv, int & input_counter) \n    : SettingsCommon(argc, argv, input_counter) \n  { \n    set(argc, argv, input_counter);\n  }\n  Settings() = default;\n\n  inline void set(int argc, char **argv, int & input_counter){\n    if (argc > input_counter) total_accept       = boost::lexical_cast<int>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) initial_relax_time = boost::lexical_cast<double>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) relax_time         = boost::lexical_cast<double>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) dt_relax           = boost::lexical_cast<double>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) temperture         = boost::lexical_cast<double>(argv[input_counter]);++input_counter;\n\n    if (argc > input_counter) J                  = boost::lexical_cast<double>(argv[input_counter]);++input_counter;\n    if (argc > input_counter) alpha              = boost::lexical_cast<double>(argv[input_counter]);++input_counter;\n  }\n\n  template <class Dataput>\n  inline void declare(Dataput & dataput){\n    SettingsCommon::declare(dataput);\n\n    dataput <<  \"<<System Depend Settings>> \" << std::endl\n            <<  \"  \" << Hamiltonian::name() << std::endl\n            <<  \"  \" << EnsemblerOrigin::name() << std::endl\n            <<  \"  \" << Lattice::name() << std::endl\n\n            << \"  Number of step for fianally accept : total_accept = \" << total_accept << std::endl\n            << \"  Relaxtion time for update : relax_time = \" << relax_time << std::endl\n            << \"  Interbal of time development : dt_relax  = \" << dt_relax << std::endl\n            << \"  Temperture : temperture = \" << temperture << std::endl\n\n            << \"  Coupling constant : J = \" << J << std::endl\n            << \"  Coupling constant : alpha = \" << alpha << std::endl;\n  }\n\n  Hamiltonian hamiltonian(){\n    Lattice lattice_t(Ns);\n\n    std::vector<std::vector<int> > pair_table(\n                                              num_particles,\n                                              std::vector<int>(N_adj)\n                                              ); \n    lattice_t.create_table(pair_table);\n\n    Hamiltonian hamiltonian_t(\n                              num_particles,\n                              J,\n                              alpha,\n                              pair_table,\n                              N_adj\n                              );\n    return hamiltonian_t;\n  }\n\n  Ensembler ensembler(){\n    Ensembler ensembler_t(\n                          num_particles,\n                          temperture,\n                          dt_relax,\n                          relax_time,\n                          total_accept,\n                          initial_relax_time,\n                          hamiltonian()\n                          );\n    return ensembler_t;\n  }\n\n}; //end Settings definition\n\n\n\n#endif\n", "meta": {"hexsha": "625ff777d4414423e937068b2498a0ba98d952d7", "size": 4273, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "toda-lattice-gge/include/specific/toda_lattice_periodic_boundary_thermalization_from_equilibrium.hpp", "max_stars_repo_name": "FIshikawa/ClassicalStatPhys", "max_stars_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "toda-lattice-gge/include/specific/toda_lattice_periodic_boundary_thermalization_from_equilibrium.hpp", "max_issues_repo_name": "FIshikawa/ClassicalStatPhys", "max_issues_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T08:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T09:29:10.000Z", "max_forks_repo_path": "toda-lattice-gge/include/specific/toda_lattice_periodic_boundary_thermalization_from_equilibrium.hpp", "max_forks_repo_name": "FIshikawa/ClassicalStatPhys", "max_forks_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-18T03:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-21T22:58:27.000Z", "avg_line_length": 36.8362068966, "max_line_length": 116, "alphanum_fraction": 0.5911537561, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482762, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.4085512035231881}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n#include <opt/optimization_problem.hpp>\n\nnamespace ccd {\nnamespace opt {\n\n    /**\n     * We handle the LCP(A, b), which seeks vectors s and x which satisfy the\n     * following constraints\n     * \\f{align*}\n     *     s = A x + b \\\\\n     *     0 \\leq x \\perp s \\geq 0\n     * \\f}\n     */\n    enum LCPSolver {\n        /// Solve the LCP using the Guass-Seidel method\n        LCP_GAUSS_SEIDEL,\n        /// Solve the LCP as a QP using Mosek\n        LCP_MOSEK,\n        /// Sove the LCP using minimum-map Newton's method\n        LCP_NEWTON\n    };\n\n    /**\n     * @brief Solve the LCP using a given solver.\n     */\n    bool lcp_solve(const Eigen::VectorXd& gxi,\n        const Eigen::MatrixXd& jac_gxi,\n        const Eigen::MatrixXd& tilde_jac_gxi,\n        const Eigen::VectorXd& tilde_b,\n        const LCPSolver solver,\n        Eigen::VectorXd& alpha);\n\n    /**\n     * @brief Solve the LCP using Gauss-Seidel\n     *\n     * To use our gauss-seidel implementation we require to express\n     * the problem as\n     *      s = q + N (Mx + p)\n     *\n     * @param gxi \\f$q\\f$\n     * @param jac_gxi \\f$N\\f$\n     * @param tilde_jac_gxi \\f$M\\f$\n     * @param tilde_b \\f$p\\f$\n     * @param alpha \\f$x\\f$\n     */\n    bool lcp_gauss_seidel(const Eigen::VectorXd& gxi,\n        const Eigen::MatrixXd& jac_gxi,\n        const Eigen::MatrixXd& tilde_jac_gxi,\n        const Eigen::VectorXd& tilde_b,\n        Eigen::VectorXd& alpha);\n\n#if BUILD_WITH_MOSEK\n    bool lcp_mosek(\n        const Eigen::MatrixXd& A, const Eigen::VectorXd& b, Eigen::VectorXd& x);\n#endif\n\n    bool lcp_newton(const Eigen::MatrixXd& A_dense,\n        const Eigen::VectorXd& b,\n        Eigen::VectorXd& x);\n\n} // namespace opt\n} // namespace ccd\n", "meta": {"hexsha": "28ef14cf251e98a75a06163bd3e66358f9046b96", "size": 1753, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "comparisons/STIV/src/solvers/lcp_solver.hpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "comparisons/STIV/src/solvers/lcp_solver.hpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "comparisons/STIV/src/solvers/lcp_solver.hpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 25.7794117647, "max_line_length": 80, "alphanum_fraction": 0.5892755277, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707281, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4085426308084814}}
{"text": "/*\n * Copyright [2019] [Christopher Syben]\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * \n * Ray-driven cone-beam projector CUDA kernel using texture inteprolation\n * Implementation adapted from CONRAD\n * PYRO-NN is developed as an Open Source project under the Apache License, Version 2.0.\n*/\n#if GOOGLE_CUDA\n#define EIGEN_USE_GPU\n#include \"../helper_headers/helper_grid.h\"\n#include \"../helper_headers/helper_math.h\"\n#include \"../helper_headers/helper_eigen.h\"\n#include \"../helper_headers/helper_geometry_gpu.h\"\n#include <Eigen/QR>\ntexture<float, 3, cudaReadModeElementType> volume_as_texture;\n#define CUDART_INF_F __int_as_float(0x7f800000)\n\n#define BLOCKSIZE_X           16\n#define BLOCKSIZE_Y           16\n\n#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }\ninline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)\n{\n   if (code != cudaSuccess) \n   {        \n      fprintf(stderr,\"GPUassert: %s %s %d\\n\", cudaGetErrorString(code), file, line);\n      exit(code);\n   }\n}\n\n__device__ float kernel_project3D_tex_interp(const float3 source_point, const float3 ray_vector, const float step_size, const uint3 volume_size)\n{   \n    float pixel = 0.0f;\n    // Step 1: compute alpha value at entry and exit point of the volume\n    float min_alpha, max_alpha;\n    min_alpha = 0;\n    max_alpha = CUDART_INF_F;\n\n    if (0.0f != ray_vector.x)\n    {\n        float volume_min_edge_point = 0 - 0.5f;\n        float volume_max_edge_point = volume_size.x - 0.5f;\n\n\n        float reci = 1.0f / ray_vector.x;\n        float alpha0 = (volume_min_edge_point - source_point.x) * reci;\n        float alpha1 = (volume_max_edge_point - source_point.x) * reci;\n        min_alpha = fmin(alpha0, alpha1);\n        max_alpha = fmax(alpha0, alpha1);\n    }\n\n    if (0.0f != ray_vector.y)\n    {\n        float volume_min_edge_point = 0 - 0.5f;\n        float volume_max_edge_point = volume_size.y - 0.5f;\n\n        float reci = 1.0f / ray_vector.y;\n        float alpha0 = (volume_min_edge_point - source_point.y) * reci;\n        float alpha1 = (volume_max_edge_point - source_point.y) * reci;\n        min_alpha = fmax(min_alpha, fmin(alpha0, alpha1));\n        max_alpha = fmin(max_alpha, fmax(alpha0, alpha1));\n    }\n\n    if (0.0f != ray_vector.z)\n    {\n        float volume_min_edge_point = 0 - 0.5f;\n        float volume_max_edge_point = volume_size.z - 0.5f;\n\n        float reci = 1.0f / ray_vector.z;\n        float alpha0 = (volume_min_edge_point - source_point.z) * reci;\n        float alpha1 = (volume_max_edge_point - source_point.z) * reci;\n        min_alpha = fmax(min_alpha, fmin(alpha0, alpha1));\n        max_alpha = fmin(max_alpha, fmax(alpha0, alpha1));\n    }\n    // we start not at the exact entry point\n    // => we can be sure to be inside the volume\n    min_alpha += step_size * 0.5f;\n\n    // Step 2: Cast ray if it intersects the volume\n    // Trapezoidal rule (interpolating function = piecewise linear func)\n\n    float px, py, pz;\n    \n    // Entrance boundary\n    // For the initial interpolated value, only a half stepsize is\n    //  considered in the computation.\n    if (min_alpha < max_alpha)\n    {\n        px = source_point.x + min_alpha * ray_vector.x;\n        py = source_point.y + min_alpha * ray_vector.y;\n        pz = source_point.z + min_alpha * ray_vector.z;\n\n        pixel += 0.5f * tex3D(volume_as_texture, px+0.5f, py+0.5f, pz+0.5f );\n\n        min_alpha += step_size;\n    }\n    // Mid segments\n    while (min_alpha < max_alpha)\n    {\n        px = source_point.x + min_alpha * ray_vector.x;\n        py = source_point.y + min_alpha * ray_vector.y;\n        pz = source_point.z + min_alpha * ray_vector.z;\n\n        pixel += tex3D(volume_as_texture, px+0.5f, py+0.5f, pz+0.5f );\n\n        min_alpha += step_size;\n    }\n    // Scaling by stepsize;\n    pixel *= step_size;\n\n    // Last segment of the line\n    if (pixel > 0.0f)\n    {   \n        pixel -= 0.5f * step_size * tex3D(volume_as_texture, px+0.5f, py+0.5f, pz+0.5f );\n        \n        min_alpha -= step_size;\n        float last_step_size = max_alpha - min_alpha;\n\n        pixel += 0.5f * last_step_size* tex3D(volume_as_texture, px+0.5f, py+0.5f, pz+0.5f );\n\n        px = source_point.x + max_alpha * ray_vector.x;\n        py = source_point.y + max_alpha * ray_vector.y;\n        pz = source_point.z + max_alpha * ray_vector.z;\n        \n        // The last segment of the line integral takes care of the\n        // varying length.\n        pixel += 0.5f * last_step_size * tex3D(volume_as_texture, px+0.5f, py+0.5f, pz+0.5f);\n    }\n    return pixel;\n}\n\n__global__ void project_3Dcone_beam_kernel_tex_interp(float *pSinogram, const float *d_inv_AR_matrices, const float3 *d_src_points, const float *sampling_step_size,\n                                          const uint3 volume_size, const float *volume_spacing_ptr,\n                                          const uint2 detector_size, const int number_of_projections)\n{\n    uint2 detector_idx = make_uint2( blockIdx.x * blockDim.x + threadIdx.x,  blockIdx.y* blockDim.y + threadIdx.y  );\n    uint projection_number = blockIdx.z;\n    //Prep: Wrap pointer to float3 for better readable code\n    float3 volume_spacing = make_float3(*(volume_spacing_ptr+2), *(volume_spacing_ptr+1), *volume_spacing_ptr);\n    if (detector_idx.x >= detector_size.x || detector_idx.y >= detector_size.y || blockIdx.z >= number_of_projections)\n    {\n        return;\n    }\n    // //Preparations:\n\td_inv_AR_matrices += projection_number * 9;\n    float3 source_point = d_src_points[projection_number];\n    \n    //Compute ray direction\n    const float rx = d_inv_AR_matrices[2] + detector_idx.y * d_inv_AR_matrices[1] + detector_idx.x * d_inv_AR_matrices[0];\n    const float ry = d_inv_AR_matrices[5] + detector_idx.y * d_inv_AR_matrices[4] + detector_idx.x * d_inv_AR_matrices[3];\n    const float rz = d_inv_AR_matrices[8] + detector_idx.y * d_inv_AR_matrices[7] + detector_idx.x * d_inv_AR_matrices[6];\n\n    float3 ray_vector = make_float3(rx,ry,rz);\n    ray_vector = normalize(ray_vector);\n\n    float pixel = kernel_project3D_tex_interp(\n        source_point,\n        ray_vector,\n        *sampling_step_size,\n        volume_size);\n\n    pixel *= sqrt((ray_vector.x * volume_spacing.x) * (ray_vector.x * volume_spacing.x) +\n            (ray_vector.y * volume_spacing.y) * (ray_vector.y * volume_spacing.y) +\n            (ray_vector.z * volume_spacing.z) * (ray_vector.z * volume_spacing.z));\n\n    unsigned sinogram_idx = projection_number * detector_size.y * detector_size.x +  detector_idx.y * detector_size.x + detector_idx.x;\n    \n    pSinogram[sinogram_idx] = pixel;\n    return;\n}\n\n/*************** WARNING ******************./\n    * \n    *   Tensorflow is allocating the whole GPU memory for itself and just leave a small slack memory\n    *   using cudaMalloc and cudaMalloc3D will allocate memory in this small slack memory !\n    *   Therefore, currently only small volumes can be used (they have to fit into the slack memory which TF does not allocae !)\n    * \n    *   This is the kernel based on texture interpolation, thus, the allocations are not within the Tensorflow managed memory.\n    *   If memory errors occure:\n    *    1. start Tensorflow with less gpu memory and allow growth\n    *    2. switch to software-based interpolation. \n    * \n    *   TODO: use context->allocate_tmp and context->allocate_persistent instead of cudaMalloc for the inv_AR_matrix and src_points array\n    *       : https://stackoverflow.com/questions/48580580/tensorflow-new-op-cuda-kernel-memory-managment\n    * \n    */\nvoid Cone_Projection_Kernel_Tex_Interp_Launcher(const float* volume_ptr, float *out, const float *inv_AR_matrix,const float *src_points, \n                                    const int number_of_projections, const int volume_width, const int volume_height, const int volume_depth, \n                                    const float *volume_spacing, const int detector_width, const int detector_height,const float *step_size)\n{\n    cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<float>();\n    volume_as_texture.addressMode[0] = cudaAddressModeBorder;\n    volume_as_texture.addressMode[1] = cudaAddressModeBorder;\n    volume_as_texture.addressMode[2] = cudaAddressModeBorder;\n    volume_as_texture.filterMode = cudaFilterModeLinear;\n    volume_as_texture.normalized = false;\n\n    // //COPY inv AR matrix to graphics card as float array\n    auto matrices_size_b = number_of_projections * 9 * sizeof(float);\n    float *d_inv_AR_matrices;\n    gpuErrchk(cudaMalloc(&d_inv_AR_matrices, matrices_size_b));\n    gpuErrchk(cudaMemcpy(d_inv_AR_matrices, inv_AR_matrix, matrices_size_b, cudaMemcpyHostToDevice));\n    //COPY source points to graphics card as float3\n    auto src_points_size_b = number_of_projections * sizeof(float3);\n    float3 *d_src_points;\n    gpuErrchk(cudaMalloc(&d_src_points, src_points_size_b));\n    gpuErrchk(cudaMemcpy(d_src_points, src_points, src_points_size_b, cudaMemcpyHostToDevice));\n\n    //COPY volume to graphics card\n    //Malloc cuda array for texture\n    cudaExtent volume_extent = make_cudaExtent(  volume_width, volume_height, volume_depth );\n    cudaExtent volume_extent_byte = make_cudaExtent( sizeof(float)*volume_width, volume_height, volume_depth );\n\n    cudaPitchedPtr d_volumeMem = make_cudaPitchedPtr( const_cast<float*>( volume_ptr ),\n                                                volume_width*sizeof(float),\n                                                volume_width,\n                                                volume_height\n                                            );\n   \n    cudaArray *volume_array;\n    gpuErrchk(cudaMalloc3DArray(&volume_array, &channelDesc, volume_extent));\n    \n    cudaMemcpy3DParms copyParams = {0};\n    copyParams.srcPtr = d_volumeMem;\n    copyParams.dstArray = volume_array;\n    copyParams.extent = volume_extent;\n    copyParams.kind = cudaMemcpyDeviceToDevice;\n\n    gpuErrchk(cudaMemcpy3D(&copyParams)); \n\n    gpuErrchk(cudaBindTextureToArray(volume_as_texture, volume_array, channelDesc))\n    uint3 volume_size = make_uint3(volume_width, volume_height, volume_depth);\n    uint2 detector_size = make_uint2(detector_width, detector_height);\n    \n    const dim3 blocksize = dim3( BLOCKSIZE_X, BLOCKSIZE_Y, 1 );\n    const dim3 gridsize = dim3( detector_size.x / blocksize.x + 1, detector_size.y / blocksize.y + 1 , number_of_projections+1);\n\n    project_3Dcone_beam_kernel_tex_interp<<<gridsize, blocksize>>>(out, d_inv_AR_matrices, d_src_points, step_size,\n                                        volume_size, volume_spacing, detector_size, number_of_projections);\n\n    cudaDeviceSynchronize();\n\n\n    // check for errors\n    gpuErrchk( cudaPeekAtLastError() );\n    gpuErrchk(cudaFreeArray(volume_array));\n    gpuErrchk(cudaUnbindTexture(volume_as_texture));\n    gpuErrchk(cudaFree(d_inv_AR_matrices));\n    gpuErrchk(cudaFree(d_src_points));\n}\n\n#endif", "meta": {"hexsha": "0ab19662ad1b92226e234dfb77b0ed738e0e75a4", "size": 11377, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cc/kernels/cone_projector_3D_CudaKernel_hardware_interp.cu.cc", "max_stars_repo_name": "csyben/PYRO-NN-Layers", "max_stars_repo_head_hexsha": "9bec5ccaf62eb1fec01c1668ba1a6375673f8b12", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T10:07:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T09:37:43.000Z", "max_issues_repo_path": "cc/kernels/cone_projector_3D_CudaKernel_hardware_interp.cu.cc", "max_issues_repo_name": "csyben/PYRO-NN-Layers", "max_issues_repo_head_hexsha": "9bec5ccaf62eb1fec01c1668ba1a6375673f8b12", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-06-19T15:45:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T18:39:48.000Z", "max_forks_repo_path": "cc/kernels/cone_projector_3D_CudaKernel_hardware_interp.cu.cc", "max_forks_repo_name": "csyben/PYRO-NN-Layers", "max_forks_repo_head_hexsha": "9bec5ccaf62eb1fec01c1668ba1a6375673f8b12", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-04-20T09:09:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-06T09:25:10.000Z", "avg_line_length": 43.0946969697, "max_line_length": 164, "alphanum_fraction": 0.6796167707, "num_tokens": 2835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.40853896791919747}}
{"text": "/*\n * Copyright (C) 2008-2011, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n */\n\n#include <iostream>\n#include <boost/lexical_cast.hpp>\n#include <boost/mpl/integral_c.hpp>\n#include <boost/numeric/conversion/converter.hpp>\n\n#include <libport/cmath>\n#include <libport/cstdlib>\n#include <libport/ufloat.hh>\n\n#ifdef LIBPORT_URBI_UFLOAT_LONG_LONG\n# include <libport/ull-fixed-point.cc>\n#endif\n\n#ifdef LIBPORT_URBI_UFLOAT_FLOATING\n# include <libport/uffloat.cc>\n#endif\n\n\nnamespace libport\n{\n#ifdef LIBPORT_URBI_UFLOAT_TABULATED\n\n# ifndef SINTABLE_POWER\n  // The tables will containe 2^sintable_power elements.\n#  define SINTABLE_POWER 10\n# endif\n\n  void buildSinusTable(int powersize);\n  class DummyInit\n  {\n  public:\n    DummyInit()\n    {\n      buildSinusTable(SINTABLE_POWER);\n    }\n  };\n\n  DummyInit _dummyInit__;\n\n  static ufloat* sinTable=0; //we store [O, PI/2[\n  static ufloat* asinTable=0; //we store [O, 1[\n\n  static unsigned long tableSize; //must be a power of two\n  static int tableShift;\n\n  void buildSinusTable(int powersize)\n  {\n    size_t size = 1<<powersize;\n    tableShift = powersize;\n    //don't use a step-based generation or errors will accumulate\n    delete [] sinTable;\n    delete [] asinTable;\n\n    sinTable = new ufloat[size];\n    asinTable = new ufloat[size];\n\n    tableSize = size;\n    for (size_t i=0;i<size;i++)\n    {\n      double idx = (double)i*(M_PI/2.0)/(double)size;\n      float val = ::sin(idx);\n      sinTable[i]=val;\n\n      double idx2 = (double)i/(double)size;\n      asinTable[i] = ::asin(idx2);\n    }\n  }\n\n#endif\n\n\n#if defined LIBPORT_URBI_UFLOAT_TABULATED \\\n && !defined LIBPORT_URBI_UFLOAT_FLOATING\n\n  ufloat tabulatedSin(ufloat val)\n  {\n    ufloat fidx = (val*(ufloat)tableSize / (M_PI/2.0));\n    int idx = (int) fidx;\n    ufloat rem = fidx -(ufloat)idx;\n\n    idx = idx & (tableSize-1);\n\n    if (fmod(val, M_PI) >= M_PI/2)\n      idx = (tableSize-idx-1); //sin(pi/2+x) = sin(pi/2-x)\n    ufloat interp = sinTable(idx)*(1.0-rem)+sinTable[(idx+1)%tableSize]*rem;\n\n    return fmod(val, M_PI*2) > M_PI ? -interp : interp;\n  }\n\n  ufloat tabulatedCos(ufloat val)\n  {\n    ufloat fidx = (val*(ufloat)tableSize / (M_PI/2.0));\n    int idx = (int) fidx;\n    ufloat rem = fidx -(ufloat)idx;\n\n    idx = idx & (tableSize-1);\n\n    if (fmod(val, M_PI) < M_PI/2)\n      idx = (tableSize-idx-1); //sin(pi/2+x) = sin(pi/2-x)\n\n    ufloat interp = sinTable(idx)*(1.0-rem)+sinTable[(idx+1)%tableSize]*rem;\n\n    return fmod(val, M_PI*2) > M_PI ? -interp : interp;\n  }\n\n\n  ufloat tabulatedASin(ufloat val)\n  {\n    ufloat fidx = val *(ufloat)tableSize;\n    int idx =(int) fidx;\n    ufloat rem = fidx -(ufloat)idx;\n    idx = idx & (tableSize-1);\n    ufloat interp = asinTable(idx)*(1.0-rem)+asinTable[(idx+1)%tableSize]*rem;\n\n    return val < 0.0 ? -interp : interp;\n  }\n\n#endif\n\n\n  /*------------------------.\n  | From string to ufloat.  |\n  `------------------------*/\n\n  // MSVC makes it uselessly complex to pass isdigit-like functions by\n  // pointer.\n  /// \\param xdigit  whether hexadecimal instead of decimal.\n  static inline\n  bool\n  is_digit(int c, bool xdigit)\n  {\n    return xdigit ? isxdigit(c) : isdigit(c);\n  }\n\n  /// Remove underscores, allowed only between two digits.\n  ///\n  /// \\param xdigit  whether hexadecimal instead of decimal.\n  static\n  std::string\n  as_ufloat_strip(const std::string& s, bool xdigit)\n  {\n    std::string res;\n    size_t len = s.size();\n    for (size_t i = 0; i < len; /* nothing */)\n      if (s[i] == '_')\n      {\n        // Look for the next non-underscore character.\n        size_t next = s.find_first_not_of(\"_\", i);\n        if (res.empty()\n            || !is_digit(res[res.size() - 1], xdigit)\n            || !(next < len)\n            || !is_digit(s[next], xdigit))\n          throw boost::bad_lexical_cast();\n        i = next;\n      }\n      else\n      {\n        res.append(1, s[i]);\n        ++i;\n      }\n    return res;\n  }\n\n  ufloat\n  as_ufloat(const std::string& s)\n  {\n    // Convert.\n    if (s.substr(0, 2) == \"0x\")\n    {\n      std::string pure = as_ufloat_strip(s, true);\n      char* end = 0;\n      ufloat res = strtoll(pure.c_str(), &end, 0);\n      // Refuse garbage after.\n      if (end && *end)\n        throw boost::bad_lexical_cast();\n      return res;\n    }\n    else\n      return boost::lexical_cast<libport::ufloat>\n        (as_ufloat_strip(s, false));\n  }\n\n\n  /*------------------.\n  | cast exceptions.  |\n  `------------------*/\n\n  const char *bad_numeric_cast::what() const throw()\n  {\n    return \"bad numeric conversion: overflow or non empty fractional part\";\n  }\n\n  const char *negative_overflow::what() const throw()\n  {\n    return \"bad numeric conversion: negative overflow\";\n  }\n\n  const char *positive_overflow::what() const throw()\n  {\n    return \"bad numeric conversion: positive overflow\";\n  }\n\n\n  /*-------------------.\n  | ufloat converter.  |\n  `-------------------*/\n\n  template<typename S>\n  struct ExactFloat2IntRounderPolicy\n  {\n    typedef S source_type;\n    typedef S argument_type;\n\n    static source_type nearbyint(argument_type s)\n    {\n      if (s != ceil(s))\n\tthrow boost::numeric::bad_numeric_cast();\n      return s;\n    }\n\n    typedef boost::mpl::integral_c<std::float_round_style,std::round_to_nearest>\n      round_style;\n  };\n\n\n  /*-------------------.\n  | numeric_castable.  |\n  `-------------------*/\n\n  template <typename T>\n  bool\n  numeric_castable(ufloat val)\n  {\n    double int_part;\n    if (modf(val, &int_part) != 0)\n      return false;\n\n    static boost::numeric::converter\n      <T,\n      ufloat,\n      boost::numeric::conversion_traits<T, ufloat>,\n      boost::numeric::def_overflow_handler,\n      ExactFloat2IntRounderPolicy<ufloat> > converter;\n\n    return converter.out_of_range(val) == boost::numeric::cInRange;\n  }\n\n# define UFLOAT_CAST(Type)                                      \\\n  template                                                      \\\n  bool numeric_castable<Type>(ufloat v);\n\n  // Instantiate.\n  UFLOAT_CASTS\n\n#undef UFLOAT_CAST\n\n\n  /*---------------.\n  | numeric_cast.  |\n  `---------------*/\n\n  template <typename T>\n  T\n  numeric_cast(ufloat val) throw (bad_numeric_cast)\n  {\n    try\n    {\n      static boost::numeric::converter\n        <T,\n        ufloat,\n        boost::numeric::conversion_traits<T, ufloat>,\n        boost::numeric::def_overflow_handler,\n        ExactFloat2IntRounderPolicy<ufloat> > converter;\n\n      return converter(val);\n    }\n#define RETHROW(Name)                           \\\n    catch (boost::numeric::Name&)               \\\n    {                                           \\\n      throw Name();                             \\\n    }\n    RETHROW(negative_overflow)\n    RETHROW(positive_overflow)\n    RETHROW(bad_numeric_cast)\n#undef RETHROW\n  }\n\n  /*----------------.\n  | rounding_cast.  |\n  `----------------*/\n\n  template <typename T>\n  T\n  rounding_cast(ufloat val) throw (bad_numeric_cast)\n  {\n    try\n    {\n      static boost::numeric::converter\n        <T,\n        ufloat,\n        boost::numeric::conversion_traits<T, ufloat>,\n        boost::numeric::def_overflow_handler,\n        boost::numeric::RoundEven<ufloat> > converter;\n\n      return converter(val);\n    }\n#define RETHROW(Name)                           \\\n    catch (boost::numeric::Name&)               \\\n    {                                           \\\n      throw Name();                             \\\n    }\n    RETHROW(negative_overflow)\n    RETHROW(positive_overflow)\n    RETHROW(bad_numeric_cast)\n#undef RETHROW\n  }\n\n# define UFLOAT_CAST(Type)                                      \\\n  template                                                      \\\n  Type                                                          \\\n  numeric_cast<Type>(ufloat v) throw (bad_numeric_cast);        \\\n                                                                \\\n  template                                                      \\\n  Type                                                          \\\n  rounding_cast<Type>(ufloat v) throw (bad_numeric_cast);\n\n  // Instantiate.\n  UFLOAT_CASTS\n\n#undef UFLOAT_CAST\n\n} // namespace libport\n", "meta": {"hexsha": "d951e97820c3c9e2722427fba678852f33083716", "size": 8252, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/libport/ufloat.cc", "max_stars_repo_name": "jcbaillie/libport", "max_stars_repo_head_hexsha": "b8192b177ae0ae63979c17ea7685a8617b03e11f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-05-29T09:35:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T07:45:01.000Z", "max_issues_repo_path": "lib/libport/ufloat.cc", "max_issues_repo_name": "jcbaillie/libport", "max_issues_repo_head_hexsha": "b8192b177ae0ae63979c17ea7685a8617b03e11f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-31T10:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-31T10:35:06.000Z", "max_forks_repo_path": "lib/libport/ufloat.cc", "max_forks_repo_name": "jcbaillie/libport", "max_forks_repo_head_hexsha": "b8192b177ae0ae63979c17ea7685a8617b03e11f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T20:49:06.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-24T04:06:22.000Z", "avg_line_length": 24.0583090379, "max_line_length": 80, "alphanum_fraction": 0.5631362094, "num_tokens": 2173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4085284237949408}}
{"text": "/*\n * This is part of the fl library, a C++ Bayesian filtering library\n * (https://github.com/filtering-library)\n *\n * Copyright (c) 2015 Max Planck Society,\n * \t\t\t\t Autonomous Motion Department,\n * \t\t\t     Institute for Intelligent Systems\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n */\n\n/**\n * \\file discrete_distribution.hpp\n * \\date 05/25/2014\n * \\author Manuel Wuthrich (manuel.wuthrich@gmail.com)\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n#pragma once\n\n\n#include <Eigen/Core>\n\n#include <vector>\n\n#include <fl/util/types.hpp>\n#include <fl/util/traits.hpp>\n#include <fl/util/assertions.hpp>\n#include <fl/distribution/interface/moments.hpp>\n#include <fl/distribution/interface/standard_gaussian_mapping.hpp>\n\nnamespace fl\n{\n\ntemplate <typename Variate, int Locations = Eigen::Dynamic>\nclass DiscreteDistribution\n    : public Moments<typename FirstMomentOf<Variate>::Type>,\n      public StandardGaussianMapping<Variate, 1>\n{\npublic:\n    typedef Moments<typename FirstMomentOf<Variate>::Type>  MomentsInterface;\n    typedef typename MomentsInterface::Variate              Mean;\n    typedef typename MomentsInterface::SecondMoment         Covariance;\n\n    typedef Eigen::Array<Real,    Locations, 1> Function;\n    typedef Eigen::Array<Variate, Locations, 1> LocationArray;\n\n    typedef StandardGaussianMapping<Variate, 1> StdGaussianMapping;\n    typedef typename StdGaussianMapping::StandardVariate StandardVariate;\n\npublic:\n    /// constructor and destructor *********************************************\n    explicit\n    DiscreteDistribution(int size = MaxOf<Locations, 1>::value)\n    {\n        set_uniform(size);\n    }\n\n    virtual ~DiscreteDistribution() noexcept { }\n\n    /// non-const functions ****************************************************\n\n    // set ---------------------------------------------------------------------\n    virtual void log_unnormalized_prob_mass(const Function& log_prob_mass)\n    {\n        // rescale for numeric stability\n        log_prob_mass_ = log_prob_mass - log_prob_mass.maxCoeff();\n\n        // copy to prob mass\n        prob_mass_ = log_prob_mass_.exp();\n        Real sum = prob_mass_.sum();\n\n        // normalize\n        prob_mass_ /= sum;\n        log_prob_mass_ -= std::log(sum);\n\n        // compute cdf\n        cumul_distr_.resize(log_prob_mass_.size());\n\n        cumul_distr_[0] = prob_mass_[0];\n        for(int i = 1; i < cumul_distr_.size(); i++)\n        {\n            cumul_distr_[i] = cumul_distr_[i-1] + prob_mass_[i];\n        }\n\n        // resize locations\n        locations_.resize(log_prob_mass_.size());\n    }\n\n    virtual void delta_log_prob_mass(const Function& delta)\n    {\n        log_unnormalized_prob_mass(log_prob_mass_ + delta);\n    }\n\n    virtual void set_uniform(int new_size = -1)\n    {\n        if (new_size == -1) new_size = size();\n\n        log_unnormalized_prob_mass(Function::Zero(new_size));\n    }\n\n    virtual Variate& location(int i)\n    {\n        return locations_[i];\n    }\n\n    template <typename Distribution>\n    void from_distribution(const Distribution& distribution, const int& new_size)\n    {\n        // we first create a local array to sample to. this way, if this\n        // is passed as an argument the locations and pmf are not overwritten\n        // while sampling\n        LocationArray new_locations(new_size);\n\n        for(int i = 0; i < new_size; i++)\n        {\n            new_locations[i] = distribution.sample();\n        }\n\n        set_uniform(new_size);\n        locations_ = new_locations;\n    }\n\n\n\n    /// const functions ********************************************************\n\n    // sampling ----------------------------------------------------------------\n    virtual Variate map_standard_normal(const StandardVariate& gaussian_sample,\n                                        int& index) const\n    {\n        StandardVariate scaled_sample = gaussian_sample / std::sqrt(2.0);\n        StandardVariate uniform_sample = 0.5 * (1.0 + std::erf(scaled_sample));\n\n        return map_standard_uniform(uniform_sample, index);\n    }\n\n    virtual Variate map_standard_uniform(const StandardVariate& uniform_sample,\n                                         int& index) const\n    {\n        index = 0;\n        for (index = 0; index < cumul_distr_.size(); ++index)\n        {\n            if (cumul_distr_[index] >= uniform_sample) break;\n        }\n\n        return locations_[index];\n    }\n\n    using StdGaussianMapping::sample;\n\n    virtual Variate sample(int& index) const\n    {\n        return map_standard_normal(this->standard_gaussian_.sample(), index);\n    }\n\n    virtual Variate map_standard_normal(const StandardVariate& gaussian_sample) const\n    {\n        int index;\n        return map_standard_normal(gaussian_sample, index);\n    }\n\n    virtual Variate map_standard_uniform(const StandardVariate& uniform_sample) const\n    {\n        int index;\n        return map_standard_uniform(uniform_sample, index);\n    }\n\n\n    // get ---------------------------------------------------------------------\n    virtual const Variate& location(int i) const\n    {\n        return locations_[i];\n    }\n\n    virtual const LocationArray& locations() const\n    {\n        return locations_;\n    }\n\n    virtual Real log_prob_mass(const int& i) const\n    {\n        return log_prob_mass_(i);\n    }\n\n    virtual Function log_prob_mass() const\n    {\n        return log_prob_mass_;\n    }\n\n    virtual Real prob_mass(const int& i) const\n    {\n        return prob_mass_(i);\n    }\n\n    virtual Function prob_mass() const\n    {\n        return prob_mass_;\n    }\n\n    virtual int size() const\n    {\n        return locations_.size();\n    }\n\n    virtual int dimension() const\n    {\n        return locations_[0].rows();\n    }\n\n\n    // compute properties ------------------------------------------------------\n    virtual const Mean& mean() const\n    {\n        mu_ = Mean::Zero(dimension());\n\n        for(int i = 0; i < locations_.size(); i++)\n        {\n            mu_ += prob_mass(i) * locations_[i].template cast<Real>();\n        }\n\n        return mu_;\n    }\n\n    virtual const Variate& max() const\n    {\n        int max_index;\n        log_prob_mass_.maxCoeff(&max_index);\n\n        return locations_(max_index);\n    }\n\n\n\n    virtual const Covariance& covariance() const\n    {\n        Mean mu = mean();\n        cov_ = Covariance::Zero(dimension(), dimension());\n        for(int i = 0; i < locations_.size(); i++)\n        {\n            Mean delta = (locations_[i].template cast<Real>()-mu);\n            cov_ += prob_mass(i) * delta * delta.transpose();\n        }\n\n        return cov_;\n    }\n\n    virtual Real entropy() const\n    {\n        return - log_prob_mass_.cwiseProduct(prob_mass_).sum();\n    }\n\n    // implements KL(p||u) where p is this distr, and u is the uniform distr\n    virtual Real kl_given_uniform() const\n    {\n        return std::log(Real(size())) - entropy();\n    }\n\n\nprotected:\n    /// member variables *******************************************************\n    LocationArray locations_;\n\n    Function log_prob_mass_;\n    Function prob_mass_;\n    Function cumul_distr_;\n\n    mutable Mean mu_;\n    mutable Covariance cov_;\n};\n\n}\n", "meta": {"hexsha": "2bfbb284ea362a75578aa312584d8260c725c14b", "size": 7240, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/distribution/discrete_distribution.hpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "include/fl/distribution/discrete_distribution.hpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "include/fl/distribution/discrete_distribution.hpp", "max_forks_repo_name": "aeolusbot-tommyliu/fl", "max_forks_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T20:55:13.000Z", "avg_line_length": 26.4233576642, "max_line_length": 85, "alphanum_fraction": 0.5864640884, "num_tokens": 1563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.408520032416304}}
{"text": "/*\n *            Copyright 2009-2020 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n// Third party includes\n#include <boost/math/constants/constants.hpp>\n\n// VOTCA includes\n#include <votca/tools/constants.h>\n\n// Local VOTCA includes\n#include <votca/xtp/orbitals.h>\n\n// Local private VOTCA includes\n#include \"spectrum.h\"\n\nnamespace votca {\nnamespace xtp {\n\nvoid Spectrum::Initialize(const tools::Property& user_options) {\n\n  tools::Property options =\n      LoadDefaultsAndUpdateWithUserOptions(\"xtp\", user_options);\n\n  _job_name = options.ifExistsReturnElseReturnDefault<std::string>(\"job_name\",\n                                                                   _job_name);\n\n  // orbitals file or pure DFT output\n  _orbfile = options.ifExistsReturnElseReturnDefault<std::string>(\n      \".orbitals\", _job_name + \".orb\");\n\n  _output_file = options.ifExistsReturnElseReturnDefault<std::string>(\n      \".output\", _job_name + \"_spectrum.dat\");\n\n  _n_pt = options.get(\".points\").as<Index>();\n  _lower = options.get(\".lower\").as<double>();\n  _upper = options.get(\".upper\").as<double>();\n  _fwhm = options.get(\".fwhm\").as<double>();\n\n  _spectrum_type = options.get(\".type\").as<std::string>();\n  _minexc = options.get(\".minexc\").as<Index>();\n  _maxexc = options.get(\".maxexc\").as<Index>();\n  _shiftby = options.get(\".shift\").as<double>();\n}\n\nbool Spectrum::Evaluate() {\n  OPENMP::setMaxThreads(_nThreads);\n  _log.setReportLevel(Log::current_level);\n  _log.setMultithreading(true);\n\n  _log.setCommonPreface(\"\\n... ...\");\n\n  XTP_LOG(Log::error, _log)\n      << \"Calculating absorption spectrum plot \" << _orbfile << std::flush;\n\n  Orbitals orbitals;\n  // load the QM data from serialized orbitals object\n  XTP_LOG(Log::error, _log)\n      << \" Loading QM data from \" << _orbfile << std::flush;\n  orbitals.ReadFromCpt(_orbfile);\n\n  // check if orbitals contains singlet energies and transition dipoles\n  if (!orbitals.hasBSESinglets()) {\n    throw std::runtime_error(\n        \"BSE singlet energies not stored in QM data file!\");\n  }\n\n  if (!orbitals.hasTransitionDipoles()) {\n    throw std::runtime_error(\n        \"BSE transition dipoles not stored in QM data file!\");\n  }\n\n  const Eigen::VectorXd BSESingletEnergies =\n      orbitals.BSESinglets().eigenvalues() * tools::conv::hrt2ev;\n  const std::vector<Eigen::Vector3d>& TransitionDipoles =\n      orbitals.TransitionDipoles();\n  Eigen::VectorXd osc = orbitals.Oscillatorstrengths();\n\n  if (_maxexc > Index(TransitionDipoles.size())) {\n    _maxexc = Index(TransitionDipoles.size()) - 1;\n  }\n\n  Index n_exc = _maxexc - _minexc + 1;\n  XTP_LOG(Log::error, _log)\n      << \" Considering \" << n_exc << \" excitation with max energy \"\n      << BSESingletEnergies(_maxexc) << \" eV / min wave length \"\n      << evtonm(BSESingletEnergies[_maxexc - 1]) << \" nm\" << std::flush;\n\n  /*\n   *\n   * For a single excitation, broaden by Lineshape function L(v-W)\n   *    eps(v) = f * L(v-W)\n   *\n   * where\n   *       v: energy\n   *       f: oscillator strength in dipole-length gauge\n   *       W: excitation energy\n   *\n   * Lineshape function depend on FWHM and can be\n   *\n   *      Gaussian\n   *          L(v-W) = 1/(sqrt(2pi)sigma) * exp(-0.5 (v-W)^2/sigma^2\n   *\n   *\n   *            with sigma: derived from FWHM (FWHM/2.3548)\n   *\n   *     Lorentzian\n   *          L(v-W) = 1/pi * 0.5 FWHM/( (v-w)^2 + 0.25*FWHM^2 )\n   *\n   * Full spectrum is superposition of individual spectra.\n   *\n   *  Alternatively, one can calculate the imaginary part of the\n   *  frequency-dependent dielectric function\n   *\n   *   IM(eps(v)) ~ 1/v^2 * W^2 * |td|^2 * L(v-W)\n   *              = 1/v^2 * W   * f      * L(v-W)\n   *\n   *\n   */\n\n  std::ofstream ofs(_output_file, std::ofstream::out);\n\n  if (_spectrum_type == \"energy\") {\n    ofs << \"# E(eV)    epsGaussian    IM(eps)Gaussian   epsLorentz    \"\n           \"Im(esp)Lorentz\\n\";\n    for (Index i_pt = 0; i_pt <= _n_pt; i_pt++) {\n\n      double e = (_lower + double(i_pt) * (_upper - _lower) / double(_n_pt));\n\n      double eps_Gaussian = 0.0;\n      double imeps_Gaussian = 0.0;\n      double eps_Lorentzian = 0.0;\n      double imeps_Lorentzian = 0.0;\n\n      for (Index i_exc = _minexc; i_exc <= _maxexc; i_exc++) {\n        eps_Gaussian +=\n            osc[i_exc] *\n            Gaussian(e, BSESingletEnergies(i_exc) + _shiftby, _fwhm);\n        imeps_Gaussian += osc[i_exc] * BSESingletEnergies(i_exc) *\n                          Gaussian(e, BSESingletEnergies(i_exc), _fwhm);\n        eps_Lorentzian +=\n            osc[i_exc] * Lorentzian(e, BSESingletEnergies(i_exc), _fwhm);\n        imeps_Lorentzian += osc[i_exc] * BSESingletEnergies(i_exc) *\n                            Lorentzian(e, BSESingletEnergies(i_exc), _fwhm);\n      }\n\n      ofs << e << \"    \" << eps_Gaussian << \"   \" << imeps_Gaussian << \"   \"\n          << eps_Lorentzian << \"   \" << imeps_Lorentzian << std::endl;\n    }\n\n    XTP_LOG(Log::error, _log)\n        << \" Spectrum in energy range from  \" << _lower << \" to \" << _upper\n        << \" eV and with broadening of FWHM \" << _fwhm\n        << \" eV written to file  \" << _output_file << std::flush;\n  }\n\n  if (_spectrum_type == \"wavelength\") {\n\n    ofs << \"# lambda(nm)    epsGaussian    IM(eps)Gaussian   epsLorentz    \"\n           \"Im(esp)Lorentz\\n\";\n    for (Index i_pt = 0; i_pt <= _n_pt; i_pt++) {\n\n      double lambda =\n          (_lower + double(i_pt) * (_upper - _lower) / double(_n_pt));\n      double eps_Gaussian = 0.0;\n      double imeps_Gaussian = 0.0;\n      double eps_Lorentzian = 0.0;\n      double imeps_Lorentzian = 0.0;\n\n      for (Index i_exc = _minexc; i_exc <= _maxexc; i_exc++) {\n        double exc_lambda = nmtoev(BSESingletEnergies(i_exc) + _shiftby);\n        eps_Gaussian += osc[i_exc] * Gaussian(lambda, exc_lambda, _fwhm);\n        imeps_Gaussian +=\n            osc[i_exc] * exc_lambda * Gaussian(lambda, exc_lambda, _fwhm);\n        eps_Lorentzian += osc[i_exc] * Lorentzian(lambda, exc_lambda, _fwhm);\n        imeps_Lorentzian +=\n            osc[i_exc] * exc_lambda * Lorentzian(lambda, exc_lambda, _fwhm);\n      }\n\n      ofs << lambda << \"    \" << eps_Gaussian << \"   \" << imeps_Gaussian\n          << \"   \" << eps_Lorentzian << \"   \" << imeps_Lorentzian << std::endl;\n    }\n    XTP_LOG(Log::error, _log)\n        << \" Spectrum in wavelength range from  \" << _lower << \" to \" << _upper\n        << \" nm and with broadening of FWHM \" << _fwhm\n        << \" nm written to file  \" << _output_file << std::flush;\n  }\n\n  ofs.close();\n  return true;\n}\n\ndouble Spectrum::Lorentzian(double x, double center, double fwhm) {\n  return 0.5 * fwhm / (std::pow(x - center, 2) + 0.25 * fwhm * fwhm) /\n         boost::math::constants::pi<double>();\n}\n\ndouble Spectrum::Gaussian(double x, double center, double fwhm) {\n  // FWHM = 2*sqrt(2 ln2) sigma = 2.3548 sigma\n  double sigma = fwhm / 2.3548;\n  return std::exp(-0.5 * std::pow((x - center) / sigma, 2)) / sigma /\n         sqrt(2.0 * boost::math::constants::pi<double>());\n}\n\ndouble Spectrum::evtonm(double eV) { return 1241.0 / eV; }\n\ndouble Spectrum::evtoinvcm(double eV) { return 8065.73 * eV; }\n\ndouble Spectrum::nmtoinvcm(double nm) { return 1241.0 * 8065.73 / nm; }\n\ndouble Spectrum::invcmtonm(double invcm) { return 1.0e7 / invcm; }\n\ndouble Spectrum::nmtoev(double nm) { return 1241.0 / nm; }\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "f31c8982d05f72807927286cac1c1e49d8098248", "size": 7883, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/tools/spectrum.cc", "max_stars_repo_name": "fossabot/xtp", "max_stars_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/tools/spectrum.cc", "max_issues_repo_name": "fossabot/xtp", "max_issues_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/tools/spectrum.cc", "max_forks_repo_name": "fossabot/xtp", "max_forks_repo_head_hexsha": "e82cc53f23e213d09da15da80ada6e32ac031a07", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9784482759, "max_line_length": 79, "alphanum_fraction": 0.6130914626, "num_tokens": 2359, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.408520032416304}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// weighted_peaks_over_threshold.hpp\r\n//\r\n//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_PEAKS_OVER_THRESHOLD_HPP_DE_01_01_2006\r\n#define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_PEAKS_OVER_THRESHOLD_HPP_DE_01_01_2006\r\n\r\n#include <vector>\r\n#include <limits>\r\n#include <numeric>\r\n#include <functional>\r\n#include <boost/throw_exception.hpp>\r\n#include <boost/range.hpp>\r\n#include <boost/mpl/if.hpp>\r\n#include <boost/mpl/placeholders.hpp>\r\n#include <boost/parameter/keyword.hpp>\r\n#include <boost/tuple/tuple.hpp>\r\n#include <boost/accumulators/numeric/functional.hpp>\r\n#include <boost/accumulators/framework/accumulator_base.hpp>\r\n#include <boost/accumulators/framework/extractor.hpp>\r\n#include <boost/accumulators/framework/parameters/sample.hpp>\r\n#include <boost/accumulators/framework/depends_on.hpp>\r\n#include <boost/accumulators/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>\r\n#include <boost/accumulators/statistics/peaks_over_threshold.hpp> // for named parameters pot_threshold_value and pot_threshold_probability\r\n#include <boost/accumulators/statistics/sum.hpp>\r\n#include <boost/accumulators/statistics/tail_variate.hpp>\r\n\r\n#ifdef _MSC_VER\r\n# pragma warning(push)\r\n# pragma warning(disable: 4127) // conditional expression is constant\r\n#endif\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n\r\nnamespace impl\r\n{\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // weighted_peaks_over_threshold_impl\r\n    //  works with an explicit threshold value and does not depend on order statistics of weighted samples\r\n    /**\r\n        @brief Weighted Peaks over Threshold Method for Weighted Quantile and Weighted Tail Mean Estimation\r\n\r\n        @sa peaks_over_threshold_impl\r\n\r\n        @param quantile_probability\r\n        @param pot_threshold_value\r\n    */\r\n    template<typename Sample, typename Weight, typename LeftRight>\r\n    struct weighted_peaks_over_threshold_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::multiplies<Weight, Sample>::result_type weighted_sample;\r\n        typedef typename numeric::functional::average<weighted_sample, std::size_t>::result_type float_type;\r\n        // for boost::result_of\r\n        typedef boost::tuple<float_type, float_type, float_type> result_type;\r\n\r\n        template<typename Args>\r\n        weighted_peaks_over_threshold_impl(Args const &args)\r\n          : sign_((is_same<LeftRight, left>::value) ? -1 : 1)\r\n          , mu_(sign_ * numeric::average(args[sample | Sample()], (std::size_t)1))\r\n          , sigma2_(numeric::average(args[sample | Sample()], (std::size_t)1))\r\n          , w_sum_(numeric::average(args[weight | Weight()], (std::size_t)1))\r\n          , threshold_(sign_ * args[pot_threshold_value])\r\n          , fit_parameters_(boost::make_tuple(0., 0., 0.))\r\n          , is_dirty_(true)\r\n        {\r\n        }\r\n\r\n        template<typename Args>\r\n        void operator ()(Args const &args)\r\n        {\r\n            this->is_dirty_ = true;\r\n\r\n            if (this->sign_ * args[sample] > this->threshold_)\r\n            {\r\n                this->mu_ += args[weight] * args[sample];\r\n                this->sigma2_ += args[weight] * args[sample] * args[sample];\r\n                this->w_sum_ += args[weight];\r\n            }\r\n        }\r\n\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            if (this->is_dirty_)\r\n            {\r\n                this->is_dirty_ = false;\r\n\r\n                this->mu_ = this->sign_ * numeric::average(this->mu_, this->w_sum_);\r\n                this->sigma2_ = numeric::average(this->sigma2_, this->w_sum_);\r\n                this->sigma2_ -= this->mu_ * this->mu_;\r\n\r\n                float_type threshold_probability = numeric::average(sum_of_weights(args) - this->w_sum_, sum_of_weights(args));\r\n\r\n                float_type tmp = numeric::average(( this->mu_ - this->threshold_ )*( this->mu_ - this->threshold_ ), this->sigma2_);\r\n                float_type xi_hat = 0.5 * ( 1. - tmp );\r\n                float_type beta_hat = 0.5 * ( this->mu_ - this->threshold_ ) * ( 1. + tmp );\r\n                float_type beta_bar = beta_hat * std::pow(1. - threshold_probability, xi_hat);\r\n                float_type u_bar = this->threshold_ - beta_bar * ( std::pow(1. - threshold_probability, -xi_hat) - 1.)/xi_hat;\r\n                this->fit_parameters_ = boost::make_tuple(u_bar, beta_bar, xi_hat);\r\n            }\r\n\r\n            return this->fit_parameters_;\r\n        }\r\n\r\n    private:\r\n        short sign_;                         // for left tail fitting, mirror the extreme values\r\n        mutable float_type mu_;              // mean of samples above threshold\r\n        mutable float_type sigma2_;          // variance of samples above threshold\r\n        mutable float_type w_sum_;           // sum of weights of samples above threshold\r\n        float_type threshold_;\r\n        mutable result_type fit_parameters_; // boost::tuple that stores fit parameters\r\n        mutable bool is_dirty_;\r\n    };\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // weighted_peaks_over_threshold_prob_impl\r\n    //  determines threshold from a given threshold probability using order statistics\r\n    /**\r\n        @brief Peaks over Threshold Method for Quantile and Tail Mean Estimation\r\n\r\n        @sa weighted_peaks_over_threshold_impl\r\n\r\n        @param quantile_probability\r\n        @param pot_threshold_probability\r\n    */\r\n    template<typename Sample, typename Weight, typename LeftRight>\r\n    struct weighted_peaks_over_threshold_prob_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::multiplies<Weight, Sample>::result_type weighted_sample;\r\n        typedef typename numeric::functional::average<weighted_sample, std::size_t>::result_type float_type;\r\n        // for boost::result_of\r\n        typedef boost::tuple<float_type, float_type, float_type> result_type;\r\n\r\n        template<typename Args>\r\n        weighted_peaks_over_threshold_prob_impl(Args const &args)\r\n          : sign_((is_same<LeftRight, left>::value) ? -1 : 1)\r\n          , mu_(sign_ * numeric::average(args[sample | Sample()], (std::size_t)1))\r\n          , sigma2_(numeric::average(args[sample | Sample()], (std::size_t)1))\r\n          , threshold_probability_(args[pot_threshold_probability])\r\n          , fit_parameters_(boost::make_tuple(0., 0., 0.))\r\n          , is_dirty_(true)\r\n        {\r\n        }\r\n\r\n        void operator ()(dont_care)\r\n        {\r\n            this->is_dirty_ = true;\r\n        }\r\n\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            if (this->is_dirty_)\r\n            {\r\n                this->is_dirty_ = false;\r\n\r\n                float_type threshold = sum_of_weights(args)\r\n                             * ( ( is_same<LeftRight, left>::value ) ? this->threshold_probability_ : 1. - this->threshold_probability_ );\r\n\r\n                std::size_t n = 0;\r\n                Weight sum = Weight(0);\r\n\r\n                while (sum < threshold)\r\n                {\r\n                    if (n < static_cast<std::size_t>(tail_weights(args).size()))\r\n                    {\r\n                        mu_ += *(tail_weights(args).begin() + n) * *(tail(args).begin() + n);\r\n                        sigma2_ += *(tail_weights(args).begin() + n) * *(tail(args).begin() + n) * (*(tail(args).begin() + n));\r\n                        sum += *(tail_weights(args).begin() + n);\r\n                        n++;\r\n                    }\r\n                    else\r\n                    {\r\n                        if (std::numeric_limits<float_type>::has_quiet_NaN)\r\n                        {\r\n                            return boost::make_tuple(\r\n                                std::numeric_limits<float_type>::quiet_NaN()\r\n                              , std::numeric_limits<float_type>::quiet_NaN()\r\n                              , std::numeric_limits<float_type>::quiet_NaN()\r\n                            );\r\n                        }\r\n                        else\r\n                        {\r\n                            std::ostringstream msg;\r\n                            msg << \"index n = \" << n << \" is not in valid range [0, \" << tail(args).size() << \")\";\r\n                            boost::throw_exception(std::runtime_error(msg.str()));\r\n                            return boost::make_tuple(Sample(0), Sample(0), Sample(0));\r\n                        }\r\n                    }\r\n                }\r\n\r\n                float_type u = *(tail(args).begin() + n - 1) * this->sign_;\r\n\r\n\r\n                this->mu_ = this->sign_ * numeric::average(this->mu_, sum);\r\n                this->sigma2_ = numeric::average(this->sigma2_, sum);\r\n                this->sigma2_ -= this->mu_ * this->mu_;\r\n\r\n                if (is_same<LeftRight, left>::value)\r\n                    this->threshold_probability_ = 1. - this->threshold_probability_;\r\n\r\n                float_type tmp = numeric::average(( this->mu_ - u )*( this->mu_ - u ), this->sigma2_);\r\n                float_type xi_hat = 0.5 * ( 1. - tmp );\r\n                float_type beta_hat = 0.5 * ( this->mu_ - u ) * ( 1. + tmp );\r\n                float_type beta_bar = beta_hat * std::pow(1. - threshold_probability_, xi_hat);\r\n                float_type u_bar = u - beta_bar * ( std::pow(1. - threshold_probability_, -xi_hat) - 1.)/xi_hat;\r\n                this->fit_parameters_ = boost::make_tuple(u_bar, beta_bar, xi_hat);\r\n\r\n            }\r\n\r\n            return this->fit_parameters_;\r\n        }\r\n\r\n    private:\r\n        short sign_;                                // for left tail fitting, mirror the extreme values\r\n        mutable float_type mu_;                     // mean of samples above threshold u\r\n        mutable float_type sigma2_;                 // variance of samples above threshold u\r\n        mutable float_type threshold_probability_;\r\n        mutable result_type fit_parameters_;        // boost::tuple that stores fit parameters\r\n        mutable bool is_dirty_;\r\n    };\r\n\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::weighted_peaks_over_threshold\r\n//\r\nnamespace tag\r\n{\r\n    template<typename LeftRight>\r\n    struct weighted_peaks_over_threshold\r\n      : depends_on<sum_of_weights>\r\n      , pot_threshold_value\r\n    {\r\n        /// INTERNAL ONLY\r\n        typedef accumulators::impl::weighted_peaks_over_threshold_impl<mpl::_1, mpl::_2, LeftRight> impl;\r\n    };\r\n\r\n    template<typename LeftRight>\r\n    struct weighted_peaks_over_threshold_prob\r\n      : depends_on<sum_of_weights, tail_weights<LeftRight> >\r\n      , pot_threshold_probability\r\n    {\r\n        /// INTERNAL ONLY\r\n        typedef accumulators::impl::weighted_peaks_over_threshold_prob_impl<mpl::_1, mpl::_2, LeftRight> impl;\r\n    };\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::weighted_peaks_over_threshold\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::abstract_peaks_over_threshold> const weighted_peaks_over_threshold = {};\r\n\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_peaks_over_threshold)\r\n}\r\n\r\nusing extract::weighted_peaks_over_threshold;\r\n\r\n// weighted_peaks_over_threshold<LeftRight>(with_threshold_value) -> weighted_peaks_over_threshold<LeftRight>\r\ntemplate<typename LeftRight>\r\nstruct as_feature<tag::weighted_peaks_over_threshold<LeftRight>(with_threshold_value)>\r\n{\r\n    typedef tag::weighted_peaks_over_threshold<LeftRight> type;\r\n};\r\n\r\n// weighted_peaks_over_threshold<LeftRight>(with_threshold_probability) -> weighted_peaks_over_threshold_prob<LeftRight>\r\ntemplate<typename LeftRight>\r\nstruct as_feature<tag::weighted_peaks_over_threshold<LeftRight>(with_threshold_probability)>\r\n{\r\n    typedef tag::weighted_peaks_over_threshold_prob<LeftRight> type;\r\n};\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#ifdef _MSC_VER\r\n# pragma warning(pop)\r\n#endif\r\n\r\n#endif\r\n", "meta": {"hexsha": "d542123c25bf8a3dc4e9f558c0e87e61ed9f28bc", "size": 12258, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/accumulators/statistics/weighted_peaks_over_threshold.hpp", "max_stars_repo_name": "importlib/klib", "max_stars_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "master/core/third/boost/accumulators/statistics/weighted_peaks_over_threshold.hpp", "max_issues_repo_name": "isuhao/klib", "max_issues_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "master/core/third/boost/accumulators/statistics/weighted_peaks_over_threshold.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 42.2689655172, "max_line_length": 140, "alphanum_fraction": 0.5855767662, "num_tokens": 2572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.408520032416304}}
{"text": "// VMDモーションを間引く\n\n#include <vector>\n#include <Eigen/Core>\n#include \"VMD.h\"\n#include \"interpolate.h\"\n#include \"reducevmd.h\"\n\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n// head番目からtail番目のボーンキーフレームのうち、残すべきものを再帰的に探して返す。\n// ただし返値にtail番目のボーンは含まれないので、コール元で追加する必要がある。\nvector<VMD_Frame> reduce_bone_frame_recursive(const vector<VMD_Frame>& v, int head, int tail, float threshold_pos, float threshold_rot, bool bezier)\n{\n  float max_pos_err = 0.0;\n  float max_rot_err = 0.0;\n  int max_idx_pos = 0;\n  int max_idx_rot = 0;\n  VMD_Frame head_frame = v[head];\n  VMD_Frame tail_frame = v[tail];\n  const int bezier_interpolation_limit = 60;\n  if (bezier && tail - head < bezier_interpolation_limit) {\n    optimize_bezier_parameter(tail_frame, v, head, tail);\n  }\n\n  // headフレームの値とtailフレームの値によって決まる補完曲線(直線)から最も離れた(誤差の大きい)フレームを探す\n  for (int i = head + 1; i < tail; i++) {\n    VMD_Frame f = interpolate_frame(head_frame, tail_frame, i, bezier);\n    float pos_err = (f.position - v[i].position).norm();\n    if (pos_err > max_pos_err) {\n      max_idx_pos = i;\n      max_pos_err = pos_err;\n    }\n    float rot_err = fabs(f.rotation.angularDistance(v[i].rotation) * 180 / M_PI);\n    if (rot_err > max_rot_err) {\n      max_idx_rot = i;\n      max_rot_err = rot_err;\n    }\n  }\n\n  // 補間曲線から最も離れたフレームの誤差が閾値を超えていたら、そのフレーム(max_idx_*)を残し、\n  // [head, max_idx_*] と [max_idx_*, tail] のそれぞれの区間を再帰的に探す。\n  vector<VMD_Frame> v1;\n  if (max_pos_err > threshold_pos) {\n    v1 = reduce_bone_frame_recursive(v, head, max_idx_pos, threshold_pos, threshold_rot, bezier);\n    vector<VMD_Frame> v2 = reduce_bone_frame_recursive(v, max_idx_pos, tail, threshold_pos, threshold_rot, bezier);\n    v1.insert(v1.end(), v2.begin(), v2.end());\n  } else {\n    if (max_rot_err > threshold_rot) {\n      v1 = reduce_bone_frame_recursive(v, head, max_idx_rot, threshold_pos, threshold_rot, bezier);\n      vector<VMD_Frame> v2 = reduce_bone_frame_recursive(v, max_idx_rot, tail, threshold_pos, threshold_rot, bezier);\n      v1.insert(v1.end(), v2.begin(), v2.end());\n    } else {\n      v1.push_back(tail_frame);\n    }\n  }\n  return v1;\n}\n\n// head番目からtail番目のボーンキーフレームのうち、残すべきものを探して返す。\nvector<VMD_Frame> reduce_bone_frame(const vector<VMD_Frame>& v, int head, int tail, float threshold_pos, float threshold_rot, bool bezier)\n{\n  if (threshold_pos < 0 || threshold_rot < 0) {\n    vector<VMD_Frame> v1(v);\n    return v1;\n  }\n\n  vector<VMD_Frame> v1 = reduce_bone_frame_recursive(v, head, tail, threshold_pos, threshold_rot, bezier);\n  v1.insert(v1.begin(), v.front());\n\n  return v1;\n}\n  \n// head番目からtail番目の表情キーフレームのうち、残すべきものを再帰的に探して返す。\n// ただし返値にtail番目のフレームは含まれないので、コール元で追加する必要がある。\nvector<VMD_Morph> reduce_morph_frame_recursive(const vector<VMD_Morph>& v, int head, int tail, float threshold)\n{\n  float max = 0.0;\n  int max_idx = 0;\n  int total = tail - head;\n  for (int i = head + 1; i < tail; i++) {\n    float iv = v[head].weight + (v[tail].weight - v[head].weight) * (i - head) / total;\n    float e = abs(iv - v[i].weight);\n    if (e > max) {\n      max_idx = i;\n      max = e;\n    }\n  }\n\n  vector<VMD_Morph> v1;\n  if (max > threshold) {\n    v1 = reduce_morph_frame_recursive(v, head, max_idx, threshold);\n    vector<VMD_Morph> v2 = reduce_morph_frame_recursive(v, max_idx, tail, threshold);\n    v1.insert(v1.end(), v2.begin(), v2.end());\n  } else {\n    v1.push_back(v[head]);\n  }\n  return v1;\n}\n\n// head番目からtail番目の表情キーフレームのうち、残すべきものを探して返す。\nvector<VMD_Morph> reduce_morph_frame(const vector<VMD_Morph>& v, int head, int tail, float threshold)\n{\n  if (threshold < 0) {\n    vector<VMD_Morph> v1(v);\n    return v1;\n  }\n\n  vector<VMD_Morph> v1 = reduce_morph_frame_recursive(v, head, tail, threshold);\n  v1.push_back(v.back());\n  return v1;\n}\n\n", "meta": {"hexsha": "1941702dde47d94d5f04ee7e4758f96d10ffcc11", "size": 3677, "ext": "cc", "lang": "C++", "max_stars_repo_path": "reducevmd.cc", "max_stars_repo_name": "ikeno-ikeo/readfacevmd", "max_stars_repo_head_hexsha": "854354812cbe27531afe8681c1b5b1df7207a42b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 49.0, "max_stars_repo_stars_event_min_datetime": "2018-05-19T07:28:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T07:16:06.000Z", "max_issues_repo_path": "reducevmd.cc", "max_issues_repo_name": "ikeno-ikeo/readfacevmd", "max_issues_repo_head_hexsha": "854354812cbe27531afe8681c1b5b1df7207a42b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-05-29T10:10:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T00:42:49.000Z", "max_forks_repo_path": "reducevmd.cc", "max_forks_repo_name": "ikeno-ikeo/readfacevmd", "max_forks_repo_head_hexsha": "854354812cbe27531afe8681c1b5b1df7207a42b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-03T20:58:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T09:06:47.000Z", "avg_line_length": 31.9739130435, "max_line_length": 148, "alphanum_fraction": 0.6915964101, "num_tokens": 1371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721305, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.40845062269331933}}
{"text": "//\n// VariationalBayesEstimatorOnATM.hpp\n//\n// Copyright (c) 2017 Shion Hosoda\n//\n// This software is released under the MIT License.\n// http://opensource.org/licenses/mit-license.php\n//\n\n#ifndef VBATM\n#define VBATM\n\n#include<stdlib.h>\n#include<math.h>\n#include<cmath>\n#include<iostream>\n#include<vector>\n#include<numeric>\n#include<memory>\n#include<random>\n#include<iomanip>\n#include<fstream>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include\"BOWFileParser.hpp\"\n#include\"AuthorFileParser.hpp\"\n#include\"utils.hpp\"\n\n\nenum BetaUpdateManner{\n    SYMMETRY, ASYMMETRY\n};\n\nclass VariationalBayesEstimatorOnATM{\nprotected:\n    const std::vector<std::vector<unsigned int> > &_frequencyMatrix;\n    const std::vector<std::vector<unsigned int> > &_docVoca;\n    const unsigned int _K, _V, _D, _M;\n    const std::vector<std::vector<unsigned int> > &_docAuth;\n    double _convergenceDiterminationRate;\n    std::vector<std::vector<std::vector<std::vector<double> > > > _qzy;\n    std::vector<std::vector<double> > _thetaEx, _phiEx;\n    std::vector<double> _alpha, _beta;\n    double _alphaSum, _betaSum;\n    std::vector<std::vector<double> > _alphaTimeSeries, _betaTimeSeries;\n    std::vector<double> _nm, _nk;\n    std::vector<std::vector<double> > _nmk, _nkv;\n    double _variationalLowerBound;\n    std::vector<double> _VLBTimeSeries;\npublic:\n    VariationalBayesEstimatorOnATM(const BOWFileParser &parser, const AuthorFileParser &aParser, const unsigned int K, const double convergenceDiterminationRate);\n    virtual ~VariationalBayesEstimatorOnATM();\n    virtual void initializeParam();\n    virtual void initializeHyperParam();\n    virtual void calculateEx();\n    virtual void calculateHyperParamSum();\n    virtual void updateQzy();\n    virtual void updateNEx();\n    virtual void updateBeta(BetaUpdateManner manner);\n    virtual void updateHyperParameters();\n    virtual double calculateVariationalLowerBound()const;\n    virtual void writeParameter(std::string thetaFilename, std::string phiFilename, std::string alphaFilename, std::string betaFilename)const;\n    virtual void writeVariationalLowerBound(std::string VLBFilename, std::string VLBTimeSeriesFilename)const;\n    virtual void runIteraions();\n};\n\n#endif\n", "meta": {"hexsha": "ef77c882953fddc78c92bc786d99c39e41380c7c", "size": 2260, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/VariationalBayesEstimatorOnATM.hpp", "max_stars_repo_name": "shion-h/TopicModels", "max_stars_repo_head_hexsha": "7c9f0653163cf3b583010c45e981a56da1339a8a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-22T09:47:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-20T03:48:15.000Z", "max_issues_repo_path": "src/include/VariationalBayesEstimatorOnATM.hpp", "max_issues_repo_name": "shion-h/TopicModels", "max_issues_repo_head_hexsha": "7c9f0653163cf3b583010c45e981a56da1339a8a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/VariationalBayesEstimatorOnATM.hpp", "max_forks_repo_name": "shion-h/TopicModels", "max_forks_repo_head_hexsha": "7c9f0653163cf3b583010c45e981a56da1339a8a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2352941176, "max_line_length": 162, "alphanum_fraction": 0.753539823, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4084506226933193}}
{"text": "/* -------------------------------------------------------------------------\n *  A repertory of multi primitive-to-primitive (MP2P) ICP algorithms in C++\n * Copyright (C) 2018-2021 Jose Luis Blanco, University of Almeria\n * See LICENSE for license information.\n * ------------------------------------------------------------------------- */\n/**\n * @file   covariance.cpp\n * @brief  Covariance estimation methods for ICP results\n * @author Jose Luis Blanco Claraco\n * @date   Jun 9, 2020\n */\n\n#include <mp2p_icp/covariance.h>\n#include <mp2p_icp/errorTerms.h>\n#include <mrpt/math/CVectorDynamic.h>\n#include <mrpt/math/num_jacobian.h>\n\n#include <Eigen/Dense>\n\nusing namespace mp2p_icp;\n\nmrpt::math::CMatrixDouble66 mp2p_icp::covariance(\n    const Pairings& in, const mrpt::poses::CPose3D& finalAlignSolution,\n    const CovarianceParameters& param)\n{\n    // If we don't have pairings, we can't provide an estimation:\n    if (in.empty())\n    {\n        mrpt::math::CMatrixDouble66 cov;\n        cov.setDiagonal(1e6);\n        return cov;\n    }\n\n    mrpt::math::CMatrixDouble61 xInitial;\n    xInitial[0] = finalAlignSolution.x();\n    xInitial[1] = finalAlignSolution.y();\n    xInitial[0] = finalAlignSolution.x();\n    xInitial[3] = finalAlignSolution.yaw();\n    xInitial[4] = finalAlignSolution.pitch();\n    xInitial[5] = finalAlignSolution.roll();\n\n    mrpt::math::CMatrixDouble61 xIncrs;\n    for (int i = 0; i < 3; i++) xIncrs[i] = param.finDif_xyz;\n    for (int i = 0; i < 3; i++) xIncrs[3 + i] = param.finDif_angles;\n\n    struct LambdaParams\n    {\n    };\n\n    LambdaParams lmbParams;\n\n    auto errorLambda = [&](const mrpt::math::CMatrixDouble61& x,\n                           const LambdaParams&,\n                           mrpt::math::CVectorDouble& err) {\n        mrpt::poses::CPose3D pose;\n        pose.setFromValues(x[0], x[1], x[2], x[3], x[4], x[5]);\n\n        const auto nPt2Pt = in.paired_pt2pt.size();\n        const auto nPt2Ln = in.paired_pt2ln.size();\n        const auto nPt2Pl = in.paired_pt2pl.size();\n        const auto nPl2Pl = in.paired_pl2pl.size();\n        const auto nLn2Ln = in.paired_ln2ln.size();\n\n        const auto nErrorTerms =\n            (nPt2Pt + nPl2Pl + nPt2Ln + nPt2Pl) * 3 + nLn2Ln * 4;\n        ASSERT_(nErrorTerms > 0);\n        err.resize(nErrorTerms);\n\n        // Point-to-point:\n        for (size_t idx_pt = 0; idx_pt < nPt2Pt; idx_pt++)\n        {\n            // Error:\n            const auto&                       p = in.paired_pt2pt[idx_pt];\n            mrpt::math::CVectorFixedDouble<3> ret =\n                mp2p_icp::error_point2point(p, pose);\n            err.block<3, 1>(idx_pt * 3, 0) = ret.asEigen();\n        }\n        auto base_idx = nPt2Pt * 3;\n\n        // Point-to-line\n        for (size_t idx_pt = 0; idx_pt < nPt2Ln; idx_pt++)\n        {\n            // Error\n            const auto&                       p = in.paired_pt2ln[idx_pt];\n            mrpt::math::CVectorFixedDouble<3> ret =\n                mp2p_icp::error_point2line(p, pose);\n            err.block<3, 1>(base_idx + idx_pt * 3, 0) = ret.asEigen();\n        }\n        base_idx += nPt2Ln * 3;\n\n        // Line-to-Line\n        // Minimum angle to approach zero\n        for (size_t idx_ln = 0; idx_ln < nLn2Ln; idx_ln++)\n        {\n            const auto&                       p = in.paired_ln2ln[idx_ln];\n            mrpt::math::CVectorFixedDouble<4> ret =\n                mp2p_icp::error_line2line(p, pose);\n            err.block<4, 1>(base_idx + idx_ln * 4, 0) = ret.asEigen();\n        }\n        base_idx += nLn2Ln;\n\n        // Point-to-plane:\n        for (size_t idx_pl = 0; idx_pl < nPt2Pl; idx_pl++)\n        {\n            // Error:\n            const auto&                       p = in.paired_pt2pl[idx_pl];\n            mrpt::math::CVectorFixedDouble<3> ret =\n                mp2p_icp::error_point2plane(p, pose);\n            err.block<3, 1>(idx_pl * 3 + base_idx, 0) = ret.asEigen();\n        }\n        base_idx += nPt2Pl * 3;\n\n        // Plane-to-plane (only direction of normal vectors):\n        for (size_t idx_pl = 0; idx_pl < nPl2Pl; idx_pl++)\n        {\n            // Error term:\n            const auto&                       p = in.paired_pl2pl[idx_pl];\n            mrpt::math::CVectorFixedDouble<3> ret =\n                mp2p_icp::error_plane2plane(p, pose);\n            err.block<3, 1>(idx_pl * 3 + base_idx, 0) = ret.asEigen();\n        }\n    };\n\n    // Do NOT use \"Eigen::MatrixXd\", it may have different alignment\n    // requirements than MRPT matrices:\n    mrpt::math::CMatrixDouble jacob;\n    mrpt::math::estimateJacobian(\n        xInitial,\n        std::function<void(\n            const mrpt::math::CMatrixDouble61&, const LambdaParams&,\n            mrpt::math::CVectorDouble&)>(errorLambda),\n        xIncrs, lmbParams, jacob);\n\n    const mrpt::math::CMatrixDouble66 hessian(\n        jacob.asEigen().transpose() * jacob.asEigen());\n\n    const mrpt::math::CMatrixDouble66 cov = hessian.inverse_LLt();\n\n    return cov;\n}\n\n// other ideas?\n// See: http://censi.mit.edu/pub/research/2007-icra-icpcov-slides.pdf\n", "meta": {"hexsha": "3ac23c9e40cb003ea6bafcc11c3c0ef20edd5cd0", "size": 5025, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mp2p_icp/src/covariance.cpp", "max_stars_repo_name": "MOLAorg/mp2_icp", "max_stars_repo_head_hexsha": "e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-07T08:10:09.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-07T15:01:02.000Z", "max_issues_repo_path": "mp2p_icp/src/covariance.cpp", "max_issues_repo_name": "MOLAorg/mp2_icp", "max_issues_repo_head_hexsha": "e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mp2p_icp/src/covariance.cpp", "max_forks_repo_name": "MOLAorg/mp2_icp", "max_forks_repo_head_hexsha": "e53a5f5f2cc6b86a095d1cba6f07f03c13a72abb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8958333333, "max_line_length": 79, "alphanum_fraction": 0.5526368159, "num_tokens": 1432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.5273165233795672, "lm_q1q2_score": 0.40845061720542714}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"poses-precomp.h\"  // Precompiled headers\n\n#include <mrpt/poses/CPose2DInterpolator.h>\n#include <mrpt/serialization/stl_serialization.h>\n#include <Eigen/Dense>\n#include \"CPoseInterpolatorBase.hpp\"  // templ impl\n\nusing namespace mrpt::poses;\n\nIMPLEMENTS_SERIALIZABLE(CPose2DInterpolator, CSerializable, mrpt::poses)\n\nuint8_t CPose2DInterpolator::serializeGetVersion() const { return 0; }\nvoid CPose2DInterpolator::serializeTo(mrpt::serialization::CArchive& out) const\n{\n\tout << m_path;\n}\nvoid CPose2DInterpolator::serializeFrom(\n\tmrpt::serialization::CArchive& in, uint8_t version)\n{\n\tswitch (version)\n\t{\n\t\tcase 0:\n\t\t{\n\t\t\tin >> m_path;\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tMRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version);\n\t};\n}\n\nnamespace mrpt::poses\n{\n// Specialization for DIM=2\ntemplate <>\nvoid CPoseInterpolatorBase<2>::impl_interpolation(\n\tconst TTimePosePair& p1, const TTimePosePair& p2, const TTimePosePair& p3,\n\tconst TTimePosePair& p4, const TInterpolatorMethod method,\n\tconst mrpt::Clock::time_point& t, pose_t& out_interp) const\n{\n\tusing mrpt::math::TPose2D;\n\tusing doubleDuration = std::chrono::duration<double>;\n\tdoubleDuration durationT(t.time_since_epoch());\n\tdouble td = durationT.count();\n\tmrpt::math::CVectorFixedDouble<4> ts;\n\tts[0] =\n\t\tstd::chrono::duration_cast<doubleDuration>(p1.first.time_since_epoch())\n\t\t\t.count();\n\tts[1] =\n\t\tstd::chrono::duration_cast<doubleDuration>(p2.first.time_since_epoch())\n\t\t\t.count();\n\tts[2] =\n\t\tstd::chrono::duration_cast<doubleDuration>(p3.first.time_since_epoch())\n\t\t\t.count();\n\tts[3] =\n\t\tstd::chrono::duration_cast<doubleDuration>(p4.first.time_since_epoch())\n\t\t\t.count();\n\n\tmrpt::math::CVectorFixedDouble<4> X, Y, yaw;\n\tX[0] = p1.second.x;\n\tY[0] = p1.second.y;\n\tyaw[0] = p1.second.phi;\n\tX[1] = p2.second.x;\n\tY[1] = p2.second.y;\n\tyaw[1] = p2.second.phi;\n\tX[2] = p3.second.x;\n\tY[2] = p3.second.y;\n\tyaw[2] = p3.second.phi;\n\tX[3] = p4.second.x;\n\tY[3] = p4.second.y;\n\tyaw[3] = p4.second.phi;\n\n\tunwrap2PiSequence(yaw);\n\n\t// Target interpolated values:\n\tswitch (method)\n\t{\n\t\tcase imSpline:\n\t\t{\n\t\t\t// ---------------------------------------\n\t\t\t//    SPLINE INTERPOLATION\n\t\t\t// ---------------------------------------\n\t\t\tout_interp.x = math::spline(td, ts, X);\n\t\t\tout_interp.y = math::spline(td, ts, Y);\n\t\t\tout_interp.phi = math::spline(td, ts, yaw, true);  // Wrap 2pi\n\t\t}\n\t\tbreak;\n\n\t\tcase imLinear2Neig:\n\t\t{\n\t\t\tout_interp.x =\n\t\t\t\tmath::interpolate2points(td, ts[1], X[1], ts[2], X[2]);\n\t\t\tout_interp.y =\n\t\t\t\tmath::interpolate2points(td, ts[1], Y[1], ts[2], Y[2]);\n\t\t\tout_interp.phi = math::interpolate2points(\n\t\t\t\ttd, ts[1], yaw[1], ts[2], yaw[2], true);  // Wrap 2pi\n\t\t}\n\t\tbreak;\n\n\t\tcase imLinear4Neig:\n\t\t{\n\t\t\tout_interp.x =\n\t\t\t\tmath::leastSquareLinearFit<double, decltype(ts), 4>(td, ts, X);\n\t\t\tout_interp.y =\n\t\t\t\tmath::leastSquareLinearFit<double, decltype(ts), 4>(td, ts, Y);\n\t\t\tout_interp.phi =\n\t\t\t\tmath::leastSquareLinearFit<double, decltype(ts), 4>(\n\t\t\t\t\ttd, ts, yaw, true);  // Wrap 2pi\n\t\t}\n\t\tbreak;\n\n\t\tcase imSSLLLL:\n\t\t{\n\t\t\tout_interp.x = math::spline(td, ts, X);\n\t\t\tout_interp.y = math::spline(td, ts, Y);\n\t\t\tout_interp.phi =\n\t\t\t\tmath::leastSquareLinearFit<double, decltype(ts), 4>(\n\t\t\t\t\ttd, ts, yaw, true);  // Wrap 2pi\n\t\t}\n\t\tbreak;\n\n\t\tcase imSSLSLL:\n\t\t{\n\t\t\tout_interp.x = math::spline(td, ts, X);\n\t\t\tout_interp.y = math::spline(td, ts, Y);\n\t\t\tout_interp.phi = math::spline(td, ts, yaw, true);  // Wrap 2pi\n\t\t}\n\t\tbreak;\n\n\t\tcase imLinearSlerp:\n\t\t{\n\t\t\tconst double ratio = (td - ts[1]) / (ts[2] - ts[1]);\n\t\t\tconst double Aang = mrpt::math::angDistance(yaw[1], yaw[2]);\n\t\t\tout_interp.phi = yaw[1] + ratio * Aang;\n\n\t\t\tout_interp.x =\n\t\t\t\tmath::interpolate2points(td, ts[1], X[1], ts[2], X[2]);\n\t\t\tout_interp.y =\n\t\t\t\tmath::interpolate2points(td, ts[1], Y[1], ts[2], Y[2]);\n\t\t}\n\t\tbreak;\n\n\t\tcase imSplineSlerp:\n\t\t{\n\t\t\tconst double ratio = (td - ts[1]) / (ts[2] - ts[1]);\n\t\t\tconst double Aang = mrpt::math::angDistance(yaw[1], yaw[2]);\n\t\t\tout_interp.phi = yaw[1] + ratio * Aang;\n\n\t\t\tout_interp.x = math::spline(td, ts, X);\n\t\t\tout_interp.y = math::spline(td, ts, Y);\n\t\t}\n\t\tbreak;\n\n\t\tdefault:\n\t\t\tTHROW_EXCEPTION(\"Unknown value for interpolation method!\");\n\t};  // end switch\n}\n\n// Explicit instantations:\ntemplate class CPoseInterpolatorBase<2>;\n}  // namespace mrpt::poses\n", "meta": {"hexsha": "e1f334893a4de210043e345d0b94fcfc825a635e", "size": 4854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/poses/src/CPose2DInterpolator.cpp", "max_stars_repo_name": "zarmomin/mrpt", "max_stars_repo_head_hexsha": "1baff7cf8ec9fd23e1a72714553bcbd88c201966", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T06:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T06:24:08.000Z", "max_issues_repo_path": "libs/poses/src/CPose2DInterpolator.cpp", "max_issues_repo_name": "gao-ouyang/mrpt", "max_issues_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/poses/src/CPose2DInterpolator.cpp", "max_forks_repo_name": "gao-ouyang/mrpt", "max_forks_repo_head_hexsha": "4af5fdf7e45b00be4a64c3d4f009acb9ef415ec7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T02:55:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T02:55:04.000Z", "avg_line_length": 28.3859649123, "max_line_length": 80, "alphanum_fraction": 0.6032138443, "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649232, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.40845061720542697}}
{"text": "#ifndef CX_DQMC_CHECKERBOARD_HPP\n#define CX_DQMC_CHECKERBOARD_HPP\n\n#include \"la.hpp\"\n#include \"parameters.hpp\"\n\n#include <boost/multi_array.hpp>\n\n#include <exception>\n#include <cmath>\n#include <memory>\n\nnamespace cx_dqmc {\n    namespace checkerboard {\n\n\tinline void graph_to_checkerboard(dqmc::parameters& p, cx_dqmc::workspace& ws) {\n\t    for (int i = 0; i < p.graph.num_bonds(); ++i) {\n\t\tws.bond_used[i] = -1;\n\t    }\n\t    \n\t    int bonds_used = 0;\n\t    int sites_used = 0;\n\t    int first_unused_bond = 0;\n\n\t    alps::graph_helper<>::bond_iterator itr1, itr1_end;\n\t    int b, s1, s2;\n\t    double t, im_t;\n\t    while (bonds_used < p.graph.num_bonds()) {\n\t\tsp_mat hopping(p.N, p.N);\n\t\tsp_mat hopping_inv(p.N, p.N);\n\n\t\tcx_sp_mat cx_hopping(p.N, p.N);\n\t\tcx_sp_mat cx_hopping_inv(p.N, p.N);\n\n\t\tint elements = 0;\n\t\t    \n\t\tfor (int i = 0; i < p.N; ++i) { ws.site_used[i] = -1; }\n\t\t\n\t\tfor (boost::tie(itr1, itr1_end) = p.graph.bonds(); itr1 != itr1_end; ++itr1) {\t   \n\t\t    b = p.graph.index(*itr1);\n\t\t    s1 = p.graph.source(*itr1);\n\t\t    s2 = p.graph.target(*itr1);\n\t\t    \n\t\t    if (ws.bond_used[b] == 1) continue;\n\t\t    if (ws.site_used[s1] == 1 || ws.site_used[s2] == 1) continue;\n\t\t    \n\t\t    ws.bond_used[b] = 1;\n\t\t    ws.site_used[s1] = 1;\n\t\t    ws.site_used[s2] = 1;\n\t\t    t = p.ts[p.graph.bond_type(*itr1)];\n\n\t\t    if (p.complex_hoppings == false) {\n\t\t\thopping.insert(s1, s1) = cosh(t * p.delta_tau/2.);\n\t\t\thopping.insert(s2, s2) = cosh(t * p.delta_tau/2.);\n\t\t\thopping.insert(s1, s2) = sinh(t * p.delta_tau/2.);\n\t\t\thopping.insert(s2, s1) = sinh(t * p.delta_tau/2.);\n\t\t    \n\t\t\thopping_inv.insert(s1, s1) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_inv.insert(s2, s2) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_inv.insert(s1, s2) = -sinh(t * p.delta_tau/2.);\n\t\t\thopping_inv.insert(s2, s1) = -sinh(t * p.delta_tau/2.);\n\t\t    } else {\n\t\t\tim_t = p.im_ts[p.graph.bond_type(*itr1)];\t\t\t\n\t\t\tstd::complex<double> cx_t(t, im_t);\n\t\t\tstd::complex<double> abs_t(sqrt(t*t + im_t*im_t), 0);\n\t\t\tcx_hopping.insert(s1, s1) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping.insert(s2, s2) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping.insert(s1, s2) = sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t;\n\t\t\tcx_hopping.insert(s2, s1) = sinh(abs_t * p.delta_tau/2.) * std::conj(cx_t / abs_t);\n\t\t    \n\t\t\tcx_hopping_inv.insert(s1, s1) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_inv.insert(s2, s2) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_inv.insert(s1, s2) = -(sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t);\n\t\t\tcx_hopping_inv.insert(s2, s1) = -sinh(abs_t * p.delta_tau/2.) * std::conj(cx_t / abs_t);\n\t\t    }\n\t\t    // std::cout << \"Using \" << s1 << \" and \" << s2 << std::endl;\n\t\t    ++bonds_used;\n\t\t    ++elements;\n\t\t}\n\n\t\tif (elements != 0) {\n\t\t    for (int i = 0; i < p.N; ++i) {\n\t\t\tif(ws.site_used[i] == -1) {\n\t\t\t    if (p.complex_hoppings == false) {\n\t\t\t\thopping.insert(i, i) = 1.;\n\t\t\t\thopping_inv.insert(i, i) = 1.;\n\t\t\t    } else {\n\t\t\t\tcx_hopping.insert(i, i) = std::complex<double>(1., 0.);\n\t\t\t\tcx_hopping_inv.insert(i, i) = std::complex<double>(1., 0.);\n\t\t\t    }\t\t\t\t\n\t\t\t}\n\t\t    }\n\t\t    // arma::mat(hopping).print(\"A hopping matrix\");\n\n\t\t    if (p.complex_hoppings == false) {\n\t\t\tws.sparse_hoppings.push_back(hopping);\n\t\t\tws.sparse_hoppings_inv.push_back(hopping_inv);\n\t\t    } else {\n\t\t\tws.cx_sparse_hoppings.push_back(cx_hopping);\n\t\t\tws.cx_sparse_hoppings_inv.push_back(cx_hopping_inv);\n\t\t    }\n\t\t}\n\t    }\t    \n\t}\n\n\tinline void graph_to_checkerboard_renyi(dqmc::parameters& p, cx_dqmc::workspace& ws) {\n\t    for (int i = 0; i < p.graph.num_bonds(); ++i) { ws.bond_used[i] = -1; }\n\t    \n\t    int bonds_used = 0;\n\t    int sites_used = 0;\n\t    int first_unused_bond = 0;\n\n\t    alps::graph_helper<>::bond_iterator itr1, itr1_end;\n\t    int b, s1, s2, s1a, s2a;\n\t    double t;\n\t    std::complex<double> one(1., 0.);\n\t    \n\t    while (bonds_used < p.graph.num_bonds()) {\n\t\tsp_mat hopping_0(ws.vol, ws.vol), hopping_0_inv(ws.vol, ws.vol),\n\t\t    hopping_1(ws.vol, ws.vol), hopping_1_inv(ws.vol, ws.vol),\n\t\t    hopping_2(ws.vol, ws.vol), hopping_2_inv(ws.vol, ws.vol),\n\t\t    hopping_3(ws.vol, ws.vol), hopping_3_inv(ws.vol, ws.vol);\n\n\t\tcx_sp_mat cx_hopping_0(ws.vol, ws.vol), cx_hopping_0_inv(ws.vol, ws.vol),\n\t\t    cx_hopping_1(ws.vol, ws.vol), cx_hopping_1_inv(ws.vol, ws.vol),\n\t\t    cx_hopping_2(ws.vol, ws.vol), cx_hopping_2_inv(ws.vol, ws.vol),\n\t\t    cx_hopping_3(ws.vol, ws.vol), cx_hopping_3_inv(ws.vol, ws.vol);\n\t\t\n\t\tint elements = 0;\n\t\t\n\t\tfor (int i = 0; i < p.N; ++i) ws.site_used[i] = -1;\n\t\tfor (int i = 0; i < p.N + p.n_B; ++i) {\n\t\t    if (p.complex_hoppings == false) {\n\t\t\thopping_0.insert(i, i) = 1.;\n\t\t\thopping_0_inv.insert(i, i) = 1.;\n\t\t\thopping_1.insert(i, i) = 1.;\n\t\t\thopping_1_inv.insert(i, i) = 1.;\t\t\t\n\t\t\thopping_2.insert(i, i) = 1.;\n\t\t\thopping_2_inv.insert(i, i) = 1.;\n\t\t\thopping_3.insert(i, i) = 1.;\n\t\t\thopping_3_inv.insert(i, i) = 1.;\n\t\t    } else {\n\t\t\tcx_hopping_0.insert(i, i) = one;\n\t\t\tcx_hopping_0_inv.insert(i, i) = one;\n\t\t\tcx_hopping_1.insert(i, i) = one;\n\t\t\tcx_hopping_1_inv.insert(i, i) = one;\n\t\t\tcx_hopping_2.insert(i, i) = one;\n\t\t\tcx_hopping_2_inv.insert(i, i) = one;\n\t\t\tcx_hopping_3.insert(i, i) = one;\n\t\t\tcx_hopping_3_inv.insert(i, i) = one;\n\t\t    }\n\t\t}\n\t\t\n\t\tfor (boost::tie(itr1, itr1_end) = p.graph.bonds(); itr1 != itr1_end; ++itr1) {\t   \n\t\t    b = p.graph.index(*itr1);\n\t\t    s1 = p.graph.source(*itr1);\n\t\t    s2 = p.graph.target(*itr1);\n\t\t    s1a = s1;\n\t\t    s2a = s2;\n\t\t    \n\t\t    if (ws.bond_used[b] == 1) continue;\n\t\t    if (ws.site_used[s1] == 1 || ws.site_used[s2] == 1) continue;\n\t\t    \n\t\t    ws.bond_used[b] = 1;\n\t\t    ws.site_used[s1] = 1;\n\t\t    ws.site_used[s2] = 1;\n\n\t\t    t = p.ts[p.graph.bond_type(*itr1)];\t\n\t\t    \n\t\t    if (s1 >= p.n_A) s1a = s1 + p.n_B;\n\t\t    if (s2 >= p.n_A) s2a = s2 + p.n_B;\n\n\t\t    if (p.complex_hoppings == false) {\n\t\t\thopping_0.coeffRef(s1, s1) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_0.coeffRef(s2, s2) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_0.coeffRef(s1, s2) = sinh(t * p.delta_tau/2.);\n\t\t\thopping_0.coeffRef(s2, s1) = sinh(t * p.delta_tau/2.);\n\t\t    \n\t\t\thopping_0_inv.coeffRef(s1, s1) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_0_inv.coeffRef(s2, s2) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_0_inv.coeffRef(s1, s2) = -sinh(t * p.delta_tau/2.);\n\t\t\thopping_0_inv.coeffRef(s2, s1) = -sinh(t * p.delta_tau/2.);\n\t\t    \n\t\t\thopping_1.coeffRef(s1, s1) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_1.coeffRef(s2, s2) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_1.coeffRef(s1, s2) = sinh(t * p.delta_tau/2.);\n\t\t\thopping_1.coeffRef(s2, s1) = sinh(t * p.delta_tau/2.);\n\t\t    \n\t\t\thopping_1_inv.coeffRef(s1, s1) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_1_inv.coeffRef(s2, s2) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_1_inv.coeffRef(s1, s2) = -sinh(t * p.delta_tau/2.);\n\t\t\thopping_1_inv.coeffRef(s2, s1) = -sinh(t * p.delta_tau/2.);\n\t\t\t\n\t\t\thopping_2.coeffRef(s1a, s1a) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_2.coeffRef(s2a, s2a) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_2.coeffRef(s1a, s2a) = sinh(t * p.delta_tau/2.);\n\t\t\thopping_2.coeffRef(s2a, s1a) = sinh(t * p.delta_tau/2.);\n\n\t\t\thopping_2_inv.coeffRef(s1a, s1a) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_2_inv.coeffRef(s2a, s2a) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_2_inv.coeffRef(s1a, s2a) = -sinh(t * p.delta_tau/2.);\n\t\t\thopping_2_inv.coeffRef(s2a, s1a) = -sinh(t * p.delta_tau/2.);\n\n\t\t\thopping_3.coeffRef(s1a, s1a) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_3.coeffRef(s2a, s2a) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_3.coeffRef(s1a, s2a) = sinh(t * p.delta_tau/2.);\n\t\t\thopping_3.coeffRef(s2a, s1a) = sinh(t * p.delta_tau/2.);\n\n\t\t\thopping_3_inv.coeffRef(s1a, s1a) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_3_inv.coeffRef(s2a, s2a) = cosh(t * p.delta_tau/2.);\n\t\t\thopping_3_inv.coeffRef(s1a, s2a) = -sinh(t * p.delta_tau/2.);\n\t\t\thopping_3_inv.coeffRef(s2a, s1a) = -sinh(t * p.delta_tau/2.);\n\t\t    } else {\n\t\t\tdouble im_t = p.im_ts[p.graph.bond_type(*itr1)];\n\t\t\tstd::complex<double> cx_t(t, im_t);\n\t\t\tstd::complex<double> abs_t(sqrt(t*t + im_t*im_t), 0);\n\t\t\tcx_hopping_0.coeffRef(s1, s1) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_0.coeffRef(s2, s2) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_0.coeffRef(s1, s2) = sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t;\n\t\t\tcx_hopping_0.coeffRef(s2, s1) = sinh(abs_t * p.delta_tau/2.) * std::conj(cx_t / abs_t);\n\t\t    \n\t\t\tcx_hopping_0_inv.coeffRef(s1, s1) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_0_inv.coeffRef(s2, s2) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_0_inv.coeffRef(s1, s2) = -(sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t ) ;\n\t\t\tcx_hopping_0_inv.coeffRef(s2, s1) = -sinh(abs_t * p.delta_tau/2.) * std::conj(cx_t / abs_t );\n\t\t    \n\t\t\tcx_hopping_1.coeffRef(s1, s1) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_1.coeffRef(s2, s2) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_1.coeffRef(s1, s2) = sinh(abs_t * p.delta_tau/2.)  * cx_t / abs_t;\n\t\t\tcx_hopping_1.coeffRef(s2, s1) = std::conj(sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t);\n\t\t    \n\t\t\tcx_hopping_1_inv.coeffRef(s1, s1) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_1_inv.coeffRef(s2, s2) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_1_inv.coeffRef(s1, s2) = -(sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t);\n\t\t\tcx_hopping_1_inv.coeffRef(s2, s1) = -std::conj(sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t);\n\t\t\t\n\t\t\tcx_hopping_2.coeffRef(s1a, s1a) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_2.coeffRef(s2a, s2a) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_2.coeffRef(s1a, s2a) = sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t;\n\t\t\tcx_hopping_2.coeffRef(s2a, s1a) = std::conj(sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t);\n\n\t\t\tcx_hopping_2_inv.coeffRef(s1a, s1a) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_2_inv.coeffRef(s2a, s2a) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_2_inv.coeffRef(s1a, s2a) = -(sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t);\n\t\t\tcx_hopping_2_inv.coeffRef(s2a, s1a) = -std::conj(sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t);\n\n\t\t\tcx_hopping_3.coeffRef(s1a, s1a) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_3.coeffRef(s2a, s2a) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_3.coeffRef(s1a, s2a) = sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t;\n\t\t\tcx_hopping_3.coeffRef(s2a, s1a) = std::conj(sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t);\n\n\t\t\tcx_hopping_3_inv.coeffRef(s1a, s1a) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_3_inv.coeffRef(s2a, s2a) = cosh(abs_t * p.delta_tau/2.);\n\t\t\tcx_hopping_3_inv.coeffRef(s1a, s2a) = -(sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t);\n\t\t\tcx_hopping_3_inv.coeffRef(s2a, s1a) = -std::conj(sinh(abs_t * p.delta_tau/2.) * cx_t / abs_t);\n\t\t    }\n\t\t    ++bonds_used;\n\t\t    ++elements;\n\t\t}\n\n\t\tif (elements != 0) {\n\t\t    if (p.complex_hoppings == false) {\n\t\t\tws.sparse_hoppings_0.push_back(hopping_0);\n\t\t\tws.sparse_hoppings_0_inv.push_back(hopping_0_inv);\n\n\t\t\tws.sparse_hoppings_1.push_back(hopping_1);\n\t\t\tws.sparse_hoppings_1_inv.push_back(hopping_1_inv);\n\n\t\t\tws.sparse_hoppings_2.push_back(hopping_2);\n\t\t\tws.sparse_hoppings_2_inv.push_back(hopping_2_inv);\n\t\t\t\n\t\t\tws.sparse_hoppings_3.push_back(hopping_3);\n\t\t\tws.sparse_hoppings_3_inv.push_back(hopping_3_inv);\n\t\t    } else {\n\t\t\tws.cx_sparse_hoppings_0.push_back(cx_hopping_0);\n\t\t\tws.cx_sparse_hoppings_0_inv.push_back(cx_hopping_0_inv);\n\n\t\t\tws.cx_sparse_hoppings_1.push_back(cx_hopping_1);\n\t\t\tws.cx_sparse_hoppings_1_inv.push_back(cx_hopping_1_inv);\n\n\t\t\tws.cx_sparse_hoppings_2.push_back(cx_hopping_2);\n\t\t\tws.cx_sparse_hoppings_2_inv.push_back(cx_hopping_2_inv);\n\t\t\t\n\t\t\tws.cx_sparse_hoppings_3.push_back(cx_hopping_3);\n\t\t\tws.cx_sparse_hoppings_3_inv.push_back(cx_hopping_3_inv);\n\t\t    }\n\t\t}\t\t    \n\t    }\t    \n\t}\n\n\t\n\tinline void hop_left(cx_dqmc::workspace * ws, cx_mat_t& M, double pref) {\n\t    using namespace std;\n\t    int par = 0;\n\t    \n\t    if (ws->complex_hoppings == false) {\n\t\tif (pref > 0) {\n\t\t    for (int i = 0; i < ws->sparse_hoppings.size(); ++i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->sparse_hoppings[i] * M;\n\t\t\telse \n\t\t\t    M = ws->sparse_hoppings[i] * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->sparse_hoppings[i] * M;\n\t\t\telse \n\t\t\t    M = ws->sparse_hoppings[i] * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    for (int i = 0; i < ws->sparse_hoppings.size(); ++i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->sparse_hoppings_inv[i] * M;\n\t\t\telse \n\t\t\t    M = ws->sparse_hoppings_inv[i] * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->sparse_hoppings_inv[i] * M;\n\t\t\telse \n\t\t\t    M = ws->sparse_hoppings_inv[i] * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t    }\n\t    else {\n\t\tif (pref > 0) {\n\t\t    for (int i = 0; i < ws->cx_sparse_hoppings.size(); ++i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->cx_sparse_hoppings[i] * M;\n\t\t\telse \n\t\t\t    M = ws->cx_sparse_hoppings[i] * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->cx_sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->cx_sparse_hoppings[i] * M;\n\t\t\telse \n\t\t\t    M = ws->cx_sparse_hoppings[i] * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    for (int i = 0; i < ws->cx_sparse_hoppings.size(); ++i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->cx_sparse_hoppings_inv[i] * M;\n\t\t\telse \n\t\t\t    M = ws->cx_sparse_hoppings_inv[i] * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->cx_sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->cx_sparse_hoppings_inv[i] * M;\n\t\t\telse \n\t\t\t    M = ws->cx_sparse_hoppings_inv[i] * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t    }\n\n\t    \n\t    if (par == 1)\n\t\tM = ws->hop_temp;\t    \n\t}\n\n\n\tinline void hop_left_t(cx_dqmc::workspace * ws, cx_mat_t& M, double pref) {\n\t    using namespace std;\n\t    int par = 0;\n\n\t    if (ws->complex_hoppings == false) {\n\t\tif (pref > 0) {\n\t\t    for (int i = 0; i < ws->sparse_hoppings.size(); ++i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->sparse_hoppings[i].transpose() * M;\n\t\t\telse \n\t\t\t    M = ws->sparse_hoppings[i].transpose() * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->sparse_hoppings[i].transpose() * M;\n\t\t\telse \n\t\t\t    M = ws->sparse_hoppings[i].transpose() * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    for (int i = 0; i < ws->sparse_hoppings.size(); ++i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->sparse_hoppings_inv[i].transpose() * M;\n\t\t\telse \n\t\t\t    M = ws->sparse_hoppings_inv[i].transpose() * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->sparse_hoppings_inv[i].transpose() * M;\n\t\t\telse \n\t\t\t    M = ws->sparse_hoppings_inv[i].transpose() * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t    } else {\n\t\tif (pref > 0) {\n\t\t    for (int i = 0; i < ws->cx_sparse_hoppings.size(); ++i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->cx_sparse_hoppings[i].transpose() * M;\n\t\t\telse \n\t\t\t    M = ws->cx_sparse_hoppings[i].transpose() * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->cx_sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->cx_sparse_hoppings[i].transpose() * M;\n\t\t\telse \n\t\t\t    M = ws->cx_sparse_hoppings[i].transpose() * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    for (int i = 0; i < ws->cx_sparse_hoppings.size(); ++i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->cx_sparse_hoppings_inv[i].transpose() * M;\n\t\t\telse \n\t\t\t    M = ws->cx_sparse_hoppings_inv[i].transpose() * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->cx_sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = ws->cx_sparse_hoppings_inv[i].transpose() * M;\n\t\t\telse \n\t\t\t    M = ws->cx_sparse_hoppings_inv[i].transpose() * ws->hop_temp;\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t    }\n\n\t    \n\t    if (par == 1)\n\t\tM = ws->hop_temp;\t    \n\t}\n\n\n\tinline void hop_right(cx_dqmc::workspace * ws, cx_mat_t& M, double pref) {\n\t    int par = 0;\n\n\t    if (ws->complex_hoppings == false) {\n\t\tif (pref > 0) {\n\t\t    for (int i = 0; i < ws->sparse_hoppings.size(); ++i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = M * ws->sparse_hoppings[i];\n\t\t\telse\n\t\t\t    M = ws->hop_temp * ws->sparse_hoppings[i];\n\t\t\tpar = (par == 0) ? 1 : 0;\t\t    \n\t\t    }\n\t\t\n\t\t    for (int i = ws->sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = M * ws->sparse_hoppings[i];\n\t\t\telse\n\t\t\t    M = ws->hop_temp * ws->sparse_hoppings[i];\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    for (int i = 0; i < ws->sparse_hoppings.size(); ++i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = M * ws->sparse_hoppings_inv[i];\n\t\t\telse\n\t\t\t    M = ws->hop_temp * ws->sparse_hoppings_inv[i];\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = M * ws->sparse_hoppings_inv[i];\n\t\t\telse\n\t\t\t    M = ws->hop_temp * ws->sparse_hoppings_inv[i];\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t    } else {\n\t\tif (pref > 0) {\n\t\t    for (int i = 0; i < ws->cx_sparse_hoppings.size(); ++i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = M * ws->cx_sparse_hoppings[i];\n\t\t\telse\n\t\t\t    M = ws->hop_temp * ws->cx_sparse_hoppings[i];\n\t\t\tpar = (par == 0) ? 1 : 0;\t\t    \n\t\t    }\n\t\t\n\t\t    for (int i = ws->cx_sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = M * ws->cx_sparse_hoppings[i];\n\t\t\telse\n\t\t\t    M = ws->hop_temp * ws->cx_sparse_hoppings[i];\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    for (int i = 0; i < ws->cx_sparse_hoppings.size(); ++i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = M * ws->cx_sparse_hoppings_inv[i];\n\t\t\telse\n\t\t\t    M = ws->hop_temp * ws->cx_sparse_hoppings_inv[i];\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->cx_sparse_hoppings.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) \n\t\t\t    ws->hop_temp = M * ws->cx_sparse_hoppings_inv[i];\n\t\t\telse\n\t\t\t    M = ws->hop_temp * ws->cx_sparse_hoppings_inv[i];\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t    }\n\t    if (par == 1)\n\t\tM = ws->hop_temp;\t    \n\t}\n\n\n\tinline void hop_left_renyi(cx_dqmc::workspace * ws,\n\t\t\t\t   cx_mat_t& M,\n\t\t\t\t   double pref, \n\t\t\t\t   int section) {\n\t    using namespace std;\n\t    int par = 0;\n\t    // cout << \"section \" << section << endl;\n\n\t    if (ws->complex_hoppings == false) {\n\t\tif (pref > 0) {\n\t\t    for (int i = 0; i < ws->sparse_hoppings_0.size(); ++i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->sparse_hoppings_0[i] * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->sparse_hoppings_1[i] * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->sparse_hoppings_2[i] * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->sparse_hoppings_3[i] * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->sparse_hoppings_0[i] * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->sparse_hoppings_1[i] * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->sparse_hoppings_2[i] * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->sparse_hoppings_3[i] * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\n\t\t    // cx_dqmc::interaction::onsite_left_fake(p, ws, M, spin, pref, section, slice);\n\t\t    for (int i = ws->sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->sparse_hoppings_0[i] * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->sparse_hoppings_1[i] * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->sparse_hoppings_2[i] * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->sparse_hoppings_3[i] * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->sparse_hoppings_0[i] * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->sparse_hoppings_1[i] * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->sparse_hoppings_2[i] * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->sparse_hoppings_3[i] * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    for (int i = 0; i < ws->sparse_hoppings_0.size(); ++i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->sparse_hoppings_0_inv[i] * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->sparse_hoppings_1_inv[i] * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->sparse_hoppings_2_inv[i] * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->sparse_hoppings_3_inv[i] * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->sparse_hoppings_0_inv[i] * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->sparse_hoppings_1_inv[i] * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->sparse_hoppings_2_inv[i] * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->sparse_hoppings_3_inv[i] * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\n\t\t    // cx_dqmc::interaction::onsite_left_fake(p, ws, M, spin, pref, section, slice);\n\t\t    for (int i = ws->sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->sparse_hoppings_0_inv[i] * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->sparse_hoppings_1_inv[i] * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->sparse_hoppings_2_inv[i] * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->sparse_hoppings_3_inv[i] * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->sparse_hoppings_0_inv[i] * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->sparse_hoppings_1_inv[i] * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->sparse_hoppings_2_inv[i] * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->sparse_hoppings_3_inv[i] * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t    } else {\n\t\tif (pref > 0) {\n\t\t    for (int i = 0; i < ws->cx_sparse_hoppings_0.size(); ++i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->cx_sparse_hoppings_0[i] * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->cx_sparse_hoppings_1[i] * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->cx_sparse_hoppings_2[i] * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->cx_sparse_hoppings_3[i] * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->cx_sparse_hoppings_0[i] * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->cx_sparse_hoppings_1[i] * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->cx_sparse_hoppings_2[i] * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->cx_sparse_hoppings_3[i] * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\n\t\t    // cx_dqmc::interaction::onsite_left_fake(p, ws, M, spin, pref, section, slice);\n\t\t    for (int i = ws->cx_sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->cx_sparse_hoppings_0[i] * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->cx_sparse_hoppings_1[i] * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->cx_sparse_hoppings_2[i] * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->cx_sparse_hoppings_3[i] * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->cx_sparse_hoppings_0[i] * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->cx_sparse_hoppings_1[i] * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->cx_sparse_hoppings_2[i] * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->cx_sparse_hoppings_3[i] * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    for (int i = 0; i < ws->cx_sparse_hoppings_0.size(); ++i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->cx_sparse_hoppings_0_inv[i] * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->cx_sparse_hoppings_1_inv[i] * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->cx_sparse_hoppings_2_inv[i] * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->cx_sparse_hoppings_3_inv[i] * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->cx_sparse_hoppings_0_inv[i] * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->cx_sparse_hoppings_1_inv[i] * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->cx_sparse_hoppings_2_inv[i] * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->cx_sparse_hoppings_3_inv[i] * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\n\t\t    // cx_dqmc::interaction::onsite_left_fake(p, ws, M, spin, pref, section, slice);\n\t\t    for (int i = ws->cx_sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->cx_sparse_hoppings_0_inv[i] * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->cx_sparse_hoppings_1_inv[i] * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->cx_sparse_hoppings_2_inv[i] * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->cx_sparse_hoppings_3_inv[i] * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->cx_sparse_hoppings_0_inv[i] * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->cx_sparse_hoppings_1_inv[i] * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->cx_sparse_hoppings_2_inv[i] * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->cx_sparse_hoppings_3_inv[i] * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t    }\n\t    if (par == 1)\n\t\tM = ws->hop_temp;\n\t}\n\n\n\n\tinline void hop_left_renyi_t(cx_dqmc::workspace * ws,\n\t\t\t\t   cx_mat_t& M,\n\t\t\t\t   double pref, \n\t\t\t\t   int section) {\n\t    using namespace std;\n\t    int par = 0;\n\t    // cout << \"section \" << section << endl;\n\n\t    if (ws->complex_hoppings == false) {\n\t\tif (pref > 0) {\n\t\t    for (int i = 0; i < ws->sparse_hoppings_0.size(); ++i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->sparse_hoppings_0[i].transpose() * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->sparse_hoppings_1[i].transpose() * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->sparse_hoppings_2[i].transpose() * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->sparse_hoppings_3[i].transpose() * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->sparse_hoppings_0[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->sparse_hoppings_1[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->sparse_hoppings_2[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->sparse_hoppings_3[i].transpose() * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\n\t\t    // cx_dqmc::interaction::onsite_left_fake(p, ws, M, spin, pref, section, slice);\n\t\t    for (int i = ws->sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->sparse_hoppings_0[i].transpose() * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->sparse_hoppings_1[i].transpose() * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->sparse_hoppings_2[i].transpose() * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->sparse_hoppings_3[i].transpose() * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->sparse_hoppings_0[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->sparse_hoppings_1[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->sparse_hoppings_2[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->sparse_hoppings_3[i].transpose() * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    for (int i = 0; i < ws->sparse_hoppings_0.size(); ++i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->sparse_hoppings_0_inv[i].transpose() * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->sparse_hoppings_1_inv[i].transpose() * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->sparse_hoppings_2_inv[i].transpose() * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->sparse_hoppings_3_inv[i].transpose() * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->sparse_hoppings_0_inv[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->sparse_hoppings_1_inv[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->sparse_hoppings_2_inv[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->sparse_hoppings_3_inv[i].transpose() * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\n\t\t    // cx_dqmc::interaction::onsite_left_fake(p, ws, M, spin, pref, section, slice);\n\t\t    for (int i = ws->sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->sparse_hoppings_0_inv[i].transpose() * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->sparse_hoppings_1_inv[i].transpose() * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->sparse_hoppings_2_inv[i].transpose() * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->sparse_hoppings_3_inv[i].transpose() * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->sparse_hoppings_0_inv[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->sparse_hoppings_1_inv[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->sparse_hoppings_2_inv[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->sparse_hoppings_3_inv[i].transpose() * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t    } else {\n\t\tif (pref > 0) {\n\t\t    for (int i = 0; i < ws->cx_sparse_hoppings_0.size(); ++i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->cx_sparse_hoppings_0[i].transpose() * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->cx_sparse_hoppings_1[i].transpose() * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->cx_sparse_hoppings_2[i].transpose() * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->cx_sparse_hoppings_3[i].transpose() * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->cx_sparse_hoppings_0[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->cx_sparse_hoppings_1[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->cx_sparse_hoppings_2[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->cx_sparse_hoppings_3[i].transpose() * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\n\t\t    // cx_dqmc::interaction::onsite_left_fake(p, ws, M, spin, pref, section, slice);\n\t\t    for (int i = ws->cx_sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->cx_sparse_hoppings_0[i].transpose() * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->cx_sparse_hoppings_1[i].transpose() * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->cx_sparse_hoppings_2[i].transpose() * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->cx_sparse_hoppings_3[i].transpose() * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->cx_sparse_hoppings_0[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->cx_sparse_hoppings_1[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->cx_sparse_hoppings_2[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->cx_sparse_hoppings_3[i].transpose() * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    for (int i = 0; i < ws->cx_sparse_hoppings_0.size(); ++i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->cx_sparse_hoppings_0_inv[i].transpose() * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->cx_sparse_hoppings_1_inv[i].transpose() * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->cx_sparse_hoppings_2_inv[i].transpose() * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->cx_sparse_hoppings_3_inv[i].transpose() * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->cx_sparse_hoppings_0_inv[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->cx_sparse_hoppings_1_inv[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->cx_sparse_hoppings_2_inv[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->cx_sparse_hoppings_3_inv[i].transpose() * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\n\t\t    // cx_dqmc::interaction::onsite_left_fake(p, ws, M, spin, pref, section, slice);\n\t\t    for (int i = ws->cx_sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = ws->cx_sparse_hoppings_0_inv[i].transpose() * M;\n\t\t\t    if (section == 1) ws->hop_temp = ws->cx_sparse_hoppings_1_inv[i].transpose() * M;\n\t\t\t    if (section == 2) ws->hop_temp = ws->cx_sparse_hoppings_2_inv[i].transpose() * M;\n\t\t\t    if (section == 3) ws->hop_temp = ws->cx_sparse_hoppings_3_inv[i].transpose() * M;\n\t\t\t} else {\n\t\t\t    if (section == 0) M = ws->cx_sparse_hoppings_0_inv[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 1) M = ws->cx_sparse_hoppings_1_inv[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 2) M = ws->cx_sparse_hoppings_2_inv[i].transpose() * ws->hop_temp ;\n\t\t\t    if (section == 3) M = ws->cx_sparse_hoppings_3_inv[i].transpose() * ws->hop_temp ;\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t    }\n\t    if (par == 1)\n\t\tM = ws->hop_temp;\n\t}\n\n\n\tinline void hop_right_renyi(cx_dqmc::workspace * ws,\n\t\t\t\t    cx_mat_t&__restrict__ M,\n\t\t\t\t    double pref, int section) {\n\t    int par = 0;\n\n\t    if (ws->complex_hoppings == false) {\n\t\tif (pref > 0) {\n\t\t    for (int i = 0; i < ws->sparse_hoppings_0.size(); ++i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = M * ws->sparse_hoppings_0[i];\n\t\t\t    if (section == 1) ws->hop_temp = M * ws->sparse_hoppings_1[i];\n\t\t\t    if (section == 2) ws->hop_temp = M * ws->sparse_hoppings_2[i];\n\t\t\t    if (section == 3) ws->hop_temp = M * ws->sparse_hoppings_3[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t    if (section == 0) M = ws->hop_temp * ws->sparse_hoppings_0[i];\n\t\t\t    if (section == 1) M = ws->hop_temp * ws->sparse_hoppings_1[i];\n\t\t\t    if (section == 2) M = ws->hop_temp * ws->sparse_hoppings_2[i];\n\t\t\t    if (section == 3) M = ws->hop_temp * ws->sparse_hoppings_3[i];\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = M * ws->sparse_hoppings_0[i];\n\t\t\t    if (section == 1) ws->hop_temp = M * ws->sparse_hoppings_1[i];\n\t\t\t    if (section == 2) ws->hop_temp = M * ws->sparse_hoppings_2[i];\n\t\t\t    if (section == 3) ws->hop_temp = M * ws->sparse_hoppings_3[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t    if (section == 0) M = ws->hop_temp * ws->sparse_hoppings_0[i];\n\t\t\t    if (section == 1) M = ws->hop_temp * ws->sparse_hoppings_1[i];\n\t\t\t    if (section == 2) M = ws->hop_temp * ws->sparse_hoppings_2[i];\n\t\t\t    if (section == 3) M = ws->hop_temp * ws->sparse_hoppings_3[i];\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    for (int i = 0; i < ws->sparse_hoppings_0.size(); ++i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = M * ws->sparse_hoppings_0_inv[i];\n\t\t\t    if (section == 1) ws->hop_temp = M * ws->sparse_hoppings_1_inv[i];\n\t\t\t    if (section == 2) ws->hop_temp = M * ws->sparse_hoppings_2_inv[i];\n\t\t\t    if (section == 3) ws->hop_temp = M * ws->sparse_hoppings_3_inv[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t    if (section == 0) M = ws->hop_temp * ws->sparse_hoppings_0_inv[i];\n\t\t\t    if (section == 1) M = ws->hop_temp * ws->sparse_hoppings_1_inv[i];\n\t\t\t    if (section == 2) M = ws->hop_temp * ws->sparse_hoppings_2_inv[i];\n\t\t\t    if (section == 3) M = ws->hop_temp * ws->sparse_hoppings_3_inv[i];\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = M * ws->sparse_hoppings_0_inv[i];\n\t\t\t    if (section == 1) ws->hop_temp = M * ws->sparse_hoppings_1_inv[i];\n\t\t\t    if (section == 2) ws->hop_temp = M * ws->sparse_hoppings_2_inv[i];\n\t\t\t    if (section == 3) ws->hop_temp = M * ws->sparse_hoppings_3_inv[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t    if (section == 0) M = ws->hop_temp * ws->sparse_hoppings_0_inv[i];\n\t\t\t    if (section == 1) M = ws->hop_temp * ws->sparse_hoppings_1_inv[i];\n\t\t\t    if (section == 2) M = ws->hop_temp * ws->sparse_hoppings_2_inv[i];\n\t\t\t    if (section == 3) M = ws->hop_temp * ws->sparse_hoppings_3_inv[i];\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t    } \n\t    else {\n\t\tif (pref > 0) {\n\t\t    for (int i = 0; i < ws->cx_sparse_hoppings_0.size(); ++i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = M * ws->cx_sparse_hoppings_0[i];\n\t\t\t    if (section == 1) ws->hop_temp = M * ws->cx_sparse_hoppings_1[i];\n\t\t\t    if (section == 2) ws->hop_temp = M * ws->cx_sparse_hoppings_2[i];\n\t\t\t    if (section == 3) ws->hop_temp = M * ws->cx_sparse_hoppings_3[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t    if (section == 0) M = ws->hop_temp * ws->cx_sparse_hoppings_0[i];\n\t\t\t    if (section == 1) M = ws->hop_temp * ws->cx_sparse_hoppings_1[i];\n\t\t\t    if (section == 2) M = ws->hop_temp * ws->cx_sparse_hoppings_2[i];\n\t\t\t    if (section == 3) M = ws->hop_temp * ws->cx_sparse_hoppings_3[i];\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->cx_sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = M * ws->cx_sparse_hoppings_0[i];\n\t\t\t    if (section == 1) ws->hop_temp = M * ws->cx_sparse_hoppings_1[i];\n\t\t\t    if (section == 2) ws->hop_temp = M * ws->cx_sparse_hoppings_2[i];\n\t\t\t    if (section == 3) ws->hop_temp = M * ws->cx_sparse_hoppings_3[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t    if (section == 0) M = ws->hop_temp * ws->cx_sparse_hoppings_0[i];\n\t\t\t    if (section == 1) M = ws->hop_temp * ws->cx_sparse_hoppings_1[i];\n\t\t\t    if (section == 2) M = ws->hop_temp * ws->cx_sparse_hoppings_2[i];\n\t\t\t    if (section == 3) M = ws->hop_temp * ws->cx_sparse_hoppings_3[i];\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    for (int i = 0; i < ws->cx_sparse_hoppings_0.size(); ++i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = M * ws->cx_sparse_hoppings_0_inv[i];\n\t\t\t    if (section == 1) ws->hop_temp = M * ws->cx_sparse_hoppings_1_inv[i];\n\t\t\t    if (section == 2) ws->hop_temp = M * ws->cx_sparse_hoppings_2_inv[i];\n\t\t\t    if (section == 3) ws->hop_temp = M * ws->cx_sparse_hoppings_3_inv[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t    if (section == 0) M = ws->hop_temp * ws->cx_sparse_hoppings_0_inv[i];\n\t\t\t    if (section == 1) M = ws->hop_temp * ws->cx_sparse_hoppings_1_inv[i];\n\t\t\t    if (section == 2) M = ws->hop_temp * ws->cx_sparse_hoppings_2_inv[i];\n\t\t\t    if (section == 3) M = ws->hop_temp * ws->cx_sparse_hoppings_3_inv[i];\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t\n\t\t    for (int i = ws->cx_sparse_hoppings_0.size() - 1; i >=0; --i) {\n\t\t\tif (par == 0) {\n\t\t\t    if (section == 0) ws->hop_temp = M * ws->cx_sparse_hoppings_0_inv[i];\n\t\t\t    if (section == 1) ws->hop_temp = M * ws->cx_sparse_hoppings_1_inv[i];\n\t\t\t    if (section == 2) ws->hop_temp = M * ws->cx_sparse_hoppings_2_inv[i];\n\t\t\t    if (section == 3) ws->hop_temp = M * ws->cx_sparse_hoppings_3_inv[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t    if (section == 0) M = ws->hop_temp * ws->cx_sparse_hoppings_0_inv[i];\n\t\t\t    if (section == 1) M = ws->hop_temp * ws->cx_sparse_hoppings_1_inv[i];\n\t\t\t    if (section == 2) M = ws->hop_temp * ws->cx_sparse_hoppings_2_inv[i];\n\t\t\t    if (section == 3) M = ws->hop_temp * ws->cx_sparse_hoppings_3_inv[i];\n\t\t\t}\n\t\t\tpar = (par == 0) ? 1 : 0;\n\t\t    }\n\t\t}\n\t    }\t\t\n\t    if (par == 1)\n\t\tM = ws->hop_temp;\n\t}\t\n    }\n}\n#endif\n", "meta": {"hexsha": "62e4443d81697fc5af9eedc162500a896c231912", "size": 38418, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libdqmc/cx_checkerboard.hpp", "max_stars_repo_name": "pebroecker/DQMC", "max_stars_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libdqmc/cx_checkerboard.hpp", "max_issues_repo_name": "pebroecker/DQMC", "max_issues_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libdqmc/cx_checkerboard.hpp", "max_forks_repo_name": "pebroecker/DQMC", "max_forks_repo_head_hexsha": "c4a96cb20347ef722b6ae68c415233d464c89e93", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.524691358, "max_line_length": 97, "alphanum_fraction": 0.573611328, "num_tokens": 14272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.40845061171753455}}
{"text": "#include <armadillo>\n#include <boost/program_options.hpp>\n#include <HSMM.hpp>\n#include <json.hpp>\n#include <ProMPs_emission.hpp>\n\nusing namespace arma;\nusing namespace hsmm;\nusing namespace robotics;\nusing namespace std;\nusing json = nlohmann::json;\nnamespace po = boost::program_options;\n\nfield<mat> fromMatToField(const mat& obs) {\n    field<mat> ret(obs.n_cols);\n    for(int i = 0; i < obs.n_cols; i++)\n        ret(i) = obs.col(i);\n    return ret;\n}\n\n// Running the Viterbi algorithm.\nvoid ViterbiAlgorithm(HSMM& promp_hsmm, const field<field<mat>>& seq_obs,\n        string filename) {\n    int nseq = seq_obs.n_elem;\n    for(int s = 0; s < nseq; s++) {\n        const field<mat>& obs = seq_obs(s);\n        int nstates = promp_hsmm.nstates_;\n        int nobs = obs.n_elem;\n        imat psi_duration(nstates, nobs, fill::zeros);\n        imat psi_state(nstates, nobs, fill::zeros);\n        mat delta(nstates, nobs, fill::zeros);\n        cout << \"Before pdf\" << endl;\n        cube log_pdf = promp_hsmm.computeEmissionsLogLikelihood(obs);\n        cout << \"After pdf\" << endl;\n        Viterbi(promp_hsmm.transition_, promp_hsmm.pi_, promp_hsmm.duration_,\n                log_pdf, delta, psi_duration, psi_state,\n                promp_hsmm.min_duration_, nobs);\n        cout << \"Delta last column\" << endl;\n        cout << delta.col(nobs - 1) << endl;\n        ivec viterbiStates, viterbiDurations;\n        viterbiPath(psi_duration, psi_state, delta, viterbiStates,\n                viterbiDurations);\n        cout << \"Viterbi states and durations\" << endl;\n        imat states_and_durations = join_horiz(viterbiStates, viterbiDurations);\n        cout << states_and_durations << endl;\n        cout << \"Python states list representation\" << endl;\n        cout << \"[\";\n        for(int i = 0; i < viterbiStates.n_elem; i++)\n            cout << viterbiStates[i] <<\n                    ((i + 1 == viterbiStates.n_elem)? \"]\" : \",\");\n        cout << endl;\n        cout << \"Python duration list representation\" << endl;\n        cout << \"[\";\n        for(int i = 0; i < viterbiDurations.n_elem; i++)\n            cout << viterbiDurations[i] <<\n                    ((i + 1 == viterbiDurations.n_elem)? \"]\" : \",\");\n        cout << endl;\n\n        // Saving the matrix of joint states and durations.\n        string viterbi_filename(filename);\n        if (nseq > 1)\n            viterbi_filename += string(\".\") + to_string(s);\n        states_and_durations.save(viterbi_filename, raw_ascii);\n    }\n}\n\nint main(int argc, char *argv[]) {\n    po::options_description desc(\"Options\");\n    desc.add_options()\n        (\"help,h\", \"Produce help message\")\n        (\"input,i\", po::value<string>(), \"Path to the input obs\")\n        (\"params,p\", po::value<string>(), \"Path to the json input params\")\n        (\"output,o\", po::value<string>(), \"Path to the output viterbi file(s)\")\n        (\"polybasisfun\", po::value<int>()->default_value(1), \"Order of the \"\n                \"poly basis functions\")\n\t    (\"norbf\", \"Flag to deactivate the radial basis functions\")\n        (\"nsequences,n\", po::value<int>()->default_value(1),\n                \"Number of sequences used for training\");\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n    if (vm.count(\"help\")) {\n        cout << desc << endl;\n        return 0;\n    }\n    if (!vm.count(\"input\") || !vm.count(\"output\") || !vm.count(\"params\")) {\n        cerr << \"Error: You should provide input and output files\" << endl;\n        return 1;\n    }\n    string input_filename = vm[\"input\"].as<string>();\n    string output_filename = vm[\"output\"].as<string>();\n    string params = vm[\"params\"].as<string>();\n    int nseq = vm[\"nsequences\"].as<int>();\n\n    field<field<mat>> seq_obs(nseq);\n    int njoints;\n    for(int i = 0; i < nseq; i++) {\n        string name = input_filename;\n        if (nseq != 1)\n            name += string(\".\") + to_string(i);\n        mat obs;\n        obs.load(name, raw_ascii);\n        ifstream input_params_file(params);\n        json input_params;\n        input_params_file >> input_params;\n        njoints = obs.n_rows;\n        int nobs = obs.n_cols;\n        cout << \"Time series shape: (\" << njoints << \", \" << nobs << \").\" << endl;\n        seq_obs(i) = fromMatToField(obs);\n    }\n\n    ifstream input_params_file(params);\n    json input_params;\n    input_params_file >> input_params;\n    int min_duration = input_params[\"min_duration\"];\n    int nstates = input_params[\"nstates\"];\n    int ndurations = input_params[\"ndurations\"];\n    mat transition(nstates, nstates);\n    transition.fill(1.0 / (nstates - 1));\n    transition.diag().zeros(); // No self-transitions.\n    vec pi(nstates);\n    pi.fill(1.0/nstates);\n    mat durations(nstates, ndurations);\n    durations.fill(1.0 / ndurations);\n\n    // Setting a combination of polynomial and rbf basis functions.\n    auto rbf = shared_ptr<ScalarGaussBasis>(new ScalarGaussBasis(\n                {0.25,0.5,0.75},0.25));\n    auto poly = make_shared<ScalarPolyBasis>(vm[\"polybasisfun\"].as<int>());\n    auto comb = shared_ptr<ScalarCombBasis>(new ScalarCombBasis({rbf, poly}));\n    if (vm.count(\"norbf\"))\n        comb = shared_ptr<ScalarCombBasis>(new ScalarCombBasis({poly}));\n    int n_basis_functions = comb->dim();\n\n    // Instantiating as many ProMPs as hidden states.\n    vector<FullProMP> promps;\n    for(int i = 0; i < nstates; i++) {\n        vec mu_w(n_basis_functions * njoints);\n        mu_w.randn();\n        mat Sigma_w = eye<mat>(n_basis_functions * njoints,\n                    n_basis_functions * njoints);\n        mat Sigma_y = 0.01*eye<mat>(njoints, njoints);\n        ProMP promp(mu_w, Sigma_w, Sigma_y);\n        FullProMP poly(comb, promp, njoints);\n        promps.push_back(poly);\n    }\n\n    // Creating the ProMP emission and parsing the model parameters as json.\n    shared_ptr<AbstractEmission> ptr_emission(new ProMPsEmission(promps));\n    HSMM promp_hsmm(ptr_emission, transition, pi, durations, min_duration);\n    promp_hsmm.from_stream(input_params);\n\n    ViterbiAlgorithm(promp_hsmm, seq_obs, output_filename);\n    return 0;\n}\n", "meta": {"hexsha": "1f6117402c993c00fa7ca45af41be702e691c75e", "size": 6080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/promps_hsmm_ball_viterbi.cpp", "max_stars_repo_name": "DiegoAE/BOSD", "max_stars_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-05-03T05:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T18:14:31.000Z", "max_issues_repo_path": "examples/promps_hsmm_ball_viterbi.cpp", "max_issues_repo_name": "DiegoAE/BOSD", "max_issues_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-14T15:29:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-04T10:14:54.000Z", "max_forks_repo_path": "examples/promps_hsmm_ball_viterbi.cpp", "max_forks_repo_name": "DiegoAE/BOSD", "max_forks_repo_head_hexsha": "a7ce88462c64c540ba2922d16eb6f7eba8055b47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-07-01T07:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-01T07:44:09.000Z", "avg_line_length": 38.9743589744, "max_line_length": 82, "alphanum_fraction": 0.6116776316, "num_tokens": 1590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.40844542782467724}}
{"text": "#ifndef QST_WAVEFUNCTIONCOMPLEX_HPP\n#define QST_WAVEFUNCTIONCOMPLEX_HPP\n#include <iostream>\n#include <Eigen/Dense>\n#include <random>\n#include <fstream>\n#include <iostream>\n\nnamespace qst{\n\nclass WavefunctionComplex{\n\n    int N_;            // Number of degrees of freedom (visible units)\n    int npar_;         // Number of parameters\n    int nparLambda_;   // Number of amplitude parameters\n    int nparMu_;       // Number of phase parameters\n    Rbm rbmAm_;        // RBM for the amplitude\n    Rbm rbmPh_;        // RBM for the phases\n\n    const std::complex<double> I_; // Imaginary unit\n    \n    //Random number generator \n    std::mt19937 rgen_;\n    \npublic:\n    // Constructor \n    WavefunctionComplex(Parameters &par):rbmAm_(par),\n                                  rbmPh_(par),\n                                  I_(0,1){\n        npar_ = rbmAm_.Npar() + rbmPh_.Npar();  // Total number of parameters\n        nparLambda_ = rbmAm_.Npar();\n        nparMu_ = rbmPh_.Npar();\n        N_ = rbmAm_.Nvisible();\n        std::random_device rd;\n        //rgen_.seed(rd());\n        rgen_.seed(13579);\n    }\n    \n    // Private members access functions\n    inline int N()const{\n        return N_;\n    }\n    inline int Npar()const{\n        return npar_;\n    }\n    inline int NparLambda()const{\n        return nparLambda_;\n    }\n    inline int NparMu()const{\n        return nparMu_;\n    }\n    inline int Nchains(){\n        return rbmAm_.Nchains();\n    }\n    inline Eigen::VectorXd VisibleStateRow(int s){\n        return rbmAm_.VisibleStateRow(s);\n    }\n\n    // Set the state of the wavefunction's degrees of freedom\n    inline void SetVisibleLayer(Eigen::MatrixXd v){\n        rbmAm_.SetVisibleLayer(v);\n    }\n \n    // Initialize the wavefunction parameters    \n    void InitRandomPars(int seed,double sigma){\n        rbmAm_.InitRandomPars(seed,sigma);\n        rbmPh_.InitRandomPars(seed,sigma);\n    }\n    \n    // Amplitude\n    double amplitude(const Eigen::VectorXd & v){\n        return std::sqrt(rbmAm_.prob(v));//exp(0.5*rbmAm_.LogVal(v));         \n    }\n    // Phase\n    double phase(const Eigen::VectorXd & v){\n        return std::log(rbmPh_.prob(v));\n    }\n    // Psi\n    std::complex<double> psi(const Eigen::VectorXd & v){\n        return amplitude(v)*exp(0.5*I_*phase(v));\n    }\n\n    //---- SAMPLING ----/\n    \n    // Perform k steps of Gibbs sampling\n    void Sample(int steps){\n        rbmAm_.Sample(steps);\n    }\n   \n    //---- DERIVATIVES ----//\n    \n    //Compute gradient of effective energy wrt Lambda \n    Eigen::VectorXd LambdaGrad(const Eigen::VectorXd & v){\n        return rbmAm_.VisEnergyGrad(v);\n    }\n    //Compute gradient of effective energy wrt all parameters\n    Eigen::VectorXd Grad(const Eigen::VectorXd & v){\n        Eigen::VectorXd der(npar_);\n        der<<rbmAm_.VisEnergyGrad(v),rbmPh_.VisEnergyGrad(v);\n        return der;\n    }\n    //Compute the gradient of the effective energy in an arbitrary basis given by U\n    void rotatedGrad(const std::vector<std::string> & basis,\n                            const Eigen::VectorXd & state,//VectorRbmT & gradR){\n                            std::map<std::string,Eigen::MatrixXcd> & Unitaries,\n                            Eigen::VectorXcd &gradR ){\n        int t=0,counter=0;\n        std::complex<double> U=1.0,den=0.0;\n        std::bitset<16> bit;\n        std::bitset<16> st;\n        std::vector<int> basisIndex;\n        Eigen::VectorXd v(N_);\n        Eigen::VectorXcd num(npar_);\n        //Eigen::VectorXcd gradR(npar_);\n        num.setZero(); \n        basisIndex.clear();\n        // Extract the sites where the rotation is non-trivial\n        for(int j=0;j<N_;j++){\n            if (basis[j]!=\"Z\"){\n                t++;\n                basisIndex.push_back(j);\n            }\n        }\n\n        // Loop over the states of the local Hilbert space\n        for(int i=0;i<1<<t;i++){\n            counter =0;\n            bit = i;\n            v=state;\n            for(int j=0;j<N_;j++){\n                if (basis[j] != \"Z\"){\n                    v(j) = bit[counter];\n                    counter++;\n                }\n            }\n            U=1.0;\n            //Compute the product of the matrix elements of the unitary rotations\n            for(int ii=0;ii<t;ii++){\n                U = U * Unitaries[basis[basisIndex[ii]]](int(state(basisIndex[ii])),int(v(basisIndex[ii])));\n            }\n            num += U*Grad(v)*psi(v); \n            den += U*psi(v);\n        }\n        gradR = num/den;\n    }\n\n    \n    //---- UTILITIES ----//\n\n    //Get RBM parameters\n    Eigen::VectorXd GetParameters(){\n        Eigen::VectorXd pars(npar_);\n        pars<<rbmAm_.GetParameters(),rbmPh_.GetParameters();\n        return pars;\n    }\n\n    // Set RBM parameters\n    void SetParameters(const Eigen::VectorXd & pars){\n        Eigen::VectorXd parsAm(nparLambda_);\n        Eigen::VectorXd parsPh(npar_-nparLambda_);\n\n        for(int i=0;i<nparLambda_;i++){\n            parsAm(i)=pars(i);\n        }\n        for(int i=0;i<npar_-nparLambda_;i++){\n            parsPh(i)=pars(nparLambda_+i);\n        }\n        rbmAm_.SetParameters(parsAm);\n        rbmPh_.SetParameters(parsPh);\n    }\n\n    void LoadWeights(std::string &fileName){\n        std::ifstream fin(fileName);\n        rbmAm_.LoadWeights(fin);\n        rbmPh_.LoadWeights(fin);\n    }\n};\n}\n\n#endif\n", "meta": {"hexsha": "5d0a4644190bc4ffb8fde52c7c7565d52ef73a21", "size": 5286, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "qucumber/cpp/wavefunction_complex.hpp", "max_stars_repo_name": "PatrickHuembeli/QuCumber", "max_stars_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-02T10:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-02T10:03:45.000Z", "max_issues_repo_path": "qucumber/cpp/wavefunction_complex.hpp", "max_issues_repo_name": "PatrickHuembeli/QuCumber", "max_issues_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "qucumber/cpp/wavefunction_complex.hpp", "max_forks_repo_name": "PatrickHuembeli/QuCumber", "max_forks_repo_head_hexsha": "a9f8912a086f334ab2af20bf52493a528332a214", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2044198895, "max_line_length": 108, "alphanum_fraction": 0.5529701097, "num_tokens": 1339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.4084454229114849}}
{"text": "/*\nThis file is part of Bohrium and Copyright (c) 2012 the Bohrium team:\nhttp://bohrium.bitbucket.org\n\nBohrium is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as \npublished by the Free Software Foundation, either version 3 \nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the \nGNU Lesser General Public License along with bohrium. \n\nIf not, see <http://www.gnu.org/licenses/>.\n*/\n#include <iostream>\n#include <Eigen/Dense>\n#include <bp_util.h>\n\nusing namespace std;\nusing namespace Eigen;\n\ntemplate <typename T>\nArray<T, Dynamic, 1>& cnd(const Array<T, Dynamic, 1>& x)\n{\n    size_t samples = x.size();\n    Array<T, Dynamic, 1> l(samples), k(samples), w(samples);\n    Array<T, Dynamic, 1> mask(samples);\n    Array<bool, Dynamic, 1> mask_bool(samples);\n\n    T a1 = 0.31938153,\n      a2 =-0.356563782,\n      a3 = 1.781477937,\n      a4 =-1.821255978,\n      a5 = 1.330274429,\n      pp = 2.5066282746310002; // sqrt(2.0*PI)\n\n    l = abs(x);\n    //k = (T)1.0 / ((T)1.0 + (T)0.2316419 * l);\n    //k = (T)0.5 / l / (T)0.5;\n    k = l / (T)0.5;\n    w = (T)1.0 - (T)1.0 / (T)pp * exp((T)-(T)1.0*l*l/(T)2.0) * \\\n        ((T)a1*k + \\\n         (T)a2*(pow(k,(T)2)) + \\\n         (T)a3*(pow(k,(T)3)) + \\\n         (T)a4*(pow(k,(T)4)) + \\\n         (T)a5*(pow(k,(T)5)));\n\n    mask_bool= (x < (T)0.0);\n    mask = mask_bool.cast<T>();\n    return w * (mask) + ((T)1.0-w);\n    //return w * (mask) + ((T)1.0-w)* mask;\n    //return w * (!mask) + (1.0-w)* mask;\n}\n\ntemplate <typename T>\nT* pricing(size_t samples, size_t iterations, char flag, T x, T d_t, T r, T v)\n{\n    T* p    = (T*)malloc(sizeof(T)*samples);    // Intermediate results\n    T t     = d_t;                              // Initial delta\n\n    Array<T, Dynamic, 1> d1(samples), d2(samples), res(samples);\n    Array<T, Dynamic, 1> s = Array<T, Dynamic, 1>::Random(samples)*4.0 +58.0;      // Model between 58-62\n\n    for(size_t i=0; i<iterations; i++) {\n        d1 = (log(s/x) + (r+v*v/2.0)*t) / (v*sqrt(t));\n        d2 = d1-v*sqrt(t);\n\n        if (flag == 'c') {\n\n            size_t samples = x.size();\n            Array<T, Dynamic, 1> l(samples), k(samples), w(samples);\n            Array<T, Dynamic, 1> mask(samples);\n            Array<bool, Dynamic, 1> mask_bool(samples);\n\n            T a1 = 0.31938153,\n              a2 =-0.356563782,\n              a3 = 1.781477937,\n              a4 =-1.821255978,\n              a5 = 1.330274429,\n              pp = 2.5066282746310002; // sqrt(2.0*PI)\n\n            l = abs(x);\n            //k = (T)1.0 / ((T)1.0 + (T)0.2316419 * l);\n            //k = (T)0.5 / l / (T)0.5;\n            k = l / (T)0.5;\n            w = (T)1.0 - (T)1.0 / (T)pp * exp((T)-(T)1.0*l*l/(T)2.0) * \\\n                ((T)a1*k + \\\n                 (T)a2*(pow(k,(T)2)) + \\\n                 (T)a3*(pow(k,(T)3)) + \\\n                 (T)a4*(pow(k,(T)4)) + \\\n                 (T)a5*(pow(k,(T)5)));\n\n            mask_bool= (x < (T)0.0);\n            mask = mask_bool.cast<T>();\n            res =  w * (!mask) + (1.0-w)* mask;\n\n            //cnd<T>(d1);\n            //res = s * cnd<T>(d1) -x * exp(-r*t) * cnd<T>(d2);\n        } else {\n/*\n            Array<T, Dynamic, 1> tmp1(samples), tmp2(samples);\n            tmp1 = -1.0*d2;\n            tmp2 = -1.0*d1;\n            res = x * exp(-r*t) * cnd<T>(tmp1) - s*cnd<T>(tmp2);\n    */\n        }\n\n        t += d_t;                               // Increment delta\n        p[i] = res.sum() / (T)samples;           // Result from timestep\n    }\n\n    return p;\n}\n\nint main(int argc, char* argv[])\n{\n    bp_util_type bp = bp_util_create(argc, argv, 2);    // Grab arguments\n    if (bp.args.has_error) {\n        return 1;\n    }\n    const size_t samples    = bp.args.sizes[0];\n    const size_t iterations = bp.args.sizes[1];\n\n    bp.timer_start();                                   // Start timer\n    double* prices = pricing(                           // Run...\n        samples, iterations,\n        'c', 65.0, 1.0 / 365.0,\n        0.08, 0.3\n    );\n    bp.timer_stop();                                    // Stop timer\n    \n    bp.print(\"black_scholes(cpp11_bxx)\");               // Print restults..\n    if (bp.args.verbose) {                              // ..verbosely.\n        cout << \", \\\"output\\\": [\";\n        for(size_t i=0; i<iterations; i++) {\n            cout << prices[i];\n            if (iterations-1!=i) {\n                cout << \", \";\n            }\n        }\n        cout << \"]\" << endl;\n    }\n    free(prices);                                       // Cleanup\n\n    return 0;\n}\n\n", "meta": {"hexsha": "f2a7bfb436065d16d0e9c789e03d699aa8ca1058", "size": 4810, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchpress/benchmarks/black_scholes/cpp11_eigen/src/black_scholes.cpp", "max_stars_repo_name": "bh107/benchpress", "max_stars_repo_head_hexsha": "e1dcda446a986d4d828b14d807e37e10cf4a046b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-03-31T15:39:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T21:30:49.000Z", "max_issues_repo_path": "benchpress/benchmarks/black_scholes/cpp11_eigen/src/black_scholes.cpp", "max_issues_repo_name": "bh107/benchpress", "max_issues_repo_head_hexsha": "e1dcda446a986d4d828b14d807e37e10cf4a046b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2015-04-13T12:03:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-28T13:31:11.000Z", "max_forks_repo_path": "benchpress/benchmarks/black_scholes/cpp11_eigen/src/black_scholes.cpp", "max_forks_repo_name": "bh107/benchpress", "max_forks_repo_head_hexsha": "e1dcda446a986d4d828b14d807e37e10cf4a046b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-06-28T08:06:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T17:30:25.000Z", "avg_line_length": 31.4379084967, "max_line_length": 105, "alphanum_fraction": 0.4794178794, "num_tokens": 1529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145998, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4084384567450589}}
{"text": "//==================================================================================================\n/**\n  Copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n**/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_GENERIC_D_EXPO_REDUCTION_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_DETAIL_GENERIC_D_EXPO_REDUCTION_HPP_INCLUDED\n\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/function/horn1.hpp>\n#include <boost/simd/arch/common/detail/tags.hpp>\n#include <boost/simd/constant/invlog10_2.hpp>\n#include <boost/simd/constant/invlog_2.hpp>\n#include <boost/simd/detail/constant/log10_2hi.hpp>\n#include <boost/simd/detail/constant/log10_2lo.hpp>\n#include <boost/simd/constant/log_10.hpp>\n#include <boost/simd/constant/log_2.hpp>\n#include <boost/simd/detail/constant/log_2hi.hpp>\n#include <boost/simd/detail/constant/log_2lo.hpp>\n#include <boost/simd/detail/constant/maxlog.hpp>\n#include <boost/simd/detail/constant/maxlog10.hpp>\n#include <boost/simd/detail/constant/maxlog2.hpp>\n#include <boost/simd/detail/constant/minlog.hpp>\n#include <boost/simd/detail/constant/minlog10.hpp>\n#include <boost/simd/detail/constant/minlog2.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/function/is_greater_equal.hpp>\n#include <boost/simd/function/is_less_equal.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/fnms.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/inc.hpp>\n#include <boost/simd/function/oneminus.hpp>\n#include <boost/simd/function/nearbyint.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/logical.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n\nnamespace boost { namespace simd\n{\n  namespace detail\n  {\n    namespace bd =  boost::dispatch;\n    namespace bs =  boost::simd;\n\n    template < class A0> struct exp_reduction < A0, bs::tag::exp_, double>\n    {\n      static BOOST_FORCEINLINE auto isgemaxlog(A0 const& a0) BOOST_NOEXCEPT\n        -> decltype(is_greater_equal(a0, Maxlog<A0>()))\n      {\n        return is_greater_equal(a0, Maxlog<A0>());\n      }\n\n      static BOOST_FORCEINLINE auto isleminlog(A0 const& a0) BOOST_NOEXCEPT\n        -> decltype(is_less_equal(a0, Minlog<A0>()))\n      {\n        return is_less_equal(a0, Minlog<A0>());\n      }\n\n      static BOOST_FORCEINLINE A0 reduce( A0 const& a0\n                                        , A0& hi, A0& lo, A0& x) BOOST_NOEXCEPT\n      {\n        A0 k = nearbyint(Invlog_2<A0>()*a0);\n        hi = fnms(k, Log_2hi<A0>(), a0); //a0-k*L\n        lo = k*Log_2lo<A0>();\n        x  = hi-lo;\n        return k;\n      }\n\n      static BOOST_FORCEINLINE A0 approx(A0 const& x) BOOST_NOEXCEPT\n      {\n        A0 const t = sqr(x);\n        return fnms(t,\n                    horn<A0\n                         , 0x3fc555555555553eull\n                         , 0xbf66c16c16bebd93ull\n                         , 0x3f11566aaf25de2cull\n                         , 0xbebbbd41c5d26bf1ull\n                         , 0x3e66376972bea4d0ull\n                    >(t), x); //x-h*t\n    }\n\n      static BOOST_FORCEINLINE A0 finalize(A0 const& x, A0 const& c, A0 const& hi, A0 const& lo) BOOST_NOEXCEPT\n      {\n        return One<A0>()-(((lo-(x*c)/(Two<A0>()-c))-hi));\n      }\n\n    };\n\n    template < class A0 > struct exp_reduction < A0, bs::tag::exp2_, double>\n    {\n      static BOOST_FORCEINLINE auto isgemaxlog(A0 const& a0) BOOST_NOEXCEPT\n        -> decltype(is_greater_equal(a0, Maxlog2<A0>()))\n      {\n        return is_greater_equal(a0, Maxlog2<A0>());\n      }\n\n      static BOOST_FORCEINLINE auto isleminlog(A0 const& a0) BOOST_NOEXCEPT\n        -> decltype(is_less_equal(a0, Minlog2<A0>()))\n      {\n        return is_less_equal(a0, Minlog2<A0>());\n      }\n\n      static BOOST_FORCEINLINE A0 reduce(A0 const& a0, A0 const&, A0 const&, A0& x) BOOST_NOEXCEPT\n      {\n        A0 k = nearbyint(a0);\n        x = (a0 - k)*Log_2<A0>();\n        return k;\n      }\n\n      static BOOST_FORCEINLINE A0 approx(A0 const& x) BOOST_NOEXCEPT\n      {\n        const A0 t =  sqr(x);\n        return fnms(t,\n                    horn<A0\n                         , 0x3fc555555555553eull\n                         , 0xbf66c16c16bebd93ull\n                         , 0x3f11566aaf25de2cull\n                         , 0xbebbbd41c5d26bf1ull\n                         , 0x3e66376972bea4d0ull\n                    > (t), x); //x-h*t\n      }\n\n      static BOOST_FORCEINLINE A0 finalize(A0 const& x, A0 const& c, A0 const&, A0& ) BOOST_NOEXCEPT\n      {\n        return oneminus(((-(x*c)/(Two<A0>()-c))-x));\n      }\n    };\n\n    template < class A0 > struct exp_reduction < A0, bs::tag::exp10_, double>\n    {\n      static BOOST_FORCEINLINE auto isgemaxlog(A0 const& a0) BOOST_NOEXCEPT\n        -> decltype(is_greater_equal(a0, Maxlog10<A0>()))\n      {\n        return is_greater_equal(a0, Maxlog10<A0>());\n      }\n\n      static BOOST_FORCEINLINE auto isleminlog(A0 const& a0) BOOST_NOEXCEPT\n        -> decltype(is_less_equal(a0, Minlog10<A0>()))\n      {\n        return is_less_equal(a0, Minlog10<A0>());\n      }\n\n      static BOOST_FORCEINLINE A0 reduce(A0 const& a0, A0&, A0&, A0& x) BOOST_NOEXCEPT\n      {\n        A0 k  = nearbyint(Invlog10_2<A0>()*a0);\n        x = fnms(k, Log10_2hi<A0>(), a0);\n        x = fnms(k, Log10_2lo<A0>(), x);\n        return k;\n      }\n\n      static BOOST_FORCEINLINE A0 approx(A0 x) BOOST_NOEXCEPT\n      {\n        A0 xx = sqr(x);\n        A0 px = x*horn<A0,\n                       0x40a2b4798e134a01ull,\n                       0x40796b7a050349e4ull,\n                       0x40277d9474c55934ull,\n                       0x3fa4fd75f3062dd4ull\n                       > (xx);\n        A0 x2 =  px/(horn1<A0,\n                          0x40a03f37650df6e2ull,\n                          0x4093e05eefd67782ull,\n                          0x405545fdce51ca08ull\n                     //   0x3ff0000000000000ull\n                          > (xx)-px);\n        return inc(x2+x2);\n      }\n\n      static BOOST_FORCEINLINE A0 finalize(A0 const&, A0 const& c, A0 const&, A0& ) BOOST_NOEXCEPT\n      {\n        return c;\n      }\n    };\n  }\n} }\n#endif\n", "meta": {"hexsha": "f7625cb685d53c023e515ac51b2c316df9752463", "size": 6297, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/detail/generic/d_expo_reduction.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/detail/generic/d_expo_reduction.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/detail/generic/d_expo_reduction.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 34.5989010989, "max_line_length": 111, "alphanum_fraction": 0.5802763221, "num_tokens": 1778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746407, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4084384508486045}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n// \n// Copyright (C) 2016 Alec Jacobson <alecjacobson@gmail.com>\n// \n// This Source Code Form is subject to the terms of the Mozilla Public License \n// v. 2.0. If a copy of the MPL was not distributed with this file, You can \n// obtain one at http://mozilla.org/MPL/2.0/.\n#include <igl/parallel_transport_angles.h>\n#include <Eigen/Geometry>\n\ntemplate <typename DerivedV, typename DerivedF, typename DerivedK>\nIGL_INLINE void igl::parallel_transport_angles(\nconst Eigen::PlainObjectBase<DerivedV>& V,\nconst Eigen::PlainObjectBase<DerivedF>& F,\nconst Eigen::PlainObjectBase<DerivedV>& FN,\nconst Eigen::MatrixXi &E2F,\nconst Eigen::MatrixXi &F2E,\nEigen::PlainObjectBase<DerivedK> &K)\n{\n  int numE = E2F.rows();\n\n  Eigen::VectorXi isBorderEdge;\n  isBorderEdge.setZero(numE,1);\n  for(unsigned i=0; i<numE; ++i)\n  {\n    if ((E2F(i,0) == -1) || ((E2F(i,1) == -1)))\n      isBorderEdge[i] = 1;\n  }\n\n  K.setZero(numE);\n  // For every non-border edge\n  for (unsigned eid=0; eid<numE; ++eid)\n  {\n    if (!isBorderEdge[eid])\n    {\n      int fid0 = E2F(eid,0);\n      int fid1 = E2F(eid,1);\n\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> N0 = FN.row(fid0);\n//      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> N1 = FN.row(fid1);\n\n      // find common edge on triangle 0 and 1\n      int fid0_vc = -1;\n      int fid1_vc = -1;\n      for (unsigned i=0;i<3;++i)\n      {\n        if (F2E(fid0,i) == eid)\n          fid0_vc = i;\n        if (F2E(fid1,i) == eid)\n          fid1_vc = i;\n      }\n      assert(fid0_vc != -1);\n      assert(fid1_vc != -1);\n\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> common_edge = V.row(F(fid0,(fid0_vc+1)%3)) - V.row(F(fid0,fid0_vc));\n      common_edge.normalize();\n\n      // Map the two triangles in a new space where the common edge is the x axis and the N0 the z axis\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> P;\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> o = V.row(F(fid0,fid0_vc));\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> tmp = -N0.cross(common_edge);\n      P << common_edge, tmp, N0;\n      //      P.transposeInPlace();\n\n\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> V0;\n      V0.row(0) = V.row(F(fid0,0)) -o;\n      V0.row(1) = V.row(F(fid0,1)) -o;\n      V0.row(2) = V.row(F(fid0,2)) -o;\n\n      V0 = (P*V0.transpose()).transpose();\n\n      //      assert(V0(0,2) < 1e-10);\n      //      assert(V0(1,2) < 1e-10);\n      //      assert(V0(2,2) < 1e-10);\n\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> V1;\n      V1.row(0) = V.row(F(fid1,0)) -o;\n      V1.row(1) = V.row(F(fid1,1)) -o;\n      V1.row(2) = V.row(F(fid1,2)) -o;\n      V1 = (P*V1.transpose()).transpose();\n\n      //      assert(V1(fid1_vc,2) < 10e-10);\n      //      assert(V1((fid1_vc+1)%3,2) < 10e-10);\n\n      // compute rotation R such that R * N1 = N0\n      // i.e. map both triangles to the same plane\n      double alpha = -atan2(V1((fid1_vc+2)%3,2),V1((fid1_vc+2)%3,1));\n\n      Eigen::Matrix<typename DerivedV::Scalar, 3, 3> R;\n      R << 1,          0,            0,\n      0, cos(alpha), -sin(alpha) ,\n      0, sin(alpha),  cos(alpha);\n      V1 = (R*V1.transpose()).transpose();\n\n      //      assert(V1(0,2) < 1e-10);\n      //      assert(V1(1,2) < 1e-10);\n      //      assert(V1(2,2) < 1e-10);\n\n      // measure the angle between the reference frames\n      // k_ij is the angle between the triangle on the left and the one on the right\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> ref0 = V0.row(1) - V0.row(0);\n      Eigen::Matrix<typename DerivedV::Scalar, 1, 3> ref1 = V1.row(1) - V1.row(0);\n\n      ref0.normalize();\n      ref1.normalize();\n\n      double ktemp = atan2(ref1(1),ref1(0)) - atan2(ref0(1),ref0(0));\n\n      // just to be sure, rotate ref0 using angle ktemp...\n      Eigen::Matrix<typename DerivedV::Scalar,2,2> R2;\n      R2 << cos(ktemp), -sin(ktemp), sin(ktemp), cos(ktemp);\n\n//      Eigen::Matrix<typename DerivedV::Scalar, 1, 2> tmp1 = R2*(ref0.head(2)).transpose();\n\n      //      assert(tmp1(0) - ref1(0) < 1e-10);\n      //      assert(tmp1(1) - ref1(1) < 1e-10);\n\n      K[eid] = ktemp;\n    }\n  }\n\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\ntemplate void igl::parallel_transport_angles<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::Matrix<int, -1, -1, 0, -1, -1> const&, Eigen::Matrix<int, -1, -1, 0, -1, -1> const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);\n#endif\n", "meta": {"hexsha": "0e3803df2b6203093c3cde17294bfd8d8f06a49c", "size": 4757, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "igl/parallel_transport_angles.cpp", "max_stars_repo_name": "aviadtzemah/animation2", "max_stars_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2392.0, "max_stars_repo_stars_event_min_datetime": "2016-12-17T14:14:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:40:40.000Z", "max_issues_repo_path": "igl/parallel_transport_angles.cpp", "max_issues_repo_name": "aviadtzemah/animation2", "max_issues_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 106.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T17:47:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-01T19:44:11.000Z", "max_forks_repo_path": "igl/parallel_transport_angles.cpp", "max_forks_repo_name": "aviadtzemah/animation2", "max_forks_repo_head_hexsha": "9a3f980fbe27672fe71f8f61f73b5713f2af5089", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 184.0, "max_forks_repo_forks_event_min_datetime": "2017-11-15T09:55:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T16:30:46.000Z", "avg_line_length": 36.8759689922, "max_line_length": 544, "alphanum_fraction": 0.5860836662, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4083829008752294}}
{"text": "#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Projection_traits_xy_3.h>\n\n#include <CGAL/Delaunay_triangulation_2.h>\n#include <CGAL/Triangulation_vertex_base_with_info_2.h>\n#include <CGAL/Triangulation_face_base_with_info_2.h>\n\n#include <CGAL/boost/graph/graph_traits_Delaunay_triangulation_2.h>\n#include <CGAL/boost/graph/copy_face_graph.h>\n\n#include <CGAL/Point_set_3.h>\n#include <CGAL/Point_set_3/IO.h>\n#include <CGAL/compute_average_spacing.h>\n\n#include <CGAL/Surface_mesh.h>\n#include <CGAL/Polygon_mesh_processing/locate.h>\n\n#include <CGAL/Polygon_mesh_processing/triangulate_hole.h>\n#include <CGAL/Polygon_mesh_processing/border.h>\n#include <CGAL/Polygon_mesh_processing/remesh.h>\n\n#include <boost/graph/adjacency_list.hpp>\n#include <CGAL/boost/graph/split_graph_into_polylines.h>\n\n#include <CGAL/IO/WKT.h>\n\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\n#include <CGAL/Constrained_triangulation_plus_2.h>\n\n#include <CGAL/Polyline_simplification_2/simplify.h>\n#include <CGAL/Polyline_simplification_2/Squared_distance_cost.h>\n\n#include <CGAL/Classification.h>\n\n#include <CGAL/Random.h>\n\n#include <fstream>\n#include <queue>\n\n#include \"include/Color_ramp.h\"\n\n///////////////////////////////////////////////////////////////////\n//! [TIN DS]\n\nusing Kernel = CGAL::Exact_predicates_inexact_constructions_kernel;\nusing Projection_traits = CGAL::Projection_traits_xy_3<Kernel>;\nusing Point_2 = Kernel::Point_2;\nusing Point_3 = Kernel::Point_3;\nusing Segment_3 = Kernel::Segment_3;\n\n// Triangulated Irregular Network\nusing TIN = CGAL::Delaunay_triangulation_2<Projection_traits>;\n\n//! [TIN DS]\n///////////////////////////////////////////////////////////////////\n\n///////////////////////////////////////////////////////////////////\n//! [TIN_with_info DS]\n\n// Triangulated Irregular Network (with info)\nusing Point_set = CGAL::Point_set_3<Point_3>;\nusing Vbi = CGAL::Triangulation_vertex_base_with_info_2 <Point_set::Index, Projection_traits>;\nusing Fbi = CGAL::Triangulation_face_base_with_info_2<int, Projection_traits>;\nusing TDS = CGAL::Triangulation_data_structure_2<Vbi, Fbi>;\nusing TIN_with_info = CGAL::Delaunay_triangulation_2<Projection_traits, TDS>;\n\n//! [TIN_with_info DS]\n///////////////////////////////////////////////////////////////////\n\nnamespace Classification = CGAL::Classification;\n\n#ifdef CGAL_LINKED_WITH_TBB\nusing Concurrency_tag = CGAL::Parallel_tag;\n#else\nusing Concurrency_tag = CGAL::Sequential_tag;\n#endif\n\n//////////////////////////////////////////////////\u0007/////////////////\n//! [Contouring functions]\n\nbool face_has_isovalue (TIN::Face_handle fh, double isovalue)\n{\n  bool above = false, below = false;\n  for (int i = 0; i < 3; ++ i)\n  {\n    // Face has isovalue if one of its vertices is above and another\n    // one below\n    if (fh->vertex(i)->point().z() > isovalue)\n      above = true;\n    if (fh->vertex(i)->point().z() < isovalue)\n      below = true;\n  }\n\n  return (above && below);\n}\n\nSegment_3 isocontour_in_face (TIN::Face_handle fh, double isovalue)\n{\n  Point_3 source;\n  Point_3 target;\n  bool source_found = false;\n\n  for (int i = 0; i < 3; ++ i)\n  {\n    Point_3 p0 = fh->vertex((i+1) % 3)->point();\n    Point_3 p1 = fh->vertex((i+2) % 3)->point();\n\n    // Check if the isovalue crosses segment (p0,p1)\n    if ((p0.z() - isovalue) * (p1.z() - isovalue) > 0)\n      continue;\n\n    double zbottom = p0.z();\n    double ztop = p1.z();\n    if (zbottom > ztop)\n    {\n      std::swap (zbottom, ztop);\n      std::swap (p0, p1);\n    }\n\n    // Compute position of segment vertex\n    double ratio = (isovalue - zbottom) / (ztop - zbottom);\n    Point_3 p = CGAL::barycenter (p0, (1 - ratio), p1,ratio);\n\n    if (source_found)\n      target = p;\n    else\n    {\n      source = p;\n      source_found = true;\n    }\n  }\n\n  return Segment_3 (source, target);\n}\n\n\n//! [Contouring functions]\n///////////////////////////////////////////////////////////////////\n\n///////////////////////////////////////////////////////////////////\n//! [Contouring visitor]\n\ntemplate <typename Graph>\nclass Polylines_visitor\n{\nprivate:\n  std::vector<std::vector<Point_3> >& polylines;\n  Graph& graph;\n\npublic:\n\n  Polylines_visitor (Graph& graph, std::vector<std::vector<Point_3> >& polylines)\n    : polylines (polylines), graph(graph) { }\n\n  void start_new_polyline()\n  {\n    polylines.push_back (std::vector<Point_3>());\n  }\n\n  void add_node (typename Graph::vertex_descriptor vd)\n  {\n    polylines.back().push_back (graph[vd]);\n  }\n\n  void end_polyline()\n  {\n    // filter small polylines\n    if (polylines.back().size() < 50)\n      polylines.pop_back();\n  }\n};\n\n//! [Contouring visitor]\n///////////////////////////////////////////////////////////////////\n\n///////////////////////////////////////////////////////////////////\n//! [CDT]\n\nnamespace PS = CGAL::Polyline_simplification_2;\nusing CDT_vertex_base = PS::Vertex_base_2<Projection_traits>;\nusing CDT_face_base = CGAL::Constrained_triangulation_face_base_2<Projection_traits>;\nusing CDT_TDS = CGAL::Triangulation_data_structure_2<CDT_vertex_base, CDT_face_base>;\nusing CDT = CGAL::Constrained_Delaunay_triangulation_2<Projection_traits, CDT_TDS>;\nusing CTP = CGAL::Constrained_triangulation_plus_2<CDT>;\n\n//! [CDT]\n///////////////////////////////////////////////////////////////////\n\nint main (int argc, char** argv)\n{\n  if (argc != 2)\n  {\n    std::cerr << \"Usage: \" << argv[0] << \" points.ply\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Init DSM]\n\n  // Read points\n  std::ifstream ifile (argv[1], std::ios_base::binary);\n  CGAL::Point_set_3<Point_3> points;\n  ifile >> points;\n  std::cerr << points.size() << \" point(s) read\" << std::endl;\n\n  // Create DSM\n  TIN dsm (points.points().begin(), points.points().end());\n\n  //! [Init DSM]\n  ///////////////////////////////////////////////////////////////////\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Save DSM]\n\n  using Mesh = CGAL::Surface_mesh<Point_3>;\n\n  Mesh dsm_mesh;\n  CGAL::copy_face_graph (dsm, dsm_mesh);\n  std::ofstream dsm_ofile (\"dsm.ply\", std::ios_base::binary);\n  CGAL::IO::set_binary_mode (dsm_ofile);\n  CGAL::IO::write_PLY (dsm_ofile, dsm_mesh);\n  dsm_ofile.close();\n\n  //! [Save DSM]\n  ///////////////////////////////////////////////////////////////////\n\n  ///////////////////////////////////////////////////////////////////\n  //! [TIN_with_info]\n\n  auto idx_to_point_with_info\n    = [&](const Point_set::Index& idx) -> std::pair<Point_3, Point_set::Index>\n      {\n        return std::make_pair (points.point(idx), idx);\n      };\n\n  TIN_with_info tin_with_info\n    (boost::make_transform_iterator (points.begin(), idx_to_point_with_info),\n     boost::make_transform_iterator (points.end(), idx_to_point_with_info));\n\n  //! [TIN_with_info]\n  ///////////////////////////////////////////////////////////////////\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Components]\n\n  double spacing = CGAL::compute_average_spacing<Concurrency_tag>(points, 6);\n  spacing *= 2;\n\n  auto face_height\n    = [&](const TIN_with_info::Face_handle fh) -> double\n      {\n        double out = 0.;\n        for (int i = 0; i < 3; ++ i)\n          out = (std::max) (out, CGAL::abs(fh->vertex(i)->point().z() - fh->vertex((i+1)%3)->point().z()));\n        return out;\n      };\n\n  // Initialize faces info\n  for (TIN_with_info::Face_handle fh : tin_with_info.all_face_handles())\n    if (tin_with_info.is_infinite(fh) || face_height(fh) > spacing) // Filtered faces are given info() = -2\n      fh->info() = -2;\n    else // Pending faces are given info() = -1;\n      fh->info() = -1;\n\n  // Flooding algorithm\n  std::vector<int> component_size;\n  for (TIN_with_info::Face_handle fh : tin_with_info.finite_face_handles())\n  {\n    if (fh->info() != -1)\n      continue;\n\n    std::queue<TIN_with_info::Face_handle> todo;\n    todo.push(fh);\n\n    int size = 0;\n    while (!todo.empty())\n    {\n      TIN_with_info::Face_handle current = todo.front();\n      todo.pop();\n\n      if (current->info() != -1)\n        continue;\n      current->info() = int(component_size.size());\n      ++ size;\n\n      for (int i = 0; i < 3; ++ i)\n        todo.push (current->neighbor(i));\n    }\n\n    component_size.push_back (size);\n  }\n\n  std::cerr << component_size.size() << \" connected component(s) found\" << std::endl;\n\n  //! [Components]\n  ///////////////////////////////////////////////////////////////////\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Save TIN with info]\n\n  Mesh tin_colored_mesh;\n\n  Mesh::Property_map<Mesh::Face_index, CGAL::IO::Color>\n    color_map = tin_colored_mesh.add_property_map<Mesh::Face_index, CGAL::IO::Color>(\"f:color\").first;\n\n  CGAL::copy_face_graph (tin_with_info, tin_colored_mesh,\n                         CGAL::parameters::face_to_face_output_iterator\n                         (boost::make_function_output_iterator\n                          ([&](const std::pair<TIN_with_info::Face_handle, Mesh::Face_index>& ff)\n                           {\n                             // Color unassigned faces gray\n                             if (ff.first->info() < 0)\n                               color_map[ff.second] = CGAL::IO::Color(128, 128, 128);\n                             else\n                             {\n                               // Random color seeded by the component ID\n                               CGAL::Random r (ff.first->info());\n                               color_map[ff.second] = CGAL::IO::Color (r.get_int(64, 192),\n                                                                   r.get_int(64, 192),\n                                                                   r.get_int(64, 192));\n                             }\n                           })));\n\n  std::ofstream tin_colored_ofile (\"colored_tin.ply\", std::ios_base::binary);\n  CGAL::IO::set_binary_mode (tin_colored_ofile);\n  CGAL::IO::write_PLY (tin_colored_ofile, tin_colored_mesh);\n  tin_colored_ofile.close();\n\n  //! [Save TIN with info]\n  ///////////////////////////////////////////////////////////////////\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Filtering]\n\n  int min_size = int(points.size() / 2);\n\n  std::vector<TIN_with_info::Vertex_handle> to_remove;\n  for (TIN_with_info::Vertex_handle vh : tin_with_info.finite_vertex_handles())\n  {\n    TIN_with_info::Face_circulator circ = tin_with_info.incident_faces (vh),\n      start = circ;\n\n    // Remove a vertex if it's only adjacent to components smaller than threshold\n    bool keep = false;\n    do\n    {\n      if (circ->info() >= 0 && component_size[std::size_t(circ->info())] > min_size)\n      {\n        keep = true;\n        break;\n      }\n    }\n    while (++ circ != start);\n\n    if (!keep)\n      to_remove.push_back (vh);\n  }\n\n  std::cerr << to_remove.size() << \" vertices(s) will be removed after filtering\" << std::endl;\n  for (TIN_with_info::Vertex_handle vh : to_remove)\n    tin_with_info.remove (vh);\n\n  //! [Filtering]\n  ///////////////////////////////////////////////////////////////////\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Hole filling]\n\n  // Copy and keep track of overly large faces\n  Mesh dtm_mesh;\n\n  std::vector<Mesh::Face_index> face_selection;\n  Mesh::Property_map<Mesh::Face_index, bool> face_selection_map\n   = dtm_mesh.add_property_map<Mesh::Face_index, bool>(\"is_selected\", false).first;\n\n  double limit = CGAL::square (5 * spacing);\n  CGAL::copy_face_graph (tin_with_info, dtm_mesh,\n                         CGAL::parameters::face_to_face_output_iterator\n                         (boost::make_function_output_iterator\n                          ([&](const std::pair<TIN_with_info::Face_handle, Mesh::Face_index>& ff)\n                           {\n                             double longest_edge = 0.;\n                             bool border = false;\n                             for (int i = 0; i < 3; ++ i)\n                             {\n                               longest_edge = (std::max)(longest_edge, CGAL::squared_distance\n                                                         (ff.first->vertex((i+1)%3)->point(),\n                                                          ff.first->vertex((i+2)%3)->point()));\n\n                               TIN_with_info::Face_circulator circ\n                                 = tin_with_info.incident_faces (ff.first->vertex(i)),\n                                 start = circ;\n                               do\n                               {\n                                 if (tin_with_info.is_infinite (circ))\n                                 {\n                                   border = true;\n                                   break;\n                                 }\n                               }\n                               while (++ circ != start);\n\n                               if (border)\n                                 break;\n                             }\n\n                             // Select if face is too big AND it's not\n                             // on the border (to have closed holes)\n                             if (!border && longest_edge > limit)\n                             {\n                               face_selection_map[ff.second] = true;\n                               face_selection.push_back (ff.second);\n                             }\n                           })));\n\n  // Save original DTM\n  std::ofstream dtm_ofile (\"dtm.ply\", std::ios_base::binary);\n  CGAL::IO::set_binary_mode (dtm_ofile);\n  CGAL::IO::write_PLY (dtm_ofile, dtm_mesh);\n  dtm_ofile.close();\n\n  std::cerr << face_selection.size() << \" face(s) are selected for removal\" << std::endl;\n\n  // Expand face selection to keep a well formed 2-manifold mesh after removal\n  CGAL::expand_face_selection_for_removal (face_selection, dtm_mesh, face_selection_map);\n  face_selection.clear();\n  for (Mesh::Face_index fi : faces(dtm_mesh))\n    if (face_selection_map[fi])\n      face_selection.push_back(fi);\n\n  std::cerr << face_selection.size() << \" face(s) are selected for removal after expansion\" << std::endl;\n\n  for (Mesh::Face_index fi : face_selection)\n    CGAL::Euler::remove_face (halfedge(fi, dtm_mesh), dtm_mesh);\n  dtm_mesh.collect_garbage();\n\n  if (!dtm_mesh.is_valid())\n    std::cerr << \"Invalid mesh!\" << std::endl;\n\n  // Save filtered DTM\n  std::ofstream dtm_holes_ofile (\"dtm_with_holes.ply\", std::ios_base::binary);\n  CGAL::IO::set_binary_mode (dtm_holes_ofile);\n  CGAL::IO::write_PLY (dtm_holes_ofile, dtm_mesh);\n  dtm_holes_ofile.close();\n\n  // Get all holes\n  std::vector<Mesh::Halfedge_index> holes;\n  CGAL::Polygon_mesh_processing::extract_boundary_cycles (dtm_mesh, std::back_inserter (holes));\n\n  std::cerr << holes.size() << \" hole(s) identified\" << std::endl;\n\n  // Identify outer hull (hole with maximum size)\n  double max_size = 0.;\n  Mesh::Halfedge_index outer_hull;\n  for (Mesh::Halfedge_index hi : holes)\n  {\n    CGAL::Bbox_3 hole_bbox;\n    for (Mesh::Halfedge_index haf : CGAL::halfedges_around_face(hi, dtm_mesh))\n    {\n      const Point_3& p = dtm_mesh.point(target(haf, dtm_mesh));\n      hole_bbox += p.bbox();\n    }\n    double size = CGAL::squared_distance (Point_2(hole_bbox.xmin(), hole_bbox.ymin()),\n                                          Point_2(hole_bbox.xmax(), hole_bbox.ymax()));\n    if (size > max_size)\n    {\n      max_size = size;\n      outer_hull = hi;\n    }\n  }\n\n  // Fill all holes except the bigest (which is the outer hull of the mesh)\n  for (Mesh::Halfedge_index hi : holes)\n    if (hi != outer_hull)\n      CGAL::Polygon_mesh_processing::triangulate_refine_and_fair_hole\n        (dtm_mesh, hi, CGAL::Emptyset_iterator(), CGAL::Emptyset_iterator());\n\n  // Save DTM with holes filled\n  std::ofstream dtm_filled_ofile (\"dtm_filled.ply\", std::ios_base::binary);\n  CGAL::IO::set_binary_mode (dtm_filled_ofile);\n  CGAL::IO::write_PLY (dtm_filled_ofile, dtm_mesh);\n  dtm_filled_ofile.close();\n\n  //! [Hole filling]\n  ///////////////////////////////////////////////////////////////////\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Remeshing]\n\n  CGAL::Polygon_mesh_processing::isotropic_remeshing (faces(dtm_mesh), spacing, dtm_mesh);\n\n  std::ofstream dtm_remeshed_ofile (\"dtm_remeshed.ply\", std::ios_base::binary);\n  CGAL::IO::set_binary_mode (dtm_remeshed_ofile);\n  CGAL::IO::write_PLY (dtm_remeshed_ofile, dtm_mesh);\n  dtm_remeshed_ofile.close();\n\n  //! [Remeshing]\n  ///////////////////////////////////////////////////////////////////\n\n  TIN dtm_clean (dtm_mesh.points().begin(), dtm_mesh.points().end());\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Rastering]\n\n  CGAL::Bbox_3 bbox = CGAL::bbox_3 (points.points().begin(), points.points().end());\n\n  // Generate raster image 1920-pixels large\n  std::size_t width = 1920;\n  std::size_t height = std::size_t((bbox.ymax() - bbox.ymin()) * 1920 / (bbox.xmax() - bbox.xmin()));\n\n  std::cerr << \"Rastering with resolution \" << width << \"x\" << height << std::endl;\n\n  // Use PPM format (Portable PixMap) for simplicity\n  std::ofstream raster_ofile (\"raster.ppm\", std::ios_base::binary);\n\n  // PPM header\n  raster_ofile << \"P6\" << std::endl // magic number\n               << width << \" \" << height << std::endl // dimensions of the image\n               << 255 << std::endl; // maximum color value\n\n  // Use rainbow color ramp output\n  Color_ramp color_ramp;\n\n  // Keeping track of location from one point to its neighbor allows\n  // for fast locate in DT\n  TIN::Face_handle location;\n\n  // Query each pixel of the image\n  for (std::size_t y = 0; y < height; ++ y)\n    for (std::size_t x = 0; x < width; ++ x)\n    {\n      Point_3 query (bbox.xmin() + x * (bbox.xmax() - bbox.xmin()) / double(width),\n                     bbox.ymin() + (height-y) * (bbox.ymax() - bbox.ymin()) / double(height),\n                     0); // not relevant for location in 2D\n\n      location = dtm_clean.locate (query, location);\n\n      // Points outside the convex hull will be colored black\n      std::array<unsigned char, 3> colors { 0, 0, 0 };\n      if (!dtm_clean.is_infinite(location))\n      {\n        std::array<double, 3> barycentric_coordinates\n          = CGAL::Polygon_mesh_processing::barycentric_coordinates\n          (Point_2 (location->vertex(0)->point().x(), location->vertex(0)->point().y()),\n           Point_2 (location->vertex(1)->point().x(), location->vertex(1)->point().y()),\n           Point_2 (location->vertex(2)->point().x(), location->vertex(2)->point().y()),\n           Point_2 (query.x(), query.y()),\n           Kernel());\n\n        double height_at_query\n          = (barycentric_coordinates[0] * location->vertex(0)->point().z()\n             + barycentric_coordinates[1] * location->vertex(1)->point().z()\n             + barycentric_coordinates[2] * location->vertex(2)->point().z());\n\n        // Color ramp generates a color depending on a value from 0 to 1\n        double height_ratio = (height_at_query - bbox.zmin()) / (bbox.zmax() - bbox.zmin());\n        colors = color_ramp.get(height_ratio);\n      }\n      raster_ofile.write ((char*)(&colors), 3);\n    }\n\n  raster_ofile.close();\n\n  //! [Rastering]\n  ///////////////////////////////////////////////////////////////////\n\n  // Smooth heights with 5 successive Gaussian filters\n  double gaussian_variance = 4 * spacing * spacing;\n  for (TIN::Vertex_handle vh : dtm_clean.finite_vertex_handles())\n  {\n    double z = vh->point().z();\n    double total_weight = 1;\n\n    TIN::Vertex_circulator circ = dtm_clean.incident_vertices (vh),\n      start = circ;\n\n    do\n    {\n      if (!dtm_clean.is_infinite(circ))\n      {\n        double sq_dist = CGAL::squared_distance (vh->point(), circ->point());\n\n        double weight = std::exp(- sq_dist / gaussian_variance);\n        z += weight * circ->point().z();\n        total_weight += weight;\n      }\n    }\n    while (++ circ != start);\n\n    z /= total_weight;\n\n    vh->point() = Point_3 (vh->point().x(), vh->point().y(), z);\n  }\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Contouring extraction]\n\n  std::array<double, 50> isovalues; // Contour 50 isovalues\n  for (std::size_t i = 0; i < isovalues.size(); ++ i)\n    isovalues[i] = bbox.zmin() + ((i+1) * (bbox.zmax() - bbox.zmin()) / (isovalues.size() - 2));\n\n  // First find on each face if they are crossed by some isovalues and\n  // extract segments in a graph\n  using Segment_graph = boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, Point_3>;\n  Segment_graph graph;\n  using Map_p2v = std::map<Point_3, Segment_graph::vertex_descriptor>;\n  Map_p2v map_p2v;\n  for (TIN::Face_handle vh : dtm_clean.finite_face_handles())\n    for (double iv : isovalues)\n      if (face_has_isovalue (vh, iv))\n      {\n        Segment_3 segment = isocontour_in_face (vh, iv);\n        for (const Point_3& p : { segment.source(), segment.target() })\n        {\n          // Only insert end points of segments once to get a well connected graph\n          Map_p2v::iterator iter;\n          bool inserted;\n          std::tie (iter, inserted) = map_p2v.insert (std::make_pair (p, Segment_graph::vertex_descriptor()));\n          if (inserted)\n          {\n            iter->second = boost::add_vertex (graph);\n            graph[iter->second] = p;\n          }\n        }\n        boost::add_edge (map_p2v[segment.source()], map_p2v[segment.target()], graph);\n      }\n\n  //! [Contouring extraction]\n  ///////////////////////////////////////////////////////////////////\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Contouring split]\n\n  // Split segments into polylines\n  std::vector<std::vector<Point_3> > polylines;\n  Polylines_visitor<Segment_graph> visitor (graph, polylines);\n  CGAL::split_graph_into_polylines (graph, visitor);\n\n  std::cerr << polylines.size() << \" polylines computed, with \"\n            << map_p2v.size() << \" vertices in total\" << std::endl;\n\n  // Output to WKT file\n  std::ofstream contour_ofile (\"contour.wkt\");\n  contour_ofile.precision(18);\n  CGAL::IO::write_multi_linestring_WKT (contour_ofile, polylines);\n  contour_ofile.close();\n\n  //! [Contouring split]\n  ///////////////////////////////////////////////////////////////////\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Contouring simplify]\n\n  // Construct constrained Delaunay triangulation with polylines as constraints\n  CTP ctp;\n  for (const std::vector<Point_3>& poly : polylines)\n    ctp.insert_constraint (poly.begin(), poly.end());\n\n  // Simplification algorithm with limit on distance\n  PS::simplify (ctp, PS::Squared_distance_cost(), PS::Stop_above_cost_threshold (16 * spacing * spacing));\n\n  polylines.clear();\n  for (CTP::Constraint_id cid : ctp.constraints())\n  {\n    polylines.push_back (std::vector<Point_3>());\n    polylines.back().reserve (ctp.vertices_in_constraint (cid).size());\n    for (CTP::Vertex_handle vh : ctp.vertices_in_constraint(cid))\n      polylines.back().push_back (vh->point());\n  }\n\n  std::size_t nb_vertices\n    = std::accumulate (polylines.begin(), polylines.end(), 0u,\n                       [](std::size_t size, const std::vector<Point_3>& poly) -> std::size_t\n                       { return size + poly.size(); });\n\n  std::cerr << nb_vertices\n            << \" vertices remaining after simplification (\"\n            << 100. * (nb_vertices / double(map_p2v.size())) << \"%)\" << std::endl;\n\n  // Output to WKT file\n  std::ofstream simplified_ofile (\"simplified.wkt\");\n  simplified_ofile.precision(18);\n  CGAL::IO::write_multi_linestring_WKT (simplified_ofile, polylines);\n  simplified_ofile.close();\n\n  //! [Contouring simplify]\n  ///////////////////////////////////////////////////////////////////\n\n  ///////////////////////////////////////////////////////////////////\n  //! [Classification]\n\n  // Get training from input\n  Point_set::Property_map<int> training_map;\n  bool training_found;\n  std::tie (training_map, training_found) = points.property_map<int>(\"training\");\n\n  if (training_found)\n  {\n    std::cerr << \"Classifying ground/vegetation/building\" << std::endl;\n\n    // Create labels\n    Classification::Label_set labels ({ \"ground\", \"vegetation\", \"building\" });\n\n    // Generate features\n    Classification::Feature_set features;\n    Classification::Point_set_feature_generator<Kernel, Point_set, Point_set::Point_map>\n      generator (points, points.point_map(), 5); // 5 scales\n\n#ifdef CGAL_LINKED_WITH_TBB\n    // If TBB is used, features can be computed in parallel\n    features.begin_parallel_additions();\n    generator.generate_point_based_features (features);\n    features.end_parallel_additions();\n#else\n    generator.generate_point_based_features (features);\n#endif\n\n    // Train a random forest classifier\n    Classification::ETHZ::Random_forest_classifier classifier (labels, features);\n    classifier.train (points.range(training_map));\n\n    // Classify with graphcut regularization\n    Point_set::Property_map<int> label_map = points.add_property_map<int>(\"labels\").first;\n    Classification::classify_with_graphcut<Concurrency_tag>\n      (points, points.point_map(), labels, classifier,\n       generator.neighborhood().k_neighbor_query(12), // regularize on 12-neighbors graph\n       0.5f, // graphcut weight\n       12, // Subdivide to speed-up process\n       label_map);\n\n    // Evaluate\n    std::cerr << \"Mean IoU on training data = \"\n              << Classification::Evaluation(labels,\n                                            points.range(training_map),\n                                            points.range(label_map)).mean_intersection_over_union() << std::endl;\n\n    // Save the classified point set\n    std::ofstream classified_ofile (\"classified.ply\");\n    CGAL::IO::set_binary_mode (classified_ofile);\n    classified_ofile << points;\n    classified_ofile.close();\n  }\n\n  //! [Classification]\n  ///////////////////////////////////////////////////////////////////\n\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "fe90c4234158c05e360673b878d0a6cc8b9dc6ae", "size": 25962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Classification/examples/Classification/gis_tutorial_example.cpp", "max_stars_repo_name": "antoniospg/cgal", "max_stars_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-01-20T17:02:24.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-20T17:02:24.000Z", "max_issues_repo_path": "Classification/examples/Classification/gis_tutorial_example.cpp", "max_issues_repo_name": "antoniospg/cgal", "max_issues_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2018-01-10T13:32:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-30T12:23:20.000Z", "max_forks_repo_path": "Classification/examples/Classification/gis_tutorial_example.cpp", "max_forks_repo_name": "antoniospg/cgal", "max_forks_repo_head_hexsha": "2891c22fc7f64f680ac7e144407afe49f6425cb9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T15:26:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-21T15:26:25.000Z", "avg_line_length": 34.616, "max_line_length": 113, "alphanum_fraction": 0.5603189277, "num_tokens": 6315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4083828936343597}}
{"text": "/*  This file is part of libDAI - http://www.libdai.org/\n *\n *  Copyright (c) 2006-2011, The libDAI authors. All rights reserved.\n *\n *  Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.\n */\n\n\n#include <algorithm>\n#include <cmath>\n#include <boost/dynamic_bitset.hpp>\n#include <dai/regiongraph.h>\n#include <dai/factorgraph.h>\n#include <dai/clustergraph.h>\n\n\nnamespace dai {\n\n\nusing namespace std;\n\n\nvoid RegionGraph::construct( const FactorGraph &fg, const std::vector<VarSet> &ors, const std::vector<Region> &irs, const std::vector<std::pair<size_t,size_t> > &edges ) {\n    // Copy factor graph structure\n    FactorGraph::operator=( fg );\n\n    // Copy inner regions\n    _IRs = irs;\n\n    // Construct outer regions (giving them counting number 1.0)\n    _ORs.clear();\n    _ORs.reserve( ors.size() );\n    bforeach( const VarSet &alpha, ors )\n        _ORs.push_back( FRegion(Factor(alpha, 1.0), 1.0) );\n\n    // For each factor, find an outer region that subsumes that factor.\n    // Then, multiply the outer region with that factor.\n    _fac2OR.clear();\n    _fac2OR.reserve( nrFactors() );\n    for( size_t I = 0; I < nrFactors(); I++ ) {\n        size_t alpha;\n        for( alpha = 0; alpha < nrORs(); alpha++ )\n            if( OR(alpha).vars() >> factor(I).vars() ) {\n                _fac2OR.push_back( alpha );\n                break;\n            }\n        DAI_ASSERT( alpha != nrORs() );\n    }\n    recomputeORs();\n\n    // Create bipartite graph\n    _G.construct( nrORs(), nrIRs(), edges.begin(), edges.end() );\n}\n\n\nvoid RegionGraph::constructCVM( const FactorGraph &fg, const std::vector<VarSet> &cl, size_t verbose ) {\n    if( verbose )\n        cerr << \"constructCVM called (\" << fg.nrVars() << \" vars, \" << fg.nrFactors() << \" facs, \" << cl.size() << \" clusters)\" << endl;\n\n    // Retain only maximal clusters\n    if( verbose )\n        cerr << \"  Constructing ClusterGraph\" << endl;\n    ClusterGraph cg( cl );\n    if( verbose )\n        cerr << \"  Erasing non-maximal clusters\" << endl;\n    cg.eraseNonMaximal();\n\n    // Create inner regions - first pass\n    if( verbose )\n        cerr << \"  Creating inner regions (first pass)\" << endl;\n    set<VarSet> betas;\n    for( size_t alpha = 0; alpha < cg.nrClusters(); alpha++ )\n        for( size_t alpha2 = alpha; (++alpha2) != cg.nrClusters(); ) {\n            VarSet intersection = cg.cluster(alpha) & cg.cluster(alpha2);\n            if( intersection.size() > 0 )\n                betas.insert( intersection );\n        }\n\n    // Create inner regions - subsequent passes\n    if( verbose )\n        cerr << \"  Creating inner regions (next passes)\" << endl;\n    set<VarSet> new_betas;\n    do {\n        new_betas.clear();\n        for( set<VarSet>::const_iterator gamma = betas.begin(); gamma != betas.end(); gamma++ )\n            for( set<VarSet>::const_iterator gamma2 = gamma; (++gamma2) != betas.end(); ) {\n                VarSet intersection = (*gamma) & (*gamma2);\n                if( (intersection.size() > 0) && (betas.count(intersection) == 0) )\n                    new_betas.insert( intersection );\n            }\n        betas.insert(new_betas.begin(), new_betas.end());\n    } while( new_betas.size() );\n\n    // Create inner regions - final phase\n    if( verbose )\n        cerr << \"  Creating inner regions (final phase)\" << endl;\n    vector<Region> irs;\n    irs.reserve( betas.size() );\n    for( set<VarSet>::const_iterator beta = betas.begin(); beta != betas.end(); beta++ )\n        irs.push_back( Region(*beta,0.0) );\n\n    // Create edges\n    if( verbose )\n        cerr << \"  Creating edges\" << endl;\n    vector<pair<size_t,size_t> > edges;\n    for( size_t beta = 0; beta < irs.size(); beta++ )\n        for( size_t alpha = 0; alpha < cg.nrClusters(); alpha++ )\n            if( cg.cluster(alpha) >> irs[beta] )\n                edges.push_back( pair<size_t,size_t>(alpha,beta) );\n\n    // Construct region graph\n    if( verbose )\n        cerr << \"  Constructing region graph\" << endl;\n    construct( fg, cg.clusters(), irs, edges );\n\n    // Calculate counting numbers\n    if( verbose )\n        cerr << \"  Calculating counting numbers\" << endl;\n    calcCVMCountingNumbers();\n    \n    if( verbose )\n        cerr << \"Done.\" << endl;\n}\n\n\nvoid RegionGraph::calcCVMCountingNumbers() {\n    // Calculates counting numbers of inner regions based upon counting numbers of outer regions\n\n    vector<vector<size_t> > ancestors(nrIRs());\n    boost::dynamic_bitset<> assigned(nrIRs());\n    for( size_t beta = 0; beta < nrIRs(); beta++ ) {\n        IR(beta).c() = 0.0;\n        for( size_t beta2 = 0; beta2 < nrIRs(); beta2++ )\n            if( (beta2 != beta) && IR(beta2) >> IR(beta) )\n                ancestors[beta].push_back(beta2);\n    }\n\n    bool new_counting;\n    do {\n        new_counting = false;\n        for( size_t beta = 0; beta < nrIRs(); beta++ ) {\n            if( !assigned[beta] ) {\n                bool has_unassigned_ancestor = false;\n                for( vector<size_t>::const_iterator beta2 = ancestors[beta].begin(); (beta2 != ancestors[beta].end()) && !has_unassigned_ancestor; beta2++ )\n                    if( !assigned[*beta2] )\n                        has_unassigned_ancestor = true;\n                if( !has_unassigned_ancestor ) {\n                    Real c = 1.0;\n                    bforeach( const Neighbor &alpha, nbIR(beta) )\n                        c -= OR(alpha).c();\n                    for( vector<size_t>::const_iterator beta2 = ancestors[beta].begin(); beta2 != ancestors[beta].end(); beta2++ )\n                        c -= IR(*beta2).c();\n                    IR(beta).c() = c;\n                    assigned.set(beta, true);\n                    new_counting = true;\n                }\n            }\n        }\n    } while( new_counting );\n}\n\n\nbool RegionGraph::checkCountingNumbers() const {\n    // Checks whether the counting numbers satisfy the fundamental relation\n\n    bool all_valid = true;\n    for( vector<Var>::const_iterator n = vars().begin(); n != vars().end(); n++ ) {\n        Real c_n = 0.0;\n        for( size_t alpha = 0; alpha < nrORs(); alpha++ )\n            if( OR(alpha).vars().contains( *n ) )\n                c_n += OR(alpha).c();\n        for( size_t beta = 0; beta < nrIRs(); beta++ )\n            if( IR(beta).contains( *n ) )\n                c_n += IR(beta).c();\n        if( fabs(c_n - 1.0) > 1e-15 ) {\n            all_valid = false;\n            cerr << \"WARNING: counting numbers do not satisfy relation for \" << *n << \"(c_n = \" << c_n << \").\" << endl;\n        }\n    }\n\n    return all_valid;\n}\n\n\nvoid RegionGraph::recomputeORs() {\n    for( size_t alpha = 0; alpha < nrORs(); alpha++ )\n        OR(alpha).fill( 1.0 );\n    for( size_t I = 0; I < nrFactors(); I++ )\n        if( fac2OR(I) != -1U )\n            OR( fac2OR(I) ) *= factor( I );\n}\n\n\nvoid RegionGraph::recomputeORs( const VarSet &ns ) {\n    for( size_t alpha = 0; alpha < nrORs(); alpha++ )\n        if( OR(alpha).vars().intersects( ns ) )\n            OR(alpha).fill( 1.0 );\n    for( size_t I = 0; I < nrFactors(); I++ )\n        if( fac2OR(I) != -1U )\n            if( OR( fac2OR(I) ).vars().intersects( ns ) )\n                OR( fac2OR(I) ) *= factor( I );\n}\n\n\nvoid RegionGraph::recomputeOR( size_t I ) {\n    DAI_ASSERT( I < nrFactors() );\n    if( fac2OR(I) != -1U ) {\n        size_t alpha = fac2OR(I);\n        OR(alpha).fill( 1.0 );\n        for( size_t J = 0; J < nrFactors(); J++ )\n            if( fac2OR(J) == alpha )\n                OR(alpha) *= factor( J );\n    }\n}\n\n\n/// Send RegionGraph to output stream\nostream & operator << (ostream & os, const RegionGraph & rg) {\n    os << \"digraph RegionGraph {\" << endl;\n    os << \"node[shape=box];\" << endl;\n    for( size_t alpha = 0; alpha < rg.nrORs(); alpha++ )\n        os << \"\\ta\" << alpha << \" [label=\\\"a\" << alpha << \": \" << rg.OR(alpha).vars() << \", c=\" << rg.OR(alpha).c() << \"\\\"];\" << endl;\n    os << \"node[shape=ellipse];\" << endl;\n    for( size_t beta = 0; beta < rg.nrIRs(); beta++ )\n        os << \"\\tb\" << beta << \" [label=\\\"b\" << beta << \": \" << (VarSet)rg.IR(beta) << \", c=\" << rg.IR(beta).c() << \"\\\"];\" << endl;\n    for( size_t alpha = 0; alpha < rg.nrORs(); alpha++ )\n        bforeach( const Neighbor &beta, rg.nbOR(alpha) )\n            os << \"\\ta\" << alpha << \" -> b\" << beta << \";\" << endl;\n    os << \"}\" << endl;\n    return os;\n}\n\n\n} // end of namespace dai\n", "meta": {"hexsha": "5bf683caa3c6be955ebaeabee56497bbcc6acf8a", "size": 8318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/regiongraph.cpp", "max_stars_repo_name": "durgeshra/libDAI-1", "max_stars_repo_head_hexsha": "f72414d4381e302c0655f4055dbf526c738bf485", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2015-01-19T18:56:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T20:30:50.000Z", "max_issues_repo_path": "src/regiongraph.cpp", "max_issues_repo_name": "durgeshra/libDAI-1", "max_issues_repo_head_hexsha": "f72414d4381e302c0655f4055dbf526c738bf485", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-01-18T08:17:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-28T18:08:38.000Z", "max_forks_repo_path": "src/regiongraph.cpp", "max_forks_repo_name": "durgeshra/libDAI-1", "max_forks_repo_head_hexsha": "f72414d4381e302c0655f4055dbf526c738bf485", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2015-04-07T07:38:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-01T22:18:58.000Z", "avg_line_length": 35.3957446809, "max_line_length": 171, "alphanum_fraction": 0.5408752104, "num_tokens": 2299, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4083828936343597}}
{"text": "#include \"GltfUtil.h\"\n#include \"SimpleMesh.h\"\n#include \"Sphere.h\"\n#include \"VoxelGrid.h\"\n#include \"mathkit.h\"\n#include <Eigen/Core>\n#include <bobyqa.h>\n#include <chrono>\n#include <fmt/format.h>\n#include <fstream>\n#include <iomanip>\n#include <json.hpp>\n#include <random>\n#include <spherical_harmonics.h>\n#include <unordered_set>\n#include <vector>\n\n#ifdef WIN32\n#define NOMINMAX\n#include <direct.h>\n#include <windows.h>\n#else\n#include <unistd.h>\n#endif\n\nstruct SphericalHarmonics {\n    vec3 L00 {};\n    vec3 L11 {};\n    vec3 L10 {};\n    vec3 L1_1 {};\n    vec3 L21 {};\n    vec3 L2_1 {};\n    vec3 L2_2 {};\n    vec3 L20 {};\n    vec3 L22 {};\n};\n\nstruct SphereSet {\n    SphereSet(const SimpleMesh& mesh)\n        : mesh(mesh)\n    {\n    }\n\n    std::vector<Sphere> spheres;\n    std::vector<SphericalHarmonics> sphereSH;\n\n    const SimpleMesh& mesh;\n\n    struct {\n        std::unique_ptr<VoxelGrid> shell;\n        std::unique_ptr<VoxelGrid> filled;\n        std::unique_ptr<VoxelGrid> inside;\n    } grids;\n};\n\nstruct Triangle {\npublic:\n    Triangle(vec3 v0, vec3 v1, vec3 v2)\n    {\n        v[0] = v0;\n        v[1] = v1;\n        v[2] = v2;\n\n        vec3 crossP = cross(v1 - v0, v2 - v0);\n        area = length(crossP) / 2.0f;\n        normal = normalize(crossP);\n    }\n\n    vec3 v[3];\n    vec3 normal;\n    float area;\n};\n\nvec3 getRandomSphereLocationInsideMesh(const VoxelGrid& grid, std::default_random_engine& generator)\n{\n    aabb3 bounds = grid.gridBounds();\n    std::uniform_real_distribution<float> uniformInGridX { bounds.min.x, bounds.max.x };\n    std::uniform_real_distribution<float> uniformInGridY { bounds.min.y, bounds.max.y };\n    std::uniform_real_distribution<float> uniformInGridZ { bounds.min.z, bounds.max.z };\n\n    vec3 location;\n    ivec3 gridCoord;\n\n    do {\n        location = { uniformInGridX(generator),\n                     uniformInGridY(generator),\n                     uniformInGridZ(generator) };\n        gridCoord = grid.remapToGridSpace(location, std::round);\n    } while (grid.get(gridCoord) == 0);\n\n    return location;\n}\n\nvoid assignSpheresRandomlyInVolume(SphereSet& set, unsigned numSpheres)\n{\n    auto& grid = *set.grids.inside;\n    assert(numSpheres <= grid.numFilledVoxels());\n\n    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n    std::default_random_engine generator { seed };\n\n    for (size_t i = 0; i < numSpheres; ++i) {\n        vec3 location = getRandomSphereLocationInsideMesh(grid, generator);\n        Sphere sphere { location, 0.0 };\n        set.spheres.push_back(sphere);\n    }\n\n    aabb3 bounds = grid.gridBounds();\n    std::uniform_real_distribution<float> uniformInGridX { bounds.min.x, bounds.max.x };\n    std::uniform_real_distribution<float> uniformInGridY { bounds.min.y, bounds.max.y };\n    std::uniform_real_distribution<float> uniformInGridZ { bounds.min.z, bounds.max.z };\n\n    while (set.spheres.size() < numSpheres) {\n\n        float x = uniformInGridX(generator);\n        float y = uniformInGridY(generator);\n        float z = uniformInGridZ(generator);\n\n        ivec3 gridCoord = grid.remapToGridSpace({ x, y, z }, std::round);\n        if (grid.get(gridCoord) > 0) {\n            Sphere sphere { vec3(x, y, z), 0.0f };\n            set.spheres.push_back(sphere);\n        }\n    }\n}\n\nbool sphereTriangleIntersection(const Sphere& sphere, const vec3& v0, const vec3& v1, const vec3& v2)\n{\n    // From https://realtimecollisiondetection.net/blog/?p=103\n\n    vec3 P = sphere.origin;\n    float r = sphere.radius;\n    float rr = r * r;\n\n    vec3 A = v0 - P;\n    vec3 B = v1 - P;\n    vec3 C = v2 - P;\n\n    vec3 V = cross(B - A, C - A);\n    float d = dot(A, V);\n    float e = dot(V, V);\n    bool sep1 = d * d > rr * e;\n\n    float aa = dot(A, A);\n    float ab = dot(A, B);\n    float ac = dot(A, C);\n    float bb = dot(B, B);\n    float bc = dot(B, C);\n    float cc = dot(C, C);\n\n    bool sep2 = (aa > rr) & (ab > aa) & (ac > aa);\n    bool sep3 = (bb > rr) & (ab > bb) & (bc > bb);\n    bool sep4 = (cc > rr) & (ac > cc) & (bc > cc);\n\n    vec3 AB = B - A;\n    vec3 BC = C - B;\n    vec3 CA = A - C;\n\n    float d1 = ab - aa;\n    float d2 = bc - bb;\n    float d3 = ac - cc;\n\n    float e1 = dot(AB, AB);\n    float e2 = dot(BC, BC);\n    float e3 = dot(CA, CA);\n\n    vec3 Q1 = A * e1 - d1 * AB;\n    vec3 Q2 = B * e2 - d2 * BC;\n    vec3 Q3 = C * e3 - d3 * CA;\n\n    vec3 QC = C * e1 - Q1;\n    vec3 QA = A * e2 - Q2;\n    vec3 QB = B * e3 - Q3;\n\n    bool sep5 = (dot(Q1, Q1) > rr * e1 * e1) && (dot(Q1, QC) > 0);\n    bool sep6 = (dot(Q2, Q2) > rr * e2 * e2) && (dot(Q2, QA) > 0);\n    bool sep7 = (dot(Q3, Q3) > rr * e3 * e3) && (dot(Q3, QB) > 0);\n\n    bool separated = sep1 | sep2 | sep3 | sep4 | sep5 | sep6 | sep7;\n    return !separated;\n}\n\nbool sphereInsideMeshVolume(const Sphere& sphere, const SimpleMesh& mesh)\n{\n    // NOTE: Implicit, but this assumes that the mesh is one solid blob with no islands!\n\n    // NOTE: To avoid expensive(/not-implemented) checks to see if the sphere centers are inside the volume\n    //  of the object, we will assume they are and through other means verify that it will be invariant. The\n    //  other means are: 1) spawning points inside the volume, and 2) always making steps small enough that\n    //  we wont leave the volume when optimizing.\n\n    if (sphere.radius == 0.0) {\n        return true;\n    }\n\n    volatile bool result = true;\n    #pragma omp parallel for shared(result)\n    for (int i = 0; i < mesh.triangleCount(); ++i) {\n        if (result) {\n            // TODO: Maybe don't reconstruct these every query?!\n            vec3 v0, v1, v2;\n            mesh.triangle(i, v0, v1, v2);\n\n            if (sphereTriangleIntersection(sphere, v0, v1, v2)) {\n                result = false;\n            }\n        }\n    }\n\n    return result;\n}\n\nbool sphereSetInsideMeshVolume(const SphereSet& set, const SimpleMesh& mesh)\n{\n    for (const Sphere& sphere : set.spheres) {\n        if (!sphereInsideMeshVolume(sphere, mesh)) {\n            return false;\n        }\n    }\n    return true;\n}\n\nvoid expandSpheresMaximally(SphereSet& set)\n{\n    aabb3 gridBounds = set.grids.shell->gridBounds();\n    double gridDiameter = distance(gridBounds.min, gridBounds.max);\n\n    #pragma omp parallel for\n    for (int i = 0; i < set.spheres.size(); ++i) {\n        Sphere& sphere = set.spheres[i];\n\n        Sphere minSphere { sphere.origin, 0.0 };\n        Sphere maxSphere { sphere.origin, gridDiameter };\n\n        assert(sphereInsideMeshVolume(minSphere, set.mesh));\n        assert(!sphereInsideMeshVolume(maxSphere, set.mesh));\n\n        while (abs(maxSphere.radius - minSphere.radius) > 1e-8) {\n\n            double midpoint = (minSphere.radius + maxSphere.radius) / 2.0;\n            Sphere middleSphere { sphere.origin, midpoint };\n\n            bool midOk = sphereInsideMeshVolume(middleSphere, set.mesh);\n            if (midOk) {\n                minSphere = middleSphere;\n            } else {\n                maxSphere = middleSphere;\n            }\n        }\n\n        // Make sure to be conservative with the choice to we don't break the invariant\n        sphere.radius = minSphere.radius;\n        assert(sphereInsideMeshVolume(sphere, set.mesh));\n    }\n\n#if 0\n    std::sort(set.spheres.begin(), set.spheres.end(), [](const Sphere& lhs, const Sphere& rhs) {\n        return lhs.radius > rhs.radius;\n    });\n    fmt::print(\"   grid 'radius' {}\\n\", gridDiameter / 2.0);\n    for (auto& sphere : set.spheres) {\n        fmt::print(\"     sphere radius {}\\n\", sphere.radius);\n    }\n#endif\n}\n\ndouble sphereSetIntersectionVolumeOverestimation(const SphereSet& set)\n{\n    // Except some special cases there are no analytical solutions for volume intersection of many spheres. See\n    // https://www.researchgate.net/publication/289097700_Volume_of_intersection_of_six_spheres_A_special_case_of_practical_interest\n    // for some more information. In this case we don't really care about the exact intersection, but we do want to avoid as much\n    // intersection as possible, so just overcounting it works here, I think..\n\n    double intersection = 0.0;\n\n    size_t sphereCount = set.spheres.size();\n    for (size_t i = 0; i < sphereCount; ++i) {\n        const Sphere& self = set.spheres[i];\n        for (size_t k = i + 1; k < sphereCount; ++k) {\n            const Sphere& other = set.spheres[k];\n            intersection += self.overlapWith(other);\n        }\n    }\n\n    return intersection;\n}\n\ndouble sphereSetUnionVolume(const SphereSet& set)\n{\n    double volume = 0.0;\n\n    size_t sphereCount = set.spheres.size();\n    for (const Sphere& sphere : set.spheres) {\n        volume += sphere.volume();\n    }\n\n    // TODO: Maybe scale down the intersection a bit, since we know it overestimates?\n    double intersectionOverestimation = sphereSetIntersectionVolumeOverestimation(set);\n    volume -= 0.25 * intersectionOverestimation;\n\n    return volume;\n}\n\nstruct SphereFittingData {\n    SphereSet* set;\n    unsigned sphereIndex;\n};\n\nREAL sphereFittingObjectiveFunction(const INTEGER n, const REAL* x, void* dataPtr)\n{\n    assert(n == 4);\n\n    Sphere testSphere;\n    testSphere.radius = x[3];\n    testSphere.origin = { x[0], x[1], x[2] };\n\n    SphereFittingData& data = *reinterpret_cast<SphereFittingData*>(dataPtr);\n    SphereSet& set = *data.set;\n\n    // Temporarily swap in the sphere to test\n    Sphere currentSphere = set.spheres[data.sphereIndex];\n    set.spheres[data.sphereIndex] = testSphere;\n\n    if (!sphereInsideMeshVolume(testSphere, set.mesh)) {\n        return 99999.99; // BOBYQA doesn't seem to like infinities, but this will do\n    }\n\n    // Since BOBYQA solves a minimization problem we want to minimize\n    // the *negative* volume to get a maximal volume solution.\n    double metric = -sphereSetUnionVolume(set);\n\n    // Replace the current sphere back into the sphere set\n    set.spheres[data.sphereIndex] = currentSphere;\n\n    return metric;\n}\n\nvoid sphereFitting(SphereSet& set)\n{\n    // To avoid fitting the spheres in the same order every time.\n    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n    std::shuffle(set.spheres.begin(), set.spheres.end(), std::default_random_engine(seed));\n\n    for (size_t sphereIdx = 0; sphereIdx < set.spheres.size(); ++sphereIdx) {\n\n        Sphere& sphere = set.spheres[sphereIdx];\n        assert(sphere.radius > 0.0);\n\n        // Origin (3) + radius (1)\n        constexpr INTEGER n = 3 + 1;\n\n        // NPT is the number of interpolation conditions.  Its value must be in the interval\n        // [N+2,(N+1)(N+2)/2].  Choices that exceed 2*N+1 are not recommended.\n        // TODO: Find a good value!\n#if 0\n        constexpr INTEGER npt = n + 2; // (6)\n#else\n        constexpr INTEGER npt = (n + 1) * (n + 2) / 2; // (15)\n#endif\n\n        REAL x[n] = {\n            sphere.origin.x,\n            sphere.origin.y,\n            sphere.origin.z,\n            sphere.radius\n        };\n\n        // To inscribe a box = {min, max} in a sphere we want to find the min & max\n        // points which lie along the diagonal that goes through the box center.\n        //\n        //  sqrt(x^2 + y^2 + y^3) = r\n        //   since diagonal -> x=y=z = d\n        //             sqrt(3d^2) = r\n        //                   3d^2 = r^2\n        //                      d = sqrt(r^2 / 3)\n        //\n        double d = std::sqrt(sphere.radius * sphere.radius / 3.0);\n        vec3 boxDiagonal = vec3(d, d, d) * 0.99f; // (avoid overstepping!)\n        aabb3 boxInSphere { sphere.origin - boxDiagonal, sphere.origin + boxDiagonal };\n\n        REAL xLower[n] = {\n            boxInSphere.min.x,\n            boxInSphere.min.y,\n            boxInSphere.min.z,\n            1e-8\n        };\n\n        aabb3 gridBounds = set.grids.shell->gridBounds();\n        double gridMaxDistance = length(gridBounds.max - gridBounds.min);\n\n        REAL xUpper[n] = {\n            boxInSphere.max.x,\n            boxInSphere.max.y,\n            boxInSphere.max.z,\n            gridMaxDistance\n        };\n\n        // \"Typically, RHOBEG should be about one tenth of the greatest expected change to a variable\"\n        // TODO: Find good value!\n        REAL rhoBeg = (2.0 * d) / 10.0;\n\n        // RHOEND should indicate the accuracy that is required in the final values of the variables\n        // NOTE: Some models are tiny, others are huge.. So an absolute/constant accuracy is probably\n        //  not very helpful here. A fraction of the sphere radius could maybe work as a scale-aware metric?\n        // TODO: Find good value!\n        REAL rhoEnd = gridMaxDistance * 1e-8;\n\n        //The array W will be used for working space.  Its length must be at least\n        // (NPT+5)*(NPT+N)+3*N*(N+5)/2.  Upon successful return, the first element of W\n        // will be set to the function value at the solution. */\n        REAL workingMemory[(npt + 5) * (npt + n) + 3 * n * (n + 5) / 2];\n\n        INTEGER logLevel = 0;\n        INTEGER maxObjFunCalls = 10'000;\n\n        SphereFittingData data { &set, sphereIdx };\n\n        int status = bobyqa(n, npt, sphereFittingObjectiveFunction, (void*)(&data),\n                            x, xLower, xUpper, rhoBeg, rhoEnd,\n                            logLevel, maxObjFunCalls, workingMemory);\n\n        switch (status) {\n        case BOBYQA_SUCCESS: {\n            // algorithm converged!\n            vec3 newOrigin { x[0], x[1], x[2] };\n            double newRadius = x[3];\n\n#if 0\n            fmt::print(\"      - ({}, {}, {}) r={}\\n\", newOrigin.x, newOrigin.y, newOrigin.z, newRadius);\n\n            vec3 diffOrigin = newOrigin - sphere.origin;\n            double diffRadius = newRadius - sphere.radius;\n            //fmt::print(\"      - ({}, {}, {}) r={}\\n\", diffOrigin.x, diffOrigin.y, diffOrigin.z, diffRadius);\n            //assert(length(diffOrigin) > 1e-6 && abs(diffRadius > 1e-6));\n#endif\n\n            sphere.origin = newOrigin;\n            sphere.radius = newRadius;\n            return;\n        }\n        case BOBYQA_BAD_NPT:\n            fmt::print(\"bobyqa error: NPT is not in the required interval\\n\");\n            assert(false); // npt is hardcoded to a valid value!\n            break;\n        case BOBYQA_TOO_CLOSE:\n            fmt::print(\"bobyqa error: insufficient space between the bounds\\n\");\n            break;\n        case BOBYQA_ROUNDING_ERRORS:\n            fmt::print(\"bobyqa error: too much cancellation in a denominator\\n\");\n            break;\n        case BOBYQA_TOO_MANY_EVALUATIONS:\n            fmt::print(\"bobyqa error: maximum number of function evaluations exceeded\\n\");\n            break;\n        case BOBYQA_STEP_FAILED:\n            fmt::print(\"bobyqa error: a trust region step has failed to reduce Q\\n\");\n            break;\n        default:\n            assert(false);\n        }\n    }\n}\n\nvec3 randomPointInSphere(const Sphere& sphere)\n{\n    std::uniform_real_distribution<double> randomOffset { -sphere.radius, +sphere.radius };\n\n    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n    std::default_random_engine generator { seed };\n\n    vec3 offset;\n    do {\n        offset = { randomOffset(generator), randomOffset(generator), randomOffset(generator) };\n    } while (length(offset) > sphere.radius);\n\n    return sphere.origin + offset;\n}\n\nvoid sphereTeleportation(SphereSet& set)\n{\n    if (set.spheres.size() == 1) {\n        // TODO: Maybe pick a new starting point?\n        // Or let the teleportation fail like this and restart from the main loop?\n        return;\n    }\n\n    std::sort(set.spheres.begin(), set.spheres.end(), [](const Sphere& lhs, const Sphere& rhs) {\n        return lhs.radius < rhs.radius;\n    });\n\n    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n    std::default_random_engine generator { seed };\n\n    size_t numToReplace = std::ceil(set.spheres.size() / 8.0);\n    for (size_t i = 0; i < numToReplace; ++i) {\n\n        Sphere& sphere = set.spheres[i];\n        sphere.origin = getRandomSphereLocationInsideMesh(*set.grids.inside, generator);\n\n        // NOTE: A sphere expansion will happen after this is done, so we don't need to take care of that now\n        sphere.radius = 0.0;\n    }\n}\n\ndouble aabbVolume(const aabb3& aabb)\n{\n    glm::vec<3, double> dims = aabb.max - aabb.min;\n    return dims.x * dims.y * dims.z;\n}\n\nstd::optional<vec3> triangleRayIntersection(vec3 v0, vec3 v1, vec3 v2, vec3 rayOrigin, vec3 rayDirection, float& outT)\n{\n    // From GraphicsCodex\n\n    const vec3& e1 = v1 - v0;\n    const vec3& e2 = v2 - v0;\n\n    vec3 N = normalize(cross(e1, e2));\n\n    vec3 q = cross(rayDirection, e2);\n    float a = dot(e1, q);\n\n    // Close to the limit of precision?\n    if (fabsf(a) <= 1e-4f) {\n        return {};\n    }\n\n    const vec3& s = (rayOrigin - v0) / a;\n    const vec3& r = cross(s, e1);\n\n    // Barycentric coordinates\n    float b[3];\n    b[0] = dot(s, q);\n    b[1] = dot(r, rayDirection);\n    b[2] = 1.0f - b[0] - b[1];\n\n    // Intersected inside triangle?\n    float t = dot(e2, r);\n    if ((b[0] >= 0) && (b[1] >= 0) && (b[2] >= 0) && t >= 0) {\n\n        vec3 hitPoint = rayOrigin + t * rayDirection;\n\n        // TODO: This worked on a previous project... What's up with the order though?\n        vec3 barycentric { b[2], b[0], b[1] };\n\n        outT = t;\n        return barycentric;\n    }\n\n    return {};\n}\n\nvec3 raytraceMesh(const SimpleMesh& mesh, vec3 o, vec3 d)\n{\n    float closestT = INFINITE;\n    int64_t closestTriangle = -1;\n    vec3 closestBarycentric {};\n\n    for (size_t ti = 0; ti < mesh.triangleCount(); ++ti) {\n\n        vec3 v0, v1, v2;\n        mesh.triangle(ti, v0, v1, v2);\n\n        float t;\n        std::optional<vec3> bary = triangleRayIntersection(v0, v1, v2, o, d, t);\n\n        if (bary.has_value() && t < closestT) {\n            closestBarycentric = bary.value();\n            closestTriangle = ti;\n            closestT = t;\n        }\n    }\n\n    if (closestTriangle == -1) {\n        return vec3(0, 0, 0);\n    }\n\n    vec2 uv0, uv1, uv2;\n    mesh.triangleTexcoords(closestTriangle, uv0, uv1, uv2);\n\n    vec3 b = closestBarycentric;\n    vec2 uv = b[0] * uv0 + b[1] * uv1 + b[2] * uv2;\n\n    assert(mesh.hasTexture());\n    vec3 color = mesh.texture().sample(uv);\n\n    return color;\n}\n\nSphericalHarmonics generateSphericalHarmonics(vec3 sampleCenter, size_t numSamples, const SimpleMesh& mesh)\n{\n\n    auto rgbFunction = [&](double phi, double theta) -> vec3 {\n        Eigen::Vector3d v = sh::ToVector(phi, theta);\n        vec3 direction = vec3(v.x(), v.y(), v.z());\n        vec3 Lsrgb = raytraceMesh(mesh, sampleCenter, direction);\n        return pow(Lsrgb, vec3(2.2f));\n    };\n\n    std::vector<double> r = *sh::ProjectFunction(\n        2, [&](double phi, double theta) -> double {\n            vec3 color = rgbFunction(phi, theta);\n            return color.r;\n        },\n        numSamples);\n    std::vector<double> g = *sh::ProjectFunction(\n        2, [&](double phi, double theta) -> double {\n            vec3 color = rgbFunction(phi, theta);\n            return color.g;\n        },\n        numSamples);\n    std::vector<double> b = *sh::ProjectFunction(\n        2, [&](double phi, double theta) -> double {\n            vec3 color = rgbFunction(phi, theta);\n            return color.b;\n        },\n        numSamples);\n\n    assert(r.size() == 9);\n    assert(g.size() == 9);\n    assert(b.size() == 9);\n\n    SphericalHarmonics sh;\n\n    sh.L00 = vec3(r[0], g[0], b[0]);\n\n    sh.L1_1 = vec3(r[1], g[1], b[1]);\n    sh.L10 = vec3(r[2], g[2], b[2]);\n    sh.L11 = vec3(r[3], g[3], b[3]);\n\n    sh.L2_2 = vec3(r[4], g[4], b[4]);\n    sh.L2_1 = vec3(r[5], g[5], b[5]);\n    sh.L20 = vec3(r[6], g[6], b[6]);\n    sh.L21 = vec3(r[7], g[7], b[7]);\n    sh.L22 = vec3(r[8], g[8], b[8]);\n\n    return sh;\n}\n\nstd::vector<SphericalHarmonics> generateSphericalHarmonicsForSphereColors(const SphereSet& set, size_t numSamples)\n{\n    std::vector<SphericalHarmonics> SHs;\n\n    for (const Sphere& sphere : set.spheres) {\n        SphericalHarmonics sh = generateSphericalHarmonics(sphere.origin, numSamples, set.mesh);\n        SHs.push_back(sh);\n    }\n\n    return SHs;\n}\n\nvoid generateJsonOutput(const SphereSet& sphereSet, const std::string& outPath)\n{\n    using namespace nlohmann;\n\n    json j;\n    j[\"proxy\"] = \"sphere-set\";\n    j[\"spheres\"] = {};\n\n    for (size_t i = 0; i < sphereSet.spheres.size(); ++i) {\n\n        const Sphere& sphere = sphereSet.spheres[i];\n        const SphericalHarmonics& sh = sphereSet.sphereSH[i];\n\n        json jsonSphere = {\n            { \"center\", { sphere.origin.x, sphere.origin.y, sphere.origin.z } },\n            { \"radius\", sphere.radius },\n            { \"sh\",\n              { { \"L00\", { sh.L00.x, sh.L00.y, sh.L00.z } },\n                { \"L1_1\", { sh.L1_1.x, sh.L1_1.y, sh.L1_1.z } },\n                { \"L10\", { sh.L10.x, sh.L10.y, sh.L10.z } },\n                { \"L11\", { sh.L11.x, sh.L11.y, sh.L11.z } },\n                { \"L2_2\", { sh.L2_2.x, sh.L2_2.y, sh.L2_2.z } },\n                { \"L2_1\", { sh.L2_1.x, sh.L2_1.y, sh.L2_1.z } },\n                { \"L20\", { sh.L20.x, sh.L20.y, sh.L20.z } },\n                { \"L21\", { sh.L21.x, sh.L21.y, sh.L21.z } },\n                { \"L22\", { sh.L22.x, sh.L22.y, sh.L22.z } } } }\n        };\n        j[\"spheres\"].push_back(jsonSphere);\n    }\n\n    std::ofstream outstream(outPath);\n    outstream << std::setw(4) << j << std::endl;\n}\n\nvoid generateOutput(const SphereSet& sphereSet, bool doPrint = true)\n{\n    size_t sphereCount = sphereSet.spheres.size();\n\n    std::string result = \"const vec4 spheres[] = vec4[](\\n\";\n    for (size_t i = 0; i < sphereCount; ++i) {\n        const Sphere& sphere = sphereSet.spheres[i];\n        std::string line = fmt::format(\"\\tvec4({}, {}, {}, {}){}\\n\",\n                                       sphere.origin.x, sphere.origin.y, sphere.origin.z,\n                                       sphere.radius, (i + 1 == sphereCount) ? \"\" : \",\");\n        result += line;\n    }\n    result += \");\\n\";\n\n    if (doPrint) {\n        fmt::print(result);\n    }\n\n#ifdef WIN32\n    OpenClipboard(0);\n    EmptyClipboard();\n    HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, result.size() + 1);\n    if (!hg) {\n        CloseClipboard();\n        return;\n    }\n    memcpy(GlobalLock(hg), result.c_str(), result.size());\n    GlobalUnlock(hg);\n    SetClipboardData(CF_TEXT, hg);\n    CloseClipboard();\n    GlobalFree(hg);\n#endif\n}\n\nvoid setApplicationWorkingDirectory(char* executableName, const std::string& workingDir)\n{\n#ifdef WIN32\n    char fullPathBuf[_MAX_PATH] = {};\n    assert(_fullpath(fullPathBuf, executableName, sizeof(fullPathBuf)));\n    std::string fullPath { fullPathBuf };\n\n    size_t startOfWorkingDirName = fullPath.find(workingDir);\n    std::string newWorkingDir = fullPath.substr(0, startOfWorkingDirName + workingDir.length() + 1);\n    assert(_chdir(newWorkingDir.c_str()) == 0);\n#else\n    char fullPathBuf[PATH_MAX] = {};\n    assert(realpath(executableName, fullPathBuf));\n    std::string fullPath { fullPathBuf };\n\n    size_t startOfWorkingDirName = fullPath.find(workingDir);\n    std::string newWorkingDir = fullPath.substr(0, startOfWorkingDirName + workingDir.length() + 1);\n    assert(chdir(newWorkingDir.c_str()) == 0);\n#endif\n}\n\nint main(int argc, char** argv)\n{\n    setApplicationWorkingDirectory(argv[0], \"ProxyGen\");\n\n    std::string path = \"assets/Barrel/barrel.gltf\";\n    std::string outPath = \"assets/Barrel/barrel_spheres.json\";\n\n    constexpr unsigned numSpheres = 2;\n    const size_t gridDimensions = 126;\n\n    constexpr size_t numShSamples = 4096;\n\n    fmt::print(\"=> loading model '{}'\\n\", path);\n    auto [basePath, model] = GltfUtil::loadModel(path);\n    std::vector<SimpleMesh> simpleMeshes {};\n    GltfUtil::bakeDownModelToSimpleMeshes(model, basePath, simpleMeshes);\n    if (simpleMeshes.size() > 1) {\n        fmt::print(\"==> model has more than one meshes; only the first will be used!\\n\");\n    }\n\n    const SimpleMesh& mesh = simpleMeshes[0];\n    SphereSet set { mesh };\n\n    fmt::print(\"=> creating voxel grids\\n\");\n\n    aabb3 meshBounds { vec3(+INFINITY), vec3(-INFINITY) };\n    mesh.extendAABB(meshBounds.min, meshBounds.max);\n\n    set.grids.shell = std::make_unique<VoxelGrid>(glm::ivec3(gridDimensions), meshBounds);\n    set.grids.shell->insertMesh(mesh, true);\n    set.grids.shell->quantizeColors(10);\n\n    set.grids.filled = std::make_unique<VoxelGrid>(*set.grids.shell);\n    set.grids.filled->fillVolumes();\n\n    set.grids.inside = std::make_unique<VoxelGrid>(*set.grids.filled);\n    set.grids.inside->subtractGrid(*set.grids.shell);\n\n    fmt::print(\"=> assigning initial spheres\\n\");\n    assignSpheresRandomlyInVolume(set, numSpheres);\n\n    fmt::print(\"=> optimizing begin\\n\");\n\n    bool didJustTeleport = false;\n    double previousVolume = -std::numeric_limits<double>::infinity();\n\n    double bestVolume = std::numeric_limits<double>::min();\n    std::vector<Sphere> bestSolution {};\n\n    constexpr int maxConsecutiveReverts = 3;\n    int numConsecutiveReverts = 0;\n\n    constexpr int maxIterations = 10'000;\n    int iteration = 0;\n\n    for (; iteration < maxIterations; ++iteration) {\n\n        fmt::print(\"==> expanding spheres\\n\");\n        expandSpheresMaximally(set);\n        double newVolume = sphereSetUnionVolume(set);\n        fmt::print(\"   volume: {}\\n\", newVolume);\n\n        if (newVolume > bestVolume) {\n            bestVolume = newVolume;\n            bestSolution = set.spheres;\n        }\n\n        if (newVolume > previousVolume) {\n\n            fmt::print(\"===> sphere fitting\\n\");\n            sphereFitting(set);\n\n            didJustTeleport = false;\n            numConsecutiveReverts = 0;\n\n        } else {\n\n            if (didJustTeleport) {\n                fmt::print(\"==> teleportation failed to increase volume, \");\n                if (numConsecutiveReverts < maxConsecutiveReverts) {\n                    fmt::print(\"reverting to known good solution\\n\");\n                    set.spheres = bestSolution;\n                    numConsecutiveReverts += 1;\n                    //continue; (no, we have to teleport from this new stage first!)\n                } else {\n                    fmt::print(\"and max reverts reached, so aborting\\n\");\n                    break;\n                }\n            }\n\n            fmt::print(\"===> sphere teleportation\\n\");\n            sphereTeleportation(set);\n            didJustTeleport = true;\n        }\n\n        previousVolume = newVolume;\n\n        if (iteration % 10 == 0) {\n            double itDone = 100.0 * double(iteration) / double(maxIterations);\n            fmt::print(\"==> {} iterations done ({:.1f}%)\\n\", iteration, itDone);\n            generateOutput(set, false);\n        }\n    }\n\n    if (iteration == maxIterations) {\n        fmt::print(\"==> max iterations reached\\n\");\n    }\n\n    if (numConsecutiveReverts == maxConsecutiveReverts) {\n        fmt::print(\"==> max consectutive reverts reached\\n\");\n    }\n\n    fmt::print(\"=> optimizing done\\n\");\n\n    fmt::print(\"=> generating sphere output with volume {} (AABB volume {})\\n\", bestVolume, aabbVolume(meshBounds));\n    set.spheres = bestSolution;\n\n    fmt::print(\"=> generating SH color representations for spheres ({} samples)\\n\", numShSamples);\n    std::vector<SphericalHarmonics> SHs = generateSphericalHarmonicsForSphereColors(set, numShSamples);\n    set.sphereSH = SHs;\n\n    generateOutput(set);\n    generateJsonOutput(set, outPath);\n}\n", "meta": {"hexsha": "84cb13455406af1d1eafbff1bb535de1023b9cde", "size": 27125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/src/BoundedSphereSet.cpp", "max_stars_repo_name": "Shimmen/ProxyGen", "max_stars_repo_head_hexsha": "97240c6d91ed2adac5f40e88e49f9541b2c5740e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-12T09:00:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-22T05:27:42.000Z", "max_issues_repo_path": "code/src/BoundedSphereSet.cpp", "max_issues_repo_name": "Shimmen/ProxyGen", "max_issues_repo_head_hexsha": "97240c6d91ed2adac5f40e88e49f9541b2c5740e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/src/BoundedSphereSet.cpp", "max_forks_repo_name": "Shimmen/ProxyGen", "max_forks_repo_head_hexsha": "97240c6d91ed2adac5f40e88e49f9541b2c5740e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3946759259, "max_line_length": 132, "alphanum_fraction": 0.5944700461, "num_tokens": 7432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825006, "lm_q2_score": 0.5234203489363239, "lm_q1q2_score": 0.40826416137260935}}
{"text": "/*\n * optimize_tnc.cpp\n *\n *  Created on: Feb 9, 2010\n *      Author: smitty\n */\n\n#include \"optimize_state_reconstructor_periods_nlopt.h\"\n#include <iostream>\n#include <stdio.h>\n#include <nlopt.hpp>\n#include <math.h>\n#include <vector>\n\n#include \"state_reconstructor.h\"\n#include \"rate_model.h\"\n\n#include <armadillo>\nusing namespace arma;\n\n\nStateReconstructor * nloptsr_periods;\nvector<RateModel> * nloptrm_periods;\nvector<mat> * nloptfree_variables_periods;\n\n//double nlopt_sr(int n, const double *x, void *state) {\n//double nlopt_sr(unsigned n, const double *x, double *grad, void *my_func_data);\ndouble nlopt_sr_periods(unsigned n, const double *x, double *grad, void *my_func_data) {\n    for (unsigned int k=0; k < nloptfree_variables_periods->size(); k++) {\n        for (unsigned int i=0; i < (*nloptfree_variables_periods)[k].n_rows; i++) {\n            for (unsigned int j=0; j < (*nloptfree_variables_periods)[k].n_cols; j++) {\n                if (i != j) {\n                    (*nloptrm_periods)[k].set_Q_cell(i,j,x[int(nloptfree_variables_periods->at(k)(i,j))]);\n                    if ((*nloptrm_periods)[k].get_Q()(i,j) < 0 || (*nloptrm_periods)[k].get_Q()(i,j) >= 1000) {\n                        return 1000000000000;\n                    }\n                }\n            }\n        }\n    }\n    double like;\n    for (unsigned int i=0; i < nloptrm_periods->size(); i++) {\n        nloptrm_periods->at(i).set_Q_diag();\n    }\n    like = nloptsr_periods->eval_likelihood();\n    for (unsigned int i=0; i < nloptrm_periods->size(); i++) {\n        if (nloptrm_periods->at(i).neg_p == true) {\n            like = 10000000000000;\n            break;\n        }\n    }\n//    cout << like << endl;\n    if (like < 0 || like == std::numeric_limits<double>::infinity()) {\n        like = 10000000000000;\n    }\n    return like;\n}\n\nvoid optimize_sr_periods_nlopt(vector<RateModel> * _rm,StateReconstructor * _sr, vector<mat> * _free_mask, int _nfree) {\n    nloptsr_periods = _sr;\n    nloptrm_periods = _rm;\n    nloptfree_variables_periods = _free_mask;\n    \n    nlopt::opt opt(nlopt::LN_NELDERMEAD, _nfree);\n    //nlopt::opt opt(nlopt::LN_BOBYQA, _nfree);\n    //nlopt::opt opt(nlopt::LN_PRAXIS, _nfree);\n    //nlopt::opt opt(nlopt::LN_SBPLX, _nfree);\n    //nlopt::opt opt(nlopt::LN_COBYLA, _nfree);\n    //nlopt::opt opt(nlopt::LN_NEWUOA, _nfree);\n    \n    opt.set_lower_bounds(0.0000);\n    opt.set_upper_bounds(100000);\n    opt.set_min_objective(nlopt_sr_periods, NULL);\n    opt.set_xtol_rel(0.001);\n    opt.set_maxeval(10000);\n    \n    vector<double> x(_nfree,0);\n    for (unsigned int k=0; k < _rm->size(); k++) {\n        for (unsigned int i=0; i < _rm->at(k).get_Q().n_rows; i++) {\n            for (unsigned int j=0; j < _rm->at(k).get_Q().n_cols; j++) {\n                if (i != j) {\n                    x[int((*_free_mask)[k](i, j))] = _rm->at(k).get_Q()(i, j);\n                    //cout << x[int((*_free_mask)[k](i,j))] << \" \";\n                }\n            }\n            cout << endl;\n        }\n    }\n    //double minf;\n    vector<double> result = opt.optimize(x);\n    for (unsigned int k=0; k < _rm->size(); k++) {\n        for (unsigned int i=0; i < _rm->at(k).get_Q().n_rows; i++) {\n            for (unsigned int j=0; j < _rm->at(k).get_Q().n_cols; j++) {\n                if (i != j) {\n                    (*_free_mask)[k](i, j) = result[int((*_free_mask)[k](i, j))];\n                    //cout << x[int((*(*_free_mask)[k])(i,j))] << \" \";\n                }\n            }\n        //cout << endl;\n        }\n    }\n    //if ((&minf) < 0) {\n    //   printf(\"nlopt failed!\\n\");\n    //}\n    //else {\n    //    printf(\"found minimum at %0.10g\\n\", x[0], x[1], minf);\n    //}\n}\n\n\n\n", "meta": {"hexsha": "ba7cbbd97f3847b3e7a6e15f303fa3fb6dcfb801", "size": 3665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_periods_nlopt.cpp", "max_stars_repo_name": "jlanga/smsk_selection", "max_stars_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-18T05:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T10:22:33.000Z", "max_issues_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_periods_nlopt.cpp", "max_issues_repo_name": "jlanga/smsk_selection", "max_issues_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T07:26:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-08T13:59:48.000Z", "max_forks_repo_path": "src/phyx-1.01/src/optimize_state_reconstructor_periods_nlopt.cpp", "max_forks_repo_name": "jlanga/smsk_orthofinder", "max_forks_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-18T05:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:23:31.000Z", "avg_line_length": 32.7232142857, "max_line_length": 120, "alphanum_fraction": 0.548431105, "num_tokens": 1142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541068, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.40826415601886}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_BERNOULLI_LOGIT_LPMF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_BERNOULLI_LOGIT_LPMF_HPP\n\n#include <stan/math/prim/scal/meta/is_constant_struct.hpp>\n#include <stan/math/prim/scal/meta/partials_return_type.hpp>\n#include <stan/math/prim/scal/meta/operands_and_partials.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_bounded.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/fun/size_zero.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/fun/inv_logit.hpp>\n#include <stan/math/prim/scal/fun/log1m.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>\n#include <boost/random/bernoulli_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n/**\n * Returns the log PMF of the logit-parametrized Bernoulli distribution. If\n * containers are supplied, returns the log sum of the probabilities.\n *\n * @tparam T_n type of integer parameter\n * @tparam T_prob type of chance of success parameter\n * @param n integer parameter\n * @param theta logit-transformed chance of success parameter\n * @return log probability or log sum of probabilities\n * @throw std::domain_error if theta is infinite.\n * @throw std::invalid_argument if container sizes mismatch.\n */\ntemplate <bool propto, typename T_n, typename T_prob>\ntypename return_type<T_prob>::type bernoulli_logit_lpmf(const T_n& n,\n                                                        const T_prob& theta) {\n  static const char* function = \"bernoulli_logit_lpmf\";\n  typedef\n      typename stan::partials_return_type<T_n, T_prob>::type T_partials_return;\n\n  using std::exp;\n\n  if (size_zero(n, theta))\n    return 0.0;\n\n  T_partials_return logp(0.0);\n\n  check_bounded(function, \"n\", n, 0, 1);\n  check_not_nan(function, \"Logit transformed probability parameter\", theta);\n  check_consistent_sizes(function, \"Random variable\", n,\n                         \"Probability parameter\", theta);\n\n  if (!include_summand<propto, T_prob>::value)\n    return 0.0;\n\n  scalar_seq_view<T_n> n_vec(n);\n  scalar_seq_view<T_prob> theta_vec(theta);\n  size_t N = max_size(n, theta);\n  operands_and_partials<T_prob> ops_partials(theta);\n\n  for (size_t n = 0; n < N; n++) {\n    const T_partials_return theta_dbl = value_of(theta_vec[n]);\n\n    const int sign = 2 * n_vec[n] - 1;\n    const T_partials_return ntheta = sign * theta_dbl;\n    const T_partials_return exp_m_ntheta = exp(-ntheta);\n\n    // Handle extreme values gracefully using Taylor approximations.\n    static const double cutoff = 20.0;\n    if (ntheta > cutoff)\n      logp -= exp_m_ntheta;\n    else if (ntheta < -cutoff)\n      logp += ntheta;\n    else\n      logp -= log1p(exp_m_ntheta);\n\n    if (!is_constant_struct<T_prob>::value) {\n      if (ntheta > cutoff)\n        ops_partials.edge1_.partials_[n] -= exp_m_ntheta;\n      else if (ntheta < -cutoff)\n        ops_partials.edge1_.partials_[n] += sign;\n      else\n        ops_partials.edge1_.partials_[n]\n            += sign * exp_m_ntheta / (exp_m_ntheta + 1);\n    }\n  }\n  return ops_partials.build(logp);\n}\n\ntemplate <typename T_n, typename T_prob>\ninline typename return_type<T_prob>::type bernoulli_logit_lpmf(\n    const T_n& n, const T_prob& theta) {\n  return bernoulli_logit_lpmf<false>(n, theta);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "4f750616388cb83b387d321ea24fa2af6fc60f36", "size": 3566, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/scal/prob/bernoulli_logit_lpmf.hpp", "max_stars_repo_name": "vchiapaikeo/prophet", "max_stars_repo_head_hexsha": "e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/scal/prob/bernoulli_logit_lpmf.hpp", "max_issues_repo_name": "vchiapaikeo/prophet", "max_issues_repo_head_hexsha": "e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "venv/lib/python3.7/site-packages/pystan/stan/lib/stan_math/stan/math/prim/scal/prob/bernoulli_logit_lpmf.hpp", "max_forks_repo_name": "vchiapaikeo/prophet", "max_forks_repo_head_hexsha": "e8c250ca7bfffc280baa7dabc80a2c2d1f72c6a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9607843137, "max_line_length": 79, "alphanum_fraction": 0.7187324734, "num_tokens": 964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125848754472, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.40824002081252747}}
{"text": "/*\n*  @file \t\tex9.cpp\n*  @details  \tThis file is the solution to exercise 9.\n*  @author    \tAlexander Rettkowski\n*  @date      \t12.07.2017\n*/\n#include <boost/config/warning_disable.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/phoenix_object.hpp>\n#include <boost/fusion/include/adapt_struct.hpp>\n#include <boost/fusion/include/io.hpp>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n#include <boost/property_map/property_map.hpp>\n\n#include <boost/timer/timer.hpp>\n#include <boost/chrono.hpp>\n\n#include <iostream>\n#include <string>\n#include <complex>\n#include <fstream>\n#include <queue> \n\n#include <omp.h>\n\nusing namespace boost;\n\nnamespace exercise9\n{\n\tnamespace qi = boost::spirit::qi;\n\tnamespace ascii = boost::spirit::ascii;\n\tstruct edge\n\t{\n\t\tint startNode;\n\t\tint endNode;\n\t\tint length;\n\t};\n}\n\n\nBOOST_FUSION_ADAPT_STRUCT(\n\texercise9::edge,\n\t(int, startNode)\n\t(int, endNode)\n\t(int, length)\n)\n\nnamespace exercise9\n{\n\ttemplate <typename Iterator>\n\tstruct line_parser : qi::grammar<Iterator, edge()>\n\t{\n\t\tline_parser() : line_parser::base_type(start)\n\t\t{\n\t\t\tusing qi::int_;\n\t\t\tstart %= int_ >> ' ' >> int_ >> ' ' >> int_;\n\t\t}\n\n\t\tqi::rule<Iterator, edge()> start;\n\t};\n}\n\n\n/**\n* This method checks (in a naive way), if a given number is prime or not.\n* @param number The number to check.\n* @returns True, if number is prime; false otherwise.\n*/\nbool isPrime(int number) {\n\tif (number == 2)\n\t\treturn true;\n\tif (number % 2 == 0)\n\t\treturn false;\n\tfor (int i = 3; (i*i) <= number; i += 2) {\n\t\tif (number % i == 0) return false;\n\t}\n\treturn true;\n}\n\n/**\n* The function that calculates the shortest paths using Dijkstra's method.\n* @param numberOfNodes Number of nodes in the graph.\n* @param graph The graph represented as a vector auf edge-vectors.\n* @param startNode The id of the node where the search starts.\n* @returns The weight of the Steiner Tree and the edge list of the tree coupled as a std::pair\n*/\nstd::pair<int, std::list<std::pair<int, int>>>  steinerTree(int numberOfNodes, std::vector< std::vector< std::pair<int, int> > > graph, int startNode)\n{\n\tstd::vector<int> connectedVertices;\n\tconnectedVertices.push_back(startNode);\n\tstd::list<std::pair<int, int>> edgeList;\n\n\tstd::vector<int> predecessors(numberOfNodes, -1);\n\tstd::vector<int> distanceTo(numberOfNodes, INT_MAX);\n\tstd::priority_queue< std::pair<int, int>, std::vector< std::pair<int, int> >, std::greater< std::pair<int, int> > > queue;\n\tqueue.push(std::pair<int, int>(startNode, 0));\n\tdistanceTo[startNode] = 0;\n\t//predecessors[startNode] = -1;\n\tint steinerWeight = 0;\n\n\tint currentNode, compareNode, compareNodeDistance, currentNodeDistance;\n\n\twhile (!queue.empty()) {\n\t\tcurrentNode = queue.top().first;\n\t\tcurrentNodeDistance = queue.top().second;\n\t\tqueue.pop();\n\n\t\tif (distanceTo[currentNode] < currentNodeDistance) continue;\n\n\t\tfor (int i = 0; i < graph[currentNode].size(); i++) {\n\t\t\tcompareNode = graph[currentNode][i].first;\n\t\t\tcompareNodeDistance = graph[currentNode][i].second;\n\t\t\tif (distanceTo[compareNode] > distanceTo[currentNode] + compareNodeDistance) {\n\t\t\t\tif (isPrime(compareNode))\n\t\t\t\t{\n\t\t\t\t\tpredecessors[compareNode] = currentNode;\n\n\t\t\t\t\tint backtracknode = compareNode;\n\t\t\t\t\twhile (std::find(connectedVertices.begin(), connectedVertices.end(), backtracknode) == connectedVertices.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (std::pair<int, int> edge : graph[predecessors[backtracknode]])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (edge.first == backtracknode)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tedgeList.push_back(std::pair<int, int>(predecessors[backtracknode], backtracknode));\n\t\t\t\t\t\t\t\tsteinerWeight += edge.second;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdistanceTo[backtracknode] = 0;\n\t\t\t\t\t\tconnectedVertices.push_back(backtracknode);\n\t\t\t\t\t\tbacktracknode = predecessors[backtracknode];\n\t\t\t\t\t\tqueue.push(std::pair<int, int>(backtracknode, 0));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdistanceTo[compareNode] = distanceTo[currentNode] + compareNodeDistance;\n\t\t\t\t\tqueue.push(std::pair<int, int>(compareNode, distanceTo[compareNode]));\n\t\t\t\t\tpredecessors[compareNode] = currentNode;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\treturn std::pair<int, std::list<std::pair<int, int>>>(steinerWeight, edgeList);\n}\n\n/**\n* The main function that reads in a file and processes it.\n* @param argc Number of command line arguments.\n* @param *argv a pointer to the array of command line arguments.\n*/\nint main(int argc, char *argv[])\n{\n\ttimer::cpu_timer boostTimer;\n\n\tusing boost::spirit::ascii::space;\n\ttypedef std::string::const_iterator iterator_type;\n\ttypedef exercise9::line_parser<iterator_type> line_parser;\n\tline_parser parser;\n\tstd::string currentLine;\n\tstd::ifstream file(argv[1]);\n\n\t// get number of nodes\n\tchar delimiter = ' ';\n\tgetline(file, currentLine, delimiter);\n\tconst int numberOfNodes = stoi(currentLine);\n\tgetline(file, currentLine);\n\tint constSub = 1;\n\n\tstd::vector<std::vector<std::pair<int, int>>> edges(numberOfNodes);\n\twhile (getline(file, currentLine))\n\t{\n\t\texercise9::edge parsedLine;\n\t\tstd::string::const_iterator currentPosition = currentLine.begin();\n\t\tstd::string::const_iterator lineEnd = currentLine.end();\n\t\tbool parsingSucceeded = phrase_parse(currentPosition, lineEnd, parser, space, parsedLine);\n\n\t\tif (parsingSucceeded && currentPosition == lineEnd)\n\t\t{\n\t\t\tstd::pair<int, int> *tempEdge = new std::pair<int, int>();\n\t\t\ttempEdge->first = parsedLine.endNode - constSub;\n\t\t\ttempEdge->second = parsedLine.length;\n\t\t\tedges[parsedLine.startNode - constSub].push_back(*tempEdge);\n\n\t\t\tstd::pair<int, int> *reverseEdge = new std::pair<int, int>();\n\t\t\treverseEdge->first = parsedLine.startNode - constSub;\n\t\t\treverseEdge->second = parsedLine.length;\n\t\t\tedges[parsedLine.endNode - constSub].push_back(*reverseEdge);\n\t\t}\n\t}\n\n\tfile.close();\n\n\ttimer::cpu_timer runTimer;\n\tomp_set_dynamic(0);\n\tomp_set_num_threads(std::stoi(argv[2]));\n\tstd::vector<int> terminalIds;\n\tfor (int i = 0; i < numberOfNodes; i++)\n\t{\n\t\tif (isPrime(i))\n\t\t\tterminalIds.push_back(i);\n\t}\n\tstd::vector<int> lengths(terminalIds.size());\n\n#pragma omp parallel for\n\tfor (int i = 0; i < terminalIds.size(); i++)\n\t\t{\n\t\t    std::pair<int, std::list<std::pair<int, int>>> currentRun = steinerTree(numberOfNodes, edges, terminalIds[i]);\n\t\t\tlengths[i] = currentRun.first;\n\t\t\tstd::cout << \"Length starting from \" << i << \": \" << lengths[i] << std::endl;\n\t\t}\n\n\tint minlength = INT32_MAX;\n\tint minId = -1;\n\tfor (int i = 0; i < terminalIds.size(); i++)\n\t{\n\t\tif (lengths[i] < minlength)\n\t\t{\n\t\t\tminlength = lengths[i];\n\t\t\tminId = i;\n\t\t}\n\t}\n\n\ttimer::cpu_times runtime = boostTimer.elapsed();\n\tstd::list<std::pair<int, int>> edgelist = steinerTree(numberOfNodes, edges, minId).second;\n\n\n\tstd::cout << \"TLEN: \" << minlength << std::endl;\n\tstd::cout << \"TREE: \";\n\n\tfor (std::pair<int, int> edge : edgelist)\n\t{\n\t\tstd::cout << \"(\" << edge.first << \", \" << edge.second << \") \";\n\t}\n\tstd::cout << std::endl;\n\n\ttimer::cpu_times time = boostTimer.elapsed();\n\tstd::cout << \"TIME: \" << (time.user + time.system) / 1e9 << \"s\\n\";\n\tstd::cout << \"WALL: \" << runtime.wall / 1e9 << \"s\\n\";\n\n\n\treturn 0;\n}\n\n", "meta": {"hexsha": "08114eadd705a12a0519c3d24c698361a195d5b1", "size": 7162, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rettkowski/ex9.cpp", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "rettkowski/ex9.cpp", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "rettkowski/ex9.cpp", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 28.3083003953, "max_line_length": 150, "alphanum_fraction": 0.6843060598, "num_tokens": 1943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5428632831725053, "lm_q1q2_score": 0.40824001477824934}}
{"text": "/*\n [auto_generated]\n boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp\n\n [begin_description]\n Implementation of the Dormand-Prince 5(4) method. This stepper can also be used with the dense-output controlled stepper.\n [end_description]\n\n Copyright 2009-2011 Karsten Ahnert\n Copyright 2009-2011 Mario Mulansky\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE_1_0.txt or\n copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n#ifndef BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA_DOPRI5_HPP_INCLUDED\n#define BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA_DOPRI5_HPP_INCLUDED\n\n\n#include <boost/numeric/odeint/util/bind.hpp>\n\n#include <boost/numeric/odeint/stepper/base/explicit_error_stepper_fsal_base.hpp>\n#include <boost/numeric/odeint/algebra/range_algebra.hpp>\n#include <boost/numeric/odeint/algebra/default_operations.hpp>\n#include <boost/numeric/odeint/algebra/algebra_dispatcher.hpp>\n#include <boost/numeric/odeint/algebra/operations_dispatcher.hpp>\n#include <boost/numeric/odeint/stepper/stepper_categories.hpp>\n\n#include <boost/numeric/odeint/util/state_wrapper.hpp>\n#include <boost/numeric/odeint/util/is_resizeable.hpp>\n#include <boost/numeric/odeint/util/resizer.hpp>\n#include <boost/numeric/odeint/util/same_instance.hpp>\n\nnamespace boost {\nnamespace numeric {\nnamespace odeint {\n\n\n\ntemplate<\nclass State ,\nclass Value = double ,\nclass Deriv = State ,\nclass Time = Value ,\nclass Algebra = typename algebra_dispatcher< State >::algebra_type ,\nclass Operations = typename operations_dispatcher< State >::operations_type ,\nclass Resizer = initially_resizer\n>\nclass runge_kutta_dopri5\n#ifndef DOXYGEN_SKIP\n: public explicit_error_stepper_fsal_base<\n  runge_kutta_dopri5< State , Value , Deriv , Time , Algebra , Operations , Resizer > ,\n  5 , 5 , 4 , State , Value , Deriv , Time , Algebra , Operations , Resizer >\n#else\n: public explicit_error_stepper_fsal_base\n#endif\n{\n\npublic :\n\n    #ifndef DOXYGEN_SKIP\n    typedef explicit_error_stepper_fsal_base<\n    runge_kutta_dopri5< State , Value , Deriv , Time , Algebra , Operations , Resizer > ,\n    5 , 5 , 4 , State , Value , Deriv , Time , Algebra , Operations , Resizer > stepper_base_type;\n    #else\n    typedef explicit_error_stepper_fsal_base< runge_kutta_dopri5< ... > , ... > stepper_base_type;\n    #endif\n    \n    typedef typename stepper_base_type::state_type state_type;\n    typedef typename stepper_base_type::value_type value_type;\n    typedef typename stepper_base_type::deriv_type deriv_type;\n    typedef typename stepper_base_type::time_type time_type;\n    typedef typename stepper_base_type::algebra_type algebra_type;\n    typedef typename stepper_base_type::operations_type operations_type;\n    typedef typename stepper_base_type::resizer_type resizer_type;\n\n    #ifndef DOXYGEN_SKIP\n    typedef typename stepper_base_type::stepper_type stepper_type;\n    typedef typename stepper_base_type::wrapped_state_type wrapped_state_type;\n    typedef typename stepper_base_type::wrapped_deriv_type wrapped_deriv_type;\n    #endif // DOXYGEN_SKIP\n\n\n    runge_kutta_dopri5( const algebra_type &algebra = algebra_type() ) : stepper_base_type( algebra )\n    { }\n\n\n    template< class System , class StateIn , class DerivIn , class StateOut , class DerivOut >\n    void do_step_impl( System system , const StateIn &in , const DerivIn &dxdt_in , time_type t ,\n            StateOut &out , DerivOut &dxdt_out , time_type dt )\n    {\n        const value_type a2 = static_cast<value_type> ( 1 ) / static_cast<value_type>( 5 );\n        const value_type a3 = static_cast<value_type> ( 3 ) / static_cast<value_type> ( 10 );\n        const value_type a4 = static_cast<value_type> ( 4 ) / static_cast<value_type> ( 5 );\n        const value_type a5 = static_cast<value_type> ( 8 )/static_cast<value_type> ( 9 );\n\n        const value_type b21 = static_cast<value_type> ( 1 ) / static_cast<value_type> ( 5 );\n\n        const value_type b31 = static_cast<value_type> ( 3 ) / static_cast<value_type>( 40 );\n        const value_type b32 = static_cast<value_type> ( 9 ) / static_cast<value_type>( 40 );\n\n        const value_type b41 = static_cast<value_type> ( 44 ) / static_cast<value_type> ( 45 );\n        const value_type b42 = static_cast<value_type> ( -56 ) / static_cast<value_type> ( 15 );\n        const value_type b43 = static_cast<value_type> ( 32 ) / static_cast<value_type> ( 9 );\n\n        const value_type b51 = static_cast<value_type> ( 19372 ) / static_cast<value_type>( 6561 );\n        const value_type b52 = static_cast<value_type> ( -25360 ) / static_cast<value_type> ( 2187 );\n        const value_type b53 = static_cast<value_type> ( 64448 ) / static_cast<value_type>( 6561 );\n        const value_type b54 = static_cast<value_type> ( -212 ) / static_cast<value_type>( 729 );\n\n        const value_type b61 = static_cast<value_type> ( 9017 ) / static_cast<value_type>( 3168 );\n        const value_type b62 = static_cast<value_type> ( -355 ) / static_cast<value_type>( 33 );\n        const value_type b63 = static_cast<value_type> ( 46732 ) / static_cast<value_type>( 5247 );\n        const value_type b64 = static_cast<value_type> ( 49 ) / static_cast<value_type>( 176 );\n        const value_type b65 = static_cast<value_type> ( -5103 ) / static_cast<value_type>( 18656 );\n\n        const value_type c1 = static_cast<value_type> ( 35 ) / static_cast<value_type>( 384 );\n        const value_type c3 = static_cast<value_type> ( 500 ) / static_cast<value_type>( 1113 );\n        const value_type c4 = static_cast<value_type> ( 125 ) / static_cast<value_type>( 192 );\n        const value_type c5 = static_cast<value_type> ( -2187 ) / static_cast<value_type>( 6784 );\n        const value_type c6 = static_cast<value_type> ( 11 ) / static_cast<value_type>( 84 );\n\n        typename odeint::unwrap_reference< System >::type &sys = system;\n\n        m_k_x_tmp_resizer.adjust_size( in , detail::bind( &stepper_type::template resize_k_x_tmp_impl<StateIn> , detail::ref( *this ) , detail::_1 ) );\n\n        //m_x_tmp = x + dt*b21*dxdt\n        stepper_base_type::m_algebra.for_each3( m_x_tmp.m_v , in , dxdt_in ,\n                typename operations_type::template scale_sum2< value_type , time_type >( 1.0 , dt*b21 ) );\n\n        sys( m_x_tmp.m_v , m_k2.m_v , t + dt*a2 );\n        // m_x_tmp = x + dt*b31*dxdt + dt*b32*m_k2\n        stepper_base_type::m_algebra.for_each4( m_x_tmp.m_v , in , dxdt_in , m_k2.m_v ,\n                typename operations_type::template scale_sum3< value_type , time_type , time_type >( 1.0 , dt*b31 , dt*b32 ));\n\n        sys( m_x_tmp.m_v , m_k3.m_v , t + dt*a3 );\n        // m_x_tmp = x + dt * (b41*dxdt + b42*m_k2 + b43*m_k3)\n        stepper_base_type::m_algebra.for_each5( m_x_tmp.m_v , in , dxdt_in , m_k2.m_v , m_k3.m_v ,\n                typename operations_type::template scale_sum4< value_type , time_type , time_type , time_type >( 1.0 , dt*b41 , dt*b42 , dt*b43 ));\n\n        sys( m_x_tmp.m_v, m_k4.m_v , t + dt*a4 );\n        stepper_base_type::m_algebra.for_each6( m_x_tmp.m_v , in , dxdt_in , m_k2.m_v , m_k3.m_v , m_k4.m_v ,\n                typename operations_type::template scale_sum5< value_type , time_type , time_type , time_type , time_type >( 1.0 , dt*b51 , dt*b52 , dt*b53 , dt*b54 ));\n\n        sys( m_x_tmp.m_v , m_k5.m_v , t + dt*a5 );\n        stepper_base_type::m_algebra.for_each7( m_x_tmp.m_v , in , dxdt_in , m_k2.m_v , m_k3.m_v , m_k4.m_v , m_k5.m_v ,\n                typename operations_type::template scale_sum6< value_type , time_type , time_type , time_type , time_type , time_type >( 1.0 , dt*b61 , dt*b62 , dt*b63 , dt*b64 , dt*b65 ));\n\n        sys( m_x_tmp.m_v , m_k6.m_v , t + dt );\n        stepper_base_type::m_algebra.for_each7( out , in , dxdt_in , m_k3.m_v , m_k4.m_v , m_k5.m_v , m_k6.m_v ,\n                typename operations_type::template scale_sum6< value_type , time_type , time_type , time_type , time_type , time_type >( 1.0 , dt*c1 , dt*c3 , dt*c4 , dt*c5 , dt*c6 ));\n\n        // the new derivative\n        sys( out , dxdt_out , t + dt );\n    }\n\n\n\n    template< class System , class StateIn , class DerivIn , class StateOut , class DerivOut , class Err >\n    void do_step_impl( System system , const StateIn &in , const DerivIn &dxdt_in , time_type t ,\n            StateOut &out , DerivOut &dxdt_out , time_type dt , Err &xerr )\n    {\n        const value_type c1 = static_cast<value_type> ( 35 ) / static_cast<value_type>( 384 );\n        const value_type c3 = static_cast<value_type> ( 500 ) / static_cast<value_type>( 1113 );\n        const value_type c4 = static_cast<value_type> ( 125 ) / static_cast<value_type>( 192 );\n        const value_type c5 = static_cast<value_type> ( -2187 ) / static_cast<value_type>( 6784 );\n        const value_type c6 = static_cast<value_type> ( 11 ) / static_cast<value_type>( 84 );\n\n        const value_type dc1 = c1 - static_cast<value_type> ( 5179 ) / static_cast<value_type>( 57600 );\n        const value_type dc3 = c3 - static_cast<value_type> ( 7571 ) / static_cast<value_type>( 16695 );\n        const value_type dc4 = c4 - static_cast<value_type> ( 393 ) / static_cast<value_type>( 640 );\n        const value_type dc5 = c5 - static_cast<value_type> ( -92097 ) / static_cast<value_type>( 339200 );\n        const value_type dc6 = c6 - static_cast<value_type> ( 187 ) / static_cast<value_type>( 2100 );\n        const value_type dc7 = static_cast<value_type>( -1 ) / static_cast<value_type> ( 40 );\n\n        /* ToDo: copy only if &dxdt_in == &dxdt_out ? */\n        if( same_instance( dxdt_in , dxdt_out ) )\n        {\n            m_dxdt_tmp_resizer.adjust_size( in , detail::bind( &stepper_type::template resize_dxdt_tmp_impl<StateIn> , detail::ref( *this ) , detail::_1 ) );\n            boost::numeric::odeint::copy( dxdt_in , m_dxdt_tmp.m_v );\n            do_step_impl( system , in , dxdt_in , t , out , dxdt_out , dt );\n            //error estimate\n            stepper_base_type::m_algebra.for_each7( xerr , m_dxdt_tmp.m_v , m_k3.m_v , m_k4.m_v , m_k5.m_v , m_k6.m_v , dxdt_out ,\n                                                    typename operations_type::template scale_sum6< time_type , time_type , time_type , time_type , time_type , time_type >( dt*dc1 , dt*dc3 , dt*dc4 , dt*dc5 , dt*dc6 , dt*dc7 ) );\n\n        }\n        else\n        {\n            do_step_impl( system , in , dxdt_in , t , out , dxdt_out , dt );\n            //error estimate\n            stepper_base_type::m_algebra.for_each7( xerr , dxdt_in , m_k3.m_v , m_k4.m_v , m_k5.m_v , m_k6.m_v , dxdt_out ,\n                                                    typename operations_type::template scale_sum6< time_type , time_type , time_type , time_type , time_type , time_type >( dt*dc1 , dt*dc3 , dt*dc4 , dt*dc5 , dt*dc6 , dt*dc7 ) );\n        \n        }\n\n    }\n\n\n    /*\n     * Calculates Dense-Output for Dopri5\n     *\n     * See Hairer, Norsett, Wanner: Solving Ordinary Differential Equations, Nonstiff Problems. I, p.191/192\n     *\n     * y(t+theta) = y(t) + h * sum_i^7 b_i(theta) * k_i\n     *\n     * A = theta^2 * ( 3 - 2 theta )\n     * B = theta^2 * ( theta - 1 )\n     * C = theta^2 * ( theta - 1 )^2\n     * D = theta   * ( theta - 1 )^2\n     *\n     * b_1( theta ) = A * b_1 - C * X1( theta ) + D\n     * b_2( theta ) = 0\n     * b_3( theta ) = A * b_3 + C * X3( theta )\n     * b_4( theta ) = A * b_4 - C * X4( theta )\n     * b_5( theta ) = A * b_5 + C * X5( theta )\n     * b_6( theta ) = A * b_6 - C * X6( theta )\n     * b_7( theta ) = B + C * X7( theta )\n     *\n     * An alternative Method is described in:\n     *\n     * www-m2.ma.tum.de/homepages/simeon/numerik3/kap3.ps\n     */\n    template< class StateOut , class StateIn1 , class DerivIn1 , class StateIn2 , class DerivIn2 >\n    void calc_state( time_type t , StateOut &x ,\n                     const StateIn1 &x_old , const DerivIn1 &deriv_old , time_type t_old ,\n                     const StateIn2 & /* x_new */ , const DerivIn2 &deriv_new , time_type t_new ) const\n    {\n        const value_type b1 = static_cast<value_type> ( 35 ) / static_cast<value_type>( 384 );\n        const value_type b3 = static_cast<value_type> ( 500 ) / static_cast<value_type>( 1113 );\n        const value_type b4 = static_cast<value_type> ( 125 ) / static_cast<value_type>( 192 );\n        const value_type b5 = static_cast<value_type> ( -2187 ) / static_cast<value_type>( 6784 );\n        const value_type b6 = static_cast<value_type> ( 11 ) / static_cast<value_type>( 84 );\n\n        const time_type dt = ( t_new - t_old );\n        const value_type theta = ( t - t_old ) / dt;\n        const value_type X1 = static_cast< value_type >( 5 ) * ( static_cast< value_type >( 2558722523LL ) - static_cast< value_type >( 31403016 ) * theta ) / static_cast< value_type >( 11282082432LL );\n        const value_type X3 = static_cast< value_type >( 100 ) * ( static_cast< value_type >( 882725551 ) - static_cast< value_type >( 15701508 ) * theta ) / static_cast< value_type >( 32700410799LL );\n        const value_type X4 = static_cast< value_type >( 25 ) * ( static_cast< value_type >( 443332067 ) - static_cast< value_type >( 31403016 ) * theta ) / static_cast< value_type >( 1880347072LL ) ;\n        const value_type X5 = static_cast< value_type >( 32805 ) * ( static_cast< value_type >( 23143187 ) - static_cast< value_type >( 3489224 ) * theta ) / static_cast< value_type >( 199316789632LL );\n        const value_type X6 = static_cast< value_type >( 55 ) * ( static_cast< value_type >( 29972135 ) - static_cast< value_type >( 7076736 ) * theta ) / static_cast< value_type >( 822651844 );\n        const value_type X7 = static_cast< value_type >( 10 ) * ( static_cast< value_type >( 7414447 ) - static_cast< value_type >( 829305 ) * theta ) / static_cast< value_type >( 29380423 );\n\n        const value_type theta_m_1 = theta - static_cast< value_type >( 1 );\n        const value_type theta_sq = theta * theta;\n        const value_type A = theta_sq * ( static_cast< value_type >( 3 ) - static_cast< value_type >( 2 ) * theta );\n        const value_type B = theta_sq * theta_m_1;\n        const value_type C = theta_sq * theta_m_1 * theta_m_1;\n        const value_type D = theta * theta_m_1 * theta_m_1;\n\n        const value_type b1_theta = A * b1 - C * X1 + D;\n        const value_type b3_theta = A * b3 + C * X3;\n        const value_type b4_theta = A * b4 - C * X4;\n        const value_type b5_theta = A * b5 + C * X5;\n        const value_type b6_theta = A * b6 - C * X6;\n        const value_type b7_theta = B + C * X7;\n\n        // const state_type &k1 = *m_old_deriv;\n        // const state_type &k3 = dopri5().m_k3;\n        // const state_type &k4 = dopri5().m_k4;\n        // const state_type &k5 = dopri5().m_k5;\n        // const state_type &k6 = dopri5().m_k6;\n        // const state_type &k7 = *m_current_deriv;\n\n        stepper_base_type::m_algebra.for_each8( x , x_old , deriv_old , m_k3.m_v , m_k4.m_v , m_k5.m_v , m_k6.m_v , deriv_new ,\n                typename operations_type::template scale_sum7< value_type , time_type , time_type , time_type , time_type , time_type , time_type >( 1.0 , dt * b1_theta , dt * b3_theta , dt * b4_theta , dt * b5_theta , dt * b6_theta , dt * b7_theta ) );\n    }\n\n\n    template< class StateIn >\n    void adjust_size( const StateIn &x )\n    {\n        resize_k_x_tmp_impl( x );\n        resize_dxdt_tmp_impl( x );\n        stepper_base_type::adjust_size( x );\n    }\n    \n\nprivate:\n\n    template< class StateIn >\n    bool resize_k_x_tmp_impl( const StateIn &x )\n    {\n        bool resized = false;\n        resized |= adjust_size_by_resizeability( m_x_tmp , x , typename is_resizeable<state_type>::type() );\n        resized |= adjust_size_by_resizeability( m_k2 , x , typename is_resizeable<deriv_type>::type() );\n        resized |= adjust_size_by_resizeability( m_k3 , x , typename is_resizeable<deriv_type>::type() );\n        resized |= adjust_size_by_resizeability( m_k4 , x , typename is_resizeable<deriv_type>::type() );\n        resized |= adjust_size_by_resizeability( m_k5 , x , typename is_resizeable<deriv_type>::type() );\n        resized |= adjust_size_by_resizeability( m_k6 , x , typename is_resizeable<deriv_type>::type() );\n        return resized;\n    }\n\n    template< class StateIn >\n    bool resize_dxdt_tmp_impl( const StateIn &x )\n    {\n        return adjust_size_by_resizeability( m_dxdt_tmp , x , typename is_resizeable<deriv_type>::type() );\n    }\n        \n\n\n    wrapped_state_type m_x_tmp;\n    wrapped_deriv_type m_k2 , m_k3 , m_k4 , m_k5 , m_k6 ;\n    wrapped_deriv_type m_dxdt_tmp;\n    resizer_type m_k_x_tmp_resizer;\n    resizer_type m_dxdt_tmp_resizer;\n};\n\n\n\n/************* DOXYGEN ************/\n/**\n * \\class runge_kutta_dopri5\n * \\brief The Runge-Kutta Dormand-Prince 5 method.\n *\n * The Runge-Kutta Dormand-Prince 5 method is a very popular method for solving ODEs, see\n * <a href=\"\"></a>.\n * The method is explicit and fulfills the Error Stepper concept. Step size control\n * is provided but continuous output is available which make this method favourable for many applications. \n * \n * This class derives from explicit_error_stepper_fsal_base and inherits its interface via CRTP (current recurring\n * template pattern). The method possesses the FSAL (first-same-as-last) property. See\n * explicit_error_stepper_fsal_base for more details.\n *\n * \\tparam State The state type.\n * \\tparam Value The value type.\n * \\tparam Deriv The type representing the time derivative of the state.\n * \\tparam Time The time representing the independent variable - the time.\n * \\tparam Algebra The algebra type.\n * \\tparam Operations The operations type.\n * \\tparam Resizer The resizer policy type.\n */\n\n\n    /**\n     * \\fn runge_kutta_dopri5::runge_kutta_dopri5( const algebra_type &algebra )\n     * \\brief Constructs the runge_kutta_dopri5 class. This constructor can be used as a default\n     * constructor if the algebra has a default constructor.\n     * \\param algebra A copy of algebra is made and stored inside explicit_stepper_base.\n     */\n\n    /**\n     * \\fn runge_kutta_dopri5::do_step_impl( System system , const StateIn &in , const DerivIn &dxdt_in , time_type t , StateOut &out , DerivOut &dxdt_out , time_type dt )\n     * \\brief This method performs one step. The derivative `dxdt_in` of `in` at the time `t` is passed to the\n     * method. The result is updated out-of-place, hence the input is in `in` and the output in `out`. Furthermore,\n     * the derivative is update out-of-place, hence the input is assumed to be in `dxdt_in` and the output in\n     * `dxdt_out`. \n     * Access to this step functionality is provided by explicit_error_stepper_fsal_base and \n     * `do_step_impl` should not be called directly.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param in The state of the ODE which should be solved. in is not modified in this method\n     * \\param dxdt_in The derivative of x at t. dxdt_in is not modified by this method\n     * \\param t The value of the time, at which the step should be performed.\n     * \\param out The result of the step is written in out.\n     * \\param dxdt_out The result of the new derivative at time t+dt.\n     * \\param dt The step size.\n     */\n\n    /**\n     * \\fn runge_kutta_dopri5::do_step_impl( System system , const StateIn &in , const DerivIn &dxdt_in , time_type t , StateOut &out , DerivOut &dxdt_out , time_type dt , Err &xerr )\n     * \\brief This method performs one step. The derivative `dxdt_in` of `in` at the time `t` is passed to the\n     * method. The result is updated out-of-place, hence the input is in `in` and the output in `out`. Furthermore,\n     * the derivative is update out-of-place, hence the input is assumed to be in `dxdt_in` and the output in\n     * `dxdt_out`. \n     * Access to this step functionality is provided by explicit_error_stepper_fsal_base and \n     * `do_step_impl` should not be called directly.\n     * An estimation of the error is calculated.\n     *\n     * \\param system The system function to solve, hence the r.h.s. of the ODE. It must fulfill the\n     *               Simple System concept.\n     * \\param in The state of the ODE which should be solved. in is not modified in this method\n     * \\param dxdt_in The derivative of x at t. dxdt_in is not modified by this method\n     * \\param t The value of the time, at which the step should be performed.\n     * \\param out The result of the step is written in out.\n     * \\param dxdt_out The result of the new derivative at time t+dt.\n     * \\param dt The step size.\n     * \\param xerr An estimation of the error.\n     */\n\n    /**\n     * \\fn runge_kutta_dopri5::calc_state( time_type t , StateOut &x , const StateIn1 &x_old , const DerivIn1 &deriv_old , time_type t_old , const StateIn2 &  , const DerivIn2 &deriv_new , time_type t_new ) const\n     * \\brief This method is used for continuous output and it calculates the state `x` at a time `t` from the \n     * knowledge of two states `old_state` and `current_state` at time points `t_old` and `t_new`. It also uses\n     * internal variables to calculate the result. Hence this method must be called after two successful `do_step`\n     * calls.\n     */\n\n    /**\n     * \\fn runge_kutta_dopri5::adjust_size( const StateIn &x )\n     * \\brief Adjust the size of all temporaries in the stepper manually.\n     * \\param x A state from which the size of the temporaries to be resized is deduced.\n     */\n\n} // odeint\n} // numeric\n} // boost\n\n\n#endif // BOOST_NUMERIC_ODEINT_STEPPER_RUNGE_KUTTA_DOPRI5_HPP_INCLUDED\n", "meta": {"hexsha": "a6218071d50974a11244fd140976c1682f8fc417", "size": 21453, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Externals/Boost/boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp", "max_stars_repo_name": "MINATILO/packing-generation", "max_stars_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2015-08-23T12:05:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:39:56.000Z", "max_issues_repo_path": "Externals/Boost/boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp", "max_issues_repo_name": "MINATILO/packing-generation", "max_issues_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-07-20T17:57:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T10:31:50.000Z", "max_forks_repo_path": "Externals/Boost/boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp", "max_forks_repo_name": "MINATILO/packing-generation", "max_forks_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2015-10-14T02:43:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T12:51:03.000Z", "avg_line_length": 53.2332506203, "max_line_length": 253, "alphanum_fraction": 0.6707686571, "num_tokens": 6039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.4081697388895816}}
{"text": "#ifndef CANNON_ML_LLOYD_H\n#define CANNON_ML_LLOYD_H \n\n/*!\n * \\file cannon/ml/lloyd.hpp\n * \\brief File containing functions relating to Lloyd's algorithm for Voronoi\n * relaxation.\n */\n\n#include <Eigen/Dense>\n\nusing namespace Eigen;\n\nnamespace cannon {\n  namespace ml {\n\n    /*!\n     * \\brief Enum class representing the different ways that the centroid\n     * integral used by Lloyd's algorithm can be numerically approximated.\n     */\n    enum class LloydSamplingStrategy {\n      Grid,\n      Uniform,\n    };\n\n    /*!\n     * \\brief Function to compute a single iteration of the classic Lloyd's\n     * algorithm in place within the specified bounds.\n     *\n     * \\param pts The current points making up the Voronoi diagram.\n     * \\param strat Sampling strategy to use for approximating centroid\n     * \\param x_low X axis lower bound\n     * \\param x_high X axis upper bound\n     * \\param y_low Y axis lower bound\n     * \\param y_high Y axis upper bound\n     */\n    void do_lloyd_iteration(\n        Matrix2Xd &pts,\n        LloydSamplingStrategy strat = LloydSamplingStrategy::Grid,\n        double x_low = -1.0, double x_high = 1.0, double y_low = -1.0,\n        double y_high = 1.0);\n\n    /*!\n     * \\brief Function to compute a single iteration of Lloyd's\n     * algorithm with respect to the input weighting function in place within\n     * the specified bounds.\n     *\n     * \\param pts The current points making up the Voronoi diagram.\n     * \\param f The weighting function to use. Should be everywhere positive.\n     * \\param strat Sampling strategy to use for approximating centroid\n     * \\param x_low X axis lower bound\n     * \\param x_high X axis upper bound\n     * \\param y_low Y axis lower bound\n     * \\param y_high Y axis upper bound\n     */\n    void do_lloyd_iteration(\n        Matrix2Xd &pts, std::function<double(const Vector2d&)> f,\n        LloydSamplingStrategy strat = LloydSamplingStrategy::Grid,\n        double x_low = -1.0, double x_high = 1.0, double y_low = -1.0,\n        double y_high = 1.0);\n  }\n}\n\n#endif /* ifndef CANNON_ML_LLOYD_H */\n", "meta": {"hexsha": "aade22db820c2d5e19b25f4ed55bea6372d02b11", "size": 2062, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/ml/lloyd.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/ml/lloyd.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/ml/lloyd.hpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7230769231, "max_line_length": 77, "alphanum_fraction": 0.6702230844, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.6757646140788307, "lm_q1q2_score": 0.40811576254774284}}
{"text": "//\n// $Id: base.hpp 7297 2015-03-12 05:30:33Z paragmallick $\n//\n//\n// Original author: Witold Wolski <wewolski@gmail.com>\n//\n// Copyright : ETH Zurich\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \n// you may not use this file except in compliance with the License. \n// You may obtain a copy of the License at \n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software \n// distributed under the License is distributed on an \"AS IS\" BASIS, \n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n// See the License for the specific language governing permissions and \n// limitations under the License.\n//\n\n#ifndef BASE_H\n#define BASE_H\n\n#include <math.h>\n#include <algorithm>\n#include <vector>\n#include <functional>\n#include <numeric>\n#include <stdexcept>\n#include <limits>\n#include <iterator>\n#include <cmath>\n#include <string>\n#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_integral.hpp>\n#include \"pwiz/utility/findmf/base/base/utilities/base.hpp\"\n\nnamespace ralab\n{\n  namespace base\n  {\n    namespace base\n    {\n\n      /// generates the sequence from, from+/-1, ..., to (identical to from:to).\n      template<typename TReal>\n      void seq\n      (\n          TReal from, //!<[in] the starting  value of the sequence\n          TReal to, //!<[in] the end value of the sequence\n          std::vector<TReal> &result //!<[out] result sequence\n          )\n      {\n        result.clear();\n        typedef typename std::vector<TReal>::size_type size_type;\n        if( from <= to )\n        {\n          size_type length = static_cast<size_type>(to - from) + 1;\n          result.resize(length);\n          std::generate(result.begin() , result.end() , utilities::SeqPlus<TReal>(from));\n        }\n        else\n        {\n          size_type length = static_cast<size_type>(from - to) + 1 ;\n          result.resize(length);\n          std::generate(result.begin() , result.end() , utilities::SeqMinus<TReal>(from));\n        }\n      }\n\n      /// generates sequence: from, from+by, from + 2*by, ..., up to a sequence value less than, or equal than to.\n      /// Specifying to < from and by of positive sign is an error.\n      template<typename TReal>\n      void seq(\n          TReal from,//!<[in] the starting value of the sequence\n          TReal to,//!<[in] the end value of the sequence\n          TReal by, //!<[in] number: increment of the sequence\n          std::vector<TReal> &result //!<[out] result sequence\n          )\n      {\n        result.clear();\n        typedef typename std::vector<TReal>::size_type size_type;\n        size_type size = static_cast<size_type>(  (to - from)  / by ) + 1u ;\n        result.reserve( size );\n\n        if(from <= to)\n        {\n          if(!(by > 0)){\n            throw std::logic_error(std::string( \"by > 0\" ));\n          }\n          for(; from <= to; from += by)\n          {\n            result.push_back(from);\n          }\n        }\n        else\n        {\n          if(! (by < 0) ){\n            throw std::logic_error(std::string( \"by < 0\" ));\n          }\n          for(; from >= to; from += by)\n          {\n            result.push_back(from);\n          }\n        }\n      }\n\n      /// generates sequence: from, to of length\n      /// calls seq with \\$[ by = ( ( to - from ) / (  length  - 1. ) ) \\$]\n      template<typename TReal>\n      void seq_length(\n          TReal from,//!<[in] the starting value of the sequence\n          TReal to,//!<[in] the end value of the sequence\n          unsigned int length, //!<[in] length of sequence\n          std::vector<TReal> &result //!<[out] result sequence\n          )\n      {\n        TReal by = ( ( to - from ) / ( static_cast<TReal>( length ) - 1. ) );\n        seq(from, to, by, result);\n\n        //this is required because of machine precision...\n        // sometimes by does not add's up to precisely _to_ nad\n        if(result.size() < length)\n        {\n          result.push_back(result[result.size()-1] + by );\n        }\n        else\n        {\n          result.resize(length);\n        }\n      }\n\n      /// generates the sequence [1, 2, ..., length(ref)]\n      /// (as if argument along.with had been specified),\n      /// unless the argument is numeric of length 1 when it is interpreted as\n      ///  1:from (even for seq(0) for compatibility with S).\n\n      template< typename T1 , typename T2 >\n      void seq\n      (\n          std::vector<T1> & ref, //!<[in] take the length from the length of this argument.\n          std::vector<T2> & res //!<[out] result sequence\n          )\n      {\n        T2 t(1);\n        res.assign(ref.size() , t );\n        std::partial_sum( res.begin() , res.end() , res.begin() );\n      }\n\n      /// Generates Sequence 1,2,3,....length .\n      /// Generates 1, 2, ..., length unless length.out = 0, when it generates\n      /// integer(0).\n\n      template<typename TSize, typename TReal>\n      typename boost::enable_if<boost::is_integral<TSize>, void>::type\n      seq(\n          TSize length, //!< [in] length of sequence\n          std::vector<TReal> &res //!< [out] result sequence\n          )\n      {\n        TReal t(1);\n        res.assign(length , t );\n        std::partial_sum(res.begin(),res.end(),res.begin());\n      }\n\n\n      /// MEAN Trimmed arithmetic mean.\n\n      /// ## Default S3 method:\n      /// mean(x, trim = 0, na.rm = FALSE, ...)\n\n      /// Arguments\n      /// x \tAn R object. Currently there are methods for numeric data frames, numeric vectors and dates. A complex vector is allowed for trim = 0, only.\n      /// trim \tthe fraction (0 to 0.5) of observations to be trimmed from each end of x before the mean is computed. Values outside that range are taken as the nearest endpoint.\n      /// na.rm \ta logical value indicating whether NA values should be stripped before the computation proceeds.\n      /// ... \tfurther arguments passed to or from other methods.\n\n      /// Value\n      /// For a data frame, a named vector with the appropriate method being applied column by column.\n      /// If trim is zero (the default), the arithmetic mean of the values in x is computed, as a numeric or complex vector of length one. If x is not logical (coerced to numeric), integer, numeric or complex, NA is returned, with a warning.\n      /// If trim is non-zero, a symmetrically trimmed mean is computed with a fraction of trim observations deleted from each end before the mean is computed.\n\n\n      template < typename InputIterator >\n      inline\n      typename std::iterator_traits<InputIterator>::value_type\n      mean(\n          InputIterator begin, //!< [in]\n          InputIterator end //!< [in]\n          )\n      {\n        typedef typename std::iterator_traits<InputIterator>::value_type TReal;\n        TReal size = static_cast<TReal>(std::distance(begin,end));\n        TReal sum = std::accumulate(begin , end, 0. );\n        return(sum/size);\n      }\n\n      /// mean\n      template <typename TReal>\n      inline TReal mean(const std::vector<TReal> & x )\n      {\n        TReal size = static_cast<TReal>(x.size());\n        TReal sum = std::accumulate(x.begin() , x.end(), 0. );\n        return ( sum / size ) ;\n      }\n\n      /// mean\n      template <typename TReal>\n      TReal mean(\n          const std::vector<TReal> & x, //!< [in]\n          TReal trim  //!< [in] trim 0 - 0.5\n          )\n      {\n        if(trim >= 0.5)\n        {\n          trim = 0.4999999;\n        }\n        TReal size = static_cast<TReal>(x.size());\n        std::vector<TReal> wc(x); //working copy\n        std::sort(wc.begin(),wc.end());\n        size_t nrelemstrim = static_cast<size_t>(round( size * trim )) ;\n        size_t nrelems = std::distance(wc.begin() + nrelemstrim, wc.end() - nrelemstrim );\n        TReal sum = std::accumulate(wc.begin() + nrelemstrim , wc.end() - nrelemstrim, 0. );\n        return ( sum / static_cast<TReal>( nrelems ) ); //static_cast will be required with boost::math::round\n      }\n\n      /// computes the mean\n      template<class Iter_T>\n      typename std::iterator_traits<Iter_T>::value_type geometricMean(Iter_T first, Iter_T last)\n      {\n        typedef typename std::iterator_traits<Iter_T>::value_type TReal;\n        size_t cnt = distance(first, last);\n        std::vector<TReal> copyOfInput(first, last);\n\n        // ln(x)\n        typename std::vector<TReal>::iterator inputIt;\n\n        for(inputIt = copyOfInput.begin(); inputIt != copyOfInput.end() ; ++inputIt)\n        {\n          *inputIt = std::log(*inputIt);\n        }\n\n        // sum(ln(x))\n        TReal sum( std::accumulate(copyOfInput.begin(), copyOfInput.end(), TReal() ));\n\n        // e^(sum(ln(x))/N)\n        TReal geomean( std::exp(sum / cnt) );\n        return geomean;\n      }\n\n\n      /// Range of Values\n      /// range returns a std::pair containing minimum and maximum of all the given values.\n      template<typename TReal>\n      void Range(\n          const std::vector<TReal> & values, //!< [in] data\n          std::pair<TReal,TReal> & range //!< [out] range\n          )\n      {\n        TReal min = * std::min_element(values.begin(),values.end());\n        TReal max = * std::max_element(values.begin(),values.end());\n        range.first = min;\n        range.second = max;\n      }\n\n      ///  maximum of 3 numbers\n      template<typename T>\n      inline double max3(T a, T b, T c)\n      {\n        T max;\n        if(a>b)\n          max=a;\n        else\n          max=b;\n        if(max<c)\n          max=c;\n        return(max);\n      }\n\n      /// log base 2\n      template<typename TReal>\n      inline TReal log2(TReal test)\n      {\n        if(test==0)\n          return(0);\n        else\n          return( log10( test ) / log10( static_cast<TReal>(2.) ));\n      }\n\n    }//namespace BASE ends here\n  }//namespace base ends here\n}//namespace ralab ends here\n\n#endif // BASE_H\n", "meta": {"hexsha": "9c019cfcd3d5bc117de7154e0c797b06ee1c6b44", "size": 9811, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/findmf/base/base/base.hpp", "max_stars_repo_name": "edyp-lab/pwiz-mzdb", "max_stars_repo_head_hexsha": "d13ce17f4061596c7e3daf9cf5671167b5996831", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T08:33:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-12T06:14:54.000Z", "max_issues_repo_path": "pwiz/utility/findmf/base/base/base.hpp", "max_issues_repo_name": "shze/pwizard-deb", "max_issues_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "pwiz/utility/findmf/base/base/base.hpp", "max_forks_repo_name": "shze/pwizard-deb", "max_forks_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-02-03T09:41:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T18:42:36.000Z", "avg_line_length": 33.2576271186, "max_line_length": 241, "alphanum_fraction": 0.5711955968, "num_tokens": 2420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.640635861701035, "lm_q1q2_score": 0.408104763122831}}
{"text": "// Implementing the class that is defined in the header file: BarrierOption.hpp\r\n//\r\n// (c) Sudhansh Dua\r\n\r\n\r\n\r\n#include \"BarrierOption.hpp\"\r\n#include <string>\r\n#include <boost/math/distributions.hpp>\r\n#include <cmath>\r\n\r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n\r\ndouble BarrierOption::DownAndOutCallBarrier() const\r\n{\r\n\treturn ::DownAndOutCallBarrier(S, H, K, cr, T, r, sig, b, type, InOrOut);\r\n}\r\n\r\ndouble BarrierOption::DownAndOutPutBarrier() const\r\n{\r\n\treturn ::DownAndOutPutBarrier(S, H, K, cr, T, r, sig, b, type, InOrOut);\r\n}\r\n\r\ndouble BarrierOption::DownAndInCallBarrier() const\r\n{\r\n\treturn ::DownAndInCallBarrier(S, H, K, cr, T, r, sig, b, type, InOrOut);\r\n}\r\n\r\ndouble BarrierOption::DownAndInPutBarrier() const\r\n{\r\n\treturn ::DownAndInPutBarrier(S, H, K, cr, T, r, sig, b, type, InOrOut);\r\n}\r\n\r\ndouble BarrierOption::UpAndOutCallBarrier() const\r\n{\r\n\treturn ::UpAndOutCallBarrier(S, H, K, cr, T, r, sig, b, type, InOrOut);\r\n}\r\n\r\ndouble BarrierOption::UpAndOutPutBarrier() const\r\n{\r\n\treturn ::UpAndOutPutBarrier(S, H, K, cr, T, r, sig, b, type, InOrOut);\r\n}\r\n\r\ndouble BarrierOption::UpAndInCallBarrier() const\r\n{\r\n\treturn ::UpAndInCallBarrier(S, H, K, cr, T, r, sig, b, type, InOrOut);\r\n}\r\n\r\ndouble BarrierOption::UpAndInPutBarrier() const\r\n{\r\n\treturn ::UpAndInPutBarrier(S, H, K, cr, T, r, sig, b, type, InOrOut);\r\n}\r\n\r\n\r\nvoid BarrierOption::init()\t\t// Initialising all the default values\r\n{\r\n\t//\tDefault values\r\n\tT = 1;\r\n\tH = 105;\t\t\t\r\n\tcr = 3;\r\n\tr = 0.08;\r\n\tsig = 0.25;\r\n\tK = 100;\r\n\tS = 100;\t\t\t//\tDefault stock price \r\n\tb = r;\t\t\t\t//\tBlack - Scholes(1973) stock option model: b = r (i.e. non-dividend paying stock)\r\n\r\n\ttype = \"C\";\t\t\t//\tCall option as default\r\n\tInOrOut = \"In\";\t\t\t//\tIn Barrier as default\r\n}\r\n\r\nvoid BarrierOption::copy(const BarrierOption& option)\r\n{\r\n\tH = option.H;\r\n\tT = option.T;\r\n\tInOrOut = option.InOrOut;\r\n\tcr = option.cr;\r\n\tr = option.r;\r\n\tsig = option.sig;\r\n\tK = option.K;\r\n\tb = option.b;\r\n\ttype = option.type;\r\n\tS = option.S;\r\n}\r\n\r\n\r\n//\tConstructors and destructor\r\n//\tDefault Constructor\r\nBarrierOption::BarrierOption() : Option()\r\n{\r\n\tinit();\r\n}\r\n\r\n//\tCopy constructor\r\nBarrierOption::BarrierOption(const BarrierOption& option) : Option(option)\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nBarrierOption::BarrierOption(const double& S1, const double& H1, const double& K1, const double& cr1, const double& T1, const double& r1, const double& sig1, \r\n\tconst double& b1, const string type1, const string InOrOut1) : Option(), S(S1), H(H1), K(K1), cr(cr1), T(T1), r(r1), sig(sig1), b(b1), type(type1), InOrOut(InOrOut1) {}\r\n\r\n//\tDestructor\r\nBarrierOption::~BarrierOption() {}\r\n\r\n\r\n//\tAssignment Operator\r\nBarrierOption& BarrierOption::operator = (const BarrierOption& option)\r\n{\r\n\tif (this == &option)\r\n\t{\r\n\t\treturn *this;\t\t//\tSelf-assignment check!\r\n\t}\r\n\tOption::operator = (option);\r\n\tcopy(option);\r\n\treturn *this;\r\n}\r\n\r\n\r\n// Functions that calculate the option price\r\ndouble BarrierOption::Price() const\r\n{\r\n\tif (S >= H)\r\n\t{ \t\t\t\t\t\t\t// Down Barrier\r\n\r\n\t\tif (InOrOut == \"In\")\t\t\t\t\t\t// Down and in barrier\r\n\t\t{ \r\n\r\n\t\t\tif (type == \"C\")\r\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t// Down and in call barrier\r\n\t\t\t\treturn DownAndInCallBarrier();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t// Down and in put barrier\r\n\t\t\t\treturn DownAndInPutBarrier();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\t\t\t\t\t\t\t\t// Down and out barrier\r\n\t\t\tif (type == \"C\")\r\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t// Down and out call barrier\r\n\t\t\t\treturn DownAndOutCallBarrier();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t// Down and out put barrier\r\n\t\t\t\treturn DownAndOutPutBarrier();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\telse\r\n\t{\t\t\t\t\t\t\t// Up Barrier\r\n\r\n\t\tif (InOrOut == \"In\")\r\n\t\t{\t\t\t\t\t\t\t\t// Up and in barrier\r\n\r\n\t\t\tif (type == \"C\")\r\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t// Up and in call barrier\r\n\t\t\t\treturn UpAndInCallBarrier();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t// Up and in put barrier\r\n\t\t\t\treturn UpAndInPutBarrier();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\t\t\t\t\t\t\t\t// Up and out barrier\r\n\t\t\tif (type == \"C\")\r\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t// Up and out call barrier\r\n\t\t\t\treturn UpAndOutCallBarrier();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\t\t\t\t\t\t\t\t\t\t\t\t// Up and out put barrier\r\n\t\t\t\treturn UpAndOutPutBarrier();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n// Modifier functions\r\nvoid BarrierOption::toggle()\t\t\t//\tChange the option type\r\n{\r\n\ttype = ((type == \"C\") ? \"P\" : \"C\");\r\n}\r\n\r\n\r\n// Global Functions\r\n\r\ndouble DownAndOutCallBarrier(const double S, const double H, const double K, const double cr, const double T, const double r, const double sig, const double b, const string type, const string InOrOut)\r\n{\r\n\tdouble ita = 1;\r\n\tdouble phi = 1;\r\n\r\n\tdouble mu = (b - (sig * sig * 0.5)) / (sig * sig);\r\n\tdouble psi = sqrt((mu * mu) + (2 * r / (sig * sig)));\r\n\tdouble x1 = (log(S / K) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble x2 = (log(S / H) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y1 = (log(H * H / (S * K)) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y2 = (log(H / S)) / (sig * sqrt(T)) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble z = (log(H / S) / (sig * sqrt(T))) + (psi * sig * sqrt(T));\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\tdouble A = (phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x1)) - (phi * K * exp(-r * T) * cdf(standard_normal, phi * (x1 - (sig * sqrt(T)))));\r\n\tdouble B = (phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x2)) - (phi * K * exp(-r * T) * cdf(standard_normal, phi * (x2 - (sig * sqrt(T)))));\r\n\tdouble C = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y1)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y1 - (sig * sqrt(T))))));\r\n\tdouble D = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y2)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T))))));\r\n\tdouble E = (cr * exp(-r * T) * ((cdf(standard_normal, ita * (x2 - (sig * sqrt(T))))) - (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T)))))));\r\n\tdouble F = (cr * ((pow(H / S, mu + psi) * cdf(standard_normal, ita * z)) + (pow(H / S, mu - psi) * cdf(standard_normal, ita * (z - (2 * psi * sig * sqrt(T)))))));\r\n\r\n\tif (K > H)\r\n\t{\r\n\t\treturn A - C + F;\r\n\t}\r\n\telse\r\n\t\treturn B - D + F;\r\n}\r\n\r\n\r\ndouble DownAndOutPutBarrier(const double S, const double H, const double K, const double cr, const double T, const double r, const double sig, const double b, const string type, const string InOrOut)\r\n{\r\n\tdouble ita = 1;\r\n\tdouble phi = -1;\r\n\r\n\tdouble mu = (b - (sig * sig * 0.5)) / (sig * sig);\r\n\tdouble psi = sqrt((mu * mu) + (2 * r / (sig * sig)));\r\n\tdouble x1 = (log(S / K) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble x2 = (log(S / H) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y1 = (log(H * H / (S * K)) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y2 = (log(H / S)) / (sig * sqrt(T)) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble z = (log(H / S) / (sig * sqrt(T))) + (psi * sig * sqrt(T));\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\tdouble A = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x1) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x1 - (sig * sqrt(T))));\r\n\tdouble B = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x2) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x2 - (sig * sqrt(T))));\r\n\tdouble C = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y1)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y1 - (sig * sqrt(T))))));\r\n\tdouble D = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y2)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T))))));\r\n\tdouble E = (cr * exp(-r * T) * ((cdf(standard_normal, ita * (x2 - (sig * sqrt(T))))) - (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T)))))));\r\n\tdouble F = (cr * ((pow(H / S, mu + psi) * cdf(standard_normal, ita * z)) + (pow(H / S, mu - psi) * cdf(standard_normal, ita * (z - (2 * psi * sig * sqrt(T)))))));\r\n\r\n\tif (K > H)\r\n\t{\r\n\t\treturn A - B + C - D + F;\r\n\t}\r\n\telse\r\n\t\treturn F;\r\n}\r\n\r\n\r\ndouble DownAndInCallBarrier(const double S, const double H, const double K, const double cr, const double T, const double r, const double sig, const double b, const string type, const string InOrOut)\r\n{\r\n\tdouble ita = 1;\r\n\tdouble phi = 1;\r\n\r\n\tdouble mu = (b - (sig * sig * 0.5)) / (sig * sig);\r\n\tdouble psi = sqrt((mu * mu) + (2 * r / (sig * sig)));\r\n\tdouble x1 = (log(S / K) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble x2 = (log(S / H) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y1 = (log(H * H / (S * K)) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y2 = (log(H / S)) / (sig * sqrt(T)) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble z = (log(H / S) / (sig * sqrt(T))) + (psi * sig * sqrt(T));\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\tdouble A = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x1) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x1 - (sig * sqrt(T))));\r\n\tdouble B = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x2) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x2 - (sig * sqrt(T))));\r\n\tdouble C = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y1)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y1 - (sig * sqrt(T))))));\r\n\tdouble D = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y2)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T))))));\r\n\tdouble E = (cr * exp(-r * T) * ((cdf(standard_normal, ita * (x2 - (sig * sqrt(T))))) - (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T)))))));\r\n\tdouble F = (cr * ((pow(H / S, mu + psi) * cdf(standard_normal, ita * z)) + (pow(H / S, mu - psi) * cdf(standard_normal, ita * (z - (2 * psi * sig * sqrt(T)))))));\r\n\r\n\tif (K > H)\r\n\t{\r\n\t\treturn C + E;\r\n\t}\r\n\telse\r\n\t\treturn A - B + D + E;\r\n\r\n}\r\n\r\n\r\ndouble DownAndInPutBarrier(const double S, const double H, const double K, const double cr, const double T, const double r, const double sig, const double b, const string type, const string InOrOut)\r\n{\r\n\tdouble ita = 1;\r\n\tdouble phi = -1;\r\n\r\n\tdouble mu = (b - (sig * sig * 0.5)) / (sig * sig);\r\n\tdouble psi = sqrt((mu * mu) + (2 * r / (sig * sig)));\r\n\tdouble x1 = (log(S / K) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble x2 = (log(S / H) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y1 = (log(H * H / (S * K)) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y2 = (log(H / S)) / (sig * sqrt(T)) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble z = (log(H / S) / (sig * sqrt(T))) + (psi * sig * sqrt(T));\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\tdouble A = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x1) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x1 - (sig * sqrt(T))));\r\n\tdouble B = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x2) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x2 - (sig * sqrt(T))));\r\n\tdouble C = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y1)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y1 - (sig * sqrt(T))))));\r\n\tdouble D = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y2)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T))))));\r\n\tdouble E = (cr * exp(-r * T) * ((cdf(standard_normal, ita * (x2 - (sig * sqrt(T))))) - (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T)))))));\r\n\tdouble F = (cr * ((pow(H / S, mu + psi) * cdf(standard_normal, ita * z)) + (pow(H / S, mu - psi) * cdf(standard_normal, ita * (z - (2 * psi * sig * sqrt(T)))))));\r\n\r\n\tif (K > H)\r\n\t{\r\n\t\treturn B - C + D + E;\r\n\t}\r\n\telse\r\n\t\treturn A + E;\r\n}\r\n\r\n\r\ndouble UpAndOutCallBarrier(const double S, const double H, const double K, const double cr, const double T, const double r, const double sig, const double b, const string type, const string InOrOut)\r\n{\r\n\tdouble ita = -1;\r\n\tdouble phi = 1;\r\n\r\n\tdouble mu = (b - (sig * sig * 0.5)) / (sig * sig);\r\n\tdouble psi = sqrt((mu * mu) + (2 * r / (sig * sig)));\r\n\tdouble x1 = (log(S / K) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble x2 = (log(S / H) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y1 = (log(H * H / (S * K)) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y2 = (log(H / S)) / (sig * sqrt(T)) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble z = (log(H / S) / (sig * sqrt(T))) + (psi * sig * sqrt(T));\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\tdouble A = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x1) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x1 - (sig * sqrt(T))));\r\n\tdouble B = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x2) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x2 - (sig * sqrt(T))));\r\n\tdouble C = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y1)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y1 - (sig * sqrt(T))))));\r\n\tdouble D = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y2)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T))))));\r\n\tdouble E = (cr * exp(-r * T) * ((cdf(standard_normal, ita * (x2 - (sig * sqrt(T))))) - (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T)))))));\r\n\tdouble F = (cr * ((pow(H / S, mu + psi) * cdf(standard_normal, ita * z)) + (pow(H / S, mu - psi) * cdf(standard_normal, ita * (z - (2 * psi * sig * sqrt(T)))))));\r\n\r\n\tif (K > H)\r\n\t{\r\n\t\treturn F;\r\n\t}\r\n\telse\r\n\t\treturn A - B + C - D + F;\r\n\r\n}\r\n\r\n\r\ndouble UpAndOutPutBarrier(const double S, const double H, const double K, const double cr, const double T, const double r, const double sig, const double b, const string type, const string InOrOut)\r\n{\r\n\tdouble ita = -1;\r\n\tdouble phi = -1;\r\n\r\n\tdouble mu = (b - (sig * sig * 0.5)) / (sig * sig);\r\n\tdouble psi = sqrt((mu * mu) + (2 * r / (sig * sig)));\r\n\tdouble x1 = (log(S / K) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble x2 = (log(S / H) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y1 = (log(H * H / (S * K)) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y2 = (log(H / S)) / (sig * sqrt(T)) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble z = (log(H / S) / (sig * sqrt(T))) + (psi * sig * sqrt(T));\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\tdouble A = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x1) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x1 - (sig * sqrt(T))));\r\n\tdouble B = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x2) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x2 - (sig * sqrt(T))));\r\n\tdouble C = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y1)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y1 - (sig * sqrt(T))))));\r\n\tdouble D = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y2)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T))))));\r\n\tdouble E = (cr * exp(-r * T) * ((cdf(standard_normal, ita * (x2 - (sig * sqrt(T))))) - (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T)))))));\r\n\tdouble F = (cr * ((pow(H / S, mu + psi) * cdf(standard_normal, ita * z)) + (pow(H / S, mu - psi) * cdf(standard_normal, ita * (z - (2 * psi * sig * sqrt(T)))))));\r\n\r\n\tif (K > H)\r\n\t{\r\n\t\treturn B - D + F;\r\n\t}\r\n\telse\r\n\t\treturn A - C + F;\r\n}\r\n\r\n\r\ndouble UpAndInCallBarrier(const double S, const double H, const double K, const double cr, const double T, const double r, const double sig, const double b, const string type, const string InOrOut)\r\n{\r\n\tdouble ita = -1;\r\n\tdouble phi = 1;\r\n\r\n\tdouble mu = (b - (sig * sig * 0.5)) / (sig * sig);\r\n\tdouble psi = sqrt((mu * mu) + (2 * r / (sig * sig)));\r\n\tdouble x1 = (log(S / K) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble x2 = (log(S / H) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y1 = (log(H * H / (S * K)) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y2 = (log(H / S)) / (sig * sqrt(T)) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble z = (log(H / S) / (sig * sqrt(T))) + (psi * sig * sqrt(T));\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\tdouble A = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x1) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x1 - (sig * sqrt(T))));\r\n\tdouble B = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x2) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x2 - (sig * sqrt(T))));\r\n\tdouble C = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y1)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y1 - (sig * sqrt(T))))));\r\n\tdouble D = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y2)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T))))));\r\n\tdouble E = (cr * exp(-r * T) * ((cdf(standard_normal, ita * (x2 - (sig * sqrt(T))))) - (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T)))))));\r\n\tdouble F = (cr * ((pow(H / S, mu + psi) * cdf(standard_normal, ita * z)) + (pow(H / S, mu - psi) * cdf(standard_normal, ita * (z - (2 * psi * sig * sqrt(T)))))));\r\n\r\n\tif (K > H)\r\n\t{\r\n\t\treturn A + E;\r\n\t}\r\n\telse\r\n\t\treturn B - C + D + E;\r\n\r\n}\r\n\r\n\r\ndouble UpAndInPutBarrier(const double S, const double H, const double K, const double cr, const double T, const double r, const double sig, const double b, const string type, const string InOrOut)\r\n{\r\n\tdouble ita = -1;\r\n\tdouble phi = -1;\r\n\r\n\tdouble mu = (b - (sig * sig * 0.5)) / (sig * sig);\r\n\tdouble psi = sqrt((mu * mu) + (2 * r / (sig * sig)));\r\n\tdouble x1 = (log(S / K) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble x2 = (log(S / H) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y1 = (log(H * H / (S * K)) / (sig * sqrt(T))) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble y2 = (log(H / S)) / (sig * sqrt(T)) + ((1 + mu) * sig * sqrt(T));\r\n\tdouble z = (log(H / S) / (sig * sqrt(T))) + (psi * sig * sqrt(T));\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\tdouble A = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x1) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x1 - (sig * sqrt(T))));\r\n\tdouble B = phi * S * exp((b - r) * T) * cdf(standard_normal, phi * x2) - phi * K * exp(-r * T) * cdf(standard_normal, phi * (x2 - (sig * sqrt(T))));\r\n\tdouble C = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y1)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y1 - (sig * sqrt(T))))));\r\n\tdouble D = (phi * S * pow(H / S, 2 * (mu + 1)) * exp((b - r) * T) * cdf(standard_normal, ita * y2)) - (phi * K * exp(-r * T) * (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T))))));\r\n\tdouble E = (cr * exp(-r * T) * ((cdf(standard_normal, ita * (x2 - (sig * sqrt(T))))) - (pow(H / S, 2 * mu) * cdf(standard_normal, ita * (y2 - (sig * sqrt(T)))))));\r\n\tdouble F = (cr * ((pow(H / S, mu + psi) * cdf(standard_normal, ita * z)) + (pow(H / S, mu - psi) * cdf(standard_normal, ita * (z - (2 * psi * sig * sqrt(T)))))));\r\n\r\n\tif (K > H)\r\n\t{\r\n\t\treturn A - B + D + E;\r\n\t}\r\n\telse\r\n\t\treturn C + E;\r\n}\r\n\r\n", "meta": {"hexsha": "01430a9815c2334da208633d9a3618490a0b2537", "size": 19497, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BarrierOption.cpp", "max_stars_repo_name": "sudhanshdua/Option_Classes", "max_stars_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BarrierOption.cpp", "max_issues_repo_name": "sudhanshdua/Option_Classes", "max_issues_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BarrierOption.cpp", "max_forks_repo_name": "sudhanshdua/Option_Classes", "max_forks_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.8206896552, "max_line_length": 204, "alphanum_fraction": 0.5308509001, "num_tokens": 7032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4080588034836847}}
{"text": "#ifndef SKYLARK_INNER_HPP\n#define SKYLARK_INNER_HPP\n\n#include <boost/mpi.hpp>\n\nnamespace skylark { namespace base {\n\ntemplate<typename T>\ninline El::Base<T> Nrm2(const El::Matrix<T>& x) {\n    return El::Nrm2(x);\n}\n\ntemplate<typename T>\ninline El::Base<T> Nrm2(const El::DistMatrix<T>& x) {\n    return El::Nrm2(x);\n}\n\ntemplate<typename T>\ninline El::Base<T> Nrm2(const El::DistMatrix<T, El::VC, El::STAR>& x) {\n    boost::mpi::communicator comm(x.DistComm().comm, boost::mpi::comm_attach);\n    T local = El::Nrm2(x.LockedMatrix());\n    T snrm = boost::mpi::all_reduce(comm, local * local, std::plus<T>());\n    return sqrt(snrm);\n}\n\ntemplate<typename T>\ninline El::Base<T> Nrm2(const El::DistMatrix<T, El::VR, El::STAR>& x) {\n    boost::mpi::communicator comm(x.DistComm(), boost::mpi::comm_attach);\n    T local = El::Nrm2(x.LockedMatrix());\n    T snrm = boost::mpi::all_reduce(comm, local * local, std::plus<T>());\n    return sqrt(snrm);\n}\n\ntemplate<typename T>\ninline El::Base<T> Nrm2(const El::DistMatrix<T, El::STAR, El::STAR>& x) {\n    return El::Nrm2(x.LockedMatrix());\n}\n\ntemplate<typename T>\ninline void ColumnNrm2(const El::Matrix<T>& A,\n    El::Matrix<El::Base<T> >& N) {\n\n    N.Resize(A.Width(), 1);\n    T *n = N.Buffer();\n    const T *a = A.LockedBuffer();\n    for(El::Int j = 0; j < A.Width(); j++) {\n        n[j] = 0.0;\n        for(El::Int i = 0; i < A.Height(); i++)\n            n[j] += a[j * A.LDim() + i] * El::Conj(a[j * A.LDim() + i]);\n        n[j] = sqrt(n[j]);\n    }\n}\n\ntemplate<typename T>\ninline void ColumnNrm2(const El::DistMatrix<T, El::STAR, El::STAR>& A,\n    El::DistMatrix<El::Base<T>, El::STAR, El::STAR>& N) {\n    N.Resize(A.Width(), 1);\n    T *n = N.Buffer();\n    const T *a = A.LockedBuffer();\n    for(El::Int j = 0; j < A.Width(); j++) {\n        n[j] = 0.0;\n        for(El::Int i = 0; i < A.LocalHeight(); i++)\n            n[j] += a[j * A.LDim() + i] * El::Conj(a[j * A.LDim() + i]);\n        n[j] = sqrt(n[j]);\n    }\n}\n\ntemplate<typename T, El::Distribution U, El::Distribution V>\ninline void ColumnNrm2(const El::DistMatrix<T, U, V>& A,\n    El::DistMatrix<El::Base<T>, El::STAR, El::STAR>& N) {\n\n    std::vector<T> n(A.Width(), 1);\n    std::fill(n.begin(), n.end(), 0.0);\n    const El::Matrix<T> &Al = A.LockedMatrix();\n    const T *a = Al.LockedBuffer();\n    for(int j = 0; j < Al.Width(); j++)\n        for(int i = 0; i < Al.Height(); i++)\n            n[A.GlobalCol(j)] +=\n                a[j * Al.LDim() + i] * El::Conj(a[j * Al.LDim() + i]);\n\n    N.Resize(A.Width(), 1);\n    El::Zero(N);\n    boost::mpi::communicator comm(N.Grid().Comm().comm, boost::mpi::comm_attach);\n    boost::mpi::all_reduce(comm, n.data(), A.Width(), N.Buffer(), std::plus<T>());\n    for(int j = 0; j < A.Width(); j++)\n        N.Set(j, 0, sqrt(N.Get(j, 0)));\n}\n\ntemplate<typename T>\ninline void ColumnNrm2(const El::AbstractDistMatrix<T>& A,\n    El::DistMatrix<El::Base<T>, El::STAR, El::STAR>& N) {\n\n    N.Resize(A.Width(), 1);\n\n    if (A.Participating()) {\n        std::vector<T> n(A.Width(), 1);\n        std::fill(n.begin(), n.end(), 0.0);\n        const El::Matrix<T> &Al = A.LockedMatrix();\n        const T *a = Al.LockedBuffer();\n        for(El::Int j = 0; j < Al.Width(); j++)\n            for(El::Int i = 0; i < Al.Height(); i++)\n                n[A.GlobalCol(j)] +=\n                    a[j * Al.LDim() + i] * El::Conj(a[j * Al.LDim() + i]);\n\n\n        El::Zero(N);\n        El::mpi::AllReduce(n.data(), N.Buffer(), A.Width(), MPI_SUM,\n            A.DistComm());\n        for(El::Int j = 0; j < A.Width(); j++)\n            N.Set(j, 0, sqrt(N.Get(j, 0)));\n    }\n\n    El::mpi::Broadcast(N.Buffer(), A.Width(), A.Root(), A.CrossComm());\n}\n\n\ntemplate<typename T>\ninline void ColumnDot(const El::Matrix<T>& A, const El::Matrix<T>& B,\n    El::Matrix<T>& N) {\n\n    // TODO just assuming sizes are OK for now.\n\n    T *n = N.Buffer();\n    const T *a = A.LockedBuffer();\n    const T *b = B.LockedBuffer();\n    for(El::Int j = 0; j < A.Width(); j++) {\n        n[j] = 0.0;\n        for(El::Int i = 0; i < A.Height(); i++)\n            n[j] += a[j * A.LDim() + i] * El::Conj(b[j * B.LDim() + i]);\n    }\n}\n\ntemplate<typename T>\ninline void ColumnDot(const El::DistMatrix<T, El::STAR, El::STAR>& A,\n    const El::DistMatrix<T, El::STAR, El::STAR>& B,\n    El::DistMatrix<T, El::STAR, El::STAR>& N) {\n\n    // TODO just assuming sizes are OK for now.\n\n    T *n = N.Buffer();\n    const T *a = A.LockedBuffer();\n    const T *b = B.LockedBuffer();\n    for(El::Int j = 0; j < A.Width(); j++) {\n        n[j] = 0.0;\n        for(El::Int i = 0; i < A.LocalHeight(); i++)\n            n[j] += a[j * A.LDim() + i] * El::Conj(b[j * B.LDim() + i]);\n    }\n}\n\ntemplate<typename T, El::Distribution U, El::Distribution V>\ninline void ColumnDot(const El::DistMatrix<T, U, V>& A,\n    const El::DistMatrix<T, U, V>& B,\n    El::DistMatrix<T, El::STAR, El::STAR>& N) {\n\n    // TODO just assuming sizes are OK for now, and grid aligned.\n    std::vector<T> n(A.Width(), 1);\n    std::fill(n.begin(), n.end(), 0);\n    const El::Matrix<T> &Al = A.LockedMatrix();\n    const T *a = Al.LockedBuffer();\n    const El::Matrix<T> &Bl = B.LockedMatrix();\n    const T *b = Bl.LockedBuffer();\n    for(El::Int j = 0; j < Al.Width(); j++)\n        for(El::Int i = 0; i < Al.Height(); i++)\n            n[A.GlobalCol(j)] +=\n                a[j * Al.LDim() + i] * El::Conj(b[j * Bl.LDim() + i]);\n\n   N.Resize(A.Width(), 1);\n   El::Zero(N);\n   boost::mpi::communicator comm(N.Grid().Comm().comm, boost::mpi::comm_attach);\n   boost::mpi::all_reduce(comm, n.data(), A.Width(), N.Buffer(), std::plus<T>());\n}\n\ntemplate<typename T>\ninline void RowDot(const El::Matrix<T>& A, const El::Matrix<T>& B, \n    El::Matrix<T>& N) {\n\n    // TODO just assuming sizes are OK for now.\n\n    T *n = N.Buffer();\n    const T *a = A.LockedBuffer();\n    const T *b = B.LockedBuffer();\n    for(El::Int i = 0; i < A.Height(); i++)\n        n[i] = 0.0;\n\n    for(El::Int j = 0; j < A.Width(); j++) {\n        for(El::Int i = 0; i < A.Height(); i++)\n            n[i] += a[j * A.LDim() + i] * El::Conj(b[j * B.LDim() + i]);\n    }\n}\n\n} } // namespace skylark::base\n\n#endif // SKYLARK_INNER_HPP\n", "meta": {"hexsha": "1ab1162c10643b21a0e6d6f0aed16220984881c5", "size": 6112, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "base/inner.hpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "base/inner.hpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "base/inner.hpp", "max_forks_repo_name": "xdata-skylark/libskylark", "max_forks_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 31.5051546392, "max_line_length": 82, "alphanum_fraction": 0.5341950262, "num_tokens": 1999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.6442250928250375, "lm_q1q2_score": 0.40805878591418804}}
{"text": "#define BOOST_SPIRIT_USE_PHOENIX_V3\n#include <boost/variant/variant.hpp>\n#include <boost/variant/recursive_wrapper.hpp>\n#include <boost/variant/static_visitor.hpp>\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/qi_no_case.hpp>\n#include <boost/spirit/include/phoenix.hpp>\n\n#include <random>\n#include <string>\n\n#define WIN32_LEAN_AND_MEAN\n#define NOMINMAX\n#include <sdkddkver.h>\n#include <Windows.h>\n\n#include \"weather.h\"\n#include \"perlin.h\"\n#include \"misc.h\"\n\nusing namespace boost::spirit;\n\ntemplate <typename Iterator>\nstruct grammar : public qi::grammar<Iterator, double(), ascii::space_type>\n{\n\tqi::rule<Iterator, double(), ascii::space_type> expr, term, fctr;\n\tdouble time;\n\tgrammar(double t) : grammar::base_type(expr), time(t)\n\t{\n\t\texpr = term[_val = _1] >> *(('+' >> term[_val += _1]) | ('-' >> term[_val -= _1]));\n\t\tterm = fctr[_val = _1] >> *(('*' >> fctr[_val *= _1]) | ('/' >> fctr[_val /= _1]));\n\t\tfctr = double_[_val = _1]\n\t\t\t| '(' >> expr[_val = _1] >> ')'\n\t\t\t| qi::no_case[qi::lit('t')][_val = time]\n\t\t\t| qi::no_case[\"cloud(\"] >> expr[_val = boost::phoenix::bind(cloud_, _1)] >> \")\"\n\t\t\t| qi::no_case[\"rain(\"] >> expr[_val = boost::phoenix::bind(rain_, _1)] >> \")\"\n\t\t\t| qi::no_case[\"wind_speed(\"] >> expr[_val = boost::phoenix::bind(wind_speed_, _1)] >> \")\"\n\t\t\t| qi::no_case[\"air_temp(\"] >> expr[_val = boost::phoenix::bind(air_temp_, _1)] >> \")\"\n\t\t\t;\n\t}\n};\n\ndouble rain_chance_;\ndouble min_air_temp_;\ndouble max_air_temp_;\n\nperlin::noise cloud_;\nperlin::noise rain_;\nperlin::noise wind_speed_;\nperlin::noise air_temp_;\n\nstd::string cloud_expr_;\nstd::string rain_expr_;\nstd::string wind_speed_expr_;\nstd::string air_temp_expr_;\n\nstd::random_device rd_;\nstd::mt19937 mt_;\nbool rainfall_ = false;\nbool stoprain_ = false;\n\nvoid weather_init(unsigned int seed, weather_config *config)\n{\n\tif (seed == 0)\n\t\tseed = rd_();\n\tmt_.seed(seed);\n\n\tif (config != nullptr)\n\t{\n\t\train_chance_ = config->rain_chance;\n\t\tmin_air_temp_ = config->min_air_temp;\n\t\tmax_air_temp_ = config->max_air_temp;\n\n\t\tcloud_.set_seed(mt_());\n\t\tcloud_.set_zero(config->cloud.zero);\n\t\tcloud_.set_amplitude(config->cloud.amplitude);\n\t\tcloud_.set_min_value(config->cloud.min);\n\t\tcloud_.set_max_value(config->cloud.max);\n\t\tcloud_.set_frequency(1.0 / config->cloud.period);\n\t\tcloud_.set_octave(config->cloud.octave);\n\t\tcloud_expr_ = config->cloud.expression != nullptr\n\t\t\t? config->cloud.expression : \"cloud(T)\";\n\n\t\train_.set_seed(mt_());\n\t\train_.set_zero(config->rain.zero);\n\t\train_.set_amplitude(config->rain.amplitude);\n\t\train_.set_min_value(config->rain.min);\n\t\train_.set_max_value(config->rain.max);\n\t\train_.set_frequency(1.0 / config->rain.period);\n\t\train_.set_octave(config->rain.octave);\n\t\train_expr_ = config->rain.expression != nullptr\n\t\t\t? config->rain.expression : \"rain(T)\";\n\n\t\twind_speed_.set_seed(mt_());\n\t\twind_speed_.set_zero(config->wind_speed.zero);\n\t\twind_speed_.set_amplitude(config->wind_speed.amplitude);\n\t\twind_speed_.set_min_value(config->wind_speed.min);\n\t\twind_speed_.set_max_value(config->wind_speed.max);\n\t\twind_speed_.set_frequency(1.0 / config->wind_speed.period);\n\t\twind_speed_.set_octave(config->wind_speed.octave);\n\t\twind_speed_expr_ = config->wind_speed.expression != nullptr\n\t\t\t? config->wind_speed.expression : \"wind_speed(T)\";\n\n\t\tair_temp_.set_seed(mt_());\n\t\tair_temp_.set_zero(config->air_temp.zero);\n\t\tair_temp_.set_amplitude(config->air_temp.amplitude);\n\t\tair_temp_.set_min_value(config->air_temp.min);\n\t\tair_temp_.set_max_value(config->air_temp.max);\n\t\tair_temp_.set_frequency(1.0 / config->air_temp.period);\n\t\tair_temp_.set_octave(config->air_temp.octave);\n\t\tair_temp_expr_ = config->air_temp.expression != nullptr\n\t\t\t? config->air_temp.expression : \"air_temp(T)\";\n\t}\n}\n\nvoid weather_simulate(double time, weather_info *info)\n{\n\tdouble c = 0, r = 0, w = 0, a = 0;\n\tgrammar<std::string::iterator> g(time);\n\tqi::phrase_parse(cloud_expr_.begin(), cloud_expr_.end(), g, ascii::space, c);\n\tqi::phrase_parse(rain_expr_.begin(), rain_expr_.end(), g, ascii::space, r);\n\tqi::phrase_parse(wind_speed_expr_.begin(), wind_speed_expr_.end(), g, ascii::space, w);\n\tqi::phrase_parse(air_temp_expr_.begin(), air_temp_expr_.end(), g, ascii::space, a);\n\n\tr = clamp<double>(r, rain_.min_value(), c);\n\ta *= (max_air_temp_ - min_air_temp_) / 2;\n\ta += min_air_temp_ + (max_air_temp_ - min_air_temp_) / 2;\n\n\tif (!rainfall_)\n\t{\n\t\tif (0 < r)\n\t\t{\n\t\t\tif (!stoprain_)\n\t\t\t{\n\t\t\t\tstd::uniform_real_distribution<double> chance(0, 1);\n\t\t\t\tif (rain_chance_ < chance(mt_))\n\t\t\t\t{\n\t\t\t\t\tstoprain_ = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstoprain_ = false;\n\t\t}\n\t}\n\n\tr = stoprain_ ? 0 : r;\n\trainfall_ = 0 < r;\n\n\tinfo->cloud = c;\n\tinfo->rain = r;\n\tinfo->air_temp = a;\n\tinfo->wind_speed = w;\n}\n", "meta": {"hexsha": "37312f48e2e94e577fdb615272ea67dc490169e3", "size": 4729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "weather.cpp", "max_stars_repo_name": "palm3r/RandomWeather", "max_stars_repo_head_hexsha": "69cc4c9135d8537843ada5bc89fb6b96e8392a2b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "weather.cpp", "max_issues_repo_name": "palm3r/RandomWeather", "max_issues_repo_head_hexsha": "69cc4c9135d8537843ada5bc89fb6b96e8392a2b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "weather.cpp", "max_forks_repo_name": "palm3r/RandomWeather", "max_forks_repo_head_hexsha": "69cc4c9135d8537843ada5bc89fb6b96e8392a2b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1210191083, "max_line_length": 92, "alphanum_fraction": 0.6948614929, "num_tokens": 1436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8289388083214155, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.4079938466943354}}
{"text": "//\r\n// Copyright (c) 2016 - 2017 Mesh Consultants Inc.\r\n// Permission is hereby granted, free of charge, to any person obtaining a copy\r\n// of this software and associated documentation files (the \"Software\"), to deal\r\n// in the Software without restriction, including without limitation the rights\r\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n// copies of the Software, and to permit persons to whom the Software is\r\n// furnished to do so, subject to the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be included in\r\n// all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n// THE SOFTWARE.\r\n//\r\n\r\n\r\n#include \"Geomlib_Rhodo.h\"\n\n#include <Eigen/Core>\n\n#include <Urho3D/Core/Variant.h>\n#include <Urho3D/Math/Vector3.h>\n\nGeomlib::Rhodo::Rhodo(Rhodo& originalRhodo, int jumpIndex)\n{\n\tEigen::RowVector3i unitlessCoordinates = originalRhodo.ComputeUnitlessCoordinates()\n\t\t+ RhodoEigen::jumpsToNeighbors[jumpIndex];\n\tfamily_ = ComputeFamilyFromUnitlessCoordinates(unitlessCoordinates);\n\txDiamJumps_ = (unitlessCoordinates(0) - RhodoEigen::iGeneratingRhodos[family_](0)) / 4;\n\tyDiamJumps_ = (unitlessCoordinates(1) - RhodoEigen::iGeneratingRhodos[family_](1)) / 4;\n\tzDiamJumps_ = (unitlessCoordinates(2) - RhodoEigen::iGeneratingRhodos[family_](2)) / 4;\n}\n\nGeomlib::Rhodo::Rhodo(int xUnitless, int yUnitless, int zUnitless)\n{\n\tEigen::RowVector3i unitlessCoords(xUnitless, yUnitless, zUnitless);\n\tfamily_ = ComputeFamilyFromUnitlessCoordinates(unitlessCoords);\n\tEigen::RowVector3i generatingCenter = RhodoEigen::iGeneratingRhodos[family_];\n\txDiamJumps_ = (unitlessCoords[0] - generatingCenter[0]) / 4;\n\tyDiamJumps_ = (unitlessCoords[1] - generatingCenter[1]) / 4;\n\tzDiamJumps_ = (unitlessCoords[2] - generatingCenter[2]) / 4;\n}\n\n\nEigen::RowVector3f Geomlib::Rhodo::ComputeCoordinates(float s) const\n{\n\treturn s * (RhodoEigen::fGeneratingRhodos[family_] +\n\t\t(4 * (float)xDiamJumps_) * Eigen::RowVector3f(1.0f, 0.0f, 0.0f) +\n\t\t(4 * (float)yDiamJumps_) * Eigen::RowVector3f(0.0f, 1.0f, 0.0f) +\n\t\t(4 * (float)zDiamJumps_) * Eigen::RowVector3f(0.0f, 0.0f, 1.0f));\n}\n\nEigen::RowVector3i Geomlib::Rhodo::ComputeUnitlessCoordinates() const\n{\n\treturn RhodoEigen::iGeneratingRhodos[family_] +\n\t\t(4 * xDiamJumps_) * Eigen::RowVector3i(1, 0, 0) +\n\t\t(4 * yDiamJumps_) * Eigen::RowVector3i(0, 1, 0) +\n\t\t(4 * zDiamJumps_) * Eigen::RowVector3i(0, 0, 1);\n}\n\nUrho3D::VariantVector Geomlib::Rhodo::ComputeVertices(float scale) const\n{\n\tUrho3D::VariantVector tmp;\n\n\tEigen::RowVector3i uCenter = ComputeUnitlessCoordinates();\n\n\tfor (unsigned i = 0; i < 14; ++i) {\n\t\tEigen::RowVector3i vert = uCenter + RhodoEigen::rhodoVertexCoords[i];\n\t\tUrho3D::Vector3 baseCoords(scale * vert(0), scale * vert(1), scale * vert(2));\n\t\ttmp.Push(baseCoords);\n\t}\n\n\treturn tmp;\n}\n\nUrho3D::VariantVector Geomlib::Rhodo::ComputeRhombicPolylines(float scale) const\n{\n\tUrho3D::VariantVector tmp;\n\n\tEigen::RowVector3i uCenter = ComputeUnitlessCoordinates();\n\tEigen::RowVector3f fCenter = scale * Eigen::RowVector3f((float)uCenter(0), (float)uCenter(1), (float)uCenter(2));\n\n\t// Loop across the 12 rhombic faces of the rhombic dodecahedron\n\tfor (unsigned i = 0; i < 12; ++i) {\n\t\t// Get rhombic face i\n\t\tconst Eigen::RowVector3f* rhombus = RhodoEigen::neighborRhombi[i];\n\t\tUrho3D::VariantMap rhombusPolyLine;\n\t\tUrho3D::VariantVector verts;\n\t\t// Loop over the 4 vertices of this rhombus\n\t\tfor (unsigned j = 0; j < 4; ++j) {\n\t\t\tEigen::RowVector3f v = scale * rhombus[j] + fCenter;\n\n\t\t\tUrho3D::Vector3 vert(v(0), v(1), v(2));\n\t\t\tverts.Push(vert);\n\t\t}\n\t\t// Close the rhombus polyline by adding the initial vertex again at the end\n\t\tEigen::RowVector3f v = scale * rhombus[0] + fCenter;\n\t\tUrho3D::Vector3 vert(v(0), v(1), v(2));\n\t\tverts.Push(vert);\n\n\t\trhombusPolyLine[\"vertices\"] = verts;\n\t\ttmp.Push(rhombusPolyLine);\n\t}\n\n\treturn tmp;\n}\n\n// hackish, depends on definition of generatingCenterDisplacements\nint Geomlib::ComputeFamilyFromUnitlessCoordinates(const Eigen::RowVector3i& unitlessCoordinates)\n{\n\tint a = unitlessCoordinates[0] % 4;\n\tint b = unitlessCoordinates[1] % 4;\n\tif (a == 0) {\n\t\tif (b == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\telse {\n\t\t\treturn 1;\n\t\t}\n\t}\n\telse {\n\t\tif (b == 0) {\n\t\t\treturn 2;\n\t\t}\n\t\telse {\n\t\t\treturn 3;\n\t\t}\n\t}\n}", "meta": {"hexsha": "a096c28962b9a2ae0aedd3d4390134cbb8c8bd42", "size": 4716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry/Geomlib_Rhodo.cpp", "max_stars_repo_name": "elix22/IogramSource", "max_stars_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-03-01T04:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T13:33:50.000Z", "max_issues_repo_path": "Geometry/Geomlib_Rhodo.cpp", "max_issues_repo_name": "elix22/IogramSource", "max_issues_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-03-09T05:22:49.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T18:38:05.000Z", "max_forks_repo_path": "Geometry/Geomlib_Rhodo.cpp", "max_forks_repo_name": "elix22/IogramSource", "max_forks_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-03-01T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:36:54.000Z", "avg_line_length": 34.9333333333, "max_line_length": 114, "alphanum_fraction": 0.7220101781, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.6477982179521103, "lm_q1q2_score": 0.4079668683880689}}
{"text": "// Copyright András Vukics 2006–2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n#include \"Particle_.h\"\n\n#include \"ParsParticle.h\"\n#include \"ParticleInitialCondition.h\"\n\n#include \"LazyDensityOperatorFFT.h\"\n#include \"TridiagonalHamiltonian.h\"\n\n#include <boost/math/special_functions/hermite.hpp>\n\n#include \"TMP_Tools.h\"\n\n#include <boost/assign/list_of.hpp>\n#include <boost/bind.hpp>\n#include <utility>\n\nusing namespace std;\nusing namespace mathutils;\nusing namespace cpputils;\nusing namespace fft;\n\n\n\n////////\n//\n// Exact\n//\n////////\n\n\nnamespace {\n\nconst particle::Exact::Diagonal fExpFill(const particle::Spatial& space, double omrec)\n{\n  return particle::Exact::Diagonal(-DCOMP_I*omrec*blitz::sqr(space.getK()));\n}\n\n} \n\n\nparticle::Exact::Exact(const Spatial& space, double omrec)\n  : FreeExact(space.getDimension()), details::Storage(space,omrec), factorExponents_(fExpFill(space,omrec))\n{\n}\n\nvoid particle::Exact::updateU(structure::OneTime t) const\n{\n  getDiagonal()=exp(factorExponents_*t);\n}\n \n\n//////////////\n//\n// Hamiltonian\n//\n//////////////\n\n\nnamespace {\n\nconst particle::Tridiagonal expINKX(size_t dim, ptrdiff_t nK)\n{\n  using particle::Tridiagonal;\n\n  typedef Tridiagonal::Diagonal Diag;\n\n  ptrdiff_t D=dim-(nK>0 ? nK : -nK);\n  if (D<0) return Tridiagonal();\n\n  Diag temp(D); temp=1;\n  if (nK>0) return Tridiagonal(Diag(),nK,temp);\n  else if (nK==0) return Tridiagonal(temp);\n  return Tridiagonal(Diag(),-nK,Diag(),temp);\n}\n\n\nconst particle::Tridiagonal cosNKX(size_t dim, ptrdiff_t nK)\n{\n  return (expINKX(dim,nK)+expINKX(dim,-nK))/2.;\n}\n\n\nconst particle::Tridiagonal hOverI(size_t dim, double vClass, const ModeFunction& mf)\n{\n  return (vClass && !isComplex(get<0>(mf))) ? vClass*(get<0>(mf)==MFT_SIN ? -1 : 1)*cosNKX(dim,get<1>(mf)<<1)/(2.*DCOMP_I) : particle::Tridiagonal();\n}\n\n\nconst particle::Tridiagonal::Diagonal mainDiagonal(const particle::Spatial& space, double omrec)\n{\n  return particle::Tridiagonal::Diagonal(DCOMP_I*omrec*blitz::sqr(space.getK()));\n}\n\n\n} \n\n\nnamespace particle { // open it for the partial specializations\n\ntemplate<>\nHamiltonian<true >::Hamiltonian(const Spatial& space, double omrec, double vClass, const ModeFunction& mf)\n  : Base(furnishWithFreqs(hOverI(space.getDimension(),vClass,mf),mainDiagonal(space,omrec))), Exact(space,omrec)\n{\n}\n\n\ntemplate<>\nHamiltonian<false>::Hamiltonian(const Spatial& space, double omrec, double vClass, const ModeFunction& mf)\n  : Base(\n         Tridiagonal(mainDiagonal(space,-omrec))\n         +\n         hOverI(space.getDimension(),vClass,mf)\n         )\n{\n}\n\n\ntemplate<> template<>\nHamiltonian<false>::Hamiltonian(const Spatial& space, double omrec)\n  : Base(\n         Tridiagonal(mainDiagonal(space,-omrec))\n         )\n{\n}\n\n} // particle\n\n///////////\n//\n// Averaged\n//\n///////////\n\n\nparticle::Averaged::Averaged(const Spatial& space)\n  : Base(\"Particle\",{\"<P>\",\"VAR(P)\",\"<X>\",\"DEV(X)\"}),\n    space_(space)\n{\n}\n\n\nauto particle::Averaged::average_v(NoTime, const LazyDensityOperator& matrix) const -> const Averages\n{\n  int dim=space_.getDimension();\n\n  auto averages(initializedAverages());\n  \n  const LazyDensityOperator::Ptr matrixX(quantumdata::ffTransform<tmptools::Vector<0> >(matrix,DIR_KX));\n  \n  for (int i=0; i<dim; i++) {\n\n    double diag=matrix(i);\n    averages(0)+=    space_.k(i) *diag;\n    averages(1)+=sqr(space_.k(i))*diag;\n  }\n\n  for (int i=0; i<dim; i++) {\n    double diag=matrixX->operator()(i);\n    averages(2)+=    space_.x(i) *diag; \n    averages(3)+=sqr(space_.x(i))*diag;      \n  }\n\n  return averages;\n}\n\n\n\nvoid particle::Averaged::process_v(Averages& averages) const\n{\n  averages(1)-=sqr(averages(0));\n  averages(3)=sqrt(averages(3)-sqr(averages(2)));\n}\n\n\n\n////////////////\n//\n// Highest level\n//\n////////////////\n\nParticleBase::ParticleBase(size_t fin, \n                           const RealFreqs& realFreqs, const ComplexFreqs& complexFreqs)\n  : Free(1<<fin,realFreqs,complexFreqs), Averaged(particle::Spatial(fin))\n{\n  getParsStream()<<\"Particle\\n\";\n  getSpace().header(getParsStream());\n}\n\n\nPumpedParticleBase::PumpedParticleBase(size_t fin, double vClass, const ModeFunction& mf,\n                                       const RealFreqs& realFreqs, const ComplexFreqs& complexFreqs)\n  : ParticleBase(fin,\n                 boost::assign::list_of(*realFreqs.begin()).range(next(realFreqs.begin()),realFreqs.end())({\"vClass\",vClass,1.}),\n                 complexFreqs),\n    vClass_(vClass), mf_(mf)\n{\n  getParsStream()<<\"Pump \"<<mf<<endl;\n}\n\n\n\nParticle::Particle(const particle::Pars& p)\n  : ParticleBase(p.fin,{RF{\"omrec\",p.omrec,1<<p.fin}}),\n    Exact(getSpace(),p.omrec)\n{\n}\n\n\nParticleSch::ParticleSch(const particle::Pars& p)\n  : ParticleBase(p.fin,{RF{\"omrec\",p.omrec,sqr(1<<p.fin)}}),\n    Hamiltonian<false>(getSpace(),p.omrec)\n{\n  getParsStream()<<\"Schroedinger picture.\\n\";\n}\n\n\n\nPumpedParticle::PumpedParticle(const particle::ParsPumped& p)\n  : PumpedParticleBase(p.fin,p.vClass,ModeFunction(p.modePart,p.kPart),{RF{\"omrec\",p.omrec,1<<p.fin}}),\n    Hamiltonian<true>(getSpace(),p.omrec,p.vClass,getMF())\n{\n}\n\n\nPumpedParticleSch::PumpedParticleSch(const particle::ParsPumped& p)\n  : PumpedParticleBase(p.fin,p.vClass,ModeFunction(p.modePart,p.kPart),{RF{\"omrec\" ,p.omrec,sqr(1<<p.fin)}}),\n    Hamiltonian<false>(getSpace(),p.omrec,p.vClass,getMF())\n{\n  getParsStream()<<\"Schroedinger picture.\\n\";\n}\n\n\n//////////\n//\n// Helpers\n//\n//////////\n\n\nnamespace {\n\nusing particle::Spatial;\n\nconst Spatial::Array fill(size_t fin, double d, double m)\n{\n  Spatial::Array res(1<<fin);\n  return res=d*blitz::tensor::i-m;\n}\n\n} \n\n\nparticle::Spatial::Spatial(size_t fin, double deltaK)\n  : fin_(fin),\n    xMax_(PI/deltaK), deltaX_(2*xMax_/(1<<fin)), kMax_(PI/deltaX_), deltaK_(deltaK),\n    x_(fill(fin,deltaX_,xMax_)), k_(fill(fin,deltaK_,kMax_))\n{\n}\n\n\nvoid particle::Spatial::header(std::ostream& os) const\n{\n  os<<\"Spatial Degree of Freedom finesse=\"<<fin_<<\" xMax=\"<<xMax_<<\" deltaX=\"<<deltaX_<<\" kMax=\"<<kMax_<<\" deltaK=\"<<deltaK_<<std::endl;\n}\n\n\n\nauto particle::expINKX(particle::Ptr particle, ptrdiff_t nK) -> const Tridiagonal\n{\n  size_t dim=particle->getDimension();\n  Tridiagonal res(::expINKX(dim,nK));\n  if (const auto exact=dynamic_cast<const particle::Exact*>(particle.get())) res.furnishWithFreqs(mainDiagonal(get<0>(*exact),get<1>(*exact)));\n  return res;\n}\n\n\nauto particle::mfNKX(particle::Ptr particle, const ModeFunction& modeFunction) -> const Tridiagonal\n{\n  ModeFunctionType mf(get<0>(modeFunction));\n  ptrdiff_t        nK(get<1>(modeFunction));\n  switch (mf) {\n  case MFT_SIN  : return sinNKX (particle,nK);\n  case MFT_COS  : return cosNKX (particle,nK);\n  case MFT_PLUS : return expINKX(particle,nK);\n  case MFT_MINUS:                            ;\n  }\n  return expINKX(particle,-nK);\n}\n\nauto particle::mfComposition(particle::Ptr particle, const ModeFunction& modeFunction1, const ModeFunction& modeFunction2) -> const Tridiagonal\n{\n  ModeFunctionType mf1(get<0>(modeFunction1));\n  ModeFunctionType mf2(get<0>(modeFunction2));\n  ptrdiff_t        nK1(get<1>(modeFunction1));\n  ptrdiff_t        nK2(get<1>(modeFunction2));\n  ptrdiff_t        nK(abs(nK1));\n  ptrdiff_t        sign1 = mf1==MFT_SIN && nK1<0 ? -1 : 1;\n  ptrdiff_t        sign2 = mf2==MFT_SIN && nK2<0 ? -1 : 1;\n  ptrdiff_t        sign  = sign1*sign2;\n\n  if (abs(nK1) != abs(nK2)) throw std::runtime_error(\"Not a Tridiagonal\");\n\n  if (mf1==MFT_PLUS  && nK1<0) { mf1=MFT_MINUS; nK1*=-1; }\n  if (mf1==MFT_MINUS && nK1<0) { mf1=MFT_PLUS;  nK1*=-1; }\n  if (mf2==MFT_PLUS  && nK2<0) { mf2=MFT_MINUS; nK2*=-1; }\n  if (mf2==MFT_MINUS && nK2<0) { mf2=MFT_PLUS;  nK2*=-1; }\n\n  Tridiagonal id(quantumoperator::identity(particle->getSpace().getDimension()));\n\n  typedef pair<ModeFunctionType,ModeFunctionType> MFPair;\n\n  MFPair mfs(mf1,mf2);\n\n  if (mfs == MFPair(MFT_SIN,MFT_SIN)){\n    return sign * (id-cosNKX(particle,2*nK)) / 2.;\n  }\n  if (mfs == MFPair(MFT_COS,MFT_COS)){\n    return (id+cosNKX(particle,2*nK)) / 2.;\n  }\n  if (mfs == MFPair(MFT_SIN,MFT_COS) || mfs == MFPair(MFT_COS,MFT_SIN)){\n    return sign * sinNKX(particle,2*nK) / 2.;\n  }\n  if (mfs == MFPair(MFT_PLUS,MFT_PLUS) || mfs == MFPair(MFT_MINUS,MFT_MINUS)){\n    return id;\n  }\n  if (mfs == MFPair(MFT_PLUS,MFT_MINUS)){\n    return expINKX(particle,-2*nK);\n  }\n  if (mfs == MFPair(MFT_MINUS,MFT_PLUS)){\n    return expINKX(particle,2*nK);\n  }\n  if (mfs == MFPair(MFT_PLUS,MFT_SIN) || mfs == MFPair(MFT_SIN,MFT_MINUS)) {\n    return sign * (expINKX(particle, -2*nK)-id) * DCOMP_I/2.;\n  }\n  if (mfs == MFPair(MFT_PLUS,MFT_COS) || mfs == MFPair(MFT_COS,MFT_MINUS)) {\n    return (id + expINKX(particle,-2*nK)) / 2.;\n  }\n  if (mfs == MFPair(MFT_MINUS,MFT_COS) || mfs == MFPair(MFT_COS,MFT_PLUS)) {\n    return (id + expINKX(particle, 2*nK)) / 2.;\n  }\n  if (!(mfs == MFPair(MFT_MINUS,MFT_SIN) || mfs == MFPair(MFT_SIN,MFT_PLUS))) {\n    // this should never be reached\n    throw std::logic_error(\"In mfComposition\");\n  }\n  return -sign * (expINKX(particle,2*nK)-id) * DCOMP_I/2.;\n}\n\n/*\nconst Tridiagonal mfNKX_AbsSqr(ModeFunctionType mf, size_t dim, ptrdiff_t K)\n{\n  return (mfcomplex(mf) ? Identity(dim) : (mf==MFT_Sin ? -1 : 1)*cosNKX(dim,2*K))/2.;\n  // The other 1/2 should be taken into account separately!\n}\n*/\n\nauto particle::wavePacket(const InitialCondition& init, const Spatial& space, bool kFlag) -> StateVector\n{\n  double \n    offset1=PI*init.getX0(),\n    offset2=   init.getK0();\n\n  if (init.isInK()) {swap(offset1,offset2); offset2=-offset2;}\n\n  const Spatial::Array array(init.isInK() ? space.getK() : space.getX());\n\n  StateVectorLow psiLow(exp(-blitz::sqr(array-offset1)/(4*sqr(init.getSig()))+DCOMP_I*array*offset2));\n\n  if      ( kFlag && !init.isInK()) quantumdata::ffTransform(psiLow,DIR_XK);\n  else if (!kFlag &&  init.isInK()) quantumdata::ffTransform(psiLow,DIR_KX);\n\n  StateVector res(psiLow,quantumdata::byReference); res.renorm();\n\n  return res;\n\n}\n\n\nauto particle::wavePacket(const Pars& p, bool kFlag) -> StateVector\n{\n  return wavePacket(p.init,Spatial(p.fin),kFlag);\n}\n\n\nnamespace {\n\nconst particle::InitialCondition coherent(const particle::ParsPumped& p)\n{\n  return particle::InitialCondition(p.init.getX0(),p.init.getK0(),pow(p.omrec/fabs(p.vClass),.25)/sqrt(2),false);\n}\n\n}\n\nauto particle::wavePacket(const ParsPumped& p, bool kFlag) -> StateVector\n{\n  if (p.init.getSig()) return wavePacket(static_cast<const Pars&>(p),kFlag);\n  else                 return wavePacket(coherent(p),\n                                         Spatial(p.fin),\n                                         kFlag);\n}\n\n\nauto particle::hoState(int n, const InitialCondition& init, const Spatial& space, bool kFlag) -> StateVector\n{\n  if (n<0) n=0;\n\n  double kx0(PI*init.getX0());\n\n  size_t dim=space.getDimension();\n\n  StateVectorLow psiLow(dim);\n\n  for (size_t j=0; j<dim; j++) {\n    double temp=(space.getX()(j)-kx0)/init.getSig();\n    psiLow(j)=exp(-sqr(temp)/2.)*boost::math::hermite(n,temp);\n  }\n\n  if (kFlag) quantumdata::ffTransform(psiLow,DIR_XK);\n  \n  StateVector res(psiLow,quantumdata::byReference); res.renorm();\n\n  return res;\n\n}\n\n\nauto particle::hoState(const Pars      & p, bool kFlag) -> StateVector\n{\n  return hoState(p.hoInitn,p.init,Spatial(p.fin),kFlag);\n}\n\n\nauto particle::hoState(const ParsPumped& p, bool kFlag) -> StateVector\n{\n  if (p.init.getSig()) return hoState(static_cast<const Pars&>(p),kFlag);\n  else                 return hoState(p.hoInitn,\n                                      coherent(p),\n                                      Spatial(p.fin),\n                                      kFlag);\n}\n\n\nauto particle::init(const Pars& p) -> StateVector\n{\n  if (const auto pp=dynamic_cast<const ParsPumped*>(&p))\n    return p.hoInitn<0 ? wavePacket(*pp) : hoState(*pp);\n  else\n    return p.hoInitn<0 ? wavePacket( p ) : hoState( p );\n}\n\n\n\n\nparticle::Ptr particle::make(const Pars& p, QM_Picture qmp)\n{\n  return qmp==QMP_SCH ? Ptr(std::make_shared<ParticleSch>(p)) : Ptr(std::make_shared<Particle>(p));\n}\n\n\nparticle::PtrPumped particle::makePumped(const ParsPumped& p, QM_Picture qmp)\n{\n  return qmp==QMP_SCH ? PtrPumped(std::make_shared<PumpedParticleSch>(p)) : PtrPumped(std::make_shared<PumpedParticle>(p));\n}\n", "meta": {"hexsha": "c8f5711399f5c4b4d1d6717e6efb7ea191bdb50d", "size": 12117, "ext": "cc", "lang": "C++", "max_stars_repo_path": "CPPQEDelements/frees/Particle.cc", "max_stars_repo_name": "bartoszek/cppqed", "max_stars_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CPPQEDelements/frees/Particle.cc", "max_issues_repo_name": "bartoszek/cppqed", "max_issues_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CPPQEDelements/frees/Particle.cc", "max_forks_repo_name": "bartoszek/cppqed", "max_forks_repo_head_hexsha": "712b601e377642885f40cbf8a65eb1525360f654", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0580645161, "max_line_length": 149, "alphanum_fraction": 0.6579186267, "num_tokens": 3731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208002, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4079426603459941}}
{"text": "/*\n * Copyright 2018 James Dyer\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n *\n * This is being developed for the TANGO Project: http://tango-project.eu\n */\n\n#include <sstream>\n#include <NTL/RR.h>\n#include <json/json.h>\n#include \"HE2NEncrypter.h\"\n#include \"Random.h\"\n\nHE2NEncrypter::~HE2NEncrypter()\n{\n\tdelete kappamod;\n};\n\nHE2NEncrypter::HE2NEncrypter(int lambda, int eta, int nu){\n\tkappa = NTL::RandomPrime_ZZ(nu,20);\n\tgenerateParameters(lambda,eta);\n\tNTL::ZZ_p::init(modulus);\n\tNTL::ZZ_p ktmp = NTL::to_ZZ_p(kappa);\n\tkappamod = new NTL::ZZ_p(ktmp);\n}\n\nHE2NEncrypter::HE2NEncrypter(int n, int d, int rho, int rhoprime)\n{\n    /* Compute lower bound for kappa */\n\tNTL::RR rtwo = NTL::RR(2);\n\tNTL::RR exp1 = NTL::RR(rho*d);\n\tNTL::RR nplusone = NTL::RR(n+1);\n\tNTL::RR exp2 = NTL::RR(d);\n\tNTL::RR exp3 = NTL::RR(rho);\n\tNTL::RR kloBound = pow(rtwo,exp1)*pow(nplusone,exp2);\n\tNTL::ZZ kappaLowerBound = to_ZZ(kloBound);\n\t/* Generate kappa as prime > lower bound */\n\tlong nu = NumBits(kappaLowerBound)+1;\n\tkappa = NTL::RandomPrime_ZZ(nu,20);\n\n\t/*compute lower bound for p */\n\tNTL::RR kappareal = to_RR(kappa);\n\tNTL::RR ploBound = pow(pow(rtwo,exp3)+pow(kappareal,rtwo),exp2)*pow(nplusone,exp2);\n\tNTL::ZZ pLowerBound = to_ZZ(ploBound);\n\n\t/* Generate p and q */\n\tlong lambda = NumBits(pLowerBound) + 1;\n\tlong eta = ((lambda * lambda / rho) - lambda);\n\n\tgenerateParameters(lambda,eta);\n\tNTL::ZZ_p::init(modulus);\n\tNTL::ZZ_p ktmp = NTL::to_ZZ_p(kappa);\n\tkappamod = new NTL::ZZ_p(ktmp);\n};\n\nNTL::vec_ZZ_p HE2NEncrypter::encrypt(NTL::ZZ& plaintext)\n{\n    NTL::ZZ_p r = NTL::to_ZZ_p(rng->nextBigInteger(q));\n    NTL::ZZ_p s = NTL::to_ZZ_p(rng->nextBigInteger(kappa));\n    NTL::ZZ_p t = NTL::to_ZZ_p(rng->nextBigInteger(modulus));\n    NTL::ZZ_p ptext = NTL::to_ZZ_p(plaintext);\n    NTL::ZZ_p c = ptext + r*(*pmod) +s*(*kappamod);\n    return ONE_VECTOR*c + (*a)*t;\n};\n\nstd::string HE2NEncrypter::writeSecretsToJSON()\n{\n\tJson::Value root;\n\tstd::ostringstream pStr,modStr,kappaStr,gammaStr;\n\tpStr << p;\n\troot[\"p\"] = pStr.str();\n\tmodStr << modulus;\n\troot[\"modulus\"] = modStr.str();\n\tkappaStr << kappa;\n\troot[\"kappa\"] = kappaStr.str();\n\tgammaStr << (*gamma);\n    root[\"gamma\"]=gammaStr.str();\n\tJson::FastWriter writer;\n\treturn writer.write(root);\n};\n\n", "meta": {"hexsha": "4192e4a3455399223423a40d6f8f5c8fb9e135e7", "size": 2741, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HE2NEncrypter.cpp", "max_stars_repo_name": "TANGO-Project/cryptsdc", "max_stars_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HE2NEncrypter.cpp", "max_issues_repo_name": "TANGO-Project/cryptsdc", "max_issues_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HE2NEncrypter.cpp", "max_forks_repo_name": "TANGO-Project/cryptsdc", "max_forks_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4731182796, "max_line_length": 84, "alphanum_fraction": 0.6880700474, "num_tokens": 905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.40794265417329356}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl\n Copyright (C) 2003 Ferdinando Ametrano\n Copyright (C) 2007 StatPro Italia srl\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/instruments/vanillaoption.hpp>\n#include <ql/instruments/impliedvolatility.hpp>\n#include <ql/pricingengines/vanilla/analyticeuropeanengine.hpp>\n#include <ql/pricingengines/vanilla/fdamericanengine.hpp>\n#include <ql/pricingengines/vanilla/fdbermudanengine.hpp>\n#include <ql/exercise.hpp>\n#include <boost/scoped_ptr.hpp>\n\nnamespace QuantLib {\n\n    VanillaOption::VanillaOption(\n        const boost::shared_ptr<StrikedTypePayoff>& payoff,\n        const boost::shared_ptr<Exercise>& exercise)\n    : OneAssetOption(payoff, exercise) {}\n\n\n    Volatility VanillaOption::impliedVolatility(\n             Real targetValue,\n             const boost::shared_ptr<GeneralizedBlackScholesProcess>& process,\n             Real accuracy,\n             Size maxEvaluations,\n             Volatility minVol,\n             Volatility maxVol) const {\n\n        QL_REQUIRE(!isExpired(), \"option expired\");\n\n        boost::shared_ptr<SimpleQuote> volQuote(new SimpleQuote);\n\n        boost::shared_ptr<GeneralizedBlackScholesProcess> newProcess =\n            detail::ImpliedVolatilityHelper::clone(process, volQuote);\n\n        // engines are built-in for the time being\n        boost::scoped_ptr<PricingEngine> engine;\n        switch (exercise_->type()) {\n          case Exercise::European:\n            engine.reset(new AnalyticEuropeanEngine(newProcess));\n            break;\n          case Exercise::American:\n            engine.reset(new FDAmericanEngine<CrankNicolson>(newProcess));\n            break;\n          case Exercise::Bermudan:\n            engine.reset(new FDBermudanEngine<CrankNicolson>(newProcess));\n            break;\n          default:\n            QL_FAIL(\"unknown exercise type\");\n        }\n\n        return detail::ImpliedVolatilityHelper::calculate(*this,\n                                                          *engine,\n                                                          *volQuote,\n                                                          targetValue,\n                                                          accuracy,\n                                                          maxEvaluations,\n                                                          minVol, maxVol);\n    }\n\n}\n\n", "meta": {"hexsha": "176acacd66f59386734e969cf9f7e6693f35678c", "size": 3087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/instruments/vanillaoption.cpp", "max_stars_repo_name": "grandtiger/quantlib", "max_stars_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "ql/instruments/vanillaoption.cpp", "max_issues_repo_name": "grandtiger/quantlib", "max_issues_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T18:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-17T18:49:22.000Z", "max_forks_repo_path": "ql/instruments/vanillaoption.cpp", "max_forks_repo_name": "grandtiger/quantlib", "max_forks_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 38.5875, "max_line_length": 79, "alphanum_fraction": 0.6196954972, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.40788933538152217}}
{"text": "/**\n * Copyright 2021 Huawei Technologies Co., Ltd\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#include \"backend/kernel_compiler/cpu/eigen/eigh_cpu_kernel.h\"\n#include <Eigen/Eigenvalues>\n#include <type_traits>\n#include \"utils/ms_utils.h\"\n\nnamespace mindspore {\nnamespace kernel {\n\nnamespace {\nconstexpr size_t kInputsNum = 2;\nconstexpr size_t kOutputsNum = 2;\nconstexpr size_t kDefaultShape = 1;\nconstexpr auto kAMatrixDimNum = 2;\n\n}  // namespace\nusing Eigen::Dynamic;\nusing Eigen::EigenSolver;\nusing Eigen::Lower;\nusing Eigen::Map;\nusing Eigen::MatrixBase;\nusing Eigen::RowMajor;\nusing Eigen::Upper;\n\ntemplate <typename T>\nusing MatrixSquare = Eigen::Matrix<T, Dynamic, Dynamic, RowMajor>;\n\ntemplate <typename T>\nusing ComplexMatrixSquare = Eigen::Matrix<std::complex<T>, Dynamic, Dynamic, RowMajor>;\n\ntemplate <typename T>\nvoid EighCPUKernel<T>::InitKernel(const CNodePtr &kernel_node) {\n  dtype_ = AnfAlgo::GetInputDeviceDataType(kernel_node, 0);\n\n  compute_eigen_vectors = AnfAlgo::GetNodeAttr<bool>(kernel_node, C_EIEH_VECTOR);\n\n  auto A_shape = AnfAlgo::GetPrevNodeOutputInferShape(kernel_node, 0);\n  CHECK_KERNEL_INPUTS_NUM(A_shape.size(), kAMatrixDimNum, AnfAlgo::GetCNodeName(kernel_node));\n\n  if (A_shape.size() != kShape2dDims || A_shape[0] != A_shape[1]) {\n    MS_LOG(EXCEPTION) << \"wrong array shape, A should be a matrix, but got [\" << A_shape[0] << \" X \" << A_shape[1]\n                      << \"]\";\n  }\n  m_ = A_shape[0];\n}\n\ntemplate <typename T>\nvoid EighCPUKernel<T>::InitInputOutputSize(const CNodePtr &kernel_node) {\n  CPUKernel::InitInputOutputSize(kernel_node);\n  (void)workspace_size_list_.template emplace_back(m_ * m_ * sizeof(T));\n}\n\ntemplate <typename T>\nbool SolveSelfAdjointMatrix(const Map<MatrixSquare<T>> &A, Map<MatrixSquare<T>> *output, Map<MatrixSquare<T>> *outputv,\n                            bool compute_eigen_vectors) {\n  Eigen::SelfAdjointEigenSolver<MatrixSquare<T>> solver(A);\n  output->noalias() = solver.eigenvalues();\n  if (compute_eigen_vectors) {\n    outputv->noalias() = solver.eigenvectors();\n  }\n  return true;\n}\n\ntemplate <typename T>\nbool SolveComplexMatrix(const Map<MatrixSquare<T>> &A, Map<MatrixSquare<T>> *output, Map<MatrixSquare<T>> *outputv,\n                        bool compute_eigen_vectors) {\n  Eigen::ComplexEigenSolver<MatrixSquare<T>> solver(A);\n  output->noalias() = solver.eigenvalues();\n  if (compute_eigen_vectors) {\n    outputv->noalias() = solver.eigenvectors();\n  }\n  return true;\n}\n\ntemplate <typename T>\nbool EighCPUKernel<T>::Launch(const std::vector<AddressPtr> &inputs, const std::vector<AddressPtr> &workspace,\n                              const std::vector<AddressPtr> &outputs) {\n  CHECK_KERNEL_INPUTS_NUM(inputs.size(), kInputsNum, kernel_name_);\n  CHECK_KERNEL_OUTPUTS_NUM(outputs.size(), kOutputsNum, kernel_name_);\n\n  auto A_addr = reinterpret_cast<T *>(inputs[0]->addr);\n  // is the Matrix a symmetric matrix(0, all, general matxi, -1 lower triangle, 1 upper triangle)\n  auto symmetric_type = reinterpret_cast<bool *>(inputs[1]->addr);\n  auto output_addr = reinterpret_cast<T *>(outputs[0]->addr);\n  auto output_v_addr = reinterpret_cast<T *>(outputs[1]->addr);\n  Map<MatrixSquare<T>> A(A_addr, m_, m_);\n  Map<MatrixSquare<T>> A_(A_addr, m_, m_);\n  Map<MatrixSquare<T>> output(output_addr, m_, 1);\n  Map<MatrixSquare<T>> outputv(output_v_addr, m_, m_);\n  // selfadjoint matrix\n  if (*symmetric_type) {\n    A_ = A.template selfadjointView<Lower>();\n  } else {\n    A_ = A.template selfadjointView<Upper>();\n  }\n  // Real scalar eigen solver\n  if constexpr (std::is_same_v<T, float>) {\n    SolveSelfAdjointMatrix(A_, &output, &outputv, compute_eigen_vectors);\n  } else if constexpr (std::is_same_v<T, double>) {\n    SolveSelfAdjointMatrix(A_, &output, &outputv, compute_eigen_vectors);\n  } else {\n    // complex eigen solver\n    SolveComplexMatrix(A_, &output, &outputv, compute_eigen_vectors);\n  }\n  return true;\n}\n}  // namespace kernel\n}  // namespace mindspore\n", "meta": {"hexsha": "17ef369cd0a4e27b24e3f6db834fea774d89540e", "size": 4464, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mindspore/ccsrc/backend/kernel_compiler/cpu/eigen/eigh_cpu_kernel.cc", "max_stars_repo_name": "LaiYongqiang/mindspore", "max_stars_repo_head_hexsha": "1b7a38ccd86b55af50a0ea55c7f2f43813ed3e0e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-19T14:21:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T14:21:45.000Z", "max_issues_repo_path": "mindspore/ccsrc/backend/kernel_compiler/cpu/eigen/eigh_cpu_kernel.cc", "max_issues_repo_name": "LaiYongqiang/mindspore", "max_issues_repo_head_hexsha": "1b7a38ccd86b55af50a0ea55c7f2f43813ed3e0e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mindspore/ccsrc/backend/kernel_compiler/cpu/eigen/eigh_cpu_kernel.cc", "max_forks_repo_name": "LaiYongqiang/mindspore", "max_forks_repo_head_hexsha": "1b7a38ccd86b55af50a0ea55c7f2f43813ed3e0e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2926829268, "max_line_length": 119, "alphanum_fraction": 0.7170698925, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.40768626088252297}}
{"text": "/* +------------------------------------------------------------------------+\n   |                     Mobile Robot Programming Toolkit (MRPT)            |\n   |                          https://www.mrpt.org/                         |\n   |                                                                        |\n   | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file     |\n   | See: https://www.mrpt.org/Authors - All rights reserved.               |\n   | Released under BSD License. See: https://www.mrpt.org/License          |\n   +------------------------------------------------------------------------+ */\n\n#include \"poses-precomp.h\"  // Precompiled headers\n\n#include <mrpt/bayes/CParticleFilterCapable.h>\n#include <mrpt/math/distributions.h>\n#include <mrpt/math/matrix_serialization.h>\n#include <mrpt/poses/CPointPDFSOG.h>\n#include <mrpt/poses/CPose3D.h>\n#include <mrpt/poses/CPosePDF.h>\n#include <mrpt/random.h>\n#include <mrpt/serialization/CArchive.h>\n#include <mrpt/system/os.h>\n#include <Eigen/Dense>\n\nusing namespace mrpt::poses;\nusing namespace mrpt::math;\n\nusing namespace mrpt::bayes;\nusing namespace mrpt::random;\nusing namespace mrpt::system;\nusing namespace std;\n\nIMPLEMENTS_SERIALIZABLE(CPointPDFSOG, CPosePDF, mrpt::poses)\n\n/*---------------------------------------------------------------\n\tConstructor\n  ---------------------------------------------------------------*/\nCPointPDFSOG::CPointPDFSOG(size_t nModes) : m_modes(nModes) {}\n/*---------------------------------------------------------------\n\t\t\tclear\n  ---------------------------------------------------------------*/\nvoid CPointPDFSOG::clear() { m_modes.clear(); }\n/*---------------------------------------------------------------\n\tResize\n  ---------------------------------------------------------------*/\nvoid CPointPDFSOG::resize(const size_t N) { m_modes.resize(N); }\n/*---------------------------------------------------------------\n\t\t\t\t\t\tgetMean\n  Returns an estimate of the pose, (the mean, or mathematical expectation of the\n PDF)\n ---------------------------------------------------------------*/\nvoid CPointPDFSOG::getMean(CPoint3D& p) const\n{\n\tsize_t N = m_modes.size();\n\tdouble X = 0, Y = 0, Z = 0;\n\n\tif (N)\n\t{\n\t\tCListGaussianModes::const_iterator it;\n\t\tdouble sumW = 0;\n\n\t\tfor (it = m_modes.begin(); it != m_modes.end(); ++it)\n\t\t{\n\t\t\tdouble w;\n\t\t\tsumW += w = exp(it->log_w);\n\t\t\tX += it->val.mean.x() * w;\n\t\t\tY += it->val.mean.y() * w;\n\t\t\tZ += it->val.mean.z() * w;\n\t\t}\n\t\tif (sumW > 0)\n\t\t{\n\t\t\tX /= sumW;\n\t\t\tY /= sumW;\n\t\t\tZ /= sumW;\n\t\t}\n\t}\n\n\tp.x(X);\n\tp.y(Y);\n\tp.z(Z);\n}\n\nstd::tuple<CMatrixDouble33, CPoint3D> CPointPDFSOG::getCovarianceAndMean() const\n{\n\tsize_t N = m_modes.size();\n\n\tCMatrixDouble33 estCov;\n\tCPoint3D p;\n\tgetMean(p);\n\testCov.setZero();\n\n\tif (N)\n\t{\n\t\t// 1) Get the mean:\n\t\tdouble sumW = 0;\n\t\tauto estMean = CMatrixDouble31(p);\n\n\t\tCListGaussianModes::const_iterator it;\n\n\t\tfor (it = m_modes.begin(); it != m_modes.end(); ++it)\n\t\t{\n\t\t\tdouble w;\n\t\t\tsumW += w = exp(it->log_w);\n\n\t\t\tauto estMean_i = CMatrixDouble31(it->val.mean);\n\t\t\testMean_i -= estMean;\n\n\t\t\tauto partCov =\n\t\t\t\tCMatrixDouble33(estMean_i.asEigen() * estMean_i.transpose());\n\t\t\tpartCov += it->val.cov;\n\t\t\tpartCov *= w;\n\t\t\testCov += partCov;\n\t\t}\n\n\t\tif (sumW != 0) estCov *= (1.0 / sumW);\n\t}\n\n\treturn {estCov, p};\n}\n\nuint8_t CPointPDFSOG::serializeGetVersion() const { return 1; }\nvoid CPointPDFSOG::serializeTo(mrpt::serialization::CArchive& out) const\n{\n\tuint32_t N = m_modes.size();\n\tout << N;\n\tfor (const auto& m : m_modes)\n\t{\n\t\tout << m.log_w;\n\t\tout << m.val.mean;\n\t\tmrpt::math::serializeSymmetricMatrixTo(m.val.cov, out);\n\t}\n}\nvoid CPointPDFSOG::serializeFrom(\n\tmrpt::serialization::CArchive& in, uint8_t version)\n{\n\tswitch (version)\n\t{\n\t\tcase 0:\n\t\tcase 1:\n\t\t{\n\t\t\tuint32_t N;\n\t\t\tin >> N;\n\t\t\tthis->resize(N);\n\t\t\tfor (auto& m : m_modes)\n\t\t\t{\n\t\t\t\tin >> m.log_w;\n\n\t\t\t\t// In version 0, weights were linear!!\n\t\t\t\tif (version == 0) m.log_w = log(max(1e-300, m.log_w));\n\n\t\t\t\tin >> m.val.mean;\n\t\t\t\tmrpt::math::deserializeSymmetricMatrixFrom(m.val.cov, in);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tMRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version);\n\t};\n}\n\nvoid CPointPDFSOG::copyFrom(const CPointPDF& o)\n{\n\tMRPT_START\n\n\tif (this == &o) return;  // It may be used sometimes\n\n\tif (o.GetRuntimeClass() == CLASS_ID(CPointPDFSOG))\n\t{\n\t\tm_modes = dynamic_cast<const CPointPDFSOG*>(&o)->m_modes;\n\t}\n\telse\n\t{\n\t\t// Approximate as a mono-modal gaussian pdf:\n\t\tthis->resize(1);\n\t\tm_modes[0].log_w = 0;\n\t\to.getCovarianceAndMean(m_modes[0].val.cov, m_modes[0].val.mean);\n\t}\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tsaveToTextFile\n  ---------------------------------------------------------------*/\nbool CPointPDFSOG::saveToTextFile(const std::string& file) const\n{\n\tFILE* f = os::fopen(file.c_str(), \"wt\");\n\tif (!f) return false;\n\n\tfor (const auto& m_mode : m_modes)\n\t\tos::fprintf(\n\t\t\tf, \"%e %e %e %e %e %e %e %e %e %e\\n\", exp(m_mode.log_w),\n\t\t\tm_mode.val.mean.x(), m_mode.val.mean.y(), m_mode.val.mean.z(),\n\t\t\tm_mode.val.cov(0, 0), m_mode.val.cov(1, 1), m_mode.val.cov(2, 2),\n\t\t\tm_mode.val.cov(0, 1), m_mode.val.cov(0, 2), m_mode.val.cov(1, 2));\n\tos::fclose(f);\n\treturn true;\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tchangeCoordinatesReference\n ---------------------------------------------------------------*/\nvoid CPointPDFSOG::changeCoordinatesReference(const CPose3D& newReferenceBase)\n{\n\tfor (auto& m : m_modes) m.val.changeCoordinatesReference(newReferenceBase);\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\tdrawSingleSample\n ---------------------------------------------------------------*/\nvoid CPointPDFSOG::drawSingleSample(CPoint3D& outSample) const\n{\n\tMRPT_START\n\n\tASSERT_(m_modes.size() > 0);\n\n\t// 1st: Select a mode with a probability proportional to its weight:\n\tvector<double> logWeights(m_modes.size());\n\tvector<size_t> outIdxs;\n\tvector<double>::iterator itW;\n\tCListGaussianModes::const_iterator it;\n\tfor (it = m_modes.begin(), itW = logWeights.begin(); it != m_modes.end();\n\t\t ++it, ++itW)\n\t\t*itW = it->log_w;\n\n\tCParticleFilterCapable::computeResampling(\n\t\tCParticleFilter::prMultinomial,  // Resampling algorithm\n\t\tlogWeights,  // input: log weights\n\t\toutIdxs  // output: indexes\n\t);\n\n\t// we need just one: take the first (arbitrary)\n\tsize_t selectedIdx = outIdxs[0];\n\tASSERT_(selectedIdx < m_modes.size());\n\tconst CPointPDFGaussian* selMode = &m_modes[selectedIdx].val;\n\n\t// 2nd: Draw a position from the selected Gaussian:\n\tCVectorDouble vec;\n\tgetRandomGenerator().drawGaussianMultivariate(vec, selMode->cov);\n\n\tASSERT_(vec.size() == 3);\n\toutSample.x(selMode->mean.x() + vec[0]);\n\toutSample.y(selMode->mean.y() + vec[1]);\n\toutSample.z(selMode->mean.z() + vec[2]);\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\tbayesianFusion\n ---------------------------------------------------------------*/\nvoid CPointPDFSOG::bayesianFusion(\n\tconst CPointPDF& p1_, const CPointPDF& p2_,\n\tconst double minMahalanobisDistToDrop)\n{\n\tMRPT_START\n\n\t// p1: CPointPDFSOG, p2: CPosePDFGaussian:\n\n\tASSERT_(p1_.GetRuntimeClass() == CLASS_ID(CPointPDFSOG));\n\tASSERT_(p2_.GetRuntimeClass() == CLASS_ID(CPointPDFSOG));\n\n\tconst auto* p1 = dynamic_cast<const CPointPDFSOG*>(&p1_);\n\tconst auto* p2 = dynamic_cast<const CPointPDFSOG*>(&p2_);\n\n\t// Compute the new kernel means, covariances, and weights after multiplying\n\t// to the Gaussian \"p2\":\n\tCPointPDFGaussian auxGaussianProduct, auxSOG_Kernel_i;\n\n\tfloat minMahalanobisDistToDrop2 = square(minMahalanobisDistToDrop);\n\n\tthis->m_modes.clear();\n\tbool is2D =\n\t\tfalse;  // to detect & avoid errors in 3x3 matrix inversions of range=2.\n\n\tfor (const auto& m : p1->m_modes)\n\t{\n\t\tCMatrixDouble33 c = m.val.cov;\n\n\t\t// Is a 2D covariance??\n\t\tif (c(2, 2) == 0)\n\t\t{\n\t\t\tis2D = true;\n\t\t\tc(2, 2) = 1;\n\t\t}\n\n\t\tASSERT_(c(0, 0) != 0 && c(0, 0) != 0);\n\n\t\tconst CMatrixDouble33 covInv = c.inverse_LLt();\n\n\t\tEigen::Vector3d eta = covInv * CMatrixDouble31(m.val.mean);\n\n\t\t// Normal distribution canonical form constant:\n\t\t// See: http://www-static.cc.gatech.edu/~wujx/paper/Gaussian.pdf\n\t\tdouble a = -0.5 * (3 * log(M_2PI) - log(covInv.det()) +\n\t\t\t\t\t\t   (eta.transpose() * c.asEigen() * eta)(0, 0));\n\n\t\tfor (const auto& m2 : p2->m_modes)\n\t\t{\n\t\t\tauxSOG_Kernel_i = m2.val;\n\t\t\tif (auxSOG_Kernel_i.cov(2, 2) == 0)\n\t\t\t{\n\t\t\t\tauxSOG_Kernel_i.cov(2, 2) = 1;\n\t\t\t\tis2D = true;\n\t\t\t}\n\t\t\tASSERT_(\n\t\t\t\tauxSOG_Kernel_i.cov(0, 0) > 0 && auxSOG_Kernel_i.cov(1, 1) > 0);\n\n\t\t\t// Should we drop this product term??\n\t\t\tbool reallyComputeThisOne = true;\n\t\t\tif (minMahalanobisDistToDrop > 0)\n\t\t\t{\n\t\t\t\t// Approximate (fast) mahalanobis distance (square):\n\t\t\t\tfloat mahaDist2;\n\n\t\t\t\tfloat stdX2 = max(auxSOG_Kernel_i.cov(0, 0), m.val.cov(0, 0));\n\t\t\t\tmahaDist2 =\n\t\t\t\t\tsquare(auxSOG_Kernel_i.mean.x() - m.val.mean.x()) / stdX2;\n\n\t\t\t\tfloat stdY2 = max(auxSOG_Kernel_i.cov(1, 1), m.val.cov(1, 1));\n\t\t\t\tmahaDist2 +=\n\t\t\t\t\tsquare(auxSOG_Kernel_i.mean.y() - m.val.mean.y()) / stdY2;\n\n\t\t\t\tif (!is2D)\n\t\t\t\t{\n\t\t\t\t\tfloat stdZ2 =\n\t\t\t\t\t\tmax(auxSOG_Kernel_i.cov(2, 2), m.val.cov(2, 2));\n\t\t\t\t\tmahaDist2 +=\n\t\t\t\t\t\tsquare(auxSOG_Kernel_i.mean.z() - m.val.mean.z()) /\n\t\t\t\t\t\tstdZ2;\n\t\t\t\t}\n\n\t\t\t\treallyComputeThisOne = mahaDist2 < minMahalanobisDistToDrop2;\n\t\t\t}\n\n\t\t\tif (reallyComputeThisOne)\n\t\t\t{\n\t\t\t\tauxGaussianProduct.bayesianFusion(auxSOG_Kernel_i, m.val);\n\n\t\t\t\t// ----------------------------------------------------------------------\n\t\t\t\t// The new weight is given by:\n\t\t\t\t//\n\t\t\t\t//   w'_i = w_i * exp( a + a_i - a' )\n\t\t\t\t//\n\t\t\t\t//      a = -1/2 ( dimensionality * log(2pi) - log(det(Cov^-1))\n\t\t\t\t//      + (Cov^-1 * mu)^t * Cov^-1 * (Cov^-1 * mu) )\n\t\t\t\t//\n\t\t\t\t// ----------------------------------------------------------------------\n\t\t\t\tTGaussianMode newKernel;\n\n\t\t\t\tnewKernel.val = auxGaussianProduct;  // Copy mean & cov\n\n\t\t\t\tCMatrixDouble33 covInv_i = auxSOG_Kernel_i.cov.inverse_LLt();\n\t\t\t\tEigen::Vector3d eta_i =\n\t\t\t\t\tCMatrixDouble31(auxSOG_Kernel_i.mean).asEigen();\n\t\t\t\teta_i = covInv_i.asEigen() * eta_i;\n\n\t\t\t\tCMatrixDouble33 new_covInv_i = newKernel.val.cov.inverse_LLt();\n\t\t\t\tEigen::Vector3d new_eta_i =\n\t\t\t\t\tCMatrixDouble31(newKernel.val.mean).asEigen();\n\t\t\t\tnew_eta_i = new_covInv_i.asEigen() * new_eta_i;\n\n\t\t\t\tdouble a_i =\n\t\t\t\t\t-0.5 * (3 * log(M_2PI) - log(new_covInv_i.det()) +\n\t\t\t\t\t\t\t(eta_i.transpose() * auxSOG_Kernel_i.cov.asEigen() *\n\t\t\t\t\t\t\t eta_i)(0, 0));\n\t\t\t\tdouble new_a_i =\n\t\t\t\t\t-0.5 * (3 * log(M_2PI) - log(new_covInv_i.det()) +\n\t\t\t\t\t\t\t(new_eta_i.transpose() *\n\t\t\t\t\t\t\t newKernel.val.cov.asEigen() * new_eta_i)(0, 0));\n\n\t\t\t\tnewKernel.log_w = m.log_w + m2.log_w + a + a_i - new_a_i;\n\n\t\t\t\t// Fix 2D case:\n\t\t\t\tif (is2D) newKernel.val.cov(2, 2) = 0;\n\n\t\t\t\t// Add to the results (in \"this\") the new kernel:\n\t\t\t\tthis->m_modes.push_back(newKernel);\n\t\t\t}  // end if reallyComputeThisOne\n\t\t}  // end for it2\n\n\t}  // end for it1\n\n\tnormalizeWeights();\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tenforceCovSymmetry\n ---------------------------------------------------------------*/\nvoid CPointPDFSOG::enforceCovSymmetry()\n{\n\tMRPT_START\n\t// Differences, when they exist, appear in the ~15'th significant\n\t//  digit, so... just take one of them arbitrarily!\n\tfor (auto& m_mode : m_modes)\n\t{\n\t\tm_mode.val.cov(0, 1) = m_mode.val.cov(1, 0);\n\t\tm_mode.val.cov(0, 2) = m_mode.val.cov(2, 0);\n\t\tm_mode.val.cov(1, 2) = m_mode.val.cov(2, 1);\n\t}\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tnormalizeWeights\n ---------------------------------------------------------------*/\nvoid CPointPDFSOG::normalizeWeights()\n{\n\tMRPT_START\n\n\tif (!m_modes.size()) return;\n\n\tCListGaussianModes::iterator it;\n\tdouble maxW = m_modes[0].log_w;\n\tfor (it = m_modes.begin(); it != m_modes.end(); ++it)\n\t\tmaxW = max(maxW, it->log_w);\n\n\tfor (it = m_modes.begin(); it != m_modes.end(); ++it) it->log_w -= maxW;\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tESS\n ---------------------------------------------------------------*/\ndouble CPointPDFSOG::ESS() const\n{\n\tMRPT_START\n\tCListGaussianModes::const_iterator it;\n\tdouble cum = 0;\n\n\t/* Sum of weights: */\n\tdouble sumLinearWeights = 0;\n\tfor (it = m_modes.begin(); it != m_modes.end(); ++it)\n\t\tsumLinearWeights += exp(it->log_w);\n\n\t/* Compute ESS: */\n\tfor (it = m_modes.begin(); it != m_modes.end(); ++it)\n\t\tcum += square(exp(it->log_w) / sumLinearWeights);\n\n\tif (cum == 0)\n\t\treturn 0;\n\telse\n\t\treturn 1.0 / (m_modes.size() * cum);\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tevaluatePDFInArea\n ---------------------------------------------------------------*/\nvoid CPointPDFSOG::evaluatePDFInArea(\n\tfloat x_min, float x_max, float y_min, float y_max, float resolutionXY,\n\tfloat z, CMatrixD& outMatrix, bool sumOverAllZs)\n{\n\tMRPT_START\n\n\tASSERT_(x_max > x_min);\n\tASSERT_(y_max > y_min);\n\tASSERT_(resolutionXY > 0);\n\n\tconst auto Nx = (size_t)ceil((x_max - x_min) / resolutionXY);\n\tconst auto Ny = (size_t)ceil((y_max - y_min) / resolutionXY);\n\toutMatrix.setSize(Ny, Nx);\n\n\tfor (size_t i = 0; i < Ny; i++)\n\t{\n\t\tconst float y = y_min + i * resolutionXY;\n\t\tfor (size_t j = 0; j < Nx; j++)\n\t\t{\n\t\t\tfloat x = x_min + j * resolutionXY;\n\t\t\toutMatrix(i, j) = evaluatePDF(CPoint3D(x, y, z), sumOverAllZs);\n\t\t}\n\t}\n\n\tMRPT_END\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tevaluatePDF\n ---------------------------------------------------------------*/\ndouble CPointPDFSOG::evaluatePDF(const CPoint3D& x, bool sumOverAllZs) const\n{\n\tif (!sumOverAllZs)\n\t{\n\t\t// Normal evaluation:\n\t\tauto X = CMatrixDouble31(x);\n\t\tdouble ret = 0;\n\n\t\tCMatrixDouble31 MU;\n\n\t\tfor (const auto& m_mode : m_modes)\n\t\t{\n\t\t\tMU = CMatrixDouble31(m_mode.val.mean);\n\t\t\tret += exp(m_mode.log_w) * math::normalPDF(X, MU, m_mode.val.cov);\n\t\t}\n\n\t\treturn ret;\n\t}\n\telse\n\t{\n\t\t// Only X,Y:\n\t\tCMatrixD X(2, 1), MU(2, 1), COV(2, 2);\n\t\tdouble ret = 0;\n\n\t\tX(0, 0) = x.x();\n\t\tX(1, 0) = x.y();\n\n\t\tfor (const auto& m_mode : m_modes)\n\t\t{\n\t\t\tMU(0, 0) = m_mode.val.mean.x();\n\t\t\tMU(1, 0) = m_mode.val.mean.y();\n\n\t\t\tCOV(0, 0) = m_mode.val.cov(0, 0);\n\t\t\tCOV(1, 1) = m_mode.val.cov(1, 1);\n\t\t\tCOV(0, 1) = COV(1, 0) = m_mode.val.cov(0, 1);\n\n\t\t\tret += exp(m_mode.log_w) * math::normalPDF(X, MU, COV);\n\t\t}\n\n\t\treturn ret;\n\t}\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tgetMostLikelyMode\n ---------------------------------------------------------------*/\nvoid CPointPDFSOG::getMostLikelyMode(CPointPDFGaussian& outVal) const\n{\n\tif (this->empty())\n\t{\n\t\toutVal = CPointPDFGaussian();\n\t}\n\telse\n\t{\n\t\tauto it_best = m_modes.end();\n\t\tfor (auto it = m_modes.begin(); it != m_modes.end(); ++it)\n\t\t\tif (it_best == m_modes.end() || it->log_w > it_best->log_w)\n\t\t\t\tit_best = it;\n\n\t\toutVal = it_best->val;\n\t}\n}\n\n/*---------------------------------------------------------------\n\t\t\t\t\t\tgetAs3DObject\n ---------------------------------------------------------------*/\n// void  CPointPDFSOG::getAs3DObject( mrpt::opengl::CSetOfObjects::Ptr\t&outObj\n// )\n// const\n//{\n//\t// For each gaussian node\n//\tfor (CListGaussianModes::const_iterator it = m_modes.begin(); it!=\n// m_modes.end();++it)\n//\t{\n//\t\topengl::CEllipsoid::Ptr obj =\n// std::make_shared<opengl::CEllipsoid>();\n//\n//\t\tobj->setPose( it->val.mean);\n//\t\tobj->setCovMatrix(it->val.cov,  it->val.cov(2,2)==0  ?  2:3);\n//\n//\t\tobj->setQuantiles(3);\n//\t\tobj->enableDrawSolid3D(false);\n//\t\tobj->setColor(1,0,0, 0.5);\n//\n//\t\toutObj->insert( obj );\n//\t} // end for each gaussian node\n//}\n", "meta": {"hexsha": "679e5dc82c98aad3d959f1f62bf1c4b98beb2326", "size": 15470, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/poses/src/CPointPDFSOG.cpp", "max_stars_repo_name": "NewProggie/mrpt", "max_stars_repo_head_hexsha": "4929a1d066c5e9295e50150f38d7f1f64d8964ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-10T06:24:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T06:24:08.000Z", "max_issues_repo_path": "libs/poses/src/CPointPDFSOG.cpp", "max_issues_repo_name": "YangZhengShi/mrpt", "max_issues_repo_head_hexsha": "836b840ab63f4cf22c43989930ffb4d6b130a95f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/poses/src/CPointPDFSOG.cpp", "max_forks_repo_name": "YangZhengShi/mrpt", "max_forks_repo_head_hexsha": "836b840ab63f4cf22c43989930ffb4d6b130a95f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1880492091, "max_line_length": 80, "alphanum_fraction": 0.5436328378, "num_tokens": 4595, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.40768625396732744}}
{"text": "#pragma once\n\n#include <deal.II/base/numbers.h>\n// // system includes --------------------------------------------------------\n#include <cmath>\n\n#include \"base/numbers.hpp\"\n#include \"enum/enum.hpp\"\n#include \"moment_base.hpp\"\n#include \"quadrature/qmidpoint.hpp\"\n#include \"quadrature/quad_handler1d.hpp\"\n#include \"quadrature/quadrature_handler.hpp\"\n#include \"spectral/basis/spectral_elem_accessor.hpp\"\n#include \"spectral/basis/toolbox/spectral_basis.hpp\"\n\nnamespace boltzmann {\n\nclass Energy : public MomentBase\n{\n public:\n  Energy() {}\n\n  // ------------------------------------------------------------\n  template <typename SPECTRAL_BASIS>\n  Energy(const SPECTRAL_BASIS& spectral_basis)\n  {\n    init(spectral_basis);\n  }\n\n  // ------------------------------------------------------------\n  template <typename SPECTRAL_BASIS>\n  void init(const SPECTRAL_BASIS& spectral_basis);\n\n  /**\n   * @brief compute energy\n   *\n   * @param dst\n   * @param src\n   * @param count #physical dofs\n   */\n  void compute(double* dst, const double* src, int count) const;\n\n  // ------------------------------------------------------------\n  double compute(const double* src) const;\n\n  // ------------------------------------------------------------\n  template <typename VEC_IN, typename VEC_OUT, typename INDEXER>\n  void compute(VEC_OUT& dst,\n               const VEC_IN& src,\n               const dealii::IndexSet& relevant_phys_dofs,\n               const INDEXER& indexer) const\n  {\n    // some g++ cannot see this function inherited from MomentBase\n    MomentBase::compute(dst, src, relevant_phys_dofs, indexer);\n  }\n\n private:\n  using MomentBase::entry_t;\n  using MomentBase::n_velo_dofs;\n  using MomentBase::contributions;\n};\n\n// ------------------------------------------------------------\ntemplate <typename SPECTRAL_BASIS>\nvoid\nEnergy::init(const SPECTRAL_BASIS& spectral_basis)\n{\n  n_velo_dofs = spectral_basis.n_dofs();\n\n  typedef typename std::tuple_element<1, typename SPECTRAL_BASIS::elem_t::container_t>::type\n      radial_elem_t;\n\n  typedef typename std::tuple_element<0, typename SPECTRAL_BASIS::elem_t::container_t>::type\n      angular_elem_t;\n\n  auto& QR_handler = QuadHandler<MaxwellQuadrature>::GetInstance();\n  typedef QuadAdaptor<MaxwellQuadrature> qr_adapt;\n\n  unsigned int nqR = spectral::get_max_k(spectral_basis) + 2;\n  Eigen::VectorXd pts_qR(nqR);\n  Eigen::VectorXd wts_qR(nqR);\n\n  qr_adapt::apply(pts_qR.data(), wts_qR.data(), QR_handler.get(nqR), 0.5);\n\n  typedef typename SPECTRAL_BASIS::elem_t elem_t;\n  for (auto it = spectral_basis.begin(); it != spectral_basis.end(); ++it) {\n    typename elem_t::Acc::template get<radial_elem_t> getter;\n    typename elem_t::Acc::template get<angular_elem_t> geta;\n\n    if (geta(*it).get_id().l != 0) continue;\n\n    const auto& rr = getter(*it);\n    const double w = rr.w();\n\n    if (std::abs(w - 0.5) > 1e-10)\n      throw std::runtime_error(\"Error: wrong element weight in Energy::init\");\n\n    double sum = 0;\n    for (unsigned int q = 0; q < pts_qR.size(); ++q) {\n      const double r = pts_qR[q];\n      sum += rr.evaluate(r) * r * r * wts_qR[q];\n    }\n    const unsigned int i = it - spectral_basis.begin();\n    contributions.push_back(std::make_pair(i, 2 * numbers::PI * sum));\n  }\n}\n\n// ------------------------------------------------------------\nvoid\nEnergy::compute(double* dst, const double* src, int count) const\n{\n#pragma omp parallel for\n  for (int i = 0; i < count; ++i) {\n    const double* local_src = src + i * n_velo_dofs;\n    double sum = 0;\n    for (unsigned int j = 0; j < contributions.size(); ++j) {\n      sum += contributions[j].second * local_src[contributions[j].first];\n    }\n    dst[i] = sum;\n  }\n}\n\n// ------------------------------------------------------------\ndouble\nEnergy::compute(const double* src) const\n{\n  double sum = 0.0;\n  for (unsigned int j = 0; j < contributions.size(); ++j) {\n    sum += contributions[j].second * src[contributions[j].first];\n  }\n  return sum;\n}\n\n}  // end namespace boltzmann\n", "meta": {"hexsha": "86846808b60f37dfba61054ffa81aee830c4fce8", "size": 3983, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/post_processing/energy.hpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/post_processing/energy.hpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/post_processing/energy.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5037037037, "max_line_length": 92, "alphanum_fraction": 0.5960331408, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484143, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.40768625396732744}}
{"text": "#pragma once\n/**\n\n   @file FishSchool.hpp\n   @brief Fish school simulator with deterministic motion equations.\n\n*/\n\n#include <atomic>\n#include <chrono>\n#include <cinttypes>\n#include <memory>\n\n#include <boost/statechart/detail/memory.hpp>\n#include <boost/statechart/fifo_scheduler.hpp>\n#include <boost/statechart/event_base.hpp>\n\n#include <yaml-cpp/yaml.h>\n\n#ifdef _MSC_VER\n#pragma warning(push, 0)\n#endif\n#include <dds/pub/Publisher.hpp>\n#include <dds/sub/Subscriber.hpp>\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include <mimir/IAlgorithm.hpp>\n\nnamespace mimir\n{\n  namespace algorithm\n  {\n    /**\n       @brief Kinematic fish school simulation model.\n\n       \\rst\n\n       This class implements a simple kinematic fish school, which can be controlled by\n       its inputs. The fish school is modelled as a 5 degrees of freedom kinematic\n       body. It has a three dimensional position represented in an inertial reference\n       frame, \\{NED\\}, with axes pointing North, East, and Down, respectively. The body\n       can rotate about its y-axis -- pitch: :math:`\\theta`, and z-axis -- yaw:\n       :math:`\\psi`. The fish school is modeled as an under-actuated entity, meaning that\n       it can only change forward speed (surge) and its angular velocities. The input to\n       the simulation model are surge :math:`u`, rate of turn :math:`r`, and desired depth\n       :math:`D_d`. The desired depth is achieved with a first order response using pitch\n       angular velocity as manipulated variable. The commanded surge and rate of turn is\n       immidiate, i.e. there is no dynamic response. Let us define some quantities to\n       describe the fish school with an ordinary differential equation.\n\n       .. math::\n          :nowrap:\n\n          \\begin{align}\n            \\boldsymbol{p} = \\begin{bmatrix}N\\\\E\\\\D\\\\\\end{bmatrix} &\\in \\mathbb{R}^3 &\\text{position}\\\\\n            \\boldsymbol{\\Theta} = \\begin{bmatrix}\\theta\\\\\\psi\\end{bmatrix} &\\in \\mathbb{S}^2 &\\text{attitude}\\\\\n            \\boldsymbol{v} = \\begin{bmatrix}u\\\\v\\\\w\\end{bmatrix} &\\in \\mathbb{R}^3 &\\text{linear velocity}\\\\\n            \\boldsymbol{w} = \\begin{bmatrix}p\\\\q\\\\r\\\\\\end{bmatrix} &\\in \\mathbb{R}^3 &\\text{angular velocity}\\\\\n            D_d &\\in \\mathbb{R} &\\text{desired depth} \\\\\n            \\boldsymbol{\\eta}(t) = \\begin{bmatrix}\\boldsymbol{p}\\\\\\Theta\\end{bmatrix}, &\\quad\\mathbb{R} \\to \\mathbb{R}^3 \\times \\mathbb{S}^2&\\text{state vector}\n          \\end{align}\n\n       Let :math:`R_y(\\theta), R_z(\\psi) \\in SO(3)` be rotation matrixes, so that\n       :math:`R(\\boldsymbol{\\eta})` is the chained rotation defined as follows:\n\n       .. math::\n          :nowrap:\n\n          \\begin{align*}\n            R_y(\\theta) &= \\left[\\begin{array}{ccc}\\cos(\\theta)&0 &\\sin(\\theta)\\\\0&1&0\\\\-\\sin(\\theta)&0&\\cos(\\theta) \\end{array} \\right] \\\\\n            R_z(\\psi) &= \\left[\\begin{array}{ccc}\\cos(\\psi)&-\\sin(\\psi)&0\\\\\\sin(\\psi)&\\cos(\\psi)&0\\\\0&0&1 \\end{array} \\right]\\\\\n            R(\\boldsymbol{\\eta}) &= R_z(\\psi)R_y(\\theta) \\\\\n          \\end{align*}\n\n       We then use the angular velocity transformation :math:`T(\\theta)` as defined in\n       :cite:`Fossen2011` and the combined state vector transformation\n       :math:`J(\\boldsymbol{\\eta})` for our 5-dimensional system becomes:\n\n       .. math::\n          :nowrap:\n\n          \\begin{align*}\n            T(\\theta) &= \\left[\\begin{array}{cc}1&0\\\\0& \\frac{1}{\\cos(\\theta)}\\end{array} \\right] \\\\\n            J(\\boldsymbol{\\eta}) &= \\left[\\begin{array}{cc}R(\\boldsymbol{\\eta})&0\\\\0& T(\\theta)\\end{array} \\right] \\\\\n          \\end{align*}\n\n       The depth response has a proportional feedback on depth error and a stabilizing\n       term to level out the pitch: :math:`q_d = 0.1(D - D_d)\\cos(2\\theta) - \\theta`. The\n       resulting ordinary differential equation and input vector are, respectively,\n\n       .. math::\n          :nowrap:\n\n          \\begin{align*}\n            \\dat \\eta(t) &= J(\\boldsymbol{\\eta}) \\begin{bmatrix}v\\\\q_d\\\\q\\end{bmatrix} \\\\\n            u(t_d) &= \\begin{bmatrix}v_d\\\\r_d\\\\Z_d\\end{bmatrix},\n          \\end{align*}\n\n       where :math:`t_d` indicates discrete time points indicated by ``time_step_ms`` in\n       the YAML config.\n\n       The table below describes the inputs, outputs and parameters of the\n       algorithm. These variables are specified using the YAML configuration file defined\n       further below.\n\n       +----------------+----------------------------+-------------------------------------+---------------+----------------+----------------------+-----------------+\n       | Name           | Symbol                     | Description                         | Causality     | Variability    | Default              | Unit            |\n       +================+============================+=====================================+===============+================+======================+=================+\n       | ``fish_ctrl``  | :math:`u`                  | Desired: Surge, rate of turn, depth | ``input``     | ``discrete``   | \\                    | [m/s, rad/s, m] |\n       +----------------+----------------------------+-------------------------------------+---------------+----------------+----------------------+-----------------+\n       | ``kinematics`` | :math:`y`                  | ``fkin::Kinematics6D``              | ``output``    | ``continuous`` | \\                    | \\               |\n       +----------------+----------------------------+-------------------------------------+---------------+----------------+----------------------+-----------------+\n       | ``position``   | :math:`p_{p,0}`            | Initial; North, East, Down          | ``parameter`` | ``fixed``      | :math:`[0, 100, 50]` | m               |\n       +----------------+----------------------------+-------------------------------------+---------------+----------------+----------------------+-----------------+\n       | ``euler``      | :math:`[\\theta_0, \\psi_0]` | Initial; Pitch, Yaw                 | ``parameter`` | ``fixed``      | :math:`[0,0]`        | rad             |\n       +----------------+----------------------------+-------------------------------------+---------------+----------------+----------------------+-----------------+\n\n       .. warning::\n\n          This numerical model is DEPRECATED in favor of a more detailed model with\n          stochastic behavior defined using FMI :cite:`fmi2`. Nevertheless, it may serve\n          as an example on how to implement a simple :cpp:class:`mimir::IAlgorithm`.\n\n       \\endrst\n\n    */\n    class FishSchool : public IAlgorithm\n    {\n    public:\n      /**\n         @brief FishSchool constructor.\n\n         The constructor parses the specification from the given YAML\n         node. It establishes data structures and sets up DDS readers\n         and writers according to the input/output scheme of the\n         algorithm. The following YAML code block shows the expected\n         layout of the ``FishSchool`` map of a input config file.  The\n         inputs, outputs, and initial conditions are communicated with\n         DDS communication. Common is their DDS topic and DDS\n         identifier. The specification is deemed self-explanatory.\n\n         \\rst\n\n         .. code-block:: yaml\n\n             time_step_ms: 200\n             inputs:\n               fish_ctrl:                # DDS type: fkin::IdVec3d\n                 topic: fkinFishCtrl\n                 id: Fish\n                 max_age_ms: -1\n             outputs:                    # DDS type: fkin::Kinematics6D\n               kinematics:\n                 topic: fkinKinematics6D\n                 id: Fish\n             initial_conditions:\n               position:                 # DDS type: fkin::IdVec3d\n                 topic: fkinPosition\n                 id: FishInit\n                 max_wait_ms: 80\n                 fallback: [0, 100, 50]\n               euler:                    # DDS type: fkin::IdVec3d\n                 topic: fkinEuler\n                 id: FishInit\n                 max_wait_ms: 80\n                 fallback: [0, 0, 0]\n\n         \\endrst\n\n         @param [in] config YAML configuration from input file.\n         @param [in] scheduler State machine scheduler, needed to post events to state machine.\n         @param [in] machine State machine processor handle, needed to post events to state machine.\n         @param publisher DDS data writer to send data.\n         @param subscriber DDS data reader to receive data.\n      */\n      explicit FishSchool(\n          const YAML::Node& config,\n          boost::statechart::fifo_scheduler<>& scheduler,\n          boost::statechart::fifo_scheduler<>::processor_handle machine,\n          dds::pub::Publisher publisher,\n          dds::sub::Subscriber subscriber);\n      /// Destructor.\n      virtual ~FishSchool();\n      /**\n         See base class for details.\n\n         \\rst\n         The algorithm uses CVODES from SUNDIALS :cite:`Hindmarsh2005sundials`.\n         \\endrst\n      */\n      virtual void solve(const std::atomic<bool>& cancel_token);\n      /// See base class.\n      virtual void initialize(const std::atomic<bool>& cancel_token);\n      /// See base class.\n      virtual void timer(const std::atomic<bool>& cancel_token);\n      /// Name identifier of algorithm.\n      virtual inline const char* name() { return \"FishSchool\"; }\n      /// Helper function that queues event to state machine.\n      void event(boost::statechart::event_base * const event);\n\n    private:\n      /// March simulation time one time step ahead.\n      inline void step_time() { m_next_step += m_time_step; }\n      FishSchool() = delete;\n      class Impl;\n      std::unique_ptr<Impl> m_impl; ///< Holds the implementation of the algorithm.\n      boost::statechart::fifo_scheduler<> & m_scheduler; ///< Members for state machine.\n      boost::statechart::fifo_scheduler<>::processor_handle m_stateMachine; ///< Member for state machine.\n      const std::chrono::milliseconds m_time_step; ///< Discrete time step.\n      std::chrono::steady_clock::time_point m_next_step; ///< Simulation time point.\n      const YAML::Node m_config; ///< YAML configuration for algorithm.\n    };\n\n  }\n}\n", "meta": {"hexsha": "c777d684e81767bae4b38dfdcc85aa3549eb7581", "size": 10114, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mimir/algorithm/FishSchool.hpp", "max_stars_repo_name": "sintef-ocean/mimir", "max_stars_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mimir/algorithm/FishSchool.hpp", "max_issues_repo_name": "sintef-ocean/mimir", "max_issues_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mimir/algorithm/FishSchool.hpp", "max_forks_repo_name": "sintef-ocean/mimir", "max_forks_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.3944954128, "max_line_length": 166, "alphanum_fraction": 0.5312438204, "num_tokens": 2393, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.4076453434323969}}
{"text": "/*-----------------------------------------------------------------------------+\nInterval Container Library\nAuthor: Joachim Faulhaber\nCopyright (c) 2007-2009: Joachim Faulhaber\nCopyright (c) 1999-2006: Cortex Software GmbH, Kantstrasse 57, Berlin\n+------------------------------------------------------------------------------+\n   Distributed under the Boost Software License, Version 1.0.\n      (See accompanying file LICENCE.txt or copy at\n           http://www.boost.org/LICENSE_1_0.txt)\n+-----------------------------------------------------------------------------*/\n\n/** Example boost_party.cpp \\file boost_party.cpp\n    \\brief Generates an attendance history of a party by inserting into an interval_map.\n           Demonstrating <i>aggregate on overlap</i>.\n\n    boost_party.cpp demonstrates the possibilities of an interval map\n    (interval_map or split_interval_map). Boost::posix_time::ptime is used as time\n    parameter. An interval_map maps intervals to a given content. In this case the\n    content is a set of party guests represented by their name strings.\n\n    As time goes by, groups of people join the party and leave later in the evening.\n    So we add a time interval and a name set to the interval_map for the attendance\n    of each group of people, that come together and leave together.\n\n    On every overlap of intervals, the corresponding name sets are accumulated. At\n    the points of overlap the intervals are split. The accumulation of content on\n    overlap of intervals is done via an operator += that has to be implemented\n    for the content parameter of the interval_map.\n\n    Finally the interval_map contains the history of attendance and all points in\n    time, where the group of party guests changed.\n\n    boost_party.cpp demonstrates a principle that we call\n    <b><em>aggregate on overlap</em></b>:\n    On insertion a value associated to the interval is aggregated (added) to those\n    values in the interval_map that overlap with the inserted value.\n\n    There are two behavioral aspects to <b>aggregate on overlap</b>: a <em>decompositional\n    behavior</em> and a <em>accumulative behavior</em>.\n\n    The <em>decompositional behavior</em> splits up intervals on the time dimension of the\n    interval_map so that the intervals change whenever associated values\n    change.\n\n    The <em>accumulative behavior</em> accumulates associated values on every overlap of\n    an insertion for the associated values.\n\n    \\include boost_party_/boost_party.cpp\n*/\n//[example_boost_party\n// The next line includes <boost/date_time/posix_time/posix_time.hpp>\n// and a few lines of adapter code.\n#include <boost/icl/ptime.hpp>\n#include <iostream>\n#include <boost/icl/interval_map.hpp>\n\nusing namespace std;\nusing namespace boost::posix_time;\nusing namespace boost::icl;\n\n// Type set<string> collects the names of party guests. Since std::set is\n// a model of the itl's set concept, the concept provides an operator +=\n// that performs a set union on overlap of intervals.\ntypedef std::set<string> GuestSetT;\n\nvoid boost_party()\n{\n    GuestSetT mary_harry;\n    mary_harry.insert(\"Mary\");\n    mary_harry.insert(\"Harry\");\n\n    GuestSetT diana_susan;\n    diana_susan.insert(\"Diana\");\n    diana_susan.insert(\"Susan\");\n\n    GuestSetT peter;\n    peter.insert(\"Peter\");\n\n    // A party is an interval map that maps time intervals to sets of guests\n    interval_map<ptime, GuestSetT> party;\n\n    party.add( // add and element\n      make_pair(\n        interval<ptime>::right_open(\n          time_from_string(\"2008-05-20 19:30\"),\n          time_from_string(\"2008-05-20 23:00\")),\n        mary_harry));\n\n    party += // element addition can also be done via operator +=\n      make_pair(\n        interval<ptime>::right_open(\n          time_from_string(\"2008-05-20 20:10\"),\n          time_from_string(\"2008-05-21 00:00\")),\n        diana_susan);\n\n    party +=\n      make_pair(\n        interval<ptime>::right_open(\n          time_from_string(\"2008-05-20 22:15\"),\n          time_from_string(\"2008-05-21 00:30\")),\n        peter);\n\n\n    interval_map<ptime, GuestSetT>::iterator it = party.begin();\n    cout << \"----- History of party guests -------------------------\\n\";\n    while(it != party.end())\n    {\n        interval<ptime>::type when = it->first;\n        // Who is at the party within the time interval 'when' ?\n        GuestSetT who = (*it++).second;\n        cout << when << \": \" << who << endl;\n    }\n\n}\n\n\nint main()\n{\n    cout << \">>Interval Container Library: Sample boost_party.cpp <<\\n\";\n    cout << \"-------------------------------------------------------\\n\";\n    boost_party();\n    return 0;\n}\n\n// Program output:\n/*-----------------------------------------------------------------------------\n>>Interval Container Library: Sample boost_party.cpp <<\n-------------------------------------------------------\n----- History of party guests -------------------------\n[2008-May-20 19:30:00, 2008-May-20 20:10:00): Harry Mary\n[2008-May-20 20:10:00, 2008-May-20 22:15:00): Diana Harry Mary Susan\n[2008-May-20 22:15:00, 2008-May-20 23:00:00): Diana Harry Mary Peter Susan\n[2008-May-20 23:00:00, 2008-May-21 00:00:00): Diana Peter Susan\n[2008-May-21 00:00:00, 2008-May-21 00:30:00): Peter\n-----------------------------------------------------------------------------*/\n//]\n", "meta": {"hexsha": "e7ca771e11cf8e8ebca1da8ff67b846bf10b5efe", "size": 5292, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/icl/example/boost_party_/boost_party.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/icl/example/boost_party_/boost_party.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/icl/example/boost_party_/boost_party.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 38.6277372263, "max_line_length": 90, "alphanum_fraction": 0.6237717309, "num_tokens": 1227, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.6791787121629466, "lm_q1q2_score": 0.40763515689753793}}
{"text": "#ifndef SM_EIGEN_MATRIX_SQRT_HPP\n#define SM_EIGEN_MATRIX_SQRT_HPP\n\n#include <sm/assert_macros.hpp>\n#include <Eigen/Cholesky>\n\nnamespace sm {\n    namespace eigen {\n        \n        /** \n         * \\brief Compute the square root of a matrix using the LDLt decomposition for square, positive semidefinite matrices\n         *\n         * To reconstruct the input matrix, \\f$ \\mathbf A \\f$, from the returned matrix, \\f$ \\mathbf S \\f$,\n         * use, \\f$ \\mathbf A = \\mathbf S \\mathbf S^T \\f$.\n         * \n         * \n         * @param inMatrix      The square matrix whose square root should be computed.\n         * @param outMatrixSqrt The output square root.\n         */\n        template<typename DERIVED1, typename DERIVED2>\n        /*Eigen::ComputationInfo*/ void computeMatrixSqrt(const Eigen::MatrixBase<DERIVED1> & inMatrix,\n                                                          const Eigen::MatrixBase<DERIVED2> & outMatrixSqrt)\n        {\n            SM_ASSERT_EQ_DBG(std::runtime_error, inMatrix.rows(), inMatrix.cols(), \"This method is only valid for square input matrices\");\n            \n            DERIVED2 & result = const_cast<DERIVED2 &>(outMatrixSqrt.derived());\n\n            // This is tricky. Using the output matrix type causes the input matrix\n            // type to be upgraded to a real numeric matrix. This is useful if, \n            // for example, the inMatrix is something like Eigen::Matrix3d::Identity(),\n            // which is not an actual matrix. Using DERIVED1 as the template argument\n            // in that case will cause a firestorm of compiler errors.\n            Eigen::LDLT< DERIVED2 > ldlt(inMatrix.derived());\n            result = ldlt.matrixL();\n            result = ldlt.transpositionsP().transpose() * result;\n            result *= ldlt.vectorD().array().sqrt().matrix().asDiagonal();\n            \n            //return ldlt.info();\n            \n        }\n\n    } // namespace eigen\n} // namespace sm\n\n#endif /* SM_EIGEN_MATRIX_SQRT_HPP */\n", "meta": {"hexsha": "01048fabea30d9576b170d6bd1445504e0c22879", "size": 1984, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_eigen/include/sm/eigen/matrix_sqrt.hpp", "max_stars_repo_name": "PushyamiKaveti/kalibr", "max_stars_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 2690.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T03:50:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:27:01.000Z", "max_issues_repo_path": "Schweizer-Messer/sm_eigen/include/sm/eigen/matrix_sqrt.hpp", "max_issues_repo_name": "PushyamiKaveti/kalibr", "max_issues_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 481.0, "max_issues_repo_issues_event_min_datetime": "2015-01-27T10:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:02:41.000Z", "max_forks_repo_path": "Schweizer-Messer/sm_eigen/include/sm/eigen/matrix_sqrt.hpp", "max_forks_repo_name": "PushyamiKaveti/kalibr", "max_forks_repo_head_hexsha": "d8bdfc59ee666ef854012becc93571f96fe5d80c", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 1091.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T21:21:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:55:33.000Z", "avg_line_length": 43.1304347826, "max_line_length": 138, "alphanum_fraction": 0.6013104839, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.40763514910255944}}
{"text": "#include \"teca_integrated_water_vapor.h\"\n\n#include \"teca_cartesian_mesh.h\"\n#include \"teca_array_collection.h\"\n#include \"teca_variant_array.h\"\n#include \"teca_metadata.h\"\n#include \"teca_coordinate_util.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <cmath>\n\n#if defined(TECA_HAS_BOOST)\n#include <boost/program_options.hpp>\n#endif\n\nusing std::string;\nusing std::vector;\nusing std::cerr;\nusing std::endl;\nusing std::cos;\n\n//#define TECA_DEBUG\n\nnamespace {\ntemplate <typename coord_t, typename num_t>\nvoid cartesian_iwv(unsigned long nx, unsigned long ny, unsigned long nz,\n    const coord_t *plev, const num_t *q, num_t *iwv)\n{\n    unsigned long nxy = nx*ny;\n\n    // initialize the result\n    memset(iwv, 0, nxy*sizeof(num_t));\n\n    // work an x-y slice at  a time\n    unsigned long nzm1 = nz - 1;\n    for (unsigned long k = 0; k < nzm1; ++k)\n    {\n        // dp over the slice\n        num_t h2 = num_t(0.5) * (plev[k+1] - plev[k]);\n\n        // the current two x-y-planes of data\n        unsigned long knxy = k*nxy;\n        const num_t *q_k0 = q + knxy;\n        const num_t *q_k1 = q_k0 + nxy;\n\n        // accumulate this plane of data using trapazoid rule\n        for (unsigned long i = 0; i < nxy; ++i)\n        {\n            iwv[i] += h2 * (q_k0[i] + q_k1[i]);\n        }\n    }\n\n    // check the sign, in this way we can handle both increasing and decreasing\n    // pressure coordinates\n    num_t s = plev[1] - plev[0] < num_t(0) ? num_t(-1) : num_t(1);\n\n    // scale by -1/g\n    num_t m1g = s/num_t(9.80665);\n    for (unsigned long i = 0; i < nxy; ++i)\n        iwv[i] *= m1g;\n}\n\ntemplate <typename coord_t, typename num_t>\nvoid cartesian_iwv(unsigned long nx, unsigned long ny, unsigned long nz,\n    const coord_t *plev, const num_t *q, const char *q_valid, num_t *iwv)\n{\n    unsigned long nxy = nx*ny;\n\n    // initialize the result\n    memset(iwv, 0, nxy*sizeof(num_t));\n\n    // work an x-y slice at a time\n    unsigned long nzm1 = nz - 1;\n    for (unsigned long k = 0; k < nzm1; ++k)\n    {\n        // dp over the slice\n        num_t h2 = num_t(0.5) * (plev[k+1] - plev[k]);\n\n        // the current two x-y-planes of data\n        unsigned long knxy = k*nxy;\n        const num_t *q_k0 = q + knxy;\n        const num_t *q_k1 = q_k0 + nxy;\n\n        const char *q_valid_k0 = q_valid + knxy;\n        const char *q_valid_k1 = q_valid_k0 + nxy;\n\n        // accumulate this plane of data using trapazoid rule\n        for (unsigned long i = 0; i < nxy; ++i)\n        {\n            iwv[i] += ((q_valid_k0[i] && q_valid_k1[i]) ?\n               h2 * (q_k0[i] + q_k1[i]) : num_t(0));\n        }\n    }\n\n    // check the sign, in this way we can handle both increasing and decreasing\n    // pressure coordinates\n    num_t s = plev[1] - plev[0] < num_t(0) ? num_t(-1) : num_t(1);\n\n    // scale by -1/g\n    num_t m1g = s/num_t(9.80665);\n    for (unsigned long i = 0; i < nxy; ++i)\n        iwv[i] *= m1g;\n}\n}\n\n// --------------------------------------------------------------------------\nteca_integrated_water_vapor::teca_integrated_water_vapor() :\n    specific_humidity_variable(\"Q\"), iwv_variable(\"IWV\"),\n    fill_value(1.0e20)\n{\n    this->set_number_of_input_connections(1);\n    this->set_number_of_output_ports(1);\n}\n\n// --------------------------------------------------------------------------\nteca_integrated_water_vapor::~teca_integrated_water_vapor()\n{}\n\n#if defined(TECA_HAS_BOOST)\n// --------------------------------------------------------------------------\nvoid teca_integrated_water_vapor::get_properties_description(\n    const string &prefix, options_description &global_opts)\n{\n    options_description opts(\"Options for \"\n        + (prefix.empty()?\"teca_integrated_water_vapor\":prefix));\n\n    opts.add_options()\n        TECA_POPTS_GET(std::string, prefix, specific_humidity_variable,\n            \"name of the variable containg the specific humidity\")\n        TECA_POPTS_GET(double, prefix, fill_value,\n            \"the value of the NetCDF _FillValue attribute\")\n        ;\n\n    this->teca_algorithm::get_properties_description(prefix, opts);\n\n    global_opts.add(opts);\n}\n\n// --------------------------------------------------------------------------\nvoid teca_integrated_water_vapor::set_properties(\n    const string &prefix, variables_map &opts)\n{\n    this->teca_algorithm::set_properties(prefix, opts);\n\n    TECA_POPTS_SET(opts, std::string, prefix, specific_humidity_variable)\n    TECA_POPTS_SET(opts, double, prefix, fill_value)\n}\n#endif\n\n// --------------------------------------------------------------------------\nteca_metadata teca_integrated_water_vapor::get_output_metadata(\n    unsigned int port,\n    const std::vector<teca_metadata> &input_md)\n{\n#ifdef TECA_DEBUG\n    std::cerr << teca_parallel_id()\n        << \"teca_integrated_water_vapor::get_output_metadata\" << std::endl;\n#endif\n    (void)port;\n\n    // set things up in the first pass, and don't modify in subsequent passes\n    // due to threading concerns\n\n    if (this->get_number_of_derived_variables() == 0)\n    {\n        // the base class will handle dealing with the transformation of\n        // mesh dimensions and reporting the array we produce, but we have\n        // to determine the data type and tell the name of the produced array.\n        const teca_metadata &md = input_md[0];\n\n        teca_metadata attributes;\n        if (md.get(\"attributes\", attributes))\n        {\n            TECA_FATAL_ERROR(\"Failed to determine output data type \"\n                \"because attributes are misisng\")\n            return teca_metadata();\n        }\n\n        teca_metadata hus_atts;\n        if (attributes.get(this->specific_humidity_variable, hus_atts))\n        {\n            TECA_FATAL_ERROR(\"Failed to determine output data type \"\n                \"because attributes for \\\"\" << this->specific_humidity_variable\n                << \"\\\" are misisng\")\n            return teca_metadata();\n        }\n\n        int type_code = 0;\n        if (hus_atts.get(\"type_code\", type_code))\n        {\n            TECA_FATAL_ERROR(\"Failed to determine output data type \"\n                \"because attributes for \\\"\" << this->specific_humidity_variable\n                << \"\\\" is misisng a \\\"type_code\\\"\")\n            return teca_metadata();\n        }\n\n        teca_array_attributes iwv_atts(\n            type_code, teca_array_attributes::point_centering,\n            0, \"kg m^{-1} s^{-1}\", \"longitudinal integrated vapor transport\",\n            \"the longitudinal component of integrated vapor transport\",\n            1, this->fill_value);\n\n\n        // install name and attributes of the output variables in the base classs\n        this->append_derived_variable(this->iwv_variable);\n        this->append_derived_variable_attribute(iwv_atts);\n    }\n\n    if (this->get_number_of_dependent_variables() == 0)\n    {\n        // install the names of the input variables in the base class\n        this->append_dependent_variable(this->specific_humidity_variable);\n    }\n\n    // invoke the base class method, which does the work of transforming\n    // the mesh and reporting the variables and their attributes.\n    return teca_vertical_reduction::get_output_metadata(port, input_md);\n}\n\n// --------------------------------------------------------------------------\nstd::vector<teca_metadata> teca_integrated_water_vapor::get_upstream_request(\n    unsigned int port,\n    const std::vector<teca_metadata> &input_md,\n    const teca_metadata &request)\n{\n    // invoke the base class method\n    return teca_vertical_reduction::get_upstream_request(port, input_md, request);\n}\n\n// --------------------------------------------------------------------------\nconst_p_teca_dataset teca_integrated_water_vapor::execute(\n    unsigned int port,\n    const std::vector<const_p_teca_dataset> &input_data,\n    const teca_metadata &request)\n{\n#ifdef TECA_DEBUG\n    std::cerr << teca_parallel_id()\n        << \"teca_integrated_water_vapor::execute\" << std::endl;\n#endif\n    (void)port;\n\n    // get the input mesh\n    const_p_teca_cartesian_mesh in_mesh\n        = std::dynamic_pointer_cast<const teca_cartesian_mesh>(input_data[0]);\n\n    if (!in_mesh)\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IWV because a cartesian mesh is required.\")\n        return nullptr;\n    }\n\n    // get the input dimensions\n    unsigned long extent[6] = {0};\n    if (in_mesh->get_extent(extent))\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IWV because mesh extent is missing.\")\n        return nullptr;\n    }\n\n    unsigned long nx = extent[1] - extent[0] + 1;\n    unsigned long ny = extent[3] - extent[2] + 1;\n    unsigned long nz = extent[5] - extent[4] + 1;\n\n    // get the pressure coordinates\n    const_p_teca_variant_array p = in_mesh->get_z_coordinates();\n    if (!p)\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IWV because pressure coordinates are missing\")\n        return nullptr;\n    }\n\n    if (p->size() < 2)\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IWV because z dimensions \"\n            << p->size() << \" < 2 as required by the integration method\")\n        return nullptr;\n    }\n\n    // gather the input arrays\n    const_p_teca_variant_array q =\n        in_mesh->get_point_arrays()->get(this->specific_humidity_variable);\n\n    if (!q)\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IWV because specific humidity \\\"\"\n            << this->specific_humidity_variable << \"\\\" is missing\")\n        return nullptr;\n    }\n\n    const_p_teca_variant_array q_valid =\n           in_mesh->get_point_arrays()->get(this->specific_humidity_variable + \"_valid\");\n\n    // the base class will construct the output mesh\n    p_teca_cartesian_mesh out_mesh\n        = std::dynamic_pointer_cast<teca_cartesian_mesh>(\n            std::const_pointer_cast<teca_dataset>(\n                teca_vertical_reduction::execute(port, input_data, request)));\n\n    if (!out_mesh)\n    {\n        TECA_FATAL_ERROR(\"Failed to compute IWV because the output mesh was \"\n            \"not constructed\")\n        return nullptr;\n    }\n\n    // allocate the output arrays\n    unsigned long nxy = nx*ny;\n    p_teca_variant_array iwv = q->new_instance(nxy);\n\n    // store the result\n    out_mesh->get_point_arrays()->set(this->iwv_variable, iwv);\n\n    // calculate IWV\n    NESTED_TEMPLATE_DISPATCH_FP(const teca_variant_array_impl,\n        p.get(), _COORDS,\n\n        const NT_COORDS *p_p = static_cast<TT_COORDS*>(p.get())->get();\n\n        NESTED_TEMPLATE_DISPATCH_FP(teca_variant_array_impl,\n            iwv.get(), _DATA,\n\n            NT_DATA *p_iwv = static_cast<TT_DATA*>(iwv.get())->get();\n\n            const NT_DATA *p_q = static_cast<const TT_DATA*>(q.get())->get();\n\n            const char *p_q_valid = nullptr;\n            if (q_valid)\n            {\n                using TT_MASK = teca_char_array;\n\n                p_q_valid = dynamic_cast<const TT_MASK*>(q_valid.get())->get();\n\n                ::cartesian_iwv(nx, ny, nz, p_p, p_q, p_q_valid, p_iwv);\n            }\n            else\n            {\n                ::cartesian_iwv(nx, ny, nz, p_p, p_q, p_iwv);\n            }\n            )\n        )\n\n    // pass 2D arrays through.\n    p_teca_array_collection in_arrays =\n        std::const_pointer_cast<teca_array_collection>(in_mesh->get_point_arrays());\n\n    p_teca_array_collection out_arrays = out_mesh->get_point_arrays();\n\n    int n_arrays = in_arrays->size();\n    for (int i = 0; i < n_arrays; ++i)\n    {\n        p_teca_variant_array array = in_arrays->get(i);\n        if (array->size() == nxy)\n        {\n            // pass the array.\n            out_arrays->append(in_arrays->get_name(i), array);\n        }\n    }\n\n    return out_mesh;\n}\n", "meta": {"hexsha": "5d7f759110698b21333d09dedda8e1ad63285e84", "size": 11556, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "alg/teca_integrated_water_vapor.cxx", "max_stars_repo_name": "LBL-EESA/TECA", "max_stars_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-03-28T14:22:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T05:02:25.000Z", "max_issues_repo_path": "alg/teca_integrated_water_vapor.cxx", "max_issues_repo_name": "LBL-EESA/TECA", "max_issues_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL"], "max_issues_count": 476.0, "max_issues_repo_issues_event_min_datetime": "2016-11-28T18:06:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-25T05:31:42.000Z", "max_forks_repo_path": "alg/teca_integrated_water_vapor.cxx", "max_forks_repo_name": "LBL-EESA/TECA", "max_forks_repo_head_hexsha": "63923b8a12914f3758dc9525239bc48cd8864b39", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2017-04-25T18:15:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-28T18:16:05.000Z", "avg_line_length": 31.8347107438, "max_line_length": 90, "alphanum_fraction": 0.6066112842, "num_tokens": 2867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791786991753929, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.4076351491025594}}
{"text": "#include \"util/statistics.hpp\"\n\n#include <map>\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/density.hpp>\n#include <boost/accumulators/statistics/tail_quantile.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/error_of.hpp>\n#include <boost/accumulators/statistics/error_of_mean.hpp>\n#include <boost/accumulators/statistics/variance.hpp>\nusing namespace boost::accumulators;\n\nstatic uint32_t handles = 0;\nstatic std::map<uint32_t, void *> db;\n\ntypedef accumulator_set<double, stats<tag::mean, tag::error_of<tag::mean>, tag::variance(lazy) > > stat_mean_t;\n\ntypedef accumulator_set<double, stats<tag::density > > stat_histo_t;\ntypedef boost::iterator_range<std::vector<std::pair<double, double> >::iterator > stat_histo_iter_t;\n\ntypedef accumulator_set<double, stats<tag::tail_quantile<left> > > stat_tail_left_t;\ntypedef accumulator_set<double, stats<tag::tail_quantile<right> > > stat_tail_right_t;\n\nuint32_t init_mean_stat() {\n  db[handles] = (void *)(new stat_mean_t());\n  return handles++;\n}\n\nuint32_t init_histo_stat(uint32_t binN, uint32_t cacheS) {\n  db[handles] = (void *)(new stat_histo_t(tag::density::num_bins = binN,\n                                             tag::density::cache_size = cacheS));\n  return handles++;\n}\n\nuint32_t init_tail_stat(bool dir, uint32_t cacheS) {\n  if(dir)\n    db[handles] = (void *)(new stat_tail_left_t(tag::tail<left>::cache_size = cacheS));\n  else\n    db[handles] = (void *)(new stat_tail_right_t(tag::tail<right>::cache_size = cacheS));\n  return handles++;\n}\n\nvoid record_mean_stat(uint32_t handle, double sample) {\n  assert(db.count(handle));\n  stat_mean_t *stat = (stat_mean_t *)(db[handle]);\n  (*stat)(sample);\n}\n\nvoid record_histo_stat(uint32_t handle, double sample) {\n  assert(db.count(handle));\n  stat_histo_t *stat = (stat_histo_t *)(db[handle]);\n  (*stat)(sample);\n}\n\nvoid record_tail_stat(uint32_t handle, bool dir, double sample) {\n  assert(db.count(handle));\n  if(dir) {\n    stat_tail_right_t *stat = (stat_tail_right_t *)(db[handle]);\n    (*stat)(sample);\n  } else {\n    stat_tail_left_t *stat = (stat_tail_left_t *)(db[handle]);\n    (*stat)(sample);\n  }\n}\n\nuint32_t get_mean_count(uint32_t handle) {\n  assert(db.count(handle));\n  stat_mean_t *stat = (stat_mean_t *)(db[handle]);\n  return count(*stat);\n}\n\ndouble get_mean_mean(uint32_t handle) {\n  assert(db.count(handle));\n  stat_mean_t *stat = (stat_mean_t *)(db[handle]);\n  return mean(*stat);\n}\n\ndouble get_mean_error(uint32_t handle) {\n  assert(db.count(handle));\n  stat_mean_t *stat = (stat_mean_t *)(db[handle]);\n  return error_of<tag::mean>(*stat);\n}\n\ndouble get_mean_variance(uint32_t handle) {\n  assert(db.count(handle));\n  stat_mean_t *stat = (stat_mean_t *)(db[handle]);\n  return variance(*stat);\n}\n\nuint32_t get_histo_count(uint32_t handle) {\n  assert(db.count(handle));\n  stat_histo_t *stat = (stat_histo_t *)(db[handle]);\n  return count(*stat);\n}\n\nstd::vector<std::pair<double, double> > get_histo_density(uint32_t handle) {\n  assert(db.count(handle));\n  stat_histo_t *stat = (stat_histo_t *)(db[handle]);\n  stat_histo_iter_t hist = density(*stat);\n  std::vector<std::pair<double, double> > rv(hist.size());\n  for(uint32_t i=0; i<hist.size(); i++) rv[i] = hist[i];\n  return rv;\n}\n\ndouble get_tail_quantile(uint32_t handle, bool dir, double ratio) {\n  assert(db.count(handle));\n  if(dir) {\n    stat_tail_right_t *stat = (stat_tail_right_t *)(db[handle]);\n    assert(ratio >= 0.5);\n    return quantile(*stat, quantile_probability = ratio);\n  } else {\n    stat_tail_left_t *stat = (stat_tail_left_t *)(db[handle]);\n    assert(ratio <= 0.5);\n    return quantile(*stat, quantile_probability = ratio);\n  }\n}\n\nvoid close_mean_stat(uint32_t handle) {\n  assert(db.count(handle));\n  stat_mean_t *stat = (stat_mean_t *)(db[handle]);\n  delete stat;\n  db.erase(handle);\n}\n\nvoid close_histo_stat(uint32_t handle) {\n  assert(db.count(handle));\n  stat_histo_t *stat = (stat_histo_t *)(db[handle]);\n  delete stat;\n  db.erase(handle);\n}\n\nvoid close_tail_stat(uint32_t handle, bool dir) {\n  assert(db.count(handle));\n  if(dir) {\n    stat_tail_right_t *stat = (stat_tail_right_t *)(db[handle]);\n    delete stat;\n  } else {\n    stat_tail_left_t *stat = (stat_tail_left_t *)(db[handle]);\n    delete stat;\n  }\n  db.erase(handle);\n}\n", "meta": {"hexsha": "eb3267a6709492959fbd61b299e0ae36167ab33d", "size": 4368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/statistics.cpp", "max_stars_repo_name": "comparch-security/smart-cache-evict", "max_stars_repo_head_hexsha": "89f7413fb3afef0c2c69012f6a19f60dabc041ab", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-06-11T11:30:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T00:44:05.000Z", "max_issues_repo_path": "util/statistics.cpp", "max_issues_repo_name": "comparch-security/smart-cache-evict", "max_issues_repo_head_hexsha": "89f7413fb3afef0c2c69012f6a19f60dabc041ab", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-14T10:24:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T08:06:54.000Z", "max_forks_repo_path": "util/statistics.cpp", "max_forks_repo_name": "comparch-security/smart-cache-evict", "max_forks_repo_head_hexsha": "89f7413fb3afef0c2c69012f6a19f60dabc041ab", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-08T03:15:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T03:15:50.000Z", "avg_line_length": 30.3333333333, "max_line_length": 111, "alphanum_fraction": 0.7039835165, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.40754545551903}}
{"text": "#include <Eigen/Dense>\n#include \"edge_labeler.h\"\n#include \"g2o/stuff/unscented.h\"\n\nnamespace g2o {\n\n  using namespace std;\n  using namespace Eigen;\n\n  typedef SigmaPoint<VectorXd> MySigmaPoint;\n\n  EdgeLabeler::EdgeLabeler(SparseOptimizer* optimizer) {\n    _optimizer = optimizer;\n  }\n\n  int EdgeLabeler::labelEdges(std::set<OptimizableGraph::Edge*>& edges){\n    // assume the system is \"solved\"\n    // compute the sparse pattern of the inverse\n    std::set<std::pair<int, int> > pattern;\n    for (std::set<OptimizableGraph::Edge*>::iterator it=edges.begin(); it!=edges.end(); it++){\n      augmentSparsePattern(pattern, *it);\n    }\n\n\n    SparseBlockMatrix<MatrixXd> spInv;\n\n    bool result = computePartialInverse(spInv, pattern);\n    //cerr << \"partial inverse computed = \" << result << endl;\n    //cerr << \"non zero blocks\" << spInv.nonZeroBlocks() << endl;\n\n    if (! result ){\n      return -1;\n    }\n    int count=0;\n    for (std::set<OptimizableGraph::Edge*>::iterator it=edges.begin(); it!=edges.end(); it++){\n      count += labelEdge(spInv, *it) ? 1 : 0;\n    }\n    return count;\n  }\n\n  void EdgeLabeler::augmentSparsePattern(std::set<std::pair<int, int> >& pattern, OptimizableGraph::Edge* e){\n    for (size_t i=0; i<e->vertices().size(); i++){\n      const OptimizableGraph::Vertex* v=(const OptimizableGraph::Vertex*) e->vertices()[i];\n      int ti=v->hessianIndex();\n      if (ti==-1)\n\tcontinue;\n      for (size_t j=i; j<e->vertices().size(); j++){\n\tconst OptimizableGraph::Vertex* v=(const OptimizableGraph::Vertex*) e->vertices()[j];\n\tint tj = v->hessianIndex();\n\tif (tj==-1)\n\t  continue;\n\tif(tj<ti)\n\t  swap(ti,tj);\n\tpattern.insert(std::make_pair(ti, tj));\n      }\n    }\n  }\n\n  bool EdgeLabeler::computePartialInverse(SparseBlockMatrix<MatrixXd>& spinv, const std::set<std::pair<int,int> >& pattern){\n    std::vector<std::pair<int, int> > blockIndices(pattern.size());\n    // Why this does not work???\n    //std::copy(pattern.begin(),pattern.end(),blockIndices.begin());\n\n    int k=0;\n    for(std::set<std::pair<int, int> >::const_iterator it= pattern.begin(); it!=pattern.end(); it++){\n      blockIndices[k++]=*it;\n    }\n\n    //cerr << \"sparse pattern contains \" << blockIndices.size() << \" blocks\" << endl;\n    return _optimizer->computeMarginals(spinv, blockIndices);\n  }\n\n  bool EdgeLabeler::labelEdge( const SparseBlockMatrix<MatrixXd>& spinv, OptimizableGraph::Edge* e){\n\n    Eigen::Map<MatrixXd> info(e->informationData(), e->dimension(), e->dimension());\n    // cerr << \"original information matrix\" << endl;\n    // cerr << info << endl;\n\n    int maxDim=0;\n    for (size_t i=0; i<e->vertices().size(); i++){\n      const OptimizableGraph::Vertex* v=(const OptimizableGraph::Vertex*) e->vertices()[i];\n      int ti=v->hessianIndex();\n      if (ti==-1)\n\tcontinue;\n      maxDim+=v->minimalEstimateDimension();\n    }\n\n\n    //cerr << \"maxDim= \" << maxDim << endl;\n    MatrixXd cov(maxDim, maxDim);\n    int cumRow=0;\n    for (size_t i=0; i<e->vertices().size(); i++){\n      const OptimizableGraph::Vertex* vr=(const OptimizableGraph::Vertex*) e->vertices()[i];\n      int ti=vr->hessianIndex();\n      if (ti>-1) {\n\tint cumCol=0;\n\tfor (size_t j=0; j<e->vertices().size(); j++){\n\t  const OptimizableGraph::Vertex* vc=(const OptimizableGraph::Vertex*) e->vertices()[j];\n\t  int tj = vc->hessianIndex();\n\t  if (tj>-1){\n\t    // cerr << \"ti=\" << ti << \" tj=\" << tj\n\t    //    << \" cumRow=\" << cumRow << \" cumCol=\" << cumCol << endl;\n\t    if (ti<=tj){\n\t      assert(spinv.block(ti, tj));\n\t      // cerr << \"cblock_ptr\" << spinv.block(ti, tj) << endl;\n\t      // cerr << \"cblock.size=\" << spinv.block(ti, tj)->rows() << \",\" << spinv.block(ti, tj)->cols() << endl;\n\t      // cerr << \"cblock\" << endl;\n\t      // cerr << *spinv.block(ti, tj) << endl;\n\t      cov.block(cumRow, cumCol, vr->minimalEstimateDimension(), vc->minimalEstimateDimension()) =\n\t\t*spinv.block(ti, tj);\n\t    } else {\n\t      assert(spinv.block(tj, ti));\n\t      // cerr << \"cblock.size=\" << spinv.block(tj, ti)->cols() << \",\" << spinv.block(tj, ti)->rows() << endl;\n\t      // cerr << \"cblock\" << endl;\n\t      // cerr << spinv.block(tj, ti)->transpose() << endl;\n\t      cov.block(cumRow, cumCol, vr->minimalEstimateDimension(), vc->minimalEstimateDimension()) =\n\t\tspinv.block(tj, ti)->transpose();\n\t    }\n\t    cumCol += vc->minimalEstimateDimension();\n\t  }\n\t}\n\tcumRow += vr->minimalEstimateDimension();\n      }\n    }\n\n    // cerr << \"covariance assembled\" << endl;\n    // cerr << cov << endl;\n    // now cov contains the aggregate marginals of the state variables in the edge\n    VectorXd incMean(maxDim);\n    incMean.fill(0);\n    std::vector<MySigmaPoint, Eigen::aligned_allocator<MySigmaPoint> > incrementPoints;\n    if (! sampleUnscented(incrementPoints, incMean, cov)){\n      cerr << \"sampleUnscented fail\" << endl;\n      return false;\n    }\n    // now determine the zero-error measure by applying the error function of the edge\n    // with a zero measurement\n    // TODO!!!\n    bool smss = e->setMeasurementFromState();\n    if (! smss) {\n      cerr << \"FATAL: Edge::setMeasurementFromState() not implemented\" << endl;\n    }\n    assert(smss && \"Edge::setMeasurementFromState() not implemented\");\n\n    //std::vector<MySigmaPoint> globalPoints(incrementPoints.size());\n    std::vector<MySigmaPoint, Eigen::aligned_allocator<MySigmaPoint> > errorPoints(incrementPoints.size());\n\n    // for each sigma point, project it to the global space, by considering those variables\n    // that are involved\n    //cerr << \"sigma points are extracted, remapping to measurement space\" << endl;\n    for (size_t i=0; i<incrementPoints.size(); i++) {\n      int cumPos=0;\n      //VectorXd globalPoint(maxDim);\n\n      // push all the \"active\" state variables\n      for (size_t j=0; j<e->vertices().size(); j++){\n        OptimizableGraph::Vertex* vr=(OptimizableGraph::Vertex*) e->vertices()[j];\n        int tj=vr->hessianIndex();\n        if (tj==-1)\n          continue;\n        vr->push();\n      }\n\n      for (size_t j=0; j<e->vertices().size(); j++){\n        OptimizableGraph::Vertex* vr=(OptimizableGraph::Vertex*) e->vertices()[j];\n        int tj=vr->hessianIndex();\n        if (tj==-1)\n          continue;\n        vr->oplus(&incrementPoints[i]._sample[cumPos]);\n        //assert(vr->getMinimalEstimateData(&globalPoint[cumPos]) && \"Vertex::getMinimalEstimateData(...) not implemented\");\n        cumPos+=vr->minimalEstimateDimension();\n      }\n\n      // construct the sigma point in the global space\n      // globalPoints[i]._sample=globalPoint;\n      // globalPoints[i]._wi=incrementPoints[i]._wi;\n      // globalPoints[i]._wp=incrementPoints[i]._wp;\n\n      // construct the sigma point in the error space\n      e->computeError();\n      Map<VectorXd> errorPoint(e->errorData(),e->dimension());\n\n      errorPoints[i]._sample=errorPoint;\n      errorPoints[i]._wi=incrementPoints[i]._wi;\n      errorPoints[i]._wp=incrementPoints[i]._wp;\n\n      // pop all the \"active\" state variables\n      for (size_t j=0; j<e->vertices().size(); j++){\n        OptimizableGraph::Vertex* vr=(OptimizableGraph::Vertex*) e->vertices()[j];\n        int tj=vr->hessianIndex();\n        if (tj==-1)\n          continue;\n        vr->pop();\n      }\n\n    }\n\n    // reconstruct the covariance of the error by the sigma points\n    MatrixXd errorCov(e->dimension(), e->dimension());\n    VectorXd errorMean(e->dimension());\n    reconstructGaussian(errorMean, errorCov, errorPoints);\n    info=errorCov.inverse();\n\n    // cerr << \"remapped information matrix\" << endl;\n    // cerr << info << endl;\n    return true;\n  }\n\n}\n", "meta": {"hexsha": "e160d85ca9ab19c63f34a4d46599d115f9d86ab8", "size": 7536, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Thirdparty/g2o/g2o/apps/g2o_hierarchical/edge_labeler.cpp", "max_stars_repo_name": "liyi2017/StructSLAM", "max_stars_repo_head_hexsha": "7eb205489d7bde30ee74b08e72d01deaa42741fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 57.0, "max_stars_repo_stars_event_min_datetime": "2018-03-11T03:35:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:39:26.000Z", "max_issues_repo_path": "Thirdparty/g2o/g2o/apps/g2o_hierarchical/edge_labeler.cpp", "max_issues_repo_name": "jyakaranda/StructSLAM", "max_issues_repo_head_hexsha": "7eb205489d7bde30ee74b08e72d01deaa42741fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-03-06T02:16:42.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-07T08:45:52.000Z", "max_forks_repo_path": "Thirdparty/g2o/g2o/apps/g2o_hierarchical/edge_labeler.cpp", "max_forks_repo_name": "jyakaranda/StructSLAM", "max_forks_repo_head_hexsha": "7eb205489d7bde30ee74b08e72d01deaa42741fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2017-07-23T11:33:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T05:35:53.000Z", "avg_line_length": 35.8857142857, "max_line_length": 124, "alphanum_fraction": 0.6177016985, "num_tokens": 2049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.40754545551903}}
{"text": "#include <graphene/singularity/scan.hpp>\n#include <queue>\n#include <boost/graph/graphviz.hpp>\n\nusing namespace boost;\nusing namespace boost::numeric::ublas;\nusing namespace singularity;\n\nscan::scan(double parameter_e, uint parameter_m) {\n    this->parameter_e = parameter_e;\n    this->parameter_m = parameter_m;\n}\n\nvoid scan::process(Graph& g) {\n    calculate_similarity(g);\n    calculate_neighbours(g);\n    find_clusters(g);\n}\n\nvoid scan::calculate_neighbours(Graph& g)\n{\n    calculate_neighbours_partial(g, range_t(0, g.m_vertices.size()));\n}\n\nvoid scan::calculate_neighbours_partial(Graph& g, range_t r) {\n    Graph::vertex_iterator current, end;\n    tie(current, end) = vertices(g);\n    for (;current != end; current++) {\n        unsigned int id = get(vertex_index, g, *current);\n        if (id >= r.start() && id < r.start() + r.size()) {\n            calculate_neighbours(g, *current);\n        }\n    }\n}\n\n\nvoid scan::calculate_neighbours(Graph& g, Graph::vertex_descriptor vertex)\n{\n    Graph::out_edge_iterator current, end;\n    tie(current, end) =  out_edges(vertex, g);\n    unsigned int neighbours_count = 0;\n    for(; current != end; current++) {\n        bool structural_similarity_is_high = get(edge_similarity_is_high, g, *current);\n        if (structural_similarity_is_high) {\n            neighbours_count++;\n        }\n    }\n    \n    bool is_core;\n    \n    if (neighbours_count >= parameter_m) {\n        is_core = true;\n    } else {\n        is_core = false;\n    }\n    put(vertex_is_core, g, vertex, is_core);\n    put(vertex_neighbour_count, g, vertex, neighbours_count);\n}\n\n\nvoid scan::calculate_similarity(Graph& g)\n{\n    calculate_similarity_partial(g, range_t(0,g.m_edges.size()));\n}\n\nvoid scan::calculate_similarity_partial(Graph& g, range_t r)\n{\n    Graph::edge_iterator current, end;\n    tie(current, end) = edges(g);\n    for (;current != end; current++) {\n        unsigned int id = get(edge_index, g, *current);\n        if (id >= r.start() && id < r.start() + r.size()) {\n            calculate_similarity(g, *current);\n        }\n    }\n}\n\nvoid scan::calculate_similarity(Graph &g, Graph::edge_descriptor link)\n{\n    double parameter_e_sq = parameter_e * parameter_e;\n    \n    Graph::vertex_descriptor v1 = source(link, g), v2 = target(link, g);\n    \n    Graph::degree_size_type v_1_N=0, v_2_N=0, v_12_N=0;\n    \n    v_1_N = out_degree(v1, g) + 1;\n    v_2_N = out_degree(v2, g) + 1;\n    v_12_N = 2;\n    \n    Graph::adjacency_iterator current_it, end_it;\n    \n    tie( current_it, end_it ) = adjacent_vertices(v1, g);\n    \n    for (; current_it < end_it; current_it++) {\n        bool found;\n        Graph::edge_descriptor link2x;\n        Graph::vertex_descriptor vx = *current_it;\n        tie(link2x, found) = edge(v2, vx, g);\n        if (found) {\n            v_12_N++;\n        }\n    }\n    \n    double similarity = (double) (v_12_N * v_12_N) / (v_1_N * v_2_N);\n\n    put(edge_similarity, g, link, similarity);\n    put(edge_similarity_is_high, g, link, similarity >= parameter_e_sq);\n}\n\nvoid scan::find_clusters(Graph& g)\n{\n    unsigned int new_cluster_id = 0;\n    \n    std::queue<Graph::vertex_descriptor> q;\n    \n    auto vertex_cluster_id_map = get(vertex_cluster_id, g);\n    auto vertex_status_map = get(vertex_status, g);\n    auto vertex_is_core_map = get(vertex_is_core, g);\n    auto edge_similarity_is_high_map = get(edge_similarity_is_high, g);\n    \n    Graph::vertex_iterator current, end;\n    \n    tie(current, end) = vertices(g);\n    \n    for ( ; current != end; current++ ) {\n        vertex_status_map[*current] = node_status_unclassified;\n    }\n\n    tie(current, end) = vertices(g);\n    \n    id_generator gen;\n    \n    for ( ; current != end; current++ ) {\n        Graph::vertex_descriptor v =  *current;\n        \n        if (vertex_status_map[v] != node_status_unclassified) {\n            continue;\n        }\n        \n        if (vertex_is_core_map[v]) {\n            new_cluster_id = gen.get_next_id();\n            vertex_cluster_id_map[v] = new_cluster_id;\n            vertex_status_map[v] = node_status_member;\n            q.push(v);\n            \n            while (q.size() > 0) {\n                Graph::vertex_descriptor y = q.front();\n                \n                if (vertex_is_core_map[y]) {\n                    Graph::out_edge_iterator current_edge, end_edge;\n                    tie(current_edge, end_edge) = out_edges(y, g);\n                    for (; current_edge != end_edge; current_edge++ ) {\n                        bool similarity_is_high = edge_similarity_is_high_map[*current_edge];\n                        if (similarity_is_high) {\n                            Graph::vertex_descriptor x = target(*current_edge, g);\n                            node_status_t status = vertex_status_map[x];\n                            if (status == node_status_unclassified || status == node_status_non_member) {\n                                vertex_cluster_id_map[x] = new_cluster_id;\n                                vertex_status_map[x] = node_status_member;\n                            }\n                            if (status == node_status_unclassified) {\n                                q.push(x);\n                            }\n                        }\n                    }\n                }\n                \n                q.pop();\n            }\n        } else {\n            vertex_status_map[v] = node_status_non_member;\n        }\n    }\n    \n    tie(current, end) = vertices(g);\n    \n    for ( ; current != end; current++ ) {\n        Graph::vertex_descriptor v =  *current;\n        node_status_t status = vertex_status_map[v];\n        if (status == node_status_non_member) {\n            new_cluster_id = gen.get_next_id();\n            vertex_cluster_id_map[v] = new_cluster_id;\n            bool cluster_is_found = false;\n            unsigned int found_cluster_id;\n            bool node_is_hub = false;\n            Graph::out_edge_iterator current_edge, end_edge;\n            tie(current_edge, end_edge) = out_edges(v, g);\n            for (; current_edge != end_edge; current_edge++ ) {\n                Graph::vertex_descriptor x = target(*current_edge, g);\n                if (vertex_status_map[x] == node_status_member) {\n                    if (!cluster_is_found) {\n                        cluster_is_found = true;\n                        found_cluster_id = vertex_cluster_id_map[x];\n                    } else {\n                        if (found_cluster_id != vertex_cluster_id_map[x]) {\n                            node_is_hub = true;\n                            break;\n                        }\n                    }\n                }\n            }\n            \n            vertex_status_map[v] = node_is_hub ? node_status_hub : node_status_outlier;\n        }\n    }\n\n    set_property(g, graph_num_clusters, new_cluster_id + 1);\n}\n\nid_generator::id_generator() {\n    init();\n}\n\n\nvoid id_generator::init() {\n    current_id = 0;\n}\n\nunsigned int id_generator::get_next_id() {\n    return current_id ++;\n}\n\nvoid scan::print_graph(Graph& g) {\n    \n//    \n//    dynamic_properties dp;\n//    \n//    \n//    Graph::vertex_iterator current, end;\n//    \n//    tie (current, end) = vertices(g);\n//    for (; current != end; current++) {\n//        unsigned int index = get(vertex_index, g, *current);\n//        unsigned int cluster_id = get(vertex_cluster_id, g, *current);\n//        node_status_t status = get(vertex_status, g, *current);\n//        std::string name; \n//        switch (status) {\n//            case node_status_member:\n//                name = std::string(\"member\");\n//                break;\n//            case node_status_hub:\n//                name = std::string(\"hub\");\n//                break;\n//            case node_status_outlier:\n//                name = std::string(\"outlier\");\n//                break;\n//            default:\n//                name = std::string(\"?\");\n//        }\n//        \n//        std::string format = std::string(\"%d (%d) %s\");\n//        put(vertex_name, g, *current, name);\n//    } \n//    \n//    dp.property(\"similarity\", boost::get(edge_similarity, g));\n//    dp.property(\"neighbours\", boost::get(vertex_neighbour_count, g));\n//    dp.property(\"node_id\", boost::get(vertex_index, g));\n//    dp.property(\"is_core\", boost::get(vertex_is_core, g));\n//    dp.property(\"cluster_id\", boost::get(vertex_cluster_id, g));\n//    dp.property(\"status\", boost::get(vertex_name, g));\n//    \n//    write_graphviz_dp(std::cout, g, dp);\n    \n    property_map<Graph, vertex_cluster_id_t>::type vertex_cluster_id_map = get(vertex_cluster_id, g);\n    property_map<Graph, vertex_index_t>::type vertex_id_map = get(vertex_index, g);\n    property_map<Graph, edge_similarity_t>::type edge_similarity_map = get(edge_similarity, g);\n    \n    dynamic_properties dp;\n    \n    dp.property(\"cluster_id\", vertex_cluster_id_map);\n    dp.property(\"id\", vertex_id_map);\n    dp.property(\"similarity\", edge_similarity_map);\n    \n    write_graphviz_dp(std::cout, g, dp, \"id\");\n}\n\n", "meta": {"hexsha": "196679de2353dac53dcf9967cb6ce79ab3368eec", "size": 8926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/singularity/singularity/scan.cpp", "max_stars_repo_name": "petrkotegov/gravity-core", "max_stars_repo_head_hexsha": "52c9a96126739c33ee0681946e1d88c5be9a6190", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-05-25T17:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-23T21:13:26.000Z", "max_issues_repo_path": "libraries/singularity/singularity/scan.cpp", "max_issues_repo_name": "petrkotegov/gravity-core", "max_issues_repo_head_hexsha": "52c9a96126739c33ee0681946e1d88c5be9a6190", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-05-25T19:44:30.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-03T11:35:27.000Z", "max_forks_repo_path": "libraries/singularity/singularity/scan.cpp", "max_forks_repo_name": "petrkotegov/gravity-core", "max_forks_repo_head_hexsha": "52c9a96126739c33ee0681946e1d88c5be9a6190", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-05-30T04:37:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-05T14:47:34.000Z", "avg_line_length": 32.2238267148, "max_line_length": 105, "alphanum_fraction": 0.5678915528, "num_tokens": 2042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4075050354572094}}
{"text": "#define DEBUG 1\n/**\n * File    : F.cpp\n * Author  : Kazune Takahashi\n * Created : 2019/12/24 20:41:23\n * Powered by Visual Studio Code\n */\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <functional>\n#include <random>\n#include <chrono>\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n// ----- boost -----\n#include <boost/rational.hpp>\n// ----- using directives and manipulations -----\nusing boost::rational;\nusing namespace std;\nusing ll = long long;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n// constexpr ll MOD{998244353LL}; // be careful\nconstexpr ll MAX_SIZE{3000010LL};\n// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n  }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n  }\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{x % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(const Mint &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(const Mint &a) { return *this += -a; }\n  Mint &operator*=(const Mint &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(const Mint &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }\n  bool operator<(const Mint &a) const { return x < a.x; }\n  bool operator<=(const Mint &a) const { return x <= a.x; }\n  bool operator>(const Mint &a) const { return x > a.x; }\n  bool operator>=(const Mint &a) const { return x >= a.x; }\n  bool operator==(const Mint &a) const { return x == a.x; }\n  bool operator!=(const Mint &a) const { return !(*this == a); }\n  const Mint power(ll N)\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n  return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)\n{\n  return Mint<MOD>{lhs} / rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n  return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n  return stream << a.x;\n}\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i = 2LL; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i = 1LL; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\n// constexpr ll infty{1000000000000000LL};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes(int i)\n{\n  cout << i << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n// ----- main() -----\n\nint H, W;\nvector<string> S;\n\nvoid stamp(int x, int y)\n{\n\n#if DEBUG == 1\n  cerr << \"stamp(\" << x << \", \" << y << \")\" << endl;\n#endif\n  for (auto i = x; i < min(H, x + H / 2); i++)\n  {\n    for (auto j = y; j < min(W, y + W / 2); j++)\n    {\n      S[i][j] = '#';\n#if DEBUG == 1\n      cerr << \"S[\" << i << \"][\" << j << \"]\" << endl;\n#endif\n    }\n  }\n}\n\nint main()\n{\n  cin >> H >> W;\n  S.resize(H);\n  for (auto i = 0; i < H; i++)\n  {\n    cin >> S[i];\n  }\n  set<int> X, Y;\n  for (auto i = 0; i < H; i++)\n  {\n    for (auto j = 0; j < W; j++)\n    {\n      if (S[i][j] == '.')\n      {\n        X.insert(i);\n        Y.insert(j);\n      }\n    }\n  }\n  if (X.empty())\n  {\n    Yes(0);\n  }\n  auto it = X.begin();\n  int ubh{*it};\n  it = X.end();\n  it--;\n  int lbh{*it};\n  it = Y.begin();\n  int ubw{*it};\n  it = Y.end();\n  it--;\n  int lbw{*it};\n  int height{lbh - ubh + 1};\n  int width{lbw - ubw + 1};\n  if (height <= H / 2 && width <= W / 2)\n  {\n    Yes(1);\n  }\n  if (height <= H / 2)\n  {\n    Yes(2);\n  }\n  if (width <= W / 2)\n  {\n    Yes(2);\n  }\n  int cnt{0};\n  for (auto k = 0; k < H + W - 1; k++)\n  {\n    for (auto i = 0; i <= k; i++)\n    {\n      auto j = k - i;\n      if (!(i < H && j < W))\n      {\n        continue;\n      }\n      if (0 <= i && i < H && 0 <= j && j < W && S[i][j] == '.')\n      {\n        ++cnt;\n        stamp(i, j);\n      }\n      auto ni = H - 1 - i;\n      auto nj = W - 1 - j;\n      if (0 <= ni && ni < H && 0 <= j && j < W && S[ni][j] == '.')\n      {\n        ++cnt;\n        stamp(ni - H / 2 + 1, j);\n      }\n      if (0 <= i && i < H && 0 <= nj && nj < W && S[i][nj] == '.')\n      {\n        ++cnt;\n        stamp(i, nj - W / 2 + 1);\n      }\n      if (0 <= ni && ni < H && 0 <= nj && nj < W && S[ni][nj] == '.')\n      {\n        ++cnt;\n        stamp(ni - H / 2 + 1, nj - W / 2 + 1);\n      }\n    }\n  }\n  if (cnt > 4)\n  {\n    assert(false);\n  }\n  cout << cnt << endl;\n}\n", "meta": {"hexsha": "707c20bd2551dddcfe1fb26d05eace3a7baab546", "size": 6283, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/1224_xmascon19/F.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2019/1224_xmascon19/F.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2019/1224_xmascon19/F.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 20.4657980456, "max_line_length": 69, "alphanum_fraction": 0.4964189082, "num_tokens": 2138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768248, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4075050354572094}}
{"text": "//=====================================================\n// File   :  ublas_interface.hh\n// Author :  L. Plagne <laurent.plagne@edf.fr)>\n// Copyright (C) EDF R&D,  lun sep 30 14:23:27 CEST 2002\n//=====================================================\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 2\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n// You should have received a copy of the GNU General Public License\n// along with this program; if not, write to the Free Software\n// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n//\n#ifndef UBLAS_INTERFACE_HH\n#define UBLAS_INTERFACE_HH\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n\nusing namespace boost::numeric;\n\ntemplate <class real>\nclass ublas_interface{\n\npublic :\n\n  typedef real real_type ;\n\n  typedef std::vector<real> stl_vector;\n  typedef std::vector<stl_vector> stl_matrix;\n\n  typedef typename boost::numeric::ublas::matrix<real,boost::numeric::ublas::column_major> gene_matrix;\n  typedef typename boost::numeric::ublas::vector<real> gene_vector;\n\n  static inline std::string name( void ) { return \"ublas\"; }\n\n  static void free_matrix(gene_matrix & A, int N) {}\n\n  static void free_vector(gene_vector & B) {}\n\n  static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){\n    A.resize(A_stl.size(),A_stl[0].size());\n    for (int j=0; j<A_stl.size() ; j++)\n      for (int i=0; i<A_stl[j].size() ; i++)\n        A(i,j)=A_stl[j][i];\n  }\n\n  static inline void vector_from_stl(gene_vector & B, stl_vector & B_stl){\n    B.resize(B_stl.size());\n    for (int i=0; i<B_stl.size() ; i++)\n      B(i)=B_stl[i];\n  }\n\n  static inline void vector_to_stl(gene_vector & B, stl_vector & B_stl){\n    for (int i=0; i<B_stl.size() ; i++)\n      B_stl[i]=B(i);\n  }\n\n  static inline void matrix_to_stl(gene_matrix & A, stl_matrix & A_stl){\n    int N=A_stl.size();\n    for (int j=0;j<N;j++)\n    {\n      A_stl[j].resize(N);\n      for (int i=0;i<N;i++)\n        A_stl[j][i]=A(i,j);\n    }\n  }\n\n  static inline void copy_vector(const gene_vector & source, gene_vector & cible, int N){\n    for (int i=0;i<N;i++){\n      cible(i) = source(i);\n    }\n  }\n\n  static inline void copy_matrix(const gene_matrix & source, gene_matrix & cible, int N){\n    for (int i=0;i<N;i++){\n      for (int j=0;j<N;j++){\n        cible(i,j) = source(i,j);\n      }\n    }\n  }\n\n  static inline void matrix_vector_product_slow(gene_matrix & A, gene_vector & B, gene_vector & X, int N){\n    X =  prod(A,B);\n  }\n\n  static inline void matrix_matrix_product_slow(gene_matrix & A, gene_matrix & B, gene_matrix & X, int N){\n    X =  prod(A,B);\n  }\n\n  static inline void axpy_slow(const real coef, const gene_vector & X, gene_vector & Y, int N){\n    Y+=coef*X;\n  }\n\n  // alias free assignments\n\n  static inline void matrix_vector_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){\n    X.assign(prod(A,B));\n  }\n\n  static inline void atv_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){\n    X.assign(prod(trans(A),B));\n  }\n\n  static inline void matrix_matrix_product(gene_matrix & A, gene_matrix & B, gene_matrix & X, int N){\n    X.assign(prod(A,B));\n  }\n\n  static inline void axpy(const real coef, const gene_vector & X, gene_vector & Y, int N){\n    Y.plus_assign(coef*X);\n  }\n\n  static inline void axpby(real a, const gene_vector & X, real b, gene_vector & Y, int N){\n    Y = a*X + b*Y;\n  }\n\n  static inline void ata_product(gene_matrix & A, gene_matrix & X, int N){\n    // X =  prod(trans(A),A);\n    X.assign(prod(trans(A),A));\n  }\n\n  static inline void aat_product(gene_matrix & A, gene_matrix & X, int N){\n    // X =  prod(A,trans(A));\n    X.assign(prod(A,trans(A)));\n  }\n\n  static inline void trisolve_lower(const gene_matrix & L, const gene_vector& B, gene_vector & X, int N){\n    X = solve(L, B, ublas::lower_tag ());\n  }\n\n};\n\n#endif\n", "meta": {"hexsha": "f59b7cf2f537802329a2f39c76063f7a039cd362", "size": 4341, "ext": "hh", "lang": "C++", "max_stars_repo_path": "tools/eigen/bench/btl/libs/ublas/ublas_interface.hh", "max_stars_repo_name": "Krissmedt/imprunko", "max_stars_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2111.0, "max_stars_repo_stars_event_min_datetime": "2019-01-29T07:01:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T06:48:14.000Z", "max_issues_repo_path": "tools/eigen/bench/btl/libs/ublas/ublas_interface.hh", "max_issues_repo_name": "Krissmedt/imprunko", "max_issues_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 131.0, "max_issues_repo_issues_event_min_datetime": "2019-02-18T10:56:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-27T12:07:00.000Z", "max_forks_repo_path": "tools/eigen/bench/btl/libs/ublas/ublas_interface.hh", "max_forks_repo_name": "Krissmedt/imprunko", "max_forks_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 421.0, "max_forks_repo_forks_event_min_datetime": "2019-02-12T07:59:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T05:22:01.000Z", "avg_line_length": 30.5704225352, "max_line_length": 106, "alphanum_fraction": 0.6463948399, "num_tokens": 1229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.407415858287152}}
{"text": "//ibd_m.cpp equivalent cpp script of ibd_m.py\n#include <boost/python.hpp>\n#include<iostream>\n#include<vector>\n#include<algorithm>\n#include<map>\n#include<string>\nusing namespace std;\ntypedef std::vector<float> VecFloat;\ntypedef std::vector<string> VecString;\ntypedef std::vector<int> VecInt;\ntypedef std::vector<int> VecInt;\ntypedef std::vector<VecInt> VecVecInt;\nVecFloat sib_ibd(VecString &geno);\nfloat prob_ibd(VecString &geno, string &allele);\nfloat cousin_ibd(VecString &geno);\nfloat un_ibd(VecString &geno); \n\nVecFloat sib_ibd(VecString &geno)\n{\n\tVecFloat ibd (3,0.0);\n\tVecVecInt inherit;\n\tstd::vector<VecVecInt> compat_inherit;\n\tfor (VecString::iterator it=geno.begin()+4; it<geno.end(); it++)\n\t{\n\t\t//for each allele in offspring\n\t\tstring sib_allele = *it;\n\t\tVecInt tmp_inheirt;\n\t\tVecString::iterator pos=geno.begin()-1;\n\t\twhile (pos != geno.begin()+4)\n\t\t{\n\t\t\tpos = std::find(pos+1,geno.begin()+4,sib_allele);\n\t\t\tif ((pos-geno.begin()) !=4){tmp_inheirt.push_back(pos-geno.begin());}\n\t\t}\n\t\tinherit.push_back(tmp_inheirt);\n\t}\n\tfor (int indiv=0; indiv<2; indiv++)\n\t{\n\t\t//for each offspring\n\t\tVecVecInt sib_inherit;\n\t\tfor (VecInt::iterator tmp_it=inherit[2*indiv].begin();tmp_it<inherit[2*indiv].end();tmp_it++)\n\t\t{\n\t\t\tfor (VecInt::iterator tmp2_it=inherit[2*indiv+1].begin();tmp2_it<inherit[2*indiv+1].end();tmp2_it++)\n\t\t\t{\n\t\t\t\tif (*tmp_it<2 && *tmp2_it>1 || *tmp_it>1 && *tmp2_it<2)\n\t\t\t\t{\n\t\t\t\t\tVecInt temp {*tmp_it,*tmp2_it};\n\t\t\t\t\tsib_inherit.push_back(temp);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcompat_inherit.push_back(sib_inherit);\n\t}\n\tfloat count[3] = {0.0,0.0,0.0};\n\tint count_sum = compat_inherit[0].size()*compat_inherit[1].size();\n\tfor (VecVecInt::iterator tmp1_it=compat_inherit[0].begin(); tmp1_it<compat_inherit[0].end(); tmp1_it++)\n\t{\n\t\t//count IBD value\n\t\tfor (VecVecInt::iterator tmp2_it=compat_inherit[1].begin(); tmp2_it<compat_inherit[1].end(); tmp2_it++)\n\t\t{\n\t\t\tint ibd_count=0;\n\t\t\tVecInt tmp_common;\n\t\t\tfor (VecInt::iterator i = tmp1_it->begin(); i != tmp1_it->begin()+2;i++)\n\t\t\t{\n\t\t\t\tif (std::find(tmp2_it->begin(),tmp2_it->begin()+2,*i) != tmp2_it->begin()+2 && geno.at(*i) != \"1\")\n\t\t\t\t{\n\t\t\t\t\ttmp_common.push_back(*i);//shared allele in [0,1,2,3]\n\t\t\t\t}\n\t\t\t}\n\t\t\tibd_count = tmp_common.size();\n\t\t\tcount[ibd_count]++;\n\t\t}\n\t}\n\tfor (int i=0; i<3; i++){ibd[i]=count[i]/count_sum;}\n\treturn ibd;\t\n}\n\nfloat prob_ibd(VecString &geno, string &allele)\n{\n\tVecInt pos;   //position of the given allele in parental genotypes\n\tVecVecInt alt_pos;\n\tfloat prob=0.0;\n\tVecString alt {\"-1\",\"-1\"};\n\tfor (auto iter=geno.begin(); iter != geno.begin()+4; iter++)\n\t{\n\t\tif (*iter == allele){pos.push_back((iter-geno.begin()));}\n\t}\n\tfor (auto iter=geno.begin()+4; iter != geno.end(); iter++)\n\t{\n\t\t//determine the alternative allele\n\t\tint tmp_pos = iter-(geno.begin()+4);\n\t\tif (*iter != allele)\n\t\t{\n\t\t\tif (tmp_pos<2){alt[0]=*iter;}\n\t\t\telse {alt[1]=*iter;}\n\t\t}\n\t\telse if (tmp_pos%2==1 && alt[tmp_pos/2]==\"-1\"){alt[tmp_pos/2]=*iter;}\n\t}\n\tVecInt altpos1, altpos2;\n\tfor (auto iter=geno.begin(); iter != geno.begin()+4; iter++)\n\t{\n\t\tif (*iter == alt[0]){altpos1.push_back((iter-geno.begin()));}\n\t\tif (*iter == alt[1]){altpos2.push_back((iter-geno.begin()));}\n\t}\n\talt_pos.push_back(altpos1);\n\talt_pos.push_back(altpos2);\n\tvector<map<int,float>> freq_map;\n\tfor (int i=0;i<2;i++)\n\t{\n\t\tmap<int,float> tmp_occurrence;\n\t\tVecInt tmp_p_compat;\n\t\tfor (auto p : pos)\n\t\t{\n\t\t\tfor (auto q : alt_pos[i])\n\t\t\t{\n\t\t\t\tif (p<2 && q>1 || p>1 && q<2){tmp_p_compat.push_back(p);}\n\t\t\t}\n\t\t}\n\t\tfor (auto tmp : tmp_p_compat)\n\t\t{\n\t\t\tfloat count = (float) 1/tmp_p_compat.size();\n\t\t\tif(tmp_occurrence.find(tmp)==tmp_occurrence.end())\n\t\t\t{\n\t\t\t\t//not in key\n\t\t\t\ttmp_occurrence[tmp]=count;\n\t\t\t}\n\t\t\telse {tmp_occurrence[tmp]+=count;}\n\t\t}\n\t\tfreq_map.push_back(tmp_occurrence);\n\t}\n\tfor (auto &it1 : freq_map[0])\n\t{\n\t\tfor (auto &it2 : freq_map[1])\n\t\t{\n\t\t\tif (it2.first==it1.first){prob+=it1.second*it2.second;}\n\t\t}\n\t}\n\treturn prob;\n}\n\nfloat cousin_ibd(VecString &geno)\n{\n\t//calculate IBD between cousins\n\t//geno = GT for [grandparents, fam1, fam2] important parent put in the first place of each family\n\tVecString ag = {geno[8],geno[9]};       //GT for 2 cousins\n\tVecString bg = {geno[14],geno[15]};\n\tVecString shared_allele;\n\tfloat total_p = 0.0;\n\tfor (auto ait : ag)\n\t{\n\t\tif (std::find(bg.begin(),bg.end(),ait) != bg.end() && ait != \"1\"){shared_allele.push_back(ait);} //possible shared RV\n\t}\n\tif (shared_allele.size()==2 && shared_allele[0]==shared_allele[1]){shared_allele.pop_back();}\n\tfor (auto a : shared_allele)\n\t{\t\n\t\tint rep=0;\n\t\tfor (auto tmp : ag)\n\t\t{\n\t\t\tfor (auto tmp1 : bg)\n\t\t\t{\n\t\t\t\tif (tmp==a && tmp1==a){rep++;}\n\t\t\t}\n\t\t}\n\t\tVecFloat f_inherit;\n\t\tint flag=0;\n\t\tfor (int fid=0; fid<2; fid++)\n\t\t{\n\t\t\tVecVecInt possible_inherit;\n\t\t\tVecString pg = {geno[fid*6+4],geno[fid*6+5],geno[fid*6+6],geno[fid*6+7]};     //parental genotypes\n\t\t\tstring alt=\"-1\";\n\t\t\tVecInt pos, pos_alt;\n\t\t\tif (fid==0)\n\t\t\t{\n\t\t\t\tfor (auto ait=ag.begin(); ait != ag.end(); ait++)\n\t\t\t\t{\n\t\t\t\t\tif (*ait != a)\n\t\t\t\t\t{\n\t\t\t\t\t\talt=*ait;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse if (ait-ag.begin()==1)\n\t\t\t\t\t{\n\t\t\t\t\t\talt=*ait;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (fid==1)\n\t\t\t{\n\t\t\t\tfor (auto bit=bg.begin(); bit != bg.end(); bit++)\n\t\t\t\t{\n\t\t\t\t\tif (*bit != a)\n\t\t\t\t\t{\n\t\t\t\t\t\talt=*bit;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse if (bit-bg.begin()==1)\n\t\t\t\t\t{\n\t\t\t\t\t\talt=*bit;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (auto it = pg.begin(); it !=pg.end(); it++)\n\t\t\t{\n\t\t\t\tif (*it == a) {pos.push_back((it-pg.begin()));}\n\t\t\t\tif (*it == alt) {pos_alt.push_back((it-pg.begin()));}\n\t\t\t}\n\t\t\tfor (auto p : pos)\n\t\t\t{\n\t\t\t\tfor (auto q : pos_alt)\n\t\t\t\t{\n\t\t\t\t\tif (p<2 && q>1 || p>1 && q<2)\n\t\t\t\t\t{\n\t\t\t\t\t\tVecInt tmp_pos={p,q};\n\t\t\t\t\t\t//cout<<p<<\" \"<<q<<endl;\n\t\t\t\t\t\tpossible_inherit.push_back(tmp_pos);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tint count=0;\n\t\t\tfor (auto inherit : possible_inherit)\n\t\t\t{\n\t\t\t\tif (inherit[0]<2){count++;}\n\t\t\t}\n\t\t\tfloat f_in;\n\t\t\tif (possible_inherit.size()>0)\n\t\t\t{\n\t\t\t\tf_in = (float)count/possible_inherit.size();\n\t\t\t}\n\t\t\telse {f_in=0;}\n\t\t\tf_inherit.push_back(f_in);\n\t\t\tif (f_in>0){flag++;}     //family having a possibility to inherit the particular allele\n\t\t\tif (flag==2)\n\t\t\t{\n\t\t\t\t//get the GT for upper nuclear family\n\t\t\t\tVecString up_gt={geno[0],geno[1],geno[2],geno[3],geno[4],geno[5],geno[10],geno[11]};  \n\t\t\t\tfloat prob = prob_ibd(up_gt,a);\n\t\t\t\ttotal_p += (f_inherit[0]*f_inherit[1]*prob)*rep;\n\t\t\t}\n\t\t\telse {total_p+=0;}\n\t\t}\n\t}\n\treturn total_p;\n}\n\nfloat un_ibd(VecString &geno)\n{\n\t//calculate IBD between Uncle-Nephew pair\n\t//geno = GT for [grandparents uncle father mother kid(nephew)]\n\tVecString Uncle_g = {geno[4],geno[5]};\n\tVecString Nephew_g = {geno[10],geno[11]};\n\tVecString pg = {geno[6],geno[7],geno[8],geno[9]};\n\tVecString gt = {geno[0],geno[1],geno[2],geno[3],geno[4],geno[5],geno[6],geno[7]};\n\tVecString shared_allele;\n\tfloat total_p=0.0;\n\tfor (auto g : Uncle_g)\n\t{\n\t\tif (std::find(Nephew_g.begin(),Nephew_g.end(),g) != Nephew_g.end() && g != \"1\")\n\t\t{\n\t\t\tshared_allele.push_back(g);\n\t\t}\n\t}\n\tif (shared_allele.size()==2 && shared_allele[0]==shared_allele[1]){shared_allele.pop_back();}\n\tfor (auto ref : shared_allele)\n\t{\n\t\tVecString tmp_alleles;\n\t\tfor (auto b : Nephew_g)\n\t\t{\n\t\t\tif (b==ref){tmp_alleles.push_back(b);}\n\t\t}\n\t\tfor (auto allele : tmp_alleles)\n\t\t{\n\t\t\tfloat f=0.0;\n\t\t\tint m=0;\n\t\t\tint n=0;\n\t\t\tstring alt=\"-1\";\n\t\t\tfor (auto bit=Nephew_g.begin(); bit != Nephew_g.end(); bit++)\n\t\t\t{\n\t\t\t\tif (*bit != ref)\n\t\t\t\t{\n\t\t\t\t\talt=*bit;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse if (bit-Nephew_g.begin()==1)\n\t\t\t\t{\n\t\t\t\t\talt=*bit;\n\t\t\t\t}\n\t\t\t}\n\t\t\tVecInt pos1,pos2;\n\t\t\tfor (auto tmp=pg.begin();tmp!=pg.end();tmp++)\n\t\t\t{\n\t\t\t\tif (*tmp==ref){pos1.push_back((tmp-pg.begin()));}\n\t\t\t\tif (*tmp==alt){pos2.push_back((tmp-pg.begin()));}\n\t\t\t}\n\t\t\tfor (auto p : pos1)\n\t\t\t{\n\t\t\t\tfor (auto q : pos2)\n\t\t\t\t{\n\t\t\t\t\tif (p<2 && q>1){m++;}\n\t\t\t\t\telse if (p>1 && q<2){n++;}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ((m+n)>0){f=(float)m/(m+n);}\n\t\t\telse{f=0;}\n\t\t\tfloat prob=0;\n\t\t\tif (f!=0)\n\t\t\t{\n\t\t\t\tprob=prob_ibd(gt,ref);\n\t\t\t}\n\t\t\tif (Uncle_g[0]==Uncle_g[1] && Uncle_g[0]==ref)\n\t\t\t{\n\t\t\t\tprob *=2;\n\t\t\t}\n\t\t\ttotal_p += f*prob;\n\t\t}\n\t}\n\treturn total_p;\n}\nboost::python::list sib_apply(boost::python::list geno_py)\n{\n\tVecString geno;\n\tVecFloat ibd;\n\tboost::python::list ibd_py;\n\tfor (int i=0; i<len(geno_py); i++)\n\t{\n\t\tboost::python::extract<int> extracted_geno(geno_py[i]);\n\t\tstring str_geno = std::to_string(extracted_geno); \n\t\tgeno.push_back(str_geno);\n\t} \n\tibd=sib_ibd(geno);\n\tfor (auto iter : ibd)\n\t{\n\t\tibd_py.append(iter);\n\t}\n\treturn ibd_py;\n}\n\nfloat prob_ibd_apply(boost::python::list geno_py,int allele)\n{\n\tVecString geno;\n\tfloat prob;\n\tstring str_allele = std::to_string(allele);\n\tfor (int i=0; i<len(geno_py); i++)\n\t{\n\t\tboost::python::extract<int> extracted_geno(geno_py[i]);\n\t\tstring str_geno = std::to_string(extracted_geno);\n\t\tgeno.push_back(str_geno);\n\t} \n\tprob = prob_ibd(geno, str_allele);\n\treturn prob;\n}\n\nfloat cousin_apply(boost::python::list geno_py)\n{\n\tVecString geno;\n\tfloat prob;\n\tfor (int i=0; i<len(geno_py); i++)\n\t{\n\t\tboost::python::extract<int> extracted_geno(geno_py[i]);\n\t\tstring str_geno = std::to_string(extracted_geno);\n\t\tgeno.push_back(str_geno);\n\t} \n\tprob = cousin_ibd(geno);\n\treturn prob;\n}\n\nfloat un_apply(boost::python::list geno_py)\n{\n\tVecString geno;\n\tfloat prob;\n\tfor (int i=0; i<len(geno_py); i++)\n\t{\n\t\tboost::python::extract<int> extracted_geno(geno_py[i]);\n\t\tstring str_geno = std::to_string(extracted_geno);\n\t\tgeno.push_back(str_geno);\n\t} \n\tprob = un_ibd(geno);\n\treturn prob;\n}\nBOOST_PYTHON_MODULE(ibd_rv_cpp){\n\tusing namespace boost::python;\n\tdef(\"sib_ibd\",sib_ibd);\n\tdef(\"sib_apply\",sib_apply);\n\tdef(\"prob_ibd_apply\",prob_ibd_apply);\n\tdef(\"cousin_apply\",cousin_apply);\n\tdef(\"un_apply\",un_apply);\n}\n\n/*int main()\n{\n\tVecString geno {\"1\",\"1\",\"2\",\"1\",\"1\",\"1\",\"2\",\"1\",\"1\",\"1\",\"1\",\"1\"};\n\tfloat prob=un_ibd(geno);\n\tcout<<\"IBD:\"<<prob<<endl;\n\treturn 0;\n}\nint main(int argc, char* argv[])\n{\n\tVecString geno;\n\tVecFloat ibd;\n\tfor (char* i=*(argv+1); *i != '\\0';i++)\n\t{\n\t\tgeno.push_back(string(1,*i));\n\t}\n\tibd=sib_ibd(geno);\n}*/\n", "meta": {"hexsha": "ad927df5d78c953c0a61fab6826c91cb65e04b16", "size": 9832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppextend/ibd_m_rv.cpp", "max_stars_repo_name": "statgenetics/rvnpl", "max_stars_repo_head_hexsha": "22053ca4e24e5486e1179a5e85aaf316a218391f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-28T12:00:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T12:00:34.000Z", "max_issues_repo_path": "cppextend/ibd_m_rv.cpp", "max_issues_repo_name": "changebio/rvnpl", "max_issues_repo_head_hexsha": "22053ca4e24e5486e1179a5e85aaf316a218391f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-03-18T02:39:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-12T08:05:24.000Z", "max_forks_repo_path": "cppextend/ibd_m_rv.cpp", "max_forks_repo_name": "changebio/rvnpl", "max_forks_repo_head_hexsha": "22053ca4e24e5486e1179a5e85aaf316a218391f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-01-26T03:22:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T14:27:51.000Z", "avg_line_length": 24.2765432099, "max_line_length": 119, "alphanum_fraction": 0.6137103336, "num_tokens": 3478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4072060266339286}}
{"text": "/* ----------------------------------------------------------------------------\n * GTDynamics Copyright 2020, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n/**\n * @file  main.cpp\n * @brief Spider trajectory optimization with pre-specified footholds.\n * @Author: Alejandro Escontrela\n * @Author: Stephanie McCormick\n * @Author: Disha Das\n * @Author: Tarushree Gandhi\n */\n\n#include <gtdynamics/dynamics/DynamicsGraph.h>\n#include <gtdynamics/dynamics/OptimizerSetting.h>\n#include <gtdynamics/factors/MinTorqueFactor.h>\n#include <gtdynamics/factors/PointGoalFactor.h>\n#include <gtdynamics/universal_robot/Robot.h>\n#include <gtdynamics/universal_robot/sdf.h>\n#include <gtdynamics/utils/DynamicsSymbol.h>\n#include <gtdynamics/utils/initialize_solution_utils.h>\n#include <gtsam/linear/NoiseModel.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n#include <gtsam/nonlinear/LevenbergMarquardtParams.h>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/slam/PriorFactor.h>\n\n#include <algorithm>\n#include <boost/algorithm/string/join.hpp>\n#include <boost/optional.hpp>\n#include <fstream>\n#include <iostream>\n#include <utility>\n\n#define GROUND_HEIGHT -1.75\n\nusing std::string;\nusing std::vector;\n\nusing gtsam::Point3;\nusing gtsam::Pose3;\nusing gtsam::Rot3;\nusing gtsam::Values;\nusing gtsam::Vector;\nusing gtsam::Vector3;\nusing gtsam::Vector6;\nusing gtsam::noiseModel::Isotropic;\n\nusing namespace gtdynamics;\n\nint main(int argc, char** argv) {\n  // Load Stephanie's spider robot.\n  auto robot = gtdynamics::CreateRobotFromFile(kSdfPath + string(\"spider.sdf\"),\n                                               \"spider\");\n\n  double sigma_dynamics = 1e-5;    // std of dynamics constraints.\n  double sigma_objectives = 1e-6;  // std of additional objectives.\n  double sigma_joints = 1.85e-4;   // 1.85e-4\n\n  // Noise models.\n  auto dynamics_model_6 = Isotropic::Sigma(6, sigma_dynamics),\n       dynamics_model_3 = Isotropic::Sigma(3, sigma_dynamics),\n       dynamics_model_1 = Isotropic::Sigma(1, sigma_dynamics),\n       dynamics_model_1_2 = Isotropic::Sigma(1, sigma_joints),\n       objectives_model_6 = Isotropic::Sigma(6, sigma_objectives),\n       objectives_model_3 = Isotropic::Sigma(3, sigma_objectives),\n       objectives_model_1 = Isotropic::Sigma(1, sigma_objectives);\n\n  // TODO(aescontrela): Make a constructor for OptimizerSetting that\n  //     initializes all noise models with the same sigma.\n  auto opt = gtdynamics::OptimizerSetting();\n  opt.bp_cost_model = dynamics_model_6;\n  opt.bv_cost_model = dynamics_model_6;\n  opt.ba_cost_model = dynamics_model_6;\n  opt.p_cost_model = dynamics_model_6;\n  opt.v_cost_model = dynamics_model_6;\n  opt.a_cost_model = dynamics_model_6;\n  opt.f_cost_model = dynamics_model_6;\n  opt.fa_cost_model = dynamics_model_6;\n  opt.t_cost_model = dynamics_model_1;\n  opt.cp_cost_model = dynamics_model_1;\n  opt.cfriction_cost_model = dynamics_model_1;\n  opt.cv_cost_model = dynamics_model_3;\n  opt.ca_cost_model = dynamics_model_3;\n  opt.planar_cost_model = dynamics_model_3;\n  opt.prior_q_cost_model = dynamics_model_1;\n  opt.prior_qv_cost_model = dynamics_model_1;\n  opt.prior_qa_cost_model = dynamics_model_1;\n  opt.prior_t_cost_model = dynamics_model_1;\n  opt.q_col_cost_model = dynamics_model_1;\n  opt.v_col_cost_model = dynamics_model_1;\n  opt.time_cost_model = dynamics_model_1;\n\n  // Env parameters.\n  Vector3 gravity(0, 0, -9.8);\n  double mu = 1.0;\n\n  auto graph_builder = gtdynamics::DynamicsGraph(opt, gravity);\n\n  vector<string> links = {\"tarsus_1_L1\", \"tarsus_2_L2\", \"tarsus_3_L3\",\n                          \"tarsus_4_L4\", \"tarsus_5_R4\", \"tarsus_6_R3\",\n                          \"tarsus_7_R2\", \"tarsus_8_R1\"};\n  // All contacts.\n  const Point3 contact_in_com(0, 0.19, 0);\n  PointOnLink cp1(robot.link(\"tarsus_1_L1\"), contact_in_com);  // Front left.\n  PointOnLink cp2(robot.link(\"tarsus_2_L2\"), contact_in_com);  // Hind left.\n  PointOnLink cp3(robot.link(\"tarsus_3_L3\"), contact_in_com);  // Front right.\n  PointOnLink cp4(robot.link(\"tarsus_4_L4\"), contact_in_com);  // Hind right.\n  PointOnLink cp5(robot.link(\"tarsus_5_R4\"), contact_in_com);  // Front left.\n  PointOnLink cp6(robot.link(\"tarsus_6_R3\"), contact_in_com);  // Hind left.\n  PointOnLink cp7(robot.link(\"tarsus_7_R2\"), contact_in_com);  // Front right.\n  PointOnLink cp8(robot.link(\"tarsus_8_R1\"), contact_in_com);  // Hind right.\n\n  // Contact points for each phase.\n  // This gait moves one leg at a time.\n  using CPs = PointOnLinks;\n  CPs t00 = {cp1, cp2, cp3, cp4, cp5, cp6, cp7, cp8};\n  // Initially stationary.\n  CPs p0 = {cp1, cp2, cp3, cp4, cp5, cp6, cp7, cp8};\n  CPs t01 = {cp2, cp3, cp4, cp5, cp6, cp7, cp8};\n  CPs p1 = {cp2, cp3, cp4, cp5, cp6, cp7, cp8};\n  CPs t12 = {cp3, cp4, cp5, cp6, cp7, cp8};\n  CPs p2 = {cp1, cp3, cp4, cp5, cp6, cp7, cp8};\n  CPs t23 = {cp1, cp4, cp5, cp6, cp7, cp8};\n  CPs p3 = {cp1, cp2, cp4, cp5, cp6, cp7, cp8};\n  CPs t34 = {cp1, cp2, cp5, cp6, cp7, cp8};\n  CPs p4 = {cp1, cp2, cp3, cp5, cp6, cp7, cp8};\n  CPs t45 = {cp1, cp2, cp3, cp6, cp7, cp8};\n  CPs p5 = {cp1, cp2, cp3, cp4, cp6, cp7, cp8};\n  CPs t56 = {cp1, cp2, cp3, cp4, cp7, cp8};\n  CPs p6 = {cp1, cp2, cp3, cp4, cp5, cp7, cp8};\n  CPs t67 = {cp1, cp2, cp3, cp4, cp5, cp8};\n  CPs p7 = {cp1, cp2, cp3, cp4, cp5, cp6, cp8};\n  CPs t78 = {cp1, cp2, cp3, cp4, cp5, cp6};\n  CPs p8 = {cp1, cp2, cp3, cp4, cp5, cp6, cp7};\n  CPs t80 = {cp2, cp3, cp4, cp5, cp6, cp7};\n\n  // This gait moves four legs at a time (alternating tetrapod).\n  CPs t0a = {cp2, cp4, cp6, cp8};\n  CPs pa = {cp2, cp4, cp6, cp8};\n  CPs tab = {};\n  CPs pb = {cp1, cp3, cp5, cp7};\n  CPs tb0 = {cp1, cp3, cp5, cp7};\n\n  // Define contact points for each phase, transition contact points,\n  // and phase durations.\n  // Alternating Tetrapod:\n  vector<CPs> phase_cps = {p0, pa, p0, pb, p0, pa, p0, pb, p0, pa,\n                           p0, pb, p0, pa, p0, pb, p0, pa, p0, pb};\n  vector<CPs> trans_cps = {t0a, t0a, tb0, tb0, t0a, t0a, tb0, tb0, t0a, t0a,\n                           tb0, tb0, t0a, t0a, tb0, tb0, t0a, t0a, tb0};\n  vector<int> phase_steps = {20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n                             20, 20, 20, 20, 20, 20, 20, 20, 20, 20};\n\n  // Define noise to be added to initial values, desired timestep duration,\n  // vector of link name strings, robot model for each phase, and\n  // phase transition initial values.\n  double gaussian_noise = 1e-5;\n\n  double dt_des = 1. / 240;\n  vector<Values> transition_graph_init;\n\n  // Define the cumulative phase steps.\n  vector<int> cum_phase_steps;\n  for (int i = 0; i < phase_steps.size(); i++) {\n    int cum_val =\n        i == 0 ? phase_steps[0] : phase_steps[i] + cum_phase_steps[i - 1];\n    cum_phase_steps.push_back(cum_val);\n    std::cout << cum_val << std::endl;\n  }\n  int t_f = cum_phase_steps[cum_phase_steps.size() - 1];  // Final timestep.\n\n  // Collocation scheme.\n  auto collocation = gtdynamics::CollocationScheme::Euler;\n\n  // Graphs for transition between phases + their initial values.\n  vector<gtsam::NonlinearFactorGraph> transition_graphs;\n  for (int p = 1; p < phase_cps.size(); p++) {\n    std::cout << \"Creating transition graph\" << std::endl;\n    transition_graphs.push_back(graph_builder.dynamicsFactorGraph(\n        robot, cum_phase_steps[p - 1], trans_cps[p - 1], mu));\n    std::cout << \"Creating initial values\" << std::endl;\n    transition_graph_init.push_back(ZeroValues(\n        robot, cum_phase_steps[p - 1], gaussian_noise, trans_cps[p - 1]));\n  }\n\n  // Construct the multi-phase trajectory factor graph.\n  std::cout << \"Creating dynamics graph\" << std::endl;\n  auto graph = graph_builder.multiPhaseTrajectoryFG(\n      robot, phase_steps, transition_graphs, collocation, phase_cps, mu);\n\n  // Build the objective factors.\n  gtsam::NonlinearFactorGraph objective_factors;\n  auto base_link = robot.link(\"body\");\n\n  std::map<string, gtdynamics::LinkSharedPtr> link_map;\n  for (auto&& link : links)\n    link_map.insert(std::make_pair(link, robot.link(link)));\n\n  // Previous contact point goal.\n  std::map<string, Point3> prev_cp;\n  for (auto&& link : links) {\n    prev_cp.insert(std::make_pair(link, link_map[link]->bMcom() * cp1.point));\n  }\n\n  // Distance to move contact point per time step during swing.\n  auto contact_offset = Point3(0, 0.007, 0);\n\n  // Set this to 'right' or 'left' to make the spider rotate in place\n  string turn = \"right\";\n\n  // Add contact point objectives to factor graph.\n  for (int p = 0; p < phase_cps.size(); p++) {\n    // Phase start and end timesteps.\n    int t_p_i = cum_phase_steps[p] - phase_steps[p];\n    if (p != 0) t_p_i += 1;\n    int t_p_f = cum_phase_steps[p];\n\n    // Obtain the contact links and swing links for this phase.\n    vector<string> phase_contact_links;\n    for (auto&& cp : phase_cps[p]) {\n      phase_contact_links.push_back(cp.link->name());\n    }\n    vector<string> phase_swing_links;\n    for (auto&& l : links) {\n      if (std::find(phase_contact_links.begin(), phase_contact_links.end(),\n                    l) == phase_contact_links.end()) {\n        phase_swing_links.push_back(l);\n      }\n    }\n\n    for (int t = t_p_i; t <= t_p_f; t++) {\n      // Normalized phase progress.\n      double t_normed = (double)(t - t_p_i) / (double)(t_p_f - t_p_i);\n\n      for (auto&& pcl : phase_contact_links) {\n        // TODO(aescontrela): Use correct contact point for each link.\n        // TODO(frank): #179 make sure height is handled correctly.\n        objective_factors.add(gtdynamics::PointGoalFactor(\n            internal::PoseKey(link_map[pcl]->id(), t),\n            Isotropic::Sigma(3, 1e-7), cp1.point,\n            Point3(prev_cp[pcl].x(), prev_cp[pcl].y(), GROUND_HEIGHT - 0.05)));\n      }\n\n      double h =\n          GROUND_HEIGHT + std::pow(t_normed, 1.1) * std::pow(1 - t_normed, 0.7);\n\n      for (auto&& psl : phase_swing_links) {\n        objective_factors.add(gtdynamics::PointGoalFactor(\n            internal::PoseKey(link_map[psl]->id(), t),\n            Isotropic::Sigma(3, 1e-7), cp1.point,\n            Point3(prev_cp[psl].x(), prev_cp[psl].y(), h)));\n      }\n\n      // Update the goal point for the swing links.\n      for (auto&& psl : phase_swing_links) {\n        if (turn.compare(\"right\") == 0) {\n          if (psl.find_first_of(\"1234\") != string::npos)\n            prev_cp[psl] = prev_cp[psl] + contact_offset;\n          else\n            prev_cp[psl] = prev_cp[psl] - contact_offset;\n        } else {\n          if (psl.find_first_of(\"5678\") != string::npos)\n            prev_cp[psl] = prev_cp[psl] + contact_offset;\n          else\n            prev_cp[psl] = prev_cp[psl] - contact_offset;\n        }\n      }\n    }\n  }\n\n  // Add base goal objectives to the factor graph.\n  for (int t = 0; t <= t_f; t++) {\n    objective_factors.add(gtsam::PriorFactor<gtsam::Pose3>(\n        internal::PoseKey(base_link->id(), t),\n        gtsam::Pose3(gtsam::Rot3(), gtsam::Point3(0, 0.0, 0.5)),\n        Isotropic::Sigma(6, 6e-5)));  // 6.2e-5\n  }\n\n  // Add link boundary conditions to FG.\n  for (auto&& link : robot.links()) {\n    // Initial link pose, twists.\n    objective_factors.add(gtsam::PriorFactor<gtsam::Pose3>(\n        internal::PoseKey(link->id(), 0), link->bMcom(), dynamics_model_6));\n    objective_factors.add(gtsam::PriorFactor<Vector6>(\n        internal::TwistKey(link->id(), 0), Vector6::Zero(), dynamics_model_6));\n\n    // Final link twists, accelerations.\n    objective_factors.add(\n        gtsam::PriorFactor<Vector6>(internal::TwistKey(link->id(), t_f),\n                                    Vector6::Zero(), objectives_model_6));\n    objective_factors.add(\n        gtsam::PriorFactor<Vector6>(internal::TwistAccelKey(link->id(), t_f),\n                                    Vector6::Zero(), objectives_model_6));\n  }\n\n  // Add joint boundary conditions to FG.\n  for (auto&& joint : robot.joints()) {\n    // Add priors to joint angles\n    for (int t = 0; t <= t_f; t++) {\n      if (joint->name().find(\"hip_\") == 0) {\n        objective_factors.add(gtsam::PriorFactor<double>(\n            internal::JointAngleKey(joint->id(), t), 0, dynamics_model_1_2));\n      } else if (joint->name().find(\"hip2\") == 0) {\n        objective_factors.add(gtsam::PriorFactor<double>(\n            internal::JointAngleKey(joint->id(), t), 0.9, dynamics_model_1_2));\n      } else if (joint->name().find(\"knee\") == 0) {\n        objective_factors.add(\n            gtsam::PriorFactor<double>(internal::JointAngleKey(joint->id(), t),\n                                       -1.22, dynamics_model_1_2));\n      } else {\n        objective_factors.add(gtsam::PriorFactor<double>(\n            internal::JointAngleKey(joint->id(), t), 0.26, dynamics_model_1_2));\n      }\n    }\n\n    objective_factors.add(gtsam::PriorFactor<double>(\n        internal::JointVelKey(joint->id(), 0), 0.0, dynamics_model_1));\n\n    objective_factors.add(gtsam::PriorFactor<double>(\n        internal::JointVelKey(joint->id(), t_f), 0.0, objectives_model_1));\n    objective_factors.add(gtsam::PriorFactor<double>(\n        internal::JointAccelKey(joint->id(), t_f), 0.0, objectives_model_1));\n  }\n\n  // Add prior factor constraining all Phase keys to have duration of 1 / 240.\n  for (int phase = 0; phase < phase_steps.size(); phase++)\n    objective_factors.add(gtsam::PriorFactor<double>(\n        PhaseKey(phase), dt_des,\n        gtsam::noiseModel::Isotropic::Sigma(1, 1e-30)));\n\n  // Add min torque objectives.\n  for (int t = 0; t <= t_f; t++) {\n    for (auto&& joint : robot.joints())\n      objective_factors.add(gtdynamics::MinTorqueFactor(\n          internal::TorqueKey(joint->id(), t),\n          gtsam::noiseModel::Gaussian::Covariance(gtsam::I_1x1)));\n  }\n  graph.add(objective_factors);\n\n  // Initialize solution.\n  gtsam::Values init_vals;\n  init_vals = gtdynamics::MultiPhaseZeroValuesTrajectory(\n      robot, phase_steps, transition_graph_init, dt_des, gaussian_noise,\n      phase_cps);\n\n  // Optimize!\n  gtsam::LevenbergMarquardtParams params;\n  params.setVerbosityLM(\"SUMMARY\");\n  params.setlambdaInitial(1e0);\n  params.setlambdaLowerBound(1e-7);\n  params.setlambdaUpperBound(1e10);\n  gtsam::LevenbergMarquardtOptimizer optimizer(graph, init_vals, params);\n  auto results = optimizer.optimize();\n\n  vector<string> joint_names;\n  for (auto&& joint : robot.joints()) joint_names.push_back(joint->name());\n  string joint_names_str = boost::algorithm::join(joint_names, \",\");\n  std::ofstream traj_file;\n\n  traj_file.open(\"rotation_traj.csv\");\n  // angles, vels, accels, torques, time.\n  traj_file << joint_names_str << \",\" << joint_names_str << \",\"\n            << joint_names_str << \",\" << joint_names_str << \",t\"\n            << \"\\n\";\n  int t = 0;\n  for (int phase = 0; phase < phase_steps.size(); phase++) {\n    for (int phase_step = 0; phase_step < phase_steps[phase]; phase_step++) {\n      vector<string> vals;\n      for (auto&& joint : robot.joints())\n        vals.push_back(std::to_string(JointAngle(results, joint->id(), t)));\n      for (auto&& joint : robot.joints())\n        vals.push_back(std::to_string(JointVel(results, joint->id(), t)));\n      for (auto&& joint : robot.joints())\n        vals.push_back(std::to_string(JointAccel(results, joint->id(), t)));\n      for (auto&& joint : robot.joints())\n        vals.push_back(std::to_string(Torque(results, joint->id(), t)));\n      vals.push_back(std::to_string(results.atDouble(PhaseKey(phase))));\n      t++;\n      string vals_str = boost::algorithm::join(vals, \",\");\n      traj_file << vals_str << \"\\n\";\n    }\n  }\n  traj_file.close();\n\n  return 0;\n\n}  // namespace gtdynamics\n", "meta": {"hexsha": "00bcb1d1e3a36d320c338925405a03f80b29185c", "size": 15599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example_spider_walking/main_rotate.cpp", "max_stars_repo_name": "mfkiwl/GTDynamics", "max_stars_repo_head_hexsha": "e5121e6a7ba5f8b5778f8934631bd99ea0946997", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/example_spider_walking/main_rotate.cpp", "max_issues_repo_name": "mfkiwl/GTDynamics", "max_issues_repo_head_hexsha": "e5121e6a7ba5f8b5778f8934631bd99ea0946997", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example_spider_walking/main_rotate.cpp", "max_forks_repo_name": "mfkiwl/GTDynamics", "max_forks_repo_head_hexsha": "e5121e6a7ba5f8b5778f8934631bd99ea0946997", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.7933673469, "max_line_length": 80, "alphanum_fraction": 0.6456183089, "num_tokens": 4716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4072060192544206}}
{"text": "// Copyright (C) 2015 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/global_pose_estimation/robust_rotation_estimator.h\"\n\n#include <Eigen/Core>\n#include <Eigen/SparseCore>\n#include <ceres/rotation.h>\n#include <unordered_map>\n\n#include \"theia/math/l1_solver.h\"\n#include \"theia/math/matrix/sparse_cholesky_llt.h\"\n#include \"theia/math/rotation.h\"\n#include \"theia/sfm/types.h\"\n#include \"theia/util/hash.h\"\n#include \"theia/util/map_util.h\"\n\nnamespace theia {\n\nbool RobustRotationEstimator::EstimateRotations(\n    const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs,\n    std::unordered_map<ViewId, Eigen::Vector3d>* global_orientations) {\n  for (const auto& view_pair : view_pairs) {\n    AddRelativeRotationConstraint(view_pair.first, view_pair.second.rotation_2);\n  }\n  return EstimateRotations(global_orientations);\n}\n\nvoid RobustRotationEstimator::AddRelativeRotationConstraint(\n    const ViewIdPair& view_id_pair, const Eigen::Vector3d& relative_rotation) {\n  // Store the relative orientation constraint.\n  relative_rotations_.emplace_back(view_id_pair, relative_rotation);\n}\n\nbool RobustRotationEstimator::EstimateRotations(\n    std::unordered_map<ViewId, Eigen::Vector3d>* global_orientations) {\n  CHECK_GT(relative_rotations_.size(), 0)\n      << \"Relative rotation constraints must be added to the robust rotation \"\n         \"solver before estimating global rotations.\";\n  global_orientations_ = CHECK_NOTNULL(global_orientations);\n\n  if (fixed_view_ids_.size() == 0) {\n    // just set the first rotation fix\n    fixed_view_ids_.insert(std::begin(*global_orientations)->first);\n    nr_fixed_rotations_ = 1;\n  }\n  // Compute a mapping of view ids to indices in the linear system. One rotation\n  // will have an index of -1 and will not be added to the linear system. This\n  // will remove the gauge freedom (effectively holding one camera as the\n  // identity rotation).\n  int index = 0;\n  int fix_index = -nr_fixed_rotations_;\n  view_id_to_index_.reserve(global_orientations->size());\n  for (const auto& orientation : *global_orientations) {\n      if (fixed_view_ids_.find(orientation.first) == fixed_view_ids_.end()) {\n          view_id_to_index_[orientation.first] = index;\n          ++index;\n      } else {\n          view_id_to_index_[orientation.first] = fix_index;\n          ++fix_index;\n      }\n  }\n\n  Eigen::SparseMatrix<double> sparse_mat;\n  SetupLinearSystem();\n\n  if (!SolveL1Regression()) {\n    LOG(ERROR) << \"Could not solve the L1 regression step.\";\n    return false;\n  }\n\n  if (!SolveIRLS()) {\n    LOG(ERROR) << \"Could not solve the least squares error step.\";\n    return false;\n  }\n\n  return true;\n}\n\n// Set up the sparse linear system.\nvoid RobustRotationEstimator::SetupLinearSystem() {\n  // The rotation change is one less than the number of global rotations because\n  // we keep one rotation constant.\n  tangent_space_step_.resize((global_orientations_->size() - nr_fixed_rotations_) * 3);\n  tangent_space_residual_.resize(relative_rotations_.size() * 3);\n  sparse_matrix_.resize(relative_rotations_.size() * 3,\n                        (global_orientations_->size() - nr_fixed_rotations_) * 3);\n\n  // For each relative rotation constraint, add an entry to the sparse\n  // matrix. We use the first order approximation of angle axis such that:\n  // R_ij = R_j - R_i. This makes the sparse matrix just a bunch of identity\n  // matrices.\n  int rotation_error_index = 0;\n  std::vector<Eigen::Triplet<double> > triplet_list;\n  for (const auto& relative_rotation : relative_rotations_) {\n\n    // see if this rotation should be fixed\n    if (fixed_view_ids_.find(relative_rotation.first.first) == fixed_view_ids_.end()) {\n      const int view1_index =\n        FindOrDie(view_id_to_index_, relative_rotation.first.first);\n\n      triplet_list.emplace_back(3 * rotation_error_index,\n                                3 * view1_index,\n                                -1.0);\n      triplet_list.emplace_back(3 * rotation_error_index + 1,\n                                3 * view1_index + 1,\n                                -1.0);\n      triplet_list.emplace_back(3 * rotation_error_index + 2,\n                                3 * view1_index + 2,\n                                -1.0);\n\n    }\n    if (fixed_view_ids_.find(relative_rotation.first.second) == fixed_view_ids_.end())  {\n      const int view2_index =\n        FindOrDie(view_id_to_index_, relative_rotation.first.second);\n      triplet_list.emplace_back(3 * rotation_error_index + 0,\n                                3 * view2_index + 0,\n                                1.0);\n      triplet_list.emplace_back(3 * rotation_error_index + 1,\n                                3 * view2_index + 1,\n                                1.0);\n      triplet_list.emplace_back(3 * rotation_error_index + 2,\n                                3 * view2_index + 2,\n                                1.0);\n\n    }\n\n    ++rotation_error_index;\n  }\n  sparse_matrix_.setFromTriplets(triplet_list.begin(), triplet_list.end());\n}\n\nbool RobustRotationEstimator::SolveL1Regression() {\n  L1Solver<Eigen::SparseMatrix<double> >::Options options;\n  options.max_num_iterations = 5;\n  L1Solver<Eigen::SparseMatrix<double> > l1_solver(options, sparse_matrix_);\n\n  tangent_space_step_.setZero();\n  ComputeResiduals();\n  for (int i = 0; i < options_.max_num_l1_iterations; i++) {\n    l1_solver.Solve(tangent_space_residual_, &tangent_space_step_);\n    UpdateGlobalRotations();\n    ComputeResiduals();\n\n    double avg_step_size = ComputeAverageStepSize();\n\n    if (avg_step_size <= options_.l1_step_convergence_threshold) {\n      break;\n    }\n    options.max_num_iterations *= 2;\n    l1_solver.SetMaxIterations(options.max_num_iterations);\n  }\n  return true;\n}\n\nbool RobustRotationEstimator::SolveIRLS() {\n  const int num_edges = tangent_space_residual_.size() / 3;\n\n  // Set up the linear solver and analyze the sparsity pattern of the\n  // system. Since the sparsity pattern will not change with each linear solve\n  // this can help speed up the solution time.\n  SparseCholeskyLLt linear_solver;\n  linear_solver.AnalyzePattern(sparse_matrix_.transpose() * sparse_matrix_);\n  if (linear_solver.Info() != Eigen::Success) {\n    LOG(ERROR) << \"Cholesky decomposition failed.\";\n    return false;\n  }\n\n  VLOG(2) << \"Iteration   SqError         Delta\";\n  const std::string row_format = \"  % 4d     % 4.4e     % 4.4e\";\n\n  ComputeResiduals();\n\n  Eigen::ArrayXd weights(num_edges * 3);\n  Eigen::SparseMatrix<double> at_weight;\n  for (int i = 0; i < options_.max_num_irls_iterations; i++) {\n    // Compute the Huber-like weights for each error term.\n    const double& sigma = options_.irls_loss_parameter_sigma;\n    for (int k = 0; k < num_edges; ++k) {\n      double e_sq = tangent_space_residual_.segment<3>(3 * k).squaredNorm();\n      double tmp = e_sq + sigma * sigma;\n      double w = sigma / (tmp * tmp);\n      weights.segment<3>(3 * k).setConstant(w);\n    }\n\n    // Update the factorization for the weighted values.\n    at_weight = sparse_matrix_.transpose() * weights.matrix().asDiagonal();\n    linear_solver.Factorize(at_weight * sparse_matrix_);\n    if (linear_solver.Info() != Eigen::Success) {\n      LOG(ERROR) << \"Failed to factorize the least squares system.\";\n      return false;\n    }\n\n    // Solve the least squares problem..\n    tangent_space_step_ =\n        linear_solver.Solve(at_weight * tangent_space_residual_);\n    if (linear_solver.Info() != Eigen::Success) {\n      LOG(ERROR) << \"Failed to solve the least squares system.\";\n      return false;\n    }\n\n    UpdateGlobalRotations();\n    ComputeResiduals();\n    const double avg_step_size = ComputeAverageStepSize();\n\n    VLOG(2) << StringPrintf(row_format.c_str(),\n                            i,\n                            tangent_space_residual_.squaredNorm(),\n                            avg_step_size);\n\n    if (avg_step_size < options_.irls_step_convergence_threshold) {\n      VLOG(1) << \"IRLS Converged in \" << i + 1 << \" iterations.\";\n      break;\n    }\n  }\n  return true;\n}\n\n// Update the global orientations using the current value in the\n// rotation_change.\nvoid RobustRotationEstimator::UpdateGlobalRotations() {\n  for (auto& rotation : *global_orientations_) {\n    if (fixed_view_ids_.find(rotation.first) != fixed_view_ids_.end()) {\n      continue;\n    }\n\n    const int view_index = FindOrDie(view_id_to_index_, rotation.first);\n    // Apply the rotation change to the global orientation.\n    const Eigen::Vector3d& rotation_change =\n        tangent_space_step_.segment<3>(3 * view_index);\n    rotation.second = MultiplyRotations(rotation.second, rotation_change);\n  }\n}\n\n// Computes the relative rotation error based on the current global\n// orientation estimates.\nvoid RobustRotationEstimator::ComputeResiduals() {\n  int rotation_error_index = 0;\n  for (const auto& relative_rotation : relative_rotations_) {\n    const Eigen::Vector3d& relative_rotation_aa = relative_rotation.second;\n    const Eigen::Vector3d& rotation1 =\n        FindOrDie(*global_orientations_, relative_rotation.first.first);\n    const Eigen::Vector3d& rotation2 =\n        FindOrDie(*global_orientations_, relative_rotation.first.second);\n\n    // Compute the relative rotation error as:\n    //   R_err = R2^t * R_12 * R1.\n    tangent_space_residual_.segment<3>(3 * rotation_error_index) =\n        MultiplyRotations(-rotation2,\n                          MultiplyRotations(relative_rotation_aa, rotation1));\n    ++rotation_error_index;\n  }\n}\n\ndouble RobustRotationEstimator::ComputeAverageStepSize() {\n  // compute the average step size of the update in tangent_space_step_\n  const int numVertices = tangent_space_step_.size() / 3;\n  double delta_V = 0;\n  for (int k = 0; k < numVertices; ++k) {\n    delta_V += tangent_space_step_.segment<3>(3 * k).norm();\n  }\n  return delta_V / numVertices;\n}\n\nbool RobustRotationEstimator::EstimateRotationsWrapper(\n    const std::unordered_map<ViewIdPair, TwoViewInfo>& view_pairs,\n    std::unordered_map<ViewId, Eigen::Vector3d>& init_global_orientations) {\n    return EstimateRotations(view_pairs, &init_global_orientations);\n}\n\nvoid RobustRotationEstimator::SetFixedGlobalRotations(const std::set<ViewId>& fixed_views) {\n    fixed_view_ids_ = fixed_views;\n    nr_fixed_rotations_ = fixed_view_ids_.size();\n\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "8252ee9ff844bd0a3fa60382b9c2252b9a2cda34", "size": 12001, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/global_pose_estimation/robust_rotation_estimator.cc", "max_stars_repo_name": "urbste/TheiaSfM", "max_stars_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T03:01:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T08:08:45.000Z", "max_issues_repo_path": "src/theia/sfm/global_pose_estimation/robust_rotation_estimator.cc", "max_issues_repo_name": "urbste/TheiaSfM", "max_issues_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/global_pose_estimation/robust_rotation_estimator.cc", "max_forks_repo_name": "urbste/TheiaSfM", "max_forks_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-20T03:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T08:08:52.000Z", "avg_line_length": 38.8381877023, "max_line_length": 92, "alphanum_fraction": 0.6946087826, "num_tokens": 2809, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4072060192544206}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <Eigen/Sparse>\n#include <Eigen/SPQRSupport>\n\nint main() {\n  Eigen::SparseMatrix<double> sm1(3, 3);\n  /*\n  sm1.reserve(3000000);\n\n  {\n    std::vector<Eigen::Triplet<double>> tripletList;\n    tripletList.reserve(3000000);\n  \n    std::ifstream ifile (\"output.txt\");\n  \n    std::string substr;\n    int i, j;\n    double v;\n  \n    while (ifile) {\n      std::getline(ifile, substr, ',');\n      if (!ifile) break;\n      i = std::stoi(substr);\n  \n      std::getline(ifile, substr, ',');\n      j = std::stoi(substr);\n  \n      std::getline(ifile, substr);\n      v = std::stod(substr);\n\n      tripletList.push_back(Eigen::Triplet<double>(i, j, v));\n    }\n\n    sm1.setFromTriplets(tripletList.begin(), tripletList.end());\n  }\n  */\n\n  std::vector<Eigen::Triplet<double>> tripletList = {\n    {0, 0, 5},\n    {1, 1, 3},\n  };\n\n  sm1.setFromTriplets(tripletList.begin(), tripletList.end());\n\n  Eigen::SPQR<Eigen::SparseMatrix<double>> spqr(sm1);\n\n  std::cout << \"info : \" << spqr.info() << std::endl;\n  std::cout << \"rank : \" << spqr.rank() << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "20f32da973548d902f066c846762c6860f744037", "size": 1119, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/main.cpp", "max_stars_repo_name": "nilsalex/diffeo-involutizer", "max_stars_repo_head_hexsha": "875bd8408dc4395156412b7e7f218f073e32e1eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/main.cpp", "max_issues_repo_name": "nilsalex/diffeo-involutizer", "max_issues_repo_head_hexsha": "875bd8408dc4395156412b7e7f218f073e32e1eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/main.cpp", "max_forks_repo_name": "nilsalex/diffeo-involutizer", "max_forks_repo_head_hexsha": "875bd8408dc4395156412b7e7f218f073e32e1eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.3454545455, "max_line_length": 64, "alphanum_fraction": 0.5871313673, "num_tokens": 339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672043084051, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.4071900504531885}}
{"text": "/*    Copyright (c) 2010-2015, Delft University of Technology\n *    All rights reserved.\n *\n *    Redistribution and use in source and binary forms, with or without modification, are\n *    permitted provided that the following conditions are met:\n *      - Redistributions of source code must retain the above copyright notice, this list of\n *        conditions and the following disclaimer.\n *      - Redistributions in binary form must reproduce the above copyright notice, this list of\n *        conditions and the following disclaimer in the documentation and/or other materials\n *        provided with the distribution.\n *      - Neither the name of the Delft University of Technology nor the names of its contributors\n *        may be used to endorse or promote products derived from this software without specific\n *        prior written permission.\n *\n *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\n *    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *    MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *    COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n *    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n *    GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *    AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n *    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n *    OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *    Changelog\n *      YYMMDD    Author            Comment\n *      101111    E. Iorfida        File created.\n *      101111    E. Iorfida        Implementation of all the equations up to the Newton method.\n *      101117    E. Iorfida        Velocities computations added.\n *      101126    E. Iorfida        Get/set codes deleted.\n *      101206    E. Iorfida        LambertTargetingElements class deleted,\n *                                  added setInitialState, modified punctuation. Set single\n *                                  variables, change variables names in more understandable ones.\n *      101209    E. Iorfida        Corrected some coding errors.\n *      101213    E. Iorfida        Deleted lambertAngle, added numberOfRevolution, modified\n *                                  implementation.\n *      101214    E. Iorfida        Implementation only for the case with numberOfRevolution = 0.\n *      110113    E. Iorfida        Added necessary elements to build pointer-to-member-function\n *                                  to RootFinderAlgorithms and NewtonRaphsonMethod classes.\n *      110124    E. Iorfida        Added necessary piece of code to be able to use the last\n *                                  version of Newton-Raphson code.\n *      110126    E. Iorfida        Initialized member functions.\n *      110130    J. Melman         Simplified variable names, e.g., 'normOfdeletVelocityVector'\n *                                  became 'speed'. Requested references to specific formulas. Also\n *                                  corrected 'tangential' to 'transverse'. Simplified computation\n *                                  of radial unit vector. Corrected computation of transverse\n *                                  heliocentric velocity.\n *      110201    E. Iorfida        Added pointerToCelestialBody and modified variable names (from\n *                                  heliocentric, to inertial). Added patch for negative case of\n *                                  initialLambertGuess_. Added equations references.\n *      110206    E. Iorfida        Added unique function for Newton-Raphson method. Added\n *                                  computeAbsoluteValue to the initialLambertGuess_ for\n *                                  non-converging cases.\n *      110208    E. Iorfida        Added CartesianPositionElements objects as input and\n *                                  CartesianVelocityElements objects as output.\n *      110418    E. Iorfida        Added a new normal plane that take into account the case of two\n *                                  parallel position vector (with a relative angle of 180\n *                                  degrees). Better defined the pointers to the output\n *                                  CartesianVelocityElements.\n *      120326    D. Dirkx          Changed raw pointers to shared pointers.\n *      120620    T. Secretin       Adapted and moved code from LambertTargeter.cpp.\n *      120813    P. Musegaas       Changed code to new root finding structure.\n *      140117    E. Brandon        Changed constructor input argument naming to be consistent with\n *                                  other Lambert classes.\n *\n *    References\n *\n *    Notes\n *\n */\n\n#include <boost/make_shared.hpp>\n\n#include <Eigen/Geometry>\n\n#include \"Tudat/Astrodynamics/MissionSegments/lambertRoutines.h\"\n#include \"Tudat/Astrodynamics/MissionSegments/lambertTargeterGooding.h\"\n\n//! Tudat library namespace.\nnamespace tudat\n{\nnamespace mission_segments\n{\n\nusing namespace root_finders;\n\n//! Constructor with immediate definition of parameters and execution of the algorithm.\nLambertTargeterGooding::LambertTargeterGooding( \n        const Eigen::Vector3d& aCartesianPositionAtDeparture,\n        const Eigen::Vector3d& aCartesianPositionAtArrival,\n        const double aTimeOfFlight,\n        const double aGravitationalParameter,\n        RootFinderPointer aRootFinder )\n    : LambertTargeter( aCartesianPositionAtDeparture, aCartesianPositionAtArrival,\n                       aTimeOfFlight, aGravitationalParameter ),\n      rootFinder( aRootFinder )\n{\n    // Required because the make_shared in the function definition gives problems for MSVC.\n    if ( !rootFinder.get( ) )\n    {\n        rootFinder = boost::make_shared< NewtonRaphson >( 1.0e-12, 1000 );\n    }\n\n    // Execute algorithm.\n    execute( );\n}\n\n//! Execute Lambert targeting solver.\nvoid LambertTargeterGooding::execute( )\n{\n    // Call Gooding's Lambert targeting routine.\n    solveLambertProblemGooding( cartesianPositionAtDeparture, cartesianPositionAtArrival,\n                                timeOfFlight, gravitationalParameter,\n                                cartesianVelocityAtDeparture, cartesianVelocityAtArrival,\n                                rootFinder );\n}\n\n//! Get radial velocity at departure.\ndouble LambertTargeterGooding::getRadialVelocityAtDeparture( )\n{\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtDeparture = cartesianPositionAtDeparture.normalized( );\n\n    // Compute radial velocity at departure.\n    return cartesianVelocityAtDeparture.dot( radialUnitVectorAtDeparture );\n}\n\n//! Get radial velocity at arrival.\ndouble LambertTargeterGooding::getRadialVelocityAtArrival( )\n{\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtArrival = cartesianPositionAtArrival.normalized( );\n\n    // Compute radial velocity at arrival.\n    return cartesianVelocityAtArrival.dot( radialUnitVectorAtArrival );\n}\n\n//! Get transverse velocity at departure.\ndouble LambertTargeterGooding::getTransverseVelocityAtDeparture( )\n{\n    // Compute angular momemtum vector.\n    const Eigen::Vector3d angularMomentumVector =\n            cartesianPositionAtDeparture.cross( cartesianVelocityAtDeparture );\n\n    // Compute normalized angular momentum vector.\n    const Eigen::Vector3d angularMomentumUnitVector = angularMomentumVector.normalized( );\n\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtDeparture\n            = cartesianPositionAtDeparture.normalized( );\n\n    // Compute tangential unit vector.\n    Eigen::Vector3d tangentialUnitVectorAtDeparture =\n                angularMomentumUnitVector.cross( radialUnitVectorAtDeparture );\n\n    // Compute tangential velocity at departure.\n    return cartesianVelocityAtDeparture.dot( tangentialUnitVectorAtDeparture );\n}\n\n//! Get transverse velocity at arrival.\ndouble LambertTargeterGooding::getTransverseVelocityAtArrival( )\n{\n    // Compute angular momemtum vector.\n    const Eigen::Vector3d angularMomentumVector =\n            cartesianPositionAtArrival.cross( cartesianVelocityAtArrival );\n\n    // Compute normalized angular momentum vector.\n    const Eigen::Vector3d angularMomentumUnitVector = angularMomentumVector.normalized( );\n\n    // Determine radial unit vector.\n    const Eigen::Vector3d radialUnitVectorAtArrival = cartesianPositionAtArrival.normalized( );\n\n    // Compute tangential unit vector.\n    Eigen::Vector3d tangentialUnitVectorAtArrival =\n                angularMomentumUnitVector.cross( radialUnitVectorAtArrival );\n\n    // Compute tangential velocity at departure.\n    return cartesianVelocityAtArrival.dot( tangentialUnitVectorAtArrival );\n}\n\n//! Get semi-major axis.\ndouble LambertTargeterGooding::getSemiMajorAxis( )\n{\n    // Compute specific orbital energy: eps = v^2/ - mu/r.\n    const double specificOrbitalEnergy = cartesianVelocityAtDeparture.squaredNorm( ) / 2.0\n            - gravitationalParameter / cartesianPositionAtDeparture.norm( );\n\n    // Compute semi-major axis: a = -mu / 2*eps.\n    return -gravitationalParameter / ( 2.0 * specificOrbitalEnergy );\n}\n\n} // namespace mission_segments\n} // namespace tudat\n", "meta": {"hexsha": "b58ecb5092398f466ae6b964fa3cc95da5915841", "size": 9405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/MissionSegments/lambertTargeterGooding.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/MissionSegments/lambertTargeterGooding.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/MissionSegments/lambertTargeterGooding.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 48.4793814433, "max_line_length": 99, "alphanum_fraction": 0.6801701223, "num_tokens": 1985, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.6619228825191872, "lm_q1q2_score": 0.40714072632574005}}
{"text": "//\n// Created by joshua on 7/13/17.\n//\n#include \"sim_env/Controller.h\"\n#include \"sim_env/utils/EigenUtils.h\"\n#include <boost/math/constants/constants.hpp>\n#include <cmath>\n\nusing namespace sim_env;\n\nsim_env::PIDController::PIDController(float kp, float ki, float kd)\n{\n    _kp = kp;\n    _ki = ki;\n    _kd = kd;\n    reset();\n}\n\nsim_env::PIDController::~PIDController()\n{\n    // nothing to do here\n}\n\nvoid sim_env::PIDController::setKp(float kp)\n{\n    _kp = kp;\n}\n\nvoid sim_env::PIDController::setKi(float ki)\n{\n    _ki = ki;\n}\n\nvoid sim_env::PIDController::setKd(float kd)\n{\n    _kd = kd;\n}\n\nvoid sim_env::PIDController::setGains(float kp, float ki, float kd)\n{\n    setKp(kp);\n    setKi(ki);\n    setKd(kd);\n}\n\nvoid sim_env::PIDController::setTarget(float target_state)\n{\n    if (target_state != _target) {\n        reset();\n        _target = target_state;\n    }\n}\n\nfloat sim_env::PIDController::getTarget() const\n{\n    return _target;\n}\n\nbool sim_env::PIDController::isTargetSatisfied(float current_state, float threshold) const\n{\n    return std::fabs(current_state - _target) < threshold;\n}\n\nfloat sim_env::PIDController::control(float current_state)\n{\n    float error = _target - current_state;\n    float delta_error = 0.0f;\n    if (not std::isnan(_prev_error)) {\n        delta_error = error - _prev_error;\n    }\n    _prev_error = error;\n    _integral_part += error;\n    float output = _kp * error + _ki * _integral_part + _kd * delta_error;\n    //    if (isTargetSatisfied(current_state, 0.001f)) {\n    //        auto logger = DefaultLogger::getInstance();\n    //        std::stringstream ss;\n    //        ss << \"target is satisfied. output is \" << output;\n    //        ss << \"error is \" << error << \" current state is \" << current_state;\n    //        ss << \"kp: \" << _kp << \" ki\" << _ki << \"kd\" << _kd;\n    //        logger->logDebug(ss.str());\n    //    }\n    return output;\n}\n\nvoid sim_env::PIDController::reset()\n{\n    _integral_part = 0.0;\n    _prev_error = nanf(\"\");\n}\n\n////////////////////// IndependentMDPIDController //////////////////////////////\nIndependentMDPIDController::IndependentMDPIDController(float kp, float ki, float kd)\n{\n    _default_ki = ki;\n    _default_kp = kp;\n    _default_kd = kd;\n    setGains(kp, ki, kd);\n}\n\nIndependentMDPIDController::~IndependentMDPIDController()\n{\n    // nothing to do here.\n}\n\nvoid IndependentMDPIDController::setTarget(const Eigen::VectorXf& target_state)\n{\n    if (target_state.size() != _controllers.size()) {\n        throw std::runtime_error(\"[sim_env::IndependentMDPIDController::setTarget]\"\n                                 \"Invalid input state dimension.\");\n    }\n    for (size_t i = 0; i < target_state.size(); ++i) {\n        _controllers.at(i).setTarget(target_state[i]);\n    }\n}\n\nvoid IndependentMDPIDController::getTarget(Eigen::VectorXf& target_state) const\n{\n    target_state.resize(_controllers.size());\n    for (size_t i = 0; i < _controllers.size(); ++i) {\n        target_state[i] = _controllers.at(i).getTarget();\n    }\n}\n\nvoid IndependentMDPIDController::control(Eigen::VectorXf& output,\n    const Eigen::VectorXf& current_state)\n{\n    if (_controllers.size() != current_state.size()) {\n        throw std::runtime_error(\"[sim_env::IndependentMDPIDController::control]\"\n                                 \"Invalid input state dimension.\");\n    }\n    output.resize(_controllers.size());\n    for (size_t i = 0; i < _controllers.size(); ++i) {\n        output[i] = _controllers.at(i).control(current_state[i]);\n    }\n}\n\nvoid IndependentMDPIDController::reset()\n{\n    for (auto& controller : _controllers) {\n        controller.reset();\n    }\n}\n\nbool IndependentMDPIDController::isTargetSatisfied(Eigen::VectorXf& current_state, float threshold) const\n{\n    bool target_satisfied = true;\n    for (size_t i = 0; i < _controllers.size(); ++i) {\n        target_satisfied = target_satisfied and _controllers.at(i).isTargetSatisfied(current_state[i], threshold);\n    }\n    return target_satisfied;\n}\n\nvoid IndependentMDPIDController::setGains(float kp, float ki, float kd)\n{\n    for (auto& controller : _controllers) {\n        controller.setGains(kp, ki, kd);\n    }\n}\n\nvoid IndependentMDPIDController::setGains(const Eigen::VectorXf& kps, const Eigen::VectorXf& kis, const Eigen::VectorXf& kds)\n{\n    if (_controllers.size() != kps.size() or _controllers.size() != kis.size() or _controllers.size() != kds.size()) {\n        throw std::runtime_error(\"[sim_env::IndependentMDPIDController::setGains]\"\n                                 \"Invalid input vector dimension.\");\n    }\n    for (size_t i = 0; i < _controllers.size(); ++i) {\n        _controllers.at(i).setGains(kps[i], kis[i], kds[i]);\n    }\n}\n\nvoid IndependentMDPIDController::setKps(const Eigen::VectorXf& kps)\n{\n    if (_controllers.size() != kps.size()) {\n        throw std::runtime_error(\"[sim_env::IndependentMDPIDController::setKps]\"\n                                 \"Invalid input vector dimension.\");\n    }\n    for (size_t i = 0; i < _controllers.size(); ++i) {\n        _controllers.at(i).setKp(kps[i]);\n    }\n}\n\nvoid IndependentMDPIDController::setKp(float kp)\n{\n    for (auto& controller : _controllers) {\n        controller.setKp(kp);\n    }\n}\n\nvoid IndependentMDPIDController::setKis(const Eigen::VectorXf& kis)\n{\n    if (_controllers.size() != kis.size()) {\n        throw std::runtime_error(\"[sim_env::IndependentMDPIDController::setKis]\"\n                                 \"Invalid input vector dimension.\");\n    }\n    for (size_t i = 0; i < _controllers.size(); ++i) {\n        _controllers.at(i).setKi(kis[i]);\n    }\n}\n\nvoid IndependentMDPIDController::setKi(float ki)\n{\n    for (auto& controller : _controllers) {\n        controller.setKi(ki);\n    }\n}\n\nvoid IndependentMDPIDController::setKds(const Eigen::VectorXf& kds)\n{\n    if (_controllers.size() != kds.size()) {\n        throw std::runtime_error(\"[sim_env::IndependentMDPIDController::setKds]\"\n                                 \"Invalid input vector dimension.\");\n    }\n    for (size_t i = 0; i < _controllers.size(); ++i) {\n        _controllers.at(i).setKd(kds[i]);\n    }\n}\n\nvoid IndependentMDPIDController::setKd(float kd)\n{\n    for (auto& controller : _controllers) {\n        controller.setKd(kd);\n    }\n}\n\nunsigned int IndependentMDPIDController::getStateDimension()\n{\n    return (unsigned int)_controllers.size();\n}\n\nvoid IndependentMDPIDController::setStateDimension(unsigned int dim)\n{\n    if (dim != _controllers.size()) {\n        unsigned int prev_dim = (unsigned int)_controllers.size();\n        _controllers.resize(dim);\n        reset();\n        for (unsigned int i = prev_dim; i < _controllers.size(); ++i) {\n            _controllers.at(i).setGains(_default_kp, _default_ki, _default_kd);\n        }\n    }\n}\n\n//*************************** RobotController ************************************//\nRobotController::~RobotController() = default;\n\n//*************************** RobotPositionController ****************************//\nRobotPositionController::RobotPositionController(RobotPtr robot,\n    RobotVelocityControllerPtr velocity_controller)\n    : _pid_controller(1.0, 0.0, 0.0)\n    , _velocity_controller(velocity_controller)\n    , _robot(robot)\n{\n}\n\nRobotPositionController::~RobotPositionController()\n{\n}\n\nvoid RobotPositionController::setPositionProjectionFn(PositionProjectionFn pos_constraint)\n{\n    _pos_proj_fn = pos_constraint;\n}\n\nvoid RobotPositionController::setVelocityProjectionFn(VelocityProjectionFn vel_constraint)\n{\n    _vel_proj_fn = vel_constraint;\n}\n\nvoid RobotPositionController::setTarget(const Eigen::VectorXf& position)\n{\n    setTargetPosition(position);\n}\n\nvoid RobotPositionController::setTargetPosition(const Eigen::VectorXf& position)\n{\n    if (_robot.expired()) {\n        LoggerPtr logger = DefaultLogger::getInstance();\n        logger->logErr(\"Can not access underlying robot; the pointer is not valid anymore!\",\n            \"[sim_env::RobotPositionController::setTargetPosition]\");\n    }\n    RobotPtr robot = _robot.lock();\n    LoggerPtr logger = robot->getWorld()->getLogger();\n    // std::stringstream ss;\n    // ss << \"Setting target position \" << position.transpose();\n    // logger->logDebug(ss.str(), \"[sim_env::RobotPositionController::setTargetPosition]\");\n    _pid_controller.setStateDimension((unsigned int)position.size());\n    _pid_controller.setTarget(position);\n}\n\nunsigned int RobotPositionController::getTargetDimension() const\n{\n    auto robot = _robot.lock();\n    return robot->getNumActiveDOFs();\n}\n\nRobotPtr RobotPositionController::getRobot() const\n{\n    return _robot.lock();\n}\n\ninline float cyclicPositionError(const Eigen::Array2f& pos_range, float pos, float target)\n{\n    float error = target - pos;\n    float overflow_error = pos_range[1] - pos + target - pos_range[0];\n    float underflow_error = pos_range[0] - pos + target - pos_range[1];\n    error = std::abs(error) < std::abs(overflow_error) ? error : overflow_error;\n    error = std::abs(error) < std::abs(underflow_error) ? error : underflow_error;\n    return error;\n}\n\nbool RobotPositionController::control(const Eigen::VectorXf& positions, const Eigen::VectorXf& velocities,\n    float timestep, RobotConstPtr robot,\n    Eigen::VectorXf& output)\n{\n    Eigen::VectorXf target_position;\n    _pid_controller.getTarget(target_position);\n    if (target_position.size() != robot->getActiveDOFs().size()) {\n        LoggerPtr logger = robot->getWorld()->getLogger();\n        logger->logErr(\"The provided target position has different dimension from the active DOFs.\"\n                       \"[sim_env::RobotPositionController::setTargetPosition]\");\n        std::stringstream ss;\n        ss << \"target size is \" << target_position.size() << \" active dof size is \" << robot->getNumActiveDOFs();\n        logger->logErr(ss.str());\n        return false;\n    }\n    // project target position onto constraint set (this should only do anything if the user set invalid target positions)\n    if (_pos_proj_fn) {\n        _pos_proj_fn(target_position, robot);\n    }\n    Eigen::VectorXf target_velocities(positions.size());\n    //    _pid_controller.control(target_velocities, positions);\n    // TODO see whether we still can use a PID somehow\n    // TODO this is not moving in a straight line. we could make the decision on\n    // TODO whether to move in a straight line or not dependent on a parameter\n    // Eigen::ArrayX2f velocity_limits = robot->getDOFVelocityLimits();\n    // Eigen::ArrayX2f acceleration_limits = robot->getDOFAccelerationLimits();\n    // Eigen::VectorXf delta_position = target_position - positions;\n    Eigen::VectorXi dof_indices = robot->getActiveDOFs();\n    assert(dof_indices.size() == positions.size());\n    DOFInformation dof_info;\n    for (int idx = 0; idx < dof_indices.size(); ++idx) {\n        // get dof information\n        robot->getDOFInformation(dof_indices[idx], dof_info);\n        float delta_position = target_position[idx] - positions[idx];\n        if (dof_info.cyclic) {\n            delta_position = cyclicPositionError(dof_info.position_limits, positions[idx], target_position[idx]);\n        }\n        // first, command max velocity for each dof separately\n        float velocity_sign(1.0f);\n        if (std::signbit(delta_position)) {\n            // need negative velocity\n            target_velocities[idx] = dof_info.velocity_limits[0];\n            assert(std::signbit(target_velocities[idx]));\n            velocity_sign = -1.0f;\n        } else {\n            // need positive velocity\n            target_velocities[idx] = dof_info.velocity_limits[1];\n            velocity_sign = 1.0f;\n        }\n        // next compute the maximum velocity we can have to not overshoot\n        float abs_position_error = std::abs(delta_position);\n        float abs_max_break_accel = 0.0f;\n        if (std::signbit(velocities[idx])) {\n            abs_max_break_accel = std::abs(dof_info.acceleration_limits[1]);\n        } else {\n            abs_max_break_accel = std::abs(dof_info.acceleration_limits[0]);\n        }\n        float abs_max_break_velocity = std::sqrt(2.0f * abs_position_error * abs_max_break_accel);\n        // finally, set the target velocity such maximal, but such that we do not overshoot.\n        target_velocities[idx] = velocity_sign * std::min(abs_max_break_velocity, std::abs(target_velocities[idx]));\n    }\n    // { // TODO delete this block\n\n    //     auto robot = _robot.lock();\n    //     auto world = robot->getWorld();\n    //     auto logger = world->getLogger();\n    //     logger->logDebug(boost::format(\"Position error: x:%1%, y: %2%, theta: %3%\") % delta_position[0] % delta_position[1] % delta_position[2], \"[sim_env::PositionController]\");\n    // }\n    if (_vel_proj_fn) {\n        _vel_proj_fn(target_velocities, robot);\n    }\n    _velocity_controller->setTargetVelocity(target_velocities);\n    _velocity_controller->control(positions, velocities, timestep, robot, output);\n    return true;\n}\n\n///////////////////////////// RobotVelocityController ///////////////////////////////\n//RobotVelocityController::RobotVelocityController(RobotPtr robot):\n//        _pid_controller(10.0, 0.0, 0.0),\n//        _robot(robot) {\n//}\n\nRobotVelocityController::~RobotVelocityController() = default;\n\nvoid RobotVelocityController::setTarget(const Eigen::VectorXf& target)\n{\n    setTargetVelocity(target);\n}\n\n//void RobotVelocityController::setTargetVelocity(const Eigen::VectorXf &velocity) {\n//    if (_robot.expired()) {\n//        LoggerPtr logger = DefaultLogger::getInstance();\n//        logger->logErr(\"Can not access underlying robot; the pointer is not valid anymore!\",\n//                       \"[sim_env::RobotVelocityController::setTargetVelocity]\");\n//    }\n//    RobotPtr robot = _robot.lock();\n//    Eigen::VectorXf new_target = velocity;\n//    LoggerPtr logger = robot->getWorld()->getLogger();\n//    // scale the target velocity to limits\n//    using namespace utils::eigen;\n//    ScalingResult scaling_result = scaleToLimits(new_target, robot->getDOFVelocityLimits());\n//    if (scaling_result == ScalingResult::Failure) {\n//        logger->logWarn(\"Impossible target velocity direction detected. The requested velocity can not be scaled to the given limits\",\n//                        \"[sim_env::RobotVelocityController::setTargetVelocity]\");\n//    } else if (scaling_result == ScalingResult::Scaled) {\n//        logger->logWarn(\"Requested velocity is out of limits. Scaling it down.\",\n//                        \"[sim_env::RobotVelocityController::setTargetVelocity]\");\n//    }\n//    std::stringstream ss;\n//    ss << \"Setting target velocity \" << new_target.transpose();\n//    logger->logDebug(ss.str(), \"[sim_env::RobotVelocityController::setTargetVelocity]\");\n//    // set the new target\n//    _pid_controller.setStateDimension((unsigned int) new_target.size());\n//    _pid_controller.setTarget(new_target);\n//}\n//\n//bool RobotVelocityController::control(const Eigen::VectorXf &positions, const Eigen::VectorXf &velocities,\n//                                      float timestep, RobotConstPtr robot,\n//                                      Eigen::VectorXf &output) {\n//    Eigen::VectorXf target_velocity;\n//    _pid_controller.getTarget(target_velocity);\n//    if (target_velocity.size() != robot->getActiveDOFs().size()) {\n//        LoggerPtr logger = robot->getWorld()->getLogger();\n//        logger->logErr(\"The provided target position has different dimension from the active DOFs.\"\n//                               \"[sim_env::RobotVelocityController::setTargetVelocity]\");\n//        return false;\n//    }\n//    _pid_controller.control(output, velocities);\n////    LoggerPtr logger = robot->getWorld()->getLogger();\n////    std::stringstream ss;\n////    ss << \"Target velocities are \" << target_velocity.transpose();\n////    ss << \" Current velocities are \" << velocities.transpose();\n////    logger->logDebug(ss.str());\n//    // TODO limit efforts?\n//    return true;\n//}\n//\n//IndependentMDPIDController& RobotVelocityController::getPIDController() {\n//   return _pid_controller;\n//}\n//\n//LoggerPtr RobotVelocityController::getLogger() {\n//    if (_robot.expired()) {\n//        return DefaultLogger::getInstance();\n//    }\n//    RobotPtr robot = _robot.lock();\n//    return robot->getWorld()->getLogger();\n//}\n\nSE2RobotPositionController::SE2RobotPositionController(RobotPtr robot, RobotVelocityControllerPtr velocity_controller)\n    : _robot(robot)\n    , _velocity_controller(velocity_controller)\n{\n    assert(robot->getNumDOFs() >= 3);\n    assert(!robot->isStatic());\n    // velocity limits\n    auto dof_vel_limits = robot->getDOFVelocityLimits();\n    float x_limit = std::min(std::abs(dof_vel_limits(0, 0)), std::abs(dof_vel_limits(0, 1)));\n    float y_limit = std::min(std::abs(dof_vel_limits(1, 0)), std::abs(dof_vel_limits(1, 1)));\n    _cartesian_vel_limit = std::min(x_limit, y_limit);\n    _angular_vel_limit = std::min(std::abs(dof_vel_limits(2, 0)), std::abs(dof_vel_limits(2, 1)));\n    // accelaration limits\n    auto dof_acc_limits = robot->getDOFAccelerationLimits();\n    x_limit = std::min(std::abs(dof_acc_limits(0, 0)), std::abs(dof_acc_limits(0, 1)));\n    y_limit = std::min(std::abs(dof_acc_limits(1, 0)), std::abs(dof_acc_limits(1, 1)));\n    _cartesian_acc_limit = std::min(x_limit, y_limit);\n    _angular_acc_limit = std::min(std::abs(dof_acc_limits(2, 0)), std::abs(dof_acc_limits(2, 1)));\n    _set_point.resize(3);\n}\n\nSE2RobotPositionController::~SE2RobotPositionController()\n{\n}\n\nvoid SE2RobotPositionController::setPositionProjectionFn(PositionProjectionFn pos_constraint)\n{\n    _pos_proj_fn = pos_constraint;\n}\n\nvoid SE2RobotPositionController::setVelocityProjectionFn(VelocityProjectionFn vel_constraint)\n{\n    _vel_proj_fn = vel_constraint;\n}\n\ninline float normlizeOrientation(float v)\n{\n    const float pi = boost::math::constants::pi<float>();\n    float sign = std::signbit(v) ? -1.0f : 1.0f;\n    return sign * (std::abs(v) - std::floor((std::abs(v) + pi) / (2.0f * pi)) * 2.0f * pi);\n}\n\ninline float shortestSO2Direction(float val_1, float val_2)\n{\n    float value = val_2 - val_1;\n    if (std::abs(value) > boost::math::constants::pi<float>()) {\n        if (value > 0.0f) { // val_2 > val_1\n            value -= 2.0f * boost::math::constants::pi<float>();\n        } else {\n            value += 2.0f * boost::math::constants::pi<float>();\n        }\n    }\n    return value;\n}\n\nvoid SE2RobotPositionController::setTarget(const Eigen::VectorXf& target)\n{\n    static const std::string log_prefix(\"[SE2RobotPositionController::setTarget]\");\n    if (target.size() != 3) {\n        auto robot = getRobot();\n        auto logger = robot->getWorld()->getLogger();\n        logger->logErr(boost::format(\"Target has invalid dimension. Expected dimension is 3, actual dimension is %1%\") % target.size(), log_prefix);\n        return;\n    }\n    _last_target = target;\n    // normalize target orientation\n    _last_target[2] = normlizeOrientation(_last_target[2]);\n\n    // logger->logDebug(boost::format(\"Target %1%, %2%, %3%\") % _last_target[0] % _last_target[1] % _last_target[2], log_prefix);\n}\n\nvoid SE2RobotPositionController::setTargetPosition(const Eigen::VectorXf& position)\n{\n    setTarget(position);\n}\n\nunsigned int SE2RobotPositionController::getTargetDimension() const\n{\n    return 3;\n}\n\nRobotPtr SE2RobotPositionController::getRobot() const\n{\n    auto robot = _robot.lock();\n    if (!robot) {\n        std::logic_error(\"[SE2RobotPositionController::getRobot] Could not acquire robot. Weak pointer expired.\");\n    }\n    return robot;\n}\n\nbool SE2RobotPositionController::control(const Eigen::VectorXf& positions,\n    const Eigen::VectorXf& velocities,\n    float timestep,\n    RobotConstPtr robot,\n    Eigen::VectorXf& output)\n{\n    static const std::string log_prefix(\"[SE2RobotPositionController::control]\");\n    auto logger = robot->getConstWorld()->getConstLogger();\n    if (_last_target.size() != 3) {\n        logger->logWarn(\"No target set. Can not control any position\", log_prefix);\n        return false;\n    }\n    assert(positions.size() >= 3);\n    // compute error in cartesian position\n    Eigen::Vector2f cart_error = _last_target.head(2) - positions.head(2);\n    // logger->logDebug(boost::format(\"Target %1%, %2%, %3%\") % _last_target[0] % _last_target[1] % _last_target[2], log_prefix);\n    float cart_error_norm = cart_error.norm();\n    if (cart_error_norm > 0.0f) {\n        cart_error /= cart_error_norm;\n    }\n    // compute the maximum velocity we can have to not overshoot\n    float abs_max_break_velocity = std::sqrt(2.0f * cart_error_norm * _cartesian_acc_limit);\n    float cart_vel = std::min(abs_max_break_velocity, _cartesian_vel_limit);\n    // do the same for angular velocity\n    // float angular_error = _last_target[2] - positions[2];\n    float angular_error = shortestSO2Direction(positions[2], _last_target[2]);\n    float angular_error_norm = std::abs(angular_error);\n    float max_break_velocity_angular = std::sqrt(2.0f * angular_error_norm * _angular_acc_limit);\n    float omega = std::min(max_break_velocity_angular, _angular_vel_limit);\n    // if we are at our target position, command zero velocity, else compute a velocity taking us to our target\n    if (angular_error_norm < 1e-4 and cart_error_norm < 1e-4) {\n        _set_point.setZero();\n    } else {\n        // debug log\n        // logger->logDebug(boost::format(\"cart_error: %1%, cart_vel: %2%, angular_error: %3%, angular_vel: %4%\") % cart_error_norm % cart_vel % angular_error % omega, log_prefix);\n        // now compute how much time we will need for each to reach its destination\n        // we travel for some time at max velocity, followed by a decelaration phase\n        // in the decelaration we slow down from v to 0, i.e. its duration is v / a. The distance we travel\n        // in the decelaration is 0.5f * v / a. Accordingly, the time we are at the max velocity is t = s / v - 0.5 * v / a.\n        // If we are in the deceleration phase already, t becomes negative.\n        float t_angular_plateau = 0.0f;\n        if (angular_error_norm > 0.0f) {\n            t_angular_plateau = angular_error_norm / omega - 0.5f * omega / _angular_acc_limit;\n        }\n        float t_cart_plateau = 0.0f;\n        if (cart_error_norm > 0.0f) {\n            t_cart_plateau = cart_error_norm / cart_vel - 0.5f * cart_vel / _cartesian_acc_limit;\n        }\n        float t_angular = std::max(t_angular_plateau, 0.0f) + omega / _angular_acc_limit;\n        float t_cart = std::max(t_cart_plateau, 0.0f) + cart_vel / _cartesian_acc_limit;\n        // logger->logDebug(boost::format(\"Estimated duration till target, cart: %1%, angular %2%\") % t_cart % t_angular, log_prefix);\n        if (t_cart < t_angular) { // we will take more time to reach our angle destination, slow down cartesian\n            float a = _cartesian_acc_limit * t_angular;\n            float b = _cartesian_acc_limit * _cartesian_acc_limit * t_angular * t_angular - 2.0f * _cartesian_acc_limit * cart_error_norm;\n            assert(b >= 0.0f);\n            cart_vel = a - std::sqrt(b);\n        } else { // we will take more time to reach our cartesian destination, slow down angular\n            float a = _angular_acc_limit * t_cart;\n            float b = _angular_acc_limit * _angular_acc_limit * t_cart * t_cart - 2.0f * _angular_acc_limit * angular_error_norm;\n            assert(b >= 0.0f);\n            omega = a - std::sqrt(b);\n        }\n        // logger->logDebug(boost::format(\"Commanded velocities: cart: %1%, angular: %2%\") % cart_vel % omega, log_prefix);\n        // logger->logDebug(boost::format(\"Cartesian velocity direction (x, y): %1%, %2%\") % cart_error[0] % cart_error[1], log_prefix);\n        _set_point.head(2) = cart_vel * cart_error;\n        _set_point[2] = omega * angular_error / angular_error_norm;\n        // TODO We should also define the velocities during acceleration phase. For large position errors and max velocities,\n        // TODO it takes the robot different amount of time to accelerate to the respective target velocity for each DoF.\n        // TODO Hence, the robot will not move all the time in the direction that we command (this depends on the underlying velocity controller of course).\n        // TODO Alternatively, could define a velocity controller that operates in the same way as this position controller, i.e.\n        // TODO one that ensures that a commanded target velocity is reached synchronously for all DOFs.\n    }\n    _velocity_controller->setTargetVelocity(_set_point);\n    _velocity_controller->control(positions, velocities, timestep, robot, output);\n    return true;\n}", "meta": {"hexsha": "084ed9d2182cf189b26eb23a3124c3910ad61ca3", "size": 24463, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sim_env/Controller.cpp", "max_stars_repo_name": "Haoran-SONG/sim_env", "max_stars_repo_head_hexsha": "75b32f1b296779b6221eb9b6f3b8351bc755403e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sim_env/Controller.cpp", "max_issues_repo_name": "Haoran-SONG/sim_env", "max_issues_repo_head_hexsha": "75b32f1b296779b6221eb9b6f3b8351bc755403e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sim_env/Controller.cpp", "max_forks_repo_name": "Haoran-SONG/sim_env", "max_forks_repo_head_hexsha": "75b32f1b296779b6221eb9b6f3b8351bc755403e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-04T12:59:56.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-04T12:59:56.000Z", "avg_line_length": 39.203525641, "max_line_length": 181, "alphanum_fraction": 0.6613252667, "num_tokens": 6027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4071407222236004}}
{"text": "#pragma once\n\n#include <csv2/writer.hpp>\n\n#include <fmt/core.h>\n\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n#include <boost/range/numeric.hpp>\n\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <limits>\n#include <numeric>\n#include <ranges>\n#include <tuple>\n#include <type_traits>\n\nnamespace profitview::util\n{\n\nclass CsvWriter : public csv2::Writer<csv2::delimiter<','>>\n{    // Provides shorthand\n     // `write()`\npublic:\n    CsvWriter(auto& stream)\n        : csv2::Writer<csv2::delimiter<','>>(stream)\n    {}\n\n    void write(auto&&... args)\n    {\n        write_row<std::vector<std::string>>({fmt::format(\"{}\", std::forward<decltype(args)>(args))...});\n    }\n};\n\n// boost::accumulate should do this, but there's a compile fail\ninline auto accumulate(const auto& s, auto i) -> auto { return std::accumulate(std::begin(s), std::end(s), i); }\n\ninline auto accumulate(auto& s, auto i, auto op) -> auto { return std::accumulate(std::begin(s), std::end(s), i, op); }\n\nauto stdev(auto& s, auto m, int p) -> auto\n{    // Calculate standard deviation given mean (m)\n    auto const variance{[&m, &p](auto a, const auto& v) { return a + (v - m) * (v - m) / (p - 1);}};\n\n    return std::sqrt(accumulate(s, 0.0, variance));\n}\n\nauto ma(auto const& s, int p = 0) -> auto { return accumulate(s, 0.0) / (p ? p : s.size()); }\n\n// Exponential Moving Average (ema) difference formula from\n// https://en.wikipedia.org/wiki/Moving_average:\nauto ema(auto const& s, auto p, auto m = 0) -> auto\n{\n    auto alpha{2.0f / (p - 1)};\n    auto const ema_step{[&alpha](auto a, const auto& price) { return price * alpha + a * (1 - alpha); }};\n\n    return accumulate(s, m, ema_step);\n}\n\nauto abs_differences(const auto& prices, int e) -> auto\n{\n    auto b{prices.end() - e};\n    assert(prices.size() > e);\n\n    using namespace std::ranges;\n\n    subrange lagged{b - 1, prices.end() - 1}, aligned{b, prices.end()};\n    std::vector<typename std::remove_cvref_t<decltype(prices)>::value_type> differences(e);\n    transform(\n        lagged, aligned, differences.begin(), [](auto n, auto m) -> auto { return std::abs(n - m); });\n\n    return std::make_tuple(differences, prices.back() - *b);\n}\n\nauto is_monotonic(auto const& s) -> std::tuple<bool, bool>    // { monotonic, up }\n{                                                             // If monotonic     ascending      { true,  true  }\n    // If monotonic     descending     { true,  false }\n    // If non-monotonic now ascending  { false, true  }\n    // If non-monotonic now descending { false, false }\n    auto sgn = [](int a, int b) { return a < b ? 1 : (a == b) ? 0 : -1; };\n    int prev = 0;\n    for (int i = 0; i < s.size() - 1; ++i)\n    {\n        int c = sgn(s[i], s[i + 1]);\n        if (c != 0)\n        {\n            if (c != prev && prev != 0)\n            {\n                return {false, c == 1};\n            }\n            prev = c;\n        }\n    }\n    return {true, prev == 1};\n}\n\n}    // namespace profitview::util", "meta": {"hexsha": "797eda93619a62128da124c1179c6791339313d1", "size": 3028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils.hpp", "max_stars_repo_name": "Twon/cpp_crypto_algos", "max_stars_repo_head_hexsha": "e785f6c25ef50dc3c2f593b08b6857dffcd32eca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.hpp", "max_issues_repo_name": "Twon/cpp_crypto_algos", "max_issues_repo_head_hexsha": "e785f6c25ef50dc3c2f593b08b6857dffcd32eca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.hpp", "max_forks_repo_name": "Twon/cpp_crypto_algos", "max_forks_repo_head_hexsha": "e785f6c25ef50dc3c2f593b08b6857dffcd32eca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5858585859, "max_line_length": 119, "alphanum_fraction": 0.5762879789, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.4071407222236004}}
{"text": "// This file is part of libigl, a simple c++ geometry processing library.\n//\n// Copyright (C) 2014 Daniele Panozzo <daniele.panozzo@gmail.com>\n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n\n#include \"nrosy.h\"\n\n#include <igl/copyleft/comiso/nrosy.h>\n#include <igl/triangle_triangle_adjacency.h>\n#include <igl/edge_topology.h>\n#include <igl/per_face_normals.h>\n\n#include <iostream>\n#include <fstream>\n\n#include <Eigen/Geometry>\n#include <Eigen/Sparse>\n#include <queue>\n\n#include <gmm/gmm.h>\n#include <CoMISo/Solver/ConstrainedSolver.hh>\n#include <CoMISo/Solver/MISolver.hh>\n#include <CoMISo/Solver/GMM_Tools.hh>\n\nnamespace igl\n{\nnamespace copyleft\n{\n\nnamespace comiso\n{\nclass NRosyField\n{\npublic:\n  // Init\n  IGL_INLINE NRosyField(const Eigen::MatrixXd& _V, const Eigen::MatrixXi& _F);\n\n  // Generate the N-rosy field\n  // N degree of the rosy field\n  // roundseparately: round the integer variables one at a time, slower but higher quality\n  IGL_INLINE void solve(const int N = 4);\n\n  // Set a hard constraint on fid\n  // fid: face id\n  // v: direction to fix (in 3d)\n  IGL_INLINE void setConstraintHard(const int fid, const Eigen::Vector3d& v);\n\n  // Set a soft constraint on fid\n  // fid: face id\n  // w: weight of the soft constraint, clipped between 0 and 1\n  // v: direction to fix (in 3d)\n  IGL_INLINE void setConstraintSoft(const int fid, const double w, const Eigen::Vector3d& v);\n\n  // Set the ratio between smoothness and soft constraints (0 -> smoothness only, 1 -> soft constr only)\n  IGL_INLINE void setSoftAlpha(double alpha);\n\n  // Reset constraints (at least one constraint must be present or solve will fail)\n  IGL_INLINE void resetConstraints();\n\n  // Return the current field\n  IGL_INLINE Eigen::MatrixXd getFieldPerFace();\n\n  // Return the current field (in Ahish's ffield format)\n  IGL_INLINE Eigen::MatrixXd getFFieldPerFace();\n\n  // Compute singularity indexes\n  IGL_INLINE void findCones(int N);\n\n  // Return the singularities\n  IGL_INLINE Eigen::VectorXd getSingularityIndexPerVertex();\n\nprivate:\n\n  // Compute angle differences between reference frames\n  IGL_INLINE void computek();\n\n  // Remove useless matchings\n  IGL_INLINE void reduceSpace();\n\n  // Prepare the system matrix\n  IGL_INLINE void prepareSystemMatrix(const int N);\n\n  // Solve without roundings\n  IGL_INLINE void solveNoRoundings();\n\n  // Solve with roundings using CoMIso\n  IGL_INLINE void solveRoundings();\n\n  // Round all p to 0 and fix\n  IGL_INLINE void roundAndFixToZero();\n\n  // Round all p and fix\n  IGL_INLINE void roundAndFix();\n\n  // Convert a vector in 3d to an angle wrt the local reference system\n  IGL_INLINE double convert3DtoLocal(unsigned fid, const Eigen::Vector3d& v);\n\n  // Convert an angle wrt the local reference system to a 3d vector\n  IGL_INLINE Eigen::Vector3d convertLocalto3D(unsigned fid, double a);\n\n  // Compute the per vertex angle defect\n  IGL_INLINE Eigen::VectorXd angleDefect();\n\n  // Temporary variable for the field\n  Eigen::VectorXd angles;\n\n  // Hard constraints\n  Eigen::VectorXd hard;\n  std::vector<bool> isHard;\n\n  // Soft constraints\n  Eigen::VectorXd soft;\n  Eigen::VectorXd wSoft;\n  double          softAlpha;\n\n  // Face Topology\n  Eigen::MatrixXi TT, TTi;\n\n  // Edge Topology\n  Eigen::MatrixXi EV, FE, EF;\n  std::vector<bool> isBorderEdge;\n\n  // Per Edge information\n  // Angle between two reference frames\n  Eigen::VectorXd k;\n\n  // Jumps\n  Eigen::VectorXi p;\n  std::vector<bool> pFixed;\n\n  // Mesh\n  Eigen::MatrixXd V;\n  Eigen::MatrixXi F;\n\n  // Normals per face\n  Eigen::MatrixXd N;\n\n  // Singularity index\n  Eigen::VectorXd singularityIndex;\n\n  // Reference frame per triangle\n  std::vector<Eigen::MatrixXd> TPs;\n\n  // System stuff\n  Eigen::SparseMatrix<double> A;\n  Eigen::VectorXd b;\n  Eigen::VectorXi tag_t;\n  Eigen::VectorXi tag_p;\n\n};\n\n} // NAMESPACE COMISO\n} // NAMESPACE COPYLEFT\n} // NAMESPACE IGL\n\nigl::copyleft::comiso::NRosyField::NRosyField(const Eigen::MatrixXd& _V, const Eigen::MatrixXi& _F)\n{\n  using namespace std;\n  using namespace Eigen;\n\n  V = _V;\n  F = _F;\n\n  assert(V.rows() > 0);\n  assert(F.rows() > 0);\n\n\n  // Generate topological relations\n  igl::triangle_triangle_adjacency(F,TT,TTi);\n  igl::edge_topology(V,F, EV, FE, EF);\n\n  // Flag border edges\n  isBorderEdge.resize(EV.rows());\n  for(unsigned i=0; i<EV.rows(); ++i)\n    isBorderEdge[i] = (EF(i,0) == -1) || ((EF(i,1) == -1));\n\n  // Generate normals per face\n  igl::per_face_normals(V, F, N);\n\n  // Generate reference frames\n  for(unsigned fid=0; fid<F.rows(); ++fid)\n  {\n    // First edge\n    Vector3d e1 = V.row(F(fid,1)) - V.row(F(fid,0));\n    e1.normalize();\n    Vector3d e2 = N.row(fid);\n    e2 = e2.cross(e1);\n    e2.normalize();\n\n    MatrixXd TP(2,3);\n    TP << e1.transpose(), e2.transpose();\n    TPs.push_back(TP);\n  }\n\n  // Alloc internal variables\n  angles = VectorXd::Zero(F.rows());\n  p = VectorXi::Zero(EV.rows());\n  pFixed.resize(EV.rows());\n  k = VectorXd::Zero(EV.rows());\n  singularityIndex = VectorXd::Zero(V.rows());\n\n  // Reset the constraints\n  resetConstraints();\n\n  // Compute k, differences between reference frames\n  computek();\n\n  softAlpha = 0.5;\n}\n\nvoid igl::copyleft::comiso::NRosyField::setSoftAlpha(double alpha)\n{\n  assert(alpha >= 0 && alpha < 1);\n  softAlpha = alpha;\n}\n\n\nvoid igl::copyleft::comiso::NRosyField::prepareSystemMatrix(const int N)\n{\n  using namespace std;\n  using namespace Eigen;\n\n  double Nd = N;\n\n  // Minimize the MIQ energy\n  // Energy on edge ij is\n  //     (t_i - t_j + kij + pij*(2*pi/N))^2\n  // Partial derivatives:\n  //   t_i: 2     ( t_i - t_j + kij + pij*(2*pi/N)) = 0\n  //   t_j: 2     (-t_i + t_j - kij - pij*(2*pi/N)) = 0\n  //   pij: 4pi/N ( t_i - t_j + kij + pij*(2*pi/N)) = 0\n  //\n  //          t_i      t_j         pij       kij\n  // t_i [     2       -2           4pi/N      2    ]\n  // t_j [    -2        2          -4pi/N     -2    ]\n  // pij [   4pi/N   -4pi/N    2*(2pi/N)^2   4pi/N  ]\n\n  // Count and tag the variables\n  tag_t = VectorXi::Constant(F.rows(),-1);\n  vector<int> id_t;\n  int count = 0;\n  for(unsigned i=0; i<F.rows(); ++i)\n    if (!isHard[i])\n    {\n      tag_t(i) = count++;\n      id_t.push_back(i);\n    }\n\n  unsigned count_t = id_t.size();\n\n  tag_p = VectorXi::Constant(EF.rows(),-1);\n  vector<int> id_p;\n  for(unsigned i=0; i<EF.rows(); ++i)\n  {\n    if (!pFixed[i])\n    {\n      // if it is not fixed then it is a variable\n      tag_p(i) = count++;\n    }\n\n    // if it is not a border edge,\n    if (!isBorderEdge[i])\n    {\n      // and it is not between two fixed faces\n      if (!(isHard[EF(i,0)] && isHard[EF(i,1)]))\n      {\n          // then it participates in the energy!\n          id_p.push_back(i);\n      }\n    }\n  }\n\n  unsigned count_p = count - count_t;\n  // System sizes: A (count_t + count_p) x (count_t + count_p)\n  //               b (count_t + count_p)\n\n  b = VectorXd::Zero(count_t + count_p);\n\n  std::vector<Eigen::Triplet<double> > T;\n  T.reserve(3 * 4 * count_p);\n\n  for(unsigned r=0; r<id_p.size(); ++r)\n  {\n    int eid = id_p[r];\n    int i = EF(eid,0);\n    int j = EF(eid,1);\n    bool isFixed_i = isHard[i];\n    bool isFixed_j = isHard[j];\n    bool isFixed_p = pFixed[eid];\n    int row;\n    // (i)-th row: t_i [     2       -2           4pi/N      2    ]\n    if (!isFixed_i)\n    {\n      row = tag_t[i];\n      if (isFixed_i) b(row) += -2               * hard[i]; else T.push_back(Eigen::Triplet<double>(row,tag_t[i]  , 2             ));\n      if (isFixed_j) b(row) +=  2               * hard[j]; else T.push_back(Eigen::Triplet<double>(row,tag_t[j]  ,-2             ));\n      if (isFixed_p) b(row) += -((4 * igl::PI)/Nd) * p[eid] ; else T.push_back(Eigen::Triplet<double>(row,tag_p[eid],((4 * igl::PI)/Nd)));\n      b(row) += -2 * k[eid];\n      assert(hard[i] == hard[i]);\n      assert(hard[j] == hard[j]);\n      assert(p[eid] == p[eid]);\n      assert(k[eid] == k[eid]);\n      assert(b(row) == b(row));\n    }\n    // (j)+1 -th row: t_j [    -2        2          -4pi/N     -2    ]\n    if (!isFixed_j)\n    {\n      row = tag_t[j];\n      if (isFixed_i) b(row) += 2               * hard[i]; else T.push_back(Eigen::Triplet<double>(row,tag_t[i]  , -2             ));\n      if (isFixed_j) b(row) += -2              * hard[j]; else T.push_back(Eigen::Triplet<double>(row,tag_t[j] ,  2              ));\n      if (isFixed_p) b(row) += ((4 * igl::PI)/Nd) * p[eid] ; else T.push_back(Eigen::Triplet<double>(row,tag_p[eid],-((4 * igl::PI)/Nd)));\n      b(row) += 2 * k[eid];\n      assert(k[eid] == k[eid]);\n      assert(b(row) == b(row));\n    }\n    // (r*3)+2 -th row: pij [   4pi/N   -4pi/N    2*(2pi/N)^2   4pi/N  ]\n    if (!isFixed_p)\n    {\n      row = tag_p[eid];\n      if (isFixed_i) b(row) += -(4 * igl::PI)/Nd              * hard[i]; else T.push_back(Eigen::Triplet<double>(row,tag_t[i] ,   (4 * igl::PI)/Nd             ));\n      if (isFixed_j) b(row) +=  (4 * igl::PI)/Nd              * hard[j]; else T.push_back(Eigen::Triplet<double>(row,tag_t[j] ,  -(4 * igl::PI)/Nd             ));\n      if (isFixed_p) b(row) += -(2 * pow(((2*igl::PI)/Nd),2)) * p[eid] ;  else T.push_back(Eigen::Triplet<double>(row,tag_p[eid],  (2 * pow(((2*igl::PI)/Nd),2))));\n      b(row) += - (4 * igl::PI)/Nd * k[eid];\n      assert(k[eid] == k[eid]);\n      assert(b(row) == b(row));\n    }\n\n  }\n\n  A = SparseMatrix<double>(count_t + count_p, count_t + count_p);\n  A.setFromTriplets(T.begin(), T.end());\n\n  // Soft constraints\n  bool addSoft = false;\n\n  for(unsigned i=0; i<wSoft.size();++i)\n    if (wSoft[i] != 0)\n      addSoft = true;\n\n  if (addSoft)\n  {\n    cerr << \" Adding soft here: \" << endl;\n    cerr << \" softAplha: \" << softAlpha << endl;\n    VectorXd bSoft = VectorXd::Zero(count_t + count_p);\n\n    std::vector<Eigen::Triplet<double> > TSoft;\n    TSoft.reserve(2 * count_p);\n\n    for(unsigned i=0; i<F.rows(); ++i)\n    {\n      int varid = tag_t[i];\n      if (varid != -1) // if it is a variable in the system\n      {\n        TSoft.push_back(Eigen::Triplet<double>(varid,varid,wSoft[i]));\n        bSoft[varid] += wSoft[i] * soft[i];\n      }\n    }\n    SparseMatrix<double> ASoft(count_t + count_p, count_t + count_p);\n    ASoft.setFromTriplets(TSoft.begin(), TSoft.end());\n\n//    ofstream s(\"/Users/daniele/As.txt\");\n//    for(unsigned i=0; i<TSoft.size(); ++i)\n//      s << TSoft[i].row() << \" \" << TSoft[i].col() << \" \" << TSoft[i].value() << endl;\n//    s.close();\n\n//    ofstream s2(\"/Users/daniele/bs.txt\");\n//    for(unsigned i=0; i<bSoft.rows(); ++i)\n//      s2 << bSoft(i) << endl;\n//    s2.close();\n\n    // Stupid Eigen bug\n    SparseMatrix<double> Atmp (count_t + count_p, count_t + count_p);\n    SparseMatrix<double> Atmp2(count_t + count_p, count_t + count_p);\n    SparseMatrix<double> Atmp3(count_t + count_p, count_t + count_p);\n\n    // Merge the two part of the energy\n    Atmp = (1.0 - softAlpha)*A;\n    Atmp2 = softAlpha * ASoft;\n    Atmp3 = Atmp+Atmp2;\n\n    A = Atmp3;\n    b = b*(1.0 - softAlpha) + bSoft * softAlpha;\n  }\n\n//  ofstream s(\"/Users/daniele/A.txt\");\n//  for (int k=0; k<A.outerSize(); ++k)\n//    for (SparseMatrix<double>::InnerIterator it(A,k); it; ++it)\n//    {\n//      s << it.row() << \" \" << it.col() << \" \" << it.value() << endl;\n//    }\n//  s.close();\n//\n//  ofstream s2(\"/Users/daniele/b.txt\");\n//  for(unsigned i=0; i<b.rows(); ++i)\n//    s2 << b(i) << endl;\n//  s2.close();\n}\n\nvoid igl::copyleft::comiso::NRosyField::solveNoRoundings()\n{\n  using namespace std;\n  using namespace Eigen;\n\n  // Solve the linear system\n  SimplicialLDLT<SparseMatrix<double> > solver;\n  solver.compute(A);\n  VectorXd x = solver.solve(b);\n\n  // Copy the result back\n  for(unsigned i=0; i<F.rows(); ++i)\n    if (tag_t[i] != -1)\n      angles[i] = x(tag_t[i]);\n    else\n      angles[i] = hard[i];\n\n  for(unsigned i=0; i<EF.rows(); ++i)\n    if(tag_p[i]  != -1)\n      p[i] = roundl(x[tag_p[i]]);\n}\n\nvoid igl::copyleft::comiso::NRosyField::solveRoundings()\n{\n  using namespace std;\n  using namespace Eigen;\n\n  unsigned n = A.rows();\n\n  gmm::col_matrix< gmm::wsvector< double > > gmm_A;\n  std::vector<double> gmm_b;\n  std::vector<int> ids_to_round;\n  std::vector<double> x;\n\n  gmm_A.resize(n,n);\n  gmm_b.resize(n);\n  x.resize(n);\n\n  // Copy A\n  for (int k=0; k<A.outerSize(); ++k)\n    for (SparseMatrix<double>::InnerIterator it(A,k); it; ++it)\n    {\n      gmm_A(it.row(),it.col()) += it.value();\n    }\n\n  // Copy b\n  for(unsigned i=0; i<n;++i)\n    gmm_b[i] = b[i];\n\n  // Set variables to round\n  ids_to_round.clear();\n  for(unsigned i=0; i<tag_p.size();++i)\n    if(tag_p[i] != -1)\n      ids_to_round.push_back(tag_p[i]);\n\n  // Empty constraints\n  gmm::row_matrix< gmm::wsvector< double > > gmm_C(0, n);\n\n  COMISO::ConstrainedSolver cs;\n  //print_miso_settings(cs.misolver());\n  cs.solve(gmm_C, gmm_A, x, gmm_b, ids_to_round, 0.0, false, true);\n\n  // Copy the result back\n  for(unsigned i=0; i<F.rows(); ++i)\n    if (tag_t[i] != -1)\n      angles[i] = x[tag_t[i]];\n    else\n      angles[i] = hard[i];\n\n  for(unsigned i=0; i<EF.rows(); ++i)\n    if(tag_p[i]  != -1)\n      p[i] = roundl(x[tag_p[i]]);\n\n}\n\n\nvoid igl::copyleft::comiso::NRosyField::roundAndFix()\n{\n  for(unsigned i=0; i<p.rows(); ++i)\n    pFixed[i] = true;\n}\n\nvoid igl::copyleft::comiso::NRosyField::roundAndFixToZero()\n{\n  for(unsigned i=0; i<p.rows(); ++i)\n  {\n    pFixed[i] = true;\n    p[i] = 0;\n  }\n}\n\nvoid igl::copyleft::comiso::NRosyField::solve(const int N)\n{\n  // Reduce the search space by fixing matchings\n  reduceSpace();\n\n  // Build the system\n  prepareSystemMatrix(N);\n\n  // Solve with integer roundings\n  solveRoundings();\n\n  // This is a very greedy solving strategy\n  // // Solve with no roundings\n  // solveNoRoundings();\n  //\n  // // Round all p and fix them\n  // roundAndFix();\n  //\n  // // Build the system\n  // prepareSystemMatrix(N);\n  //\n  // // Solve with no roundings (they are all fixed)\n  // solveNoRoundings();\n\n  // Find the cones\n  findCones(N);\n}\n\nvoid igl::copyleft::comiso::NRosyField::setConstraintHard(const int fid, const Eigen::Vector3d& v)\n{\n  isHard[fid] = true;\n  hard(fid) = convert3DtoLocal(fid, v);\n}\n\nvoid igl::copyleft::comiso::NRosyField::setConstraintSoft(const int fid, const double w, const Eigen::Vector3d& v)\n{\n  wSoft(fid) = w;\n  soft(fid) = convert3DtoLocal(fid, v);\n}\n\nvoid igl::copyleft::comiso::NRosyField::resetConstraints()\n{\n  using namespace std;\n  using namespace Eigen;\n\n  isHard.resize(F.rows());\n  for(unsigned i=0; i<F.rows(); ++i)\n    isHard[i] = false;\n  hard   = VectorXd::Zero(F.rows());\n\n  wSoft  = VectorXd::Zero(F.rows());\n  soft   = VectorXd::Zero(F.rows());\n}\n\nEigen::MatrixXd igl::copyleft::comiso::NRosyField::getFieldPerFace()\n{\n  using namespace std;\n  using namespace Eigen;\n\n  MatrixXd result(F.rows(),3);\n  for(unsigned i=0; i<F.rows(); ++i)\n    result.row(i) = convertLocalto3D(i, angles(i));\n  return result;\n}\n\nEigen::MatrixXd igl::copyleft::comiso::NRosyField::getFFieldPerFace()\n{\n  using namespace std;\n  using namespace Eigen;\n\n  MatrixXd result(F.rows(),6);\n  for(unsigned i=0; i<F.rows(); ++i)\n  {\n      Vector3d v1 = convertLocalto3D(i, angles(i));\n      Vector3d n = N.row(i);\n      Vector3d v2 = n.cross(v1);\n      v1.normalize();\n      v2.normalize();\n\n      result.block(i,0,1,3) = v1.transpose();\n      result.block(i,3,1,3) = v2.transpose();\n  }\n  return result;\n}\n\n\nvoid igl::copyleft::comiso::NRosyField::computek()\n{\n  using namespace std;\n  using namespace Eigen;\n\n  // For every non-border edge\n  for (unsigned eid=0; eid<EF.rows(); ++eid)\n  {\n    if (!isBorderEdge[eid])\n    {\n      int fid0 = EF(eid,0);\n      int fid1 = EF(eid,1);\n\n      Vector3d N0 = N.row(fid0);\n      Vector3d N1 = N.row(fid1);\n\n      // find common edge on triangle 0 and 1\n      int fid0_vc = -1;\n      int fid1_vc = -1;\n      for (unsigned i=0;i<3;++i)\n      {\n        if (EV(eid,0) == F(fid0,i))\n          fid0_vc = i;\n        if (EV(eid,1) == F(fid1,i))\n          fid1_vc = i;\n      }\n      assert(fid0_vc != -1);\n      assert(fid1_vc != -1);\n\n      Vector3d common_edge = V.row(F(fid0,(fid0_vc+1)%3)) - V.row(F(fid0,fid0_vc));\n      common_edge.normalize();\n\n      // Map the two triangles in a new space where the common edge is the x axis and the N0 the z axis\n      MatrixXd P(3,3);\n      VectorXd o = V.row(F(fid0,fid0_vc));\n      VectorXd tmp = -N0.cross(common_edge);\n      P << common_edge, tmp, N0;\n      P.transposeInPlace();\n\n\n      MatrixXd V0(3,3);\n      V0.row(0) = V.row(F(fid0,0)).transpose() -o;\n      V0.row(1) = V.row(F(fid0,1)).transpose() -o;\n      V0.row(2) = V.row(F(fid0,2)).transpose() -o;\n\n      V0 = (P*V0.transpose()).transpose();\n\n      assert(V0(0,2) < 10e-10);\n      assert(V0(1,2) < 10e-10);\n      assert(V0(2,2) < 10e-10);\n\n      MatrixXd V1(3,3);\n      V1.row(0) = V.row(F(fid1,0)).transpose() -o;\n      V1.row(1) = V.row(F(fid1,1)).transpose() -o;\n      V1.row(2) = V.row(F(fid1,2)).transpose() -o;\n      V1 = (P*V1.transpose()).transpose();\n\n      assert(V1(fid1_vc,2) < 10e-10);\n      assert(V1((fid1_vc+1)%3,2) < 10e-10);\n\n      // compute rotation R such that R * N1 = N0\n      // i.e. map both triangles to the same plane\n      double alpha = -atan2(V1((fid1_vc+2)%3,2),V1((fid1_vc+2)%3,1));\n\n      MatrixXd R(3,3);\n      R << 1,          0,            0,\n           0, cos(alpha), -sin(alpha) ,\n           0, sin(alpha),  cos(alpha);\n      V1 = (R*V1.transpose()).transpose();\n\n      assert(V1(0,2) < 10e-10);\n      assert(V1(1,2) < 10e-10);\n      assert(V1(2,2) < 10e-10);\n\n      // measure the angle between the reference frames\n      // k_ij is the angle between the triangle on the left and the one on the right\n      VectorXd ref0 = V0.row(1) - V0.row(0);\n      VectorXd ref1 = V1.row(1) - V1.row(0);\n\n      ref0.normalize();\n      ref1.normalize();\n\n      double ktemp = atan2(ref1(1),ref1(0)) - atan2(ref0(1),ref0(0));\n\n      // just to be sure, rotate ref0 using angle ktemp...\n      MatrixXd R2(2,2);\n      R2 << cos(ktemp), -sin(ktemp), sin(ktemp), cos(ktemp);\n\n      tmp = R2*ref0.head<2>();\n\n      assert(tmp(0) - ref1(0) < 10^10);\n      assert(tmp(1) - ref1(1) < 10^10);\n\n      k[eid] = ktemp;\n    }\n  }\n\n}\n\nvoid igl::copyleft::comiso::NRosyField::reduceSpace()\n{\n  using namespace std;\n  using namespace Eigen;\n\n  // All variables are free in the beginning\n  for(unsigned i=0; i<EV.rows(); ++i)\n    pFixed[i] = false;\n\n  vector<VectorXd> debug;\n\n  // debug\n//  MatrixXd B(F.rows(),3);\n//  for(unsigned i=0; i<F.rows(); ++i)\n//    B.row(i) = 1./3. * (V.row(F(i,0)) + V.row(F(i,1)) + V.row(F(i,2)));\n\n  vector<bool> visited(EV.rows());\n  for(unsigned i=0; i<EV.rows(); ++i)\n    visited[i] = false;\n\n  vector<bool> starting(EV.rows());\n  for(unsigned i=0; i<EV.rows(); ++i)\n    starting[i] = false;\n\n  queue<int> q;\n  for(unsigned i=0; i<F.rows(); ++i)\n    if (isHard[i] || wSoft[i] != 0)\n    {\n      q.push(i);\n      starting[i] = true;\n    }\n\n  // Reduce the search space (see MI paper)\n  while (!q.empty())\n  {\n    int c = q.front();\n    q.pop();\n\n    visited[c] = true;\n    for(int i=0; i<3; ++i)\n    {\n      int eid = FE(c,i);\n      int fid = TT(c,i);\n\n      // skip borders\n      if (fid != -1)\n      {\n        assert((EF(eid,0) == c && EF(eid,1) == fid) || (EF(eid,1) == c && EF(eid,0) == fid));\n        // for every neighbouring face\n        if (!visited[fid] && !starting[fid])\n        {\n          pFixed[eid] = true;\n          p[eid] = 0;\n          visited[fid] = true;\n          q.push(fid);\n\n        }\n      }\n      else\n      {\n        // fix borders\n        pFixed[eid] = true;\n        p[eid] = 0;\n      }\n    }\n\n  }\n\n  // Force matchings between fixed faces\n  for(unsigned i=0; i<F.rows();++i)\n  {\n    if (isHard[i])\n    {\n      for(unsigned int j=0; j<3; ++j)\n      {\n        int fid = TT(i,j);\n        if ((fid!=-1) && (isHard[fid]))\n        {\n          // i and fid are adjacent and fixed\n          int eid = FE(i,j);\n          int fid0 = EF(eid,0);\n          int fid1 = EF(eid,1);\n\n          pFixed[eid] = true;\n          p[eid] = roundl(2.0/igl::PI*(hard(fid1) - hard(fid0) - k(eid)));\n        }\n      }\n    }\n  }\n\n//  std::ofstream s(\"/Users/daniele/debug.txt\");\n//  for(unsigned i=0; i<debug.size(); i += 2)\n//    s << debug[i].transpose() << \" \" << debug[i+1].transpose() << endl;\n//  s.close();\n\n}\n\ndouble igl::copyleft::comiso::NRosyField::convert3DtoLocal(unsigned fid, const Eigen::Vector3d& v)\n{\n  using namespace std;\n  using namespace Eigen;\n\n  // Project onto the tangent plane\n  Vector2d vp = TPs[fid] * v;\n\n  // Convert to angle\n  return atan2(vp(1),vp(0));\n}\n\nEigen::Vector3d igl::copyleft::comiso::NRosyField::convertLocalto3D(unsigned fid, double a)\n{\n  using namespace std;\n  using namespace Eigen;\n\n  Vector2d vp(cos(a),sin(a));\n  return vp.transpose() * TPs[fid];\n}\n\nEigen::VectorXd igl::copyleft::comiso::NRosyField::angleDefect()\n{\n  Eigen::VectorXd A = Eigen::VectorXd::Constant(V.rows(),-2*igl::PI);\n\n  for (unsigned i=0; i < F.rows(); ++i)\n  {\n    for (int j = 0; j < 3; ++j)\n    {\n      Eigen::VectorXd a = V.row(F(i,(j+1)%3)) - V.row(F(i,j));\n      Eigen::VectorXd b = V.row(F(i,(j+2)%3)) - V.row(F(i,j));\n      double t = a.transpose()*b;\n      t /= (a.norm() * b.norm());\n      A(F(i,j)) += acos(t);\n    }\n  }\n\n  return A;\n}\n\nvoid igl::copyleft::comiso::NRosyField::findCones(int N)\n{\n  // Compute I0, see http://www.graphics.rwth-aachen.de/media/papers/bommes_zimmer_2009_siggraph_011.pdf for details\n\n  Eigen::VectorXd I0 = Eigen::VectorXd::Zero(V.rows());\n\n  // first the k\n  for (unsigned i=0; i < EV.rows(); ++i)\n  {\n    if (!isBorderEdge[i])\n    {\n      I0(EV(i,0)) -= k(i);\n      I0(EV(i,1)) += k(i);\n    }\n  }\n\n  // then the A\n  Eigen::VectorXd A = angleDefect();\n\n  I0 = I0 + A;\n\n  // normalize\n  I0 = I0 / (2*igl::PI);\n\n  // round to integer (remove numerical noise)\n  for (unsigned i=0; i < I0.size(); ++i)\n    I0(i) = round(I0(i));\n\n  // compute I\n  Eigen::VectorXd I = I0;\n\n  for (unsigned i=0; i < EV.rows(); ++i)\n  {\n    if (!isBorderEdge[i])\n    {\n      I(EV(i,0)) -= double(p(i))/double(N);\n      I(EV(i,1)) += double(p(i))/double(N);\n    }\n  }\n\n  // Clear the vertices on the edges\n  for (unsigned i=0; i < EV.rows(); ++i)\n  {\n    if (isBorderEdge[i])\n    {\n      I0(EV(i,0)) = 0;\n      I0(EV(i,1)) = 0;\n      I(EV(i,0)) = 0;\n      I(EV(i,1)) = 0;\n      A(EV(i,0)) = 0;\n      A(EV(i,1)) = 0;\n    }\n  }\n\n  singularityIndex = I;\n}\n\nEigen::VectorXd igl::copyleft::comiso::NRosyField::getSingularityIndexPerVertex()\n{\n  return singularityIndex;\n}\n\nIGL_INLINE void igl::copyleft::comiso::nrosy(\n  const Eigen::MatrixXd& V,\n  const Eigen::MatrixXi& F,\n  const Eigen::VectorXi& b,\n  const Eigen::MatrixXd& bc,\n  const Eigen::VectorXi& b_soft,\n  const Eigen::VectorXd& w_soft,\n  const Eigen::MatrixXd& bc_soft,\n  const int N,\n  const double soft,\n  Eigen::MatrixXd& R,\n  Eigen::VectorXd& S\n  )\n{\n  // Init solver\n  igl::copyleft::comiso::NRosyField solver(V,F);\n\n  // Add hard constraints\n  for (unsigned i=0; i<b.size();++i)\n    solver.setConstraintHard(b(i),bc.row(i));\n\n  // Add soft constraints\n  for (unsigned i=0; i<b_soft.size();++i)\n    solver.setConstraintSoft(b_soft(i),w_soft(i),bc_soft.row(i));\n\n  // Set the soft constraints global weight\n  solver.setSoftAlpha(soft);\n\n  // Interpolate\n  solver.solve(N);\n\n  // Copy the result back\n  R = solver.getFieldPerFace();\n\n  // Extract singularity indices\n  S = solver.getSingularityIndexPerVertex();\n}\n\n\nIGL_INLINE void igl::copyleft::comiso::nrosy(\n                           const Eigen::MatrixXd& V,\n                           const Eigen::MatrixXi& F,\n                           const Eigen::VectorXi& b,\n                           const Eigen::MatrixXd& bc,\n                           const int N,\n                           Eigen::MatrixXd& R,\n                           Eigen::VectorXd& S\n                           )\n{\n  // Init solver\n  igl::copyleft::comiso::NRosyField solver(V,F);\n\n  // Add hard constraints\n  for (unsigned i=0; i<b.size();++i)\n    solver.setConstraintHard(b(i),bc.row(i));\n\n  // Interpolate\n  solver.solve(N);\n\n  // Copy the result back\n  R = solver.getFieldPerFace();\n\n  // Extract singularity indices\n  S = solver.getSingularityIndexPerVertex();\n}\n", "meta": {"hexsha": "0f3ee86bc76b77262ea461b3557a141e81e923f2", "size": 24056, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "isometric-deformation/ext/libigl/include/igl/copyleft/comiso/nrosy.cpp", "max_stars_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_stars_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2019-11-27T00:43:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-25T14:35:54.000Z", "max_issues_repo_path": "isometric-deformation/ext/libigl/include/igl/copyleft/comiso/nrosy.cpp", "max_issues_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_issues_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isometric-deformation/ext/libigl/include/igl/copyleft/comiso/nrosy.cpp", "max_forks_repo_name": "jiayaozhang/CS-370-Mesh-Processing", "max_forks_repo_head_hexsha": "26646d29af8cbc0d461302afa137f12b508b8b1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-11-27T05:19:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-23T22:49:53.000Z", "avg_line_length": 25.5371549894, "max_line_length": 163, "alphanum_fraction": 0.5796890589, "num_tokens": 7692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.40714071401932117}}
{"text": "/**\n * @file \n * @author Denise Ratasich\n * @date 11.10.2013\n *\n * @brief Implementation of the SIR particle filter.\n */\n\n#include <ctime>\n#include <boost/random/variate_generator.hpp>\n#include <boost/random/uniform_real.hpp>\n// uniform_real gets depricated with newer versions, change to\n// uniform_real_distribution with newer version of boost! (see also\n// ParticleFilterSIR::resample)\n//#include <boost/random/uniform_real_distribution.hpp>\n\n#include \"estimation/ParticleFilterSIR.h\"\n#include \"probability/pdfs.h\"\n#include \"probability/sampling.h\"\n\nnamespace estimation \n{\n  ParticleFilterSIR::ParticleFilterSIR (unsigned int N) \n    : AbstractParticleFilter(N)\n  {\n    rng.seed((unsigned int)clock());\n  }\n\n  ParticleFilterSIR::~ParticleFilterSIR () \n  {\n    // nothing to do\n  }\n  \n  void ParticleFilterSIR::log(std::ostream& os, Log type, int index) const\n  {\n    switch (type)\n    {\n    case PARTICLES:\n      for (int i = 0; i < particles.size(); i++)\n\tos << particles[i][index] << \" \";\n      os << std::endl;\n      break;\n    case WEIGHTS:\n      for (int i = 0; i < particles.size(); i++)\n\tos << weights[i] << \" \";\n      os << std::endl;\n      break;\n    case NEFF:\n      os << Neff << std::endl;\n      break;\n    }\n  }\n\n  // -----------------------------------------\n  // getters and setters\n  // -----------------------------------------\n  void ParticleFilterSIR::setProcessNoiseCovariance (MatrixXd& Q)\n  {\n    this->Q = Q;\n    validated = false;\n  }\n\n  void ParticleFilterSIR::setMeasurementNoiseCovariance (MatrixXd& R)\n  {\n    this->R = R;\n    validated = false;\n  }\n\n  void ParticleFilterSIR::validate (void)\n  {\n    try \n    {\n      // check for minimal initialization -----------------------\n      if (!f)\t\t\t// callback empty\n\tthrow std::runtime_error(\"State transition model missing.\");\n      if (!h)\t\t\t// callback empty\n\tthrow std::runtime_error(\"Observation model missing.\");\n      if (Q.rows() == 0)\n\tthrow std::runtime_error(\"Process noise covariance missing.\");\n      if (R.rows() == 0)\n\tthrow std::runtime_error(\"Measurement noise covariance missing.\");\n      if (particles[0].size() == 0)\n\tthrow std::runtime_error(\"Particles not initialized.\");      \n\n      // take sizes from required parameters\n      int n = particles[0].size();\n      int m = R.rows();\n\n      // create other parameters if missing ---------------------\n      // none\n\n      // check appropriate sizes of matrices and vectors --------\n      if (Q.rows() != n  ||  Q.cols() != n)\n\tthrow std::runtime_error(\"Process noise covariance has invalid size.\");\n      if (R.rows() != R.cols())\n\tthrow std::runtime_error(\"Measurement noise covariance must be a square matrix.\");\n\n      // validation finished successfully -----------------------\n      validated = true;\n\n      // further things to initialize ---------------------------\n      // create output state\n      if (out.size() != n) {\t// not initialized till now or invalid size from reinit\n\tout.clear();\n\tfor (int i = 0; i < n; i++)\n\t  out.add(OutputValue());\n      }\n    } \n    catch(std::exception& e) \n    {\n      std::string additionalInfo = \"ParticleFilterSIR: Validation failed. \";\n      throw estimator_error(additionalInfo + e.what());\n    }\n  }\n\n  // -----------------------------------------\n  // Overrides of ParticleFilterSIR's IEstimator implementation\n  // -----------------------------------------\n\n  void ParticleFilterSIR::serialize(std::ostream& os) const\n  {\n    os << \"SIR Particle Filter\";\n  }\n\n  // -----------------------------------------\n  // Particle Filtering\n  // -----------------------------------------\n  void ParticleFilterSIR::sample (void)\n  {    \n    // estimate next state of particles\n    for (int i = 0; i < particles.size(); i++)\n    {      \n      // sample from process noise: zero mean gaussian with covariance Q\n      VectorXd w = probability::sampleNormalDistribution(VectorXd::Zero(Q.rows()), Q);\n      \n      f(particles[i], u);\t\t// time update\n      particles[i] = particles[i] + w;  // add noise\n    }\n  }\n\n  void ParticleFilterSIR::weight (Input measurements)\n  {\n    double sumWeights = 0, sumWeightsSquare = 0;\n   \n    // measurement vector z\n    VectorXd z(R.rows());\n\n    if (measurements.size() != z.size())\n      throw std::runtime_error(\"Number of measurements invalid.\");\n\n    // calculate weight\n    for (int i = 0; i < particles.size(); i++)\n    {\n      // weight = likelihood of the measurement\n      // estimate expected measurement when in state i\n      VectorXd z_expected = VectorXd::Zero(z.size());\n      h(z_expected, particles[i]);\n\n      // get probability of the measurement (mean = z_expected,\n      // covariance = measurement noise covariance)\n      prepareMeasurements(z, measurements, z_expected);\t// fills z\n      double weight = probability::pdfNormalDistribution(z, z_expected, R);\n      \n      weights[i] = weights[i] * weight;\t// set weight (consider old weight!)\n      sumWeights += weights[i];\t\t// add to sum for normalization\n    }\n\n    // normalize weights\n    for (int i = 0; i < particles.size(); i++)\n    {\n      weights[i] /= sumWeights;\n\n      // accumulate for Neff-calculation\n      sumWeightsSquare += weights[i] * weights[i];\n    }\n\n    // evaluate effective number of particles\n    Neff = 1 / sumWeightsSquare;\n  }\n\n  void ParticleFilterSIR::resample (void)\n  {\n    int N = particles.size();\n\n    if (Neff > 0.8*N)\n      return;\n\n    // copy current particles to the buffer 'partices_old' where the\n    // new ones will be chosen from; the array 'particles' will be\n    // filled with these drawn ones\n    std::vector<VectorXd> particles_old(particles);\n\n    // 1. generate CDF\n    std::vector<double> cdf(N);\n    cdf[0] = weights[0];\n    for (int i = 1; i < N; i++)\n      cdf[i] = cdf[i-1] + weights[i];\n    \n    // 2. draw a starting point\n    boost::uniform_real<> dist(0, 1.0 / N);\n    boost::variate_generator<boost::mt19937&, boost::uniform_real<> >\n      random(rng, dist);\n    double u0 = random();\t// u0 is then betw 0..1/N\n    int i = 0;\n\n    for (int j = 0; j < N; j++)\n    {\n      // 3. move along the CDF\n      double uj = u0 + ((double)j)/N;\n\n      // check where the random number in the CDF fits -> this is the\n      // sample to choose; a sample with higher weight has a higher\n      // span in the CDF, hence will be chosen more often\n      while (uj > cdf[i])\n      \ti++;\n\n      particles[j] = particles_old[i];\n      weights[j] = 1.0 / N;\n    }\n  }\n}\n", "meta": {"hexsha": "14076bf8cdcbf20dffdcccfc46a706b03860e845", "size": 6409, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sf_estimation/src/estimation/ParticleFilterSIR.cpp", "max_stars_repo_name": "tuw-cpsg/sf-pkg", "max_stars_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T09:47:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T16:01:11.000Z", "max_issues_repo_path": "sf_estimation/src/estimation/ParticleFilterSIR.cpp", "max_issues_repo_name": "ros-agriculture/sf-pkg", "max_issues_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T04:59:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-13T14:39:24.000Z", "max_forks_repo_path": "sf_estimation/src/estimation/ParticleFilterSIR.cpp", "max_forks_repo_name": "tuw-cpsg/sf-pkg", "max_forks_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-17T21:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T17:00:28.000Z", "avg_line_length": 28.8693693694, "max_line_length": 86, "alphanum_fraction": 0.5840224684, "num_tokens": 1596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.40714071401932117}}
{"text": "#include \"format_helper.h\"\n\n#include <iostream>\n#include <iomanip>\n#include <dirent.h>\n#include <sys/stat.h>\n\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include \"math_helper.h\"\n\nnamespace core {\n\nusing namespace std;\nusing namespace cv;\n\nnamespace {\nvoid GetCalibParams(const cv::Mat& P_left, const cv::Mat& P_right, double* calib) {\n  //std::cout << P_left << \"\\n\" << P_right;\n  calib[0] = P_left.at<double>(0,0);\n  calib[1] = P_left.at<double>(1,1);\n  calib[2] = P_left.at<double>(0,2);\n  calib[3] = P_left.at<double>(1,2);\n  //calib[4] = std::abs(P_left.at<double>(0,3) - P_right.at<double>(0,3)) / calib[0];\n  double x_diff = P_left.at<double>(0,3) - P_right.at<double>(0,3);\n  double y_diff = P_left.at<double>(1,3) - P_right.at<double>(1,3);\n  double z_diff = P_left.at<double>(2,3) - P_right.at<double>(2,3);\n  calib[4] = std::sqrt(x_diff*x_diff + y_diff*y_diff + z_diff*z_diff) / calib[0];\n  //for (int i = 0; i < 5; i++)\n  //  std::cout << calib[i] << \"\\n\";\n}\n}\n\nvoid FormatHelper::ParseKITTIDatasetConfig(\n    const std::string config_file, std::string& cam_params_file, std::string& dataset_name,\n    std::string& left_folder, std::string& right_folder, std::string& gt_filepath,\n    std::size_t& start_num, std::size_t& end_num, std::size_t& num_width) {\n  try {\n    po::variables_map vm;\n    po::options_description config(\"Config file options\");\n    config.add_options()\n      (\"dataset_name\", po::value<std::string>(&dataset_name)->required(), \"name\")\n      (\"camera_params,p\", po::value<std::string>(&cam_params_file)->required(), \"camera params file\")\n      (\"left_folder\", po::value<std::string>(&left_folder)->required(), \"folder\")\n      (\"right_folder\", po::value<std::string>(&right_folder)->required(), \"folder\")\n      (\"start_num\", po::value<std::size_t>(&start_num)->required(), \"start number\")\n      (\"end_num\", po::value<std::size_t>(&end_num)->required(), \"end number\")\n      (\"num_width\", po::value<std::size_t>(&num_width)->required(), \"padding\")\n      (\"groundtruth,g\", po::value<std::string>(&gt_filepath)->required(), \"file with motion GT\");\n\n    std::ifstream ifs(config_file);\n    if (!ifs) {\n      throw \"can not open config file: \" + config_file + \"\\n\";\n    }\n    else {\n      po::store(parse_config_file(ifs, config, true), vm);\n      notify(vm);\n    }\n  }\n  catch(std::exception& e) {\n    std::cout << e.what() << \"\\n\";\n    throw 1;\n  }\n\n  left_folder += \"/\";\n  right_folder += \"/\";\n}\n\nvoid FormatHelper::ReadCalibKitti(const std::string path, double* grey_cam, double* color_cam)\n{\n  std::ifstream calib_file(path);\n  std::vector<cv::Mat> P;\n  P.resize(4);\n\n  std::string word;\n  for (int i = 0; i < 4; i++) {\n    P[i].create(3, 4, CV_64F);\n    calib_file >> word;\n    for (int j = 0; j < 12; j++) {\n      calib_file >> word;\n      int row = j / 4;\n      int col = j % 4;\n      P[i].at<double>(row,col) = std::stod(word);\n    }\n    //std::cout << P[i] << \"\\n\";\n  }\n  //std::cout << \"\\nCalib mono:\\n\";\n  GetCalibParams(P[0], P[1], grey_cam);\n  //std::cout << \"\\nCalib color:\\n\";\n  GetCalibParams(P[2], P[3], color_cam);\n}\n\n// reads next matrix in a row\nvoid FormatHelper::ReadNextRtMatrix(std::ifstream& file, cv::Mat& Rt)\n{\n   std::string line;\n   getline(file, line);\n   stringstream stream(line);\n   string val;\n   //cout << \"LINE: \" << line << endl;\n   Rt = Mat::eye(4, 4, CV_64F);\n   for(int i = 0; i < 3; i++) {\n      for(int j = 0; j < 4; j++) {\n         stream >> val;\n         Rt.at<double>(i,j) = std::stod(val);\n         //cout << \"READ: \" << motion_params[i] << endl << endl;\n      }\n   }\n}\n\nvoid FormatHelper::Read2FrameMotionFromAccCameraMotion(const std::string filename, const int num_of_motions,\n                                                       std::vector<cv::Mat>& world_motion,\n                                                       std::vector<cv::Mat>& camera_motion) {\n  // wrt - world motion\n  // crt - camera motion\n  std::ifstream file(filename);\n  cv::Mat wrt, wrt_prev, wrt_curr;\n  // read first (usually identety) matrix\n  core::FormatHelper::ReadNextRtMatrix(file, wrt_curr);\n  core::MathHelper::invTrans(wrt_curr, wrt_prev);\n\n  for (int i = 0; i < num_of_motions; i++) {\n    core::FormatHelper::ReadNextRtMatrix(file, wrt_curr);\n    cv::Mat crt = wrt_prev * wrt_curr;\n    core::MathHelper::invTrans(wrt_curr, wrt_prev);\n    camera_motion.push_back(crt.clone());\n    core::MathHelper::invTrans(crt, wrt);\n    world_motion.push_back(wrt.clone());\n    //std::cout << crt << \"\\n\\n\";\n    //std::cout << wrt << \"\\n\\n\";\n  }\n}\n\nvoid FormatHelper::WriteMatRt(const cv::Mat& Rt, std::ofstream& fp) {\n   //std::setprecision(6);\n   for(int i = 0; i < (Rt.rows-1); i++) {\n      for(int j = 0; j < Rt.cols; j++) {\n        double val = Rt.at<double>(i,j);\n        fp << std::scientific << val << \" \";\n      }\n   }\n   fp << endl;\n}\n\nvoid FormatHelper::WriteMotionToFile(const Eigen::Matrix4d& Rt, std::ofstream& file) {\n  //std::setprecision(6);\n  for(int i = 0; i < Rt.rows() - 1; i++)\n    for(int j = 0; j < Rt.cols(); j++)\n      file << std::scientific << Rt(i,j) << \" \";\n  file << std::endl;\n}\n\nvoid FormatHelper::WriteMatRt(const cv::Mat& Rt, std::ofstream& fp, bool convert_to_cm)\n{\n   //std::setprecision(6);\n   for(int i = 0; i < (Rt.rows-1); i++) {\n      for(int j = 0; j < Rt.cols; j++) {\n        double val = Rt.at<double>(i,j);\n        if(convert_to_cm && j == 3)\n          val *= 100.0;\n        fp << std::scientific << val << \" \";\n      }\n   }\n   fp << endl;\n}\n\n// [fx fy cx cy tx=baseline]\nvoid FormatHelper::readCameraParams(const std::string& filepath, double (&cam_params)[5])\n{\n   ifstream file(filepath);\n   std::string line;\n   getline(file, line);\n   stringstream stream(line);\n   string val;\n   //cout << \"[FormatHelper]: Using camera params: \";\n   for(int i = 0; i < 5; i++) {\n      stream >> val;\n      cam_params[i] = std::stod(val);\n      //cout << cam_params[i] << \"  \";\n   }\n   cout << endl;\n   file.close();\n}\n\nvoid FormatHelper::readGpsPoints(string filename, vector<Mat> points)\n{\n   ifstream file(filename);\n   string val;\n   points.clear();\n   Mat pt(2, 1, CV_64F);\n   while(!file.eof()) {\n      file >> val;\n      pt.at<double>(0,0) = std::stod(val);\n      file >> val;\n      pt.at<double>(1,0) = std::stod(val);\n      cout << pt << endl;\n      points.push_back(pt.clone());\n      for(int i = 0; i < 9; i++) file >> val;\n   }\n}\n\nvoid FormatHelper::getCalibParams(std::string& intrinsic_filename, std::string& extrinsic_filename, cv::Mat& P_left,\n                    cv::Mat& P_right, cv::Mat& Q, cv::Mat& C_left, cv::Mat& D_left, cv::Mat& C_right, cv::Mat& D_right)\n{\n   // reading intrinsic parameters\n   //FileStorage fs(intrinsic_filename, CV_STORAGE_READ);\n   FileStorage fs(intrinsic_filename, FileStorage::READ);\n   if(!fs.isOpened())\n   {\n      cout << \"Failed to open file \" << intrinsic_filename << endl;\n      return;\n   }\n\n   //Mat M1, D1, M2, D2;\n   fs[\"M1\"] >> C_left;\n   fs[\"D1\"] >> D_left;\n   fs[\"M2\"] >> C_right;\n   fs[\"D2\"] >> D_right;\n   Mat R, T, R1, R2;\n   fs[\"R\"] >> R;\n   fs[\"T\"] >> T;\n\n   // TODO - read this also from file\n   //cv::Size imageSize(CALIB_WIDTH, CALIB_HEIGHT);\n   //stereoRectify(C_left, D_left, C_right, D_right, imageSize, R, T, R1, R2, P_left, P_right, Q, CALIB_ZERO_DISPARITY, \n   //      -1, imageSize);\n\n   return;\n}\n\nbool FormatHelper::readStringList(const std::string& filename, std::vector<std::string>& l)\n{\n   l.resize(0);\n   FileStorage fs(filename, FileStorage::READ);\n   if( !fs.isOpened() )\n      return false;\n   FileNode n = fs.getFirstTopLevelNode();\n   if( n.type() != FileNode::SEQ )\n      return false;\n   FileNodeIterator it = n.begin(), it_end = n.end();\n   for( ; it != it_end; ++it )\n      l.push_back((string)*it);\n   return true;\n}\n\n\n/* Returns a list of files in a directory (except the ones that begin with a dot) */\nvoid FormatHelper::GetFilesInFolder(const std::string& dir_path, std::vector<std::string>& files,\n                                    bool get_full_path = false) {\n  DIR *dir;\n  struct dirent *ent;\n  struct stat st;\n  dir = opendir(dir_path.c_str());\n  while ((ent = readdir(dir)) != NULL) {\n    const std::string file_name = ent->d_name;\n    const std::string full_file_name = dir_path + \"/\" + file_name;\n    if (file_name[0] == '.')\n      continue;\n    if (stat(full_file_name.c_str(), &st) == -1)\n      continue;\n    const bool is_directory = (st.st_mode & S_IFDIR) != 0;\n    if (is_directory)\n      continue;\n\n    if (get_full_path)\n      files.push_back(full_file_name);\n    else\n      files.push_back(file_name);\n  }\n  closedir(dir);\n  std::sort(files.begin(), files.end());\n}\n\n}\n", "meta": {"hexsha": "430ca06abf1590bcb486c5e18eb56717caf983a7", "size": 8599, "ext": "cc", "lang": "C++", "max_stars_repo_path": "core/format_helper.cc", "max_stars_repo_name": "bartn8/stereo-vision", "max_stars_repo_head_hexsha": "1180045fe560478e5c441e75202cc899fe90ec3d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2016-04-02T18:18:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-14T11:47:58.000Z", "max_issues_repo_path": "core/format_helper.cc", "max_issues_repo_name": "bartn8/stereo-vision", "max_issues_repo_head_hexsha": "1180045fe560478e5c441e75202cc899fe90ec3d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-08-01T14:36:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-14T08:15:50.000Z", "max_forks_repo_path": "core/format_helper.cc", "max_forks_repo_name": "bartn8/stereo-vision", "max_forks_repo_head_hexsha": "1180045fe560478e5c441e75202cc899fe90ec3d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2016-08-25T11:28:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T12:17:47.000Z", "avg_line_length": 31.1557971014, "max_line_length": 120, "alphanum_fraction": 0.5946040237, "num_tokens": 2583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4071095999731374}}
{"text": "#include <iostream>\n#include <thread>\n#include <chrono>\n#include <memory>\n#include <array>\n#include <vector>\n#include <random>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/NonLinearOptimization>\n\n#include \"sfmMyFunctions.h\"\n#include \"sfmExceptionMacro.h\"\n#include \"sfmBasicTypes.h\"\n#include \"sfmPedestrianSpawner.h\"\n\n//this always seems to be highlighted but it complies fine\n#include \"sfmVisualiser.h\"\n\nint main(int argc, char** argv)\n{\n    //variables needed throughout the function\n    double world_width_x = 50.0;\n    double world_height_y = 10.0;\n    int no_pedestrians = 100;\n    int choice;\n    double dt = 0.1;\n    double finish_time_s = 100;\n    double v_max = 1.3;\n    std::vector<std::shared_ptr<sfm::Forces> >pedestrians;\n\n    // Create viewer and initialise with required number of pedestrians\n    //left here as its easier to reposition the viewer to where you would like it before\n    //entering the selection, i left a second commented later incase someone didnt like\n    //this, it is a little jarring at first.\n    sfm::Visualiser viewer(no_pedestrians, world_width_x, world_height_y);\n\n    // neatened up the interface to easily pick from three demos\n    std::cout   << \"Please Pick Demo of 100 pedestrians over 50 seconds; \\n\"\n                << \"1(Directional),2(Targeted) or 3(All random);) \" << std::endl;\n    std::cin >> choice;\n\n    //this has all the pedestrians moving straight along the x axis to their opposite side\n    if(choice == 1){\n    \n        //set up variables for directional functions\n        sfm::dir2d left_side_x(1,2);\n        sfm::dir2d left_side_y(0.1,9.9);\n        sfm::dir2d right_side_x(48,49);\n        sfm::dir2d right_side_y(0.1,9.9);\n        sfm::dir2d direc1(1,0);\n        sfm::dir2d direc2(-1,0);\n\n        //creates 2 sets of pedestrians in the same format as in the open_mp file\n        //essencially we create 2 sets of pedestrians and append them to the total.\n        std::vector<std::shared_ptr<sfm::Forces> >pedestrians1;\n        pedestrians1 = sfm::Factory::Distributed(pedestrians1,\"Directional\",no_pedestrians/2,direc1,direc1,left_side_x,left_side_y);\n        for(int point = 0; point < pedestrians1.size();++point){\n            pedestrians.emplace_back(pedestrians1[point]);\n        } \n        std::vector<std::shared_ptr<sfm::Forces> >pedestrians2;\n        pedestrians2 = sfm::Factory::Distributed(pedestrians2,\"Directional\",no_pedestrians/2,direc2,direc2,right_side_x,right_side_y);\n        for(int point = 0; point < pedestrians2.size();++point){\n            pedestrians.emplace_back(pedestrians2[point]);\n        }   \n    }\n\n    //this has all the pedestrians moving straight along to a point on the opposite side\n    else if(choice == 2){\n\n        //variables for targeted pedestrians\n        sfm::dir2d left_side_x(1,2);\n        sfm::dir2d left_side_y(0.1,9.9);\n        sfm::dir2d dest_left_x(48,49);\n        sfm::dir2d dest_left_y(0.1,9.9);\n        sfm::dir2d right_side_x(48,49);\n        sfm::dir2d right_side_y(0.1,9.9);\n        sfm::dir2d dest_right_x(1,2);\n        sfm::dir2d dest_right_y(0.1,9.9);\n\n        // this uses the distributed fixed class method\n        std::vector<std::shared_ptr<sfm::Forces> >pedestrians1;\n        pedestrians1 = sfm::Factory::Distributed(pedestrians1,\"Targeted\",no_pedestrians/2,dest_left_x,dest_left_y,left_side_x,left_side_y);\n        for(int point = 0; point < pedestrians1.size();++point){\n            pedestrians.emplace_back(pedestrians1[point]);\n        } \n        std::vector<std::shared_ptr<sfm::Forces> >pedestrians2;\n        pedestrians2 = sfm::Factory::Distributed(pedestrians2,\"Targeted\",no_pedestrians/2,dest_right_x,dest_right_y,right_side_x,right_side_y);\n        for(int point = 0; point < pedestrians2.size();++point){\n            pedestrians.emplace_back(pedestrians2[point]);\n        } \n\n    }\n\n    // this will randomly spawn 100 pedestrains at 100 randompoints\n    else if(choice == 3){\n\n        //very simple to spawn random pedestrians\n        pedestrians = sfm::Factory::Spawner(pedestrians,no_pedestrians);\n    }\n    else{\n        std::cout << \"Pick one of the three demos\" <<std::endl;\n    }\n\n    // Create viewer and initialise with required number of pedestrians\n    //sfm::Visualiser viewer(no_pedestrians, world_width_x, world_height_y);\n\n    //for loop over time\n    for(int t=0; t<(finish_time_s/dt);++t){   \n\n        //next a for loop that goes through each pedestrian and calculates its resultant force and then updates the new qualities\n        //detailed explanation in open mp\n        for(int j=0; j<pedestrians.size();++j){\n            viewer.SetPedestrian(j, pedestrians[j]->Return_Current_Position()[1],\n                                    pedestrians[j]->Return_Current_Position()[0],\n                                    pedestrians[j]->Return_Velocity()[1],\n                                    pedestrians[j]->Return_Velocity()[0]);\n            sfm::dir2d temp_force = pedestrians[j]->Resultant_force(pedestrians,temp_force, dt);\n            sfm::dir2d  new_velocity = (temp_force*dt) + pedestrians[j]->Return_Velocity();\n            if(new_velocity.length() > v_max*pedestrians[j]->Return_Speed()){\n                new_velocity = new_velocity*(v_max*pedestrians[j]->Return_Speed()/new_velocity.length());\n                }\n            sfm::dir2d position(pedestrians[j]->Return_Current_Position()[1],pedestrians[j]->Return_Current_Position()[0]);\n            sfm::pos2d new_position = {position[1]+(new_velocity[1]*dt),(position[0]+new_velocity[0]*dt)};\n            pedestrians[j]->Update_Velocity(new_velocity);\n            pedestrians[j]->Update_Current_Position(new_position);           \n        }\n        \n        // Tell viewer to redraw scene\n        viewer.UpdateScene();\n\n        // Sleep for a bit so can see visualiser updating, i left it as 10 miliseconds at the \n        // actual sleep time of 100 ms seemed a bit too slow (0.1s dt)\n        std::this_thread::sleep_for (std::chrono::milliseconds(100));\n\n    } \n\n    return 0;\n}", "meta": {"hexsha": "7dc317d074b7ff6abb74cb6e2975032f04b34438", "size": 5994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/CommandLineApps/sfmVisualiser.cpp", "max_stars_repo_name": "sukrire/PHAS0100Assignment2", "max_stars_repo_head_hexsha": "9838e21ac663f557b7969161dee061086effdabd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/CommandLineApps/sfmVisualiser.cpp", "max_issues_repo_name": "sukrire/PHAS0100Assignment2", "max_issues_repo_head_hexsha": "9838e21ac663f557b7969161dee061086effdabd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/CommandLineApps/sfmVisualiser.cpp", "max_forks_repo_name": "sukrire/PHAS0100Assignment2", "max_forks_repo_head_hexsha": "9838e21ac663f557b7969161dee061086effdabd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-16T16:42:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T12:50:33.000Z", "avg_line_length": 43.4347826087, "max_line_length": 143, "alphanum_fraction": 0.6544878212, "num_tokens": 1577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4071095999731374}}
{"text": "/*\n * SVD_pvfmm.hpp\n *\n *  Created on: Feb 20, 2017\n *      Author: wyan\n */\n\n#ifndef SVD_PVFMM_HPP_\n#define SVD_PVFMM_HPP_\n\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <vector>\n\n#include <Eigen/Dense>\n\ntemplate <class T>\ninline void gemm(char TransA, char TransB, int M, int N, int K, T alpha, T *A,\n                 int lda, T *B, int ldb, T beta, T *C, int ldc) {\n    if ((TransA == 'N' || TransA == 'n') && (TransB == 'N' || TransB == 'n')) {\n#pragma omp parallel for\n        for (auto n = 0; n < N; n++) {     // Columns of C\n            for (auto m = 0; m < M; m++) { // Rows of C\n                T AxB = 0;\n                for (auto k = 0; k < K; k++) {\n                    AxB += A[m + lda * k] * B[k + ldb * n];\n                }\n                C[m + ldc * n] =\n                    alpha * AxB + (beta == 0 ? 0 : beta * C[m + ldc * n]);\n            }\n        }\n    } else if (TransA == 'N' || TransA == 'n') {\n#pragma omp parallel for\n        for (auto n = 0; n < N; n++) {     // Columns of C\n            for (auto m = 0; m < M; m++) { // Rows of C\n                T AxB = 0;\n                for (auto k = 0; k < K; k++) {\n                    AxB += A[m + lda * k] * B[n + ldb * k];\n                }\n                C[m + ldc * n] =\n                    alpha * AxB + (beta == 0 ? 0 : beta * C[m + ldc * n]);\n            }\n        }\n    } else if (TransB == 'N' || TransB == 'n') {\n#pragma omp parallel for\n        for (auto n = 0; n < N; n++) {     // Columns of C\n            for (auto m = 0; m < M; m++) { // Rows of C\n                T AxB = 0;\n                for (auto k = 0; k < K; k++) {\n                    AxB += A[k + lda * m] * B[k + ldb * n];\n                }\n                C[m + ldc * n] =\n                    alpha * AxB + (beta == 0 ? 0 : beta * C[m + ldc * n]);\n            }\n        }\n    } else {\n#pragma omp parallel for\n        for (auto n = 0; n < N; n++) {     // Columns of C\n            for (auto m = 0; m < M; m++) { // Rows of C\n                T AxB = 0;\n                for (auto k = 0; k < K; k++) {\n                    AxB += A[k + lda * m] * B[n + ldb * k];\n                }\n                C[m + ldc * n] =\n                    alpha * AxB + (beta == 0 ? 0 : beta * C[m + ldc * n]);\n            }\n        }\n    }\n}\n\n#define U(i, j) U_[(i)*dim[0] + (j)]\n#define S(i, j) S_[(i)*dim[1] + (j)]\n#define V(i, j) V_[(i)*dim[1] + (j)]\n\ntemplate <class T>\nvoid GivensL(T *S_, const size_t dim[2], size_t m, T a, T b) {\n    T r = sqrt(a * a + b * b);\n    T c = a / r;\n    T s = -b / r;\n\n#pragma omp parallel for\n    for (size_t i = 0; i < dim[1]; i++) {\n        T S0 = S(m + 0, i);\n        T S1 = S(m + 1, i);\n        S(m, i) += S0 * (c - 1);\n        S(m, i) += S1 * (-s);\n\n        S(m + 1, i) += S0 * (s);\n        S(m + 1, i) += S1 * (c - 1);\n    }\n}\n\ntemplate <class T>\nvoid GivensR(T *S_, const size_t dim[2], size_t m, T a, T b) {\n    T r = sqrt(a * a + b * b);\n    T c = a / r;\n    T s = -b / r;\n\n#pragma omp parallel for\n    for (size_t i = 0; i < dim[0]; i++) {\n        T S0 = S(i, m + 0);\n        T S1 = S(i, m + 1);\n        S(i, m) += S0 * (c - 1);\n        S(i, m) += S1 * (-s);\n\n        S(i, m + 1) += S0 * (s);\n        S(i, m + 1) += S1 * (c - 1);\n    }\n}\n\ntemplate <class T>\nvoid SVD(const size_t dim[2], T *U_, T *S_, T *V_, T eps = -1) {\n    assert(dim[0] >= dim[1]);\n#ifdef SVD_DEBUG\n    Matrix<T> M0(dim[0], dim[1], S_);\n#endif\n\n    { // Bi-diagonalization\n        size_t n = std::min(dim[0], dim[1]);\n        std::vector<T> house_vec(std::max(dim[0], dim[1]));\n        for (size_t i = 0; i < n; i++) {\n            // Column Householder\n            {\n                T x1 = S(i, i);\n                if (x1 < 0)\n                    x1 = -x1;\n\n                T x_inv_norm = 0;\n                for (size_t j = i; j < dim[0]; j++) {\n                    x_inv_norm += S(j, i) * S(j, i);\n                }\n                if (x_inv_norm > 0)\n                    x_inv_norm = 1 / sqrt(x_inv_norm);\n\n                T alpha = sqrt(1 + x1 * x_inv_norm);\n                T beta = x_inv_norm / alpha;\n\n                house_vec[i] = -alpha;\n                for (size_t j = i + 1; j < dim[0]; j++) {\n                    house_vec[j] = -beta * S(j, i);\n                }\n                if (S(i, i) < 0)\n                    for (size_t j = i + 1; j < dim[0]; j++) {\n                        house_vec[j] = -house_vec[j];\n                    }\n            }\n#pragma omp parallel for\n            for (size_t k = i; k < dim[1]; k++) {\n                T dot_prod = 0;\n                for (size_t j = i; j < dim[0]; j++) {\n                    dot_prod += S(j, k) * house_vec[j];\n                }\n                for (size_t j = i; j < dim[0]; j++) {\n                    S(j, k) -= dot_prod * house_vec[j];\n                }\n            }\n#pragma omp parallel for\n            for (size_t k = 0; k < dim[0]; k++) {\n                T dot_prod = 0;\n                for (size_t j = i; j < dim[0]; j++) {\n                    dot_prod += U(k, j) * house_vec[j];\n                }\n                for (size_t j = i; j < dim[0]; j++) {\n                    U(k, j) -= dot_prod * house_vec[j];\n                }\n            }\n\n            // Row Householder\n            if (i >= n - 1)\n                continue;\n            {\n                T x1 = S(i, i + 1);\n                if (x1 < 0)\n                    x1 = -x1;\n\n                T x_inv_norm = 0;\n                for (size_t j = i + 1; j < dim[1]; j++) {\n                    x_inv_norm += S(i, j) * S(i, j);\n                }\n                if (x_inv_norm > 0)\n                    x_inv_norm = 1 / sqrt(x_inv_norm);\n\n                T alpha = sqrt(1 + x1 * x_inv_norm);\n                T beta = x_inv_norm / alpha;\n\n                house_vec[i + 1] = -alpha;\n                for (size_t j = i + 2; j < dim[1]; j++) {\n                    house_vec[j] = -beta * S(i, j);\n                }\n                if (S(i, i + 1) < 0)\n                    for (size_t j = i + 2; j < dim[1]; j++) {\n                        house_vec[j] = -house_vec[j];\n                    }\n            }\n#pragma omp parallel for\n            for (size_t k = i; k < dim[0]; k++) {\n                T dot_prod = 0;\n                for (size_t j = i + 1; j < dim[1]; j++) {\n                    dot_prod += S(k, j) * house_vec[j];\n                }\n                for (size_t j = i + 1; j < dim[1]; j++) {\n                    S(k, j) -= dot_prod * house_vec[j];\n                }\n            }\n#pragma omp parallel for\n            for (size_t k = 0; k < dim[1]; k++) {\n                T dot_prod = 0;\n                for (size_t j = i + 1; j < dim[1]; j++) {\n                    dot_prod += V(j, k) * house_vec[j];\n                }\n                for (size_t j = i + 1; j < dim[1]; j++) {\n                    V(j, k) -= dot_prod * house_vec[j];\n                }\n            }\n        }\n    }\n\n    size_t k0 = 0;\n    size_t iter = 0;\n    if (eps < 0) {\n        eps = 1.0;\n        while (eps + (T)1.0 > 1.0)\n            eps *= 0.5;\n        eps *= 64.0;\n    }\n    while (k0 < dim[1] - 1) { // Diagonalization\n        iter++;\n\n        T S_max = 0.0;\n        for (size_t i = 0; i < dim[1]; i++)\n            S_max = (S_max > S(i, i) ? S_max : S(i, i));\n\n        while (k0 < dim[1] - 1 && std::abs<T>(S(k0, k0 + 1)) <= eps * S_max)\n            k0++;\n        if (k0 == dim[1] - 1)\n            continue;\n\n        size_t n = k0 + 2;\n        while (n < dim[1] && std::abs<T>(S(n - 1, n)) > eps * S_max)\n            n++;\n\n        T alpha = 0;\n        T beta = 0;\n        { // Compute mu\n            T C[2][2];\n            C[0][0] = S(n - 2, n - 2) * S(n - 2, n - 2);\n            if (n - k0 > 2)\n                C[0][0] += S(n - 3, n - 2) * S(n - 3, n - 2);\n            C[0][1] = S(n - 2, n - 2) * S(n - 2, n - 1);\n            C[1][0] = S(n - 2, n - 2) * S(n - 2, n - 1);\n            C[1][1] = S(n - 1, n - 1) * S(n - 1, n - 1) +\n                      S(n - 2, n - 1) * S(n - 2, n - 1);\n\n            T b = -(C[0][0] + C[1][1]) / 2;\n            T c = C[0][0] * C[1][1] - C[0][1] * C[1][0];\n            T d = 0;\n            if (b * b - c > 0)\n                d = sqrt(b * b - c);\n            else {\n                T b = (C[0][0] - C[1][1]) / 2;\n                T c = -C[0][1] * C[1][0];\n                if (b * b - c > 0)\n                    d = sqrt(b * b - c);\n            }\n\n            T lambda1 = -b + d;\n            T lambda2 = -b - d;\n\n            T d1 = lambda1 - C[1][1];\n            d1 = (d1 < 0 ? -d1 : d1);\n            T d2 = lambda2 - C[1][1];\n            d2 = (d2 < 0 ? -d2 : d2);\n            T mu = (d1 < d2 ? lambda1 : lambda2);\n\n            alpha = S(k0, k0) * S(k0, k0) - mu;\n            beta = S(k0, k0) * S(k0, k0 + 1);\n        }\n\n        for (size_t k = k0; k < n - 1; k++) {\n            size_t dimU[2] = {dim[0], dim[0]};\n            size_t dimV[2] = {dim[1], dim[1]};\n            GivensR(S_, dim, k, alpha, beta);\n            GivensL(V_, dimV, k, alpha, beta);\n\n            alpha = S(k, k);\n            beta = S(k + 1, k);\n            GivensL(S_, dim, k, alpha, beta);\n            GivensR(U_, dimU, k, alpha, beta);\n\n            alpha = S(k, k + 1);\n            beta = S(k, k + 2);\n        }\n\n        { // Make S bi-diagonal again\n            for (size_t i0 = k0; i0 < n - 1; i0++) {\n                for (size_t i1 = 0; i1 < dim[1]; i1++) {\n                    if (i0 > i1 || i0 + 1 < i1)\n                        S(i0, i1) = 0;\n                }\n            }\n            for (size_t i0 = 0; i0 < dim[0]; i0++) {\n                for (size_t i1 = k0; i1 < n - 1; i1++) {\n                    if (i0 > i1 || i0 + 1 < i1)\n                        S(i0, i1) = 0;\n                }\n            }\n            for (size_t i = 0; i < dim[1] - 1; i++) {\n                if (std::abs<T>(S(i, i + 1)) <= eps * S_max) {\n                    S(i, i + 1) = 0;\n                }\n            }\n        }\n        // std::cout<<iter<<' '<<k0<<' '<<n<<'\\n';\n    }\n\n    { // Check Error\n#ifdef SVD_DEBUG\n        Matrix<T> U0(dim[0], dim[0], U_);\n        Matrix<T> S0(dim[0], dim[1], S_);\n        Matrix<T> V0(dim[1], dim[1], V_);\n        Matrix<T> E = M0 - U0 * S0 * V0;\n        T max_err = 0;\n        T max_nondiag0 = 0;\n        T max_nondiag1 = 0;\n        for (size_t i = 0; i < E.Dim(0); i++)\n            for (size_t j = 0; j < E.Dim(1); j++) {\n                if (max_err < pvfmm::fabs<T>(E[i][j]))\n                    max_err = pvfmm::fabs<T>(E[i][j]);\n                if ((i > j + 0 || i + 0 < j) &&\n                    max_nondiag0 < pvfmm::fabs<T>(S0[i][j]))\n                    max_nondiag0 = pvfmm::fabs<T>(S0[i][j]);\n                if ((i > j + 1 || i + 1 < j) &&\n                    max_nondiag1 < pvfmm::fabs<T>(S0[i][j]))\n                    max_nondiag1 = pvfmm::fabs<T>(S0[i][j]);\n            }\n        std::cout << max_err << '\\n';\n        std::cout << max_nondiag0 << '\\n';\n        std::cout << max_nondiag1 << '\\n';\n#endif\n    }\n}\n\n#undef U\n#undef S\n#undef V\n#undef SVD_DEBUG\n\ntemplate <class T>\ninline void svd(char *JOBU, char *JOBVT, int *M, int *N, T *A, int *LDA, T *S,\n                T *U, int *LDU, T *VT, int *LDVT, T *WORK, int *LWORK,\n                int *INFO) {\n\n    const size_t dim[2] = {static_cast<size_t>(std::max(*N, *M)),\n                           static_cast<size_t>(std::min(*N, *M))};\n\n    std::vector<T> Udata(dim[0] * dim[0], 0);\n    std::vector<T> Vdata(dim[1] * dim[1], 0);\n    std::vector<T> Sdata(dim[0] * dim[1], 0);\n    T *U_ = Udata.data();\n    T *V_ = Vdata.data();\n    T *S_ = Sdata.data();\n    //\tT* U_ = mem::aligned_new < T > (dim[0] * dim[0]);\n    //\tmemset(U_, 0, dim[0] * dim[0] * sizeof(T));\n    //\tT* V_ = mem::aligned_new < T > (dim[1] * dim[1]);\n    //\tmemset(V_, 0, dim[1] * dim[1] * sizeof(T));\n    //\tT* S_ = mem::aligned_new < T > (dim[0] * dim[1]);\n\n    const size_t lda = *LDA;\n    const size_t ldu = *LDU;\n    const size_t ldv = *LDVT;\n\n    if (dim[1] == static_cast<size_t>(*M)) {\n        for (size_t i = 0; i < dim[0]; i++) {\n            for (size_t j = 0; j < dim[1]; j++) {\n                S_[i * dim[1] + j] = A[i * lda + j];\n            }\n        }\n    } else {\n        for (size_t i = 0; i < dim[0]; i++) {\n            for (size_t j = 0; j < dim[1]; j++) {\n                S_[i * dim[1] + j] = A[j * lda + i];\n            }\n        }\n    }\n    for (size_t i = 0; i < dim[0]; i++) {\n        U_[i * dim[0] + i] = 1;\n    }\n    for (size_t i = 0; i < dim[1]; i++) {\n        V_[i * dim[1] + i] = 1;\n    }\n\n    SVD<T>(dim, U_, S_, V_, (T)-1);\n\n    for (size_t i = 0; i < dim[1]; i++) { // Set S\n        S[i] = S_[i * dim[1] + i];\n    }\n    if (dim[1] == static_cast<size_t>(*M)) { // Set U\n        for (size_t i = 0; i < dim[1]; i++)\n            for (int j = 0; j < *M; j++) {\n                U[j + ldu * i] = V_[j + i * dim[1]] * (S[i] < 0.0 ? -1.0 : 1.0);\n            }\n    } else {\n        for (size_t i = 0; i < dim[1]; i++)\n            for (int j = 0; j < *M; j++) {\n                U[j + ldu * i] = U_[i + j * dim[0]] * (S[i] < 0.0 ? -1.0 : 1.0);\n            }\n    }\n    if (dim[0] == static_cast<size_t>(*N)) { // Set V\n        for (int i = 0; i < *N; i++)\n            for (size_t j = 0; j < dim[1]; j++) {\n                VT[j + ldv * i] = U_[j + i * dim[0]];\n            }\n    } else {\n        for (int i = 0; i < *N; i++)\n            for (size_t j = 0; j < dim[1]; j++) {\n                VT[j + ldv * i] = V_[i + j * dim[1]];\n            }\n    }\n    for (size_t i = 0; i < dim[1]; i++) {\n        S[i] = S[i] * (S[i] < 0.0 ? -1.0 : 1.0);\n    }\n\n    //\tmem::aligned_delete < T > (U_);\n    //\tmem::aligned_delete < T > (S_);\n    //\tmem::aligned_delete < T > (V_);\n\n    if (0) { // Verify\n        const size_t dim[2] = {static_cast<size_t>(std::max(*N, *M)),\n                               static_cast<size_t>(std::min(*N, *M))};\n        const size_t lda = *LDA;\n        const size_t ldu = *LDU;\n        const size_t ldv = *LDVT;\n\n        Eigen::MatrixXd A1(*M, *N);\n        Eigen::MatrixXd S1(dim[1], dim[1]);\n        Eigen::MatrixXd U1(*M, dim[1]);\n        Eigen::MatrixXd V1(dim[1], *N);\n        for (size_t i = 0; i < *N; i++)\n            for (size_t j = 0; j < *M; j++) {\n                //\t\t\t\tA1[j][i] = A[j + i * lda];\n                A1(j, i) = A[j + i * lda];\n            }\n        S1.setZero();\n        for (size_t i = 0; i < dim[1]; i++) { // Set S\n                                              //\t\t\tS1[i][i] = S[i];\n            S1(i, i) = S[i];\n        }\n        for (size_t i = 0; i < dim[1]; i++)\n            for (size_t j = 0; j < *M; j++) {\n                //\t\t\t\tU1[j][i] = U[j + ldu * i];\n                U1(j, i) = U[j + ldu * i];\n            }\n        for (size_t i = 0; i < *N; i++)\n            for (size_t j = 0; j < dim[1]; j++) {\n                //\t\t\t\tV1[j][i] = VT[j + ldv * i];\n                V1(j, i) = VT[j + ldv * i];\n            }\n        std::cout << U1 * S1 * V1 - A1 << '\\n';\n    }\n}\n\ntemplate <class T>\nvoid pinv_pvfmm(T *M, int n1, int n2, T eps, T *M_) {\n    if (n1 * n2 == 0)\n        return;\n    int m = n2;\n    int n = n1;\n    int k = (m < n ? m : n);\n\n    std::vector<T> Udata(m * k);\n    std::vector<T> Sdata(k);\n    std::vector<T> VTdata(k * n);\n\n    //\tT* tU = mem::aligned_new < T > (m * k);\n    //\tT* tS = mem::aligned_new < T > (k);\n    //\tT* tVT = mem::aligned_new < T > (k * n);\n\n    T *tU = Udata.data();\n    T *tS = Sdata.data();\n    T *tVT = VTdata.data();\n\n    // SVD\n    int INFO = 0;\n    char JOBU = 'S';\n    char JOBVT = 'S';\n\n    // int wssize = max(3*min(m,n)+max(m,n), 5*min(m,n));\n    int wssize = 3 * (m < n ? m : n) + (m > n ? m : n);\n    int wssize1 = 5 * (m < n ? m : n);\n    wssize = (wssize > wssize1 ? wssize : wssize1);\n\n    //\tT* wsbuf = mem::aligned_new < T > (wssize);\n    std::vector<T> wsbufdata(wssize);\n    T *wsbuf = wsbufdata.data();\n\n    svd(&JOBU, &JOBVT, &m, &n, &M[0], &m, &tS[0], &tU[0], &m, &tVT[0], &k,\n        wsbuf, &wssize, &INFO);\n    if (INFO != 0)\n        std::cout << INFO << '\\n';\n    assert(INFO == 0);\n    //\tmem::aligned_delete < T > (wsbuf);\n\n    T eps_ = tS[0] * eps;\n    for (int i = 0; i < k; i++)\n        if (tS[i] < eps_) {\n            tS[i] = 0;\n        } else {\n            tS[i] = 1.0 / tS[i];\n            //\t\t\tstd::cout << tS[i] << std::endl;\n        }\n    for (int i = 0; i < m; i++) {\n        for (int j = 0; j < k; j++) {\n            tU[i + j * m] *= tS[j];\n        }\n    }\n\n    gemm<T>('T', 'T', n, m, k, 1.0, &tVT[0], k, &tU[0], m, 0.0, M_, n);\n    //\tmem::aligned_delete < T > (tU);\n    //\tmem::aligned_delete < T > (tS);\n    //\tmem::aligned_delete < T > (tVT);\n}\n\ninline void pinv(const Eigen::MatrixXd &Mat, Eigen::MatrixXd &MatPinv) {\n    double eps = 1;\n    while (eps + 1.0 > 1.0) {\n        eps *= 0.5;\n    }\n    eps = sqrt(eps);\n\n    std::vector<double> M(Mat.cols() * Mat.rows());\n    std::vector<double> Mpinv(M.size());\n\n    // row major\n    for (int i = 0; i < Mat.rows(); i++) {\n        for (int j = 0; j < Mat.cols(); j++) {\n            M[i * Mat.cols() + j] = Mat(i, j);\n        }\n    }\n\n    pinv_pvfmm<double>(M.data(), Mat.rows(), Mat.cols(), eps, Mpinv.data());\n\n    //#define U(i,j) U_[(i)*dim[0]+(j)]\n    // row major\n    for (int i = 0; i < Mat.cols(); i++) {\n        for (int j = 0; j < Mat.rows(); j++) {\n            MatPinv(i, j) = Mpinv[i * Mat.rows() + j];\n        }\n    }\n}\n\ninline void pinv(const Eigen::MatrixXd &Mat, Eigen::MatrixXd &MatPinvU,\n                 Eigen::MatrixXd &MatPinvVT) {\n    // this is the really backward stable SVD used by pvfmm\n\n    double eps = 1;\n    while (eps * (double)0.5 + (double)1.0 > 1.0) {\n        eps *= 0.5;\n    }\n\n    std::vector<double> M(Mat.cols() * Mat.rows());\n    std::vector<double> Mpinv(M.size());\n\n    // row major\n    for (int i = 0; i < Mat.rows(); i++) {\n        for (int j = 0; j < Mat.cols(); j++) {\n            M[i * Mat.cols() + j] = Mat(i, j);\n        }\n    }\n\n    const int n1 = Mat.rows();\n    const int n2 = Mat.cols();\n\n    if (n1 * n2 == 0)\n        return;\n    int m = n2;\n    int n = n1;\n    int k = (m < n ? m : n);\n\n    std::vector<double> Udata(m * k);\n    std::vector<double> Sdata(k);\n    std::vector<double> VTdata(k * n);\n\n    //\tT* tU = mem::aligned_new < T > (m * k);\n    //\tT* tS = mem::aligned_new < T > (k);\n    //\tT* tVT = mem::aligned_new < T > (k * n);\n\n    double *tU = Udata.data();\n    double *tS = Sdata.data();\n    double *tVT = VTdata.data();\n\n    // SVD\n    int INFO = 0;\n    char JOBU = 'S';\n    char JOBVT = 'S';\n\n    // int wssize = max(3*min(m,n)+max(m,n), 5*min(m,n));\n    int wssize = 3 * (m < n ? m : n) + (m > n ? m : n);\n    int wssize1 = 5 * (m < n ? m : n);\n    wssize = (wssize > wssize1 ? wssize : wssize1);\n\n    //\tT* wsbuf = mem::aligned_new < T > (wssize);\n    std::vector<double> wsbufdata(wssize);\n    double *wsbuf = wsbufdata.data();\n\n    svd(&JOBU, &JOBVT, &m, &n, &M[0], &m, &tS[0], &tU[0], &m, &tVT[0], &k,\n        wsbuf, &wssize, &INFO);\n    if (INFO != 0) {\n        std::cout << INFO << '\\n';\n    }\n    assert(INFO == 0);\n    //\tmem::aligned_delete < T > (wsbuf);\n\n    double eps_ = tS[0] * eps;\n\n    for (int i = 0; i < k; i++) {\n        tS[i] = (tS[i] > eps_ * 4 ? 1.0 / tS[i] : 0.0);\n    }\n\n    //\tfor (int i = 0; i < k; i++)\n    //\t\tif (tS[i] < eps_) {\n    //\t\t\ttS[i] = 0;\n    //\t\t} else {\n    //\t\t\ttS[i] = 1.0 / tS[i];\n    ////\t\t\tstd::cout << tS[i] << std::endl;\n    //\t\t}\n    for (int i = 0; i < m; i++) {\n        for (int j = 0; j < k; j++) {\n            tU[i + j * m] *= tS[j];\n        }\n    }\n\n    MatPinvU.resize(m, k);\n    MatPinvVT.resize(n, k);\n    for (int i = 0; i < m; i++) {\n        for (int j = 0; j < k; j++) {\n            MatPinvU(i, j) = tU[i * k + j];\n        }\n    }\n\n    for (int i = 0; i < n; i++) {\n        for (int j = 0; j < k; j++) {\n            MatPinvVT(i, j) = tVT[i * k + j];\n        }\n    }\n\n    //#define U(i,j) U_[(i)*dim[0]+(j)]\n    // row major\n}\n\n#endif /* M2LLAPLACE_1D3D_SVD_PVFMM_HPP_ */\n", "meta": {"hexsha": "283417bc5dcfa4809e7a489209034f11503dd658", "size": 19815, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Util/SVD_pvfmm.hpp", "max_stars_repo_name": "wenyan4work/PeriodicFMM", "max_stars_repo_head_hexsha": "00a512fd22da3f215f040be1c99c1c01b7c63c1f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-06-14T02:07:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-18T04:41:34.000Z", "max_issues_repo_path": "Util/SVD_pvfmm.hpp", "max_issues_repo_name": "wenyan4work/PeriodicFMM", "max_issues_repo_head_hexsha": "00a512fd22da3f215f040be1c99c1c01b7c63c1f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Util/SVD_pvfmm.hpp", "max_forks_repo_name": "wenyan4work/PeriodicFMM", "max_forks_repo_head_hexsha": "00a512fd22da3f215f040be1c99c1c01b7c63c1f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T16:30:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T20:26:36.000Z", "avg_line_length": 30.3911042945, "max_line_length": 80, "alphanum_fraction": 0.3665404996, "num_tokens": 7060, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.40710959227059107}}
{"text": "//  Copyright John Maddock 2007.\r\n//  Use, modification and distribution are subject to the\r\n//  Boost Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include <iostream>\r\n\r\n//[policy_eg_2\r\n\r\n#include <boost/math/special_functions/gamma.hpp>\r\n\r\nint main()\r\n{\r\n   using namespace boost::math::policies;\r\n   errno = 0;\r\n   std::cout << \"Result of tgamma(30000) is: \" \r\n      << boost::math::tgamma(\r\n         30000, \r\n         make_policy(\r\n            domain_error<errno_on_error>(),\r\n            pole_error<errno_on_error>(),\r\n            overflow_error<errno_on_error>(),\r\n            evaluation_error<errno_on_error>() \r\n         )\r\n      ) << std::endl;\r\n   // Check errno was set:\r\n   std::cout << \"errno = \" << errno << std::endl;\r\n   // and again with evaluation at a pole:\r\n   std::cout << \"Result of tgamma(-10) is: \" \r\n      << boost::math::tgamma(\r\n         -10, \r\n         make_policy(\r\n            domain_error<errno_on_error>(),\r\n            pole_error<errno_on_error>(),\r\n            overflow_error<errno_on_error>(),\r\n            evaluation_error<errno_on_error>() \r\n         )\r\n      ) << std::endl;\r\n   // Check errno was set:\r\n   std::cout << \"errno = \" << errno << std::endl;\r\n}\r\n\r\n//]\r\n\r\n", "meta": {"hexsha": "d183e557ab32b9c1dbf4a45844f83ed71be4be61", "size": 1287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/policy_eg_2.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/math/example/policy_eg_2.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/example/policy_eg_2.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 28.6, "max_line_length": 69, "alphanum_fraction": 0.5672105672, "num_tokens": 324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4070623716343578}}
{"text": "/*! @file mean.cc\n *  @brief Arithmetic and geometric means calculation.\n *  @author Markovtsev Vadim <v.markovtsev@samsung.com>\n *  @version 1.0\n *\n *  @section Notes\n *  This code partially conforms to <a href=\"http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml\">Google C++ Style Guide</a>.\n *\n *  @section Copyright\n *  Copyright © 2013 Samsung R&D Institute Russia\n *\n *  @section License\n *  Licensed to the Apache Software Foundation (ASF) under one\n *  or more contributor license agreements.  See the NOTICE file\n *  distributed with this work for additional information\n *  regarding copyright ownership.  The ASF licenses this file\n *  to you under the Apache License, Version 2.0 (the\n *  \"License\"); you may not use this file except in compliance\n *  with the License.  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an\n *  \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n *  KIND, either express or implied.  See the License for the\n *  specific language governing permissions and limitations\n *  under the License.\n */\n\n#include \"src/transforms/mean.h\"\n#include <algorithm>\n#include <limits>\n#include <simd/arithmetic-inl.h>\n#include <simd/mathfun.h>\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wold-style-cast\"\n#include <boost/regex.hpp>\n#pragma GCC diagnostic pop\n\nnamespace sound_feature_extraction {\nnamespace transforms {\n\nusing formats::FixedArray;\n\nstd::set<MeanType> Parse(const std::string& value,\n                         identity<std::set<MeanType>>) {\n  static const std::unordered_map<std::string, MeanType> map {\n    { internal::kMeanTypeArithmeticStr, kMeanTypeArithmetic },\n    { internal::kMeanTypeGeometricStr, kMeanTypeGeometric },\n  };\n\n  static const boost::regex all_regex(\"^\\\\s*(\\\\w+\\\\s*(\\\\s|$))+\");\n  boost::smatch match;\n  if (!boost::regex_match(value, match, all_regex)) {\n    throw InvalidParameterValueException();\n  }\n\n  std::set<MeanType> ret;\n  std::transform(boost::sregex_token_iterator(value.begin(), value.end(),\n                                            boost::regex(\"\\\\s*(\\\\w+)\\\\s*\"),\n                                            1),\n                 boost::sregex_token_iterator(),\n                 std::inserter(ret, ret.begin()),\n                 [](const std::string& subval) {\n    auto mtypeit = map.find(subval);\n    if (mtypeit == map.end()) {\n      throw InvalidParameterValueException();\n    }\n    return mtypeit->second;\n  });\n\n  return ret;\n}\n\nMean::Mean() : types_(kDefaultMeanTypes()) {\n}\n\nALWAYS_VALID_TP(Mean, types)\n\nvoid Mean::Do(const float* in,\n            FixedArray<kMeanTypeCount>* out) const noexcept {\n  for (int j = 0; j < kMeanTypeCount; j++) {\n    auto mt = static_cast<MeanType>(j);\n    if (types_.find(mt) != types_.end()) {\n      (*out)[j] = Do(use_simd(), in, input_format_->Size(), mt);\n    } else {\n      (*out)[j] = 0;\n    }\n  }\n}\n\nfloat Mean::Do(bool simd, const float* input, size_t length,\n               MeanType type) noexcept {\n  int ilength = static_cast<int>(length);\n  switch (type) {\n    case kMeanTypeArithmetic: {\n      float res;\n      if (simd) {\n#if defined(__AVX__) || defined(__ARM_NEON__)\n        res = sum_elements(input, length);\n      } else {\n#else\n      } {\n#endif\n        res = sum_elements_na(input, length);\n      }\n      res /= length;\n      return res;\n    }\n    case kMeanTypeGeometric: {\n      const float power = 1.f / ilength;\n      if (simd) {\n#ifdef __AVX__\n        __m256 res = _mm256_set1_ps(1.f), tmp = _mm256_set1_ps(1.f);\n        const __m256 powvec = _mm256_set1_ps(power);\n        const __m256 infvec = _mm256_set1_ps(\n            std::numeric_limits<float>::infinity());\n        for (int j = 0; j < ilength - 7; j += 8) {\n          __m256 vec = _mm256_load_ps(input + j);\n          __m256 mulvec = _mm256_mul_ps(tmp, vec);\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wold-style-cast\"\n          __m256 cmpvec = _mm256_cmp_ps(mulvec, infvec, _CMP_EQ_UQ);\n          int check = _mm256_movemask_ps(cmpvec);\n          if (check != 0) {\n            // Taking a power from 0 can lead to unexpected results...\n            // Apply the mask to workaround zeros in tmp\n            cmpvec = _mm256_cmp_ps(tmp, _mm256_set1_ps(0.f), _CMP_EQ_UQ);\n            tmp = pow256_ps(tmp, powvec);\n            tmp = _mm256_blendv_ps(tmp, _mm256_set1_ps(0.f), cmpvec);\n            res = _mm256_mul_ps(res, tmp);\n            tmp = vec;\n          } else {\n            tmp = mulvec;\n          }\n#pragma GCC diagnostic pop\n        }\n        for (int i = 0; i < 8; i++) {\n          if (_mm256_get_ps(tmp, i) == 0) {\n            return 0;\n          }\n        }\n        tmp = pow256_ps(tmp, powvec);\n        res = _mm256_mul_ps(res, tmp);\n        float sctmp = 1.f;\n        for (int j = (ilength & ~0x7); j < ilength; j++) {\n          sctmp *= input[j];\n        }\n        float scres = powf(sctmp, power);\n        for (int j = 0; j < 8; j++) {\n          scres *= _mm256_get_ps(res, j);\n        }\n        return scres;\n      } else {\n#elif defined(__ARM_NEON__)\n        float32x4_t res = vdupq_n_f32(1.0f), tmp = vdupq_n_f32(1.0f),\n            powvec = vdupq_n_f32(power),\n            infvec = vdupq_n_f32(std::numeric_limits<float>::infinity());\n\n        for (int j = 0; j < ilength - 3; j += 4) {\n          float32x4_t vec = vld1q_f32(input + j);\n          float32x4_t mulvec = vmulq_f32(tmp, vec);\n          uint32x4_t cmpvec = vceqq_f32(mulvec, infvec);\n          uint64x2_t cmpvec2 = vpaddlq_u32(cmpvec);\n          if (vgetq_lane_u64(cmpvec2, 0) != 0 ||\n              vgetq_lane_u64(cmpvec2, 1) != 0) {\n            tmp = pow_ps(tmp, powvec);\n            res = vmulq_f32(res, tmp);\n            tmp = vec;\n          } else {\n            tmp = mulvec;\n          }\n        }\n        tmp = pow_ps(tmp, powvec);\n        res = vmulq_f32(res, tmp);\n        float sctmp = 1.f;\n        for (int j = (ilength & ~0x3); j < ilength; j++) {\n          sctmp *= input[j];\n        }\n        float scres = powf(sctmp, power);\n        scres *= vgetq_lane_f32(res, 0) * vgetq_lane_f32(res, 1) *\n            vgetq_lane_f32(res, 2) * vgetq_lane_f32(res, 3);\n        return scres;\n      } else {\n#else\n      } {\n#endif\n        float res = 1.f, tmp = 1.f;\n        for (int j = 0; j < ilength; j++) {\n          float val = input[j];\n          float multmp = tmp * val;\n          if (multmp == std::numeric_limits<float>::infinity()) {\n            res *= powf(tmp, power);\n            tmp = val;\n          } else {\n            tmp = multmp;\n          }\n        }\n        if (tmp != 1.f) {\n          res *= powf(tmp, power);\n        }\n        return res;\n      }\n    }\n    default:\n      break;\n  }\n  return 0.f;\n}\n\nRTP(Mean, types)\nREGISTER_TRANSFORM(Mean);\n\n}  // namespace transforms\n}  // namespace sound_feature_extraction\n", "meta": {"hexsha": "d61b374bdb72dfd169b386ebe70240fb9440d21c", "size": 6926, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/transforms/mean.cc", "max_stars_repo_name": "Samsung/veles.sound_feature_extraction-", "max_stars_repo_head_hexsha": "56b7c5d3816d092c72a874ca236e889fe843e6cd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-11-10T06:06:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-28T04:54:17.000Z", "max_issues_repo_path": "src/transforms/mean.cc", "max_issues_repo_name": "Samsung/veles.sound_feature_extraction-", "max_issues_repo_head_hexsha": "56b7c5d3816d092c72a874ca236e889fe843e6cd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/transforms/mean.cc", "max_forks_repo_name": "Samsung/veles.sound_feature_extraction-", "max_forks_repo_head_hexsha": "56b7c5d3816d092c72a874ca236e889fe843e6cd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-08-08T20:28:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T01:03:47.000Z", "avg_line_length": 31.9170506912, "max_line_length": 136, "alphanum_fraction": 0.5788333815, "num_tokens": 1929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718435083355188, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.40700583540857377}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// BSD 3-Clause License\n//\n// Copyright (C) 2019-2020, LAAS-CNRS, University of Edinburgh\n// Copyright note valid unless otherwise stated in individual files.\n// All rights reserved.\n///////////////////////////////////////////////////////////////////////////////\n\n#include <Eigen/Core>\n#include <example-robot-data/path.hpp>\n#include <pinocchio/algorithm/model.hpp>\n#include <pinocchio/parsers/srdf.hpp>\n#include <pinocchio/parsers/urdf.hpp>\n\n#include \"crocoddyl/core/costs/cost-sum.hpp\"\n#include \"crocoddyl/core/costs/residual.hpp\"\n#include \"crocoddyl/core/integrator/euler.hpp\"\n#include \"crocoddyl/core/mathbase.hpp\"\n#include \"crocoddyl/core/residuals/control.hpp\"\n#include \"crocoddyl/core/solvers/ddp.hpp\"\n#include \"crocoddyl/core/utils/callbacks.hpp\"\n#include \"crocoddyl/core/utils/timer.hpp\"\n#include \"crocoddyl/multibody/actions/free-fwddyn.hpp\"\n#include \"crocoddyl/multibody/actuations/full.hpp\"\n#include \"crocoddyl/multibody/residuals/frame-placement.hpp\"\n#include \"crocoddyl/multibody/residuals/state.hpp\"\n#include \"crocoddyl/multibody/states/multibody.hpp\"\n\nusing boost::make_shared;\nusing boost::shared_ptr;\nusing namespace crocoddyl;\n\nstd::tuple<shared_ptr<ActionModelAbstractTpl<double>>, shared_ptr<ActionModelAbstractTpl<double>>>\nbuild_arm_action_models()\n{\n    typedef typename MathBaseTpl<double>::Vector3s Vector3s;\n    typedef typename MathBaseTpl<double>::Matrix3s Matrix3s;\n\n    // because urdf is not supported with all double types.\n    pinocchio::ModelTpl<double> modeld;\n    pinocchio::urdf::buildModel(EXAMPLE_ROBOT_DATA_MODEL_DIR \"/talos_data/robots/talos_left_arm.urdf\", modeld);\n    pinocchio::srdf::loadReferenceConfigurations(modeld, EXAMPLE_ROBOT_DATA_MODEL_DIR \"/talos_data/srdf/talos.srdf\",\n                                                 false);\n\n    pinocchio::ModelTpl<double> model_full(modeld.cast<double>()), model;\n    std::vector<pinocchio::JointIndex> locked_joints;\n    locked_joints.push_back(5);\n    locked_joints.push_back(6);\n    locked_joints.push_back(7);\n    pinocchio::buildReducedModel(model_full, locked_joints, Eigen::VectorXd::Zero(model_full.nq), model);\n\n    shared_ptr<StateMultibodyTpl<double>> state =\n        make_shared<StateMultibodyTpl<double>>(make_shared<pinocchio::ModelTpl<double>>(model));\n\n    auto goalTrackingCost = make_shared<CostModelResidualTpl<double>>(\n        state, make_shared<ResidualModelFramePlacementTpl<double>>(\n                   state, model.getFrameId(\"gripper_left_joint\"),\n                   pinocchio::SE3Tpl<double>(Matrix3s::Identity(), Vector3s(double(0), double(0), double(.4)))));\n    auto xRegCost = make_shared<CostModelResidualTpl<double>>(state, make_shared<ResidualModelStateTpl<double>>(state));\n    auto uRegCost =\n        make_shared<CostModelResidualTpl<double>>(state, make_shared<ResidualModelControlTpl<double>>(state));\n\n    // Create a cost model per the running and terminal action model.\n    auto runningCostModel = make_shared<CostModelSumTpl<double>>(state);\n    auto terminalCostModel = make_shared<CostModelSumTpl<double>>(state);\n\n    // Then let's added the running and terminal cost functions\n    runningCostModel->addCost(\"gripperPose\", goalTrackingCost, double(1));\n    runningCostModel->addCost(\"xReg\", xRegCost, double(1e-4));\n    runningCostModel->addCost(\"uReg\", uRegCost, double(1e-4));\n    terminalCostModel->addCost(\"gripperPose\", goalTrackingCost, double(1));\n\n    // We define an actuation model\n    auto actuation = make_shared<ActuationModelFullTpl<double>>(state);\n\n    // Next, we need to create an action model for running and terminal knots. The\n    // forward dynamics (computed using ABA) are implemented\n    // inside DifferentialActionModelFullyActuated.\n    auto runningDAM =\n        make_shared<DifferentialActionModelFreeFwdDynamicsTpl<double>>(state, actuation, runningCostModel);\n\n    auto runningModel = make_shared<IntegratedActionModelEulerTpl<double>>(runningDAM, double(1e-3));\n    auto terminalModel = make_shared<IntegratedActionModelEulerTpl<double>>(runningDAM, double(0.));\n\n    return {runningModel, terminalModel};\n}\n\nint main(int argc, char *argv[])\n{\n    unsigned int N = 100;  // number of nodes\n    unsigned int T = 5e3;  // number of trials\n    unsigned int MAXITER = 1;\n\n    if (argc > 1)\n    {\n        T = atoi(argv[1]);\n    }\n\n    // Building the running and terminal models\n    auto [runningModel, terminalModel] = build_arm_action_models();\n\n    // Get the initial state\n    shared_ptr<StateMultibody> state = boost::static_pointer_cast<StateMultibody>(runningModel->get_state());\n\n    std::cout << \"NQ: \" << state->get_nq() << std::endl;\n    std::cout << \"Number of nodes: \" << N << std::endl << std::endl;\n\n    Eigen::VectorXd q0 = Eigen::VectorXd::Random(state->get_nq());\n    Eigen::VectorXd x0(state->get_nx());\n    x0 << q0, Eigen::VectorXd::Random(state->get_nv());\n\n    // For this optimal control problem, we define 100 knots (or running action\n    // models) plus a terminal knot\n    std::vector<shared_ptr<ActionModelAbstract>> runningModels(N, runningModel);\n    ShootingProblem problem(x0, runningModels, terminalModel);\n    std::vector<Eigen::VectorXd> xs(N + 1, x0);\n    std::vector<Eigen::VectorXd> us(N, Eigen::VectorXd::Zero(runningModel->get_nu()));\n    for (unsigned int i = 0; i < N; ++i)\n    {\n        const shared_ptr<ActionModelAbstract> &model = problem.get_runningModels()[i];\n        const shared_ptr<ActionDataAbstract> &data = problem.get_runningDatas()[i];\n        model->quasiStatic(data, us[i], x0);\n    }\n\n    // Formulating the optimal control problem\n    SolverDDP ddp(problem);\n\n    // Solving the optimal control problem\n    Eigen::ArrayXd duration(T);\n    for (unsigned int i = 0; i < T; ++i)\n    {\n        Timer timer;\n        ddp.solve(xs, us, MAXITER, false, 0.1);\n        duration[i] = timer.get_duration();\n    }\n\n    double avrg_duration = duration.sum() / T;\n    double min_duration = duration.minCoeff();\n    double max_duration = duration.maxCoeff();\n    std::cout << \"  DDP.solve [ms]: \" << avrg_duration << \" (\" << min_duration << \"-\" << max_duration << \")\"\n              << std::endl;\n\n    // Running calc\n    for (unsigned int i = 0; i < T; ++i)\n    {\n        Timer timer;\n        problem.calc(xs, us);\n        duration[i] = timer.get_duration();\n    }\n\n    avrg_duration = duration.sum() / T;\n    min_duration = duration.minCoeff();\n    max_duration = duration.maxCoeff();\n    std::cout << \"  ShootingProblem.calc [ms]: \" << avrg_duration << \" (\" << min_duration << \"-\" << max_duration << \")\"\n              << std::endl;\n\n    // Running calcDiff\n    for (unsigned int i = 0; i < T; ++i)\n    {\n        Timer timer;\n        problem.calcDiff(xs, us);\n        duration[i] = timer.get_duration();\n    }\n\n    avrg_duration = duration.sum() / T;\n    min_duration = duration.minCoeff();\n    max_duration = duration.maxCoeff();\n    std::cout << \"  ShootingProblem.calcDiff [ms]: \" << avrg_duration << \" (\" << min_duration << \"-\" << max_duration\n              << \")\" << std::endl;\n}\n\n// import sys\n\n// import crocoddyl\n// import numpy as np\n// import example_robot_data\n// import pinocchio\n\n// # Load robot\n// robot = example_robot_data.load(\"talos\")\n\n// # Create data structures\n// rdata = robot.model.createData()\n// state = crocoddyl.StateMultibody(robot.model)\n// actuation = crocoddyl.ActuationModelFloatingBase(state)\n\n// # Set integration time\n// DT = 5e-2\n// T = 60\n// target = np.array([0.5, 0, 1.8])\n\n// # Initialize reference state, target and reference CoM\n// rightFoot = \"right_sole_link\"\n// leftFoot = \"left_sole_link\"\n// endEffector = \"gripper_left_joint\"\n// endEffectorId = robot.model.getFrameId(endEffector)\n// rightFootId = robot.model.getFrameId(rightFoot)\n// leftFootId = robot.model.getFrameId(leftFoot)\n// q0 = robot.model.referenceConfigurations[\"half_sitting\"]\n// x0 = np.concatenate([q0, np.zeros(robot.model.nv)])\n// pinocchio.forwardKinematics(robot.model, rdata, q0)\n// pinocchio.updateFramePlacements(robot.model, rdata)\n\n// # Initialize Gepetto viewer\n// display = crocoddyl.GepettoDisplay(robot, frameNames=[rightFoot, leftFoot])\n// display.robot.viewer.gui.addSphere(\"world/point\", 0.05, [1.0, 0.0, 0.0, 1.0])\n// display.robot.viewer.gui.applyConfiguration(\"world/point\", target.tolist() + [0.0, 0.0, 0.0, 1.0])\n\n// # Add contact to the model\n// contactModel = crocoddyl.ContactModelMultiple(state, actuation.nu)\n// supportContactModelLeft = crocoddyl.ContactModel6D(\n//     state, leftFootId, pinocchio.SE3.Identity(), actuation.nu, np.array([0, 0])\n// )\n// contactModel.addContact(leftFoot + \"_contact\", supportContactModelLeft)\n// supportContactModelRight = crocoddyl.ContactModel6D(\n//     state, rightFootId, pinocchio.SE3.Identity(), actuation.nu, np.array([0, 0])\n// )\n// contactModel.addContact(rightFoot + \"_contact\", supportContactModelRight)\n\n// contactModelLeft = crocoddyl.ContactModelMultiple(state, actuation.nu)\n// contactModelLeft.addContact(\n//     \"contact\",\n//     crocoddyl.ContactModel6D(\n//         state, leftFootId, pinocchio.SE3.Identity(), actuation.nu, np.array([0, 0])\n//     ),\n// )\n\n// contactModelRight = crocoddyl.ContactModelMultiple(state, actuation.nu)\n// contactModelRight.addContact(\n//     \"contact\",\n//     crocoddyl.ContactModel6D(\n//         state, rightFootId, pinocchio.SE3.Identity(), actuation.nu, np.array([0, 0])\n//     ),\n// )\n\n// # Cost for self-collision\n// maxfloat = sys.float_info.max\n// xlb = np.concatenate(\n//     [\n//         -maxfloat * np.ones(6),  # dimension of the SE(3) manifold\n//         robot.model.lowerPositionLimit[7:],\n//         -maxfloat * np.ones(state.nv),\n//     ]\n// )\n// xub = np.concatenate(\n//     [\n//         maxfloat * np.ones(6),  # dimension of the SE(3) manifold\n//         robot.model.upperPositionLimit[7:],\n//         maxfloat * np.ones(state.nv),\n//     ]\n// )\n// bounds = crocoddyl.ActivationBounds(xlb, xub, 1.0)\n// xLimitResidual = crocoddyl.ResidualModelState(state, x0, actuation.nu)\n// xLimitActivation = crocoddyl.ActivationModelQuadraticBarrier(bounds)\n// limitCost = crocoddyl.CostModelResidual(state, xLimitActivation, xLimitResidual)\n\n// # Cost for state and control\n// xResidual = crocoddyl.ResidualModelState(state, x0, actuation.nu)\n// xActivation = crocoddyl.ActivationModelWeightedQuad(\n//     np.array([0] * 3 + [10.0] * 3 + [0.01] * (state.nv - 6) + [10] * state.nv) ** 2\n// )\n// uResidual = crocoddyl.ResidualModelControl(state, actuation.nu)\n// xTActivation = crocoddyl.ActivationModelWeightedQuad(\n//     np.array([0] * 3 + [10.0] * 3 + [0.01] * (state.nv - 6) + [100] * state.nv) ** 2\n// )\n// xRegCost = crocoddyl.CostModelResidual(state, xActivation, xResidual)\n// uRegCost = crocoddyl.CostModelResidual(state, uResidual)\n// xRegTermCost = crocoddyl.CostModelResidual(state, xTActivation, xResidual)\n\n// # Cost for target reaching\n// framePlacementResidual = crocoddyl.ResidualModelFramePlacement(\n//     state, endEffectorId, pinocchio.SE3(np.eye(3), target), actuation.nu\n// )\n// framePlacementActivation = crocoddyl.ActivationModelWeightedQuad(\n//     np.array([1] * 3 + [0.0001] * 3) ** 2\n// )\n// goalTrackingCost = crocoddyl.CostModelResidual(\n//     state, framePlacementActivation, framePlacementResidual\n// )\n\n// # Create cost model per each action model\n// runningCostModel = crocoddyl.CostModelSum(state, actuation.nu)\n// terminalCostModel = crocoddyl.CostModelSum(state, actuation.nu)\n\n// # Then let's added the running and terminal cost functions\n// runningCostModel.addCost(\"gripperPose\", goalTrackingCost, 1e2)\n// runningCostModel.addCost(\"stateReg\", xRegCost, 1e-3)\n// runningCostModel.addCost(\"ctrlReg\", uRegCost, 1e-4)\n// runningCostModel.addCost(\"limitCost\", limitCost, 1e3)\n\n// terminalCostModel.addCost(\"gripperPose\", goalTrackingCost, 1e2)\n// terminalCostModel.addCost(\"stateReg\", xRegTermCost, 1e-3)\n// terminalCostModel.addCost(\"limitCost\", limitCost, 1e3)\n\n// # Create the action model\n// dmodelRunningLeft = crocoddyl.DifferentialActionModelContactFwdDynamics(\n//     state, actuation, contactModelLeft, runningCostModel\n// )\n// dmodelTerminalLeft = crocoddyl.DifferentialActionModelContactFwdDynamics(\n//     state, actuation, contactModelLeft, terminalCostModel\n// )\n\n// dmodelRunning = crocoddyl.DifferentialActionModelContactFwdDynamics(\n//     state, actuation, contactModelRight, runningCostModel\n// )\n// dmodelTerminal = crocoddyl.DifferentialActionModelContactFwdDynamics(\n//     state, actuation, contactModelRight, terminalCostModel\n// )\n// runningModelLeft = crocoddyl.IntegratedActionModelEuler(dmodelRunningLeft, DT)\n// runningModel = crocoddyl.IntegratedActionModelEuler(dmodelRunning, DT)\n// terminalModel = crocoddyl.IntegratedActionModelEuler(dmodelTerminal, 0)\n\n// # Problem definition\n// x0 = np.concatenate([q0, pinocchio.utils.zero(state.nv)])\n// problem = crocoddyl.ShootingProblem(x0, [runningModel] * T + [runningModelLeft] * T, terminalModel)\n\n// # Creating the DDP solver for this OC problem, defining a logger\n// solver = crocoddyl.SolverFDDP(problem)\n// solver.setCallbacks(\n//     [\n//         crocoddyl.CallbackVerbose(),\n//         crocoddyl.CallbackDisplay(\n//             crocoddyl.GepettoDisplay(robot, 4, 4, frameNames=[rightFoot, leftFoot])\n//         ),\n//     ]\n// )\n\n// # Solving it with the FDDP algorithm\n// xs = [x0] * (solver.problem.T + 1)\n// us = solver.problem.quasiStatic([x0] * solver.problem.T)\n// solver.solve(xs, us, 500, False, 0.1)\n\n// # Visualizing the solution in gepetto-viewer\n// display.displayFromSolver(solver)\n\n// # Get final state and end effector position\n// xT = solver.xs[-1]\n// pinocchio.forwardKinematics(robot.model, rdata, xT[: state.nq])\n// pinocchio.updateFramePlacements(robot.model, rdata)\n// com = pinocchio.centerOfMass(robot.model, rdata, xT[: state.nq])\n// finalPosEff = np.array(rdata.oMf[robot.model.getFrameId(\"gripper_left_joint\")].translation.T.flat)\n\n// print(\"Finally reached = \", finalPosEff)\n// print(\"Distance between hand and target = \", np.linalg.norm(finalPosEff - target))\n// print(\"Distance to default state = \", np.linalg.norm(x0 - np.array(xT.flat)))\n// # print(\"XY distance to CoM reference = \", np.linalg.norm(com[:2] - comRef[:2]))", "meta": {"hexsha": "2509394f956948e3f43c72a3aabdeca4056acff6", "size": 14193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "benchmark/arm-manipulation-optctrl.cpp", "max_stars_repo_name": "tomstewart89/crocoddyl", "max_stars_repo_head_hexsha": "8a85af3a1d4d8f231b0000e660a30b8295e5f44a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark/arm-manipulation-optctrl.cpp", "max_issues_repo_name": "tomstewart89/crocoddyl", "max_issues_repo_head_hexsha": "8a85af3a1d4d8f231b0000e660a30b8295e5f44a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark/arm-manipulation-optctrl.cpp", "max_forks_repo_name": "tomstewart89/crocoddyl", "max_forks_repo_head_hexsha": "8a85af3a1d4d8f231b0000e660a30b8295e5f44a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0202312139, "max_line_length": 120, "alphanum_fraction": 0.6944972874, "num_tokens": 3876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.40688651096731504}}
{"text": "/******************************************************************************\n * Author:   Laurent Kneip                                                    *\n * Contact:  kneip.laurent@gmail.com                                          *\n * License:  Copyright (c) 2013 Laurent Kneip, ANU. All rights reserved.      *\n *                                                                            *\n * Redistribution and use in source and binary forms, with or without         *\n * modification, are permitted provided that the following conditions         *\n * are met:                                                                   *\n * * Redistributions of source code must retain the above copyright           *\n *   notice, this list of conditions and the following disclaimer.            *\n * * Redistributions in binary form must reproduce the above copyright        *\n *   notice, this list of conditions and the following disclaimer in the      *\n *   documentation and/or other materials provided with the distribution.     *\n * * Neither the name of ANU nor the names of its contributors may be         *\n *   used to endorse or promote products derived from this software without   *\n *   specific prior written permission.                                       *\n *                                                                            *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"*\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  *\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *\n * ARE DISCLAIMED. IN NO EVENT SHALL ANU OR THE CONTRIBUTORS BE LIABLE        *\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT         *\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY  *\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF     *\n * SUCH DAMAGE.                                                               *\n ******************************************************************************/\n\n\n#include <Eigen/NonLinearOptimization>\n#include <Eigen/NumericalDiff>\n\n#include <opengv/absolute_pose/modules/main.hpp>\n#include <opengv/absolute_pose/modules/gp3p/modules.hpp>\n#include <opengv/absolute_pose/modules/gpnp1/modules.hpp>\n#include <opengv/absolute_pose/modules/gpnp2/modules.hpp>\n#include <opengv/absolute_pose/modules/gpnp3/modules.hpp>\n#include <opengv/absolute_pose/modules/gpnp4/modules.hpp>\n#include <opengv/absolute_pose/modules/gpnp5/modules.hpp>\n#include <opengv/absolute_pose/modules/upnp2.hpp>\n#include <opengv/absolute_pose/modules/upnp4.hpp>\n#include <opengv/OptimizationFunctor.hpp>\n#include <opengv/math/roots.hpp>\n#include <opengv/math/arun.hpp>\n#include <opengv/math/cayley.hpp>\n\nvoid\nopengv::absolute_pose::modules::p3p_kneip_main(\n    const bearingVectors_t & f,\n    const points_t & p,\n    transformations_t & solutions )\n{\n  point_t P1 = p[0];\n  point_t P2 = p[1];\n  point_t P3 = p[2];\n\n  Eigen::Vector3d temp1 = P2 - P1;\n  Eigen::Vector3d temp2 = P3 - P1;\n\n  if( temp1.cross(temp2).norm() == 0)\n    return;\n\n  bearingVector_t f1 = f[0];\n  bearingVector_t f2 = f[1];\n  bearingVector_t f3 = f[2];\n\n  Eigen::Vector3d e1 = f1;\n  Eigen::Vector3d e3 = f1.cross(f2);\n  e3 = e3/e3.norm();\n  Eigen::Vector3d e2 = e3.cross(e1);\n\n  rotation_t T;\n  T.row(0) = e1.transpose();\n  T.row(1) = e2.transpose();\n  T.row(2) = e3.transpose();\n\n  f3 = T*f3;\n\n  if( f3(2,0) > 0)\n  {\n    f1 = f[1];\n    f2 = f[0];\n    f3 = f[2];\n\n    e1 = f1;\n    e3 = f1.cross(f2);\n    e3 = e3/e3.norm();\n    e2 = e3.cross(e1);\n\n    T.row(0) = e1.transpose();\n    T.row(1) = e2.transpose();\n    T.row(2) = e3.transpose();\n\n    f3 = T*f3;\n\n    P1 = p[1];\n    P2 = p[0];\n    P3 = p[2];\n  }\n\n  Eigen::Vector3d n1 = P2-P1;\n  n1 = n1/n1.norm();\n  Eigen::Vector3d n3 = n1.cross(P3-P1);\n  n3 = n3/n3.norm();\n  Eigen::Vector3d n2 = n3.cross(n1);\n\n  rotation_t N;\n  N.row(0) = n1.transpose();\n  N.row(1) = n2.transpose();\n  N.row(2) = n3.transpose();\n\n  P3 = N*(P3-P1);\n\n  double d_12 = temp1.norm();\n  double f_1 = f3(0,0)/f3(2,0);\n  double f_2 = f3(1,0)/f3(2,0);\n  double p_1 = P3(0,0);\n  double p_2 = P3(1,0);\n\n  double cos_beta = f1.dot(f2);\n  double b = 1/( 1 - pow( cos_beta, 2 ) ) - 1;\n\n  if( cos_beta < 0 )\n    b = -sqrt(b);\n  else\n    b = sqrt(b);\n\n  double f_1_pw2 = pow(f_1,2);\n  double f_2_pw2 = pow(f_2,2);\n  double p_1_pw2 = pow(p_1,2);\n  double p_1_pw3 = p_1_pw2 * p_1;\n  double p_1_pw4 = p_1_pw3 * p_1;\n  double p_2_pw2 = pow(p_2,2);\n  double p_2_pw3 = p_2_pw2 * p_2;\n  double p_2_pw4 = p_2_pw3 * p_2;\n  double d_12_pw2 = pow(d_12,2);\n  double b_pw2 = pow(b,2);\n\n  Eigen::Matrix<double,5,1> factors;\n\n  factors(0,0) = -f_2_pw2*p_2_pw4\n                 -p_2_pw4*f_1_pw2\n                 -p_2_pw4;\n\n  factors(1,0) = 2*p_2_pw3*d_12*b\n                 +2*f_2_pw2*p_2_pw3*d_12*b\n                 -2*f_2*p_2_pw3*f_1*d_12;\n\n  factors(2,0) = -f_2_pw2*p_2_pw2*p_1_pw2\n                 -f_2_pw2*p_2_pw2*d_12_pw2*b_pw2\n                 -f_2_pw2*p_2_pw2*d_12_pw2\n                 +f_2_pw2*p_2_pw4\n                 +p_2_pw4*f_1_pw2\n                 +2*p_1*p_2_pw2*d_12\n                 +2*f_1*f_2*p_1*p_2_pw2*d_12*b\n                 -p_2_pw2*p_1_pw2*f_1_pw2\n                 +2*p_1*p_2_pw2*f_2_pw2*d_12\n                 -p_2_pw2*d_12_pw2*b_pw2\n                 -2*p_1_pw2*p_2_pw2;\n\n  factors(3,0) = 2*p_1_pw2*p_2*d_12*b\n                 +2*f_2*p_2_pw3*f_1*d_12\n                 -2*f_2_pw2*p_2_pw3*d_12*b\n                 -2*p_1*p_2*d_12_pw2*b;\n\n  factors(4,0) = -2*f_2*p_2_pw2*f_1*p_1*d_12*b\n                 +f_2_pw2*p_2_pw2*d_12_pw2\n                 +2*p_1_pw3*d_12\n                 -p_1_pw2*d_12_pw2\n                 +f_2_pw2*p_2_pw2*p_1_pw2\n                 -p_1_pw4\n                 -2*f_2_pw2*p_2_pw2*p_1*d_12\n                 +p_2_pw2*f_1_pw2*p_1_pw2\n                 +f_2_pw2*p_2_pw2*d_12_pw2*b_pw2;\n\n  std::vector<double> realRoots = math::o4_roots(factors);\n\n  for( int i = 0; i < 4; i++ )\n  {\n    double cot_alpha =\n        (-f_1*p_1/f_2-realRoots[i]*p_2+d_12*b)/\n        (-f_1*realRoots[i]*p_2/f_2+p_1-d_12);\n\n    double cos_theta = realRoots[i];\n    double sin_theta = sqrt(1-pow(realRoots[i],2));\n    double sin_alpha = sqrt(1/(pow(cot_alpha,2)+1));\n    double cos_alpha = sqrt(1-pow(sin_alpha,2));\n\n    if (cot_alpha < 0)\n      cos_alpha = -cos_alpha;\n\n    translation_t C;\n    C(0,0) = d_12*cos_alpha*(sin_alpha*b+cos_alpha);\n    C(1,0) = cos_theta*d_12*sin_alpha*(sin_alpha*b+cos_alpha);\n    C(2,0) = sin_theta*d_12*sin_alpha*(sin_alpha*b+cos_alpha);\n\n    C = P1 + N.transpose()*C;\n\n    rotation_t R;\n    R(0,0) = -cos_alpha;\n    R(0,1) = -sin_alpha*cos_theta;\n    R(0,2) = -sin_alpha*sin_theta;\n    R(1,0) = sin_alpha;\n    R(1,1) = -cos_alpha*cos_theta;\n    R(1,2) = -cos_alpha*sin_theta;\n    R(2,0) = 0.0;\n    R(2,1) = -sin_theta;\n    R(2,2) = cos_theta;\n\n    R = N.transpose()*R.transpose()*T;\n\n    transformation_t solution;\n    solution.col(3) = C;\n    solution.block<3,3>(0,0) = R;\n\n    solutions.push_back(solution);\n  }\n}\n\nvoid\nopengv::absolute_pose::modules::p3p_gao_main(\n    const bearingVectors_t & f,\n    const points_t & points,\n    transformations_t & solutions )\n{\n  point_t A = points[0];\n  point_t B = points[1];\n  point_t C = points[2];\n\n  Eigen::Vector3d tempp;\n  tempp = A-B;\n  double AB = tempp.norm();\n  tempp = B-C;\n  double BC = tempp.norm();\n  tempp = A-C;\n  double AC = tempp.norm();\n\n  bearingVector_t f1 = f[0];\n  bearingVector_t f2 = f[1];\n  bearingVector_t f3 = f[2];\n\n  double cosalpha = f2.transpose()*f3;\n  double cosbeta = f1.transpose()*f3;\n  double cosgamma = f1.transpose()*f2;\n\n  double a=pow((BC/AB),2);\n  double b=pow((AC/AB),2);\n  double p=2*cosalpha;\n  double q=2*cosbeta;\n  double r=2*cosgamma;\n\n  double aSq = a * a;\n  double bSq = b * b;\n  double pSq = p*p;\n  double qSq = q*q;\n  double rSq = r*r;\n\n  if ((pSq + qSq + rSq - p*q*r - 1) == 0)\n    return;\n\n  Eigen::Matrix<double,5,1> factors;\n\n  factors[0] = -2*b + bSq + aSq + 1 - b*rSq*a + 2*b*a - 2*a;\n\n  if (factors[0] == 0)\n    return;\n\n  factors[1] =\n      -2*b*q*a - 2*aSq*q + b*rSq*q*a - 2*q + 2*b*q +\n      4*a*q + p*b*r + b*r*p*a - bSq*r*p;\n  factors[2] =\n      qSq + bSq*rSq - b*pSq - q*p*b*r + bSq*pSq - b*rSq*a +\n      2 - 2*bSq - a*b*r*p*q + 2*aSq - 4*a - 2*qSq*a + qSq*aSq;\n  factors[3] =\n      -bSq*r*p + b*r*p*a - 2*aSq*q + q*pSq*b +\n      2*b*q*a + 4*a*q + p*b*r - 2*b*q - 2*q;\n  factors[4] = 1 - 2*a + 2*b + bSq - b*pSq + aSq - 2*b*a;\n\n  std::vector<double> x_temp = math::o4_roots(factors);\n  Eigen::Matrix<double,4,1> x;\n  for( size_t i = 0; i < 4; i++ ) x[i] = x_temp[i];\n\n  double temp = (pSq*(a-1+b) + p*q*r - q*a*r*p + (a-1-b)*rSq);\n  double b0 = b * temp * temp;\n\n  double rCb = rSq*r;\n\n  Eigen::Matrix<double,4,1> tempXP2;\n  tempXP2[0] = x[0]*x[0];\n  tempXP2[1] = x[1]*x[1];\n  tempXP2[2] = x[2]*x[2];\n  tempXP2[3] = x[3]*x[3];\n  Eigen::Matrix<double,4,1> tempXP3;\n  tempXP3[0] = tempXP2[0]*x[0];\n  tempXP3[1] = tempXP2[1]*x[1];\n  tempXP3[2] = tempXP2[2]*x[2];\n  tempXP3[3] = tempXP2[3]*x[3];\n\n  Eigen::Matrix<double,4,1> ones;\n  for( size_t i = 0; i < 4; i++) ones[i] = 1.0;\n\n  Eigen::Matrix<double,4,1> b1_part1 =\n      (1-a-b)*tempXP2 + (q*a-q)*x + (1 - a + b)*ones;\n\n  Eigen::Matrix<double,4,1> b1_part2 =\n      (aSq*rCb + 2*b*rCb*a - b*rSq*rCb*a - 2*a*rCb + rCb + bSq*rCb\n      - 2*rCb*b)*tempXP3\n      +(p*rSq + p*aSq*rSq - 2*b*rCb*q*a + 2*rCb*b*q - 2*rCb*q - 2*p*(a+b)*rSq\n      + rSq*rSq*p*b + 4*a*rCb*q + b*q*a*rCb*rSq - 2*rCb*aSq*q +2*rSq*p*b*a\n      + bSq*rSq*p - rSq*rSq*p*bSq)*tempXP2\n      +(rCb*qSq + rSq*rCb*bSq + r*pSq*bSq - 4*a*rCb - 2*a*rCb*qSq + rCb*qSq*aSq\n      + 2*aSq*rCb - 2*bSq*rCb - 2*pSq*b*r + 4*p*a*rSq*q + 2*a*pSq*r*b\n      - 2*a*rSq*q*b*p - 2*pSq*a*r + r*pSq - b*rSq*rCb*a + 2*p*rSq*b*q\n      + r*pSq*aSq -2*p*q*rSq + 2*rCb - 2*rSq*p*aSq*q - rSq*rSq*q*b*p)*x\n      +(4*a*rCb*q + p*rSq*qSq + 2*pSq*p*b*a - 4*p*a*rSq - 2*rCb*b*q - 2*pSq*q*r\n      - 2*bSq*rSq*p + rSq*rSq*p*b + 2*p*aSq*rSq - 2*rCb*aSq*q - 2*pSq*p*a\n      + pSq*p*aSq + 2*p*rSq + pSq*p + 2*b*rCb*q*a + 2*q*pSq*b*r + 4*q*a*r*pSq\n      - 2*p*a*rSq*qSq - 2*pSq*aSq*r*q + p*aSq*rSq*qSq - 2*rCb*q - 2*pSq*p*b\n      + pSq*p*bSq - 2*pSq*b*r*q*a)*ones;\n\n  Eigen::Matrix<double,4,1> b1;\n  b1[0] = b1_part1[0]*b1_part2[0];\n  b1[1] = b1_part1[1]*b1_part2[1];\n  b1[2] = b1_part1[2]*b1_part2[2];\n  b1[3] = b1_part1[3]*b1_part2[3];\n\n  Eigen::Matrix<double,4,1> y=b1/b0;\n  Eigen::Matrix<double,4,1> tempYP2;\n  tempYP2[0] = pow(y[0],2);\n  tempYP2[1] = pow(y[1],2);\n  tempYP2[2] = pow(y[2],2);\n  tempYP2[3] = pow(y[3],2);\n\n  Eigen::Matrix<double,4,1> tempXY;\n  tempXY[0] = x[0]*y[0];\n  tempXY[1] = x[1]*y[1];\n  tempXY[2] = x[2]*y[2];\n  tempXY[3] = x[3]*y[3];\n\n  Eigen::Matrix<double,4,1> v= tempXP2 + tempYP2 - r*tempXY;\n\n  Eigen::Matrix<double,4,1> Z;\n  Z[0] = AB/sqrt(v[0]);\n  Z[1] = AB/sqrt(v[1]);\n  Z[2] = AB/sqrt(v[2]);\n  Z[3] = AB/sqrt(v[3]);\n\n  Eigen::Matrix<double,4,1> X;\n  X[0] = x[0]*Z[0];\n  X[1] = x[1]*Z[1];\n  X[2] = x[2]*Z[2];\n  X[3] = x[3]*Z[3];\n\n  Eigen::Matrix<double,4,1> Y;\n  Y[0] = y[0]*Z[0];\n  Y[1] = y[1]*Z[1];\n  Y[2] = y[2]*Z[2];\n  Y[3] = y[3]*Z[3];\n\n  for( int i = 0; i < 4; i++ )\n  {\n    //apply arun to find the transformation\n    points_t p_cam;\n    p_cam.push_back(X[i]*f1);\n    p_cam.push_back(Y[i]*f2);\n    p_cam.push_back(Z[i]*f3);\n\n    transformation_t solution = math::arun_complete(points,p_cam);\n    solutions.push_back(solution);\n  }\n}\n\nvoid\nopengv::absolute_pose::modules::gp3p_main(\n    const Eigen::Matrix3d & f,\n    const Eigen::Matrix3d & v,\n    const Eigen::Matrix3d & p,\n    transformations_t & solutions)\n{\n  Eigen::Matrix<double,48,85> groebnerMatrix =\n      Eigen::Matrix<double,48,85>::Zero();\n  gp3p::init(groebnerMatrix,f,v,p);\n  gp3p::compute(groebnerMatrix);\n\n  Eigen::Matrix<double,8,8> M = Eigen::Matrix<double,8,8>::Zero();\n  M.block<6,8>(0,0) = -groebnerMatrix.block<6,8>(36,77);\n  M(6,0) = 1.0;\n  M(7,6) = 1.0;\n\n  Eigen::ComplexEigenSolver< Eigen::Matrix<double,8,8> > Eig(M,true);\n  Eigen::Matrix<std::complex<double>,8,1> D = Eig.eigenvalues();\n  Eigen::Matrix<std::complex<double>,8,8> V = Eig.eigenvectors();\n\n  for( int c = 0; c < V.cols(); c++ )\n  {\n    std::complex<double> eigValue = D[c];\n\n    if( eigValue.imag() < 0.0001 )\n    {\n      cayley_t cayley;\n      Eigen::Vector3d n;\n\n      for(size_t i = 0; i < 3; i++)\n      {\n        std::complex<double> cay = V(i+4,c)/V(7,c);\n        cayley[2-i] = cay.real();\n        std::complex<double> depth = V(i+1,c)/V(7,c);\n        n[2-i] = depth.real();\n      }\n\n      rotation_t rotation = math::cayley2rot(cayley);\n      //the groebner problem was set up to find the transpose!\n      rotation.transposeInPlace();\n\n      point_t center_cam = Eigen::Vector3d::Zero();\n      point_t center_world = Eigen::Vector3d::Zero();\n      for( size_t i = 0; i < (size_t) f.cols(); i++ )\n      {\n        point_t temp = rotation*(n[i]*f.col(i)+v.col(i));\n        center_cam = center_cam + temp;\n        center_world = center_world + p.col(i);\n      }\n\n      center_cam = center_cam/f.cols();\n      center_world = center_world/f.cols();\n      translation_t translation = center_world - center_cam;\n\n      transformation_t transformation;\n      transformation.block<3,3>(0,0) = rotation;\n      transformation.col(3) = translation;\n      solutions.push_back(transformation);\n    }\n  }\n}\n\nvoid\nopengv::absolute_pose::modules::gpnp_main(\n    const Eigen::Matrix<double,12,1> & a,\n    const Eigen::Matrix<double,12,12> & V,\n    const points_t & c,\n    transformation_t & transformation )\n{\n  //extracting the nullspace vectors\n  Eigen::Matrix<double,12,1> vec_5 = V.col(7);\n  Eigen::Matrix<double,12,1> vec_4 = V.col(8);\n  Eigen::Matrix<double,12,1> vec_3 = V.col(9);\n  Eigen::Matrix<double,12,1> vec_2 = V.col(10);\n  Eigen::Matrix<double,12,1> vec_1 = V.col(11);\n\n  point_t c0 = c[0];\n  point_t c1 = c[0];\n  point_t c2 = c[0];\n  point_t c3 = c[0];\n\n  Eigen::Matrix<double,12,1> solution;\n  std::vector<double> errors;\n  translation_t t;\n  translations_t ts;\n  rotation_t R;\n  rotations_t Rs;\n  std::vector<double> factors;\n\n  solution = a;\n  errors.push_back(gpnp_evaluate(solution,c,t,R));\n  ts.push_back(t);\n  Rs.push_back(R);\n\n  //nice, now we just need to find the right combination\n  //let's start with trying out the linear combination of the most right\n  //null-space vector\n  Eigen::Matrix<double,5,3> groebnerMatrix1 =\n      Eigen::Matrix<double,5,3>::Zero();\n  gpnp1::init(groebnerMatrix1,a,vec_1,c0,c1,c2,c3);\n  gpnp1::compute(groebnerMatrix1);\n  factors.push_back(-groebnerMatrix1(3,2)/groebnerMatrix1(3,1));\n  gpnp_optimize( a, V, c, factors );\n  solution = a;\n  for(size_t i = 0; i < factors.size(); i++)\n    solution += factors[i]*V.col(12-factors.size()+i);\n  errors.push_back(gpnp_evaluate(solution,c,t,R));\n  ts.push_back(t);\n  Rs.push_back(R);\n\n  //now let's compute the solution using two nullspace vectors\n  Eigen::Matrix<double,10,6> groebnerMatrix2 =\n      Eigen::Matrix<double,10,6>::Zero();\n  gpnp2::init(groebnerMatrix2,a,vec_2,vec_1,c0,c1,c2,c3);\n  gpnp2::compute(groebnerMatrix2);\n  factors[0] = -groebnerMatrix2(8,5)/groebnerMatrix2(8,4);\n  factors.push_back(\n      -(groebnerMatrix2(7,4)*factors[0]+groebnerMatrix2(7,5))/\n      groebnerMatrix2(7,3));\n  gpnp_optimize( a, V, c, factors );\n  solution = a;\n  for(size_t i = 0; i < factors.size(); i++)\n    solution += factors[i]*V.col(12-factors.size()+i);\n  errors.push_back(gpnp_evaluate(solution,c,t,R));\n  ts.push_back(t);\n  Rs.push_back(R);\n\n  //now let's compute the solution using three nullspace vectors\n  Eigen::Matrix<double,15,18> groebnerMatrix3 =\n      Eigen::Matrix<double,15,18>::Zero();\n  gpnp3::init(groebnerMatrix3,a,vec_3,vec_2,vec_1,c0,c1,c2,c3);\n  gpnp3::compute(groebnerMatrix3);\n  factors[0] = -groebnerMatrix3(13,17)/groebnerMatrix3(13,16);\n  factors[1] =\n      -(groebnerMatrix3(12,16)*factors[0]+groebnerMatrix3(12,17))/\n      groebnerMatrix3(12,15);\n  factors.push_back(\n      -(groebnerMatrix3(11,15)*factors[1]+groebnerMatrix3(11,16)*factors[0]+\n      groebnerMatrix3(11,17))/groebnerMatrix3(11,14));\n  gpnp_optimize( a, V, c, factors );\n  solution = a;\n  for(size_t i = 0; i < factors.size(); i++)\n    solution += factors[i]*V.col(12-factors.size()+i);\n  errors.push_back(gpnp_evaluate(solution,c,t,R));\n  ts.push_back(t);\n  Rs.push_back(R);\n\n  //now let's compute the solution using four nullspace vectors\n  Eigen::Matrix<double,25,37> groebnerMatrix4 =\n      Eigen::Matrix<double,25,37>::Zero();\n  gpnp4::init(groebnerMatrix4,a,vec_4,vec_3,vec_2,vec_1,c0,c1,c2,c3);\n  gpnp4::compute(groebnerMatrix4);\n  factors[0] = -groebnerMatrix4(23,36)/groebnerMatrix4(23,35);\n  factors[1] =\n      -(groebnerMatrix4(22,35)*factors[0]+groebnerMatrix4(22,36))/\n      groebnerMatrix4(22,34);\n  factors[2] =\n      -(groebnerMatrix4(21,34)*factors[1]+groebnerMatrix4(21,35)*factors[0]+\n      groebnerMatrix4(21,36))/groebnerMatrix4(21,33);\n  factors.push_back(\n      -(groebnerMatrix4(20,33)*factors[2]+groebnerMatrix4(20,34)*factors[1]+\n      groebnerMatrix4(20,35)*factors[0]+groebnerMatrix4(20,36))/\n      groebnerMatrix4(20,32));\n  gpnp_optimize( a, V, c, factors );\n  solution = a;\n  for(size_t i = 0; i < factors.size(); i++)\n    solution += factors[i]*V.col(12-factors.size()+i);\n  errors.push_back(gpnp_evaluate(solution,c,t,R));\n  ts.push_back(t);\n  Rs.push_back(R);\n\n  //now let's compute the solution using five nullspace vectors\n  Eigen::Matrix<double,44,80> groebnerMatrix5 =\n      Eigen::Matrix<double,44,80>::Zero();\n  gpnp5::init(groebnerMatrix5,a,vec_5,vec_4,vec_3,vec_2,vec_1,c0,c1,c2,c3);\n  gpnp5::compute(groebnerMatrix5);\n  factors[0] = -groebnerMatrix5(42,79)/groebnerMatrix5(42,78);\n  factors[1] =\n      -(groebnerMatrix5(41,78)*factors[0]+groebnerMatrix5(41,79))/\n      groebnerMatrix5(41,77);\n  factors[2] =\n      -(groebnerMatrix5(40,77)*factors[1]+groebnerMatrix5(40,78)*factors[0]+\n      groebnerMatrix5(40,79))/groebnerMatrix5(40,76);\n  factors[3] =\n      -(groebnerMatrix5(39,76)*factors[2]+groebnerMatrix5(39,77)*factors[1]+\n      groebnerMatrix5(39,78)*factors[0]+groebnerMatrix5(39,79))/\n      groebnerMatrix5(39,75);\n  factors.push_back(\n      -(groebnerMatrix5(38,75)*factors[3]+groebnerMatrix5(38,76)*factors[1]+\n      groebnerMatrix5(38,77)*factors[1]+groebnerMatrix5(38,78)*factors[0]+\n      groebnerMatrix5(38,79))/groebnerMatrix5(38,74));\n  gpnp_optimize( a, V, c, factors );\n  solution = a;\n  for(size_t i = 0; i < factors.size(); i++)\n    solution += factors[i]*V.col(12-factors.size()+i);\n  errors.push_back(gpnp_evaluate(solution,c,t,R));\n  ts.push_back(t);\n  Rs.push_back(R);\n\n  //find best solution\n  double smallestError = errors.at(0);\n  int minimumIndex = 0;\n  for( int i = 1; i < 6; i++ )\n  {\n    if( errors.at(i) < smallestError )\n    {\n      smallestError = errors.at(i);\n      minimumIndex = i;\n    }\n  }\n\n  transformation.col(3) = ts.at(minimumIndex);\n  transformation.block<3,3>(0,0) = Rs.at(minimumIndex);\n}\n\ndouble\nopengv::absolute_pose::modules::gpnp_evaluate(\n    const Eigen::Matrix<double,12,1> & solution,\n    const points_t & c,\n    translation_t & t,\n    rotation_t & R )\n{\n  points_t ccam;\n  for(size_t i = 0; i<4; i++)\n    ccam.push_back(solution.block<3,1>(i*3,0));\n\n  transformation_t transformation = math::arun_complete(c,ccam);\n  t = transformation.col(3);\n  R = transformation.block<3,3>(0,0);\n\n  //transform world points into camera frame and compute the error\n  double error = 0.0;\n  for(size_t i = 0; i<4; i++)\n  {\n    point_t ccam_reprojected = R.transpose() * (c[i] - t);\n    error +=\n        1.0 -\n        (ccam_reprojected.dot(ccam[i])/(ccam[i].norm()*ccam_reprojected.norm()));\n  }\n\n  return error;\n}\n\nnamespace opengv\n{\nnamespace absolute_pose\n{\nnamespace modules\n{\n\nstruct GpnpOptimizationFunctor : OptimizationFunctor<double>\n{\n  const Eigen::Matrix<double,12,1> & _a;\n  const Eigen::Matrix<double,12,12> & _V;\n  const points_t & _c;\n  size_t _dim;\n\n  GpnpOptimizationFunctor(\n      const Eigen::Matrix<double,12,1> & a,\n      const Eigen::Matrix<double,12,12> & V,\n      const points_t & c,\n      size_t dim ) :\n      OptimizationFunctor<double>(dim,6),\n      _a(a),\n      _V(V),\n      _c(c),\n      _dim(dim) {}\n\n  int operator()(const VectorXd &x, VectorXd &fvec) const\n  {\n    assert( x.size() == _dim );\n    assert( (unsigned int) fvec.size() == 6);\n\n    Eigen::Matrix<double,12,1> solution = _a;\n    for(size_t i = 0; i < _dim; i++)\n      solution += x[i]*_V.col(12-_dim+i);\n\n    points_t ccam;\n    for(size_t i = 0; i<4; i++)\n      ccam.push_back(solution.block<3,1>(i*3,0));\n\n    Eigen::Vector3d diffw;\n    Eigen::Vector3d diffc;\n    size_t index = 0;\n\n    for(size_t i = 0; i<3; i++)\n    {\n      for(size_t j = i+1; j < 4; j++)\n      {\n        diffw = _c[i]-_c[j];\n        diffc = ccam[i]-ccam[j];\n        fvec[index++] = diffw.dot(diffw)-diffc.dot(diffc);\n      }\n    }\n\n    return 0;\n  }\n};\n\n}\n}\n}\n\nvoid\nopengv::absolute_pose::modules::gpnp_optimize(\n    const Eigen::Matrix<double,12,1> & a,\n    const Eigen::Matrix<double,12,12> & V,\n    const points_t & c,\n    std::vector<double> & factors )\n{\n  const int n=factors.size();\n  VectorXd x(n);\n\n  for(size_t i = 0; i < factors.size(); i++)\n    x[i] = factors[i];\n\n  GpnpOptimizationFunctor functor( a, V, c, factors.size() );\n  NumericalDiff<GpnpOptimizationFunctor> numDiff(functor);\n  LevenbergMarquardt< NumericalDiff<GpnpOptimizationFunctor> > lm(numDiff);\n\n  lm.resetParameters();\n  lm.parameters.ftol = 1.E10*NumTraits<double>::epsilon();\n  lm.parameters.xtol = 1.E10*NumTraits<double>::epsilon();\n  lm.parameters.maxfev = 1000;\n  lm.minimize(x);\n\n  for(size_t i = 0; i < factors.size(); i++)\n    factors[i] = x[i];\n}\n\nvoid\nopengv::absolute_pose::modules::upnp_fill_s(\n    const Eigen::Vector4d & quaternion,\n    Eigen::Matrix<double,10,1> & s )\n{\n  s[0] = quaternion[0] * quaternion[0];\n  s[1] = quaternion[1] * quaternion[1];\n  s[2] = quaternion[2] * quaternion[2];\n  s[3] = quaternion[3] * quaternion[3];\n  s[4] = quaternion[0] * quaternion[1];\n  s[5] = quaternion[0] * quaternion[2];\n  s[6] = quaternion[0] * quaternion[3];\n  s[7] = quaternion[1] * quaternion[2];\n  s[8] = quaternion[1] * quaternion[3];\n  s[9] = quaternion[2] * quaternion[3];\n}\n\n//we use this one if the number of correspondences is pretty low (more robust)\nvoid\nopengv::absolute_pose::modules::upnp_main(\n    const Eigen::Matrix<double,10,10> & M,\n    const Eigen::Matrix<double,1,10> & C,\n    double gamma,\n    std::vector<std::pair<double,Eigen::Vector4d>,Eigen::aligned_allocator< std::pair<double,Eigen::Vector4d> > > & quaternions )\n{\n  Eigen::Matrix<double,16,16> Action;\n  upnp::setupAction_gj( M, C, gamma, Action );\n  Eigen::ComplexEigenSolver< Eigen::Matrix<double,16,16> > Eig( Action, true );\n  Eigen::Matrix<std::complex<double>,16,16> V = Eig.eigenvectors();\n  \n  //cut the double solutions\n  double doubleSolThreshold = 0.00000001;\n  \n  for( int i = 0; i < 16; i++ )\n  {\n    //we decided to drop the test for imaginary part\n    //I've noticed that when the number of points is really low, things get a little\n    //weary with noise, and complex solutions might actually be pretty good\n    \n    Eigen::Vector4d quaternion;\n    double norm = 0.0;\n    for( int q = 0; q < 4; q++ )\n    {\n      quaternion[q] = V(11+q,i).real();\n      norm += pow(quaternion[q],2.0);\n    }\n    norm = sqrt(norm);\n    if(quaternion[0] < 0) // this here is maybe risky, what if quaternion[0] is very small\n      norm *= -1.0;\n    for( int q = 0; q < 4; q++ )\n      quaternion[q] /= norm;\n    \n    bool alreadyThere = false;\n    for( size_t s = 0; s < quaternions.size(); s++ )\n    {\n      Eigen::Vector4d diff = quaternion - quaternions[s].second;\n      if( diff.norm() < doubleSolThreshold )\n      {\n        alreadyThere = true;\n        break;\n      }\n    }\n    \n    if( !alreadyThere )\n    {\n      Eigen::Matrix<double,10,1> s;\n      upnp_fill_s(quaternion,s);\n      Eigen::Matrix<double,1,1> valueM = s.transpose() * M * s + 2.0 * C * s;\n      double value = valueM[0] + gamma;\n      \n      std::vector<std::pair<double,Eigen::Vector4d>,Eigen::aligned_allocator< std::pair<double,Eigen::Vector4d> > >::iterator\n          qidx = quaternions.begin();\n      while( qidx != quaternions.end() && qidx->first < value )\n        qidx++;\n      \n      quaternions.insert(qidx,std::pair<double,Eigen::Vector4d>(value,quaternion));\n    }\n  }\n}\n\n//this one is the really fast, symmetric version, that we use in the normal case\nvoid\nopengv::absolute_pose::modules::upnp_main_sym(\n    const Eigen::Matrix<double,10,10> & M,\n    const Eigen::Matrix<double,1,10> & C,\n    double gamma,\n    std::vector<std::pair<double,Eigen::Vector4d>,Eigen::aligned_allocator< std::pair<double,Eigen::Vector4d> > > & quaternions )\n{\n  Eigen::Matrix<double,8,8> Action;\n  upnp::setupAction_sym_gj( M, C, gamma, Action );\n  Eigen::ComplexEigenSolver< Eigen::Matrix<double,8,8> > Eig( Action, true );\n  Eigen::Matrix<std::complex<double>,8,8> V = Eig.eigenvectors();\n  \n  //ok, let's cut the imaginary solutions (with a reasonable threshold!)\n  double imagThreshold = 0.01;\n  std::vector<std::pair<double,Eigen::Vector4d>,Eigen::aligned_allocator< std::pair<double,Eigen::Vector4d> > > bad_quaternions;\n  \n  Eigen::Matrix<std::complex<double>,8,1> D = Eig.eigenvalues();\n  for( int i = 0; i < 8; i++ )\n  {\n    Eigen::Vector4d quaternion;\n    quaternion[3] = V(7,i).real();\n    quaternion[2] = V(6,i).real();\n    quaternion[1] = V(5,i).real();\n    quaternion[0] = V(4,i).real();\n    \n    double norm = 0.0;\n    for( int q = 0; q < 4; q++ )\n      norm += pow(quaternion[q],2.0);\n    norm = sqrt(norm);\n    for( int q = 0; q < 4; q++ )\n      quaternion[q] /= norm;\n    \n    Eigen::Matrix<double,10,1> s;\n    upnp_fill_s(quaternion,s);\n    Eigen::Matrix<double,1,1> valueM = s.transpose() * M * s + 2.0 * C * s;\n    double value = valueM[0] + gamma;\n\n    if( true )//fabs(D[i].imag()) < imagThreshold ) //use all results for the moment\n    {\n      std::vector<std::pair<double,Eigen::Vector4d>,Eigen::aligned_allocator< std::pair<double,Eigen::Vector4d> > >::iterator\n          qidx = quaternions.begin();\n      while( qidx != quaternions.end() && qidx->first < value )\n        qidx++;\n      \n      quaternions.insert(qidx,std::pair<double,Eigen::Vector4d>(value,quaternion));\n    }\n    else\n    {\n      std::vector<std::pair<double,Eigen::Vector4d>,Eigen::aligned_allocator< std::pair<double,Eigen::Vector4d> > >::iterator\n          qidx = bad_quaternions.begin();\n      while( qidx != bad_quaternions.end() && qidx->first < value )\n        qidx++;\n      \n      bad_quaternions.insert(qidx,std::pair<double,Eigen::Vector4d>(value,quaternion));\n    }\n  }\n  if( quaternions.size() == 0 )\n    quaternions = bad_quaternions;\n}\n", "meta": {"hexsha": "0597c087479344f58af4d9a3f7aebbcdd2b106f6", "size": 26806, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/absolute_pose/modules/main.cpp", "max_stars_repo_name": "baritone/opengv", "max_stars_repo_head_hexsha": "2148bd9d74fc84f667302a1619116fa10c4b3935", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-31T17:22:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-31T17:22:23.000Z", "max_issues_repo_path": "src/absolute_pose/modules/main.cpp", "max_issues_repo_name": "baritone/opengv", "max_issues_repo_head_hexsha": "2148bd9d74fc84f667302a1619116fa10c4b3935", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/absolute_pose/modules/main.cpp", "max_forks_repo_name": "baritone/opengv", "max_forks_repo_head_hexsha": "2148bd9d74fc84f667302a1619116fa10c4b3935", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-09T09:03:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T15:08:41.000Z", "avg_line_length": 31.6855791962, "max_line_length": 129, "alphanum_fraction": 0.6034469895, "num_tokens": 9320, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.40688651096731504}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_DIVCEIL_HPP_INCLUDED\n#define BOOST_SIMD_TOOLBOX_ARITHMETIC_FUNCTIONS_SIMD_COMMON_DIVCEIL_HPP_INCLUDED\n\n#include <boost/simd/toolbox/arithmetic/functions/divceil.hpp>\n#include <boost/simd/include/functions/simd/group.hpp>\n#include <boost/simd/include/functions/simd/split.hpp>\n#include <boost/simd/include/functions/simd/ceil.hpp>\n#include <boost/simd/include/functions/simd/tofloat.hpp>\n#include <boost/simd/include/functions/simd/divs.hpp>\n#include <boost/simd/include/functions/simd/bitwise_cast.hpp>\n#include <boost/simd/include/functions/simd/divides.hpp>\n#include <boost/simd/include/constants/one.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divceil_, tag::cpu_, (A0)(X)\n                            , ((simd_<arithmetic_<A0>,X>))\n                              ((simd_<arithmetic_<A0>,X>))\n                            )\n  {\n    typedef typename dispatch::meta::as_floating<A0>::type result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return ceil(tofloat(a0)/tofloat(a1)); }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divceil_, tag::cpu_, (A0)(X)\n                            , ((simd_<unsigned_<A0>,X>))\n                              ((simd_<unsigned_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return rdivide(a0+a1-One<A0>(), a1); }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divceil_, tag::cpu_, (A0)(X)\n                            , ((simd_<int16_<A0>,X>))\n                              ((simd_<int16_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename meta::scalar_of<A0>::type           stype;\n      typedef typename dispatch::meta::upgrade<stype>::type          itype;\n      typedef simd::native<itype,X>                       ivtype;\n      ivtype a0l, a0h, a1l, a1h;\n      boost::fusion::tie(a0l, a0h) = split(a0);\n      boost::fusion::tie(a1l, a1h) = split(a1);\n      return bitwise_cast<A0>(group(divceil(a0l, a1l),divceil(a0h, a1h)));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divceil_, tag::cpu_, (A0)(X)\n                            , ((simd_<int8_<A0>,X>))\n                              ((simd_<int8_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)\n    {\n      typedef typename meta::scalar_of<A0>::type           stype;\n      typedef typename dispatch::meta::upgrade<stype>::type          itype;\n      typedef simd::native<itype, X>                      ivtype;\n      ivtype a0l, a0h, a1l, a1h;\n      boost::fusion::tie(a0l, a0h) = split(a0);\n      boost::fusion::tie(a1l, a1h) = split(a1);\n      return simd::bitwise_cast<A0>(group(divceil(a0l, a1l),divceil(a0h, a1h) ));\n    }\n  };\n\n  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::divceil_, tag::cpu_, (A0)(X)\n                            , ((simd_<floating_<A0>,X>))\n                              ((simd_<floating_<A0>,X>))\n                            )\n  {\n    typedef A0 result_type;\n    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2) { return ceil(a0/a1); }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "89e871df9dbe77332562028d95342a5d651ba3f3", "size": 3755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/divceil.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/divceil.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/arithmetic/include/boost/simd/toolbox/arithmetic/functions/simd/common/divceil.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2637362637, "max_line_length": 83, "alphanum_fraction": 0.5664447403, "num_tokens": 983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.40688651096731493}}
{"text": "/*--\r\n  Open3DMotion \r\n  Copyright (c) 2004-2013.\r\n  All rights reserved.\r\n  See LICENSE.txt for more information.\r\n--*/\r\n\r\n#include \"Open3DMotion/Biomechanics/Algorithms/MOSHFIT/RigidBodyShape.h\"\r\n\r\n#ifndef OPEN3DMOTION_LINEAR_ALGEBRA_EIGEN\r\nextern \"C\"\r\n{\r\n#include <f2clibs/f2c.h>\r\n#include <clapack.h>\r\n}\r\n#else\r\n#include <Eigen/Dense>\r\n#include <Eigen/SVD>\r\n#endif\r\n\r\nnamespace Open3DMotion\r\n{  \r\n  const UInt32 RigidBodyResult::success = 0;\r\n  const UInt32 RigidBodyResult::timesequence_mismatch = 1;\r\n  const UInt32 RigidBodyResult::visibility_disconnected = 2;\r\n  const UInt32 RigidBodyResult::insufficient_points = 3;\r\n  const UInt32 RigidBodyResult::did_not_converge = 4;\r\n  \r\n\tRigidBodyShape::RigidBodyShape()\r\n\t{\r\n\t}\r\n\t\t\r\n\tRigidBodyShape::RigidBodyShape(const RigidBodyShape& src)\r\n\t{\r\n\t\t*this = src;\r\n\t}\r\n\r\n\tconst RigidBodyShape& RigidBodyShape::operator=(const RigidBodyShape& src)\r\n\t{\r\n\t\tmarker.assign( src.marker.begin(), src.marker.end() );\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tRigidBodyShape::~RigidBodyShape()\r\n\t{\r\n\t}\r\n\r\n\tvoid RigidBodyShape::AddMarker(const double* position, bool visible)\r\n\t{\r\n\t\tmarker.resize(NumMarkers()+1);\r\n\t\tmarker.back().position = position;\r\n\t\tmarker.back().visible = visible ? 1 : 0;\r\n\t}\r\n\r\n\tbool RigidBodyShape::IsVisibilitySupersetOf(const RigidBodyShape& other) const\r\n\t{\r\n\t\tif (marker.size() == other.marker.size())\r\n\t\t{\r\n\t\t\tfor (std::vector<RigidBodyMarker>::const_iterator iter_this( marker.begin() ), iter_other( other.marker.begin() );\r\n\t\t\t\t\t iter_this != marker.end(); iter_this++, iter_other++)\r\n\t\t\t{\r\n\t\t\t\tif (iter_other->visible && !iter_this->visible)\r\n\t\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\tbool RigidBodyShape::IsVisibilitySubsetOf(const RigidBodyShape& other) const\r\n\t{\r\n\t\tif (marker.size() == other.marker.size())\r\n\t\t{\r\n\t\t\tfor (std::vector<RigidBodyMarker>::const_iterator iter_this( marker.begin() ), iter_other( other.marker.begin() );\r\n\t\t\t\t\t iter_this != marker.end(); iter_this++, iter_other++)\r\n\t\t\t{\r\n\t\t\t\tif (iter_this->visible && !iter_other->visible)\r\n\t\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\tsize_t RigidBodyShape::NumberOfVisibleMarkersInCommonWith(const RigidBodyShape& other) const\r\n\t{\r\n\t\tsize_t count = 0;\r\n\t\tif (marker.size() == other.marker.size())\r\n\t\t{\r\n\t\t\tfor (std::vector<RigidBodyMarker>::const_iterator iter_this( marker.begin() ), iter_other( other.marker.begin() );\r\n\t\t\t\t\t iter_this != marker.end(); iter_this++, iter_other++)\r\n\t\t\t{\r\n\t\t\t\tif (iter_this->visible && iter_other->visible)\r\n\t\t\t\t\t++count;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn count;\r\n\t}\r\n\r\n\tvoid RigidBodyShape::EvaluateNonsingularity3D(std::vector<double>& s, std::vector<double>& coords)\r\n\t{\r\n\t\tlong num_points(coords.size() / 3);\r\n    s.resize(3);\r\n    \r\n#ifndef OPEN3DMOTION_LINEAR_ALGEBRA_EIGEN\r\n    long three(3);\r\n\t\tlong lwork(256);\r\n\t\tdouble work[256];\r\n\t\tlong info(0);\r\n\t\t\t\t\r\n\t\tstd::vector<double> U(9);\r\n\t\tstd::vector<double> VT(num_points*num_points);\r\n\r\n\t\t// use lapack routine\r\n\t\t// note coords must be column-major so first 3 elements correspond to first coord\r\n\t\tdgesvd_(\r\n\t\t\t\"N\",  // don't actually need U\r\n\t\t\t\"N\",  // don't actually need VT\r\n\t\t\t&three, // rows\r\n\t\t\t&num_points,      // cols\r\n\t\t\t&coords[0],   // input/output matrix\r\n\t\t\t&three, // leading dimension of Acpy\r\n\t\t\t&s[0],      // singular values\r\n\t\t\t&U[0],      // left orthonormal matrix\r\n\t\t\t&three, // leading dimension of left\r\n\t\t\t&VT[0],      // right orthonormal matrix\r\n\t\t\t&num_points, // leading dimension of right \r\n\t\t\twork,   // workspace\r\n\t\t\t&lwork, // size of workspace\r\n\t\t\t&info);   // returned error codes\r\n#else    \r\n\t\tEigen::Map< Eigen::Matrix<double, Eigen::Dynamic, 3, Eigen::RowMajor> >\r\n      _coords(&coords[0], (int)num_points, 3);\r\n    Eigen::Map< Eigen::Matrix<double, 3, 1> > _s(&s[0], 3, 1);\r\n    Eigen::JacobiSVD< Eigen::Matrix<double, Eigen::Dynamic, 3, Eigen::RowMajor> > svd(_coords);\r\n    _s = svd.singularValues();\r\n#endif // OPEN3DMOTION_LINEAR_ALGEBRA_EIGEN\r\n\t}\r\n\r\n  \r\n\tbool RigidBodyShape::HasUniqueFitWith(const RigidBodyShape& other, double tolerance) const\r\n\t{\r\n\t\tif (marker.size() == other.marker.size())\r\n\t\t{\r\n\t\t\tsize_t num_in_common(0);\r\n\t\t\tVector3 common_centroid(0.0);\r\n\t\t\tstd::vector<double> common_coords;\r\n\t\t\tcommon_coords.reserve(3*NumMarkers());\r\n\t\t\tfor (std::vector<RigidBodyMarker>::const_iterator iter_this( marker.begin() ), iter_other( other.marker.begin() );\r\n\t\t\t\t\t iter_this != marker.end(); iter_this++, iter_other++)\r\n\t\t\t{\r\n\t\t\t\tif (iter_this->visible && iter_other->visible)\r\n\t\t\t\t{\r\n\t\t\t\t\tconst Vector3& x = iter_this->position;\r\n\t\t\t\t\tfor (size_t j = 0; j < 3; j++)\r\n\t\t\t\t\t\tcommon_coords.push_back(x[j]);\r\n\t\t\t\t\tnum_in_common++;\r\n\t\t\t\t\tcommon_centroid += x;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (num_in_common >= 3)\r\n\t\t\t{\r\n\t\t\t\t// subract centroid\r\n\t\t\t\tcommon_centroid /= num_in_common;\r\n\t\t\t\tdouble* x = &common_coords[0];\r\n\t\t\t\tfor (size_t j = 0; j < num_in_common; j++, x+=3)\r\n\t\t\t\t{\r\n\t\t\t\t\tVector3::Sub(x, x, common_centroid);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// find singular values to estimate how non-colinear these points are\r\n\t\t\t\tstd::vector<double> s;\r\n\t\t\t\tRigidBodyShape::EvaluateNonsingularity3D(s, common_coords);\r\n\r\n\t\t\t\t// Simplified expression to test points sufficiently non-colinear\r\n\t\t\t\t// (condition is sufficient but not always necessary)\r\n\t\t\t\tdouble min_colinearity_allowed = 3.56*sqrt((double)num_in_common)*tolerance;\r\n\t\t\t\tif (s[1] > min_colinearity_allowed)\r\n\t\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn false;\r\n\t}\r\n\r\n\tUInt32 RigidBodyShape::ComputeFitTo(RigidTransform3& T, const RigidBodyShape& base) const\r\n\t{\r\n\t\tsize_t num_points = NumMarkers();\r\n\t\tif (num_points == base.NumMarkers())\r\n\t\t{\r\n\t\t\t// get centroids\r\n\t\t\tVector3 centroidA(0,0,0);\r\n\t\t\tVector3 centroidB(0,0,0);\r\n\t\t\tconst RigidBodyMarker* iter_A = &base.marker[0];\r\n\t\t\tconst RigidBodyMarker* iter_B = &marker[0];\r\n\t\t\tsize_t ipoint(0);\r\n\t\t\tsize_t num_in_common(0);\r\n\t\t\tfor (ipoint = 0; ipoint < num_points; ipoint++, iter_A++,iter_B++)\r\n\t\t\t{\r\n\t\t\t\tif (iter_A->visible && iter_B->visible)\r\n\t\t\t\t{\r\n\t\t\t\t\tVector3::Add(centroidA.x, centroidA.x, iter_A->position);\r\n\t\t\t\t\tVector3::Add(centroidB.x, centroidB.x, iter_B->position);\r\n\t\t\t\t\t++num_in_common;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (num_in_common >= 3)\r\n\t\t\t{\r\n\t\t\t\t// normalise\r\n\t\t\t\tcentroidA /= num_in_common;\r\n\t\t\t\tcentroidB /= num_in_common;\r\n\r\n\t\t\t\t// correlation matrix\r\n\t\t\t\tdouble sum_correl[9] =\r\n\t\t\t\t{ 0.0, 0.0, 0.0,\r\n\t\t\t\t\t0.0, 0.0, 0.0,\r\n\t\t\t\t\t0.0, 0.0, 0.0 \r\n\t\t\t\t};\r\n\r\n\t\t\t\t// find correlation matrix\r\n\t\t\t\titer_A = &base.marker[0];\r\n\t\t\t\titer_B = &marker[0];\r\n\t\t\t\tfor (ipoint = 0; ipoint < num_points; ipoint++, iter_A++, iter_B++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (iter_A->visible && iter_B->visible)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t// input minus centroid\r\n\t\t\t\t\t\tVector3 normA;\r\n\t\t\t\t\t\tVector3::Sub(normA, iter_A->position, centroidA);\r\n\r\n\t\t\t\t\t\t// cal minus centroid\r\n\t\t\t\t\t\tVector3 normB;\r\n\t\t\t\t\t\tVector3::Sub(normB, iter_B->position, centroidB);\r\n\r\n\t\t\t\t\t\t// correlation (outer product)\r\n\t\t\t\t\t\tfor (int i = 0; i < 3; i++)\r\n\t\t\t\t\t\t\tfor (int j = 0; j < 3; j++)\r\n\t\t\t\t\t\t\tsum_correl[3*i+j] += normA[i]*normB[j];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// SVD of correlation to get rotation\r\n\t\t\t\t// from mean coords to this frame\r\n\t\t\t\tdouble s[3];\r\n\t\t\t\tdouble U[9], VT[9];\r\n\t\t\t\tMatrix3x3::SVD(U, s, VT, sum_correl);\r\n\r\n\t\t\t\t// force right-handed coord system\r\n\t\t\t\tdouble detU = Matrix3x3::Det(U);\r\n\t\t\t\tdouble detV = Matrix3x3::Det(VT);\r\n\t\t\t\tif (detU*detV < 0.0)\r\n\t\t\t\t{\r\n\t\t\t\t\tVT[6] *= -1.0;\r\n\t\t\t\t\tVT[7] *= -1.0;\r\n\t\t\t\t\tVT[8] *= -1.0;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// this is the correct way round\r\n\t\t\t\tMatrix3x3::Mul(T.R, U, VT);\r\n\r\n\t\t\t\t// do post-subtraction of centroid B to get translation vector\r\n\t\t\t\tdouble RcentroidB[3];\r\n\t\t\t\tMatrix3x3::MulVec(RcentroidB, T.R, centroidB);\r\n\t\t\t\tVector3::Sub(T.t, centroidA, RcentroidB);\r\n\r\n\t\t#if 0\r\n\t\t\t\titer_A = ptA;\r\n\t\t\t\titer_B = ptB;\r\n\t\t\t\tfor (ipoint = 0; ipoint < npoints; ipoint++, iter_A+=3, iter_B+=3)\r\n\t\t\t\t{\r\n\t\t\t\t\tVector3 Tb;\r\n\t\t\t\t\tRigidTransform3::MulVec(Tb, R, t, iter_B);\r\n\t\t\t\t\tcerr << \"x: \" << iter_A[0] << \" \" << Tb[0] << endl;\r\n\t\t\t\t\tcerr << \"y: \" << iter_A[1] << \" \" << Tb[1] << endl;\r\n\t\t\t\t\tcerr << \"z: \" << iter_A[2] << \" \" << Tb[2] << endl;\r\n\t\t\t\t\tVector3::Sub(Tb, Tb, iter_A);\r\n\t\t\t\t\tcerr << \"Mod: \" << Tb.Modulus() << endl;\r\n\t\t\t\t}\r\n\t\t#endif\r\n\r\n\t\t\t\treturn RigidBodyResult::success;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn RigidBodyResult::insufficient_points;\r\n\t}\r\n\r\n}\r\n", "meta": {"hexsha": "72541fb99ba48c95271090c04a58ec6cd9825244", "size": 8259, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Utilities/Open3DMotion/src/Open3DMotion/Biomechanics/Algorithms/MOSHFIT/RigidBodyShape.cpp", "max_stars_repo_name": "mitkof6/BTKCore", "max_stars_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_stars_repo_licenses": ["Barr", "Unlicense"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-04-21T20:40:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:35:03.000Z", "max_issues_repo_path": "Utilities/Open3DMotion/src/Open3DMotion/Biomechanics/Algorithms/MOSHFIT/RigidBodyShape.cpp", "max_issues_repo_name": "mitkof6/BTKCore", "max_issues_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_issues_repo_licenses": ["Barr", "Unlicense"], "max_issues_count": 40.0, "max_issues_repo_issues_event_min_datetime": "2018-03-11T15:14:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T18:13:48.000Z", "max_forks_repo_path": "Utilities/Open3DMotion/src/Open3DMotion/Biomechanics/Algorithms/MOSHFIT/RigidBodyShape.cpp", "max_forks_repo_name": "mitkof6/BTKCore", "max_forks_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_forks_repo_licenses": ["Barr", "Unlicense"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2015-05-11T11:04:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T20:37:04.000Z", "avg_line_length": 27.8080808081, "max_line_length": 118, "alphanum_fraction": 0.6158130524, "num_tokens": 2477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4068865050234334}}
{"text": "#pragma once\n\n#if defined(_OPENMP)\n#include <omp.h>\n#endif\n\n#include <cmath>\n#include <cstdint>\n#include <functional>\n#include <limits>\n#include <iostream>\n#include <stdexcept>\n#include <utility>\n#include <vector>\n\n#include <Eigen/Geometry>\n#include <common_robotics_utilities/math.hpp>\n#include <common_robotics_utilities/openmp_helpers.hpp>\n\nnamespace common_robotics_utilities\n{\n/// Implementation of hierarchical clustering, in both Single-link and\n/// Complete-link forms. Unlike some implementations, this does not produce the\n/// dendrogram of clusters - it only returns the accumulated clusters up to the\n/// provided cluster distance bound. In complete-link clustering, the maximum\n/// point-to-point distance in any cluster must be <= distance bound, and\n/// clustering is performed by combining two items (each could be a point or an\n/// existing cluster) if the maximum distance is less than distance bound.\n/// Single-link clustering is produced by combining two items (each could be a\n/// point or an existing cluster) if the minimum distance is less than distance\n/// bound.\n/// Complete-link clustering produces dense clusters, while single-link\n/// clustering produces long \"thin\" clusters.\nnamespace simple_hierarchical_clustering\n{\nenum class ClusterStrategy { SINGLE_LINK, COMPLETE_LINK };\n\n/// Storage for a single \"item\" - either an index to a single value or an index\n/// to an existing cluster.\nclass Item\n{\nprivate:\n  int64_t index_ = -1;\n  bool is_cluster_ = false;\n\npublic:\n  Item() : index_(-1), is_cluster_(false) {}\n\n  Item(const int64_t index, const bool is_cluster)\n      : index_(index), is_cluster_(is_cluster)\n  {\n    if (index_ < 0)\n    {\n      throw std::invalid_argument(\"index < 0\");\n    }\n  }\n\n  int64_t Index() const { return index_; }\n\n  bool IsValue() const { return !is_cluster_; }\n\n  bool IsCluster() const { return is_cluster_; }\n\n  bool IsValid() const { return (index_ >= 0); }\n};\n\n/// Storage for a pair of \"items\" and the distance between them\nclass ClosestPair\n{\nprivate:\n  Item first_item_;\n  Item second_item_;\n  double distance_ = std::numeric_limits<double>::infinity();\n\npublic:\n  ClosestPair() : distance_(std::numeric_limits<double>::infinity()) {}\n\n  ClosestPair(const Item& first_item, const Item& second_item,\n              const double distance)\n      : first_item_(first_item), second_item_(second_item), distance_(distance)\n  {\n    if (distance < 0.0)\n    {\n      throw std::invalid_argument(\"distance < 0.0\");\n    }\n    if (!first_item_.IsValid())\n    {\n      throw std::invalid_argument(\"first_item is not valid\");\n    }\n    if (!second_item_.IsValid())\n    {\n      throw std::invalid_argument(\"second_item is not valid\");\n    }\n    if (first_item_.IsValue() == second_item_.IsValue())\n    {\n      if (first_item_.Index() == second_item_.Index())\n      {\n        throw std::invalid_argument(\"first and second items are the same\");\n      }\n    }\n  }\n\n  const Item& FirstItem() const { return first_item_; }\n\n  const Item& SecondItem() const { return second_item_; }\n\n  double Distance() const { return distance_; }\n\n  bool IsValid() const\n  {\n    return first_item_.IsValid() && second_item_.IsValid();\n  }\n};\n\n/// Find the closest existing clusters in @param clusters, using the pairwise\n/// element-to-element distances in @param distance_matrix and the strategy\n/// specified by @param strategy. @return closest pair of clusters.\n/// Search is performed in parallel.\ninline ClosestPair GetClosestClustersParallel(\n    const Eigen::MatrixXd& distance_matrix,\n    const std::vector<std::vector<int64_t>>& clusters,\n    const ClusterStrategy strategy)\n{\n  std::vector<ClosestPair> per_thread_closest_clusters(\n      openmp_helpers::GetNumOmpThreads(), ClosestPair());\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n  for (size_t first_cluster_idx = 0; first_cluster_idx < clusters.size();\n       first_cluster_idx++)\n  {\n    // Skip empty clusters\n    const std::vector<int64_t>& first_cluster = clusters.at(first_cluster_idx);\n    if (first_cluster.size() > 0)\n    {\n      // Only compare against remaining clusters\n      for (size_t second_cluster_idx = first_cluster_idx + 1;\n           second_cluster_idx < clusters.size();\n           second_cluster_idx++)\n      {\n        // Skip empty clusters\n        const std::vector<int64_t>& second_cluster\n            = clusters.at(second_cluster_idx);\n        if (second_cluster.size() > 0)\n        {\n          // Compute cluster-cluster distance\n          double minimum_distance = std::numeric_limits<double>::infinity();\n          double maximum_distance = 0.0;\n          for (const int64_t& cluster1_index : first_cluster)\n          {\n            for (const int64_t& cluster2_index : second_cluster)\n            {\n              const double distance\n                  = distance_matrix(cluster1_index, cluster2_index);\n              minimum_distance = std::min(minimum_distance, distance);\n              maximum_distance = std::max(maximum_distance, distance);\n            }\n          }\n          const double cluster_distance\n              = (strategy == ClusterStrategy::COMPLETE_LINK) ? maximum_distance\n                                                             : minimum_distance;\n          const int32_t thread_num = openmp_helpers::GetContextOmpThreadNum();\n          const double current_closest_distance\n              = per_thread_closest_clusters.at(thread_num).Distance();\n          if (cluster_distance < current_closest_distance)\n          {\n            per_thread_closest_clusters.at(thread_num)\n                = ClosestPair(Item(first_cluster_idx, true),\n                              Item(second_cluster_idx, true),\n                              cluster_distance);\n          }\n        }\n      }\n    }\n  }\n  ClosestPair closest_clusters;\n  for (const ClosestPair& per_thread_closest_cluster_pair\n       : per_thread_closest_clusters)\n  {\n    if (per_thread_closest_cluster_pair.Distance()\n        < closest_clusters.Distance())\n    {\n      closest_clusters = per_thread_closest_cluster_pair;\n    }\n  }\n  return closest_clusters;\n}\n\n/// Find the closest existing clusters in @param clusters, using the pairwise\n/// element-to-element distances in @param distance_matrix and the strategy\n/// specified by @param strategy. @return closest pair of clusters.\ninline ClosestPair GetClosestClustersSerial(\n    const Eigen::MatrixXd& distance_matrix,\n    const std::vector<std::vector<int64_t>>& clusters,\n    const ClusterStrategy strategy)\n{\n  ClosestPair closest_clusters;\n  for (size_t first_cluster_idx = 0; first_cluster_idx < clusters.size();\n       first_cluster_idx++)\n  {\n    // Skip empty clusters\n    const std::vector<int64_t>& first_cluster = clusters.at(first_cluster_idx);\n    if (first_cluster.size() > 0)\n    {\n      // Only compare against remaining clusters\n      for (size_t second_cluster_idx = first_cluster_idx + 1;\n           second_cluster_idx < clusters.size();\n           second_cluster_idx++)\n      {\n        // Skip empty clusters\n        const std::vector<int64_t>& second_cluster\n            = clusters.at(second_cluster_idx);\n        if (second_cluster.size() > 0)\n        {\n          // Compute cluster-cluster distance\n          double minimum_distance = std::numeric_limits<double>::infinity();\n          double maximum_distance = 0.0;\n          for (const int64_t& cluster1_index : first_cluster)\n          {\n            for (const int64_t& cluster2_index : second_cluster)\n            {\n              const double distance\n                  = distance_matrix(cluster1_index, cluster2_index);\n              minimum_distance = std::min(minimum_distance, distance);\n              maximum_distance = std::max(maximum_distance, distance);\n            }\n          }\n          const double cluster_distance\n              = (strategy == ClusterStrategy::COMPLETE_LINK) ? maximum_distance\n                                                             : minimum_distance;\n          if (cluster_distance < closest_clusters.Distance())\n          {\n            closest_clusters = ClosestPair(Item(first_cluster_idx, true),\n                                           Item(second_cluster_idx, true),\n                                           cluster_distance);\n          }\n        }\n      }\n    }\n  }\n  return closest_clusters;\n}\n\n/// Find the closest existing clusters in @param clusters, using the pairwise\n/// element-to-element distances in @param distance_matrix and the strategy\n/// specified by @param strategy. @return closest pair of clusters.\n/// @param use_parallel selects if the search should be performed in parallel.\ninline ClosestPair GetClosestClusters(\n    const Eigen::MatrixXd& distance_matrix,\n    const std::vector<std::vector<int64_t>>& clusters,\n    const ClusterStrategy strategy,\n    const bool use_parallel)\n{\n  if (use_parallel)\n  {\n    return GetClosestClustersParallel(distance_matrix, clusters, strategy);\n  }\n  else\n  {\n    return GetClosestClustersSerial(distance_matrix, clusters, strategy);\n  }\n}\n\n/// Find the closest value-{value, cluster} pair, using @param datapoint_mask to\n/// ignore values that have already been clustered, @param distance_matrix to\n/// provide pairwise value-to-value distances, existing clusters provided by\n/// @param clusters, and strategy specified by @param strategy.\n/// Search is performed in parallel. @return closest pair.\ninline ClosestPair GetClosestValueToOtherParallel(\n    const std::vector<uint8_t>& datapoint_mask,\n    const Eigen::MatrixXd& distance_matrix,\n    const std::vector<std::vector<int64_t>>& clusters,\n    const ClusterStrategy strategy)\n{\n  std::vector<ClosestPair> per_thread_closest_value_other(\n      openmp_helpers::GetNumOmpThreads(), ClosestPair());\n#if defined(_OPENMP)\n#pragma omp parallel for\n#endif\n  for (size_t value_idx = 0; value_idx < datapoint_mask.size(); value_idx++)\n  {\n    // Make sure we're not already clustered\n    if (datapoint_mask.at(value_idx) == 0x00)\n    {\n      const int32_t thread_num = openmp_helpers::GetContextOmpThreadNum();\n      // Check against other values\n      for (size_t other_value_idx = value_idx + 1;\n           other_value_idx < datapoint_mask.size(); other_value_idx++)\n      {\n        // Make sure it's not already clustered\n        if (datapoint_mask.at(other_value_idx) == 0x00)\n        {\n          const double distance = distance_matrix(value_idx, other_value_idx);\n          const double current_closest_distance\n              = per_thread_closest_value_other.at(thread_num).Distance();\n          if (distance < current_closest_distance)\n          {\n            per_thread_closest_value_other.at(thread_num)\n                = ClosestPair(Item(value_idx, false),\n                              Item(other_value_idx, false),\n                              distance);\n          }\n        }\n      }\n      // Check against clusters\n      for (size_t cluster_idx = 0; cluster_idx < clusters.size(); cluster_idx++)\n      {\n        const std::vector<int64_t>& cluster = clusters.at(cluster_idx);\n        // Skip empty clusters\n        if (cluster.size() > 0)\n        {\n          // Compute cluster-cluster distance\n          double minimum_distance = std::numeric_limits<double>::infinity();\n          double maximum_distance = 0.0;\n          for (const int64_t& cluster_element_idx : cluster)\n          {\n            const double distance\n                = distance_matrix(value_idx, cluster_element_idx);\n            minimum_distance = std::min(minimum_distance, distance);\n            maximum_distance = std::max(maximum_distance, distance);\n          }\n          const double cluster_distance\n              = (strategy == ClusterStrategy::COMPLETE_LINK) ? maximum_distance\n                                                             : minimum_distance;\n          const double current_closest_distance\n              = per_thread_closest_value_other.at(thread_num).Distance();\n          if (cluster_distance < current_closest_distance)\n          {\n            per_thread_closest_value_other.at(thread_num)\n                = ClosestPair(Item(value_idx, false),\n                              Item(cluster_idx, true),\n                              cluster_distance);\n          }\n        }\n      }\n    }\n  }\n  ClosestPair closest_value_other;\n  for (const ClosestPair& value_other : per_thread_closest_value_other)\n  {\n    if (value_other.Distance() < closest_value_other.Distance())\n    {\n      closest_value_other = value_other;\n    }\n  }\n  return closest_value_other;\n}\n\n/// Find the closest value-{value, cluster} pair, using @param datapoint_mask to\n/// ignore values that have already been clustered, @param distance_matrix to\n/// provide pairwise value-to-value distances, existing clusters provided by\n/// @param clusters, and strategy specified by @param strategy. @return closest\n/// pair.\ninline ClosestPair GetClosestValueToOtherSerial(\n    const std::vector<uint8_t>& datapoint_mask,\n    const Eigen::MatrixXd& distance_matrix,\n    const std::vector<std::vector<int64_t>>& clusters,\n    const ClusterStrategy strategy)\n{\n  ClosestPair closest_value_other;\n  for (size_t value_idx = 0; value_idx < datapoint_mask.size(); value_idx++)\n  {\n    // Make sure we're not already clustered\n    if (datapoint_mask.at(value_idx) == 0x00)\n    {\n      // Check against other values\n      for (size_t other_value_idx = value_idx + 1;\n           other_value_idx < datapoint_mask.size(); other_value_idx++)\n      {\n        // Make sure it's not already clustered\n        if (datapoint_mask.at(other_value_idx) == 0x00)\n        {\n          const double distance = distance_matrix(value_idx, other_value_idx);\n          if (distance < closest_value_other.Distance())\n          {\n            closest_value_other = ClosestPair(Item(value_idx, false),\n                                              Item(other_value_idx, false),\n                                              distance);\n          }\n        }\n      }\n      // Check against clusters\n      for (size_t cluster_idx = 0; cluster_idx < clusters.size(); cluster_idx++)\n      {\n        const std::vector<int64_t>& cluster = clusters.at(cluster_idx);\n        // Skip empty clusters\n        if (cluster.size() > 0)\n        {\n          // Compute cluster-cluster distance\n          double minimum_distance = std::numeric_limits<double>::infinity();\n          double maximum_distance = 0.0;\n          for (const int64_t& cluster_element_idx : cluster)\n          {\n            const double distance\n                = distance_matrix(value_idx, cluster_element_idx);\n            minimum_distance = std::min(minimum_distance, distance);\n            maximum_distance = std::max(maximum_distance, distance);\n          }\n          const double cluster_distance\n              = (strategy == ClusterStrategy::COMPLETE_LINK) ? maximum_distance\n                                                             : minimum_distance;\n          if (cluster_distance < closest_value_other.Distance())\n          {\n            closest_value_other = ClosestPair(Item(value_idx, false),\n                                              Item(cluster_idx, true),\n                                              cluster_distance);\n          }\n        }\n      }\n    }\n  }\n  return closest_value_other;\n}\n\n/// Find the closest value-{value, cluster} pair, using @param datapoint_mask to\n/// ignore values that have already been clustered, @param distance_matrix to\n/// provide pairwise value-to-value distances, existing clusters provided by\n/// @param clusters, and strategy specified by @param strategy.\n/// @param use_parallel selects if the search should be performed in parallel.\n/// @return closest pair.\ninline ClosestPair GetClosestValueToOther(\n    const std::vector<uint8_t>& datapoint_mask,\n    const Eigen::MatrixXd& distance_matrix,\n    const std::vector<std::vector<int64_t>>& clusters,\n    const ClusterStrategy strategy,\n    const bool use_parallel)\n{\n  if (use_parallel)\n  {\n    return GetClosestValueToOtherParallel(\n        datapoint_mask, distance_matrix, clusters, strategy);\n  }\n  else\n  {\n    return GetClosestValueToOtherSerial(\n        datapoint_mask, distance_matrix, clusters, strategy);\n  }\n}\n\n/// Find the closest {value, cluster}-{value, cluster} pair, using @param\n/// datapoint_mask to ignore values that have already been clustered, @param\n/// distance_matrix to provide pairwise value-to-value distances, existing\n/// clusters provided by @param clusters, and strategy specified by @param\n/// strategy. @param use_parallel selects if the search should be performed in\n/// parallel. @return closest pair.\ninline ClosestPair GetClosestPair(\n    const std::vector<uint8_t>& datapoint_mask,\n    const Eigen::MatrixXd& distance_matrix,\n    const std::vector<std::vector<int64_t>>& clusters,\n    const ClusterStrategy strategy,\n    const bool use_parallel)\n{\n  const ClosestPair closest_value_to_other\n      = GetClosestValueToOther(datapoint_mask, distance_matrix, clusters,\n                               strategy, use_parallel);\n  const ClosestPair closest_clusters\n      = GetClosestClusters(distance_matrix, clusters, strategy, use_parallel);\n  if (closest_value_to_other.IsValid() && closest_clusters.IsValid())\n  {\n    if (closest_value_to_other.Distance() < closest_clusters.Distance())\n    {\n      return closest_value_to_other;\n    }\n    else\n    {\n      return closest_clusters;\n    }\n  }\n  else if (closest_value_to_other.IsValid())\n  {\n    return closest_value_to_other;\n  }\n  else if (closest_clusters.IsValid())\n  {\n    return closest_clusters;\n  }\n  else\n  {\n    return ClosestPair();\n  }\n}\n\ntemplate<typename DataType, typename Container=std::vector<DataType>>\nclass ClusteringResult\n{\nprivate:\n  std::vector<Container> clusters_;\n  double final_closest_distance_ = 0.0;\n\npublic:\n  ClusteringResult() {}\n\n  ClusteringResult(const std::vector<Container>& clusters,\n                   const double final_closest_distance)\n      : clusters_(clusters), final_closest_distance_(final_closest_distance) {}\n\n  const std::vector<Container>& Clusters() const { return clusters_; }\n\n  double FinalClosestDistance() const { return final_closest_distance_; }\n};\n\nusing IndexClusteringResult = ClusteringResult<int64_t, std::vector<int64_t>>;\n\n/// Perform hierarchical index clustering of @param data up to @param\n/// max_cluster_distance, using @param distance_matrix to provide pairwise\n/// value-to-value distance for values in @param data. Strategy to use is\n/// specified by @param strategy, and @param use_parallel selects if parallel\n/// search should be used internally.\ninline IndexClusteringResult IndexClusterWithDistanceMatrix(\n    const Eigen::MatrixXd& distance_matrix, const double max_cluster_distance,\n    const ClusterStrategy strategy, const bool use_parallel = false)\n{\n  if (distance_matrix.rows() != distance_matrix.cols())\n  {\n    throw std::invalid_argument(\"distance_matrix is not square\");\n  }\n  else if (distance_matrix.rows() == 0)\n  {\n    throw std::invalid_argument(\"distance_matrix is empty\");\n  }\n  std::vector<uint8_t> datapoint_mask(distance_matrix.rows(), 0u);\n  std::vector<std::vector<int64_t>> cluster_indices;\n  double closest_distance = 0.0;\n  bool complete = false;\n  while (!complete)\n  {\n    // Get closest pair of items (an element can be a cluster or single value!)\n    const ClosestPair closest_element_pair\n        = GetClosestPair(datapoint_mask, distance_matrix, cluster_indices,\n                         strategy, use_parallel);\n    if (closest_element_pair.IsValid()\n        && closest_element_pair.Distance() <= max_cluster_distance)\n    {\n      closest_distance = closest_element_pair.Distance();\n      const auto& first_item = closest_element_pair.FirstItem();\n      const auto& second_item = closest_element_pair.SecondItem();\n      // If both elements are values, create a new cluster\n      if (first_item.IsValue() && second_item.IsValue())\n      {\n        // Add a cluster\n        cluster_indices.push_back(std::vector<int64_t>{first_item.Index(),\n                                                       second_item.Index()});\n        // Mask out the indices (this way we know they are already clustered)\n        datapoint_mask.at(static_cast<size_t>(first_item.Index())) = 1u;\n        datapoint_mask.at(static_cast<size_t>(second_item.Index())) = 1u;\n      }\n      // If both elements are clusters, merge the clusters\n      else if (first_item.IsCluster() && second_item.IsCluster())\n      {\n        // Merge the second cluster into the first\n        std::vector<int64_t>& first_cluster\n            = cluster_indices.at(static_cast<size_t>(first_item.Index()));\n        std::vector<int64_t>& second_cluster\n            = cluster_indices.at(static_cast<size_t>(second_item.Index()));\n        first_cluster.insert(\n            first_cluster.end(), second_cluster.begin(), second_cluster.end());\n        // Empty the second cluster\n        // (we don't remove, because this would trigger a move and reallocation)\n        second_cluster.clear();\n      }\n      // If one of the elements is a cluster and the other is a point, add the\n      // point to the existing cluster\n      else\n      {\n        const bool first_is_cluster = first_item.IsCluster();\n        const int64_t cluster_index\n            = (first_is_cluster) ? first_item.Index() : second_item.Index();\n        const int64_t value_index\n            = (first_is_cluster) ? second_item.Index() : first_item.Index();\n        // Add the element to the cluster\n        std::vector<int64_t>& cluster\n            = cluster_indices.at(static_cast<size_t>(cluster_index));\n        cluster.push_back(value_index);\n        // Mask out the index (this way we know it is are already clustered)\n        datapoint_mask.at(static_cast<size_t>(value_index)) = 1u;\n      }\n    }\n    else\n    {\n      complete = true;\n    }\n  }\n  // Get rid of empty clusters left over from cluster-cluster merges\n  std::vector<std::vector<int64_t>> index_clusters;\n  index_clusters.reserve(cluster_indices.size());\n  for (const auto& index_cluster : cluster_indices)\n  {\n    if (index_cluster.size() > 0)\n    {\n      index_clusters.push_back(index_cluster);\n    }\n  }\n  // Add any points that we haven't clustered into their own clusters\n  for (size_t idx = 0; idx < datapoint_mask.size(); idx++)\n  {\n    // If an element hasn't been clustered at all yet, make a new cluster\n    if (datapoint_mask.at(idx) == 0)\n    {\n      index_clusters.push_back(\n          std::vector<int64_t>(1, static_cast<int64_t>(idx)));\n    }\n  }\n  index_clusters.shrink_to_fit();\n  return IndexClusteringResult(index_clusters, closest_distance);\n}\n\ntemplate<typename DataType, typename Container=std::vector<DataType>>\ninline ClusteringResult<DataType, Container>\nMakeElementClusteringFromIndexClustering(\n    const Container& data,\n    const IndexClusteringResult& index_clustering)\n{\n  std::vector<Container> clusters(index_clustering.Clusters().size());\n  for (size_t idx = 0; idx < clusters.size(); idx++)\n  {\n    const std::vector<int64_t>& current_index_cluster\n        = index_clustering.Clusters().at(idx);\n    Container& current_cluster = clusters.at(idx);\n    // Use reserve + shrink_to_fit for cases where DataType is not\n    // default-constructible.\n    current_cluster.reserve(current_index_cluster.size());\n    for (const int64_t data_index : current_index_cluster)\n    {\n      current_cluster.push_back(data.at(static_cast<size_t>(data_index)));\n    }\n    current_cluster.shrink_to_fit();\n  }\n  return ClusteringResult<DataType, Container>(\n      clusters, index_clustering.FinalClosestDistance());\n}\n\n/// Perform hierarchical clustering of @param data up to @param\n/// max_cluster_distance, using @param distance_matrix to provide pairwise\n/// value-to-value distance for values in @param data. Strategy to use is\n/// specified by @param strategy, and @param use_parallel selects if parallel\n/// search should be used internally.\ntemplate<typename DataType, typename Container=std::vector<DataType>>\ninline ClusteringResult<DataType, Container> ClusterWithDistanceMatrix(\n    const Container& data, const Eigen::MatrixXd& distance_matrix,\n    const double max_cluster_distance, const ClusterStrategy strategy,\n    const bool use_parallel = false)\n{\n  // Safety check the input\n  if (data.empty())\n  {\n    throw std::invalid_argument(\"data is empty\");\n  }\n  if (static_cast<size_t>(distance_matrix.rows()) != data.size()\n      || static_cast<size_t>(distance_matrix.cols()) != data.size())\n  {\n    throw std::invalid_argument(\"distance_matrix is the wrong size\");\n  }\n  // Perform index clustering\n  const auto index_clustering = IndexClusterWithDistanceMatrix(\n      distance_matrix, max_cluster_distance, strategy, use_parallel);\n  // Extract the actual cluster data from index clusters\n  return MakeElementClusteringFromIndexClustering<DataType, Container>(\n      data, index_clustering);\n}\n\n/// Perform hierarchical index clustering of @param data up to @param\n/// max_cluster_distance, using @param distance_fn to compute pairwise\n/// value-to-value distance for values in @param data. Strategy to use is\n/// specified by @param strategy, and @param use_parallel selects if parallel\n/// search should be used internally.\ntemplate<typename DataType, typename Container=std::vector<DataType>>\ninline IndexClusteringResult IndexCluster(\n    const Container& data,\n    const std::function<double(const DataType&, const DataType&)>& distance_fn,\n    const double max_cluster_distance, const ClusterStrategy strategy,\n    const bool use_parallel = false)\n{\n  const Eigen::MatrixXd distance_matrix\n      = math::BuildPairwiseDistanceMatrix<DataType, Container>(\n          data, distance_fn, use_parallel);\n  return IndexClusterWithDistanceMatrix(\n      distance_matrix, max_cluster_distance, strategy, use_parallel);\n}\n\n/// Perform hierarchical clustering of @param data up to @param\n/// max_cluster_distance, using @param distance_fn to compute pairwise\n/// value-to-value distance for values in @param data. Strategy to use is\n/// specified by @param strategy, and @param use_parallel selects if parallel\n/// search should be used internally.\ntemplate<typename DataType, typename Container=std::vector<DataType>>\ninline ClusteringResult<DataType, Container> Cluster(\n    const Container& data,\n    const std::function<double(const DataType&, const DataType&)>& distance_fn,\n    const double max_cluster_distance, const ClusterStrategy strategy,\n    const bool use_parallel = false)\n{\n  const Eigen::MatrixXd distance_matrix\n      = math::BuildPairwiseDistanceMatrix<DataType, Container>(\n          data, distance_fn, use_parallel);\n  return ClusterWithDistanceMatrix<DataType, Container>(\n      data, distance_matrix, max_cluster_distance, strategy, use_parallel);\n}\n}  // namespace simple_hierarchical_clustering\n}  // namespace common_robotics_utilities\n", "meta": {"hexsha": "4b29e46404272b8d5263a87318a016e784bcfa87", "size": 26764, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common_robotics_utilities/simple_hierarchical_clustering.hpp", "max_stars_repo_name": "calderpg/common_robotics_utilities", "max_stars_repo_head_hexsha": "8b1c06dd45b283f8234c6a4d565bcb7078d1a851", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-10-15T19:04:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T01:35:16.000Z", "max_issues_repo_path": "include/common_robotics_utilities/simple_hierarchical_clustering.hpp", "max_issues_repo_name": "calderpg/common_robotics_utilities", "max_issues_repo_head_hexsha": "8b1c06dd45b283f8234c6a4d565bcb7078d1a851", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-18T19:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-21T15:08:21.000Z", "max_forks_repo_path": "include/common_robotics_utilities/simple_hierarchical_clustering.hpp", "max_forks_repo_name": "calderpg/common_robotics_utilities", "max_forks_repo_head_hexsha": "8b1c06dd45b283f8234c6a4d565bcb7078d1a851", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-10-17T21:12:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-18T03:53:47.000Z", "avg_line_length": 38.2342857143, "max_line_length": 80, "alphanum_fraction": 0.6761694814, "num_tokens": 5641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4068865050234334}}
{"text": "//\n// Created by Hao Wu on 11/10/16.\n//\n\n//\n// Created by Hao Wu on 11/7/16.\n//\n\n#include <iostream>\n#include \"ROWPlus/ROWPlus.h\"\n#include <boost/numeric/odeint.hpp>\n\n#include \"RxnFunctor.h\"\n\nusing namespace Eigen;\nusing namespace ROWPlus;\nusing namespace boost::numeric::odeint;\nusing namespace Cantera;\nusing namespace std;\n\ntemplate<typename vec>\nvoid initX(vec& x, IdealGasMix& gas) {\n  x.resize(gas.nSpecies()+1);\n  gas.setState_TPX(300.0, OneAtm,\n                   \"H:1e-3, H2:2.0, O:1e-3, OH:1e-3, H2O:1e-1, O2:1e-3, HO2:1e-3, H2O2:1e-3, \"\n                       \"N2:3.76\");\n  x[0] = gas.temperature();\n  gas.getMassFractions(x.data()+1);\n}\nint main(const int argc, const char *argv[]) {\n\n  const double t1 = strtod(argv[1], NULL);\n\n  IdealGasMix gas(\"burke_h2_only.xml\");\n  gas.setState_TPX(300.0, OneAtm,\n                   \"H:1e-3, H2:2.0, O:1e-3, OH:1e-3, H2O:1e-1, O2:1e-3, HO2:1e-3, H2O2:1e-3, \"\n                       \"N2:3.76\");\n  RxnFunctor fun(gas);\n\n  std::cout << \"Cantera 0D\" << std::endl;\n\n  RxnFunctor::state_type x_ref;\n  initX(x_ref, gas);\n  typedef runge_kutta_cash_karp54<RxnFunctor::state_type> error_stepper_type;\n  integrate_adaptive(make_controlled<error_stepper_type>(1.0e-12, 1.0e-12),\n                     fun, x_ref, 0.0, t1, 1e-8 );\n  cout << \"T = \" << x_ref[0] << endl;\n\n  // initialize solution vectors\n  RxnFunctor::state_type x_t1;\n  VectorXd x_t2;\n\n  fun.checkBound(false);\n  // creat solver: runge_kutta4_classic\n  runge_kutta4_classic< RxnFunctor::state_type > stepper_rk4;\n  // create solver: ROWPlus::rosenbrock4\n  ROWPlus::rosenbrock4<RxnFunctor, double> stepper_grk4t;\n  stepper_grk4t.makeConstantStepper(&fun);\n  // creat solver: rosenbrock_krylov4 ROK4A\n  rosenbrock_krylov4<RxnFunctor, double> stepper_rok4a(8);\n  ODEOptions<double> _opts = stepper_rok4a.getOptions();\n  _opts.TypeScheme = ROK4A;\n  stepper_rok4a.makeConstantStepper(&fun);\n  // creat solver: rosenbrock_krylov4 ROK4E\n  rosenbrock_krylov4<RxnFunctor, double> stepper_rok4e(8);\n  stepper_rok4e.makeConstantStepper(&fun);\n\n  //\n  double dt = 1e-4;\n  while (dt >= 1e-7) {\n    ROWPlusSolverSpace::Status ret;\n    cout << dt << \" \";\n    // stepper_rk54\n    initX(x_t1, gas);\n    integrate_const( stepper_rk4 , fun , x_t1 , 0.0 , t1 , dt );\n    Map<VectorXd>(x_t1.data(), x_t1.size()) -= Map<VectorXd>(x_ref.data(), x_ref.size());\n    cout << Map<VectorXd>(x_t1.data(), x_t1.size()).stableNorm() /\n        Map<VectorXd>(x_ref.data(), x_ref.size()).stableNorm() << \" \";\n    // stepper_grk4t\n    initX(x_t2, gas);\n    ret = stepper_grk4t.step(x_t2, 0.0, t1, dt);\n    if (ret != ROWPlusSolverSpace::ComputeSucessful) {\n      cout << \"STAT = \" << ret << endl;\n      return 1;\n    }\n    x_t2 -= Map<VectorXd>(x_ref.data(), x_ref.size());\n    cout << x_t2.stableNorm() /\n        Map<VectorXd>(x_ref.data(), x_ref.size()).stableNorm() << \" \";\n    // stepper_rok4a\n    initX(x_t2, gas);\n    ret = stepper_rok4a.step(x_t2, 0.0, t1, dt);\n    if (ret != ROWPlusSolverSpace::ComputeSucessful) {\n      cout << \"STAT = \" << ret << endl;\n      return 1;\n    }\n    x_t2 -= Map<VectorXd>(x_ref.data(), x_ref.size());\n    cout << x_t2.stableNorm() /\n        Map<VectorXd>(x_ref.data(), x_ref.size()).stableNorm() << \" \";\n    // stepper_rok4e\n    initX(x_t2, gas);\n    ret = stepper_rok4e.step(x_t2, 0.0, t1, dt);\n    if (ret != ROWPlusSolverSpace::ComputeSucessful) {\n      cout << \"STAT = \" << ret << endl;\n      return 1;\n    }\n    x_t2 -= Map<VectorXd>(x_ref.data(), x_ref.size());\n    cout << x_t2.stableNorm() /\n        Map<VectorXd>(x_ref.data(), x_ref.size()).stableNorm() << \" \";\n\n    cout << endl;\n    dt /= 2.0;\n  }\n  return 0;\n}", "meta": {"hexsha": "869cd30a59187b16b7eea65cb17fc3950e0e8c86", "size": 3631, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/ChemicalSystems/FixedStepSize.cpp", "max_stars_repo_name": "IhmeGroup/ROWPlus", "max_stars_repo_head_hexsha": "5c6b36bf68ce8702e22956aa2c23cdc2a297192c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/ChemicalSystems/FixedStepSize.cpp", "max_issues_repo_name": "IhmeGroup/ROWPlus", "max_issues_repo_head_hexsha": "5c6b36bf68ce8702e22956aa2c23cdc2a297192c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/ChemicalSystems/FixedStepSize.cpp", "max_forks_repo_name": "IhmeGroup/ROWPlus", "max_forks_repo_head_hexsha": "5c6b36bf68ce8702e22956aa2c23cdc2a297192c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-25T22:41:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-25T22:41:59.000Z", "avg_line_length": 31.850877193, "max_line_length": 94, "alphanum_fraction": 0.6254475351, "num_tokens": 1275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.40685456456421304}}
{"text": "// Copyright (C) 2014 The Regents of the University of California (Regents).\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//\n//     * Redistributions in binary form must reproduce the above\n//       copyright notice, this list of conditions and the following\n//       disclaimer in the documentation and/or other materials provided\n//       with the distribution.\n//\n//     * Neither the name of The Regents or University of California nor the\n//       names of its contributors may be used to endorse or promote products\n//       derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Please contact the author of this library if you have any questions.\n// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia/sfm/estimators/estimate_relative_pose.h\"\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <limits>\n#include <memory>\n#include <vector>\n\n#include \"theia/matching/feature_correspondence.h\"\n#include \"theia/sfm/create_and_initialize_ransac_variant.h\"\n#include \"theia/sfm/pose/essential_matrix_utils.h\"\n#include \"theia/sfm/pose/five_point_relative_pose.h\"\n#include \"theia/sfm/pose/util.h\"\n#include \"theia/sfm/triangulation/triangulation.h\"\n#include \"theia/solvers/estimator.h\"\n#include \"theia/solvers/sample_consensus_estimator.h\"\n#include \"theia/util/util.h\"\n\nnamespace theia {\nnamespace {\n\nusing Eigen::Matrix3d;\nusing Eigen::Vector3d;\n\n// An estimator for computing the relative pose from 5 feature\n// correspondences. The feature correspondences should be normalized\n// by the focal length with the principal point at (0, 0).\nclass RelativePoseEstimator\n    : public Estimator<FeatureCorrespondence, RelativePose> {\n public:\n  RelativePoseEstimator() {}\n\n  // 5 correspondences are needed to determine an essential matrix and thus a\n  // relative pose..\n  double SampleSize() const { return 5; }\n\n  // Estimates candidate relative poses from correspondences.\n  bool EstimateModel(const std::vector<FeatureCorrespondence>& correspondences,\n                     std::vector<RelativePose>* relative_poses) const {\n    std::vector<Eigen::Vector2d> image1_points, image2_points;\n    image1_points.reserve(correspondences.size());\n    image2_points.reserve(correspondences.size());\n    for (int i = 0; i < correspondences.size(); i++) {\n      image1_points.emplace_back(correspondences[i].feature1.point_);\n      image2_points.emplace_back(correspondences[i].feature2.point_);\n    }\n\n    std::vector<Matrix3d> essential_matrices;\n    if (!FivePointRelativePose(\n            image1_points, image2_points, &essential_matrices)) {\n      return false;\n    }\n\n    relative_poses->reserve(essential_matrices.size() * 4);\n    for (const Eigen::Matrix3d& essential_matrix : essential_matrices) {\n      RelativePose relative_pose;\n      relative_pose.essential_matrix = essential_matrix;\n\n      // The best relative pose decomposition should have at least 4\n      // triangulated points in front of the camera. This is because one point\n      // may be at infinity.\n      const int num_points_in_front_of_cameras =\n          GetBestPoseFromEssentialMatrix(essential_matrix,\n                                         correspondences,\n                                         &relative_pose.rotation,\n                                         &relative_pose.position);\n      if (num_points_in_front_of_cameras >= 4) {\n        relative_poses->push_back(relative_pose);\n      }\n    }\n    return relative_poses->size() > 0;\n  }\n\n  // The error for a correspondences given a model. This is the squared sampson\n  // error.\n  double Error(const FeatureCorrespondence& correspondence,\n               const RelativePose& relative_pose) const {\n    if (IsTriangulatedPointInFrontOfCameras(\n            correspondence, relative_pose.rotation, relative_pose.position)) {\n      return SquaredSampsonDistance(relative_pose.essential_matrix,\n                                    correspondence.feature1.point_,\n                                    correspondence.feature2.point_);\n    }\n    return std::numeric_limits<double>::max();\n  }\n\n private:\n  DISALLOW_COPY_AND_ASSIGN(RelativePoseEstimator);\n};\n\n}  // namespace\n\nbool EstimateRelativePose(\n    const RansacParameters& ransac_params,\n    const RansacType& ransac_type,\n    const std::vector<FeatureCorrespondence>& normalized_correspondences,\n    RelativePose* relative_pose,\n    RansacSummary* ransac_summary) {\n  RelativePoseEstimator relative_pose_estimator;\n  std::unique_ptr<SampleConsensusEstimator<RelativePoseEstimator> > ransac =\n      CreateAndInitializeRansacVariant(\n          ransac_type, ransac_params, relative_pose_estimator);\n  // Estimate the relative pose.\n  return ransac->Estimate(\n      normalized_correspondences, relative_pose, ransac_summary);\n}\n\n}  // namespace theia\n", "meta": {"hexsha": "a76bca4b64361e6a77f9c334e7e8e1d777232d19", "size": 5839, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/estimators/estimate_relative_pose.cc", "max_stars_repo_name": "urbste/pyTheiaSfM", "max_stars_repo_head_hexsha": "814034c96b602fef1dc76ae6692278d61179ebcc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-10T19:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T08:16:54.000Z", "max_issues_repo_path": "src/theia/sfm/estimators/estimate_relative_pose.cc", "max_issues_repo_name": "urbste/TheiaSfM", "max_issues_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/estimators/estimate_relative_pose.cc", "max_forks_repo_name": "urbste/TheiaSfM", "max_forks_repo_head_hexsha": "a92fa27e90b6182e2a2511a46d24283afad1a995", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-03-20T03:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T08:08:52.000Z", "avg_line_length": 40.8321678322, "max_line_length": 79, "alphanum_fraction": 0.7249529029, "num_tokens": 1263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4067489745777674}}
{"text": "/*\n * hartman_skrekovski_color.hpp\n * Author: Aven Bross\n * \n * Implementation of Hartman-Skrekovski path 3-choosing algorithm.\n */\n\n#ifndef __HARTMAN_SKREKOVSKI_COLOR_HPP\n#define __HARTMAN_SKREKOVSKI_COLOR_HPP\n\n// STL headers\n#include <vector>\n#include <utility>\n#include <algorithm>\n\n// Basic graph headers\n#include <boost/graph/graph_traits.hpp>\n\n// Local project headers\n#include \"disjoint_set.hpp\"\n#include \"incidence_list_helpers.hpp\"\n\nnamespace {\n    // The three states a vertex may have\n    const int INTERIOR_MARK = 0;\n\n    /* \n     * set_face_location\n     *\n     * inputs: a vertex v, the new face location for v, a read-write-able vertex\n     *     property map storing the face location of each vertex, a disjoint set\n     *     structure to store face location sets.\n     * \n     * outputs: sets the face location of v to the given face location, if the\n     *     given location doesn't exist, that is, the integer new_face_location\n     *     is negative, a new face location is created in the disjoint set\n     *     structure.\n     */\n    template<typename vertex_t, typename face_location_map_t>\n    inline int set_face_location(\n            vertex_t v, int new_face_location,\n            face_location_map_t & face_location_map,\n            disjoint_set_t & face_location_sets\n        )\n    {\n        if(!face_location_sets.exists(new_face_location)) {\n            face_location_map[v] = face_location_sets.make_next();\n        }\n        else {\n            face_location_map[v] = face_location_sets.find(new_face_location);\n        }\n        return face_location_map[v];\n    }\n    \n    /*\n     * hartman_skrekovski_color\n     *\n     * assumptions: There is a cycle C=v_0v_1...v_k in the weakly triangulated\n     *     being colored. Suppose x, y, and p are in C such that p is between x\n     *     and y clockwise around C. Suppose all vertices other than x, y, and p\n     *     are uncolored. Suppose vertices x, y, and p have lists of size 1 or\n     *     more, other vertices in C have lists of size 2 or more, and vertices\n     *     in the subgraph bounded by C have lists of size 3 or more.\n     *     Additionally, if p is colored some color c, assume vertices between x\n     *     and p clockwise, including x, don't have the color c in their lists.\n     * \n     * inputs: A weakly triangulated planar graph with vertex indices\n     *     (predefined boost property), a valid augmented planar embedding of\n     *     the graph (modeling the boost AugmentedEmbedding concept defined in\n     *     documentation), a read-write-able vertex property map assigning each\n     *     vertex an integer to track face location, a disjoint set structure to\n     *     store face location sets, a read-write-able vertex property map\n     *     assigning each vertex an integer to track state, a read-able vertex\n     *     property map assigning a pair of iterators from its augmented\n     *     embedding list to track the range of valid neighbors, a read-write-\n     *     able vertex property map to which the coloring will be assigned, the\n     *     vertices x, y, and p on the outer cycle of the current subgraph, and\n     *     the integers for the current face location marks.\n     * \n     * outputs: The coloring vertex property will contain a valid path list-\n     *     coloring of the subgraph bounded by C such that x, y, and p each\n     *     receive at most one same color neighbor. Moreover, if x=y=p then\n     *     x,y,p receive no same color neighbors.\n     */\n\n    template<\n            typename graph_t, typename augmented_embedding_t,\n            typename face_location_map_t, typename neighbor_range_map_t,\n            typename color_list_map_t, typename vertex_t\n                = typename boost::graph_traits<graph_t>::vertex_descriptor\n        >\n    void hartman_skrekovski_color_recursive(\n            const graph_t & graph,\n            const augmented_embedding_t & augmented_embedding,\n            face_location_map_t & face_location_map,\n            disjoint_set_t & face_location_sets, \n            neighbor_range_map_t & neighbor_range_map,\n            color_list_map_t & color_list_map,\n            vertex_t x, vertex_t y, vertex_t p,\n            int before_p, int before_y, int before_x\n        )\n    {\n        // If p isn't colored yet we are starting a new path\n        if(color_list_map[p].size() > 1) {\n            // Color p the first color in its list\n            color_list_map[p].erase(\n                    ++color_list_map[p].begin(),\n                    color_list_map[p].end()\n                );\n        }\n        \n        // Grab p's the color from p's singleton list\n        auto p_color = color_list_map[p].front();\n        \n        // Track the vertices that will become x and y in the first cycle\n        vertex_t new_x = x, new_y = y;\n        \n        // Iterate through p's adjacency list\n        auto neighbor_iter = neighbor_range_map[p].first;\n        do {\n            // Wrap adjacency list\n            if(neighbor_iter == augmented_embedding[p].end())\n                neighbor_iter = augmented_embedding[p].begin();\n            \n            // Grab neighbor n, and the iterator to p in n's adjacency list\n            vertex_t n = neighbor_iter -> vertex;\n            auto back_iter = neighbor_iter -> iterator;\n            int n_location = face_location_map[n];\n            \n            // Look for p_color in n's color list\n            auto color_iter = std::find(\n                    color_list_map[n].begin(),\n                    color_list_map[n].end(), p_color\n                );\n            \n            // The case n is not in C\n            if(face_location_map[n] == INTERIOR_MARK) {\n                // Note that n is between x and p on the first cycle\n                before_p = set_face_location(\n                        n, before_p, face_location_map, face_location_sets\n                    );\n                \n                // Initialize n's neighbor range to start at the edge pn\n                initialize_neighbor_range(\n                        n, back_iter, neighbor_range_map, augmented_embedding\n                    );\n                \n                // Remove the edge pn from n's neighbor range\n                remove_first_neighbor(\n                        n, neighbor_range_map, augmented_embedding\n                    );\n                \n                // Remove the path color from n's list\n                if(color_iter != color_list_map[n].end()) {\n                    color_list_map[n].erase(color_iter);\n                    color_iter = color_list_map[n].end();\n                }\n            }\n            // The case n is immediately counterclockwise to p in C\n            else if(neighbor_iter == neighbor_range_map[p].first) {\n                // If p has a single neighbor the current subgraph is K_2\n                if(neighbor_iter == neighbor_range_map[p].second) {\n                    // If is neither x nor y, ensure it doesn't receive p_color\n                    if(n != x && n != y) {\n                        // Remove the path color from n's list\n                        if(color_iter != color_list_map[n].end()) {\n                            color_list_map[n].erase(color_iter);\n                            color_iter = color_list_map[n].end();\n                        }\n                    }\n                    \n                    // Color n with any color remaining in its list\n                    if(color_list_map[n].size() > 1) {\n                        color_list_map[n].erase(\n                                ++color_list_map[n].begin(),\n                                color_list_map[n].end()\n                            );\n                    }\n                    \n                    break;\n                }\n                // If n is y and y has the path color, swap p and y so the\n                //     path runs clockwise\n                else if(n == y && color_iter != color_list_map[n].end()) {\n                    if(color_list_map[n].size() > 1) {\n                        // Remove all colors other than the path color\n                        color_list_map[n].erase(\n                                color_list_map[n].begin(),\n                                color_iter\n                            );\n                        color_list_map[n].erase(\n                                ++color_list_map[n].begin(),\n                                color_list_map[n].end()\n                            );\n                    }\n                    \n                    hartman_skrekovski_color_recursive(\n                            graph, augmented_embedding,\n                            face_location_map, face_location_sets,\n                            neighbor_range_map, color_list_map,\n                            y, p, y,\n                            -1, -1, before_y\n                        );\n                    \n                    break;\n                }\n                else {\n                    // If we are removing x, setup new_x as n\n                    if(x == p) {\n                        new_x = n;\n                        \n                        // Note that n is between x and p on the first cycle\n                        before_p = set_face_location(\n                                n, before_p, face_location_map,\n                                face_location_sets\n                            );\n                    }\n                    \n                    // Remove path color from n's list\n                    if(color_iter != color_list_map[n].end()) {\n                        color_list_map[n].erase(color_iter);\n                        color_iter = color_list_map[n].end();\n                    }\n                    \n                    // Remove the edge pn from n's adjacency list\n                    remove_last_neighbor(\n                            n, neighbor_range_map, augmented_embedding\n                        );\n                }\n            }\n            else {\n                // Divide the neighbor range of n at the edge pn\n                auto n_ranges = split_neighbor_range(\n                        n, back_iter, neighbor_range_map, augmented_embedding\n                    );\n                \n                // p has been removed from the first cycle so we may remove\n                //     those neighbors from p's neighbor range\n                neighbor_range_map[p].first = neighbor_iter;\n                \n                // The case we are removing y\n                if(p == y) {\n                    if(color_iter != color_list_map[n].end()) {\n                        color_list_map[n].erase(color_iter);\n                        color_iter = color_list_map[n].end();\n                    }\n                    \n                    // If p=x=y then we are removing a single vertex path\n                    if(p == x) {\n                        // Color the subgraph bounded by the first cycle\n                        neighbor_range_map[n] = n_ranges.second;\n                        hartman_skrekovski_color_recursive(\n                                graph, augmented_embedding,\n                                face_location_map, face_location_sets,\n                                neighbor_range_map, color_list_map,\n                                new_x, n, new_x,\n                                -1, before_p, before_y\n                            );\n                        \n                        // If the edge pn is a chord, we must color the rest\n                        if(back_iter != n_ranges.first.first) {\n                            // Color the subgraph bounded by the second cycle\n                            neighbor_range_map[n] = n_ranges.first;\n                            hartman_skrekovski_color_recursive(\n                                    graph, augmented_embedding,\n                                    face_location_map, face_location_sets,\n                                    neighbor_range_map, color_list_map,\n                                    n, p, p,\n                                    -1, -1, before_y\n                                );\n                        }\n                        \n                        break;\n                    }\n                    // The case the edge pn is in the cycle, i.e. not a chord\n                    else if(neighbor_iter == neighbor_range_map[p].second) {\n                        // Color the subgraph bounded by the first cycle\n                        neighbor_range_map[n] = n_ranges.second;\n                        hartman_skrekovski_color_recursive(\n                                graph, augmented_embedding,\n                                face_location_map, face_location_sets,\n                                neighbor_range_map, color_list_map,\n                                new_x, n, new_x,\n                                -1, before_p, before_x\n                            );\n                        \n                        break;\n                    }\n                    // Otherwise we condition on the location of n as usual\n                    \n                    // Remember n will be our new y vertex for the first cycle\n                    new_y = n;\n                }\n                \n                // The case n is in C[p,y] \n                if(face_location_sets.compare(n_location, before_y) || n == y) {\n                    vertex_t new_p = n;\n                    \n                    // The case n needs to be colored\n                    if(color_iter != color_list_map[n].end()\n                        && color_list_map[n].size() > 1)\n                    {\n                        // Remove all colors other than the path color\n                        color_list_map[n].erase(\n                                color_list_map[n].begin(),\n                                color_iter\n                            );\n                        color_list_map[n].erase(\n                                ++color_list_map[n].begin(),\n                                color_list_map[n].end()\n                            );\n                    }\n                    // The case n will not be added to the path\n                    else if(color_list_map[n].size() > 1\n                        || color_list_map[n].front() != p_color)\n                    {\n                        // Start new path at the new x on the first cycle\n                        new_p = new_x;\n                        \n                        // Combine the before_p and before_y segments\n                        before_y = face_location_sets.take_union(\n                                before_p, before_y\n                            );\n                        \n                        // Note before_p is gone\n                        before_p = -1;\n                    }\n                    \n                    /*\n                     * This is the most complicated case.\n                     * There are two sub-cases to consider:\n                     * \n                     * Case 1: p_color in L[n]\n                     *   In this case |L[n]|=1. In the first call we will\n                     *   continue coloring the path from n. In the second\n                     *   call, we will immediately find the edge pn and,\n                     *   since it the first edge and in the cycle, we will\n                     *   immediately remove the two vertex path np. Thus\n                     *   no vertex in the path will recieve a new same color\n                     *   neighbor from the second call.\n                     *\n                     * Case 2: p_color is not in L[n]\n                     *   In this case the first call will start a new path\n                     *   from the vertex new_x. By removing p_color from all\n                     *   neighbors of vertices in the path, we ensure no\n                     *   vertices in the path, including n, will recieve any\n                     *   new same color neighbors in the first call. In the\n                     *   second call we will be continuing the path from p.\n                     *   Since p_color is not in L[n] and x=y=n, the vertex\n                     *   n will not recieve any new same color neighbors in\n                     *   the second call.\n                     \n                     */\n                    \n                    // Color the subgraph bounded by the first cycle\n                    neighbor_range_map[n] = n_ranges.second;\n                    hartman_skrekovski_color_recursive(\n                            graph, augmented_embedding,\n                            face_location_map, face_location_sets,\n                            neighbor_range_map, color_list_map,\n                            new_x, new_y, new_p,\n                            before_p, before_y, before_x\n                        );\n                    \n                    // If the edge pn is a chord, handle the rest\n                    if(back_iter != n_ranges.first.first) {\n                        // Color the subgraph bounded by the second cycle\n                        neighbor_range_map[n] = n_ranges.first;\n                        hartman_skrekovski_color_recursive(\n                                graph, augmented_embedding,\n                                face_location_map, face_location_sets,\n                                neighbor_range_map, color_list_map,\n                                n, n, p,\n                                -1, before_y, -1\n                            );\n                    }\n                }\n                // The case n is in C[y,x], n != y\n                else if(face_location_sets.compare(n_location, before_x)) {\n                    if(color_iter != color_list_map[n].end()) {\n                        color_list_map[n].erase(color_iter);\n                        color_iter = color_list_map[n].end();\n                    }\n                    \n                    // Color the subgraph bounded by the first cycle\n                    neighbor_range_map[n] = n_ranges.second;\n                    hartman_skrekovski_color_recursive(\n                            graph, augmented_embedding,\n                            face_location_map, face_location_sets,\n                            neighbor_range_map, color_list_map,\n                            new_x, n, new_x,\n                            -1, before_p, before_x\n                        );\n                    \n                    // Color the subgraph bounded by the second cycle\n                    neighbor_range_map[n] = n_ranges.first;\n                    hartman_skrekovski_color_recursive(\n                            graph, augmented_embedding,\n                            face_location_map, face_location_sets,\n                            neighbor_range_map, color_list_map,\n                            n, y, p,\n                            -1, before_y, before_x\n                        );\n                }\n                // The case n is in C[x,p]\n                else {\n                    // Color the subgraph bounded b the second cycle\n                    neighbor_range_map[n] = n_ranges.first;\n                    hartman_skrekovski_color_recursive(\n                            graph, augmented_embedding,\n                            face_location_map, face_location_sets,\n                            neighbor_range_map, color_list_map,\n                            x, y, p,\n                            before_p, before_y, before_x\n                        );\n                    \n                    // Color the subgraph bounded by the first cycle\n                    neighbor_range_map[n] = n_ranges.second;\n                    hartman_skrekovski_color_recursive(\n                            graph, augmented_embedding,\n                            face_location_map, face_location_sets,\n                            neighbor_range_map, color_list_map,\n                            n, n, n,\n                            -1, before_p, -1\n                        );\n                }\n                \n                break;\n            }\n        } while(neighbor_iter++ != neighbor_range_map[p].second);\n    }\n}\n\n\n/*\n * hartman_skrekovski_color\n * \n * inputs: A weakly triangulated planar graph with vertex indices (predefined\n *     boost property), a valid augmented planar embedding of the graph\n *     (modeling the boost AugmentedEmbedding concept defined in documentation),\n *     a read-able vertex property map assigning a range of colors to each\n *     vertex (each vertex must recieve a range of at least 3 colors if\n *     interior, and at least two colors if on the outer face), a read-write-\n *     able vertex property map to which the coloring will be assigned, and\n *     finally a pair of iterators for the list of vertices on the outer face of\n *     the graph in clockwise order.\n * \n * outputs: The coloring will be a valid assignment of colors from the input\n *     color lists such that each color class induces a disjoint union of paths.\n */\n \ntemplate<\n        typename graph_t,\n        typename augmented_embedding_t,\n        typename color_list_map_t,\n        typename neighbor_range_map_t,\n        typename face_location_map_t,\n        typename face_iterator_t\n    >\nvoid hartman_skrekovski_color(\n        const graph_t & graph,\n        const augmented_embedding_t & augmented_embedding,\n        face_iterator_t face_begin, face_iterator_t face_end,\n        neighbor_range_map_t & neighbor_range_map,\n        face_location_map_t & face_location_map,\n        color_list_map_t & color_list_map\n    )\n{\n    // Type definitions\n    typedef typename boost::graph_traits<graph_t>::vertex_descriptor vertex_t;\n    \n    // Setup face location sets (we will have only the region before_y)\n    disjoint_set_t face_location_sets;\n    \n    // Make a set for 0, the location given to interior vertices\n    face_location_sets.make_next();\n    \n    // Intitially all vertices will be\n    int before_y = -1;\n    \n    // Initialize vertices on outer face\n    for(auto face_iter = face_begin; face_iter != face_end; ++face_iter)\n    {\n        auto next = face_iter;\n        if(++next == face_end) next = face_begin;\n        \n        vertex_t l = *face_iter;\n        vertex_t v = *next;\n        \n        before_y = set_face_location(\n                v, before_y, face_location_map, face_location_sets\n            );\n        \n        auto back_iter = find_neighbor_iterator(\n                v, l, augmented_embedding, graph\n            );\n        initialize_neighbor_range(\n                v, back_iter, neighbor_range_map, augmented_embedding\n            );\n    }\n    \n    vertex_t x = *face_begin, y = *(--face_end);\n    \n    // Construct the path choosing from given color lists\n    hartman_skrekovski_color_recursive(\n            graph, augmented_embedding,\n            face_location_map, face_location_sets,\n            neighbor_range_map, color_list_map,\n            x, y, x,\n            -1, before_y, -1\n        );\n}\n\n/*\n * A wrapper that automatically construct fast property maps for the\n * face_location_map and neighbor_range_map, but requires that graph_t is some\n * definition of boost::adjacency_list.\n */\n\ntemplate<\n        typename graph_t,\n        typename augmented_embedding_t,\n        typename color_list_map_t,\n        typename face_iterator_t\n    >\nvoid hartman_skrekovski_color(\n        const graph_t & graph,\n        const augmented_embedding_t & augmented_embedding,\n        face_iterator_t face_begin, face_iterator_t face_end,\n        color_list_map_t & color_list_map\n    )\n{\n    // Vertex property map to store vertex marks\n    typedef boost::iterator_property_map<\n            std::vector<int>::iterator,\n            typename boost::property_map<\n                    graph_t, boost::vertex_index_t\n                >::const_type\n        > integer_property_map_t;\n    \n    // Vertex property map type for the neighbor ranges of planar_embedding_t\n    typedef typename boost::property_traits<augmented_embedding_t>::value_type\n            ::const_iterator embedding_iterator_t;\n    typedef typename std::vector<\n            std::pair<embedding_iterator_t, embedding_iterator_t>\n        > neighbor_range_storage_t;\n    typedef boost::iterator_property_map<\n            typename neighbor_range_storage_t::iterator,\n            typename boost::property_map<\n                    graph_t, boost::vertex_index_t\n                >::const_type\n        > neighbor_range_map_t;\n    \n    // Construct a vertex property for neighbor ranges\n    neighbor_range_storage_t neighbor_range_storage(boost::num_vertices(graph));\n    neighbor_range_map_t neighbor_range_map(\n            neighbor_range_storage.begin(),\n            boost::get(boost::vertex_index, graph)\n        );\n    \n    // Construct a vertex property map to store face location marks\n    std::vector<int> face_location_storage(boost::num_vertices(graph));\n    integer_property_map_t face_location_map(\n            face_location_storage.begin(),\n            boost::get(boost::vertex_index, graph)\n        );\n    \n    // Call Hartman-Skrekovski with the given cycle and \n    hartman_skrekovski_color(\n            graph,\n            augmented_embedding,\n            face_begin, face_end,\n            neighbor_range_map,\n            face_location_map,\n            color_list_map\n        );\n}\n\n#endif\n", "meta": {"hexsha": "44d480e5e59f39f01d37c4886f5d0cec063b6ba4", "size": 25212, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/path_coloring/hartman_skrekovski_color.hpp", "max_stars_repo_name": "permutationlock/path_coloring_bgl", "max_stars_repo_head_hexsha": "ec8ca14faadfdf65f7dcab9aef5a91d82dc7d6d1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/include/path_coloring/hartman_skrekovski_color.hpp", "max_issues_repo_name": "permutationlock/path_coloring_bgl", "max_issues_repo_head_hexsha": "ec8ca14faadfdf65f7dcab9aef5a91d82dc7d6d1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/path_coloring/hartman_skrekovski_color.hpp", "max_forks_repo_name": "permutationlock/path_coloring_bgl", "max_forks_repo_head_hexsha": "ec8ca14faadfdf65f7dcab9aef5a91d82dc7d6d1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4689655172, "max_line_length": 80, "alphanum_fraction": 0.5059495478, "num_tokens": 4680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4067489745777674}}
{"text": "/*\n@copyright Louis Dionne 2015\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_DET_HPP\n#define BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_DET_HPP\n\n#include <boost/hana/constant.hpp>\n#include <boost/hana/foldable.hpp>\n#include <boost/hana/functional/always.hpp>\n#include <boost/hana/functional/compose.hpp>\n#include <boost/hana/functional/fix.hpp>\n#include <boost/hana/functional/on.hpp>\n#include <boost/hana/functional/partial.hpp>\n#include <boost/hana/functional/placeholder.hpp>\n#include <boost/hana/functor.hpp>\n#include <boost/hana/integral_constant.hpp>\n#include <boost/hana/iterable.hpp>\n#include <boost/hana/sequence.hpp>\n#include <boost/hana/logical.hpp>\n#include <boost/hana/monoid.hpp>\n#include <boost/hana/range.hpp>\n#include <boost/hana/ring.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <utility>\n\n#include \"matrix.hpp\"\n\n\nnamespace cppcon {\n    namespace detail {\n        auto remove_at = [](auto n, auto xs) {\n            using namespace boost::hana;\n            using L = datatype_t<decltype(xs)>;\n            auto with_indices = zip(xs, to<L>(range(size_t<0>, length(xs))));\n            auto removed = filter(with_indices, compose(n != _, last));\n            return transform(removed, head);\n        };\n    }\n\n    auto det = boost::hana::fix([](auto det, auto&& m) -> decltype(auto) {\n        using namespace boost::hana;\n        auto matrix_minor = [=](auto&& m, auto i, auto j) -> decltype(auto) {\n            return det(unpack(\n                transform(\n                    detail::remove_at(i, rows(std::forward<decltype(m)>(m))),\n                    partial(detail::remove_at, j)\n                ),\n                matrix\n            ));\n        };\n\n        auto cofactor = [=](auto&& m, auto i, auto j) {\n            return power(int_<-1>, plus(i, j)) *\n                    matrix_minor(std::forward<decltype(m)>(m), i, j);\n        };\n\n        return eval_if(m.size() == size_t<1>,\n            always(m.at(size_t<0>, size_t<0>)),\n            [=](auto _) {\n                auto cofactors_1st_row = unpack(_(range)(size_t<0>, m.ncolumns()),\n                    on(make<Tuple>, partial(cofactor, m, size_t<0>))\n                );\n                return detail::tuple_scalar_product(head(rows(m)), cofactors_1st_row);\n            }\n        );\n    });\n} // end namespace cppcon\n\n#endif // !BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_DET_HPP\n", "meta": {"hexsha": "b2b07e10322b99b4c0ac6832eaa6c750758efa16", "size": 2492, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "example/cppcon_2014/matrix/det.hpp", "max_stars_repo_name": "josephwinston/hana", "max_stars_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/cppcon_2014/matrix/det.hpp", "max_issues_repo_name": "josephwinston/hana", "max_issues_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/cppcon_2014/matrix/det.hpp", "max_forks_repo_name": "josephwinston/hana", "max_forks_repo_head_hexsha": "a8586ec1812e14e43dfd6867209412aa1d254e1a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6756756757, "max_line_length": 86, "alphanum_fraction": 0.613964687, "num_tokens": 608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4067489675231902}}
{"text": "#include <gmp.h>\n#include <fc/crypto/alt_bn128.hpp>\n\n#include <libff/algebra/curves/alt_bn128/alt_bn128_g1.hpp>\n#include <libff/algebra/curves/alt_bn128/alt_bn128_g2.hpp>\n#include <libff/algebra/curves/alt_bn128/alt_bn128_pairing.hpp>\n#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>\n\n#include <libff/common/profiling.hpp>\n#include <boost/throw_exception.hpp>\n#include <algorithm>\n\nnamespace fc {\n\n    using Scalar = libff::bigint<libff::alt_bn128_q_limbs>;\n\n    void initLibSnark() noexcept {\n        static bool s_initialized = []() noexcept {\n            libff::inhibit_profiling_info = true;\n            libff::inhibit_profiling_counters = true;\n            libff::alt_bn128_pp::init_public_params();\n            return true; \n        }();\n        (void)s_initialized;\n    }\n\n    Scalar to_scalar(const bytes& be) noexcept {\n        mpz_t m;\n        mpz_init(m);\n        mpz_import(m, be.size(), /*order=*/1, /*size=*/1, /*endian=*/0, /*nails=*/0, &be[0]);\n        Scalar out{m};\n        mpz_clear(m);\n        return out;\n    }\n\n    // Notation warning: Yellow Paper's p is the same libff's q.\n    // Returns x < p (YP notation).\n    static bool valid_element_of_fp(const Scalar& x) noexcept {\n        return mpn_cmp(x.data, libff::alt_bn128_modulus_q.data, libff::alt_bn128_q_limbs) < 0;\n    }\n\n    std::variant<alt_bn128_error, libff::alt_bn128_G1> decode_g1_element(const bytes& bytes64_be) noexcept {\n        if(bytes64_be.size() != 64) {\n            return alt_bn128_error::input_len_error;\n        }\n    \n        bytes sub1(bytes64_be.begin(), bytes64_be.begin()+32);\n        bytes sub2(bytes64_be.begin()+32, bytes64_be.begin()+64);\n\n        Scalar x{to_scalar(sub1)};\n        Scalar y{to_scalar(sub2)};\n\n        if (!valid_element_of_fp(x) || !valid_element_of_fp(y)) {\n            return alt_bn128_error::operand_component_invalid;\n        }\n\n        if (x.is_zero() && y.is_zero()) {\n            return alt_bn128_error::operand_at_origin;\n        }\n\n        libff::alt_bn128_G1 point{x, y, libff::alt_bn128_Fq::one()};\n        if (!point.is_well_formed()) {\n            return alt_bn128_error::operand_not_in_curve;\n        }\n        return point;\n    }\n\n    std::variant<alt_bn128_error, libff::alt_bn128_Fq2> decode_fp2_element(const bytes& bytes64_be) noexcept {\n        if(bytes64_be.size() != 64) {\n            return alt_bn128_error::input_len_error;\n        }\n\n        // big-endian encoding\n        bytes sub1(bytes64_be.begin()+32, bytes64_be.begin()+64);\n        bytes sub2(bytes64_be.begin(), bytes64_be.begin()+32);        \n\n        Scalar c0{to_scalar(sub1)};\n        Scalar c1{to_scalar(sub2)};\n\n        if (!valid_element_of_fp(c0) || !valid_element_of_fp(c1)) {\n            return alt_bn128_error::operand_component_invalid;\n        }\n\n        return libff::alt_bn128_Fq2{c0, c1};\n    }\n\n    std::variant<alt_bn128_error, libff::alt_bn128_G2> decode_g2_element(const bytes& bytes128_be) noexcept {\n\n        bytes sub1(bytes128_be.begin(), bytes128_be.begin()+64);        \n        auto maybe_x = decode_fp2_element(sub1);\n        if (std::holds_alternative<alt_bn128_error>(maybe_x)) {\n            return std::get<alt_bn128_error>(maybe_x);\n        }\n\n        bytes sub2(bytes128_be.begin()+64, bytes128_be.begin()+128);        \n        auto maybe_y = decode_fp2_element(sub2);\n        if (std::holds_alternative<alt_bn128_error>(maybe_y)) {\n            return std::get<alt_bn128_error>(maybe_y);\n        }\n\n        const auto& x = std::get<libff::alt_bn128_Fq2>(maybe_x);\n        const auto& y = std::get<libff::alt_bn128_Fq2>(maybe_y);\n\n        if (x.is_zero() && y.is_zero()) {\n            return alt_bn128_error::operand_at_origin;\n        }\n\n        libff::alt_bn128_G2 point{x, y, libff::alt_bn128_Fq2::one()};\n        if (!point.is_well_formed()) {\n            return alt_bn128_error::operand_not_in_curve;\n        }\n\n        if (!(libff::alt_bn128_G2::order() * point).is_zero()) {\n            // wrong order, doesn't belong to the subgroup G2\n            return alt_bn128_error::operand_outside_g2;\n        }\n\n        return point;\n    }\n\n    bytes encode_g1_element(libff::alt_bn128_G1 p) noexcept {\n        bytes out(64, '\\0');\n        if (p.is_zero()) {\n            return out;\n        }\n\n        p.to_affine_coordinates();\n\n        auto x{p.X.as_bigint()};\n        auto y{p.Y.as_bigint()};\n\n        std::memcpy(&out[0], y.data, 32);\n        std::memcpy(&out[32], x.data, 32);\n\n        std::reverse(out.begin(), out.end());\n        return out;\n    }\n\n    std::variant<alt_bn128_error, bytes> alt_bn128_add(const bytes& op1, const bytes& op2) {\n        fc::initLibSnark();\n\n        auto maybe_x = decode_g1_element(op1);\n        if (std::holds_alternative<alt_bn128_error>(maybe_x)) {\n            return std::get<alt_bn128_error>(maybe_x);\n        }\n\n        auto maybe_y = decode_g1_element(op2);\n        if (std::holds_alternative<alt_bn128_error>(maybe_y)) {\n            return std::get<alt_bn128_error>(maybe_y);\n        }\n\n        const auto& x = std::get<libff::alt_bn128_G1>(maybe_x);\n        const auto& y = std::get<libff::alt_bn128_G1>(maybe_y);\n\n        libff::alt_bn128_G1 g1Sum = x + y;\n        return encode_g1_element(g1Sum);\n    }\n\n    std::variant<alt_bn128_error, bytes> alt_bn128_mul(const bytes& g1_point, const bytes& scalar) {\n        initLibSnark();\n\n        auto maybe_x = decode_g1_element(g1_point);\n        if (std::holds_alternative<alt_bn128_error>(maybe_x)) {\n            return std::get<alt_bn128_error>(maybe_x);\n        }\n\n        auto& x = std::get<libff::alt_bn128_G1>(maybe_x);\n\n        if(scalar.size() != 32) {\n            return alt_bn128_error::invalid_scalar_size;\n        }\n\n        Scalar n{to_scalar(scalar)};\n\n        libff::alt_bn128_G1 g1Product = n * x;\n        return encode_g1_element(g1Product);\n    }\n    \n    static constexpr size_t kSnarkvStride{192};\n\n    std::variant<alt_bn128_error, bool>  alt_bn128_pair(const bytes& g1_g2_pairs, const yield_function_t& yield) {\n        if (g1_g2_pairs.size() % kSnarkvStride != 0) {\n            return alt_bn128_error::pairing_list_size_error;\n        }\n\n        size_t k{g1_g2_pairs.size() / kSnarkvStride};\n\n        initLibSnark();\n        using namespace libff;\n\n        static const auto one{alt_bn128_Fq12::one()};\n        auto accumulator{one};\n\n        for (size_t i{0}; i < k; ++i) {\n            auto offset = i * kSnarkvStride;\n\n            bytes sub1(g1_g2_pairs.begin()+offset, g1_g2_pairs.begin()+offset+64);        \n            auto maybe_a = decode_g1_element(sub1);\n            if (std::holds_alternative<alt_bn128_error>(maybe_a)) {\n                return std::get<alt_bn128_error>(maybe_a);\n            }\n\n            bytes sub2(g1_g2_pairs.begin()+offset+64, g1_g2_pairs.begin()+offset+64+128);        \n            auto maybe_b = decode_g2_element(sub2);\n            if (std::holds_alternative<alt_bn128_error>(maybe_b)) {\n                return std::get<alt_bn128_error>(maybe_b);\n            }\n           \n            const auto& a = std::get<libff::alt_bn128_G1>(maybe_a);\n            const auto& b = std::get<libff::alt_bn128_G2>(maybe_b);\n\n            if (a.is_zero() || b.is_zero()) {\n                continue;\n            }\n\n            accumulator = accumulator * alt_bn128_miller_loop(alt_bn128_precompute_G1(a), alt_bn128_precompute_G2(b));\n            yield();\n        }\n\n        bool pair_result = false;\n        if (alt_bn128_final_exponentiation(accumulator) == one) {\n            pair_result = true;\n        }\n\n        return pair_result;\n    }\n}\n", "meta": {"hexsha": "94003282ace3512c6611bbd09a3d90f7f2aecd1a", "size": 7524, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/crypto/alt_bn128.cpp", "max_stars_repo_name": "eosnetworkfoundation/mandel-fc", "max_stars_repo_head_hexsha": "3b24dc3ae79ab962ce05a8aaef62f0886cb086e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-17T23:48:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-17T23:48:50.000Z", "max_issues_repo_path": "src/crypto/alt_bn128.cpp", "max_issues_repo_name": "eosnetworkfoundation/mandel-fc", "max_issues_repo_head_hexsha": "3b24dc3ae79ab962ce05a8aaef62f0886cb086e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-06T20:17:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-06T20:17:15.000Z", "max_forks_repo_path": "src/crypto/alt_bn128.cpp", "max_forks_repo_name": "eosnetworkfoundation/mandel-fc", "max_forks_repo_head_hexsha": "3b24dc3ae79ab962ce05a8aaef62f0886cb086e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-31T22:49:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T18:16:58.000Z", "avg_line_length": 33.0, "max_line_length": 118, "alphanum_fraction": 0.6061935141, "num_tokens": 2034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8198933447152497, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.4067440291375089}}
{"text": "#include<fastenvelope/obb.h>\n#include <Eigen/Eigenvalues> \n#include<fstream>\n#include <iomanip>\n#include<fastenvelope/FastEnvelope.h>// for is_triangle_degenerated()\nnamespace fastEnvelope {\n\n\tstd::vector<obb> obb::build_obb_matrixs(const std::vector<Vector3>& face_vertices, const int p_face[8][3], const int c_face[6][3],\n\t\tconst std::array<std::vector<int>, 8>& p_facepoint, const std::array<std::array<int, 4>, 6>& c_facepoint) {\n\t\tstd::vector<Vector3> points;\n\n\t\tint dege;\n\t\tVector3 normal;\n\t\tstd::vector<obb> M;\n\t\tM.reserve(8);\n\n\t\tif (face_vertices.size() == polyhedron_point_number1) {\n\t\t\t//M.resize(polyhedron_face_number1);\n\n\t\t\tfor (int j = 0; j < polyhedron_face_number1; j++) {\n\t\t\t\t//triangle to get normal: {envelope_vertices[i][p_face[j][0]],envelope_vertices[i][p_face[j][1]],envelope_vertices[i][p_face[j][2]]}\n#ifdef DO_NOT_HAVE_DEGENERATED_FACES\n\t\t\t\tif (((face_vertices[p_face[j][0]] - face_vertices[p_face[j][1]]).cross(\n\t\t\t\t\tface_vertices[p_face[j][0]] - face_vertices[p_face[j][2]])).norm() < SCALAR_ZERO)\n\t\t\t\t\tnormal = FastEnvelope::accurate_normal_vector(face_vertices[p_face[j][0]], face_vertices[p_face[j][1]],\n\t\t\t\t\t\tface_vertices[p_face[j][0]], face_vertices[p_face[j][2]]);\n\t\t\t\telse {\n\t\t\t\t\tnormal = ((face_vertices[p_face[j][0]] - face_vertices[p_face[j][1]]).cross(face_vertices[p_face[j][0]] - face_vertices[p_face[j][2]])).normalized();\n\t\t\t\t}\n#else\n\t\t\t\t\t//triangle to get normal: {envelope_vertices[i][p_face[j][0]],envelope_vertices[i][p_face[j][1]],envelope_vertices[i][p_face[j][2]]}\n\n\t\t\t\tdege = FastEnvelope::is_triangle_degenerated(face_vertices[p_face[j][0]], face_vertices[p_face[j][1]], face_vertices[p_face[j][2]]);\n\t\t\t\tif (dege == FastEnvelope::DEGENERATED_SEGMENT || dege == FastEnvelope::DEGENERATED_POINT) {\n\t\t\t\t\tstd::cout << \"need to fix here, face degeneration\" << std::endl;\n\t\t\t\t\texit(0);\n\t\t\t\t}\n\n\t\t\t\tif (dege == FastEnvelope::NERLY_DEGENERATED) {\n\t\t\t\t\tnormal = FastEnvelope::accurate_normal_vector(face_vertices[p_face[j][0]], face_vertices[p_face[j][1]],\n\t\t\t\t\t\tface_vertices[p_face[j][0]], face_vertices[p_face[j][2]]);\n\t\t\t\t}\n\t\t\t\tif (dege == FastEnvelope::NOT_DEGENERATED) {\n\t\t\t\t\tnormal = ((face_vertices[p_face[j][0]] - face_vertices[p_face[j][1]]).cross(face_vertices[p_face[j][0]] - face_vertices[p_face[j][2]])).normalized();\n\t\t\t\t}\n#endif\n\t\t\t\tpoints.clear();\n\t\t\t\tpoints.resize(p_facepoint[j].size());\n\t\t\t\tfor (int k = 0; k < p_facepoint[j].size(); k++) {\n\t\t\t\t\tpoints[k] = face_vertices[p_facepoint[j][k]];\n\t\t\t\t}\n\n\t\t\t\tM.emplace_back();\n\t\t\t\tbuild_obb(points, normal, OBB_OFFSET, M.back().Trans, M.back().invTrans);\n\t\t\t}\n\n\t\t}\n\n\t\tif (face_vertices.size() == polyhedron_point_number2) {\n\t\t\tM.resize(polyhedron_face_number2);\n\n\t\t\tfor (int j = 0; j < polyhedron_face_number2; j++) {\n#ifdef DO_NOT_HAVE_DEGENERATED_FACES\n\t\t\t\tif (((face_vertices[c_face[j][0]] - face_vertices[c_face[j][1]]).cross(\n\t\t\t\t\tface_vertices[c_face[j][0]] - face_vertices[c_face[j][2]])).norm() < SCALAR_ZERO)\n\t\t\t\t\tnormal = FastEnvelope::accurate_normal_vector(face_vertices[c_face[j][0]], face_vertices[c_face[j][1]],\n\t\t\t\t\t\tface_vertices[c_face[j][0]], face_vertices[c_face[j][2]]);\n\t\t\t\telse {\n\t\t\t\t\tnormal = (face_vertices[c_face[j][0]] - face_vertices[c_face[j][1]]).cross(face_vertices[c_face[j][0]] - face_vertices[c_face[j][2]]).normalized();\n\t\t\t\t}\n#else\t\t\t\t\n\n\n\n\t\t\t\t//triangle to get normal: {envelope_vertices[i][p_face[j][0]],envelope_vertices[i][p_face[j][1]],envelope_vertices[i][p_face[j][2]]}\n\n\t\t\t\tdege = FastEnvelope::is_triangle_degenerated(face_vertices[c_face[j][0]], face_vertices[c_face[j][1]], face_vertices[c_face[j][2]]);\n\t\t\t\tif (dege == FastEnvelope::DEGENERATED_SEGMENT || dege == FastEnvelope::DEGENERATED_POINT) {\n\t\t\t\t\tstd::cout << \"need to fix here, face degeneration\" << std::endl;\n\t\t\t\t\texit(0);\n\t\t\t\t}\n\n\t\t\t\tif (dege == FastEnvelope::NERLY_DEGENERATED) {\n\t\t\t\t\tnormal = FastEnvelope::accurate_normal_vector(face_vertices[c_face[j][0]], face_vertices[c_face[j][1]],\n\t\t\t\t\t\tface_vertices[c_face[j][0]], face_vertices[c_face[j][2]]);\n\t\t\t\t}\n\t\t\t\tif (dege == FastEnvelope::NOT_DEGENERATED) {\n\t\t\t\t\tnormal = (face_vertices[c_face[j][0]] - face_vertices[c_face[j][1]]).cross(face_vertices[c_face[j][0]] - face_vertices[c_face[j][2]]).normalized();\n\t\t\t\t}\n\n#endif\n\t\t\t\tpoints.clear();\n\t\t\t\tpoints.resize(c_facepoint[j].size());\n\t\t\t\tfor (int k = 0; k < c_facepoint[j].size(); k++) {\n\t\t\t\t\tpoints[k] = face_vertices[c_facepoint[j][k]];\n\t\t\t\t}\n\n\t\t\t\tM.emplace_back();\n\t\t\t\tbuild_obb(points, normal, OBB_OFFSET, M.back().Trans, M.back().invTrans);\n\t\t\t}\n\t\t}\n\t\treturn M;\n\n\t}\n\n\tbool obb::intersects(const obb& M2) const {\n\t\treturn obb_intersection(Trans, invTrans, M2.Trans, M2.invTrans);\n\t}\n\n\tbool obb::intersects(const obb& M2, const obb& M3) const {\n\n\t\t//bool flag1=obb_intersection(Trans, invTrans, M2.Trans, M2.invTrans);\n\t\tbool flag1 = intersects(M2);\n\t\tif (flag1 == false) return false;\n\n\t\t//bool flag2 = obb_intersection(Trans, invTrans, M3.Trans, M3.invTrans);\n\t\tbool flag2 = intersects(M3);\n\t\tif (flag2 == false) return false;\n\n\t\t//bool flag3 = obb_intersection(M2.Trans, M2.invTrans, M3.Trans, M3.invTrans);\n\t\tbool flag3 = M2.intersects(M3);\n\t\tif (flag3 == false) return false;\n\n\t\treturn true;\n\t}\n\n\tobb obb::build_triangle_obb_matrixs(const Vector3&t0, const Vector3&t1, const Vector3&t2) {\n\t\tVector3 normal;\n\t\tobb res;\n\t\tif (((t0 - t1).cross(t0 - t2)).norm() < SCALAR_ZERO)\n\t\t\tnormal = FastEnvelope::accurate_normal_vector(t0, t1,\n\t\t\t\tt0, t2);\n\t\telse {\n\t\t\tnormal = ((t0 - t1).cross(t0 - t2)).normalized();\n\t\t}\n\t\tstd::vector<Vector3> points(3);\n\t\tpoints[0] = t0; points[1] = t1; points[2] = t2;\n\t\tbuild_obb(points, normal, OBB_OFFSET, res.Trans, res.invTrans);\n\t\treturn res;\n\t}\n\n\tvoid obb::build_obb(const std::vector<Vector3>& points, const Vector3& normal, const Scalar offset,\n\t\tEigen::Matrix4d &M, Eigen::Matrix4d &invM)\n\t{\n\t\tEigen::MatrixXd  PS(3, points.size()), PS1(3, points.size());\n\t\tVector3 cent;\n\t\tcent <<\n\t\t\t0, 0, 0;\n\n\t\tfor (int i = 0; i < points.size(); i++) {\n\t\t\tPS(0, i) = points[i][0];\n\t\t\tPS(1, i) = points[i][1];\n\t\t\tPS(2, i) = points[i][2];\n\n\t\t}\n\t\tcent[0] = PS.row(0).sum() / points.size();\n\t\tcent[1] = PS.row(1).sum() / points.size();\n\t\tcent[2] = PS.row(2).sum() / points.size();\n\t\tPS1.row(0) = PS.row(0) - Eigen::MatrixXd::Ones(1, points.size())*cent[0];\n\t\tPS1.row(1) = PS.row(1) - Eigen::MatrixXd::Ones(1, points.size())*cent[1];\n\t\tPS1.row(2) = PS.row(2) - Eigen::MatrixXd::Ones(1, points.size())*cent[2];\n\t\tEigen::MatrixXd PCA = PS1 * PS1.transpose();\n\t\tEigen::EigenSolver<Eigen::MatrixXd> eg(PCA);\n\t\tEigen::VectorXcd ev = eg.eigenvalues();\n\n\t\tint maxid = 0;\n\n\t\tfor (int i = 1; i < 3; i++) {\n\n\t\t\tif (ev[maxid].real() <= ev(i).real()) {\n\t\t\t\tmaxid = i;\n\t\t\t}\n\t\t}\n\t\tassert(ev(maxid).real() > 0);\n\t\tEigen::VectorXcd v = eg.eigenvectors().col(maxid);\n\t\tVector3 y;\n\t\ty[0] = v[0].real(); y[1] = v[1].real(); y[2] = v[2].real();\n\t\ty = y.normalized();\n\t\tassert(normal.dot(y) < SCALAR_ZERO);\n\n\t\tVector3 z = normal.cross(y);\n\t\tMatrix3 R;\n\t\tR.col(0) = normal;\n\t\tR.col(1) = y;\n\t\tR.col(2) = z;\n\n\t\tMatrix3 invR = R.transpose();//inv(R)=trans(R)\n\t\tVector3 T0 = -1 * R*cent, T1;//R*cent+T0=[0,0,0]\n\t\tEigen::Matrix4d Trans0, invTrans0, Trans1, invTrans1, Scalling, invScalling;\n\n\t\tTrans0 << R, T0,\n\t\t\t0, 0, 0, 1;\n\t\tinvTrans0 << invR, cent,\n\t\t\t0, 0, 0, 1;\n\t\tEigen::MatrixXd  PSG(4, points.size()), prog(4, points.size());\n\t\tPSG << PS,\n\t\t\tEigen::MatrixXd::Ones(1, points.size());\n\t\tprog = Trans0 * PSG;//contains the projection of the points in new axis\n\t\tVector3 min, max, mid, corner;\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tmin[i] = prog.row(i).minCoeff();\n\t\t\tmax[i] = prog.row(i).maxCoeff();\n\t\t}\n\t\tmid = (min + max) / 2;\n\t\tcorner = max - mid + Vector3(offset, offset, offset);\n\t\tEigen::MatrixXd procg(4, 1), centng(4, 1), centn(3, 1);\n\t\tprocg << mid,\n\t\t\t1;\n\t\tcentng = invTrans0 * procg;\n\t\tcentn(0) = centng(0); centn(1) = centng(1); centn(2) = centng(2);\n\t\tT1 = -1 * R*centn;\n\t\tTrans1 << R, T1,\n\t\t\t0, 0, 0, 1;\n\t\tinvTrans1 << invR, centn,\n\t\t\t0, 0, 0, 1;\n\t\tScalling = Eigen::Matrix4d::Zero(4, 4);\n\t\tScalling(0, 0) = corner(0);\n\t\tScalling(1, 1) = corner(1);\n\t\tScalling(2, 2) = corner(2);\n\t\tScalling(3, 3) = 1;\n\t\tinvScalling = Scalling.inverse();\n\t\tM = invScalling * Trans1;\n\t\tinvM = invTrans1 * Scalling;\n\t}\n\n\tbool obb::obb_intersection(const Eigen::Matrix4d &M1, const Eigen::Matrix4d &invM1, const Eigen::Matrix4d &M2, const Eigen::Matrix4d &invM2) {\n\n\t\tEigen::MatrixXd ub(8, 4);\n\n\t\tub << -1, -1, -1, 1,\n\t\t\t1, -1, -1, 1,\n\t\t\t1, 1, -1, 1,\n\t\t\t-1, 1, -1, 1,\n\t\t\t-1, 1, 1, 1,\n\t\t\t-1, -1, 1, 1,\n\t\t\t1, -1, 1, 1,\n\t\t\t1, 1, 1, 1;\n\t\tEigen::MatrixXd b21(4, 8), b12(4, 8);\n\n\t\tScalar minx, miny, minz, maxx, maxy, maxz;\n\n\t\tb12 = M2 * invM1*ub.transpose();\n\n\t\tminx = b12.row(0).minCoeff();\n\t\tif (minx >= 1) return false;\n\t\tminy = b12.row(1).minCoeff();\n\t\tif (miny >= 1) return false;\n\t\tminz = b12.row(2).minCoeff();\n\t\tif (minz >= 1) return false;\n\n\t\tmaxx = b12.row(0).maxCoeff();\n\t\tif (maxx <= -1) return false;\n\t\tmaxy = b12.row(1).maxCoeff();\n\t\tif (maxy <= -1) return false;\n\t\tmaxz = b12.row(2).maxCoeff();\n\t\tif (maxz <= -1) return false;\n\n\t\tb21 = M1 * invM2*ub.transpose();\n\n\t\tminx = b21.row(0).minCoeff();\n\t\tif (minx >= 1) return false;\n\t\tminy = b21.row(1).minCoeff();\n\t\tif (miny >= 1) return false;\n\t\tminz = b21.row(2).minCoeff();\n\t\tif (minz >= 1) return false;\n\n\t\tmaxx = b21.row(0).maxCoeff();\n\t\tif (maxx <= -1) return false;\n\t\tmaxy = b21.row(1).maxCoeff();\n\t\tif (maxy <= -1) return false;\n\t\tmaxz = b21.row(2).maxCoeff();\n\t\tif (maxz <= -1) return false;\n\n\n\t\treturn true;\n\n\t}\n#include <time.h>\n\tvoid obb::test() {\n\t\tstd::vector<Vector3> p, p1;\n\t\tVector3 dis;\n\t\tsrand(int(time(0)));\n\t\tdis = Vector3(rand() % 100, rand() % 100, rand() % 100) / 50;\n\t\tp.resize(20);\n\t\tfor (int i = 0; i < p.size(); i++) {\n\t\t\tp[i] = Vector3(rand() % 100, rand() % 100, rand() % 100) / 100 + dis;\n\t\t}\n\t\tEigen::MatrixXd  PS(3, p.size());\n\n\n\t\tfor (int i = 0; i < p.size(); i++) {\n\t\t\tPS(0, i) = p[i][0];\n\t\t\tPS(1, i) = p[i][1];\n\t\t\tPS(2, i) = p[i][2];\n\n\t\t}\n\n\t\tEigen::MatrixXd PCA = PS * PS.transpose();\n\t\tEigen::EigenSolver<Eigen::MatrixXd> eg(PCA);\n\t\tEigen::VectorXcd ev = eg.eigenvalues();\n\n\t\tint minid = 0;\n\n\t\tfor (int i = 1; i < 3; i++) {\n\n\t\t\tif (ev[minid].real() >= ev(i).real()) {//find the minimal eigenvalue\n\t\t\t\tminid = i;\n\t\t\t}\n\t\t}\n\n\t\tEigen::VectorXcd v = eg.eigenvectors().col(minid);\n\t\tVector3 normal;\n\t\tnormal[0] = v[0].real(); normal[1] = v[1].real(); normal[2] = v[2].real();\n\t\tScalar offset = 0.1;\n\t\tEigen::Matrix4d M, invM;\n\t\tbuild_obb(p, normal, offset, M, invM);\n\t\tstd::ofstream fout;\n\t\tfout.open(\"D:\\\\vs\\\\fast_envelope\\\\obb\\\\points.txt\");\n\n\t\tfor (int i = 0; i < p.size(); i++) {\n\n\t\t\tfout << std::setprecision(17) << p[i][0] << \" \" << p[i][1] << \" \" << p[i][2] << std::endl;\n\n\t\t}\n\t\tfout.close();\n\t\tfout.open(\"D:\\\\vs\\\\fast_envelope\\\\obb\\\\matrixes.txt\");\n\n\t\tfor (int i = 0; i < 4; i++) {\n\n\t\t\tfout << std::setprecision(17) << M(i, 0) << \" \" << M(i, 1) << \" \" << M(i, 2) << \" \" << M(i, 3) << std::endl;\n\n\t\t}\n\t\tfor (int i = 0; i < 4; i++) {\n\n\t\t\tfout << std::setprecision(17) << invM(i, 0) << \" \" << invM(i, 1) << \" \" << invM(i, 2) << \" \" << invM(i, 3) << std::endl;\n\n\t\t}\n\n\t\tfout.close();\n\n\n\n\n\t\t//////////////////////////\n\n\t\t//srand(int(time(0)));\n\t\tdis = Vector3(rand() % 100, rand() % 100, rand() % 100) / 100 * 3;\n\t\tp.clear();\n\t\tp.resize(20);\n\t\tfor (int i = 0; i < p.size(); i++) {\n\t\t\tp[i] = Vector3(rand() % 100, rand() % 100, rand() % 100) / 100 + dis;\n\t\t}\n\t\tEigen::MatrixXd  PS1(3, p.size());\n\n\n\t\tfor (int i = 0; i < p.size(); i++) {\n\t\t\tPS1(0, i) = p[i][0];\n\t\t\tPS1(1, i) = p[i][1];\n\t\t\tPS1(2, i) = p[i][2];\n\n\t\t}\n\n\t\tEigen::MatrixXd PCA1 = PS1 * PS1.transpose();\n\t\tEigen::EigenSolver<Eigen::MatrixXd> eg1(PCA1);\n\t\tEigen::VectorXcd ev1 = eg1.eigenvalues();\n\n\t\tminid = 0;\n\n\t\tfor (int i = 1; i < 3; i++) {\n\n\t\t\tif (ev1[minid].real() >= ev1(i).real()) {//find the minimal eigenvalue\n\t\t\t\tminid = i;\n\t\t\t}\n\t\t}\n\n\t\tEigen::VectorXcd v1 = eg1.eigenvectors().col(minid);\n\n\t\tnormal[0] = v1[0].real(); normal[1] = v1[1].real(); normal[2] = v1[2].real();\n\n\t\tEigen::Matrix4d M1, invM1;\n\t\tbuild_obb(p, normal, offset, M1, invM1);\n\n\t\tfout.open(\"D:\\\\vs\\\\fast_envelope\\\\obb\\\\points1.txt\");\n\n\t\tfor (int i = 0; i < p.size(); i++) {\n\n\t\t\tfout << std::setprecision(17) << p[i][0] << \" \" << p[i][1] << \" \" << p[i][2] << std::endl;\n\n\t\t}\n\t\tfout.close();\n\t\tfout.open(\"D:\\\\vs\\\\fast_envelope\\\\obb\\\\matrixes1.txt\");\n\n\t\tfor (int i = 0; i < 4; i++) {\n\n\t\t\tfout << std::setprecision(17) << M1(i, 0) << \" \" << M1(i, 1) << \" \" << M1(i, 2) << \" \" << M1(i, 3) << std::endl;\n\n\t\t}\n\t\tfor (int i = 0; i < 4; i++) {\n\n\t\t\tfout << std::setprecision(17) << invM1(i, 0) << \" \" << invM1(i, 1) << \" \" << invM1(i, 2) << \" \" << invM1(i, 3) << std::endl;\n\n\t\t}\n\n\t\tfout.close();\n\n\t\tstd::cout << \"is intersected? \" << obb_intersection(M, invM, M1, invM1) << std::endl;\n\t}\n}", "meta": {"hexsha": "0e0e1518d556616b5baa2689a353b74bea82ffe2", "size": 12612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/obb.cpp", "max_stars_repo_name": "dcoeurjo/fast-envelope", "max_stars_repo_head_hexsha": "0d58124c589bed510acb83567674b8531e71a7e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2020-04-27T17:55:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T07:54:37.000Z", "max_issues_repo_path": "src/obb.cpp", "max_issues_repo_name": "dcoeurjo/fast-envelope", "max_issues_repo_head_hexsha": "0d58124c589bed510acb83567674b8531e71a7e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-08-28T15:22:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-27T07:48:43.000Z", "max_forks_repo_path": "src/obb.cpp", "max_forks_repo_name": "dcoeurjo/fast-envelope", "max_forks_repo_head_hexsha": "0d58124c589bed510acb83567674b8531e71a7e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T21:32:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T22:52:46.000Z", "avg_line_length": 30.9117647059, "max_line_length": 154, "alphanum_fraction": 0.5975261656, "num_tokens": 4621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.49609382947091957, "lm_q1q2_score": 0.40674402477103316}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/*\n *   File \"lstm_b_tapenade_generated.c\" is generated by Tapenade 3.14 (r7259) from this file.\n *   To reproduce such a generation you can use Tapenade CLI\n *   (can be downloaded from http://www-sop.inria.fr/tropics/tapenade/downloading.html)\n *\n *   After installing use the next command to generate a file:\n *\n *      tapenade -b -o lstm_tapenade -head \"lstm_objective(loss)/(main_params extra_params)\" lstm.c\n *\n *   This will produce a file \"lstm_tapenade_b.c\" which content will be the same as the content of the file \"lstm_b_tapenade_generated.c\",\n *   except one-line header. Moreover a log-file \"lstm_tapenade_b.msg\" will be produced.\n *\n *   NOTE: the code in \"lstm_b_tapenade_generated.c\" is wrong and won't work.\n *         REPAIRED SOURCE IS STORED IN THE FILE \"lstm_b.c\".\n *         You can either use diff tool or read \"lstm_b.c\" header to figure out what changes was performed to fix the code.\n *\n *   NOTE: you can also use Tapenade web server (http://tapenade.inria.fr:8080/tapenade/index.jsp)\n *         for generating but the result can be slightly different.\n */\n\n#include \"../adbench/lstm.h\"\n\nextern \"C\" {\n#include \"lstm.h\"\n\n// UTILS\n// Sigmoid on scalar\ndouble sigmoid(double x)\n{\n    return 1.0 / (1.0 + exp(-x));\n}\n\n// log(sum(exp(x), 2))\ndouble logsumexp(double const* vect, int sz)\n{\n    double sum = 0.0;\n    int i;\n\n    for (i = 0; i < sz; i++)\n    {\n        sum += exp(vect[i]);\n    }\n\n    sum += 2;\n    return log(sum);\n}\n\n// LSTM OBJECTIVE\n// The LSTM model\nvoid lstm_model(\n    int hsize,\n    double const* __restrict weight,\n    double const* __restrict bias,\n    double* __restrict hidden,\n    double* __restrict cell,\n    double const* __restrict input\n)\n{\n    // TODO NOTE THIS\n    //__builtin_assume(hsize > 0);\n\n    double* gates = (double*)malloc(4 * hsize * sizeof(double));\n    double* forget = &(gates[0]);\n    double* ingate = &(gates[hsize]);\n    double* outgate = &(gates[2 * hsize]);\n    double* change = &(gates[3 * hsize]);\n\n    int i;\n    // caching input\n    // hidden (needed)\n    for (i = 0; i < hsize; i++)\n    {\n        forget[i] = sigmoid(input[i] * weight[i] + bias[i]);\n        ingate[i] = sigmoid(hidden[i] * weight[hsize + i] + bias[hsize + i]);\n        outgate[i] = sigmoid(input[i] * weight[2 * hsize + i] + bias[2 * hsize + i]);\n        change[i] = tanh(hidden[i] * weight[3 * hsize + i] + bias[3 * hsize + i]);\n    }\n\n    // caching cell (needed)\n    for (i = 0; i < hsize; i++)\n    {\n        cell[i] = cell[i] * forget[i] + ingate[i] * change[i];\n    }\n\n    for (i = 0; i < hsize; i++)\n    {\n        hidden[i] = outgate[i] * tanh(cell[i]);\n    }\n\n    free(gates);\n}\n\n// Predict LSTM output given an input\nvoid lstm_predict(\n    int l,\n    int b,\n    double const* __restrict w,\n    double const* __restrict w2,\n    double* __restrict s,\n    double const* __restrict x,\n    double* __restrict x2\n)\n{\n    int i;\n    for (i = 0; i < b; i++)\n    {\n        x2[i] = x[i] * w2[i];\n    }\n\n    double* xp = x2;\n    for (i = 0; i <= 2 * l * b - 1; i += 2 * b)\n    {\n        lstm_model(b, &(w[i * 4]), &(w[(i + b) * 4]), &(s[i]), &(s[i + b]), xp);\n        xp = &(s[i]);\n    }\n\n    for (i = 0; i < b; i++)\n    {\n        x2[i] = xp[i] * w2[b + i] + w2[2 * b + i];\n    }\n}\n\n// LSTM objective (loss function)\nvoid lstm_objective(\n    int l,\n    int c,\n    int b,\n    double const* __restrict main_params,\n    double const* __restrict extra_params,\n    double* __restrict state,\n    double const* __restrict sequence,\n    double* __restrict loss\n)\n{\n    int i, t;\n    double total = 0.0;\n    int count = 0;\n    const double* input = &(sequence[0]);\n    double* ypred = (double*)malloc(b * sizeof(double));\n    double* ynorm = (double*)malloc(b * sizeof(double));\n    const double* ygold;\n    double lse;\n\n    __builtin_assume(b>0);\n    for (t = 0; t <= (c - 1) * b - 1; t += b)\n    {\n        lstm_predict(l, b, main_params, extra_params, state, input, ypred);\n        lse = logsumexp(ypred, b);\n        for (i = 0; i < b; i++)\n        {\n            ynorm[i] = ypred[i] - lse;\n        }\n\n        ygold = &(sequence[t + b]);\n        for (i = 0; i < b; i++)\n        {\n            total += ygold[i] * ynorm[i];\n        }\n\n        count += b;\n        input = ygold;\n    }\n\n    *loss = -total / count;\n\n    free(ypred);\n    free(ynorm);\n}\n\nextern int enzyme_const;\nextern int enzyme_dup;\nextern int enzyme_dupnoneed;\nvoid __enzyme_autodiff(...) noexcept;\n\n// *      tapenade -b -o lstm_tapenade -head \"lstm_objective(loss)/(main_params extra_params)\" lstm.c\n\nvoid dlstm_objective(\n    int l,\n    int c,\n    int b,\n    double const* main_params,\n    double* dmain_params,\n    double const* extra_params,\n    double* dextra_params,\n    double* state,\n    double const* sequence,\n    double* loss,\n    double* dloss\n)\n{\n    __enzyme_autodiff(lstm_objective,\n        enzyme_const, l,\n        enzyme_const, c,\n        enzyme_const, b,\n        enzyme_dup, main_params, dmain_params,\n        enzyme_dup, extra_params, dextra_params,\n        enzyme_const, state,\n        enzyme_const, sequence,\n        enzyme_dupnoneed, loss, dloss\n    );\n}\n\n}\n\n\n//! Tapenade\nextern \"C\" {\n\n#include <adBuffer.h>\n\n/*\n  Differentiation of sigmoid in reverse (adjoint) mode:\n   gradient     of useful results: sigmoid\n   with respect to varying inputs: x\n*/\n// UTILS\n// Sigmoid on scalar\nvoid sigmoid_b(double x, double *xb, double sigmoidb) {\n    double temp;\n    double sigmoid;\n    temp = exp(-x) + 1.0;\n    *xb = exp(-x)*sigmoidb/(temp*temp);\n}\n\n// UTILS\n// Sigmoid on scalar\ndouble sigmoid_nodiff(double x) {\n    return 1.0/(1.0+exp(-x));\n}\n\n/*\n  Differentiation of logsumexp in reverse (adjoint) mode:\n   gradient     of useful results: logsumexp *vect\n   with respect to varying inputs: *vect\n   Plus diff mem management of: vect:in\n*/\n// log(sum(exp(x), 2))\nvoid logsumexp_b(const double *vect, double *vectb, int sz, double logsumexpb)\n{\n    double sum = 0.0;\n    double sumb = 0.0;\n    int i;\n    double logsumexp;\n    for (i = 0; i < sz; ++i)\n        sum = sum + exp(vect[i]);\n    sum = sum + 2;\n    sumb = logsumexpb/sum;\n    for (i = sz-1; i > -1; --i)\n        vectb[i] = vectb[i] + exp(vect[i])*sumb;\n}\n\n// log(sum(exp(x), 2))\ndouble logsumexp_nodiff(const double *vect, int sz) {\n    double sum = 0.0;\n    int i;\n    for (i = 0; i < sz; ++i)\n        sum += exp(vect[i]);\n    sum += 2;\n    return log(sum);\n}\n\n/*\n  Differentiation of lstm_model in reverse (adjoint) mode:\n   gradient     of useful results: alloc(*gates) *cell *bias *hidden\n                *weight *input\n   with respect to varying inputs: alloc(*gates) *cell *bias *hidden\n                *weight *input\n   Plus diff mem management of: cell:in bias:in hidden:in weight:in\n                input:in\n*/\n// LSTM OBJECTIVE\n// The LSTM model\nvoid lstm_model_b(int hsize, const double *weight, double *weightb, const\n        double *bias, double *biasb, double *hidden, double *hiddenb, double *\n        cell, double *cellb, const double *input, double *inputb) {\n    double *gates;\n    double *gatesb;\n    double arg1;\n    double arg1b;\n    int ii1;\n    double temp;\n    double tempb;\n    gatesb = (double *)malloc(4*hsize*sizeof(double));\n    for (ii1 = 0; ii1 < 4*hsize; ++ii1)\n        gatesb[ii1] = 0.0;\n    gates = (double *)malloc(4*hsize*sizeof(double));\n    double *forget = &(gates[0]);\n    double *forgetb = &(gatesb[0]);\n    double *ingate = &(gates[hsize]);\n    double *ingateb = &(gatesb[hsize]);\n    double *outgate = &(gates[2*hsize]);\n    double *outgateb = &(gatesb[2*hsize]);\n    double *change = &(gates[3*hsize]);\n    double *changeb = &(gatesb[3*hsize]);\n    int i;\n    for (i = 0; i < hsize; ++i) {\n        arg1 = input[i]*weight[i] + bias[i];\n        forget[i] = sigmoid_nodiff(arg1);\n        arg1 = hidden[i]*weight[hsize+i] + bias[hsize + i];\n        ingate[i] = sigmoid_nodiff(arg1);\n        arg1 = input[i]*weight[2*hsize+i] + bias[2*hsize + i];\n        outgate[i] = sigmoid_nodiff(arg1);\n        change[i] = tanh(hidden[i]*weight[3*hsize+i] + bias[3*hsize + i]);\n    }\n    for (i = 0; i < hsize; ++i) {\n        pushReal8(cell[i]);\n        cell[i] = cell[i]*forget[i] + ingate[i]*change[i];\n    }\n    for (i = hsize-1; i > -1; --i) {\n        outgateb[i] = outgateb[i] + tanh(cell[i])*hiddenb[i];\n        cellb[i] = cellb[i] + outgate[i]*(1.0-tanh(cell[i])*tanh(cell[i]))*\n            hiddenb[i];\n        hiddenb[i] = 0.0;\n    }\n    for (i = hsize-1; i > -1; --i) {\n        popReal8(&(cell[i]));\n        forgetb[i] = forgetb[i] + cell[i]*cellb[i];\n        ingateb[i] = ingateb[i] + change[i]*cellb[i];\n        changeb[i] = changeb[i] + ingate[i]*cellb[i];\n        cellb[i] = forget[i]*cellb[i];\n    }\n    for (i = hsize-1; i > -1; --i) {\n        temp = weight[3*hsize + i];\n        tempb = (1.0-tanh(hidden[i]*temp+bias[3*hsize+i])*tanh(hidden[i]*temp+\n            bias[3*hsize+i]))*changeb[i];\n        hiddenb[i] = hiddenb[i] + temp*tempb;\n        weightb[3*hsize + i] = weightb[3*hsize + i] + hidden[i]*tempb;\n        biasb[3*hsize + i] = biasb[3*hsize + i] + tempb;\n        changeb[i] = 0.0;\n        arg1 = input[i]*weight[2*hsize+i] + bias[2*hsize + i];\n        sigmoid_b(arg1, &arg1b, outgateb[i]);\n        outgateb[i] = 0.0;\n        inputb[i] = inputb[i] + weight[2*hsize+i]*arg1b;\n        weightb[2*hsize + i] = weightb[2*hsize + i] + input[i]*arg1b;\n        biasb[2*hsize + i] = biasb[2*hsize + i] + arg1b;\n        arg1 = hidden[i]*weight[hsize+i] + bias[hsize + i];\n        sigmoid_b(arg1, &arg1b, ingateb[i]);\n        ingateb[i] = 0.0;\n        hiddenb[i] = hiddenb[i] + weight[hsize+i]*arg1b;\n        weightb[hsize + i] = weightb[hsize + i] + hidden[i]*arg1b;\n        biasb[hsize + i] = biasb[hsize + i] + arg1b;\n        arg1 = input[i]*weight[i] + bias[i];\n        sigmoid_b(arg1, &arg1b, forgetb[i]);\n        forgetb[i] = 0.0;\n        inputb[i] = inputb[i] + weight[i]*arg1b;\n        weightb[i] = weightb[i] + input[i]*arg1b;\n        biasb[i] = biasb[i] + arg1b;\n    }\n    free(gates);\n    free(gatesb);\n}\n\n// LSTM OBJECTIVE\n// The LSTM model\nvoid lstm_model_nodiff(int hsize, const double *weight, const double *bias,\n        double *hidden, double *cell, const double *input) {\n    double *gates;\n    double arg1;\n    gates = (double *)malloc(4*hsize*sizeof(double));\n    double *forget = &(gates[0]);\n    double *ingate = &(gates[hsize]);\n    double *outgate = &(gates[2*hsize]);\n    double *change = &(gates[3*hsize]);\n    int i;\n    for (i = 0; i < hsize; ++i) {\n        arg1 = input[i]*weight[i] + bias[i];\n        forget[i] = sigmoid_nodiff(arg1);\n        arg1 = hidden[i]*weight[hsize+i] + bias[hsize + i];\n        ingate[i] = sigmoid_nodiff(arg1);\n        arg1 = input[i]*weight[2*hsize+i] + bias[2*hsize + i];\n        outgate[i] = sigmoid_nodiff(arg1);\n        change[i] = tanh(hidden[i]*weight[3*hsize+i] + bias[3*hsize + i]);\n    }\n    for (i = 0; i < hsize; ++i)\n        cell[i] = cell[i]*forget[i] + ingate[i]*change[i];\n    for (i = 0; i < hsize; ++i)\n        hidden[i] = outgate[i]*tanh(cell[i]);\n    free(gates);\n}\n\n/*\n  Differentiation of lstm_predict in reverse (adjoint) mode:\n   gradient     of useful results: alloc(*gates) *s *w *w2 *x2\n   with respect to varying inputs: alloc(*gates) *s *w *w2 *x2\n   Plus diff mem management of: s:in w:in w2:in x2:in\n*/\n// Predict LSTM output given an input\nvoid lstm_predict_b(int l, int b, const double *w, double *wb, const double *\n        w2, double *w2b, double *s, double *sb, const double *x, double *x2,\n        double *x2b) {\n    int i;\n    double tmp;\n    double tmpb;\n    for (i = 0; i < b; ++i) {\n        pushReal8(x2[i]);\n        x2[i] = x[i]*w2[i];\n    }\n    double *xp = x2;\n    double *xpb = x2b;\n    for (i = 0; i <= 2*l*b-1; i += 2*b) {\n        pushReal8Array(s + i, 2 * b); /* TFIX */\n        lstm_model_nodiff(b, &(w[i*4]), &(w[(i+b)*4]), &(s[i]), &(s[i + b]),\n                          xp);\n        pushPointer8(xpb);\n        xpb = &(sb[i]);\n        pushPointer8(xp);\n        xp = &(s[i]);\n    }\n    for (i = 0; i < b; ++i) {\n        tmp = xp[i]*w2[b+i] + w2[2*b + i];\n        pushReal8(x2[i]);\n        x2[i] = tmp;\n    }\n    for (i = b-1; i > -1; --i) {\n        popReal8(&(x2[i]));\n        tmpb = x2b[i];\n        x2b[i] = 0.0;\n        xpb[i] = xpb[i] + w2[b+i]*tmpb;\n        w2b[b + i] = w2b[b + i] + xp[i]*tmpb;\n        w2b[2*b + i] = w2b[2*b + i] + tmpb;\n    }\n    for (i = 2*l*b-(2*l*b-1)%(2*b)-1; i >= 0; i += -(2*b)) { /* TFIX */\n        popPointer8((void **)&xp);\n        popPointer8((void **)&xpb);\n        popReal8Array(s + i, 2 * b); /* TFIX */\n        lstm_model_b(b, &(w[i*4]), &(wb[i*4]), &(w[(i+b)*4]), &(wb[(i+b)*4]),\n                     &(s[i]), &(sb[i]), &(s[i + b]), &(sb[i + b]), xp, xpb);\n    }\n    for (i = b-1; i > -1; --i) {\n        popReal8(&(x2[i]));\n        w2b[i] = w2b[i] + x[i]*x2b[i];\n        x2b[i] = 0.0;\n    }\n}\n\n// Predict LSTM output given an input\nvoid lstm_predict_nodiff(int l, int b, const double *w, const double *w2,\n        double *s, const double *x, double *x2) {\n    int i;\n    for (i = 0; i < b; ++i)\n        x2[i] = x[i]*w2[i];\n    double *xp = x2;\n    for (i = 0; i <= 2*l*b-1; i += 2*b) {\n        lstm_model_nodiff(b, &(w[i*4]), &(w[(i+b)*4]), &(s[i]), &(s[i + b]),\n                          xp);\n        xp = &(s[i]);\n    }\n    for (i = 0; i < b; ++i)\n        x2[i] = xp[i]*w2[b+i] + w2[2*b + i];\n}\n\n/*\n  Differentiation of lstm_objective in reverse (adjoint) mode:\n   gradient     of useful results: *loss\n   with respect to varying inputs: *main_params *extra_params\n                *loss\n   RW status of diff variables: *main_params:out *extra_params:out\n                *loss:in-out\n   Plus diff mem management of: extra_params:in loss:in\n*/\n// LSTM objective (loss function)\nvoid lstm_objective_b(int l, int c, int b, const double *main_params, double *\n        main_paramsb, const double *extra_params, double *extra_paramsb,\n        double *state, const double *sequence, double *loss, double *lossb) {\n    int i, t;\n    double total = 0.0;\n    double totalb = 0.0;\n    int count = 0;\n    const double *input = &(sequence[0]);\n    double *ypred;\n    double *ypredb;\n    int ii1;\n    int branch;\n    double* stateb = (double*)malloc(2 * l * b * sizeof(double)); /* TFIX */\n    ypredb = (double *)malloc(b*sizeof(double));\n    for (ii1 = 0; ii1 < b; ++ii1)\n        ypredb[ii1] = 0.0;\n    ypred = (double *)malloc(b*sizeof(double));\n    double *ynorm;\n    double *ynormb;\n    ynormb = (double *)malloc(b*sizeof(double));\n    for (ii1 = 0; ii1 < b; ++ii1)\n        ynormb[ii1] = 0.0;\n    ynorm = (double *)malloc(b*sizeof(double));\n    const double* ygold = NULL; /* TFIX */\n    double lse;\n    double lseb;\n    for (t = 0; t <= (c-1)*b-1; t += b) {\n        if (ypred) {\n            pushReal8Array(ypred, b); /* TFIX */\n            pushControl1b(1);\n        } else\n            pushControl1b(0);\n        pushReal8Array(state, 2 * b * l); /* TFIX */\n        lstm_predict_nodiff(l, b, main_params, extra_params, state, input,\n                            ypred);\n        pushPointer8((void*)ygold);\n        ygold = &(sequence[t + b]);\n        count = count + b;\n        pushPointer8((void*)input);\n        input = ygold;\n    }\n    totalb = -(*lossb/count);\n    *lossb = 0.0;\n    for (ii1 = 0; ii1 < 8 * l * b; ii1++) /* TFIX */\n        main_paramsb[ii1] = 0.0;\n    for (ii1 = 0; ii1 < 3 * b; ii1++) /* TFIX */\n        extra_paramsb[ii1] = 0.0;\n    for (t = 0; t < 2 * l * b; t++) /* TFIX */\n        stateb[t] = 0.0;\n    for (t = (c-1)*b-((c-1)*b-1)%b-1; t >= 0; t += -b) { /* TFIX */\n        popPointer8((void **)&input);\n        for (i = b-1; i > -1; --i)\n            ynormb[i] = ynormb[i] + ygold[i]*totalb;\n        popPointer8((void **)&ygold);\n        lseb = 0.0;\n        for (i = b-1; i > -1; --i) {\n            ypredb[i] = ypredb[i] + ynormb[i];\n            lseb = lseb - ynormb[i];\n            ynormb[i] = 0.0;\n        }\n        logsumexp_b(ypred, ypredb, b, lseb);\n        popReal8Array(state, 2 * b * l); /* TFIX */\n        popControl1b(&branch);\n        if (branch == 1)\n            popReal8Array(ypred, b); /* TFIX */\n        lstm_predict_b(l, b, main_params, main_paramsb, extra_params,\n                       extra_paramsb, state, stateb, input, ypred, ypredb);\n    }\n    free(ynorm);\n    free(ynormb);\n    free(ypred);\n    free(ypredb);\n    free(stateb); /* TFIX */ // Added to dispose memory allocated in repaired code\n}\n\n\n}\n\n\n#if 1\n//! Adept\n#include <adept_source.h>\n#include <adept.h>\n#include <adept_arrays.h>\nusing adept::adouble;\nusing adept::aVector;\n\nnamespace adeptTest {\n// Sigmoid on scalar\ntemplate<typename T>\nT sigmoid(T x) {\n    return adouble(1) / (adouble(1) + exp(-x));\n}\n\n// log(sum(exp(x), 2))\ntemplate<typename T>\nT logsumexp(const T* vect, int sz) {\n    T sum = 0.0;\n    for (int i = 0; i < sz; ++i)\n        sum += exp(vect[i]);\n    sum += adouble(2);\n    return log(sum);\n}\n\n// LSTM OBJECTIVE\n\n// The LSTM model\ntemplate<typename T>\nvoid lstm_model(\n    int hsize,\n    T* weight,\n    T* bias,\n    T* hidden,\n    T* cell,\n    T* input\n)\n{\n\n    T* gates = new T[4*hsize];\n    T* forget = &(gates[0]);\n    T* ingate = &(gates[hsize]);\n    T* outgate = &(gates[2 * hsize]);\n    T* change = &(gates[3 * hsize]);\n\n    int i;\n    // caching input\n    // hidden (needed)\n    for (i = 0; i < hsize; i++)\n    {\n        forget[i] = sigmoid<adouble>(input[i] * weight[i] + bias[i]);\n        ingate[i] = sigmoid<adouble>(hidden[i] * weight[hsize + i] + bias[hsize + i]);\n        outgate[i] = sigmoid<adouble>(input[i] * weight[2 * hsize + i] + bias[2 * hsize + i]);\n        change[i] = tanh(hidden[i] * weight[3 * hsize + i] + bias[3 * hsize + i]);\n    }\n\n    // caching cell (needed)\n    for (i = 0; i < hsize; i++)\n    {\n        cell[i] = cell[i] * forget[i] + ingate[i] * change[i];\n    }\n\n    for (i = 0; i < hsize; i++)\n    {\n        hidden[i] = outgate[i] * tanh(cell[i]);\n    }\n\n    delete[] gates;\n}\n\n// Predict LSTM output given an input\ntemplate<typename T>\nvoid lstm_predict(\n    int l,\n    int b,\n    T* w,\n    T* w2,\n    T* s,\n    T* x,\n    T* x2\n)\n{\n    int i;\n    for (i = 0; i < b; i++)\n    {\n        x2[i] = x[i] * w2[i];\n    }\n\n    T* xp = x2;\n    for (i = 0; i <= 2 * l * b - 1; i += 2 * b)\n    {\n        lstm_model(b, &(w[i * 4]), &(w[(i + b) * 4]), &(s[i]), &(s[i + b]), xp);\n        xp = &(s[i]);\n    }\n\n    for (i = 0; i < b; i++)\n    {\n        x2[i] = xp[i] * w2[b + i] + w2[2 * b + i];\n    }\n}\n\n// LSTM objective (loss function)\ntemplate<typename T>\nvoid lstm_objective(\n    int l,\n    int c,\n    int b,\n    T * __restrict main_params,\n    T * __restrict extra_params,\n    T* __restrict state,\n    T * __restrict sequence,\n    T* __restrict loss\n)\n{\n    int i, t;\n    T total = 0.0;\n    int count = 0;\n    T* input = &(sequence[0]);\n    T* ypred = new T[b];\n    T* ynorm = new T[b];\n    T* ygold;\n    T lse;\n\n    __builtin_assume(b>0);\n    for (t = 0; t <= (c - 1) * b - 1; t += b)\n    {\n        lstm_predict(l, b, main_params, extra_params, state, input, ypred);\n        lse = logsumexp(ypred, b);\n        for (i = 0; i < b; i++)\n        {\n            ynorm[i] = ypred[i] - lse;\n        }\n\n        ygold = &(sequence[t + b]);\n        for (i = 0; i < b; i++)\n        {\n            total += ygold[i] * ynorm[i];\n        }\n\n        count += b;\n        input = ygold;\n    }\n\n    *loss = -total / adouble(count);\n\n    delete[] ypred;\n    delete[] ynorm;\n}\n};\n\n// Note ADBench did not have an adept impl\nvoid adept_dlstm_objective(int l, int c, int b, const double *main_params, double *\n        main_paramsb, const double *extra_params, double *extra_paramsb,\n        double *state, const double *sequence, double *loss, double *lossb) {\n\n    int main_sz = 2 * l * 4 * b;\n    int extra_sz = 3 * b;\n    int state_sz = 2 * l * b;\n    int seq_sz = c* b;\n\n  adept::Stack stack;\n\n  adouble *amain = new adouble[main_sz];\n  adouble *aextra = new adouble[extra_sz];\n  adouble *astate = new adouble[state_sz];\n  adouble *aseq = new adouble[seq_sz];\n\n      adept::set_values(amain, main_sz, main_params);\n      adept::set_values(aextra, extra_sz, extra_params);\n      adept::set_values(astate, state_sz, state);\n      adept::set_values(aseq, seq_sz, sequence);\n\n      adouble aloss;\n\n      stack.new_recording();\n      adouble aerr;\n\n      adeptTest::lstm_objective(l, c, b, amain, aextra, astate, aseq, &aloss);\n      aloss.set_gradient(1.); // only one J row here\n\n      stack.compute_adjoint();\n\n      adept::get_gradients(amain, main_sz, main_paramsb);\n      adept::get_gradients(aextra, extra_sz, extra_paramsb);\n\n}\n#endif\n", "meta": {"hexsha": "dbbc9929a7cc5b05a2b2c6052e45b1bbae570e5b", "size": 20503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "enzyme/benchmarks/lstm/lstm.cpp", "max_stars_repo_name": "anandijain/Enzyme", "max_stars_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 674.0, "max_stars_repo_stars_event_min_datetime": "2020-10-05T17:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T11:18:11.000Z", "max_issues_repo_path": "enzyme/benchmarks/lstm/lstm.cpp", "max_issues_repo_name": "anandijain/Enzyme", "max_issues_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 119.0, "max_issues_repo_issues_event_min_datetime": "2020-10-07T00:47:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-06T16:46:58.000Z", "max_forks_repo_path": "enzyme/benchmarks/lstm/lstm.cpp", "max_forks_repo_name": "anandijain/Enzyme", "max_forks_repo_head_hexsha": "fcaeb498a7fcb941be02ca407444fbb81e31c02e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T14:45:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T05:51:07.000Z", "avg_line_length": 28.047879617, "max_line_length": 138, "alphanum_fraction": 0.540311174, "num_tokens": 6783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4067377454830883}}
{"text": "// File: train_adagrad.cc\n// Author: Karl Moritz Hermann (mail@karlmoritz.com)\n// Created: 01-01-2013\n// Last Update: Thu 03 Oct 2013 11:48:28 AM BST\n\n// STL\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <random>\n\n// Boost\n#include <boost/program_options/variables_map.hpp>\n#include <boost/program_options/parsers.hpp>\n\n// L-BFGS\n#include <lbfgs.h>\n\n// Local\n#include \"train_adagrad.h\"\n#include \"train_update.h\"\n#include \"recursive_autoencoder.h\"\n#include \"utils.h\"\n#include \"fast_math.h\"\n\nusing namespace std;\nnamespace bpo = boost::program_options;\n\n\nint train_adagrad(Model &model, int iterations, float eta, int batches, Real lambda)\n{\n  Real* vars = nullptr;\n  int number_vars = 0;\n\n  setVarsAndNumber(vars,number_vars,model);\n  WeightArrayType theta(vars,number_vars);\n\n  Real* Gt_d = new Real[number_vars]();\n  // Real* Ginv_d = new Real[number_vars]();\n  WeightArrayType Gt(Gt_d,number_vars);\n  // WeightArrayType Ginv(Ginv_d,number_vars);\n  // Gt.setOnes(); // initialize to ones..\n\n  Real* gradient = new Real[number_vars]();\n  lbfgsfloatval_t error = 0;\n\n  // Remove L2 regularization as AdaGrad uses L1 instead\n  model.calc_L2 = false;\n\n  int size = model.corpus.size();\n  int num_batches = min(batches,size/2);\n  int batchsize = max((size/num_batches),2);\n  // eta = eta / num_batches;\n  cout << \"Batch size: \" << batchsize << \"  eta \" << eta << endl;\n\n  Real update;\n  Real l1_reg;\n\n  for (auto iteration = 0; iteration < iterations; ++iteration)\n  {\n    cout << \"Iteration \" << iteration << endl;\n    std::random_shuffle ( model.indexes.begin(), model.indexes.end() );\n    for (auto batch = 0; batch < num_batches; ++batch)\n    {\n      model.from = batch*batchsize;\n      model.to = min((batch+1)*batchsize,size);\n      error = computeCostAndGrad(model,nullptr,gradient,number_vars);\n\n      // seeing that I need to iterate ...\n      for (int i = 0; i < number_vars; ++i) {\n        Gt_d[i] += gradient[i]*gradient[i];\n        // Update weight: ( eta / \\sqrt(Sum square gradients) ) * gradient\n        if (Gt_d[i] != 0) {\n        update = vars[i] - ((eta / (sqrt(Gt_d[i]))) * gradient[i]);\n        l1_reg = (eta / (sqrt(Gt_d[i]))) * lambda;\n        vars[i] = signum(update) * max(0.0, abs(update) - l1_reg);\n        }\n      }\n    }\n\n    if (iteration % model.rae.config.dump_freq == 0)\n    {\n      printf(\"Dumping model ...\\n\");\n      dumpModel(model,iteration);\n    }\n  }\n\n  delete [] gradient;\n  // delete [] Ginv_d;\n  delete [] Gt_d;\n  return 0;\n}\n\n", "meta": {"hexsha": "2f84bc4f4379f599da24585419598daea92d0ccd", "size": 2487, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/common/train_adagrad.cc", "max_stars_repo_name": "karlmoritz/oxcvsm", "max_stars_repo_head_hexsha": "02fd78231a8b3c4d48e9e759a3a075d04bcd0529", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-02-06T01:41:41.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-06T15:50:32.000Z", "max_issues_repo_path": "src/common/train_adagrad.cc", "max_issues_repo_name": "karlmoritz/oxcvsm", "max_issues_repo_head_hexsha": "02fd78231a8b3c4d48e9e759a3a075d04bcd0529", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/train_adagrad.cc", "max_forks_repo_name": "karlmoritz/oxcvsm", "max_forks_repo_head_hexsha": "02fd78231a8b3c4d48e9e759a3a075d04bcd0529", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T10:49:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T17:59:22.000Z", "avg_line_length": 26.4574468085, "max_line_length": 84, "alphanum_fraction": 0.6413349417, "num_tokens": 705, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177517, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4066519499757135}}
{"text": "#pragma once\n#include <unordered_set>\n#include <numeric>\n#include \"TopicModel.hpp\"\n#include <Eigen/Dense>\n#include \"../Utils/Utils.hpp\"\n#include \"../Utils/math.h\"\n#include \"../Utils/sample.hpp\"\n\n/*\nImplementation of LDA using Collapsed Variational Bayes zero-order estimation by bab2min\n\n* Blei, D. M., Ng, A. Y., & Jordan, M. I. (2003). Latent dirichlet allocation. Journal of machine Learning research, 3(Jan), 993-1022.\n\nTerm Weighting Scheme is based on following paper:\n* Wilson, A. T., & Chew, P. A. (2010, June). Term weighting schemes for latent dirichlet allocation. In human language technologies: The 2010 annual conference of the North American Chapter of the Association for Computational Linguistics (pp. 465-473). Association for Computational Linguistics.\n\n*/\n\n#define GETTER(name, type, field) type get##name() const override { return field; }\nnamespace tomoto\n{\n\tstruct DocumentLDACVB0 : public DocumentBase\n\t{\n\tpublic:\n\t\tusing DocumentBase::DocumentBase;\n\n\t\tEigen::MatrixXf Zs;\n\t\tEigen::VectorXf numByTopic;\n\n\t\tDEFINE_SERIALIZER_AFTER_BASE(DocumentBase, Zs);\n\n\t\ttemplate<typename _TopicModel> void update(Float* ptr, const _TopicModel& mdl);\n\n\t\tint32_t getSumWordWeight() const\n\t\t{\n\t\t\treturn this->words.size();\n\t\t}\n\t};\n\n\tstruct ModelStateLDACVB0\n\t{\n\t\tEigen::VectorXf zLikelihood;\n\t\tEigen::VectorXf numByTopic;\n\t\tEigen::MatrixXf numByTopicWord;\n\n\t\tDEFINE_SERIALIZER(numByTopic, numByTopicWord);\n\t};\n\n\tclass ILDACVB0Model : public ITopicModel\n\t{\n\tpublic:\n\t\tusing DefaultDocType = DocumentLDACVB0;\n\t\tstatic ILDACVB0Model* create(size_t _K = 1, Float _alpha = 0.1, Float _eta = 0.01, size_t _rg = std::random_device{}());\n\n\t\tvirtual size_t addDoc(const std::vector<std::string>& words) = 0;\n\t\tvirtual std::unique_ptr<DocumentBase> makeDoc(const std::vector<std::string>& words) const = 0;\n\t\tTermWeight getTermWeight() const { return TermWeight::one; };\n\t\tvirtual size_t getOptimInterval() const = 0;\n\t\tvirtual void setOptimInterval(size_t) = 0;\n\t\tvirtual void setBurnInIteration(size_t) {}\n\t\tvirtual std::vector<size_t> getCountByTopic() const = 0;\n\t\tvirtual size_t getK() const = 0;\n\t\tvirtual Float getAlpha() const = 0;\n\t\tvirtual Float getEta() const = 0;\n\n\t\tvirtual std::vector<Float> getWordPrior(const std::string& word) const { return {}; }\n\t\tvirtual void setWordPrior(const std::string& word, const std::vector<Float>& priors) {}\n\t};\n\n\ttemplate<typename _Interface = ILDACVB0Model,\n\t\ttypename _Derived = void, \n\t\ttypename _DocType = DocumentLDACVB0,\n\t\ttypename _ModelState = ModelStateLDACVB0>\n\tclass LDACVB0Model : public TopicModel<0, _Interface,\n\t\ttypename std::conditional<std::is_same<_Derived, void>::value, LDACVB0Model<>, _Derived>::type, \n\t\t_DocType, _ModelState>\n\t{\n\tprotected:\n\t\tusing DerivedClass = typename std::conditional<std::is_same<_Derived, void>::value, LDACVB0Model, _Derived>::type;\n\t\tusing BaseClass = TopicModel<0, _Interface, DerivedClass, _DocType, _ModelState>;\n\t\tfriend BaseClass;\n\n\t\tstatic constexpr const char TWID[] = \"one\\0\";\n\t\tstatic constexpr static constexpr char TMID[] = \"LDA\\0\";\n\n\t\tFloat alpha;\n\t\tVector alphas;\n\t\tFloat eta;\n\t\tTid K;\n\t\tsize_t optimInterval = 50;\n\n\t\ttemplate<typename _List>\n\t\tstatic Float calcDigammaSum(_List list, size_t len, Float alpha)\n\t\t{\n\t\t\tauto listExpr = Vector::NullaryExpr(len, list);\n\t\t\tauto dAlpha = math::digammaT(alpha);\n\t\t\treturn (math::digammaApprox(listExpr.array() + alpha) - dAlpha).sum();\n\t\t}\n\n\t\tvoid optimizeParameters(ThreadPool& pool, _ModelState* localData)\n\t\t{\n\t\t\tconst auto K = this->K;\n\t\t\tfor (size_t i = 0; i < 5; ++i)\n\t\t\t{\n\t\t\t\tFloat denom = calcDigammaSum([&](size_t i) { return this->docs[i].getSumWordWeight(); }, this->docs.size(), alphas.sum());\n\t\t\t\tfor (size_t k = 0; k < K; ++k)\n\t\t\t\t{\n\t\t\t\t\tFloat nom = calcDigammaSum([&](size_t i) { return this->docs[i].numByTopic[k]; }, this->docs.size(), alphas(k));\n\t\t\t\t\talphas(k) = std::max(nom / denom * alphas(k), 1e-5f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst Eigen::VectorXf& getZLikelihoods(_ModelState& ld, const _DocType& doc, size_t docId, size_t vid) const\n\t\t{\n\t\t\tconst size_t V = this->realV;\n\t\t\tassert(vid < V);\n\t\t\tauto& zLikelihood = ld.zLikelihood;\n\t\t\tzLikelihood = (doc.numByTopic.array().template cast<Float>() + alphas.array())\n\t\t\t\t* (ld.numByTopicWord.col(vid).array().template cast<Float>() + eta)\n\t\t\t\t/ (ld.numByTopic.array().template cast<Float>() + V * eta);\n\t\t\tzLikelihood /= zLikelihood.sum() + 1e-10;\n\t\t\treturn zLikelihood;\n\t\t}\n\n\t\ttemplate<int _Inc, typename _Vec>\n\t\tinline void addWordTo(_ModelState& ld, _DocType& doc, uint32_t pid, Vid vid, _Vec tDist) const\n\t\t{\n\t\t\tassert(vid < this->realV);\n\t\t\tconstexpr bool _dec = _Inc < 0;\n\t\t\tdoc.numByTopic += _Inc * tDist;\n\t\t\tif (_dec) doc.numByTopic = doc.numByTopic.cwiseMax(0);\n\t\t\tld.numByTopic += _Inc * tDist;\n\t\t\tif (_dec) ld.numByTopic = ld.numByTopic.cwiseMax(0);\n\t\t\tld.numByTopicWord.col(vid) += _Inc * tDist;\n\t\t\tif (_dec) ld.numByTopicWord.col(vid) = ld.numByTopicWord.col(vid).cwiseMax(0);\n\t\t}\n\n\t\ttemplate<ParallelScheme _ps, bool _infer, typename _ExtraDocData>\n\t\tvoid sampleDocument(_DocType& doc, const _ExtraDocData& edd, size_t docId, _ModelState& ld, _RandGen& rgs, size_t iterationCnt, size_t partitionId = 0) const\n\t\t{\n\t\t\tfor (size_t w = 0; w < doc.words.size(); ++w)\n\t\t\t{\n\t\t\t\tif (doc.words[w] >= this->realV) continue;\n\t\t\t\taddWordTo<-1>(ld, doc, w, doc.words[w], doc.Zs.col(w));\n\t\t\t\tdoc.Zs.col(w) = static_cast<const DerivedClass*>(this)->getZLikelihoods(ld, doc, docId, doc.words[w]);\n\t\t\t\taddWordTo<1>(ld, doc, w, doc.words[w], doc.Zs.col(w));\n\t\t\t}\n\t\t}\n\n\t\ttemplate<typename _DocIter, typename _ExtraDocData>\n\t\tvoid updatePartition(ThreadPool& pool, _ModelState* localData, _DocIter first, _DocIter last, _ExtraDocData& edd)\n\t\t{\n\t\t}\n\n\t\ttemplate<ParallelScheme _ps>\n\t\tvoid trainOne(ThreadPool& pool, _ModelState* localData, _RandGen* rgs)\n\t\t{\n\t\t\tstd::vector<std::future<void>> res;\n\t\t\tconst size_t chStride = std::min(pool.getNumWorkers() * 8, this->docs.size());\n\t\t\tfor (size_t ch = 0; ch < chStride; ++ch)\n\t\t\t{\n\t\t\t\tres.emplace_back(pool.enqueue([&, this, ch, chStride](size_t threadId)\n\t\t\t\t{\n\t\t\t\t\tforShuffled((this->docs.size() - 1 - ch) / chStride + 1, rgs[threadId](), [&, this](size_t id)\n\t\t\t\t\t{\n\t\t\t\t\t\tstatic_cast<DerivedClass*>(this)->template sampleDocument<ParallelScheme::copy_merge>(\n\t\t\t\t\t\t\tthis->docs[id * chStride + ch], 0, id * chStride + ch,\n\t\t\t\t\t\t\tlocalData[threadId], rgs[threadId], this->globalStep);\n\t\t\t\t\t});\n\t\t\t\t}));\n\t\t\t}\n\t\t\tfor (auto& r : res) r.get();\n\t\t\tstatic_cast<DerivedClass*>(this)->updateGlobalInfo(pool, localData);\n\t\t\tstatic_cast<DerivedClass*>(this)->mergeState(pool, this->globalState, this->tState, localData);\n\t\t\tif (this->globalStep >= 250 && optimInterval && (this->globalStep + 1) % optimInterval == 0)\n\t\t\t{\n\t\t\t\tstatic_cast<DerivedClass*>(this)->optimizeParameters(pool, localData);\n\t\t\t}\n\t\t}\n\n\t\tvoid updateGlobalInfo(ThreadPool& pool, _ModelState* localData)\n\t\t{\n\t\t\tstd::vector<std::future<void>> res;\n\n\t\t\tthis->globalState.numByTopic.setZero();\n\t\t\tthis->globalState.numByTopicWord.setZero();\n\t\t\tfor (auto& doc : this->docs)\n\t\t\t{\n\t\t\t\tdoc.numByTopic = doc.Zs.rowwise().sum();\n\t\t\t\tthis->globalState.numByTopic += doc.numByTopic;\n\t\t\t\tfor (size_t i = 0; i < doc.words.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tthis->globalState.numByTopicWord.col(doc.words[i]) += doc.Zs.col(i);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (size_t i = 0; i < pool.getNumWorkers(); ++i)\n\t\t\t{\n\t\t\t\tres.emplace_back(pool.enqueue([&, i](size_t threadId)\n\t\t\t\t{\n\t\t\t\t\tlocalData[i] = this->globalState;\n\t\t\t\t}));\n\t\t\t}\n\t\t\tfor (auto& r : res) r.get();\n\t\t}\n\n\t\tvoid mergeState(ThreadPool& pool, _ModelState& globalState, _ModelState& tState, _ModelState* localData) const\n\t\t{\n\t\t}\n\n\t\ttemplate<typename _DocIter>\n\t\tdouble getLLDocs(_DocIter _first, _DocIter _last) const\n\t\t{\n\t\t\tdouble ll = 0;\n\t\t\t// doc-topic distribution\n\t\t\tll += (math::lgammaT(K*alpha) - math::lgammaT(alpha)*K) * std::distance(_first, _last);\n\t\t\tfor (; _first != _last; ++_first)\n\t\t\t{\n\t\t\t\tauto& doc = *_first;\n\t\t\t\tll -= math::lgammaT(doc.getSumWordWeight() + K * alpha);\n\t\t\t\tfor (Tid k = 0; k < K; ++k)\n\t\t\t\t{\n\t\t\t\t\tll += math::lgammaT(doc.numByTopic[k] + alpha);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ll;\n\t\t}\n\n\t\tdouble getLLRest(const _ModelState& ld) const\n\t\t{\n\t\t\tdouble ll = 0;\n\t\t\tconst size_t V = this->realV;\n\t\t\t// topic-word distribution\n\t\t\t// it has the very-small-value problem\n\t\t\tll += (math::lgammaT(V*eta) - math::lgammaT(eta)*V) * K;\n\t\t\tfor (Tid k = 0; k < K; ++k)\n\t\t\t{\n\t\t\t\tll -= math::lgammaT(ld.numByTopic[k] + V * eta);\n\t\t\t\tfor (Vid v = 0; v < V; ++v)\n\t\t\t\t{\n\t\t\t\t\tll += math::lgammaT(ld.numByTopicWord(k, v) + eta);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ll;\n\t\t}\n\n\t\tdouble getLL() const\n\t\t{\n\t\t\treturn static_cast<const DerivedClass*>(this)->template getLLDocs<>(this->docs.begin(), this->docs.end())\n\t\t\t\t+ static_cast<const DerivedClass*>(this)->getLLRest(this->globalState);\n\t\t}\n\n\t\tvoid prepareShared()\n\t\t{\n\t\t}\n\t\t\n\t\tvoid prepareDoc(_DocType& doc, Float* topicDocPtr, size_t wordSize) const\n\t\t{\n\t\t\tdoc.numByTopic = Eigen::VectorXf::Zero(K);\n\t\t\tdoc.Zs = Eigen::MatrixXf::Zero(K, wordSize);\n\t\t}\n\n\t\tvoid initGlobalState(bool initDocs)\n\t\t{\n\t\t\tconst size_t V = this->realV;\n\t\t\tthis->globalState.zLikelihood = Vector::Zero(K);\n\t\t\tif (initDocs)\n\t\t\t{\n\t\t\t\tthis->globalState.numByTopic = Vector::Zero(K);\n\t\t\t\tthis->globalState.numByTopicWord = Matrix::Zero(K, V);\n\t\t\t}\n\t\t}\n\n\t\tstruct Generator\n\t\t{\n\t\t\tstd::uniform_int_distribution<Tid> theta;\n\t\t};\n\n\t\tGenerator makeGeneratorForInit(const _DocType*) const\n\t\t{\n\t\t\treturn Generator{ std::uniform_int_distribution<Tid>{0, (Tid)(K - 1)} };\n\t\t}\n\n\t\ttemplate<bool _Infer>\n\t\tvoid updateStateWithDoc(Generator& g, _ModelState& ld, _RandGen& rgs, _DocType& doc, size_t i) const\n\t\t{\n\t\t\tdoc.Zs.col(i).setZero();\n\t\t\tdoc.Zs(g.theta(rgs), i) = 1;\n\t\t\taddWordTo<1>(ld, doc, i, doc.words[i], doc.Zs.col(i));\n\t\t}\n\n\t\ttemplate<bool _Infer, typename _Generator>\n\t\tvoid initializeDocState(_DocType& doc, Float* topicDocPtr, _Generator& g, _ModelState& ld, _RandGen& rgs) const\n\t\t{\n\t\t\tstd::vector<uint32_t> tf(this->realV);\n\t\t\tstatic_cast<const DerivedClass*>(this)->prepareDoc(doc, topicDocPtr, doc.words.size());\n\t\t\t\n\t\t\tfor (size_t i = 0; i < doc.words.size(); ++i)\n\t\t\t{\n\t\t\t\tif (doc.words[i] >= this->realV) continue;\n\t\t\t\tstatic_cast<const DerivedClass*>(this)->template updateStateWithDoc<_Infer>(g, ld, rgs, doc, i);\n\t\t\t}\n\t\t}\n\n\t\tstd::vector<uint64_t> _getTopicsCount() const\n\t\t{\n\t\t\tEigen::VectorXf cnt = Eigen::VectorXf::Zero(K);\n\t\t\tfor (auto& doc : this->docs)\n\t\t\t{\n\t\t\t\tcnt += doc.Zs.rowwise().sum();\n\t\t\t}\n\n\t\t\treturn { cnt.data(), cnt.data() + K };\n\t\t}\n\n\t\ttemplate<ParallelScheme _ps>\n\t\tsize_t estimateMaxThreads() const\n\t\t{\n\t\t\tif (_ps == ParallelScheme::partition)\n\t\t\t{\n\t\t\t\treturn this->realV / 4;\n\t\t\t}\n\t\t\tif (_ps == ParallelScheme::copy_merge)\n\t\t\t{\n\t\t\t\treturn this->docs.size() / 2;\n\t\t\t}\n\t\t\treturn (size_t)-1;\n\t\t}\n\n\t\tDEFINE_SERIALIZER(alpha, eta, K);\n\n\tpublic:\n\t\tLDACVB0Model(size_t _K = 1, Float _alpha = 0.1, Float _eta = 0.01, size_t _rg = std::random_device{}())\n\t\t\t: BaseClass(_rg), K(_K), alpha(_alpha), eta(_eta)\n\t\t{ \n\t\t\talphas = Vector::Constant(K, alpha);\n\t\t}\n\t\tGETTER(K, size_t, K);\n\t\tGETTER(Alpha, Float, alpha);\n\t\tGETTER(Eta, Float, eta);\n\t\tGETTER(OptimInterval, size_t, optimInterval);\n\n\t\n\t\tvoid setOptimInterval(size_t _optimInterval) override\n\t\t{\n\t\t\toptimInterval = _optimInterval;\n\t\t}\n\n\t\tsize_t addDoc(const std::vector<std::string>& words) override\n\t\t{\n\t\t\treturn this->_addDoc(this->_makeDoc(words));\n\t\t}\n\n\t\tstd::unique_ptr<DocumentBase> makeDoc(const std::vector<std::string>& words) const override\n\t\t{\n\t\t\treturn std::make_unique<_DocType>(as_mutable(this)->template _makeDoc<true>(words));\n\t\t}\n\n\t\tvoid updateDocs()\n\t\t{\n\t\t\tfor (auto& doc : this->docs)\n\t\t\t{\n\t\t\t\tdoc.template update<>(nullptr, *static_cast<DerivedClass*>(this));\n\t\t\t}\n\t\t}\n\n\t\tvoid prepare(bool initDocs = true, size_t minWordCnt = 0, size_t minWordDf = 0, size_t removeTopN = 0) override\n\t\t{\n\t\t\tif (initDocs) this->removeStopwords(minWordCnt, minWordDf, removeTopN);\n\t\t\tstatic_cast<DerivedClass*>(this)->updateWeakArray();\n\t\t\tstatic_cast<DerivedClass*>(this)->initGlobalState(initDocs);\n\n\t\t\tif (initDocs)\n\t\t\t{\n\t\t\t\tauto generator = static_cast<DerivedClass*>(this)->makeGeneratorForInit(nullptr);\n\t\t\t\tfor (auto& doc : this->docs)\n\t\t\t\t{\n\t\t\t\t\tinitializeDocState<false>(doc, nullptr, generator, this->globalState, this->rg);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstatic_cast<DerivedClass*>(this)->updateDocs();\n\t\t\t}\n\t\t\tstatic_cast<DerivedClass*>(this)->prepareShared();\n\t\t}\n\n\t\tstd::vector<size_t> getCountByTopic() const override\n\t\t{\n\t\t\treturn static_cast<const DerivedClass*>(this)->_getTopicsCount();\n\t\t}\n\n\t\tstd::vector<Float> getTopicsByDoc(const _DocType& doc) const\n\t\t{\n\t\t\tstd::vector<Float> ret(K);\n\t\t\tFloat sum = doc.getSumWordWeight() + K * alpha;\n\t\t\ttransform(doc.numByTopic.data(), doc.numByTopic.data() + K, ret.begin(), [sum, this](size_t n)\n\t\t\t{\n\t\t\t\treturn (n + alpha) / sum;\n\t\t\t});\n\t\t\treturn ret;\n\t\t}\n\n\t\tstd::vector<Float> _getWidsByTopic(Tid tid, bool normalize = true) const\n\t\t{\n\t\t\tassert(tid < K);\n\t\t\tconst size_t V = this->realV;\n\t\t\tstd::vector<Float> ret(V);\n\t\t\tFloat sum = this->globalState.numByTopic[tid] + V * eta;\n\t\t\tauto r = this->globalState.numByTopicWord.row(tid);\n\t\t\tfor (size_t v = 0; v < V; ++v)\n\t\t\t{\n\t\t\t\tret[v] = (r[v] + eta) / sum;\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\ttemplate<bool _Together, ParallelScheme _ps, typename _Iter>\n\t\tstd::vector<double> _infer(_Iter docFirst, _Iter docLast, size_t maxIter, Float tolerance, size_t numWorkers) const\n\t\t{\n\t\t\treturn {};\n\t\t}\n\t};\n\n\ttemplate<typename _TopicModel>\n\tvoid DocumentLDACVB0::update(Float * ptr, const _TopicModel & mdl)\n\t{\n\t\tnumByTopic = Eigen::VectorXf::Zero(mdl.getK());\n\t\tfor (size_t i = 0; i < Zs.cols(); ++i)\n\t\t{\n\t\t\tnumByTopic += Zs.col(i);\n\t\t}\n\t}\n\n\tinline ILDACVB0Model* ILDACVB0Model::create(size_t _K, Float _alpha, Float _eta, const _RandGen& _rg)\n\t{\n\t\treturn new LDACVB0Model<>(_K, _alpha, _eta, _rg);\n\t}\n\n}", "meta": {"hexsha": "03f5ebc8e642e4db1af7ce65ebdfe54153e89f1f", "size": 13710, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/TopicModel/LDACVB0Model.hpp", "max_stars_repo_name": "jonaschn/tomotopy", "max_stars_repo_head_hexsha": "e37878ac3531a13e29317912298bf4b5f457521b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TopicModel/LDACVB0Model.hpp", "max_issues_repo_name": "jonaschn/tomotopy", "max_issues_repo_head_hexsha": "e37878ac3531a13e29317912298bf4b5f457521b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TopicModel/LDACVB0Model.hpp", "max_forks_repo_name": "jonaschn/tomotopy", "max_forks_repo_head_hexsha": "e37878ac3531a13e29317912298bf4b5f457521b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0180995475, "max_line_length": 296, "alphanum_fraction": 0.6690736689, "num_tokens": 4301, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529375, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.40660984570793224}}
{"text": "// Copyright 2019, Collabora, Ltd.\n// SPDX-License-Identifier: BSL-1.0\n/*!\n * @file\n * @brief  Base implementations for math library.\n * @author Jakob Bornecrantz <jakob@collabora.com>\n * @author Ryan Pavlik <ryan.pavlik@collabora.com>\n * @ingroup aux_math\n */\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include <assert.h>\n\n#include \"math/m_api.h\"\n#include \"math/m_eigen_interop.h\"\n\n/*\n *\n * Copy helpers.\n *\n */\n\nstatic inline Eigen::Quaternionf\ncopy(const struct xrt_quat& q)\n{\n\t// Eigen constructor order is different from XRT, OpenHMD and OpenXR!\n\t//  Eigen: `float w, x, y, z`.\n\t// OpenXR: `float x, y, z, w`.\n\treturn Eigen::Quaternionf(q.w, q.x, q.y, q.z);\n}\n\nstatic inline Eigen::Quaternionf\ncopy(const struct xrt_quat* q)\n{\n\treturn copy(*q);\n}\n\nstatic inline Eigen::Vector3f\ncopy(const struct xrt_vec3& v)\n{\n\treturn Eigen::Vector3f(v.x, v.y, v.z);\n}\n\nstatic inline Eigen::Vector3f\ncopy(const struct xrt_vec3* v)\n{\n\treturn copy(*v);\n}\n\n\n/*\n *\n * Exported vector functions.\n *\n */\nvoid\nmath_vec3_accum(const struct xrt_vec3* additional, struct xrt_vec3* inAndOut)\n{\n\tassert(additional != NULL);\n\tassert(inAndOut != NULL);\n\n\tmap_vec3(*inAndOut) += map_vec3(*additional);\n}\n\n/*\n *\n * Exported quaternion functions.\n *\n */\n\nvoid\nmath_quat_rotate(const struct xrt_quat* left,\n                 const struct xrt_quat* right,\n                 struct xrt_quat* result)\n{\n\tassert(left != NULL);\n\tassert(right != NULL);\n\tassert(result != NULL);\n\n\tauto l = copy(left);\n\tauto r = copy(right);\n\n\tauto q = l * r;\n\n\tmap_quat(*result) = q;\n}\n\nvoid\nmath_quat_rotate_vec3(const struct xrt_quat* left,\n                      const struct xrt_vec3* right,\n                      struct xrt_vec3* result)\n{\n\tassert(left != NULL);\n\tassert(right != NULL);\n\tassert(result != NULL);\n\n\tauto l = copy(left);\n\tauto r = copy(right);\n\n\tauto v = l * r;\n\n\tmap_vec3(*result) = v;\n}\n\n\n/*\n *\n * Exported pose functions.\n *\n */\n\nbool\nmath_pose_validate(const struct xrt_pose* pose)\n{\n\tassert(pose != NULL);\n\n\tconst float FLOAT_EPSILON = Eigen::NumTraits<float>::epsilon();\n\tauto norm = orientation(*pose).squaredNorm();\n\tif (norm > 1.0f + FLOAT_EPSILON || norm < 1.0f - FLOAT_EPSILON) {\n\t\treturn false;\n\t}\n\n\t// Technically not yet a required check, but easier to stop problems\n\t// now than once denormalized numbers pollute the rest of our state.\n\t// see https://gitlab.khronos.org/openxr/openxr/issues/922\n\tif (!orientation(*pose).coeffs().allFinite()) {\n\t\treturn false;\n\t}\n\tif (!position(*pose).allFinite()) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nvoid\nmath_pose_invert(const struct xrt_pose* pose, struct xrt_pose* outPose)\n{\n\tassert(pose != NULL);\n\tassert(outPose != NULL);\n\n\t// store results to temporary locals so we can do this \"in-place\"\n\t// (pose == outPose) if desired.\n\tEigen::Vector3f newPosition = -position(*pose);\n\t// Conjugate legal here since pose must be normalized/unit length.\n\tEigen::Quaternionf newOrientation = orientation(*pose).conjugate();\n\n\tposition(*outPose) = newPosition;\n\torientation(*outPose) = newOrientation;\n}\n\n/*!\n * Return the result of transforming a point by a pose/transform.\n */\nstatic inline Eigen::Vector3f\ntransform_point(const xrt_pose& transform, const xrt_vec3& point)\n{\n\treturn orientation(transform) * map_vec3(point) + position(transform);\n}\n\n/*!\n * Return the result of transforming a pose by a pose/transform.\n */\nstatic inline xrt_pose\ntransform_pose(const xrt_pose& transform, const xrt_pose& pose)\n{\n\txrt_pose ret;\n\tposition(ret) = transform_point(transform, pose.position);\n\torientation(ret) = orientation(transform) * orientation(pose);\n\treturn ret;\n}\n\nvoid\nmath_pose_transform(const struct xrt_pose* transform,\n                    const struct xrt_pose* pose,\n                    struct xrt_pose* outPose)\n{\n\tassert(pose != NULL);\n\tassert(transform != NULL);\n\tassert(outPose != NULL);\n\n\txrt_pose newPose = transform_pose(*transform, *pose);\n\tmemcpy(outPose, &newPose, sizeof(xrt_pose));\n}\n\nvoid\nmath_pose_openxr_locate(const struct xrt_pose* space_pose,\n                        const struct xrt_pose* relative_pose,\n                        const struct xrt_pose* base_space_pose,\n                        struct xrt_pose* result)\n{\n\tassert(space_pose != NULL);\n\tassert(relative_pose != NULL);\n\tassert(base_space_pose != NULL);\n\tassert(result != NULL);\n\n\t// Compilers are slighty better optimizing\n\t// if we copy the arguments in one go.\n\tconst auto bsp = *base_space_pose;\n\tconst auto rel = *relative_pose;\n\tconst auto spc = *space_pose;\n\tstruct xrt_pose pose;\n\n\t// Apply the invert of the base space to identity.\n\tmath_pose_invert(&bsp, &pose);\n\n\t// Apply the pure pose from the space relation.\n\tmath_pose_transform(&pose, &rel, &pose);\n\n\t// Apply the space pose.\n\tmath_pose_transform(&pose, &spc, &pose);\n\n\t*result = pose;\n}\n\n/*!\n * Return the result of rotating a derivative vector by a matrix.\n *\n * This is a differential transform.\n */\nstatic inline Eigen::Vector3f\nrotate_deriv(Eigen::Matrix3f const& rotation,\n             const xrt_vec3& derivativeVector,\n             Eigen::Matrix3f const& rotationInverse)\n{\n\treturn ((rotation * map_vec3(derivativeVector)).transpose() *\n\t        rotationInverse)\n\t    .transpose();\n}\n\n#ifndef XRT_DOXYGEN\n\n#define MAKE_REL_FLAG_CHECK(NAME, MASK)                                        \\\n\tstatic inline bool NAME(xrt_space_relation_flags flags)                \\\n\t{                                                                      \\\n\t\treturn ((flags & (MASK)) != 0);                                \\\n\t}\n\nMAKE_REL_FLAG_CHECK(has_some_pose_component,\n                    XRT_SPACE_RELATION_POSITION_VALID_BIT |\n                        XRT_SPACE_RELATION_ORIENTATION_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_position, XRT_SPACE_RELATION_POSITION_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_orientation, XRT_SPACE_RELATION_ORIENTATION_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_lin_vel, XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_ang_vel, XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_lin_acc,\n                    XRT_SPACE_RELATION_LINEAR_ACCELERATION_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_ang_acc,\n                    XRT_SPACE_RELATION_ANGULAR_ACCELERATION_VALID_BIT)\nMAKE_REL_FLAG_CHECK(has_some_derivative,\n                    XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT |\n                        XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT |\n                        XRT_SPACE_RELATION_LINEAR_ACCELERATION_VALID_BIT |\n                        XRT_SPACE_RELATION_ANGULAR_ACCELERATION_VALID_BIT)\n\n#undef MAKE_REL_FLAG_CHECK\n\n#endif // !XRT_DOXYGEN\n\n/*!\n * Apply a transform to a space relation.\n */\nstatic inline void\ntransform_accumulate_pose(const xrt_pose& transform,\n                          xrt_space_relation& relation,\n                          bool do_translation = true,\n                          bool do_rotation = true)\n{\n\tassert(do_translation || do_rotation);\n\n\t// Save the quat in case we are self-transforming.\n\tEigen::Quaternionf quat = orientation(transform);\n\n\tauto flags = relation.relation_flags;\n\t// so code looks similar\n\tauto in_out_relation = &relation;\n\n\t// transform (rotate and translate) the pose, if applicable.\n\tif (has_some_pose_component(flags)) {\n\t\t// Zero out transform parts we don't want to use,\n\t\t// because math_pose_transform doesn't take flags.\n\t\txrt_pose transform_copy = transform;\n\t\tif (!do_translation) {\n\t\t\tposition(transform_copy) = Eigen::Vector3f::Zero();\n\t\t}\n\t\tif (!do_rotation) {\n\t\t\torientation(transform_copy) =\n\t\t\t    Eigen::Quaternionf::Identity();\n\t\t}\n\n\t\tmath_pose_transform(&in_out_relation->pose, &transform,\n\t\t                    &in_out_relation->pose);\n\t}\n\n\tif (do_rotation && has_some_derivative(flags)) {\n\n\t\t// prepare matrices required for rotating derivatives from the\n\t\t// saved quat.\n\t\tEigen::Matrix3f rot = quat.toRotationMatrix();\n\t\tEigen::Matrix3f rotInverse = rot.inverse();\n\n\t\t// Rotate derivatives, if applicable.\n\t\tif (has_lin_vel(flags)) {\n\t\t\tmap_vec3(in_out_relation->linear_velocity) =\n\t\t\t    rotate_deriv(rot, in_out_relation->linear_velocity,\n\t\t\t                 rotInverse);\n\t\t}\n\n\t\tif (has_ang_vel(flags)) {\n\t\t\tmap_vec3(in_out_relation->angular_velocity) =\n\t\t\t    rotate_deriv(rot, in_out_relation->angular_velocity,\n\t\t\t                 rotInverse);\n\t\t}\n\n\t\tif (has_lin_acc(flags)) {\n\t\t\tmap_vec3(in_out_relation->linear_acceleration) =\n\t\t\t    rotate_deriv(rot,\n\t\t\t                 in_out_relation->linear_acceleration,\n\t\t\t                 rotInverse);\n\t\t}\n\n\t\tif (has_ang_acc(flags)) {\n\t\t\tmap_vec3(in_out_relation->angular_acceleration) =\n\t\t\t    rotate_deriv(rot,\n\t\t\t                 in_out_relation->angular_acceleration,\n\t\t\t                 rotInverse);\n\t\t}\n\t}\n}\n\nstatic const struct xrt_space_relation BLANK_RELATION = {\n    XRT_SPACE_RELATION_BITMASK_ALL,\n    {{0.0f, 0.0f, 0.0f, 1.0f}, {0.0f, 0.0f, 0.0f}},\n    {0, 0, 0},\n    {0, 0, 0},\n    {0, 0, 0},\n    {0, 0, 0},\n};\n\nvoid\nmath_relation_reset(struct xrt_space_relation* out)\n{\n\t*out = BLANK_RELATION;\n}\n\nvoid\nmath_relation_accumulate_transform(const struct xrt_pose* transform,\n                                   struct xrt_space_relation* in_out_relation)\n{\n\tassert(transform != nullptr);\n\tassert(in_out_relation != nullptr);\n\n\t// No modifying the validity flags here.\n\ttransform_accumulate_pose(*transform, *in_out_relation);\n}\n\n\nvoid\nmath_relation_accumulate_relation(\n    const struct xrt_space_relation* additional_relation,\n    struct xrt_space_relation* in_out_relation)\n{\n\tassert(additional_relation != NULL);\n\tassert(in_out_relation != NULL);\n\n\t// Update the flags.\n\txrt_space_relation_flags flags = (enum xrt_space_relation_flags)(\n\t    in_out_relation->relation_flags &\n\t    additional_relation->relation_flags);\n\tin_out_relation->relation_flags = flags;\n\n\tif (has_some_pose_component(flags)) {\n\t\t// First, just do the pose part (including rotating\n\t\t// derivatives, if applicable).\n\t\ttransform_accumulate_pose(additional_relation->pose,\n\t\t                          *in_out_relation, has_position(flags),\n\t\t                          has_orientation(flags));\n\t}\n\n\t// Then, accumulate the derivatives, if required.\n\tif (has_lin_vel(flags)) {\n\t\tmap_vec3(in_out_relation->linear_velocity) +=\n\t\t    map_vec3(additional_relation->linear_velocity);\n\t}\n\n\tif (has_ang_vel(flags)) {\n\t\tmap_vec3(in_out_relation->angular_velocity) +=\n\t\t    map_vec3(additional_relation->angular_velocity);\n\t}\n\n\tif (has_lin_acc(flags)) {\n\t\tmap_vec3(in_out_relation->linear_acceleration) +=\n\t\t    map_vec3(additional_relation->linear_acceleration);\n\t}\n\n\tif (has_ang_acc(flags)) {\n\t\tmap_vec3(in_out_relation->angular_acceleration) +=\n\t\t    map_vec3(additional_relation->angular_acceleration);\n\t}\n}\n\nvoid\nmath_relation_openxr_locate(const struct xrt_pose* space_pose,\n                            const struct xrt_space_relation* relative_relation,\n                            const struct xrt_pose* base_space_pose,\n                            struct xrt_space_relation* result)\n{\n\tassert(space_pose != NULL);\n\tassert(relative_relation != NULL);\n\tassert(base_space_pose != NULL);\n\tassert(result != NULL);\n\n\t// Compilers are slighty better optimizing\n\t// if we copy the arguments in one go.\n\tconst auto bsp = *base_space_pose;\n\tconst auto spc = *space_pose;\n\tstruct xrt_space_relation accumulating_relation = BLANK_RELATION;\n\n\t// Apply the invert of the base space to identity.\n\tmath_pose_invert(&bsp, &accumulating_relation.pose);\n\n\t// Apply the pure relation between spaces.\n\tmath_relation_accumulate_relation(relative_relation,\n\t                                  &accumulating_relation);\n\n\t// Apply the space pose.\n\tmath_relation_accumulate_transform(&spc, &accumulating_relation);\n\n\t*result = accumulating_relation;\n}\n", "meta": {"hexsha": "312bef066676bca78ecc77f30ce4b4789a10b591", "size": 11640, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/xrt/auxiliary/math/m_base.cpp", "max_stars_repo_name": "tweakoz/monado", "max_stars_repo_head_hexsha": "bc770524937032e8d6fb1f8eb4daa37289ae1f69", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/xrt/auxiliary/math/m_base.cpp", "max_issues_repo_name": "tweakoz/monado", "max_issues_repo_head_hexsha": "bc770524937032e8d6fb1f8eb4daa37289ae1f69", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/xrt/auxiliary/math/m_base.cpp", "max_forks_repo_name": "tweakoz/monado", "max_forks_repo_head_hexsha": "bc770524937032e8d6fb1f8eb4daa37289ae1f69", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9444444444, "max_line_length": 80, "alphanum_fraction": 0.683419244, "num_tokens": 2768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.4066008982977953}}
{"text": "#include <vector>\n#include <string>\n#include <map>\n\n#include \"rate_model.h\"\n\n#include <armadillo>\nusing namespace arma;\n\ninline int signof(double d) {return d >= 0 ? 1 : -1;}\ninline double roundto(double in) {return floor(in*(1000)+0.5)/(1000);}\n\nRateModel::RateModel(int _nstates):Q(_nstates,_nstates),labels(),Q_mask(),\n    lasteigval(_nstates,_nstates),lasteigvec(_nstates,_nstates),\n    eigval(_nstates,_nstates),eigvec(_nstates,_nstates),\n    lasteigval_simple(_nstates,_nstates),lasteigvec_simple(_nstates,_nstates),\n    eigval_simple(_nstates,_nstates),eigvec_simple(_nstates,_nstates),nstates(_nstates) {\n    \n    setup_Q();\n    sameQ = false;\n    lasteigval.fill(0);\n    lasteigvec.fill(0);\n    eigval.fill(0);\n    eigvec.fill(0);\n    lasteigval_simple.fill(0);\n    lasteigvec_simple.fill(0);\n    eigval_simple.fill(0);\n    eigvec_simple.fill(0);\n}\n\n\nvoid RateModel::set_Q_cell(int from, int to, double num) {\n    Q(from,to) = num;\n    sameQ = false;\n}\n\nvoid RateModel::set_Q_diag() {\n    for (unsigned int i=0; i < Q.n_rows; i++) {\n        double su = 0;\n        for (unsigned int j=0; j < Q.n_cols; j++) {\n            if (i != j) {\n                su += Q(i, j);\n            }\n        }\n        Q(i, i) = 0-su;\n    }\n    sameQ = false;\n}\n\nvoid RateModel::setup_Q() {\n    Q.fill(0);\n    for (unsigned int i=0; i < Q.n_rows; i++) {\n        for (unsigned int j=0; j < Q.n_cols; j++) {\n            if (i != j) {\n                Q(i, j) = 1./nstates;\n            } else {\n                Q(i, j) = -(1./nstates * (nstates-1));\n            }\n        }\n    }\n    sameQ = false;\n}\n\nvoid RateModel::setup_Q(vector<vector<double> > & inQ) {\n    for (unsigned int i=0; i < Q.n_rows; i++) {\n        for (unsigned int j=0; j < Q.n_cols; j++) {\n            Q(i, j) = inQ[i][j];\n        }\n    }\n    for (unsigned int i=0; i < Q.n_rows; i++) {\n        colvec a = (sum(Q,1));\n        Q(i, i) = -(a(i)-Q(i, i));\n    }\n    sameQ = false;\n}\n\nvoid RateModel::setup_Q(mat & inQ) {\n    for (unsigned int i=0; i < Q.n_rows; i++) {\n        for (unsigned int j=0; j < Q.n_cols; j++) {\n            Q(i, j) = inQ(i, j);\n        }\n    }\n    set_Q_diag();\n    sameQ = false;\n}\n\nvoid RateModel::set_n_qs(int number) {\n    for (int i=0; i < number; i++) {\n        mat tm(nstates,nstates);\n        Qs.push_back(tm);\n    }\n}\n\nvoid RateModel::set_Q_which(mat & inQ,int which) {\n    for (unsigned int i=0; i < Qs[which].n_rows; i++) {\n        for (unsigned int j=0; j < Qs[which].n_cols; j++) {\n            Qs[which](i, j) = inQ(i, j);\n        }\n    }\n    for (unsigned int i=0; i < Qs[which].n_rows; i++) {\n        double su = 0;\n        for (unsigned int j=0; j < Qs[which].n_cols; j++) {\n            if (i != j) {\n                su += Qs[which](i, j);\n            }\n        }\n        Qs[which](i, i) = 0-su;\n    }\n    sameQ = false;\n}\n\nvoid RateModel::set_Q(mat & inQ) {\n    for (unsigned int i=0; i < Q.n_rows; i++) {\n        for (unsigned int j=0; j < Q.n_cols; j++) {\n            Q(i, j) = inQ(i, j);\n        }\n    }\n    sameQ = false;\n}\n\nmat & RateModel::get_Q() {\n    return Q;\n}\n\ncx_mat RateModel::setup_P(double bl,bool store_p_matrices) {\n    //sameQ = false;\n    eigvec.fill(0);\n    eigval.fill(0);\n    bool isImag = get_eigenvec_eigenval_from_Q(&eigval, &eigvec); // isImag is not used?\n    //cout << eigval << endl;\n    //cout << eigvec << endl;\n    for (int i=0; i < nstates; i++) {\n        eigval(i, i) = exp(eigval(i, i) * bl);\n    }\n    cx_mat C_inv = inv(eigvec);\n    cx_mat P = eigvec * eigval * C_inv;\n    neg_p = false;\n    for (unsigned int i=0; i < P.n_rows; i++) {\n        for (unsigned int j=0; j < P.n_cols; j++) {\n            if (real(P(i, j))<0)\n            neg_p = true;\n        }\n    }\n    if (store_p_matrices == true) {\n        stored_p_matrices[bl] = P;    \n    }\n    return P;\n}\n\nvoid RateModel::setup_P_simple(mat & p,double bl,bool store_p_matrices) {\n//    sameQ = false;\n    eigvec_simple.fill(0);\n    eigval_simple.fill(0);\n    get_eigenvec_eigenval_from_Q_simple(&eigval_simple, &eigvec_simple);\n    //cout << eigval << endl;\n    //cout << eigvec << endl;\n    for (int i=0; i < nstates; i++) {\n        eigval_simple(i, i) = exp(eigval_simple(i, i) * bl);\n    }\n    mat C_inv = inv(eigvec_simple);\n    p = eigvec_simple * eigval_simple * C_inv;\n/*    if (store_p_matrices == true) {\n    stored_p_matrices[bl] = P;    \n    }*/\n    //return P;\n}\n\nvoid RateModel::get_eigenvec_eigenval_from_Q_simple(mat * eigval, mat * eigvec) {\n    if (sameQ == true) {\n        for (unsigned int i=0; i < Q.n_rows; i++) {\n            for (unsigned int j=0; j < Q.n_cols; j++) {\n                (*eigval)(i, j) = lasteigval_simple(i, j);\n                (*eigvec)(i, j) = lasteigvec_simple(i, j);\n            }\n        }\n        return;\n    }\n    mat tQ(nstates,nstates); tQ.fill(0);\n    for (unsigned int i=0; i < Q.n_rows; i++) {\n        for (unsigned int j=0; j < Q.n_cols; j++) {\n            tQ(i, j) = Q(i, j);\n        }\n    }\n    colvec eigva;\n    mat eigve;\n    eig_sym(eigva,eigve,tQ);\n    //bool isImag = false; // not used\n    for (unsigned int i=0; i < Q.n_rows; i++) {\n        for (unsigned int j=0; j < Q.n_cols; j++) {\n            if (i == j) {\n                (*eigval)(i, j) = eigva(i);\n                lasteigval_simple(i, j) = eigva(i);\n            } else {\n                (*eigval)(i, j) = 0;\n                lasteigval_simple(i, j) = 0;\n            }\n            (*eigvec)(i, j) = eigve(i, j);\n            lasteigvec_simple(i, j) = eigve(i, j);\n        }\n    }\n    return;\n}\n\n\n/*\n * this should be used to caluculate the eigenvalues and eigenvectors\n * as U * Q * U-1 -- eigen decomposition\n *\n * this should use the armadillo library\n */\nbool RateModel::get_eigenvec_eigenval_from_Q(cx_mat * eigval, cx_mat * eigvec) {\n    if (sameQ == true) {\n        for (unsigned int i=0; i < Q.n_rows; i++) {\n            for (unsigned int j=0; j < Q.n_cols; j++) {\n                (*eigval)(i, j) = lasteigval(i, j);\n                (*eigvec)(i, j) = lasteigvec(i, j);\n            }\n        }\n        return lastImag;\n    }\n    mat tQ(nstates,nstates); tQ.fill(0);\n    for (unsigned int i=0; i < Q.n_rows; i++) {\n        for (unsigned int j=0; j < Q.n_cols; j++) {\n            tQ(i, j) = Q(i, j);\n        }\n    }\n    cx_colvec eigva;\n    cx_mat eigve;\n    eig_gen(eigva,eigve,tQ);\n    bool isImag = false;\n    for (unsigned int i=0; i < Q.n_rows; i++) {\n        for (unsigned int j=0; j < Q.n_cols; j++) {\n            if (i == j) {\n                (*eigval)(i, j) = eigva(i);\n                lasteigval(i, j) = eigva(i);\n            } else {\n                (*eigval)(i, j) = 0;\n                lasteigval(i, j) = 0;\n            }\n            (*eigvec)(i, j) = eigve(i, j);\n            lasteigvec(i, j) = eigve(i, j);\n            if (imag((*eigvec)(i, j)) > 0 || imag((*eigval)(i, j))) {\n                isImag = true;\n            }\n        }\n    }\n    //lasteigval = eigval;\n    //lasteigvec = eigvec;\n    lastImag = isImag;\n    return isImag;\n}\n\n//taking out fortran\n//\n/*\nextern\"C\" {\n    void wrapalldmexpv_(int * n,int* m,double * t,double* v,double * w,double* tol,double* anorm,double* wsp,int * lwsp,int* iwsp,int *liwsp, int * itrace,int *iflag,int *ia, int *ja, double *a, int *nz, double * res);\n    void wrapsingledmexpv_(int * n,int* m,double * t,double* v,double * w,double* tol,double* anorm,double* wsp,int * lwsp,int* iwsp,int *liwsp, int * itrace,int *iflag,int *ia, int *ja, double *a, int *nz, double * res);\n    void wrapdgpadm_(int * ideg,int * m,double * t,double * H,int * ldh,double * wsp,int * lwsp,int * ipiv,int * iexph,int *ns,int *iflag );\n}\n\nvoid RateModel::setup_fortran_P_whichQ(int which, mat & P, double t) {\n    Q = Qs[which];\n    setup_fortran_P(P,t,false);\n}\n*/\n//taking out fortran\n/*\n * runs the basic padm fortran expokit full matrix exp\n *\nvoid RateModel::setup_fortran_P(mat & P, double t, bool store_p_matrices) {\n    //\n    //  return P, the matrix of dist-to-dist transition probabilities,\n    //  from the model's rate matrix (Q) over a time duration (t)\n    //\n    int ideg = 6;\n    int m = Q.n_rows; // square so you only need the rows\n    int ldh = m;\n    double tol = 1;\n    int iflag = 0;\n    int lwsp = 4*m*m+6+1;\n    double * wsp = new double[lwsp];\n    int * ipiv = new int[m];\n    int iexph = 0;\n    int ns = 0;\n    double * H = new double [m*m];\n    convert_matrix_to_single_row_for_fortran(Q, t, H);\n    wrapdgpadm_(&ideg, &m, &tol, H, &ldh, wsp, &lwsp, ipiv, &iexph, &ns, &iflag);\n\n    for (int i=0; i < m; i++) {\n        for (int j=0; j < m; j++) {\n            P(i, j) = wsp[iexph + (j-1) * m + (i-1) + m];\n        }\n    }\n    delete [] wsp;\n    delete [] ipiv;\n    delete [] H;\n    for (int i=0; i < nstates; i++) {\n        double sum = 0.0;\n        for (int j=0; j < nstates; j++) {\n            sum += P(i, j);\n        }\n        for (int j=0; j < nstates; j++) {\n            P(i, j) = (P(i, j)/sum);\n        }\n    }\n    \n}\n*/\nvoid RateModel::set_sameQ(bool s) {\n    sameQ = s;\n}\n\nvoid update_simple_goldman_yang_q(mat * inm, double K, double w, mat & bigpibf,mat &bigpiK, mat & bigpiw) {\n    double s = 0;\n    for (int i=0; i < 61; i++) {\n        for (int j=0; j < 61; j++) {\n            if (bigpibf(i, j) == 0) {\n                (*inm)(i, j) = 0;\n            } else {\n                (*inm)(i, j) = 1/61.;\n                if (bigpiK(i, j) != 0) {\n                    (*inm)(i, j) *= K;\n                }\n                if (bigpiw(i, j) != 0) {\n                    (*inm)(i, j) *= w;\n                }\n            } \n            if (i == j) {\n                (*inm)(i, j) = 0;\n            }\n            s += (*inm)(i, j);\n        }\n    }\n    (*inm) = (*inm)/s;\n    for (unsigned int i=0; i < (*inm).n_rows; i++) {\n        double su = 0;\n        for (unsigned int j=0; j < (*inm).n_cols; j++) {\n            if (i != j) {\n            su += (*inm)(i, j);\n            }\n        }\n        (*inm)(i, i) = 0-su;\n    }\n    (*inm) = (*inm)/(1/61.);\n    //(*inm) = trans((*inm));\n}\n\nbool test_transition(char a, char b) {\n    bool ret = false;\n    if ((a == 'A' &&  b == 'G') || (a == 'C' &&  b == 'T') || (a == 'G' &&  b == 'A') || (a == 'T' &&  b == 'C')) {\n        ret = true;\n    }\n    return ret;\n}\n\nvoid generate_bigpibf_K_w(mat * bf, mat * K, mat * w,map<string, string> & codon_dict, \n    map<string, vector<int> > & codon_index, vector<string> & codon_list) {\n    for (int i=0; i < 61; i++) {\n        for (int j=0; j < 61; j++) {\n            int diff = 0;\n            bool transit = false;\n            bool nonsyn = false;\n            for (int m=0; m < 3; m++) {\n                if (codon_list[i][m] != codon_list[j][m]) {\n                    diff += 1;\n                }\n                transit = test_transition(codon_list[i][m],codon_list[j][m]);\n            }\n            if (diff > 1) {\n                (*bf)(i, j) = 0;\n            } else {\n                if (codon_dict[codon_list[i]] != codon_dict[codon_list[j]]) {\n                    nonsyn = true;\n                }\n                (*bf)(i, j) = 1;\n                if (transit) {\n                    (*K)(i, j) = 1;\n                }\n                if (nonsyn) {\n                    (*w)(i, j) = 1;\n                }\n            }\n        }\n    }\n}\n\n//take out fortran\n/*\nvoid convert_matrix_to_single_row_for_fortran(mat & inmatrix, double t, double * H) {\n    int count = 0;\n    for (unsigned int i=0; i < inmatrix.n_cols; i++) {\n        for (unsigned int j=0; j < inmatrix.n_cols; j++) {\n            H[i+(j*inmatrix.n_cols)] = inmatrix(i, j)*t;\n            count += 1;\n        }\n    }\n}\n*/\n", "meta": {"hexsha": "1e905eae7a922f59c27dcfb919cb4558b8470f54", "size": 11522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phyx-1.01/src/rate_model.cpp", "max_stars_repo_name": "jlanga/smsk_selection", "max_stars_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-18T05:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T10:22:33.000Z", "max_issues_repo_path": "src/phyx-1.01/src/rate_model.cpp", "max_issues_repo_name": "jlanga/smsk_selection", "max_issues_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T07:26:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-08T13:59:48.000Z", "max_forks_repo_path": "src/phyx-1.01/src/rate_model.cpp", "max_forks_repo_name": "jlanga/smsk_orthofinder", "max_forks_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-18T05:20:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:23:31.000Z", "avg_line_length": 28.805, "max_line_length": 221, "alphanum_fraction": 0.4812532546, "num_tokens": 3803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.4066008982977953}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// This file was modified by Oracle on 2014, 2016, 2017.\n// Modifications copyright (c) 2014-2017 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_CORE_SRS_HPP\n#define BOOST_GEOMETRY_CORE_SRS_HPP\n\n\n#include <cstddef>\n\n#include <boost/static_assert.hpp>\n\n#include <boost/geometry/core/radius.hpp>\n#include <boost/geometry/core/tag.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs\n{\n\n/*!\n    \\brief Defines spheroid radius values for use in geographical CS calculations\n    \\note See http://en.wikipedia.org/wiki/Figure_of_the_Earth\n          and http://en.wikipedia.org/wiki/World_Geodetic_System#A_new_World_Geodetic_System:_WGS84\n*/\ntemplate <typename RadiusType>\nclass spheroid\n{\npublic:\n    spheroid(RadiusType const& a, RadiusType const& b)\n        : m_a(a)\n        , m_b(b)\n    {}\n\n    spheroid()\n        : m_a(RadiusType(6378137.0))\n        , m_b(RadiusType(6356752.3142451793))\n    {}\n\n    template <std::size_t I>\n    RadiusType get_radius() const\n    {\n        BOOST_STATIC_ASSERT(I < 3);\n\n        return I < 2 ? m_a : m_b;\n    }\n\n    template <std::size_t I>\n    void set_radius(RadiusType const& radius)\n    {\n        BOOST_STATIC_ASSERT(I < 3);\n\n        (I < 2 ? m_a : m_b) = radius;\n    }\n\nprivate:\n    RadiusType m_a, m_b; // equatorial radius, polar radius\n};\n\n} // namespace srs\n\n// Traits specializations for spheroid\n#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS\nnamespace traits\n{\n\ntemplate <typename RadiusType>\nstruct tag< srs::spheroid<RadiusType> >\n{\n    typedef srs_spheroid_tag type;\n};\n\ntemplate <typename RadiusType>\nstruct radius_type< srs::spheroid<RadiusType> >\n{\n    typedef RadiusType type;\n};\n\ntemplate <typename RadiusType, std::size_t Dimension>\nstruct radius_access<srs::spheroid<RadiusType>, Dimension>\n{\n    typedef srs::spheroid<RadiusType> spheroid_type;\n\n    static inline RadiusType get(spheroid_type const& s)\n    {\n        return s.template get_radius<Dimension>();\n    }\n\n    static inline void set(spheroid_type& s, RadiusType const& value)\n    {\n        s.template set_radius<Dimension>(value);\n    }\n};\n\n} // namespace traits\n#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS\n\n\nnamespace srs\n{\n\n/*!\n    \\brief Defines sphere radius value for use in spherical CS calculations\n*/\ntemplate <typename RadiusType>\nclass sphere\n{\npublic:\n    explicit sphere(RadiusType const& r)\n        : m_r(r)\n    {}\n\n    sphere()\n        : m_r(RadiusType((2.0 * 6378137.0 + 6356752.3142451793) / 3.0))\n    {}\n\n    template <std::size_t I>\n    RadiusType get_radius() const\n    {\n        BOOST_STATIC_ASSERT(I < 3);\n\n        return m_r;\n    }\n\n    template <std::size_t I>\n    void set_radius(RadiusType const& radius)\n    {\n        BOOST_STATIC_ASSERT(I < 3);\n\n        m_r = radius;\n    }\n\nprivate:\n    RadiusType m_r; // radius\n};\n\n} // namespace srs\n\n// Traits specializations for sphere\n#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS\nnamespace traits\n{\n\ntemplate <typename RadiusType>\nstruct tag< srs::sphere<RadiusType> >\n{\n    typedef srs_sphere_tag type;\n};\n\ntemplate <typename RadiusType>\nstruct radius_type< srs::sphere<RadiusType> >\n{\n    typedef RadiusType type;\n};\n\ntemplate <typename RadiusType, std::size_t Dimension>\nstruct radius_access<srs::sphere<RadiusType>, Dimension>\n{\n    typedef srs::sphere<RadiusType> sphere_type;\n\n    static inline RadiusType get(sphere_type const& s)\n    {\n        return s.template get_radius<Dimension>();\n    }\n\n    static inline void set(sphere_type& s, RadiusType const& value)\n    {\n        s.template set_radius<Dimension>(value);\n    }\n};\n\n} // namespace traits\n#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_CORE_SRS_HPP\n", "meta": {"hexsha": "b8120c6560fc66a87633ef7020d8ef4cce706be7", "size": 4355, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/geometry/core/srs.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T20:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T20:03:51.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/geometry/core/srs.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:18:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:39:44.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/geometry/core/srs.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-21T17:46:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T17:46:28.000Z", "avg_line_length": 22.1065989848, "max_line_length": 99, "alphanum_fraction": 0.6985074627, "num_tokens": 1153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4065393388500099}}
{"text": "// Copyright 2019 AES WBC Authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <stdarg.h>\n\n#include <NTL/mat_GF2.h>\n\n#include \"aes_private.h\"\n\nnamespace {\n\nvoid err_quit(const char *fmt, ...) {\n  va_list ap;\n  char buf[1024];\n\n  va_start(ap, fmt);\n  vsprintf(buf, fmt, ap);\n  strcat(buf, \"\\n\");\n  fputs(buf, stderr);\n  fflush(stderr);\n  va_end(ap);\n\n  exit(1);\n}\n\nvoid read_key(const char *in, uint8_t* key, size_t size) {\n  if (strlen(in) != size << 1)\n    err_quit(\"Invalid key (should be a valid %d-bits hexadecimal string)\",\n        (size == 16) ? 128 : ((size == 24) ? 192 : 256));\n  for (size_t i = 0; i < size; i++) {\n    sscanf(in + i * 2, \"%2hhx\", key + i);\n  }\n}\n\ntemplate<typename T>\ninline NTL::vec_GF2 from_scalar(T in);\n\ntemplate<>\ninline NTL::vec_GF2 from_scalar(uint8_t in) {\n  NTL::vec_GF2 result;\n  result.SetLength(8);\n  for (int i = 0; i < 8; i++) {\n    result[7 - i] = ((in >> i) & 1);\n  }\n  return result;\n}\n\ntemplate<>\ninline NTL::vec_GF2 from_scalar(uint32_t in) {\n  NTL::vec_GF2 result;\n  result.SetLength(32);\n  for (int i = 0; i < 32; i++) {\n    result[31 - i] = ((in >> i) & 1);\n  }\n  return result;\n}\n\ntemplate<typename T>\ninline T to_scalar(const NTL::vec_GF2& in);\n\ntemplate<>\ninline uint8_t to_scalar(const NTL::vec_GF2& in) {\n  uint8_t result = 0;\n  for (int i = 0; i < 2; i++) {\n    long i0 = NTL::rep(in[i*4+0]), i1 = NTL::rep(in[i*4+1]),\n         i2 = NTL::rep(in[i*4+2]), i3 = NTL::rep(in[i*4+3]);\n    result = (result << 4) | (i0 << 3) | (i1 << 2) | (i2 << 1) | (i3 << 0);\n  }\n  return result;\n}\n\ntemplate<>\ninline uint32_t to_scalar(const NTL::vec_GF2& in) {\n  uint32_t result = 0;\n  for (int i = 0; i < 8; i++) {\n    long i0 = NTL::rep(in[i*4+0]), i1 = NTL::rep(in[i*4+1]),\n         i2 = NTL::rep(in[i*4+2]), i3 = NTL::rep(in[i*4+3]);\n    result = (result << 4) | (i0 << 3) | (i1 << 2) | (i2 << 1) | (i3 << 0);\n  }\n  return result;\n}\n\ntemplate<typename T>\ninline T mul(const NTL::mat_GF2& mat, T x) {\n  return to_scalar<T>(mat * from_scalar<T>(x));\n}\n\nNTL::mat_GF2 GenerateGF2RandomMatrix(int dimension) {\n  NTL::mat_GF2 mat(NTL::INIT_SIZE, dimension, dimension);\n  for (int i = 0; i < dimension; i++) {\n    for (int j = 0; j < dimension; j++) {\n      mat[i][j] = NTL::random_GF2();\n    }\n  }\n  return mat;\n}\n\nNTL::mat_GF2 GenerateRandomGF2InvertibleMatrix(int dimension) {\n  for (;;) {\n    NTL::mat_GF2 result = GenerateGF2RandomMatrix(dimension);\n    if (NTL::determinant(result) != 0)\n      return result;\n  }\n}\n\n// Calculate the T-boxes, which is a combination of the AddRoundKeyAfterShift\n// and the SubBytes functions.\nvoid CalculateTboxes(const uint32_t roundKey[],\n    uint8_t Tboxes[][16][256], int Nr) {\n  for (int r = 0; r < Nr; r++) {\n    for (int x = 0; x < 256; x++) {\n      uint8_t state[16] = {\n        (uint8_t)x, (uint8_t)x, (uint8_t)x, (uint8_t)x,\n        (uint8_t)x, (uint8_t)x, (uint8_t)x, (uint8_t)x,\n        (uint8_t)x, (uint8_t)x, (uint8_t)x, (uint8_t)x,\n        (uint8_t)x, (uint8_t)x, (uint8_t)x, (uint8_t)x\n      };\n      AddRoundKeyAfterShift(state, &roundKey[r*4]);\n      SubBytes(state);\n      if (r == Nr-1) {\n        AddRoundKey(state, &roundKey[4*Nr]);\n      }\n      for (int i = 0; i < 16; i++) {\n        Tboxes[r][i][x] = state[i];\n      }\n    }\n  }\n}\n\nvoid CalculateTy(uint8_t Ty[4][256][4]) {\n  for (int x = 0; x < 256; x++) {\n    Ty[0][x][0] = gf_mul[x][0];\n    Ty[0][x][1] = gf_mul[x][1];\n    Ty[0][x][2] = x;\n    Ty[0][x][3] = x;\n\n    Ty[1][x][0] = x;\n    Ty[1][x][1] = gf_mul[x][0];\n    Ty[1][x][2] = gf_mul[x][1];\n    Ty[1][x][3] = x;\n\n    Ty[2][x][0] = x;\n    Ty[2][x][1] = x;\n    Ty[2][x][2] = gf_mul[x][0];\n    Ty[2][x][3] = gf_mul[x][1];\n\n    Ty[3][x][0] = gf_mul[x][1];\n    Ty[3][x][1] = x;\n    Ty[3][x][2] = x;\n    Ty[3][x][3] = gf_mul[x][0];\n  }\n}\n\nvoid CalculateTyBoxes(uint32_t roundKey[],\n    uint32_t Tyboxes[][16][256], uint8_t TboxesLast[16][256],\n    uint32_t MBL[][16][256], bool enableL, bool enableMB, int Nr) {\n  uint8_t Tboxes[Nr][16][256];\n  uint8_t Ty[4][256][4];\n\n  CalculateTboxes(roundKey, Tboxes, Nr);\n  CalculateTy(Ty);\n\n  for (int r = 0; r < Nr-1; r++) {\n    for (int x = 0; x < 256; x++) {\n      for (int j = 0; j < 4; j++) {\n        for (int i = 0; i < 4; i++) {\n          uint32_t v0 = Ty[0][Tboxes[r][j*4 + i][x]][i],\n                   v1 = Ty[1][Tboxes[r][j*4 + i][x]][i],\n                   v2 = Ty[2][Tboxes[r][j*4 + i][x]][i],\n                   v3 = Ty[3][Tboxes[r][j*4 + i][x]][i];\n          Tyboxes[r][j*4 + i][x] = (v0 << 24) | (v1 << 16) | (v2 << 8) | v3;\n          MBL[r][j*4 + i][x] = x << ((3 - i) << 3);\n        }\n      }\n    }\n  }\n\n  for (int x = 0; x < 256; x++) {\n    for (int i = 0; i < 16; i++) {\n      TboxesLast[i][x] = Tboxes[Nr-1][i][x];\n    }\n  }\n\n  if (enableMB) {\n    NTL::mat_GF2 MB[Nr-1][4];\n    for (int r = 0; r < Nr-1; r++) {\n      for (int i = 0; i < 4; i++) {\n        MB[r][i] = GenerateRandomGF2InvertibleMatrix(32);\n      }\n    }\n\n    // When applying MB and inv(MB), the operation is quite easy; there is no\n    // need to safeguard the existing table, as it is a simple substitution. \n    for (int r = 0; r < Nr-1; r++) {\n      for (int x = 0; x < 256; x++) {\n        for (int i = 0; i < 16; i++) {\n          Tyboxes[r][i][x] = mul<uint32_t>(MB[r][i >> 2], Tyboxes[r][i][x]);\n          MBL[r][i][x] = mul<uint32_t>(NTL::inv(MB[r][i >> 2]), MBL[r][i][x]);\n        }\n      }\n    }\n  }\n\n  if (enableL) {\n    NTL::mat_GF2 L[Nr-1][16];\n    for (int r = 0; r < Nr-1; r++) {\n      for (int i = 0; i < 16; i++) {\n        L[r][i] = GenerateRandomGF2InvertibleMatrix(8);\n      }\n    }\n\n    // When applying L and inv(L), things get a little tricky. As it involves\n    // non-linear substitutions, the original table has to be copied before\n    // being updated.\n    for (int r = 0; r < Nr-1; r++) {\n      \n      if (r > 0) {\n        // Rounds 1 to Nr-1 are reversed here.\n        for (int i = 0; i < 16; i++) {\n          uint32_t oldTyboxes[256];\n          for (int x = 0; x < 256; x++)\n            oldTyboxes[x] = Tyboxes[r][i][x];\n          for (int x = 0; x < 256; x++)\n            Tyboxes[r][i][x] = oldTyboxes[mul<uint8_t>(NTL::inv(L[r-1][i]), x)];\n        }\n      }\n  \n      // Apply the L transformation at each round.\n      for (int j = 0; j < 4; ++j) {\n        for (int x = 0; x < 256; x++) {\n          uint32_t out0 = MBL[r][j*4 + 0][x];\n          uint32_t out1 = MBL[r][j*4 + 1][x];\n          uint32_t out2 = MBL[r][j*4 + 2][x];\n          uint32_t out3 = MBL[r][j*4 + 3][x];\n  \n          MBL[r][j*4 + 0][x] = (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 0]], out0 >> 24) << 24)\n                             | (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 1]], out0 >> 16) << 16)\n                             | (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 2]], out0 >>  8) <<  8)\n                             | (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 3]], out0 >>  0) <<  0);\n  \n          MBL[r][j*4 + 1][x] = (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 0]], out1 >> 24) << 24)\n                             | (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 1]], out1 >> 16) << 16)\n                             | (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 2]], out1 >>  8) <<  8)\n                             | (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 3]], out1 >>  0) <<  0);\n  \n          MBL[r][j*4 + 2][x] = (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 0]], out2 >> 24) << 24)\n                             | (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 1]], out2 >> 16) << 16)\n                             | (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 2]], out2 >>  8) <<  8)\n                             | (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 3]], out2 >>  0) <<  0);\n  \n          MBL[r][j*4 + 3][x] = (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 0]], out3 >> 24) << 24)\n                             | (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 1]], out3 >> 16) << 16)\n                             | (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 2]], out3 >>  8) <<  8)\n                             | (mul<uint8_t>(L[r][InvShiftRowsTab[j*4 + 3]], out3 >>  0) <<  0);\n        }\n      }\n    }\n  \n    // The last and final round 9 is reversed here.\n    for (int i = 0; i < 16; i++) {\n      uint8_t oldTboxesLast[256];\n      for (int x = 0; x < 256; x++)\n        oldTboxesLast[x] = TboxesLast[i][x];\n      for (int x = 0; x < 256; x++)\n        TboxesLast[i][x] = oldTboxesLast[mul<uint8_t>(NTL::inv(L[Nr-2][i]), x)];\n    }\n  }\n}\n\nvoid GenerateXorTable(FILE* out, int Nr) {\n  uint8_t Xor[Nr-1][96][16][16];\n  for (int r = 0; r < Nr-1; r++)\n    for (int n = 0; n < 96; n++)\n      for (int i = 0; i < 16; i++)\n        for (int j = 0; j < 16; j++)\n          Xor[r][n][i][j] = i ^ j;\n\n  fprintf(out, \"constexpr uint8_t Xor[%d][96][16][16] = {\\n\", Nr-1);\n  for (int r = 0; r < Nr-1; r++) {\n    fprintf(out, \"  {\\n\");\n    for (int n = 0; n < 96; n++) {\n      fprintf(out, \"    {\\n\");\n      for (int i = 0; i < 16; i++) {\n        fprintf(out, \"      { \");\n        for (int j = 0; j < 16; j++)\n          fprintf(out, \"0x%02x, \", Xor[r][n][i][j]);\n        fprintf(out, \"},\\n\");\n      }\n      fprintf(out, \"    },\\n\");\n    }\n    fprintf(out, \"  },\\n\");\n  }\n  fprintf(out, \"};\\n\\n\");\n}\n\nvoid GenerateEncryptingTables(FILE* out, uint32_t* roundKey, int Nr) {\n  uint32_t Tyboxes[Nr-1][16][256];\n  uint8_t TboxesLast[16][256];\n  uint32_t MBL[Nr-1][16][256];\n\n  CalculateTyBoxes(roundKey, Tyboxes, TboxesLast, MBL, true, true, Nr);\n\n  fprintf(out, \"constexpr uint32_t Tyboxes[%d][16][256] = {\\n\", Nr-1);\n  for (int r = 0; r < Nr-1; r++) {\n    fprintf(out, \"  {\\n\");\n    for (int i = 0; i < 16; i++) {\n      fprintf(out, \"    {\\n\");\n      for (int x = 0; x < 256; x++) {\n        if ((x % 8) == 0) {\n          fprintf(out, \"      \");\n        }\n        fprintf(out, \"0x%08x,\", Tyboxes[r][i][x]);\n        if (x > 0 && (x % 8) == 7) {\n          fprintf(out, \"\\n\");\n        } else {\n          fprintf(out, \" \");\n        }\n      }\n      fprintf(out, \"    },\\n\");\n    }\n    fprintf(out, \"  },\\n\");\n  }\n  fprintf(out, \"};\\n\\n\");\n\n  fprintf(out, \"constexpr uint8_t TboxesLast[16][256] = {\\n\");\n  for (int i = 0; i < 16; i++) {\n    fprintf(out, \"  {\\n\");\n    for (int x = 0; x < 256; x++) {\n      if (x % 16 == 0) {\n        fprintf(out, \"    \");\n      }\n      fprintf(out, \"0x%02x, \", TboxesLast[i][x]);\n      if (x % 16 == 15) {\n        fprintf(out, \"\\n\");\n      }\n    }\n    fprintf(out, \"  },\\n\");\n  }\n  fprintf(out, \"};\\n\\n\");\n\n  fprintf(out, \"constexpr uint32_t MBL[%d][16][256] = {\\n\", Nr-1);\n  for (int r = 0; r < Nr-1; r++) {\n    fprintf(out, \"  {\\n\");\n    for (int i = 0; i < 16; i++) {\n      fprintf(out, \"    {\\n\");\n      for (int x = 0; x < 256; x++) {\n        if ((x % 8) == 0) {\n          fprintf(out, \"      \");\n        }\n        fprintf(out, \"0x%08x,\", MBL[r][i][x]);\n        if (x > 0 && (x % 8) == 7) {\n          fprintf(out, \"\\n\");\n        } else {\n          fprintf(out, \" \");\n        }\n      }\n      fprintf(out, \"    },\\n\");\n    }\n    fprintf(out, \"  },\\n\");\n  }\n  fprintf(out, \"};\\n\\n\");\n}\n\nvoid GenerateTables(const char* hexKey, int Nk, int Nr) {\n  uint8_t key[Nk*4];\n  uint32_t roundKey[(Nr+1)*4];\n\n  read_key(hexKey, key, Nk*4);\n  ExpandKeys(key, roundKey, Nk, Nr);\n\n  FILE* out = fopen(\"aes_whitebox_tables.cc\", \"w\");\n\n  fprintf(out,\n      \"// This file is generated, do not edit.\\n\"\n      \"\\n\"\n      \"namespace {\\n\"\n      \"\\n\"\n      \"constexpr int Nr = %d;\\n\"\n      \"\\n\", Nr);\n\n  GenerateXorTable(out, Nr);\n  GenerateEncryptingTables(out, roundKey, Nr);\n\n  fprintf(out, \"}  // namespace\");\n\n  fflush(out);\n  fclose(out);\n}\n\nvoid syntax() {\n  err_quit(\"Syntax: aes_whitebox_gen <aes128|aes192|aes256> <hex-key>\");\n}\n\n}  // namespace\n\nint main(int argc, char* argv[]) {\n  int Nk = 0, Nr = 0;\n\n  if (argc != 3) {\n    syntax();\n  } else if (strcmp(argv[1], \"aes128\") == 0) {\n    Nk = 4, Nr = 10;\n  } else if (strcmp(argv[1], \"aes192\") == 0) {\n    Nk = 6, Nr = 12;\n  } else if (strcmp(argv[1], \"aes256\") == 0) {\n    Nk = 8, Nr = 14;\n  } else if (strcmp(argv[1], \"aes512\") == 0) {\n    Nk = 16, Nr = 22;\n  } else if (strcmp(argv[1], \"aes1024\") == 0) {\n    Nk = 32, Nr = 38;\n  } else if (strcmp(argv[1], \"aes2048\") == 0) {\n    Nk = 64, Nr = 70;\n  } else if (strcmp(argv[1], \"aes4096\") == 0) {\n    Nk = 128, Nr = 134;\n  } else {\n    syntax();\n  }\n\n  GenerateTables(argv[2], Nk, Nr);\n  return 0;\n}\n", "meta": {"hexsha": "9cb462ef36da5f687b26e088eb16f70584e8b5c1", "size": 12366, "ext": "cc", "lang": "C++", "max_stars_repo_path": "aes_whitebox_compiler.cc", "max_stars_repo_name": "balena/aes-whitebox", "max_stars_repo_head_hexsha": "6c47af74aef5042c57315e44c6495049c0ff6072", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2019-11-20T10:28:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T06:34:44.000Z", "max_issues_repo_path": "aes_whitebox_compiler.cc", "max_issues_repo_name": "balena/aes-whitebox", "max_issues_repo_head_hexsha": "6c47af74aef5042c57315e44c6495049c0ff6072", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-02-15T15:42:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-04T16:47:43.000Z", "max_forks_repo_path": "aes_whitebox_compiler.cc", "max_forks_repo_name": "balena/aes-whitebox", "max_forks_repo_head_hexsha": "6c47af74aef5042c57315e44c6495049c0ff6072", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2020-02-17T07:47:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:48:44.000Z", "avg_line_length": 28.9601873536, "max_line_length": 96, "alphanum_fraction": 0.4805110788, "num_tokens": 4656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4064787633946267}}
{"text": "#include \"kfeaturelbp.h\"\n#include \"kpicinfo.h\"\n#include \"common.h\"\n\n#include \"gdal_priv.h\"\n#include \"cpl_conv.h\" // for CPLMalloc()\n\n#include <boost/dynamic_bitset.hpp>\n#include <boost/math/special_functions/sin_pi.hpp>\n#include <boost/math/special_functions/cos_pi.hpp>\n\n#include <QCoreApplication>\n#include <QFile>\n#include <QDebug>\n\n#include <map>\n#include <utility>\n#include <limits>\n\n// test the extend function\n//    KFeatureLBP *t= new KFeatureLBP();\n//    float a[20]={1,2,3,4,\n//             2,3,4,5,\n//             3,4,5,6,\n//             4,5,6,7,\n//             5,6,7,8};\n//    float *b = new float(110);\n//    t->replicateExtend(a,b,10,11);\n//    for(int i=0;i<11;++i)\n//    {\n//        for(int j=0;j<10;++j)\n//        {\n//            std::cout<<int(b[10*i+j])<<\" \";\n//        }\n//        std::cout<<\"\\r\\n\";\n//    }\n//    std::cout<<\"end\"<<std::endl;\n//    delete b;\nKFeatureLBP::~KFeatureLBP()\n{\n    CPLFree(m_pHistogram);\n\n    for(int bandIndex = 0;bandIndex<m_bandNum;++bandIndex){\n        //qDebug()<<m_extDataBuff[bandIndex];\n        CPLFree(m_extDataBuff[bandIndex]);\n    }\n    CPLFree(m_extDataBuff);\n}\n\nKFeatureLBP::KFeatureLBP(GDALDataset *piDataset, GDALDataset *poDataset, int sampleNum, int kernelRadius, bool improved)\n    : m_piDataset(piDataset),\n      m_poDataset(poDataset),\n      m_kernelRadius(kernelRadius),\n      m_sampleNum(sampleNum),\n      m_beImproved(improved),\n      m_fileName(\"\"),\n      refTable(NULL)\n{\n\n}\n\nbool KFeatureLBP::calLBP(float *inBuff, GByte *outBuff, int width, int height,bool toBeNormarlized, KProgressBar * pProgressBar)\n{\n    assert(NULL != outBuff);\n    assert(NULL != inBuff);\n\n    boost::dynamic_bitset<> tempOne(m_sampleNum,1);\n    boost::dynamic_bitset<> tempZero(m_sampleNum,0);\n\n    GUIntBig maxValue = get2Power(m_sampleNum);\n\n    for(int iYPos = m_kernelRadius,iYDes=0;iYPos<height-m_kernelRadius;++iYPos,++iYDes)\n    {\n        for(int iXPos = m_kernelRadius,iXDes=0;iXPos<width-m_kernelRadius;++iXPos,++iXDes)\n        {\n            boost::dynamic_bitset<> tempbin(m_sampleNum,0);\n            // calculate anticlockwise\n            for(int nsCnt=0;nsCnt<m_sampleNum;++nsCnt)\n            {\n                float fxAxis = iXPos + m_kernelRadius*boost::math::cos_pi(2.*nsCnt/m_sampleNum);\n                float fyAxis = iYPos - m_kernelRadius*boost::math::sin_pi(2.*nsCnt/m_sampleNum);\n                int ixAxis = static_cast<int>(fxAxis);\n                int iyAxis = static_cast<int>(fyAxis);\n                fxAxis = fxAxis-ixAxis;\n                fyAxis = fyAxis-iyAxis;\n                /** bilinear interpolation algorithm\n                 * y x-------\n                 * |(0,0)\n                 * |  |a   b|\n                 * |  | x,y | --> gray(x,y)=(1-x)*[(1-y)*a + y*c] + x*[(1-y)*b + y*d]\n                 * |  |c   d|\n                 *\n                 *                  |f(0,0) f(1,0)||1-y|\n                 * gray(x,y)=[1-x,x]|             ||   |\n                 *                  |f(0,1) f(1,1)|| y |\n                 */\n                float tempValue = (1-fxAxis)*((1-fyAxis)*inBuff[iyAxis*width+ixAxis]\n                        +fyAxis*inBuff[(iyAxis+1)*width+ixAxis])\n                        +fxAxis*((1-fyAxis)*inBuff[iyAxis*width+ixAxis+1]\n                        +fyAxis*inBuff[(iyAxis+1)*width+ixAxis+1]);\n\n                tempbin <<= 1;\n                tempbin |= tempValue>inBuff[iYPos*width+iXPos]?tempOne:tempZero;\n            }\n            if(NULL != pProgressBar) pProgressBar->autoUpdate();\n            if(toBeNormarlized==false)\n            {\n                if(m_beImproved) outBuff[iYDes*(width-2*m_kernelRadius)+iXDes]=refTable[tempbin.to_ulong()];\n                else outBuff[iYDes*(width-2*m_kernelRadius)+iXDes]=tempbin.to_ulong()*255./maxValue;\n            }\n            else{\n                if(m_beImproved) outBuff[iYDes*(width-2*m_kernelRadius)+iXDes]=refTable[tempbin.to_ulong()]*255./(m_sampleNum+2.);\n                // here we suppose that the traditional lbp is normarlized anyway\n                else outBuff[iYDes*(width-2*m_kernelRadius)+iXDes]=tempbin.to_ulong()*255./maxValue;\n            }\n\n//            tempbin=tempZero;\n//            tempbin <<= 1;\n//            tempbin |= inBuff[iYPos*width+iXPos+1]>inBuff[iYPos*width+iXPos]?tempOne:tempZero;\n//            tempbin <<= 1;\n//            tempbin |= inBuff[(iYPos-1)*width+iXPos+1]>inBuff[iYPos*width+iXPos]?tempOne:tempZero;\n//            tempbin <<= 1;\n//            tempbin |= inBuff[(iYPos-1)*width+iXPos]>inBuff[iYPos*width+iXPos]?tempOne:tempZero;\n//            tempbin <<= 1;\n//            tempbin |= inBuff[(iYPos-1)*width+iXPos-1]>inBuff[iYPos*width+iXPos]?tempOne:tempZero;\n//            tempbin <<= 1;\n//            tempbin |= inBuff[iYPos*width+iXPos-1]>inBuff[iYPos*width+iXPos]?tempOne:tempZero;\n//            tempbin <<= 1;\n//            tempbin |= inBuff[(iYPos+1)*width+iXPos-1]>inBuff[iYPos*width+iXPos]?tempOne:tempZero;\n//            tempbin <<= 1;\n//            tempbin |= inBuff[(iYPos+1)*width+iXPos]>inBuff[iYPos*width+iXPos]?tempOne:tempZero;\n//            tempbin <<= 1;\n//            tempbin |= inBuff[(iYPos+1)*width+iXPos+1]>inBuff[iYPos*width+iXPos]?tempOne:tempZero;\n//            outBuff[iYDes*(width-2*m_kernelRadius)+iXDes]=tempbin.to_ulong();\n        }\n    }\n\n    return true;\n}\n\nbool KFeatureLBP::run(Kapok::K_BorderTypes type,bool toBeNormarlized)\n{\n    int bandNum = KPicInfo::getInstance()->getBandNum();\n    int nXSize = KPicInfo::getInstance()->getWidth();\n    int nYSize = KPicInfo::getInstance()->getHeight();\n\n    //GDALRasterBand * piBand = NULL;\n    GDALRasterBand * poBand = NULL;\n    //float *pafData = NULL;\n    GByte *pafOutData = NULL;\n    int err_code = 1 + bandNum;\n    if(externDataSet(type)) err_code -= 1;\n\n    if(m_beImproved){\n        // create the reference table\n        GUIntBig maxIndex = get2Power(m_sampleNum);\n        GUIntBig minValue = 0;\n        KProgressBar progressBar(\"Calculating LBP refTable\",maxIndex,80);\n        K_PROGRESS_START(progressBar);\n        for(GUIntBig index = 0;index < maxIndex;++index)\n        {\n            // Achieving Rotation Invariance\n            minValue = index;\n            // leave the template args to be empty means determined by the compiler\n            boost::dynamic_bitset<> bin(m_sampleNum, index);\n            for(int pos = 0;pos<m_sampleNum;++pos){\n                boost::dynamic_bitset<> tempbin=(bin>>pos)|(bin<<m_sampleNum-pos);\n                if(minValue>tempbin.to_ulong()){\n                    minValue = tempbin.to_ulong();\n                }\n            }\n            // confirm the \"Uniform\" Patterns\n            boost::dynamic_bitset<> temp(m_sampleNum,minValue);\n            GByte cycleSum = abs(temp[0] - temp[m_sampleNum - 1]);\n            // the default value is set to be the num of bits which are set\n            refTable[index] = bin.count();\n            for(GByte pos = 0;pos < m_sampleNum - 1;++pos)\n            {\n                cycleSum += abs(temp[pos]-temp[pos+1]);\n                if(cycleSum > 2){\n                    refTable[index] = m_sampleNum+1;\n                    break;\n                }\n            }\n            progressBar.autoUpdate();\n        }\n        K_PROGRESS_END(progressBar);\n    }\n\n    KProgressBar progressBar(\"Calculating LBP feature\",bandNum*nXSize*nYSize,80);\n    K_PROGRESS_START(progressBar);\n    // get the LBP feature\n    pafOutData = (GByte *) CPLMalloc(sizeof(GByte)*nXSize*nYSize);\n    //pafData = (float *) CPLMalloc(sizeof(float)*(nXSize + 2*m_kernelRadius + 1)*(nYSize + 2*m_kernelRadius + 1));\n    for(int index = 0; index < bandNum; ++index)\n    {\n        //piBand = m_piDataset->GetRasterBand(index + 1);\n        poBand = m_poDataset->GetRasterBand(index + 1);\n\n//        piBand->RasterIO( GF_Read, 0, 0, nXSize + 2*m_kernelRadius + 1, nYSize + 2*m_kernelRadius + 1\n//                          , pafData, nXSize + 2*m_kernelRadius + 1, nYSize + 2*m_kernelRadius + 1\n//                          , GDT_Float32, 0, 0 );\n\n        if(calLBP(m_extDataBuff[index],pafOutData,nXSize + 2*m_kernelRadius,nYSize + 2*m_kernelRadius,toBeNormarlized,&progressBar)) err_code -= 1;\n\n        poBand->RasterIO( GF_Write, 0, 0, nXSize , nYSize, pafOutData\n                          , nXSize, nYSize, GDT_Byte, 0, 0 );\n        poBand->FlushCache();\n\n    }\n    K_PROGRESS_END(progressBar);\n\n    GDALClose(m_poDataset);\n\n    std::map<int,long> histMap;\n    int maxValue = (std::numeric_limits<int>::min)();\n\n    if(!m_beImproved || toBeNormarlized) maxValue=256;\n    else maxValue = m_sampleNum+2;\n\n    for(int index = 0;index<maxValue;++index) histMap[index]=0;\n    for(long index = 0;index<nXSize*nYSize;++index){ histMap[pafOutData[index]]++; }\n    m_pHistogram = (long *) CPLMalloc(sizeof(long)*maxValue+sizeof(long));\n    m_pHistogram[0]=maxValue;\n    // key start at 0\n    for(std::map<int,long>::iterator it = histMap.begin();it != histMap.end();++it){\n        m_pHistogram[it->first+1]=it->second;\n    }\n\n    // release\n    if(NULL != refTable) CPLFree(refTable);\n    //CPLFree(pafData);\n    CPLFree(pafOutData);\n//    char ** filelist;// =m_piDataset->GetFileList();\n//    GDALClose(m_piDataset);\n\n//    // just fetch the first one\n//    QString temp(*filelist);\n//    CSLDestroy (filelist);\n//    QFile file(temp);\n//    if(!file.remove()) std::cout<<\"KFeatureLBP:remove the temp file failed!\"<<std::endl;\n//    //qDebug()<<\"close\";\n\n\n    return (0 == err_code);\n}\n\nGDALDataset *KFeatureLBP::build(QString fileName)\n{\n    m_fileName = fileName;\n    if(KPicInfo::dataAttach(m_piDataset)) KPicInfo::getInstance()->build();\n    //qDebug()<<\"failed\";qDebug()<<KPicInfo::dataAttach(m_piDataset);\n    int bandNum = KPicInfo::getInstance()->getBandNum();\n    int nXSize = KPicInfo::getInstance()->getWidth();\n    int nYSize = KPicInfo::getInstance()->getHeight();\n\n    if(m_sampleNum > 24){\n        std::cout<<\"KFeatureLBP:Sample points cannot more than 24!\"<<std::endl;\n        exit( 1 );\n    }\n\n    bool beSame = K_CheckDataSetEqu(m_piDataset,m_poDataset);\n\n    if(!beSame){\n        QString tempName=QCoreApplication::applicationDirPath()+\"/tempImg%%KFeatureLBP\";\n        //QString tempInputName=QCoreApplication::applicationDirPath()+\"/tempExtImg%%KFeatureLBP\"+KPicInfo::getInstance()->getFileExtName();\n        //QString tempName=\"D:/tempImg%%KFeatureLBP\";\n        //QString tempInputName=\"D:/tempExtImg%%KFeatureLBP\"+KPicInfo::getInstance()->getFileExtName();\n        if(!m_fileName.isEmpty()){ tempName = m_fileName; }\n\n        const char *pszFormat = m_piDataset->GetDriverName();\n        GDALDriver *poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat);\n        if( poDriver == NULL )\n        {\n            std::cout<<\"KFeatureLBP:GetGDALDriverManager failed!\"<<std::endl;\n            exit( 1 );\n        }\n        if( CSLFetchBoolean( poDriver->GetMetadata(), GDAL_DCAP_CREATE, FALSE ) )\n        {\n            //qDebug( \"KFeatureLBP:Driver %s supports Create() method.\", pszFormat );\n            m_realExtName = KPicInfo::getInstance()->getFileExtName();\n        }\n        else\n        {\n            poDriver = GetGDALDriverManager()->GetDriverByName(\"BMP\");\n            m_realExtName = \".bmp\";\n        }\n        tempName += m_realExtName;\n        if(NULL != m_poDataset) GDALClose(m_poDataset);\n        // allocate the output Dataset\n        m_poDataset = poDriver->Create(tempName.toUtf8().data(),nXSize,nYSize\n                                       ,bandNum,GDT_Byte,0);\n        // store the previous handle\n        //m_piOrgDataset = m_piDataset;\n        // +1 is to guarantee the success of bilinear interpolation algorithm\n        // build the new handle to store the extended image\n        //qDebug()<<\"failed\";qDebug()<<KPicInfo::getInstance()->getType();\n        m_extDataBuff = (float **) CPLMalloc(sizeof(float *)*bandNum);\n        m_bandNum = bandNum;\n        for(int bandIndex = 0;bandIndex<bandNum;++bandIndex){\n            m_extDataBuff[bandIndex] = (float *) CPLMalloc(sizeof(float)*(nXSize+2*m_kernelRadius + 1)*(nYSize+2*m_kernelRadius + 1));\n        }\n//        m_piDataset = poDriver->Create(tempInputName.toUtf8().data()\n//                                       ,nXSize+2*m_kernelRadius + 1,nYSize+2*m_kernelRadius + 1\n//                                       ,bandNum,KPicInfo::getInstance()->getType(),0);\n\n    }else{\n        std::cout<<\"KFeatureLBP:the input and output cannot be same!\"<<std::endl;\n        m_poDataset = NULL;\n    }\n\n    assert(NULL != m_poDataset);\n\n    if(NULL != refTable) CPLFree(refTable);\n    if(m_beImproved) refTable = (unsigned char *) CPLMalloc(sizeof(unsigned char)*get2Power(m_sampleNum));\n    else refTable=NULL;\n\n    return m_poDataset;\n}\n\nbool KFeatureLBP::constExtend(float * inBuff, float * outBuff, int width, int height, float defaultValue)\n{\n    assert(NULL != outBuff);\n    assert(NULL != inBuff);\n\n    // fill the outbuff with the default value\n    for(GIntBig index = 0;index < (width + 1) * (height + 1);++index)\n    {\n        outBuff[index] = defaultValue;\n    }\n    // copy the source to the outbuff\n    for(int iYDes = m_kernelRadius,iYSrc = 0;iYDes < height - m_kernelRadius;++iYDes,++iYSrc)\n    {\n        for(int iXDes = m_kernelRadius,iXSrc = 0;iXDes < width - m_kernelRadius;++iXDes,++iXSrc)\n        {\n            outBuff[iYDes*width+iXDes] = inBuff[iYSrc*(width-2*m_kernelRadius)+iXSrc];\n        }\n    }\n    return true;\n}\n\nbool KFeatureLBP::reflectExtend(float * inBuff, float * outBuff, int width, int height)\n{\n    assert(NULL != outBuff);\n    assert(NULL != inBuff);\n\n    if(width < 3 * m_kernelRadius || height < 3 * m_kernelRadius)\n    {\n        std::cout<<\"KFeatureLBP:each line of the image cannot be shorter than KernelSize!\"<<std::endl;\n        exit( 1 );\n    }\n    // copy the source to the outbuff\n    for(int iYDes = m_kernelRadius,iYSrc = 0;iYDes < height - m_kernelRadius;++iYDes,++iYSrc)\n    {\n        for(int iXDes = m_kernelRadius,iXSrc = 0;iXDes < width - m_kernelRadius;++iXDes,++iXSrc)\n        {\n            outBuff[iYDes*width+iXDes] = inBuff[iYSrc*(width-2*m_kernelRadius)+iXSrc];\n        }\n    }\n\n    // fill horizontal\n    for(int iYDes = m_kernelRadius;iYDes < height - m_kernelRadius;++iYDes)\n    {\n        // fill the head of each line\n        int iXDes = m_kernelRadius-1,iXSrc = m_kernelRadius+1;\n        for(;iXDes >= 0 && iXSrc < width - m_kernelRadius;--iXDes,++iXSrc)\n        {\n            outBuff[iYDes*width+iXDes] = outBuff[iYDes*width+iXSrc];\n        }\n        for(;iXDes >= 0;--iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = outBuff[iYDes*width+iXSrc-1];\n        }\n        // fill the end of each line\n        iXDes = width - m_kernelRadius,iXSrc = width - m_kernelRadius - 2;\n        for(;iXDes < width + 1&& iXSrc >= m_kernelRadius;++iXDes,--iXSrc)\n        {\n            outBuff[iYDes*width+iXDes] = outBuff[iYDes*width+iXSrc];\n        }\n        for(;iXDes < width + 1;++iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = outBuff[iYDes*width+iXSrc+1];\n        }\n    }\n\n    // fill vertical -- think rotate 90 degrees\n    for(int iYDes = m_kernelRadius;iYDes < width - m_kernelRadius;++iYDes)\n    {\n        // fill the head of each line\n        int iXDes = m_kernelRadius-1,iXSrc = m_kernelRadius+1;\n        for(;iXDes >= 0 && iXSrc < height - m_kernelRadius;--iXDes,++iXSrc)\n        {\n            outBuff[iXDes*width+iYDes] = outBuff[iXSrc*width+iYDes];\n        }\n        for(;iXDes >= 0;--iXDes)\n        {\n            outBuff[iXDes*width+iYDes] = outBuff[(iXSrc-1)*width+iYDes];\n        }\n        // fill the end of each line\n        iXDes = height - m_kernelRadius,iXSrc = height - m_kernelRadius - 2;\n        for(;iXDes < height + 1 && iXSrc >= m_kernelRadius;++iXDes,--iXSrc)\n        {\n            outBuff[iXDes*width+iYDes] = outBuff[iXSrc*width+iYDes];\n        }\n        for(;iXDes < height + 1;++iXDes)\n        {\n            outBuff[iXDes*width+iYDes] = outBuff[(iXSrc+1)*width+iYDes];\n        }\n    }\n\n    // fill four corners, please find the axis of symmetry carefully\n    for(int iYDes = 0;iYDes < m_kernelRadius;++iYDes)\n    {\n        for(int iXDes = 0;iXDes < m_kernelRadius;++iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = (outBuff[(2*m_kernelRadius-iYDes)*width+iXDes]+outBuff[iYDes*width+2*m_kernelRadius-iXDes])/2;\n        }\n    }\n    for(int iYDes = 0;iYDes < m_kernelRadius;++iYDes)\n    {\n        for(int iXDes = width-m_kernelRadius;iXDes < width + 1;++iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = (outBuff[(2*m_kernelRadius-iYDes)*width+iXDes]+outBuff[iYDes*width+2*(width-m_kernelRadius-1)-iXDes])/2;\n        }\n    }\n    for(int iYDes = height - m_kernelRadius;iYDes < height + 1;++iYDes)\n    {\n        for(int iXDes = 0;iXDes < m_kernelRadius;++iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = (outBuff[(2*(height-m_kernelRadius-1)-iYDes)*width+iXDes]+outBuff[iYDes*width+2*m_kernelRadius-iXDes])/2;\n        }\n    }\n    for(int iYDes = height - m_kernelRadius;iYDes < height + 1;++iYDes)\n    {\n        for(int iXDes = width - m_kernelRadius;iXDes < width + 1;++iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = (outBuff[(2*(height-m_kernelRadius-1)-iYDes)*width+iXDes]+outBuff[iYDes*width+2*(width-m_kernelRadius-1)-iXDes])/2;\n        }\n    }\n    return true;\n}\n\nbool KFeatureLBP::replicateExtend(float * inBuff, float * outBuff, int width, int height)\n{\n    assert(NULL != outBuff);\n    assert(NULL != inBuff);\n\n    if(width < 3 * m_kernelRadius || height < 3 * m_kernelRadius)\n    {\n        std::cout<<\"KFeatureLBP:each line of the image cannot be shorter than KernelSize!\"<<std::endl;\n        exit( 1 );\n    }\n    // copy the source to the outbuff\n    for(int iYDes = m_kernelRadius,iYSrc = 0;iYDes < height - m_kernelRadius;++iYDes,++iYSrc)\n    {\n        for(int iXDes = m_kernelRadius,iXSrc = 0;iXDes < width - m_kernelRadius;++iXDes,++iXSrc)\n        {\n            outBuff[iYDes*width+iXDes] = inBuff[iYSrc*(width-2*m_kernelRadius)+iXSrc];\n        }\n    }\n\n    // fill horizontal\n    for(int iYDes = m_kernelRadius;iYDes < height - m_kernelRadius;++iYDes)\n    {\n        // fill the head of each line\n        int iXDes = m_kernelRadius-1,iXSrc = m_kernelRadius;\n        for(;iXDes >= 0 && iXSrc < width - m_kernelRadius;--iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = outBuff[iYDes*width+iXSrc];\n        }\n        for(;iXDes >= 0;--iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = outBuff[iYDes*width+iXSrc];\n        }\n        // fill the end of each line\n        iXDes = width - m_kernelRadius,iXSrc = width - m_kernelRadius - 1;\n        for(;iXDes < width + 1 && iXSrc >= m_kernelRadius;++iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = outBuff[iYDes*width+iXSrc];\n        }\n        for(;iXDes < width + 1;++iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = outBuff[iYDes*width+iXSrc];\n        }\n    }\n\n    // fill vertical -- think rotate 90 degrees\n    for(int iYDes = m_kernelRadius;iYDes < width - m_kernelRadius;++iYDes)\n    {\n        // fill the head of each line\n        int iXDes = m_kernelRadius-1,iXSrc = m_kernelRadius;\n        for(;iXDes >= 0 && iXSrc < height - m_kernelRadius;--iXDes)\n        {\n            outBuff[iXDes*width+iYDes] = outBuff[iXSrc*width+iYDes];\n        }\n        for(;iXDes >= 0;--iXDes)\n        {\n            outBuff[iXDes*width+iYDes] = outBuff[iXSrc*width+iYDes];\n        }\n        // fill the end of each line\n        iXDes = height - m_kernelRadius,iXSrc = height - m_kernelRadius - 1;\n        for(;iXDes < height + 1 && iXSrc >= m_kernelRadius;++iXDes)\n        {\n            outBuff[iXDes*width+iYDes] = outBuff[iXSrc*width+iYDes];\n        }\n        for(;iXDes < height + 1;++iXDes)\n        {\n            outBuff[iXDes*width+iYDes] = outBuff[iXSrc*width+iYDes];\n        }\n    }\n\n    // fill four corners, please find the axis of symmetry carefully\n    for(int iYDes = 0;iYDes < m_kernelRadius;++iYDes)\n    {\n        for(int iXDes = 0;iXDes < m_kernelRadius;++iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = outBuff[m_kernelRadius*width+m_kernelRadius];\n        }\n    }\n    for(int iYDes = 0;iYDes < m_kernelRadius;++iYDes)\n    {\n        for(int iXDes = width-m_kernelRadius;iXDes < width + 1;++iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = outBuff[m_kernelRadius*width+width-m_kernelRadius-1];\n        }\n    }\n    for(int iYDes = height - m_kernelRadius;iYDes < height + 1;++iYDes)\n    {\n        for(int iXDes = 0;iXDes < m_kernelRadius;++iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = outBuff[(height-m_kernelRadius-1)*width+m_kernelRadius];\n        }\n    }\n    for(int iYDes = height - m_kernelRadius;iYDes < height + 1;++iYDes)\n    {\n        for(int iXDes = width - m_kernelRadius;iXDes < width + 1;++iXDes)\n        {\n            outBuff[iYDes*width+iXDes] = outBuff[(height-m_kernelRadius-1)*width+width-m_kernelRadius-1];\n        }\n    }\n    return true;\n}\n\nbool KFeatureLBP::externDataSet(Kapok::K_BorderTypes type,float defaultValue)\n{\n    int bandNum = KPicInfo::getInstance()->getBandNum();\n    int nXSize = KPicInfo::getInstance()->getWidth();\n    int nYSize = KPicInfo::getInstance()->getHeight();\n    unsigned int err = bandNum;\n    GDALRasterBand * piBand = NULL;\n    //GDALRasterBand * poBand = NULL;\n    float *pafData = NULL;\n    //float *pafOutData = NULL;\n    pafData = (float *) CPLMalloc(sizeof(float)*nXSize*nYSize);\n    //pafOutData = (float *) CPLMalloc(sizeof(float)*(nXSize + 2*m_kernelRadius + 1)*(nYSize + 2*m_kernelRadius + 1));\n    for(int index = 0; index < bandNum; ++index)\n    {\n        piBand = m_piDataset->GetRasterBand(index + 1);\n        //poBand = m_piDataset->GetRasterBand(index + 1);\n\n        piBand->RasterIO( GF_Read, 0, 0, nXSize, nYSize, pafData, nXSize, nYSize, GDT_Float32, 0, 0 );\n        switch(type)\n        {\n        case Kapok::Border_Constant:\n            err -= constExtend(pafData, m_extDataBuff[index], nXSize + 2*m_kernelRadius, nYSize + 2*m_kernelRadius, defaultValue);\n            break;\n        case Kapok::Border_Replicate:\n            err -= replicateExtend(pafData, m_extDataBuff[index], nXSize + 2*m_kernelRadius, nYSize + 2*m_kernelRadius);\n            break;\n        case Kapok::Border_Reflect:\n        default:\n            err -= reflectExtend(pafData, m_extDataBuff[index], nXSize + 2*m_kernelRadius, nYSize + 2*m_kernelRadius);\n            break;\n        }\n\n//        poBand->RasterIO( GF_Write, 0, 0, nXSize + 2*m_kernelRadius + 1\n//                          , nYSize + 2*m_kernelRadius + 1, pafOutData\n//                          , nXSize + 2*m_kernelRadius + 1, nYSize + 2*m_kernelRadius + 1, GDT_Float32, 0, 0 );\n//        poBand->FlushCache();\n    }\n    CPLFree(pafData);\n    //CPLFree(pafOutData);\n\n    return !err;\n}\n\nQString KFeatureLBP::getSVMString(int start)\n{\n    int size = m_pHistogram[0];\n    QString temp(\"\");\n    if(NULL==m_pHistogram) exit(1);\n//    for(int index= start;index<start+size;++index){\n//        temp+=QString(\"%1:%%2 \").arg(index).arg(index-start+1);\n//    }\n    for(int index = 1;index<size+1;++index){\n        temp+=QString(\"%1:%2 \").arg(index-1+start).arg(m_pHistogram[index]);\n        //temp=QString(temp).arg(m_pHistogram[index]);\n        //qDebug()<<temp;\n    }\n    return temp;\n}\n", "meta": {"hexsha": "140f5799a6fe5569825bd1e199bf1cbf3b9c15f4", "size": 23145, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kfeaturelbp.cpp", "max_stars_repo_name": "PlainSailing/GraduationDesignTest", "max_stars_repo_head_hexsha": "cebcfcdc6d04b24c5e0ba03b962d6896694369ab", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-27T07:20:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T07:20:30.000Z", "max_issues_repo_path": "kfeaturelbp.cpp", "max_issues_repo_name": "PlainSailing/GraduationDesignTest", "max_issues_repo_head_hexsha": "cebcfcdc6d04b24c5e0ba03b962d6896694369ab", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kfeaturelbp.cpp", "max_forks_repo_name": "PlainSailing/GraduationDesignTest", "max_forks_repo_head_hexsha": "cebcfcdc6d04b24c5e0ba03b962d6896694369ab", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4468438538, "max_line_length": 156, "alphanum_fraction": 0.5882047959, "num_tokens": 6788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.40645389925569697}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2019 Mikhail Komarov <nemo@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_STREAM_SALSA20_POLICY_HPP\n#define CRYPTO3_STREAM_SALSA20_POLICY_HPP\n\n#include <boost/endian/conversion.hpp>\n\n#include <nil/crypto3/detail/inline_variable.hpp>\n\n#include <nil/crypto3/stream/detail/basic_functions.hpp>\n\n#define SALSA20_QUARTER_ROUND(x1, x2, x3, x4) \\\n    do {                                      \\\n        x2 ^= policy_type::rotl<7>(x1 + x4);  \\\n        x3 ^= policy_type::rotl<9>(x2 + x1);  \\\n        x4 ^= policy_type::rotl<13>(x3 + x2); \\\n        x1 ^= policy_type::rotl<18>(x4 + x3); \\\n    } while (0)\n\nnamespace nil {\n    namespace crypto3 {\n        namespace stream {\n            namespace detail {\n                template<std::size_t IVBits, std::size_t KeyBits, std::size_t Rounds>\n                struct salsa20_policy : public basic_functions<32> {\n                    typedef basic_functions<32> policy_type;\n\n                    typedef typename policy_type::byte_type byte_type;\n                    typedef typename policy_type::word_type word_type;\n\n                    constexpr static const std::size_t rounds = Rounds;\n                    BOOST_STATIC_ASSERT(Rounds % 2 == 0);\n\n                    constexpr static const std::size_t value_bits = CHAR_BIT;\n                    typedef byte_type value_type;\n\n                    constexpr static const std::size_t block_size = 64;\n                    constexpr static const std::size_t block_bits = block_size * value_bits;\n                    typedef std::array<byte_type, block_size> block_type;\n\n                    constexpr static const std::size_t min_key_bits = 16 * CHAR_BIT;\n                    constexpr static const std::size_t max_key_bits = 32 * CHAR_BIT;\n                    constexpr static const std::size_t key_bits = KeyBits;\n                    constexpr static const std::size_t key_size = key_bits / CHAR_BIT;\n                    BOOST_STATIC_ASSERT(min_key_bits <= KeyBits <= max_key_bits);\n                    BOOST_STATIC_ASSERT(key_size % 16 == 0);\n                    typedef std::array<byte_type, key_size> key_type;\n\n                    constexpr static const std::size_t key_schedule_size = 16;\n                    constexpr static const std::size_t key_schedule_bits = key_schedule_size * word_bits;\n                    typedef std::array<word_type, key_schedule_size> key_schedule_type;\n\n                    constexpr static const std::size_t round_constants_size = 4;\n                    typedef std::array<word_type, round_constants_size> round_constants_type;\n\n                    CRYPTO3_INLINE_VARIABLE(round_constants_type, tau,\n                                            ({0x61707865, 0x3120646e, 0x79622d36, 0x6b206574}));\n                    CRYPTO3_INLINE_VARIABLE(round_constants_type, sigma,\n                                            ({0x61707865, 0x3320646e, 0x79622d32, 0x6b206574}));\n\n                    constexpr static const std::size_t iv_bits = IVBits;\n                    constexpr static const std::size_t iv_size = IVBits / CHAR_BIT;\n                    typedef std::array<byte_type, iv_size> iv_type;\n\n                    static void hsalsa20(word_type output[8], const key_schedule_type input) {\n                        word_type x00 = input[0], x01 = input[1], x02 = input[2], x03 = input[3], x04 = input[4],\n                                  x05 = input[5], x06 = input[6], x07 = input[7], x08 = input[8], x09 = input[9],\n                                  x10 = input[10], x11 = input[11], x12 = input[12], x13 = input[13], x14 = input[14],\n                                  x15 = input[15];\n\n                        for (size_t i = 0; i != rounds / 2; ++i) {\n                            SALSA20_QUARTER_ROUND(x00, x04, x08, x12);\n                            SALSA20_QUARTER_ROUND(x05, x09, x13, x01);\n                            SALSA20_QUARTER_ROUND(x10, x14, x02, x06);\n                            SALSA20_QUARTER_ROUND(x15, x03, x07, x11);\n\n                            SALSA20_QUARTER_ROUND(x00, x01, x02, x03);\n                            SALSA20_QUARTER_ROUND(x05, x06, x07, x04);\n                            SALSA20_QUARTER_ROUND(x10, x11, x08, x09);\n                            SALSA20_QUARTER_ROUND(x15, x12, x13, x14);\n                        }\n\n                        output[0] = x00;\n                        output[1] = x05;\n                        output[2] = x10;\n                        output[3] = x15;\n                        output[4] = x06;\n                        output[5] = x07;\n                        output[6] = x08;\n                        output[7] = x09;\n                    }\n\n                    static void salsa_core(block_type &block, const key_schedule_type &input) {\n                        word_type x00 = input[0], x01 = input[1], x02 = input[2], x03 = input[3], x04 = input[4],\n                                  x05 = input[5], x06 = input[6], x07 = input[7], x08 = input[8], x09 = input[9],\n                                  x10 = input[10], x11 = input[11], x12 = input[12], x13 = input[13], x14 = input[14],\n                                  x15 = input[15];\n\n                        for (size_t i = 0; i != rounds / 2; ++i) {\n                            SALSA20_QUARTER_ROUND(x00, x04, x08, x12);\n                            SALSA20_QUARTER_ROUND(x05, x09, x13, x01);\n                            SALSA20_QUARTER_ROUND(x10, x14, x02, x06);\n                            SALSA20_QUARTER_ROUND(x15, x03, x07, x11);\n\n                            SALSA20_QUARTER_ROUND(x00, x01, x02, x03);\n                            SALSA20_QUARTER_ROUND(x05, x06, x07, x04);\n                            SALSA20_QUARTER_ROUND(x10, x11, x08, x09);\n                            SALSA20_QUARTER_ROUND(x15, x12, x13, x14);\n                        }\n\n                        boost::endian::store_little_u32(x00 + input[0], block[4 * 0]);\n                        boost::endian::store_little_u32(x01 + input[1], block[4 * 1]);\n                        boost::endian::store_little_u32(x02 + input[2], block[4 * 2]);\n                        boost::endian::store_little_u32(x03 + input[3], block[4 * 3]);\n                        boost::endian::store_little_u32(x04 + input[4], block[4 * 4]);\n                        boost::endian::store_little_u32(x05 + input[5], block[4 * 5]);\n                        boost::endian::store_little_u32(x06 + input[6], block[4 * 6]);\n                        boost::endian::store_little_u32(x07 + input[7], block[4 * 7]);\n                        boost::endian::store_little_u32(x08 + input[8], block[4 * 8]);\n                        boost::endian::store_little_u32(x09 + input[9], block[4 * 9]);\n                        boost::endian::store_little_u32(x10 + input[10], block[4 * 10]);\n                        boost::endian::store_little_u32(x11 + input[11], block[4 * 11]);\n                        boost::endian::store_little_u32(x12 + input[12], block[4 * 12]);\n                        boost::endian::store_little_u32(x13 + input[13], block[4 * 13]);\n                        boost::endian::store_little_u32(x14 + input[14], block[4 * 14]);\n                        boost::endian::store_little_u32(x15 + input[15], block[4 * 15]);\n                    }\n                };\n            }    // namespace detail\n        }        // namespace stream\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_SALSA20_POLICY_HPP\n", "meta": {"hexsha": "42dd2de30c8b64d14874cee21fa64b78b0af3e49", "size": 8658, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/stream/detail/salsa20/salsa20_policy.hpp", "max_stars_repo_name": "NilFoundation/crypto3-stream", "max_stars_repo_head_hexsha": "104802b3f0f1097174acc457f93a34ea4e875ca2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "include/nil/crypto3/stream/detail/salsa20/salsa20_policy.hpp", "max_issues_repo_name": "NilFoundation/crypto3-stream", "max_issues_repo_head_hexsha": "104802b3f0f1097174acc457f93a34ea4e875ca2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/nil/crypto3/stream/detail/salsa20/salsa20_policy.hpp", "max_forks_repo_name": "NilFoundation/crypto3-stream", "max_forks_repo_head_hexsha": "104802b3f0f1097174acc457f93a34ea4e875ca2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-12T10:53:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:53:21.000Z", "avg_line_length": 55.1464968153, "max_line_length": 118, "alphanum_fraction": 0.5274890275, "num_tokens": 2071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4064538992556969}}
{"text": "/**\n * ****************************************************************************\n * Copyright (c) 2015, Robert Lukierski.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n * ****************************************************************************\n * N-Sphere.\n * ****************************************************************************\n */\n\n#ifndef VISIONCORE_TYPES_HYPERSPHERE_HPP\n#define VISIONCORE_TYPES_HYPERSPHERE_HPP\n\n#include <VisionCore/Platform.hpp>\n\n#include <Eigen/Dense>\n\n// https://en.wikipedia.org/wiki/N-sphere\n\nnamespace vc\n{\n    \nnamespace types\n{\n    \ntemplate<typename _Scalar, int _Dimension = 0> class Hypersphere;\n\ntemplate <typename T> using CircleT = Hypersphere<T,1>;\ntemplate <typename T> using SphereT = Hypersphere<T,2>;\n\nnamespace internal\n{\n\ntemplate<typename T, int Dimension>\nstruct helper_surface_area;\n\ntemplate<typename T, int Dimension>\nstruct helper_volume\n{\n    EIGEN_DEVICE_FUNC static inline T calc(T radius)\n    {\n        return (radius / T(Dimension)) * helper_surface_area<T,Dimension-1>::calc(radius);\n    }\n};\n\ntemplate<typename T, int Dimension>\nstruct helper_surface_area\n{\n    EIGEN_DEVICE_FUNC static inline T calc(T radius)\n    {\n        return T(2.0 * M_PI) * radius * helper_volume<T,Dimension-1>::calc(radius);\n    }\n};\n\ntemplate<typename T>\nstruct helper_surface_area<T,0>\n{\n    EIGEN_DEVICE_FUNC static inline T calc(T radius) { return T(2.0); }\n};\n\ntemplate<typename T>\nstruct helper_volume<T,0>\n{\n    EIGEN_DEVICE_FUNC static inline T calc(T radius) { return T(1.0); }\n};\n    \n}\n\n}\n\n}\n\nnamespace Eigen \n{\n    namespace internal \n    {\n        template<typename _Scalar, int _Dimension>\n        struct traits<vc::types::Hypersphere<_Scalar,_Dimension> > \n        {\n            static constexpr int Dimension = _Dimension;\n            typedef _Scalar Scalar;\n            typedef Matrix<Scalar,_Dimension+1,1> CoeffType;\n        };\n        \n        template<typename _Scalar, int _Dimension, int _Options>\n        struct traits<Map<vc::types::Hypersphere<_Scalar,_Dimension>, _Options> >\n            : traits<vc::types::Hypersphere<_Scalar, _Dimension> > \n        {\n            static constexpr int Dimension = _Dimension;\n            typedef _Scalar Scalar;\n            typedef Map<Matrix<Scalar,_Dimension+1,1>, _Options> CoeffType;\n        };\n        \n        template<typename _Scalar, int _Dimension, int _Options>\n        struct traits<Map<const vc::types::Hypersphere<_Scalar,_Dimension>, _Options> >\n            : traits<const vc::types::Hypersphere<_Scalar, _Dimension> > \n        {\n            static constexpr int Dimension = _Dimension;\n            typedef _Scalar Scalar;\n            typedef Map<const Matrix<Scalar,_Dimension+1,1>, _Options> CoeffType;\n        };\n        \n    }\n}\n\nnamespace vc\n{\n    \nnamespace types\n{\n\ntemplate<typename Derived>\nclass HypersphereBase\n{\npublic:\n    static constexpr int Dimension = Eigen::internal::traits<Derived>::Dimension;\n    typedef typename Eigen::internal::traits<Derived>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<Derived>::CoeffType CoeffType;\n    typedef Eigen::Matrix<Scalar,Dimension+1,1> VectorT;\n    \n    static inline constexpr int dimension() { return Dimension; }\n    \n    template<typename NewScalarType>\n    EIGEN_DEVICE_FUNC inline Hypersphere<NewScalarType,Dimension> cast() const \n    {\n        return Hypersphere<NewScalarType,Dimension>(coeff().template cast<NewScalarType>(), \n                                                    (NewScalarType)radius());\n    }\n        \n    EIGEN_DEVICE_FUNC CoeffType& coeff() \n    {\n        return static_cast<Derived*>(this)->coeff_nonconst();\n    }\n    \n    EIGEN_DEVICE_FUNC const CoeffType& coeff() const\n    {\n        return static_cast<const Derived*>(this)->coeff_const();\n    }\n    \n    EIGEN_DEVICE_FUNC Scalar& radius() \n    {\n        return static_cast<Derived*>(this)->radius_nonconst();\n    }\n    \n    EIGEN_DEVICE_FUNC const Scalar& radius() const\n    {\n        return static_cast<const Derived*>(this)->radius_const();\n    }\n        \n    template<typename OtherDerived>\n    EIGEN_DEVICE_FUNC inline HypersphereBase<Derived>& operator=(const HypersphereBase<OtherDerived>& other)\n    {\n        coeff() = other.coeff();\n        return *this;\n    }\n    \n    EIGEN_DEVICE_FUNC inline Scalar volume()\n    {\n        using Eigen::numext::pow;\n        return (pow(Scalar(M_PI), Scalar(Dimension+1)/Scalar(2.0)) / (tgamma(Scalar(Dimension+1)/Scalar(2.0) + Scalar(1.0)))) * pow(radius(), (Scalar)(Dimension+1) );\n    }\n    \n    template<int OtherDimension>\n    EIGEN_DEVICE_FUNC inline Scalar volume()\n    {\n        return internal::helper_volume<Scalar,OtherDimension+1>::calc(radius());\n    }\n    \n    EIGEN_DEVICE_FUNC inline Scalar surfaceArea()\n    {\n        return internal::helper_surface_area<Scalar,Dimension>::calc(radius());\n    }\n    \n    template<int OtherDimension>\n    EIGEN_DEVICE_FUNC inline Scalar surfaceArea()\n    {\n        return internal::helper_surface_area<Scalar,OtherDimension>::calc(radius());\n    }\n\n    EIGEN_DEVICE_FUNC inline Scalar operator()(const VectorT& x) const\n    {\n        return evaluate(x);\n    }\n    \n    EIGEN_DEVICE_FUNC inline Scalar evaluate(const VectorT& x) const\n    {\n        Scalar sum = Scalar(0.0);\n        \n        for(int i = 0 ; i < Dimension + 1 ; ++i)\n        {\n            const Scalar term = coeff()(i) - x(i);\n            sum += (term * term);\n        }\n        \n        return sqrt(sum);\n    }\n    \n    EIGEN_DEVICE_FUNC inline bool isPointInside(const VectorT& x) const\n    {\n        return evaluate(x) < radius();\n    }\n    \n    EIGEN_DEVICE_FUNC inline void setZero()\n    {\n        coeff().setZero();\n        radius() = Scalar(0.0);\n    }\n    \n#ifdef VISIONCORE_ENABLE_CEREAL\n    template<typename Archive>\n    void load(Archive & archive, std::uint32_t const version)\n    {\n        archive(cereal::make_nvp(\"Coefficients\", coeff()));\n        archive(cereal::make_nvp(\"Radius\", radius()));\n    }\n    \n    template<typename Archive>\n    void save(Archive & archive, std::uint32_t const version) const\n    {\n        archive(cereal::make_nvp(\"Coefficients\", coeff()));\n        archive(cereal::make_nvp(\"Radius\", radius()));\n    }\n#endif // VISIONCORE_ENABLE_CEREAL    \n};\n\n/**\n * Generic Hypersphere.\n */\ntemplate<typename _Scalar, int _Dimension>\nclass Hypersphere : public HypersphereBase<Hypersphere<_Scalar,_Dimension>> \n{\n    typedef HypersphereBase<Hypersphere<_Scalar,_Dimension>> Base;\npublic:\n    static constexpr int Dimension = Eigen::internal::traits<Hypersphere>::Dimension;\n    typedef typename Eigen::internal::traits<Hypersphere>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<Hypersphere>::CoeffType CoeffType;\n    \n    friend class vc::types::HypersphereBase<Hypersphere<_Scalar,_Dimension>>;\n    \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    //EIGEN_INHERIT_ASSIGNMENT_EQUAL_OPERATOR(Hypersphere)\n    using Base::operator=;   \n    \n    EIGEN_DEVICE_FUNC inline Hypersphere()\n    {\n    }\n    \n    EIGEN_DEVICE_FUNC inline Hypersphere(const Hypersphere<_Scalar,_Dimension>& other) : coeff_(other.coeff()), radius_(other.radius())\n    {\n    }\n    \n    template<typename OtherDerived> \n    EIGEN_DEVICE_FUNC inline Hypersphere(const HypersphereBase<OtherDerived>& other) : coeff_(other.coeff()), radius_(other.radius())\n    {\n    }\n    \n    EIGEN_DEVICE_FUNC inline Hypersphere(const CoeffType& coeff, const Scalar& r) : coeff_(coeff), radius_(r)\n    {\n    }\n    \n    EIGEN_DEVICE_FUNC inline ~Hypersphere()\n    {\n    }\n                    \nprotected:\n    EIGEN_DEVICE_FUNC inline const CoeffType& coeff_const() const { return coeff_; }\n    EIGEN_DEVICE_FUNC inline CoeffType& coeff_nonconst() { return coeff_; }\n    \n    EIGEN_DEVICE_FUNC inline const Scalar& radius_const() const { return radius_; }\n    EIGEN_DEVICE_FUNC inline Scalar& radius_nonconst() { return radius_; }\n    \n    CoeffType coeff_;\n    Scalar radius_;\n};\n\ntemplate<typename _Scalar, int _Dimension>\ninline std::ostream& operator<<(std::ostream& os, const Hypersphere<_Scalar,_Dimension>& p)\n{\n    os << _Dimension << \"-Sphere(r = \" << p.radius() << \", \" << p.coeff() << \")\";\n    return os;\n}\n    \n}\n\n}\n\nnamespace Eigen \n{\n/**\n * Specialisation of Eigen::Map for Hypersphere.\n */\ntemplate<typename _Scalar, int _Dimension, int _Options>\nclass Map<vc::types::Hypersphere<_Scalar,_Dimension>, _Options>\n    : public vc::types::HypersphereBase<Map<vc::types::Hypersphere<_Scalar,_Dimension>, _Options> > \n{\n    typedef vc::types::HypersphereBase<Map<vc::types::Hypersphere<_Scalar,_Dimension>, _Options> > Base;\n    \npublic:\n    static constexpr int Dimension = Eigen::internal::traits<Map>::Dimension;\n    typedef typename Eigen::internal::traits<Map>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<Map>::CoeffType CoeffType;\n    \n    friend class vc::types::HypersphereBase<Map<vc::types::Hypersphere<_Scalar,_Dimension>, _Options> >;\n    \n    EIGEN_INHERIT_ASSIGNMENT_EQUAL_OPERATOR(Map)\n    \n    EIGEN_DEVICE_FUNC inline Map(Scalar* coeffs) : coeff_(coeffs), radius_(coeffs + Dimension + 1)\n    {\n    }\n    \nprotected:\n    EIGEN_DEVICE_FUNC inline const CoeffType& coeff_const() const { return coeff_; }\n    EIGEN_DEVICE_FUNC inline CoeffType& coeff_nonconst() { return coeff_; }\n    \n    EIGEN_DEVICE_FUNC inline const Scalar& radius_const() const { return *radius_; }\n    EIGEN_DEVICE_FUNC inline Scalar& radius_nonconst() { return *radius_; }\n    \n    CoeffType coeff_;\n    Scalar* radius_;\n};\n\n/**\n * Specialisation of Eigen::Map for const Hypersphere.\n */\ntemplate<typename _Scalar, int _Dimension, int _Options>\nclass Map<const vc::types::Hypersphere<_Scalar,_Dimension>, _Options>\n    : public vc::types::HypersphereBase<Map<const vc::types::Hypersphere<_Scalar,_Dimension>, _Options> > \n{\n    typedef vc::types::HypersphereBase<Map<const vc::types::Hypersphere<_Scalar,_Dimension>, _Options> > Base;\n    \npublic:\n    static constexpr int Dimension = Eigen::internal::traits<Map>::Dimension;\n    typedef typename Eigen::internal::traits<Map>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<Map>::CoeffType CoeffType;\n        \n    friend class vc::types::HypersphereBase<Map<const vc::types::Hypersphere<_Scalar,_Dimension>, _Options> >;\n    \n    EIGEN_INHERIT_ASSIGNMENT_EQUAL_OPERATOR(Map)\n    \n    EIGEN_DEVICE_FUNC inline Map(const Scalar* coeffs) : coeff_(coeffs), radius_(coeffs + Dimension + 1)\n    {\n    }\n    \nprotected:\n    EIGEN_DEVICE_FUNC inline const CoeffType& coeff_const() const { return coeff_; }    \n    EIGEN_DEVICE_FUNC inline const Scalar& radius_const() const { return *radius_; }\n    \n    const CoeffType coeff_;\n    const Scalar* radius_;\n};\n\n}\n\n#endif // VISIONCORE_TYPES_HYPERSPHERE_HPP\n", "meta": {"hexsha": "dfffa7833101d53c388533708ffd9d705ce0084b", "size": 12199, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/VisionCore/Types/Hypersphere.hpp", "max_stars_repo_name": "lukier/vision_core", "max_stars_repo_head_hexsha": "45cb1bf7b74e1e1d5aa1078494a328b317d5a368", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2016-10-30T23:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T12:27:40.000Z", "max_issues_repo_path": "include/VisionCore/Types/Hypersphere.hpp", "max_issues_repo_name": "jczarnowski/vision_core", "max_issues_repo_head_hexsha": "924c53339b1d99ebb3b1e358edfaa1a4e8d3703b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T04:45:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T01:32:22.000Z", "max_forks_repo_path": "include/VisionCore/Types/Hypersphere.hpp", "max_forks_repo_name": "lukier/vision_core", "max_forks_repo_head_hexsha": "45cb1bf7b74e1e1d5aa1078494a328b317d5a368", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-14T00:46:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T08:55:11.000Z", "avg_line_length": 32.0183727034, "max_line_length": 166, "alphanum_fraction": 0.6698090007, "num_tokens": 2857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.40644834433761934}}
{"text": "#include \"engine.hpp\"\n\n#include <algorithm>\n#include <numeric>\n#include <cmath>\n#include <functional> // for std::cref (pass reference of VectorField to odeint)\n#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp>\n#include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>\n#include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp>\n#include <boost/numeric/odeint/stepper/generation.hpp> // make_controlled\n\n#include \"variable.hpp\"\n#include \"sde.hpp\" // SDE integrator\n\nnamespace odeint = boost::numeric::odeint;\n\ntypedef odeint::runge_kutta_cash_karp54<RealVec> real_vec_error_stepper_type;\n\nconstexpr bool VERBOSE = false; // TODO: better way to handle message printing\n\nconst double Engine::dt_max = 1.0;\nconst double Engine::dt_init = 0.001;\nconst double Engine::h_init = 0.01; // TODO: can be relaxed with higher-order solvers!\n\nEngine::Engine(const State & s0, const std::vector<Transition*> transitions,\n    const Parameters & par) : s0(s0), h(h_init), dt(dt_init), vf(s0, transitions, par) {\n  // duplicate transitions\n  replace_transitions(transitions); // copy transitions to this->transitions\n}\n\nEngine::Engine(const Engine & e) : s0(e.s0), h(e.h), dt(e.dt), vf(e.vf) {\n  // copy constructor: duplicate transitions\n  replace_transitions(e.transitions);\n}\n\nEngine & Engine::operator=(const Engine & e) { // copy assignment constructor\n  if ( this != &e ) {\n    s0 = e.s0;\n    h = e.h;\n    dt = e.dt;\n    vf = e.vf;\n    replace_transitions(e.transitions);\n  } // else do nothing\n  return *this;\n}\n\nvoid Engine::reset(const State & s0, const Parameters & par) {\n  this->s0 = s0;\n  // FIXME: reset algorithmic parameters??\n  // FIXME: update VectorField?\n}\n\n\nState Engine::evolve_gillespie(State s, double tmax, const Parameters & p, Rng & rng) {\n  while ( true ) {\n    // choose the next event\n    std::vector<double> rates(transitions.size(), 0.0);\n    std::transform(transitions.begin(), transitions.end(), rates.begin(),\n        [&] (Transition* x) -> double {return x->rate(s, p);});\n    double lambda = std::accumulate(rates.begin(), rates.end(), 0.0);\n    // check that lambda > 0 (otherwise jump to tmax)\n    if ( lambda == 0 ) {\n      s.t() = tmax;\n      break;\n    } // else, lambda > 0\n    double time_increment = rng.exponential(lambda);\n    // check that the next event takes place before tmax\n    if ( std::nextafter(s.t() + time_increment, tmax) >= tmax ) {\n      s.t() = tmax;\n      break;\n    } // else, apply the transition and incerment the time with dt\n\n    Transition* trans = choose_random_transition(transitions, rates, lambda, rng);\n    if ( trans == nullptr ) {\n      throw std::logic_error(\"unable to randomly choose transition\" + RIGHT_HERE);\n    }\n    s = trans->apply(s);\n    s.t() += time_increment; // manually increase the time\n    // TODO: make dt optional argument for Transition::apply?\n  }\n  return s;\n}\n\nState Engine::evolve_tauleap(State s, double tmax, const Parameters & p, Rng & rng) {\n  while ( std::nextafter(s.t(), tmax) < tmax ) {\n    // choose the next event\n    std::vector<double> rates(transitions.size(), 0.0);\n    std::transform(transitions.begin(), transitions.end(), rates.begin(),\n        [&] (Transition* x) -> double {return x->rate(s, p);});\n    double lambda = std::accumulate(rates.begin(), rates.end(), 0.0);\n    // sample number of events\n    int n = rng.poisson(lambda * dt);\n    // do n transitions\n    for ( int i = 0; i < n; ++i ) {\n      Transition* trans = choose_random_transition(transitions, rates, lambda, rng);\n      if ( trans == nullptr ) {\n        throw std::logic_error(\"unable to randomly choose transition\" + RIGHT_HERE);\n      }\n      s = trans->apply(s);\n      // re-compute the rates..\n      std::transform(transitions.begin(), transitions.end(), rates.begin(),\n          [&] (Transition* x) -> double {return x->rate(s, p);});\n      lambda = std::accumulate(rates.begin(), rates.end(), 0.0);\n    }\n    s.t() += dt; // manually increase the time\n    // adjust the timestep\n    if ( lambda > 0 ) {\n      dt = std::min({dt_max, 1/lambda, tmax - s.t()}); // TODO: smoothen, use intermediate rates\n    } else {\n      dt = std::min(dt_max, tmax - s.t());\n    }\n  }\n  return s;\n}\n\nState Engine::evolve_ode(State s, double tmax, const Parameters & p) {\n  // make sure that all variables of the state are continuous\n  for ( auto & var : s ) {\n    var.make_continuous(); // make_continous makes the entire vector continuous\n  }\n  // initialize a vectorfield with the fully continous state\n  vf.update(s, p);\n  // integrate the system of ODEs\n  if ( tmax > s.t() ) {\n    std::tie(s, std::ignore) = integrate(tmax - s.t(), vf, s, h);\n  }\n  return s;\n}\n\n\nState Engine::evolve_sde(State s, double tmax, const Parameters & p, Rng & rng) {\n  // make sure that all variables of the state are continuous\n  for ( auto & var : s ) {\n    var.make_continuous(); // make_continous makes the entire vector continuous\n  }\n  // initialize a vectorfield with the fully continous state\n  vf.update(s, p);\n  // integrate the system of SDEs\n  if ( tmax > s.t() ) {\n    std::tie(s, std::ignore) = sde_integrate(tmax - s.t(), vf, s, h, rng);\n  }\n  return s;\n}\n\nState Engine::evolve_hybrid(State s, double tmax,\n    const Parameters & p, Rng & rng, bool sde) {\n  // use THRESHOLD to define a backwards-compatible switcher\n  VarTypeSwitcher switcher = [](const State & s, const Parameters & p) -> std::vector<bool> {\n    std::vector<bool> ought_discrete(s.flat_size());\n    for ( size_t i = 0; i < s.flat_size(); ++i ) {\n      const Variable & var = s[i];\n      if ( var.is_discrete )\n        // keep discrete if below threshold + window/2\n        ought_discrete[i] = (var.disc_value < THRESHOLD + WINDOW/2);\n      else { // continuous\n        // make discrete if below threshold - window/2\n        ought_discrete[i] = (var.cont_value < THRESHOLD - WINDOW/2);\n      }\n    }\n    return ought_discrete;\n  };\n  // now use the general method\n  return evolve_hybrid(s, tmax, p, switcher, rng, sde);\n}\n\n\n\nState Engine::evolve_hybrid(State s, double tmax,\n    const Parameters & p, const VarTypeSwitcher & switcher, Rng & rng, bool sde) {\n  // make sure that the timestep \"fits\"\n  while ( std::nextafter(s.t(), tmax) < tmax ) {\n    /* test if we need to switch Variables from discrete\n     * to continuous and vice versa. Do this first to\n     * avoid problems with the initially defined state.\n     */\n    std::vector<bool> ought_discrete = switcher(s, p);\n    for ( size_t i = 0; i < s.flat_size(); ++i ) {\n      Variable & var = s[i];\n      if ( var.is_discrete && !ought_discrete[i] ) {\n        var.make_continuous();\n        // print message for debugging etc.\n        if ( VERBOSE ) {\n          std::cout << \"# switching from discrete to continuous\" << std::endl;\n        }\n      }\n      if ( !var.is_discrete && ought_discrete[i] ) {\n        if ( VERBOSE && var.value() < 0 ) {\n          std::cerr << \"# WARNING: negative var detected: \" << var << std::endl;\n        }\n        var.make_discrete();\n        // be careful with the initial timestep...\n        dt = std::min(dt, dt_init);\n        // print message for debugging etc.\n        if ( VERBOSE ) {\n          std::cout << \"# switching from continuous to discrete\" << std::endl;\n        }\n      }\n    }\n    // re-assign indices whenever the signature of s has changed\n    vf.update(s, p);\n    // take a good time step based on instantaneous transition rate\n    double lambda = vf.totalTransitionRate();\n    if ( lambda > 0 ) {\n      dt = std::min(dt_max, 1/lambda);\n    } else {\n      dt = dt_max;\n    }\n    double time_increment = std::min(dt, tmax - s.t());\n    // integrate the deterministic variables and the loads\n    std::map<Transition*, double> loads;\n    if ( sde ) {\n      // h is passed by ref and modified (TODO adaptive SDE integrator)\n      std::tie(s, loads) = sde_integrate(time_increment, vf, s, h, rng);\n    } else { // use ODE integrator\n      // h is passed by ref and modified\n      std::tie(s, loads) = integrate(time_increment, vf, s, h);\n    }\n    auto op = [] (double c, std::pair<Transition*, double> l) {return c + l.second;};\n    double Lambda = std::accumulate(loads.begin(), loads.end(), 0.0, op);\n    // sample number of events (0 if Lambda = 0)\n    int n = (Lambda > 0 ? rng.poisson(Lambda) : 0); // Lambda = lambda * dt\n\n    // do n transitions\n    for ( int i = 0; i < n; ++i ) {\n      if ( i > 0 ) {\n        // re-compute the rates in order to apply another transition\n        for ( auto & [trans, load] : loads ) {\n          load = trans->rate(s, p) * dt; // approximate load by rate * dt\n        }\n        Lambda = std::accumulate(loads.begin(), loads.end(), 0.0, op);\n        if ( Lambda == 0 ) {\n          // print message for debugging etc.\n          if ( VERBOSE ) {\n            std::cerr << \"# WARNING: sampling more than one event is not possible\"\n                      << RIGHT_HERE << std::endl;\n          }\n          break; // break for ( i = 0; i < n; ++i )\n        }\n      }\n      // sample a random transition\n      Transition* trans = choose_random_transition(loads, Lambda, rng);\n      if ( trans == nullptr ) {\n        throw std::logic_error(\"unable to choose random transition\" + RIGHT_HERE);\n      } // else..\n      State s_prime = trans->apply(s);\n      if ( s_prime.isNonNegative() ) {\n        s = s_prime;\n      } else {\n        throw std::logic_error(\"about to do an illegal transition\" + RIGHT_HERE);\n      }\n    } // for i = 0 ... n-1\n  }\n  return s;\n}\n\n/** Auxiliary integrate function is a wrapper around the Boost odeint methods.\n *\n * The State is \"encoded\" into a single vector, that can be handled by\n * odeint. After integration, the vector is decoded back into the State\n * object.\n */\nstd::pair<State, std::map<Transition*, double>>\n    integrate(double dt, const VectorField & vf, const State & s, double & h) {\n  // TODO: verify that s and vf are compatible\n  auto controlled_stepper = odeint::make_controlled(1e-6, 1e-6, real_vec_error_stepper_type());\n  // TODO: make the stepper member of engine\n  RealVec y = vf.encode(s);\n\n  double t_start = s.t();\n  double t_end = s.t() + dt;\n  double t_old = s.t(); // used to keep track of the timestep\n  double h0 = h; // the initially proposed stepsize\n  // observer is used to get h before final step to t_end\n  auto observer = [&] (const RealVec & y, double t_new) {\n    if ( t_old < t_new && t_new < t_end ) {\n      h = t_new - t_old;\n      t_old = t_new;\n    }\n  };\n  size_t steps = odeint::integrate_adaptive(controlled_stepper,\n      std::cref(vf), y, t_start, t_end, h0,\n      observer);\n  (void) steps; // TODO: do something with steps??\n\n  State u = vf.decodeState(s.t()+dt, y);\n  auto loads = vf.decodeLoads(s.t()+dt, y);\n  return std::make_pair(u, loads);\n}\n\n\n\n\n\n/** Use an SDE integrator to evolve the State forward in time.\n */\nstd::pair<State, std::map<Transition*, double>>\n    sde_integrate(double dt, const VectorField & vf, const State & s, double & h, Rng & rng) {\n  // define the EM stepper\n  EulerMaruyamaStepper stepper(rng); // rng is passed by ref\n  // TODO: verify that s and vf are compatible\n  RealVec y = vf.encode(s);\n\n  double t_start = s.t();\n  double t_end = s.t() + dt;\n  double h0 = std::min(dt, h);\n  size_t steps = odeint::integrate_const(stepper, std::cref(vf),\n      y, t_start, t_end, h0);\n  (void) steps; // TODO: do something with steps??\n\n  State u = vf.decodeState(t_end, y);\n  auto loads = vf.decodeLoads(t_end, y);\n  return std::make_pair(u, loads);\n}\n\n\n\n\n\n\n\n\n\nTransition* choose_random_transition(const std::vector<Transition*> & transitions,\n    const std::vector<double> & rates, double lambda, Rng & rng) {\n  if ( lambda <= 0 ) {\n    std::cerr << \"# WARNING: lambda not positive: \" << lambda << RIGHT_HERE << std::endl;\n    return nullptr;\n  }\n  double u = 0.0;\n  try {\n    u = rng.uniform(0, lambda);\n  } catch ( const std::exception & ex ) {\n    std::cout << ex.what() << RIGHT_HERE << std::endl;\n    throw ex;\n  }\n  auto transit = transitions.begin();\n  for ( auto r : rates ) {\n    u -= r;\n    if ( u < 0 ) {\n      break;\n    } // else...\n    ++transit;\n  }\n  if ( transit != transitions.end() ) {\n    return *transit;\n  } else {\n    return nullptr; // signals failure\n  }\n}\n\nTransition* choose_random_transition(const std::map<Transition*, double> & loads,\n    double Lambda, Rng & rng) {\n  if ( Lambda <= 0 ) {\n    std::cerr << \"# WARNING: lambda not positive: \" << Lambda << RIGHT_HERE << std::endl;\n    return nullptr;\n  }\n  double u = 0.0;\n  try { // FIXME: Lambda can be nan!!\n    u = rng.uniform(0, Lambda);\n  } catch ( const std::exception & ex ) {\n    std::cout << ex.what() << RIGHT_HERE << std::endl;\n    throw ex;\n  }\n  //double u = rng.uniform(0, Lambda);\n  for ( auto & load : loads ) {\n    u -= load.second;\n    if ( u < 0 ) {\n      return load.first;\n    }\n  } // for load in loads\n  return nullptr; // signals failure\n}\n", "meta": {"hexsha": "584e80162043ba15505e92a768f17db97b5327b0", "size": 12842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "stochepi/src/engine.cpp", "max_stars_repo_name": "eeg-lanl/sarscov2-selection", "max_stars_repo_head_hexsha": "c2087cbaf55de9930736aa6677a57008a2397583", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stochepi/src/engine.cpp", "max_issues_repo_name": "eeg-lanl/sarscov2-selection", "max_issues_repo_head_hexsha": "c2087cbaf55de9930736aa6677a57008a2397583", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stochepi/src/engine.cpp", "max_forks_repo_name": "eeg-lanl/sarscov2-selection", "max_forks_repo_head_hexsha": "c2087cbaf55de9930736aa6677a57008a2397583", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4289544236, "max_line_length": 96, "alphanum_fraction": 0.6185173649, "num_tokens": 3525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4063183036428736}}
{"text": "/*********************************************************************************\n *  OKVIS - Open Keyframe-based Visual-Inertial SLAM\n *  Copyright (c) 2015, Autonomous Systems Lab / ETH Zurich\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions are met:\n *\n *   * Redistributions of source code must retain the above copyright notice,\n *     this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above copyright notice,\n *     this list of conditions and the following disclaimer in the documentation\n *     and/or other materials provided with the distribution.\n *   * Neither the name of Autonomous Systems Lab / ETH Zurich nor the names of\n *     its contributors may be used to endorse or promote products derived from\n *     this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n *  Created on: Feb 3, 2015\n *      Author: Stefan Leutenegger (s.leutenegger@imperial.ac.uk)\n *********************************************************************************/\n\n/**\n * @file implementation/RadialTangentialDistortion.hpp\n * @brief Header implementation file for the RadialTangentialDistortion class.\n * @author Stefan Leutenegger\n */\n\n#include <Eigen/LU>\n#include <iostream>\n\n/// \\brief vio Main namespace of this package.\nnamespace vio {\n/// \\brief cameras Namespace for camera-related functionality.\nnamespace cameras {\n\n// The default constructor with all zero ki\nRadialTangentialDistortion::RadialTangentialDistortion()\n    : k1_(0.0), k2_(0.0), p1_(0.0), p2_(0.0) {\n  parameters_.setZero();\n}\n\n// Constructor initialising ki\nRadialTangentialDistortion::RadialTangentialDistortion(float k1, float k2,\n                                                       float p1, float p2) {\n  parameters_[0] = k1;\n  parameters_[1] = k2;\n  parameters_[2] = p1;\n  parameters_[3] = p2;\n  k1_ = k1;\n  k2_ = k2;\n  p1_ = p1;\n  p2_ = p2;\n}\n\nbool RadialTangentialDistortion::setParameters(\n    const Eigen::VectorXd& parameters) {\n  if (parameters.cols() != NumDistortionIntrinsics) {\n    return false;\n  }\n  parameters_ = parameters.cast<float>();\n  k1_ = parameters[0];\n  k2_ = parameters[1];\n  p1_ = parameters[2];\n  p2_ = parameters[3];\n  return true;\n}\n\nbool RadialTangentialDistortion::distort(\n    const Eigen::Vector2d& pointUndistorted,\n    Eigen::Vector2d* pointDistorted) const {\n  // just compute the distorted point\n  const float u0 = pointUndistorted[0];\n  const float u1 = pointUndistorted[1];\n  const float mx_u = u0 * u0;\n  const float my_u = u1 * u1;\n  const float mxy_u = u0 * u1;\n  const float rho_u = mx_u + my_u;\n  const float rad_dist_u = k1_ * rho_u + k2_ * rho_u * rho_u;\n  (*pointDistorted)[0] =\n      u0 + u0 * rad_dist_u + 2.0 * p1_ * mxy_u + p2_ * (rho_u + 2.0 * mx_u);\n  (*pointDistorted)[1] =\n      u1 + u1 * rad_dist_u + 2.0 * p2_ * mxy_u + p1_ * (rho_u + 2.0 * my_u);\n  return true;\n}\nbool RadialTangentialDistortion::distort(\n    const Eigen::Vector2f& pointUndistorted,\n    Eigen::Vector2f* pointDistorted) const {\n  // just compute the distorted point\n  const float u0 = pointUndistorted[0];\n  const float u1 = pointUndistorted[1];\n  const float mx_u = u0 * u0;\n  const float my_u = u1 * u1;\n  const float mxy_u = u0 * u1;\n  const float rho_u = mx_u + my_u;\n  const float rad_dist_u = k1_ * rho_u + k2_ * rho_u * rho_u;\n  (*pointDistorted)[0] =\n      u0 + u0 * rad_dist_u + 2.0 * p1_ * mxy_u + p2_ * (rho_u + 2.0 * mx_u);\n  (*pointDistorted)[1] =\n      u1 + u1 * rad_dist_u + 2.0 * p2_ * mxy_u + p1_ * (rho_u + 2.0 * my_u);\n  return true;\n}\n\nbool RadialTangentialDistortion::distort(\n    const Eigen::Vector2d& pointUndistorted, Eigen::Vector2d* pointDistorted,\n    Eigen::Matrix2d* pointJacobian, Eigen::Matrix2Xd* parameterJacobian) const {\n  // first compute the distorted point\n  const float u0 = pointUndistorted[0];\n  const float u1 = pointUndistorted[1];\n  const float mx_u = u0 * u0;\n  const float my_u = u1 * u1;\n  const float mxy_u = u0 * u1;\n  const float rho_u = mx_u + my_u;\n  const float rad_dist_u = k1_ * rho_u + k2_ * rho_u * rho_u;\n  (*pointDistorted)[0] =\n      u0 + u0 * rad_dist_u + 2.0 * p1_ * mxy_u + p2_ * (rho_u + 2.0 * mx_u);\n  (*pointDistorted)[1] =\n      u1 + u1 * rad_dist_u + 2.0 * p2_ * mxy_u + p1_ * (rho_u + 2.0 * my_u);\n\n  // next the Jacobian w.r.t. changes on the undistorted point\n  Eigen::Matrix2d& J = *pointJacobian;\n  J(0, 0) = 1 + rad_dist_u + k1_ * 2.0 * mx_u + k2_ * rho_u * 4 * mx_u +\n            2.0 * p1_ * u1 + 6 * p2_ * u0;\n  J(1, 0) = k1_ * 2.0 * u0 * u1 + k2_ * 4 * rho_u * u0 * u1 + p1_ * 2.0 * u0 +\n            2.0 * p2_ * u1;\n  J(0, 1) = J(1, 0);\n  J(1, 1) = 1 + rad_dist_u + k1_ * 2.0 * my_u + k2_ * rho_u * 4 * my_u +\n            6 * p1_ * u1 + 2.0 * p2_ * u0;\n\n  if (parameterJacobian) {\n    // the Jacobian w.r.t. intrinsics parameters\n    Eigen::Matrix2Xd& J2 = *parameterJacobian;\n    J2.resize(2, NumDistortionIntrinsics);\n    const float r2 = rho_u;\n    const float r4 = r2 * r2;\n\n    //[ u0*(u0^2 + u1^2), u0*(u0^2 + u1^2)^2,       2*u0*u1, 3*u0^2 + u1^2]\n    //[ u1*(u0^2 + u1^2), u1*(u0^2 + u1^2)^2, u0^2 + 3*u1^2,       2*u0*u1]\n\n    J2(0, 0) = u0 * r2;\n    J2(0, 1) = u0 * r4;\n    J2(0, 2) = 2.0 * u0 * u1;\n    J2(0, 3) = r2 + 2.0 * u0 * u0;\n\n    J2(1, 0) = u1 * r2;\n    J2(1, 1) = u1 * r4;\n    J2(1, 2) = r2 + 2.0 * u1 * u1;\n    J2(1, 3) = 2.0 * u0 * u1;\n  }\n  return true;\n}\nbool RadialTangentialDistortion::distort(\n    const Eigen::Vector2f& pointUndistorted, Eigen::Vector2f* pointDistorted,\n    Eigen::Matrix2f* pointJacobian, Eigen::Matrix2Xf* parameterJacobian) const {\n  // first compute the distorted point\n  const float u0 = pointUndistorted[0];\n  const float u1 = pointUndistorted[1];\n  const float mx_u = u0 * u0;\n  const float my_u = u1 * u1;\n  const float mxy_u = u0 * u1;\n  const float rho_u = mx_u + my_u;\n  const float rad_dist_u = k1_ * rho_u + k2_ * rho_u * rho_u;\n  (*pointDistorted)[0] =\n      u0 + u0 * rad_dist_u + 2.0 * p1_ * mxy_u + p2_ * (rho_u + 2.0 * mx_u);\n  (*pointDistorted)[1] =\n      u1 + u1 * rad_dist_u + 2.0 * p2_ * mxy_u + p1_ * (rho_u + 2.0 * my_u);\n\n  // next the Jacobian w.r.t. changes on the undistorted point\n  Eigen::Matrix2f& J = *pointJacobian;\n  J(0, 0) = 1 + rad_dist_u + k1_ * 2.0 * mx_u + k2_ * rho_u * 4 * mx_u +\n            2.0 * p1_ * u1 + 6 * p2_ * u0;\n  J(1, 0) = k1_ * 2.0 * u0 * u1 + k2_ * 4 * rho_u * u0 * u1 + p1_ * 2.0 * u0 +\n            2.0 * p2_ * u1;\n  J(0, 1) = J(1, 0);\n  J(1, 1) = 1 + rad_dist_u + k1_ * 2.0 * my_u + k2_ * rho_u * 4 * my_u +\n            6 * p1_ * u1 + 2.0 * p2_ * u0;\n\n  if (parameterJacobian) {\n    // the Jacobian w.r.t. intrinsics parameters\n    Eigen::Matrix2Xf& J2 = *parameterJacobian;\n    J2.resize(2, NumDistortionIntrinsics);\n    const float r2 = rho_u;\n    const float r4 = r2 * r2;\n\n    //[ u0*(u0^2 + u1^2), u0*(u0^2 + u1^2)^2,       2*u0*u1, 3*u0^2 + u1^2]\n    //[ u1*(u0^2 + u1^2), u1*(u0^2 + u1^2)^2, u0^2 + 3*u1^2,       2*u0*u1]\n\n    J2(0, 0) = u0 * r2;\n    J2(0, 1) = u0 * r4;\n    J2(0, 2) = 2.0 * u0 * u1;\n    J2(0, 3) = r2 + 2.0 * u0 * u0;\n\n    J2(1, 0) = u1 * r2;\n    J2(1, 1) = u1 * r4;\n    J2(1, 2) = r2 + 2.0 * u1 * u1;\n    J2(1, 3) = 2.0 * u0 * u1;\n  }\n  return true;\n}\n\nbool RadialTangentialDistortion::distortWithExternalParameters(\n    const Eigen::Vector2d& pointUndistorted, const Eigen::VectorXd& parameters,\n    Eigen::Vector2d* pointDistorted, Eigen::Matrix2d* pointJacobian,\n    Eigen::Matrix2Xd* parameterJacobian) const {\n  const float k1 = parameters[0];\n  const float k2 = parameters[1];\n  const float p1 = parameters[2];\n  const float p2 = parameters[3];\n  // first compute the distorted point\n  const float u0 = pointUndistorted[0];\n  const float u1 = pointUndistorted[1];\n  const float mx_u = u0 * u0;\n  const float my_u = u1 * u1;\n  const float mxy_u = u0 * u1;\n  const float rho_u = mx_u + my_u;\n  const float rad_dist_u = k1 * rho_u + k2 * rho_u * rho_u;\n  (*pointDistorted)[0] =\n      u0 + u0 * rad_dist_u + 2.0 * p1 * mxy_u + p2 * (rho_u + 2.0 * mx_u);\n  (*pointDistorted)[1] =\n      u1 + u1 * rad_dist_u + 2.0 * p2 * mxy_u + p1 * (rho_u + 2.0 * my_u);\n\n  // next the Jacobian w.r.t. changes on the undistorted point\n  Eigen::Matrix2d& J = *pointJacobian;\n  J(0, 0) = 1 + rad_dist_u + k1 * 2.0 * mx_u + k2 * rho_u * 4 * mx_u +\n            2.0 * p1 * u1 + 6 * p2 * u0;\n  J(1, 0) = k1 * 2.0 * u0 * u1 + k2 * 4 * rho_u * u0 * u1 + p1 * 2.0 * u0 +\n            2.0 * p2 * u1;\n  J(0, 1) = J(1, 0);\n  J(1, 1) = 1 + rad_dist_u + k1 * 2.0 * my_u + k2 * rho_u * 4 * my_u +\n            6 * p1 * u1 + 2.0 * p2 * u0;\n\n  if (parameterJacobian) {\n    // the Jacobian w.r.t. intrinsics parameters\n    Eigen::Matrix2Xd& J2 = *parameterJacobian;\n    J2.resize(2, NumDistortionIntrinsics);\n    const float r2 = rho_u;\n    const float r4 = r2 * r2;\n\n    //[ u0*(u0^2 + u1^2), u0*(u0^2 + u1^2)^2,       2*u0*u1, 3*u0^2 + u1^2]\n    //[ u1*(u0^2 + u1^2), u1*(u0^2 + u1^2)^2, u0^2 + 3*u1^2,       2*u0*u1]\n\n    J2(0, 0) = u0 * r2;\n    J2(0, 1) = u0 * r4;\n    J2(0, 2) = 2.0 * u0 * u1;\n    J2(0, 3) = r2 + 2.0 * u0 * u0;\n\n    J2(1, 0) = u1 * r2;\n    J2(1, 1) = u1 * r4;\n    J2(1, 2) = r2 + 2.0 * u1 * u1;\n    J2(1, 3) = 2.0 * u0 * u1;\n  }\n  return true;\n}\nbool RadialTangentialDistortion::undistort(\n    const Eigen::Vector2d& pointDistorted,\n    Eigen::Vector2d* pointUndistorted) const {\n  // this is expensive: we solve with Gauss-Newton...\n  Eigen::Vector2d x_bar = pointDistorted;  // initialise at distorted point\n  const int n = 5;                         // just 5 iterations max.\n  Eigen::Matrix2d E;                       // error Jacobian\n\n  bool success = false;\n  for (int i = 0; i < n; i++) {\n    Eigen::Vector2d x_tmp;\n\n    distort(x_bar, &x_tmp, &E);\n\n    Eigen::Vector2d e(pointDistorted - x_tmp);\n    Eigen::Matrix2d E2 = (E.transpose() * E);\n    Eigen::Vector2d du = E2.inverse() * E.transpose() * e;\n\n    x_bar += du;\n\n    const double chi2 = e.dot(e);\n    if (chi2 < 1e-4) {\n      success = true;\n    }\n    if (chi2 < 1e-15) {\n      success = true;\n      break;\n    }\n  }\n  *pointUndistorted = x_bar;\n\n  if (!success) {\n    // std::cout<<(E.transpose() * E)<<std::endl;\n  }\n  return success;\n}\n\nbool RadialTangentialDistortion::undistort(\n    const Eigen::Vector2f& pointDistorted,\n    Eigen::Vector2f* pointUndistorted) const {\n  // this is expensive: we solve with Gauss-Newton...\n  Eigen::Vector2f x_bar = pointDistorted;  // initialise at distorted point\n  const int n = 5;                         // just 5 iterations max.\n  Eigen::Matrix2f E;                       // error Jacobian\n\n  bool success = false;\n  for (int i = 0; i < n; i++) {\n    Eigen::Vector2f x_tmp;\n\n    distort(x_bar, &x_tmp, &E);\n\n    Eigen::Vector2f e(pointDistorted - x_tmp);\n    Eigen::Matrix2f E2 = (E.transpose() * E);\n    Eigen::Vector2f du = E2.inverse() * E.transpose() * e;\n\n    x_bar += du;\n\n    const double chi2 = e.dot(e);\n    if (chi2 < 1e-4) {\n      success = true;\n    }\n    if (chi2 < 1e-15) {\n      success = true;\n      break;\n    }\n  }\n  *pointUndistorted = x_bar;\n\n  if (!success) {\n    // std::cout<<(E.transpose() * E)<<std::endl;\n  }\n  return success;\n}\n\nbool RadialTangentialDistortion::undistort(\n    const Eigen::Vector2d& pointDistorted, Eigen::Vector2d* pointUndistorted,\n    Eigen::Matrix2d* pointJacobian) const {\n  // this is expensive: we solve with Gauss-Newton...\n  Eigen::Vector2d x_bar = pointDistorted;  // initialise at distorted point\n  const int n = 5;                         // just 5 iterations max.\n  Eigen::Matrix2d E;                       // error Jacobian\n\n  bool success = false;\n  for (int i = 0; i < n; i++) {\n    Eigen::Vector2d x_tmp;\n\n    distort(x_bar, &x_tmp, &E);\n\n    Eigen::Vector2d e(pointDistorted - x_tmp);\n    Eigen::Vector2d dx = (E.transpose() * E).inverse() * E.transpose() * e;\n\n    x_bar += dx;\n\n    const double chi2 = e.dot(e);\n    if (chi2 < 1e-4) {\n      success = true;\n    }\n    if (chi2 < 1e-15) {\n      success = true;\n      break;\n    }\n  }\n  *pointUndistorted = x_bar;\n\n  // the Jacobian of the inverse map is simply the inverse Jacobian.\n  *pointJacobian = E.inverse();\n\n  return success;\n}\n\nbool RadialTangentialDistortion::undistort(\n    const Eigen::Vector2f& pointDistorted, Eigen::Vector2f* pointUndistorted,\n    Eigen::Matrix2f* pointJacobian) const {\n  Eigen::Vector2f x_bar = pointDistorted;  // initialize at distorted point\n  const int n = 5;                         // Max 5 iterations\n  Eigen::Matrix2f E;                       // error Jacobian\n\n  bool success = false;\n  for (int i = 0; i < n; ++i) {\n    Eigen::Vector2f x_tmp;\n    distort(x_bar, &x_tmp, &E);\n\n    Eigen::Vector2f e(pointDistorted - x_tmp);\n    Eigen::Vector2f dx = (E.transpose() * E).inverse() * E.transpose() * e;\n\n    x_bar += dx;\n\n    const float chi2 = e.dot(e);\n    if (chi2 < 1e-4) {\n      success = true;\n    }\n    if (chi2 < 1e-8) {\n      success = true;\n      break;\n    }\n  }\n  *pointUndistorted = x_bar;\n\n  // the Jacobian of the inverse map is simply the inverse Jacobian.\n  *pointJacobian = E.inverse();\n\n  return success;\n}\n\n}  // namespace cameras\n}  // namespace vio\n", "meta": {"hexsha": "c84d64f81faf3b172e05c5f384f7ea73fa5df93d", "size": 13896, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Frontend/cameras/implementation/RadialTangentialDistortion.hpp", "max_stars_repo_name": "TongLing916/ICE-BA", "max_stars_repo_head_hexsha": "b8febd35af821e3bbb5909c66a485b9e234a80fe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Frontend/cameras/implementation/RadialTangentialDistortion.hpp", "max_issues_repo_name": "TongLing916/ICE-BA", "max_issues_repo_head_hexsha": "b8febd35af821e3bbb5909c66a485b9e234a80fe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Frontend/cameras/implementation/RadialTangentialDistortion.hpp", "max_forks_repo_name": "TongLing916/ICE-BA", "max_forks_repo_head_hexsha": "b8febd35af821e3bbb5909c66a485b9e234a80fe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8926829268, "max_line_length": 83, "alphanum_fraction": 0.5999568221, "num_tokens": 4940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.743167997235783, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.40631829742279857}}
{"text": "#include <mandoline/mesh3.hpp>\n#include <mtao/cmdline_parser.hpp>\n#include <mtao/logging/logger.hpp>\n\n#include <Eigen/Dense>\nusing namespace mandoline;\n\n\n\n\n\n\n\ntemplate <typename Matrix, typename Vector>\nstruct SparseLDLT\n{\n    typedef typename Matrix::Scalar Scalar;\n    SparseLDLT() {}\n    SparseLDLT(const Matrix & A)\n    {\n        // L=tril(A);\n        L=A.template triangularView<Eigen::StrictlyLower>();//Don't copy the diagonal\n        for(int i=0; i<L.rows(); ++i)\n        {\n            if(L.coeff(i,i)!=0)\n                L.coeffRef(i,i)=0;\n        }\n        Dinv=D=A.diagonal();\n\n\n\n        // for k=1:size(L,2)\n        for(int k=0; k<A.rows(); ++k)//k is the column that we're infecting the remaining columns with\n        {//L(:,k)\n\n\n\n            //Solidify the current column values\n            //==================================\n            if(D(k)==0) continue;\n            if(Dinv(k)<0.25*D(k))//If D has shrunk too much since it started\n                Dinv(k)=1/D(k);\n            else\n                Dinv(k)=1/Dinv(k);\n            L.innerVector(k) *= Dinv(k);\n\n            //Add k terms to all of the following columns\n            //===========================================\n            for(typename Matrix::InnerIterator it(L,k); it; ++it)// -L(i,k)*D(k)*L(j,k)\n            {\n                int j = it.row();//j>k\n                if(j<=k) continue;\n                Scalar missing=0;\n                Scalar multiplier=it.value();//L(j,k)*D(k)\n\n                typename Matrix::InnerIterator k_it(L,k);\n                typename Matrix::InnerIterator j_it(L,j);\n                //move down teh column of L(:,k) to collect missing elements in the match with A(:,j)\n                //i=k_it.row()\n\n                while (k_it && k_it.row()<j){//L(i,k)\n                    while(j_it)//L(i,j) occasionally\n                    {\n                        if(j_it.row() < k_it.row())\n                            ++j_it;\n                        else if(j_it.row() == k_it.row())//L(i,k) are L(i,j) are nonzero\n                            break;\n                        else\n                        {\n                            missing += k_it.value();//L(i,k) will fill something not in L(i,j)\n                            break;\n                        }\n                    }\n                    ++k_it;\n                }\n\n\n                if(k_it && j_it.row() == j)\n                {\n                    Dinv(j) -= it.value() * multiplier;\n                }\n\n\n                typename Matrix::InnerIterator j_it2(L,j);\n                while(k_it && j_it2)\n                {\n                    if(j_it2.row() < k_it.row())\n                        ++j_it2;\n                    else if(j_it2.row() == k_it.row())//L(i,k) and L(i,j) are both nonzero, -=L(i,k)*L(j,k)*D(k)\n                    {\n                        j_it2.valueRef() -= multiplier * k_it.value() ;//k_it.value()=L(i,k)\n                        ++j_it2;\n                        ++k_it;\n                    }\n                    else\n                    {\n                        missing+=k_it.value();\n                        ++k_it;\n                    }\n                }\n\n                while(k_it)\n                {\n                    missing+=k_it.value();\n                    ++k_it;\n                }\n                Dinv(j)-=0.97*missing*multiplier;\n            }\n        }\n\n        /*\n           std::cout << L << std::endl;\n           */\n\n    }\n    void solve(const Vector & b, Vector & x)\n    {\n        x = L.template triangularView<Eigen::UnitLower>().solve(b);\n        x.noalias() = x.cwiseProduct(Dinv);//safe beacuse it's a dot\n        L.transpose().template triangularView<Eigen::UnitUpper>().solveInPlace(x);\n    }\n    Matrix getA()\n    {\n        Matrix\n                A = L.template triangularView<Eigen::UnitLower>();\n        A = A * D.asDiagonal();\n        A = A * L.template triangularView<Eigen::UnitLower>().transpose();\n\n        return A;\n    }\nprivate:\n    Matrix L;\n    Vector D,Dinv;\n};\n\ntemplate <typename MatrixType, typename VectorType, typename Preconditioner>\nstruct PreconditionedConjugateGradient\n{\n    typedef MatrixType Matrix;\n    typedef VectorType Vector;\n    typedef typename Vector::Scalar Scalar;\n    PreconditionedConjugateGradient(const Matrix & A): A(A)\n    {\n        precond = Preconditioner(A);\n    }\n    auto solve(const Vector& b) {\n        auto x = b.eval();\n        x.setZero();\n        Vector r = b-A*x;\n        Vector z;\n        precond.solve(r,z);\n        Vector p = z;\n        Vector Ap = A*p;\n        Scalar rdz = r.dot(z);\n        Scalar alpha, beta;\n        auto error = [&]() { return r.template lpNorm<Eigen::Infinity>(); };\n\n        uint iterations = 0;\n        while(++iterations < 10 &&\n                error() > epsilon)\n        {\n            alpha = (rdz)/(p.dot(Ap));\n            x+=alpha * p;\n            r-=alpha * Ap;\n            precond.solve(r,z);\n            beta=1/rdz;\n            rdz = r.dot(z);\n            beta*=rdz;\n            p=z+beta*p;\n            Ap=A*p;\n        }\n        return x;\n    }\nprivate:\n    const Matrix & A;\n    Preconditioner precond;\n\n    Scalar epsilon = 1e-5;\n\n};\n\ntemplate <typename Matrix, typename Vector>\nauto ldlt_pcg_solver(const Matrix & A, const Vector& b)\n{\n    return PreconditionedConjugateGradient<Matrix,Vector, SparseLDLT<Matrix, mtao::Vector<typename Vector::Scalar, Vector::RowsAtCompileTime>>>(A);\n    //auto solver = IterativeLinearSolver<PreconditionedConjugateGradientCapsule<Matrix,Vector, Preconditioner> >(A.rows(), 1e-5);\n}\ntemplate <typename Matrix, typename Vector>\nauto ldlt_pcg_solve(const Matrix & A, const Vector & b)\n{\n    auto solver = ldlt_pcg_solver(A,b);\n    //auto solver = IterativeLinearSolver<PreconditionedConjugateGradientCapsule<Matrix,Vector, Preconditioner> >(A.rows(), 1e-5);\n    return solver.solve(b);\n}\n\n\n\n\n\n\nusing namespace mtao::logging;\n\ndouble max_eigenvalue(const Eigen::SparseMatrix<double>& A) {\n    mtao::VecXd xold = mtao::VecXd::Random(A.rows()).normalized();\n    mtao::VecXd x = (A * xold).normalized();\n    while((x - xold).norm() > 1e-5) {\n        xold = x;\n        x = (A * xold).normalized();\n        std::cout << \"Max:\" << (x-xold).norm() << std::endl;\n    }\n    return (A*x).norm();\n}\n\ndouble min_eigenvalue(const Eigen::SparseMatrix<double>& A) {\n    mtao::VecXd xold = mtao::VecXd::Random(A.rows()).normalized();\n    std::cout << \"Preparing solver\" << std::endl;\n    auto solver = ldlt_pcg_solver(A,xold);\n    std::cout << \"Done\" << std::endl;\n\n    mtao::VecXd x = (solver.solve(xold)).normalized();\n    while((x - xold).norm() > 1e-5) {\n        xold = x;\n        x = (solver.solve(xold)).normalized();\n        std::cout << \"Min:\" << (x-xold).norm() << std::endl;\n    }\n    return (A*x).norm();\n}\n\nint main(int argc, char * argv[]) {\n\n    auto&& log = make_logger(\"profiler\",mtao::logging::Level::All);\n    mtao::CommandLineParser clp;\n    clp.parse(argc, argv);\n\n    if(clp.args().size() < 1) {\n        fatal() << \"No input mesh filename!\";\n        return {};\n    }\n\n    std::string input_cutmesh = clp.arg(0);\n\n    CutCellMesh<3> ccm = CutCellMesh<3>::from_proto(input_cutmesh);\n\n    auto B = ccm.boundary();\n    mtao::VecXd DM = ccm.mesh_face_mask();\n    B = DM.asDiagonal() * B;\n    DM = mtao::VecXd::Ones(ccm.cell_size());\n    for(auto&& [i,c]: mtao::iterator::enumerate(ccm.cells())) {\n    }\n    B = B * DM.asDiagonal();\n\n    mtao::VecXd DH2 = ccm.dual_hodge2();\n    Eigen::SparseMatrix<double> L = B.transpose() * DH2.asDiagonal() * B;\n\n\n    double M = max_eigenvalue(L);\n    double m = min_eigenvalue(L);\n    \n    std::cout << m << \" < \" << M  << std::endl;\n    std::cout << \"condition number: \" << (M / m) << std::endl;\n}\n", "meta": {"hexsha": "1afde3ad7415c03c3a753c9869b5bff082ac1ac9", "size": 7678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/laplacian_test.cpp", "max_stars_repo_name": "mtao/mandoline", "max_stars_repo_head_hexsha": "79438c5b210a2ca4b9f72cbfd2879a9ae6a665da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2019-11-12T11:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:09:19.000Z", "max_issues_repo_path": "tests/laplacian_test.cpp", "max_issues_repo_name": "mtao/mandoline", "max_issues_repo_head_hexsha": "79438c5b210a2ca4b9f72cbfd2879a9ae6a665da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-17T01:49:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-29T19:46:36.000Z", "max_forks_repo_path": "tests/laplacian_test.cpp", "max_forks_repo_name": "mtao/mandoline", "max_forks_repo_head_hexsha": "79438c5b210a2ca4b9f72cbfd2879a9ae6a665da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T02:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T06:15:22.000Z", "avg_line_length": 29.3053435115, "max_line_length": 147, "alphanum_fraction": 0.494269341, "num_tokens": 1948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.78793120560257, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.4062730218283313}}
{"text": "#include <vector>\n#include <stdexcept>\n#include <fstream>\n#include \"Graph.h\"\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/trim_all.hpp>\n#include <boost/algorithm/string/join.hpp>\n#include <iostream>\n#include <boost/regex.hpp>\n\ninline const string BoolToString(bool b)\n{\n    return b ? \"true\" : \"false\";\n}\n\nGraph::Graph(vector<vector<int>> adjacencyMatrix) {\n    nodes = vector<string>();\n    for (int i = 0; i < adjacencyMatrix[0].size(); i++) {\n        nodes.push_back(to_string(i));\n    }\n    if (isSquareMatrix(adjacencyMatrix)) {\n        this->adjacencyMatrix = adjacencyMatrix;\n    } else {\n        throw invalid_argument(\"adjacency matrix has to be symmetrical\");\n    };\n}\n\n\nGraph::Graph(vector<vector<int>> adjacencyMatrix, vector<string> node_names) {\n    cout << \"node names: \" << endl;\n    for (string str : node_names) {\n        cout << str << endl;\n    }\n    if (isSquareMatrix(adjacencyMatrix)) {\n        this->adjacencyMatrix = adjacencyMatrix;\n    } else {\n        throw invalid_argument(\"adjacency matrix has to be symmetrical\");\n    };\n\n    if (node_names.size() == getNumberOfNodes()) {\n        this->nodes = vector<string>();\n        for (string node : node_names) {\n            nodes.push_back(node);\n        }\n    } else {\n        cout << \"Nodes: \" << getNumberOfNodes() << \", nodes in argument: \" << node_names.size() << endl;\n        throw invalid_argument(\"Nodes number does not match adjencency matrix:\\nNodes: \");\n    }\n}\n\n\nGraph::Graph(string matlabMatrix) {\n\n    // replace all tabs\n    boost::replace_all(matlabMatrix, \"\\t\", \" \");\n    // remove leading, trailing spaces and compress double spaces\n    boost::trim_all(matlabMatrix);\n\n    // replace spaces before and after semicolons\n    boost::replace_all(matlabMatrix, \" ; \", \";\");\n    boost::replace_all(matlabMatrix, \"; \", \";\");\n    boost::replace_all(matlabMatrix, \" ;\", \";\");\n\n    if (!boost::starts_with(matlabMatrix, \"[\") || !boost::ends_with(matlabMatrix, \"]\")) {\n        throw invalid_argument(\"A valid matlab matrix notation must start with '[' and end up with ']'.\");\n    }\n\n    // remove square braces and arising (trailing) spaces\n    matlabMatrix.erase(0, 1);\n    matlabMatrix.erase(matlabMatrix.size() - 1);\n    boost::trim(matlabMatrix);\n\n    // split string at ';' ==> get rows of the matrix\n    vector<std::string> rows;\n    boost::split(rows, matlabMatrix, boost::is_any_of(\";\"));\n    vector<vector<int>> adjacencyMatrix = getZeroizedMatrix((int) rows.size(), (int) rows.size());\n    int columnMax = 0;\n\n    // get columns of the matrix\n    for (unsigned long rIndex = 0; rIndex < rows.size(); rIndex++) {\n        vector<std::string> columns;\n        boost::split(columns, rows[rIndex], boost::is_any_of(\" \"));\n        boost::trim(rows[rIndex]);\n\n        if (columnMax == 0) {\n            columnMax = (int) columns.size();\n        }\n\n        // Error: There is a row with more ore less columns\n        if (columnMax != columns.size()) {\n            throw invalid_argument(\"There must be a syntax error, because the number of columns are different.\");\n        }\n\n        // matrix must be square!\n        if (rows.size() != columns.size()) {\n            throw invalid_argument(\"adjacency matrix has to be symmetrical\");\n        }\n\n        // add values to matrix\n        for (unsigned long cIndex = 0; cIndex < columns.size(); cIndex++) {\n            try {\n                adjacencyMatrix.at(rIndex).at(cIndex) = stoi(columns[cIndex]);\n            } catch (const invalid_argument &e) {\n                throw invalid_argument(\"matrix entries must be and contain at least one integer.\");\n            }\n\n        }\n    }\n\n    this->adjacencyMatrix = adjacencyMatrix;\n\n    nodes = vector<string>();\n    for (int i = 0; i < adjacencyMatrix[0].size(); i++) {\n        nodes.push_back(to_string(i));\n    }\n}\n\nbool Graph::isSquareMatrix(const vector<vector<int>> &adjacencyMatrix) const {\n    int rows = (int) adjacencyMatrix.size();\n    int cols = 0;\n    for (vector<int> row : adjacencyMatrix) {\n        // row.size() = number of cols in the current row\n        if (row.size() > cols) {\n            cols = (int) row.size();\n        }\n    }\n\n    return rows == cols;\n}\n\nconst vector<vector<int>> &Graph::getAdjacencyMatrix() const {\n    return adjacencyMatrix;\n}\n\n/**\n * Detect the number of nodes of the given graph.\n * @return number of nodes.\n */\nint Graph::getNumberOfNodes() const {\n    return (int) this->adjacencyMatrix.size();\n}\n\nint Graph::getInDeg(int vertexIndex) {\n\n    if (vertexIndex < 0 || vertexIndex >= this->getNumberOfNodes()) {\n        throw invalid_argument(\"vertex index has to be between 0 and n, but is \" + to_string(vertexIndex) + \".\");\n    }\n\n    // no value cached ==> calculate degree\n    if (this->inDeg.empty() || this->inDeg[vertexIndex] < 1) {\n\n        // count edges\n        int countIngoingEdges = 0;\n        for (int row = 0; row < this->getNumberOfNodes(); row++) {\n            // adds ingoing edges\n            countIngoingEdges += this->adjacencyMatrix[row][vertexIndex];\n\n            // In undirected graphs loops are counted twice:\n            if (adjacencyMatrix[row][vertexIndex] > 0 && row == vertexIndex && !this->isDirected()) {\n                countIngoingEdges++;\n            }\n        }\n\n        // setting cache value\n        this->inDeg.resize((unsigned long) this->getNumberOfNodes());\n        this->inDeg[vertexIndex] = countIngoingEdges;\n    }\n\n    return this->inDeg[vertexIndex];\n}\n\nint Graph::getOutDeg(int vertexIndex) {\n\n    if (vertexIndex < 0 || vertexIndex >= this->getNumberOfNodes()) {\n        throw invalid_argument(\"vertex index has to be between 0 and n, but is \" + to_string(vertexIndex) + \".\");\n    }\n\n    // no value cached ==> calculate degree\n    if (this->outDeg.empty() || this->outDeg[vertexIndex] < 1) {\n\n        // count edges\n        int countOutgoingEdges = 0;\n        for (int col = 0; col < this->getNumberOfNodes(); col++) {\n            // adds ingoing edges\n            countOutgoingEdges += this->adjacencyMatrix[vertexIndex][col];\n\n            // In undirected graphs loops are counted twice:\n            if (adjacencyMatrix[vertexIndex][col] > 0 && col == vertexIndex && !this->isDirected()) {\n                countOutgoingEdges++;\n            }\n        }\n\n        // setting cache value\n        this->outDeg.resize((unsigned long) this->getNumberOfNodes());\n        this->outDeg[vertexIndex] = countOutgoingEdges;\n    }\n\n    return this->outDeg[vertexIndex];\n}\n\nbool Graph::isDirected() {\n\n    // Get cached result.\n    switch (this->type) {\n        case DIRECTED:\n            return true;\n\n        case UNDIRECTED:\n            return false;\n\n        case UNCHECKED:\n            // check if values of the adjacency matrix are set symmetrically ==> undirected graph\n            // otherwise diagraph\n            for (int row = 0; row < this->getNumberOfNodes(); row++) {\n                // check only upper triangle part of matrix\n                for (int col = row + 1; col < this->getNumberOfNodes(); col++) {\n                    // values must be the same, otherwise its a digraph\n                    if (this->getAdjacencyMatrix()[row][col] != this->getAdjacencyMatrix()[col][row]) {\n                        // cache result\n                        this->type = DIRECTED;\n                        return true;\n                    }\n                }\n            }\n\n            break;\n    }\n\n    // cache result\n    this->type = UNDIRECTED;\n    return false;\n}\n\nbool Graph::isFreeOfLoops() {\n\n    if (isFreeOfLoopsFlag) {\n        return isFreeOfLoopsCache;\n    }\n\n    isFreeOfLoopsFlag = true;\n\n    for (int mainDiagonal = 0; mainDiagonal < this->getNumberOfNodes(); ++mainDiagonal) {\n        // check if there is a loop\n        if (this->getAdjacencyMatrix()[mainDiagonal][mainDiagonal] > 0) {\n            isFreeOfLoopsCache = false;\n            return isFreeOfLoopsCache;\n        }\n    }\n\n    isFreeOfLoopsCache = true;\n    return isFreeOfLoopsCache;\n}\n\nbool Graph::isMultigraph() {\n\n    if (isMultigraphFlag) {\n        return isMultigraphCache;\n    }\n\n    isMultigraphFlag = true;\n\n    /*\n     * if the adjacency matrix contains a value greater than 1 the matrix\n     * has multiple edges and therefore the graph is a multigraph.\n     */\n    for (int row = 0; row < this->getNumberOfNodes(); ++row) {\n        for (int col = 0; col < this->getNumberOfNodes(); ++col) {\n            if (this->getAdjacencyMatrix()[row][col] > 1) {\n                isMultigraphCache = true;\n                return isMultigraphCache;\n            }\n        }\n    }\n\n    isMultigraphCache = false;\n    return isMultigraphCache;\n}\n\nbool Graph::isSimple() {\n    return !this->isDirected() && !isMultigraph() && isFreeOfLoops();\n}\n\nbool Graph::isComplete() {\n\n    if (isCompleteFlag) {\n        return isCompleteCache;\n    }\n\n    isCompleteFlag = true;\n\n\n    /*\n     * the graph is complete if the adjacency matrix has only entries of 1\n     * except the main diagonal which must be 0.\n     */\n    if (!isFreeOfLoops()) {\n        isCompleteCache = false;\n        return isCompleteCache;\n    }\n\n    for (int row = 0; row < this->getNumberOfNodes(); row++) {\n        for (int col = 0; col < this->getNumberOfNodes(); col++) {\n            // only 1 is allowed now\n            if (row != col && this->getAdjacencyMatrix()[row][col] != 1) {\n                isCompleteCache = false;\n                return isCompleteCache;\n            }\n        }\n    }\n\n    isCompleteCache = true;\n    return isCompleteCache;\n}\n\nbool Graph::isRegular() {\n\n    if (isRegularFlag) {\n        return isRegularCache;\n    }\n\n    isRegularFlag = true;\n\n    // get in/out deg of the first vertex\n    int inDegOfFirstVertex = this->getInDeg(0);\n    int outDegOfFirstVertex = this->getOutDeg(0);\n\n    // all other vertices must have the same deg,\n    // otherwise this graph is not regular\n    for (int vertex = 1; vertex < this->getNumberOfNodes(); vertex++) {\n\n\n        // directed graph ==> indeg and outdeg can differ ==> we have to test both\n        // undirected graph ==> indeg and outdeg must be the same ==> we only must test one\n        // ==> we can use the following commands for both types\n        if (this->getInDeg(vertex) != inDegOfFirstVertex || this->getOutDeg(vertex) != outDegOfFirstVertex) {\n            isRegularCache = false;\n            return isRegularCache;\n        }\n\n    }\n\n    isRegularCache = true;\n    return isRegularCache;\n}\n\n/**\n * Transform the graph to json-format.\n * @return string json.\n */\nstring Graph::graphToJson() {\n\n    string edgeType = \"line\";\n\n    if (this->isDirected())\n        string edgeType = \"arrow\";\n\n    int size = (int) this->adjacencyMatrix.size();\n\n    string nodes = \"\\\"nodes\\\": [\";\n\n    // parse json nodes\n    for (int i = 0; i < size; i++) {\n        nodes += \"{ \";\n        nodes += \"\\\"id\\\": \\\"\" + to_string(i) + \"\\\",\";\n        nodes += \"\\\"label\\\": \\\"\" + to_string(i) + \"\\\",\";\n        nodes += \"\\\"x\\\": \\\"\" + to_string(rand() % 10) + \"\\\",\";\n        nodes += \"\\\"y\\\": \\\"\" + to_string(rand() % 10) + \"\\\",\";\n        nodes += \"\\\"size\\\": \\\"\" + to_string(1) + \"\\\"\";\n\n        if (i < (size - 1)) {\n            nodes += \"},\";\n        } else {\n            nodes += \"}\";\n        }\n    }\n\n    nodes += \"]\";\n\n    string edges = \"\\\"edges\\\": [\";\n    int y = 0;\n    int id = 0;\n\n    // parse json edges\n    for (vector<int> row : adjacencyMatrix) {\n\n        // column\n        for (int x = 0; x < row.size(); x++) {\n\n            // if there is a connection between two nodes.\n            if (row[x] == 1) {\n\n                if (id == 0) {\n                    // first element\n                    edges += \"{ \";\n                } else {\n                    edges += \", { \";\n                }\n\n                // set properties\n                edges += \"\\\"id\\\": \" + to_string(id) + \",\";\n                edges += \"\\\"source\\\": \" + to_string(y) + \",\";\n                edges += \"\\\"target\\\": \" + to_string(x) + \",\";\n                edges += \"\\\"type\\\": \\\"\" + edgeType + \"\\\",\";\n                edges += \"\\\"size\\\": \" + to_string(1);\n\n                edges += \"}\";\n\n                id++;\n            }\n        }\n        y++;\n    }\n\n    edges += \"]\";\n\n    string properties = \"\\\"properties\\\": {\" ;\n\n    properties += \"\\\"Vertices\\\": \\\"\" + to_string(getNumberOfNodes()) + \"\\\",\";\n    properties += \"\\\"Edges\\\": \\\"\" + to_string(getNumberOfEdges()) + \"\\\",\";\n    properties += \"\\\"isDirected\\\": \\\"\" + BoolToString(isDirected()) + \"\\\",\";\n    properties += \"\\\"isComplete\\\": \\\"\" + BoolToString(isComplete()) + \"\\\",\";\n    properties += \"\\\"isMultigraph\\\": \\\"\" + BoolToString(isMultigraph()) + \"\\\",\";\n    properties += \"\\\"isRegular\\\": \\\"\" + BoolToString(isRegular()) + \"\\\",\";\n    properties += \"\\\"isSimple\\\": \\\"\" + BoolToString(isSimple()) + \"\\\",\";\n    properties += \"\\\"hasCycle\\\": \\\"\" + BoolToString(hasCycle()) + \"\\\",\";\n    properties += \"\\\"isFreeOfLoops\\\": \\\"\" + BoolToString(isFreeOfLoops()) + \"\\\",\";\n    properties += \"\\\"isForest\\\": \\\"\" + BoolToString(isForest()) + \"\\\"\";\n\n    properties += \"}\";\n\n    return \"{ \\\"graph\\\": {\" + nodes + \", \" + edges + \"}, \" + properties + \" }\";\n}\n\n/**\n * Export a given file with custom data.\n * @param fileName string file name.\n * @param data string of data.\n */\nvoid Graph::exportFile(const string fileName, const string data) const {\n    ofstream file;\n    file.open(fileName);\n    file << data;\n    file.close();\n}\n\n\nvoid Graph::exportAdjazenzmatrixFile(const string fileName) const {\n    return exportFile(fileName, getAdjacencyMatrixString());\n}\n\n/**\n * Checks the graph if a cycle exists. DFS.\n * @return true if a cycle exists, else false\n */\nbool Graph::hasCycle() {\n\n    if (hasCycleFlag) {\n        return hasCycleCache;\n    }\n\n    int nodes = this->getNumberOfNodes();\n\n    // array for the visited nodes\n    bool *visited = new bool[nodes];\n    // array for the stack\n    bool *stack = new bool[nodes];\n\n    // set the default values to the stack and the visited nodes arrays\n    for (int i = 0; i < nodes; i++) {\n        visited[i] = false;\n        stack[i] = false;\n    }\n\n    for (int i = 0; i < nodes; i++) {\n        if (hasCycleRec(i, visited, stack)) {\n            hasCycleCache = true;\n            hasCycleFlag = true;\n            return true;\n        }\n    }\n\n    hasCycleFlag = true;\n    hasCycleCache = false;\n    return false;\n}\n\n/**\n * Private helper function for hasCycle function.\n * @param i current index.\n * @param visited array contains visited elements.\n * @param stack for recursion.\n * @return true if cycle found else false\n */\nbool Graph::hasCycleRec(const int i, bool *visited, bool *stack) const {\n\n    // check if node was not visited.\n    if (!visited[i]) {\n        visited[i] = true;\n        stack[i] = true;\n\n        // iterate through the given adja matrix row (i)\n        for (int x = 0; x < this->getNumberOfNodes(); ++x) {\n            if (adjacencyMatrix[x][i] > 0) {\n                // if the current node has an edge\n                if (!visited[x] && hasCycleRec(x, visited, stack)) {\n                    // if node was not visited and there is a existing cycle\n                    return true;\n                } else if (stack[x]) {\n                    // if the stack contains the current node\n                    return true;\n                }\n            }\n        }\n\n    }\n\n    // delete node from stack if the node was visited\n    stack[i] = false;\n    return false;\n}\n\n/**\n * Checks if the graph contains the given edge.\n * @param from node number\n * @param to node number\n * @return true if the edge exists, else if not\n */\nbool Graph::hasEdge(const int from, const int to) {\n\n    if (isDirected()) {\n        return adjacencyMatrix[from][to] > 0;\n    } else {\n        return adjacencyMatrix[from][to] > 0 && adjacencyMatrix[to][from] > 0;\n    }\n\n}\n\n/**\n * Checks, if the graph contains the given path.\n * @param path vector with path nodes.\n * @return true if graph contains the path, else false\n */\nbool Graph::hasPath(const vector<int> path) const {\n\n    if (path.size() == 0) {\n        throw invalid_argument(\"The vector must contain at least one value!\");\n    }\n\n    for (int i = 0; i < path.size(); i++) {\n        if (path[i] >= this->getNumberOfNodes()) {\n            throw invalid_argument(\"The vector contains not existing nodes!\");\n        } else if (i + 1 < path.size() && adjacencyMatrix[path[i]][path[i + 1]] == 0) {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nbool Graph::hasConnectivity(int s, int t) {\n\n    if (s < 0 || s > getNumberOfNodes() - 1) {\n        throw invalid_argument(\"invalid s\");\n    } else if (t < 0 || t > getNumberOfNodes() - 1) {\n        throw invalid_argument(\"invalid t\");\n    }\n\n    // there is a direct connection form s to t\n    if (getAdjacencyMatrix()[s][t] > 0) {\n        return true;\n    }\n\n    // loops are not allowed if adjacency matrix has none there\n    if (s == t && getAdjacencyMatrix()[s][t] == 0) {\n        return false;\n    }\n\n    // there is no direct connection from s to t\n    // test if there are any connections using idea from\n    // https://de.wikipedia.org/wiki/Adjazenzmatrix#Pfadl.C3.A4nge_in_Graphen_berechnen\n    // we skip identity (A^0) and original adjacency matrix (A^1) ==> start at k = 2\n    for (int k = 2; k < getNumberOfNodes(); ++k) {\n\n        vector<vector<int>> tmp = powerMatrix(getAdjacencyMatrix(), k);\n\n        if (tmp[s][t] > 0) {\n            return true;\n        }\n    }\n\n    return false;\n}\n\nbool Graph::isSameMatrix(const vector<vector<int>> &A, const vector<vector<int>> &B) {\n\n    if (A.size() != B.size() || A[0].size() != B[0].size()) {\n        return false;\n    }\n\n    // rows of A\n    for (int i = 0; i < A.size(); i++) {\n        // cols of A\n        for (int j = 0; j < A[0].size(); j++) {\n            if (A[i][j] != B[i][j]) {\n                return false;\n            }\n        }\n    }\n\n    return true;\n}\n\nvector<vector<int>> Graph::getZeroizedMatrix(int rows, int cols) {\n\n    // initialize an empty square matrix\n    vector<vector<int>> resultMatrix = vector<vector<int>>((unsigned long) rows);\n\n    // only diagonal is 1\n    for (int diagonal = 0; diagonal < rows; diagonal++) {\n        // set row to 0\n        resultMatrix[diagonal] = vector<int>((unsigned long) cols, 0);\n    }\n\n    return resultMatrix;\n}\n\nvector<vector<int>> Graph::getIdentityMatrix(int size) {\n\n    // initialize an empty square matrix\n    vector<vector<int>> resultMatrix = getZeroizedMatrix(size, size);\n\n    // set diagonal to 1\n    for (int diagonal = 0; diagonal < size; diagonal++) {\n        resultMatrix[diagonal][diagonal] = 1;\n    }\n\n    return resultMatrix;\n}\n\nvector<vector<int>> Graph::powerMatrix(vector<vector<int>> squareMatrix, int exponent) {\n\n    // initialize an empty square matrix\n    vector<vector<int>> resultMatrix;\n\n    if (exponent < 0) {\n        throw invalid_argument(\"not implemented yet\");\n\n    } else if (exponent == 0) {\n        resultMatrix = getIdentityMatrix((int) squareMatrix.size());\n\n    } else if (exponent == 1) {\n        return squareMatrix;\n\n    } else {\n        resultMatrix = getIdentityMatrix((int) squareMatrix.size());\n\n        for (int multiplyIndex = 0; multiplyIndex < exponent; multiplyIndex++) {\n            resultMatrix = multiplyMatrix(resultMatrix, squareMatrix);\n        }\n    }\n\n    return resultMatrix;\n}\n\nvector<vector<int>> Graph::multiplyMatrix(const vector<vector<int>> &A, const vector<vector<int>> &B) {\n    // rows of A\n    int l = (int) A.size();\n\n    // cols of A MUST BE rows of B\n    int m = (int) A[0].size();\n    if (A[0].size() != B.size()) {\n        throw invalid_argument(\"Matrix A must have as much rows as B columns. \");\n    }\n\n    // cols of B\n    int n = (int) B[0].size();\n\n    vector<vector<int>> C = getZeroizedMatrix(l, n);\n\n    // multiply matrix c_{ij} = \\sum_{j=1}^{m} a_{ij} \\cdot \\b_{jk}\n    // loop over rows of C\n    for (int i = 0; i < l; i++) {\n        // loop over columns of C\n        for (int k = 0; k < n; k++) {\n            // loop over columns of A/rows of B\n            for (int j = 0; j < m; j++) {\n                C[i][k] = C[i][k] + A[i][j] * B[j][k];\n            }\n        }\n    }\n\n    return C;\n}\n\nvector<vector<int>> Graph::addMatrix(const vector<vector<int>> &A, const vector<vector<int>> &B) {\n\n    if (A.size() != B.size() || A[0].size() != B[0].size()) {\n        throw invalid_argument(\"Matrix A and B must have the same size (rows and columns). \");\n    }\n\n    // rows of A\n    int m = (int) A.size();\n\n    // cols of A MUST BE rows of B\n    int n = (int) A[0].size();\n\n    vector<vector<int>> C = getZeroizedMatrix(m, n);\n\n    // add matrix\n    for (int i = 0; i < m; i++) {\n        for (int j = 0; j < n; j++) {\n            C[i][j] = A[i][j] + B[i][j];\n        }\n    }\n\n    return C;\n}\n\nint Graph::getNumberOfEdges() {\n    if (adjacencyMatrix.size() <= 0) {\n        return 0;\n    }\n    int count = 0;\n    long end = adjacencyMatrix.size();\n    for (long i = 0; i < end; i++) {\n        for (long j = 0; j < end; j++) {\n            if (adjacencyMatrix[i][j]) {\n                count++;\n            }\n        }\n    }\n    if (!isDirected()) {\n        count /= 2;\n    }\n    return count;\n}\n\nstring Graph::exportDot() {\n    string data = \"\";\n    if (isDirected()) { data += \"digraph {\\n\"; } else { data += \"graph {\\n\"; }\n\n    //create nodes - in case one node has no edges\n    for (int i = 0; i < adjacencyMatrix.size(); i++) {\n        data += nodes[i] + \"\\n\";\n    }\n\n    for (int x = 0; x < adjacencyMatrix.size(); x++) {\n        if (!isDirected()) {\n            for (long y = 0; y <= x; y++) {\n                if (adjacencyMatrix[x][y] > 0) {\n                    data += \"\\t\" + nodes[x];\n                    data += \" -- \";\n                    data += nodes[y];\n                }\n            }\n        } else {\n            for (int y = 0; y < adjacencyMatrix.size(); y++) {\n                if (adjacencyMatrix[x][y] > 0) {\n                    data += \"\\t\" + nodes[x];\n                    data += \" -> \";\n                    data += nodes[y];\n                }\n            }\n        }\n    }\n    data += \"\\n}\\n\";\n    return data;\n}\n\nbool Graph::areNeighbours(int from, int to) {\n\n    if (from < 0 || to < 0 || from > getNumberOfNodes() - 1 || to > getNumberOfNodes() - 1) {\n        throw out_of_range(\"from and to have to be in the range. \");\n    }\n\n    if (isDirected()) {\n        return getAdjacencyMatrix()[from][to] > 0;\n    } else {\n        return getAdjacencyMatrix()[from][to] > 0 && getAdjacencyMatrix()[to][from] > 0;\n    }\n}\n\nstring Graph::exportDot(vector<int> path) {\n    if (!hasPath(path)) {\n        return \"error: Not a valid path\";\n    }\n\n    string data = \"\";\n    if (isDirected()) { data += \"digraph {\\n\"; } else { data += \"graph {\\n\"; }\n\n    //create nodes - in case one node has no edges\n    for (int i = 0; i < adjacencyMatrix.size(); i++) {\n        data += nodes[i] + \"\\n\";\n    }\n\n    for (int x = 0; x < adjacencyMatrix.size(); x++) {\n        if (!isDirected()) {\n            for (long y = 0; y <= x; y++) {\n                if (adjacencyMatrix[x][y] > 0) {\n                    data += \"\\t\" + nodes[x];\n                    data += \" -- \";\n                    data += nodes[y];\n                    //Create path color\n                    for (int i = 1; i <= path.size(); i++) {\n                        if (path[i - 1] == x && path[i] == y) {\n                            data += \"[color= maroon];\";\n                        }\n                    }\n                }\n\n            }\n        } else {\n            for (int y = 0; y < adjacencyMatrix.size(); y++) {\n                if (adjacencyMatrix[x][y] > 0) {\n                    data += \"\\t\" + nodes[x];\n                    data += \" -> \";\n                    data += nodes[y];\n                    //Create path color\n                    for (int i = 1; i <= path.size(); i++) {\n                        if (path[i - 1] == x && path[i] == y) {\n                            data += \"[color= maroon];\";\n                        }\n                    }\n                }\n            }\n        }\n    }\n    data += \"\\n}\\n\";\n    return data;\n}\n\nconst string Graph::getAdjacencyMatrixString() const {\n    stringstream ss;\n\n    long end = adjacencyMatrix.size();\n    for (long i = 0; i < end; i++) {\n        auto mat = adjacencyMatrix[i];\n\n        std::vector<std::string> list;\n        transform(mat.begin(), mat.end(), std::back_inserter(list),\n                  [](const int i) { return to_string(i); });\n\n        ss << boost::algorithm::join(list, \",\");\n        ss << endl;\n    }\n\n    return ss.str();\n}\n\nbool Graph::isForest() {\n    if (isForestCache) {\n        return isForestFlag;\n    }\n\n    isForestCache = true;\n    if(hasCycle() || !isDirected()) {\n        isForestFlag = false;\n        return false;\n    }\n    for (int i = 0; i < adjacencyMatrix.size(); i++) {\n        if(getInDeg(i) > 1) {\n            isForestFlag = false;\n            return false;\n        }\n    }\n    isForestFlag = true;\n    return true;\n}\n", "meta": {"hexsha": "fb5c8320ec5ccbff345fea5a4a4d550fe3a3d230", "size": 24831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphtool/Graph.cpp", "max_stars_repo_name": "089/blatt-2-amf0", "max_stars_repo_head_hexsha": "c6da0f816a80c8b3eaedf9230b0476433ea7b2c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-03T13:19:19.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-03T13:19:19.000Z", "max_issues_repo_path": "graphtool/Graph.cpp", "max_issues_repo_name": "089/Graphs", "max_issues_repo_head_hexsha": "c6da0f816a80c8b3eaedf9230b0476433ea7b2c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T18:07:59.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-07T12:53:21.000Z", "max_forks_repo_path": "graphtool/Graph.cpp", "max_forks_repo_name": "089/Graphs", "max_forks_repo_head_hexsha": "c6da0f816a80c8b3eaedf9230b0476433ea7b2c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-07-07T14:30:01.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-07T14:30:01.000Z", "avg_line_length": 28.5742232451, "max_line_length": 113, "alphanum_fraction": 0.534009907, "num_tokens": 6276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4060425159574356}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_TRANSFORM3DVECTOR_HPP\n#define RW_MATH_TRANSFORM3DVECTOR_HPP\n\n/**\n * @file Transform3DVector.hpp\n */\n\n#if !defined(SWIG)\n\n#include <rw/core/Ptr.hpp>\n#include <rw/math/EAA.hpp>\n#include <rw/math/Quaternion.hpp>\n#include <rw/math/Rotation3DVector.hpp>\n#include <rw/math/Transform3D.hpp>\n#include <rw/math/Vector3D.hpp>\n\n#include <Eigen/Core>\n\n#endif\nnamespace rw { namespace math {\n    /** @addtogroup math */\n    /* @{*/\n\n    /**\n     * @brief this class is a interpolatable Transform3D, consisting of a Vecor3D and a Quaternion.\n     * It is implemented to be very Interconvertable with a Transform3D, and allow operations souch\n     * as Transform * scalar and Transform + Transform.\n     */\n    template< class T = double > class Transform3DVector\n    {\n      public:\n        typedef Eigen::Matrix< T, 7, 1 > type;\n        typedef rw::core::Ptr< Transform3DVector< T > > Ptr;\n\n        /**\n         * @brief default constructor\n         */\n        Transform3DVector ():Transform3DVector(Vector3D<T>(),Quaternion<T>()) {}\n\n        /**\n         * @brief Constuct a Transformation matrix as a Vector\n         * @param vec [in] the vector of the transform\n         * @param rot [in] the rotation of the transform\n         */\n        Transform3DVector (const Vector3D< T >& vec, const Quaternion< T >& rot)\n        {\n            _t3d[0] = vec[0];\n            _t3d[1] = vec[1];\n            _t3d[2] = vec[2];\n            _t3d[3] = rot[0];\n            _t3d[4] = rot[1];\n            _t3d[5] = rot[2];\n            _t3d[6] = rot[3];\n        }\n\n        /**\n         * @brief Constuct a Transformation matrix as a Vector\n         * @param vec [in] the vector of the transform\n         * @param rot [in] the rotation of the transform\n         */\n        Transform3DVector (const Vector3D< T >& vec, const Rotation3DVector< T >& rot)\n        {\n            Quaternion< T > rotq (rot);\n            _t3d[0] = vec[0];\n            _t3d[1] = vec[1];\n            _t3d[2] = vec[2];\n            _t3d[3] = rotq[0];\n            _t3d[4] = rotq[1];\n            _t3d[5] = rotq[2];\n            _t3d[6] = rotq[3];\n        }\n\n        /**\n         * @brief Constuct a Transform3DVector from a Transform3D\n         * @param t3d [in] Transform3D\n         */\n        Transform3DVector (const Transform3D< T >& t3d) :\n            Transform3DVector (t3d.P (), Quaternion< T > (t3d.R ()))\n        {}\n\n        /**\n         * @brief Constuct a Transform3DVector from a EigenVector\n         * @param vec [in] Transform3D\n         */\n        Transform3DVector (const type& vec) : _t3d (vec) {}\n\n        /**\n         * @brief destructor\n         */\n        ~Transform3DVector () {}\n\n        // ###################################################\n        // #                 Math Operators                  #\n        // ###################################################\n\n        // ########## Vector3D Operators\n\n        /**\n         * @brief add a Vector3D to the position of the transform\n         * @param rhs [in] the right hand side value\n         * @return result of devision\n         */\n        Transform3DVector< T > operator+ (const Vector3D< T >& rhs) const\n        {\n            Transform3DVector< T > ret = *this;\n            for (size_t i = 0; i < rhs.size (); i++) {\n                ret[i] += rhs[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief subtract a Vector3D from the position of the transform\n         * @param rhs [in] the right hand side value\n         * @return result of devision\n         */\n        Transform3DVector< T > operator- (const Vector3D< T >& rhs) const\n        {\n            Transform3DVector< T > ret = *this;\n            for (size_t i = 0; i < rhs.size (); i++) {\n                ret[i + 3] -= rhs[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief Matrix vector multiplication with Vector3D. Same as Transform3D<> * Vector3D<>;\n         * @param rhs [in] the right hand side value\n         * @return result of multiplication\n         */\n        Vector3D< T > operator* (const Vector3D< T >& rhs) const\n        {\n            return this->toTransform3D () * rhs;\n        }\n\n        // ########## Quaternion Operators\n\n        /**\n         * @brief add a Quaternion to the rotation of the transform\n         * @param rhs [in] the right hand side value\n         * @return result of devision\n         */\n        Transform3DVector< T > operator+ (const Quaternion< T >& rhs) const\n        {\n            Transform3DVector< T > ret = *this;\n            for (size_t i = 0; i < rhs.size (); i++) {\n                ret[i + 3] += rhs[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief subtract a Quaternion from the rotation of the transform\n         * @param rhs [in] the right hand side value\n         * @return result of devision\n         */\n        Transform3DVector< T > operator- (const Quaternion< T >& rhs) const\n        {\n            Transform3DVector< T > ret = *this;\n            for (size_t i = 0; i < rhs.size (); i++) {\n                ret[i + 3] -= rhs[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief element wise devide a Quaternion with the Quaternion rotation of the transform\n         * @param rhs [in] the right hand side value\n         * @return result of devision\n         */\n        Transform3DVector< T > operator/ (const Quaternion< T >& rhs) const\n        {\n            Transform3DVector< T > ret = *this;\n            for (size_t i = 0; i < rhs.size (); i++) {\n                ret[i + 3] /= rhs[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief element wise multiply a Quaternion with the Quaternion rotation of the transform\n         * @param rhs [in] the right hand side value\n         * @return result of multiplication\n         */\n        Transform3DVector< T > operator* (const Quaternion< T >& rhs) const\n        {\n            Transform3DVector< T > ret = *this;\n            for (size_t i = 0; i < rhs.size (); i++) {\n                ret[i + 3] *= rhs[i];\n            }\n            return ret;\n        }\n\n        // ########## Transform3DVector Operations\n\n        /**\n         * @brief element wise add two Transform3DVectors\n         * @param rhs [in] the Transform3D vector to be added with\n         * @return the sum of the two objects\n         */\n        Transform3DVector< T > operator+ (const Transform3DVector< T >& rhs) const\n        {\n            Transform3DVector< T > ret = *this;\n            for (size_t i = 0; i < ret.size (); i++) {\n                ret[i] += rhs[i];\n            }\n            return ret;\n        }\n\n        /**\n         * @brief element wise subtract two Transform3DVectors\n         * @param rhs [in] the Transform3D vector to be subtracted with\n         * @return the difference of the two objects\n         */\n        Transform3DVector< T > operator- (const Transform3DVector< T >& rhs) const\n        {\n            Transform3DVector< T > ret = *this;\n            for (size_t i = 0; i < ret.size (); i++) {\n                ret[i] -= rhs[i];\n            }\n            return ret;\n        }\n\n        // ########## Scalar Operations\n\n        /**\n         * @brief Scalar multiplication\n         * @param rhs [in] the scalar to multiply with\n         * @return product of the multiplication\n         */\n        Transform3DVector< T > operator* (const T& rhs) const\n        {\n            return Transform3DVector< T > (this->_t3d * rhs);\n        }\n\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Scalar multiplication\n         * @param lhs [in] the scalar to multiply with\n         * @param rhs [in] the Transform3DVector being multiplied with a scalar\n         * @return product of the multiplication\n         */\n        friend Transform3DVector< T > operator* (const T& lhs, const Transform3DVector< T >& rhs)\n        {\n            return Transform3DVector< T > (lhs * rhs._t3d);\n        }\n#endif\n        /**\n         * @brief Scalar addition\n         * @param rhs [in] the scalar to add\n         * @return the sum\n         */\n        Transform3DVector< T > operator+ (const T& rhs) const\n        {\n            Transform3DVector< T > ret = *this;\n            for (size_t i = 0; i < ret.size (); i++) {\n                ret[i] += rhs;\n            }\n            return ret;\n        }\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Scalar addition\n         * @param lhs [in] the scalar to subtraction\n         * @param rhs [in] the Transform3DVector being subtracted from\n         * @return the difference\n         */\n        friend Transform3DVector< T > operator+ (const T& lhs, const Transform3DVector< T >& rhs)\n        {\n            Transform3DVector< T > ret = rhs;\n            for (size_t i = 0; i < ret.size (); i++) {\n                ret[i] += lhs;\n            }\n            return ret;\n        }\n#endif\n        /**\n         * @brief Scalar subtraction\n         * @param rhs [in] the scalar to subtract\n         * @return the difference\n         */\n        Transform3DVector< T > operator- (const T& rhs) const\n        {\n            Transform3DVector< T > ret = *this;\n            for (size_t i = 0; i < ret.size (); i++) {\n                ret[i] -= rhs;\n            }\n            return ret;\n        }\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Scalar subtraction\n         * @param lhs [in] the scalar to subtract\n         * @param rhs [in] the Transform3DVector being subtracted from\n         * @return the difference\n         */\n        friend Transform3DVector< T > operator- (const T& lhs, const Transform3DVector< T >& rhs)\n        {\n            Transform3DVector< T > ret = rhs;\n            for (size_t i = 0; i < ret.size (); i++) {\n                ret[i] = lhs - rhs[i];\n            }\n            return ret;\n        }\n#endif\n\n        /**\n         * @brief Scalar devision\n         * @param rhs [in] the scalar to devide with\n         * @return the result\n         */\n        Transform3DVector< T > operator/ (const T& rhs) const\n        {\n            return Transform3DVector< T > (this->_t3d / rhs);\n        }\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Scalar devision\n         * @param lhs [in] the scalar to devide with\n         * @param rhs [in] the Transform3DVector being devided\n         * @return the result\n         */\n        friend Transform3DVector< T > operator/ (const T& lhs, const Transform3DVector< T >& rhs)\n        {\n            Transform3DVector< T > ret = rhs;\n            for (size_t i = 0; i < ret.size (); i++) {\n                ret[i] = lhs / rhs[i];\n            }\n            return ret;\n        }\n#endif\n\n        // ###################################################\n        // #                Acces Operators                  #\n        // ###################################################\n\n#if !defined(SWIG)\n        /**\n         * @brief acces operator\n         * @param i [in] index of the Vector\n         * @return requested value\n         */\n        T& operator() (size_t i) { return _t3d[i]; }\n\n        /**\n         * @brief acces operator\n         * @param i [in] index of the Vector\n         * @return requested value\n         */\n        T operator() (size_t i) const { return _t3d[i]; }\n\n        /**\n         * @brief acces operator\n         * @param i [in] index of the Vector\n         * @return requested value\n         */\n        T& operator[] (size_t i) { return _t3d[i]; }\n\n        /**\n         * @brief acces operator\n         * @param i [in] index of the Vector\n         * @return requested value\n         */\n        T operator[] (size_t i) const { return _t3d[i]; }\n#else\n        ARRAYOPERATOR (T);\n\n#endif\n        /**\n         * @brief get the size. Index 0-2 Vector, 3-6 Quaternion\n         * @return always 7\n         */\n        size_t size () const { return 7u; }\n\n        /**\n         * @brief get the position Vector of the transform\n         * @return a copy of the position vector\n         */\n        Vector3D< T > toVector3D () const { return Vector3D< T > (_t3d[0], _t3d[1], _t3d[2]); }\n\n        /**\n         * @brief get the Rotation of the transform\n         * @return a copy of the quaternion rotation\n         */\n        Quaternion< T > toQuaternion () const\n        {\n            return Quaternion< T > (_t3d[3], _t3d[4], _t3d[5], _t3d[6]);\n        }\n\n        /**\n         * @brief convert the rotation part to EAA\n         * @return toration in EAA form\n         */\n        EAA< T > toEAA () const { return EAA< T > (this->toQuaternion ().toRotation3D ()); }\n\n        /**\n         * @brief Returns the corresponding Trandforma3D matrix\n         * @return The transformation matrix\n         */\n        Transform3D< T > toTransform3D () const\n        {\n            return Transform3D< T > (this->toVector3D (), this->toQuaternion ());\n        }\n\n        /**\n         * @brief get the underling eigen type\n         * @return reference to eigen vector\n         */\n        Eigen::Matrix< T, 7, 1 >& e () { return _t3d; }\n#if !defined(SWIG)\n        friend std::ostream& operator<< (std::ostream& os, const Transform3DVector< T >& t)\n        {\n            return os << \"Transform3DVector(\" << t.toVector3D () << \", \" << t.toQuaternion ()\n                      << \")\";\n        }\n#endif\n        // ###################################################\n        // #             assignement Operators               #\n        // ###################################################\n\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief copy the transform\n         * @param rhs the transform to copy\n         * @return a copy of this object\n         */\n        Transform3DVector< T >& operator= (const Transform3DVector< T >& rhs)\n        {\n            this->_t3d = rhs._t3d;\n            return *this;\n        }\n#endif\n        /**\n         * @brief add to the transform\n         * @param rhs the transform to be added\n         * @return a copy of this object\n         */\n        Transform3DVector< T >& operator+= (const Transform3DVector< T >& rhs)\n        {\n            this->_t3d = this->_t3d + rhs._t3d;\n            return *this;\n        }\n\n        /**\n         * @brief subtract from the transform\n         * @param rhs the transform to be subtracted\n         * @return a copy of this object\n         */\n        Transform3DVector< T >& operator-= (const Transform3DVector< T >& rhs)\n        {\n            this->_t3d = this->_t3d - rhs._t3d;\n            return *this;\n        }\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Override the Roation of the transform\n         * @param rhs the new rotation\n         * @return a copy of this object\n         */\n        Transform3DVector< T >& operator= (const Quaternion< T >& rhs)\n        {\n            *this = Transform3DVector< T > (this->toVector3D (), rhs);\n            return *this;\n        }\n#endif\n        /**\n         * @brief add to the Roation of the transform\n         * @param rhs the rotation to be added\n         * @return a copy of this object\n         */\n        Transform3DVector< T >& operator+= (const Quaternion< T >& rhs)\n        {\n            *this = *this + rhs;\n            return *this;\n        }\n\n        /**\n         * @brief add to the Roation of the transform\n         * @param rhs the rotation to be added\n         * @return a copy of this object\n         */\n        Transform3DVector< T >& operator-= (const Quaternion< T >& rhs)\n        {\n            *this = *this - rhs;\n            return *this;\n        }\n\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief convert and copy the transform\n         * @param rhs the transform to copy\n         * @return a copy of this object\n         */\n        Transform3DVector< T >& operator= (const Transform3D< T >& rhs)\n        {\n            this->_t3d = Transform3DVector< T > (rhs)._t3d;\n            return *this;\n        }\n#endif\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief Override the position of the transform\n         * @param rhs the new position\n         * @return a copy of this object\n         */\n        Transform3DVector< T >& operator= (const Vector3D< T >& rhs)\n        {\n            *this = Transform3DVector< T > (rhs, this->toQuaternion ());\n            return *this;\n        }\n#endif\n        /**\n         * @brief add to the position of the transform\n         * @param rhs the new position\n         * @return a copy of this object\n         */\n        Transform3DVector< T >& operator+= (const Vector3D< T >& rhs)\n        {\n            *this = *this + rhs;\n            return *this;\n        }\n\n        /**\n         * @brief subtract from the position of the transform\n         * @param rhs the new position\n         * @return a copy of this object\n         */\n        Transform3DVector< T >& operator-= (const Vector3D< T >& rhs)\n        {\n            *this = *this - rhs;\n            return *this;\n        }\n#if !defined(SWIGPYTHON)\n        /**\n         * @brief copy the transform from an eigen vector\n         * @param rhs the transform to copy\n         * @return a copy of this object\n         */\n        Transform3DVector< T >& operator= (const type& rhs)\n        {\n            this->_t3d = rhs;\n            return *this;\n        }\n#endif\n#if !defined(SWIG)\n        /**\n         * @brief implicit conversion to transform\n         */\n        operator Transform3D< T > () const { return this->toTransform3D (); }\n#endif\n\n      private:\n        type _t3d;\n    };\n\n#if defined(SWIGPYTHON)\n\n#endif\n\n#if !defined(SWIG)\n    extern template class rw::math::Transform3DVector< double >;\n    extern template class rw::math::Transform3DVector< float >;\n\n    using Transform3DVectord = Transform3DVector< double >;\n    using Transform3DVectorf = Transform3DVector< float >;\n\n#endif\n    /**@}*/\n}}    // namespace rw::math\n\n#endif    // end include guard\n", "meta": {"hexsha": "aa4c70bbc05947662a9d0268ae02fa6cf095a8b6", "size": 18604, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/Transform3DVector.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/Transform3DVector.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/math/Transform3DVector.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5857385399, "max_line_length": 99, "alphanum_fraction": 0.4975274135, "num_tokens": 4564, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.40604250802720077}}
{"text": "// Standard C++ libraries\n#include <iomanip>\n\n// Boost libraries\n#include <boost/property_tree/ptree.hpp>\n#include <boost/math/tools/roots.hpp>\n\n// Standard user-made libraries\n#include <fparameters/SpaceIterator.h>\n#include <fparameters/parameters.h>\n#include <fluminosities/thermalSync.h>\n#include <fluminosities/thermalBremss.h>\n#include <fluminosities/luminosityHadronic.h>\n#include <fluminosities/luminositySynchrotron.h>\n#include <fluminosities/blackBody.h>\n#include <fluminosities/reflection.h>\n#include <fluminosities/probexact.h>\n#include <fluminosities/luminosityNTHadronic.h>\n#include <fmath/mathFunctions.h>\n#include <fmath/physics.h>\n#include <fmath/fbisection.h>\n#include <fparameters/Dimension.h>\n#include \"absorption.h\"\n#include <fmath/RungeKutta.h>\n// Project headers\n#include \"globalVariables.h\"\n#include \"messages.h\"\n#include \"read.h\"\n#include \"thermalCompton.h\"\n#include \"thermalProcesses.h\"\n#include \"adafFunctions.h\"\n#include \"write.h\"\n\n// Namespaces\nusing namespace std;\n\nvoid localProcesses(State& st, Matrix& lumOutSy, Matrix& lumOutBr, Matrix& lumOutpp,\n\t\t\t\t\t\tVector& energies, const int flags[], Matrix& lumOut)\n{\n\tsize_t jE=0;\n\tst.photon.ps.iterate([&](const SpaceIterator& itE) {\n\t\tenergies[jE++] = itE.val(DIM_E);\n\t},{-1,0,0});\n\n\t#pragma omp parallel for\n\tfor (size_t jE=0; jE<nE; jE++) {\n\t\tdouble frequency=energies[jE]/planck;\n\t\tdouble lumSync1,lumSync2,lumBremss1,lumBremss2;\n\t\tlumSync1 = lumSync2 = lumBremss1 = lumBremss2 = 0.0;\n\t\tsize_t jR=0;\n\t\tst.photon.ps.iterate([&](const SpaceIterator& itER) {\n\t\t\tdouble r = itER.val(DIM_R);\n\t\t\tdouble thetaH = st.thetaH.get(itER);\n\t\t\tdouble rB1 = r/sqrt(paso_r);\n\t\t\tdouble rB2 = r*sqrt(paso_r);\n\t\t\t//double area = 4.0*pi*rB2*rB2*cos(thetaH);\n\t\t\tdouble area = 2.0*pi*( (height_method == 0) ? rB2*rB2*(2.0*cos(thetaH)+P2(sin(thetaH))) :\n\t\t\t\t\t\t\t\t\t2.0*rB2*height_fun(r)+(rB2*rB2-rB1*rB1) );\n\t\t\tdouble fluxToLum = area;\n\t\t\tdouble vol = volume(r);\n\t\t\tdouble emissToLum = vol*4.0*pi;\n\t\t\tdouble lumBr = 0.0;\n\t\t\tdouble lumSy = 0.0;\n\t\t\tdouble lumRJ = 0.0;\n\n\t\t\tdouble temp = st.tempElectrons.get(itER);\n\t\t\tdouble temp_i = st.tempIons.get(itER);\n\t\t\tdouble magf = st.magf.get(itER);\n\t\t\tdouble dens_i = st.denf_i.get(itER);\n\t\t\tdouble dens_e = st.denf_e.get(itER);\n\t\t\tdouble jSy = jSync(energies[jE],temp,magf,dens_e);\n\t\t\tif (flags[0]) {\n\t\t\t\tlumRJ = pi*bb(frequency,temp)*fluxToLum;\n\t\t\t\tlumSy = jSy*emissToLum;\n\t\t\t}\n\t\t\tif (flags[1])\n\t\t\t\tlumBr = jBremss(energies[jE],temp,dens_i,dens_e)*emissToLum;\n\t\t\tif (flags[2] && temp_i > 1.0e11 && frequency > 1.0e20 && frequency < 1.0e26) {\n\t\t\t\tdouble jpp = luminosityHadronic(energies[jE],dens_i,temp_i);\n\t\t\t\tlumOutpp[jE][jR] = jpp*vol;\n\t\t\t}\n            if (flags[0]) {\n\t\t\t\tif (jR > 0)\n\t\t\t\t\tlumSync2 = min((1.0-scattAA[jR-1][jR])*lumSync1+lumSy,lumRJ);\n\t\t\t\telse \n\t\t\t\t\tlumSync2 = min(lumSy,lumRJ);\n\t\t\t\tif (lumSync2 > lumSync1)\n\t\t\t\t\tlumOutSy[jE][jR] = lumSync2-lumSync1;\n\t\t\t\tlumSync1 = lumSync2;\n            }\n\t\t\t\n\t\t\tif (flags[1]) {\n\t\t\t\tif (flags[0] && frequency < 1.0e14) {\n\t\t\t\t\tif (lumBr > lumRJ)\n\t\t\t\t\t\tlumBr = 0.0;\n\t\t\t\t}\n\t\t\t\tlumOutBr[jE][jR]=lumBr;\n\t\t\t}\n\t\t\t\n\t\t\tlumOut[jE][jR] = lumOutSy[jE][jR]+lumOutBr[jE][jR]+lumOutpp[jE][jR];\n\t\t\tjR++;\n\t\t},{jE,-1,0});\n\t}\n}\n\nvoid localProcesses2(State& st, Matrix& lumOutSy, Matrix& lumOutBr,\n\t\t\t\t\t\tVector& energies, const int flags[], Matrix& lumOut)\n{\n\tsize_t jE=0;\n\tst.photon.ps.iterate([&](const SpaceIterator& itE) {\n\t\tenergies[jE++] = itE.val(DIM_E);\n\t},{-1,0,0});\n\n\t#pragma omp parallel for\n\tfor (size_t jE=0;jE<nE;jE++) {\n\t\tsize_t jR=0;\n\t\tst.photon.ps.iterate([&](const SpaceIterator& itER) {\n\t\t\tdouble r = itER.val(DIM_R);\n\t\t\tdouble rB2 = r*sqrt(paso_r);\n\t\t\tdouble rB1 = rB2/paso_r;\n\t\t\tdouble temp_e = st.tempElectrons.get(itER);\n\t\t\tdouble temp_i = st.tempIons.get(itER);\n\t\t\tdouble magf = st.magf.get(itER);\n\t\t\tdouble dens_i = st.denf_i.get(itER);\n\t\t\tdouble dens_e = st.denf_e.get(itER);\n\t\t\tdouble xSy,xBr;\n\t\t\tdouble unrEnergy = energies[jE]/redshift_to_inf[jR];\n\t\t\tunrEnergy = energies[jE];\n\t\t\txSy = xBr = 0.0;\n\t\t\tif (flags[0])\n\t\t\t\txSy = jSync(unrEnergy,temp_e,magf,dens_e)*4.0*pi;\n\t\t\tif (flags[1])\n\t\t\t\txBr = jBremss(unrEnergy,temp_e,dens_i,dens_e)*4.0*pi;\n\t\t\t\n\t\t\tSpaceCoord psc = {jE, jR, 0};\n\t\t\tdouble b_nu = bb(unrEnergy/planck,temp_e);\n\t\t\tdouble kappa = (xSy+xBr)/(4.0*pi*b_nu);\n\t\t\tdouble tau = 0.5*sqrt(pi)*kappa*height_fun(r);\n\t\t\tdouble fluxSy = (2.0*sqrt(3.0)*tau > 1.0e-9) ? \n\t\t\t\t\t\t\t2.0*pi/sqrt(3.0)*b_nu*(1.0-exp(-2.0*sqrt(3.0)*tau)) :\n\t\t\t\t\t\t\t0.5*sqrt(pi)*xSy*height_fun(r);\n\t\t\tdouble fluxBr = (2.0*sqrt(3.0)*tau < 1.0e-3) ? 0.5*sqrt(pi)*xBr*height_fun(r) : 0.0;\n\t\t\t\t\t\t\t\n\t\t\tlumOutSy[jE][jR] = 2.0 * pi*(rB2*rB2-rB1*rB1) * fluxSy;\n\t\t\tlumOutBr[jE][jR] = 2.0 * pi*(rB2*rB2-rB1*rB1) * fluxBr;\n\t\t\tlumOut[jE][jR] = lumOutSy[jE][jR] + lumOutBr[jE][jR];\n\t\t\tjR++;\n\t\t},{jE,-1,0});\n\t}\n}\n\nvoid localProcesses3(State& st, Matrix& lumOutSy, Matrix& lumOutBr, Matrix& lumOutpp,\n\t\t\t\t\t\tVector& energies, const int flags[], Matrix& lumOut)\n{\n\tsize_t jE=0;\n\tst.photon.ps.iterate([&](const SpaceIterator& itE) {\n\t\tenergies[jE++] = itE.val(DIM_E);\n\t},{-1,0,0});\n\t\n\t#pragma omp parallel for\n\tfor (int jE=0;jE<nE;jE++) {\n\t\tdouble frequency=energies[jE]/planck;\n\t\tsize_t jR = 0.0;\n\t\tst.photon.ps.iterate([&](const SpaceIterator& itR) {\n\t\t\tdouble r = itR.val(DIM_R);\n\t\t\tdouble magf = st.magf.get(itR);\n\t\t\tdouble temp = st.tempElectrons.get(itR);\n\t\t\tdouble dens_e = st.denf_e.get(itR);\n\t\t\tdouble dens_i = st.denf_i.get(itR);\n\t\t\t\n\t\t\tdouble jv_th = jSync(energies[jE],temp,magf,dens_e)+jBremss(energies[jE],temp,dens_i,dens_e);\n\t\t\t//jv_th *= 4*pi;\n\t\t\tdouble jv_pl = luminositySynchrotron2(energies[jE],st.ntElectron,itR,magf)/frequency/(4*pi);\n\t\t\tdouble av_th = jv_th / bb(frequency,temp);\n\t\t\tSpaceCoord psc = {jE,jR,0};\n\t\t\tdouble av_pl = ssaAbsorptionCoeff(energies[jE],magf,st.ntElectron,psc);\n\t\t\t\n\t\t\t//double height = (r/schwRadius > 15) ? r*costhetaH(r) : height_fun(r);\n\t\t\tdouble height = r*costhetaH(r);\n\t\t\tdouble Sv = (jv_th+jv_pl)/(av_th+av_pl);\n\t\t\t//double Sv = jv_pl/(av_th+av_pl);\n\t\t\tdouble Inup = (frequency < 1.0e14) ? Sv * (1.0-exp(-2.0*height*(av_th+av_pl))) :\n\t\t\t\t\t\t\t2.0*height*(jv_th+jv_pl);\n\t\t\t//\t\t\t\t2.0*height*jv_pl;\n\t\t\tdouble flux = 2.0*pi*r*r*(paso_r-1.0)*Inup;\n\t\t\tif (r/schwRadius <= 15)\n\t\t\t\tlumOutpp[jE][jR] = 4*pi*flux* (1.0-scattAA[jR][jR]);\n\t\t\telse\n\t\t\t\tlumOutBr[jE][jR] = 4*pi*flux* (1.0-scattAA[jR][jR]);\n\t\t\tlumOut[jE][jR] = lumOutpp[jE][jR]+lumOutBr[jE][jR];\n\t\t\tjR++;\n\t\t},{jE,-1,0});\n\t}\n}\n\n\nvoid reflectedSpectrum(Matrix lumOut, Matrix& lumOutRefl, Vector energies,\n\t\t\t\t\t\tdouble pasoE)\n{\n\tsize_t numInt = 40;\n\tfor (size_t jE=nE/2;jE<nE;jE++) {\n\t\tdouble freq = energies[jE]/planck;\n\t\tdouble x = energies[jE]/(electronMass*cLight2);\n\t\tdouble xMax = 1.0e2;\n\t\tfor (size_t jRcd=0;jRcd<nRcd;jRcd++) {\n\t\t\tdouble freq0,pasoFreq,aux1;\n\t\t\tint logicalInt = 1;\n\t\t\tif (x > 0.03 && x < xMax) {\n\t\t\t\tfreq0 = energies[jE]/planck;\n\t\t\t\tpasoFreq = pow(xMax/x,1.0/(numInt+1));\n\t\t\t\taux1 = 0.0;\n\t\t\t} else if (x <= 0.03) {\n\t\t\t\tfreq0 = 0.03*electronMass*cLight2/planck;\n\t\t\t\tpasoFreq = pow(xMax/0.03,1.0/(numInt+1));\n\t\t\t\taux1 = greenDeltaFunc(x);\n\t\t\t} else { logicalInt = 0; aux1 = 0.0; }\n\t\t\t\n\t\t\tdouble lum = 0.0;\n\t\t\tif (logicalInt == 1) {\n\t\t\t\tfor (size_t jjFreq=0;jjFreq<numInt;jjFreq++) {\n\t\t\t\t\tdouble dfreq0 = freq0*(sqrt(pasoFreq)-pow(pasoFreq,-0.5));\n\t\t\t\t\tdouble lumInc = lumShellInc(freq0,jE,jRcd,lumOut,reachAD,energies,nR,redshift_RIAF_to_CD);\n\t\t\t\t\tdouble green = greenFuncRefl(freq,freq0);\n\t\t\t\t\tlum += green*lumInc*dfreq0*(freq/freq0);\n\t\t\t\t\tfreq0 *= pasoFreq;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlumOutRefl[jE][jRcd] =\n\t\t\t\t\tlum + aux1*lumShellInc(freq,jE,jRcd,lumOut,reachAD,energies,nR,redshift_RIAF_to_CD);\n\t\t\t\t\t\n\t\t}\n\t}\n}\n\nvoid coldDiskLuminosity(State& st, Matrix lumOut, Matrix& lumOutRefl, \n\t\t\t\t\t\tMatrix& lumOutCD, Vector energies)\n{\n\tmatrixInit(lumOutCD,nE,nRcd,0.0);\n\tmatrixInit(lumOutRefl,nE,nRcd,0.0);\n\n\t//#pragma omp parallel for\n\tfor (int jRcd=0;jRcd<nRcd;jRcd++) {\n\t\tdouble rCd = st.photon.ps[DIM_Rcd][jRcd];\n\t\t\n\t\tdouble lj1 = rCd/sqrt(paso_rCD);\n\t\tdouble lj2 = rCd*sqrt(paso_rCD);\n\t\tdouble area = 2.0*pi*(lj2*lj2-lj1*lj1);\n\t\tdouble aux1 = auxCD(rCd);\n\t\tdouble aux2 = 0.0;\n\t\t\n\t\tdouble pasoE = pow(st.photon.emax()/st.photon.emin(),1.0/(nE-1));\n\t\t//reflectedSpectrum(lumOut,lumOutRefl,energies,pasoE);\n\n\t\tfor (size_t jjE=0;jjE<nE;jjE++) {\n\t\t\tdouble frequency = st.photon.ps[DIM_E][jjE]/planck;\n\t\t\tdouble dfreq = frequency*(sqrt(pasoE)-1.0/sqrt(pasoE));\n\t\t\tdouble lumInc = 0.0;\n\t\t\tfor (size_t kR=0;kR<nR;kR++) {\n\t\t\t\tlumInc += (lumOut[jjE][kR]*reachAD[kR][jRcd] * pow(redshift_RIAF_to_CD[kR][jRcd],2));\n\t\t\t}\n\t\t\taux2 += ((lumInc - lumOutRefl[jjE][jRcd])*dfreq);\n\t\t}\n\t\tdouble aux = aux1+aux2;\n\t\tdouble temp = pow(aux/area/ stefanBoltzmann,0.25);\n\t\tcout << \"RadiusCD = \" << rCd/schwRadius << \" Temperature [K] = \" << scientific << temp << endl;\n\n\t\tfor(size_t jE=0;jE<nE;jE++) {\n\t\t\tdouble frequency = st.photon.ps[DIM_E][jE]/planck;\n\t\t\tlumOutCD[jE][jRcd] = area * pi * bb(frequency,1.7*temp)/pow(1.7,4);\n\t\t};\n\t}\n}\n\nvoid localCompton(const State& st, Matrix& lumOut, Matrix& lumOutIC, Vector energies)\n{\n\tMatrix lumOutLocal;\n\tmatrixInitCopy(lumOutLocal,nE,nR,lumOut);\n\t\n\tVector comptonProbVec(nTempCompton*nNuPrimCompton*nNuCompton,0.0);\n\tif (calculateComptonRedMatrix) comptonMatrix();\n\tvectorRead(\"comptonProbMatrix.dat\",comptonProbVec,comptonProbVec.size());\n\t\n\t// PARA CADA CELDA\n\tsize_t jR=0;\n\tst.photon.ps.iterate([&](const SpaceIterator& itR) {\n\n\t\tdouble temp = st.tempElectrons.get(itR);\n\t\tdouble normtemp = boltzmann*temp/(electronMass*cLight2);\n\t\tif (normtemp >= tempMinCompton && normtemp < tempMaxCompton) {\n\t\t\t\n\t\t\tdouble eDens = st.denf_e.get(itR);\n\t\t\tdouble r = itR.val(DIM_R);\n\t\t\tdouble vol = volume(r);\n\t\t\t\n\t\t\tdouble tescap = 0.5*sqrt(pi)*height_fun(r)/cLight;\n\t\t\tVector nOld(nE,0.0),nNew(nE,0.0),nWithoutCompton(nE,0.0);\n\t\t\tdouble tauu = eDens*thomson*height_fun(r);\n\t\t\t\n\t\t\tfor (size_t jE=0;jE<nE;jE++) {\n\t\t\t\tnOld[jE] = lumOut[jE][jR]/vol / energies[jE] * tescap;\n\t\t\t\tnWithoutCompton[jE] = lumOut[jE][jR]/vol / energies[jE] * tescap;\n\t\t\t}\n\t\t\t\n\t\t\tdouble res = 0.0;\n\t\t\tsize_t it=1;\n\t\t\tint cond = 1;\n\t\t\tdo {\n\t\t\t\tcout << \"jR = \" << jR << \"\\t Iteration number = \" << it << endl;\n\t\t\t\tcond = 0;\n\t\t\t\t\n\t\t\t\tfor (size_t jE=0;jE<nE;jE++) {\n\t\t\t\t\tdouble frequency = energies[jE]/planck;\n\t\t\t\t\tif (frequency > nuMinCompton && frequency < nuMaxCompton) {\n\t\t\t\t\t\tdouble frequency = energies[jE]/planck;\n\t\t\t\t\t\tdouble rateScatt = rateThermal(normtemp,frequency)*eDens;\n\t\t\t\t\t\tdouble denom = 1.0/tescap + rateScatt;\n\t\t\t\t\t\tdouble integ = comptonNewLocal2(nOld,normtemp,jE,energies);\n\t\t\t\t\t\tnNew[jE] = (1.0/denom) * integ * eDens;\n\t\t\t\t\t\tif (nNew[jE] > nWithoutCompton[jE]) cond = 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfor (size_t jE=0;jE<nE;jE++) {\n\t\t\t\t\tnOld[jE] = nNew[jE];\n\t\t\t\t\tlumOut[jE][jR] += nNew[jE]*energies[jE]*vol / tescap;\n\t\t\t\t\tlumOutIC[jE][jR] = lumOut[jE][jR]-lumOutLocal[jE][jR];\n\t\t\t\t}\n\t\t\t\tcout << \"Condition = \" << cond << endl;\n\t\t\t\t++it;\n\t\t\t} while (cond == 1 && it < 40);\n\t\t}\n\t\tjR++;\n\t},{0,-1,0});\n\t\n\tshow_message(msgEnd,Module_thermalCompton);\n}\n\nvoid thermalCompton2(State& st, Matrix& lumOut, Matrix& lumOutBr, Matrix& lumInICm,\n\t\t\t\t\t\tMatrix& lumOutIC, Matrix& lumOutIC_CD,\n\t\t\t\t\t\tMatrix& lumOutIC_Br, Vector energies, int processesFlags[])\n{\n\tshow_message(msgStart,Module_thermalCompton);\n\t\n\tVector tempVec(nTempCompton,0.0);\n\tVector nuPrimVec(nNuPrimCompton,0.0);\n\tVector nuVec(nNuCompton,0.0);\n\tVector comptonProbVec(nTempCompton*nNuPrimCompton*nNuCompton,0.0);\n\t\n\tif (comptonMethod == 0) {\n\t\tif (calculateComptonRedMatrix) comptonMatrix2();\n\t\tvectorRead(\"comptonProbMatrix2.dat\",comptonProbVec,comptonProbVec.size());\n\t\tvectorRead(\"tempComptonVec.dat\",tempVec,tempVec.size());\n\t} else {\n\t\tif (calculateComptonRedMatrix) comptonMatrix();\n\t\tvectorRead(\"comptonProbMatrix.dat\",comptonProbVec,comptonProbVec.size());\n\t}\n\n\tvectorRead(\"nuPrimComptonVec.dat\",nuPrimVec,nuPrimVec.size());\n\tvectorRead(\"nuComptonVec.dat\",nuVec,nuVec.size());\n\t\n\tMatrix lumOutLocal,lumOutLocal_Br,lumOutCD,lumOutRefl,lumOutIC_CD_copy, lumOutIC_Br_copy;\n\tmatrixInit(lumOutCD, nE, nRcd, 0.0);\n\tmatrixInit(lumOutRefl, nE, nRcd, 0.0);\n\tmatrixInit(lumOutIC, nE, nR, 0.0);\n\tmatrixInit(lumOutIC_CD, nE, nR, 0.0);\n\tmatrixInit(lumOutIC_CD_copy, nE, nR, 0.0);\n\tmatrixInit(lumOutIC_Br_copy, nE, nR, 0.0);\n\tVector lumInIC(nE, 0.0);\n\tVector lumInIC_CD(nE, 0.0);\n\tVector lumInIC_Br(nE, 0.0);\n\tmatrixInitCopy(lumOutLocal, nE, nR, lumOut);\n\tVector p(nR*nE*nE, 0.0);\n\t\n\tVector a(nR, 1.0);\n\tif (comptonMethod == 1)\n\t\tcNew(st, p, a);\n\t\t//cNew(st, p, redshift_to_inf);\n\n\tif (processesFlags[3])\n\t\tcoldDiskLuminosity(st, lumOut, lumOutRefl, lumOutCD, energies);\n\t\t\n\tdouble res;\t\t// Residual.\n\tsize_t it=1;\t// Iterations.\n\tdo {\n\t\tcout << \"Iteration number = \" << it << endl;\n\t\tres=0.0;\n\t\t\n\t\t// To compute the residuals.\n\t\tVector lumOld(nE,0.0);\n\t\tfor (size_t jE=0;jE<nE;jE++) {\n\t\t\tfor (size_t jR=0;jR<nR;jR++) {\n\t\t\t\tlumOld[jE] += lumOut[jE][jR] + lumOutIC_CD[jE][jR];\n\t\t\t}\n\t\t\tif (processesFlags[3]) {\n\t\t\t\tfor (size_t jRcd=0;jRcd<nRcd;jRcd++) {\n\t\t\t\t\tlumOld[jE] += lumOutCD[jE][jRcd] + lumOutRefl[jE][jRcd];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tmatrixInit(lumOutIC,nE,nR,0.0);\n\t\tmatrixInit(lumOutIC_Br,nE,nR,0.0);\n\t\tmatrixInit(lumOutIC_CD,nE,nR,0.0);\n\t\t\n\t\t// For each shell.\n\t\tsize_t jR=0;\n\t\tst.photon.ps.iterate([&](const SpaceIterator& itR) {\n\t\t\tdouble normtemp = boltzmann*st.tempElectrons.get(itR)/(electronMass*cLight2);\n\t\t\t// Compute the scattered luminosity.\n\t\t\tfill(lumInIC.begin(),lumInIC.end(),0.0);\n\t\t\tfill(lumInIC_CD.begin(),lumInIC_CD.end(),0.0);\n\t\t\tfill(lumInIC_Br.begin(),lumInIC_Br.end(),0.0);\n\t\t\t\n\t\t\tfor (size_t jjE=0;jjE<nE;jjE++) {\n\t\t\t\tfor (size_t jjR=0;jjR<nR;jjR++) {\n\t\t\t\t\tVector lumVec(nE,0.0);\n\t\t\t\t\t//lumInIC[jjE] += scattAA[jjR][jR] * lumOut[jjE][jjR] * pow(redshift[jjR][jR],2);\n\t\t\t\t\tfor (size_t jjjE=0;jjjE<nE;jjjE++)\n\t\t\t\t\t\tlumVec[jjjE] = lumOut[jjjE][jjR];\n\t\t\t\t\t\t\n\t\t\t\t\tdouble localEnergy = energies[jjE] / redshift[jjR][jR];\n\t\t\t\t\tlumInIC[jjE] += scattAA[jjR][jR] * pow(redshift[jjR][jR],2) \n\t\t\t\t\t\t\t\t\t\t* lumInterp(lumVec,energies,jjE,nE,localEnergy);\n\t\t\t\t}\n\t\t\t\tfor (size_t jjR=0;jjR<nR;jjR++) {\n\t\t\t\t\tVector lumVec(nE,0.0);\n\t\t\t\t\t//lumInIC[jjE] += scattAA[jjR][jR] * lumOut[jjE][jjR] * pow(redshift[jjR][jR],2);\n\t\t\t\t\tfor (size_t jjjE=0;jjjE<nE;jjjE++)\n\t\t\t\t\t\tlumVec[jjjE] = lumOutBr[jjjE][jjR] + lumOutIC_Br_copy[jjjE][jjR];\n\t\t\t\t\t\t\n\t\t\t\t\tdouble localEnergy = energies[jjE] / redshift[jjR][jR];\n\t\t\t\t\tlumInIC_Br[jjE] += scattAA[jjR][jR] * pow(redshift[jjR][jR],2) \n\t\t\t\t\t\t\t\t\t\t* lumInterp(lumVec,energies,jjE,nE,localEnergy);\n\t\t\t\t}\n\t\t\t\tif (processesFlags[3]) {\n\t\t\t\t\tfor (size_t jRcd=0;jRcd<nRcd;jRcd++) {\n\t\t\t\t\t\tVector lumVec(nE,0.0);\n\t\t\t\t\t\tfor (size_t jjjE=0;jjjE<nE;jjjE++)\n\t\t\t\t\t\t\tlumVec[jjjE] = lumOutCD[jjjE][jRcd]+lumOutRefl[jjjE][jRcd];\n\t\t\t\t\t\t\n\t\t\t\t\t\tdouble localEnergy = energies[jjE] / redshift_CD_to_RIAF[jRcd][jR];\n\t\t\t\t\t\tlumInIC_CD[jjE] += scattDA[jRcd][jR] * pow(redshift_CD_to_RIAF[jRcd][jR],2) *\n\t\t\t\t\t\t\t\t\t\t\tlumInterp(lumVec,energies,jjE,nE,localEnergy);\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\tfor (size_t jjR=0;jjR<nR;jjR++) {\n\t\t\t\t\t\tVector lumVec(nE,0.0);\n\t\t\t\t\t\tfor (size_t jjjE=0;jjjE<nE;jjjE++)\n\t\t\t\t\t\t\tlumVec[jjjE] = lumOutIC_CD_copy[jjjE][jjR];\n\t\t\t\t\t\t\n\t\t\t\t\t\tdouble localEnergy = energies[jjE] / redshift[jjR][jR];\n\t\t\t\t\t\tlumInIC_CD[jjE] += scattAA[jjR][jR] * pow(redshift[jjR][jR],2) \n\t\t\t\t\t\t\t\t\t\t* lumInterp(lumVec,energies,jjE,nE,localEnergy);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlumInICm[jjE][jR] = lumInIC[jjE] + lumInIC_CD[jjE];\n\t\t\t}\n\t\t\tif (normtemp > tempMinCompton && normtemp < tempMaxCompton) {\n\t\t\t\t\n\t\t\t\tfor (size_t jE=0;jE<nE;jE++) {\n\t\t\t\t\tdouble frequency = energies[jE]/planck;\n\t\t\t\t\tif (comptonMethod == 3) {\n\t\t\t\t\t\tif (it == 1) \n\t\t\t\t\t\t\tcomptonNewNewNewPruebaVector(jR,energies,jE,p,normtemp);\n\t\t\t\t\t\tif (frequency > nuMinCompton && frequency < nuMaxCompton)\n\t\t\t\t\t\t\tlumOutIC[jE][jR] = compton(p,lumInIC,jR,energies,jE);\n\t\t\t\t\t\t\tlumOutIC_CD[jE][jR] = compton(p,lumInIC_CD,jR,energies,jE);\n\t\t\t\t\t\t\tlumOutIC_Br[jE][jR] = compton(p,lumInIC_Br,jR,energies,jE);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (frequency > nuMinCompton && frequency < nuMaxCompton)\n\t\t\t\t\t\t\tlumOutIC[jE][jR] = compton(p,lumInIC,jR,energies,jE);\n\t\t\t\t\t\t\tlumOutIC_CD[jE][jR] = compton(p,lumInIC_CD,jR,energies,jE);\n\t\t\t\t\t\t\tlumOutIC_Br[jE][jR] = compton(p,lumInIC_Br,jR,energies,jE);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tjR++;\n\t\t},{0,-1,0});\n\t\t\n\t\tdouble pasoNuPrim = pow(energies[nE-1]/energies[0],1.0/(nE-1));\n\t\tdouble nPhNS = 0.0;\n\t\tdouble nPhBS = 0.0;\n\t\tdouble nPhAS = 0.0;\n\t\tfor (size_t jE=0;jE<nE;jE++) {\n\t\t\tdouble dNu = energies[jE]/planck * (sqrt(pasoNuPrim)-1.0/sqrt(pasoNuPrim));\n\t\t\tdouble lumNew = 0.0;\n\t\t\tfor (size_t jR=0;jR<nR;jR++) {\n\t\t\t\tnPhNS += lumOutLocal[jE][jR]/energies[jE] * dNu;\n\t\t\t\tnPhBS += lumInICm[jE][jR]/energies[jE] * dNu;\n\t\t\t\tnPhAS += lumOutIC[jE][jR]/energies[jE] * dNu;\n\t\t\t\tdouble lumAux = lumOutLocal[jE][jR]+lumOutIC[jE][jR];\n\t\t\t\tlumNew += (lumAux + lumOutIC_CD[jE][jR]);\n\t\t\t\tlumOut[jE][jR] = lumAux;\n\t\t\t\tlumOutIC_CD_copy[jE][jR] = lumOutIC_CD[jE][jR];\n\t\t\t\tlumOutIC_Br_copy[jE][jR] = lumOutIC_Br[jE][jR];\n\t\t\t}\n\t\t\tfor (size_t jRcd=0;jRcd<nRcd;jRcd++) {\n\t\t\t\tlumNew += (lumOutCD[jE][jRcd]+lumOutRefl[jE][jRcd]);\n\t\t\t}\n\t\t\tif (lumNew > 0.0 && lumOld[jE] > 0.0)\n\t\t\t\tres += abs(log10(lumNew/lumOld[jE]));\n\t\t}\n\t\tcout << endl;\n\t\tcout << \"Total photons non-scattered per unit time = \" \n\t\t\t\t\t\t<< nPhNS << \" s^-1\" << endl;\n\t\tcout << \"Total photons scattered per unit time, before scattering = \" \n\t\t\t\t\t\t << nPhBS << \" s^-1\" << endl;\n\t\tcout << \"Total photons scattered per unit time, after scattering = \" \n\t\t\t\t\t\t << nPhAS << \" s^-1\" << endl;\n\t\tcout << endl;\n\t\t\n\t\tres /= nE;\n\t\tcout << \"Residuo = \" << res << endl;\n\t\t++it;\n\t} while (res > 1.0e-3 && it < 100);\n\t\n\tfor (size_t jE=0;jE<nE;jE++)\n\t\tfor (size_t jR=0;jR<nR;jR++)\n\t\t\tlumOut[jE][jR] += lumOutIC_CD[jE][jR];\n\n\tshow_message(msgEnd,Module_thermalCompton);\n}\n\n/*\nvoid thermalCompton(State& st, Matrix& lumOut, Matrix& lumInICm, Matrix& lumOutIC, Vector energies, \n\t\t\t\t\t\tint processesFlags[])\n{\n\tshow_message(msgStart,Module_thermalCompton);\n\tVector tempVec(nTempCompton,0.0);\n\tVector nuPrimVec(nNuPrimCompton,0.0);\n\tVector nuVec(nNuCompton,0.0);\n\tVector comptonProbVec(nTempCompton*nNuPrimCompton*nNuCompton,0.0);\n\t\n\tif (comptonMethod == 0) {\n\t\tif (calculateComptonRedMatrix) comptonMatrix2();\n\t\tvectorRead(\"comptonProbMatrix2.dat\",comptonProbVec,comptonProbVec.size());\n\t\tvectorRead(\"tempComptonVec.dat\",tempVec,tempVec.size());\n\t} else {\n\t\tif (calculateComptonRedMatrix) comptonMatrix();\n\t\tvectorRead(\"comptonProbMatrix.dat\",comptonProbVec,comptonProbVec.size());\n\t}\n\n\tvectorRead(\"nuPrimComptonVec.dat\",nuPrimVec,nuPrimVec.size());\n\tvectorRead(\"nuComptonVec.dat\",nuVec,nuVec.size());\n\t\n\tMatrix lumOutCD,lumOutRefl,lumOutIC_local;\n\tmatrixInit(lumOutCD,nE,nRcd,0.0);\n\tmatrixInit(lumOutRefl,nE,nRcd,0.0);\n\tVector lumInIC(nE,0.0);\n\tVector lumBeforeCompton(nE,0.0);\n\tmatrixInitCopy(lumOutIC_local,nE,nR,lumOut);\n\tVector p(nR*nE*nE,0.0);\n\t\n\tfor (size_t jE=0;jE<nE;jE++)\n\t\tfor (size_t jR=0;jR<nR;jR++)\n\t\t\tlumBeforeCompton[jE] += lumOut[jE][jR];\n\t\n\tif (comptonMethod == 1) cNew(st,p,redshift_to_inf);\n\t\n\tint cond = 1;\t\t// Residual.\n\tsize_t it=1;\t// Iterations.\n\tdo {\n\t\tcout << \"Iteration number = \" << it << endl;\n\t\tcond = 0;\n\t\tif (processesFlags[3])\n\t\t\tcoldDiskLuminosity(st,lumOut,lumOutRefl,lumOutCD,energies);\n\n\t\tVector lumCompton(nE,0.0);\n\t\t\n\t\t// For each shell.\n\t\tsize_t jR=0;\n\t\tst.photon.ps.iterate([&](const SpaceIterator& itR) {\n\t\t\tdouble normtemp = boltzmann*st.tempElectrons.get(itR)/(electronMass*cLight2);\n\t\t\t// Compute the scattered luminosity.\n\t\t\tfill(lumInIC.begin(),lumInIC.end(),0.0);\n\t\t\tfor (size_t jjE=0;jjE<nE;jjE++) {\n\t\t\t\t\n\t\t\t\tfor (size_t jjR=0;jjR<nR;jjR++)\n\t\t\t\t\tlumInIC[jjE] += scattAA[jjR][jR] * lumOutIC_local[jjE][jjR];\n\t\t\t\t\n\t\t\t\tif (processesFlags[3]) {\n\t\t\t\t\tfor (size_t jRcd=0;jRcd<nRcd;jRcd++)\n\t\t\t\t\t\tlumInIC[jjE] += scattDA[jRcd][jR] * \n\t\t\t\t\t\t\t\t\t\t\t(lumOutCD[jjE][jRcd]+lumOutRefl[jjE][jRcd]);\n\t\t\t\t}\n\t\t\t\tlumInICm[jjE][jR] = lumInIC[jjE];\n\t\t\t}\n\n\t\t\tfor (size_t jE=0;jE<nE;jE++)\n\t\t\t\tlumOutIC_local[jE][jR] = 0.0;\n\n\t\t\tif (normtemp > tempMinCompton && normtemp < tempMaxCompton) {\n\t\t\t\tdouble A = 1.0+4.0*normtemp*(1.0+4.0*normtemp);\n\t\t\t\tVector unrEnergies_vec(nE);\n\t\t\t\tfor (size_t jE=0;jE<nE;jE++)\n\t\t\t\t\tunrEnergies_vec[jE] = energies[jE]/redshift_to_inf[jR];\n\t\t\t\t\n\t\t\t\tfor (size_t jE=0;jE<nE;jE++) {\n\t\t\t\t\tdouble frequency = energies[jE]/planck;\n\t\t\t\t\tdouble unrFrequency = unrEnergies_vec[jE]/planck;\n\t\t\t\t\tif (unrFrequency > nuMinCompton && unrFrequency < nuMaxCompton) {\n\t\t\t\t\t\tlumOutIC_local[jE][jR] = compton(p,lumInIC,jR,unrEnergies_vec,jE);\n\t\t\t\t\t\tlumCompton[jE] += lumOutIC_local[jE][jR];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tjR++;\n\t\t},{0,-1,0});\n\t\t\n\t\tfor (size_t jE=0;jE<nE;jE++)\n\t\t\tif (lumCompton[jE] > 0.01*lumBeforeCompton[jE]) cond = 1;\n\t\t\n\t\t\n\t\tdouble pasoNuPrim = pow(energies[nE-1]/energies[0],1.0/(nE-1));\n\t\tdouble nPhNS = 0.0;\n\t\tdouble nPhBS = 0.0;\n\t\tdouble nPhAS = 0.0;\n\t\tfor (size_t jE=0;jE<nE;jE++) {\n\t\t\tdouble dNu = energies[jE]/planck * (sqrt(pasoNuPrim)-1.0/sqrt(pasoNuPrim));\n\t\t\tfor (size_t jR=0;jR<nR;jR++) {\n\t\t\t\tnPhBS += lumInICm[jE][jR]/energies[jE] * dNu;\n\t\t\t\tnPhAS += lumOutIC_local[jE][jR]/energies[jE] * dNu;\n\t\t\t\tlumOut[jE][jR] += lumOutIC_local[jE][jR];\n\t\t\t\tlumOutIC[jE][jR] += lumOutIC_local[jE][jR];\n\t\t\t}\n\t\t}\n\t\tcout << endl;\n\t\tcout << \"Total photons scattered per unit time, before scattering = \" \n\t\t\t\t\t << nPhBS << \" s^-1\" << endl;\n\t\tcout << \"Total photons scattered per unit time, after scattering = \" \n\t\t\t\t\t << nPhAS << \" s^-1\" << endl;\n\t\tcout << endl;\n\t\t\n\t\tcout << \"Condition = \" << cond << endl;\n\t\t++it;\n\t} while (cond);\n\tshow_message(msgEnd,Module_thermalCompton);\n}\n*/\n\nvoid writeLuminosities(State& st, Vector energies, Matrix lumOutSy, Matrix lumOutBr,\n\t\t\t\t\t\tMatrix lumOutpp, Matrix lumInICm, Matrix lumOutIC, Matrix lumOutIC_CD,\n\t\t\t\t\t\tMatrix lumOutIC_Br,\n\t\t\t\t\t\tMatrix lumOut, Matrix lumOutCD, Matrix lumOutRefl, const string& filename)\n{\n\tofstream file1,file2;\n\tofstream fileCell;\n\tfile1.open(filename.c_str(),ios::out);\n\tfile2.open(\"lumRadius.dat\",ios::out);\n\tfileCell.open(\"lumCell.txt\",ios::out);\n\t\n\tdouble lumSy,lumBr,lumICin,lumIC,lumIC_CD,lumIC_Br,lumpp,lumTot,lumCD,lumRefl;\n\tdouble lumThermalTot = 0.0;\n\tdouble lumThermalTotRIAF = 0.0;\n\tdouble pasoF = pow(energies[nE-1]/energies[0],1.0/(nE-1));\n\tfor (size_t jE=0;jE<nE;jE++) {\n\t\tdouble E = energies[jE];\n\t\tdouble frequency = E/planck;\n\t\tdouble energyEV = energies[jE]/EV_TO_ERG;\n\t\tlumSy = lumBr = lumICin = lumIC = lumIC_CD = lumIC_Br = lumpp = lumTot = lumCD = lumRefl = 0.0;\n\t\tfor (size_t jR=0;jR<nR;jR++) {\n\t\t\tVector lumSyVec(nE,0.0), lumBrVec(nE,0.0), lumICinVec(nE,0.0), lumICVec(nE,0.0),\n\t\t\t\t\tlumIC_CDVec(nE,0.0), lumIC_BrVec(nE,0.0), lumppVec(nE,0.0), lumOutVec(nE,0.0);\n\t\t\tfor (size_t jjE=0;jjE<nE;jjE++) {\n\t\t\t\tlumSyVec[jjE] = lumOutSy[jjE][jR];\n\t\t\t\tlumBrVec[jjE] = lumOutBr[jjE][jR];\n\t\t\t\tlumICinVec[jjE] = lumInICm[jjE][jR];\n\t\t\t\tlumICVec[jjE] = lumOutIC[jjE][jR];\n\t\t\t\tlumIC_CDVec[jjE] = lumOutIC_CD[jjE][jR];\n\t\t\t\tlumIC_BrVec[jjE] = lumOutIC_Br[jjE][jR];\n\t\t\t\tlumppVec[jjE] = lumOutpp[jjE][jR];\n\t\t\t\tlumOutVec[jjE] = lumOut[jjE][jR];\n\t\t\t}\n\t\t\tdouble localEnergy = energies[jE]/redshift_to_inf[jR];\n\t\t\tlumSy += lumInterp(lumSyVec,energies,jE,nE,localEnergy) * pow(redshift_to_inf[jR],3) * escapeAi[jR];\n\t\t\tlumBr += lumInterp(lumBrVec,energies,jE,nE,localEnergy) * pow(redshift_to_inf[jR],3) * escapeAi[jR];\n\t\t\tlumICin += lumInterp(lumICinVec,energies,jE,nE,localEnergy) * pow(redshift_to_inf[jR],3) * escapeAi[jR];\n\t\t\tlumIC += lumInterp(lumICVec,energies,jE,nE,localEnergy) * pow(redshift_to_inf[jR],3) * escapeAi[jR];\n\t\t\tlumIC_CD += lumInterp(lumIC_CDVec,energies,jE,nE,localEnergy) * pow(redshift_to_inf[jR],3) * escapeAi[jR];\n\t\t\tlumIC_Br += lumInterp(lumIC_BrVec,energies,jE,nE,localEnergy) * pow(redshift_to_inf[jR],3) * escapeAi[jR];\n\t\t\t\n\t\t\tlumpp += lumInterp(lumppVec,energies,jE,nE,localEnergy) * pow(redshift_to_inf[jR],3) * escapeAi[jR];\n\t\t\tlumTot += lumInterp(lumOutVec,energies,jE,nE,localEnergy) * pow(redshift_to_inf[jR],3) * escapeAi[jR];\n\t\t}\n\t\tfor (size_t jRcd=0;jRcd<nRcd;jRcd++) {\n\t\t\tdouble localEnergy = energies[jE]/redshift_CD_to_inf[jRcd];\n\t\t\tVector lumCDVec(nE,0.0), lumReflVec(nE,0.0);\n\t\t\tfor (size_t jjE=0;jjE<nE;jjE++) {\n\t\t\t\tlumCDVec[jjE] = lumOutCD[jjE][jRcd];\n\t\t\t\tlumReflVec[jjE] = lumOutRefl[jjE][jRcd];\n\t\t\t}\n\t\t\tlumCD += lumInterp(lumCDVec,energies,jE,nE,localEnergy) * pow(redshift_CD_to_inf[jRcd],3) * escapeDi[jRcd];\n\t\t\tlumRefl += lumInterp(lumReflVec,energies,jE,nE,localEnergy) * pow(redshift_CD_to_inf[jRcd],3) * escapeDi[jRcd];\n\t\t}\n\t\tdouble dfreq = frequency*(pasoF-1.0);\n\t\tlumThermalTot += (lumTot + lumCD + lumRefl)*dfreq;\n\t\tlumThermalTotRIAF += lumTot*dfreq;\n        file1\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << frequency\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << energyEV\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumSy*frequency\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumBr*frequency\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumIC*frequency\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumpp*frequency\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumCD*frequency\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumRefl*frequency\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumTot*frequency\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumICin*frequency\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumIC_CD*frequency\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumIC_Br*frequency\n\t\t\t<< endl;\n\t};\n\tcout << \"Total thermal luminosity (power) = \" << lumThermalTot << endl;\n\t\n\tdouble lumThermal = 0.0;\n\tfor (size_t jR=0;jR<nR;jR++) {\n\t\tdouble r = st.denf_i.ps[DIM_R][jR]/schwRadius;\n\t\tVector lumVec(nE,0.0);\n\t\tfor (size_t jjE=0;jjE<nE;jjE++)\n\t\t\tlumVec[jjE] = lumOut[jjE][jR];\n\t\t\n\t\tfor (size_t jE=0;jE<nE;jE++) {\n\t\t\tdouble E = energies[jE];\n\t\t\tdouble localEnergy = E / redshift_to_inf[jR];\n\t\t\tdouble frequency = E/planck;\n\t\t\tdouble dfreq = frequency*(pasoF-1.0);\n\t\t\tlumThermal += lumInterp(lumVec,energies,jE,nE,localEnergy)*dfreq*escapeAi[jR] * pow(redshift_to_inf[jR],3);\n\t\t}\n\t\tcout << \"percentage of the lum produced inside r = \" << r*sqrt(paso_r)\n\t\t\t << \" equal to \" << lumThermal/lumThermalTotRIAF * 100 << \" %\" << endl;\n\t};\n\t\n\tdouble eVar = pow(energies[nE-1]/energies[0],1.0/(nE-1));\n\tsize_t jR=0;\n\tst.photon.ps.iterate([&](const SpaceIterator& itR) {\n\t\tdouble r = itR.val(DIM_R)/schwRadius;\n\t\tdouble vol = volume(itR.val(DIM_R));\n\t\tlumSy = lumBr = lumICin = lumIC = lumpp = lumTot = 0.0;\n\t\tfor (size_t jE=0;jE<nE;jE++)  {\n\t\t\tdouble frequency = energies[jE]/planck;\n\t\t\tdouble dfrequency = frequency * (eVar-1.0);\n\t\t\tlumSy += lumOutSy[jE][jR]*dfrequency;\n\t\t\tlumBr += lumOutBr[jE][jR]*dfrequency;\n\t\t\tlumICin += lumInICm[jE][jR]*dfrequency;\n\t\t\tlumIC += lumOutIC[jE][jR]*dfrequency;\n\t\t\tlumpp += lumOutpp[jE][jR]*dfrequency;\n\t\t\tlumTot += lumOut[jE][jR]*dfrequency;\n\t\t\tfileCell << log10(r) << \"\\t\" << log10(energies[jE]/planck)\n\t\t\t\t\t << \"\\t\" << safeLog10(lumOut[jE][jR]*frequency) << endl;\n\t\t}\n\t\t\n\t\tfile2\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << r\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << vol\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumSy\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumBr\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumIC\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumpp\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumTot\n\t\t\t<< setw(10) << setiosflags(ios::fixed) << scientific << setprecision(2) << lumICin\n\t\t\t<< endl;\n\t\tjR++;\n\t},{0,-1,0});\n\t\n\tfile1.close();\n\tfile2.close();\n\tfileCell.close();\n}\n\nvoid photonDensity(State& st, Vector energies, Matrix lumOut)\n{\n\tofstream file;\n\tfile.open(\"photonDensity_gap.dat\",ios::out);\n\t\n\tsize_t nZ = nR;\n\tdouble zMin = schwRadius;\n\tdouble pasoZ = pow(1e6,1.0/nZ);\n\tdouble z = zMin;\n\tst.photon.ps.iterate([&](const SpaceIterator& iZ) {\n\t\tz *= pasoZ;\n\t\tdouble Uph = 0.0;\n\t\tsize_t jE=0;\n\t\tdouble pasoE = pow(energies.back()/energies.front(),1.0/(energies.size()-1));\n\t\tst.photon.ps.iterate([&](const SpaceIterator& iZE) {\n\t\t\tdouble nPh = 0.0;\n\t\t\tdouble energy = iZE.val(DIM_E);\n\t\t\tdouble dE = energy * (pasoE - 1.0);\n\t\t\tsize_t jR=0;\n\t\t\tst.photon.ps.iterate([&](const SpaceIterator& iZER) {\n\t\t\t\tdouble r = iZER.val(DIM_R);\n\t\t\t\tdouble dist2 = z*z+r*r;\n\t\t\t\tnPh += ( lumOut[jE][jR] / (4*pi*dist2*cLight*energy*planck) );\n\t\t\t\tjR++;\n\t\t\t},{iZE.coord[DIM_E],-1,0});\n\t\t\tUph += nPh * energy * dE;\n\t\t\tfile << z/schwRadius << \"\\t\" << energy << \"\\t\" << nPh << endl;\n\t\t\tst.photon.injection.set(iZE,nPh);\n\t\t\tjE++;\n\t\t},{-1,iZ.coord[DIM_R],0});\n\t\tdouble Ub = P2(magneticField(st.denf_e.ps[DIM_R][0])/pow(z/schwRadius,1))/(8*pi);\n\t\tcout << \"z = \" << z/schwRadius << \" Rs,\\t Uph = \" << Uph << \" erg cm^-3,\\t Uph/Ub = \" << Uph/Ub << endl;\n\t},{0,-1,0});\n\tfile.close();\n}\n\nvoid photonDensityAux(State& st, Vector energies, Matrix lumOut)\n{\n\tVector z(50,GlobalConfig.get<double>(\"zGap\")*schwRadius);\n\tdouble zMax = z[0]*1000;\n\tdouble pasoZ = pow(zMax/z[0],1.0/50);\n\tfor (size_t i=1;i<50;i++) z[i] = z[i-1]*pasoZ;\n\t\n\tofstream file;\n\tfile.open(\"photonDensity_z.dat\",ios::out);\n\n\tfor (size_t i=1;i<50;i++) {\n\t\tdouble Uph = 0.0;\n\t\tsize_t jE=0;\n\t\tdouble pasoE = pow(energies.back()/energies.front(),1.0/(energies.size()-1));\n\t\tst.photon.ps.iterate([&](const SpaceIterator& itE) {\n\t\t\tdouble nPh = 0.0;\n\t\t\tdouble energy = itE.val(DIM_E);\n\t\t\tdouble dE = energy * (pasoE - 1.0);\n\t\t\tsize_t jR=0;\n\t\t\tst.photon.ps.iterate([&](const SpaceIterator& itER) {\n\t\t\t\tdouble r = itER.val(DIM_R);\n\t\t\t\tdouble dist2 = z[i]*z[i]+r*r;\n\t\t\t\tnPh += ( lumOut[jE][jR] / (4*pi*dist2*cLight*energy*planck) );\n\t\t\t\tjR++;\n\t\t\t},{itE.coord[DIM_E],-1,0});\n\t\t\tUph += nPh * dE;\n\t\t\tjE++;\n\t\t},{-1,0,0});\n\t\tfile << z[i]/schwRadius << \"\\t\" << Uph << endl;\n\t}\n\tfile.close();\n}\n\nvoid targetField(State& st, Matrix lumOut, Matrix lumCD, Matrix lumRefl, Vector energies)\n{\n\tsize_t jE=0;\n\tst.photon.ps.iterate([&](const SpaceIterator& itE) {\n\t\tsize_t jR=0;\n\t\tdouble E = itE.val(DIM_E);\n\t\tst.photon.ps.iterate([&](const SpaceIterator& itER) {\n\t\t\tdouble r = itER.val(DIM_R);\n\t\t\tdouble rB2 = r*sqrt(paso_r);\n\t\t\tdouble rB1 = rB2/paso_r;\n\t\t\tdouble vol = volume(r);\n\t\t\tdouble lumReachingShell = 0.0;\n\t\t\tdouble height = height_fun(r);\n\t\t\tdouble tau_es_1 = st.denf_e.get(itER)*thomson*height;\n\t\t\tdouble tau_es_2 = tau_es_1 * (rB2-rB1)/height;\n\t\t\tdouble tescape = height/cLight * (1.0 + tau_es_1);\n\t\t\tdouble tcross = (rB2-rB1)/cLight * (1.0 + tau_es_2);\n\t\t\t\n\t\t\tfor (size_t jjR=0;jjR<nR;jjR++) {\n\t\t\t\tVector lumVec(nE,0.0);\n\t\t\t\tfor (size_t jjE=0;jjE<nE;jjE++)\n\t\t\t\t\tlumVec[jjE] = lumOut[jE][jjR];\n\t\t\t\t\n\t\t\t\tdouble localEnergy = E / redshift[jjR][jR];\n\t\t\t\tdouble lumLocal = lumInterp(lumVec,energies,jE,nE,localEnergy);\n\t\t\t\tlumReachingShell += ( (jjR == jR) ? lumOut[jE][jR]*tescape : \n\t\t\t\t\t\t\t\t\treachAA[jjR][jR]*pow(redshift[jjR][jR],2)*lumLocal*tcross );\n\t\t\t}\n\t\t\tfor (size_t jjRcd=0;jjRcd<nRcd;jjRcd++) {\n\t\t\t\tVector lumVec(nE,0.0);\n\t\t\t\tfor (size_t jjE=0;jjE<nE;jjE++)\n\t\t\t\t\tlumVec[jjE] = lumCD[jE][jjRcd] + lumRefl[jE][jjRcd];\n\t\t\t\t\n\t\t\t\tdouble localEnergy = E / redshift_CD_to_RIAF[jjRcd][jR];\n\t\t\t\tlumReachingShell += reachDA[jjRcd][jR]*pow(redshift_CD_to_RIAF[jjRcd][jR],2) * \n\t\t\t\t\t\t\t\t\tlumInterp(lumVec,energies,jE,nE,localEnergy)*tcross;\n\t\t\t}\n\t\t\tst.photon.distribution.set(itER,lumReachingShell/(vol*planck*E)); //erg^⁻1 cm^-3 */\n\t\t\t//for (size_t jjR=0;jjR<nR;jjR++)\n\t\t\t//\tlumReachingShell += reachAA[jjR][jR]*pow(redshift[jjR][jR],2)*lumOut[jE][jjR];\n\t\t\t//for (size_t jjRcd=0;jjRcd<nRcd;jjRcd++)\n\t\t\t//\tlumReachingShell += reachDA[jjRcd][jR]*pow(redshift_CD_to_RIAF[jjRcd][jR],2)*\n\t\t\t//\t\t\t\t\t\t\t(lumCD[jE][jjRcd]+lumRefl[jE][jjRcd]);\n\t\t\t//st.photon.distribution.set(itER, lumReachingShell/(4.0*pi*r*height*planck*E*cLight)); //erg^⁻1 cm^-3\n\t\t\tjR++;\n\t\t},{itE.coord[DIM_E],-1,0});\n\t\tjE++;\n\t},{-1,0,0});\n}\n\nvoid absorptionLumThermal(State& st, Matrix lumOut, Matrix lumCD, Matrix lumRefl, Matrix& lumOut_gg,\n\t\t\t\t\t\t\tVector energies)\n{\n\tint cond = 1;\n\tMatrix lumOut_gg_aux;\n\tmatrixInitCopy(lumOut_gg,nE,nR,lumOut);\n\tmatrixInitCopy(lumOut_gg_aux,nE,nR,lumOut);\n\tint it = 0;\n\tdo {\n\t\tcond = 0;\n\t\ttargetField(st,lumOut_gg,lumCD,lumRefl,energies);\n\t\tst.photon.ps.iterate([&](const SpaceIterator& iR) {\n\t\t\tdouble height = height_fun(iR.val(DIM_R));\n\t\t\tfor (size_t jE=0;jE<nE;jE++) {\n\t\t\t\tdouble E = st.photon.ps[DIM_E][jE];\n\t\t\t\tdouble kappa_gg = integSimpsonLog(st.photon.emin(),st.photon.emax(),\n\t\t\t\t\t\t[&E,&iR,&st](double Eph)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (Eph*E > P2(electronRestEnergy))\n\t\t\t\t\t\t\t\treturn st.photon.distribution.interpolate({{0,Eph}},&iR.coord)*\n\t\t\t\t\t\t\t\t\t\tggCrossSection2(E,Eph);\n\t\t\t\t\t\t\telse \n\t\t\t\t\t\t\t\treturn 0.0;\n\t\t\t\t\t\t},50);\n\t\t\t\tdouble tau_gg = 0.5*sqrt(pi)*kappa_gg*height;\n\t\t\t\tdouble factor_gg = (tau_gg > 1.0e-5) ? \n\t\t\t\t\t\t\t\t\t(1.0-exp(-2*sqrt(3.0)*tau_gg))/(2.0*sqrt(3.0)*tau_gg) : 1.0;\n\t\t\t\tdouble lum = lumOut[jE][iR.coord[DIM_R]] * factor_gg;\n\t\t\t\tlumOut_gg[jE][iR.coord[DIM_R]] = lum;\n\t\t\t\tif (lum > 0.0 && lumOut[jE][iR.coord[DIM_R]] > 0.0)\n\t\t\t\t\tif (abs(safeLog10(lum/lumOut_gg_aux[jE][iR.coord[DIM_R]])) > 0.01) cond = 1;\n\t\t\t\tlumOut_gg_aux[jE][iR.coord[DIM_R]] = lum;\n\t\t\t}\n\t\t},{0,-1,0});\n\t\tit++;\n\t\tcout << \"Iteration number \" << it << \".\" << endl;\n\t} while (cond && it <= 20);\n\tcout << \"Exit in \" << it << \" iterarations.\" << endl;\n}\n/*\nvoid calculateElectronTemp(State& st, Matrix lumOut, Matrix lumInICm, Vector energies, double& res)\n{\n\tofstream fileNewTemp_e, fileCooling;\n\tfileNewTemp_e.open(\"newTempElectrons.txt\");\n\tfileCooling.open(\"coolingElectrons.txt\");\n\tdouble eVar = pow(energies[nE-1]/energies[0],1.0/(nE-1));\n\tsize_t newDim = 10000;\n\tVector logTe2(newDim,logTe.back());\n\tdouble paso_r_new = pow(st.denf_e.ps[DIM_R][nR-1]/st.denf_e.ps[DIM_R][1],1.0/(newDim-1));\n\tdouble r = st.denf_e.ps[DIM_R][nR-1];\n\tdouble dlogr = log(paso_r_new);\n\tsize_t kR = 1;\n\twhile (r > st.denf_e.ps[DIM_R][1]) {\n\t\tdouble Qmin = Qmin_func(r,lumOut,lumInICm,energies,st);\n\t\tdouble v = radialVel(r);\n\t\tdouble Te = exp(logTe2[kR-1]);\n\t\tdouble Ti = ionTemp(r);\n\t\tdouble pe = massDensityADAF(r) * boltzmann * Te / (atomicMassUnit*eMeanMolecularWeight);\n\t\tdouble Qie = qie_beta(r,Ti,Te);\n\t\tdouble Qp = Qplus(r,Ti,Te);\n\t\tdouble Qs = r/(pe*v) * (delta*Qp + Qie - Qmin);//*min(P3(Te/electronTemp(r)),1.0));\n\t\tdouble normtemp = boltzmann*Te / electronRestEnergy;\n\t\tdouble a_aux = 3.0-6.0/(4.0+5.0*normtemp) + normtemp * 30.0/P2(4.0+5.0*normtemp);\n\t\tdouble dlogrhodlogr = dlogrho_dlogr(r);\n\t\tdouble func = (Qs+dlogrhodlogr) / a_aux;\n\t\t\n\t\twhile (abs(func*dlogr) > 0.01) {\n\t\t\tpaso_r_new = pow(paso_r_new,1.0/10);\n\t\t\tdlogr = log(paso_r_new);\n\t\t}\n\t\tlogTe2[kR] = min(log(min(electronTempOriginal(r),electronTemp(r))),\n\t\t\t\t\t\tlogTe2[kR-1] - func * dlogr);\n\t\t//logTe2[kR] = logTe2[kR-1] - func *dlogr;\n\t\tfileNewTemp_e << log10(r/schwRadius) << \"\\t\" << log10(exp(logTe2[kR])) << endl;\n\t\tfileCooling << log10(r/schwRadius) << \"\\t\" << Qp << \"\\t\" << Qie << \"\\t\" << Qmin << endl;\n\n\t\t//cout << kR << endl;\n\t\tkR++;\n\t\tr /= paso_r_new;\n\t\tpaso_r_new = pow(paso_r_new,10);\n\t\tdlogr = log(paso_r_new);\n\t}\n\tfileNewTemp_e.close();\n\tfileCooling.close();\n}*/\n\nvoid thermalRadiation(State& st, const string& filename)\n{\n\tshow_message(msgStart,Module_thermalLuminosities);\n\n\tMatrix lumOutSy,lumOutBr,lumOutpp,lumInICm,lumOutIC,lumOutIC_CD,lumOutIC_Br,\n\t\t\tlumOut,lumOutCD,lumOutRefl,lumOut_gg;\n\tMatrix lumSy,lumBr,lumIC,lum;\n\tmatrixInit(lumOutSy,nE,nR,0.0);\n\tmatrixInit(lumOutBr,nE,nR,0.0);\n\tmatrixInit(lumOutpp,nE,nR,0.0);\n\tmatrixInit(lumInICm,nE,nR,0.0);\n\tmatrixInit(lumOutIC,nE,nR,0.0);\n\tmatrixInit(lumOutIC_CD,nE,nR,0.0);\n\tmatrixInit(lumOutIC_Br,nE,nR,0.0);\n\tmatrixInit(lumOutCD,nE,nR,0.0);\n\tmatrixInit(lumOutRefl,nE,nR,0.0);\n\tmatrixInit(lumOut,nE,nR,0.0);\n\tmatrixInit(lumOut_gg,nE,nR,0.0);\n\n\tVector energies(nE,0.0);\n\t\n\tint processesFlags[numProcesses];\treadThermalProcesses(processesFlags);\n\tif (processesFlags[0] || processesFlags[1] || processesFlags[2] || processesFlags[3]) {\n\t\tdouble res = 0.0;\n\t\tdo {\n\t\t\tif (processesFlags[0] || processesFlags[1] || processesFlags[2])\n\t\t\t\tif (height_method == 0)\n\t\t\t\t\tlocalProcesses(st,lumOutSy,lumOutBr,lumOutpp,energies,processesFlags,lumOut);\n\t\t\t\telse {\n\t\t\t\t\tlocalProcesses2(st,lumOutSy,lumOutBr,energies,processesFlags,lumOut);\n\t\t\t\t}\n\t\t\tif (processesFlags[4]) {\n\t\t\t\tif (comptonMethod == 2)\n\t\t\t\t\tlocalCompton(st,lumOut,lumOutIC,energies);\n\t\t\t\telse\n\t\t\t\t\tthermalCompton2(st,lumOut,lumOutBr,lumInICm,lumOutIC,lumOutIC_CD,lumOutIC_Br,energies,processesFlags);\n\t\t\t}\n\t\t\tif (processesFlags[3])\n\t\t\t\tcoldDiskLuminosity(st,lumOut,lumOutRefl,lumOutCD,energies);\n\t\t} while (res > 1.0e-3);\n\t\t//photonDensity(st,energies,lumOut);\n\t\t//photonDensityAux(st,energies,lumOut);\n\t\tabsorptionLumThermal(st,lumOut,lumOutCD,lumOutRefl,lumOut_gg,energies);\n\t\twriteLuminosities(st,energies,lumOutSy,lumOutBr,lumOutpp,lumInICm,\n\t\t\t\t\t\t\tlumOutIC,lumOutIC_CD,lumOutIC_Br,lumOut_gg,lumOutCD,lumOutRefl,filename);\n\t}\n\twriteEandRParamSpace(\"photonDensity\", st.photon.distribution, 0, 0);\n\twriteRParamSpace(\"photonDensity_R\", st.photon.distribution, 0, 0);\n\tshow_message(msgEnd,Module_thermalLuminosities);\n}", "meta": {"hexsha": "032017ff8d0dd1b54108e67c60edac3dc09121f4", "size": 36992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adaf/thermalProcesses.cpp", "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_issues_repo_path": "src/adaf/thermalProcesses.cpp", "max_issues_repo_name": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/adaf/thermalProcesses.cpp", "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.125, "max_line_length": 114, "alphanum_fraction": 0.6500865052, "num_tokens": 14139, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.40602336550190615}}
{"text": "// Copyright (c) 2020 Marcus Valtonen Örnhag\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include \"get_valtonenornhag_arxiv_2020b.hpp\"\n#include <Eigen/Geometry>\n#include <cmath>  // max\n#include <vector>\n#include \"solver_valtonenornhag_arxiv_2020b_fHf.hpp\"\n#include \"normalize2dpts.hpp\"\n#include \"posedata.hpp\"\n\nnamespace HomLib {\nnamespace ValtonenOrnhagArxiv2020B {\n    inline Eigen::Vector4d construct_hvector(double w, const Eigen::VectorXd input);\n\n    std::vector<HomLib::PoseData> get_fHf(\n        const Eigen::MatrixXd &p1,\n        const Eigen::MatrixXd &p2,\n        const Eigen::Matrix3d &R1,\n        const Eigen::Matrix3d &R2\n    ) {\n        // This is a 2-point method\n        int nbr_pts = 2;\n\n        // We expect inhomogenous input data, i.e. p1 and p2 are 2x3 matrices\n        assert(p1.rows() == 2);\n        assert(p2.rows() == 2);\n        assert(p1.cols() == nbr_pts);\n        assert(p2.cols() == nbr_pts);\n        int nbr_coeffs = 26;\n\n        // Save copies of the inverse rotation\n        Eigen::Matrix3d R1T = R1.transpose();\n        Eigen::Matrix3d R2T = R2.transpose();\n\n        // Compute normalization matrix\n        double scale1 = normalize2dpts(p1);\n        double scale2 = normalize2dpts(p2);\n        double scale = std::max(scale1, scale2);\n        Eigen::Vector3d s;\n        s << scale, scale, 1.0;\n        Eigen::DiagonalMatrix<double, 3> S = s.asDiagonal();\n\n        // Normalize data\n        Eigen::MatrixXd x1(3, 2);\n        Eigen::MatrixXd x2(3, 2);\n        x1 = p1.colwise().homogeneous();\n        x2 = p2.colwise().homogeneous();\n\n        x1 = S * x1;\n        x2 = S * x2;\n\n        Eigen::Matrix2d x1t;\n        x1t << x1.colwise().hnormalized();\n        Eigen::Matrix2d x2t;\n        x2t << x2.colwise().hnormalized();\n\n        // Wrap input data to expected format\n        Eigen::VectorXd input(nbr_coeffs);\n        input << x1t.col(0),\n                 x2t.col(0),\n                 x1t.col(1),\n                 x2t.col(1),\n                 Eigen::Map<Eigen::VectorXd>(R1T.data(), 9),\n                 Eigen::Map<Eigen::VectorXd>(R2T.data(), 9);\n\n        // Extract w\n        Eigen::VectorXcd w = HomLib::ValtonenOrnhagArxiv2020B::solver_fHf(input);\n\n        // Pre-processing: Remove complex-valued solutions\n        double thresh = 1e-5;\n        Eigen::ArrayXd real_w = w.imag().array().abs();\n\n        // This is a 2 pt solver\n        std::vector<HomLib::PoseData> posedata;\n        HomLib::PoseData tmp_pose;\n        double w_tmp;\n        Eigen::Vector4d hvec;\n        Eigen::Matrix3d K, Ki, Htmp;\n\n        double tol = 1e-13;\n\n        for (int i = 0; i < real_w.size(); i++) {\n            if (real_w(i) <= thresh) {\n                // Compute algebraic error, and compare to other solutions.\n                w_tmp = w(i).real();\n\n                // Compute h vector\n                hvec = construct_hvector(w_tmp, input);\n\n                // Two spurious solutions were added, corresponding to last element\n                // equal to zero.\n                if (std::abs(hvec(3)) > tol) {\n                    Htmp = Eigen::Matrix3d::Identity(3, 3);\n                    Htmp.col(1) = hvec.hnormalized();\n\n                    K = Eigen::Vector3d(w_tmp, w_tmp, 1).asDiagonal();\n                    Ki = Eigen::Vector3d(1, 1, w_tmp).asDiagonal();\n                    Htmp = S.inverse() * K * R2 * Htmp * R1T * Ki * S;\n\n                    // Package output\n                    tmp_pose.homography = Htmp;\n                    tmp_pose.focal_length = w_tmp / scale;\n                    posedata.push_back(tmp_pose);\n                }\n            }\n        }\n\n        return posedata;\n    }\n\n    inline Eigen::Vector4d construct_hvector(double w, const Eigen::VectorXd input) {\n        Eigen::VectorXd d(27);\n        d << w, input;\n\n        double s1 = d[0]*d[25];\n        double s2 = d[0]*d[16];\n        double t1 = s1 + d[7]*d[19] + d[8]*d[22];\n        double t2 = d[3]*d[19] + s1 + d[4]*d[22];\n        double t3 = d[5]*d[10] + s2 + d[6]*d[13];\n        double t4 = d[1]*d[10] + d[2]*d[13] + s2;\n        double u1 = d[0]*d[24];\n        double u2 = d[0]*d[15];\n        double u3 = d[0]*d[26];\n\n        Eigen::Matrix<double, 4, 4> M;\n        M << 0, -t4*(d[3]*d[20] + u3 + d[4]*d[23]), t4*t2, (d[1]*d[11] + d[2]*d[14] + d[0]*d[17])*t2,  // NOLINT\n             -t4*t2,  t4*(d[3]*d[18] + u1 + d[4]*d[21]), 0, -(d[1]*d[9] + d[2]*d[12] + u2)*t2,  // NOLINT\n             0, -t3*(u3 + d[7]*d[20] + d[8]*d[23]), t3*t1,  (d[5]*d[11] + d[0]*d[17] + d[6]*d[14])*t1,  // NOLINT\n             -t3*t1,  t3*(u1 + d[7]*d[18] + d[8]*d[21]), 0, -(d[5]*d[9] + u2 + d[6]*d[12])*t1;  // NOLINT\n\n        // Perform SVD\n        Eigen::JacobiSVD<Eigen::Matrix<double, 4, 4>> svd(M, Eigen::ComputeFullV);\n\n        // Extract hvector\n        Eigen::Vector4d h = svd.matrixV().col(3);\n\n        return h;\n    }\n}  // namespace ValtonenOrnhagArxiv2020B\n}  // namespace HomLib\n", "meta": {"hexsha": "24b50f35f4559287b47e45b068819d631f48ed64", "size": 5913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solvers/valtonenornhag_arxiv_2020b/get_valtonenornhag_arxiv_2020b_fHf.cpp", "max_stars_repo_name": "marcusvaltonen/HomLib", "max_stars_repo_head_hexsha": "cc8c3ba78bbfcb30fdbe17e5aa45405f4757889b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-01-07T18:58:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T10:37:37.000Z", "max_issues_repo_path": "src/solvers/valtonenornhag_arxiv_2020b/get_valtonenornhag_arxiv_2020b_fHf.cpp", "max_issues_repo_name": "marcusvaltonen/HomLib", "max_issues_repo_head_hexsha": "cc8c3ba78bbfcb30fdbe17e5aa45405f4757889b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solvers/valtonenornhag_arxiv_2020b/get_valtonenornhag_arxiv_2020b_fHf.cpp", "max_forks_repo_name": "marcusvaltonen/HomLib", "max_forks_repo_head_hexsha": "cc8c3ba78bbfcb30fdbe17e5aa45405f4757889b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-19T19:59:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-19T19:59:02.000Z", "avg_line_length": 37.1886792453, "max_line_length": 113, "alphanum_fraction": 0.564180619, "num_tokens": 1772, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.40592458550216565}}
{"text": "//\n//  expr/detail/expr.hpp\n//  solver\n//\n//  Created by Alexandre Martin on 28/04/2016.\n//  Copyright © 2016 scalexm. All rights reserved.\n//\n\n#ifndef DETAIL_EXPR_HPP\n#define DETAIL_EXPR_HPP\n\n#include <ostream>\n#include <boost/variant.hpp>\n\nnamespace expr { namespace detail {\n    /*\n        tags for the template struct binary: each tag identifies a binary logical operator\n    */\n    struct and_tag {\n        constexpr static const char * text = \"/\\\\\";\n    };\n\n    struct or_tag {\n        constexpr static const char * text = \"\\\\/\";\n    };\n\n    struct xor_tag {\n        constexpr static const char * text = \"X\";\n    };\n\n    struct impl_tag {\n        constexpr static const char * text = \"=>\";\n    };\n\n    struct equiv_tag {\n        constexpr static const char * text = \"<=>\";\n    };\n\n    struct none_ { };\n    template<class Atom> struct not_;\n    template<class Tag, class Atom> struct binary_;\n\n    template<class Atom>\n    using and_ = binary_<detail::and_tag, Atom>;\n\n    template<class Atom>\n    using or_ = binary_<detail::or_tag, Atom>;\n\n    template<class Atom>\n    using xor_ = binary_<detail::xor_tag, Atom>;\n\n    template<class Atom>\n    using impl_ = binary_<detail::impl_tag, Atom>;\n\n    template<class Atom>\n    using equiv_ = binary_<detail::equiv_tag, Atom>;\n\n    template<class Atom>\n    using expr_ = boost::variant<\n        none_, // none in first position for default ctor\n        Atom,\n        boost::recursive_wrapper<not_<Atom>>,\n        boost::recursive_wrapper<and_<Atom>>,\n        boost::recursive_wrapper<or_<Atom>>,\n        boost::recursive_wrapper<xor_<Atom>>,\n        boost::recursive_wrapper<impl_<Atom>>,\n        boost::recursive_wrapper<equiv_<Atom>>\n    >;\n\n    template<class Tag, class Atom>\n    struct binary_ {\n        expr_<Atom> op_left, op_right;\n    };\n\n    template<class Atom>\n    struct not_ {\n        expr_<Atom> op;\n    };\n\n    inline bool operator ==(const none_ &, const none_ &) {\n        return true;\n    }\n\n    template<class Atom>\n    inline bool operator ==(const not_<Atom> & a, const not_<Atom> & b) {\n        return a.op == b.op;\n    }\n\n    template<class Tag, class Atom>\n    inline bool operator ==(const binary_<Tag, Atom> & a, const binary_<Tag, Atom> & b) {\n        return a.op_left == b.op_left && a.op_right == b.op_right;\n    }\n\n    inline std::ostream & operator <<(std::ostream & stream, const none_ &) {\n        return stream << \"[none]\";\n    }\n\n    template<class Atom>\n    inline std::ostream & operator <<(std::ostream & stream, const not_<Atom> & exp) {\n        return stream << \"~(\" << exp.op << \")\";\n    }\n\n    template<class Tag, class Atom>\n    inline std::ostream & operator <<(std::ostream & stream, const binary_<Tag, Atom> & exp) {\n        return stream << \"(\" << exp.op_left << \" \" << Tag::text << \" \" << exp.op_right << \")\";\n    }\n} }\n\n\n#endif\n", "meta": {"hexsha": "1f41ce58efc6f024f04def139197ca5a3f6cee3b", "size": 2829, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "solver/expr/detail/expr.hpp", "max_stars_repo_name": "scalexm/sat_solver", "max_stars_repo_head_hexsha": "0235f76d0a93c4b8ff59071479c8ca139d2e162a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-02-16T17:39:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-04T09:11:11.000Z", "max_issues_repo_path": "solver/expr/detail/expr.hpp", "max_issues_repo_name": "scalexm/sat_solver", "max_issues_repo_head_hexsha": "0235f76d0a93c4b8ff59071479c8ca139d2e162a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solver/expr/detail/expr.hpp", "max_forks_repo_name": "scalexm/sat_solver", "max_forks_repo_head_hexsha": "0235f76d0a93c4b8ff59071479c8ca139d2e162a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4864864865, "max_line_length": 94, "alphanum_fraction": 0.6023329799, "num_tokens": 687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.40592458550216565}}
{"text": "/*\n * This file is part of the statismo library.\n *\n * Author: Marcel Luethi (marcel.luethi@unibas.ch)\n *\n * Copyright (c) 2011 University of Basel\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * Neither the name of the project's author nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n#ifndef __PCAModelBuilder_TXX\n#define __PCAModelBuilder_TXX\n\n#include \"PCAModelBuilder.h\"\n\n#include <iostream>\n\n#include <Eigen/SVD>\n#include <Eigen/Eigenvalues>\n\n#include \"CommonTypes.h\"\n#include \"Exceptions.h\"\n\nnamespace statismo {\n\ntemplate <typename T>\nPCAModelBuilder<T>::PCAModelBuilder()\n    : Superclass() {\n}\n\n\ntemplate <typename T>\ntypename PCAModelBuilder<T>::StatisticalModelType*\nPCAModelBuilder<T>::BuildNewModel(const DataItemListType& sampleDataList, double noiseVariance, bool computeScores, EigenValueMethod method) const {\n\n    unsigned n = sampleDataList.size();\n    if (n <= 0) {\n        throw StatisticalModelException(\"Provided empty sample set. Cannot build the sample matrix\");\n    }\n\n    unsigned p = sampleDataList.front()->GetSampleVector().rows();\n    const Representer<T>* representer = sampleDataList.front()->GetRepresenter();\n\n\n    // Compute the mean vector mu\n    VectorType mu = VectorType::Zero(p);\n\n    for (typename DataItemListType::const_iterator it = sampleDataList.begin();\n            it != sampleDataList.end();  ++it) {\n        assert((*it)->GetSampleVector().rows() == p); // all samples must have same number of rows\n        assert((*it)->GetRepresenter() == representer); // all samples have the same representer\n        mu += (*it)->GetSampleVector();\n    }\n    mu /= n;\n\n    // Build the mean free sample matrix X0\n    MatrixType X0(n, p);\n    unsigned i = 0;\n    for (typename DataItemListType::const_iterator it = sampleDataList.begin();\n            it != sampleDataList.end(); ++it) {\n        X0.row(i++) = (*it)->GetSampleVector() - mu;\n    }\n\n\n\n\n\n    // build the model\n    StatisticalModelType* model = BuildNewModelInternal(representer, X0, mu, noiseVariance, method);\n\n    // compute the scores if requested\n    MatrixType scores;\n    if (computeScores) {\n        scores = this->ComputeScores(sampleDataList, model);\n    }\n\n\n    typename BuilderInfo::ParameterInfoList bi;\n    bi.push_back(BuilderInfo::KeyValuePair(\"NoiseVariance \", Utils::toString(noiseVariance)));\n\n    typename BuilderInfo::DataInfoList dataInfo;\n    i = 0;\n    for (typename DataItemListType::const_iterator it = sampleDataList.begin();\n            it != sampleDataList.end();\n            ++it, i++) {\n        std::ostringstream os;\n        os << \"URI_\" << i;\n        dataInfo.push_back(BuilderInfo::KeyValuePair(os.str().c_str(),(*it)->GetDatasetURI()));\n    }\n\n\n    // finally add meta data to the model info\n    BuilderInfo builderInfo(\"PCAModelBuilder\", dataInfo, bi);\n\n    ModelInfo::BuilderInfoList biList;\n    biList.push_back(builderInfo);\n\n    ModelInfo info(scores, biList);\n    model->SetModelInfo(info);\n\n    return model;\n}\n\n\ntemplate <typename T>\ntypename PCAModelBuilder<T>::StatisticalModelType*\nPCAModelBuilder<T>::BuildNewModelInternal(const Representer<T>* representer, const MatrixType& X0, const VectorType& mu,\n        double noiseVariance, EigenValueMethod method) const {\n\n    unsigned n = X0.rows();\n    unsigned p = X0.cols();\n\n    switch(method) {\n    case JacobiSVD:\n\n        typedef Eigen::JacobiSVD<MatrixType> SVDType;\n        typedef Eigen::JacobiSVD<MatrixTypeDoublePrecision> SVDDoublePrecisionType;\n\n        // We destinguish the case where we have more variables than samples and\n        // the case where we have more samples than variable.\n        // In the first case we compute the (smaller) inner product matrix instead of the full covariance matrix.\n        // It is known that this has the same non-zero singular values as the covariance matrix.\n        // Furthermore, it is possible to compute the corresponding eigenvectors of the covariance matrix from the\n        // decomposition.\n\n        if (n < p) {\n            // we compute the eigenvectors of the covariance matrix by computing an SVD of the\n            // n x n inner product matrix 1/(n-1) X0X0^T\n            MatrixType Cov = X0 * X0.transpose() * 1.0/(n-1);\n            SVDDoublePrecisionType SVD(Cov.cast<double>(), Eigen::ComputeThinV);\n            VectorType singularValues = SVD.singularValues().cast<ScalarType>();\n            MatrixType V = SVD.matrixV().cast<ScalarType>();\n\n            unsigned numComponentsAboveTolerance = ((singularValues.array() - noiseVariance - Superclass::TOLERANCE) > 0).count();\n\n            // there can be at most n-1 nonzero singular values in this case. Everything else must be due to numerical inaccuracies\n            unsigned numComponentsToKeep = std::min(numComponentsAboveTolerance, n - 1);\n            // compute the pseudo inverse of the square root of the singular values\n            // which is then needed to recompute the PCA basis\n            VectorType singSqrt = singularValues.array().sqrt();\n            VectorType singSqrtInv = VectorType::Zero(singSqrt.rows());\n            for (unsigned i = 0; i < numComponentsToKeep; i++) {\n                assert(singSqrt(i) > Superclass::TOLERANCE);\n                singSqrtInv(i) = 1.0 / singSqrt(i);\n            }\n\n            if (numComponentsToKeep == 0) {\n                throw StatisticalModelException(\"All the eigenvalues are below the given tolerance. Model cannot be built.\");\n            }\n\n            // we recover the eigenvectors U of the full covariance matrix from the eigenvectors V of the inner product matrix.\n            // We use the fact that if we decompose X as X=UDV^T, then we get X^TX = UD^2U^T and XX^T = VD^2V^T (exploiting the orthogonormality\n            // of the matrix U and V from the SVD). The additional factor sqrt(n-1) is to compensate for the 1/sqrt(n-1) in the formula\n            // for the covariance matrix.\n\n            MatrixType pcaBasis = X0.transpose() * V * singSqrtInv.asDiagonal();\n            pcaBasis /= sqrt(n - 1.0);\n            pcaBasis.conservativeResize(Eigen::NoChange, numComponentsToKeep);\n\n\n            VectorType sampleVarianceVector = singularValues.topRows(numComponentsToKeep);\n            VectorType pcaVariance = (sampleVarianceVector - VectorType::Ones(numComponentsToKeep) * noiseVariance);\n\n            StatisticalModelType* model = StatisticalModelType::Create(representer, mu, pcaBasis, pcaVariance, noiseVariance);\n\n            return model;\n        } else {\n            // we compute an SVD of the full p x p  covariance matrix 1/(n-1) X0^TX0 directly\n            SVDType SVD(X0.transpose() * X0, Eigen::ComputeThinU);\n            VectorType singularValues = SVD.singularValues();\n            singularValues /= (n - 1.0);\n            unsigned numComponentsToKeep = ((singularValues.array() - noiseVariance - Superclass::TOLERANCE) > 0).count();\n            MatrixType pcaBasis = SVD.matrixU();\n            \n            pcaBasis.conservativeResize(Eigen::NoChange, numComponentsToKeep);\n\n            if (numComponentsToKeep == 0) {\n                throw StatisticalModelException(\"All the eigenvalues are below the given tolerance. Model cannot be built.\");\n            }\n\n            VectorType sampleVarianceVector = singularValues.topRows(numComponentsToKeep);\n            VectorType pcaVariance = (sampleVarianceVector - VectorType::Ones(numComponentsToKeep) * noiseVariance);\n            StatisticalModelType* model = StatisticalModelType::Create(representer, mu, pcaBasis, pcaVariance, noiseVariance);\n            return model;\n        }\n        break;\n\n    case SelfAdjointEigenSolver: {\n        // we compute the eigenvalues/eigenvectors of the full p x p  covariance matrix 1/(n-1) X0^TX0 directly\n\n        typedef Eigen::SelfAdjointEigenSolver<MatrixType> SelfAdjointEigenSolver;\n        SelfAdjointEigenSolver es;\n        es.compute(X0.transpose() * X0);\n        VectorType eigenValues = es.eigenvalues().reverse(); // SelfAdjointEigenSolver orders the eigenvalues in increasing order\n        eigenValues /= (n -1.0);\n\n\n        unsigned numComponentsToKeep = ((eigenValues.array() - noiseVariance - Superclass::TOLERANCE) > 0).count();\n        MatrixType pcaBasis = es.eigenvectors().rowwise().reverse(); \n        pcaBasis.conservativeResize(Eigen::NoChange, numComponentsToKeep);\n\n\n        if (numComponentsToKeep == 0) {\n            throw StatisticalModelException(\"All the eigenvalues are below the given tolerance. Model cannot be built.\");\n        }\n\n        VectorType sampleVarianceVector = eigenValues.topRows(numComponentsToKeep);\n        VectorType pcaVariance = (sampleVarianceVector - VectorType::Ones(numComponentsToKeep) * noiseVariance);\n        StatisticalModelType* model = StatisticalModelType::Create(representer, mu, pcaBasis, pcaVariance, noiseVariance);\n        return model;\n    }\n    break;\n\n    default:\n        throw StatisticalModelException(\"Unrecognized decomposition/eigenvalue solver method.\");\n        return 0;\n        break;\n    }\n}\n\n\n} // namespace statismo\n\n#endif\n", "meta": {"hexsha": "d31336f53b43fdbcec239bde52d1fce2f1f47707", "size": 10398, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "modules/core/include/PCAModelBuilder.hxx", "max_stars_repo_name": "skn123/statismo", "max_stars_repo_head_hexsha": "5998a32e1b1fd496f2703eea27dc143a6b3f8e1f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 223.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T18:50:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T08:14:17.000Z", "max_issues_repo_path": "modules/core/include/PCAModelBuilder.hxx", "max_issues_repo_name": "skn123/statismo", "max_issues_repo_head_hexsha": "5998a32e1b1fd496f2703eea27dc143a6b3f8e1f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 84.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T09:54:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-05T17:17:05.000Z", "max_forks_repo_path": "modules/core/include/PCAModelBuilder.hxx", "max_forks_repo_name": "skn123/statismo", "max_forks_repo_head_hexsha": "5998a32e1b1fd496f2703eea27dc143a6b3f8e1f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 94.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T20:02:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-15T08:45:18.000Z", "avg_line_length": 41.2619047619, "max_line_length": 148, "alphanum_fraction": 0.6853241008, "num_tokens": 2420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.40592458550216565}}
{"text": "/*  _______________________________________________________________________\n\n    DAKOTA: Design Analysis Kit for Optimization and Terascale Applications\n    Copyright 2014 Sandia Corporation.\n    This software is distributed under the GNU Lesser General Public License.\n    For more information, see the README file in the top Dakota directory.\n    _______________________________________________________________________ */\n\n//- Description:  This file contains code related to data utilities that should\n//-               be compiled, rather than inlined in data_util.hpp.\n//-\n//- Owner:        Mike Eldred\n//- Version: $Id: dakota_data_util.cpp 7024 2010-10-16 01:24:42Z mseldre $\n\n#include \"dakota_data_util.hpp\"\n#include <boost/math/special_functions/round.hpp>\n\nnamespace Dakota {\n\n// ------------\n// == operators\n// ------------\n\n\nbool nearby(const RealVector& rv1, const RealVector& rv2, Real rel_tol)\n{\n  // Check for equality in array lengths\n  size_t len = rv1.length();\n  if ( rv2.length() != len )\n    return false;\n\t\n  // Check each value (labels are ignored!)\n  Real abs_tol = DBL_MIN; // ~ 2.2e-308\n  for (size_t i=0; i<len; i++)\n    // prevent division by 0\n    if (std::abs(rv1[i]) < abs_tol) { //(rv1[i] == 0.)\n      if (std::abs(rv2[i]) > abs_tol) //(rv2[i] != 0.)\n\treturn false;\n    }\n    else if ( std::abs(1. - rv2[i]/rv1[i]) > rel_tol ) // DBL_EPSILON\n      return false;\n\n  return true;\n}\n\n\nbool operator==(const ShortArray& dsa1, const ShortArray& dsa2)\n{\n  // Check for equality in array lengths\n  size_t len = dsa1.size();\n  if ( dsa2.size() != len )\n    return false;\n\n  // Check each value\n  for (size_t i=0; i<len; ++i)\n    if ( dsa2[i] != dsa1[i] )\n      return false;\n\n  return true;\n}\n\n\nbool operator==(const StringArray& dsa1, const StringArray& dsa2)\n{\n  // Check for equality in array lengths\n  size_t len = dsa1.size();\n  if ( dsa2.size() != len )\n    return false;\n\n  // Check each string\n  for (size_t i=0; i<len; ++i)\n    if ( dsa2[i] != dsa1[i] )\n      return false;\n\n  return true;\n}\n\n\n// ---------------------------------\n// miscellaneous numerical utilities\n// ---------------------------------\n\nReal rel_change_L2(const RealVector& curr_rv, const RealVector& prev_rv)\n{\n  size_t i, rv_len = prev_rv.length();\n  Real norm = 0.;\n\n  // check previous vector for zeros\n  bool zero_prev = false, zero_curr = false;\n  for (i=0; i<rv_len; ++i)\n    if (std::abs(prev_rv[i]) < Pecos::SMALL_NUMBER)\n      { zero_prev = true; break; }\n  // check current vector for zeros\n  if (zero_prev)\n    for (i=0; i<rv_len; ++i)\n      if (std::abs(curr_rv[i]) < Pecos::SMALL_NUMBER)\n\t{ zero_curr = true; break; }\n\n  // Compute norm of relative change one of three ways\n  if (!zero_prev) { // change relative to previous\n    for (i=0; i<rv_len; ++i)\n      norm += std::pow(curr_rv[i] / prev_rv[i] - 1., 2.);\n    return std::sqrt(norm);\n  }\n  else if (!zero_curr) { // change relative to current\n    for (i=0; i<rv_len; ++i)\n      norm += std::pow(prev_rv[i] / curr_rv[i] - 1., 2.);\n    return std::sqrt(norm);\n  }\n  else { // absolute change scaled by norm of previous\n    Real scaling = 0.;\n    for (i=0; i<rv_len; ++i) {\n      norm    += std::pow(curr_rv[i] - prev_rv[i], 2.);\n      scaling += std::pow(prev_rv[i], 2.);\n    }\n    return (scaling > Pecos::SMALL_NUMBER) ?\n      std::sqrt(norm / scaling) : std::sqrt(norm);\n  }\n}\n\n\nReal rel_change_L2(const RealVector& curr_rv1, const RealVector& prev_rv1,\n\t\t   const IntVector&  curr_iv,  const IntVector&  prev_iv,\n\t\t   const RealVector& curr_rv2, const RealVector& prev_rv2)\n{\n  size_t i, rv1_len = prev_rv1.length(), iv_len = prev_iv.length(),\n    rv2_len = prev_rv2.length();\n  Real norm = 0.;\n\n  // check previous vectors for zeros\n  bool zero_prev = false, zero_curr = false;\n  for (i=0; i<rv1_len; ++i)\n    if (std::abs(prev_rv1[i]) < Pecos::SMALL_NUMBER)\n      { zero_prev = true; break; }\n  if (!zero_prev)\n    for (i=0; i<iv_len; ++i)\n      if (std::abs(prev_iv[i]))\n\t{ zero_prev = true; break; }\n  if (!zero_prev)\n    for (i=0; i<rv2_len; ++i)\n      if (std::abs(prev_rv2[i]) < Pecos::SMALL_NUMBER)\n\t{ zero_prev = true; break; }\n  // check current vectors for zeros\n  if (zero_prev) {\n    for (i=0; i<rv1_len; ++i)\n      if (std::abs(curr_rv1[i]) < Pecos::SMALL_NUMBER)\n\t{ zero_curr = true; break; }\n    if (!zero_prev)\n      for (i=0; i<iv_len; ++i)\n\tif (std::abs(curr_iv[i]))\n\t  { zero_curr = true; break; }\n    if (!zero_prev)\n      for (i=0; i<rv2_len; ++i)\n\tif (std::abs(curr_rv2[i]) < Pecos::SMALL_NUMBER)\n\t  { zero_curr = true; break; }\n  }\n\n  // Compute norm of relative change one of three ways\n  if (!zero_prev) { // change relative to previous\n    for (i=0; i<rv1_len; ++i)\n      norm += std::pow(curr_rv1[i] / prev_rv1[i] - 1., 2.);\n    for (i=0; i<iv_len; ++i)\n      norm += std::pow(curr_iv[i]  / prev_iv[i]  - 1., 2.);\n    for (i=0; i<rv2_len; ++i)\n      norm += std::pow(curr_rv2[i] / prev_rv2[i] - 1., 2.);\n    return std::sqrt(norm);\n  }\n  else if (!zero_curr) { // change relative to current\n    for (i=0; i<rv1_len; ++i)\n      norm += std::pow(prev_rv1[i] / curr_rv1[i] - 1., 2.);\n    for (i=0; i<iv_len; ++i)\n      norm += std::pow(prev_iv[i]  / curr_iv[i]  - 1., 2.);\n    for (i=0; i<rv2_len; ++i)\n      norm += std::pow(prev_rv2[i] / curr_rv2[i] - 1., 2.);\n    return std::sqrt(norm);\n  }\n  else { // absolute change scaled by norm of previous\n    Real scaling = 0.;\n    for (i=0; i<rv1_len; ++i) {\n      norm    += std::pow(curr_rv1[i] - prev_rv1[i], 2.);\n      scaling += prev_rv1[i] * prev_rv1[i];\n    }\n    for (i=0; i<iv_len; ++i) {\n      norm    += std::pow(curr_iv[i] - prev_iv[i], 2.);\n      scaling += prev_iv[i] * prev_iv[i];\n    }\n    for (i=0; i<rv2_len; ++i) {\n      norm    += std::pow(curr_rv2[i] - prev_rv2[i], 2.);\n      scaling += prev_rv2[i] * prev_rv2[i];\n    }\n    return (scaling > Pecos::SMALL_NUMBER) ?\n      std::sqrt(norm / scaling) : std::sqrt(norm);\n  }\n}\n\nvoid remove_column(RealMatrix& matrix, int index)\n{\n  int num_cols = matrix.numCols();\n  RealMatrix matrix_new(matrix.numRows(), num_cols-1);\n  for (int i = 0; i<num_cols; ++i){\n      const RealVector& col_vec = Teuchos::getCol(Teuchos::View, matrix, i);\n    if (i < index){\n      Teuchos::setCol(col_vec, i, matrix_new);\n    }\n    if (i > index){\n      Teuchos::setCol(col_vec, i-1, matrix_new);\n    }\n  }\n  matrix.reshape(matrix.numRows(), num_cols-1);\n  matrix = matrix_new;\n}\n\n\nvoid iround(const RealVector& input_vec, IntVector& rounded_vec)\n{\n  int len = input_vec.length();\n  if (rounded_vec.length() != len)\n    rounded_vec.resize(len);\n  for (int i=0; i<len; ++i)\n    rounded_vec[i] = boost::math::iround(input_vec[i]);\n}\n\n\n} // namespace Dakota\n", "meta": {"hexsha": "ad988cf0d30ae868f9f5abc4f3b5a411058b4ee5", "size": 6646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/dakota_data_util.cpp", "max_stars_repo_name": "jnnccc/Dakota-orb", "max_stars_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dakota_data_util.cpp", "max_issues_repo_name": "jnnccc/Dakota-orb", "max_issues_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dakota_data_util.cpp", "max_forks_repo_name": "jnnccc/Dakota-orb", "max_forks_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5377777778, "max_line_length": 79, "alphanum_fraction": 0.6038218477, "num_tokens": 2132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.5888891307678321, "lm_q1q2_score": 0.4059245779849179}}
{"text": "#include <fstream>\r\n#include <iostream>\r\n#include <boost/thread/thread.hpp>\r\n#include <boost/thread/mutex.hpp>\r\n#include <boost/bind.hpp>\r\n\r\nextern \"C\"\r\n{\r\n\t#include \"mtrand.h\"\r\n\t#include \"cvodesim.h\"\r\n\t#include \"ssa.h\"\r\n\t#include \"testing.h\"\r\n}\r\n\r\n#include \"ParameterMC.h\"\r\n\r\nstatic int NUM_THREADS = 4;\r\nstatic boost::mutex mutex;\r\n\r\nstatic double ** SUM_XiXj = 0;\r\nstatic double * SUM_Xi = 0;\r\n\r\nvoid setNumThreads(int n)\r\n{\r\n\tif (n > 0)\r\n\t\tNUM_THREADS = n;\r\n}\r\n\r\nstatic void sampleParameterSpaceSingleRun(int numSamples, int numParameters, RandomParameterFunc getRandParams, TargetFunc isGood, int * count)\r\n{\r\n\tint i=0,j=0,k=0,n=0,accept=0;\r\n\tdouble * params = (double*)malloc(numParameters * sizeof(double));\r\n\r\n\t//run n times\r\n\tfor (k=0; k < numSamples; ++k)\r\n\t{\r\n\t\t//get a random set of parameter\r\n\t\tgetRandParams(params);\r\n\r\n\t\t//check if it is acceptable (the time consuming step, usually)\r\n\t\taccept = isGood(params);\r\n\r\n\t\tif (accept)\r\n\t\t{\r\n\t\t\t//if acceptable, store it\r\n\t\t\tmutex.lock();\r\n\t\t\t++(*count);\r\n\t\t\tfor (i=0; i < numParameters; ++i)\r\n\t\t\t{\r\n\t\t\t\t//std::cout << params[i] << \"\\t\";\r\n\t\t\t\tSUM_Xi[i] += params[i];\r\n\t\t\t\tfor (j=i; j < numParameters; ++j)\r\n\t\t\t\t\tSUM_XiXj[i][j] += params[i] * params[j];\r\n\t\t\t}\r\n\t\t\t//std::cout << std::endl;\r\n\t\t\tmutex.unlock();\r\n\t\t}\r\n\t}\r\n\r\n\tdelete params;\r\n}\r\n\r\nvoid sampleParameterSpace(int numSamples, int numParameters, RandomParameterFunc getRandParams, TargetFunc isGood, double * Mu, double ** Sigma)\r\n{\r\n\tint i = 0, j = 0, n = 0, n_last = 0, num_threads = 0, count = 0;\r\n\tboost::thread ** threads = 0;\r\n\tboost::thread * thread = 0;\r\n\r\n\t/**** global arrays for storing covariance and means ****/\r\n\t//SUM_XiXj = new double*[numParameters];\r\n\t//SUM_Xi = new double[numParameters];\r\n\r\n\tSUM_XiXj = Sigma;\r\n\tSUM_Xi = Mu;\r\n\r\n\tfor (i=0; i < numParameters; ++i)\r\n\t{\r\n\t\t//SUM_XiXj[i] = new double[numParameters];\r\n\t\tSUM_Xi[i] = 0.0;\r\n\r\n\t\tfor (j=0; j < numParameters; ++j)\r\n\t\t\tSUM_XiXj[i][j] = 0.0;\r\n\t}\r\n\r\n\t/**** divide the task amongst n threads ****/\r\n\r\n\tif (numSamples < NUM_THREADS)\r\n\t\tnumSamples = NUM_THREADS;\r\n\r\n\tn = (int)(numSamples/NUM_THREADS); //each thread is allocated n runs\r\n\tnum_threads = NUM_THREADS;\r\n\r\n\tn_last = numSamples - (n * NUM_THREADS);  //last thread is given n_last runs\r\n\tif (n_last > 0)\r\n\t\t++num_threads;\r\n\r\n\tthreads = new boost::thread*[num_threads];\r\n\r\n\t/**** make Boost threads ****/\r\n\r\n\tfor (i=0; i < num_threads; ++i)\r\n\t{\r\n\t\tif ((n_last > 0) && (i == (num_threads-1)))\r\n\t\t\tn = n_last;\r\n\r\n\t\tthread = new boost::thread(\r\n\t\t\tboost::bind(\r\n\t\t\t&sampleParameterSpaceSingleRun,\r\n\t\t\tn,\r\n\t\t\tnumParameters,\r\n\t\t\tgetRandParams,\r\n\t\t\tisGood,\r\n\t\t\t&count));\r\n\r\n\t\tthreads[i] = thread;\r\n\t}\r\n\r\n\tfor (i=0; i < num_threads; ++i)\r\n\t\tthreads[i]->join();\r\n\r\n\r\n\tfor (i=0; i < num_threads; ++i)\r\n\t\tdelete threads[i];\r\n\r\n\tdelete threads;\r\n\r\n\t--count; //unbiased mean and cov\r\n\r\n\tfor (i = 0; i < numParameters; ++i)\r\n\t\tSUM_Xi[i] /= (double)count;\r\n\r\n\tfor (i = 0; i < numParameters; ++i)\r\n\t{\r\n\t\tfor (j = i; j < numParameters; ++j)\r\n\t\t{\r\n\t\t\tSUM_XiXj[i][j] = SUM_XiXj[i][j]/(double)count - SUM_Xi[i]*SUM_Xi[j];\r\n\t\t\tSUM_XiXj[j][i] = SUM_XiXj[i][j];\r\n\t\t}\r\n\t}\r\n}\r\n\r\n//testing\r\n\r\nint isgood(double * p)\r\n{\r\n\tint numPeaks = 0;\r\n\tint i,k,sz;\r\n\tdouble dt,dx,mu;\r\n\tdouble * y = 0;\r\n\r\n\tassignParameters(p);\r\n\tTCinitialize();\r\n\t\r\n\t//y = ODEsim2(TCvars, TCreactions, TCstoic, &TCpropensity, TCinit, 0, 100, 0.1, 0,0,0,0);\r\n\t//sz = 1000;\r\n\ty = SSA(TCvars, TCreactions, TCstoic, &TCpropensity, TCinit, 0, 100, 100000, &sz, 0,0,0,0) ;\r\n\tif (y)\r\n\t{\r\n\t\tmu = 0.0;\r\n\t\tfor (i = sz/2; i < sz; ++i)\t\t\r\n\t\t\tmu += getValue(y,TCvars+1,i,8);\r\n\t\t\r\n\t\tmu = 2.0*mu/sz;\r\n\t\tdt = sz/100;\r\n\r\n\t\tfor (i=1,k=0; i < sz; ++i)\r\n\t\t{\r\n\t\t\tdx = mu - getValue(y,TCvars+1,i,8);\r\n\t\t\tif ((dx*dx) < 1)\r\n\t\t\t{\r\n\t\t\t\tif (k==0 || (i > k+dt))\r\n\t\t\t\t\t++numPeaks;\r\n\t\t\t\tk = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfree(y);\r\n\t}\r\n\r\n\treturn (int)( sz > 100 && numPeaks > 10 );\r\n}\r\n\r\nvoid randomParams(double * p)\r\n{\r\n\tint i;\r\n\tfor (i=0; i < TCparams; ++i)\r\n\t\tp[i] = mtrand() * pow(2.0,5 * mtrand());\r\n\tp[6] = 4.0*mtrand();\r\n\tp[8] = 4.0*mtrand();\r\n\tp[16] = 4.0*mtrand();\r\n\tp[18] = 4.0*mtrand();\r\n}\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\tdouble * Mu = new double[TCparams];\r\n\tdouble ** Sigma = new double*[TCparams];\r\n\r\n\tfor (int i=0; i < TCparams; ++i)\r\n\t\tSigma[i] = new double[TCparams];\r\n\r\n\tFILE * fout = fopen( \"params.tab\", \"w\" );\r\n\r\n\tsampleParameterSpace(1000000, TCparams ,&randomParams, &isgood, Mu, Sigma);\r\n\r\n\tfprintf(fout, \"\\n\\nMu\\n\\n\");\r\n\r\n\tfor (int i=0; i < TCparams; ++i)\r\n\t{\r\n\t\tfprintf(fout, \"%lf\\t\",Mu[i]);\r\n\t}\r\n\r\n\tfprintf(fout, \"\\n\\nSigma\\n\\n\");\r\n\r\n\tfor (int i=0; i < TCparams; ++i)\r\n\t{\r\n\t\tfor (int j=0; j < TCparams; ++j)\r\n\t\t\tfprintf(fout, \"%lf\\t\",Sigma[i][j]);\r\n\t\tfprintf(fout, \"\\n\");\r\n\t}\r\n\r\n\tfclose(fout);\r\n\r\n\tfor (int i=0; i < TCparams; ++i)\r\n\t\tdelete Sigma[i];\r\n\r\n\tdelete Sigma;\r\n\tdelete Mu;\r\n\r\n\treturn 0;\r\n}\r\n", "meta": {"hexsha": "0907e91d4e65cae160268a469af591b38b5c7d78", "size": 4786, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "parameters/ParameterMC.cpp", "max_stars_repo_name": "dchandran/evolvenetworks", "max_stars_repo_head_hexsha": "072f9e1292552f691a86457ffd16a5743724fb5e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-22T17:17:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-22T17:17:41.000Z", "max_issues_repo_path": "parameters/ParameterMC.cpp", "max_issues_repo_name": "dchandran/evolvenetworks", "max_issues_repo_head_hexsha": "072f9e1292552f691a86457ffd16a5743724fb5e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parameters/ParameterMC.cpp", "max_forks_repo_name": "dchandran/evolvenetworks", "max_forks_repo_head_hexsha": "072f9e1292552f691a86457ffd16a5743724fb5e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7186147186, "max_line_length": 145, "alphanum_fraction": 0.5716673631, "num_tokens": 1630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.4059245779849178}}
{"text": "/* Author: Toby D. Young, Polish Academy of Sciences,             */\n/*         Wolfgang Bangerth, Texas A&M University                */\n/*    $Id: step-36.cc 28237 2013-02-05 16:53:54Z heister $*/\n/*                                                                */\n/*    Copyright (C) 2009, 2011-2012 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n// @sect3{Include files}\n\n// As mentioned in the introduction, this program is essentially only a\n// slightly revised version of step-4. As a consequence, most of the following\n// include files are as used there, or at least as used already in previous\n// tutorial programs:\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/function_parser.h>\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/base/utilities.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/lac/full_matrix.h>\n\n// PETSc appears here because SLEPc depends on this library:\n#include <deal.II/lac/petsc_sparse_matrix.h>\n#include <deal.II/lac/petsc_vector.h>\n\n// And then we need to actually import the interfaces for solvers that SLEPc\n// provides:\n#include <deal.II/lac/slepc_solver.h>\n\n// We also need some standard C++:\n#include <fstream>\n#include <iostream>\n\n// Finally, as in previous programs, we import all the deal.II class and\n// function names into the namespace into which everything in this program\n// will go:\nnamespace Step36\n{\n  using namespace dealii;\n\n  // @sect3{The <code>EigenvalueProblem</code> class template}\n\n  // Following is the class declaration for the main class template. It looks\n  // pretty much exactly like what has already been shown in step-4:\n  template <int dim>\n  class EigenvalueProblem\n  {\n  public:\n    EigenvalueProblem (const std::string &prm_file);\n    void run ();\n\n  private:\n    void make_grid_and_dofs ();\n    void assemble_system ();\n    unsigned int solve ();\n    void output_results () const;\n\n    Triangulation<dim> triangulation;\n    FE_Q<dim>          fe;\n    DoFHandler<dim>    dof_handler;\n\n    // With these exceptions: For our eigenvalue problem, we need both a\n    // stiffness matrix for the left hand side as well as a mass matrix for\n    // the right hand side. We also need not just one solution function, but a\n    // whole set of these for the eigenfunctions we want to compute, along\n    // with the corresponding eigenvalues:\n    PETScWrappers::SparseMatrix        stiffness_matrix, mass_matrix;\n    std::vector<PETScWrappers::Vector> eigenfunctions;\n    std::vector<double>                eigenvalues;\n\n    // And then we need an object that will store several run-time parameters\n    // that we will specify in an input file:\n    ParameterHandler parameters;\n\n    // Finally, we will have an object that contains \"constraints\" on our\n    // degrees of freedom. This could include hanging node constraints if we\n    // had adaptively refined meshes (which we don't have in the current\n    // program). Here, we will store the constraints for boundary nodes\n    // $U_i=0$.\n    ConstraintMatrix constraints;\n  };\n\n  // @sect3{Implementation of the <code>EigenvalueProblem</code> class}\n\n  // @sect4{EigenvalueProblem::EigenvalueProblem}\n\n  // First up, the constructor. The main new part is handling the run-time\n  // input parameters. We need to declare their existence first, and then read\n  // their values from the input file whose name is specified as an argument\n  // to this function:\n  template <int dim>\n  EigenvalueProblem<dim>::EigenvalueProblem (const std::string &prm_file)\n    :\n    fe (1),\n    dof_handler (triangulation)\n  {\n//TODO investigate why the minimum number of refinement steps required to obtain the correct eigenvalue degeneracies is 6\n    parameters.declare_entry (\"Global mesh refinement steps\", \"5\",\n                              Patterns::Integer (0, 20),\n                              \"The number of times the 1-cell coarse mesh should \"\n                              \"be refined globally for our computations.\");\n    parameters.declare_entry (\"Number of eigenvalues/eigenfunctions\", \"5\",\n                              Patterns::Integer (0, 100),\n                              \"The number of eigenvalues/eigenfunctions \"\n                              \"to be computed.\");\n    parameters.declare_entry (\"Potential\", \"0\",\n                              Patterns::Anything(),\n                              \"A functional description of the potential.\");\n\n    parameters.read_input (prm_file);\n  }\n\n\n  // @sect4{EigenvalueProblem::make_grid_and_dofs}\n\n  // The next function creates a mesh on the domain $[-1,1]^d$, refines it as\n  // many times as the input file calls for, and then attaches a DoFHandler to\n  // it and initializes the matrices and vectors to their correct sizes. We\n  // also build the constraints that correspond to the boundary values\n  // $u|_{\\partial\\Omega}=0$.\n  //\n  // For the matrices, we use the PETSc wrappers. These have the ability to\n  // allocate memory as necessary as non-zero entries are added. This seems\n  // inefficient: we could as well first compute the sparsity pattern,\n  // initialize the matrices with it, and as we then insert entries we can be\n  // sure that we do not need to re-allocate memory and free the one used\n  // previously. One way to do that would be to use code like this:\n  // @code\n  //   CompressedSimpleSparsityPattern\n  //      csp (dof_handler.n_dofs(),\n  //           dof_handler.n_dofs());\n  //   DoFTools::make_sparsity_pattern (dof_handler, csp);\n  //   csp.compress ();\n  //   stiffness_matrix.reinit (csp);\n  //   mass_matrix.reinit (csp);\n  // @endcode\n  // instead of the two <code>reinit()</code> calls for the\n  // stiffness and mass matrices below.\n  //\n  // This doesn't quite work, unfortunately. The code above may lead to a few\n  // entries in the non-zero pattern to which we only ever write zero entries;\n  // most notably, this holds true for off-diagonal entries for those rows and\n  // columns that belong to boundary nodes. This shouldn't be a problem, but\n  // for whatever reason, PETSc's ILU preconditioner, which we use to solve\n  // linear systems in the eigenvalue solver, doesn't like these extra entries\n  // and aborts with an error message.\n  //\n  // In the absence of any obvious way to avoid this, we simply settle for the\n  // second best option, which is have PETSc allocate memory as\n  // necessary. That said, since this is not a time critical part, this whole\n  // affair is of no further importance.\n  template <int dim>\n  void EigenvalueProblem<dim>::make_grid_and_dofs ()\n  {\n    GridGenerator::hyper_cube (triangulation, -1, 1);\n    triangulation.refine_global (parameters.get_integer (\"Global mesh refinement steps\"));\n    dof_handler.distribute_dofs (fe);\n\n    DoFTools::make_zero_boundary_constraints (dof_handler, constraints);\n    constraints.close ();\n\n    stiffness_matrix.reinit (dof_handler.n_dofs(),\n                             dof_handler.n_dofs(),\n                             dof_handler.max_couplings_between_dofs());\n    mass_matrix.reinit (dof_handler.n_dofs(),\n                        dof_handler.n_dofs(),\n                        dof_handler.max_couplings_between_dofs());\n\n    // The next step is to take care of the eigenspectrum. In this case, the\n    // outputs are eigenvalues and eigenfunctions, so we set the size of the\n    // list of eigenfunctions and eigenvalues to be as large as we asked for\n    // in the input file:\n    eigenfunctions\n    .resize (parameters.get_integer (\"Number of eigenvalues/eigenfunctions\"));\n    for (unsigned int i=0; i<eigenfunctions.size (); ++i)\n      eigenfunctions[i].reinit (dof_handler.n_dofs ());\n\n    eigenvalues.resize (eigenfunctions.size ());\n  }\n\n\n  // @sect4{EigenvalueProblem::assemble_system}\n\n  // Here, we assemble the global stiffness and mass matrices from local\n  // contributions $A^K_{ij} = \\int_K \\nabla\\varphi_i(\\mathbf x) \\cdot\n  // \\nabla\\varphi_j(\\mathbf x) + V(\\mathbf x)\\varphi_i(\\mathbf\n  // x)\\varphi_j(\\mathbf x)$ and $M^K_{ij} = \\int_K \\varphi_i(\\mathbf\n  // x)\\varphi_j(\\mathbf x)$ respectively. This function should be immediately\n  // familiar if you've seen previous tutorial programs. The only thing new\n  // would be setting up an object that described the potential $V(\\mathbf x)$\n  // using the expression that we got from the input file. We then need to\n  // evaluate this object at the quadrature points on each cell. If you've\n  // seen how to evaluate function objects (see, for example the coefficient\n  // in step-5), the code here will also look rather familiar.\n  template <int dim>\n  void EigenvalueProblem<dim>::assemble_system ()\n  {\n    QGauss<dim>   quadrature_formula(2);\n\n    FEValues<dim> fe_values (fe, quadrature_formula,\n                             update_values | update_gradients |\n                             update_quadrature_points | update_JxW_values);\n\n    const unsigned int dofs_per_cell = fe.dofs_per_cell;\n    const unsigned int n_q_points    = quadrature_formula.size();\n\n    FullMatrix<double> cell_stiffness_matrix (dofs_per_cell, dofs_per_cell);\n    FullMatrix<double> cell_mass_matrix (dofs_per_cell, dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    FunctionParser<dim> potential;\n    potential.initialize (FunctionParser<dim>::default_variable_names (),\n                          parameters.get (\"Potential\"),\n                          typename FunctionParser<dim>::ConstMap());\n\n    std::vector<double> potential_values (n_q_points);\n\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active (),\n    endc = dof_handler.end ();\n    for (; cell!=endc; ++cell)\n      {\n        fe_values.reinit (cell);\n        cell_stiffness_matrix = 0;\n        cell_mass_matrix      = 0;\n\n        potential.value_list (fe_values.get_quadrature_points(),\n                              potential_values);\n\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            for (unsigned int j=0; j<dofs_per_cell; ++j)\n              {\n                cell_stiffness_matrix (i, j)\n                += (fe_values.shape_grad (i, q_point) *\n                    fe_values.shape_grad (j, q_point)\n                    +\n                    potential_values[q_point] *\n                    fe_values.shape_value (i, q_point) *\n                    fe_values.shape_value (j, q_point)\n                   ) * fe_values.JxW (q_point);\n\n                cell_mass_matrix (i, j)\n                += (fe_values.shape_value (i, q_point) *\n                    fe_values.shape_value (j, q_point)\n                   ) * fe_values.JxW (q_point);\n              }\n\n        // Now that we have the local matrix contributions, we transfer them\n        // into the global objects and take care of zero boundary constraints:\n        cell->get_dof_indices (local_dof_indices);\n\n        constraints\n        .distribute_local_to_global (cell_stiffness_matrix,\n                                     local_dof_indices,\n                                     stiffness_matrix);\n        constraints\n        .distribute_local_to_global (cell_mass_matrix,\n                                     local_dof_indices,\n                                     mass_matrix);\n      }\n\n    // At the end of the function, we tell PETSc that the matrices have now\n    // been fully assembled and that the sparse matrix representation can now\n    // be compressed as no more entries will be added:\n    stiffness_matrix.compress ();\n    mass_matrix.compress ();\n  }\n\n\n  // @sect4{EigenvalueProblem::solve}\n\n  // This is the key new functionality of the program. Now that the system is\n  // set up, here is a good time to actually solve the problem: As with other\n  // examples this is done using a \"solve\" routine. Essentially, it works as\n  // in other programs: you set up a SolverControl object that describes the\n  // accuracy to which we want to solve the linear systems, and then we select\n  // the kind of solver we want. Here we choose the Krylov-Schur solver of\n  // SLEPc, a pretty fast and robust choice for this kind of problem:\n  template <int dim>\n  unsigned int EigenvalueProblem<dim>::solve ()\n  {\n\n    // We start here, as we normally do, by assigning convergence control we\n    // want:\n    SolverControl solver_control (dof_handler.n_dofs(), 1e-9);\n    SLEPcWrappers::SolverKrylovSchur eigensolver (solver_control);\n\n    // Before we actually solve for the eigenfunctions and -values, we have to\n    // also select which set of eigenvalues to solve for. Lets select those\n    // eigenvalues and corresponding eigenfunctions with the smallest real\n    // part (in fact, the problem we solve here is symmetric and so the\n    // eigenvalues are purely real). After that, we can actually let SLEPc do\n    // its work:\n    eigensolver.set_which_eigenpairs (EPS_SMALLEST_REAL);\n\n    eigensolver.solve (stiffness_matrix, mass_matrix,\n                       eigenvalues, eigenfunctions,\n                       eigenfunctions.size());\n\n    // The output of the call above is a set of vectors and values. In\n    // eigenvalue problems, the eigenfunctions are only determined up to a\n    // constant that can be fixed pretty arbitrarily. Knowing nothing about\n    // the origin of the eigenvalue problem, SLEPc has no other choice than to\n    // normalize the eigenvectors to one in the $l_2$ (vector)\n    // norm. Unfortunately this norm has little to do with any norm we may be\n    // interested from a eigenfunction perspective: the $L_2(\\Omega)$ norm, or\n    // maybe the $L_\\infty(\\Omega)$ norm.\n    //\n    // Let us choose the latter and rescale eigenfunctions so that they have\n    // $\\|\\phi_i(\\mathbf x)\\|_{L^\\infty(\\Omega)}=1$ instead of\n    // $\\|\\Phi\\|_{l_2}=1$ (where $\\phi_i$ is the $i$th eigen<i>function</i>\n    // and $\\Phi_i$ the corresponding vector of nodal values). For the $Q_1$\n    // elements chosen here, we know that the maximum of the function\n    // $\\phi_i(\\mathbf x)$ is attained at one of the nodes, so $\\max_{\\mathbf\n    // x}\\phi_i(\\mathbf x)=\\max_j (\\Phi_i)_j$, making the normalization in the\n    // $L_\\infty$ norm trivial. Note that this doesn't work as easily if we\n    // had chosen $Q_k$ elements with $k>1$: there, the maximum of a function\n    // does not necessarily have to be attained at a node, and so\n    // $\\max_{\\mathbf x}\\phi_i(\\mathbf x)\\ge\\max_j (\\Phi_i)_j$ (although the\n    // equality is usually nearly true).\n    for (unsigned int i=0; i<eigenfunctions.size(); ++i)\n      eigenfunctions[i] /= eigenfunctions[i].linfty_norm ();\n\n    // Finally return the number of iterations it took to converge:\n    return solver_control.last_step ();\n  }\n\n\n  // @sect4{EigenvalueProblem::output_results}\n\n  // This is the last significant function of this program. It uses the\n  // DataOut class to generate graphical output from the eigenfunctions for\n  // later visualization. It works as in many of the other tutorial programs.\n  //\n  // The whole collection of functions is then output as a single VTK file.\n  template <int dim>\n  void EigenvalueProblem<dim>::output_results () const\n  {\n    DataOut<dim> data_out;\n\n    data_out.attach_dof_handler (dof_handler);\n\n    for (unsigned int i=0; i<eigenfunctions.size(); ++i)\n      data_out.add_data_vector (eigenfunctions[i],\n                                std::string(\"eigenfunction_\") +\n                                Utilities::int_to_string(i));\n\n    // The only thing worth discussing may be that because the potential is\n    // specified as a function expression in the input file, it would be nice\n    // to also have it as a graphical representation along with the\n    // eigenfunctions. The process to achieve this is relatively\n    // straightforward: we build an object that represents $V(\\mathbf x)$ and\n    // then we interpolate this continuous function onto the finite element\n    // space. The result we also attach to the DataOut object for\n    // visualization.\n    Vector<double> projected_potential (dof_handler.n_dofs());\n    {\n      FunctionParser<dim> potential;\n      potential.initialize (FunctionParser<dim>::default_variable_names (),\n                            parameters.get (\"Potential\"),\n                            typename FunctionParser<dim>::ConstMap());\n      VectorTools::interpolate (dof_handler, potential, projected_potential);\n    }\n    data_out.add_data_vector (projected_potential, \"interpolated_potential\");\n\n    data_out.build_patches ();\n\n    std::ofstream output (\"eigenvectors.vtk\");\n    data_out.write_vtk (output);\n  }\n\n\n  // @sect4{EigenvalueProblem::run}\n\n  // This is the function which has the top-level control over everything. It\n  // is almost exactly the same as in step-4:\n  template <int dim>\n  void EigenvalueProblem<dim>::run ()\n  {\n    make_grid_and_dofs ();\n\n    std::cout << \"   Number of active cells:       \"\n              << triangulation.n_active_cells ()\n              << std::endl\n              << \"   Number of degrees of freedom: \"\n              << dof_handler.n_dofs ()\n              << std::endl;\n\n    assemble_system ();\n\n    const unsigned int n_iterations = solve ();\n    std::cout << \"   Solver converged in \" << n_iterations\n              << \" iterations.\" << std::endl;\n\n    output_results ();\n\n    std::cout << std::endl;\n    for (unsigned int i=0; i<eigenvalues.size(); ++i)\n      std::cout << \"      Eigenvalue \" << i\n                << \" : \" << eigenvalues[i]\n                << std::endl;\n  }\n}\n\n// @sect3{The <code>main</code> function}\nint main (int argc, char **argv)\n{\n  try\n    {\n\n      // Here is another difference from other steps: We initialize the SLEPc\n      // work space which inherently initializes the PETSc work space, then go\n      // ahead run the whole program. After that is done, we finalize the\n      // SLEPc-PETSc work.\n      SlepcInitialize (&argc, &argv, 0, 0);\n\n      {\n        using namespace dealii;\n        using namespace Step36;\n\n        deallog.depth_console (0);\n\n        EigenvalueProblem<2> problem (\"step-36.prm\");\n        problem.run ();\n      }\n\n      SlepcFinalize ();\n    }\n\n  // All the while, we are watching out if any exceptions should have been\n  // generated. If that is so, we panic...\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  // If no exceptions are thrown, then we tell the program to stop monkeying\n  // around and exit nicely:\n  std::cout << std::endl\n            << \"   Job done.\"\n            << std::endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "aae8cdadeb7a00b5e75cbee3a882aa038c5ea6a4", "size": 20027, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-36/step-36.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/step-36/step-36.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/step-36/step-36.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 41.3780991736, "max_line_length": 121, "alphanum_fraction": 0.6391371648, "num_tokens": 4707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.40592457179671804}}
{"text": "#include <cmath>\r\n#include <aslam/backend/util/utils.hpp>\r\n#include <aslam/backend/LineSearch.hpp>\r\n#include <Eigen/Dense>\r\n#include <sm/eigen/assert_macros.hpp>\r\n#include <sm/PropertyTree.hpp>\r\n#include <sm/logging.hpp>\r\n\r\n/*\r\nMost of the following is a c++ translations of code from https://github.com/scipy/scipy/blob/master/scipy/optimize/linesearch.py,\r\nthe function dcstep is based on https://github.com/scipy/scipy/blob/master/scipy/optimize/minpack2/dcstep.f,\r\nthe class Dcsrch is based on https://github.com/scipy/scipy/blob/master/scipy/optimize/minpack2/dcsrch.f .\r\n\r\nFor those parts the following license applies:\r\n\r\nSciPy project (http://www.scipy.org/):\r\n\r\nCopyright (c) 2001, 2002 Enthought, Inc.\r\nAll rights reserved.\r\n\r\nCopyright (c) 2003-2016 SciPy Developers.\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions are met:\r\n\r\n  a. Redistributions of source code must retain the above copyright notice,\r\n     this list of conditions and the following disclaimer.\r\n  b. Redistributions in binary form must reproduce the above copyright\r\n     notice, this list of conditions and the following disclaimer in the\r\n     documentation and/or other materials provided with the distribution.\r\n  c. Neither the name of Enthought nor the names of the SciPy Developers\r\n     may be used to endorse or promote products derived from this software\r\n     without specific prior written permission.\r\n\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS\r\nBE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\r\nOR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\r\nTHE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n*/\r\n\r\nusing namespace std;\r\n\r\nnamespace aslam {\r\nnamespace backend {\r\n\r\nusing std::isnan;\r\n\r\nvoid dcstep(double& stx, double& fx, double& dx, double& sty, double& fy, double& dy, double& stp,\r\n            const double fp, const double dp, bool& brackt, const double stpmin, const double stpmax) {\r\n\r\n  double sgnd = dp*(utils::sign(dx));\r\n  double stpf;\r\n\r\n  // First case: A higher function value. The minimum is bracketed.\r\n  // If the cubic step is closer to stx than the quadratic step, the\r\n  // cubic step is taken, otherwise the average of the cubic and\r\n  // quadratic steps is taken.\r\n  if (fp > fx) {\r\n\r\n    const double theta = 3.0*(fx-fp)/(stp-stx) + dx + dp;\r\n    const double s = max(abs(theta), max(abs(dx), abs(dp)));\r\n    const double srec = 1./s;\r\n    double gamma = s*sqrt(utils::sqr(theta*srec)-(dx*srec)*(dp*srec));\r\n    if (stp < stx)\r\n        gamma = -gamma;\r\n    const double p = (gamma-dx) + theta;\r\n    const double q = ((gamma-dx)+gamma) + dp;\r\n    const double r = p/q;\r\n    const double stpc = stx + r*(stp-stx);\r\n    const double stpq = stx + ((dx/((fx-fp)/(stp-stx)+dx))/2.0)*(stp-stx);\r\n    if (abs(stpc-stx) < abs(stpq-stx))\r\n      stpf = stpc;\r\n    else\r\n      stpf = stpc + (stpq-stpc)/2.0;\r\n\r\n    brackt = true;\r\n\r\n  // Second case: A lower function value and derivatives of opposite\r\n  // sign. The minimum is bracketed. If the cubic step is farther from\r\n  // stp than the secant step, the cubic step is taken, otherwise the\r\n  // secant step is taken.\r\n  } else if (sgnd < 0.0) {\r\n\r\n    const double theta = 3.0*(fx-fp)/(stp-stx) + dx + dp;\r\n    const double s = max(abs(theta), max(abs(dx), abs(dp)));\r\n    const double srec = 1./s;\r\n    double gamma = s*sqrt(utils::sqr(theta*srec)-(dx*srec)*(dp*srec));\r\n    if (stp > stx)\r\n      gamma = -gamma;\r\n    const double p = (gamma-dp) + theta;\r\n    const double q = ((gamma-dp)+gamma) + dx;\r\n    const double r = p/q;\r\n    const double stpc = stp + r*(stx-stp);\r\n    const double stpq = stp + (dp/(dp-dx))*(stx-stp);\r\n    if (abs(stpc-stp) > abs(stpq-stp))\r\n      stpf = stpc;\r\n    else\r\n      stpf = stpq;\r\n    brackt = true;\r\n\r\n  // Third case: A lower function value, derivatives of the same sign,\r\n  // and the magnitude of the derivative decreases.\r\n  } else if (abs(dp) < abs(dx)) {\r\n\r\n      // The cubic step is computed only if the cubic tends to infinity\r\n      // in the direction of the step or if the minimum of the cubic\r\n      // is beyond stp. Otherwise the cubic step is defined to be the\r\n      // secant step.\r\n      const double theta = 3.0*(fx-fp)/(stp-stx) + dx + dp;\r\n      const double s = max(abs(theta), max(abs(dx), abs(dp)));\r\n\r\n      // The case gamma = 0 only arises if the cubic does not tend\r\n      // to infinity in the direction of the step.\r\n      const double srec = 1./s;\r\n      double gamma = s*sqrt(max(0.0, utils::sqr(theta*srec)-(dx*srec)*(dp*srec)));\r\n      if (stp > stx)\r\n        gamma = -gamma;\r\n      const double p = (gamma-dp) + theta;\r\n      const double q = (gamma+(dx-dp)) + gamma;\r\n      const double r = p/q;\r\n      double stpc;\r\n      if (r < 0.0 and gamma != 0.0)\r\n        stpc = stp + r*(stx-stp);\r\n      else if (stp > stx)\r\n        stpc = stpmax;\r\n      else\r\n        stpc = stpmin;\r\n\r\n      const double stpq = stp + (dp/(dp-dx))*(stx-stp);\r\n\r\n      if (brackt) {\r\n\r\n        // A minimizer has been bracketed. If the cubic step is\r\n        // closer to stp than the secant step, the cubic step is\r\n        // taken, otherwise the secant step is taken.\r\n\r\n        if (abs(stpc-stp) < abs(stpq-stp))\r\n          stpf = stpc;\r\n        else\r\n          stpf = stpq;\r\n\r\n        if (stp > stx)\r\n          stpf = min(stp+0.66*(sty-stp),stpf);\r\n        else\r\n          stpf = max(stp+0.66*(sty-stp),stpf);\r\n\r\n      } else {\r\n\r\n        // A minimizer has not been bracketed. If the cubic step is\r\n        // farther from stp than the secant step, the cubic step is\r\n        // taken, otherwise the secant step is taken.\r\n\r\n        if (abs(stpc-stp) > abs(stpq-stp))\r\n          stpf = stpc;\r\n        else\r\n          stpf = stpq;\r\n\r\n        stpf = max( min(stpmax,stpf), stpmin);\r\n      }\r\n\r\n  // Fourth case: A lower function value, derivatives of the same sign,\r\n  // and the magnitude of the derivative does not decrease. If the\r\n  // minimum is not bracketed, the step is either stpmin or stpmax,\r\n  // otherwise the cubic step is taken.\r\n  } else {\r\n\r\n    if (brackt) {\r\n      const double theta = 3.0*(fp-fy)/(sty-stp) + dy + dp;\r\n      const double s = max(abs(theta), max(abs(dy), abs(dp)));\r\n      const double srec = 1./s;\r\n      double gamma = s*sqrt(utils::sqr(theta*srec)-(dy*srec)*(dp*srec));\r\n      if (stp > sty)\r\n          gamma = -gamma;\r\n      const double p = (gamma-dp) + theta;\r\n      const double q = ((gamma-dp)+gamma) + dy;\r\n      const double r = p/q;\r\n      const double stpc = stp + r*(sty-stp);\r\n      stpf = stpc;\r\n\r\n    } else if (stp > stx) {\r\n      stpf = stpmax;\r\n    } else {\r\n      stpf = stpmin;\r\n    }\r\n  }\r\n\r\n  // Update the interval which contains a minimizer.\r\n  if (fp > fx) {\r\n    sty = stp;\r\n    fy = fp;\r\n    dy = dp;\r\n  } else {\r\n    if (sgnd < 0) {\r\n      sty = stx;\r\n      fy = fx;\r\n      dy = dx;\r\n    }\r\n\r\n    stx = stp;\r\n    fx = fp;\r\n    dx = dp;\r\n  }\r\n\r\n  // Compute the new step.\r\n  stp = stpf;\r\n}\r\n\r\n\r\ndouble cubicMin(double a, double fa, double fpa, double b, double fb, double c, double fc) {\r\n  const double db = b - a;\r\n  const double dc = c - a;\r\n  const double denom = utils::sqr(db * dc) * (db - dc);\r\n  Eigen::Matrix2d d1;\r\n  d1(0,0) = utils::sqr(dc);\r\n  d1(0,1) = -utils::sqr(db);\r\n  d1(1,0) = -d1(0,0)*dc;\r\n  d1(1,1) = -d1(0,1)*db;\r\n  Eigen::Vector2d AB = d1*(Eigen::Vector2d(fb - fa - fpa * db, fc - fa - fpa * dc))/denom;\r\n  const double radical = utils::sqr((double)AB[1]) - 3.0 * AB[0] * fpa;\r\n  return a + (-AB[1] + sqrt(radical)) / (3.0 * AB[0]);\r\n}\r\n\r\ndouble quadMin(double a, double fa, double fpa, double b, double fb) {\r\n  const double db = b - a;\r\n  const double B = (fb - fa - fpa * db) / utils::sqr(db);\r\n  return a - 0.5 * fpa / B;\r\n}\r\n\r\n\r\nDcsrch::Dcsrch(double stepLengthInit, double error, double errorDerivative, double minStepLength, double maxStepLength, double ftol, double xtol, double gtol) :\r\n    _xtol(xtol),\r\n    _ftol (ftol),\r\n    _gtol(gtol),\r\n    _minStepLength(minStepLength),\r\n    _maxStepLength(maxStepLength),\r\n    _stepLength(stepLengthInit),\r\n    _finit(error),\r\n    _fx(error),\r\n    _fy(error),\r\n    _ginit(errorDerivative),\r\n    _gtest(_ftol*_ginit),\r\n    _ginitTimesNegGtol(-_gtol*_ginit),\r\n    _gx(errorDerivative),\r\n    _gy(errorDerivative),\r\n    _stmax(stepLengthInit + _xtrapu*stepLengthInit),\r\n    _width(maxStepLength - minStepLength),\r\n    _width1(_width*2.0)\r\n{\r\n\r\n  SM_ASSERT_GT_DBG(Exception, _xtol, 0.0, \"\");\r\n  SM_ASSERT_GT_DBG(Exception, _ftol, 0.0, \"\");\r\n  SM_ASSERT_GT_DBG(Exception, _gtol, 0.0, \"\");\r\n  SM_ASSERT_GT_DBG(Exception, _minStepLength, 0.0, \"\");\r\n  SM_ASSERT_GT_DBG(Exception, _maxStepLength, 0.0, \"\");\r\n\r\n  SM_ASSERT_LT(Exception, errorDerivative, 0.0, \"\");\r\n\r\n  SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"Dcsrch: initial interval: [\" << _stx << \", \" << _sty << \"], step length: \" << _stepLength);\r\n\r\n}\r\n\r\ndouble Dcsrch::updateStepLength(double error, double errorDerivative) {\r\n\r\n  if (_stage == 0) {\r\n    _stage++;\r\n    return _stepLength;\r\n  }\r\n\r\n  // If psi(stepLength) <= 0 and f'(stepLength) >= 0 for some step, then the\r\n  // algorithm enters the second stage.\r\n  const double ftest = _finit + _stepLength*_gtest;\r\n  if (_stage == 1 && error <= ftest && errorDerivative >= 0.0)\r\n    _stage = 2;\r\n\r\n  SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: dcsrch -- stage: \" << _stage << \", ftest: \" << ftest <<\r\n                      \", minimum step length: \" << _stmin << \", maximum step length: \" << _stmax);\r\n\r\n  // Test for warnings.\r\n  if (_brackt && (_stepLength <= _stmin || _stepLength >= _stmax)) {\r\n    SM_WARN_STREAM(setprecision(20) << \"LineSearch: dcsrch -- Rounding errors prevent progress: step length \" << _stepLength <<\r\n            \" outside interval (\" << _stmin << \", \" << _stmax << \")\");\r\n    _status = WARNING;\r\n  }\r\n  if (_brackt && _stmax-_stmin <= _xtol*_stmax) {\r\n    SM_WARN_STREAM(setprecision(20) << \"LineSearch: dcsrch -- xtol test satisfied: \" << (_stmax-_stmin) << \" <= \" << _xtol*_stmax);\r\n    _status = WARNING;\r\n  }\r\n  if (_stepLength == _maxStepLength && error <= ftest && errorDerivative <= _gtest) {\r\n    SM_WARN(\"LineSearch: dcsrch -- step length reached maximum step length\");\r\n    _status = WARNING;\r\n  }\r\n  if (_stepLength == _minStepLength && (error > ftest || errorDerivative >= _gtest)) {\r\n    SM_WARN(\"LineSearch: dcsrch -- step length reached minimum step length\");\r\n    _status = WARNING;\r\n  }\r\n\r\n  // Test for convergence.\r\n  if (error <= ftest) {\r\n\r\n    SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: dcsrch -- sufficient decrease condition satisfied: \" << error << \" <= \" << ftest);\r\n\r\n    if (abs(errorDerivative) <= _ginitTimesNegGtol)\r\n      _status = CONVERGED;\r\n    else\r\n      SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: dcsrch -- curvature condition not satisfied: \" << abs(errorDerivative) << \" <= \" << _ginitTimesNegGtol);\r\n\r\n  } else {\r\n    SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: dcsrch -- sufficient decrease condition not satisfied: \" << error << \" <= \" << ftest);\r\n  }\r\n\r\n  // Test for termination.\r\n  if (_status == WARNING || _status == CONVERGED)\r\n    return _stepLength;\r\n\r\n  // A modified function is used to predict the step during the\r\n  // first stage if a lower function value has been obtained but\r\n  // the decrease is not sufficient.\r\n  if (_stage == 1 && error <= _fx && error > ftest) {\r\n\r\n    // Define the modified function and derivative values.\r\n    const double fm = error - _stepLength*_gtest;\r\n    double fxm = _fx - _stx*_gtest;\r\n    double fym = _fy - _sty*_gtest;\r\n    double gm = errorDerivative - _gtest;\r\n    double gxm = _gx - _gtest;\r\n    double gym = _gy - _gtest;\r\n\r\n    // Call dcstep to update stx, sty, and to compute the new step.\r\n    dcstep(_stx, fxm, gxm, _sty, fym, gym, _stepLength, fm, gm, _brackt, _stmin, _stmax);\r\n\r\n    // Reset the function and derivative values for error.\r\n    _fx = fxm + _stx*_gtest;\r\n    _fy = fym + _sty*_gtest;\r\n    _gx = gxm + _gtest;\r\n    _gy = gym + _gtest;\r\n\r\n  } else {\r\n    // Call dcstep to update stx, sty, and to compute the new step.\r\n    dcstep(_stx, _fx, _gx, _sty, _fy, _gy, _stepLength, error, errorDerivative, _brackt, _stmin, _stmax);\r\n  }\r\n\r\n  // Decide if a bisection step is needed.\r\n  if (_brackt) {\r\n    const double dstxy = _sty - _stx;\r\n    const double absdstxy = abs(dstxy);\r\n    if (absdstxy >= 0.66 * _width1)\r\n      _stepLength = _stx + 0.5*dstxy;\r\n    _width1 = _width;\r\n    _width = absdstxy;\r\n  }\r\n\r\n  // Set the minimum and maximum steps allowed for stepLength.\r\n  if (_brackt) {\r\n    _stmin = min(_stx,_sty);\r\n    _stmax = max(_stx,_sty);\r\n  } else {\r\n    const double dstpx = _stepLength - _stx;\r\n    _stmin = _stepLength + _xtrapl*dstpx;\r\n    _stmax = _stepLength + _xtrapu*dstpx;\r\n  }\r\n\r\n  // Force the step to be within the bounds.\r\n  _stepLength = min( max(_stepLength, _minStepLength), _maxStepLength);\r\n\r\n  // If further progress is not possible, let stepLength be the best\r\n  // point obtained during the search.\r\n  if ((_brackt && (_stepLength <= _minStepLength || _stepLength >= _maxStepLength)) ||\r\n      (_brackt && _maxStepLength-_minStepLength <= _xtol*_maxStepLength))\r\n    _stepLength = _stx;\r\n\r\n  SM_ALL_STREAM_NAMED(\"optimization.linesearch\", \"Dcsrch: new interval: [\" << _stx << \", \" << _sty << \"], step length = \" << _stepLength);\r\n\r\n  return _stepLength;\r\n}\r\n\r\n\r\n\r\nLineSearchOptions::LineSearchOptions() {\r\n  check();\r\n}\r\n\r\nLineSearchOptions::LineSearchOptions(const sm::PropertyTree& config)\r\n{\r\n  c1WolfeCondition = config.getDouble(\"c1WolfeCondition\", c1WolfeCondition);\r\n  c2WolfeCondition = config.getDouble(\"c2WolfeCondition\", c2WolfeCondition);\r\n  maxStepLength = config.getDouble(\"maxStepLength\", maxStepLength);\r\n  minStepLength = config.getDouble(\"minStepLength\", minStepLength);\r\n  xtol = config.getDouble(\"xtol\", xtol);\r\n  initialStepLength = config.getDouble(\"initialStepLength\", initialStepLength);\r\n  nMaxIterWolfe1 = config.getInt(\"nMaxIterWolfe1\", nMaxIterWolfe1);\r\n  nMaxIterWolfe2 = config.getInt(\"nMaxIterWolfe2\", nMaxIterWolfe2);\r\n  nMaxIterZoom = config.getInt(\"nMaxIterZoom\", nMaxIterZoom);\r\n  check();\r\n}\r\n\r\nvoid LineSearchOptions::check() const {\r\n  SM_ASSERT_GE(Exception, c1WolfeCondition, 0.0, \"\");\r\n  SM_ASSERT_GE(Exception, c2WolfeCondition, c1WolfeCondition, \"\");\r\n  SM_ASSERT_GE(Exception, maxStepLength, 0.0, \"\");\r\n  SM_ASSERT_GE(Exception, minStepLength, 0.0, \"\");\r\n  SM_ASSERT_GE(Exception, xtol, 0.0, \"\");\r\n  SM_ASSERT_GT(Exception, initialStepLength, 0.0, \"\");\r\n  SM_ASSERT_GT(Exception, nMaxIterWolfe1, 0, \"\");\r\n  SM_ASSERT_GT(Exception, nMaxIterWolfe2, 0, \"\");\r\n  SM_ASSERT_GT(Exception, nMaxIterZoom, 0, \"\");\r\n}\r\n\r\nostream& operator<<(ostream& out, const aslam::backend::LineSearchOptions& options)\r\n{\r\n  out << \"LineSearchOptions:\\n\";\r\n  out << \"\\tc1WolfeCondition: \" << options.c1WolfeCondition << endl;\r\n  out << \"\\tc1WolfeCondition: \" << options.c1WolfeCondition << endl;\r\n  out << \"\\tc2WolfeCondition: \" << options.c2WolfeCondition << endl;\r\n  out << \"\\tmaxStepLength: \" << options.maxStepLength << endl;\r\n  out << \"\\tminStepLength: \" << options.minStepLength << endl;\r\n  out << \"\\txtol: \" << options.xtol << endl;\r\n  out << \"\\tinitialStepLength: \" << options.initialStepLength << endl;\r\n  out << \"\\tnMaxIterWolfe1: \" << options.nMaxIterWolfe1 << endl;\r\n  out << \"\\tnMaxIterWolfe2: \" << options.nMaxIterWolfe2 << endl;\r\n  out << \"\\tnMaxIterZoom: \" << options.nMaxIterZoom;\r\n  return out;\r\n}\r\n\r\n\r\nLineSearch::LineSearch(const boost::shared_ptr<CostFunctionInterface>& cf, const LineSearchOptions& options) :\r\n    _costFunction(cf),\r\n    _options(options)\r\n{\r\n  SM_ASSERT_TRUE(Exception, cf != nullptr, \"\");\r\n  _options.check();\r\n}\r\n\r\nLineSearch::LineSearch(const boost::shared_ptr<CostFunctionInterface>& cf) :\r\n    LineSearch::LineSearch(cf, LineSearchOptions())\r\n{\r\n}\r\n\r\nLineSearch::LineSearch(const boost::shared_ptr<CostFunctionInterface>& cf, const sm::PropertyTree& config) :\r\n    LineSearch::LineSearch(cf, LineSearchOptions(config))\r\n{\r\n}\r\n\r\nLineSearch::~LineSearch()\r\n{\r\n\r\n}\r\n\r\n\r\nvoid LineSearch::initialize(boost::optional<const RowVectorType&> searchDirection /*= boost::optional<const RowVectorType&>()*/,\r\n                            boost::optional<double> error /*= boost::optional<double>()*/,\r\n                            boost::optional<const RowVectorType&> gradient /*= boost::optional<const RowVectorType&>()*/)\r\n{\r\n  _stepLength = 0.0;\r\n  _errorOutdated = _derrorOutdated = true;\r\n  _errorOld = std::numeric_limits<double>::signaling_NaN();\r\n\r\n  if (error)\r\n    _error = error.get();\r\n  else\r\n    this->updateError();\r\n  _errorOutdated = false;\r\n\r\n  if (gradient)\r\n    _gradient = gradient.get();\r\n  else\r\n    this->updateGradient();\r\n\r\n  if (searchDirection)\r\n    this->setSearchDirection(searchDirection.get());\r\n  else\r\n    _searchDirection = RowVectorType::Zero(0);\r\n\r\n}\r\n\r\n\r\nvoid LineSearch::setSearchDirection(const RowVectorType& searchDirection) {\r\n  using namespace Eigen;\r\n  _stepLength = 0.0; // if the search direction changed, we must avoid skipping updates with same step lengths\r\n  _searchDirection = searchDirection;\r\n  _derror = computeErrorDerivative();\r\n  _derrorOutdated = false;\r\n  SM_VERBOSE_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: set search direction to \" << _searchDirection.format(IOFormat(15, DontAlignCols, \", \", \", \", \"\", \"\", \"[\", \"]\")));\r\n  SM_VERBOSE_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: computed error derivative \" << _derror);\r\n  SM_ASSERT_LE(Exception, _derror, 0.0, \"Wrong search direction supplied! In case approximate Hessian information is used, \"\r\n      \"this could mean your Hessian estimate became negative\");\r\n}\r\n\r\n\r\nvoid LineSearch::applyStateUpdate(const double s) {\r\n\r\n  using namespace Eigen;\r\n  static IOFormat fmt(15, 0, \", \", \", \", \"\", \"\", \"[\", \"]\");\r\n\r\n  double ds = s - _stepLength;\r\n  _stepLength = s;\r\n\r\n  if (ds != 0.0) { // save computation time\r\n    Eigen::RowVectorXd p = sm::logging::getLevel() <= sm::logging::Level::Verbose ?\r\n        utils::getFlattenedDesignVariableParameters(_costFunction->getDesignVariables()).transpose() :  Eigen::RowVectorXd();\r\n    utils::applyStateUpdate(_costFunction->getDesignVariables(), ds*_searchDirection);\r\n    _errorOutdated = _derrorOutdated = true;\r\n    SM_VERBOSE_STREAM_NAMED(\"optimization.linesearch\", \"LineSearch: update step length \" << s - ds << \" -> \" << _stepLength << \" (ds: \" << ds<< \")\");\r\n    SM_VERBOSE_STREAM_NAMED(\"optimization.linesearch\", \"LineSearch: update state\" << std::endl <<\r\n                            \"Old  : \" << p.format(fmt) << std::endl <<\r\n                            \"New  : \" << utils::getFlattenedDesignVariableParameters(_costFunction->getDesignVariables()).transpose().format(fmt) << std::endl <<\r\n                            \"Delta: \" << (utils::getFlattenedDesignVariableParameters(_costFunction->getDesignVariables()).transpose() - p).format(fmt));\r\n  } else {\r\n    SM_ALL_NAMED(\"optimization.linesearch\", \"LineSearch: skipping unnecessary update of information\");\r\n  }\r\n}\r\n\r\n\r\nvoid LineSearch::updateError() {\r\n  if (_errorOutdated) {\r\n    const double errorOld = _error;\r\n    _error = _costFunction->evaluateError();\r\n    if (_evalErrorCallback) _evalErrorCallback();\r\n    SM_VERBOSE_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: update error \" << errorOld << \" -> \" << _error << \" (\" << _error - errorOld << \")\");\r\n  }\r\n  _errorOutdated = false;\r\n}\r\n\r\nvoid LineSearch::updateGradient() {\r\n  _costFunction->computeGradient(_gradient);\r\n  if (_evalGradCallback) _evalGradCallback();\r\n}\r\n\r\nvoid LineSearch::updateErrorDerivative() {\r\n  if (_derrorOutdated) {\r\n    const double dErrorOld = _derror;\r\n    this->updateGradient();\r\n    _derror = computeErrorDerivative();\r\n    SM_VERBOSE_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: update error derivative \"<< dErrorOld << \" -> \" << _derror << \" (\" << _derror - dErrorOld << \")\");\r\n  }\r\n  _derrorOutdated = false;\r\n}\r\n\r\nbool LineSearch::zoom(double minStepSize, double maxStepSize, double error_lo, double error_hi, double derror_lo, double error0, double derror0) {\r\n\r\n  size_t i = 0;\r\n  const double delta1 = 0.2;  // cubic interpolant check\r\n  const double delta2 = 0.1;  // quadratic interpolant check\r\n  double error_rec = error0;\r\n  double stepSize_rec = 0.0;\r\n\r\n  while (true) {\r\n    // Interpolate to find a trial step length between a_lo and a_hi.\r\n    // Use cubic interpolation in the first step.\r\n    // If the result is within delta * dalpha or outside of the bounded interval defined by a_lo or a_hi use quadratic interpolation.\r\n    // If the result is still too close, then use bisection\r\n\r\n    const double dStepLength = maxStepSize - minStepSize;\r\n    double a, b;\r\n    if (dStepLength < 0.0) {\r\n      a = maxStepSize;\r\n      b = minStepSize;\r\n    } else {\r\n      a = minStepSize;\r\n      b = maxStepSize;\r\n    }\r\n\r\n    // Try cubic interpolation\r\n    double cubicchk;\r\n    double stepSize_j = numeric_limits<double>::signaling_NaN();\r\n    if (i > 0) {\r\n      cubicchk = delta1 * dStepLength;\r\n      stepSize_j = cubicMin(minStepSize, error_lo, derror_lo, maxStepSize, error_hi, stepSize_rec, error_rec);\r\n      SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: zoom -- cubic interpolation through points [\" << minStepSize <<\r\n                          \", \" << maxStepSize << \", \" << stepSize_rec << \"] with errors \" << \"[\" << error_lo << \", \" << error_hi << \", \" << error_rec <<\r\n                          \"] and derivative at lower interval point \" << derror_lo << \" returned step length \" << stepSize_j);\r\n    }\r\n\r\n    // Try quadratic interpolation\r\n    if (i == 0 || isnan(stepSize_j) || stepSize_j > b - cubicchk || stepSize_j < a + cubicchk) {\r\n      const double quadchk = delta2 * dStepLength;\r\n      stepSize_j = quadMin(minStepSize, error_lo, derror_lo, maxStepSize, error_hi);\r\n      SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: zoom -- quadratic interpolation through points [\" << minStepSize <<\r\n                          \", \" << maxStepSize << \"] with errors \" << \"[\" << error_lo << \", \" << error_hi << \"] and derivative at lower interval point \" <<\r\n                          derror_lo << \" returned step length \" << stepSize_j);\r\n      if (isnan(stepSize_j) || stepSize_j > b - quadchk || stepSize_j < a + quadchk)\r\n        stepSize_j = minStepSize + 0.5*dStepLength;\r\n    }\r\n\r\n    // Move state to stepSize_j, do not compute gradient information at new point yet since\r\n    // we have to check first whether the error decreased. If not, there's no need to compute the gradient.\r\n    this->applyStateUpdate(stepSize_j);\r\n    this->updateError();\r\n\r\n    // Check new value of stepSize_j\r\n    const double error_j = getError();\r\n\r\n    // Check Wolfe condition 1 (Armijo rule)\r\n    if ((error_j > error0 + _options.c1WolfeCondition*stepSize_j*derror_lo) or (error_j >= error_lo)) {\r\n      // If condition is not satisfied, set endpoint of interval to new point stepSize_j\r\n      error_rec = error_hi;\r\n      stepSize_rec = maxStepSize;\r\n      maxStepSize = stepSize_j;\r\n      error_hi = error_j;\r\n      SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: zoom -- sufficient decrease condition not satisfied: \" << error_j << \" <= \" << error0 + _options.c1WolfeCondition*stepSize_j*derror_lo);\r\n    } else {\r\n      SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: zoom -- sufficient decrease condition satisfied: \" << error_j << \" <= \" << error0 + _options.c1WolfeCondition*stepSize_j*derror_lo);\r\n      // If Armijo rule is satisfied, also check curvature condition.\r\n      // Therefore we have to update the gradient based information now.\r\n      this->updateErrorDerivative();\r\n      const double derror_j = getErrorDerivative();\r\n      if (abs(derror_j) <= -_options.c2WolfeCondition*derror0)  { // If curvature condition is satisfied, we found a suitable point\r\n        SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: zoom -- curvature condition satisfied: \" << abs(derror_j) << \" <= \" << -_options.c2WolfeCondition*derror0);\r\n        break;\r\n      }\r\n\r\n      SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: zoom -- curvature condition not satisfied: \" << abs(derror_j) << \" <= \" << -_options.c2WolfeCondition*derror0);\r\n\r\n      if (derror_j*(maxStepSize - minStepSize) >= 0) {\r\n        error_rec = error_hi;\r\n        stepSize_rec = maxStepSize;\r\n        maxStepSize = minStepSize;\r\n        error_hi = error_lo;\r\n      } else {\r\n        error_rec = error_lo;\r\n        stepSize_rec = minStepSize;\r\n      }\r\n      minStepSize = stepSize_j;\r\n      error_lo = error_j;\r\n      derror_lo = derror_j;\r\n    }\r\n\r\n    i++;\r\n    if (i == _options.nMaxIterZoom) {\r\n      SM_ERROR(\"LineSearch: zoom -- Failed to find a conforming step size\");\r\n      return false;\r\n    }\r\n\r\n    SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: zoom -- update interval: [\" << minStepSize << \", \" << maxStepSize << \"]\");\r\n  }\r\n\r\n  return true;\r\n}\r\n\r\ndouble LineSearch::computeErrorDerivative() const {\r\n  return _gradient*_searchDirection.transpose();\r\n}\r\n\r\n\r\nbool LineSearch::lineSearchWolfe1() {\r\n\r\n  // Check that the error and gradient information is up to date and not NaN\r\n  SM_ASSERT_FALSE(Exception, isnan(getError()), \"\");\r\n  SM_ASSERT_FALSE(Exception, isnan(getErrorDerivative()), \"\");\r\n\r\n  double stepLength = _options.initialStepLength;\r\n  if (!isnan(_errorOld) && _derror != 0.0) {\r\n    stepLength = min(_options.maxStepLength, 1.01*2.0*(_error - _errorOld)/_derror);\r\n    if (stepLength < 0.0) stepLength = _options.initialStepLength;\r\n  }\r\n\r\n  _errorOld = _error;\r\n\r\n  SM_ASSERT_GE(Exception, stepLength, _options.minStepLength, \"\");\r\n  SM_ASSERT_LE(Exception, stepLength, _options.maxStepLength, \"\");\r\n\r\n  SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: wolfe1 -- starting line search at error value \" <<\r\n                      _error << \" and derivative \" << _derror);\r\n\r\n  if (_derror == 0.0) {\r\n    SM_FINE_STREAM_NAMED(\"optimization.linesearch\", \"LineSearch: Error derivative is zero, seems like the system is at its optimum.\");\r\n    return true;\r\n  }\r\n\r\n  bool success = false;\r\n  bool terminate = false;\r\n  Dcsrch dcsrch(stepLength, getError(), getErrorDerivative(), _options.minStepLength,\r\n                _options.maxStepLength, _options.c1WolfeCondition, _options.xtol, _options.c2WolfeCondition);\r\n\r\n  size_t cnt = 0;\r\n  while(!terminate && cnt < _options.nMaxIterWolfe1) {\r\n\r\n    SM_ALL_STREAM_NAMED(\"optimization.linesearch\", \"LineSearch: wolfe1 -- iteration \" << cnt);\r\n\r\n    const double stp = dcsrch.updateStepLength(getError(), getErrorDerivative());\r\n\r\n    switch(dcsrch.status()) {\r\n      case Dcsrch::RUNNING:\r\n        stepLength = stp;\r\n        this->applyStateUpdate(stp);\r\n        this->updateError();\r\n        this->updateErrorDerivative();\r\n        break;\r\n      case Dcsrch::CONVERGED:\r\n        SM_FINE_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: wolfe1 -- converged, final step length \" << stp <<\r\n                              \", final error \" << getError() << \", final error derivative \" << getErrorDerivative());\r\n        success = terminate = true;\r\n        break;\r\n      case Dcsrch::WARNING:\r\n        terminate = true;\r\n        break;\r\n    }\r\n\r\n    cnt++;\r\n  }\r\n\r\n  if (cnt == _options.nMaxIterWolfe1) { // maxiter reached, the line search did not converge\r\n    SM_ERROR_STREAM(\"LineSearch: wolfe1 -- no solution found in \" << _options.nMaxIterWolfe1 << \" iterations\");\r\n    return false;\r\n  }\r\n\r\n  if (!success) {\r\n    SM_ERROR(\"LineSearch: wolfe1 -- dcsrch exited with a warning\");\r\n    return false;\r\n  }\r\n\r\n  return true;\r\n\r\n}\r\n\r\nbool LineSearch::lineSearchWolfe2() {\r\n\r\n  // Check that the error and gradient information is up to date and not NaN\r\n  SM_ASSERT_FALSE(Exception, isnan(getError()), \"\");\r\n  SM_ASSERT_FALSE(Exception, isnan(getErrorDerivative()), \"\");\r\n\r\n  double minStepLength = 0.0;\r\n  double maxStepLength = _options.initialStepLength;\r\n  if (!isnan(_errorOld) && _derror != 0) {\r\n    maxStepLength = min(_options.initialStepLength, 1.01*2.0*(_error - _errorOld)/_derror);\r\n    if (maxStepLength < 0.0) maxStepLength = _options.initialStepLength;\r\n  }\r\n\r\n  _errorOld = _error;\r\n\r\n  SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: wolfe2 -- starting line search at error value \" <<\r\n                      _error << \" and derivative \" << _derror);\r\n\r\n  if (_derror == 0.0) {\r\n    SM_FINE_STREAM_NAMED(\"optimization.linesearch\", \"LineSearch: Error derivative is zero, seems like the system is at its optimum.\");\r\n    return true;\r\n  }\r\n\r\n  if (maxStepLength == 0.0) {\r\n    SM_WARN(\"LineSearch: wolfe2 -- Maximum step length is zero. This shouldn't happen. \"\r\n        \"Perhaps the increment has slipped below machine precision?\");\r\n    return false;\r\n  }\r\n\r\n  const double error0 = _error;\r\n  const double derror0 = _derror;\r\n  double errorStepMin = error0;\r\n  double derrorStepMin = derror0;\r\n\r\n  this->applyStateUpdate(maxStepLength); // Move to position x + maxStepLength*searchDirection\r\n  this->updateError();\r\n  double errorStepMax = getError();\r\n//  double derrorStepMax; // evaluated below\r\n\r\n  bool success = false;\r\n  for (size_t i=0; i<_options.nMaxIterWolfe2; ++i) {\r\n\r\n    SM_ALL_STREAM_NAMED(\"optimization.linesearch\", \"LineSearch: wolfe2 -- iteration \" << i);\r\n\r\n    if (maxStepLength == 0.0)\r\n      break;\r\n\r\n    // Check Wolfe condition 1 (Armijo rule)\r\n    if ((errorStepMax > error0 + _options.c1WolfeCondition * maxStepLength * derror0) || ((errorStepMax >= errorStepMin) && (i > 0))) {\r\n      SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: wolfe2 -- sufficient decrease condition not satisfied: \" <<\r\n                          errorStepMax << \" <= \" <<  error0 + _options.c1WolfeCondition * maxStepLength * derror0);\r\n      // zoom will move the state to a good position in the interval [minStepLength, maxStepLength]\r\n      SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: wolfe2 -- calling zoom with interval [ \" << minStepLength << \", \" << maxStepLength << \"] with errors \" <<\r\n                          \"[ \" << errorStepMin << \", \" << errorStepMax << \"] and derivative at lower interval point \" << derrorStepMin);\r\n      success = this->zoom(minStepLength, maxStepLength, errorStepMin, errorStepMax, derrorStepMin, error0, derror0);\r\n      break;\r\n    }\r\n\r\n    this->updateErrorDerivative();\r\n    const double derrorStepMax = getErrorDerivative();\r\n\r\n    // Check curvature condition\r\n    if ((abs(derrorStepMax) <= -_options.c2WolfeCondition*derror0)) {\r\n      success = true;\r\n      SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: wolfe2 -- curvature condition satisfied: \" << abs(derrorStepMax) << \" <= \" << -_options.c2WolfeCondition*derror0);\r\n      break;\r\n    } else {\r\n      SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: wolfe2 -- curvature condition not satisfied: \" << abs(derrorStepMax) << \" <= \" << -_options.c2WolfeCondition*derror0);\r\n    }\r\n\r\n    if ((derrorStepMax >= 0.0)) {\r\n      SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: wolfe2 -- calling zoom with interval [ \" << maxStepLength << \", \" << minStepLength << \"] with errors \" <<\r\n                          \"[ \" << errorStepMax << \", \" << errorStepMin << \"] and derivative at lower interval point \" << derrorStepMax);\r\n      success = zoom(maxStepLength, minStepLength, errorStepMax, errorStepMin, derrorStepMax, error0, derror0);\r\n      break;\r\n    }\r\n\r\n    double maxStepLengthNew = 2.0 * maxStepLength; // increase by factor of two on each iteration\r\n    minStepLength = maxStepLength;\r\n    maxStepLength = maxStepLengthNew;\r\n    errorStepMin = errorStepMax;\r\n\r\n    this->applyStateUpdate(maxStepLength);\r\n    this->updateError();\r\n    errorStepMax = getError();\r\n    derrorStepMin = derrorStepMax;\r\n\r\n    SM_ALL_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: wolfe2 -- update interval: [\" << minStepLength << \", \" << maxStepLength << \"]\");\r\n\r\n  }\r\n\r\n  if (success)\r\n    SM_FINE_STREAM_NAMED(\"optimization.linesearch\", setprecision(20) << \"LineSearch: wolfe2 -- converged, final step length \" << getCurrentStepLength() <<\r\n                         \", final error \" << getError());\r\n  else\r\n    SM_ERROR_STREAM(\"LineSearch: wolfe2 -- no solution found in \" << _options.nMaxIterWolfe2 << \" iterations\");\r\n\r\n  return success;\r\n\r\n}\r\n\r\nbool LineSearch::lineSearchWolfe12() {\r\n\r\n  const double errorOld0 = _errorOld; // _errorOld gets modified by lineSearchWolfe1\r\n  const double error0 = _error;\r\n  const double derror0 = _derror;\r\n\r\n  utils::DesignVariableState dvstate(_costFunction->getDesignVariables());\r\n\r\n  if (!lineSearchWolfe1()) {\r\n    SM_FINE_STREAM_NAMED(\"optimization.linesearch\", \"LineSearch: method wolfe1 failed, trying method wolfe2\");\r\n\r\n    // restore error values to the ones before calling lineSearchWolfe1().\r\n    // These are the values that correspond to step length zero.\r\n    _errorOld = errorOld0;\r\n    _error = error0;\r\n    _derror = derror0;\r\n    _stepLength = 0.0;\r\n    dvstate.restore();\r\n\r\n    return lineSearchWolfe2();\r\n  }\r\n\r\n  return true;\r\n}\r\n\r\n} // namespace backend\r\n} // namespace aslam\r\n", "meta": {"hexsha": "15c4b45bc10b22f14789726ec1f5a4e80f4f5964", "size": 34163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aslam_backend/src/LineSearch.cpp", "max_stars_repo_name": "ethz-asl/aslam_optimizer", "max_stars_repo_head_hexsha": "8e9dd18f9f0d8af461e88e108a3beda2003daf11", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2017-04-26T13:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T01:52:22.000Z", "max_issues_repo_path": "aslam_backend/src/LineSearch.cpp", "max_issues_repo_name": "ethz-asl/aslam_optimizer", "max_issues_repo_head_hexsha": "8e9dd18f9f0d8af461e88e108a3beda2003daf11", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:02:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-12T06:07:22.000Z", "max_forks_repo_path": "aslam_backend/src/LineSearch.cpp", "max_forks_repo_name": "ethz-asl/aslam_optimizer", "max_forks_repo_head_hexsha": "8e9dd18f9f0d8af461e88e108a3beda2003daf11", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-06-28T04:17:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T04:58:36.000Z", "avg_line_length": 40.0504103165, "max_line_length": 223, "alphanum_fraction": 0.6486549776, "num_tokens": 9259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.4058847202666087}}
{"text": "//////////////////////////////////////////////////////////////////////////////////////////////////\n// \\brief a class to perform solve generalized eigenvalue problem by SPAM\n//\n//\n//\n//  solve with spam method\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <vector>\n#include <string>\n#include <numeric>\n#include <cassert>\n#include <algorithm>\n#include <cmath>\n#include <complex>\n#include <iostream>\n//#include <mpi.h>\n\n#include <boost/format.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"formic/utils/exception.h\"\n#include \"formic/utils/matrix.h\"\n#include \"formic/utils/lapack_interface.h\"\n#include \"formic/utils/mpi_interface.h\"\n#include \"formic/utils/lmyengine/eigen_solver.h\"\n#include \"spam_solver.h\"\n\n//////////////////////////////////////////////////////////////////////////////////////////////////\n// \\brief solve the subspace generalized eigenvalue problem\n//        with nonsymmetric H and symmetric S for outer loop\n//\n//\n//////////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid cqmc::engine::SpamLMHD::solve_subspace_nonsymmetric(const bool outer)\n{\n\n  // one in complex form\n  const std::complex<double> complex_one(1.0, 0.0);\n  const std::complex<double> complex_zero(0.0, 0.0);\n\n  const int m  = _nkry;\n\n  // create vectors and matrices used in svd routine\n  formic::Matrix<double> u;\n  formic::Matrix<double> vt;\n  formic::ColVec<double> sin_vals;\n  int truncate_index = 0;\n\n  // make sure the subspace matrix is not empty\n  if ( outer ) {\n    if ( _subS.rows() == 0 || _subH.rows() == 0 )\n      throw formic::Exception(\"subspace matrix is empty upon solving subspace eigenvalue problem(outer)\");\n  }\n\n  else {\n    if ( _hy_subS.rows() == 0 || _hy_subH.rows() == 0 )\n      throw formic::Exception(\"subspace matrix is empty upon solving subspace eigenvalue problem(inner)\");\n  }\n\n  // perform svd to subspace overlap matrix\n  if ( outer )\n    _subS.svd(u, sin_vals, vt);\n  else\n    _hy_subS.svd(u, sin_vals, vt);\n  formic::Matrix<double> v = vt.t();\n\n  // record the smallest singular value of subspace overlap matrix\n  if ( outer )\n    _smallest_sin_value_outer = std::abs(sin_vals.at(0));\n  else\n    _smallest_sin_value_inner = std::abs(sin_vals.at(0));\n  for (int i = 0; i < m; i++) {\n    if ( outer )\n      _smallest_sin_value_outer = std::min(_smallest_sin_value_outer, std::abs(sin_vals.at(i)));\n    else\n      _smallest_sin_value_inner = std::min(_smallest_sin_value_inner, std::abs(sin_vals.at(i)));\n    truncate_index = i;\n\n    // check if singular value is smaller than singular value threshold\n    if ( outer && _smallest_sin_value_outer < _singular_value_threshold)\n      break;\n    else if ( !outer && _smallest_sin_value_inner < _singular_value_threshold)\n      break;\n  }\n\n  // get the number of colums of new U and V matrix by add 1 to truncate index\n  truncate_index ++;\n\n  // throw away those columns in U and V matrix which corresponds to singular values below the threshold\n  u.conservativeResize(m, truncate_index);\n  v.conservativeResize(m, truncate_index);\n\n  // throw away those small singular values\n  sin_vals.conservativeResize(truncate_index);\n\n  // convert the truncated singular value vector to a truncated_index * truncated_index diagonal matrix\n  formic::Matrix<double> trun_sin_val_matrix(truncate_index, truncate_index, 0.0);\n  for (int i = 0; i < truncate_index; i++)\n    trun_sin_val_matrix.at(i,i) = sin_vals.at(i);\n\n  // calculate the inverse of this matrix\n  for(int i = 0; i < truncate_index; i++){\n    for(int j = 0; j < truncate_index; j++){\n      trun_sin_val_matrix.at(i,j) = (trun_sin_val_matrix.at(i,j) == 0 ? trun_sin_val_matrix.at(i,j) : 1 / trun_sin_val_matrix.at(i,j));\n    }\n  }\n\n  // calculate matrix S_trun^-1 * U^-1 * H * V\n  formic::Matrix<double> new_sub_H = trun_sin_val_matrix * u.t() * (outer ? _subH : _hy_subH) * v;\n\n  // set a vector to hold eigenvalues\n  formic::ColVec<std::complex<double> > e_evals;\n\n  // set an eigen array to hold energies\n  formic::ColVec<std::complex<double> > energy_list;\n\n  // a matrix to hold eigenvectors\n  formic::Matrix<std::complex<double> > evecs_list;\n\n  // solve this standard eigenvalue problem ( new_H * y = lambda * y, y = V^T * x, x is the original eigenvector)\n  new_sub_H.nonsym_eig(e_evals, evecs_list);\n\n  // if we are doing excited state calculations, convert the resulting eigenvalues to energy( this is important in harmonic davidson)\n  if ( !_ground ) {\n    energy_list = _hd_shift * complex_one - complex_one / e_evals;\n  }\n\n  // if we are doing ground state calculation, then do nothing\n  if ( _ground ) {\n    energy_list = e_evals.clone();\n  }\n\n  int selected = 0;\n  // if we want to chase the closest, selected the eigenvalue that is real and most similar to the previous eigenvalue( this is essestially an attempt to stay in the same solution)\n  if ( _chase_closest ) { // currently turn on this if statement for spam\n    std::complex<double> closest_energy = energy_list.at(0);\n    std::complex<double> corrs_eval = e_evals.at(0);\n    for (int j = 1; j < truncate_index; j++){\n      // first check if this energy is real\n      if ( std::abs((energy_list.at(j)).imag()) < 1.0e-6 ) {\n\n        // then select the energy that is closest to the previous one\n        if(std::abs( complex_one * (outer ? _energy_outer : _energy_inner) - energy_list.at(j) ) < std::abs(complex_one * (outer ? _energy_outer : _energy_inner) - closest_energy )){\n          selected = j;\n          closest_energy = energy_list.at(j);\n          corrs_eval = e_evals.at(j);\n        }\n      }\n    }\n\n    // if the eigenvalue has an imaginary component, we abort\n    _eval_was_complex = false;\n    if( std::abs(closest_energy.imag()) > 1.0e-6 ) {\n      _eval_was_complex = true;\n      return;\n    }\n\n    // if the eigenvalue is real, we record it and the corresponding eigenvector\n    if ( outer ) {\n      // record energy\n      _energy_outer = closest_energy.real();\n\n      // record the eigenvalue\n      _sub_eval_outer = corrs_eval.real();\n    }\n\n    else {\n      // record energy\n      _energy_inner = closest_energy.real();\n\n      // record the eigenvalue\n      _sub_eval_inner = corrs_eval.real();\n    }\n\n    // record the eigenvector y\n    _wv4 = evecs_list.col_as_vec(selected);\n\n    // convert y to x\n    _wv5.reset(m);\n    // convert v to complex form to make sure that all quantities in dgemm call are of the same type\n    formic::Matrix<std::complex<double> > v_complex(v.rows(), v.cols(), complex_zero);\n    for (int i = 0; i < v_complex.rows(); i++) {\n      for (int j = 0; j < v_complex.cols(); j++) {\n        v_complex.at(i,j) = std::complex<double>(v.at(i,j), 0.0);\n      }\n    }\n    formic::xgemm('N', 'N', m, 1, truncate_index, complex_one, &v_complex.at(0,0), m, &_wv4.at(0), truncate_index, complex_zero, &_wv5.at(0), m);\n    //_wv5 = V * _wv4;\n\n    // take real part of the vector x, put that into eigenvector\n    (outer ? _sub_evec_outer : _sub_evec_inner).reset(m);\n    for (int i = 0; i < m; i++) {\n      (outer ? _sub_evec_outer : _sub_evec_inner)(i) = _wv5.at(i).real();\n    }\n  }\n\n  // if we want to chase the lowest, select the lowest eigenvalue(currently turn off this if statement for spam)\n  if ( _chase_lowest ) {\n\n    // the vector that stores all lower-than-current energy(target function)\n    std::vector<std::complex<double> > lower_than_current_list;\n    std::vector<int> lower_than_current_index;\n    //Eigen::ArrayXcd eval_list = (es.eigenvalues()).array();\n    std::complex<double> lowest_eval = e_evals.at(0);\n\n    double inner_eval = 0.0;\n    if ( !_ground ) \n      inner_eval = 1.0 / (_hd_shift - _energy_inner);\n    else \n      inner_eval = _energy_inner;\n\n    // if it's outer iteration, we just make sure that we choose the lowest energy(target function)\n    //if ( outer ) {\n    for (int j = 1; j < truncate_index; j++) {\n      if (e_evals.at(j).real() < lowest_eval.real()) {\n        selected = j;\n        lowest_eval = e_evals.at(j);\n      }\n    }\n    //}\n\n    // if it's inner iteration\n    //else {\n    //\n    //  // we first need to get all energy(target function) lower than current\n    //  for (int j = 0; j < truncate_index; j++) {\n    //    if (eval_list(j).real() < inner_eval) {\n    //      lower_than_current_list.push_back(eval_list(j));\n    //      lower_than_current_index.push_back(j);\n    //    }\n    //  }\n\n    //  lowest_eval = lower_than_current_list.at(0);\n    //  selected = lower_than_current_index.at(0);\n    //  // then we select from lower list the closest energy(target function)\n    //  for (int i = 1; i < lower_than_current_list.size(); i++) {\n    //\n    //    // first check if this energy is real\n    //    if ( std::abs((lower_than_current_list.at(i)).imag()) < 1.0e-6 ) {\n\n    //      // then select energy\n    //      if ( std::abs( complex_one * inner_eval - lower_than_current_list.at(i) ) < std::abs(complex_one * inner_eval - lowest_eval )) {\n    //        selected = lower_than_current_index.at(i);\n    //        lowest_eval = lower_than_current_list.at(i);\n    //      }\n    //    }\n    //  }\n    //}\n\n\n    // if the eigenvalue has an imaginary component, we abort\n    _eval_was_complex = false;\n    if ( std::abs(lowest_eval.imag()) > 1.0e-6 ) {\n      _eval_was_complex = true;\n      return;\n    }\n\n    // if the eigenvalue is real, we record it\n    if ( !_ground ) {\n      if ( outer )\n        _energy_outer = _hd_shift - 1.0 / lowest_eval.real();\n      else\n        _energy_inner = _hd_shift - 1.0 / lowest_eval.real();\n    }\n\n    else {\n      if ( outer )\n        _energy_outer = lowest_eval.real();\n      else\n        _energy_inner = lowest_eval.real();\n    }\n\n    // record the eigenvalue\n    (outer ? _sub_eval_outer : _sub_eval_inner) = lowest_eval.real();\n\n    // record the eigenvector y\n    _wv4 = evecs_list.col_as_vec(selected);\n\n    // convert y to x\n    _wv5.reset(m);\n    // convert v to complex form to make sure that all quantities in dgemm call are of the same type\n    formic::Matrix<std::complex<double> > v_complex(v.rows(), v.cols(), complex_zero);\n    for (int i = 0; i < v_complex.rows(); i++) {\n      for (int j = 0; j < v_complex.cols(); j++) {\n        v_complex.at(i,j) = std::complex<double>(v.at(i,j), 0.0);\n      }\n    }\n    formic::xgemm('N', 'N', m, 1, truncate_index, complex_one, &v_complex.at(0,0), m, &_wv4.at(0), truncate_index, complex_zero, &_wv5.at(0), m);\n    //_wv5 = V * _wv4;\n\n    // take real part of vector x, put that into eigenvector\n    (outer ? _sub_evec_outer : _sub_evec_inner).reset(m);\n    for (int i = 0; i < m; i++) {\n      (outer ? _sub_evec_outer : _sub_evec_inner)(i) = _wv5.at(i).real();\n    }\n  }\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// \\brief solves the subspace eigenvalue problem\n//\n//\n//\n///////////////////////////////////////////////////////////////////////////////\n\nvoid cqmc::engine::SpamLMHD::solve_subspace(const bool outer)\n{\n  this -> solve_subspace_nonsymmetric(outer);\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n// \\brief adds a new krylov vector for inner loop of spam\n//\n//\n//\n//\n/////////////////////////////////////////////////////////////////////////////////\n\nvoid cqmc::engine::SpamLMHD::add_krylov_vector_inner(const formic::ColVec<double> & v)\n{\n\n  int my_rank = formic::mpi::rank();\n\n  // check vector length\n  if (my_rank == 0 && v.size() != _der_rat.cols())\n    throw formic::Exception(\"bad vector length of %d in SpamLMHD::add_krylov_vector_outer: expected length of %d\") % v.size() % _der_rat.cols();\n\n  // increment krylov subspace size and remember the old size\n  const int nold = _nkry++;\n\n  _wv1.reset(v.size());\n  _wv1 = v;\n\n  // perform gram-schmidt orthogonalization against the existing krylov vectors\n  if (my_rank == 0) {\n    for (int i = 0; i < nold; i++) {\n      _wv1 -= dotc(_kvecs.col_as_vec(i), _wv1) * _kvecs.col_as_vec(i);\n    }\n  }\n\n  // broadcast this vector to all processes\n  formic::mpi::bcast(&_wv1.at(0), _wv1.size());\n\n  // compute the product of approximate hamiltonian times the new krylov vector\n  formic::ColVec<double> hs(_nfds);\n  this -> HMatVecOp(_wv1, hs, false, true);\n  formic::ColVec<double> hs_avg(hs.size());\n  formic::mpi::reduce(&hs.at(0), &hs_avg.at(0), hs.size(), MPI_SUM);\n  hs = hs_avg.clone();\n\n  // compute the product of approximate overlap matrix times this new krylov vector\n  this -> SMatVecOp(_wv1, _wv2, true);\n  formic::ColVec<double> _wv2_avg(_wv2.size());\n  formic::mpi::reduce(&_wv2.at(0), &_wv2_avg.at(0), _wv2.size(), MPI_SUM);\n  _wv2 = _wv2_avg.clone();\n\n\n  // modify the hamiltonian product to account for \"identity shift\"\n  if (my_rank == 0) {\n    for (int i = 1; i < hs.size(); i++) {\n      hs.at(i) += _hshift_i * _wv1.at(i);\n    }\n  }\n\n  // modify hamiltonian product to account for \"overlap\" shift\n  if (my_rank == 0 && nold > 0) {\n    hs += _hshift_s * _wv2;\n  }\n\n\n  // normalize the new krylov vector and save the vector and its operation on overlap matrix\n  if (my_rank == 0) {\n    const double norm = std::sqrt(_wv1.norm2());\n    _wv1 /= norm;\n    _wv2 /= norm;\n    hs /= norm;\n\n    // krylov space\n    _kvecs.conservativeResize(_nfds, _nkry);\n    std::copy(_wv1.begin(), _wv1.end(), _kvecs.col_begin(_nkry-1));\n\n    // S_hybrid * krylov space\n    _hsvecs.conservativeResize(_nfds, _nkry);\n\n    // temp vector that store (S * X)^T * xnew by blas level-2\n    formic::ColVec<double> new_col_s_temp1(_nkry_full);\n    formic::dgemv('T', _nfds, _nkry_full, 1.0, &_svecs.at(0,0), _nfds, &_wv1.at(0), 1, 0.0, &new_col_s_temp1.at(0), 1);\n\n    // tenp vector that store X * (S * X)^T * xnew + S(1) * xnew\n    formic::ColVec<double> new_col_s_temp2(_nfds);\n    formic::dgemv('N', _nfds, _nkry_full, 1.0, &_kvecs.at(0,0), _nfds, &new_col_s_temp1.at(0), 1, 0.0, &new_col_s_temp2.at(0), 1);\n    //daxpy(_nfds, 1.0, &_wv2(0), 1, &new_col_s_temp2(0), 1);\n    new_col_s_temp2 += _wv2;\n\n    // temp vector that store X * S(1)*xnew\n    formic::ColVec<double> new_col_s_temp3(_nkry_full);\n    formic::dgemv('T', _nfds, _nkry_full, 1.0, &_kvecs.at(0,0), _nfds, &_wv2.at(0), 1, 0.0, &new_col_s_temp3.at(0), 1);\n\n    formic::ColVec<double> new_col_s(_nfds);\n    formic::dgemv('N', _nfds, _nkry_full, 1.0, &_kvecs.at(0,0), _nfds, &new_col_s_temp3.at(0), 1, 0.0, &new_col_s.at(0), 1);\n    //daxpy(_nfds, -1.0, &new_col_s(0), 1, &new_col_s_temp2(0), 1);\n    new_col_s = -1.0 * new_col_s + new_col_s_temp2;\n\n    std::copy(new_col_s.begin(), new_col_s.end(), _hsvecs.col_begin(_nkry-1));\n\n    // H_hybrid * krylov space\n    _hhvecs.conservativeResize(_nfds, _nkry);\n\n    // temp vector that store (H^T * X)^T * xnew\n    formic::ColVec<double> new_col_h_temp1(_nkry_full);\n    formic::dgemv('T', _nfds, _nkry_full, 1.0, &_thvecs.at(0,0), _nfds, &_wv1.at(0), 1, 0.0, &new_col_h_temp1.at(0), 1);\n\n    // temp vector that store X * (H^T * X)^T * xnew + H(1)*xnew\n    formic::ColVec<double> new_col_h_temp2(_nfds);\n    formic::dgemv('N', _nfds, _nkry_full, 1.0, &_kvecs.at(0,0), _nfds, &new_col_h_temp1.at(0), 1, 0.0, &new_col_h_temp2.at(0), 1);\n    //daxpy(_nfds, 1.0, &hs(0), 1, &new_col_h_temp2(0), 1);\n    new_col_h_temp2 += hs;\n\n    // temp vector that store X^T * H(1)*xnew\n    formic::ColVec<double> new_col_h_temp3(_nkry_full);\n    formic::dgemv('T', _nfds, _nkry_full, 1.0, &_kvecs.at(0,0), _nfds, &hs.at(0), 1, 0.0, &new_col_h_temp3.at(0), 1);\n\n    formic::ColVec<double> new_col_h(_nfds);\n    formic::dgemv('N', _nfds, _nkry_full, 1.0, &_kvecs.at(0,0), _nfds, &new_col_h_temp3.at(0), 1, 0.0, &new_col_h.at(0), 1);\n    //daxpy(_nfds, -1.0, &new_col_h(0), 1, &new_col_h_temp2(0), 1);\n    new_col_h = -1.0 * new_col_h + new_col_h_temp2;\n\n    std::copy(new_col_h.begin(), new_col_h.end(), _hhvecs.col_begin(_nkry-1));\n\n    // update subspace projection of hybrid Hamiltonian\n    _hy_subH.conservativeResize(_nkry, _nkry);\n    _wv3 = _wv1.t() * _hhvecs;\n    _wv6 = _kvecs.t() * new_col_h;\n    std::copy(_wv3.begin(), _wv3.end(), _hy_subH.row_begin(_nkry-1));\n    std::copy(_wv6.begin(), _wv6.end(), _hy_subH.col_begin(_nkry-1));\n    //_hy_subH.bottomRows(1) = _wv3;\n    //_hy_subH.rightCols(1) = _wv6;\n\n    // update subspace projection of hybrid overlap\n    _hy_subS.conservativeResize(_nkry, _nkry);\n    _wv3 = _wv1.t() * _hsvecs;\n    _wv6 = _kvecs.t() * new_col_s;\n\n    std::copy(_wv3.begin(), _wv3.end(), _hy_subS.row_begin(_nkry-1));\n    std::copy(_wv6.begin(), _wv6.end(), _hy_subS.col_begin(_nkry-1));\n    //_hy_subS.bottomRows(1) = _wv3;\n    //_hy_subS.rightCols(1) = _wv6;\n\n    // add this vector to intermediate krylov space\n    _kvecs_about_to_add.conservativeResize(_nfds, _nkry - _nkry_full);\n     std::copy(_wv1.begin(), _wv1.end(), _kvecs_about_to_add.col_begin(_nkry-_nkry_full-1));\n    //_kvecs_about_to_add.rightCols(1) = _wv1;\n  }\n\n\n}\n\n////////////////////////////////////////////////////////////////////////////////////\n// \\brief adds a bunch of new Krylov vectors for spam outer loop\n//\n// NOTE: This function assumes that the input vectors are already orthonormal!!\n//\n//\n////////////////////////////////////////////////////////////////////////////////////\nvoid cqmc::engine::SpamLMHD::add_krylov_vectors_outer(const formic::Matrix<double> & m)\n{\n\n  int my_rank = formic::mpi::rank();\n\n  // check matrix size\n  if (my_rank == 0 && m.rows() != _der_rat.cols())\n    throw formic::Exception(\"bad matrix size of %d in SpamLMHD::add_krylov_vector_outer: expected length of %d\") % m.rows() % _der_rat.cols();\n\n  // get the number of new krylov vectors\n  const int Nnew = m.cols();\n\n  // remember the old size\n  const int nold = _nkry;\n\n  // if this is the first krylov vector, we increment the number of krylov vectors by the number of new krylov vectors\n  if ( nold == 0 )\n    _nkry += Nnew;\n\n  // record the number of krylov vectors that have been multiplied by full hamiltonian and overlap, which is different from the total number of krylov vectors\n  _nkry_full = _nkry;\n\n  // put input matrix into work matrix\n  _wm1.reset(m.rows(), Nnew);\n  _wm1 = m;\n\n  // compute the product of Hamiltonian times these new krylov vectors\n  formic::Matrix<double> hs(_nfds, Nnew);\n  this -> HMatMatOp(_wm1, hs, false, false);\n  formic::Matrix<double> hs_avg(_nfds, Nnew);\n  formic::mpi::reduce(&hs.at(0,0), &hs_avg.at(0,0), hs.size(), MPI_SUM);\n  hs = hs_avg.clone();\n\n  // compute the product of Hamiltonian transpose times these new krylov vectors\n  formic::Matrix<double> ths(_nfds, Nnew);\n  this -> HMatMatOp(_wm1, ths, true, false);\n  formic::Matrix<double> ths_avg(ths.rows(), ths.cols());\n  formic::mpi::reduce(&ths.at(0,0), &ths_avg.at(0,0), ths.size(), MPI_SUM);\n  ths = ths_avg.clone();\n\n  // compute the product of the overlap matrix times these new krylov vectors\n  this -> SMatMatOp(_wm1, _wm2, false);\n  formic::Matrix<double> _wm2_avg(_wm2.rows(), _wm2.cols());\n  formic::mpi::reduce(&_wm2.at(0,0), &_wm2_avg.at(0,0), _wm2.size(), MPI_SUM);\n  _wm2 = _wm2_avg.clone();\n\n  // modify hamiltonian product to account for \"identity\" shift\n  if (my_rank == 0) {\n    for (int i = 1; i < Nnew; i++) {\n      for (int j = 0; j < hs.rows(); j++) {\n        hs.at(j,i) += _hshift_i * _wm1.at(j,i);\n        ths.at(j,i) += _hshift_i * _wm1.at(j,i);\n      }\n    }\n  }\n\n  // modify hamiltonian product to account for \"overlap\" shift\n  if (my_rank == 0 && nold > 0) {\n    hs += _hshift_s * _wm2;\n    ths += _hshift_s * _wm2;\n  }\n\n\n\n  // save these krylov vectors and their operation on matrix\n  if ( my_rank == 0 ) {\n\n    // krylov space\n    if ( nold == 0 ) {\n      _kvecs.conservativeResize(_nfds, _nkry);\n      for (int i = 0; i < Nnew; i++)\n        std::copy(_wm1.col_begin(i), _wm1.col_end(i), _kvecs.col_begin(_nkry-Nnew+i));\n      //_kvecs.rightCols(Nnew) = _wm1;\n    }\n\n    // H * krylov space\n    _hvecs.conservativeResize(_nfds, _nkry);\n    for (int i = 0; i < Nnew; i++)\n      std::copy(hs.col_begin(i), hs.col_end(i), _hvecs.col_begin(_nkry-Nnew+i));\n    //_hvecs.rightCols(Nnew) = hs;\n\n    // H_hybrid * krylov space\n    _hhvecs.reset(_nfds, _nkry);\n    _hhvecs = _hvecs.clone();\n\n    // H^T * krylov space\n    _thvecs.conservativeResize(_nfds, _nkry);\n    for (int i = 0; i < Nnew; i++)\n      std::copy(ths.col_begin(i), ths.col_end(i), _thvecs.col_begin(_nkry-Nnew+i));\n    //_thvecs.rightCols(Nnew) = ths;\n\n    // S * krylov space\n    _svecs.conservativeResize(_nfds, _nkry);\n    for (int i = 0; i < Nnew; i++)\n      std::copy(_wm2.col_begin(i), _wm2.col_end(i), _svecs.col_begin(_nkry-Nnew+i));\n    //_svecs.rightCols(Nnew) = _wm2;\n\n    // S_hybrid * krylov space\n    _hsvecs.reset(_nfds, _nkry);\n    _hsvecs = _svecs.clone();\n\n    // update subspace projection of hamiltonian\n    _subH.conservativeResize(_nkry, _nkry);\n    _wm3 = _wm1.t() * _hvecs;\n    _wm4 = _kvecs.t() * hs;\n    for (int i = 0; i < Nnew; i++)\n      std::copy(_wm4.col_begin(i), _wm4.col_end(i), _subH.col_begin(_nkry-Nnew+i));\n\n    for (int i = 0; i < Nnew; i++)\n      std::copy(_wm3.col_begin(i), _wm3.col_end(i), _subH.row_begin(_nkry-Nnew+i));\n    //_subH.bottomRows(Nnew) = _wm3;\n    //_subH.rightCols(Nnew) = _wm4;\n\n    // set the hybrid Hamiltonian subspace projection matrix same as the full hamiltonian\n    _hy_subH.reset(_nkry, _nkry);\n    _hy_subH = _subH.clone();\n\n    // update subspace projection of the overlap\n    _subS.conservativeResize(_nkry, _nkry);\n    _wm3 = _wm1.t() * _svecs;\n    _wm4 = _kvecs.t() * _wm2;\n    for (int i = 0; i < Nnew; i++)\n      std::copy(_wm4.col_begin(i), _wm4.col_end(i), _subS.col_begin(_nkry-Nnew+i));\n\n    for (int i = 0; i < Nnew; i++)\n      std::copy(_wm3.col_begin(i), _wm3.col_end(i), _subS.row_begin(_nkry-Nnew+i));\n    //_subS.bottomRows(Nnew) = _wm3;\n    //_subS.rightCols(Nnew) = _wm4;\n\n    // set the hybrid overlap subspace projection matrix same as the full overlap\n    _hy_subS.reset(_nkry, _nkry);\n    _hy_subS = _subS.clone();\n\n  }\n\n}\n\n\n////////////////////////////////////////////////////////////////////////////////////\n// \\brief function that perfoms hamiltonian matrix-vector multiplication\n//\n// \\param[in]   x              input vector\n// \\param[in]   matrix_built   whether we have already built the matrix or not\n// \\param[in]   transpose      whether to use transposed hamiltonian or not\n// \\param[in]   approximate    whether to use approximated hamiltonian or not\n// \\param[out]  y              result vector\n//\n////////////////////////////////////////////////////////////////////////////////////\n\nvoid cqmc::engine::SpamLMHD::HMatVecOp(const formic::ColVec<double> & x, formic::ColVec<double> & y, const bool transpose, const bool approximate)\n{\n  // size the resulting vector correctly\n  y.reset(x.size());\n\n\n  // the number of samples on each process\n  int Ns = _le_der.rows();\n\n  // if we multiply by approximated matrix, we need to change Ns by approximate degree\n  if ( approximate )\n    Ns /= _appro_degree;\n\n  // the number of independent variables\n  const int Nind = _le_der.cols();\n\n  // check whether derivative vector matrices have the same size\n  if ( _le_der.rows() != _der_rat.rows() && _le_der.cols() != _der_rat.cols())\n    throw formic::Exception(\"the input derivative vector matrices are of different size!\");\n\n  // if we are doing ground state calculation\n  if ( _ground && !approximate ) {\n\n    // if we do H*x\n    if ( !transpose ) {\n\n      // temp vector to store le_der * x\n      formic::ColVec<double> temp(Ns);\n\n      // call blas level-2 function\n      formic::dgemv('N', Ns, Nind, 1.0, &_le_der.at(0,0), Ns, &x.at(0), 1, 0.0, &temp.at(0), 1);\n\n      // call blas level-2 function\n      formic::dgemv('T', Ns, Nind, 1.0, &_der_rat.at(0,0), Ns, &temp.at(0), 1, 0.0, &y.at(0), 1);\n\n      return;\n    }\n\n    // if we do H^T * x\n    else {\n\n      // temp vector that store der_rat * x\n      formic::ColVec<double> temp(Ns);\n\n      // call blas level-2 function\n      formic::dgemv('N', Ns, Nind, 1.0, &_der_rat.at(0,0), Ns, &x.at(0), 1, 0.0, &temp.at(0), 1);\n\n      // call blas level-2 function\n      formic::dgemv('T', Ns, Nind, 1.0, &_le_der.at(0,0), Ns, &temp.at(0), 1, 0.0, &y.at(0), 1);\n\n      return;\n    }\n  }\n\n\n  // if we are doing ground state calculation and multiply by approximate matrix\n  else if ( _ground && approximate ) {\n\n    // if we want H * x\n    if ( !transpose ) {\n\n      // temp vector that stores le_der_appro * x\n      formic::ColVec<double> temp(Ns);\n\n      // call blas level-2 function\n      formic::dgemv('N', Ns, Nind, _appro_factor, &_le_der_appro.at(0,0), Ns, &x.at(0), 1, 0.0, &temp.at(0), 1);\n\n      // call blas level-2 function\n      formic::dgemv('T', Ns, Nind, 1.0, &_der_rat_appro.at(0,0), Ns, &temp.at(0), 1, 0.0, &y.at(0), 1);\n\n      return;\n    }\n\n    // if we want H^T * x\n    else {\n\n      // temp vector that stores der_rat * x\n      formic::ColVec<double> temp(Ns);\n\n      // call blas level-2 function\n      formic::dgemv('N', Ns, Nind, _appro_factor, &_der_rat_appro.at(0,0), Ns, &x.at(0), 1, 0.0, &temp.at(0), 1);\n\n      // call blas level-2 function\n      formic::dgemv('T', Ns, Nind, 1.0, &_le_der_appro.at(0,0), Ns, &temp.at(0), 1, 0.0, &y.at(0), 1);\n\n      return;\n    }\n  }\n\n  // if we are doing excited state calculation and full matrix\n  else if ( !_ground && !approximate ) {\n\n    // if we want H*x\n    if ( !transpose ) {\n\n      // temp vectpr to store omega * der_rat * x\n      formic::ColVec<double> temp1(Ns);\n\n      // temp vector to store le_der * x\n      formic::ColVec<double> temp2(Ns);\n\n      // call blas level-2 function\n      formic::dgemv('N', Ns, Nind, _hd_shift, &_der_rat.at(0,0), Ns, &x.at(0), 1, 0.0, &temp1.at(0), 1);\n\n      // call blas level-2 function\n      formic::dgemv('N', Ns, Nind, 1.0, &_le_der.at(0,0), Ns, &x.at(0), 1, 0.0, &temp2.at(0), 1);\n\n      // combine these two temp vector together\n      temp1 -= temp2;\n\n      // left multiply by _der_rat^T\n      formic::dgemv('T', Ns, Nind, 1.0, &_der_rat.at(0,0), Ns, &temp1.at(0), 1, 0.0, &y.at(0), 1);\n\n      return;\n    }\n\n    // if we want H^T * x\n    else {\n\n      // temp vector that store _der_rat * x\n      formic::ColVec<double> temp1(Ns);\n\n      // call blas level-2 function\n      formic::dgemv('N', Ns, Nind, 1.0, &_der_rat.at(0,0), Ns, &x.at(0), 1, 0.0, &temp1.at(0), 1);\n\n      // temp vector that store _le_der^T * _der_rat * x\n      formic::ColVec<double> temp2(Nind);\n\n      // call blas level-2 function\n      formic::dgemv('T', Ns, Nind, 1.0, &_le_der.at(0,0), Ns, &temp1.at(0), 1, 0.0, &temp2.at(0), 1);\n\n      // call bals level-2 function\n      formic::dgemv('T', Ns, Nind, _hd_shift, &_der_rat.at(0,0), Ns, &temp1.at(0), 1, 0.0, &y.at(0), 1);\n\n      // get the resulting vector\n      y -= temp2;\n\n      return;\n    }\n  }\n\n  // if we are doing excited state calculation and approximate matrix\n  else if ( !_ground && approximate ) {\n\n    // if we want H*x\n    if ( !transpose ) {\n\n      // temp vector that stores omega * der_rat * x\n      formic::ColVec<double> temp1(Ns);\n\n      // temp vector that stores le_der * x\n      formic::ColVec<double> temp2(Ns);\n\n      // call blas level-2 function\n      formic::dgemv('N', Ns, Nind, _hd_shift, &_der_rat_appro.at(0, 0), Ns, &x.at(0), 1, 0.0, &temp1.at(0), 1);\n\n      // call blas level-2 function\n      formic::dgemv('N', Ns, Nind, 1.0, &_le_der_appro.at(0, 0), Ns, &x.at(0), 1, 0.0, &temp2.at(0), 1);\n\n      // combine these two temp vector together\n      temp1 -= temp2;\n\n      // left multiply by _der_rat_^T\n      formic::dgemv('T', Ns, Nind, _appro_factor, &_der_rat_appro.at(0, 0), Ns, &temp1.at(0), 1, 0.0, &y.at(0), 1);\n\n      return;\n    }\n\n    // if we want H^T * x\n    else {\n\n      // temp vector that store _der_rat * x\n      formic::ColVec<double> temp1(Ns);\n\n      // call blas level-2 function\n      formic::dgemv('N', Ns, Nind, _appro_factor, &_der_rat_appro.at(0, 0), Ns, &x.at(0), 1, 0.0, &temp1.at(0), 1);\n\n      // temp vector that store _le_der^T * _der_rat * x\n      formic::ColVec<double> temp2(Nind);\n\n      // call blas level-2 function\n      formic::dgemv('T', Ns, Nind, 1.0, &_le_der_appro.at(0, 0), Ns, &temp1.at(0), 1, 0.0, &temp2.at(0), 1);\n\n      // call bals level-2 function\n      formic::dgemv('T', Ns, Nind, _hd_shift, &_der_rat_appro.at(0, 0), Ns, &temp1.at(0), 1, 0.0, &y.at(0), 1);\n\n      // get the resulting vector\n      y -= temp2;\n\n      return;\n    }\n  }\n}\n\n////////////////////////////////////////////////////////////////////////////////////\n// \\brief function that performs hamiltonian matrix-matrix multiplication\n//\n// \\param[in]   x              input matrix\n// \\param[in]   matrix_built   whether we have already built the matrix or not\n// \\param[in]   transpose      whether to use the transposed hamiltonian or not\n// \\param[in]   approximate    whether to use approximated hamiltonian or not\n// \\param[out]  y              result matrix\n//\n////////////////////////////////////////////////////////////////////////////////////\n\nvoid cqmc::engine::SpamLMHD::HMatMatOp(const formic::Matrix<double> & x, formic::Matrix<double> & y, const bool transpose, const bool approximate)\n{\n\n  // size the resulting matrix correctly\n  y.reset(x.rows(), x.cols());\n\n  // the number of samples on each process\n  int Ns = _le_der.rows();\n\n  // the number of independent variables\n  int Nind = _le_der.cols();\n\n  // the number of new krylov vectors\n  int Nnew = x.cols();\n\n  // if the approximate flag is set to be true, throw out an error\n  if ( approximate )\n    throw formic::Exception(\"Matrix-Matrix multiplication doesn't support appriximate matrix\");\n\n  // check to see whether derivative vector matrices have the same size\n  if ( _le_der.rows() != _der_rat.rows() && _le_der.cols() != _der_rat.cols())\n    throw formic::Exception(\"the input derivative vector %d by %d and %d by %d matrices are of different size!\") % _le_der.rows() % _le_der.cols() % _der_rat.rows() % _der_rat.cols();\n\n  // if we are doing ground state calculation\n  if ( _ground ) {\n\n    // if we do H*x\n    if ( !transpose ) {\n\n      // temp matrix to store le_der * x\n      formic::Matrix<double> temp(Ns, Nnew);\n\n      // call blas level-3 function\n      formic::dgemm('N', 'N', Ns, Nnew, Nind, 1.0, &_le_der.at(0, 0), Ns, &x.at(0, 0), Nind, 0.0, &temp.at(0, 0), Ns);\n\n      // call blas level-3 function\n      formic::dgemm('T', 'N', Nind, Nnew, Ns, 1.0,  &_der_rat.at(0, 0), Ns, &temp.at(0, 0), Ns, 0.0, &y.at(0, 0), Nind);\n\n      return;\n    }\n\n    // if we do H^T * x\n    else {\n\n      // temp mattrix that stores der_rat * x\n      formic::Matrix<double> temp(Ns, Nnew);\n\n      // call blas level-3 function\n      formic::dgemm('N', 'N', Ns, Nnew, Nind, 1.0, &_der_rat.at(0, 0), Ns, &x.at(0, 0), Nind, 0.0, &temp.at(0, 0), Ns);\n\n      // call blas level-3 function\n      formic::dgemm('T', 'N', Nind, Nnew, Ns, 1.0, &_le_der.at(0, 0), Ns, &temp.at(0, 0), Ns, 0.0, &y.at(0, 0), Nind);\n\n      return;\n    }\n  }\n\n  // if we are doing excited state calculation\n  else if ( !_ground ) {\n\n    // if we want H*x\n    if ( !transpose ) {\n\n      // temp matrix that stores omega * der_rat * x\n      formic::Matrix<double> temp1(Ns, Nnew);\n\n      // temp matrix that stores le_der * x\n      formic::Matrix<double> temp2(Ns, Nnew);\n\n      // call blas level-3 function\n      formic::dgemm('N', 'N', Ns, Nnew, Nind, _hd_shift, &_der_rat.at(0, 0), Ns, &x.at(0, 0), Nind, 0.0, &temp1.at(0, 0), Ns);\n\n      // call blas level-3 function\n      formic::dgemm('N', 'N', Ns, Nnew, Nind, 1.0, &_le_der.at(0, 0), Ns, &x.at(0, 0), Nind, 0.0, &temp2.at(0, 0), Ns);\n\n      // combine these two temp matrices together\n      temp1 -= temp2;\n\n      // left multiply by _der_rat^T\n      formic::dgemm('T', 'N', Nind, Nnew, Ns, 1.0, &_der_rat.at(0, 0), Ns, &temp1.at(0, 0), Ns, 0.0, &y.at(0, 0), Nind);\n\n      return;\n    }\n\n    // if we want H^T*x\n    else {\n\n      // temp vector that stored _der_rat * x\n      formic::Matrix<double> temp1(Ns, Nnew);\n\n      // call blas level-3 function\n      formic::dgemm('N', 'N', Ns, Nnew, Nind, 1.0, &_der_rat.at(0, 0), Ns, &x.at(0, 0), Nind, 0.0, &temp1.at(0, 0), Ns);\n\n      // temp matrix that stores _le_der^T * _der_rat * x\n      formic::Matrix<double> temp2(Nind, Nnew);\n\n      // call blas level-3 function\n      formic::dgemm('T', 'N', Nind, Nnew, Ns, 1.0, &_le_der.at(0, 0), Ns, &temp1.at(0, 0), Ns, 0.0, &temp2.at(0, 0), Nind);\n\n      // call blas level-3 function\n      formic::dgemm('T', 'N', Nind, Nnew, Ns, _hd_shift, &_der_rat.at(0, 0), Ns, &temp1.at(0, 0), Ns, 0.0, &y.at(0, 0), Nind);\n\n      // get the resulting vector\n      y -= temp2;\n\n      return;\n    }\n  }\n}\n\n\n////////////////////////////////////////////////////////////////////////////////////\n// \\brief function that performs overlap matrix-vector multiplication\n//\n// \\param[in]   x              input vector\n// \\param[in]   matrix_built   whether we have already built the matrix or not\n// \\param[in]   approximate    whether to use approximated overlap or not\n// \\param[out]  y              result vector\n// NOTE: Unlike hamiltonian matrix-vector multiplication function, no transpose flag\n//       in this function because overlap matrix is assumed to be symmetric\n//\n////////////////////////////////////////////////////////////////////////////////////\n\nvoid cqmc::engine::SpamLMHD::SMatVecOp(const formic::ColVec<double> & x, formic::ColVec<double> & y, const bool approximate)\n{\n\n  // size the resulting vector correctly\n  y.reset(x.size());\n\n  // since we do not have the matrix, then we need to do der_rat * le_der * x on each process\n  // the matrix free implementation is a little bit complicated, I will explain it here\n  // we have two derivative vector matrox, L(i, j) = <i|H|[psi_j>/<i|psi>, D(i, j) = <i|psi_j>/<i|psi>\n  // i denotes configuration(electron position in real space and number vector in Hilbert space)\n  // psi_j denotes wfn derivative w.r.t. jth variable, and j=0 means undifferentiated wfn\n  // note that |value/guiding|^2 and weights should be absorbed in L and D matrix\n  // in ground state calculation, H = D^T * D, Hx = D^T * Dx\n  // in excited state calculation, H = (omega * D - L)^T * (omega * D - L), temp1 = omage * D * x\n  // temp2 = Lx\n\n  // number of samples\n  int Ns = _le_der.rows();\n\n  // the number of independent variables + 1\n  const int Nind = _le_der.cols();\n\n  // check to see whether derivative vector matrices have the same size\n  if ( _le_der.rows() != _der_rat.rows() && _le_der.cols() != _der_rat.cols() )\n    throw formic::Exception(\"input derivative vectors are of different size\");\n\n  // modify number of samples based on approximate degree\n  if ( approximate )\n    Ns /= _appro_degree;\n\n  // if we are doing ground state calculation\n  if ( _ground && !approximate ) {\n\n    // temp vector that store _der_rat * x\n    formic::ColVec<double> temp(Ns);\n\n    // call blas level-2 function\n    formic::dgemv('N', Ns, Nind, 1.0, &_der_rat.at(0, 0), Ns, &x.at(0), 1, 0.0, &temp.at(0), 1);\n\n    // call blas levec-2 function\n    formic::dgemv('T', Ns, Nind, 1.0, &_der_rat.at(0, 0), Ns, &temp.at(0), 1, 0.0, &y.at(0), 1);\n\n    return;\n  }\n\n  // if we multiply by approximate matrix\n  else if ( _ground && approximate ) {\n\n    // temp vector that stores _der_rat * x\n    formic::ColVec<double> temp(Ns);\n\n    // call blas level-2 function\n    formic::dgemv('N', Ns, Nind, 1.0, &_der_rat_appro.at(0, 0), Ns, &x.at(0), 1, 0.0, &temp.at(0), 1);\n\n    // call blas level-2 function\n    formic::dgemv('T', Ns, Nind, _appro_factor, &_der_rat_appro.at(0, 0), Ns, &temp.at(0), 1, 0.0, &y.at(0), 1);\n\n    return;\n  }\n\n  else if ( !_ground && !approximate ) {\n\n    // temp vectpr to store omega * der_rat * x\n    formic::ColVec<double> temp1(Ns);\n\n    // temp vector to store le_der * x\n    formic::ColVec<double> temp2(Ns);\n\n    // temp vector that store omega * der_rat^T * (omega * der_rat - le_der) * x\n    formic::ColVec<double> temp3(x.size());\n\n    // call blas level-2 function\n    formic::dgemv('N', Ns, Nind, _hd_shift, &_der_rat.at(0, 0), Ns, &x.at(0), 1, 0.0, &temp1.at(0), 1);\n\n    // call blas level-2 function\n    formic::dgemv('N', Ns, Nind, 1.0, &_le_der.at(0, 0), Ns, &x.at(0), 1, 0.0, &temp2.at(0), 1);\n\n    // combine these two temp vector together\n    temp1 -= temp2;\n\n    // omega * D^T * (omega * D - L) * x\n    formic::dgemv('T', Ns, Nind, _hd_shift, &_der_rat.at(0, 0), Ns, &temp1.at(0), 1, 0.0, &y.at(0), 1);\n\n    // L^T * (omega * D - L) * x\n    formic::dgemv('T', Ns, Nind, 1.0, &_le_der.at(0, 0), Ns, &temp1.at(0), 1, 0.0, &temp3.at(0), 1);\n\n    // (omega * D^T - L^T) * (omega * D - L) * x\n    y -= temp3;\n\n    return;\n  }\n\n  // if we multiply by approximate matrix\n  else if ( !_ground && approximate ) {\n\n    // temp vectpr to store omega * der_rat * x\n    formic::ColVec<double> temp1(Ns);\n\n    // temp vector to store le_der * x\n    formic::ColVec<double> temp2(Ns);\n\n    // temp vector that store omega * der_rat^T * (omega * der_rat - le_der) * x\n    formic::ColVec<double> temp3(x.size());\n\n    // call blas level-2 function\n    formic::dgemv('N', Ns, Nind, _hd_shift, &_der_rat_appro.at(0, 0), Ns, &x.at(0), 1, 0.0, &temp1.at(0), 1);\n\n    // call blas level-2 function\n    formic::dgemv('N', Ns, Nind, 1.0, &_le_der_appro.at(0, 0), Ns, &x.at(0), 1, 0.0, &temp2.at(0), 1);\n\n    // combine these two temp vector together\n    temp1 -= temp2;\n\n    // omega * D^T * (omega * D - L) * x\n    formic::dgemv('T', Ns, Nind, _hd_shift, &_der_rat_appro.at(0, 0), Ns, &temp1.at(0), 1, 0.0, &y.at(0), 1);\n\n    // L^T * (omega * D - L) * x\n    formic::dgemv('T', Ns, Nind, 1.0, &_le_der_appro.at(0, 0), Ns, &temp1.at(0), 1, 0.0, &temp3.at(0), 1);\n\n    // (omega * D^T - L^T) * (omega * D - L) * x\n    y -= temp3;\n\n    // account for approximation prefactor\n    y *= _appro_factor;\n\n    return;\n  }\n}\n\n////////////////////////////////////////////////////////////////////////////////////\n// \\brief function that performs overlap matrix-matrix multiplication\n//\n// \\param[in]   x              input matrix\n// \\param[in]   matrix_built   whether we have already built the matrix or not\n// \\param[in]   approximate    whether to use approximated overlap or not\n// \\param[out]  y              result matrix\n// NOTE: Unlike hamiltonian matrix-matrix multiplication function, no transpose flag\n//       in this function because overlap matrix is assumed to be symmetric\n//\n////////////////////////////////////////////////////////////////////////////////////\n\nvoid cqmc::engine::SpamLMHD::SMatMatOp(const formic::Matrix<double> & x, formic::Matrix<double> & y, const bool approximate)\n{\n  // size the resulting matrix correctly\n  y.reset(x.rows(), x.cols());\n\n  // the number of samples on each process\n  int Ns = _le_der.rows();\n\n  // the number of independent variables\n  int Nind = _le_der.cols();\n\n  // the number of new krylov vectors\n  int Nnew = x.cols();\n\n  // if the approximate flag is set to be true, throw out an error\n  if ( approximate )\n    throw formic::Exception(\"Matrix-Matrix multiplication doesn't support approximate matrix\");\n\n  // check to see whether derivative vector matrices have the same size\n  if ( _le_der.rows() != _der_rat.rows() && _le_der.cols() != _der_rat.cols())\n    throw formic::Exception(\"the input derivative vector matrices are of different size!\");\n\n  // if we are doing ground state calculation\n  if ( _ground ) {\n\n    // temp matrix that stores _der_rat * x\n    formic::Matrix<double> temp(Ns, Nnew);\n\n    // call blas level-3 function\n    formic::dgemm('N', 'N', Ns, Nnew, Nind, 1.0, &_der_rat.at(0, 0), Ns, &x.at(0, 0), Nind, 0.0, &temp.at(0, 0), Ns);\n\n    // call blas level-3 function\n    formic::dgemm('T', 'N', Nind, Nnew, Ns, 1.0, &_der_rat.at(0, 0), Ns, &temp.at(0, 0), Ns, 0.0, &y.at(0, 0), Nind);\n\n    return;\n  }\n\n  // if we are doing excited state calculation\n  else {\n\n    // temp matrix that stores omega * der_rat * x\n    formic::Matrix<double> temp1(Ns, Nnew);\n\n    // temp matrix that stores le_der * x\n    formic::Matrix<double> temp2(Ns, Nnew);\n\n    // temp matrix that stores omega * der_rat^T * (omega * der_rat - le_der) * x\n    formic::Matrix<double> temp3(Nind, Nnew);\n\n    // call blas level-3 function\n    formic::dgemm('N', 'N', Ns, Nnew, Nind, _hd_shift, &_der_rat.at(0, 0), Ns, &x.at(0, 0), Nind, 0.0, &temp1.at(0, 0), Ns);\n\n    // call blas level-3 function\n    formic::dgemm('N', 'N', Ns, Nnew, Nind, 1.0, &_le_der.at(0, 0), Ns, &x.at(0, 0), Nind, 0.0, &temp2.at(0, 0), Ns);\n\n    // combine these two temp vectors together\n    temp1 -= temp2;\n\n    // omega * D^T * (omega * D - L) * x\n    formic::dgemm('T', 'N', Nind, Nnew, Ns, _hd_shift, &_der_rat.at(0, 0), Ns, &temp1.at(0, 0), Ns, 0.0, &y.at(0, 0), Nind);\n\n    // L^T * (omega * D - L) * x\n    formic::dgemm('T', 'N', Nind, Nnew, Ns, 1.0, &_le_der.at(0, 0), Ns, &temp1.at(0, 0), Ns, 0.0, &temp3.at(0, 0), Nind);\n\n    // (omega * D^T - L^T) * (omega * D - L) * x\n    y -= temp3;\n\n    return;\n  }\n}\n\n\n/////////////////////////////////////////////////////////////////////////////////\n// \\brief constructor\n//\n//\n//\n/////////////////////////////////////////////////////////////////////////////////\n\ncqmc::engine::SpamLMHD::SpamLMHD(const formic::VarDeps* dep_ptr,\n                                 const int nfds,\n                                 const int lm_krylov_iter,\n                                 const int inner_maxIter,\n                                 const int appro_degree,\n                                 const bool inner_print,\n                                 const double lm_eigen_thresh,\n                                 const double lm_min_S_eval,\n                                 const double appro_factor,\n                                 const bool var_deps_use,\n                                 const bool chase_lowest,\n                                 const bool chase_closest,\n                                 const bool ground,\n                                 const std::vector<double>& vf,\n                                 const double init_energy,\n                                 const double hd_shift,\n                                 const double lm_max_e_change,\n                                 const double total_weight,\n                                 const double vgsa,\n                                 formic::Matrix<double> & der_rat,\n                                 formic::Matrix<double> & le_der,\n                                 formic::Matrix<double> & der_rat_appro,\n                                 formic::Matrix<double> & le_der_appro)\n:EigenSolver<double>(dep_ptr,\n                  nfds,\n                  lm_eigen_thresh,\n                  var_deps_use,\n                  chase_lowest,\n                  chase_closest,\n                  ground,\n                  false,\n                  vf,\n                  init_energy,\n                  0.0,\n                  hd_shift,\n                  0.0,\n                  lm_max_e_change,\n                  total_weight,\n                  vgsa,\n                  der_rat,\n                  le_der),\n      _nkry(0),\n      _nkry_full(0),\n      _n_max_iter(lm_krylov_iter),\n      _inner_maxIter(inner_maxIter),\n      _appro_degree(appro_degree),\n      _inner_print(inner_print),\n      _smallest_sin_value_inner(0.0),\n      _smallest_sin_value_outer(0.0),\n      _singular_value_threshold(lm_min_S_eval),\n      _init_energy(init_energy),\n      _energy_outer(init_energy),\n      _energy_inner(init_energy),\n      _appro_factor(appro_factor),\n      _der_rat_appro(der_rat_appro),\n      _le_der_appro(le_der_appro)\n{\n}\n\n/////////////////////////////////////////////////////////////////////////////////////\n// \\brief solves the eigenvalue problem via the normal davidson method\n//\n//\n//\n/////////////////////////////////////////////////////////////////////////////////////\n\nbool cqmc::engine::SpamLMHD::iterative_solve(double & eval, std::ostream & output)\n{\n\n  int my_rank = formic::mpi::rank();\n\n  // initialize the solution vector to the unit vector along the first direction\n  _evecs.reset( ( _var_deps_use ? 1 + _dep_ptr->n_tot() : _nfds ), 0.0 );\n  _evecs.at(0) = 1.0;\n\n  // ensure that at least one vector is in the outer krylov subspace\n  if ( my_rank == 0 && _nkry == 0)\n    throw formic::Exception(\"Empty krylov subspace upon entry to iterative_solve. Did you forget to add the initial vector?\");\n\n  // return value, whether the solver is successful or not\n  bool retval = true;\n\n  // converge flag(outer)\n  bool converged_outer = false;\n\n  // converge flag(inner)\n  bool converged_inner = false;\n\n  // best outer residual\n  double _best_residual_outer = 1.0e100;\n\n  // best inner residual\n  double _best_residual_inner = 1.0e100;\n\n  // times of outer iteration\n  int iter_outer = 0;\n\n  // times of inner iteration\n  int iter_inner = 0;\n\n  // print out that we have started the iteration\n  if (my_rank == 0)\n    output << boost::format(\"iteration solving starts here(engine) \\n\") << std::endl << std::endl;\n\n  while(true) {\n    \n    // smallest singular value \n    double smallest_sin_value_outer = 0.0;\n\n    // solve subspace eigenvalue problem on root process\n    if ( my_rank == 0 ) {\n      this -> solve_subspace_nonsymmetric(true);\n    }\n\n    // send resulting eigenvalues to all processes and record it as the new best estimate\n    formic::mpi::bcast(&_energy_outer, 1);\n    eval = _energy_outer;\n\n    // check if the energy has an imaginary component and stop iteration when it does\n    formic::mpi::bcast(&_eval_was_complex, 1);\n    if ( _eval_was_complex ) {\n      if ( my_rank == 0 )\n        output << boost::format(\"spam iteration %4i: stopping due to imaginary component in energy\") % iter_outer << std::endl;\n      break;\n    }\n\n    // if energy change is unreasonable, stop iterating and set bad solve flag\n    if (std::abs(_energy_outer - _init_energy) > _max_energy_change) {\n      retval = false;\n      if ( my_rank == 0 )\n        output << boost::format(\"spam iteration %4i stopping due to too large eigenvalue change\") % iter_outer << std::endl;\n      break;\n    }\n\n    // if the overlap matrix becomes singular, stop iterating\n    formic::mpi::bcast(&_smallest_sin_value_outer, 1);\n    if (std::abs(_smallest_sin_value_outer) < _singular_value_threshold) {\n      if (my_rank == 0)\n        output << boost::format(\"spam iteration %4i stopping due to small subspace S singular value of %.2e\") % iter_outer % _smallest_sin_value_outer << std::endl;\n      break;\n    }\n\n    // construct new Krylov vector from subspace eigenvector\n    _wv1.reset(_nfds);\n    if (my_rank == 0) {\n      _wv6.reset(_nfds);\n      _wv6 = _kvecs * _sub_evec_outer;\n      // get normalization factor\n      const double temp_norm = std::sqrt(_wv6.norm2());\n\n      // normalize this new vector\n      _wv6 /= temp_norm;\n\n      // add up linear combination of Hamiltonian and overlap products to make the new residual vector\n      _wv1.reset(_nfds);\n      _wv1 = _hvecs * _sub_evec_outer;\n      _wv1 = _wv1 - _sub_eval_outer * _svecs * _sub_evec_outer;\n    }\n\n    // send this new vector to all processes\n    formic::mpi::bcast(&_wv1.at(0), _wv1.size());\n\n    // compute the residual norm and send it to all processes\n    double current_outer_residual;\n    current_outer_residual = _wv1.norm2();\n    formic::mpi::bcast(&current_outer_residual, 1);\n\n    // if this is the best residual, save it and save the new eigenvector estimate\n    if (my_rank == 0 && current_outer_residual < _best_residual_outer) {\n      _best_residual_outer = current_outer_residual;\n\n      // get current eigenvector estimate, which corresponds to the set of independent variables\n      formic::ColVec<double> ind_evecs;\n      ind_evecs = _wv6.clone();\n\n      // if our actual variables are dependent on the set of independent variables worded with here, expand the eigenvector into the full set of variables\n      if ( _var_deps_use ) {\n\n        // size the eigenvector correctly\n        _evecs.reset( (1 + _dep_ptr -> n_tot()), 0.0);\n        _evecs.at(0) = ind_evecs.at(0);\n\n        // get some temporary vectors\n        formic::ColVec<double> _evec_temp(_dep_ptr -> n_tot());\n        formic::ColVec<double> _ind_temp(_dep_ptr -> n_ind());\n        for (int i = 0; i < _ind_temp.size(); i++) {\n          _ind_temp.at(i) = ind_evecs.at(i+1);\n        }\n        _dep_ptr -> expand_ind_to_all(&_ind_temp.at(0), &_evec_temp.at(0));\n\n        for ( int i = 0; i < _evec_temp.size(); i++) {\n          _evecs.at(i+1) = _evec_temp.at(i);\n        }\n      }\n\n      // otherwise just copy the eigenvector into output since the independent and total variable sets are the same\n      else {\n        _evecs = ind_evecs.clone();\n      }\n    }\n\n    // print iteration results\n    if (my_rank == 0) {\n\n      // if we are doing ground state calculation, then print out energy\n      if ( _ground )\n        output << boost::format(\"spam outer iteration %4i:   krylov dim = %3i   energy = %20.12f       residual = %.2e           smallest_sin_value = %.2e\")\n        % iter_outer\n        % _nkry\n        % _energy_outer\n        % current_outer_residual\n        % _smallest_sin_value_outer\n        << std::endl;\n\n      // if we are doing excited state calculation, then print out target function value\n      else\n        output << boost::format(\"spam outer iteration %4i:   krylov dim = %3i   tar_fn = %20.12f       residual = %.2e           smallest_sin_value = %.2e\")\n        % iter_outer\n        % _nkry\n        % _sub_eval_outer\n        % current_outer_residual\n        % _smallest_sin_value_outer\n        << std::endl;\n    }\n\n    // check for convergence\n    converged_outer = current_outer_residual < _residual_threshold;\n\n    // if iteration has already converged, we exit iteration\n    if ( converged_outer )\n      break;\n\n    // if iteration hasn't converged, we increment the iteration count by 1 and stop if maximum number of iterations has been reached\n    if ( iter_outer ++ >= _n_max_iter)\n      break;\n\n    // now this is important, we add the new krylov basis vector to inner loop\n    this -> add_krylov_vector_inner(_wv1);\n\n    // now enter inner loop\n    while (true) {\n     \n      // average of smallest singular value\n      double smallest_sin_val_avg_inner = 0.0;\n\n      // solve subspace eigenvalue problem on root process\n      if ( my_rank == 0 ) {\n        this -> solve_subspace_nonsymmetric(false);\n      }\n\n      // send resulting eigenvalues to all processes and record it as the new best estimate\n      formic::mpi::bcast(&_energy_inner, 1);\n\n      // check if the energy(or target function) has an imaginary component and stop iteration when it does\n      formic::mpi::bcast(&_eval_was_complex, 1);\n      if ( _eval_was_complex ) {\n        if ( my_rank == 0 )\n          output << boost::format(\"spam outer iteration %4i inner iteration %4i: stopping due to imaginary component in energy\") % iter_outer % iter_inner << std::endl;\n        break;\n      }\n\n      // if energy(or target function) change is unreasonable, stop iterating but don't set bag solve flag\n      if (std::abs(_energy_inner - _init_energy) > _max_energy_change) {\n        //retval = false;\n        if ( my_rank == 0 )\n          output << boost::format(\"spam outer iteration %4i inner iteration %4i: stopping due to too large eigenvalue change\") % iter_outer % iter_inner << std::endl;\n        break;\n      }\n\n      // if the overlap matrix becomes singular, stop iterating\n      formic::mpi::bcast(&_smallest_sin_value_inner, 1);\n      if (std::abs(_smallest_sin_value_inner) < _singular_value_threshold) {\n        if (my_rank == 0)\n          output << boost::format(\"spam outer iteration %4i inner iteration %4i: stopping due to too small S singular value of %.2e\") % iter_outer % iter_inner % _smallest_sin_value_inner << std::endl;\n        break;\n      }\n\n      // construct new krylov vector from subspace eigenvector\n      if (my_rank == 0) {\n        _wv6.reset(_nfds);\n        _wv6 = _kvecs * _sub_evec_inner;\n        // get normalization factor\n        const double temp_norm = std::sqrt(_wv6.norm2());\n\n        // normalize this new vector\n        _wv6 /= temp_norm;\n\n        // add up linear combination of Hamiltonian and overlap products to make the new residual vector\n        _wv1.reset(_nfds);\n        _wv1 = _hhvecs * _sub_evec_inner;\n        _wv1 = _wv1 - _sub_eval_inner * _hsvecs * _sub_evec_inner;\n      }\n\n      // send this new vector to all processes\n      formic::mpi::bcast(&_wv1.at(0), _wv1.size());\n\n      // compute the residual norm and send it to all processes\n      double current_inner_residual;\n      current_inner_residual = _wv1.norm2();\n      formic::mpi::bcast(&current_inner_residual, 1);\n\n      // if this is the best residual, save it and save the new eigenvector estimate\n      if (my_rank == 0 && current_inner_residual < _best_residual_inner)\n        _best_residual_inner = current_inner_residual;\n\n      // print iteration results if request\n      if (my_rank == 0 && _inner_print) {\n\n        // if we are doing ground state calculation, then print out energy\n        if ( _ground )\n          output << boost::format(\"spam outer iteration %4i inner iteration %4i: krylov dim = %3i  energy = %20.12f      residual = %.2e        smallest_sin_value = %.2e\")\n          % iter_outer\n          % iter_inner\n          % _kvecs.cols()\n          % _energy_inner\n          % current_inner_residual\n          % _smallest_sin_value_inner\n          << std::endl;\n\n        // if we are doing excited state calculation, then print out target function value\n        else\n          output << boost::format(\"spam outer iteration %4i inner iteration %4i: krylov dim = %3i  energy = %20.12f      residual = %.2e        smallest_sin_value = %.2e\")\n          % iter_outer\n          % iter_inner\n          % _kvecs.cols()\n          % _sub_eval_inner\n          % current_inner_residual\n          % _smallest_sin_value_inner\n          << std::endl;\n      }\n\n      // check for convergence\n      converged_inner = current_inner_residual < _residual_threshold;\n\n      // if iteration has already converged, we exit iteration\n      if ( converged_inner )\n        break;\n\n      // if iteration hasn't converged, we increment the iteration count by 1 and stop if maximum number of iterations has been reached\n      if ( iter_inner ++ >= _inner_maxIter )\n        break;\n\n      // add this new krylov basis vector to inner loop\n      this -> add_krylov_vector_inner(_wv1);\n\n    // end of spam inner loop\n    }\n\n    // size the intermediate vectors correctly for non-root process\n    if ( my_rank != 0 )\n      _kvecs_about_to_add.reset(_nfds, _nkry - _nkry_full);\n\n    // broadcast intermediate vectors that will be added to full krylov space\n    formic::mpi::bcast(&_kvecs_about_to_add.at(0, 0), _kvecs_about_to_add.size());\n\n    // add these new krylov vectors to outer loop\n    this -> add_krylov_vectors_outer(_kvecs_about_to_add);\n\n    // clear these intermediate vectors\n    _kvecs_about_to_add.reset(0, 0);\n\n    // reset the number of inner iterations\n    iter_inner = 0;\n\n  // end of spam outer loop\n  }\n\n  // print iteration information\n  if (converged_outer && my_rank == 0)\n    output << boost::format(\"spam solver converged in %10i iterations\") % iter_outer << std::endl << std::endl;\n\n  else if (my_rank == 0)\n    output << boost::format(\"spam solver did not converge after %10i iterations\") % iter_outer << std::endl << std::endl;\n\n  return retval;\n\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////\n// \\brief solves the eigenvalue problem\n//\n//\n//\n///////////////////////////////////////////////////////////////////////////////////////////////\n\nbool cqmc::engine::SpamLMHD::solve(double & eval, std::ostream & output)\n{\n  return this -> iterative_solve(eval, output);\n}\n\n////////////////////////////////////////////////////////////////////////////////////\n// \\brief updates hamiltonian * krylov vector and hamiltonian projection based on\n//        new shift\n//\n//\n////////////////////////////////////////////////////////////////////////////////////\n\nvoid cqmc::engine::SpamLMHD::update_hvecs_sub(const double new_i_shift, const double new_s_shift)\n{\n  int my_rank = formic::mpi::rank();\n\n  // get the different between new shift and old shift\n  const double diff_shift_i = new_i_shift - _hshift_i;\n  const double diff_shift_s = new_s_shift - _hshift_s;\n\n  if (my_rank == 0) {\n    // update \"identity shift\" for the hamiltonian product\n    for (int j = 0; j < _nkry; j ++) {\n      for (int i = 1; i < _nfds; i ++) {\n        _hvecs.at(i, j) += diff_shift_i * _kvecs.at(i, j);\n        _thvecs.at(i, j) += diff_shift_i * _kvecs.at(i, j);\n      }\n    }\n\n    // update \"overlap shift\" for the hamiltonian product\n    for (int j = 1; j < _nkry; j++) {\n      for (int i = 0; i < _nfds; i++) {\n        _hvecs.at(i, j) += diff_shift_s * _svecs.at(i, j);\n        _thvecs.at(i, j) += diff_shift_s * _svecs.at(i, j);\n      }\n    }\n\n    _hhvecs = _hvecs;\n\n    // update projection of hamiltonian matrix\n    _subH = _kvecs.t() * _hvecs;\n    _hy_subH = _subH.clone();\n  }\n}\n\n////////////////////////////////////////////////////////////////////////////////////\n// \\brief reset the eigen solver\n//\n// \\brief clear subspace projection of Hamiltonian and overlap matrix, clear Krylov\n//        subspace and action of Hamiltonian and overlap matrix\n////////////////////////////////////////////////////////////////////////////////////\n\nvoid cqmc::engine::SpamLMHD::child_reset()\n{\n  // clear subspace projection of Hamiltonian and overlap matrix\n  _subH.reset(0, 0);\n  _hy_subH.reset(0, 0);\n  _subS.reset(0, 0);\n  _hy_subS.reset(0, 0);\n\n  // clear Krylov subspace\n  _nkry = 0;\n  _nkry_full = 0;\n  _kvecs.reset(0, 0);\n  _kvecs_about_to_add.reset(0, 0);\n\n  // clear Hamiltonian and overlap matrix's action on krylov subspace\n  _hvecs.reset(0, 0);\n  _thvecs.reset(0, 0);\n  _ahvecs.reset(0, 0);\n  _athvecs.reset(0, 0);\n  _hhvecs.reset(0, 0);\n\n  _svecs.reset(0, 0);\n  _asvecs.reset(0, 0);\n  _hsvecs.reset(0, 0);\n\n  // clear eigenvector and wavefunction coefficients\n  _sub_evec_outer.reset(0);\n  _sub_evec_inner.reset(0);\n  _evecs_inner.reset(0);\n\n  // clear all values calculated from last solve\n  _sub_eval_outer = 0.0;\n  _sub_eval_inner = 0.0;\n  _smallest_sin_value_outer = 1e10;\n  _smallest_sin_value_inner = 1e10;\n\n  // set the inner and outer energy to be initial energy\n  _energy_inner = _init_energy;\n  _energy_outer = _init_energy;\n}\n\n///////////////////////////////////////////////////////////////////////////////////////////////\n// \\brief converts eigenvectors into wave function coefficients\n//        solving this question Hc = Sd for d, S is the ground overlap matrix\n//\n//\n///////////////////////////////////////////////////////////////////////////////////////////////\n\nvoid cqmc::engine::SpamLMHD::child_convert_to_wf_coeff()\n{\n\n  return;\n\n}\n", "meta": {"hexsha": "02d128153154042796195a20900b1ef710bc7b46", "size": 58531, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/formic/utils/lmyengine/spam_solver.cpp", "max_stars_repo_name": "eugeneswalker/qmcpack", "max_stars_repo_head_hexsha": "352ff27f163bb92e0c232c48bec8ae7951ed9d8c", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/formic/utils/lmyengine/spam_solver.cpp", "max_issues_repo_name": "eugeneswalker/qmcpack", "max_issues_repo_head_hexsha": "352ff27f163bb92e0c232c48bec8ae7951ed9d8c", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-09T20:57:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-10T00:00:17.000Z", "max_forks_repo_path": "src/formic/utils/lmyengine/spam_solver.cpp", "max_forks_repo_name": "williamfgc/qmcpack", "max_forks_repo_head_hexsha": "732b473841e7823a21ab55ff397eed059f0f2e96", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.366163142, "max_line_length": 201, "alphanum_fraction": 0.5951888743, "num_tokens": 17577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.40584547950577704}}
{"text": "#include \"Snapshot.h\"\n#include <linux/perf_event.h>\n#define ARMA_DONT_PRINT_ERRORS\n#include <armadillo>\n#include <boost/math/distributions.hpp>\n\nSnapshot::Snapshot(int debuglevel)\n    : cycles(PERF_COUNT_HW_CPU_CYCLES),\n      instructions(PERF_COUNT_HW_INSTRUCTIONS),\n      cachemisses(PERF_COUNT_HW_CACHE_MISSES),\n      branchmisses(PERF_COUNT_HW_BRANCH_MISSES),\n      debug(debuglevel)\n{\n}\n\nSnapshot::~Snapshot()\n{\n}\n\nvoid Snapshot::start()\n{\n    if (debug >= 2)\n        std::cout << \"Snapshot start\\n\";\n    cycles.start();\n    instructions.start();\n    cachemisses.start();\n    branchmisses.start();\n}\n\nSnapshot::Sample Snapshot::stop(const std::string &evname, uint64_t numitems, uint64_t numiterations)\n{\n    Sample samp;\n    if (numiterations > 0)\n    {\n        samp.numitems = numitems;\n        samp.cycles = double(cycles.stop()) / numiterations;\n        samp.instructions = double(instructions.stop()) / numiterations;\n        samp.cachemisses = double(cachemisses.stop()) / numiterations;\n        samp.branchmisses = double(branchmisses.stop()) / numiterations;\n        samples[evname].push_back(samp);\n    }\n    if (debug >= 2)\n        std::cout << \"Snapshot stop, Items:\" << numitems\n                  << \" Cycles:\" << samp.cycles\n                  << \" Instr:\" << samp.instructions << \" CacheMiss:\"\n                  << samp.cachemisses << \" BranchMiss:\" << samp.branchmisses\n                  << \" NumIter:\" << numiterations << \"\\n\";\n\n    return samp;\n}\n\nstatic std::vector<uint32_t> calcMask(uint32_t num)\n{\n    std::vector<uint32_t> ixvec;\n    for (unsigned j = 0; num > 0; ++j, num >>= 1)\n    {\n        if ((num & 1) != 0)\n            ixvec.push_back(j);\n    }\n    return ixvec;\n}\n\n// I should really spawn this into a LinearModel class\nstruct RegResults\n{\n    bool ok;\n    arma::mat C;\n    arma::colvec b;\n    arma::colvec sol;\n    arma::colvec res;\n    arma::colvec serr;\n    arma::colvec tval;\n    arma::colvec pval;\n\n    double fval;\n    double fpval;\n    double rsq;\n    double rsqadj;\n    double loglik;\n    double aic;\n    double bic;\n\n    bool solve();\n};\n\nstatic bool calcModel(uint32_t modelnum,\n                      const arma::mat &C,\n                      const arma::vec &b,\n                      RegResults &reg)\n{\n    auto ixvec = calcMask(modelnum);\n    uint32_t numcols = ixvec.size();\n    uint32_t numrows = C.n_rows;\n    reg.b = b;\n    reg.C.resize(numrows, numcols);\n    for (uint32_t j = 0; j < numcols; ++j)\n    {\n        reg.C.col(j) = C.col(ixvec[j]);\n    }\n    return reg.solve();\n}\n\nstatic arma::colvec cdf(const arma::colvec &x, uint32_t ndof)\n{\n    unsigned nrows = x.n_rows;\n    arma::colvec y(nrows);\n    boost::math::students_t st(ndof);\n    for (unsigned j = 0; j < nrows; ++j)\n    {\n        y(j) = cdf(st, x(j));\n    }\n    return y;\n}\n\nbool RegResults::solve()\n{\n    // Dimensionality of the problem\n    uint32_t nobs = C.n_rows;\n    uint32_t ncoef = C.n_cols;\n\n    // Initialize all metrics to NAN\n    rsq = rsqadj = fval = fpval = loglik = aic = bic = std::numeric_limits<double>::quiet_NaN();\n\n    // Check dimensions\n    if (nobs <= ncoef)\n        return false;\n\n    // Solve system with LSQ\n    ok = arma::solve(sol, C, b);\n    if (not ok)\n        return false;\n\n    try\n    {\n        // Residuals\n        res = b - C * sol;\n\n        // Degrees of freedom\n        uint32_t ndof = nobs - ncoef;\n\n        // Variance of residuals\n        double s2 = arma::dot(res, res) / ndof;\n\n        // Standard errors\n        serr = arma::sqrt(s2 * arma::diagvec(arma::pinv(C.t() * C)));\n\n        // t-values and respective p-values\n        tval = sol / serr;\n        pval = (1 - cdf(arma::abs(tval), ndof)) * 2;\n\n        // R-squared measures\n        rsq = 1 - arma::dot(res, res) / arma::dot(b, b);\n        rsqadj = 1 - (1 - rsq) * ((nobs - 1) / (nobs - ncoef));\n\n        // Compute F-value and respective probability for model selection\n        fval = (rsq / (ncoef - 1)) / ((1 - rsq) / ndof);\n        boost::math::fisher_f ff(ncoef - 1, nobs - ncoef);\n        fpval = 1 - cdf(ff, fval);\n\n        // log likelihood for model selection with Akaike information coefficients\n        loglik = -(nobs * 0.5) * (1 + log(2 * M_PI)) - (nobs / 2.) * log(arma::dot(res, res) / nobs);\n        aic = -(2. * loglik) / nobs + double(2 * ncoef) / nobs;\n        bic = -(2. * loglik) / nobs + double(ncoef * log(nobs)) / nobs;\n    }\n    catch (...)\n    {\n        // bad luck\n        return false;\n    }\n    return true;\n}\n\nvoid Snapshot::summary(const std::string &header, FILE *f)\n{\n    static const std::vector<std::string> colnames = {\"Constant\",\n                                                      \"CacheMisses\",\n                                                      \"BranchMisses\",\n                                                      \"Log(N)\", \"N\",\n                                                      \"N*Log(N)\", \"N^2\"};\n\n    // cycle through events map\n    for (const auto &ism : samples)\n    {\n        std::string evname = ism.first;\n        const std::vector<Sample> &svec(ism.second);\n\n        // fill in data matrix with all points collected\n        uint32_t numpoints = svec.size();\n        double suminstr = 0;\n        double sumbranches = 0;\n        double sumcycles = 0;\n        arma::mat C(numpoints, 7);\n        arma::vec b(numpoints);\n        for (unsigned j = 0; j < numpoints; ++j)\n        {\n            const Sample &sm(svec[j]);\n            C(j, 0) = 1;\n            C(j, 1) = double(sm.cachemisses);\n            C(j, 2) = double(sm.branchmisses);\n            C(j, 3) = log(sm.numitems);\n            C(j, 4) = sm.numitems;\n            C(j, 5) = sm.numitems * log(sm.numitems);\n            C(j, 6) = sm.numitems * sm.numitems;\n            b(j) = double(sm.cycles);\n            suminstr += double(sm.instructions);\n            sumcycles += double(sm.cycles);\n            sumbranches += double(sm.branchmisses);\n        }\n        double cycinstr = suminstr > 0 ? sumcycles / suminstr : -1;\n        double cycbranch = sumbranches > 0 ? sumcycles / sumbranches : -1;\n\n        RegResults bestreg;\n        bool found = false;\n        uint32_t bestmodel = 0;\n        for (uint32_t np = 0; np < 4; np++)\n        {\n            for (uint32_t k = 1; k <= 7; ++k)\n            {\n                uint32_t modelnum = k + (1 << (np + 3));\n                RegResults reg;\n                if (calcModel(modelnum, C, b, reg))\n                {\n                    if (reg.pval.max() > 0.05)\n                        continue;\n\n                    if ((not found) or (reg.aic < bestreg.aic))\n                    {\n                        bestreg = reg;\n                        bestmodel = modelnum;\n                        found = true;\n                    }\n                }\n                if (debug > 0)\n                {\n                    fprintf(f, \"%s, Event:%s, Cyc/Ins:%3.2f Cyc/Bch:%3.2f Points:%d Rsq:%5.2f F:%f LL:%f aic:%f bic:%f \\n\",\n                            header.c_str(), evname.c_str(),\n                            cycinstr, cycbranch, numpoints,\n                            reg.rsq, reg.fpval,\n                            reg.loglik, reg.aic, reg.bic);\n\n                    auto mask = calcMask(bestmodel);\n                    for (unsigned j = 0; j < mask.size(); ++j)\n                    {\n                        fprintf(f, \"   Term: %-12s  p:%7.5f coef:%g\\n\",\n                                colnames[mask[j]].c_str(),\n                                reg.pval(j),\n                                reg.sol(j));\n                    }\n                }\n            }\n        }\n\n        if (not found)\n        {\n            fprintf(f, \"    Model did not converge\\n\");\n        }\n        else\n        {\n            fprintf(f, \"\\n========== Best Model\\n%s, Event:%s, Cyc/Ins:%3.2f Cyc/Bch:%3.2f Points:%d Rsq:%5.2f F:%f LL:%f aic:%f bic:%f \\n\",\n                    header.c_str(), evname.c_str(),\n                    cycinstr, cycbranch, numpoints,\n                    bestreg.rsq, bestreg.fpval,\n                    bestreg.loglik, bestreg.aic, bestreg.bic);\n\n            auto mask = calcMask(bestmodel);\n            for (unsigned j = 0; j < mask.size(); ++j)\n            {\n                fprintf(f, \"   Term: %-12s  p:%7.5f coef:%g\\n\",\n                        colnames[mask[j]].c_str(),\n                        bestreg.pval(j),\n                        bestreg.sol(j));\n            }\n        }\n    }\n}\n", "meta": {"hexsha": "ea1950c509b2404761c699998bf2801016a5745d", "size": 8357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Snapshot.cpp", "max_stars_repo_name": "HFTrader/tiny-cpp-perf-stats", "max_stars_repo_head_hexsha": "dffac6b7a952e6dc7394d7ed39865a31be4ef43d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2016-05-03T05:59:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T20:43:42.000Z", "max_issues_repo_path": "Snapshot.cpp", "max_issues_repo_name": "HFTrader/tiny-cpp-perf-stats", "max_issues_repo_head_hexsha": "dffac6b7a952e6dc7394d7ed39865a31be4ef43d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-30T09:02:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-01T22:52:21.000Z", "max_forks_repo_path": "Snapshot.cpp", "max_forks_repo_name": "HFTrader/tiny-cpp-perf-stats", "max_forks_repo_head_hexsha": "dffac6b7a952e6dc7394d7ed39865a31be4ef43d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-07-16T15:21:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-09T19:06:29.000Z", "avg_line_length": 30.2789855072, "max_line_length": 140, "alphanum_fraction": 0.4866578916, "num_tokens": 2223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.6334102775181399, "lm_q1q2_score": 0.4057853346022106}}
{"text": "#include \"pybind11/pybind11.h\"\n\n#include \"xtensor/xmath.hpp\"\n#include \"xtensor/xarray.hpp\"\n#include <boost/pending/disjoint_sets.hpp>\n\n#define FORCE_IMPORT_ARRAY\n#include \"xtensor-python/pytensor.hpp\"\n\n#include <iostream>\n#include <numeric>\n#include <cmath>\n\nnamespace py = pybind11;\n\n\nxt::pytensor<uint64_t, 2> watershed(const xt::pytensor<float, 2> & weights,\n                                    xt::pytensor<uint64_t, 2> & seeds)\n{\n    typedef typename xt::pytensor<float, 2>::shape_type IndexType;\n    const auto & shape = weights.shape();\n    const std::size_t n_nodes = shape[0] * shape[1];\n\n    // make union find and map seeds to reperesentatives\n    std::vector<uint64_t> ranks(n_nodes);\n    std::vector<uint64_t> parents(n_nodes);\n    boost::disjoint_sets<uint64_t*, uint64_t*> ufd(&ranks[0], &parents[0]);\n    for(uint64_t node = 0; node < n_nodes; ++node) {\n        ufd.make_set(node);\n    }\n\n    // argsort the edges by edge weight\n    auto flat_weights = xt::flatten(weights);\n    auto flat_seeds = xt::flatten(seeds);\n\n    std::vector<std::size_t> argsorted(n_nodes);\n    std::iota(argsorted.begin(), argsorted.end(), 0);\n    std::sort(argsorted.begin(), argsorted.end(), [&](const std::size_t a,\n                                                      const std::size_t b){\n        return flat_weights[a] < flat_weights[b];}\n    );\n\n    const int n_ngbs = 4;\n    std::vector<int> shifts_x = {-1, 1, 0, 0};\n    std::vector<int> shifts_y = {0, 0, -1, 1};\n\n    // run kruskal\n    for(const uint64_t u : argsorted) {\n        // get representative\n        const uint64_t ru = ufd.find_set(u);\n\n        // get seed\n        uint64_t seed_u = flat_seeds[ru];\n        if(seed_u == 0) {\n            seed_u = seeds[u];\n            flat_seeds[ru] = seed_u;\n        } else {\n            const uint64_t seed_uu = seeds[u];\n            if(seed_uu != 0 && seed_uu != seed_u) {\n                std::cout << u << \", \" << ru << \" : \" << seed_uu << \", \" << seed_u << std::endl;\n                throw std::runtime_error(\"Seeds disagree!\");\n            }\n        }\n\n        const auto coordinate = xt::unravel_index(u, shape);\n        std::vector<IndexType> neighbor_coords;\n\n        // make the neighbors\n        for(unsigned ngb = 0; ngb < n_ngbs; ++ngb) {\n            const int sx = shifts_x[ngb];\n            const int sy = shifts_y[ngb];\n            const int64_t x = coordinate[0] + sx;\n            const int64_t y = coordinate[1] + sy;\n\n            // bounds check\n            if(sx < 0 || sx >= shape[0]) {\n                continue;\n            }\n            if(sy < 0 || sy >= shape[1]) {\n                continue;\n            }\n\n            neighbor_coords.emplace_back(IndexType({x, y}));\n        }\n\n        const auto neighbors = xt::ravel_indices(neighbor_coords, shape);\n        // iterate over the neighbors\n        for(const uint64_t v: neighbors) {\n            const uint64_t rv = ufd.find_set(v);\n            if(ru == rv) {\n                continue;\n            }\n\n            const uint64_t seed_v = flat_seeds[v];\n            if(seed_u != 0 && seed_v != 0 && (seed_v != seed_u)) {\n                continue;\n            }\n\n            ufd.link(ru, rv);\n            if(seed_u != 0) {\n                flat_seeds[ru] = seed_u;\n                flat_seeds[rv] = seed_u;\n            }\n            else if(seed_v != 0) {\n                flat_seeds[ru] = seed_v;\n                flat_seeds[rv] = seed_v;\n            }\n        }\n    }\n\n    xt::pytensor<uint64_t, 2> seg = xt::zeros<uint64_t>(shape);\n    return seg;\n}\n\nPYBIND11_MODULE(wsxt, m)\n{\n    xt::import_numpy();\n\n    m.doc() = R\"pbdoc(\n        wsxt\n\n        .. currentmodule:: wsxt\n\n        .. autosummary::\n           :toctree: _generate\n\n           watershed\n    )pbdoc\";\n\n    m.def(\"watershed\", watershed, \"compute watershed\");\n}\n", "meta": {"hexsha": "9a5b9cbedc9c70eab02af70825ce641626403a65", "size": 3793, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wsxt/src/main.cpp", "max_stars_repo_name": "constantinpape/fastpy", "max_stars_repo_head_hexsha": "b3b4f7114b393d4c4d413b13ed032461fd2e903e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "wsxt/src/main.cpp", "max_issues_repo_name": "constantinpape/fastpy", "max_issues_repo_head_hexsha": "b3b4f7114b393d4c4d413b13ed032461fd2e903e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wsxt/src/main.cpp", "max_forks_repo_name": "constantinpape/fastpy", "max_forks_repo_head_hexsha": "b3b4f7114b393d4c4d413b13ed032461fd2e903e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-09T15:02:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-09T15:02:31.000Z", "avg_line_length": 28.7348484848, "max_line_length": 96, "alphanum_fraction": 0.5270234643, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4057470702544803}}
{"text": "// This file is part of PolyMPC, a lightweight C++ template library\n// for real-time nonlinear optimization and optimal control.\n//\n// Copyright (C) 2020 Listov Petr <petr.listov@epfl.ch>\n//\n// This Source Code Form is subject to the terms of the Mozilla\n// Public License v. 2.0. If a copy of the MPL was not distributed\n// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#ifndef UTILS_HPP\n#define UTILS_HPP\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n\ntemplate <typename qp_t>\nvoid print_qp(qp_t qp)\n{\n    Eigen::IOFormat fmt(Eigen::StreamPrecision, 0, \", \", \",\", \"[\", \"]\", \"[\", \"]\");\n    std::cout << \"P = \" << qp.P.format(fmt) << std::endl;\n    std::cout << \"q = \" << qp.q.transpose().format(fmt) << std::endl;\n    std::cout << \"A = \" << qp.A.format(fmt) << std::endl;\n    std::cout << \"l = \" << qp.l.transpose().format(fmt) << std::endl;\n    std::cout << \"u = \" << qp.u.transpose().format(fmt) << std::endl;\n}\n\ntemplate <typename Mat>\nbool is_psd(Mat &h)\n{\n    Eigen::EigenSolver<Mat> eigensolver(h);\n    for (int i = 0; i < eigensolver.eigenvalues().RowsAtCompileTime; i++) {\n        double v = eigensolver.eigenvalues()(i).real();\n        if (v < 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\n#endif /* UTILS_HPP */\n", "meta": {"hexsha": "fbd6adf07f2c363ad68328c663fa6a348ba496dd", "size": 1293, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "polympc/src/solvers/utils.hpp", "max_stars_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_stars_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "polympc/src/solvers/utils.hpp", "max_issues_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_issues_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "polympc/src/solvers/utils.hpp", "max_forks_repo_name": "alexandreguerradeoliveira/rocket_gnc", "max_forks_repo_head_hexsha": "164e96daca01d9edbc45bfaac0f6b55fe7324f24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7857142857, "max_line_length": 82, "alphanum_fraction": 0.6133023975, "num_tokens": 374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.40570785204945337}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the library KASKADE 7                               */\n/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */\n/*                                                                           */\n/*  Copyright (C) 2002-2011 Zuse Institute Berlin                            */\n/*                                                                           */\n/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */\n/*    see $KASKADE/academic.txt                                              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#ifndef LIMEX_HH\n#define LIMEX_HH\n\n#include <boost/timer/timer.hpp>\n\n#include \"timestepping/extrapolation.hh\"\n#include \"fem/iterate_grid.hh\"\n#include \"timestepping/semieuler.hh\"\n\nnamespace Kaskade\n{\n  /**\n   * This class implements the extrapolated linearly implicit Euler\n   * method for integrating time-dependent evolution problems. The\n   * implementation follows Deuflhard/Bornemann Chapter 6.4.3.\n   *\n   * \\todo Currently the matrix \\f$ B \\f$ has to be constant.\n   */\n  template <class Eq>\n  class Limex\n  {\n  public:\n    typedef Eq                                                     EvolutionEquation;\n    typedef typename EvolutionEquation::AnsatzVars::VariableSet State;\n\n  private:\n    typedef SemiLinearizationAt<SemiImplicitEulerStep<EvolutionEquation> > Linearization;\n    typedef VariationalFunctionalAssembler<Linearization> GOp;\n\n  public:\n    /**\n     * Constructs an ODE integrator. The arguments eq and ansatzVars\n     * have to exist during the lifetime of the integrator.\n     */\n    Limex(GridManager<typename EvolutionEquation::AnsatzVars::Grid>& gridManager,\n        EvolutionEquation& eq_, typename EvolutionEquation::AnsatzVars const& ansatzVars_,\n        std::vector<std::pair<double,double> > const& tolX):\n          ansatzVars(ansatzVars_), eq(&eq_,0), gop(gridManager.signals,ansatzVars.spaces), extrap(0),\n          rhsAssemblyTime(0.0), matrixAssemblyTime(0.0), factorizationTime(0.0), solutionTime(0.0) {}\n\n    /**\n     * Computes a state increment that advances the given state in\n     * time. The time in the given evolution equation is increased by\n     * dt.\n     *\n     * \\param x the initial state to be evolved\n     * \\param dt the time step\n     * \\param order the extrapolation order\n     * \\return the state increment (references an internal variable that will be invalidated by a subsequent call of step)\n     *\n     * \\todo (i) check for B constant, do not reassemble matrix in this case (ii) implement fixed point\n     * iteration instead of new factorization in case B is not constant\n     */\n    State const& step(State const& x, double dt, int order)\n    {\n      boost::timer::cpu_timer timer;\n\n      std::vector<double> stepFractions(order+1);\n      for (int i=0; i<=order; ++i) stepFractions[i] = 1.0/(i+1);\n      extrap.clear();\n\n      int const nvars = EvolutionEquation::AnsatzVars::noOfVariables;\n      int const neq = EvolutionEquation::TestVars::noOfVariables;\n      size_t nnz = gop.nnz(0,neq,0,nvars,false);\n      size_t size = ansatzVars.degreesOfFreedom(0,nvars);\n\n      std::vector<int> ridx(nnz), cidx(nnz);\n      std::vector<double> data(nnz), rhs(size), sol(size);\n\n      State dx(x), dxsum(x), tmp(x);\n      double const t = eq.time();\n\n      eq.temporalEvaluationRange(t,t+dt);\n\n      for (int i=0; i<=order; ++i) {\n        double const tau = stepFractions[i]*dt;\n        eq.setTau(tau);\n        eq.time(t);\n\n        // Evaluate and factorize matrix B(t)-tau*J\n        dx *= 0;\n        timer.start();\n        gop.assemble(Linearization(eq,x,x,dx));\n        matrixAssemblyTime += (double)(timer.elapsed().user)/1e9;\n\n        timer.start();\n        gop.toTriplet(0,neq,0,nvars,ridx.begin(),cidx.begin(),data.begin(),false);\n        UMFFactorization<double> matrix(size,0,ridx,cidx,data);\n        factorizationTime += timer.elapsed();\n\n        // First right hand side (j=0) has been assembled together with matrix.\n        timer.start();\n        gop.toSequence(0,neq,rhs.begin());\n        for (int k=0; k<rhs.size(); ++k) assert(finite(rhs[k]));\n        matrix.solve(rhs,sol);\n        for (int k=0; k<sol.size(); ++k) assert(finite(sol[k]));\n        dx.read(sol.begin());\n        dxsum = dx;\n        solutionTime += (double)(timer.elapsed().user)/1e9;\n\n        // propagate by linearly implicit Euler\n        for (int j=1; j<=i; ++j) {\n          // Assemble new right hand side tau*f(x_j)+(B(t)-B(t+j*tau))*dx_(j-1)\n          eq.time(eq.time()+tau);\n          tmp = x; tmp += dxsum;\n          timer.start();\n          gop.assemble(Linearization(eq,tmp,x,dx),GOp::RHS);\n          rhsAssemblyTime += timer.elapsed();\n          timer.start();\n          gop.toSequence(0,neq,rhs.begin());\n          for (int k=0; k<rhs.size(); ++k) assert(finite(rhs[k]));\n          matrix.solve(rhs,sol);\n          for (int k=0; k<sol.size(); ++k) assert(finite(sol[k]));\n          dx.read(sol.begin());\n          dxsum += dx;\n          solutionTime += (double)(timer.elapsed().user)/1e9;\n        }\n\n        // insert into extrapolation tableau\n        extrap.push_back(dxsum,stepFractions[i]);\n\n        // restore initial time\n        eq.time(t);\n      }\n\n      return extrap.back();\n    }\n\n    double estimateError(State const& x,int i, int j) const\n    {\n      assert(extrap.size()>1);\n\n      std::vector<std::pair<double,double> > e(ansatzVars.noOfVariables);\n\n      relativeError(typename EvolutionEquation::AnsatzVars::Variables(),extrap[i].data,\n                    extrap[j].data,x.data,ansatzVars.spaces,eq.scaling(),\n                    e.begin());\n\n      return e[0].first/(0.1+e[0].second);\n    }\n\n    template <class OutStream>\n    void reportTime(OutStream& out) const {\n      out << \"Limex time: \" << matrixAssemblyTime << \"s matrix assembly\\n\"\n          << \"            \" << rhsAssemblyTime << \"s rhs assembly\\n\"\n          << \"            \" << factorizationTime << \"s factorization\\n\"\n          << \"            \" << solutionTime << \"s solution\\n\";\n    }\n\n    void advanceTime(double dt) { eq.time(eq.time()+dt); }\n\n\n  private:\n    typename EvolutionEquation::AnsatzVars const& ansatzVars;\n    SemiImplicitEulerStep<EvolutionEquation>  eq;\n    GOp                                       gop;\n\n  public:\n    ExtrapolationTableau<State>  extrap;\n    double rhsAssemblyTime, matrixAssemblyTime, factorizationTime, solutionTime;\n  };\n} // namespace Kaskade\n#endif\n", "meta": {"hexsha": "2671adfa0fa6e0cb373d126dae95c5624fc83bc7", "size": 6703, "ext": "hh", "lang": "C++", "max_stars_repo_path": "Kaskade/timestepping/limex.hh", "max_stars_repo_name": "chenzongxiong/streambox", "max_stars_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-07-03T14:03:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T10:18:49.000Z", "max_issues_repo_path": "Kaskade/timestepping/limex.hh", "max_issues_repo_name": "chenzongxiong/streambox", "max_issues_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-02-17T12:01:30.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T22:02:33.000Z", "max_forks_repo_path": "Kaskade/timestepping/limex.hh", "max_forks_repo_name": "chenzongxiong/streambox", "max_forks_repo_head_hexsha": "76f95780d1bf6c02731e39d8ac73937cea352b95", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T04:41:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-11T21:44:42.000Z", "avg_line_length": 38.0852272727, "max_line_length": 122, "alphanum_fraction": 0.5652692824, "num_tokens": 1696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.40570785204945337}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n#include <complex>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/morton_dense.hpp> \n#include <boost/numeric/mtl/matrix/compressed2D.hpp> \n#include <boost/numeric/mtl/matrix/map_view.hpp>\n#include <boost/numeric/mtl/matrix/hermitian_view.hpp>\n#include <boost/numeric/mtl/matrix/inserter.hpp>\n#include <boost/numeric/mtl/recursion/predefined_masks.hpp>\n#include <boost/numeric/mtl/operation/print.hpp>\n#include <boost/numeric/mtl/operation/set_to_zero.hpp>\n#include <boost/numeric/mtl/operation/conj.hpp>\n#include <boost/numeric/mtl/operation/imag.hpp>\n#include <boost/numeric/mtl/operation/real.hpp>\n#include <boost/numeric/mtl/operation/scale.hpp>\n#include <boost/numeric/mtl/operation/hermitian.hpp>\n#include <boost/numeric/mtl/operation/operators.hpp>\n#include <boost/numeric/mtl/operation/mult_result.hpp>\n#include <boost/numeric/mtl/utility/ashape.hpp>\n\n\nusing namespace std;  \n\ntypedef complex<double> ct;\n\ndouble value(double)\n{\n    return 7.0;\n}\n\ncomplex<double> value(complex<double>)\n{\n    return ct(7.0, 1.0);\n}\n\n// scaled value\ndouble svalue(double)\n{\n    return 14.0;\n}\n\nct svalue(ct)\n{\n    return ct(14.0, 2.0);\n}\n\n// conjugated value\ndouble cvalue(double)\n{\n    return 7.0;\n}\n\nct cvalue(ct)\n{\n    return ct(7.0, -1.0);\n}\n\n// complex scaled value\nct csvalue(double)\n{\n    return ct(0.0, 7.0);\n}\n\nct csvalue(ct)\n{\n    return ct(-1.0, 7.0);\n}\n\n\ntemplate <typename Matrix>\nvoid test(Matrix& matrix, const char* name)\n{\n    using mtl::conj; using mtl::imag; using mtl::real;\n\n    set_to_zero(matrix);\n    typename Matrix::value_type ref(0);\n\n    {\n\tmtl::mat::inserter<Matrix>  ins(matrix);\n\tins(2, 3) << value(ref);\n\tins(4, 3) << value(ref) + 1.0;\n\tins(2, 5) << value(ref) + 2.0;\n    }\n\n    cout << \"\\n\\n\" << name << \"\\n\";\n    cout << \"Original matrix:\\n\" << matrix << \"\\n\";\n\n    mtl::mat::scaled_view<double, Matrix>  scaled_matrix(2.0, matrix);\n    cout << \"matrix  scaled with 2.0\\n\" << scaled_matrix << \"\\n\";\n    MTL_THROW_IF(scaled_matrix(2, 3) != svalue(ref), mtl::runtime_error(\"scaling wrong\"));\n   \n    cout << \"matrix  scaled with 2.0 (as operator)\\n\" << 2.0 * matrix << \"\\n\";\n    MTL_THROW_IF((2.0 * matrix)(2, 3) != svalue(ref), mtl::runtime_error(\"scaling wrong\"));\n\n    mtl::mat::conj_view<Matrix>  conj_matrix(matrix);\n    cout << \"conjugated matrix\\n\" << conj_matrix << \"\\n\";\n    MTL_THROW_IF(conj_matrix(2, 3) != cvalue(ref), mtl::runtime_error(\" wrong\"));\n\n    mtl::mat::scaled_view<ct, Matrix>  cscaled_matrix(ct(0.0, 1.0), matrix);\n    cout << \"matrix scaled with i (complex(0, 1))\\n\" << cscaled_matrix << \"\\n\";\n    MTL_THROW_IF(cscaled_matrix(2, 3) != csvalue(ref), mtl::runtime_error(\"complex scaling wrong\"));\n\n    mtl::mat::hermitian_view<Matrix>  hermitian_matrix(matrix);\n    cout << \"Hermitian matrix (conjugate transposed)\\n\" << hermitian_matrix << \"\\n\";\n    MTL_THROW_IF(hermitian_matrix(3, 2) != cvalue(ref), mtl::runtime_error(\"conjugate transposing  wrong\"));\n\n    cout << \"matrix  scaled with 2.0 (free function)\\n\" << scale(2.0, matrix) << \"\\n\";\n    MTL_THROW_IF(scale(2.0, matrix)(2, 3) != svalue(ref), mtl::runtime_error(\"scaling wrong\"));\n\n    cout << \"matrix  scaled with 2.0 (free function as mtl::scale)\\n\" << mtl::scale(2.0, matrix) << \"\\n\";\n\n#if defined(__GNUC__) && __GNUC__ == 4 && (__GNUC_MINOR__ >= 3 && __GNUC_MINOR__ <= 6)\n    cout << \"conjugated matrix (free function) \\n\" << mtl::mat::conj(matrix) << \"\\n\";\n    MTL_THROW_IF(mtl::mat::conj(matrix)(2, 3) != cvalue(ref), mtl::runtime_error(\"conjugating wrong\"));\n\n    cout << \"imaginary part of matrix (free function) \\n\" << mtl::mat::imag(matrix) << \"\\n\";\n    MTL_THROW_IF(mtl::mat::imag(matrix)(2, 3) != imag(value(ref)), mtl::runtime_error(\"imaginary part wrong\"));\n\n    cout << \"real part of matrix (free function) \\n\" << mtl::mat::real(matrix) << \"\\n\";\n    MTL_THROW_IF(mtl::mat::real(matrix)(2, 3) != real(value(ref)), mtl::runtime_error(\"real part wrong\"));\n#else\n    cout << \"conjugated matrix (free function) \\n\" << conj(matrix) << \"\\n\";\n    MTL_THROW_IF(conj(matrix)(2, 3) != cvalue(ref), mtl::runtime_error(\"conjugating wrong\"));\n\n    cout << \"imaginary part of matrix (free function) \\n\" << imag(matrix) << \"\\n\";\n    MTL_THROW_IF(imag(matrix)(2, 3) != imag(value(ref)), mtl::runtime_error(\"imaginary part wrong\"));\n\n    cout << \"real part of matrix (free function) \\n\" << real(matrix) << \"\\n\";\n    MTL_THROW_IF(real(matrix)(2, 3) != real(value(ref)), mtl::runtime_error(\"real part wrong\"));\n#endif\n    cout << \"negation of matrix (free function) \\n\" << -matrix << \"\\n\";\n    MTL_THROW_IF((-matrix)(2, 3) != -(value(ref)), mtl::runtime_error(\"negation wrong\"));\n\n    cout << \"matrix scaled with i (complex(0, 1)) (free function)\\n\" << scale(ct(0.0, 1.0), matrix) << \"\\n\";\n    MTL_THROW_IF(scale(ct(0.0, 1.0), matrix)(2, 3) != csvalue(ref), mtl::runtime_error(\"complex scaling wrong\"));\n\n    cout << \"Hermitian  matrix (conjugate transposed) (free function)\\n\" << hermitian(matrix) << \"\\n\";\n    MTL_THROW_IF(hermitian(matrix)(3, 2) != cvalue(ref), mtl::runtime_error(\"conjugate transposing wrong\"));\n\n\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    using namespace mtl;\n    unsigned size= 7; \n    if (argc > 1) size= atoi(argv[1]); \n\n    dense2D<double>                                      dr(size, size);\n    dense2D<double, mat::parameters<col_major> >      dc(size, size);\n    morton_dense<double, recursion::morton_z_mask>       mzd(size, size);\n    morton_dense<double, recursion::doppled_2_row_mask>  d2r(size, size);\n    compressed2D<double>                                 cr(size, size);\n    compressed2D<double, mat::parameters<col_major> > cc(size, size);\n\n    dense2D<complex<double> >                            drc(size, size);\n    compressed2D<complex<double> >                       crc(size, size);\n\n\n    test(dr, \"Dense row major\");\n    test(dc, \"Dense column major\");\n    test(mzd, \"Morton Z-order\");\n    test(d2r, \"Hybrid 2 row-major\");\n    test(cr, \"Compressed row major\");\n    test(cc, \"Compressed column major\");\n    test(drc, \"Dense row major complex\");\n    test(crc, \"Compressed row major complex\");\n\n    double p(2.0);\n    dr=-dr;\n\n#if defined(__GNUC__) && __GNUC__ == 4 && (__GNUC_MINOR__ >= 3 && __GNUC_MINOR__ <= 6)\n    std::cout << \"Only for gcc 4.4.\\n\";\n    dr=mat::real(dr);\n    dr=mat::conj(dr)+p*mat::imag(dr);\n#else\n    dr=real(dr);\n    dr=conj(dr)+p*imag(dr);\n#endif\n    return 0;\n}\n", "meta": {"hexsha": "07753bb204bae5a2c26d454a3778b976dadb6e78", "size": 6851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_map_view_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/matrix_map_view_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/matrix_map_view_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 34.7766497462, "max_line_length": 113, "alphanum_fraction": 0.643117793, "num_tokens": 2095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.6261241632752915, "lm_q1q2_score": 0.40560212570123927}}
{"text": "/**\n * \\file boost/numeric/ublasx/operation/balance.hpp\n *\n * \\brief Balance a matrix or a pair of matrices to improve eigenvalue accuracy.\n *\n * <hr/>\n *\n * Copyright (c) 2011, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_BALANCE_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_BALANCE_HPP\n\n\n#include <boost/mpl/assert.hpp>\n#include <boost/numeric/bindings/lapack/computational/gebak.hpp>\n#include <boost/numeric/bindings/lapack/computational/gebal.hpp>\n#include <boost/numeric/bindings/lapack/computational/ggbak.hpp>\n#include <boost/numeric/bindings/lapack/computational/ggbal.hpp>\n#include <boost/numeric/bindings/tag.hpp>\n#include <boost/numeric/bindings/ublas.hpp>\n#include <boost/numeric/ublas/detail/config.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/vector_expression.hpp>\n#include <boost/numeric/ublasx/detail/debug.hpp>\n#include <boost/numeric/ublasx/operation/num_columns.hpp>\n#include <boost/numeric/ublasx/operation/num_rows.hpp>\n#include <boost/numeric/ublasx/operation/size.hpp>\n#include <boost/numeric/ublasx/traits/layout_type.hpp>\n#include <boost/type_traits/is_same.hpp>\n\n\n//TODO: implement overloaded functions for matrices with special structure (e.g., symmetric matrices).\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\nnamespace detail { namespace /*<unnamed>*/ {\n\n/**\n * \\brief Diagonal matrix balancing to improve eigenvalue accuracy.\n *\n * \\tparam MatrixT The type of the matrix to be balanced.\n * \\tparam SVectorT The type of the scaling vector.\n * \\tparam PVectorT The type of the permuting vector.\n * \\tparam BVectorT The type of the balancing matrix.\n *\n * \\param A The matrix to be balanced.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\param want_scaling_vec Tells if the caller has requested to compute the\n *  scaling vector.\n * \\param scaling_vec The computed scaling vector.\n * \\param want_permuting_vec Tells if the caller has requested to compute the\n *  permutation vector.\n * \\param permuting_vec The computed permuting vector.\n * \\param want_balancing_mat Tells if the caller has requested to compute the\n *  balancing matrix.\n * \\param balancing_mat The computed balancing matrix.\n * \\return none, but \\a A, \\a scaling_vec, \\a permuting_vec, and\n *  \\a balancing_mat are changed (possibly, if requested).\n *\n * Version for matrices with column-major layout.\n */\ntemplate <\n\ttypename MatrixT,\n\ttypename SVectorT,\n\ttypename PVectorT,\n\ttypename BMatrixT\n>\nvoid balance_impl(MatrixT& A,\n\t\t\t\t  bool scale,\n\t\t\t\t  bool permute,\n\t\t\t\t  bool want_scaling_vec,\n\t\t\t\t  SVectorT& scaling_vec,\n\t\t\t\t  bool want_permuting_vec,\n\t\t\t\t  PVectorT& permuting_vec,\n\t\t\t\t  bool want_balancing_mat,\n\t\t\t\t  BMatrixT& balancing_mat,\n\t\t\t\t  column_major_tag)\n{\n\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n\ttypedef typename matrix_traits<MatrixT>::size_type size_type;\n\ttypedef typename type_traits<value_type>::real_type real_type;\n\ttypedef vector<real_type> work_vector_type;\n\n\t// pre: A must be square\n\tBOOST_UBLAS_CHECK(\n\t\t\tublasx::num_rows(A) == ublasx::num_columns(A),\n\t\t\tbad_size()\n\t\t);\n\n\tchar job;\n\n\tif (scale && !permute)\n\t{\n\t\t// Only scale\n\t\tjob = 'S';\n\t}\n\telse if (!scale && permute)\n\t{\n\t\t// Only permute\n\t\tjob = 'P';\n\t}\n\telse if (!scale && !permute)\n\t{\n\t\t// Do nothing but simply set ILO = 1, IHI = N, SCALE(I) = 1.0 for i = 1,...,N;\n\t\tjob = 'N';\n\t}\n\telse\n\t{\n\t\t// Both scale and permute\n\t\tjob = 'B';\n\t}\n\n\tsize_type n = num_rows(A);\n\t::fortran_int_t ilo;\n\t::fortran_int_t ihi;\n\twork_vector_type tmp_scale_vec(n);\n\n\t::boost::numeric::bindings::lapack::gebal(job,\n\t\t\t\t\t\t\t\t\t\t\t  A,\n\t\t\t\t\t\t\t\t\t\t\t  ilo,\n\t\t\t\t\t\t\t\t\t\t\t  ihi,\n\t\t\t\t\t\t\t\t\t\t\t  tmp_scale_vec);\n\n\tif (want_scaling_vec)\n\t{\n\t\tif (size(scaling_vec) != n)\n\t\t{\n\t\t\tscaling_vec.resize(n, false);\n\t\t}\n\n\t\tfor (size_type i = 0; i < (static_cast<size_type>(ilo)-1); ++i)\n\t\t{\n\t\t\tscaling_vec(i) = real_type(1);\n\t\t}\n\t\tfor (size_type i = ilo-1; i < static_cast<size_type>(ihi); ++i)\n\t\t{\n\t\t\tscaling_vec(i) = tmp_scale_vec(i);\n\t\t}\n\t\tfor (size_type i = ihi; i < n; ++i)\n\t\t{\n\t\t\tscaling_vec(i) = real_type(1);\n\t\t}\n\t}\n\tif (want_permuting_vec)\n\t{\n\t\tif (size(permuting_vec) != n)\n\t\t{\n\t\t\tpermuting_vec.resize(n, false);\n\t\t}\n\n\t\tfor (size_type i = 0; i < n; ++i)\n\t\t{\n\t\t\tpermuting_vec(i) = i;\n\t\t}\n\t\tfor (size_type i = n-1; i >= static_cast<size_type>(ihi); --i)\n\t\t{\n\t\t\tsize_type j(tmp_scale_vec(i)-1);\n\t\t\t::std::swap(permuting_vec(i), permuting_vec(j));\n\t\t}\n\t\tfor (size_type i = 0; i < (static_cast<size_type>(ilo)-1); ++i)\n\t\t{\n\t\t\tsize_type j(tmp_scale_vec(i)-1);\n\t\t\t::std::swap(permuting_vec(i), permuting_vec(j));\n\t\t}\n\t}\n\tif (want_balancing_mat)\n\t{\n\t\tbalancing_mat = identity_matrix<real_type>(n,n);\n\n\t\t::boost::numeric::bindings::tag::right side;\n\n\t\t::boost::numeric::bindings::lapack::gebak(job,\n\t\t\t\t\t\t\t\t\t\t\t\t  side,\n\t\t\t\t\t\t\t\t\t\t\t\t  ilo,\n\t\t\t\t\t\t\t\t\t\t\t\t  ihi,\n\t\t\t\t\t\t\t\t\t\t\t\t  tmp_scale_vec,\n\t\t\t\t\t\t\t\t\t\t\t\t  balancing_mat);\n\t}\n}\n\n\n/**\n * \\brief Diagonal matrix balancing to improve eigenvalue accuracy.\n *\n * \\tparam MatrixT The type of the matrix to be balanced.\n * \\tparam SVectorT The type of the scaling vector.\n * \\tparam PVectorT The type of the permuting vector.\n * \\tparam BVectorT The type of the balancing matrix.\n *\n * \\param A The matrix to be balanced.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\param want_scaling_vec Tells if the caller has requested to compute the\n *  scaling vector.\n * \\param scaling_vec The computed scaling vector.\n * \\param want_permuting_vec Tells if the caller has requested to compute the\n *  permutation vector.\n * \\param permuting_vec The computed permuting vector.\n * \\param want_balancing_mat Tells if the caller has requested to compute the\n *  balancing matrix.\n * \\param balancing_mat The computed balancing matrix.\n * \\return none, but \\a A, \\a scaling_vec, \\a permuting_vec, and\n *  \\a balancing_mat are changed (possibly, if requested).\n *\n * Version for matrices with row-major layout.\n */\ntemplate <\n\ttypename MatrixT,\n\ttypename SVectorT,\n\ttypename PVectorT,\n\ttypename BMatrixT\n>\nvoid balance_impl(MatrixT& A,\n\t\t\t\t  bool scale,\n\t\t\t\t  bool permute,\n\t\t\t\t  bool want_scaling_vec,\n\t\t\t\t  SVectorT& scaling_vec,\n\t\t\t\t  bool want_permuting_vec,\n\t\t\t\t  PVectorT& permuting_vec,\n\t\t\t\t  bool want_balancing_mat,\n\t\t\t\t  BMatrixT& balancing_mat,\n\t\t\t\t  row_major_tag)\n{\n    // Note: LAPACK works with column-major matrices\n\n    typedef typename matrix_traits<MatrixT>::value_type value_type;\n\n    typedef matrix<value_type, column_major> colmaj_matrix_type;\n\n\tcolmaj_matrix_type tmp_A(A);\n\tcolmaj_matrix_type tmp_balancing_mat;\n\n\tbalance_impl(tmp_A,\n\t\t\t\t scale,\n\t\t\t\t permute,\n\t\t\t\t want_scaling_vec,\n\t\t\t\t scaling_vec,\n\t\t\t\t want_permuting_vec,\n\t\t\t\t permuting_vec,\n\t\t\t\t want_balancing_mat,\n\t\t\t\t tmp_balancing_mat,\n\t\t\t\t column_major_tag());\n\n\tA = tmp_A;\n\n\tif (want_balancing_mat)\n\t{\n\t\tbalancing_mat = tmp_balancing_mat;\n\t}\n}\n\n\n/**\n * \\brief Diagonal matrix balancing to improve generalized eigenvalue accuracy.\n *\n * \\tparam Matrix1T The type of the first matrix in the input pencil to be\n *  balanced.\n * \\tparam Matrix2T The type of the second matrix in the input pencil to be\n *  balanced.\n * \\tparam SLVectorT The type of the scaling vector applied to the left side\n *  of the input pencil.\n * \\tparam SRVectorT The type of the scaling vector applied to the right side\n *  of the input pencil.\n * \\tparam PLVectorT The type of the permuting vector applied to the left side\n *  pf the input pencil.\n * \\tparam PRVectorT The type of the permuting vector applied to the right side\n *  pf the input pencil.\n * \\tparam BVectorT The type of the balancing matrix.\n *\n * \\param A The first matrix in the input pencil (A,B) to be balanced.\n * \\param B The second matrix in the input pencil (A,B) to be balanced.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\param want_scaling_vec Tells if the caller has requested to compute the\n *  scaling vectors.\n * \\param left_scaling_vec The computed scaling vector applied to the left side\n *  of the input pencil (A,B).\n * \\param right_scaling_vec The computed scaling vector applied to the right\n *  side of the input pencil (A,B).\n * \\param want_permuting_vec Tells if the caller has requested to compute the\n *  permutation vectors.\n * \\param left_permuting_vec The computed permuting vector applied to the left\n *  size of the input pencil (A,B).\n * \\param right_permuting_vec The computed permuting vector applied to the right\n *  size of the input pencil (A,B).\n * \\param want_balancing_mat Tells if the caller has requested to compute the\n *  balancing matrix.\n * \\param balancing_mat The computed balancing matrix.\n * \\return none, but \\a A, \\a B, \\a left_scaling_vec, \\a right_scaling_vec,\n *  \\a left_permuting_vec, \\a right_permuting_vec, and \\a balancing_mat are\n *  changed (possibly, if requested).\n *\n * Version for matrices with column-major layout.\n */\ntemplate <\n\ttypename Matrix1T,\n\ttypename Matrix2T,\n\ttypename SLVectorT,\n\ttypename PLVectorT,\n\ttypename SRVectorT,\n\ttypename PRVectorT,\n\ttypename BMatrixT\n>\nvoid balance_impl(Matrix1T& A,\n\t\t\t\t  Matrix2T& B,\n\t\t\t\t  bool scale,\n\t\t\t\t  bool permute,\n\t\t\t\t  bool want_scaling_vec,\n\t\t\t\t  SLVectorT& left_scaling_vec,\n\t\t\t\t  SRVectorT& right_scaling_vec,\n\t\t\t\t  bool want_permuting_vec,\n\t\t\t\t  PLVectorT& left_permuting_vec,\n\t\t\t\t  PRVectorT& right_permuting_vec,\n\t\t\t\t  bool want_balancing_mat,\n\t\t\t\t  BMatrixT& balancing_mat,\n\t\t\t\t  column_major_tag)\n{\n\ttypedef typename promote_traits<\n\t\t\t\t\t\ttypename matrix_traits<Matrix1T>::value_type,\n\t\t\t\t\t\ttypename matrix_traits<Matrix2T>::value_type\n\t\t\t\t>::promote_type value_type;\n\ttypedef typename promote_traits<\n\t\t\t\t\t\ttypename matrix_traits<Matrix1T>::size_type,\n\t\t\t\t\t\ttypename matrix_traits<Matrix2T>::size_type\n\t\t\t\t>::promote_type size_type;\n\ttypedef typename type_traits<value_type>::real_type real_type;\n\ttypedef vector<real_type> work_vector_type;\n\n    // pre: same orientation category\n\tBOOST_MPL_ASSERT(\n\t\t(\n\t\t\t::boost::is_same<\n\t\t\t\t\ttypename matrix_traits<Matrix1T>::orientation_category,\n\t\t\t\t\ttypename matrix_traits<Matrix2T>::orientation_category\n\t\t\t>\n\t\t)\n\t);\n\t// pre: A must be square\n\tBOOST_UBLAS_CHECK(\n\t\t\tublasx::num_rows(A) == ublasx::num_columns(A),\n\t\t\tbad_size()\n\t\t);\n\t// pre: B must be square\n\tBOOST_UBLAS_CHECK(\n\t\t\tublasx::num_rows(B) == ublasx::num_columns(B),\n\t\t\tbad_size()\n\t\t);\n\t// pre: A and B must be of the same order\n\tBOOST_UBLAS_CHECK(\n\t\t\tublasx::num_rows(A) == ublasx::num_rows(B),\n\t\t\tbad_size()\n\t\t);\n\n\tchar job;\n\n\tif (scale && !permute)\n\t{\n\t\t// Only scale\n\t\tjob = 'S';\n\t}\n\telse if (!scale && permute)\n\t{\n\t\t// Only permute\n\t\tjob = 'P';\n\t}\n\telse if (!scale && !permute)\n\t{\n\t\t// Do nothing but simply set ILO = 1, IHI = N, LSCALE(I) = 1.0 and RSCALE(I) for i = 1,...,N;\n\t\tjob = 'N';\n\t}\n\telse\n\t{\n\t\t// Both scale and permute\n\t\tjob = 'B';\n\t}\n\n\tsize_type n = num_rows(A);\n\t::fortran_int_t ilo;\n\t::fortran_int_t ihi;\n\twork_vector_type tmp_lscale_vec(n);\n\twork_vector_type tmp_rscale_vec(n);\n\n\t::boost::numeric::bindings::lapack::ggbal(job,\n\t\t\t\t\t\t\t\t\t\t\t  A,\n\t\t\t\t\t\t\t\t\t\t\t  ilo,\n\t\t\t\t\t\t\t\t\t\t\t  ihi,\n\t\t\t\t\t\t\t\t\t\t\t  tmp_lscale_vec,\n\t\t\t\t\t\t\t\t\t\t\t  tmp_rscale_vec);\n\n\tif (want_scaling_vec)\n\t{\n\t\tif (size(left_scaling_vec) != n)\n\t\t{\n\t\t\tleft_scaling_vec.resize(n, false);\n\t\t}\n\t\tif (size(right_scaling_vec) != n)\n\t\t{\n\t\t\tright_scaling_vec.resize(n, false);\n\t\t}\n\n\t\tfor (size_type i = 0; i < (static_cast<size_type>(ilo)-1); ++i)\n\t\t{\n\t\t\tleft_scaling_vec(i) = right_scaling_vec(i)\n\t\t\t\t\t\t\t\t= real_type(1);\n\t\t}\n\t\tfor (size_type i = ilo-1; i < static_cast<size_type>(ihi); ++i)\n\t\t{\n\t\t\tleft_scaling_vec(i) = tmp_lscale_vec(i);\n\t\t\tright_scaling_vec(i) = tmp_rscale_vec(i);\n\t\t}\n\t\tfor (size_type i = ihi; i < n; ++i)\n\t\t{\n\t\t\tleft_scaling_vec(i) = right_scaling_vec(i)\n\t\t\t\t\t\t\t\t= real_type(1);\n\t\t}\n\t}\n\tif (want_permuting_vec)\n\t{\n\t\tif (size(left_permuting_vec) != n)\n\t\t{\n\t\t\tleft_permuting_vec.resize(n, false);\n\t\t}\n\t\tif (size(right_permuting_vec) != n)\n\t\t{\n\t\t\tright_permuting_vec.resize(n, false);\n\t\t}\n\n\t\tfor (size_type i = 0; i < n; ++i)\n\t\t{\n\t\t\tleft_permuting_vec(i) = right_permuting_vec(i)\n\t\t\t\t\t\t\t\t  = i;\n\t\t}\n\t\tfor (size_type i = n-1; i >= static_cast<size_type>(ihi); --i)\n\t\t{\n\t\t\tsize_type j;\n\t\t\tj = tmp_lscale_vec(i)-1;\n\t\t\t::std::swap(left_permuting_vec(i), left_permuting_vec(j));\n\t\t\tj = tmp_rscale_vec(i)-1;\n\t\t\t::std::swap(right_permuting_vec(i), right_permuting_vec(j));\n\t\t}\n\t\tfor (size_type i = 0; i < (static_cast<size_type>(ilo)-1); ++i)\n\t\t{\n\t\t\tsize_type j;\n\t\t\tj = tmp_lscale_vec(i)-1;\n\t\t\t::std::swap(left_permuting_vec(i), left_permuting_vec(j));\n\t\t\tj = tmp_rscale_vec(i)-1;\n\t\t\t::std::swap(right_permuting_vec(i), right_permuting_vec(j));\n\t\t}\n\t}\n\tif (want_balancing_mat)\n\t{\n\t\tbalancing_mat = identity_matrix<real_type>(n,n);\n\n\t\t::boost::numeric::bindings::tag::right side;\n\n\t\t::boost::numeric::bindings::lapack::ggbak(job,\n\t\t\t\t\t\t\t\t\t\t\t\t  side,\n\t\t\t\t\t\t\t\t\t\t\t\t  ilo,\n\t\t\t\t\t\t\t\t\t\t\t\t  ihi,\n\t\t\t\t\t\t\t\t\t\t\t\t  tmp_lscale_vec,\n\t\t\t\t\t\t\t\t\t\t\t\t  tmp_rscale_vec,\n\t\t\t\t\t\t\t\t\t\t\t\t  balancing_mat);\n\t}\n}\n\n\n/**\n * \\brief Diagonal matrix balancing to improve generalized eigenvalue accuracy.\n *\n * \\tparam Matrix1T The type of the first matrix in the input pencil to be\n *  balanced.\n * \\tparam Matrix2T The type of the second matrix in the input pencil to be\n *  balanced.\n * \\tparam SLVectorT The type of the scaling vector applied to the left side\n *  of the input pencil.\n * \\tparam SRVectorT The type of the scaling vector applied to the right side\n *  of the input pencil.\n * \\tparam PLVectorT The type of the permuting vector applied to the left side\n *  pf the input pencil.\n * \\tparam PRVectorT The type of the permuting vector applied to the right side\n *  pf the input pencil.\n * \\tparam BVectorT The type of the balancing matrix.\n *\n * \\param A The first matrix in the input pencil (A,B) to be balanced.\n * \\param B The second matrix in the input pencil (A,B) to be balanced.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\param want_scaling_vec Tells if the caller has requested to compute the\n *  scaling vectors.\n * \\param left_scaling_vec The computed scaling vector applied to the left side\n *  of the input pencil (A,B).\n * \\param right_scaling_vec The computed scaling vector applied to the right\n *  side of the input pencil (A,B).\n * \\param want_permuting_vec Tells if the caller has requested to compute the\n *  permutation vectors.\n * \\param left_permuting_vec The computed permuting vector applied to the left\n *  size of the input pencil (A,B).\n * \\param right_permuting_vec The computed permuting vector applied to the right\n *  size of the input pencil (A,B).\n * \\param want_balancing_mat Tells if the caller has requested to compute the\n *  balancing matrix.\n * \\param balancing_mat The computed balancing matrix.\n * \\return none, but \\a A, \\a B, \\a left_scaling_vec, \\a right_scaling_vec,\n *  \\a left_permuting_vec, \\a right_permuting_vec, and \\a balancing_mat are\n *  changed (possibly, if requested).\n *\n * Version for matrices with row-major layout.\n */\ntemplate <\n\ttypename Matrix1T,\n\ttypename Matrix2T,\n\ttypename SLVectorT,\n\ttypename PLVectorT,\n\ttypename SRVectorT,\n\ttypename PRVectorT,\n\ttypename BMatrixT\n>\nvoid balance_impl(Matrix1T& A,\n\t\t\t\t  Matrix2T& B,\n\t\t\t\t  bool scale,\n\t\t\t\t  bool permute,\n\t\t\t\t  bool want_scaling_vec,\n\t\t\t\t  SLVectorT& left_scaling_vec,\n\t\t\t\t  SRVectorT& right_scaling_vec,\n\t\t\t\t  bool want_permuting_vec,\n\t\t\t\t  PLVectorT& left_permuting_vec,\n\t\t\t\t  PRVectorT& right_permuting_vec,\n\t\t\t\t  bool want_balancing_mat,\n\t\t\t\t  BMatrixT& balancing_mat,\n\t\t\t\t  row_major_tag)\n{\n    // Note: LAPACK works with column-major matrices\n\n\ttypedef typename promote_traits<\n\t\t\t\t\t\ttypename matrix_traits<Matrix1T>::value_type,\n\t\t\t\t\t\ttypename matrix_traits<Matrix2T>::value_type\n\t\t\t\t>::promote_type value_type;\n\n    typedef matrix<value_type, column_major> colmaj_matrix_type;\n\n\tcolmaj_matrix_type tmp_A(A);\n\tcolmaj_matrix_type tmp_B(B);\n\tcolmaj_matrix_type tmp_balancing_mat;\n\n\tbalance_impl(tmp_A,\n\t\t\t\t tmp_B,\n\t\t\t\t scale,\n\t\t\t\t permute,\n\t\t\t\t want_scaling_vec,\n\t\t\t\t left_scaling_vec,\n\t\t\t\t right_scaling_vec,\n\t\t\t\t want_permuting_vec,\n\t\t\t\t left_permuting_vec,\n\t\t\t\t right_permuting_vec,\n\t\t\t\t want_balancing_mat,\n\t\t\t\t tmp_balancing_mat,\n\t\t\t\t column_major_tag());\n\n\tA = tmp_A;\n\tB = tmp_B;\n\n\tif (want_balancing_mat)\n\t{\n\t\tbalancing_mat = tmp_balancing_mat;\n\t}\n}\n\n}} // Namespace detail::<unnamed>\n\n\n//@{ Balance of Single Matrix\n\n\n/// Traits type class for the \\c balance operation (single matrix version).\ntemplate <typename MatrixT>\nstruct balance_traits\n{\n\t/// The type of the balanced matrix.\n\ttypedef matrix<typename matrix_traits<MatrixT>::value_type,\n\t\t\t\t   typename layout_type<MatrixT>::type> balanced_matrix_type;\n\t/// The type of the balancing matrix.\n\ttypedef matrix<typename matrix_traits<MatrixT>::value_type,\n\t\t\t\t   typename layout_type<MatrixT>::type> balancing_matrix_type;\n\t/// The type of the scaling vector.\n\ttypedef vector<typename type_traits<\n\t\t\t\t\t\ttypename matrix_traits<MatrixT>::value_type\n\t\t\t\t\t>::real_type> scaling_vector_type;\n\t/// The type of the permuting vector.\n\ttypedef vector<typename matrix_traits<MatrixT>::size_type> permuting_vector_type;\n};\n\n\n/**\n * \\brief Diagonal matrix balancing to improve eigenvalue accuracy.\n *\n * \\tparam MatrixT The type of the matrix to be balanced.\n *\n * \\param A The matrix to be balanced.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\return none, but matrix \\a A is overwritten by its balanced counterpart.\n */\ntemplate <typename MatrixT>\nBOOST_UBLAS_INLINE\nvoid balance_inplace(MatrixT& A, bool scale = true, bool permute = true)\n{\n\ttypedef typename matrix_traits<MatrixT>::orientation_category orientation_category;\n//\ttypedef typename matrix_traits<MatrixT>::size_type size_type;\n//\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n//\ttypedef typename type_traits<value_type>::real_type real_type;\n\n//\tvector<real_type> dummy_scaling_vec;\n//\tvector<size_type> dummy_permuting_vec;\n//\tmatrix<value_type,column_major> dummy_balancing_mat;\n\ttypename balance_traits<MatrixT>::scaling_vector_type dummy_scaling_vec;\n\ttypename balance_traits<MatrixT>::permuting_vector_type dummy_permuting_vec;\n\ttypename balance_traits<MatrixT>::balancing_matrix_type dummy_balancing_mat;\n\n\tdetail::balance_impl(A,\n\t\t\t\t\t\t scale,\n\t\t\t\t\t\t permute,\n\t\t\t\t\t\t false,\n\t\t\t\t\t\t dummy_scaling_vec,\n\t\t\t\t\t\t false,\n\t\t\t\t\t\t dummy_permuting_vec,\n\t\t\t\t\t\t false,\n\t\t\t\t\t\t dummy_balancing_mat,\n\t\t\t\t\t\t orientation_category());\n}\n\n\n/**\n * \\brief Diagonal matrix balancing to improve eigenvalue accuracy.\n *\n * \\tparam MatrixT The type of the matrix to be balanced.\n * \\tparam MatrixExprT The type of the balancing matrix.\n *\n * \\param A The matrix to be balanced.\n * \\param balancing_mat The computed balancing matrix.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\return none, but matrices \\a A and \\a balancing_mat are overwritten by the\n *  balanced counterpart of \\a A and by the computed balanced matrix,\n *  respectively.\n */\ntemplate <typename MatrixT, typename MatrixExprT>\nBOOST_UBLAS_INLINE\nvoid balance_inplace(MatrixT& A,\n\t\t\t\t\t matrix_container<MatrixExprT>& balancing_mat,\n\t\t\t\t\t bool scale = true,\n\t\t\t\t\t bool permute = true)\n{\n\ttypedef typename matrix_traits<MatrixT>::orientation_category orientation_category;\n//\ttypedef typename matrix_traits<MatrixT>::size_type size_type;\n//\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n//\ttypedef typename type_traits<value_type>::real_type real_type;\n\n//\tvector<real_type> dummy_scaling_vec;\n//\tvector<size_type> dummy_permuting_vec;\n\ttypename balance_traits<MatrixT>::scaling_vector_type dummy_scaling_vec;\n\ttypename balance_traits<MatrixT>::permuting_vector_type dummy_permuting_vec;\n\n\tdetail::balance_impl(A,\n\t\t\t\t\t\t scale,\n\t\t\t\t\t\t permute,\n\t\t\t\t\t\t false,\n\t\t\t\t\t\t dummy_scaling_vec,\n\t\t\t\t\t\t false,\n\t\t\t\t\t\t dummy_permuting_vec,\n\t\t\t\t\t\t true,\n\t\t\t\t\t\t balancing_mat(),\n\t\t\t\t\t\t orientation_category());\n}\n\n\n/**\n * \\brief Diagonal matrix balancing to improve eigenvalue accuracy.\n *\n * \\tparam MatrixT The type of the matrix to be balanced.\n * \\tparam VectorExprT The type of the scaling vector.\n *\n * \\param A The matrix to be balanced.\n * \\param scaling_vec The computed scaling vector.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\return none, but matrix \\a A and vector \\a scaling_vec are overwritten by\n *  the balanced counterpart of \\a A and by the computed scaling vector,\n *  respectively.\n */\ntemplate <typename MatrixT, typename VectorExprT>\nBOOST_UBLAS_INLINE\nvoid balance_inplace(MatrixT& A,\n\t\t\t\t\t vector_container<VectorExprT>& scaling_vec,\n\t\t\t\t\t bool scale = true,\n\t\t\t\t\t bool permute = true)\n{\n\ttypedef typename matrix_traits<MatrixT>::orientation_category orientation_category;\n//\ttypedef typename matrix_traits<MatrixT>::size_type size_type;\n//\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n\n//\tvector<size_type> dummy_permuting_vec;\n//\tmatrix<value_type,column_major> dummy_balancing_mat;\n\ttypename balance_traits<MatrixT>::permuting_vector_type dummy_permuting_vec;\n\ttypename balance_traits<MatrixT>::balancing_matrix_type dummy_balancing_mat;\n\n\tdetail::balance_impl(A,\n\t\t\t\t\t\t scale,\n\t\t\t\t\t\t permute,\n\t\t\t\t\t\t true,\n\t\t\t\t\t\t scaling_vec(),\n\t\t\t\t\t\t false,\n\t\t\t\t\t\t dummy_permuting_vec,\n\t\t\t\t\t\t false,\n\t\t\t\t\t\t dummy_balancing_mat,\n\t\t\t\t\t\t orientation_category());\n}\n\n\n/**\n * \\brief Diagonal matrix balancing to improve eigenvalue accuracy.\n *\n * \\tparam MatrixT The type of the matrix to be balanced.\n * \\tparam SVectorExprT The type of the scaling vector.\n * \\tparam PVectorExprT The type of the permuting vector.\n *\n * \\param A The matrix to be balanced.\n * \\param scaling_vec The computed scaling vector.\n * \\param permuting_vec The computed permuting vector.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\return none, but matrix \\a A and vectors \\a scaling_vec and \\a permuting_vec\n *  are overwritten by the balanced counterpart of \\a A, by the computed\n *  scaling vector, and by the computed permuting vector, respectively.\n */\ntemplate <typename MatrixT, typename SVectorExprT, typename PVectorExprT>\nBOOST_UBLAS_INLINE\nvoid balance_inplace(MatrixT& A,\n\t\t\t\t\t vector_container<SVectorExprT>& scaling_vec,\n\t\t\t\t\t vector_container<PVectorExprT>& permuting_vec,\n\t\t\t\t\t bool scale = true,\n\t\t\t\t\t bool permute = true)\n{\n\ttypedef typename matrix_traits<MatrixT>::orientation_category orientation_category;\n//\ttypedef typename matrix_traits<MatrixT>::value_type value_type;\n\n//\tmatrix<value_type,column_major> dummy_balancing_mat;\n\ttypename balance_traits<MatrixT>::balancing_matrix_type dummy_balancing_mat;\n\n\tdetail::balance_impl(A,\n\t\t\t\t\t\t scale,\n\t\t\t\t\t\t permute,\n\t\t\t\t\t\t true,\n\t\t\t\t\t\t scaling_vec(),\n\t\t\t\t\t\t true,\n\t\t\t\t\t\t permuting_vec(),\n\t\t\t\t\t\t false,\n\t\t\t\t\t\t dummy_balancing_mat,\n\t\t\t\t\t\t orientation_category());\n}\n\n\n/**\n * \\brief Diagonal matrix balancing to improve eigenvalue accuracy.\n *\n * \\tparam MatrixT The type of the matrix to be balanced.\n *\n * \\param A The matrix to be balanced.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\return The balanced matrix.\n */\ntemplate <typename MatrixExprT>\nBOOST_UBLAS_INLINE\ntypename balance_traits<MatrixExprT>::balanced_matrix_type balance(matrix_expression<MatrixExprT> const& A,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   bool scale = true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   bool permute = true)\n{\n\t//typedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\t//typedef typename layout_type<MatrixExprT>::type balanced_layout_type;\n\t//typedef matrix<value_type,balanced_layout_type> balanced_matrix_type;\n\ttypedef typename balance_traits<MatrixExprT>::balanced_matrix_type balanced_matrix_type;\n\n\tbalanced_matrix_type X(A);\n\n\tbalance_inplace(X, scale, permute);\n\n\treturn X;\n}\n\n\n/**\n * \\brief Diagonal matrix balancing to improve eigenvalue accuracy.\n *\n * \\tparam AMatrixExprT The type of the matrix to be balanced.\n * \\tparam BMatrixExprT The type of the balancing matrix.\n *\n * \\param A The matrix to be balanced.\n * \\param balancing_mat The balancing matrix.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\return The balanced matrix; furthermore, the matrix \\a balancing_mat is\n *  overwritten by the computed balancing matrix.\n */\ntemplate <typename AMatrixExprT, typename BMatrixExprT>\nBOOST_UBLAS_INLINE\ntypename balance_traits<AMatrixExprT>::balanced_matrix_type balance(matrix_expression<AMatrixExprT> const& A,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmatrix_container<BMatrixExprT>& balancing_mat,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbool scale = true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbool permute = true)\n{\n\t//typedef typename matrix_traits<AMatrixExprT>::value_type value_type;\n\t//typedef typename layout_type<AMatrixExprT>::type balanced_layout_type;\n\t//typedef matrix<value_type,balanced_layout_type> balanced_matrix_type;\n\ttypedef typename balance_traits<AMatrixExprT>::balanced_matrix_type balanced_matrix_type;\n\n\tbalanced_matrix_type X(A);\n\n\tbalance_inplace(X, balancing_mat, scale, permute);\n\n\treturn X;\n}\n\n\n/**\n * \\brief Diagonal matrix balancing to improve eigenvalue accuracy.\n *\n * \\tparam MatrixExprT The type of the matrix to be balanced.\n * \\tparam VectorExprT The type of the scaling vector.\n *\n * \\param A The matrix to be balanced.\n * \\param scaling_vec The scaling vector.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\return The balanced matrix; furthermore, the vector \\a scaling_vec is\n *  overwritten by the computed scaling vector.\n */\ntemplate <typename MatrixExprT, typename VectorExprT>\nBOOST_UBLAS_INLINE\ntypename balance_traits<MatrixExprT>::balanced_matrix_type balance(matrix_expression<MatrixExprT> const& A,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   vector_container<VectorExprT>& scaling_vec,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   bool scale = true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   bool permute = true)\n{\n\t//typedef typename matrix_traits<MatrixExprT>::value_type value_type;\n\t//typedef typename layout_type<MatrixExprT>::type balanced_layout_type;\n\t//typedef matrix<value_type,balanced_layout_type> balanced_matrix_type;\n\ttypedef typename balance_traits<MatrixExprT>::balanced_matrix_type balanced_matrix_type;\n\n\tbalanced_matrix_type X(A);\n\n\tbalance_inplace(X, scaling_vec, scale, permute);\n\n\treturn X;\n}\n\n\n/**\n * \\brief Diagonal matrix balancing to improve eigenvalue accuracy.\n *\n * \\tparam MatrixExprT The type of the matrix to be balanced.\n * \\tparam SVectorExprT The type of the scaling vector.\n * \\tparam PVectorExprT The type of the permuting vector.\n *\n * \\param A The matrix to be balanced.\n * \\param scaling_vec The scaling vector.\n * \\param permuting_vec The permuting vector.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\return The balanced matrix; furthermore, the vector \\a scaling_vec is\n *  overwritten by the computed scaling vector.\n */\ntemplate <typename MatrixExprT, typename SVectorExprT, typename PVectorExprT>\nBOOST_UBLAS_INLINE\ntypename balance_traits<MatrixExprT>::balanced_matrix_type balance(matrix_expression<MatrixExprT> const& A,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   vector_container<SVectorExprT>& scaling_vec,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   vector_container<PVectorExprT>& permuting_vec,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   bool scale = true,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   bool permute = true)\n{\n\ttypedef typename balance_traits<MatrixExprT>::balanced_matrix_type balanced_matrix_type;\n\n\tbalanced_matrix_type X(A);\n\n\tbalance_inplace(X, scaling_vec, permuting_vec, scale, permute);\n\n\treturn X;\n}\n\n\n//@} Balance of Single Matrix\n\n\n//@{ Balance of Matrix Pair\n\n\n/// Traits type class for the \\c balance operation (matrix pencil version).\ntemplate <typename Matrix1T, typename Matrix2T>\nstruct pair_balance_traits\n{\n\t/// The type of the balanced matrix.\n\ttypedef matrix<typename promote_traits<\n\t\t\t\t\t\t\ttypename matrix_traits<Matrix1T>::value_type,\n\t\t\t\t\t\t\ttypename matrix_traits<Matrix2T>::value_type\n\t\t\t\t\t\t>::promote_type,\n\t\t\t\t   typename layout_type<Matrix1T>::type\n\t\t\t\t> balanced_matrix_type;\n\t/// The type of the balancing matrix.\n\ttypedef matrix<typename promote_traits<\n\t\t\t\t\t\t\ttypename matrix_traits<Matrix1T>::value_type,\n\t\t\t\t\t\t\ttypename matrix_traits<Matrix2T>::value_type\n\t\t\t\t\t\t>::promote_type,\n\t\t\t\t   typename layout_type<Matrix1T>::type\n\t\t\t\t> balancing_matrix_type;\n\t/// The type of the scaling vector.\n\ttypedef vector<typename type_traits<\n\t\t\t\t\t\ttypename promote_traits<\n\t\t\t\t\t\t\ttypename matrix_traits<Matrix1T>::value_type,\n\t\t\t\t\t\t\ttypename matrix_traits<Matrix2T>::value_type\n\t\t\t\t\t\t>::promote_type\n\t\t\t\t\t>::real_type> scaling_vector_type;\n\t/// The type of the permuting vector.\n\ttypedef vector<typename promote_traits<\n\t\t\t\t\t\t\ttypename matrix_traits<Matrix1T>::size_type,\n\t\t\t\t\t\t\ttypename matrix_traits<Matrix2T>::size_type\n\t\t\t\t\t\t>::promote_type\n\t\t\t\t> permuting_vector_type;\n};\n\n\n/**\n * \\brief Diagonal matrix balancing to improve eigenvalue accuracy.\n *\n * \\tparam MatrixT The type of the matrix to be balanced.\n *\n * \\param A The matrix to be balanced.\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\return none, but matrix \\a A is overwritten by its balanced counterpart.\n */\ntemplate <typename MatrixExpr1T, typename MatrixExpr2T>\nBOOST_UBLAS_INLINE\nvoid balance_inplace(matrix_container<MatrixExpr1T>& A, matrix_container<MatrixExpr2T>& B, bool scale = true, bool permute = true)\n{\n\ttypedef typename matrix_traits<MatrixExpr1T>::orientation_category orientation_category;\n\ttypedef typename pair_balance_traits<MatrixExpr1T,MatrixExpr2T>::scaling_vector_type scaling_vector_type;\n\ttypedef typename pair_balance_traits<MatrixExpr1T,MatrixExpr2T>::permuting_vector_type permuting_vector_type;\n\ttypedef typename pair_balance_traits<MatrixExpr1T,MatrixExpr2T>::balancing_matrix_type balancing_matrix_type;\n\n\tscaling_vector_type dummy_left_scaling_vec;\n\tscaling_vector_type dummy_right_scaling_vec;\n\tpermuting_vector_type dummy_left_permuting_vec;\n\tpermuting_vector_type dummy_right_permuting_vec;\n\tbalancing_matrix_type dummy_balancing_mat;\n\n\tdetail::balance_impl(A,\n\t\t\t\t\t\t B,\n\t\t\t\t\t\t scale,\n\t\t\t\t\t\t permute,\n\t\t\t\t\t\t false,\n\t\t\t\t\t\t dummy_left_scaling_vec,\n\t\t\t\t\t\t dummy_right_scaling_vec,\n\t\t\t\t\t\t false,\n\t\t\t\t\t\t dummy_left_permuting_vec,\n\t\t\t\t\t\t dummy_right_permuting_vec,\n\t\t\t\t\t\t false,\n\t\t\t\t\t\t dummy_balancing_mat,\n\t\t\t\t\t\t orientation_category());\n}\n\n\n/**\n * \\brief Diagonal matrix balancing to improve generalized eigenvalue accuracy.\n *\n * \\tparam MatrixExpr1T The type of the first matrix of the input pencil to be\n *  balanced.\n * \\tparam MatrixExpr2T The type of the second matrix of the input pencil to be\n *  balanced.\n * \\tparam SLVectorExprT The type of the scaling vector applied to the left side\n *  of the input pencil.\n * \\tparam SRVectorExprT The type of the scaling vector applied to the right\n *  side of the input pencil.\n * \\tparam PLVectorExprT The type of the permuting vector applied to the left\n *  size of the input pencil.\n * \\tparam PRVectorExprT The type of the permuting vector applied to the right\n *  size of the input pencil.\n *\n * \\param A The first matrix of the input pencil (A,B) to be balanced.\n * \\param B The second matrix of the input pencil (A,B) to be balanced.\n * \\param left_scaling_vec The scaling vector applied to the left side of the\n *  input pencil (A,B).\n * \\param right_scaling_vec The scaling vector applied to the right side of the\n *  input pencil (A,B).\n * \\param left_permuting_vec The permuting vector applied to the left side of\n *  the input pencil (A,B)..\n * \\param right_permuting_vec The permuting vector applied to the right side of\n *  the input pencil (A,B)..\n * \\param scale Tells if scaling is to be applied.\n * \\param permute Tells if permutation is to be applied.\n * \\return The balanced matrix; furthermore, the vectors \\a left_scaling_vec,\n *  \\a right_scaling_vec, \\a left_permuting_vec, and \\a right_permuting_vec are\n *  overwritten by the computed scaling vectors and by the permuting scaling\n *  vectors, respectively.\n */\ntemplate <\n\ttypename MatrixExpr1T,\n\ttypename MatrixExpr2T,\n\ttypename BMatrixExpr1T,\n\ttypename BMatrixExpr2T,\n\ttypename SLVectorExprT,\n\ttypename SRVectorExprT,\n\ttypename PLVectorExprT,\n\ttypename PRVectorExprT\n>\nBOOST_UBLAS_INLINE\nvoid balance(matrix_expression<MatrixExpr1T> const& A,\n\t\t\t matrix_expression<MatrixExpr2T> const& B,\n\t\t\t matrix_container<BMatrixExpr1T>& BA,\n\t\t\t matrix_container<BMatrixExpr2T>& BB,\n\t\t\t vector_container<SLVectorExprT>& left_scaling_vec,\n\t\t\t vector_container<SRVectorExprT>& right_scaling_vec,\n\t\t\t vector_container<PLVectorExprT>& left_permuting_vec,\n\t\t\t vector_container<PRVectorExprT>& right_permuting_vec,\n\t\t\t bool scale = true,\n\t\t\t bool permute = true)\n{\n\ttypedef typename pair_balance_traits<MatrixExpr1T,MatrixExpr2T>::balanced_matrix_type balanced_matrix_type;\n\n\tbalanced_matrix_type X(A);\n\tbalanced_matrix_type Y(B);\n\n\tbalance_inplace(X,\n\t\t\t\t\tY,\n\t\t\t\t\tleft_scaling_vec,\n\t\t\t\t\tright_scaling_vec,\n\t\t\t\t\tleft_permuting_vec,\n\t\t\t\t\tright_permuting_vec,\n\t\t\t\t\tscale,\n\t\t\t\t\tpermute);\n\n\tBA() = X;\n\tBB() = Y;\n}\n\n\n//@} Balance of Matrix Pair\n\n}}} // Namespace boost:numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_BALANCE_HPP\n", "meta": {"hexsha": "a906438fea28bd24f6cf3c26d3c5956e80e77127", "size": 33627, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/balance.hpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/ublasx/operation/balance.hpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/ublasx/operation/balance.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5450281426, "max_line_length": 130, "alphanum_fraction": 0.7267077051, "num_tokens": 8471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.40558604713174917}}
{"text": "/// \\file   tatonnement.hpp\n///\n/// \\brief  Implements the tâtonnement process (hill climbing), implemented as a\n///         numerical optimisation (L-BFGS) with\n///         automatic differentiation using the Stan-math library.\n///\n/// \\remark This code uses the spelling `tatonnement`, as the accent on `â` can\n///         not be rendered in some filesystem character sets.\n///\n/// \\authors    Maarten P. Scholl\n/// \\date       2018-02-02\n/// \\copyright  Copyright 2017-2019 The Institute for New Economic Thinking,\n///             Oxford Martin School, University of Oxford\n///\n///             Licensed under the Apache License, Version 2.0 (the \"License\");\n///             you may not use this file except in compliance with the License.\n///             You may obtain a copy of the License at\n///\n///                 http://www.apache.org/licenses/LICENSE-2.0\n///\n///             Unless required by applicable law or agreed to in writing,\n///             software distributed under the License is distributed on an \"AS\n///             IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n///             express or implied. See the License for the specific language\n///             governing permissions and limitations under the License.\n///\n///             You may obtain instructions to fulfill the attribution\n///             requirements in CITATION.cff\n///\n#ifndef PROJECT_TATONNEMENT_HPP\n#define PROJECT_TATONNEMENT_HPP\n\n#include <iostream>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <adept.h>\n\n#include <esl/economics/markets/differentiable_demand_supply_function.hpp>\n#include <esl/economics/markets/quote.hpp>\n\n\nnamespace tatonnement {\n    ///\n    /// \\brief\n    ///\n    class excess_demand_model\n    {\n    public:\n        std::vector<std::shared_ptr<differentiable_demand_supply_function>>\n            excess_demand_functions_;\n\n        explicit excess_demand_model(\n            std::map<esl::identity<esl::law::property>, esl::economics::quote> initial_quotes);\n\n        virtual ~excess_demand_model();\n\n    public://protected:\n        std::map<esl::identity<esl::law::property>, esl::economics::quote> quotes_;\n\n        adept::Stack stack_;                    // Adept stack object\n        std::vector<adept::adouble> active_x_;  // Active state variables\n\n        adept::adouble calc_function_value(const adept::adouble *x);\n        std::vector<adept::adouble> multiroot_function_value(const adept::adouble *x);\n\n#ifndef ADEPT_NO_AUTOMATIC_DIFFERENTIATION\n        double         calc_function_value(const double *x);\n\n        std::vector<double> multiroot_function_value(const double *x);\n#endif\n\n        double calc_function_value_and_gradient(const double *x, double *dJ_dx) ;\n\n        std::vector<double> multiroot_function_value_and_gradient(const double *x, double *dJ_dx) ;\n\n        //friend double extern \"C\" my_function_value(const gsl_vector *variables, void *params);\n        //friend void extern \"C\" my_function_gradient(const gsl_vector *x, void *params, gsl_vector *gradJ);\n        //friend void extern \"C\" my_function_value_and_gradient(const gsl_vector *x, void *params, double *J, gsl_vector *gradJ);\n\n    public:\n        std::optional<std::map<esl::identity<esl::law::property>, double>> do_compute();\n    };  // model\n}  // namespace tatonnement\n\n#endif  // PROJECT_TATONNEMENT_HPP\n", "meta": {"hexsha": "45d8bac226b03ee18c7afba95d32e418098ccef3", "size": 3370, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "esl/economics/markets/walras/tatonnement.hpp", "max_stars_repo_name": "fagan2888/ESL", "max_stars_repo_head_hexsha": "24ffa903e8c5b9e725eed9861623d4b6a4a205a2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-17T18:18:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T18:18:08.000Z", "max_issues_repo_path": "esl/economics/markets/walras/tatonnement.hpp", "max_issues_repo_name": "fagan2888/ESL", "max_issues_repo_head_hexsha": "24ffa903e8c5b9e725eed9861623d4b6a4a205a2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esl/economics/markets/walras/tatonnement.hpp", "max_forks_repo_name": "fagan2888/ESL", "max_forks_repo_head_hexsha": "24ffa903e8c5b9e725eed9861623d4b6a4a205a2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8651685393, "max_line_length": 129, "alphanum_fraction": 0.6700296736, "num_tokens": 769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.40558603929341924}}
{"text": "// Std includes\n#include <cmath>\n#include <iostream>\n// Thirdparties includes\n#include <Eigen/Dense>\n// Lib includes\n#include \"Eigen/src/Core/Matrix.h\"\n#include \"s0s/runge_kutta_fehlberg.h\"\n#include \"sl0/spheroid.h\"\n// Simple includes\n#include \"flow.h\"\n\n// Types\nusing TypeScalar = double;\ntemplate<int Size>\nusing TypeVector = Eigen::Matrix<TypeScalar, Size, 1>;\n// Space\nconstexpr unsigned int DIM = 3;\nusing TypeSpaceVector = Eigen::Matrix<TypeScalar, DIM, 1>;\nusing TypeSpaceMatrix = Eigen::Matrix<TypeScalar, DIM, DIM>;\n// Ref and View\ntemplate<typename ...Args>\nusing TypeRef = Eigen::Ref<Args...>;\ntemplate<typename ...Args>\nusing TypeView = Eigen::Map<Args...>;\n// Solver\nusing TypeSolver = s0s::SolverRungeKuttaFehlberg<TypeVector<Eigen::Dynamic>, TypeView>;\n// Flow\nusing TypeFlow = Flow<TypeSpaceVector, TypeSpaceMatrix, TypeRef>;\n\nint main () { \n    TypeSpaceVector x0;\n    x0 << 0,\n          0,\n          0;\n    TypeSpaceVector p0;\n    p0 << 1,\n          0,\n          0;\n    double t0 = 0.0;\n    double dt = 1e-2;\n    double tEnd = 1.0;\n    // Create ellipsoid\n    sl0::Spheroid<TypeVector, DIM, TypeView, TypeFlow, TypeSolver> spheroid(std::make_shared<TypeFlow>(), 1.0);\n    // Set initial state\n    spheroid.sStep->x(spheroid.state.data()) = x0;\n    spheroid.sStep->axis(spheroid.state.data()) = p0;\n    spheroid.t = t0;\n    // Compute\n    std::cout << \"Spheroid in a simple shear flow : \\n\";\n    std::cout << \"\\n\";\n    std::cout << \"Orientation after each step : \\n\";\n    for(std::size_t i = 0; i < (tEnd - t0)/dt; i++) {\n        spheroid.update(dt);\n        std::cout << spheroid.sStep->axis(spheroid.state.data()) << \"\\n\";\n    }\n    // out\n    std::cout << \"Spheroid in a simple shear flow : \\n\";\n    std::cout << \"\\n\";\n    std::cout << \"Final orientation : \\n\";\n    std::cout << spheroid.sStep->axis(spheroid.state.data()) << \"\\n\";\n    std::cout << std::endl;\n}\n", "meta": {"hexsha": "c94960aa4bd4102e5fa9de019f70acbe76dfad0e", "size": 1882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/spheroid/main.cpp", "max_stars_repo_name": "C0PEP0D/sl0", "max_stars_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/spheroid/main.cpp", "max_issues_repo_name": "C0PEP0D/sl0", "max_issues_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/spheroid/main.cpp", "max_forks_repo_name": "C0PEP0D/sl0", "max_forks_repo_head_hexsha": "65d6a6c6d9c230676aaa4088fc411dc3971ec15a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.40625, "max_line_length": 111, "alphanum_fraction": 0.6323060574, "num_tokens": 572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837743174788, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4055697373362183}}
{"text": "// Copyright (c) 2017 Graphcore Ltd. All rights reserved.\n\n#ifndef poplibs_test_Lstm_hpp\n#define poplibs_test_Lstm_hpp\n\n#include <boost/multi_array.hpp>\n#include <popnn/LstmDef.hpp>\n\nnamespace poplibs_test {\nnamespace lstm {\n\n// Defines for state information in forward pass\n#define LSTM_NUM_FWD_STATES 7\n#define LSTM_FWD_STATE_ACTS_IDX 0\n#define LSTM_FWD_STATE_CELL_STATE_IDX 1\n\n// Defines for state information in backward pass\n#define LSTM_NUM_BWD_STATES BASIC_LSTM_CELL_NUM_UNITS\n\n/**\n * Compute the cell state and output of a basic non-fused LSTM cell (without\n * peephole connections). The cell state and outputs are concatented into a\n * single dimension.\n *\n * \\param input               Input to the LSTM cell of dimension\n *                            [sequenceSize][batchSize][inputSize]\n * \\param weightsInput        Weights in the LSTM cell which weigh the input\n *                            sequence. It is of dimension\n *                            [NUM_LSTM_UNITS][inputSize][outputSize]\n * \\param weightsOutput       Weights in the LSTM cell which weigh the output\n *                            sequence. It is of dimension\n *                            [NUM_LSTM_UNITS][outputSize][outputSize]\n * \\param biases              Biases in the LSTM cell of dimension\n *                            [NUM_LSTM_UNITS][outputSize]\n * \\param prevOutput          Previous output used in the first time step\n *                            [batchSize][outputSize]\n * \\param prevCellState       Initial cell state of shape\n *                            [batchSize][outputSize]\n * \\param state               The forward state for all the sequence steps of\n *                            dimension\n *                            [LSTM_NUM_FWD_STATES][sequenceSize][batchSize]\n *                            [outputSize]\n * \\param cellOrder           The order that the weights for each gate are\n *                            stored in the input.\n */\nvoid basicLstmCellForwardPass(\n    const boost::multi_array_ref<double, 3> input,\n    const boost::multi_array_ref<double, 2> biases,\n    const boost::multi_array_ref<double, 2> prevOutput,\n    const boost::multi_array_ref<double, 3> weightsInput,\n    const boost::multi_array_ref<double, 3> weightsOutput,\n    boost::multi_array_ref<double, 2> prevCellState,\n    boost::multi_array_ref<double, 4> state,\n    const std::vector<BasicLstmCellUnit> &cellOrder);\n\n/** Run backward pass given forward sequence\n *\n * \\param weightsInput    Input weights\n *                        shape: [NUM_LSTM_UNITS][input ch][output ch]\n * \\param weightsOutput   Output weights\n *                        shape: [NUM_LSTM_UNITS][output ch][output ch]\n * \\param gradsNextLayer  Gradients from next layer needed to compute gradients\n *                        for this layer. shape: [sequence][batch][output ch]\n * \\param prevCellState   Cell state of the initial step in the forward pass\n *                        shape: [batch][output ch]\n * \\param fwdState        Forward state returned by \\see\n *                        basicLstmCellForwardPass.\n *                        shape: [LSTM_NUM_FWD_STATES][sequence][batch]\n *                               [output ch]\n * \\param bwdState        Backward state returned by this function\n *                        shape:[LSTM_NUM_BWD_STATES][sequence]\n *                              [batch][output ch]\n * \\param gradsPrevLayer  Gradients for previous layer computed by this function\n *                        shape: [sequence][batch][input ch]\n * \\param cellOrder       The order that the weights for each gate are\n *                        stored in the input.\n */\nvoid basicLstmCellBackwardPass(\n    const boost::multi_array_ref<double, 3> weightsInput,\n    const boost::multi_array_ref<double, 3> weightsOutput,\n    const boost::multi_array_ref<double, 3> gradsNextLayer,\n    const boost::multi_array_ref<double, 2> prevCellState,\n    const boost::multi_array_ref<double, 4> fwdState,\n    boost::multi_array_ref<double, 4> bwdState,\n    boost::multi_array_ref<double, 3> gradsPrevLayer,\n    const std::vector<BasicLstmCellUnit> &cellOrder);\n\n/** Param update\n *\n * \\param prevLayerActs   Activations from previous layer\n *                        shape: [sequence][batch][input ch]\n * \\param fwdState        Forward state compute by \\see basicLstmCellForwardPass\n *                        shape: [LSTM_NUM_FWD_STATES][sequence][batch][output]\n * \\param outputActsInit  Initial activations for the forward pass\n *                        shape: [batch][output ch]\n * \\param bwdState        Backward channel state generated by backward pass\n *                        shape\" [LSTM_NUM_BWD_STATES][sequence][batch][output]\n * \\param weightsInputDeltas  Weight deltas computed by this function\n *                            shape: [NUM_LSTM_UNITS][input ch][output ch]\n * \\param weightsOutputDeltas Weight deltas computed by this function\n *                            shape: [NUM_LSTM_UNITS][output ch][output ch]\n *\n * \\param biasDeltas      Bias deltas computed by this function\n *                        shape: [NUM_LSTM_UNITS][output ch]\n * \\param cellOrder       The order that the weights for each gate are\n *                        stored in the input.\n */\nvoid basicLstmCellParamUpdate(\n    const boost::multi_array_ref<double, 3> prevLayerActs,\n    const boost::multi_array_ref<double, 4> fwdState,\n    const boost::multi_array_ref<double, 2> outputActsInit,\n    const boost::multi_array_ref<double, 4> bwdState,\n    boost::multi_array_ref<double, 3> weightsInputDeltas,\n    boost::multi_array_ref<double, 3> weightsOutputDeltas,\n    boost::multi_array_ref<double, 2> biasDeltas,\n    const std::vector<BasicLstmCellUnit> &cellOrder);\n} // namespace lstm\n} // namespace poplibs_test\n\n#endif // poplibs_test_Lstm_hpp\n", "meta": {"hexsha": "f26b9d3dd39af2095b926cfc4bd96612b596f194", "size": 5793, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/poplibs_test/Lstm.hpp", "max_stars_repo_name": "giantchen2012/poplibs", "max_stars_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-23T05:58:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-23T05:58:24.000Z", "max_issues_repo_path": "include/poplibs_test/Lstm.hpp", "max_issues_repo_name": "giantchen2012/poplibs", "max_issues_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/poplibs_test/Lstm.hpp", "max_forks_repo_name": "giantchen2012/poplibs", "max_forks_repo_head_hexsha": "2bc6b6f3d40863c928b935b5da88f40ddd77078e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.8760330579, "max_line_length": 80, "alphanum_fraction": 0.6416364578, "num_tokens": 1298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7634837635542924, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.40556973161871274}}
{"text": "#include \"tbb/parallel_for.h\"\n#include <iostream>\n#include <mex.h>\n#include <omp.h>\n#include <vector>\n\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Sparse>\n// #include <Eigen/StdVector>\n\n// #include <range/v3/all.hpp>\n// #include <range/v3/core.hpp>\n\n// #include \"storage_aliases.h\"\n\n// #define ngp int(*mxGetPr(prhs[0]))\n#define input prhs[0]\n#define output plhs[0]\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n\n  if (!(mxIsStruct(prhs[0]) && mxGetNumberOfFields(prhs[0]) > 0 && (nlhs > 0) &&\n        (nrhs > 0))) {\n    mexErrMsgIdAndTxt(\"MATLAB:mexcpp:typeargin\",\n                      \"First argument has to be double scalar.\");\n    return;\n  }\n\n  auto eps_p_bar = mxGetField(prhs[0], 0, \"eps_p_bar\");\n  auto sigma_bar = mxGetField(prhs[0], 0, \"sigma_bar\");\n  auto Hdo = mxGetField(prhs[0], 0, \"Hdo\");\n  auto inv_Hdo = mxGetField(prhs[0], 0, \"iHdo\");\n  auto delta_in = mxGetField(prhs[0], 0, \"delta\");\n  // auto DG_proj = mxGetField(prhs[0], 0, \"DG_proj\");\n  // auto D_operator = mxGetField(prhs[0], 0, \"D_operator\");\n  // auto ntp_in = mxGetField(prhs[0], 0, \"ntp\");\n  auto dt = mxGetField(prhs[0], 0, \"dt\");\n  auto I_g = mxGetField(prhs[0], 0, \"I_g\");\n  auto sgn = mxGetField(prhs[0], 0, \"sign\");\n  auto sign = int(*mxGetPr(sgn));\n  auto d_t = double(*mxGetPr(dt));\n\n  auto Hdo_Dimensions = mxGetDimensions(Hdo);\n  auto sigma_Dimensions = mxGetDimensions(sigma_bar);\n  size_t const ncomp = 6; // TODO 3D only\n  if (Hdo_Dimensions[0] != 6)\n    mexErrMsgIdAndTxt(\"MATLAB:mexcpp:nargin\", \"3D only, ncomp should equal 6.\");\n  size_t const ngp = Hdo_Dimensions[2];\n  size_t const ntp = Hdo_Dimensions[3];\n  size_t const nmodes = sigma_Dimensions[1];\n\n  using Matrix = Eigen::MatrixXd;\n  using Vector = Eigen::VectorXd;\n  using matrix6 = Eigen::Matrix<double, 6, 6>;\n\n  // Eigen::Map<Vector> Hdo_v(mxGetPr(Hdo), ntp * ngp * ncomp * ncomp);\n  // Eigen::Map<Vector> inv_Hdo_v(mxGetPr(inv_Hdo), ntp * ngp * ncomp * ncomp);\n  // Eigen::Map<Vector> delta_v(mxGetPr(delta_in), ntp * ngp * ncomp);\n  // Eigen::Map<Vector> sigma_v(mxGetPr(sigma_bar), ngp * ncomp * nmodes);\n  // Eigen::Map<Vector> eps_p_v(mxGetPr(eps_p_bar), ngp * ncomp * nmodes);\n\n  // clang-format off\n  // time_matrix6_storage H(ntp, gauss_matrix6_storage(ngp, matrix6_storage()));\n  // time_matrix6_storage iH(ntp, gauss_matrix6_storage(ngp, matrix6_storage()));\n  // time_vector_storage delta(ntp, gauss_vector_storage(ngp, vector_storage(ncomp)));\n  // gauss_matrix_storage sigma(ngp, matrix_storage(ncomp, nmodes));\n  // gauss_matrix_storage eps_p(ngp, matrix_storage(ncomp, nmodes));\n  // clang-format on\n\n  auto const tensor_shift = ncomp * ncomp;\n  auto const vector_shift = ncomp * nmodes;\n  auto const delta_shift = ncomp;\n\n  // using sparse_matrix = Eigen::SparseMatrix<double, Eigen::RowMajor>;\n  // sparse_matrix A(nmodes * ntp, nmodes * ntp);\n  // A.reserve(2 * nmodes * nmodes * ntp - (2 * nmodes - 1));\n  // A.coeffs() = 0.0;\n  Matrix A = Matrix::Zero(nmodes * ntp, nmodes * ntp);\n  Vector b = Vector::Zero(ntp * nmodes);\n\n  auto const nel = ntp - 1;\n\n  // TODO\n  // std::vector<std::int32_t> dofs(nel);\n  // std::generate(begin(dofs), end(dofs), [j = -nmodes] () mutable {\n  //      j += nmodes;\n  //      return j;\n  // });\n\n  std::vector<std::int32_t> dofs;\n  for (size_t j = 0; j < nel * nmodes; j += nmodes)\n    dofs.push_back(j);\n\n  std::vector<std::int32_t> fixed_dofs;\n  for (size_t j = 0; j < nmodes; j++)\n    fixed_dofs.push_back(j);\n\n    // how come I don't have race condition here? TODO\n    // clang-format off\n// #pragma omp parallel for collapse(2)\n#pragma omp declare reduction(+ : Eigen::MatrixXd : omp_out =  omp_out + omp_in)\n#pragma omp declare reduction(+ : Eigen::VectorXd : omp_out =  omp_out + omp_in)\n\n#pragma omp parallel for\n  for (size_t i = 0; i < ntp; i++) {\n    Matrix a11 = Matrix::Zero(nmodes, nmodes);\n    Matrix a10 = Matrix::Zero(nmodes, nmodes);\n    Matrix a00 = Matrix::Zero(nmodes, nmodes);\n    Vector d1 = Vector::Zero(nmodes);\n    Vector d0 = Vector::Zero(nmodes);\n\n\n// #pragma omp parallel for reduction(+ : a11,a10,a00,d1,d0)\n// #pragma omp parallel for\n    for (size_t j = 0; j < ngp; j++) {\n      int const int_idx = j * tensor_shift;\n      int const tensor_idx = (i * ngp + j) * tensor_shift;\n      int const delta_idx = (i * ngp + j) * delta_shift;\n      int const vector_idx = j * vector_shift;\n\n      //Hdo_v.segment(tensor_idx, tensor_shift);\n      // Eigen::Map<matrix6> Int_space(mxGetPr(I_g));\n      matrix6 Int_space = Eigen::Map<matrix6>(mxGetPr(I_g) + int_idx, ncomp, ncomp);\n      matrix6 H = Eigen::Map<matrix6>(mxGetPr(Hdo) + tensor_idx, ncomp, ncomp);\n      matrix6 iH = Eigen::Map<matrix6>(mxGetPr(inv_Hdo) + tensor_idx);\n      Vector delta = Eigen::Map<Vector>(mxGetPr(delta_in) + delta_idx, ncomp);\n      Matrix sigma = Eigen::Map<Matrix>(mxGetPr(sigma_bar) + vector_idx, ncomp,nmodes);\n      Matrix eps_p = Eigen::Map<Matrix>(mxGetPr(eps_p_bar) + vector_idx, ncomp,nmodes);\n\n      a11.noalias() += eps_p.transpose() * (iH * (Int_space * eps_p)); // TODO noalias\n      a10 += -1.0 * sign * eps_p.transpose() * Int_space * sigma;\n      a00 += sigma.transpose() * (H * (Int_space * sigma)); // TODO I_g is the same for all elements? shouldn't be\n      d1 += -1.0 * sign * eps_p.transpose() * (iH * (Int_space * delta));\n      d0 += sigma.transpose() * Int_space * delta;\n    }\n\n    Matrix t11 = a11 / (d_t * d_t); // TODO use cwiseQuotient\n    Matrix t12 = a10 / (d_t);       //   a01 = a10;\n    Matrix t22 = t11 + t12 + t12 + a00;\n    t12 = -t12 - t11;\n    Vector b0 = -d1 / (d_t);\n    Vector b1 = d1 / (d_t) + d0;\n\n    if (i>0) { //for (size_t i = 0; i < nel; i++) {\n      Matrix a_el(2 * nmodes, 2 * nmodes);\n      Vector b_el(2 * nmodes);\n\n      a_el << t11, t12,\n              t12, t22;\n\n      b_el << b0,\n              b1; // TODO use I_time\n\n//       for (size_t j = 0; j < 2 * nmodes; j++) {\n//         for (size_t k = 0; k < 2 * nmodes; k++) {\n// #pragma omp critical\n//           A.coeffRef(dofs[i-1]+j, dofs[i-1]+k) += a_el(j,k);\n//         }\n//       }\n//       for (size_t j = 0; j < 2 * nmodes; j++) {\n// #pragma omp atomic\n//           b.coeffRef(dofs[i-1]+j) += b_el(j);\n//       }\n\n#pragma omp critical\n{\n      A.block(dofs[i-1], dofs[i-1], 2 * nmodes, 2 * nmodes) += a_el; // TODO this assembly is not final\n      b.segment(dofs[i-1], 2 * nmodes) += b_el;\n}\n    }\n  }\n  // clang-format on\n\n  for (auto const fixed_dof : fixed_dofs) {\n    auto const diagonal_entry = A.coeff(fixed_dof, fixed_dof); // TODO // sparse\n\n    b(fixed_dof) = 0.0;\n\n    std::vector<std::int64_t> non_zero_visitor;\n\n    // // Zero the rows and columns\n    // for (sparse_matrix::InnerIterator it(A, fixed_dof); it; ++it) {\n    //   // Set the value of the col or row resp. to zero\n    //   it.valueRef() = 0.0;\n    //   non_zero_visitor.push_back(A.IsRowMajor ? it.col() : it.row());\n    // }\n    // // Zero the row or col respectively\n    // for (auto const &non_zero : non_zero_visitor) {\n    //   const auto row = A.IsRowMajor ? non_zero : fixed_dof;\n    //   const auto col = A.IsRowMajor ? fixed_dof : non_zero;\n    //\n    //   A.coeffRef(row, col) = 0.0;\n    // }\n    for (int i = 0; i < A.rows(); i++) {\n      for (int j = 0; j < A.cols(); j++) {\n        A.coeffRef(fixed_dof, j) = 0.0;\n        A.coeffRef(i, fixed_dof) = 0.0;\n      }\n    }\n    // Reset the diagonal to the same value to preserve conditioning\n    A.coeffRef(fixed_dof, fixed_dof) = diagonal_entry;\n  }\n\n  // TODO //Vector x = (b.norm() > 0.0) ? A.partialPivLu().solve(b)\n\n  Vector x;\n  if (b.norm() > 0)\n    x = A.partialPivLu().solve(b); // fullPivLu\n  else {\n    x = b;\n  }\n  // Eigen::SimplicialCholesky<Eigen::SparseMatrix<double>> chol(\n  //     A); // performs a Cholesky factorization of A\n  // Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>> chol(\n  //     A); // performs a Cholesky factorization of A\n  // Eigen::VectorXd x = chol.solve(\n  //     b); // use the factorization to solve for the given right hand side\n\n  output = mxCreateDoubleMatrix(nmodes, ntp, mxREAL);\n  auto out_pt = mxGetPr(output);\n  Eigen::Map<Eigen::MatrixXd> mapp(out_pt, nmodes, ntp);\n  mapp = x; // copy\n  // std::copy(x.begin(), x.end(), mxGetPr(output));\n  return;\n}\n\n// mxArray *cpp_to_MexArray(const std::vector<double> &v) {\n//   mxArray *mx = mxCreateDoubleMatrix(1, v.size(), mxREAL);\n//   std::copy(v.begin(), v.end(), mxGetPr(mx));\n//\n//   return mx;\n// }\n", "meta": {"hexsha": "af77d08902013b2aee553f5584d5485cb2ee11de", "size": 8430, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab/matlab_mex/src_mex/semi_cleaned_version/mex_functions/src/compute_time_mode/compute_time_mode.cpp", "max_stars_repo_name": "shadialameddin/numerical_tools_and_friends", "max_stars_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matlab/matlab_mex/src_mex/semi_cleaned_version/mex_functions/src/compute_time_mode/compute_time_mode.cpp", "max_issues_repo_name": "shadialameddin/numerical_tools_and_friends", "max_issues_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matlab/matlab_mex/src_mex/semi_cleaned_version/mex_functions/src/compute_time_mode/compute_time_mode.cpp", "max_forks_repo_name": "shadialameddin/numerical_tools_and_friends", "max_forks_repo_head_hexsha": "cc9f10f58886ee286ed89080e38ebd303d3c72a5", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0256410256, "max_line_length": 114, "alphanum_fraction": 0.6158956109, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.40549457143719597}}
{"text": "#include <LBFGSB.h>\n#include <vector>\n#include <iostream>\n#include <Eigen/Dense>\n#include <MathUtil.h>\n#include <fstream>\n#include <iomanip>\n\n#include <nlopt.hpp>\n#include <Pluckertree.h>\n#include <PluckertreeSegments.h>\n\nusing namespace LBFGSpp;\n\nusing Vector = Eigen::VectorXd;\n\nclass FixedMomentMinDist\n{\nprivate:\n    using number_t = double;\n    using Vector3_t = Eigen::Vector3d;\n    using Vector2_t = Eigen::Vector2d;\n    using Matrix3_t = Eigen::Matrix3d;\n\n    Vector3_t q;\n    Vector3_t h1;\n    Vector3_t h2;\npublic:\n    FixedMomentMinDist(Vector3_t q, Vector3_t dirLowerBound, Vector3_t dirUpperBound)\n            : q(std::move(q)), h1(std::move(dirLowerBound)), h2(std::move(dirUpperBound)) {}\n\n    double operator()(const Vector& x, Vector& grad)\n     {\n        // Careful, don't disturb the big pile of math!\n        number_t phi_k = x[0];\n        number_t theta_k = x[1];\n        number_t r_k = x[2];\n\n        // f(k)\n\n\n        Vector3_t k = spherical2cart(phi_k, theta_k, r_k);\n        Vector3_t kd = k / r_k;\n        Vector3_t qp = q - kd*(q.dot(kd));\n        Vector3_t qpd = qp.normalized();\n        auto u = (qp - q).norm();\n\n        auto sin_gamma = std::min(r_k/qp.norm(), (number_t)1.0f);\n        auto cos_gamma = std::sqrt(1 - sin_gamma * sin_gamma);\n\n        Vector3_t da = qpd * cos_gamma + kd.cross(qpd) * sin_gamma;\n        Vector3_t d_alpha;\n        auto da_dot_h1 = da.dot(h1);\n        auto da_dot_h2 = da.dot(h2);\n        if(da_dot_h1 >= 0 && da_dot_h2 >= 0)\n        {\n            d_alpha = da;\n        }else if(da_dot_h1 <= da_dot_h2)\n        {\n            Vector h1_cross_k = h1.cross(k);\n            d_alpha = std::copysign(1.0f, h2.dot(h1_cross_k)) * h1_cross_k.normalized();\n        }else\n        {\n            Vector h2_cross_k = h2.cross(k);\n            d_alpha = std::copysign(1.0f, h1.dot(h2_cross_k)) * h2_cross_k.normalized();\n        }\n\n        Vector3_t db = - qpd * cos_gamma + kd.cross(qpd) * sin_gamma;\n        Vector3_t d_beta;\n        auto db_dot_h1 = db.dot(h1);\n        auto db_dot_h2 = db.dot(h2);\n        if(db_dot_h1 >= 0 && db_dot_h2 >= 0)\n        {\n            d_beta = db;\n        }else if(db_dot_h1 < db_dot_h2)\n        {\n            Vector h1_cross_k = h1.cross(k);\n            d_beta = std::copysign(1.0f, h2.dot(h1_cross_k)) * h1_cross_k.normalized();\n        }else\n        {\n            Vector h2_cross_k = h2.cross(k);\n            d_beta = std::copysign(1.0f, h1.dot(h2_cross_k)) * h2_cross_k.normalized();\n        }\n\n        auto va = (qp.cross(d_alpha) - k).norm();\n        auto vb = (qp.cross(d_beta) - k).norm();\n        auto v = std::min(va, vb);\n\n        auto f = std::sqrt(u*u + v*v);\n\n        // partial\n        /*auto sin_theta_k = std::sin(theta_k);\n        auto pow2_sin_theta_k = sin_theta_k * sin_theta_k;\n        auto sin_2theta_k = std::sin(2*theta_k);\n\n        auto cos_theta_k = std::cos(theta_k);\n        auto cos_2theta_k = std::cos(2*theta_k);\n        auto pow2_cos_theta_k = cos_theta_k * cos_theta_k;\n\n        auto sin_phi_k = std::sin(phi_k);\n        auto pow2_sin_phi_k = sin_phi_k * sin_phi_k;\n        auto sin_2phi_k = std::sin(2*phi_k);\n\n        auto cos_phi_k = std::cos(phi_k);\n        auto cos_2phi_k = std::cos(2*phi_k);\n        auto pow2_cos_phi_k = cos_phi_k * cos_phi_k;\n\n        ///\n        auto partial_k_phi_k = r_k * Vector3_t(sin_theta_k * (-sin_phi_k), sin_theta_k * cos_phi_k, cos_theta_k);\n        auto partial_k_theta_k = r_k * Vector3_t(cos_theta_k * cos_phi_k, cos_theta_k * sin_phi_k, (-sin_theta_k));\n        auto partial_k_r_k = Vector3_t(sin_theta_k * cos_phi_k, sin_theta_k * sin_phi_k, cos_theta_k);\n\n        Matrix3_t partial_k;\n        partial_k.row(0) = partial_k_phi_k;\n        partial_k.row(1) = partial_k_theta_k;\n        partial_k.row(2) = partial_k_r_k;\n        ///\n\n        auto k_norm = k.norm();\n        Matrix3_t partial_kd;\n        for(int i = 0; i < 3; ++i)\n        {\n            partial_kd.row(i) = (partial_k.row(i)/k_norm) - k.transpose() * ((-1/(std::pow(k_norm, 3))) * (k.x() * partial_k.row(i).x() + k.y() * partial_k.row(i).y() + k.z() * partial_k.row(i).z()));\n        }\n\n        ///\n        Matrix3_t partial_qp;\n        for(int i = 0; i < 3; ++i)\n        {\n            partial_qp.row(i).x() = q.x() * 2 * kd.x() * partial_kd.row(i).x();\n            partial_qp.row(i).x() += q.y() * (partial_kd.row(i).x() * kd.y() + kd.x() * partial_kd.row(i).y());\n            partial_qp.row(i).x() += q.z() * (partial_kd.row(i).x() * kd.z() + kd.x() * partial_kd.row(i).z());\n\n            partial_qp.row(i).y() = q.x() * (partial_kd.row(i).y() * kd.x() + kd.y() * partial_kd.row(i).x());\n            partial_qp.row(i).y() += q.y() * 2 * kd.y() * partial_kd.row(i).y();\n            partial_qp.row(i).y() += q.z() * (partial_kd.row(i).y() * kd.z() + kd.y() * partial_kd.row(i).z());\n\n            partial_qp.row(i).z() = q.x() * (partial_kd.row(i).z() * kd.x() + kd.z() * partial_kd.row(i).x());\n            partial_qp.row(i).z() += q.y() * (partial_kd.row(i).z() * kd.y() + kd.z() * partial_kd.row(i).y());\n            partial_qp.row(i).z() += q.z() * 2 * kd.z() * partial_kd.row(i).z();\n\n            partial_qp.row(i) *= -1;\n        }\n        ///\n\n        //auto partial_pow2_u_phi_k = 2*(qp.x() - q.x()) * partial_qp_phi_k.x() + 2*(qp.y() - q.y()) * partial_qp_phi_k.y() + 2*(qp.z() - q.z()) * partial_qp_phi_k.z();\n        auto partial_pow2_u = 2 * (partial_qp * (qp - q));\n\n\n\n        auto da_xy_norm = Eigen::Vector2f(da.x(), da.y()).norm();\n\n        auto qp_norm = qp.norm();\n        //double partial_delta_phi_k = (1/qp_norm) * (qp.x() * partial_qp_phi_k.x() + qp.y() * partial_qp_phi_k.y() + qp.z() * partial_qp_phi_k.z());\n        Vector3_t partial_delta;\n        for(int i = 0; i < 3; i++)\n        {\n            partial_delta[i] = (1/qp_norm) * (qp.x() * partial_qp.row(i).x() + qp.y() * partial_qp.row(i).y() + qp.z() * partial_qp.row(i).z());\n        }\n\n        Matrix3_t partial_qpd;\n        for(int i = 0; i < 3; i++)\n        {\n            partial_qpd.row(i) = (partial_qp.row(i)/qp_norm) + qp.transpose() * (-1/qp.squaredNorm()) * partial_delta[i];\n        }\n\n\n\n        Vector3_t partial_sin_gamma(0, 0, 0);\n        //double partial_sin_gamma_phi_k = 1;\n        if(r_k/qp_norm > 1)\n        {\n            for(int i = 0; i < 3; i++)\n            {\n                partial_sin_gamma[i] = -(r_k/qp.squaredNorm()) * partial_delta[i]; //TODO: is this wrong for i=2?\n                //partial_sin_gamma_phi_k = -(r_k/qp.squaredNorm()) * partial_delta_phi_k;\n            }\n        }\n\n        Vector3_t partial_cos_gamma;\n        for(int i = 0; i < 3; i++)\n        {\n            //TODO\n            partial_cos_gamma[i] = (1/std::sqrt(1-sin_gamma*sin_gamma)) * (-sin_gamma * partial_sin_gamma[i]);\n        }\n\n        Matrix3_t partial_da = Matrix3_t::Zero();\n        float sign = 1.0f;\n        if(va >= vb)\n        {\n            sign = -1.0f; //partial_db\n        }\n\n        for(int i = 0; i < 3; i++)\n        {\n            partial_da.row(i).x() += sign * partial_qpd.row(i).x() * cos_gamma + qpd.x() * partial_cos_gamma[i];\n            partial_da.row(i).y() += sign * partial_qpd.row(i).y() * cos_gamma + qpd.x() * partial_cos_gamma[i];\n            partial_da.row(i).z() += sign * partial_qpd.row(i).z() * cos_gamma + qpd.z() * partial_cos_gamma[i];\n\n            partial_da.row(i).x() += partial_kd.row(i).y() * qpd.z() * sin_gamma + kd.y() * partial_qpd.row(i).z() * sin_gamma + kd.y() * qpd.z() * partial_sin_gamma[i];\n            partial_da.row(i).y() += partial_kd.row(i).x() * qpd.z() * sin_gamma + kd.x() * partial_qpd.row(i).z() * sin_gamma + kd.x() * qpd.z() * partial_sin_gamma[i];\n            partial_da.row(i).z() += partial_kd.row(i).x() * qpd.y() * sin_gamma + kd.x() * partial_qpd.row(i).y() * sin_gamma + kd.x() * qpd.y() * partial_sin_gamma[i];\n\n            partial_da.row(i).x() += partial_kd.row(i).z() * qpd.y() * sin_gamma + kd.z() * partial_qpd.row(i).y() * sin_gamma + kd.z() * qpd.y() * partial_sin_gamma[i];\n            partial_da.row(i).y() += partial_kd.row(i).z() * qpd.x() * sin_gamma + kd.z() * partial_qpd.row(i).x() * sin_gamma + kd.z() * qpd.x() * partial_sin_gamma[i];\n            partial_da.row(i).z() += partial_kd.row(i).y() * qpd.x() * sin_gamma + kd.y() * partial_qpd.row(i).x() * sin_gamma + kd.y() * qpd.x() * partial_sin_gamma[i];\n        }\n\n\n        Matrix3_t partial_d_alpha; //also partial_d_beta, depending on va >= vb\n        if(da_dot_h1 >= 0 && da_dot_h2 >= 0)\n        {\n            partial_d_alpha = partial_da;\n        }else if(da_dot_h1 < da_dot_h2 || (da_dot_h1 == da_dot_h2 && va < vb))\n        {\n            for(int i = 0; i < 3; i++)\n            {\n                auto h1_cross_k_sqr_norm = h1.cross(k).squaredNorm();\n                auto h1_cross_k_norm = std::sqrt(h1_cross_k_sqr_norm);\n\n                auto partial_h1_cross_k_norm = (h1.y()*k.z() - h1.z()*k.y())*(h1.y()*partial_k.row(i).z() - h1.z()*partial_k.row(i).y());\n                partial_h1_cross_k_norm += (h1.x()*k.z() - h1.z()*k.x())*(h1.x()*partial_k.row(i).z() - h1.z()*partial_k.row(i).x());\n                partial_h1_cross_k_norm += (h1.x()*k.y() - h1.y()*k.x())*(h1.x()*partial_k.row(i).y() - h1.y()*partial_k.row(i).x());\n                partial_h1_cross_k_norm *= (1.0/h1_cross_k_norm);\n\n                auto fact = std::copysign(1.0, k.dot(h2.cross(h1))) / h1_cross_k_sqr_norm;\n\n                partial_d_alpha.row(i).x() = h1_cross_k_norm * (h1.y() * partial_k.row(i).z() - h1.z() * partial_k.row(i).y());\n                partial_d_alpha.row(i).x() -= partial_h1_cross_k_norm * (h1.y() * k.z() - h1.z() * k.y());\n\n                partial_d_alpha.row(i).y() = h1_cross_k_norm * (h1.x() * partial_k.row(i).z() - h1.z() * partial_k.row(i).x());\n                partial_d_alpha.row(i).y() -= partial_h1_cross_k_norm * (h1.x() * k.z() - h1.z() * k.x());\n\n                partial_d_alpha.row(i).z() = h1_cross_k_norm * (h1.x() * partial_k.row(i).y() - h1.y() * partial_k.row(i).x());\n                partial_d_alpha.row(i).z() -= partial_h1_cross_k_norm * (h1.x() * k.y() - h1.y() * k.x());\n\n                partial_d_alpha.row(i) *= fact;\n            }\n        }else\n        {\n            for(int i = 0; i < 3; i++)\n            {\n                auto h2_cross_k_sqr_norm = h2.cross(k).squaredNorm();\n                auto h2_cross_k_norm = std::sqrt(h2_cross_k_sqr_norm);\n\n                auto partial_h2_cross_k_norm = (h1.y()*k.z() - h2.z()*k.y())*(h2.y()*partial_k.row(i).z() - h2.z()*partial_k.row(i).y());\n                partial_h2_cross_k_norm += (h2.x()*k.z() - h2.z()*k.x())*(h2.x()*partial_k.row(i).z() - h2.z()*partial_k.row(i).x());\n                partial_h2_cross_k_norm += (h2.x()*k.y() - h2.y()*k.x())*(h2.x()*partial_k.row(i).y() - h2.y()*partial_k.row(i).x());\n                partial_h2_cross_k_norm *= (1.0/h2_cross_k_norm);\n\n                auto fact = std::copysign(1.0, k.dot(h2.cross(h1))) / h2_cross_k_sqr_norm;\n\n                partial_d_alpha.row(i).x() = h2_cross_k_norm * (h2.y() * partial_k.row(i).z() - h2.z() * partial_k.row(i).y());\n                partial_d_alpha.row(i).x() -= partial_h2_cross_k_norm * (h2.y() * k.z() - h2.z() * k.y());\n\n                partial_d_alpha.row(i).y() = h2_cross_k_norm * (h2.x() * partial_k.row(i).z() - h2.z() * partial_k.row(i).x());\n                partial_d_alpha.row(i).y() -= partial_h2_cross_k_norm * (h2.x() * k.z() - h2.z() * k.x());\n\n                partial_d_alpha.row(i).z() = h2_cross_k_norm * (h2.x() * partial_k.row(i).y() - h2.y() * partial_k.row(i).x());\n                partial_d_alpha.row(i).z() -= partial_h2_cross_k_norm * (h2.x() * k.y() - h2.y() * k.x());\n\n                partial_d_alpha.row(i) *= fact;\n            }\n        }\n\n        ////\n\n        auto c_alpha = qp.cross(da);\n        Matrix3_t partial_c_alpha;\n        for(int i = 0; i < 3; i++)\n        {\n            partial_c_alpha.row(i) = Vector3_t(\n                    (partial_qp.row(i).y()*d_alpha.z() + qp.y() * partial_d_alpha.row(i).z()) - (partial_qp.row(i).z()*d_alpha.y() + qp.z()*partial_d_alpha.row(i).y()),\n                    (partial_qp.row(i).x()*d_alpha.z() + qp.x() * partial_d_alpha.row(i).z()) - (partial_qp.row(i).z()*d_alpha.x() + qp.z()*partial_d_alpha.row(i).x()),\n                    (partial_qp.row(i).x()*d_alpha.y() + qp.x() * partial_d_alpha.row(i).y()) - (partial_qp.row(i).y()*d_alpha.x() + qp.y()*partial_d_alpha.row(i).x())\n            );\n        }\n\n        Vector3_t partial_v;\n        for(int i = 0; i < 3; i++)\n        {\n            partial_v[i] = (1.0/va) * (\n                    (c_alpha.x() - k.x()) * (partial_c_alpha.row(i).x() - partial_k.row(i).x()) +\n                    (c_alpha.y() - k.y()) * (partial_c_alpha.row(i).y() - partial_k.row(i).y()) +\n                    (c_alpha.z() - k.z()) * (partial_c_alpha.row(i).z() - partial_k.row(i).z())\n            );\n        }\n\n        Vector3_t partial_pow2_v = 2*va*partial_v;\n\n        grad = (1.0/(2.0*std::sqrt(u*u + v*v))) * (partial_pow2_u + partial_pow2_v);\n        /*assert(!grad.hasNaN());\n        assert(!std::isinf(grad[0]));\n        assert(!std::isinf(grad[1]));\n        assert(!std::isinf(grad[2]));*/\n\n        return f;\n    }\n};\n\nclass FixedMomentMinHitDist\n{\nprivate:\n    using number_t = double;\n    using Vector3_t = Eigen::Vector3d;\n    using Vector2_t = Eigen::Vector2d;\n    using Matrix3_t = Eigen::Matrix3d;\n\n    Vector3_t q;\n    Vector3_t q_n;\n    Vector3_t h1;\n    Vector3_t h2;\npublic:\n    FixedMomentMinHitDist(Vector3_t q, Vector3_t q_n, Vector3_t dirLowerBound, Vector3_t dirUpperBound)\n            : q(std::move(q)), q_n(std::move(q_n)), h1(std::move(dirLowerBound)), h2(std::move(dirUpperBound)) {}\n\n    double operator()(const Vector& x, Vector& grad)\n    {\n        // Careful, don't disturb the big pile of math!\n        number_t phi_k = x[0];\n        number_t theta_k = x[1];\n        number_t r_k = x[2];\n\n        // f(k)\n\n        Vector3_t k = spherical2cart(phi_k, theta_k, r_k);\n        Vector3_t kd = k.normalized();\n\n        //Find intersection line of directionvector plane with query plane\n        Vector3_t kd_cross_qn = kd.cross(q_n);\n        auto kd_cross_qn_norm = kd_cross_qn.norm();\n        if(kd_cross_qn_norm < 1e-6) // All lines are parallel to the query plane, assume all miss.\n        {\n            return std::numeric_limits<double>::infinity();\n        }\n        Vector3_t isect_d = kd_cross_qn / kd_cross_qn_norm;\n        Vector3_t isect_k = kd * (q_n.dot(q)/kd_cross_qn_norm);\n        Vector3_t isect_p = isect_d.cross(isect_k);\n        Vector3_t qpl = isect_p + isect_d * isect_d.dot(q - isect_p);\n        Vector3_t qpld = qpl.normalized();\n\n        auto sin_gamma = std::min(r_k/qpl.norm(), (number_t)1.0f);\n        auto cos_gamma = std::sqrt(1 - sin_gamma * sin_gamma);\n\n        Vector3_t da = qpld * cos_gamma + kd.cross(qpld) * sin_gamma;\n        Vector3_t d_alpha;\n        auto da_dot_h1 = da.dot(h1);\n        auto da_dot_h2 = da.dot(h2);\n        if(da_dot_h1 >= 0 && da_dot_h2 >= 0)\n        {\n            d_alpha = da;\n        }else if(da_dot_h1 <= da_dot_h2)\n        {\n            Vector h1_cross_k = h1.cross(k);\n            d_alpha = std::copysign(1.0f, h2.dot(h1_cross_k)) * h1_cross_k.normalized();\n        }else\n        {\n            Vector h2_cross_k = h2.cross(k);\n            d_alpha = std::copysign(1.0f, h1.dot(h2_cross_k)) * h2_cross_k.normalized();\n        }\n\n        Vector3_t db = - qpld * cos_gamma + kd.cross(qpld) * sin_gamma;\n        Vector3_t d_beta;\n        auto db_dot_h1 = db.dot(h1);\n        auto db_dot_h2 = db.dot(h2);\n        if(db_dot_h1 >= 0 && db_dot_h2 >= 0)\n        {\n            d_beta = db;\n        }else if(db_dot_h1 < db_dot_h2)\n        {\n            Vector h1_cross_k = h1.cross(k);\n            d_beta = std::copysign(1.0f, h2.dot(h1_cross_k)) * h1_cross_k.normalized();\n        }else\n        {\n            Vector h2_cross_k = h2.cross(k);\n            d_beta = std::copysign(1.0f, h1.dot(h2_cross_k)) * h2_cross_k.normalized();\n        }\n\n        //Calculate intersection point of isect line with (d;k)\n        number_t va = std::numeric_limits<double>::infinity();\n        if(1 - std::abs(d_alpha.dot(isect_d)) > 1e-3)\n        {\n            Vector3_t isect_d_cross_d_alpha = isect_d.cross(d_alpha);\n            Vector3_t vp_a = (1.0/isect_d.cross(d_alpha).squaredNorm()) * (isect_d * (k.dot(isect_d_cross_d_alpha)) - d_alpha * (isect_k.dot(isect_d_cross_d_alpha)));\n            va = (q - vp_a).norm();\n        }\n\n        number_t vb = std::numeric_limits<double>::infinity();\n        if(1 - std::abs(d_beta.dot(isect_d)) > 1e-3)\n        {\n            Vector3_t isect_d_cross_d_beta = isect_d.cross(d_beta);\n            Vector3_t vp_b = (1.0/isect_d.cross(d_beta).squaredNorm()) * (isect_d * (k.dot(isect_d_cross_d_beta)) - d_beta * (isect_k.dot(isect_d_cross_d_beta)));\n            vb = (q - vp_b).norm();\n        }\n\n        auto v = std::min(va, vb);\n        if(std::isinf(v))\n        {\n            return std::numeric_limits<double>::infinity();\n        }\n\n        return v;\n    }\n};\n\nclass FixedMomentMinSegmentDist\n{\nprivate:\n    using number_t = double;\n    using Vector3_t = Eigen::Vector3d;\n    using Vector2_t = Eigen::Vector2d;\n    using Matrix3_t = Eigen::Matrix3d;\n\n    Vector3_t q;\n    Vector3_t h1;\n    Vector3_t h2;\n    float t1;\n    float t2;\npublic:\n    FixedMomentMinSegmentDist(Vector3_t q, Vector3_t dirLowerBound, Vector3_t dirUpperBound, float t1, float t2)\n            : q(std::move(q)), h1(std::move(dirLowerBound)), h2(std::move(dirUpperBound)), t1(t1), t2(t2) {}\n\n    double operator()(const Vector& x, Vector& grad)\n    {\n        number_t phi_k = x[0];\n        number_t theta_k = x[1];\n        number_t r_k = x[2];\n\n        // f(k)\n\n        Vector3_t k = spherical2cart(phi_k, theta_k, r_k);\n        Vector3_t kd = k / r_k;\n        Vector3_t qp = q - kd*(q.dot(kd));\n        auto qp_norm = qp.norm();\n        Vector3_t qpd = qp / qp_norm;\n        auto u = (qp - q).norm();\n\n        auto calc_dist_for_gamma = [](const Vector3_t& qp, const Vector3_t& qpd, const Vector3_t& k, const Vector3_t& kd,\n                const Vector3_t& h1, const Vector3_t& h2, number_t orientation, number_t sin_gamma, number_t t1, number_t t2)\n        {\n            auto cos_gamma = std::sqrt(1 - sin_gamma * sin_gamma);\n            Vector3_t da = orientation * qpd * cos_gamma + kd.cross(qpd) * sin_gamma;\n            Vector3_t d_alpha;\n            auto da_dot_h1 = da.dot(h1);\n            auto da_dot_h2 = da.dot(h2);\n            if(da_dot_h1 >= 0 && da_dot_h2 >= 0)\n            {\n                d_alpha = da;\n            }else if(da_dot_h1 <= da_dot_h2)\n            {\n                Vector h1_cross_k = h1.cross(k);\n                d_alpha = std::copysign(1.0f, h2.dot(h1_cross_k)) * h1_cross_k.normalized();\n            }else\n            {\n                Vector h2_cross_k = h2.cross(k);\n                d_alpha = std::copysign(1.0f, h1.dot(h2_cross_k)) * h2_cross_k.normalized();\n            }\n\n            //auto v = (qp.cross(d_alpha) - k).norm();\n            Vector3_t p = d_alpha.cross(k);\n            auto t = std::min(std::max(d_alpha.dot(qp), t1), t2);\n            auto v = ((p + t*d_alpha) - qp).norm();\n            return v;\n        };\n\n        auto t1_k_hypo_sqr = t1*t1 + r_k*r_k;\n        auto t2_k_hypo_sqr = t2*t2 + r_k*r_k;\n        number_t v;\n        if(t1 >= 0 && t2 >= 0)\n        {\n            number_t sin_gamma;\n            if(qp_norm > t2_k_hypo_sqr)\n            {\n                sin_gamma = std::min(r_k/std::sqrt(t2_k_hypo_sqr), (number_t)1.0f);\n            }\n            else if(qp_norm < t1_k_hypo_sqr)\n            {\n                sin_gamma = std::min(r_k/std::sqrt(t1_k_hypo_sqr), (number_t)1.0f);\n            }\n            else\n            {\n                sin_gamma = std::min(r_k/qp_norm, (number_t)1.0f);\n            }\n            v = calc_dist_for_gamma(qp, qpd, k, kd, h1, h2, 1, sin_gamma, t1, t2);\n        }\n        else if(t1 <= 0 && t2 <= 0)\n        {\n            number_t sin_gamma;\n            if(qp_norm > t1_k_hypo_sqr)\n            {\n                sin_gamma = std::min(r_k/std::sqrt(t1_k_hypo_sqr), (number_t)1.0f);\n            }\n            else if(qp_norm < t2_k_hypo_sqr)\n            {\n                sin_gamma = std::min(r_k/std::sqrt(t2_k_hypo_sqr), (number_t)1.0f);\n            }\n            else\n            {\n                sin_gamma = std::min(r_k/qp_norm, (number_t)1.0f);\n            }\n            v = calc_dist_for_gamma(qp, qpd, k, kd, h1, h2, -1, sin_gamma, t1, t2);\n        }\n        else\n        {\n            number_t sin_gamma_a;\n            if(qp_norm > t2_k_hypo_sqr)\n            {\n                sin_gamma_a = std::min(r_k/std::sqrt(t2_k_hypo_sqr), (number_t)1.0f);\n            }\n            else\n            {\n                sin_gamma_a = std::min(r_k/qp_norm, (number_t)1.0f);\n            }\n            number_t va = calc_dist_for_gamma(qp, qpd, k, kd, h1, h2, 1, sin_gamma_a, t1, t2);\n\n            number_t sin_gamma_b;\n            if(qp_norm > t1_k_hypo_sqr)\n            {\n                sin_gamma_b = std::min(r_k/std::sqrt(t1_k_hypo_sqr), (number_t)1.0f);\n            }\n            else\n            {\n                sin_gamma_b = std::min(r_k/qp_norm, (number_t)1.0f);\n            }\n            number_t vb = calc_dist_for_gamma(qp, qpd, k, kd, h1, h2, -1, sin_gamma_b, t1, t2);\n\n            v = std::min(va, vb);\n        }\n\n        auto f = std::sqrt(u*u + v*v);\n        return f;\n    }\n};\n\nnamespace pluckertree\n{\n    double FindMinDist(\n            const Eigen::Vector3f& point,\n            const Eigen::Vector3f& dirLowerBound,\n            const Eigen::Vector3f& dirUpperBound,\n            const Eigen::Vector3f& momentLowerBound,\n            const Eigen::Vector3f& momentUpperBound,\n            Eigen::Vector3f& minimum\n    )\n    {\n        auto minimize = [point,dirLowerBound,dirUpperBound,momentLowerBound,momentUpperBound](Eigen::Vector3f& minimum){\n            //nlopt::opt opt(nlopt::LN_COBYLA, 3);//LN_NELDERMEAD, LN_SBPLX\n            nlopt::opt opt(nlopt::LN_SBPLX, 3);//LN_NELDERMEAD, LN_SBPLX\n\n            std::vector<double> lb(momentLowerBound.data(), momentLowerBound.data() + momentLowerBound.rows() * momentLowerBound.cols());\n            opt.set_lower_bounds(lb);\n\n            std::vector<double> hb(momentUpperBound.data(), momentUpperBound.data() + momentUpperBound.rows() * momentUpperBound.cols());\n            opt.set_upper_bounds(hb);\n\n            FixedMomentMinDist fun(point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>());\n            auto obj_func = [](const std::vector<double> &x, std::vector<double> &grad, void* f_data) -> double {\n                FixedMomentMinDist* fun = reinterpret_cast<FixedMomentMinDist*>(f_data);\n                Vector x_vect = Eigen::Vector3d {x[0], x[1], x[2]};\n                Vector grad_vect = Eigen::Vector3d {0, 0, 0};\n                auto result = (*fun)(x_vect, grad_vect);\n                return result;\n            };\n            opt.set_min_objective(obj_func, &fun);\n\n            opt.set_xtol_rel(1e-3);\n            opt.set_stopval(1e-3);\n            opt.set_maxtime(1);\n            opt.set_maxeval(1000);\n\n            //Vector vec = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f).cast<double>();\n            Vector vec = minimum.cast<double>();\n            std::vector<double> x(vec.data(), vec.data() + vec.rows() * vec.cols());\n\n            try\n            {\n                double minf;\n                nlopt::result result = opt.optimize(x, minf);\n\n                minimum = {x[0], x[1], x[2]};\n                return minf;\n            }\n            catch(std::exception &e) {\n                std::cout << \"nlopt failed: \" << e.what() << std::endl;\n                throw;\n            }\n        };\n        Eigen::Vector3f minHint;\n        //minHint = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f);\n        double minVal = 1E99;\n        minHint = momentLowerBound;\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; } //TODO: this can be higher if the parent node has a higher min dist value\n        minHint = momentUpperBound;\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentLowerBound.x(), momentLowerBound.y(), momentUpperBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentLowerBound.x(), momentUpperBound.y(), momentLowerBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentUpperBound.x(), momentLowerBound.y(), momentLowerBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentLowerBound.x(), momentUpperBound.y(), momentUpperBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentUpperBound.x(), momentUpperBound.y(), momentLowerBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentUpperBound.x(), momentLowerBound.y(), momentUpperBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        return minVal;\n\n        /*// Set up parameters\n        LBFGSBParam<double> param;\n        param.epsilon = 1e-6;\n        param.max_iterations = 100;\n\n        // Create solver and function object\n        LBFGSBSolver<double> solver(param);  // New solver class\n        FixedMomentMinDist fun(point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>());\n\n        // Initial guess\n        Vector x = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f).cast<double>();\n\n        // x will be overwritten to be the best point found\n        double dist;\n        int nbIter = solver.minimize(fun, x, dist, momentLowerBound.cast<double>(), momentUpperBound.cast<double>());\n        minimum = x.cast<float>();\n\n        std::cout << nbIter << \" iterations\" << std::endl;\n        std::cout << \"x = \\n\" << x.transpose() << std::endl;\n        std::cout << \"f(x) = \" << dist << std::endl;\n\n        return dist;*/\n    }\n\n    double FindMinHitDist(\n            const Eigen::Vector3f& point,\n            const Eigen::Vector3f& point_normal,\n            const Eigen::Vector3f& dirLowerBound,\n            const Eigen::Vector3f& dirUpperBound,\n            const Eigen::Vector3f& momentLowerBound,\n            const Eigen::Vector3f& momentUpperBound,\n            Eigen::Vector3f& minimum\n    )\n    {\n        auto minimize = [point,point_normal,dirLowerBound,dirUpperBound,momentLowerBound,momentUpperBound](Eigen::Vector3f& minimum){\n            //nlopt::opt opt(nlopt::LN_COBYLA, 3);//LN_NELDERMEAD, LN_SBPLX\n            nlopt::opt opt(nlopt::LN_SBPLX, 3);//LN_NELDERMEAD, LN_SBPLX\n\n            std::vector<double> lb(momentLowerBound.data(), momentLowerBound.data() + momentLowerBound.rows() * momentLowerBound.cols());\n            opt.set_lower_bounds(lb);\n\n            std::vector<double> hb(momentUpperBound.data(), momentUpperBound.data() + momentUpperBound.rows() * momentUpperBound.cols());\n            opt.set_upper_bounds(hb);\n\n            FixedMomentMinHitDist fun(point.cast<double>(), point_normal.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>());\n            auto obj_func = [](const std::vector<double> &x, std::vector<double> &grad, void* f_data) -> double {\n                FixedMomentMinHitDist* fun = reinterpret_cast<FixedMomentMinHitDist*>(f_data);\n                Vector x_vect = Eigen::Vector3d {x[0], x[1], x[2]};\n                Vector grad_vect = Eigen::Vector3d {0, 0, 0};\n                auto result = (*fun)(x_vect, grad_vect);\n                return result;\n            };\n            opt.set_min_objective(obj_func, &fun);\n\n            opt.set_xtol_rel(1e-3);\n            opt.set_stopval(1e-3);\n            opt.set_maxtime(1);\n            opt.set_maxeval(1000);\n\n            //Vector vec = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f).cast<double>();\n            Vector vec = minimum.cast<double>();\n            std::vector<double> x(vec.data(), vec.data() + vec.rows() * vec.cols());\n\n            try\n            {\n                double minf;\n                nlopt::result result = opt.optimize(x, minf);\n\n                minimum = {x[0], x[1], x[2]};\n                return minf;\n            }\n            catch(std::exception &e) {\n                std::cout << \"nlopt failed: \" << e.what() << std::endl;\n                throw;\n            }\n        };\n        Eigen::Vector3f minHint;\n        //minHint = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f);\n        double minVal = 1E99;\n        minHint = momentLowerBound;\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; } //TODO: this can be higher if the parent node has a higher min dist value\n        minHint = momentUpperBound;\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentLowerBound.x(), momentLowerBound.y(), momentUpperBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentLowerBound.x(), momentUpperBound.y(), momentLowerBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentUpperBound.x(), momentLowerBound.y(), momentLowerBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentLowerBound.x(), momentUpperBound.y(), momentUpperBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentUpperBound.x(), momentUpperBound.y(), momentLowerBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentUpperBound.x(), momentLowerBound.y(), momentUpperBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        return minVal;\n    }\n\n    // Segments\n    double segments::FindMinDist(\n            const Eigen::Vector3f& point,\n            const Eigen::Vector3f& dirLowerBound,\n            const Eigen::Vector3f& dirUpperBound,\n            const Eigen::Vector3f& momentLowerBound,\n            const Eigen::Vector3f& momentUpperBound,\n            float t1Min,\n            float t2Max,\n            Eigen::Vector3f& min\n    )\n    {\n        auto minimize = [point,dirLowerBound,dirUpperBound,momentLowerBound,momentUpperBound, t1Min, t2Max](Eigen::Vector3f& minimum){\n            nlopt::opt opt(nlopt::LN_COBYLA, 3);//LN_NELDERMEAD, LN_SBPLX\n\n            std::vector<double> lb(momentLowerBound.data(), momentLowerBound.data() + momentLowerBound.rows() * momentLowerBound.cols());\n            opt.set_lower_bounds(lb);\n\n            std::vector<double> hb(momentUpperBound.data(), momentUpperBound.data() + momentUpperBound.rows() * momentUpperBound.cols());\n            opt.set_upper_bounds(hb);\n\n            FixedMomentMinSegmentDist fun(point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>(), t1Min, t2Max);\n            auto obj_func = [](const std::vector<double> &x, std::vector<double> &grad, void* f_data) -> double {\n                FixedMomentMinSegmentDist* fun = reinterpret_cast<FixedMomentMinSegmentDist*>(f_data);\n                Vector x_vect = Eigen::Vector3d {x[0], x[1], x[2]};\n                Vector grad_vect = Eigen::Vector3d {0, 0, 0};\n                auto result = (*fun)(x_vect, grad_vect);\n                return result;\n            };\n            opt.set_min_objective(obj_func, &fun);\n\n            opt.set_xtol_rel(1e-3);\n            opt.set_stopval(1e-3);\n            opt.set_maxtime(1);\n            opt.set_maxeval(1000);\n\n            //Vector vec = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f).cast<double>();\n            Vector vec = minimum.cast<double>();\n            std::vector<double> x(vec.data(), vec.data() + vec.rows() * vec.cols());\n\n            try\n            {\n                double minf;\n                nlopt::result result = opt.optimize(x, minf);\n\n                minimum = {x[0], x[1], x[2]};\n                return minf;\n            }\n            catch(std::exception &e) {\n                std::cout << \"nlopt failed: \" << e.what() << std::endl;\n                throw;\n            }\n        };\n        Eigen::Vector3f minHint;\n        //minHint = (momentLowerBound + (momentUpperBound - momentLowerBound)/2.0f);\n        double minVal = 1E99;\n        minHint = momentLowerBound;\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; } //TODO: this can be higher if the parent node has a higher min dist value\n        minHint = momentUpperBound;\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentLowerBound.x(), momentLowerBound.y(), momentUpperBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentLowerBound.x(), momentUpperBound.y(), momentLowerBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentUpperBound.x(), momentLowerBound.y(), momentLowerBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentLowerBound.x(), momentUpperBound.y(), momentUpperBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentUpperBound.x(), momentUpperBound.y(), momentLowerBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        if(minVal < 1e-3){ return minVal; }\n        minHint = Eigen::Vector3f(momentUpperBound.x(), momentLowerBound.y(), momentUpperBound.z());\n        minVal = std::min(minVal, minimize(minHint));\n        Diag::minimizations++;\n        return minVal;\n    }\n\n    double FindMinDist(\n            const Eigen::Vector3f& point,\n            const Eigen::Vector3f& dirLowerBound,\n            const Eigen::Vector3f& dirUpperBound,\n            const Eigen::Vector3f& moment\n    )\n    {\n        FixedMomentMinDist f(point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>());\n\n        Vector vect = moment.cast<double>();\n        Vector grad;\n        auto dist = f(vect, grad);\n\n        return dist;\n    }\n\n///// POINTCLOUD EXPORT\nthread_local unsigned int pluckertree::Diag::visited = 0;\nthread_local unsigned int pluckertree::Diag::minimizations = 0;\nstd::optional<std::function<void(float, float, float, int)>> pluckertree::Diag::on_node_visited;\nstd::optional<std::function<void(float, float, int)>> pluckertree::Diag::on_node_enter;\nstd::optional<std::function<void(float, float, float, int)>> pluckertree::Diag::on_node_leave;\nstd::optional<std::function<void(float, float, float, float)>> pluckertree::Diag::on_build_variance_calculated;\nbool pluckertree::Diag::force_visit_all = false;\n\nstd::random_device pluckertree::MyRand::rand_dev;\n\nstruct GridPoint\n{\n    Eigen::Vector3f pos;\n    Eigen::Vector3f grad;\n    float dist;\n};\n\n/*std::vector<GridPoint> CalculateGrid(\n        const Eigen::Vector3f& point,\n        const Eigen::Vector3f& query_point,\n        const Eigen::Vector3f& dirLowerBound,\n        const Eigen::Vector3f& dirUpperBound,\n        float x_start,\n        float x_end,\n        float y_start,\n        float y_end,\n        float z_start,\n        float z_end,\n        float resolution\n)\n{\n    FixedMomentMinHitDist f(point.cast<double>(), query_point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>());\n\n    auto x_steps = int((x_end - x_start) / resolution);\n    auto y_steps = int((y_end - y_start) / resolution);\n    auto z_steps = int((z_end - z_start) / resolution);\n\n    std::vector<GridPoint> points(x_steps * y_steps * z_steps);\n\n    for(int x_i = 0; x_i < x_steps; x_i++)\n    {\n        std::cout << ((float)x_i/(float)x_steps)*100.0f << \"%\\r\";\n        std::cout.flush();\n        auto x = x_start + resolution*x_i;\n        for(int y_i = 0; y_i < y_steps; y_i++)\n        {\n            auto y = y_start + resolution*y_i;\n            for(int z_i = 0; z_i < z_steps; z_i++)\n            {\n                auto z = z_start + resolution*z_i;\n\n                Vector vect = cart2spherical(Eigen::Vector3d(x, y, z));\n                Vector grad;\n                auto dist = f(vect, grad);\n\n                auto& curPoint = points[(x_i * y_steps * z_steps) + (y_i * z_steps) + z_i];\n                curPoint.pos = Eigen::Vector3f(x, y, z);\n                curPoint.dist = dist;\n                //curPoint.grad = grad.cast<float>();\n            }\n        }\n    }\n    std::cout << std::endl;\n\n    return points;\n}*/\n\nstd::vector<GridPoint> CalculateBallSlice(\n        const Eigen::Vector3f& point,\n        const Eigen::Vector3f& dirLowerBound,\n        const Eigen::Vector3f& dirUpperBound,\n        const Eigen::Vector3f& mlb,\n        const Eigen::Vector3f& mub,\n        float resolution\n)\n{\n    FixedMomentMinDist f(point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>());\n\n    Eigen::Vector3f stepSize = (mub - mlb) / resolution;\n\n    std::vector<GridPoint> points(resolution * resolution * resolution);\n\n    for(int x_i = 0; x_i < resolution; x_i++)\n    {\n        std::cout << ((float)x_i/(float)resolution)*100.0f << \"%\\r\";\n        std::cout.flush();\n        auto x = mlb.x() + stepSize.x()*x_i;\n        for(int y_i = 0; y_i < resolution; y_i++)\n        {\n            auto y = mlb.y() + stepSize.y()*y_i;\n            for(int z_i = 0; z_i < resolution; z_i++)\n            {\n                auto z = mlb.z() + stepSize.z()*z_i;\n\n                Vector vect = Eigen::Vector3d(x, y, z);\n                Vector grad;\n                auto dist = f(vect, grad);\n\n                auto& curPoint = points[(x_i * resolution * resolution) + (y_i * resolution) + z_i];\n                curPoint.pos = spherical2cart(x, y, z);\n                curPoint.dist = dist;\n                //curPoint.grad = grad.cast<float>();\n            }\n        }\n    }\n    std::cout << std::endl;\n\n    return points;\n}\n\nstd::vector<GridPoint> CalculateBallSlice(\n        const Eigen::Vector3f& point,\n        const Eigen::Vector3f& query_point,\n        const Eigen::Vector3f& dirLowerBound,\n        const Eigen::Vector3f& dirUpperBound,\n        const Eigen::Vector3f& mlb,\n        const Eigen::Vector3f& mub,\n        float resolution\n)\n{\n    FixedMomentMinHitDist f(point.cast<double>(), query_point.cast<double>(), dirLowerBound.cast<double>(), dirUpperBound.cast<double>());\n\n    Eigen::Vector3f stepSize = (mub - mlb) / resolution;\n\n    std::vector<GridPoint> points(resolution * resolution * resolution);\n\n    for(int x_i = 0; x_i < resolution; x_i++)\n    {\n        std::cout << ((float)x_i/(float)resolution)*100.0f << \"%\\r\";\n        std::cout.flush();\n        auto x = mlb.x() + stepSize.x()*x_i;\n        for(int y_i = 0; y_i < resolution; y_i++)\n        {\n            auto y = mlb.y() + stepSize.y()*y_i;\n            for(int z_i = 0; z_i < resolution; z_i++)\n            {\n                auto z = mlb.z() + stepSize.z()*z_i;\n\n                Vector vect = Eigen::Vector3d(x, y, z);\n                Vector grad;\n                auto dist = f(vect, grad);\n\n                auto& curPoint = points[(x_i * resolution * resolution) + (y_i * resolution) + z_i];\n                curPoint.pos = spherical2cart(x, y, z);\n                curPoint.dist = dist;\n                //curPoint.grad = grad.cast<float>();\n            }\n        }\n    }\n    std::cout << std::endl;\n\n    return points;\n}\n\nvoid show_me_the_grid(std::string& file,\n                      const Eigen::Vector3f& dlb,\n                      const Eigen::Vector3f& dub,\n                      const Eigen::Vector3f& mlb,\n                      const Eigen::Vector3f& mub,\n                      const Eigen::Vector3f& q)\n{\n    /*Eigen::Vector3f dlb = Eigen::Vector3f(0,0,-1);\n    Eigen::Vector3f dub = Eigen::Vector3f(-std::sqrt(2)/2.0, std::sqrt(2)/2, 0);\n    Eigen::Vector3f mlb(-M_PI, 0.785398185, 1);\n    Eigen::Vector3f mub(-M_PI/2, 2.3561945, 80);\n    Eigen::Vector3f q(25.216011, 86.2393799, 64.2581253);\n    Eigen::Vector3f q_normal(0.742901862, 0.662636876, 0.0949169919);*/\n\n    float resolution = 300;\n    //auto data = CalculateBallSlice(q, q_normal, dlb, dub, mlb, mub, resolution);\n    auto data = CalculateBallSlice(q, dlb, dub, mlb, mub, resolution);\n\n    std::fstream myfile;\n    myfile = std::fstream(file, std::ios::out | std::ios::binary);\n\n    unsigned int size = data.size();\n    myfile.write(reinterpret_cast<char*>(&size), sizeof(unsigned int));\n    for(const auto& entry : data)\n    {\n        myfile.write(reinterpret_cast<const char*>(&entry.pos.x()), sizeof(float));\n        myfile.write(reinterpret_cast<const char*>(&entry.pos.y()), sizeof(float));\n        myfile.write(reinterpret_cast<const char*>(&entry.pos.z()), sizeof(float));\n        myfile.write(reinterpret_cast<const char*>(&entry.grad.x()), sizeof(float));\n        myfile.write(reinterpret_cast<const char*>(&entry.grad.y()), sizeof(float));\n        myfile.write(reinterpret_cast<const char*>(&entry.grad.z()), sizeof(float));\n        myfile.write(reinterpret_cast<const char*>(&entry.dist), sizeof(float));\n    }\n    myfile.close();\n}\n\n/////\n\n}", "meta": {"hexsha": "6c493b07876a48b998c326327f73b1606619c21f", "size": 42505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pluckertree/RegionDistanceMinimizer.cpp", "max_stars_repo_name": "Wouterdek/pluckertree", "max_stars_repo_head_hexsha": "f55d1ed617f0b158e0904ba8c2320a88358e5ada", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pluckertree/RegionDistanceMinimizer.cpp", "max_issues_repo_name": "Wouterdek/pluckertree", "max_issues_repo_head_hexsha": "f55d1ed617f0b158e0904ba8c2320a88358e5ada", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pluckertree/RegionDistanceMinimizer.cpp", "max_forks_repo_name": "Wouterdek/pluckertree", "max_forks_repo_head_hexsha": "f55d1ed617f0b158e0904ba8c2320a88358e5ada", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.027992278, "max_line_length": 200, "alphanum_fraction": 0.5597459122, "num_tokens": 11993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8438951104066295, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.4054736070592699}}
{"text": "#include <pybind11/eigen.h>\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\nnamespace py = pybind11;\n\n#include <Eigen/Dense>\n#include <MeshFEM/ElasticityTensor.hh>\n#include <MeshFEM/Fields.hh>\n#include <MeshFEM/SymmetricMatrix.hh>\n#include <MeshFEM/Materials.hh>\n#include <MeshFEM/VonMises.hh>\n#include <MeshFEM/Utilities/NameMangling.hh>\n\ntemplate<typename _Real, size_t N>\nvoid bindTensors(py::module& module, py::module& detail_module) {\n    using ETensor = ElasticityTensor    <_Real, N>;\n    using SMValue = SymmetricMatrixValue<_Real, N>;\n    using SMF     = SymmetricMatrixField<_Real, N>;\n\n    auto py_et = py::class_<ETensor>(module, NameMangler<ETensor>::name().c_str())\n        .def(py::init<>())\n        .def(py::init([](const std::string& material_file) { return Materials::Constant<N>(material_file).getTensor(); }), py::arg(\"material_file\"))\n        .def(py::init<_Real, _Real>(), py::arg(\"E\"), py::arg(\"nu\"))\n        .def(\"setIsotropic\", &ETensor::setIsotropic, py::arg(\"E\"), py::arg(\"nu\"))\n        .def(\"setIdentity\",  &ETensor::setIdentity)\n\n        .def(\"getOrthotropicParameters\", py::overload_cast<>(&ETensor::getOrthotropicParameters, py::const_))\n        .def(\"anisotropy\", &ETensor::anisotropy)\n\n        .def(\"__call__\", [](const ETensor &E, size_t i, size_t j, size_t k, size_t l) {\n                    if ((i >= N) || (j >= N) || (k >= N) || (l >= N))\n                        throw std::runtime_error(\"Index out of bounds\");\n                    return E(i, j, k, l);\n                })\n        .def_property_readonly(\"D\", [](const ETensor &E) {\n                    typename ETensor::DType D;\n                    for (int i = 0; i < D.rows(); ++i) {\n                        for (int j = 0; j < D.cols(); ++j) {\n                            D(i, j) = E.D(i, j);\n                        }\n                    }\n                    return D;\n                })\n        .def(\"doubleContract\", [](const ETensor &E, const SMValue &smat) { return E.doubleContract(smat); }, py::arg(\"smat\"))\n        .def(\"doubleContract\", [](const ETensor &E, const SMF     & smf) { \n                    SMF result(smf.domainSize());\n                    for (size_t i = 0; i < smf.domainSize(); ++i)\n                        result(i) = E.doubleContract(smf(i));\n                    return result;\n                }, py::arg(\"smat\"))\n        // .def(\"doubleContract\",    [](const ETensor &E, const ETensor &Eother) { return E.doubleContract(Eother);    }, py::arg(\"E\")) // this produces a non-major-symmetric result, which we haven't bound yet\n        .def(\"quadrupleContract\", [](const ETensor &E, const ETensor &Eother) { return E.quadrupleContract(Eother); }, py::arg(\"E\"))\n\n        .def(\"computeEigenstrains\", &ETensor::computeEigenstrains)\n\n        .def(\"inverse\",         &ETensor::inverse)\n        .def(\"pseudoinverse\",   &ETensor::inverse)\n        .def(\"frobeniusNormSq\", &ETensor::frobeniusNormSq)\n        .def(\"transform\",       &ETensor::transform, py::arg(\"R\"), \"Apply a *orthogonal* change of coordinates to this tensor\")\n        .def(\"__sub__\", [](const ETensor &E, const ETensor &Eother) { return E - Eother; })\n        .def(\"__repr__\", [](const ETensor &E) {\n                std::stringstream ss;\n                ss << N << \"D elasticity tensor with orthotropic moduli: \";\n                E.printOrthotropic(ss);\n                return ss.str(); })\n        ;\n\n    if (N == 3) {\n        py_et.def(\"setOrthotropic\",\n            &ETensor::setOrthotropic3D,\n            py::arg(\"Ex\"),   py::arg(\"Ey\"),   py::arg(\"Ez\"),\n            py::arg(\"nuYX\"), py::arg(\"nuZX\"), py::arg(\"nuZY\"),\n            py::arg(\"muYZ\"), py::arg(\"myZX\"), py::arg(\"muXY\"));\n    }\n\n    if (N == 2) {\n        py_et.def(\"setOrthotropic\",\n            &ETensor::setOrthotropic2D,\n            py::arg(\"Ex\"),   py::arg(\"Ey\"),\n            py::arg(\"nuYX\"), py::arg(\"muXY\"));\n    }\n\n    py::class_<SMValue>(detail_module, NameMangler<SMValue>::name().c_str())\n        .def(\"__call__\", [](const SMValue &sm, size_t i, size_t j) { if ((i >= N) || (j >= N)) throw std::runtime_error(\"Index out of bounds\"); return sm(i, j); }, py::arg(\"i\"), py::arg(\"j\"))\n        .def(\"toMatrix\", [](const SMValue &sm) { return sm.toMatrix(); })\n        .def(\"eigenvalues\",        &SMValue::eigenvalues)\n        .def(\"eigenDecomposition\", &SMValue::eigenDecomposition)\n        ;\n\n    py::class_<SMF>(detail_module, (\"SymmetricMatrixField\" + std::to_string(N) + \"D\" + floatingPointTypeSuffix<_Real>()).c_str())\n        .def(\"vonMises\", [](const SMF &smf) {\n                SMF smf_vm = vonMises(smf);\n                Eigen::VectorXd result(smf_vm.domainSize());\n                for (size_t i = 0; i < smf_vm.domainSize(); ++i)\n                    result[i] = std::sqrt(smf_vm(i).frobeniusNormSq());\n                return result;\n            })\n        .def(\"eigendecomposition\", [](const SMF &smf) {\n                std::vector<SMEigenDecompositionType<_Real, N>> result;\n                result.reserve(smf.domainSize());\n                for (size_t i = 0; i < smf.domainSize(); ++i)\n                    result.push_back(smf(i).eigenDecomposition());\n                return result;\n            })\n        .def(\"__call__\", [](const SMF &smf, size_t i) { if (i >= smf.domainSize()) throw std::runtime_error(\"Index out of bounds.\"); return SMValue(smf(i)); })\n        ;\n\n    module.def(\"SymmetricMatrix\", [](const Eigen::Matrix<_Real, flatLen(N), 1> &flatValues) { return SMValue(flatValues); }, py::arg(\"flatValues\"));\n    module.def(\"SymmetricMatrix\", [](const Eigen::Matrix<_Real, N, N>          &mat)        { return SMValue(       mat); }, py::arg(\"mat\"));\n}\n\ntemplate<typename _Real>\nvoid addBindings(py::module &m) {\n    py::module detail_module = m.def_submodule(\"detail\");\n    py::class_<ETensorEigenDecomposition>(detail_module, \"ETensorEigenDecomposition\")\n        .def_readonly(\"eigenstrains\", &ETensorEigenDecomposition::strains) // flattened symmetric matrix field\n        .def_readonly(\"eigenvalues\",  &ETensorEigenDecomposition::lambdas)\n        ;\n    bindTensors<_Real, 2>(m, detail_module);\n    bindTensors<_Real, 3>(m, detail_module);\n}\n\nPYBIND11_MODULE(tensors, m) {\n    m.doc() = \"Tensors and tensor fields used for elasticity simulations\";\n\n    addBindings<double>(m);\n}\n", "meta": {"hexsha": "2914e112c3012f4c18e211c52c934353518ef69e", "size": 6252, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/python_bindings/tensors.cc", "max_stars_repo_name": "MeshFEM/MeshFEM", "max_stars_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T10:05:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T13:41:50.000Z", "max_issues_repo_path": "src/python_bindings/tensors.cc", "max_issues_repo_name": "MeshFEM/MeshFEM", "max_issues_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-01T15:58:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-19T03:31:09.000Z", "max_forks_repo_path": "src/python_bindings/tensors.cc", "max_forks_repo_name": "MeshFEM/MeshFEM", "max_forks_repo_head_hexsha": "9b3619fa450d83722879bfd0f5a3fe69d927bd63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-10-05T09:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T03:02:39.000Z", "avg_line_length": 48.84375, "max_line_length": 209, "alphanum_fraction": 0.562699936, "num_tokens": 1745, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833945721304, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4054327106672269}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2015 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_REM_PIO2_MEDIUM_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_REM_PIO2_MEDIUM_HPP_INCLUDED\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n#include <boost/simd/function/nearbyint.hpp>\n#include <boost/simd/function/toint.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/constant/three.hpp>\n#include <boost/simd/detail/constant/pio2_1.hpp>\n#include <boost/simd/detail/constant/pio2_1t.hpp>\n#include <boost/simd/detail/constant/pio2_2.hpp>\n#include <boost/simd/detail/constant/pio2_2t.hpp>\n#include <boost/simd/constant/pio2_3.hpp>\n#include <boost/simd/detail/constant/pio2_3t.hpp>\n#include <boost/simd/constant/twoopi.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/function/quadrant.hpp>\n#include <utility>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD (rem_pio2_medium_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bd::scalar_ < bd::floating_<A0> >\n                          )\n  {\n    using result_t = std::pair<A0, A0>;\n    BOOST_FORCEINLINE result_t operator() ( A0 t) const\n    {\n      const A0 fn = nearbyint(t*Twoopi<A0>());\n      A0 r  = t-fn*Pio2_1<A0>();\n      A0 w  = fn*Pio2_1t<A0>();\n      A0 t2 = r;\n      w  = fn*Pio2_2<A0>();\n      r  = t2-w;\n      w  = fn*Pio2_2t<A0>()-((t2-r)-w);\n      t2 = r;\n      w  = fn*Pio2_3<A0>();\n      r  = t2-w;\n      w  = fn*Pio2_3t<A0>()-((t2-r)-w);\n      return  {quadrant(fn), r-w};\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "617ab4b891f1e4d8204ea7ccb389e633fe718334", "size": 2158, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/scalar/function/rem_pio2_medium.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/arch/common/scalar/function/rem_pio2_medium.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/scalar/function/rem_pio2_medium.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 32.696969697, "max_line_length": 100, "alphanum_fraction": 0.5996292864, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4054326997725387}}
{"text": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// Written by Cornelius Steinhardt\n\n\n#ifndef ITL_TFQMR_INCLUDE\n#define ITL_TFQMR_INCLUDE\n\n#include <boost/numeric/mtl/concept/collection.hpp>\n#include <boost/numeric/mtl/utility/exception.hpp>\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/linear_algebra/inverse.hpp>\n#include <boost/numeric/mtl/utility/irange.hpp>\n#include <boost/numeric/mtl/operation/resource.hpp>\n#include <boost/numeric/mtl/interface/vpt.hpp>\n\n#include <boost/numeric/itl/krylov/base_solver.hpp>\n\nnamespace itl {\n\n/// Transposed-free Quasi-minimal residual\ntemplate < typename Matrix, typename Vector,\n\t   typename LeftPreconditioner, typename RightPreconditioner, typename Iteration >\nint tfqmr(const Matrix &A, Vector &x, const Vector &b, const LeftPreconditioner &L, \n\t  const RightPreconditioner &R, Iteration& iter)\n{\n    mtl::vampir_trace<7009> tracer;\n    using math::reciprocal; using mtl::size;\n    typedef typename mtl::Collection<Vector>::value_type Scalar;\n\n    if (size(b) == 0) throw mtl::logic_error(\"empty rhs vector\");\n\n    const Scalar                zero= math::zero(Scalar()), one= math::one(Scalar());\n    Scalar                      theta(zero), eta(zero), tau, rho, rhon, sigma, alpha, beta, c;\n    Vector                      rt(b - A*Vector(solve(R, x))) /* shift x= R*x */, r(solve(L, rt)), u1(resource(x)), u2(resource(x)), \n                                y1(resource(x)), y2(resource(x)), w(resource(x)), d(resource(x), zero), v(resource(x));\n\n    if (iter.finished(rt))\n\treturn iter;\n    y1= w= r;\n    rt= A * Vector(solve(R, y1));\n    u1= v= solve(L,rt);\n    tau= two_norm(r);\n    rho= tau * tau;\n\n    // TFQMR iteration\n    while (! iter.finished(tau)) {\n\t++iter;\n\tsigma= dot(r,v);\n        if (sigma == zero)\n\t    return iter.fail(1, \"tfgmr breakdown, sigma=0 #1\");\n        alpha= rho / sigma;\n\n        // inner loop\n        for(int j=1; j < 3; j++) {\n            if (j == 1) {\n                w-= alpha * u1;\n                d= y1+ (theta * theta * eta / alpha) * d;\n\t    } else {\n                y2= y1 - alpha * v;\n                rt= A * Vector(solve(R, y2));\n                u2= solve(L, rt);\n                w-= alpha * u2;\n                d= y2 + (theta * theta * eta / alpha) * d;\n            }\n            theta= two_norm(w) / tau;\n            c= reciprocal(sqrt(one + theta*theta));\n            tau*= theta * c;\n            eta= c * c * alpha;\n            x+= eta * d;\n        } // end inner loop\n        if (rho == zero)\n            return iter.fail(1, \"tfgmr breakdown, rho=0 #2\");\n        rhon= dot(r,w);\n        beta= rhon/rho;\n        rho= rhon;\n        y1= w + beta*y2;\n        rt= A * Vector(solve(R, y1));\n        u1= solve(L, rt);\n        v= u1 + beta*(u2 + beta*v);\n        rt= A * x - b;\n    }\n    //shift back\n    x= solve(R, x);\n    return iter;\n}\n\n/// Solver class for Transposed-free quasi-minimal residual method; right preconditioner ignored (prints warning if not identity)\n/** Methods inherited from \\ref base_solver. **/\ntemplate < typename LinearOperator, typename Preconditioner= pc::identity<LinearOperator>, \n\t   typename RightPreconditioner= pc::identity<LinearOperator> >\nclass tfqmr_solver\n  : public base_solver< tfqmr_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator >\n{\n    typedef base_solver< tfqmr_solver<LinearOperator, Preconditioner, RightPreconditioner>, LinearOperator > base;\n  public:\n    /// Construct solver from a linear operator; generate (left) preconditioner from it\n    explicit tfqmr_solver(const LinearOperator& A) : base(A), L(A), R(A) {}\n\n    /// Construct solver from a linear operator and left preconditioner\n    tfqmr_solver(const LinearOperator& A, const Preconditioner& L) : base(A), L(L), R(A) {}\n\n    /// Construct solver from a linear operator and left preconditioner\n    tfqmr_solver(const LinearOperator& A, const Preconditioner& L, const RightPreconditioner& R) \n      : base(A), L(L), R(R) {}\n\n    /// Solve linear system approximately as specified by \\p iter\n    template < typename HilbertSpaceX, typename HilbertSpaceB, typename Iteration >\n    int solve(HilbertSpaceX& x, const HilbertSpaceB& b, Iteration& iter) const\n    {\n\treturn tfqmr(this->A, x, b, L, R, iter);\n    }\n\n  private:\n    Preconditioner        L;\n    RightPreconditioner   R;\n};\n\n} // namespace itl\n\n#endif // ITL_TFQMR_INCLUDE\n", "meta": {"hexsha": "e75d09602633a6f5bd671b1f105ea1b9f698fd34", "size": 4774, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/itl/krylov/tfqmr.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "boost/numeric/itl/krylov/tfqmr.hpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "boost/numeric/itl/krylov/tfqmr.hpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 36.1666666667, "max_line_length": 133, "alphanum_fraction": 0.6265186426, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4053503900062879}}
{"text": "#include <vector>\n#include <cfloat>\n\n#include <boost/foreach.hpp>\n\n#include \"types.hpp\"\n#include \"track.hpp\"\n\nusing namespace std;\n\n/**\n * iterates over all possible wire_pos_ptr combinations\n * if next combination is not available returns false\n */\nbool\tnext_combination( vector<wire_pos_ptr_t> &wire_pos_ptr, const vector<int> &wire_count )\n{\n\tconst int chambers_count = wire_count.size();\n\tint\ti = 0;\n\n\twhile(1 + wire_pos_ptr[i] == wire_count[i])\n\t{\n\t\ti++;\n\n\t\tif (i == chambers_count)\n\t\t{\n\t\t\t/* reached last combination */\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tfor(int j = 0; j < i; j++)\n\t{\n\t\twire_pos_ptr[j] = 0;\n\t}\n\n\twire_pos_ptr[i]++;\n\n\treturn true;\n}\n\n/**\n * Removes items from data that haven't got any wires left in them.\n * @param data - data[i] is a pointer to list of wires for i-th chamber\n * @return false if there is no enough non-empty chambers left\n */\nbool\tdelete_empty_chambers( vector< vector<wire_pos_t>* > &data, vector<double> &normal_pos, vector<uint> &used_chambers )\n{\n\tuint\tempty_chambers_count = 0;\n\tauto\tdata_it = data.begin();\n\tauto\tnormal_pos_it = normal_pos.begin();\n\tauto\tused_chambers_it = used_chambers.begin();\n\n\t// check if there is enough non-empty chambers\n\twhile(data_it != data.end())\n\t{\n\t\tif ((*data_it)->empty())\n\t\t{\n\t\t\tempty_chambers_count++;\n\n\t\t\tif (data.size() <= MIN_TRACK_CHAMBERS)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tdata_it = data.erase(data_it);\n\t\t\tnormal_pos_it = normal_pos.erase(normal_pos_it);\n\t\t\tused_chambers_it = used_chambers.erase(used_chambers_it);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdata_it++;\n\t\t\tnormal_pos_it++;\n\t\t\tused_chambers_it++;\n\t\t}\n\t}\n\n\treturn true;\n}\n\ntrack_info_t\treconstruct_track( const vector< vector<wire_pos_t>* > &data, const vector<double> &normal_pos )\n{\n\tconst chamber_id_t\tchambers_count = data.size();\n\tvector<wire_pos_ptr_t>\tbest_wire_pos_ptr(chambers_count);\n\tvector<wire_pos_ptr_t>\twire_pos_ptr(chambers_count);\n\tvector<int>\t\twire_count(chambers_count);\n\n\t// initialize variables\n\t{\n\t\tint chamber_id = 0;\n\n\t\tBOOST_FOREACH(auto chamber_data, data)\n\t\t{\n\t\t\twire_pos_ptr[chamber_id] = 0;\n\t\t\twire_count[chamber_id] = chamber_data->size();\n\n\t\t\tchamber_id++;\n\t\t}\n\t}\n\n\tdouble\tbest_c0, best_c1;\n\tdouble\tbest_sumsq, prev_best_sumsq = FLT_MAX;\n\tvector<double>\tbest_wires_pos;\n\tbool\tfirst = true;\n\n\tdo\n\t{\n\t\tvector<double>\twires;\n\t\tdouble\tc0, c1, sumsq;\n\t\tint i = 0;\n\n\t\t// fill array with values to fit\n\t\tBOOST_FOREACH(auto chamber_data, data)\n\t\t{\n\t\t\twire_pos_t\twire_id = (*chamber_data)[wire_pos_ptr[i]];\n\n\t\t\twires.push_back(wire_id);\n\n\t\t\ti++;\n\t\t}\n\n\t\t// perform linear fit\n\t\t{\n\t\t\tdouble\tm_x = 0;\n\t\t\tdouble\tm_y = 0;\n\t\t\tdouble\tm_dxdy = 0;\n\t\t\tdouble\tm_dxdx = 0;\n\t\t\tint\t\tN = normal_pos.size();\n\n\t\t\tBOOST_FOREACH(double x, normal_pos)\n\t\t\t{\n\t\t\t\tm_x += x;\n\t\t\t}\n\t\t\tm_x /= N;\n\n\t\t\tBOOST_FOREACH(double y, wires)\n\t\t\t{\n\t\t\t\tm_y += y;\n\t\t\t}\n\t\t\tm_y /= N;\n\n\t\t\tauto\txit = normal_pos.begin();\n\t\t\tauto\tyit = wires.begin();\n\t\t\twhile(xit != normal_pos.end())\n\t\t\t{\n\t\t\t\tm_dxdy += (*xit - m_x) * (*yit - m_y);\n\t\t\t\tm_dxdx += (*xit - m_x) * (*xit - m_x);\n\t\t\t\txit++; yit++;\n\t\t\t}\n\t\t\tm_dxdy /= N;\n\t\t\tm_dxdx /= N;\n\n\t\t\tc1 = m_dxdy / m_dxdx;\n\t\t\tc0 = m_y - c1 * m_x;\n\n\t\t\txit = normal_pos.begin();\n\t\t\tyit = wires.begin();\n\t\t\tsumsq = 0;\n\t\t\twhile(xit != normal_pos.end())\n\t\t\t{\n\t\t\t\tdouble\tv = *yit - (c0 + *xit * c1);\n\t\t\t\tsumsq += v * v;\n\t\t\t\txit++; yit++;\n\t\t\t}\n\t\t}\n\n\t\tif (first || (best_sumsq > sumsq))\n\t\t{\n\t\t\tprev_best_sumsq = best_sumsq;\n\t\t\tbest_sumsq = sumsq;\n\t\t\tbest_c0 = c0;\n\t\t\tbest_c1 = c1;\n\t\t\tbest_wires_pos = wires;\n\t\t\tfirst = false;\n\n\t\t\t// save best wires array positions\n\t\t\tfor(chamber_id_t chamber_id = 0; chamber_id < chambers_count; chamber_id++)\n\t\t\t{\n\t\t\t\tbest_wire_pos_ptr[chamber_id] = wire_pos_ptr[chamber_id];\n\t\t\t}\n\t\t}\n\t}\n\twhile(next_combination(wire_pos_ptr, wire_count));\n\n\treturn track_info_t({\n\t\t\tbest_c0, best_c1, best_sumsq, prev_best_sumsq, best_wires_pos, best_wire_pos_ptr\n\t\t\t\t});\n}\n\n/**\n * @warning This function deletes wires that lie on the reconstructd track.\n */\ntemplate<track_type_t track_type>\nvector<track_info_t>\treconstruct_all_tracks( vector< vector<wire_pos_t>* > data, vector<double> normal_pos, double max_chisq )\n{\n\tvector<uint>\tused_chambers;\n\tvector<track_info_t>\tresult;\n\n\tfor(uint i = 0; i < data.size(); i++)\n\t{\n\t\tused_chambers.push_back(i);\n\t}\n\n\t// check if there is enough chambers\n\tif (data.size() < MIN_TRACK_CHAMBERS)\n\t{\n\t\tthrow \"Not enough chambers in original data!\";\n\t}\n\n\twhile(delete_empty_chambers(data, normal_pos, used_chambers))\n\t{\n\t\ttrack_info_t\ttrack = reconstruct_track(data, normal_pos);\n\n\t\ttrack.used_chambers = used_chambers;\n\n\t\tif ((max_chisq > 0) && (track.chisq > max_chisq))\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tresult.push_back(track);\n\n\t\tchamber_id_t\tchamber_id = 0;\n\n\t\tBOOST_FOREACH(auto chamber_data, data)\n\t\t{\n\t\t\twire_pos_ptr_t\tdeletion_pos = track.wire_pos_ptr[chamber_id];\n\n\t\t\t// now delete wires that compose the reconstructd track\n\t\t\tif (track_type == track_type_t::prop)\n\t\t\t{\n\t\t\t\tchamber_data->erase(chamber_data->begin() + deletion_pos);\n\t\t\t}\n\t\t\telse if (track_type == track_type_t::drift)\n\t\t\t{\n\t\t\t\t// for drift chamber point consists of the left and right side\n\t\t\t\t// so we need to remove both\n\t\t\t\tdeletion_pos &= ~1;\n\t\t\t\tchamber_data->erase(chamber_data->begin() + deletion_pos,\n\t\t\t\t                    chamber_data->begin() + deletion_pos + 2);\n\t\t\t}\n\n\t\t\tchamber_id++;\n\t\t}\n\t}\n\n\treturn result;\n}\n\ntemplate vector<track_info_t> reconstruct_all_tracks<track_type_t::prop>( vector< vector<wire_pos_t>* > data, vector<double> normal_pos, double max_chisq );\ntemplate vector<track_info_t> reconstruct_all_tracks<track_type_t::drift>( vector< vector<wire_pos_t>* > data, vector<double> normal_pos, double max_chisq );\n", "meta": {"hexsha": "6dbb43f450ea02fa5ccfff627d0cf066ae7b85b8", "size": 5582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/epecur/track.cpp", "max_stars_repo_name": "veprbl/libepecur", "max_stars_repo_head_hexsha": "83167ac6220e69887c03b556f1a7ffc518cbb227", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-25T13:41:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T13:41:19.000Z", "max_issues_repo_path": "src/epecur/track.cpp", "max_issues_repo_name": "veprbl/libepecur", "max_issues_repo_head_hexsha": "83167ac6220e69887c03b556f1a7ffc518cbb227", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/epecur/track.cpp", "max_forks_repo_name": "veprbl/libepecur", "max_forks_repo_head_hexsha": "83167ac6220e69887c03b556f1a7ffc518cbb227", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2390438247, "max_line_length": 157, "alphanum_fraction": 0.6707273379, "num_tokens": 1689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4053503900062879}}
{"text": "#include <iostream>\n#include <fstream>\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include \"headers/util.h\"\n#include \"headers/rmat.h\"\n#include \"headers/matutil.h\"\n#include \"headers/matrix_wrapper.h\"\n#include \"headers/timer.h\"\n\nusing namespace std;\nusing namespace boost::numeric::ublas;\n\nint main(int argc, char** argv) {\n  uint64_t n = atol(argv[1]);\n  uint64_t m = atol(argv[2]);\n\n  RmatConfig cfg(0.57, 0.19, 0.19);\n  CustomMatrix *mat = new CustomMatrix(n);\n  timer t;\n  t.start();\n  rmat<CustomMatrix>(mat, m, cfg);\n  t.stop();\n  cout << \"Took: \" << t.get_total() << endl;\n\n  // timer t;\n  // t.start();\n  // list<Edge> l = listRmat(n, m, cfg);\n  // t.stop();\n  // cout << \"Took: \" << t.get_total() << endl;\n\n  // fs.open(\"data/gen-32bit_uniform.csv\", ios::trunc);\n  // MatrixWrapper<CustomMatrix> *w = new MatrixWrapper<CustomMatrix>(1024, 1024, 0, true);\n  // ofstream fs;\n  // timer t;\n\n  // RmatConfig cfg;\n  // cout << \"Starting now\" << endl;\n\n  // rmat<MatrixWrapper<CompAdjMat>>(w, 50000, cfg);\n  // rmatSeq<AdjMatrix>(w, 25571, cfg);\n  // rmat<CustomMatrix>(x, 5000, cfg);\n  // rmatSeq<CustomMatrix>(x, 5000, cfg);\n  // cout << \"Finished generating graph, writing to file...\" << endl;\n  // will::matutil::writeAdjMatrix(*w, fs);\n  // will::matutil::writeAdjMatrix(*x, fs);\n  // cout << \"Done!\" << endl;\n\n  // {\n  //   timer t;\n  //   MatrixWrapper<AdjMatrix> *w = new MatrixWrapper<AdjMatrix>(50000, 50000);\n  //   RmatConfig cfg(0.57, 0.19, 0.19);\n  //   t.start();\n  //   rmatSeq<AdjMatrix>(w, 505571000, cfg);\n  //   t.stop();\n  //   cout << w->getMat() << endl;\n  //   cout << \"Took: \" << t.get_total() << endl;\n  // }\n\n  // {\n  //   timer t;\n  //   RmatConfig cfg(0.57, 0.19, 0.19);\n  //   t.start();\n  //   std::list<Edge> res = listRmat(30000, 50557100, cfg);\n  //   t.stop();\n  //   cout << res.size() << endl;\n  //   cout << \"Took: \" << t.get_total() << endl;\n  // }\n\n\n  // will::matutil::writeAdjMatrix(*w, std::cout);\n  // std::cout << m << std::endl;\n  // MatrixWrapper<CompAdjMat> w(10, 10);\n  // w.insert(3, 3, 9);\n  // w.set(1, 1, 9);\n  // cout << static_cast<int>(w.get(3, 3)) << endl;\n  // m = w.getMat();\n  // will::matutil::writeAdjMatrix(*m, std::cout);\n}\n", "meta": {"hexsha": "58f5cd1ceebaab401e0a612ae898b21da85e2e95", "size": 2227, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test.cpp", "max_stars_repo_name": "willshiao/cs260-rmat", "max_stars_repo_head_hexsha": "d7103e0a643976ce1553b9e674468c1d40fbaf72", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-16T21:08:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-16T21:11:04.000Z", "max_issues_repo_path": "src/test.cpp", "max_issues_repo_name": "willshiao/cs260-rmat", "max_issues_repo_head_hexsha": "d7103e0a643976ce1553b9e674468c1d40fbaf72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test.cpp", "max_forks_repo_name": "willshiao/cs260-rmat", "max_forks_repo_head_hexsha": "d7103e0a643976ce1553b9e674468c1d40fbaf72", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4938271605, "max_line_length": 91, "alphanum_fraction": 0.5823978446, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300048, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.40535039000628786}}
{"text": "#include <iostream>\n#include <cassert>\n#include <vector>\n#include <iomanip>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> GraphTraits;\ntypedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,\n                              boost::property<boost::edge_capacity_t, long,\n                                              boost::property<boost::edge_residual_capacity_t, long,\n                                                              boost::property<boost::edge_reverse_t, GraphTraits::edge_descriptor,\n                                                                              boost::property<boost::edge_weight_t, long>>>>>\n    Graph;\n\nconst int debug_level = 0;\n\n#define DEBUG(min_level, x)      \\\n  if (debug_level >= min_level)  \\\n  {                              \\\n    std::cerr << x << std::endl; \\\n  }\n\nstruct Booking\n{\n  int s, t, d, a, p;\n};\n\nconst int max_possible_profit = 100;\n\nclass TimeIndexer\n{\npublic:\n  void add_time(int t)\n  {\n    time_set.insert(t);\n  }\n\n  void rebuild()\n  {\n    time_vector.resize(time_set.size());\n    std::copy(time_set.begin(), time_set.end(), time_vector.begin());\n  }\n\n  int time_to_index(int t) const\n  {\n    const auto it = std::lower_bound(time_vector.begin(), time_vector.end(), t);\n    assert(it != time_vector.end() && *it == t);\n    return it - time_vector.begin();\n  }\n\n  int index_to_time(int i) const\n  {\n    return time_vector.at(i);\n  }\n\n  int size() const\n  {\n    return time_set.size();\n  }\n\nprivate:\n  std::set<int> time_set;\n  std::vector<int> time_vector;\n};\n\nvoid testcase()\n{\n  int n, s;\n  std::cin >> n >> s;\n  assert(n >= 1 && n <= 10000 && s >= 2 && s <= 10);\n\n  int total_cars = 0;\n  std::vector<int> initial_cars_by_station(s);\n  for (int &l : initial_cars_by_station)\n  {\n    std::cin >> l;\n    assert(l >= 0 && l <= 100);\n    total_cars += l;\n  }\n\n  std::vector<Booking> bookings(n);\n  for (Booking &b : bookings)\n  {\n    std::cin >> b.s >> b.t >> b.d >> b.a >> b.p;\n    assert(b.s >= 1 && b.s <= s && b.t >= 1 && b.t <= s);\n    b.s--;\n    b.t--;\n    assert(b.d >= 0 && b.d < b.a && b.a <= 100000);\n    assert(b.p >= 1 && b.p <= max_possible_profit);\n  }\n\n  TimeIndexer global_time_indexer;\n  std::vector<TimeIndexer> local_time_indexers(s);\n  for (Booking &b : bookings)\n  {\n    global_time_indexer.add_time(b.d);\n    global_time_indexer.add_time(b.a);\n    local_time_indexers.at(b.s).add_time(b.d);\n    local_time_indexers.at(b.t).add_time(b.a);\n  }\n\n  global_time_indexer.rebuild();\n  for (TimeIndexer &local_time_indexer : local_time_indexers)\n  {\n    // IMPORTANT The first and last global time must exist at every station, otherwise\n    // the max_possible_profit * global_time_slot_delta compensation won't work correctly\n    local_time_indexer.add_time(global_time_indexer.index_to_time(0));\n    local_time_indexer.add_time(global_time_indexer.index_to_time(global_time_indexer.size() - 1));\n\n    local_time_indexer.rebuild();\n  }\n\n  std::vector<int> local_time_slot_cumulative_sum{0};\n  for (int i = 0; i < s; i++)\n  {\n    local_time_slot_cumulative_sum.push_back(local_time_slot_cumulative_sum.back() + local_time_indexers.at(i).size());\n  }\n\n  int next_free_node = 0;\n  const int node_source = next_free_node++;\n  const int node_target = next_free_node++;\n  const auto get_station_time_node = [next_free_node, s, &local_time_indexers, &local_time_slot_cumulative_sum](const int i_time, const int i_station) {\n    assert(i_station >= 0 && i_station < s && i_time >= 0 && i_time < local_time_indexers.at(i_station).size());\n    return next_free_node + local_time_slot_cumulative_sum.at(i_station) + i_time;\n  };\n  next_free_node += local_time_slot_cumulative_sum.back();\n  const auto get_trip_node = [next_free_node, n](const int i_trip) {\n    assert(i_trip >= 0 && i_trip < n);\n    return next_free_node + i_trip;\n  };\n  next_free_node += n;\n  const int num_nodes = next_free_node;\n  Graph G(num_nodes);\n\n  const auto add_edge = [&G](int from, int to, long capacity, long cost) {\n    auto c_map = boost::get(boost::edge_capacity, G);\n    auto r_map = boost::get(boost::edge_reverse, G);\n    auto w_map = boost::get(boost::edge_weight, G);\n    const Graph::edge_descriptor e = boost::add_edge(from, to, G).first;\n    const Graph::edge_descriptor rev_e = boost::add_edge(to, from, G).first;\n    c_map[e] = capacity;\n    c_map[rev_e] = 0;\n    r_map[e] = rev_e;\n    r_map[rev_e] = e;\n    w_map[e] = cost;\n    w_map[rev_e] = -cost;\n  };\n\n  for (int i_station = 0; i_station < s; i_station++)\n  {\n    const TimeIndexer &local_time_indexer = local_time_indexers.at(i_station);\n\n    add_edge(node_source, get_station_time_node(0, i_station), initial_cars_by_station.at(i_station), 0);\n    add_edge(get_station_time_node(local_time_indexer.size() - 1, i_station), node_target, total_cars, 0);\n\n    for (int i_time = 1; i_time < local_time_indexer.size(); i_time++)\n    {\n      const int global_time_slot_delta = global_time_indexer.time_to_index(local_time_indexer.index_to_time(i_time)) - global_time_indexer.time_to_index(local_time_indexer.index_to_time(i_time - 1));\n      assert(global_time_slot_delta > 0);\n      add_edge(get_station_time_node(i_time - 1, i_station), get_station_time_node(i_time, i_station), total_cars, global_time_slot_delta * max_possible_profit);\n    }\n  }\n\n  for (int i_trip = 0; i_trip < n; i_trip++)\n  {\n    Booking &b = bookings.at(i_trip);\n    const int i_d = local_time_indexers.at(b.s).time_to_index(b.d), i_a = local_time_indexers.at(b.t).time_to_index(b.a);\n    const int global_time_slot_delta = global_time_indexer.time_to_index(b.a) - global_time_indexer.time_to_index(b.d);\n    assert(global_time_slot_delta > 0);\n    add_edge(get_station_time_node(i_d, b.s), get_trip_node(i_trip), 1, max_possible_profit * global_time_slot_delta - b.p);\n    add_edge(get_trip_node(i_trip), get_station_time_node(i_a, b.t), 1, 0);\n  }\n\n  boost::successive_shortest_path_nonnegative_weights(G, node_source, node_target);\n  const int flow_cost = boost::find_flow_cost(G);\n  const int total_profit = total_cars * (global_time_indexer.size() - 1) * max_possible_profit - flow_cost;\n  std::cout << total_profit << \"\\n\";\n}\n\nint main()\n{\n  std::ios_base::sync_with_stdio(false);\n  std::cout << std::fixed << std::setprecision(0);\n\n  int t;\n  std::cin >> t;\n  for (int i = 0; i < t; i++)\n  {\n    testcase();\n    DEBUG(1, \"\");\n  }\n\n  return 0;\n}", "meta": {"hexsha": "8b93e3495f8e41f1a9a9d24ff5a8bfb849e5962e", "size": 6560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "week-12/car-sharing/src/main.cpp", "max_stars_repo_name": "tehwalris/algolab", "max_stars_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T08:21:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T08:21:32.000Z", "max_issues_repo_path": "week-12/car-sharing/src/main.cpp", "max_issues_repo_name": "tehwalris/algolab", "max_issues_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "week-12/car-sharing/src/main.cpp", "max_forks_repo_name": "tehwalris/algolab", "max_forks_repo_head_hexsha": "489e0f6dd137336fa32b8002fc6eed8a7d35d87a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4693877551, "max_line_length": 199, "alphanum_fraction": 0.662804878, "num_tokens": 1784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585669110202, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.40535038350845704}}
{"text": "\n#include <deal.II/base/function.h>\n#include <deal.II/base/function_parser.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/base/table_handler.h>\n\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/petsc_parallel_sparse_matrix.h>\n#include <deal.II/lac/petsc_parallel_vector.h>\n#include <deal.II/lac/petsc_solver.h>\n#include <deal.II/lac/petsc_precondition.h>\n#include <deal.II/lac/sparsity_tools.h>\n#include <deal.II/lac/vector.h>\n\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n#include <deal.II/distributed/grid_refinement.h>\n#include <deal.II/distributed/tria.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_system.h>\n#include <deal.II/fe/fe_q.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <mandy/elastic_tensor.h>\n#include <mandy/lattice_tensor.h>\n#include <mandy/matrix_creator.h>\n#include <mandy/vector_creator.h>\n\n#include <mandy/crystal_symmetry_group.h>\n\n#include <fstream>\n#include <iostream>\n\n#include <algorithm>    // std::transform\n#include <functional>   // std::plus\n\nnamespace mandy\n{\n\n  /**\n   * Solve the system Mx=b, where M is the mass matrix and b is a\n   * linear function.\n   */\n  template <int dim>\n  class MaterialID\n  {\n  public:\n\n    /**\n     * Class constructor.\n     */\n    MaterialID (const std::string &prm);\n\n    /**\n     * Class destructor.\n     */\n    ~MaterialID ();\n\n    /**\n     * Wrapper function, that controls the order of excecution.\n     */\n    void run ();\n    \n  private:\n\n    /**\n     * Make intial coarse grid.\n     */\n    void make_coarse_grid ();\n\n    /**\n     * Setup system matrices and vectors.\n     */\n    void setup_system ();\n\n    /**\n     * Assemble system matrices and vectors.\n     */\n    void assemble_system();\n\n    /**\n     * Solve the linear algebra system.\n     */\n    unsigned int solve ();\n    \n    /**\n     * Output results, ie., finite element functions and derived\n     * quantitites for this cycle.\n     */\n    void output_results (const unsigned int cycle);\n\n    /**\n     * Refine grid based on Kelly's error estimator working on the\n     * material id (solution vector).\n     */\n    void refine_grid ();\n    \n    /**\n     * MPI communicator.\n     */\n    MPI_Comm mpi_communicator;\n\n    /**\n     * A distributed grid on which all computations are done.\n     */\n    dealii::parallel::distributed::Triangulation<dim> triangulation;\n\n    /**\n     * Scalar DoF handler primarily used for interpolating material\n     * identification.\n     */\n    dealii::DoFHandler<dim> dof_handler;\n\n    /**\n     * Scalar valued finite element primarily used for interpolating\n     * material iudentification.\n     */\n    dealii::FESystem<dim> fe;\n    \n    /**\n     * Index set of locally owned DoFs.\n     */\n    dealii::IndexSet locally_owned_dofs;\n    \n    /**\n     * Index set of locally relevant DoFs.\n     */\n    dealii::IndexSet locally_relevant_dofs;\n    \n    /**\n     * A list of (hanging node) constraints.\n     */\n    dealii::ConstraintMatrix constraints;\n    \n    /**\n     * System matrix - a mass matrix.\n     */\n    dealii::PETScWrappers::MPI::SparseMatrix system_matrix;\n\n    /**\n     * Locally relevant solution vector.\n     */\n    dealii::PETScWrappers::MPI::Vector locally_relevant_solution;\n\n    /**\n     * System right hand side function - interpolated function.\n     */\n    dealii::PETScWrappers::MPI::Vector system_rhs;\n    \n    /**\n     * Parallel iostream.\n     */\n    dealii::ConditionalOStream pcout;\n\n    /**\n     * Stop clock.\n     */\n    dealii::TimerOutput timer;\n    \n    /**\n     * Input parameter file.\n     */\n    dealii::ParameterHandler parameters;\n    \n  }; // MaterialID\n\n  \n  /**\n   * Class constructor.\n   */\n  template <int dim>\n  MaterialID<dim>::MaterialID (const std::string &prm)\n    :\n    mpi_communicator (MPI_COMM_WORLD),\n    triangulation (mpi_communicator,\n                   typename dealii::Triangulation<dim>::MeshSmoothing\n                   (dealii::Triangulation<dim>::smoothing_on_refinement |\n                    dealii::Triangulation<dim>::smoothing_on_coarsening)),\n    dof_handler (triangulation),\n    fe (dealii::FE_Q<dim> (2), 1),\n    // ---\n    pcout (std::cout, (dealii::Utilities::MPI::this_mpi_process (mpi_communicator) == 0)),\n    timer (mpi_communicator, pcout,\n\t   dealii::TimerOutput::summary,\n\t   dealii::TimerOutput::wall_times)\n  {\n    parameters.declare_entry (\"Global mesh refinement steps\", \"5\",\n                              dealii::Patterns::Integer (0, 20),\n                              \"The number of times the 1-cell coarse mesh should \"\n                              \"be refined globally for our computations.\");\n\n    parameters.declare_entry (\"MaterialID\", \"0\",\n                              dealii::Patterns::Anything (),\n                              \"A functional description of the material ID.\");\n    \n    parameters.parse_input (prm);\n  }\n\n  \n  /**\n   * Class destructor.\n   */\n  template <int dim>\n  MaterialID<dim>::~MaterialID ()\n  {\n    // Wipe DoF handlers.\n    dof_handler.clear ();\n  }\n\n\n  /**\n   * Make initial coarse grid.\n   */\n  template <int dim>\n  void\n  MaterialID<dim>::make_coarse_grid ()\n  {\n    dealii::TimerOutput::Scope time (timer, \"make coarse grid\");\n\n    // Create a coarse grid according to the parameters given in the\n    // input file.\n    dealii::GridGenerator::hyper_cube (triangulation, -10, 10);\n    \n    triangulation.refine_global (parameters.get_integer (\"Global mesh refinement steps\"));\n  }\n\n\n  /**\n   * Setup system matrices and vectors.\n   */\n  template <int dim>\n  void MaterialID<dim>::setup_system ()\n  {\n    dealii::TimerOutput::Scope time (timer, \"setup system\");\n\n    // Determine locally relevant DoFs.\n    dof_handler.distribute_dofs (fe);\n    locally_owned_dofs = dof_handler.locally_owned_dofs ();\n    dealii::DoFTools::extract_locally_relevant_dofs (dof_handler, locally_relevant_dofs);\n\n    // Initialise distributed vectors.\n    locally_relevant_solution.reinit (locally_owned_dofs, locally_relevant_dofs,\n\t\t\t\t      mpi_communicator);\n    system_rhs.reinit (locally_owned_dofs,\n\t\t       mpi_communicator);\n\n    // Setup hanging node constraints.\n    constraints.clear ();\n    constraints.reinit (locally_relevant_dofs);\n    dealii::DoFTools::make_hanging_node_constraints (dof_handler, constraints);\n    constraints.close ();\n\n    // Finally, create a distributed sparsity pattern and initialise\n    // the system matrix from that.\n    dealii::DynamicSparsityPattern dsp (locally_relevant_dofs);\n    dealii::DoFTools::make_sparsity_pattern (dof_handler, dsp, constraints, false);\n    dealii::SparsityTools::distribute_sparsity_pattern (dsp,\n\t\t\t\t\t\t\tdof_handler.n_locally_owned_dofs_per_processor (),\n\t\t\t\t\t\t\tmpi_communicator,\n\t\t\t\t\t\t\tlocally_relevant_dofs);\n\n    system_matrix.reinit (locally_owned_dofs, locally_owned_dofs,\n                          dsp, mpi_communicator);\n\n  }\n\n\n  /**\n   * Assemble system matrices and vectors.\n   *\n   * TODO Ideally, we would use a function like this:\n   *\n   * dealii::MatrixCreator::create_mass_matrix (dof_handler, quadrature_rule, system_matrix, 1, constraints);\n   *\n   * however no such thing currently exists in the deal.II library for\n   * parallel matrices and vectors. Instead, the mass matrix and right\n   * hand side vector are assembled by hand in functions defined in\n   * the namepsaces, mandy::MatrixCreator and mandy::VectorCreator,\n   * respectively.\n   */\n  template <int dim>\n  void\n  MaterialID<dim>::assemble_system ()\n  {\n    dealii::TimerOutput::Scope time (timer, \"assemble system\");\n\n    // Define quadrature rule to be used.\n    const dealii::QGauss<dim> quadrature_formula (3);\n\n    // Initialise the function parser.\n    dealii::FunctionParser<dim> material_identification;\n    material_identification.initialize (dealii::FunctionParser<dim>::default_variable_names (),\n\t\t\t\t\tparameters.get (\"MaterialID\"),\n\t\t\t\t\ttypename dealii::FunctionParser<dim>::ConstMap ());\n    \n    mandy::MatrixCreator::create_mass_matrix<dim> (fe, dof_handler, quadrature_formula,\n\t\t\t\t\t\t   system_matrix, constraints,\n\t\t\t\t\t\t   mpi_communicator);\n\n    mandy::VectorCreator::create_right_hand_side_vector<dim> (fe, dof_handler, quadrature_formula,\n     \t\t\t\t\t\t\t      system_rhs, constraints,\n\t\t\t\t\t\t\t      material_identification,\n\t\t\t\t\t\t\t      mpi_communicator);\n  }\n  \n\n  /**\n   * Solve the linear algebra system.\n   */\n  template <int dim>\n  unsigned int\n  MaterialID<dim>::solve ()\n  {\n    dealii::TimerOutput::Scope time (timer, \"solve\");\n    \n    dealii::PETScWrappers::MPI::Vector completely_distributed_solution (locally_owned_dofs, mpi_communicator);\n\n    // Solve using conjugate gradient method with no preconditioner\n    // (ie., system_matrix is ignored).\n    dealii::SolverControl solver_control (dof_handler.n_dofs (), 1e-06);\n    dealii::PETScWrappers::SolverCG solver (solver_control, mpi_communicator);\n    dealii::PETScWrappers::PreconditionNone preconditioner (system_matrix);\n    \n    solver.solve (system_matrix, completely_distributed_solution, system_rhs,\n\t\t  preconditioner);\n    \n    // Ensure that all ghost elements are also copied as necessary.\n    constraints.distribute (completely_distributed_solution);\n    locally_relevant_solution = completely_distributed_solution;\n\n    // Return the number of iterations (last step) of the solve.\n    return solver_control.last_step ();\n  }\n\n\n  /**\n   * Output results, ie., finite element functions and derived\n   * quantitites for this cycle..\n   */\n  template <int dim>\n  void\n  MaterialID<dim>::output_results (const unsigned int cycle)\n  {\n    dealii::TimerOutput::Scope time (timer, \"output_results\");\n\n    dealii::DataOut<dim> data_out;\n    data_out.attach_dof_handler (dof_handler);\n    data_out.add_data_vector (locally_relevant_solution, \"material_id\");\n\n    dealii::Vector<float> subdomain (triangulation.n_active_cells ());\n    for (unsigned int i=0; i<subdomain.size(); ++i)\n      subdomain (i) = triangulation.locally_owned_subdomain ();\n    data_out.add_data_vector (subdomain, \"subdomain\");\n\n    data_out.build_patches ();\n    \n    const std::string filename = (\"material_id-\" +\n                                  dealii::Utilities::int_to_string (cycle, 2) +\n                                  \".\" +\n                                  dealii::Utilities::int_to_string\n                                  (triangulation.locally_owned_subdomain (), 4));\n\n    std::ofstream output ((filename + \".vtu\").c_str ());\n    data_out.write_vtu (output);\n\n    if (dealii::Utilities::MPI::this_mpi_process(mpi_communicator) == 1)\n      {\n\tstd::vector<std::string> filenames;\n\t\n\tfor (unsigned int i=0;\n\t     i<dealii::Utilities::MPI::n_mpi_processes (mpi_communicator);\n\t     ++i)\n\t  filenames.push_back (\"material_id-\" +\n\t\t\t       dealii::Utilities::int_to_string (cycle, 2) +\n\t\t\t       \".\" +\n\t\t\t       dealii::Utilities::int_to_string (i, 4) +\n\t\t\t       \".vtu\");\n\tstd::ofstream master_output ((\"material_id-\" +\n\t\t\t\t      dealii::Utilities::int_to_string (cycle, 2) +\n\t\t\t\t      \".pvtu\").c_str ());\n\n\tdata_out.write_pvtu_record (master_output, filenames);\n      }\n  }\n\n\n  /**\n   * Refine grid based on Kelly's error estimator working on the\n   * material id (solution vector).\n   */\n  template <int dim>\n  void MaterialID<dim>::refine_grid ()\n  {\n    dealii::TimerOutput::Scope time (timer, \"refine grid\");\n\n    dealii::Vector<float> estimated_error_per_cell (triangulation.n_active_cells());\n    \n    dealii::KellyErrorEstimator<dim>::estimate (dof_handler, dealii::QGauss<dim-1>(4),\n\t\t\t\t\t\ttypename dealii::FunctionMap<dim>::type (),\n\t\t\t\t\t\tlocally_relevant_solution,\n\t\t\t\t\t\testimated_error_per_cell);\n\n    dealii::parallel::distributed::GridRefinement::\n      refine_and_coarsen_fixed_number (triangulation,\n\t\t\t\t       estimated_error_per_cell,\n\t\t\t\t       0.250, 0.025);\n\n    triangulation.execute_coarsening_and_refinement ();\n  }\n  \n  \n  /**\n   * Run the application in the order specified.\n   */\n  template <int dim>\n  void\n  MaterialID<dim>::run ()\n  {\n    const unsigned int n_cycles = 5;\n    \n    for (unsigned int cycle=0; cycle<n_cycles; ++cycle)\n      {\n        pcout << \"MaterialID:: Cycle \" << cycle << ':'\n\t      << std::endl;\n\n\tif (cycle==0)\n\t  make_coarse_grid ();\n\n\telse\n\t  refine_grid ();\n\t\n\tpcout << \"   Number of active cells:       \"\n\t      << triangulation.n_global_active_cells ()\n\t      << std::endl;\n\n\tsetup_system ();\n\n\tpcout << \"   Number of degrees of freedom: \"\n\t      << dof_handler.n_dofs ()\n\t      << std::endl;\n\t\n\tassemble_system ();\n\n\tconst unsigned int n_iterations = solve ();\n\n\tpcout << \"   Solved in \" << n_iterations\n\t      << \" iterations.\"\n\t      << std::endl;\n\n\tpcout << \"   Linfty-norm:                  \"\n\t      << locally_relevant_solution.linfty_norm ()\n\t      << std::endl;\n\n\t// Output results if the number of processes is less than or\n\t// equal to 32.\n\tif (dealii::Utilities::MPI::n_mpi_processes (mpi_communicator) <= 32)\n\t  output_results (cycle);\n\n\t// timer.print_summary ();\n        pcout << std::endl;\n\t\n      } // for cycle<n_cycles\n  } \n  \n} // namespace mandy\n\n\n/**\n * Main function: Initialise problem and run it.\n */\nint main (int argc, char *argv[])\n{\n  // Initialise MPI\n  dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);\n  \n  try\n    {\n      mandy::MaterialID<3> material_id (\"step-0-material.prm\");\n      material_id.run ();\n    }\n\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "2a4e1d973527b92f9fbe51ab3ce6680761b116d2", "size": 14752, "ext": "cc", "lang": "C++", "max_stars_repo_path": "archive/step-0-material.cc", "max_stars_repo_name": "oneliefleft/mandy", "max_stars_repo_head_hexsha": "e791f7defbf3f13a63769ad7231ddd32dcfd1a32", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "archive/step-0-material.cc", "max_issues_repo_name": "oneliefleft/mandy", "max_issues_repo_head_hexsha": "e791f7defbf3f13a63769ad7231ddd32dcfd1a32", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-02-24T13:55:50.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-24T14:00:20.000Z", "max_forks_repo_path": "archive/step-0-material.cc", "max_forks_repo_name": "oneliefleft/mandy", "max_forks_repo_head_hexsha": "e791f7defbf3f13a63769ad7231ddd32dcfd1a32", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8865784499, "max_line_length": 110, "alphanum_fraction": 0.630829718, "num_tokens": 3566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.40532215900269014}}
{"text": "#include \"mpi_fsi.h\"\n#include \"mpi_scnsim.h\"\n#include \"mpi_shared_hypo_elasticity.h\"\n#include \"parameters.h\"\n#include \"utilities.h\"\n#include <deal.II/grid/grid_in.h>\n#include <deal.II/grid/grid_out.h>\n\nextern template class Fluid::MPI::SCnsIM<2>;\nextern template class Solid::MPI::SharedHypoElasticity<2>;\nextern template class MPI::FSI<2>;\n\nusing namespace dealii;\n\ntemplate <int dim>\nclass SigmaPMLField : public Function<dim>\n{\npublic:\n  SigmaPMLField(double sig, double l)\n    : Function<dim>(), SigmaPMLMax(sig), PMLLength(l)\n  {\n  }\n  virtual double value(const Point<dim> &p,\n                       const unsigned int component = 0) const;\n  virtual void value_list(const std::vector<Point<dim>> &points,\n                          std::vector<double> &values,\n                          const unsigned int component = 0) const;\n\nprivate:\n  double SigmaPMLMax;\n  double PMLLength;\n};\n\ntemplate <int dim>\nclass ArtificialBF : public TensorFunction<1, dim>\n{\npublic:\n  ArtificialBF() : TensorFunction<1, dim>() {}\n  virtual Tensor<1, dim> value(const Point<dim> &p) const;\n  virtual void value_list(const std::vector<Point<dim>> &points,\n                          std::vector<Tensor<1, dim>> &values) const;\n};\n\ntemplate <int dim>\ndouble SigmaPMLField<dim>::value(const Point<dim> &p,\n                                 const unsigned int component) const\n{\n  (void)component;\n  (void)p;\n  double SigmaPML = 0.0;\n  double boundary = 0.0;\n  // For tube acoustics\n  if (p[0] < PMLLength + boundary)\n    // A quadratic increasing function from boundary-PMLlength to the boundary\n    SigmaPML = SigmaPMLMax * pow((PMLLength + boundary - p[0]) / PMLLength, 4);\n  return SigmaPML;\n}\n\ntemplate <int dim>\nvoid SigmaPMLField<dim>::value_list(const std::vector<Point<dim>> &points,\n                                    std::vector<double> &values,\n                                    const unsigned int component) const\n{\n  (void)component;\n  for (unsigned int i = 0; i < points.size(); ++i)\n    values[i] = this->value(points[i]);\n}\n\ntemplate <int dim>\nTensor<1, dim> ArtificialBF<dim>::value(const Point<dim> &p) const\n{\n  Tensor<1, dim> value;\n  double rho = 1.3e-3;\n  double bf = 1.0e4 / rho;\n  if (p[0] > 1.0 - 5e-4 && p[0] < 2.0 + 5e-4)\n    value[0] = bf;\n  return value;\n}\n\ntemplate <int dim>\nvoid ArtificialBF<dim>::value_list(const std::vector<Point<dim>> &points,\n                                   std::vector<Tensor<1, dim>> &values) const\n{\n  for (unsigned int i = 0; i < points.size(); ++i)\n    values[i] = this->value(points[i]);\n}\n\nint main(int argc, char *argv[])\n{\n  using namespace dealii;\n\n  double PMLlength = 1.0, SigmaMax = 340000;\n\n  try\n    {\n      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n\n      std::string infile(\"parameters.prm\");\n      if (argc > 1)\n        {\n          infile = argv[1];\n        }\n      Parameters::AllParameters params(infile);\n\n      if (params.dimension == 2)\n        {\n          // Read solid mesh\n          Triangulation<2> tria_solid;\n          dealii::GridGenerator::subdivided_hyper_rectangle(\n            tria_solid,\n            {static_cast<unsigned int>(10), static_cast<unsigned int>(40)},\n            Point<2>(0, 0),\n            Point<2>(0.5, 2),\n            true);\n\n          // Read fluid mesh\n          parallel::distributed::Triangulation<2> tria_fluid(MPI_COMM_WORLD);\n          dealii::GridGenerator::subdivided_hyper_rectangle(\n            tria_fluid,\n            {static_cast<unsigned int>(114), static_cast<unsigned int>(29)},\n            Point<2>(0, 0),\n            Point<2>(5, 2),\n            true);\n\n          // Translate solid mesh\n          Tensor<1, 2> offset({2, 0});\n          GridTools::shift(offset, tria_solid);\n\n          // placeholder for hard code BC\n          std::shared_ptr<Functions::ZeroFunction<2>> ptr =\n            std::make_shared<Functions::ZeroFunction<2>>(\n              Functions::ZeroFunction<2>(3));\n          // initialize the pml field\n          auto pml = std::make_shared<SigmaPMLField<2>>(\n            SigmaPMLField<2>(SigmaMax, PMLlength));\n          // artificial body force\n          auto bf_ptr = std::make_shared<ArtificialBF<2>>(ArtificialBF<2>());\n\n          Fluid::MPI::SCnsIM<2> fluid(tria_fluid,\n                                      params); //, ptr, pml, bf_ptr);\n          Solid::MPI::SharedHypoElasticity<2> solid(\n            tria_solid, params, 0.05, 1.3);\n          MPI::FSI<2> fsi(fluid, solid, params);\n          fsi.run();\n        }\n      else\n        {\n          AssertThrow(false, ExcNotImplemented());\n        }\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl\n                << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl\n                << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n  return 0;\n}\n", "meta": {"hexsha": "a00c9acb0c2f65c54c2e6d62e2a72a7aeae2ac2f", "size": 5453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/fsi-rkpm-rk4/fsi-rkpm-rk4.cpp", "max_stars_repo_name": "yufeimi/OpenIFEM", "max_stars_repo_head_hexsha": "51cdd1633e41a3f5a3175e216c8584da43f3dc76", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2019-04-08T15:24:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T16:52:32.000Z", "max_issues_repo_path": "tests/fsi-rkpm-rk4/fsi-rkpm-rk4.cpp", "max_issues_repo_name": "chenjiatu/OpenIFEM", "max_issues_repo_head_hexsha": "dc0e0081e08827d8f20a3744683ac31ff9e78a55", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2018-05-10T14:42:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T18:41:54.000Z", "max_forks_repo_path": "tests/fsi-rkpm-rk4/fsi-rkpm-rk4.cpp", "max_forks_repo_name": "chenjiatu/OpenIFEM", "max_forks_repo_head_hexsha": "dc0e0081e08827d8f20a3744683ac31ff9e78a55", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2018-04-16T01:40:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-13T05:55:15.000Z", "avg_line_length": 30.6348314607, "max_line_length": 79, "alphanum_fraction": 0.5347515129, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.40532215900269003}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TOOLBOX_HYPERBOLIC_FUNCTIONS_SIMD_COMMON_SINHCOSH_HPP_INCLUDED\n#define NT2_TOOLBOX_HYPERBOLIC_FUNCTIONS_SIMD_COMMON_SINHCOSH_HPP_INCLUDED\n\n#include <nt2/toolbox/hyperbolic/functions/sinhcosh.hpp>\n#include <nt2/include/functions/simd/tofloat.hpp>\n#include <nt2/include/functions/simd/abs.hpp>\n#include <nt2/include/functions/simd/expm1.hpp>\n#include <nt2/include/functions/simd/if_else.hpp>\n#include <nt2/include/functions/simd/negif.hpp>\n#include <nt2/include/functions/simd/is_equal.hpp>\n#include <nt2/include/functions/simd/oneplus.hpp>\n#include <nt2/include/functions/simd/is_negative.hpp>\n#include <nt2/include/functions/simd/divides.hpp>\n#include <nt2/include/functions/simd/multiplies.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/half.hpp>\n#include <nt2/sdk/meta/as_logical.hpp>\n#include <nt2/sdk/meta/cardinal_of.hpp>\n#include <boost/fusion/tuple.hpp>\n\nnamespace nt2 { namespace ext\n{\n  NT2_FUNCTOR_IMPLEMENTATION_IF(  nt2::tag::sinhcosh_, tag::cpu_,(A0)(A1)(X)\n                                  , (boost::mpl::equal_to < nt2::meta::cardinal_of<A0>\n                                                        , nt2::meta::cardinal_of<A1>\n                                                        >\n                                )\n                               , ((simd_<arithmetic_<A0>,X>))\n                                 ((simd_<floating_<A1>,X>))\n                                 ((simd_<floating_<A1>,X>))\n                             )\n  {\n    typedef int result_type;\n    inline result_type operator()(A0 const& a0,A1 & a1,A1 & a2) const\n    {\n      typedef typename meta::as_logical<A1>::type ltype;\n      A1 a00 =  nt2::abs(a0);\n      ltype test =  eq(a00, Inf<A1>());\n      const A1 u = nt2::expm1(a00);\n      const A1 up1 = oneplus(u);\n      const A1 tmp =u/up1;\n      a1 = negif(is_negative(a0), if_else(test, a00, Half<A1>()*tmp*(oneplus(up1))));\n      a2 = if_else(test, a00, oneplus(Half<A1>()*tmp*u));\n      return 0;\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION_IF(nt2::tag::sinhcosh_, tag::cpu_,(A0)(A1)(X),\n                                (boost::mpl::equal_to<nt2::meta::cardinal_of<A0>,\n                                                 nt2::meta::cardinal_of<A1>\n                                        >\n                                ),\n                                ((simd_ < arithmetic_<A0>,X > ))\n                                ((simd_ < floating_<A1>,X > ))\n                             )\n  {\n    typedef A1 result_type;\n    inline result_type operator()(A0 const& a0,A1 & a2) const\n    {\n      A1 a1;\n      sinhcosh(tofloat(a0),a1, a2);\n      return a1;\n    }\n  };\n\n  NT2_FUNCTOR_IMPLEMENTATION(nt2::tag::sinhcosh_, tag::cpu_,\n                         (A0)(X),\n                         ((simd_<arithmetic_<A0>,X>))\n                        )\n  {\n      typedef typename meta::as_floating<A0>::type  rtype;\n      typedef boost::fusion::tuple<rtype, rtype> result_type;\n\n    NT2_FUNCTOR_CALL(1)\n    {\n      result_type res;\n      boost::fusion::at_c<0>(res) = sinhcosh(tofloat(a0),\n                                              boost::fusion::at_c<1>(res));\n      return res;\n    }\n  };\n} }\n#endif\n", "meta": {"hexsha": "be9f5e9068283539da2e3ebfbb669d32a7debf7c", "size": 3675, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/hyperbolic/include/nt2/toolbox/hyperbolic/functions/simd/common/sinhcosh.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/hyperbolic/include/nt2/toolbox/hyperbolic/functions/simd/common/sinhcosh.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/hyperbolic/include/nt2/toolbox/hyperbolic/functions/simd/common/sinhcosh.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9456521739, "max_line_length": 86, "alphanum_fraction": 0.5229931973, "num_tokens": 918, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7520125626441471, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4053221530115412}}
{"text": "/* ----------------------------------------------------------------------------\n\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/*\n * @file Unit3.h\n * @date Feb 02, 2011\n * @author Can Erdogan\n * @author Frank Dellaert\n * @author Alex Trevor\n * @brief The Unit3 class - basically a point on a unit sphere\n */\n\n#include <gtsam/geometry/Unit3.h>\n#include <gtsam/geometry/Point2.h>\n#include <boost/random/mersenne_twister.hpp>\n\n#ifdef __clang__\n#  pragma clang diagnostic push\n#  pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n#include <boost/random/uniform_on_sphere.hpp>\n#ifdef __clang__\n#  pragma clang diagnostic pop\n#endif\n\n#include <boost/random/variate_generator.hpp>\n#include <iostream>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/* ************************************************************************* */\nUnit3 Unit3::FromPoint3(const Point3& point, boost::optional<Matrix&> H) {\n  Unit3 direction(point);\n  if (H) {\n    // 3*3 Derivative of representation with respect to point is 3*3:\n    Matrix D_p_point;\n    point.normalize(D_p_point); // TODO, this calculates norm a second time :-(\n    // Calculate the 2*3 Jacobian\n    H->resize(2, 3);\n    *H << direction.basis().transpose() * D_p_point;\n  }\n  return direction;\n}\n\n/* ************************************************************************* */\nUnit3 Unit3::Random(boost::mt19937 & rng) {\n  // TODO allow any engine without including all of boost :-(\n  boost::uniform_on_sphere<double> randomDirection(3);\n  // This variate_generator object is required for versions of boost somewhere\n  // around 1.46, instead of drawing directly using boost::uniform_on_sphere(rng).\n  boost::variate_generator<boost::mt19937&, boost::uniform_on_sphere<double> >\n      generator(rng, randomDirection);\n  vector<double> d = generator();\n  Unit3 result;\n  result.p_ = Point3(d[0], d[1], d[2]);\n  return result;\n}\n\n/* ************************************************************************* */\nconst Unit3::Matrix32& Unit3::basis() const {\n\n  // Return cached version if exists\n  if (B_)\n    return *B_;\n\n  // Get the axis of rotation with the minimum projected length of the point\n  Point3 axis;\n  double mx = fabs(p_.x()), my = fabs(p_.y()), mz = fabs(p_.z());\n  if ((mx <= my) && (mx <= mz))\n    axis = Point3(1.0, 0.0, 0.0);\n  else if ((my <= mx) && (my <= mz))\n    axis = Point3(0.0, 1.0, 0.0);\n  else if ((mz <= mx) && (mz <= my))\n    axis = Point3(0.0, 0.0, 1.0);\n  else\n    assert(false);\n\n  // Create the two basis vectors\n  Point3 b1 = p_.cross(axis);\n  b1 = b1 / b1.norm();\n  Point3 b2 = p_.cross(b1);\n  b2 = b2 / b2.norm();\n\n  // Create the basis matrix\n  B_.reset(Unit3::Matrix32());\n  (*B_) << b1.x(), b2.x(), b1.y(), b2.y(), b1.z(), b2.z();\n  return *B_;\n}\n\n/* ************************************************************************* */\n/// The print fuction\nvoid Unit3::print(const std::string& s) const {\n  cout << s << \":\" << p_ << endl;\n}\n\nvoid Unit3::print(std::ostream& os, const std::string& s) const {\n  os << s << \":\" << p_ << endl;\n}\n\n/* ************************************************************************* */\nMatrix Unit3::skew() const {\n  return skewSymmetric(p_.x(), p_.y(), p_.z());\n}\n\n/* ************************************************************************* */\nVector Unit3::error(const Unit3& q, boost::optional<Matrix&> H) const {\n  // 2D error is equal to B'*q, as B is 3x2 matrix and q is 3x1\n  Matrix Bt = basis().transpose();\n  Vector xi = Bt * q.p_.vector();\n  if (H)\n    *H = Bt * q.basis();\n  return xi;\n}\n\n/* ************************************************************************* */\ndouble Unit3::distance(const Unit3& q, boost::optional<Matrix&> H) const {\n  Vector xi = error(q, H);\n  double theta = xi.norm();\n  if (H)\n    *H = (xi.transpose() / theta) * (*H);\n  return theta;\n}\n\n/* ************************************************************************* */\nUnit3 Unit3::retract(const Vector& v) const {\n\n  // Get the vector form of the point and the basis matrix\n  Vector p = Point3::Logmap(p_);\n  Matrix B = basis();\n\n  // Compute the 3D xi_hat vector\n  Vector xi_hat = v(0) * B.col(0) + v(1) * B.col(1);\n\n  double xi_hat_norm = xi_hat.norm();\n\n  // Avoid nan\n  if (xi_hat_norm == 0.0) {\n    if (v.norm() == 0.0)\n      return Unit3(point3());\n    else\n      return Unit3(-point3());\n  }\n\n  Vector exp_p_xi_hat = cos(xi_hat_norm) * p\n      + sin(xi_hat_norm) * (xi_hat / xi_hat_norm);\n  return Unit3(exp_p_xi_hat);\n\n}\n\n/* ************************************************************************* */\nVector Unit3::localCoordinates(const Unit3& y) const {\n\n  Vector p = Point3::Logmap(p_);\n  Vector q = Point3::Logmap(y.p_);\n  double dot = p.dot(q);\n\n  // Check for special cases\n  if (std::abs(dot - 1.0) < 1e-16)\n    return (Vector(2) << 0, 0);\n  else if (std::abs(dot + 1.0) < 1e-16)\n    return (Vector(2) << M_PI, 0);\n  else {\n    // no special case\n    double theta = acos(dot);\n    Vector result_hat = (theta / sin(theta)) * (q - p * dot);\n    return basis().transpose() * result_hat;\n  }\n}\n/* ************************************************************************* */\n\n}\n", "meta": {"hexsha": "e7826688479da6ef8faf825cbe25f8bdcdc61c96", "size": 5366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Unit3.cpp", "max_stars_repo_name": "anpl-technion/gtsam-3.2.1-anpl", "max_stars_repo_head_hexsha": "5473e07ab523e79097a11b308952026172b9ef3c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gtsam/geometry/Unit3.cpp", "max_issues_repo_name": "anpl-technion/gtsam-3.2.1-anpl", "max_issues_repo_head_hexsha": "5473e07ab523e79097a11b308952026172b9ef3c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/geometry/Unit3.cpp", "max_forks_repo_name": "anpl-technion/gtsam-3.2.1-anpl", "max_forks_repo_head_hexsha": "5473e07ab523e79097a11b308952026172b9ef3c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4835164835, "max_line_length": 82, "alphanum_fraction": 0.5232948192, "num_tokens": 1423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.40526563120620124}}
{"text": "/*\n * Copyright 2018 James Dyer\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n *\n * This is being developed for the TANGO Project: http://tango-project.eu\n */\n\n#include <iostream>\n#include <sstream>\n#include <NTL/RR.h>\n#include <NTL/ZZ_p.h>\n#include <json/json.h>\n#include \"HE1Encrypter.h\"\n\n#include \"Random.h\"\n\nHE1Encrypter::HE1Encrypter(int lambda, int eta)\n{\n\tgenerateParameters(lambda,eta);\n}\n\nHE1Encrypter::HE1Encrypter(int n, int d, int rho)\n{\n\tNTL::RR two(2);\n\tNTL::RR exp1(rho*d);\n\tNTL::RR nplusone(n+1);\n\tNTL::RR exp2(d);\n\tNTL::RR ploBound;\n\tploBound = pow(two,exp1)*pow(nplusone,exp2);\n\tNTL::ZZ pLowerBound;\n\tconv(pLowerBound,ploBound);\n\tlong lambda = NumBits(pLowerBound) + 1;\n\tlong eta = ((lambda * lambda / rho) - lambda);\n\tgenerateParameters(lambda,eta);\n};\n\nNTL::ZZ_p HE1Encrypter::encrypt(NTL::ZZ& plaintext)\n{\n\tNTL::ZZ_p r = to_ZZ_p(rng->nextBigInteger(ONE, q));\n\tNTL::ZZ_p ptext = to_ZZ_p(plaintext);\n\treturn ptext+r*(*pmod);\n};\n\nNTL::ZZ& HE1Encrypter::getKey()\n{\n\treturn p;\n};\n\nstd::string HE1Encrypter::writeSecretsToJSON()\n{\n\tJson::Value root;\n\tstd::stringstream pStr;\n\tpStr << p;\n\troot[\"p\"] = pStr.str();\n\tJson::FastWriter writer;\n\treturn writer.write(root);\n};\n", "meta": {"hexsha": "08f8dc5a3a33f16b02ba118326a4fcf7612abcaa", "size": 1692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HE1Encrypter.cpp", "max_stars_repo_name": "TANGO-Project/cryptsdc", "max_stars_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HE1Encrypter.cpp", "max_issues_repo_name": "TANGO-Project/cryptsdc", "max_issues_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HE1Encrypter.cpp", "max_forks_repo_name": "TANGO-Project/cryptsdc", "max_forks_repo_head_hexsha": "4428fc289c97818d58a8010593636c64bde56e82", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5217391304, "max_line_length": 80, "alphanum_fraction": 0.7092198582, "num_tokens": 497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.40526563120620124}}
{"text": "/*=============================================================================\r\n    Copyright (c) 2001-2010 Joel de Guzman\r\n\r\n    Distributed under the Boost Software License, Version 1.0. (See accompanying\r\n    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n=============================================================================*/\r\n///////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Yet another calculator example! This time, we will compile to a simple\r\n//  virtual machine. This is actually one of the very first Spirit example\r\n//  circa 2000. Now, it's ported to Spirit2.\r\n//\r\n//  [ JDG Sometime 2000 ]       pre-boost\r\n//  [ JDG September 18, 2002 ]  spirit1\r\n//  [ JDG April 8, 2007 ]       spirit2\r\n//\r\n///////////////////////////////////////////////////////////////////////////////\r\n\r\n#include <boost/config/warning_disable.hpp>\r\n#include <boost/spirit/include/qi.hpp>\r\n#include <boost/spirit/include/phoenix_core.hpp>\r\n#include <boost/spirit/include/phoenix_container.hpp>\r\n#include <boost/spirit/include/phoenix_statement.hpp>\r\n#include <boost/spirit/include/phoenix_object.hpp>\r\n#include <boost/spirit/include/phoenix_operator.hpp>\r\n\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nnamespace client\r\n{\r\n    namespace qi = boost::spirit::qi;\r\n    namespace phoenix = boost::phoenix;\r\n    namespace ascii = boost::spirit::ascii;\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    //  The Virtual Machine\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    enum byte_code\r\n    {\r\n        op_neg,     //  negate the top stack entry\r\n        op_add,     //  add top two stack entries\r\n        op_sub,     //  subtract top two stack entries\r\n        op_mul,     //  multiply top two stack entries\r\n        op_div,     //  divide top two stack entries\r\n        op_int,     //  push constant integer into the stack\r\n    };\r\n\r\n    class vmachine\r\n    {\r\n    public:\r\n\r\n        vmachine(unsigned stackSize = 4096)\r\n          : stack(stackSize)\r\n          , stack_ptr(stack.begin())\r\n        {\r\n        }\r\n\r\n        int top() const { return stack_ptr[-1]; };\r\n        void execute(std::vector<int> const& code);\r\n\r\n    private:\r\n\r\n        std::vector<int> stack;\r\n        std::vector<int>::iterator stack_ptr;\r\n    };\r\n\r\n    void vmachine::execute(std::vector<int> const& code)\r\n    {\r\n        std::vector<int>::const_iterator pc = code.begin();\r\n        stack_ptr = stack.begin();\r\n\r\n        while (pc != code.end())\r\n        {\r\n            switch (*pc++)\r\n            {\r\n                case op_neg:\r\n                    stack_ptr[-1] = -stack_ptr[-1];\r\n                    break;\r\n\r\n                case op_add:\r\n                    --stack_ptr;\r\n                    stack_ptr[-1] += stack_ptr[0];\r\n                    break;\r\n\r\n                case op_sub:\r\n                    --stack_ptr;\r\n                    stack_ptr[-1] -= stack_ptr[0];\r\n                    break;\r\n\r\n                case op_mul:\r\n                    --stack_ptr;\r\n                    stack_ptr[-1] *= stack_ptr[0];\r\n                    break;\r\n\r\n                case op_div:\r\n                    --stack_ptr;\r\n                    stack_ptr[-1] /= stack_ptr[0];\r\n                    break;\r\n\r\n                case op_int:\r\n                    *stack_ptr++ = *pc++;\r\n                    break;\r\n            }\r\n        }\r\n    }\r\n\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    //  Our calculator grammar and compiler\r\n    ///////////////////////////////////////////////////////////////////////////\r\n    template <typename Iterator>\r\n    struct calculator : qi::grammar<Iterator, ascii::space_type>\r\n    {\r\n        calculator(std::vector<int>& code)\r\n          : calculator::base_type(expression)\r\n          , code(code)\r\n        {\r\n            using namespace qi::labels;\r\n            using qi::uint_;\r\n            using qi::on_error;\r\n            using qi::fail;\r\n\r\n            using phoenix::val;\r\n            using phoenix::ref;\r\n            using phoenix::push_back;\r\n            using phoenix::construct;\r\n\r\n            expression =\r\n                term\r\n                >> *(   ('+' > term             [push_back(ref(code), op_add)])\r\n                    |   ('-' > term             [push_back(ref(code), op_sub)])\r\n                    )\r\n                ;\r\n\r\n            term =\r\n                factor\r\n                >> *(   ('*' > factor           [push_back(ref(code), op_mul)])\r\n                    |   ('/' > factor           [push_back(ref(code), op_div)])\r\n                    )\r\n                ;\r\n\r\n            factor =\r\n                uint_                           [\r\n                                                    push_back(ref(code), op_int),\r\n                                                    push_back(ref(code), _1)\r\n                                                ]\r\n                |   '(' > expression > ')'\r\n                |   ('-' > factor               [push_back(ref(code), op_neg)])\r\n                |   ('+' > factor)\r\n                ;\r\n\r\n            expression.name(\"expression\");\r\n            term.name(\"term\");\r\n            factor.name(\"factor\");\r\n\r\n            on_error<fail>\r\n            (\r\n                expression\r\n              , std::cout\r\n                    << val(\"Error! Expecting \")\r\n                    << _4                               // what failed?\r\n                    << val(\" here: \\\"\")\r\n                    << construct<std::string>(_3, _2)   // iterators to error-pos, end\r\n                    << val(\"\\\"\")\r\n                    << std::endl\r\n            );\r\n        }\r\n\r\n        qi::rule<Iterator, ascii::space_type> expression, term, factor;\r\n        std::vector<int>& code;\r\n    };\r\n\r\n    template <typename Grammar>\r\n    bool compile(Grammar const& calc, std::string const& expr)\r\n    {\r\n        std::string::const_iterator iter = expr.begin();\r\n        std::string::const_iterator end = expr.end();\r\n        bool r = phrase_parse(iter, end, calc, ascii::space);\r\n\r\n        if (r && iter == end)\r\n        {\r\n            std::cout << \"-------------------------\\n\";\r\n            std::cout << \"Parsing succeeded\\n\";\r\n            std::cout << \"-------------------------\\n\";\r\n            return true;\r\n        }\r\n        else\r\n        {\r\n            std::cout << \"-------------------------\\n\";\r\n            std::cout << \"Parsing failed\\n\";\r\n            std::cout << \"-------------------------\\n\";\r\n            return false;\r\n        }\r\n    }\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n//  Main program\r\n///////////////////////////////////////////////////////////////////////////////\r\nint\r\nmain()\r\n{\r\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    std::cout << \"Expression parser...\\n\\n\";\r\n    std::cout << \"/////////////////////////////////////////////////////////\\n\\n\";\r\n    std::cout << \"Type an expression...or [q or Q] to quit\\n\\n\";\r\n\r\n    typedef std::string::const_iterator iterator_type;\r\n    typedef client::calculator<iterator_type> calculator;\r\n\r\n    client::vmachine mach;          //  Our virtual machine\r\n    std::vector<int> code;          //  Our VM code\r\n    calculator calc(code);          //  Our grammar\r\n\r\n    std::string str;\r\n    while (std::getline(std::cin, str))\r\n    {\r\n        if (str.empty() || str[0] == 'q' || str[0] == 'Q')\r\n            break;\r\n\r\n        code.clear();\r\n        if (client::compile(calc, str))\r\n        {\r\n            mach.execute(code);\r\n            std::cout << \"\\n\\nresult = \" << mach.top() << std::endl;\r\n            std::cout << \"-------------------------\\n\\n\";\r\n        }\r\n    }\r\n\r\n    std::cout << \"Bye... :-) \\n\\n\";\r\n    return 0;\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "f686529df2d3064c9302083dc761f4885d749e73", "size": 7819, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/spirit/example/qi/calc5.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/spirit/example/qi/calc5.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/spirit/example/qi/calc5.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 33.1313559322, "max_line_length": 87, "alphanum_fraction": 0.3877733726, "num_tokens": 1487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.6926419894793248, "lm_q1q2_score": 0.4052656274939752}}
{"text": "/*! EXAMPLE\n\tshows calculation of ECP integrals and first derivatives for HI\n\tin a cc-pVDZ(-PP) basis, using ECP28MDF \n\n\tUSAGE\n\t./example [LIBECPINT_SHARE_DIR_PATH]\n */\n\n#include \"libecpint.hpp\"\n\n// if you want to try out the Eigen matrix build\n#ifdef _WITH_EIGEN\n\t#include <Eigen/Dense>\n\t#include <Eigen/Core>\n#endif\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <array>\n#include <algorithm>\n#include <iterator>\n\nusing DVec = std::vector<double>;\nusing IVec = std::vector<int>;\nusing Coord = std::array<double, 3>;\n\nvoid read_basis_file(std::string, DVec&, DVec&, DVec&, IVec&, IVec&, Coord&);\n\nint main(int argc, char* argv[]) {\n\tusing namespace libecpint; \n\t\n\t// this code expects the path to the libecpint/share directory\n\t// to be passed as an argument to the executable\n\tstd::string share_dir = argv[1]; \n\t\n\t// Roughly equilibrium position HI molecule\n\t// NOTE: coordinate values must be in BOHR\n\tCoord H_pos = {0.0, 0.0, 0.0};\n\tCoord I_pos = {0.0, 0.0, 3.0};\n\t\n\t// Let's read in the GTO basis from file\n\t// store in standard vectors\n\tDVec g_exps, g_coeffs; // length = total number of primitives in basis\n\tIVec g_ams, g_lens; // length = total number of shells in basis\n\tDVec g_coords; // length = 3*total number of shells\n\t\n\t// hydrogen cc-pVDZ\n\tread_basis_file(\"hydrogen.bas\", g_exps, g_coeffs, g_coords, g_ams, g_lens, H_pos);\n\t// iodine cc-pVDZ-PP\n\tread_basis_file(\"iodine.bas\", g_exps, g_coeffs,  g_coords, g_ams, g_lens, I_pos);\n\t// check sizes, should read 'Basis read: 44, 12, 36'\n\tstd::cout << \"Basis read: \" << g_exps.size() << \", \" << g_ams.size() << \", \" << g_coords.size() << std::endl; \n\t\n\t\n\t// Now to perform a calculation using the high-level API we do the following:\n\tECPIntegrator factory; // object used to build ECP integral matrices\n\t\n\t// Set the orbital basis sets \n\tfactory.set_gaussian_basis(g_ams.size(), g_coords.data(), g_exps.data(), g_coeffs.data(), g_ams.data(), g_lens.data());\n\t// put an ECP on the iodine (charge = 53, name=\"ecp28mdf\")\n\tstd::vector<std::string> names = {\"ecp28mdf\"};\n\tint charges[1] = {53};\n\tfactory.set_ecp_basis_from_library(1, I_pos.data(), charges, names, share_dir);\n\t\n\t// initialise - we want integrals and derivatives, so deriv_order=1\n\tfactory.init(1);\n\t\n\t// and compute both the integrals and derivatives\n\tstd::cout << \"Computing integrals...\" << std::endl;\n\tfactory.compute_integrals();\n\tstd::cout << \"Computing first derivs...\" << std::endl;\n\tfactory.compute_first_derivs();\n\tstd::cout << \"Done.\" << std::endl; \n\t\n\t// we can now access the integrals\n\t// as an example, let's build them into an\n\t// eigen matrix\n#ifdef _WITH_EIGEN\n\t // grab the integrals\n\t std::shared_ptr<DVec> ints = factory.get_integrals();\n\t \n\t // map into a square matrix\n\t // note that we use ROW-MAJOR ORDERING\n\t // 12 basis functions\n\t Eigen::MatrixXd ecpints = Eigen::Map<Eigen::Matrix<double, 12, 12, Eigen::RowMajor>>(ints->data());\n\t std::cout << \"ECP Integrals:\" << std::endl;\n\t std::cout << ecpints << std::endl; \n\t\n\t // we could do the same with derivatives\n\t // this returns pointers in order [Hx, Hy, Hz, Ix, Iy, Iz]\n\t std::vector<std::shared_ptr<DVec>> derivs = factory.get_first_derivs();\n\t // e.g. the Iodine y-derivative\n\t Eigen::MatrixXd iodine_y_derivs = Eigen::Map<Eigen::Matrix<double, 12, 12, Eigen::RowMajor>>(derivs[4]->data());\n\t std::cout << \"y-derivs on iodine:\" << std::endl;\n\t std::cout << iodine_y_derivs << std::endl; \n#endif\n\t\n\treturn 0;\n}\n\n/*! Reads in the Gaussian orbital basis from a file. \n\n\tfilename - the path/name of the basis file\n\texps - vector to place exponents in\n\tcoeffs - vector to place coefficients in\n\tcoords - the vector of xyz coords for each shell\n\tams - vector to place angular momenta in\n\tlens - vector to place shell lengths in\n\tatom - the position of the atom being read in  \n */\nvoid read_basis_file(std::string filename, DVec& exps, DVec& coeffs, DVec& coords, IVec& ams, IVec& lens, Coord& atom) { \n\tstd::ifstream input_file(filename);\n\tif (input_file.is_open()) {\n\t\t// We expect the file to have the format\n\t\t// L; x, c; x, c; x, c; x, c;\n\t\t// with a line for each shell\n\t\tstd::string line, token; \n\t\twhile (!input_file.eof()) {\n\t\t\tstd::getline(input_file, line);\n\t\t\t\n\t\t\t// split the line by semicolon\n\t\t\tsize_t sc_pos = line.find(';');\n\t\t\tint len = -1;\n\t\t\tint am;\n\t\t\twhile (sc_pos != std::string::npos) {\n\t\t\t\ttoken = line.substr(0, sc_pos);\n\t\t\t\tline.erase(0, sc_pos+1); \n\t\t\t\t\n\t\t\t\t// First bit is L\n\t\t\t\tif (len == -1) {\n\t\t\t\t\tam = std::stoi(token);\n\t\t\t\t\tlen++; \n\t\t\t\t} else {\n\t\t\t\t\t// subsequent bits are x,c\n\t\t\t\t\tsize_t c_pos = token.find(',');\n\t\t\t\t\tif (c_pos != std::string::npos) {\n\t\t\t\t\t\texps.push_back(std::stod(token.substr(0, c_pos)));\n\t\t\t\t\t\tcoeffs.push_back(std::stod(token.substr(c_pos+1, token.length())));\n\t\t\t\t\t\tlen++; \n\t\t\t\t\t} \n\t\t\t\t}\n\t\t\t\tsc_pos = line.find(';'); \n\t\t\t}\n\t\t\tif (len > 0) {\n\t\t\t\t// non-empty shell found\n\t\t\t\tams.push_back(am);\n\t\t\t\tlens.push_back(len);\n\t\t\t\tstd::copy(atom.begin(), atom.end(), std::back_inserter(coords));\n\t\t\t}\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "4307f0ec8a1bb30e88a2763d8e228eb0e480a15e", "size": 4992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/example.cpp", "max_stars_repo_name": "berquist/libecpint", "max_stars_repo_head_hexsha": "46e9280eab334fcf17e0824f39b56f11d3e54762", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2017-12-23T15:43:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T20:13:15.000Z", "max_issues_repo_path": "example/example.cpp", "max_issues_repo_name": "berquist/libecpint", "max_issues_repo_head_hexsha": "46e9280eab334fcf17e0824f39b56f11d3e54762", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 54.0, "max_issues_repo_issues_event_min_datetime": "2018-09-07T18:02:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T10:47:16.000Z", "max_forks_repo_path": "example/example.cpp", "max_forks_repo_name": "berquist/libecpint", "max_forks_repo_head_hexsha": "46e9280eab334fcf17e0824f39b56f11d3e54762", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2018-06-21T12:30:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-01T10:18:09.000Z", "avg_line_length": 32.2064516129, "max_line_length": 121, "alphanum_fraction": 0.6646634615, "num_tokens": 1508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4052656237817491}}
{"text": "#include <Eigen/Dense>\n#include <vector>\n#include <iostream>\n#include \"gpu_func.h\"\n#include <sys/time.h>\n#include \"proxgpu_types.h\"\n\n\n// Compute the gradient at B\nnumeric get_value_only(cox_cache &dev_cache,\n                  cox_data &dev_data,\n                  cox_param &dev_param,\n                  numeric *B,\n                  int *ncase,\n                  int *ncase_cumu,\n                  int K,\n                  int p,\n                  cublasHandle_t handle,\n                  cudaStream_t *streams,\n                  numeric *cox_val_host)\n{\n    numeric result = 0.0;\n    for (int k = 0; k < K; ++k)\n    {\n        int n = ncase[k];\n        int offset = ncase_cumu[k];\n        compute_product(dev_data.X+offset*p, B+p*k, dev_cache.eta+offset, n, p, streams[k], handle,CUBLAS_OP_N);\n        apply_exp(dev_cache.eta+offset, dev_cache.exp_eta+offset, n, streams[k]);\n        // Save rev_cumsum result to dev_cache.outer_accumu to avoid more cache variables\n        rev_cumsum(dev_cache.exp_eta+offset, dev_cache.outer_accumu+offset ,n, streams[k]);\n        adjust_ties(dev_cache.outer_accumu+offset, dev_data.rankmin+offset, dev_cache.exp_accumu+offset, n, streams[k]);\n\n        get_coxvalue(dev_cache.exp_accumu+offset, dev_cache.eta+offset, dev_data.censor+offset, dev_cache.cox_val+k, n, streams[k]);\n        cudaMemcpyAsync(cox_val_host+k, dev_cache.cox_val+k, sizeof(numeric)*1, cudaMemcpyDeviceToHost, streams[k]);\n    }\n\n    cudaDeviceSynchronize();\n    for(int k = 0; k < K; ++k)\n    {\n        result += cox_val_host[k];\n    }\n    return result;\n}\n\n\n\n// Compute the gradient at B and save the result to dev_grad\nnumeric get_gradient(cox_cache &dev_cache,\n                  cox_data &dev_data,\n                  cox_param &dev_param,\n                  numeric *dev_grad,\n                  numeric *B,\n                  int *ncase,\n                  int *ncase_cumu,\n                  int K,\n                  int p,\n                  cublasHandle_t handle,\n                  cudaStream_t *streams,\n                  bool get_val = false,\n                  numeric *cox_val_host=0)\n{\n    for(int k = 0; k <K; ++k)\n    {\n        int n = ncase[k];\n        int offset = ncase_cumu[k];\n        compute_product(dev_data.X+offset*p, B+p*k, dev_cache.eta+offset, n, p, streams[k], handle,CUBLAS_OP_N);\n        apply_exp(dev_cache.eta+offset, dev_cache.exp_eta+offset, n, streams[k]);\n        // Save rev_cumsum result to dev_cache.outer_accumu to avoid more cache variables\n        rev_cumsum(dev_cache.exp_eta+offset, dev_cache.outer_accumu+offset ,n, streams[k]);\n        adjust_ties(dev_cache.outer_accumu+offset, dev_data.rankmin+offset, dev_cache.exp_accumu+offset, n, streams[k]);\n        // Above is  _update_exp()\n        // Below is _update_outer()\n        // Save the result of division to residual to avoid more cache variables\n        cwise_div(dev_data.censor+offset, dev_cache.exp_accumu+offset, dev_cache.residual+offset,  n, streams[k]);\n        cumsum(dev_cache.residual+offset, n, streams[k]);\n        adjust_ties(dev_cache.residual+offset, dev_data.rankmax+offset, dev_cache.outer_accumu+offset, n, streams[k]);\n        mult_add(dev_cache.residual+offset,\n                 dev_cache.exp_eta+offset, \n                 dev_cache.outer_accumu+offset, \n                 dev_data.censor+offset, \n                 n, streams[k]);\n        // residual ready\n        compute_product(dev_data.X+offset*p, \n                        dev_cache.residual+offset, \n                        dev_grad + k*p, n, p, streams[k], handle, CUBLAS_OP_T);\n        // Gradient ready\n        // get_val will modify eta, but it's fine\n        if(get_val)\n        {\n            get_coxvalue(dev_cache.exp_accumu+offset, dev_cache.eta+offset, dev_data.censor+offset, dev_cache.cox_val+k, n, streams[k]);\n            cudaMemcpyAsync(cox_val_host+k, dev_cache.cox_val+k, sizeof(numeric)*1, cudaMemcpyDeviceToHost, streams[k]);\n        }\n    }\n    numeric result = 0.0;\n    if (get_val)\n    {\n        cudaDeviceSynchronize();\n        for(int k = 0; k < K; ++k)\n        {\n            result += cox_val_host[k];\n        }\n\n    }\n    return result;\n}\n\n\n// [[Rcpp::export]]\nRcpp::List solve_path(const Rcpp::List & X_list,\n                        const Rcpp::List & censoring_list,\n                        MatrixXd B,\n                        const Rcpp::List & rankmin_list,\n                        const Rcpp::List & rankmax_list,\n                        double step_size,\n                        VectorXd lambda_1_all,\n                        VectorXd lambda_2_all,\n                        Eigen::RowVectorXd penalty_factor, // Penalty factor for each group of variables\n                        int niter, // Maximum number of iterations\n                        double linesearch_beta,\n                        double eps, // convergence criteria\n                        double tol = 1e-10// line search tolerance\n                        )\n{\n    // B is a long and skinny matrix now! rows are features and cols are responses\n    const int p = B.rows();\n    const int K = B.cols();\n    // Create CUDA streams and handle\n    cudaStream_t *streams = (cudaStream_t *) malloc(K * sizeof(cudaStream_t));\n    for (int k = 0; k<K; ++k)\n    {\n        cudaStreamCreate(&streams[k]);\n    }\n    cublasHandle_t handle;\n    cublasCreate(&handle);\n    cudaStream_t copy_stream;\n    cudaStream_t nest_stream;\n    cudaStreamCreate(&copy_stream);\n    cudaStreamCreate(&nest_stream);\n\n    cox_data dev_data;\n    cox_cache dev_cache;\n    cox_param dev_param;\n    numeric *cox_val_host=(numeric *)malloc(sizeof(numeric)*K);\n    MatrixXd host_B(p,K);\n\n    int *ncase_cumu = (int *)malloc(sizeof(int)*(K+1));\n    ncase_cumu[0] = 0;\n    int *ncase = (int*)malloc(sizeof(int)*K);\n    std::vector<MapMatd> X_all;\n    std::vector<MapVecd> censor; // Modify this in R\n    std::vector<MapVeci> rankmin;\n    std::vector<MapVeci> rankmax;\n    for (int k = 0; k<K; ++k)\n    {\n        X_all.emplace_back(Rcpp::as<MapMatd>(X_list[k]));\n        censor.emplace_back(Rcpp::as<MapVecd>(censoring_list[k]));\n        rankmin.emplace_back(Rcpp::as<MapVeci>(rankmin_list[k]));\n        rankmax.emplace_back(Rcpp::as<MapVeci>(rankmax_list[k]));\n        ncase[k] = X_all[k].rows();\n        ncase_cumu[k+1] = ncase_cumu[k] + ncase[k];\n    }\n\n    allocate_device_memory(dev_data, dev_cache, dev_param, ncase_cumu[K], K, p);\n\n    // initialize parameters on the device\n    cudaMemcpy(dev_param.B, &B(0,0), sizeof(numeric)*K*p, cudaMemcpyHostToDevice);\n    cudaMemcpy(dev_param.v, &B(0,0), sizeof(numeric)*K*p, cudaMemcpyHostToDevice);\n    cudaMemcpy(dev_param.penalty_factor, &penalty_factor(0), sizeof(numeric)*p, cudaMemcpyHostToDevice);\n\n    // Copy the data\n    for(int k = 0; k <K; ++k)\n    {\n        int n = ncase[k];\n        cudaMemcpyAsync(dev_data.X+ncase_cumu[k]*p, &(X_all[k](0,0)), sizeof(numeric) * p *n, cudaMemcpyHostToDevice, streams[k]);\n        cudaMemcpyAsync(dev_data.censor+ncase_cumu[k], &(censor[k][0]), sizeof(numeric) *n, cudaMemcpyHostToDevice, streams[k]);\n        cudaMemcpyAsync(dev_data.rankmin+ncase_cumu[k], &(rankmin[k][0]), sizeof(int)*n, cudaMemcpyHostToDevice, streams[k]);\n        cudaMemcpyAsync(dev_data.rankmax+ncase_cumu[k], &(rankmax[k][0]), sizeof(int)*n, cudaMemcpyHostToDevice, streams[k]); \n    }\n\n    numeric cox_val;\n    numeric cox_val_next;\n    numeric rhs_ls; // right-hand side of line search condition\n    numeric diff; // Max norm of the difference of two consecutive iterates\n    numeric lambda_1;\n    numeric lambda_2;\n    const int num_lambda = lambda_1_all.size();\n    numeric step_size_intial = step_size;\n    Rcpp::List result(num_lambda);\n    bool stop; // Stop line searching\n    numeric weight_old, weight_new;\n    // Initialization done, starting solving the path\n    struct timeval start, end;\n    for (int lam_ind = 0; lam_ind < num_lambda; ++lam_ind){\n        gettimeofday(&start, NULL);\n\n        lambda_1 = lambda_1_all[lam_ind];\n        lambda_2 = lambda_2_all[lam_ind];\n        weight_old = 1.0;\n        step_size = step_size_intial;\n        // Inner iteration\n        for (int i = 0; i < niter; ++i)\n        {\n\n            // Set prev_B = B\n            cublas_copy(dev_param, K*p, copy_stream, handle);\n            // Wait for Nesterov weight update\n            cudaStreamSynchronize(nest_stream);\n            // Update the gradient at v, compute cox_val at v\n            cox_val = get_gradient(dev_cache,\n                                    dev_data,\n                                    dev_param,\n                                    dev_param.grad,\n                                    dev_param.v,\n                                    ncase,\n                                    ncase_cumu,\n                                    K,\n                                    p,\n                                    handle,\n                                    streams,\n                                    true,\n                                    cox_val_host);\n            \n            // Enter line search\n            while(true)\n            {\n                // Update  B\n                update_parameters(dev_param,\n                                    K,\n                                    p,\n                                    step_size,\n                                    lambda_1,\n                                    lambda_2);\n\n                // Get cox_val at updated B\n                cox_val_next = get_value_only(dev_cache,\n                                                dev_data,\n                                                dev_param,\n                                                dev_param.B,\n                                                ncase,\n                                                ncase_cumu,\n                                                K,\n                                                p,\n                                                handle,\n                                                streams,\n                                                cox_val_host);\n\n                stop = false;\n                // This block are the line search conditions\n                if(abs((cox_val_next - cox_val)/fmax(1.0, abs(cox_val_next))) > tol){\n                    rhs_ls = cox_val + ls_stop_v1(dev_param, step_size,K,p);\n                    stop = (cox_val_next <= rhs_ls);\n                } else \n                {\n                    get_gradient(dev_cache,\n                                dev_data,\n                                dev_param,\n                                dev_param.grad_ls,\n                                dev_param.B,\n                                ncase,\n                                ncase_cumu,\n                                K,\n                                p,\n                                handle,\n                                streams);\n                    rhs_ls = ls_stop_v2(dev_param, step_size,K,p);\n                    stop = (rhs_ls >= 0);\n\n                }\n\n                if (stop)\n                {\n                    break;\n                }\n                step_size /= linesearch_beta;\n            }\n\n            diff = max_diff(dev_param, K, p);\n            if (diff < eps)\n            {\n                std::cout << \"convergence based on parameter change reached in \" << i <<\" iterations\\n\";\n                std::cout << \"current step size is \" << step_size << std::endl;\n                gettimeofday(&end, NULL);\n                double delta  = ((end.tv_sec  - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6;\n                std::cout <<  \"elapsed time is \" << delta << \" seconds\" << std::endl;\n                Rcpp::checkUserInterrupt();\n                break;\n            }\n\n             // Nesterov weight\n            weight_new = 0.5*(1+sqrt(1+4*weight_old*weight_old));\n            nesterov_update(dev_param,K,p, weight_old, weight_new, nest_stream, handle);\n            weight_old = weight_new;\n\n            if (i != 0 && i % 100 == 0)\n            {\n                std::cout << \"reached \" << i << \" iterations\\n\";\n                gettimeofday(&end, NULL);\n                double delta  = ((end.tv_sec  - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6;\n                std::cout <<  \"elapsed time is \" << delta  << \" seconds\" << std::endl;\n                Rcpp::checkUserInterrupt();\n            }\n\n        }\n        cudaMemcpy(&host_B(0,0), dev_param.B, sizeof(numeric)*K*p, cudaMemcpyDeviceToHost);\n        result[lam_ind] = host_B;\n        std::cout << \"Solution for the \" <<  lam_ind+1 << \"th lambda pair is obtained\\n\";\n    }\n\n\n\n\n    free_device_memory(dev_data, dev_cache, dev_param);\n    cublasDestroy(handle);\n    for (int si = 0; si< K;++si){\n        cudaStreamDestroy(streams[si]);\n    }\n    cudaStreamDestroy(copy_stream);\n    cudaStreamDestroy(nest_stream);\n    free(streams);\n    free(ncase_cumu);\n    free(ncase);\n    return result;\n}", "meta": {"hexsha": "12885303416441b95afbcb3c1c466045279b2fc5", "size": 12889, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cox.cpp", "max_stars_repo_name": "RuilinLi/multiresponse_cox_gpu", "max_stars_repo_head_hexsha": "4da917c1038ae185a289079b58ca1ec9554af546", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cox.cpp", "max_issues_repo_name": "RuilinLi/multiresponse_cox_gpu", "max_issues_repo_head_hexsha": "4da917c1038ae185a289079b58ca1ec9554af546", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cox.cpp", "max_forks_repo_name": "RuilinLi/multiresponse_cox_gpu", "max_forks_repo_head_hexsha": "4da917c1038ae185a289079b58ca1ec9554af546", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9040247678, "max_line_length": 136, "alphanum_fraction": 0.517805881, "num_tokens": 2880, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8104789086703225, "lm_q2_score": 0.5, "lm_q1q2_score": 0.40523945433516123}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_LOG2_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_LOG2_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/simd/function/musl.hpp>\n#include <boost/simd/function/std.hpp>\n#include <boost/assert.hpp>\n#include <boost/config.hpp>\n#include <cmath>\n#include <boost/simd/function/simd/any.hpp>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/fms.hpp>\n#include <boost/simd/function/ifrexp.hpp>\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/function/if_nan_else.hpp>\n#include <boost/simd/function/ilog2.hpp>\n#include <boost/simd/function/is_lez.hpp>\n#include <boost/simd/function/is_ngez.hpp>\n#include <boost/simd/function/musl.hpp>\n#include <boost/simd/function/plain.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/tofloat.hpp>\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/invlog_2.hpp>\n#include <boost/simd/constant/nan.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/smallestposval.hpp>\n#include <boost/simd/constant/sqrt_2o_2.hpp>\n\n#include <boost/simd/detail/constant/invlog_2hi.hpp>\n#include <boost/simd/detail/constant/invlog_2lo.hpp>\n\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log2_\n                          , (typename A0,typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::single_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 const& a0) const BOOST_NOEXCEPT\n    {\n      return musl_(log2)(a0);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD_IF ( log2_\n                          , (typename A0,typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::double_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 const& a0) const BOOST_NOEXCEPT\n    {\n      return musl_(log2)(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log2_\n                          , (typename A0,typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::arithmetic_<A0>, X >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 const& a0) const BOOST_NOEXCEPT\n    {\n      return bitwise_cast<A0>(bs::ilog2(a0));\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log2_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::musl_tag\n                          , bs::pack_< bd::single_<A0>, X>\n                          )\n  {\n    /* origin: FreeBSD /usr/src/lib/msun/src/e_log2f.c */\n    /*\n     * ====================================================\n     * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.\n     *\n     * Developed at SunPro, a Sun Microsystems, Inc. business.\n     * Permission to use, copy, modify, and distribute this\n     * software is freely granted, provided that this notice\n     * is preserved.\n     * ====================================================\n     */\n    BOOST_FORCEINLINE A0 operator() (const musl_tag &, const A0& a0) const BOOST_NOEXCEPT\n    {\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      A0 x =  a0;\n      iA0 k(0);\n      auto isnez = is_nez(a0);\n#ifndef BOOST_SIMD_NO_DENORMALS\n      auto test = is_less(a0, Smallestposval<A0>())&&isnez;\n      if (any(test))\n      {\n        k = if_minus(test, k, iA0(25));\n        x = if_else(test, x*A0(33554432ul), x);\n      }\n#endif\n      uiA0 ix = bitwise_cast<uiA0>(x);\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      ix += 0x3f800000 - 0x3f3504f3;\n      k += bitwise_cast<iA0>(ix>>23) - 0x7f;\n      ix = (ix&0x007fffff) + 0x3f3504f3;\n      x =  bitwise_cast<A0>(ix);\n      A0 f = dec(x);\n      A0 s = f/(2.0f + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0, 0x3eccce13, 0x3e789e26>(w);\n      A0 t2= z*horn<A0, 0x3f2aaaaa, 0x3e91e9ee>(w);\n      A0 R = t2 + t1;\n      A0 hfsq = Half<A0>()*sqr(f);\n\n      A0 dk = tofloat(k);\n      A0 r =   fma(fms(s, hfsq+R, hfsq)+f, Invlog_2<A0>(), dk);\n      // The original algorithm does some extra calculation in place of the return line\n      // to get extra precision but this is uneeded for float as the exhaustive test shows\n      // a 0.5 ulp maximal error on the full range.\n      // Moreover all log2(exp2(i)) i =  1..31 are flint\n      // I leave the code here in case an exotic proc will not play the game.\n      //       A0  hi = f - hfsq;\n      //       hi =  bitwise_and(hi, uiA0(0xfffff000ul));\n      //       A0  lo = fma(s, hfsq+R, f - hi - hfsq);\n      //       A0 r = (lo+hi)*detail::Invlog_2lo<A0>() + lo*detail::Invlog_2hi<A0>() + hi*detail::Invlog_2hi<A0>() + k;\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n      A0 zz = if_else(isnez, if_else(a0 == Inf<A0>(), Inf<A0>(), r), Minf<A0>());\n#else\n      A0 zz = if_else(isnez, r, Minf<A0>());\n#endif\n      return if_nan_else(is_ngez(a0), zz);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log2_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::musl_tag\n                             , bs::pack_< bd::double_<A0>, X>\n                             )\n  {\n    BOOST_FORCEINLINE A0 operator() (const musl_tag &, const A0& a0) const BOOST_NOEXCEPT\n    {\n    /* origin: FreeBSD /usr/src/lib/msun/src/e_log2f.c */\n    /*\n     * ====================================================\n     * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.\n     *\n     * Developed at SunPro, a Sun Microsystems, Inc. business.\n     * Permission to use, copy, modify, and distribute this\n     * software is freely granted, provided that this notice\n     * is preserved.\n     * ====================================================\n     */\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      A0 x =  a0;\n      uiA0 hx = bitwise_cast<uiA0>(x) >> 32;\n      iA0 k(0);\n      auto isnez = is_nez(a0);\n\n#ifndef BOOST_SIMD_NO_DENORMALS\n      auto test = is_less(a0, Smallestposval<A0>())&&isnez;\n      if (any(test))\n      {\n        k = if_minus(test, k, iA0(54));\n        x = if_else(test, x*A0(18014398509481984ull), x);\n      }\n#endif\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      hx += 0x3ff00000 - 0x3fe6a09e;\n      k += bitwise_cast<iA0>(hx>>20) - 0x3ff;\n      hx = (hx&0x000fffff) + 0x3fe6a09e;\n      x = bitwise_cast<A0>(hx<<32 | (bitwise_and(0xffffffffull, bitwise_cast<uiA0>(x))));\n\n      A0 f = dec(x);\n      A0 s = f/(2.0f + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0, 0x3fd999999997fa04ll, 0x3fcc71c51d8e78afll, 0x3fc39a09d078c69fll > (w);\n      A0 t2= z*horn<A0, 0x3fe5555555555593ll, 0x3fd2492494229359ll\n                      , 0x3fc7466496cb03dell, 0x3fc2f112df3e5244ll> (w);\n      A0 R = t2 + t1;\n      A0 hfsq = Half<A0>()*sqr(f);\n//        return -(hfsq-(s*(hfsq+R))-f)*Invlog_2<A0>()+dk;  // fast ?\n\n      /*\n       * f-hfsq must (for args near 1) be evaluated in extra precision\n       * to avoid a large cancellation when x is near sqrt(2) or 1/sqrt(2).\n       * This is fairly efficient since f-hfsq only depends on f, so can\n       * be evaluated in parallel with R.  Not combining hfsq with R also\n       * keeps R small (though not as small as a true `lo' term would be),\n       * so that extra precision is not needed for terms involving R.\n       *\n       * Compiler bugs involving extra precision used to break Dekker's\n       * theorem for spitting f-hfsq as hi+lo, unless double_t was used\n       * or the multi-precision calculations were avoided when double_t\n       * has extra precision.  These problems are now automatically\n       * avoided as a side effect of the optimization of combining the\n       * Dekker splitting step with the clear-low-bits step.\n       *\n       * y must (for args near sqrt(2) and 1/sqrt(2)) be added in extra\n       * precision to avoid a very large cancellation when x is very near\n       * these values.  Unlike the above cancellations, this problem is\n       * specific to base 2.  It is strange that adding +-1 is so much\n       * harder than adding +-ln2 or +-log10_2.\n       *\n       * This uses Dekker's theorem to normalize y+val_hi, so the\n       * compiler bugs are back in some configurations, sigh.  And I\n       * don't want to used double_t to avoid them, since that gives a\n       * pessimization and the support for avoiding the pessimization\n       * is not yet available.\n       *\n       * The multi-precision calculations for the multiplications are\n       * routine.\n       */\n\n      /* hi+lo = f - hfsq + s*(hfsq+R) ~ log(1+f) */\n      A0  hi = f - hfsq;\n      hi =  bitwise_and(hi, (Allbits<uiA0>() << 32));\n      A0 lo = fma(s, hfsq+R, f - hi - hfsq);\n\n      A0 val_hi = hi*Invlog_2hi<A0>();\n      A0 val_lo = fma(lo+hi, Invlog_2lo<A0>(), lo*Invlog_2hi<A0>());\n\n      A0 dk = tofloat(k);\n      A0 w1 = dk + val_hi;\n      val_lo += (dk - w1) + val_hi;\n      val_hi = w1;\n      A0 r =  val_lo + val_hi;\n#ifndef BOOST_SIMD_NO_INFINITIES\n      A0 zz = if_else(isnez, if_else(a0 == Inf<A0>(), Inf<A0>(), r), Minf<A0>());\n#else\n      A0 zz = if_else(isnez, r, Minf<A0>());\n#endif\n      return if_nan_else(is_ngez(a0), zz);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log2_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::plain_tag\n                             , bs::pack_< bd::single_<A0>, X>\n                             )\n  {\n    /* origin: FreeBSD /usr/src/lib/msun/src/e_log2f.c */\n    /*\n     * ====================================================\n     * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.\n     *\n     * Developed at SunPro, a Sun Microsystems, Inc. business.\n     * Permission to use, copy, modify, and distribute this\n     * software is freely granted, provided that this notice\n     * is preserved.\n     * ====================================================\n     */\n    BOOST_FORCEINLINE A0 operator() (const plain_tag &, const A0& a0) const BOOST_NOEXCEPT\n    {\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      A0 x =  a0;\n      iA0 k(0);\n      auto isnez = is_nez(a0);\n#ifndef BOOST_SIMD_NO_DENORMALS\n      auto test = is_less(a0, Smallestposval<A0>())&&isnez;\n      if (any(test))\n      {\n        k = if_minus(test, k, iA0(25));\n        x = if_else(test, x*A0(33554432ul), x);\n      }\n#endif\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      iA0 kk;\n      std::tie(x, kk) = ifrexp(x);\n      A0 x_lt_sqrthf = genmask(Sqrt_2o_2<A0>() > x);\n      k += kk + bitwise_cast<iA0>(x_lt_sqrthf);\n      A0 f = dec(x+bitwise_and(x, x_lt_sqrthf));\n      A0 dk = tofloat(k);\n\n      A0 s = f/(2.0f + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0, 0x3eccce13, 0x3e789e26>(w);\n      A0 t2= z*horn<A0, 0x3f2aaaaa, 0x3e91e9ee>(w);\n      A0 R = t2 + t1;\n      A0 hfsq = Half<A0>()*sqr(f);\n\n      A0 r =   fma(fms(s, hfsq+R, hfsq)+f, Invlog_2<A0>(), dk);\n      // The original algorithm does some extra calculation in place of the return line\n      // to get extra precision but this is uneeded for float as the exhaustive test shows\n      // a 0.5 ulp maximal error on the full range.\n      // Moreover all log2(exp2(i)) i =  1..31 are flint\n      // I leave the code here in case an exotic proc will not play the game.\n      //       A0  hi = f - hfsq;\n      //       hi =  bitwise_and(hi, uiA0(0xfffff000ul));\n      //       A0  lo = fma(s, hfsq+R, f - hi - hfsq);\n      //       A0 r = (lo+hi)*Invlog_2lo<A0>() + lo*Invlog_2hi<A0>() + hi*Invlog_2hi<A0>() + k;\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n      A0 zz = if_else(isnez, if_else(a0 == Inf<A0>(), Inf<A0>(), r), Minf<A0>());\n#else\n      A0 zz = if_else(isnez, r, Minf<A0>());\n#endif\n      return if_nan_else(is_ngez(a0), zz);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log2_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::plain_tag\n                             , bs::pack_< bd::double_<A0>, X>\n                             )\n  {\n    BOOST_FORCEINLINE A0 operator() (const plain_tag &, const A0& a0) const BOOST_NOEXCEPT\n    {\n      /* origin: FreeBSD /usr/src/lib/msun/src/e_log2f.c */\n      /*\n       * ====================================================\n       * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.\n       *\n       * Developed at SunPro, a Sun Microsystems, Inc. business.\n       * Permission to use, copy, modify, and distribute this\n       * software is freely granted, provided that this notice\n       * is preserved.\n       * ====================================================\n       */\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      A0 x =  a0;\n      uiA0 hx = bitwise_cast<uiA0>(x) >> 32;\n      iA0 k(0);\n      auto isnez = is_nez(a0);\n\n#ifndef BOOST_SIMD_NO_DENORMALS\n      auto test = is_less(a0, Smallestposval<A0>())&&isnez;\n      if (any(test))\n      {\n        k = if_minus(test, k, iA0(54));\n        x = if_else(test, x*A0(18014398509481984ull), x);\n      }\n#endif\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      iA0 kk;\n      std::tie(x, kk) = ifrexp(x);\n      A0 x_lt_sqrthf = genmask(Sqrt_2o_2<A0>() > x);\n      k += kk + bitwise_cast<iA0>(x_lt_sqrthf);\n      A0 f = dec(x+bitwise_and(x, x_lt_sqrthf));\n      A0 dk = tofloat(k);\n\n      A0 s = f/(2.0f + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0, 0x3fd999999997fa04ll, 0x3fcc71c51d8e78afll, 0x3fc39a09d078c69fll > (w);\n      A0 t2= z*horn<A0, 0x3fe5555555555593ll, 0x3fd2492494229359ll\n        , 0x3fc7466496cb03dell, 0x3fc2f112df3e5244ll> (w);\n      A0 R = t2 + t1;\n      A0 hfsq = Half<A0>()*sqr(f);\n//        return -(hfsq-(s*(hfsq+R))-f)*Invlog_2<A0>()+dk;  // fast ?\n\n      /*\n       * f-hfsq must (for args near 1) be evaluated in extra precision\n       * to avoid a large cancellation when x is near sqrt(2) or 1/sqrt(2).\n       * This is fairly efficient since f-hfsq only depends on f, so can\n       * be evaluated in parallel with R.  Not combining hfsq with R also\n       * keeps R small (though not as small as a true `lo' term would be),\n       * so that extra precision is not needed for terms involving R.\n       *\n       * Compiler bugs involving extra precision used to break Dekker's\n       * theorem for spitting f-hfsq as hi+lo, unless double_t was used\n       * or the multi-precision calculations were avoided when double_t\n       * has extra precision.  These problems are now automatically\n       * avoided as a side effect of the optimization of combining the\n       * Dekker splitting step with the clear-low-bits step.\n       *\n       * y must (for args near sqrt(2) and 1/sqrt(2)) be added in extra\n       * precision to avoid a very large cancellation when x is very near\n       * these values.  Unlike the above cancellations, this problem is\n       * specific to base 2.  It is strange that adding +-1 is so much\n       * harder than adding +-ln2 or +-log10_2.\n       *\n       * This uses Dekker's theorem to normalize y+val_hi, so the\n       * compiler bugs are back in some configurations, sigh.  And I\n       * don't want to used double_t to avoid them, since that gives a\n       * pessimization and the support for avoiding the pessimization\n       * is not yet available.\n       *\n       * The multi-precision calculations for the multiplications are\n       * routine.\n       */\n\n      /* hi+lo = f - hfsq + s*(hfsq+R) ~ log(1+f) */\n      A0  hi = f - hfsq;\n      hi =  bitwise_and(hi, (Allbits<uiA0>() << 32));\n      A0 lo = fma(s, hfsq+R, f - hi - hfsq);\n\n      A0 val_hi = hi*Invlog_2hi<A0>();\n      A0 val_lo = fma(lo+hi, Invlog_2lo<A0>(), lo*Invlog_2hi<A0>());\n\n      A0 w1 = dk + val_hi;\n      val_lo += (dk - w1) + val_hi;\n      val_hi = w1;\n      A0 r =  val_lo + val_hi;\n#ifndef BOOST_SIMD_NO_INFINITIES\n      A0 zz = if_else(isnez, if_else(a0 == Inf<A0>(), Inf<A0>(), r), Minf<A0>());\n#else\n      A0 zz = if_else(isnez, r, Minf<A0>());\n#endif\n      return if_nan_else(is_ngez(a0), zz);\n    }\n  };\n\n} } }\n\n\n#endif\n", "meta": {"hexsha": "e4923f65002ad46f0541afac2c1059c0898943a9", "size": 17298, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/function/log2.hpp", "max_stars_repo_name": "nickporubsky/boost-simd-clone", "max_stars_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "include/boost/simd/arch/common/simd/function/log2.hpp", "max_issues_repo_name": "nickporubsky/boost-simd-clone", "max_issues_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/simd/function/log2.hpp", "max_forks_repo_name": "nickporubsky/boost-simd-clone", "max_forks_repo_head_hexsha": "b81dfcd9d6524a131ea714f1eebb5bb75adddcc7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 38.44, "max_line_length": 119, "alphanum_fraction": 0.5570008093, "num_tokens": 5142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8104788995148791, "lm_q2_score": 0.5, "lm_q1q2_score": 0.40523944975743953}}
{"text": "/*\n * @Description: Kalman filter based localization on GNSS-INS-Sim\n * @Author: Ge Yao\n * @Date: 2020-11-12 15:14:07\n */\n#ifndef LIDAR_LOCALIZATION_FILTERING_GNSS_INS_SIM_FILTERING_HPP_\n#define LIDAR_LOCALIZATION_FILTERING_GNSS_INS_SIM_FILTERING_HPP_\n\n#include <string>\n#include <deque>\n#include <unordered_map>\n\n#include <Eigen/Dense>\n\n#include <yaml-cpp/yaml.h>\n\n#include \"lidar_localization/EKFStd.h\"\n\n#include \"lidar_localization/sensor_data/imu_data.hpp\"\n#include \"lidar_localization/sensor_data/pos_vel_mag_data.hpp\"\n#include \"lidar_localization/sensor_data/pose_data.hpp\"\n\n#include \"lidar_localization/models/kalman_filter/kalman_filter.hpp\"\n\nnamespace lidar_localization {\n\nclass GNSSINSSimFiltering {\n  public:\n    GNSSINSSimFiltering();\n\n    bool Init(\n      const Eigen::Matrix4f& init_pose,\n      const Eigen::Vector3f &init_vel,\n      const IMUData &init_imu_data\n    );\n\n    bool Update(\n      const IMUData &imu_data\n    );\n    bool Correct(\n      const IMUData &imu_data,\n      const PosVelMagData &pos_vel_mag_data\n    );\n\n    // getters:\n    bool HasInited() const { return has_inited_; }\n\n    double GetTime(void) { return kalman_filter_ptr_->GetTime(); }\n    Eigen::Matrix4f GetPose(void) { return current_pose_; }\n    Eigen::Vector3f GetVel(void) { return current_vel_; }\n    void GetOdometry(Eigen::Matrix4f &pose, Eigen::Vector3f &vel);\n    void GetStandardDeviation(EKFStd &kf_std_msg);\n    void SaveObservabilityAnalysis(void);\n    \n  private:\n    bool InitWithConfig(void);\n    bool InitFusion(const YAML::Node& config_node);\n\n    // init pose setter:\n    bool SetInitGNSS(const Eigen::Matrix4f& init_pose);\n    bool SetInitPose(const Eigen::Matrix4f& init_pose);\n\n  private:\n    bool has_inited_ = false;\n\n    // Kalman filter:\n    struct {\n      std::string FUSION_METHOD;\n\n      std::unordered_map<std::string, KalmanFilter::MeasurementType> FUSION_STRATEGY_ID;\n      KalmanFilter::MeasurementType FUSION_STRATEGY;\n    } CONFIG;\n    std::shared_ptr<KalmanFilter> kalman_filter_ptr_;\n    KalmanFilter::Measurement current_measurement_;\n    \n    Eigen::Matrix4f current_gnss_pose_ = Eigen::Matrix4f::Identity();\n    Eigen::Matrix4f init_pose_ = Eigen::Matrix4f::Identity(); \n    Eigen::Matrix4f current_pose_ = Eigen::Matrix4f::Identity();\n    Eigen::Vector3f current_vel_ = Eigen::Vector3f::Zero();\n    KalmanFilter::Cov current_cov_;\n};\n\n} // namespace lidar_localization\n\n#endif // LIDAR_LOCALIZATION_FILTERING_GNSS_INS_SIM_FILTERING_HPP_", "meta": {"hexsha": "f35a3af037d659e056c661933b3ca80a18664ca0", "size": 2469, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "FILTER/07-filtering-advanced/src/lidar_localization/include/lidar_localization/filtering/gnss_ins_sim_filtering.hpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-03-19T05:51:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T06:10:16.000Z", "max_issues_repo_path": "08-graph-optimization/sensor-fusion-for-localization-and-mapping/workspace/assignments/08-graph-optimization/src/lidar_localization/include/lidar_localization/filtering/gnss_ins_sim_filtering.hpp", "max_issues_repo_name": "WeihengXia0123/LiDar-SLAM", "max_issues_repo_head_hexsha": "834060da7ee0125cefd310d6215821551bac16c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "08-graph-optimization/sensor-fusion-for-localization-and-mapping/workspace/assignments/08-graph-optimization/src/lidar_localization/include/lidar_localization/filtering/gnss_ins_sim_filtering.hpp", "max_forks_repo_name": "WeihengXia0123/LiDar-SLAM", "max_forks_repo_head_hexsha": "834060da7ee0125cefd310d6215821551bac16c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T12:31:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T17:12:44.000Z", "avg_line_length": 29.0470588235, "max_line_length": 88, "alphanum_fraction": 0.7355204536, "num_tokens": 663, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929104825007, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4052229479671293}}
{"text": "#define EIGEN_DEFAULT_DENSE_INDEX_TYPE int32_t\n\n#include \"../repos/stl_reader/stl_reader.h\"\n#include <array>\n#include <deque>\n#include <chrono>\n#include <random>\n#include <fstream>\n#include <iostream>\n#include <Eigen/Dense>\n\n\nusing Triangle = std::array<Eigen::Vector3f, 3u>;\nusing CudaTriangle = Eigen::Vector3f*;\nusing CudaConstTriangle = Eigen::Vector3f const*;\nusing Triangles = std::deque<Triangle>;\n\nconstexpr float   cgEpsilon        = 0.00001f;       // TODO consider if uniform epsilon suits all needs.\nconstexpr uint32_t cgSignumZero     = 0u;\nconstexpr uint32_t cgSignumPlus     = 1u;\nconstexpr uint32_t cgSignumMinus    = 2u;\nconstexpr uint32_t cgSignumShift0   = 0u;\nconstexpr uint32_t cgSignumShift1   = 2u;\nconstexpr uint32_t cgSignumShift2   = 4u;\nconstexpr uint32_t cgSignumAllZero  = (cgSignumZero  << cgSignumShift0) | (cgSignumZero  << cgSignumShift1) | (cgSignumZero  << cgSignumShift2);\nconstexpr uint32_t cgSignumAllPlus  = (cgSignumPlus  << cgSignumShift0) | (cgSignumPlus  << cgSignumShift1) | (cgSignumPlus  << cgSignumShift2);\nconstexpr uint32_t cgSignumAllMinus = (cgSignumMinus << cgSignumShift0) | (cgSignumMinus << cgSignumShift1) | (cgSignumMinus << cgSignumShift2);\n\nconstexpr uint32_t cgSignumSelect0a = (cgSignumPlus  << cgSignumShift0) | (cgSignumMinus << cgSignumShift1) | (cgSignumMinus << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect0b = (cgSignumMinus << cgSignumShift0) | (cgSignumPlus  << cgSignumShift1) | (cgSignumPlus  << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect0c = (cgSignumZero  << cgSignumShift0) | (cgSignumPlus  << cgSignumShift1) | (cgSignumPlus  << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect0d = (cgSignumZero  << cgSignumShift0) | (cgSignumMinus << cgSignumShift1) | (cgSignumMinus << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect0e = (cgSignumPlus  << cgSignumShift0) | (cgSignumZero  << cgSignumShift1) | (cgSignumZero  << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect0f = (cgSignumMinus << cgSignumShift0) | (cgSignumZero  << cgSignumShift1) | (cgSignumZero  << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect0g = (cgSignumZero  << cgSignumShift0) | (cgSignumPlus  << cgSignumShift1) | (cgSignumMinus << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect0h = (cgSignumZero  << cgSignumShift0) | (cgSignumMinus << cgSignumShift1) | (cgSignumPlus  << cgSignumShift2);\n\nconstexpr uint32_t cgSignumSelect1a = (cgSignumPlus  << cgSignumShift1) | (cgSignumMinus << cgSignumShift0) | (cgSignumMinus << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect1b = (cgSignumMinus << cgSignumShift1) | (cgSignumPlus  << cgSignumShift0) | (cgSignumPlus  << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect1c = (cgSignumZero  << cgSignumShift1) | (cgSignumPlus  << cgSignumShift0) | (cgSignumPlus  << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect1d = (cgSignumZero  << cgSignumShift1) | (cgSignumMinus << cgSignumShift0) | (cgSignumMinus << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect1e = (cgSignumPlus  << cgSignumShift1) | (cgSignumZero  << cgSignumShift0) | (cgSignumZero  << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect1f = (cgSignumMinus << cgSignumShift1) | (cgSignumZero  << cgSignumShift0) | (cgSignumZero  << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect1g = (cgSignumZero  << cgSignumShift1) | (cgSignumPlus  << cgSignumShift0) | (cgSignumMinus << cgSignumShift2);\nconstexpr uint32_t cgSignumSelect1h = (cgSignumZero  << cgSignumShift1) | (cgSignumMinus << cgSignumShift0) | (cgSignumPlus  << cgSignumShift2);\n\n// Otherwise select 2, no need for checking and thus no constants.\n\nconstexpr uint32_t cgSignumCircumferenceA = (cgSignumZero << cgSignumShift0) | (cgSignumPlus << cgSignumShift1) | (cgSignumPlus << cgSignumShift2);\nconstexpr uint32_t cgSignumCircumferenceB = (cgSignumZero << cgSignumShift0) | (cgSignumZero << cgSignumShift1) | (cgSignumPlus << cgSignumShift2);\nconstexpr uint32_t cgSignumCircumferenceC = (cgSignumPlus << cgSignumShift0) | (cgSignumZero << cgSignumShift1) | (cgSignumPlus << cgSignumShift2);\nconstexpr uint32_t cgSignumCircumferenceD = (cgSignumPlus << cgSignumShift0) | (cgSignumZero << cgSignumShift1) | (cgSignumZero << cgSignumShift2);\nconstexpr uint32_t cgSignumCircumferenceE = (cgSignumPlus << cgSignumShift0) | (cgSignumPlus << cgSignumShift1) | (cgSignumZero << cgSignumShift2);\nconstexpr uint32_t cgSignumCircumferenceF = (cgSignumZero << cgSignumShift0) | (cgSignumPlus << cgSignumShift1) | (cgSignumZero << cgSignumShift2);\n\nconstexpr uint32_t calculateSignum(float const distances[3]) noexcept {\n  uint32_t result = 0u;\n  for(int32_t i = 0; i < 3; ++i) {\n    int32_t tmp = cgSignumZero;\n    if(distances[i] > cgEpsilon) {\n      tmp = cgSignumPlus;\n    }\n    else if(distances[i] < -cgEpsilon) {\n      tmp = cgSignumMinus;\n    }\n    else { // nothing to do\n    }\n    result |= tmp << (cgSignumShift1 * i);\n  }\n  return result;\n}\n\nvoid calculateNormals(Eigen::Vector2f const aShape[3], Eigen::Vector2f aNormals[3]) noexcept {\n  Eigen::Vector2f side = aShape[1] - aShape[0];\n  aNormals[0](0) = -side(1);\n  aNormals[0](1) = side(0);\n  float correction = 1.0f;\n  if(aNormals[0].dot(aShape[2]) < 0.0f) {\n    correction = -1.0f;                     // They shall point towards the interior.\n    aNormals[0] *= correction;\n  }\n  else { // nothing to do\n  }\n  side = aShape[2] - aShape[1];\n  aNormals[1](0) = -side(1) * correction;\n  aNormals[1](1) = side(0) * correction;\n  side = aShape[0] - aShape[2];\n  aNormals[2](0) = -side(1) * correction;\n  aNormals[2](1) = side(0) * correction;\n}\n\nbool doesTouchOther(uint32_t const aSignums) noexcept {\n  bool result = (aSignums == cgSignumAllPlus\n  || aSignums == cgSignumCircumferenceA\n  || aSignums == cgSignumCircumferenceB\n  || aSignums == cgSignumCircumferenceC\n  || aSignums == cgSignumCircumferenceD\n  || aSignums == cgSignumCircumferenceE\n  || aSignums == cgSignumCircumferenceF);\nif(result) std::cout << \"coplanar circumference or interior\\n\";\n  return result;\n}\n\nbool checkCornerOnPerimeterAndInterior(Eigen::Vector2f aShape1[3], Eigen::Vector2f aShape2[3]) noexcept {\n  Eigen::Vector2f normals1[3]; // i : i->(i+1)%3\n  Eigen::Vector2f normals2[3];\n  calculateNormals(aShape1, normals1); // Normal vectors point to the center.\n  calculateNormals(aShape2, normals2);\n  bool result = false;\n  for(int32_t indexCorner = 0; indexCorner < 3; ++indexCorner) {\n    float distancesCornerFromEachSideOfShape1[3];\n    float distancesCornerFromEachSideOfShape2[3];\n    for(int32_t indexSide = 0; indexSide < 3; ++indexSide) {\n      distancesCornerFromEachSideOfShape2[indexSide] = normals2[indexSide].dot(aShape1[indexCorner] - aShape2[indexSide]);\n      distancesCornerFromEachSideOfShape1[indexSide] = normals1[indexSide].dot(aShape2[indexCorner] - aShape1[indexSide]);\n    }\n    result = result || doesTouchOther(calculateSignum(distancesCornerFromEachSideOfShape2));\n    result = result || doesTouchOther(calculateSignum(distancesCornerFromEachSideOfShape1));   // True if one corner is on the sides, corners or interior of the other triangle.\n    // Don't break out since it won't use on CUDA.\n  }\n  return result;\n}\n    \nbool checkTrueIntersecitonOfSides(Eigen::Vector2f aShape1[3], Eigen::Vector2f aShape2[3]) noexcept {\n  bool result = false;\n  for(int32_t indexSide1 = 0; indexSide1 < 3; ++indexSide1) {\n    for(int32_t indexSide2 = 0; indexSide2 < 3; ++indexSide2) {\n      Eigen::Vector2f &side1a = aShape1[indexSide1];\n      Eigen::Vector2f &side1b = aShape1[(indexSide1 + 1) % 3];\n      Eigen::Vector2f &side2a = aShape2[indexSide2];\n      Eigen::Vector2f &side2b = aShape2[(indexSide2 + 1) % 3];\n      // Manually solve linear EQ to make sure we have as few branches as possible.\n      uint32_t nonzeroAindex = (fabs(side1a(0) - side1b(0)) > cgEpsilon ? 0 : 1);\n      float a = side1a(nonzeroAindex) - side1b(nonzeroAindex);\n      float b = side2b(nonzeroAindex) - side2a(nonzeroAindex);\n      float c = side1a(1 - nonzeroAindex) - side1b(1 - nonzeroAindex);\n      float d = side2b(1 - nonzeroAindex) - side2a(1 - nonzeroAindex);\n      float determinant = a * d - b * c;\n      if(fabs(determinant) > cgEpsilon) {\n        float k = side1a(nonzeroAindex) - side2a(nonzeroAindex);\n        float l = side1a(1 - nonzeroAindex) - side2a(1 - nonzeroAindex);\n        float v = (l * a - c * k) / determinant;\n        float u = (k - b * v) / a;\nif(u >= 0.0f && u <= 1.0f && v >= 0.0f && v <= 1.0f) std::cout << u << ' ' << v << \" coplanar sides intersect\\n\";\n        result = result || (u >= 0.0f && u <= 1.0f && v >= 0.0f && v <= 1.0f);  // The intersection is inside of both sides.\n      }\n      else { // nothing to do, because the lines are parallel but can't touch each other.\n      }\n    }\n  }\n  return result;\n}\n\nbool hasCommonPoint(CudaConstTriangle const aShape1, CudaConstTriangle const aShape2, Eigen::Vector3f const &aShape1normal, Eigen::Vector3f const &aShape2normal) noexcept { // coplanar\n  Eigen::Vector3f normal;\n  if(aShape1normal.dot(aShape2normal) > 0.0f) {\n    normal = aShape1normal + aShape2normal;\n  }\n  else {\n    normal = aShape1normal - aShape2normal;\n  }\n  int32_t indexX = 1;\n  int32_t indexY = 2;\n  float abs1 = fabs(normal(1)); // Looking for the biggest projection. TODO fabsf for CUDA\n  if(abs1 > fabs(normal(0))) {\n    indexX = 0;\n  }\n  else { // nothing to do\n  }\n  if(fabs(normal(2)) > abs1) {\n    indexX = 0;\n    indexY = 1;\n  }\n  else { // nothing to do\n  }\n  Eigen::Vector2f shape1[3];\n  Eigen::Vector2f shape2[3];\n  for(int32_t i = 0; i < 3; ++i) {\n    shape1[i](0) = aShape1[i](indexX);  // Project 3D triangle to axis-parallel plane.\n    shape1[i](1) = aShape1[i](indexY);\n    shape2[i](0) = aShape2[i](indexX);\n    shape2[i](1) = aShape2[i](indexY);\n  }\n  bool result = checkCornerOnPerimeterAndInterior(shape1, shape2);\n  if(!result) { // Common point may only occur now when sides truly intersect each other.\n    result = checkTrueIntersecitonOfSides(shape1, shape2);\n  }\n  else { // nothing to do\n  }\n  return result;\n}\n\nvoid calculateIntersectionParameter(\n  CudaConstTriangle const aShape\n, Eigen::Vector3f const &aIntersectionVector\n, float const aDistanceCornerNfromOtherPlane[3]\n, uint32_t const aSignumShapeFromOtherPlane\n, float &aIntersectionParameterA\n, float &aIntersectionParameterB) noexcept {\n  int32_t indexCommon, indexA, indexB;\n  if(aSignumShapeFromOtherPlane == cgSignumSelect0a\n  || aSignumShapeFromOtherPlane == cgSignumSelect0b\n  || aSignumShapeFromOtherPlane == cgSignumSelect0c\n  || aSignumShapeFromOtherPlane == cgSignumSelect0d\n  || aSignumShapeFromOtherPlane == cgSignumSelect0e\n  || aSignumShapeFromOtherPlane == cgSignumSelect0f\n  || aSignumShapeFromOtherPlane == cgSignumSelect0g\n  || aSignumShapeFromOtherPlane == cgSignumSelect0h) {\n    indexCommon = 0; indexA = 1; indexB = 2;\n  }\n  else if(aSignumShapeFromOtherPlane == cgSignumSelect1a\n  || aSignumShapeFromOtherPlane == cgSignumSelect1b\n  || aSignumShapeFromOtherPlane == cgSignumSelect1c\n  || aSignumShapeFromOtherPlane == cgSignumSelect1d\n  || aSignumShapeFromOtherPlane == cgSignumSelect1e\n  || aSignumShapeFromOtherPlane == cgSignumSelect1f\n  || aSignumShapeFromOtherPlane == cgSignumSelect1g\n  || aSignumShapeFromOtherPlane == cgSignumSelect1h) {\n    indexCommon = 1; indexA = 0; indexB = 2;\n  }\n  else {\n    indexCommon = 2; indexA = 1; indexB = 0;\n  }\n  float vertexProjections[3];\n  for(int32_t i = 0; i < 3; ++i) {\n    vertexProjections[i] = aIntersectionVector.dot(aShape[i]);\n  }\n  aIntersectionParameterA = \n   vertexProjections[indexA]\n + (vertexProjections[indexCommon] - vertexProjections[indexA])\n * aDistanceCornerNfromOtherPlane[indexA]\n / (aDistanceCornerNfromOtherPlane[indexA] - aDistanceCornerNfromOtherPlane[indexCommon]);\n  aIntersectionParameterB = \n   vertexProjections[indexB]\n + (vertexProjections[indexCommon] - vertexProjections[indexB])\n * aDistanceCornerNfromOtherPlane[indexB]\n / (aDistanceCornerNfromOtherPlane[indexB] - aDistanceCornerNfromOtherPlane[indexCommon]);\n}\n\nbool hasCommonPoint(CudaConstTriangle const aShape1, CudaConstTriangle const aShape2) noexcept { // Entry point for common point check.\n  bool result = false;\n  Eigen::Vector3f shape1normal = (aShape1[1] - aShape1[0]).cross(aShape1[2] - aShape1[0]);\n  Eigen::Vector3f shape2normal = (aShape2[1] - aShape2[0]).cross(aShape2[2] - aShape2[0]);\n  shape1normal.normalize();\n  shape2normal.normalize();\n  float distanceCornerNofShape1FromPlane2[3];\n  float distanceCornerNofShape2FromPlane1[3];\n  for(int32_t i = 0; i < 3; ++i) {\n    distanceCornerNofShape1FromPlane2[i] = shape2normal.dot(aShape1[i] - aShape2[0]);\n    distanceCornerNofShape2FromPlane1[i] = shape1normal.dot(aShape2[i] - aShape1[0]);\n  }\n  uint32_t signumShape1FromPlane2 = calculateSignum(distanceCornerNofShape1FromPlane2); // These contain info about relation of each point and the other plane.\n  uint32_t signumShape2FromPlane1 = calculateSignum(distanceCornerNofShape2FromPlane1);\n  if(signumShape1FromPlane2 == cgSignumAllPlus || signumShape1FromPlane2 == cgSignumAllMinus || signumShape2FromPlane1 == cgSignumAllPlus || signumShape2FromPlane1 == cgSignumAllMinus) {\n    // Nothing to do: one triangle is completely on the one side of the other's plane\n  }\n  else {\n    Eigen::Vector3f intersectionVector = shape1normal.cross(shape2normal);\n    if(intersectionVector.norm() > cgEpsilon && signumShape1FromPlane2 != cgSignumAllZero && signumShape2FromPlane1 != cgSignumAllZero) { // Real intersection, planes are not identical, and both triangles touch the common line.\n      intersectionVector.normalize();\n      float intersectionParameterAshape1;\n      float intersectionParameterBshape1;\n      float intersectionParameterAshape2;\n      float intersectionParameterBshape2;\n      calculateIntersectionParameter(aShape1, intersectionVector, distanceCornerNofShape1FromPlane2, signumShape1FromPlane2, intersectionParameterAshape1, intersectionParameterBshape1); // The two parameters will contain the locations of the touching point.\n      calculateIntersectionParameter(aShape2, intersectionVector, distanceCornerNofShape2FromPlane1, signumShape2FromPlane1, intersectionParameterAshape2, intersectionParameterBshape2);\n      if(intersectionParameterAshape1 > intersectionParameterBshape1) {\n        std::swap(intersectionParameterAshape1, intersectionParameterBshape1);\n      }\n      else { // nothing to do\n      }\n      if(intersectionParameterAshape2 > intersectionParameterBshape2) {\n        std::swap(intersectionParameterAshape2, intersectionParameterBshape2);\n      }\n      else { // nothing to do\n      }\n      if(intersectionParameterAshape1 - cgEpsilon <= intersectionParameterAshape2 && intersectionParameterAshape2 <= intersectionParameterBshape1 + cgEpsilon // Epsilons make possible to check for triangles with corner-corner or corner-edge touch.\n      || intersectionParameterAshape1 - cgEpsilon <= intersectionParameterBshape2 && intersectionParameterBshape2 <= intersectionParameterBshape1 + cgEpsilon\n      || intersectionParameterAshape2 - cgEpsilon <= intersectionParameterAshape1 && intersectionParameterAshape1 <= intersectionParameterBshape2 + cgEpsilon\n      || intersectionParameterAshape2 - cgEpsilon <= intersectionParameterBshape1 && intersectionParameterBshape1 <= intersectionParameterBshape2 + cgEpsilon) {\nstd::cout << \"on intersecting line\\n\";\n        result = true;\n      }\n      else { // nothing to do\n      }\n    }\n    else {\n      result = hasCommonPoint(aShape1, aShape2, shape1normal, shape2normal); // Coplanar triangles\n    }\n  }\n  return result;\n}\n\nEigen::Matrix3f randomTransform() {\n  std::default_random_engine generator;\n  generator.seed((std::chrono::high_resolution_clock::now() - std::chrono::high_resolution_clock::time_point::min()).count());\n  std::uniform_real_distribution<float> distribution(0.0f, 1.0f);\n  Eigen::Matrix3f result;\n  for(int32_t i = 0; i < 9; ++i) {\n    result(i / 3, i % 3) = distribution(generator);\n  }\n  return result;\n}\n\nTriangles readTriangles(char const * const aFilename, Eigen::Matrix3f const &aTransform) {\n  Triangles result;\n  stl_reader::StlMesh<float, int32_t> mesh(aFilename);\n  for(int32_t indexTriangle = 0; indexTriangle < mesh.num_tris(); ++indexTriangle) {\n      Triangle triangle;\n      for(int32_t indexCorner = 0; indexCorner < 3; ++indexCorner) {\n          float const * const coords = mesh.tri_corner_coords(indexTriangle, indexCorner);\n          Eigen::Vector3f in;\n          for(int32_t i = 0; i < 3; ++i) {\n            in(i) = coords[i];\n          }\n          triangle[indexCorner] = aTransform * in;\n      }\n      result.push_back(triangle);\n  }\n  return result;\n}\n\nvoid writeTriangles(Triangles const &aTriangles, char const * const aFilename) {\n  std::ofstream out(aFilename);\n  out << \"solid Exported from Blender-2.82 (sub 7)\\n\";\n  for(auto const & triangle : aTriangles) {\n//    Eigen::Vector3f normal = (triangle[1] - triangle[0]).cross(aShape2[2] - aShape2[0]);\n//  shape1normal.normalize();\n    out << \"facet normal 0.000000 0.000000 0.000000\\nouter loop\\n\";\n    for(auto const & vertex : triangle) {\n      out << \"vertex \" << vertex(0) << ' ' << vertex(1) << ' ' << vertex(2) << '\\n';\n    }\n    out << \"endloop\\nendfacet\\n\";\n  }\n  out << \"endsolid Exported from Blender-2.82 (sub 7)\\n\";\n}\n\nvoid check(Triangles const &aTriangles) {\n  for(int32_t i = 0; i < aTriangles.size(); ++i) {\n    for(int32_t j = i + 1; j < aTriangles.size(); ++j) {\n      if(hasCommonPoint(aTriangles[i].data(), aTriangles[j].data())) {\n        std::cout << \"Has common point: \" << i << ' ' << j << \"\\n\\n\";\n      }\n      else { // nothing to do\n      }\n    }\n  }\n}\n\nint main(int argc, char **argv) {\n  int ret = 0;\n  if(argc < 2) {\n    std::cerr << \"Usage: \" << argv[0] << \" <filenameIn> [filenameOut]\\n\";\n    ret = 1;\n  }\n  else {\n    try {\n      auto transform = randomTransform();\n      auto triangles = readTriangles(argv[1], transform);\n      if(argc >= 3) {\n        writeTriangles(triangles, argv[2]);\n      }\n      else { // nothing to do\n      }\n      check(triangles);\n    }\n    catch(std::exception &e) {\n      ret = 2;\n    }\n  }\n  return ret;\n}\n", "meta": {"hexsha": "626204145ad38265be42b1a76595a366dea59ab7", "size": 18037, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tmp/first.cpp", "max_stars_repo_name": "balazs-bamer/link-intersection-brute-force", "max_stars_repo_head_hexsha": "1098d5555ebaa9c23c326f75c493b855199ff6bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-27T10:40:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T10:40:50.000Z", "max_issues_repo_path": "tmp/first.cpp", "max_issues_repo_name": "balazs-bamer/link-intersection-brute-force", "max_issues_repo_head_hexsha": "1098d5555ebaa9c23c326f75c493b855199ff6bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-04-27T16:05:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-28T11:52:39.000Z", "max_forks_repo_path": "tmp/first.cpp", "max_forks_repo_name": "balazs-bamer/link-intersection-brute-force", "max_forks_repo_head_hexsha": "1098d5555ebaa9c23c326f75c493b855199ff6bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.3565683646, "max_line_length": 257, "alphanum_fraction": 0.7136441759, "num_tokens": 5566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7799929002541067, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.40522294265326053}}
{"text": "#include \"stdafx.h\"\n\n#include \"problem.hpp\"\n#include \"utility.hpp\"\n\n#include <fstream>\n#include <regex>\n#include <utility>\n#include <unordered_map>\n#include <unordered_set>\n#include <numeric>\n#include <boost/algorithm/string.hpp>\n\nstruct advent_2017_15 : problem\n{\n\tadvent_2017_15() noexcept : problem(2017, 15) {\n\t}\n\nprotected:\n\tstruct generator\n\t{\n\t\tstd::string name;\n\t\tuint64_t seed;\n\t\tuint64_t factor;\n\t\tuint64_t current;\n\n\t\tgenerator(const std::string& name_, uint64_t seed_, uint64_t factor_) : name(name_), seed(seed_), factor(factor_), current(seed_) {\n\t\t}\n\n\t\tuint16_t generate(uint64_t divisor) noexcept {\n\t\t\tfor(;;) {\n\t\t\t\tconst uint64_t product = current * factor;\n\t\t\t\tcurrent = product % 2'147'483'647ui64;\n\t\t\t\tif((current % divisor) == 0ui64) {\n\t\t\t\t\treturn current & 0xffff;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid reset() noexcept {\n\t\t\tcurrent = seed;\n\t\t}\n\t};\n\n\tstd::unique_ptr<generator> a;\n\tstd::unique_ptr<generator> b;\n\n\tvoid prepare_input(std::ifstream& fin) override {\n\t\tstd::regex pattern(R\"(Generator ([[:upper:]]) starts with ([[:digit:]]*))\");\n\t\tstd::string line;\n\t\tstd::getline(fin, line);\n\t\tstd::smatch m;\n\t\tstd::regex_search(line, m, pattern);\n\t\ta = std::make_unique<generator>(m[1], std::stoul(m[2]), 16'807);\n\t\tstd::getline(fin, line);\n\t\tstd::regex_search(line, m, pattern);\n\t\tb = std::make_unique<generator>(m[1], std::stoul(m[2]), 48'271);\n\t}\n\n\tstd::string part_1() override {\n\t\tstd::size_t pairs = 0;\n\t\tfor(std::size_t i = 0; i < 40'000'000; ++i) {\n\t\t\tpairs += a->generate(1) == b->generate(1);\n\t\t}\n\t\treturn std::to_string(pairs);\n\t}\n\n\tvoid tidy_up() noexcept override {\n\t\ta->reset();\n\t\tb->reset();\n\t}\n\n\tstd::string part_2() override {\n\t\tstd::size_t pairs = 0;\n\t\tfor(std::size_t i = 0; i < 5'000'000; ++i) {\n\t\t\tpairs += a->generate(4) == b->generate(8);\n\t\t}\n\t\treturn std::to_string(pairs);\n\t}\n};\n\nREGISTER_SOLVER(2017, 15);\n", "meta": {"hexsha": "46fe43b536095d3ed045a7f42f15eb9dc8cb528c", "size": 1838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aoc/src/2017/day-15.cpp", "max_stars_repo_name": "DrPizza/advent-of-code-2017", "max_stars_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_stars_repo_licenses": ["Zlib"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-09T06:13:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-18T12:15:08.000Z", "max_issues_repo_path": "aoc/src/2017/day-15.cpp", "max_issues_repo_name": "DrPizza/advent-of-code-2017", "max_issues_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_issues_repo_licenses": ["Zlib"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-03T17:46:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-03T17:46:56.000Z", "max_forks_repo_path": "aoc/src/2017/day-15.cpp", "max_forks_repo_name": "DrPizza/advent-of-code", "max_forks_repo_head_hexsha": "bcba170e3ffececb9c5b29f3b0fa0193fa59dcf9", "max_forks_repo_licenses": ["Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.1445783133, "max_line_length": 133, "alphanum_fraction": 0.6441784548, "num_tokens": 577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4050846961713026}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__FEEDBACK__OCP_HPP_\n#define SMOOTH__FEEDBACK__OCP_HPP_\n\n/**\n * @file\n * @brief Optimal control problem definition.\n */\n\n#include <Eigen/Core>\n#include <smooth/diff.hpp>\n#include <smooth/lie_group.hpp>\n\n#include <iostream>\n\n#include \"traits.hpp\"\n\nnamespace smooth::feedback {\n\n// \\cond\n// Forward declaration\ntemplate<LieGroup _X, Manifold _U, int _Nq, int _Ncr, int _Nce>\nstruct OCPSolution;\n// \\endcond\n\n/**\n * @brief Optimal control problem definition\n * @tparam _X state space\n * @tparam _U input space\n *\n * Problem is defined on the interval \\f$ t \\in [0, t_f] \\f$.\n * \\f[\n * \\begin{cases}\n *  \\min              & \\theta(t_f, x_0, x_f, q)                                         \\\\\n *  \\text{s.t.}       & x(0) = x_0                                                       \\\\\n *                    & x(t_f) = x_f                                                     \\\\\n *                    & \\dot x(t) = f(t, x(t), u(t))                                     \\\\\n *                    & q = \\int_{0}^{t_f} g(t, x(t), u(t)) \\mathrm{d}t                  \\\\\n *                    & c_{rl} \\leq c_r(t, x(t), u(t)) \\leq c_{ru} \\quad t \\in [0, t_f]  \\\\\n *                    & c_{el} \\leq c_e(t_f, x_0, x_f, q) \\leq c_{eu}\n * \\end{cases}\n * \\f]\n *\n * The optimal control problem depends on arbitrary functions \\f$ \\theta, f, g, c_r, c_e \\f$.\n * The type of those functions are template pararamters in this structure.\n *\n * @note To enable automatic differentiation \\f$ \\theta, f, g, c_r, c_e \\f$ must be templated over\n * the scalar type.\n */\ntemplate<LieGroup _X, Manifold _U, typename Theta, typename F, typename G, typename CR, typename CE>\nstruct OCP\n{\n  /// @brief State space\n  using X = _X;\n  /// @brief Input space\n  using U = _U;\n\n  /// @brief State space dimension\n  static constexpr int Nx = Dof<X>;\n  /// @brief Input space dimension\n  static constexpr int Nu = Dof<U>;\n  /// @brief Number of integrals\n  static constexpr int Nq = std::invoke_result_t<G, double, X, U>::SizeAtCompileTime;\n  /// @brief Number of running constraints\n  static constexpr int Ncr = std::invoke_result_t<CR, double, X, U>::SizeAtCompileTime;\n  /// @brief Number of end constraints\n  static constexpr int Nce =\n    std::invoke_result_t<CE, double, X, X, Eigen::Matrix<double, Nq, 1>>::SizeAtCompileTime;\n\n  /// @brief Solution type corresponding to this problem\n  using Solution = OCPSolution<X, U, Nq, Ncr, Nce>;\n\n  static_assert(Nx > 0, \"Static size required\");\n  static_assert(Nu > 0, \"Static size required\");\n  static_assert(Nq > 0, \"Static size required\");\n  static_assert(Ncr > 0, \"Static size required\");\n  static_assert(Nce > 0, \"Static size required\");\n\n  /// @brief Objective function \\f$ \\theta : R \\times X \\times X \\times R^{n_q} \\rightarrow R \\f$\n  Theta theta;\n\n  /// @brief System dynamics \\f$ f : R \\times X \\times U \\rightarrow Tangent<X> \\f$\n  F f;\n  /// @brief Integrals \\f$ g : R \\times X \\times U \\rightarrow R^{n_q} \\f$\n  G g;\n\n  /// @brief Running constraint \\f$ c_r : R \\times X \\times U \\rightarrow R^{n_{cr}} \\f$\n  CR cr;\n  /// @brief Running constraint lower bound \\f$ c_{rl} \\in R^{n_{cr}} \\f$\n  Eigen::Vector<double, Ncr> crl = Eigen::Vector<double, Ncr>::Zero();\n  /// @brief Running constraint upper bound \\f$ c_{ru} \\in R^{n_{cr}} \\f$\n  Eigen::Vector<double, Ncr> cru = Eigen::Vector<double, Ncr>::Zero();\n\n  /// @brief End constraint \\f$ c_e : R \\times X \\times X \\times R^{n_q} \\rightarrow R^{n_{ce}} \\f$\n  CE ce;\n  /// @brief End constraint lower bound \\f$ c_{el} \\in R^{n_{ce}} \\f$\n  Eigen::Vector<double, Nce> cel = Eigen::Vector<double, Nce>::Zero();\n  /// @brief End constraint upper bound \\f$ c_{eu} \\in R^{n_{ce}} \\f$\n  Eigen::Vector<double, Nce> ceu = Eigen::Vector<double, Nce>::Zero();\n};\n\n/// @brief Concept that is true for OCP specializations\ntemplate<typename T>\nconcept OCPType = traits::is_specialization_of_v<std::decay_t<T>, OCP>;\n\n/// @brief Concept that is true for FlatOCP specializations\ntemplate<typename T>\nconcept FlatOCPType = OCPType<T> &&(smooth::traits::RnType<typename std::decay_t<T>::X> &&\n                                      smooth::traits::RnType<typename std::decay_t<T>::U>);\n\n/**\n * @brief Solution to OCP.\n */\ntemplate<LieGroup _X, Manifold _U, int _Nq, int _Ncr, int _Nce>\nstruct OCPSolution\n{\n  /// @brief State space\n  using X = _X;\n  /// @brief Input space\n  using U = _U;\n\n  /// @brief Number of integrals\n  static constexpr int Nq = _Nq;\n  /// @brief Number of running constraints\n  static constexpr int Ncr = _Ncr;\n  /// @brief Number of end constraints\n  static constexpr int Nce = _Nce;\n\n  ///@{\n  /// @brief Initial and final time\n  double t0, tf;\n  //}@\n\n  /// @brief Integral values\n  Eigen::Vector<double, Nq> Q{};\n\n  ///@{\n  /// @brief Callable functions for state and input\n  std::function<U(double)> u;\n  std::function<X(double)> x;\n  //}@\n\n  /// @brief Multipliers for integral constraints\n  Eigen::Vector<double, Nq> lambda_q{};\n\n  /// @brief Multipliers for endpoint constraints\n  Eigen::Vector<double, Nce> lambda_ce{};\n\n  /// @brief Multipliers for dynamics equality constraint\n  std::function<Eigen::Vector<double, Dof<X>>(double)> lambda_dyn{};\n\n  /// @brief Multipliers for active running constraints\n  std::function<Eigen::Vector<double, Ncr>(double)> lambda_cr{};\n};\n\n/**\n * @brief Test analytic derivatives for an OCP problem.\n *\n * @tparam DT differentiation method to compare against.\n *\n * @param ocp problem to test derivatives for\n * @param num_trials number of random points to test\n *\n * @todo Make it possible to test a subset of derivatives\n */\ntemplate<diff::Type DT = diff::Type::Numerical>\nbool test_ocp_derivatives(OCPType auto & ocp, uint32_t num_trials = 1, double eps = 1e-4)\n{\n  using OCP = std::decay_t<decltype(ocp)>;\n\n  using X = typename OCP::X;\n  using U = typename OCP::U;\n  using Q = Eigen::Vector<double, OCP::Nq>;\n\n  if (!diff::detail::diffable_order1<decltype(ocp.theta), std::tuple<double, X, X, Q>>) {\n    std::cout << \"no jacobian for theta\\n\";\n  }\n  if (!diff::detail::diffable_order2<decltype(ocp.theta), std::tuple<double, X, X, Q>>) {\n    std::cout << \"no hessian for theta\\n\";\n  }\n  if (!diff::detail::diffable_order1<decltype(ocp.f), std::tuple<double, X, U>>) {\n    std::cout << \"no jacobian for f\\n\";\n  }\n  if (!diff::detail::diffable_order2<decltype(ocp.f), std::tuple<double, X, U>>) {\n    std::cout << \"no hessian for f\\n\";\n  }\n  if (!diff::detail::diffable_order1<decltype(ocp.g), std::tuple<double, X, U>>) {\n    std::cout << \"no jacobian for g\\n\";\n  }\n  if (!diff::detail::diffable_order2<decltype(ocp.g), std::tuple<double, X, U>>) {\n    std::cout << \"no hessian for g\\n\";\n  }\n  if (!diff::detail::diffable_order1<decltype(ocp.cr), std::tuple<double, X, U>>) {\n    std::cout << \"no jacobian for cr\\n\";\n  }\n  if (!diff::detail::diffable_order2<decltype(ocp.cr), std::tuple<double, X, U>>) {\n    std::cout << \"no hessian for cr\\n\";\n  }\n  if (!diff::detail::diffable_order1<decltype(ocp.ce), std::tuple<double, X, X, Q>>) {\n    std::cout << \"no jacobian for ce\\n\";\n  }\n  if (!diff::detail::diffable_order2<decltype(ocp.ce), std::tuple<double, X, X, Q>>) {\n    std::cout << \"no hessian for ce\\n\";\n  }\n\n  const auto cmp = [&eps](const auto & m1, const auto & m2) {\n    return (\n      // clang-format off\n      (m1.cols() == m2.cols())\n      && (m1.rows() == m2.rows())\n      && (\n          m1.isApprox(m2, 1e-4) ||\n          Eigen::MatrixXd(m1 - m2).cwiseAbs().maxCoeff() < eps\n      )\n      // clang-format on\n    );\n  };\n\n  bool success = true;\n\n  for (auto trial = 0u; trial < num_trials; ++trial) {\n    // endpt parameters\n    const double tf                        = 1 + static_cast<double>(std::rand()) / RAND_MAX;\n    const X x0                             = Random<X>();\n    const X xf                             = Random<X>();\n    const Eigen::Vector<double, OCP::Nq> q = Eigen::Vector<double, OCP::Nq>::Random();\n    const double t                         = 1 + static_cast<double>(std::rand()) / RAND_MAX;\n    const X x                              = Random<X>();\n    const U u                              = Random<U>();\n\n    // theta\n    if constexpr (diff::detail::diffable_order1<decltype(ocp.theta), std::tuple<double, X, X, Q>>) {\n      const auto [f_def, df_def] = diff::dr<1, diff::Type::Analytic>(ocp.theta, wrt(tf, x0, xf, q));\n      const auto [f_num, df_num] = diff::dr<1, DT>(ocp.theta, wrt(tf, x0, xf, q));\n\n      if (!cmp(df_def, df_num)) {\n        std::cout << \"Error in 1st derivative of theta: got\\n\"\n                  << Eigen::MatrixXd(df_def) << \"\\nbut expected\\n\"\n                  << Eigen::MatrixXd(df_num) << '\\n';\n        success = false;\n      };\n    }\n    if constexpr (diff::detail::diffable_order2<decltype(ocp.theta), std::tuple<double, X, X, Q>>) {\n      const auto [f_def, df_def, d2f_def] =\n        diff::dr<2, diff::Type::Analytic>(ocp.theta, wrt(tf, x0, xf, q));\n      const auto [f_num, df_num, d2f_num] = diff::dr<2, DT>(ocp.theta, wrt(tf, x0, xf, q));\n\n      if (!cmp(d2f_def, d2f_num)) {\n        std::cout << \"Error in 2nd derivative of theta: got\\n\"\n                  << Eigen::MatrixXd(d2f_def) << \"\\nbut expected\\n\"\n                  << Eigen::MatrixXd(d2f_num) << '\\n';\n        success = false;\n      };\n    }\n\n    // end constraints\n    if constexpr (diff::detail::diffable_order1<decltype(ocp.ce), std::tuple<double, X, X, Q>>) {\n      const auto [f_def, df_def] = diff::dr<1, diff::Type::Analytic>(ocp.ce, wrt(tf, x0, xf, q));\n      const auto [f_num, df_num] = diff::dr<1, DT>(ocp.ce, wrt(tf, x0, xf, q));\n\n      if (!cmp(df_def, df_num)) {\n        std::cout << \"Error in 1st derivative of ce: got\\n\"\n                  << Eigen::MatrixXd(df_def) << \"\\nbut expected\\n\"\n                  << Eigen::MatrixXd(df_num) << '\\n';\n        success = false;\n      };\n    }\n    if constexpr (diff::detail::diffable_order2<decltype(ocp.ce), std::tuple<double, X, X, Q>>) {\n      const auto [f_def, df_def, d2f_def] =\n        diff::dr<2, diff::Type::Analytic>(ocp.ce, wrt(tf, x0, xf, q));\n      const auto [f_num, df_num, d2f_num] = diff::dr<2, DT>(ocp.ce, wrt(tf, x0, xf, q));\n\n      if (!cmp(d2f_def, d2f_num)) {\n        std::cout << \"Error in 2nd derivative of ce: got\\n\"\n                  << Eigen::MatrixXd(d2f_def) << \"\\nbut expected\\n\"\n                  << Eigen::MatrixXd(d2f_num) << '\\n';\n        success = false;\n      };\n    }\n\n    // dynamics\n    if constexpr (diff::detail::diffable_order1<decltype(ocp.f), std::tuple<double, X, U>>) {\n      const auto [f_def, df_def] = diff::dr<1, diff::Type::Analytic>(ocp.f, wrt(t, x, u));\n      const auto [f_num, df_num] = diff::dr<1, DT>(ocp.f, wrt(t, x, u));\n      if (!cmp(df_def, df_num)) {\n        std::cout << \"Error in 1st derivative of f: got\\n\"\n                  << Eigen::MatrixXd(df_def) << \"\\nbut expected\\n\"\n                  << Eigen::MatrixXd(df_num) << '\\n';\n        success = false;\n      };\n    }\n    if constexpr (diff::detail::diffable_order2<decltype(ocp.f), std::tuple<double, X, U>>) {\n      const auto [f_def, df_def, d2f_def] = diff::dr<2, diff::Type::Analytic>(ocp.f, wrt(t, x, u));\n      const auto [f_num, df_num, d2f_num] = diff::dr<2, DT>(ocp.f, wrt(t, x, u));\n      if (!cmp(d2f_def, d2f_num)) {\n        std::cout << \"Error in 2nd derivative of f: got\\n\"\n                  << Eigen::MatrixXd(d2f_def) << \"\\nbut expected\\n\"\n                  << Eigen::MatrixXd(d2f_num) << '\\n';\n        success = false;\n      };\n    }\n\n    // integrand\n    if constexpr (diff::detail::diffable_order1<decltype(ocp.g), std::tuple<double, X, U>>) {\n      const auto [f_def, df_def] = diff::dr<1, diff::Type::Analytic>(ocp.g, wrt(t, x, u));\n      const auto [f_num, df_num] = diff::dr<1, DT>(ocp.g, wrt(t, x, u));\n      if (!cmp(df_def, df_num)) {\n        std::cout << \"Error in 1st derivative of g: got\\n\"\n                  << Eigen::MatrixXd(df_def) << \"\\nbut expected\\n\"\n                  << Eigen::MatrixXd(df_num) << '\\n';\n        success = false;\n      };\n    }\n    if constexpr (diff::detail::diffable_order2<decltype(ocp.g), std::tuple<double, X, U>>) {\n      const auto [f_def, df_def, d2f_def] = diff::dr<2, diff::Type::Analytic>(ocp.g, wrt(t, x, u));\n      const auto [f_num, df_num, d2f_num] = diff::dr<2, DT>(ocp.g, wrt(t, x, u));\n      if (!cmp(d2f_def, d2f_num)) {\n        std::cout << \"Error in 2nd derivative of g: got\\n\"\n                  << Eigen::MatrixXd(d2f_def) << \"\\nbut expected\\n\"\n                  << Eigen::MatrixXd(d2f_num) << '\\n';\n        success = false;\n      };\n    }\n\n    // running constraints\n    if constexpr (diff::detail::diffable_order1<decltype(ocp.cr), std::tuple<double, X, U>>) {\n      const auto [f_def, df_def] = diff::dr<1, diff::Type::Analytic>(ocp.cr, wrt(t, x, u));\n      const auto [f_num, df_num] = diff::dr<1, DT>(ocp.cr, wrt(t, x, u));\n      if (!cmp(df_def, df_num)) {\n        std::cout << \"Error in 1st derivative of cr: got\\n\"\n                  << Eigen::MatrixXd(df_def) << \"\\nbut expected\\n\"\n                  << Eigen::MatrixXd(df_num) << '\\n';\n        success = false;\n      };\n    }\n    if constexpr (diff::detail::diffable_order2<decltype(ocp.cr), std::tuple<double, X, U>>) {\n      const auto [f_def, df_def, d2f_def] = diff::dr<2, diff::Type::Analytic>(ocp.cr, wrt(t, x, u));\n      const auto [f_num, df_num, d2f_num] = diff::dr<2, DT>(ocp.cr, wrt(t, x, u));\n      if (!cmp(d2f_def, d2f_num)) {\n        std::cout << \"Error in 2nd derivative of cr: got\\n\"\n                  << Eigen::MatrixXd(d2f_def) << \"\\nbut expected\\n\"\n                  << Eigen::MatrixXd(d2f_num) << '\\n';\n        success = false;\n      };\n    }\n  }\n\n  return success;\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__OCP_HPP_\n", "meta": {"hexsha": "cb5a87dc13faf5e644e6dde942e83f712362d27b", "size": 14916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/ocp.hpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/smooth/feedback/ocp.hpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smooth/feedback/ocp.hpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4603174603, "max_line_length": 100, "alphanum_fraction": 0.5925181014, "num_tokens": 4423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629465, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.4050846961713026}}
{"text": "#include <cstdio>\n#include <cstdlib>\n\n#include <iostream>\n\n#include <armadillo>\n\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char* argv[]) {\n  if (argc < 3) {\n    cerr << \"Usage: \" << argv[0] << \" num-particles rand-seed\\n\";\n    return EXIT_FAILURE;\n  }\n\n  const size_t num_particles = atoi(argv[1]);\n  \n  const ulong rand_seed = strtoul(argv[2], nullptr, 10);\n  clog << \"Using random seed: \" << rand_seed << \"\\n\";\n  srand(rand_seed);\n\n  const double sigma = pow(2.0, 1.0 / 6.0);\n  mat::fixed<3, 3> L = 40.0 * sigma * eye(3, 3);\n  L.save(\"cell.mat\", arma::csv_ascii);\n  \n  mat x = randu<mat>(3, num_particles);\n  mat r = L * x;\n  r.save(\"positions.mat\", arma::csv_ascii);\n  \n  vec q = 2e1 * randu<vec>(num_particles);\n  // vec q = ones<vec>(num_particles);\n  for (size_t n = 0; n < num_particles; ++n) if (n % 3 != 0) q[n] = 0.0;\n  q.save(\"charges.mat\", arma::csv_ascii);\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "4410ecfb2ed4485a7d52efd02c2c115ee2e42dbb", "size": 917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "make-box.cpp", "max_stars_repo_name": "jmbr/libpme6", "max_stars_repo_head_hexsha": "2e81cacdf941c8114615363fbae59d7f06742838", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2015-07-21T14:46:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-25T20:38:43.000Z", "max_issues_repo_path": "make-box.cpp", "max_issues_repo_name": "jmbr/libpme6", "max_issues_repo_head_hexsha": "2e81cacdf941c8114615363fbae59d7f06742838", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-13T20:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-15T23:08:34.000Z", "max_forks_repo_path": "make-box.cpp", "max_forks_repo_name": "jmbr/libpme6", "max_forks_repo_head_hexsha": "2e81cacdf941c8114615363fbae59d7f06742838", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-03-07T10:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T22:34:01.000Z", "avg_line_length": 24.1315789474, "max_line_length": 72, "alphanum_fraction": 0.6106870229, "num_tokens": 305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461390043208004, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.40505146958865373}}
{"text": "#define NPY_NO_DEPRECATED_API NPY_1_11_API_VERSION\n\n#include <iostream>\n#include <stdint.h>\n#include <alloca.h>\n#include <omp.h>\n#include <Eigen/Core>\n#include <Python.h>\n#include <numpy/ndarrayobject.h>\n\nusing namespace Eigen;\nusing namespace std;\n\nstatic double extract_double(PyArrayObject *arr, int i) {\n    return ((double*) PyArray_DATA(arr))[i];\n}\n\nstatic double extract_double_2d(PyArrayObject *arr, int i, int j) {\n    return ((double*) PyArray_DATA(arr))[i * PyArray_DIM(arr, 1) + j];\n}\n\nstatic double extract_int64_t(PyArrayObject *arr, int i) {\n    return ((int64_t*) PyArray_DATA(arr))[i];\n}\n\nvoid capsule_cleanup(PyObject *capsule) {\n    void *memory = PyCapsule_GetPointer(capsule, NULL);\n    delete memory;\n}\n\nstatic PyObject* run(PyObject * module, PyObject * args) {\n    //TODO: check if parameters are null.\n    //TODO: check that dicts have the required members.\n    //TODO: check that all parameters have the right sizes.\n    //TODO: i'm not sending any error messages.\n    import_array();\n    \n    PyObject *data_ptr = NULL, *model_ptr = NULL, *fwd_msgs = NULL;\n    PyArrayObject *alldata = NULL, *allresources = NULL, *starts = NULL, *lengths = NULL, *learns = NULL, *forgets = NULL, *guesses = NULL, *slips = NULL, *forward_messages = NULL;\n    double prior;\n    int parallel;\n\n    if (!PyArg_ParseTuple(args, \"OOOi\", &data_ptr, &model_ptr, &fwd_msgs, &parallel)) {\n        PyErr_SetString(PyExc_ValueError, \"Error parsing arguments.\");\n        return NULL;\n    }\n\n    if (!parallel)\n        omp_set_num_threads(1);\n\n    int DTYPE = PyArray_ObjectType(fwd_msgs, NPY_FLOAT);\n    forward_messages = (PyArrayObject *)PyArray_FROM_OTF(fwd_msgs, DTYPE, NPY_ARRAY_IN_ARRAY);\n\n    char* DM_NAMES[] = {\"data\", \"resources\", \"starts\", \"lengths\", \"learns\", \"forgets\", \"guesses\", \"slips\"};\n    PyArrayObject** DM_PTRS[] = {&alldata, &allresources, &starts, &lengths, &learns, &forgets, &guesses, &slips};\n    for (int i = 0; i < 8; i++) {\n        PyObject *dp = PyDict_GetItemString(i < 4 ? data_ptr : model_ptr, DM_NAMES[i]);\n        DTYPE = PyArray_ObjectType(dp, (i < 4 ? (i < 1 ? NPY_INT : NPY_INT64) : NPY_FLOAT)); // hack to force correct type\n        *DM_PTRS[i] = (PyArrayObject *)PyArray_FROM_OTF(dp, DTYPE, NPY_ARRAY_IN_ARRAY);\n    }\n    prior = PyFloat_AsDouble(PyDict_GetItemString(model_ptr, \"prior\"));\n\n    int bigT = (int) PyArray_DIM(alldata, 1), num_subparts = (int) PyArray_DIM(alldata, 0);\n    int len_allresources = (int) PyArray_DIM(allresources, 0);\n    int num_sequences = (int) PyArray_DIM(starts, 0);\n    int len_lengths = (int) PyArray_DIM(lengths, 0);\n    int num_resources = (int) PyArray_DIM(learns, 0);\n\n    Array2d initial_distn;\n    initial_distn << 1-prior, prior;\n\n    MatrixXd As(2,2*num_resources);\n    for (int n=0; n<num_resources; n++) {\n        double learn = extract_double(learns, n);\n        double forget = extract_double(forgets, n);\n        As.col(2*n) << 1-learn, learn;\n        As.col(2*n+1) << forget, 1-forget;\n    }\n\n    // forward messages\n    //numpy::ndarray all_forward_messages = extract<numpy::ndarray>(forward_messages);\n    double * forward_messages_temp = new double[2*bigT];\n    for (int i=0; i<2; i++) {\n        for (int j=0; j<bigT; j++){\n            forward_messages_temp[i* bigT +j] = extract_double_2d(forward_messages, i, j);\n        }\n    }\n\n    //// outputs\n\n    double* all_predictions = new double[2 * bigT];\n    Map<Array2Xd,Aligned> predictions(all_predictions,2,bigT);\n\n    /* COMPUTATION */\n\n    #pragma omp parallel for\n    for (int sequence_index=0; sequence_index < num_sequences; sequence_index++) {\n        // NOTE: -1 because Matlab indexing starts at 1\n        int64_t sequence_start = extract_int64_t(starts, sequence_index) - 1;\n        int64_t T = extract_int64_t(lengths, sequence_index);\n\n        //int16_t *resources = allresources + sequence_start;\n        Map<MatrixXd, Aligned> forward_messages(forward_messages_temp + 2*sequence_start,2,T);\n        Map<MatrixXd, Aligned> predictions(all_predictions + 2*sequence_start,2,T);\n\n        predictions.col(0) = initial_distn;\n        for (int t=0; t<T-1; t++) {\n            int64_t resources_temp = extract_int64_t(allresources, sequence_start + t);\n            predictions.col(t+1) = As.block(0,2*(resources_temp-1),2,2) * forward_messages.col(t);\n        }\n    }\n\n    npy_intp dims[] = {2, bigT};\n    PyObject *all_predictions_arr = (PyObject *) PyArray_SimpleNewFromData(2, dims, NPY_DOUBLE, all_predictions);\n    PyObject *capsule = PyCapsule_New(all_predictions, NULL, capsule_cleanup);\n    PyArray_SetBaseObject((PyArrayObject *) all_predictions_arr, capsule);\n\n    for (int i = 0; i < 8; i++)\n        Py_XDECREF(*DM_PTRS[i]);\n    Py_XDECREF(forward_messages);\n\n    return(all_predictions_arr);\n}\n\nstatic PyMethodDef predict_onestep_states_Methods[] = {\n    {\"run\",  run, METH_VARARGS,\n     \"Generates predictions for BKT model\"},\n    {NULL, NULL, 0, NULL}        /* Sentinel */\n};\n\n\nstatic struct PyModuleDef predict_onestep_states_module = {\n   PyModuleDef_HEAD_INIT,\n   \"predict_onestep_states\",   /* name of module */\n   NULL, /* module documentation, may be NULL */\n   -1,       /* size of per-interpreter state of the module,\n                or -1 if the module keeps state in global variables. */\n   predict_onestep_states_Methods\n};\n\nPyMODINIT_FUNC PyInit_predict_onestep_states() {\n    return PyModule_Create(&predict_onestep_states_module);\n}\n\n", "meta": {"hexsha": "5be1aa1fe8e9f2d333c43a72a79fd7975b865a7a", "size": 5408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-cpp/pyBKT/fit/predict_onestep_states.cpp", "max_stars_repo_name": "bukeplato/pyBKT", "max_stars_repo_head_hexsha": "733a4ccf0de78bef7d47b5a6af7131c7778560db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 132.0, "max_stars_repo_stars_event_min_datetime": "2018-03-22T06:04:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T21:54:27.000Z", "max_issues_repo_path": "source-cpp/pyBKT/fit/predict_onestep_states.cpp", "max_issues_repo_name": "bukeplato/pyBKT", "max_issues_repo_head_hexsha": "733a4ccf0de78bef7d47b5a6af7131c7778560db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-01-10T14:00:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T04:00:47.000Z", "max_forks_repo_path": "source-cpp/pyBKT/fit/predict_onestep_states.cpp", "max_forks_repo_name": "bukeplato/pyBKT", "max_forks_repo_head_hexsha": "733a4ccf0de78bef7d47b5a6af7131c7778560db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2017-09-12T04:30:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T08:54:52.000Z", "avg_line_length": 37.2965517241, "max_line_length": 180, "alphanum_fraction": 0.6727071006, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7461389930307512, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.40505146345970056}}
{"text": "#ifndef BOOST_SAFE_NUMERICS_INTERVAL_HPP\n#define BOOST_SAFE_NUMERICS_INTERVAL_HPP\n\n//  Copyright (c) 2012 Robert Ramey\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <limits>\n#include <cassert>\n#include <type_traits>\n#include <initializer_list>\n#include <algorithm> // minmax, min, max\n\n#include <boost/logic/tribool.hpp>\n\n#include \"utility.hpp\" // log\n\n#include \"concept/integer.hpp\"\n\n// from stack overflow\n// http://stackoverflow.com/questions/23815138/implementing-variadic-min-max-functions\n\nnamespace boost {\nnamespace safe_numerics {\n\ntemplate<typename R>\nstruct interval {\n    const R l;\n    const R u;\n\n    template<typename T>\n    constexpr interval(const T & lower, const T & upper) :\n        l(lower),\n        u(upper)\n    {\n        // assert(static_cast<bool>(l <= u));\n    }\n    template<typename T>\n    constexpr interval(const std::pair<T, T> & p) :\n        l(p.first),\n        u(p.second)\n    {}\n    template<class T>\n    constexpr interval(const interval<T> & rhs) :\n        l(rhs.l),\n        u(rhs.u)\n    {}\n    constexpr interval() :\n        l(std::numeric_limits<R>::min()),\n        u(std::numeric_limits<R>::max())\n    {}\n    // return true if this interval contains the given point\n    constexpr tribool includes(const R & t) const {\n        return l <= t && t <= u;\n    }\n    // if this interval contains every point found in some other inteval t\n    //  return true\n    // otherwise\n    //  return false or indeterminate\n    constexpr tribool includes(const interval<R> & t) const {\n        return u >= t.u && l <= t.l;\n    }\n\n    // return true if this interval contains the given point\n    constexpr tribool excludes(const R & t) const {\n        return t < l || t > u;\n    }\n    // if this interval excludes every point found in some other inteval t\n    //  return true\n    // otherwise\n    //  return false or indeterminate\n    constexpr tribool excludes(const interval<R> & t) const {\n        return t.u < l || u < t.l;\n    }\n\n};\n\ntemplate<class R>\nconstexpr inline interval<R> make_interval(){\n    return interval<R>();\n}\ntemplate<class R>\nconstexpr  inline interval<R> make_interval(const R &){\n    return interval<R>();\n}\n\n// account for the fact that for floats and doubles\n// the most negative value is called \"lowest\" rather\n// than min\ntemplate<>\nconstexpr inline interval<float>::interval() :\n    l(std::numeric_limits<float>::lowest()),\n    u(std::numeric_limits<float>::max())\n{}\ntemplate<>\nconstexpr inline interval<double>::interval() :\n    l(std::numeric_limits<double>::lowest()),\n    u(std::numeric_limits<double>::max())\n{}\n\ntemplate<typename T>\nconstexpr inline interval<T> operator+(const interval<T> & t, const interval<T> & u){\n    // adapted from https://en.wikipedia.org/wiki/Interval_arithmetic\n    return {t.l + u.l, t.u + u.u};\n}\n\ntemplate<typename T>\nconstexpr inline interval<T> operator-(const interval<T> & t, const interval<T> & u){\n    // adapted from https://en.wikipedia.org/wiki/Interval_arithmetic\n    return {t.l - u.u, t.u - u.l};\n}\n\ntemplate<typename T>\nconstexpr inline interval<T> operator*(const interval<T> & t, const interval<T> & u){\n    // adapted from https://en.wikipedia.org/wiki/Interval_arithmetic\n    return utility::minmax<T>(\n        std::initializer_list<T> {\n            t.l * u.l,\n            t.l * u.u,\n            t.u * u.l,\n            t.u * u.u\n        }\n    );\n}\n\n// interval division\n// note: presumes 0 is not included in the range of the denominator\ntemplate<typename T>\nconstexpr inline interval<T> operator/(const interval<T> & t, const interval<T> & u){\n    assert(static_cast<bool>(u.excludes(T(0))));\n    return utility::minmax<T>(\n        std::initializer_list<T> {\n            t.l / u.l,\n            t.l / u.u,\n            t.u / u.l,\n            t.u / u.u\n        }\n    );\n}\n\n// modulus of two intervals.  This will give a new range of for the modulus.\n// note: presumes 0 is not included in the range of the denominator\ntemplate<typename T>\nconstexpr inline interval<T> operator%(const interval<T> & t, const interval<T> & u){\n    assert(static_cast<bool>(u.excludes(T(0))));\n    return utility::minmax<T>(\n        std::initializer_list<T> {\n            t.l % u.l,\n            t.l % u.u,\n            t.u % u.l,\n            t.u % u.u\n        }\n    );\n}\n\ntemplate<typename T>\nconstexpr inline interval<T> operator<<(const interval<T> & t, const interval<T> & u){\n    static_assert(\n        boost::safe_numerics::Integer<T>::value,\n        \"left shift only defined for integral type\"\n    );\n    //return interval<T>{t.l << u.l, t.u << u.u};\n    return utility::minmax<T>(\n        std::initializer_list<T> {\n            t.l << u.l,\n            t.l << u.u,\n            t.u << u.l,\n            t.u << u.u\n        }\n    );\n}\n\ntemplate<typename T>\nconstexpr inline interval<T> operator>>(const interval<T> & t, const interval<T> & u){\n    static_assert(\n        boost::safe_numerics::Integer<T>::value,\n        \"right shift only defined for integral type\"\n    );\n    //return interval<T>{t.l >> u.u, t.u >> u.l};\n    return utility::minmax<T>(\n        std::initializer_list<T> {\n            t.l >> u.l,\n            t.l >> u.u,\n            t.u >> u.l,\n            t.u >> u.u\n        }\n    );\n}\n\n// union of two intervals\ntemplate<typename T>\nconstexpr interval<T> operator|(const interval<T> & t, const interval<T> & u){\n    const T & rl = std::min(t.l, u.l);\n    const T & ru = std::max(t.u, u.u);\n    return interval<T>(rl, ru);\n}\n\n// intersection of two intervals\ntemplate<typename T>\nconstexpr inline interval<T> operator&(const interval<T> & t, const interval<T> & u){\n    const T & rl = std::max(t.l, u.l);\n    const T & ru = std::min(t.u, u.u);\n    return interval<T>(rl, ru);\n}\n\n// determine whether two intervals intersect\ntemplate<typename T>\nconstexpr inline boost::logic::tribool intersect(const interval<T> & t, const interval<T> & u){\n    return t.u >= u.l || t.l <= u.u;\n}\n\ntemplate<typename T>\nconstexpr inline boost::logic::tribool operator<(\n    const interval<T> & t,\n    const interval<T> & u\n){\n    return\n        // if every element in t is less than every element in u\n        t.u < u.l ? boost::logic::tribool(true):\n        // if every element in t is greater than every element in u\n        t.l > u.u ? boost::logic::tribool(false):\n        // otherwise some element(s) in t are greater than some element in u\n        boost::logic::indeterminate\n    ;\n}\n\ntemplate<typename T>\nconstexpr inline boost::logic::tribool operator>(\n    const interval<T> & t,\n    const interval<T> & u\n){\n    return\n        // if every element in t is greater than every element in u\n        t.l > u.u ? boost::logic::tribool(true) :\n        // if every element in t is less than every element in u\n        t.u < u.l ? boost::logic::tribool(false) :\n        // otherwise some element(s) in t are greater than some element in u\n        boost::logic::indeterminate\n    ;\n}\n\ntemplate<typename T>\nconstexpr inline bool operator==(\n    const interval<T> & t,\n    const interval<T> & u\n){\n    // intervals have the same limits\n    return t.l == u.l && t.u == u.u;\n}\n\ntemplate<typename T>\nconstexpr inline bool operator!=(\n    const interval<T> & t,\n    const interval<T> & u\n){\n    return ! (t == u);\n}\n\ntemplate<typename T>\nconstexpr inline boost::logic::tribool operator<=(\n    const interval<T> & t,\n    const interval<T> & u\n){\n    return ! (t > u);\n}\n\ntemplate<typename T>\nconstexpr inline boost::logic::tribool operator>=(\n    const interval<T> & t,\n    const interval<T> & u\n){\n    return ! (t < u);\n}\n\n} // safe_numerics\n} // boost\n\n#include <iosfwd>\n\nnamespace std {\n\ntemplate<typename CharT, typename Traits, typename T>\ninline std::basic_ostream<CharT, Traits> &\noperator<<(\n    std::basic_ostream<CharT, Traits> & os,\n    const boost::safe_numerics::interval<T> & i\n){\n    return os << '[' << i.l << ',' << i.u << ']';\n}\ntemplate<typename CharT, typename Traits>\ninline std::basic_ostream<CharT, Traits> &\noperator<<(\n    std::basic_ostream<CharT, Traits> & os,\n    const boost::safe_numerics::interval<unsigned char> & i\n){\n    os << \"[\" << (unsigned)i.l << \",\" << (unsigned)i.u << \"]\";\n    return os;\n}\n\ntemplate<typename CharT, typename Traits>\ninline std::basic_ostream<CharT, Traits> &\noperator<<(\n    std::basic_ostream<CharT, Traits> & os,\n    const boost::safe_numerics::interval<signed char> & i\n){\n    os << \"[\" << (int)i.l << \",\" << (int)i.u << \"]\";\n    return os;\n}\n\n} // std\n\n#endif // BOOST_SAFE_NUMERICS_INTERVAL_HPP\n", "meta": {"hexsha": "4f715dbe1cce45ac586b5ef6c5ab4adb30e3f5c5", "size": 8555, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/safe_numerics/interval.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 57.0, "max_stars_repo_stars_event_min_datetime": "2018-01-13T12:19:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T14:35:09.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/safe_numerics/interval.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2018-07-02T05:33:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-30T13:39:38.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/safe_numerics/interval.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2018-01-11T18:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-21T20:16:12.000Z", "avg_line_length": 27.1587301587, "max_line_length": 95, "alphanum_fraction": 0.6136762127, "num_tokens": 2179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4049846167001816}}
{"text": "#ifndef LINEAR_SOLVERS_HPP\n#define LINEAR_SOLVERS_HPP\n\n#include \"compressed_sensing.hpp\"\n#include <boost/shared_ptr.hpp>\n\nnamespace Pecos {\n\nvoid normalise_columns( RealMatrix &A, RealVector &result );\n\nclass LinearSolver\n{\nprotected:\n\n  RealVector residualTols_;\n\n  int maxIters_;\n\n  int verbosity_;\n\n  bool normaliseInputs_;\n\n  Real solverTol_;\n  \n  Real conjugateGradientTol_;\n\n  int numPrimaryEqs_;\n\npublic:\n\n  LinearSolver() : \n    maxIters_(std::numeric_limits<int>::max()), verbosity_(0),\n    normaliseInputs_(false), solverTol_(1.e-6), conjugateGradientTol_(-1.), \n    numPrimaryEqs_( -1 )\n  { residualTols_.size( 1 ); };\n\n  ~LinearSolver()\n  {\n    clear();\n  };\n\n  void clear()\n  {\n    maxIters_ = std::numeric_limits<int>::max();\n    verbosity_ = 0; solverTol_ = 1.e-6; conjugateGradientTol_ = -1.;\n    numPrimaryEqs_ = -1; residualTols_.size( 1 );\n  }\n\n  /**\n   * \\brief Find a regularized solution to AX = B\n   */\n  virtual void solve( RealMatrix &A, RealMatrix &B, RealMatrix &result_0, \n\t\t      RealMatrix &result_1 )\n  {\n    std::string msg = \"solve() Has not been implemented for \";\n    msg += \"this class.\";\n    throw( std::runtime_error( msg ) );\n  };\n  \n  virtual void solve_using_points( RealMatrix &build_points, RealMatrix &B, \n\t\t\t\t   RealMatrix &result_0, \n\t\t\t\t   RealMatrix &result_1 )\n  {\n    std::string msg = \"solve_using_points() Has not been implemented for \";\n    msg += \"this class.\";\n    throw( std::runtime_error( msg ) );\n  };\n\n  void set_verbosity( int verbosity )\n  {\n    verbosity_ = verbosity;\n  };\n  \n  void set_residual_tolerance( Real tolerance )\n  {\n    RealVector residual_tols( 1, false );\n    residual_tols[0] = tolerance;\n    set_residual_tolerances( residual_tols );\n  };\n\n  void set_residual_tolerances( const RealVector &residual_tols )\n  {\n    residualTols_.sizeUninitialized( residual_tols.length() );\n    residualTols_.assign( residual_tols );\n  };\n\n\n  void set_solver_tolerance( Real tolerance )\n  {\n    solverTol_  = tolerance;\n  };\n\n  void set_conjugate_gradient_tolerance( Real tolerance )\n  {\n    conjugateGradientTol_  = tolerance;\n  };\n\n  void set_num_primary_equations( int num_primary_eqs )\n  {\n    numPrimaryEqs_  = num_primary_eqs;\n  };\n\n  Real get_residual_tolerance()\n  {\n    return residualTols_[0];\n  };\n\n  void get_residual_tolerances( RealVector &result_0 )\n  {\n    result_0.sizeUninitialized( residualTols_.length() );\n    result_0.assign( residualTols_ );\n  };\n\n  void set_max_iters( int max_iters )\n  {\n    maxIters_ = max_iters;\n  };\n\n  void set_normalise_inputs( bool normalise )\n  {\n    normaliseInputs_ = normalise;\n  };\n\n  void copy( const LinearSolver &source )\n  {\n    set_residual_tolerances( source.residualTols_ );\n    set_max_iters( source.maxIters_ );\n    set_verbosity( source.verbosity_ );\n  };\n\n  void normalise_columns( RealMatrix &A, RealVector &result )\n  {\n    int M = A.numRows(), N = A.numCols();\n    result.sizeUninitialized( N );\n    for ( int i = 0; i < N; i++ )\n      {\n\tRealVector col( Teuchos::View, A[i], M );\n\tresult[i] = col.normFrobenius();\n\tcol.scale(1./result[i]);\n      }\n  };\n\n  void adjust_coefficients( const RealVector &normalisation_factors, \n\t\t\t    RealMatrix &coefficients )\n  {\n    int num_coeff = coefficients.numRows(), num_qoi = coefficients.numCols();\n    for ( int i = 0; i < num_qoi; i++ )\n      {\n\tfor ( int j = 0; j < num_coeff; j++ )\n\t  coefficients(j,i) /= normalisation_factors[j];\n      } \n  };\n\n  /**\n   * For adaptive methods such as orthogonal least interpolation\n   * it is sometimes necessary to reconstruct the Matrix A of Ax=b\n   * for instance when performing cross validation\n   */\n  virtual void build_matrix( const RealMatrix &build_points,\n\t\t\t     RealMatrix &result_0 )\n  {\n    std::string msg = \"linear_solver::build_matrix() Not implemented.\";\n    throw( std::runtime_error( msg ) );\n  }\n};\n\nclass BPSolver : public LinearSolver\n{\nprotected:\n\npublic:\n\n  BPSolver(){};\n\n  ~BPSolver(){};\n\n  /**\n   * \\brief Find the solution min ||x||_0 such that |AX = B||_2 == 0\n   */\n  void solve( RealMatrix &A, RealMatrix &B, RealMatrix &result_0, \n\t      RealMatrix &result_1 )\n  {\n    if ( B.numCols() != 1 )\n      throw( std::runtime_error(\" BPSolver::solve() B must be a vector\") );\n\n    RealVector b( Teuchos::View, B[0], B.numRows() );\n    RealMatrix A_copy( A );\n\n    RealVector column_norms;\n    if ( normaliseInputs_ )\n      normalise_columns( A_copy, column_norms );\n\n    BP_primal_dual_interior_point_method( A_copy, b, \n\t\t\t\t\t  result_0, \n\t\t\t\t\t  solverTol_, \n\t\t\t\t\t  conjugateGradientTol_,\n\t\t\t\t\t  verbosity_ );\n\n    if ( normaliseInputs_ )\n      adjust_coefficients( column_norms, result_0 );\n\n    result_1.shapeUninitialized( 2, 1 );\n    result_1(0,0) = 0.;\n    int num_non_zeros = 0;\n    for ( int i = 0; i < result_0.numRows(); i++ )\n      if ( std::abs( result_0(i,0) ) > std::numeric_limits<double>::epsilon() )\n\tnum_non_zeros++;\n    result_1(1,0) = num_non_zeros;\n  };\n};\n\nclass BPDNSolver : public LinearSolver\n{ \npublic:\n  \n  BPDNSolver(){};\n  \n  ~BPDNSolver(){};\n\n  /**\n   * \\brief Find the solution min ||x||_0 such that |AX = B||_2 < eps\n   */\n  void solve( RealMatrix &A, RealMatrix &B, RealMatrix &result_0, \n\t      RealMatrix &result_1 )\n  {\n    if ( residualTols_.length() <= 0 )\n      throw( std::runtime_error(\" BPDNSolver::solve() set residual tols\") );\n\n    if ( B.numCols() != 1 )\n      throw( std::runtime_error(\" BPDNSolver::solve() B must be a vector\") );\n\n    RealVector b( Teuchos::View, B[0], B.numRows() );\n    RealMatrix A_copy( A );\n\n    RealVector column_norms;\n    if ( normaliseInputs_ )\n      normalise_columns( A_copy, column_norms );\n\n    result_0.shapeUninitialized( A.numCols(), residualTols_.length() );\n    result_1.shapeUninitialized( 2, residualTols_.length() );\n    for ( int j = 0; j < residualTols_.length(); j++ )\n      {\n\tRealMatrix x;\n\tBPDN_log_barrier_interior_point_method( A_copy, b, \n\t\t\t\t\t\tx, \n\t\t\t\t\t\tresidualTols_[j],\n\t\t\t\t\t\tsolverTol_, \n\t\t\t\t\t\tconjugateGradientTol_,\n\t\t\t\t\t\tverbosity_ );\n\t\n\tif ( normaliseInputs_ )\n\t  adjust_coefficients( column_norms, x );\n\t\n\tresult_1(0,j) = residualTols_[j];\n\tint num_non_zeros = 0;\n\tfor ( int i = 0; i < result_0.numRows(); i++ )\n\t  {\n\t    if ( std::abs( x(i,0) ) > std::numeric_limits<double>::epsilon() )\n\t      num_non_zeros++;\n\t    result_0(i,j) = x(i,0);\n\t  }\n\tresult_1(1,j) = num_non_zeros;\n      }\n  };\n};\n\nclass OMPSolver : public LinearSolver\n{\nprotected:\n  IntVector ordering_; // enforce a set of columns to be chosen first\n\npublic:\n\n  OMPSolver(){};\n\n  ~OMPSolver(){};\n\n  /**\n   * \\brief Find the solution min ||x||_0 such that |AX = B||_2 < eps\n   */\n  void solve( RealMatrix &A, RealMatrix &B, RealMatrix &result_0, \n\t      RealMatrix &result_1 )\n  {\n    if ( B.numCols() != 1 )\n      throw( std::runtime_error(\" OMPSolver::solve() B must be a vector\") );\n\n    RealVector b( Teuchos::View, B[0], B.numRows() );\n    RealMatrix A_copy( A );\n\n    RealVector column_norms;\n    if ( normaliseInputs_ )\n      normalise_columns( A_copy, column_norms );\n\n    orthogonal_matching_pursuit( A_copy, b, result_0, result_1, \n\t\t\t\t residualTols_[0], maxIters_, verbosity_,\n\t\t\t\t ordering_ );\n\n    if ( normaliseInputs_ )\n      adjust_coefficients( column_norms, result_0 );\n  };\n\n  void set_ordering( IntVector &ordering )\n  {\n    ordering_.resize( ordering.length() );\n    ordering_.assign( ordering );\n  };\n};\n\nclass LARSSolver : public LinearSolver\n{\nprivate:\n\n  int solver_;\n  \n  Real delta_;\n\npublic:\n  LARSSolver() : solver_( LEAST_ANGLE_REGRESSION ), delta_( 0.0 ){};\n\n  ~LARSSolver(){clear();};\n\n  void clear()\n  {\n    LinearSolver::clear();\n    solver_ = LEAST_ANGLE_REGRESSION; delta_ = 0.0;\n  };\n\n  void set_sub_solver( int solver_id )\n  {\n    if ( ( solver_id != LASSO_REGRESSION ) && \n\t ( solver_id != LEAST_ANGLE_REGRESSION ) )\n      {\n\tstd::stringstream msg;\n\tmsg << \"set_sub_solver() solver id must be either: \" << LASSO_REGRESSION\n\t    << \" or \" << LEAST_ANGLE_REGRESSION << \"\\n\";\n\tthrow( std::runtime_error( msg.str() ) );\n      }\n    solver_ = solver_id;\n  };\n\n  void set_delta( Real delta )\n  {\n    delta_ = delta;\n  }\n\n  /**\n   * \\brief Find the solution min ||x||_0 such that |AX = B||_2 < eps\n   */\n  void solve( RealMatrix &A, RealMatrix &B, RealMatrix &result_0, \n\t      RealMatrix &result_1 )\n  {\n    if ( B.numCols() != 1 )\n      throw( std::runtime_error(\" LARSSolver::solve() B must be a vector\") );\n\n    RealVector b( Teuchos::View, B[0], B.numRows() );\n    RealMatrix A_copy( A );\n    \n    RealVector column_norms;\n    if ( normaliseInputs_ )\n      normalise_columns( A_copy, column_norms );\n\n    least_angle_regression( A_copy, b, result_0, result_1, \n\t\t\t    residualTols_[0], solver_, delta_, \n\t\t\t    maxIters_, verbosity_ );\n\n    if ( normaliseInputs_ )\n      adjust_coefficients( column_norms, result_0 );\n  };\n};\n\nclass COSAMPSolver : public LinearSolver\n{\nprivate:\n  int sparsity_;\n\npublic:\n  COSAMPSolver() : sparsity_( 0 ) {};\n\n  ~COSAMPSolver(){clear();};\n\n  void clear()\n  {\n    LinearSolver::clear();\n    sparsity_ = 0;\n  };\n\n  void set_sparsity( int sparsity )\n  {\n    sparsity_ = sparsity;\n  }\n\n  /**\n   * \\brief Find the solution min ||x||_0 such that |AX = B||_2 < eps\n   */\n  void solve( RealMatrix &A, RealMatrix &B, RealMatrix &result_0, \n\t      RealMatrix &result_1 )\n  {\n    if ( B.numCols() != 1 )\n      throw( std::runtime_error(\" COSAMPSolver::solve() B must be a vector\") );\n\n    RealVector b( Teuchos::View, B[0], B.numRows() );\n    RealMatrix A_copy( A );\n    \n    RealVector column_norms;\n    if ( normaliseInputs_ )\n      normalise_columns( A_copy, column_norms );\n\n    cosamp( A_copy, b, result_0, result_1, sparsity_,\n\t    maxIters_, verbosity_ );\n\n    if ( normaliseInputs_ )\n      adjust_coefficients( column_norms, result_0 );\n  };\n};\n\nclass LSQSolver : public LinearSolver\n{\npublic:\n  LSQSolver(){};\n\n  ~LSQSolver(){};\n\n  /**\n   * \\brief Find the solution min ||x||_0 such that |AX = B||_2 < eps\n   */\n  void solve( RealMatrix &A, RealMatrix &B, RealMatrix &result_0, \n\t      RealMatrix &result_1 )\n  {\n    if ( B.numCols() != 1 )\n      throw( std::runtime_error(\"LSQSolver::solve() B must be a vector\") );\n\n   if ( A.numRows() < A.numCols() )\n     std::cout << \"LSQSolver::solve() Warning A is under-determined. \" <<\n       \"M = \" << A.numRows() << \" N = \" << A.numCols() <<\n       \". Returning minimum norm solution\\n\";\n   \n\n    RealVector b( Teuchos::View, B[0], B.numRows() );\n    RealMatrix A_copy( A );\n    \n    RealVector column_norms;\n    if ( normaliseInputs_ )\n      normalise_columns( A_copy, column_norms );\n\n    RealVector singular_values;\n    int rank(0);\n    svd_solve( A_copy, b, result_0, singular_values, rank, \n\t       solverTol_ );\n    \n    result_1.shapeUninitialized( 2, 1 );\n    RealVector residual( b );\n    residual.multiply( Teuchos::NO_TRANS, Teuchos::NO_TRANS, \n\t\t       -1.0, A_copy, result_0, 1.0 );\n    result_1(0,0) = residual.normFrobenius();\n    int num_non_zeros = 0;\n    for ( int i = 0; i < result_0.numRows(); i++ )\n      {\n\tif ( std::abs( result_0(i,0) ) > std::numeric_limits<double>::epsilon() )\n\t  num_non_zeros++;\n      }\n    result_1(1,0) = num_non_zeros;\t  \n\n    if ( normaliseInputs_ )\n      adjust_coefficients( column_norms, result_0 );\n  };\n};\n\nclass EqualityConstrainedLSQSolver : public LinearSolver\n{\n\npublic:\n  EqualityConstrainedLSQSolver(){};\n\n  ~EqualityConstrainedLSQSolver(){};\n\n  /**\n   * \\brief Find the solution min ||x||_0 such that |AX = B||_2 < eps\n   */\n  void solve( RealMatrix &A, RealMatrix &B, RealMatrix &result_0, \n\t      RealMatrix &result_1 )\n  {\n    if ( B.numCols() != 1 )\n      throw( std::runtime_error(\" EqualityConstrainedLSQSolver::solve() B must be a vector\") );\n\n    if ( numPrimaryEqs_ <= 0 )\n      throw( std::runtime_error(\" EqualityConstrainedLSQSolver::solve() set num primary equations\") );\n\n    if ( numPrimaryEqs_ > A.numCols() )\n      throw( std::runtime_error(\" EqualityConstrainedLSQSolver::solve() num primary equations is larger than the number of columns in A\") );\n\n    if ( A.numRows() < A.numCols() )\n      throw( std::runtime_error(\" EqualityConstrainedLSQSolver::solve() A is underdetermined\") );\n\n    RealMatrix A_copy( A );\n    \n    RealVector column_norms;\n    if ( normaliseInputs_ )\n      normalise_columns( A_copy, column_norms );\n\n    RealMatrix C_eq( Teuchos::View, A_copy, numPrimaryEqs_,\n\t\t     A_copy.numCols(), 0, 0 );\n    RealMatrix A_eq( Teuchos::View, A_copy, \n\t\t     A_copy.numRows() - numPrimaryEqs_,\n\t\t     A_copy.numCols(), numPrimaryEqs_, 0 );\n    RealVector d_eq( Teuchos::View, B.values(), numPrimaryEqs_ );\n    RealVector b_eq( Teuchos::View, \n\t\t     B.values() + numPrimaryEqs_, \n\t\t     B.numRows() - numPrimaryEqs_ );\n    equality_constrained_least_squares_solve( A_eq, b_eq, C_eq, d_eq,\n\t\t\t\t\t      result_0 );\n    \n    \n    result_1.shapeUninitialized( 2, 1 );\n    RealVector residual( b_eq );\n    residual.multiply( Teuchos::NO_TRANS, Teuchos::NO_TRANS, \n\t\t       -1.0, A_eq, result_0, 1.0 );\n    result_1(0,0) = residual.normFrobenius();\n    int num_non_zeros = 0;\n    for ( int i = 0; i < result_0.numRows(); i++ )\n      {\n\tif ( std::abs( result_0(i,0) ) > std::numeric_limits<double>::epsilon() )\n\t  num_non_zeros++;\n      }\n    result_1(1,0) = num_non_zeros;\t  \n\n    if ( normaliseInputs_ )\n      adjust_coefficients( column_norms, result_0 );\n  };\n};\n\ntypedef boost::shared_ptr<LinearSolver> LinearSolver_ptr;\n\n/**\n * \\brief Specify a set of options for using the CompressedSensingTool\n */\nclass CompressedSensingOptions\n{\npublic:\n  //solverType solver; //!< Specify which regression solver to use. See solverType\n  short solver; //!< Specify which regression solver to use: see pecos_global_defs\n  Real solverTolerance; //!< Specify the internal tolerance of the solver\n  Real epsilon;         //!< Specify the residual tolerance of the solver\n  Real delta;           //!< Specify the regularization parameter value\n  int maxNumIterations; //!< Specify the maximum number of solver iterations\n  bool standardizeInputs;  //!< Specify if the inputs need to be standardized\n  bool storeHistory;       //<! Specify if the solution history should be stored \n  Real conjugateGradientsTolerance; //<! Specify wether to use conjugate gradients internally to solve newton step in BP and BPDN.  If < 0 cholesky factorization will be used.\n  int verbosity;           //!< The verbosity level. 0: off, 1: warnings on,  2: all print statements on.\n  int numFunctionSamples; //!< The number of function samples used to construct A and B. Used when A contains gradient information. If zero then numFunctionSamples = A.numRows()\n\npublic:\n\n  CompressedSensingOptions() : \n    solver( DEFAULT_LEAST_SQ_REGRESSION ), solverTolerance( -1. ),\n    epsilon( 0.0 ), delta( 0.0 ),\n    maxNumIterations( std::numeric_limits<int>::max() ), \n    standardizeInputs( false ), storeHistory( false ), \n    conjugateGradientsTolerance( -1 ), verbosity( 0 ), numFunctionSamples( 0 )\n  {};\n\n  ~CompressedSensingOptions(){};\n\n  void print()\n  {\n    std::cout << \"Solver: \" << solver << \"\\n\";\n    std::cout << \"Solver Tolerance: \" << solverTolerance << \"\\n\";\n    std::cout << \"Epsilon: \" << epsilon << \"\\n\";\n    std::cout << \"Delta: \" << delta << \"\\n\";\n    std::cout << \"MaxNumIterations: \" << maxNumIterations << \"\\n\";\n    std::cout << \"StandardizeInputs: \" << standardizeInputs << \"\\n\";\n    std::cout << \"StoreHistory: \" << storeHistory << \"\\n\";\n    std::cout << \"Verbosity: \" << verbosity << \"\\n\";\n  };\n\n  CompressedSensingOptions& operator=(const CompressedSensingOptions& source )\n  {\n    if(this == &source)\n      return (*this);\n    solver = source.solver;\n    solverTolerance = source.solverTolerance; \n    epsilon = source.epsilon;         \n    delta = source.delta;\n    maxNumIterations = source.maxNumIterations; \n    standardizeInputs = source.standardizeInputs;\n    storeHistory = source.storeHistory;     \n    conjugateGradientsTolerance = source.conjugateGradientsTolerance; \n    verbosity = source.verbosity;\n    numFunctionSamples = source.numFunctionSamples;\n    return (*this);\n  }\n\n  CompressedSensingOptions( const CompressedSensingOptions& source )\n  {\n    solver = source.solver;\n    solverTolerance = source.solverTolerance; \n    epsilon = source.epsilon;         \n    delta = source.delta;\n    maxNumIterations = source.maxNumIterations; \n    standardizeInputs = source.standardizeInputs;\n    storeHistory = source.storeHistory;     \n    conjugateGradientsTolerance = source.conjugateGradientsTolerance; \n    verbosity = source.verbosity;\n    numFunctionSamples = source.numFunctionSamples;\n  }\n};\n\ntypedef std::vector< std::vector<CompressedSensingOptions> > CompressedSensingOptionsList;\n\n/**\n * \\class CompressedSensingTool\n * \\brief Tool that implements a number of popular compressed sensing algorithms \n */\nclass CompressedSensingTool\n{\nprotected:\n  LinearSolver_ptr linearSolver_;\n\npublic:\n\n  /// Default constructor\n  CompressedSensingTool()\n  {   \n    std::cout.precision( std::numeric_limits<Real>::digits10 );\n    std::cout.setf( std::ios::scientific );\n  };\n\n  // Deconstructor\n  ~CompressedSensingTool(){};\n\n  //! @name Interface tools.\n  //@{ \n\n  /**\n   * \\brief Wrapper to call any of the compressed sensing methods\n   *\n   * \\param A ( M x N ) matrix of the linear system AX=B\n   *\n   * \\param B ( M x num_rhs ) matrix of the linear system AX=B\n   *\n   * \\param solutions (output) vector containing multiple solutions\n   * to AX=B. Each entry in solutions is a ( N x num_rhs ) matrix\n   * opts.solver=LS will return only one solution whilst methods such\n   * as OMP, LARS, and LASSO will return a history of solutions\n   *\n   * \\param opts specifies the method options\n   *\n   * \\param opts_list specifies the method options that can be used to\n   * reproduce all the solutions found.\n   */\n  void solve( RealMatrix &A, \n\t      RealMatrix &B, \n\t      RealMatrixArray &solutions,\n\t      CompressedSensingOptions &opts,\n\t      CompressedSensingOptionsList &opts_list );\n\n  void set_linear_solver( CompressedSensingOptions &opts );\n\n  LinearSolver_ptr get_linear_solver();\n};\n\n} // namespace Pecos\n\n#endif //LINEAR_SOLVERS_HPP\n", "meta": {"hexsha": "bd65e41374440cc60ed41f086c540d146f82e493", "size": 18047, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dakota-6.3.0.Windows.x86/include/LinearSolver.hpp", "max_stars_repo_name": "seakers/ExtUtils", "max_stars_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dakota-6.3.0.Windows.x86/include/LinearSolver.hpp", "max_issues_repo_name": "seakers/ExtUtils", "max_issues_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dakota-6.3.0.Windows.x86/include/LinearSolver.hpp", "max_forks_repo_name": "seakers/ExtUtils", "max_forks_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-18T14:13:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T14:13:14.000Z", "avg_line_length": 27.1792168675, "max_line_length": 177, "alphanum_fraction": 0.6527400676, "num_tokens": 5053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4049846084547341}}
{"text": "//\r\n// Copyright (c) 2016 - 2017 Mesh Consultants Inc.\r\n// Permission is hereby granted, free of charge, to any person obtaining a copy\r\n// of this software and associated documentation files (the \"Software\"), to deal\r\n// in the Software without restriction, including without limitation the rights\r\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n// copies of the Software, and to permit persons to whom the Software is\r\n// furnished to do so, subject to the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be included in\r\n// all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n// THE SOFTWARE.\r\n//\r\n\r\n\r\n#include \"Geomlib_TriMeshSubdivide.h\"\n\n#include <iostream>\n#include <vector>\n\n#include <Urho3D/Core/Variant.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#pragma warning(push, 0)\n#include <igl/edges.h>\n#include <igl/edge_flaps.h>\n#include <igl/unique_edge_map.h>\n#pragma warning(pop)\n\n#include \"ConversionUtilities.h\"\n#include \"TriMesh.h\"\n\n#pragma warning(disable : 4244)\n\n// collection of helper functions quarantined in anonymous namespace\nnamespace {\n\n\t// reviewed: CHECK\n\tint look_up_edge_index(const Eigen::MatrixXi& E, int s, int t)\n\t{\n\t\tint edge_index = -1;\n\t\tfor (unsigned e = 0; e < E.rows(); ++e) {\n\t\t\tif ((E(e, 0) == s && E(e, 1) == t) || (E(e, 0) == t && E(e, 1) == s)) {\n\t\t\t\tedge_index = e;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn edge_index;\n\t}\n\n\n\tvoid face_edge_map(\n\t\tconst Eigen::MatrixXi& F,\n\t\tconst Eigen::MatrixXi& E,\n\t\tEigen::MatrixXi& FE)\n\t{\n\t\tFE.setZero(F.rows(), 3);\n\n\t\tEigen::VectorXi EMAP;\n\t\tEigen::MatrixXi NE, EF, EI;\n\t\tigl::edge_flaps(F, NE, EMAP, EF, EI);\n\n\t\tfor (int f = 0; f < F.rows(); ++f) {\n\t\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\t\tint j = (i + 1) % 3;\n\t\t\t\tint k = (i + 2) % 3;\n\t\t\t\tint r, s, t;\n\t\t\t\tr = F(f, i);\n\t\t\t\ts = F(f, j);\n\t\t\t\tt = F(f, k);\n\t\t\t\tint e = look_up_edge_index(E, s, t);\n\t\t\t\tFE(f, i) = e;\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\n\t// If a row of F has entries\n\t//   a, b, c\n\t// Then the corresponding row for FM has entries\n\t//   i, j, k\n\t// where\n\t//   i is the index (into edge-subdivided vertex matrix) of the midpoint of the edge joining (b,c)\n\t//   j is the index (into edge-subdivided vertex matrix) of the midpoint of the edge joining (c,a)\n\t//   k is the index (into edge-subdivided vertex matrix) of the midpoint of the edge joining (a,b)\n\tvoid face_edge_midpoint_map(\n\t\tint numVertices,\n\t\tconst Eigen::MatrixXi& F,\n\t\tconst Eigen::MatrixXi& E,\n\t\tEigen::MatrixXi& FM)\n\t{\n\t\tFM.setZero(F.rows(), 3);\n\n\t\tfor (int f = 0; f < F.rows(); ++f) {\n\t\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\t\tint j = (i + 1) % 3;\n\t\t\t\tint k = (i + 2) % 3;\n\t\t\t\tint r, s, t;\n\t\t\t\tr = F(f, i);\n\t\t\t\ts = F(f, j);\n\t\t\t\tt = F(f, k);\n\t\t\t\tint e = look_up_edge_index(E, s, t);\n\t\t\t\tFM(f, i) = e + numVertices;\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\n\tvoid subdivide_mesh(\n\t\tconst Eigen::MatrixXd& OV,\n\t\tconst Eigen::MatrixXi& OF,\n\t\tEigen::MatrixXd& NV,\n\t\tEigen::MatrixXi& NF)\n\t{\n\t\tEigen::MatrixXi E;\n\t\tEigen::MatrixXi uE;\n\t\tEigen::VectorXi EMAP;\n\t\tstd::vector<std::vector<int> > uE2E;\n\t\tigl::unique_edge_map(OF, E, uE, EMAP, uE2E);\n\n\t\t// add midpoints to edge-subdivided vertex matrix NV\n\t\tNV.setZero(OV.rows() + uE.rows(), 3);\n\t\tNV.block(0, 0, OV.rows(), 3) = OV;\n\t\tfor (int e = 0; e < uE.rows(); ++e) {\n\t\t\tint v, w;\n\t\t\tv = uE(e, 0);\n\t\t\tw = uE(e, 1);\n\t\t\tNV.row(OV.rows() + e) = 0.5 * (OV.row(v) + OV.row(w));\n\t\t}\n\n\t\t// compute subdivided face data into NF\n\t\tNF.setZero(4 * OF.rows(), 3);\n\t\tfor (int f = 0; f < OF.rows(); ++f) {\n\t\t\tint v0, v1, v2;\n\t\t\tv0 = OV.rows() + EMAP(f);\n\t\t\tv1 = OV.rows() + EMAP(OF.rows() + f);\n\t\t\tv2 = OV.rows() + EMAP(2 * OF.rows() + f);\n\t\t\t//\n\t\t\tNF.row(4 * f) = Eigen::RowVector3i(v0, v1, v2);\n\t\t\tNF.row(4 * f + 1) = Eigen::RowVector3i(OF(f, 0), v2, v1);\n\t\t\tNF.row(4 * f + 2) = Eigen::RowVector3i(v2, OF(f, 1), v0);\n\t\t\tNF.row(4 * f + 3) = Eigen::RowVector3i(v1, v0, OF(f, 2));\n\t\t}\n\t\treturn;\n\t}\n\n\tvoid subdivide_mesh(\n\t\tconst Eigen::MatrixXd& OV,\n\t\tconst Eigen::MatrixXi& OF,\n\t\tconst Eigen::VectorXi& KEEP,\n\t\tEigen::MatrixXd& NV,\n\t\tEigen::MatrixXi& NF,\n\t\tEigen::VectorXi& NKEEP)\n\t{\n\t\tEigen::MatrixXi E;\n\t\tEigen::MatrixXi uE;\n\t\tEigen::VectorXi EMAP;\n\t\tstd::vector<std::vector<int> > uE2E;\n\t\tigl::unique_edge_map(OF, E, uE, EMAP, uE2E);\n\n\t\tNKEEP.setZero(4 * KEEP.rows());\n\n\t\t// add midpoints to edge-subdivided vertex matrix NV\n\t\tNV.setZero(OV.rows() + uE.rows(), 3);\n\t\tNV.block(0, 0, OV.rows(), 3) = OV;\n\t\tfor (int e = 0; e < uE.rows(); ++e) {\n\t\t\tint v, w;\n\t\t\tv = uE(e, 0);\n\t\t\tw = uE(e, 1);\n\t\t\tNV.row(OV.rows() + e) = 0.5 * (OV.row(v) + OV.row(w));\n\t\t}\n\n\t\t// compute subdivided face data into NF\n\t\tNF.setZero(4 * OF.rows(), 3);\n\t\tfor (int f = 0; f < OF.rows(); ++f) {\n\t\t\tint v0, v1, v2;\n\t\t\tv0 = OV.rows() + EMAP(f);\n\t\t\tv1 = OV.rows() + EMAP(OF.rows() + f);\n\t\t\tv2 = OV.rows() + EMAP(2 * OF.rows() + f);\n\t\t\t//\n\t\t\tNF.row(4 * f) = Eigen::RowVector3i(v0, v1, v2);\n\t\t\tNF.row(4 * f + 1) = Eigen::RowVector3i(OF(f, 0), v2, v1);\n\t\t\tNF.row(4 * f + 2) = Eigen::RowVector3i(v2, OF(f, 1), v0);\n\t\t\tNF.row(4 * f + 3) = Eigen::RowVector3i(v1, v0, OF(f, 2));\n\t\t\tint val = KEEP(f);\n\t\t\tNKEEP(4 * f) = val;\n\t\t\tNKEEP(4 * f + 1) = val;\n\t\t\tNKEEP(4 * f + 2) = val;\n\t\t\tNKEEP(4 * f + 3) = val;\n\t\t}\n\t\treturn;\n\t}\n\n\tvoid double_subdivide_mesh(\n\t\tconst Eigen::MatrixXd& OV,\n\t\tconst Eigen::MatrixXi& OF,\n\t\tEigen::MatrixXd& NV,\n\t\tEigen::MatrixXi& NF)\n\t{\n\t\tEigen::MatrixXd V;\n\t\tEigen::MatrixXi F;\n\t\tsubdivide_mesh(OV, OF, V, F);\n\t\tsubdivide_mesh(V, F, NV, NF);\n\n\t\treturn;\n\t}\n\n\tvoid subdivide_mesh(\n\t\tconst Eigen::MatrixXd& OV,\n\t\tconst Eigen::MatrixXi& OF,\n\t\tconst Eigen::VectorXi& KEEP,\n\t\tEigen::MatrixXd& NV,\n\t\tEigen::MatrixXi& NF,\n\t\tEigen::VectorXi& NKEEP,\n\t\tint steps)\n\t{\n\t\tEigen::MatrixXd V = OV;\n\t\tEigen::MatrixXi F = OF;\n\t\tEigen::VectorXi nKEEP = KEEP;\n\t\tfor (int i = 0; i < steps; ++i) {\n\t\t\tsubdivide_mesh(V, F, nKEEP, NV, NF, NKEEP);\n\t\t\tV.setZero(NV.rows(), 3);\n\t\t\tF.setZero(NF.rows(), 3);\n\t\t\tnKEEP.setZero(NKEEP.rows());\n\t\t\tV = NV;\n\t\t\tF = NF;\n\t\t\tnKEEP = NKEEP;\n\t\t}\n\t\treturn;\n\t}\n\n\n\n\t///////////////////////////////////////////////////////////////////////////////////////////////\n\n\t// Inputs:\n\t//     V: #V by 3 list of vertices\n\t//     F: #F by 3 list of faces into V\n\t//     KEEP: #F by 1 list taking values -1 (in shadow), 0 (on shadow-light boundary), 1 (in sunlight)\n\t// Outputs:\n\t//     NV: #NV by 3 list of vertices in the subdivided mesh\n\t//     NF: #NF by 3 list of faces (into NV) of the subdivided mesh\n\t//     NKEEP: #NF by 1 list taking values -1, 0, 1\n\tvoid subdivide_step(\n\t\tconst Eigen::MatrixXd& V,\n\t\tconst Eigen::MatrixXi& F,\n\t\tconst Eigen::VectorXi& KEEP,\n\t\tEigen::MatrixXd& NV,\n\t\tEigen::MatrixXi& NF,\n\t\tEigen::VectorXi& NKEEP)\n\t{\n\t\tEigen::VectorXi nKEEP = KEEP;\n\n\t\t// compute adjacency data\n\t\tEigen::MatrixXi E;\n\t\tEigen::MatrixXi uE;\n\t\tEigen::VectorXi EMAP;\n\t\tstd::vector<std::vector<int> > uE2E;\n\t\tigl::unique_edge_map(F, E, uE, EMAP, uE2E);\n\n\t\t// set up the new vertex matrix\n\t\t// make it as large as it could possibly need to be, i.e., in case every face gets subdivided\n\t\tNV.setZero(V.rows() + uE.rows(), 3);\n\t\tNV.block(0, 0, V.rows(), 3) = V;\n\t\t// set up the new face matrix\n\t\t// make it as large as it could possibly need to be, i.e., in case every face gets subdivided\n\t\tNF.resize(4 * F.rows(), 3);\n\t\tNF = Eigen::MatrixXi::Constant(4 * F.rows(), 3, -1);\n\t\tNF.block(0, 0, F.rows(), 3) = F;\n\t\tNKEEP.setZero(NF.rows());\n\n\n\t\t// FIRST PASS of FACE SUBDIVISION\n\n\t\t// Rows of SPLIT correspond to rows of uE (unordered edges).\n\t\t// If row e of SPLIT has value -1 then row e (index into uE) has not yet been split.\n\t\t// If row e of SPLIT has non-negative value i then edge e has been split,\n\t\t// in the sense that its midpoint has been added to the updated vertex matrix\n\t\t// and its index there is i.\n\t\tEigen::VectorXi SPLIT = Eigen::VectorXi::Constant(uE.rows(), -1);\n\n\t\tint facesDivided = 0;\n\t\tint edgesSplit = 0;\n\t\tstd::vector<int> undivided_faces;\n\t\tfor (int f = 0; f < F.rows(); ++f) {\n\t\t\t// indices into V (and therefore into NV) of vertices of face f\n\t\t\tint i, j, k;\n\t\t\ti = F(f, 0);\n\t\t\tj = F(f, 1);\n\t\t\tk = F(f, 2);\n\t\t\t// indices into uE of edges of face f\n\t\t\tint e0, e1, e2;\n\t\t\te0 = EMAP(f);\n\t\t\te1 = EMAP(F.rows() + f);\n\t\t\te2 = EMAP(2 * F.rows() + f);\n\t\t\t// indices into NV of midpoints of edges e0, e1, e2\n\t\t\tint m0, m1, m2;\n\n\t\t\tif (nKEEP(f) == 0) {\n\t\t\t\t// split edges with indices e0, e1, e2 if they have not already been split\n\n\t\t\t\t// split e0 if necessary\n\t\t\t\tint v = SPLIT(e0);\n\t\t\t\tm0 = v;\n\t\t\t\tif (v == -1) {\n\t\t\t\t\tv = V.rows() + edgesSplit;\n\t\t\t\t\tSPLIT(e0) = v;\n\t\t\t\t\tm0 = v;\n\t\t\t\t\t// do the split\n\t\t\t\t\tNV.row(v) = 0.5 * (V.row(uE(e0, 0)) + V.row(uE(e0, 1)));\n\t\t\t\t\tedgesSplit++;\n\t\t\t\t}\n\t\t\t\t// split e1 if necessary\n\t\t\t\tv = SPLIT(e1);\n\t\t\t\tm1 = v;\n\t\t\t\tif (v == -1) {\n\t\t\t\t\tv = V.rows() + edgesSplit;\n\t\t\t\t\tSPLIT(e1) = v;\n\t\t\t\t\tm1 = v;\n\t\t\t\t\t// do the split\n\t\t\t\t\tNV.row(v) = 0.5 * (V.row(uE(e1, 0)) + V.row(uE(e1, 1)));\n\t\t\t\t\tedgesSplit++;\n\t\t\t\t}\n\t\t\t\t// split e2 if necessary\n\t\t\t\tv = SPLIT(e2);\n\t\t\t\tm2 = v;\n\t\t\t\tif (v == -1) {\n\t\t\t\t\tv = V.rows() + edgesSplit;\n\t\t\t\t\tSPLIT(e2) = v;\n\t\t\t\t\tm2 = v;\n\t\t\t\t\t// do the split\n\t\t\t\t\tNV.row(v) = 0.5 * (V.row(uE(e2, 0)) + V.row(uE(e2, 1)));\n\t\t\t\t\tedgesSplit++;\n\t\t\t\t}\n\n\t\t\t\t// Now all the edges are split (whether we did it just now or it was split at a previous face).\n\t\t\t\t// face f has vertices with indices i,j,k into NV\n\t\t\t\t// midpoints of edges have indices m0,m1,m2 into NV\n\t\t\t\t// and the four faces should go into NF with indices\n\t\t\t\t//   f (inner face overwrites big original face)\n\t\t\t\t//   f0, f1, f2\n\t\t\t\tint f0, f1, f2;\n\t\t\t\tf0 = F.rows() + 3 * facesDivided;\n\t\t\t\tf1 = f0 + 1;\n\t\t\t\tf2 = f0 + 2;\n\t\t\t\tfacesDivided++;\n\t\t\t\tNF.row(f) = Eigen::RowVector3i(m0, m1, m2);\n\t\t\t\tNF.row(f0) = Eigen::RowVector3i(i, m2, m1);\n\t\t\t\tNF.row(f1) = Eigen::RowVector3i(m2, j, m0);\n\t\t\t\tNF.row(f2) = Eigen::RowVector3i(m1, m0, k);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tundivided_faces.push_back(f);\n\t\t\t}\n\t\t}\n\n\t\t// clean up new vertex matrix NV\n\t\tNV.conservativeResize(V.rows() + edgesSplit, 3);\n\n\t\t// SECOND PASS of FACE SUBDIVISION, i.e., clean up\n\n\t\tfor (int i = 0; i < undivided_faces.size(); ++i) {\n\t\t\tint f = undivided_faces[i];\n\t\t\tint e0, e1, e2;\n\t\t\te0 = EMAP(f);\n\t\t\te1 = EMAP(f + F.rows());\n\t\t\te2 = EMAP(f + 2 * F.rows());\n\t\t\tint m0, m1, m2;\n\t\t\tm0 = SPLIT(e0);\n\t\t\tm1 = SPLIT(e1);\n\t\t\tm2 = SPLIT(e2);\n\t\t\tint v0, v1, v2;\n\t\t\tv0 = F(f, 0);\n\t\t\tv1 = F(f, 1);\n\t\t\tv2 = F(f, 2);\n\t\t\tint f0, f1, f2;\n\t\t\tf0 = F.rows() + 3 * facesDivided;\n\t\t\tf1 = f0 + 1;\n\t\t\tf2 = f0 + 2;\n\t\t\tfacesDivided++;\n\n\t\t\tint l = nKEEP(f);\n\t\t\tNKEEP(f) = l;\n\t\t\tNKEEP(f0) = l;\n\t\t\tNKEEP(f1) = l;\n\t\t\tNKEEP(f2) = l;\n\n\t\t\tif (m0 == m1 && m1 == m2) {\n\t\t\t\t// face has had NO edges split\n\t\t\t}\n\t\t\telse if (m0 == m1) {\n\t\t\t\t// face has had only edge e2 split\n\t\t\t\tNF.row(f) = Eigen::RowVector3i(v0, m2, v2);\n\t\t\t\tNF.row(f0) = Eigen::RowVector3i(m2, v1, v2);\n\t\t\t}\n\t\t\telse if (m1 == m2) { // -1, -1, m0\n\t\t\t\t\t\t\t\t // face has had only edge e0 split\n\t\t\t\tNF.row(f) = Eigen::RowVector3i(v1, m0, v0);\n\t\t\t\tNF.row(f0) = Eigen::RowVector3i(m0, v2, v0);\n\t\t\t}\n\t\t\telse if (m2 == m0) { // -1, -1, m1\n\t\t\t\t\t\t\t\t // face has had only edge e1 split\n\t\t\t\tNF.row(f) = Eigen::RowVector3i(v2, m1, v1);\n\t\t\t\tNF.row(f0) = Eigen::RowVector3i(m1, v0, v1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (m0 == -1) {\n\t\t\t\t\t// face has had edges e1, e2 split\n\t\t\t\t\tNF.row(f) = Eigen::RowVector3i(v1, v2, m2);\n\t\t\t\t\tNF.row(f0) = Eigen::RowVector3i(m2, v2, m1);\n\t\t\t\t\tNF.row(f1) = Eigen::RowVector3i(m2, m1, v0);\n\t\t\t\t}\n\t\t\t\telse if (m1 == -1) {\n\t\t\t\t\t// face has had edges e0, e2 split\n\t\t\t\t\tNF.row(f) = Eigen::RowVector3i(v2, v0, m0);\n\t\t\t\t\tNF.row(f0) = Eigen::RowVector3i(m0, v0, m2);\n\t\t\t\t\tNF.row(f1) = Eigen::RowVector3i(m0, m2, v1);\n\t\t\t\t}\n\t\t\t\telse if (m2 == -1) {\n\t\t\t\t\t// face has had edges e0, e1 split\n\t\t\t\t\tNF.row(f) = Eigen::RowVector3i(v0, v1, m1);\n\t\t\t\t\tNF.row(f0) = Eigen::RowVector3i(m1, v1, m0);\n\t\t\t\t\tNF.row(f1) = Eigen::RowVector3i(m1, m0, v2);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// all three edges e0, e1, e2 have been split\n\t\t\t\t\t// face f has vertices with indices v0, v1, v2 into NV\n\t\t\t\t\t// midpoints of edges have indices m0, m1, m2 into NV\n\t\t\t\t\t// and the four faces should go into NF with indices\n\t\t\t\t\t//   f (inner face overwrites big original face)\n\t\t\t\t\t//   f0, f1, f2\n\t\t\t\t\tNF.row(f) = Eigen::RowVector3i(m0, m1, m2);\n\t\t\t\t\tNF.row(f0) = Eigen::RowVector3i(v0, m2, m1);\n\t\t\t\t\tNF.row(f1) = Eigen::RowVector3i(m2, v1, m0);\n\t\t\t\t\tNF.row(f2) = Eigen::RowVector3i(m1, m0, v2);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\t// clean up new face matrix NF and new kept faces vector NKEEP\n\t\tstd::vector<int> faces;\n\t\tstd::vector<int> keep;\n\t\tfor (int f = 0; f < NF.rows(); ++f) {\n\t\t\tif (NF(f, 0) != -1) {\n\t\t\t\tfaces.push_back(NF(f, 0));\n\t\t\t\tfaces.push_back(NF(f, 1));\n\t\t\t\tfaces.push_back(NF(f, 2));\n\t\t\t\tkeep.push_back(NKEEP(f));\n\t\t\t}\n\t\t}\n\t\tint numFaces = faces.size() / 3;\n\t\tNF.resize(numFaces, 3);\n\t\tNKEEP.resize(numFaces);\n\t\tfor (int f = 0; f < NF.rows(); ++f) {\n\t\t\tNF(f, 0) = faces[3 * f + 0];\n\t\t\tNF(f, 1) = faces[3 * f + 1];\n\t\t\tNF(f, 2) = faces[3 * f + 2];\n\t\t\tNKEEP(f) = keep[f];\n\t\t}\n\n\t\treturn;\n\t}\n\n\tvoid smart_subdivide_mesh(\n\t\tconst Eigen::MatrixXd& OV,\n\t\tconst Eigen::MatrixXi& OF,\n\t\tEigen::MatrixXd& NV,\n\t\tEigen::MatrixXi& NF,\n\t\tEigen::VectorXi& NKEEP,\n\t\tint steps)\n\t{\n\n\t\tEigen::MatrixXd V;\n\t\tEigen::MatrixXi F;\n\t\tEigen::VectorXi nKEEP;\n\n\t\tEigen::VectorXi KEEP = Eigen::VectorXi::Constant(OF.rows(), 0);\n\t\tsubdivide_step(OV, OF, KEEP, NV, NF, NKEEP);\n\n\t\tif (steps > 1) {\n\t\t\tV.resize(NV.rows(), 3);\n\t\t\tV = NV;\n\t\t\tF.resize(NF.rows(), 3);\n\t\t\tF = NF;\n\t\t\tnKEEP.resize(NKEEP.rows());\n\t\t\tnKEEP = NKEEP;\n\t\t}\n\n\t\tfor (int i = 1; i < steps; ++i) {\n\t\t\tsubdivide_step(V, F, nKEEP, NV, NF, NKEEP);\n\t\t\t// update intermediate matrices\n\t\t\tV.resize(NV.rows(), 3);\n\t\t\tV = NV;\n\t\t\tF.resize(NF.rows(), 3);\n\t\t\tF = NF;\n\t\t\tnKEEP.resize(NKEEP.rows());\n\t\t\tnKEEP = NKEEP;\n\t\t}\n\t\treturn;\n\t}\n\n\tvoid subdivide_mesh(\n\t\tconst Eigen::MatrixXd& OV,\n\t\tconst Eigen::MatrixXi& OF,\n\t\tEigen::MatrixXd& NV,\n\t\tEigen::MatrixXi& NF,\n\t\tint steps)\n\t{\n\t\tEigen::MatrixXd V = OV;\n\t\tEigen::MatrixXi F = OF;\n\t\tfor (int i = 0; i < steps; ++i) {\n\t\t\tsubdivide_mesh(V, F, NV, NF);\n\t\t\tV.setZero(NV.rows(), 3);\n\t\t\tF.setZero(NF.rows(), 3);\n\t\t\tV = NV;\n\t\t\tF = NF;\n\t\t}\n\t\treturn;\n\t}\n}\n\nbool Geomlib::TriMeshSubdivide(\n\tconst Urho3D::Variant& meshIn,\n\tint steps,\n\tUrho3D::Variant& meshOut\n)\n{\n\tif (!TriMesh_Verify(meshIn)) {\n\t\tmeshOut = Urho3D::Variant();\n\t\treturn false;\n\t}\n\n\tEigen::MatrixXf V;\n\tEigen::MatrixXi F;\n\tIglMeshToMatrices(meshIn, V, F);\n\n\tEigen::MatrixXd Vd = IglFloatToDouble(V);\n\tEigen::MatrixXd NVd;\n\tEigen::MatrixXi NF;\n\n\tsubdivide_mesh(Vd, F, NVd, NF, steps);\n\n\tEigen::MatrixXf NV = IglDoubleToFloat(NVd);\n\n\tmeshOut = TriMesh_Make(NV, NF);\n\treturn true;\n}\n", "meta": {"hexsha": "31caea97cf73fdd15ad662aa74db193c06fc68d2", "size": 14897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry/Geomlib_TriMeshSubdivide.cpp", "max_stars_repo_name": "elix22/IogramSource", "max_stars_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-03-01T04:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T13:33:50.000Z", "max_issues_repo_path": "Geometry/Geomlib_TriMeshSubdivide.cpp", "max_issues_repo_name": "elix22/IogramSource", "max_issues_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-03-09T05:22:49.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T18:38:05.000Z", "max_forks_repo_path": "Geometry/Geomlib_TriMeshSubdivide.cpp", "max_forks_repo_name": "elix22/IogramSource", "max_forks_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-03-01T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:36:54.000Z", "avg_line_length": 26.6971326165, "max_line_length": 102, "alphanum_fraction": 0.5801839297, "num_tokens": 5522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4049846084547341}}
{"text": "//  Copyright John Maddock 2007.\n//  Copyright Paul A. Bristow 2007.\n\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_STATS_FIND_SCALE_HPP\n#define BOOST_STATS_FIND_SCALE_HPP\n\n#include <boost/math/distributions/fwd.hpp> // for all distribution signatures.\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/policies/policy.hpp>\n// using boost::math::policies::policy;\n#include <boost/math/tools/traits.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/math/policies/error_handling.hpp>\n// using boost::math::complement; // will be needed by users who want complement,\n// but NOT placed here to avoid putting it in global scope.\n\nnamespace boost\n{\n  namespace math\n  {\n    // Function to find location of random variable z\n    // to give probability p (given scale)\n    // Applies to normal, lognormal, extreme value, Cauchy, (and symmetrical triangular),\n    // distributions that have scale.\n    // BOOST_STATIC_ASSERTs, see below, are used to enforce this.\n\n    template <class Dist, class Policy>\n    inline\n      typename Dist::value_type find_scale( // For example, normal mean.\n      typename Dist::value_type z, // location of random variable z to give probability, P(X > z) == p.\n      // For example, a nominal minimum acceptable weight z, so that p * 100 % are > z\n      typename Dist::value_type p, // probability value desired at x, say 0.95 for 95% > z.\n      typename Dist::value_type location, // location parameter, for example, normal distribution mean.\n      const Policy& pol \n      )\n    {\n#if !defined(BOOST_NO_SFINAE) && !BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x590))\n      BOOST_STATIC_ASSERT(::boost::math::tools::is_distribution<Dist>::value); \n      BOOST_STATIC_ASSERT(::boost::math::tools::is_scaled_distribution<Dist>::value); \n#endif\n      static const char* function = \"boost::math::find_scale<Dist, Policy>(%1%, %1%, %1%, Policy)\";\n\n      if(!(boost::math::isfinite)(p) || (p < 0) || (p > 1))\n      {\n        return policies::raise_domain_error<typename Dist::value_type>(\n          function, \"Probability parameter was %1%, but must be >= 0 and <= 1!\", p, pol);\n      }\n      if(!(boost::math::isfinite)(z))\n      {\n        return policies::raise_domain_error<typename Dist::value_type>(\n          function, \"find_scale z parameter was %1%, but must be finite!\", z, pol);\n      }\n      if(!(boost::math::isfinite)(location))\n      {\n        return policies::raise_domain_error<typename Dist::value_type>(\n          function, \"find_scale location parameter was %1%, but must be finite!\", location, pol);\n      }\n\n      //cout << \"z \" << z << \", p \" << p << \",  quantile(Dist(), p) \"\n      //<< quantile(Dist(), p) << \", z - mean \" << z - location \n      //<<\", sd \" << (z - location)  / quantile(Dist(), p) << endl;\n\n      //quantile(N01, 0.001) -3.09023\n      //quantile(N01, 0.01) -2.32635\n      //quantile(N01, 0.05) -1.64485\n      //quantile(N01, 0.333333) -0.430728\n      //quantile(N01, 0.5) 0  \n      //quantile(N01, 0.666667) 0.430728\n      //quantile(N01, 0.9) 1.28155\n      //quantile(N01, 0.95) 1.64485\n      //quantile(N01, 0.99) 2.32635\n      //quantile(N01, 0.999) 3.09023\n\n      typename Dist::value_type result = \n        (z - location)  // difference between desired x and current location.\n        / quantile(Dist(), p); // standard distribution.\n\n      if (result <= 0)\n      { // If policy isn't to throw, return the scale <= 0.\n        policies::raise_evaluation_error<typename Dist::value_type>(function,\n          \"Computed scale (%1%) is <= 0!\" \" Was the complement intended?\",\n          result, Policy());\n      }\n      return result;\n    } // template <class Dist, class Policy> find_scale\n\n    template <class Dist>\n    inline // with default policy.\n      typename Dist::value_type find_scale( // For example, normal mean.\n      typename Dist::value_type z, // location of random variable z to give probability, P(X > z) == p.\n      // For example, a nominal minimum acceptable z, so that p * 100 % are > z\n      typename Dist::value_type p, // probability value desired at x, say 0.95 for 95% > z.\n      typename Dist::value_type location) // location parameter, for example, mean.\n    { // Forward to find_scale using the default policy.\n      return (find_scale<Dist>(z, p, location, policies::policy<>()));\n    } // find_scale\n\n    template <class Dist, class Real1, class Real2, class Real3, class Policy>\n    inline typename Dist::value_type find_scale(\n      complemented4_type<Real1, Real2, Real3, Policy> const& c)\n    {\n      //cout << \"cparam1 q \" << c.param1 // q\n      //  << \", c.dist z \" << c.dist // z\n      //  << \", c.param2 l \" << c.param2 // l\n      //  << \", quantile (Dist(), c.param1 = q) \"\n      //  << quantile(Dist(), c.param1) //q\n      //  << endl;\n\n#if !defined(BOOST_NO_SFINAE) && !BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x590))\n      BOOST_STATIC_ASSERT(::boost::math::tools::is_distribution<Dist>::value); \n      BOOST_STATIC_ASSERT(::boost::math::tools::is_scaled_distribution<Dist>::value); \n#endif\n      static const char* function = \"boost::math::find_scale<Dist, Policy>(complement(%1%, %1%, %1%, Policy))\";\n\n      // Checks on arguments, as not complemented version,\n      // Explicit policy.\n      typename Dist::value_type q = c.param1;\n      if(!(boost::math::isfinite)(q) || (q < 0) || (q > 1))\n      {\n        return policies::raise_domain_error<typename Dist::value_type>(\n          function, \"Probability parameter was %1%, but must be >= 0 and <= 1!\", q, c.param3);\n      }\n      typename Dist::value_type z = c.dist;\n      if(!(boost::math::isfinite)(z))\n      {\n        return policies::raise_domain_error<typename Dist::value_type>(\n          function, \"find_scale z parameter was %1%, but must be finite!\", z, c.param3);\n      }\n      typename Dist::value_type location = c.param2;\n      if(!(boost::math::isfinite)(location))\n      {\n        return policies::raise_domain_error<typename Dist::value_type>(\n          function, \"find_scale location parameter was %1%, but must be finite!\", location, c.param3);\n      }\n\n      typename Dist::value_type result = \n        (c.dist - c.param2)  // difference between desired x and current location.\n        / quantile(complement(Dist(), c.param1));\n      //     (  z    - location) / (quantile(complement(Dist(),  q)) \n      if (result <= 0)\n      { // If policy isn't to throw, return the scale <= 0.\n        policies::raise_evaluation_error<typename Dist::value_type>(function,\n          \"Computed scale (%1%) is <= 0!\" \" Was the complement intended?\",\n          result, Policy());\n      }\n      return result;\n    } // template <class Dist, class Policy, class Real1, class Real2, class Real3> typename Dist::value_type find_scale\n\n    // So the user can start from the complement q = (1 - p) of the probability p,\n    // for example, s = find_scale<normal>(complement(z, q, l));\n\n    template <class Dist, class Real1, class Real2, class Real3>\n    inline typename Dist::value_type find_scale(\n      complemented3_type<Real1, Real2, Real3> const& c)\n    {\n      //cout << \"cparam1 q \" << c.param1 // q\n      //  << \", c.dist z \" << c.dist // z\n      //  << \", c.param2 l \" << c.param2 // l\n      //  << \", quantile (Dist(), c.param1 = q) \"\n      //  << quantile(Dist(), c.param1) //q\n      //  << endl;\n\n#if !defined(BOOST_NO_SFINAE) && !BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x590))\n      BOOST_STATIC_ASSERT(::boost::math::tools::is_distribution<Dist>::value); \n      BOOST_STATIC_ASSERT(::boost::math::tools::is_scaled_distribution<Dist>::value); \n#endif\n      static const char* function = \"boost::math::find_scale<Dist, Policy>(complement(%1%, %1%, %1%, Policy))\";\n\n      // Checks on arguments, as not complemented version,\n      // default policy policies::policy<>().\n      typename Dist::value_type q = c.param1;\n      if(!(boost::math::isfinite)(q) || (q < 0) || (q > 1))\n      {\n        return policies::raise_domain_error<typename Dist::value_type>(\n          function, \"Probability parameter was %1%, but must be >= 0 and <= 1!\", q, policies::policy<>());\n      }\n      typename Dist::value_type z = c.dist;\n      if(!(boost::math::isfinite)(z))\n      {\n        return policies::raise_domain_error<typename Dist::value_type>(\n          function, \"find_scale z parameter was %1%, but must be finite!\", z, policies::policy<>());\n      }\n      typename Dist::value_type location = c.param2;\n      if(!(boost::math::isfinite)(location))\n      {\n        return policies::raise_domain_error<typename Dist::value_type>(\n          function, \"find_scale location parameter was %1%, but must be finite!\", location, policies::policy<>());\n      }\n\n      typename Dist::value_type result = \n        (z - location)  // difference between desired x and current location.\n        / quantile(complement(Dist(), q));\n      //     (  z    - location) / (quantile(complement(Dist(),  q)) \n      if (result <= 0)\n      { // If policy isn't to throw, return the scale <= 0.\n        policies::raise_evaluation_error<typename Dist::value_type>(function,\n          \"Computed scale (%1%) is <= 0!\" \" Was the complement intended?\",\n          result, policies::policy<>()); // This is only the default policy - also Want a version with Policy here.\n      }\n      return result;\n    } // template <class Dist, class Real1, class Real2, class Real3> typename Dist::value_type find_scale\n\n  } // namespace boost\n} // namespace math\n\n#endif // BOOST_STATS_FIND_SCALE_HPP\n", "meta": {"hexsha": "e3baafc6573f14715b0036d5c3532afbcd2de01a", "size": 9674, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/math/distributions/find_scale.hpp", "max_stars_repo_name": "189569400/ClickHouse", "max_stars_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "contrib/libboost/boost_1_62_0/boost/math/distributions/find_scale.hpp", "max_issues_repo_name": "189569400/ClickHouse", "max_issues_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "contrib/libboost/boost_1_62_0/boost/math/distributions/find_scale.hpp", "max_forks_repo_name": "189569400/ClickHouse", "max_forks_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 45.6320754717, "max_line_length": 120, "alphanum_fraction": 0.6302460203, "num_tokens": 2558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.40498460020928645}}
{"text": "/* \n// Copyright 2018 University of Liege\n// \n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n// \n//     http://www.apache.org/licenses/LICENSE-2.0\n// \n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Authors:\n// - Adrien Crovato\n*/\n\n//// Panel splitting\n// Split a panel and compute AIC on each sub-panel\n//\n// Inputs:\n// - idP: influencing panel index\n// - idF: target field cell index\n// - x0: x - coordinate of first corner point of panel in local axes\n// - x1: x - coordinate of second corner point of panel in local axes\n// - x2: x - coordinate of third corner point of panel in local axes\n// - x3: x - coordinate of fourth corner point of panel in local axes\n// - y0: y - coordinate of first corner point of panel in local axes\n// - y1: y - coordinate of second corner point of panel in local axes\n// - y2: y - coordinate of third corner point of panel in local axes\n// - y3: y - coordinate of fourth corner point of panel in local axes\n// - bPan: body panels (structure)\n// - fPan: field panels (structure)\n// - sp: sub-panels (structure)\n\n#include <iostream>\n#include <Eigen/Dense>\n#include <array>\n#include \"split_panel.h\"\n#include \"infcB.h\"\n\n#define NDIM 3\n#define NSING 2\n\nusing namespace std;\nusing namespace Eigen;\n\narray<RowVectorXd,NSING> split_panel(int idP, int idF,\n                                  double x0, double x1, double x2, double x3, double y0, double y1, double y2, double y3,\n                                  Network &bPan, Field &fPan, Subpanel &sp) {\n\n    //// Initialization\n    int idx; // counter\n    double a0, a1 ,b0, b1; // interpolation coefficients\n    VectorXd xV0, xV1, xV2, xV3, yV0, yV1, yV2, yV3; // sub-panel vertices\n    xV0.resize(sp.NS);\n    xV1.resize(sp.NS);\n    xV2.resize(sp.NS);\n    xV3.resize(sp.NS);\n    yV0.resize(sp.NS);\n    yV1.resize(sp.NS);\n    yV2.resize(sp.NS);\n    yV3.resize(sp.NS);\n    Vector3d tgt; // target points\n    tgt.resize(NDIM);\n\n    array <RowVectorXd, NSING> coeff; // returned and temporary coefficients\n    array <double, NSING> coeffT;\n    for (int i = 0; i < NSING; i++)\n        coeff[i].resize(sp.NS);\n\n    //// Change coordinates\n    // Cell center\n    tgt(0) = bPan.l(idP,0)*fPan.CG(idF,0) + bPan.l(idP,1)*fPan.CG(idF,1) + bPan.l(idP,2)*fPan.CG(idF,2);\n    tgt(1) = bPan.p(idP,0)*fPan.CG(idF,0) + bPan.p(idP,1)*fPan.CG(idF,1) + bPan.p(idP,2)*fPan.CG(idF,2);\n    tgt(2) = bPan.n(idP,0)*(fPan.CG(idF,0) - bPan.CG(idP,0)) + bPan.n(idP,1)*(fPan.CG(idF,1) - bPan.CG(idP,1))\n               + bPan.n(idP,2)*(fPan.CG(idF,2) - bPan.CG(idP,2));\n\n    //// Split panel\n    // Compute sub-panels vertices\n    idx = 0;\n    for (int j = 0; j < sp.NSs; j++) {\n        for (int i = 0; i < sp.NSs; i++) {\n            // Compute weight factors\n            a0 = (double) i/sp.NSs;\n            a1 = (double) (i+1)/sp.NSs;\n            b0 = (double) j/sp.NSs;\n            b1 = (double) (j+1)/sp.NSs;\n            // Compute new vertices\n            xV0(idx) = (1-b0)*((1-a0)*x0 + a0*x1) + b0*(a0*x2 +(1-a0)*x3);\n            xV1(idx) = (1-b0)*((1-a1)*x0 + a1*x1) + b0*(a1*x2 +(1-a1)*x3);\n            xV2(idx) = (1-b1)*((1-a1)*x0 + a1*x1) + b1*(a1*x2 +(1-a1)*x3);\n            xV3(idx) = (1-b1)*((1-a0)*x0 + a0*x1) + b1*(a0*x2 +(1-a0)*x3);\n            yV0(idx) = (1-b0)*((1-a0)*y0 + a0*y1) + b0*(a0*y2 +(1-a0)*y3);\n            yV1(idx) = (1-b0)*((1-a1)*y0 + a1*y1) + b0*(a1*y2 +(1-a1)*y3);\n            yV2(idx) = (1-b1)*((1-a1)*y0 + a1*y1) + b1*(a1*y2 +(1-a1)*y3);\n            yV3(idx) = (1-b1)*((1-a0)*y0 + a0*y1) + b1*(a0*y2 +(1-a0)*y3);\n            idx ++;\n        }\n    }\n\n    //// Compute AIC\n    for (int j = 0; j < sp.NS; j++) {\n        // call infcBB\n        coeffT = infcB(0, 0, 1, tgt(0), tgt(1), tgt(2), xV0(j), yV0(j), xV1(j), yV1(j), xV2(j), yV2(j), xV3(j), yV3(j));\n        // Store to return\n        coeff[0](j) = coeffT[0];\n        coeff[1](j) = coeffT[1];\n    }\n    return coeff;\n}\n", "meta": {"hexsha": "22e1e48c9205560f363c2c1155155580d19f2b8f", "size": 4267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/split_panel.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/split_panel.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/split_panel.cpp", "max_forks_repo_name": "acrovato/aero", "max_forks_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4298245614, "max_line_length": 121, "alphanum_fraction": 0.5753456761, "num_tokens": 1496, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4049432421375034}}
{"text": "#ifndef AQ1_MAIN_HPP\n#define AQ1_MAIN_HPP\n\n#include <iostream>\n#include <memory>\n#include <optional>\n#include <string>\n#include <variant>\n#include <vector>\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/rational.hpp>\n\nnamespace mp = boost::multiprecision;\nusing MPInt = mp::cpp_int;\nusing MPRational = boost::rational<MPInt>;\nusing MPFloat = mp::cpp_dec_float_100;\n\nenum class TOK {\n    NUMLIT,  // Numeric literal\n    OWARI,   // End of file\n    PLUS,\n    MINUS,\n    STAR,\n    SLASH,\n    PERCENT,\n    NEWLINE,\n    LPAREN,\n    RPAREN,\n    IDENT,\n    COMMA,\n    FMTLIT,\n};\n\nstruct FormatLiteral {\n    bool is_signed, is_zero_padded;\n    int field_width, precision;\n};\n\nstruct Token {\n    TOK kind;\n    std::variant<std::monostate, MPRational, std::string, FormatLiteral> data;\n\n    static const Token &owari()\n    {\n        static const Token tok{TOK::OWARI, std::monostate{}};\n        return tok;\n    }\n};\n\nclass Lex {\nprivate:\n    std::istream &is_;\n    std::optional<Token> pending_;\n    std::vector<char> history_;\n\n    int getch();\n    void putback(int ch);\n    Token next_token();\n\npublic:\n    Lex(std::istream &is) : is_(is), pending_(std::nullopt)\n    {\n    }\n\n    // Get the next non-NEWLINE token.\n    Token get();\n    // Expect the next non-NEWLINE token.\n    Token expect(TOK kind);\n    // Return if the next non-NEWLINE token's kind is `kind`.\n    bool match(TOK kind);\n\n    // Peek the next token. This function will NOT skip NEWLINE.\n    Token peek_next();\n\n    std::string clear_history();\n};\n\nclass ASTNode {\npublic:\n    ASTNode() = default;\n\n    // Thanks to:\n    // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-copy-virtual\n    // Thanks to:\n    // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-five\n    virtual ~ASTNode() = default;\n    ASTNode(const ASTNode &) = delete;\n    ASTNode &operator=(const ASTNode &) = delete;\n    ASTNode(ASTNode &&) = delete;\n    ASTNode &operator=(ASTNode &&) = delete;\n\n    virtual MPRational eval() const = 0;\n};\n\nusing ASTNodePtr = std::shared_ptr<ASTNode>;\n\nenum class UNARYOP {\n    PLUS,\n    MINUS,\n};\n\nclass UnaryOp : public ASTNode {\nprivate:\n    UNARYOP kind_;\n    ASTNodePtr src_;\n\npublic:\n    UnaryOp(UNARYOP kind, ASTNodePtr src) : kind_(kind), src_(std::move(src))\n    {\n    }\n\n    MPRational eval() const override;\n};\n\nenum class BINOP {\n    ADD,\n    SUB,\n    MUL,\n    DIV,\n};\n\nclass BinOp : public ASTNode {\nprivate:\n    BINOP kind_;\n    ASTNodePtr lhs_, rhs_;\n\npublic:\n    BinOp(BINOP kind, ASTNodePtr lhs, ASTNodePtr rhs)\n        : kind_(kind), lhs_(std::move(lhs)), rhs_(std::move(rhs))\n    {\n    }\n\n    MPRational eval() const override;\n};\n\nclass NumImm : public ASTNode {\nprivate:\n    MPRational val_;\n\npublic:\n    NumImm(MPRational val) : val_(std::move(val))\n    {\n    }\n\n    MPRational eval() const override\n    {\n        return val_;\n    }\n};\n\nclass FuncCall : public ASTNode {\nprivate:\n    std::string name_;\n    std::vector<ASTNodePtr> args_;\n\npublic:\n    FuncCall(std::string name, std::vector<ASTNodePtr> args)\n        : name_(std::move(name)), args_(std::move(args))\n    {\n    }\n\n    MPRational eval() const override;\n};\n\nclass FormatPrint : public ASTNode {\nprivate:\n    ASTNodePtr src_;\n    int field_width_, precision_;\n\npublic:\n    FormatPrint(ASTNodePtr src, int field_width, int precision)\n        : src_(std::move(src)), field_width_(field_width), precision_(precision)\n    {\n    }\n\n    MPRational eval() const override;\n};\n\nclass Parser {\nprivate:\n    Lex &lex_;\n\n    ASTNodePtr parse_primary();\n    ASTNodePtr parse_unary();\n    ASTNodePtr parse_multiplicative();\n    ASTNodePtr parse_additive();\n    ASTNodePtr parse_expr();\n\npublic:\n    Parser(Lex &lex) : lex_(lex)\n    {\n    }\n\n    ASTNodePtr parse();\n};\n\n#endif\n", "meta": {"hexsha": "df8c1f763354e508a750ca6a42164859d8958b89", "size": 3836, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "main.hpp", "max_stars_repo_name": "ushitora-anqou/aq1", "max_stars_repo_head_hexsha": "f9c394e7571a5a599331f723f0611d8365bda2b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-15T22:31:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-15T22:31:21.000Z", "max_issues_repo_path": "main.hpp", "max_issues_repo_name": "ushitora-anqou/aq1", "max_issues_repo_head_hexsha": "f9c394e7571a5a599331f723f0611d8365bda2b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.hpp", "max_forks_repo_name": "ushitora-anqou/aq1", "max_forks_repo_head_hexsha": "f9c394e7571a5a599331f723f0611d8365bda2b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.18, "max_line_length": 99, "alphanum_fraction": 0.6470281543, "num_tokens": 1034, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4049432421375034}}
{"text": "#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <cmath>\n#include <fstream>\n#include <valarray>\n#include <sstream>\n#include <string>\n#include <list>\n#include <vector>\n\nusing namespace std::string_literals;\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include \"vlasovpp/field.h\"\n#include \"vlasovpp/complex_field.h\"\n#include \"vlasovpp/weno.h\"\n#include \"vlasovpp/fft.h\"\n#include \"vlasovpp/array_view.h\"\n#include \"vlasovpp/poisson.h\"\n#include \"vlasovpp/rk.h\"\n#include \"vlasovpp/config.h\"\n#include \"vlasovpp/signal_handler.h\"\n#include \"vlasovpp/iteration.h\"\n#include \"vlasovpp/splitting.h\"\n\nnamespace math = boost::math::constants;\nconst std::complex<double> & I = std::complex<double>(0.,1.);\n\n#define SQ(X) ((X)*(X))\n#define Zi(i) (i*f.step.dz+f.range.z_min)\n#define Vkx(k) (k*f.step.dvx+f.range.vx_min)\n#define Vky(k) (k*f.step.dvy+f.range.vy_min)\n#define Vkz(k) (k*f.step.dvz+f.range.vz_min)\n\nauto\nmaxwellian ( double rho , std::vector<double> u , double T ) {\n  return [=](double z,double vx,double vy,double vz) {\n    return rho/( std::pow(2.*math::pi<double>()*T,1.5) )*std::exp( -0.5*(SQ(vx-u[0])+SQ(vy-u[1])+SQ(vz-u[2]))/T );\n  };\n}\n\nint\nmain ( int argc , char const * argv[] )\n{\n  std::string p(\"config.init\");\n  if ( argc > 1 )\n    { p = argv[1]; }\n  auto c = config(p);\n  c.name = \"vmls\";\n\n  c.create_output_directory();\n  {\n    std::ofstream ofconfig( c.output_dir / \"config.init\" );\n    ofconfig << c << \"\\n\";\n    ofconfig.close();\n  }\n\n/* ------------------------------------------------------------------------- */\n  field3d<double> f(boost::extents[c.Nvx][c.Nvy][c.Nvz][c.Nz]);\n  complex_field<double,3> hf(boost::extents[c.Nvx][c.Nvy][c.Nvz][c.Nz]);\n\n  const double Kx = 0.5;\n  f.range.vx_min = -5.; f.range.vx_max = 5.;\n  f.range.vy_min = -5.; f.range.vy_max = 5.;\n  f.range.vz_min = -5.; f.range.vz_max = 5.;\n  f.range.z_min =  0.;  f.range.z_max = 2./Kx*math::pi<double>();\n  f.compute_steps();\n\n  double dt = 0.1;\n\n  ublas::vector<double> vx(c.Nv,0.),vy(c.Nv,0.),vz(c.Nv,0.);\n  std::generate( vx.begin() , vx.end() , [&,k=0]() mutable {return (k++)*f.step.dvx+f.range.vx_min;} );\n  std::generate( vy.begin() , vy.end() , [&,k=0]() mutable {return (k++)*f.step.dvy+f.range.vy_min;} );\n  std::generate( vz.begin() , vz.end() , [&,k=0]() mutable {return (k++)*f.step.dvz+f.range.vz_min;} );\n\n  ublas::vector<double> kx(c.Nx); // beware, Nx need to be odd\n  {\n    double l = f.range.len_z();\n    for ( auto i=0u ; i<c.Nx/2 ; ++i ) { kx[i]      = 2.*math::pi<double>()*i/l; }\n    for ( int i=-c.Nx/2 ; i<0 ; ++i ) { kx[c.Nx+i] = 2.*math::pi<double>()*i/l; }\n  }\n\n  auto M1 = maxwellian(1.,{0.,0.,0.},1.);\n  for (std::size_t k_x=0u ; k_x<f.size(0) ; ++k_x ) {\n    for (std::size_t k_y=0u ; k_y<f.size(1) ; ++k_y ) {\n      for (std::size_t k_z=0u ; k_z<f.size(2) ; ++k_z ) {\n        for (std::size_t i=0u ; i<f.size_x() ; ++i ) {\n          f[k_x][k_y][k_z][i] = M1( Zi(i),Vkx(k_x),Vky(k_y),Vkz(k_z) ) * (1. + 0.5*std::cos(Kx*Zi(i)));\n        }\n        fft::fft(f[k_x][k_y][k_z].begin(),f[k_x][k_y][k_z].end(),hf[k_x][k_y][k_z].begin());\n      }\n    }\n  }\n\n\n  const double B0 = 1.;\n  ublas::vector<double> Ex(c.Nz,0.),Ey(c.Nz,0.);\n  ublas::vector<double> jcx(c.Nz,0.),jcy(c.Nz,0.);\n\n\n  std::vector<double> electric_energy;  electric_energy.reserve(100);\n  std::vector<double> electric_energy_x; electric_energy_x.reserve(100);\n  std::vector<double> electric_energy_y; electric_energy_y.reserve(100);\n  std::vector<double> times; times.reserve(100);\n\n  hybird1dx3dv_b0<double> Lie( f , f.range.len_z() , B0 );\n  double current_t = 0.;\n  times.push_back(0.);\n\n  auto compute_electric_energy = [&]( const ublas::vector<double> & E ) {\n    double electric_energy = 0.;\n    for ( const auto & ei : E ) { electric_energy += ei*ei*f.step.dz; }\n      return electric_energy;\n  };\n  double eex=0.,eey=0.;\n  eex = compute_electric_energy(Ex); eey = compute_electric_energy(Ey);\n  electric_energy_x.push_back(std::sqrt(eex));\n  electric_energy_y.push_back(std::sqrt(eey));\n  electric_energy.push_back(std::sqrt(eex+eey));\n\n  while ( current_t<c.Tf ) {\n    std::cout << \"\\r\" << current_t << \" / \" << c.Tf << std::flush; \n\n/*\n    Lie.H_E_tilde(dt,jcx,jcy,Ex,Ey,hf);\n    //for ( int i = 0 ; i<c.Nz ; ++i ) { jcx[i] = 0.; jcy[i] = 0.; }\n    Lie.H_jc(dt,jcx,jcy,Ex,Ey,hf);\n    //for ( int i = 0 ; i<c.Nz ; ++i ) { jcx[i] = 0.; jcy[i] = 0.; }\n    Lie.H_f_tilde(dt,jcx,jcy,Ex,Ey,hf);\n    //for ( int i = 0 ; i<c.Nz ; ++i ) { jcx[i] = 0.; jcy[i] = 0.; }\n*/\n\n    Lie.H_E(dt,jcx,jcy,Ex,Ey,hf);\n    //for ( int i = 0 ; i<c.Nz ; ++i ) { jcx[i] = 0.; jcy[i] = 0.; }\n\n    Lie.H_jc(dt,jcx,jcy,Ex,Ey,hf);\n    //for ( int i = 0 ; i<c.Nz ; ++i ) { jcx[i] = 0.; jcy[i] = 0.; }\n\n    Lie.H_f(dt,jcx,jcy,Ex,Ey,hf);\n    //for ( int i = 0 ; i<c.Nz ; ++i ) { jcx[i] = 0.; jcy[i] = 0.; }\n\n    eex = compute_electric_energy(Ex); eey = compute_electric_energy(Ey);\n    electric_energy.push_back( std::sqrt(eex+eey) );\n    electric_energy_x.push_back(std::sqrt(eex));\n    electric_energy_y.push_back(std::sqrt(eey));\n    current_t += dt;\n    times.push_back(current_t);\n  }\n\n  auto dt_y = [&,count=0] (auto const& y) mutable {\n    std::stringstream ss; ss<<times[count++]<<\" \"<<y;\n    return ss.str();\n  };\n  c << monitoring::data( \"ee_tilde.dat\"  , electric_energy   , dt_y );\n  c << monitoring::data( \"eex_tilde.dat\" , electric_energy_x , dt_y );\n  c << monitoring::data( \"eey_tilde.dat\" , electric_energy_y , dt_y );\n\n  return 0;\n}\n", "meta": {"hexsha": "43cd8aaa9e5db90b18382d13182fad1e84f19a27", "size": 5509, "ext": "cc", "lang": "C++", "max_stars_repo_path": "code/hybrid1dx3dv_b0.cc", "max_stars_repo_name": "kivvix/vlasovpp", "max_stars_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/hybrid1dx3dv_b0.cc", "max_issues_repo_name": "kivvix/vlasovpp", "max_issues_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/hybrid1dx3dv_b0.cc", "max_forks_repo_name": "kivvix/vlasovpp", "max_forks_repo_head_hexsha": "123072d42ddcceef9278e0cd3ac18d5b3fa4b3c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5914634146, "max_line_length": 114, "alphanum_fraction": 0.590669813, "num_tokens": 1959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.4049432421375034}}
{"text": "//=======================================================================\n// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file iterative_rounding_example.cpp\n * @brief Iterative rounding example\n * This is an example implementation of an algorithm within the Iterative\n * Rounding framework.\n * The implemented algorithm is a vertex cover 2-approximation.\n * @author Piotr Godlewski\n * @version 1.0\n * @date 2014-03-24\n */\n\n\n//! [Iterative Rounding Problem Example]\n#include \"paal/iterative_rounding/iterative_rounding.hpp\"\n#include \"paal/utils/floating.hpp\"\n#include \"paal/utils/functors.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/range/iterator_range.hpp>\n\n#include <iostream>\n#include <unordered_map>\n\nnamespace ir = paal::ir;\n\ntemplate <typename Graph, typename CostMap, typename OutputIter>\nclass vertex_cover {\npublic:\n    vertex_cover(const Graph & g, CostMap cost_map, OutputIter cover) :\n        m_g(g), m_cost_map(cost_map), m_cover(cover) {}\n\n    using Vertex = typename boost::graph_traits<Graph>::vertex_descriptor;\n    using VertexMap = std::unordered_map<Vertex, paal::lp::col_id>;\n\n    const Graph &get_graph() const { return m_g; }\n\n    auto get_cost(Vertex v)->decltype(std::declval<CostMap>()(v)) {\n        return m_cost_map(v);\n    }\n\n    void bind_col_to_vertex(paal::lp::col_id col, Vertex v) {\n        m_vertex_map.insert(typename VertexMap::value_type(v, col));\n    }\n\n    paal::lp::col_id vertex_to_column(Vertex v) { return m_vertex_map[v]; }\n\n    void add_to_cover(Vertex v) {\n        *m_cover = v;\n        ++m_cover;\n    }\n\n  private:\n    const Graph &m_g;\n    CostMap m_cost_map;\n    OutputIter m_cover;\n    VertexMap m_vertex_map;\n};\n//! [Iterative Rounding Problem Example]\n\n//! [Iterative Rounding Components Example]\nstruct vertex_cover_init {\n    template <typename Problem, typename LP>\n    void operator()(Problem &problem, LP &lp) {\n        lp.set_optimization_type(paal::lp::MINIMIZE);\n\n        // variables for vertices\n        for (auto v :\n             boost::make_iterator_range(vertices(problem.get_graph()))) {\n            problem.bind_col_to_vertex(lp.add_column(problem.get_cost(v)), v);\n        }\n\n        // x_u + x_v >= 1 for each edge e=(u,v)\n        for (auto e : boost::make_iterator_range(edges(problem.get_graph()))) {\n            auto x_u = problem.vertex_to_column(source(e, problem.get_graph()));\n            auto x_v = problem.vertex_to_column(target(e, problem.get_graph()));\n            lp.add_row(x_u + x_v >= 1);\n        }\n    }\n};\n\nstruct vertex_cover_set_solution {\n    template <typename Problem, typename GetSolution>\n    void operator()(Problem &problem, const GetSolution &solution) {\n        // add vertices with column value equal 1 to cover\n        for (auto v :\n             boost::make_iterator_range(vertices(problem.get_graph()))) {\n            if (m_compare.e(solution(problem.vertex_to_column(v)), 1)) {\n                problem.add_to_cover(v);\n            }\n        }\n    }\n\nprivate:\n    const paal::utils::compare<double> m_compare;\n};\n\nusing vertex_cover_ir_components =\n    ir::IRcomponents<vertex_cover_init, ir::round_condition_greater_than_half,\n                     paal::utils::always_false, vertex_cover_set_solution>;\n//! [Iterative Rounding Components Example]\n\n//! [Iterative Rounding Example]\nint main() {\n    using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,\n        boost::no_property, boost::no_property>;\n    using Vertex = boost::graph_traits<Graph>::vertex_descriptor;\n\n    // sample problem\n    std::vector<std::pair<int, int>> edges{ { 0, 1 }, { 0, 2 }, { 1, 2 },\n                                            { 1, 3 }, { 1, 4 }, { 1, 5 },\n                                            { 5, 0 }, { 3, 4 } };\n    std::vector<int> costs{ 1, 2, 1, 2, 1, 5 };\n\n    Graph g(edges.begin(), edges.end(), 6);\n    auto vertex_costs = paal::utils::make_array_to_functor(costs);\n    std::vector<Vertex> result_cover;\n    auto insert_iter = std::back_inserter(result_cover);\n\n    vertex_cover<Graph, decltype(vertex_costs), decltype(insert_iter)> problem(\n        g, vertex_costs, insert_iter);\n\n    // solve it\n    auto result =\n        ir::solve_iterative_rounding(problem, vertex_cover_ir_components());\n\n    // print result\n    if (result.first == paal::lp::OPTIMAL) {\n        std::cout << \"Vertices in the cover:\" << std::endl;\n        for (auto v : result_cover) {\n            std::cout << \"Vertex \" << v << std::endl;\n        }\n        std::cout << \"Cost of the solution: \" << *(result.second) << std::endl;\n    } else {\n        std::cout << \"The instance is infeasible\" << std::endl;\n    }\n    paal::lp::glp::free_env();\n    return 0;\n}\n//! [Iterative Rounding Example]\n", "meta": {"hexsha": "9e3dc1597e8380d9bb1087ce833b94c225a2ee95", "size": 4924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/iterative_rounding/iterative_rounding_example.cpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/iterative_rounding/iterative_rounding_example.cpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/iterative_rounding/iterative_rounding_example.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 33.4965986395, "max_line_length": 85, "alphanum_fraction": 0.6218521527, "num_tokens": 1201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4048936307733618}}
{"text": "#include <iostream>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n#include <opencv2/xfeatures2d.hpp>\n#include <opencv2/xfeatures2d/nonfree.hpp>\n#include <opencv2/opencv.hpp>\n\n#include <g2o/core/base_vertex.h>\n#include <g2o/core/base_unary_edge.h>\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/solvers/dense/linear_solver_dense.h>\n#include <sophus/se3.hpp>\n#include <Eigen/Core>\n\n#include <chrono>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\nusing namespace std;\nusing namespace cv;\n\nvoid writeResults( const string& filename, const vector<string>& timestamps, const vector<Mat>& Rt )\n{\n    CV_Assert( timestamps.size() == Rt.size() );\n\n    ofstream file( filename.c_str() );\n    if( !file.is_open() )\n        return;\n\n    cout.precision(4);\n    for( size_t i = 0; i < Rt.size(); i++ )\n    {\n        const Mat& Rt_curr = Rt[i];\n        if( Rt_curr.empty() )\n            continue;\n\n        CV_Assert( Rt_curr.type() == CV_64FC1 );\n\n        Mat R = Rt_curr(Rect(0,0,3,3)), rvec;\n        Rodrigues(R, rvec);\n        double alpha = norm( rvec );\n        if(alpha > DBL_MIN)\n            rvec = rvec / alpha;\n\n        double cos_alpha2 = std::cos(0.5 * alpha);\n        double sin_alpha2 = std::sin(0.5 * alpha);\n\n        rvec *= sin_alpha2;\n\n        CV_Assert( rvec.type() == CV_64FC1 );\n        // timestamp tx ty tz qx qy qz qw\n        file << timestamps[i] << \" \" << fixed\n             << Rt_curr.at<double>(0,3) << \" \" << Rt_curr.at<double>(1,3) << \" \" << Rt_curr.at<double>(2,3) << \" \"\n             << rvec.at<double>(0) << \" \" << rvec.at<double>(1) << \" \" << rvec.at<double>(2) << \" \" << cos_alpha2 << endl;\n\n    }\n    file.close();\n}\n\nvoid find_feature_matches(\n const Mat &img_1, const Mat &img_2, std::vector<KeyPoint> &keypoints_1,vector<KeyPoint> &keypoints_2,std::vector<DMatch> &matches, const Mat &img_3);\n void find_feature_matches_another(\n const Mat &img_1, const Mat &img_2, std::vector<KeyPoint> &keypoints_1,vector<KeyPoint> &keypoints_2,std::vector<DMatch> &matches, const Mat &img_3);\n\n// // 像素坐标转相机归一化坐标\n Point2d pixel2cam(const Point2d &p, const Mat &K);\n\n// BA by g2o\ntypedef vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> VecVector2d;\ntypedef vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> VecVector3d;\n\nMat bundleAdjustmentG2O(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose,\n  const string& filename, \n  const vector<string>& timestamps\n);\n\nint main(int argc, char **argv) {\n\tif(argc != 4){\n        cout << \"Format: file_with_rgb_depth_pairs trajectory_file odometry_name [Rgbd or ICP or RgbdICP or FastICP]\" << endl;\n        return -1;\n   }\n\n   vector<string> timestamps;\n   vector<Mat> Rts, Rts_ba;\n\n   const string filename = argv[1];\n   ifstream file( filename.c_str() );\n   if( !file.is_open() )\n      return -1;\n   char dlmrt = '/';\n   size_t pos = filename.rfind(dlmrt);\n   string dirname = pos == string::npos ? \"\" : filename.substr(0, pos) + dlmrt;\n\n   const int timestampLength = 17;\n   const int rgbPathLehgth = 17+8;\n   const int depthPathLehgth = 17+10;\n\n   float fx = 517.3f, // default\n         fy = 516.5f,\n         cx = 318.6f,\n         cy = 255.3f;\n   string datas[793];\n   string str1;\n   std::getline(file, str1);\n    datas[0] = str1;\n   \n        \n    for(int i = 1; !file.eof(); i++){\n        string str;\n        std::getline(file, str);\n        datas[i] = str;\n        if(str.empty()) break;\n        if(str.at(0) == '#') continue; /* comment */\n        cout << \" previous image: \" << datas[i-1] << \"\\n\" << \" current image \"<< str << endl;\n        Mat image, depth, image1, depth1, image2, depth2;\n        // if(i > 2) {\n        //     string rgbFilename2 = datas[i-2].substr(timestampLength + 1, rgbPathLehgth );\n        //     string timestap2 = datas[i-2].substr(0, timestampLength);\n        //     string depthFilename2 = datas[i-2].substr(2*timestampLength + rgbPathLehgth + 3, depthPathLehgth );\n\n        //     image2 = imread(dirname + rgbFilename2);\n        //     depth2 = imread(dirname + depthFilename2, -1);\n        // }\n        \n        string rgbFilename1 = datas[i-1].substr(timestampLength + 1, rgbPathLehgth );\n        string timestap1 = datas[i-1].substr(0, timestampLength);\n        string depthFilename1 = datas[i-1].substr(2*timestampLength + rgbPathLehgth + 3, depthPathLehgth );\n        image1 = imread(dirname + rgbFilename1);\n        depth1 = imread(dirname + depthFilename1, -1);\n    \n        string rgbFilename = str.substr(timestampLength + 1, rgbPathLehgth );\n        string timestap = str.substr(0, timestampLength);\n        string depthFilename = str.substr(2*timestampLength + rgbPathLehgth + 3, depthPathLehgth );\n        image = imread(dirname + rgbFilename);\n        depth = imread(dirname + depthFilename, -1);\n\n        // cout << \"prev prev \" << datas[i-2] << \" previous image: \" << datas[i-1] << \" current image \"<< str << endl;\n        // CV_Assert(!image.empty());\n        // CV_Assert(!depth.empty());\n        // CV_Assert(!image1.empty());\n        // CV_Assert(!depth1.empty());\n        // CV_Assert(depth.type() == CV_16UC1);\n        // CV_Assert(depth1.type() == CV_16UC1);\n\n        // if(i > 2){\n        //     CV_Assert(!image2.empty());\n        //     CV_Assert(!depth2.empty()); \n        //     CV_Assert(depth2.type() == CV_16UC1);\n        // }\n\n\n        std::vector<KeyPoint> keypoints_1, keypoints_2, key1, key2;\n        vector<DMatch> matches;\n        Ptr<FeatureDetector> detector = ORB::create();\n        detector->detect(image1, key1);\n        detector->detect(image, key2);\n        if(key1.size() == 0 || key2.size() == 0){\n            find_feature_matches_another(image1, image, keypoints_1, keypoints_2, matches, image2);\n            cout << \"第二個: \" <<  \"一共找到了\" << matches.size() << \"组匹配点\" << endl;\n        }\n        else{\n            find_feature_matches(image1, image, keypoints_1, keypoints_2, matches, image2);\n            cout << \"第一個: \" <<\"一共找到了\" << matches.size() << \"组匹配点\" << endl;\n        }\n        \n        // 建立3D点\n        //Mat d1 = imread(depth1, IMREAD_UNCHANGED);       // 深度图为16位无符号数，单通道图像\n        Mat K = (Mat_<double>(3, 3) << 517.3f, 0, 318.6f, 0, 516.5f, 255.3f, 0, 0, 1);\n        vector<Point2f> pts_2d_old;\n        vector<Point2f> pts_2d;\n        int index = 1;\n        for (DMatch m:matches) {\n                ushort d = depth1.ptr<unsigned short>(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)];\n                // cout << \"depth \" << d << endl;\n                if (d == 0){   // bad depth\n                    continue;\n                // d = 1;\n                }\n                // cout << \"this is matches: \" <<  index << endl;\n                float dd = d / 5000.0;\n                // cout << \"keypoints_1[m.queryIdx].pt \" << keypoints_1[m.queryIdx].pt << endl;\n                Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n                // cout << \"p1.x \" << p1.x << \" p1.y \" << p1.y << endl;\n                // cout << \"keypoints_2[m.trainIdx].pt \" << keypoints_2[m.trainIdx].pt << endl;\n                pts_2d_old.push_back(Point2f(p1.x * dd, p1.y * dd));\n                pts_2d.push_back(keypoints_2[m.trainIdx].pt);\n                index += 1;\n            // }\n        }\n        bool b = false;\n        // if(i ==373) {b = true;}\n        cout << \"2d-2d pairs: \" << pts_2d_old.size() << \" \" << pts_2d.size() << \" \"  << i <<  endl;\n        vector<Scalar> colors;\n        cv::RNG rng;\n        for(int i = 0; i < 100; i++){\n            int r = rng.uniform(0, 256);\n            int g = rng.uniform(0, 256);\n            int b = rng.uniform(0, 256);\n            colors.push_back(Scalar(r,g,b));\n        }\n        // vector<Point2f> p_old, p_new;\n        // cv::goodFeaturesToTrack(image1, p_old, 100, 0.3, 7, Mat(), 7, false, 0.04);\n        // // Calculate optical flow\n        vector<uchar> status;\n        vector<float> err;\n        Mat mask = Mat::zeros(image1.size(), image1.type());\n        cv::TermCriteria criteria = TermCriteria((TermCriteria::COUNT) + (TermCriteria::EPS), 10, 0.03);\n        cv::calcOpticalFlowPyrLK(image, image1, pts_2d_old, pts_2d, status, err, Size(15,15), 2, criteria);\n        vector<Point2f> good_new;\n        // Visualization part\n        for(uint i = 0; i < pts_2d_old.size(); i++){\n            // Select good points\n            if(status[i] == 1) {\n                good_new.push_back(pts_2d[i]);\n                // Draw the tracks\n                line(mask,pts_2d[i], pts_2d_old[i], colors[i], 2);\n                circle(image, pts_2d[i], 5, colors[i], -1);\n            }\n        }\n        // Display the demo\n        Mat img;\n        cv::add(image, mask, img);\n        // if (save) {\n        //     string save_path = \"./optical_flow_frames/frame_\" + to_string(counter) + \".jpg\";\n        //     imwrite(save_path, img);\n        // }\n        cv::imshow(\"flow\", img);\n        // int keyboard = cv::waitKey(25);\n        // if (keyboard == 'q' || keyboard == 27)\n        //     break;\n        // Update the previous frame and previous points\n        image1 = image.clone();\n        pts_2d_old = good_new;\n\n      \n//       chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n//       Mat r, t, inliers;\n//       solvePnPRansac(pts_3d, pts_2d, K, Mat(), r, t, b, 300, 0.05, 0.95, inliers);\n//       // cout << inliers << inliers.size()  << inliers.at<int>(1,0)  << inliers.at<int>(3,0)<< endl;\n//       for (int i=0; i<inliers.rows; i++){\n//          cout << \"inliers -> keypoints_1: \" << keypoints_1[inliers.at<int>(i,0)].pt << \"inliers -> keypoints_2: \" << keypoints_2[inliers.at<int>(i,0)].pt << endl;\n//       }\n//       // cout << \"inliers \"<< inliers << endl;\n//       cout<<\"pnp OK = \"<<b<<\", inliers point num = \"<<inliers.rows<<endl;\n//       Mat R;\n//       cv::Rodrigues(r, R); // r为旋转向量形式，用Rodrigues公式转换为矩阵\n//       chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n//       chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n//       cout << \"solve pnp in opencv cost time: \" << time_used.count() << \" seconds.\" << endl;\n\n//       cout << \"R=\" << endl << R << endl;\n//       cout << \"t=\" << endl << t << endl;\n//       timestamps.push_back( timestap );\n//       Mat output;\n//       hconcat(R, t, output);\n   \n//       Mat Rt = Mat::eye(4,4,CV_64FC1);\n//       Rt.at<double>(0,0) = R.at<double>(0,0);\n//       Rt.at<double>(0,1) = R.at<double>(0,1);\n//       Rt.at<double>(0,2) = R.at<double>(0,2);\n//       Rt.at<double>(1,0) = R.at<double>(1,0);\n//       Rt.at<double>(1,1) = R.at<double>(1,1);\n//       Rt.at<double>(1,2) = R.at<double>(1,2);\n//       Rt.at<double>(2,0) = R.at<double>(2,0);\n//       Rt.at<double>(2,1) = R.at<double>(2,1);\n//       Rt.at<double>(2,2) = R.at<double>(2,2);\n//       Rt.at<double>(0,3) = t.at<double>(0,0);\n//       Rt.at<double>(1,3) = t.at<double>(0,1);\n//       Rt.at<double>(2,3) = t.at<double>(0,2);\n//       cout << \"Rt \" << Rt << endl;  \n//       Rts.push_back(Rt);\n\n//       Mat Rt_ba;\n\n//       VecVector3d pts_3d_eigen;\n//       VecVector2d pts_2d_eigen;\n//       for (size_t i = 0; i < pts_3d.size(); ++i) {\n//          // cout << \"vector3d \" << Eigen::Vector3d(pts_3d[i].x, pts_3d[i].y, pts_3d[i].z) << \"vector2d \" << Eigen::Vector2d(pts_2d[i].x, pts_2d[i].y) << endl;\n//          pts_3d_eigen.push_back(Eigen::Vector3d(pts_3d[i].x, pts_3d[i].y, pts_3d[i].z));\n//          pts_2d_eigen.push_back(Eigen::Vector2d(pts_2d[i].x, pts_2d[i].y));\n//       }\n//       // for (size_t i = 0; i < pts_3d.size(); ++i) {\n//       //    for (size_t j = 0; j < 3; ++j) {\n//       //       cout << \" eigen3d \" << pts_3d_eigen[i][j] << cout << \" eigen2d \"  <<*pts_2d_eigen[i][j];\n//       //    }\n//       // }\n//       cout << \"calling bundle adjustment by g2o\" << endl;\n//       Sophus::SE3d pose_g2o;\n//       t1 = chrono::steady_clock::now();\n//       Rt_ba = bundleAdjustmentG2O(pts_3d_eigen, pts_2d_eigen, K, pose_g2o, argv[2], timestamps);\n//       Rts_ba.push_back(Rt_ba);\n//       t2 = chrono::steady_clock::now();\n//       time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n//       cout << \"solve pnp by g2o cost time: \" << time_used.count() << \" seconds.\" << endl;\n   }\n//    writeResults(argv[2], timestamps, Rts);\n//    //writeResults(argv[2], timestamps, Rts_ba);\n   \n  return 0;\n}\nvoid find_feature_matches_another(const Mat &img_1, const Mat &img_2,\n                           std::vector<KeyPoint> &keypoints_1,\n\t\t\t                  std::vector<KeyPoint> &keypoints_2,\n                           std::vector<DMatch> &matches,\n                           const Mat &img_3) {\n   Mat descriptors_1, descriptors_2, descriptors_3, descriptors_4;\n   Ptr<FeatureDetector> detector = AgastFeatureDetector::create();\n   Ptr<DescriptorExtractor> descriptor = AgastFeatureDetector::create();\n   Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n   detector->detect(img_1, keypoints_1);\n   detector->detect(img_2, keypoints_2);\n   cout << \"keypoints_1.size() \"<< keypoints_1.size() << \" keypoints_2.size() \" << keypoints_2.size() << endl;\n   // if(keypoints_1.size() != 0 && keypoints_2.size() != 0){\n      for (int i=0; i< keypoints_1.size(); i++){\n         // cout << \"keypoint1 \" << keypoints_1[i].pt << \"keypoint2 \" << keypoints_2[i].pt << endl;\n      }\n      descriptor->compute(img_1, keypoints_1, descriptors_1);\n      descriptor->compute(img_2, keypoints_2, descriptors_2);\n   // }\n   int eee = descriptors_1.empty();\n   int ddd = descriptors_2.empty();\n\n   vector<DMatch> match;\n   matcher->match(descriptors_1, descriptors_2, match);\n   double min_dist = 10000, max_dist = 0;\n     for (int i = 0; i < descriptors_1.rows; i++) {\n    double dist = match[i].distance;\n     if (dist < min_dist) min_dist = dist;\n     if (dist > max_dist) max_dist = dist;\n   }\n   printf(\"-- Max dist : %f \\n\", max_dist);\n   printf(\"-- Min dist : %f \\n\", min_dist);\n   for (int i = 0; i < descriptors_1.rows; i++) {\n    if (match[i].distance <= max(2 * min_dist, 10.0)) {\n       matches.push_back(match[i]);\n     }\n   }\n }\n void find_feature_matches(const Mat &img_1, const Mat &img_2,\n                           std::vector<KeyPoint> &keypoints_1,\n\t\t\t                  std::vector<KeyPoint> &keypoints_2,\n                           std::vector<DMatch> &matches,\n                           const Mat &img_3) {\n\n   Mat descriptors_1, descriptors_2, descriptors_3, descriptors_4;\n   Ptr<FeatureDetector> detector = ORB::create();\n   Ptr<DescriptorExtractor> descriptor = ORB::create();\n   Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n   detector->detect(img_1, keypoints_1);\n   detector->detect(img_2, keypoints_2);\n   cout << \"keypoints_1.size() \"<< keypoints_1.size() << \" keypoints_2.size() \" << keypoints_2.size() << endl;\n      for (int i=0; i< keypoints_1.size(); i++){\n         // cout << \"keypoint1 \" << keypoints_1[i].pt << \"keypoint2 \" << keypoints_2[i].pt << endl;\n      }\n      descriptor->compute(img_1, keypoints_1, descriptors_1);\n      descriptor->compute(img_2, keypoints_2, descriptors_2);\n   int eee = descriptors_1.empty();\n   int ddd = descriptors_2.empty();\n   vector<DMatch> match;\n   matcher->match(descriptors_1, descriptors_2, match);\n   double min_dist = 10000, max_dist = 0;\n     for (int i = 0; i < descriptors_1.rows; i++) {\n    double dist = match[i].distance;\n     if (dist < min_dist) min_dist = dist;\n     if (dist > max_dist) max_dist = dist;\n   }\n\n   printf(\"-- Max dist : %f \\n\", max_dist);\n   printf(\"-- Min dist : %f \\n\", min_dist);\n   for (int i = 0; i < descriptors_1.rows; i++) {\n    if (match[i].distance <= max(2 * min_dist, 10.0)) {\n       matches.push_back(match[i]);\n     }\n   }\n }\n\n Point2d pixel2cam(const Point2d &p, const Mat &K) {\n   return Point2d\n     (\n       (p.x - K.at<double>(0, 2)) / K.at<double>(0, 0),\n       (p.y - K.at<double>(1, 2)) / K.at<double>(1, 1)\n     );\n }\n\n/// vertex and edges used in g2o ba\nclass VertexPose : public g2o::BaseVertex<6, Sophus::SE3d> {\n   public:\n      EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n   virtual void setToOriginImpl() override {\n      _estimate = Sophus::SE3d();\n   }\n\n   /// left multiplication on SE3\n   virtual void oplusImpl(const double *update) override {\n      Eigen::Matrix<double, 6, 1> update_eigen;\n      update_eigen << update[0], update[1], update[2], update[3], update[4], update[5];\n      _estimate = Sophus::SE3d::exp(update_eigen) * _estimate;\n   }\n\n   virtual bool read(istream &in) override {}\n\n   virtual bool write(ostream &out) const override {}\n};\n\nclass EdgeProjection : public g2o::BaseUnaryEdge<2, Eigen::Vector2d, VertexPose> {\n   public:\n      EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n      EdgeProjection(const Eigen::Vector3d &pos, const Eigen::Matrix3d &K) : _pos3d(pos), _K(K) {}\n\n   virtual void computeError() override {\n      const VertexPose *v = static_cast<VertexPose *> (_vertices[0]);\n      Sophus::SE3d T = v->estimate();\n      Eigen::Vector3d pos_pixel = _K * (T * _pos3d);\n      pos_pixel /= pos_pixel[2];\n      _error = _measurement - pos_pixel.head<2>();\n   }\n\n   virtual void linearizeOplus() override {\n      const VertexPose *v = static_cast<VertexPose *> (_vertices[0]);\n      Sophus::SE3d T = v->estimate();\n      Eigen::Vector3d pos_cam = T * _pos3d;\n      double fx = _K(0, 0);\n      double fy = _K(1, 1);\n      double cx = _K(0, 2);\n      double cy = _K(1, 2);\n      double X = pos_cam[0];\n      double Y = pos_cam[1];\n      double Z = pos_cam[2];\n      double Z2 = Z * Z;\n      _jacobianOplusXi\n         << -fx / Z, 0, fx * X / Z2, fx * X * Y / Z2, -fx - fx * X * X / Z2, fx * Y / Z,\n         0, -fy / Z, fy * Y / (Z * Z), fy + fy * Y * Y / Z2, -fy * X * Y / Z2, -fy * X / Z;\n   }\n\n   virtual bool read(istream &in) override {}\n\n   virtual bool write(ostream &out) const override {}\n\n   private:\n      Eigen::Vector3d _pos3d;\n      Eigen::Matrix3d _K;\n};\n\nMat bundleAdjustmentG2O(\n  const VecVector3d &points_3d,\n  const VecVector2d &points_2d,\n  const Mat &K,\n  Sophus::SE3d &pose,\n  const string& filename, \n  const vector<string>& timestamps) {\n\n  // 构建图优化，先设定g2o\n  typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 3>> BlockSolverType;  // pose is 6, landmark is 3\n  typedef g2o::LinearSolverDense<BlockSolverType::PoseMatrixType> LinearSolverType; // 线性求解器类型\n  // 梯度下降方法，可以从GN, LM, DogLeg 中选\n  auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n  g2o::make_unique<BlockSolverType>(g2o::make_unique<LinearSolverType>()));\n  g2o::SparseOptimizer optimizer;     // 图模型\n  optimizer.setAlgorithm(solver);   // 设置求解器\n  optimizer.setVerbose(true);       // 打开调试输出\n\n  // vertex\n  VertexPose *vertex_pose = new VertexPose(); // camera vertex_pose\n  vertex_pose->setId(0);\n  vertex_pose->setEstimate(Sophus::SE3d());\n  optimizer.addVertex(vertex_pose);\n\n  // K\n  Eigen::Matrix3d K_eigen;\n  K_eigen <<\n          K.at<double>(0, 0), K.at<double>(0, 1), K.at<double>(0, 2),\n    K.at<double>(1, 0), K.at<double>(1, 1), K.at<double>(1, 2),\n    K.at<double>(2, 0), K.at<double>(2, 1), K.at<double>(2, 2);\n\n  // edges\n  int index = 1;\n  for (size_t i = 0; i < points_2d.size(); ++i) {\n    auto p2d = points_2d[i];\n    auto p3d = points_3d[i];\n    EdgeProjection *edge = new EdgeProjection(p3d, K_eigen);\n    edge->setId(index);\n    edge->setVertex(0, vertex_pose);\n    edge->setMeasurement(p2d);\n    edge->setInformation(Eigen::Matrix2d::Identity());\n    optimizer.addEdge(edge);\n    index++;\n  }\n\n  chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n  optimizer.setVerbose(true);\n  optimizer.initializeOptimization();\n  optimizer.optimize(10);\n  chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n  chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);\n  cout << \"optimization costs time: \" << time_used.count() << \" seconds.\" << endl;\n  cout << \"pose estimated by g2o =\\n\" << vertex_pose->estimate().matrix() << endl;\n//   cout << \"pose matrix \"  << vertex_pose->estimate().matrix()(0) << vertex_pose->estimate().matrix()(1) << vertex_pose->estimate().matrix()(4) << endl;\n\n  Mat Rt = Mat::eye(4,4,CV_64FC1);\n  Rt.at<double>(0,0) = vertex_pose->estimate().matrix()(0);\n  Rt.at<double>(1,0) = vertex_pose->estimate().matrix()(1);\n  Rt.at<double>(2,0) = vertex_pose->estimate().matrix()(2);\n  Rt.at<double>(3,0) = vertex_pose->estimate().matrix()(3);\n  Rt.at<double>(0,1) = vertex_pose->estimate().matrix()(4);\n  Rt.at<double>(1,1) = vertex_pose->estimate().matrix()(5);\n  Rt.at<double>(2,1) = vertex_pose->estimate().matrix()(6);\n  Rt.at<double>(3,1) = vertex_pose->estimate().matrix()(7);\n  Rt.at<double>(0,2) = vertex_pose->estimate().matrix()(8);\n  Rt.at<double>(1,2) = vertex_pose->estimate().matrix()(9);\n  Rt.at<double>(2,2) = vertex_pose->estimate().matrix()(10);\n  Rt.at<double>(3,2) = vertex_pose->estimate().matrix()(11);\n  Rt.at<double>(0,3) = vertex_pose->estimate().matrix()(12);\n  Rt.at<double>(1,3) = vertex_pose->estimate().matrix()(13);\n  Rt.at<double>(2,3) = vertex_pose->estimate().matrix()(14);\n  Rt.at<double>(3,3) = vertex_pose->estimate().matrix()(15);\n  \n//   writeResults(filename, timestamps, vertex_pose->estimate().matrix());\n  pose = vertex_pose->estimate();\n  return Rt;\n}\n\n\n", "meta": {"hexsha": "130d4403444ab99ed7137d6c3883bca59a7e5050", "size": 21468, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "flow_old.cpp", "max_stars_repo_name": "Peter52550/visual-odometry", "max_stars_repo_head_hexsha": "985a02b69ff8384a2b488500c7308f0e58385739", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "flow_old.cpp", "max_issues_repo_name": "Peter52550/visual-odometry", "max_issues_repo_head_hexsha": "985a02b69ff8384a2b488500c7308f0e58385739", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "flow_old.cpp", "max_forks_repo_name": "Peter52550/visual-odometry", "max_forks_repo_head_hexsha": "985a02b69ff8384a2b488500c7308f0e58385739", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1271028037, "max_line_length": 165, "alphanum_fraction": 0.5857089622, "num_tokens": 6618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702880639792, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4047146492177786}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <iomanip>\n\n#include \"../include/structures.h\"\n#include \"../include/transformations.h\"\n#include \"../../point_to_point_source_to_target_tait_bryan_wc_jacobian.h\"\n#include \"../../point_to_point_source_to_target_rodrigues_wc_jacobian.h\"\n#include \"../../point_to_point_source_to_target_quaternion_wc_jacobian.h\"\n#include \"../../quaternion_constraint_jacobian.h\"\n#include \"../include/cauchy.h\"\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = 0.0, rotate_y = 0.0;\nfloat translate_z = -100.0;\nfloat translate_x, translate_y = 0.0;\n\nbool initGL(int *argc, char **argv);\nvoid display();\nvoid keyboard(unsigned char key, int x, int y);\nvoid mouse(int button, int state, int x, int y);\nvoid motion(int x, int y);\nvoid reshape(int w, int h);\nvoid printHelp();\n\n\nEigen::Affine3d pose_source;\nstd::vector<Eigen::Vector3d> points_target_global;\nstd::vector<Eigen::Vector3d> points_source_local;\n\nint main(int argc, char *argv[]){\n\n\tfor(size_t i = 0 ; i < 100; i++){\n\t\tEigen::Vector3d p;\n\t\tp.x() = ((float(rand()%1000000))/1000000.0f - 0.5) * 100;\n\t\tp.y() = ((float(rand()%1000000))/1000000.0f - 0.5) * 100;\n\t\tp.z() = ((float(rand()%1000000))/1000000.0f - 0.5) * 100;\n\t\tpoints_target_global.push_back(p);\n\t}\n\n\tTaitBryanPose pose;\n\tpose.px = -4;\n\tpose.py = 0.4;\n\tpose.pz = -0.2;\n\tpose.om = 0.1;\n\tpose.fi = 0.2;\n\tpose.ka = 0.3;\n\tpose_source = affine_matrix_from_pose_tait_bryan(pose);\n\n\tEigen::Affine3d m_inv = pose_source.inverse();\n\tfor(size_t j = 0 ; j < points_target_global.size(); j++){\n\t\tEigen::Vector3d vt = m_inv * points_target_global[j];\n\t\tpoints_source_local.push_back(vt);\n\t}\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\n\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"point to point source to target\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01,\n\t\t\t10000.0);\n\tglutReshapeFunc(reshape);\n\n\treturn true;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tglBegin(GL_LINES);\n\tglColor3f(1.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(1.0f, 0.0f, 0.0f);\n\n\tglColor3f(0.0f, 1.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 1.0f, 0.0f);\n\n\tglColor3f(0.0f, 0.0f, 1.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 1.0f);\n\tglEnd();\n\n\n\tEigen::Affine3d &m = pose_source;\n\n\tglBegin(GL_LINES);\n\t\tglColor3f(1.0f, 0.0f, 0.0f);\n\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\tglVertex3f(m(0,3) + m(0,0), m(1,3) + m(1,0), m(2,3) + m(2,0));\n\n\t\tglColor3f(0.0f, 1.0f, 0.0f);\n\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\tglVertex3f(m(0,3) + m(0,1), m(1,3) + m(1,1), m(2,3) + m(2,1));\n\n\t\tglColor3f(0.0f, 0.0f, 1.0f);\n\t\tglVertex3f(m(0,3), m(1,3), m(2,3));\n\t\tglVertex3f(m(0,3) + m(0,2), m(1,3) + m(1,2), m(2,3) + m(2,2));\n\tglEnd();\n\n\n\tglColor3f(1,0,0);\n\tglPointSize(3);\n\tglBegin(GL_POINTS);\n\tfor(auto &p:points_source_local){\n\t\tEigen::Vector3d vt;\n\t\tvt = m * p;\n\t\tglVertex3f(vt.x(), vt.y(), vt.z());\n\t}\n\tglEnd();\n\tglPointSize(1);\n\n\tglColor3f(0,0,1);\n\tglPointSize(3);\n\tglBegin(GL_POINTS);\n\n\tfor(auto &p:points_target_global){\n\t\tglVertex3f(p.x(), p.y(), p.z());\n\t}\n\tglEnd();\n\tglPointSize(1);\n\n\tglColor3f(0,1,0);\n\tglBegin(GL_LINES);\n\tfor(int i = 0; i < points_source_local.size(); i++){\n\t\tEigen::Vector3d v(points_source_local[i].x(), points_source_local[i].y(), points_source_local[i].z());\n\t\tEigen::Vector3d vt;\n\t\tvt = m * v;\n\t\tglVertex3f(vt.x(), vt.y(), vt.z());\n\t\tglVertex3f(points_target_global[i].x(), points_target_global[i].y(), points_target_global[i].z());\n\t}\n\tglEnd();\n\n\tglutSwapBuffers();\n}\n\n\n\nvoid keyboard(unsigned char key, int /*x*/, int /*y*/) {\n\tswitch (key) {\n\t\tcase (27): {\n\t\t\tglutDestroyWindow(glutGetWindow());\n\t\t\treturn;\n\t\t}\n\t\tcase 'n':{\n\t\t\t\tTaitBryanPose pose;\n\t\t\t\tpose.px = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.0;\n\t\t\t\tpose.py = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.0;\n\t\t\t\tpose.pz = ((float(rand()%1000000))/1000000.0f - 0.5) * 1.0;\n\t\t\t\tpose.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\n\t\t\t\tpose_source = pose_source * affine_matrix_from_pose_tait_bryan(pose);\n\n\t\t\tbreak;\n\t\t}\n\t\tcase 't':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tTaitBryanPose pose_s = pose_tait_bryan_from_affine_matrix(pose_source);\n\nfor(size_t i = 0 ; i < points_source_local.size(); i++){\n\tEigen::Vector3d &p_t = points_target_global[i];\n\tEigen::Vector3d &p_s = points_source_local[i];\n\tdouble delta_x;\n\tdouble delta_y;\n\tdouble delta_z;\n\tpoint_to_point_source_to_target_tait_bryan_wc(delta_x, delta_y, delta_z, pose_s.px, pose_s.py, pose_s.pz, pose_s.om, pose_s.fi, pose_s.ka, p_s.x(), p_s.y(), p_s.z(), p_t.x(), p_t.y(), p_t.z());\n\n\tEigen::Matrix<double, 3, 6, Eigen::RowMajor> jacobian;\n\tpoint_to_point_source_to_target_tait_bryan_wc_jacobian(jacobian, pose_s.px, pose_s.py, pose_s.pz, pose_s.om, pose_s.fi, pose_s.ka, p_s.x(), p_s.y(), p_s.z());\n\n\tint ir = tripletListB.size();\n\n\tfor(int row = 0; row < 3; row++){\n\t\tfor(int col = 0; col < 6; col++){\n\t\t\tif(jacobian(row,col)!=0.0){\n\t\t\ttripletListA.emplace_back(ir+row,col,-jacobian(row,col));\n\t\t\t}\n\t\t}\n\t}\n\n\ttripletListP.emplace_back(ir    , ir    , 1);\n\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\n\ttripletListB.emplace_back(ir    , 0,  delta_x);\n\ttripletListB.emplace_back(ir + 1, 0,  delta_y);\n\ttripletListB.emplace_back(ir + 2, 0,  delta_z);\n}\n\nEigen::SparseMatrix<double> matA(tripletListB.size(), 6);\nEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\nEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\nmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\nmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\nmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\nEigen::SparseMatrix<double> AtPA(6, 6);\nEigen::SparseMatrix<double> AtPB(6, 1);\n\nEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\nAtPA = AtP * matA;\nAtPB = AtP * matB;\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\nEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\nEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(pose_source);\n\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\tpose.ka += h_x[counter++];\n\n\t\t\t\tpose_source = affine_matrix_from_pose_tait_bryan(pose);\n\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'r':{\n\n\t\t\tTaitBryanPose posetb = pose_tait_bryan_from_affine_matrix(pose_source);\n\t\t\tposetb.om += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\tposetb.fi += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\tposetb.ka += (float(rand()%1000000)/1000000.0 - 0.5) * 2.0 * 0.00001;\n\t\t\tpose_source = affine_matrix_from_pose_tait_bryan(posetb);\n\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tRodriguesPose pose_s = pose_rodrigues_from_affine_matrix(pose_source);\n\n\t\t\tfor(size_t i = 0 ; i < points_source_local.size(); i++){\n\t\t\t\tEigen::Vector3d &p_t = points_target_global[i];\n\t\t\t\tEigen::Vector3d &p_s = points_source_local[i];\n\t\t\t\tdouble delta_x;\n\t\t\t\tdouble delta_y;\n\t\t\t\tdouble delta_z;\n\t\t\t\tpoint_to_point_source_to_target_rodrigues_wc(delta_x, delta_y, delta_z, pose_s.px, pose_s.py, pose_s.pz, pose_s.sx, pose_s.sy, pose_s.sz, p_s.x(), p_s.y(), p_s.z(), p_t.x(), p_t.y(), p_t.z());\n\n\t\t\t\tEigen::Matrix<double, 3, 6, Eigen::RowMajor> jacobian;\n\t\t\t\tpoint_to_point_source_to_target_rodrigues_wc_jacobian(jacobian, pose_s.px, pose_s.py, pose_s.pz, pose_s.sx, pose_s.sy, pose_s.sz, p_s.x(), p_s.y(), p_s.z());\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\ttripletListA.emplace_back(ir     , 0, -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir     , 1, -jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir     , 2, -jacobian(0,2));\n\t\t\t\ttripletListA.emplace_back(ir     , 3, -jacobian(0,3));\n\t\t\t\ttripletListA.emplace_back(ir     , 4, -jacobian(0,4));\n\t\t\t\ttripletListA.emplace_back(ir     , 5, -jacobian(0,5));\n\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 0, -jacobian(1,0));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 1, -jacobian(1,1));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 2, -jacobian(1,2));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 3, -jacobian(1,3));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 4, -jacobian(1,4));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 5, -jacobian(1,5));\n\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 0, -jacobian(2,0));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 1, -jacobian(2,1));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 2, -jacobian(2,2));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 3, -jacobian(2,3));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 4, -jacobian(2,4));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 5, -jacobian(2,5));\n\n\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  cauchy(delta_x, 1));\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  cauchy(delta_y, 1));\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2,  cauchy(delta_z, 1));\n\n\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta_x);\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta_y);\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta_z);\n\t\t\t}\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(6, 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(6, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(pose_source);\n\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\tpose.sx += h_x[counter++];\n\t\t\t\tpose.sy += h_x[counter++];\n\t\t\t\tpose.sz += h_x[counter++];\n\n\t\t\t\tpose_source = affine_matrix_from_pose_rodrigues(pose);\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'q':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tQuaternionPose pose_s = pose_quaternion_from_affine_matrix(pose_source);\n\n\t\t\tfor(size_t i = 0 ; i < points_source_local.size(); i++){\n\t\t\t\tEigen::Vector3d &p_t = points_target_global[i];\n\t\t\t\tEigen::Vector3d &p_s = points_source_local[i];\n\t\t\t\tdouble delta_x;\n\t\t\t\tdouble delta_y;\n\t\t\t\tdouble delta_z;\n\t\t\t\tpoint_to_point_source_to_target_quaternion_wc(delta_x, delta_y, delta_z, pose_s.px, pose_s.py, pose_s.pz, pose_s.q0, pose_s.q1, pose_s.q2, pose_s.q3, p_s.x(), p_s.y(), p_s.z(), p_t.x(), p_t.y(), p_t.z());\n\n\t\t\t\tEigen::Matrix<double, 3, 7, Eigen::RowMajor> jacobian;\n\t\t\t\tpoint_to_point_source_to_target_quaternion_wc_jacobian(jacobian, pose_s.px, pose_s.py, pose_s.pz, pose_s.q0, pose_s.q1, pose_s.q2, pose_s.q3, p_s.x(), p_s.y(), p_s.z());\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\ttripletListA.emplace_back(ir     , 0, -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir     , 1, -jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir     , 2, -jacobian(0,2));\n\t\t\t\ttripletListA.emplace_back(ir     , 3, -jacobian(0,3));\n\t\t\t\ttripletListA.emplace_back(ir     , 4, -jacobian(0,4));\n\t\t\t\ttripletListA.emplace_back(ir     , 5, -jacobian(0,5));\n\t\t\t\ttripletListA.emplace_back(ir     , 6, -jacobian(0,6));\n\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 0, -jacobian(1,0));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 1, -jacobian(1,1));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 2, -jacobian(1,2));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 3, -jacobian(1,3));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 4, -jacobian(1,4));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 5, -jacobian(1,5));\n\t\t\t\ttripletListA.emplace_back(ir + 1 , 6, -jacobian(1,6));\n\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 0, -jacobian(2,0));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 1, -jacobian(2,1));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 2, -jacobian(2,2));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 3, -jacobian(2,3));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 4, -jacobian(2,4));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 5, -jacobian(2,5));\n\t\t\t\ttripletListA.emplace_back(ir + 2 , 6, -jacobian(2,6));\n\n\t\t\t\ttripletListP.emplace_back(ir    , ir    ,  cauchy(delta_x, 1));\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1,  cauchy(delta_y, 1));\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2,  cauchy(delta_z, 1));\n\n\t\t\t\ttripletListB.emplace_back(ir    , 0,  delta_x);\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0,  delta_y);\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0,  delta_z);\n\t\t\t}\n\n\n\t\t\tint ir = tripletListB.size();\n\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(pose_source);\n\n\t\t\tdouble delta;\n\t\t\tquaternion_constraint(delta, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\tEigen::Matrix<double, 1, 4> jacobian;\n\t\t\tquaternion_constraint_jacobian(jacobian, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\ttripletListA.emplace_back(ir, 3 , -jacobian(0,0));\n\t\t\ttripletListA.emplace_back(ir, 4 , -jacobian(0,1));\n\t\t\ttripletListA.emplace_back(ir, 5 , -jacobian(0,2));\n\t\t\ttripletListA.emplace_back(ir, 6 , -jacobian(0,3));\n\n\t\t\ttripletListP.emplace_back(ir, ir, 1000000.0);\n\n\t\t\ttripletListB.emplace_back(ir, 0, delta);\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), 7);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\t\t\tEigen::SparseMatrix<double> AtPA(7, 7);\n\t\t\tEigen::SparseMatrix<double> AtPB(7, 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(h_x.size() == 7){\n\t\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t\tstd::cout << \"update\" << std::endl;\n\n\t\t\t\tint counter = 0;\n\n\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(pose_source);\n\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\tpose.q0 += h_x[counter++];\n\t\t\t\tpose.q1 += h_x[counter++];\n\t\t\t\tpose.q2 += h_x[counter++];\n\t\t\t\tpose.q3 += h_x[counter++];\n\n\t\t\t\tpose_source = affine_matrix_from_pose_quaternion(pose);\n\t\t\t}else{\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"n: add noise to pose source\" << std::endl;\n\tstd::cout << \"t: optimize (Tait-Bryan)\" << std::endl;\n\tstd::cout << \"r: optimize (Rodrigues)\" << std::endl;\n\tstd::cout << \"q: optimize (Quaternion)\" << std::endl;\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "783ef1aef9c985f31f9045e7a16736befd844194", "size": 18865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/point_to_point_source_to_target.cpp", "max_stars_repo_name": "michalpelka/observation_equations", "max_stars_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "codes/c++Examples/src/point_to_point_source_to_target.cpp", "max_issues_repo_name": "michalpelka/observation_equations", "max_issues_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/c++Examples/src/point_to_point_source_to_target.cpp", "max_forks_repo_name": "michalpelka/observation_equations", "max_forks_repo_head_hexsha": "023ba4cd57d738447ed118279fdb4c06ae5746f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0279605263, "max_line_length": 208, "alphanum_fraction": 0.6532202491, "num_tokens": 6591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.40471463594394}}
{"text": "﻿//***********************************************************\r\n// 26/01/2021\t1.0.0\tRémi Saint-Amant   Creation\r\n//***********************************************************\r\n#include \"ALeucopodaModel.h\"\r\n//#include \"ALeucopodaEquations.h\"\r\n#include \"ModelBase/EntryPoint.h\"\r\n#include \"Basic\\DegreeDays.h\"\r\n//#include \"Leucopoda.h\"\r\n//#include <boost/math/distributions/weibull.hpp>\r\n//#include <boost/math/distributions/beta.hpp>\r\n//#include <boost/math/distributions/Rayleigh.hpp>\r\n#include <boost/math/distributions/logistic.hpp>\r\n//#include <boost/math/distributions/exponential.hpp>\r\n//#include <boost/math/distributions/lognormal.hpp>\r\n#include \"ModelBase/SimulatedAnnealingVector.h\"\r\n\r\nusing namespace WBSF::HOURLY_DATA;\r\nusing namespace std;\r\nusing namespace WBSF::TZZ;\r\n\r\n\r\n//static const bool BEGIN_JULY = true;\r\n//static const size_t FIRST_Y = BEGIN_JULY ? 1 : 0;\r\n\r\nnamespace WBSF\r\n{\r\n\r\n\tstatic const size_t NB_GENERATIONS_MAX = 6;\r\n\r\n\t//static const CDegreeDays::TDailyMethod DD_METHOD = CDegreeDays::MODIFIED_ALLEN_WAVE;\r\n\tstatic const CDegreeDays::TDailyMethod DD_METHOD = CDegreeDays::ALLEN_WAVE;\r\n\t//enum { O_CDD, O_GENERATION, O_DIAPAUSED, O_EGG, O_LARVA, O_PUPA, O_ADULT, O_DEAD_ADULT, O_BROOD, NB_OUTPUTS };\r\n\tenum { O_EGG, O_LARVA, O_PREPUPA, O_PUPA, O_ADULT, O_DEAD_ADULT, O_BROOD, O_DEAD_ATTRITION, NB_OUTPUT_ONE_G, O_IN_DIAPAUSE = (NB_OUTPUT_ONE_G * NB_GENERATIONS_MAX - O_PUPA), O_D_DAY_LENGTH, NB_DAILY_OUTPUTS };\r\n\r\n\r\n\t//this line link this model with the EntryPoint of the DLL\r\n\tstatic const bool bRegistred =\r\n\t\tCModelFactory::RegisterModel(CAprocerosLeucopodaModel::CreateObject);\r\n\r\n\tCAprocerosLeucopodaModel::CAprocerosLeucopodaModel()\r\n\t{\r\n\t\t//NB_INPUT_PARAMETER is used to determine if the dll\r\n\t\t//uses the same number of parameters than the model interface\r\n\t\tNB_INPUT_PARAMETER = -1;\r\n\t\tVERSION = \"1.0.0 (2021)\";\r\n\r\n\t\tm_generationSurvival = 1;\r\n//\t\tm_bCumul = false;\r\n//\t\tm_stage = 0;\r\n\t//\tm_T = 0;\r\n\r\n\t\t//m_EWD.fill(0);\r\n\t\t//m_EAS.fill(0);\r\n\t\t//Set parameters to equation\r\n\t\t//ASSERT(stand.m_equations.m_EWD.size() == m_EWD.size());\r\n\t\tfor (size_t p = 0; p < m_EWD.size(); p++)\r\n\t\t\tm_EWD[p] = CAprocerosLeucopodaEquations::EWD[p];\r\n\r\n\t\t//ASSERT(stand.m_equations.m_EAS.size() == m_EAS.size());\r\n\t\tfor (size_t p = 0; p < m_EAS.size(); p++)\r\n\t\t\tm_EAS[p] = CAprocerosLeucopodaEquations::EAS[p];\r\n\r\n\r\n\t\t//m_P.fill(0);\r\n\t\t/*m_P[Τᴴ²] = 19.1;\r\n\t\tm_P[delta] = 45;\r\n\t\tm_P[μ1] = 239.6;\r\n\t\tm_P[ѕ1] = 41.4;\r\n\t\tm_P[μ2] = 876.0;\r\n\t\tm_P[ѕ2] = 55.6;\r\n\t\tm_P[μ3] = 625.2;\r\n\t\tm_P[ѕ3] = 38.3;\r\n\t\t\t*/\r\n\t}\r\n\r\n\tCAprocerosLeucopodaModel::~CAprocerosLeucopodaModel()\r\n\t{\r\n\t}\r\n\r\n\r\n\t//this method is call to load your parameter in your variable\r\n\tERMsg CAprocerosLeucopodaModel::ProcessParameters(const CParameterVector& parameters)\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\tsize_t c = 0;\r\n\r\n\t\t//\t\tm_stage = parameters[c++].GetInt() + 1;\r\n\t\t\t//\tm_T = parameters[c++].GetInt()+1;\r\n\r\n\t\t//m_bCumul = parameters[c++].GetBool();\r\n\t\tif (parameters.size() == m_EWD.size() + m_EAS.size() + 1)\r\n\t\t{\r\n\t\t\t//entering winter diapause  parameters\r\n\t\t\tfor (size_t p = 0; p < m_EWD.size(); p++)\r\n\t\t\t{\r\n\t\t\t\tm_EWD[p] = parameters[c++].GetFloat();\r\n\t\t\t}\r\n\r\n\t\t\t//Emerging Adult from Soil (spring) parameters\r\n\t\t\tfor (size_t p = 0; p < m_EAS.size(); p++)\r\n\t\t\t{\r\n\t\t\t\tm_EAS[p] = parameters[c++].GetFloat();\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\tERMsg CAprocerosLeucopodaModel::OnExecuteDaily()\r\n\t{\r\n\t\tERMsg msg;\r\n\r\n\t\t/*\tif (m_weather.GetNbYears() < 2)\r\n\t\t\t{\r\n\t\t\t\tmsg.ajoute(\"Laricobius nigrinus model need at least 2 years of data\");\r\n\t\t\t\treturn msg;\r\n\t\t\t}*/\r\n\r\n\t\tif (!m_weather.IsHourly())\r\n\t\t\tm_weather.ComputeHourlyVariables();\r\n\r\n\t\t//This is where the model is actually executed\r\n\t\tm_output.Init(m_weather.GetEntireTPeriod(CTM(CTM::DAILY)), NB_DAILY_OUTPUTS, 0);\r\n\r\n\t\t//we simulate 2 years at a time. \r\n\t\t//we also manager the possibility to have only one year\r\n\t\tfor (size_t y = 0; y < m_weather.size(); y++)\r\n\t\t{\r\n\t\t\t//one output by generation\r\n\t\t\tvector<CModelStatVector> outputs;\r\n\t\t\tExecuteDaily(m_weather[y].GetTRef().GetYear(), m_weather, outputs);\r\n\r\n\r\n\t\t\t//merge generations vector into one output vector (max of 5 generations)\r\n\t\t\tsize_t maxG = min(NB_GENERATIONS_MAX, outputs.size());\r\n\r\n\t\t\tCTPeriod p = m_weather[y].GetEntireTPeriod(CTM(CTM::DAILY));\r\n\t\t\tfor (CTRef TRef = p.Begin(); TRef <= p.End(); TRef++)\r\n\t\t\t{\r\n\t\t\t\tCStatistic diapause;\r\n\t\t\t\tfor (size_t g = 0, ss = 0; g < maxG; g++)\r\n\t\t\t\t{\r\n\t\t\t\t\tsize_t s_i = (g==0)?PUPA:EGG;\r\n\t\t\t\t\tfor (size_t s = s_i; s < NB_OUTPUT_ONE_G; s++, ss++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_output[TRef][ss] = outputs[g][TRef][s];\r\n\t\t\t\t\t\tdiapause += outputs[g][TRef][S_DIAPAUSE];\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\r\n\t\t\t\tm_output[TRef][O_IN_DIAPAUSE] = diapause[SUM];\r\n\t\t\t\tm_output[TRef][O_D_DAY_LENGTH] = m_weather.GetDayLength(TRef) / 3600.;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn msg;\r\n\t}\r\n\r\n\tvoid CAprocerosLeucopodaModel::ExecuteDaily(int year, const CWeatherYears& weather, vector<CModelStatVector>& output)\r\n\t{\r\n\t\t//Create stand\r\n\t\tCTZZStand stand(this);\r\n\t\tstand.m_bApplyAttrition = true;\r\n\t\tstand.m_generationSurvival = m_generationSurvival;\r\n\r\n\t\t\r\n\t\t//Set parameters to equation\r\n\r\n\t\tASSERT(stand.m_equations.m_EWD.size() == m_EWD.size());\r\n\t\tfor (size_t p = 0; p < m_EWD.size(); p++)\r\n\t\t\tstand.m_equations.m_EWD[p] = m_EWD[p];\r\n\r\n\t\tASSERT(stand.m_equations.m_EAS.size() == m_EAS.size());\r\n\t\tfor (size_t p = 0; p < m_EAS.size(); p++)\r\n\t\t\tstand.m_equations.m_EAS[p] = m_EAS[p];\r\n\r\n\r\n\t\tstand.init(year, weather);\r\n\r\n\t\t//compute 30 days avg\r\n\t\t//stand.ComputeTavg30(year, weather);\r\n\r\n\r\n\t\t//Create host\r\n\t\tCTZZHostPtr pHost(new CTZZHost(&stand));\r\n\r\n\t\tpHost->m_nbMinObjects = 10;\r\n\t\tpHost->m_nbMaxObjects = 1000;\r\n\r\n\r\n\t\tpHost->Initialize<CAprocerosLeucopoda>(CInitialPopulation(CTRef(year, JANUARY, DAY_01), 0, 400, 100, TZZ::PUPA, WBSF::FEMALE, true, 0));\r\n\r\n\t\t//add host to stand\t\t\t\r\n\t\tstand.m_host.push_front(pHost);\r\n\r\n\t\tCTPeriod p = weather[year].GetEntireTPeriod(CTM(CTM::DAILY));\r\n\t\t\r\n\r\n\r\n\t\tfor (CTRef d = p.Begin(); d <= p.End(); d++)\r\n\t\t{\r\n\r\n\t\t\tstand.Live(weather.GetDay(d));\r\n\t\t\t//if (output.IsInside(d))\r\n\t\t\t\t//stand.GetStat(d, output[d]);\r\n\r\n\t\t\tsize_t nbGenerations = stand.GetFirstHost()->GetNbGeneration();\r\n\t\t\tif (nbGenerations > output.size())\r\n\t\t\t\toutput.push_back(CModelStatVector(p, NB_STATS, 0));\r\n\r\n\t\t\tfor (size_t g = 0; g < nbGenerations; g++)\r\n\t\t\t\tstand.GetStat(d, output[g][d], g);\r\n\r\n\r\n\r\n\t\t\tstand.AdjustPopulation();\r\n\t\t\tHxGridTestConnection();\r\n\t\t}\r\n\r\n\r\n\r\n\r\n\t\t//if (m_bCumul)\r\n\t\t//{\r\n\t\t//\tfor (size_t g = 0; g < output.size(); g++)\r\n\t\t//\t{\r\n\t\t//\t\t//cumulative result\r\n\t\t//\t\tfor (size_t s = S_EGG; s < S_ADULT; s++)\r\n\t\t//\t\t{\r\n\t\t//\t\t\tCTPeriod p = weather[year].GetEntireTPeriod(CTM(CTM::DAILY));\r\n\r\n\t\t//\t\t\tCStatistic stat = output[g].GetStat(s, p);\r\n\t\t//\t\t\tif (stat.IsInit() && stat[SUM] > 0)\r\n\t\t//\t\t\t{\r\n\t\t//\t\t\t\toutput[g][0][s] = output[g][0][s] * 100 / stat[SUM];//when first day is not 0\r\n\t\t//\t\t\t\tfor (CTRef d = p.Begin() + 1; d <= p.End(); d++)\r\n\t\t//\t\t\t\t{\r\n\t\t//\t\t\t\t\toutput[g][d][s] = output[g][d - 1][s] + output[g][d][s] * 100 / stat[SUM];\r\n\t\t//\t\t\t\t\t_ASSERTE(!_isnan(output[g][d][s]));\r\n\t\t//\t\t\t\t}\r\n\t\t//\t\t\t}\r\n\t\t//\t\t}\r\n\t\t//\t}\r\n\t\t//}\r\n\t}\r\n\r\n\t\r\n\r\n\t//void CAprocerosLeucopodaModel::GetCDD(int year, const CWeatherYears& weather, CModelStatVector& CDD)\r\n\t//{\r\n\t//\tCDegreeDays DDmodel(DD_METHOD, m_P[Τᴴ¹], m_P[Τᴴ²]);\r\n\t//\tCModelStatVector DD;\r\n\t//\tDDmodel.Execute(weather[year], DD);\r\n\r\n\r\n\r\n\t//\tCDD.Init(DD.GetTPeriod(), 1, 0.0);\r\n\r\n\t//\t//for (CTRef TRef = DD.GetFirstTRef(); TRef <= DD.GetLastTRef(); TRef++)\r\n\t//\tCDD[0][0] = DD[0][CDegreeDays::S_DD];\r\n\t//\tfor (size_t i = 1; i < DD.size(); i++)\r\n\t//\t\tCDD[i][0] = CDD[i - 1][0] + DD[i][CDegreeDays::S_DD];\r\n\t//}\r\n\r\n\tvoid CAprocerosLeucopodaModel::GetCDD(const CWeatherYears& weather, CModelStatVector& CDD)\r\n\t{\r\n\t\t//CTZZStand* pStand = GetStand();\r\n\t\tCDegreeDays DDmodel(DD_METHOD, m_EAS[Τᴴ¹], m_EAS[Τᴴ²]);\r\n\t\tCModelStatVector DD;\r\n\t\tDDmodel.Execute(weather, DD);\r\n\r\n\r\n\t\tCDD.Init(DD.GetTPeriod(), 1, -999);\r\n\r\n\t\tfor (size_t y = 0; y < weather.GetNbYears(); y++)\r\n\t\t{\r\n\t\t\tCTPeriod p = weather[y].GetEntireTPeriod();\r\n\t\t\t//p.Begin() = p.Begin() + int(m_P[delta]);\r\n\t\t\tCDD[p.Begin()][0] = DD[p.Begin()][CDegreeDays::S_DD];\r\n\r\n\t\t\tfor (CTRef TRef = p.Begin() + 1; TRef <= p.End(); TRef++)\r\n\t\t\t\tCDD[TRef][0] = CDD[TRef - 1][0] + DD[TRef][CDegreeDays::S_DD];\r\n\t\t}\r\n\r\n\t}\r\n\r\n\t//enum TSpecies { S_LA_G1, S_LA_G2, S_LP, S_LN };\r\n\tenum TInput { I_KEYID, I_DATE, I_STAGE, I_GENERATION, I_N, I_CUMUL, NB_INPUTS };\r\n\tvoid CAprocerosLeucopodaModel::AddDailyResult(const StringVector& header, const StringVector& data)\r\n\t{\r\n\t\t//KeyID\tDate\tStage\tGeneration\tN\tCumul\r\n\t\tASSERT(data.size() == NB_INPUTS);\r\n\t\t//SYC\tsite\tYear\tcollection\tcol_date\temerge_date\tdaily_count\tspecies\tn_days P Time\r\n\t\t//if (stoi(data[I_VARIABLE]) == m_stage && stoi(data[I_T]) == m_T)\r\n\t\t//{\r\n\t\tCSAResult obs;\r\n\t\tobs.m_ref.FromFormatedString(data[I_DATE]);\r\n\t\tobs.m_obs.resize(NB_INPUTS);\r\n\t\tfor (size_t i = 2; i < NB_INPUTS; i++)\r\n\t\t{\r\n\t\t\tif (i == I_STAGE)\r\n\t\t\t\tobs.m_obs[i] = 0;\r\n\t\t\telse\r\n\t\t\t\tobs.m_obs[i] = stod(data[i]);\r\n\t\t}\r\n\t\t\t\r\n\t\t//CSAResult obs;\r\n\r\n\t\t//CStatistic egg_creation_date;\r\n\r\n\t\t\r\n\t\t//obs.m_obs.resize(3);\r\n\t\t//obs.m_obs[0] = 0;\r\n\t\t//obs.m_obs[1] = stod(data[I_GENERATION]);\r\n\t\t//obs.m_obs[2] = stod(data[I_CUMUL]);\r\n\t\t////obs.m_obs[I_S] = ;\r\n\t\t////obs.m_obs[I_P] = stod(data[10]);\r\n\t\t////obs.m_obs[I_CDD] = stod(data[11]);\r\n\t\t////obs.m_obs[I_P] = stod(data[12]);\r\n\r\n\r\n\t\t//if (data[7] == \"LA\" && data[8] == \"1\")\r\n\t\t//\tobs.m_obs[I_S] = S_LA_G1;\r\n\t\t//else if (data[7] == \"LA\" && data[8] == \"2\")\r\n\t\t//\tobs.m_obs[I_S] = S_LA_G2;\r\n\t\t//else if (data[7] == \"LP\")\r\n\t\t//\tobs.m_obs[I_S] = S_LP;\r\n\t\t//else if (data[7] == \"LN\")\r\n\t\t//\tobs.m_obs[I_S] = S_LN;\r\n\r\n\t\tm_SAResult.push_back(obs);\r\n\t}\r\n\r\n\t//ASSERT(data.size() == NB_INPUTS);\r\n\t////SYC\tsite\tYear\tcollection\tcol_date\temerge_date\tdaily_count\tspecies\tn_days P Time\r\n\t//if (stoi(data[I_VARIABLE]) == m_stage && stoi(data[I_T]) == m_T)\r\n\t//{\r\n\t//\tCSAResult obs;\r\n\t//\tobs.m_obs.resize(NB_INPUTS);\r\n\t//\tfor (size_t i = 0; i < NB_INPUTS; i++)\r\n\t//\t\tobs.m_obs[i] = stod(data[i]);\r\n\t//\t//CSAResult obs;\r\n\r\n\t//\t//CStatistic egg_creation_date;\r\n\r\n\t//\t//obs.m_ref.FromFormatedString(data[5]);\r\n\t//\t//obs.m_obs.resize(NB_INPUTS);\r\n\t//\t//obs.m_obs[I_N] = stod(data[6]);\r\n\t//\t////obs.m_obs[I_S] = ;\r\n\t//\t////obs.m_obs[I_P] = stod(data[10]);\r\n\t//\t////obs.m_obs[I_CDD] = stod(data[11]);\r\n\t//\t////obs.m_obs[I_P] = stod(data[12]);\r\n\r\n\r\n\t//\t//if (data[7] == \"LA\" && data[8] == \"1\")\r\n\t//\t//\tobs.m_obs[I_S] = S_LA_G1;\r\n\t//\t//else if (data[7] == \"LA\" && data[8] == \"2\")\r\n\t//\t//\tobs.m_obs[I_S] = S_LA_G2;\r\n\t//\t//else if (data[7] == \"LP\")\r\n\t//\t//\tobs.m_obs[I_S] = S_LP;\r\n\t//\t//else if (data[7] == \"LN\")\r\n\t//\t//\tobs.m_obs[I_S] = S_LN;\r\n\r\n\t//\tm_SAResult.push_back(obs);\r\n\t//}\r\n//\t}\r\n\r\n\r\n\r\n\t//double GetSimX(size_t s, CTRef TRefO, double obs, const CModelStatVector& output)\r\n\t//{\r\n\t//\tdouble x = -999;\r\n\r\n\t//\tif (obs > -999)\r\n\t//\t{\r\n\t//\t\t//if (obs > 0.01 && obs < 99.99)\r\n\t//\t\tif (obs >= 100)\r\n\t//\t\t\tobs = 99.99;//to avoid some problem of truncation\r\n\r\n\t//\t\tlong index = output.GetFirstIndex(s, \">=\", obs, 1, CTPeriod(TRefO.GetYear(), FIRST_MONTH, FIRST_DAY, TRefO.GetYear(), LAST_MONTH, LAST_DAY));\r\n\t//\t\tif (index >= 1)\r\n\t//\t\t{\r\n\t//\t\t\tdouble obsX1 = output.GetFirstTRef().GetJDay() + index;\r\n\t//\t\t\tdouble obsX2 = output.GetFirstTRef().GetJDay() + index + 1;\r\n\r\n\t//\t\t\tdouble obsY1 = output[index][s];\r\n\t//\t\t\tdouble obsY2 = output[index + 1][s];\r\n\t//\t\t\tif (obsY2 != obsY1)\r\n\t//\t\t\t{\r\n\t//\t\t\t\tdouble slope = (obsX2 - obsX1) / (obsY2 - obsY1);\r\n\t//\t\t\t\tdouble obsX = obsX1 + (obs - obsY1)*slope;\r\n\t//\t\t\t\tASSERT(!_isnan(obsX) && _finite(obsX));\r\n\r\n\t//\t\t\t\tx = obsX;\r\n\t//\t\t\t}\r\n\t//\t\t}\r\n\t//\t}\r\n\r\n\t//\treturn x;\r\n\t//}\r\n\r\n\tbool CAprocerosLeucopodaModel::IsParamValid()const\r\n\t{\r\n\t\tbool bValid = true;\r\n\r\n\t\treturn bValid;\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\t//static const int ROUND_VAL = 4;\r\n\t//CTRef CAprocerosLeucopodaModel::GetEmergence(const CWeatherYear& weather)\r\n\t//{\r\n\t//\tCTPeriod p = weather.GetEntireTPeriod(CTM(CTM::DAILY));\r\n\r\n\t//\tdouble sumDD = 0;\r\n\t//\tfor (CTRef TRef = p.Begin()+172; TRef <= p.End()&& TRef<= p.Begin() + int(m_ADE[ʎ0]); TRef++)\r\n\t//\t{\r\n\t//\t\t//size_t ii = TRef - p.Begin();\r\n\t//\t\tconst CWeatherDay& wday = m_weather.GetDay(TRef);\r\n\t//\t\tdouble T = wday[H_TNTX][MEAN];\r\n\t//\t\tT = Round(max(m_ADE[ʎa], T), ROUND_VAL);\r\n\r\n\t//\t\tdouble DD = min(0.0, T - m_ADE[ʎb]);//DD is negative\r\n\r\n\t//\t\t//if (ii < m_ADE[ʎ0])\r\n\t//\t\t\tsumDD += DD;\r\n\t//\t}\r\n\r\n\r\n\t//\tboost::math::logistic_distribution<double> begin_dist(m_ADE[ʎ2], m_ADE[ʎ3]);\r\n\t//\tint begin = (int)Round(m_ADE[ʎ0] + m_ADE[ʎ1] * cdf(begin_dist, sumDD), 0);\r\n\t//\treturn  p.Begin() + begin;\r\n\t//}\r\n\t//enum TPout {P_CDD, P_CE, LA_G1= P_CE, P_LA_G2, P_LP, P_LN, NB_P};//CE = cumulative emergence\r\n\t//void CAprocerosLeucopodaModel::GetPobs(CModelStatVector& P)\r\n\t//{\r\n\t//\tstring ID = GetInfo().m_loc.m_ID;\r\n\t//\tstring SY = ID.substr(0, ID.length() - 2);\r\n\r\n\t//\t//compute CDD for all temperature rprofile\r\n\t//\tarray< double, 4> total = { 0 };\r\n\t//\tvector<tuple<double, CTRef, double, bool, size_t>> d;\r\n\t//\tconst CSimulatedAnnealingVector& SA = GetSimulatedAnnealingVector();\r\n\r\n\t//\tfor (size_t i = 0; i < SA.size(); i++)\r\n\t//\t{\r\n\t//\t\tstring IDi = SA[i]->GetInfo().m_loc.m_ID;\r\n\t//\t\tstring SYi = IDi.substr(0, IDi.length() - 2);\r\n\t//\t\tif (SYi == SY)\r\n\t//\t\t{\r\n\t//\t\t\tCModelStatVector CDD;\r\n\t//\t\t\tGetCDD(SA[i]->m_weather, CDD);\r\n\t//\t\t\tconst CSAResultVector& v = SA[i]->GetSAResult();\r\n\t//\t\t\tfor (size_t ii = 0; ii < v.size(); ii++)\r\n\t//\t\t\t{\r\n\t//\t\t\t\td.push_back(make_tuple(CDD[v[ii].m_ref][0], v[ii].m_ref, v[ii].m_obs[I_N], IDi == ID, v[ii].m_obs[I_S]));\r\n\t//\t\t\t\ttotal[v[ii].m_obs[I_S]] += v[ii].m_obs[I_N];\r\n\t//\t\t\t}\r\n\t//\t\t}\r\n\t//\t}\r\n\r\n\t//\tsort(d.begin(), d.end());\r\n\r\n\t//\tP.Init(m_weather.GetEntireTPeriod(CTM::DAILY), NB_P, 0);\r\n\t//\tarray< double, 4> sum = { 0 };\r\n\t//\tfor (size_t i = 0; i < d.size(); i++)\r\n\t//\t{\r\n\t//\t\tsize_t s = std::get<4>(d[i]);\r\n\t//\t\tsum[s] += std::get<2>(d[i]);\r\n\t//\t\tif (std::get<3>(d[i]))\r\n\t//\t\t{\r\n\t//\t\t\tCTRef Tref = std::get<1>(d[i]);\r\n\t//\t\t\t/*double obsP = -999;\r\n\t//\t\t\tfor (size_t k = 0; k < m_SAResult.size(); k++)\r\n\t//\t\t\t\tif (m_SAResult[k].m_ref == Tref)\r\n\t//\t\t\t\t\tobsP = m_SAResult[k].m_obs[I_P];*/\r\n\r\n\r\n\t//\t\t\tdouble CDD = std::get<0>(d[i]);\r\n\t//\t\t\tdouble p = Round(100 * sum[s] / total[s], 1);\r\n\t//\t\t\t\r\n\t//\t\t\tP[Tref][P_CDD] = CDD;\r\n\t//\t\t\tP[Tref][P_CE + s] = p;\r\n\t//\t\t}\r\n\t//\t}\r\n\t//}\r\n\r\n\t//void CAprocerosLeucopodaModel::CalibrateEmergence(CStatisticXY& stat)\r\n\t//{\r\n\t//\tif (m_SAResult.empty())\r\n\t//\t\treturn;\r\n\r\n\t//\t//boost::math::lognormal_distribution<double> emerge_dist(m_P[μ], m_P[ѕ]);\r\n\r\n\r\n\r\n\t//\t//boost::math::weibull_distribution<double> emerge_dist(m_P[μ], m_P[ѕ]);\r\n\t//\t//boost::math::beta_distribution<double> emerge_dist(m_P[μ], m_P[ѕ]);\r\n\t//\t//boost::math::exponential_distribution<double> emerge_dist(m_P[ѕ]);\r\n\t//\t//boost::math::rayleigh_distribution<double> emerge_dist(m_P[ѕ]);\r\n\r\n\r\n\t//\t//CModelStatVector CDD; \r\n\t//\t//GetCDD(m_weather, CDD);\r\n\r\n\t//\tdouble n = 0;\r\n\r\n\t//\tfor (size_t i = 0; i < m_SAResult.size(); i++)\r\n\t//\t\tn += m_SAResult[i].m_obs[I_N];\r\n\r\n\r\n\t//\tCModelStatVector P;\r\n\t//\tGetPobs(P);\r\n\r\n\t//\t//array<boost::math::logistic_distribution<double>,4> emerge_dist(mu, S);\r\n\t//\t//\t\tarray<boost::math::logistic_distribution<double>, 4> emerge_dist = { {m_P[μ1], m_P[ѕ1], m_P[μ1], m_P[ѕ1]} };\r\n\r\n\t//\tfor (size_t i = 0; i < m_SAResult.size(); i++)\r\n\t//\t{\r\n\t//\t\tsize_t s = m_SAResult[i].m_obs[I_S];\r\n\t//\t\tdouble mu = m_P[μ1 + 2 * s];\r\n\t//\t\tdouble S = m_P[ѕ1 + 2 * s];\r\n\r\n\t//\t\tboost::math::logistic_distribution<double> emerge_dist(mu, S);\r\n\r\n\t//\t\tdouble CDD = P[m_SAResult[i].m_ref][P_CDD];\r\n\t//\t\tdouble obs = P[m_SAResult[i].m_ref][P_CE+s];\r\n\t//\t\tASSERT(obs >= 0 && obs <= 100);\r\n\r\n\t//\t\tdouble sim = Round(100 * cdf(emerge_dist, max(0.0, CDD)), 1);\r\n\t//\t\tfor (size_t ii = 0; ii < log(n); ii++)\r\n\t//\t\t\tstat.Add(obs, sim);\r\n\r\n\t//\t}//for all results\r\n\r\n\t//\treturn;\r\n\r\n\t//}\r\n\r\n\t//static double ei(size_t n) { return pow(1.0 + 1.0 / n, n); }\r\n\t//static double cv_2_sigma(double cv, size_t n)\r\n\t//{\r\n\t//\tstatic const double e = exp(1);\r\n\t//\tstatic const double p[3] = { 0.528196, 2.373248, 3.493202 };//with 10 000 replication\r\n\t//\treturn e * cv*(1 - p[0] * sqrt(e - ei(n))) / (p[1] + cv * (1 - p[2] * sqrt(e - ei(n))));\r\n\t//}\r\n\r\n\tvoid CAprocerosLeucopodaModel::GetFValueDaily(CStatisticXY& stat)\r\n\t{\r\n\t\t\r\n\t\tASSERT(!m_SAResult.empty() );\r\n\t\t\r\n\t\t//CTZZStand* pStand = GetStand();\r\n\t\t//for (size_t p = 0; p < m_EAS.size(); p++)\r\n\t\t\t//pStand->m_equations.m_EAS[p] = m_EAS[p];\r\n\r\n\t\tif (!IsParamValid())\r\n\t\t\treturn;\r\n\r\n\r\n\t\t//boost::math::lognormal_distribution<double> emerge_dist(m_P[μ], m_P[ѕ]);\r\n\r\n\r\n\r\n\t\t//boost::math::weibull_distribution<double> emerge_dist(m_P[μ], m_P[ѕ]);\r\n\t\t//boost::math::beta_distribution<double> emerge_dist(m_P[μ], m_P[ѕ]);\r\n\t\t//boost::math::exponential_distribution<double> emerge_dist(m_P[ѕ]);\r\n\t\t//boost::math::rayleigh_distribution<double> emerge_dist(m_P[ѕ]);\r\n\r\n\r\n\t\t//CModelStatVector CDD; \r\n\t\t//GetCDD(m_weather, CDD);\r\n\r\n\t\tdouble n = 0;\r\n\r\n\t\tfor (size_t i = 0; i < m_SAResult.size(); i++)\r\n\t\t\tn += m_SAResult[i].m_obs[I_N];\r\n\r\n\r\n\t\tCModelStatVector CDD;\r\n\t\tGetCDD(m_weather, CDD);\r\n\t\t//GetPobs(P);\r\n\r\n\t\t\r\n\t\tboost::math::logistic_distribution<double> emerge_dist(m_EAS[μ], m_EAS[ѕ]);\r\n\t\t\r\n\r\n\t\tfor (size_t i = 0; i < m_SAResult.size(); i++)\r\n\t\t{\r\n\t\t\tsize_t s = m_SAResult[i].m_obs[I_STAGE];\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tdouble GDD = CDD[m_SAResult[i].m_ref][CDegreeDays::S_DD];\r\n\t\t\tdouble obs = m_SAResult[i].m_obs[I_CUMUL];\r\n\t\t\t//ASSERT(obs >= 0 && obs <= 100);\r\n\r\n\t\t\tdouble sim = Round(100 * cdf(emerge_dist, max(0.0, GDD)), 1);\r\n\t\t\t//for (size_t ii = 0; ii < log(n); ii++)\r\n\t\t\tstat.Add(obs, sim);\r\n\r\n\t\t}//for all results\r\n\r\n\t\treturn;\r\n\r\n\r\n\t\t//bool bZero = false;\r\n\t\t//CStatistic x;\r\n\t\t//for (size_t i = 0; i < m_SAResult.size(); i++)\r\n\t\t//{\r\n\t\t//\t//ASSERT(m_SAResult[i].m_obs[I_VARIABLE] == m_stage);\r\n\t\t//\t//ASSERT(m_SAResult[i].m_obs[I_T] == m_T);\r\n\r\n\t\t//\tsize_t n = size_t(ceil(m_P[i]));\r\n\t\t//\tbZero |= n == 0;\r\n\r\n\t\t//\tfor (size_t b = 0; b < n; b++)\r\n\t\t//\t\tx += m_SAResult[i].m_obs[I_TIME];\r\n\r\n\t\t//}//for all results\r\n\r\n\t\t////if (!bZero  && int(x[NB_VALUE]) == int(m_SAResult[0].m_obs[I_N]) )\r\n\t\t//{\r\n\t\t//\tdouble obs = m_SAResult[0].m_obs[I_MEAN_TIME];\r\n\t\t//\tdouble sim = x[MEAN];\r\n\t\t//\tstat.Add(obs, sim);\r\n\r\n\t\t//\tobs = m_SAResult[0].m_obs[I_TIME_SD] * 10;\r\n\t\t//\tsim = x[STD_DEV] * 10;\r\n\t\t//\tstat.Add(obs, sim);\r\n\r\n\t\t//\tobs = size_t(m_SAResult[0].m_obs[I_N]);\r\n\t\t//\tsim = size_t(x[NB_VALUE]);\r\n\t\t//\tstat.Add(obs, sim);\r\n\r\n\r\n\r\n\t\t//\tCStatistic stat_ws;\r\n\t\t//\tCStatistic stat_n;\r\n\r\n\r\n\t\t//\t//compute sigma\r\n\r\n\t\t//\tdouble mean = x[MEAN];\r\n\t\t//\tdouble sd = x[STD_DEV];\r\n\t\t//\tdouble n = x[NB_VALUE];\r\n\t\t//\tif (n > 0)\r\n\t\t//\t{\r\n\t\t//\t\tdouble cv = sd / mean;\r\n\t\t//\t\tdouble sigma = cv_2_sigma(cv, n);\r\n\r\n\t\t//\t\tstat_ws += n * sigma;\r\n\t\t//\t\tstat_n += n;\r\n\t\t//\t}\r\n\r\n\t\t//\tstatic const double SIGMA_OBS[4] = { 0.102, 0.157, 0.203, 0.118 };\r\n\r\n\r\n\t\t//\tobs = SIGMA_OBS[m_stage];\r\n\t\t//\tsim = stat_ws[SUM] / stat_n[SUM];\r\n\r\n\t\t//}\r\n\r\n\t}\r\n\r\n\r\n\r\n\t//void CAprocerosLeucopodaModel::FinalizeStat(CStatisticXY& stat)\r\n\t//{\r\n\t//\t\r\n\t//}\r\n}\r\n\r\n\r\n\r\n", "meta": {"hexsha": "afcb002941a4cb4244a949368c9e9bfe3ab8a1f0", "size": 18865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wbsModels/AprocerosLeucopoda/ALeucopodaModel.cpp", "max_stars_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_stars_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-05-26T21:19:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T14:17:29.000Z", "max_issues_repo_path": "wbsModels/AprocerosLeucopoda/ALeucopodaModel.cpp", "max_issues_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_issues_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-02-18T12:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-13T12:57:45.000Z", "max_forks_repo_path": "wbsModels/AprocerosLeucopoda/ALeucopodaModel.cpp", "max_forks_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_forks_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-16T02:49:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-16T02:49:20.000Z", "avg_line_length": 27.5401459854, "max_line_length": 211, "alphanum_fraction": 0.5865359131, "num_tokens": 6877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.40468770585086006}}
{"text": "//State Vector- variable acceleration model\n\t// X(0) = quad_position.point.x;\n    // X(1) = m_velocity.point.x;\n    // X(2) = m_acc_bias.point.x;\n    // X(3) = quad_position.point.y;\n    // X(4) = m_velocity.point.y;\n    // X(5) = m_acc_bias.point.y;\n    // X(6) = quad_position.point.z;\n    // X(7) = m_velocity.point.z;\n    // X(8) = m_acc_bias.point.z;\n\t// X(9)  = leader.point.x;\n    // X(10) = leader.point.y;\n    // X(11) = leader.point.z;\n\t// X(12) = leader.point.x;\n\t// X(13) = leader.point.y;\n\t// X(14) = leader.point.z;\n//Input Vector\n\t// U(0) = quad.imu.acc.x\n\t// U(1) = 0\n\t// U(2) = 0\n\t// U(3) = quad.imu.acc.y\n\t// U(4) = 0\n\t// U(5) = 0\n\t// U(6) = quad.imu.acc.z\n\t// U(7) = 0\n\t// U(8) = 0\n\t// U(9)  = leader_quad.point.x\n\t// U(10) = leader_quad.point.y\n\t// U(11) = leader_quad.point.z\n\t// U(12) = neighbor_quad.point.x\n\t// U(13) = neighbor_quad.point.y\n\t// U(14) = neighbor_quad.point.z\n\n#include <Eigen/Dense>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <bits/stdc++.h>\n#include <ros/ros.h>\n#include <math.h>\n#include <stdio.h>\n#include <dwm1001/anchor.h> \n#include <sensor_msgs/Imu.h>\n#include \"std_msgs/MultiArrayLayout.h\"\n#include \"std_msgs/MultiArrayDimension.h\"\n#include \"std_msgs/Float32MultiArray.h\"\n#include \"geometry_msgs/PoseStamped.h\"\n#include \"geometry_msgs/Vector3Stamped.h\"\n\n// Declarations\nint count =0 ;\ndouble r_pred_l,r_meas_l;\nEigen::MatrixXd H_l(1,15);\ndouble R_l;\ndouble m_R_scale_l,sigma_r_l;\nEigen::VectorXd K_l(15);\nEigen::VectorXd X_p_l(15);\nEigen::MatrixXd P_p_l(15,15);\ndouble error_l;\ndouble precisionRangeErrEst_l;\n//\ndouble r_pred_n,r_meas_n;\nEigen::MatrixXd H_n(1,15);\ndouble R_n;\ndouble m_R_scale_n,sigma_r_n;\nEigen::VectorXd K_n(15);\nEigen::VectorXd X_p_n(15);\nEigen::MatrixXd P_p_n(15,15);\ndouble error_n;\ndouble precisionRangeErrEst_n;\n//\ngeometry_msgs::Vector3Stamped pose;\ngeometry_msgs::Vector3Stamped vel;\ngeometry_msgs::Vector3Stamped acc_;\nfloat ax,ay,az; \nEigen::Quaternionf q;\nEigen::MatrixXf R_mat(3,3);\nEigen::MatrixXf imuacc(3,1);\nEigen::MatrixXf acc(3,1);\n//\nEigen::VectorXd X(15);\nEigen::VectorXd X_e(15);\nEigen::MatrixXd F(15,15);\nEigen::MatrixXd block_F(3,3);\nEigen::MatrixXd Q(15,15);\nEigen::VectorXd u(15);\nEigen::MatrixXd B(15,15);\nEigen::MatrixXd P(15,15);\nEigen::MatrixXd M(15,15);\nEigen::MatrixXd block_B(3,3);\nEigen::MatrixXd block_Q(3,3);\nEigen::MatrixXd B_I(6,6);\nEigen::MatrixXd Q_lead(3,3);\nEigen::MatrixXd Q_neigh(3,3);\ndouble tao_acc;\ndouble tao_bias;\ndouble sigma_a,r_meas;\ndouble T;\ndouble m_last_range_time;\nstd_msgs::Float32MultiArray output;\ndouble error_threshold,precisionRangeMm;\ndouble m_kalman_sigma_a,T_sq,m_tao_acc_sqrt,m_tao_bias_sqrt,T_cub,m_z_damping_factor,m_Q_scale;\ndouble m_snr_threshold,error;\ndouble x,y,z,x_l,y_l,z_l,x_n,y_n,z_n;\ndouble q_l,q_n;\n\n\n\nvoid setState(Eigen::VectorXd Y)\n{\n    X = Y;\n}\nvoid setCovariance(Eigen::MatrixXd S)\n{\n    P = S;\n}\n\nvoid convert_NED(sensor_msgs::Imu imu)\n{\n\t//conerts the acceleration from body frame to earth frame(NED) \n    q = Eigen::Quaternionf(imu.orientation.w, imu.orientation.x, imu.orientation.y, imu.orientation.z);\n    R_mat= q.toRotationMatrix();\n    \n    ax=imu.linear_acceleration.x;\n    ay=imu.linear_acceleration.y;\n    az=imu.linear_acceleration.z;\n    imuacc << ax,ay,az;\n    acc= R_mat*imuacc;\n\n}\n\n\nvoid prediction_step(const sensor_msgs::Imu::ConstPtr& msg)\n{\n\tconvert_NED(*msg);\t\n  \tax=acc(0,0);\n  \tay=-acc(1,0);\n  \taz=-1*(acc(2,0)-9.8);\n\n    //ROS_WARN(\"Acceleration:## %f, ## %f, ## %f\", ax,ay,az);\n    T = msg->header.stamp.toSec() - m_last_range_time;\n    if(T>1){\n        T = 1;\n    } else if(T<0){\n        T = 0.01;\n    }\n    \n    sigma_a = m_kalman_sigma_a;\n   // r_meas = double(precisionRangeMm) / 1000.0;\n    \n    T_sq = std::pow(T,2);\n    T_cub = std::pow(T,3);\n\n    // F is a 9x9 State Transition Matrix\n    F = Eigen::MatrixXd::Zero(15,15);\n\n    block_F << 1, T, -T_sq/2.0,\n               0, 1, -T,\n               0, 0, 1;\n    F.block<3,3>(0,0) = block_F;\n    F.block<3,3>(3,3) = block_F;\n    F.block<3,3>(6,6) = block_F;\n\n    u << ax, 0, 0,\n         ay, 0, 0,\n         az, 0, 0,\n         x_l,y_l,z_l,\n         x_n,y_n,z_n;\n    B = Eigen::MatrixXd::Zero(15,15);\n    B_I = Eigen::MatrixXd::Identity(6,6);\n    block_B << T_sq/2.0,  0,  0,\n               T      ,  0,  0,\n               0      ,  0,  0;\n    B.block<3,3>(0,0) = block_B;\n    B.block<3,3>(3,3) = block_B;\n    B.block<3,3>(6,6) = block_B;\n    B.block<6,6>(9,9) = B_I;\n\n    // X is the predicted state vector and the predicted covariance matrix\n    X_e = F*X + B * u;\n\n    // Q is the acceleration model\n    tao_acc = m_tao_acc_sqrt * m_tao_acc_sqrt;\n    tao_bias = m_tao_bias_sqrt * m_tao_bias_sqrt;\n    Q = Eigen::MatrixXd::Zero(15,15);\n    \n    block_Q << (T_cub*tao_acc/3.0)+(T_cub*T_sq)*tao_bias/20.0, (T_sq*tao_acc/2)+(T_sq*T_sq)*tao_bias/8.0  ,-T_cub*tao_bias/6,\n        \t   (T_sq*tao_acc/2.0)+(T_sq*T_sq)*tao_bias/8.0 ,   T*tao_acc+(T_cub*tao_bias/3) \t\t\t  ,-T_sq*tao_bias/2,\n         \t   -T_cub*tao_bias/6.0,\t\t\t\t\t\t    -T_sq*tao_bias/2 \t\t\t\t\t\t  ,T*tao_bias         ;\n\n    Q_lead <<  q_l,  0,  0,\n    \t\t\t0, q_l, 0,\n    \t\t\t0,  0,  q_l ;\n    Q_neigh << q_n,  0,  0,\n    \t\t\t0, q_n, 0,\n    \t\t\t0,  0,  q_n ;\n\n    Q.block<3,3>(0,0) = block_Q;\n    Q.block<3,3>(3,3) = block_Q;\n    Q.block<3,3>(6,6) = block_Q * m_z_damping_factor;\n    Q *= m_Q_scale;\n    Q.block<3,3>(9,9) = Q_lead;\n    Q.block<3,3>(12,12) = Q_neigh;\n    //ROS_WARN(\"covariance:## %f, ## %f, ## %f\",(T_cub*tao_acc/3.0)+(T_cub*T_sq)*tao_bias/20.0 , T*tao_acc+(T_cub*tao_bias/3), T*tao_bias);\n   \n    // if(count%250 == 0)\n    // std::cout << P << '\\n'<<'\\n';\n    // M is the predicted covariance matrix\n\tM = F*P*F.transpose() + Q;\n\n    // time update\n    m_last_range_time = msg->header.stamp.toSec();\n    //count++;\n    error = X.squaredNorm()-X_e.squaredNorm();\n    if(error < error_threshold){\n        //ROS_WARN(\"\\n sucess too large: %f\", error);\n        setState(X_e);\n        setCovariance(M);\n        return ;\n    } else {\n\n        ROS_WARN(\"\\n Estimate too large: %f\", error);\n        return ;\n    }\n\n}\n\n\nvoid correction_step_leader(const dwm1001::anchor::ConstPtr& msg)\n{\t\n\tr_pred_l = std::sqrt( std::pow(X(0) -  X(9), 2) +\n                          std::pow(X(3) - X(10), 2) +\n                          std::pow(X(6) - X(11), 2) ) + 1e-5;\n\n\tr_meas_l = msg->range;\n    // H is the linearized measurement matrix\n    H_l << (X(0) -  X(9))/r_pred_l, 0, 0,\n           (X(3) - X(10))/r_pred_l, 0, 0,\n           (X(6) - X(11))/r_pred_l, 0, 0,\n           (X(9) - X(0))/r_pred_l, (X(10) - X(3))/r_pred_l, (X(11) - X(6))/r_pred_l,\n         \t0,\t0,\t0;\n\n    // K is the Kalman Gain\n    sigma_r_l = double(precisionRangeErrEst_l) / 1000.0;\n    R_l = std::pow(sigma_r_l,2) * m_R_scale_l;\n    //ROS_WARN(\"R_matrix:## %f\",R);\n    K_l = P*H_l.transpose() / ( (H_l*P*H_l.transpose())(0,0) + R_l );\n    // Update P for the a posteriori covariance matrix\n    P_p_l = ( Eigen::MatrixXd::Identity(15,15) - K_l*H_l ) * P;\n    // Return the measurement innovation\n    error_l = std::fabs(r_meas_l - r_pred_l);\n    // Update the state\n    X_p_l = X + K_l * (r_meas_l - r_pred_l);\n    // decide to take the range info or not.\n    if(error_l < error_threshold){\n        //ROS_WARN(\"\\n sucess too large: %f\", error);\n        setState(X_p_l);\n        setCovariance(P_p_l);\n     \n        return ;\n    } else {\n\n        ROS_WARN(\"Anchor id , Update too large: %f --\", error_l);\n        std::cout << msg->device_id << \"\\n\";\n        return ;\n    }\n\n}\n\n\nvoid correction_step_neigh(const dwm1001::anchor::ConstPtr& msg)\n{\t\n\tr_pred_n = std::sqrt( std::pow(X(0) - X(12), 2) +\n                          std::pow(X(3) - X(13), 2) +\n                          std::pow(X(6) - X(14), 2) ) + 1e-5;\n\n\tr_meas_n = msg->range;\n    // H is the linearized measurement matrix\n    H_n << (X(0) - X(12))/r_pred_n, 0, 0,\n           (X(3) - X(13))/r_pred_n, 0, 0,\n           (X(6) - X(14))/r_pred_n, 0, 0,\n         \t0,\t0,\t0,\n           (X(12) - X(0))/r_pred_n, (X(13) - X(3))/r_pred_n, (X(14) - X(6))/r_pred_n ;\n\n    // K is the Kalman Gain\n    sigma_r_n = double(precisionRangeErrEst_n) / 1000.0;\n    R_n = std::pow(sigma_r_n,2) * m_R_scale_n;\n    //ROS_WARN(\"R_matrix:## %f\",R);\n    K_n = P*H_n.transpose() / ( (H_n*P*H_n.transpose())(0,0) + R_n );\n    // Update P for the a posteriori covariance matrix\n    P_p_n = ( Eigen::MatrixXd::Identity(15,15) - K_n*H_n ) * P;\n    // Return the measurement innovation\n    error_n = std::fabs(r_meas_n - r_pred_n);\n    // Update the state\n    X_p_n = X + K_n * (r_meas_n - r_pred_n);\n    // decide to take the range info or not.\n    if(error < error_threshold){\n        //ROS_WARN(\"\\n sucess too large: %f\", error);\n        setState(X_p_n);\n        setCovariance(P_p_n);\n     \n        return ;\n    } else {\n\n        ROS_WARN(\"Anchor id , Update too large: %f --\", error_n);\n        std::cout << msg->device_id << \"\\n\";\n        return ;\n    }\n\n}\n\n\n// void anchor_lead_cb(const dwm1001::anchor::ConstPtr& msg)\n// {\n// \tcorrection_step_leader(msg);\n// }\n\n// void anchor_neigh_cb(const dwm1001::anchor::ConstPtr& msg)\n// {\n// \tcorrection_step_neigh(msg);\n// }\n\nvoid position_lead_cb(const geometry_msgs::PoseStamped::ConstPtr& msg)\n{\n\tx_l =  msg->pose.position.x;\n    y_l =  msg->pose.position.y;\n    z_l =  msg->pose.position.z;\n}\n\nvoid position_neigh_cb(const geometry_msgs::PoseStamped::ConstPtr& msg)\n{\n\tx_n =  msg->pose.position.x;\n    y_n =  msg->pose.position.y;\n    z_n =  msg->pose.position.z;\n}\n\nvoid param(ros::NodeHandle& nh)\n{\n    nh.getParam(\"KalmanFilter_swarm/start_x\", x);\n    nh.getParam(\"KalmanFilter_swarm/start_y\", y);\n    nh.getParam(\"KalmanFilter_swarm/start_z\", z);\n    nh.getParam(\"KalmanFilter_swarm/lead_x\", x_l);\n    nh.getParam(\"KalmanFilter_swarm/lead_y\", y_l);\n    nh.getParam(\"KalmanFilter_swarm/lead_z\", z_l);\n    nh.getParam(\"KalmanFilter_swarm/neighbor_x\", x_n);\n    nh.getParam(\"KalmanFilter_swarm/neighbor_y\", y_n);\n    nh.getParam(\"KalmanFilter_swarm/neighbor_z\", z_n);\n    nh.getParam(\"KalmanFilter_swarm/error_threshold\", error_threshold);\n    nh.getParam(\"KalmanFilter_swarm/m_R_scale_leader\", m_R_scale_l);\n    nh.getParam(\"KalmanFilter_swarm/precisionRangeErrEst_leader\", precisionRangeErrEst_l);\n    nh.getParam(\"KalmanFilter_swarm/m_R_scale_neighbor\", m_R_scale_n);\n    nh.getParam(\"KalmanFilter_swarm/precisionRangeErrEst_neighbor\", precisionRangeErrEst_n);\n    nh.getParam(\"KalmanFilter_swarm/m_kalman_sigma_a\", m_kalman_sigma_a);\n    nh.getParam(\"KalmanFilter_swarm/precisionRangeMm\", precisionRangeMm);\n    nh.getParam(\"KalmanFilter_swarm/leader_covariance\", q_l);\n    nh.getParam(\"KalmanFilter_swarm/neighbor_covariance\", q_n);\n    nh.getParam(\"KalmanFilter_swarm/m_tao_acc_sqrt\", m_tao_acc_sqrt);\n    nh.getParam(\"KalmanFilter_swarm/m_tao_bias_sqrt\", m_tao_bias_sqrt );\n    nh.getParam(\"KalmanFilter_swarm/m_z_damping_factor\", m_z_damping_factor);\n    nh.getParam(\"KalmanFilter_swarm/m_Q_scale\", m_Q_scale);\n}\n\n\nvoid Initialize(ros::NodeHandle& nh)\n{\n \n    param(nh);\n    // ROS_WARN(\"m_Q_scale %f\", m_Q_scale);\n    // ROS_WARN(\"x %f\", x);\n\n    m_kalman_sigma_a = 0.125;\n    m_snr_threshold = -100; \n \n    Eigen::MatrixXd nine_cov = Eigen::MatrixXd::Identity(15,15);\n    nine_cov(0,0) = 0.001;\n    nine_cov(3,3) = 0.001;\n    nine_cov(6,6) = 0.001;\n    // set cov of vel\n    nine_cov(1,1) = 0.01;\n    nine_cov(4,4) = 0.01;\n    nine_cov(7,7) = 0.01;\n    // set cov of acc_bias\n    nine_cov(2,2) = 0.01;\n    nine_cov(5,5) = 0.01;\n    nine_cov(8,8) = 0.01;\n\n    nine_cov(9,9)   = 0.001;\n    nine_cov(10,10) = 0.001;\n    nine_cov(11,11) = 0.001;\n\n    nine_cov(12,12) = 0.001;\n    nine_cov(13,13) = 0.001;\n    nine_cov(14,14) = 0.001;\n\n    setCovariance(nine_cov);\n    X<<x,0,0,y,0,0,z,0,0,x_l,y_l,z_l,x_n,y_n,z_n;\n    m_last_range_time = ros::Time::now().toSec();\n\n}\n\n\nint main(int argc, char** argv){\n\n    ros::init(argc,argv,\"KalmanFilter_swarm\");\n    ros::NodeHandle nh;     \n    //Initializinging the parameters\n    Initialize(nh);\n  \n    //Subscriber and Publisher for the data. remapped in the launch file to the topic required\n    ros::Subscriber Imu=nh.subscribe(\"imu\",100,prediction_step);\n    ros::Subscriber anchor_1 = nh.subscribe(\"anchor_lead\", 100,correction_step_leader);\n    ros::Subscriber anchor_2 = nh.subscribe(\"anchor_neigh\",100,correction_step_neigh);\n    ros::Subscriber anchor_3 = nh.subscribe(\"position_leader\",100,position_lead_cb);\n    ros::Subscriber anchor_4 = nh.subscribe(\"position_neighour\",100,position_neigh_cb);\n\n    //ros::Publisher fused = nh.advertise<std_msgs::Float32MultiArray>(\"Filtered_data\", 100);\n    ros::Publisher fused_pose = nh.advertise<geometry_msgs::Vector3Stamped>(\"Filtered_pose\", 10);\n    ros::Publisher fused_vel = nh.advertise<geometry_msgs::Vector3Stamped>(\"Filtered_velocity\", 10);\n    ros::Publisher fused_acc = nh.advertise<geometry_msgs::Vector3Stamped>(\"Filtered_acc\", 10);\n\n    ros::Rate loop_rate(50);\n    while(ros::ok()){\n        param(nh);\n    //\toutput.data.clear();\n\t//\tfor (int i = 0; i < 15; i++)\n\t//\t\toutput.data.push_back(X(i));\n\t\t\n        pose.header.stamp = ros::Time::now();\n        pose.vector.x=X(0);\n        pose.vector.y=X(3);\n        pose.vector.z=X(6);\n\n        vel.header.stamp = ros::Time::now();\n        vel.vector.x=X(1);\n        vel.vector.y=X(4);\n        vel.vector.z=X(7);\n\n        acc_.header.stamp = ros::Time::now();\n        acc_.vector.x=ax;\n        acc_.vector.y=ay;\n        acc_.vector.z=az;\n    //    fused.publish(output);\n        fused_pose.publish(pose);\n        fused_vel.publish(vel);\n        fused_acc.publish(acc_);\n        ros::spinOnce();\n        loop_rate.sleep();\n    }\n    return 0;\n}  ", "meta": {"hexsha": "005cc89adc5016e63db3c2774163d7540d9ee5f1", "size": 13538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gazebo_sim/gps_denied/src/ekf_swarm_acc.cpp", "max_stars_repo_name": "naveenbiitk/State_Estimation", "max_stars_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-05T06:19:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-05T06:19:20.000Z", "max_issues_repo_path": "gazebo_sim/gps_denied/src/ekf_swarm_acc.cpp", "max_issues_repo_name": "naveenbiitk/State_Estimation", "max_issues_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gazebo_sim/gps_denied/src/ekf_swarm_acc.cpp", "max_forks_repo_name": "naveenbiitk/State_Estimation", "max_forks_repo_head_hexsha": "ed6f00355745ba16dcbbe5bf794fd9be56a1d999", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1514476615, "max_line_length": 139, "alphanum_fraction": 0.6176687842, "num_tokens": 4557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8221891130942474, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.40467172678379193}}
{"text": "/*\nCopyright (C) 2012 Mathias Eitz and Ronald Richter.\nAll rights reserved.\n\nThis file is part of the imdb library and is made available under\nthe terms of the BSD license (see the LICENSE file).\n*/\n\n#ifndef KMEANS_HPP\n#define KMEANS_HPP\n\n#include <vector>\n#include <algorithm>\n#include <iostream>\n#include <set>\n\n#include <boost/random.hpp>\n#include <boost/thread/thread.hpp>\n#include <boost/thread/mutex.hpp>\n#include <boost/thread/locks.hpp>\n\n#include <QTime>\n\n#include \"../search/distance.hpp\"\n#include \"kmeans_init.hpp\"\n\n\n\n/**\n * @brief Standard kmeans clustering\n */\ntemplate <class collection_t, class dist_fn>\nclass kmeans\n{\n    typedef boost::mutex               mutex_t;\n    typedef boost::lock_guard<mutex_t> locker_t;\n\n    typedef typename collection_t::value_type sample_t;\n\n    public:\n\n    /**\n     * @brief Standard k-means clustering given a distance function\n     * @param collection Datastructure containing the samples to be clustered, typically a vector<vector<float> >, where the 'inner'\n     * vector<float> would be a single sample.\n     * @param numclusters Number of clusters to use.\n     * @param initalgorithm Algorithm used to estimate the inital cluster centers\n     * @param distfn Distance function used for comparing two samples.\n     */\n    kmeans(const collection_t& collection, std::size_t numclusters, KmeansInitAlgorithm initalgorithm = KmeansInitRandom, const dist_fn& distfn = dist_fn())\n     : _collection(collection), _distfn(distfn), _centers(numclusters), _clusters(collection.size())\n    {\n        // get initial centers\n        std::vector<std::size_t> initindices;\n        if (initalgorithm == KmeansInitPlusPlus)\n        {\n            kmeans_init_plusplus(initindices, collection, numclusters, distfn);\n        }\n        else\n        {\n            kmeans_init_random(initindices, collection, numclusters);\n        }\n\n        for (std::size_t i = 0; i < initindices.size(); i++) _centers[i] = collection[initindices[i]];\n    }\n\n    /**\n     * @brief Perform k-means clustering on the dataset provided in the constructor\n     *\n     * Iterates until at least one of the following two criteria are met:\n     * - maximum number of iterations reached\n     * - the fraction of samples that changed clusters is below minchangesfraction\n     * @param maxiteration Maximum number of iterations\n     * @param minchangesfraction Fraction of changes, if less changes happen in a certain iteration, clustering is done.\n     */\n    void run(std::size_t maxiteration, double minchangesfraction)\n    {\n        using namespace boost;\n\n        // main iteration\n        std::size_t iteration = 0;\n        for (;;)\n        {\n            if (maxiteration > 0 && iteration == maxiteration) break;\n\n            QTime time;\n            time.start();\n            std::size_t changes = 0;\n\n            // distribute items on clusters in parallel\n            thread_group pool;\n            std::size_t idx = 0;\n            mutex_t mtx;\n            for (std::size_t i = 0; i < thread::hardware_concurrency(); i++)\n            {\n                pool.create_thread(bind(&kmeans::distribute_samples, this, ref(idx), ref(changes), ref(mtx)));\n            }\n            pool.join_all();\n\n            iteration++;\n\n            std::cout << \"changes: \" << changes << \" distribution time: \" << time.elapsed() << std::endl;\n\n            if (changes <= std::ceil(_collection.size() * minchangesfraction)) break;\n\n            // compute new centers\n            std::vector<std::size_t> clustersize(_centers.size(), 0);\n            for (std::size_t i = 0; i < _collection.size(); i++)\n            {\n                std::size_t k = _clusters[i];\n\n                // if it is the first assignment for that cluster, then zero the center\n                if (clustersize[k] == 0) std::fill(_centers[k].begin(), _centers[k].end(), 0);\n\n                add_operation(_centers[k], _collection[i]);\n                clustersize[k]++;\n            }\n\n            // assign new centers\n            std::vector<std::size_t> invalid, valid;\n            for (std::size_t i = 0; i < _centers.size(); i++)\n            {\n                if (clustersize[i] > 0)\n                {\n                    div_operation(_centers[i], clustersize[i]);\n                    valid.push_back(i);\n                }\n                else\n                {\n                    invalid.push_back(i);\n                }\n                //std::cout << \"clustersize \" << i << \": \" << clustersize[i] << std::endl;\n            }\n\n            // fix invalid centers, i.e. those with no members\n            while (!invalid.empty() && !valid.empty())\n            {\n                std::size_t current = invalid.back();\nstd::cout << \"handle invalid clusters: \" << invalid.size() << std::endl;\n                // compute for each valid cluster the variance\n                // of distances to all members and get the\n                // most distant member\n                std::vector<double> maxdist(_centers.size(), 0.0);\n                std::vector<double> variance(_centers.size(), 0.0);\n                std::vector<std::size_t> farthest(_centers.size());\n                for (std::size_t i = 0; i < valid.size(); i++)\n                {\n                    std::size_t c = valid[i];\n\n\n                    for (std::size_t k = 0; k < _collection.size(); k++)\n                    {\n                        if (_clusters[k] != c) continue;\n\n                        double d = _distfn(_collection[k], _centers[c]);\n                        if (d > maxdist[c])\n                        {\n                            maxdist[c] = d;\n                            farthest[c] = k;\n                        }\n                        variance[c] += d*d;\n                    }\n                    variance[c] /= clustersize[c];\n                }\n\n                // get cluster with highest variance and make\n                // the farthest member of that cluster the\n                // new center\n                std::size_t c = std::distance(variance.begin(), std::max_element(variance.begin(), variance.end()));\n                _centers[current] = _collection[farthest[c]];\n                _clusters[farthest[c]] = current;\n\nstd::cout << \"reassign \" << current << \" to sample \" << farthest[c] << \" of cluster \" << c << std::endl;\n\n                valid.pop_back();\n                invalid.pop_back();\n            }\n\nstd::cout << \"iteration \" << iteration << \" time: \" << time.elapsed() << std::endl;\n        }\n\nstd::cout << \"kmeans iterations: \" << iteration << std::endl;\n    }\n\n\n    /// Run clustering, using theoretically unlimited number of iterations. Clustering will\n    /// stop when the fraction of changes falls below 0.01\n    void run_default()\n    {\n        this->run(std::numeric_limits<std::size_t>::max(), 0.01);\n    }\n\n    /// Vector of cluster membership: clusters[i] = j means that the sample with index i\n    /// is a member of cluster j\n    const std::vector<std::size_t>& clusters() const\n    {\n        return _clusters;\n    }\n\n    /// Vector of cluster centers\n    const std::vector<sample_t>& centers() const\n    {\n        return _centers;\n    }\n\n\n    /// Convenience function generating a clustering table:\n    /// table[i][j] = k means that the sample with index k belongs to cluster i.\n    template <class index_t>\n    void make_cluster_table(std::vector<std::vector<index_t> >& table)\n    {\n        table.resize(_centers.size());\n        for (std::size_t i = 0; i < _clusters.size(); i++) table[_clusters[i]].push_back(i);\n    }\n\n    template <class T>\n    static void add_operation(T& lhs, const T& rhs)\n    {\n        for (std::size_t i = 0; i < lhs.size(); i++) lhs[i] += rhs[i];\n    }\n\n    template <class T>\n    static void div_operation(T& lhs, double rhs)\n    {\n        for (std::size_t i = 0; i < lhs.size(); i++) lhs[i] /= rhs;\n    }\n\n    private:\n\n    void distribute_samples(std::size_t& index, std::size_t& changes, mutex_t& mutex)\n    {\n        std::vector<double> dists(_centers.size());\n        std::size_t currentchanges = 0;\n\n        for (;;)\n        {\n            std::size_t i;\n\n            {\n                locker_t locker(mutex);\n                if (index == _collection.size()) break;\n                i = index++;\n            }\n\n            // compute distance of current point to every center\n            std::transform(_centers.begin(), _centers.end(), dists.begin(), boost::bind(_distfn, boost::ref(_collection[i]), boost::arg<1>()));\n\n            // find the minimum distance, i.e. the nearest center\n            std::size_t c = std::distance(dists.begin(), std::min_element(dists.begin(), dists.end()));\n\n            // update cluster membership\n            {\n                locker_t locker(_mutex);\n\n                if (_clusters[i] != c)\n                {\n                    _clusters[i] = c;\n                    currentchanges++;\n                }\n//if (i % 1000 == 0) std::cout << \"kmeans distribute: \" << i << std::endl;\n            }\n        }\n\n        {\n            locker_t locker(mutex);\n            changes += currentchanges;\n        }\n    }\n\n    const collection_t& _collection;\n    const dist_fn&      _distfn;\n\n    std::vector<sample_t>    _centers;\n    std::vector<std::size_t> _clusters;\n\n    boost::mutex        _mutex;\n};\n\n\n#endif // KMEANS_HPP\n", "meta": {"hexsha": "7d7f34990180b220016e93aa2cf4f2b086a881c8", "size": 9268, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "util/kmeans.hpp", "max_stars_repo_name": "mathiaseitz/imdb_framework", "max_stars_repo_head_hexsha": "f8512447613bbbd19f62329c0ba121f28b8b52e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-08-19T04:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-26T20:11:12.000Z", "max_issues_repo_path": "util/kmeans.hpp", "max_issues_repo_name": "zddhub/imdb_framework", "max_issues_repo_head_hexsha": "f8512447613bbbd19f62329c0ba121f28b8b52e7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/kmeans.hpp", "max_forks_repo_name": "zddhub/imdb_framework", "max_forks_repo_head_hexsha": "f8512447613bbbd19f62329c0ba121f28b8b52e7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-12-21T13:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T01:29:11.000Z", "avg_line_length": 32.9822064057, "max_line_length": 156, "alphanum_fraction": 0.5482304704, "num_tokens": 2079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.40456272530158555}}
{"text": "﻿/***************************************************************\n * Author:    Yixin Zhuang (yixin.zhuang@gmail.com)\n **************************************************************/\n\n\n#include \"core/Segmentation.h\"\n\n#include <fstream>\n#include <queue>\n\n//i use boost_1_67_0\n#include <boost/config.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\nusing namespace boost;\n//boost graph\ntypedef adjacency_list < vecS, vecS, undirectedS,\n\tno_property, property < edge_weight_t, double > > graph_t;\ntypedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;\ntypedef graph_traits < graph_t >::edge_descriptor edge_descriptor;\ntypedef std::pair<int, int> Edge;\n\nusing namespace GeoProperty;\n\n#include \"andres/graph/graph.hxx\"\n#include \"andres/graph/complete-graph.hxx\"\n#include \"andres/graph/multicut-lifted/greedy-additive.hxx\"\n#include \"andres/graph/multicut-lifted/kernighan-lin.hxx\"\n\nvoid Mitani_WaterShed::distanceToFeature_ShortestPath(std::list<MyMesh::Vertex>& vers, std::list<MyMesh::Edge>& edges, std::set<int>& sources, std::vector<double>& res)\n{\n\t//build dual graph;\n\n\tint superNode = vers.size();\n\tint vNum = vers.size() + 1; //will add a super node\n\tint eNum = edges.size() + sources.size();//will add edges connecting super node and sources\n\n\t// init graph\n\tgraph_t g(vNum);\n\tproperty_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);\n\tfor (auto i = edges.begin(); i != edges.end(); i++)\n\t{\t\t\n\t\tint nodeID[] = { i->vertex_iter(0)->id(), i->vertex_iter(1)->id() };\n\t\tgraph_traits < graph_t >::edge_descriptor e;\n\t\tbool inserted;\n\t\tboost::tie(e, inserted) = add_edge(nodeID[0], nodeID[1], g);\n\t\tif (!inserted) cout << \"insert edge failed\" << endl;\n\t\tweightmap[e] = i->length();\n\t}\n\tfor (auto i = sources.begin(); i != sources.end(); i++)\n\t{\n\t\tgraph_traits < graph_t >::edge_descriptor e;\n\t\tbool inserted;\n\t\tboost::tie(e, inserted) = add_edge(*i, superNode, g);\n\t\tif (!inserted) cout << \"insert edge failed\" << endl;\n\t\tweightmap[e] = 0;\n\t}\n\n\t//shortest path;\n\tstd::vector<vertex_descriptor> p(vNum);\n\tstd::vector<double> d(vNum);\n\tvertex_descriptor s = vertex(superNode, g);\n\tdijkstra_shortest_paths(g, s, predecessor_map(&p[0]).distance_map(&d[0]));\n\n\td.pop_back();\n\tdouble maxDist = *std::max_element(d.begin(), d.end());\n\tres.resize(d.size());\n\tfor (int i = 0; i < d.size(); i++)\n\t{\n\t\tres[i] = maxDist - d[i];\n\t}\n}\nvoid Mitani_WaterShed::distanceToFeature_ShortestPath(MGraph& pg, std::set<int>& sources, std::vector<double>& res)\n{\n\t//build dual graph;\n\n\tint superNode = pg.vNum;\n\tint vNum = pg.vNum + 1; //will add a super node\n\tint eNum = pg.eNum + sources.size();//will add edges connecting super node and sources\n\n\t// init graph\n\tgraph_t g(vNum);\n\tproperty_map<graph_t, edge_weight_t>::type weightmap = get(edge_weight, g);\n\tfor (auto i = pg.es.begin(); i != pg.es.end(); i++)\n\t{\n\t\tint nodeID[] = { i->n1, i->n2 };\n\t\tgraph_traits < graph_t >::edge_descriptor e;\n\t\tbool inserted;\n\t\tboost::tie(e, inserted) = add_edge(nodeID[0], nodeID[1], g);\n\t\tif (!inserted) cout << \"insert edge failed\" << endl;\n\t\tweightmap[e] = i->w;\n\t}\n\tfor (auto i = sources.begin(); i != sources.end(); i++)\n\t{\n\t\tgraph_traits < graph_t >::edge_descriptor e;\n\t\tbool inserted;\n\t\tboost::tie(e, inserted) = add_edge(*i, superNode, g);\n\t\tif (!inserted) cout << \"insert edge failed\" << endl;\n\t\tweightmap[e] = 0;\n\t}\n\n\t//shortest path;\n\tstd::vector<vertex_descriptor> p(vNum);\n\tstd::vector<double> d(vNum);\n\tvertex_descriptor s = vertex(superNode, g);\n\tdijkstra_shortest_paths(g, s, predecessor_map(&p[0]).distance_map(&d[0]));\n\n\td.pop_back();\n\tdouble maxDist = *std::max_element(d.begin(), d.end());\n\tres.resize(d.size());\n\tfor (int i = 0; i < d.size(); i++)\n\t{\n\t\tres[i] = maxDist - d[i];\n\t}\n}\n\nint Mitani_WaterShed::grow(const std::vector<std::list<MyMesh::Vertex>::iterator>& vers, const std::vector<double>& distanceToFeature, std::vector<bool>& isExtrema, std::vector<unsigned>& vertexLabels)\n{\n\t//init indexed items, and the flood fronts;\n\tint vNum = distanceToFeature.size();\n\tstd::vector<bool> unIndexed(vNum, true);\n\n\tvertexLabels.clear(); vertexLabels.resize(vNum, UINT_MAX);\n\tint labelId = 0;\n\tstd::priority_queue<HighFunction> floodFront;\n\tfor (int i = 0; i < vNum; i++)\n\t{\n\t\tif (isExtrema[i])\n\t\t{\n\t\t\tunIndexed[i] = false;\n\t\t\tvertexLabels[i] = labelId++;\n\t\t\tfloodFront.push(HighFunction(i, distanceToFeature[i]));\n\t\t}\n\t}\n\n\tconst auto vts = vers;\n\twhile (!floodFront.empty())\n\t{\n\t\tHighFunction v = floodFront.top(); floodFront.pop();\n\n\t\tfor (int i = 0; i < vts[v.m_id]->vertex_iter().size(); i++)\n\t\t{\n\t\t\tint id = vts[v.m_id]->vertex_iter()[i]->id();\n\t\t\tif (unIndexed[id]) //unindexed neighbore;\n\t\t\t{\n\t\t\t\tHighFunction newV(id, distanceToFeature[id]);\n\t\t\t\tfloodFront.push(newV);\n\n\t\t\t\tunIndexed[id] = false;\n\t\t\t\tvertexLabels[id] = vertexLabels[v.m_id];\n\t\t\t}\n\t\t}\n\t}\n\n\tcout << \"cluster number:\" << labelId << endl;\n\treturn labelId;\n}\n//////////////////////////////////////////////////////////////////////////\n//grow2 -- Implement of Paper: Analysis and Comparison of Algorithms for Morse Decompositions on Triangulated Terrains\n//by Maria Vitali, Leila De Floriani, Paola Magillo\n//detailed in section 5:watershed algorithms, page 9.\n//the output contains not just the cluster labels of vertices, but also the boundary vertices(between basins). \nint Mitani_WaterShed::grow2(MGraph& pg, const std::vector<double>& distanceToFeature, const std::vector<std::set<unsigned> >& neighbours, std::vector<unsigned>& vertexLabels)\n{\n\t//init indexed items, and the flood fronts;\n\tint vNum = distanceToFeature.size();\n\tstd::vector<bool> unIndexed(vNum, true);\n\tstd::priority_queue<HighFunction> floodFront;\n\tfor (int i = 0; i < vNum; i++)\n\t{\n\t\tfloodFront.push(HighFunction(i, distanceToFeature[i]));\n\t}\n\t\n\tint labelId = 0;\n\tstd::vector<int> labels(vNum, -1);\n\twhile (!floodFront.empty())\n\t{\n\t\tHighFunction v = floodFront.top(); floodFront.pop();\n\t\tstd::set<int> ls;\n\t\tfor (auto n = neighbours[v.m_id].begin(); n != neighbours[v.m_id].end(); n++)\n\t\t{\n\t\t\tif (!unIndexed[*n] && labels[*n] != -2) //neighbours assigned as basin;\n\t\t\t{\n\t\t\t\tls.insert(labels[*n]);\n\t\t\t}\n\t\t}\n\n\t\tif (ls.empty())\n\t\t{\n\t\t\tlabels[v.m_id] = labelId; labelId++;//new cluster begins...\n\t\t}\n\t\telse if (ls.size() == 1)\n\t\t{\n\t\t\tlabels[v.m_id] = *ls.begin();//basin node\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlabels[v.m_id] = -2;//watershed node\n\t\t}\n\n\t\tunIndexed[v.m_id] = false;\n\t}\n\n\tvertexLabels.resize(vNum, 0);\n\tfor (int i = 0; i < vNum; i++)\n\t{\n\t\tif (labels[i] == -2)\n\t\t{\n\t\t\tvertexLabels[i] = UINT_MAX; //watershed node\n\t\t}\n\t}\n\n\treturn labelId;\n}\nvoid Mitani_WaterShed::thresholdClusters(MyMesh* mesh, std::vector<unsigned>& faceLabels, unsigned& segNum, std::vector<bool>& isFeature, double thres)\n{\n\t// In our case, we use area as measurement of cluster size, for merging. Other criteria, like perimeter, would only require few changes of the code.\n\tdouble averageArea = 0;\n\tstd::vector<double> faceAreas(mesh->getFaces().size());\n\tfor (auto i = mesh->getFaces().begin(); i != mesh->getFaces().end(); i++)\n\t{\n\t\tfaceAreas[i->id()] = i->triangleCost(2);\n\t\taverageArea += faceAreas[i->id()];\n\t}\n\n\tthres = averageArea * thres*0.01; //thres percent (thres%) of total area;\n\n\t//initialize area of all clusters;\n\tstd::vector<double> scores(segNum, 0.0);\n\tfor (auto i = mesh->getFaces().begin(); i != mesh->getFaces().end(); i++)\n\t{\n\t\tscores[faceLabels[i->id()]] += faceAreas[i->id()];\n\t}\n\t\n\t//shared boundary length between clusters;\n\tstd::vector<double> sharesRow(segNum, 0.0);\n\tstd::vector<std::vector<double> > sharesMatrix(segNum, sharesRow);\n\tfor (auto i = mesh->getEdges().begin(); i != mesh->getEdges().end(); i++)\n\t{\n\t\tif (i->manifold())\n\t\t{\n\t\t\tint l1 = faceLabels[i->face_iter(0)->id()];\n\t\t\tint l2 = faceLabels[i->face_iter(1)->id()];\n\n\t\t\tif (l1 != l2 && !isFeature[i->face_iter(0)->id()] && !isFeature[i->face_iter(1)->id()])\n\t\t\t{\n\t\t\t\tsharesMatrix[l1][l2] = sharesMatrix[l2][l1] += i->length(); //in dual graph case, use i->dualLength;\n\t\t\t}\n\t\t}\n\t}\n\n\t//build adjacency and priority queue;\n\tstd::multiset<ClusterArea> clusterQueue;\n\tfor (int i = 0; i < scores.size(); i++)\n\t{\n\t\tclusterQueue.insert(ClusterArea(i, scores[i]));\n\t}\n\tif (clusterQueue.size() != scores.size())\n\t{\n\t\tcout << \"numerical issue\" << endl;\n\t}\n\t//adjcents between clusters;\n\tstd::list<std::multiset<DecreaseOrderExt> > clusterAdjcencyList(segNum);\n\tstd::vector<std::list<std::multiset<DecreaseOrderExt> >::iterator> clusterAdjcency;\n\tfor (auto i = clusterAdjcencyList.begin(); i != clusterAdjcencyList.end(); i++)\n\t{\n\t\tclusterAdjcency.push_back(i);\n\t}\n\n\tfor (auto i = mesh->getEdges().begin(); i != mesh->getEdges().end(); i++)\n\t{\n\t\tif (i->manifold())\n\t\t{\n\t\t\tint l1 = faceLabels[i->face_iter(0)->id()];\n\t\t\tint l2 = faceLabels[i->face_iter(1)->id()];\n\n\t\t\tif (l1 != l2)\n\t\t\t{\n\t\t\t\tif (clusterAdjcency[l1]->find(DecreaseOrderExt(l2, scores[l2], sharesMatrix[l1][l2])) == clusterAdjcency[l1]->end())\n\t\t\t\t\tclusterAdjcency[l1]->insert(DecreaseOrderExt(l2, scores[l2], sharesMatrix[l1][l2]));\n\n\t\t\t\tif (clusterAdjcency[l2]->find(DecreaseOrderExt(l1, scores[l1], sharesMatrix[l1][l2])) == clusterAdjcency[l2]->end())\n\t\t\t\t\tclusterAdjcency[l2]->insert(DecreaseOrderExt(l1, scores[l1], sharesMatrix[l1][l2]));\n\t\t\t}\n\t\t}\n\t}\n\n\t//clusters\n\tstd::list<std::set<int>> clusters(segNum);\n\tstd::vector<std::list<std::set<int>>::iterator> iclusters;\n\tfor (auto i = clusters.begin(); i != clusters.end(); i++)\n\t{\n\t\ticlusters.push_back(i);\n\t}\n\tfor (int i = 0; i < faceLabels.size(); i++)\n\t{\n\t\ticlusters[faceLabels[i]]->insert(i);\n\t}\n\n// \tcout << \"thres:\" << thres << endl;\n\twhile (!clusterQueue.empty())\n\t{\n\t\tClusterArea ci = *clusterQueue.begin(); clusterQueue.erase(clusterQueue.begin());\n\t\tif (ci.m_val > thres)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\tif (clusterAdjcency[ci.m_id]->empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tDecreaseOrderExt cj_ = *clusterAdjcency[ci.m_id]->begin();\n\t\tClusterArea cj(cj_.m_id, cj_.m_val);\n\n\t\tclusterAdjcency[ci.m_id]->erase(clusterAdjcency[ci.m_id]->begin()); //remove cj from ci's\n\n\t\tauto tp = clusterAdjcency[cj.m_id]->begin();\n\t\tfor (; tp != clusterAdjcency[cj.m_id]->end(); tp++)\n\t\t{\n\t\t\tif (tp->m_id == ci.m_id )\n\t\t\t\tbreak;\n\t\t}\n\t\tif (tp == clusterAdjcency[cj.m_id]->end())\n\t\t{\n\t\t\tcout << \"invalid merge\" << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tclusterAdjcency[cj.m_id]->erase(tp);\n\t\t}\n\n\t\tauto i = std::find(clusterQueue.begin(), clusterQueue.end(), cj);\n\t\tif (i == clusterQueue.end())\n\t\t{\n\t\t\tcout << \"invalid reference\" << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tclusterQueue.erase(i);\n\t\t}\n\n\t\t//0. merge ci to cj.\n\t\t//1. cj is still in clusterQueue, need to update it, the new area is not just sum of ci and cj.\n\t\t//2. clear ci's clusterAdjacency, and add adj to cj, if not existed in cj. add cj to ci's adjacency, if not existed.\n\t\t\n\t\t//0. merge ci to cj.\n\t\tfor (auto i = iclusters[ci.m_id]->begin(); i != iclusters[ci.m_id]->end(); i++)\n\t\t{\n\t\t\tfaceLabels[*i] = cj.m_id;\n\t\t}\n\t\ticlusters[cj.m_id]->insert(iclusters[ci.m_id]->begin(), iclusters[ci.m_id]->end());\n\t\ticlusters[ci.m_id]->clear();\n\n\n\t\t//1. cj is still in clusterQueue, need to update it, the new area is  just sum of ci and cj.\n\t\t//2. clear ci's clusterAdjacency, and add it's adjacency to cj, if not existed in cj, and cj to it's adjacency, if not existed in...\n\t\t// ci's = {ci_a, ci_...}\n\t\tdouble newScore = ci.m_val + cj.m_val;\n\t\tclusterQueue.insert(ClusterArea(cj.m_id,newScore));\n\n\t\tfor (auto i = clusterAdjcency[ci.m_id]->begin(); i != clusterAdjcency[ci.m_id]->end(); i++)\n\t\t{\n\t\t\tint ci_a = i->m_id; // for each cluster\n\n\t\t\t//if ci_a not in cj, then add to cj, if exist, then update their shared boundary, m_val_ext;\n\t\t\t//if cj not in ci_a, then add to ci_a, if exist, then update their shared boundary, m_val_ext;\n\t\t\tauto ip = clusterAdjcency[ci_a]->begin();\n\t\t\tfor (; ip != clusterAdjcency[ci_a]->end(); ip++)\n\t\t\t{\n\t\t\t\tif (ip->m_id == cj.m_id && ip->m_val == cj.m_val)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ip == clusterAdjcency[ci_a]->end())\n\t\t\t{\n\t\t\t\tclusterAdjcency[ci_a]->insert(DecreaseOrderExt(cj.m_id, newScore, i->m_val_ext));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdouble temp = ip->m_val_ext;\n\t\t\t\tclusterAdjcency[ci_a]->erase(ip);\n\t\t\t\tclusterAdjcency[ci_a]->insert(DecreaseOrderExt(cj.m_id, newScore, i->m_val_ext + temp));\n\t\t\t}\n\n\t\t\tip = clusterAdjcency[cj.m_id]->begin();\n\t\t\tfor (; ip != clusterAdjcency[cj.m_id]->end(); ip++)\n\t\t\t{\n\t\t\t\tif (ip->m_id == i->m_id && ip->m_val == i->m_val)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ip == clusterAdjcency[cj.m_id]->end())\n\t\t\t{\n\t\t\t\tclusterAdjcency[cj.m_id]->insert(DecreaseOrderExt(i->m_id, i->m_val, i->m_val_ext));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdouble temp = ip->m_val_ext;\n\t\t\t\tclusterAdjcency[cj.m_id]->erase(ip);\n\t\t\t\tclusterAdjcency[cj.m_id]->insert(DecreaseOrderExt(i->m_id, i->m_val, i->m_val_ext + temp));\n\t\t\t}\n\n\n\t\t\t//remove ci from ci_a\n\t\t\tip = clusterAdjcency[ci_a]->begin();\n\t\t\tfor (; ip != clusterAdjcency[ci_a]->end(); ip++)\n\t\t\t{\n\t\t\t\tif (ip->m_id == ci.m_id && ip->m_val == ci.m_val)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ip == clusterAdjcency[ci_a]->end())\n\t\t\t{\n\t\t\t\tcout << endl << ci_a << \" error \" << ci.m_id << \" \" << ci.m_val << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tclusterAdjcency[ci_a]->erase(ip);\n\t\t\t}\n\t\t}\n\n\t\tclusterAdjcency[ci.m_id]->clear();\n\n\t\t//for all cj_a in cj, even though not appeared in ci, need to update cj_a's element cj...\n\t\tfor (auto i = clusterAdjcency[cj.m_id]->begin(); i != clusterAdjcency[cj.m_id]->end();i++)\n\t\t{\n\t\t\tauto ip = clusterAdjcency[i->m_id]->begin();\n\t\t\tfor (; ip != clusterAdjcency[i->m_id]->end(); ip++)\n\t\t\t{\n\t\t\t\tif (ip->m_id == cj.m_id)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ip == clusterAdjcency[i->m_id]->end())\n\t\t\t{\n\t\t\t\tcout << \"bad reference\" << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tclusterAdjcency[i->m_id]->erase(ip);\n\t\t\t\tclusterAdjcency[i->m_id]->insert(DecreaseOrderExt(cj.m_id, newScore,i->m_val_ext));\n\t\t\t}\t\t\t\n\t\t}\n\n\t}\n\n\t//update label;\n\tint ind = 0;\n\tfor (auto i = clusters.begin(); i != clusters.end(); i++)\n\t{\n\t\tif (i->empty())\n\t\t\tcontinue;\n\n\t\tfor (auto f = i->begin(); f != i->end(); f++)\n\t\t{\n\t\t\tfaceLabels[*f] = ind;\n\t\t}\n\n\t\tind++;\n\t}\n\tsegNum = ind;\n}\n\nvoid MeshSegment::convertFaceToVertexLabelling(std::vector<unsigned>& vertexLabel,std::vector<unsigned>& faceLabel)\n{\n\tunsigned vNum = myMesh->getVertices().size();\n\tstd::vector<std::vector<unsigned> > vertexMultiLabels(vNum);\n\tfor (auto i = myMesh->getFaces().begin(); i != myMesh->getFaces().end(); i++)\n\t{\n\t\tfor (unsigned j = 0; j < 3; j++)\n\t\t{\n\t\t\tvertexMultiLabels[i->vertex_iter(j)->id()].push_back(faceLabel[i->id()]);\n\t\t}\n\t}\n\n\tvertexLabel.clear(); vertexLabel.resize(vNum);\n\tfor (int i = 0; i < vNum; i++)\n\t{\n\t\tstd::map<unsigned, unsigned> st;\n\t\tstd::map<unsigned, unsigned>::iterator it;\n\t\tfor (int j = 0; j < vertexMultiLabels[i].size(); j++)\n\t\t{\n\t\t\tit = st.find(vertexMultiLabels[i][j]);\n\t\t\tif (it == st.end())\n\t\t\t{\n\t\t\t\tst[vertexMultiLabels[i][j]] = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tst[vertexMultiLabels[i][j]] = it->second + 1;\n\t\t\t}\n\t\t}\n\n\t\tstd::pair<unsigned, unsigned> majorPair(vertexMultiLabels[i][0],1);\n\t\tfor (it = st.begin(); it != st.end(); it++)\n\t\t{\n\t\t\tif (majorPair.second < it->second)\n\t\t\t{\n\t\t\t\tmajorPair.first = it->first;\n\t\t\t\tmajorPair.second = it->second;\n\t\t\t}\n\t\t}\n\t\tvertexLabel[i] = majorPair.first;\n\t}\n\n\tstd::vector<double> weights;\n\tgetWeights(edgeWeightParameter,weights);\n\n\tdouble cutCost = 0;\n\tfor (auto e = myMesh->getEdges().begin(); e != myMesh->getEdges().end(); e++)\n\t{\n\t\tif (vertexLabel[e->vertex_iter(0)->id()] != vertexLabel[e->vertex_iter(1)->id()])\n\t\t{\n\t\t\tcutCost += weights[e->id()];\n\t\t\tgraphFeature.ef[e->id()].isCut = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgraphFeature.ef[e->id()].isCut = false;\n\t\t}\n\t}\n\tcout << \"Cost:\" << cutCost << endl;\n\n\tunsigned eNum = myMesh->getEdges().size();\n\tvertexLabel.clear(); vertexLabel.resize(vNum);\n\tsegNumber = 0;\n\tstd::vector<bool> visitedVer(vNum, false);\n\tstd::vector<bool> visitedEdge(eNum, false);\n\tfor (int i = 0; i < vNum; i++)\n\t{\n\t\tif (visitedVer[i] == true) continue;\n\n\t\tstd::vector<int> frontVer(1, i);\n\t\t//propagates vertex with same label, and group them into a subgraph\n\t\twhile (!frontVer.empty())\n\t\t{\n\t\t\tint fv = frontVer.back(); frontVer.pop_back();\n\t\t\tvertexLabel[fv] = segNumber;\n\n\t\t\tauto v = mg.vs[fv].vadjs.begin();\n\t\t\tauto e = mg.vs[fv].eadjs.begin();\n\t\t\tfor (; v != mg.vs[fv].vadjs.end(); v++, e++)\n\t\t\t{\n\t\t\t\tif (graphFeature.ef[*e].isCut || visitedEdge[*e] == true)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvisitedEdge[*e] = true;\n\n\t\t\t\tif (visitedVer[*v] == true)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvisitedVer[*v] = true;\n\n\t\t\t\tfrontVer.push_back(*v);\n\t\t\t}\n\t\t}\n\t\tsegNumber++;\n\t}\n\n\tcout << endl << \"cluster number :\" << segNumber << endl;\n}\nvoid MeshSegment::convertVertexToFaceLabelling(std::vector<unsigned>& vertexLabel,std::vector<unsigned>& faceLabel)\n{\n\tunsigned fNum = myMesh->getFaces().size();\n\tstd::vector<std::vector<unsigned> > faceMultiLabels(fNum);\n\tfor (auto i = myMesh->getFaces().begin(); i != myMesh->getFaces().end(); i++)\n\t{\n\t\tfor (unsigned j = 0; j < 3; j++)\n\t\t{\n\t\t\tfaceMultiLabels[i->id()].push_back(vertexLabel[i->vertex_iter(j)->id()]);\n\t\t}\n\t}\n\t\n\tfaceLabel.clear();\tfaceLabel.resize(fNum);\n\tfor (int i = 0; i < fNum; i++)\n\t{\n\t\tstd::map<unsigned, unsigned> st;\n\t\tstd::map<unsigned, unsigned>::iterator it;\n\t\tfor (int j = 0; j < faceMultiLabels[i].size(); j++)\n\t\t{\n\t\t\tit = st.find(faceMultiLabels[i][j]);\n\t\t\tif (it == st.end())\n\t\t\t{\n\t\t\t\tst[faceMultiLabels[i][j]] = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tst[faceMultiLabels[i][j]] = it->second + 1;\n\t\t\t}\n\t\t}\n\n\t\tstd::pair<unsigned, unsigned> majorPair(faceMultiLabels[i][0], 1);\n\t\tfor (it = st.begin(); it != st.end(); it++)\n\t\t{\n\t\t\tif (majorPair.second < it->second)\n\t\t\t{\n\t\t\t\tmajorPair.first = it->first;\n\t\t\t\tmajorPair.second = it->second;\n\t\t\t}\n\t\t}\n\n\t\tfaceLabel[i] = majorPair.first;\n\t}\n}\n\n///////////////////OVER SEGMENTATION///////////////////////////////\nvoid MeshSegment::Mitani_Watershed()\n{\n\tclock_t tstr = clock();\n\n\t//find sources;\n\tstd::set<int> sources;\n\tfor (auto e_it = myMesh->getEdges().begin(); e_it != myMesh->getEdges().end(); e_it++)\n\t{\n\t\tif (graphFeature.ef[e_it->id()].lab != -1)\n\t\t{\n\t\t\tsources.insert(e_it->vertex_iter(0)->id());\n\t\t\tsources.insert(e_it->vertex_iter(1)->id());\n\t\t}\n\t}\n\n\tws.distanceToFeature_ShortestPath(myMesh->getVertices(), myMesh->getEdges(), sources, ws.distanceToFeature);\n\n\t//local extrema, and growing\n\tauto& vers = myMesh->getVIter();\n\tstd::vector<bool> isExtrema(vers.size(), true);\n\tint ringSize = mitani_Watershed_Ringsize;\n\tfor (int i = 0; i < vers.size(); i++)\n\t{\n\t\tint v1 = i;\n\t\tif (isExtrema[v1])\n\t\t{\n\t\t\tint times = ringSize;\n\t\t\tstd::set<int> fronts; fronts.insert(v1);\n\t\t\tstd::set<int> visited = fronts;\n\t\t\tstd::set<int> nextFronts = fronts;\n\t\t\twhile (times > 0)\n\t\t\t{\n\t\t\t\tfor (auto j = fronts.begin(); j != fronts.end(); j++)\n\t\t\t\t{\n\t\t\t\t\tauto vj = vers[*j];\n\t\t\t\t\tfor (int k = 0; k < vj->vertex_iter().size(); k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint v2 = vj->vertex_iter()[k]->id();\n\t\t\t\t\t\tif (visited.find(v2)!=visited.end())continue;\n\t\t\t\t\t\tnextFronts.insert(v2);\n\t\t\t\t\t\tvisited.insert(v2);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfronts = nextFronts;\n\t\t\t\ttimes--;\n\t\t\t}\n\n\t\t\tvisited.erase(v1);\n\t\t\tfor (auto j = visited.begin(); j != visited.end(); j++)\n\t\t\t{\n\t\t\t\tint v2 = *j;\n\t\t\t\tws.distanceToFeature[v1] < ws.distanceToFeature[v2] ? isExtrema[v2] = false : isExtrema[v1] = false;\n\t\t\t}\n\t\t}\n\t}\n\n\tauto& multiCutLabels = vertexLabel;\n\tauto& multiCutNum = segNumber;\n\tmultiCutNum = ws.grow(myMesh->getVIter(), ws.distanceToFeature, isExtrema, multiCutLabels);\n\n\tclock_t totalTime = clock() - tstr;\n\tcout << \"Watershed Segmentation Use \" << totalTime / 1000 << \"sec\" << totalTime % 1000 << \"mm\" << endl;\n\n\tstd::vector<double> weights;\n\tgetWeights(edgeWeightParameter, weights);\n\n\tvertexLabelBeforeMerge = vertexLabel;\n\n\tdouble cutCost = 0;\n\tfor (auto e = myMesh->getEdges().begin(); e != myMesh->getEdges().end(); e++)\n\t{\n\t\tif (multiCutLabels[e->vertex_iter(0)->id()] != multiCutLabels[e->vertex_iter(1)->id()])\n\t\t{\n\t\t\tcutCost += weights[e->id()];\n\t\t\tgraphFeature.ef[e->id()].isCut = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgraphFeature.ef[e->id()].isCut = false;\n\t\t}\n\t}\n\tcout << \"Cost:\" << cutCost << endl;\n}\nvoid MeshSegment::Mitani_Watershed_Dual()\n{\n\tclock_t tstr = clock();\n\n\t//build dual graph;\n\tstd::list<MyMesh::Vertex> versArray(myMesh->getFaces().size());\n\tstd::vector<std::list<MyMesh::Vertex>::iterator> vers(myMesh->getFaces().size());\n\tint ind = 0;\n\tfor (auto v = versArray.begin(); v != versArray.end(); v++, ind++)\n\t{\n\t\tv->id() = ind;\n\t\tvers[ind] = v;\n\t}\n\n\tfor (auto f = myMesh->getFaces().begin(); f != myMesh->getFaces().end(); f++)\n\t{\n\t\tvers[f->id()]->coordinate() = f->center_point();\n\t}\n\n\tstd::vector<double> edgeCosts(myMesh->getEdges().size());\n\tstd::vector<double> edgeLengths(myMesh->getEdges().size());\n\t{\n\t\tstd::vector<Tensor>& tAnis = faceAnis;\n\n\t\tfor (auto e_it = myMesh->getEdges().begin(); e_it != myMesh->getEdges().end(); e_it++)\n\t\t{\n\t\t\tif (e_it->manifold())\n\t\t\t{\n\t\t\t\tMyMesh::FaceIter f[] = { e_it->face_iter(0), e_it->face_iter(1) };\n\t\t\t\tunsigned fid[] = { f[0]->id(), f[1]->id() };\n\t\t\t\tVec3 edgeVec = graphFeature.cf[f[0]->id()].rep - graphFeature.cf[f[1]->id()].rep;\n\t\t\t\tdouble edgeCost = 0;\n\t\t\t\tfor (unsigned k = 0; k < 2; k++)\n\t\t\t\t{\n\t\t\t\t\tVec2 edgeVec2D = Vec2(edgeVec.dot(tAnis[fid[k]].dir1), edgeVec.dot(tAnis[fid[k]].dir2));// two direction were swapped, since we computed dual edge's cost; and in faceAnis, mag1>mag2;\n\t\t\t\t\tedgeCost += sqrt(pow(edgeVec2D.x, 2)*tAnis[fid[k]].mag1 + pow(edgeVec2D.y, 2)*tAnis[fid[k]].mag2);\n\t\t\t\t}\n\t\t\t\tedgeCosts[e_it->id()] = edgeCost*0.5;\n\t\t\t\tedgeLengths[e_it->id()] = edgeVec.length();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tMyMesh::FaceIter f[] = { e_it->face_iter(0) };\n\t\t\t\tunsigned fid[] = { f[0]->id(), f[1]->id() };\n\t\t\t\tVec3 edgeVec = graphFeature.cf[f[0]->id()].rep - graphFeature.ef[e_it->id()].rep;\n\t\t\t\tdouble edgeCost = 0;\n\t\t\t\tfor (unsigned k = 0; k < 1; k++)\n\t\t\t\t{\n\t\t\t\t\tVec2 edgeVec2D = Vec2(edgeVec.dot(tAnis[fid[k]].dir1), edgeVec.dot(tAnis[fid[k]].dir2));// two direction were swapped, since we computed dual edge's cost; and in faceAnis, mag1>mag2;\n\t\t\t\t\tedgeCost += sqrt(pow(edgeVec2D.x, 2)*tAnis[fid[k]].mag1 + pow(edgeVec2D.y, 2)*tAnis[fid[k]].mag2);\n\t\t\t\t}\n\t\t\t\tedgeCosts[e_it->id()] = edgeCost + 1e-6; //make sure the boundary edge has weight larger than 0;\n\t\t\t\tedgeLengths[e_it->id()] = edgeVec.length();\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::list<MyMesh::Edge> edgesArray;\n\tfor (auto e = myMesh->getEdges().begin(); e != myMesh->getEdges().end(); e++)\n\t{\n\t\tif (!e->manifold()) continue;\n\n\t\tint f1 = e->face_iter(0)->id();\n\t\tint f2 = e->face_iter(1)->id();\n\n\t\tvers[f1]->vertex_iter().push_back(vers[f2]);\n\t\tvers[f2]->vertex_iter().push_back(vers[f1]);\n\n\t\tMyMesh::Edge de;\n\t\t{//compute anis distance\n\t\t\tif (isAnisGeodesics_Watershed)\n\t\t\t{\n\t\t\t\tde.length() = edgeCosts[e->id()];\n\t\t\t}\t\t\t\n\t\t\telse\n\t\t\t{\n\t\t\t\tde.length() = edgeLengths[e->id()];\n\t\t\t}\n\t\t}\n\t\tde.vertex_iter(0) = vers[f1];\n\t\tde.vertex_iter(1) = vers[f2];\n\t\tedgesArray.push_back(de);\n\t}\n\tstd::vector<std::list<MyMesh::Edge>::iterator> edges(edgesArray.size());\n\tind = 0;\n\tfor (auto e = edgesArray.begin(); e != edgesArray.end(); e++, ind++)\n\t{\n\t\te->id() = ind;\n\t\tedges[ind] = e;\n\t}\n\n\t//find sources;\n\tstd::set<int> sources;\n\tfor (unsigned i = 0; i<crestEdgesVisible.size(); i++)\n\t{\n\t\tif (!crestEdgesVisible[i])\n\t\t\tcontinue;\n\n\t\tunsigned faceID = crestEdges[i][2];\n\t\tif (faceID>myMesh->getFaces().size())\n\t\t{\n\t\t\tcontinue; // crest line data is not alway clean\n\t\t}\n\t\tsources.insert(faceID);\n\t}\n\tfor (auto f = userSketches.begin(); f != userSketches.end(); f++)\n\t{\n\t\tsources.insert(f->fid);\n\t}\n\n\tws.distanceToFeature_ShortestPath(versArray, edgesArray, sources, ws.distanceToFeature);\n\n\t//local extrema, and growing\n\tstd::vector<std::set<unsigned> > neighbours(myMesh->getFaces().size());\n\tfor (auto f = myMesh->getFaces().begin(); f != myMesh->getFaces().end(); f++)\n\t{\n\t\tauto& fs = neighbours[f->id()];\n\t\tfor (unsigned j = 0; j < 3; j++)\n\t\t{\n\t\t\tfor (auto e = 0; e < f->vertex_iter(j)->edge_iter().size(); e++)\n\t\t\t{\n\t\t\t\tfs.insert(f->vertex_iter(j)->edge_iter()[e]->face_iter(0)->id());\n\t\t\t\tif (f->vertex_iter(j)->edge_iter()[e]->manifold())\n\t\t\t\t\tfs.insert(f->vertex_iter(j)->edge_iter()[e]->face_iter(1)->id());\n\t\t\t}\n\t\t}\n\t}\n\n// \tstd::vector<bool> isExtrema(neighbours.size(), true);\n// \tfor (unsigned i = 0; i < neighbours.size(); i++)\n// \t{\n// \t\tfor (auto j = neighbours[i].begin(); j != neighbours[i].end(); j++)\n// \t\t{\n// \t\t\tif(ws.distanceToFeature[i] > ws.distanceToFeature[*j])\n// \t\t\t{\n// \t\t\t\tisExtrema[i] = false;\n// \t\t\t}\n// \t\t}\n// \t}\n\n\tstd::vector<unsigned> watershedLabels;\n\tws.grow2(mg,ws.distanceToFeature, neighbours, watershedLabels);\n\n\tclock_t totalTime = clock() - tstr;\n\tcout << \"Watershed Segmentation Use \" << totalTime / 1000 << \"sec\" << totalTime % 1000 << \"mm\" << endl;\n\n\tstd::vector<double> weights;\n\tgetWeights(edgeWeightParameter, weights);\n\n\tdouble cutCost = 0;\n\tfor (auto e = myMesh->getEdges().begin(); e != myMesh->getEdges().end(); e++)\n\t{\n\t\tif (!e->manifold()) continue;\n\n\t\tif (watershedLabels[e->face_iter(0)->id()] == UINT_MAX && watershedLabels[e->face_iter(1)->id()] == UINT_MAX)\n\t\t{\n\t\t\tcutCost += weights[e->id()];\n\t\t\tgraphFeature.ef[e->id()].isCut = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgraphFeature.ef[e->id()].isCut = false;\n\t\t}\n\t}\n\tcout << \"Cost:\" << cutCost << endl;\n\n\tunsigned vNum = myMesh->getVertices().size();\n\tunsigned eNum = myMesh->getEdges().size();\n\tvertexLabel.clear(); vertexLabel.resize(vNum);\n\tsegNumber = 0;\n\tstd::vector<bool> visitedVer(vNum, false);\n\tstd::vector<bool> visitedEdge(eNum, false);\n\tfor (int i = 0; i < vNum; i++)\n\t{\n\t\tif (visitedVer[i] == true) continue;\n\n\t\tstd::vector<int> frontVer(1, i);\n\t\t//propagates vertex with same label, and group them into a subgraph\n\t\twhile (!frontVer.empty())\n\t\t{\n\t\t\tint fv = frontVer.back(); frontVer.pop_back();\n\t\t\tvertexLabel[fv] = segNumber;\n\n\t\t\tauto v = mg.vs[fv].vadjs.begin();\n\t\t\tauto e = mg.vs[fv].eadjs.begin();\n\t\t\tfor (; v != mg.vs[fv].vadjs.end(); v++, e++)\n\t\t\t{\n\t\t\t\tif (graphFeature.ef[*e].isCut || visitedEdge[*e] == true)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvisitedEdge[*e] = true;\n\n\t\t\t\tif (visitedVer[*v] == true)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvisitedVer[*v] = true;\n\n\t\t\t\tfrontVer.push_back(*v);\n\t\t\t}\n\t\t}\n\t\tsegNumber++;\n\t}\n\n\tcout << endl << \"cluster number:\" << segNumber << endl;\n\n\tvertexLabelBeforeMerge = vertexLabel;\n}\n////////////////////MERGING//////////////////////////////////\nvoid MeshSegment::LMP_Merging(const std::vector<unsigned>& vertexLabel, std::vector< std::list< std::list< MGTriple > >::iterator >&pCIter,\n\tunsigned labelId, std::vector<unsigned>& newLabels)\n{\n\tunsigned numE = 0;\n\tunsigned numV = labelId;\n\tstd::vector<std::pair<std::pair<unsigned, unsigned>, double> > edges;\n\tfor (int i = 0; i < pCIter.size(); i++){\n\t\tfor (auto tpc = pCIter[i]->begin(); tpc != pCIter[i]->end(); tpc++)\n\t\t{\n\t\t\tif (i != tpc->j)\n\t\t\t{\n\t\t\t\tnumE++;\n\t\t\t\tedges.push_back(std::pair<std::pair<unsigned, unsigned>, double>(std::pair<unsigned, unsigned>(i, tpc->j), tpc->val));\n\t\t\t}\n\t\t}\n\t}\n\tcout << \"number of edges:\" << numE << \"  number of vertices:\" << numV << endl;\n\n\tandres::graph::Graph<> graph;\n\tgraph.insertVertices(numV);\n\tstd::vector<double> weights(numE);\n\tfor (int i = 0; i < numE; i++)\n\t{\n\t\tgraph.insertEdge(edges[i].first.first, edges[i].first.second);\n\t\tweights[i] = edges[i].second;\n\t}\n\n\tstd::vector<char> edge_labels(graph.numberOfEdges(), 1);\n\tandres::graph::multicut_lifted::greedyAdditiveEdgeContraction(graph, graph, weights, edge_labels);\n\n\tstd::vector<char> out_labels(graph.numberOfEdges(), 1);\n\tandres::graph::multicut_lifted::kernighanLin(graph, graph, weights, edge_labels, out_labels);\n\n\tstd::vector<unsigned> res(numV);\n\tstd::vector<bool> visitedVer(numV, false);\n\tstd::vector<bool> visitedEdge(numE, false);\n\tunsigned multiCutNum = 0;\n\tfor (int i = 0; i < numV; i++)\n\t{\n\t\tif (visitedVer[i] == true) continue;\n\n\t\tstd::vector<int> frontVer(1, i);\n\t\t//propagates vertex with same label, and group them into a subgraph\n\t\twhile (!frontVer.empty())\n\t\t{\n\t\t\tint fv = frontVer.back(); frontVer.pop_back();\n\t\t\tres[fv] = multiCutNum;\n\t\t\t\n\t\t\t\n\t\t\tfor (auto p = graph.adjacenciesToVertexBegin(fv); p != graph.adjacenciesToVertexEnd(fv); p++)\n\t\t\t{\n\t\t\t\tauto eid = p->edge();\n\t\t\t\tif (out_labels[eid] || visitedEdge[eid] == true)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvisitedEdge[eid] = true;\n\n\t\t\t\tif (visitedVer[p->vertex()] == true)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvisitedVer[p->vertex()] = true;\n\n\t\t\t\tfrontVer.push_back(p->vertex());\n\t\t\t}\n\t\t}\n\t\tmultiCutNum++;\n\t}\n\t//////////////////////////////////////////////////////////////////////////\n\tnewLabels.clear(); newLabels.resize(vertexLabel.size());\n\tfor (size_t i = 0; i < vertexLabel.size(); i++)\n\t{\n\t\tnewLabels[i] = res[vertexLabel[i]];\n\t}\n}\nvoid MeshSegment::Mitani_Watershed_Dual_Partial(std::vector<unsigned>& fs)\n{\n\tif (fs.empty())return;\n\n\tstd::set<int> patchLabels;\n\tfor (int i = 0; i < fs.size(); i++)\n\t{\n\t\tauto&f = myMesh->getFIter()[fs[i]];\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tpatchLabels.insert(vertexLabel[f->vertex_iter(j)->id()]);\n\t\t}\n\t}\n\n\tstd::vector<bool> faceInPatches(myMesh->getFaces().size(), true);\n\tsubgraphVers.clear(); subgraphVers.resize(myMesh->getVertices().size(), true);\n\tunsigned numV = faceInPatches.size();\n\tfor (auto f = myMesh->getFaces().begin(); f != myMesh->getFaces().end(); f++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tif (std::find(patchLabels.begin(), patchLabels.end(), vertexLabel[f->vertex_iter(j)->id()]) == patchLabels.end())\n\t\t\t{\n\t\t\t\tfaceInPatches[f->id()] = false;\n\t\t\t\tsubgraphVers[f->vertex_iter(j)->id()] = false;\n\t\t\t}\n\t\t}\n\t\tif (faceInPatches[f->id()] == false) numV--;\n\t}\n\n\tMGraph pg;//partial graph;\n\tpg.vNum = numV;\n\tpg.vs.clear(); pg.vs.resize(pg.vNum);\n\n\tstd::map<unsigned, unsigned> localIndToGlobalInd;\n\tstd::map<unsigned, unsigned> globalIndToLocalInd;\n\tunsigned ind = 0;\n\tfor (auto f = myMesh->getFaces().begin(); f != myMesh->getFaces().end(); f++)\n\t{\n\t\tif (faceInPatches[f->id()])\n\t\t{\n\t\t\tpg.vs[ind].id = ind;\n\t\t\tpg.vs[ind].coord = f->center_point();\n\t\t\tlocalIndToGlobalInd[ind] = f->id();\n\t\t\tglobalIndToLocalInd[f->id()] = ind;\n\t\t\tind++;\n\t\t}\n\t}\n\n\tpg.es.clear();\n\tind = 0;\n\tfor (auto e = myMesh->getEdges().begin(); e != myMesh->getEdges().end(); e++)\n\t{\n\t\tif (!e->manifold()) continue;\n\n\t\tint f1 = e->face_iter(0)->id();\n\t\tint f2 = e->face_iter(1)->id();\n\t\tif (!faceInPatches[f1] || !faceInPatches[f2]) continue;\n\n\t\tf1 = globalIndToLocalInd[f1];\n\t\tf2 = globalIndToLocalInd[f2];\n\n\t\tpg.vs[f1].vadjs.push_back(f2);\n\t\tpg.vs[f2].vadjs.push_back(f1);\n\n\t\tMGraph::Edge de;\n\t\tde.w = e->cost();\n\t\tde.n1 = f1;\n\t\tde.n2 = f2;\n\t\tpg.es.push_back(de);\n\n\t\tpg.vs[f1].eadjs.push_back(ind);\n\t\tpg.vs[f2].eadjs.push_back(ind);\n\t\tind++;\n\t}\n\tpg.eNum = pg.es.size();\n\n\t//find sources;\n\tstd::set<int> sources;\n\t{\n\t\tfor (unsigned i = 0; i < crestEdgesVisible.size(); i++)\n\t\t{\n\t\t\tif (!crestEdgesVisible[i])\n\t\t\t\tcontinue;\n\n\t\t\tunsigned faceID = crestEdges[i][2];\n\t\t\tif (faceID > myMesh->getFaces().size())\n\t\t\t{\n\t\t\t\tcontinue; // crest line data is not alway clean\n\t\t\t}\n\t\t\tif (!faceInPatches[faceID]) continue;\n\n\t\t\tsources.insert(globalIndToLocalInd[faceID]);\n\t\t}\n\t\tif (!graphCutLocally)\n\t\t{\n\t\t\tfor (unsigned i = 0; i < userSketches.size(); i++)\n\t\t\t{\n\t\t\t\tif (!faceInPatches[userSketches[i].fid])continue;\n\n\t\t\t\tsources.insert(globalIndToLocalInd[userSketches[i].fid]);\n\t\t\t}\n\t\t\tfor (unsigned i = 0; i < fs.size(); i++)\n\t\t\t{\n\t\t\t\tsources.insert(globalIndToLocalInd[fs[i]]);\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::vector<double> distanceToFeature;\n\tws.distanceToFeature_ShortestPath(pg, sources, distanceToFeature);\n\n\t//localhood\n\tstd::vector<std::set<unsigned> > neighbours(pg.vNum);\n\tfor (auto f = myMesh->getFaces().begin(); f != myMesh->getFaces().end(); f++)\n\t{\n\t\tif (faceInPatches[f->id()] == false)continue;\n\n\t\tauto& fs = neighbours[globalIndToLocalInd[f->id()]];\n\t\tfor (unsigned j = 0; j < 3; j++)\n\t\t{\n\t\t\tfor (auto e = 0; e < f->vertex_iter(j)->edge_iter().size(); e++)\n\t\t\t{\n\t\t\t\tunsigned tid = f->vertex_iter(j)->edge_iter()[e]->face_iter(0)->id();\n\t\t\t\tif (faceInPatches[tid])\n\t\t\t\t\tfs.insert(globalIndToLocalInd[tid]);\n\t\t\t\tif (f->vertex_iter(j)->edge_iter()[e]->manifold())\n\t\t\t\t{\n\t\t\t\t\ttid = f->vertex_iter(j)->edge_iter()[e]->face_iter(1)->id();\n\t\t\t\t\tif (faceInPatches[tid])\n\t\t\t\t\t\tfs.insert(globalIndToLocalInd[tid]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::vector<unsigned> watershedLabels;\n\tws.grow2(pg, distanceToFeature, neighbours, watershedLabels);\n\n\tdouble cutCost = 0;\n\tfor (auto e = myMesh->getEdges().begin(); e != myMesh->getEdges().end(); e++)\n\t{\n\t\tif (!e->manifold()) continue;\n\n\t\tif (vertexLabel[e->vertex_iter(0)->id()] != vertexLabel[e->vertex_iter(1)->id()])\n\t\t\tgraphFeature.ef[e->id()].isCut = true;\n\t\telse\n\t\t\tgraphFeature.ef[e->id()].isCut = false;\n\n\t\tint f1 = e->face_iter(0)->id();\n\t\tint f2 = e->face_iter(1)->id();\n\n\t\tif (!faceInPatches[f1] && !faceInPatches[f2])\n\t\t\tcontinue;\n\t\telse if (faceInPatches[f1] && !faceInPatches[f2] && watershedLabels[globalIndToLocalInd[f1]] == UINT_MAX)\n\t\t{\n\t\t\tgraphFeature.ef[e->id()].isCut = true;\n\t\t\tcontinue;\n\t\t}\n\t\telse if (!faceInPatches[f1] && faceInPatches[f2] && watershedLabels[globalIndToLocalInd[f2]] == UINT_MAX)\n\t\t{\n\t\t\tgraphFeature.ef[e->id()].isCut = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (watershedLabels[globalIndToLocalInd[f1]] == UINT_MAX && watershedLabels[globalIndToLocalInd[f2]] == UINT_MAX)\n\t\t{\n\t\t\tgraphFeature.ef[e->id()].isCut = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgraphFeature.ef[e->id()].isCut = false;\n\t\t}\n\t}\n\n\tunsigned vNum = myMesh->getVertices().size();\n\tunsigned eNum = myMesh->getEdges().size();\n\tvertexLabel.clear(); vertexLabel.resize(vNum);\n\tsegNumber = 0;\n\tstd::vector<bool> visitedVer(vNum, false);\n\tstd::vector<bool> visitedEdge(eNum, false);\n\tfor (int i = 0; i < vNum; i++)\n\t{\n\t\tif (visitedVer[i] == true) continue;\n\n\t\tstd::vector<int> frontVer(1, i);\n\t\t//propagates vertex with same label, and group them into a subgraph\n\t\twhile (!frontVer.empty())\n\t\t{\n\t\t\tint fv = frontVer.back(); frontVer.pop_back();\n\t\t\tvertexLabel[fv] = segNumber;\n\n\t\t\tauto v = mg.vs[fv].vadjs.begin();\n\t\t\tauto e = mg.vs[fv].eadjs.begin();\n\t\t\tfor (; v != mg.vs[fv].vadjs.end(); v++, e++)\n\t\t\t{\n\t\t\t\tif (graphFeature.ef[*e].isCut || visitedEdge[*e] == true)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvisitedEdge[*e] = true;\n\n\t\t\t\tif (visitedVer[*v] == true)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvisitedVer[*v] = true;\n\n\t\t\t\tfrontVer.push_back(*v);\n\t\t\t}\n\t\t}\n\t\tsegNumber++;\n\t}\n\n\tcout << \"cluster number:\" << segNumber << endl;\n\n\tvertexLabelBeforeMerge = vertexLabel;\n\n\t//update initial cut graph;\n\tif (false)\n\t{\n\t\tstd::vector<bool> isCut(myMesh->getEdges().size());\n\t\tfor (auto e = myMesh->getEdges().begin(); e != myMesh->getEdges().end(); e++)\n\t\t{\n\t\t\tif (!e->manifold()) continue;\n\n\t\t\tif (vertexLabelInit[e->vertex_iter(0)->id()] != vertexLabelInit[e->vertex_iter(1)->id()])\n\t\t\t\tisCut[e->id()] = true;\n\t\t\telse\n\t\t\t\tisCut[e->id()] = false;\n\n\t\t\tint f1 = e->face_iter(0)->id();\n\t\t\tint f2 = e->face_iter(1)->id();\n\n\t\t\tif (!faceInPatches[f1] && !faceInPatches[f2])\n\t\t\t\tcontinue;\n\t\t\telse if (faceInPatches[f1] && !faceInPatches[f2] && watershedLabels[globalIndToLocalInd[f1]] == UINT_MAX)\n\t\t\t{\n\t\t\t\tisCut[e->id()] = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse if (!faceInPatches[f1] && faceInPatches[f2] && watershedLabels[globalIndToLocalInd[f2]] == UINT_MAX)\n\t\t\t{\n\t\t\t\tisCut[e->id()] = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (watershedLabels[globalIndToLocalInd[f1]] == UINT_MAX && watershedLabels[globalIndToLocalInd[f2]] == UINT_MAX)\n\t\t\t{\n\t\t\t\tisCut[e->id()] = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tisCut[e->id()] = false;\n\t\t\t}\n\t\t}\n\t\tvertexLabelInit.clear(); vertexLabelInit.resize(vNum);\n\t\tunsigned initSegNumber = 0;\n\t\tvisitedVer.clear(); visitedVer.resize(vNum, false);\n\t\tvisitedEdge.clear(); visitedEdge.resize(eNum, false);\n\t\tfor (int i = 0; i < vNum; i++)\n\t\t{\n\t\t\tif (visitedVer[i] == true) continue;\n\n\t\t\tstd::vector<int> frontVer(1, i);\n\t\t\t//propagates vertex with same label, and group them into a subgraph\n\t\t\twhile (!frontVer.empty())\n\t\t\t{\n\t\t\t\tint fv = frontVer.back(); frontVer.pop_back();\n\t\t\t\tvertexLabelInit[fv] = initSegNumber;\n\n\t\t\t\tauto v = mg.vs[fv].vadjs.begin();\n\t\t\t\tauto e = mg.vs[fv].eadjs.begin();\n\t\t\t\tfor (; v != mg.vs[fv].vadjs.end(); v++, e++)\n\t\t\t\t{\n\t\t\t\t\tif (isCut[*e] || visitedEdge[*e] == true)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tvisitedEdge[*e] = true;\n\n\t\t\t\t\tif (visitedVer[*v] == true)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tvisitedVer[*v] = true;\n\n\t\t\t\t\tfrontVer.push_back(*v);\n\t\t\t\t}\n\t\t\t}\n\t\t\tinitSegNumber++;\n\t\t}\n\t}\n\n\t//for debugging\n\tws.distanceToFeature.clear();\n\tfor (int i = 0; i < myMesh->getFaces().size(); i++)\n\t{\n\t\tif (globalIndToLocalInd.find(i) == globalIndToLocalInd.end())\n\t\t\tws.distanceToFeature.push_back(0);\n\t\telse\n\t\t\tws.distanceToFeature.push_back(distanceToFeature[globalIndToLocalInd[i]]);\n\t}\n}\nvoid MeshSegment::LMP_Partitioning()\n{\n\tclock_t tstr = clock();\n\n\tunsigned vNum = myMesh->getVertices().size();\n\tunsigned eNum = myMesh->getEdges().size();\n\n\tandres::graph::Graph<> graph;\n\tgraph.insertVertices(vNum);\n\tfor (auto e = myMesh->getEdges().begin(); e != myMesh->getEdges().end(); e++)\n\t{\n\t\tgraph.insertEdge(e->vertex_iter(0)->id(), e->vertex_iter(1)->id());\n\t}\n\tstd::vector<double> weights;\n\tgetWeights(edgeWeightParameter, weights);\n\n\tstd::vector<char> edge_labels(graph.numberOfEdges(), 1);\n\t//andres::graph::multicut_lifted::greedyAdditiveEdgeContraction(graph, graph, weights, edge_labels);\n\n\tstd::vector<char> out_labels(graph.numberOfEdges(), 1);\n\t//andres::graph::multicut_lifted::kernighanLin(graph, graph, weights, edge_labels, out_labels);\n\n\n\tauto& multiCutLabels = vertexLabel;\n\tauto& multiCutNum = segNumber;\n\tmultiCutLabels.clear(); multiCutLabels.resize(myMesh->getVertices().size());\n\tmultiCutNum = 0;\n\tstd::vector<bool> visitedVer(vNum, false);\n\tstd::vector<bool> visitedEdge(eNum, false);\n\tfor (int i = 0; i < vNum; i++)\n\t{\n\t\tif (visitedVer[i] == true) continue;\n\n\t\tstd::vector<int> frontVer(1, i);\n\t\t//propagates vertex with same label, and group them into a subgraph\n\t\twhile (!frontVer.empty())\n\t\t{\n\t\t\tint fv = frontVer.back(); frontVer.pop_back();\n\t\t\tmultiCutLabels[fv] = multiCutNum;\n\n\t\t\tauto v = mg.vs[fv].vadjs.begin();\n\t\t\tauto e = mg.vs[fv].eadjs.begin();\n\t\t\tfor (; v != mg.vs[fv].vadjs.end(); v++, e++)\n\t\t\t{\n\t\t\t\tif (out_labels[*e] || visitedEdge[*e] == true)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvisitedEdge[*e] = true;\n\n\t\t\t\tif (visitedVer[*v] == true)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvisitedVer[*v] = true;\n\n\t\t\t\tfrontVer.push_back(*v);\n\t\t\t}\n\t\t}\n\t\tmultiCutNum++;\n\t}\n\n\tclock_t tinit = clock() - tstr;\n\tcout << endl << \"LMP takes:\" << tinit / 1000 << \"sec\" << tinit % 1000 << \"mm to generate \" << multiCutNum << \" patches.\" << endl;\n\t//////////////////////////////////////////////////////////////////////////\n\n\tvertexLabelBeforeMerge = vertexLabel;\n\n\tdouble cutCost = 0;\n\tfor (int i = 0; i < eNum; i++)\n\t{\n\t\tif (out_labels[i])\n\t\t{\n\t\t\tcutCost += weights[i];\n\t\t\tgraphFeature.ef[i].isCut = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tgraphFeature.ef[i].isCut = false;\n\t\t}\n\t}\n\tcout << \"Cost:\" << cutCost << endl;\n}", "meta": {"hexsha": "6615ccdc9fe15925c34a328cc4f003dc4936d056", "size": 38265, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CurveNetMaker/core/Algorithms.cpp", "max_stars_repo_name": "yixin26/Mesh-Segmentation", "max_stars_repo_head_hexsha": "4c0a775d73970710ff5108aa47b1be8455231285", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2017-11-21T13:55:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T07:57:28.000Z", "max_issues_repo_path": "CurveNetMaker/core/Algorithms.cpp", "max_issues_repo_name": "yixin26/CurveNet-Mesh", "max_issues_repo_head_hexsha": "4c0a775d73970710ff5108aa47b1be8455231285", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-03-02T22:36:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T10:43:38.000Z", "max_forks_repo_path": "CurveNetMaker/core/Algorithms.cpp", "max_forks_repo_name": "yixin26/CurveNet-Mesh", "max_forks_repo_head_hexsha": "4c0a775d73970710ff5108aa47b1be8455231285", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-01-15T08:57:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T12:03:57.000Z", "avg_line_length": 28.3444444444, "max_line_length": 201, "alphanum_fraction": 0.6218476414, "num_tokens": 12050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.40456272530158555}}
{"text": "// Copyright 2020 the Autoware Foundation\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Co-developed by Tier IV, Inc. and Apex.AI, Inc.\n\n#ifndef NDT__UTILS_HPP_\n#define NDT__UTILS_HPP_\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <geometry_msgs/msg/transform.hpp>\n#include <geometry_msgs/msg/pose.hpp>\n#include <Eigen/Eigenvalues>\n#include <limits>\n\nnamespace autoware\n{\nnamespace localization\n{\nnamespace ndt\n{\n\n/// This function will check if the covariance is valid based on its eigenvalues. If the covariance\n/// is valid, eigen values smaller than a fraction of the biggest eigen value will be capped to the\n/// threshold. Covariance then will be reconstructed from the modified set of eigen values and\n/// vectors. This should result in increased numerical stability as stated in [Magnusson 2009].\n/// If the covariance is invalid, it will not be updated and false will be returned.\n/// \\tparam Derived Deduced Eigen Matrix type.\n/// \\param covariance [in, out] Covariance matrix to get stabilized.\n/// \\param scaling_factor [in] The ratio between the max. eigen value and the minimum\n/// allowed eigenvalue. Default value is 0.01 as suggested in [Magnusson 2009], page 60.\n/// \\return True if the covariance matrix is valid.\ntemplate<typename Derived>\nbool try_stabilize_covariance(\n  Eigen::MatrixBase<Derived> & covariance,\n  typename Derived::PlainMatrix::Scalar scaling_factor = 0.01)\n{\n  using CovMatrixT = typename Derived::PlainMatrix;\n  using ScalarT = typename CovMatrixT::Scalar;\n  using IndexT = typename CovMatrixT::Index;\n  constexpr auto TOL = std::numeric_limits<ScalarT>::epsilon();\n  Eigen::SelfAdjointEigenSolver<CovMatrixT> solver;\n  solver.compute(covariance);\n\n  CovMatrixT evecs = solver.eigenvectors();\n  typename decltype(solver)::RealVectorType evals = solver.eigenvalues();\n  // Cap the minimum eigen values to scale times the largest eigen value.\n  const ScalarT max_e_val = *std::max_element(evals.data(), evals.data() + evals.size());\n  const ScalarT min_e_val = max_e_val * scaling_factor;\n  if (min_e_val < TOL) {\n    return false;\n  }\n  auto stabilized = false;\n  for (auto i = IndexT{0}; i < evals.size(); ++i) {\n    ScalarT & e_val = evals(i);\n    if (e_val < TOL) {\n      // Covariance is not full rank.\n      return false;\n    }\n    if (e_val < min_e_val) {\n      e_val = min_e_val;\n      stabilized = true;\n    }\n  }\n  if (stabilized) {\n    covariance = evecs * evals.asDiagonal() * evecs.inverse();\n  }\n  return true;\n}\n\ntemplate<typename T>\nusing EigenPose = Eigen::Matrix<T, 6U, 1U>;\ntemplate<typename T>\nusing EigenTransform = Eigen::Transform<T, 3, Eigen::Affine, Eigen::ColMajor>;\nusing RosTransform = geometry_msgs::msg::Transform;\nusing RosPose = geometry_msgs::msg::Pose;\nnamespace transform_adapters\n{\n/// Template function to convert a 6D pose to a transformation matrix.\n/// This function should be specialized and implemented for the supported types.\n/// \\tparam PoseT Pose type.\n/// \\tparam TransformT Transform type.\n/// \\param[in] pose pose to convert\n/// \\param[out] transform resulting transform\ntemplate<typename PoseT, typename TransformT>\nvoid pose_to_transform(const PoseT & pose, TransformT & transform);\n\n/// Template function to convert a 6D pose to a transformation matrix.\n/// This function should be specialized and implemented for the supported types.\n/// \\tparam PoseT Pose type.\n/// \\tparam TransformT Transform type.\n/// \\param[in] transform resulting transform\n/// \\param[out] pose pose to convert\ntemplate<typename PoseT, typename TransformT>\nvoid transform_to_pose(const TransformT & transform, PoseT & pose);\n\n\ntemplate<typename T>\nvoid pose_to_transform(\n  const EigenPose<T> & pose,\n  EigenTransform<T> & transform)\n{\n  static_assert(std::is_floating_point<T>::value, \"Eigen transform should use floating points\");\n  transform.setIdentity();\n  transform.translation() = pose.head(3);\n  transform.rotate(Eigen::AngleAxis<T>(pose(3), Eigen::Vector3d::UnitX()));\n  transform.rotate(Eigen::AngleAxis<T>(pose(4), Eigen::Vector3d::UnitY()));\n  transform.rotate(Eigen::AngleAxis<T>(pose(5), Eigen::Vector3d::UnitZ()));\n}\n\n/// Specialization to convert from the eigen pose to the ros transform type.\n/// \\tparam T Eigen scalar type\ntemplate<typename T>\nvoid pose_to_transform(\n  const EigenPose<T> & pose,\n  RosTransform & transform)\n{\n  static_assert(std::is_floating_point<T>::value, \"Eigen pose should use floating points\");\n  Eigen::Quaternion<T> eig_rot{Eigen::Quaternion<T>{}.setIdentity()};\n  eig_rot.setIdentity();\n  eig_rot =\n    Eigen::AngleAxis<T>(pose(3), Eigen::Matrix<T, 3, 1>::UnitX()) *\n    Eigen::AngleAxis<T>(pose(4), Eigen::Matrix<T, 3, 1>::UnitY()) *\n    Eigen::AngleAxis<T>(pose(5), Eigen::Matrix<T, 3, 1>::UnitZ());\n\n  decltype(RosTransform::translation) trans;\n  decltype(RosTransform::rotation) rot;\n\n  trans.set__x(pose(0)).set__y(pose(1)).set__z(pose(2));\n  transform.set__translation(trans);\n\n  rot.set__x(eig_rot.x()).\n  set__y(eig_rot.y()).\n  set__z(eig_rot.z()).\n  set__w(eig_rot.w());\n  transform.set__rotation(rot);\n}\n\n/// Specialization to convert from the eigen pose to the ros pose type.\n/// `pose_to_transform` template is used as conversion to `RosPose`\n/// is identical to conversion to `RosTransform`\n/// \\tparam T Eigen scalar type\ntemplate<typename T>\nvoid pose_to_transform(\n  const EigenPose<T> & pose,\n  RosPose & ros_pose)\n{\n  static_assert(std::is_floating_point<T>::value, \"Eigen pose should use floating points\");\n  Eigen::Quaternion<T> eig_rot{Eigen::Quaternion<T>{}.setIdentity()};\n  eig_rot =\n    Eigen::AngleAxis<T>(pose(3), Eigen::Matrix<T, 3, 1>::UnitX()) *\n    Eigen::AngleAxis<T>(pose(4), Eigen::Matrix<T, 3, 1>::UnitY()) *\n    Eigen::AngleAxis<T>(pose(5), Eigen::Matrix<T, 3, 1>::UnitZ());\n\n  decltype(RosPose::position) trans;\n  decltype(RosTransform::rotation) rot;\n\n  trans.set__x(pose(0)).set__y(pose(1)).set__z(pose(2));\n  ros_pose.set__position(trans);\n\n  rot.set__x(eig_rot.x()).\n  set__y(eig_rot.y()).\n  set__z(eig_rot.z()).\n  set__w(eig_rot.w());\n  ros_pose.set__orientation(rot);\n}\n\n/// Specialization to convert from the ros pose type to an eigen one.\n/// \\tparam T Eigen scalar type\ntemplate<typename T>\nvoid transform_to_pose(const RosTransform & transform, EigenPose<T> & pose)\n{\n  static_assert(std::is_floating_point<T>::value, \"Eigen pose should use floating points\");\n  const auto & ros_rot = transform.rotation;\n  const auto & ros_trans = transform.translation;\n  Eigen::Quaternion<T> eig_rot{ros_rot.w, ros_rot.x, ros_rot.y, ros_rot.z};\n  pose(0) = ros_trans.x;\n  pose(1) = ros_trans.y;\n  pose(2) = ros_trans.z;\n\n  const auto rot = eig_rot.matrix().eulerAngles(0, 1, 2);\n  pose(3) = rot(0);\n  pose(4) = rot(1);\n  pose(5) = rot(2);\n}\n\n/// Specialization to convert from the ros pose type to an eigen one.\n/// `transform_to_pose` template is used as conversion from `RosPose`\n/// is identical to conversion from `RosTransform`\n/// \\tparam T Eigen scalar type\ntemplate<typename T>\nvoid transform_to_pose(const RosPose & ros_pose, EigenPose<T> & pose)\n{\n  static_assert(std::is_floating_point<T>::value, \"Eigen pose should use floating points\");\n  const auto & ros_rot = ros_pose.orientation;\n  const auto & ros_trans = ros_pose.position;\n  Eigen::Quaternion<T> eig_rot{ros_rot.w, ros_rot.x, ros_rot.y, ros_rot.z};\n  pose(0) = ros_trans.x;\n  pose(1) = ros_trans.y;\n  pose(2) = ros_trans.z;\n\n  const auto rot = eig_rot.matrix().eulerAngles(0, 1, 2);\n  pose(3) = rot(0);\n  pose(4) = rot(1);\n  pose(5) = rot(2);\n}\n\n}  // namespace transform_adapters\n}  // namespace ndt\n}  // namespace localization\n}  // namespace autoware\n\n#endif  // NDT__UTILS_HPP_\n", "meta": {"hexsha": "0d4ab5c709532ff637b7bc7ca0c16db316ede6a6", "size": 8127, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/localization/ndt/include/ndt/utils.hpp", "max_stars_repo_name": "fanyu2021/fyAutowareAuto", "max_stars_repo_head_hexsha": "073661c0634de671ff01bda8a316a5ce10c96ca9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-04T00:38:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T05:48:58.000Z", "max_issues_repo_path": "src/localization/ndt/include/ndt/utils.hpp", "max_issues_repo_name": "fanyu2021/fyAutowareAuto", "max_issues_repo_head_hexsha": "073661c0634de671ff01bda8a316a5ce10c96ca9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/localization/ndt/include/ndt/utils.hpp", "max_forks_repo_name": "fanyu2021/fyAutowareAuto", "max_forks_repo_head_hexsha": "073661c0634de671ff01bda8a316a5ce10c96ca9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-04T00:38:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-04T00:38:56.000Z", "avg_line_length": 36.12, "max_line_length": 99, "alphanum_fraction": 0.720438046, "num_tokens": 2150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334525, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.40456272530158544}}
{"text": "#include \"math/SparseMatrix.h\"\n\n/// Disable some warning to compile Eigen with gcc 7.1\n#ifdef SPH_GCC\n#if __GNUC__ >= 7\n#pragma GCC diagnostic ignored \"-Wint-in-bool-context\"\n#pragma GCC diagnostic ignored \"-Wduplicated-branches\"\n#endif\n#endif\n\n#ifdef SPH_USE_EIGEN\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/SparseLU>\n#endif\n\nNAMESPACE_SPH_BEGIN\n\n#ifdef SPH_USE_EIGEN\n\nclass SparseMatrix::Impl {\nprivate:\n    Eigen::SparseMatrix<Float> matrix;\n    Array<Eigen::Triplet<Float>> triplets;\n\n    using SparseVector = Eigen::Matrix<Float, Eigen::Dynamic, 1>;\n\npublic:\n    Impl(const Size rows, const Size cols)\n        : matrix(rows, cols) {}\n\n    void insert(const Size i, const Size j, const Float value) {\n        SPH_ASSERT(i < matrix.innerSize() && j < matrix.innerSize(), i, j);\n        triplets.push(Eigen::Triplet<Float>(i, j, value));\n    }\n\n    Expected<Array<Float>> solve(const Array<Float>& values,\n        const SparseMatrix::Solver solver,\n        const Float tolerance) {\n        SPH_ASSERT(values.size() == matrix.innerSize());\n        // this is takes straigh from Eigen documentation\n        // (http://eigen.tuxfamily.org/dox-devel/group__TopicSparseSystems.html)\n\n        matrix.setFromTriplets(triplets.begin(), triplets.end());\n        /// \\todo experiment with different solvers\n\n        SparseVector b;\n        b.resize(values.size());\n        for (Size i = 0; i < values.size(); ++i) {\n            b(i) = values[i];\n        }\n\n        Expected<SparseVector> a;\n        switch (solver) {\n        case SparseMatrix::Solver::LU: {\n            Eigen::SparseLU<Eigen::SparseMatrix<Float>, Eigen::COLAMDOrdering<int>> solver;\n            a = solveImpl(solver, b);\n            break;\n        }\n        case SparseMatrix::Solver::CG: {\n#ifdef SPH_DEBUG\n            // check that the matrix is symmetric\n            {\n                const Size n = matrix.innerSize();\n                for (Size i = 0; i < n; ++i) {\n                    for (Size j = i; j < n; ++j) {\n                        const Float mij = matrix.coeff(i, j);\n                        const Float mji = matrix.coeff(j, i);\n                        SPH_ASSERT(almostEqual(mij, mji), mij, mji);\n                    }\n                }\n            }\n#endif\n            Eigen::ConjugateGradient<Eigen::SparseMatrix<Float>, Eigen::Lower | Eigen::Upper> solver;\n            if (tolerance > 0._f) {\n                solver.setTolerance(tolerance);\n            }\n            a = solveImpl(solver, b);\n            break;\n        }\n        case SparseMatrix::Solver::LSCG: {\n            Eigen::LeastSquaresConjugateGradient<Eigen::SparseMatrix<Float>> solver;\n            if (tolerance > 0._f) {\n                solver.setTolerance(tolerance);\n            }\n            a = solveImpl(solver, b);\n            break;\n        }\n        case SparseMatrix::Solver::BICGSTAB: {\n            Eigen::BiCGSTAB<Eigen::SparseMatrix<Float>> solver;\n            if (tolerance > 0._f) {\n                solver.setTolerance(tolerance);\n            }\n            a = solveImpl(solver, b);\n            break;\n        }\n        default:\n            NOT_IMPLEMENTED;\n        }\n\n        if (!a) {\n            return makeUnexpected<Array<Float>>(a.error());\n        }\n        Array<Float> result;\n        result.resize(matrix.outerSize());\n        for (Size i = 0; i < result.size(); ++i) {\n            result[i] = a.value()(i);\n        }\n        return Expected<Array<Float>>(std::move(result));\n    }\n\nprivate:\n    template <typename TSolver>\n    Expected<SparseVector> solveImpl(TSolver& solver, const SparseVector& b) {\n        solver.compute(matrix);\n        if (solver.info() != Eigen::Success) {\n            return makeUnexpected<SparseVector>(\"Decomposition of matrix failed\");\n        }\n        SparseVector a;\n        a = solver.solve(b);\n        if (solver.info() != Eigen::Success) {\n            return makeUnexpected<SparseVector>(\"Equations cannot be solved\");\n        }\n        return a;\n    }\n};\n\nSparseMatrix::SparseMatrix() = default;\n\nSparseMatrix::SparseMatrix(const Size rows, const Size cols)\n    : impl(makeAuto<Impl>(rows, cols)) {}\n\nSparseMatrix::~SparseMatrix() = default;\n\nvoid SparseMatrix::resize(const Size rows, const Size cols) {\n    impl = makeAuto<Impl>(rows, cols);\n}\n\nvoid SparseMatrix::insert(const Size i, const Size j, const Float value) {\n    impl->insert(i, j, value);\n}\n\nExpected<Array<Float>> SparseMatrix::solve(const Array<Float>& values,\n    const Solver solver,\n    const Float tolerance) {\n    return impl->solve(values, solver, tolerance);\n}\n\n#endif\n\nNAMESPACE_SPH_END\n", "meta": {"hexsha": "208dbb8bccbe3426b20758ef031fb454126c8898", "size": 4578, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/math/SparseMatrix.cpp", "max_stars_repo_name": "grische/OpenSPH", "max_stars_repo_head_hexsha": "74a8fff865157ae94e8d7ed249b116fbadf6ad20", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-04-02T04:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T09:52:01.000Z", "max_issues_repo_path": "core/math/SparseMatrix.cpp", "max_issues_repo_name": "pavelsevecek/OpenSPH", "max_issues_repo_head_hexsha": "d547c0af6270a739d772a4dcba8a70dc01775367", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-27T21:25:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T21:25:34.000Z", "max_forks_repo_path": "core/math/SparseMatrix.cpp", "max_forks_repo_name": "grische/OpenSPH", "max_forks_repo_head_hexsha": "74a8fff865157ae94e8d7ed249b116fbadf6ad20", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-22T11:44:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T11:44:52.000Z", "avg_line_length": 30.3178807947, "max_line_length": 101, "alphanum_fraction": 0.5786369594, "num_tokens": 1074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.815232489352, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.4044318075517443}}
{"text": "#ifndef MANIFOLDS_FUNCTIONS_MULTI_MATRIX_REDUCTION_HH\n#define MANIFOLDS_FUNCTIONS_MULTI_MATRIX_REDUCTION_HH\n\n#include \"data/multi_matrix.hh\"\n#include \"function.hh\"\n#include \"full_function_defs.hh\"\n#include <boost/mpl/find.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/mpl/end.hpp>\n#include <utility>\n\nnamespace manifolds {\ntemplate <int n1, int n2> struct ReduxPair {\n  static const int first = n1;\n  static const int second = n2;\n};\n\ntemplate <class... ReductionPairs>\nstruct Reduction : Function<int_<26>, 1, 1>,\n                   FunctionCommon<Reduction<ReductionPairs...> > {\n  using FunctionCommon<Reduction>::operator();\n  template <class Arg, class Array, class... Indices,\n            class = typename std::enable_if<\n                (sizeof...(Indices) == Arg::dimensions)>::type>\n  static auto CoeffFromArray(void *, Arg arg, Array a, Indices... indices) {\n    return arg.Coeff(indices...);\n  }\n\n  template <class Arg, class Array, class... Indices,\n            class = typename std::enable_if<\n                (sizeof...(Indices) != Arg::dimensions)>::type>\n  static auto CoeffFromArray(int *, Arg arg, Array a, Indices... indices) {\n    return CoeffFromArray(arg, a, indices..., a[sizeof...(Indices)]);\n  }\n\n  template <class Vector, int index>\n  using is_not_in = typename boost::is_same<\n      typename boost::mpl::find<Vector, int_<index> >::type,\n      typename boost::mpl::end<Vector>::type>::type;\n\n  template <class MMatrix, class Skips, class IndicesTuple = tuple<>,\n            int index = 0, bool = MMatrix::dimensions == index>\n  struct output_type {\n    typedef int_<MMatrix::template dimension<index>::value> dim;\n    typedef typename std::conditional<\n        is_not_in<Skips, index>::value,\n        decltype(push_back(std::declval<IndicesTuple>(), dim())),\n        IndicesTuple>::type next_tuple;\n\n    typedef typename output_type<MMatrix, Skips, next_tuple, index + 1>::type\n    type;\n  };\n\n  template <class MMatrix, class Skips, int index, int... dimensions>\n  struct output_type<MMatrix, Skips, tuple<int_<dimensions>...>, index, true> {\n    typedef MultiMatrix<typename MMatrix::CoefficientType, dimensions...> type;\n  };\n\n  template <class Array> static bool inc_pair(Array &a, int b, int c, int dim) {\n    ++a[b];\n    ++a[c];\n    return a[b] == dim;\n  }\n\n  template <class Arg> auto eval(Arg arg) const {\n    static const bool all_good = and_<bool_<\n        Arg::template dimension<ReductionPairs::first>::value ==\n        Arg::template dimension<ReductionPairs::second>::value>...>::value;\n    static_assert(all_good, \"Can only contract indices \"\n                            \"of the same dimension\");\n    static std::array<std::pair<int, int>, sizeof...(ReductionPairs)> reduxes =\n        { { std::make_pair(ReductionPairs::first,\n                           ReductionPairs::second)... } };\n    int in_indices[Arg::dimensions] = {};\n    typename output_type<\n        Arg, boost::mpl::vector<int_<ReductionPairs::first>...,\n                                int_<ReductionPairs::second>...> >::type result;\n    int out_indices[decltype(result)::dimensions] = {};\n    while (true) {\n      while (true) {\n        result.Coeff(out_indices) += arg.Coeff(in_indices);\n        unsigned index = 0;\n        while (inc_pair(in_indices, reduxes[index].first, reduxes[index].second,\n                        arg.Dimension(reduxes[index].second))) {\n          in_indices[reduxes[index].first] = 0;\n          in_indices[reduxes[index].second] = 0;\n          if (++index == sizeof...(ReductionPairs)) {\n            goto output_index_done;\n          }\n        }\n      }\n    output_index_done:\n      int index = 0;\n      while (true) {\n        if (std::find_if(reduxes.begin(), reduxes.end(), [index](auto x) {\n              return x.first == index || x.second == index;\n            }) == reduxes.end()) {\n          if (++in_indices[index] == arg.Dimension(index)) {\n            int smaller_ones = 0;\n            for (auto x : reduxes) {\n              smaller_ones += ((x.first) < index) + (x.second < index);\n            }\n            in_indices[index] = out_indices[index - smaller_ones] = 0;\n            if (++index == (int)Arg::dimensions)\n              return result;\n          } else {\n            int smaller_ones = 0;\n            for (auto x : reduxes) {\n              smaller_ones += ((x.first) < index) + (x.second < index);\n            }\n            ++out_indices[index - smaller_ones];\n            break;\n          }\n        } else if (++index == (int)Arg::dimensions)\n          return result;\n      }\n    }\n  }\n};\n}\n\n#endif\n", "meta": {"hexsha": "be5e3f656f94a32507b35af802bfe00a137dacce", "size": 4569, "ext": "hh", "lang": "C++", "max_stars_repo_path": "functions/multi_matrix_reduction.hh", "max_stars_repo_name": "GuylainGreer/manifolds", "max_stars_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "functions/multi_matrix_reduction.hh", "max_issues_repo_name": "GuylainGreer/manifolds", "max_issues_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "functions/multi_matrix_reduction.hh", "max_forks_repo_name": "GuylainGreer/manifolds", "max_forks_repo_head_hexsha": "96f996f67fc523c726f2edbc9705125c212bedae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1463414634, "max_line_length": 80, "alphanum_fraction": 0.6012256511, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4040647565650411}}
{"text": "#include <learning/independences/continuous/mutual_information.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n#include <algorithm>\n\n#include <iomanip>\n\nnamespace learning::independences::continuous {\n\ndouble mi_pair(const DataFrame& df, int k) {\n    KDTree kdtree(df);\n    auto knn_results = kdtree.query(df, k + 1, std::numeric_limits<double>::infinity());\n\n    VectorXd eps(df->num_rows());\n    for (auto i = 0; i < df->num_rows(); ++i) {\n        eps(i) = knn_results[i].first(k);\n    }\n\n    VectorXi nv1(df->num_rows());\n    VectorXi nv2(df->num_rows());\n\n    auto raw_values1 = df.data<arrow::FloatType>(0);\n    auto raw_values2 = df.data<arrow::FloatType>(1);\n    for (int i = 0, rows = static_cast<int>(df->num_rows()); i < rows; ++i) {\n        auto eps_i = static_cast<int>(eps(i));\n\n        auto v1 = static_cast<int>(raw_values1[i]);\n        auto v2 = static_cast<int>(raw_values2[i]);\n\n        nv1(i) = std::min(1 + v1, eps_i) + std::min(rows - v1, eps_i) - 1;\n        nv2(i) = std::min(1 + v2, eps_i) + std::min(rows - v2, eps_i) - 1;\n    }\n\n    double res = 0;\n    for (int i = 0; i < df->num_rows(); ++i) {\n        res -= boost::math::digamma(nv1(i)) + boost::math::digamma(nv2(i));\n    }\n\n    res /= df->num_rows();\n    res += boost::math::digamma(k) + boost::math::digamma(df->num_rows());\n\n    return res;\n}\n\ndouble mi_triple(const DataFrame& df, int k) {\n    KDTree kdtree(df);\n    auto knn_results = kdtree.query(df, k + 1, std::numeric_limits<double>::infinity());\n\n    VectorXd eps(df->num_rows());\n    for (auto i = 0; i < df->num_rows(); ++i) {\n        eps(i) = knn_results[i].first(k);\n    }\n\n    VectorXi n_xz = VectorXi::Zero(df->num_rows());\n    VectorXi n_yz = VectorXi::Zero(df->num_rows());\n    VectorXi n_z(df->num_rows());\n\n    auto raw_x = df.data<arrow::FloatType>(0);\n    auto raw_y = df.data<arrow::FloatType>(1);\n    auto raw_z = df.data<arrow::FloatType>(2);\n\n    IndexComparator comp_z(raw_z);\n    std::vector<size_t> sort_z(df->num_rows());\n    std::iota(sort_z.begin(), sort_z.end(), 0);\n    std::sort(sort_z.begin(), sort_z.end(), comp_z);\n\n    for (int i = 0, rows = static_cast<int>(df->num_rows()); i < rows; ++i) {\n        auto eps_i = static_cast<int>(eps(i));\n        auto x_i = static_cast<int>(raw_x[i]);\n        auto y_i = static_cast<int>(raw_y[i]);\n        auto z_i = static_cast<int>(raw_z[i]);\n\n        n_z(i) = std::min(1 + z_i, eps_i) + std::min(rows - z_i, eps_i) - 1;\n\n        if (z_i < eps_i) {\n            for (int j = 0, end = z_i + eps_i; j < end; ++j) {\n                auto index = sort_z[j];\n                auto x_value = raw_x[index];\n                auto y_value = raw_y[index];\n                if (std::abs(x_i - x_value) < eps_i) ++n_xz(i);\n                if (std::abs(y_i - y_value) < eps_i) ++n_yz(i);\n            }\n        } else if (z_i > (rows - eps_i)) {\n            for (int j = z_i - eps_i + 1, end = df->num_rows(); j < end; ++j) {\n                auto index = sort_z[j];\n                auto x_value = raw_x[index];\n                auto y_value = raw_y[index];\n                if (std::abs(x_i - x_value) < eps_i) ++n_xz(i);\n                if (std::abs(y_i - y_value) < eps_i) ++n_yz(i);\n            }\n        } else {\n            for (int j = z_i - eps_i + 1, end = z_i + eps_i; j < end; ++j) {\n                auto index = sort_z[j];\n                auto x_value = raw_x[index];\n                auto y_value = raw_y[index];\n                if (std::abs(x_i - x_value) < eps_i) ++n_xz(i);\n                if (std::abs(y_i - y_value) < eps_i) ++n_yz(i);\n            }\n        }\n    }\n\n    double res = 0;\n    for (int i = 0; i < df->num_rows(); ++i) {\n        res += boost::math::digamma(n_z(i)) - boost::math::digamma(n_xz(i)) - boost::math::digamma(n_yz(i));\n    }\n\n    res /= df->num_rows();\n    res += boost::math::digamma(k);\n\n    return res;\n}\n\ndouble mi_general(const DataFrame& df, int k) {\n    KDTree kdtree(df);\n    auto knn_results = kdtree.query(df, k + 1, std::numeric_limits<double>::infinity());\n\n    VectorXd eps(df->num_rows());\n    for (auto i = 0; i < df->num_rows(); ++i) {\n        eps(i) = knn_results[i].first(k);\n    }\n\n    std::vector<size_t> indices(df->num_columns() - 2);\n    std::iota(indices.begin(), indices.end(), 2);\n    auto z_df = df.loc(indices);\n    KDTree ztree(z_df);\n    auto [n_xz, n_yz, n_z] = ztree.count_ball_subspaces(z_df, df.col(0), df.col(1), eps);\n\n    double res = 0;\n    for (int i = 0; i < df->num_rows(); ++i) {\n        res += boost::math::digamma(n_z(i)) - boost::math::digamma(n_xz(i)) - boost::math::digamma(n_yz(i));\n    }\n\n    res /= df->num_rows();\n    res += boost::math::digamma(k);\n\n    return res;\n}\n\ndouble KMutualInformation::mi(const std::string& x, const std::string& y) const {\n    auto subset_df = m_ranked_df.loc(x, y);\n    return mi_pair(subset_df, m_k);\n}\n\ndouble KMutualInformation::mi(const std::string& x, const std::string& y, const std::string& z) const {\n    auto subset_df = m_ranked_df.loc(x, y, z);\n    return mi_triple(subset_df, m_k);\n}\n\ndouble KMutualInformation::mi(const std::string& x, const std::string& y, const std::vector<std::string>& z) const {\n    auto subset_df = m_ranked_df.loc(x, y, z);\n    return mi_general(subset_df, m_k);\n}\n\ndouble KMutualInformation::pvalue(const std::string& x, const std::string& y) const {\n    auto value = mi(x, y);\n\n    auto shuffled_df = m_ranked_df.loc(Copy(x), y);\n\n    auto x_begin = shuffled_df.template mutable_data<arrow::FloatType>(0);\n    auto x_end = x_begin + shuffled_df->num_rows();\n    std::mt19937 rng{m_seed};\n\n    int count_greater = 0;\n    for (int i = 0; i < m_samples; ++i) {\n        std::shuffle(x_begin, x_end, rng);\n        auto shuffled_value = mi_pair(shuffled_df, m_k);\n\n        if (shuffled_value >= value) ++count_greater;\n    }\n\n    return static_cast<double>(count_greater) / m_samples;\n}\n\ndouble KMutualInformation::pvalue(const std::string& x, const std::string& y, const std::string& z) const {\n    auto original_mi = mi(x, y, z);\n    auto z_df = m_df.loc(z);\n    auto shuffled_df = m_ranked_df.loc(Copy(x), y, z);\n    auto original_rank_x = m_ranked_df.template data<arrow::FloatType>(x);\n\n    return shuffled_pvalue(original_mi, original_rank_x, z_df, shuffled_df, MITriple{});\n}\n\ndouble KMutualInformation::pvalue(const std::string& x, const std::string& y, const std::vector<std::string>& z) const {\n    auto original_mi = mi(x, y, z);\n    auto z_df = m_df.loc(z);\n    auto shuffled_df = m_ranked_df.loc(Copy(x), y, z);\n    auto original_rank_x = m_ranked_df.template data<arrow::FloatType>(x);\n\n    return shuffled_pvalue(original_mi, original_rank_x, z_df, shuffled_df, MIGeneral{});\n}\n\n}  // namespace learning::independences::continuous", "meta": {"hexsha": "9c1580fbb9dba5a4e6548ded9d70d60d4cceb3a6", "size": 6693, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pybnesian/learning/independences/continuous/mutual_information.cpp", "max_stars_repo_name": "vishalbelsare/PyBNesian", "max_stars_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T19:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:08:05.000Z", "max_issues_repo_path": "pybnesian/learning/independences/continuous/mutual_information.cpp", "max_issues_repo_name": "vishalbelsare/PyBNesian", "max_issues_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybnesian/learning/independences/continuous/mutual_information.cpp", "max_forks_repo_name": "vishalbelsare/PyBNesian", "max_forks_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:44:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T02:57:02.000Z", "avg_line_length": 35.0418848168, "max_line_length": 120, "alphanum_fraction": 0.5883759151, "num_tokens": 2030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8080672227971212, "lm_q2_score": 0.5, "lm_q1q2_score": 0.4040336113985606}}
{"text": "/*\n * Copyright (C) 2015 Hamza Merzić\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*/\n#include \"model_parser.h\"\n\n#include <cmath>\n#include <PQP/PQP.h>\n#include <Eigen/Dense>\n#include <fstream>\n#include <memory>\n#include <algorithm>\n\n\ntypedef Eigen::Vector3f EVector3f;\n\ndouble PointDistanceToAxis(const EVector3f& point, const EVector3f& axis) {\n  double l = point.dot(axis);\n  return (point - axis * l).norm();\n}\n\ndouble PointDistanceToVector(const EVector3f& point, const EVector3f& vect) {\n  double point_a_distance(point.squaredNorm());\n  EVector3f d = point - vect;\n  double point_b_distance(d.squaredNorm());\n  EVector3f u = -vect;\n  u.normalize();\n  if (point_a_distance < point_b_distance) {\n    d = point;\n    d.normalize();\n    double c = d.dot((vect).normalized());\n    return (c > 0.0)\n        ? sqrt(point_a_distance * (1.0 - c * c)) :\n          sqrt(point_a_distance);\n  } else {\n    d.normalize();\n    double c = d.dot((-vect).normalized());\n    return (c > 0.0)\n        ? sqrt(point_b_distance * (1.0 - c * c)) :\n          sqrt(point_b_distance);\n  }\n}\n\nPQP_Model* ModelParser::GetTransformModel(const std::string& model_file,\n                                          const EMatrix& R,\n                                          const EVector3f& T,\n                                          const EVector3f& axis,\n                                          double* axis_length,\n                                          double* radius) {\n  std::ifstream input_file (model_file.c_str(), std::ios::binary);\n  try {\n    std::unique_ptr<PQP_Model> model (new PQP_Model);\n\n    char header[80] = \"\";         // Reads STL binary header\n    input_file.read(header, 80);\n\n    unsigned num_tris = 0;  // Reads number of triangles\n    input_file.read(reinterpret_cast<char*>(&num_tris), sizeof(num_tris));\n\n    EVector3f vertex[3];  // Triangle represented as three vertices\n    float surf_vec[3];\n\n    model->BeginModel();\n\n    int16_t temp = 0;  // Used for taking two bits of data after a triangle\n    uint64_t counter = 0;\n\n    *axis_length = 0.0;\n    *radius = 0.0;\n    while (counter < num_tris) {\n      input_file.read(reinterpret_cast<char*>(surf_vec), sizeof(surf_vec));\n\n      for (unsigned i = 0; i < 3; ++i) {\n        input_file.read(reinterpret_cast<char*>(&vertex[i]), sizeof(vertex[i]));\n        vertex[i] = R * vertex[i] + T;\n        *axis_length = std::max(*axis_length, double(vertex[i].dot(axis)));\n        *radius = std::max(*radius,\n            PointDistanceToVector(vertex[i], axis * *axis_length));\n      }\n      model->AddTri(vertex[0].data(), vertex[1].data(), vertex[2].data(),\n        counter);\n\n      input_file.read(reinterpret_cast<char*>(&temp), sizeof(temp));\n      ++counter;\n    }\n\n    model->EndModel();\n    return model.release();\n  }\n  catch(...) {\n    throw \"File \" + model_file + \" error!\";\n  }\n}\n\n// TODO(hamza): Try to get rid of code repetition\nPQP_Model* ModelParser::GetModel(const std::string& model_file) {\n  std::ifstream input_file (model_file.c_str(), std::ios::binary);\n  try {\n    std::unique_ptr<PQP_Model> model (new PQP_Model);\n\n    char header[80] = \"\";         // Reads STL binary header\n    input_file.read(header, 80);\n\n    unsigned num_tris = 0;  // Reads number of triangles\n    input_file.read(reinterpret_cast<char*>(&num_tris), sizeof(num_tris));\n\n    float vertex[3][3];  // Triangle represented as three vertices\n    float surf_vec[3];\n\n    model->BeginModel();\n\n    int16_t temp (0);  // Used for taking two bits of data after a triangle\n    uint64_t counter = 0;\n    while (counter < num_tris) {\n      input_file.read(reinterpret_cast<char*>(surf_vec), sizeof(surf_vec));\n\n      input_file.read(reinterpret_cast<char*>(&vertex[0]), sizeof(vertex[0]));\n      input_file.read(reinterpret_cast<char*>(&vertex[1]), sizeof(vertex[1]));\n      input_file.read(reinterpret_cast<char*>(&vertex[2]), sizeof(vertex[2]));\n      model->AddTri(vertex[0], vertex[1], vertex[2], counter);\n\n      input_file.read(reinterpret_cast<char*>(&temp), sizeof(temp));\n      ++counter;\n    }\n\n    model->EndModel();\n    return model.release();\n  }\n  catch(...) {\n    throw \"File \" + model_file + \" error!\";\n  }\n}\n", "meta": {"hexsha": "0198ec28ab766cc94e32b11faf69c2e34dba8158", "size": 4674, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/environment/model_parser.cc", "max_stars_repo_name": "hamzamerzic/repo", "max_stars_repo_head_hexsha": "e634335a5943c25115e4860988d5f98493bb3cf9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2017-04-16T14:09:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T03:09:06.000Z", "max_issues_repo_path": "src/environment/model_parser.cc", "max_issues_repo_name": "hamzamerzic/repo", "max_issues_repo_head_hexsha": "e634335a5943c25115e4860988d5f98493bb3cf9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T07:44:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T07:44:09.000Z", "max_forks_repo_path": "src/environment/model_parser.cc", "max_forks_repo_name": "hamzamerzic/repo", "max_forks_repo_head_hexsha": "e634335a5943c25115e4860988d5f98493bb3cf9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-02-06T07:08:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T02:01:25.000Z", "avg_line_length": 32.2344827586, "max_line_length": 80, "alphanum_fraction": 0.6245186136, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390746, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4039985929631613}}
{"text": "// This file is part of the dune-mlmc project:\n//   http://users.dune-project.org/projects/dune-mlmc\n// Copyright Holders: Rene Milk\n// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\n#include <config.h>\n\n#include \"msfem.hh\"\n\n#include <dune/multiscale/common/main_init.hh>\n#include <dune/multiscale/msfem/localsolution_proxy.hh>\n#include <dune/multiscale/msfem/localproblems/localgridlist.hh>\n#include <dune/multiscale/problems/base.hh>\n#include <dune/multiscale/common/grid_creation.hh>\n#include <dune/multiscale/msfem/msfem_solver.hh>\n#include <dune/multiscale/msfem/fem_solver.hh>\n#include <dune/multiscale/msfem/msfem_traits.hh>\n#include <dune/multiscale/common/heterogenous.hh>\n\n#if DUNE_MULTISCALE_WITH_DUNE_FEM\n#include <dune/fem/mpimanager.hh>\n#endif\n\n#include <dune/xt/common/ranges.hh>\n#include <dune/stuff/grid/walker/functors.hh>\n#include <dune/stuff/grid/walker/apply-on.hh>\n#include <dune/xt/common/timings.hh>\n#include <dune/xt/common/logging.hh>\n#include <dune/xt/common/configuration.hh>\n#include <dune/xt/common/signals.hh>\n#include <dune/xt/common/memory.hh>\n\n#include <dune/gdt/products/h1.hh>\n#include <dune/gdt/products/weightedl2.hh>\n#include <dune/gdt/products/boundaryl2.hh>\n\n#include <boost/filesystem.hpp>\n#include <tbb/task_scheduler_init.h>\n\n\ndouble surface_flow_gdt(const Dune::Multiscale::CommonTraits::GridType &grid,\n                    const Dune::Multiscale::CommonTraits::ConstDiscreteFunctionType& solution,\n                        const DMP::ProblemContainer& problem) {\n  using namespace Dune::Multiscale;\n  const auto gv = grid.leafGridView();\n\n  // Constants and types\n  constexpr auto dim = CommonTraits::world_dim;\n  typedef double REAL; //TODO read from input\n  typedef typename Dune::FieldVector<REAL,dim> FV;   // point on cell\n  typedef typename Dune::FieldMatrix<REAL,dim,dim> FM;   // point on cell\n  typedef typename Dune::FieldMatrix<REAL,1,dim> Grad;   // point on cell\n  typedef typename Dune::QuadratureRule<REAL,dim-1> QR;\n  typedef typename Dune::QuadratureRules<REAL,dim-1> QRS;\n\n  const auto& diffusion = problem.getDiffusion();\n\n  // Quadrature rule\n  auto iCell = gv.template begin< 0,Dune::Interior_Partition >();\n  auto iFace = gv.ibegin(*iCell);\n  const QR& rule = QRS::rule(iFace->geometry().type(),2); // TODO order as para\n\n  // Loop over cells\n  REAL localFlux(0);\n  for(iCell = gv.template begin< 0,Dune::Interior_Partition >();\n      iCell != gv.template end< 0,Dune::Interior_Partition >(); ++iCell) {\n    // Loop over interfaces\n    const auto local_solution = solution.local_function(*iCell);\n    for(iFace = gv.ibegin(*iCell); iFace != gv.iend(*iCell); ++iFace) {\n      if(iFace->boundary() && abs(iFace->geometry().center()[0]) < 1e-10) {\n        double area = iFace->geometry().volume();\n        // Loop over gauss points\n        for(auto iGauss = rule.begin(); iGauss != rule.end(); ++iGauss) {\n          FV pos = iFace->geometry().global(iGauss->position());\n          Grad grad;\n          FM diff;\n          diffusion.evaluate(pos, diff);\n          local_solution->jacobian(pos, grad);\n          localFlux -= iGauss->weight() * area * diff[0][0] * grad[0][0];\n        }\n      }\n    }\n  }\n  localFlux = grid.comm().sum(localFlux);\n  return localFlux;\n}\n\nvoid MultiLevelMonteCarlo::MsCgFemDifference::init(Dune::MPIHelper::MPICommunicator global, Dune::MPIHelper::MPICommunicator local) {\n  // inits perm field only, no create()\n  local_comm_ = local;\n  if(init_called_)\n    return;\n\n  problem_ = Dune::XT::Common::make_unique<DMP::ProblemContainer>(global, local, DXTC_CONFIG);\n  assert(problem_);\n  init_called_ = true;\n}\n\ndouble MultiLevelMonteCarlo::MsCgFemDifference::compute_inflow_difference(const Dune::Multiscale::CommonTraits::GridType& coarse_grid,\n                                                                          Dune::Multiscale::LocalsolutionProxy &msfem_solution,\n                                                                          const std::shared_ptr<Dune::Multiscale::CommonTraits::GridType> fine_grid,\n                                                                          const Dune::Multiscale::CommonTraits::ConstDiscreteFunctionType* fine_function) {\n  using namespace Dune;\n  typedef Multiscale::CommonTraits::SpaceChooserType::PartViewType\n      PartViewType;\n  const Multiscale::CommonTraits::SpaceType coarse_space(PartViewType::create(\n                                                         coarse_grid, Multiscale::CommonTraits::st_gdt_grid_level));\n  Multiscale::CommonTraits::DiscreteFunctionType projected_msfem_solution(\n        coarse_space, \"MsFEM_Solution\");\n  Multiscale::MsFEMProjection::project(\n        msfem_solution, projected_msfem_solution);\n  const auto coarse_flow = surface_flow_gdt(coarse_grid, projected_msfem_solution, *problem_);\n\n  if(fine_function && fine_grid) {\n    const auto fine_flow = surface_flow_gdt(*fine_grid, *fine_function, *problem_);\n\n    //fine_function->visualize(\"fine_sol\");\n    //projected_msfem_solution.visualize(\"proj_msfem_sol\");\n\n    return fine_flow - coarse_flow;\n  }\n\n  return coarse_flow;\n}\n\ndouble MultiLevelMonteCarlo::MsCgFemDifference::eval() {\n  using namespace Dune;\n  Dune::XT::Common::OutputScopedTiming tm(\"mlmc.difference_cg-msfem\", DXTC_LOG_INFO_0);\n  assert(init_called_);\n  assert(problem_);\n  auto coarse_grid = Multiscale::make_coarse_grid(*problem_, local_comm_);\n  // create() new perm field\n  problem_->getMutableModelData().prepare_new_evaluation(*problem_);\n  auto fine_grid = Multiscale::make_fine_grid(*problem_, coarse_grid, true,local_comm_);\n\n  typedef Multiscale::CommonTraits::SpaceChooserType::PartViewType\n      PartViewType;\n  const Multiscale::CommonTraits::SpaceType coarse_space(PartViewType::create(\n                                                           *coarse_grid, Multiscale::CommonTraits::st_gdt_grid_level));\n\n\n  std::unique_ptr<Multiscale::LocalsolutionProxy> msfem_solution(nullptr);\n\n  Multiscale::LocalGridList localgrid_list(*problem_, coarse_space);\n  Dune::XT::Common::timings().start(\"mlmc.difference_cg-msfem.msfem-solve\");\n  Multiscale::Elliptic_MsFEM_Solver().apply(*problem_, coarse_space, msfem_solution,\n                                            localgrid_list);\n  Dune::XT::Common::timings().stop(\"mlmc.difference_cg-msfem.msfem-solve\");\n\n  Dune::XT::Common::timings().start(\"mlmc.difference_cg-msfem.cgfem-solve\");\n  Multiscale::Elliptic_FEM_Solver fem(*problem_, fine_grid);\n  const auto &fine_fem_solution = fem.solve();\n  Dune::XT::Common::timings().stop(\"mlmc.difference_cg-msfem.cgfem-solve\");\n\n  Dune::XT::Common::OutputScopedTiming tmd(\"mlmc.difference_cg-msfem.compute_inflow_difference\", DXTC_LOG_INFO_0);\n  return compute_inflow_difference(*coarse_grid, *msfem_solution,\n                                   fine_grid, &fine_fem_solution);\n}\n\ndouble MultiLevelMonteCarlo::MsFemSingleDifference::eval() {\n  using namespace Dune;\n  Dune::XT::Common::OutputScopedTiming tm(\"mlmc.single_msfem\", DXTC_LOG_INFO_0);\n  assert(problem_);\n//  assert(init_called_);\n  auto coarse_grid = Multiscale::make_coarse_grid(*problem_, local_comm_);\n  // create() new perm field\n  problem_->getMutableModelData().prepare_new_evaluation(*problem_);\n  typedef Multiscale::CommonTraits::SpaceChooserType::PartViewType\n      PartViewType;\n  const Multiscale::CommonTraits::SpaceType coarse_space(PartViewType::create(\n                                                           *coarse_grid, Multiscale::CommonTraits::st_gdt_grid_level));\n  std::unique_ptr<Multiscale::LocalsolutionProxy> msfem_solution(nullptr);\n\n  Multiscale::LocalGridList localgrid_list(*problem_, coarse_space);\n  Dune::XT::Common::timings().start(\"mlmc.single_msfem.msfem-solve\");\n  Multiscale::Elliptic_MsFEM_Solver().apply(*problem_, coarse_space, msfem_solution,\n                                            localgrid_list);\n  Dune::XT::Common::timings().stop(\"mlmc.single_msfem.msfem-solve\");\n\n\n  Dune::XT::Common::OutputScopedTiming tmd(\"mlmc.single_msfem.compute_inflow_difference\", DXTC_LOG_INFO_0);\n  return compute_inflow_difference(*coarse_grid, *msfem_solution);\n}\n\n//! workaround for https://github.com/wwu-numerik/dune-stuff/issues/42\nvoid set_config_values(const std::vector<std::string> &keys,\n                       const std::vector<std::string> &values) {\n  assert(keys.size() == values.size());\n  for (const auto i : Dune::XT::Common::value_range(keys.size()))\n    DXTC_CONFIG.set(keys[i], values[i], true);\n\n  // should just be\n  // Dune::XT::Common::Config().add(Dune::XT::Common::Configuration(keys, values), \"\", true);\n}\n\nvoid handle_sigterm(int signal) {\n  DXTC_TIMINGS.stop();\n  DXTC_TIMINGS.output_per_rank(\"profiler\");\n  std::exit(signal);\n}\n\nvoid MultiLevelMonteCarlo::msfem_init(int argc, char **argv) {\n  using namespace std;\n#if DUNE_MULTISCALE_WITH_DUNE_FEM\n  Dune::Fem::MPIManager::initialize(argc, argv);\n#endif\n  auto &helper = Dune::MPIHelper::instance(argc, argv);\n  if (helper.size() > 1 &&\n      !(Dune::Capabilities::isParallel<\n        Dune::Multiscale::CommonTraits::GridType>::v)) {\n    DUNE_THROW(Dune::InvalidStateException,\n               \"mpi enabled + serial grid = bad idea\");\n  }\n\n  // config defaults defaults\n  const vector<string> keys{\"grids.macro_cells_per_dim\",\n                            \"grids.micro_cells_per_macrocell_dim\",\n                            \"msfem.oversampling_layers\", \"problem.name\"};\n  const vector<string> values{\"8\", \"12\", \"1\", \"Random\"};\n  set_config_values(keys, values);\n\n  //if (argc > 1 && boost::filesystem::is_regular_file(argv[1]))\n  //  Dune::XT::Common::Config().read_command_line(argc, argv);\n\n  if (argc > 1 ) {\n      Dune::XT::Common::Config().read_command_line(argc, argv);\n      Dune::Stuff::Common::Config().read_command_line(argc, argv);\n  }\n  Dune::XT::Common::test_create_directory(DXTC_CONFIG_GET(\"global.datadir\", \"data/\"));\n\n  // LOG_NONE = 1, LOG_ERROR = 2, LOG_INFO = 4,LOG_DEBUG = 8,LOG_CONSOLE =\n  // 16,LOG_FILE = 32\n  // --> LOG_ERROR | LOG_INFO | LOG_DEBUG | LOG_CONSOLE | LOG_FILE = 62\n  Dune::XT::Common::Logger().create(DXTC_CONFIG_GET(\"logging.level\", 62),\n                       DXTC_CONFIG_GET(\"logging.file\", std::string(argv[0]) + \".log\"),\n                       DXTC_CONFIG_GET(\"global.datadir\", \"data\"),\n                       DXTC_CONFIG_GET(\"logging.dir\", \"log\" /*path below datadir*/));\n  DXTC_TIMINGS.set_outputdir(DXTC_CONFIG_GET(\"global.datadir\", \"data\"));\n  Dune::XT::Common::install_signal_handler(SIGTERM, handle_sigterm);\n}\n\n\n\n", "meta": {"hexsha": "f0684f02621371b6539f764abc7fa6aa09b478f1", "size": 10478, "ext": "cc", "lang": "C++", "max_stars_repo_path": "dune/mlmc/msfem.cc", "max_stars_repo_name": "wwu-numerik/DUNE-mlmc", "max_stars_repo_head_hexsha": "5ea4b663ec0a30d2bfcccdf736a9db9bdcea16fb", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dune/mlmc/msfem.cc", "max_issues_repo_name": "wwu-numerik/DUNE-mlmc", "max_issues_repo_head_hexsha": "5ea4b663ec0a30d2bfcccdf736a9db9bdcea16fb", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dune/mlmc/msfem.cc", "max_forks_repo_name": "wwu-numerik/DUNE-mlmc", "max_forks_repo_head_hexsha": "5ea4b663ec0a30d2bfcccdf736a9db9bdcea16fb", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9426229508, "max_line_length": 155, "alphanum_fraction": 0.6881084176, "num_tokens": 2771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185944046238981, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4039768879475764}}
{"text": "#include \"include/GeneralizedRfAlgo.h\"\n#include <boost/math/special_functions/factorials.hpp>\n#include <queue>\n// boost logging\n#include <FastSplitList.h>\n#include <SpiAlgo.h>\n#include <boost/log/attributes/constant.hpp>\n#include <boost/log/sources/record_ostream.hpp>\n#include <future>\n\nstd::atomic_size_t GeneralizedRfAlgo::tree_idx = 0;\n\nLogDblFact GeneralizedRfAlgo::factorials = LogDblFact();\nGeneralizedRfAlgo::GeneralizedRfAlgo() : pairwise_split_scores(0) {\n\tlogger.add_attribute(\"Tag\", boost::log::attributes::constant<std::string>(\"generalized_RF\"));\n}\n\nRfAlgorithmInterface::Scalar GeneralizedRfAlgo::h_info_content(size_t a, size_t b) {\n\t// no trivial splits allowed here (outer log would return infty, because no information present)\n\tassert(a >= 2);\n\tassert(b >= 2);\n\t// precompute (maybe lazy) all double fac results for a and b separatly\n\treturn -factorials.lg_rooted_dbl_fact_fast(static_cast<long>(a)) -\n\t       factorials.lg_rooted_dbl_fact_fast(static_cast<long>(b)) +\n\t       factorials.lg_unrooted_dbl_fact_fast(static_cast<long>(a + b));\n}\n\nsize_t GeneralizedRfAlgo::bits_too_many(size_t taxa) {\n\tconstexpr size_t bit_amount_split = sizeof(pll_split_base_t) * 8;\n\tauto bits_too_many =\n\t    taxa % bit_amount_split == 0 ? 0 : bit_amount_split - (taxa % bit_amount_split);\n\tassert(bits_too_many < sizeof(pll_split_base_t) * 8);\n\treturn bits_too_many;\n}\n\nvoid GeneralizedRfAlgo::calc_thread(GeneralizedRfAlgo &alg,\n                                    const std::vector<FastSplitList> &trees,\n                                    size_t pairwise_tree_cnt,\n                                    SymmetricMatrix<Scalar> &sim) {\n\twhile (true) {\n\t\tsize_t index = tree_idx++;\n\t\tif (index >= pairwise_tree_cnt) {\n\t\t\tbreak;\n\t\t}\n\t\t// Calculates the corresponding row from the index using the quadratic formula\n\t\tauto row = static_cast<size_t>(std::sqrt(1 + 8 * index) / 2 - .5);\n\t\tsize_t col = index - (row * row + row) / 2;\n\t\tauto score = alg.calc_tree_score(trees[row], trees[col]);\n\t\tsim.raw_set_at(index, score);\n\t}\n}\n\nRfMetricInterface::Results GeneralizedRfAlgo::calculate(std::vector<PllTree> &trees,\n                                                        const RfMetricInterface::Params &params) {\n\tassert(trees.size() >= 2);\n\t// extract splits. Each tree now identifies by its index in all_splits\n\tstd::vector<PllSplitList> all_splits;\n\tall_splits.reserve(trees.size());\n\tfor (auto &t : trees) {\n\t\tt.alignNodeIndices(*trees.begin());\n\t\tall_splits.emplace_back(t);\n\t}\n\tPllSplit::split_len = all_splits.back().computeSplitLen();\n\ttaxa = all_splits.back().size() + 3;\n\n\tBOOST_LOG_SEV(logger, lg::notification) << \"Parsed trees. Starting calculations.\";\n\tfactorials.reserve(4 * taxa + 8);\n\tstd::vector<FastSplitList> fast_trees = generateFastList(all_splits);\n\tassert(PllSplit::split_len != std::numeric_limits<size_t>::max());\n\tsetup_temporary_storage(PllSplit::split_len);\n\tpairwise_split_scores = calcPairwiseSplitScores();\n\n\tBOOST_LOG_SEV(logger, lg::notification)\n\t    << \"Calculated pairwise scores; Calculating pairwise tree scores.\";\n\tRfMetricInterface::Results res(trees.size());\n\n\tsize_t pairwise_tree_cnt = res.pairwise_similarities.get_num_entries();\n\tint num_threads = params.threads == -1 ? static_cast<int>(std::thread::hardware_concurrency())\n\t                                       : params.threads;\n\tstd::vector<std::thread> pool;\n\tmatch_solver.init(all_splits.back().size());\n\n\tpool.reserve(num_threads);\n    for (int i = 0; i < num_threads; ++i) {\n\t\tpool.emplace_back(calc_thread,\n\t\t                  std::ref(*this),\n\t\t                  std::ref(fast_trees),\n\t\t                  std::ref(pairwise_tree_cnt),\n\t\t                  std::ref(res.pairwise_similarities));\n\t}\n\n\tfor (auto &thread : pool) {\n\t\tthread.join();\n\t}\n\n\t// calc mean distance between trees\n\tdouble total_dst = 0.;\n\tfor (size_t idx_a = 0; idx_a < all_splits.size(); ++idx_a) {\n\t\tfor (size_t idx_b = 0; idx_b <= idx_a; ++idx_b) {\n\t\t\ttotal_dst += res.pairwise_similarities.at(idx_a, idx_b);\n\t\t}\n\t}\n\tres.mean_distance = total_dst / static_cast<Scalar>(trees.size());\n\n\t// calculate distances\n\tcalc_pairwise_tree_dist(fast_trees, res);\n\n\tfactorials.printLog();\n\treturn res;\n}\nRfAlgorithmInterface::Scalar GeneralizedRfAlgo::calc_tree_score(const SplitList &A,\n                                                                const SplitList &B) {\n\t//\tauto scores = calc_pairwise_split_scores(A, B);\n\tSplitScores scores(A.size());\n\tScalar max_val = 0;\n\tfor (size_t row = 0; row < A.size(); ++row) {\n\t\tsize_t row_idx = A[row].getScoreIndex();\n\t\tfor (size_t col = 0; col < A.size(); ++col) {\n\t\t\tsize_t col_idx = B[col].getScoreIndex();\n\t\t\tauto val = pairwise_split_scores.checked_at(row_idx, col_idx);\n\t\t\tscores.scores.set(row, col, val);\n\t\t\tif (val > max_val) {\n\t\t\t\tmax_val = val;\n\t\t\t}\n\t\t}\n\t}\n\tscores.max_score = max_val;\n\tauto total_score = match_solver.solve(scores);\n\treturn total_score;\n}\n\n[[maybe_unused]] GeneralizedRfAlgo::SplitScores\nGeneralizedRfAlgo::calc_pairwise_split_scores(const SplitList &S1, const SplitList &S2) {\n\tSplitScores scores(S1.size());\n\tfactorials.reserve(taxa + taxa + 4);\n\tfor (size_t row = 0; row < S1.size(); ++row) {\n\t\tfor (size_t col = 0; col < S1.size(); ++col) {\n\t\t\tScalar val;\n\t\t\t// when using fast Split list, the pointers to PllSplit define equality\n\t\t\tif (&S1[row] == &S2[col]) {\n\t\t\t\tassert(S1[row] == S2[col]);\n\t\t\t\tval = calc_split_score(S1[row]);\n\t\t\t} else {\n\t\t\t\tval = calc_split_score(S1[row], S2[col]);\n\t\t\t}\n\n\t\t\tif (scores.max_score < val) {\n\t\t\t\tscores.max_score = val;\n\t\t\t}\n\t\t\tscores.scores.set(row, col, val);\n\t\t}\n\t}\n\n\treturn scores;\n}\n\nvoid GeneralizedRfAlgo::compute_split_comparison(const PllSplit &S1, const PllSplit &S2) {\n\t// B1 -> &split_buffer[0]\n\tS1.set_not(PllSplit::split_len, &temporary_split_content[0]);\n\t// B2 -> &split_buffer[split_len]\n\tS2.set_not(PllSplit::split_len, &temporary_split_content[PllSplit::split_len]);\n\t// A1 and A2 -> &split_buffer[2 * split_len]\n\tS1.intersect(S2, PllSplit::split_len, &temporary_split_content[2 * PllSplit::split_len]);\n\t// B1 and B2 -> &split_buffer[3 * split_len]\n\ttemporary_splits[0].intersect(temporary_splits[1],\n\t                              PllSplit::split_len,\n\t                              &temporary_split_content[3 * PllSplit::split_len]);\n\t// A1 and B2 -> &split_buffer[4 * split_len]\n\tS1.intersect(temporary_splits[1],\n\t             PllSplit::split_len,\n\t             &temporary_split_content[4 * PllSplit::split_len]);\n\t// A2 and B1 -> &split_buffer[5 * split_len]\n\tS2.intersect(temporary_splits[0],\n\t             PllSplit::split_len,\n\t             &temporary_split_content[5 * PllSplit::split_len]);\n}\nRfAlgorithmInterface::Scalar GeneralizedRfAlgo::calc_tree_info_content(const SplitList &S) {\n\tScalar sum = 0;\n\tfor (size_t i = 0; i < S.size(); ++i) {\n\t\tsum += S[i].getHInfoContent();\n\t}\n\treturn sum;\n}\nvoid GeneralizedRfAlgo::calc_pairwise_tree_dist(const std::vector<FastSplitList> &trees,\n                                                RfMetricInterface::Results &res) {\n\tstd::vector<GeneralizedRfAlgo::Scalar> tree_info(trees.size());\n\tfor (size_t i = 0; i < trees.size(); ++i) {\n\t\ttree_info[i] = calc_tree_info_content(trees[i]);\n\t}\n\n\tGeneralizedRfAlgo::Scalar summed_dist = 0;\n\tfor (size_t row = 0; row < trees.size(); ++row) {\n\t\tfor (size_t col = 0; col <= row; ++col) {\n\t\t\tauto score = res.pairwise_similarities.at(row, col);\n\t\t\tauto max = tree_info[row] + tree_info[col];\n\t\t\tres.pairwise_distances.set_at(row, col, (max - score - score));\n\t\t\tsummed_dist += max / score;\n\t\t}\n\t}\n\n\tres.mean_distance = summed_dist / (static_cast<Scalar>(trees.size() + 1) *\n\t                                   (static_cast<Scalar>(trees.size()) / 2.));\n}\nvoid GeneralizedRfAlgo::setup_temporary_storage(size_t split_len) {\n\ttemporary_split_content.assign(split_len * 6, 0);\n\ttemporary_splits.reserve(6);\n\tfor (size_t i = 0; i < 6; ++i) {\n\t\ttemporary_splits.emplace_back(&temporary_split_content[i * split_len]);\n\t}\n}\nGeneralizedRfAlgo::GeneralizedRfAlgo(size_t split_len) : pairwise_split_scores(0) {\n\tlogger.add_attribute(\"Tag\", boost::log::attributes::constant<std::string>(\"generalized_RF\"));\n\tsetup_temporary_storage(split_len);\n}\nstd::vector<FastSplitList>\nGeneralizedRfAlgo::generateFastList(const std::vector<PllSplitList> &slow_split_list) {\n\t// expect that all elements of slow_split_list[i] are already sorted\n\t// -> Perform k-way merge to only store non-duplicate PllSplits\n\tPllSplit::split_len = slow_split_list.front().computeSplitLen();\n\tBOOST_LOG_SEV(logger, lg::normal)\n\t    << \"Start reducing PllSplit Size, current split_len: \" << PllSplit::split_len;\n\n\tstd::vector<FastSplitList> returnList(slow_split_list.size(),\n\t                                      FastSplitList(slow_split_list.front().size()));\n\n\t// data used inside k-way merge\n\tstd::vector<size_t> currently_inPQ(slow_split_list.size(), 0);\n\tsize_t current_split_offset = 0;\n\tsize_t found_duplicates = 0;\n\t// PQ which stores a PllSplit (underlying data not touched) and the index from which tree it\n\t// originates from\n\ttypedef std::pair<PllSplit, size_t> pq_type;\n\tstd::priority_queue<pq_type, std::vector<pq_type>, std::greater<>> pq;\n\t// initialize by inserting first elements of all slow lists\n\tfor (size_t i = 0; i < slow_split_list.size(); ++i) {\n\t\tpq.push(std::make_pair(PllSplit(slow_split_list[i][0]), i));\n\t}\n\tauto insert_in_pq = [&](size_t active_slow_idx) {\n\t\t// takes the current index\n\t\tauto &active_slow_list = slow_split_list[active_slow_idx];\n\t\t// increment where the active element is\n\t\tsize_t list_idx = ++currently_inPQ[active_slow_idx];\n\t\tif (list_idx < active_slow_list.size()) {\n\t\t\tPllSplit insert_split(active_slow_list[list_idx]());\n\t\t\tpq.push(std::make_pair(insert_split, active_slow_idx));\n\t\t}\n\t};\n\twhile (!pq.empty()) {\n\t\t// no further duplications store the next split in unique_pll_splits (either because of\n\t\t// start/or handled all duplicates), increment current_split_offset\n\t\tunique_pll_splits.emplace_back(pq.top().first);\n\t\t{\n\t\t\t// pre-calc\n\t\t\tunique_pll_splits.back().perform_popcount_precalc(PllSplit::split_len);\n\t\t\tconst size_t a = unique_pll_splits.back().getPrecalcPopcnt();\n\t\t\tunique_pll_splits.back().setHInfoContent(h_info_content(a, taxa - a));\n\t\t}\n\n\t\t// get current state\n\t\tPllSplit curr_split = pq.top().first;\n\t\t{\n\t\t\tsize_t curr_slow_list_idx = pq.top().second;\n\t\t\t// add current unique split to result\n\t\t\tassert(currently_inPQ[curr_slow_list_idx] < slow_split_list.back().size());\n\t\t\treturnList[curr_slow_list_idx].setOffsetAt(currently_inPQ[curr_slow_list_idx],\n\t\t\t                                           current_split_offset);\n\t\t\t// add from the same list a replacement element\n\t\t\tpq.pop();\n\n\t\t\tinsert_in_pq(curr_slow_list_idx);\n\t\t}\n\t\t// check if further elements are equal\n\t\twhile (!pq.empty() && curr_split == pq.top().first) {\n\t\t\t++found_duplicates;\n\t\t\t// duplicate found - use the same offset value\n\t\t\tsize_t equal_in_tree_idx = pq.top().second;\n\t\t\t// the found value must have un-inserted elements\n\t\t\tassert(currently_inPQ[equal_in_tree_idx] < slow_split_list[equal_in_tree_idx].size());\n\t\t\treturnList[equal_in_tree_idx].setOffsetAt(currently_inPQ[equal_in_tree_idx],\n\t\t\t                                          current_split_offset);\n\t\t\tpq.pop();\n\t\t\t// insertion of replacement for equal_in_tree element\n\t\t\tinsert_in_pq(equal_in_tree_idx);\n\t\t}\n\t\t++current_split_offset;\n\t}\n\t{\n\t\tsize_t total_splits = slow_split_list.size() * slow_split_list.front().size();\n\t\tdouble duplicate_ratio =\n\t\t    static_cast<double>(found_duplicates) / static_cast<double>(total_splits);\n\t\tBOOST_LOG_SEV(logger, lg::notification)\n\t\t    << \"Done construction of FastSplitList. \" << found_duplicates << \" duplicates of \"\n\t\t    << total_splits << \" possible PllSplits. Duplicate ratio: \" << duplicate_ratio\n\t\t    << \" Number of unique splits: \" << unique_pll_splits.size();\n\t}\n\t// unique_pll_splits will no longer reallocate -> write base-ptr to Static variable\n\tFastSplitList::setBasePtr(&unique_pll_splits[0]);\n\treturn returnList;\n}\n\nSymmetricMatrix<GeneralizedRfAlgo::Scalar> GeneralizedRfAlgo::calcPairwiseSplitScores() {\n\tassert(!unique_pll_splits.empty());\n\tfactorials.reserve(taxa + taxa + 4);\n\n\tsize_t split_num = unique_pll_splits.size();\n\tSymmetricMatrix<Scalar> resMtx(split_num);\n\tfor (size_t row = 0; row < split_num; ++row) {\n\t\tauto &rSplit = unique_pll_splits[row];\n\t\t// let the split know, which index it is. -> should happen once per PllSplit\n\t\trSplit.setIntersectionIdx(row);\n\t\tfor (size_t col = 0; col < row; ++col) {\n\t\t\tauto &cSplit = unique_pll_splits[col];\n\t\t\tresMtx.set_at(row, col, calc_split_score(rSplit, cSplit));\n\t\t}\n\t\tresMtx.set_at(row, row, calc_split_score(rSplit));\n\t}\n\treturn resMtx;\n}\n", "meta": {"hexsha": "1451554eb07d095c1f1874fe73afbac2687da3cf", "size": 12632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rf/GeneralizedRfAlgo.cpp", "max_stars_repo_name": "DoktorBotti/RF_Metrics", "max_stars_repo_head_hexsha": "07b65723939b536883373b755a052f511c1c4f90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-03T07:54:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T02:23:49.000Z", "max_issues_repo_path": "src/rf/GeneralizedRfAlgo.cpp", "max_issues_repo_name": "DoktorBotti/RF_Metrics", "max_issues_repo_head_hexsha": "07b65723939b536883373b755a052f511c1c4f90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rf/GeneralizedRfAlgo.cpp", "max_forks_repo_name": "DoktorBotti/RF_Metrics", "max_forks_repo_head_hexsha": "07b65723939b536883373b755a052f511c1c4f90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5987460815, "max_line_length": 98, "alphanum_fraction": 0.6884895503, "num_tokens": 3389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.754914997895581, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.4039538291205872}}
{"text": "/*****************************************************************************/\n/*  Copyright (c) 2016, Alessandro Pieropan                                  */\n/*  All rights reserved.                                                     */\n/*                                                                           */\n/*  Redistribution and use in source and binary forms, with or without       */\n/*  modification, are permitted provided that the following conditions       */\n/*  are met:                                                                 */\n/*                                                                           */\n/*  1. Redistributions of source code must retain the above copyright        */\n/*  notice, this list of conditions and the following disclaimer.            */\n/*                                                                           */\n/*  2. Redistributions in binary form must reproduce the above copyright     */\n/*  notice, this list of conditions and the following disclaimer in the      */\n/*  documentation and/or other materials provided with the distribution.     */\n/*                                                                           */\n/*  3. Neither the name of the copyright holder nor the names of its         */\n/*  contributors may be used to endorse or promote products derived from     */\n/*  this software without specific prior written permission.                 */\n/*                                                                           */\n/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS      */\n/*  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT        */\n/*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR    */\n/*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT     */\n/*  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,   */\n/*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT         */\n/*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,    */\n/*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY    */\n/*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT      */\n/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE    */\n/*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.     */\n/*****************************************************************************/\n\n#include \"opencv2/video/tracking.hpp\"\n#include \"opencv2/highgui/highgui.hpp\"\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <random>\n#include <cmath>\n\n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\ndouble deg2rad(double deg) {\n    return deg * M_PI / 180.0;\n}\n\n\n\ntemplate <typename T>\nstring toString(Mat& mat) {\n  stringstream ss;\n  ss << fixed << setprecision(3);\n  for (auto i = 0; i < mat.rows; ++i) {\n    for (auto j = 0; j < mat.cols; ++j) {\n      ss << mat.at<T>(i, j) << \" \";\n    }\n    ss << \"\\n\";\n  }\n\n  return ss.str();\n}\n\nvoid printKalman(KalmanFilter& kf) {\n  ofstream file(\"/home/alessandro/debug/pkf.txt\");\n\n  Mat prediction = kf.predict();\n\n  file << \"transition matrix: \" << toString<float>(kf.transitionMatrix) << \"\\n\"\n       << \"post \" << toString<float>(kf.statePost) << \"\\n\"\n       << \"predict \" << toString<float>(prediction) << endl;\n\n  Mat_<float> measurement(6, 1);\n  measurement(0) = 0.01;\n  measurement(1) = 0;\n  measurement(2) = 0;\n  measurement(3) = 0;\n  measurement(4) = 0;\n  measurement(5) = 0;\n\n  Mat estimated = kf.correct(measurement);\n\n  file << \"measurements: \" << toString<float>(measurement) << \"\\n\"\n       << \"post \" << toString<float>(kf.statePost) << \"\\n\"\n       << \"estimated \" << toString<float>(estimated) << endl;\n\n  file.close();\n\n}\n\nKalmanFilter initKalmanPose() {\n  KalmanFilter kalman_pose_pnp_(18, 6);\n\n  Mat A = Mat::eye(18, 18, CV_32FC1);\n\n  double dt = 1;\n\n  for (auto i = 0; i < 9; ++i) {\n    auto id_vel = i + 3;\n    auto id_acc = i + 6;\n    auto id_vel2 = i + 12;\n    auto id_acc2 = i + 15;\n\n    if (id_vel < 9) A.at<float>(i, id_vel) = dt;\n    if (id_acc < 9) A.at<float>(i, id_acc) = 0.5 * dt * dt;\n    if (id_vel2 < 18) A.at<float>(i + 9, id_vel2) = dt;\n    if (id_acc2 < 18) A.at<float>(i + 9, id_acc2) = 0.5 * dt * dt;\n  }\n\n  kalman_pose_pnp_.transitionMatrix = A.clone();\n\n  kalman_pose_pnp_.measurementMatrix.at<float>(0, 0) = 1;\n  kalman_pose_pnp_.measurementMatrix.at<float>(1, 1) = 1;\n  kalman_pose_pnp_.measurementMatrix.at<float>(2, 2) = 1;\n  kalman_pose_pnp_.measurementMatrix.at<float>(3, 9) = 1;\n  kalman_pose_pnp_.measurementMatrix.at<float>(4, 10) = 1;\n  kalman_pose_pnp_.measurementMatrix.at<float>(5, 11) = 1;\n\n  setIdentity(kalman_pose_pnp_.processNoiseCov, Scalar::all(1e-1));\n  setIdentity(kalman_pose_pnp_.measurementNoiseCov, Scalar::all(1e-2));\n  setIdentity(kalman_pose_pnp_.errorCovPost, Scalar::all(.1));\n\n  kalman_pose_pnp_.measurementNoiseCov.at<float>(0, 0) = 5;\n  kalman_pose_pnp_.measurementNoiseCov.at<float>(1, 1) = 1;\n  kalman_pose_pnp_.measurementNoiseCov.at<float>(2, 2) = 1;\n  kalman_pose_pnp_.measurementNoiseCov.at<float>(3, 3) = 1;\n  kalman_pose_pnp_.measurementNoiseCov.at<float>(4, 4) = 1;\n  kalman_pose_pnp_.measurementNoiseCov.at<float>(5, 5) = 1;\n\n  kalman_pose_pnp_.statePre.at<float>(0) = 0;\n  kalman_pose_pnp_.statePre.at<float>(1) = 0;\n  kalman_pose_pnp_.statePre.at<float>(2) = 0;\n  kalman_pose_pnp_.statePre.at<float>(3) = 0;\n  kalman_pose_pnp_.statePre.at<float>(4) = 0;\n  kalman_pose_pnp_.statePre.at<float>(5) = 0;\n  kalman_pose_pnp_.statePre.at<float>(6) = 0;\n  kalman_pose_pnp_.statePre.at<float>(7) = 0;\n  kalman_pose_pnp_.statePre.at<float>(8) = 0;\n  kalman_pose_pnp_.statePre.at<float>(9) = 0;\n  kalman_pose_pnp_.statePre.at<float>(10) = 0;\n  kalman_pose_pnp_.statePre.at<float>(11) = 0;\n  kalman_pose_pnp_.statePre.at<float>(12) = 0;\n  kalman_pose_pnp_.statePre.at<float>(13) = 0;\n  kalman_pose_pnp_.statePre.at<float>(14) = 0;\n  kalman_pose_pnp_.statePre.at<float>(15) = 0;\n  kalman_pose_pnp_.statePre.at<float>(16) = 0;\n  kalman_pose_pnp_.statePre.at<float>(17) = 0;\n\n  return kalman_pose_pnp_;\n}\n\nvoid testKalmanPose()\n{\n\n    ofstream file(\"/home/alessandro/debug/pkf.txt\");\n    random_device rd;\n    default_random_engine dre(rd());\n\n    std::uniform_real_distribution<float> dist(0, 1);\n\n    float tx = 1;\n    float tx_acc =0;\n    float rx_acc = 0;\n    float rx = deg2rad(2);\n\n    uniform_real_distribution<float> deg_dist(0, rx/4);\n\n    KalmanFilter kfp = initKalmanPose();\n\n    file << toString<float>(kfp.measurementNoiseCov) << \"\\n\";\n\n    for(auto i = 0; i < 5; ++i)\n    {\n        float val = dist(dre);\n\n        tx_acc += val + tx;\n        rx_acc += rx + deg_dist(dre);\n\n        Mat_<float> measurement(6, 1);\n        measurement(0) = tx_acc;\n        measurement(1) = 0;\n        measurement(2) = 0;\n        measurement(3) = 0;\n        measurement(4) = 0;\n        measurement(5) = rx_acc;\n\n        Mat predictions = kfp.predict();\n        Mat corrections = kfp.correct(measurement);\n        Mat pred_t, mea_t, corr_t;\n        transpose(predictions, pred_t);\n        transpose(corrections, corr_t);\n        transpose(measurement, mea_t);\n\n        file << \"predictions \\n\" << toString<float>(pred_t);\n        file << \"measurements \\n\" << toString<float>(mea_t);\n        file << \"corrections \\n\" << toString<float>(corr_t) << \"\\n\";\n    }\n\n    file.close();\n\n}\n\nvoid test_eigen() {\n  Matrix3f m;\n\n  m(0,0) = 1;\n  m(0,1) = -0.001;\n  m(0,2) = 0.006;\n\n  m(1,0) = 0.001;\n  m(1,1) = 1;\n  m(1,2) = -0.001;\n\n  m(2,0) = -0.006;\n  m(2,1) = 0.001;\n  m(2,2) = 1;\n\n\n  cout << \"original rotation:\" << endl;\n  cout << m << endl << endl;\n\n  Vector3f ea = m.eulerAngles(2, 1, 0);\n  cout << \"to Euler angles:\" << endl;\n  cout << ea << endl << endl;\n\n  Matrix3f n;\n  n = AngleAxisf(ea[0], Vector3f::UnitZ()) *\n      AngleAxisf(ea[1], Vector3f::UnitY()) *\n      AngleAxisf(ea[2], Vector3f::UnitX());\n  cout << \"recalc original rotation:\" << endl;\n  cout << n << endl;\n}\n\nfloat mouse_x, mouse_y;\n\nvoid CallBackFunc(int event, int x, int y, int flags, void* userdata) {\n  if (event == EVENT_LBUTTONDOWN) {\n    //cout << \"Left button of the mouse is clicked - position (\" << x << \", \" << y\n    //     << \")\" << endl;\n  } else if (event == EVENT_RBUTTONDOWN) {\n    //cout << \"Right button of the mouse is clicked - position (\" << x << \", \"\n    //     << y << \")\" << endl;\n  } else if (event == EVENT_MBUTTONDOWN) {\n    //cout << \"Middle button of the mouse is clicked - position (\" << x << \", \"\n    //     << y << \")\" << endl;\n  } else if (event == EVENT_MOUSEMOVE) {\n//    cout << \"Mouse move over the window - position (\" << x << \", \" << y << \")\"\n//         << endl;\n    mouse_x = x;\n    mouse_y = y;\n  }\n}\n\nint main(int argc, char** argv) {\n\n    //testKalmanPose();\n\n    //test_eigen();\n\n  KalmanFilter KF(4, 2, 0);\n  KF.transitionMatrix =\n      *(Mat_<float>(4, 4) << 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1);\n\n  Mat_<float> measurement(2, 1);\n  measurement.setTo(Scalar(0));\n\n  // init...\n  KF.statePre.at<float>(0) = 320;\n  KF.statePre.at<float>(1) = 240;\n  KF.statePre.at<float>(2) = 0;\n  KF.statePre.at<float>(3) = 0;\n  setIdentity(KF.measurementMatrix);\n  setIdentity(KF.processNoiseCov, Scalar::all(1e-4));\n  setIdentity(KF.measurementNoiseCov, Scalar::all(1e-1));\n  setIdentity(KF.errorCovPost, Scalar::all(.1));\n\n  cout << fixed << setprecision(2) << \"process noise cov \\n\"\n       << KF.processNoiseCov << \" \\n\"\n       << \"measurementNoiseCov \\n\" << KF.measurementNoiseCov << \"\\n\"\n       << \"errorCovPost \\n\" << KF.errorCovPost << endl;\n\n  return 0;\n\n  // Create a window\n  namedWindow(\"Kalman tutorial\", 1);\n\n  // set the callback function for any mouse event\n  setMouseCallback(\"Kalman tutorial\", CallBackFunc, NULL);\n\n  Mat res_image(480, 640, CV_8UC3, Scalar(0, 0, 0));\n\n  mouse_x = 320;\n  mouse_y = 240;\n\n  vector<Point> mouse_line;\n  vector<Point> estimated_line;\n\n  bool running = true;\n  while (running) {\n    Mat res_image(480, 640, CV_8UC3, Scalar(0, 0, 0));\n\n    // First predict, to update the internal statePre variable\n    Mat prediction = KF.predict();\n    Point predictPt(prediction.at<float>(0), prediction.at<float>(1));\n\n    // Get mouse point\n    measurement(0) = mouse_x;\n    measurement(1) = mouse_y;\n\n    Point measPt(measurement(0), measurement(1));\n\n    // The \"correct\" phase that is going to use the predicted value and our\n    // measurement\n    Mat estimated = KF.correct(measurement);\n    Point statePt(estimated.at<float>(0), estimated.at<float>(1));\n\n    mouse_line.push_back(measPt);\n    estimated_line.push_back(statePt);\n\n    if (mouse_line.size() > 0) {\n      polylines(res_image, mouse_line, false, Scalar(255, 0, 0));\n      polylines(res_image, estimated_line, false, Scalar(0, 255, 0));\n    }\n\n    // circle(res_image, measPt, 1, Scalar(255,0,0), -1);\n    // circle(res_image, statePt, 1, Scalar(0,255,0), -1);\n\n    imshow(\"Kalman tutorial\", res_image);\n\n    auto c = waitKey(100);\n\n    if (c == 'q') break;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "120d53b11c16b027b2999f76cb06fc0d08b95a00", "size": 11049, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tracker_tests/src/kalman_filter.cpp", "max_stars_repo_name": "clickcao/fato", "max_stars_repo_head_hexsha": "d2de665e83f82ea1094f488102aba37a8cdd53bb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-31T04:11:32.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-31T04:11:32.000Z", "max_issues_repo_path": "tracker_tests/src/kalman_filter.cpp", "max_issues_repo_name": "clickcao/fato", "max_issues_repo_head_hexsha": "d2de665e83f82ea1094f488102aba37a8cdd53bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tracker_tests/src/kalman_filter.cpp", "max_forks_repo_name": "clickcao/fato", "max_forks_repo_head_hexsha": "d2de665e83f82ea1094f488102aba37a8cdd53bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4017595308, "max_line_length": 82, "alphanum_fraction": 0.5914562404, "num_tokens": 3231, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.4039538232195469}}
{"text": "// from ros-control meta packages\n#include <controller_interface/controller.h>\n#include <hardware_interface/joint_command_interface.h>\n\n#include <pluginlib/class_list_macros.h>\n#include <std_msgs/Float64MultiArray.h>\n\n#include <urdf/model.h>\n\n#include <Eigen/LU>\n// from kdl packages\n#include <kdl/tree.hpp>\n#include <kdl/kdl.hpp>\n#include <kdl/chain.hpp>\n#include <kdl_parser/kdl_parser.hpp>\n#include <kdl/chaindynparam.hpp>              // inverse dynamics\n#include <kdl/jntarrayacc.hpp>\n#include <kdl/jntarray.hpp>\n#include <math.h>\n#include <numeric>\n#include <kdl/chainjnttojacsolver.hpp>\n#include <kdl/chainfksolver.hpp>\n#include <kdl/chainfksolverpos_recursive.hpp>\n#include <kdl/chainfksolvervel_recursive.hpp>\n#include <kdl/framevel.hpp>\n\n#include <boost/scoped_ptr.hpp>\n#include <boost/lexical_cast.hpp>\n\n#define PI 3.141592\n#define D2R PI / 180.0\n#define R2D 180.0 / PI\n#define SaveDataMax 49\n\nnamespace arm_controllers\n{\nclass GravityControllerReactive : public controller_interface::Controller<hardware_interface::EffortJointInterface>\n{\n  public:\n    bool init(hardware_interface::EffortJointInterface *hw, ros::NodeHandle &n)\n    {\n        // ********* 1. Get joint name / gain from the parameter server *********\n        // 1.1 Joint Name\n        if (!n.getParam(\"joints\", joint_names_))\n        {\n            ROS_ERROR(\"Could not find joint name\");\n            return false;\n        }\n        n_joints_ = joint_names_.size();\n\n        if (n_joints_ == 0)\n        {\n            ROS_ERROR(\"List of joint names is empty.\");\n            return false;\n        }\n        else\n        {\n            ROS_INFO(\"Found %d joint names\", n_joints_);\n            for (int i = 0; i < n_joints_; i++)\n            {\n                ROS_INFO(\"%s\", joint_names_[i].c_str());\n            }\n        }\n\n        // 1.2 Gain\n        // 1.2.1 Joint Controller\n        Kp_.resize(n_joints_);\n        Kd_.resize(n_joints_);\n        Ki_.resize(n_joints_);\n        seg_jac_1.resize(1);\n        seg_jac_2.resize(2);\n        seg_jac_3.resize(3);\n        seg_jac_4.resize(4);\n        seg_jac_5.resize(5);\n        J_.resize(n_joints_);\n        K_kine_.resize(n_joints_);\n        K_kine_.data(0) = 1.0;\n        K_kine_.data(1) = 1.0;\n        K_kine_.data(2) = 1.0;\n        K_kine_.data(3) = 1.0;\n        K_kine_.data(4) = 1.0;\n        K_kine_.data(5) = 1.0;\n\n        std::vector<double> Kp(n_joints_), Ki(n_joints_), Kd(n_joints_);\n        for (size_t i = 0; i < n_joints_; i++)\n        {\n            std::string si = boost::lexical_cast<std::string>(i + 1);\n            if (n.getParam(\"/elfin/gravity_controller_reactive/gains/elfin_joint\" + si + \"/pid/p\", Kp[i]))\n            {\n                Kp_(i) = Kp[i];\n            }\n            else\n            {\n                std::cout << \"/elfin/gravity_controller_reactive/gains/elfin_joint\" + si + \"/pid/p\" << std::endl;\n                ROS_ERROR(\"Cannot find pid/p gain\");\n                return false;\n            }\n\n            if (n.getParam(\"/elfin/gravity_controller_reactive/gains/elfin_joint\" + si + \"/pid/i\", Ki[i]))\n            {\n                Ki_(i) = Ki[i];\n            }\n            else\n            {\n                ROS_ERROR(\"Cannot find pid/i gain\");\n                return false;\n            }\n\n            if (n.getParam(\"/elfin/gravity_controller_reactive/gains/elfin_joint\" + si + \"/pid/d\", Kd[i]))\n            {\n                Kd_(i) = Kd[i];\n            }\n            else\n            {\n                ROS_ERROR(\"Cannot find pid/d gain\");\n                return false;\n            }\n        }\n\n        // 2. ********* urdf *********\n        urdf::Model urdf;\n        if (!urdf.initParam(\"robot_description\"))\n        {\n            ROS_ERROR(\"Failed to parse urdf file\");\n            return false;\n        }\n        else\n        {\n            ROS_INFO(\"Found robot_description\");\n        }\n\n        // 3. ********* Get the joint object to use in the realtime loop [Joint Handle, URDF] *********\n        for (int i = 0; i < n_joints_; i++)\n        {\n            try\n            {\n                joints_.push_back(hw->getHandle(joint_names_[i]));\n            }\n            catch (const hardware_interface::HardwareInterfaceException &e)\n            {\n                ROS_ERROR_STREAM(\"Exception thrown: \" << e.what());\n                return false;\n            }\n\n            urdf::JointConstSharedPtr joint_urdf = urdf.getJoint(joint_names_[i]);\n            if (!joint_urdf)\n            {\n                ROS_ERROR(\"Could not find joint '%s' in urdf\", joint_names_[i].c_str());\n                return false;\n            }\n            joint_urdfs_.push_back(joint_urdf);\n        }\n\n        // 4. ********* KDL *********\n        // 4.1 kdl parser\n        if (!kdl_parser::treeFromUrdfModel(urdf, kdl_tree_))\n        {\n            ROS_ERROR(\"Failed to construct kdl tree\");\n            return false;\n        }\n        else\n        {\n            ROS_INFO(\"Constructed kdl tree\");\n        }\n\n        // 4.2 kdl chain\n        std::string root_name, tip_name;\n        if (!n.getParam(\"root_link\", root_name))\n        {\n            ROS_ERROR(\"Could not find root link name\");\n            return false;\n        }\n        if (!n.getParam(\"tip_link\", tip_name))\n        {\n            ROS_ERROR(\"Could not find tip link name\");\n            return false;\n        }\n        if (!kdl_tree_.getChain(root_name, tip_name, kdl_chain_))\n        {\n            ROS_ERROR_STREAM(\"Failed to get KDL chain from tree: \");\n            ROS_ERROR_STREAM(\"  \" << root_name << \" --> \" << tip_name);\n            ROS_ERROR_STREAM(\"  Tree has \" << kdl_tree_.getNrOfJoints() << \" joints\");\n            ROS_ERROR_STREAM(\"  Tree has \" << kdl_tree_.getNrOfSegments() << \" segments\");\n            ROS_ERROR_STREAM(\"  The segments are:\");\n\n            KDL::SegmentMap segment_map = kdl_tree_.getSegments();\n            KDL::SegmentMap::iterator it;\n\n            for (it = segment_map.begin(); it != segment_map.end(); it++)\n                ROS_ERROR_STREAM(\"    \" << (*it).first);\n\n            return false;\n        }\n        else\n        {\n            ROS_INFO(\"Got kdl chain\");\n        }\n\n        // 4.3 inverse dynamics solver 초기화\n        gravity_ = KDL::Vector::Zero(); // ?\n        gravity_(2) = -9.81;            // 0: x-axis 1: y-axis 2: z-axis\n\n        id_solver_.reset(new KDL::ChainDynParam(kdl_chain_, gravity_));\n        FKSolver_.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_));\n        FKSolver_vel_.reset(new KDL::ChainFkSolverVel_recursive(kdl_chain_));\n        jnt_to_jac_solver_.reset(new KDL::ChainJntToJacSolver(kdl_chain_));\n\n        kdl_tree_.getChain(\"world\", \"elfin_link1\", kdl_chain_1);\n        jac_solver_1.reset(new KDL::ChainJntToJacSolver(kdl_chain_1));\n        fk_solver_1.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_1));\n\n        kdl_tree_.getChain(\"world\", \"elfin_link2\", kdl_chain_2);\n        jac_solver_2.reset(new KDL::ChainJntToJacSolver(kdl_chain_2));\n        fk_solver_2.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_2));\n\n        kdl_tree_.getChain(\"world\", \"elfin_link3\", kdl_chain_3);\n        jac_solver_3.reset(new KDL::ChainJntToJacSolver(kdl_chain_3));\n        fk_solver_3.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_3));\n\n        kdl_tree_.getChain(\"world\", \"elfin_link4\", kdl_chain_4);\n        jac_solver_4.reset(new KDL::ChainJntToJacSolver(kdl_chain_4));\n        fk_solver_4.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_4));\n\n        kdl_tree_.getChain(\"world\", \"elfin_link5\", kdl_chain_5);\n        jac_solver_5.reset(new KDL::ChainJntToJacSolver(kdl_chain_5));\n        fk_solver_5.reset(new KDL::ChainFkSolverPos_recursive(kdl_chain_5));\n\n\n\n\n        // ********* 5. 각종 변수 초기화 *********\n\n        // 5.1 Vector 초기화 (사이즈 정의 및 값 0)\n        tau_d_.data = Eigen::VectorXd::Zero(n_joints_);\n\n        qd_.data = Eigen::VectorXd::Zero(n_joints_);\n        qd_dot_.data = Eigen::VectorXd::Zero(n_joints_);\n        qd_ddot_.data = Eigen::VectorXd::Zero(n_joints_);\n        qd_old_.data = Eigen::VectorXd::Zero(n_joints_);\n\n        q_.data = Eigen::VectorXd::Zero(n_joints_);\n        qdot_.data = Eigen::VectorXd::Zero(n_joints_);\n        xdot_.data = Eigen::VectorXd::Zero(n_joints_);\n        ex_ = Eigen::VectorXd::Zero(n_joints_);\n        jnt_limits_lower_.data = Eigen::VectorXd::Zero(n_joints_);\n        jnt_limits_upper_.data = Eigen::VectorXd::Zero(n_joints_);\n        diff_to_low_.data = Eigen::VectorXd::Zero(n_joints_);\n        diff_to_low_prev_.data = Eigen::VectorXd::Zero(n_joints_);\n        diff_to_upper_.data = Eigen::VectorXd::Zero(n_joints_);\n        diff_to_upper_prev_.data = Eigen::VectorXd::Zero(n_joints_);\n        ex_obstacle_prev_ = Eigen::VectorXd::Zero(n_joints_);\n\n        obstacle_.p(0) = -0.1;\n        obstacle_.p(1) = -0.1;\n        obstacle_.p(2) = 0.75;\n        obstacle_.M.RPY(0,0,0);\n\n        jnt_limits_lower_(0) = -0.6;\n        jnt_limits_lower_(1) = -0.6;\n        jnt_limits_lower_(2) = -0.6;\n        jnt_limits_lower_(3) = -0.6;\n        jnt_limits_lower_(4) = -0.6;\n        jnt_limits_lower_(5) = -0.6;\n\n        jnt_limits_upper_(0) = 0.6;\n        jnt_limits_upper_(1) = 0.6;\n        jnt_limits_upper_(2) = 0.6;\n        jnt_limits_upper_(3) = 0.6;\n        jnt_limits_upper_(4) = 0.6;\n        jnt_limits_upper_(5) = 0.6;\n\n        table_corner_1 = KDL::Vector(-0.2, -0.25, 0.3);\n        table_corner_2 = KDL::Vector(-0.9, -0.25, 0.3);\n        table_corner_3 = KDL::Vector(-0.9, 0.25, 0.3);\n        table_corner_4 = KDL::Vector(-0.2, 0.25, 0.3);\n\n        interpolated_table_surface_.push_back(table_corner_1);\n        interpolated_table_surface_.push_back(table_corner_2);\n     //   interpolated_table_surface_.push_back(table_corner_3);\n     //   interpolated_table_surface_.push_back(table_corner_4);\n\n        int split_num = 30;\n        for(int i = 1; i < split_num; i++){\n            double diff12 = (table_corner_2(0) - table_corner_1(0)) * i/split_num;\n            interpolated_table_surface_.push_back(KDL::Vector(table_corner_1(0) + diff12, -0.25, 0.3));\n         //   double diff23 = (table_corner_3(1) - table_corner_2(1)) * i/split_num;\n         //   interpolated_table_surface_.push_back(KDL::Vector(-0.9, diff23, 0.5));\n         //   double diff34 = (table_corner_4(0) - table_corner_3(0)) * i/split_num;\n         //   interpolated_table_surface_.push_back(KDL::Vector(diff34, 0.25, 0.5));\n         //   double diff41 = (table_corner_1(1) - table_corner_4(1)) * i/split_num;\n         //   interpolated_table_surface_.push_back(KDL::Vector(-0.2, diff41, 0.5));\n        }\n        std::vector<KDL::Vector> tmp_copy = interpolated_table_surface_;\n        for(int i = 1; i < (int)tmp_copy.size(); i++){\n            double curr_x = tmp_copy[i](0);\n            for(int j = 0; j <= split_num; j++){\n                double next_y = tmp_copy[i](1) + 0.5*j/split_num;\n                interpolated_table_surface_.push_back(KDL::Vector(curr_x, next_y, 0.3));\n            }\n        }\n        std::cout << \"TABLE HAS: \" << interpolated_table_surface_.size() << std::endl;\n\n\n        for(int i = 1; i <= 5; i++){\n            KDL::JntArray arr;\n            arr.data = Eigen::VectorXd::Zero(i);\n            arm_segment_states_.push_back(arr);\n        }\n        std::cout << \"JntArrays done \" << std::endl;\n\n        e_.data = Eigen::VectorXd::Zero(n_joints_);\n        e_dot_.data = Eigen::VectorXd::Zero(n_joints_);\n        e_int_.data = Eigen::VectorXd::Zero(n_joints_);\n\n        // 5.2 Matrix 초기화 (사이즈 정의 및 값 0)\n        M_.resize(kdl_chain_.getNrOfJoints());\n        C_.resize(kdl_chain_.getNrOfJoints());\n        G_.resize(kdl_chain_.getNrOfJoints());\n     \n\n\n        // ********* 6. ROS 명령어 *********\n        // 6.1 publisher\n        pub_qd_ = n.advertise<std_msgs::Float64MultiArray>(\"qd\", 1000);\n        pub_q_ = n.advertise<std_msgs::Float64MultiArray>(\"q\", 1000);\n        pub_e_ = n.advertise<std_msgs::Float64MultiArray>(\"e\", 1000);\n\n        pub_SaveData_ = n.advertise<std_msgs::Float64MultiArray>(\"SaveData\", 1000); // 뒤에 숫자는?\n\n        // 6.2 subsriber\n\n        return true;\n    }\n\n    void commandCB(const std_msgs::Float64MultiArrayConstPtr &msg)\n    {\n        if (msg->data.size() != n_joints_)\n        {\n            ROS_ERROR_STREAM(\"Dimension of command (\" << msg->data.size() << \") does not match number of joints (\" << n_joints_ << \")! Not executing!\");\n            return;\n        }\n    }\n\n    void starting(const ros::Time &time)\n    {\n        t = 0.0;\n        ROS_INFO(\"Starting Reactive Controller\");\n    }\n\n    void update(const ros::Time &time, const ros::Duration &period)\n    {\n        // ********* 0. Get states from gazebo *********\n        // 0.1 sampling time\n        double dt = period.toSec();\n        t = t + 0.001;\n\n        // 0.2 joint state\n        for (int i = 0; i < n_joints_; i++)\n        {\n            q_(i) = joints_[i].getPosition();\n            qdot_(i) = joints_[i].getVelocity();\n        }\n\n        int segment_length = 1;\n        for(int i = 0; i < 5; i++){\n            for(int j = 1; j <= segment_length; j++){\n                arm_segment_states_[i](j) = q_(j);\n            }\n            segment_length++;\n        }\n\n\n\n        std::vector<KDL::Jacobian> jacobians_;\n        jac_solver_1->JntToJac(arm_segment_states_[0], seg_jac_1);\n        jacobians_.push_back(seg_jac_1);\n\n        jac_solver_2->JntToJac(arm_segment_states_[1], seg_jac_2);\n        jacobians_.push_back(seg_jac_2);\n\n        jac_solver_3->JntToJac(arm_segment_states_[2], seg_jac_3);\n        jacobians_.push_back(seg_jac_3);\n\n        jac_solver_4->JntToJac(arm_segment_states_[3], seg_jac_4);\n        jacobians_.push_back(seg_jac_4);\n\n        jac_solver_5->JntToJac(arm_segment_states_[4], seg_jac_5);\n        jacobians_.push_back(seg_jac_5);\n        \n\n\n        // ********* 1. Desired Trajecoty in Joint Space *********\n\n        for (size_t i = 0; i < n_joints_; i++)\n        {\n            qd_ddot_(i) = -M_PI * M_PI / 4 * 45 * KDL::deg2rad * sin(M_PI / 2 * t); \n            qd_dot_(i) = M_PI / 2 * 45 * KDL::deg2rad * cos(M_PI / 2 * t);\n            qd_(i) = 45 * KDL::deg2rad * sin(M_PI / 2* t);\n          //  continue;\n         //  \n            if( t < 1 ){\n                qd_(i) = 0;\n            }\n           // qd_(i) = 0;\n            qd_ddot_(i) = 0;\n            qd_dot_(i) = 0;\n\n            // This is the sequence to bring the arm to starting position.\n            if(t < 2){ \n               // qd_(i) = 0;\n                qd_(0) = -1.6;\n                qd_(1) = 0;\n                qd_(2) = -1.4; \n                qd_(3) = 0.01;\n                qd_(4) = -1.57;\n                qd_(5) = 0;\n            }\n\n\n            // This is the sweeping sequence.\n            if(t > 2){ \n          //     qd_(i) = 1.57;\n                //qd_(0) = q_(0) + dt*30;\n           //     qd_(0) += dt;\n             //   qd_(1) = 0;\n               // qd_(2) = -1.4; \n            //    qd_(3) = 0.01;\n              //  qd_(4) = -1.57;\n                //qd_(5) = 0;\n              //  qd_(1) = 35 * KDL::deg2rad * sin(M_PI / 2* t);\n            }\n            if(t < 1){ \n               // qd_(i) = 0;\n                qd_(0) = 0;\n                qd_(1) = 0;\n                qd_(2) = 0; \n                qd_(3) = 0.0;\n                qd_(4) = 0;\n                qd_(5) = 0;\n            }\n\n\n            // This is the sweeping sequence.\n            if(t > 1){ \n          //     qd_(i) = 1.57;\n                //qd_(0) = q_(0) + dt*30;\n                qd_(0) = 0;\n                //qd_(1) = 0;\n                //qd_(2) = 0; \n                qd_(1) = -55 * KDL::deg2rad * sin(M_PI * t);\n                qd_(2) = -55 * KDL::deg2rad * sin(M_PI * t);\n                qd_(3) = 0;\n                qd_(4) = 0;\n                qd_(5) = 0;\n\n            }\n\n        }\n\n        tau_rep_ = Eigen::VectorXd::Zero(n_joints_);\n\n        // *** 2.2.1 Compute model(M,C,G) ***\n        id_solver_->JntToMass(q_, M_);\n        id_solver_->JntToCoriolis(q_, qdot_, C_);\n        id_solver_->JntToGravity(q_, G_); \n\n\n        // Apply Joint limits as repulsive forces/torques\n        KDL::JntArray diff_q_;\n        Subtract(q_, qd_, diff_q_);\n        Subtract(q_, jnt_limits_lower_, diff_to_low_);\n        Subtract(q_, jnt_limits_upper_, diff_to_upper_);\n        \n //       Eigen::Matrix<double, 6, 1> U_att = (1/2) * diff_q_.data.cwiseProduct(diff_q_.data);\n //       Eigen::Matrix<double, 6, 1> U_rep_low_ = -(1/2) * diff_to_low_.data.cwiseProduct(diff_to_low_.data);\n //       Eigen::Matrix<double, 6, 1> U_rep_upper_ = -(1/2) * diff_to_upper_.data.cwiseProduct(diff_to_upper_.data);\n        \n\n\n        KDL::Frame xd_;\n        KDL::Frame x_up_lim_;\n        KDL::Frame x_low_lim_;\n        Eigen::Matrix<double, 6, 1> ex_low_;\n        Eigen::Matrix<double, 6, 1> ex_upper_;\n        Eigen::Matrix<double, 6, 1> ex_obstacle_;\n\n        jnt_to_jac_solver_->JntToJac(q_, J_);\n        FKSolver_->JntToCart(qd_, xd_);\n        FKSolver_->JntToCart(jnt_limits_lower_, x_low_lim_);\n        FKSolver_->JntToCart(jnt_limits_upper_, x_up_lim_);\n        FKSolver_->JntToCart(q_, x_);\n\n\n        // Calculate workspace positions for joints and middle parts of links.\n        std::vector<KDL::Frame> arm_segment_states_cart_;\n        std::vector<KDL::Frame> arm_segment_midpoints_states_cart_;\n\n\n\n        KDL::Frame seg_cart_;\n        fk_solver_1->JntToCart(arm_segment_states_[0], seg_cart_);\n        arm_segment_states_cart_.push_back(seg_cart_);\n        fk_solver_2->JntToCart(arm_segment_states_[1], seg_cart_);\n        arm_segment_states_cart_.push_back(seg_cart_);\n        fk_solver_3->JntToCart(arm_segment_states_[2], seg_cart_);\n        arm_segment_states_cart_.push_back(seg_cart_);\n        fk_solver_4->JntToCart(arm_segment_states_[3], seg_cart_);\n        arm_segment_states_cart_.push_back(seg_cart_);\n        fk_solver_5->JntToCart(arm_segment_states_[4], seg_cart_);\n        arm_segment_states_cart_.push_back(seg_cart_);\n\n\n\n\n        for(int i = 0; i < (int)arm_segment_states_cart_.size() - 1; i++){\n            KDL::Frame start_ = arm_segment_states_cart_[i];\n            KDL::Frame end_ = arm_segment_states_cart_[i+1];\n            KDL::Frame mid_point_;\n            mid_point_.p(0) = (start_.p(0) + end_.p(0)) / 2;\n            mid_point_.p(1) = (start_.p(1) + end_.p(1)) / 2;\n            mid_point_.p(2) = (start_.p(2) + end_.p(2)) / 2;\n            mid_point_.M.RPY(0,0,0);\n            arm_segment_midpoints_states_cart_.push_back(mid_point_);\n        }\n\n\n        ex_temp_ = diff(x_, xd_);\n\n        ex_(0) = ex_temp_(0);\n        ex_(1) = ex_temp_(1);\n        ex_(2) = ex_temp_(2);\n        ex_(3) = ex_temp_(3);\n        ex_(4) = ex_temp_(4);\n        ex_(5) = ex_temp_(5);\n\n        ex_temp_ = diff(x_, x_up_lim_);\n\n        ex_upper_(0) = ex_temp_(0);\n        ex_upper_(1) = ex_temp_(1);\n        ex_upper_(2) = ex_temp_(2);\n        ex_upper_(3) = ex_temp_(3);\n        ex_upper_(4) = ex_temp_(4);\n        ex_upper_(5) = ex_temp_(5);\n\n        ex_temp_ = diff(x_, x_low_lim_);\n\n        ex_low_(0) = ex_temp_(0);\n        ex_low_(1) = ex_temp_(1);\n        ex_low_(2) = ex_temp_(2);\n        ex_low_(3) = ex_temp_(3);\n        ex_low_(4) = ex_temp_(4);\n        ex_low_(5) = ex_temp_(5);\n\n        ex_obstacle_ = ex_obstacle_prev_;\n\n        ex_temp_ = diff(obstacle_, x_);\n\n        ex_obstacle_(0) = ex_temp_(0);\n        ex_obstacle_(1) = ex_temp_(1);\n        ex_obstacle_(2) = ex_temp_(2);\n        ex_obstacle_(3) = ex_temp_(3);\n        ex_obstacle_(4) = ex_temp_(4);\n        ex_obstacle_(5) = ex_temp_(5);\n\n        Eigen::Matrix<double, 6, 1> grad_D_ = ex_obstacle_ - ex_obstacle_prev_;\n\n     //   Eigen::Matrix<double, 6, 1> U_att = (1/2) * ex_.cwiseProduct(ex_);\n        Eigen::Matrix<double, 6, 1> U_rep_lower_ = -(1/2) * ex_low_.cwiseProduct(ex_low_);\n        Eigen::Matrix<double, 6, 1> U_rep_upper_ = -(1/2) * ex_upper_.cwiseProduct(ex_upper_);\n        Eigen::Matrix<double, 6, 1> U_rep_ = U_rep_lower_ + U_rep_upper_;\n\n\n       // Eigen::Matrix<double, 6, 1> F_att = -ex_;\n        Eigen::Matrix<double, 6, 1> F_rep_lower_; // = (1 / ex_low_) * (1 / ex_low_.cwiseProduct(ex_low_));\n        Eigen::Matrix<double, 6, 1> F_rep_upper_; // = (1 / ex_upper_) * (1 / ex_upper_.cwiseProduct(ex_upper_));\n        Eigen::Matrix<double, 6, 1> F_obstacle_;\n\n\n        // This is where the joint limits are applied.\n        double Q_star_ = 0.0;\n        \n        Eigen::Matrix<double, 6, 1> grad_D_low_ = diff_to_low_.data - diff_to_low_prev_.data;\n        Eigen::Matrix<double, 6, 1> grad_D_upper_ = diff_to_upper_.data - diff_to_upper_prev_.data;\n        for(int i = 0; i < 6; i++){\n\n            // UNCOMMENT THIS break to include joint limit forces.\n             break;\n            if( abs(diff_to_low_(i)) < Q_star_ ){\n                tau_rep_(i) += 0.001*(1 / diff_to_low_(i) - 1 / Q_star_) * (1 / diff_to_low_(i) - 1 / Q_star_);\n            }\n            if( abs(diff_to_upper_(i)) < Q_star_){\n                tau_rep_(i) += -0.001 * (1 / diff_to_upper_(i) - 1 / Q_star_) * (1 / diff_to_upper_(i) - 1 / Q_star_);\n            }\n        }\n        diff_to_low_prev_ = diff_to_low_;\n        diff_to_upper_prev_ = diff_to_upper_;\n\n\n\n\n\n        double Q_star_table_ = 0.22;\n        double closest_dist_ = 999;\n        int closest_idx_ = -2;\n        Eigen::Matrix<double, 6, 1> ex_table_point_ = Eigen::VectorXd::Zero(6);\n        Eigen::Matrix<double, 6, 1> ex_closest_table_point_ = Eigen::VectorXd::Zero(6);\n        Eigen::Matrix<double, 6, 1> F_rep_table_total_ = Eigen::VectorXd::Zero(6);\n\n\n        // Include repulsion field of the table WRT end effector only.\n        for(int i = 0; i < (int)interpolated_table_surface_.size(); i++){\n           // break;\n            KDL::Vector curr_table_point_ = interpolated_table_surface_[i];\n            ex_table_point_(0) = curr_table_point_(0) - x_.p(0);\n            ex_table_point_(1) = curr_table_point_(1) - x_.p(1);\n            ex_table_point_(2) = curr_table_point_(2) - x_.p(2);\n            table_point_distances_[i] = -ex_table_point_;\n\n            double dist = sqrt( ex_table_point_(0)*ex_table_point_(0) + ex_table_point_(1)*ex_table_point_(1) + ex_table_point_(2)*ex_table_point_(2));\n            if( dist < Q_star_table_ ){\n                closest_dist_ = dist;\n                closest_idx_ = i;\n                ex_closest_table_point_ = -ex_table_point_;\n                \n                Eigen::Matrix<double, 6, 1> grad_D_table_ = ex_table_point_ - table_point_distances_prev_[i];\n\n\n                F_rep_table_total_(0) = -0.1 * (1 / ex_table_point_(0) - 1 / Q_star_table_) * (1 / (ex_table_point_(0) * ex_table_point_(0)) * -grad_D_table_(0));\n                F_rep_table_total_(1) = -0.1 * (1 / ex_table_point_(1) - 1 / Q_star_table_) * (1 / (ex_table_point_(1) * ex_table_point_(1)) * -grad_D_table_(1));\n                F_rep_table_total_(2) = -10 * (1 / ex_table_point_(2) - 1 / Q_star_table_) * (1 / (ex_table_point_(2) * ex_table_point_(2)) * -grad_D_table_(2));\n                for(int f = 0; f < 3; f++){\n                    if( F_rep_table_total_(f) > 500 ){\n                        F_rep_table_total_(f) = 500;\n                    }\n                }\n                \n                // UNCOMMENT THIS to include the tables repulsion forces in the arm.\n               tau_rep_ += J_.data.transpose() * F_rep_table_total_;\n            }\n        }\n\n\n\n\n        // Include repulsion field of the table WRT all physical points of arm.\n        for(int i = 0; i < (int)interpolated_table_surface_.size(); i++){\n          // break;\n            KDL::Vector curr_table_point_ = interpolated_table_surface_[i];\n\n            for(int a = 1; a < (int)arm_segment_states_cart_.size(); a++ ){\n                KDL::Frame arm_point_ = arm_segment_states_cart_[a];\n                ex_table_point_(0) = curr_table_point_(0) - arm_point_.p(0);\n                ex_table_point_(1) = curr_table_point_(1) - arm_point_.p(1);\n                ex_table_point_(2) = curr_table_point_(2) - arm_point_.p(2);\n                table_point_distances_arm_[a][i] = -ex_table_point_;\n\n                double dist = sqrt( ex_table_point_(0)*ex_table_point_(0) + ex_table_point_(1)*ex_table_point_(1) + ex_table_point_(2)*ex_table_point_(2));\n                if( dist < Q_star_table_ ){\n\n                    closest_dist_ = dist;\n                    closest_idx_ = i;\n                    ex_closest_table_point_ = -ex_table_point_;\n\n                    std::cout << \"ROWS: \" << jacobians_[a].rows()  << \" COLUMNS: \" << jacobians_[a].columns() << std::endl;\n                    int c_size = jacobians_[a].columns();\n                    //Eigen::VectorXd F_rep_table_total_segs_ = Eigen::VectorXd::Zero(jacobians_[a].columns());\n                    Eigen::Matrix<double, 6, 1> grad_D_table_ = ex_table_point_ - table_point_distances_arm_prev_[a][i];\n\n                   // F_rep_table_total_(0) = -0.01 * (1 / ex_table_point_(0) - 1 / Q_star_table_) * (1 / (ex_table_point_(0) * ex_table_point_(0)) * -grad_D_table_(0));\n                   // F_rep_table_total_(1) = -0.01 * (1 / ex_table_point_(1) - 1 / Q_star_table_) * (1 / (ex_table_point_(1) * ex_table_point_(1)) * -grad_D_table_(1));\n                    F_rep_table_total_(2) = -1 * (1 / ex_table_point_(2) - 1 / Q_star_table_) * (1 / (ex_table_point_(2) * ex_table_point_(2)) * -grad_D_table_(2));\n                    for(int f = 0; f < 3; f++){\n                        if( F_rep_table_total_(f) > 1000 ){\n                            F_rep_table_total_(f) = 1000;\n                        }\n                    }\n                   std::cout << \"x: \" << F_rep_table_total_(0) << \" y: \" << F_rep_table_total_(1) << \" z: \"  << F_rep_table_total_(2) << std::endl;\n                // UNCOMMENT THIS to include the tables repulsion forces in the arm.\n                   Eigen::VectorXd torques = jacobians_[a].data.transpose() * F_rep_table_total_;\n                   for(int t = 0; t < c_size; t++){\n                      tau_rep_(t) += torques(t) - (M_.data * qdot_.data)(t);\n                   }\n                }\n            }\n        }\n        tau_rep_ -= M_.data * qdot_.data;\n        \n\n\n\n       // ex_table_prev_ = ex_closest_table_point_;\n        table_point_distances_prev_ = table_point_distances_;\n        table_point_distances_arm_prev_ = table_point_distances_arm_;\n\n        //Eigen::Matrix<double, 6, 1> F_rep_ = F_obstacle_;\n        Eigen::Matrix<double, 6, 1> F_rep_ = F_rep_table_total_;\n        F_rep_(3) = 0;\n        F_rep_(4) = 0;\n        F_rep_(5) = 0;\n       \n\n        // ********* 2. Motion Controller in Joint Space*********\n        // *** 2.1 Error Definition in Joint Space ***\n        e_.data = qd_.data - q_.data;\n        e_dot_.data = qd_dot_.data - qdot_.data;\n        e_int_.data = qd_.data - q_.data; // (To do: e_int 업데이트 필요요)\n\n\n        \n        // *** 2.2.2 gravity + PD as in slides ***\n\n        // This can be considered as u_att\n        tau_PD_grav_.data = G_.data + Kp_.data.cwiseProduct(e_.data) - Kd_.data.cwiseProduct(qdot_.data);\n\n        //tau_rep_ = J_.data.transpose() * F_rep_ - M_.data * qdot_.data; \n       // tau_rep_ = J_.data.transpose() * F_rep_ - Kd_.data.cwiseProduct(qdot_.data); \n        KDL::JntArray tau_total_;\n        tau_total_.data = tau_PD_grav_.data + tau_rep_;\n        \n        \n\n\n        // *** 2.3 Apply Torque Command to Actuator ***\n\n        // Use 'e_dot_.data = qdot_c_.data - qdot_.data' for kinematic controller. \n        // Otherwise use 'e_dot_.data = qd_dot_.data - qdot_.data'.\n        //e_dot_.data = qdot_c_.data - qdot_.data;\n        //aux_d_.data = M_.data * (qd_ddot_.data + Kd_.data.cwiseProduct(e_dot_.data));\n        //comp_d_.data = C_.data + G_.data;\n        //tau_d_.data = aux_d_.data + comp_d_.data;\n\n\n        for (int i = 0; i < n_joints_; i++)\n        {\n            joints_[i].setCommand(tau_total_(i));\n            //joints_[i].setCommand(tau_PD_grav_(i));\n            //joints_[i].setCommand(tau_d_(i));\n        }\n\n        // ********* 3. data 저장 *********\n        save_data();\n\n        // ********* 4. state 출력 *********\n        print_state();\n    }\n\n    void stopping(const ros::Time &time)\n    {\n    }\n\n    void save_data()\n    {\n        // 1\n        // Simulation time (unit: sec)\n        SaveData_[0] = t;\n\n        // Desired position in joint space (unit: rad)\n        SaveData_[1] = qd_(0);\n        SaveData_[2] = qd_(1);\n        SaveData_[3] = qd_(2);\n        SaveData_[4] = qd_(3);\n        SaveData_[5] = qd_(4);\n        SaveData_[6] = qd_(5);\n\n        // Desired velocity in joint space (unit: rad/s)\n        SaveData_[7] = qd_dot_(0);\n        SaveData_[8] = qd_dot_(1);\n        SaveData_[9] = qd_dot_(2);\n        SaveData_[10] = qd_dot_(3);\n        SaveData_[11] = qd_dot_(4);\n        SaveData_[12] = qd_dot_(5);\n\n        // Desired acceleration in joint space (unit: rad/s^2)\n        SaveData_[13] = qd_ddot_(0);\n        SaveData_[14] = qd_ddot_(1);\n        SaveData_[15] = qd_ddot_(2);\n        SaveData_[16] = qd_ddot_(3);\n        SaveData_[17] = qd_ddot_(4);\n        SaveData_[18] = qd_ddot_(5);\n\n        // Actual position in joint space (unit: rad)\n        SaveData_[19] = q_(0);\n        SaveData_[20] = q_(1);\n        SaveData_[21] = q_(2);\n        SaveData_[22] = q_(3);\n        SaveData_[23] = q_(4);\n        SaveData_[24] = q_(5);\n\n        // Actual velocity in joint space (unit: rad/s)\n        SaveData_[25] = qdot_(0);\n        SaveData_[26] = qdot_(1);\n        SaveData_[27] = qdot_(2);\n        SaveData_[28] = qdot_(3);\n        SaveData_[29] = qdot_(4);\n        SaveData_[30] = qdot_(5);\n\n        // Error position in joint space (unit: rad)\n        SaveData_[31] = e_(0);\n        SaveData_[32] = e_(1);\n        SaveData_[33] = e_(2);\n        SaveData_[34] = e_(3);\n        SaveData_[35] = e_(4);\n        SaveData_[36] = e_(5);\n\n        j1_avg.push_back(abs(R2D * e_(0)));\n        j2_avg.push_back(abs(R2D * e_(1)));\n        j3_avg.push_back(abs(R2D * e_(2)));\n        j4_avg.push_back(abs(R2D * e_(3)));\n        j5_avg.push_back(abs(R2D * e_(4)));\n        j6_avg.push_back(abs(R2D * e_(5)));\n\n        // Error velocity in joint space (unit: rad/s)\n        SaveData_[37] = e_dot_(0);\n        SaveData_[38] = e_dot_(1);\n        SaveData_[39] = e_dot_(3);\n        SaveData_[40] = e_dot_(4);\n        SaveData_[41] = e_dot_(5);\n        SaveData_[42] = e_dot_(6);\n\n\n        j1_vel_avg.push_back(abs(R2D * e_dot_(0)));\n        j2_vel_avg.push_back(abs(R2D * e_dot_(1)));\n        j3_vel_avg.push_back(abs(R2D * e_dot_(2)));\n        j4_vel_avg.push_back(abs(R2D * e_dot_(3)));\n        j5_vel_avg.push_back(abs(R2D * e_dot_(4)));\n        j6_vel_avg.push_back(abs(R2D * e_dot_(5)));\n\n        // Error intergal value in joint space (unit: rad*sec)\n        SaveData_[43] = e_int_(0);\n        SaveData_[44] = e_int_(1);\n        SaveData_[45] = e_int_(2);\n        SaveData_[46] = e_int_(3);\n        SaveData_[47] = e_int_(4);\n        SaveData_[48] = e_int_(5);\n\n        // 2\n        msg_qd_.data.clear();\n        msg_q_.data.clear();\n        msg_e_.data.clear();\n\n        msg_SaveData_.data.clear();\n\n        // 3\n        for (int i = 0; i < n_joints_; i++)\n        {\n            msg_qd_.data.push_back(qd_(i));\n            msg_q_.data.push_back(q_(i));\n            msg_e_.data.push_back(e_(i));\n        }\n\n        for (int i = 0; i < SaveDataMax; i++)\n        {\n            msg_SaveData_.data.push_back(SaveData_[i]);\n        }\n\n        // 4\n        pub_qd_.publish(msg_qd_);\n        pub_q_.publish(msg_q_);\n        pub_e_.publish(msg_e_);\n\n        pub_SaveData_.publish(msg_SaveData_);\n    }\n\n    void print_state()\n    {\n        static int count = 0;\n        if (count > 99)\n        {\n            printf(\"*********************************************************\\n\\n\");\n            printf(\"*** Simulation Time (unit: sec)  ***\\n\");\n            printf(\"t = %f\\n\", t);\n            printf(\"\\n\");\n\n            printf(\"*** Desired State in Joint Space (unit: deg) ***\\n\");\n            printf(\"qd_(0): %f, \", qd_(0)*R2D);\n            printf(\"qd_(1): %f, \", qd_(1)*R2D);\n            printf(\"qd_(2): %f, \", qd_(2)*R2D);\n            printf(\"qd_(3): %f, \", qd_(3)*R2D);\n            printf(\"qd_(4): %f, \", qd_(4)*R2D);\n            printf(\"qd_(5): %f\\n\", qd_(5)*R2D);\n            printf(\"\\n\");\n\n            printf(\"*** Actual State in Joint Space (unit: deg) ***\\n\");\n            printf(\"q_(0): %f, \", q_(0) * R2D);\n            printf(\"q_(1): %f, \", q_(1) * R2D);\n            printf(\"q_(2): %f, \", q_(2) * R2D);\n            printf(\"q_(3): %f, \", q_(3) * R2D);\n            printf(\"q_(4): %f, \", q_(4) * R2D);\n            printf(\"q_(5): %f\\n\", q_(5) * R2D);\n            printf(\"\\n\");\n\n\n            printf(\"*** Joint Space Vel Error (unit: deg)  ***\\n\");\n            printf(\"%f, \", R2D * e_dot_(0));\n            printf(\"%f, \", R2D * e_dot_(1));\n            printf(\"%f, \", R2D * e_dot_(2));\n            printf(\"%f, \", R2D * e_dot_(3));\n            printf(\"%f, \", R2D * e_dot_(4));\n            printf(\"%f\\n\", R2D * e_dot_(5));\n            printf(\"\\n\");\n\n            int num_vals = j1_vel_avg.size(); \n            double average = 0.0;\n            if ( num_vals != 0) {\n                average = std::accumulate( j1_vel_avg.begin(), j1_vel_avg.end(), 0.0) / num_vals; \n                std::cout << \"JOINT VEL ERROR AVERAGES: \" << std::to_string(average) << \" - \";\n                average = 0.0;\n                average = std::accumulate( j2_vel_avg.begin(), j2_vel_avg.end(), 0.0) / num_vals; \n                std::cout << std::to_string(average) << \" - \";\n                average = 0.0;\n                average = std::accumulate( j3_vel_avg.begin(), j3_vel_avg.end(), 0.0) / num_vals; \n                std::cout << std::to_string(average) << \" - \";\n                average = 0.0;\n                average = std::accumulate( j4_vel_avg.begin(), j4_vel_avg.end(), 0.0) / num_vals; \n                std::cout << std::to_string(average) << \" - \";\n                average = 0.0;\n                average = std::accumulate( j5_vel_avg.begin(), j5_vel_avg.end(), 0.0) / num_vals; \n                std::cout << std::to_string(average) << \" - \";\n                average = 0.0;\n                average = std::accumulate( j6_vel_avg.begin(), j6_vel_avg.end(), 0.0) / num_vals; \n                std::cout << std::to_string(average) << std::endl;\n            }\n\n            count = 0;\n        }\n        count++;\n    }\n\n  private:\n    // others\n    double t;\n\n    //Joint handles\n    unsigned int n_joints_;                               // joint 숫자\n    std::vector<std::string> joint_names_;                // joint name ??\n    std::vector<hardware_interface::JointHandle> joints_; // ??\n    std::vector<urdf::JointConstSharedPtr> joint_urdfs_;  // ??\n\n    // kdl\n    KDL::Tree kdl_tree_;   // tree?\n    KDL::Chain kdl_chain_; // chain?\n\n    // kdl M,C,G\n    KDL::JntSpaceInertiaMatrix M_; // intertia matrix\n    KDL::JntSpaceInertiaMatrix M_inv_;\n    KDL::JntArray C_;              // coriolis\n    KDL::JntArray G_;              // gravity torque vector\n    KDL::Vector gravity_;\n\n    // kdl solver\n    boost::scoped_ptr<KDL::ChainDynParam> id_solver_;                  // Solver To compute the inverse dynamics\n\n    // Joint Space State\n    KDL::JntArray qd_, qd_dot_, qd_ddot_;\n    KDL::JntArray qd_old_;\n    KDL::JntArray q_, qdot_, qddot_;\n    KDL::JntArray e_, e_dot_, e_int_, e_ddot_;\n    KDL::Jacobian J_;\n    KDL::Jacobian seg_jac_1;\n    KDL::Jacobian seg_jac_2;\n    KDL::Jacobian seg_jac_3;\n    KDL::Jacobian seg_jac_4;\n    KDL::Jacobian seg_jac_5;\n    boost::scoped_ptr<KDL::ChainFkSolverPos>    FKSolver_;\n    boost::scoped_ptr<KDL::ChainFkSolverVel>  FKSolver_vel_;\n    boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_solver_; \n    boost::scoped_ptr<KDL::ChainJntToJacSolver> jac_solver_1;  \n    boost::scoped_ptr<KDL::ChainJntToJacSolver> jac_solver_2;  \n    boost::scoped_ptr<KDL::ChainJntToJacSolver> jac_solver_3;  \n    boost::scoped_ptr<KDL::ChainJntToJacSolver> jac_solver_4;  \n    boost::scoped_ptr<KDL::ChainJntToJacSolver> jac_solver_5; \n    boost::scoped_ptr<KDL::ChainFkSolverPos>    fk_solver_1; \n    boost::scoped_ptr<KDL::ChainFkSolverPos>    fk_solver_2; \n    boost::scoped_ptr<KDL::ChainFkSolverPos>    fk_solver_3; \n    boost::scoped_ptr<KDL::ChainFkSolverPos>    fk_solver_4; \n    boost::scoped_ptr<KDL::ChainFkSolverPos>    fk_solver_5;                     \n    KDL::JntArray  xdot_;\n    \n\n    // Input\n    KDL::JntArray aux_d_;\n    KDL::JntArray aux_d_Kpzero_;\n    KDL::JntArray comp_d_;\n    KDL::JntArray tau_d_;\n    KDL::JntArray tau_PD_grav_;\n    KDL::JntArray vel_control_;\n    KDL::JntArray kine_control_;\n    KDL::JntArray qdot_c_;\n    double rotX_pos, rotY_pos, rotZ_pos, rotW_pos, rotX_des, rotY_des, rotZ_des, rotW_des;\n\n\n    // Joint limits\n    KDL::JntArray jnt_limits_lower_;\n    KDL::JntArray jnt_limits_upper_;\n    KDL::JntArray diff_to_low_;\n    KDL::JntArray diff_to_upper_;\n    KDL::JntArray diff_to_low_prev_;\n    KDL::JntArray diff_to_upper_prev_;\n    KDL::Frame obstacle_;\n    std::vector<KDL::JntArray> arm_segment_states_;\n   \n\n    Eigen::Matrix<double, 6, 1> ex_obstacle_prev_;\n    Eigen::Matrix<double, 3, 1> ex_table_prev_;\n    KDL::Vector table_corner_1;\n    KDL::Vector table_corner_2;\n    KDL::Vector table_corner_3;\n    KDL::Vector table_corner_4;\n    std::vector<KDL::Vector> interpolated_table_surface_;\n    std::map<int, Eigen::Matrix<double, 6, 1>> table_point_distances_;\n    std::map<int, Eigen::Matrix<double, 6, 1>> table_point_distances_prev_;\n    std::map<int, std::map<int, Eigen::Matrix<double, 6, 1>>> table_point_distances_arm_;\n    std::map<int, std::map<int, Eigen::Matrix<double, 6, 1>>> table_point_distances_arm_prev_;\n    Eigen::Matrix<double ,6, 1> tau_rep_;\n    std::vector<boost::scoped_ptr<KDL::ChainJntToJacSolver>> jac_seg_solvers_;\n\n\n    // gains\n    KDL::JntArray Kp_, Ki_, Kd_, K_kine_;\n    KDL::Frame fKine_pos_Frame_;\n    KDL::Frame fKine_des_Frame_;\n    KDL::Twist ex_temp_;\n    Eigen::Matrix<double, 6, 1> ex_;\n    KDL::Frame x_;\n    KDL::FrameVel fKine_vel_Frame_;\n    KDL::JntArrayVel qdot_vel_array_;\n\n    KDL::Chain kdl_chain_1;\n    KDL::Chain kdl_chain_2;\n    KDL::Chain kdl_chain_3;\n    KDL::Chain kdl_chain_4;\n    KDL::Chain kdl_chain_5;\n\n\n\n    // save the data\n    double SaveData_[SaveDataMax];\n    std::vector<double> j1_avg;\n    std::vector<double> j2_avg;\n    std::vector<double> j3_avg;\n    std::vector<double> j4_avg;\n    std::vector<double> j5_avg;\n    std::vector<double> j6_avg;\n\n    std::vector<double> j1_vel_avg;\n    std::vector<double> j2_vel_avg;\n    std::vector<double> j3_vel_avg;\n    std::vector<double> j4_vel_avg;\n    std::vector<double> j5_vel_avg;\n    std::vector<double> j6_vel_avg;\n\n    // ros publisher\n    ros::Publisher pub_qd_, pub_q_, pub_e_;\n    ros::Publisher pub_SaveData_;\n\n    // ros message\n    std_msgs::Float64MultiArray msg_qd_, msg_q_, msg_e_;\n    std_msgs::Float64MultiArray msg_SaveData_;\n};\n}; // namespace arm_controllers\nPLUGINLIB_EXPORT_CLASS(arm_controllers::GravityControllerReactive, controller_interface::ControllerBase)\n", "meta": {"hexsha": "f1ffbabc6377d552f74001611a8e98b41f2c9c56", "size": 38806, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "arm_controllers/src/gravity_controller_reactive.cpp", "max_stars_repo_name": "AliZ-dev/AR-devUp", "max_stars_repo_head_hexsha": "c44becbb178ca9a04599d954d2f634560cd18c71", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-14T10:14:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-14T10:14:39.000Z", "max_issues_repo_path": "arm_controllers/src/gravity_controller_reactive.cpp", "max_issues_repo_name": "AliZ-dev/AR-devUp", "max_issues_repo_head_hexsha": "c44becbb178ca9a04599d954d2f634560cd18c71", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arm_controllers/src/gravity_controller_reactive.cpp", "max_forks_repo_name": "AliZ-dev/AR-devUp", "max_forks_repo_head_hexsha": "c44becbb178ca9a04599d954d2f634560cd18c71", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-30T14:17:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-30T14:17:03.000Z", "avg_line_length": 36.5404896422, "max_line_length": 169, "alphanum_fraction": 0.5551718806, "num_tokens": 11507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.40395381731850655}}
{"text": "// -*- mode: c++; indent-tabs-mode: nil; -*-\n//\n// Paragraph\n// Copyright (c) 2016-2019 Illumina, Inc.\n// All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// You may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//\t\thttp://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied\n// See the License for the specific language governing permissions and limitations\n//\n//\n\n#include \"genotyping/BreakpointGenotyper.hh\"\n#include \"common/Error.hh\"\n#include <algorithm>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/math/special_functions/binomial.hpp>\n#include <cmath>\n#include <limits>\n#include <math.h>\n#include <numeric>\n\nusing boost::math::normal_distribution;\nusing boost::math::poisson_distribution;\nusing std::map;\nusing std::vector;\n\nnamespace genotyping\n{\n\n/**\n * @param genotype_parameters GenotypeParameter class\n */\nBreakpointGenotyper::BreakpointGenotyper(std::unique_ptr<GenotypingParameters> const& param)\n    : n_alleles_(param->numAlleles())\n    , ploidy_(param->ploidy())\n    , coverage_test_cutoff_(param->coverageTestCutoff())\n    , min_pass_gq_(param->minPassGQ())\n    , min_overlap_bases_(param->minOverlapBases())\n    , possible_genotypes(param->possibleGenotypes())\n{\n    if (param->alleleErrorRates().empty())\n    {\n        allele_error_rate_.push_back(param->otherAlleleErrorRate());\n    }\n    else\n    {\n        allele_error_rate_ = param->alleleErrorRates();\n    }\n\n    if (param->hetHaplotypeFractions().empty())\n    {\n        haplotype_read_fraction_.push_back(param->otherHetHaplotypeFraction());\n    }\n    else\n    {\n        haplotype_read_fraction_ = param->hetHaplotypeFractions();\n    }\n\n    if (!param->genotypeFractions().empty())\n    {\n        genotype_prior_ = param->genotypeFractions();\n        for (auto& phi : genotype_prior_)\n        {\n            if (phi.first.size() < ploidy_)\n            {\n                error(\"Error: genotype and ploidy does not match.\");\n            }\n            if (phi.second < 0 || phi.second > 1)\n            {\n                error(\"Error: genotype prior should be between 0~1.\");\n            }\n            phi.second = log(phi.second);\n        }\n    }\n};\n\nGenotype BreakpointGenotyper::genotype(\n    const BreakpointGenotyperParameter& param, const std::vector<int32_t>& read_counts_per_allele) const\n{\n    if (read_counts_per_allele.size() != n_alleles_)\n    {\n        error(\n            \"Error: number of read counts and alleles mismatches. %i != %i.\", (int)read_counts_per_allele.size(),\n            n_alleles_);\n    }\n    Genotype result;\n\n    // compute adjusted depth\n    const double multiplier = (param.read_length - min_overlap_bases_) / (double)param.read_length;\n    assert(multiplier > 0);\n    const double lambda = param.read_depth * multiplier;\n    const int32_t total_num_reads = std::accumulate(read_counts_per_allele.begin(), read_counts_per_allele.end(), 0);\n    if (total_num_reads == 0)\n    {\n        result.filters.insert(\"NO_READS\");\n        return result;\n    }\n    result.num_reads = total_num_reads;\n\n    // compute GL and GT\n    double best_gl = -std::numeric_limits<double>::max();\n\n    for (const auto& igt : possible_genotypes)\n    {\n        const double gl = genotypeLikelihood(lambda, igt, read_counts_per_allele);\n        result.gl_name.push_back(igt);\n        result.gl.push_back(gl);\n\n        // update GT if GL is better\n        if (gl > best_gl)\n        {\n            best_gl = gl;\n            result.gt = igt;\n        }\n    }\n\n    // compute GQ and set filter\n    double sum_gl = 0;\n    for (auto l : result.gl)\n    {\n        sum_gl += exp(l);\n    }\n    double pr_gt_error = (double)1.0 - exp(best_gl) / sum_gl;\n    if (pr_gt_error == 0)\n    {\n        result.gq = 100;\n    }\n    else\n    {\n        double gq_log10 = log10(pr_gt_error);\n        if (gq_log10 < -10)\n        {\n            result.gq = 100;\n        }\n        else\n        {\n            result.gq = -10 * gq_log10;\n        }\n    }\n    if (result.gq < min_pass_gq_)\n    {\n        result.filters.insert(\"GQ\");\n    }\n\n    // compute allele fractions\n    result.allele_fractions.resize(n_alleles_, 0.0);\n    for (unsigned int al = 0; al < n_alleles_; ++al)\n    {\n        result.allele_fractions[al] = ((double)read_counts_per_allele[al]) / total_num_reads;\n    }\n\n    // compute coverage test p value\n    double coverage_test_pvalue;\n    if (param.use_poisson_depth) // use poisson test for depth (more stringent)\n    {\n        const poisson_distribution<> poisson_coverage_distribution(lambda);\n        coverage_test_pvalue = cdf(poisson_coverage_distribution, total_num_reads);\n    }\n    else // use normal test for depth (default)\n    {\n        const normal_distribution<> normal_coverage_distribution(lambda, param.depth_sd);\n        coverage_test_pvalue = cdf(normal_coverage_distribution, total_num_reads);\n    }\n\n    if (coverage_test_pvalue > 0.5)\n    {\n        coverage_test_pvalue = 1 - coverage_test_pvalue;\n        if (coverage_test_pvalue < coverage_test_cutoff_.first)\n        {\n            result.filters.insert(\"BP_DEPTH\");\n        }\n    }\n    else\n    {\n        if (coverage_test_pvalue < coverage_test_cutoff_.second)\n        {\n            result.filters.insert(\"BP_DEPTH\");\n        }\n    }\n    result.coverage_test_pvalue = coverage_test_pvalue;\n\n    return result;\n}\n\n/**\n * return genotype likelihood given genotype (using Poisson model with internal parameters)\n * @param lambda Poisson distribution parameter\n * @param gv Genotype vector\n * @param read_counts Read count vector for each allele\n */\ndouble BreakpointGenotyper::genotypeLikelihood(\n    double lambda, const GenotypeVector& gv, const vector<int32_t>& read_counts) const\n{\n    double log_phi;\n    auto it = genotype_prior_.find(gv);\n    if (it == genotype_prior_.end())\n    {\n        log_phi = 0;\n    }\n    else\n    {\n        log_phi = it->second;\n    }\n\n    // compute how many copies of each allele we have in this GT\n    vector<int> allele_ploidy;\n    allele_ploidy.resize(n_alleles_, 0);\n    for (unsigned int al = 0; al < n_alleles_; ++al)\n    {\n        for (const auto g : gv)\n        {\n            if (al == g)\n            {\n                ++allele_ploidy[al];\n            }\n        }\n    }\n\n    // compute GL by summing all allele contributions\n    double gl = log_phi;\n    for (unsigned int al = 0; al < n_alleles_; ++al)\n    {\n        if (allele_ploidy[al] == 0)\n        {\n            // no copies -> all reads supporting this allele will be errors\n            const double eps = (allele_error_rate_.size() == 1 ? allele_error_rate_[0] : allele_error_rate_[al]);\n            const poisson_distribution<> error_distribution(lambda * eps);\n            gl += log(pdf(error_distribution, read_counts[al]));\n        }\n        else\n        {\n            const double mu\n                = (haplotype_read_fraction_.size() == 1 ? haplotype_read_fraction_[0] : haplotype_read_fraction_[al]);\n            const double mu_with_ploidy = allele_ploidy[al] * mu;\n\n            const poisson_distribution<> allele_count_distribution(lambda * mu_with_ploidy);\n            gl += log(pdf(allele_count_distribution, read_counts[al]));\n        }\n        if (std::isinf(gl))\n        {\n            return -std::numeric_limits<double>::max();\n        }\n    }\n\n    return gl;\n}\n}\n", "meta": {"hexsha": "ee5b1ab7c36a48625bf74c23dfc5031d44074aae", "size": 7576, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/c++/lib/genotyping/BreakpointGenotyper.cpp", "max_stars_repo_name": "vb-wayne/paragraph", "max_stars_repo_head_hexsha": "3f6f6f7a2a3ac209c7dbb21487ca4d9eaed5c14c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 111.0, "max_stars_repo_stars_event_min_datetime": "2017-11-24T18:22:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T07:55:31.000Z", "max_issues_repo_path": "src/c++/lib/genotyping/BreakpointGenotyper.cpp", "max_issues_repo_name": "vb-wayne/paragraph", "max_issues_repo_head_hexsha": "3f6f6f7a2a3ac209c7dbb21487ca4d9eaed5c14c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2018-01-01T19:58:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T12:01:17.000Z", "max_forks_repo_path": "src/c++/lib/genotyping/BreakpointGenotyper.cpp", "max_forks_repo_name": "vb-wayne/paragraph", "max_forks_repo_head_hexsha": "3f6f6f7a2a3ac209c7dbb21487ca4d9eaed5c14c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2018-03-01T04:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T14:52:03.000Z", "avg_line_length": 29.4785992218, "max_line_length": 118, "alphanum_fraction": 0.6288278775, "num_tokens": 1863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4038238514306539}}
{"text": "#include <string>\n#include <sstream>\n#include <iostream>\n#include <vector>\n#include <list>\n#include <math.h>\n#include <vtkSmartPointer.h>\n#include <vtkPolyDataReader.h>\n#include <vtkPolyDataWriter.h>\n#include <vtkPolyData.h>\n#include <vtkCellData.h>\n#include <vtkPointData.h>\n#include <vtkCell.h>\n#include <vtkDoubleArray.h>\n#include <vtkKdTree.h>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n#include <omp.h>\n//#include \"HelperFunctions.h\"\n\nusing namespace std;\n//using namespace OPS;\n\ntypedef Eigen::Vector3d Vector3d;\n\n//! A struct to store a vtkIdType and an angle\nstruct neighbors{\n    vtkIdType _id;\n    double_t _angle;\n    neighbors(vtkIdType i, double_t a):_id(i), _angle(a){}\n    bool operator <(const neighbors &n) const{\n\treturn _angle < n._angle;\n    }\n};\n\nint main(int argc, char* argv[])\n{\n    if( argc != 5 ) {\n\tcout << \"argc = \" << argc << endl\n\t    << \"Usage: dualMesh baseName numStart numEnd numOPENMPThreads\"\n\t    << endl;\n\treturn(0);\n    }\n\n    ////////////////////////////////////////////////////////////////////\n    // Input section\n    ////////////////////////////////////////////////////////////////////\n\n    // read in vtk file\n    string baseFileName = argv[1];\n    size_t numStart = stoi(argv[2]);\n    size_t numEnd = stoi(argv[3]);\n    size_t numThreads = stoi(argv[4]);\n\n    //Set the number of threads\n    omp_set_num_threads(numThreads);\n\n#pragma omp parallel for\n    for(size_t bigI=numStart; bigI <= numEnd; bigI++){\n\tstringstream sstm;\n\tstring inputFileName, outFileName;\n\tsstm << baseFileName << \"-\" << bigI <<\".vtk\";\n\tinputFileName = sstm.str();\n\tsstm.str(\"\");\n\tsstm.clear();\n\n\tauto reader = vtkSmartPointer<vtkPolyDataReader>::New();\n\treader->SetFileName( inputFileName.c_str() );\n\treader->Update();\n\tvtkSmartPointer<vtkPolyData> inputMesh = reader->GetOutput();\n\tinputMesh->BuildLinks();\n\tsize_t npts = inputMesh->GetNumberOfPoints();\n\n\t//get displacement vectors, if they exist\n\tstring vectorName=\"displacements\";\n\tvtkSmartPointer<vtkDoubleArray> displacements =\n\t    vtkDoubleArray::SafeDownCast(inputMesh->GetPointData()->\n\t\t    GetVectors(vectorName.c_str()));\n\n\t// get vertex positions\n\tstd::vector< Vector3d > points( npts, Vector3d::Zero() );\n\n\t// Calculate centroid of each triangle while updating points vector\n\tauto newPts = vtkSmartPointer<vtkPoints>::New();\n\tvtkSmartPointer<vtkCellArray> cells = inputMesh->GetPolys();\n\tauto cellPointIds = vtkSmartPointer<vtkIdList>::New();\n\tcells->InitTraversal();\n\twhile( cells->GetNextCell( cellPointIds ) ){\n\t    size_t numCellPoints = cellPointIds->GetNumberOfIds();\n\t    Vector3d centroid(0.0,0.0,0.0);\n\t    for(size_t i=0; i < numCellPoints; i++){\n\t\tvtkIdType currCellPoint = cellPointIds->GetId(i);\n\t\tinputMesh->GetPoint( currCellPoint, &points[currCellPoint][0] );\n\t\tif( displacements.GetPointer() != NULL){\n\t\t    Vector3d currDisp(0.0,0.0,0.0);\n\t\t    displacements->GetTuple( currCellPoint, &currDisp[0] );\n\t\t    points[currCellPoint] += currDisp;\n\t\t}\n\t\tcentroid += points[currCellPoint];\n\t    }\n\t    centroid /= numCellPoints;\n\t    newPts->InsertNextPoint( &centroid[0] );\n\t}\n\n\t// Prepare valence Cell Data array\n\tauto valence = vtkSmartPointer<vtkIntArray>::New();\n\tvalence->SetName(\"Valence\");\n\tvalence->SetNumberOfComponents(1);\n\n\t// Prepare new cell array for polygons\n\tauto newPolys = vtkSmartPointer<vtkCellArray>::New();\n\n\tfor(size_t a=0; a < npts; a++) {\n\n\t    auto currPolyPtIds = vtkSmartPointer<vtkIdList>::New();\n\t    std::list< neighbors > currPoly;\n\t    Vector3d vec0, vecj, currCross, axis, centroid(0.0,0.0,0.0);\n\t    double vec0_norm, vecj_norm, sign, currSin, currCos, currAngle;\n\n\t    inputMesh->GetPointCells( a, currPolyPtIds );\n\t    size_t numCellPoints = currPolyPtIds->GetNumberOfIds();\n\n\t    // Get coordinates of first cell's centroid\n\t    vtkIdType currId = currPolyPtIds->GetId(0);\n\t    newPts->GetPoint( currId, &centroid[0] );\n\t    vec0 = (centroid - points[a]).normalized();\n\t    neighbors pt0(currId, 0.0);\n\t    currPoly.push_back( pt0 );\n\n\t    // For remaining centroids\n\t    for(auto j=1; j < numCellPoints; j++){\n\t\tcurrId = currPolyPtIds->GetId(j);\n\t\tnewPts->GetPoint( currId, &centroid[0] );\n\t\tvecj = (centroid - points[a]).normalized();\n\t\tcurrSin = (vec0.cross( vecj )).norm();\n\t\taxis = (vec0.cross( vecj )).normalized();\n\t\tsign = axis.dot( points[a] );\n\t\tcurrSin = (sign > 0.0) ? currSin : -1.0 * currSin;\n\t\tcurrCos = vec0.dot( vecj );\n\t\tcurrAngle = (180 / M_PI) * atan2(currSin, currCos);\n\t\tcurrAngle = (currAngle < 0) ? (360 + currAngle) : currAngle;\n\t\tneighbors ptj(currId, currAngle);\n\t\tcurrPoly.push_back(ptj);\n\t    }\n\n\t    //Sort the list of neigbors and make a polygon\n\t    currPoly.sort();\n\t    newPolys->InsertNextCell( numCellPoints );\n\t    for(auto t = currPoly.begin(); t != currPoly.end(); ++t){\n\t\tneighbors n = *t;\n\t\tnewPolys->InsertCellPoint( n._id );\n\t    }\n\t    valence->InsertNextTuple1( numCellPoints );\n\t}\n\n\t//Assign points and polygons to a new polydata and write it out\n\tauto newPolyData = vtkSmartPointer<vtkPolyData>::New();\n\tauto writer = vtkSmartPointer<vtkPolyDataWriter>::New();\n\n\tnewPolyData->SetPoints( newPts );\n\tnewPolyData->SetPolys( newPolys );\n\tnewPolyData->GetCellData()->AddArray( valence );\n\twriter->SetInputData( newPolyData );\n\tsstm << baseFileName << \"-dual-\" << bigI <<\".vtk\";\n\toutFileName = sstm.str();\n\tsstm.str(\"\");\n\tsstm.clear();\n\twriter->SetFileName(outFileName.c_str());\n\twriter->Write();\n    }\n    return 0;\n}\n", "meta": {"hexsha": "3c5852420135ef1b5998ae1a16dd123ba63745e0", "size": 5399, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "DualMesh.cxx", "max_stars_repo_name": "amit112amit/vtk-voronoi", "max_stars_repo_head_hexsha": "c3e1a6e3b0f80b96eb4e41822bd7286c4cb46e35", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T13:34:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-20T13:34:07.000Z", "max_issues_repo_path": "DualMesh.cxx", "max_issues_repo_name": "amit112amit/vtk-voronoi", "max_issues_repo_head_hexsha": "c3e1a6e3b0f80b96eb4e41822bd7286c4cb46e35", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DualMesh.cxx", "max_forks_repo_name": "amit112amit/vtk-voronoi", "max_forks_repo_head_hexsha": "c3e1a6e3b0f80b96eb4e41822bd7286c4cb46e35", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2080924855, "max_line_length": 72, "alphanum_fraction": 0.6641970735, "num_tokens": 1486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.40382385143065386}}
{"text": "////////////////////////////////////////////////////////////////////////////////\n//  Copyright (c) 2012 Zach Byerly\n//  Copyright (c) 2012 Bryce Adelstein-Lelbach\n//\n//  Distributed under the Boost Software License, Version 1.0. (See accompanying\n//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n////////////////////////////////////////////////////////////////////////////////\n\n#if !defined(OCTOPUS_9BA6055C_E7A9_4A16_8A24_B8B410AA1A14)\n#define OCTOPUS_9BA6055C_E7A9_4A16_8A24_B8B410AA1A14\n\n// http://www.vistrails.org/index.php/User:Tohline/Apps/PapaloizouPringleTori\n\n#include <octopus/state.hpp>\n#include <octopus/vector2d.hpp>\n#include <octopus/driver.hpp>\n#include <octopus/science.hpp>\n#include <octopus/engine/engine_interface.hpp>\n#include <octopus/engine/ini.hpp>\n#include <octopus/octree/octree_reduce.hpp>\n#include <octopus/octree/octree_apply_leaf.hpp>\n#include <octopus/math.hpp>\n#include <octopus/global_variable.hpp>\n#include <octopus/io/multi_writer.hpp>\n#include <octopus/io/fstream.hpp>\n\n#if defined(OCTOPUS_HAVE_SILO)\n    #include <octopus/io/silo.hpp>\n#endif\n\n#include <boost/format.hpp>\n#include <boost/atomic.hpp>\n#include <boost/math/constants/constants.hpp>\n\n#include <hpx/include/plain_actions.hpp>\n\n// FIXME: Move shared code from the drivers into a shared object/headers.\n// FIXME: Names.\n// FIXME: Proper configuration.\n// FIXME: Globals are bad mkay.\n\nenum rotational_direction\n{\n    rotate_clockwise,\n    rotate_counterclockwise\n};\n\nenum momentum_conservation\n{\n    angular_momentum_conservation,\n    cartesian_momentum_conservation\n};\n\n///////////////////////////////////////////////////////////////////////////////\ndouble const initial_cfl_factor = 1.0e-2;\n\ndouble const cfl_factor = 0.4;\n\n/// Gravitation constant.\ndouble const G = 1.0; \n\n/// Mass of the central object.\ndouble const M_C = 1.0;\n\n/// Outer radius of the torus.\ndouble const R_outer = 1.0;\n\n/// Polytropic index.\ndouble const gamma_ = 1.333; \n\ndouble const polytropic_n = 3.0;\n\n/// Amplitude of the perturbation.\ndouble const kick_amplitude = 1e-2;\n\n/// Angular speed of the frame, e.g. how fast the grid rotates.\nOCTOPUS_GLOBAL_VARIABLE((double), omega);\n\n/// Direction of the torus' rotation.\nOCTOPUS_GLOBAL_VARIABLE((rotational_direction), rot_dir);\n\n/// Advection scheme. \nOCTOPUS_GLOBAL_VARIABLE((momentum_conservation), mom_cons);\n\n/// If true, a rotating frame of reference is used. \nOCTOPUS_GLOBAL_VARIABLE((bool), rotating_grid);\n\n/// Polytropic constant.\nOCTOPUS_GLOBAL_VARIABLE((double), kappa);\n\n/// The ratio of the inner radius to the outer radius, e.g. the thinnness of the\n/// torus. \nOCTOPUS_GLOBAL_VARIABLE((double), X_in);\n\n/// Mode of the perturbation.\nOCTOPUS_GLOBAL_VARIABLE((boost::uint64_t), kick_mode);\n\n///////////////////////////////////////////////////////////////////////////////\n/// Mass density\ndouble&       rho(octopus::state& u)       { return u[0]; }\ndouble const& rho(octopus::state const& u) { return u[0]; }\n\n/// Momentum density (X-axis)\ndouble&       momentum_x(octopus::state& u)       { return u[1]; }\ndouble const& momentum_x(octopus::state const& u) { return u[1]; }\n\n/// Momentum density (Y-axis)\ndouble&       momentum_y(octopus::state& u)       { return u[2]; }\ndouble const& momentum_y(octopus::state const& u) { return u[2]; }\n\n/// Momentum density (Z-axis)\ndouble&       momentum_z(octopus::state& u)       { return u[3]; }\ndouble const& momentum_z(octopus::state const& u) { return u[3]; }\n\n/// Total energy of the gas \ndouble&       total_energy(octopus::state& u)       { return u[4]; }\ndouble const& total_energy(octopus::state const& u) { return u[4]; }\n\n/// Entropy tracer\ndouble&       tau(octopus::state& u)       { return u[5]; }\ndouble const& tau(octopus::state const& u) { return u[5]; }\n\nenum { radial_momentum_idx = 6 };\n\ndouble&       angular_momentum(octopus::state& u)       { return u[7]; }\ndouble const& angular_momentum(octopus::state const& u) { return u[7]; }\n\ndouble radius(octopus::array<double, 3> const& v)\n{\n    return std::sqrt(v[0]*v[0] + v[1]*v[1]);\n}\n\ndouble radius(double x, double y)\n{\n    return std::sqrt(x*x + y*y);\n}\n\ndouble radial_momentum(\n    octopus::state const& u\n  , octopus::array<double, 3> const& v\n    )\n{\n    switch (mom_cons)\n    {\n        case angular_momentum_conservation:\n            return u[radial_momentum_idx]; \n        case cartesian_momentum_conservation:\n        {\n            double const R = radius(v);\n            return momentum_x(u)*v[0]/R + momentum_y(u)*v[1]/R;\n        }\n        default: break;\n    }\n\n    OCTOPUS_ASSERT(false);\n    return 0.0;\n}\n\ndouble tangential_momentum(\n    octopus::state const& u\n  , octopus::array<double, 3> const& v\n    )\n{\n    double const R = radius(v);\n    \n    switch (mom_cons)\n    {\n        case angular_momentum_conservation:\n            return angular_momentum(u)/R - rho(u)*R*omega; \n        case cartesian_momentum_conservation:\n            return momentum_y(u)*v[0]/R\n                 - momentum_x(u)*v[1]/R\n                 - rho(u)*R*omega;\n        default: break;\n    }\n\n    OCTOPUS_ASSERT(false);\n    return 0.0;\n}\n\ntemplate <octopus::axis Axis>\ndouble gravity(octopus::array<double, 3> const& v)\n{\n    double const x = v[0];\n    double const y = v[1];\n    double const z = v[2];\n\n    double const r = std::sqrt(x*x + y*y + z*z);\n    double const F = -G*M_C/(r*r);\n\n    switch (Axis)\n    {\n        case octopus::x_axis:\n            return F*(x/r);\n        case octopus::y_axis:\n            return F*(y/r);\n        case octopus::z_axis:\n            return F*(z/r);\n        default: break;\n    }\n\n    OCTOPUS_ASSERT(false);\n    return 0.0; \n}\n\ndouble radial_gravity(octopus::array<double, 3> const& v)\n{\n    double const x = v[0];\n    double const y = v[1];\n    double const z = v[2];\n\n    double const r = std::sqrt(x*x + y*y + z*z);\n    double const R = radius(v);\n    double const F = -G*M_C/(r*r);\n\n    return F*(R/r);\n}\n\ntemplate <octopus::axis Axis>\ndouble velocity(\n    octopus::state const& u\n  , octopus::array<double, 3> const& v\n    )\n{\n    double const x = v[0];\n    double const y = v[1];\n\n    double const R = radius(v);\n    double const st = tangential_momentum(u, v);\n    double const sr = radial_momentum(u, v);\n \n    switch (Axis)\n    {\n        case octopus::x_axis:\n            return (x*sr-y*st)/R/rho(u);\n        case octopus::y_axis:\n            return (y*sr+x*st)/R/rho(u);\n        case octopus::z_axis:\n            return momentum_z(u)/rho(u);\n        default: break;\n    }\n\n    OCTOPUS_ASSERT(false);\n    return 0.0; \n}\n\ndouble kinetic_energy(\n    octopus::state const& u\n  , octopus::array<double, 3> const& v\n    )\n{\n    double const sr = radial_momentum(u, v);\n    double const st = tangential_momentum(u, v);\n    return 0.5 * (sr*sr + st*st + momentum_z(u)*momentum_z(u)) / rho(u); \n}\n\n/// Gas pressure - polytropic equation of state.\ndouble pressure(octopus::state const& u)\n{\n    return kappa * std::pow(rho(u), gamma_);\n}\n\ndouble speed_of_sound(octopus::state const& u)\n{\n    OCTOPUS_ASSERT(rho(u) > 0.0);\n    OCTOPUS_ASSERT(pressure(u) >= 0.0);\n    return std::sqrt(gamma_ * pressure(u) / rho(u)); \n}\n\n// Omega at the radius with the highest pressure.\ndouble omega_R_0()\n{\n    double const j_H = std::sqrt(2.0*X_in/(1.0+X_in));\n    double const j_here = j_H*std::sqrt(G*M_C*R_outer);\n    return (G*M_C)*(G*M_C)/(j_here*j_here*j_here);\n}\n\nvoid initialize_omega()\n{\n    if (rotating_grid)\n        omega = omega_R_0();\n    else\n        omega = 0.0; \n}\n\ndouble orbital_period()\n{\n    double const pi = boost::math::constants::pi<double>();\n    return 2.0*pi/omega_R_0(); \n}\n\ndouble z_max(double R)\n{\n    using std::pow;\n    using std::sqrt;\n\n    double const X = R/R_outer;\n    double const j_H = sqrt(2.0*X_in/(1.0+X_in));\n    double const C = 1.0/(1.0+X_in);\n    double const tmp = pow(C+0.5*(j_H/X)*(j_H/X), -2.0) - X*X;\n\n    if (tmp <= 0.0)\n        return 0.0; \n\n    return R_outer*sqrt(tmp);\n}\n\ndouble rho_max() \n{\n    using std::pow;\n    using std::sqrt;\n\n    double const n = polytropic_n;\n\n    double const R_0 = R_outer*2.0*X_in/(1.0+X_in);        \n    double const j_H = sqrt(2.0*X_in/(1.0+X_in));\n    double const X_max = R_0/R_outer;\n    double const C = 1.0/(1.0+X_in);\n    double const H_max = 1.0/sqrt(X_max*X_max) - 0.5*(j_H/X_max)*(j_H/X_max)-C;\n\n    return pow(H_max/((n+1)*kappa), n);\n}\n\ndouble density_floor()\n{\n    return 1e-10 * rho_max();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Kernels.\nstruct initialize : octopus::trivial_serialization \n{ // {{{\n    void operator()(octopus::octree_server& U) const\n    {\n/*\n        boost::uint64_t const gnx = octopus::config().grid_node_length;\n\n        for (boost::uint64_t i = 0; i < gnx; ++i)\n            for (boost::uint64_t j = 0; j < gnx; ++j)\n                for (boost::uint64_t k = 0; k < gnx; ++k)\n                {\n                    if (U.x_center(i) > 0.0 && U.y_center(j) > 0.0)\n                        rho(U(i, j, k)) = 1.0;\n                    else\n                        rho(U(i, j, k)) = 1.0e-10;\n\n                    momentum_x(U(i, j, k))       = 0.0; \n                    momentum_y(U(i, j, k))       = 0.0;\n                    momentum_z(U(i, j, k))       = 0.0;\n                    total_energy(U(i, j, k))     = 0.0;  \n                    tau(U(i, j, k))              = 0.0;\n                    angular_momentum(U(i, j, k)) = 0.0;\n                    U(i, j, k)[radial_momentum_idx] = 0.0;\n                }\n*/\n        using std::pow;\n        using std::sqrt;\n        using std::atan2;\n        using std::cos;\n\n        double const ei0 = 1.0;\n        double const tau0 = pow(ei0, 1.0 / gamma_);\n        double const rho1 = density_floor();\n        double const ei1 = density_floor();\n        double const tau1 = pow(ei1, 1.0 / gamma_);\n    \n        double const R_inner = X_in * R_outer;\n\n        double const C = 1.0/(1.0+X_in);\n\n        double const j_H = sqrt(2.0*X_in/(1.0+X_in));\n        // Conversion to \"real\" units (REVIEW: What does this mean?)\n        double const j_here = j_H*sqrt(G*M_C*R_outer); \n  \n        boost::uint64_t const gnx = octopus::config().grid_node_length;\n \n        for (boost::uint64_t i = 0; i < gnx; ++i)\n        {\n            for (boost::uint64_t j = 0; j < gnx; ++j)\n            {\n                for (boost::uint64_t k = 0; k < gnx; ++k)\n                {\n                    double const x_here = U.x_center(i);\n                    double const y_here = U.y_center(j);\n                    // REVIEW: Why do we do std::abs() here?\n                    double const z_here = std::fabs(U.z_center(k));\n  \n                    double const R = radius(x_here, y_here);\n\n                    // DEBUGGING\n                    //std::cout << \"r       = \" << R       << \"\\n\"\n                    //          << \"R_inner = \" << R_inner << \"\\n\"\n                    //          << \"R_outer = \" << R_outer << \"\\n\";\n    \n                    if ((R_inner <= R) && (R_outer >= R))\n                    {\n                        // DEBUGGING\n                        //std::cout << \"z     = \" << z_here << \"\\n\"\n                        //          << \"z_max = \" << z_max  << \"\\n\";\n\n                        if (z_here <= z_max(R))\n                        {\n                            double const X = R/R_outer;\n\n                            double const z = z_here/R_outer;\n                            double const H_here = 1.0/sqrt(X*X+z*z)\n                                                - 0.5*(j_H/X)*(j_H/X) - C;\n\n                            double const n = polytropic_n;\n                            double rho_here = (pow(H_here/((n+1)*kappa), n))\n                                            * (G*M_C/R_outer);\n\n                            OCTOPUS_ASSERT(rho_here > 0.0);\n\n                            double const theta_here = atan2(y_here, x_here);\n\n                            if (kick_mode != 0)\n                                rho_here *= 1.0 + ( kick_amplitude\n                                                  * cos(kick_mode*theta_here));\n\n                            OCTOPUS_ASSERT(rho_here > 0.0);\n\n                            rho(U(i, j, k)) = rho_here;\n\n                            double& mom_x = momentum_x(U(i, j, k));\n                            double& mom_y = momentum_y(U(i, j, k));\n\n                            switch (rot_dir)\n                            {\n                                case rotate_counterclockwise:\n                                {\n                                    mom_x = (-y_here)*rho_here*j_here/pow(R, 2);\n                                    mom_y = (+x_here)*rho_here*j_here/pow(R, 2);\n                                    break;\n                                }\n\n                                case rotate_clockwise:\n                                {\n                                    mom_x = (+y_here)*rho_here*j_here/pow(R, 2);\n                                    mom_y = (-x_here)*rho_here*j_here/pow(R, 2);\n                                    break;\n                                }\n\n                                default: OCTOPUS_ASSERT(false);\n                            }\n\n                            total_energy(U(i, j, k))     = ei0;\n                            tau(U(i, j, k))              = tau0;\n                            angular_momentum(U(i, j, k)) = j_here*rho_here;\n                        }\n\n                        else\n                        {\n                            rho(U(i, j, k))              = rho1;\n                            momentum_x(U(i, j, k))       = 0.0; \n                            momentum_y(U(i, j, k))       = 0.0;\n                            total_energy(U(i, j, k))     = ei1;  \n                            tau(U(i, j, k))              = tau1;\n                            angular_momentum(U(i, j, k)) = 0.0;\n                        }\n                    }\n                    \n                    else\n                    {\n                        rho(U(i, j, k))              = rho1;\n                        momentum_x(U(i, j, k))       = 0.0; \n                        momentum_y(U(i, j, k))       = 0.0;\n                        total_energy(U(i, j, k))     = ei1;  \n                        tau(U(i, j, k))              = tau1;\n                        angular_momentum(U(i, j, k)) = 0.0;\n                    }\n\n                    // DEBUGGING\n                    //std::cout << \"(\" << x_here\n                    //          << \", \" << y_here\n                    //          << \", \" << z_here << \") == \"\n                    //          << rho(U(i, j, k)) << \"\\n\";\n\n                    momentum_z(U(i, j, k))          = 0.0; \n                    U(i, j, k)[radial_momentum_idx] = 0.0;\n\n//                    rho(U(i, j, k)) = (std::max)(rho(U(i, j, k))\n//                                               , density_floor()); \n                }\n            }\n        }\n    }\n}; // }}}\n\nstruct enforce_outflow : octopus::trivial_serialization\n{\n    void operator()(\n        octopus::octree_server& U\n      , octopus::state& u\n      , octopus::array<double, 3> const& loc\n      , octopus::face f\n        ) const\n    {\n/*\n        std::cout << \"ENFORCE OUTFLOW: (\" << loc[0]\n                                  << \", \" << loc[1]\n                                  << \", \" << loc[2]\n                                  << \") \" << f;\n*/\n        switch (invert(f))\n        {\n            case octopus::XU:\n            {\n                if (velocity<octopus::x_axis>(u, loc) > 0.0)\n                {\n//                    std::cout << \" OUTFLOW\";\n                    total_energy(u) -= 0.5*momentum_x(u)*momentum_x(u)/rho(u);\n                    momentum_x(u) = 0.0;\n\n                    //double const vy = velocity<octopus::y_axis>(u, loc);\n                    double const R = radius(loc);\n                    angular_momentum(u) =\n                        loc[0]*velocity<octopus::y_axis>(u, loc)*rho(u);\n                    u[radial_momentum_idx] =\n                        loc[1]*velocity<octopus::y_axis>(u, loc)*rho(u)/R;\n                }\n                break;\n            }\n            case octopus::XL:\n            {\n                if (velocity<octopus::x_axis>(u, loc) < 0.0)\n                {\n//                    std::cout << \" OUTFLOW\";\n                    total_energy(u) -= 0.5*momentum_x(u)*momentum_x(u)/rho(u);\n                    momentum_x(u) = 0.0;\n\n                    //double const vy = velocity<octopus::y_axis>(u, loc);\n                    double const R = radius(loc);\n                    angular_momentum(u) =\n                        loc[0]*velocity<octopus::y_axis>(u, loc)*rho(u);\n                    u[radial_momentum_idx] =\n                        loc[1]*velocity<octopus::y_axis>(u, loc)*rho(u)/R;\n                }\n                break;\n            }\n\n            case octopus::YU:\n            {\n                if (velocity<octopus::y_axis>(u, loc) > 0.0)\n                {\n//                    std::cout << \" OUTFLOW\";\n                    total_energy(u) -= 0.5*momentum_y(u)*momentum_y(u)/rho(u);\n                    momentum_y(u) = 0.0;\n\n                    //double const vx = velocity<octopus::x_axis>(u, loc);\n                    double const R = radius(loc);\n                    angular_momentum(u) =\n                        -loc[1]*velocity<octopus::x_axis>(u, loc)*rho(u);\n                    u[radial_momentum_idx] =\n                        loc[0]*velocity<octopus::x_axis>(u, loc)*rho(u)/R;\n                }\n                break;\n            }\n            case octopus::YL:\n            {\n                if (velocity<octopus::y_axis>(u, loc) < 0.0)\n                {\n//                    std::cout << \" OUTFLOW\";\n                    total_energy(u) -= 0.5*momentum_y(u)*momentum_y(u)/rho(u);\n                    momentum_y(u) = 0.0;\n\n                    //double const vx = velocity<octopus::x_axis>(u, loc);\n                    double const R = radius(loc);\n                    angular_momentum(u) =\n                        -loc[1]*velocity<octopus::x_axis>(u, loc)*rho(u);\n                    u[radial_momentum_idx] =\n                        loc[0]*velocity<octopus::x_axis>(u, loc)*rho(u)/R;\n                }\n                break;\n            }\n\n            case octopus::ZU:\n            {\n                if (momentum_z(u) > 0.0)\n                {\n//                    std::cout << \" OUTFLOW\";\n                    total_energy(u) -= 0.5*momentum_z(u)*momentum_z(u)/rho(u);\n                    momentum_z(u) = 0.0;\n                }\n                break;\n            }\n            case octopus::ZL:\n            {\n                if (momentum_z(u) < 0.0)\n                {\n//                    std::cout << \" OUTFLOW\";\n                    total_energy(u) -= 0.5*momentum_z(u)*momentum_z(u)/rho(u);\n                    momentum_z(u) = 0.0;\n                }\n                break;\n            }\n\n            default: OCTOPUS_ASSERT(false); break;\n        }\n\n//        std::cout << \"\\n\";\n    } \n};\n\nstruct enforce_lower_limits : octopus::trivial_serialization\n{\n    void operator()(\n        octopus::state& u\n      , octopus::array<double, 3> const& v \n        ) const\n    {\n//        OCTOPUS_ASSERT(rho(u) >= 0.0);\n\n        rho(u) = (std::max)(rho(u), density_floor()); \n\n        double const internal_energy = total_energy(u) - kinetic_energy(u, v);\n\n        if (internal_energy > 0.1 * total_energy(u))\n        {\n            tau(u) = std::pow((std::max)(internal_energy, density_floor())\n                                       , 1.0 / gamma_); \n        }\n\n        // Floor everything in the center of the grid.\n        double const R_inner = X_in * R_outer;\n\n        if (radius(v) < 0.5 * R_inner)\n        {\n            // REVIEW: Why don't we floor tau and energy? \n            rho(u)                 = density_floor();\n            momentum_x(u)          = 0.0;\n            momentum_y(u)          = 0.0;\n            momentum_z(u)          = 0.0;\n            angular_momentum(u)    = 0.0;\n            u[radial_momentum_idx] = 0.0;\n        }\n\n        // If we're not conserving angular momentum, define angular momentum \n        // in terms of x and y momentum. \n        // FIXME: Not sure this belongs in this particular function, or perhaps\n        // this hook should be renamed to be something more generic than\n        // enforce_lower_limits.\n        else if (mom_cons != angular_momentum_conservation)\n            angular_momentum(u) = momentum_y(u)*v[0] - momentum_x(u)*v[1];\n    }\n};\n\nstruct reflect_z : octopus::trivial_serialization\n{\n    void operator()(octopus::state& s) const\n    {\n        momentum_z(s) = -momentum_z(s);\n    }\n};\n\nstruct max_eigenvalue : octopus::trivial_serialization\n{\n    double operator()(\n        octopus::octree_server& U\n      , octopus::state const& u\n      , octopus::array<double, 3> const& v \n      , octopus::axis a\n        ) const\n    {\n        switch (a)\n        {\n            case octopus::x_axis:\n                return std::fabs(velocity<octopus::x_axis>(u, v)) \n                     + speed_of_sound(u);\n\n            case octopus::y_axis:\n                return std::fabs(velocity<octopus::y_axis>(u, v)) \n                     + speed_of_sound(u);\n\n            case octopus::z_axis:\n                return std::fabs(velocity<octopus::z_axis>(u, v)) \n                     + speed_of_sound(u);\n\n            default: { OCTOPUS_ASSERT(false); break; }\n        }\n\n        return 0.0;\n    }\n};\n\n// FIXME: Refactor reconstruction harness (nearly identical code is used in\n// octree_server for computing fluxes).\nstruct cfl_treewise_compute_dt : octopus::trivial_serialization\n{\n    cfl_treewise_compute_dt() {} \n\n    double compute_x_dt(octopus::octree_server& U) const\n    { // {{{ \n        double dt_inv = 0.0; \n\n        boost::uint64_t const bw = octopus::science().ghost_zone_length;\n        boost::uint64_t const gnx = octopus::config().grid_node_length;\n    \n/*\n        octopus::vector2d<double> q0(gnx);\n        octopus::vector2d<double> ql(gnx);\n        octopus::vector2d<double> qr(gnx);\n*/\n        std::vector<octopus::state> q0(gnx);\n        std::vector<octopus::state> ql(gnx);\n        std::vector<octopus::state> qr(gnx);\n    \n        for (boost::uint64_t k = bw; k < (gnx - bw); ++k)\n            for (boost::uint64_t j = bw; j < (gnx - bw); ++j)\n            {\n                for (boost::uint64_t i = 0; i < gnx; ++i)\n                {\n                    q0[i] = U(i, j, k);\n        \n                    octopus::array<double, 3> loc = U.center_coords(i, j, k);\n        \n                    octopus::science().conserved_to_primitive(q0[i], loc);\n                }\n        \n                octopus::science().reconstruct(q0, ql, qr);\n        \n                for (boost::uint64_t i = bw; i < gnx - bw + 1; ++i)\n                {\n                    octopus::array<double, 3> loc = U.x_face_coords(i, j, k);\n        \n                    octopus::science().primitive_to_conserved(ql[i], loc);\n                    octopus::science().primitive_to_conserved(qr[i], loc);\n       \n                    double const l_dt_inv =\n                        (max_eigenvalue()(U, ql[i], loc, octopus::x_axis));\n                    double const r_dt_inv = \n                        (max_eigenvalue()(U, qr[i], loc, octopus::x_axis));\n\n                    dt_inv = octopus::maximum(dt_inv, l_dt_inv, r_dt_inv);\n                    OCTOPUS_ASSERT(0.0 < dt_inv);\n                }\n            }\n\n        return cfl_factor * (1.0 / (dt_inv / (U.get_dx())));\n    } // }}}\n    \n    double compute_y_dt(octopus::octree_server& U) const\n    { // {{{ \n        double dt_inv = 0.0; \n\n        boost::uint64_t const bw = octopus::science().ghost_zone_length;\n        boost::uint64_t const gnx = octopus::config().grid_node_length;\n    \n/*\n        octopus::vector2d<double> q0(gnx);\n        octopus::vector2d<double> ql(gnx);\n        octopus::vector2d<double> qr(gnx);\n*/\n        std::vector<octopus::state> q0(gnx);\n        std::vector<octopus::state> ql(gnx);\n        std::vector<octopus::state> qr(gnx);\n    \n        for (boost::uint64_t i = bw; i < (gnx - bw); ++i)\n            for (boost::uint64_t k = bw; k < (gnx - bw); ++k)\n            {\n                for (boost::uint64_t j = 0; j < gnx; ++j)\n                {\n                    q0[j] = U(i, j, k);\n        \n                    octopus::array<double, 3> loc = U.center_coords(i, j, k);\n        \n                    octopus::science().conserved_to_primitive(q0[j], loc);\n                }\n        \n                octopus::science().reconstruct(q0, ql, qr);\n        \n                for (boost::uint64_t j = bw; j < gnx - bw + 1; ++j)\n                {\n                    octopus::array<double, 3> loc = U.y_face_coords(i, j, k);\n        \n                    octopus::science().primitive_to_conserved(ql[j], loc);\n                    octopus::science().primitive_to_conserved(qr[j], loc);\n        \n                    double const l_dt_inv =\n                        (max_eigenvalue()(U, ql[j], loc, octopus::y_axis));\n                    double const r_dt_inv = \n                        (max_eigenvalue()(U, qr[j], loc, octopus::y_axis));\n\n                    dt_inv = octopus::maximum(dt_inv, l_dt_inv, r_dt_inv);\n                    OCTOPUS_ASSERT(0.0 < dt_inv);\n                }\n            }\n\n        return cfl_factor * (1.0 / (dt_inv / (U.get_dx())));\n    } // }}}\n    \n    double compute_z_dt(octopus::octree_server& U) const\n    { // {{{ \n        double dt_inv = 0.0; \n\n        boost::uint64_t const bw = octopus::science().ghost_zone_length;\n        boost::uint64_t const gnx = octopus::config().grid_node_length;\n    \n/*\n        octopus::vector2d<double> q0(gnx);\n        octopus::vector2d<double> ql(gnx);\n        octopus::vector2d<double> qr(gnx);\n*/\n        std::vector<octopus::state> q0(gnx);\n        std::vector<octopus::state> ql(gnx);\n        std::vector<octopus::state> qr(gnx);\n    \n        for (boost::uint64_t i = bw; i < (gnx - bw); ++i)\n            for (boost::uint64_t j = bw; j < (gnx - bw); ++j)\n            {\n                for (boost::uint64_t k = 0; k < gnx; ++k)\n                {\n                    q0[k] = U(i, j, k);\n        \n                    octopus::array<double, 3> loc = U.center_coords(i, j, k);\n    \n                    octopus::science().conserved_to_primitive(q0[k], loc);\n                }\n        \n                octopus::science().reconstruct(q0, ql, qr);\n        \n                for (boost::uint64_t k = bw; k < gnx - bw + 1; ++k)\n                {\n                    octopus::array<double, 3> loc = U.z_face_coords(i, j, k);\n        \n                    octopus::science().primitive_to_conserved(ql[k], loc);\n                    octopus::science().primitive_to_conserved(qr[k], loc);\n        \n                    double const l_dt_inv =\n                        (max_eigenvalue()(U, ql[k], loc, octopus::z_axis));\n                    double const r_dt_inv =\n                        (max_eigenvalue()(U, qr[k], loc, octopus::z_axis));\n\n                    dt_inv = octopus::maximum(dt_inv, l_dt_inv, r_dt_inv);\n                    OCTOPUS_ASSERT(0.0 < dt_inv);\n                }\n            }\n\n        return cfl_factor * (1.0 / (dt_inv / (U.get_dx())));\n    } // }}}\n\n    // Compute maximum dt locally in parallel. \n    double operator()(octopus::octree_server& U) const\n    {\n        // Do two directions in other threads.\n        boost::array<hpx::future<double>, 2> xy =\n        { {\n            hpx::async(boost::bind\n                (&cfl_treewise_compute_dt::compute_x_dt, this, boost::ref(U)))\n          , hpx::async(boost::bind\n                (&cfl_treewise_compute_dt::compute_y_dt, this, boost::ref(U)))\n        } };\n\n        // And do one direction here.\n        double dt_limit = compute_z_dt(U);\n        OCTOPUS_ASSERT(0.0 < dt_limit);\n\n        // Wait for the x and y computations.\n        dt_limit = (std::min)(dt_limit, xy[0].move());\n        OCTOPUS_ASSERT(0.0 < dt_limit);\n\n        dt_limit = (std::min)(dt_limit, xy[1].move());\n        OCTOPUS_ASSERT(0.0 < dt_limit);\n\n        return dt_limit;\n    }\n};\n\nstruct cfl_initial_dt : octopus::trivial_serialization\n{\n    double operator()(octopus::octree_server& root) const\n    {\n        return initial_cfl_factor \n             * root.reduce<double>(cfl_treewise_compute_dt()\n                                 , octopus::minimum_functor()\n                                 , std::numeric_limits<double>::max());\n    }\n};\n\n// IMPLEMENT: Post prediction.\nstruct cfl_predict_dt\n{\n  private:\n    double max_dt_growth_;\n    double fudge_factor_;\n\n  public:\n    cfl_predict_dt() : max_dt_growth_(0.0), fudge_factor_(0.0) {}\n\n    cfl_predict_dt(\n        double max_dt_growth\n      , double fudge_factor\n        )\n      : max_dt_growth_(max_dt_growth)\n      , fudge_factor_(fudge_factor)\n    {}\n\n    /// Returns the tuple (timestep N + 1 size, timestep N + gap size)\n    octopus::dt_prediction operator()(\n        octopus::octree_server& root\n        ) const\n    {\n        OCTOPUS_ASSERT(0 < max_dt_growth_);\n        OCTOPUS_ASSERT(0 < fudge_factor_);\n\n        OCTOPUS_ASSERT(0 == root.get_level());\n\n        double next_dt = root.reduce<double>(cfl_treewise_compute_dt()\n                                           , octopus::minimum_functor()\n                                           , std::numeric_limits<double>::max());\n\n        return octopus::dt_prediction(next_dt, fudge_factor_ * next_dt); \n    }\n\n    template <typename Archive>\n    void serialize(Archive& ar, unsigned int)\n    {\n        ar & max_dt_growth_;\n        ar & fudge_factor_;\n    }\n};\n\n// Primitive variables are mass, velocity and pressure. Conserved variables\n// are mass, momentum and energy. \n\nstruct conserved_to_primitive : octopus::trivial_serialization\n{\n    void operator()(\n        octopus::state& u\n      , octopus::array<double, 3> const& v\n        ) const\n    {\n        double const R = radius(v);\n\n        total_energy(u)        -= kinetic_energy(u, v);\n        momentum_x(u)          /= rho(u);\n        momentum_y(u)          /= rho(u);\n        momentum_z(u)          /= rho(u);\n        u[radial_momentum_idx] /= rho(u);\n        angular_momentum(u)    /= rho(u) * R;\n        angular_momentum(u)    -= omega * R;\n    }\n};\n\nstruct primitive_to_conserved : octopus::trivial_serialization\n{\n    void operator()(\n        octopus::state& u\n      , octopus::array<double, 3> const& v\n        ) const\n    {\n        double const R = radius(v);\n\n        momentum_x(u)          *= rho(u);\n        momentum_y(u)          *= rho(u);\n        momentum_z(u)          *= rho(u);\n        u[radial_momentum_idx] *= rho(u);\n        angular_momentum(u)    += omega * R;\n        angular_momentum(u)    *= rho(u) * R;\n        total_energy(u)        += kinetic_energy(u, v);\n    }\n};\n\nstruct source : octopus::trivial_serialization\n{\n    octopus::state operator()(\n        octopus::octree_server& U \n      , octopus::state const& u\n      , octopus::array<double, 3> const& v\n        ) const\n    {\n        octopus::state s;\n\n/*\n        if (  octopus::compare_real(v[0], -1.26562, 1e-5)\n           && octopus::compare_real(v[1], -1.45312, 1e-5)\n           && octopus::compare_real(v[2], 0.046875, 1e-5))\n        {\n            std::stringstream ss;\n            ss << ( boost::format(\"SOURCE U (%g, %g, %g):\")\n                  % v[0] % v[1] % v[2]); \n            for (boost::uint64_t i = 0; i < u.size(); ++i)\n                ss << ( boost::format(\" %.16x\")\n                      % octopus::hex_real(u[i]));\n            ss << \"\\n\";\n//            ss << ( boost::format(\"Z GRAVITY: %.17e\\n\")\n//                  % gravity<octopus::z_axis>(v));\n            std::cout << ss.str();\n        }\n\n        return s;\n*/\n\n        double const R = radius(v);\n        double const p = pressure(u);\n        double const lz = angular_momentum(u);\n\n        // This is the radial momentum source term (independent of gravity).\n        s[radial_momentum_idx] += (p + std::pow(lz/R, 2)/rho(u))/R;\n\n        // Add half of the Coriolis force for rotating cartesian momentum.\n        momentum_x(s) += momentum_y(u)*omega;\n        momentum_y(s) -= momentum_x(u)*omega; \n\n        // There won't be any gravity within a certain radius of the center.\n        if (R < 0.5*(X_in*R_outer))\n            return s;        \n\n        momentum_x(s) += rho(u)*gravity<octopus::x_axis>(v);\n        momentum_y(s) += rho(u)*gravity<octopus::y_axis>(v);\n        momentum_z(s) += rho(u)*gravity<octopus::z_axis>(v);\n\n        s[radial_momentum_idx] += rho(u)*radial_gravity(v);\n\n        return s;\n    }\n};\n\n// REVIEW: For rot_dir to work properly, do we need to make some changes here?\nstruct flux : octopus::trivial_serialization\n{\n    octopus::state operator()(\n        octopus::octree_server& U\n      , octopus::state& u\n      , octopus::array<double, 3> const& loc\n      , octopus::array<boost::uint64_t, 3> const& idx\n      , octopus::axis a \n        ) const\n    {\n        double const p = pressure(u);\n        double const R = radius(loc);\n \n        octopus::state fl;\n\n        switch (a)\n        {\n            case octopus::x_axis:\n            {\n                // Velocity.\n                double const v = velocity<octopus::x_axis>(u, loc);\n\n                for (boost::uint64_t i = 0; i < u.size(); ++i)\n                    fl[i] = u[i] * v;\n\n                momentum_x(fl)   += p;\n                total_energy(fl) += v * p;\n\n                fl[radial_momentum_idx] += loc[0] * p / R;\n                angular_momentum(fl)    -= loc[1] * p;\n\n/*\n                if (  octopus::compare_real(U.x_center(idx[0]), -1.26562, 1e-5)\n                   && octopus::compare_real(U.y_center(idx[1]), -1.45312, 1e-5)\n                   && octopus::compare_real(U.z_center(idx[2]), 0.046875, 1e-5))\n                {\n                    std::stringstream ss;\n                    ss << ( boost::format(\"X FLUX U (%g, %g, %g):\")\n                          % U.x_center(idx[0])\n                          % U.y_center(idx[1])\n                          % U.z_center(idx[2]));\n                    for (boost::uint64_t i = 0; i < fl.size(); ++i)\n                        ss << ( boost::format(\" %.16x\")\n                              % octopus::hex_real(u[i]));\n                    ss << \"\\n\";\n                    ss << ( boost::format(\"X FLUX (%g, %g, %g):\")\n                          % U.x_center(idx[0])\n                          % U.y_center(idx[1])\n                          % U.z_center(idx[2]));\n                    for (boost::uint64_t i = 0; i < fl.size(); ++i)\n                        ss << ( boost::format(\" %.16x\")\n                              % octopus::hex_real(fl[i]));\n                    ss << \"\\n\";\n                    ss << (boost::format(\"RADIUS: %.17e\\n\") % R);\n                    ss << (boost::format(\"PRESSURE: %.17e\\n\") % p);\n                    ss << (boost::format(\"VELOCITY: %.17e\\n\") % v);\n                    std::cout << ss.str();\n                }\n*/\n\n                break;\n            }\n\n            case octopus::y_axis:\n            {\n                double const v = velocity<octopus::y_axis>(u, loc);\n\n                for (boost::uint64_t i = 0; i < u.size(); ++i)\n                    fl[i] = u[i] * v;\n\n                momentum_y(fl)   += p;\n                total_energy(fl) += v * p;\n\n                fl[radial_momentum_idx] += loc[1] * p / R;\n                angular_momentum(fl)    += loc[0] * p;\n\n                break;\n            }\n\n            case octopus::z_axis:\n            {\n                double const v = velocity<octopus::z_axis>(u, loc);\n\n                for (boost::uint64_t i = 0; i < u.size(); ++i)\n                    fl[i] = u[i] * v;\n\n                momentum_z(fl)   += p;\n                total_energy(fl) += v * p;\n\n                break;\n            }\n\n            default: { OCTOPUS_ASSERT(false); break; }\n        }\n\n        return fl;\n    }\n};\n\nstruct refine_by_geometry\n  : octopus::elementwise_refinement_criteria_base<refine_by_geometry>\n{\n    /// Returns true if we should refine the region that contains this point.\n    bool refine(\n        octopus::octree_server& U\n      , octopus::state const& u\n      , octopus::array<double, 3> loc\n        )\n    {\n        using std::sqrt;\n        using std::abs;\n\n        double const dx = U.get_dx();\n\n        double const xU = loc[0]+0.5*dx; // x upper\n        double const xL = loc[0]-0.5*dx; // x lower\n        double const yU = loc[1]+0.5*dx; // y upper\n        double const yL = loc[1]-0.5*dx; // y lower\n\n        double const radius0 = radius(loc[0], loc[1]); \n        double const radius1 = radius(xU, yU);\n        double const radius2 = radius(xU, yL);\n        double const radius3 = radius(xL, yU);\n        double const radius4 = radius(xL, yL);\n\n        bool condition0 = (\n            std::fabs(loc[2]+0.5*dx) < z_max(radius0) ||\n            std::fabs(loc[2]-0.5*dx) < z_max(radius0)\n            );\n\n        bool condition1 = (\n            ((radius1 < R_outer) && (radius1 > X_in*R_outer)) ||  \n            ((radius2 < R_outer) && (radius2 > X_in*R_outer)) ||  \n            ((radius3 < R_outer) && (radius3 > X_in*R_outer)) ||  \n            ((radius4 < R_outer) && (radius4 > X_in*R_outer))\n            );\n\n        return condition0 && condition1;\n    }\n\n    /// If this returns true for all regions in a point, that region will be\n    /// unrefined.\n    bool unrefine(\n        octopus::octree_server& U\n      , octopus::state const& u\n      , octopus::array<double, 3> loc\n        )\n    {\n        // Unused currently.\n        return false;\n    }\n\n    template <typename Archive>\n    void serialize(Archive& ar, const unsigned int)\n    {\n        typedef elementwise_refinement_criteria_base<refine_by_geometry>\n            base_type;\n        ar & hpx::util::base_object_nonvirt<base_type>(*this);\n    }\n};\n\nstruct output_equatorial_plane \n{\n    struct slicer \n    {\n      private:\n        std::ofstream* ofs_;\n\n      public:\n        slicer() : ofs_(0) {}\n\n        slicer(std::ofstream& ofs) : ofs_(&ofs) {}\n\n        void operator()(\n            octopus::octree_server& U\n          , octopus::state& u\n          , octopus::array<double, 3>& loc\n            ) const\n        {\n            (*ofs_) << ( boost::format(\"%g %g %g %i\")\n                       % loc[0]\n                       % loc[1]\n                       % loc[2]\n                       % U.get_level());\n\n            for (boost::uint64_t i = 0; i < u.size(); ++i)\n            {\n//                (*ofs_) << ( boost::format(\" %016x\")\n//                           % octopus::hex_real(u[i]));\n                (*ofs_) << \" \" << u[i];\n            }\n\n            (*ofs_) << \"\\n\";\n        }\n\n        template <typename Archive>\n        void serialize(Archive& ar, const unsigned int)\n        {\n            OCTOPUS_ASSERT(false);\n        };\n    };\n\n  private:\n    octopus::axis axis_;\n  public:\n    output_equatorial_plane() : axis_() {}\n\n    output_equatorial_plane(octopus::axis a) : axis_(a) {}\n\n    void operator()(\n        octopus::octree_server& U\n      , std::ofstream& ofs\n        ) const\n    {\n        U.slice_leaf(slicer(ofs), axis_, 1e-7);\n    }\n\n    template <typename Archive>\n    void serialize(Archive& ar, const unsigned int)\n    {\n        ar & axis_;\n    };\n};\n\nstruct add_functor : octopus::trivial_serialization\n{\n    boost::uint64_t operator()(boost::uint64_t a, boost::uint64_t b) const\n    {\n        return a + b;\n    } \n};\n\nstruct one_functor : octopus::trivial_serialization\n{\n    boost::uint64_t operator()(octopus::octree_server&) const\n    {\n        return 1;\n    } \n};\n\nboost::uint64_t count_nodes(octopus::octree_server& U)\n{\n    return U.reduce<boost::uint64_t>(one_functor(), add_functor(), 0);\n}\n\nstruct slice_distribution : octopus::trivial_serialization\n{\n    hpx::id_type operator()(\n        octopus::octree_init_data const& init\n      , std::vector<hpx::id_type> const& localities\n        ) const\n    {\n        double const pi = boost::math::constants::pi<double>();\n\n        boost::uint64_t const bw = octopus::science().ghost_zone_length;\n        double const grid_dim = octopus::config().spatial_domain;\n        boost::uint64_t const gnx = octopus::config().grid_node_length;\n\n        boost::uint64_t n = localities.size();\n\n        boost::uint64_t i = gnx / 2;\n        boost::uint64_t j = gnx / 2; \n//        boost::uint64_t i = 0;\n//        boost::uint64_t j = 0; \n\n        double const dx0 = octopus::science().initial_dx();\n\n        double const x = double(init.offset[0] + i) * init.dx - grid_dim\n                            - bw * dx0 - init.origin[0];\n        double const y = double(init.offset[1] + j) * init.dx - grid_dim\n                            - bw * dx0 - init.origin[1]; \n\n//        double const x = x_face + 0.5 * init.dx;\n//        double const y = y_face + 0.5 * init.dx;\n//        double const x = x_face;\n//        double const y = y_face;\n\n        double theta = std::atan2(y, x);\n\n        if (theta < 0)\n            theta += 2*pi;\n\n//        std::cout << ( boost::format(\"x=%1%, y=%2%, theta=%3%, loc[0]=%4%, loc[1]=%5%\\n\")\n//                     % x % y % theta % init.location[0] % init.location[1]);\n\n        boost::uint64_t l = 0;\n\n        while (true)\n        {\n            OCTOPUS_ASSERT(l < n);\n\n            double lower_bound = double(l)/double(n) * 2*pi;\n\n//            std::cout << ( boost::format(\"l=%1%, lower_bound=%2%\\n\")\n//                         % l % lower_bound);\n\n            if (theta >= lower_bound)\n            {\n                double upper_bound = double(l+1)/double(n) * 2*pi;\n\n                if (theta < upper_bound)\n                    break;\n            }\n\n            ++l;\n        }\n\n        OCTOPUS_ASSERT(l < n);\n\n        return localities[l];\n    }\n};\n\nstruct reset_checkpoint : octopus::trivial_serialization\n{\n    void operator()() const\n    {\n        octopus::checkpoint().seekp(0);\n    }\n};\n\n#endif // OCTOPUS_9BA6055C_E7A9_4A16_8A24_B8B410AA1A14\n\n", "meta": {"hexsha": "bbc3f4352aeb8fa6d85a1368e288a0165251a7a5", "size": 41738, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/3d_torus/3d_torus.hpp", "max_stars_repo_name": "STEllAR-GROUP/octopus", "max_stars_repo_head_hexsha": "a1f910d63380e4ebf91198ac2bc2896505ce6146", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-01-30T14:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-19T19:03:19.000Z", "max_issues_repo_path": "applications/3d_torus/3d_torus.hpp", "max_issues_repo_name": "STEllAR-GROUP/octopus", "max_issues_repo_head_hexsha": "a1f910d63380e4ebf91198ac2bc2896505ce6146", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/3d_torus/3d_torus.hpp", "max_forks_repo_name": "STEllAR-GROUP/octopus", "max_forks_repo_head_hexsha": "a1f910d63380e4ebf91198ac2bc2896505ce6146", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.078183172, "max_line_length": 91, "alphanum_fraction": 0.4813359528, "num_tokens": 10927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998508568416, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4038238460703111}}
{"text": "#include <QApplication>\n#include <QAction>\n#include <QMainWindow>\n#include <QStringList>\n\n#include \"Scene_surface_mesh_item.h\"\n#include \"Scene_textured_surface_mesh_item.h\"\n#include \"Scene_polyhedron_selection_item.h\"\n#include \"SMesh_type.h\"\n#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>\n#include <CGAL/Three/Polyhedron_demo_plugin_interface.h>\n#include <CGAL/Three/Three.h>\n#include \"Scene.h\"\n#include <QElapsedTimer>\n#include <QGraphicsScene>\n#include <QGraphicsItem>\n#include <QPen>\n#include <QDockWidget>\n#include <Messages_interface.h>\n#include <CGAL/Polygon_mesh_processing/border.h>\n#include <CGAL/Polygon_mesh_processing/measure.h>\n#include <CGAL/property_map.h>\n\n\n#include <CGAL/boost/graph/Seam_mesh.h>\n#include <CGAL/boost/graph/graph_traits_Seam_mesh.h>\n\n#include <CGAL/Surface_mesh_parameterization/ARAP_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/Barycentric_mapping_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/Discrete_authalic_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/Discrete_conformal_map_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/Iterative_authalic_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/Error_code.h>\n#include <CGAL/Surface_mesh_parameterization/LSCM_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/Two_vertices_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/internal/orbifold_cone_helper.h>\n#include <CGAL/Surface_mesh_parameterization/Orbifold_Tutte_parameterizer_3.h>\n#include <CGAL/Surface_mesh_parameterization/parameterize.h>\n\n#include <boost/container/flat_map.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <vector>\n#include <unordered_map>\n#include <unordered_set>\n\n#include <CGAL/boost/graph/properties.h>\n#include <CGAL/Qt/GraphicsViewNavigation.h>\n\n#include \"ui_Parameterization_widget.h\"\n#include \"ui_OTE_dialog.h\"\n\ntypedef Scene_surface_mesh_item Scene_facegraph_item;\ntypedef Scene_textured_surface_mesh_item Scene_textured_facegraph_item;\ntypedef SMesh Textured_face_graph;\ntypedef SMesh Base_face_graph;\ntypedef SMesh Face_graph;\ntypedef EPICK Traits;\n\nnamespace SMP = CGAL::Surface_mesh_parameterization;\n\ntypedef std::unordered_set<boost::graph_traits<Base_face_graph>::face_descriptor> Component;\ntypedef std::vector<Component> Components;\n\nstruct Is_selected_property_map{\n  typedef boost::graph_traits<Base_face_graph>::edge_descriptor edge_descriptor;\n  typedef boost::property_map<Base_face_graph, boost::halfedge_index_t>::type HIndexMap;\n  std::vector<bool>* is_selected_ptr;\n  Base_face_graph* graph;\n  HIndexMap idmap;\n  Is_selected_property_map()\n    : is_selected_ptr(nullptr), graph(nullptr) {}\n  Is_selected_property_map(std::vector<bool>& is_selected,\n                           Base_face_graph* graph)\n    : is_selected_ptr( &is_selected), graph(graph)\n  {\n    idmap = get(boost::halfedge_index, *graph);\n  }\n\n  std::size_t id(edge_descriptor ed) { return get(idmap, halfedge(ed, *graph))/2; }\n\n  friend bool get(Is_selected_property_map map, edge_descriptor ed)\n  {\n    CGAL_assertion(map.is_selected_ptr!=NULL);\n    return (*map.is_selected_ptr)[map.id(ed)];\n  }\n\n  friend void put(Is_selected_property_map map, edge_descriptor ed, bool b)\n  {\n    CGAL_assertion(map.is_selected_ptr!=NULL);\n    (*map.is_selected_ptr)[map.id(ed)]=b;\n  }\n};\n\nclass Navigation : public CGAL::Qt::GraphicsViewNavigation\n{\npublic:\n  Navigation()\n    :CGAL::Qt::GraphicsViewNavigation(),\n      prev_pos(QPoint(0,0))\n  { }\n\nprotected:\n  bool eventFilter(QObject *obj, QEvent *ev)\n  {\n    QGraphicsView* v = qobject_cast<QGraphicsView*>(obj);\n    if(v == nullptr) {\n      QWidget* viewport = qobject_cast<QWidget*>(obj);\n      if(viewport == nullptr) {\n        return false;\n      }\n      v = qobject_cast<QGraphicsView*>(viewport->parent());\n      if(v == nullptr) {\n        return false;\n      }\n    }\n    switch(ev->type())\n    {\n    case QEvent::MouseMove: {\n      QMouseEvent* me = static_cast<QMouseEvent*>(ev);\n      if(is_dragging)\n      {\n        qreal dir[2] = {v->mapToScene(me->pos()).x() - prev_pos.x(),\n                        v->mapToScene(me->pos()).y() - prev_pos.y()};\n\n        v->translate(dir[0],dir[1]);\n        v->update();\n      }\n      prev_pos = v->mapToScene(me->pos());\n      break;\n    }\n\n    case QEvent::MouseButtonPress: {\n      is_dragging = true;\n      break;\n    }\n    case QEvent::MouseButtonRelease: {\n      is_dragging = false;\n      break;\n    }\n    case QEvent::Wheel: {\n      QWheelEvent* event = static_cast<QWheelEvent*>(ev);\n#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)\n      QPoint pos = event->pos();\n#else\n      QPointF pos = event->position();\n#endif\n      QPointF old_pos = v->mapToScene(pos.x(), pos.y());\n      if(event->angleDelta().y() <0)\n        v->scale(1.2, 1.2);\n      else\n        v->scale(0.8, 0.8);\n      QPointF new_pos = v->mapToScene(pos.x(), pos.y());\n      QPointF delta = new_pos - old_pos;\n      v->translate(delta.x(), delta.y());\n      v->update();\n      break;\n    }\n\n    case QEvent::MouseButtonDblClick: {\n      v->fitInView(v->scene()->itemsBoundingRect(), Qt::KeepAspectRatio);\n      break;\n    }\n    default:\n      CGAL::Qt::GraphicsViewNavigation::eventFilter(obj, ev);\n    }\n    return false;\n  }\nprivate:\n  bool is_dragging;\n  QPointF prev_pos;\n};\n\nnamespace SMP = CGAL::Surface_mesh_parameterization;\n\ntypedef Traits::FT                                                  FT;\ntypedef boost::graph_traits<Face_graph>::vertex_descriptor          P_vertex_descriptor;\ntypedef Traits::Point_2                                             Point_2;\ntypedef boost::graph_traits<Face_graph>::edge_descriptor            P_edge_descriptor;\ntypedef boost::graph_traits<Face_graph>::halfedge_descriptor        P_halfedge_descriptor;\n\n// Textured polyhedron\ntypedef boost::graph_traits<Base_face_graph>::\n                                         edge_descriptor            T_edge_descriptor;\ntypedef boost::graph_traits<Base_face_graph>::\n                                         halfedge_descriptor        T_halfedge_descriptor;\ntypedef boost::graph_traits<Base_face_graph>::\n                                         vertex_descriptor          T_vertex_descriptor;\n\n// Seam\ntypedef CGAL::Unique_hash_map<T_halfedge_descriptor,Point_2>        UV_uhm;\ntypedef CGAL::Unique_hash_map<T_edge_descriptor,bool>               Seam_edge_uhm;\ntypedef CGAL::Unique_hash_map<T_vertex_descriptor,bool>             Seam_vertex_uhm;\n\ntypedef boost::associative_property_map<UV_uhm>                     UV_pmap;\ntypedef boost::associative_property_map<Seam_edge_uhm>              Seam_edge_pmap;\ntypedef boost::associative_property_map<Seam_vertex_uhm>            Seam_vertex_pmap;\n\ntypedef CGAL::Seam_mesh<Base_face_graph,\n                        Seam_edge_pmap, Seam_vertex_pmap>           Seam_mesh;\n\ntypedef boost::graph_traits<Seam_mesh>::vertex_descriptor           s_vertex_descriptor;\ntypedef boost::graph_traits<Seam_mesh>::halfedge_descriptor         s_halfedge_descriptor;\ntypedef boost::graph_traits<Seam_mesh>::face_descriptor             s_face_descriptor;\n\ntypedef boost::graph_traits<Seam_mesh>::edges_size_type             s_edges_size_type;\n\ntypedef std::unordered_set<boost::graph_traits<Base_face_graph>::\nface_descriptor>                                                    Component;\ntypedef std::vector<Component>                                      Components;\n\ntypedef std::unordered_set<s_face_descriptor>                       SComponent;\ntypedef std::vector<SComponent>                                     SComponents;\n\nclass UVItem : public QGraphicsItem\n{\npublic :\n  UVItem(Components* components,\n         Base_face_graph* graph,\n         std::vector<std::vector<float> >uv_borders,\n         QRectF brect)\n    :\n      QGraphicsItem(),\n      bounding_rect(brect),\n      components(components),\n      graph(graph),\n      m_borders(uv_borders),\n      m_concatenated_borders(),\n      m_current_component(0)\n  {\n    std::size_t total_border_size = 0;\n    for(std::size_t i=0; i<m_borders.size(); ++i)\n      total_border_size += m_borders[i].size();\n\n    m_concatenated_borders.resize(total_border_size);\n    for(std::size_t i=0; i<m_borders.size(); ++i)\n    {\n      const std::vector<float>& ith_border = m_borders[i];\n      m_concatenated_borders.insert(m_concatenated_borders.end(),\n                                    ith_border.begin(), ith_border.end());\n    }\n  }\n\n  ~UVItem()\n  {\n    delete components;\n  }\n\n  const std::vector<std::vector<float> >& borders() const { return m_borders; }\n  const std::vector<float>& concatenated_borders() const { return m_concatenated_borders; }\n\n  QRectF boundingRect() const\n  {\n    return bounding_rect;\n  }\n\n  QString item_name()const{ return texMesh_name; }\n  void set_item_name(QString s){ texMesh_name = s;}\n\n  void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)\n  {\n    QPen pen;\n    QBrush brush;\n    brush.setColor(QColor(100, 100, 255));\n    brush.setStyle(Qt::SolidPattern);\n    pen.setColor(Qt::black);\n    pen.setWidth(0);\n    painter->setPen(pen);\n    painter->setBrush(brush);\n    SMesh::Property_map<halfedge_descriptor,float> u,v;\n\n    u = graph->add_property_map<halfedge_descriptor,float>(\"h:u\", 0.0f).first;\n    v = graph->add_property_map<halfedge_descriptor,float>(\"h:v\", 0.0f).first;\n\n    for( Component::iterator\n         fi = components->at(m_current_component).begin();\n         fi != components->at(m_current_component).end();\n         ++fi)\n    {\n      boost::graph_traits<Base_face_graph>::face_descriptor f(*fi);\n\n      QPointF points[3];\n      boost::graph_traits<Base_face_graph>::halfedge_descriptor h = halfedge(f, *graph);;\n      points[0] = QPointF(get(u, h), get(v, h));\n      h = next(halfedge(f, *graph), *graph);\n      points[1] = QPointF(get(u, h), get(v, h));\n      h = next(next(halfedge(f, *graph), *graph), *graph);\n      points[2] = QPointF(get(u, h), get(v, h));\n      painter->drawPolygon(points,3);\n    }\n  }\n\n  int number_of_components()const{return static_cast<int>(components->size());}\n  int current_component()const{return m_current_component;}\n  void set_current_component(int n){m_current_component = n;}\n\nprivate:\n  QString texMesh_name;\n  QRectF bounding_rect;\n  Components* components;\n  Base_face_graph* graph;\n  std::vector<std::vector<float> > m_borders;\n  std::vector<float> m_concatenated_borders;\n  int m_current_component;\n};\n\nusing namespace CGAL::Three;\n\nclass Polyhedron_demo_parameterization_plugin :\n    public QObject,\n    public Polyhedron_demo_plugin_helper\n{\n  Q_OBJECT\n  Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)\n  Q_PLUGIN_METADATA(IID \"com.geometryfactory.PolyhedronDemo.PluginInterface/1.0\")\n\npublic:\n  // used by Polyhedron_demo_plugin_helper\n  QList<QAction*> actions() const\n  {\n    return _actions;\n  }\n\n  ~Polyhedron_demo_parameterization_plugin()\n  {\n    delete navigation;\n  }\n  void init(QMainWindow* mainWindow,\n            Scene_interface* scene_interface,\n            Messages_interface* msg)\n  {\n    mw = mainWindow;\n    scene = scene_interface;\n    messages = msg;\n    Scene* true_scene = static_cast<Scene*>(scene);\n    connect(true_scene, SIGNAL(itemAboutToBeDestroyed(CGAL::Three::Scene_item*)),\n            this, SLOT(destroyPolyline(CGAL::Three::Scene_item*)));\n    QAction* actionMVC = new QAction(\"Mean Value Coordinates\", mw);\n    QAction* actionDCP = new QAction (\"Discrete Conformal Map\", mw);\n    QAction* actionLSC = new QAction(\"Least Square Conformal Map\", mw);\n    QAction* actionDAP = new QAction(\"Discrete Authalic\", mw);\n    QAction* actionIAP = new QAction(\"Iterative Authalic\", mw);\n    QAction* actionARAP = new QAction(\"As Rigid As Possible\", mw);\n    QAction* actionOTE = new QAction(\"Orbifold Tutte Embedding\", mw);\n    QAction* actionBTP = new QAction(\"Tutte Barycentric\", mw);\n    actionMVC->setObjectName(\"actionMVC\");\n    actionDCP->setObjectName(\"actionDCP\");\n    actionLSC->setObjectName(\"actionLSC\");\n    actionDAP->setObjectName(\"actionDAP\");\n    actionIAP->setObjectName(\"actionIAP\");\n    actionARAP->setObjectName(\"actionARAP\");\n    actionOTE->setObjectName(\"actionOTE\");\n    actionBTP->setObjectName(\"actionBTP\");\n\n    _actions << actionARAP\n             << actionBTP\n             << actionDAP\n             << actionIAP\n             << actionDCP\n             << actionLSC\n             << actionMVC\n             << actionOTE;\n    autoConnectActions();\n    Q_FOREACH(QAction *action, _actions)\n      action->setProperty(\"subMenuName\",\n                          \"Triangulated Surface Mesh Parameterization\"\n                          );\n    dock_widget = new QDockWidget(\n          \"UVMapping \"\n          , mw);\n    ui_widget.setupUi(dock_widget);\n    dock_widget->setWindowTitle(tr(\n                                  \"UVMapping \"\n                                  ));\n    graphics_scene = new QGraphicsScene(dock_widget);\n    ui_widget.graphicsView->setScene(graphics_scene);\n    ui_widget.graphicsView->setRenderHints(QPainter::Antialiasing);\n    navigation = new Navigation();\n    ui_widget.graphicsView->installEventFilter(navigation);\n    ui_widget.graphicsView->viewport()->installEventFilter(navigation);\n    ui_widget.component_numberLabel->setText(\"Component : 1\");\n    connect(ui_widget.prevButton, &QPushButton::clicked, this, &Polyhedron_demo_parameterization_plugin::on_prevButton_pressed);\n    connect(ui_widget.nextButton, &QPushButton::clicked, this, &Polyhedron_demo_parameterization_plugin::on_nextButton_pressed);\n    addDockWidget(dock_widget);\n    dock_widget->setVisible(false);\n    current_uv_item = nullptr;\n  }\n\n  bool applicable(QAction*) const\n  {\n    if (scene->selectionIndices().size() == 1)\n    {\n    return qobject_cast<Scene_facegraph_item*>(scene->item(scene->mainSelectionIndex()))\n        || qobject_cast<Scene_polyhedron_selection_item*>(scene->item(scene->mainSelectionIndex()));\n    }\n\n    Q_FOREACH(CGAL::Three::Scene_interface::Item_id id, scene->selectionIndices())\n    {\n      //if one facegraph is found in the selection, it's fine\n      if (qobject_cast<Scene_facegraph_item*>(scene->item(id)))\n        return true;\n    }\n    return false;\n  }\n\n  void closure()\n  {\n    dock_widget->hide();\n  }\n\npublic Q_SLOTS:\n  void on_actionMVC_triggered();\n  void on_actionDCP_triggered();\n  void on_actionLSC_triggered();\n  void on_actionDAP_triggered();\n  void on_actionIAP_triggered();\n  void on_actionARAP_triggered();\n  void on_actionOTE_triggered();\n  void on_actionBTP_triggered();\n  void on_prevButton_pressed();\n  void on_nextButton_pressed();\n\n  void replacePolyline()\n  {\n    if(current_uv_item){\n      Scene_textured_facegraph_item* t_item =\n          qobject_cast<Scene_textured_facegraph_item*>(projections.key(current_uv_item));\n     t_item->add_border_edges(std::vector<float>(0));\n    }\n\n    int id = scene->mainSelectionIndex();\n\n    Q_FOREACH(UVItem* pl, projections)\n    {\n      if(pl==nullptr || pl != projections[scene->item(id)])\n        continue;\n      current_uv_item = pl;\n      break;\n    }\n\n    if(!current_uv_item)\n    {\n      dock_widget->setWindowTitle(tr(\"UVMapping\"));\n      ui_widget.component_numberLabel->setText(QString(\"Component :\"));\n    }\n    else\n    {\n      if(!graphics_scene->items().empty())\n        graphics_scene->removeItem(graphics_scene->items().first());\n\n      graphics_scene->addItem(current_uv_item);\n      ui_widget.graphicsView->fitInView(current_uv_item->boundingRect(),\n                                        Qt::KeepAspectRatio);\n      ui_widget.component_numberLabel->setText(\n            QString(\"Component : %1/%2\").arg(current_uv_item->current_component()+1)\n            .arg(current_uv_item->number_of_components()));\n      dock_widget->setWindowTitle(tr(\"UVMapping for %1\")\n                                  .arg(current_uv_item->item_name()));\n      Scene_textured_facegraph_item* t_item =\n          qobject_cast<Scene_textured_facegraph_item*>(projections.key(current_uv_item));\n     t_item->add_border_edges(\n            current_uv_item->concatenated_borders());\n    }\n  }\n\n  void destroyPolyline(CGAL::Three::Scene_item* item)\n  {\n    Q_FOREACH(UVItem* pli, projections)\n    {\n      if(projections.key(pli) != item)\n        continue;\n      graphics_scene->removeItem(pli);\n      delete pli;\n      projections.remove(item);\n      break;\n    }\n\n    if(projections.empty() || projections.first() == NULL)\n    {\n      current_uv_item = nullptr;\n      dock_widget->setWindowTitle(tr(\"UVMapping\"));\n      ui_widget.component_numberLabel->setText(QString(\"Component :\"));\n    }\n    else\n      current_uv_item = projections.first();\n  }\n\nprotected:\n  enum Parameterization_method { PARAM_MVC, PARAM_DCP, PARAM_LSC, PARAM_DAP,\n                                 PARAM_IAP, PARAM_ARAP, PARAM_OTE, PARAM_BTP};\n  void parameterize(Parameterization_method method);\n\nprivate:\n  Messages_interface *messages;\n  QList<QAction*> _actions;\n  QDockWidget* dock_widget;\n  Ui::Parameterization ui_widget;\n  QGraphicsScene *graphics_scene;\n  Navigation* navigation;\n  QMap<Scene_item*, UVItem*> projections;\n  UVItem* current_uv_item;\n}; // end Polyhedron_demo_parameterization_plugin\n\nvoid Polyhedron_demo_parameterization_plugin::on_prevButton_pressed()\n{\n  int id = scene->mainSelectionIndex();\n  Q_FOREACH(UVItem* pl, projections)\n  {\n    if(pl==nullptr\n       || pl != projections[scene->item(id)])\n      continue;\n\n    current_uv_item = pl;\n    break;\n  }\n  if(current_uv_item == nullptr)\n    return;\n  current_uv_item->set_current_component((std::max)(0,current_uv_item->current_component()-1));\n  replacePolyline();\n}\n\nvoid Polyhedron_demo_parameterization_plugin::on_nextButton_pressed()\n{\n  int id = scene->mainSelectionIndex();\n  Q_FOREACH(UVItem* pl, projections)\n  {\n    if(pl==nullptr\n       || pl != projections[scene->item(id)])\n      continue;\n\n    current_uv_item = pl;\n    break;\n  }\n  if(current_uv_item == nullptr)\n    return;\n  current_uv_item->set_current_component((std::min)(current_uv_item->number_of_components()-1,current_uv_item->current_component()+1));\n  ui_widget.component_numberLabel->setText(QString(\"Component : %1/%2\").arg(current_uv_item->current_component()+1).arg(current_uv_item->number_of_components()));\n  replacePolyline();\n}\n\nvoid Polyhedron_demo_parameterization_plugin::parameterize(const Parameterization_method method)\n{\n  // get active polyhedron\n  Scene_facegraph_item* poly_item = nullptr;\n  CGAL::Three::Scene_interface::Item_id index = scene->mainSelectionIndex();\n  Q_FOREACH(CGAL::Three::Scene_interface::Item_id id, scene->selectionIndices())\n  {\n    poly_item = qobject_cast<Scene_facegraph_item*>(scene->item(id));\n    if(!poly_item)\n    {\n      continue;\n    }\n    else\n    {\n      index = id;\n      break;\n    }\n  }\n\n  if(!poly_item)\n  {\n    CGAL::Three::Three::error(\"Selected item is not of the right type.\");\n    return;\n  }\n\n  Face_graph* pMesh = poly_item->face_graph();\n  if(!pMesh)\n  {\n    CGAL::Three::Three::error(\"Selected item has no valid polyhedron.\");\n    return;\n  }\n  Scene_polyhedron_selection_item* sel_item = nullptr;\n  bool is_seamed = false;\n  Q_FOREACH(CGAL::Three::Scene_interface::Item_id id, scene->selectionIndices())\n  {\n    sel_item = qobject_cast<Scene_polyhedron_selection_item*>(scene->item(id));\n    if(!sel_item)\n      continue;\n    if(sel_item->selected_edges.empty())\n      continue;\n    if(method == PARAM_OTE && sel_item->selected_vertices.empty())\n       continue;\n    is_seamed = true;\n  }\n\n  if(method == PARAM_OTE &&\n     (sel_item == nullptr || sel_item->selected_vertices.empty())) {\n    std::cerr << \"\\nError: no cones/seam selected; Aborting parameterization.\" << std::endl;\n    return;\n  }\n\n  // Two property maps to store the seam edges and vertices\n  Seam_edge_uhm seam_edge_uhm(false);\n  Seam_edge_pmap seam_edge_pm(seam_edge_uhm);\n\n  Seam_vertex_uhm seam_vertex_uhm(false);\n  Seam_vertex_pmap seam_vertex_pm(seam_vertex_uhm);\n\n  if(!is_seamed && is_closed(*pMesh))\n  {\n    CGAL::Three::Three::error(\"The selected mesh has no (real or virtual) border.\");\n    return;\n  }\n\n  QApplication::setOverrideCursor(Qt::WaitCursor);\n\n  ///////////////////////////////////\n  ////////// PARAMETERIZE ///////////\n  ///////////////////////////////////\n\n  QElapsedTimer time;\n  time.start();\n  // add textured polyhedon to the scene\n\n  // \\todo for surface_mesh\n  Base_face_graph tMesh = *pMesh;\n  std::vector<bool> mark(num_halfedges(tMesh)/2,false);\n  std::vector<T_edge_descriptor> seam_edges;\n  typedef boost::property_map<Base_face_graph, boost::vertex_index_t>::type VIDMap;\n  VIDMap vidmap = get(boost::vertex_index, tMesh);\n  if(is_seamed)\n  {\n    //create a textured_polyhedron edges selection from the ids of the corresponding vertices\n    typedef boost::property_map<Base_face_graph, boost::halfedge_index_t>::type HIDMap;\n    HIDMap hidmap = get(boost::halfedge_index, tMesh);\n    for(P_edge_descriptor ed : sel_item->selected_edges)\n    {\n      boost::graph_traits<Face_graph>::vertex_descriptor a(source(ed, *pMesh)), b(target(ed, *pMesh));\n\n      for(boost::graph_traits<Textured_face_graph>::edge_iterator it =\n          edges(tMesh).begin(); it != edges(tMesh).end();\n          ++it)\n      {\n        boost::graph_traits<Textured_face_graph>::vertex_descriptor ta(source(*it, tMesh)), tb(target(*it, tMesh));\n\n        if((get(vidmap, ta) == get(vidmap, a) && get(vidmap,tb) == get(vidmap,b))\n           ||\n           (get(vidmap,ta) == get(vidmap,b) && get(vidmap,tb) == get(vidmap,a)))\n        {\n          T_edge_descriptor ted(*it);\n          seam_edges.push_back(ted);\n          break;\n        }\n      }\n\n    }\n    qDebug() << sel_item->selected_edges.size() << \", \" << seam_edges.size();\n    //fill seam mesh pmaps\n    for(T_edge_descriptor ed : seam_edges)\n    {\n      T_halfedge_descriptor hd = halfedge(ed, tMesh);\n      T_vertex_descriptor svd(source(hd, tMesh)), tvd(target(hd, tMesh));\n      if(!is_border(ed, tMesh))\n      {\n        put(seam_edge_pm, ed, true);\n        put(seam_vertex_pm, svd, true);\n        put(seam_vertex_pm, tvd, true);\n        mark[get(hidmap, hd)/2] = true;\n      }\n    }\n  }\n\n  // map the cones from the selection plugin to the textured polyhedron\n  std::unordered_set<T_vertex_descriptor> unordered_cones;\n  if(method == PARAM_OTE) {\n    for(P_vertex_descriptor vd : sel_item->selected_vertices) {\n      boost::graph_traits<Face_graph>::vertex_descriptor pvd(vd);\n      boost::graph_traits<Textured_face_graph>::vertex_iterator it = vertices(tMesh).begin(),\n          end = vertices(tMesh).end();\n      for(; it!=end; ++it) {\n        boost::graph_traits<Textured_face_graph>::vertex_descriptor tvd(*it);\n        if(get(vidmap, *it) == get(vidmap, pvd)) {\n          unordered_cones.insert(tvd);\n        }\n      }\n    }\n  }\n  Seam_mesh sMesh(tMesh, seam_edge_pm, seam_vertex_pm);\n  sMesh.set_seam_edges_number(static_cast<s_edges_size_type>(seam_edges.size()));\n\n  // The parameterized values\n  UV_uhm uv_uhm;\n  UV_pmap uv_pm(uv_uhm);\n\n  QString new_item_name;\n  //determine the different connected_components\n  boost::container::flat_map<boost::graph_traits<Base_face_graph>::face_descriptor, int> face_component_map;\n  boost::associative_property_map< boost::container::flat_map<s_face_descriptor, int> >\n      fccmap(face_component_map);\n\n  Is_selected_property_map edge_pmap(mark, &tMesh);\n\n  int number_of_components =\n      CGAL::Polygon_mesh_processing::connected_components(\n        tMesh,\n        fccmap,\n        CGAL::parameters::edge_is_constrained_map(\n          edge_pmap));\n\n  // Next is the gathering of the border halfedges of the connected component.\n  // It is wrong to pass the underlying mesh tMesh: a sphere split in half does\n  // not have any border if border_halfedges() is run with tMesh.\n  //\n  // The proper way would be to completely redesign the plugin to use Seam meshes\n  // everywhere. But that's not worth it. Instead, we abuse the fact that faces\n  // are the same in tMesh and sMesh.\n\n  // the SEAM MESH faces of each connected component\n  SComponents s_components(number_of_components);\n\n  for(boost::graph_traits<Base_face_graph>::face_iterator fit = faces(tMesh).begin();\n      fit != faces(tMesh).end(); ++fit) {\n    s_components.at(fccmap[*fit]).insert(s_face_descriptor(*fit));\n  }\n\n  // once per component\n  std::vector<std::vector<float> >uv_borders;\n  uv_borders.resize(number_of_components);\n\n  // to track whether the components are successfully parameterized\n  SMP::Error_code status = SMP::OK;\n\n  for(int current_component=0; current_component<number_of_components; ++current_component)\n  {\n    std::vector<s_halfedge_descriptor> border;\n    PMP::border_halfedges(s_components.at(current_component),\n                          sMesh, std::back_inserter(border));\n\n    std::cout << sMesh.number_of_seam_edges() << \" seams\" << std::endl;\n    std::cout << (s_components.at(current_component)).size() << \" faces\" << std::endl;\n    std::cout << border.size() << \" border halfedges\" << std::endl;\n\n    // find longest border in the connected component\n    s_halfedge_descriptor bhd; // a halfedge on the (possibly virtual) border\n    std::unordered_set<s_halfedge_descriptor> visited;\n    FT result_len = 0;\n    for(s_halfedge_descriptor hd : border)\n    {\n      assert(is_border(hd, sMesh));\n\n      if(visited.find(hd) == visited.end())\n      {\n        FT len = 0;\n        for(s_halfedge_descriptor haf : halfedges_around_face(hd, sMesh))\n        {\n          len += PMP::edge_length(haf, sMesh);\n          visited.insert(haf);\n        }\n\n        if(result_len < len)\n        {\n          result_len = len;\n          bhd = hd;\n        }\n      }\n    }\n    CGAL_postcondition(bhd != s_halfedge_descriptor());\n    CGAL_postcondition(is_border(bhd, sMesh));\n    typedef boost::property_map<Base_face_graph, boost::vertex_point_t>::type VPMap;\n    VPMap vpmap =get(boost::vertex_point, tMesh);\n\n    // collect the border edges for that connected component\n    for(s_halfedge_descriptor haf : halfedges_around_face(bhd, sMesh))\n    {\n        uv_borders[current_component].push_back(get(vpmap, source(haf, tMesh)).x());\n        uv_borders[current_component].push_back(get(vpmap, source(haf, tMesh)).y());\n        uv_borders[current_component].push_back(get(vpmap, source(haf, tMesh)).z());\n\n        uv_borders[current_component].push_back(get(vpmap, target(haf, tMesh)).x());\n        uv_borders[current_component].push_back(get(vpmap, target(haf, tMesh)).y());\n        uv_borders[current_component].push_back(get(vpmap, target(haf, tMesh)).z());\n    }\n\n    switch(method)\n    {\n    case PARAM_MVC:\n    {\n      std::cout << \"Parameterize (MVC)...\" << std::endl;\n      new_item_name = tr(\"%1 (parameterized (MVC))\").arg(poly_item->name());\n      typedef SMP::Mean_value_coordinates_parameterizer_3<Seam_mesh> Parameterizer;\n      status = SMP::parameterize(sMesh, Parameterizer(), bhd, uv_pm);\n      break;\n    }\n    case PARAM_DCP:\n    {\n      new_item_name = tr(\"%1 (parameterized (DCP))\").arg(poly_item->name());\n      std::cout << \"Parameterize (DCP)...\" << std::endl;\n      typedef SMP::Discrete_conformal_map_parameterizer_3<Seam_mesh> Parameterizer;\n      status = SMP::parameterize(sMesh, Parameterizer(), bhd, uv_pm);\n      break;\n    }\n    case PARAM_LSC:\n    {\n      new_item_name = tr(\"%1 (parameterized (LSC))\").arg(poly_item->name());\n      std::cout << \"Parameterize (LSC)...\" << std::endl;\n      typedef SMP::LSCM_parameterizer_3<Seam_mesh> Parameterizer;\n      status = SMP::parameterize(sMesh, Parameterizer(), bhd, uv_pm);\n      break;\n    }\n    case PARAM_DAP:\n    {\n      new_item_name = tr(\"%1 (parameterized (DAP))\").arg(poly_item->name());\n      std::cout << \"Parameterize (DAP)...\" << std::endl;\n      typedef SMP::Discrete_authalic_parameterizer_3<Seam_mesh> Parameterizer;\n      status = SMP::parameterize(sMesh, Parameterizer(), bhd, uv_pm);\n      break;\n    }\n    case PARAM_IAP:\n    {\n      new_item_name = tr(\"%1 (parameterized (IAP))\").arg(poly_item->name());\n      std::cout << \"Parameterize (IAP)...\" << std::endl;\n      typedef SMP::Iterative_authalic_parameterizer_3<Seam_mesh> Parameterizer;\n      Parameterizer parameterizer;\n      status = parameterizer.parameterize(sMesh, bhd, uv_pm, 15 /*iterations*/);\n      break;\n    }\n    case PARAM_ARAP:\n    {\n      new_item_name = tr(\"%1 (parameterized (ARAP))\").arg(poly_item->name());\n      std::cout << \"Parameterize (ARAP)...\" << std::endl;\n      FT lambda = 10000; // a big value to ensure the parameterization is ARAP (and not ASAP)\n      typedef SMP::ARAP_parameterizer_3<Seam_mesh> Parameterizer;\n      status = SMP::parameterize(sMesh, Parameterizer(lambda), bhd, uv_pm);\n      break;\n    }\n    case PARAM_OTE:\n    {\n      new_item_name = tr(\"%1 (parameterized (OTE))\").arg(poly_item->name());\n      std::cout << \"Parameterize (OTE)...\" << std::endl;\n\n      // OTE cannot handle multiple connected components right now\n      // @todo (need to remove the assertions such as cones.size() == 4\n      //        and check where and when cones are used (passed by ID, for ex.?))\n      if(number_of_components != 1) {\n        std::cerr << \"Orbifold Tutte Embedding can only handle one connected component\" << std::endl;\n        status = SMP::ERROR_NO_TOPOLOGICAL_BALL;\n        break;\n      }\n\n      typedef SMP::Orbifold_Tutte_parameterizer_3<Seam_mesh> Parameterizer;\n\n      // Get orbifold type\n      QDialog dialog(mw);\n      Ui::OTE_dialog ui;\n      ui.setupUi(&dialog);\n      connect(ui.buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));\n      connect(ui.buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));\n\n      QApplication::restoreOverrideCursor();\n\n      int i = dialog.exec();\n      if (i == QDialog::Rejected)\n      {\n        std::cout << \"Aborting parameterization\" << std::endl;\n        QApplication::restoreOverrideCursor();\n        return;\n      }\n\n      SMP::Orbifold_type orb = static_cast<SMP::Orbifold_type>(ui.OrbComboBox->currentIndex());\n      std::cout << \"Selected orbifold type: \" << ui.OrbComboBox->currentText().toStdString() << std::endl;\n\n      if((unordered_cones.size() != 3 && unordered_cones.size() != 4) ||\n         (unordered_cones.size() == 3 && orb == SMP::Parallelogram ) ||\n         (unordered_cones.size() == 4 && orb != SMP::Parallelogram)) {\n        std::cerr << \"Error: incompatible orbifold type and number of cones\" << std::endl;\n        std::cerr << \"Types I, II & III require 3 selected vertices\" << std::endl;\n        std::cerr << \"Type IV requires 4 selected vertices\" << std::endl;\n        QApplication::restoreOverrideCursor();\n        return;\n      }\n\n      // Now, parameterize\n      Parameterizer parameterizer(orb);\n\n      // Mark cones in the seam mesh\n      std::unordered_map<s_vertex_descriptor, SMP::Cone_type> cmap;\n      if(!SMP::locate_unordered_cones(sMesh, unordered_cones.begin(), unordered_cones.end(), cmap))\n      {\n        std::cerr << \"Error: invalid cone or seam selection\" << std::endl;\n        QApplication::restoreOverrideCursor();\n        return;\n      }\n\n      QApplication::setOverrideCursor(Qt::WaitCursor);\n\n      // Fill the index property map\n      typedef std::unordered_map<s_vertex_descriptor, int> Indices;\n      Indices indices;\n      CGAL::Polygon_mesh_processing::connected_component(\n             face(opposite(bhd, sMesh), sMesh),\n             sMesh,\n             boost::make_function_output_iterator(\n             SMP::internal::Index_map_filler<Seam_mesh, Indices>(sMesh, indices)));\n      boost::associative_property_map<Indices> vimap(indices);\n\n      // Call to parameterizer\n      status = parameterizer.parameterize(sMesh, bhd, cmap, uv_pm, vimap);\n      break;\n    }\n    case PARAM_BTP:\n    {\n      std::cout << \"Parameterize (BTP)...\" << std::endl;\n      new_item_name = tr(\"%1 (parameterized (BTP))\").arg(poly_item->name());\n      typedef SMP::Barycentric_mapping_parameterizer_3<Seam_mesh> Parameterizer;\n      status = SMP::parameterize(sMesh, Parameterizer(), bhd, uv_pm);\n      break;\n    }\n    } //end switch\n\n    std::cout << \"Connected component \" << current_component << \": \";\n    if(status == SMP::OK) {\n      std::cout << \"success (in \" << time.elapsed() << \" ms)\" << std::endl;\n    } else {\n      std::cerr << \"failure: \" << SMP::get_error_message(status) << std::endl;\n      QApplication::restoreOverrideCursor();\n      return;\n    }\n\n    if(status != SMP::OK)\n      break;\n\n  } //end for each component\n\n  QApplication::restoreOverrideCursor();\n  QPointF pmin(FLT_MAX, FLT_MAX), pmax(-FLT_MAX, -FLT_MAX);\n\n  SMesh::Property_map<halfedge_descriptor, float> umap;\n  SMesh::Property_map<halfedge_descriptor, float> vmap;\n\n  umap = tMesh.add_property_map<halfedge_descriptor, float>(\"h:u\", 0.0f).first;\n  vmap = tMesh.add_property_map<halfedge_descriptor, float>(\"h:v\", 0.0f).first;\n\n  tMesh.property_stats(std::cerr);\n  Base_face_graph::Halfedge_iterator it;\n  for(it = tMesh.halfedges_begin();\n      it != tMesh.halfedges_end();\n      ++it)\n  {\n    Seam_mesh::halfedge_descriptor hd(*it);\n    FT u = uv_pm[target(hd, sMesh)].x();\n    FT v = uv_pm[target(hd, sMesh)].y();\n    put(umap, *it, static_cast<float>(u));\n    put(vmap, *it, static_cast<float>(v));\n    if(u<pmin.x())\n      pmin.setX(u);\n    if(u>pmax.x())\n      pmax.setX(u);\n    if(v<pmin.y())\n      pmin.setY(v);\n    if(v>pmax.y())\n      pmax.setY(v);\n  }\n\n  Components* components = new Components(0);\n  components->resize(number_of_components);\n  boost::graph_traits<Base_face_graph>::face_iterator bfit;\n\n  for(bfit = faces(tMesh).begin();\n      bfit != faces(tMesh).end();\n      ++bfit)\n  {\n    components->at(fccmap[*bfit]).insert(*bfit);\n  }\n\n  Scene_textured_facegraph_item* new_item = new Scene_textured_facegraph_item(tMesh);\n  UVItem *projection = new UVItem(components,new_item->textured_face_graph(), uv_borders, QRectF(pmin, pmax));\n  projection->set_item_name(new_item_name);\n\n  new_item->setName(new_item_name);\n  new_item->setColor(Qt::white);\n  new_item->setRenderingMode(poly_item->renderingMode());\n  connect( new_item, SIGNAL(selectionChanged()),\n           this, SLOT(replacePolyline()) );\n  poly_item->setVisible(false);\n  scene->itemChanged(index);\n  scene->addItem(new_item);\n  if(!graphics_scene->items().empty())\n    graphics_scene->removeItem(graphics_scene->items().first());\n  graphics_scene->addItem(projection);\n  projections[new_item] = projection;\n  if(current_uv_item){\n    Scene_textured_facegraph_item* t_item =\n        qobject_cast<Scene_textured_facegraph_item*>(projections.key(current_uv_item));\n   t_item->add_border_edges(std::vector<float>(0));\n  }\n  current_uv_item = projection;\n  Scene_textured_facegraph_item* t_item =\n      qobject_cast<Scene_textured_facegraph_item*>(projections.key(current_uv_item));\n  t_item->add_border_edges(\n        current_uv_item->concatenated_borders());\n  if(dock_widget->isHidden()){\n    dock_widget->setVisible(true);\n    dock_widget->raise();\n  }\n  dock_widget->setWindowTitle(tr(\"UVMapping for %1\").arg(new_item->name()));\n  ui_widget.component_numberLabel->setText(QString(\"Component : %1/%2\").arg(current_uv_item->current_component()+1).arg(current_uv_item->number_of_components()));\n  ui_widget.graphicsView->fitInView(projection->boundingRect(), Qt::KeepAspectRatio);\n\n  QApplication::restoreOverrideCursor();\n\n}\n\nvoid Polyhedron_demo_parameterization_plugin::on_actionMVC_triggered()\n{\n  std::cerr << \"MVC...\";\n  parameterize(PARAM_MVC);\n}\n\nvoid Polyhedron_demo_parameterization_plugin::on_actionDCP_triggered()\n{\n  std::cerr << \"DCP...\";\n  parameterize(PARAM_DCP);\n}\n\nvoid Polyhedron_demo_parameterization_plugin::on_actionLSC_triggered()\n{\n  std::cerr << \"LSC...\";\n  parameterize(PARAM_LSC);\n}\n\nvoid Polyhedron_demo_parameterization_plugin::on_actionDAP_triggered()\n{\n  std::cerr << \"DAP...\";\n  parameterize(PARAM_DAP);\n}\n\nvoid Polyhedron_demo_parameterization_plugin::on_actionIAP_triggered()\n{\n  std::cerr << \"IAP...\";\n  parameterize(PARAM_IAP);\n}\n\nvoid Polyhedron_demo_parameterization_plugin::on_actionARAP_triggered()\n{\n  std::cerr << \"ARAP...\";\n  parameterize(PARAM_ARAP);\n}\n\nvoid Polyhedron_demo_parameterization_plugin::on_actionOTE_triggered()\n{\n  std::cerr << \"OTE...\";\n  parameterize(PARAM_OTE);\n}\n\nvoid Polyhedron_demo_parameterization_plugin::on_actionBTP_triggered()\n{\n  std::cerr << \"BTP...\";\n  parameterize(PARAM_BTP);\n}\n\n#include \"Parameterization_plugin.moc\"\n", "meta": {"hexsha": "448c9b270274ea15e00e4c678945c915a030f15c", "size": 36281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Parameterization_plugin.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Parameterization_plugin.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Polyhedron/demo/Polyhedron/Plugins/Surface_mesh/Parameterization_plugin.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4222011385, "max_line_length": 162, "alphanum_fraction": 0.674623081, "num_tokens": 8941, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.40381618724712104}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2011-2014, Willow Garage, Inc.\n *  Copyright (c) 2014-2015, Open Source Robotics Foundation\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of Open Source Robotics Foundation nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n */\n\n/** \\author Jia Pan */\n\n#include <hpp/fcl/ccd/taylor_model.h>\n#include <cassert>\n#include <iostream>\n#include <cmath>\n#include <boost/math/constants/constants.hpp>\n\n\nnamespace fcl\n{\n\nTaylorModel::TaylorModel()\n{\n  coeffs_[0] = coeffs_[1] = coeffs_[2] = coeffs_[3] = 0;\n}\n\nTaylorModel::TaylorModel(const boost::shared_ptr<TimeInterval>& time_interval) : time_interval_(time_interval)\n{\n  coeffs_[0] = coeffs_[1] = coeffs_[2] = coeffs_[3] = 0;\n}\n\nTaylorModel::TaylorModel(FCL_REAL coeff, const boost::shared_ptr<TimeInterval>& time_interval) : time_interval_(time_interval)\n{\n  coeffs_[0] = coeff;\n  coeffs_[1] = coeffs_[2] = coeffs_[3] = r_[0] = r_[1] = 0;\n}\n\nTaylorModel::TaylorModel(FCL_REAL coeffs[3], const Interval& r, const boost::shared_ptr<TimeInterval>& time_interval) : time_interval_(time_interval)\n{\n  coeffs_[0] = coeffs[0];\n  coeffs_[1] = coeffs[1];\n  coeffs_[2] = coeffs[2];\n  coeffs_[3] = coeffs[3];\n\n  r_ = r;\n}\n\nTaylorModel::TaylorModel(FCL_REAL c0, FCL_REAL c1, FCL_REAL c2, FCL_REAL c3, const Interval& r, const boost::shared_ptr<TimeInterval>& time_interval) : time_interval_(time_interval)\n{\n  coeffs_[0] = c0;\n  coeffs_[1] = c1;\n  coeffs_[2] = c2;\n  coeffs_[3] = c3;\n\n  r_ = r;\n}\n\nTaylorModel TaylorModel::operator + (FCL_REAL d) const\n{\n  return TaylorModel(coeffs_[0] + d, coeffs_[1], coeffs_[2], coeffs_[3], r_, time_interval_);\n}\n\nTaylorModel& TaylorModel::operator += (FCL_REAL d)\n{\n  coeffs_[0] += d;\n  return *this;\n}\n\nTaylorModel TaylorModel::operator - (FCL_REAL d) const\n{\n  return TaylorModel(coeffs_[0] - d, coeffs_[1], coeffs_[2], coeffs_[3], r_, time_interval_);\n}\n\nTaylorModel& TaylorModel::operator -= (FCL_REAL d)\n{\n  coeffs_[0] -= d;\n  return *this;\n}\n\n\nTaylorModel TaylorModel::operator + (const TaylorModel& other) const\n{\n  assert(other.time_interval_ == time_interval_);\n  return TaylorModel(coeffs_[0] + other.coeffs_[0], coeffs_[1] + other.coeffs_[1], coeffs_[2] + other.coeffs_[2], coeffs_[3] + other.coeffs_[3], r_ + other.r_, time_interval_);\n}\n\nTaylorModel TaylorModel::operator - (const TaylorModel& other) const\n{\n  assert(other.time_interval_ == time_interval_);\n  return TaylorModel(coeffs_[0] - other.coeffs_[0], coeffs_[1] - other.coeffs_[1], coeffs_[2] - other.coeffs_[2], coeffs_[3] - other.coeffs_[3], r_ - other.r_, time_interval_);\n}\nTaylorModel& TaylorModel::operator += (const TaylorModel& other)\n{\n  assert(other.time_interval_ == time_interval_);\n  coeffs_[0] += other.coeffs_[0];\n  coeffs_[1] += other.coeffs_[1];\n  coeffs_[2] += other.coeffs_[2];\n  coeffs_[3] += other.coeffs_[3];\n  r_ += other.r_;\n  return *this;\n}\n\nTaylorModel& TaylorModel::operator -= (const TaylorModel& other)\n{\n  assert(other.time_interval_ == time_interval_);\n  coeffs_[0] -= other.coeffs_[0];\n  coeffs_[1] -= other.coeffs_[1];\n  coeffs_[2] -= other.coeffs_[2];\n  coeffs_[3] -= other.coeffs_[3];\n  r_ -= other.r_;\n  return *this;\n}\n\n/// @brief Taylor model multiplication:\n/// f(t) = c0+c1*t+c2*t^2+c3*t^3+[a,b]\n/// g(t) = c0'+c1'*t+c2'*t^2+c3'*t^2+[c,d]\n/// f(t)g(t)= c0c0'+\n///           (c0c1'+c1c0')t+\n///           (c0c2'+c1c1'+c2c0')t^2+\n///           (c0c3'+c1c2'+c2c1'+c3c0')t^3+\n///           [a,b][c,d]+\n///           (c1c3'+c2c2'+c3c1')t^4+\n///           (c2c3'+c3c2')t^5+\n///           (c3c3')t^6+\n///           (c0+c1*t+c2*t^2+c3*t^3)[c,d]+\n///           (c0'+c1'*t+c2'*t^2+c3'*c^3)[a,b]\nTaylorModel TaylorModel::operator * (const TaylorModel& other) const\n{\n  TaylorModel res(*this);\n  res *= other;\n  return res;\n}\n\nTaylorModel TaylorModel::operator * (FCL_REAL d) const\n{\n  return TaylorModel(coeffs_[0] * d, coeffs_[1] * d, coeffs_[2] * d, coeffs_[3] * d,  r_ * d, time_interval_);\n}\n\nTaylorModel& TaylorModel::operator *= (const TaylorModel& other)\n{\n  assert(other.time_interval_ == time_interval_);\n  register FCL_REAL c0, c1, c2, c3;\n  register FCL_REAL c0b = other.coeffs_[0], c1b = other.coeffs_[1], c2b = other.coeffs_[2], c3b = other.coeffs_[3];\n\n  const Interval& rb = other.r_;\n\n  c0 = coeffs_[0] * c0b;\n  c1 = coeffs_[0] * c1b + coeffs_[1] * c0b;\n  c2 = coeffs_[0] * c2b + coeffs_[1] * c1b + coeffs_[2] * c0b;\n  c3 = coeffs_[0] * c3b + coeffs_[1] * c2b + coeffs_[2] * c1b + coeffs_[3] * c0b;\n\n  Interval remainder(r_ * rb);\n  register FCL_REAL tempVal = coeffs_[1] * c3b + coeffs_[2] * c2b + coeffs_[3] * c1b;\n  remainder += time_interval_->t4_ * tempVal;\n\n  tempVal = coeffs_[2] * c3b + coeffs_[3] * c2b;\n  remainder += time_interval_->t5_ * tempVal;\n\n  tempVal = coeffs_[3] * c3b;\n  remainder += time_interval_->t6_ * tempVal;\n\n  remainder += ((Interval(coeffs_[0]) + time_interval_->t_ * coeffs_[1] + time_interval_->t2_ * coeffs_[2] + time_interval_->t3_ * coeffs_[3]) * rb +\n                (Interval(c0b) + time_interval_->t_ * c1b + time_interval_->t2_ * c2b + time_interval_->t3_ * c3b) * r_);\n\n  coeffs_[0] = c0;\n  coeffs_[1] = c1;\n  coeffs_[2] = c2;\n  coeffs_[3] = c3;\n\n  r_ = remainder;\n\n  return *this;\n}\n\nTaylorModel& TaylorModel::operator *= (FCL_REAL d)\n{\n  coeffs_[0] *= d;\n  coeffs_[1] *= d;\n  coeffs_[2] *= d;\n  coeffs_[3] *= d;\n  r_ *= d;\n  return *this;\n}\n\n\nTaylorModel TaylorModel::operator - () const\n{\n  return TaylorModel(-coeffs_[0], -coeffs_[1], -coeffs_[2], -coeffs_[3], -r_, time_interval_);\n}\n\nvoid TaylorModel::print() const\n{\n  std::cout << coeffs_[0] << \"+\" << coeffs_[1] << \"*t+\" << coeffs_[2] << \"*t^2+\" << coeffs_[3] << \"*t^3+[\" << r_[0] << \",\" << r_[1] << \"]\" << std::endl;\n}\n\nInterval TaylorModel::getBound(FCL_REAL t) const\n{\n  return Interval(coeffs_[0] + t * (coeffs_[1] + t * (coeffs_[2] + t * coeffs_[3]))) + r_;\n}\n\nInterval TaylorModel::getBound(FCL_REAL t0, FCL_REAL t1) const\n{\n  Interval t(t0, t1);\n  Interval t2(t0 * t0, t1 * t1);\n  Interval t3(t0 * t2[0], t1 * t2[1]);\n\n  return Interval(coeffs_[0]) + t * coeffs_[1] + t2 * coeffs_[2] + t3 * coeffs_[3] + r_;\n}\n\nInterval TaylorModel::getBound() const\n{\n  return Interval(coeffs_[0] + r_[0], coeffs_[1] + r_[1]) + time_interval_->t_ * coeffs_[1] + time_interval_->t2_ * coeffs_[2] + time_interval_->t3_ * coeffs_[3];\n}\n\nInterval TaylorModel::getTightBound(FCL_REAL t0, FCL_REAL t1) const\n{\n  if(t0 < time_interval_->t_[0]) t0 = time_interval_->t_[0];\n  if(t1 > time_interval_->t_[1]) t1 = time_interval_->t_[1];\n\n  if(coeffs_[3] == 0)\n  {\n    register FCL_REAL a = -coeffs_[1] / (2 * coeffs_[2]);\n    Interval polybounds;\n    if(a <= t1 && a >= t0)\n    {\n      FCL_REAL AQ = coeffs_[0] + a * (coeffs_[1] + a * coeffs_[2]);\n      register FCL_REAL t = t0;\n      FCL_REAL LQ = coeffs_[0] + t * (coeffs_[1] + t * coeffs_[2]);\n      t = t1;\n      FCL_REAL RQ = coeffs_[0] + t * (coeffs_[1] + t * coeffs_[2]);\n\n      FCL_REAL minQ = LQ, maxQ = RQ;\n      if(LQ > RQ)\n      {\n        minQ = RQ;\n        maxQ = LQ;\n      }\n\n      if(minQ > AQ) minQ = AQ;\n      if(maxQ < AQ) maxQ = AQ;\n\n      polybounds.setValue(minQ, maxQ);\n    }\n    else\n    {\n      register FCL_REAL t = t0;\n      FCL_REAL LQ = coeffs_[0] + t * (coeffs_[1] + t * coeffs_[2]);\n      t = t1;\n      FCL_REAL RQ = coeffs_[0] + t * (coeffs_[1] + t * coeffs_[2]);\n\n      if(LQ > RQ) polybounds.setValue(RQ, LQ);\n      else polybounds.setValue(LQ, RQ);\n    }\n\n    return polybounds + r_;\n  }\n  else\n  {\n    register FCL_REAL t = t0;\n    FCL_REAL LQ = coeffs_[0] + t * (coeffs_[1] + t * (coeffs_[2] + t * coeffs_[3]));\n    t = t1;\n    FCL_REAL RQ = coeffs_[0] + t * (coeffs_[1] + t * (coeffs_[2] + t * coeffs_[3]));\n\n    if(LQ > RQ)\n    {\n      FCL_REAL tmp = LQ;\n      LQ = RQ;\n      RQ = tmp;\n    }\n\n    // derivative: c1+2*c2*t+3*c3*t^2\n\n    FCL_REAL delta = coeffs_[2] * coeffs_[2] - 3 * coeffs_[1] * coeffs_[3];\n    if(delta < 0)\n      return Interval(LQ, RQ) + r_;\n\n    FCL_REAL r1 = (-coeffs_[2]-sqrt(delta))/(3*coeffs_[3]);\n    FCL_REAL r2 = (-coeffs_[2]+sqrt(delta))/(3*coeffs_[3]);\n\n    if(r1 <= t1 && r1 >= t0)\n    {\n      FCL_REAL Q = coeffs_[0] + r1 * (coeffs_[1] + r1 * (coeffs_[2] + r1 * coeffs_[3]));\n      if(Q < LQ) LQ = Q;\n      else if(Q > RQ) RQ = Q;\n    }\n\n    if(r2 <= t1 && r2 >= t0)\n    {\n      FCL_REAL Q = coeffs_[0] + r2 * (coeffs_[1] + r2 * (coeffs_[2] + r2 * coeffs_[3]));\n      if(Q < LQ) LQ = Q;\n      else if(Q > RQ) RQ = Q;\n    }\n\n    return Interval(LQ, RQ) + r_;\n  }\n}\n\nInterval TaylorModel::getTightBound() const\n{\n  return getTightBound(time_interval_->t_[0], time_interval_->t_[1]);\n}\n\nvoid TaylorModel::setZero()\n{\n  coeffs_[0] = coeffs_[1] = coeffs_[2] = coeffs_[3] = 0;\n  r_.setValue(0);\n}\n\nTaylorModel operator * (FCL_REAL d, const TaylorModel& a)\n{\n  TaylorModel res(a);\n  res.coeff(0) *= d;\n  res.coeff(1) *= d;\n  res.coeff(2) *= d;\n  res.coeff(3) *= d;\n  res.remainder() *= d;\n  return res;\n}\n\nTaylorModel operator + (FCL_REAL d, const TaylorModel& a)\n{\n  return a + d;\n}\n\nTaylorModel operator - (FCL_REAL d, const TaylorModel& a)\n{\n  return -a + d;\n}\n\n\nvoid generateTaylorModelForCosFunc(TaylorModel& tm, FCL_REAL w, FCL_REAL q0)\n{\n  FCL_REAL a = tm.getTimeInterval()->t_.center();\n  FCL_REAL t = w * a + q0;\n  FCL_REAL w2 = w * w;\n  FCL_REAL fa = cos(t);\n  FCL_REAL fda = -w*sin(t);\n  FCL_REAL fdda = -w2*fa;\n  FCL_REAL fddda = -w2*fda;\n\n  tm.coeff(0) = fa-a*(fda-0.5*a*(fdda-1.0/3.0*a*fddda));\n  tm.coeff(1) = fda-a*fdda+0.5*a*a*fddda;\n  tm.coeff(2) = 0.5*(fdda-a*fddda);\n  tm.coeff(3) = 1.0/6.0*fddda;\n\n  // compute bounds for w^3 cos(wt+q0)/16, t \\in [t0, t1]\n  Interval fddddBounds;\n  if(w == 0) fddddBounds.setValue(0);\n  else\n  {\n    FCL_REAL cosQL = cos(tm.getTimeInterval()->t_[0] * w + q0);\n    FCL_REAL cosQR = cos(tm.getTimeInterval()->t_[1] * w + q0);\n\n    if(cosQL < cosQR) fddddBounds.setValue(cosQL, cosQR);\n    else fddddBounds.setValue(cosQR, cosQL);\n\n    // enlarge to handle round-off errors\n    fddddBounds[0] -= 1e-15;\n    fddddBounds[1] += 1e-15;\n\n    // cos reaches maximum if there exists an integer k in [(w*t0+q0)/2pi, (w*t1+q0)/2pi];\n    // cos reaches minimum if there exists an integer k in [(w*t0+q0-pi)/2pi, (w*t1+q0-pi)/2pi]\n\n    FCL_REAL k1 = (tm.getTimeInterval()->t_[0] * w + q0) / (2 * boost::math::constants::pi<FCL_REAL>());\n    FCL_REAL k2 = (tm.getTimeInterval()->t_[1] * w + q0) / (2 * boost::math::constants::pi<FCL_REAL>());\n\n\n    if(w > 0)\n    {\n      if(ceil(k2) - floor(k1) > 1) fddddBounds[1] = 1;\n      k1 -= 0.5;\n      k2 -= 0.5;\n      if(ceil(k2) - floor(k1) > 1) fddddBounds[0] = -1;\n    }\n    else\n    {\n      if(ceil(k1) - floor(k2) > 1) fddddBounds[1] = 1;\n      k1 -= 0.5;\n      k2 -= 0.5;\n      if(ceil(k1) - floor(k2) > 1) fddddBounds[0] = -1;\n    }\n  }\n\n  FCL_REAL w4 = w2 * w2;\n  fddddBounds *= w4;\n\n  FCL_REAL midSize = 0.5 * (tm.getTimeInterval()->t_[1] - tm.getTimeInterval()->t_[0]);\n  FCL_REAL midSize2 = midSize * midSize;\n  FCL_REAL midSize4 = midSize2 * midSize2;\n\n  // [0, midSize4] * fdddBounds\n  if(fddddBounds[0] > 0)\n    tm.remainder().setValue(0, fddddBounds[1] * midSize4 * (1.0 / 24));\n  else if(fddddBounds[0] < 0)\n    tm.remainder().setValue(fddddBounds[0] * midSize4 * (1.0 / 24), 0);\n  else\n    tm.remainder().setValue(fddddBounds[0] * midSize4 * (1.0 / 24), fddddBounds[1] * midSize4 * (1.0 / 24));\n}\n\nvoid generateTaylorModelForSinFunc(TaylorModel& tm, FCL_REAL w, FCL_REAL q0)\n{\n  FCL_REAL a = tm.getTimeInterval()->t_.center();\n  FCL_REAL t = w * a + q0;\n  FCL_REAL w2 = w * w;\n  FCL_REAL fa = sin(t);\n  FCL_REAL fda = w*cos(t);\n  FCL_REAL fdda = -w2*fa;\n  FCL_REAL fddda = -w2*fda;\n\n  tm.coeff(0) = fa-a*(fda-0.5*a*(fdda-1.0/3.0*a*fddda));\n  tm.coeff(1) = fda-a*fdda+0.5*a*a*fddda;\n  tm.coeff(2) = 0.5*(fdda-a*fddda);\n  tm.coeff(3) = 1.0/6.0*fddda;\n\n  // compute bounds for w^3 sin(wt+q0)/16, t \\in [t0, t1]\n\n  Interval fddddBounds;\n\n  if(w == 0) fddddBounds.setValue(0);\n  else\n  {\n    FCL_REAL sinQL = sin(w * tm.getTimeInterval()->t_[0] + q0);\n    FCL_REAL sinQR = sin(w * tm.getTimeInterval()->t_[1] + q0);\n\n    if(sinQL < sinQR) fddddBounds.setValue(sinQL, sinQR);\n    else fddddBounds.setValue(sinQR, sinQL);\n\n    // enlarge to handle round-off errors\n    fddddBounds[0] -= 1e-15;\n    fddddBounds[1] += 1e-15;\n\n    // sin reaches maximum if there exists an integer k in [(w*t0+q0-pi/2)/2pi, (w*t1+q0-pi/2)/2pi];\n    // sin reaches minimum if there exists an integer k in [(w*t0+q0-pi-pi/2)/2pi, (w*t1+q0-pi-pi/2)/2pi]\n\n    FCL_REAL k1 = (tm.getTimeInterval()->t_[0] * w + q0) / (2 * boost::math::constants::pi<FCL_REAL>()) - 0.25;\n    FCL_REAL k2 = (tm.getTimeInterval()->t_[1] * w + q0) / (2 * boost::math::constants::pi<FCL_REAL>()) - 0.25;\n\n    if(w > 0)\n    {\n      if(ceil(k2) - floor(k1) > 1) fddddBounds[1] = 1;\n      k1 -= 0.5;\n      k2 -= 0.5;\n      if(ceil(k2) - floor(k1) > 1) fddddBounds[0] = -1;\n    }\n    else\n    {\n      if(ceil(k1) - floor(k2) > 1) fddddBounds[1] = 1;\n      k1 -= 0.5;\n      k2 -= 0.5;\n      if(ceil(k1) - floor(k2) > 1) fddddBounds[0] = -1;\n    }\n\n    FCL_REAL w4 = w2 * w2;\n    fddddBounds *= w4;\n\n    FCL_REAL midSize = 0.5 * (tm.getTimeInterval()->t_[1] - tm.getTimeInterval()->t_[0]);\n    FCL_REAL midSize2 = midSize * midSize;\n    FCL_REAL midSize4 = midSize2 * midSize2;\n\n    // [0, midSize4] * fdddBounds\n    if(fddddBounds[0] > 0)\n      tm.remainder().setValue(0, fddddBounds[1] * midSize4 * (1.0 / 24));\n    else if(fddddBounds[0] < 0)\n      tm.remainder().setValue(fddddBounds[0] * midSize4 * (1.0 / 24), 0);\n    else\n      tm.remainder().setValue(fddddBounds[0] * midSize4 * (1.0 / 24), fddddBounds[1] * midSize4 * (1.0 / 24));\n  }\n}\n\nvoid generateTaylorModelForLinearFunc(TaylorModel& tm, FCL_REAL p, FCL_REAL v)\n{\n  tm.coeff(0) = p;\n  tm.coeff(1) = v;\n  tm.coeff(2) = 0;\n  tm.coeff(3) = 0;\n  tm.remainder()[0] = 0;\n  tm.remainder()[1] = 0;\n}\n\n}\n", "meta": {"hexsha": "b1b64468bffd010cd4c707eafee6fd9d2d70155b", "size": 15199, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ccd/taylor_model.cpp", "max_stars_repo_name": "nassimeblinlaas/hpp-fcl-nouveau", "max_stars_repo_head_hexsha": "0a52cde1b64b1e9f25cf38bb60a80b06f98ec37a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ccd/taylor_model.cpp", "max_issues_repo_name": "nassimeblinlaas/hpp-fcl-nouveau", "max_issues_repo_head_hexsha": "0a52cde1b64b1e9f25cf38bb60a80b06f98ec37a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ccd/taylor_model.cpp", "max_forks_repo_name": "nassimeblinlaas/hpp-fcl-nouveau", "max_forks_repo_head_hexsha": "0a52cde1b64b1e9f25cf38bb60a80b06f98ec37a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9783037475, "max_line_length": 181, "alphanum_fraction": 0.6178038029, "num_tokens": 5358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.40381618724712104}}
{"text": "// Copyright (c) 2012 libmv authors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n#include \"libmv/simple_pipeline/keyframe_selection.h\"\n\n#include \"libmv/numeric/numeric.h\"\n#include \"ceres/ceres.h\"\n#include \"libmv/logging/logging.h\"\n#include \"libmv/multiview/homography.h\"\n#include \"libmv/multiview/fundamental.h\"\n#include \"libmv/simple_pipeline/intersect.h\"\n#include \"libmv/simple_pipeline/bundle.h\"\n\n#include <Eigen/Eigenvalues>\n\nnamespace libmv {\nnamespace {\n\nVec2 NorrmalizedToPixelSpace(const Vec2 &vec,\n                             const CameraIntrinsics &intrinsics) {\n  Vec2 result;\n\n  double focal_length_x = intrinsics.focal_length_x();\n  double focal_length_y = intrinsics.focal_length_y();\n\n  double principal_point_x = intrinsics.principal_point_x();\n  double principal_point_y = intrinsics.principal_point_y();\n\n  result(0) = vec(0) * focal_length_x + principal_point_x;\n  result(1) = vec(1) * focal_length_y + principal_point_y;\n\n  return result;\n}\n\nMat3 IntrinsicsNormalizationMatrix(const CameraIntrinsics &intrinsics) {\n  Mat3 T = Mat3::Identity(), S = Mat3::Identity();\n\n  T(0, 2) = -intrinsics.principal_point_x();\n  T(1, 2) = -intrinsics.principal_point_y();\n\n  S(0, 0) /= intrinsics.focal_length_x();\n  S(1, 1) /= intrinsics.focal_length_y();\n\n  return S * T;\n}\n\nclass HomographySymmetricGeometricCostFunctor {\n public:\n  HomographySymmetricGeometricCostFunctor(const Vec2 &x,\n                                          const Vec2 &y)\n      : x_(x), y_(y) { }\n\n  template<typename T>\n  bool operator()(const T *homography_parameters, T *residuals) const {\n    typedef Eigen::Matrix<T, 3, 3> Mat3;\n    typedef Eigen::Matrix<T, 3, 1> Vec3;\n\n    Mat3 H(homography_parameters);\n\n    Vec3 x(T(x_(0)), T(x_(1)), T(1.0));\n    Vec3 y(T(y_(0)), T(y_(1)), T(1.0));\n\n    Vec3 H_x = H * x;\n    Vec3 Hinv_y = H.inverse() * y;\n\n    H_x /= H_x(2);\n    Hinv_y /= Hinv_y(2);\n\n    residuals[0] = H_x(0) - T(y_(0));\n    residuals[1] = H_x(1) - T(y_(1));\n\n    residuals[2] = Hinv_y(0) - T(x_(0));\n    residuals[3] = Hinv_y(1) - T(x_(1));\n\n    return true;\n  }\n\n  const Vec2 x_;\n  const Vec2 y_;\n};\n\nvoid ComputeHomographyFromCorrespondences(const Mat &x1, const Mat &x2,\n                                          CameraIntrinsics &intrinsics,\n                                          Mat3 *H) {\n  // Algebraic homography estimation, happens with normalized coordinates\n  Homography2DFromCorrespondencesLinear(x1, x2, H, 1e-12);\n\n  // Refine matrix using Ceres minimizer\n\n  // TODO(sergey): look into refinement in pixel space.\n  ceres::Problem problem;\n\n  for (int i = 0; i < x1.cols(); i++) {\n    HomographySymmetricGeometricCostFunctor\n        *homography_symmetric_geometric_cost_function =\n            new HomographySymmetricGeometricCostFunctor(x1.col(i),\n                                                        x2.col(i));\n\n    problem.AddResidualBlock(\n        new ceres::AutoDiffCostFunction<\n            HomographySymmetricGeometricCostFunctor,\n            4, /* num_residuals */\n            9>(homography_symmetric_geometric_cost_function),\n        NULL,\n        H->data());\n  }\n\n  // Configure the solve.\n  ceres::Solver::Options solver_options;\n  solver_options.linear_solver_type = ceres::DENSE_QR;\n  solver_options.max_num_iterations = 50;\n  solver_options.update_state_every_iteration = true;\n  solver_options.parameter_tolerance = 1e-16;\n  solver_options.function_tolerance = 1e-16;\n\n  // Run the solve.\n  ceres::Solver::Summary summary;\n  ceres::Solve(solver_options, &problem, &summary);\n\n  VLOG(1) << \"Summary:\\n\" << summary.FullReport();\n\n  // Convert homography to original pixel space\n  Mat3 N = IntrinsicsNormalizationMatrix(intrinsics);\n  *H = N.inverse() * (*H) * N;\n}\n\nclass FundamentalSymmetricEpipolarCostFunctor {\n public:\n  FundamentalSymmetricEpipolarCostFunctor(const Vec2 &x,\n                                          const Vec2 &y)\n    : x_(x), y_(y) {}\n\n  template<typename T>\n  bool operator()(const T *fundamental_parameters, T *residuals) const {\n    typedef Eigen::Matrix<T, 3, 3> Mat3;\n    typedef Eigen::Matrix<T, 3, 1> Vec3;\n\n    Mat3 F(fundamental_parameters);\n\n    Vec3 x(T(x_(0)), T(x_(1)), T(1.0));\n    Vec3 y(T(y_(0)), T(y_(1)), T(1.0));\n\n    Vec3 F_x = F * x;\n    Vec3 Ft_y = F.transpose() * y;\n    T y_F_x = y.dot(F_x);\n\n    residuals[0] = y_F_x * T(1) / F_x.head(2).norm();\n    residuals[1] = y_F_x * T(1) / Ft_y.head(2).norm();\n\n    return true;\n  }\n\n  const Mat x_;\n  const Mat y_;\n};\n\nvoid ComputeFundamentalFromCorrespondences(const Mat &x1, const Mat &x2,\n                                           CameraIntrinsics &intrinsics,\n                                           Mat3 *F) {\n  // Algebraic fundamental estimation, happens with normalized coordinates\n  NormalizedEightPointSolver(x1, x2, F);\n\n  // Refine matrix using Ceres minimizer\n\n  // TODO(sergey): look into refinement in pixel space.\n  ceres::Problem problem;\n\n  for (int i = 0; i < x1.cols(); i++) {\n    FundamentalSymmetricEpipolarCostFunctor\n        *fundamental_symmetric_epipolar_cost_function =\n            new FundamentalSymmetricEpipolarCostFunctor(x1.col(i),\n                                                        x2.col(i));\n\n    problem.AddResidualBlock(\n        new ceres::AutoDiffCostFunction<\n            FundamentalSymmetricEpipolarCostFunctor,\n            2, /* num_residuals */\n            9>(fundamental_symmetric_epipolar_cost_function),\n        NULL,\n        F->data());\n  }\n\n  // Configure the solve.\n  ceres::Solver::Options solver_options;\n  solver_options.linear_solver_type = ceres::DENSE_NORMAL_CHOLESKY;\n  solver_options.max_num_iterations = 50;\n  solver_options.update_state_every_iteration = true;\n  solver_options.parameter_tolerance = 1e-16;\n  solver_options.function_tolerance = 1e-16;\n\n  // Run the solve.\n  ceres::Solver::Summary summary;\n  ceres::Solve(solver_options, &problem, &summary);\n\n  VLOG(1) << \"Summary:\\n\" << summary.FullReport();\n\n  // Convert fundamental to original pixel space\n  Mat3 N = IntrinsicsNormalizationMatrix(intrinsics);\n  *F = N.inverse() * (*F) * N;\n}\n\n// P.H.S. Torr\n// Geometric Motion Segmentation and Model Selection\n//\n// http://reference.kfupm.edu.sa/content/g/e/geometric_motion_segmentation_and_model__126445.pdf\n//\n// d is the number of dimensions modeled\n//     (d = 3 for a fundamental matrix or 2 for a homography)\n// k is the number of degrees of freedom in the model\n//     (k = 7 for a fundamental matrix or 8 for a homography)\n// r is the dimension of the data\n//     (r = 4 for 2D correspondences between two frames)\ndouble GRIC(const Vec &e, int d, int k, int r) {\n  int n = e.rows();\n  double lambda1 = log(static_cast<double>(r));\n  double lambda2 = log(static_cast<double>(r * n));\n\n  // lambda3 limits the residual error, and this paper\n  // http://elvera.nue.tu-berlin.de/files/0990Knorr2006.pdf\n  // suggests using lambda3 of 2\n  // same value is used in Torr's Problem of degeneracy in structure\n  // and motion recovery from uncalibrated image sequences\n  // http://www.robots.ox.ac.uk/~vgg/publications/papers/torr99.ps.gz\n  double lambda3 = 2.0;\n\n  // measurement error of tracker\n  double sigma2 = 0.01;\n\n  // Actual GRIC computation\n  double gric_result = 0.0;\n\n  for (int i = 0; i < n; i++) {\n    double rho = std::min(e(i) * e(i) / sigma2, lambda3 * (r - d));\n    gric_result += rho;\n  }\n\n  gric_result += lambda1 * d * n;\n  gric_result += lambda2 * k;\n\n  return gric_result;\n}\n\n// Compute a generalized inverse using eigen value decomposition.\n// It'll actually also zero 7 last eigen values to deal with\n// gauges, since this function is used to compute variance of\n// reconstructed 3D points.\n//\n// TODO(sergey): Could be generalized by making it so number\n//               of values to be zeroed is passed by an argument\n//               and moved to numeric module.\nMat pseudoInverse(const Mat &matrix) {\n  Eigen::EigenSolver<Mat> eigenSolver(matrix);\n  Mat D = eigenSolver.pseudoEigenvalueMatrix();\n  Mat V = eigenSolver.pseudoEigenvectors();\n\n  double epsilon = std::numeric_limits<double>::epsilon();\n\n  for (int i = 0; i < D.cols(); ++i) {\n    if (D(i, i) > epsilon)\n      D(i, i) = 1.0 / D(i, i);\n    else\n      D(i, i) = 0.0;\n  }\n\n  // Zero last 7 (which corresponds to smallest eigen values).\n  // 7 equals to the number of gauge freedoms.\n  for (int i = D.cols() - 7; i < D.cols(); ++i)\n    D(i, i) = 0.0;\n\n  return V * D * V.inverse();\n}\n}  // namespace\n\nvoid SelectkeyframesBasedOnGRICAndVariance(const Tracks &tracks,\n                                           CameraIntrinsics &intrinsics,\n                                           vector<int> &keyframes) {\n  // Mirza Tahir Ahmed, Matthew N. Dailey\n  // Robust key frame extraction for 3D reconstruction from video streams\n  //\n  // http://www.cs.ait.ac.th/~mdailey/papers/Tahir-KeyFrame.pdf\n\n  int max_image = tracks.MaxImage();\n  int next_keyframe = 1;\n  int number_keyframes = 0;\n\n  // Limit correspondence ratio from both sides.\n  // On the one hand if number of correspondent features is too low,\n  // triangulation will suffer.\n  // On the other hand high correspondence likely means short baseline.\n  // which also will affect om accuracy\n  const double Tmin = 0.8;\n  const double Tmax = 1.0;\n\n  Mat3 N = IntrinsicsNormalizationMatrix(intrinsics);\n  Mat3 N_inverse = N.inverse();\n\n  double Sc_best = std::numeric_limits<double>::max();\n  double success_intersects_factor_best = 0.0f;\n\n  while (next_keyframe != -1) {\n    int current_keyframe = next_keyframe;\n    double Sc_best_candidate = std::numeric_limits<double>::max();\n\n    LG << \"Found keyframe \" << next_keyframe;\n\n    number_keyframes++;\n    next_keyframe = -1;\n\n    for (int candidate_image = current_keyframe + 1;\n         candidate_image <= max_image;\n         candidate_image++) {\n      // Conjunction of all markers from both keyframes\n      vector<Marker> all_markers =\n        tracks.MarkersInBothImages(current_keyframe, candidate_image);\n\n      // Match keypoints between frames current_keyframe and candidate_image\n      vector<Marker> tracked_markers =\n        tracks.MarkersForTracksInBothImages(current_keyframe, candidate_image);\n\n      // Correspondences in normalized space\n      Mat x1, x2;\n      CoordinatesForMarkersInImage(tracked_markers, current_keyframe, &x1);\n      CoordinatesForMarkersInImage(tracked_markers, candidate_image, &x2);\n\n      LG << \"Found \" << x1.cols()\n         << \" correspondences between \" << current_keyframe\n         << \" and \" << candidate_image;\n\n      // Not enough points to construct fundamental matrix\n      if (x1.cols() < 8 || x2.cols() < 8)\n        continue;\n\n      // STEP 1: Correspondence ratio constraint\n      int Tc = tracked_markers.size();\n      int Tf = all_markers.size();\n      double Rc = static_cast<double>(Tc) / Tf;\n\n      LG << \"Correspondence between \" << current_keyframe\n         << \" and \" << candidate_image\n         << \": \" << Rc;\n\n      if (Rc < Tmin || Rc > Tmax)\n        continue;\n\n      Mat3 H, F;\n      ComputeHomographyFromCorrespondences(x1, x2, intrinsics, &H);\n      ComputeFundamentalFromCorrespondences(x1, x2, intrinsics, &F);\n\n      // TODO(sergey): STEP 2: Discard outlier matches\n\n      // STEP 3: Geometric Robust Information Criteria\n\n      // Compute error values for homography and fundamental matrices\n      Vec H_e, F_e;\n      H_e.resize(x1.cols());\n      F_e.resize(x1.cols());\n      for (int i = 0; i < x1.cols(); i++) {\n        Vec2 current_x1 =\n          NorrmalizedToPixelSpace(Vec2(x1(0, i), x1(1, i)), intrinsics);\n        Vec2 current_x2 =\n          NorrmalizedToPixelSpace(Vec2(x2(0, i), x2(1, i)), intrinsics);\n\n        H_e(i) = SymmetricGeometricDistance(H, current_x1, current_x2);\n        F_e(i) = SymmetricEpipolarDistance(F, current_x1, current_x2);\n      }\n\n      LG << \"H_e: \" << H_e.transpose();\n      LG << \"F_e: \" << F_e.transpose();\n\n      // Degeneracy constraint\n      double GRIC_H = GRIC(H_e, 2, 8, 4);\n      double GRIC_F = GRIC(F_e, 3, 7, 4);\n\n      LG << \"GRIC values for frames \" << current_keyframe\n         << \" and \" << candidate_image\n         << \", H-GRIC: \" << GRIC_H\n         << \", F-GRIC: \" << GRIC_F;\n\n      if (GRIC_H <= GRIC_F)\n        continue;\n\n      // TODO(sergey): STEP 4: PELC criterion\n\n      // STEP 5: Estimation of reconstruction error\n      //\n      // Uses paper Keyframe Selection for Camera Motion and Structure\n      // Estimation from Multiple Views\n      // Uses ftp://ftp.tnt.uni-hannover.de/pub/papers/2004/ECCV2004-TTHBAW.pdf\n      // Basically, equation (15)\n      //\n      // TODO(sergey): separate all the constraints into functions,\n      //               this one is getting to much cluttered already\n\n      // Definitions in equation (15):\n      // - I is the number of 3D feature points\n      // - A is the number of essential parameters of one camera\n\n      EuclideanReconstruction reconstruction;\n\n      // The F matrix should be an E matrix, but squash it just to be sure\n\n      // Reconstruction should happen using normalized fundamental matrix\n      Mat3 F_normal = N * F * N_inverse;\n\n      Mat3 E;\n      FundamentalToEssential(F_normal, &E);\n\n      // Recover motion between the two images. Since this function assumes a\n      // calibrated camera, use the identity for K\n      Mat3 R;\n      Vec3 t;\n      Mat3 K = Mat3::Identity();\n\n      if (!MotionFromEssentialAndCorrespondence(E,\n                                                K, x1.col(0),\n                                                K, x2.col(0),\n                                                &R, &t)) {\n        LG << \"Failed to compute R and t from E and K\";\n        continue;\n      }\n\n      LG << \"Camera transform between frames \" << current_keyframe\n         << \" and \" << candidate_image\n         << \":\\nR:\\n\" << R\n         << \"\\nt:\" << t.transpose();\n\n      // First camera is identity, second one is relative to it\n      reconstruction.InsertCamera(current_keyframe,\n                                  Mat3::Identity(),\n                                  Vec3::Zero());\n      reconstruction.InsertCamera(candidate_image, R, t);\n\n      // Reconstruct 3D points\n      int intersects_total = 0, intersects_success = 0;\n      for (int i = 0; i < tracked_markers.size(); i++) {\n        if (!reconstruction.PointForTrack(tracked_markers[i].track)) {\n          vector<Marker> reconstructed_markers;\n\n          int track = tracked_markers[i].track;\n\n          reconstructed_markers.push_back(tracked_markers[i]);\n\n          // We know there're always only two markers for a track\n          // Also, we're using brute-force search because we don't\n          // actually know about markers layout in a list, but\n          // at this moment this cycle will run just once, which\n          // is not so big deal\n\n          for (int j = i + 1; j < tracked_markers.size(); j++) {\n            if (tracked_markers[j].track == track) {\n              reconstructed_markers.push_back(tracked_markers[j]);\n              break;\n            }\n          }\n\n          intersects_total++;\n\n          if (EuclideanIntersect(reconstructed_markers, &reconstruction)) {\n            LG << \"Ran Intersect() for track \" << track;\n            intersects_success++;\n          } else {\n            LG << \"Filed to intersect track \" << track;\n          }\n        }\n      }\n\n      double success_intersects_factor =\n          (double) intersects_success / intersects_total;\n\n      if (success_intersects_factor < success_intersects_factor_best) {\n        LG << \"Skip keyframe candidate because of \"\n              \"lower successful intersections ratio\";\n\n        continue;\n      }\n\n      success_intersects_factor_best = success_intersects_factor;\n\n      Tracks two_frames_tracks(tracked_markers);\n      CameraIntrinsics empty_intrinsics;\n      BundleEvaluation evaluation;\n      evaluation.evaluate_jacobian = true;\n\n      EuclideanBundleCommonIntrinsics(two_frames_tracks,\n                                      BUNDLE_NO_INTRINSICS,\n                                      BUNDLE_NO_CONSTRAINTS,\n                                      &reconstruction,\n                                      &empty_intrinsics,\n                                      &evaluation);\n\n      Mat &jacobian = evaluation.jacobian;\n\n      Mat JT_J = jacobian.transpose() * jacobian;\n      Mat JT_J_inv = pseudoInverse(JT_J);\n\n      Mat temp_derived = JT_J * JT_J_inv * JT_J;\n      bool is_inversed = (temp_derived - JT_J).cwiseAbs2().sum() <\n          1e-4 * std::min(temp_derived.cwiseAbs2().sum(),\n                          JT_J.cwiseAbs2().sum());\n\n      LG << \"Check on inversed: \" << (is_inversed ? \"true\" : \"false\" )\n         << \", det(JT_J): \" << JT_J.determinant();\n\n      if (!is_inversed) {\n        LG << \"Ignoring candidature due to poor jacobian stability\";\n        continue;\n      }\n\n      Mat Sigma_P;\n      Sigma_P = JT_J_inv.bottomRightCorner(evaluation.num_points * 3,\n                                           evaluation.num_points * 3);\n\n      int I = evaluation.num_points;\n      int A = 12;\n\n      double Sc = static_cast<double>(I + A) / Square(3 * I) * Sigma_P.trace();\n\n      LG << \"Expected estimation error between \"\n         << current_keyframe << \" and \"\n         << candidate_image << \": \" << Sc;\n\n      // Pairing with a lower Sc indicates a better choice\n      if (Sc > Sc_best_candidate)\n        continue;\n\n      Sc_best_candidate = Sc;\n\n      next_keyframe = candidate_image;\n    }\n\n    // This is a bit arbitrary and main reason of having this is to deal\n    // better with situations when there's no keyframes were found for\n    // current keyframe this could happen when there's no so much parallax\n    // in the beginning of image sequence and then most of features are\n    // getting occluded. In this case there could be good keyframe pair in\n    // the middle of the sequence\n    //\n    // However, it's just quick hack and smarter way to do this would be nice\n    if (next_keyframe == -1) {\n      next_keyframe = current_keyframe + 10;\n      number_keyframes = 0;\n\n      if (next_keyframe >= max_image)\n        break;\n\n      LG << \"Starting searching for keyframes starting from \" << next_keyframe;\n    } else {\n      // New pair's expected reconstruction error is lower\n      // than existing pair's one.\n      //\n      // For now let's store just one candidate, easy to\n      // store more candidates but needs some thoughts\n      // how to choose best one automatically from them\n      // (or allow user to choose pair manually).\n      if (Sc_best > Sc_best_candidate) {\n        keyframes.clear();\n        keyframes.push_back(current_keyframe);\n        keyframes.push_back(next_keyframe);\n        Sc_best = Sc_best_candidate;\n      }\n    }\n  }\n}\n\n}  // namespace libmv\n", "meta": {"hexsha": "71993845e393b1fe19facae93162a485836c6473", "size": 19671, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libmv/simple_pipeline/keyframe_selection.cc", "max_stars_repo_name": "paulinus/libmv", "max_stars_repo_head_hexsha": "6656bde5aea4c715695fa98fca6e2b3417e82d76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libmv/simple_pipeline/keyframe_selection.cc", "max_issues_repo_name": "paulinus/libmv", "max_issues_repo_head_hexsha": "6656bde5aea4c715695fa98fca6e2b3417e82d76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libmv/simple_pipeline/keyframe_selection.cc", "max_forks_repo_name": "paulinus/libmv", "max_forks_repo_head_hexsha": "6656bde5aea4c715695fa98fca6e2b3417e82d76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7409948542, "max_line_length": 96, "alphanum_fraction": 0.6298103808, "num_tokens": 4958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4038161800083794}}
{"text": "/*\n==============================================================================\nKratosStructuralApplication\nA library based on:\nKratos\nA General Purpose Software for Multi-Physics Finite Element Analysis\nVersion 1.0 (Released on march 05, 2007).\n\nCopyright 2007\nPooyan Dadvand, Riccardo Rossi, Janosch Stascheit, Felix Nagel\npooyan@cimne.upc.edu\nrrossi@cimne.upc.edu\njanosch.stascheit@rub.de\nnagel@sd.rub.de\n- CIMNE (International Center for Numerical Methods in Engineering),\nGran Capita' s/n, 08034 Barcelona, Spain\n- Ruhr-University Bochum, Institute for Structural Mechanics, Germany\n\n\nPermission is hereby granted, free  of charge, to any person obtaining\na  copy  of this  software  and  associated  documentation files  (the\n\"Software\"), to  deal in  the Software without  restriction, including\nwithout limitation  the rights to  use, copy, modify,  merge, publish,\ndistribute,  sublicense and/or  sell copies  of the  Software,  and to\npermit persons to whom the Software  is furnished to do so, subject to\nthe following condition:\n\nDistribution of this code for  any  commercial purpose  is permissible\nONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS.\n\nThe  above  copyright  notice  and  this permission  notice  shall  be\nincluded in all copies or substantial portions of the Software.\n\nTHE  SOFTWARE IS  PROVIDED  \"AS  IS\", WITHOUT  WARRANTY  OF ANY  KIND,\nEXPRESS OR  IMPLIED, INCLUDING  BUT NOT LIMITED  TO THE  WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT  SHALL THE AUTHORS OR COPYRIGHT HOLDERS  BE LIABLE FOR ANY\nCLAIM, DAMAGES OR  OTHER LIABILITY, WHETHER IN AN  ACTION OF CONTRACT,\nTORT  OR OTHERWISE, ARISING  FROM, OUT  OF OR  IN CONNECTION  WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n==============================================================================\n*/\n/* **************************************************************************************\n*\n*   Last Modified by:    $Author: G.D.Huynh $\n*   Date:                $Date: 25.042018 $\n*   Revision:            $Revision: 1.0 $\n*\n* ***************************************************************************************/\n\n\n// System includes\n// External includes\n#include <boost/timer.hpp>\n// Project includes\n#include \"includes/define.h\"\n#include \"custom_elements/nonlinear_bending_strip.h\"\n#include \"utilities/math_utils.h\"\n#include \"utilities/openmp_utils.h\"\n#include \"structural_application/custom_utilities/sd_math_utils.h\"\n#include \"isogeometric_application/custom_utilities/isogeometric_math_utils.h\"\n#include \"isogeometric_application/isogeometric_application.h\"\n\n#define ENABLE_PROFILING\n\n#include <iostream>\nusing namespace std;\n\nnamespace Kratos\n{\n//***********************************************************************************\n//***********************************************************************************\n// -------- //\n//  PUBLIC  //\n// -------- //\n\n// Constructor\nNonLinearBendingStrip::NonLinearBendingStrip()\n{\n}\n\n// Constructor\nNonLinearBendingStrip::NonLinearBendingStrip( IndexType NewId, GeometryType::Pointer pGeometry )\n    : Element( NewId, pGeometry )\n{\n    mpIsogeometricGeometry =\n        boost::dynamic_pointer_cast<IsogeometricGeometryType>(pGetGeometry());\n}\n\n// Constructor\nNonLinearBendingStrip::NonLinearBendingStrip( IndexType NewId, GeometryType::Pointer pGeometry,\n                          PropertiesType::Pointer pProperties )\n    : Element( NewId, pGeometry, pProperties )\n{\n    mpIsogeometricGeometry =\n        boost::dynamic_pointer_cast<IsogeometricGeometryType>(pGetGeometry());\n}\n\n//***********************************************************************************\n//***********************************************************************************\nElement::Pointer NonLinearBendingStrip::Create( IndexType NewId,\n                                        NodesArrayType const& ThisNodes,\n                                        PropertiesType::Pointer pProperties ) const\n{\n    return Element::Pointer( new NonLinearBendingStrip( NewId, GetGeometry().Create( ThisNodes ), pProperties ) );\n}\n\n//***********************************************************************************\n//***********************************************************************************\nElement::Pointer NonLinearBendingStrip::Create( IndexType NewId,\n    GeometryType::Pointer pGeom,\n    PropertiesType::Pointer pProperties ) const\n{\nreturn Element::Pointer( new NonLinearBendingStrip( NewId, pGeom, pProperties ) );\n}\n\n//***********************************************************************************\n//***********************************************************************************\n// Destructor\nNonLinearBendingStrip::~NonLinearBendingStrip()\n{\n}\n\n//***********************************************************************************\n//***********************************************************************************\nvoid NonLinearBendingStrip::EquationIdVector( EquationIdVectorType& rResult,\n                                    const ProcessInfo& rCurrentProcessInfo ) const\n{\n    KRATOS_TRY\n    unsigned int number_of_nodes = GetGeometry().size();\n    unsigned int dim = number_of_nodes * 3;\n\n    if ( rResult.size() != dim )\n        rResult.resize( dim );\n\n    for ( unsigned int i = 0; i < number_of_nodes; i++ )\n    {\n        int index = i * 3;\n        rResult[index]   = GetGeometry()[i].GetDof( DISPLACEMENT_X ).EquationId();\n        rResult[index+1] = GetGeometry()[i].GetDof( DISPLACEMENT_Y ).EquationId();\n        rResult[index+2] = GetGeometry()[i].GetDof( DISPLACEMENT_Z ).EquationId();\n    }\n\n    //KRATOS_WATCH(rResult)\n\n    KRATOS_CATCH( \"\" )\n}\n\n//***********************************************************************************\n//***********************************************************************************\nvoid NonLinearBendingStrip::GetDofList( DofsVectorType& ElementalDofList,\n                              const ProcessInfo& rCurrentProcessInfo ) const\n{\n    ElementalDofList.resize( 0 );\n\n    for ( unsigned int i = 0; i < GetGeometry().size(); i++ )\n    {\n        ElementalDofList.push_back( GetGeometry()[i].pGetDof( DISPLACEMENT_X ) );\n        ElementalDofList.push_back( GetGeometry()[i].pGetDof( DISPLACEMENT_Y ) );\n        ElementalDofList.push_back( GetGeometry()[i].pGetDof( DISPLACEMENT_Z ) );\n    }\n}\n\n//***********************************************************************************\n//***********************************************************************************\nvoid NonLinearBendingStrip::Initialize(const ProcessInfo& rCurrentProcessInfo)\n{\n    KRATOS_TRY\n\n\n        mThisIntegrationMethod = GeometryData::GI_GAUSS_1;\n\n        mDim = 3;\n        mNumberOfNodes = mpIsogeometricGeometry->size();\n        mStrainSize = 3;\n        mNumberOfDof = mNumberOfNodes*mDim;\n        mThickness = GetProperties()[THICKNESS];\n\n        // material parameters\n        mE = GetProperties()[YOUNG_MODULUS];\n        mNU = GetProperties()[POISSON_RATIO];\n        mLambda = mE*mNU /(1.0 +mNU)/(1.0 - 2.0*mNU);\n        mMu = 0.5*mE/(1.0 + mNU);\n\n        ////////////////////////////////////////////////////////////////\n        // get nodal coordinates vector R in undeformed configuration //\n        if(mNodalCoordinates.size() != mNumberOfNodes)\n            mNodalCoordinates.resize(mNumberOfNodes);\n\n        for(unsigned int I=0; I< mNumberOfNodes; ++I)\n            mNodalCoordinates[I].resize(mDim);\n\n        for (unsigned int I=0; I< mNumberOfNodes; ++I)\n        {\n            mNodalCoordinates[I](0) = (*mpIsogeometricGeometry)[I].X0();\n            mNodalCoordinates[I](1) = (*mpIsogeometricGeometry)[I].Y0();\n            mNodalCoordinates[I](2) = (*mpIsogeometricGeometry)[I].Z0();\n        }\n\n        #ifdef ENABLE_BEZIER_GEOMETRY\n        //initialize the geometry\n        mpIsogeometricGeometry->Initialize(mThisIntegrationMethod);\n        #endif\n\n        //Initialization of the constitutive law vector and\n        // declaration, definition and initialization of the material\n        // law was at each integration point\n        const GeometryType::IntegrationPointsArrayType& integration_points =\n        mpIsogeometricGeometry->IntegrationPoints(mThisIntegrationMethod);\n\n        mNumberOfIntegrationPoint = integration_points.size();\n\n        //////////////////////////////////////////////////////////////\n        ///// compute  Jacobian ,Inverse Jacobian, Det Jacobian /////\n        mInvJ0.resize(integration_points.size());\n        mN.resize(integration_points.size());\n        mDN_De.resize(integration_points.size());\n\n        for (unsigned int i = 0; i < integration_points.size(); ++i)\n        {\n            mInvJ0[i].resize(mDim, mDim, false);\n            noalias(mInvJ0[i]) = ZeroMatrix(mDim, mDim);\n\n            mN[i].resize(mNumberOfNodes);\n            noalias(mN[i]) = ZeroVector(mNumberOfNodes);\n\n            mDN_De[i].resize(mNumberOfNodes, 2);\n            noalias(mDN_De[i]) = ZeroMatrix(mNumberOfNodes,2);\n\n        }\n\n\n        mDetJ0.resize(integration_points.size(), false);\n        // TODO remove the storage for Jacobian to save memory\n        noalias(mDetJ0) = ZeroVector(integration_points.size());\n\n        mIntegrationWeight.resize(integration_points.size());\n\n\n\n        // calculate the Jacobian\n        mJ0.resize(integration_points.size());\n        mJ0 = mpIsogeometricGeometry->Jacobian0(mJ0, mThisIntegrationMethod);\n        double DetJ_temp;\n        mTotalDomainInitialSize = 0.0;\n\n        for(unsigned int PointNumber = 0; PointNumber < integration_points.size(); ++ PointNumber)\n        {\n            mN[PointNumber] = mpIsogeometricGeometry->ShapeFunctionsValues( mN[PointNumber] , integration_points[PointNumber]);\n            mDN_De[PointNumber] = mpIsogeometricGeometry->ShapeFunctionsLocalGradients( mDN_De[PointNumber], integration_points[PointNumber]);\n\n            MathUtils<double>::InvertMatrix(mJ0[PointNumber], mInvJ0[PointNumber],  DetJ_temp);\n\n            Matrix JtJ = prod(trans(mJ0[PointNumber]), mJ0[PointNumber]);\n            mDetJ0[PointNumber] = sqrt(MathUtils<double>::Det(JtJ));\n\n            //getting informations for integration\n            mIntegrationWeight[PointNumber] = integration_points[PointNumber].Weight();\n\n            mTotalDomainInitialSize += mDetJ0[PointNumber]* mIntegrationWeight[PointNumber];\n\n\n        }\n\n\n        mIsInitialized = true;\n\n\n        #ifdef ENABLE_BEZIER_GEOMETRY\n        // clean the geometry internal data\n        mpIsogeometricGeometry->Clean();\n        #endif\n\n    KRATOS_CATCH(\"\")\n}\n\n//***********************************************************************************\n//***********************************************************************************\nvoid NonLinearBendingStrip::CalculateLocalSystem( MatrixType& rLeftHandSideMatrix,\n                                                VectorType& rRightHandSideVector,\n                                                const ProcessInfo& rCurrentProcessInfo )\n{\n    //calculation flags\n    bool CalculateStiffnessMatrixFlag = true;\n    bool CalculateResidualVectorFlag = true;\n\n    CalculateAll( rLeftHandSideMatrix, rRightHandSideVector, rCurrentProcessInfo,\n                  CalculateStiffnessMatrixFlag, CalculateResidualVectorFlag );\n}\n\n//***********************************************************************************\n//***********************************************************************************\nvoid NonLinearBendingStrip::CalculateAll( MatrixType& rLeftHandSideMatrix,\n                                VectorType& rRightHandSideVector,\n                                const ProcessInfo& rCurrentProcessInfo,\n                                bool CalculateStiffnessMatrixFlag,\n                                bool CalculateResidualVectorFlag )\n{\n    KRATOS_TRY\n\n\n    if (CalculateStiffnessMatrixFlag==true)\n    {\n        if (rLeftHandSideMatrix.size1() != mNumberOfDof)\n            rLeftHandSideMatrix.resize(mNumberOfDof, mNumberOfDof);\n        noalias(rLeftHandSideMatrix) = ZeroMatrix(mNumberOfDof, mNumberOfDof);\n    }\n\n    if (CalculateResidualVectorFlag==true)\n    {\n        if (rRightHandSideVector.size() != mNumberOfDof)\n            rRightHandSideVector.resize(mNumberOfDof);\n        noalias(rRightHandSideVector) = ZeroVector(mNumberOfDof);\n    }\n\n    ////////////////////////////////////////////////////////////////////////////////\n    ////// compute residual vector and stiffness matrix over integration points/////\n\n    #ifdef ENABLE_BEZIER_GEOMETRY\n    //initialize the geometry\n    mpIsogeometricGeometry->Initialize(mThisIntegrationMethod);\n    #endif\n\n    // get integration points\n    const GeometryType::IntegrationPointsArrayType& integration_points =\n        mpIsogeometricGeometry->IntegrationPoints(mThisIntegrationMethod);\n\n    // Current displacements\n    Matrix CurrentDisplacement(mNumberOfNodes, mDim);\n    for(unsigned int node =0; node < mpIsogeometricGeometry->size() ;++node)\n        noalias(row(CurrentDisplacement, node)) = (*mpIsogeometricGeometry)[node].GetSolutionStepValue(DISPLACEMENT);\n\n    ///////////////////////////////////////////////////////////////////////////////////////\n    //////////////////////////////////////// loop over integration points\n    for(unsigned int PointNumber=0; PointNumber < integration_points.size(); ++PointNumber)\n    {\n\n            //////////// get shape function values and their derivatives\n            ShapeFunctionsSecondDerivativesType D2N_De2;\n            D2N_De2 = mpIsogeometricGeometry->ShapeFunctionsSecondDerivatives(D2N_De2, integration_points[PointNumber]);\n\n            /////// i. covariant base vectors\n            std::vector<Vector> u_a;\n            std::vector<Vector> a;\n            std::vector<Vector> A;  // covarianti base vector of undeformed configuration\n            ReferenceCovariantBaseVector(A, mDN_De[PointNumber], mNodalCoordinates);\n            FirstDerivativeDisplacement_a( u_a, mDN_De[PointNumber] , CurrentDisplacement);\n            DeformedCovariantBaseVector( a, A, u_a );\n\n            // normal directors\n            Vector a3Vector, A3Vector, aa3Vector, AA3Vector; double a3, A3;\n            NormalDirector(a3Vector,  aa3Vector, a3, a);\n            NormalDirector(A3Vector, AA3Vector, A3, A);\n\n            ////ii. derivative of covariant base vectors\n            std::vector<std::vector<Vector> > u_ab;\n            std::vector<std::vector<Vector> > a_ab;\n            std::vector<std::vector<Vector> > A_ab;\n            DerivativeReferenceCovariantBaseVector(A_ab, D2N_De2, mNodalCoordinates);\n            SecondDerivativeDisplacement_ab( u_ab,  D2N_De2 , CurrentDisplacement);\n            DerivativeDeformedCovariantBaseVector( a_ab , A_ab,  u_ab);\n\n            std::vector<Vector> UnitBasisVector;\n            this->UnitBaseVectors(UnitBasisVector);\n\n            // a_ar\n            std::vector< std::vector<std::vector<Vector>> > a_ar;\n            DerivativeCovariantBaseVector_r( a_ar, mDN_De[PointNumber], UnitBasisVector);\n\n            // aa3_rVector\n            std::vector<std::vector<Vector>> aa3_rVector;\n            DerivativeNonNormalizedDirector_r( aa3_rVector , a_ar, a);\n\n            // a3_r\n            std::vector<std::vector<double>> a3_r;\n            DerivativeDirectorNorm_r(a3_r , aa3_rVector, a3Vector);\n\n            // a3_rVector\n            std::vector<std::vector<Vector>> a3_rVector;\n            DerivativeDirector_r(a3_rVector ,  aa3_rVector, a3_r, a3Vector, a3);\n\n            // a_abr\n            std::vector< std::vector<std::vector<std::vector<Vector>>> > a_abr;\n            DerivativeCovariantBaseVector_abr( a_abr, D2N_De2, UnitBasisVector);\n\n            /*// aa3_rsVector\n            std::vector<std::vector<std::vector<std::vector<Vector>>> > aa3_rsVector;\n            SecondDerivativeNonNormalizedDirector_rs( aa3_rsVector , a_ar);\n\n            // a3_rs\n            std::vector<std::vector<std::vector<std::vector<double>>> > a3_rs;\n            SecondDerivativeDirectorNorm_rs(a3_rs , aa3_rsVector,  aa3Vector, a3Vector,  a3, aa3_rVector);\n\n            // a3_rsVector\n            std::vector<std::vector<std::vector<std::vector<Vector>>> > a3_rsVector;\n            SecondDerivativeDirector_rs( a3_rsVector,  aa3_rsVector, a3_rs, a3Vector, a3,  aa3_rVector, a3_r);\n            */\n\n            // metric and curvature coefficents\n            Matrix Aab(2,2);\n            Matrix aab(2,2);\n            Matrix Bab(2,2);\n            Matrix bab(2,2);\n            CovariantMetricCoefficient(Aab, A);\n            CovariantMetricCoefficient(aab, a);\n            CovariantCurvatureCoefficient(Bab, A_ab, A3Vector);\n            CovariantCurvatureCoefficient(bab, a_ab, a3Vector);\n\n            double detJA = sqrt(MathUtils<double>::Det(Aab));\n            // contravariant base vectors\n            std::vector<Vector> AA;\n            ContravariantBaseVector( AA, A, Aab);\n\n            // local Cartesian basis\n            std::vector<Vector> EE;\n            LocalCartesianBasisVector(EE,  A, A3Vector);\n\n\n            // transformation coeff\n            std::vector< std::vector<std::vector<std::vector<double>>> > TransformationCoeff;\n            LocalTransformationCoefficient(TransformationCoeff, EE, AA);\n\n            // membrane and bending strains\n            Matrix kTensor;\n            computeCurvatureChange(kTensor,  Bab, bab);\n\n            // transform strains to local form\n            Matrix kkTensor = ZeroMatrix(2,2);\n            Vector kkVector(3);\n            LocalTransformationOfTensor(kkTensor , kTensor, TransformationCoeff);\n            kkVector = SD_MathUtils<int>::TensorToStrainVector( kkTensor);\n\n            // material matrix\n            Matrix D0 = ZeroMatrix(mStrainSize,mStrainSize);\n            CalculateConstitutiveMatrix(D0);\n\n            Vector moVector= ZeroVector(mStrainSize);\n            noalias(moVector) = pow(mThickness,3.0)/12.0*prod(D0,kkVector) ;\n\n            // first derivative of bending strains w.r.t displacement\n            std::vector<std::vector<Vector> > kLocalVector_r;\n            FirstDerivativeLocalCurvatureChange_r( kLocalVector_r,  a_abr, a_ab, a3Vector , a3_rVector, TransformationCoeff);\n\n            // bending bending B matrix\n            Matrix BBb(mStrainSize, mNumberOfDof);\n            CreatingBmatrix( BBb, kLocalVector_r);\n\n            ///////////////////////////////////////////////\n            ///// nonlinear part of stiffness matrix //////\n            ///////////////////////////////////////////////\n\n            //std::vector<std::vector<Matrix>> kLocalVector_rs;\n            //SecondDerivativeLocalCurvatureChange_rs(kLocalVector_rs , a_abr, a3_rVector,  a_ab, a3_rsVector, TransformationCoeff);\n\n\n            if(CalculateStiffnessMatrixFlag == true)\n            {\n                AddLinearStiffnessMatrix(rLeftHandSideMatrix, D0, BBb, BBb, pow(mThickness,3.0)/12.0*detJA , mIntegrationWeight[PointNumber]);\n                //AddNonlinearStiffnessMatrix(rLeftHandSideMatrix,moVector, kLocalVector_rs,  detJA , mIntegrationWeight[PointNumber]);\n            }\n\n            if(CalculateResidualVectorFlag == true)\n            {\n                AddInternalForces(rRightHandSideVector , moVector,kLocalVector_r, detJA , mIntegrationWeight[PointNumber]);\n\n            }\n\n\n    }// loop over integration points\n\n\n    //KRATOS_WATCH(rRightHandSideVector)\n\n\n    #ifdef ENABLE_BEZIER_GEOMETRY\n    // clean the geometry internal data\n    mpIsogeometricGeometry->Clean();\n    #endif\n\n\n    KRATOS_CATCH( \"\" )\n}\n\n    ///////////////////////////////////////// all components of residual vectors and stiffness matrices ///////////\n    ///////////////////// add left hand side contribution\n    void NonLinearBendingStrip::AddInternalForces(VectorType& RightHandSideVector, const Vector& StressResultants,\n        std::vector<std::vector<Vector> >& StrainVector_r, const double& DetJ, const double& Weight)\n    {\n       noalias(RightHandSideVector) -= StressResultants(0)*StrainVector_r[0][0]*DetJ*Weight;\n       noalias(RightHandSideVector) -= StressResultants(1)*StrainVector_r[1][1]*DetJ*Weight;\n       noalias(RightHandSideVector) -= StressResultants(2)*StrainVector_r[0][1]*DetJ*Weight;\n    }\n\n    void NonLinearBendingStrip::AddLinearStiffnessMatrix(MatrixType& LeftHandSideMatrix, const Matrix& Di, const Matrix& BlhsMatrix\n        , const Matrix& BrhsMatrix, const double& DetJ, const double& Weight)\n    {\n        noalias(LeftHandSideMatrix) += prod( trans(BlhsMatrix), Matrix(prod(Di, BrhsMatrix)) )*DetJ*Weight;\n    }\n\n    void NonLinearBendingStrip::AddNonlinearStiffnessMatrix( MatrixType& LeftHandSideMatrix,const Vector& StressResultants\n        , const std::vector<std::vector<Matrix>>& StrainVector_rs, const double& DetJ, const double& Weight)\n    {\n        noalias(LeftHandSideMatrix) += StressResultants(0)*StrainVector_rs[0][0]*DetJ*Weight;\n        noalias(LeftHandSideMatrix) += StressResultants(1)*StrainVector_rs[1][1]*DetJ*Weight;\n        noalias(LeftHandSideMatrix) += StressResultants(2)*StrainVector_rs[0][1]*DetJ*Weight;\n    }\n    ////////////////////////////////////////////////////////\n    ///////////////////// strain tensors ///////////////////\n    ////////////////////////////////////////////////////////\n\n\n    void NonLinearBendingStrip::computeCurvatureChange(Matrix& kTensor, Matrix& Bab, Matrix& bab)\n    {\n        kTensor.resize(2,2);\n        kTensor = ZeroMatrix(2,2);\n\n        noalias(kTensor) = Bab - bab;\n\n    }\n\n    /////////////////////////////////////////////////////////////////////////\n    /////////////////////////// base vectors and their derivatives///////////\n    /////////////////////////////////////////////////////////////////////////\n    void NonLinearBendingStrip::DeformedCovariantBaseVector(std::vector<Vector>& a, std::vector<Vector>& A\n                    , std::vector<Vector>& u_a )\n    {\n\n        a.resize(2);\n        for(unsigned int alpha=0; alpha< 2; alpha++)\n        {\n            a[alpha].resize(mDim);\n            a[alpha] = ZeroVector(mDim);\n        }\n\n        for(unsigned int alpha=0; alpha < 2; alpha++)\n        {\n            noalias(a[alpha]) = A[alpha] + u_a[alpha];\n        }\n    }\n\n\n    void NonLinearBendingStrip::ReferenceCovariantBaseVector(std::vector<Vector>& A, const Matrix& DN_De\n                                                                            , const std::vector<Vector>& X)\n    {\n\n        // resize A\n        A.resize(2);\n        for(unsigned int alpha=0; alpha< 2; alpha++)\n        {\n            A[alpha].resize(mDim);\n            A[alpha] = ZeroVector(mDim);\n        }\n\n\n\n        for(unsigned alpha=0; alpha < 2; alpha++)\n        {\n            for(unsigned int i=0; i<mDim; i++)\n            {\n                for(unsigned int I=0; I<mNumberOfNodes; I++)\n                {\n                    // compute a1, a2\n                    A[alpha](i) += DN_De(I,alpha)*X[I](i) ;\n                }\n            }\n        }\n    }\n\n\n    void NonLinearBendingStrip::FirstDerivativeDisplacement_a(std::vector<Vector>& u_a, const Matrix& DN_De , const Matrix& u)\n    {\n        u_a.resize(2);\n\n        for(unsigned int i=0; i< 2; i++)\n        {\n            u_a[i].resize(mDim);\n            u_a[i] = ZeroVector(mDim);\n        }\n\n        for(unsigned alpha=0; alpha < 2; alpha++)\n        {\n            for(unsigned int i=0; i<mDim; i++)\n            {\n                for(unsigned int I=0; I<mNumberOfNodes; I++)\n                {\n                    // compute a1, a2\n                    u_a[alpha](i) += DN_De(I,alpha)*u(I,i) ;\n                }\n            }\n        }\n    }\n\n    void NonLinearBendingStrip::SecondDerivativeDisplacement_ab(std::vector<std::vector<Vector> >& u_ab\n        , const ShapeFunctionsSecondDerivativesType& D2N_De2 , const Matrix& u)\n    {\n        u_ab.resize(2);\n\n        for(unsigned int alpha=0; alpha< 2; alpha++)\n        {\n            u_ab[alpha].resize(2);\n\n            for(unsigned int beta=0; beta<2; beta++)\n            {\n\n                    u_ab[alpha][beta].resize(mDim);\n                    u_ab[alpha][beta] = ZeroVector(mDim);\n\n            }\n        }\n\n        for(unsigned alpha=0; alpha<2; alpha++)\n        {\n            for(unsigned beta=0; beta<2; beta++)\n            {\n                for(unsigned int i=0; i< mDim; ++i)\n                {\n                    for(unsigned int I=0; I< mNumberOfNodes; ++I)\n                    {\n                        // compute a_11\n                        u_ab[alpha][beta](i) += D2N_De2[I](alpha,beta)*u(I,i);\n                    }\n                }\n            }\n        }\n    }\n\n    void NonLinearBendingStrip::NormalDirector(Vector& a3Vector, Vector& aa3Vector, double& a3,  std::vector<Vector>& a)\n    {\n        aa3Vector = MathUtils<double>::CrossProduct(a[0], a[1]);\n        a3 = MathUtils<double>::Norm3(aa3Vector);\n        a3Vector = aa3Vector/a3;\n    }\n\n\n\n    void NonLinearBendingStrip::ContravariantBaseVector(std::vector<Vector>& AA, std::vector<Vector>& A, Matrix& Aab)\n    {\n        AA.resize(2);\n        for(unsigned alpha=0; alpha<2;alpha++)\n        {\n            AA[alpha].resize(3);\n            AA[alpha] = ZeroVector(3);\n        }\n\n\n        double temp_ab;\n        Matrix AAab(2,2);\n        MathUtils<double>::InvertMatrix(Aab, AAab, temp_ab);\n\n        noalias(AA[0]) = AAab(0,0)*A[0] +  AAab(0,1)*A[1] ;\n\n        noalias(AA[1]) = AAab(1,0)*A[0] + AAab(1,1)*A[1] ;\n    }\n\n    void NonLinearBendingStrip::DerivativeReferenceCovariantBaseVector(std::vector<std::vector<Vector> >& A_ab,\n        const ShapeFunctionsSecondDerivativesType& D2N_De2, const std::vector<Vector>& X)\n    {\n        A_ab.resize(2);\n\n        for(unsigned int alpha=0; alpha< 2; alpha++)\n        {\n            A_ab[alpha].resize(2);\n\n            for(unsigned int beta=0; beta<2; beta++)\n            {\n\n                    A_ab[alpha][beta].resize(mDim);\n                    A_ab[alpha][beta] = ZeroVector(mDim);\n\n            }\n        }\n\n        for(unsigned alpha=0; alpha<2; alpha++)\n        {\n            for(unsigned beta=0; beta<2; beta++)\n            {\n                for(unsigned int i=0; i< mDim; ++i)\n                {\n                    for(unsigned int I=0; I< mNumberOfNodes; ++I)\n                    {\n                        // compute a_11\n                        A_ab[alpha][beta](i) += D2N_De2[I](alpha,beta)*X[I](i) ;\n                    }\n                }\n            }\n        }\n\n    }\n\n    void NonLinearBendingStrip::DerivativeDeformedCovariantBaseVector(std::vector<std::vector<Vector> >& a_ab\n        , std::vector<std::vector<Vector> >& A_ab\n        , std::vector<std::vector<Vector> >& u_ab)\n    {\n        a_ab.resize(2);\n\n        for(unsigned int alpha=0; alpha< 2; alpha++)\n        {\n            a_ab[alpha].resize(2);\n\n            for(unsigned int beta=0; beta<2; beta++)\n            {\n                a_ab[alpha][beta].resize(mDim);\n                a_ab[alpha][beta] = ZeroVector(mDim);\n            }\n        }\n\n        for(unsigned alpha=0; alpha<2; alpha++)\n        {\n            for(unsigned beta=0; beta<2; beta++)\n            {\n                noalias(a_ab[alpha][beta]) = A_ab[alpha][beta] + u_ab[alpha][beta];\n            }\n        }\n\n    }\n\n    ///////////////////////////////////////////////////////////////////\n    ////////// shell fundamental properties ///////////////////////////\n    ///////////////////////////////////////////////////////////////////\n\n    void NonLinearBendingStrip::CovariantCurvatureCoefficient(Matrix& Bab\n        , std::vector<std::vector<Vector> >& A_ab, Vector& A3Vector)\n    {\n        Bab.resize(2,2);\n        Bab = ZeroMatrix(2,2);\n\n        for(unsigned int alpha=0; alpha<2; alpha++)\n        {\n            for(unsigned int beta=0; beta<2; beta++)\n            {\n                Bab(alpha,beta)= MathUtils<double>::Dot3(A_ab[alpha][beta], A3Vector);\n            }\n        }\n    }\n\n    void NonLinearBendingStrip::CovariantMetricCoefficient(Matrix& Aab, std::vector<Vector>& A)\n    {\n        Aab.resize(2,2);\n        Aab = ZeroMatrix(2,2);\n\n        for(unsigned int alpha=0; alpha<2; alpha++)\n        {\n            for(unsigned int beta=0; beta<2; beta++)\n            {\n                Aab(alpha,beta)= MathUtils<double>::Dot3(A[alpha], A[beta]);\n            }\n        }\n    }\n\n    // second derivative of base vector w.r.t u_r\n    void NonLinearBendingStrip::DerivativeCovariantBaseVector_abr( std::vector< std::vector<std::vector<std::vector<Vector>>> >& a_abr\n        ,const ShapeFunctionsSecondDerivativesType& D2N_De2, std::vector<Vector>& UnitBasisVector)\n    {\n        a_abr.resize(2);\n        for(unsigned int alpha = 0; alpha < 2; alpha++)\n        {\n            a_abr[alpha].resize(2);\n            for(unsigned int beta = 0; beta < 2; beta++)\n            {\n                a_abr[alpha][beta].resize(mNumberOfNodes);\n                for(unsigned int I = 0; I< mNumberOfNodes; I++)\n                {\n                    a_abr[alpha][beta][I].resize(mDim);\n                    for(unsigned int i=0; i< mDim; i++)\n                    {\n                        a_abr[alpha][beta][I][i].resize(mDim);\n                        a_abr[alpha][beta][I][i] = ZeroVector(mDim);\n                    }\n                }\n\n            }\n        }\n\n\n        for(unsigned int alpha = 0; alpha < 2; alpha++)\n        {\n            for(unsigned int beta = 0; beta < 2; beta++)\n            {\n                for(unsigned int I=0; I < mNumberOfNodes; I++)\n                {\n                    for(unsigned int i=0; i<mDim; i++)\n                    {\n                        a_abr[alpha][beta][I][i] = D2N_De2[I](alpha,beta)*UnitBasisVector[i];\n                    }\n                }\n            }\n        }\n\n\n    }\n\n    void NonLinearBendingStrip::DerivativeCovariantBaseVector_r(std::vector< std::vector<std::vector<Vector>> >& a_ar, const Matrix& DN_De, std::vector<Vector>& UnitBasisVector)\n    {\n        a_ar.resize(2);\n        for(unsigned int alpha = 0; alpha<2; alpha++)\n        {\n            a_ar[alpha].resize(mNumberOfNodes);\n            for(unsigned int I=0; I< mNumberOfNodes; I++)\n            {\n                a_ar[alpha][I].resize(mDim);\n\n                for(unsigned int i=0; i<mDim; i++)\n                {\n                    a_ar[alpha][I][i].resize(mDim);\n                    a_ar[alpha][I][i] = ZeroVector(mDim);\n                }\n            }\n\n        }\n\n\n        for(unsigned int alpha = 0; alpha<2; alpha++)\n        {\n            for(unsigned int I=0; I < mNumberOfNodes; I++)\n            {\n                for(unsigned int i=0; i<mDim; i++)\n                {\n                    a_ar[alpha][I][i] = DN_De(I,alpha)*UnitBasisVector[i];\n                }\n            }\n        }\n\n    }\n    ///////////////////////////////////////////////////////////////////////////\n    ///// first derivative of curvature changes and necessary components //////\n    ///////////////////////////////////////////////////////////////////////////\n    void NonLinearBendingStrip::DerivativeNonNormalizedDirector_r( std::vector<std::vector<Vector>>& aa3_rVector\n        , std::vector< std::vector<std::vector<Vector>> >& a_ar, std::vector<Vector>& a)\n    {\n        aa3_rVector.resize(mNumberOfNodes);\n        for(unsigned int I = 0; I< mNumberOfNodes; I++)\n        {\n            aa3_rVector[I].resize(mDim);\n            for(unsigned int i=0; i< mDim; i++)\n            {\n                aa3_rVector[I][i].resize(mDim);\n                aa3_rVector[I][i] = ZeroVector(mDim);\n            }\n        }\n\n\n        for(unsigned int I=0; I < mNumberOfNodes; I++)\n        {\n            for(unsigned int i=0; i<mDim; i++)\n            {\n                aa3_rVector[I][i] = MathUtils<double>::CrossProduct(a_ar[0][I][i] ,a[1]) + MathUtils<double>::CrossProduct(a[0], a_ar[1][I][i] );\n            }\n        }\n\n\n    }\n\n    void NonLinearBendingStrip::SecondDerivativeNonNormalizedDirector_rs(\n          std::vector<std::vector<std::vector<std::vector<Vector>>> >& aa3_rsVector\n        , std::vector< std::vector<std::vector<Vector>> >& a_ar)\n    {\n        aa3_rsVector.resize(mNumberOfNodes);\n        for(unsigned int I = 0; I< mNumberOfNodes; I++)\n        {\n            aa3_rsVector[I].resize(mNumberOfNodes);\n            for(unsigned int J = 0; J< mNumberOfNodes; J++)\n            {\n                aa3_rsVector[I][J].resize(mDim);\n                for(unsigned int i=0; i< mDim; i++)\n                {\n                    aa3_rsVector[I][J][i].resize(mDim);\n                    for(unsigned int j=0; j< mDim; j++)\n                    {\n                        aa3_rsVector[I][J][i][j].resize(mDim);\n                        aa3_rsVector[I][J][i][j] = ZeroVector(mDim);\n                    }\n                }\n            }\n        }\n\n\n        for(unsigned int I = 0; I< mNumberOfNodes; I++)\n        {\n            for(unsigned int J = 0; J< mNumberOfNodes; J++)\n            {\n                for(unsigned int i=0; i< mDim; i++)\n                {\n                    for(unsigned int j=0; j< mDim; j++)\n                    {\n                        aa3_rsVector[I][J][i][j] = MathUtils<double>::CrossProduct(a_ar[0][I][i], a_ar[1][J][j]) + MathUtils<double>::CrossProduct(a_ar[0][J][j], a_ar[1][I][i]);\n                    }\n                }\n            }\n        }\n\n\n    }\n\n    void NonLinearBendingStrip::DerivativeDirectorNorm_r(std::vector<std::vector<double>>& a3_r\n        , std::vector<std::vector<Vector>>& aa3_rVector, Vector& a3Vector)\n    {\n        a3_r.resize(mNumberOfNodes);\n        for(unsigned int I = 0; I< mNumberOfNodes; I++)\n        {\n            a3_r[I].resize(mDim);\n            for(unsigned int i=0; i< mDim; i++)\n            {\n                a3_r[I][i] = 0.0;\n            }\n        }\n\n\n        for(unsigned int I=0; I < mNumberOfNodes; I++)\n        {\n            for(unsigned int i=0; i<mDim; i++)\n            {\n                a3_r[I][i] = MathUtils<double>::Dot3(a3Vector ,aa3_rVector[I][i]) ;\n            }\n        }\n\n\n    }\n\n    void NonLinearBendingStrip::SecondDerivativeDirectorNorm_rs(\n          std::vector<std::vector<std::vector<std::vector<double>>> >& a3_rs\n        , std::vector<std::vector<std::vector<std::vector<Vector>>> >& aa3_rsVector\n        , Vector& aa3Vector, Vector& a3Vector, double& a3,  std::vector<std::vector<Vector>>& aa3_rVector)\n    {\n        a3_rs.resize(mNumberOfNodes);\n        for(unsigned int I = 0; I< mNumberOfNodes; I++)\n        {\n            a3_rs[I].resize(mNumberOfNodes);\n            for(unsigned int J = 0; J< mNumberOfNodes; J++)\n            {\n                a3_rs[I][J].resize(mDim);\n                for(unsigned int i=0; i< mDim; i++)\n                {\n                    a3_rs[I][J][i].resize(mDim);\n                    for(unsigned int j=0; j< mDim; j++)\n                    {\n                        a3_rs[I][J][i][j]= 0.0;\n                    }\n                }\n            }\n        }\n\n\n        for(unsigned int I = 0; I< mNumberOfNodes; I++)\n        {\n            for(unsigned int J = 0; J< mNumberOfNodes; J++)\n            {\n                for(unsigned int i=0; i< mDim; i++)\n                {\n                    for(unsigned int j=0; j< mDim; j++)\n                    {\n                        a3_rs[I][J][i][j] = ( MathUtils<double>::Dot3(aa3_rsVector[I][J][i][j], aa3Vector)\n                         + MathUtils<double>::Dot3(aa3_rVector[I][i], aa3_rVector[J][j])\n                         - MathUtils<double>::Dot3(aa3_rVector[I][i], a3Vector)*MathUtils<double>::Dot3(aa3_rVector[J][j], a3Vector) )/a3;\n                    }\n                }\n            }\n        }\n\n    }\n\n    void NonLinearBendingStrip::DerivativeDirector_r( std::vector<std::vector<Vector>>& a3_rVector\n        ,  std::vector<std::vector<Vector>>& aa3_rVector, std::vector<std::vector<double>>& a3_r, Vector& a3Vector, double& a3)\n    {\n        a3_rVector.resize(mNumberOfNodes);\n        for(unsigned int I = 0; I< mNumberOfNodes; I++)\n        {\n            a3_rVector[I].resize(mDim);\n            for(unsigned int i=0; i< mDim; i++)\n            {\n                a3_rVector[I][i].resize(mDim);\n                a3_rVector[I][i] = ZeroVector(mDim);\n            }\n        }\n\n\n        for(unsigned int I=0; I < mNumberOfNodes; I++)\n        {\n            for(unsigned int i=0; i<mDim; i++)\n            {\n                a3_rVector[I][i] = (aa3_rVector[I][i] - a3_r[I][i]*a3Vector)/a3;\n            }\n        }\n\n\n    }\n\n    void NonLinearBendingStrip::SecondDerivativeDirector_rs(\n          std::vector<std::vector<std::vector<std::vector<Vector>>> >& a3_rsVector\n        , std::vector<std::vector<std::vector<std::vector<Vector>>> >& aa3_rsVector\n        , std::vector<std::vector<std::vector<std::vector<double>>> >& a3_rs, Vector& a3Vector, double& a3\n        ,  std::vector<std::vector<Vector>>& aa3_rVector, std::vector<std::vector<double>>& a3_r)\n    {\n        a3_rsVector.resize(mNumberOfNodes);\n        for(unsigned int I = 0; I< mNumberOfNodes; I++)\n        {\n            a3_rsVector[I].resize(mNumberOfNodes);\n            for(unsigned int J = 0; J< mNumberOfNodes; J++)\n            {\n                a3_rsVector[I][J].resize(mDim);\n                for(unsigned int i=0; i< mDim; i++)\n                {\n                    a3_rsVector[I][J][i].resize(mDim);\n                    for(unsigned int j=0; j< mDim; j++)\n                    {\n                        a3_rsVector[I][J][i][j].resize(mDim);\n                        a3_rsVector[I][J][i][j]= ZeroVector(mDim);;\n                    }\n                }\n            }\n        }\n\n\n        for(unsigned int I = 0; I< mNumberOfNodes; I++)\n        {\n            for(unsigned int J = 0; J< mNumberOfNodes; J++)\n            {\n                for(unsigned int i=0; i< mDim; i++)\n                {\n                    for(unsigned int j=0; j< mDim; j++)\n                    {\n                        a3_rsVector[I][J][i][j] = (aa3_rsVector[I][J][i][j] - a3_rs[I][J][i][j]*a3Vector)/a3\n                            + (2.0*a3_r[I][i]*a3_r[J][j]*a3Vector - a3_r[I][i]*aa3_rVector[J][j] - a3_r[J][j]*aa3_rVector[I][i])*pow(a3,-2.0);\n                    }\n                }\n            }\n        }\n\n    }\n\n    void NonLinearBendingStrip::FirstDerivativeLocalCurvatureChange_r(std::vector<std::vector<Vector> >& kLocalVector_r\n        , std::vector< std::vector<std::vector<std::vector<Vector>>> >& a_abr\n        , std::vector<std::vector<Vector> >& a_ab\n        , Vector& a3Vector , std::vector<std::vector<Vector>>& a3_rVector\n        , std::vector< std::vector<std::vector<std::vector<double>>> >& TransformationCoeff)\n    {\n        kLocalVector_r.resize(2);\n        for(unsigned int alpha=0; alpha< 2; alpha++)\n        {\n            kLocalVector_r[alpha].resize(2);\n\n            for(unsigned int beta=0; beta<2; beta++)\n            {\n                kLocalVector_r[alpha][beta].resize(mNumberOfDof);\n                kLocalVector_r[alpha][beta] = ZeroVector(mNumberOfDof);\n            }\n        }\n\n        Vector temp(mNumberOfDof);\n        for(unsigned int gamma=0; gamma<2;gamma++)\n        {\n            for(unsigned int delta=0; delta<2; delta++)\n            {\n                temp = ZeroVector(mNumberOfDof);\n\n                for(unsigned int alpha=0; alpha<2;alpha++)\n                {\n                    for(unsigned int beta=0; beta<2; beta++)\n                    {\n                        for(unsigned int I=0; I< mNumberOfNodes; I++)\n                        {\n                            for(unsigned int i=0; i< mDim; i++)\n                            {\n                                temp(I*mDim + i) += ( MathUtils<double>::Dot3(a_abr[alpha][beta][I][i] ,a3Vector) + MathUtils<double>::Dot3(a_ab[alpha][beta], a3_rVector[I][i]) )\n                                *TransformationCoeff[gamma][delta][alpha][beta] ;\n                            }\n                        }\n                    }\n                }\n\n                noalias(kLocalVector_r[gamma][delta])= temp*(-1.0);\n            }\n        }\n\n        kLocalVector_r[0][1] *= 2.0;\n        kLocalVector_r[1][0] *= 2.0;\n    }\n\n    void NonLinearBendingStrip::SecondDerivativeLocalCurvatureChange_rs(std::vector<std::vector<Matrix> >& kLocalVector_rs\n        ,std::vector< std::vector<std::vector<std::vector<Vector>>> >& a_abr, std::vector<std::vector<Vector>>& a3_rVector\n        , std::vector<std::vector<Vector> >& a_ab, std::vector<std::vector<std::vector<std::vector<Vector>>> >& a3_rsVector\n        , std::vector< std::vector<std::vector<std::vector<double>>> >& TransformationCoeff)\n    {\n        if (kLocalVector_rs.size() != 2)\n            kLocalVector_rs.resize(2);\n\n        for(unsigned int i=0; i< 2; ++i)\n        {\n            if(kLocalVector_rs[i].size() !=2)\n                kLocalVector_rs[i].resize(2);\n\n            for(unsigned int j=0; j<2; ++j)\n            {\n                if (kLocalVector_rs[i][j].size1() != mNumberOfDof)\n                {\n                    kLocalVector_rs[i][j].resize(mNumberOfDof, mNumberOfDof);\n                    noalias(kLocalVector_rs[i][j]) = ZeroMatrix(mNumberOfDof, mNumberOfDof);\n                }\n            }\n        }\n\n\n        Matrix temp(mNumberOfDof, mNumberOfDof);\n\n        for(unsigned int gamma=0; gamma<2;++gamma)\n        {\n            for(unsigned int delta=0; delta<2; ++delta)\n            {\n                temp = ZeroMatrix(mNumberOfDof, mNumberOfDof);\n\n                for(unsigned int alpha=0; alpha<2;++alpha)\n                {\n                    for(unsigned int beta=0; beta<2; ++beta)\n                    {\n                        for(unsigned int I=0; I< mNumberOfNodes; ++I)\n                        {\n                            for(unsigned int J=0; J < mNumberOfNodes; ++J)\n                            {\n                                for(unsigned int i=0; i< mDim; ++i)\n                                {\n                                    for(unsigned int j=0; j< mDim; ++j)\n                                    {\n                                        temp(I*mDim+i, J*mDim+j) += ( MathUtils<double>::Dot3(a_abr[alpha][beta][I][i], a3_rVector[J][j])\n                                           + MathUtils<double>::Dot3(a_abr[alpha][beta][J][j], a3_rVector[I][i])\n                                           + MathUtils<double>::Dot3(a_ab[alpha][beta], a3_rsVector[I][J][i][j]) )\n                                           *TransformationCoeff[gamma][delta][alpha][beta] ;\n\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n\n                noalias(kLocalVector_rs[gamma][delta]) = temp*(-1.0);\n            }\n        }\n\n        kLocalVector_rs[0][1] *= 2.0;\n        kLocalVector_rs[1][0] *= 2.0;\n    }\n\n\n\n\n\n    //////////////////////////////////////////////////////////////\n    //////////// addtional utilities /////////////////////////////\n    //////////////////////////////////////////////////////////////\n    void NonLinearBendingStrip::CreatingBmatrix(Matrix& BMatrix, const std::vector<std::vector<Vector> >& LocalStrainVector_r)\n    {\n        if(BMatrix.size1() != mStrainSize)\n            BMatrix.resize(mStrainSize, mNumberOfDof);\n        noalias(BMatrix) = ZeroMatrix(mStrainSize, mNumberOfDof);\n\n        for (int i=0; i< mNumberOfDof; i++)\n        {\n            BMatrix(0,i) = LocalStrainVector_r[0][0](i);\n            BMatrix(1,i) = LocalStrainVector_r[1][1](i);\n            BMatrix(2,i) = LocalStrainVector_r[0][1](i);\n        }\n\n    }\n\n\n    void NonLinearBendingStrip::LocalTransformationOfTensor(Matrix& T, Matrix& M, std::vector< std::vector<std::vector<std::vector<double>>> >& TransformationCoeff)\n    {\n        if(T.size1()!=2)\n            T.resize(2, 2);\n\n        for(unsigned int gamma=0; gamma<2;++gamma)\n        {\n            for(unsigned int delta=0; delta<2; ++delta)\n            {\n                double temp=0.0;\n                for(unsigned int alpha=0; alpha<2;++alpha)\n                {\n                    for(unsigned int beta=0; beta<2; ++beta)\n                    {\n                        temp += M(alpha,beta)*TransformationCoeff[gamma][delta][alpha][beta] ;\n                    }\n                }\n                T(gamma,delta)= temp;\n            }\n        }\n    }\n\n    void NonLinearBendingStrip::UnitBaseVectors(std::vector<Vector>& e)\n    {\n            if (e.size() != 3)\n                e.resize(3);\n\n            e[0]=e[1]=e[2]=ZeroVector(mDim);\n            e[0](0)=e[1](1)=e[2](2)= 1.0;\n    }\n\n\n\n    void NonLinearBendingStrip::LocalCartesianBasisVector(std::vector<Vector>& EE, std::vector<Vector>& A, Vector& A3Vector)\n    {\n        EE.resize(3);\n        for(unsigned int i=0; i<3; ++i)\n        {\n            EE[i].resize(3);\n        }\n\n        EE[0] = A[0]/MathUtils<double>::Norm3(A[0]);\n\n        Vector EE2_temp = ZeroVector(3);\n        noalias(EE2_temp) +=  A[1];\n        noalias(EE2_temp) -=  MathUtils<double>::Dot3(A[1], EE[0])*EE[0];\n        noalias(EE[1]) = ( EE2_temp )/MathUtils<double>::Norm3(EE2_temp);\n\n        EE[2] = A3Vector;\n\n\n    }\n\n\n\n    void NonLinearBendingStrip::LocalTransformationCoefficient(std::vector< std::vector<std::vector<std::vector<double>>> >& TransformationCoeff, std::vector<Vector>& EE, std::vector<Vector>& AA)\n    {\n        TransformationCoeff.resize(2);\n        for(unsigned int gamma=0; gamma <2; gamma++)\n        {\n            TransformationCoeff[gamma].resize(2);\n            for(unsigned int delta = 0; delta<2; delta++)\n            {\n                TransformationCoeff[gamma][delta].resize(2);\n                for(unsigned int alpha=0; alpha< 2; alpha++)\n                {\n                    TransformationCoeff[gamma][delta][alpha].resize(2);\n\n                    for(unsigned int beta=0; beta<2; beta++)\n                    {\n                        TransformationCoeff[gamma][delta][alpha][beta] = 0.0;\n                    }\n                }\n\n            }\n        }\n\n\n        for(unsigned int gamma=0; gamma <2; gamma++)\n        {\n            for(unsigned int delta = 0; delta<2; delta++)\n            {\n                for(unsigned int alpha=0; alpha< 2; alpha++)\n                {\n                    for(unsigned int beta=0; beta<2; beta++)\n                    {\n                        TransformationCoeff[gamma][delta][alpha][beta] = MathUtils<double>::Dot3(EE[gamma],AA[alpha])*MathUtils<double>::Dot3(AA[beta],EE[delta]);\n                    }\n                }\n\n            }\n        }\n\n    }\n\n    ///////////// material matrix\n    void NonLinearBendingStrip::CalculateConstitutiveMatrix(Matrix& D)\n    {\n        if (D.size1() != 3)\n            D.resize(3,3);\n        D = ZeroMatrix(3,3);\n\n        D(1,1) = pow(10.0 ,4.0)*mE;\n    }\n\n\n\n} // Namespace Kratos.\n", "meta": {"hexsha": "a32ebac9b2a276e387478019be5505d3a04fd519", "size": 46442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "custom_elements/nonlinear_bending_strip.cpp", "max_stars_repo_name": "rwilliams01/isogeometric_structural_application", "max_stars_repo_head_hexsha": "5f0468c35ae0b1f8e16861b3568d755222b8a967", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "custom_elements/nonlinear_bending_strip.cpp", "max_issues_repo_name": "rwilliams01/isogeometric_structural_application", "max_issues_repo_head_hexsha": "5f0468c35ae0b1f8e16861b3568d755222b8a967", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "custom_elements/nonlinear_bending_strip.cpp", "max_forks_repo_name": "rwilliams01/isogeometric_structural_application", "max_forks_repo_head_hexsha": "5f0468c35ae0b1f8e16861b3568d755222b8a967", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.453689168, "max_line_length": 195, "alphanum_fraction": 0.517591835, "num_tokens": 10998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.4037454387005374}}
{"text": "//\n//  synthetic_data_helper.cpp\n//  synthetic_data_helper\n//\n//  Created by Cristián Garay on 10/15/16.\n//  Revised and edited by Anirudhan Badrinath on 27/02/20.\n//\n\n#define NPY_NO_DEPRECATED_API NPY_1_11_API_VERSION\n\n#include <iostream>\n#include <stdint.h>\n#include <alloca.h>\n#include <Eigen/Core>\n#include <Python.h>\n#include <numpy/ndarrayobject.h>\n\nusing namespace Eigen;\nusing namespace std;\n\nstatic double extract_double(PyArrayObject *arr, int i) {\n    return ((double*) PyArray_DATA(arr))[i];\n}\n\nstatic double extract_double_2d(PyArrayObject *arr, int i, int j) {\n    return ((double*) PyArray_DATA(arr))[i * PyArray_DIM(arr, 1) + j];\n}\n\nstatic double extract_int64_t(PyArrayObject *arr, int i) {\n    return ((int64_t*) PyArray_DATA(arr))[i];\n}\n\nvoid capsule_cleanup(PyObject *capsule) {\n    void *memory = PyCapsule_GetPointer(capsule, NULL);\n    delete memory;\n}\n\n\nstatic PyObject* run(PyObject * module, PyObject * args) {\n    //TODO: check if parameters are null.\n    //TODO: check that dicts have the required members.\n    //TODO: check that all parameters have the right sizes.\n    //TODO: i'm not sending any error messages.\n    import_array();\n\n    PyObject *model_ptr = NULL, *starts_obj = NULL, *lengths_obj = NULL, *resources_obj = NULL;\n    PyArrayObject *resources = NULL, *starts = NULL, *lengths = NULL, *learns = NULL, *forgets = NULL, *guesses = NULL, *slips = NULL;\n    double prior;\n\n    if (!PyArg_ParseTuple(args, \"OOOO\", &model_ptr, &starts_obj, &lengths_obj, &resources_obj)) {\n        PyErr_SetString(PyExc_ValueError, \"Error parsing arguments.\");\n        return NULL;\n    }\n\n    int DTYPE = PyArray_ObjectType(starts_obj, NPY_INT64);\n    starts = (PyArrayObject *)PyArray_FROM_OTF(starts_obj, DTYPE, NPY_ARRAY_IN_ARRAY);\n    DTYPE = PyArray_ObjectType(lengths_obj, NPY_INT64);\n    lengths = (PyArrayObject *)PyArray_FROM_OTF(lengths_obj, DTYPE, NPY_ARRAY_IN_ARRAY);\n    DTYPE = PyArray_ObjectType(resources_obj, NPY_INT64);\n    resources = (PyArrayObject *)PyArray_FROM_OTF(resources_obj, DTYPE, NPY_ARRAY_IN_ARRAY);\n\n    char* DM_NAMES[] = {\"learns\", \"forgets\", \"guesses\", \"slips\"};\n    PyArrayObject** DM_PTRS[] = {&learns, &forgets, &guesses, &slips};\n    for (int i = 0; i < 4; i++) {\n        PyObject *dp = PyDict_GetItemString(model_ptr, DM_NAMES[i]);\n        DTYPE = PyArray_ObjectType(dp, NPY_FLOAT); // hack to force correct type\n        *DM_PTRS[i] = (PyArrayObject *)PyArray_FROM_OTF(dp, DTYPE, NPY_ARRAY_IN_ARRAY);\n    }\n    prior = PyFloat_AsDouble(PyDict_GetItemString(model_ptr, \"prior\"));\n\n    int num_subparts = (int) PyArray_DIM(slips, 0);\n    int num_sequences = (int) PyArray_DIM(starts, 0);\n    int num_resources = (int) PyArray_DIM(learns, 0);\n    \n    Vector2d initial_distn;\n    initial_distn << 1-prior, prior;\n    \n    MatrixXd As(2, 2*num_resources);\n    for (int n=0; n<num_resources; n++) {\n        double learn = extract_double(learns,n);\n        double forget = extract_double(forgets,n);\n        As.col(2*n) << 1-learn, learn;\n        As.col(2*n+1) << forget, 1-forget;\n    }\n    \n    int64_t bigT = 0;\n    for (int k=0; k<num_sequences; k++) {\n        bigT += extract_int64_t(lengths,k); //extract this as int??\n    }\n    \n    //// outputs\n    int* all_stateseqs = new int[bigT];\n    int* all_data = new int[num_subparts * bigT]; //used to be int8_t\n    *all_data = 0;\n    \n    /* COMPUTATION */\n    \n    for (int sequence_index=0; sequence_index < num_sequences; sequence_index++) {\n        int64_t sequence_start = extract_int64_t(starts,sequence_index) - 1; //should i extract these as ints?\n        int64_t T = extract_int64_t(lengths, sequence_index);\n        \n        Vector2d nextstate_distr = initial_distn;\n\n        for (int t=0; t<T; t++) {\n            *(all_stateseqs + sequence_start + t) = nextstate_distr(0) < ((double) rand()) / ((double) RAND_MAX); //always all_stateseqs[0]?\n            for (int n=0; n<num_subparts; n++) {\n                *(all_data + n * (bigT) + sequence_start + t) = ((*(all_stateseqs + sequence_start + t)) ? extract_double(slips, n) : (1-extract_double(guesses, n))) < (((double) rand()) / ((double) RAND_MAX));\n            }\n            \n            nextstate_distr = As.col(2*(extract_int64_t(resources, sequence_start + t)-1)+*(all_stateseqs + sequence_start + t)); //extract int is right??\n        }\n    }\n    \n    PyObject *result = PyDict_New();\n\n    npy_intp dims1[] = {1, bigT};\n    PyObject *all_stateseqs_arr = (PyObject *) PyArray_SimpleNewFromData(2, dims1, NPY_INT, all_stateseqs);\n    PyObject *capsule1 = PyCapsule_New(all_stateseqs, NULL, capsule_cleanup);\n    PyArray_SetBaseObject((PyArrayObject *) all_stateseqs_arr, capsule1);\n\n    npy_intp dims2[] = {num_subparts, bigT};\n    PyObject *all_data_arr = (PyObject *) PyArray_SimpleNewFromData(2, dims2, NPY_INT, all_data);\n    PyObject *capsule2 = PyCapsule_New(all_data, NULL, capsule_cleanup);\n    PyArray_SetBaseObject((PyArrayObject *) all_data_arr, capsule2);\n\n    PyDict_SetItemString(result, \"stateseqs\", all_stateseqs_arr);\n    PyDict_SetItemString(result, \"data\", all_data_arr);\n\n    Py_XDECREF(resources);\n    Py_XDECREF(starts);\n    Py_XDECREF(lengths);\n    Py_XDECREF(all_stateseqs_arr);\n    Py_XDECREF(all_data_arr);\n\n    for (int i = 0; i < 4; i++)\n        Py_XDECREF(*DM_PTRS[i]);\n\n    return(result);\n}\n\nstatic PyMethodDef synthetic_data_helper_Methods[] = {\n    {\"create_synthetic_data\",  run, METH_VARARGS,\n     \"Helper for creating synthetic data from true model\"},\n    {NULL, NULL, 0, NULL}        /* Sentinel */\n};\n\n\nstatic struct PyModuleDef synthetic_data_helper_module = {\n   PyModuleDef_HEAD_INIT,\n   \"synthetic_data_helper\",   /* name of module */\n   NULL, /* module documentation, may be NULL */\n   -1,       /* size of per-interpreter state of the module,\n                or -1 if the module keeps state in global variables. */\n   synthetic_data_helper_Methods\n};\n\nPyMODINIT_FUNC PyInit_synthetic_data_helper() {\n    return PyModule_Create(&synthetic_data_helper_module);\n}\n\n", "meta": {"hexsha": "290ce4fdc39a697365e9de78cae078ded776d7fc", "size": 5980, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-cpp/pyBKT/generate/synthetic_data_helper.cpp", "max_stars_repo_name": "bukeplato/pyBKT", "max_stars_repo_head_hexsha": "733a4ccf0de78bef7d47b5a6af7131c7778560db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 132.0, "max_stars_repo_stars_event_min_datetime": "2018-03-22T06:04:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T21:54:27.000Z", "max_issues_repo_path": "source-cpp/pyBKT/generate/synthetic_data_helper.cpp", "max_issues_repo_name": "bukeplato/pyBKT", "max_issues_repo_head_hexsha": "733a4ccf0de78bef7d47b5a6af7131c7778560db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2018-01-10T14:00:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T04:00:47.000Z", "max_forks_repo_path": "source-cpp/pyBKT/generate/synthetic_data_helper.cpp", "max_forks_repo_name": "bukeplato/pyBKT", "max_forks_repo_head_hexsha": "733a4ccf0de78bef7d47b5a6af7131c7778560db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 46.0, "max_forks_repo_forks_event_min_datetime": "2017-09-12T04:30:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T08:54:52.000Z", "avg_line_length": 37.1428571429, "max_line_length": 210, "alphanum_fraction": 0.672909699, "num_tokens": 1676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872131147275, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4037454387005374}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2018 John Maddock\n//  Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_HYPERGEOMETRIC_PFQ_SERIES_HPP_\n#define BOOST_HYPERGEOMETRIC_PFQ_SERIES_HPP_\n\n#ifndef BOOST_MATH_PFQ_MAX_B_TERMS\n#  define BOOST_MATH_PFQ_MAX_B_TERMS 5\n#endif\n\n#include <boost/array.hpp>\n#include <boost/math/special_functions/detail/hypergeometric_series.hpp>\n\n  namespace boost { namespace math { namespace detail {\n\n     template <class Seq, class Real>\n     unsigned set_crossover_locations(const Seq& aj, const Seq& bj, const Real& z, unsigned int* crossover_locations)\n     {\n        BOOST_MATH_STD_USING\n        unsigned N_terms = 0;\n\n        if(aj.size() == 1 && bj.size() == 1)\n        {\n           //\n           // For 1F1 we can work out where the peaks in the series occur,\n           //  which is to say when:\n           //\n           // (a + k)z / (k(b + k)) == +-1\n           //\n           // Then we are at either a maxima or a minima in the series, and the\n           // last such point must be a maxima since the series is globally convergent.\n           // Potentially then we are solving 2 quadratic equations and have up to 4\n           // solutions, any solutions which are complex or negative are discarded,\n           // leaving us with 4 options:\n           //\n           // 0 solutions: The series is directly convergent.\n           // 1 solution : The series diverges to a maxima before converging.\n           // 2 solutions: The series is initially convergent, followed by divergence to a maxima before final convergence.\n           // 3 solutions: The series diverges to a maxima, converges to a minima before diverging again to a second maxima before final convergence.\n           // 4 solutions: The series converges to a minima before diverging to a maxima, converging to a minima, diverging to a second maxima and then converging.\n           //\n           // The first 2 situations are adequately handled by direct series evaluation, while the 2,3 and 4 solutions are not.\n           //\n           Real a = *aj.begin();\n           Real b = *bj.begin();\n           Real sq = 4 * a * z + b * b - 2 * b * z + z * z;\n           if (sq >= 0)\n           {\n              Real t = (-sqrt(sq) - b + z) / 2;\n              if (t >= 0)\n              {\n                 crossover_locations[N_terms] = itrunc(t);\n                 ++N_terms;\n              }\n              t = (sqrt(sq) - b + z) / 2;\n              if (t >= 0)\n              {\n                 crossover_locations[N_terms] = itrunc(t);\n                 ++N_terms;\n              }\n           }\n           sq = -4 * a * z + b * b + 2 * b * z + z * z;\n           if (sq >= 0)\n           {\n              Real t = (-sqrt(sq) - b - z) / 2;\n              if (t >= 0)\n              {\n                 crossover_locations[N_terms] = itrunc(t);\n                 ++N_terms;\n              }\n              t = (sqrt(sq) - b - z) / 2;\n              if (t >= 0)\n              {\n                 crossover_locations[N_terms] = itrunc(t);\n                 ++N_terms;\n              }\n           }\n           std::sort(crossover_locations, crossover_locations + N_terms, std::less<Real>());\n           //\n           // Now we need to discard every other terms, as these are the minima:\n           //\n           switch (N_terms)\n           {\n           case 0:\n           case 1:\n              break;\n           case 2:\n              crossover_locations[0] = crossover_locations[1];\n              --N_terms;\n              break;\n           case 3:\n              crossover_locations[1] = crossover_locations[2];\n              --N_terms;\n              break;\n           case 4:\n              crossover_locations[0] = crossover_locations[1];\n              crossover_locations[1] = crossover_locations[3];\n              N_terms -= 2;\n              break;\n           }\n        }\n        else\n        {\n           unsigned n = 0;\n           for (auto bi = bj.begin(); bi != bj.end(); ++bi, ++n)\n           {\n              crossover_locations[n] = *bi >= 0 ? 0 : itrunc(-*bi) + 1;\n           }\n           std::sort(crossover_locations, crossover_locations + bj.size(), std::less<Real>());\n           N_terms = (unsigned)bj.size();\n        }\n        return N_terms;\n     }\n\n     template <class Seq, class Real, class Policy, class Terminal>\n     std::pair<Real, Real> hypergeometric_pFq_checked_series_impl(const Seq& aj, const Seq& bj, const Real& z, const Policy& pol, const Terminal& termination, int& log_scale)\n     {\n        BOOST_MATH_STD_USING\n        Real result = 1;\n        Real abs_result = 1;\n        Real term = 1;\n        Real term0 = 0;\n        Real tol = boost::math::policies::get_epsilon<Real, Policy>();\n        boost::uintmax_t k = 0;\n        Real upper_limit(sqrt(boost::math::tools::max_value<Real>())), diff;\n        Real lower_limit(1 / upper_limit);\n        int log_scaling_factor = itrunc(boost::math::tools::log_max_value<Real>()) - 2;\n        Real scaling_factor = exp(Real(log_scaling_factor));\n        Real term_m1;\n        int local_scaling = 0;\n\n        if ((aj.size() == 1) && (bj.size() == 0))\n        {\n           if (fabs(z) > 1)\n           {\n              if ((z > 0) && (floor(*aj.begin()) != *aj.begin()))\n              {\n                 Real r = policies::raise_domain_error(\"boost::math::hypergeometric_pFq\", \"Got p == 1 and q == 0 and |z| > 1, result is imaginary\", z, pol);\n                 return std::make_pair(r, r);\n              }\n              std::pair<Real, Real> r = hypergeometric_pFq_checked_series_impl(aj, bj, Real(1 / z), pol, termination, log_scale);\n              Real mul = pow(-z, -*aj.begin());\n              r.first *= mul;\n              r.second *= mul;\n              return r;\n           }\n        }\n\n        if (aj.size() > bj.size())\n        {\n           if (aj.size() == bj.size() + 1)\n           {\n              if (fabs(z) > 1)\n              {\n                 Real r = policies::raise_domain_error(\"boost::math::hypergeometric_pFq\", \"Got p == q+1 and |z| > 1, series does not converge\", z, pol);\n                 return std::make_pair(r, r);\n              }\n              if (fabs(z) == 1)\n              {\n                 Real s = 0;\n                 for (auto i = bj.begin(); i != bj.end(); ++i)\n                    s += *i;\n                 for (auto i = aj.begin(); i != aj.end(); ++i)\n                    s -= *i;\n                 if ((z == 1) && (s <= 0))\n                 {\n                    Real r = policies::raise_domain_error(\"boost::math::hypergeometric_pFq\", \"Got p == q+1 and |z| == 1, in a situation where the series does not converge\", z, pol);\n                    return std::make_pair(r, r);\n                 }\n                 if ((z == -1) && (s <= -1))\n                 {\n                    Real r = policies::raise_domain_error(\"boost::math::hypergeometric_pFq\", \"Got p == q+1 and |z| == 1, in a situation where the series does not converge\", z, pol);\n                    return std::make_pair(r, r);\n                 }\n              }\n           }\n           else\n           {\n              Real r = policies::raise_domain_error(\"boost::math::hypergeometric_pFq\", \"Got p > q+1, series does not converge\", z, pol);\n              return std::make_pair(r, r);\n           }\n        }\n\n        while (!termination(k))\n        {\n           for (auto ai = aj.begin(); ai != aj.end(); ++ai)\n           {\n              term *= *ai + k;\n           }\n           if (term == 0)\n           {\n              // There is a negative integer in the aj's:\n              return std::make_pair(result, abs_result);\n           }\n           for (auto bi = bj.begin(); bi != bj.end(); ++bi)\n           {\n              if (*bi + k == 0)\n              {\n                 // The series is undefined:\n                 result = boost::math::policies::raise_domain_error(\"boost::math::hypergeometric_pFq<%1%>\", \"One of the b values was the negative integer %1%\", *bi, pol);\n                 return std::make_pair(result, result);\n              }\n              term /= *bi + k;\n           }\n           term *= z;\n           ++k;\n           term /= k;\n           //std::cout << k << \" \" << *bj.begin() + k << \" \" << result << \" \" << term << /*\" \" << term_at_k(*aj.begin(), *bj.begin(), z, k, pol) <<*/ std::endl;\n           result += term;\n           abs_result += abs(term);\n           //std::cout << \"k = \" << k << \" term = \" << term * exp(log_scale) << \" result = \" << result * exp(log_scale) << \" abs_result = \" << abs_result * exp(log_scale) << std::endl;\n\n           //\n           // Rescaling:\n           //\n           if (fabs(abs_result) >= upper_limit)\n           {\n              abs_result /= scaling_factor;\n              result /= scaling_factor;\n              term /= scaling_factor;\n              log_scale += log_scaling_factor;\n              local_scaling += log_scaling_factor;\n           }\n           if (fabs(abs_result) < lower_limit)\n           {\n              abs_result *= scaling_factor;\n              result *= scaling_factor;\n              term *= scaling_factor;\n              log_scale -= log_scaling_factor;\n              local_scaling -= log_scaling_factor;\n           }\n\n           if ((abs(result * tol) > abs(term)) && (abs(term0) > abs(term)))\n              break;\n           if (abs_result * tol > abs(result))\n           {\n              // We have no correct bits in the result... just give up!\n              result = boost::math::policies::raise_evaluation_error(\"boost::math::hypergeometric_pFq<%1%>\", \"Cancellation is so severe that no bits in the reuslt are correct, last result was %1%\", Real(result * exp(Real(log_scale))), pol);\n              return std::make_pair(result, result);\n           }\n           term0 = term;\n        }\n        //std::cout << \"result = \" << result << std::endl;\n        //std::cout << \"local_scaling = \" << local_scaling << std::endl;\n        //std::cout << \"Norm result = \" << std::setprecision(35) << boost::multiprecision::mpfr_float_50(result) * exp(boost::multiprecision::mpfr_float_50(local_scaling)) << std::endl;\n        //\n        // We have to be careful when one of the b's crosses the origin:\n        //\n        if(bj.size() > BOOST_MATH_PFQ_MAX_B_TERMS)\n           policies::raise_domain_error<Real>(\"boost::math::hypergeometric_pFq<%1%>(Seq, Seq, %1%)\", \n              \"The number of b terms must be less than the value of BOOST_MATH_PFQ_MAX_B_TERMS (\" BOOST_STRINGIZE(BOOST_MATH_PFQ_MAX_B_TERMS)  \"), but got %1%.\",\n              Real(bj.size()), pol);\n\n        unsigned crossover_locations[BOOST_MATH_PFQ_MAX_B_TERMS];\n\n        unsigned N_crossovers = set_crossover_locations(aj, bj, z, crossover_locations);\n\n        bool terminate = false;   // Set to true if one of the a's passes through the origin and terminates the series.\n\n        for (unsigned n = 0; n < N_crossovers; ++n)\n        {\n           if (k < crossover_locations[n])\n           {\n              for (auto ai = aj.begin(); ai != aj.end(); ++ai)\n              {\n                 if ((*ai < 0) && (floor(*ai) == *ai) && (*ai > crossover_locations[n]))\n                    return std::make_pair(result, abs_result);  // b's will never cross the origin!\n              }\n              //\n              // local results:\n              //\n              Real loop_result = 0;\n              Real loop_abs_result = 0;\n              int loop_scale = 0;\n              //\n              // loop_error_scale will be used to increase the size of the error\n              // estimate (absolute sum), based on the errors inherent in calculating \n              // the pochhammer symbols.\n              //\n              Real loop_error_scale = 0;\n              //boost::multiprecision::mpfi_float err_est = 0;\n              //\n              // b hasn't crossed the origin yet and the series may spring back into life at that point\n              // so we need to jump forward to that term and then evaluate forwards and backwards from there:\n              //\n              unsigned s = crossover_locations[n];\n              boost::uintmax_t backstop = k;\n              int s1(1), s2(1);\n              term = 0;\n              for (auto ai = aj.begin(); ai != aj.end(); ++ai)\n              {\n                 if ((floor(*ai) == *ai) && (*ai < 0) && (-*ai <= s))\n                 {\n                    // One of the a terms has passed through zero and terminated the series:\n                    terminate = true;\n                    break;\n                 }\n                 else\n                 {\n                    int ls = 1;\n                    Real p = log_pochhammer(*ai, s, pol, &ls);\n                    s1 *= ls;\n                    term += p;\n                    loop_error_scale = (std::max)(p, loop_error_scale);\n                    //err_est += boost::multiprecision::mpfi_float(p);\n                 }\n              }\n              //std::cout << \"term = \" << term << std::endl;\n              if (terminate)\n                 break;\n              for (auto bi = bj.begin(); bi != bj.end(); ++bi)\n              {\n                 int ls = 1;\n                 Real p = log_pochhammer(*bi, s, pol, &ls);\n                 s2 *= ls;\n                 term -= p;\n                 loop_error_scale = (std::max)(p, loop_error_scale);\n                 //err_est -= boost::multiprecision::mpfi_float(p);\n              }\n              //std::cout << \"term = \" << term << std::endl;\n              Real p = lgamma(Real(s + 1), pol);\n              term -= p;\n              loop_error_scale = (std::max)(p, loop_error_scale);\n              //err_est -= boost::multiprecision::mpfi_float(p);\n              p = s * log(fabs(z));\n              term += p;\n              loop_error_scale = (std::max)(p, loop_error_scale);\n              //err_est += boost::multiprecision::mpfi_float(p);\n              //err_est = exp(err_est);\n              //std::cout << err_est << std::endl;\n              //\n              // Convert loop_error scale to the absolute error\n              // in term after exp is applied:\n              //\n              loop_error_scale *= tools::epsilon<Real>();\n              //\n              // Convert to relative error after exp:\n              //\n              loop_error_scale = fabs(expm1(loop_error_scale, pol));\n              //\n              // Convert to multiplier for the error term:\n              //\n              loop_error_scale /= tools::epsilon<Real>();\n\n              if (z < 0)\n                 s1 *= (s & 1 ? -1 : 1);\n\n              if (term <= tools::log_min_value<Real>())\n              {\n                 // rescale if we can:\n                 int scale = itrunc(floor(term - tools::log_min_value<Real>()) - 2);\n                 term -= scale;\n                 loop_scale += scale;\n              }\n               if (term > 10)\n               {\n                  int scale = itrunc(floor(term));\n                  term -= scale;\n                  loop_scale += scale;\n               }\n               //std::cout << \"term = \" << term << std::endl;\n               term = s1 * s2 * exp(term);\n               //std::cout << \"term = \" << term << std::endl;\n               //std::cout << \"loop_scale = \" << loop_scale << std::endl;\n               k = s;\n               term0 = term;\n               int saved_loop_scale = loop_scale;\n               bool terms_are_growing = true;\n               bool trivial_small_series_check = false;\n               do\n               {\n                  loop_result += term;\n                  loop_abs_result += fabs(term);\n                  //std::cout << \"k = \" << k << \" term = \" << term * exp(loop_scale) << \" result = \" << loop_result * exp(loop_scale) << \" abs_result = \" << loop_abs_result * exp(loop_scale) << std::endl;\n                  if (fabs(loop_result) >= upper_limit)\n                  {\n                     loop_result /= scaling_factor;\n                     loop_abs_result /= scaling_factor;\n                     term /= scaling_factor;\n                     loop_scale += log_scaling_factor;\n                  }\n                  if (fabs(loop_result) < lower_limit)\n                  {\n                     loop_result *= scaling_factor;\n                     loop_abs_result *= scaling_factor;\n                     term *= scaling_factor;\n                     loop_scale -= log_scaling_factor;\n                  }\n                  term_m1 = term;\n                  for (auto ai = aj.begin(); ai != aj.end(); ++ai)\n                  {\n                     term *= *ai + k;\n                  }\n                  if (term == 0)\n                  {\n                     // There is a negative integer in the aj's:\n                     return std::make_pair(result, abs_result);\n                  }\n                  for (auto bi = bj.begin(); bi != bj.end(); ++bi)\n                  {\n                     if (*bi + k == 0)\n                     {\n                        // The series is undefined:\n                        result = boost::math::policies::raise_domain_error(\"boost::math::hypergeometric_pFq<%1%>\", \"One of the b values was the negative integer %1%\", *bi, pol);\n                        return std::make_pair(result, result);\n                     }\n                     term /= *bi + k;\n                  }\n                  term *= z / (k + 1);\n\n                  ++k;\n                  diff = fabs(term / loop_result);\n                  terms_are_growing = fabs(term) > fabs(term_m1);\n                  if (!trivial_small_series_check && !terms_are_growing)\n                  {\n                     //\n                     // Now that we have started to converge, check to see if the value of\n                     // this local sum is trivially small compared to the result.  If so\n                     // abort this part of the series.\n                     //\n                     trivial_small_series_check = true;\n                     Real d; \n                     if (loop_scale > local_scaling)\n                     {\n                        int rescale = local_scaling - loop_scale;\n                        if (rescale < tools::log_min_value<Real>())\n                           d = 1;  // arbitrary value, we want to keep going\n                        else\n                           d = fabs(term / (result * exp(Real(rescale))));\n                     }\n                     else\n                     {\n                        int rescale = loop_scale - local_scaling;\n                        if (rescale < tools::log_min_value<Real>())\n                           d = 0;  // terminate this loop\n                        else\n                           d = fabs(term * exp(Real(rescale)) / result);\n                     }\n                     if (d < boost::math::policies::get_epsilon<Real, Policy>())\n                        break;\n                  }\n               } while (!termination(k - s) && ((diff > boost::math::policies::get_epsilon<Real, Policy>()) || terms_are_growing));\n\n               //std::cout << \"Norm loop result = \" << std::setprecision(35) << boost::multiprecision::mpfr_float_50(loop_result)* exp(boost::multiprecision::mpfr_float_50(loop_scale)) << std::endl;\n               //\n               // We now need to combine the results of the first series summation with whatever\n               // local results we have now.  First though, rescale abs_result by loop_error_scale\n               // to factor in the error in the pochhammer terms at the start of this block:\n               //\n               boost::uintmax_t next_backstop = k;\n               loop_abs_result += loop_error_scale * fabs(loop_result);\n               if (loop_scale > local_scaling)\n               {\n                  //\n                  // Need to shrink previous result:\n                  //\n                  int rescale = local_scaling - loop_scale;\n                  local_scaling = loop_scale;\n                  log_scale -= rescale;\n                  Real ex = exp(Real(rescale));\n                  result *= ex;\n                  abs_result *= ex;\n                  result += loop_result;\n                  abs_result += loop_abs_result;\n               }\n               else if (local_scaling > loop_scale)\n               {\n                  //\n                  // Need to shrink local result:\n                  //\n                  int rescale = loop_scale - local_scaling;\n                  Real ex = exp(Real(rescale));\n                  loop_result *= ex;\n                  loop_abs_result *= ex;\n                  result += loop_result;\n                  abs_result += loop_abs_result;\n               }\n               else\n               {\n                  result += loop_result;\n                  abs_result += loop_abs_result;\n               }\n               //\n               // Now go backwards as well:\n               //\n               k = s;\n               term = term0;\n               loop_result = 0;\n               loop_abs_result = 0;\n               loop_scale = saved_loop_scale;\n               trivial_small_series_check = false;\n               do\n               {\n                  --k;\n                  if (k == backstop)\n                     break;\n                  term_m1 = term;\n                  for (auto ai = aj.begin(); ai != aj.end(); ++ai)\n                  {\n                     term /= *ai + k;\n                  }\n                  for (auto bi = bj.begin(); bi != bj.end(); ++bi)\n                  {\n                     if (*bi + k == 0)\n                     {\n                        // The series is undefined:\n                        result = boost::math::policies::raise_domain_error(\"boost::math::hypergeometric_pFq<%1%>\", \"One of the b values was the negative integer %1%\", *bi, pol);\n                        return std::make_pair(result, result);\n                     }\n                     term *= *bi + k;\n                  }\n                  term *= (k + 1) / z;\n                  loop_result += term;\n                  loop_abs_result += fabs(term);\n\n                  if (!trivial_small_series_check && (fabs(term) < fabs(term_m1)))\n                  {\n                     //\n                     // Now that we have started to converge, check to see if the value of\n                     // this local sum is trivially small compared to the result.  If so\n                     // abort this part of the series.\n                     //\n                     trivial_small_series_check = true;\n                     Real d;\n                     if (loop_scale > local_scaling)\n                     {\n                        int rescale = local_scaling - loop_scale;\n                        if (rescale < tools::log_min_value<Real>())\n                           d = 1;  // keep going\n                        else\n                           d = fabs(term / (result * exp(Real(rescale))));\n                     }\n                     else\n                     {\n                        int rescale = loop_scale - local_scaling;\n                        if (rescale < tools::log_min_value<Real>())\n                           d = 0;  // stop, underflow\n                        else\n                           d = fabs(term * exp(Real(rescale)) / result);\n                     }\n                     if (d < boost::math::policies::get_epsilon<Real, Policy>())\n                        break;\n                  }\n\n                  //std::cout << \"k = \" << k << \" result = \" << result << \" abs_result = \" << abs_result << std::endl;\n                  if (fabs(loop_result) >= upper_limit)\n                  {\n                     loop_result /= scaling_factor;\n                     loop_abs_result /= scaling_factor;\n                     term /= scaling_factor;\n                     loop_scale += log_scaling_factor;\n                  }\n                  if (fabs(loop_result) < lower_limit)\n                  {\n                     loop_result *= scaling_factor;\n                     loop_abs_result *= scaling_factor;\n                     term *= scaling_factor;\n                     loop_scale -= log_scaling_factor;\n                  }\n                  diff = fabs(term / loop_result);\n               } while (!termination(s - k) && ((diff > boost::math::policies::get_epsilon<Real, Policy>()) || (fabs(term) > fabs(term_m1))));\n\n               //std::cout << \"Norm loop result = \" << std::setprecision(35) << boost::multiprecision::mpfr_float_50(loop_result)* exp(boost::multiprecision::mpfr_float_50(loop_scale)) << std::endl;\n               //\n               // We now need to combine the results of the first series summation with whatever\n               // local results we have now.  First though, rescale abs_result by loop_error_scale\n               // to factor in the error in the pochhammer terms at the start of this block:\n               //\n               loop_abs_result += loop_error_scale * fabs(loop_result);\n               //\n               if (loop_scale > local_scaling)\n               {\n                  //\n                  // Need to shrink previous result:\n                  //\n                  int rescale = local_scaling - loop_scale;\n                  local_scaling = loop_scale;\n                  log_scale -= rescale;\n                  Real ex = exp(Real(rescale));\n                  result *= ex;\n                  abs_result *= ex;\n                  result += loop_result;\n                  abs_result += loop_abs_result;\n               }\n               else if (local_scaling > loop_scale)\n               {\n                  //\n                  // Need to shrink local result:\n                  //\n                  int rescale = loop_scale - local_scaling;\n                  Real ex = exp(Real(rescale));\n                  loop_result *= ex;\n                  loop_abs_result *= ex;\n                  result += loop_result;\n                  abs_result += loop_abs_result;\n               }\n               else\n               {\n                  result += loop_result;\n                  abs_result += loop_abs_result;\n               }\n               //\n               // Reset k to the largest k we reached\n               //\n               k = next_backstop;\n           }\n        }\n\n        return std::make_pair(result, abs_result);\n     }\n\n     struct iteration_terminator\n     {\n        iteration_terminator(boost::uintmax_t i) : m(i) {}\n\n        bool operator()(boost::uintmax_t v) const { return v >= m; }\n\n        boost::uintmax_t m;\n     };\n\n     template <class Seq, class Real, class Policy>\n     Real hypergeometric_pFq_checked_series_impl(const Seq& aj, const Seq& bj, const Real& z, const Policy& pol, int& log_scale)\n     {\n        BOOST_MATH_STD_USING\n        iteration_terminator term(boost::math::policies::get_max_series_iterations<Policy>());\n        std::pair<Real, Real> result = hypergeometric_pFq_checked_series_impl(aj, bj, z, pol, term, log_scale);\n        //\n        // Check to see how many digits we've lost, if it's more than half, raise an evaluation error -\n        // this is an entirely arbitrary cut off, but not unreasonable.\n        //\n        if (result.second * sqrt(boost::math::policies::get_epsilon<Real, Policy>()) > abs(result.first))\n        {\n           return boost::math::policies::raise_evaluation_error(\"boost::math::hypergeometric_pFq<%1%>\", \"Cancellation is so severe that fewer than half the bits in the result are correct, last result was %1%\", Real(result.first * exp(Real(log_scale))), pol);\n        }\n        return result.first;\n     }\n\n     template <class Real, class Policy>\n     inline Real hypergeometric_1F1_checked_series_impl(const Real& a, const Real& b, const Real& z, const Policy& pol, int& log_scale)\n     {\n        boost::array<Real, 1> aj = { a };\n        boost::array<Real, 1> bj = { b };\n        return hypergeometric_pFq_checked_series_impl(aj, bj, z, pol, log_scale);\n     }\n\n  } } } // namespaces\n\n#endif // BOOST_HYPERGEOMETRIC_PFQ_SERIES_HPP_\n", "meta": {"hexsha": "a1ae02b68378afdfd150db062e307c929f3cac23", "size": 27948, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.75.0/boost/math/special_functions/detail/hypergeometric_pFq_checked_series.hpp", "max_stars_repo_name": "detcitty/math", "max_stars_repo_head_hexsha": "fe99d5f31171edb24bc841a9fa2f082982771d35", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-02-14T06:44:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T07:33:34.000Z", "max_issues_repo_path": "lib/boost_1.75.0/boost/math/special_functions/detail/hypergeometric_pFq_checked_series.hpp", "max_issues_repo_name": "detcitty/math", "max_issues_repo_head_hexsha": "fe99d5f31171edb24bc841a9fa2f082982771d35", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-05-23T08:01:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-06T20:49:05.000Z", "max_forks_repo_path": "lib/boost_1.75.0/boost/math/special_functions/detail/hypergeometric_pFq_checked_series.hpp", "max_forks_repo_name": "detcitty/math", "max_forks_repo_head_hexsha": "fe99d5f31171edb24bc841a9fa2f082982771d35", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T14:12:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-22T19:20:54.000Z", "avg_line_length": 42.8650306748, "max_line_length": 258, "alphanum_fraction": 0.4598897953, "num_tokens": 6008, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4037454326622952}}
{"text": "//\n//  Copyright (c) 2000-2002\n//  Joerg Walter, Mathias Koch\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  GeNeSys mbH & Co. KG in producing this work.\n//\n\n#ifndef _BOOST_UBLAS_OPERATION_BLOCKED_\n#define _BOOST_UBLAS_OPERATION_BLOCKED_\n\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublas/detail/vector_assign.hpp> // indexing_vector_assign\n#include <boost/numeric/ublas/detail/matrix_assign.hpp> // indexing_matrix_assign\n\n\nnamespace boost { namespace numeric { namespace ublas {\n\n    template<class V, typename V::size_type BS, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    V\n    block_prod (const matrix_expression<E1> &e1,\n                const vector_expression<E2> &e2) {\n        typedef V vector_type;\n        typedef const E1 expression1_type;\n        typedef const E2 expression2_type;\n        typedef typename V::size_type size_type;\n        typedef typename V::value_type value_type;\n        const size_type block_size = BS;\n\n        V v (e1 ().size1 ());\n#if BOOST_UBLAS_TYPE_CHECK\n        vector<value_type> cv (v.size ());\n        typedef typename type_traits<value_type>::real_type real_type;\n        real_type verrorbound (norm_1 (v) + norm_1 (e1) * norm_1 (e2));\n        indexing_vector_assign<scalar_assign> (cv, prod (e1, e2));\n#endif\n        size_type i_size = e1 ().size1 ();\n        size_type j_size = BOOST_UBLAS_SAME (e1 ().size2 (), e2 ().size ());\n        for (size_type i_begin = 0; i_begin < i_size; i_begin += block_size) {\n            size_type i_end = i_begin + (std::min) (i_size - i_begin, block_size);\n            // FIX: never ignore Martin Weiser's advice ;-(\n#ifdef BOOST_UBLAS_NO_CACHE\n            vector_range<vector_type> v_range (v, range (i_begin, i_end));\n#else\n            // vector<value_type, bounded_array<value_type, block_size> > v_range (i_end - i_begin);\n            vector<value_type> v_range (i_end - i_begin);\n#endif\n            v_range.assign (zero_vector<value_type> (i_end - i_begin));\n            for (size_type j_begin = 0; j_begin < j_size; j_begin += block_size) {\n                size_type j_end = j_begin + (std::min) (j_size - j_begin, block_size);\n#ifdef BOOST_UBLAS_NO_CACHE\n                const matrix_range<expression1_type> e1_range (e1 (), range (i_begin, i_end), range (j_begin, j_end));\n                const vector_range<expression2_type> e2_range (e2 (), range (j_begin, j_end));\n                v_range.plus_assign (prod (e1_range, e2_range));\n#else\n                // const matrix<value_type, row_major, bounded_array<value_type, block_size * block_size> > e1_range (project (e1 (), range (i_begin, i_end), range (j_begin, j_end)));\n                // const vector<value_type, bounded_array<value_type, block_size> > e2_range (project (e2 (), range (j_begin, j_end)));\n                const matrix<value_type, row_major> e1_range (project (e1 (), range (i_begin, i_end), range (j_begin, j_end)));\n                const vector<value_type> e2_range (project (e2 (), range (j_begin, j_end)));\n                v_range.plus_assign (prod (e1_range, e2_range));\n#endif\n            }\n#ifndef BOOST_UBLAS_NO_CACHE\n            project (v, range (i_begin, i_end)).assign (v_range);\n#endif\n        }\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (norm_1 (v - cv) <= 2 * std::numeric_limits<real_type>::epsilon () * verrorbound, internal_logic ());\n#endif\n        return v;\n    }\n\n    template<class V, typename V::size_type BS, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    V\n    block_prod (const vector_expression<E1> &e1,\n                const matrix_expression<E2> &e2) {\n        typedef V vector_type;\n        typedef const E1 expression1_type;\n        typedef const E2 expression2_type;\n        typedef typename V::size_type size_type;\n        typedef typename V::value_type value_type;\n        const size_type block_size = BS;\n\n        V v (e2 ().size2 ());\n#if BOOST_UBLAS_TYPE_CHECK\n        vector<value_type> cv (v.size ());\n        typedef typename type_traits<value_type>::real_type real_type;\n        real_type verrorbound (norm_1 (v) + norm_1 (e1) * norm_1 (e2));\n        indexing_vector_assign<scalar_assign> (cv, prod (e1, e2));\n#endif\n        size_type i_size = BOOST_UBLAS_SAME (e1 ().size (), e2 ().size1 ());\n        size_type j_size = e2 ().size2 ();\n        for (size_type j_begin = 0; j_begin < j_size; j_begin += block_size) {\n            size_type j_end = j_begin + (std::min) (j_size - j_begin, block_size);\n            // FIX: never ignore Martin Weiser's advice ;-(\n#ifdef BOOST_UBLAS_NO_CACHE\n            vector_range<vector_type> v_range (v, range (j_begin, j_end));\n#else\n            // vector<value_type, bounded_array<value_type, block_size> > v_range (j_end - j_begin);\n            vector<value_type> v_range (j_end - j_begin);\n#endif\n            v_range.assign (zero_vector<value_type> (j_end - j_begin));\n            for (size_type i_begin = 0; i_begin < i_size; i_begin += block_size) {\n                size_type i_end = i_begin + (std::min) (i_size - i_begin, block_size);\n#ifdef BOOST_UBLAS_NO_CACHE\n                const vector_range<expression1_type> e1_range (e1 (), range (i_begin, i_end));\n                const matrix_range<expression2_type> e2_range (e2 (), range (i_begin, i_end), range (j_begin, j_end));\n#else\n                // const vector<value_type, bounded_array<value_type, block_size> > e1_range (project (e1 (), range (i_begin, i_end)));\n                // const matrix<value_type, column_major, bounded_array<value_type, block_size * block_size> > e2_range (project (e2 (), range (i_begin, i_end), range (j_begin, j_end)));\n                const vector<value_type> e1_range (project (e1 (), range (i_begin, i_end)));\n                const matrix<value_type, column_major> e2_range (project (e2 (), range (i_begin, i_end), range (j_begin, j_end)));\n#endif\n                v_range.plus_assign (prod (e1_range, e2_range));\n            }\n#ifndef BOOST_UBLAS_NO_CACHE\n            project (v, range (j_begin, j_end)).assign (v_range);\n#endif\n        }\n#if BOOST_UBLAS_TYPE_CHECK\n        BOOST_UBLAS_CHECK (norm_1 (v - cv) <= 2 * std::numeric_limits<real_type>::epsilon () * verrorbound, internal_logic ());\n#endif\n        return v;\n    }\n\n    template<class M, typename M::size_type BS, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    M\n    block_prod (const matrix_expression<E1> &e1,\n                const matrix_expression<E2> &e2,\n                row_major_tag) {\n        typedef M matrix_type;\n        typedef const E1 expression1_type;\n        typedef const E2 expression2_type;\n        typedef typename M::size_type size_type;\n        typedef typename M::value_type value_type;\n        const size_type block_size = BS;\n\n        M m (e1 ().size1 (), e2 ().size2 ());\n#if BOOST_UBLAS_TYPE_CHECK\n        matrix<value_type, row_major> cm (m.size1 (), m.size2 ());\n        typedef typename type_traits<value_type>::real_type real_type;\n        real_type merrorbound (norm_1 (m) + norm_1 (e1) * norm_1 (e2));\n        indexing_matrix_assign<scalar_assign> (cm, prod (e1, e2), row_major_tag ());\n        disable_type_check<bool>::value = true;\n#endif\n        size_type i_size = e1 ().size1 ();\n        size_type j_size = e2 ().size2 ();\n        size_type k_size = BOOST_UBLAS_SAME (e1 ().size2 (), e2 ().size1 ());\n        for (size_type i_begin = 0; i_begin < i_size; i_begin += block_size) {\n            size_type i_end = i_begin + (std::min) (i_size - i_begin, block_size);\n            for (size_type j_begin = 0; j_begin < j_size; j_begin += block_size) {\n                size_type j_end = j_begin + (std::min) (j_size - j_begin, block_size);\n                // FIX: never ignore Martin Weiser's advice ;-(\n#ifdef BOOST_UBLAS_NO_CACHE\n                matrix_range<matrix_type> m_range (m, range (i_begin, i_end), range (j_begin, j_end));\n#else\n                // matrix<value_type, row_major, bounded_array<value_type, block_size * block_size> > m_range (i_end - i_begin, j_end - j_begin);\n                matrix<value_type, row_major> m_range (i_end - i_begin, j_end - j_begin);\n#endif\n                m_range.assign (zero_matrix<value_type> (i_end - i_begin, j_end - j_begin));\n                for (size_type k_begin = 0; k_begin < k_size; k_begin += block_size) {\n                    size_type k_end = k_begin + (std::min) (k_size - k_begin, block_size);\n#ifdef BOOST_UBLAS_NO_CACHE\n                    const matrix_range<expression1_type> e1_range (e1 (), range (i_begin, i_end), range (k_begin, k_end));\n                    const matrix_range<expression2_type> e2_range (e2 (), range (k_begin, k_end), range (j_begin, j_end));\n#else\n                    // const matrix<value_type, row_major, bounded_array<value_type, block_size * block_size> > e1_range (project (e1 (), range (i_begin, i_end), range (k_begin, k_end)));\n                    // const matrix<value_type, column_major, bounded_array<value_type, block_size * block_size> > e2_range (project (e2 (), range (k_begin, k_end), range (j_begin, j_end)));\n                    const matrix<value_type, row_major> e1_range (project (e1 (), range (i_begin, i_end), range (k_begin, k_end)));\n                    const matrix<value_type, column_major> e2_range (project (e2 (), range (k_begin, k_end), range (j_begin, j_end)));\n#endif\n                    m_range.plus_assign (prod (e1_range, e2_range));\n                }\n#ifndef BOOST_UBLAS_NO_CACHE\n                project (m, range (i_begin, i_end), range (j_begin, j_end)).assign (m_range);\n#endif\n            }\n        }\n#if BOOST_UBLAS_TYPE_CHECK\n        disable_type_check<bool>::value = false;\n        BOOST_UBLAS_CHECK (norm_1 (m - cm) <= 2 * std::numeric_limits<real_type>::epsilon () * merrorbound, internal_logic ());\n#endif\n        return m;\n    }\n\n    template<class M, typename M::size_type BS, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    M\n    block_prod (const matrix_expression<E1> &e1,\n                const matrix_expression<E2> &e2,\n                column_major_tag) {\n        typedef M matrix_type;\n        typedef const E1 expression1_type;\n        typedef const E2 expression2_type;\n        typedef typename M::size_type size_type;\n        typedef typename M::value_type value_type;\n        const size_type block_size = BS;\n\n        M m (e1 ().size1 (), e2 ().size2 ());\n#if BOOST_UBLAS_TYPE_CHECK\n        matrix<value_type, column_major> cm (m.size1 (), m.size2 ());\n        typedef typename type_traits<value_type>::real_type real_type;\n        real_type merrorbound (norm_1 (m) + norm_1 (e1) * norm_1 (e2));\n        indexing_matrix_assign<scalar_assign> (cm, prod (e1, e2), column_major_tag ());\n        disable_type_check<bool>::value = true;\n#endif\n        size_type i_size = e1 ().size1 ();\n        size_type j_size = e2 ().size2 ();\n        size_type k_size = BOOST_UBLAS_SAME (e1 ().size2 (), e2 ().size1 ());\n        for (size_type j_begin = 0; j_begin < j_size; j_begin += block_size) {\n            size_type j_end = j_begin + (std::min) (j_size - j_begin, block_size);\n            for (size_type i_begin = 0; i_begin < i_size; i_begin += block_size) {\n                size_type i_end = i_begin + (std::min) (i_size - i_begin, block_size);\n                // FIX: never ignore Martin Weiser's advice ;-(\n#ifdef BOOST_UBLAS_NO_CACHE\n                matrix_range<matrix_type> m_range (m, range (i_begin, i_end), range (j_begin, j_end));\n#else\n                // matrix<value_type, column_major, bounded_array<value_type, block_size * block_size> > m_range (i_end - i_begin, j_end - j_begin);\n                matrix<value_type, column_major> m_range (i_end - i_begin, j_end - j_begin);\n#endif\n                m_range.assign (zero_matrix<value_type> (i_end - i_begin, j_end - j_begin));\n                for (size_type k_begin = 0; k_begin < k_size; k_begin += block_size) {\n                    size_type k_end = k_begin + (std::min) (k_size - k_begin, block_size);\n#ifdef BOOST_UBLAS_NO_CACHE\n                    const matrix_range<expression1_type> e1_range (e1 (), range (i_begin, i_end), range (k_begin, k_end));\n                    const matrix_range<expression2_type> e2_range (e2 (), range (k_begin, k_end), range (j_begin, j_end));\n#else\n                    // const matrix<value_type, row_major, bounded_array<value_type, block_size * block_size> > e1_range (project (e1 (), range (i_begin, i_end), range (k_begin, k_end)));\n                    // const matrix<value_type, column_major, bounded_array<value_type, block_size * block_size> > e2_range (project (e2 (), range (k_begin, k_end), range (j_begin, j_end)));\n                    const matrix<value_type, row_major> e1_range (project (e1 (), range (i_begin, i_end), range (k_begin, k_end)));\n                    const matrix<value_type, column_major> e2_range (project (e2 (), range (k_begin, k_end), range (j_begin, j_end)));\n#endif\n                    m_range.plus_assign (prod (e1_range, e2_range));\n                }\n#ifndef BOOST_UBLAS_NO_CACHE\n                project (m, range (i_begin, i_end), range (j_begin, j_end)).assign (m_range);\n#endif\n            }\n        }\n#if BOOST_UBLAS_TYPE_CHECK\n        disable_type_check<bool>::value = false;\n        BOOST_UBLAS_CHECK (norm_1 (m - cm) <= 2 * std::numeric_limits<real_type>::epsilon () * merrorbound, internal_logic ());\n#endif\n        return m;\n    }\n\n    // Dispatcher\n    template<class M, typename M::size_type BS, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    M\n    block_prod (const matrix_expression<E1> &e1,\n                const matrix_expression<E2> &e2) {\n        typedef typename M::orientation_category orientation_category;\n        return block_prod<M, BS> (e1, e2, orientation_category ());\n    }\n\n}}}\n\n#endif\n", "meta": {"hexsha": "812b24ea5824774c23317730bfc56f7e1a09f37f", "size": 13813, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/numeric/ublas/operation_blocked.hpp", "max_stars_repo_name": "189569400/ClickHouse", "max_stars_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "contrib/libboost/boost_1_62_0/boost/numeric/ublas/operation_blocked.hpp", "max_issues_repo_name": "189569400/ClickHouse", "max_issues_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "contrib/libboost/boost_1_62_0/boost/numeric/ublas/operation_blocked.hpp", "max_forks_repo_name": "189569400/ClickHouse", "max_forks_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 51.734082397, "max_line_length": 190, "alphanum_fraction": 0.6367190328, "num_tokens": 3651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754607093178, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.40364089217927673}}
{"text": "//By Fatemeh Saki, University of Texas at Dallas, Spring 2017\n// Modified by Nasim Alamdari, 2017\n#include \"stdafx.h\"\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <dlib/svm.h>\n\n\n// Macros for this module\n#define R2_MULTIPLIER_CONST\t\t1.1\n#define THRESHOLD_CONST\t\t\t0.3\n\n// SVM Macros\n#define SVM_TYPE\t\t\t\tSVDD\n#define KERNEL_TYPE\t\t\t\tRBF\n#define TOL\t\t\t\t\t\t1e-8 \n#define PI\t\t\t\t\t\t3.14159265358979323846\n#define CACHE_SIZE\t\t\t\t100\n\n// -----------------------------------------------------------------------------------------------\n// Definition of the Classification function\nvoid Classification(const SVCluster* ClusterSet, double** frame, int* ClassOut, const int sizeC, const int m, const int n)\n{\n\t/* \n\tinitialize the output vector\n\tClassOut[0] is equivalent of CloseCL\tin MATLAB\n\tClassOut[1] is equivalent of ClassType\tin MATLAB\n\tClassOut[2] is equivalent of NovOp\t\tin MATLAB\n\t*/\n\tfor (int i = 0; i < 2; i++)\n\t\tClassOut[i] = 0;\n\n\n\t// allocating memory for the Dist results\n\tdouble **Dist = (double **)malloc(sizeC * sizeof(double *));\n\tfor (int i = 0; i < sizeC; i++)\n\t\tDist[i] = (double *)malloc(m* sizeof(double)); // modified by Nasim\n\n\t// allocating memory for the closeness index results\n\tdouble **CloseIdx = (double **)malloc(sizeC * sizeof(double *));\n\tfor (int i = 0; i < sizeC; i++)\n\t\tCloseIdx[i] = (double *)malloc(m* sizeof(double)); // modified by Nasim\n\n\n\t// loop over the cluster set and perform the calculation\n\tfor (int i = 0; i < sizeC; i++){\n\n\t\t// extract the structure information for the ith element\n\t\tint c = (ClusterSet + i)->c;\n\t\tint r = (ClusterSet + i)->r;\n\t\tdouble Kxx = (ClusterSet + i)->Kxx;\n\t\tdouble R2 = (ClusterSet + i)->R2;\n\t\tdouble sigma = (ClusterSet + i)->sigma;\n\t\tdouble offsets = (ClusterSet + i)->offsets;\n\t\tdouble* alpha = (ClusterSet + i)->alpha;\n\t\tdouble** SVvect = (ClusterSet + i)->SVvectors;\n\n\n\t\t// declare the kernelDist vector\n\t\tdouble *kernelDist = (double *)malloc(m * sizeof(double)); //modified by Nasim\n\n\t\t// allocating memory for the result pauerwise euclidian distance \n\t\tdouble **DistMtx = (double **)malloc(r * sizeof(double *));\n\t\tfor (int j = 0; j < r; j++)\n\t\t\tDistMtx[j] = (double *)malloc(m* sizeof(double));\n\n\t\t// calculate the distance \n\t\tMyDistm(SVvect, frame, DistMtx, r, m, c);// corrected by Nasim\n\n\t\t// claculate alphaK (to save memory we reuse DistMtx) \n\t\tmyExp(DistMtx, alpha, r, m, sigma); // corrected by Nasim\n\n\n\t\t//ofstream out_data;\n\t\t//out_data.open(\"OFC Results.txt\", ios::trunc); //modified by Nasim\n\t\t// loop over j to calculate the kernelDist\n\t\tfor (int j = 0; j < m; j++){ // modified by Nasim\n\t\t\tdouble sum = 0;\n\t\t\tfor (int k = 0; k < r; k++){\n\t\t\t\tsum += DistMtx[k][j]; //modified by Nasim (previously was DistMtx[j][k];)\n\t\t\t}\n\n\n\t\t\t//kernelDist[j] = (1 - 2 * sum + Kxx) / (R2_MULTIPLIER_CONST * R2);\n\t\t\tkernelDist[j] = (1 - 2 * sum + Kxx); // Modified by Nasim\n\t\t\tDist[i][j] = kernelDist[j] / (R2_MULTIPLIER_CONST * R2);\n\n\t\t\t// Perform a comparision for the calculation of CloseIdx\n\t\t\tif (kernelDist[j] <= (R2_MULTIPLIER_CONST * R2))\n\t\t\t\tCloseIdx[i][j] = 1; //modified by Nasim\n\t\t\telse\n\t\t\t\tCloseIdx[i][j] = 0;\n\n\t\t\t//out_data << CloseIdx[i][j] << '\\n';\n\n\t\t}// end of the for loop\n\t\t//out_data.close();\n\t\t// free the memory for the current SVCluster\n\t\tfor (int j = 0; j < r; j++) free(DistMtx[j]);\n\t\tfree(DistMtx);\n\n\t\tfree(kernelDist);\n\n\t\tDistMtx = NULL;\n\t\tkernelDist = NULL;\n\t}// end of the for loop\n\t\n\t// declare the sumCloseIdx vector\n\tdouble *sumCloseIdx = (double *)malloc(sizeC * sizeof(double));\n\n\t// calculate the sum of closeIdx matrix across the first dimension\n\tfor (int i = 0; i < sizeC; i++){\n\t\tdouble sum = 0;\n\t\tfor (int j = 0; j < m; j++) //modified by Nasim\n\t\t\tsum += CloseIdx[i][j];\n\n\t\tsumCloseIdx[i] = sum;\n\t}\n\t\n\t// define a threshold\n\tdouble threshold = floor(THRESHOLD_CONST * m);\n\n\t// perform the required comparisions\n\tif (sizeC == 1){\n\t\tif (compareArrays(sumCloseIdx, threshold, sizeC)){\n\t\t\tClassOut[0] = 1;\n\t\t\tClassOut[1] = 1;\n\t\t\tClassOut[2] = 0; // modified by Nasim\n\t\t}\n\t\telse\n\t\t\tClassOut[0] = 0; // modified by Nasim\n\t\t    ClassOut[1] = 0; // modified by Nasim\n\t\t\tClassOut[2] = 1;\n\n\t}\n\telse if (sizeC > 1){\n\t\t// declare the Clust vector\n\t\tint *Clust = (int *)malloc(m * sizeof(int)); // modified by Nasim\n\t\t// find the min of matrix dist across the first dimension\n\t\tminMatrixR(Dist, Clust, sizeC, m); \n\n\t\t//ofstream out_data;\n\t\t//out_data.open(\"OFC Results.txt\", ios::trunc); //modified by Nasim\n\t\tint *Clust2 = (int *)malloc(m * sizeof(int)); //added by Nasim\n\t\tfor (int i = 0; i < m; i++){ //added by Nasim\n\t\t\tClust2[i] = Clust[i] + 1;\n\t\t\t//out_data << Clust2[i] << ',';\n\t\t}\n\t\t//out_data.close();\n\t\t// take the statistical mode of array Clust\n\t\tint CloseCL2 = mode(Clust2, m); // modified by Nasim\n\t\t// now compute the sum\n\t\tdouble sum = 0;\n\t\tfor (int i = 0; i < m; i++) //modified by Nasim\n\t\t\tsum += CloseIdx[CloseCL2-1][i]; // modified by Nasim\n\n\t\tif (sum>=threshold){\n\t\t\tClassOut[0] = CloseCL2;\n\t\t\tClassOut[1] = 1;\n\t\t}\n\t\telse if (sum==0)\n\t\t\tClassOut[2] = 1;\n\n\t}\n\t\n\n\t//free the allocated memory\n\tfor (int i = 0; i < sizeC; i++) free(Dist[i]);\n\tfree(Dist);\n\n\tfor (int i = 0; i < sizeC; i++) free(CloseIdx[i]);\n\tfree(CloseIdx);\n\n\tfree(sumCloseIdx);\n\n\tDist\t\t= NULL;\n\tCloseIdx\t= NULL;\n\tsumCloseIdx = NULL;\n\n\treturn;\n}\n\n\n\n// -----------------------------------------------------------------------------------------------\n// Definition of the connection Check function\nint connectionCheck(double** frame1, double** frame2, const int Rowsize1, const int Rowsize2, const int ColSize, const double eps1, const double eps2){\n\n\t// allocating memory for the euclidian distance matrix\n\tdouble **DistMtx = (double **)malloc(Rowsize1 * sizeof(double *));\n\tfor (int i = 0; i < Rowsize1; i++)\n\t\tDistMtx[i] = (double *)malloc(Rowsize2 * sizeof(double)); //modified byNasim\n\n\t// run the Eclidean distance function\n\tMyDistm(frame1, frame2, DistMtx, Rowsize1, Rowsize2, ColSize);\n\n\t// calculate the conditional sum of the matrix entries\n\tdouble clustDist = sumMatrixCond(DistMtx, Rowsize1, Rowsize2, eps1 + eps2); // modified by Nasim\n\n\n\t// free the allocated memory \n\tfor (int i = 0; i < Rowsize1; i++) free(DistMtx[i]); //modified by Nasim\n\tfree(DistMtx);\n\n\t// avoid danggling pointer\n\tDistMtx = NULL;\n\n\tif (clustDist > (THRESHOLD_CONST * Rowsize1 * THRESHOLD_CONST * Rowsize2))\n\t\treturn +1;\n\n\treturn -1;\n}\n\n\n\n// -----------------------------------------------------------------------------------------------\n// Definition of the Frame analysis function\n//Confirmed by Nasim\ndouble frameAnalysis(double** frame, const int RowSize, const int ColSize)\n{\n\t// allocating memory for the euclidian distance matrix\n\tdouble **DistMtx = (double **)malloc(RowSize * sizeof(double *));\n\tfor (int i = 0; i < RowSize; i++)\n\t\tDistMtx[i] = (double *)malloc(RowSize * sizeof(double));\n\n\t// run the Eclidean distance function\n\tMyDistm(frame, frame, DistMtx, RowSize, RowSize, ColSize);\n\n\t// find the mean of the matrix entries\n\tdouble mDist = meanMatrix(DistMtx, RowSize, ColSize)/2;\n\n\t// find the maximum element\n\tdouble radius = maxMatrix(DistMtx, RowSize, ColSize);\n\t\n\t// for debug purpose only\n\t//printFrame(DistMtx, Rowsize, ColSize);\n\n\t// free the allocated memory \n\tfor (int i = 0; i < RowSize; i++) free(DistMtx[i]);\n\tfree(DistMtx);\n\n\t// avoid danggling pointer\n\tDistMtx = NULL;\n\n\treturn radius;\n}\n\n// -----------------------------------------------------------------------------------------------\n// Definition of the Cluster Creation function //modified by Nasim\nSVCluster* ClusterCreation(double** svData, const int svRow, const int svCol, const double fracRejection, const double sigma){\n\n\t//******************************* Nasim added: dlib one-class SVM****************\n\t// We will use column vectors to store our points.  Here we make a convenient typedef\n\t// for the kind of vector we will use.\n\ttypedef dlib::matrix<double,0, 1> sample_type; //Nasim: This typedef declares a matrix with unknow(0) rows and 1 column. This is column vector.\n\n\t// Then we select the kernel we want to use.  For our present problem the radial basis\n  // kernel is quite effective.\n\ttypedef dlib::radial_basis_kernel<sample_type> kernel_type; //Nasim: use same\n\n\tstd::vector<sample_type> samples;\n\tsample_type samp(svCol); //Nasim: my data should be m(8), since 8 features every vector\n\n\tfor (int i = 0; i< svRow; i++)\n\t{\n\t\t\tsamp(0) = svData[i][0];\n\t\t\tsamp(1) = svData[i][1];\n\t\t\tsamp(2) = svData[i][2];\n\t\t\tsamp(3) = svData[i][3];\n\t\t\tsamp(4) = svData[i][4];\n\t\t\tsamp(5) = svData[i][5];\n\t\t\tsamp(6) = svData[i][6];\n\t\t\tsamp(7) = svData[i][7];\n\t\t\tsamples.push_back(samp);\n\t}\n\n\t//vector_normalizer<sample_type> normalizer;\n\t// let the normalizer learn the mean and standard deviation of the samples\n\t//normalizer.train(samples);\n\t// now normalize each sample\n\t//for (unsigned long i = 0; i < samples.size(); ++i)\n\t//\tsamples[i] = normalizer(samples[i]);\n\n\t// Now make the object responsible for training one-class SVMs.\n\tdlib::svm_one_class_trainer<kernel_type> trainer;\n\n\t// Here we set the width of the radial basis kernel\n\ttrainer.set_kernel(kernel_type(sigma)); // Nasim 4.0 is width of rbf kernel (sigma)\n\tdouble NU = svRow*fracRejection;\n\ttrainer.set_nu((NU < 1) ? 1 : 1 / NU);\n\ttrainer.set_epsilon(TOL);\n\t//trainer.set_nu(1/svRow*fracRejection);\n\t//trainer.set_lambda(0.00001);\n\t//const double C = get_option(parser, \"c\", 1.0);\n\t//trainer.set_c(C);\n\n\t// Now train a one-class SVM.  The result is a function, df(),\n\tdlib::decision_function<kernel_type> df = trainer.train(samples);\n\n\t//cout << \"\\n number of support vectors in our learned_function is \"\n\t//\t<< df.basis_vectors.size() << endl;\n\n\t//df.alpha;\n\t//df.b;\n\t//df.basis_vectors;\n\t//df.kernel_function;\n\t//df.kernel_function.gamma;\n\n\t//***********************************************************************************\n\t// initialize mySVClust by allocating memory dynamically\n\tSVCluster* mySVClust = (SVCluster *)malloc(sizeof(SVCluster));\n\n\t\n\n\t// allocating memory for the SVvectors matrix //modified by Nasim\n\tdouble **SVvectors = (double **)malloc(df.basis_vectors.size() * sizeof(double *));\n\tfor (int j = 0; j < df.basis_vectors.size(); j++)\n\tSVvectors[j] = (double *)malloc(svCol * sizeof(double));\n\n\t// populate the SVvectors matrix from the model\n\tfor (int i = 0; i < df.basis_vectors.size(); i++) {\n\t\tfor (int j = 0; j < svCol; j++) {\n\t\t\tSVvectors[i][j] = df.basis_vectors(i)(j);\n        \n\t\t}\n    \n\t}\n\t\n\tdouble sumAlpha = 0;\n\tfor (int i = 0; i < df.basis_vectors.size(); i++) {\n\t\tsumAlpha += df.alpha(i);\n\t}\n\n\tdouble *alpha = (double *)malloc(df.basis_vectors.size() * sizeof(double));\n\tfor (int i = 0; i < df.basis_vectors.size(); i++) {\n\t\talpha[i] = df.alpha(i) / sumAlpha; //Nasim: not sure about devision by sumAlpha\n\t\t//alpha[i] = df.alpha(i); //Nasim\n\t\t\n\t}\n\t\n\n\t// allocating memory for the result pauerwise euclidian distance \n\tdouble **DistMtx = (double **)malloc(df.basis_vectors.size() * sizeof(double *));\n\tfor (int j = 0; j < df.basis_vectors.size(); j++)\n\tDistMtx[j] = (double *)malloc(df.basis_vectors.size() * sizeof(double));\n\n\t// calculate the distance \n\tMyDistm(SVvectors, SVvectors, DistMtx, df.basis_vectors.size(), df.basis_vectors.size(), svCol);\n\n\t// claculate Kxx (to save memory we reuse DistMtx) \n\tdouble Kxx = myExp_alpha(DistMtx, alpha, df.basis_vectors.size(), sigma);\n\n\t//------added by Nasim----------------------------------------\n\tdouble *Dx = (double *)malloc(df.basis_vectors.size() * sizeof(double));\n\tfor (int i = 0; i < df.basis_vectors.size(); i++) {\n\t\tdouble K = 0;\n\t\tfor (int j = 0; j < df.basis_vectors.size(); j++) {\n\t\t\tK += alpha[i]*exp(-DistMtx[j][i] / (sigma * sigma)); \n\t\t}\n\t\tDx[i] = -2 * K;\n\t}\n\n\tdouble offs = 1 + Kxx;\n\tdouble sum = 0;\n\tfor (int i = 0; i < df.basis_vectors.size(); i++) {\n\t\tsum += Dx[i];\n\t}\n\tdouble R2 = sum / df.basis_vectors.size(); //\n\tdouble threshold = R2 + offs;\n\t//------------------------------------------------------------------\n\t// free the memory for DistMtx\n\tfor (int j = 0; j < df.basis_vectors.size(); j++) free(DistMtx[j]);\n\tfree(DistMtx);\n\n\tDistMtx = NULL;\n\n\n\t// pack the data in the structure\n\tmySVClust->SVvectors    = SVvectors;\n\tmySVClust->alpha        = alpha;\n\tmySVClust->r\t\t\t= df.basis_vectors.size();\n\tmySVClust->c            = svCol;\n\tmySVClust->Kxx\t\t\t= Kxx;\n\tmySVClust->R2           = threshold;//model->r_square;\t// had to make changes to the svm library to get access to this\n\tmySVClust->sigma        = df.kernel_function.gamma;\t\t\t// redundant\n\tmySVClust->offsets      = offs;\t\t\t\t// // Modified by Nasim\n\n\t\t\t\t\t\t\t\t\t\t// free the svm-related dynamic memory\n\t\t\t\t\t\t\t\t\t\t//free(prob.x);\n\t\t\t\t\t\t\t\t\t\t//free(prob.y);\n\t\t\t\t\t\t\t\t\t\t//free(x_space);\n\t\t\t\t\t\t\t\t\t\t//svm_free_and_destroy_model(&model);\n\t\t\t\t\t\t\t\t\t\t//svm_destroy_param(&param);\n\n\treturn mySVClust;\n}\n", "meta": {"hexsha": "b9160f44940cbd5ac4bee17437eb43e1bc69dfea", "size": 12688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OFC_iOS/OFC_iOS/Frameprocessing.cpp", "max_stars_repo_name": "ssprl/Unsupervised-Noise-Classification", "max_stars_repo_head_hexsha": "0929a804dab679c5cf7190c1d1db8ab985deb845", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-26T08:36:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T08:36:09.000Z", "max_issues_repo_path": "OFC_iOS/OFC_iOS/Frameprocessing.cpp", "max_issues_repo_name": "ssprl/Unsupervised-Noise-Classification", "max_issues_repo_head_hexsha": "0929a804dab679c5cf7190c1d1db8ab985deb845", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OFC_iOS/OFC_iOS/Frameprocessing.cpp", "max_forks_repo_name": "ssprl/Unsupervised-Noise-Classification", "max_forks_repo_head_hexsha": "0929a804dab679c5cf7190c1d1db8ab985deb845", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-12T14:12:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T14:12:06.000Z", "avg_line_length": 31.8793969849, "max_line_length": 151, "alphanum_fraction": 0.6242906683, "num_tokens": 3783, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754489059774, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4036408856346731}}
{"text": "#include \"SeparationAlgorithms.hpp\"\n\n#include \"LinearConstraint.hpp\"\n#include \"LinearVariableComposition.hpp\"\n#include \"Model.hpp\"\n#include \"SupportGraphs.hpp\"\n#include \"Variable.hpp\"\n#include \"WeightManager.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/one_bit_color_map.hpp>\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n#include <boost/range/iterator_range.hpp>\n\n#include <xtensor/xtensor.hpp>\n#include <xtensor/xvectorize.hpp>\n#include <xtensor/xview.hpp>\n\nnamespace tsplp::graph\n{\n    using EdgeWeightProperty = boost::property<boost::edge_weight_t, double>;\n    using UndirectedGraph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, EdgeWeightProperty>;\n\n    Separator::Separator(const xt::xtensor<Variable, 3>& variables, const WeightManager& weightManager, const Model& model)\n        : m_variables(variables), m_weightManager(weightManager), m_model(model), m_spSupportGraph(std::make_unique<PiSigmaSupportGraph>(variables, weightManager.Dependencies(), model))\n    {\n    }\n\n    Separator::~Separator() noexcept = default;\n\n    std::optional<LinearConstraint> Separator::Ucut() const\n    {\n        const auto N = m_weightManager.N();\n        const auto vf = xt::vectorize([this](Variable v) { return v.GetObjectiveValue(m_model); });\n        const auto values = vf(m_variables);\n\n        UndirectedGraph graph(N);\n        for (size_t u = 0; u < N; ++u)\n        {\n            for (size_t v = u + 1; v < N; ++v)\n            {\n                const auto weight = xt::sum(xt::view(values, xt::all(), u, v))() + xt::sum(xt::view(values, xt::all(), v, u))();\n                boost::add_edge(u, v, weight, graph);\n            }\n        }\n\n        const auto parities = boost::make_one_bit_color_map(N, get(boost::vertex_index, graph));\n\n        const auto cutSize = boost::stoer_wagner_min_cut(graph, get(boost::edge_weight, graph), boost::parity_map(parities));\n\n        if (cutSize >= 2.0 - 1.e-10)\n            return std::nullopt;\n\n        LinearVariableComposition sum;\n        for (size_t u = 0; u < N; ++u)\n            for (size_t v = 0; v < N; ++v)\n                if (get(parities, u) != get(parities, v))\n                    sum += xt::sum(xt::view(m_variables, xt::all(), u, v) + 0)();\n\n        return sum >= 2;\n    }\n\n    std::optional<LinearConstraint> Separator::Pi() const\n    {\n        if (m_weightManager.Dependencies().GetArcs().empty())\n            return std::nullopt;\n\n        const auto N = m_weightManager.N();\n        const auto A = m_weightManager.A();\n\n        for (size_t n = 0; n < N; ++n)\n        {\n            if (m_weightManager.Dependencies().GetIncomingSpan(n).empty())\n                continue;\n\n            for (size_t a = 0; a < A; ++a)\n            {\n                const auto e = m_weightManager.EndPositions()[a];\n                if (n == e)\n                    continue;\n\n                const auto [cutSize, cutEdges] = m_spSupportGraph->FindMinCut(n, e, PiSigmaSupportGraph::ConstraintType::Pi);\n\n                if (cutSize < 1.0 - 1.e-10)\n                {\n\n                    LinearVariableComposition sum;\n                    for (const auto& [u, v] : cutEdges)\n                        sum += xt::sum(xt::view(m_variables, xt::all(), u, v) + 0)();\n\n                    assert(std::abs(sum.Evaluate(m_model) - cutSize) < 1.e-10);\n                    auto constraint = sum >= 1;\n                    assert(!constraint.Evaluate(m_model));\n\n                    return constraint;\n                }\n            }\n        }\n\n        return std::nullopt;\n    }\n\n    std::optional<LinearConstraint> Separator::Sigma() const\n    {\n        if (m_weightManager.Dependencies().GetArcs().empty())\n            return std::nullopt;\n\n        const auto N = m_weightManager.N();\n        const auto A = m_weightManager.A();\n\n        for (size_t n = 0; n < N; ++n)\n        {\n            if (m_weightManager.Dependencies().GetOutgoingSpan(n).empty())\n                continue;\n\n            for (size_t a = 0; a < A; ++a)\n            {\n                const auto s = m_weightManager.StartPositions()[a];\n                if (n == s)\n                    continue;\n\n                const auto [cutSize, cutEdges] = m_spSupportGraph->FindMinCut(s, n, PiSigmaSupportGraph::ConstraintType::Sigma);\n\n                if (cutSize < 1.0 - 1.e-10)\n                {\n                    LinearVariableComposition sum;\n                    for (const auto& [u, v] : cutEdges)\n                        sum += xt::sum(xt::view(m_variables, xt::all(), u, v) + 0)();\n\n                    auto constraint = sum >= 1;\n                    assert(!constraint.Evaluate(m_model));\n\n                    return constraint;\n                }\n            }\n        }\n\n        return std::nullopt;\n    }\n\n    std::optional<LinearConstraint> Separator::PiSigma() const\n    {\n        if (m_weightManager.Dependencies().GetArcs().empty())\n            return std::nullopt;\n\n        for (const auto& [s, t] : m_weightManager.Dependencies().GetArcs())\n        {\n            const auto [cutSize, cutEdges] = m_spSupportGraph->FindMinCut(s, t, PiSigmaSupportGraph::ConstraintType::PiSigma);\n\n            if (cutSize < 1.0 - 1.e-10)\n            {\n                LinearVariableComposition sum;\n                for (const auto& [u, v] : cutEdges)\n                    sum += xt::sum(xt::view(m_variables, xt::all(), u, v) + 0)();\n\n                assert(std::abs(sum.Evaluate(m_model) - cutSize) < 1.e-10);\n                auto constraint = sum >= 1;\n                assert(!constraint.Evaluate(m_model));\n\n                return constraint;\n            }\n        }\n\n        return std::nullopt;\n    }\n}\n", "meta": {"hexsha": "0008f2c7fdfa89cd7646e64490464c6da724addd", "size": 5657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tsplp/src/SeparationAlgorithms.cpp", "max_stars_repo_name": "sebrockm/mtsp-vrp", "max_stars_repo_head_hexsha": "28955855d253f51fcb9397a0b22c6774f66f8d55", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tsplp/src/SeparationAlgorithms.cpp", "max_issues_repo_name": "sebrockm/mtsp-vrp", "max_issues_repo_head_hexsha": "28955855d253f51fcb9397a0b22c6774f66f8d55", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tsplp/src/SeparationAlgorithms.cpp", "max_forks_repo_name": "sebrockm/mtsp-vrp", "max_forks_repo_head_hexsha": "28955855d253f51fcb9397a0b22c6774f66f8d55", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.874251497, "max_line_length": 185, "alphanum_fraction": 0.5472865476, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.40355635620947955}}
{"text": "// Copyright (c) 2012-2017 VideoStitch SAS\n// Copyright (c) 2018 stitchEm\n\n#ifndef __INPUT_DISTANCE_HPP__\n#define __INPUT_DISTANCE_HPP__\n\n#include \"calibrationConfig.hpp\"\n#include \"camera.hpp\"\n\n#include <ceres/ceres.h>\n#include <Eigen/Dense>\n\n#include <unordered_map>\n#include <assert.h>\n\nnamespace VideoStitch {\nnamespace Calibration {\n\n#define INDEX_HFOCAL_CAM1 0\n#define INDEX_HFOCAL_CAM2 1\n#define INDEX_VFOCAL_CAM1 2\n#define INDEX_VFOCAL_CAM2 3\n#define INDEX_HCENTER_CAM1 4\n#define INDEX_HCENTER_CAM2 5\n#define INDEX_VCENTER_CAM1 6\n#define INDEX_VCENTER_CAM2 7\n#define INDEX_LENSDISTORTA_CAM1 8\n#define INDEX_LENSDISTORTA_CAM2 9\n#define INDEX_LENSDISTORTB_CAM1 10\n#define INDEX_LENSDISTORTB_CAM2 11\n#define INDEX_LENSDISTORTC_CAM1 12\n#define INDEX_LENSDISTORTC_CAM2 13\n#define INDEX_ROTATION_CAM1 14\n#define INDEX_ROTATION_CAM2 15\n#define INDEX_TX_CAM1 16\n#define INDEX_TX_CAM2 17\n#define INDEX_TY_CAM1 18\n#define INDEX_TY_CAM2 19\n#define INDEX_TZ_CAM1 20\n#define INDEX_TZ_CAM2 21\n#define INDEX_3DPOINT 22\n#define INDEX_LAST 23\n\n#define SIZE_VFOCAL_CAM1 4\n#define SIZE_VFOCAL_CAM2 4\n#define SIZE_HFOCAL_CAM1 4\n#define SIZE_HFOCAL_CAM2 4\n#define SIZE_VCENTER_CAM1 4\n#define SIZE_VCENTER_CAM2 4\n#define SIZE_HCENTER_CAM1 4\n#define SIZE_HCENTER_CAM2 4\n#define SIZE_LENSDISTORTA_CAM1 4\n#define SIZE_LENSDISTORTA_CAM2 4\n#define SIZE_LENSDISTORTB_CAM1 4\n#define SIZE_LENSDISTORTB_CAM2 4\n#define SIZE_LENSDISTORTC_CAM1 4\n#define SIZE_LENSDISTORTC_CAM2 4\n#define SIZE_ROTATION_CAM1 9\n#define SIZE_ROTATION_CAM2 9\n#define SIZE_TX_CAM1 4\n#define SIZE_TX_CAM2 4\n#define SIZE_TY_CAM1 4\n#define SIZE_TY_CAM2 4\n#define SIZE_TZ_CAM1 4\n#define SIZE_TZ_CAM2 4\n#define SIZE_3DPOINT 3\n\nclass inputDistanceCostFunction : public ceres::CostFunction {\n public:\n  inputDistanceCostFunction(const std::shared_ptr<Camera>& cam1, const std::shared_ptr<Camera>& cam2,\n                            const Eigen::Vector2d& impt1, const Eigen::Vector2d& impt2, const CalibrationConfig& config,\n                            const double sphereScale)\n      : camera1(cam1->clone()),\n        camera2(cam2->clone()),\n        impt1(impt1),\n        impt2(impt2),\n        sphereScale(sphereScale),\n        needsScaling(std::abs(sphereScale - 1.) > 1e-6) {\n    // prepare hashmap of parameter indexes, to get continuously increasing indices and parameter availability through\n    // the has() function not all of them may be used in a cost function, depending on the calibration config this\n    // hashmap is used to find\n    hashmap.reserve(INDEX_LAST);\n    int index = 0;\n\n    hashmap[INDEX_HFOCAL_CAM1] = index++;\n    if (!config.hasSingleFocal()) {\n      hashmap[INDEX_HFOCAL_CAM2] = index++;\n    }\n    hashmap[INDEX_VFOCAL_CAM1] = index++;\n    if (!config.hasSingleFocal()) {\n      hashmap[INDEX_VFOCAL_CAM2] = index++;\n    }\n    hashmap[INDEX_HCENTER_CAM1] = index++;\n    hashmap[INDEX_HCENTER_CAM2] = index++;\n    hashmap[INDEX_VCENTER_CAM1] = index++;\n    hashmap[INDEX_VCENTER_CAM2] = index++;\n    hashmap[INDEX_LENSDISTORTA_CAM1] = index++;\n    hashmap[INDEX_LENSDISTORTA_CAM2] = index++;\n    hashmap[INDEX_LENSDISTORTB_CAM1] = index++;\n    hashmap[INDEX_LENSDISTORTB_CAM2] = index++;\n    hashmap[INDEX_LENSDISTORTC_CAM1] = index++;\n    hashmap[INDEX_LENSDISTORTC_CAM2] = index++;\n    hashmap[INDEX_ROTATION_CAM1] = index++;\n    hashmap[INDEX_ROTATION_CAM2] = index++;\n    assert(index <= INDEX_LAST);\n\n    set_num_residuals(2);\n    std::vector<int>* blocks = mutable_parameter_block_sizes();\n\n    // adds the block params if index is in hashmap\n#define CONDITIONAL_ADD_BLOCK(PARAM) \\\n  if (has(INDEX_##PARAM)) blocks->push_back(SIZE_##PARAM)\n\n    CONDITIONAL_ADD_BLOCK(HFOCAL_CAM1);\n    CONDITIONAL_ADD_BLOCK(HFOCAL_CAM2);\n    CONDITIONAL_ADD_BLOCK(VFOCAL_CAM1);\n    CONDITIONAL_ADD_BLOCK(VFOCAL_CAM2);\n    CONDITIONAL_ADD_BLOCK(HCENTER_CAM1);\n    CONDITIONAL_ADD_BLOCK(HCENTER_CAM2);\n    CONDITIONAL_ADD_BLOCK(VCENTER_CAM1);\n    CONDITIONAL_ADD_BLOCK(VCENTER_CAM2);\n    CONDITIONAL_ADD_BLOCK(LENSDISTORTA_CAM1);\n    CONDITIONAL_ADD_BLOCK(LENSDISTORTA_CAM2);\n    CONDITIONAL_ADD_BLOCK(LENSDISTORTB_CAM1);\n    CONDITIONAL_ADD_BLOCK(LENSDISTORTB_CAM2);\n    CONDITIONAL_ADD_BLOCK(LENSDISTORTC_CAM1);\n    CONDITIONAL_ADD_BLOCK(LENSDISTORTC_CAM2);\n    CONDITIONAL_ADD_BLOCK(ROTATION_CAM1);\n    CONDITIONAL_ADD_BLOCK(ROTATION_CAM2);\n\n#undef CONDITIONAL_ADD_BLOCK\n  }\n\n  bool has(char parameter_index) const {\n    assert(parameter_index < INDEX_LAST);\n    return hashmap.find(parameter_index) != hashmap.end();\n  }\n\n  size_t map(char parameter_index) const {\n    assert(parameter_index < INDEX_LAST);\n    return hashmap.at(parameter_index);\n  }\n\n  void resetJacobians(double** jacobians) const {\n    if (jacobians == nullptr) {\n      return;\n    }\n\n#define RESET_JACOBIAN(PARAM, ROWS, COLS)                             \\\n  if (has(INDEX_##PARAM) && jacobians[map(INDEX_##PARAM)] != nullptr) \\\n  Eigen::Map<Eigen::Matrix<double, ROWS, COLS, Eigen::RowMajor> >(jacobians[map(INDEX_##PARAM)]).fill(0)\n\n    RESET_JACOBIAN(HFOCAL_CAM1, 2, 4);\n    RESET_JACOBIAN(HFOCAL_CAM2, 2, 4);\n    RESET_JACOBIAN(VFOCAL_CAM1, 2, 4);\n    RESET_JACOBIAN(VFOCAL_CAM2, 2, 4);\n    RESET_JACOBIAN(HCENTER_CAM1, 2, 4);\n    RESET_JACOBIAN(HCENTER_CAM2, 2, 4);\n    RESET_JACOBIAN(VCENTER_CAM1, 2, 4);\n    RESET_JACOBIAN(VCENTER_CAM2, 2, 4);\n    RESET_JACOBIAN(LENSDISTORTA_CAM1, 2, 4);\n    RESET_JACOBIAN(LENSDISTORTA_CAM2, 2, 4);\n    RESET_JACOBIAN(LENSDISTORTB_CAM1, 2, 4);\n    RESET_JACOBIAN(LENSDISTORTB_CAM2, 2, 4);\n    RESET_JACOBIAN(LENSDISTORTC_CAM1, 2, 4);\n    RESET_JACOBIAN(LENSDISTORTC_CAM2, 2, 4);\n    RESET_JACOBIAN(ROTATION_CAM1, 2, 9);\n    RESET_JACOBIAN(ROTATION_CAM2, 2, 9);\n\n#undef RESET_JACOBIAN\n  }\n\n  virtual bool Evaluate(double const* const* parameters, double* residuals, double** jacobians) const {\n    bool validProj, validLift;\n    Eigen::Vector3d refpt;\n    Eigen::Vector2d estimpt;\n    Eigen::Matrix<double, 3, 4> Jhfocal_lift;\n    Eigen::Matrix<double, 3, 4> Jvfocal_lift;\n    Eigen::Matrix<double, 3, 4> Jhcenter_lift;\n    Eigen::Matrix<double, 3, 4> Jvcenter_lift;\n    Eigen::Matrix<double, 3, 4> JdistortA_lift;\n    Eigen::Matrix<double, 3, 4> JdistortB_lift;\n    Eigen::Matrix<double, 3, 4> JdistortC_lift;\n    Eigen::Matrix<double, 3, 9> Jrotation_lift;\n    Eigen::Matrix<double, 3, 4> JtX_lift;\n    Eigen::Matrix<double, 3, 4> JtY_lift;\n    Eigen::Matrix<double, 3, 4> JtZ_lift;\n    Eigen::Matrix<double, 2, 3> Jpoint_project;\n    Eigen::Matrix<double, 2, 4> Jhfocal_project;\n    Eigen::Matrix<double, 2, 4> Jvfocal_project;\n    Eigen::Matrix<double, 2, 4> Jhcenter_project;\n    Eigen::Matrix<double, 2, 4> Jvcenter_project;\n    Eigen::Matrix<double, 2, 4> JdistortA_project;\n    Eigen::Matrix<double, 2, 4> JdistortB_project;\n    Eigen::Matrix<double, 2, 4> JdistortC_project;\n    Eigen::Matrix<double, 2, 9> Jrotation_project;\n    Eigen::Matrix<double, 2, 4> JtX_project;\n    Eigen::Matrix<double, 2, 4> JtY_project;\n    Eigen::Matrix<double, 2, 4> JtZ_project;\n\n    residuals[0] = 0.0;\n    residuals[1] = 0.0;\n    resetJacobians(jacobians);\n\n    if (has(INDEX_HFOCAL_CAM1)) {\n      camera1->setHorizontalFocal(parameters[map(INDEX_HFOCAL_CAM1)]);\n    }\n    if (has(INDEX_HFOCAL_CAM2)) {\n      camera2->setHorizontalFocal(parameters[map(INDEX_HFOCAL_CAM2)]);\n    } else {\n      camera2->setHorizontalFocal(parameters[map(INDEX_HFOCAL_CAM1)]);\n    }\n    if (has(INDEX_VFOCAL_CAM1)) {\n      camera1->setVerticalFocal(parameters[map(INDEX_VFOCAL_CAM1)]);\n    }\n    if (has(INDEX_VFOCAL_CAM2)) {\n      camera2->setVerticalFocal(parameters[map(INDEX_VFOCAL_CAM2)]);\n    } else {\n      camera2->setVerticalFocal(parameters[map(INDEX_VFOCAL_CAM1)]);\n    }\n    if (has(INDEX_HCENTER_CAM1)) {\n      camera1->setHorizontalCenter(parameters[map(INDEX_HCENTER_CAM1)]);\n    }\n    if (has(INDEX_HCENTER_CAM2)) {\n      camera2->setHorizontalCenter(parameters[map(INDEX_HCENTER_CAM2)]);\n    }\n    if (has(INDEX_VCENTER_CAM1)) {\n      camera1->setVerticalCenter(parameters[map(INDEX_VCENTER_CAM1)]);\n    }\n    if (has(INDEX_VCENTER_CAM2)) {\n      camera2->setVerticalCenter(parameters[map(INDEX_VCENTER_CAM2)]);\n    }\n    if (has(INDEX_LENSDISTORTA_CAM1)) {\n      camera1->setDistortionA(parameters[map(INDEX_LENSDISTORTA_CAM1)]);\n    }\n    if (has(INDEX_LENSDISTORTA_CAM2)) {\n      camera2->setDistortionA(parameters[map(INDEX_LENSDISTORTA_CAM2)]);\n    }\n    if (has(INDEX_LENSDISTORTB_CAM1)) {\n      camera1->setDistortionB(parameters[map(INDEX_LENSDISTORTB_CAM1)]);\n    }\n    if (has(INDEX_LENSDISTORTB_CAM2)) {\n      camera2->setDistortionB(parameters[map(INDEX_LENSDISTORTB_CAM2)]);\n    }\n    if (has(INDEX_LENSDISTORTC_CAM1)) {\n      camera1->setDistortionC(parameters[map(INDEX_LENSDISTORTC_CAM1)]);\n    }\n    if (has(INDEX_LENSDISTORTC_CAM2)) {\n      camera2->setDistortionC(parameters[map(INDEX_LENSDISTORTC_CAM2)]);\n    }\n    if (has(INDEX_ROTATION_CAM1)) {\n      camera1->setRotation(parameters[map(INDEX_ROTATION_CAM1)]);\n    }\n    if (has(INDEX_ROTATION_CAM2)) {\n      camera2->setRotation(parameters[map(INDEX_ROTATION_CAM2)]);\n    }\n\n    validLift =\n        camera1->lift(refpt, Jhfocal_lift, Jvfocal_lift, Jhcenter_lift, Jvcenter_lift, JdistortA_lift, JdistortB_lift,\n                      JdistortC_lift, Jrotation_lift, JtX_lift, JtY_lift, JtZ_lift, impt1, sphereScale);\n    if (!validLift) {\n      return true;\n    }\n\n    assert(std::abs(refpt.norm() - sphereScale) < 1e-6 && (bool)\"lift() failed to put point at sphereScale\");\n\n    validProj = camera2->project(estimpt, Jpoint_project, Jhfocal_project, Jvfocal_project, Jhcenter_project,\n                                 Jvcenter_project, JdistortA_project, JdistortB_project, JdistortC_project,\n                                 Jrotation_project, JtX_project, JtY_project, JtZ_project, refpt);\n    if (!validProj) {\n      return true;\n    }\n\n    residuals[0] = estimpt(0) - impt2(0);\n    residuals[1] = estimpt(1) - impt2(1);\n\n    if (VS_ISNAN(residuals[0])) {\n      residuals[0] = 0;\n      residuals[1] = 0;\n      return true;\n    }\n\n    if (jacobians == nullptr) {\n      return true;\n    }\n\n#define SET_JACOBIAN(PARAM, ROWS, COLS, VALUE)                                                        \\\n  if (has(INDEX_##PARAM) && jacobians[map(INDEX_##PARAM)] != nullptr) {                               \\\n    Eigen::Map<Eigen::Matrix<double, ROWS, COLS, Eigen::RowMajor> > J(jacobians[map(INDEX_##PARAM)]); \\\n    J = (VALUE);                                                                                      \\\n  }\n\n    SET_JACOBIAN(HFOCAL_CAM1, 2, 4, Jpoint_project * Jhfocal_lift);\n    SET_JACOBIAN(HFOCAL_CAM2, 2, 4, Jhfocal_project);\n    SET_JACOBIAN(VFOCAL_CAM1, 2, 4, Jpoint_project * Jvfocal_lift);\n    SET_JACOBIAN(VFOCAL_CAM2, 2, 4, Jvfocal_project);\n    SET_JACOBIAN(HCENTER_CAM1, 2, 4, Jpoint_project * Jhcenter_lift);\n    SET_JACOBIAN(HCENTER_CAM2, 2, 4, Jhcenter_project);\n    SET_JACOBIAN(VCENTER_CAM1, 2, 4, Jpoint_project * Jvcenter_lift);\n    SET_JACOBIAN(VCENTER_CAM2, 2, 4, Jvcenter_project);\n    SET_JACOBIAN(LENSDISTORTA_CAM1, 2, 4, Jpoint_project * JdistortA_lift);\n    SET_JACOBIAN(LENSDISTORTA_CAM2, 2, 4, JdistortA_project);\n    SET_JACOBIAN(LENSDISTORTB_CAM1, 2, 4, Jpoint_project * JdistortB_lift);\n    SET_JACOBIAN(LENSDISTORTB_CAM2, 2, 4, JdistortB_project);\n    SET_JACOBIAN(LENSDISTORTC_CAM1, 2, 4, Jpoint_project * JdistortC_lift);\n    SET_JACOBIAN(LENSDISTORTC_CAM2, 2, 4, JdistortC_project);\n    SET_JACOBIAN(ROTATION_CAM1, 2, 9, Jpoint_project * Jrotation_lift);\n    SET_JACOBIAN(ROTATION_CAM2, 2, 9, Jrotation_project);\n\n#undef SET_JACOBIAN\n\n    return true;\n  }\n\n private:\n  std::shared_ptr<Camera> camera1;\n  std::shared_ptr<Camera> camera2;\n  Eigen::Vector2d impt1;\n  Eigen::Vector2d impt2;\n  double sphereScale;\n  bool needsScaling;\n  std::unordered_map<char, size_t> hashmap;\n};\n\n}  // namespace Calibration\n}  // namespace VideoStitch\n\n#endif\n", "meta": {"hexsha": "48137229ba1a5e7557365acaf8a85ad19ed69551", "size": 11818, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/src/calibration/inputDistance.hpp", "max_stars_repo_name": "tlalexander/stitchEm", "max_stars_repo_head_hexsha": "cdff821ad2c500703e6cb237ec61139fce7bf11c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 182.0, "max_stars_repo_stars_event_min_datetime": "2019-04-19T12:38:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T16:48:20.000Z", "max_issues_repo_path": "lib/src/calibration/inputDistance.hpp", "max_issues_repo_name": "tlalexander/stitchEm", "max_issues_repo_head_hexsha": "cdff821ad2c500703e6cb237ec61139fce7bf11c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 107.0, "max_issues_repo_issues_event_min_datetime": "2019-04-23T10:49:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T18:12:28.000Z", "max_forks_repo_path": "lib/src/calibration/inputDistance.hpp", "max_forks_repo_name": "tlalexander/stitchEm", "max_forks_repo_head_hexsha": "cdff821ad2c500703e6cb237ec61139fce7bf11c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2019-06-04T11:27:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T23:49:49.000Z", "avg_line_length": 35.9209726444, "max_line_length": 120, "alphanum_fraction": 0.7068031816, "num_tokens": 3741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624688140726, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.40355635620947955}}
{"text": "/*\n * $Revision: 223 $ $Date: 2010-03-30 05:44:44 -0700 (Tue, 30 Mar 2010) $\n *\n * Copyright by Astos Solutions GmbH, Germany\n *\n * this file is published under the Astos Solutions Free Public License\n * For details on copyright and terms of use see\n * http://www.astos.de/Astos_Solutions_Free_Public_License.html\n */\n\n#include \"Spectrum.h\"\n#include <Eigen/Array>\n#include <Eigen/LU>\n#include <cmath>\n\nusing namespace vesta;\nusing namespace Eigen;\nusing namespace std;\n\n\nstatic float XYZtoSRGBMatrixValues[9] =\n{\n    3.2410f, -1.5374f, -0.4986f,\n   -0.9692f,  1.8760f,  0.0416f,\n    0.0556f, -0.2040f,  1.0570f\n};\n\nstatic Matrix3f XYZtoSRGB = Matrix3f::Map(XYZtoSRGBMatrixValues).transpose();\nstatic Matrix3f SRGBtoXYZ = XYZtoSRGB.inverse();\n\n\n/** Normalize the spectrum so that the largest component is equal\n  * to 1.0.\n  */\nvoid\nSpectrum::normalize()\n{\n    float maxValue = m_samples.cwise().abs().maxCoeff();\n    if (maxValue > 0.0f)\n    {\n        m_samples /= maxValue;\n    }\n}\n\n\n/** Convert from CIE XYZ color space to linear sRGB. sRGB gamma\n  * correction must be applied in order to convert to the standard\n  * sRGB color space. \\see Spectrum::LinearSRGBtoSRGB\n  */\nSpectrum\nSpectrum::XYZtoLinearSRGB(const Spectrum& xyz)\n{\n    Vector3f srgb = XYZtoSRGB * xyz.m_samples.start<3>();\n    return Spectrum(srgb.x(), srgb.y(), srgb.z());\n}\n\n\n/** Convert from linear sRGB color space to CIE XYZ.\n  */\nSpectrum\nSpectrum::LinearSRGBtoXYZ(const Spectrum& srgb)\n{\n    Vector3f xyz = SRGBtoXYZ * srgb.m_samples.start<3>();\n    return Spectrum(xyz.x(), xyz.y(), xyz.z());\n}\n\n\nstatic float fromLinearSRGB(float x)\n{\n    return x < 0.0031308f ? 12.92f * x : 1.055 * pow(x, 1.0f / 2.4f) - 0.055f;\n}\n\n\nstatic float toLinearSRGB(float x)\n{\n    return x < 0.04045f ? x / 12.92f : pow((x + 0.055f) / 1.055f, 2.4f);\n}\n\n\n/** Apply the inverse sRGB gamma correction step to convert from 'linear sRGB'\n  * color to sRGB color.\n  */\nSpectrum\nSpectrum::LinearSRGBtoSRGB(const Spectrum& srgb)\n{\n    return Spectrum(fromLinearSRGB(srgb.red()),\n                    fromLinearSRGB(srgb.green()),\n                    fromLinearSRGB(srgb.blue()));\n}\n\n\n/** Apply the sRGB gamma correction step to convert from sRGB color space to\n  * a linear color space that uses the sRGB tristimulus values.\n  */\nSpectrum\nSpectrum::SRGBtoLinearSRGB(const Spectrum& srgb)\n{\n    return Spectrum(toLinearSRGB(srgb.red()),\n                    toLinearSRGB(srgb.green()),\n                    toLinearSRGB(srgb.blue()));\n}\n", "meta": {"hexsha": "08039403e267873f15332b5081f0e156dd277e0d", "size": 2480, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "thirdparty/vesta/Spectrum.cpp", "max_stars_repo_name": "hoehnp/SpaceDesignTool", "max_stars_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_stars_repo_licenses": ["IJG"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-09-05T12:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T05:34:23.000Z", "max_issues_repo_path": "thirdparty/vesta/Spectrum.cpp", "max_issues_repo_name": "hoehnp/SpaceDesignTool", "max_issues_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_issues_repo_licenses": ["IJG"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-02-07T19:09:21.000Z", "max_issues_repo_issues_event_max_datetime": "2015-08-14T03:15:42.000Z", "max_forks_repo_path": "thirdparty/vesta/Spectrum.cpp", "max_forks_repo_name": "hoehnp/SpaceDesignTool", "max_forks_repo_head_hexsha": "9abd34048274b2ce9dbbb685124177b02d6a34ca", "max_forks_repo_licenses": ["IJG"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-03-25T15:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T12:16:47.000Z", "avg_line_length": 24.3137254902, "max_line_length": 78, "alphanum_fraction": 0.6701612903, "num_tokens": 759, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.40354177249318735}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2021 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n/*! \\file PID.hpp\n  \\brief Proportional-Integral-Derivative Controller\n*/\n\n#ifndef PID_H\n#define PID_H\n\n#include \"Actuator.hpp\"\n#include \"SiconosAlgebraTypeDef.hpp\"\n#include <boost/circular_buffer.hpp>\n\nclass PID : public Actuator\n{\nprivate:\n  /** default constructor */\n  PID() {};\n\n  /** serialization hooks\n   */\n  ACCEPT_SERIALIZATION(PID);\n\n  /** error vector */\n  std::shared_ptr<boost::circular_buffer<double> > _err;\n\n  /** reference we are tracking */\n  double _ref;\n\n  double _curDeltaT;\n\n  /** vector of gains */\n  SP::SiconosVector _K;\n\npublic:\n\n  /** Constructor.\n   * \\param sensor the ControlSensor feeding the Actuator\n   * \\param B the B matrix\n   */\n  PID(SP::ControlSensor sensor, SP::SimpleMatrix B = std::shared_ptr<SimpleMatrix>());\n\n  /** destructor\n   */\n  virtual ~PID();\n\n  /** initialize actuator data.\n   * \\param nsds a NonSmoothDynamicalSystem\n   * \\param s the simulation\n   */\n  virtual void initialize(const NonSmoothDynamicalSystem& nsds, const Simulation& s);\n\n  /** Compute the new control law at each event\n   * Here we are using the following formula:\n   * \\f$ u_k = u_{k-1} + c_1 e_k + c_2 e_{k-1} + c_3 e_{k-2} \\f$ , where\n   * \\f{array} c_1 &= K_P - \\frac{K_D}{\\Delta t} + K_I \\Delta t \\\\\n   * c_2 &= -1 - \\frac{2K_D}{\\Delta t} \\\\\n   * c_3 &= \\frac{K_D}{\\Delta t} \\\\\n   * \\f}\n   */\n  void actuate();\n\n  /** Set K\n   * \\param K SP::SiconosVector \\f$ [K_P, K_I, K_D] \\f$\n   */\n  void setK(SP::SiconosVector K);\n\n  /** Set the value of _ref to reference\n   * \\param reference the new value\n   */\n  void inline setRef(double reference)\n  {\n    _ref = reference;\n  }\n\n  /** Get the timestep from the TimeDiscretisation associated with this PID controller\n  *  \\param td the TimeDiscretisation for this Actuator\n  */\n  virtual void setTimeDiscretisation(const TimeDiscretisation& td);\n\n  void setDeltaT(double deltaT)\n  {\n    _curDeltaT = deltaT;\n  }\n/** display the data of the Actuator on the standard output\n   */\n  virtual void display() const;\n\n};\n#endif\n", "meta": {"hexsha": "d50dd658547aa6237c91d4bdbfcdaa0db4d0823e", "size": 2687, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "control/src/Controller/PID.hpp", "max_stars_repo_name": "BuildJet/siconos", "max_stars_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "control/src/Controller/PID.hpp", "max_issues_repo_name": "BuildJet/siconos", "max_issues_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "control/src/Controller/PID.hpp", "max_forks_repo_name": "BuildJet/siconos", "max_forks_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 25.1121495327, "max_line_length": 86, "alphanum_fraction": 0.6795682918, "num_tokens": 739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102955, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.40352566729012046}}
{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2008, Willow Garage, Inc.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the Willow Garage nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n// Original version: Melonee Wise <mwise@willowgarage.com>\n#include <cstdio>\n#include \"youbot_driver/generic/PidController.hpp\"\n#include <boost/math/special_functions/fpclassify.hpp>\n\nnamespace youbot {\n\nPidController::PidController(double P, double I, double D, double I1, double I2) :\n  p_gain_(P), i_gain_(I), d_gain_(D), i_max_(I1), i_min_(I2)\n{\n  p_error_last_ = 0.0;\n  p_error_ = 0.0;\n  d_error_ = 0.0;\n  i_error_ = 0.0;\n  cmd_ = 0.0;\n  last_i_error = 0.0;\n}\n\nPidController::~PidController()\n{\n}\n\nvoid PidController::initPid(double P, double I, double D, double I1, double I2)\n{\n  p_gain_ = P;\n  i_gain_ = I;\n  d_gain_ = D;\n  i_max_ = I1;\n  i_min_ = I2;\n\n  reset();\n}\n\nvoid PidController::reset()\n{\n  p_error_last_ = 0.0;\n  p_error_ = 0.0;\n  d_error_ = 0.0;\n  i_error_ = 0.0;\n  cmd_ = 0.0;\n}\n\nvoid PidController::getGains(double &p, double &i, double &d, double &i_max, double &i_min)\n{\n  p = p_gain_;\n  i = i_gain_;\n  d = d_gain_;\n  i_max = i_max_;\n  i_min = i_min_;\n}\n\nvoid PidController::setGains(double P, double I, double D, double I1, double I2)\n{\n  p_gain_ = P;\n  i_gain_ = I;\n  d_gain_ = D;\n  i_max_ = I1;\n  i_min_ = I2;\n}\n\n\ndouble PidController::updatePid(double error, boost::posix_time::time_duration dt)\n{\n  double p_term, d_term, i_term;\n  p_error_ = error; //this is pError = pState-pTarget\n  double deltatime = (double)dt.total_microseconds()/1000.0; //in milli seconds\n  \n\n  if (deltatime == 0.0 || boost::math::isnan(error) || boost::math::isinf(error))\n    return 0.0;\n\n  // Calculate proportional contribution to command\n  p_term = p_gain_ * p_error_;\n\n  // Calculate the integral error\n  \n  i_error_ = last_i_error + deltatime * p_error_;\n  last_i_error = deltatime * p_error_;\n\n  //Calculate integral contribution to command\n  i_term = i_gain_ * i_error_;\n\n  // Limit i_term so that the limit is meaningful in the output\n  if (i_term > i_max_)\n  {\n    i_term = i_max_;\n    i_error_=i_term/i_gain_;\n  }\n  else if (i_term < i_min_)\n  {\n    i_term = i_min_;\n    i_error_=i_term/i_gain_;\n  }\n\n  // Calculate the derivative error\n  if (deltatime != 0)\n  {\n    d_error_ = (p_error_ - p_error_last_) / deltatime;\n    p_error_last_ = p_error_;\n  }\n  // Calculate derivative contribution to command\n  d_term = d_gain_ * d_error_;\n  cmd_ = -p_term - i_term - d_term;\n  \n // printf(\" p_error_ %lf  i_error_ %lf  p_term %lf i_term %lf  dt %lf out %lf\\n\", p_error_, i_error_, p_term, i_term, deltatime, cmd_);\n\n  return cmd_;\n}\n\n\ndouble PidController::updatePid(double error, double error_dot, boost::posix_time::time_duration dt)\n{\n  double p_term, d_term, i_term;\n  p_error_ = error; //this is pError = pState-pTarget\n  d_error_ = error_dot;\n  double deltatime = (double)dt.total_microseconds()/1000.0;  //in milli seconds\n\n  if (deltatime == 0.0 || boost::math::isnan(error) || boost::math::isinf(error) || boost::math::isnan(error_dot) || boost::math::isinf(error_dot))\n    return 0.0;\n\n\n  // Calculate proportional contribution to command\n  p_term = p_gain_ * p_error_;\n\n  // Calculate the integral error\n  i_error_ = last_i_error + deltatime * p_error_;\n  last_i_error = deltatime * p_error_;\n  \n // i_error_ = i_error_ + deltatime * p_error_;\n //   printf(\"i_error_ %lf dt.fractional_seconds() %lf\\n\", i_error_, deltatime);\n\n  //Calculate integral contribution to command\n  i_term = i_gain_ * i_error_;\n\n  // Limit i_term so that the limit is meaningful in the output\n  if (i_term > i_max_)\n  {\n    i_term = i_max_;\n    i_error_=i_term/i_gain_;\n  }\n  else if (i_term < i_min_)\n  {\n    i_term = i_min_;\n    i_error_=i_term/i_gain_;\n  }\n\n  // Calculate derivative contribution to command\n  d_term = d_gain_ * d_error_;\n  cmd_ = -p_term - i_term - d_term;\n\n  return cmd_;\n}\n\n\n\nvoid PidController::setCurrentCmd(double cmd)\n{\n  cmd_ = cmd;\n}\n\ndouble PidController::getCurrentCmd()\n{\n  return cmd_;\n}\n\nvoid PidController::getCurrentPIDErrors(double& pe, double& ie, double& de)\n{\n  pe = p_error_;\n  ie = i_error_;\n  de = d_error_;\n}\n\n}\n", "meta": {"hexsha": "28a0a9e3644cfea12a48eb42dc50521a86cbc917", "size": 5755, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "youbot/youbot_driver/src/generic/PidController.cpp", "max_stars_repo_name": "MrJaeqx/ESA--WORK", "max_stars_repo_head_hexsha": "50d5b397f634db98e2627a764c7731e76a4b3feb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-03-09T13:44:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-18T16:17:03.000Z", "max_issues_repo_path": "youbot/youbot_driver/src/generic/PidController.cpp", "max_issues_repo_name": "MrJaeqx/ESA--WORK", "max_issues_repo_head_hexsha": "50d5b397f634db98e2627a764c7731e76a4b3feb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2017-11-19T16:26:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-19T12:36:10.000Z", "max_forks_repo_path": "youbot/youbot_driver/src/generic/PidController.cpp", "max_forks_repo_name": "FontysAtWork/ESA-PROJ", "max_forks_repo_head_hexsha": "50d5b397f634db98e2627a764c7731e76a4b3feb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-11-19T12:45:37.000Z", "max_forks_repo_forks_event_max_datetime": "2017-11-19T12:45:37.000Z", "avg_line_length": 27.6682692308, "max_line_length": 147, "alphanum_fraction": 0.683753258, "num_tokens": 1618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.600188359260205, "lm_q1q2_score": 0.40352565940904145}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_VON_MISES_RNG_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_VON_MISES_RNG_HPP\n\n#include <stan/math/prim/meta.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_finite.hpp>\n#include <stan/math/prim/scal/err/check_greater.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <boost/random/uniform_real_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n\nnamespace stan {\nnamespace math {\n\n/** \\ingroup prob_dists\n * Return a von Mises random variate for the given location and concentration\n * using the specified random number generator.\n *\n * mu and kappa can each be a scalar or a vector. Any non-scalar\n * inputs must be the same length.\n *\n * The algorithm used in von_mises_rng is a modified version of the\n * algorithm in:\n *\n * Efficient Simulation of the von Mises Distribution\n * D. J. Best and N. I. Fisher\n * Journal of the Royal Statistical Society. Series C (Applied Statistics),\n * Vol. 28, No. 2 (1979), pp. 152-157\n *\n * See licenses/stan-license.txt for Stan license.\n *\n * @tparam T_loc Type of location parameter\n * @tparam T_conc Type of concentration parameter\n * @tparam RNG type of random number generator\n * @param mu (Sequence of) location parameter(s)\n * @param kappa (Sequence of) positive concentration parameter(s)\n * @param rng random number generator\n * @return (Sequence of) von Mises random variate(s)\n * @throw std::domain_error if mu is infinite or kappa is nonpositive\n * @throw std::invalid_argument if non-scalar arguments are of different\n * sizes\n */\ntemplate <typename T_loc, typename T_conc, class RNG>\ninline typename VectorBuilder<true, double, T_loc, T_conc>::type von_mises_rng(\n    const T_loc& mu, const T_conc& kappa, RNG& rng) {\n  using boost::random::uniform_real_distribution;\n  using boost::variate_generator;\n  static const char* function = \"von_mises_rng\";\n\n  check_finite(function, \"mean\", mu);\n  check_positive_finite(function, \"inverse of variance\", kappa);\n  check_consistent_sizes(function, \"Location parameter\", mu,\n                         \"Concentration Parameter\", kappa);\n\n  scalar_seq_view<T_loc> mu_vec(mu);\n  scalar_seq_view<T_conc> kappa_vec(kappa);\n  size_t N = max_size(mu, kappa);\n  VectorBuilder<true, double, T_loc, T_conc> output(N);\n\n  variate_generator<RNG&, uniform_real_distribution<> > uniform_rng(\n      rng, uniform_real_distribution<>(0.0, 1.0));\n\n  for (size_t n = 0; n < N; ++n) {\n    double r = 1 + std::pow((1 + 4 * kappa_vec[n] * kappa_vec[n]), 0.5);\n    double rho = 0.5 * (r - std::pow(2 * r, 0.5)) / kappa_vec[n];\n    double s = 0.5 * (1 + rho * rho) / rho;\n\n    bool done = false;\n    double W;\n    while (!done) {\n      double Z = std::cos(pi() * uniform_rng());\n      W = (1 + s * Z) / (s + Z);\n      double Y = kappa_vec[n] * (s - W);\n      double U2 = uniform_rng();\n      done = Y * (2 - Y) - U2 > 0;\n\n      if (!done) {\n        done = std::log(Y / U2) + 1 - Y >= 0;\n      }\n    }\n\n    double U3 = uniform_rng() - 0.5;\n    double sign = ((U3 >= 0) - (U3 <= 0));\n\n    //  it's really an fmod() with a positivity constraint\n    output[n]\n        = sign * std::acos(W)\n          + std::fmod(std::fmod(mu_vec[n], 2 * pi()) + 2 * stan::math::pi(),\n                      2 * pi());\n  }\n\n  return output.data();\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "4f7ce3adfdba3444f5836c2782d92e26f670d970", "size": 3474, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/prob/von_mises_rng.hpp", "max_stars_repo_name": "StrayDoki/math", "max_stars_repo_head_hexsha": "2f2f99759b822e3c8467d3efc56e781125067eb6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/scal/prob/von_mises_rng.hpp", "max_issues_repo_name": "StrayDoki/math", "max_issues_repo_head_hexsha": "2f2f99759b822e3c8467d3efc56e781125067eb6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/scal/prob/von_mises_rng.hpp", "max_forks_repo_name": "StrayDoki/math", "max_forks_repo_head_hexsha": "2f2f99759b822e3c8467d3efc56e781125067eb6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.74, "max_line_length": 79, "alphanum_fraction": 0.6741508348, "num_tokens": 973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.6334102567576902, "lm_q1q2_score": 0.403501839094375}}
{"text": "#ifndef I_SEE_PEE_ITERATOR_HPP\n#define I_SEE_PEE_ITERATOR_HPP\n\n#include <Eigen/Dense>\n#include <cmath>\n\nnamespace i_see_pee {\n\ntemplate<typename T>\nstruct centered_submap_iterator {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  using data_t = Eigen::Matrix<T, 2ul, 1ul>;\n  using bound_t = Eigen::Matrix<size_t, 2ul, 1ul>;\n\n  explicit centered_submap_iterator(const bound_t &_dim) noexcept :\n          size_(_dim.cast<T>()), curr_(data_t::Zero()), prod_(size_.prod()) {}\n\n  centered_submap_iterator &operator++() noexcept {\n    ++curr_(1);\n    if (curr_(1) >= size_(1)) {\n      curr_(1) = 0;\n      ++curr_(0);\n    }\n    return *this;\n  }\n\n  inline const data_t &operator*() const noexcept {\n    return curr_;\n  }\n\n  inline const data_t *operator->() const noexcept {\n    return &curr_;\n  }\n\n  inline bool past_end() const noexcept {\n    return curr_(0) >= size_(0) || !prod_;\n  }\n\nprivate:\n  data_t size_, curr_;\n  size_t prod_;\n};\n\ntemplate<typename T>\nstruct submap_iterator {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  using centered_submap_iterator_t = centered_submap_iterator<T>;\n  using data_t = typename centered_submap_iterator_t::data_t;\n  using bound_t = typename centered_submap_iterator_t::bound_t;\n\n  submap_iterator() noexcept :\n          iter_(bound_t::Zero()), begin_(data_t::Zero()), curr_(data_t::Zero()) {}\n\n  submap_iterator(const data_t &_begin, const bound_t &_size) noexcept :\n          iter_(_size), begin_(_begin), curr_(_begin) {}\n\n  submap_iterator &operator++() noexcept {\n    ++iter_;\n    curr_ = begin_ + *iter_;\n    return *this;\n  }\n\n  inline const data_t &operator*() const noexcept {\n    return curr_;\n  }\n\n  inline const data_t *operator->() const noexcept {\n    return &curr_;\n  }\n\n  inline bool past_end() const noexcept {\n    return iter_.past_end();\n  }\n\nprivate:\n  data_t begin_, curr_;\n  centered_submap_iterator_t iter_;\n};\n\ntemplate<typename T>\nstruct circle_iterator {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n  using submap_iterator_t = submap_iterator<T>;\n  using data_t = typename submap_iterator_t::data_t;\n  using bound_t = typename submap_iterator_t::bound_t;\n\n  circle_iterator(const data_t &_center, T _radius) noexcept :\n          center_(_center), radius_(_radius) {\n    // get the positive radius\n    _radius = std::abs(_radius);\n\n    // get the submap parameters with 1 pixel at the center\n    const data_t rad(_radius, _radius);\n    const data_t begin = _center - rad;\n    const bound_t size = rad.template cast<size_t>() * 2 + bound_t::Ones();\n    iter_ = submap_iterator_t(begin, size);\n\n    // advance till valid position to allow instant access\n    while (!valid(*iter_)) {\n      ++iter_;\n    }\n  }\n\n  circle_iterator &operator++() noexcept {\n    do {\n      ++iter_;\n    } while (!iter_.past_end() && !valid(*iter_));\n    return *this;\n  }\n\n  inline const data_t &operator*() const noexcept {\n    return *iter_;\n  }\n\n  inline const data_t *operator->() const noexcept {\n    return iter_.operator->();\n  }\n\n  bool past_end() const noexcept {\n    return iter_.past_end();\n  }\n\nprivate:\n\n  bool valid(const data_t &_d) const noexcept {\n    return (center_ - _d).norm() <= radius_;\n  }\n\n  const data_t center_;\n  const T radius_;\n  submap_iterator_t iter_;\n};\n\n} // namespace i_see_pee\n\n#endif //I_SEE_PEE_ITERATOR_HPP\n", "meta": {"hexsha": "c0cd0e90e3294dc3080f21ed26ff4085a775982b", "size": 3258, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/i_see_pee/iterator.hpp", "max_stars_repo_name": "dorezyuk/i_see_pee", "max_stars_repo_head_hexsha": "4fb06db0646eed945ebb949d0c234fc27fcbc318", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2019-03-09T13:27:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T10:19:49.000Z", "max_issues_repo_path": "include/i_see_pee/iterator.hpp", "max_issues_repo_name": "dorezyuk/i_see_pee", "max_issues_repo_head_hexsha": "4fb06db0646eed945ebb949d0c234fc27fcbc318", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/i_see_pee/iterator.hpp", "max_forks_repo_name": "dorezyuk/i_see_pee", "max_forks_repo_head_hexsha": "4fb06db0646eed945ebb949d0c234fc27fcbc318", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-06-25T15:08:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T08:52:25.000Z", "avg_line_length": 23.2714285714, "max_line_length": 82, "alphanum_fraction": 0.678330264, "num_tokens": 860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4034386251041442}}
{"text": "//| Copyright Inria May 2015\n//| This project has received funding from the European Research Council (ERC) under\n//| the European Union's Horizon 2020 research and innovation programme (grant\n//| agreement No 637972) - see http://www.resibots.eu\n//|\n//| Contributor(s):\n//|   - Jean-Baptiste Mouret (jean-baptiste.mouret@inria.fr)\n//|   - Antoine Cully (antoinecully@gmail.com)\n//|   - Konstantinos Chatzilygeroudis (konstantinos.chatzilygeroudis@inria.fr)\n//|   - Federico Allocati (fede.allocati@gmail.com)\n//|   - Vaios Papaspyros (b.papaspyros@gmail.com)\n//|   - Roberto Rama (bertoski@gmail.com)\n//|\n//| This software is a computer library whose purpose is to optimize continuous,\n//| black-box functions. It mainly implements Gaussian processes and Bayesian\n//| optimization.\n//| Main repository: http://github.com/resibots/limbo\n//| Documentation: http://www.resibots.eu/limbo\n//|\n//| This software is governed by the CeCILL-C license under French law and\n//| abiding by the rules of distribution of free software.  You can  use,\n//| modify and/ or redistribute the software under the terms of the CeCILL-C\n//| license as circulated by CEA, CNRS and INRIA at the following URL\n//| \"http://www.cecill.info\".\n//|\n//| As a counterpart to the access to the source code and  rights to copy,\n//| modify and redistribute granted by the license, users are provided only\n//| with a limited warranty  and the software's author,  the holder of the\n//| economic rights,  and the successive licensors  have only  limited\n//| liability.\n//|\n//| In this respect, the user's attention is drawn to the risks associated\n//| with loading,  using,  modifying and/or developing or reproducing the\n//| software by the user in light of its specific status of free software,\n//| that may mean  that it is complicated to manipulate,  and  that  also\n//| therefore means  that it is reserved for developers  and  experienced\n//| professionals having in-depth computer knowledge. Users are therefore\n//| encouraged to load and test the software's suitability as regards their\n//| requirements in conditions enabling the security of their systems and/or\n//| data to be ensured and,  more generally, to use and operate it in the\n//| same conditions as regards security.\n//|\n//| The fact that you are presently reading this means that you have had\n//| knowledge of the CeCILL-C license and that you accept its terms.\n//|\n#ifndef LIMBO_ACQUI_EI_HPP\n#define LIMBO_ACQUI_EI_HPP\n\n#include <Eigen/Core>\n#include <cmath>\n#include <vector>\n\n#include <limbo/opt/optimizer.hpp>\n#include <limbo/tools/macros.hpp>\n\nnamespace limbo {\n    namespace defaults {\n        struct acqui_ei {\n            /// @ingroup acqui_defaults\n            BO_PARAM(double, jitter, 0.0);\n        };\n    }\n    namespace acqui {\n        /** @ingroup acqui\n        \\rst\n        Classic EI (Expected Improvement). See :cite:`brochu2010tutorial`, p. 14\n\n          .. math::\n            EI(x) = (\\mu(x) - f(x^+) - \\xi)\\Phi(Z) + \\sigma(x)\\phi(Z),\\\\\\text{with } Z = \\frac{\\mu(x)-f(x^+) - \\xi}{\\sigma(x)}.\n\n        Parameters:\n          - ``double jitter`` - :math:`\\xi`\n        \\endrst\n        */\n        template <typename Params, typename Model>\n        class EI {\n        public:\n            EI(const Model& model, int iteration = 0) : _model(model), _nb_samples(-1) {}\n\n            size_t dim_in() const { return _model.dim_in(); }\n\n            size_t dim_out() const { return _model.dim_out(); }\n\n            template <typename AggregatorFunction>\n            opt::eval_t operator()(const Eigen::VectorXd& v, const AggregatorFunction& afun, bool gradient)\n            {\n                assert(!gradient);\n\n                Eigen::VectorXd mu;\n                double sigma_sq;\n                std::tie(mu, sigma_sq) = _model.query(v);\n                double sigma = std::sqrt(sigma_sq);\n\n                // If \\sigma(x) = 0 or we do not have any observation yet we return 0\n                if (sigma < 1e-10 || _model.samples().size() < 1)\n                    return opt::no_grad(0.0);\n\n                // Compute EI(x)\n                // First find the best so far (predicted) observation -- if needed\n                if (_nb_samples != _model.nb_samples()) {\n                    std::vector<double> rewards;\n                    for (auto s : _model.samples()) {\n                        rewards.push_back(afun(_model.mu(s)));\n                    }\n\n                    _nb_samples = _model.nb_samples();\n                    _f_max = *std::max_element(rewards.begin(), rewards.end());\n                }\n                // Calculate Z and \\Phi(Z) and \\phi(Z)\n                double X = afun(mu) - _f_max - Params::acqui_ei::jitter();\n                double Z = X / sigma;\n                double phi = std::exp(-0.5 * std::pow(Z, 2.0)) / std::sqrt(2.0 * M_PI);\n                double Phi = 0.5 * std::erfc(-Z / std::sqrt(2)); //0.5 * (1.0 + std::erf(Z / std::sqrt(2)));\n\n                return opt::no_grad(X * Phi + sigma * phi);\n            }\n\n        protected:\n            const Model& _model;\n            int _nb_samples;\n            double _f_max;\n        };\n    }\n}\n\n#endif\n", "meta": {"hexsha": "c868d6d3e8861e77a64c620941a845e2ea03240b", "size": 5120, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "limbo/src/limbo/acqui/ei.hpp", "max_stars_repo_name": "yjjuan/automl_cplusplus", "max_stars_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-08T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T17:52:18.000Z", "max_issues_repo_path": "limbo/src/limbo/acqui/ei.hpp", "max_issues_repo_name": "yjjuan/automl_cplusplus", "max_issues_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "limbo/src/limbo/acqui/ei.hpp", "max_forks_repo_name": "yjjuan/automl_cplusplus", "max_forks_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.3149606299, "max_line_length": 127, "alphanum_fraction": 0.6109375, "num_tokens": 1286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.40343862510414413}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_SEC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_SEC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-trigonometric\n    Function object implementing sec capabilities\n\n    secant of the angle in radian: \\f$1/\\cos(x)\\f$.\n\n    @par Semantic:\n\n    For every parameter of floating type\n\n    @code\n    auto r = sec(x);\n    @endcode\n\n    @see cos, secd, secpi, rec\n\n  **/\n  Value sec(Value const & v0);\n} }\n#endif\n\n#include <boost/simd/function/scalar/sec.hpp>\n#include <boost/simd/function/simd/sec.hpp>\n\n#endif\n", "meta": {"hexsha": "33c14058ab842ea335dd427cb652fbbd450c1af2", "size": 974, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/sec.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/function/sec.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/sec.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 22.1363636364, "max_line_length": 100, "alphanum_fraction": 0.5616016427, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.40331350451104087}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef LA_ALGEBRAIC_CONCEPTS_DOC_INCLUDE\n#define LA_ALGEBRAIC_CONCEPTS_DOC_INCLUDE\n\n#ifdef __GXX_CONCEPTS__\n#  include <concepts>\n#else \n#  include <boost/numeric/linear_algebra/pseudo_concept.hpp>\n#endif\n\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/linear_algebra/inverse.hpp>\n\n/// Namespace for purely algebraic concepts\nnamespace algebra {\n\n/** @addtogroup Concepts\n *  @{\n */\n\n#ifndef __GXX_CONCEPTS__\n    //! Concept Commutative\n    /*!\n        \\param Operation A functor implementing a binary operation\n        \\param Element The type upon the binary operation is defined   \n\n        \\par Notation:\n        <table summary=\"notation\">\n          <tr>\n            <td>op</td>\n    \t<td>Object of type Operation</td>\n          </tr>\n          <tr>\n            <td>x, y</td>\n    \t<td>Objects of type Element</td>\n          </tr>\n        </table>\n        \\invariant\n        <table summary=\"invariants\">\n          <tr>\n            <td>Commutativity</td>\n    \t<td>op(x, y) == op(y, x)</td>\n          </tr>\n        </table>\n     */\n    template <typename Operation, typename Element>\n    struct Commutative \n    {};\n#else \n    concept Commutative<typename Operation, typename Element>\n    {\n\taxiom Commutativity(Operation op, Element x, Element y)\n\t{\n\t    op(x, y) == op(y, x); \n\t}   \n    };\n#endif\n\n\n#ifndef __GXX_CONCEPTS__\n    //! Concept Associative\n    /*!\n        \\param Operation A functor implementing a binary operation\n        \\param Element The type upon the binary operation is defined   \n\n        \\par Notation:\n        <table summary=\"notation\">\n          <tr>\n            <td>op</td>\n    \t<td>Object of type Operation</td>\n          </tr>\n          <tr>\n            <td>x, y, z</td>\n    \t<td>Objects of type Element</td>\n          </tr>\n        </table>\n        \\invariant\n        <table summary=\"invariants\">\n          <tr>\n            <td>Associativity</td>\n    \t<td>op(x, op(y, z)) == op(op(x, y), z)</td>\n          </tr>\n        </table>\n     */\n    template <typename Operation, typename Element>\n    struct Associative\n    {};\n#else\n    concept Associative<typename Operation, typename Element>\n    {\n        axiom Associativity(Operation op, Element x, Element y, Element z)\n        {\n\t    op(x, op(y, z)) == op(op(x, y), z); \n        }\n    };\n#endif\n\n\n#ifndef __GXX_CONCEPTS__\n    //! Concept SemiGroup\n    /*!\n        \\param Operation A functor implementing a binary operation\n        \\param Element The type upon the binary operation is defined   \n\n        \\note\n        -# The algebraic concept SemiGroup only requires associativity and is identical with the concept Associative.\n     */\n    template <typename Operation, typename Element>\n    struct SemiGroup\n        : Associative<Operation, Element>\n    {};\n#else\n    auto concept SemiGroup<typename Operation, typename Element>\n      : Associative<Operation, Element>\n    {};\n#endif\n\n\n#ifndef __GXX_CONCEPTS__\n    //! Concept Monoid\n    /*!\n        \\param Operation A functor implementing a binary operation\n        \\param Element The type upon the binary operation is defined   \n\n        \\par Refinement of:\n\t- SemiGroup\n        \\par Notation:\n        <table summary=\"notation\">\n          <tr>\n            <td>op</td>\n    \t<td>Object of type Operation</td>\n          </tr>\n          <tr>\n            <td>x</td>\n    \t<td>Object of type Element</td>\n          </tr>\n        </table>\n        \\invariant\n        <table summary=\"invariants\">\n          <tr>\n            <td>Neutrality from right</td>\n\t    <td>op( x, identity(op, x) ) == x</td>\n          </tr>\n          <tr>\n            <td>Neutrality from left</td>\n\t    <td>op( identity(op, x), x ) == x</td>\n          </tr>\n        </table>\n     */\n    template <typename Operation, typename Element>\n    struct Monoid\n      : SemiGroup<Operation, Element> \n    {\n\t/// Associated type; if not defined in concept_map automatically detected as result of identity\n        typedef associated_type identity_result_type; \n        identity_result_type identity(Operation, Element); ///< Identity element of Operation\n    };\n#else\n    concept Monoid<typename Operation, typename Element>\n      : SemiGroup<Operation, Element> \n    {\n        typename identity_result_type;\n        identity_result_type identity(Operation, Element);\n\n        axiom Neutrality(Operation op, Element x)\n        {\n\t    op( x, identity(op, x) ) == x;\n\t    op( identity(op, x), x ) == x;\n        }\n    };\n#endif\n\n#ifdef __GXX_CONCEPTS__\n    auto concept Inversion<typename Operation, typename Element>\n    {\n        typename inverse_result_type;\n        inverse_result_type inverse(Operation, Element);\n     \n    };\n#else\n    //! Concept Inversion\n    /*!\n        \\param Operation A functor implementing a binary operation\n        \\param Element The type upon the binary operation is defined  \n\n\t\\par Associated Types:\n\t- inverse_result_type\n\t\\par Valid Expressions:\n\t- inverse(op, x);\n     */\n    template <typename Operation, typename Element>\n    struct Inversion\n    {\n\t/// Associated type; if not defined in concept_map automatically detected as result of inverse\n        typedef associated_type inverse_result_type;\n\n\t/// Returns inverse of \\p x regarding operation \\p op\n        inverse_result_type inverse(Operation op, Element x);\n    };\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    concept Group<typename Operation, typename Element>\n      : Monoid<Operation, Element>, Inversion<Operation, Element>\n    {\n        axiom Inversion(Operation op, Element x)\n        {\n\t    op( x, inverse(op, x) ) == identity(op, x);\n\t    op( inverse(op, x), x ) == identity(op, x);\n        }\n    };\n#else\n    //! Concept Group\n    /*!\n        \\param Operation A functor implementing a binary operation\n        \\param Element The type upon the binary operation is defined   \n\n        \\par Refinement of:\n\t- Monoid\n\t- Inversion\n        \\par Notation:\n        <table summary=\"notation\">\n          <tr>\n            <td>op</td>\n    \t<td>Object of type Operation</td>\n          </tr>\n          <tr>\n            <td>x</td>\n    \t<td>Object of type Element</td>\n          </tr>\n        </table>\n        \\invariant\n        <table summary=\"invariants\">\n          <tr>\n            <td>Inverse from right</td>\n    \t<td>op( x, inverse(op, x) ) == identity(op, x)</td>\n          </tr>\n          <tr>\n            <td>Inverse from left</td>\n    \t<td>op( inverse(op, x), x ) == identity(op, x)</td>\n          </tr>\n        </table>\n     */\n    template <typename Operation, typename Element>\n    struct Group\n      : Monoid<Operation, Element>,\n\tInversion<Operation, Element>\n    {};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    auto concept AbelianGroup<typename Operation, typename Element>\n      : Group<Operation, Element>, Commutative<Operation, Element>\n    {};\n#else\n    //! Concept AbelianGroup\n    /*!\n        \\param Operation A functor implementing a binary operation\n        \\param Element The type upon the binary operation is defined   \n\n        \\par Refinement of:\n\t- Group\n\t- Commutative\n     */\n    template <typename Operation, typename Element>\n    struct AbelianGroup\n      : Group<Operation, Element>,\n\tCommutative<Operation, Element>\n    {};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    concept Distributive<typename AddOp, typename MultOp, typename Element>\n    {\n        axiom Distributivity(AddOp add, MultOp mult, Element x, Element y, Element z)\n        {\n\t    // From left\n\t    mult(x, add(y, z)) == add(mult(x, y), mult(x, z));\n\t    // z right\n\t    mult(add(x, y), z) == add(mult(x, z), mult(y, z));\n        }\n    };\n#else\n    //! Concept Distributive\n    /*!\n        \\param AddOp A functor implementing a binary operation representing addition\n        \\param MultOp A functor implementing a binary operation representing multiplication\n        \\param Element The type upon the binary operation is defined   \n\n        \\par Notation:\n        <table summary=\"notation\">\n          <tr>\n            <td>add</td>\n\t    <td>Object of type AddOp</td>\n          </tr>\n          <tr>\n            <td>mult</td>\n\t    <td>Object of type Multop</td>\n          </tr>\n          <tr>\n            <td>x, y, z</td>\n\t    <td>Objects of type Element</td>\n          </tr>\n        </table>\n        \\invariant\n        <table summary=\"invariants\">\n          <tr>\n            <td>Distributivity from left</td>\n\t    <td>mult(x, add(y, z)) == add(mult(x, y), mult(x, z))</td>\n          </tr>\n          <tr>\n            <td>Distributivity from right</td>\n\t    <td>mult(add(x, y), z) == add(mult(x, z), mult(y, z))</td>\n          </tr>\n        </table>\n     */    \n    template <typename AddOp, typename MultOp, typename Element>\n    struct Distributive\n    {};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    auto concept Ring<typename AddOp, typename MultOp, typename Element>\n      : AbelianGroup<AddOp, Element>,\n        SemiGroup<MultOp, Element>,\n        Distributive<AddOp, MultOp, Element>\n    {};\n#else\n    //! Concept Ring\n    /*!\n        \\param AddOp A functor implementing a binary operation representing addition\n        \\param MultOp A functor implementing a binary operation representing multiplication\n        \\param Element The type upon the binary operation is defined   \n\n        \\par Refinement of:\n\t- AbelianGroup <MultOp, Element>\n\t- SemiGroup <MultOp, Element>\n        - Distributive <AddOp, MultOp, Element>\n     */\n    template <typename AddOp, typename MultOp, typename Element>\n    struct Ring\n      : AbelianGroup<AddOp, Element>,\n        SemiGroup<MultOp, Element>,\n        Distributive<AddOp, MultOp, Element>\n    {};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    auto concept RingWithIdentity<typename AddOp, typename MultOp, typename Element>\n      : Ring<AddOp, MultOp, Element>,\n        Monoid<MultOp, Element>\n    {};\n#else\n    //! Concept RingWithIdentity\n    /*!\n        \\param AddOp A functor implementing a binary operation representing addition\n        \\param MultOp A functor implementing a binary operation representing multiplication\n        \\param Element The type upon the binary operation is defined   \n\n        \\par Refinement of:\n\t- Ring <AddOp, MultOp, Element>\n        - Monoid <MultOp, Element>\n     */\n    template <typename AddOp, typename MultOp, typename Element>\n    struct RingWithIdentity\n      : Ring<AddOp, MultOp, Element>,\n        Monoid<MultOp, Element>\n    {};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    concept DivisionRing<typename AddOp, typename MultOp, typename Element>\n      : RingWithIdentity<AddOp, MultOp, Element>,\n        Inversion<MultOp, Element>\n    {\n        // 0 != 1, otherwise trivial\n        axiom ZeroIsDifferentFromOne(AddOp add, MultOp mult, Element x)\n        {\n\t    identity(add, x) != identity(mult, x);       \n        }\n\n        // Non-zero divisibility from left and from right\n        axiom NonZeroDivisibility(AddOp add, MultOp mult, Element x)\n        {\n\t    if (x != identity(add, x))\n\t\tmult(inverse(mult, x), x) == identity(mult, x);\n\t    if (x != identity(add, x))\n\t\tmult(x, inverse(mult, x)) == identity(mult, x);\n        }\n    };    \n#else\n    //! Concept DivisionRing\n    /*!\n        \\param AddOp A functor implementing a binary operation representing addition\n        \\param MultOp A functor implementing a binary operation representing multiplication\n        \\param Element The type upon the binary operation is defined   \n\n        \\par Refinement of:\n\t- RingWithIdentity <AddOp, MultOp, Element>\n        - Inversion <MultOp, Element>\n\n        \\par Notation:\n        <table summary=\"notation\">\n          <tr>\n            <td>add</td>\n\t    <td>Object of type AddOp</td>\n          </tr>\n          <tr>\n            <td>mult</td>\n\t    <td>Object of type Multop</td>\n          </tr>\n          <tr>\n            <td>x, y, z</td>\n\t    <td>Objects of type Element</td>\n          </tr>\n        </table>\n\n        \\invariant\n        <table summary=\"invariants\">\n          <tr>\n            <td>Non-zero divisibility from left</td>\n\t    <td>mult(inverse(mult, x), x) == identity(mult, x)</td>\n\t    <td>if x != identity(add, x)</td>\n          </tr>\n          <tr>\n            <td>Non-zero divisibility from right</td>\n\t    <td>mult(x, inverse(mult, x)) == identity(mult, x)</td>\n\t    <td>if x != identity(add, x)</td>\n          </tr>\n          <tr>\n            <td>Zero is different from one</td>\n\t    <td>identity(add, x) != identity(mult, x)</td>\n\t    <td></td>\n          </tr>\n\t</table>\n\n\t\\note\n\t-# Zero and one can be theoretically identical in a DivisionRing.  However,\n\t   this implies that there is only one element x in the Ring with x + x = x and \n\t   x * x = x (which is actually even a Field). \n\t   Because this structure has no practical value we exclude it from \n\t   consideration.\n     */\n    template <typename AddOp, typename MultOp, typename Element>\n    struct DivisionRing\n      : RingWithIdentity<AddOp, MultOp, Element>,\n        Inversion<MultOp, Element>\n    {};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    // SkewField is defined as synonym for DivisionRing\n    auto concept SkewField<typename AddOp, typename MultOp, typename Element>\n      : DivisionRing<AddOp, MultOp, Element>\n    {};\n#else\n    //! Concept SkewField\n    /*!\n        \\param AddOp A functor implementing a binary operation representing addition\n        \\param MultOp A functor implementing a binary operation representing multiplication\n        \\param Element The type upon the binary operation is defined   \n\n        \\par Refinement of:\n\t- DivisionRing <AddOp, MultOp, Element>\n\t\\note\n\t- Because the refinement of DivisionRing to SkewField is automatic the two concepts\n\t  are identical.\n     */\n    template <typename AddOp, typename MultOp, typename Element>\n    struct SkewField\n      : DivisionRing<AddOp, MultOp, Element>\n    {};\n#endif\n\n\n#ifdef __GXX_CONCEPTS__\n    auto concept Field<typename AddOp, typename MultOp, typename Element>\n      : DivisionRing<AddOp, MultOp, Element>,\n        Commutative<MultOp, Element>\n    {};\n#else\n    //! Concept Field\n    /*!\n        \\param AddOp A functor implementing a binary operation representing addition\n        \\param MultOp A functor implementing a binary operation representing multiplication\n        \\param Element The type upon the binary operation is defined   \n\n        \\par Refinement of:\n\t- DivisionRing <AddOp, MultOp, Element>\n\t- Commutative <MultOp, Element>\n     */\n    template <typename AddOp, typename MultOp, typename Element>\n    struct Field\n      : DivisionRing<AddOp, MultOp, Element>,\n        Commutative<MultOp, Element>\n    {};\n#endif\n\n/*@}*/ // end of group Concepts\n\n} // algebra\n\n#endif // LA_ALGEBRAIC_CONCEPTS_DOC_INCLUDE\n", "meta": {"hexsha": "6b8817016d28bc9cefe0854df567697db32ff504", "size": 14967, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/linear_algebra/algebraic_concepts.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/linear_algebra/algebraic_concepts.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "lib/mtl4/boost/numeric/linear_algebra/algebraic_concepts.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 28.6724137931, "max_line_length": 117, "alphanum_fraction": 0.6079374624, "num_tokens": 3672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.4032280503416805}}
{"text": "/* ----------------------------------------------------------------------------\n\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/*\n * @file Unit3.h\n * @date Feb 02, 2011\n * @author Can Erdogan\n * @author Frank Dellaert\n * @author Alex Trevor\n * @author Zhaoyang Lv\n * @brief The Unit3 class - basically a point on a unit sphere\n */\n\n#include <gtsam/geometry/Unit3.h>\n#include <gtsam/geometry/Point2.h>\n#include <gtsam/config.h>  // for GTSAM_USE_TBB\n\n#ifdef __clang__\n#  pragma clang diagnostic push\n#  pragma clang diagnostic ignored \"-Wunused-variable\"\n#endif\n#include <boost/random/uniform_on_sphere.hpp>\n#ifdef __clang__\n#  pragma clang diagnostic pop\n#endif\n\n#include <boost/random/variate_generator.hpp>\n#include <iostream>\n#include <limits>\n#include <cmath>\n#include <vector>\n\nusing namespace std;\n\nnamespace gtsam {\n\n/* ************************************************************************* */\nUnit3 Unit3::FromPoint3(const Point3& point, OptionalJacobian<2, 3> H) {\n  // 3*3 Derivative of representation with respect to point is 3*3:\n  Matrix3 D_p_point;\n  Unit3 direction;\n  direction.p_ = normalize(point, H ? &D_p_point : 0);\n  if (H)\n    *H << direction.basis().transpose() * D_p_point;\n  return direction;\n}\n\n/* ************************************************************************* */\nUnit3 Unit3::Random(boost::mt19937 & rng) {\n  // TODO(dellaert): allow any engine without including all of boost :-(\n  boost::uniform_on_sphere<double> randomDirection(3);\n  // This variate_generator object is required for versions of boost somewhere\n  // around 1.46, instead of drawing directly using boost::uniform_on_sphere(rng).\n  boost::variate_generator<boost::mt19937&, boost::uniform_on_sphere<double> > generator(\n      rng, randomDirection);\n  const vector<double> d = generator();\n  return Unit3(d[0], d[1], d[2]);\n}\n\n/* ************************************************************************* */\n// Get the axis of rotation with the minimum projected length of the point\nstatic Point3 CalculateBestAxis(const Point3& n) {\n  double mx = fabs(n.x()), my = fabs(n.y()), mz = fabs(n.z());\n  if ((mx <= my) && (mx <= mz)) {\n    return Point3(1.0, 0.0, 0.0);\n  } else if ((my <= mx) && (my <= mz)) {\n    return Point3(0.0, 1.0, 0.0);\n  } else {\n    return Point3(0, 0, 1);\n  }\n}\n\n/* ************************************************************************* */\nconst Matrix32& Unit3::basis(OptionalJacobian<6, 2> H) const {\n#ifdef GTSAM_USE_TBB\n  // NOTE(hayk): At some point it seemed like this reproducably resulted in\n  // deadlock. However, I don't know why and I can no longer reproduce it.\n  // It either was a red herring or there is still a latent bug left to debug.\n  tbb::mutex::scoped_lock lock(B_mutex_);\n#endif\n\n  const bool cachedBasis = static_cast<bool>(B_);\n  const bool cachedJacobian = static_cast<bool>(H_B_);\n\n  if (H) {\n    if (!cachedJacobian) {\n      // Compute Jacobian. Recomputes B_\n      Matrix32 B;\n      Matrix62 jacobian;\n      Matrix33 H_B1_n, H_b1_B1, H_b2_n, H_b2_b1;\n\n      // Choose the direction of the first basis vector b1 in the tangent plane\n      // by crossing n with the chosen axis.\n      const Point3 n(p_), axis = CalculateBestAxis(n);\n      const Point3 B1 = gtsam::cross(n, axis, &H_B1_n);\n\n      // Normalize result to get a unit vector: b1 = B1 / |B1|.\n      B.col(0) = normalize(B1, &H_b1_B1);\n\n      // Get the second basis vector b2, which is orthogonal to n and b1.\n      B.col(1) = gtsam::cross(n, B.col(0), &H_b2_n, &H_b2_b1);\n\n      // Chain rule tomfoolery to compute the jacobian.\n      const Matrix32& H_n_p = B;\n      jacobian.block<3, 2>(0, 0) = H_b1_B1 * H_B1_n * H_n_p;\n      auto H_b1_p = jacobian.block<3, 2>(0, 0);\n      jacobian.block<3, 2>(3, 0) = H_b2_n * H_n_p + H_b2_b1 * H_b1_p;\n\n      // Cache the result and jacobian\n      H_B_.reset(jacobian);\n      B_.reset(B);\n    }\n\n    // Return cached jacobian, possibly computed just above\n    *H = *H_B_;\n  }\n\n  if (!cachedBasis) {\n    // Same calculation as above, without derivatives.\n    // Done after H block, as that possibly computes B_ for the first time\n    Matrix32 B;\n\n    const Point3 n(p_), axis = CalculateBestAxis(n);\n    const Point3 B1 = gtsam::cross(n, axis);\n    B.col(0) = normalize(B1);\n    B.col(1) = gtsam::cross(n, B.col(0));\n    B_.reset(B);\n  }\n\n  return *B_;\n}\n\n/* ************************************************************************* */\nPoint3 Unit3::point3(OptionalJacobian<3, 2> H) const {\n  if (H)\n    *H = basis();\n  return Point3(p_);\n}\n\n/* ************************************************************************* */\nVector3 Unit3::unitVector(OptionalJacobian<3, 2> H) const {\n  if (H)\n    *H = basis();\n  return p_;\n}\n\n/* ************************************************************************* */\nstd::ostream& operator<<(std::ostream& os, const Unit3& pair) {\n  os << pair.p_ << endl;\n  return os;\n}\n\n/* ************************************************************************* */\nvoid Unit3::print(const std::string& s) const {\n  cout << s << \":\" << p_ << endl;\n}\n\n/* ************************************************************************* */\nMatrix3 Unit3::skew() const {\n  return skewSymmetric(p_.x(), p_.y(), p_.z());\n}\n\n/* ************************************************************************* */\ndouble Unit3::dot(const Unit3& q, OptionalJacobian<1, 2> H_p,\n                  OptionalJacobian<1, 2> H_q) const {\n  // Get the unit vectors of each, and the derivative.\n  Matrix32 H_pn_p;\n  Point3 pn = point3(H_p ? &H_pn_p : nullptr);\n\n  Matrix32 H_qn_q;\n  const Point3 qn = q.point3(H_q ? &H_qn_q : nullptr);\n\n  // Compute the dot product of the Point3s.\n  Matrix13 H_dot_pn, H_dot_qn;\n  double d = gtsam::dot(pn, qn, H_p ? &H_dot_pn : nullptr, H_q ? &H_dot_qn : nullptr);\n\n  if (H_p) {\n    (*H_p) << H_dot_pn * H_pn_p;\n  }\n\n  if (H_q) {\n    (*H_q) = H_dot_qn * H_qn_q;\n  }\n\n  return d;\n}\n\n/* ************************************************************************* */\nVector2 Unit3::error(const Unit3& q, OptionalJacobian<2, 2> H_q) const {\n  // 2D error is equal to B'*q, as B is 3x2 matrix and q is 3x1\n  const Vector2 xi = basis().transpose() * q.p_;\n  if (H_q) {\n    *H_q = basis().transpose() * q.basis();\n  }\n  return xi;\n}\n\n/* ************************************************************************* */\nVector2 Unit3::errorVector(const Unit3& q, OptionalJacobian<2, 2> H_p,\n                           OptionalJacobian<2, 2> H_q) const {\n  // Get the point3 of this, and the derivative.\n  Matrix32 H_qn_q;\n  const Point3 qn = q.point3(H_q ? &H_qn_q : nullptr);\n\n  // 2D error here is projecting q into the tangent plane of this (p).\n  Matrix62 H_B_p;\n  Matrix23 Bt = basis(H_p ? &H_B_p : nullptr).transpose();\n  Vector2 xi = Bt * qn;\n\n  if (H_p) {\n    // Derivatives of each basis vector.\n    const Matrix32& H_b1_p = H_B_p.block<3, 2>(0, 0);\n    const Matrix32& H_b2_p = H_B_p.block<3, 2>(3, 0);\n\n    // Derivatives of the two entries of xi wrt the basis vectors.\n    const Matrix13 H_xi1_b1 = qn.transpose();\n    const Matrix13 H_xi2_b2 = qn.transpose();\n\n    // Assemble dxi/dp = dxi/dB * dB/dp.\n    const Matrix12 H_xi1_p = H_xi1_b1 * H_b1_p;\n    const Matrix12 H_xi2_p = H_xi2_b2 * H_b2_p;\n    *H_p << H_xi1_p, H_xi2_p;\n  }\n\n  if (H_q) {\n    // dxi/dq is given by dxi/dqu * dqu/dq, where qu is the unit vector of q.\n    const Matrix23 H_xi_qu = Bt;\n    *H_q = H_xi_qu * H_qn_q;\n  }\n\n  return xi;\n}\n\n/* ************************************************************************* */\ndouble Unit3::distance(const Unit3& q, OptionalJacobian<1, 2> H) const {\n  Matrix2 H_xi_q;\n  const Vector2 xi = error(q, H ? &H_xi_q : nullptr);\n  const double theta = xi.norm();\n  if (H)\n    *H = (xi.transpose() / theta) * H_xi_q;\n  return theta;\n}\n\n/* ************************************************************************* */\nUnit3 Unit3::retract(const Vector2& v, OptionalJacobian<2,2> H) const {\n  // Compute the 3D xi_hat vector\n  const Vector3 xi_hat = basis() * v;\n  const double theta = xi_hat.norm();\n  const double c = std::cos(theta);\n\n  // Treat case of very small v differently.\n  Matrix23 H_from_point;\n  if (theta < std::numeric_limits<double>::epsilon()) {\n    const Unit3 exp_p_xi_hat = Unit3::FromPoint3(c * p_ + xi_hat,\n                                                 H? &H_from_point : nullptr);\n    if (H) { // Jacobian\n      *H = H_from_point *\n          (-p_ * xi_hat.transpose() + Matrix33::Identity()) * basis();\n    }\n    return exp_p_xi_hat;\n  }\n\n  const double st = std::sin(theta) / theta;\n  const Unit3 exp_p_xi_hat = Unit3::FromPoint3(c * p_ + xi_hat * st,\n                                               H? &H_from_point : nullptr);\n  if (H) { // Jacobian\n    *H = H_from_point *\n        (p_ * -st * xi_hat.transpose() + st * Matrix33::Identity() +\n        xi_hat * ((c - st) / std::pow(theta, 2)) * xi_hat.transpose()) * basis();\n  }\n  return exp_p_xi_hat;\n}\n\n/* ************************************************************************* */\nVector2 Unit3::localCoordinates(const Unit3& other) const {\n  const double x = p_.dot(other.p_);\n  // Crucial quantity here is y = theta/sin(theta) with theta=acos(x)\n  // Now, y = acos(x) / sin(acos(x)) = acos(x)/sqrt(1-x^2)\n  // We treat the special case 1 and -1 below\n  const double x2 = x * x;\n  const double z = 1 - x2;\n  double y;\n  if (z < std::numeric_limits<double>::epsilon()) {\n    if (x > 0)  // first order expansion at x=1\n      y = 1.0 - (x - 1.0) / 3.0;\n    else  // cop out\n      return Vector2(M_PI, 0.0);\n  } else {\n    // no special case\n    y = acos(x) / sqrt(z);\n  }\n  return basis().transpose() * y * (other.p_ - x * p_);\n}\n/* ************************************************************************* */\n\n}  // namespace gtsam\n", "meta": {"hexsha": "f661f819dbe5c19d9922c6c584427026bc401a8c", "size": 9969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/geometry/Unit3.cpp", "max_stars_repo_name": "chrisbeall/gtsam", "max_stars_repo_head_hexsha": "44fac28e850ff32086737116e79a6e29f9cea25b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gtsam/geometry/Unit3.cpp", "max_issues_repo_name": "chrisbeall/gtsam", "max_issues_repo_head_hexsha": "44fac28e850ff32086737116e79a6e29f9cea25b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-10-30T21:17:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-18T18:47:40.000Z", "max_forks_repo_path": "gtsam/geometry/Unit3.cpp", "max_forks_repo_name": "chrisbeall/gtsam", "max_forks_repo_head_hexsha": "44fac28e850ff32086737116e79a6e29f9cea25b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-04T18:52:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-04T18:52:09.000Z", "avg_line_length": 32.6852459016, "max_line_length": 89, "alphanum_fraction": 0.5433844919, "num_tokens": 2814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.6477982043529715, "lm_q1q2_score": 0.40322804610922497}}
{"text": "//=======================================================================\n// Copyright (c)\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file bounded_degree_mst_example.cpp\n * @brief\n * @author Piotr Godlewski\n * @version 1.0\n * @date 2013-11-21\n */\n\n\n//! [Bounded-Degree Minimum Spanning Tree Example]\n#include \"paal/iterative_rounding/bounded_degree_min_spanning_tree/bounded_degree_mst.hpp\"\n#include \"paal/utils/functors.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n\n#include <iostream>\n#include <vector>\n\nint main() {\n    using Graph = boost::adjacency_list<boost::vecS, boost::vecS,\n        boost::undirectedS, boost::no_property,\n        boost::property<boost::edge_weight_t, int>>;\n    using Edge = boost::graph_traits<Graph>::edge_descriptor;\n\n    // sample problem\n    std::vector<std::pair<int, int>> edges {{0,1},{0,2},{1,2},{1,3},{1,4},\n        {1,5},{5,0},{3,4}};\n    std::vector<int> costs {1,2,1,2,1,1,1,5};\n    std::vector<int> bounds {3,2,2,2,2,2};\n\n    Graph g(edges.begin(), edges.end(), costs.begin(), 6);\n    auto degree_bounds = paal::utils::make_array_to_functor(bounds);\n\n    std::vector<Edge> result_tree;\n\n    // optional input validity checking\n    auto bdmst = paal::ir::make_bounded_degree_mst(\n        g, degree_bounds, std::back_inserter(result_tree));\n    auto error = bdmst.check_input_validity();\n    if (error) {\n        std::cerr << \"The input is not valid!\" << std::endl;\n        std::cerr << *error << std::endl;\n        return -1;\n    }\n\n    // solve it\n    auto result = paal::ir::bounded_degree_mst_iterative_rounding(\n        g, degree_bounds, std::back_inserter(result_tree));\n\n    // print result\n    if (result.first == paal::lp::OPTIMAL) {\n        std::cout << \"Edges in the spanning tree\" << std::endl;\n        for (auto e : result_tree) {\n            std::cout << \"Edge \" << e << std::endl;\n        }\n        std::cout << \"Cost of the solution: \" << *(result.second) << std::endl;\n    } else {\n        std::cout << \"The instance is infeasible\" << std::endl;\n    }\n    paal::lp::glp::free_env();\n    return 0;\n}\n    //! [Bounded-Degree Minimum Spanning Tree Example]\n", "meta": {"hexsha": "b65011785e4ff93459ec98abdf96b52fb1a75fc2", "size": 2312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/iterative_rounding/bounded_degree_mst_example.cpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/iterative_rounding/bounded_degree_mst_example.cpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/iterative_rounding/bounded_degree_mst_example.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 32.5633802817, "max_line_length": 90, "alphanum_fraction": 0.5908304498, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.40322804550022384}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2009, Willow Garage, Inc.\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of Willow Garage, Inc. nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n#include \"precomp.hpp\"\n\n// Eigen\n#include <Eigen/Core>\n\n// OpenCV\n#include <opencv2/core/eigen.hpp>\n#include <opencv2/sfm/numeric.hpp>\n\n// libmv headers\n#include \"libmv/numeric/numeric.h\"\n\n#include <iostream>\n\nnamespace cv\n{\nnamespace sfm\n{\n\ntemplate<typename T>\nvoid\nmeanAndVarianceAlongRows( const Mat_<T> &A,\n                          Mat_<T> mean,\n                          Mat_<T> variance )\n{\n  const int n = A.rows, m = A.cols;\n\n  for( int i = 0; i < n; ++i )\n  {\n    mean(i) = 0;\n    variance(i) = 0;\n\n    for( int j = 0; j < m; ++j )\n    {\n      T x = A(i,j);\n      mean(i) += x;\n      variance(i) += x*x;\n    }\n  }\n\n  mean /= m;\n  for (int i = 0; i < n; ++i) {\n    variance(i) = variance(i) / m - (mean(i)*mean(i));\n  }\n}\n\nvoid\nmeanAndVarianceAlongRows( InputArray _A,\n                          OutputArray _mean,\n                          OutputArray _variance )\n{\n  const Mat A = _A.getMat();\n  const int depth = A.depth();\n  CV_Assert( depth == CV_32F || depth == CV_64F );\n\n  _mean.create(A.rows, 1, depth);\n  _variance.create(A.rows, 1, depth);\n\n  Mat mean = _mean.getMat(), variance = _variance.getMat();\n\n  if( depth == CV_32F )\n  {\n    meanAndVarianceAlongRows<float>( A, mean, variance );\n  }\n  else\n  {\n    meanAndVarianceAlongRows<double>( A, mean, variance );\n  }\n}\n\n\n//template<typename T>\n//inline Mat\n//skewMatMinimal( const Mat_<T> &x )\n//{\n//  Mat_<T> skew(2,3);\n//  skew << 0, -1,  x(1),\n//          1,  0, -x(0);\n//  return skew;\n//}\n//\n//Mat\n//skewMatMinimal( InputArray _x )\n//{\n//  Mat x = _x.getMat();\n//  CV_Assert( x.rows == 3 && x.cols == 1 );\n//\n//  int depth = x.depth();\n//  if( depth == CV_32F )\n//  {\n//    return skewMatMinimal<float>(x);\n//  }\n//  else\n//  {\n//    return skewMatMinimal<double>(x);\n//  }\n//}\n\ntemplate<typename T>\nMat\nskewMat( const Mat_<T> &x )\n{\n  Mat_<T> skew(3,3);\n  skew <<   0 , -x(2),  x(1),\n          x(2),    0 , -x(0),\n         -x(1),  x(0),    0;\n\n  return skew;\n}\n\nMat\nskew( InputArray _x )\n{\n  const Mat x = _x.getMat();\n  const int depth = x.depth();\n  CV_Assert( x.size() == Size(3,1) || x.size() == Size(1,3) );\n  CV_Assert( depth == CV_32F || depth == CV_64F );\n\n  Mat skewMatrix;\n  if( depth == CV_32F )\n  {\n    skewMatrix = skewMat<float>(x);\n  }\n  else if( depth == CV_64F )\n  {\n    skewMatrix = skewMat<double>(x);\n  }\n  else\n  {\n    //CV_Error(CV_StsBadArg, \"The DataType must be CV_32F or CV_64F\");\n  }\n\n  return skewMatrix;\n}\n\n\n} /* namespace sfm */\n} /* namespace cv */\n", "meta": {"hexsha": "221afcf95c8e020e3cdea5f6f503e8ed1527a15e", "size": 4127, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencv_contrib-3.3.0/modules/sfm/src/numeric.cpp", "max_stars_repo_name": "AmericaGL/TrashTalk_Dapp", "max_stars_repo_head_hexsha": "401f17289261b5f537b239e7759dc039d53211e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 36.0, "max_stars_repo_stars_event_min_datetime": "2017-04-13T03:01:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T10:38:27.000Z", "max_issues_repo_path": "opencv_contrib-3.3.0/modules/sfm/src/numeric.cpp", "max_issues_repo_name": "AmericaGL/TrashTalk_Dapp", "max_issues_repo_head_hexsha": "401f17289261b5f537b239e7759dc039d53211e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2018-10-16T07:28:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-15T02:21:16.000Z", "max_forks_repo_path": "opencv_contrib-3.3.0/modules/sfm/src/numeric.cpp", "max_forks_repo_name": "AmericaGL/TrashTalk_Dapp", "max_forks_repo_head_hexsha": "401f17289261b5f537b239e7759dc039d53211e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2015-10-23T19:36:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-02T12:20:32.000Z", "avg_line_length": 23.7183908046, "max_line_length": 72, "alphanum_fraction": 0.6210322268, "num_tokens": 1180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.6224593312018546, "lm_q1q2_score": 0.40322804550022384}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_SCALAR_MNORM_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_SCALAR_MNORM_HPP_INCLUDED\n#include <nt2/linalg/functions/mnorm.hpp>\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/ismatrix.hpp>\n#include <nt2/include/functions/isvector.hpp>\n#include <nt2/include/functions/svd.hpp>\n#include <nt2/include/functions/globalnorm2.hpp>\n#include <nt2/include/functions/mnorm1.hpp>\n#include <nt2/include/functions/mnorminf.hpp>\n#include <nt2/include/functions/mnormfro.hpp>\n#include <nt2/include/constants/mone.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/inf.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/core/container/dsl/forward.hpp>\n#include <nt2/core/functions/table/details/is_definitely_vector.hpp>\n#include <boost/assert.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/static_assert.hpp>\n\nnamespace nt2 {  namespace ext\n{\n\n  BOOST_DISPATCH_IMPLEMENT  ( mnorm_, tag::cpu_\n                            , (A0)\n                            , (scalar_<unspecified_<A0> >)\n                            )\n  {\n    typedef typename meta::as_real<A0>::type result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      return nt2::abs(a0);\n    }\n  };\n\n\n  BOOST_DISPATCH_IMPLEMENT  ( mnorm_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_<unspecified_<A0> >)\n                              (unspecified_<A1>)\n                            )\n  {\n    typedef typename meta::as_real<A0>::type result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 const&) const\n    {\n      return nt2::abs(a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( mnorm_, tag::cpu_\n                            , (A0)\n                            , ((ast_<A0, nt2::container::domain>))\n                            )\n  {\n    typedef typename A0::value_type                   type_t;\n    typedef typename meta::as_real<type_t>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      BOOST_ASSERT_MSG(nt2::ismatrix(a0), \"a0 is not a matrix\");\n      typedef typename details::is_vector<typename A0::extent_type>::type choice_t;\n      return eval(a0, choice_t());\n    }\n\n    BOOST_FORCEINLINE result_type\n    eval(A0 const& a0, boost::mpl::true_ const &) const\n    {\n      return globalnorm2(a0);\n    }\n\n    BOOST_FORCEINLINE result_type\n    eval(A0 const& a0, boost::mpl::false_ const &) const\n    {\n      return svd(a0)(1);\n    }\n\n    BOOST_FORCEINLINE result_type\n    eval(A0 const& a0, nt2::meta::indeterminate_ const &) const\n    {\n      if (isvector(a0))\n        return globalnorm2(a0);\n      else\n        return svd(a0)(1);\n    }\n\n\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( mnorm_, tag::cpu_\n                            , (A0)(A1)\n                            , ((ast_<A0, nt2::container::domain>))\n                              (scalar_<arithmetic_<A1> >)\n                            )\n  {\n    typedef typename A0::value_type                   type_t;\n    typedef typename meta::as_real<type_t>::type result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 const & a1) const\n    {\n      BOOST_ASSERT_MSG(nt2::ismatrix(a0), \"a0 is not a matrix\");\n      BOOST_ASSERT_MSG((a1 == Two<A1>()) ||\n                       (a1 == One<A1>()) ||\n                       (a1 == Inf<A1>()) ||\n                       (a1 == Mone<A1>()),\n                       \"mnorm is not defined for this parameters setting\");\n      if (a1 == Two<A1>()) return nt2::mnorm(a0);\n      if (a1 == One<A1>()) return nt2::mnorm1(a0);\n      if (a1 == Inf<A1>()) return nt2::mnorminf(a0);\n      return nt2::mnormfro(a0);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( mnorm_, tag::cpu_,\n                                     (A0)(A1),\n                                     ((ast_<A0, nt2::container::domain>))\n                                     (unspecified_<A1>)\n                                     )\n  {\n    typedef typename A0::value_type                   type_t;\n    typedef typename meta::as_real<type_t>::type result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const &a0, A1 const&) const\n    {\n      return eval(a0, A1());\n    }\n\n  private:\n    BOOST_FORCEINLINE result_type eval(A0 const &a0\n                                      , nt2::meta::as_<tag::Inf> const&) const\n    {\n      return nt2::mnorminf(a0);\n    }\n    BOOST_FORCEINLINE result_type eval(A0 const &a0\n                                      , nt2::meta::as_<tag::inf_> const&) const\n    {\n      return nt2::mnorminf(a0);\n    }\n    BOOST_FORCEINLINE result_type eval(A0 const &a0\n                                      , nt2::meta::as_<tag::One> const&) const\n    {\n      return nt2::mnorm1(a0);\n    }\n    BOOST_FORCEINLINE result_type eval(A0 const &a0\n                                      , nt2::meta::as_<tag::one_> const&) const\n    {\n      return nt2::mnorm1(a0);\n    }\n    BOOST_FORCEINLINE result_type eval(A0 const &a0\n                                      , nt2::meta::as_<tag::Two> const&) const\n    {\n      return mnorm(a0);\n    }\n    BOOST_FORCEINLINE result_type eval(A0 const &a0\n                                      , nt2::meta::as_<tag::two_> const&) const\n    {\n      return mnorm(a0);\n    }\n    BOOST_FORCEINLINE result_type eval(A0 const &a0\n                                      , nt2::meta::as_<tag::fro_> const&) const\n    {\n      return mnormfro(a0);\n    }\n  };\n\n   // Selects globalnorm from static norm value\n  BOOST_DISPATCH_IMPLEMENT  ( mnorm_, tag::cpu_\n                            , (A0)(A1)\n                            , ((ast_<A0, nt2::container::domain>))\n                              (mpl_integral_< scalar_< fundamental_<A1> > >)\n                            )\n  {\n    typedef typename A0::value_type                   type_t;\n    typedef typename meta::as_real<type_t>::type result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const &a0, A1 const&) const\n    {\n      // outside of Inf,  Minf,  One and Two no hope\n      BOOST_ASSERT_MSG(nt2::ismatrix(a0), \"a0 is not a matrix\");\n      BOOST_STATIC_ASSERT_MSG((A1::value == 2) ||\n                              (A1::value == 1) ||\n                              (A1::value == 0) ||\n                              (A1::value == -1)\n                             , \"Norm value must be 1 2 0 (inf_) or -1 (fro_)\" );\n      return eval(a0, A1());\n    }\n\n    BOOST_FORCEINLINE result_type eval( A0 const &a0\n                                      , boost::mpl::int_<2> const&\n                                      ) const\n    {\n      return nt2::mnorm2(a0);\n    }\n    BOOST_FORCEINLINE result_type eval( A0 const &a0\n                                      , boost::mpl::int_<1> const&\n                                      ) const\n    {\n      return nt2::mnorm1(a0);\n    }\n    BOOST_FORCEINLINE result_type eval( A0 const &a0\n                                      , boost::mpl::int_<-1> const&\n                                      ) const\n    {\n      return nt2::mnormfro(a0);\n    }\n    BOOST_FORCEINLINE result_type eval( A0 const &a0\n                                      , boost::mpl::int_<0> const&\n                                      ) const\n    {\n      return nt2::mnorminf(a0);\n    }\n  };\n\n\n} }\n\n#endif\n", "meta": {"hexsha": "ae7e5ecd44c1c31402e2b5da7086db1513cfed51", "size": 7777, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/scalar/mnorm.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/linalg/include/nt2/linalg/functions/scalar/mnorm.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/linalg/include/nt2/linalg/functions/scalar/mnorm.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 34.5644444444, "max_line_length": 83, "alphanum_fraction": 0.5129227208, "num_tokens": 1902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190477, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.4030484071200499}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RWLIBS_ALGORITHMS_NULLSPACEPROJECTION_HPP\n#define RWLIBS_ALGORITHMS_NULLSPACEPROJECTION_HPP\n\n#include <rw/kinematics/State.hpp>\n#include <rw/math/Q.hpp>\n\n#include <Eigen/Core>\n\nnamespace rw { namespace kinematics {\n    class Frame;\n}}    // namespace rw::kinematics\nnamespace rw { namespace models {\n    class Device;\n}}    // namespace rw::models\n\nnamespace rwlibs { namespace algorithms {\n\n    /**\n     * @brief Performs a projection in the null space of the device Jacobian to move joints away\n     * from singularities.\n     *\n     * Given a device with redundant degrees of freedom, the null space of the Jacobian can be used\n     * to move joints away from their limits. The problem of finding an optimal correction is\n     * formulated as a quadratic optimization problem in which joint position, velocity and\n     * acceleration limits are formulated as in the QP/XQP method.\n     *\n     * The basic NullSpaceProjection assumes all 6 degrees of freedom of the tool needs to be\n     * constrainted.\n     */\n    class NullSpaceProjection\n    {\n      public:\n        /**\n         * @brief Construct NullSpaceProjection\n         * @param device [in] Device to consider\n         * @param controlFrame [in] Frame for which to calculate the Jacobian\n         * @param state [in] State giving the assembly of the workcell\n         * @param dt [in] Time step size\n         */\n        NullSpaceProjection (rw::models::Device* device, rw::kinematics::Frame* controlFrame,\n                             const rw::kinematics::State& state, double dt);\n\n        /**\n         * @brief Destructor\n         */\n        virtual ~NullSpaceProjection ();\n\n        /**\n         * @brief Solves to give a joint motion moving away from joint limits while satisfying the\n         * main task.\n         *\n         * Usage:\n         * \\code\n         * NullSpaceProjection nps(device, device->getEnd(), state);\n         * ...\n         * ...\n         * \\\\input Current configuration q, current velocity dq and desired new velocity dq1\n         * Q qns = nps.solve(q, dq, dq1);\n         * dq = dq1+qns;\n         * \\endcode\n         *\n         * @param q [in] Configuration of the device\n         * @param dqcurrent [in] The current velocity\n         * @param dq1 [in] The new velocity calculated e.g. by the XQPController\n         */\n        rw::math::Q solve (const rw::math::Q& q, const rw::math::Q& dqcurrent,\n                           const rw::math::Q& dq1);\n\n        /**\n         * @brief Enumeration used to specify frame associated with the projection\n         */\n        enum ProjectionFrame {\n            BaseFrame = 0, /** Robot Base Frame */\n            ControlFrame   /**The Frame specified as the controlFrame*/\n        };\n\n        /**\n         * @brief Specifies an initial projection of the Jacobian before calculating the null-space\n         *\n         * Given a projection matric \\f$P\\f$ it is multiplied with the device Jacobian as $\\f$P\n         * J\\f$. This can be used to ignore degrees of freedom such as tool rool.\n         *\n         * \\see XQPController::setProjection\n         *\n         * Usage: Setup for system ignoring tool roll\n         * \\code\n         * XQPController* xqp = new XQPController(device, device->getEnd(), state, dt)\n         * Eigen::Matrix<double,5,6 P;\n         * for (int i = 0; i<5; i++)\n         *     P(i,i) = 1;\n         * xqp->setProjection(P, XQPController::ControlFrame);\n         * \\endcode\n         *\n         * @param P [in] The projection matrix\n         * @param space [in] The space in which to apply the projection\n         */\n        void setProjection (const Eigen::MatrixXd& P, ProjectionFrame space);\n\n        /**\n         * @brief Sets the threshold for the joint limits\n         *\n         * Given an upper and a lower bound \\f$upper\\f$ and \\f$lower\\f$ the proximity of the joint\n         * limits is defined as \\f$upper-\\tau (upper-lower)\\f$ where \\f$\\tau\\f$ is the threshold\n         * specified here.\n         *\n         * @param threshold [in] Relative threshold for the joint limits\n         */\n        void setThreshold (double threshold);\n\n        /**\n         * @brief Sets the weight of the joint limits\n         *\n         * @param w [in] Weight of the joint limit\n         */\n        void setJointLimitsWeight (double w);\n\n      private:\n        /**\n         * Calculate gradient for joint limit cost function\n         */\n        rw::math::Q getGradient (const rw::math::Q& q);\n\n        /**\n         * Calculate velocity limits associated with position, velocity and acceleration limits as\n         * in the QPController\n         */\n        void calculateVelocityLimits (rw::math::Q& lower, rw::math::Q& upper, const rw::math::Q& q,\n                                      const rw::math::Q& dq);\n\n        rw::models::Device* _device;\n        rw::kinematics::Frame* _controlFrame;\n        rw::kinematics::State _state;\n        int _dof;\n        double _dt;\n\n        rw::math::Q _qlower;\n        rw::math::Q _qupper;\n        rw::math::Q _dqlimit;\n        rw::math::Q _ddqlimit;\n        rw::math::Q _thresholdLower;\n        rw::math::Q _thresholdUpper;\n        Eigen::MatrixXd _P;\n        ProjectionFrame _space;\n\n        double _weightJointLimits;\n    };\n\n}}    // namespace rwlibs::algorithms\n\n#endif /*RWLIBS_ALGORITHMS_NULLSPACEPROJECTION_HPP*/\n", "meta": {"hexsha": "30db56143a2d4dce3b8a2c830beccc555f0e9368", "size": 6172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rwlibs/algorithms/xqpcontroller/NullSpaceProjection.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rwlibs/algorithms/xqpcontroller/NullSpaceProjection.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rwlibs/algorithms/xqpcontroller/NullSpaceProjection.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7380952381, "max_line_length": 99, "alphanum_fraction": 0.5912184057, "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017746, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.4030456540548667}}
{"text": "/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Hidekazu Ikeno\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n\n///\n/// \\file mod_prony_reduction.hpp\n///\n/// Sparse approximation of exponential sum by the modified Prony method.\n///\n\n#ifndef MXPFIT_MOD_PRONY_REDUCTION_HPP\n#define MXPFIT_MOD_PRONY_REDUCTION_HPP\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <Eigen/QR>\n#include <Eigen/SVD>\n\n#include <mxpfit/exponential_sum.hpp>\n\nnamespace mxpfit\n{\n\n///\n/// ### ModPronyReduction\n///\n/// \\brief Find a truncated exponential sum function with smaller number of\n///        terms by the modified Prony's method\n///\n/// \\tparam T  Scalar type of exponential sum function.\n///\n/// For a given exponential sum function with real exponents,\n///\n/// \\f[\n///   f(t)=\\sum_{j=1}^{n} c_{j}^{} e^{-a_{j}^{} t}, \\quad\n///   (a_{j} > 0),\n/// \\f]\n///\n/// and prescribed accuracy \\f$\\epsilon > 0,\\f$ this class calculates truncated\n/// exponential \\f$\\hat{f}(t)\\f$ sum such that\n///\n/// \\f[\n///   \\hat{f}(t)=\\sum_{j=1}^{k} \\hat{c}_{j}^{}e^{-\\hat{a}_{j}^{} t}, \\quad\n///   \\left| f(t)-\\hat{f}(t) \\right| < \\epsilon,\n/// \\f]\n///\n/// where \\f$k \\leq n.\\f$ Exponents are assumed to be real and sorted in\n/// ascending order.\n///\ntemplate <typename T>\nclass ModPronyReduction\n{\npublic:\n    using Scalar     = T;\n    using RealScalar = typename Eigen::NumTraits<Scalar>::Real;\n    using Index      = Eigen::Index;\n\n    using VectorType = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n    using MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n    using ResultType = ExponentialSum<Scalar>;\n\n    ///\n    /// Compute truncated exponential sum \\f$ \\hat{f}(t) \\f$\n    ///\n    /// \\tparam DerivedF type of exponential sum inheriting ExponentialSumBase\n    ///\n    /// \\param[in] orig original exponential sum function, \\f$ f(t) \\f$\n    /// \\param[in] threshold  prescribed accuracy \\f$0 < \\epsilon \\ll 1\\f$\n    ///\n    /// \\return An instance of ExponentialSum represents \\f$\\hat{f}(t)\\f$\n    ///\n    template <typename DerivedF>\n    static ResultType compute(const ExponentialSumBase<DerivedF>& orig,\n                              RealScalar threshold);\n};\n\ntemplate <typename T>\ntemplate <typename DerivedF>\ntypename ModPronyReduction<T>::ResultType\nModPronyReduction<T>::compute(const ExponentialSumBase<DerivedF>& fn,\n                              RealScalar threshold)\n{\n    using Eigen::numext::real;\n    //\n    // Express the exponential sum whose exponents are less than a threshold\n    // (set to 1 here) with the linear combinations of fewer exponential\n    // functions.\n    //\n    // Note that exponents are all positive, and sorted in ascending order.\n    //\n    Index m0 = 0;\n    for (; m0 < fm.size(); ++m0)\n    {\n        if (fn.exponent(m0) >= T(1))\n        {\n            break;\n        }\n    }\n\n    VectorType h(2 * m0);\n    const auto w_small = fn.weights().head(m0);   // View\n    const auto p_small = fn.exponents().head(m0); // View\n    h(0)               = w_small.sum();\n    h(1)               = -(w_small * p_small).sum();\n    Index m            = 1;\n    auto factorial     = T(1);\n    for (; m < m0; ++m)\n    {\n        h(2 * m + 0) = (w_small * p_small.pow(2 * m + 0)).sum();\n        h(2 * m + 1) = -(w_small * p_small.pow(2 * m + 1)).sum();\n        factorial *= T((2 * m) * (2 * m + 1));\n        if (-h(2 * m + 1) / factorial < eps)\n        {\n            // Taylor expansion converges with the tolerance eps.\n            ++m;\n            break;\n        }\n    }\n\n    //\n    // Construct a Hankel matrix from the sequence h, and solve the linear\n    // equation, H q = b, with b = -h(m:2m-1).\n    //\n    MatrixType H(m, m);\n    for (Index i = 0; i < m; ++i)\n    {\n        H.col(i) = h.segment(i, m);\n    }\n    VectorType b(-h.segment(m, m));\n    VectorType q(H.colPivHouseholderQr().solve(b));\n\n    //\n    // Find the roots of the Prony polynomial,\n    //\n    // q(z) = \\sum_{k=0}^{m-1} q_k z^{k}.\n    //\n    // The roots of q(z) can be obtained as the eigenvalues of the companion\n    // matrix,\n    //\n    //     (0  0  ...  0 -p[0]  )\n    //     (1  0  ...  0 -p[1]  )\n    // C = (0  1  ...  0 -p[2]  )\n    //     (.. .. ...  .. ..    )\n    //     (0  0  ...  1 -p[m-1])\n    //\n    MatrixType& companion = H;\n    companion.setZeros();\n    companion.diagonal(-1).setOnes();\n    companion.col(m - 1) = -q;\n    Eigen::EigenSolver<MatrixType> es(companion,\n                                      /*compute eigenvectors*/ false);\n    // Vector gamma(arma::real(arma::eig_gen(companion)));\n\n    // --- Update exponents & weights\n    const Index keep = fn.size() - m0;\n    ResultType ret(keep + m);\n    ret.exponents().head(m)    = -es.eigenvalues().real();\n    ret.exponents().tail(keep) = fn.exponents().tail(keep);\n    //\n    // Construct Vandermonde matrix from gamma\n    //\n    MatrixType V(2 * m, m);\n    for (Index i = 0; i < m; ++i)\n    {\n        const auto z = real(gamma(i));\n        V(0, i)      = T(1);\n        for (Index j = 1; j < V.rows(); ++j)\n        {\n            V(j, i) = V(j - 1, i) * z; // z[i]**j\n        }\n    }\n    //\n    // Solve overdetermined Vandermonde system,\n    //\n    // V(0:2m-1,0:m-1) w(0:m-1) = h(0:2m-1)\n    //\n    // by the least square method.\n    //\n    ret.weights().head(m)    = V.colPivHouseholderQr().solve(h.head(2 * m));\n    ret.weights().tail(keep) = fn.weights().tail(keep);\n\n    return ret;\n}\n/// \\internal\n///\n/// ### reduce_terms_with_small_exponents\n///\n/// Find shorter exponential sum approximation by removing terms with small\n/// exponents using the modified Prony's method.\n///\ntemplate <typename T>\nGaussianSum<T> reduce_terms_with_small_exponents(const GaussianSum<T>& gs_orig,\n                                                 T eps)\n{\n    using UIndex  = arma::uword;\n    using SUIndex = arma::sword;\n    using Vector  = arma::Col<T>;\n    using Matrix  = arma::Mat<T>;\n    //\n    // Express the sum of Gaussians whose exponents are less than a threshold\n    // (set to 1 here) with the linear combinations of fewer Gaussians.\n    //\n    // Note that exponents are all positive, and sorted in ascending order.\n    //\n    UIndex m0 = 0;\n    for (; m0 < gs_orig.size(); ++m0)\n    {\n        if (gs_orig.exponent(m0) >= T(1))\n        {\n            break;\n        }\n    }\n\n    Vector h(2 * m0);\n    const auto w_small = gs_orig.weights().head(m0);   // View\n    const auto p_small = gs_orig.exponents().head(m0); // View\n    h(0)               = arma::sum(w_small);\n    h(1)               = -arma::sum(w_small % p_small);\n    UIndex m           = 1;\n    auto factorial     = T(1);\n    for (; m < m0; ++m)\n    {\n        h(2 * m + 0) = arma::sum(w_small % arma::pow(p_small, 2 * m + 0));\n        h(2 * m + 1) = -arma::sum(w_small % arma::pow(p_small, 2 * m + 1));\n        factorial *= T((2 * m) * (2 * m + 1));\n        if (-h(2 * m + 1) / factorial < eps)\n        {\n            // Taylor expansion converges with the tolerance eps.\n            ++m;\n            break;\n        }\n    }\n\n    //\n    // Construct a Hankel matrix from the sequence h, and solve the linear\n    // equation, H q = b, with b = -h(m:2m-1).\n    //\n    Matrix H(m, m);\n    for (UIndex i = 0; i < m; ++i)\n    {\n        H.col(i) = h.subvec(i, i + m - 1);\n    }\n    Vector b(-h.subvec(m, 2 * m - 1));\n    Vector q(arma::solve(H, b));\n    //\n    // Find the roots of the Prony polynomial,\n    //\n    // q(z) = \\sum_{k=0}^{m-1} q_k z^{k}.\n    //\n    // The roots of q(z) can be obtained as the eigenvalues of the companion\n    // matrix,\n    //\n    //     (0  0  ...  0 -p[0]  )\n    //     (1  0  ...  0 -p[1]  )\n    // C = (0  1  ...  0 -p[2]  )\n    //     (.. .. ...  .. ..    )\n    //     (0  0  ...  1 -p[m-1])\n    //\n    Matrix companion(m, m, arma::fill::zeros);\n    companion.diag(-1).ones();\n    companion.col(m - 1) = -q;\n    Vector gamma(arma::real(arma::eig_gen(companion)));\n\n    // --- Update exponents & weights\n    auto keep = gs_orig.size() - m0;\n    GaussianSum<T> gs(keep + m);\n    gs.exponents_unsafe().head(m)    = -gamma;\n    gs.exponents_unsafe().tail(keep) = gs_orig.exponents().tail(keep);\n    //\n    // Construct Vandermonde matrix from gamma\n    //\n    Matrix V(2 * m, m);\n    for (UIndex i = 0; i < m; ++i)\n    {\n        const auto z = gamma(i);\n        V(0, i)      = T(1);\n        for (UIndex j = 1; j < V.n_rows; ++j)\n        {\n            V(j, i) = V(j - 1, i) * z; // z[i]**j\n        }\n    }\n    //\n    // Solve overdetermined Vandermonde system,\n    //\n    // V(0:2m-1,0:m-1) w(0:m-1) = h(0:2m-1)\n    //\n    // by the least square method.\n    //\n    gs.weights_unsafe().head(m)    = arma::solve(V, h.head(2 * m));\n    gs.weights_unsafe().tail(keep) = gs_orig.weights().tail(keep);\n\n    return gs;\n}\n\n} // namespace mxpfit\n\n#endif /* MXPFIT_MOD_PRONY_REDUCTION_HPP */\n", "meta": {"hexsha": "3d0f3481905a5b734cc8fdf2a6fdf9ef2356dfbf", "size": 9776, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/mod_prony_reduction.hpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "include/mxpfit/mod_prony_reduction.hpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "include/mxpfit/mod_prony_reduction.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7421383648, "max_line_length": 80, "alphanum_fraction": 0.5560556465, "num_tokens": 2903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.40304564567922774}}
{"text": "//=======================================================================\r\n// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, \r\n//\r\n// This file is part of the Boost Graph Library\r\n//\r\n// You should have received a copy of the License Agreement for the\r\n// Boost Graph Library along with the software; see the file LICENSE.\r\n// If not, contact Office of Research, Indiana University,\r\n// Bloomington, IN 47405.\r\n//\r\n// Permission to modify the code and to distribute the code is\r\n// granted, provided the text of this NOTICE is retained, a notice if\r\n// the code was modified is included with the above COPYRIGHT NOTICE\r\n// and with the COPYRIGHT NOTICE in the LICENSE file, and that the\r\n// LICENSE file is distributed with the modified code.\r\n//\r\n// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.\r\n// By way of example, but not limitation, Licensor MAKES NO\r\n// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY\r\n// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS\r\n// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS\r\n// OR OTHER RIGHTS.\r\n//=======================================================================\r\n#include <boost/config.hpp>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <vector>\r\n#include <boost/property_map.hpp>\r\n#include <boost/graph/adjacency_list.hpp>\r\n#include <boost/graph/graphviz.hpp>\r\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\r\n\r\nint\r\nmain()\r\n{\r\n  using namespace boost;\r\n  typedef adjacency_list<vecS, vecS, directedS, no_property,\r\n    property< edge_weight_t, int, property< edge_weight2_t, int > > > Graph;\r\n  const int V = 5;\r\n  typedef std::pair < int, int >Edge;\r\n  Edge edge_array[] =\r\n    { Edge(0, 1), Edge(0, 4), Edge(0, 2), Edge(1, 3), Edge(1, 4),\r\n    Edge(2, 1), Edge(3, 2), Edge(3, 0), Edge(4, 3)\r\n  };\r\n  const std::size_t E = sizeof(edge_array) / sizeof(Edge);\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n  // VC++ can't handle the iterator constructor\r\n  Graph g(V);\r\n  for (std::size_t j = 0; j < E; ++j)\r\n    add_edge(edge_array[j].first, edge_array[j].second, g);\r\n#else\r\n  Graph g(edge_array, edge_array + E, V);\r\n#endif\r\n\r\n  property_map < Graph, edge_weight_t >::type w = get(edge_weight, g);\r\n  int weights[] = { 3, -4, 8, 1, 7, 4, -5, 2, 6 };\r\n  int *wp = weights;\r\n\r\n  graph_traits < Graph >::edge_iterator e, e_end;\r\n  for (boost::tie(e, e_end) = edges(g); e != e_end; ++e)\r\n    w[*e] = *wp++;\r\n\r\n  std::vector < int >d(V, std::numeric_limits < int >::max());\r\n  int D[V][V];\r\n  johnson_all_pairs_shortest_paths(g, D, distance_map(&d[0]));\r\n\r\n  std::cout << \"     \";\r\n  for (int k = 0; k < V; ++k)\r\n    std::cout << std::setw(5) << k;\r\n  std::cout << std::endl;\r\n  for (int i = 0; i < V; ++i) {\r\n    std::cout << i << \" -> \";\r\n    for (int j = 0; j < V; ++j) {\r\n      if (D[i][j] > 20 || D[i][j] < -20)\r\n        std::cout << std::setw(5) << \"inf\";\r\n      else\r\n        std::cout << std::setw(5) << D[i][j];\r\n    }\r\n    std::cout << std::endl;\r\n  }\r\n\r\n  std::ofstream fout(\"figs/johnson-eg.dot\");\r\n  fout << \"digraph A {\\n\"\r\n    << \"  rankdir=LR\\n\"\r\n    << \"size=\\\"5,3\\\"\\n\"\r\n    << \"ratio=\\\"fill\\\"\\n\"\r\n    << \"edge[style=\\\"bold\\\"]\\n\" << \"node[shape=\\\"circle\\\"]\\n\";\r\n\r\n  graph_traits < Graph >::edge_iterator ei, ei_end;\r\n  for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\r\n    fout << source(*ei, g) << \" -> \" << target(*ei, g)\r\n      << \"[label=\" << get(edge_weight, g)[*ei] << \"]\\n\";\r\n\r\n  fout << \"}\\n\";\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "e214da557818cfe8ebc61c6c93895d6f95cb08e9", "size": 3525, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/johnson-eg.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/johnson-eg.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/graph/example/johnson-eg.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9693877551, "max_line_length": 77, "alphanum_fraction": 0.5863829787, "num_tokens": 1025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.618780440773956, "lm_q1q2_score": 0.4030456418826823}}
{"text": "//\n// utils.hpp\n//\n// Copyright (c) 2018 Shion Hosoda\n//\n// This software is released under the MIT License.\n// http://opensource.org/licenses/mit-license.php\n//\n\n#ifndef UTILS\n#define UTILS\n\n#include<stdlib.h>\n#include<math.h>\n#include<cmath>\n#include<iostream>\n#include<vector>\n#include<numeric>\n#include<memory>\n#include<random>\n#include<iomanip>\n#include<fstream>\n#include<limits>\n#include <boost/lexical_cast.hpp>\n#include<Eigen/Dense>\n#include<Eigen/Core>\n#include<Eigen/LU>\n#include <Eigen/Cholesky>\n\ntemplate<class T>\nvoid readCSV(std::string filename, std::vector<std::vector<T> > &matrix, std::vector<std::string> *rowNamesPointer=nullptr, std::vector<std::string> *columnNamesPointer=nullptr){\n    matrix.clear();\n    if(rowNamesPointer != nullptr){\n        (*rowNamesPointer).clear();\n    }\n    if(columnNamesPointer != nullptr){\n        (*columnNamesPointer).clear();\n    }\n    std::ifstream inputText(filename);\n    if(!inputText){\n        std::cout<<\"Cannot open Csvfile\";\n        exit(1);\n    }\n    std::string str;\n    // row\n    for(int i=0; std::getline(inputText,str); i++){\n        std::vector<T> vec;\n        std::string token;\n        std::istringstream stream(str);\n\n        //column name\n        if(i==0 && columnNamesPointer!=nullptr){\n            //column\n            for(int j=0; std::getline(stream,token,','); j++){\n                if(j==0 && rowNamesPointer!=nullptr)continue;\n                (*columnNamesPointer).push_back(token);\n            }\n            continue;\n        }\n        //column\n        for(int j=0; std::getline(stream,token,','); j++){\n            if(j==0 && rowNamesPointer!=nullptr)(*rowNamesPointer).push_back(token);\n            else{\n                try{\n                    vec.push_back(boost::lexical_cast<T>(token));\n                }catch(...){\n                    std::cout<<\"row:\"<<i<<\" column:\"<<j<<\" value:\"<<token<<\" error\";\n                    exit(0);\n                }\n            }\n        }\n        matrix.push_back(vec);\n    }\n}\n\ntemplate<typename T>\nvoid parseCSV2Eigen(std::string filename, Eigen::Matrix<T, Eigen::Dynamic, 1> &eigenVector, std::vector<std::string> *rowNamesPointer=nullptr, std::vector<std::string> *columnNamesPointer=nullptr){\n    std::vector<std::vector<T> > matrix;\n    readCSV<T>(filename, matrix, rowNamesPointer, columnNamesPointer);\n    eigenVector = Eigen::Matrix<T, Eigen::Dynamic, 1>(matrix.size());\n    for (int i = 0; i < matrix.size(); i++){\n        eigenVector(i) = matrix[i][0];\n    }\n}\n\ntemplate<typename T>\nvoid parseCSV2Eigen(std::string filename, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &eigenMatrix, std::vector<std::string> *rowNamesPointer=nullptr, std::vector<std::string> *columnNamesPointer=nullptr){\n    std::vector<std::vector<T> > matrix;\n    readCSV<T>(filename, matrix, rowNamesPointer, columnNamesPointer);\n    eigenMatrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>(matrix.size(), matrix[0].size());\n    for (int i = 0; i < matrix.size(); i++){\n        eigenMatrix.row(i) = Eigen::Matrix<T, Eigen::Dynamic, 1>::Map(&matrix[i][0], matrix[0].size());\n    }\n}\n\ntemplate<class T>\nvoid convertUnique(const std::vector<T> &v) {\n    std::sort(v.begin(), v.end());\n    v.erase(std::unique(v.begin(), v.end()), v.end());\n}\n\ntemplate<typename T>\ndouble logdet(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &matrix){\n    return 2.0 * Eigen::LLT<Eigen::MatrixXd>(matrix).matrixL().toDenseMatrix().diagonal().array().log().sum();\n}\n\ntemplate<typename T>\ndouble logSumExp(const Eigen::Matrix<T, Eigen::Dynamic, 1> &logVector){\n    double constant(logVector.maxCoeff());\n    double sumexp((logVector.array() - constant).array().exp().sum());\n    return log(sumexp) + constant;\n}\n\ntemplate<typename T>\nEigen::VectorXd normalizeWithLogSumExp(const Eigen::Matrix<T, Eigen::Dynamic, 1> &logVector){\n    Eigen::VectorXd resVector = (logVector.array() - logVector.maxCoeff()).array().exp();\n    return resVector/resVector.sum();\n}\n\ntemplate<typename T>\nvoid eraseVectorElement(std::vector<T> &vector, unsigned int idx){\n    vector.erase(vector.begin() + idx);\n}\n\nconst static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, \",\", \"\\n\");\n\ntemplate<typename T>\nvoid outputEigenMatrix(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &matrix, std::string filename){\n    std::ofstream stream(filename);\n    stream<<matrix.format(CSVFormat);\n    stream.close();\n }\n\ntemplate<typename T>\nvoid outputVectorEigenVector(const std::vector<Eigen::Matrix<T, Eigen::Dynamic, 1>> &vectorVector, std::string filename){\n    std::ofstream stream(filename);\n    for(int i=0; i<vectorVector.size(); i++){\n        // Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> tempMatrix(vectorVector[i].transpose());\n        // stream<<tempMatrix.format(CSVFormat);\n        stream<<vectorVector[i].transpose().format(CSVFormat)<<std::endl;\n        // std::cout<<tempMatrix.format(CSVFormat);\n    }\n    stream.close();\n }\n\ntemplate<typename T>\nvoid outputEigenMatrixForDebug(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &matrix, std::string msg){\n    std::ofstream stream;\n    stream.open(\"./check\", std::ios::app);\n    stream<<msg<<std::endl;\n    stream<<matrix.format(CSVFormat);\n    stream<<std::endl;\n    stream.close();\n}\n\ntemplate<typename T>\nvoid outputVector(const std::vector<T> &vector, std::string filename){\n    std::ofstream stream;\n    stream.open(filename, std::ios::out);\n    stream<<std::setprecision(std::numeric_limits<double>::max_digits10);\n    for(int i=0;i<vector.size();i++){\n        stream<<vector[i];\n        stream<<std::endl;\n    }\n    stream.close();\n}\n\n\n#endif\n", "meta": {"hexsha": "7b39cbe711e1ba1b5c8a449da8b205cfece998fc", "size": 5627, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/include/utils.hpp", "max_stars_repo_name": "shion-h/Umibato", "max_stars_repo_head_hexsha": "20718f75a3e4549f26315984691409b49d9d75d5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-01-30T06:02:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T17:02:22.000Z", "max_issues_repo_path": "src/include/utils.hpp", "max_issues_repo_name": "shion-h/Umibato", "max_issues_repo_head_hexsha": "20718f75a3e4549f26315984691409b49d9d75d5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/include/utils.hpp", "max_forks_repo_name": "shion-h/Umibato", "max_forks_repo_head_hexsha": "20718f75a3e4549f26315984691409b49d9d75d5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-17T16:37:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T16:37:21.000Z", "avg_line_length": 33.1, "max_line_length": 210, "alphanum_fraction": 0.6417273858, "num_tokens": 1397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.6513548511303338, "lm_q1q2_score": 0.4030456373035888}}
{"text": "/*\n Deterministic Bayesian Sparse Linear Mixed Model (DBSLMM)\n Copyright (C) 2019  Sheng Yang and Xiang Zhou\n \n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n \n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <vector>\n#include <string>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <armadillo>\n#include \"../include/calc_asymptotic_variance.hpp\"\n#include \"../include/dbslmm.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char * argv[])\n{\n  DBSLMM cDB;\n  PARAM cPar;\n  cDB.Assign(argc, argv, cPar);\n  \n  //int nchr = 22; //number of chromosomes\n  int nchr = 1;\n  //initialize a arma::field to store outputs for var calcs!\n  \n  arma::field < arma::mat> training(5000, 5); //5000 is always bigger than the number of LD BLocks in the genome\n  arma::field < arma::mat> test(5000, 5);\n  double sigma2_s = cPar.h / (double)cPar.nsnp;\n  unsigned int row_total = 0; //initialize counter for number of rows in field\n  for (int i = 0; i < nchr; ++i){\n    //int i = 0;\n    int chr = i + 1;\n    std::string filetr (\"Chr\" + std::to_string(chr) + \"_training.dat\");\n    std::string filete (\"Chr\" + std::to_string(chr) + \"_test.dat\");\n    arma::field <arma::mat > tr;\n    arma::field <arma::mat > te; \n    tr.load(filetr);\n    cout << filetr << endl;\n    cout << \"number of elements in tr: \" << tr.n_elem << endl;\n    cout << \"number of rows in tr: \" << tr.n_rows << endl;\n    cout << \"number of columns in tr: \" << tr.n_cols << endl;\n    \n    te.load(filete);\n    cout << filete << endl; \n    cout << \"number of elements in te: \" << te.n_elem << endl;\n    cout << \"number of rows in te: \" << te.n_rows << endl;\n    cout << \"number of columns in te: \" << te.n_cols << endl;\n    \n    unsigned int rows_in_block = te.n_rows;\n    training.rows(row_total, row_total+rows_in_block - 1) = tr;\n    test.rows(row_total, row_total+rows_in_block - 1) = te;\n    row_total = row_total + rows_in_block;\n    \n//    training.row(i) = assembleMatrices(tr);//store in a two-dimensional field\n//    test.row(i) = assembleMatrices(te);\n  }\n  training = training.rows(0, row_total - 1);\n  cout << \"training has this many rows: \" << row_total << endl;\n  test = test.rows(0, row_total - 1);\n  cout << \"test has this many rows: \" << row_total << endl;  \n  //var calcs here! \n  //1. assemble genome-wide matrices from \"training\" & \"test\"\n  arma::field < arma::mat > mats_training = assembleMatrices(training);\n  arma::field < arma::mat > mats_test = assembleMatrices(test);\n  //2. input matrices to calc_asymptotic_variance\n  cout << \"Starting asymptotic variance calculations...\" << endl; \n  arma::mat vv = calc_asymptotic_variance(mats_training(2), //Sigma_ll\n                                          arma::trans(mats_training(1)), // Sigma_ls \n                                          mats_training(0), //Sigma_ss\n                                          training.col(0),\n                                          sigma2_s, \n                                          cPar.n, \n                                          mats_test(4), //X_l\n                                          mats_test(3)); // X_s\n  //3. write diagonal of var to a csv file\n  arma::vec vd = diagvec(vv);\n  vd.save(\"out.csv\", csv_ascii);\n\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "cf77e381f229a224ddba86189faacbe915804f93", "size": 3827, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "fboehm/DBSLMMread", "max_stars_repo_head_hexsha": "23626971f492228ba11e08d3b6b848ffbf942dc3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "fboehm/DBSLMMread", "max_issues_repo_head_hexsha": "23626971f492228ba11e08d3b6b848ffbf942dc3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "fboehm/DBSLMMread", "max_forks_repo_head_hexsha": "23626971f492228ba11e08d3b6b848ffbf942dc3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.6565656566, "max_line_length": 112, "alphanum_fraction": 0.6221583486, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.40303249787012624}}
{"text": "#include \"akumuli_def.h\"\n#include \"anomalydetector.h\"\n#include \"hashfnfamily.h\"\n#include \"queryprocessor_framework.h\"\n\n#include <random>\n#include <stdexcept>\n\n#include <boost/exception/all.hpp>\n\nnamespace Akumuli {\nnamespace QP {\n\n//                          //\n//      CountingSketch      //\n//                          //\n\nstruct CountingSketch {\n    HashFnFamily const& hashes_;\n    const u32 N;\n    const u32 K;\n    double sum_;\n    std::vector<std::vector<double>> tables_;\n\n    CountingSketch(HashFnFamily const& hf)\n        : hashes_(hf)\n        , N(hf.N)\n        , K(hf.K)\n        , sum_(0.0)\n    {\n        for (u32 i = 0u; i < N; i++) {\n            std::vector<double> row;\n            row.resize(K, 0.0);\n            tables_.push_back(std::move(row));\n        }\n    }\n\n    CountingSketch(CountingSketch const& cs)\n        : hashes_(cs.hashes_)\n        , N(cs.N)\n        , K(cs.K)\n        , sum_(cs.sum_)\n    {\n        for (auto ixrow = 0u; ixrow < N; ixrow++) {\n            std::vector<double> row;\n            row.resize(K, 0.0);\n            std::vector<double> const& rcs = cs.tables_[ixrow];\n            for (auto col = 0u; col < K; col++) {\n                row[col] = rcs[col];\n            }\n            tables_.push_back(std::move(row));\n        }\n    }\n\n    void _update_sum() {\n        sum_ = 0.0;\n        for (auto val: tables_[0]) {\n            sum_ += val;\n        }\n    }\n\n    void add(u64 id, double value) {\n        sum_ += value;\n        for (u32 i = 0; i < N; i++) {\n            // calculate hash from id to K\n            u32 hash = hashes_.hash(i, id);\n            tables_[i][hash] += value;\n        }\n    }\n\n    //! Second moment estimator\n    double estimateF2() const {\n        std::vector<double> results;\n        auto f = 1./(K - 1);\n        for (u32 i = 0u; i < N; i++) {\n            double rowsum = std::accumulate(tables_[i].begin(), tables_[i].end(), 0.0, [](double acc, double val) {\n                return acc + val*val;\n            });\n            double res = K*f*sqrt(rowsum) - f*sum_*sum_;\n            results.push_back(res);\n        }\n        std::sort(results.begin(), results.end());\n        return results[N/2];\n    }\n\n    //! Unbiased value estimator\n    double estimate(u64 id) const {\n        std::vector<double> results;\n        for (u32 i = 0u; i < N; i++) {\n            u32 hash = hashes_.hash(i, id);\n            double value = tables_[i][hash];\n            double estimate = (value - sum_/K)/(1. - 1./K);\n            results.push_back(estimate);\n        }\n        std::sort(results.begin(), results.end());\n        return results[N/2];\n    }\n\n    //! current sketch <- absolute difference between two arguments\n    void diff(CountingSketch const& lhs, CountingSketch const& rhs) {\n        for (auto ixrow = 0u; ixrow < N; ixrow++) {\n            std::vector<double>& row = tables_[ixrow];\n            std::vector<double> const& lrow = lhs.tables_[ixrow];\n            std::vector<double> const& rrow = rhs.tables_[ixrow];\n            for (auto col = 0u; col < K; col++) {\n                row[col] = std::fabs(lrow[col] - rrow[col]);\n            }\n        }\n        _update_sum();\n    }\n\n    //! Add sketch\n    void add(CountingSketch const& val) {\n        for (auto ixrow = 0u; ixrow < N; ixrow++) {\n            std::vector<double>& row = tables_[ixrow];\n            std::vector<double> const& rval = val.tables_[ixrow];\n            for (auto col = 0u; col < K; col++) {\n                row[col] = row[col] + rval[col];\n            }\n        }\n        _update_sum();\n    }\n\n    //! Substract sketch\n    void sub(CountingSketch const& val) {\n        for (auto ixrow = 0u; ixrow < N; ixrow++) {\n            std::vector<double>& row = tables_[ixrow];\n            std::vector<double> const& rval = val.tables_[ixrow];\n            for (auto col = 0u; col < K; col++) {\n                row[col] = row[col] - rval[col];\n            }\n        }\n        _update_sum();\n    }\n\n    //! Multiply sketch by value\n    void mul(double value) {\n        for (auto ixrow = 0u; ixrow < N; ixrow++) {\n            std::vector<double>& row = tables_[ixrow];\n            for (auto col = 0u; col < K; col++) {\n                row[col] *= value;\n            }\n        }\n        _update_sum();\n    }\n\n    //! Multiply by another sketch\n    void mul(CountingSketch const& value) {\n        for (auto ixrow = 0u; ixrow < N; ixrow++) {\n            std::vector<double>& row = tables_[ixrow];\n            std::vector<double> const& rval = value.tables_[ixrow];\n            for (auto col = 0u; col < K; col++) {\n                row[col] = row[col] * rval[col];\n            }\n        }\n        _update_sum();\n    }\n\n    //! Divide by another sketch\n    void div(CountingSketch const& value) {\n        for (auto ixrow = 0u; ixrow < N; ixrow++) {\n            std::vector<double>& row = tables_[ixrow];\n            std::vector<double> const& rval = value.tables_[ixrow];\n            for (auto col = 0u; col < K; col++) {\n                row[col] = row[col] / rval[col];\n            }\n        }\n        _update_sum();\n    }\n};\n\n\n//                          //\n//      PreciseCounter      //\n//                          //\n\nstruct PreciseCounter {\n    std::unordered_map<u64, double> table_;\n\n    //! C-tor. Parameter `hf` is unused for the sake of interface unification.\n    PreciseCounter(HashFnFamily const& hf) {\n    }\n\n    PreciseCounter(PreciseCounter const& cs)\n        : table_(cs.table_)\n    {\n    }\n\n    void add(u64 id, double value) {\n        table_[id] += value;\n    }\n\n    //! Unbiased value estimator\n    double estimate(u64 id) const {\n        auto it = table_.find(id);\n        if (it != table_.end()) {\n            return it->second;\n        }\n        return 0.;\n    }\n\n    //! Second moment estimator\n    double estimateF2() const {\n        double sum = std::accumulate(table_.begin(), table_.end(), 0.0,\n                                     [](double acc, std::pair<u64, double> pval) {\n            return acc + pval.second*pval.second;\n        });\n        return sqrt(sum);\n    }\n\n    //! current sketch <- absolute difference between two arguments\n    void diff(PreciseCounter const& lhs, PreciseCounter const& rhs) {\n        const std::unordered_map<u64, double> *small, *large;\n        if (lhs.table_.size() < rhs.table_.size()) {\n            small = &lhs.table_;\n            large = &rhs.table_;\n        } else {\n            small = &rhs.table_;\n            large = &lhs.table_;\n        }\n        table_.clear();\n        // Scan largest\n        for (auto it = large->begin(); it != large->end(); it++) {\n            auto small_it = small->find(it->first);\n            double val = 0.;\n            if (small_it != small->end()) {\n                val = small_it->second;\n            }\n            table_[it->first] = std::fabs(it->second - val);\n        }\n    }\n\n    //! Add sketch\n    void add(PreciseCounter const& val) {\n        for(auto it = val.table_.begin(); it != val.table_.end(); it++) {\n            table_[it->first] += it->second;\n        }\n    }\n\n    //! Substract sketch\n    void sub(PreciseCounter const& val) {\n        for(auto it = val.table_.begin(); it != val.table_.end(); it++) {\n            table_[it->first] -= it->second;\n        }\n    }\n\n    //! Multiply sketch by value\n    void mul(double value) {\n        for(auto it = table_.begin(); it != table_.end(); it++) {\n            it->second *= value;\n        }\n    }\n\n    //! Multiply\n    void mul(PreciseCounter const& val) {\n        for(auto it = val.table_.begin(); it != val.table_.end(); it++) {\n            table_[it->first] *= it->second;\n        }\n    }\n\n    //! Divide\n    void div(PreciseCounter const& val) {\n        for(auto it = val.table_.begin(); it != val.table_.end(); it++) {\n            table_[it->first] /= it->second;\n        }\n    }\n};\n\n\n//                              //\n//      SMASlidingWindow        //\n//                              //\n\nstatic double checked_inv(u32 depth) {\n    if (depth == 0) {\n        NodeException err(\"Sliding window depth can't be zero.\");\n        BOOST_THROW_EXCEPTION(err);\n    }\n    return 1.0/depth;\n}\n\n//! Simple moving average implementation\ntemplate<class Frame>\nstruct SMASlidingWindow {\n    typedef std::unique_ptr<Frame> PFrame;\n    PFrame             sma_;\n    const u32          depth_;\n    const double       mul_;\n    std::deque<PFrame> queue_;\n\n    SMASlidingWindow(u32 depth)\n        : depth_(depth)\n        , mul_(checked_inv(depth))\n    {\n    }\n\n    void add(PFrame sketch) {\n        if (!sma_) {\n            sma_.reset(new Frame(*sketch));\n            queue_.push_back(std::move(sketch));\n        } else {\n            sma_->add(*sketch);\n            queue_.push_back(std::move(sketch));\n            if (queue_.size() > depth_) {\n                auto removed = std::move(queue_.front());\n                queue_.pop_front();\n                sma_->sub(*removed);\n            }\n        }\n    }\n\n    PFrame forecast() const {\n        PFrame res;\n        if (queue_.size() < depth_) {\n            // return empty response\n            return std::move(res);\n        }\n        res.reset(new Frame(*sma_));\n        res->mul(mul_);\n        return std::move(res);\n    }\n};\n\n\n//                              //\n//      EWMASlidingWindow       //\n//                              //\n\n\n//! Exponentialy weighted moving average implementation\ntemplate<class Frame>\nstruct EWMASlidingWindow {\n    typedef std::unique_ptr<Frame> PFrame;\n    PFrame               ewma_;\n    const double         decay_;\n    int                  counter_;\n\n    EWMASlidingWindow(double alpha)\n        : decay_(alpha)\n        , counter_(0)\n    {\n    }\n\n    void add(PFrame sketch) {\n        if (!ewma_) {\n            ewma_.reset(new Frame(*sketch));\n            counter_ = 1;\n        } else if (counter_ < 10) {\n            ewma_->add(*sketch);\n            counter_++;\n            if (counter_ == 10) {\n                ewma_->mul(0.1);\n            }\n        } else {\n            sketch->mul(decay_);\n            ewma_->mul(1.0 - decay_);\n            ewma_->add(*sketch);\n        }\n    }\n\n    PFrame forecast() const {\n        PFrame res;\n        if (counter_ < 10) {\n            // return empty response\n            return std::move(res);\n        }\n        res.reset(new Frame(*ewma_));\n        return std::move(res);\n    }\n};\n\n\n//                                          //\n//      DoubleExpSmoothingSlidingWindow     //\n//                                          //\n\n\n//! Holt-Winters moving average implementation\ntemplate<class Frame>\nstruct DoubleExpSmoothingSlidingWindow {\n    typedef std::unique_ptr<Frame> PFrame;\n    PFrame               baseline_;\n    PFrame               slope_;\n    const double         alpha_;\n    const double         beta_;\n    int                  counter_;\n\n    /** C-tor\n      * @param alpha smoothing coefficient\n      */\n    DoubleExpSmoothingSlidingWindow(double alpha, double beta)\n        : alpha_(alpha)\n        , beta_(beta)\n        , counter_(0)\n    {\n    }\n\n    void add(PFrame value) {\n        switch(counter_) {\n        case 0:\n            std::swap(baseline_, value);\n            counter_ = 1;\n            break;\n        case 1:\n            slope_.reset(new Frame(*value));\n            slope_->sub(*baseline_);\n            baseline_ = std::move(value);\n            counter_ = 2;\n            break;\n        default: {\n                PFrame old_baseline(new Frame(*baseline_));\n                PFrame old_slope = std::move(slope_);\n                // Calculate new baseline\n                {\n                    PFrame new_baseline = std::move(value);\n                    new_baseline->mul(alpha_);\n                    old_baseline->add(*old_slope);\n                    old_baseline->mul(1.0 - alpha_);\n                    new_baseline->add(*old_baseline);\n                    std::swap(new_baseline, baseline_);\n                    std::swap(new_baseline, old_baseline);\n                }\n                // Calculate new slope\n                slope_.reset(new Frame(*baseline_));\n                slope_->sub(*old_baseline);\n                slope_->mul(beta_);\n                old_slope->mul(1.0 - beta_);\n                slope_->add(*old_slope);\n                break;\n            }\n        };\n    }\n\n    PFrame forecast() const {\n        PFrame res;\n        if (counter_ < 2) {\n            // return empty response\n            return std::move(res);\n        }\n        res.reset(new Frame(*baseline_));\n        res->add(*slope_);\n        return std::move(res);\n    }\n};\n\n\n//                                      //\n//      HoltWintersSlidingWindow        //\n//                                      //\n\n/** Holt-Winters implementation.\n  * http://static.usenix.org/events/lisa00/full_papers/brutlag/brutlag_html/\n  */\ntemplate<class Frame>\nstruct HoltWintersSlidingWindow {\n    typedef std::unique_ptr<Frame> PFrame;\n    PFrame               baseline_;\n    PFrame               slope_;\n    std::deque<PFrame>   seasonal_;\n    const double         alpha_;\n    const double         beta_;\n    const double         gamma_;\n    int                  counter_;\n    int                  period_;\n\n    HoltWintersSlidingWindow(double alpha, double beta, double gamma, int period)\n        : alpha_(alpha)\n        , beta_(beta)\n        , gamma_(gamma)\n        , counter_(0)\n        , period_(period)\n    {\n    }\n\n    void add(PFrame value) {\n        if (counter_ == 0) {\n            baseline_.reset(new Frame(*value));\n            seasonal_.push_back(std::move(value));\n        } else if (counter_ == 1) {\n            slope_.reset(new Frame(*value));\n            slope_->sub(*baseline_);\n            baseline_.reset(new Frame(*value));\n            seasonal_.push_back(std::move(value));\n        } else if (counter_ < period_) {\n            seasonal_.push_back(std::move(value));\n        } else {\n            PFrame seasonal = std::move(seasonal_.front());\n            PFrame old_baseline;\n            seasonal_.pop_front();\n            // Calculate baseline\n            {\n                PFrame new_baseline(new Frame(*value));\n                PFrame old_slope(new Frame(*slope_));\n                new_baseline->sub(*seasonal);\n                new_baseline->mul(alpha_);\n                old_slope->add(*baseline_);\n                old_slope->mul(1.0 - alpha_);\n                new_baseline->add(*old_slope);\n                old_baseline = std::move(baseline_);\n                std::swap(new_baseline, baseline_);\n            }\n            // Calculate slope\n            {\n                PFrame new_slope(new Frame(*baseline_));\n                PFrame old_slope = std::move(slope_);\n                new_slope->sub(*old_baseline);\n                new_slope->mul(beta_);\n                old_slope->mul(1.0 - beta_);\n                new_slope->add(*old_slope);\n                std::swap(new_slope, slope_);\n            }\n            // Calculate seasonality\n            {\n                value->sub(*baseline_);\n                value->mul(gamma_);\n                seasonal->mul(1.0 - gamma_);\n                value->add(*seasonal);\n                seasonal_.push_back(std::move(value));\n            }\n        }\n        counter_++;\n    }\n\n    PFrame forecast() const {\n        PFrame res;\n        if (counter_ < period_) {\n            // return empty response\n            return std::move(res);\n        }\n        res.reset(new Frame(*baseline_));\n        res->add(*slope_);\n        res->add(*seasonal_.back());\n        return std::move(res);\n    }\n};\n\n\n//                                  //\n//      AnomalyDetectorPipeline     //\n//                                  //\n\ntemplate<\n    class Frame,                        // Frame type\n    template<class F> class FMethod     // Forecasting method type\n>\nstruct AnomalyDetectorPipeline : AnomalyDetectorIface {\n    typedef FMethod<Frame>                  FcastMethod;\n    typedef std::unique_ptr<Frame>          PFrame ;\n    typedef std::unique_ptr<FcastMethod>    PSlidingWindow;\n\n    HashFnFamily                hashes_;\n    const u32              N;\n    const u32              K;\n    PFrame                      current_;\n    PFrame                      error_;\n    double                      F2_;\n    double                      threshold_;\n    PSlidingWindow              sliding_window_;\n\n    AnomalyDetectorPipeline(u32 N, u32 K, double threshold, PSlidingWindow swindow)\n        : hashes_(N, K)\n        , N(N)\n        , K(K)\n        , F2_(0.0)\n        , threshold_(threshold)\n        , sliding_window_(std::move(swindow))\n    {\n        current_.reset(new Frame(hashes_));\n    }\n\n    void add(u64 id, double value) {\n        current_->add(id, value);\n    }\n\n    //! Returns true if series is anomalous (approx)\n    bool is_anomaly_candidate(u64 id) const {\n        if (error_) {\n            double estimate = error_->estimate(id);\n            return estimate > F2_;\n        }\n        return false;\n    }\n\n    void move_sliding_window() {\n        PFrame forecast = std::move(sliding_window_->forecast());\n        if (forecast) {\n            error_ = std::move(calculate_error(forecast, current_));\n            F2_ = sqrt(error_->estimateF2())*threshold_;\n        }\n        sliding_window_->add(std::move(current_));\n        current_.reset(new Frame(hashes_));\n    }\n\n    PFrame calculate_error(const PFrame &forecast, const PFrame &actual) {\n        PFrame res;\n        res.reset(new Frame(hashes_));\n        res->diff(*forecast, *actual);\n        return std::move(res);\n    }\n};\n\ntemplate<class Window, class Detector>\nstd::unique_ptr<AnomalyDetectorIface> create_detector(u32 N,\n                                                      u32 K,\n                                                      double threshold,\n                                                      u32 window_size)\n{\n    std::unique_ptr<AnomalyDetectorIface> result;\n    std::unique_ptr<Window> window(new Window(window_size));\n    result.reset(new Detector(N, K, threshold, std::move(window)));\n    return std::move(result);\n}\n\n//! Create approximate anomaly detector based on simple moving-average smothing\nstd::unique_ptr<AnomalyDetectorIface>\n    AnomalyDetectorUtil::create_approx_sma(u32 N,\n                                           u32 K,\n                                           double threshold,\n                                           u32 window_size)\n{\n    typedef AnomalyDetectorPipeline<CountingSketch, SMASlidingWindow>   Detector;\n    typedef SMASlidingWindow<CountingSketch>                            Window;\n    std::unique_ptr<AnomalyDetectorIface> result;\n    std::unique_ptr<Window> window(new Window(window_size));\n    result.reset(new Detector(N, K, threshold, std::move(window)));\n    return std::move(result);\n}\n\n//! Create precise anomaly detector based on simple moving-average smothing\nstd::unique_ptr<AnomalyDetectorIface>\n    AnomalyDetectorUtil::create_precise_sma(double threshold,\n                                            u32 window_size)\n{\n    typedef AnomalyDetectorPipeline<PreciseCounter, SMASlidingWindow>   Detector;\n    typedef SMASlidingWindow<PreciseCounter>                            Window;\n    std::unique_ptr<AnomalyDetectorIface> result;\n    std::unique_ptr<Window> window(new Window(window_size));\n    result.reset(new Detector(1, 8, threshold, std::move(window)));\n    return std::move(result);\n}\n\n//! Create approximate anomaly detector based on simple moving-average smothing or EWMA\nstd::unique_ptr<AnomalyDetectorIface>\n    AnomalyDetectorUtil::create_approx_ewma(u32 N,\n                                            u32 K,\n                                            double threshold,\n                                            double alpha)\n{\n    typedef AnomalyDetectorPipeline<CountingSketch, EWMASlidingWindow>  Detector;\n    typedef EWMASlidingWindow<CountingSketch>                           Window;\n    std::unique_ptr<AnomalyDetectorIface> result;\n    std::unique_ptr<Window> window(new Window(alpha));\n    result.reset(new Detector(N, K, threshold, std::move(window)));\n    return std::move(result);\n}\n\n//! Create precise anomaly detector based on simple moving-average smothing or EWMA\nstd::unique_ptr<AnomalyDetectorIface>\n    AnomalyDetectorUtil::create_precise_ewma(double threshold,\n                                             double alpha)\n{\n    typedef AnomalyDetectorPipeline<PreciseCounter, EWMASlidingWindow>  Detector;\n    typedef EWMASlidingWindow<PreciseCounter>                           Window;\n    std::unique_ptr<AnomalyDetectorIface> result;\n    std::unique_ptr<Window> window(new Window(alpha));\n    result.reset(new Detector(1, 8, threshold, std::move(window)));\n    return std::move(result);\n}\n\n//! Create precise anomaly detector based on simple moving-average smothing or EWMA\nstd::unique_ptr<AnomalyDetectorIface>\n    AnomalyDetectorUtil::create_precise_double_exp_smoothing(\n                                             double threshold,\n                                             double alpha,\n                                             double beta)\n{\n    typedef AnomalyDetectorPipeline<PreciseCounter, DoubleExpSmoothingSlidingWindow>  Detector;\n    typedef DoubleExpSmoothingSlidingWindow<PreciseCounter>                           Window;\n    std::unique_ptr<AnomalyDetectorIface> result;\n    std::unique_ptr<Window> window(new Window(alpha, beta));\n    result.reset(new Detector(1, 8, threshold, std::move(window)));\n    return std::move(result);\n}\n\nstd::unique_ptr<AnomalyDetectorIface>\n    AnomalyDetectorUtil::create_approx_double_exp_smoothing(\n                                         u32 N,\n                                         u32 K,\n                                         double threshold,\n                                         double alpha,\n                                         double beta)\n{\n    typedef AnomalyDetectorPipeline<CountingSketch, DoubleExpSmoothingSlidingWindow>  Detector;\n    typedef DoubleExpSmoothingSlidingWindow<CountingSketch>                           Window;\n    std::unique_ptr<AnomalyDetectorIface> result;\n    std::unique_ptr<Window> window(new Window(alpha, beta));\n    result.reset(new Detector(N, K, threshold, std::move(window)));\n    return std::move(result);\n}\n\n//! Create precise anomaly detector based on simple moving-average smothing or EWMA\nstd::unique_ptr<AnomalyDetectorIface>\n    AnomalyDetectorUtil::create_precise_holt_winters(\n                                             double threshold,\n                                             double alpha,\n                                             double beta,\n                                             double gamma,\n                                             int period)\n{\n    typedef AnomalyDetectorPipeline<PreciseCounter, HoltWintersSlidingWindow>         Detector;\n    typedef HoltWintersSlidingWindow<PreciseCounter>                                  Window;\n    std::unique_ptr<AnomalyDetectorIface> result;\n    std::unique_ptr<Window> window(new Window(alpha, beta, gamma, period));\n    result.reset(new Detector(1, 8, threshold, std::move(window)));\n    return std::move(result);\n}\n\n//! Create precise anomaly detector based on simple moving-average smothing or EWMA\nstd::unique_ptr<AnomalyDetectorIface>\n    AnomalyDetectorUtil::create_approx_holt_winters(\n                                             u32 N,\n                                             u32 K,\n                                             double threshold,\n                                             double alpha,\n                                             double beta,\n                                             double gamma,\n                                             int period)\n{\n    typedef AnomalyDetectorPipeline<PreciseCounter, HoltWintersSlidingWindow>         Detector;\n    typedef HoltWintersSlidingWindow<PreciseCounter>                                  Window;\n    std::unique_ptr<AnomalyDetectorIface> result;\n    std::unique_ptr<Window> window(new Window(alpha, beta, gamma, period));\n    result.reset(new Detector(N, K, threshold, std::move(window)));\n    return std::move(result);\n}\n\n}\n}\n\n", "meta": {"hexsha": "6dd2ec3aeb128ff395d1ce91df5a09bac7b40d31", "size": 24018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libakumuli/anomalydetector.cpp", "max_stars_repo_name": "adulau/Akumuli", "max_stars_repo_head_hexsha": "7fd0e5934ef018575299517eea02702778ee6e6c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1094.0, "max_stars_repo_stars_event_min_datetime": "2015-01-03T13:40:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:28:25.000Z", "max_issues_repo_path": "libakumuli/anomalydetector.cpp", "max_issues_repo_name": "adulau/Akumuli", "max_issues_repo_head_hexsha": "7fd0e5934ef018575299517eea02702778ee6e6c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 193.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T09:25:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-02T08:54:35.000Z", "max_forks_repo_path": "libakumuli/anomalydetector.cpp", "max_forks_repo_name": "adulau/Akumuli", "max_forks_repo_head_hexsha": "7fd0e5934ef018575299517eea02702778ee6e6c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 124.0, "max_forks_repo_forks_event_min_datetime": "2015-02-03T14:57:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T14:27:37.000Z", "avg_line_length": 32.4567567568, "max_line_length": 115, "alphanum_fraction": 0.5147389458, "num_tokens": 5345, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4030324852418331}}
{"text": "/*\n *            Copyright 2009-2017 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include <votca/xtp/numerical_integrations.h>\n#include <votca/ctp/logger.h>\n#include <votca/xtp/espfit.h>\n#include <votca/xtp/aomatrix.h>\n#include <votca/tools/linalg.h>\n//#include <boost/progress.hpp>\n\n#include <math.h>\n#include <votca/tools/constants.h>\n\nusing namespace votca::tools;\n\n\nnamespace votca { namespace xtp {\n    namespace ub = boost::numeric::ublas;\n\n\n\n\n\nvoid Espfit::Fit2Density(std::vector< ctp::QMAtom* >& _atomlist, ub::matrix<double> &_dmat, AOBasis &_basis,BasisSet &bs,string gridsize) {\n\n\n    // setting up grid\n    Grid _grid;\n    _grid.setAtomlist(&_atomlist);\n    _grid.setupCHELPgrid();\n    //_grid.printGridtoxyzfile(\"grid.xyz\");\n    CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() <<  \" Done setting up CHELPG grid with \" << _grid.getsize() << \" points \" << endl;\n\n    // Calculating nuclear potential at gridpoints\n\n    ub::vector<double> _ESPatGrid = ub::zero_vector<double>(_grid.getsize());\n\n    AOOverlap overlap;\n    overlap.Fill(_basis);\n    ub::vector<double> DMATasarray=_dmat.data();\n    ub::vector<double> AOOasarray=overlap.Matrix().data();\n    double N_comp=0.0;\n    #pragma omp parallel for reduction(+:N_comp)\n    for ( unsigned _i =0; _i < DMATasarray.size(); _i++ ){\n            N_comp =N_comp+ DMATasarray(_i)*AOOasarray(_i);\n        }\n\n    NumericalIntegration numway;\n\n    numway.GridSetup(gridsize,&bs,_atomlist,&_basis);\n    CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Calculate Densities at Numerical Grid with gridsize \"<<gridsize  << flush;\n    double N=numway.IntegrateDensity(_dmat);\n    CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Calculated Densities at Numerical Grid, Number of electrons is \"<< N << flush;\n\n    if(std::abs(N-N_comp)>0.001){\n        CTP_LOG(ctp::logDEBUG, *_log) <<\"=======================\" << flush;\n        CTP_LOG(ctp::logDEBUG, *_log) <<\"WARNING: Calculated Densities at Numerical Grid, Number of electrons \"<< N <<\" is far away from the the real value \"<< N_comp<<\", you should increase the accuracy of the integration grid.\"<< flush;\n        N=N_comp;\n        CTP_LOG(ctp::logDEBUG, *_log) <<\"WARNING: Electronnumber set to \"<< N << flush;\n        CTP_LOG(ctp::logDEBUG, *_log) <<\"=======================\" << flush;\n    }\n\n    double netcharge=getNetcharge( _atomlist,N );\n\n    CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Calculating ESP at CHELPG grid points\"  << flush;\n    //boost::progress_display show_progress( _grid.getsize() );\n    #pragma omp parallel for\n    for ( int i = 0 ; i < _grid.getsize(); i++){\n        _ESPatGrid(i)=numway.IntegratePotential(_grid.getGrid()[i]*tools::conv::nm2bohr);\n        //++show_progress;\n    }\n\n    CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Electron contribution calculated\"  << flush;\n    if (!_do_Transition){\n    ub::vector<double> _NucPatGrid = EvalNuclearPotential(  _atomlist,  _grid );\n    _ESPatGrid += _NucPatGrid;\n    }\n\n    std::vector< tools::vec > _fitcenters;\n\n    for ( unsigned j = 0; j < _atomlist.size(); j++){\n       tools::vec _pos=_atomlist[j]->getPos()*tools::conv::ang2nm;\n      _fitcenters.push_back(_pos);\n    }\n\n    std::vector<double> _charges = FitPartialCharges(_fitcenters,_grid, _ESPatGrid, netcharge);\n\n    //Write charges to qmatoms\n    for ( unsigned _i =0 ; _i < _atomlist.size(); _i++){\n        _atomlist[_i]->charge=_charges[_i];\n    }\n    return;\n    }\n\n\nub::vector<double> Espfit::EvalNuclearPotential(std::vector< ctp::QMAtom* >& _atoms, Grid _grid) {\n    ub::vector<double> _NucPatGrid = ub::zero_vector<double>(_grid.getsize());\n\n    double Znuc=0.0;\n    const std::vector< vec >& _gridpoints = _grid.getGrid();\n    CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Calculating ESP of nuclei at CHELPG grid points\" << flush;\n\n    for (unsigned i = 0; i < _gridpoints.size(); i++) {\n        for (unsigned j = 0; j < _atoms.size(); j++) {\n            vec posatom=_atoms[j]->getPos()*tools::conv::ang2nm;\n            if (_ECP) {\n                Znuc = _elements.getNucCrgECP(_atoms[j]->type);\n            } else {\n                Znuc = _elements.getNucCrg(_atoms[j]->type);\n            }\n            double dist_j = tools::abs(_gridpoints[i]-posatom) * tools::conv::nm2bohr;\n            _NucPatGrid(i) += Znuc / dist_j;\n        }\n\n    }\n    return _NucPatGrid;\n}\n\ndouble Espfit::getNetcharge( std::vector< ctp::QMAtom* >& _atoms, double N ){\n    double netcharge=0.0;\n    if( std::abs(N)<0.05){\n        //CTP_LOG(ctp::logDEBUG, *_log) << \"Number of Electrons is \"<<N<< \" transitiondensity is used for fit\"  << flush;\n        _do_Transition=true;\n    }\n    else{\n    double Znuc_ECP = 0.0;\n    double Znuc=0.0;\n    for ( unsigned j = 0; j < _atoms.size(); j++){\n           Znuc_ECP += _elements.getNucCrgECP(_atoms[j]->type);\n           Znuc+= _elements.getNucCrg(_atoms[j]->type);\n    }\n\n    if (_ECP){\n        if (std::abs(Znuc_ECP-N)<4){\n            CTP_LOG(ctp::logDEBUG, *_log) <<\"Number of Electrons minus ECP_Nucleus charge is \"<<Znuc_ECP-N<< \" you use ECPs, sounds good\"  << flush;\n        }\n        else if (std::abs(Znuc-N)<4){\n            CTP_LOG(ctp::logDEBUG, *_log) <<\"Number of Electrons minus real Nucleus charge is \"<<Znuc-N<< \" you are sure you want ECPs?\"  << flush;\n        }\n        else{\n            CTP_LOG(ctp::logDEBUG, *_log) <<\"Warning: Your molecule is highly ionized and you want ECPs, sounds interesting\" << flush;\n        }\n        netcharge=Znuc_ECP-N;\n    }\n    else{\n        if (std::abs(Znuc-N)<4){\n            CTP_LOG(ctp::logDEBUG, *_log) <<\"Number of Electrons minus Nucleus charge is \"<<Znuc-N<< \" you probably do not use ECPs, if you do use ECPs please use the option. Otherwise you are fine\"  << flush;\n        }\n        else if(std::abs(Znuc_ECP-N)<4){\n            CTP_LOG(ctp::logDEBUG, *_log) <<\"Number of Electrons minus ECP_Nucleus charge is \"<<Znuc_ECP-N<< \" you probably use ECPs, if you do use ECPs please use the option to switch on\"  << flush;\n        }\n        else{\n            CTP_LOG(ctp::logDEBUG, *_log) <<\"Warning: Your molecule is highly ionized and you use real core potentials, sounds interesting\" << flush;\n        }\n        netcharge = Znuc-N;\n    }\n    _do_Transition=false;\n    }\n \n    netcharge=round(netcharge);\n    CTP_LOG(ctp::logDEBUG, *_log) <<\"Netcharge constrained to \" << netcharge<< flush;\n\n    return netcharge;\n}\n\n\n\nvoid Espfit::Fit2Density_analytic(std::vector< ctp::QMAtom* >& _atomlist, ub::matrix<double> &_dmat,AOBasis &_basis) {\n     double Nm2Bohr=tools::conv::nm2bohr;\n     double A2nm=tools::conv::ang2nm;\n    // setting up grid\n    Grid _grid;\n    _grid.setAtomlist(&_atomlist);\n    _grid.setupCHELPgrid();\n\n    CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() <<  \" Done setting up CHELPG grid with \" << _grid.getsize() << \" points \" << endl;\n    // Calculating nuclear potential at gridpoints\n\n    ub::vector<double> _ESPatGrid = ub::zero_vector<double>(_grid.getsize());\n\n    AOOverlap overlap;\n    overlap.Fill(_basis);\n    const ub::vector<double> DMATasarray=_dmat.data();\n    const ub::vector<double> AOOasarray=overlap.Matrix().data();\n    double N=0.0;\n    #pragma omp parallel for reduction(+:N)\n    for ( unsigned _i =0; _i < DMATasarray.size(); _i++ ){\n            N =N+ DMATasarray(_i)*AOOasarray(_i);\n        }\n\n    double netcharge=getNetcharge( _atomlist,N );\n    if(!_do_Transition){\n        ub::vector<double> _NucPatGrid = EvalNuclearPotential(  _atomlist,  _grid);\n        _ESPatGrid += _NucPatGrid;\n    }\n\n    CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Calculating ESP at CHELPG grid points\"  << flush;\n    #pragma omp parallel for\n    for ( int i = 0 ; i < _grid.getsize(); i++){\n        // AOESP matrix\n         AOESP _aoesp;\n         _aoesp.Fill(_basis, _grid.getGrid()[i]*Nm2Bohr);\n        const ub::vector<double> AOESPasarray=_aoesp.Matrix().data();\n\n        for ( unsigned _i =0; _i < DMATasarray.size(); _i++ ){\n            _ESPatGrid(i) -= DMATasarray(_i)*AOESPasarray(_i);\n        }\n    }\n\n    std::vector< tools::vec > _fitcenters;\n\n          for ( unsigned j = 0; j < _atomlist.size(); j++){\n             tools::vec _pos=A2nm*_atomlist[j]->getPos();\n            _fitcenters.push_back(_pos);\n          }\n    std::vector<double> _charges = FitPartialCharges(_fitcenters,_grid, _ESPatGrid, netcharge);\n\n    //Write charges to qmatoms\n        for ( unsigned _i =0 ; _i < _atomlist.size(); _i++){\n            _atomlist[_i]->charge=_charges[_i];\n        }\n    return;\n    }\n\nstd::vector<double> Espfit::FitPartialCharges( std::vector< tools::vec >& _fitcenters, Grid& _grid, ub::vector<double>& _potential, double& _netcharge ){\n    CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Setting up Matrices for fitting of size \"<< _fitcenters.size()+1 <<\" x \" << _fitcenters.size()+1<< flush;\n\n    const std::vector< tools::vec >& _gridpoints=_grid.getGrid();\n\n    CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Using \"<< _fitcenters.size() <<\" Fittingcenters and \" << _gridpoints.size()<< \" Gridpoints.\"<< flush;\n\n    ub::matrix<double> _Amat = ub::zero_matrix<double>(_fitcenters.size()+1,_fitcenters.size()+1);\n    ub::matrix<double> _Bvec = ub::zero_matrix<double>(_fitcenters.size()+1,1);\n    //boost::progress_display show_progress( _fitcenters.size() );\n    // setting up _Amat\n    #pragma omp parallel for\n    for ( unsigned _i =0 ; _i < _Amat.size1()-1; _i++){\n        for ( unsigned _j=_i; _j<_Amat.size2()-1; _j++){\n            for ( unsigned _k=0; _k < _gridpoints.size(); _k++){\n                double dist_i = tools::abs(_fitcenters[_i]-_gridpoints[_k])*tools::conv::nm2bohr;\n                double dist_j = tools::abs(_fitcenters[_j]-_gridpoints[_k])*tools::conv::nm2bohr;\n\n                 _Amat(_i,_j) += 1.0/dist_i/dist_j;\n            }\n            _Amat(_j,_i) = _Amat(_i,_j);\n        }\n    }\n\n    for ( unsigned _i =0 ; _i < _Amat.size1(); _i++){\n      _Amat(_i,_Amat.size1()-1) = 1.0;\n      _Amat(_Amat.size1()-1,_i) = 1.0;\n    }\n    _Amat(_Amat.size1()-1,_Amat.size1()-1) = 0.0;\n\n    // setting up Bvec\n    #pragma omp parallel for\n    for ( unsigned _i =0 ; _i < _Bvec.size1()-1; _i++){\n        for ( unsigned _k=0; _k < _gridpoints.size(); _k++){\n                double dist_i = tools::abs(_fitcenters[_i]-_gridpoints[_k])*tools::conv::nm2bohr;\n                _Bvec(_i,0) += _potential(_k)/dist_i;\n        }\n       }\n\n    _Bvec(_Bvec.size1()-1,0) = _netcharge; //netcharge!!!!\n    CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \"  Inverting Matrices \"<< flush;\n    // invert _Amat\n    ub::matrix<double> _Amat_inverse = ub::zero_matrix<double>(_fitcenters.size()+1,_fitcenters.size()+1);\n\n\n\n    if(_do_svd){\n        int notfittedatoms=linalg_invert_svd( _Amat , _Amat_inverse,_conditionnumber);\n        CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \"SVD Done. \"<<notfittedatoms<<\" could not be fitted and are set to zero.\"<< flush;\n    }\n    else{\n        linalg_invert( _Amat , _Amat_inverse);\n    }\n\n    CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Inverting Matrices done.\"<< flush;\n    //_Amat.resize(0,0);\n\n\n\n    ub::matrix<double> _charges = ub::prod(_Amat_inverse,_Bvec);\n\n    std::vector<double> _result;\n    for ( unsigned _i = 0; _i < _charges.size1(); _i++ ){\n        _result.push_back(_charges(_i,0));\n    }\n\n    double _sumcrg = 0.0;\n    for ( unsigned _i =0 ; _i < _fitcenters.size(); _i++){\n\n        //CTP_LOG(ctp::logDEBUG, *_log) << \" Center \" << _i << \" FitCharge: \" << _result[_i] << \"pos \" << _fitcenters[_i] << flush;\n        _sumcrg += _result[_i];\n    }\n\n    CTP_LOG(ctp::logDEBUG, *_log) << \" Sum of fitted charges: \" << _sumcrg << flush;\n\n    // get RMSE\n    double _rmse = 0.0;\n    double _totalPotSq = 0.0;\n    for ( unsigned _k=0 ; _k < _gridpoints.size(); _k++ ){\n        double temp = 0.0;\n        for ( unsigned _i=0; _i < _fitcenters.size(); _i++ ){\n            double dist =  tools::abs(_gridpoints[_k]-_fitcenters[_i])*tools::conv::nm2bohr;\n            temp += _result[_i]/dist;\n        }\n        _rmse += (_potential(_k) - temp)*(_potential(_k) - temp);\n        _totalPotSq += _potential(_k)*_potential(_k);\n    }\n    CTP_LOG(ctp::logDEBUG, *_log) << \" RMSE of fit:  \" << sqrt(_rmse/_gridpoints.size()) << flush;\n    CTP_LOG(ctp::logDEBUG, *_log) << \" RRMSE of fit: \" << sqrt(_rmse/_totalPotSq) << flush;\n\n    return _result;\n   }\n\n\n}}\n", "meta": {"hexsha": "cc33c02d78954f909c65518cae3450fa1739b9af", "size": 12967, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/espfit.cc", "max_stars_repo_name": "choudarykvsp/xtp", "max_stars_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-05T17:36:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-05T17:36:53.000Z", "max_issues_repo_path": "src/libxtp/espfit.cc", "max_issues_repo_name": "choudarykvsp/xtp", "max_issues_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/espfit.cc", "max_forks_repo_name": "choudarykvsp/xtp", "max_forks_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5922619048, "max_line_length": 238, "alphanum_fraction": 0.6141744428, "num_tokens": 3911, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581510799252, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.4030324852418331}}
{"text": "/*\n * Copyright (c) 2016 Abhishek Agrawal (abhishek.agrawal@protonmail.com)\n * Distributed under the MIT License.\n * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT\n */\n\n// This code will convert multiple cartesian state vectors \n// into TLE and check where exactly the Atom is failing. The cartesian\n// vectors are generated by converting randomly generated keplerian elements. \n// The conversion is achieved through the pykep library of ESA.  \n\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <exception>\n#include <cstdlib>\n#include <execinfo.h>\n\n#include <boost/exception/info.hpp>\n#include <libsgp4/Globals.h>\n#include <SML/sml.hpp>\n#include <SML/constants.hpp>\n#include <SML/basicFunctions.hpp>\n\n#include \"CppProject/TleGen.hpp\"\n#include \"CppProject/randomGen.hpp\"\n\n\ntypedef double Real;\ntypedef std::vector< Real > Vector;\ntypedef std::vector< Real > Vector6;\ntypedef std::vector< Real > Vector3;\ntypedef std::vector< Real > Vector2;\ntypedef std::vector < std::vector < Real > > Vector2D;\n\nint main(void)\n{\n    // some constants values are defined here\n    const double km2m = 1000; // conversion from km to m\n    // earth radius\n    const double EarthRadius = kXKMPER * km2m; // unit m\n    const double EarthDiam = 2 * EarthRadius;\n    // grav. parameter 'mu' of earth\n    // const double muEarth = kMU*( pow( 10, 9 ) ); // unit m^3/s^2\n    const int bypass = true; // keep this true, this just enables executing an alternate code snippet that takes care of thrown exceptions from ATOM\n\n    if(bypass == false){\n        // initialize input parameters for the function generating random orbital elements. Description can be\n        // found in randomKepElem.hpp for each of the following parameters. \n        const Vector2 range_a      = { (EarthDiam+100000), (EarthDiam+1000000) }; \n        const Vector2 range_e      = { 0, 1 };\n        const Vector2 range_i      = { 0, sml::convertDegreesToRadians( 180.0 ) };\n        const Vector2 range_raan   = { 0, sml::convertDegreesToRadians( 360.0 ) };\n        const Vector2 range_w      = { 0, sml::convertDegreesToRadians( 360.0 ) };\n        const Vector2 range_E      = { 0, sml::convertDegreesToRadians( 360.0 ) };\n        const int limit            = 100;\n        Vector2D randKep( limit, std::vector< Real >( 6 ) );\n        Vector semiAxis( limit ); // storage for random semi major axis values\n        Vector eccentricity( limit ); // storage for random eccentricity values\n        Vector inclination( limit ); // storage for random inclination values\n        Vector RAAN( limit ); // storage for random RAAN values\n        Vector AOP( limit ); // storage for random AOP values\n        Vector EA( limit ); // storage for random EA values\n\n        // call the function to generate random keplerian orbital elements. Values are stored in randKep in a 2D\n        // vector format. A single row represents one set of orbital elements, arranged in the same order as the\n        // input argument order of the elements. \n        randomGen::randomGen( range_a, limit, semiAxis );\n        randomGen::randomGen( range_e, limit, eccentricity );\n        randomGen::randomGen( range_i, limit, inclination );\n        randomGen::randomGen( range_raan, limit, RAAN );\n        randomGen::randomGen( range_w, limit, AOP );\n        randomGen::randomGen( range_E, limit, EA );\n        for(int i = 0; i < limit; i++)\n        {\n            randKep[ i ][ 0 ] = semiAxis[ i ];\n            randKep[ i ][ 1 ] = eccentricity[ i ];\n            randKep[ i ][ 2 ] = inclination[ i ];\n            randKep[ i ][ 3 ] = RAAN[ i ];\n            randKep[ i ][ 4 ] = AOP[ i ];\n            randKep[ i ][ 5 ] = EA[ i ];\n        }\n\n        \n        // remove orbital elements where the radius of perigee is inside earth\n        Vector2D randKepElem( limit, std::vector< Real >( 6 ) );\n        int newLimit = limit; // whenever a row of cartesian (keplerian) elements is removed, the limit will have to be changed. \n        Real radiusPerigee = 0; // variable storing the radius of Perigee for an orbit. this is used in our checking condition\n        std::vector< int > rowsToDelete; // stores the row numbers which have to be deleted\n        int insideCounter = 0; // to count the number of times radius of perigee is inside the Earth. \n        int outsideCounter = 0; // to count the number of times the radius of perigee is beyond a cetain upper limit\n        int newIndex = 0; // index counter for the second 2D vector\n        for(int j = 0; j < newLimit; j++)\n        {\n            radiusPerigee = randKep[ j ][ 0 ] * (1 - randKep[ j ][ 1 ]);\n            if(radiusPerigee <= EarthRadius )\n            {\n                insideCounter = insideCounter + 1; // counter increments everytime the condition is true\n            }\n            if(radiusPerigee >= (EarthRadius+2000000))\n            {\n                outsideCounter = outsideCounter + 1;\n            }\n            if(radiusPerigee > EarthRadius && radiusPerigee < (EarthRadius+2000000)) // this is obv not the most efficient way\n            {\n                randKepElem[ newIndex ] = randKep[ j ];\n                newIndex++;\n            }\n        } \n        randKepElem.erase( randKepElem.begin() + newIndex, randKepElem.end() ); // delete the left over rows in the final random keplerian element vector\n        std::vector< std::vector < Real > > ().swap(randKep); // create an empty vector with no memory allocated to it ...\n        // ... and swap it with the vector which you want to delete and deallocate the memory\n        std::cout << \"Inside counter value = \" << insideCounter << std::endl;\n        std::cout << \"Outside counter value = \" << outsideCounter << std::endl;\n        std::cout << \"Usefull sets left = \" << limit - (insideCounter + outsideCounter) << std::endl;\n        newLimit = randKepElem.size();\n        std::cout << \"Number of final rows in randKepElem 2D vector = \" << newLimit << std::endl;\n\n        // file storage\n        std::ofstream tlefile;\n        tlefile.open(\"TLEfile.csv\", std::ofstream::app);\n        tlefile << \"Solver Status Summary\" << \",\" << \"Iteration Count\" << \",\" << \"semi-major axis [km]\" << \",\" << \"eccentricity\" << \",\";\n        tlefile << \"Inclination [deg]\" << \",\" << \"RAAN [deg]\" << \",\" << \"AOP [deg]\" << \",\" << \"Eccentric Anomaly [deg]\" << std::endl;\n        // Generate the TLEs for the final random set of orbital elements\n        std::string SolverStatus;\n        int IterationCount;\n        // some other bookkeeping variables, these are not used in the convert to tle function\n        std::size_t findSuccess;\n        for(int i = 0; i < newLimit; i++)\n        {\n            IterationCount = 0;\n            TleGen::TleGen( randKepElem[ i ], SolverStatus, IterationCount ); // giving one set of orbital elements one by one to the tle generator\n            findSuccess = SolverStatus.find(\"success\");    \n            if(findSuccess == std::string::npos){\n                std::cout << \"TLE Conversion Failed\" << std::endl;\n                tlefile << \"Failed\" << \",\" << IterationCount << \",\";\n                tlefile << ( randKepElem[ i ][ 0 ]/1000 ) << \",\";\n                tlefile << randKepElem[ i ][ 1 ] << \",\";\n                tlefile << sml::convertRadiansToDegrees( randKepElem[ i ][ 2 ] ) << \",\";\n                tlefile << sml::convertRadiansToDegrees( randKepElem[ i ][ 3 ] ) << \",\";\n                tlefile << sml::convertRadiansToDegrees( randKepElem[ i ][ 4 ] ) << \",\";\n                tlefile << sml::convertRadiansToDegrees( randKepElem[ i ][ 5 ] ) << std::endl;\n            }\n            else{\n                std::cout << \"TLE conversion success\" << std::endl;\n                tlefile << \"Success\" << \",\" << IterationCount << \",\";\n                tlefile << ( randKepElem[ i ][ 0 ]/1000 ) << \",\";\n                tlefile << randKepElem[ i ][ 1 ] << \",\";\n                tlefile << sml::convertRadiansToDegrees( randKepElem[ i ][ 2 ] ) << \",\";\n                tlefile << sml::convertRadiansToDegrees( randKepElem[ i ][ 3 ] ) << \",\";\n                tlefile << sml::convertRadiansToDegrees( randKepElem[ i ][ 4 ] ) << \",\";\n                tlefile << sml::convertRadiansToDegrees( randKepElem[ i ][ 5 ] ) << std::endl;\n            }\n            \n        }\n        tlefile << std::endl << std::endl;\n        tlefile.close();\n    }\n    else{\n            const int newLimit = 1000; // number of random elementss to be generated\n            Vector2D randKepElem( newLimit, std::vector < Real >( 6 ) ); // general 2D vector to store the randomly generated keplerian elements in one place\n            int indexer = 0; // used to keep track of which orbit or set of random orbital elements is being run in the simulation\n            Vector RadiusOfPerigee( newLimit ); // to store radius of perigee value for each random orbit generated\n            \n            std::ofstream tlefile; // output file handle\n            tlefile.open( \"TLEfile3.csv\", std::ofstream::app ); // open the file and append the data\n            tlefile << \"Solver Status Summary\" << \",\" << \"Iteration Count\" << \",\" << \"semi-major axis [km]\" << \",\" << \"SMA Seed\" << \",\";\n            tlefile << \"eccentricity\" << \",\" << \"ECC Seed\" << \",\";\n            tlefile << \"Inclination [deg]\" << \",\" << \"INC Seed\" << \",\";\n            tlefile << \"RAAN [deg]\" << \",\" << \"RAAN Seed\" << \",\";\n            tlefile << \"AOP [deg]\" << \",\" << \"AOP Seed\" << \",\"; \n            tlefile << \"Eccentric Anomaly [deg]\" << \",\" << \"EA Seed\" << \",\" << \"Radius of Perigee [km]\" << std::endl;\n            \n            // bookkeeping variables, these are not used in the convert to tle function\n            std::size_t findSuccess;\n\n            Vector2 range_a = { (EarthDiam + 10000 * km2m), (EarthDiam + 90000 * km2m) }; // range for semi major axis\n            Vector2 range_e = { 0.0, 1.0 }; // range for eccentricity\n            Vector2 range_i = { 0.0, 180.0 }; // range for inclination\n            Vector2 range_raan = { 0.0, 360.0 }; // range for raan\n            Vector2 range_w = { 0.0, 360.0 }; // range for argument of perigee\n            Vector2 range_EA = { 0.0, 360.0 }; // range for eccentric anomaly\n\n            Vector eccentricity( newLimit ); // init. vector to store eccentricity values\n            Vector semiAxis( newLimit ); // initialize vector of size newLimit \n            Vector inclination( newLimit ); // vector to store random inclination values\n            Vector raan( newLimit ); // vector to store random raan values\n            Vector aop( newLimit ); // vector to store random aop values\n            Vector EA( newLimit ); // vector to store random EA values\n\n            // seed values for each orbital element, to be used in the pseudo random element generator algorithm. These seed values can be used to \n            // regenerate the psuedo random sequence at any given time in future. \n            const int semiSeed = 400; \n            const int eccSeed = 400;\n            const int incSeed = 400; \n            const int raanSeed = 300;\n            const int aopSeed = 200;\n            const int eaSeed = 100;\n\n            // random value generation\n            randomGen::randomGenWithSeed( range_a, newLimit, semiAxis, semiSeed ); \n            randomGen::randomGenWithSeed( range_e, newLimit, eccentricity, eccSeed );\n            randomGen::randomGenWithSeed( range_i, newLimit, inclination, incSeed );\n            randomGen::randomGenWithSeed( range_raan, newLimit, raan, raanSeed );\n            randomGen::randomGenWithSeed( range_w, newLimit, aop, aopSeed );\n            randomGen::randomGenWithSeed( range_EA, newLimit, EA, eaSeed );    \n\n            for(int i = 0; i < newLimit; i++)\n            {\n                randKepElem[ i ][ 0 ] = semiAxis[ i ]; // semi major axis\n                randKepElem[ i ][ 1 ] = eccentricity[ i ]; // eccentricity\n                randKepElem[ i ][ 2 ] = sml::convertDegreesToRadians( inclination[ i ] ); // inclination\n                randKepElem[ i ][ 3 ] = sml::convertDegreesToRadians( raan[ i ] ); // RAAN\n                randKepElem[ i ][ 4 ] = sml::convertDegreesToRadians( aop[ i ] ); // AOP\n                randKepElem[ i ][ 5 ] = sml::convertDegreesToRadians( EA[ i ] ); // EA\n                RadiusOfPerigee[ i ] = semiAxis[ i ] * ( 1 - eccentricity[ i ] );\n            }\n            while( indexer < newLimit)\n            {\n                std::string SolverStatus;\n                int IterationCount;\n                try\n                {\n                    indexer++;\n                    // std::cout << \"indexer = \" << indexer << std::endl;\n                    // std::cout << \"Radius of Perigee = \" << RadiusOfPerigee[ indexer - 1 ]/1000 << std::endl;\n                    // std::cout << \"Semi Axis = \" << randKepElem[ indexer - 1 ][ 0 ]/1000 << std::endl;\n                    // std::cout << \"Eccentricity = \" << randKepElem[ indexer - 1 ][ 1 ] << std::endl;\n                    // std::cout << \"Inclination = \" << sml::convertRadiansToDegrees( randKepElem[ indexer - 1 ][ 2 ] ) << std::endl;\n\n                    TleGen::TleGen( randKepElem[ indexer - 1 ], SolverStatus, IterationCount );\n                    // std::cout << SolverStatus << std::endl;\n                    findSuccess = SolverStatus.find(\"success\");    \n                    if(findSuccess == std::string::npos){\n                            // std::cout << \"TLE Conversion Failed\" << std::endl;\n                            tlefile << \"Failed\" << \",\" << IterationCount << \",\";\n                            tlefile << ( randKepElem[ indexer - 1 ][ 0 ]/1000 ) << \",\" << semiSeed << \",\";\n                            tlefile << randKepElem[ indexer - 1 ][ 1 ] << \",\" << eccSeed << \",\";\n                            tlefile << sml::convertRadiansToDegrees( randKepElem[ indexer - 1 ][ 2 ] ) << \",\" << incSeed << \",\";\n                            tlefile << sml::convertRadiansToDegrees( randKepElem[ indexer - 1 ][ 3 ] ) << \",\" << raanSeed << \",\";\n                            tlefile << sml::convertRadiansToDegrees( randKepElem[ indexer - 1 ][ 4 ] ) << \",\" << aopSeed << \",\";\n                            tlefile << sml::convertRadiansToDegrees( randKepElem[ indexer - 1 ][ 5 ] ) << \",\" << eaSeed << \",\";\n                            tlefile << RadiusOfPerigee[ indexer - 1 ]/1000 << std::endl;   \n                    }\n                    else{\n                            // std::cout << \"TLE conversion success\" << std::endl;\n                            tlefile << \"Success\" << \",\" << IterationCount << \",\";\n                            tlefile << ( randKepElem[ indexer - 1 ][ 0 ]/1000 ) << \",\" << semiSeed << \",\";\n                            tlefile << randKepElem[ indexer - 1 ][ 1 ] << \",\" << eccSeed << \",\";\n                            tlefile << sml::convertRadiansToDegrees( randKepElem[ indexer - 1 ][ 2 ] ) << \",\" << incSeed << \",\";\n                            tlefile << sml::convertRadiansToDegrees( randKepElem[ indexer - 1 ][ 3 ] ) << \",\" << raanSeed << \",\";\n                            tlefile << sml::convertRadiansToDegrees( randKepElem[ indexer - 1 ][ 4 ] ) << \",\" << aopSeed << \",\";\n                            tlefile << sml::convertRadiansToDegrees( randKepElem[ indexer - 1 ][ 5 ] ) << \",\" << eaSeed << \",\";\n                            tlefile << RadiusOfPerigee[ indexer - 1 ]/1000 << std::endl;   \n                    }\n                }\n                catch(const std::exception& err)\n                {\n                    // std::cout << \"Error Caught = \";\n                    // std::cout << err.what() << std::endl;\n                    tlefile << \"Exception Caught = \" << err.what() << \",\" << \",\";\n                    tlefile << semiAxis[ indexer - 1 ]/1000 << \",\" << semiSeed << \",\";\n                    tlefile << eccentricity[ indexer - 1 ] << \",\" << eccSeed << \",\";\n                    tlefile << inclination[ indexer - 1 ] << \",\" << incSeed << \",\";\n                    tlefile << raan[ indexer - 1 ] << \",\" << raanSeed << \",\";\n                    tlefile << aop[ indexer - 1 ] << \",\" << aopSeed << \",\";\n                    tlefile << EA[ indexer - 1 ] << \",\" << eaSeed << \",\";\n                    tlefile << RadiusOfPerigee[ indexer - 1 ]/1000 << std::endl;   \n                }\n            }\n            tlefile << std::endl << std::endl;\n            tlefile.close();\n        }\n   return EXIT_SUCCESS;\n}\n\n    \n\n\n", "meta": {"hexsha": "07eb7fc7498372e4a4c6cdf562a3ff74cf211fa0", "size": 16387, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "abhi-agrawal/TestAtomProject", "max_stars_repo_head_hexsha": "7ec8292c7eab146a98feecee5efae4110713c6f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "abhi-agrawal/TestAtomProject", "max_issues_repo_head_hexsha": "7ec8292c7eab146a98feecee5efae4110713c6f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "abhi-agrawal/TestAtomProject", "max_forks_repo_head_hexsha": "7ec8292c7eab146a98feecee5efae4110713c6f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.9045936396, "max_line_length": 157, "alphanum_fraction": 0.5459205468, "num_tokens": 4206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514777, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4030263316598961}}
{"text": "//  Copyright (c) 2018 Robert Ramey\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n\n#include <boost/safe_numerics/safe_integer.hpp>\n\nint main(){\n    std::cout << \"example 4: \";\n    std::cout << \"implicit conversions change data values\" << std::endl;\n    std::cout << \"Not using safe numerics\" << std::endl;\n    \n    // problem: implicit conversions change data values\n    try{\n        signed int   a{-1};\n        unsigned int b{1};\n        std::cout << \"a is \" << a << \" b is \" << b << '\\n';\n        if(a < b){\n            std::cout << \"a is less than b\\n\";\n        }\n        else{\n            std::cout << \"b is less than a\\n\";\n        }\n        std::cout << \"error NOT detected!\" << std::endl;\n    }\n    catch(const std::exception &){\n        // never arrive here - just produce the wrong answer!\n        std::cout << \"error detected!\" << std::endl;\n        return 1;\n    }\n\n    // solution: replace int with safe<int> and unsigned int with safe<unsigned int>\n    std::cout << \"Using safe numerics\" << std::endl;\n    try{\n        using namespace boost::safe_numerics;\n        safe<signed int>   a{-1};\n        safe<unsigned int> b{1};\n        std::cout << \"a is \" << a << \" b is \" << b << '\\n';\n        if(a < b){\n            std::cout << \"a is less than b\\n\";\n        }\n        else{\n            std::cout << \"b is less than a\\n\";\n        }\n        std::cout << \"error NOT detected!\" << std::endl;\n        return 1;\n    }\n    catch(const std::exception & e){\n        // never arrive here - just produce the correct answer!\n        std::cout << e.what() << std::endl;\n        std::cout << \"error detected!\" << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "0fb29afd597f8f3fb87425c7426df8bcf660ecb7", "size": 1778, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/example4.cpp", "max_stars_repo_name": "giomasce-throwaway/safe_numerics", "max_stars_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 111.0, "max_stars_repo_stars_event_min_datetime": "2018-09-26T00:40:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T12:02:17.000Z", "max_issues_repo_path": "example/example4.cpp", "max_issues_repo_name": "giomasce-throwaway/safe_numerics", "max_issues_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "example/example4.cpp", "max_forks_repo_name": "giomasce-throwaway/safe_numerics", "max_forks_repo_head_hexsha": "3a1676e5831bab93b9be50caec69c1887a4af7da", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 30.6551724138, "max_line_length": 84, "alphanum_fraction": 0.5292463442, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.4030263209410543}}
{"text": "// graph-tool -- a general graph modification and manipulation thingy\n//\n// Copyright (C) 2006-2018 Tiago de Paula Peixoto <tiago@skewed.de>\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 3\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// you should have received a copy of the GNU General Public License\n// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n#ifndef GRAPH_CLUSTERING_HH\n#define GRAPH_CLUSTERING_HH\n\n#include \"config.h\"\n\n#include \"hash_map_wrap.hh\"\n#include <boost/mpl/if.hpp>\n\n#ifdef _OPENMP\n#include \"omp.h\"\n#endif\n\n#ifndef __clang__\n#include <ext/numeric>\nusing __gnu_cxx::power;\n#else\ntemplate <class Value>\nValue power(Value value, int n)\n{\n    return pow(value, n);\n}\n#endif\n\nnamespace graph_tool\n{\nusing namespace boost;\nusing namespace std;\n\n// calculates the number of triangles to which v belongs\ntemplate <class Graph, class VProp>\npair<int,int>\nget_triangles(typename graph_traits<Graph>::vertex_descriptor v, VProp& mark,\n              const Graph& g)\n{\n    size_t triangles = 0;\n\n    for (auto n : adjacent_vertices_range(v, g))\n    {\n        if (n == v)\n            continue;\n        mark[n] = true;\n    }\n\n    for (auto n : adjacent_vertices_range(v, g))\n    {\n        if (n == v)\n            continue;\n        for (auto n2 : adjacent_vertices_range(n, g))\n        {\n            if (n2 == n)\n                continue;\n            if (mark[n2])\n                ++triangles;\n        }\n    }\n\n    for (auto n : adjacent_vertices_range(v, g))\n        mark[n] = false;\n\n    size_t k = out_degree(v, g);\n    if (graph_tool::is_directed(g))\n        return make_pair(triangles, (k * (k - 1)));\n    else\n        return make_pair(triangles / 2, (k * (k - 1)) / 2);\n}\n\n\n// retrieves the global clustering coefficient\nstruct get_global_clustering\n{\n    template <class Graph>\n    void operator()(const Graph& g, double& c, double& c_err) const\n    {\n        size_t triangles = 0, n = 0;\n        vector<bool> mask(num_vertices(g), false);\n\n        #pragma omp parallel if (num_vertices(g) > OPENMP_MIN_THRESH) \\\n            firstprivate(mask) reduction(+:triangles, n)\n        parallel_vertex_loop_no_spawn\n                (g,\n                 [&](auto v)\n                 {\n                     auto temp = get_triangles(v, mask, g);\n                     triangles += temp.first;\n                     n += temp.second;\n                 });\n        c = double(triangles) / n;\n\n        // \"jackknife\" variance\n        c_err = 0.0;\n        double cerr = 0.0;\n        #pragma omp parallel if (num_vertices(g) > OPENMP_MIN_THRESH) \\\n            firstprivate(mask) reduction(+:cerr)\n        parallel_vertex_loop_no_spawn\n                (g,\n                 [&](auto v)\n                 {\n                     auto temp = get_triangles(v, mask, g);\n                     double cl = double(triangles - temp.first) /\n                         (n - temp.second);\n                     cerr += power(c - cl, 2);\n                 });\n        c_err = sqrt(cerr);\n    }\n};\n\n// sets the local clustering coefficient to a property\nstruct set_clustering_to_property\n{\n    template <class Graph, class ClustMap>\n    void operator()(const Graph& g, ClustMap clust_map) const\n    {\n        typedef typename property_traits<ClustMap>::value_type c_type;\n        vector<bool> mask(num_vertices(g), false);\n\n        #pragma omp parallel if (num_vertices(g) > OPENMP_MIN_THRESH) \\\n            firstprivate(mask)\n        parallel_vertex_loop_no_spawn\n            (g,\n             [&](auto v)\n             {\n                 auto triangles = get_triangles(v, mask, g);\n                 double clustering = (triangles.second > 0) ?\n                     double(triangles.first)/triangles.second :\n                     0.0;\n                 clust_map[v] = c_type(clustering);\n             });\n    }\n\n    template <class Graph>\n    struct get_undirected_graph\n    {\n        typedef typename mpl::if_\n           <std::is_convertible<typename graph_traits<Graph>::directed_category,\n                                directed_tag>,\n            const undirected_adaptor<Graph>,\n            const Graph& >::type type;\n    };\n};\n\n} //graph-tool namespace\n\n#endif // GRAPH_CLUSTERING_HH\n", "meta": {"hexsha": "bae0bd7e806087bd9b9ead50fc8885aeac8ad836", "size": 4599, "ext": "hh", "lang": "C++", "max_stars_repo_path": "graph-tool-2.27/src/graph/clustering/graph_clustering.hh", "max_stars_repo_name": "Znigneering/CSCI-3154", "max_stars_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "graph-tool-2.27/src/graph/clustering/graph_clustering.hh", "max_issues_repo_name": "Znigneering/CSCI-3154", "max_issues_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graph-tool-2.27/src/graph/clustering/graph_clustering.hh", "max_forks_repo_name": "Znigneering/CSCI-3154", "max_forks_repo_head_hexsha": "bc318efc73d2a80025b98f5b3e4f7e4819e952e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5652173913, "max_line_length": 80, "alphanum_fraction": 0.5842574473, "num_tokens": 1065, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.402817786189385}}
{"text": "/*\n   Copyright 2015 Ruben Moreno Montoliu <ruben3d at gmail dot com>\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*/\n\n//\n// SphereAreaLight.cpp - Created on 2009.01.15\n//\n\n#include <cmath>\n#include <string>\n#include <boost/lexical_cast.hpp>\n#include \"SphereAreaLight.h\"\n#include \"Object.h\"\n#include \"Polar3.h\"\n#include \"Random.h\"\n#include \"Ray.h\"\n#include \"Sphere.h\"\n#include \"Material.h\"\n\nunsigned int SphereAreaLight::GlobalCounter = 0;\n\nSphereAreaLight::SphereAreaLight(const Transform& tr, const double intensity, const Color& color,\n\t\t\t\t\t\t\t\tconst double radius, const bool show, const Attenuation attenuation)\n\t: Light(tr, intensity, color), LightHasPosition(tr(Point(0,0,0))),\n\t\tLightHasAttenuation(attenuation), LightHasGeometry(show), m_radius(radius),\n\t\tm_minSamples(16), m_maxSamples(32)\n{\n\tLight::addAttribute(LightHasPosition::ATTRIBUTE);\n\tLight::addAttribute(LightHasAttenuation::ATTRIBUTE);\n\tLight::addAttribute(LightHasGeometry::ATTRIBUTE);\n\n\tm_id = ++GlobalCounter;\n}\n\nbool SphereAreaLight::computeSample(const Point& P, const Vector& N,\n\t\t\t\t\t\t\tconst std::list<Object*>& objects,\n\t\t\t\t\t\t\tunsigned int& haltonSeq,\n\t\t\t\t\t\t\tColor& I, Vector& L) const\n{\n\t// Light surface normal at sample point\n\tVector LN;\n\n\t// Generates a random sample. We don't want a sample facing away\n\tdo\n\t{\n\t\thaltonSeq++;\n\t\tdouble rotPhi = acos(Random::Instance().haltonSeq(haltonSeq,2)*2-1);\n\t\tdouble rotTheta = Random::Instance().haltonSeq(haltonSeq,3)*PI*2;\n\t\tPolar3 p(1,rotPhi,rotTheta);\n\t\tLN=p;\n\t}\n\twhile (N.dot(LN) <= 0);\n\n\t// Point at the light surface\n\tPoint LP = /*getPosition() +*/ Point(LN * m_radius);\n\n\t// Ray from point of intersection to light surface\n\tL = LP - P;\n\tconst double lightRayLength = L.length();\n\tL = L.normalize();\n\tRay lightRay = T(Ray(P, L));\t// <- Local to World\n\tlightRay.tmax = lightRayLength;\n\n\t// Test if the light ray is obstructed\n\tbool obstructed = false;\n\tstd::list<Object*>::const_iterator obj;\n\tfor (obj = objects.begin(); obj != objects.end(); obj++)\n\t{\n\t\tif (!(*obj)->castShadow()) continue;\n\n\t\tdouble t;\n\t\tconst Ray lightRayT = (*obj)->T.applyInv(lightRay);\t// World to object\n\t\tbool intersects = (*obj)->getGeometry()->intersects(lightRayT,t);\n\t\tif (intersects)\n\t\t{\n\t\t\tobstructed = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tI = obstructed ? Color(0,0,0) : getColor()*getIntensity()*getAttFactor(lightRayLength)*L.dot(LN);\n\treturn obstructed;\n}\n\nvoid SphereAreaLight::computeIntensity(const Vector& N, const Point& P,\n\t\t\t\t\t\t\tconst std::list<Object*>& objects,\n\t\t\t\t\t\t\tstd::list<Color>& Is, std::list<Vector>& Ls) const\n{\n\tbool penumbra = false;\n\tunsigned int haltonSeq = Random::Instance().generate(1024);\n\n\tVector tN = T.applyInv(N);\t// World to local\n\tPoint tP = T.applyInv(P);\n\tColor I;\n\tVector L;\n\tbool shadow = computeSample(tP,tN,objects,haltonSeq,I,L);\n\tIs.push_back(I);\n\tLs.push_back(T(L));\t// Local to world\n\n\tfor (int i=1; i<m_minSamples; i++)\n\t{\n\t\tColor I;\n\t\tVector L;\n\t\tbool blocked = computeSample(tP,tN,objects,haltonSeq,I,L);\n\t\tIs.push_back(I);\n\t\tLs.push_back(T(L));\t// Local to world\n\n\t\tif (blocked != shadow) penumbra = true;\n\t}\n\n\tif (penumbra)\n\t{\n\t\tfor (int n=0; n<m_maxSamples; n++)\n\t\t{\n\t\t\tColor I;\n\t\t\tVector L;\n\t\t\tcomputeSample(tP,tN,objects,haltonSeq,I,L);\n\t\t\tIs.push_back(I);\n\t\t\tLs.push_back(T(L));\t// Local to world\n\t\t}\n\t}\n}\n\nGeometry* SphereAreaLight::getGeometry() const\n{\n\treturn new Sphere(m_radius);\n}\n\nMaterial* SphereAreaLight::getMaterial() const\n{\n\tMaterial *m = new Material(std::string(\"_sal_\")+boost::lexical_cast<std::string>(m_id), getColor());\n\tm->setEmission(getIntensity());\n\tm->setSpecularIntensity(0.0);\n\tm->setSpecularGlossiness(0.0);\n\treturn m;\n}\n", "meta": {"hexsha": "1face399fb253f783cd6ec2b930ff365e94cedec", "size": 4109, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/scene/SphereAreaLight.cpp", "max_stars_repo_name": "ruben3d/luna-raytracer", "max_stars_repo_head_hexsha": "14def80f3a11502d78fd0bed757ba19edd0d9057", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-09-27T14:47:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T14:24:48.000Z", "max_issues_repo_path": "src/scene/SphereAreaLight.cpp", "max_issues_repo_name": "ruben3d/luna-raytracer", "max_issues_repo_head_hexsha": "14def80f3a11502d78fd0bed757ba19edd0d9057", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/scene/SphereAreaLight.cpp", "max_forks_repo_name": "ruben3d/luna-raytracer", "max_forks_repo_head_hexsha": "14def80f3a11502d78fd0bed757ba19edd0d9057", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-16T17:29:27.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-16T17:29:27.000Z", "avg_line_length": 27.5771812081, "max_line_length": 101, "alphanum_fraction": 0.698223412, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059414036511, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.40274860667510154}}
{"text": "#include <starpu.h>\n#include <starpu_mpi.h>\n#include <vector>\n#include <memory>\n#include <random>\n#include <iostream>\n#ifdef USE_MKL\n#include <mkl_cblas.h>\n#include <mkl_lapacke.h>\n#else\n#include <cblas.h>\n#include <lapacke.h>\n#endif\n#include <Eigen/Core>\n#include <Eigen/Cholesky>\n#include <mpi.h>\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid potrf(void *buffers[], void *cl_arg) { \n    double *A = (double *)STARPU_MATRIX_GET_PTR(buffers[0]);\n    int m = STARPU_MATRIX_GET_NX(buffers[0]);\n    int n = STARPU_MATRIX_GET_NY(buffers[0]);\n    assert(m == n);\n    LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', m, A, m);\n}\nstruct starpu_codelet potrf_cl = {\n    .where = STARPU_CPU,\n    .cpu_funcs = { potrf, NULL },\n    .nbuffers = 1,\n    .modes = { STARPU_RW }\n};\n\nvoid trsm(void *buffers[], void *cl_arg) {\n    double *A = (double *)STARPU_MATRIX_GET_PTR(buffers[0]);\n    double *B = (double *)STARPU_MATRIX_GET_PTR(buffers[1]);\n    int m = STARPU_MATRIX_GET_NX(buffers[1]);\n    int n = STARPU_MATRIX_GET_NY(buffers[1]);\n    assert(STARPU_MATRIX_GET_NX(buffers[0]) == n);\n    assert(STARPU_MATRIX_GET_NY(buffers[0]) == n);\n    cblas_dtrsm(CblasColMajor, CblasRight, CblasLower, CblasTrans, CblasNonUnit, m, n, 1.0, A, n, B, m);\n}\nstruct starpu_codelet trsm_cl = {\n    .where = STARPU_CPU,\n    .cpu_funcs = { trsm, NULL },\n    .nbuffers = 2,\n    .modes = { STARPU_R, STARPU_RW }\n};\n\nvoid syrk(void *buffers[], void *cl_arg) { \n    double *A = (double *)STARPU_MATRIX_GET_PTR(buffers[0]);\n    double *C = (double *)STARPU_MATRIX_GET_PTR(buffers[1]);\n    int m = STARPU_MATRIX_GET_NX(buffers[0]);\n    int k = STARPU_MATRIX_GET_NY(buffers[0]);\n    assert(STARPU_MATRIX_GET_NX(buffers[1]) == m);\n    assert(STARPU_MATRIX_GET_NY(buffers[1]) == m);\n    cblas_dsyrk(CblasColMajor, CblasLower, CblasNoTrans, m, k, -1.0, A, m, 1.0, C, m);\n}\nstruct starpu_codelet syrk_cl = {\n    .where = STARPU_CPU,\n    .cpu_funcs = { syrk, NULL },\n    .nbuffers = 2,\n    .modes = { STARPU_R, STARPU_RW }\n};\n\nvoid gemm(void *buffers[], void *cl_arg) {\n    double *A = (double *)STARPU_MATRIX_GET_PTR(buffers[0]);\n    double *B = (double *)STARPU_MATRIX_GET_PTR(buffers[1]);\n    double *C = (double *)STARPU_MATRIX_GET_PTR(buffers[2]);\n    int m = STARPU_MATRIX_GET_NX(buffers[2]);\n    int n = STARPU_MATRIX_GET_NY(buffers[2]);\n    int k = STARPU_MATRIX_GET_NY(buffers[0]);\n    assert(STARPU_MATRIX_GET_NX(buffers[0]) == m);\n    assert(STARPU_MATRIX_GET_NX(buffers[1]) == n);\n    assert(STARPU_MATRIX_GET_NY(buffers[1]) == k);\n    cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, m, n, k, -1.0, A, m, B, n, 1.0, C, m);\n  }\nstruct starpu_codelet gemm_cl = {\n    .where = STARPU_CPU,\n    .cpu_funcs = { gemm, NULL },\n    .nbuffers = 3,\n    .modes = { STARPU_R, STARPU_R, STARPU_RW }\n};\n\nvoid cholesky(const int block_size, const int num_blocks, const int rank, const int size, const int test, const int nrow, const int ncol, const bool prune, const int upper_block_size) {\n    auto val = [&](int i, int j) { return  1.0/(double)((i-j)*(i-j)+1.0); };\n    vector<MatrixXd*> blocks(num_blocks*num_blocks);\n    vector<starpu_data_handle_t> dataA(num_blocks*num_blocks);\n    auto block_2_rank = [&](int i, int j){return (i % nrow) * ncol + j % ncol;};\n    const int ncores = starpu_worker_get_count_by_type(STARPU_CPU_WORKER);\n    const int matrix_size = block_size * num_blocks;\n    \n    // Warmup MKL\n    {\n        Eigen::MatrixXd A = Eigen::MatrixXd::Identity(256,256);\n        Eigen::MatrixXd B = Eigen::MatrixXd::Identity(256,256);\n        Eigen::MatrixXd C = Eigen::MatrixXd::Identity(256,256);\n        for(int i = 0; i < 10; i++) {\n            cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 256, 256, 256, 1.0, A.data(), 256, B.data(), 256, 1.0, C.data(), 256);\n        }\n    }\n    \n    std::mt19937 gen(2020);\n    assert(upper_block_size <= 2*block_size);\n    const int lower_block_size = 2*block_size - upper_block_size;\n    std::uniform_int_distribution<> distrib(lower_block_size,upper_block_size); // average is block_size\n    if(rank == 0) printf(\"lower_block_size %d, upper_block_size %d\\n\", upper_block_size, lower_block_size);\n    std::vector<int> block_sizes(num_blocks, block_size);\n    {\n        int n = 0;\n        for(int i = 0; i < num_blocks-1; i++) {\n            int bs = std::min(matrix_size - n, distrib(gen));\n            n += bs;\n            block_sizes[i] = bs;\n        }\n        assert(matrix_size - n >= 0);\n        block_sizes[num_blocks-1] = matrix_size - n;\n    }\n    int total = std::accumulate(block_sizes.begin(), block_sizes.end(), 0);\n    assert(total == matrix_size);\n    std::vector<int> block_displ(num_blocks+1, 0);\n    for(int i = 1; i < num_blocks+1; i++) {\n        block_displ[i] = block_displ[i-1] + block_sizes[i-1];\n    }\n    assert(block_displ[num_blocks] == matrix_size);\n    if(rank == 0) {\n        printf(\"block sizes: \");\n        for(int i = 0; i < num_blocks; i++) { \n            assert(block_sizes[i] >= 0);\n            printf(\"%d \", block_sizes[i]); \n        };\n        printf(\"\\n\");\n        printf(\"block displ: \");\n        for(int i = 0; i < num_blocks+1; i++) { \n            assert(block_displ[i] >= 0);\n            printf(\"%d \", block_displ[i]); \n        };\n        printf(\"\\n\");\n    }\n\n    for (int ii=0; ii<num_blocks; ii++) {\n        for (int jj=0; jj<=ii; jj++) {\n            int mpi_rank = block_2_rank(ii,jj);\n            blocks[ii+jj*num_blocks] = new MatrixXd();\n            if (mpi_rank == rank) {\n                auto val_block = [&](int i, int j) { return val(block_displ[ii]+i,block_displ[jj]+j); };\n                *blocks[ii+jj*num_blocks] = MatrixXd::NullaryExpr(block_sizes[ii], block_sizes[jj], val_block);\n            }\n        }\n    }\n\n    auto is_block_non_empty = [&](int i, int j){ return block_sizes[i] > 0 && block_sizes[j] > 0; };\n\n    size_t num_pruned = 0;\n    starpu_mpi_barrier(MPI_COMM_WORLD);\n    double start = starpu_timing_now();\n\n    for (int ii=0; ii<num_blocks; ii++) {\n        for (int jj=0; jj<=ii; jj++) {\n            int mpi_rank = block_2_rank(ii,jj);\n            if(is_block_non_empty(ii,jj)){\n                if (mpi_rank == rank) {\n                    starpu_matrix_data_register(&dataA[ii+jj*num_blocks], STARPU_MAIN_RAM, (uintptr_t)blocks[ii+jj*num_blocks]->data(), block_sizes[ii], block_sizes[ii], block_sizes[jj], sizeof(double));\n                } else {\n                    starpu_matrix_data_register(&dataA[ii+jj*num_blocks], -1, (uintptr_t)NULL, block_sizes[ii], block_sizes[ii], block_sizes[jj], sizeof(double));\n                }\n                if (dataA[ii+jj*num_blocks]) {\n                    starpu_mpi_data_register(dataA[ii+jj*num_blocks], ii+jj*num_blocks, mpi_rank);\n                }\n            }\n        }\n    }\n\n    for (int kk = 0; kk < num_blocks; ++kk) {\n        // POTRF\n        if( (!prune) || block_2_rank(kk,kk) == rank) {\n            if(is_block_non_empty(kk,kk)){\n                starpu_mpi_task_insert(MPI_COMM_WORLD,&potrf_cl,\n                    STARPU_RW, dataA[kk+kk*num_blocks],\n                0);\n            }\n        } else {\n            num_pruned++;\n        }\n\n        for (int ii = kk+1; ii < num_blocks; ++ii) {\n            // TRSM\n            if( (!prune) || block_2_rank(kk,kk) == rank || block_2_rank(ii,kk) == rank) {\n                if(is_block_non_empty(ii,kk)){\n                    starpu_mpi_task_insert(MPI_COMM_WORLD,&trsm_cl,\n                        STARPU_R,  dataA[kk+kk*num_blocks],\n                        STARPU_RW, dataA[ii+kk*num_blocks],\n                    0);\n                }\n            } else {\n                num_pruned++;\n            }\n            if(block_sizes[kk] > 0) {\n                starpu_mpi_cache_flush(MPI_COMM_WORLD, dataA[kk+kk*num_blocks]);\n            }\n\n            // SYRK\n            if( (!prune) || block_2_rank(ii,kk) == rank || block_2_rank(ii,ii) == rank) {\n                if(is_block_non_empty(ii,kk)){\n                    starpu_mpi_task_insert(MPI_COMM_WORLD,&syrk_cl, \n                        STARPU_R,  dataA[ii+kk*num_blocks],\n                        STARPU_RW, dataA[ii+ii*num_blocks],\n                    0);\n                }\n            } else {\n                num_pruned++;\n            }\n\n            for (int jj = kk+1; jj < ii; ++jj) {\n                // GEMM\n                if( (!prune) || block_2_rank(ii,kk) == rank || block_2_rank(jj,kk) == rank || block_2_rank(ii,jj) == rank) {\n                    if(is_block_non_empty(ii,kk) && is_block_non_empty(jj,kk)){\n                        starpu_mpi_task_insert(MPI_COMM_WORLD,&gemm_cl,\n                            STARPU_R,  dataA[ii+kk*num_blocks],\n                            STARPU_R,  dataA[jj+kk*num_blocks],\n                            STARPU_RW, dataA[ii+jj*num_blocks],\n                        0);\n                    }\n                } else {\n                    num_pruned++;\n                }\n            }\n            if(block_sizes[kk] > 0 && block_sizes[ii] > 0) {\n                starpu_mpi_cache_flush(MPI_COMM_WORLD, dataA[ii+kk*num_blocks]);\n            }\n        }\n    }\n\n    double end_insertion = starpu_timing_now();\n    starpu_task_wait_for_all();\n    starpu_mpi_barrier(MPI_COMM_WORLD);\n    double end = starpu_timing_now();\n\n    // Makes grep/import to excel easier ; just do\n    // cat output | grep -P '\\[0\\]\\>\\>\\>\\>'\n    // to extract rank 0 info\n    printf(\">>>>test rank nranks ncores matrix_size block_size num_blocks total_time insertion_time prune num_pruned upper_block_size\\n\");\n    printf(\"[%d]>>>>chol_starpu %d %d %d %d %d %d %e %e %d %zd %d\\n\",rank,rank,size,ncores,matrix_size,block_size,num_blocks,(end-start)/1e6,(end_insertion-start)/1e6,prune,num_pruned,upper_block_size);\n\n    for (int ii=0; ii<num_blocks; ii++) {\n        for (int jj=0; jj<=ii; jj++) {\n            if(block_sizes[ii] > 0 && block_sizes[jj] > 0) {\n                starpu_data_unregister(dataA[ii+jj*num_blocks]); \n            }\n        }\n    }\n\n    if (test) {\n        printf(\"Testing...\\n\");\n        for (int ii=0; ii<num_blocks; ii++) {\n            for (int jj=0; jj<=ii; jj++) {\n                int mpi_rank = block_2_rank(ii,jj);\n                if (rank == 0 && rank != mpi_rank) {\n                    blocks[ii+jj*num_blocks] = new MatrixXd(block_sizes[ii], block_sizes[jj]);\n                    MPI_Recv(blocks[ii+jj*num_blocks]->data(), block_sizes[ii]*block_sizes[jj], MPI_DOUBLE, mpi_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n                } else if (rank == mpi_rank && rank != 0) {\n                    MPI_Send(blocks[ii+jj*num_blocks]->data(), block_sizes[ii]*block_sizes[jj], MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);\n                }\n            }\n        }\n        if (rank==0) {\n            MatrixXd B = MatrixXd::NullaryExpr(matrix_size, matrix_size, val);\n            MatrixXd L = MatrixXd::Zero(matrix_size, matrix_size);\n            for (int ii=0; ii<num_blocks; ii++) {\n                for (int jj=0; jj<num_blocks; jj++) {\n                    if (jj<=ii)  {\n                        L.block(block_displ[ii],block_displ[jj],block_sizes[ii],block_sizes[jj])=*blocks[ii+jj*num_blocks];\n                    }\n                }\n            }\n            auto L1=L.triangularView<Lower>();\n            VectorXd x = VectorXd::Random(matrix_size);\n            VectorXd b = B*x;\n            VectorXd bref = b;\n            L1.solveInPlace(b);\n            L1.transpose().solveInPlace(b);\n            double error = (b - x).norm() / x.norm();\n            printf(\"\\nError solve: %e\\n\\n\", error);\n            assert(error < 1e-6);\n        }\n    }\n}\n\nint main(int argc, char **argv)\n{\n    int req = MPI_THREAD_SERIALIZED;\n    int prov = -1;\n    MPI_Init_thread(NULL, NULL, req, &prov);\n    starpu_mpi_init_conf(&argc, &argv, 0, MPI_COMM_WORLD, NULL);\n    int rank, size;\n    starpu_mpi_comm_rank(MPI_COMM_WORLD, &rank);\n    starpu_mpi_comm_size(MPI_COMM_WORLD, &size);\n    if (rank==0) {\n        printf(\"Running on %d CPU cores per rank,\", starpu_worker_get_count_by_type(STARPU_CPU_WORKER));\n        printf(\"and %d ranks in total\\n\", size);\n    }\n    int block_size=10;\n    int num_blocks=1;\n    int test=0;\n    int nrow=1;\n    int ncol=1;\n    bool prune = true;\n    int upper_block_size = block_size;\n\n    if (argc >= 2)\n    {\n        block_size = atoi(argv[1]);\n    }\n    if (argc >= 3)\n    {\n        num_blocks = atoi(argv[2]);\n    }\n\n    if (argc >= 4) {\n        test = atoi(argv[3]);\n    }\n\n    if (argc >= 6) {\n        nrow = atoi(argv[4]);\n        ncol = atoi(argv[5]);\n    }\n\n    if (argc >= 7) {\n        prune = atoi(argv[6]);\n    }\n\n    if (argc >= 8) {\n        upper_block_size = atoi(argv[7]);\n    } else {\n        upper_block_size = block_size;\n    }\n\n    assert(nrow * ncol == size);\n    printf(\"Usage: ./cholesky_mpi block_size num_blocks test nrow ncol prune upper_block_size\\n\");\n    printf(\"block_size,%d\\n\",block_size);\n    printf(\"num_blocks,%d\\n\",num_blocks);\n    printf(\"test,%d\\n\",test);\n    printf(\"nprocs_row,%d\\n\",nrow);\n    printf(\"nprocs_col,%d\\n\",ncol);\n    printf(\"prune,%d\\n\",prune);\n    printf(\"upper_block_size,%d\\n\",upper_block_size);\n    cholesky(block_size, num_blocks, rank, size, test, nrow, ncol, prune, upper_block_size);\n    starpu_mpi_shutdown();\n    MPI_Finalize();\n    return 0;\n}\n", "meta": {"hexsha": "df062af03ecf806dc13f0f2a467509ae848887ec", "size": 13189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "starpu/cholesky_mpi.cpp", "max_stars_repo_name": "leopoldcambier/tasktorrent_paper_benchmarks", "max_stars_repo_head_hexsha": "86ef5c98fa95d6bd42571cd7775f7eae8ddd0e6b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "starpu/cholesky_mpi.cpp", "max_issues_repo_name": "leopoldcambier/tasktorrent_paper_benchmarks", "max_issues_repo_head_hexsha": "86ef5c98fa95d6bd42571cd7775f7eae8ddd0e6b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "starpu/cholesky_mpi.cpp", "max_forks_repo_name": "leopoldcambier/tasktorrent_paper_benchmarks", "max_forks_repo_head_hexsha": "86ef5c98fa95d6bd42571cd7775f7eae8ddd0e6b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3626062323, "max_line_length": 203, "alphanum_fraction": 0.5653195845, "num_tokens": 3724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.40263493288248625}}
{"text": "// An interval object.\n#pragma once\n\n#include <string>\n\n#include <boost/numeric/interval.hpp>\n\n#define USE_FILIB_INTERVALS\n#ifdef USE_FILIB_INTERVALS\n#include <interval/filib_rounding.hpp>\n#endif\n\n#include <utils/eigen_ext.hpp>\n\nnamespace ipc::rigid {\n\nnamespace interval_options {\n    typedef boost::numeric::interval_lib::checking_catch_nan<double>\n        CheckingPolicy;\n} // namespace interval_options\n\n#ifdef USE_FILIB_INTERVALS\n\n// Use filib rounding arithmetic\ntypedef boost::numeric::interval<\n    double,\n    boost::numeric::interval_lib::policies<\n        boost::numeric::interval_lib::save_state<FILibRounding>,\n        interval_options::CheckingPolicy>>\n    Interval;\n\n#elif defined(__APPLE__)\n\n// clang-format off\n#warning \"Rounding modes seem to be broken with trigonometric functions on macOS, unable to compute exact interval arithmetic!\"\n// clang-format on\ntypedef boost::numeric::interval<\n    double,\n    boost::numeric::interval_lib::policies<\n        boost::numeric::interval_lib::save_state<\n            boost::numeric::interval_lib::rounded_transc_exact<double>>,\n        interval_options::CheckingPolicy>>\n    Interval;\n\n#else\n\n// Use proper rounding arithmetic\ntypedef boost::numeric::interval<\n    double,\n    boost::numeric::interval_lib::policies<\n        boost::numeric::interval_lib::save_state<\n            boost::numeric::interval_lib::rounded_transc_std<double>>,\n        interval_options::CheckingPolicy>>\n    Interval;\n\n#endif // USE_FILIB_INTERVALS\n\ntemplate <typename Derived>\ninline Eigen::VectorXd width(const Eigen::MatrixBase<Derived>& x)\n{\n    Eigen::VectorXd w(x.size());\n    for (int i = 0; i < x.size(); i++) {\n        w(i) = width(x(i));\n    }\n    return w;\n}\n\ntemplate <typename Derived>\ninline double diagonal_width(const Eigen::MatrixBase<Derived>& x)\n{\n    Eigen::VectorXd widths = width(x);\n    double w = 0;\n    for (int i = 0; i < widths.size(); i++) {\n        w += widths(i) * widths(i);\n    }\n    return sqrt(w);\n}\n\ntemplate <typename Derived>\ninline bool zero_in(const Eigen::MatrixBase<Derived>& x)\n{\n    // Check if the origin is in the n-dimensional interval\n    for (int i = 0; i < x.size(); i++) {\n        if (!boost::numeric::zero_in(x(i))) {\n            return false;\n        }\n    }\n    return true;\n}\n\ntypedef Vector2<Interval> Vector2I;\ntypedef Vector3<Interval> Vector3I;\ntypedef VectorX<Interval> VectorXI;\ntypedef VectorMax3<Interval> VectorMax3I;\ntypedef Matrix3<Interval> Matrix2I;\ntypedef Matrix3<Interval> Matrix3I;\ntypedef MatrixMax3<Interval> MatrixMax3I;\ntypedef MatrixX<Interval> MatrixXI;\n\n/// @brief Format a string for an Interval\nstd::string fmt_interval(const Interval& i, const int precision = 16);\n/// @brief Format an eigen VectorX<Interval>\nstd::string fmt_eigen_intervals(const VectorXI& x, const int precision = 16);\n} // namespace ipc::rigid\n\nnamespace Eigen {\n\ntemplate <typename BinOp>\nstruct ScalarBinaryOpTraits<ipc::rigid::Interval, double, BinOp> {\n    typedef ipc::rigid::Interval ReturnType;\n};\n\ntemplate <typename BinOp>\nstruct ScalarBinaryOpTraits<double, ipc::rigid::Interval, BinOp> {\n    typedef ipc::rigid::Interval ReturnType;\n};\n\n#if EIGEN_MAJOR_VERSION >= 3\nnamespace internal {\n    template <typename X, typename S, typename P>\n    struct is_convertible<X, boost::numeric::interval<S, P>> {\n        enum { value = is_convertible<X, S>::value };\n    };\n\n    template <typename S, typename P1, typename P2>\n    struct is_convertible<\n        boost::numeric::interval<S, P1>,\n        boost::numeric::interval<S, P2>> {\n        enum { value = true };\n    };\n} // namespace internal\n#endif\n} // namespace Eigen\n", "meta": {"hexsha": "2134c7b8533ec75114f7814d46fdced2174ffb4b", "size": 3614, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/interval/interval.hpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "src/interval/interval.hpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "src/interval/interval.hpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 26.9701492537, "max_line_length": 127, "alphanum_fraction": 0.6972883232, "num_tokens": 874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4026349255062284}}
{"text": "#ifndef RECURSION_SEARCH_HPP\n#define RECURSION_SEARCH_HPP\n/**\n * @file recursion_search.hpp\n *\n * @brief search parameters so that the random number generator's state\n * transition function has an irreducible characteristic polynomial.\n *\n * @author Mutsuo Saito (Hiroshima University)\n * @author Makoto Matsumoto (The University of Tokyo)\n *\n * Copyright (C) 2011 Mutsuo Saito, Makoto Matsumoto,\n * Hiroshima University and The University of Tokyo.\n * All rights reserved.\n *\n * The 3-clause BSD License is applied to this software, see\n * LICENSE.txt\n */\n#include <NTL/GF2X.h>\n#include <NTL/GF2XFactoring.h>\n\nnamespace tinymt {\n    /**\n     * @class Search\n     * search parameters so that the generator's state transition function\n     * has an irreducible characteristic polynomial.\n     * 1) call start() function.\n     * 2) if start() returns true, then call get_random(), get_minpoly(),\n     * or get_count().\n     *\n     * @tparam T generators class\n     * @tparam SG sequential generator\n     */\n    template<class T, class SG> class Search {\n    public:\n        void get_minpoly(NTL::GF2X& minpoly, T& rand) {\n            using namespace std;\n            using namespace NTL;\n\n            vec_GF2 vec;\n            int mexp = rand.get_mexp();\n            vec.SetLength(mexp * 2);\n            for (int i = 0; i < mexp * 2; i++) {\n                vec[i] = rand.generate() & 1;\n            }\n            MinPolySeq(minpoly, vec, mexp);\n        }\n\n        /**\n         * generate random parameters and check if the generator's\n         * state transition function has an irreducible characteristic\n         * polynomial. If found in \\b try_count times, return true, else\n         * return false.\n         *\n         * @param try_count\n         */\n        bool start(int try_count) {\n            long mexp = rand.get_mexp();\n            long degree;\n            for (int i = 0; i < try_count; i++) {\n                rand.setup_param(sg->next());\n                rand.seeding(1);\n                get_minpoly(minpoly, rand);\n                count++;\n                degree = deg(minpoly);\n                if (degree != mexp) {\n                    continue;\n                }\n                if (IterIrredTest(minpoly)) {\n                    return true;\n                }\n            }\n            return false;\n        }\n        /**\n         * call this function after \\b start() has returned true.\n         * @return random number generator class with parameters.\n         */\n        const T& get_random() const {\n            return rand;\n        }\n\n        /**\n         * call this function after \\b start() has returned true.\n         * In this program, if minimal polynomial is irreducible,\n         * then the polynomial is characteristic polynomial of\n         * generator's state transition function.\n         *\n         * @return minimal polynomial of generated sequence.\n         */\n        const NTL::GF2X& get_minpoly() const {\n            return minpoly;\n        }\n\n        /**\n         * @return tried count after this class has created.\n         */\n        int get_count() const {\n            return count;\n        }\n\n        /**\n         * @param rand_ random number generator whose parameters are\n         * searched.\n         * @param seq_generator a sequential number generator which\n         * gives sequential number for searching parameters.\n         *\n         */\n        Search(const T& rand_, SG& seq_generator) :\n            rand(rand_)\n            {\n                sg = &seq_generator;\n                count = 0;\n            }\n    private:\n        T rand;\n        NTL::GF2X minpoly;\n        SG *sg;\n        int count;\n    };\n}\n#endif\n", "meta": {"hexsha": "ebecce63e656cdbdd313596578fa4d97a90ad4a7", "size": 3664, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdparty/tinymt/dc/include/recursion_search.hpp", "max_stars_repo_name": "mwbrown/circa", "max_stars_repo_head_hexsha": "425b4a3042addab813447813cc45888a012b2c2e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 175.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T05:51:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T10:07:45.000Z", "max_issues_repo_path": "3rdparty/tinymt/dc/include/recursion_search.hpp", "max_issues_repo_name": "mwbrown/circa", "max_issues_repo_head_hexsha": "425b4a3042addab813447813cc45888a012b2c2e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-04-04T08:15:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-06T00:04:20.000Z", "max_forks_repo_path": "3rdparty/tinymt/dc/include/recursion_search.hpp", "max_forks_repo_name": "mwbrown/circa", "max_forks_repo_head_hexsha": "425b4a3042addab813447813cc45888a012b2c2e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2015-09-08T20:37:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T09:47:04.000Z", "avg_line_length": 29.7886178862, "max_line_length": 74, "alphanum_fraction": 0.5431222707, "num_tokens": 806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5813030906443133, "lm_q1q2_score": 0.4026349255062284}}
{"text": "#include <iostream>\n#include <fstream>\n#include <strstream>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <ceres/ceres.h>\n#include <igl/point_mesh_squared_distance.h>\n#include <igl/copyleft/marching_cubes.h>\n\ntypedef double FT;\ntypedef Eigen::Matrix<FT, Eigen::Dynamic, Eigen::Dynamic> MatrixX;\ntypedef Eigen::Matrix<FT, Eigen::Dynamic, 1> VectorX;\ntypedef Eigen::Matrix<FT, 3, 1> Vector3;\n\nclass UniformGrid\n{\npublic:\n\tUniformGrid()\n\t: N(0)\n\t{}\n\tUniformGrid(int _N) {\n\t\tN = _N;\n\t\tdistances.resize(N);\n\t\tfor (auto& d : distances) {\n\t\t\td.resize(N);\n\t\t\tfor (auto& v : d)\n\t\t\t\tv.resize(N, 1e30);\n\t\t}\n\t}\n\ttemplate <class T>\n\tT distance(const T* const p) const {\n\t\tint px = *(double*)&p[0] * N;\n\t\tint py = *(double*)&p[1] * N;\n\t\tint pz = *(double*)&p[2] * N;\n\t\tif (px < 0 || py < 0 || pz < 0 || px >= N - 1 || py >= N - 1 || pz >= N - 1) {\n\t\t\tT l = (T)0;\n\t\t\tif (px < 0)\n\t\t\t\tl = l + -p[0] * (T)N;\n\t\t\telse if (px >= N)\n\t\t\t\tl = l + (p[0] * (T)N - (T)(N - 1 - 1e-3));\n\n\t\t\tif (py < 0)\n\t\t\t\tl = l + -p[1] * (T)N;\n\t\t\telse if (py >= N)\n\t\t\t\tl = l + (p[1] * (T)N - (T)(N - 1 - 1e-3));\n\n\t\t\tif (pz < 0)\n\t\t\t\tl = l + -p[2] * (T)N;\n\t\t\telse if (pz >= N)\n\t\t\t\tl = l + (p[2] * (T)N - (T)(N - 1 - 1e-3));\n\n\t\t\treturn l;\n\t\t}\n\t\tT wx = p[0] * (T)N - (T)px;\n\t\tT wy = p[1] * (T)N - (T)py;\n\t\tT wz = p[2] * (T)N - (T)pz;\n\t\tT w0 = ((T)1 - wx) * ((T)1 - wy) * ((T)1 - wz) * distances[pz    ][py    ][px    ];\n\t\tT w1 = wx \t\t   * ((T)1 - wy) * ((T)1 - wz) * distances[pz    ][py    ][px + 1];\n\t\tT w2 = ((T)1 - wx) * wy \t\t * ((T)1 - wz) * distances[pz    ][py + 1][px    ];\n\t\tT w3 = wx \t\t   * wy \t\t * ((T)1 - wz) * distances[pz    ][py + 1][px + 1];\n\t\tT w4 = ((T)1 - wx) * ((T)1 - wy) * wz \t\t   * distances[pz + 1][py    ][px    ];\n\t\tT w5 = wx \t\t   * ((T)1 - wy) * wz \t\t   * distances[pz + 1][py    ][px + 1];\n\t\tT w6 = ((T)1 - wx) * wy \t\t * wz\t\t   * distances[pz + 1][py + 1][px    ];\n\t\tT w7 = wx \t\t   * wy \t\t * wz \t\t   * distances[pz + 1][py + 1][px + 1];\n\t\tT res = w0 + w1 + w2 + w3 + w4 + w5 + w6 + w7;\n\t\tT thres = (T)0.02;\n\n\t\t//commented out for deform_tune\n\t\tif (res > thres)\n\t\t\tres = thres;\n\t\t//\n\t\t\n\t\treturn res;\n\t}\n\tint N;\n\tstd::vector<std::vector<std::vector<double> > > distances;\n};\n\nstruct LengthError {\n  LengthError(const Eigen::Vector3d& v_, double lambda_)\n  : v(v_), lambda(lambda_) {}\n\n  template <typename T>\n  bool operator()(const T* const p1,\n                  const T* const p2,\n                  T* residuals) const {\n  \tT px = p1[0] - p2[0];\n  \tT py = p1[1] - p2[1];\n  \tT pz = p1[2] - p2[2];\n  \tresiduals[0] = px - v[0];\n  \tresiduals[1] = py - v[1];\n  \tresiduals[2] = pz - v[2];\n    return true;\n  }\n\n   // Factory to hide the construction of the CostFunction object from\n   // the client code.\n   static ceres::CostFunction* Create(const Eigen::Vector3d& v, const double lambda_) {\n     return (new ceres::AutoDiffCostFunction<LengthError, 3, 3, 3>(\n                 new LengthError(v, lambda_)));\n   }\n   double lambda;\n   Eigen::Vector3d v;\n};\n\nstruct DistanceError {\n  DistanceError(UniformGrid* grid_)\n  : grid(grid_) {}\n\n  template <typename T>\n  bool operator()(const T* const p1,\n                  T* residuals) const {\n  \tresiduals[0] = grid->distance(p1);\n  \tresiduals[1] = (T)0;\n  \tresiduals[2] = (T)0;\n    return true;\n  }\n\n   // Factory to hide the construction of the CostFunction object from\n   // the client code.\n   static ceres::CostFunction* Create(UniformGrid* grid) {\n     return (new ceres::AutoDiffCostFunction<DistanceError, 3, 3>(\n                 new DistanceError(grid)));\n   }\n   UniformGrid* grid;\n};\n\nclass Mesh\n{\npublic:\n\tMesh() : scale(1.0) {}\n\tstd::vector<Eigen::Vector3d> V;\n\tstd::vector<Eigen::Vector3i> F;\n\tvoid ReadOBJ(const char* filename) {\n\t\tstd::ifstream is(filename);\n\t\tchar buffer[256];\n\t\twhile (is.getline(buffer, 256)) {\n\t\t\tstd::strstream str;\n\t\t\tstr << buffer;\n\t\t\tstr >> buffer;\n\t\t\tif (strcmp(buffer, \"v\") == 0) {\n\t\t\t\tdouble x, y, z;\n\t\t\t\tstr >> x >> y >> z;\n\t\t\t\tV.push_back(Eigen::Vector3d(x, y, z));\n\t\t\t}\n\t\t\telse if (strcmp(buffer, \"f\") == 0) {\n\t\t\t\tEigen::Vector3i f;\n\t\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\t\tstr >> buffer;\n\t\t\t\t\tint id = 0;\n\t\t\t\t\tint p = 0;\n\t\t\t\t\twhile (buffer[p] != '/') {\n\t\t\t\t\t\tid = id * 10 + (buffer[p] - '0');\n\t\t\t\t\t\tp += 1;\n\t\t\t\t\t}\n\t\t\t\t\tf[j] = id - 1;\n\t\t\t\t}\n\t\t\t\tF.push_back(f);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid ReadOBJ_Manifold(const char* filename) {\n\t\tstd::ifstream is(filename);\n\t\tchar buffer[256];\n\t\twhile (is.getline(buffer, 256)) {\n\t\t\tstd::strstream str;\n\t\t\tstr << buffer;\n\t\t\tstr >> buffer;\n\t\t\tif (strcmp(buffer, \"v\") == 0) {\n\t\t\t\tdouble x, y, z;\n\t\t\t\tstr >> x >> y >> z;\n\t\t\t\tV.push_back(Eigen::Vector3d(x, y, z));\n\t\t\t}\n\t\t\telse if (strcmp(buffer, \"f\") == 0) {\n\t\t\t\tEigen::Vector3i f;\n\t\t\t\tint idx_x, idx_y, idx_z;\n\t\t\t\tstr >> idx_x >> idx_y >> idx_z;\n\t\t\t\t// std::cout<<idx_x <<' '<< idx_y <<' '<< idx_z <<std::endl;\n\t\t\t\tf = Eigen::Vector3i(idx_x-1, idx_y-1, idx_z-1);\n\t\t\t\tF.push_back(f);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid WriteOBJ(const char* filename) {\n\t\tstd::ofstream os(filename);\n\t\tfor (int i = 0; i < V.size(); ++i) {\n\t\t\tos << \"v \" << V[i][0] << \" \" << V[i][1] << \" \" << V[i][2] << \"\\n\";\n\t\t}\n\t\tfor (int i = 0; i < F.size(); ++i) {\n\t\t\tos << \"f \" << F[i][0] + 1 << \" \" << F[i][1] + 1 << \" \" << F[i][2] + 1 << \"\\n\";\n\t\t}\n\t\tos.close();\n\t}\n\tdouble scale;\n\tEigen::Vector3d pos;\n\tvoid Normalize() {\n\t\tdouble min_p[3], max_p[3];\n\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\tmin_p[j] = 1e30;\n\t\t\tmax_p[j] = -1e30;\n\t\t\tfor (int i = 0; i < V.size(); ++i) {\n\t\t\t\tif (V[i][j] < min_p[j])\n\t\t\t\t\tmin_p[j] = V[i][j];\n\t\t\t\tif (V[i][j] > max_p[j])\n\t\t\t\t\tmax_p[j] = V[i][j];\n\t\t\t}\n\t\t}\n\t\tscale = std::max(max_p[0] - min_p[0], std::max(max_p[1] - min_p[1], max_p[2] - min_p[2])) * 1.1;\n\t\tfor (int j = 0; j < 3; ++j)\n\t\t\tpos[j] = min_p[j] - 0.05 * scale;\n\t\tfor (auto& v : V) {\n\t\t\tv = (v - pos) / scale;\n\t\t}\n\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\tmin_p[j] = 1e30;\n\t\t\tmax_p[j] = -1e30;\n\t\t\tfor (int i = 0; i < V.size(); ++i) {\n\t\t\t\tif (V[i][j] < min_p[j])\n\t\t\t\t\tmin_p[j] = V[i][j];\n\t\t\t\tif (V[i][j] > max_p[j])\n\t\t\t\t\tmax_p[j] = V[i][j];\n\t\t\t}\n\t\t}\n\t}\n\tvoid ApplyTransform(Mesh& m) {\n\t\tpos = m.pos;\n\t\tscale = m.scale;\n\t\tfor (auto& v : V) {\n\t\t\tv = (v - pos) / scale;\n\t\t}\n\t}\n\tvoid ConstructDistanceField(UniformGrid& grid) {\n\t\tEigen::MatrixXd P(grid.N * grid.N * grid.N, 3);\n\t\tint offset = 0;\n\t\tfor (int i = 0; i < grid.N; ++i) {\n\t\t\tfor (int j = 0; j < grid.N; ++j) {\n\t\t\t\tfor (int k = 0; k < grid.N; ++k) {\n\t\t\t\t\tP.row(offset) = Eigen::Vector3d(double(k) / grid.N, double(j) / grid.N, double(i) / grid.N);\n\t\t\t\t\toffset += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tEigen::MatrixXd V2(V.size(), 3);\n\t\tfor (int i = 0; i < V.size(); ++i)\n\t\t\tV2.row(i) = V[i];\n\n\t\tEigen::MatrixXi F2(F.size(), 3);\n\t\tfor (int i = 0; i < F.size(); ++i)\n\t\t\tF2.row(i) = F[i];\n\n\t\tEigen::MatrixXd N(F.size(), 3);\n\t\tfor (int i = 0; i < F.size(); ++i) {\n\t\t\tEigen::Vector3d x = V[F[i][1]] - V[F[i][0]];\n\t\t\tEigen::Vector3d y = V[F[i][2]] - V[F[i][0]];\n\t\t\tN.row(i) = x.cross(y).normalized();\n\t\t}\n\n\t\tEigen::VectorXd sqrD;\n\t\tEigen::VectorXi I;\n\t\tEigen::MatrixXd C;\n\t\tigl::point_mesh_squared_distance(P,V2,F2,sqrD,I,C);\n\n\t\toffset = 0;\n\n\t\tfor (int i = 0; i < grid.N; ++i) {\n\t\t\tfor (int j = 0; j < grid.N; ++j) {\n\t\t\t\tfor (int k = 0; k < grid.N; ++k) {\n\t\t\t\t\tEigen::Vector3d n = N.row(I[offset]);\n\t\t\t\t\tEigen::Vector3d off = P.row(offset);\n\t\t\t\t\toff -= V[F[I[offset]][0]];\n\t\t\t\t\tdouble d = n.dot(off);\n\t\t\t\t\td = 1;\n\t\t\t\t\tif (d > 0)\n\t\t\t\t\t\tgrid.distances[i][j][k] = sqrt(sqrD[offset]);\n\t\t\t\t\telse\n\t\t\t\t\t\tgrid.distances[i][j][k] = sqrt(-sqrD[offset]);\n\t\t\t\t\toffset += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tvoid FromDistanceField(UniformGrid& grid) {\n\t\tEigen::VectorXd S(grid.N * grid.N * grid.N);\n\t\tEigen::MatrixXd GV(grid.N * grid.N * grid.N, 3);\n\t\tint offset = 0;\n\t\tfor (int i = 0; i < grid.N; ++i) {\n\t\t\tfor (int j = 0; j < grid.N; ++j) {\n\t\t\t\tfor (int k = 0; k < grid.N; ++k) {\n\t\t\t\t\tS[offset] = grid.distances[i][j][k];\n\t\t\t\t\tGV.row(offset) = Eigen::Vector3d(k, j, i);\n\t\t\t\t\toffset += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tEigen::MatrixXd SV;\n\t\tEigen::MatrixXi SF;\n\t\tigl::copyleft::marching_cubes(S,GV,grid.N,grid.N,grid.N,SV,SF);\n\t\tV.resize(SV.rows());\n\t\tF.resize(SF.rows());\n\t\tfor (int i = 0; i < SV.rows(); ++i)\n\t\t\tV[i] = SV.row(i) / (double)grid.N;\n\t\tfor (int i = 0; i < SF.rows(); ++i)\n\t\t\tF[i] = SF.row(i);\n\t}\n\n\tvoid Deform(UniformGrid& grid) {\n\t\tdouble lambda = 1e-3;\n\t\tceres::Problem problem;\n\n\t\t//Move vertices\n\t\tstd::vector<ceres::ResidualBlockId> v_block_ids;\n\t\tfor (int i = 0; i < V.size(); ++i) {\n\t\t\tceres::CostFunction* cost_function = DistanceError::Create(&grid);\n\t\t\tceres::ResidualBlockId block_id = problem.AddResidualBlock(cost_function, 0, V[i].data());\n\t\t\tv_block_ids.push_back(block_id);\t\t\t\n\t\t}\n\n\t\t//Enforce rigidity\n\t\tstd::vector<ceres::ResidualBlockId> edge_block_ids;\n\t\tfor (int i = 0; i < F.size(); ++i) {\n\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\tEigen::Vector3d v = (V[F[i][j]] - V[F[i][(j + 1) % 3]]);\n\t\t\t\tceres::CostFunction* cost_function = LengthError::Create(v, lambda);\n\t\t\t\tceres::ResidualBlockId block_id = problem.AddResidualBlock(cost_function, 0, V[F[i][j]].data(), V[F[i][(j + 1) % 3]].data());\n\t\t\t\tedge_block_ids.push_back(block_id);\n\t\t\t}\n\t\t}\n\n\t\tceres::Solver::Options options;\n\t\toptions.max_num_iterations = 100;\n\t\toptions.linear_solver_type = ceres::SPARSE_SCHUR;\n\t\toptions.minimizer_progress_to_stdout = true;\n\t\tceres::Solver::Summary summary;\n\t\tceres::Solve(options, &problem, &summary);\n\t\tstd::cout << summary.FullReport() << \"\\n\";\n\n\t\t//V error\n\t\tceres::Problem::EvaluateOptions v_options;\n\t\tv_options.residual_blocks = v_block_ids;\n\t\tdouble v_cost;\n\t\tproblem.Evaluate(v_options, &v_cost, NULL, NULL, NULL);\n\t\tstd::cout<<\"Vertices cost: \"<<v_cost<<std::endl;\n\n\t\t//E error\n\t\tceres::Problem::EvaluateOptions edge_options;\n\t\tedge_options.residual_blocks = edge_block_ids;\n\t\tdouble edge_cost;\n\t\tproblem.Evaluate(edge_options, &edge_cost, NULL, NULL, NULL);\n\t\tstd::cout<<\"Rigidity cost: \"<<edge_cost<<std::endl;\n\n\t\tdouble final_cost = v_cost + edge_cost;\n\t\tstd::cout<<\"Final cost: \"<<final_cost<<std::endl;\n\t}\n\n\tdouble Get_Final_Cost(Mesh& ref){\n\t\t//normalize by number of vertices and faces\n\t\tint ref_num_v = ref.V.size();\n\t\tint source_num_f = F.size();\n\n\t\tMatrixX SV(V.size(), 3), RV(ref.V.size(), 3);\n\t\tEigen::MatrixXi SF(F.size(), 3);\n\t\tfor (int i = 0; i < V.size(); ++i)\n\t\t\tSV.row(i) = V[i];\n\t\tfor (int i = 0; i < ref.V.size(); ++i)\n\t\t\tRV.row(i) = ref.V[i];\n\t\tfor (int i = 0; i < F.size(); ++i)\n\t\t\tSF.row(i) = F[i];\n\n\n\t\tVectorX sqrD;\n\t\tEigen::VectorXi I;\n\t\tMatrixX C;\n\t\tigl::point_mesh_squared_distance(RV, SV, SF,sqrD,I,C);\n\t\tFT coverage_cost = sqrD.sum() * 0.5;\n\t\tstd::cout<<\"Coverage cost: \"<<coverage_cost << std::endl;\n\n\t\tFT rigidity_cost = 0.0;\n\t\tstd::cout<<\"Rigidity cost: \"<<rigidity_cost<<std::endl;\n\n\t\tFT final_cost = coverage_cost/ref_num_v + rigidity_cost/source_num_f;\n\t\tstd::cout<<\"Final cost: \"<<final_cost<<std::endl;\n\n\t\treturn final_cost;\n\t}\n\n};\n\n//For deformation\nint main(int argc, char** argv) {\n\tif (argc < 4) {\n\t\tprintf(\"./deform source.obj reference.obj output.obj textfile_name\\n\");\n\t\treturn 0;\n\t}\n\t//Deform source to fit the reference\n\n\tMesh src, ref;\n\tsrc.ReadOBJ_Manifold(argv[1]);\n\tref.ReadOBJ_Manifold(argv[2]);\n\n\t//Get number of vertices and faces\n\tstd::cout<<\"Source:\\t\\t\"<<\"Num vertices: \"<<src.V.size()<<\"\\tNum faces: \"<<src.F.size()<<std::endl;\n\tstd::cout<<\"Reference:\\t\"<<\"Num vertices: \"<<ref.V.size()<<\"\\tNum faces: \"<<ref.F.size()<<std::endl<<std::endl;\n\n\tUniformGrid grid(100);\n\tref.Normalize();\n\tsrc.ApplyTransform(ref);\n\n\tref.ConstructDistanceField(grid);\n\n\tsrc.Deform(grid);\n\n\tdouble cost;\n\tcost = src.Get_Final_Cost(ref);\n\n\tdouble threshold = 1e-3;\n\n\t//for deform_tune\n\t// double threshold = 1e-3;\n\t// double threshold = 5e-4; #does not filter valid deformations\n\n\tif (cost > threshold){\n\t\tstd::cout<<\"INVALID\"<<std::endl;\n\t\t// return 0;\n\t}\n\n\telse {\n\t\tstd::cout<<\"Deformed\"<<std::endl;\t\t\n\t}\n\n\tstd::string text_file_name = argv[4];\n\tstd::ofstream outfile;\n\toutfile.open(text_file_name, std::fstream::in | std::fstream::out | std::fstream::app);\n\tif (!outfile){\n\t\toutfile.open(text_file_name,  std::fstream::in | std::fstream::out | std::fstream::trunc);\n\t} \n\t//output_objectcost\n\toutfile<<argv[3]<<'\\t'<<cost<<std::endl;\n\toutfile.close();\n\n\tstd::ifstream is(argv[1]);\n\tstd::ofstream os(argv[3]);\n\tchar buffer[1024];\n\tint offset = 0;\n\twhile (is.getline(buffer, 1024)) {\n\t\tif (buffer[0] == 'v' && buffer[1] == ' ') {\n\t\t\tauto v = src.V[offset++] * src.scale + src.pos;\n\t\t\tos << \"v \" << v[0] << \" \" << v[1] << \" \" << v[2] << \"\\n\";\n\t\t} else {\n\t\t\tos << buffer << \"\\n\";\n\t\t}\n\t}\n\n\tis.close();\n\tos.close();\n\treturn 0;\n}\n\n", "meta": {"hexsha": "5592b3e9ed12134783f06aaa01a72804bf0a373e", "size": 12361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "meshdeform/deform.cpp", "max_stars_repo_name": "mikacuy/deformation_aware_embedding", "max_stars_repo_head_hexsha": "7a2cef54328c51d2bfc582fdd5b119a24e19a9ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2020-09-11T01:17:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T23:22:45.000Z", "max_issues_repo_path": "meshdeform/deform.cpp", "max_issues_repo_name": "star-cold/deformation_aware_embedding", "max_issues_repo_head_hexsha": "d5982209f072015bdc16abf281cb0f045b928720", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-16T21:41:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-25T04:06:59.000Z", "max_forks_repo_path": "meshdeform/deform.cpp", "max_forks_repo_name": "star-cold/deformation_aware_embedding", "max_forks_repo_head_hexsha": "d5982209f072015bdc16abf281cb0f045b928720", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2020-09-26T08:42:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T09:29:03.000Z", "avg_line_length": 26.6976241901, "max_line_length": 129, "alphanum_fraction": 0.5525442925, "num_tokens": 4513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8244619350028205, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.40257107291535094}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_LOG_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_LOG_HPP_INCLUDED\n\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n\n#include <boost/simd/function/any.hpp>\n#include <boost/simd/function/bitwise_and.hpp>\n#include <boost/simd/function/bitwise_cast.hpp>\n#include <boost/simd/function/dec.hpp>\n#include <boost/simd/function/fma.hpp>\n#include <boost/simd/function/frexp.hpp>\n#include <boost/simd/function/genmask.hpp>\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/if_minus.hpp>\n#include <boost/simd/function/if_nan_else.hpp>\n#include <boost/simd/function/is_ltz.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/musl.hpp>\n#include <boost/simd/function/plain.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/function/tofloat.hpp>\n\n#include <boost/simd/constant/half.hpp>\n#include <boost/simd/constant/inf.hpp>\n#include <boost/simd/constant/minf.hpp>\n#include <boost/simd/constant/smallestposval.hpp>\n#include <boost/simd/constant/sqrt_2o_2.hpp>\n#include <boost/simd/constant/two.hpp>\n\n#include <boost/simd/detail/constant/log_2hi.hpp>\n#include <boost/simd/detail/constant/log_2lo.hpp>\n\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n\n\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  namespace bs = boost::simd;\n\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::single_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 const & a0) const BOOST_NOEXCEPT\n    {\n      return musl_(log)(a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_< bd::double_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (A0 const & a0) const BOOST_NOEXCEPT\n    {\n      return musl_(log)(a0);\n    }\n  };\n  BOOST_DISPATCH_OVERLOAD_IF ( log_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::musl_tag\n                          , bs::pack_< bd::single_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const musl_tag &, const A0& a0) const BOOST_NOEXCEPT\n    {\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      A0 x =  a0;\n      iA0 k(0);\n      auto isnez = is_nez(a0);\n#ifndef BOOST_SIMD_NO_DENORMALS\n      auto test = is_less(a0, Smallestposval<A0>())&&isnez;\n      if (any(test))\n      {\n        k = if_minus(test, k, iA0(23));\n        x = if_else(test, x*A0(0x1p23f), x);\n      }\n#endif\n      uiA0 ix = bitwise_cast<uiA0>(x);\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      ix += 0x3f800000 - 0x3f3504f3;\n    //ix +=\n      k += bitwise_cast<iA0>(ix>>23) - 0x7f;\n      ix = (ix&0x007fffff) + 0x3f3504f3;\n      x =  bitwise_cast<A0>(ix);\n      A0 f = dec(x);\n      A0 s = f/(Two<A0>() + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0, 0x3eccce13, 0x3e789e26>(w);\n      A0 t2= z*horn<A0, 0x3f2aaaaa, 0x3e91e9ee>(w);\n      A0 R = t2 + t1;\n\n      A0 hfsq = Half<A0>()*sqr(f);\n      A0 dk = tofloat(k);\n      A0 r = fma(dk, Log_2hi<A0>(), ((fma(s, (hfsq+R), dk*Log_2lo<A0>()) - hfsq) + f));\n#ifndef BOOST_SIMD_NO_INFINITIES\n      A0 zz = if_else(isnez, if_else(a0 == Inf<A0>(), Inf<A0>(), r), Minf<A0>());\n#else\n      A0 zz = if_else(isnez, r, Minf<A0>());\n#endif\n      return if_nan_else(is_ltz(a0), zz);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::musl_tag\n                             , bs::pack_< bd::double_<A0>, X>\n                             )\n  {\n    BOOST_FORCEINLINE A0 operator() (const musl_tag &, const A0& a0) const BOOST_NOEXCEPT\n    {\n      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      A0 x = a0;\n      uiA0 hx = bitwise_cast<uiA0>(x) >> 32;\n      iA0 k(0);\n      auto isnez = is_nez(a0);\n\n#ifndef BOOST_SIMD_NO_DENORMALS\n      auto test = is_less(a0, Smallestposval<A0>())&&isnez;\n      if (any(test))\n      {\n        k = if_minus(test, k, iA0(54));\n        x = if_else(test, x*A0(0x1p54), x);\n      }\n#endif\n      /* reduce x into [sqrt(2)/2, sqrt(2)] */\n      hx += 0x3ff00000 - 0x3fe6a09e;\n      k += bitwise_cast<iA0>(hx>>20) - 0x3ff;\n      A0 dk = tofloat(k);\n      hx = (hx&0x000fffff) + 0x3fe6a09e;\n      x = bitwise_cast<A0>(hx<<32 | (bitwise_and(0xffffffffull, bitwise_cast<uiA0>(x))));\n\n      A0 f = dec(x);\n      A0 hfsq = Half<A0>()*sqr(f);\n      A0 s = f/(Two<A0>() + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0,\n                    0x3fd999999997fa04ll,\n                    0x3fcc71c51d8e78afll,\n                    0x3fc39a09d078c69fll\n                    > (w);\n      A0 t2= z*horn<A0,\n                    0x3fe5555555555593ll,\n                    0x3fd2492494229359ll,\n                    0x3fc7466496cb03dell,\n                    0x3fc2f112df3e5244ll\n                    > (w);\n      A0 R = t2+t1;\n      A0 r = fma(dk, Log_2hi<A0>(), ((fma(s, (hfsq+R), dk*Log_2lo<A0>()) - hfsq) + f));\n#ifndef BOOST_SIMD_NO_INFINITIES\n      A0 zz = if_else(isnez, if_else(a0 == Inf<A0>(), Inf<A0>(), r), Minf<A0>());\n#else\n      A0 zz = if_else(isnez, r, Minf<A0>());\n#endif\n      return if_nan_else(is_ltz(a0), zz);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log_\n                          , (typename A0, typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::plain_tag\n                          , bs::pack_< bd::single_<A0>, X>\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const plain_tag &, const A0& a0) const BOOST_NOEXCEPT\n    {\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      A0 x =  a0;\n      iA0 k(0);\n      auto isnez = is_nez(a0);\n#ifndef BOOST_SIMD_NO_DENORMALS\n      auto test = is_less(a0, Smallestposval<A0>())&&isnez;\n      if (any(test))\n      {\n        k = if_minus(test, k, iA0(23));\n        x = if_else(test, x*A0(0x1p23f), x);\n      }\n#endif\n      iA0 kk;\n      std::tie(x, kk) = fast_(frexp)(x);\n      A0  x_lt_sqrthf = genmask(Sqrt_2o_2<A0>() > x);\n      k += kk+bitwise_cast<iA0>(x_lt_sqrthf);\n      A0 f = dec(x+bitwise_and(x, x_lt_sqrthf));\n      A0 dk = tofloat(k);\n      A0 s = f/(Two<A0>() + f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0, 0x3eccce13, 0x3e789e26>(w);\n      A0 t2= z*horn<A0, 0x3f2aaaaa, 0x3e91e9ee>(w);\n      A0 R = t2 + t1;\n\n      A0 hfsq = Half<A0>()*sqr(f);\n      A0 r = fma(dk, Log_2hi<A0>(), ((fma(s, (hfsq+R), dk*Log_2lo<A0>()) - hfsq) + f));\n#ifndef BOOST_SIMD_NO_INFINITIES\n      A0 zz = if_else(isnez, if_else(a0 == Inf<A0>(), Inf<A0>(), r), Minf<A0>());\n#else\n      A0 zz = if_else(isnez, r, Minf<A0>());\n#endif\n      return if_nan_else(is_ltz(a0), zz);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD_IF ( log_\n                             , (typename A0, typename X)\n                             , (detail::is_native<X>)\n                             , bd::cpu_\n                             , bs::plain_tag\n                             , bs::pack_< bd::double_<A0>, X>\n                             )\n  {\n    BOOST_FORCEINLINE A0 operator() (const plain_tag &, const A0& a0) const BOOST_NOEXCEPT\n    {\n//      using uiA0 = bd::as_integer_t<A0, unsigned>;\n      using iA0 = bd::as_integer_t<A0,   signed>;\n      A0 x =  a0;\n      iA0 k(0);\n      auto isnez = is_nez(a0);\n#ifndef BOOST_SIMD_NO_DENORMALS\n      auto test = is_less(a0, Smallestposval<A0>())&&isnez;\n      if (any(test))\n      {\n        k = if_minus(test, k, iA0(23));\n        x = if_else(test, x*A0(0x1p23f), x);\n      }\n#endif\n      iA0 kk;\n      std::tie(x, kk) = fast_(frexp)(x);\n      A0  x_lt_sqrthf = genmask(Sqrt_2o_2<A0>() >  x);\n      k += kk+bitwise_cast<iA0>(x_lt_sqrthf);\n      A0 f = dec(x+bitwise_and(x, x_lt_sqrthf));\n      A0 dk = tofloat(k);\n      // compute approximation\n      A0 s = f/(Two<A0>()+f);\n      A0 z = sqr(s);\n      A0 w = sqr(z);\n      A0 t1= w*horn<A0,\n        0x3fd999999997fa04ll,\n        0x3fcc71c51d8e78afll,\n        0x3fc39a09d078c69fll\n        > (w);\n      A0 t2= z*horn<A0,\n        0x3fe5555555555593ll,\n        0x3fd2492494229359ll,\n        0x3fc7466496cb03dell,\n        0x3fc2f112df3e5244ll\n        > (w);\n      A0 R = t2+t1;\n      A0 hfsq = Half<A0>()* sqr(f);\n      A0 r = fma(dk, Log_2hi<A0>(), ((fma(s, (hfsq+R), dk*Log_2lo<A0>()) - hfsq) + f));\n#ifndef BOOST_SIMD_NO_INFINITIES\n      A0 zz = if_else(isnez, if_else(a0 == Inf<A0>(), Inf<A0>(), r), Minf<A0>());\n#else\n      A0 zz = if_else(isnez, r, Minf<A0>());\n#endif\n      return if_nan_else(is_ltz(a0), zz);\n    }\n  };\n\n} } }\n\n#endif\n  /*\n   *   1. Argument Reduction: find k and f such that\n   *                      x = 2^k * (1+f),\n   *         where  sqrt(2)/2 < 1+f < sqrt(2) .\n   *\n   *   2. Approximation of log(1+f).\n   *      Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s)\n   *               = 2s + 2/3 s**3 + 2/5 s**5 + .....,\n   *               = 2s + s*R\n   *      We use a special Remez algorithm on [0,0.1716] to generate\n   *      a polynomial of degree 14 to approximate R The maximum error\n   *      of this polynomial approximation is bounded by 2**-58.45. In\n   *      other words,\n   *                      2      4      6      8      10      12      14\n   *          R(z) ~ Lg1*s +Lg2*s +Lg3*s +Lg4*s +Lg5*s  +Lg6*s  +Lg7*s\n   *      (the values of Lg1 to Lg7 are listed in the program)\n   *      and\n   *          |      2          14          |     -58.45\n   *          | Lg1*s +...+Lg7*s    -  R(z) | <= 2\n   *          |                             |\n   *      Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2.\n   *      In order to guarantee error in log below 1ulp, we compute log\n   *      by\n   *              log(1+f) = f - s*(f - R)        (if f is not too large)\n   *              log(1+f) = f - (hfsq - s*(hfsq+R)).     (better accuracy)\n   *\n   *      3. Finally,  log(x) = k*ln2 + log(1+f).\n   *                          = k*ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*ln2_lo)))\n   *         Here ln2 is split into two floating point number:\n   *                      ln2_hi + ln2_lo,\n   *         where n*ln2_hi is always exact for |n| < 2000.\n   */\n", "meta": {"hexsha": "60e645aea564cb70d1b7a036ff5bd825fdf8750d", "size": 11188, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/arch/common/simd/function/log.hpp", "max_stars_repo_name": "timblechmann/boost.simd", "max_stars_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "include/boost/simd/arch/common/simd/function/log.hpp", "max_issues_repo_name": "timblechmann/boost.simd", "max_issues_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/arch/common/simd/function/log.hpp", "max_forks_repo_name": "timblechmann/boost.simd", "max_forks_repo_head_hexsha": "2217f1d0102193799469b533e3a7118bf4a77dde", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 34.4246153846, "max_line_length": 100, "alphanum_fraction": 0.5120664998, "num_tokens": 3643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.40255224604759143}}
{"text": "#include <Rcpp.h>\r\n#include <boost/multi_array.hpp>\r\n\r\nusing namespace Rcpp;\r\n\r\n// [[Rcpp::plugins(\"cpp11\")]]\r\n// [[Rcpp::depends(BH)]]\r\n\r\n//'Estep in girt.\r\n//'\r\n//'@param x DataFrame.\r\n//'@param a0 discrinimation parameter vector.\r\n//'@param b0 difficulty parameter vector.\r\n//'@param Xq node of theta dist.\r\n//'@param AX weight of theta dist.\r\n//'@param Yr node of phi dist.\r\n//'@param BY weighit of phi dist.\r\n//'@param D factor constant.\r\n//'@param group a vector.\r\n//'@param ind a design matrix for group.\r\n//'@param resp a design matrix for person.\r\n//'@param MLL a vector\r\n//'@export\r\n// [[Rcpp::export]]\r\n\r\n\r\nList Estep_girt_mg(DataFrame x,\r\n                NumericVector a0,\r\n                NumericVector b0,\r\n                NumericVector Xq,\r\n                NumericMatrix AX, // multigroup\r\n                NumericVector Yr,\r\n                NumericMatrix BY, // multigroup\r\n                double D,\r\n                IntegerVector group,\r\n                IntegerMatrix ind, // design matrix\r\n                IntegerMatrix resp, // design matrix\r\n                NumericVector MLL\r\n){\r\n\r\n  const int nj = x.length();// item n\r\n  const int nn = x.nrows(); // subject n\r\n  const int nq = Xq.length(); // node of theta\r\n  const int nr = Yr.length(); // node of phi\r\n  const int ng = max(group); // group n\r\n\r\n  boost::multi_array <double, 4> knqr (boost::extents[ng][nn][nq][nr]);\r\n  boost::multi_array <double, 4> hqr (boost::extents[ng][nn][nq][nr]);\r\n  boost::multi_array <double, 4> Njqr (boost::extents[ng][nj][nq][nr]);\r\n  boost::multi_array <double, 4> rjqr (boost::extents[ng][nj][nq][nr]);\r\n  //Dimension d(nn,nq,nr);\r\n  //NumericVector knqr(d);\r\n\r\n  // もとのデータフレームから項目反応パタンだけを抜き出し，行列として保存\r\n  NumericMatrix xall(nn, nj);\r\n  for (int j=0; j<nj; j++){\r\n    NumericVector kk = x[j];\r\n    for(int i=0; i<nn; i++){\r\n      double k = kk[i];\r\n      xall(i,j) = k;\r\n    }\r\n  }\r\n\r\n  int u;\r\n  double phi, theta, a, b, tt, t, A, e, p;\r\n  for(int g=0; g<ng; g++){\r\n    for(int r=0; r<nr; r++){\r\n      phi = Yr[r];\r\n      //Rprintf(\"%d % / 100%\\r\", 100/nr*(r+1));\r\n      for(int q=0; q<nq; q++){\r\n        theta = Xq[q];\r\n        for(int i=0; i<nn; i++){\r\n          if(group[i] != g+1) continue; // 集団に属さない受験者の部分はスキップ\r\n          t = 1.0;\r\n          for(int j=0; j<nj; j++){\r\n            a = a0[j];\r\n            b = b0[j];\r\n            A = sqrt(1+phi*phi*a*a);\r\n            e = exp(-D*a/A*(theta-b));\r\n            p = 1/(1+e);\r\n            u = xall(i,j);\r\n            if(u == 1){ // correct\r\n              tt = p;\r\n            } else if (u == 0) { // incorrect\r\n              tt = 1.0-p;\r\n            } else { // NA\r\n              tt = 1;\r\n            }\r\n            t = t*tt;\r\n          }\r\n          knqr[g][i][q][r] = t*AX[q]*BY[r];\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  // 各受検者のtheta, phiごとに事後分布の重みを計算する。\r\n  // 規格化\r\n  double f = 0; // 周辺対数尤度代入用\r\n  for(int g=0; g<ng; g++){\r\n    for(int i=0; i<nn; i++){\r\n      if(group[i] != g+1) continue; // 集団に属さない受験者の部分はスキップ\r\n      double Z = 0;\r\n      for(int q=0; q<nq; q++){ // 総和を1にするための分母の計算 // sum\r\n        for(int r=0; r<nr; r++){\r\n          Z += knqr[g][i][q][r];\r\n        }\r\n      }\r\n      f += log(Z);\r\n      for(int q=0; q<nq; q++){ // 総和を1にするための分母の計算 // sum\r\n        for(int r=0; r<nr; r++){\r\n          double l = knqr[g][i][q][r];\r\n          hqr[g][i][q][r] =  l / Z;\r\n        }\r\n      }\r\n    }\r\n  }\r\n  MLL.push_back(f);\r\n  if(traits::is_nan<REALSXP>(f)){\r\n    // 対数尤度の計算に失敗したら，計算を中止する。\r\n    stop(\"Can't calculate marginal log likelihood.\");\r\n  }\r\n\r\n  for(int g=0; g<ng; g++){\r\n    for(int j=0; j<nj; j++){ // 各分点の期待度数\r\n      if(ind(g,j) == 0) continue;\r\n      for(int q=0; q<nq; q++){\r\n        for(int r=0; r<nr; r++){\r\n          double k = 0;\r\n          for(int i=0; i<nn; i++){ // 欠測値がある場合，項目ごとに受検者数が異なる。\r\n            if(resp(i,j)==0) continue;\r\n            k += hqr[g][i][q][r];\r\n          }\r\n          Njqr[g][j][q][r]= k;\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  for(int g=0; g<ng; g++){\r\n    for(int j=0; j<nj; j++){ // 各分点の正答受検者の期待度数\r\n      if(ind(g,j) == 0) continue;\r\n      for(int q=0; q<nq; q++){\r\n        for(int r=0; r<nr; r++){\r\n          double h = 0;\r\n          for(int i=0; i<nn; i++){ // sum\r\n            //double d = resp(i,j);\r\n            if(resp(i,j) == 0) continue;\r\n            h += xall(i,j)*hqr[g][i][q][r];\r\n          }\r\n          rjqr[g][j][q][r] = h;\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n\r\n\r\n  return List::create(_[\"knqr\"]=knqr, _[\"hqr\"]=hqr, _[\"Njqr\"]=Njqr, _[\"rjqr\"]=rjqr, _[\"MLL\"]=MLL);\r\n\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "4f12a1f65f3644c7d724c493ab1cb6ad3bad8832", "size": 4482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Estep_girt_mg.cpp", "max_stars_repo_name": "takuizum/irtfun2", "max_stars_repo_head_hexsha": "def9eac15a1150804f3702cf3f84df1c638a1c38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Estep_girt_mg.cpp", "max_issues_repo_name": "takuizum/irtfun2", "max_issues_repo_head_hexsha": "def9eac15a1150804f3702cf3f84df1c638a1c38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Estep_girt_mg.cpp", "max_forks_repo_name": "takuizum/irtfun2", "max_forks_repo_head_hexsha": "def9eac15a1150804f3702cf3f84df1c638a1c38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3292682927, "max_line_length": 99, "alphanum_fraction": 0.4567157519, "num_tokens": 1617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145999, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.4025474789223704}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include <boost/program_options.hpp>\n#include <cstddef>\n#include <string>\n\n#include \"DataStructures/ComplexModalVector.hpp\"\n#include \"DataStructures/DataBox/DataBox.hpp\"\n#include \"DataStructures/DataVector.hpp\"\n#include \"DataStructures/SpinWeighted.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"DataStructures/VariablesTag.hpp\"\n#include \"Evolution/Systems/Cce/BoundaryData.hpp\"\n#include \"Evolution/Systems/Cce/ReducedWorldtubeModeRecorder.hpp\"\n#include \"Evolution/Systems/Cce/SpecBoundaryData.hpp\"\n#include \"Evolution/Systems/Cce/Tags.hpp\"\n#include \"Evolution/Systems/Cce/WorldtubeBufferUpdater.hpp\"\n#include \"NumericalAlgorithms/Spectral/SwshCoefficients.hpp\"\n#include \"NumericalAlgorithms/Spectral/SwshCollocation.hpp\"\n#include \"Parallel/Printf.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\n// Charm looks for this function but since we build without a main function or\n// main module we just have it be empty\nextern \"C\" void CkRegisterMainModule(void) {}\n\n// from a time-varies-fastest set of buffers provided by\n// `MetricWorldtubeH5BufferUpdater` extract the set of coefficients for a\n// particular time given by `buffer_time_offset` into the `time_span` size of\n// buffer.\nvoid slice_buffers_to_libsharp_modes(\n    const gsl::not_null<Variables<Cce::cce_metric_input_tags>*>\n        coefficients_set,\n    const Variables<Cce::cce_metric_input_tags>& coefficients_buffers,\n    const size_t time_span, const size_t buffer_time_offset, const size_t l_max,\n    const size_t computation_l_max) {\n  SpinWeighted<ComplexModalVector, 0> spin_weighted_buffer;\n\n  for (const auto& libsharp_mode :\n       Spectral::Swsh::cached_coefficients_metadata(computation_l_max)) {\n    for (size_t i = 0; i < 3; ++i) {\n      for (size_t j = i; j < 3; ++j) {\n        tmpl::for_each<\n            tmpl::list<Cce::Tags::detail::SpatialMetric,\n                       Cce::Tags::detail::Dr<Cce::Tags::detail::SpatialMetric>,\n                       Tags::dt<Cce::Tags::detail::SpatialMetric>>>(\n            [&i, &j, &libsharp_mode, &spin_weighted_buffer,\n             &coefficients_buffers, &coefficients_set, &l_max,\n             &computation_l_max, &time_span, &buffer_time_offset](auto tag_v) {\n              using tag = typename decltype(tag_v)::type;\n              spin_weighted_buffer.set_data_ref(\n                  get<tag>(*coefficients_set).get(i, j).data(),\n                  Spectral::Swsh::size_of_libsharp_coefficient_vector(\n                      computation_l_max));\n              if (libsharp_mode.l > l_max) {\n                Spectral::Swsh::goldberg_modes_to_libsharp_modes_single_pair(\n                    libsharp_mode, make_not_null(&spin_weighted_buffer), 0, 0.0,\n                    0.0);\n\n              } else {\n                Spectral::Swsh::goldberg_modes_to_libsharp_modes_single_pair(\n                    libsharp_mode, make_not_null(&spin_weighted_buffer), 0,\n                    get<tag>(coefficients_buffers)\n                        .get(i, j)[time_span *\n                                       Spectral::Swsh::goldberg_mode_index(\n                                           l_max, libsharp_mode.l,\n                                           static_cast<int>(libsharp_mode.m)) +\n                                   buffer_time_offset],\n                    get<tag>(coefficients_buffers)\n                        .get(i, j)[time_span *\n                                       Spectral::Swsh::goldberg_mode_index(\n                                           l_max, libsharp_mode.l,\n                                           -static_cast<int>(libsharp_mode.m)) +\n                                   buffer_time_offset]);\n              }\n            });\n      }\n      tmpl::for_each<tmpl::list<Cce::Tags::detail::Shift,\n                                Cce::Tags::detail::Dr<Cce::Tags::detail::Shift>,\n                                Tags::dt<Cce::Tags::detail::Shift>>>(\n          [&i, &libsharp_mode, &spin_weighted_buffer, &coefficients_buffers,\n           &coefficients_set, &l_max, &computation_l_max, &time_span,\n           &buffer_time_offset](auto tag_v) {\n            using tag = typename decltype(tag_v)::type;\n            spin_weighted_buffer.set_data_ref(\n                get<tag>(*coefficients_set).get(i).data(),\n                Spectral::Swsh::size_of_libsharp_coefficient_vector(\n                    computation_l_max));\n\n            if (libsharp_mode.l > l_max) {\n              Spectral::Swsh::goldberg_modes_to_libsharp_modes_single_pair(\n                  libsharp_mode, make_not_null(&spin_weighted_buffer), 0, 0.0,\n                  0.0);\n\n            } else {\n              Spectral::Swsh::goldberg_modes_to_libsharp_modes_single_pair(\n                  libsharp_mode, make_not_null(&spin_weighted_buffer), 0,\n                  get<tag>(coefficients_buffers)\n                      .get(i)[time_span *\n                                  Spectral::Swsh::goldberg_mode_index(\n                                      l_max, libsharp_mode.l,\n                                      static_cast<int>(libsharp_mode.m)) +\n                              buffer_time_offset],\n                  get<tag>(coefficients_buffers)\n                      .get(i)[time_span *\n                                  Spectral::Swsh::goldberg_mode_index(\n                                      l_max, libsharp_mode.l,\n                                      -static_cast<int>(libsharp_mode.m)) +\n                              buffer_time_offset]);\n            }\n          });\n    }\n    tmpl::for_each<tmpl::list<Cce::Tags::detail::Lapse,\n                              Cce::Tags::detail::Dr<Cce::Tags::detail::Lapse>,\n                              Tags::dt<Cce::Tags::detail::Lapse>>>(\n        [&libsharp_mode, &spin_weighted_buffer, &coefficients_buffers,\n         &coefficients_set, &l_max, &computation_l_max, &time_span,\n         &buffer_time_offset](auto tag_v) {\n          using tag = typename decltype(tag_v)::type;\n          spin_weighted_buffer.set_data_ref(\n              get(get<tag>(*coefficients_set)).data(),\n              Spectral::Swsh::size_of_libsharp_coefficient_vector(\n                  computation_l_max));\n\n          if (libsharp_mode.l > l_max) {\n            Spectral::Swsh::goldberg_modes_to_libsharp_modes_single_pair(\n                libsharp_mode, make_not_null(&spin_weighted_buffer), 0, 0.0,\n                0.0);\n\n          } else {\n            Spectral::Swsh::goldberg_modes_to_libsharp_modes_single_pair(\n                libsharp_mode, make_not_null(&spin_weighted_buffer), 0,\n                get(get<tag>(coefficients_buffers))\n                    [time_span * Spectral::Swsh::goldberg_mode_index(\n                                     l_max, libsharp_mode.l,\n                                     static_cast<int>(libsharp_mode.m)) +\n                     buffer_time_offset],\n                get(get<tag>(coefficients_buffers))\n                    [time_span * Spectral::Swsh::goldberg_mode_index(\n                                     l_max, libsharp_mode.l,\n                                     -static_cast<int>(libsharp_mode.m)) +\n                     buffer_time_offset]);\n          }\n        });\n  }\n}\n\n// read in the data from a (previously standard) SpEC worldtube file\n// `input_file`, perform the boundary computation, and dump the (considerably\n// smaller) dataset associated with the spin-weighted scalars to `output_file`.\nvoid perform_cce_worldtube_reduction(\n    const std::string& input_file, const std::string& output_file,\n    const size_t buffer_depth, const size_t l_max_factor,\n    const bool fix_spec_normalization = false) {\n  Cce::MetricWorldtubeH5BufferUpdater buffer_updater{input_file};\n  const size_t l_max = buffer_updater.get_l_max();\n  // Perform the boundary computation to scalars at twice the input l_max to be\n  // absolutely certain that there are no problems associated with aliasing.\n  const size_t computation_l_max = l_max_factor * l_max;\n\n  // we're not interpolating, this is just a reasonable number of rows to ingest\n  // at a time.\n  const size_t size_of_buffer = square(l_max + 1) * (buffer_depth);\n  const DataVector& time_buffer = buffer_updater.get_time_buffer();\n\n  Variables<Cce::cce_metric_input_tags> coefficients_buffers{size_of_buffer};\n  Variables<Cce::cce_metric_input_tags> coefficients_set{\n      Spectral::Swsh::size_of_libsharp_coefficient_vector(computation_l_max)};\n\n  Variables<Cce::Tags::characteristic_worldtube_boundary_tags<\n      Cce::Tags::BoundaryValue>>\n      boundary_data_variables{\n          Spectral::Swsh::number_of_swsh_collocation_points(computation_l_max)};\n\n  using reduced_boundary_tags =\n      tmpl::list<Cce::Tags::BoundaryValue<Cce::Tags::BondiBeta>,\n                 Cce::Tags::BoundaryValue<Cce::Tags::BondiU>,\n                 Cce::Tags::BoundaryValue<Cce::Tags::BondiQ>,\n                 Cce::Tags::BoundaryValue<Cce::Tags::BondiW>,\n                 Cce::Tags::BoundaryValue<Cce::Tags::BondiJ>,\n                 Cce::Tags::BoundaryValue<Cce::Tags::Dr<Cce::Tags::BondiJ>>,\n                 Cce::Tags::BoundaryValue<Cce::Tags::Du<Cce::Tags::BondiJ>>,\n                 Cce::Tags::BoundaryValue<Cce::Tags::BondiR>,\n                 Cce::Tags::BoundaryValue<Cce::Tags::Du<Cce::Tags::BondiR>>>;\n\n  size_t time_span_start = 0;\n  size_t time_span_end = 0;\n  Cce::ReducedWorldtubeModeRecorder recorder{output_file};\n\n  ComplexModalVector output_goldberg_mode_buffer{square(computation_l_max + 1)};\n  ComplexModalVector output_libsharp_mode_buffer{\n      Spectral::Swsh::size_of_libsharp_coefficient_vector(computation_l_max)};\n\n  for (size_t i = 0; i < time_buffer.size(); ++i) {\n    const double time = time_buffer[i];\n    Parallel::printf(\"reducing data at time : %f / %f \\r\", time,\n                     time_buffer[time_buffer.size() - 1]);\n    buffer_updater.update_buffers_for_time(\n        make_not_null(&coefficients_buffers), make_not_null(&time_span_start),\n        make_not_null(&time_span_end), time, l_max, 0, buffer_depth);\n\n    slice_buffers_to_libsharp_modes(\n        make_not_null(&coefficients_set), coefficients_buffers,\n        time_span_end - time_span_start, i - time_span_start, l_max,\n        computation_l_max);\n\n    if (not buffer_updater.has_version_history() and fix_spec_normalization) {\n      Cce::create_bondi_boundary_data_from_unnormalized_spec_modes(\n          make_not_null(&boundary_data_variables),\n          get<Cce::Tags::detail::SpatialMetric>(coefficients_set),\n          get<Tags::dt<Cce::Tags::detail::SpatialMetric>>(coefficients_set),\n          get<Cce::Tags::detail::Dr<Cce::Tags::detail::SpatialMetric>>(\n              coefficients_set),\n          get<Cce::Tags::detail::Shift>(coefficients_set),\n          get<Tags::dt<Cce::Tags::detail::Shift>>(coefficients_set),\n          get<Cce::Tags::detail::Dr<Cce::Tags::detail::Shift>>(\n              coefficients_set),\n          get<Cce::Tags::detail::Lapse>(coefficients_set),\n          get<Tags::dt<Cce::Tags::detail::Lapse>>(coefficients_set),\n          get<Cce::Tags::detail::Dr<Cce::Tags::detail::Lapse>>(\n              coefficients_set),\n          buffer_updater.get_extraction_radius(), computation_l_max);\n    } else {\n      Cce::create_bondi_boundary_data(\n          make_not_null(&boundary_data_variables),\n          get<Cce::Tags::detail::SpatialMetric>(coefficients_set),\n          get<Tags::dt<Cce::Tags::detail::SpatialMetric>>(coefficients_set),\n          get<Cce::Tags::detail::Dr<Cce::Tags::detail::SpatialMetric>>(\n              coefficients_set),\n          get<Cce::Tags::detail::Shift>(coefficients_set),\n          get<Tags::dt<Cce::Tags::detail::Shift>>(coefficients_set),\n          get<Cce::Tags::detail::Dr<Cce::Tags::detail::Shift>>(\n              coefficients_set),\n          get<Cce::Tags::detail::Lapse>(coefficients_set),\n          get<Tags::dt<Cce::Tags::detail::Lapse>>(coefficients_set),\n          get<Cce::Tags::detail::Dr<Cce::Tags::detail::Lapse>>(\n              coefficients_set),\n          buffer_updater.get_extraction_radius(), computation_l_max);\n    }\n    // loop over the tags that we want to dump.\n    tmpl::for_each<reduced_boundary_tags>(\n        [&recorder, &boundary_data_variables, &output_goldberg_mode_buffer,\n         &output_libsharp_mode_buffer, &l_max, &computation_l_max,\n         &time](auto tag_v) {\n          using tag = typename decltype(tag_v)::type;\n          SpinWeighted<ComplexModalVector, tag::type::type::spin>\n              spin_weighted_libsharp_view;\n          spin_weighted_libsharp_view.set_data_ref(\n              output_libsharp_mode_buffer.data(),\n              output_libsharp_mode_buffer.size());\n          Spectral::Swsh::swsh_transform(\n              computation_l_max, 1, make_not_null(&spin_weighted_libsharp_view),\n              get(get<tag>(boundary_data_variables)));\n          SpinWeighted<ComplexModalVector, tag::type::type::spin>\n              spin_weighted_goldberg_view;\n          spin_weighted_goldberg_view.set_data_ref(\n              output_goldberg_mode_buffer.data(),\n              output_goldberg_mode_buffer.size());\n          Spectral::Swsh::libsharp_to_goldberg_modes(\n              make_not_null(&spin_weighted_goldberg_view),\n              spin_weighted_libsharp_view, computation_l_max);\n\n          // The goldberg format type is in strictly increasing l modes, so to\n          // reduce to a smaller l_max, we can just take the first (l_max + 1)^2\n          // values.\n          ComplexModalVector reduced_goldberg_view{\n              output_goldberg_mode_buffer.data(), square(l_max + 1)};\n          recorder.append_worldtube_mode_data(\n              \"/\" + Cce::dataset_label_for_tag<tag>(), time,\n              reduced_goldberg_view, l_max, tag::type::type::spin == 0);\n        });\n  }\n  Parallel::printf(\"\\n\");\n}\n\n/*\n * This executable is used for converting the unnecessarily large SpEC worldtube\n * data format into a far smaller representation (roughly a factor of 4) just\n * storing the worldtube scalars that are required as input for CCE.\n */\nint main(int argc, char** argv) {\n  boost::program_options::positional_options_description pos_desc;\n  pos_desc.add(\"old_spec_cce_file\", 1).add(\"output_file\", 1);\n\n  boost::program_options::options_description desc(\"Options\");\n  desc.add_options()(\"help,h,\", \"show this help message\")(\n      \"input_file\", boost::program_options::value<std::string>()->required(),\n      \"name of old CCE data file\")(\n      \"output_file\", boost::program_options::value<std::string>()->required(),\n      \"output filename\")(\n      \"fix_spec_normalization\",\n      \"Apply corrections associated with documented SpEC \"\n      \"worldtube file errors\")(\n      \"buffer_depth\",\n      boost::program_options::value<size_t>()->default_value(2000),\n      \"number of time steps to load during each call to the file-accessing \"\n      \"routines. Higher values mean fewer, larger loads from file into RAM.\")(\n      \"lmax_factor\", boost::program_options::value<size_t>()->default_value(2),\n      \"the boundary computations will be performed at a resolution that is \"\n      \"lmax_factor times the input file lmax to avoid aliasing\");\n\n  boost::program_options::variables_map vars;\n\n  boost::program_options::store(\n      boost::program_options::command_line_parser(argc, argv)\n          .positional(pos_desc)\n          .options(desc)\n          .run(),\n      vars);\n\n  if (vars.count(\"help\") != 0u or vars.count(\"input_file\") == 0u or\n      vars.count(\"output_file\") == 0u) {\n    Parallel::printf(\"%s\\n\", desc);\n    return 0;\n  }\n\n  perform_cce_worldtube_reduction(vars[\"input_file\"].as<std::string>(),\n                                  vars[\"output_file\"].as<std::string>(),\n                                  vars[\"buffer_depth\"].as<size_t>(),\n                                  vars[\"lmax_factor\"].as<size_t>(),\n                                  vars.count(\"fix_spec_normalization\") != 0u);\n}\n", "meta": {"hexsha": "7393213d35f2e0a4fa29dd84415779dee1da718a", "size": 15897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Executables/ReduceCceWorldtube/ReduceCceWorldtube.cpp", "max_stars_repo_name": "nilsvu/spectre", "max_stars_repo_head_hexsha": "1455b9a8d7e92db8ad600c66f54795c29c3052ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 117.0, "max_stars_repo_stars_event_min_datetime": "2017-04-08T22:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:23:36.000Z", "max_issues_repo_path": "src/Executables/ReduceCceWorldtube/ReduceCceWorldtube.cpp", "max_issues_repo_name": "GitHimanshuc/spectre", "max_issues_repo_head_hexsha": "4de4033ba36547113293fe4dbdd77591485a4aee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3177.0, "max_issues_repo_issues_event_min_datetime": "2017-04-07T21:10:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:59.000Z", "max_forks_repo_path": "src/Executables/ReduceCceWorldtube/ReduceCceWorldtube.cpp", "max_forks_repo_name": "geoffrey4444/spectre", "max_forks_repo_head_hexsha": "9350d61830b360e2d5b273fdd176dcc841dbefb0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 85.0, "max_forks_repo_forks_event_min_datetime": "2017-04-07T19:36:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T10:21:00.000Z", "avg_line_length": 48.9138461538, "max_line_length": 80, "alphanum_fraction": 0.6237025854, "num_tokens": 3614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.40254747311096145}}
{"text": "#include \"fbstab/components/mpc_data.h\"\n\n#include <Eigen/Dense>\n#include <cmath>\n#include <iostream>\n#include <stdexcept>\n\n#include \"tools/matrix_sequence.h\"\n\nnamespace fbstab {\n\nusing MatrixXd = Eigen::MatrixXd;\nusing VectorXd = Eigen::VectorXd;\nusing Map = Eigen::Map<Eigen::MatrixXd>;\nusing ConstMap = Eigen::Map<const Eigen::MatrixXd>;\n\nvoid MpcData::gemvH(const Eigen::VectorXd& x, double a, double b,\n                    Eigen::VectorXd* y) const {\n  if (y == nullptr) {\n    throw std::runtime_error(\"In MpcData::gemvH: y input is null.\");\n  }\n  if (x.size() != nz_ || y->size() != nz_) {\n    throw std::runtime_error(\"Size mismatch in MpcData::gemvH.\");\n  }\n  if (b == 0.0) {\n    y->fill(0.0);\n  } else if (b != 1.0) {\n    (*y) *= b;\n  }\n\n  // Create reshaped views of input and output vectors.\n  Map w(y->data(), nx_ + nu_,\n        N_ + 1);  // w = reshape(y, [nx + nu, N + 1]);\n  ConstMap v(x.data(), nx_ + nu_,\n             N_ + 1);  // v = reshape(x, [nx + nu, N + 1]);\n  for (int i = 0; i < N_ + 1; i++) {\n    const auto& Q = Q_(i);\n    const auto& S = S_(i);\n    const auto& R = R_(i);\n\n    // These variables alias w.\n    auto yx = w.block(0, i, nx_, 1);\n    auto yu = w.block(nx_, i, nu_, 1);\n\n    // These variables alias v.\n    const auto vx = v.block(0, i, nx_, 1);\n    const auto vu = v.block(nx_, i, nu_, 1);\n\n    // [yx] += a * [Q(i) S(i)'] [vx]\n    // [yu]        [S(i) R(i) ] [vu]\n    // Using lazyProduct is inefficient so should be avoided when possible.\n    if (a == 1.0) {\n      yx.noalias() += Q * vx + S.transpose() * vu;\n      yu.noalias() += S * vx + R * vu;\n    } else if (a == -1.0) {\n      yx.noalias() -= Q * vx + S.transpose() * vu;\n      yu.noalias() -= S * vx + R * vu;\n    } else {\n      yx += a * Q.lazyProduct(vx);\n      yx += a * S.transpose().lazyProduct(vu);\n      yu += a * S.lazyProduct(vx);\n      yu += a * R.lazyProduct(vu);\n    }\n  }\n}\n\nvoid MpcData::gemvA(const Eigen::VectorXd& x, double a, double b,\n                    Eigen::VectorXd* y) const {\n  if (y == nullptr) {\n    throw std::runtime_error(\"In MpcData::gemvA: y input is null.\");\n  }\n  if (x.size() != nz_ || y->size() != nv_) {\n    throw std::runtime_error(\"Size mismatch in MpcData::gemvA.\");\n  }\n  if (b == 0.0) {\n    y->fill(0.0);\n  } else if (b != 1.0) {\n    (*y) *= b;\n  }\n  // Create reshaped views of input and output vectors.\n  ConstMap z(x.data(), nx_ + nu_, N_ + 1);\n  Map w(y->data(), nc_, N_ + 1);\n\n  for (int i = 0; i < N_ + 1; i++) {\n    const auto& E = E_(i);\n    const auto& L = L_(i);\n\n    // This aliases w.\n    auto yi = w.col(i);\n\n    // These alias z.\n    const auto xi = z.block(0, i, nx_, 1);\n    const auto ui = z.block(nx_, i, nu_, 1);\n\n    // yi += a*(E*vx + L*vu)\n    if (a == 1.0) {\n      yi.noalias() += E * xi + L * ui;\n    } else if (a == -1.0) {\n      yi.noalias() -= E * xi + L * ui;\n    } else {\n      yi += a * E.lazyProduct(xi);\n      yi += a * L.lazyProduct(ui);\n    }\n  }\n}\n\nvoid MpcData::gemvG(const Eigen::VectorXd& x, double a, double b,\n                    Eigen::VectorXd* y) const {\n  if (y == nullptr) {\n    throw std::runtime_error(\"In MpcData::gemvG: y input is null.\");\n  }\n  if (x.size() != nz_ || y->size() != nl_) {\n    throw std::runtime_error(\"Size mismatch in MpcData::gemvG.\");\n  }\n  if (b == 0.0) {\n    y->fill(0.0);\n  } else if (b != 1.0) {\n    (*y) *= b;\n  }\n  // Create reshaped views of input and output vectors.\n  ConstMap z(x.data(), nx_ + nu_, N_ + 1);\n  Map w(y->data(), nx_, N_ + 1);\n\n  w.col(0).noalias() += -a * z.block(0, 0, nx_, 1);\n\n  for (int i = 1; i < N_ + 1; i++) {\n    const auto& A = A_(i - 1);\n    const auto& B = B_(i - 1);\n\n    // Alias for the output at stage i.\n    auto yi = w.col(i);\n    // Aliases for the state and control at stage i - 1.\n    const auto xm1 = z.block(0, i - 1, nx_, 1);\n    const auto um1 = z.block(nx_, i - 1, nu_, 1);\n    // Alias for the state at stage i.\n    const auto xi = z.block(0, i, nx_, 1);\n\n    // y(i) += a*(A(i-1)*x(i-1) + B(i-1)u(i-1) - x(i))\n    if (a == 1.0) {\n      yi.noalias() += A * xm1 + B * um1;\n      yi.noalias() -= xi;\n    } else if (a == -1.0) {\n      yi.noalias() -= A * xm1 + B * um1;\n      yi.noalias() += xi;\n    } else {\n      yi += a * A.lazyProduct(xm1);\n      yi += a * B.lazyProduct(um1);\n      yi -= a * xi;\n    }\n  }\n}\n\nvoid MpcData::gemvGT(const Eigen::VectorXd& x, double a, double b,\n                     Eigen::VectorXd* y) const {\n  if (y == nullptr) {\n    throw std::runtime_error(\"In MpcData::gemvGT: y input is null.\");\n  }\n  if (x.size() != nl_ || y->size() != nz_) {\n    throw std::runtime_error(\"Size mismatch in MpcData::gemvGT.\");\n  }\n  if (b == 0.0) {\n    y->fill(0.0);\n  } else if (b != 1.0) {\n    (*y) *= b;\n  }\n\n  // Create reshaped views of input and output vectors.\n  ConstMap v(x.data(), nx_, N_ + 1);\n  Map w(y->data(), nx_ + nu_, N_ + 1);\n\n  for (int i = 0; i < N_; i++) {\n    const auto& A = A_(i);\n    const auto& B = B_(i);\n\n    // Aliases for the dual variables at stage i and i+1;\n    const auto vi = v.col(i);\n    const auto vp1 = v.col(i + 1);\n\n    // Aliases for the state and control at stage i.\n    auto xi = w.block(0, i, nx_, 1);\n    auto ui = w.block(nx_, i, nu_, 1);\n\n    // x(i) += a*(-v(i) + A(i)' * v(i+1))\n    // u(i) += a*B(i)' * v(i+1)\n    xi.noalias() += -a * vi;\n    if (a == 1.0) {\n      xi.noalias() += A.transpose() * vp1;\n      ui.noalias() += B.transpose() * vp1;\n    } else if (a == -1.0) {\n      xi.noalias() -= A.transpose() * vp1;\n      ui.noalias() -= B.transpose() * vp1;\n    } else {\n      xi.noalias() += a * A.transpose().lazyProduct(vp1);\n    }\n  }\n  // The i = N step of the recursion.\n  w.block(0, N_, nx_, 1).noalias() += -a * v.col(N_);\n}\n\nvoid MpcData::gemvAT(const Eigen::VectorXd& x, double a, double b,\n                     Eigen::VectorXd* y) const {\n  if (y == nullptr) {\n    throw std::runtime_error(\"In MpcData::gemvAT: y input is null.\");\n  }\n  if (x.size() != nv_ || y->size() != nz_) {\n    throw std::runtime_error(\"Size mismatch in MpcData::gemvAT.\");\n  }\n  if (b == 0.0) {\n    y->fill(0.0);\n  } else if (b != 1.0) {\n    (*y) *= b;\n  }\n  // Create reshaped views of input and output vectors.\n  ConstMap v(x.data(), nc_, N_ + 1);\n  Map w(y->data(), nx_ + nu_, N_ + 1);\n\n  for (int i = 0; i < N_ + 1; i++) {\n    const auto& E = E_(i);\n    const auto& L = L_(i);\n\n    auto xi = w.block(0, i, nx_, 1);\n    auto ui = w.block(nx_, i, nu_, 1);\n\n    const auto vi = v.col(i);\n    // x(i) += a*E(i)' * v(i)\n    // u(i) += a*L(i)' * v(i)\n    if (a == 1.0) {\n      xi.noalias() += E.transpose() * vi;\n      ui.noalias() += L.transpose() * vi;\n    } else if (a == -1.0) {\n      xi.noalias() -= E.transpose() * vi;\n      ui.noalias() -= L.transpose() * vi;\n    } else {\n      ui.noalias() += a * L.transpose().lazyProduct(vi);\n      xi.noalias() += a * E.transpose().lazyProduct(vi);\n    }\n  }\n}\n\nvoid MpcData::axpyf(double a, Eigen::VectorXd* y) const {\n  if (y == nullptr) {\n    throw std::runtime_error(\"In MpcData::axpyf: y input is null.\");\n  }\n  if (y->size() != nz_) {\n    throw std::runtime_error(\"Size mismatch in MpcData::axpyf.\");\n  }\n\n  // Create reshaped view of the input vector.\n  Map w(y->data(), nx_ + nu_, N_ + 1);\n\n  for (int i = 0; i < N_ + 1; i++) {\n    auto xi = w.block(0, i, nx_, 1);\n    auto ui = w.block(nx_, i, nu_, 1);\n\n    xi.noalias() += a * q_(i);\n    ui.noalias() += a * r_(i);\n  }\n}\n\nvoid MpcData::axpyh(double a, Eigen::VectorXd* y) const {\n  if (y == nullptr) {\n    throw std::runtime_error(\"In MpcData::axpyh: y input is null.\");\n  }\n  if (y->size() != nl_) {\n    throw std::runtime_error(\"Size mismatch in MpcData::axpyh.\");\n  }\n  // Create reshaped view of the input vector.\n  Map w(y->data(), nx_, N_ + 1);\n  w.col(0) += -a * x0_;\n\n  for (int i = 1; i < N_ + 1; i++) {\n    w.col(i) += -a * c_(i - 1);\n  }\n}\n\nvoid MpcData::axpyb(double a, Eigen::VectorXd* y) const {\n  if (y == nullptr) {\n    throw std::runtime_error(\"In MpcData::axpyb: y input is null.\");\n  }\n  if (y->size() != nv_) {\n    throw std::runtime_error(\"Size mismatch in MpcData::axpyb.\");\n  }\n  // Create reshaped view of the input vector.\n  Map w(y->data(), nc_, N_ + 1);\n\n  for (int i = 0; i < N_ + 1; i++) {\n    w.col(i).noalias() += -a * d_(i);\n  }\n}\n\nvoid MpcData::ValidateInputs() const {\n  bool OK = true;\n  const int N = Q_.length();\n  if (N <= 0) {\n    throw std::runtime_error(\"Horizon length must be at least 1.\");\n  }\n\n  OK = OK && N == R_.length();\n  OK = OK && N == S_.length();\n  OK = OK && N == q_.length();\n  OK = OK && N == r_.length();\n  OK = OK && (N - 1) == A_.length();\n  OK = OK && (N - 1) == B_.length();\n  OK = OK && (N - 1) == c_.length();\n  OK = OK && N == E_.length();\n  OK = OK && N == L_.length();\n  OK = OK && N == d_.length();\n  if (!OK) {\n    throw std::runtime_error(\n        \"Sequence length mismatch in input data to MpcData.\");\n  }\n\n  const int nx = Q_.rows();\n  if (x0_.size() != nx) {\n    throw std::runtime_error(\"Size mismatch in x0 input to MpcData.\");\n  }\n  if (Q_.cols() != nx) {\n    throw std::runtime_error(\"Size mismatch in Q input to MpcData.\");\n  }\n  if (S_.cols() != nx) {\n    throw std::runtime_error(\"Size mismatch in S input to MpcData.\");\n  }\n  if (q_.rows() != nx) {\n    throw std::runtime_error(\"Size mismatch in q input to MpcData.\");\n  }\n  if (E_.cols() != nx) {\n    throw std::runtime_error(\"Size mismatch in E input to MpcData.\");\n  }\n  if (A_.rows() != nx || A_.cols() != nx) {\n    throw std::runtime_error(\"Size mismatch in A input to MpcData.\");\n  }\n  if (B_.rows() != nx) {\n    throw std::runtime_error(\"Size mismatch in B input to MpcData.\");\n  }\n  if (c_.rows() != nx) {\n    throw std::runtime_error(\"Size mismatch in c input to MpcData.\");\n  }\n\n  const int nu = R_.rows();\n  if (R_.cols() != nu) {\n    throw std::runtime_error(\"Size mismatch in R input to MpcData.\");\n  }\n  if (S_.rows() != nu) {\n    throw std::runtime_error(\"Size mismatch in S input to MpcData.\");\n  }\n  if (r_.rows() != nu) {\n    throw std::runtime_error(\"Size mismatch in r input to MpcData.\");\n  }\n  if (L_.cols() != nu) {\n    throw std::runtime_error(\"Size mismatch in L input to MpcData.\");\n  }\n  if (B_.cols() != nu) {\n    throw std::runtime_error(\"Size mismatch in B input to MpcData.\");\n  }\n\n  const int nc = E_.rows();\n  if (L_.rows() != nc) {\n    throw std::runtime_error(\"Size mismatch in L input to MpcData.\");\n  }\n  if (d_.rows() != nc) {\n    throw std::runtime_error(\"Size mismatch in d input to MpcData.\");\n  }\n}\n\n}  // namespace fbstab\n", "meta": {"hexsha": "0bed8c5d97bf1a62c6a9c48a9195890f59692444", "size": 10405, "ext": "cc", "lang": "C++", "max_stars_repo_path": "fbstab/components/mpc_data.cc", "max_stars_repo_name": "tcunis/fbstab", "max_stars_repo_head_hexsha": "25d5259f683427867f140567d739a55ed7359aca", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2019-08-09T18:43:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-07T12:38:27.000Z", "max_issues_repo_path": "fbstab/components/mpc_data.cc", "max_issues_repo_name": "tcunis/fbstab", "max_issues_repo_head_hexsha": "25d5259f683427867f140567d739a55ed7359aca", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2019-08-14T17:33:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-01T12:03:36.000Z", "max_forks_repo_path": "fbstab/components/mpc_data.cc", "max_forks_repo_name": "tcunis/fbstab", "max_forks_repo_head_hexsha": "25d5259f683427867f140567d739a55ed7359aca", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-08-09T19:03:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-07T23:03:33.000Z", "avg_line_length": 28.4289617486, "max_line_length": 75, "alphanum_fraction": 0.5271504085, "num_tokens": 3601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6791787121629466, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.40252653809879735}}
{"text": "/*\n * Copyright 2010,\n * François Bleibel,\n * Olivier Stasse,\n * Nicolas Mansard\n * Joseph Mirabel\n *\n * CNRS/AIST\n *\n */\n\n#include <boost/function.hpp>\n\n#include <sot/core/binary-op.hh>\n#include <sot/core/unary-op.hh>\n#include <sot/core/variadic-op.hh>\n\n#include <sot/core/matrix-geometry.hh>\n\n#include <dynamic-graph/all-commands.h>\n#include <dynamic-graph/factory.h>\n\n#include <boost/numeric/conversion/cast.hpp>\n#include <deque>\n#include <dynamic-graph/linear-algebra.h>\n#include <sot/core/debug.hh>\n#include <sot/core/factory.hh>\n\n#include \"../tools/type-name-helper.hh\"\n\nnamespace dg = ::dynamicgraph;\n\n/* ---------------------------------------------------------------------------*/\n/* ------- GENERIC HELPERS -------------------------------------------------- */\n/* ---------------------------------------------------------------------------*/\n\n#define ADD_COMMAND(name, def) commandMap.insert(std::make_pair(name, def))\n\nnamespace dynamicgraph {\nnamespace sot {\ntemplate <typename TypeIn, typename TypeOut> struct UnaryOpHeader {\n  typedef TypeIn Tin;\n  typedef TypeOut Tout;\n  static inline std::string nameTypeIn(void) {\n    return TypeNameHelper<Tin>::typeName();\n  }\n  static inline std::string nameTypeOut(void) {\n    return TypeNameHelper<Tout>::typeName();\n  }\n  inline void addSpecificCommands(Entity &, Entity::CommandMap_t &) {}\n  inline std::string getDocString() const {\n    return std::string(\"Undocumented unary operator\\n\"\n                       \"  - input  \") +\n           nameTypeIn() +\n           std::string(\"\\n\"\n                       \"  - output \") +\n           nameTypeOut() + std::string(\"\\n\");\n  }\n};\n\n/* ---------------------------------------------------------------------- */\n/* --- ALGEBRA SELECTORS ------------------------------------------------ */\n/* ---------------------------------------------------------------------- */\nstruct VectorSelecter : public UnaryOpHeader<dg::Vector, dg::Vector> {\n  inline void operator()(const Tin &m, Vector &res) const {\n    res.resize(size);\n    Vector::Index r = 0;\n    for (std::size_t i = 0; i < idxs.size(); ++i) {\n      const Vector::Index &R = idxs[i].first;\n      const Vector::Index &nr = idxs[i].second;\n      assert((nr >= 0) && (R + nr <= m.size()));\n      res.segment(r, nr) = m.segment(R, nr);\n      r += nr;\n    }\n    assert(r == size);\n  }\n\n  typedef std::pair<Vector::Index, Vector::Index> segment_t;\n  typedef std::vector<segment_t> segments_t;\n  segments_t idxs;\n  Vector::Index size;\n\n  inline void setBounds(const int &m, const int &M) {\n    idxs = segments_t(1, segment_t(m, M - m));\n    size = M - m;\n  }\n  inline void addBounds(const int &m, const int &M) {\n    idxs.push_back(segment_t(m, M - m));\n    size += M - m;\n  }\n\n  inline void addSpecificCommands(Entity &ent,\n                                  Entity::CommandMap_t &commandMap) {\n    using namespace dynamicgraph::command;\n    std::string doc;\n\n    boost::function<void(const int &, const int &)> setBound =\n        boost::bind(&VectorSelecter::setBounds, this, _1, _2);\n    doc = docCommandVoid2(\"Set the bound of the selection [m,M[.\", \"int (min)\",\n                          \"int (max)\");\n    ADD_COMMAND(\"selec\", makeCommandVoid2(ent, setBound, doc));\n    boost::function<void(const int &, const int &)> addBound =\n        boost::bind(&VectorSelecter::addBounds, this, _1, _2);\n    doc = docCommandVoid2(\"Add a segment to be selected [m,M[.\", \"int (min)\",\n                          \"int (max)\");\n    ADD_COMMAND(\"addSelec\", makeCommandVoid2(ent, addBound, doc));\n  }\n  VectorSelecter() : size(0) {}\n};\n\n/* ---------------------------------------------------------------------- */\nstruct VectorComponent : public UnaryOpHeader<dg::Vector, double> {\n  inline void operator()(const Tin &m, double &res) const {\n    assert(index < m.size());\n    res = m(index);\n  }\n\n  int index;\n  inline void setIndex(const int &m) { index = m; }\n\n  inline void addSpecificCommands(Entity &ent,\n                                  Entity::CommandMap_t &commandMap) {\n    std::string doc;\n\n    boost::function<void(const int &)> callback =\n        boost::bind(&VectorComponent::setIndex, this, _1);\n    doc = command::docCommandVoid1(\"Set the index of the component.\",\n                                   \"int (index)\");\n    ADD_COMMAND(\"setIndex\", command::makeCommandVoid1(ent, callback, doc));\n  }\n  inline std::string getDocString() const {\n    std::string docString(\"Select a component of a vector\\n\"\n                          \"  - input  vector\\n\"\n                          \"  - output double\");\n    return docString;\n  }\n};\n\n/* ---------------------------------------------------------------------- */\nstruct MatrixSelector : public UnaryOpHeader<dg::Matrix, dg::Matrix> {\n  inline void operator()(const Matrix &m, Matrix &res) const {\n    assert((imin <= imax) && (imax <= m.rows()));\n    assert((jmin <= jmax) && (jmax <= m.cols()));\n    res.resize(imax - imin, jmax - jmin);\n    for (int i = imin; i < imax; ++i)\n      for (int j = jmin; j < jmax; ++j)\n        res(i - imin, j - jmin) = m(i, j);\n  }\n\npublic:\n  int imin, imax;\n  int jmin, jmax;\n\n  inline void setBoundsRow(const int &m, const int &M) {\n    imin = m;\n    imax = M;\n  }\n  inline void setBoundsCol(const int &m, const int &M) {\n    jmin = m;\n    jmax = M;\n  }\n\n  inline void addSpecificCommands(Entity &ent,\n                                  Entity::CommandMap_t &commandMap) {\n    using namespace dynamicgraph::command;\n    std::string doc;\n\n    boost::function<void(const int &, const int &)> setBoundsRow =\n        boost::bind(&MatrixSelector::setBoundsRow, this, _1, _2);\n    boost::function<void(const int &, const int &)> setBoundsCol =\n        boost::bind(&MatrixSelector::setBoundsCol, this, _1, _2);\n\n    doc = docCommandVoid2(\"Set the bound on rows.\", \"int (min)\", \"int (max)\");\n    ADD_COMMAND(\"selecRows\", makeCommandVoid2(ent, setBoundsRow, doc));\n\n    doc = docCommandVoid2(\"Set the bound on cols [m,M[.\", \"int (min)\",\n                          \"int (max)\");\n    ADD_COMMAND(\"selecCols\", makeCommandVoid2(ent, setBoundsCol, doc));\n  }\n};\n\n/* ---------------------------------------------------------------------- */\nstruct MatrixColumnSelector : public UnaryOpHeader<dg::Matrix, dg::Vector> {\npublic:\n  inline void operator()(const Tin &m, Tout &res) const {\n    assert((imin <= imax) && (imax <= m.rows()));\n    assert(jcol < m.cols());\n\n    res.resize(imax - imin);\n    for (int i = imin; i < imax; ++i)\n      res(i - imin) = m(i, jcol);\n  }\n\n  int imin, imax;\n  int jcol;\n  inline void selectCol(const int &m) { jcol = m; }\n  inline void setBoundsRow(const int &m, const int &M) {\n    imin = m;\n    imax = M;\n  }\n\n  inline void addSpecificCommands(Entity &ent,\n                                  Entity::CommandMap_t &commandMap) {\n    using namespace dynamicgraph::command;\n    std::string doc;\n\n    boost::function<void(const int &, const int &)> setBoundsRow =\n        boost::bind(&MatrixColumnSelector::setBoundsRow, this, _1, _2);\n    boost::function<void(const int &)> selectCol =\n        boost::bind(&MatrixColumnSelector::selectCol, this, _1);\n\n    doc = docCommandVoid2(\"Set the bound on rows.\", \"int (min)\", \"int (max)\");\n    ADD_COMMAND(\"selecRows\", makeCommandVoid2(ent, setBoundsRow, doc));\n\n    doc = docCommandVoid1(\"Select the col to copy.\", \"int (col index)\");\n    ADD_COMMAND(\"selecCols\", makeCommandVoid1(ent, selectCol, doc));\n  }\n};\n\n/* ---------------------------------------------------------------------- */\nstruct MatrixTranspose : public UnaryOpHeader<dg::Matrix, dg::Matrix> {\n  inline void operator()(const Tin &m, Tout &res) const { res = m.transpose(); }\n};\n\n/* ---------------------------------------------------------------------- */\nstruct Diagonalizer : public UnaryOpHeader<Vector, Matrix> {\n  inline void operator()(const dg::Vector &r, dg::Matrix &res) {\n    res = r.asDiagonal();\n  }\n\npublic:\n  Diagonalizer(void) : nbr(0), nbc(0) {}\n  unsigned int nbr, nbc;\n  inline void resize(const int &r, const int &c) {\n    nbr = r;\n    nbc = c;\n  }\n  inline void addSpecificCommands(Entity &ent,\n                                  Entity::CommandMap_t &commandMap) {\n    using namespace dynamicgraph::command;\n    std::string doc;\n\n    boost::function<void(const int &, const int &)> resize =\n        boost::bind(&Diagonalizer::resize, this, _1, _2);\n\n    doc = docCommandVoid2(\"Set output size.\", \"int (row)\", \"int (col)\");\n    ADD_COMMAND(\"resize\", makeCommandVoid2(ent, resize, doc));\n  }\n};\n\n/* ---------------------------------------------------------------------- */\n/* --- INVERSION -------------------------------------------------------- */\n/* ---------------------------------------------------------------------- */\n\ntemplate <typename matrixgen>\nstruct Inverser : public UnaryOpHeader<matrixgen, matrixgen> {\n  typedef typename UnaryOpHeader<matrixgen, matrixgen>::Tin Tin;\n  typedef typename UnaryOpHeader<matrixgen, matrixgen>::Tout Tout;\n  inline void operator()(const Tin &m, Tout &res) const { res = m.inverse(); }\n};\n\nstruct Normalize : public UnaryOpHeader<dg::Vector, double> {\n  inline void operator()(const dg::Vector &m, double &res) const {\n    res = m.norm();\n  }\n\n  inline std::string getDocString() const {\n    std::string docString(\"Computes the norm of a vector\\n\"\n                          \"  - input  vector\\n\"\n                          \"  - output double\");\n    return docString;\n  }\n};\n\nstruct InverserRotation : public UnaryOpHeader<MatrixRotation, MatrixRotation> {\n  inline void operator()(const Tin &m, Tout &res) const { res = m.transpose(); }\n};\n\nstruct InverserQuaternion\n    : public UnaryOpHeader<VectorQuaternion, VectorQuaternion> {\n  inline void operator()(const Tin &m, Tout &res) const { res = m.conjugate(); }\n};\n\n/* ----------------------------------------------------------------------- */\n/* --- SE3/SO3 conversions ----------------------------------------------- */\n/* ----------------------------------------------------------------------- */\n\nstruct MatrixHomoToPoseUTheta\n    : public UnaryOpHeader<MatrixHomogeneous, dg::Vector> {\n  inline void operator()(const MatrixHomogeneous &M, dg::Vector &res) {\n    res.resize(6);\n    VectorUTheta r(M.linear());\n    res.head<3>() = M.translation();\n    res.tail<3>() = r.angle() * r.axis();\n  }\n};\n\nstruct SkewSymToVector : public UnaryOpHeader<Matrix, Vector> {\n  inline void operator()(const Matrix &M, Vector &res) {\n    res.resize(3);\n    res(0) = M(7);\n    res(1) = M(2);\n    res(2) = M(3);\n  }\n};\n\nstruct PoseUThetaToMatrixHomo\n    : public UnaryOpHeader<Vector, MatrixHomogeneous> {\n  inline void operator()(const dg::Vector &v, MatrixHomogeneous &res) {\n    assert(v.size() >= 6);\n    res.translation() = v.head<3>();\n    double theta = v.tail<3>().norm();\n    if (theta > 0)\n      res.linear() = Eigen::AngleAxisd(theta, v.tail<3>() / theta).matrix();\n    else\n      res.linear().setIdentity();\n  }\n};\n\nstruct SE3VectorToMatrixHomo\n    : public UnaryOpHeader<dg::Vector, MatrixHomogeneous> {\n  void operator()(const dg::Vector &vect, MatrixHomogeneous &Mres) {\n    Mres.translation() = vect.head<3>();\n    Mres.linear().row(0) = vect.segment(3, 3);\n    Mres.linear().row(1) = vect.segment(6, 3);\n    Mres.linear().row(2) = vect.segment(9, 3);\n  }\n};\n\nstruct MatrixHomoToSE3Vector\n    : public UnaryOpHeader<MatrixHomogeneous, dg::Vector> {\n  void operator()(const MatrixHomogeneous &M, dg::Vector &res) {\n    res.resize(12);\n    res.head<3>() = M.translation();\n    res.segment(3, 3) = M.linear().row(0);\n    res.segment(6, 3) = M.linear().row(1);\n    res.segment(9, 3) = M.linear().row(2);\n  }\n};\n\nstruct PoseQuaternionToMatrixHomo\n    : public UnaryOpHeader<Vector, MatrixHomogeneous> {\n  void operator()(const dg::Vector &vect, MatrixHomogeneous &Mres) {\n    Mres.translation() = vect.head<3>();\n    Mres.linear() = VectorQuaternion(vect.tail<4>()).toRotationMatrix();\n  }\n};\n\nstruct MatrixHomoToPoseQuaternion\n    : public UnaryOpHeader<MatrixHomogeneous, Vector> {\n  inline void operator()(const MatrixHomogeneous &M, Vector &res) {\n    res.resize(7);\n    res.head<3>() = M.translation();\n    Eigen::Map<VectorQuaternion> q(res.tail<4>().data());\n    q = M.linear();\n  }\n};\n\nstruct MatrixHomoToPoseRollPitchYaw\n    : public UnaryOpHeader<MatrixHomogeneous, Vector> {\n  inline void operator()(const MatrixHomogeneous &M, dg::Vector &res) {\n    VectorRollPitchYaw r = (M.linear().eulerAngles(2, 1, 0)).reverse();\n    dg::Vector t(3);\n    t = M.translation();\n    res.resize(6);\n    for (unsigned int i = 0; i < 3; ++i)\n      res(i) = t(i);\n    for (unsigned int i = 0; i < 3; ++i)\n      res(i + 3) = r(i);\n  }\n};\n\nstruct PoseRollPitchYawToMatrixHomo\n    : public UnaryOpHeader<Vector, MatrixHomogeneous> {\n  inline void operator()(const dg::Vector &vect, MatrixHomogeneous &Mres) {\n\n    VectorRollPitchYaw r;\n    for (unsigned int i = 0; i < 3; ++i)\n      r(i) = vect(i + 3);\n    MatrixRotation R = (Eigen::AngleAxisd(r(2), Eigen::Vector3d::UnitZ()) *\n                        Eigen::AngleAxisd(r(1), Eigen::Vector3d::UnitY()) *\n                        Eigen::AngleAxisd(r(0), Eigen::Vector3d::UnitX()))\n                           .toRotationMatrix();\n\n    dg::Vector t(3);\n    for (unsigned int i = 0; i < 3; ++i)\n      t(i) = vect(i);\n\n    // buildFrom(R,t);\n    Mres = Eigen::Translation3d(t) * R;\n  }\n};\n\nstruct PoseRollPitchYawToPoseUTheta : public UnaryOpHeader<Vector, Vector> {\n  inline void operator()(const dg::Vector &vect, dg::Vector &vectres) {\n    VectorRollPitchYaw r;\n    for (unsigned int i = 0; i < 3; ++i)\n      r(i) = vect(i + 3);\n    MatrixRotation R = (Eigen::AngleAxisd(r(2), Eigen::Vector3d::UnitZ()) *\n                        Eigen::AngleAxisd(r(1), Eigen::Vector3d::UnitY()) *\n                        Eigen::AngleAxisd(r(0), Eigen::Vector3d::UnitX()))\n                           .toRotationMatrix();\n\n    VectorUTheta rrot(R);\n\n    vectres.resize(6);\n    for (unsigned int i = 0; i < 3; ++i) {\n      vectres(i) = vect(i);\n      vectres(i + 3) = rrot.angle() * rrot.axis()(i);\n    }\n  }\n};\n\nstruct HomoToMatrix : public UnaryOpHeader<MatrixHomogeneous, Matrix> {\n  inline void operator()(const MatrixHomogeneous &M, dg::Matrix &res) {\n    res = M.matrix();\n  }\n};\n\nstruct MatrixToHomo : public UnaryOpHeader<Matrix, MatrixHomogeneous> {\n  inline void operator()(const Eigen::Matrix<double, 4, 4> &M,\n                         MatrixHomogeneous &res) {\n    res = M;\n  }\n};\n\nstruct HomoToTwist : public UnaryOpHeader<MatrixHomogeneous, MatrixTwist> {\n  inline void operator()(const MatrixHomogeneous &M, MatrixTwist &res) {\n    Eigen::Vector3d _t = M.translation();\n    MatrixRotation R(M.linear());\n    Eigen::Matrix3d Tx;\n    Tx << 0, -_t(2), _t(1), _t(2), 0, -_t(0), -_t(1), _t(0), 0;\n\n    Eigen::Matrix3d sk;\n    sk = Tx * R;\n    res.block<3, 3>(0, 0) = R;\n    res.block<3, 3>(0, 3) = sk;\n    res.block<3, 3>(3, 0) = Eigen::Matrix3d::Zero();\n    res.block<3, 3>(3, 3) = R;\n  }\n};\n\nstruct HomoToRotation\n    : public UnaryOpHeader<MatrixHomogeneous, MatrixRotation> {\n  inline void operator()(const MatrixHomogeneous &M, MatrixRotation &res) {\n    res = M.linear();\n  }\n};\n\nstruct MatrixHomoToPose : public UnaryOpHeader<MatrixHomogeneous, Vector> {\n  inline void operator()(const MatrixHomogeneous &M, Vector &res) {\n    res.resize(3);\n    res = M.translation();\n  }\n};\n\nstruct RPYToMatrix : public UnaryOpHeader<VectorRollPitchYaw, MatrixRotation> {\n  inline void operator()(const VectorRollPitchYaw &r, MatrixRotation &res) {\n    res = (Eigen::AngleAxisd(r(2), Eigen::Vector3d::UnitZ()) *\n           Eigen::AngleAxisd(r(1), Eigen::Vector3d::UnitY()) *\n           Eigen::AngleAxisd(r(0), Eigen::Vector3d::UnitX()))\n              .toRotationMatrix();\n  }\n};\n\nstruct MatrixToRPY : public UnaryOpHeader<MatrixRotation, VectorRollPitchYaw> {\n  inline void operator()(const MatrixRotation &r, VectorRollPitchYaw &res) {\n    res = (r.eulerAngles(2, 1, 0)).reverse();\n  }\n};\n\nstruct RPYToQuaternion\n    : public UnaryOpHeader<VectorRollPitchYaw, VectorQuaternion> {\n  inline void operator()(const VectorRollPitchYaw &r, VectorQuaternion &res) {\n    res = (Eigen::AngleAxisd(r(2), Eigen::Vector3d::UnitZ()) *\n           Eigen::AngleAxisd(r(1), Eigen::Vector3d::UnitY()) *\n           Eigen::AngleAxisd(r(0), Eigen::Vector3d::UnitX()))\n              .toRotationMatrix();\n  }\n};\n\nstruct QuaternionToRPY\n    : public UnaryOpHeader<VectorQuaternion, VectorRollPitchYaw> {\n  inline void operator()(const VectorQuaternion &r, VectorRollPitchYaw &res) {\n    res = (r.toRotationMatrix().eulerAngles(2, 1, 0)).reverse();\n  }\n};\n\nstruct QuaternionToMatrix\n    : public UnaryOpHeader<VectorQuaternion, MatrixRotation> {\n  inline void operator()(const VectorQuaternion &r, MatrixRotation &res) {\n    res = r.toRotationMatrix();\n  }\n};\n\nstruct MatrixToQuaternion\n    : public UnaryOpHeader<MatrixRotation, VectorQuaternion> {\n  inline void operator()(const MatrixRotation &r, VectorQuaternion &res) {\n    res = r;\n  }\n};\n\nstruct MatrixToUTheta : public UnaryOpHeader<MatrixRotation, VectorUTheta> {\n  inline void operator()(const MatrixRotation &r, VectorUTheta &res) {\n    res = r;\n  }\n};\n\nstruct UThetaToQuaternion\n    : public UnaryOpHeader<VectorUTheta, VectorQuaternion> {\n  inline void operator()(const VectorUTheta &r, VectorQuaternion &res) {\n    res = r;\n  }\n};\n\ntemplate <typename TypeIn1, typename TypeIn2, typename TypeOut>\nstruct BinaryOpHeader {\n  typedef TypeIn1 Tin1;\n  typedef TypeIn2 Tin2;\n  typedef TypeOut Tout;\n  inline static std::string nameTypeIn1(void) {\n    return TypeNameHelper<Tin1>::typeName();\n  }\n  inline static std::string nameTypeIn2(void) {\n    return TypeNameHelper<Tin2>::typeName();\n  }\n  inline static std::string nameTypeOut(void) {\n    return TypeNameHelper<Tout>::typeName();\n  }\n  inline void addSpecificCommands(Entity &, Entity::CommandMap_t &) {}\n  inline std::string getDocString() const {\n    return std::string(\"Undocumented binary operator\\n\"\n                       \"  - input  \") +\n           nameTypeIn1() +\n           std::string(\"\\n\"\n                       \"  -        \") +\n           nameTypeIn2() +\n           std::string(\"\\n\"\n                       \"  - output \") +\n           nameTypeOut() + std::string(\"\\n\");\n  }\n};\n\n} /* namespace sot */\n} /* namespace dynamicgraph */\n\n/* ---------------------------------------------------------------------------*/\n/* ---------------------------------------------------------------------------*/\n/* ---------------------------------------------------------------------------*/\n\nnamespace dynamicgraph {\nnamespace sot {\n\n/* --- MULTIPLICATION --------------------------------------------------- */\n\ntemplate <typename F, typename E>\nstruct Multiplier_FxE__E : public BinaryOpHeader<F, E, E> {\n  inline void operator()(const F &f, const E &e, E &res) const { res = f * e; }\n};\n\ntemplate <>\ninline void\nMultiplier_FxE__E<dynamicgraph::sot::MatrixHomogeneous, dynamicgraph::Vector>::\noperator()(const dynamicgraph::sot::MatrixHomogeneous &f,\n           const dynamicgraph::Vector &e, dynamicgraph::Vector &res) const {\n  res = f.matrix() * e;\n}\n\ntemplate <>\ninline void Multiplier_FxE__E<double, dynamicgraph::Vector>::\noperator()(const double &x, const dynamicgraph::Vector &v,\n           dynamicgraph::Vector &res) const {\n  res = v;\n  res *= x;\n}\n\ntypedef Multiplier_FxE__E<double, dynamicgraph::Vector>\n    Multiplier_double_vector;\ntypedef Multiplier_FxE__E<dynamicgraph::Matrix, dynamicgraph::Vector>\n    Multiplier_matrix_vector;\ntypedef Multiplier_FxE__E<MatrixHomogeneous, dynamicgraph::Vector>\n    Multiplier_matrixHomo_vector;\ntypedef Multiplier_FxE__E<MatrixTwist, dynamicgraph::Vector>\n    Multiplier_matrixTwist_vector;\n\n/* --- SUBSTRACTION ----------------------------------------------------- */\ntemplate <typename T> struct Substraction : public BinaryOpHeader<T, T, T> {\n  inline void operator()(const T &v1, const T &v2, T &r) const {\n    r = v1;\n    r -= v2;\n  }\n};\n\n/* --- STACK ------------------------------------------------------------ */\nstruct VectorStack\n    : public BinaryOpHeader<dynamicgraph::Vector, dynamicgraph::Vector,\n                            dynamicgraph::Vector> {\npublic:\n  int v1min, v1max;\n  int v2min, v2max;\n  inline void operator()(const dynamicgraph::Vector &v1,\n                         const dynamicgraph::Vector &v2,\n                         dynamicgraph::Vector &res) const {\n    assert((v1max >= v1min) && (v1.size() >= v1max));\n    assert((v2max >= v2min) && (v2.size() >= v2max));\n\n    const int v1size = v1max - v1min, v2size = v2max - v2min;\n    res.resize(v1size + v2size);\n    for (int i = 0; i < v1size; ++i) {\n      res(i) = v1(i + v1min);\n    }\n    for (int i = 0; i < v2size; ++i) {\n      res(v1size + i) = v2(i + v2min);\n    }\n  }\n\n  inline void selec1(const int &m, const int M) {\n    v1min = m;\n    v1max = M;\n  }\n  inline void selec2(const int &m, const int M) {\n    v2min = m;\n    v2max = M;\n  }\n\n  inline void addSpecificCommands(Entity &ent,\n                                  Entity::CommandMap_t &commandMap) {\n    using namespace dynamicgraph::command;\n    std::string doc;\n\n    boost::function<void(const int &, const int &)> selec1 =\n        boost::bind(&VectorStack::selec1, this, _1, _2);\n    boost::function<void(const int &, const int &)> selec2 =\n        boost::bind(&VectorStack::selec2, this, _1, _2);\n\n    ADD_COMMAND(\n        \"selec1\",\n        makeCommandVoid2(ent, selec1,\n                         docCommandVoid2(\"set the min and max of selection.\",\n                                         \"int (imin)\", \"int (imax)\")));\n    ADD_COMMAND(\n        \"selec2\",\n        makeCommandVoid2(ent, selec2,\n                         docCommandVoid2(\"set the min and max of selection.\",\n                                         \"int (imin)\", \"int (imax)\")));\n  }\n};\n\n/* ---------------------------------------------------------------------- */\n\nstruct Composer\n    : public BinaryOpHeader<dynamicgraph::Matrix, dynamicgraph::Vector,\n                            MatrixHomogeneous> {\n  inline void operator()(const dynamicgraph::Matrix &R,\n                         const dynamicgraph::Vector &t,\n                         MatrixHomogeneous &H) const {\n    H.linear() = R;\n    H.translation() = t;\n  }\n};\n\n/* --- CONVOLUTION PRODUCT ---------------------------------------------- */\nstruct ConvolutionTemporal\n    : public BinaryOpHeader<dynamicgraph::Vector, dynamicgraph::Matrix,\n                            dynamicgraph::Vector> {\n  typedef std::deque<dynamicgraph::Vector> MemoryType;\n  MemoryType memory;\n\n  inline void convolution(const MemoryType &f1, const dynamicgraph::Matrix &f2,\n                          dynamicgraph::Vector &res) {\n    const Vector::Index nconv = (Vector::Index)f1.size(), nsig = f2.rows();\n    sotDEBUG(15) << \"Size: \" << nconv << \"x\" << nsig << std::endl;\n    if (nconv > f2.cols())\n      return; // TODO: error, this should not happen\n\n    res.resize(nsig);\n    res.fill(0);\n    unsigned int j = 0;\n    for (MemoryType::const_iterator iter = f1.begin(); iter != f1.end();\n         iter++) {\n      const dynamicgraph::Vector &s_tau = *iter;\n      sotDEBUG(45) << \"Sig\" << j << \": \" << s_tau;\n      if (s_tau.size() != nsig)\n        return; // TODO: error throw;\n      for (int i = 0; i < nsig; ++i) {\n        res(i) += f2(i, j) * s_tau(i);\n      }\n      j++;\n    }\n  }\n  inline void operator()(const dynamicgraph::Vector &v1,\n                         const dynamicgraph::Matrix &m2,\n                         dynamicgraph::Vector &res) {\n    memory.push_front(v1);\n    while ((Vector::Index)memory.size() > m2.cols())\n      memory.pop_back();\n    convolution(memory, m2, res);\n  }\n};\n\n/* --- BOOLEAN REDUCTION ------------------------------------------------ */\n\ntemplate <typename T> struct Comparison : public BinaryOpHeader<T, T, bool> {\n  inline void operator()(const T &a, const T &b, bool &res) const {\n    res = (a < b);\n  }\n  inline std::string getDocString() const {\n    typedef BinaryOpHeader<T, T, bool> Base;\n    return std::string(\"Comparison of inputs:\\n\"\n                       \"  - input  \") +\n           Base::nameTypeIn1() +\n           std::string(\"\\n\"\n                       \"  -        \") +\n           Base::nameTypeIn2() +\n           std::string(\"\\n\"\n                       \"  - output \") +\n           Base::nameTypeOut() +\n           std::string(\"\\n\"\n                       \"  sout = ( sin1 < sin2 )\\n\");\n  }\n};\n\ntemplate <typename T1, typename T2 = T1>\nstruct MatrixComparison : public BinaryOpHeader<T1, T2, bool> {\n  // TODO T1 or T2 could be a scalar type.\n  inline void operator()(const T1 &a, const T2 &b, bool &res) const {\n    if (equal && any)\n      res = (a.array() <= b.array()).any();\n    else if (equal && !any)\n      res = (a.array() <= b.array()).all();\n    else if (!equal && any)\n      res = (a.array() < b.array()).any();\n    else if (!equal && !any)\n      res = (a.array() < b.array()).all();\n  }\n  inline std::string getDocString() const {\n    typedef BinaryOpHeader<T1, T2, bool> Base;\n    return std::string(\"Comparison of inputs:\\n\"\n                       \"  - input  \") +\n           Base::nameTypeIn1() +\n           std::string(\"\\n\"\n                       \"  -        \") +\n           Base::nameTypeIn2() +\n           std::string(\"\\n\"\n                       \"  - output \") +\n           Base::nameTypeOut() +\n           std::string(\"\\n\"\n                       \"  sout = ( sin1 < sin2 ).op()\\n\") +\n           std::string(\"\\n\"\n                       \"  where op is either any (default) or all. The \"\n                       \"comparison can be made <=.\\n\");\n  }\n  MatrixComparison() : any(true), equal(false) {}\n  inline void addSpecificCommands(Entity &ent,\n                                  Entity::CommandMap_t &commandMap) {\n    using namespace dynamicgraph::command;\n    ADD_COMMAND(\n        \"setTrueIfAny\",\n        makeDirectSetter(ent, &any, docDirectSetter(\"trueIfAny\", \"bool\")));\n    ADD_COMMAND(\n        \"getTrueIfAny\",\n        makeDirectGetter(ent, &any, docDirectGetter(\"trueIfAny\", \"bool\")));\n    ADD_COMMAND(\"setEqual\", makeDirectSetter(ent, &equal,\n                                             docDirectSetter(\"equal\", \"bool\")));\n    ADD_COMMAND(\"getEqual\", makeDirectGetter(ent, &equal,\n                                             docDirectGetter(\"equal\", \"bool\")));\n  }\n  bool any, equal;\n};\n\n} /* namespace sot */\n} /* namespace dynamicgraph */\n\nnamespace dynamicgraph {\nnamespace sot {\n\ntemplate <typename T> struct WeightedAdder : public BinaryOpHeader<T, T, T> {\npublic:\n  double gain1, gain2;\n  inline void operator()(const T &v1, const T &v2, T &res) const {\n    res = v1;\n    res *= gain1;\n    res += gain2 * v2;\n  }\n\n  inline void addSpecificCommands(Entity &ent,\n                                  Entity::CommandMap_t &commandMap) {\n    using namespace dynamicgraph::command;\n    std::string doc;\n\n    ADD_COMMAND(\n        \"setGain1\",\n        makeDirectSetter(ent, &gain1, docDirectSetter(\"gain1\", \"double\")));\n    ADD_COMMAND(\n        \"setGain2\",\n        makeDirectSetter(ent, &gain2, docDirectSetter(\"gain2\", \"double\")));\n    ADD_COMMAND(\n        \"getGain1\",\n        makeDirectGetter(ent, &gain1, docDirectGetter(\"gain1\", \"double\")));\n    ADD_COMMAND(\n        \"getGain2\",\n        makeDirectGetter(ent, &gain2, docDirectGetter(\"gain2\", \"double\")));\n  }\n\n  inline std::string getDocString() const {\n    return std::string(\"Weighted Combination of inputs : \\n - gain{1|2} gain.\");\n  }\n};\n\n} // namespace sot\n} // namespace dynamicgraph\n\nnamespace dynamicgraph {\nnamespace sot {\ntemplate <typename Tin, typename Tout, typename Time>\nstd::string VariadicAbstract<Tin, Tout, Time>::getTypeInName(void) {\n  return TypeNameHelper<Tin>::typeName();\n}\ntemplate <typename Tin, typename Tout, typename Time>\nstd::string VariadicAbstract<Tin, Tout, Time>::getTypeOutName(void) {\n  return TypeNameHelper<Tout>::typeName();\n}\n\ntemplate <typename TypeIn, typename TypeOut> struct VariadicOpHeader {\n  typedef TypeIn Tin;\n  typedef TypeOut Tout;\n  inline static std::string nameTypeIn(void) {\n    return TypeNameHelper<Tin>::typeName();\n  }\n  inline static std::string nameTypeOut(void) {\n    return TypeNameHelper<Tout>::typeName();\n  }\n  template <typename Op>\n  inline void initialize(VariadicOp<Op> *, Entity::CommandMap_t &) {}\n  inline void updateSignalNumber(const int &) {}\n  inline std::string getDocString() const {\n    return std::string(\"Undocumented variadic operator\\n\"\n                       \"  - input  \" +\n                       nameTypeIn() +\n                       \"\\n\"\n                       \"  - output \" +\n                       nameTypeOut() + \"\\n\");\n  }\n};\n\n/* --- VectorMix ------------------------------------------------------------ */\nstruct VectorMix : public VariadicOpHeader<Vector, Vector> {\npublic:\n  typedef VariadicOp<VectorMix> Base;\n  struct segment_t {\n    Vector::Index index, size, input;\n    std::size_t sigIdx;\n    segment_t(Vector::Index i, Vector::Index s, std::size_t sig)\n        : index(i), size(s), sigIdx(sig) {}\n  };\n  typedef std::vector<segment_t> segments_t;\n  Base *entity;\n  segments_t idxs;\n  inline void operator()(const std::vector<const Vector *> &vs,\n                         Vector &res) const {\n    res = *vs[0];\n    for (std::size_t i = 0; i < idxs.size(); ++i) {\n      const segment_t &s = idxs[i];\n      if (s.sigIdx >= vs.size())\n        throw std::invalid_argument(\"Index out of range in VectorMix\");\n      res.segment(s.index, s.size) = *vs[s.sigIdx];\n    }\n  }\n\n  inline void addSelec(const int &sigIdx, const int &i, const int &s) {\n    idxs.push_back(segment_t(i, s, sigIdx));\n  }\n\n  inline void initialize(Base *ent, Entity::CommandMap_t &commandMap) {\n    using namespace dynamicgraph::command;\n    entity = ent;\n\n    ent->addSignal(\"default\");\n\n    boost::function<void(const int &, const int &, const int &)> selec =\n        boost::bind(&VectorMix::addSelec, this, _1, _2, _3);\n\n    commandMap.insert(std::make_pair(\n        \"addSelec\", makeCommandVoid3<Base, int, int, int>(\n                        *ent, selec,\n                        docCommandVoid3(\"add selection from a vector.\",\n                                        \"int (signal index >= 1)\",\n                                        \"int (index)\", \"int (size)\"))));\n  }\n};\n\n/* --- ADDITION --------------------------------------------------------- */\ntemplate <typename T> struct AdderVariadic : public VariadicOpHeader<T, T> {\n  typedef VariadicOp<AdderVariadic> Base;\n\n  Base *entity;\n  Vector coeffs;\n\n  AdderVariadic() : coeffs() {}\n  inline void operator()(const std::vector<const T *> &vs, T &res) const {\n    assert(vs.size() == (std::size_t)coeffs.size());\n    if (vs.size() == 0)\n      return;\n    res = coeffs[0] * (*vs[0]);\n    for (std::size_t i = 1; i < vs.size(); ++i)\n      res += coeffs[i] * (*vs[i]);\n  }\n\n  inline void setCoeffs(const Vector &c) {\n    if (entity->getSignalNumber() != c.size())\n      throw std::invalid_argument(\"Invalid coefficient size.\");\n    coeffs = c;\n  }\n  inline void updateSignalNumber(const int &n) { coeffs = Vector::Ones(n); }\n\n  inline void initialize(Base *ent, Entity::CommandMap_t &) {\n    entity = ent;\n    entity->setSignalNumber(2);\n  }\n\n  inline std::string getDocString() const {\n    return \"Linear combination of inputs\\n\"\n           \"  - input  \" +\n           VariadicOpHeader<T, T>::nameTypeIn() +\n           \"\\n\"\n           \"  - output \" +\n           VariadicOpHeader<T, T>::nameTypeOut() +\n           \"\\n\"\n           \"  sout = sum ([coeffs[i] * sin[i] for i in range(n) ])\\n\"\n           \"  Coefficients are set by commands, default value is 1.\\n\";\n  }\n};\n\n/* --- MULTIPLICATION --------------------------------------------------- */\ntemplate <typename T> struct Multiplier : public VariadicOpHeader<T, T> {\n  typedef VariadicOp<Multiplier> Base;\n\n  inline void operator()(const std::vector<const T *> &vs, T &res) const {\n    if (vs.size() == 0)\n      setIdentity(res);\n    else {\n      res = *vs[0];\n      for (std::size_t i = 1; i < vs.size(); ++i)\n        res *= *vs[i];\n    }\n  }\n\n  inline void setIdentity(T &res) const { res.setIdentity(); }\n\n  inline void initialize(Base *ent, Entity::CommandMap_t &) {\n    ent->setSignalNumber(2);\n  }\n};\ntemplate <> inline void Multiplier<double>::setIdentity(double &res) const {\n  res = 1;\n}\ntemplate <>\ninline void Multiplier<MatrixHomogeneous>::\noperator()(const std::vector<const MatrixHomogeneous *> &vs,\n           MatrixHomogeneous &res) const {\n  if (vs.size() == 0)\n    setIdentity(res);\n  else {\n    res = *vs[0];\n    for (std::size_t i = 1; i < vs.size(); ++i)\n      res = res * *vs[i];\n  }\n}\ntemplate <>\ninline void Multiplier<Vector>::\noperator()(const std::vector<const Vector *> &vs, Vector &res) const {\n  if (vs.size() == 0)\n    res.resize(0);\n  else {\n    res = *vs[0];\n    for (std::size_t i = 1; i < vs.size(); ++i)\n      res.array() *= vs[i]->array();\n  }\n}\n\n/* --- BOOLEAN --------------------------------------------------------- */\ntemplate <int operation> struct BoolOp : public VariadicOpHeader<bool, bool> {\n  typedef VariadicOp<BoolOp> Base;\n\n  inline void operator()(const std::vector<const bool *> &vs, bool &res) const {\n    // TODO computation could be optimized with lazy evaluation of the\n    // signals. When the output result is know, the remaining signals are\n    // not computed.\n    if (vs.size() == 0)\n      return;\n    res = *vs[0];\n    for (std::size_t i = 1; i < vs.size(); ++i)\n      switch (operation) {\n      case 0:\n        if (!res)\n          return;\n        res = *vs[i];\n        break;\n      case 1:\n        if (res)\n          return;\n        res = *vs[i];\n        break;\n      }\n  }\n};\n\n} // namespace sot\n} // namespace dynamicgraph\n\n/* --- TODO ------------------------------------------------------------------*/\n// The following commented lines are sot-v1 entities that are still waiting\n//   for conversion. Help yourself!\n\n// /* --------------------------------------------------------------------------\n// */\n\n// struct WeightedDirection\n// {\n// public:\n//   void operator()( const dynamicgraph::Vector& v1,const dynamicgraph::Vector&\n//   v2,dynamicgraph::Vector& res ) const\n//   {\n//     const double norm1 = v1.norm();\n//     const double norm2 = v2.norm();\n//     res=v2; res*=norm1;\n//     res*= (1/norm2);\n//   }\n// };\n// typedef BinaryOp< Vector,Vector,Vector,WeightedDirection > weightdir;\n// SOT_FACTORY_TEMPLATE_ENTITY_PLUGIN_ExE_E(weightdir,vector,weight_dir,\"WeightDir\")\n\n// /* --------------------------------------------------------------------------\n// */\n\n// struct Nullificator\n// {\n// public:\n//   void operator()( const dynamicgraph::Vector& v1,const dynamicgraph::Vector&\n//   v2,dynamicgraph::Vector& res ) const\n//   {\n//     const unsigned int s = std::max( v1.size(),v2.size() );\n//     res.resize(s);\n//     for( unsigned int i=0;i<s;++i )\n//       {\n// \tif( v1(i)>v2(i) ) res(i)=v1(i)-v2(i);\n// \telse \tif( v1(i)<-v2(i) ) res(i)=v1(i)+v2(i);\n// \telse res(i)=0;\n//       }\n//   }\n// };\n// typedef BinaryOp< Vector,Vector,Vector,Nullificator > vectNil;\n// SOT_FACTORY_TEMPLATE_ENTITY_PLUGIN_ExE_E(vectNil,vector,vectnil_,\"Nullificator\")\n\n// /* --------------------------------------------------------------------------\n// */\n\n// struct VirtualSpring\n// {\n// public:\n//   double spring;\n\n//   void operator()( const dynamicgraph::Vector& pos,const\n//   dynamicgraph::Vector& ref,dynamicgraph::Vector& res ) const\n//   {\n//     double norm = ref.norm();\n//     double dist = ref.scalarProduct(pos) / (norm*norm);\n\n//     res.resize( ref.size() );\n//     res = ref;  res *= dist; res -= pos;\n//     res *= spring;\n//   }\n// };\n// typedef BinaryOp< Vector,Vector,Vector,VirtualSpring > virtspring;\n// SOT_FACTORY_TEMPLATE_ENTITY_PLUGIN_ExE_E_CMD\n// (virtspring,vector,virtspring_,\n//  \"VirtualSpring\"\n//  ,else if( cmdLine==\"spring\" ){  CMDARGS_INOUT(op.spring); }\n//  ,\"VirtualSpring<pos,ref> compute the virtual force of a spring attache \"\n//  \"to the reference line <ref>. The eq is: k.(<ref|pos>/<ref|ref>.ref-pos)\"\n//  \"Params:\\n  - spring: get/set the spring factor.\")\n", "meta": {"hexsha": "1b62bff6d93014305e3fad5934d73bc81702d901", "size": 35910, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/matrix/operator.hh", "max_stars_repo_name": "machines-in-motion/sot-core", "max_stars_repo_head_hexsha": "9c0b1b3cd2bc03d36179cc8e47e11f7d42c1d4a5", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T07:15:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T13:41:06.000Z", "max_issues_repo_path": "src/matrix/operator.hh", "max_issues_repo_name": "machines-in-motion/sot-core", "max_issues_repo_head_hexsha": "9c0b1b3cd2bc03d36179cc8e47e11f7d42c1d4a5", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 121.0, "max_issues_repo_issues_event_min_datetime": "2015-02-17T08:38:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-01T10:54:05.000Z", "max_forks_repo_path": "src/matrix/operator.hh", "max_forks_repo_name": "machines-in-motion/sot-core", "max_forks_repo_head_hexsha": "9c0b1b3cd2bc03d36179cc8e47e11f7d42c1d4a5", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2015-07-01T16:25:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-08T15:06:58.000Z", "avg_line_length": 33.1885397412, "max_line_length": 84, "alphanum_fraction": 0.5636313005, "num_tokens": 9257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5926665999540697, "lm_q1q2_score": 0.40252653040150804}}
{"text": "/*\n * Copyright (c) 2015 Shihao Ji and Hyokun Yun. All Rights Reserved.\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *  http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\n * For more information, bug reports, fixes, contact:\n *   Shihao Ji  (shihaoji@yahoo.com)\n *   Hyokun Yun (yungilbert@gmail.com)\n */\n#ifndef __WORDRANK_MODEL_HPP\n#define __WORDRANK_MODEL_HPP\n\n#include <queue>\n#include <map>\n#include <unordered_set>\n#include <set>\n#include <sstream>\n#include <omp.h>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <mm_malloc.h>\n#include \"parameter.hpp\"\n#include \"data.hpp\"\n\n#ifdef USE_MKL\n#include \"mkl.h\"\n#endif\n\nusing namespace boost::posix_time;\nusing std::cout;\nusing std::flush;\nusing std::endl;\nusing std::pair;\nusing std::priority_queue;\nusing std::map;\nusing std::set;\nusing std::min;\nusing std::max;\nusing std::max_element;\n\nnamespace wordrank {\n\nstruct aux_info {\n    int col_index;\n    int row_index;\n    scalar xi;\n    scalar wi;\n};\n\nscalar logistic_loss(scalar x) {\n    return log2f(1.f + powf(2.f, x));\n}\n\nscalar hinge_loss(scalar x) {\n    return x > -1.f ? x + 1.f : 0.f;\n}\n\nscalar logistic_der(scalar x) {\n    return 1.f / (1.f + powf(2.f, -x));\n}\n\nscalar hinge_der(scalar x) {\n    return x > -1.f ? 1.f : 0.f;\n}\n\nclass Model {\n\nprivate:\n    Parameter& param_;\n    Data& data_;\n    rng_type rng_;\n\npublic:\n    Model(Parameter& param, Data& data) : param_(param), data_(data), rng_(param.random_seed_) {}\n\n    ~Model() {}\n\n    void run();\n\nprivate:\n    scalar calc_loss(scalar x) {\n        if (param_.loss_type_ == LossType::LOGISTIC) {\n            return logistic_loss(x);\n        } else if (param_.loss_type_ == LossType::HINGE) {\n            return hinge_loss(x);\n        } else {\n            //cerr << \"unsupported loss type\" << endl;\n            return 1000000.f;\n            //exit(1);\n        }\n    }\n\n    scalar calc_der(scalar x) {\n        if (param_.loss_type_ == LossType::LOGISTIC) {\n            return logistic_der(x);\n        } else if (param_.loss_type_ == LossType::HINGE) {\n            return hinge_der(x);\n        } else {\n            //cerr << \"unsupported loss type\" << endl;\n            return 1000000.f;\n            //exit(1);\n        }\n    }\n\n    void normalize(scalar* matrix, int m, int n) {\n        for (int i = 0; i < m; i++) {\n            int offset = i * n;\n            scalar norm2 = 0.f;\n            #pragma simd\n            for (int j = 0; j < n; j++) {\n                scalar v = matrix[offset + j];\n                norm2 += v * v;\n            }\n            scalar norm2r = 1.f / sqrtf(norm2);\n            if (norm2 > 1e-6f) {\n                #pragma simd\n                for (int j = 0; j < n; j++) matrix[offset + j] *= norm2r;\n            }\n        }\n    }\n\n};\n\n}\n\nvoid writelog(const char *str) {\n    cout << \"\\n\" << second_clock::local_time() << \" - \" << str << endl << flush;\n}\n\nvoid wordrank::Model::run() {\n\n    writelog(\"start run()\");\n\n    // define necessary constants\n    const int rank = param_.rank_;\n    const int dim = param_.latent_dim_;\n    const scalar alpha = param_.alpha_;\n    const scalar beta = param_.beta_;\n    const scalar tl = param_.t_;\n    const scalar tau = param_.tau_;\n    const int num_rows = data_.get_num_rows();\n    const int num_cols = data_.get_num_cols();\n\n    const int numtasks = param_.numtasks_;\n    const int numthreads = param_.numthreads_;\n    const int numparts = numthreads * numtasks;\n    const int numrows_per_part = data_.numrows_per_part_;\n    const int numcols_per_part = data_.numcols_per_part_;\n    const int num_rows_upbd = numthreads * numrows_per_part * numtasks;\n    const int num_cols_upbd = numthreads * numcols_per_part * numtasks;\n\n    const int sgd_num = param_.sgd_num_;\n    const TransformType trans_type = param_.trans_type_;\n\n    auto& train_row_nnzs = data_.train_row_nnzs_;\n    auto& train_col_nnzsum = data_.train_col_nnzsum_;\n    auto& train_row_nnzsum = data_.train_row_nnzsum_;\n\n    const size_t train_num_points = data_.train_total_nnz_;\n    const double train_total_nnzsum = data_.train_total_nnzsum_;\n\n    vector<vector<record_info>>& csc_indices = data_.csc_indices_;\n    vector<vector<index_type>>& csc_ptrs = data_.csc_ptrs_;\n    vector<index_type>& local_nnz = data_.local_nnz_;\n\n    // create thread-specific RNGs\n    rng_type rngs[numthreads];\n    for (int i = 0; i < numthreads; i++) {\n        rngs[i] = rng_type(param_.random_seed_ + 15791 * i + 373 * rank);\n    }\n    rng_type main_rng(param_.random_seed_ + 377 * rank);\n\n    /////////////////////////////////////////////////////////////////////\n    // Initialize Parameters\n    /////////////////////////////////////////////////////////////////////\n\n#ifdef USE_MKL\n    mkl_set_num_threads(1);\n#endif\n\n    // indexed by thread, local_row_index, coordinate\n\n    scalar *matrix_U = (scalar *) _mm_malloc(numthreads * numrows_per_part * dim * sizeof(scalar), 64);\n\n    scalar *matrix_V = (scalar *) _mm_malloc(numthreads * numcols_per_part * dim * sizeof(scalar), 64);\n\n    scalar *vector_Rec = (scalar *) _mm_malloc(numthreads * num_cols_upbd * sizeof(scalar), 64);\n\n    // maps local_col_index to global_col_index\n    int *col_indices = (int *) _mm_malloc(numthreads * numcols_per_part * sizeof(int), 64);\n\n    {\n        std::uniform_real_distribution<scalar> init_dist(0, 1.f);\n\n        #pragma omp parallel for num_threads(numthreads)\n        for (int thread_index = 0; thread_index < numthreads; thread_index++)\n        {\n            scalar *local_matrix_U = matrix_U + thread_index * numrows_per_part * dim;\n            for (int j = 0; j < numrows_per_part * dim; j++) {\n                local_matrix_U[j] = init_dist(rngs[thread_index]);\n            }\n            scalar *local_matrix_V = matrix_V + thread_index * numcols_per_part * dim;\n            for (int j = 0; j < numcols_per_part * dim; j++) {\n                local_matrix_V[j] = init_dist(rngs[thread_index]);\n            }\n            // normalize them\n            normalize(local_matrix_U, numrows_per_part, dim);\n            normalize(local_matrix_V, numcols_per_part, dim);\n\n            int *local_col_indices = col_indices + thread_index * numcols_per_part;\n            #pragma simd\n            for (int j = 0; j < numcols_per_part; j++) {\n                int col_index = (rank * numthreads + thread_index) * numcols_per_part + j;\n                if (col_index < num_cols) {\n                    local_col_indices[j] = col_index;\n                } else {\n                    local_col_indices[j] = -1;\n                }\n            }\n        }\n        // set the values of overflowed rows and cols to zeros\n        int numRowsOverflow = (rank + 1) * numthreads * numrows_per_part - num_rows;\n        if (numRowsOverflow > 0)\n            memset(matrix_U + numthreads * numrows_per_part - numRowsOverflow, 0, numRowsOverflow * sizeof(scalar));\n\n        int numColsOverflow = (rank + 1) * numthreads * numcols_per_part - num_cols;\n        if (numColsOverflow > 0)\n            memset(matrix_V + numthreads * numcols_per_part - numColsOverflow, 0, numColsOverflow * sizeof(scalar));\n\n    }\n\n    scalar *global_matrix_U = NULL;\n    if (rank == 0) {\n        global_matrix_U = (scalar *) _mm_malloc(num_rows_upbd * dim * sizeof(scalar), 64);\n    }\n\n    scalar *global_matrix_V = (scalar *) _mm_malloc(num_cols_upbd * dim * sizeof(scalar), 64);\n\n    int *global_col_indices = (int *) _mm_malloc(num_cols_upbd * sizeof(int), 64);\n\n    MPI_Allgather(matrix_V, numthreads * numcols_per_part * dim, MPI_SCALAR, global_matrix_V,\n            numthreads * numcols_per_part * dim, MPI_SCALAR, MPI_COMM_WORLD);\n    MPI_Allgather(col_indices, numthreads * numcols_per_part, MPI_INT, global_col_indices,\n            numthreads * numcols_per_part, MPI_INT, MPI_COMM_WORLD);\n\n    /////////////////////////////////////////////////////////////////////\n    // Optimization\n    /////////////////////////////////////////////////////////////////////\n\n    int *col_locations = (int *) _mm_malloc(num_cols * sizeof(int), 64);\n\n    // prepare auxiliary information variables\n    vector<vector<aux_info>> auxs(numthreads);\n    vector<vector<vector<aux_info *>>> rowwise_auxptrs(numthreads, vector<vector<aux_info *>>(numrows_per_part, vector<aux_info *>()));\n\n    #pragma omp parallel for num_threads(numthreads)\n    for (int thread_index = 0; thread_index < numthreads; thread_index++) {\n        auxs[thread_index].resize(local_nnz[thread_index]);\n\n        aux_info *ptr = &auxs[thread_index][0];\n        for (int col_index = 0; col_index < num_cols; col_index++) {\n            for (int j = csc_ptrs[thread_index][col_index]; j < csc_ptrs[thread_index][col_index + 1]; j++) {\n                record_info& ri = csc_indices[thread_index][j];\n                ptr->col_index = col_index;\n                ptr->row_index = ri.row_index;\n                ptr->xi = (trans_type == TransformType::RHO2) ? 0.5f : 1.0f;\n                ptr->wi = ri.weight;\n                rowwise_auxptrs[thread_index][ri.row_index].push_back(ptr);\n                ptr++;\n            }\n        }\n    }\n    // release memory\n    csc_indices.clear();\n\n    const double stepsize = param_.learning_rate_ * train_num_points / train_total_nnzsum;\n    const double reg = param_.regularization_ / ((num_cols - 1) * train_num_points);\n\n    writelog(\"starts optimization\");\n\n    int *global_perm = (int *) _mm_malloc(num_cols_upbd * sizeof(int), 64);\n    int *local_perm = (int *) _mm_malloc(numthreads * numcols_per_part * sizeof(int), 64);\n\n    double cumul_computation_time = 0.0;\n\n    /*************************************************************************/\n    /* Here is the main loop                                                 */\n    /*************************************************************************/\n    for (int iter_num = 0; iter_num < param_.max_iteration_; iter_num++) {\n\n        std::stringstream monitor_stream;\n        monitor_stream << iter_num << \", \" << param_;\n\n        cout << \"iteration: \" << iter_num << endl << flush;\n\n        if ((param_.dump_prefix_.length() > 0) && (iter_num % param_.dump_period_ == 0)) {\n\n            cout << \"dumping data\" << endl << flush;\n\n            if (rank == 0) {\n\n                MPI_Gather(matrix_U, numthreads * numrows_per_part * dim, MPI_SCALAR, global_matrix_U,\n                        numthreads * numrows_per_part * dim, MPI_SCALAR, 0, MPI_COMM_WORLD);\n\n                std::ofstream ofile(param_.dump_prefix_ + \"_word_\" + boost::lexical_cast<std::string>(iter_num) + \".txt\");\n\n                scalar *user_param = global_matrix_U;\n                for (int user_index = 0; user_index < num_rows; user_index++) {\n                    int global_row_index = data_.row_perm_inv_[user_index];\n                    if (data_.useVocab_){\n                        ofile << data_.vocab_[global_row_index];\n                    } else {\n                        ofile << global_row_index + 1;\n                    }\n\n                    for (int i = 0; i < dim; i++) {\n                        ofile << \" \";\n                        ofile << user_param[i];\n                    }\n                    ofile << endl;\n                    user_param += dim;\n                }\n                ofile.close();\n            } else {\n                MPI_Gather(matrix_U, numthreads * numrows_per_part * dim, MPI_SCALAR, global_matrix_U,\n                        numthreads * numrows_per_part * dim, MPI_SCALAR, 0, MPI_COMM_WORLD);\n            }\n\n            if (rank == 0) {\n                std::ofstream ofile(param_.dump_prefix_ + \"_context_\" + boost::lexical_cast<std::string>(iter_num) + \".txt\");\n                scalar *item_param = global_matrix_V;\n                for (int item_index = 0; item_index < num_cols_upbd; item_index++) {\n                    int global_col_index = global_col_indices[item_index];\n\n                    if (global_col_index > -1) {\n                        if (data_.useVocab_) {\n                            ofile << data_.vocab_[global_col_index];\n                        } else {\n                            ofile << global_col_index + 1;\n                        }\n\n                        for (int i = 0; i < dim; i++) {\n                            ofile << \" \";\n                            ofile << item_param[i];\n                        }\n                        ofile << endl;\n                    }\n                    item_param += dim;\n                }\n                ofile.close();\n            }\n        }\n\n\n        double compute_start_time = omp_get_wtime();\n\n        // sample a new assignment of column indices\n        if (rank == 0) {\n            std::iota(global_perm, global_perm + num_cols_upbd, 0);\n            std::shuffle(global_perm, global_perm + num_cols_upbd, main_rng);\n        }\n        MPI_Scatter(global_perm, numcols_per_part * numthreads, MPI_INT, local_perm, numcols_per_part * numthreads,\n                MPI_INT, 0, MPI_COMM_WORLD);\n\n        // copy global parameters to local space\n        {\n            #pragma omp parallel for num_threads(numthreads)\n            for (int i = 0; i < numcols_per_part * numthreads; i++) {\n                // copy the index\n                col_indices[i] = global_col_indices[local_perm[i]];\n\n                // copy the parameter value\n                scalar *source_ptr = global_matrix_V + local_perm[i] * dim;\n                scalar *target_ptr = matrix_V + i * dim;\n                std::copy(source_ptr, source_ptr + dim, target_ptr);\n            }\n        }\n\n        // inside a local machine, we use a permutation matrix\n        // to determine the order of block assignment\n        vector<vector<int> > perm_matrix(numthreads, vector<int>(numthreads, 0));\n        {\n            vector<int> col_perm(numthreads, 0);\n\n            #pragma omp parallel for num_threads(numthreads)\n            for (int i = 0; i < numthreads; i++) {\n                col_perm[i] = i;\n                #pragma simd\n                for (int j = 0; j < numthreads; j++) {\n                    perm_matrix[i][j] = (i + j) % numthreads;\n                }\n            }\n            shuffle(perm_matrix.begin(), perm_matrix.end(), main_rng);\n            shuffle(col_perm.begin(), col_perm.end(), main_rng);\n\n            // apply column permutation\n            #pragma omp parallel for num_threads(numthreads)\n            for (int i = 0; i < numthreads; i++) {\n                vector<int> tmp_buffer(numthreads, 0);\n                std::copy(perm_matrix[i].begin(), perm_matrix[i].end(), tmp_buffer.begin());\n                #pragma simd\n                for (int j = 0; j < numthreads; j++) {\n                    perm_matrix[i][col_perm[j]] = tmp_buffer[j];\n                }\n            }\n        }\n\n        // run SGD\n        for (int inner_iter = 0; inner_iter < numthreads; inner_iter++) {\n\n            #pragma omp parallel for num_threads(numthreads)\n            for (int thread_index = 0; thread_index < numthreads; thread_index++)\n            {\n                int chunk_index = perm_matrix[inner_iter][thread_index];\n\n                int *local_col_indices = col_indices + chunk_index * numcols_per_part;\n                scalar *local_matrix_U = matrix_U + thread_index * numrows_per_part * dim;\n                scalar *local_matrix_V = matrix_V + chunk_index * numcols_per_part * dim;\n\n                std::uniform_int_distribution<int> init_dist(0, numcols_per_part - 1);\n                auto sample_column = [&](int local_col_index)->int {\n                    int ret = local_col_index;\n                    while (true) {\n                        ret = init_dist(rngs[thread_index]);\n                        if ((ret != local_col_index) && (local_col_indices[ret] != -1)) {\n                            return ret;\n                        }\n                    }\n                };\n\n                scalar backup_row_vec[dim];\n\n                if (param_.loss_type_ == LossType::LOGISTIC) {\n\n                    for (int sgd_iter = 0; sgd_iter < sgd_num; sgd_iter++) {\n\n                        for (int i = 0; i < numcols_per_part; i++) {\n                            int col_index = local_col_indices[i];\n                            scalar *col_vec = local_matrix_V + i * dim;\n\n                            if (col_index < 0) {\n                                continue;\n                            }\n\n                            for (int j = csc_ptrs[thread_index][col_index]; j < csc_ptrs[thread_index][col_index + 1]; j++) {\n                                aux_info& aux_ptr = auxs[thread_index][j];\n                                int row_index = aux_ptr.row_index;\n                                scalar xi = aux_ptr.xi;\n                                scalar wi = aux_ptr.wi;\n                                scalar *row_vec = local_matrix_U + row_index * dim;\n\n                                int sam_local_index = sample_column(i);\n                                int sam_index = local_col_indices[sam_local_index];\n                                scalar *sam_vec = local_matrix_V + sam_local_index * dim;\n\n                                std::copy(row_vec, row_vec + dim, backup_row_vec);\n\n                                scalar org_dot = std::inner_product(row_vec, row_vec + dim, col_vec, 0.f);\n                                scalar sam_dot = std::inner_product(row_vec, row_vec + dim, sam_vec, 0.f);\n\n                                scalar coef = 0.f;\n\n                                switch (trans_type) {\n                                case TransformType::RHO1:\n                                    coef = wi * xi * INV_LOG2 / (tau + powf(2.f, org_dot - sam_dot));\n                                    break;\n                                case TransformType::RHO2: {\n                                    scalar logxi = logf(xi);\n                                    scalar logxi2 = logxi * logxi;\n                                    coef = wi * xi * LOG2 / (logxi2 * (tau + powf(2.f, org_dot - sam_dot)));\n                                    break;\n                                }\n                                case TransformType::RHO3:\n                                    coef = wi * powf(xi, tl) / (tau + powf(2.f, org_dot - sam_dot));\n                                    break;\n                                default:\n                                    cerr << \"unsupported transform type\" << endl;\n                                    exit(1);\n                                }\n\n                                #pragma simd\n                                for (int t = 0; t < dim; t++) {\n                                    row_vec[t] -= stepsize * (reg * train_row_nnzsum[thread_index][row_index] * row_vec[t]\n                                                     + coef * (sam_vec[t] - col_vec[t]));\n                                    col_vec[t] -= stepsize * (reg * train_col_nnzsum[col_index] * col_vec[t]\n                                                     - coef * backup_row_vec[t]);\n                                    sam_vec[t] -= stepsize * (reg * (train_total_nnzsum - train_col_nnzsum[sam_index]) * sam_vec[t]\n                                                     + coef * backup_row_vec[t]);\n                                }\n                            }\n                        }\n                    } // end of sam_iter\n                } // case of logistic loss (end)\n                else if (param_.loss_type_ == LossType::HINGE) {\n\n                    for (int sgd_iter = 0; sgd_iter < sgd_num; sgd_iter++) {\n\n                        for (int i = 0; i < numcols_per_part; i++) {\n                            int col_index = local_col_indices[i];\n                            scalar *col_vec = local_matrix_V + i * dim;\n\n                            if (col_index < 0) {\n                                continue;\n                            }\n\n                            for (int j = csc_ptrs[thread_index][col_index]; j < csc_ptrs[thread_index][col_index + 1]; j++) {\n                                aux_info& aux_ptr = auxs[thread_index][j];\n                                int row_index = aux_ptr.row_index;\n                                scalar xi = aux_ptr.xi;\n                                scalar wi = aux_ptr.wi;\n                                scalar *row_vec = local_matrix_U + row_index * dim;\n\n                                int sam_local_index = sample_column(i);\n                                int sam_index = local_col_indices[sam_local_index];\n                                scalar *sam_vec = local_matrix_V + sam_local_index * dim;\n\n                                std::copy(row_vec, row_vec + dim, backup_row_vec);\n\n                                scalar org_dot = std::inner_product(row_vec, row_vec + dim, col_vec, 0.f);\n                                scalar sam_dot = std::inner_product(row_vec, row_vec + dim, sam_vec, 0.f);\n\n                                // if hinge loss is nonzero\n                                if (sam_dot > org_dot - tau) {\n\n                                    scalar coef = 0.f;\n\n                                    switch (trans_type) {\n                                    case TransformType::RHO1:\n                                        coef = wi * xi * INV_LOG2;\n                                        break;\n                                    case TransformType::RHO2: {\n                                        scalar logxi = logf(xi);\n                                        scalar logxi2 = logxi * logxi;\n                                        coef = wi * xi * LOG2 / logxi2;\n                                        break;\n                                    }\n                                    case TransformType::RHO3:\n                                        coef = wi * powf(xi, tl);\n                                        break;\n                                    default:\n                                        cerr << \"unsupported transform type\" << endl;\n                                        exit(1);\n                                    }\n\n                                    #pragma simd\n                                    for (int t = 0; t < dim; t++) {\n                                        row_vec[t] -= stepsize * (reg * train_row_nnzsum[thread_index][row_index] * row_vec[t]\n                                                        + coef * (sam_vec[t] - col_vec[t]));\n                                        col_vec[t] -= stepsize * (reg * train_col_nnzsum[col_index] * col_vec[t]\n                                                        - coef * backup_row_vec[t]);\n                                        sam_vec[t] -= stepsize * (reg * (train_total_nnzsum - train_col_nnzsum[sam_index]) * sam_vec[t]\n                                                        + coef * backup_row_vec[t]);\n                                    }\n                                }\n                            }\n                        }\n                    }\n                } else {\n                    cerr << \"unsupported loss type 1\" << endl << flush;\n                    exit(1);\n                }\n            }\n        }\n\n        // at the end of the iteration, synchronize parameters\n        MPI_Allgather(matrix_V, numthreads * numcols_per_part * dim, MPI_SCALAR, global_matrix_V,\n                numthreads * numcols_per_part * dim, MPI_SCALAR, MPI_COMM_WORLD);\n        MPI_Allgather(col_indices, numthreads * numcols_per_part, MPI_INT, global_col_indices,\n                numthreads * numcols_per_part, MPI_INT, MPI_COMM_WORLD);\n\n        #pragma omp parallel for num_threads(numthreads)\n        #pragma simd\n        for (int i = 0; i < num_cols_upbd; i++) {\n            if (global_col_indices[i] >= 0) {\n                col_locations[global_col_indices[i]] = i;\n            }\n        }\n\n        // update auxiliary parameters exactly\n        if (iter_num > 0 && iter_num % param_.xi_period_ == 0) {\n\n            writelog(\"update auxiliary parameters\");\n\n            vector<scalar> max_xi(numthreads, -1000000.f);\n            vector<scalar> min_xi(numthreads, 1000000.f);\n            vector<scalar> mean_xi(numthreads, 0.f);\n\n\n//            cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, numthreads * numrows_per_part, num_cols_upbd,\n//                    dim, 1.0f, matrix_U, dim, global_matrix_V, dim, 0.0f, matrix_Rec, num_cols_upbd);\n\n            #pragma omp parallel for num_threads(numthreads)\n            for (int thread_index = 0; thread_index < numthreads; thread_index++)\n            {\n                scalar* vector_Rec_ptr = vector_Rec + thread_index * num_cols_upbd;\n                scalar* matrix_U_ptr = matrix_U + thread_index * numrows_per_part * dim;\n\n                for (int row_index = 0; row_index < numrows_per_part; row_index++) {\n#ifndef USE_MKL\n                    scalar* row_ptr = matrix_U_ptr + row_index * dim;\n                    for (int i = 0; i < num_cols_upbd; i++) {\n                        scalar* col_ptr = global_matrix_V + i * dim;\n                        scalar sum = 0.f;\n                        #pragma simd\n                        for (int j = 0; j < dim; j++) {\n                            sum += row_ptr[j] * col_ptr[j];\n                        }\n                        vector_Rec_ptr[i] = sum;\n                    }\n#else\n                    cblas_sgemv(CblasRowMajor, CblasNoTrans, num_cols_upbd, dim, 1.0f, global_matrix_V, dim,\n                            matrix_U_ptr + row_index * dim, 1, 0.0f, vector_Rec_ptr, 1);\n#endif\n                    vector<aux_info *>& auxptrs = rowwise_auxptrs[thread_index][row_index];\n                    int numnnzs = auxptrs.size();\n\n                    for (int i = 0; i < numnnzs; i++) {\n                        aux_info* ptr = auxptrs[i];\n                        int col_index = ptr->col_index;\n                        scalar wi = ptr->wi;\n                        scalar val = vector_Rec_ptr[col_locations[col_index]];\n                        double sum = 0;\n                        #pragma simd\n                        for (int j = 0; j < num_cols_upbd; j++) {\n                            scalar diff = vector_Rec_ptr[j] - val;\n                            sum += diff > -tau ? (tau + diff) : 0.;\n                        }\n                        ptr->xi = (trans_type == TransformType::RHO2) ? (0.5 * beta + 1) / (sqrt(sum) + 1 + beta) :\n                                alpha / (sum + beta);\n                    }\n\n                    #pragma simd\n                    for (int i = 0; i < numnnzs; i++) {\n                        aux_info* ptr = auxptrs[i];\n                        mean_xi[thread_index] += ptr->xi;\n                        if (max_xi[thread_index] < ptr->xi)\n                            max_xi[thread_index] = ptr->xi;\n                        if (min_xi[thread_index] > ptr->xi)\n                            min_xi[thread_index] = ptr->xi;\n                    }\n\n                }\n            }\n\n            scalar machine_max_xi = *max_element(max_xi.begin(), max_xi.end());\n            scalar machine_min_xi = *min_element(min_xi.begin(), min_xi.end());\n            scalar machine_mean_xi = std::accumulate(mean_xi.begin(), mean_xi.end(), 0.f) * numtasks / train_num_points;\n\n            scalar global_max_xi = -1000000.f;\n            scalar global_min_xi = 1000000.f;\n            scalar global_mean_xi = 0.f;\n\n            MPI_Allreduce(&machine_max_xi, &global_max_xi, 1, MPI_SCALAR, MPI_MAX, MPI_COMM_WORLD);\n            MPI_Allreduce(&machine_min_xi, &global_min_xi, 1, MPI_SCALAR, MPI_MIN, MPI_COMM_WORLD);\n            MPI_Allreduce(&machine_mean_xi, &global_mean_xi, 1, MPI_SCALAR, MPI_SUM, MPI_COMM_WORLD);\n\n            global_mean_xi /= numtasks;\n\n            cout << \"machine min xi: \" << machine_min_xi << \", machine max xi: \" << machine_max_xi\n                    << \", machine mean xi: \" << machine_mean_xi << \", global mean xi: \" << global_mean_xi << endl << flush;\n        }\n\n        double computation_time = omp_get_wtime() - compute_start_time;\n        cumul_computation_time += computation_time;\n        monitor_stream << \", \" << cumul_computation_time;\n\n        // calculate the objective function\n        if (param_.cost_eval_)\n        {\n            writelog(\"calculate cost function\");\n\n            vector<double> local_loss_sums(numthreads, 0);\n            vector<double> local_approx_loss_sums(numthreads, 0);\n            vector<double> local_reg_sums(numthreads, 0);\n\n            #pragma omp parallel for num_threads(numthreads)\n            for (int thread_index = 0; thread_index < numthreads; thread_index++)\n            {\n                scalar* matrix_U_ptr = matrix_U + thread_index * numrows_per_part * dim;\n                scalar* vector_Rec_ptr = vector_Rec + thread_index * num_cols_upbd;\n\n                for (int n = 0; n < local_nnz[thread_index]; n++) {\n                    aux_info& aux = auxs[thread_index][n];\n                    int row_index = aux.row_index;\n                    int col_index = aux.col_index;\n                    scalar xi = aux.xi;\n                    scalar wi = aux.wi;\n\n#ifndef USE_MKL\n                    scalar* row_ptr = matrix_U_ptr + row_index * dim;\n                    for (int i = 0; i < num_cols_upbd; i++) {\n                        scalar* col_ptr = global_matrix_V + i * dim;\n                        scalar sum = 0.f;\n                        #pragma simd\n                        for (int j = 0; j < dim; j++) {\n                            sum += row_ptr[j] * col_ptr[j];\n                        }\n                        vector_Rec_ptr[i] = sum;\n                    }\n#else\n                    cblas_sgemv(CblasRowMajor, CblasNoTrans, num_cols_upbd, dim, 1.f, global_matrix_V, dim,\n                            matrix_U_ptr + row_index * dim, 1, 0.f, vector_Rec_ptr, 1);\n#endif\n\n                    scalar val = vector_Rec_ptr[col_locations[col_index]];\n                    scalar sum = 0.f;\n                    #pragma simd\n                    for (int j = 0; j < num_cols_upbd; j++) {\n                        scalar diff = vector_Rec_ptr[j] - val;\n                        sum += diff > -tau ? (tau + diff) : 0.f;\n                    }\n                    if (trans_type == TransformType::RHO1) {\n                        local_loss_sums[thread_index] += wi * log2(sum);\n                        local_approx_loss_sums[thread_index] += wi * ((xi * (sum + beta) - 1) * INV_LOG2 - alpha * log2(xi));\n                    } else {\n                        scalar logxi = logf(xi);\n                        scalar logxi2 = logxi * logxi;\n                        local_loss_sums[thread_index] += wi * (1 - 1 / log2(sum + 1));\n                        local_approx_loss_sums[thread_index] += wi * (1 + LOG2 * (logxi - 1 + xi * (sum + 1)) / logxi2\n                                + (beta * xi - 0.5 * beta * logxi) * INV_LOG2);\n                    }\n                }\n\n                // calculate the regularizer term\n                if (param_.regularization_ > 0) {\n                    #pragma simd\n                    for (int row_index = 0; row_index < numrows_per_part; row_index++) {\n                        scalar *row_vec = matrix_U_ptr + row_index * dim;\n                        local_reg_sums[thread_index] += train_row_nnzsum[thread_index][row_index]\n                                * std::inner_product(row_vec, row_vec + dim, row_vec, 0.f);\n                    }\n                    int *local_col_indices = col_indices + thread_index * numcols_per_part;\n                    scalar *local_matrix_V = matrix_V + thread_index * numcols_per_part * dim;\n                    #pragma simd\n                    for (int col_index = 0; col_index < numcols_per_part; col_index++) {\n                        scalar *col_vec = local_matrix_V + col_index * dim;\n                        local_reg_sums[thread_index] += train_col_nnzsum[local_col_indices[col_index]]\n                                * std::inner_product(col_vec, col_vec + dim, col_vec, 0.f);\n                    }\n                }\n            }\n\n            double global_loss_sum = 0.0;\n            double machine_loss_sum = std::accumulate(local_loss_sums.begin(), local_loss_sums.end(), 0.0);\n            MPI_Allreduce(&machine_loss_sum, &global_loss_sum, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n\n            double global_approx_loss_sum = 0.0;\n            double machine_approx_loss_sum = std::accumulate(local_approx_loss_sums.begin(), local_approx_loss_sums.end(), 0.0);\n            MPI_Allreduce(&machine_approx_loss_sum, &global_approx_loss_sum, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n\n            double global_reg_sum = 0.0;\n            if (param_.regularization_ > 0) {\n                double machine_reg_sum = std::accumulate(local_reg_sums.begin(), local_reg_sums.end(), 0.0);\n                MPI_Allreduce(&machine_reg_sum, &global_reg_sum, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n            }\n\n            double cost = global_approx_loss_sum + param_.regularization_ * global_reg_sum;\n\n            monitor_stream << \", cost: \" << cost << \" (\" << global_approx_loss_sum << \" + \" << param_.regularization_ * global_reg_sum\n                    << \"), true loss: \" << global_loss_sum;\n        }\n\n        if (rank == 0) {\n            cout << \"monitor, \" << monitor_stream.str() << endl << flush;\n        }\n\n    } // end of SGD iteration\n\n    /////////////////////////////////////////////////////////////////////\n    // Deallocate Memory\n    /////////////////////////////////////////////////////////////////////\n\n    _mm_free(vector_Rec);\n    _mm_free(matrix_U);\n    _mm_free(matrix_V);\n    if (rank == 0) _mm_free(global_matrix_U);\n    _mm_free(global_matrix_V);\n    _mm_free(global_col_indices);\n    _mm_free(local_perm);\n    _mm_free(global_perm);\n    _mm_free(col_indices);\n    _mm_free(col_locations);\n}\n\n#endif\n", "meta": {"hexsha": "f1b92076e7e67643582e9e4c7b19a244ee5b6e8d", "size": 34322, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "model.hpp", "max_stars_repo_name": "prakhar-agarwal/wordrank", "max_stars_repo_head_hexsha": "de04b8aa1680da4a33b10544553261825e269b64", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 57.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T13:20:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-30T21:17:41.000Z", "max_issues_repo_path": "model.hpp", "max_issues_repo_name": "prakhar-agarwal/wordrank", "max_issues_repo_head_hexsha": "de04b8aa1680da4a33b10544553261825e269b64", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-06-02T06:05:37.000Z", "max_issues_repo_issues_event_max_datetime": "2018-01-05T12:35:19.000Z", "max_forks_repo_path": "model.hpp", "max_forks_repo_name": "prakhar-agarwal/wordrank", "max_forks_repo_head_hexsha": "de04b8aa1680da4a33b10544553261825e269b64", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-03-26T23:36:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T16:09:02.000Z", "avg_line_length": 42.9025, "max_line_length": 135, "alphanum_fraction": 0.5022143232, "num_tokens": 7615, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.40252623803140436}}
{"text": "#include <iostream>\n#include <cstdlib>\n#include <cstdio>\n#include <armadillo>\n#include <random>\n\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char **argv) {\n  if(argc <= 2) {\n    fprintf(stderr, \"Usage: %s OUT-FILE NUM-AGENTS\\n\", argv[0]);\n    return 0;\n  }\n\n  const char *filename = argv[1];\n  int N = atoi(argv[2]);\n  size_t K = 10000000;\n  double m0 = 1.0;\n\n  // pseudorandom number generator\n  default_random_engine G;\n\n  // seed PRNG with true random number\n  random_device source;\n  unsigned int seed = source();\n  G.seed(seed);\n\n  // uniform distributions\n  uniform_int_distribution<> idist(0, N-1);  // discrete distribution on [0,N)\n  uniform_real_distribution<> rdist(0, 1);   // real distribution on [0,1)\n\n  // list of agents' money\n  vector<double> m(N, m0);\n\n  // sum of m^2\n  double m2sq = N * m0 * m0;\n\n  // lists of measured variance at different steps\n  std::vector<int> step;\n  std::vector<double> variance;\n\n  // do switches\n  size_t powerOfTen = 1;\n  for(size_t k = 0; k < K; k++) {\n    // pick two random, different agents\n    int i = idist(G), j = idist(G);\n    while(i == j) j = idist(G);\n\n    // calculate total money of the two agents\n    double mtot = m[i] + m[j];\n\n    // redistribute money between the two agents\n    double e = rdist(G);\n    m2sq += (e * e + (1 - e) * (1 - e)) * mtot * mtot - m[i] * m[i] - m[j] * m[j];\n    m[i] = e * mtot;\n    m[j] = (1 - e) * mtot;\n\n    if(k >= 100 * powerOfTen)\n      powerOfTen *= 10;\n    if(k % powerOfTen == 0) {\n      // calculate variance\n      double V = m2sq / N - m0 * m0;\n\n      step.push_back(k);\n      variance.push_back(V);\n    }\n  }\n\n  // save to file\n  FILE *fp = fopen(filename, \"w\");\n  fprintf(fp, \"k\\tV\\n\");\n  for(size_t i = 0; i < step.size() && i < variance.size(); i++) {\n    fprintf(fp, \"%d\\t%.3E\\n\", step[i], variance[i]);\n  }\n  fclose(fp);\n}\n", "meta": {"hexsha": "adbdda2653709e6ea9698840b0d5f7b9c7281fea", "size": 1850, "ext": "cc", "lang": "C++", "max_stars_repo_path": "project5/code/5a-equilibrium.cc", "max_stars_repo_name": "frxstrem/fys3150", "max_stars_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project5/code/5a-equilibrium.cc", "max_issues_repo_name": "frxstrem/fys3150", "max_issues_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project5/code/5a-equilibrium.cc", "max_forks_repo_name": "frxstrem/fys3150", "max_forks_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7179487179, "max_line_length": 82, "alphanum_fraction": 0.5875675676, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228891883799, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4022261610291568}}
{"text": "//  Copyright (c) 2007, 2013 John Maddock\n//  Copyright Christopher Kormanyos 2013.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// This header just defines the function entry points, and adds dispatch\n// to the right implementation method.  Most of the implementation details\n// are in separate headers and copyright Xiaogang Zhang.\n//\n#ifndef BOOST_MATH_BESSEL_HPP\n#define BOOST_MATH_BESSEL_HPP\n\n#ifdef _MSC_VER\n#  pragma once\n#endif\n\n#include <boost/math/special_functions/detail/bessel_jy.hpp>\n#include <boost/math/special_functions/detail/bessel_jn.hpp>\n#include <boost/math/special_functions/detail/bessel_yn.hpp>\n#include <boost/math/special_functions/detail/bessel_jy_zero.hpp>\n#include <boost/math/special_functions/detail/bessel_ik.hpp>\n#include <boost/math/special_functions/detail/bessel_i0.hpp>\n#include <boost/math/special_functions/detail/bessel_i1.hpp>\n#include <boost/math/special_functions/detail/bessel_kn.hpp>\n#include <boost/math/special_functions/detail/iconv.hpp>\n#include <boost/math/special_functions/sin_pi.hpp>\n#include <boost/math/special_functions/cos_pi.hpp>\n#include <boost/math/special_functions/sinc.hpp>\n#include <boost/math/special_functions/trunc.hpp>\n#include <boost/math/special_functions/round.hpp>\n#include <boost/math/tools/rational.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <boost/math/tools/series.hpp>\n#include <boost/math/tools/roots.hpp>\n\nnamespace boost{ namespace math{\n\nnamespace detail{\n\ntemplate <class T, class Policy>\nstruct sph_bessel_j_small_z_series_term\n{\n   typedef T result_type;\n\n   sph_bessel_j_small_z_series_term(unsigned v_, T x)\n      : N(0), v(v_)\n   {\n      BOOST_MATH_STD_USING\n      mult = x / 2;\n      term = pow(mult, T(v)) / boost::math::tgamma(v+1+T(0.5f), Policy());\n      mult *= -mult;\n   }\n   T operator()()\n   {\n      T r = term;\n      ++N;\n      term *= mult / (N * T(N + v + 0.5f));\n      return r;\n   }\nprivate:\n   unsigned N;\n   unsigned v;\n   T mult;\n   T term;\n};\n\ntemplate <class T, class Policy>\ninline T sph_bessel_j_small_z_series(unsigned v, T x, const Policy& pol)\n{\n   BOOST_MATH_STD_USING // ADL of std names\n   sph_bessel_j_small_z_series_term<T, Policy> s(v, x);\n   boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\n#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))\n   T zero = 0;\n   T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, zero);\n#else\n   T result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter);\n#endif\n   policies::check_series_iterations<T>(\"boost::math::sph_bessel_j_small_z_series<%1%>(%1%,%1%)\", max_iter, pol);\n   return result * sqrt(constants::pi<T>() / 4);\n}\n\ntemplate <class T, class Policy>\nT cyl_bessel_j_imp(T v, T x, const bessel_no_int_tag& t, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n   static const char* function = \"boost::math::bessel_j<%1%>(%1%,%1%)\";\n   if(x < 0)\n   {\n      // better have integer v:\n      if(floor(v) == v)\n      {\n         T r = cyl_bessel_j_imp(v, T(-x), t, pol);\n         if(iround(v, pol) & 1)\n            r = -r;\n         return r;\n      }\n      else\n         return policies::raise_domain_error<T>(\n            function,\n            \"Got x = %1%, but we need x >= 0\", x, pol);\n   }\n   \n   T j, y;\n   bessel_jy(v, x, &j, &y, need_j, pol);\n   return j;\n}\n\ntemplate <class T, class Policy>\ninline T cyl_bessel_j_imp(T v, T x, const bessel_maybe_int_tag&, const Policy& pol)\n{\n   BOOST_MATH_STD_USING  // ADL of std names.\n   int ival = detail::iconv(v, pol);\n   // If v is an integer, use the integer recursion\n   // method, both that and Steeds method are O(v):\n   if((0 == v - ival))\n   {\n      return bessel_jn(ival, x, pol);\n   }\n   return cyl_bessel_j_imp(v, x, bessel_no_int_tag(), pol);\n}\n\ntemplate <class T, class Policy>\ninline T cyl_bessel_j_imp(int v, T x, const bessel_int_tag&, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n   return bessel_jn(v, x, pol);\n}\n\ntemplate <class T, class Policy>\ninline T sph_bessel_j_imp(unsigned n, T x, const Policy& pol)\n{\n   BOOST_MATH_STD_USING // ADL of std names\n   if(x < 0)\n      return policies::raise_domain_error<T>(\n         \"boost::math::sph_bessel_j<%1%>(%1%,%1%)\",\n         \"Got x = %1%, but function requires x > 0.\", x, pol);\n   //\n   // Special case, n == 0 resolves down to the sinus cardinal of x:\n   //\n   if(n == 0)\n      return boost::math::sinc_pi(x, pol);\n   //\n   // When x is small we may end up with 0/0, use series evaluation\n   // instead, especially as it converges rapidly:\n   //\n   if(x < 1)\n      return sph_bessel_j_small_z_series(n, x, pol);\n   //\n   // Default case is just a naive evaluation of the definition:\n   //\n   return sqrt(constants::pi<T>() / (2 * x)) \n      * cyl_bessel_j_imp(T(T(n)+T(0.5f)), x, bessel_no_int_tag(), pol);\n}\n\ntemplate <class T, class Policy>\nT cyl_bessel_i_imp(T v, T x, const Policy& pol)\n{\n   //\n   // This handles all the bessel I functions, note that we don't optimise\n   // for integer v, other than the v = 0 or 1 special cases, as Millers\n   // algorithm is at least as inefficient as the general case (the general\n   // case has better error handling too).\n   //\n   BOOST_MATH_STD_USING\n   if(x < 0)\n   {\n      // better have integer v:\n      if(floor(v) == v)\n      {\n         T r = cyl_bessel_i_imp(v, T(-x), pol);\n         if(iround(v, pol) & 1)\n            r = -r;\n         return r;\n      }\n      else\n         return policies::raise_domain_error<T>(\n         \"boost::math::cyl_bessel_i<%1%>(%1%,%1%)\",\n            \"Got x = %1%, but we need x >= 0\", x, pol);\n   }\n   if(x == 0)\n   {\n      return (v == 0) ? 1 : 0;\n   }\n   if(v == 0.5f)\n   {\n      // common special case, note try and avoid overflow in exp(x):\n      if(x >= tools::log_max_value<T>())\n      {\n         T e = exp(x / 2);\n         return e * (e / sqrt(2 * x * constants::pi<T>()));\n      }\n      return sqrt(2 / (x * constants::pi<T>())) * sinh(x);\n   }\n   if(policies::digits<T, Policy>() <= 64)\n   {\n      if(v == 0)\n      {\n         return bessel_i0(x);\n      }\n      if(v == 1)\n      {\n         return bessel_i1(x);\n      }\n   }\n   if((v > 0) && (x / v < 0.25))\n      return bessel_i_small_z_series(v, x, pol);\n   T I, K;\n   bessel_ik(v, x, &I, &K, need_i, pol);\n   return I;\n}\n\ntemplate <class T, class Policy>\ninline T cyl_bessel_k_imp(T v, T x, const bessel_no_int_tag& /* t */, const Policy& pol)\n{\n   static const char* function = \"boost::math::cyl_bessel_k<%1%>(%1%,%1%)\";\n   BOOST_MATH_STD_USING\n   if(x < 0)\n   {\n      return policies::raise_domain_error<T>(\n         function,\n         \"Got x = %1%, but we need x > 0\", x, pol);\n   }\n   if(x == 0)\n   {\n      return (v == 0) ? policies::raise_overflow_error<T>(function, 0, pol)\n         : policies::raise_domain_error<T>(\n         function,\n         \"Got x = %1%, but we need x > 0\", x, pol);\n   }\n   T I, K;\n   bessel_ik(v, x, &I, &K, need_k, pol);\n   return K;\n}\n\ntemplate <class T, class Policy>\ninline T cyl_bessel_k_imp(T v, T x, const bessel_maybe_int_tag&, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n   if((floor(v) == v))\n   {\n      return bessel_kn(itrunc(v), x, pol);\n   }\n   return cyl_bessel_k_imp(v, x, bessel_no_int_tag(), pol);\n}\n\ntemplate <class T, class Policy>\ninline T cyl_bessel_k_imp(int v, T x, const bessel_int_tag&, const Policy& pol)\n{\n   return bessel_kn(v, x, pol);\n}\n\ntemplate <class T, class Policy>\ninline T cyl_neumann_imp(T v, T x, const bessel_no_int_tag&, const Policy& pol)\n{\n   static const char* function = \"boost::math::cyl_neumann<%1%>(%1%,%1%)\";\n\n   BOOST_MATH_INSTRUMENT_VARIABLE(v);\n   BOOST_MATH_INSTRUMENT_VARIABLE(x);\n\n   if(x <= 0)\n   {\n      return (v == 0) && (x == 0) ?\n         policies::raise_overflow_error<T>(function, 0, pol)\n         : policies::raise_domain_error<T>(\n               function,\n               \"Got x = %1%, but result is complex for x <= 0\", x, pol);\n   }\n   T j, y;\n   bessel_jy(v, x, &j, &y, need_y, pol);\n   // \n   // Post evaluation check for internal overflow during evaluation,\n   // can occur when x is small and v is large, in which case the result\n   // is -INF:\n   //\n   if(!(boost::math::isfinite)(y))\n      return -policies::raise_overflow_error<T>(function, 0, pol);\n   return y;\n}\n\ntemplate <class T, class Policy>\ninline T cyl_neumann_imp(T v, T x, const bessel_maybe_int_tag&, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n\n   BOOST_MATH_INSTRUMENT_VARIABLE(v);\n   BOOST_MATH_INSTRUMENT_VARIABLE(x);\n\n   if(floor(v) == v)\n   {\n      if(asymptotic_bessel_large_x_limit(v, x))\n      {\n         T r = asymptotic_bessel_y_large_x_2(static_cast<T>(abs(v)), x);\n         if((v < 0) && (itrunc(v, pol) & 1))\n            r = -r;\n         BOOST_MATH_INSTRUMENT_VARIABLE(r);\n         return r;\n      }\n      else\n      {\n         T r = bessel_yn(itrunc(v, pol), x, pol);\n         BOOST_MATH_INSTRUMENT_VARIABLE(r);\n         return r;\n      }\n   }\n   T r = cyl_neumann_imp<T>(v, x, bessel_no_int_tag(), pol);\n   BOOST_MATH_INSTRUMENT_VARIABLE(r);\n   return r;\n}\n\ntemplate <class T, class Policy>\ninline T cyl_neumann_imp(int v, T x, const bessel_int_tag&, const Policy& pol)\n{\n   BOOST_MATH_STD_USING\n\n   BOOST_MATH_INSTRUMENT_VARIABLE(v);\n   BOOST_MATH_INSTRUMENT_VARIABLE(x);\n\n   if(asymptotic_bessel_large_x_limit(T(v), x))\n   {\n      T r = asymptotic_bessel_y_large_x_2(static_cast<T>(abs(v)), x);\n      if((v < 0) && (v & 1))\n         r = -r;\n      return r;\n   }\n   else\n      return bessel_yn(v, x, pol);\n}\n\ntemplate <class T, class Policy>\ninline T sph_neumann_imp(unsigned v, T x, const Policy& pol)\n{\n   BOOST_MATH_STD_USING // ADL of std names\n   static const char* function = \"boost::math::sph_neumann<%1%>(%1%,%1%)\";\n   //\n   // Nothing much to do here but check for errors, and\n   // evaluate the function's definition directly:\n   //\n   if(x < 0)\n      return policies::raise_domain_error<T>(\n         function,\n         \"Got x = %1%, but function requires x > 0.\", x, pol);\n\n   if(x < 2 * tools::min_value<T>())\n      return -policies::raise_overflow_error<T>(function, 0, pol);\n\n   T result = cyl_neumann_imp(T(T(v)+0.5f), x, bessel_no_int_tag(), pol);\n   T tx = sqrt(constants::pi<T>() / (2 * x));\n\n   if((tx > 1) && (tools::max_value<T>() / tx < result))\n      return -policies::raise_overflow_error<T>(function, 0, pol);\n\n   return result * tx;\n}\n\ntemplate <class T, class Policy>\ninline T cyl_bessel_j_zero_imp(T v, int m, const Policy& pol)\n{\n   BOOST_MATH_STD_USING // ADL of std names, needed for floor.\n\n   static const char* function = \"boost::math::cyl_bessel_j_zero<%1%>(%1%, int)\";\n\n   const T half_epsilon(boost::math::tools::epsilon<T>() / 2U);\n\n   // Handle non-finite order.\n   if (!(boost::math::isfinite)(v) )\n   {\n     return policies::raise_domain_error<T>(function, \"Order argument is %1%, but must be finite >= 0 !\", v, pol);\n   }\n\n   // Handle negative rank.\n   if(m < 0)\n   {\n      // Zeros of Jv(x) with negative rank are not defined and requesting one raises a domain error.\n      return policies::raise_domain_error<T>(function, \"Requested the %1%'th zero, but the rank must be positive !\", m, pol);\n   }\n\n   // Get the absolute value of the order.\n   const bool order_is_negative = (v < 0);\n   const T vv((!order_is_negative) ? v : T(-v));\n\n   // Check if the order is very close to zero or very close to an integer.\n   const bool order_is_zero    = (vv < half_epsilon);\n   const bool order_is_integer = ((vv - floor(vv)) < half_epsilon);\n\n   if(m == 0)\n   {\n      if(order_is_zero)\n      {\n         // The zero'th zero of J0(x) is not defined and requesting it raises a domain error.\n         return policies::raise_domain_error<T>(function, \"Requested the %1%'th zero of J0, but the rank must be > 0 !\", m, pol);\n      }\n\n      // The zero'th zero of Jv(x) for v < 0 is not defined\n      // unless the order is a negative integer.\n      if(order_is_negative && (!order_is_integer))\n      {\n         // For non-integer, negative order, requesting the zero'th zero raises a domain error.\n         return policies::raise_domain_error<T>(function, \"Requested the %1%'th zero of Jv for negative, non-integer order, but the rank must be > 0 !\", m, pol);\n      }\n\n      // The zero'th zero does exist and its value is zero.\n      return T(0);\n   }\n\n   // Set up the initial guess for the upcoming root-finding.\n   // If the order is a negative integer, then use the corresponding\n   // positive integer for the order.\n   const T guess_root = boost::math::detail::bessel_zero::cyl_bessel_j_zero_detail::initial_guess<T, Policy>((order_is_integer ? vv : v), m, pol);\n\n   // Select the maximum allowed iterations from the policy.\n   boost::uintmax_t number_of_iterations = policies::get_max_root_iterations<Policy>();\n\n   // Select the desired number of binary digits of precision.\n   // Account for the radix of number representations having non-two radix!\n   const int my_digits2 = policies::digits<T, Policy>();\n\n   const T delta_lo = ((guess_root > 0.2F) ? T(0.2) : T(guess_root / 2U));\n\n   // Perform the root-finding using Newton-Raphson iteration from Boost.Math.\n   const T jvm =\n      boost::math::tools::newton_raphson_iterate(\n         boost::math::detail::bessel_zero::cyl_bessel_j_zero_detail::function_object_jv_and_jv_prime<T, Policy>((order_is_integer ? vv : v), order_is_zero, pol),\n         guess_root,\n         T(guess_root - delta_lo),\n         T(guess_root + 0.2F),\n         my_digits2,\n         number_of_iterations);\n\n   if(number_of_iterations >= policies::get_max_root_iterations<Policy>())\n   {\n      policies::raise_evaluation_error<T>(function, \"Unable to locate root in a reasonable time:\"\n         \"  Current best guess is %1%\", jvm, Policy());\n   }\n\n   return jvm;\n}\n\ntemplate <class T, class Policy>\ninline T cyl_neumann_zero_imp(T v, int m, const Policy& pol)\n{\n   BOOST_MATH_STD_USING // ADL of std names, needed for floor.\n\n   static const char* function = \"boost::math::cyl_neumann_zero<%1%>(%1%, int)\";\n\n   // Handle non-finite order.\n   if (!(boost::math::isfinite)(v) )\n   {\n     return policies::raise_domain_error<T>(function, \"Order argument is %1%, but must be finite >= 0 !\", v, pol);\n   }\n\n   // Handle negative rank.\n   if(m < 0)\n   {\n      return policies::raise_domain_error<T>(function, \"Requested the %1%'th zero, but the rank must be positive !\", m, pol);\n   }\n\n   const T half_epsilon(boost::math::tools::epsilon<T>() / 2U);\n\n   // Get the absolute value of the order.\n   const bool order_is_negative = (v < 0);\n   const T vv((!order_is_negative) ? v : T(-v));\n\n   const bool order_is_integer = ((vv - floor(vv)) < half_epsilon);\n\n   // For negative integers, use reflection to positive integer order.\n   if(order_is_negative && order_is_integer)\n      return boost::math::detail::cyl_neumann_zero_imp(vv, m, pol);\n\n   // Check if the order is very close to a negative half-integer.\n   const T delta_half_integer(vv - (floor(vv) + 0.5F));\n\n   const bool order_is_negative_half_integer =\n      (order_is_negative && ((delta_half_integer > -half_epsilon) && (delta_half_integer < +half_epsilon)));\n\n   // The zero'th zero of Yv(x) for v < 0 is not defined\n   // unless the order is a negative integer.\n   if((m == 0) && (!order_is_negative_half_integer))\n   {\n      // For non-integer, negative order, requesting the zero'th zero raises a domain error.\n      return policies::raise_domain_error<T>(function, \"Requested the %1%'th zero of Yv for negative, non-half-integer order, but the rank must be > 0 !\", m, pol);\n   }\n\n   // For negative half-integers, use the corresponding\n   // spherical Bessel function of positive half-integer order.\n   if(order_is_negative_half_integer)\n      return boost::math::detail::cyl_bessel_j_zero_imp(vv, m, pol);\n\n   // Set up the initial guess for the upcoming root-finding.\n   // If the order is a negative integer, then use the corresponding\n   // positive integer for the order.\n   const T guess_root = boost::math::detail::bessel_zero::cyl_neumann_zero_detail::initial_guess<T, Policy>(v, m, pol);\n\n   // Select the maximum allowed iterations from the policy.\n   boost::uintmax_t number_of_iterations = policies::get_max_root_iterations<Policy>();\n\n   // Select the desired number of binary digits of precision.\n   // Account for the radix of number representations having non-two radix!\n   const int my_digits2 = policies::digits<T, Policy>();\n\n   const T delta_lo = ((guess_root > 0.2F) ? T(0.2) : T(guess_root / 2U));\n\n   // Perform the root-finding using Newton-Raphson iteration from Boost.Math.\n   const T yvm =\n      boost::math::tools::newton_raphson_iterate(\n         boost::math::detail::bessel_zero::cyl_neumann_zero_detail::function_object_yv_and_yv_prime<T, Policy>(v, pol),\n         guess_root,\n         T(guess_root - delta_lo),\n         T(guess_root + 0.2F),\n         my_digits2,\n         number_of_iterations);\n\n   if(number_of_iterations >= policies::get_max_root_iterations<Policy>())\n   {\n      policies::raise_evaluation_error<T>(function, \"Unable to locate root in a reasonable time:\"\n         \"  Current best guess is %1%\", yvm, Policy());\n   }\n\n   return yvm;\n}\n\n} // namespace detail\n\ntemplate <class T1, class T2, class Policy>\ninline typename detail::bessel_traits<T1, T2, Policy>::result_type cyl_bessel_j(T1 v, T2 x, const Policy& /* pol */)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename detail::bessel_traits<T1, T2, Policy>::result_type result_type;\n   typedef typename detail::bessel_traits<T1, T2, Policy>::optimisation_tag tag_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::cyl_bessel_j_imp<value_type>(v, static_cast<value_type>(x), tag_type(), forwarding_policy()), \"boost::math::cyl_bessel_j<%1%>(%1%,%1%)\");\n}\n\ntemplate <class T1, class T2>\ninline typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type cyl_bessel_j(T1 v, T2 x)\n{\n   return cyl_bessel_j(v, x, policies::policy<>());\n}\n\ntemplate <class T, class Policy>\ninline typename detail::bessel_traits<T, T, Policy>::result_type sph_bessel(unsigned v, T x, const Policy& /* pol */)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename detail::bessel_traits<T, T, Policy>::result_type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::sph_bessel_j_imp<value_type>(v, static_cast<value_type>(x), forwarding_policy()), \"boost::math::sph_bessel<%1%>(%1%,%1%)\");\n}\n\ntemplate <class T>\ninline typename detail::bessel_traits<T, T, policies::policy<> >::result_type sph_bessel(unsigned v, T x)\n{\n   return sph_bessel(v, x, policies::policy<>());\n}\n\ntemplate <class T1, class T2, class Policy>\ninline typename detail::bessel_traits<T1, T2, Policy>::result_type cyl_bessel_i(T1 v, T2 x, const Policy& /* pol */)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename detail::bessel_traits<T1, T2, Policy>::result_type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::cyl_bessel_i_imp<value_type>(v, static_cast<value_type>(x), forwarding_policy()), \"boost::math::cyl_bessel_i<%1%>(%1%,%1%)\");\n}\n\ntemplate <class T1, class T2>\ninline typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type cyl_bessel_i(T1 v, T2 x)\n{\n   return cyl_bessel_i(v, x, policies::policy<>());\n}\n\ntemplate <class T1, class T2, class Policy>\ninline typename detail::bessel_traits<T1, T2, Policy>::result_type cyl_bessel_k(T1 v, T2 x, const Policy& /* pol */)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename detail::bessel_traits<T1, T2, Policy>::result_type result_type;\n   typedef typename detail::bessel_traits<T1, T2, Policy>::optimisation_tag tag_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::cyl_bessel_k_imp<value_type>(v, static_cast<value_type>(x), tag_type(), forwarding_policy()), \"boost::math::cyl_bessel_k<%1%>(%1%,%1%)\");\n}\n\ntemplate <class T1, class T2>\ninline typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type cyl_bessel_k(T1 v, T2 x)\n{\n   return cyl_bessel_k(v, x, policies::policy<>());\n}\n\ntemplate <class T1, class T2, class Policy>\ninline typename detail::bessel_traits<T1, T2, Policy>::result_type cyl_neumann(T1 v, T2 x, const Policy& /* pol */)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename detail::bessel_traits<T1, T2, Policy>::result_type result_type;\n   typedef typename detail::bessel_traits<T1, T2, Policy>::optimisation_tag tag_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::cyl_neumann_imp<value_type>(v, static_cast<value_type>(x), tag_type(), forwarding_policy()), \"boost::math::cyl_neumann<%1%>(%1%,%1%)\");\n}\n\ntemplate <class T1, class T2>\ninline typename detail::bessel_traits<T1, T2, policies::policy<> >::result_type cyl_neumann(T1 v, T2 x)\n{\n   return cyl_neumann(v, x, policies::policy<>());\n}\n\ntemplate <class T, class Policy>\ninline typename detail::bessel_traits<T, T, Policy>::result_type sph_neumann(unsigned v, T x, const Policy& /* pol */)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename detail::bessel_traits<T, T, Policy>::result_type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::sph_neumann_imp<value_type>(v, static_cast<value_type>(x), forwarding_policy()), \"boost::math::sph_neumann<%1%>(%1%,%1%)\");\n}\n\ntemplate <class T>\ninline typename detail::bessel_traits<T, T, policies::policy<> >::result_type sph_neumann(unsigned v, T x)\n{\n   return sph_neumann(v, x, policies::policy<>());\n}\n\ntemplate <class T, class Policy>\ninline typename detail::bessel_traits<T, T, Policy>::result_type cyl_bessel_j_zero(T v, int m, const Policy& /* pol */)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename detail::bessel_traits<T, T, Policy>::result_type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n   BOOST_STATIC_ASSERT_MSG(false == std::numeric_limits<value_type>::is_integer, \"Order must be a floating-point type.\");\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::cyl_bessel_j_zero_imp<value_type>(v, m, forwarding_policy()), \"boost::math::cyl_bessel_j_zero<%1%>(%1%,%1%)\");\n}\n\ntemplate <class T>\ninline typename detail::bessel_traits<T, T, policies::policy<> >::result_type cyl_bessel_j_zero(T v, int m)\n{\n   BOOST_STATIC_ASSERT_MSG(false == std::numeric_limits<T>::is_integer, \"Order must be a floating-point type.\");\n   return cyl_bessel_j_zero<T, policies::policy<> >(v, m, policies::policy<>());\n}\n\ntemplate <class T, class OutputIterator, class Policy>\ninline OutputIterator cyl_bessel_j_zero(T v,\n                              int start_index,\n                              unsigned number_of_zeros,\n                              OutputIterator out_it,\n                              const Policy& pol)\n{\n   BOOST_STATIC_ASSERT_MSG(false == std::numeric_limits<T>::is_integer, \"Order must be a floating-point type.\");\n   for(unsigned i = 0; i < number_of_zeros; ++i)\n   {\n      *out_it = boost::math::cyl_bessel_j_zero(v, start_index + i, pol);\n      ++out_it;\n   }\n   return out_it;\n}\n\ntemplate <class T, class OutputIterator>\ninline OutputIterator cyl_bessel_j_zero(T v,\n                              int start_index,\n                              unsigned number_of_zeros,\n                              OutputIterator out_it)\n{\n   return cyl_bessel_j_zero(v, start_index, number_of_zeros, out_it, policies::policy<>());\n}\n\ntemplate <class T, class Policy>\ninline typename detail::bessel_traits<T, T, Policy>::result_type cyl_neumann_zero(T v, int m, const Policy& /* pol */)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename detail::bessel_traits<T, T, Policy>::result_type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::discrete_quantile<>,\n      policies::assert_undefined<> >::type forwarding_policy;\n   BOOST_STATIC_ASSERT_MSG(false == std::numeric_limits<value_type>::is_integer, \"Order must be a floating-point type.\");\n   return policies::checked_narrowing_cast<result_type, Policy>(detail::cyl_neumann_zero_imp<value_type>(v, m, forwarding_policy()), \"boost::math::cyl_neumann_zero<%1%>(%1%,%1%)\");\n}\n\ntemplate <class T>\ninline typename detail::bessel_traits<T, T, policies::policy<> >::result_type cyl_neumann_zero(T v, int m)\n{\n   BOOST_STATIC_ASSERT_MSG(false == std::numeric_limits<T>::is_integer, \"Order must be a floating-point type.\");\n   return cyl_neumann_zero<T, policies::policy<> >(v, m, policies::policy<>());\n}\n\ntemplate <class T, class OutputIterator, class Policy>\ninline OutputIterator cyl_neumann_zero(T v,\n                             int start_index,\n                             unsigned number_of_zeros,\n                             OutputIterator out_it,\n                             const Policy& pol)\n{\n   BOOST_STATIC_ASSERT_MSG(false == std::numeric_limits<T>::is_integer, \"Order must be a floating-point type.\");\n   for(unsigned i = 0; i < number_of_zeros; ++i)\n   {\n      *out_it = boost::math::cyl_neumann_zero(v, start_index + i, pol);\n      ++out_it;\n   }\n   return out_it;\n}\n\ntemplate <class T, class OutputIterator>\ninline OutputIterator cyl_neumann_zero(T v,\n                             int start_index,\n                             unsigned number_of_zeros,\n                             OutputIterator out_it)\n{\n   return cyl_neumann_zero(v, start_index, number_of_zeros, out_it, policies::policy<>());\n}\n\n} // namespace math\n} // namespace boost\n\n#endif // BOOST_MATH_BESSEL_HPP\n\n", "meta": {"hexsha": "b1e03bfbed9e8b820f579f0bc037197ac1b57c26", "size": 27698, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/math/special_functions/bessel.hpp", "max_stars_repo_name": "HelloSunyi/boost_1_54_0", "max_stars_repo_head_hexsha": "429fea793612f973d4b7a0e69c5af8156ae2b56e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-12-05T19:34:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T09:07:09.000Z", "max_issues_repo_path": "boost/math/special_functions/bessel.hpp", "max_issues_repo_name": "graehl/boost", "max_issues_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2015-07-22T07:35:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T16:03:06.000Z", "max_forks_repo_path": "boost/math/special_functions/bessel.hpp", "max_forks_repo_name": "graehl/boost", "max_forks_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T00:09:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T10:47:11.000Z", "avg_line_length": 36.6860927152, "max_line_length": 209, "alphanum_fraction": 0.6690374756, "num_tokens": 7522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.40222615292391106}}
{"text": "// -*- c++ -*-\n//=======================================================================\n// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.\n// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <boost/config.hpp>\n#include <iostream>\n\n#include <boost/graph/adjacency_list.hpp>\n\n/*\n  Thanks to Dale Gerdemann for this example, which inspired some\n  changes to adjacency_list to make this work properly.\n */\n\n/*\n  Sample output:\n\n  0  --c--> 1   --j--> 1   --c--> 2   --x--> 2\n  1  --c--> 2   --d--> 3\n  2  --t--> 4\n  3  --h--> 4\n  4\n\n  merging vertex 1 into vertex 0\n\n  0  --c--> 0   --j--> 0   --c--> 1   --x--> 1   --d--> 2\n  1  --t--> 3\n  2  --h--> 3\n  3\n */\n\n// merge_vertex(u,v,g):\n// incoming/outgoing edges for v become incoming/outgoing edges for u\n// v is deleted\ntemplate < class Graph, class GetEdgeProperties >\nvoid merge_vertex(typename boost::graph_traits< Graph >::vertex_descriptor u,\n    typename boost::graph_traits< Graph >::vertex_descriptor v, Graph& g,\n    GetEdgeProperties getp)\n{\n    typedef boost::graph_traits< Graph > Traits;\n    typename Traits::edge_descriptor e;\n    typename Traits::out_edge_iterator out_i, out_end;\n    for (boost::tie(out_i, out_end) = out_edges(v, g); out_i != out_end;\n         ++out_i)\n    {\n        e = *out_i;\n        typename Traits::vertex_descriptor targ = target(e, g);\n        add_edge(u, targ, getp(e), g);\n    }\n    typename Traits::in_edge_iterator in_i, in_end;\n    for (boost::tie(in_i, in_end) = in_edges(v, g); in_i != in_end; ++in_i)\n    {\n        e = *in_i;\n        typename Traits::vertex_descriptor src = source(e, g);\n        add_edge(src, u, getp(e), g);\n    }\n    clear_vertex(v, g);\n    remove_vertex(v, g);\n}\n\ntemplate < class StoredEdge > struct order_by_name\n{\n    typedef StoredEdge first_argument_type;\n    typedef StoredEdge second_argument_type;\n    typedef bool result_type;\n    bool operator()(const StoredEdge& e1, const StoredEdge& e2) const\n    {\n        // Using std::pair operator< as an easy way to get lexicographical\n        // compare over tuples.\n        return std::make_pair(e1.get_target(), boost::get(boost::edge_name, e1))\n            < std::make_pair(e2.get_target(), boost::get(boost::edge_name, e2));\n    }\n};\nstruct ordered_set_by_nameS\n{\n};\n\n#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\nnamespace boost\n{\ntemplate < class ValueType >\nstruct container_gen< ordered_set_by_nameS, ValueType >\n{\n    typedef std::set< ValueType, order_by_name< ValueType > > type;\n};\ntemplate <> struct parallel_edge_traits< ordered_set_by_nameS >\n{\n    typedef allow_parallel_edge_tag type;\n};\n}\n#endif\n\ntemplate < class Graph > struct get_edge_name\n{\n    get_edge_name(const Graph& g_) : g(g_) {}\n\n    template < class Edge >\n    boost::property< boost::edge_name_t, char > operator()(Edge e) const\n    {\n        return boost::property< boost::edge_name_t, char >(\n            boost::get(boost::edge_name, g, e));\n    }\n    const Graph& g;\n};\n\nint main()\n{\n#ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION\n    std::cout << \"This program requires partial specialization.\" << std::endl;\n#else\n    using namespace boost;\n    typedef property< edge_name_t, char > EdgeProperty;\n    typedef adjacency_list< ordered_set_by_nameS, vecS, bidirectionalS,\n        no_property, EdgeProperty >\n        graph_type;\n\n    graph_type g;\n\n    add_edge(0, 1, EdgeProperty('j'), g);\n    add_edge(0, 2, EdgeProperty('c'), g);\n    add_edge(0, 2, EdgeProperty('x'), g);\n    add_edge(1, 3, EdgeProperty('d'), g);\n    add_edge(1, 2, EdgeProperty('c'), g);\n    add_edge(1, 3, EdgeProperty('d'), g);\n    add_edge(2, 4, EdgeProperty('t'), g);\n    add_edge(3, 4, EdgeProperty('h'), g);\n    add_edge(0, 1, EdgeProperty('c'), g);\n\n    property_map< graph_type, vertex_index_t >::type id = get(vertex_index, g);\n    property_map< graph_type, edge_name_t >::type name = get(edge_name, g);\n\n    graph_traits< graph_type >::vertex_iterator i, end;\n    graph_traits< graph_type >::out_edge_iterator ei, edge_end;\n\n    for (boost::tie(i, end) = vertices(g); i != end; ++i)\n    {\n        std::cout << id[*i] << \" \";\n        for (boost::tie(ei, edge_end) = out_edges(*i, g); ei != edge_end; ++ei)\n            std::cout << \" --\" << name[*ei] << \"--> \" << id[target(*ei, g)]\n                      << \"  \";\n        std::cout << std::endl;\n    }\n    std::cout << std::endl;\n\n    std::cout << \"merging vertex 1 into vertex 0\" << std::endl << std::endl;\n    merge_vertex(0, 1, g, get_edge_name< graph_type >(g));\n\n    for (boost::tie(i, end) = vertices(g); i != end; ++i)\n    {\n        std::cout << id[*i] << \" \";\n        for (boost::tie(ei, edge_end) = out_edges(*i, g); ei != edge_end; ++ei)\n            std::cout << \" --\" << name[*ei] << \"--> \" << id[target(*ei, g)]\n                      << \"  \";\n        std::cout << std::endl;\n    }\n    std::cout << std::endl;\n#endif\n    return 0;\n}\n", "meta": {"hexsha": "09804f7c59fb63c2b3c2c1ec3933b76b1b943da0", "size": 5091, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/gerdemann.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/gerdemann.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/gerdemann.cpp", "max_forks_repo_name": "qingkouwei/mediaones", "max_forks_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 30.8545454545, "max_line_length": 80, "alphanum_fraction": 0.5967393439, "num_tokens": 1433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.4022261448186651}}
{"text": "/**\n * @file cosine_tree.hpp\n * @author Siddharth Agrawal\n *\n * Definition of Cosine Tree.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#ifndef MLPACK_CORE_TREE_COSINE_TREE_COSINE_TREE_HPP\n#define MLPACK_CORE_TREE_COSINE_TREE_COSINE_TREE_HPP\n\n#include <mlpack/prereqs.hpp>\n#include <boost/heap/priority_queue.hpp>\n\nnamespace mlpack {\nnamespace tree {\n\n// Predeclare classes for CosineNodeQueue typedef.\nclass CompareCosineNode;\nclass CosineTree;\n\n// CosineNodeQueue typedef.\ntypedef boost::heap::priority_queue<CosineTree*,\n    boost::heap::compare<CompareCosineNode> > CosineNodeQueue;\n\nclass CosineTree\n{\n public:\n  /**\n   * CosineTree constructor for the root node of the tree. It initializes the\n   * necessary variables required for splitting of the node, and building the\n   * tree further. It takes a pointer to the input matrix and calculates the\n   * relevant variables using it.\n   *\n   * @param dataset Matrix for which cosine tree is constructed.\n   */\n  CosineTree(const arma::mat& dataset);\n\n  /**\n   * CosineTree constructor for nodes other than the root node of the tree. It\n   * takes in a pointer to the parent node and a list of column indices which\n   * mentions the columns to be included in the node. The function calculate the\n   * relevant variables just like the constructor above.\n   *\n   * @param parentNode Pointer to the parent cosine node.\n   * @param subIndices Pointer to vector of column indices to be included.\n   */\n  CosineTree(CosineTree& parentNode, const std::vector<size_t>& subIndices);\n\n  /**\n   * Construct the CosineTree and the basis for the given matrix, and passed\n   * 'epsilon' and 'delta' parameters. The CosineTree is constructed by\n   * splitting nodes in the direction of maximum error, stored using a priority\n   * queue. Basis vectors are added from the left and right children of the\n   * split node. The basis vector from a node is the orthonormalized centroid of\n   * its columns. The splitting continues till the Monte Carlo estimate of the\n   * input matrix's projection on the obtained subspace is less than a fraction\n   * of the norm of the input matrix.\n   *\n   * @param dataset Matrix for which the CosineTree is constructed.\n   * @param epsilon Error tolerance fraction for calculated subspace.\n   * @param delta Cumulative probability for Monte Carlo error lower bound.\n   */\n  CosineTree(const arma::mat& dataset,\n             const double epsilon,\n             const double delta);\n\n  /**\n   * Clean up the CosineTree: release allocated memory (including children).\n   */\n  ~CosineTree();\n\n  /**\n   * Calculates the orthonormalization of the passed centroid, with respect to\n   * the current vector subspace.\n   *\n   * @param treeQueue Priority queue of cosine nodes.\n   * @param centroid Centroid of the node being added to the basis.\n   * @param newBasisVector Orthonormalized centroid of the node.\n   * @param addBasisVector Address to additional basis vector.\n   */\n  void ModifiedGramSchmidt(CosineNodeQueue& treeQueue,\n                           arma::vec& centroid,\n                           arma::vec& newBasisVector,\n                           arma::vec* addBasisVector = NULL);\n\n  /**\n   * Estimates the squared error of the projection of the input node's matrix\n   * onto the current vector subspace. A normal distribution is fit using\n   * weighted norms of projections of samples drawn from the input node's matrix\n   * columns. The error is calculated as the difference between the Frobenius\n   * norm of the input node's matrix and lower bound of the normal distribution.\n   *\n   * @param node Node for which Monte Carlo estimate is calculated.\n   * @param treeQueue Priority queue of cosine nodes.\n   * @param addBasisVector1 Address to first additional basis vector.\n   * @param addBasisVector2 Address to second additional basis vector.\n   */\n  double MonteCarloError(CosineTree* node,\n                         CosineNodeQueue& treeQueue,\n                         arma::vec* addBasisVector1 = NULL,\n                         arma::vec* addBasisVector2 = NULL);\n\n  /**\n   * Constructs the final basis matrix, after the cosine tree construction.\n   *\n   * @param treeQueue Priority queue of cosine nodes.\n   */\n  void ConstructBasis(CosineNodeQueue& treeQueue);\n\n  /**\n   * This function splits the cosine node into two children based on the cosines\n   * of the columns contained in the node, with respect to the sampled splitting\n   * point. The function also calls the CosineTree constructor for the children.\n   */\n  void CosineNodeSplit();\n\n  /**\n   * Sample 'numSamples' points from the Length-Squared distribution of the\n   * cosine node. The function uses 'l2NormsSquared' to calculate the cumulative\n   * probability distribution of the column vectors. The sampling is based on a\n   * randomly generated values in the range [0, 1].\n   */\n  void ColumnSamplesLS(std::vector<size_t>& sampledIndices,\n                       arma::vec& probabilities, size_t numSamples);\n\n  /**\n   * Sample a point from the Length-Squared distribution of the cosine node. The\n   * function uses 'l2NormsSquared' to calculate the cumulative probability\n   * distribution of the column vectors. The sampling is based on a randomly\n   * generated value in the range [0, 1].\n   */\n  size_t ColumnSampleLS();\n\n  /**\n   * Sample a column based on the cumulative Length-Squared distribution of the\n   * cosine node, and a randomly generated value in the range [0, 1]. Binary\n   * search is more efficient than searching linearly for the same. This leads\n   * a significant speedup when there are large number of columns to choose from\n   * and when a number of samples are to be drawn from the distribution.\n   *\n   * @param cDistribution Cumulative LS distribution of columns in the node.\n   * @param value Randomly generated value in the range [0, 1].\n   * @param start Starting index of the distribution interval to search in.\n   * @param end Ending index of the distribution interval to search in.\n   */\n  size_t BinarySearch(arma::vec& cDistribution, double value, size_t start,\n                      size_t end);\n\n  /**\n   * Calculate cosines of the columns present in the node, with respect to the\n   * sampled splitting point. The calculated cosine values are useful for\n   * splitting the node into its children.\n   *\n   * @param cosines Vector to store the cosine values in.\n   */\n  void CalculateCosines(arma::vec& cosines);\n\n  /**\n   * Calculate centroid of the columns present in the node. The calculated\n   * centroid is used as a basis vector for the cosine tree being constructed.\n   */\n  void CalculateCentroid();\n\n  //! Returns the basis of the constructed subspace.\n  void GetFinalBasis(arma::mat& finalBasis) { finalBasis = basis; }\n\n  //! Get pointer to the dataset matrix.\n  const arma::mat& GetDataset() const { return dataset; }\n\n  //! Get the indices of columns in the node.\n  std::vector<size_t>& VectorIndices() { return indices; }\n\n  //! Set the Monte Carlo error.\n  void L2Error(const double error) { this->l2Error = error; }\n  //! Get the Monte Carlo error.\n  double L2Error() const { return l2Error; }\n\n  //! Get pointer to the centroid vector.\n  arma::vec& Centroid() { return centroid; }\n\n  //! Set the basis vector of the node.\n  void BasisVector(arma::vec& bVector) { this->basisVector = bVector; }\n\n  //! Get the basis vector of the node.\n  arma::vec& BasisVector() { return basisVector; }\n\n  //! Get pointer to the parent node.\n  CosineTree* Parent() const { return parent; }\n  //! Modify the pointer to the parent node.\n  CosineTree*& Parent() { return parent; }\n\n  //! Get pointer to the left child of the node.\n  CosineTree* Left() const { return left; }\n  //! Modify the pointer to the left child of the node.\n  CosineTree*& Left() { return left; }\n\n  //! Get pointer to the right child of the node.\n  CosineTree* Right() const { return right; }\n  //! Modify the pointer to the left child of the node.\n  CosineTree*& Right() { return right; }\n\n  //! Get number of columns of input matrix in the node.\n  size_t NumColumns() const { return numColumns; }\n\n  //! Get the Frobenius norm squared of columns in the node.\n  double FrobNormSquared() const { return frobNormSquared; }\n\n  //! Get the column index of split point of the node.\n  size_t SplitPointIndex() const { return indices[splitPointIndex]; }\n\n private:\n  //! Matrix for which cosine tree is constructed.\n  const arma::mat& dataset;\n  //! Cumulative probability for Monte Carlo error lower bound.\n  double delta;\n  //! Subspace basis of the input dataset.\n  arma::mat basis;\n  //! Parent of the node.\n  CosineTree* parent;\n  //! Left child of the node.\n  CosineTree* left;\n  //! Right child of the node.\n  CosineTree* right;\n  //! Indices of columns of input matrix in the node.\n  std::vector<size_t> indices;\n  //! L2-norm squared of columns in the node.\n  arma::vec l2NormsSquared;\n  //! Centroid of columns of input matrix in the node.\n  arma::vec centroid;\n  //! Orthonormalized basis vector of the node.\n  arma::vec basisVector;\n  //! Index of split point of cosine node.\n  size_t splitPointIndex;\n  //! Number of columns of input matrix in the node.\n  size_t numColumns;\n  //! Monte Carlo error for this node.\n  double l2Error;\n  //! Frobenius norm squared of columns in the node.\n  double frobNormSquared;\n};\n\nclass CompareCosineNode\n{\n public:\n  // Comparison function for construction of priority queue.\n  bool operator() (const CosineTree* a, const CosineTree* b) const\n  {\n    return a->L2Error() < b->L2Error();\n  }\n};\n\n} // namespace tree\n} // namespace mlpack\n\n#endif\n", "meta": {"hexsha": "a94562afbae98ff71d17c4a161bfab42a1d07d28", "size": 9794, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/core/tree/cosine_tree/cosine_tree.hpp", "max_stars_repo_name": "RMaron/mlpack", "max_stars_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 675.0, "max_stars_repo_stars_event_min_datetime": "2019-02-07T01:23:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T05:45:10.000Z", "max_issues_repo_path": "src/mlpack/core/tree/cosine_tree/cosine_tree.hpp", "max_issues_repo_name": "RMaron/mlpack", "max_issues_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": 843.0, "max_issues_repo_issues_event_min_datetime": "2019-01-25T01:06:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T11:15:53.000Z", "max_forks_repo_path": "src/mlpack/core/tree/cosine_tree/cosine_tree.hpp", "max_forks_repo_name": "RMaron/mlpack", "max_forks_repo_head_hexsha": "a179a2708d9555ab7ee4b1e90e0c290092edad2e", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2019-02-20T06:18:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T09:36:09.000Z", "avg_line_length": 37.6692307692, "max_line_length": 80, "alphanum_fraction": 0.7077802736, "num_tokens": 2329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.40219346944133555}}
{"text": "#include \"polygons_to_triangles.h\"\n#include \"ear_clipping.h\"\n#include \"../sort.h\"\n#include \"../slice.h\"\n#include <Eigen/Eigenvalues>\n\ntemplate <\n  typename DerivedV,\n  typename DerivedI,\n  typename DerivedC,\n  typename DerivedF,\n  typename DerivedJ>\nIGL_INLINE void igl::predicates::polygons_to_triangles(\n  const Eigen::MatrixBase<DerivedV> & V,\n  const Eigen::MatrixBase<DerivedI> & I,\n  const Eigen::MatrixBase<DerivedC> & C,\n  Eigen::PlainObjectBase<DerivedF> & F,\n  Eigen::PlainObjectBase<DerivedJ> & J)\n{\n  typedef Eigen::Index Index;\n  // Each polygon results in #sides-2 triangles. So ∑#sides-2\n  F.resize(C(C.size()-1) - (C.size()-1)*2,3);\n  J.resize(F.rows());\n  {\n    Index f = 0;\n    for(Index p = 0;p<C.size()-1;p++)\n    {\n      const Index np = C(p+1)-C(p);\n      Eigen::MatrixXi pF;\n      if(np == 3)\n      {\n        pF = (Eigen::MatrixXi(1,3)<<0,1,2).finished();\n      }else\n      {\n        // Make little copy of this polygon with an initial fan\n        DerivedV pV(np,V.cols());\n        for(Index c = 0;c<np;c++)\n        {\n          pV.row(c) = V.row(I(C(p)+c));\n        }\n        // Use PCA to project to 2D\n        Eigen::MatrixXd S;\n        switch(V.cols())\n        {\n          case 2:\n            S = V.template cast<double>();\n            break;\n          case 3:\n          {\n            Eigen::MatrixXd P = (pV.rowwise() - pV.colwise().mean()).template cast<double>();\n            Eigen::Matrix3d O = P.transpose() * P;\n            Eigen::EigenSolver<Eigen::Matrix3d> es(O);\n            Eigen::Matrix3d C = es.eigenvectors().real();\n            {\n              Eigen::Vector3d _1;\n              Eigen::Vector3i I;\n              igl::sort(es.eigenvalues().real().eval(),1,false,_1,I);\n              igl::slice(Eigen::Matrix3d(C),I,2,C);\n            }\n            S = P*C.leftCols(2);\n            break;\n          }\n          default: assert(false && \"dim>3 not supported\");\n        }\n\n        Eigen::VectorXi RT = Eigen::VectorXi::Zero(S.rows(),1);\n        Eigen::VectorXi _I;\n        Eigen::MatrixXd _nS;\n\n        // compute signed area\n        {\n          double area = 0;\n          for(Index c = 0;c<np;c++)\n          {\n            area += S((c+0)%np,0)*S((c+1)%np,1) - S((c+1)%np,0)*S((c+0)%np,1);\n          }\n          //prIndexf(\"area: %g\\n\",area);\n          if(area<0)\n          {\n            S.col(0) *= -1;\n          }\n        }\n\n        // This is a really low quality triangulator and will contain nearly\n        // degenerate elements which become degenerate or worse when unprojected\n        // back to 3D.\n        igl::predicates::ear_clipping(S,RT,_I,pF,_nS);\n        // igl::predicates::ear_clipping does not gracefully fail when the input\n        // is not simple. Instead it (tends?) to output too few triangles.\n        if(pF.rows() < np-2)\n        {\n          // Fallback, use a fan\n          //std::cout<<igl::matlab_format(S,\"S\")<<std::endl;\n          //std::cout<<igl::matlab_format(RT,\"RT\")<<std::endl;\n          //std::cout<<igl::matlab_format(_I,\"I\")<<std::endl;\n          //std::cout<<igl::matlab_format(pF,\"pF\")<<std::endl;\n          //std::cout<<igl::matlab_format(_nS,\"nS\")<<std::endl;\n          //std::cout<<std::endl;\n\n          pF.resize(np-2,3);\n          for(Index c = 0;c<np;c++)\n          {\n            if(c>0 && c<np-1)\n            {\n              pF(c-1,0) = 0;\n              pF(c-1,1) = c;\n              pF(c-1,2) = c+1;\n            }\n          }\n        }\n        assert(pF.rows() == np-2);\n\n        // Could at least flip edges of degenerate edges\n\n        //if(pF.rows()>1)\n        //{\n        //  // Delaunay-ize \n        //  Eigen::MatrixXd pl;\n        //  igl::edge_lengths(pV,pF,pl);\n\n        //  typedef Eigen::Matrix<Index,Eigen::Dynamic,2> MatrixX2I;\n        //  typedef Eigen::Matrix<Index,Eigen::Dynamic,1> VectorXI;\n        //  MatrixX2I E,uE;\n        //  VectorXI EMAP;\n        //  std::vector<std::vector<Index> > uE2E;\n        //  igl::unique_edge_map(pF, E, uE, EMAP, uE2E);\n        //  typedef Index Index;\n        //  typedef double Scalar;\n        //  const Index num_faces = pF.rows();\n        //  std::vector<Index> Q;\n        //  Q.reserve(uE2E.size());\n        //  for (size_t uei=0; uei<uE2E.size(); uei++) \n        //  {\n        //    Q.push_back(uei);\n        //  }\n        //  while(!Q.empty())\n        //  {\n        //    const Index uei = Q.back();\n        //    Q.pop_back();\n        //    if (uE2E[uei].size() == 2) \n        //    {\n        //      double w;\n        //      igl::is_Indexrinsic_delaunay(pl,uE2E,num_faces,uei,w);\n        //      prIndexf(\"%d : %0.17f\\n\",uei,w);\n        //      if(w<-1e-7) \n        //      {\n        //        prIndexf(\"  flippin'\\n\");\n        //        //\n        //        //          v1                 v1\n        //        //          /|\\                / \\\n        //        //        c/ | \\b            c/f1 \\b\n        //        //     v3 /f2|f1\\ v4  =>  v3 /__f__\\ v4\n        //        //        \\  e  /            \\ f2  /\n        //        //        d\\ | /a            d\\   /a\n        //        //          \\|/                \\ /\n        //        //          v2                 v2\n        //        //\n        //        // hmm... is the flip actually in the other direction?\n        //        const Index f1 = uE2E[uei][0]%num_faces;\n        //        const Index f2 = uE2E[uei][1]%num_faces;\n        //        const Index c1 = uE2E[uei][0]/num_faces;\n        //        const Index c2 = uE2E[uei][1]/num_faces;\n        //        const size_t e_24 = f1 + ((c1 + 1) % 3) * num_faces;\n        //        const size_t e_41 = f1 + ((c1 + 2) % 3) * num_faces;\n        //        const size_t e_13 = f2 + ((c2 + 1) % 3) * num_faces;\n        //        const size_t e_32 = f2 + ((c2 + 2) % 3) * num_faces;\n        //        const size_t ue_24 = EMAP(e_24);\n        //        const size_t ue_41 = EMAP(e_41);\n        //        const size_t ue_13 = EMAP(e_13);\n        //        const size_t ue_32 = EMAP(e_32);\n        //        // new edge lengths\n        //        const Index v1 = pF(f1, (c1+1)%3);\n        //        const Index v2 = pF(f1, (c1+2)%3);\n        //        const Index v4 = pF(f1, c1);\n        //        const Index v3 = pF(f2, c2);\n        //        {\n        //          const Scalar e = pl(f1,c1);\n        //          const Scalar a = pl(f1,(c1+1)%3);\n        //          const Scalar b = pl(f1,(c1+2)%3);\n        //          const Scalar c = pl(f2,(c2+1)%3);\n        //          const Scalar d = pl(f2,(c2+2)%3);\n        //          const double f = (pV.row(v3)-pV.row(v4)).norm();\n        //          // New order\n        //          pl(f1,0) = f;\n        //          pl(f1,1) = b;\n        //          pl(f1,2) = c;\n        //          pl(f2,0) = f;\n        //          pl(f2,1) = d;\n        //          pl(f2,2) = a;\n        //        }\n        //        prIndexf(\"%d,%d %d,%d -> %d,%d\\n\",uE(uei,0),uE(uei,1),v1,v2,v3,v4);\n        //        igl::flip_edge(pF, E, uE, EMAP, uE2E, uei);\n        //        std::cout<<\"  \"<<pl.row(f1)<<std::endl;\n        //        std::cout<<\"  \"<<pl.row(f2)<<std::endl;\n        //        //// new edge lengths, slow!\n        //        //igl::edge_lengths(pV,pF,pl);\n        //        // recompute edge lengths of two faces. (extra work on untouched\n        //        // edges)\n        //        for(Index f : {f1,f2})\n        //        {\n        //          for(Index c=0;c<3;c++)\n        //          {\n        //            pl(f,c) = \n        //              (pV.row(pF(f,(c+1)%3))-pV.row(pF(f,(c+2)%3))).norm();\n        //          }\n        //        }\n        //        std::cout<<\"  \"<<pl.row(f1)<<std::endl;\n        //        std::cout<<\"  \"<<pl.row(f2)<<std::endl;\n        //        std::cout<<std::endl;\n\n        //        Q.push_back(ue_24);\n        //        Q.push_back(ue_41);\n        //        Q.push_back(ue_13);\n        //        Q.push_back(ue_32);\n        //      }\n        //    }\n        //  }\n\n\n        //  // check for self-loops (I claim these cannot happen)\n        //  for(Index f = 0;f<pF.rows();f++)\n        //  {\n        //    for(Index c =0;c<3;c++)\n        //    {\n        //      assert(pF(f,c) != pF(f,(c+1)%3) && \"self loops should not exist\");\n        //    }\n        //  }\n        //}\n      }\n      // Copy Indexo global list\n      for(Index i = 0;i<pF.rows();i++)\n      {\n        for(Index c =0;c<3;c++)\n        {\n          F(f,c) = I(C(p)+pF(i,c));\n        }\n        J(f) = p;\n        f++;\n      }\n\n    }\n    assert(f == F.rows());\n  }\n}\n\n#ifdef IGL_STATIC_LIBRARY\n// Explicit template instantiation\n#endif\n", "meta": {"hexsha": "8adb76c21b7b8e07868eece6b36e8e8b1a2b2cc3", "size": 8522, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/libigl/include/igl/predicates/polygons_to_triangles.cpp", "max_stars_repo_name": "chefmramos85/monster-mash", "max_stars_repo_head_hexsha": "239a41f6f178ca83c4be638331e32f23606b0381", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1125.0, "max_stars_repo_stars_event_min_datetime": "2021-02-01T09:51:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:50:40.000Z", "max_issues_repo_path": "third_party/libigl/include/igl/predicates/polygons_to_triangles.cpp", "max_issues_repo_name": "ryan-cranfill/monster-mash", "max_issues_repo_head_hexsha": "c1b906d996885f8a4011bdf7558e62e968e1e914", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2021-02-01T12:36:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T14:02:50.000Z", "max_forks_repo_path": "third_party/libigl/include/igl/predicates/polygons_to_triangles.cpp", "max_forks_repo_name": "ryan-cranfill/monster-mash", "max_forks_repo_head_hexsha": "c1b906d996885f8a4011bdf7558e62e968e1e914", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 148.0, "max_forks_repo_forks_event_min_datetime": "2021-02-13T10:54:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T11:55:20.000Z", "avg_line_length": 34.2248995984, "max_line_length": 93, "alphanum_fraction": 0.4178596574, "num_tokens": 2613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850154599562, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4021934623882379}}
{"text": "/*********************************************************************\n* Software License Agreement (BSD License)\n*\n*  Copyright (c) 2010, Rice University\n*  All rights reserved.\n*\n*  Redistribution and use in source and binary forms, with or without\n*  modification, are permitted provided that the following conditions\n*  are met:\n*\n*   * Redistributions of source code must retain the above copyright\n*     notice, this list of conditions and the following disclaimer.\n*   * Redistributions in binary form must reproduce the above\n*     copyright notice, this list of conditions and the following\n*     disclaimer in the documentation and/or other materials provided\n*     with the distribution.\n*   * Neither the name of the Rice University nor the names of its\n*     contributors may be used to endorse or promote products derived\n*     from this software without specific prior written permission.\n*\n*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n*  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n*  POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************/\n\n/* Author: Mark Moll */\n\n#include \"ompl/base/spaces/ReedsSheppStateSpace.h\"\n#include \"ompl/base/SpaceInformation.h\"\n#include \"ompl/util/Exception.h\"\n#include <queue>\n#include <boost/math/constants/constants.hpp>\n\n\nusing namespace ompl::base;\n\nnamespace\n{\n    // The comments, variable names, etc. use the nomenclature from the Reeds & Shepp paper.\n\n    const double pi = boost::math::constants::pi<double>();\n    const double twopi = 2. * pi;\n    const double RS_EPS = 1e-6;\n    const double ZERO = 10*std::numeric_limits<double>::epsilon();\n\n    inline double mod2pi(double x)\n    {\n        double v = fmod(x, twopi);\n        if (v < -pi)\n            v += twopi;\n        else\n            if (v > pi)\n                v -= twopi;\n        return v;\n    }\n    inline void polar(double x, double y, double &r, double &theta)\n    {\n        r = sqrt(x*x + y*y);\n        theta = atan2(y, x);\n    }\n    inline void tauOmega(double u, double v, double xi, double eta, double phi, double &tau, double &omega)\n    {\n        double delta = mod2pi(u-v), A = sin(u) - sin(delta), B = cos(u) - cos(delta) - 1.;\n        double t1 = atan2(eta*A - xi*B, xi*A + eta*B), t2 = 2. * (cos(delta) - cos(v) - cos(u)) + 3;\n        tau = (t2<0) ? mod2pi(t1+pi) : mod2pi(t1);\n        omega = mod2pi(tau - u + v - phi) ;\n    }\n\n    // formula 8.1 in Reeds-Shepp paper\n    inline bool LpSpLp(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        polar(x - sin(phi), y - 1. + cos(phi), u, t);\n        if (t >= -ZERO)\n        {\n            v = mod2pi(phi - t);\n            if (v >= -ZERO)\n            {\n                assert(fabs(u*cos(t) + sin(phi) - x) < RS_EPS);\n                assert(fabs(u*sin(t) - cos(phi) + 1 - y) < RS_EPS);\n                assert(fabs(mod2pi(t+v - phi)) < RS_EPS);\n                return true;\n            }\n        }\n        return false;\n    }\n    // formula 8.2\n    inline bool LpSpRp(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double t1, u1;\n        polar(x + sin(phi), y - 1. - cos(phi), u1, t1);\n        u1 = u1*u1;\n        if (u1 >= 4.)\n        {\n            double theta;\n            u = sqrt(u1 - 4.);\n            theta = atan2(2., u);\n            t = mod2pi(t1 + theta);\n            v = mod2pi(t - phi);\n            assert(fabs(2*sin(t) + u*cos(t) - sin(phi) - x) < RS_EPS);\n            assert(fabs(-2*cos(t) + u*sin(t) + cos(phi) + 1 - y) < RS_EPS);\n            assert(fabs(mod2pi(t-v - phi)) < RS_EPS);\n            return t>=-ZERO && v>=-ZERO;\n        }\n        return false;\n    }\n    void CSC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath &path)\n    {\n        double t, u, v, Lmin = path.length(), L;\n        if (LpSpLp(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[14], t, u, v);\n            Lmin = L;\n        }\n        if (LpSpLp(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[14], -t, -u, -v);\n            Lmin = L;\n        }\n        if (LpSpLp(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[15], t, u, v);\n            Lmin = L;\n        }\n        if (LpSpLp(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[15], -t, -u, -v);\n            Lmin = L;\n        }\n        if (LpSpRp(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[12], t, u, v);\n            Lmin = L;\n        }\n        if (LpSpRp(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[12], -t, -u, -v);\n            Lmin = L;\n        }\n        if (LpSpRp(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[13], t, u, v);\n            Lmin = L;\n        }\n        if (LpSpRp(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[13], -t, -u, -v);\n    }\n    // formula 8.3 / 8.4  *** TYPO IN PAPER ***\n    inline bool LpRmL(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double xi = x - sin(phi), eta = y - 1. + cos(phi), u1, theta;\n        polar(xi, eta, u1, theta);\n        if (u1 <= 4.)\n        {\n            u = -2.*asin(.25 * u1);\n            t = mod2pi(theta + .5 * u + pi);\n            v = mod2pi(phi - t + u);\n            assert(fabs(2*(sin(t) - sin(t-u)) + sin(phi) - x) < RS_EPS);\n            assert(fabs(2*(-cos(t) + cos(t-u)) - cos(phi) + 1 - y) < RS_EPS);\n            assert(fabs(mod2pi(t-u+v - phi)) < RS_EPS);\n            return t>=-ZERO && u<=ZERO;\n        }\n        return false;\n    }\n    void CCC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath &path)\n    {\n        double t, u, v, Lmin = path.length(), L;\n        if (LpRmL(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[0], t, u, v);\n            Lmin = L;\n        }\n        if (LpRmL(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[0], -t, -u, -v);\n            Lmin = L;\n        }\n        if (LpRmL(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[1], t, u, v);\n            Lmin = L;\n        }\n        if (LpRmL(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[1], -t, -u, -v);\n            Lmin = L;\n        }\n\n        // backwards\n        double xb = x*cos(phi) + y*sin(phi), yb = x*sin(phi) - y*cos(phi);\n        if (LpRmL(xb, yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[0], v, u, t);\n            Lmin = L;\n        }\n        if (LpRmL(-xb, yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[0], -v, -u, -t);\n            Lmin = L;\n        }\n        if (LpRmL(xb, -yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[1], v, u, t);\n            Lmin = L;\n        }\n        if (LpRmL(-xb, -yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[1], -v, -u, -t);\n    }\n    // formula 8.7\n    inline bool LpRupLumRm(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double xi = x + sin(phi), eta = y - 1. - cos(phi), rho = .25 * (2. + sqrt(xi*xi + eta*eta));\n        if (rho <= 1.)\n        {\n            u = acos(rho);\n            tauOmega(u, -u, xi, eta, phi, t, v);\n            assert(fabs(2*(sin(t)-sin(t-u)+sin(t-2*u))-sin(phi) - x) < RS_EPS);\n            assert(fabs(2*(-cos(t)+cos(t-u)-cos(t-2*u))+cos(phi)+1 - y) < RS_EPS);\n            assert(fabs(mod2pi(t-2*u-v - phi)) < RS_EPS);\n            return t>=-ZERO && v<=ZERO;\n        }\n        return false;\n    }\n    // formula 8.8\n    inline bool LpRumLumRp(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double xi = x + sin(phi), eta = y - 1. - cos(phi), rho = (20. - xi*xi - eta*eta) / 16.;\n        if (rho>=0 && rho<=1)\n        {\n            u = -acos(rho);\n            if (u >= -.5 * pi)\n            {\n                tauOmega(u, u, xi, eta, phi, t, v);\n                assert(fabs(4*sin(t)-2*sin(t-u)-sin(phi) - x) < RS_EPS);\n                assert(fabs(-4*cos(t)+2*cos(t-u)+cos(phi)+1 - y) < RS_EPS);\n                assert(fabs(mod2pi(t-v - phi)) < RS_EPS);\n                return t>=-ZERO && v>=-ZERO;\n            }\n        }\n        return false;\n    }\n    void CCCC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath &path)\n    {\n        double t, u, v, Lmin = path.length(), L;\n        if (LpRupLumRm(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[2], t, u, -u, v);\n            Lmin = L;\n        }\n        if (LpRupLumRm(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[2], -t, -u, u, -v);\n            Lmin = L;\n        }\n        if (LpRupLumRm(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[3], t, u, -u, v);\n            Lmin = L;\n        }\n        if (LpRupLumRm(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v))) // timeflip + reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[3], -t, -u, u, -v);\n            Lmin = L;\n        }\n\n        if (LpRumLumRp(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[2], t, u, u, v);\n            Lmin = L;\n        }\n        if (LpRumLumRp(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[2], -t, -u, -u, -v);\n            Lmin = L;\n        }\n        if (LpRumLumRp(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[3], t, u, u, v);\n            Lmin = L;\n        }\n        if (LpRumLumRp(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + 2.*fabs(u) + fabs(v))) // timeflip + reflect\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[3], -t, -u, -u, -v);\n    }\n    // formula 8.9\n    inline bool LpRmSmLm(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double xi = x - sin(phi), eta = y - 1. + cos(phi), rho, theta;\n        polar(xi, eta, rho, theta);\n        if (rho >= 2.)\n        {\n            double r = sqrt(rho*rho - 4.);\n            u = 2. - r;\n            t = mod2pi(theta + atan2(r, -2.));\n            v = mod2pi(phi - .5*pi - t);\n            assert(fabs(2*(sin(t)-cos(t))-u*sin(t)+sin(phi) - x) < RS_EPS);\n            assert(fabs(-2*(sin(t)+cos(t))+u*cos(t)-cos(phi)+1 - y) < RS_EPS);\n            assert(fabs(mod2pi(t+pi/2+v-phi)) < RS_EPS);\n            return t>=-ZERO && u<=ZERO && v<=ZERO;\n        }\n        return false;\n    }\n    // formula 8.10\n    inline bool LpRmSmRm(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double xi = x + sin(phi), eta = y - 1. - cos(phi), rho, theta;\n        polar(-eta, xi, rho, theta);\n        if (rho >= 2.)\n        {\n            t = theta;\n            u = 2. - rho;\n            v = mod2pi(t + .5*pi - phi);\n            assert(fabs(2*sin(t)-cos(t-v)-u*sin(t) - x) < RS_EPS);\n            assert(fabs(-2*cos(t)-sin(t-v)+u*cos(t)+1 - y) < RS_EPS);\n            assert(fabs(mod2pi(t+pi/2-v-phi)) < RS_EPS);\n            return t>=-ZERO && u<=ZERO && v<=ZERO;\n        }\n        return false;\n    }\n    void CCSC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath &path)\n    {\n        double t, u, v, Lmin = path.length() - .5*pi, L;\n        if (LpRmSmLm(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[4], t, -.5*pi, u, v);\n            Lmin = L;\n        }\n        if (LpRmSmLm(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[4], -t, .5*pi, -u, -v);\n            Lmin = L;\n        }\n        if (LpRmSmLm(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[5], t, -.5*pi, u, v);\n            Lmin = L;\n        }\n        if (LpRmSmLm(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[5], -t, .5*pi, -u, -v);\n            Lmin = L;\n        }\n\n        if (LpRmSmRm(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[8], t, -.5*pi, u, v);\n            Lmin = L;\n        }\n        if (LpRmSmRm(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[8], -t, .5*pi, -u, -v);\n            Lmin = L;\n        }\n        if (LpRmSmRm(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[9], t, -.5*pi, u, v);\n            Lmin = L;\n        }\n        if (LpRmSmRm(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[9], -t, .5*pi, -u, -v);\n            Lmin = L;\n        }\n\n        // backwards\n        double xb = x*cos(phi) + y*sin(phi), yb = x*sin(phi) - y*cos(phi);\n        if (LpRmSmLm(xb, yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[6], v, u, -.5*pi, t);\n            Lmin = L;\n        }\n        if (LpRmSmLm(-xb, yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[6], -v, -u, .5*pi, -t);\n            Lmin = L;\n        }\n        if (LpRmSmLm(xb, -yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[7], v, u, -.5*pi, t);\n            Lmin = L;\n        }\n        if (LpRmSmLm(-xb, -yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[7], -v, -u, .5*pi, -t);\n            Lmin = L;\n        }\n\n        if (LpRmSmRm(xb, yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[10], v, u, -.5*pi, t);\n            Lmin = L;\n        }\n        if (LpRmSmRm(-xb, yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[10], -v, -u, .5*pi, -t);\n            Lmin = L;\n        }\n        if (LpRmSmRm(xb, -yb, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[11], v, u, -.5*pi, t);\n            Lmin = L;\n        }\n        if (LpRmSmRm(-xb, -yb, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[11], -v, -u, .5*pi, -t);\n    }\n    // formula 8.11 *** TYPO IN PAPER ***\n    inline bool LpRmSLmRp(double x, double y, double phi, double &t, double &u, double &v)\n    {\n        double xi = x + sin(phi), eta = y - 1. - cos(phi), rho, theta;\n        polar(xi, eta, rho, theta);\n        if (rho >= 2.)\n        {\n            u = 4. - sqrt(rho*rho - 4.);\n            if (u <= ZERO)\n            {\n                t = mod2pi(atan2((4-u)*xi -2*eta, -2*xi + (u-4)*eta));\n                v = mod2pi(t - phi);\n                assert(fabs(4*sin(t)-2*cos(t)-u*sin(t)-sin(phi) - x) < RS_EPS);\n                assert(fabs(-4*cos(t)-2*sin(t)+u*cos(t)+cos(phi)+1 - y) < RS_EPS);\n                assert(fabs(mod2pi(t-v-phi)) < RS_EPS);\n                return t>=-ZERO && v>=-ZERO;\n            }\n        }\n        return false;\n    }\n    void CCSCC(double x, double y, double phi, ReedsSheppStateSpace::ReedsSheppPath &path)\n    {\n        double t, u, v, Lmin = path.length() - pi, L;\n        if (LpRmSLmRp(x, y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v)))\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[16], t, -.5*pi, u, -.5*pi, v);\n            Lmin = L;\n        }\n        if (LpRmSLmRp(-x, y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[16], -t, .5*pi, -u, .5*pi, -v);\n            Lmin = L;\n        }\n        if (LpRmSLmRp(x, -y, -phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // reflect\n        {\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[17], t, -.5*pi, u, -.5*pi, v);\n            Lmin = L;\n        }\n        if (LpRmSLmRp(-x, -y, phi, t, u, v) && Lmin > (L = fabs(t) + fabs(u) + fabs(v))) // timeflip + reflect\n            path = ReedsSheppStateSpace::ReedsSheppPath(\n                ReedsSheppStateSpace::reedsSheppPathType[17], -t, .5*pi, -u, .5*pi, -v);\n    }\n\n    ReedsSheppStateSpace::ReedsSheppPath reedsShepp(double x, double y, double phi)\n    {\n        ReedsSheppStateSpace::ReedsSheppPath path;\n        CSC(x, y, phi, path);\n        CCC(x, y, phi, path);\n        CCCC(x, y, phi, path);\n        CCSC(x, y, phi, path);\n        CCSCC(x, y, phi, path);\n        return path;\n    }\n}\n\nconst ompl::base::ReedsSheppStateSpace::ReedsSheppPathSegmentType\nompl::base::ReedsSheppStateSpace::reedsSheppPathType[18][5] = {\n    { RS_LEFT, RS_RIGHT, RS_LEFT, RS_NOP, RS_NOP },             // 0\n    { RS_RIGHT, RS_LEFT, RS_RIGHT, RS_NOP, RS_NOP },            // 1\n    { RS_LEFT, RS_RIGHT, RS_LEFT, RS_RIGHT, RS_NOP },           // 2\n    { RS_RIGHT, RS_LEFT, RS_RIGHT, RS_LEFT, RS_NOP },           // 3\n    { RS_LEFT, RS_RIGHT, RS_STRAIGHT, RS_LEFT, RS_NOP },        // 4\n    { RS_RIGHT, RS_LEFT, RS_STRAIGHT, RS_RIGHT, RS_NOP },       // 5\n    { RS_LEFT, RS_STRAIGHT, RS_RIGHT, RS_LEFT, RS_NOP },        // 6\n    { RS_RIGHT, RS_STRAIGHT, RS_LEFT, RS_RIGHT, RS_NOP },       // 7\n    { RS_LEFT, RS_RIGHT, RS_STRAIGHT, RS_RIGHT, RS_NOP },       // 8\n    { RS_RIGHT, RS_LEFT, RS_STRAIGHT, RS_LEFT, RS_NOP },        // 9\n    { RS_RIGHT, RS_STRAIGHT, RS_RIGHT, RS_LEFT, RS_NOP },       // 10\n    { RS_LEFT, RS_STRAIGHT, RS_LEFT, RS_RIGHT, RS_NOP },        // 11\n    { RS_LEFT, RS_STRAIGHT, RS_RIGHT, RS_NOP, RS_NOP },         // 12\n    { RS_RIGHT, RS_STRAIGHT, RS_LEFT, RS_NOP, RS_NOP },         // 13\n    { RS_LEFT, RS_STRAIGHT, RS_LEFT, RS_NOP, RS_NOP },          // 14\n    { RS_RIGHT, RS_STRAIGHT, RS_RIGHT, RS_NOP, RS_NOP },        // 15\n    { RS_LEFT, RS_RIGHT, RS_STRAIGHT, RS_LEFT, RS_RIGHT },      // 16\n    { RS_RIGHT, RS_LEFT, RS_STRAIGHT, RS_RIGHT, RS_LEFT }       // 17\n};\n\nompl::base::ReedsSheppStateSpace::ReedsSheppPath::ReedsSheppPath(const ReedsSheppPathSegmentType* type,\n    double t, double u, double v, double w, double x)\n    : type_(type)\n{\n    length_[0] = t; length_[1] = u; length_[2] = v; length_[3] = w; length_[4] = x;\n    totalLength_ = fabs(t) + fabs(u) + fabs(v) + fabs(w) + fabs(x);\n}\n\n\ndouble ompl::base::ReedsSheppStateSpace::distance(const State *state1, const State *state2) const\n{\n    return rho_ * reedsShepp(state1, state2).length();\n}\n\nvoid ompl::base::ReedsSheppStateSpace::interpolate(const State *from, const State *to, const double t, State *state) const\n{\n    bool firstTime = true;\n    ReedsSheppPath path;\n    interpolate(from, to, t, firstTime, path, state);\n}\n\nvoid ompl::base::ReedsSheppStateSpace::interpolate(const State *from, const State *to, const double t,\n    bool &firstTime, ReedsSheppPath &path, State *state) const\n{\n    if (firstTime)\n    {\n        if (t>=1.)\n        {\n            if (to != state)\n                copyState(state, to);\n            return;\n        }\n        if (t<=0.)\n        {\n            if (from != state)\n                copyState(state, from);\n            return;\n        }\n        path = reedsShepp(from, to);\n        firstTime = false;\n    }\n    interpolate(from, path, t, state);\n}\n\nvoid ompl::base::ReedsSheppStateSpace::interpolate(const State *from, const ReedsSheppPath &path, double t, State *state) const\n{\n    StateType *s = allocState()->as<StateType>();\n    double seg = t * path.length(), phi, v;\n\n    s->setXY(0., 0.);\n    s->setYaw(from->as<StateType>()->getYaw());\n    for (unsigned int i=0; i<5 && seg>0; ++i)\n    {\n        if (path.length_[i]<0)\n        {\n            v = std::max(-seg, path.length_[i]);\n            seg += v;\n        }\n        else\n        {\n            v = std::min(seg, path.length_[i]);\n            seg -= v;\n        }\n        phi = s->getYaw();\n        switch(path.type_[i])\n        {\n            case RS_LEFT:\n                s->setXY(s->getX() + sin(phi+v) - sin(phi), s->getY() - cos(phi+v) + cos(phi));\n                s->setYaw(phi+v);\n                break;\n            case RS_RIGHT:\n                s->setXY(s->getX() - sin(phi-v) + sin(phi), s->getY() + cos(phi-v) - cos(phi));\n                s->setYaw(phi-v);\n                break;\n            case RS_STRAIGHT:\n                s->setXY(s->getX() + v * cos(phi), s->getY() + v * sin(phi));\n                break;\n            case RS_NOP:\n                break;\n        }\n    }\n    state->as<StateType>()->setX(s->getX() * rho_ + from->as<StateType>()->getX());\n    state->as<StateType>()->setY(s->getY() * rho_ + from->as<StateType>()->getY());\n    getSubspace(1)->enforceBounds(s->as<SO2StateSpace::StateType>(1));\n    state->as<StateType>()->setYaw(s->getYaw());\n    freeState(s);\n}\n\nompl::base::ReedsSheppStateSpace::ReedsSheppPath ompl::base::ReedsSheppStateSpace::reedsShepp(const State *state1, const State *state2) const\n{\n    const StateType *s1 = static_cast<const StateType*>(state1);\n    const StateType *s2 = static_cast<const StateType*>(state2);\n    double x1 = s1->getX(), y1 = s1->getY(), th1 = s1->getYaw();\n    double x2 = s2->getX(), y2 = s2->getY(), th2 = s2->getYaw();\n    double dx = x2 - x1, dy = y2 - y1, c = cos(th1), s = sin(th1);\n    double x = c*dx + s*dy, y = -s*dx + c*dy, phi = th2 - th1;\n    return ::reedsShepp(x/rho_, y/rho_, phi);\n}\n\n\nvoid ompl::base::ReedsSheppMotionValidator::defaultSettings()\n{\n    stateSpace_ = dynamic_cast<ReedsSheppStateSpace*>(si_->getStateSpace().get());\n    if (!stateSpace_)\n        throw Exception(\"No state space for motion validator\");\n}\n\nbool ompl::base::ReedsSheppMotionValidator::checkMotion(const State *s1, const State *s2, std::pair<State*, double> &lastValid) const\n{\n    /* assume motion starts in a valid configuration so s1 is valid */\n\n    bool result = true, firstTime = true;\n    ReedsSheppStateSpace::ReedsSheppPath path;\n    int nd = stateSpace_->validSegmentCount(s1, s2);\n\n    if (nd > 1)\n    {\n        /* temporary storage for the checked state */\n        State *test = si_->allocState();\n\n        for (int j = 1 ; j < nd ; ++j)\n        {\n            stateSpace_->interpolate(s1, s2, (double)j / (double)nd, firstTime, path, test);\n            if (!si_->isValid(test))\n            {\n                lastValid.second = (double)(j - 1) / (double)nd;\n                if (lastValid.first)\n                    stateSpace_->interpolate(s1, s2, lastValid.second, firstTime, path, lastValid.first);\n                result = false;\n                break;\n            }\n        }\n        si_->freeState(test);\n    }\n\n    if (result)\n        if (!si_->isValid(s2))\n        {\n            lastValid.second = (double)(nd - 1) / (double)nd;\n            if (lastValid.first)\n                stateSpace_->interpolate(s1, s2, lastValid.second, firstTime, path, lastValid.first);\n            result = false;\n        }\n\n    if (result)\n        valid_++;\n    else\n        invalid_++;\n\n    return result;\n}\n\nbool ompl::base::ReedsSheppMotionValidator::checkMotion(const State *s1, const State *s2) const\n{\n    /* assume motion starts in a valid configuration so s1 is valid */\n    if (!si_->isValid(s2))\n        return false;\n\n    bool result = true, firstTime = true;\n    ReedsSheppStateSpace::ReedsSheppPath path;\n    int nd = stateSpace_->validSegmentCount(s1, s2);\n\n    /* initialize the queue of test positions */\n    std::queue< std::pair<int, int> > pos;\n    if (nd >= 2)\n    {\n        pos.push(std::make_pair(1, nd - 1));\n\n        /* temporary storage for the checked state */\n        State *test = si_->allocState();\n\n        /* repeatedly subdivide the path segment in the middle (and check the middle) */\n        while (!pos.empty())\n        {\n            std::pair<int, int> x = pos.front();\n\n            int mid = (x.first + x.second) / 2;\n            stateSpace_->interpolate(s1, s2, (double)mid / (double)nd, firstTime, path, test);\n\n            if (!si_->isValid(test))\n            {\n                result = false;\n                break;\n            }\n\n            pos.pop();\n\n            if (x.first < mid)\n                pos.push(std::make_pair(x.first, mid - 1));\n            if (x.second > mid)\n                pos.push(std::make_pair(mid + 1, x.second));\n        }\n\n        si_->freeState(test);\n    }\n\n    if (result)\n        valid_++;\n    else\n        invalid_++;\n\n    return result;\n}\n", "meta": {"hexsha": "3e8b6111d8f5f0678320f60f9f89234e00ec7172", "size": 29419, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/base/spaces/src/ReedsSheppStateSpace.cpp", "max_stars_repo_name": "ivaROS/ivaOmplCore", "max_stars_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-08-10T18:11:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-06T00:33:13.000Z", "max_issues_repo_path": "src/ompl/base/spaces/src/ReedsSheppStateSpace.cpp", "max_issues_repo_name": "ivaROS/ivaOmplCore", "max_issues_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ompl/base/spaces/src/ReedsSheppStateSpace.cpp", "max_forks_repo_name": "ivaROS/ivaOmplCore", "max_forks_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-16T14:01:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T09:46:59.000Z", "avg_line_length": 39.9714673913, "max_line_length": 141, "alphanum_fraction": 0.5167068901, "num_tokens": 9366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.746138993030751, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.4021563975443797}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_CBRT_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_CBRT_HPP_INCLUDED\n#include <boost/simd/detail/overload.hpp>\n\n#include <boost/simd/meta/hierarchy/simd.hpp>\n#include <boost/simd/constant/one.hpp>\n#include <boost/simd/constant/third.hpp>\n#include <boost/simd/constant/three.hpp>\n#include <boost/simd/constant/two.hpp>\n#include <boost/simd/constant/constant.hpp>\n#include <boost/simd/function/abs.hpp>\n#include <boost/simd/function/bitofsign.hpp>\n#include <boost/simd/function/bitwise_or.hpp>\n#include <boost/simd/function/divides.hpp>\n#include <boost/simd/function/frexp.hpp>\n#include <boost/simd/function/ldexp.hpp>\n#include <boost/simd/function/horn.hpp>\n#include <boost/simd/function/fast.hpp>\n#include <boost/simd/function/if_else.hpp>\n#include <boost/simd/function/is_equal.hpp>\n#include <boost/simd/function/is_eqz.hpp>\n#include <boost/simd/function/is_gez.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/function/negate.hpp>\n#include <boost/simd/function/sqr.hpp>\n#include <boost/simd/detail/dispatch/meta/as_integer.hpp>\n#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>\n\n#ifndef BOOST_SIMD_NO_DENORMALS\n#include <boost/simd/constant/smallestposval.hpp>\n#include <boost/simd/constant/twotomnmbo_3.hpp>\n#include <boost/simd/constant/twotonmb.hpp>\n#include <boost/simd/function/is_less.hpp>\n#endif\n\n#ifndef BOOST_SIMD_NO_INFINITIES\n#include <boost/simd/function/is_inf.hpp>\n#include <boost/simd/function/logical_or.hpp>\n#endif\n\nnamespace boost { namespace simd { namespace ext\n{\n   namespace bd = boost::dispatch;\n   namespace bs = boost::simd;\n   BOOST_DISPATCH_OVERLOAD_IF(cbrt_\n                          , (typename A0,typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::single_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()(const A0& a0 ) const BOOST_NOEXCEPT\n      {\n        A0 z =  bs::abs(a0);\n        using int_type =  bd::as_integer_t<A0, signed>;\n  #ifndef BOOST_SIMD_NO_DENORMALS\n        auto denormal = is_less(z, Smallestposval<A0>());\n        z = if_else(denormal, z*Twotonmb<A0>(), z);\n        A0 f = if_else(denormal, Twotomnmbo_3<A0>(), One<A0>());\n  #endif\n        const A0 CBRT2  = Constant< A0, 0x3fa14518> ();\n        const A0 CBRT4  = Constant< A0, 0x3fcb2ff5> ();\n        const A0 CBRT2I = Constant< A0, 0x3f4b2ff5> ();\n        const A0 CBRT4I = Constant< A0, 0x3f214518> ();\n        int_type e;\n        A0 x; std::tie(x, e) = fast_(frexp)(z);\n        x = horn <A0,\n          0x3ece0609,\n          0x3f91eb77,\n          0xbf745265,\n          0x3f0bf0fe,\n          0xbe09e49a\n          > (x);\n        auto flag = is_gez(e);\n        int_type e1 =  bs::abs(e);\n        int_type rem = e1;\n        e1 /= Three<int_type>();\n        rem -= e1*Three<int_type>();\n        e = negate(e1, e);\n        const A0 cbrt2 = if_else(flag, CBRT2, CBRT2I);\n        const A0 cbrt4 = if_else(flag, CBRT4, CBRT4I);\n        A0 fact = if_else(is_equal(rem, One<int_type>()), cbrt2, One<A0>());\n        fact = if_else(is_equal(rem, Two<int_type>()), cbrt4, fact);\n        x = fast_(ldexp)(x*fact, e);\n        x -= (x-z/sqr(x))*Third<A0>();\n  #ifndef BOOST_SIMD_NO_DENORMALS\n        x = bitwise_or(x, bitofsign(a0))*f;\n  #else\n        x = bitwise_or(x, bitofsign(a0));\n  #endif\n  #ifndef BOOST_SIMD_NO_INFINITIES\n        return if_else(logical_or(is_eqz(a0),is_inf(a0)), a0, x);\n  #else\n        return if_else(is_eqz(a0), a0, x);\n  #endif\n      }\n   };\n\n\n   BOOST_DISPATCH_OVERLOAD_IF(cbrt_\n                          , (typename A0,typename X)\n                          , (detail::is_native<X>)\n                          , bd::cpu_\n                          , bs::pack_<bd::double_<A0>, X>\n                          )\n   {\n      BOOST_FORCEINLINE A0 operator()(const A0& a0 ) const BOOST_NOEXCEPT\n      {\n        using int_type =  bd::as_integer_t<A0, signed>;\n        A0 z =  bs::abs(a0);\n     #ifndef BOOST_SIMD_NO_DENORMALS\n        auto denormal = is_less(z, Smallestposval<A0>());\n        z = if_else(denormal, z*Twotonmb<A0>(), z);\n        A0 f = if_else(denormal, Twotomnmbo_3<A0>(), One<A0>());\n     #endif\n        const A0 CBRT2  = Constant< A0, 0x3ff428a2f98d728bll> ();\n        const A0 CBRT4  = Constant< A0, 0x3ff965fea53d6e3dll> ();\n        const A0 CBRT2I = Constant< A0, 0x3fe965fea53d6e3dll> ();\n        const A0 CBRT4I = Constant< A0, 0x3fe428a2f98d728bll> ();\n        int_type e;\n        A0 x;\n        std::tie(x, e) = fast_(frexp)(z);\n        x = horn <A0,\n          0x3fd9c0c12122a4fell,\n          0x3ff23d6ee505873all,\n          0xbfee8a4ca3ba37b8ll,\n          0x3fe17e1fc7e59d58ll,\n          0xbfc13c93386fdff6ll >  (x);\n        auto flag = is_gez(e);\n        int_type e1 =  bs::abs(e);\n        int_type rem = e1;\n        e1 /= Three<int_type>();\n        rem -= e1*Three<int_type>();\n        e =  negate(e1, e);\n        const A0 cbrt2 = if_else(flag, CBRT2, CBRT2I);\n        const A0 cbrt4 = if_else(flag, CBRT4, CBRT4I);\n        A0 fact = if_else(is_equal(rem, One<int_type>()), cbrt2, One<A0>());\n        fact = if_else(is_equal(rem, Two<int_type>()), cbrt4, fact);\n        x = fast_(ldexp)(x*fact, e);\n        x -= (x-z/sqr(x))*Third<A0>();\n        x -= (x-z/sqr(x))*Third<A0>(); //two newton passes\n      #ifndef BOOST_SIMD_NO_DENORMALS\n        x = bitwise_or(x, bitofsign(a0))*f;\n      #else\n        x = bitwise_or(x, bitofsign(a0));\n      #endif\n      #ifndef BOOST_SIMD_NO_INFINITIES\n        return if_else(logical_or(is_eqz(a0),is_inf(a0)), a0, x);\n      #else\n        return if_else(is_eqz(a0), a0, x);\n      #endif\n    }\n   };\n\n\n}\n\n} }\n\n#endif\n", "meta": {"hexsha": "221d90550f2e11202798596d5c9a401ecf960033", "size": 6122, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/simd/function/cbrt.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/simd/function/cbrt.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/simd/function/cbrt.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 35.5930232558, "max_line_length": 100, "alphanum_fraction": 0.5913100294, "num_tokens": 1847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.4021136542562989}}
{"text": "#define DEBUG 1\n/**\n * File    : C.cpp\n * Author  : Kazune Takahashi\n * Created : 12/29/2019, 11:12:55 AM\n * Powered by Visual Studio Code\n */\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <functional>\n#include <random>\n#include <chrono>\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n// ----- boost -----\n#include <boost/rational.hpp>\n// ----- using directives and manipulations -----\nusing boost::rational;\nusing namespace std;\nusing ll = long long;\n// ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n// constexpr ll MOD{998244353LL}; // be careful\nconstexpr ll MAX_SIZE{3000010LL};\n// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed\n// ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n  if (left < right)\n  {\n    left = right;\n  }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n  if (left > right)\n  {\n    left = right;\n  }\n}\n// ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n  ll x;\n  Mint() : x{0LL} {}\n  Mint(ll x) : x{x % MOD} {}\n  Mint operator-() const { return x ? MOD - x : 0; }\n  Mint &operator+=(const Mint &a)\n  {\n    if ((x += a.x) >= MOD)\n    {\n      x -= MOD;\n    }\n    return *this;\n  }\n  Mint &operator-=(const Mint &a) { return *this += -a; }\n  Mint &operator*=(const Mint &a)\n  {\n    (x *= a.x) %= MOD;\n    return *this;\n  }\n  Mint &operator/=(const Mint &a)\n  {\n    Mint b{a};\n    return *this *= b.power(MOD - 2);\n  }\n  Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }\n  bool operator<(const Mint &a) const { return x < a.x; }\n  bool operator<=(const Mint &a) const { return x <= a.x; }\n  bool operator>(const Mint &a) const { return x > a.x; }\n  bool operator>=(const Mint &a) const { return x >= a.x; }\n  bool operator==(const Mint &a) const { return x == a.x; }\n  bool operator!=(const Mint &a) const { return !(*this == a); }\n  const Mint power(ll N)\n  {\n    if (N == 0)\n    {\n      return 1;\n    }\n    else if (N % 2 == 1)\n    {\n      return *this * power(N - 1);\n    }\n    else\n    {\n      Mint half = power(N / 2);\n      return half * half;\n    }\n  }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n  return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n  return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)\n{\n  return Mint<MOD>{lhs} / rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n  return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n  return stream << a.x;\n}\n// ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n  vector<Mint<MOD>> inv, fact, factinv;\n  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n  {\n    inv[1] = 1;\n    for (auto i = 2LL; i < MAX_SIZE; i++)\n    {\n      inv[i] = (-inv[MOD % i]) * (MOD / i);\n    }\n    fact[0] = factinv[0] = 1;\n    for (auto i = 1LL; i < MAX_SIZE; i++)\n    {\n      fact[i] = Mint<MOD>(i) * fact[i - 1];\n      factinv[i] = inv[i] * factinv[i - 1];\n    }\n  }\n  Mint<MOD> operator()(int n, int k)\n  {\n    if (n >= 0 && k >= 0 && n - k >= 0)\n    {\n      return fact[n] * factinv[k] * factinv[n - k];\n    }\n    return 0;\n  }\n  Mint<MOD> catalan(int x, int y)\n  {\n    return (*this)(x + y, y) - (*this)(x + y, y - 1);\n  }\n};\n// ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n// ----- frequently used constexpr -----\n// constexpr double epsilon{1e-10};\n// constexpr ll infty{1000000000000000LL};\n// constexpr int dx[4] = {1, 0, -1, 0};\n// constexpr int dy[4] = {0, 1, 0, -1};\n// ----- Yes() and No() -----\nvoid Yes()\n{\n  cout << \"Yes\" << endl;\n  exit(0);\n}\nvoid No()\n{\n  cout << \"No\" << endl;\n  exit(0);\n}\n// ----- main() -----\n\nclass Domino\n{\n  using board = vector<string>;\n  using point = tuple<int, int>;\n  vector<board> seed;\n\n  int N;\n  board answer;\n\npublic:\n  Domino(int N) : N{N}\n  {\n    init_seed();\n    stringstream SS;\n    for (auto i = 0; i < N; i++)\n    {\n      SS << '.';\n    }\n    answer = board(N, SS.str());\n  }\n\n  void flush()\n  {\n    if (N == 2)\n    {\n      cout << \"-1\" << endl;\n      return;\n    }\n    make_ans();\n    assert(static_cast<int>(answer.size()) == N);\n    for (auto i = 0; i < N; i++)\n    {\n      assert(static_cast<int>(answer[i].size()) == N);\n      cout << answer[i] << endl;\n    }\n  }\n\n  void init_seed()\n  {\n    seed.resize(8);\n    seed[3] = {\n        \"aa.\",\n        \"..a\",\n        \"..a\"};\n    seed[4] = {\n        \"aabc\",\n        \"ddbc\",\n        \"bcaa\",\n        \"bcdd\"};\n    seed[5] = {\n        \"aabba\",\n        \"bcc.a\",\n        \"b..cb\",\n        \"a..cb\",\n        \"abbaa\"};\n    seed[6] = {\n        \"aabc..\",\n        \"ddbc..\",\n        \"..aabc\",\n        \"..ddbc\",\n        \"bc..aa\",\n        \"bc..dd\"};\n    seed[7] = {\n        \"aabbcc.\",\n        \"dd.dd.a\",\n        \"..d..da\",\n        \"..d..db\",\n        \"dd.dd.b\",\n        \"..d..dc\",\n        \"..d..dc\"};\n  }\n\nprivate:\n  void make_ans()\n  {\n    if (N == 3)\n    {\n      answer = seed[3];\n      return;\n    }\n    int S{N % 4 + 4};\n    int x{(N - S) / 4};\n    for (auto k = 0; k < x; k++)\n    {\n      for (auto i = k * 4; i < (k + 1) * 4; i++)\n      {\n        for (auto j = k * 4; j < (k + 1) * 4; j++)\n        {\n          answer[i][j] = seed[4][i % 4][j % 4];\n        }\n      }\n    }\n    for (auto i = x * 4; i < N; i++)\n    {\n      for (auto j = x * 4; j < N; j++)\n      {\n        answer[i][j] = seed[S][i - x * 4][j - x * 4];\n      }\n    }\n  }\n};\n\nint main()\n{\n  int N;\n  cin >> N;\n  Domino domino{N};\n  domino.flush();\n}\n", "meta": {"hexsha": "c3de8636f35da395f99ccc9194908bc748d07eb6", "size": 6194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/1228_AGC041/C.cpp", "max_stars_repo_name": "kazunetakahashi/atcoder", "max_stars_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-03-24T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-17T21:16:36.000Z", "max_issues_repo_path": "2019/1228_AGC041/C.cpp", "max_issues_repo_name": "kazunetakahashi/atcoder", "max_issues_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2019/1228_AGC041/C.cpp", "max_forks_repo_name": "kazunetakahashi/atcoder", "max_forks_repo_head_hexsha": "16ce65829ccc180260b19316e276c2fcf6606c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-22T17:27:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-22T17:27:09.000Z", "avg_line_length": 20.1758957655, "max_line_length": 66, "alphanum_fraction": 0.5075879884, "num_tokens": 2021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.40196026074814656}}
{"text": "/*\n * LiquidSampler.cpp\n *\n *  Created on: Apr 18, 2012\n *      Author: selman.joe@gmail.com\n */\n\n\n#include <cstdlib>\n#include <vector>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/bernoulli_distribution.hpp>\n\n#include \"LiquidSampler.h\"\n#include \"../SpanInterval.h\"\n#include \"../SISet.h\"\n\nstd::vector<SpanInterval> LiquidSampler::operator ()(const SpanInterval& si, double p, boost::mt19937& rng) const {\n    std::vector<SpanInterval> sampled;\n\n    if (p <= 0.0) return sampled;\n    if (p >= 1.0) {\n        sampled.push_back(si);\n        return sampled;\n    }\n\n    if (si.isEmpty()) return sampled;\n\n\n    // loop over intervals ranging from the width of si, down to 1\n    std::list<Interval> toSample;\n    toSample.push_front(Interval(si.start().start(), si.finish().finish()));\n    do {\n        Interval curInterval = toSample.front();\n        toSample.pop_front();\n        //bool sampleCurInterval = ((double)rand() / (double)RAND_MAX) <= p;\n        boost::bernoulli_distribution<double> flip(p);\n        bool sampleCurInterval = flip(rng);\n        if (sampleCurInterval) {\n            sampled.push_back(SpanInterval(curInterval));\n            // now make sure none of our intervals overlap the sampled interval\n            for (std::list<Interval>::iterator it = toSample.begin();\n                    it != toSample.end();) {\n                if (intersection(curInterval, *it)) {\n                    std::vector<Interval> subtracted = it->subtract(curInterval);\n                    // put what we just processed in there and erase it\n                    for (std::vector<Interval>::const_iterator it2 = subtracted.begin();\n                            it2 != subtracted.end();\n                            it2++) {\n                        toSample.insert(it, *it2);\n                    }\n                    it = toSample.erase(it);\n                } else {\n                    it++;\n                }\n            }\n        } else {\n            // didn't sample, so lets put the smaller size of intervals next in to sample\n            if (curInterval.size() != 1) {\n                Interval left = Interval(curInterval.start(), curInterval.finish()-1);\n                Interval right = Interval(curInterval.start()+1, curInterval.finish());\n                toSample.push_front(right);\n                toSample.push_front(left);\n            }\n        }\n    } while (!toSample.empty());\n\n    return sampled;\n}\n", "meta": {"hexsha": "cabefa2df3388782cc755e6e6d70ec48cd7053dd", "size": 2432, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/inference/LiquidSampler.cpp", "max_stars_repo_name": "JunLi-Galios/repel", "max_stars_repo_head_hexsha": "e4e7f4ffc95f8d65dd478861080c9c77bab9b797", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/inference/LiquidSampler.cpp", "max_issues_repo_name": "JunLi-Galios/repel", "max_issues_repo_head_hexsha": "e4e7f4ffc95f8d65dd478861080c9c77bab9b797", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inference/LiquidSampler.cpp", "max_forks_repo_name": "JunLi-Galios/repel", "max_forks_repo_head_hexsha": "e4e7f4ffc95f8d65dd478861080c9c77bab9b797", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7428571429, "max_line_length": 115, "alphanum_fraction": 0.5575657895, "num_tokens": 527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.588889130767832, "lm_q1q2_score": 0.40196024553790644}}
{"text": "#include \"VDBVolume.h\"\n\n// OpenVDB\n#include <openvdb/Types.h>\n#include <openvdb/math/DDA.h>\n#include <openvdb/math/Ray.h>\n#include <openvdb/openvdb.h>\n\n#include <Eigen/Core>\n#include <algorithm>\n#include <cmath>\n#include <functional>\n#include <iostream>\n#include <memory>\n#include <vector>\n\nnamespace {\n\nfloat ComputeSDF(const Eigen::Vector3d& origin,\n                 const Eigen::Vector3d& point,\n                 const Eigen::Vector3d& voxel_center) {\n    const Eigen::Vector3d v_voxel_origin = voxel_center - origin;\n    const Eigen::Vector3d v_point_voxel = point - voxel_center;\n    const double dist = v_point_voxel.norm();\n    const double proj = v_voxel_origin.dot(v_point_voxel);\n    const double sign = proj / std::abs(proj);\n    return static_cast<float>(sign * dist);\n}\n\nEigen::Vector3d GetVoxelCenter(const openvdb::Coord& voxel, const openvdb::math::Transform& xform) {\n    const float voxel_size = xform.voxelSize()[0];\n    openvdb::math::Vec3d v_wf = xform.indexToWorld(voxel) + voxel_size / 2.0;\n    return Eigen::Vector3d(v_wf.x(), v_wf.y(), v_wf.z());\n}\n\n}  // namespace\n\nnamespace vdbfusion {\n\nVDBVolume::VDBVolume(float voxel_size, float sdf_trunc, bool space_carving /* = false*/)\n    : voxel_size_(voxel_size), sdf_trunc_(sdf_trunc), space_carving_(space_carving) {\n    tsdf_ = openvdb::FloatGrid::create(sdf_trunc_);\n    tsdf_->setName(\"D(x): signed distance grid\");\n    tsdf_->setTransform(openvdb::math::Transform::createLinearTransform(voxel_size_));\n    tsdf_->setGridClass(openvdb::GRID_LEVEL_SET);\n\n    weights_ = openvdb::FloatGrid::create(0.0f);\n    weights_->setName(\"W(x): weights grid\");\n    weights_->setTransform(openvdb::math::Transform::createLinearTransform(voxel_size_));\n    weights_->setGridClass(openvdb::GRID_UNKNOWN);\n}\n\nvoid VDBVolume::UpdateTSDF(const float& sdf,\n                           const openvdb::Coord& voxel,\n                           const std::function<float(float)>& weighting_function) {\n    using AccessorRW = openvdb::tree::ValueAccessorRW<openvdb::FloatTree>;\n    if (sdf > -sdf_trunc_) {\n        AccessorRW tsdf_acc = AccessorRW(tsdf_->tree());\n        AccessorRW weights_acc = AccessorRW(weights_->tree());\n        const float tsdf = std::min(sdf_trunc_, sdf);\n        const float weight = weighting_function(sdf);\n        const float last_weight = weights_acc.getValue(voxel);\n        const float last_tsdf = tsdf_acc.getValue(voxel);\n        const float new_weight = weight + last_weight;\n        const float new_tsdf = (last_tsdf * last_weight + tsdf * weight) / (new_weight);\n        tsdf_acc.setValue(voxel, new_tsdf);\n        weights_acc.setValue(voxel, new_weight);\n    }\n}\n\nvoid VDBVolume::Integrate(openvdb::FloatGrid::Ptr grid,\n                          const std::function<float(float)>& weighting_function) {\n    for (auto iter = grid->cbeginValueOn(); iter.test(); ++iter) {\n        const auto& sdf = iter.getValue();\n        const auto& voxel = iter.getCoord();\n        this->UpdateTSDF(sdf, voxel, weighting_function);\n    }\n}\n\nvoid VDBVolume::Integrate(const std::vector<Eigen::Vector3d>& points,\n                          const Eigen::Vector3d& origin,\n                          const std::function<float(float)>& weighting_function) {\n    if (points.empty()) {\n        std::cerr << \"PointCloud provided is empty\\n\";\n        return;\n    }\n\n    // Get some variables that are common to all rays\n    const openvdb::math::Transform& xform = tsdf_->transform();\n    const openvdb::Vec3R eye(origin.x(), origin.y(), origin.z());\n\n    // Get the \"unsafe\" version of the grid acessors\n    auto tsdf_acc = tsdf_->getUnsafeAccessor();\n    auto weights_acc = weights_->getUnsafeAccessor();\n\n    // Launch an for_each execution, use std::execution::par to parallelize this region\n    std::for_each(points.cbegin(), points.cend(), [&](const auto& point) {\n        // Get the direction from the sensor origin to the point and normalize it\n        const Eigen::Vector3d direction = point - origin;\n        openvdb::Vec3R dir(direction.x(), direction.y(), direction.z());\n        dir.normalize();\n\n        // Truncate the Ray before and after the source unless space_carving_ is specified.\n        const auto depth = static_cast<float>(direction.norm());\n        const float t0 = space_carving_ ? 0.0f : depth - sdf_trunc_;\n        const float t1 = depth + sdf_trunc_;\n\n        // Create one DDA per ray(per thread), the ray must operate on voxel grid coordinates.\n        const auto ray = openvdb::math::Ray<float>(eye, dir, t0, t1).worldToIndex(*tsdf_);\n        openvdb::math::DDA<decltype(ray)> dda(ray);\n        do {\n            const auto voxel = dda.voxel();\n            const auto voxel_center = GetVoxelCenter(voxel, xform);\n            const auto sdf = ComputeSDF(origin, point, voxel_center);\n            if (sdf > -sdf_trunc_) {\n                const float tsdf = std::min(sdf_trunc_, sdf);\n                const float weight = weighting_function(sdf);\n                const float last_weight = weights_acc.getValue(voxel);\n                const float last_tsdf = tsdf_acc.getValue(voxel);\n                const float new_weight = weight + last_weight;\n                const float new_tsdf = (last_tsdf * last_weight + tsdf * weight) / (new_weight);\n                tsdf_acc.setValue(voxel, new_tsdf);\n                weights_acc.setValue(voxel, new_weight);\n            }\n        } while (dda.step());\n    });\n}\n\nopenvdb::FloatGrid::Ptr VDBVolume::Prune(float min_weight) const {\n    const auto weights = weights_->tree();\n    const auto tsdf = tsdf_->tree();\n    const auto background = sdf_trunc_;\n    openvdb::FloatGrid::Ptr clean_tsdf = openvdb::FloatGrid::create(sdf_trunc_);\n    clean_tsdf->setName(\"D(x): Pruned signed distance grid\");\n    clean_tsdf->setTransform(openvdb::math::Transform::createLinearTransform(voxel_size_));\n    clean_tsdf->setGridClass(openvdb::GRID_LEVEL_SET);\n    clean_tsdf->tree().combine2Extended(tsdf, weights, [=](openvdb::CombineArgs<float>& args) {\n        if (args.aIsActive() && args.b() > min_weight) {\n            args.setResult(args.a());\n            args.setResultIsActive(true);\n        } else {\n            args.setResult(background);\n            args.setResultIsActive(false);\n        }\n    });\n    return clean_tsdf;\n}\n}  // namespace vdbfusion\n", "meta": {"hexsha": "d2b75cb6a09d76efa39bc21ea07de84902c466f9", "size": 6276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vdbfusion/vdbfusion/VDBVolume.cpp", "max_stars_repo_name": "saurabh1002/vdbfusion", "max_stars_repo_head_hexsha": "e5c010931ea08eeb852854092057cf65f0f8bc7a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 119.0, "max_stars_repo_stars_event_min_datetime": "2022-02-08T15:25:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:16:35.000Z", "max_issues_repo_path": "src/vdbfusion/vdbfusion/VDBVolume.cpp", "max_issues_repo_name": "saurabh1002/vdbfusion", "max_issues_repo_head_hexsha": "e5c010931ea08eeb852854092057cf65f0f8bc7a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2022-02-09T07:54:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T03:12:47.000Z", "max_forks_repo_path": "src/vdbfusion/vdbfusion/VDBVolume.cpp", "max_forks_repo_name": "saurabh1002/vdbfusion", "max_forks_repo_head_hexsha": "e5c010931ea08eeb852854092057cf65f0f8bc7a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T15:33:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:47:27.000Z", "avg_line_length": 42.1208053691, "max_line_length": 100, "alphanum_fraction": 0.6520076482, "num_tokens": 1575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.40191915906775744}}
{"text": "/**\n * @file max_coverage_example.cpp\n * @brief\n * @author Piotr Smulewicz\n * @version 1.0\n * @date 2014-03-13\n */\n//! [Max Coverage Example]\n#include <iostream>\n#include <vector>\n#include <iterator>\n\n#include <boost/range/irange.hpp>\n\n#include \"paal/greedy/set_cover/maximum_coverage.hpp\"\n\nint main() {\n    std::vector<std::vector<int>> set_to_elements = {\n        { 1, 2 },\n        { 3, 4, 5, 6 },\n        { 7, 8, 9, 10, 11, 12, 13, 0 },\n        { 1, 3, 5, 7, 9, 11, 13 },\n        { 2, 4, 6, 8, 10, 12, 0 }\n    };\n    const int NUMBER_OF_SETS_TO_SELECT = 2;\n    auto sets = boost::irange(0, 5);\n    using SetIterator = decltype(sets)::iterator;\n    std::vector<int> result;\n    auto element_index = [](int el){return el;};\n    auto covered = paal::greedy::maximum_coverage(\n        sets,\n        [&](int set){return set_to_elements[set];},\n        back_inserter(result),\n        element_index,\n        NUMBER_OF_SETS_TO_SELECT);\n    std::cout << \"Covered: \" << covered << std::endl;\n}\n//! [Max Coverage Example]\n", "meta": {"hexsha": "30e4914c079694ad13447177c7475e39dd6bcdc3", "size": 1014, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/greedy/max_coverage_example.cpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/greedy/max_coverage_example.cpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/greedy/max_coverage_example.cpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 26.0, "max_line_length": 53, "alphanum_fraction": 0.5867850099, "num_tokens": 329, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702642896702, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.40191915247668125}}
{"text": "/*\n * This file is part of the Interpolated Polyline (https://github.com/fzi-forschungszentrum-informatik/P3IV),\n * copyright by FZI Forschungszentrum Informatik, licensed under the BSD-3 license (see LICENSE file in main directory)\n */\n\n#pragma once\n#include <iostream>\n#include <Eigen/Core>\n#include \"sequence_distribution.hpp\"\n\nnamespace util_probability {\n\n\ntemplate <typename T>\nstruct TruncatedUnivariateNormalDistributionSequence : public UnivariateNormalDistributionSequence<T> {\n\n    TruncatedUnivariateNormalDistributionSequence() = default;\n\n    using Mean = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n    using Variance = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n    using Truncation = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\n    // todo: check to pass (const std::vector<T> mean_ ...)\n    TruncatedUnivariateNormalDistributionSequence(std::vector<T> mean_,\n                                                  std::vector<T> variance_,\n                                                  std::vector<T> upper_bound_,\n                                                  std::vector<T> lower_bound_) {\n\n        assert(mean_.size() == variance_.size());\n\n        this->_mean = Eigen::Map<Mean>(mean_.data(), mean_.size(), 1);\n        this->_covariance = Eigen::Map<Variance>(variance_.data(), variance_.size(), 1);\n        this->_upper_truncation = Eigen::Map<Truncation>(upper_bound_.data(), upper_bound_.size(), 1);\n        this->_lower_truncation = Eigen::Map<Truncation>(lower_bound_.data(), lower_bound_.size(), 1);\n    }\n\n    // todo: replace with range()\n    std::vector<T> upperBound(const T sigma) const {\n\n        std::vector<double> upper_bound;\n        upper_bound.resize(this->_mean.size());\n\n        for (size_t i = 0; i < upper_bound.size(); i++) {\n            upper_bound[i] = std::min(_upper_truncation(i, 0), this->_mean(i, 0) + this->_covariance(i, 0) * sigma);\n        }\n        return upper_bound;\n    }\n\n    std::vector<T> lowerBound(const T sigma) const {\n\n        std::vector<double> lower_bound;\n        lower_bound.resize(this->_mean.size());\n\n        for (size_t i = 0; i < lower_bound.size(); i++) {\n            lower_bound[i] = std::max(_lower_truncation(i, 0), this->_mean(i, 0) - this->_covariance(i, 0) * sigma);\n        }\n        return lower_bound;\n    }\n\nprotected:\n    Truncation _upper_truncation;\n    Truncation _lower_truncation;\n};\n\n} // namespace util_probability\n", "meta": {"hexsha": "9bd018f64af239aec865d289096e678eca6ff5f1", "size": 2396, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "p3iv_utils_probability/include/p3iv_utils_probability/truncated_distribution.hpp", "max_stars_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_stars_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T06:56:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T11:21:30.000Z", "max_issues_repo_path": "p3iv_utils_probability/include/p3iv_utils_probability/truncated_distribution.hpp", "max_issues_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_issues_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "p3iv_utils_probability/include/p3iv_utils_probability/truncated_distribution.hpp", "max_forks_repo_name": "fzi-forschungszentrum-informatik/P3IV", "max_forks_repo_head_hexsha": "51784e6dc03dcaa0ad58a5078475fa4daec774bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-10T01:56:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-10T01:56:44.000Z", "avg_line_length": 36.303030303, "max_line_length": 119, "alphanum_fraction": 0.6285475793, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.40191915247668114}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_REMCEIL_HPP_INCLUDED\n#define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_REMCEIL_HPP_INCLUDED\n\n#include <boost/simd/function/div.hpp>\n#include <boost/simd/function/ceil.hpp>\n#include <boost/simd/function/is_nez.hpp>\n#include <boost/simd/function/fnms.hpp>\n#include <boost/simd/function/minus.hpp>\n#include <boost/simd/function/multiplies.hpp>\n#include <boost/simd/detail/dispatch/function/overload.hpp>\n#include <boost/config.hpp>\n/////////////////////////////////////////////////////////////////////////////\n// The remceil() function computes the remceil of dividing x by y.  The\n// return value is x-n*y, where n is the value x / y, rounded toward +infinity\n/////////////////////////////////////////////////////////////////////////////\nnamespace boost { namespace simd { namespace ext\n{\n  namespace bd = boost::dispatch;\n  BOOST_DISPATCH_OVERLOAD ( rem_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::tag::ceil_\n                          , bd::scalar_< bd::int_<A0> >\n                          , bd::scalar_< bd::int_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (bd::functor<bs::tag::ceil_> const&\n                                    , A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      if (is_nez(a1))\n        return fnms(div(ceil, a0, a1), a1, a0);\n      else\n        return a0;\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( rem_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::fast_tag\n                          , bs::tag::ceil_\n                          , bd::scalar_< bd::int_<A0> >\n                          , bd::scalar_< bd::int_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const fast_tag &\n                                    , bd::functor<bs::tag::ceil_> const&\n                                    , A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      return fnms(div(ceil, a0, a1), a1, a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( rem_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::fast_tag\n                          , bs::tag::ceil_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() (const fast_tag &\n                                    , bd::functor<bs::tag::ceil_> const&\n                                    , A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      return  fnms(div(ceil, a0,a1), a1, a0);\n    }\n  };\n\n  BOOST_DISPATCH_OVERLOAD ( rem_\n                          , (typename A0)\n                          , bd::cpu_\n                          , bs::tag::ceil_\n                          , bd::scalar_< bd::floating_<A0> >\n                          , bd::scalar_< bd::floating_<A0> >\n                          )\n  {\n    BOOST_FORCEINLINE A0 operator() ( bd::functor<bs::tag::ceil_> const&\n                                    , A0 a0, A0 a1) const BOOST_NOEXCEPT\n    {\n      if (is_nez(a1)&&is_eqz(a0)) return a0;\n      return fnms(div(ceil, a0, a1), a1, a0);\n    }\n  };\n\n} } }\n\n\n#endif\n\n", "meta": {"hexsha": "ba233d033b012a263fbe0bcf3ec39ea7c1556305", "size": 3617, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arch/common/scalar/function/remceil.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/arch/common/scalar/function/remceil.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arch/common/scalar/function/remceil.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 35.4607843137, "max_line_length": 100, "alphanum_fraction": 0.4373790434, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.4019127070692996}}
{"text": "/*******************************************************************************\n *         Copyright 2003-2012 LASMEA UMR 6602 CNRS/U.B.P\n *         Copyright 2009-2012 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n *\n *          Distributed under the Boost Software License, Version 1.0.\n *                 See accompanying file LICENSE.txt or copy at\n *                     http://www.boost.org/LICENSE_1_0.txt\n ******************************************************************************/\n#ifndef NT2_TOOLBOX_LINALG_FUNCTIONS_MPOWER_HPP_INCLUDED\n#define NT2_TOOLBOX_LINALG_FUNCTIONS_MPOWER_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <nt2/core/container/dsl/size.hpp>\n#include <nt2/core/container/dsl/value_type.hpp>\n#include <nt2/sdk/meta/value_as.hpp>\n#include <nt2/core/utility/max_extent.hpp>\n#include <nt2/sdk/meta/tieable_hierarchy.hpp>\n#include <nt2/sdk/complex/meta/is_complex.hpp>\n#include <nt2/include/functions/isscalar.hpp>\n#include <nt2/include/functions/issquare.hpp>\n#include <nt2/include/functions/extent.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/assert.hpp>\n\nnamespace nt2\n{\n  namespace tag\n  {\n    /*!\n     * \\brief Define the tag mpower_ of functor mpower\n     *        in namespace nt2::tag for toolbox algebra\n     **/\n    struct mpower_ :  ext::tieable_<mpower_>\n    {\n      typedef ext::tieable_<mpower_>  parent;\n    };\n  }\n  /**\n   * @brief compute matricial power a0^a1\n   *\n   * a0 or a1 can be a square matricial expression,  but one of the two must be scalar\n   *\n   * @param  a0  Matrix expression or scalar\n   * @param  a1  Scalar or matrix expression\n   *\n   * @return a matrix containing a0^a1\n   **/\n\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::mpower_, mpower, 2)\n\n}\n\nnamespace nt2 { namespace ext\n{\n  template<class Domain, int N, class Expr>\n  struct  size_of<tag::mpower_,Domain,N,Expr>\n  {\n    typedef typename boost::proto::result_of::child_c<Expr&,0>::value_type  c0_t;\n    typedef typename boost::proto::result_of::child_c<Expr&,1>::value_type  c1_t;\n    typedef typename c0_t::extent_type                                     ex0_t;\n    typedef typename c1_t::extent_type                                     ex1_t;\n    typedef typename utility::result_of::max_extent<ex0_t, ex1_t>::type         result_type;\n    BOOST_FORCEINLINE result_type operator()(Expr& e) const\n    {\n      BOOST_ASSERT_MSG((isscalar( boost::proto::child_c<0>(e))&&issquare(boost::proto::child_c<1>(e)))||\n                       (isscalar( boost::proto::child_c<1>(e))&&issquare(boost::proto::child_c<0>(e))),\n                       \"mpower needs a square matrix expression and a scalar or a scalar and a square matrix expression\");\n\n      return nt2::utility::max_extent(nt2::extent(boost::proto::child_c<0>(e)),  nt2::extent(boost::proto::child_c<1>(e)));\n    }\n  };\n\n  template<class Domain, int N, class Expr>\n  struct  value_type<tag::mpower_,Domain,N,Expr>\n        : meta::value_as<Expr,0>\n  {\n    typedef typename  boost::proto::result_of::child_c<Expr&,0>::value_type::value_type v0_t;\n    typedef typename  boost::proto::result_of::child_c<Expr&,1>::value_type::value_type v1_t;\n    typedef typename  meta::is_complex<v0_t>::type                                  iscplx_0;\n    typedef typename  meta::is_complex<v1_t>::type                                  iscplx_1;\n    typedef typename  boost::mpl::if_<iscplx_0, v0_t, v1_t>::type                       t0_t;\n    typedef typename  boost::mpl::if_<iscplx_1, v1_t, t0_t>::type                       type;\n  };\n} }\n\n#endif\n\n", "meta": {"hexsha": "41d3c04b474b3a059f5147034c81e830cdf02067", "size": 3519, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/toolbox/linalg/functions/mpower.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/linalg/include/nt2/toolbox/linalg/functions/mpower.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/linalg/include/nt2/toolbox/linalg/functions/mpower.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9886363636, "max_line_length": 123, "alphanum_fraction": 0.6203466894, "num_tokens": 903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.401862626938958}}
{"text": "/*\n * Copyright (c) 2013-2015 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef ODE_NV_HPP\n#define ODE_NV_HPP\n\n// ODE (not verified)\n\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <kv/psa.hpp>\n#include <kv/ode-param.hpp>\n\n\n#ifndef ODE_FAST\n#define ODE_FAST 1\n#endif\n\n\nnamespace kv{\n\nnamespace ub = boost::numeric::ublas;\n\ntemplate <class T, class F>\nvoid\node_nv(F f, ub::vector<T>& init, const T& start, T& end, ode_param<T> p = ode_param<T>()) {\n\tint n = init.size();\n\tint i, j;\n\n\tub::vector< psa<T> > x, y;\n\tpsa<T> torg;\n\tpsa<T> t;\n\n\tT deltat;\n\tub::vector<T> result;\n\n\tT m;\n\n\tT radius, radius_tmp;\n\tT tolerance;\n\tint n_rad;\n\n\tbool save_mode, save_uh, save_rh;\n\n\tm = 1.;\n\tfor (i=0; i<n; i++) {\n\t\tusing std::abs;\n\t\tm = std::max(m, abs(init(i)));\n\t}\n\ttolerance = m * p.epsilon;\n\n\tx = init;\n\ttorg.v.resize(2);\n\ttorg.v(0) = start; torg.v(1) = 1.;\n\n\tsave_mode = psa<T>::mode();\n\tsave_uh = psa<T>::use_history();\n\tsave_rh = psa<T>::record_history();\n\tpsa<T>::mode() = 1;\n\tpsa<T>::use_history() = false;\n\tpsa<T>::record_history() = false;\n\t#if ODE_FAST == 1\n\tpsa<T>::record_history() = true;\n\tpsa<T>::history().clear();\n\t#endif\n\tfor (j=0; j<p.order; j++) {\n\t\t#if ODE_FAST == 1\n\t\tif (j == 1) psa<T>::use_history() = true;\n\t\tif (j == p.order - 1) psa<T>::record_history() = false;\n\t\t#endif\n\t\tt = setorder(torg, j);\n\t\ty = f(x, t);\n\t\tfor (i=0; i<n; i++) {\n\t\t\ty(i) = integrate(y(i));\n\t\t\ty(i) = setorder(y(i), j+1);\n\t\t}\n\t\tx = init + y;\n\t}\n\n\tif (p.autostep) {\n\t\tradius = 0.;\n\t\tn_rad = 0;\n\t\tfor (j = p.order; j>=1; j--) {\n\t\t\tm = 0.;\n\t\t\tfor (i=0; i<n; i++) {\n\t\t\t\tusing std::abs;\n\t\t\t\tm = std::max(m, abs(x(i).v(j)));\n\t\t\t}\n\t\t\tif (m == 0.) continue;\n\t\t\tradius_tmp = std::pow((double)m, 1./j);\n\t\t\tif (radius_tmp > radius) radius = radius_tmp;\n\t\t\tn_rad++;\n\t\t\tif (n_rad == 2) break;\n\t\t}\n\t\tradius = std::pow((double)tolerance, 1./p.order) / radius;\n\t}\n\n\tdeltat = end - start;\n\n\tif (p.autostep && radius < deltat) {\n\t\tend = start + radius;\n\t\tdeltat = end - start;\n\t}\n\n\tresult.resize(n);\n\tfor (i=0; i<n; i++) {\n\t\tresult(i) = eval(x(i), deltat);\n\t}\n\n\tinit = result;\n\n\tpsa<T>::mode() = save_mode;\n\tpsa<T>::use_history() = save_uh;\n\tpsa<T>::record_history() = save_rh;\n}\n\ntemplate <class T, class F>\nvoid\nodelong_nv(F f, ub::vector<T>& init, const T& start, const T& end, ode_param<T> p = ode_param<T>()) {\n\n\tub::vector<T> x;\n\tT t, t1;\n\n\tx = init;\n\tt = start;\n\tp.set_autostep(true);\n\twhile (1) {\n\t\tt1 = end;\n\t\tif (t == t1) break;\n\n\t\tode_nv(f, x, t, t1, p);\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \"t: \" << t1 << \"\\n\";\n\t\t\tstd::cout << x << \"\\n\";\n\t\t}\n\t\tt = t1;\n\t}\n\n\tinit = x;\n}\n\n} // namespace kv\n\n#endif // ODE_NV_HPP\n", "meta": {"hexsha": "7051fb5af9847493107ee9ac522b82493dcb3b2a", "size": 2733, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kv/ode-nv.hpp", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "src/interval/kv/ode-nv.hpp", "max_issues_repo_name": "takafumihoriuchi/HyLaGI", "max_issues_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "src/interval/kv/ode-nv.hpp", "max_forks_repo_name": "takafumihoriuchi/HyLaGI", "max_forks_repo_head_hexsha": "26b9f32a84611ee62d9cbbd903773d224088c959", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 18.22, "max_line_length": 101, "alphanum_fraction": 0.5729967069, "num_tokens": 1000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.6039318337259584, "lm_q1q2_score": 0.4018626109101976}}
{"text": "// GMTL is (C) Copyright 2001-2010 by Allen Bierbaum\n// Distributed under the GNU Lesser General Public License 2.1 with an\n// addendum covering inlined code. (See accompanying files LICENSE and\n// LICENSE.addendum or http://www.gnu.org/copyleft/lesser.txt)\n\n// This file was originally part of PyJuggler.\n\n// PyJuggler is (C) Copyright 2002, 2003 by Patrick Hartling\n// Distributed under the GNU Lesser General Public License 2.1.  (See\n// accompanying file COPYING.txt or http://www.gnu.org/copyleft/lesser.txt)\n\n// Includes ====================================================================\n#include <boost/python.hpp>\n#include <gmtl-wrappers.h>\n\n// Using =======================================================================\nusing namespace boost::python;\n\n// Declarations ================================================================\n\n\nnamespace  {\n\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(makeDirCosMatrix33_overloads_3_6, gmtlWrappers::makeDirCosMatrix33, 3, 6)\nBOOST_PYTHON_FUNCTION_OVERLOADS(makeDirCosMatrix44_overloads_3_6, gmtlWrappers::makeDirCosMatrix44, 3, 6)\n\n\n}// namespace \n\n\n// Module ======================================================================\nvoid _Export_gmtl_wrappers_h()\n{\n    def(\"makeAxesMatrix33\", (gmtl::Matrix<double,3,3> (*)(const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &))&gmtlWrappers::makeAxesMatrix33);\n    def(\"makeAxesMatrix33\", (gmtl::Matrix<float,3,3> (*)(const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &))&gmtlWrappers::makeAxesMatrix33);\n    def(\"makeAxesMatrix44\", (gmtl::Matrix<double,4,4> (*)(const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &))&gmtlWrappers::makeAxesMatrix44);\n    def(\"makeAxesMatrix44\", (gmtl::Matrix<float,4,4> (*)(const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &))&gmtlWrappers::makeAxesMatrix44);\n    def(\"makeDirCosMatrix33\", (gmtl::Matrix<double,3,3> (*)(const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &))&gmtlWrappers::makeDirCosMatrix33, makeDirCosMatrix33_overloads_3_6());\n    def(\"makeDirCosMatrix33\", (gmtl::Matrix<float,3,3> (*)(const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &))&gmtlWrappers::makeDirCosMatrix33, makeDirCosMatrix33_overloads_3_6());\n    def(\"makeDirCosMatrix44\", (gmtl::Matrix<double,4,4> (*)(const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &))&gmtlWrappers::makeDirCosMatrix44, makeDirCosMatrix44_overloads_3_6());\n    def(\"makeDirCosMatrix44\", (gmtl::Matrix<float,4,4> (*)(const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &))&gmtlWrappers::makeDirCosMatrix44, makeDirCosMatrix44_overloads_3_6());\n    def(\"makeRotEulerAngleXYZ\", (gmtl::EulerAngle<float,gmtl::XYZ> (*)(const gmtl::Matrix<float,4,4> &))&gmtlWrappers::makeRotEulerAngleXYZ);\n    def(\"makeRotEulerAngleXYZ\", (gmtl::EulerAngle<double,gmtl::XYZ> (*)(const gmtl::Matrix<double,4,4> &))&gmtlWrappers::makeRotEulerAngleXYZ);\n    def(\"makeRotEulerAngleZXY\", (gmtl::EulerAngle<float,gmtl::ZXY> (*)(const gmtl::Matrix<float,4,4> &))&gmtlWrappers::makeRotEulerAngleZXY);\n    def(\"makeRotEulerAngleZXY\", (gmtl::EulerAngle<double,gmtl::ZXY> (*)(const gmtl::Matrix<double,4,4> &))&gmtlWrappers::makeRotEulerAngleZXY);\n    def(\"makeRotEulerAngleZYX\", (gmtl::EulerAngle<float,gmtl::ZYX> (*)(const gmtl::Matrix<float,4,4> &))&gmtlWrappers::makeRotEulerAngleZYX);\n    def(\"makeRotEulerAngleZYX\", (gmtl::EulerAngle<double,gmtl::ZYX> (*)(const gmtl::Matrix<double,4,4> &))&gmtlWrappers::makeRotEulerAngleZYX);\n    def(\"makeRotMatrix33\", (gmtl::Matrix<double,3,3> (*)(const gmtl::Quat<double> &))&gmtlWrappers::makeRotMatrix33);\n    def(\"makeRotMatrix33\", (gmtl::Matrix<float,3,3> (*)(const gmtl::Quat<float> &))&gmtlWrappers::makeRotMatrix33);\n    def(\"makeRotMatrix33\", (gmtl::Matrix<float,3,3> (*)(const gmtl::EulerAngle<float,gmtl::ZYX> &))&gmtlWrappers::makeRotMatrix33);\n    def(\"makeRotMatrix33\", (gmtl::Matrix<float,3,3> (*)(const gmtl::EulerAngle<float,gmtl::XYZ> &))&gmtlWrappers::makeRotMatrix33);\n    def(\"makeRotMatrix33\", (gmtl::Matrix<float,3,3> (*)(const gmtl::EulerAngle<float,gmtl::ZXY> &))&gmtlWrappers::makeRotMatrix33);\n    def(\"makeRotMatrix33\", (gmtl::Matrix<float,3,3> (*)(const gmtl::AxisAngle<float> &))&gmtlWrappers::makeRotMatrix33);\n    def(\"makeRotMatrix33\", (gmtl::Matrix<double,3,3> (*)(const gmtl::AxisAngle<double> &))&gmtlWrappers::makeRotMatrix33);\n    def(\"makeRotMatrix44\", (gmtl::Matrix<float,4,4> (*)(const gmtl::Quat<float> &))&gmtlWrappers::makeRotMatrix44);\n    def(\"makeRotMatrix44\", (gmtl::Matrix<float,4,4> (*)(const gmtl::EulerAngle<float,gmtl::XYZ> &))&gmtlWrappers::makeRotMatrix44);\n    def(\"makeRotMatrix44\", (gmtl::Matrix<float,4,4> (*)(const gmtl::EulerAngle<float,gmtl::ZXY> &))&gmtlWrappers::makeRotMatrix44);\n    def(\"makeRotMatrix44\", (gmtl::Matrix<double,4,4> (*)(const gmtl::Quat<double> &))&gmtlWrappers::makeRotMatrix44);\n    def(\"makeRotMatrix44\", (gmtl::Matrix<float,4,4> (*)(const gmtl::EulerAngle<float,gmtl::ZYX> &))&gmtlWrappers::makeRotMatrix44);\n    def(\"makeRotMatrix44\", (gmtl::Matrix<float,4,4> (*)(const gmtl::AxisAngle<float> &))&gmtlWrappers::makeRotMatrix44);\n    def(\"makeRotMatrix44\", (gmtl::Matrix<double,4,4> (*)(const gmtl::AxisAngle<double> &))&gmtlWrappers::makeRotMatrix44);\n    def(\"makeRotMatrix44\", (gmtl::Matrix<float,4,4> (*)(const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &))&gmtlWrappers::makeRotMatrix44);\n    def(\"makeRotQuat\", (gmtl::Quat<float> (*)(const gmtl::Matrix<float,4,4> &))&gmtlWrappers::makeRotQuat);\n    def(\"makeRotQuat\", (gmtl::Quat<double> (*)(const gmtl::Matrix<double,4,4> &))&gmtlWrappers::makeRotQuat);\n    def(\"makeRotQuat\", (gmtl::Quat<float> (*)(const gmtl::AxisAngle<float> &))&gmtlWrappers::makeRotQuat);\n    def(\"makeRotQuat\", (gmtl::Quat<double> (*)(const gmtl::AxisAngle<double> &))&gmtlWrappers::makeRotQuat);\n    def(\"makeRotQuat\", (gmtl::Quat<float> (*)(const gmtl::Vec<float,3> &, const gmtl::Vec<float,3> &))&gmtlWrappers::makeRotQuat);\n    def(\"makeRotQuat\", (gmtl::Quat<double> (*)(const gmtl::Vec<double,3> &, const gmtl::Vec<double,3> &))&gmtlWrappers::makeRotQuat);\n    def(\"makeScaleMatrix33\", (gmtl::Matrix<double,3,3> (*)(const double&))&gmtlWrappers::makeScaleMatrix33);\n    def(\"makeScaleMatrix33\", (gmtl::Matrix<double,3,3> (*)(const gmtl::Vec<double,2> &))&gmtlWrappers::makeScaleMatrix33);\n    def(\"makeScaleMatrix33\", (gmtl::Matrix<float,3,3> (*)(const float&))&gmtlWrappers::makeScaleMatrix33);\n    def(\"makeScaleMatrix33\", (gmtl::Matrix<double,3,3> (*)(const gmtl::Vec<double,3> &))&gmtlWrappers::makeScaleMatrix33);\n    def(\"makeScaleMatrix33\", (gmtl::Matrix<float,3,3> (*)(const gmtl::Vec<float,2> &))&gmtlWrappers::makeScaleMatrix33);\n    def(\"makeScaleMatrix33\", (gmtl::Matrix<float,3,3> (*)(const gmtl::Vec<float,3> &))&gmtlWrappers::makeScaleMatrix33);\n    def(\"makeScaleMatrix44\", (gmtl::Matrix<double,4,4> (*)(const double&))&gmtlWrappers::makeScaleMatrix44);\n    def(\"makeScaleMatrix44\", (gmtl::Matrix<double,4,4> (*)(const gmtl::Vec<double,4> &))&gmtlWrappers::makeScaleMatrix44);\n    def(\"makeScaleMatrix44\", (gmtl::Matrix<float,4,4> (*)(const float&))&gmtlWrappers::makeScaleMatrix44);\n    def(\"makeScaleMatrix44\", (gmtl::Matrix<double,4,4> (*)(const gmtl::Vec<double,3> &))&gmtlWrappers::makeScaleMatrix44);\n    def(\"makeScaleMatrix44\", (gmtl::Matrix<float,4,4> (*)(const gmtl::Vec<float,4> &))&gmtlWrappers::makeScaleMatrix44);\n    def(\"makeScaleMatrix44\", (gmtl::Matrix<float,4,4> (*)(const gmtl::Vec<float,3> &))&gmtlWrappers::makeScaleMatrix44);\n    def(\"makeTransMatrix33\", (gmtl::Matrix<double,3,3> (*)(const gmtl::Vec<double,2> &))&gmtlWrappers::makeTransMatrix33);\n    def(\"makeTransMatrix33\", (gmtl::Matrix<float,3,3> (*)(const gmtl::Vec<float,2> &))&gmtlWrappers::makeTransMatrix33);\n    def(\"makeTransMatrix33\", (gmtl::Matrix<double,3,3> (*)(const gmtl::Vec<double,3> &))&gmtlWrappers::makeTransMatrix33);\n    def(\"makeTransMatrix33\", (gmtl::Matrix<float,3,3> (*)(const gmtl::Vec<float,3> &))&gmtlWrappers::makeTransMatrix33);\n    def(\"makeTransMatrix44\", (gmtl::Matrix<double,4,4> (*)(const gmtl::Vec<double,3> &))&gmtlWrappers::makeTransMatrix44);\n    def(\"makeTransMatrix44\", (gmtl::Matrix<float,4,4> (*)(const gmtl::Vec<float,3> &))&gmtlWrappers::makeTransMatrix44);\n    def(\"makeTransVec3\", (gmtl::Vec<double,3> (*)(const gmtl::Matrix<double,4,4> &))&gmtlWrappers::makeTransVec3);\n    def(\"makeTransVec3\", (gmtl::Vec<float,3> (*)(const gmtl::Matrix<float,4,4> &))&gmtlWrappers::makeTransVec3);\n    def(\"makeTransVec3\", (gmtl::Vec<double,3> (*)(const gmtl::Matrix<double,3,3> &))&gmtlWrappers::makeTransVec3);\n    def(\"makeTransVec3\", (gmtl::Vec<float,3> (*)(const gmtl::Matrix<float,3,3> &))&gmtlWrappers::makeTransVec3);\n    def(\"makeTransVec2\", (gmtl::Vec<double,2> (*)(const gmtl::Matrix<double,3,3> &))&gmtlWrappers::makeTransVec2);\n    def(\"makeTransVec2\", (gmtl::Vec<float,2> (*)(const gmtl::Matrix<float,3,3> &))&gmtlWrappers::makeTransVec2);\n    def(\"makeTransPoint3\", (gmtl::Point<double,3> (*)(const gmtl::Matrix<double,4,4> &))&gmtlWrappers::makeTransPoint3);\n    def(\"makeTransPoint3\", (gmtl::Point<float,3> (*)(const gmtl::Matrix<float,4,4> &))&gmtlWrappers::makeTransPoint3);\n}\n", "meta": {"hexsha": "ea192ca1948c921a59a46d76e22e1219fa3aab36", "size": 9642, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gmtl-0.6.1/python/src/gmtl/_gmtl_wrappers_h.cpp", "max_stars_repo_name": "Glitch0011/QuadTree-Example", "max_stars_repo_head_hexsha": "3558c999f68475bc98b8fa33b0f6d14076c9ec48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gmtl-0.6.1/python/src/gmtl/_gmtl_wrappers_h.cpp", "max_issues_repo_name": "Glitch0011/QuadTree-Example", "max_issues_repo_head_hexsha": "3558c999f68475bc98b8fa33b0f6d14076c9ec48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gmtl-0.6.1/python/src/gmtl/_gmtl_wrappers_h.cpp", "max_forks_repo_name": "Glitch0011/QuadTree-Example", "max_forks_repo_head_hexsha": "3558c999f68475bc98b8fa33b0f6d14076c9ec48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 99.4020618557, "max_line_length": 305, "alphanum_fraction": 0.6837792989, "num_tokens": 3330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.40186261091019754}}
{"text": "#include<iostream>\n#include <Eigen/Eigenvalues> \n#include\"numerics.hpp\"\n#include\"reddm.hpp\"\n#include\"tpoperators.hpp\"\n#include \"files.hpp\"\n#include\"FTLanczos.hpp\"\n#include<omp.h>\n#include <boost/program_options.hpp>\nusing namespace Many_Body;\nusing Mat= Operators::Mat;\n\nusing namespace boost::program_options;\nint main(int argc, char *argv[])\n{\n\n\n  int M{};\n  int L{};\n  double t0{};\n  double omega{};\n  double gamma{};\n  bool PB{0};\n   int runs={};\n   int Ldim={};\n    double T{};\n    double err{};\n  std::string sLdim={};\n  std::string sruns={};\nstd::string sT{};\nstd::string sM{};\nstd::string sL{};\nstd::string st0{};\nstd::string somega{};\nstd::string sgamma{};\nstd::string sPB{};\n std::string serr{};\n std::string filename=\"ompFTLM\";\n   \n\n  try\n  {\n    options_description desc{\"Options\"};\n    desc.add_options()\n      (\"help,h\", \"Help screen\")\n      (\"L\", value(&L)->default_value(4), \"L\")\n      (\"M\", value(&M)->default_value(2), \"M\")\n      (\"r\", value(&runs)->default_value(20), \"r\")\n      (\"Ld\", value(&Ldim)->default_value(20), \"Ld\")\n      (\"t0\", value(&t0)->default_value(1.), \"t0\")\n      (\"gam\", value(&gamma)->default_value(1.), \"gamma\")\n      (\"omg\", value(&omega)->default_value(1.), \"omega\")\n      (\"T\", value(&T)->default_value(1.), \"T\")\n      (\"pb\", value(&PB)->default_value(false), \"PB\")\n      (\"err\", boost::program_options::value(&err)->default_value(1E-9), \"err\");\n    boost::program_options::variables_map vm;\n    boost::program_options::store(parse_command_line(argc, argv, desc), vm);\n    boost::program_options::notify(vm);\n if (vm.count(\"help\"))\n      {std::cout << desc << '\\n'; return 0;}\n    else{\n      if (vm.count(\"L\"))\n      {\n  \tstd::cout << \"L: \" << vm[\"L\"].as<int>() << '\\n';\n\tsL=\"L\"+std::to_string(vm[\"L\"].as<int>());\n\tfilename+=sL;\n\t\n      }\n     if (vm.count(\"M\"))\n      {\n  \tstd::cout << \"M: \" << vm[\"M\"].as<int>() << '\\n';\n\tsM=\"M\"+std::to_string(vm[\"M\"].as<int>());\n\tfilename+=sM;\n\t\n      }\n     if (vm.count(\"r\"))\n      {\n  \tstd::cout << \"runs: \" << vm[\"r\"].as<int>() << '\\n';\n\tsruns=\"r\"+std::to_string(vm[\"r\"].as<int>());\n\tfilename+=sruns;\n\t\n      }\nif (vm.count(\"Ld\"))\n      {\n  \tstd::cout << \"lanczos dim: \" << vm[\"Ld\"].as<int>() << '\\n';\n\n\t\n      }\n      if (vm.count(\"t\"))\n      {\n      \tstd::cout << \"t0: \" << vm[\"t\"].as<double>() << '\\n';\n      \t      \tst0=\"t0\"+std::to_string(vm[\"t0\"].as<double>()).substr(0, 3);\n      \tfilename+=st0;\n      }\n       if (vm.count(\"omg\"))\n      {\n      \tstd::cout << \"omega: \" << vm[\"omg\"].as<double>() << '\\n';\n      \t      \tsomega=\"omg\"+std::to_string(vm[\"omg\"].as<double>()).substr(0, 3);\n      \tfilename+=somega;\n      }\n       if (vm.count(\"gam\"))\n      {\n      \tstd::cout << \"gamma: \" << vm[\"gam\"].as<double>() << '\\n';\n      \tsgamma=\"gam\"+std::to_string(vm[\"gam\"].as<double>()).substr(0, 3);\n      \tfilename+=sgamma;\n      }\n       if (vm.count(\"T\"))\n      {\n      \tstd::cout << \"T: \" << vm[\"T\"].as<double>() << '\\n';\n      }if (vm.count(\"pb\"))\n      {\n      \tstd::cout << \"PB: \" << vm[\"pb\"].as<bool>() << '\\n';\n      \tsPB=\"PB\"+std::to_string(vm[\"pb\"].as<bool>());\n      \tfilename+=sPB;\n      }\n      \t\t     if (vm.count(\"err\"))\n      {      std::cout << \"error: \" << vm[\"err\"].as<double>() << '\\n';\n      \t std::stringstream ss;\n      \t ss<<vm[\"err\"].as<double>();\n      \t serr=\"err\"+ss.str();\n      \tfilename+=serr;\n      }\n    }\n  }\n  catch (const error &ex)\n  {\n    std::cerr << ex.what() << '\\n';\n    return 0;\n  }\n\n     using HolsteinBasis= TensorProduct<ElectronBasis, PhononBasis>;\n \n  filename+=\".bin\";\n     std::vector<double> Tem;\n     std::vector<double> beta;\n     for(int i=1; i<11; i++)\n       {\n\t \t  Tem.push_back((0.1*i));\n\t  beta.push_back(1./(0.1*i));\n       }\n     \n     \n    Mat H;\n    Mat N;\n    Mat EK;\n    Mat X;\n  std::vector<Mat> obs;\n  {\n    \n    ElectronBasis e( L, 1);\n  PhononBasis ph(L, M);\n  HolsteinBasis TP(e, ph);\n  std::cout<< TP.dim<<std::endl;\n        Mat E1=Operators::EKinOperatorL(TP, e, t0,PB);\n       Mat Ebdag=Operators::NBosonCOperator(TP, ph, gamma, PB);\n       Mat Eb=Operators::NBosonDOperator(TP, ph, gamma, PB);\n      Mat Eph=Operators::NumberOperator(TP, ph, omega,  PB);\n\n      Eigen::VectorXd eigenVals(TP.dim);\n       H=E1+Eb+Eph+Ebdag;\n        N=Eph/omega;\n\tEK=E1;\n\tX=(Ebdag+Eb)/gamma;\n       obs.push_back(H);\n       obs.push_back(N);\n       obs.push_back(E1);\n       obs.push_back(X);\n  }\n\n     Eigen::MatrixXd Astot=Eigen::MatrixXd::Zero(beta.size(), obs.size());\nEigen::VectorXd Zstot=Eigen::VectorXd::Zero(beta.size());\n#pragma omp parallel\n  {\n\n#pragma omp for \n for(int i=0; i<runs; i++)\n   {\n     //     std::cout<< \" om num thread \" <<omp_get_thread_num()<<std::endl;\n     auto [Observables, SUMs]=calculate_lanczFT(obs[0], obs, beta, Ldim, err);\n\n\t#pragma omp critical\n\t{\n\t  Astot+=Observables;\n\t  Zstot+=SUMs;\n\t}\n\t//\tstd::cout << \" got meanZ \"<< SUMs.mean() << std::endl;\n    \n   }\n  }\n\n  std::cout<< \"Astot  \"<<std::endl<< Astot<< std::endl;\n  for(int i=0; i<beta.size(); i++)\n    {\n      Astot.row(i)/=Zstot(i);\n  \t   std::cout<<\" T \"<< 1./beta[i] << \"  \"<<Astot(i, 0)<<\" SUM \"<< Astot(i, 1)+Astot(i, 2)+Astot(i, 3)*gamma<<std::endl;\n    }\n  bin_write(\"E\"+filename, Eigen::VectorXd(Astot.col(0)));\n  bin_write(\"Nph\"+filename,  Eigen::VectorXd(Astot.col(1)));\n  bin_write(\"EK\"+filename, Eigen::VectorXd(Astot.col(2)));\n  bin_write(\"nX\"+filename, Eigen::VectorXd(Astot.col(3)));\n  bin_write(\"temp\"+filename, Tem);\n\t    \n\n  return 0;\n}\n", "meta": {"hexsha": "73a035a2f07be1c19c673a2c1199183517aa2cb9", "size": 5392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/holstFTLMparaOMP.cpp", "max_stars_repo_name": "jansendavid/many-body-lib", "max_stars_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/holstFTLMparaOMP.cpp", "max_issues_repo_name": "jansendavid/many-body-lib", "max_issues_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/holstFTLMparaOMP.cpp", "max_forks_repo_name": "jansendavid/many-body-lib", "max_forks_repo_head_hexsha": "eb8fcb2d61b4fdba1c1effaa706e3c298a17042b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1747572816, "max_line_length": 121, "alphanum_fraction": 0.5320845697, "num_tokens": 1718, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370423, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.4018554457993156}}
{"text": "#pragma once\n#include <mtao/types.h>\n#include <mtao/eigen_utils.h>\n#include <Eigen/Sparse>\n#include <boost/hana.hpp>\n\n//Use DECMesh by inheriting it and manually implementing boundary / cell volumes / dual cell volumes / the cell counts per type\n//\n//CachedDECMesh caches the boundary computatoins / cell volume information for when it's expensive to compute these things\n//\n//DECMeshCore implements DEC h(hodge dual) d(exterior derivative) cod(codifferential operator as well as\n//  the various laplacians (d cod / cod d / Laplace deRham (cod d + d cod) / weak laplacian (down) d cod h / weak laplacian (up) h cod d )\n//  Note: standard cotan laplacian is weak_laplacian_up<0>()\n\nnamespace mtao { namespace geometry { namespace mesh {\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim_>\nclass DECMeshCore {\n    public:\n        using types = mtao::embedded_types<T,EmbeddedDim>;\n        constexpr static int Dim = Dim_;\n        using Scalar = typename types::Scalar;\n        using VecX = typename types::VectorX;\n        using SparseMatrix = Eigen::SparseMatrix<Scalar>;\n\n        Derived& derived() { return *static_cast<Derived*>(this); }\n        const Derived& derived() const { return *static_cast<const Derived*>(this); }\n\n        template <int D>\n        SparseMatrix boundary() const { return derived().template boundary<D>(); }\n        template <int D>\n        VecX volume() const { return derived().template volume<D>(); }\n        template <int D>\n        VecX dual_volume() const { return derived().template dual_volume<D>(); }\n\n        //base operators\n        template <int D>\n        VecX h() const;\n        template <int D>\n        VecX hi() const;\n        template <int D>\n        SparseMatrix d() const;\n        template <int D>\n        SparseMatrix cod() const;\n\n        template <int D>\n        VecX h(const VecX& o) const { return h<D>().asDiagonal() * o; }\n        //inverse hodge\n        template <int D>\n        VecX hi(const VecX& o) const { return hi<D>().asDiagonal() * o; }\n        template <int D>\n        VecX d(const VecX& o) const { return d<D>() * o; }\n        //hi<D>dt<D-1>h<D>\n        template <int D>\n        VecX cod(const VecX& o) const { return cod<D>() * o; }\n\n        //laplacians\n        //d<D-1>hi<D>dt<D-1>h<D>\n        template <int D>\n        SparseMatrix laplacian_down() const;\n        //hi<D>dt<D>h<D+1>d<D>\n        template <int D>\n        SparseMatrix laplacian_up() const;\n        //d<D-1>hi<D>dt<D-1>h<D> + hi<D>dt<D>h<D+1>d<D>\n        template <int D>\n        SparseMatrix laplacian() const;\n        //d<D-1>hi<D>dt<D-1>   (h<D>)\n        template <int D>\n        SparseMatrix weak_laplacian_down() const;\n        //(hi<D>)    dt<D>h<D+1>d<D>\n        template <int D>\n        SparseMatrix weak_laplacian_up() const;\n\n        template <int D>\n        VecX weak_poisson_down(const VecX& o) const;\n        template <int D>\n        VecX weak_poisson_up(const VecX& o) const;\n        template <int D>\n        VecX weak_poisson_down_rhs(const VecX& o) const;\n        template <int D>\n        VecX weak_poisson_up_rhs(const VecX& o) const;\n\n        //Find the ___ part according to HH decomposition\n        //i.e o = da + hdhb + g\n\n        //a\n        template <int D>\n        VecX coexact_down(const VecX& o) const ;\n        //b\n        template <int D>\n        VecX exact_up(const VecX& o) const ;\n        //da\n        template <int D>\n        VecX exact(const VecX& o) const ;\n        //hdhb\n        template <int D>\n        VecX coexact(const VecX& o) const ;\n        //da + g i.e o - hdhb\n        template <int D>\n        VecX closed(const VecX& o) const ;\n        //hdhb + g i.e o - da\n        template <int D>\n        VecX coclosed(const VecX& o) const ;\n\n};\n\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim_>\nclass DECMesh: public DECMeshCore<DECMesh<Derived, T, EmbeddedDim, Dim_>, T, EmbeddedDim, Dim_> {\n    public:\n        using types = mtao::embedded_types<T,EmbeddedDim>;\n        constexpr static int Dim = Dim_;\n        using Scalar = typename types::Scalar;\n        using VecX = typename types::VectorX;\n        using SparseMatrix = Eigen::SparseMatrix<Scalar>;\n        using Mesh = DECMeshCore<DECMesh<Derived,T,EmbeddedDim,Dim>,T,EmbeddedDim,Dim>;\n\n        Derived& derived() { return *static_cast<Derived*>(this); }\n        const Derived& derived() const { return *static_cast<const Derived*>(this); }\n\n\n\n        template <int D>\n        SparseMatrix boundary() const { return derived().template boundary<D>(); }\n        /*\n        template <int C>\n        auto volume(int i) const { return derived().template volume<C>(i); }\n        template <int C>\n        auto dual_volume(int i) const { return derived().template dual_volume<C>(i); }\n        */\n        template <int C>\n        int cell_count() const { return derived().template cell_count<C>(); }\n        template <int C>\n        int dual_cell_count() const { return derived().template dual_cell_count<C>(); }\n        template <int D>\n        VecX volume() const { return derived().template volume<D>(); }\n        template <int D>\n        VecX dual_volume() const { return derived().template dual_volume<D>(); }\n};\ntemplate <typename T, int EmbeddedDim, int Dim_>\nclass CachedDECMesh: public DECMesh<CachedDECMesh<T, EmbeddedDim,Dim_>, T, EmbeddedDim, Dim_> {\n    public:\n        using types = mtao::embedded_types<T,EmbeddedDim>;\n        constexpr static int Dim = Dim_;\n        using Scalar = typename types::Scalar;\n        using VecX = typename types::VectorX;\n        using SparseMatrix = Eigen::SparseMatrix<Scalar>;\n        template <typename Derived>\n            CachedDECMesh(const DECMesh<Derived,T,EmbeddedDim,Dim>& d) {\n                using namespace boost;\n                boost::hana::for_each(hana::make_range(hana::int_c<0>,hana::int_c<Dim+1>), [&](auto t) {\n                        constexpr static int D = decltype(t)::value;\n                        m_volume[D] = d.template volume<D>();\n                        m_dual_volume[D] = d.template dual_volume<D>();\n                        });\n                boost::hana::for_each(hana::make_range(hana::int_c<1>,hana::int_c<Dim+1>), [&](auto t) {\n                        constexpr static int D = decltype(t)::value;\n                        m_boundary[D-1] = d.template boundary<D>();\n\n                        });\n            }\n\n\n        template <int C>\n        const SparseMatrix& boundary() const { return m_boundary[C-1]; }\n        template <int C>\n        auto volume(int i) const { return volume<C>()(i); }\n        template <int C>\n        auto dual_volume(int i) const { return dual_volume<C>()(i); }\n        template <int C>\n        int cell_count() const { return m_volume[C].rows();}\n        template <int C>\n        int dual_cell_count() const { return m_dual_volume[C].rows();}\n        template <int C>\n        const VecX& volume() const { return m_volume[C]; }\n        template <int C>\n        const VecX& dual_volume() const { return m_dual_volume[C]; }\n    private:\n        std::array<SparseMatrix, Dim> m_boundary;\n        std::array<VecX, Dim+1> m_volume;\n        std::array<VecX, Dim+1> m_dual_volume;\n\n};\n\n/*\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim>\ntemplate <int D>\nauto DECMesh<Derived,T,EmbeddedDim,Dim>::volume() const -> VecX {\n    int s = cell_count<D>();\n    VecX v = VecX::Zero(s);\n    for(int i = 0; i < s; ++i) {\n        v(i) = volume<D>(i);\n    }\n    return v;\n}\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim>\ntemplate <int D>\nauto DECMesh<Derived,T,EmbeddedDim,Dim>::dual_volume() const -> VecX {\n    int s = dual_cell_count<D>();\n    VecX v = VecX::Zero(s);\n    for(int i = 0; i < s; ++i) {\n        v(i) = dual_volume<D>(i);\n    }\n    return v;\n}\n*/\n\n\n\n//Base operators\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::h() const -> VecX {\n    auto p = volume<D>();\n    auto d = dual_volume<D>();\n\n    VecX ret = d.cwiseQuotient(p);\n    return mtao::eigen::finite(ret);\n}\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::hi() const -> VecX {\n    auto p = volume<D>();\n    auto d = dual_volume<D>();\n\n    VecX ret = p.cwiseQuotient(d);\n    return mtao::eigen::finite(ret);\n}\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::d() const -> SparseMatrix {\n    return boundary<D+1>().transpose();\n}\n\n// * d *\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::cod() const -> SparseMatrix {\n    return hi<D-1>().asDiagonal() * d<D-1>().transpose() * h<D>().asDiagonal();\n}\n\n//Laplacians\n//d * d *\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>:: laplacian_down() const -> SparseMatrix {\n    return d<D-1>() * cod<D>();\n}\n//* d * d\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>:: laplacian_up() const -> SparseMatrix {\n    //h<1>\n    return cod<D+1>() * d<D>();\n}\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>:: laplacian() const -> SparseMatrix {\n    if constexpr(D == 0) {\n        return laplacian_up<D>();\n    } else if(D == Dim) {\n        return laplacian_down<D>();\n    } else {\n        return laplacian_down<D>() + laplacian_down<D>();\n    }\n}\n//d * d that goes up down a dimension\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>:: weak_laplacian_down() const -> SparseMatrix {\n    auto a = d<D-1>();\n    return a * hi<D-1>().asDiagonal() * a.transpose();\n}\n//d * d that goes up a dimension\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>:: weak_laplacian_up() const -> SparseMatrix {\n    auto a = d<D>();\n    return a.transpose() * h<D+1>().asDiagonal() * a;\n}\n//d x\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::weak_poisson_down_rhs(const VecX& o) const -> VecX {\n    return d<D>(o);\n}\n//d * x\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::weak_poisson_up_rhs(const VecX& o) const -> VecX {\n    return d<D-1>().transpose() * h<D>(o);\n}\n//(d * d )^{-1} ( d x )\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::weak_poisson_down(const VecX& rhs) const -> VecX {\n    auto L = weak_laplacian_down<D>();\n    Eigen::ConjugateGradient<SparseMatrix, Eigen::Upper|Eigen::Lower> solver(L);\n    VecX p = solver.solveWithGuess(rhs,VecX::Zero(rhs.rows()));\n    return p;\n}\n//(d * d )^{-1} ( d * x )\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::weak_poisson_up(const VecX& rhs) const -> VecX {\n    auto L = weak_laplacian_up<D>();\n    Eigen::ConjugateGradient<SparseMatrix, Eigen::Upper|Eigen::Lower> solver(L);\n    VecX p = solver.solveWithGuess(rhs,VecX::Zero(rhs.rows()));\n    return p;\n}\n\n//Hodge decomposition components\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::exact_up(const VecX& o) const -> VecX {\n    //d (u - HdHp) = 0\n    //dHdHp = du\n    //d^THdHp = du\n    //Hp =(d^THd)^{-1} du\n\n\n    //d<D> | hi<D>dt<D>   (h<D+1>)\n\n\n    return hi<D+1>(weak_poisson_down<D+1>(weak_poisson_down_rhs<D>(o)));\n}\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::coexact_down(const VecX& o) const -> VecX {\n    //HdH (u - dp) = 0\n    //HdHdp = HdHu\n    //dHd^Tp = d^THu\n    //p =(dHd^T)^{-1} dHu\n\n\n    //(hi<D>)    dt<D-1>h<D> | d<D-1>\n    return weak_poisson_up<D-1>(weak_poisson_up_rhs<D>(o));\n}\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::exact(const VecX& o) const -> VecX {\n    return d<D-1>(coexact_down<D>(o));\n}\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::coexact(const VecX& o) const -> VecX {\n    return cod<D+1>(exact_up<D>(o));\n}\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::closed(const VecX& o) const -> VecX {\n    return o - coexact<D>(o);\n}\ntemplate <typename Derived, typename T, int EmbeddedDim, int Dim> template <int D>\nauto DECMeshCore<Derived,T,EmbeddedDim,Dim>::coclosed(const VecX& o) const -> VecX {\n    return o - exact<D>(o);\n}\n}}}\n", "meta": {"hexsha": "574b48b44386254b7156618c2461b0c1a2ef0e5f", "size": 12983, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mtao/geometry/mesh/dec.hpp", "max_stars_repo_name": "mtao/core", "max_stars_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mtao/geometry/mesh/dec.hpp", "max_issues_repo_name": "mtao/core", "max_issues_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:16:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:17:36.000Z", "max_forks_repo_path": "include/mtao/geometry/mesh/dec.hpp", "max_forks_repo_name": "mtao/core", "max_forks_repo_head_hexsha": "91f9bc6e852417989ed62675e2bb372e6afc7325", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2979351032, "max_line_length": 138, "alphanum_fraction": 0.6268967111, "num_tokens": 3603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7853085909370421, "lm_q2_score": 0.5117166047041652, "lm_q1q2_score": 0.40185544579931537}}
{"text": "// This file is part of the pyMOR project (http://www.pymor.org).\n// Copyright 2013-2018 pyMOR developers and contributors. All rights reserved.\n// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\n#include \"elasticity.hh\"\n\n#include <deal.II/lac/solver_bicgstab.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/numerics/solution_transfer.h>\n\n#include <fstream>\n\n//! Wrapper intended for use w/ CG algorithms\ntemplate <class Number>\nclass MatrixSum {\n\npublic:\n  typedef Number value_type;\n  typedef std::vector<const dealii::SparseMatrix<Number>*> Matrices;\n  MatrixSum(Matrices&& m, std::vector<Number> weights)\n    : matrices_(m) {\n    assert(m.size() > 0);\n    assert(m.size() == weights.size());\n    sum_.reinit(matrices_[0]->get_sparsity_pattern());\n    sum_.copy_from(*matrices_[0]);\n    sum_ *= weights[0];\n    for (size_t i = 1; i < m.size(); ++i) {\n      sum_.add(weights[i], *matrices_[1]);\n    }\n  }\n\n  dealii::SparseMatrix<Number>& sum() { return sum_; }\n\n  const dealii::SparseMatrix<Number>& sum() const { return sum_; }\n\nprivate:\n  const Matrices matrices_;\n  dealii::SparseMatrix<Number> sum_;\n};\n\nElasticityExample::ElasticityExample(int refine_steps)\n  : dof_handler_(triangulation_)\n  , fe_(FE_Q<dim>(1), dim) {\n  GridGenerator::hyper_cube(triangulation_, -1, 1);\n  refine_global(refine_steps);\n}\n\nElasticityExample::~ElasticityExample() { dof_handler_.clear(); }\n\nvoid ElasticityExample::setup_system() {\n  dof_handler_.clear();\n  dof_handler_.distribute_dofs(fe_);\n  sparsity_pattern_.reinit(dof_handler_.n_dofs(), dof_handler_.n_dofs(), dof_handler_.max_couplings_between_dofs());\n  DoFTools::make_sparsity_pattern(dof_handler_, sparsity_pattern_);\n\n  sparsity_pattern_.compress();\n\n  h1_matrix_.reinit(sparsity_pattern_);\n  lambda_system_matrix_.reinit(sparsity_pattern_);\n  mu_system_matrix_.reinit(sparsity_pattern_);\n  system_rhs_.reinit(dof_handler_.n_dofs());\n  tmp_data_.reinit(dof_handler_.n_dofs());\n}\n\nvoid ElasticityExample::assemble_h1() {\n  QGauss<dim> quadrature_formula(2);\n\n  FEValues<dim> fe_values(fe_, quadrature_formula,\n                          update_values | update_gradients | update_quadrature_points | update_JxW_values);\n\n  const unsigned int dofs_per_cell = fe_.dofs_per_cell;\n  const unsigned int n_q_points = quadrature_formula.size();\n\n  FullMatrix<Number> h1_cell_matrix(dofs_per_cell, dofs_per_cell);\n  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n  // Now we can begin with the loop over all cells:\n  typename DoFHandler<dim>::active_cell_iterator cell = dof_handler_.begin_active(), endc = dof_handler_.end();\n  for (; cell != endc; ++cell) {\n    h1_cell_matrix = 0;\n    fe_values.reinit(cell);\n\n    for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n      const unsigned int component_i = fe_.system_to_component_index(i).first;\n\n      for (unsigned int j = 0; j < dofs_per_cell; ++j) {\n        const unsigned int component_j = fe_.system_to_component_index(j).first;\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n          h1_cell_matrix(i, j) += fe_values.shape_grad(i, q_point)[component_i] *\n                                  fe_values.shape_grad(j, q_point)[component_j] * fe_values.JxW(q_point);\n        }\n      }\n    }\n\n    cell->get_dof_indices(local_dof_indices);\n    for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n      for (unsigned int j = 0; j < dofs_per_cell; ++j) {\n        h1_matrix_.add(local_dof_indices[i], local_dof_indices[j], h1_cell_matrix(i, j));\n      }\n    }\n  }\n\n  std::map<types::global_dof_index, Number> boundary_values;\n  VectorTools::interpolate_boundary_values(dof_handler_, 0, ZeroFunction<dim>(dim), boundary_values);\n  MatrixTools::apply_boundary_values(boundary_values, h1_matrix_, tmp_data_, system_rhs_);\n}\n\nvoid ElasticityExample::assemble_system() {\n  QGauss<dim> quadrature_formula(2);\n\n  FEValues<dim> fe_values(fe_, quadrature_formula,\n                          update_values | update_gradients | update_quadrature_points | update_JxW_values);\n\n  const unsigned int dofs_per_cell = fe_.dofs_per_cell;\n  const unsigned int n_q_points = quadrature_formula.size();\n\n  FullMatrix<Number> lambda_cell_matrix(dofs_per_cell, dofs_per_cell), mu_cell_matrix(dofs_per_cell, dofs_per_cell);\n  Vector<Number> cell_rhs(dofs_per_cell);\n\n  std::vector<types::global_dof_index> local_dof_indices(dofs_per_cell);\n\n  // As was shown in previous examples as well, we need a place where to\n  // store the values of the coefficients at all the quadrature points on a\n  // cell. In the present situation, we have two coefficients, lambda and\n  // mu.\n  std::vector<Number> lambda_values(n_q_points);\n  std::vector<Number> mu_values(n_q_points);\n\n  // Well, we could as well have omitted the above two arrays since we will\n  // use constant coefficients for both lambda and mu, which can be declared\n  // like this. They both represent functions always returning the constant\n  // value 1.0. Although we could omit the respective factors in the\n  // assemblage of the matrix, we use them here for purpose of\n  // demonstration.\n  Functions::ConstantFunction<dim> lambda(1), mu(1);\n\n  // Then again, we need to have the same for the right hand side. This is\n  // exactly as before in previous examples. However, we now have a\n  // vector-valued right hand side, which is why the data type of the\n  // <code>rhs_values</code> array is changed. We initialize it by\n  // <code>n_q_points</code> elements, each of which is a\n  // <code>Vector@<double@></code> with <code>dim</code> elements.\n  RightHandSide<dim> right_hand_side;\n  std::vector<Vector<Number>> rhs_values(n_q_points, Vector<Number>(dim));\n\n  // Now we can begin with the loop over all cells:\n  typename DoFHandler<dim>::active_cell_iterator cell = dof_handler_.begin_active(), endc = dof_handler_.end();\n  for (; cell != endc; ++cell) {\n    lambda_cell_matrix = 0;\n    mu_cell_matrix = 0;\n    cell_rhs = 0;\n\n    fe_values.reinit(cell);\n\n    // Next we get the values of the coefficients at the quadrature\n    // points. Likewise for the right hand side:\n    lambda.value_list(fe_values.get_quadrature_points(), lambda_values);\n    mu.value_list(fe_values.get_quadrature_points(), mu_values);\n\n    right_hand_side.vector_value_list(fe_values.get_quadrature_points(), rhs_values);\n\n    // Then assemble the entries of the local stiffness matrix and right\n    // hand side vector. This follows almost one-to-one the pattern\n    // described in the introduction of this example.  One of the few\n    // comments in place is that we can compute the number\n    // <code>comp(i)</code>, i.e. the index of the only nonzero vector\n    // component of shape function <code>i</code> using the\n    // <code>fe.system_to_component_index(i).first</code> function call\n    // below.\n    //\n    // (By accessing the <code>first</code> variable of the return value\n    // of the <code>system_to_component_index</code> function, you might\n    // already have guessed that there is more in it. In fact, the\n    // function returns a <code>std::pair@<unsigned int, unsigned\n    // int@></code>, of which the first element is <code>comp(i)</code>\n    // and the second is the value <code>base(i)</code> also noted in the\n    // introduction, i.e.  the index of this shape function within all the\n    // shape functions that are nonzero in this component,\n    // i.e. <code>base(i)</code> in the diction of the introduction. This\n    // is not a number that we are usually interested in, however.)\n    //\n    // With this knowledge, we can assemble the local matrix\n    // contributions:\n    for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n      const unsigned int component_i = fe_.system_to_component_index(i).first;\n\n      for (unsigned int j = 0; j < dofs_per_cell; ++j) {\n        const unsigned int component_j = fe_.system_to_component_index(j).first;\n\n        for (unsigned int q_point = 0; q_point < n_q_points; ++q_point) {\n          lambda_cell_matrix(i, j) +=\n              // The first term is (lambda d_i u_i, d_j v_j) + (mu d_i\n              // u_j, d_j v_i).  Note that\n              // <code>shape_grad(i,q_point)</code> returns the\n              // gradient of the only nonzero component of the i-th\n              // shape function at quadrature point q_point. The\n              // component <code>comp(i)</code> of the gradient, which\n              // is the derivative of this only nonzero vector\n              // component of the i-th shape function with respect to\n              // the comp(i)th coordinate is accessed by the appended\n              // brackets.\n              fe_values.shape_grad(i, q_point)[component_i] * fe_values.shape_grad(j, q_point)[component_j] *\n              lambda_values[q_point] * fe_values.JxW(q_point);\n          mu_cell_matrix(i, j) +=\n              (fe_values.shape_grad(i, q_point)[component_j] * fe_values.shape_grad(j, q_point)[component_i] *\n                   mu_values[q_point] +\n               // The second term is (mu nabla u_i, nabla v_j).  We\n               // need not access a specific component of the\n               // gradient, since we only have to compute the scalar\n               // product of the two gradients, of which an\n               // overloaded version of the operator* takes care, as\n               // in previous examples.\n               //\n               // Note that by using the ?: operator, we only do this\n               // if comp(i) equals comp(j), otherwise a zero is\n               // added (which will be optimized away by the\n               // compiler).\n               ((component_i == component_j)\n                    ? (fe_values.shape_grad(i, q_point) * fe_values.shape_grad(j, q_point) * mu_values[q_point])\n                    : 0)) *\n              fe_values.JxW(q_point);\n        }\n      }\n    }\n\n    // Assembling the right hand side is also just as discussed in the\n    // introduction:\n    for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n      const unsigned int component_i = fe_.system_to_component_index(i).first;\n\n      for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n        cell_rhs(i) += fe_values.shape_value(i, q_point) * rhs_values[q_point](component_i) * fe_values.JxW(q_point);\n    }\n\n    // The transfer from local degrees of freedom into the global matrix\n    // and right hand side vector does not depend on the equation under\n    // consideration, and is thus the same as in all previous\n    // examples. The same holds for the elimination of hanging nodes from\n    // the matrix and right hand side, once we are done with assembling\n    // the entire linear system:\n    cell->get_dof_indices(local_dof_indices);\n    for (unsigned int i = 0; i < dofs_per_cell; ++i) {\n      for (unsigned int j = 0; j < dofs_per_cell; ++j) {\n        lambda_system_matrix_.add(local_dof_indices[i], local_dof_indices[j], lambda_cell_matrix(i, j));\n        mu_system_matrix_.add(local_dof_indices[i], local_dof_indices[j], mu_cell_matrix(i, j));\n      }\n\n      system_rhs_(local_dof_indices[i]) += cell_rhs(i);\n    }\n  }\n  // The interpolation of the boundary values needs a small modification:\n  // since the solution function is vector-valued, so need to be the\n  // boundary values. The <code>ZeroFunction</code> constructor accepts a\n  // parameter that tells it that it shall represent a vector valued,\n  // constant zero function with that many components. By default, this\n  // parameter is equal to one, in which case the <code>ZeroFunction</code>\n  // object would represent a scalar function. Since the solution vector has\n  // <code>dim</code> components, we need to pass <code>dim</code> as number\n  // of components to the zero function as well.\n  std::map<types::global_dof_index, Number> boundary_values;\n  VectorTools::interpolate_boundary_values(dof_handler_, 0, ZeroFunction<dim>(dim), boundary_values);\n  MatrixTools::apply_boundary_values(boundary_values, mu_system_matrix_, tmp_data_, system_rhs_);\n  MatrixTools::apply_boundary_values(boundary_values, lambda_system_matrix_, tmp_data_, system_rhs_);\n}\n\nvoid ElasticityExample::_solve(Parameter param, VectorType& solution) {\n  SolverControl solver_control(20000, 1e-12);\n  SolverCG<> cg(solver_control);\n\n  deallog << \"Solving for \" << dof_handler_.n_dofs() << \" unknowns\" << std::endl;\n  Number lambda(param[\"lambda\"][0]), mu(param[\"mu\"][0]);\n  MatrixSum<Number> msum({&lambda_system_matrix_, &mu_system_matrix_}, {lambda, mu});\n\n  auto& sum = msum.sum();\n  PreconditionSSOR<> preconditioner;\n  preconditioner.initialize(sum, 1.2);\n  cg.solve(sum, solution, system_rhs_, preconditioner);\n}\n\nvoid ElasticityExample::visualize(const VectorType& solution, std::string filename) const {\n  std::ofstream output(filename);\n\n  DataOut<dim> data_out;\n  data_out.attach_dof_handler(dof_handler_);\n\n  // As said above, we need a different name for each component of the\n  // solution function. To pass one name for each component, a vector of\n  // strings is used. Since the number of components is the same as the\n  // number of dimensions we are working in, the following\n  // <code>switch</code> statement is used.\n  //\n  // We note that some graphics programs have restriction as to what\n  // characters are allowed in the names of variables. The library therefore\n  // supports only the minimal subset of these characters that is supported\n  // by all programs. Basically, these are letters, numbers, underscores,\n  // and some other characters, but in particular no whitespace and\n  // minus/hyphen. The library will throw an exception otherwise, at least\n  // if in debug mode.\n  //\n  // After listing the 1d, 2d, and 3d case, it is good style to let the\n  // program die if we run upon a case which we did not consider. Remember\n  // that the <code>Assert</code> macro generates an exception if the\n  // condition in the first parameter is not satisfied. Of course, the\n  // condition <code>false</code> can never be satisfied, so the program\n  // will always abort whenever it gets to the default statement:\n  std::vector<std::string> solution_names;\n  switch (dim) {\n    case 1:\n      solution_names.push_back(\"displacement\");\n      break;\n    case 2:\n      solution_names.push_back(\"x_displacement\");\n      solution_names.push_back(\"y_displacement\");\n      break;\n    case 3:\n      solution_names.push_back(\"x_displacement\");\n      solution_names.push_back(\"y_displacement\");\n      solution_names.push_back(\"z_displacement\");\n      break;\n    default:\n      throw ExcNotImplemented();\n  }\n\n  // After setting up the names for the different components of the solution\n  // vector, we can add the solution vector to the list of data vectors\n  // scheduled for output. Note that the following function takes a vector\n  // of strings as second argument, whereas the one which we have used in\n  // all previous examples accepted a string there. In fact, the latter\n  // function is only a shortcut for the function which we call here: it\n  // puts the single string that is passed to it into a vector of strings\n  // with only one element and forwards that to the other function.\n  data_out.add_data_vector(solution, solution_names);\n  data_out.build_patches();\n  data_out.write_vtk(output);\n}\n\nvoid ElasticityExample::refine_global(int refine_steps) {\n  triangulation_.refine_global(refine_steps);\n  setup_system();\n  assemble_h1();\n  assemble_system();\n}\n\nElasticityExample::VectorType ElasticityExample::solve(const ElasticityExample::Parameter& param) {\n  _solve(param, tmp_data_);\n  return VectorType(tmp_data_);\n}\n\nconst dealii::SparseMatrix<ElasticityExample::Number>& ElasticityExample::lambda_mat() const {\n  return lambda_system_matrix_;\n}\n\nconst dealii::SparseMatrix<ElasticityExample::Number>& ElasticityExample::mu_mat() const { return mu_system_matrix_; }\n\nconst dealii::SparseMatrix<ElasticityExample::Number>& ElasticityExample::h1_mat() const { return h1_matrix_; }\n\nconst dealii::Vector<ElasticityExample::Number>& ElasticityExample::rhs() const { return system_rhs_; }\n\nElasticityExample::Number ElasticityExample::h1_0_semi_norm(const Vector<Number>& v) const {\n  return std::sqrt(h1_matrix_.matrix_norm_square(v));\n}\n\nElasticityExample::Number ElasticityExample::energy_norm(const Vector<ElasticityExample::Number>& v) const {\n  return std::sqrt(mu_system_matrix_.matrix_norm_square(v));\n}\n\nElasticityExample::VectorType ElasticityExample::transfer_to(int refine_steps, const ElasticityExample::VectorType& v) {\n  triangulation_.prepare_coarsening_and_refinement();\n  dealii::SolutionTransfer<dim, VectorType> trans(dof_handler_);\n  trans.prepare_for_pure_refinement();\n  refine_global(refine_steps);\n\n  VectorType ret(dof_handler_.n_dofs());\n  trans.refine_interpolate(v, ret);\n  return ret;\n}\n", "meta": {"hexsha": "fd010e14337ae4d9fe616a613b73e998b4e67bfb", "size": 16722, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/elasticity.cc", "max_stars_repo_name": "pymor/pymor-deal.II", "max_stars_repo_head_hexsha": "520b36b42d7e58e8adaefb4c772d36d650f30c27", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-12T12:15:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-14T08:06:27.000Z", "max_issues_repo_path": "lib/elasticity.cc", "max_issues_repo_name": "pymor/pymor-deal.II", "max_issues_repo_head_hexsha": "520b36b42d7e58e8adaefb4c772d36d650f30c27", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-01-24T13:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-24T08:25:22.000Z", "max_forks_repo_path": "lib/elasticity.cc", "max_forks_repo_name": "pymor/pymor-deal.II", "max_forks_repo_head_hexsha": "520b36b42d7e58e8adaefb4c772d36d650f30c27", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-03-02T14:32:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T09:10:01.000Z", "avg_line_length": 44.2380952381, "max_line_length": 120, "alphanum_fraction": 0.7069728501, "num_tokens": 4162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019595, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.40181349051942583}}
{"text": "\n#include <cmath>\n#include <boost/math/special_functions/digamma.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#include \"constants.hpp\"\n#include \"fastmath.hpp\"\n#include \"logger.hpp\"\n#include \"nlopt/nlopt.h\"\n#include \"shredder.hpp\"\n\n\ndouble shredder_opt_objective(unsigned int _n, const double* _x,\n                              double* _grad, void* data)\n{\n    UNUSED(_n);\n\n    Shredder* sampler = reinterpret_cast<Shredder*>(data);\n    if (_grad) {\n        double fx = sampler->f(_x[0], _grad[0]);\n        _grad[0] = std::max<double>(std::min<double>(_grad[0], 1e4), -1e4);\n        return fx;\n    }\n    else {\n        double d;\n        return sampler->f(_x[0], d);\n    }\n}\n\n\nstatic void assert_finite(double x)\n{\n    if (!boost::math::isfinite(x)) {\n        Logger::abort(\"%f found where finite value expected.\", x);\n    }\n}\n\n\nShredder::Shredder(double lower_limit, double upper_limit, double tolerance)\n    : lower_limit(lower_limit)\n    , upper_limit(upper_limit)\n    , tolerance(tolerance)\n    , opt(NULL)\n{\n    opt = nlopt_create(NLOPT_LD_SLSQP, 1);\n    nlopt_set_lower_bounds(opt, &lower_limit);\n    nlopt_set_upper_bounds(opt, &upper_limit);\n    nlopt_set_max_objective(opt, shredder_opt_objective,\n            reinterpret_cast<void*>(this));\n    nlopt_set_maxeval(opt, 20);\n\n    nlopt_set_ftol_abs(opt, 1e-7);\n    nlopt_set_xtol_abs(opt, &tolerance);\n}\n\n\nShredder::~Shredder()\n{\n    nlopt_destroy(opt);\n}\n\n\nvoid Shredder::set_tolerance(double tolerance)\n{\n    this->tolerance = tolerance;\n    nlopt_set_xtol_abs(opt, &this->tolerance);\n}\n\n\ndouble Shredder::sample(rng_t& rng, double x0)\n{\n    double d0;\n    double lp0 = f(x0, d0);\n\n    assert_finite(lp0);\n\n    double slice_height = fastlog(\n            std::max<double>(constants::zero_eps, random_uniform_01(rng))) + lp0;\n    assert_finite(slice_height);\n\n    x_min = find_slice_edge(x0, slice_height, lp0, d0, -1);\n    x_max = find_slice_edge(x0, slice_height, lp0, d0,  1);\n\n    double x = (x_max + x_min) / 2;\n    while (x_max - x_min > tolerance) {\n        x = x_min + (x_max - x_min) * random_uniform_01(rng);\n        double d;\n        double lp = f(x, d);\n\n        if (lp >= slice_height) break;\n        else if (x > x0) x_max = x;\n        else             x_min = x;\n    }\n\n    return x;\n}\n\n\ndouble Shredder::optimize(double x0)\n{\n    // bounds may have changed\n    nlopt_set_lower_bounds(opt, &lower_limit);\n    nlopt_set_upper_bounds(opt, &upper_limit);\n\n    x0 = std::max<double>(std::min<double>(x0, upper_limit), lower_limit);\n    //x0 = (lower_limit + upper_limit) / 2;\n    double maxf;\n    nlopt_result result = nlopt_optimize(opt, &x0, &maxf);\n\n    if (result < 0 && result != NLOPT_ROUNDOFF_LIMITED) {\n        Logger::warn(\"Optimization failed with code %d\", (int) result);\n    }\n\n    return std::max<double>(std::min<double>(x0, upper_limit), lower_limit);\n}\n\n\ndouble Shredder::find_slice_edge(double x0, double slice_height,\n                                 double lp0, double d0, int direction)\n{\n    const double lp_eps = 1e-2;\n    const double d_eps  = 1e-3;\n\n    // if newton method iterations are not making progress, resort to bisection\n    size_t newton_count = 0;\n\n    double lp = lp0 - slice_height;\n    double d = d0;\n    double x = x0;\n    double x_bound_lower, x_bound_upper;\n\n    if (direction < 0) {\n        x_bound_lower = lower_limit;\n        x_bound_upper = x0;\n        double fx = f(lower_limit, d);\n        if (boost::math::isfinite(fx) && fx >= slice_height) {\n            return lower_limit;\n        }\n    }\n    else {\n        x_bound_lower = x0;\n        x_bound_upper = upper_limit;\n        double fx = f(upper_limit, d);\n        if (boost::math::isfinite(fx) && fx >= slice_height) {\n            return upper_limit;\n        }\n    }\n\n    while (fabs(lp) > lp_eps && fabs(x_bound_upper - x_bound_lower) > tolerance) {\n        double x1 = x - lp / d;\n        if (isnan(d) || d == 0.0 || fabs(d) < d_eps || !boost::math::isfinite(x1)) {\n            x1 = (x_bound_lower + x_bound_upper) / 2;\n        }\n\n        // if we are very close to the boundry, and this iteration moves us past\n        // the boundry, just give up.\n        if (direction < 0 && fabs(x - lower_limit) <= tolerance && (x1 < x || lp > 0.0)) break;\n        if (direction > 0 && fabs(x - upper_limit) <= tolerance && (x1 > x || lp > 0.0)) break;\n\n        // if we are moving in the wrong direction (i.e. toward the other root),\n        // use bisection to correct course.\n        if (direction < 0) {\n            if (lp > 0) x_bound_upper = x;\n            else        x_bound_lower = x;\n        }\n        else {\n            if (lp > 0) x_bound_lower = x;\n            else        x_bound_upper = x;\n        }\n\n        bool bisect = newton_count >= constants::max_newton_steps ||\n            x1 < x_bound_lower + tolerance || x1 > x_bound_upper - tolerance;\n\n        // try using the gradient\n        if (!bisect) {\n            x = x1;\n            lp = f(x, d) - slice_height;\n            bisect = !boost::math::isfinite(lp) || !boost::math::isfinite(d);\n        }\n\n        // resort to binary search if we seem not to be making progress\n        if (bisect) {\n            size_t iteration_count = 0;\n            while (true) {\n                x = (x_bound_lower + x_bound_upper) / 2;\n                lp = f(x, d) - slice_height;\n\n                //if (boost::math::isinf(lp) || boost::math::isinf(d)) {\n                if (!boost::math::isfinite(lp)) {\n                    if (direction < 0) x_bound_lower = x;\n                    else               x_bound_upper = x;\n                }\n                else break;\n\n                if (++iteration_count > 50) {\n                    Logger::abort(\"Slice sampler edge finding is not making progress.\");\n                }\n            }\n    }\n    else ++newton_count;\n\n        assert_finite(lp);\n    }\n\n    assert_finite(x);\n\n    return x;\n}\n\n\nstatic double sq(double x)\n{\n    return x * x;\n}\n\n\nstatic double cb(double x)\n{\n    return x * x * x;\n}\n\nstatic double lbeta(double x, double y)\n{\n    return lgamma(x) + lgamma(y) - lgamma(x + y);\n}\n\n\n#if 0\ndouble PoissonLogPdf::f(float lambda, unsigned int k)\n{\n    return k * fastlog(lambda) - lgammaf(k + 1) - lambda;\n}\n\n\ndouble PoissonLogPdf::df_dlambda(float lambda, unsigned int k)\n{\n    return (float) k / lambda - 1;\n}\n#endif\n\n\nstatic const double NEG_LOG_2_PI_DIV_2 = -log(2 * M_PI)/2;\n\ndouble NormalLogPdf::f(double mu, double sigma, const double* xs, size_t n)\n{\n    double part1 = n * (NEG_LOG_2_PI_DIV_2 - fastlog(sigma));\n    double part2 = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part2 += sq(xs[i] - mu) / (2 * sq(sigma));\n    }\n\n    return part1 - part2;\n}\n\n\nfloat NormalLogPdf::f(float mu, float sigma, const float* xs, size_t n)\n{\n    float part1 = n * (NEG_LOG_2_PI_DIV_2 - fastlog(sigma));\n    float part2 = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part2 += sq(xs[i] - mu) / (2 * sq(sigma));\n    }\n\n    return part1 - part2;\n}\n\n\ndouble NormalLogPdf::f(double mu, double sigma, const double x)\n{\n    double part1 = NEG_LOG_2_PI_DIV_2 - fastlog(sigma);\n    double part2 = sq(x - mu) / (2 * sq(sigma));\n    return part1 - part2;\n}\n\n\ndouble NormalLogPdf::df_dx(double mu, double sigma, const double x)\n{\n    return (mu - x) / sq(sigma);\n}\n\n\ndouble NormalLogPdf::df_dx(double mu, double sigma, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += mu - xs[i];\n    }\n    return part / sq(sigma);\n}\n\n\ndouble NormalLogPdf::df_dmu(double mu, double sigma, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += xs[i] - mu;\n    }\n    return part / sq(sigma);\n}\n\n\nfloat NormalLogPdf::df_dmu(float mu, float sigma, const float* xs, size_t n)\n{\n    float part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += xs[i] - mu;\n    }\n    return part / sq(sigma);\n}\n\n\ndouble NormalLogPdf::df_dsigma(double mu, double sigma, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += sq(xs[i] - mu);\n    }\n\n    return part / cb(sigma) - n/sigma;\n}\n\n\nfloat NormalLogPdf::df_dsigma(float mu, float sigma, const float* xs, size_t n)\n{\n    float part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += sq(xs[i] - mu);\n    }\n\n    return part / cb(sigma) - n/sigma;\n}\n\n\ndouble LogNormalLogPdf::f(double mu, double sigma, const double* xs, size_t n)\n{\n    double part1 = n * (NEG_LOG_2_PI_DIV_2 - fastlog(sigma));\n    double part2 = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        double logx = fastlog(xs[i]);\n        part2 += sq(logx - mu) / (2 * sq(sigma)) + logx;\n    }\n\n    return part1 - part2;\n}\n\n\ndouble LogNormalLogPdf::df_dx(double mu, double sigma, double x)\n{\n    return (mu - fastlog(x)) / (x * sq(sigma)) - 1.0 / x;\n}\n\n\ndouble LogNormalLogPdf::df_dmu(double mu, double sigma, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += fastlog(xs[i]) - mu;\n    }\n    return part / sq(sigma);\n}\n\n\ndouble LogNormalLogPdf::df_dsigma(double mu, double sigma, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += sq(fastlog(xs[i]) - mu);\n    }\n\n    return part / cb(sigma) - n/sigma;\n}\n\n\n#if 0\ndouble StudentsTLogPdf::f(double nu, double mu, double sigma, const double* xs, size_t n)\n{\n    double part1 =\n        n * (lgamma((nu + 1) / 2) - lgamma(nu / 2) - fastlog(sqrt(nu * M_PI) * sigma));\n\n    double part2 = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part2 += log1p(sq((xs[i] - mu) / sigma) / nu);\n    }\n\n    return part1 - ((nu + 1) / 2) * part2;\n}\n\n\nfloat StudentsTLogPdf::f(float nu, float mu, float sigma, const float* xs, size_t n)\n{\n    float part1 =\n        n * (lgammaf((nu + 1) / 2) - lgamma(nu / 2) - fastlog(sqrt(nu * M_PI) * sigma));\n\n    float part2 = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part2 += log1p(sq((xs[i] - mu) / sigma) / nu);\n    }\n\n    return part1 - ((nu + 1) / 2) * part2;\n}\n\n\ndouble StudentsTLogPdf::df_dx(double nu, double mu, double sigma, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += (2 * (xs[i] - mu) / sq(sigma) / nu) / (1 + sq((xs[i] - mu) / sigma) / nu);\n    }\n\n    return -((nu + 1) / 2) * part;\n}\n\n\ndouble StudentsTLogPdf::df_dmu(double nu, double mu, double sigma, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += (2 * (xs[i] - mu) / sq(sigma) / nu) / (1 + sq((xs[i] - mu) / sigma) / nu);\n    }\n\n    return ((nu + 1) / 2) * part;\n}\n\n\nfloat StudentsTLogPdf::df_dmu(float nu, float mu, float sigma, const float* xs, size_t n)\n{\n    float part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += (2 * (xs[i] - mu) / sq(sigma) / nu) / (1 + sq((xs[i] - mu) / sigma) / nu);\n    }\n\n    return ((nu + 1) / 2) * part;\n}\n\n\ndouble StudentsTLogPdf::df_dsigma(double nu, double mu, double sigma, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += (2 * sq((xs[i] - mu) / sigma) / (nu * sigma)) /\n                    (1 + sq((xs[i] - mu) / sigma) / nu);\n    }\n\n    return ((nu + 1) / 2) * part - n / sigma;\n}\n#endif\n\n\n#if 0\ndouble GammaLogPdf::f(double alpha, double beta, const double* xs, size_t n)\n{\n    double part1 = 0.0, part2 = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part1 += fastlog(xs[i]);\n        part2 += xs[i];\n    }\n\n    return\n        n * (alpha * fastlog(beta) - lgamma(alpha)) +\n        (alpha - 1) * part1 -\n        beta * part2;\n}\n\n\nfloat GammaLogPdf::f(float alpha, float beta, const float* xs, size_t n)\n{\n    float part1 = 0.0, part2 = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part1 += fastlog(xs[i]);\n        part2 += xs[i];\n    }\n\n    return\n        n * (alpha * fastlog(beta) - lgammaf(alpha)) +\n        (alpha - 1) * part1 -\n        beta * part2;\n}\n\n\ndouble GammaLogPdf::df_dx(double alpha, double beta, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += (alpha - 1) / xs[i];\n    }\n\n    return part - n * beta;\n}\n\n\ndouble GammaLogPdf::df_dalpha(double alpha, double beta, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += fastlog(xs[i]);\n    }\n\n    return n * (fastlog(beta) - boost::math::digamma(alpha)) + part;\n}\n\n\ndouble GammaLogPdf::df_dbeta(double alpha, double beta, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += xs[i];\n    }\n\n    return (double) n * (alpha / beta) - part;\n}\n\n\nfloat GammaLogPdf::df_dbeta(float alpha, float beta, const float* xs, size_t n)\n{\n    float part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += xs[i];\n    }\n\n    return (float) n * (alpha / beta) - part;\n}\n#endif\n\n\n#if 0\ndouble AltGammaLogPdf::f(double mean, double shape, const double* xs, size_t n)\n{\n    double scale =  mean / shape;\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += (shape - 1.0) * fastlog(xs[i]) - xs[i] / scale;\n    }\n\n    double ans = -(double) n * (lgamma(shape) + shape * fastlog(scale)) + part;\n    assert_finite(ans);\n    return ans;\n}\n\n\nfloat AltGammaLogPdf::f(float mean, float shape, const float* xs, size_t n)\n{\n    float scale =  mean / shape;\n    float part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += (shape - 1.0) * fastlog(xs[i]) - xs[i] / scale;\n    }\n\n    float ans = -(float) n * (lgammaf(shape) + shape * fastlog(scale)) + part;\n    assert_finite(ans);\n    return ans;\n}\n\n\ndouble AltGammaLogPdf::f(double mean, double shape, double x)\n{\n    double scale =  mean / shape;\n    double part = (shape - 1.0) * fastlog(x) - x / scale;\n    return -(lgamma(shape) + shape * fastlog(scale)) + part;\n}\n\n\nfloat AltGammaLogPdf::f(float mean, float shape, float x)\n{\n    float scale =  mean / shape;\n    float part = (shape - 1.0) * fastlog(x) - x / scale;\n    return -(lgammaf(shape) + shape * fastlog(scale)) + part;\n}\n\n\n\ndouble AltGammaLogPdf::df_dx(double mean, double shape, const double* xs, size_t n)\n{\n    double scale = mean / shape;\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += (shape - 1.0) / xs[i];\n    }\n\n    return part - (double) n / scale;\n}\n\n\ndouble AltGammaLogPdf::df_dx(double mean, double shape, double x)\n{\n    double scale = mean / shape;\n    double part = (shape - 1.0) / x;\n    return part - 1.0 / scale;\n}\n\n\ndouble AltGammaLogPdf::df_dmean(double mean, double shape, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += xs[i];\n    }\n    part *= shape / sq(mean);\n    return part - (double) n * shape / mean;\n}\n\n\nfloat AltGammaLogPdf::df_dmean(float mean, float shape, const float* xs, size_t n)\n{\n    float part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += xs[i];\n    }\n    part *= shape / sq(mean);\n    return part - (float) n * shape / mean;\n}\n\n\ndouble AltGammaLogPdf::df_dshape(double mean, double shape, const double* xs, size_t n)\n{\n    double scale = mean / shape;\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += fastlog(xs[i]) - xs[i] / mean;\n    }\n\n    return (double) n * (-boost::math::digamma(shape) + fastlog(scale) * (mean/sq(shape))) + part;\n}\n\n\nfloat AltGammaLogPdf::df_dshape(float mean, float shape, const float* xs, size_t n)\n{\n    float scale = mean / shape;\n    float part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += fastlog(xs[i]) - xs[i] / mean;\n    }\n\n    return (float) n * (-boost::math::digamma(shape) + fastlog(scale) * (mean/sq(shape))) + part;\n}\n\n\nfloat AltGammaLogPdf::df_dshape(float mean, float shape, float x)\n{\n    float scale = mean / shape;\n    float part = fastlog(x) - x / mean;\n    return (-boost::math::digamma(shape) + fastlog(scale) * (mean/sq(shape))) + part;\n}\n#endif\n\n\ndouble InvGammaLogPdf::f(double alpha, double beta, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += (alpha + 1) * fastlog(xs[i]) + beta / xs[i];\n    }\n\n    return n * (alpha * fastlog(beta) - lgamma(alpha)) - part;\n}\n\n\ndouble InvGammaLogPdf::df_dx(double alpha, double beta, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += beta / sq(xs[i]) - (alpha + 1) / xs[i];\n    }\n\n    return part;\n}\n\n\ndouble InvGammaLogPdf::df_dalpha(double alpha, double beta, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += fastlog(xs[i]);\n    }\n\n    return n * (fastlog(beta) - boost::math::digamma(alpha)) - part;\n}\n\n\ndouble InvGammaLogPdf::df_dbeta(double alpha, double beta, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += 1 / xs[i];\n    }\n\n    return n * (alpha / beta) - part;\n}\n\n\ndouble SqInvGammaLogPdf::f(double alpha, double beta, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        double x = xs[i] * xs[i];\n        part += (alpha + 1) * fastlog(x) + beta / x;\n    }\n\n    return n * (alpha * fastlog(beta) - lgamma(alpha)) - part;\n}\n\n\ndouble SqInvGammaLogPdf::df_dx(double alpha, double beta, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        part += 2 * beta / cb(xs[i]) - (2 * alpha + 2) / xs[i];\n    }\n\n    return part;\n}\n\n\ndouble SqInvGammaLogPdf::df_dalpha(double alpha, double beta, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        double x = xs[i] * xs[i];\n        part += fastlog(x);\n    }\n\n    return n * (fastlog(beta) - boost::math::digamma(alpha)) - part;\n}\n\n\ndouble SqInvGammaLogPdf::df_dbeta(double alpha, double beta, const double* xs, size_t n)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        double x = xs[i] * xs[i];\n        part += 1 / x;\n    }\n\n    return n * (alpha / beta) - part;\n}\n\n\ndouble BetaLogPdf::f(double alpha, double beta, double x)\n{\n    return (alpha - 1) * fastlog(x) + (beta - 1) * fastlog(1 - x) - lbeta(alpha, beta);\n}\n\n\ndouble BetaLogPdf::df_dx(double alpha, double beta, double x)\n{\n    return (alpha - 1) / x - (beta - 1) / (1 - x);\n}\n\n\ndouble BetaLogPdf::df_dgamma(double gamma, double c, double x)\n{\n    return c * (fastlog(x / (1 - x)) -\n                boost::math::digamma(gamma * c) +\n                boost::math::digamma((1 - gamma) * c));\n}\n\n\ndouble DirichletLogPdf::f(double alpha,\n                          const boost::numeric::ublas::matrix<double>* mean,\n                          const boost::numeric::ublas::matrix<double>* data,\n                          size_t n, size_t m)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        for (size_t j = 0; j < m; ++j) {\n            double am = alpha * (*mean)(i, j);\n            part += (am - 1) * fastlog((*data)(i, j)) - lgamma(am);\n        }\n    }\n\n    return n * lgamma(alpha) + part;\n}\n\n\ndouble DirichletLogPdf::df_dalpha(double alpha,\n                                  const boost::numeric::ublas::matrix<double>* mean,\n                                  const boost::numeric::ublas::matrix<double>* data,\n                                  size_t n, size_t m)\n{\n    double part = 0.0;\n    for (size_t i = 0; i < n; ++i) {\n        for (size_t j = 0; j < m; ++j) {\n            part += (*mean)(i, j) * (fastlog((*data)(i, j)) -\n                                     boost::math::digamma(alpha * (*mean)(i, j)));\n        }\n    }\n\n    return n * boost::math::digamma(alpha) + part;\n}\n\n\ndouble LogisticNormalLogPdf::f(double mu, double sigma, double x)\n{\n    return -fastlog(sigma) - fastlog(sqrt(2*M_PI)) -\n           sq(fastlog(x / (1 - x)) - mu) / (2 * sq(sigma)) -\n           fastlog(x) - fastlog(1-x);\n}\n\n\ndouble LogisticNormalLogPdf::df_dx(double mu, double sigma, double x)\n{\n    double y = fastlog(x / (1 - x));\n    return (1/(1-x)) - (1/x) - (mu - y) / (sq(sigma) * (x - 1) * x);\n}\n\n\n", "meta": {"hexsha": "65ce9a425a85a24cb82d4c1ebba08dd8986fe5a1", "size": 19941, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/shredder.cpp", "max_stars_repo_name": "dcjones/isolator", "max_stars_repo_head_hexsha": "24bafc0a102dce213bfc2b5b9744136ceadaba03", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 33.0, "max_stars_repo_stars_event_min_datetime": "2015-07-13T03:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T08:49:07.000Z", "max_issues_repo_path": "src/shredder.cpp", "max_issues_repo_name": "dcjones/isolator", "max_issues_repo_head_hexsha": "24bafc0a102dce213bfc2b5b9744136ceadaba03", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2016-11-29T00:04:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-10T17:46:01.000Z", "max_forks_repo_path": "src/shredder.cpp", "max_forks_repo_name": "dcjones/isolator", "max_forks_repo_head_hexsha": "24bafc0a102dce213bfc2b5b9744136ceadaba03", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T15:49:34.000Z", "max_forks_repo_forks_event_max_datetime": "2017-03-09T05:14:06.000Z", "avg_line_length": 24.7406947891, "max_line_length": 98, "alphanum_fraction": 0.5544857329, "num_tokens": 6271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.40144067489288116}}
{"text": "// Copyright (c) 2022 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#pragma once\n#include <Eigen/Core>\n#include <memory>\n\n#include \"pyinterp/detail/math.hpp\"\n#include \"pyinterp/eigen.hpp\"\n\nnamespace pyinterp::detail::math {\n\n/// Set of coordinates used for interpolation\nclass CoordsXY {\n public:\n  /// Default constructor\n  CoordsXY() = delete;\n\n  /// Creates a new instance\n  CoordsXY(const Eigen::Index x_size, const Eigen::Index y_size)\n      : x_(new Eigen::VectorXd), y_(new Eigen::VectorXd) {\n    auto nx = x_size << 1U;\n    auto ny = y_size << 1U;\n    x_->resize(nx);\n    y_->resize(ny);\n  }\n\n  /// Creates a new instance from existing coordinates\n  CoordsXY(std::shared_ptr<Eigen::VectorXd> x,\n           std::shared_ptr<Eigen::VectorXd> y)\n      : x_(std::move(x)), y_(std::move(y)) {}\n\n  /// Default destructor\n  virtual ~CoordsXY() = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  CoordsXY(const CoordsXY &rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  CoordsXY(CoordsXY &&rhs) noexcept = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const CoordsXY &rhs) -> CoordsXY & = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(CoordsXY &&rhs) noexcept -> CoordsXY & = default;\n\n  /// Get the half size of the window in abscissa.\n  [[nodiscard]] inline auto nx() const noexcept -> Eigen::Index {\n    return x_->size() >> 1;\n  }\n\n  /// Get the half size of the window in ordinate.\n  [[nodiscard]] inline auto ny() const noexcept -> Eigen::Index {\n    return y_->size() >> 1;\n  }\n\n  /// Get x-coordinates\n  constexpr auto x() noexcept -> std::shared_ptr<Eigen::VectorXd> & {\n    return x_;\n  }\n\n  /// Get x-coordinates\n  [[nodiscard]] constexpr auto x() const noexcept\n      -> const std::shared_ptr<Eigen::VectorXd> & {\n    return x_;\n  }\n\n  /// Get y-coordinates\n  constexpr auto y() noexcept -> std::shared_ptr<Eigen::VectorXd> & {\n    return y_;\n  }\n\n  /// Get y-coordinates\n  [[nodiscard]] constexpr auto y() const noexcept\n      -> const std::shared_ptr<Eigen::VectorXd> & {\n    return y_;\n  }\n\n  /// Get the ith x-axis.\n  [[nodiscard]] inline auto x(const Eigen::Index ix) const -> double {\n    return (*x_)(ix);\n  }\n\n  /// Get the ith y-axis.\n  [[nodiscard]] inline auto y(const Eigen::Index jx) const -> double {\n    return (*y_)(jx);\n  }\n\n  /// Set the ith x-axis.\n  inline auto x(const Eigen::Index ix) -> double & { return (*x_)(ix); }\n\n  /// Get the ith y-axis.\n  inline auto y(const Eigen::Index jx) -> double & { return (*y_)(jx); }\n\n  /// Normalizes the angle with respect to the first value of the X axis of this\n  /// array.\n  [[nodiscard]] inline auto normalize_angle(const double xi) const -> double {\n    return math::normalize_angle(xi, (*x_)(0), 360.0);\n  }\n\n private:\n  std::shared_ptr<Eigen::VectorXd> x_{};\n  std::shared_ptr<Eigen::VectorXd> y_{};\n};\n\n/// Set of coordinates/values used for interpolation\n///  * q11 = (x1, y1)\n///  * q12 = (x1, y2)\n///  * .../...\n///  * q1n = (x1, yn)\n///  * q21 = (x2, y1)\n///  * q22 = (x2, y2).\n///  * .../...\n///  * q2n = (x2, yn)\n///  * .../...\n///  * qnn = (xn, yn)\n///\n/// @code\n/// Array2D({{x1, x2, ..., xn}, {y1, y2, ..., yn}},\n///         {q11, q12, ..., q21, q22, ...., qnn})\n/// @endcode\nclass Frame2D : public CoordsXY {\n public:\n  /// Default constructor\n  Frame2D() = delete;\n\n  /// Creates a new Array\n  Frame2D(const Eigen::Index x_size, const Eigen::Index y_size)\n      : CoordsXY(x_size, y_size), q_(new Eigen::MatrixXd) {\n    q_->resize(x()->size(), y()->size());\n  }\n\n  /// Creates a new Array from existing coordinates/values\n  Frame2D(std::shared_ptr<Eigen::VectorXd> x,\n          std::shared_ptr<Eigen::VectorXd> y,\n          std::shared_ptr<Eigen::MatrixXd> q)\n      : CoordsXY(std::move(x), std::move(y)), q_(std::move(q)) {}\n\n  /// Default destructor\n  ~Frame2D() override = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  Frame2D(const Frame2D &rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  Frame2D(Frame2D &&rhs) noexcept = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const Frame2D &rhs) -> Frame2D & = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(Frame2D &&rhs) noexcept -> Frame2D & = default;\n\n  /// Get the values from the array for all x and y coordinates.\n  constexpr auto q() noexcept -> std::shared_ptr<Eigen::MatrixXd> & {\n    return q_;\n  }\n\n  /// Get the values from the array for all x and y coordinates.\n  [[nodiscard]] constexpr auto q() const noexcept\n      -> const std::shared_ptr<Eigen::MatrixXd> & {\n    return q_;\n  }\n\n  /// Get the value at coordinate (ix, jx).\n  [[nodiscard]] inline auto q(const Eigen::Index ix,\n                              const Eigen::Index jx) const -> double {\n    return (*q_)(ix, jx);\n  }\n\n  /// Get the value at coordinate (ix, jx).\n  inline auto q(const Eigen::Index ix, const Eigen::Index jx) -> double & {\n    return (*q_)(ix, jx);\n  }\n\n  /// Returns true if this instance does not contains at least one Not A Number\n  /// (NaN).\n  [[nodiscard]] inline auto is_valid() const -> bool { return !q_->hasNaN(); }\n\n private:\n  std::shared_ptr<Eigen::MatrixXd> q_{};\n};\n\n/// Set of coordinates/values used for 3D-interpolation\n///\n/// @tparam Z-Axis type\ntemplate <typename T>\nclass Frame3D : public CoordsXY {\n public:\n  /// Default constructor\n  Frame3D() = delete;\n\n  /// Creates a new instance\n  Frame3D(const Eigen::Index x_size, const Eigen::Index y_size,\n          const Eigen::Index z_size)\n      : CoordsXY(x_size, y_size), z_() {\n    auto nz = z_size << 1U;\n    z_.resize(nz);\n    q_.resize(nz);\n\n    for (auto iz = 0U; iz < nz; ++iz) {\n      q_(iz) = std::make_shared<Eigen::MatrixXd>(x()->size(), y()->size());\n    }\n  }\n\n  /// Get the set of coordinates/values for the ith z-layer\n  [[nodiscard]] auto frame_2d(const Eigen::Index iz) const -> Frame2D {\n    return Frame2D(x(), y(), q_(iz));\n  }\n\n  /// Default destructor\n  ~Frame3D() override = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  Frame3D(const Frame3D &rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  Frame3D(Frame3D &&rhs) noexcept = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const Frame3D &rhs) -> Frame3D & = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(Frame3D &&rhs) noexcept -> Frame3D & = default;\n\n  /// Get the half size of the window in z.\n  [[nodiscard]] inline auto nz() const noexcept -> Eigen::Index {\n    return z_.size() >> 1;\n  }\n\n  /// Get z-coordinates\n  constexpr auto z() noexcept -> Vector<T> & { return z_; }\n\n  /// Get z-coordinates\n  [[nodiscard]] constexpr auto z() const noexcept -> const Vector<T> & {\n    return z_;\n  }\n\n  /// Get the ith z-axis.\n  [[nodiscard]] inline auto z(const Eigen::Index ix) const -> T {\n    return z_(ix);\n  }\n\n  /// Set the ith z-axis.\n  inline auto z(const Eigen::Index ix) -> T & { return z_(ix); }\n\n  /// Get the value at coordinate (ix, jx, kx).\n  inline auto q(const Eigen::Index ix, const Eigen::Index jx,\n                const Eigen::Index kx) -> double & {\n    return (*q_(kx))(ix, jx);\n  }\n\n  /// Returns true if this instance does not contains at least one Not A Number\n  /// (NaN).\n  [[nodiscard]] inline auto is_valid() const -> bool {\n    for (Eigen::Index kx = 0; kx < q_.size(); ++kx) {\n      if ((*q_(kx)).hasNaN()) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n private:\n  Vector<T> z_;\n  Vector<std::shared_ptr<Eigen::MatrixXd>> q_;\n};\n\n/// Set of coordinates/values used for 4D-interpolation\n///\n/// @tparam Z-Axis type\ntemplate <typename T>\nclass Frame4D : public CoordsXY {\n public:\n  /// Default constructor\n  Frame4D() = delete;\n\n  /// Creates a new instance\n  Frame4D(const Eigen::Index x_size, const Eigen::Index y_size,\n          const Eigen::Index z_size, const Eigen::Index u_size)\n      : CoordsXY(x_size, y_size), z_() {\n    auto nz = z_size << 1U;\n    auto nu = u_size << 1U;\n    z_.resize(nz);\n    u_.resize(nu);\n    q_.resize(nz, nu);\n\n    for (auto iz = 0U; iz < nz; ++iz) {\n      for (auto iu = 0U; iu < nu; ++iu) {\n        q_(iz, iu) =\n            std::make_shared<Eigen::MatrixXd>(x()->size(), y()->size());\n      }\n    }\n  }\n\n  /// Get the set of coordinates/values for the ith z-layer\n  [[nodiscard]] auto frame_2d(const Eigen::Index iz,\n                              const Eigen::Index iu) const -> Frame2D {\n    return Frame2D(x(), y(), q_(iz, iu));\n  }\n\n  /// Default destructor\n  ~Frame4D() override = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  Frame4D(const Frame4D &rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  Frame4D(Frame4D &&rhs) noexcept = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const Frame4D &rhs) -> Frame4D & = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(Frame4D &&rhs) noexcept -> Frame4D & = default;\n\n  /// Get the half size of the window in z.\n  [[nodiscard]] inline auto nz() const noexcept -> Eigen::Index {\n    return z_.size() >> 1;\n  }\n\n  /// Get the half size of the window in u.\n  [[nodiscard]] inline auto nu() const noexcept -> Eigen::Index {\n    return u_.size() >> 1;\n  }\n\n  /// Get z-coordinates\n  constexpr auto z() noexcept -> Vector<T> & { return z_; }\n\n  /// Get u-coordinates\n  constexpr auto u() noexcept -> Eigen::VectorXd & { return u_; }\n\n  /// Get z-coordinates\n  [[nodiscard]] inline auto z() const noexcept -> const Vector<T> & {\n    return z_;\n  }\n\n  /// Get u-coordinates\n  [[nodiscard]] inline auto u() const noexcept -> const Eigen::VectorXd & {\n    return u_;\n  }\n\n  /// Get the ith z-axis.\n  [[nodiscard]] inline auto z(const Eigen::Index ix) const -> T {\n    return z_(ix);\n  }\n\n  /// Get the ith u-axis.\n  [[nodiscard]] inline auto u(const Eigen::Index ix) const -> double {\n    return u_(ix);\n  }\n\n  /// Set the ith z-axis.\n  inline auto z(const Eigen::Index ix) -> T & { return z_(ix); }\n\n  /// Set the ith u-axis.\n  inline auto u(const Eigen::Index ix) -> double & { return u_(ix); }\n\n  /// Get the value at coordinate (ix, jx, kx, lx).\n  inline auto q(const Eigen::Index ix, const Eigen::Index jx,\n                const Eigen::Index kx, const Eigen::Index lx) -> double & {\n    return (*q_(kx, lx))(ix, jx);\n  }\n\n  /// Returns true if this instance does not contains at least one Not A Number\n  /// (NaN).\n  [[nodiscard]] inline auto is_valid() const -> bool {\n    for (Eigen::Index kx = 0; kx < z_.size(); ++kx) {\n      for (Eigen::Index lx = 0; lx < u_.size(); ++lx) {\n        if ((*q_(kx, lx)).hasNaN()) {\n          return false;\n        }\n      }\n    }\n    return true;\n  }\n\n private:\n  Vector<T> z_;\n  Eigen::VectorXd u_;\n  Matrix<std::shared_ptr<Eigen::MatrixXd>> q_;\n};\n\n}  // namespace pyinterp::detail::math", "meta": {"hexsha": "053d2da23ce5545b708672d8a7da1e65f2dca48d", "size": 11086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/frame.hpp", "max_stars_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_stars_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/frame.hpp", "max_issues_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_issues_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/frame.hpp", "max_forks_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_forks_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5215311005, "max_line_length": 80, "alphanum_fraction": 0.6030128089, "num_tokens": 3167, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.4013498178503709}}
{"text": "#ifndef FLOW_H_\n#define FLOW_H_\n\n#include <Eigen/Core>\n#include <list>\n#include <map>\n#include <vector>\n\n#include \"qflow/config.hpp\"\n\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n#include <boost/graph/edmonds_karp_max_flow.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n\n#include <lemon/network_simplex.h>\n#include <lemon/preflow.h>\n#include <lemon/smart_graph.h>\n\nusing namespace boost;\nusing namespace Eigen;\n\nnamespace qflow {\n\nclass MaxFlowHelper {\n   public:\n    MaxFlowHelper() {}\n    virtual ~MaxFlowHelper(){};\n    virtual void resize(int n, int m) = 0;\n    virtual void addEdge(int x, int y, int c, int rc, int v, int cost = 1) = 0;\n    virtual int compute() = 0;\n    virtual void applyTo(std::vector<Vector2i>& edge_diff) = 0;\n};\n\nclass BoykovMaxFlowHelper : public MaxFlowHelper {\n   public:\n    typedef int EdgeWeightType;\n    typedef adjacency_list_traits<vecS, vecS, directedS> Traits;\n    // clang-format off\n    typedef adjacency_list < vecS, vecS, directedS,\n        property < vertex_name_t, std::string,\n        property < vertex_index_t, long,\n        property < vertex_color_t, boost::default_color_type,\n        property < vertex_distance_t, long,\n        property < vertex_predecessor_t, Traits::edge_descriptor > > > > >,\n\n        property < edge_capacity_t, EdgeWeightType,\n        property < edge_residual_capacity_t, EdgeWeightType,\n        property < edge_reverse_t, Traits::edge_descriptor > > > > Graph;\n    // clang-format on\n\n   public:\n    BoykovMaxFlowHelper() { rev = get(edge_reverse, g); }\n    void resize(int n, int m) {\n        vertex_descriptors.resize(n);\n        for (int i = 0; i < n; ++i) vertex_descriptors[i] = add_vertex(g);\n    }\n    int compute() {\n        EdgeWeightType flow =\n            boykov_kolmogorov_max_flow(g, vertex_descriptors.front(), vertex_descriptors.back());\n        return flow;\n    }\n    void addDirectEdge(Traits::vertex_descriptor& v1, Traits::vertex_descriptor& v2,\n                       property_map<Graph, edge_reverse_t>::type& rev, const int capacity,\n                       const int inv_capacity, Graph& g, Traits::edge_descriptor& e1,\n                       Traits::edge_descriptor& e2) {\n        e1 = add_edge(v1, v2, g).first;\n        e2 = add_edge(v2, v1, g).first;\n        put(edge_capacity, g, e1, capacity);\n        put(edge_capacity, g, e2, inv_capacity);\n\n        rev[e1] = e2;\n        rev[e2] = e1;\n    }\n    void addEdge(int x, int y, int c, int rc, int v, int cost = 1) {\n        Traits::edge_descriptor e1, e2;\n        addDirectEdge(vertex_descriptors[x], vertex_descriptors[y], rev, c, rc, g, e1, e2);\n        if (v != -1) {\n            edge_to_variables[e1] = std::make_pair(v, -1);\n            edge_to_variables[e2] = std::make_pair(v, 1);\n        }\n    }\n    void applyTo(std::vector<Vector2i>& edge_diff) {\n        property_map<Graph, edge_capacity_t>::type capacity = get(edge_capacity, g);\n        property_map<Graph, edge_residual_capacity_t>::type residual_capacity =\n            get(edge_residual_capacity, g);\n\n        graph_traits<Graph>::vertex_iterator u_iter, u_end;\n        graph_traits<Graph>::out_edge_iterator ei, e_end;\n        for (tie(u_iter, u_end) = vertices(g); u_iter != u_end; ++u_iter)\n            for (tie(ei, e_end) = out_edges(*u_iter, g); ei != e_end; ++ei)\n                if (capacity[*ei] > 0) {\n                    int flow = (capacity[*ei] - residual_capacity[*ei]);\n                    if (flow > 0) {\n                        auto it = edge_to_variables.find(*ei);\n                        if (it != edge_to_variables.end()) {\n                            edge_diff[it->second.first / 2][it->second.first % 2] +=\n                                it->second.second * flow;\n                        }\n                    }\n                }\n    }\n\n   private:\n    Graph g;\n    property_map<Graph, edge_reverse_t>::type rev;\n    std::vector<Traits::vertex_descriptor> vertex_descriptors;\n    std::map<Traits::edge_descriptor, std::pair<int, int>> edge_to_variables;\n};\n\nclass NetworkSimplexFlowHelper : public MaxFlowHelper {\n   public:\n    using Weight = int;\n    using Capacity = int;\n    using Graph = lemon::SmartDigraph;\n    using Node = Graph::Node;\n    using Arc = Graph::Arc;\n    template <typename ValueType>\n    using ArcMap = lemon::SmartDigraph::ArcMap<ValueType>;\n    using Preflow = lemon::Preflow<lemon::SmartDigraph, ArcMap<Capacity>>;\n    using NetworkSimplex = lemon::NetworkSimplex<lemon::SmartDigraph, Capacity, Weight>;\n\n   public:\n    NetworkSimplexFlowHelper() : cost(graph), capacity(graph), flow(graph), variable(graph) {}\n    ~NetworkSimplexFlowHelper(){};\n    void resize(int n, int m) {\n        nodes.reserve(n);\n        for (int i = 0; i < n; ++i) nodes.push_back(graph.addNode());\n    }\n    void addEdge(int x, int y, int c, int rc, int v, int cst = 1) {\n        assert(x >= 0);\n        assert(v >= -1);\n        if (c) {\n            auto e1 = graph.addArc(nodes[x], nodes[y]);\n            cost[e1] = cst;\n            capacity[e1] = c;\n            variable[e1] = std::make_pair(v, 1);\n        }\n\n        if (rc) {\n            auto e2 = graph.addArc(nodes[y], nodes[x]);\n            cost[e2] = cst;\n            capacity[e2] = rc;\n            variable[e2] = std::make_pair(v, -1);\n        }\n    }\n    int compute() {\n        Preflow pf(graph, capacity, nodes.front(), nodes.back());\n        NetworkSimplex ns(graph);\n\n        // Run preflow to find maximum flow\n        lprintf(\"push-relabel flow... \");\n        pf.runMinCut();\n        int maxflow = pf.flowValue();\n\n        // Run network simplex to find minimum cost maximum flow\n        ns.costMap(cost).upperMap(capacity).stSupply(nodes.front(), nodes.back(), maxflow);\n        auto status = ns.run();\n        switch (status) {\n            case NetworkSimplex::OPTIMAL:\n                ns.flowMap(flow);\n                break;\n            case NetworkSimplex::INFEASIBLE:\n                lputs(\"NetworkSimplex::INFEASIBLE\");\n                assert(0);\n                break;\n            default:\n                lputs(\"Unknown: NetworkSimplex::Default\");\n                assert(0);\n                break;\n        }\n\n        return maxflow;\n    }\n    void applyTo(std::vector<Vector2i>& edge_diff) {\n        for (Graph::ArcIt e(graph); e != lemon::INVALID; ++e) {\n            int var = variable[e].first;\n            if (var == -1) continue;\n            int sgn = variable[e].second;\n            edge_diff[var / 2][var % 2] -= sgn * flow[e];\n        }\n    }\n\n   private:\n    Graph graph;\n    ArcMap<Weight> cost;\n    ArcMap<Capacity> capacity;\n    ArcMap<Capacity> flow;\n    ArcMap<std::pair<int, int>> variable;\n    std::vector<Node> nodes;\n    std::vector<Arc> edges;\n};\n\n#ifdef WITH_GUROBI\n\n#include <gurobi_c++.h>\n\nclass GurobiFlowHelper : public MaxFlowHelper {\n   public:\n    GurobiFlowHelper() {}\n    virtual ~GurobiFlowHelper(){};\n    virtual void resize(int n, int m) {\n        nodes.resize(n * 2);\n        edges.resize(m);\n    }\n    virtual void addEdge(int x, int y, int c, int rc, int v, int cost = 1) {\n        nodes[x * 2 + 0].push_back(vars.size());\n        nodes[y * 2 + 1].push_back(vars.size());\n        vars.push_back(model.addVar(0, c, 0, GRB_INTEGER));\n        edges.push_back(std::make_pair(v, 1));\n\n        nodes[y * 2 + 0].push_back(vars.size());\n        nodes[x * 2 + 1].push_back(vars.size());\n        vars.push_back(model.addVar(0, rc, 0, GRB_INTEGER));\n        edges.push_back(std::make_pair(v, -1));\n    }\n    virtual int compute() {\n        std::cerr << \"compute\" << std::endl;\n        int ns = nodes.size() / 2;\n\n        int flow;\n        for (int i = 1; i < ns - 1; ++i) {\n            GRBLinExpr cons = 0;\n            for (auto n : nodes[2 * i + 0]) cons += vars[n];\n            for (auto n : nodes[2 * i + 1]) cons -= vars[n];\n            model.addConstr(cons == 0);\n        }\n\n        // first pass, maximum flow\n        GRBLinExpr outbound = 0;\n        {\n            lprintf(\"first pass\\n\");\n            for (auto& n : nodes[0]) outbound += vars[n];\n            for (auto& n : nodes[1]) outbound -= vars[n];\n            model.setObjective(outbound, GRB_MAXIMIZE);\n            model.optimize();\n\n            flow = (int)model.get(GRB_DoubleAttr_ObjVal);\n            lprintf(\"Gurobi result: %d\\n\", flow);\n        }\n\n        // second pass, minimum cost flow\n        {\n            lprintf(\"second pass\\n\");\n            model.addConstr(outbound == flow);\n            GRBLinExpr cost = 0;\n            for (auto& v : vars) cost += v;\n            model.setObjective(cost, GRB_MINIMIZE);\n            model.optimize();\n\n            double optimal_cost = (int)model.get(GRB_DoubleAttr_ObjVal);\n            lprintf(\"Gurobi result: %.3f\\n\", optimal_cost);\n        }\n        return flow;\n    }\n    virtual void applyTo(std::vector<Vector2i>& edge_diff) { assert(0); };\n\n   private:\n    GRBEnv env = GRBEnv();\n    GRBModel model = GRBModel(env);\n    std::vector<GRBVar> vars;\n    std::vector<std::pair<int, int>> edges;\n    std::vector<std::vector<int>> nodes;\n};\n\n#endif\n\nclass ECMaxFlowHelper : public MaxFlowHelper {\n   public:\n    struct FlowInfo {\n        int id;\n        int capacity, flow;\n        int v, d;\n        FlowInfo* rev;\n    };\n    struct SearchInfo {\n        SearchInfo(int _id, int _prev_id, FlowInfo* _info)\n            : id(_id), prev_id(_prev_id), info(_info) {}\n        int id;\n        int prev_id;\n        FlowInfo* info;\n    };\n    ECMaxFlowHelper() { num = 0; }\n    int num;\n    std::vector<FlowInfo*> variable_to_edge;\n    void resize(int n, int m) {\n        graph.resize(n);\n        variable_to_edge.resize(m, 0);\n        num = n;\n    }\n    void addEdge(int x, int y, int c, int rc, int v, int cost = 0) {\n        FlowInfo flow;\n        flow.id = y;\n        flow.capacity = c;\n        flow.flow = 0;\n        flow.v = v;\n        flow.d = -1;\n        graph[x].push_back(flow);\n        auto& f1 = graph[x].back();\n        flow.id = x;\n        flow.capacity = rc;\n        flow.flow = 0;\n        flow.v = v;\n        flow.d = 1;\n        graph[y].push_back(flow);\n        auto& f2 = graph[y].back();\n        f2.rev = &f1;\n        f1.rev = &f2;\n    }\n    int compute() {\n        int total_flow = 0;\n        int count = 0;\n        while (true) {\n            count += 1;\n            std::vector<int> vhash(num, 0);\n            std::vector<SearchInfo> q;\n            q.push_back(SearchInfo(0, -1, 0));\n            vhash[0] = 1;\n            int q_front = 0;\n            bool found = false;\n            while (q_front < q.size()) {\n                int vert = q[q_front].id;\n                for (auto& l : graph[vert]) {\n                    if (vhash[l.id] || l.capacity <= l.flow) continue;\n                    q.push_back(SearchInfo(l.id, q_front, &l));\n                    vhash[l.id] = 1;\n                    if (l.id == num - 1) {\n                        found = true;\n                        break;\n                    }\n                }\n                if (found) break;\n                q_front += 1;\n            }\n            if (q_front == q.size()) break;\n            int loc = q.size() - 1;\n            while (q[loc].prev_id != -1) {\n                q[loc].info->flow += 1;\n                q[loc].info->rev->flow -= 1;\n                loc = q[loc].prev_id;\n                // int prev_v = q[loc].id;\n                // applyFlow(prev_v, current_v, 1);\n                // applyFlow(current_v, prev_v, -1);\n            }\n            total_flow += 1;\n        }\n        return total_flow;\n    }\n    void applyTo(std::vector<Vector2i>& edge_diff) {\n        for (int i = 0; i < graph.size(); ++i) {\n            for (auto& flow : graph[i]) {\n                if (flow.flow > 0 && flow.v != -1) {\n                    if (flow.flow > 0) {\n                        edge_diff[flow.v / 2][flow.v % 2] += flow.d * flow.flow;\n                        if (abs(edge_diff[flow.v / 2][flow.v % 2]) > 2) {\n                        }\n                    }\n                }\n            }\n        }\n    }\n    void applyFlow(int v1, int v2, int flow) {\n        for (auto& it : graph[v1]) {\n            if (it.id == v2) {\n                it.flow += flow;\n                break;\n            }\n        }\n    }\n    std::vector<std::list<FlowInfo>> graph;\n};\n\n} // namespace qflow\n\n#endif\n", "meta": {"hexsha": "f3f4187ab804628edfc48fdbb0b9d852f636d2f7", "size": 12266, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/qflow/flow.hpp", "max_stars_repo_name": "matt-deboer/QuadriFlow", "max_stars_repo_head_hexsha": "cf07b472932c2fe7277de3800eb5b7a3eb46179f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/qflow/flow.hpp", "max_issues_repo_name": "matt-deboer/QuadriFlow", "max_issues_repo_head_hexsha": "cf07b472932c2fe7277de3800eb5b7a3eb46179f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/qflow/flow.hpp", "max_forks_repo_name": "matt-deboer/QuadriFlow", "max_forks_repo_head_hexsha": "cf07b472932c2fe7277de3800eb5b7a3eb46179f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6223404255, "max_line_length": 97, "alphanum_fraction": 0.5303277352, "num_tokens": 3206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.5660185351961013, "lm_q1q2_score": 0.40131796457066393}}
{"text": "/* Copyright (c) 2021 Grumpy Cat Software S.L.\n *\n * This Source Code is licensed under the MIT 2.0 license.\n * the terms can be found in  LICENSE.md at the root of\n * this project, or at http://mozilla.org/MPL/2.0/.\n */\n\n#include <gauss/dimensionality.h>\n#include <gauss/internal/scopedHostPtr.h>\n\n#include <algorithm>\n#include <boost/math/distributions/normal.hpp>\n#include <cmath>\n#include <iterator>\n#include <limits>\n#include <map>\n#include <numeric>\n#include <set>\n#include <stdexcept>\n#include <utility>\n#include <vector>\n\nusing namespace gauss::dimensionality;\n\nnamespace {\n\nstruct VisvalingamSummaryPoint {\n    float x;\n    float y;\n    int64_t area;\n};\n\nstd::vector<float> computeBreakpoints(int alphabet_size, float mean_value, float std_value) {\n    std::vector<float> res;\n    boost::math::normal dist(mean_value, std_value);\n\n    for (int i = 1; i < alphabet_size; i++) {\n        float value = static_cast<float>(quantile(dist, (float)i * (1 / (float)alphabet_size)));\n        res.push_back(value);\n    }\n    return res;\n}\n\nstd::vector<int> generateAlphabet(int alphabet_size) {\n    std::vector<int> res;\n    for (int i = 0; i < alphabet_size; i++) {\n        res.push_back(i);\n    }\n    return res;\n}\n\ndouble PerpendicularDistance(const Point &pt, const Point &lineStart, const Point &lineEnd) {\n    double dx = static_cast<double>(lineEnd.first) - lineStart.first;\n    double dy = static_cast<double>(lineEnd.second) - lineStart.second;\n\n    // Normalise\n    double mag = pow(pow(dx, 2.0) + pow(dy, 2.0), 0.5);\n    if (mag > 0.0) {\n        dx /= mag;\n        dy /= mag;\n    }\n\n    double pvx = static_cast<double>(pt.first) - lineStart.first;\n    double pvy = static_cast<double>(pt.second) - lineStart.second;\n\n    // Get dot product (project pv onto normalized direction)\n    double pvdot = dx * pvx + dy * pvy;\n\n    // Scale line direction vector\n    double dsx = pvdot * dx;\n    double dsy = pvdot * dy;\n\n    // Subtract this from pv\n    double ax = pvx - dsx;\n    double ay = pvy - dsy;\n\n    return pow(pow(ax, 2.0) + pow(ay, 2.0), 0.5);\n}\n\n/**\n * @brief We compute the vertical distance of the point p w.r.t. the line that connects start and end points.\n * We use the point-slope equiation to solve it.\n */\nfloat verticalDistance(const Point &p, const Point &start, const Point &end) {\n    float dy = end.second - start.second;\n    float dx = end.first - start.first;\n    float m = dy / dx;\n    float line_y = (p.first - start.first) * m + start.second;\n    return (p.second - line_y) * (p.second - line_y);\n}\n\n/**\n * @brief This function just inserts a point in the given position of a vector.\n */\nvoid insertPointBetweenSelected(const Point &p, int position, std::vector<Point> &selected) {\n    auto it = selected.begin();\n    selected.insert(it + position, p);\n}\n\n/**\n * @brief This function just checks if the given point is already in the vector.\n */\nbool isPointInDesiredList(const Point &point, const std::vector<Point> &selected) {\n    auto it =\n        std::find_if(selected.cbegin(), selected.cend(), [&point](const Point &p) { return p.first == point.first; });\n    return it != selected.end();\n}\n\n/**\n * @brief This function calculates the segment indices that we need to compare the point.\n */\nstd::pair<int, int> getSegmentFromSelected(const Point &point, const std::vector<Point> &selected) {\n    int lower = 0, upper = 0;\n    // We do not check the first element, as it is fixed and set to the first element of the time series\n    size_t i = 0;\n    bool rebased = false;\n    while (!rebased && (i < selected.size() - 1)) {\n        // We check points until point.first > selected[i]\n        if (point.first > selected[i].first) {\n            lower = static_cast<int>(i);\n            upper = static_cast<int>(i + 1);\n        } else {\n            rebased = true;\n        }\n        i++;\n    }\n    return std::make_pair(lower, upper);\n}\n\ntemplate <typename T>\naf::array PAA_CPU(const af::array &a, int bins) {\n    af::array result;\n    auto n = a.dims(0);\n\n    auto reducedColumn = std::vector<T>(bins);\n\n    // Find out the number of elements per bin\n    T elemPerBin = static_cast<T>(n) / static_cast<T>(bins);\n\n    // For each column\n    for (int i = 0; i < a.dims(1); i++) {\n        auto column = gauss::utils::makeScopedHostPtr(a.col(i).host<T>());\n        T start = 0.0;\n        T end = elemPerBin - 1;\n\n        // For each column\n        for (int j = 0; j < bins; j++) {\n            T avg = 0.0;\n            int count = 0;\n\n            // Compute avg for this segment\n            for (int k = start; k <= end; k++) {\n                avg = avg + column[k];\n                count++;\n            }\n            avg = avg / count;\n            reducedColumn[j] = avg;\n\n            // Compute next segment\n            start = std::ceil(end);\n            end = end + elemPerBin;\n            end = (end > n) ? n : end;\n        }\n\n        // First Column\n        af::array col(bins, 1, reducedColumn.data());\n        if (i == 0) {\n            result = col;\n        } else {\n            result = af::join(1, result, col);\n        }\n    }\n    return result;\n}\n\nfloat calculateError(const std::vector<Point> &ts, int start, int end) {\n    Point p1 = ts[start];\n    Point p2 = ts[end];\n\n    // We use the point-slope equation for the middle points between start and end: y = mx - mx_1 + y_1\n    // where m = (y_2 - y_1) / (x_2 - x_1)\n    float m = (p2.second - p1.second) / (p2.first - p1.first);\n\n    return std::accumulate(ts.cbegin() + start, ts.cbegin() + end + 1, 0.0f, [&p1, m](float acc, Point p) {\n        return acc + std::pow(p.second - (m * (p.first - p1.first) + p1.second), 2);\n    });\n}\n\nSegment merge(Segment s1, Segment s2) { return {s1.first, s2.second}; }\n\nint64_t computeTriangleArea(const VisvalingamSummaryPoint &a, const VisvalingamSummaryPoint &b,\n                            const VisvalingamSummaryPoint &c, const long scale = 1e9) {\n    float f1 = a.x * (b.y - c.y);\n    float f2 = b.x * (c.y - a.y);\n    float f3 = c.x * (a.y - b.y);\n    return static_cast<int64_t>(std::abs((static_cast<double>(f1) + f2 + f3) / 2.0f) * scale);\n}\n\ntemplate <typename Iter, typename Distance>\nIter shiftIterator(Iter iter, Distance positions) {\n    std::advance(iter, positions);\n    return iter;\n}\n\nclass mapComparator {\n   public:\n    bool operator()(const std::pair<int64_t, int64_t> &p1, const std::pair<int64_t, int64_t> &p2) const {\n        return ((p1.first < p2.first) || ((p1.first == p2.first) && (p1.second < p2.second)));\n    }\n};\n\nvoid recomputeAreaNeighbor(std::map<int64_t, VisvalingamSummaryPoint>::iterator &iterator_point,\n                           std::set<std::pair<int64_t, int64_t>, mapComparator> &point_indexer,\n                           std::map<int64_t, VisvalingamSummaryPoint> &points, const int64_t scale) {\n    auto im1m1 = shiftIterator(iterator_point, -1);\n    auto im1p1 = shiftIterator(iterator_point, 1);\n    auto original_position_minus1 = iterator_point->first;\n\n    auto old_area_minus1 = iterator_point->second.area;\n    auto new_area_minus1 = computeTriangleArea(im1m1->second, iterator_point->second, im1p1->second, scale);\n    points[iterator_point->first] =\n        VisvalingamSummaryPoint{iterator_point->second.x, iterator_point->second.y, new_area_minus1};\n\n    auto it = point_indexer.find(std::make_pair(old_area_minus1, original_position_minus1));\n    point_indexer.erase(it);\n\n    point_indexer.insert(std::pair<int64_t, int64_t>(std::make_pair(new_area_minus1, original_position_minus1)));\n}\n\n}  // namespace\n\nstd::vector<Point> gauss::dimensionality::PAA(const std::vector<Point> &points, int bins) {\n    float xrange = points.back().first - points.front().first;    \n    float width_bin = xrange / bins;\n    float reduction = bins / xrange;\n\n    std::vector<float> sum(bins, 0.0);\n    std::vector<int> counter(bins, 0);\n\n    // Iterating over the time series\n    for (const auto &p : points) {        \n        auto pos = static_cast<size_t>(std::min(p.first * reduction, (float)(bins - 1)));\n        sum[pos] += p.second;\n        counter[pos] += 1;\n    }    \n\n    std::vector<Point> result;\n    result.reserve(bins);\n    // Compute the average per bin\n    for (int i = 0; i < bins; ++i) {\n        result.emplace_back((width_bin * i) + (width_bin / 2.0f), sum[i] / counter[i]);\n    }\n    return result;\n}\n\naf::array gauss::dimensionality::PAA(const af::array &a, int bins) {\n    // Resulting array\n    af::array result;\n\n    // Check dimensions are divisible, if not, call CPU version\n    if (a.dims(0) % bins == 0) {\n        auto n = a.dims(0);\n        auto elem_row = n / bins;\n\n        af::array b = af::moddims(a, elem_row, bins, a.dims(1));\n        af::array addition = af::sum(b, 0);\n        result = af::reorder(addition / elem_row, 1, 2, 0, 3);\n    } else {\n        // Call the CPU version\n        if (a.type() == af::dtype::f64) {\n            result = PAA_CPU<double>(a, bins);\n        } else if (a.type() == af::dtype::f32) {\n            result = PAA_CPU<float>(a, bins);\n        }\n    }\n\n    return result;\n}\n\naf::array gauss::dimensionality::PIP(const af::array &ts, int numberIPs) {\n    if (ts.dims(1) != 2) {\n        throw std::invalid_argument(\"Invalid dims. Khiva array with two columns expected (x axis and y axis).\");\n    }\n    auto n = ts.dims(0);\n    auto end = n - 1;\n\n    if (n < 2) {\n        throw std::invalid_argument(\"We can't delete all those important points\");\n    } else if (n <= numberIPs) {\n        return ts;\n    }\n\n    // Extracting info from af::array\n    auto h_x = gauss::utils::makeScopedHostPtr(ts.col(0).host<float>());\n    auto h_y = gauss::utils::makeScopedHostPtr(ts.col(1).host<float>());\n\n    // Converting c-arrays to vector of points\n    std::vector<Point> points;\n    for (int i = 0; i < n; i++) {\n        points.emplace_back(h_x[i], h_y[i]);\n    }\n\n    // Allocating vectors for selected points\n    std::vector<Point> selected;\n    selected.emplace_back(points[0]);\n    selected.emplace_back(points[end]);\n\n    // we have to find (numberIPs - 2) points, as we have already included P[0] and P[end].\n    // Number of passes over the collection\n    for (int p = 0; p < (numberIPs - 2); p++) {\n        float dmax = -1.0;\n        int index = -1;\n        int position = -1;\n\n        // Find the next PIP\n        for (int i = 1; i < end; i++) {\n            // We first check if the point is already in the list.\n            if (!isPointInDesiredList(points[i], selected)) {\n                // segment contains the indices of the selected points which are the boundaries for the point i.\n                std::pair<int, int> segment = getSegmentFromSelected(points[i], selected);\n                float d = verticalDistance(points[i], selected[segment.first], selected[segment.second]);\n                // We store the point with the maximum distance to the line that connects the segment.\n                if (d > dmax) {\n                    index = i;\n                    dmax = d;\n                    position = segment.second;\n                }\n            }\n        }\n        insertPointBetweenSelected(points[index], position, selected);\n    }\n\n    // Converting from vector to array\n    std::vector<float> x;\n    x.reserve(selected.size());\n    std::vector<float> y;\n    y.reserve(selected.size());\n    for (auto &i : selected) {\n        x.emplace_back(i.first);\n        y.emplace_back(i.second);\n    }\n\n    // from c-array to af::array\n    af::array tsx(selected.size(), 1, x.data());\n    af::array tsy(selected.size(), 1, y.data());\n    af::array res = af::join(1, tsx, tsy);\n\n    return res;\n}\n\nstd::vector<Point> gauss::dimensionality::PLABottomUp(const std::vector<Point> &ts, float maxError) {\n    std::vector<Segment> segments;\n    segments.reserve(ts.size());\n\n    // Allocating vector of segments\n    for (size_t i = 0; i < ts.size() - 1; i = i + 2) {\n        segments.emplace_back(i, i + 1);\n    }\n\n    std::vector<float> mergeCost;\n    mergeCost.reserve(segments.size());\n    for (size_t i = 0; i < segments.size() - 1; i++) {\n        mergeCost.emplace_back(calculateError(ts, segments[i].first, segments[i + 1].second));\n    }\n\n    // Calculate minimum, calculating in advance\n    auto minCost = std::min_element(std::begin(mergeCost), std::end(mergeCost));\n    while ((segments.size() > 2) && (*minCost < maxError)) {\n        // We have to merge\n        auto index = std::distance(std::begin(mergeCost), minCost);\n\n        // Merge candidate segments\n        segments[index] = merge(segments[index], segments[index + 1]);\n\n        // Delete fused segment\n        segments.erase(segments.begin() + index + 1);\n        mergeCost.erase(mergeCost.begin() + index + 1);\n\n        // Calculate new cost\n        mergeCost[index] = calculateError(ts, segments[index].first, segments[index + 1].second);\n        mergeCost[index - 1] = calculateError(ts, segments[index - 1].first, segments[index].second);\n\n        // Calculate new minimum\n        minCost = std::min_element(std::begin(mergeCost), std::end(mergeCost));\n    }\n\n    // Build a polyline from a set of segments\n    std::vector<Point> result;\n    result.reserve(segments.size());\n    for (auto &segment : segments) {\n        result.emplace_back(ts[segment.first]);\n        result.emplace_back(ts[segment.second]);\n    }\n\n    return result;\n}\n\naf::array gauss::dimensionality::PLABottomUp(const af::array &ts, float maxError) {\n    if (ts.dims(1) != 2) {\n        throw std::invalid_argument(\"Invalid dims. Khiva array with two columns expected (x axis and y axis).\");\n    }\n    // Extracting info from af::array\n    auto h_x = gauss::utils::makeScopedHostPtr(ts.col(0).host<float>());\n    auto h_y = gauss::utils::makeScopedHostPtr(ts.col(1).host<float>());\n\n    std::vector<Point> points;\n    points.reserve(ts.dims(0));\n\n    // Creating a vector of Points\n    for (int i = 0; i < ts.dims(0); i++) {\n        points.emplace_back(h_x[i], h_y[i]);\n    }\n\n    std::vector<Point> reducedPoints = PLABottomUp(points, maxError);\n    std::vector<float> x;\n    x.reserve(reducedPoints.size());\n    std::vector<float> y;\n    y.reserve(reducedPoints.size());\n\n    // Converting from vector to array\n    for (const auto &point : reducedPoints) {\n        x.emplace_back(point.first);\n        y.emplace_back(point.second);\n    }\n\n    // from c-array to af::array\n    af::array tsx(reducedPoints.size(), 1, x.data());\n    af::array tsy(reducedPoints.size(), 1, y.data());\n    af::array res = af::join(1, tsx, tsy);\n\n    return res;\n}\n\nstd::vector<Point> gauss::dimensionality::PLASlidingWindow(const std::vector<Point> &ts, float maxError) {\n    std::vector<Segment> segments;\n\n    size_t anchor = 0;\n    size_t i;\n\n    // We haven´t explored the whole time series\n    while (anchor < (ts.size() - 1)) {\n        i = 1;\n        while (((anchor + i) < ts.size()) &&\n               (calculateError(ts, static_cast<int>(anchor), static_cast<int>(anchor + i)) < maxError)) {\n            i = i + 1;\n        }\n\n        if ((anchor + i) == (ts.size() - 1)) {\n            segments.emplace_back(anchor, anchor + i);\n        } else {\n            segments.emplace_back(anchor, anchor + i - 1);\n        }\n        anchor += i;\n    }\n\n    // Build a polyline from a set of segments\n    std::vector<Point> result;\n    result.reserve(segments.size());\n    for (auto &segment : segments) {\n        result.emplace_back(ts[segment.first]);\n        result.emplace_back(ts[segment.second]);\n    }\n\n    return result;\n}\n\naf::array gauss::dimensionality::PLASlidingWindow(const af::array &ts, float maxError) {\n    if (ts.dims(1) != 2) {\n        throw std::invalid_argument(\"Invalid dims. Khiva array with two columns expected (x axis and y axis).\");\n    }\n    // Extracting info from af::array\n    auto h_x = gauss::utils::makeScopedHostPtr(ts.col(0).host<float>());\n    auto h_y = gauss::utils::makeScopedHostPtr(ts.col(1).host<float>());\n\n    std::vector<Point> points;\n    points.reserve(ts.dims(0));\n\n    // Creating a vector of Points\n    for (int i = 0; i < ts.dims(0); i++) {\n        points.emplace_back(h_x[i], h_y[i]);\n    }\n\n    std::vector<Point> reducedPoints = PLASlidingWindow(points, maxError);\n    std::vector<float> x;\n    x.reserve(reducedPoints.size());\n    std::vector<float> y;\n    y.reserve(reducedPoints.size());\n    // Converting from vector to array\n    for (const auto &point : reducedPoints) {\n        x.emplace_back(point.first);\n        y.emplace_back(point.second);\n    }\n\n    // from c-array to af::array\n    af::array tsx(reducedPoints.size(), 1, x.data());\n    af::array tsy(reducedPoints.size(), 1, y.data());\n    af::array res = af::join(1, tsx, tsy);\n\n    return res;\n}\n\nstd::vector<Point> gauss::dimensionality::ramerDouglasPeucker(const std::vector<Point> &pointList, double epsilon) {\n    std::vector<Point> out;\n\n    if (pointList.size() < 2) throw std::invalid_argument(\"Not enough points to simplify ...\");\n\n    // Find the point with the maximum distance from line between start and end\n    double dmax = 0.0;\n    size_t index = 0;\n    size_t end = pointList.size() - 1;\n\n    for (size_t i = 1; i < end; i++) {\n        double d = PerpendicularDistance(pointList[i], pointList[0], pointList[end]);\n        if (d > dmax) {\n            index = i;\n            dmax = d;\n        }\n    }\n\n    // If max distance is greater than epsilon, recursively simplify\n    if (dmax > epsilon) {\n        std::vector<Point> firstLine(pointList.begin(), pointList.begin() + index + 1);\n        std::vector<Point> lastLine(pointList.begin() + index, pointList.end());\n        auto recResults1 = ramerDouglasPeucker(firstLine, epsilon);\n        auto recResults2 = ramerDouglasPeucker(lastLine, epsilon);\n\n        // Build the result list\n        out.assign(recResults1.begin(), recResults1.end() - 1);\n        out.insert(out.end(), recResults2.begin(), recResults2.end());\n        if (out.size() < 2) throw std::runtime_error(\"Problem assembling output\");\n    } else {\n        // Just return start and end points\n        out.clear();\n        out.emplace_back(pointList[0]);\n        out.emplace_back(pointList[end]);\n    }\n    return out;\n}\n\naf::array gauss::dimensionality::ramerDouglasPeucker(const af::array &pointList, double epsilon) {\n    if (pointList.dims(1) != 2) {\n        throw std::invalid_argument(\"Invalid dims. Khiva array with two columns expected (x axis and y axis).\");\n    }\n\n    auto x = gauss::utils::makeScopedHostPtr(pointList.col(0).host<float>());\n    auto y = gauss::utils::makeScopedHostPtr(pointList.col(1).host<float>());\n\n    std::vector<Point> points;\n    points.reserve(pointList.dims(0));\n    for (int i = 0; i < pointList.dims(0); i++) {\n        points.emplace_back(x[i], y[i]);\n    }\n\n    std::vector<Point> rPoints = ramerDouglasPeucker(points, epsilon);\n    af::array out = af::constant(0, rPoints.size(), 2);\n\n    std::vector<float> vx;\n    vx.reserve(rPoints.size());\n    std::vector<float> vy;\n    vy.reserve(rPoints.size());\n\n    for (const auto &rPoint : rPoints) {\n        vx.emplace_back(rPoint.first);\n        vy.emplace_back(rPoint.second);\n    }\n\n    af::array ox(rPoints.size(), vx.data());\n    af::array oy(rPoints.size(), vy.data());\n\n    return af::join(1, ox, oy);\n}\n\naf::array gauss::dimensionality::SAX(const af::array &a, int alphabet_size) {\n    if (a.dims(1) != 2) {\n        throw std::invalid_argument(\"Invalid dims. Khiva array with two columns expected (x axis and y axis).\");\n    }\n\n    af::array result = af::constant(0.0, a.dims());\n    // Let's store the x-axis.\n    result(af::span, 0) += a.col(0);\n\n    // Let's compute the y-axis.\n    for (int k = 1; k < a.dims(1); k++) {\n        af::array ts = a.col(k);\n        auto mean_value = af::mean<float>(ts);\n        auto std_value = af::stdev<float>(ts);\n        dim_t n = ts.dims(0);\n        std::vector<int> aux(n, 0);\n\n        if (std_value > 0) {\n            std::vector<float> breakingPoints = computeBreakpoints(alphabet_size, mean_value, std_value);\n            std::vector<int> alphabet = generateAlphabet(alphabet_size);\n            auto a_h = gauss::utils::makeScopedHostPtr(ts.host<float>());\n\n            // Iterate across elements of ts\n            for (int i = 0; i < n; i++) {\n                size_t j = 0;\n                while ((j < breakingPoints.size()) && (a_h[i] > breakingPoints[j])) {\n                    j++;\n                }\n                aux[i] = alphabet[j];\n            }\n        }\n\n        // from c-array to af::array\n        af::array res(aux.size(), 1, aux.data());\n        result(af::span, k) += res;\n    }\n\n    return result;\n}\n\nstd::vector<Point> gauss::dimensionality::visvalingam(const std::vector<Point> &pointList, int64_t numPoints, int64_t scale) {\n    std::map<int64_t, VisvalingamSummaryPoint> points;\n    std::set<std::pair<int64_t, int64_t>, mapComparator> point_indexer;\n    int64_t counter = 0;\n\n    std::transform(\n        pointList.cbegin(), pointList.cend(), std::inserter(points, points.end()), [&counter](const Point &point) {\n            return std::make_pair(\n                counter++, VisvalingamSummaryPoint{point.first, point.second, std::numeric_limits<int64_t>::max()});\n        });\n\n    auto points_to_be_deleted = pointList.size() - numPoints;\n    auto point_iterator = point_indexer.begin();\n\n    // Precompute areas\n    for (auto it = shiftIterator(points.begin(), 1); it != shiftIterator(points.end(), -1); ++it) {\n        auto area = computeTriangleArea(shiftIterator(it, -1)->second, it->second, shiftIterator(it, 1)->second, scale);\n        it->second.area = area;\n        point_iterator = point_indexer.insert(point_iterator, std::make_pair(area, it->first));\n    }\n\n    // One point to be deleted on each iteration\n    for (size_t iter = 0; iter < points_to_be_deleted; iter++) {\n        auto min_index_iterator = point_indexer.begin();\n        int64_t min_element = min_index_iterator->second;\n        point_indexer.erase(min_index_iterator);\n\n        auto iterator_point = points.find(min_element);\n        auto iterator_point_minus1 = shiftIterator(iterator_point, -1);\n        auto iterator_point_plus1 = shiftIterator(iterator_point, 1);\n\n        points.erase(iterator_point);\n\n        if (iterator_point_minus1->first > 0) {\n            recomputeAreaNeighbor(iterator_point_minus1, point_indexer, points, scale);\n        }\n\n        if (iterator_point_plus1->first < counter - 1) {\n            recomputeAreaNeighbor(iterator_point_plus1, point_indexer, points, scale);\n        }\n    }\n\n    std::vector<Point> out_vector;\n    out_vector.reserve(numPoints);\n    std::transform(points.cbegin(), points.cend(), std::back_inserter(out_vector),\n                   [](const std::pair<int64_t, VisvalingamSummaryPoint> &p) {\n                       return Point{p.second.x, p.second.y};\n                   });\n\n    return out_vector;\n}\n\naf::array gauss::dimensionality::visvalingam(const af::array &pointList, int numPoints) {\n    if (pointList.dims(1) != 2) {\n        throw std::invalid_argument(\"Invalid dims. Array with two columns expected (x axis and y axis).\");\n    }\n\n    std::vector<Point> points;\n    points.reserve(pointList.dims(0));\n    auto x = gauss::utils::makeScopedHostPtr(pointList.col(0).host<float>());\n    auto y = gauss::utils::makeScopedHostPtr(pointList.col(1).host<float>());\n\n    for (int i = 0; i < pointList.dims(0); i++) {\n        points.emplace_back(x[i], y[i]);\n    }\n\n    std::vector<Point> rPoints = visvalingam(points, numPoints);\n    af::array out = af::constant(0, rPoints.size(), 2);\n\n    std::vector<float> vx;\n    vx.reserve(rPoints.size());\n    std::vector<float> vy;\n    vy.reserve(rPoints.size());\n\n    for (const auto &rPoint : rPoints) {\n        vx.emplace_back(rPoint.first);\n        vy.emplace_back(rPoint.second);\n    }\n\n    af::array ox(rPoints.size(), vx.data());\n    af::array oy(rPoints.size(), vy.data());\n\n    return af::join(1, ox, oy);\n}\n", "meta": {"hexsha": "3ade9970191b6ec491be7e99e865ab5abafe136c", "size": 23756, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/gauss/src/dimensionality.cpp", "max_stars_repo_name": "shapelets/shapelets-compute", "max_stars_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T09:43:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:44:55.000Z", "max_issues_repo_path": "modules/gauss/src/dimensionality.cpp", "max_issues_repo_name": "shapelets/shapelets-compute", "max_issues_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T11:48:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:30:34.000Z", "max_forks_repo_path": "modules/gauss/src/dimensionality.cpp", "max_forks_repo_name": "shapelets/shapelets-compute", "max_forks_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0832137733, "max_line_length": 126, "alphanum_fraction": 0.6088988045, "num_tokens": 6337, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4012106473503403}}
{"text": "/*********************************************************************\r\n * BSD 3-Clause License\r\n *\r\n * Copyright (c) 2018, Rawashdeh Research Group\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\r\n *\r\n * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\r\n *\r\n * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the\r\n *    documentation and/or other materials provided with the distribution.\r\n *\r\n * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from\r\n *    this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\r\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n **********************************************************************/\r\n// Author: Mohamed Aladem\r\n\r\n#include \"lvt_motion_model.h\"\r\n#include <Eigen/Geometry>\r\n\r\nlvt_motion_model::lvt_motion_model()\r\n{\r\n    reset();\r\n}\r\n\r\nvoid lvt_motion_model::reset()\r\n{\r\n    m_last_q.setIdentity();\r\n    m_angular_velocity.setIdentity();\r\n    m_last_position.setZero();\r\n    m_linear_velocity.setZero();\r\n}\r\n\r\nlvt_pose lvt_motion_model::predict_next_pose(const lvt_pose &current_pose)\r\n{\r\n    // compute new linear velocity\r\n    lvt_vector3 new_lin_velocity = current_pose.get_position() - m_last_position;\r\n    new_lin_velocity = (new_lin_velocity + m_linear_velocity) * 0.5; // smooth velocity over time\r\n\r\n    // compute new angular velocity\r\n    lvt_quaternion current_q = current_pose.get_orientation_quaternion();\r\n    lvt_quaternion ang_vel_diff = current_q * m_last_q.inverse();\r\n    lvt_quaternion new_ang_vel = ang_vel_diff.slerp(0.5, m_angular_velocity);\r\n    new_ang_vel.normalize();\r\n\r\n    // Update state\r\n    m_last_q = current_q;\r\n    m_angular_velocity = new_ang_vel;\r\n    m_last_position = current_pose.get_position();\r\n    m_linear_velocity = new_lin_velocity;\r\n\r\n    // Integrate to compute predictions\r\n    lvt_vector3 int_pos = m_last_position + m_linear_velocity;\r\n    lvt_quaternion int_q = current_q * new_ang_vel;\r\n    int_q.normalize();\r\n    return lvt_pose(int_pos, int_q);\r\n}\r\n", "meta": {"hexsha": "9a0c1900a9428e2941fa297441806ef6f1f3e916", "size": 3066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lvt/src/lvt_motion_model.cpp", "max_stars_repo_name": "iscumd/lvt", "max_stars_repo_head_hexsha": "b698a8c1ca4852d2d3e588cf692ebd19eac34252", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 81.0, "max_stars_repo_stars_event_min_datetime": "2018-08-10T18:31:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T08:01:38.000Z", "max_issues_repo_path": "lvt/src/lvt_motion_model.cpp", "max_issues_repo_name": "iscumd/lvt", "max_issues_repo_head_hexsha": "b698a8c1ca4852d2d3e588cf692ebd19eac34252", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-24T01:03:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-08T13:20:25.000Z", "max_forks_repo_path": "lvt/src/lvt_motion_model.cpp", "max_forks_repo_name": "iscumd/lvt", "max_forks_repo_head_hexsha": "b698a8c1ca4852d2d3e588cf692ebd19eac34252", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2018-10-23T11:37:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T08:50:01.000Z", "avg_line_length": 46.4545454545, "max_line_length": 146, "alphanum_fraction": 0.7152641879, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708561, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.40121064735034023}}
{"text": "// Compile command: g++ -Wall -Wextra -std=c++17 -O2 -pthread -I/usr/include/python3.8 -I/usr/include/eigen3 -o triangular_cone_newdisloc triangular_cone_newdisloc.cpp -lpython3.8\n#include <iostream>\n#include <fstream>\n#include <cmath>\n#include <complex>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/MatrixFunctions>\n#include <vector>\n#include <utility>\n#include <functional>\n#include <thread>\n#include <map>\n#include <string>\n#include <algorithm>\n#include <ctime>\n#include <iomanip>\n#include <filesystem>\n#include \"matplotlibcpp.h\"\n\n\nnamespace plt = matplotlibcpp;\nusing Eigen::MatrixXd;\nusing Eigen::Matrix2cd;\nusing Eigen::Vector2cd;\nusing std::vector;\nusing std::sqrt;\nusing std::cos;\nusing std::acos;\nusing std::sin;\nusing std::atan2;\nusing namespace std::complex_literals;\n\ntypedef std::complex<double> cd;\ntypedef vector<vector<vector<cd>>> grid_t;\ntypedef std::function<Matrix2cd(int, double, double)> gen_coin_t;\n\n// Settings here\nint num_steps = 1000;\ndouble dy = sqrt(3);\nbool plotCone = true; // Set to true to plot the results in the cone coordinates\nint ymin = -200, ymax = 200;\nint xmin = 3*ymin/2-ymin%2-1, xmax = 3*ymax/2+ymax%2+1;\nint ntriangles_x = xmax-xmin+1;\nint ntriangles_y = ymax-ymin+1;\nint center[2] = {-xmin, -ymin};\nstd::string prefix;\nint initialState = 0;\nvector<std::string> initialStateName = {\"square\", \"shifttop\", \"shiftdl\", \"center\", \"bothsides\", \"everywhere\"};\n\nstd::time_t now = time(0);\nstd::tm *ltm = localtime(&now);\n\ngrid_t zerogrid() {\n    return vector<vector<vector<cd>>>(ntriangles_x, vector<vector<cd>> (ntriangles_y, vector<cd> (3, 0. + 0i)));\n}\ngrid_t nangrid() {\n    return vector<vector<vector<cd>>>(ntriangles_x, vector<vector<cd>> (ntriangles_y, vector<cd> (3, std::nan(\"\") + 0i)));\n}\n\ngrid_t grid = zerogrid();\n\nMatrix2cd U, C0;\nMatrix2cd sigmay, sigmaz;\n\ndouble sumAmplitudes() {\n    double ret = 0.0;\n    for(int x = xmin; x <= xmax; x++)\n        for(int y = ymin; y <= ymax; y++)\n            for(int side = 0; side < 3; side++) {\n                cd val = grid[x+center[0]][y+center[1]][side];\n                ret += std::real(val*std::conj(val));\n            }\n    return ret;\n}\n\n// Simplifies initialization for some initial states\nvoid normalizeGrid() {\n    double target = sumAmplitudes();\n    double mul = 1/sqrt(target);\n    if(target == 0)\n        return;\n    for(int x = xmin; x <= xmax; x++)\n        for(int y = ymin; y <= ymax; y++)\n            for(int side = 0; side < 3; side++)\n                grid[x+center[0]][y+center[1]][side] *= mul;\n}\n\ninline int modulo(int a, int b) {\n    return (a%b+b)%b;\n}\n\nvoid init_HQ() {\n    sigmaz <<\n        1,0,\n        0,-1;\n    sigmay <<\n        0, -1.0i,\n        1.0i, 0;\n    C0 = std::exp(1.0i*M_PI/3.0) * ((1.0i*M_PI/3.0)*sigmaz).exp();\n    double alpha = -std::acos(sqrt(5)/3);\n    Matrix2cd U0 = (-1.0i*alpha*sigmay/2.0).exp();\n    U = U0*C0*C0;\n}\n\ninline int sign(double d) {\n    if(d>=0)\n        return 1;\n    else\n        return -1;\n}\n\ninline double sq(double d) {\n    return d*d;\n}\n\ninline double correct_fmod(const double a, const double b) {\n    return std::fmod(std::fmod(a,b)+b, b);\n}\n\ninline double principal_measure(const double theta) {\n    double ret = correct_fmod(theta, 2*M_PI);\n    if(ret > M_PI)\n        ret -= 2*M_PI;\n    return ret;\n}\n\ninline double sqmodulus(const std::complex<double> comp) {\n    return std::real(comp*std::conj(comp));\n}\n\ngrid_t shift(grid_t grid) {\n    grid_t ngrid = zerogrid();\n    for(int x = xmin; x <= xmax; x++) {\n        for(int y = ymin; y <= ymax; y++) {\n            for(int i = 0; i < 3; i++) {\n                int iprec = ((i-1)%3+3)%3;\n                ngrid[x+center[0]][y+center[1]][i] = grid[x+center[0]][y+center[1]][iprec];\n            }\n        }\n    }\n    return ngrid;\n}\n\nstd::pair<double, double> real_coords(int iside, int x, int y, bool show = false) {\n    double dec;\n    if(show)\n        dec = .4;\n    else\n        dec = .5;\n    double xcoord, ycoord;\n    // Dislocation: particular case\n    if(x == 0 && y >= 0) { // Vertical line\n        if((x+y)%2 == 0) { // Tip down\n            if(iside == 0) {\n                xcoord = x-dec;\n                ycoord = (y+.5)*dy;\n            }\n            else if(iside == 1) {\n                xcoord = x;\n                ycoord = (y+.5)*dy;\n            }\n            else {\n                xcoord = x-dec;\n                ycoord = (y+.5+dec)*dy;\n            }\n        }\n        else { // Tip up\n            if(iside == 0) {\n                xcoord = x;\n                ycoord = (y+.5)*dy;\n            }\n            else if(iside == 1) {\n                xcoord = x-dec;\n                ycoord = (y+.5)*dy;\n            }\n            else {\n                xcoord = x-dec;\n                ycoord = (y+.5-dec)*dy;\n            }\n        }\n    }\n    else if(y >= 0 && (x == 3*y+1 || x == 3*y+2)) { // Diagonal line\n        if((x+y)%2 == 0) { // Tip down\n            if(iside == 0) {\n                xcoord = x-dec/2.;\n                ycoord = (y+.5-dec/2.)*dy;\n            }\n            else if(iside == 1) {\n                xcoord = x+dec;\n                ycoord = (y+.5)*dy;\n            }\n            else {\n                xcoord = x+dec/2.;\n                ycoord = (y+.5+dec/2.)*dy;\n            }\n        }\n        else { // Tip up\n            if(iside == 0) {\n                xcoord = x+dec+dec/2.;\n                ycoord = (y+.5-dec/2.)*dy;\n            }\n            else if(iside == 1) {\n                xcoord = x-dec/2.;\n                ycoord = (y+.5-dec/2.)*dy;\n            }\n            else {\n                xcoord = x;\n                ycoord = (y+.5-dec)*dy;\n            }\n        }\n    }\n    else if((x+y)%2==0) {\n        if(iside == 0) {\n            xcoord = x-dec;\n            ycoord = (y+.5)*dy;\n        }\n        else if(iside == 1) {\n            xcoord = x+dec;\n            ycoord = (y+.5)*dy;\n        }\n        else {\n            xcoord = x;\n            ycoord = (y+.5+dec)*dy;\n        }\n    }\n    else {\n        if(iside == 0) {\n            xcoord = x+dec;\n            ycoord = (y+.5)*dy;\n        }\n        else if(iside == 1) {\n            xcoord = x-dec;\n            ycoord = (y+.5)*dy;\n        }\n        else {\n            xcoord = x;\n            ycoord = (y+.5-dec)*dy;\n        }\n    }\n    return std::make_pair(xcoord, ycoord);\n}\n\nstd::pair<double, double> cone_coords(int iside, int x, int y, bool show = false) {\n    double rx, ry;\n    std::tie(rx, ry) = real_coords(iside, x, y, show);\n    double r = 5./6.*sqrt(rx*rx+ry*ry);\n    double theta_before = atan2(ry, rx);\n    double theta_rotate = principal_measure(theta_before+4*M_PI/6.);\n    double theta = 6./5.*theta_rotate;\n    return std::make_pair(r*cos(theta), r*sin(theta));\n}\n\nconst int DELTAS[][2] = {{1,0}, {-1,0}, {0,-1}};\nconst int NUM_THREADS = 8;\n\n/**\n * For the new dislocation: \n * - triangles (0,y), y >= 0, have triangle (3*y//2 + y%2 + 1, y//2) as a neighbor. \n *   Since we only consider tip up triangles, with (x+y)%2 == 1, we simply need to know that\n *   triangles (0, y), y >= 0 and y odd, have side 2 of triangle (3*(y-1)/2+2, (y-1)/2) as a neighbor at side 0.\n * - triangles (3y+1, y), y >= 0 have side 1 of triangle (0, 2y) as a neighbor at side 1.\n */\nvoid applyCoinsPartial(grid_t &ngrid, grid_t &grid, const Matrix2cd &coin, int loc_xmin, int loc_xmax) {\n    for(int x = loc_xmin; x < loc_xmax; x++) {\n        for(int y = ymin; y <= ymax; y++) {\n            if((x+y)%2==0 || (x>0 && y>(x-1)/3))\n                continue;\n            for(int iside = 0; iside < 3; iside++) {\n                int otherside = iside;\n                cd thisval = grid[x+center[0]][y+center[1]][iside];\n                int xo = x + DELTAS[iside][0], yo = y + DELTAS[iside][1];\n                if(xo > xmax || xo < xmin || yo > ymax || yo < ymin) { // No propagation at borders\n                    ngrid[x+center[0]][y+center[1]][iside] = thisval;\n                    continue;\n                }\n                if(x == 0 && y >= 0 && iside == 0) {\n                    xo = 3*(y-1)/2+2;\n                    yo = (y-1)/2;\n                    otherside = 2;\n                }\n                else if(y >= 0 && x == 3*y+1 && iside == 1) {\n                    xo = 0;\n                    yo = 2*y;\n                    otherside = 1;\n                }\n                cd otherval = grid[xo+center[0]][yo+center[1]][otherside];\n                Vector2cd vect;\n                vect << thisval, otherval;\n                Vector2cd newvect = coin*vect;\n                ngrid[x+center[0]][y+center[1]][iside] = newvect(0);\n                ngrid[xo+center[0]][yo+center[1]][otherside] = newvect(1);\n            }\n        }\n    }\n}\n\ngrid_t applyCoins(grid_t grid, const Matrix2cd &coin, bool multithread = true) {\n    grid_t ngrid = nangrid();\n    if(!multithread) {\n        for(int x = xmin; x <= xmax; x++) {\n            for(int y = ymin; y <= ymax; y++) {\n                if((x+y)%2==0 || (x>0 && y>(x-1)/3)) // dislocation : remove a 60-degree part of the lattie\n                    continue;\n                for(int iside = 0; iside < 3; iside++) {\n                    int otherside = iside;\n                    cd thisval = grid[x+center[0]][y+center[1]][iside];\n                    int xo = x + DELTAS[iside][0], yo = y + DELTAS[iside][1];\n                    if(xo > xmax || xo < xmin || yo > ymax || yo < ymin) { // No propagation at borders\n                        ngrid[x+center[0]][y+center[1]][iside] = thisval;\n                        continue;\n                    }\n                    if(x == 0 && y >= 0 && iside == 0) {\n                        xo = 3*(y-1)/2+2;\n                        yo = (y-1)/2;\n                        otherside = 2;\n                    }\n                    else if(y >= 0 && x == 3*y+1 && iside == 1) {\n                        xo = 0;\n                        yo = 2*y;\n                        otherside = 1;\n                    }\n                    cd otherval = grid[xo+center[0]][yo+center[1]][otherside];\n                    Vector2cd vect;\n                    vect << thisval, otherval;\n                    Vector2cd newvect = coin*vect;\n                    ngrid[x+center[0]][y+center[1]][iside] = newvect(0);\n                    ngrid[xo+center[0]][yo+center[1]][otherside] = newvect(1);\n                }\n            }\n        }\n    }\n    else {\n        std::thread threads[NUM_THREADS];\n        int delta_x = ntriangles_x/NUM_THREADS;\n        for(int iThread = 0; iThread < NUM_THREADS-1; iThread++) {\n            threads[iThread] = std::thread(applyCoinsPartial, std::ref(ngrid), std::ref(grid), std::ref(coin), xmin+iThread*delta_x, xmin+(iThread+1)*delta_x);\n        }\n        threads[NUM_THREADS-1] = std::thread(applyCoinsPartial, std::ref(ngrid), std::ref(grid), std::ref(coin), xmin+(NUM_THREADS-1)*delta_x, xmax+1);\n        for(int iThread = 0; iThread < NUM_THREADS; iThread++)\n            threads[iThread].join();\n    }\n    // We may miss some sides of 1 (tip up) triangles which are not adjacent to a valid 0 triangle\n    for(int x = xmin; x <= xmax; x++)\n        for(int y = ymin; y <= ymax; y++)\n            for(int side = 0; side < 3; side++) {\n                cd &newval = ngrid[x+center[0]][y+center[1]][side];\n                if(std::isnan(std::real(newval)))\n                    newval = grid[x+center[0]][y+center[1]][side];\n            }\n    return ngrid;\n}\n\nvoid plot(int iGrid = -1) {\n    PyObject *fig;\n    // Code to write the plot as Python matplotlib instructions. Use this if there are too many visible points to plot, since matplotlib-cpp segfaults in that case\n    /*std::ostringstream scriptpath;\n    scriptpath << prefix << \"/script_\" << iGrid << \".py\";\n    std::ofstream pyscript(scriptpath.str());\n    pyscript << \"from matplotlib import pyplot as plt\\n\";\n    pyscript << \"plt.figure(figsize=(10,10))\\n\";\n    pyscript << \"plt.xlim(\" << xmin << \",\" << xmax << \")\\n\";\n    pyscript << \"plt.ylim(\" << ymin*dy << \",\" << ymax*dy << \")\\n\";*/\n    if(plotCone) {\n        fig = plt::figure_size(1000,1000);\n        plt::xlim(xmin, xmax);\n        plt::ylim(ymin*dy, ymax*dy);\n        plt::set_aspect_equal();\n        vector<double> xlist, ylist, colorlist;\n        vector<double> listvals;\n        for(int x = xmin; x <= xmax; x++) {\n            for(int y = ymin; y <= ymax; y++) {\n                for(int iside = 0; iside < 3; iside++) {\n                    cd val = grid[x+center[0]][y+center[1]][iside];\n                    double col = std::real(val*std::conj(val));\n                    listvals.push_back(col);\n                }\n            }\n        }\n        std::sort(listvals.rbegin(), listvals.rend());\n        double maxi = (listvals[0]+listvals[1])/2;\n        double threshold = maxi/10;\n        for(int x = xmin; x <= xmax; x++) {\n            for(int y = ymin; y <= ymax; y++) {\n                for(int iside = 0; iside < 3; iside++) {\n                    cd val = grid[x+center[0]][y+center[1]][iside];\n                    double col = std::real(val*std::conj(val));\n                    if(col > threshold) {\n                        double rx, ry;\n                        std::tie(rx, ry) = cone_coords(iside, x, y, true);\n                        xlist.push_back(rx);\n                        ylist.push_back(ry);\n                        colorlist.push_back(col);\n                    }\n                }\n            }\n        }\n        if(maxi == 0.0)\n            maxi = 1.0;\n        maxi *= 0.6;\n        // Continued\n        /*\n        pyscript << \"plt.scatter([\";\n        for(double d : xlist)\n            pyscript << d << \",\";\n        pyscript << \"],[\";\n        for(double d : ylist)\n            pyscript << d << \",\";\n        pyscript << \"], c=[\";\n        for(double c : colorlist)\n            pyscript << c << \",\";\n        pyscript << \"], cmap=\\\"gist_heat_r\\\", vmin=0, vmax=\" << maxi << \")\\n\";*/\n        plt::scatter_colored(xlist, ylist, colorlist, 1, {{\"cmap\",\"gist_heat_r\"}, {\"vmin\", \"0\"}, {\"vmax\", std::to_string(maxi)}});\n    }\n    else {\n        fig = plt::figure_size(1000,1000);\n        plt::set_aspect_equal();\n        vector<vector<double>> imgrid(ymax-ymin+1, vector<double>(xmax-xmin+1, 0.0));\n        vector<double> listvals;\n        for(int y = ymin; y <= ymax; y++) {\n            for(int x = xmin; x <= xmax; x++) {\n                double sum = 0.0;\n                for(int iside = 0; iside < 3; iside++) {\n                    cd val = grid[x+center[0]][y+center[1]][iside];\n                    double col = std::real(val*std::conj(val));\n                    sum += col;\n                }\n                listvals.push_back(sum);\n                imgrid[y+center[1]][x+center[0]] = sum;\n            }\n        }\n        std::sort(listvals.rbegin(), listvals.rend());\n        double maxi = (listvals[0]+listvals[1])/2;\n        if(maxi == 0.0)\n            maxi = 1.0;\n        maxi *= .6;\n            \n        double minx = (xmin-.5);\n        double maxx = (xmax+.5);\n        double miny = dy*(ymin-.5);\n        double maxy = dy*(ymax+.5);\n        plt::imshow(imgrid, {minx, maxx, miny, maxy}, {{\"origin\", \"lower\"}, {\"cmap\", \"gist_heat_r\"}, {\"vmin\", \"0.0\"}, {\"vmax\", std::to_string(maxi)}});\n        plt::plot({0.0, 0.0}, {0.0, maxy}, {{\"color\",\"red\"}});\n        plt::plot({0.0, maxx}, {0.0, maxx*std::tan(M_PI/6)}, {{\"color\",\"red\"}});\n    }\n    // Continued\n    /*pyscript << \"plt.savefig(\\\"\" << prefix << \"_\" << iGrid << \".png\\\")\\n\";\n    pyscript.flush();\n    pyscript.close();*/\n    std::ostringstream filename;\n    filename << prefix << \"_\" << iGrid << \".png\";\n    plt::save(prefix + \"/\" + filename.str());\n    plt::clf();\n    plt::close(fig);\n    Py_DECREF(fig);\n\n    // Plot around dislocation line\n    vector<double> xlist2, ylist2;\n    for(int y = 0; y <= ymax; y++) {\n        vector<int> klist;\n        if(y%2)\n            klist = {2, 0, 1};\n        else\n            klist = {0, 1, 2};\n        for(int k : klist) {\n            double rx, ry;\n            std::tie(rx, ry) = real_coords(k, 0, y);\n            xlist2.push_back(ry);\n            cd val = grid[center[0]][center[1]+y][k];\n            double col = std::real(val*std::conj(val));\n            ylist2.push_back(col);\n        }\n    }\n    plt::plot(xlist2, ylist2);\n    std::ostringstream filename_disloc;\n    filename_disloc << prefix << \"_dislocation_\" << iGrid << \".png\";\n    plt::save(prefix + \"/\" + filename_disloc.str());\n    plt::clf();\n    plt::close();\n}\n\nvector<double> dislocAmplitudes;\n\nvoid step_walk(int step = -1) {\n    std::cerr << \"Begin step \" << step << std::endl;\n    grid = applyCoins(grid, U);\n    for(int j = 0; j < 3; j++) {\n        grid = applyCoins(grid, U*C0*U.adjoint());\n        grid = shift(grid);\n    }\n    grid = applyCoins(grid, U.adjoint());\n    double sumDisloc = 0;\n    for(int y = 0; y <= ymax; y++)\n        for(int k = 0; k < 3; k++)\n            sumDisloc += sqmodulus(grid[center[0]][y+center[1]][k]);\n    for(int y = 0; y <= ymax && 3*y+1 <= xmax; y++)\n        for(int k = 0; k < 3; k++)\n            sumDisloc += sqmodulus(grid[center[0]+3*y+1][center[1]+y][k]);\n    dislocAmplitudes.push_back(sumDisloc);\n    std::cerr << \"Total amplitude: \" << sumAmplitudes() << \"\\n\";\n    std::cerr << \"End step \" << step << std::endl;\n}\n\nvoid plotDislocAmplitude() {\n    std::cerr << \"Plotting dislocation amplitude\" << std::endl;\n    plt::plot(dislocAmplitudes);\n    plt::save(prefix + \"/\" + prefix + \"_disloc.png\");\n    plt::clf();\n    plt::close();\n}\n\nvoid print_params() {\n    std::ofstream ostream(prefix + \"/settings.txt\");\n    ostream << \"num_steps = \" << num_steps << \"\\n\";\n    ostream << \"initial state: \" << initialStateName[initialState] << \"\\n\";\n    if(plotCone)\n        ostream << \"Cone coordinates\\n\";\n    else\n        ostream << \"Unfolded cone\\n\";\n    ostream << \"xmin = \" << xmin << \"\\n\";\n    ostream << \"xmax = \" << xmax << \"\\n\";\n    ostream << \"ymin = \" << ymin << \"\\n\";\n    ostream << \"ymax = \" << ymax << \"\\n\";\n    ostream << \"U=\\n\" << U << \"\\n\";\n    ostream << \"C0=\\n\" << C0 << std::endl;\n    ostream.close();\n}\n\nvoid listInitialStates() {\n    for(size_t i = 0; i < initialStateName.size(); i++)\n        std::cerr << \"- \" << i << \": \" << initialStateName[i] << \"\\n\";\n}\n\nint main(int argc, char **argv)\n{\n    if(argc <= 2) {\n        std::cerr << \"Usage: \" << std::string(argv[0]) << \" <initial state> <plot cone>\\n\";\n        std::cerr << \"Initial states:\\n\";\n        listInitialStates();\n        std::cerr << \"<plot cone> should be 1 if the figure should be plotted in cone coordinates, 0 otherwise.\\n\";\n        return 1;\n    }\n    initialState = std::atoi(argv[1]);\n    if(initialState < 0 || initialState >= (int)initialStateName.size()) {\n        std::cerr << \"Invalid initial state \" << initialState << \". List of possible states:\\n\";\n        listInitialStates();\n        return 2;\n    }\n    plotCone = (bool) std::atoi(argv[2]);\n    std::ostringstream str;\n    str <<\n        \"simul_cone_newdisloc_\" << initialStateName[initialState];\n    if(plotCone)\n        str << \"_conecoord_\";\n    else\n        str << \"_altcoord_\"; \n    str <<\n        std::setw(4) << std::setfill('0') << ltm->tm_year+1900 << \"-\" << \n        std::setw(2) << ltm->tm_mon+1 << \"-\" << \n        std::setw(2) << ltm->tm_mday << \"_\" << \n        std::setw(2) << ltm->tm_hour << \"-\" << \n        std::setw(2) << ltm->tm_min << \"-\" << \n        std::setw(2) << ltm->tm_sec;\n    prefix = str.str();\n    std::filesystem::create_directory(prefix);\n    init_HQ();\n    print_params();\n    // Initial state\n    // A square\n    if(initialState == 0) {\n        for(int x = xmin/5; x <= xmax/5; x++)\n            for(int y = ymin/5; y <= ymax/5; y++)\n                for(int k = 0; k < 3; k++)\n                    if(x <= 0 || y <= (x-1)/3)\n                        grid[center[0]+x][center[1]+y][k] = 1;\n        normalizeGrid();\n    }\n    // Shifted\n    else if(initialState == 1) {\n        for(int k = 0; k < 3; k++)\n            grid[center[0]][center[1]+ymax/2-1][k]=1/sqrt(3);\n    }\n    // Shifted (in another way)\n    else if(initialState == 2) {\n        for(int k = 0; k < 3; k++)\n            grid[center[0]+xmin/4+1][center[1]+ymin/4+1][k]=1/sqrt(3);\n    }\n    // Centered\n    else if(initialState == 3) {\n        vector<vector<int> > centercoords = {{-1,-1},{-1,0},{0,-1},{0,0},{1,-1},{1,0}};\n        for(vector<int> coord : centercoords)\n            for(int k = 0; k < 3; k++)\n                grid[center[0]+coord[0]][center[1]+coord[1]][k]=1/sqrt(3*centercoords.size());\n    }\n    // Shifted, both sides of the line\n    else if(initialState == 4) {\n        for(int k=0; k<3; k++) {\n            grid[center[0]+10][center[1]+3][k] = 1/sqrt(6);\n            grid[center[0]][center[1]+6][k] = 1/sqrt(6);\n        }\n    }\n    // Everywhere, uniformly\n    else if(initialState == 5) {\n        for(int x = xmin; x <= xmax; x++)\n            for(int y = ymin; y <= ymax; y++)\n                if(x<=0 || y <= (x-1)/3)\n                    for(int k = 0; k < 3; k++)\n                        grid[center[0]+x][center[1]+y][k] = 1;\n        normalizeGrid();\n    }\n    plot(0);\n    for(int i = 0; i < num_steps; i++) {\n        step_walk(i);\n        if((i+1)%10 == 0)\n            plot(i+1);\n    }\n    plotDislocAmplitude();\n\n}\n", "meta": {"hexsha": "61b7714e0c389e9b462b7d642ab15eace22b9c39", "size": 21070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "triangular_cone_newdisloc.cpp", "max_stars_repo_name": "vdng9338/qw_simul", "max_stars_repo_head_hexsha": "19619b2a0f1a9a9b0a871ae5517d79806670f780", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "triangular_cone_newdisloc.cpp", "max_issues_repo_name": "vdng9338/qw_simul", "max_issues_repo_head_hexsha": "19619b2a0f1a9a9b0a871ae5517d79806670f780", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "triangular_cone_newdisloc.cpp", "max_forks_repo_name": "vdng9338/qw_simul", "max_forks_repo_head_hexsha": "19619b2a0f1a9a9b0a871ae5517d79806670f780", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0387722132, "max_line_length": 179, "alphanum_fraction": 0.4799715235, "num_tokens": 6266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4012106406208014}}
{"text": "#include <boost/config.hpp>\n#include <boost/version.hpp>\n\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include <iostream>\n#include <fstream>\n#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>\n#include <CGAL/Polygon_2.h>\n#include <CGAL/Polygon_with_holes_2.h>\n#include <CGAL/Constrained_Delaunay_triangulation_2.h>\n#include <CGAL/Constrained_triangulation_plus_2.h>\n#include <CGAL/Polyline_simplification_2/simplify.h>\n#include <CGAL/Polyline_simplification_2/Squared_distance_cost.h>\n#include <CGAL/IO/WKT.h>\n\nnamespace PS = CGAL::Polyline_simplification_2;\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Polygon_2<K>                                  Polygon_2;\ntypedef CGAL::Polygon_with_holes_2<K>                       Polygon_with_holes_2;\n\ntypedef PS::Vertex_base_2<K> Vb;\ntypedef CGAL::Constrained_triangulation_face_base_2<K> Fb;\ntypedef CGAL::Triangulation_data_structure_2<Vb, Fb> TDS;\ntypedef CGAL::Constrained_Delaunay_triangulation_2<K, TDS, CGAL::Exact_predicates_tag> CDT;\ntypedef CGAL::Constrained_triangulation_plus_2<CDT>     CT;\ntypedef CT::Point                           Point;\ntypedef CT::Constraint_iterator             Constraint_iterator;\ntypedef CT::Vertices_in_constraint_iterator Vertices_in_constraint_iterator;\ntypedef CT::Points_in_constraint_iterator   Points_in_constraint_iterator;\ntypedef PS::Stop_below_count_ratio_threshold Stop;\ntypedef PS::Squared_distance_cost Cost;\nint main(int argc, char* argv[])\n{\n  std::ifstream ifs( (argc==1)?\"data/polygon.wkt\":argv[1]);\n  CT ct;\n  Polygon_with_holes_2 P;\n  while(CGAL::read_polygon_WKT(ifs, P)){\n    const Polygon_2& poly = P.outer_boundary();\n    ct.insert_constraint(poly);\n    for(Polygon_with_holes_2::Hole_const_iterator it = P.holes_begin(); it != P.holes_end(); ++it){\n      const Polygon_2& hole = *it;\n      ct.insert_constraint(hole);\n    }\n  }\n  PS::simplify(ct, Cost(), Stop(0.5));\n\n  for(Constraint_iterator cit = ct.constraints_begin();\n      cit != ct.constraints_end();\n      ++cit) {\n    std::cout << \"simplified polyline\" << std::endl;\n    for(Points_in_constraint_iterator vit = \n          ct.points_in_constraint_begin(*cit);\n        vit != ct.points_in_constraint_end(*cit);\n        ++vit)\n      std::cout << *vit << std::endl;\n  }\n  return 0;\n}\n\n#else\n\nint main()\n{\n  return 0;\n}\n#endif\n", "meta": {"hexsha": "245612cd804ae6e87360f286763562b5feec0681", "size": 2366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/Polyline_simplification_2/simplify.cpp", "max_stars_repo_name": "josuehfa/DAASystem", "max_stars_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T01:13:02.000Z", "max_issues_repo_path": "CoreSystem/lib/CGAL/examples/Polyline_simplification_2/simplify.cpp", "max_issues_repo_name": "josuehfa/DAASystem", "max_issues_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoreSystem/lib/CGAL/examples/Polyline_simplification_2/simplify.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 34.7941176471, "max_line_length": 99, "alphanum_fraction": 0.7223161454, "num_tokens": 632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.5583269943353745, "lm_q1q2_score": 0.4012106406208014}}
{"text": "/*=============================================================================\nCopyright 2020 Syed Ali Hasan <alihasan9922@gmail.com>\n\nDistributed under the Boost Software License, Version 1.0. (See accompanying\nfile License.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n\n#ifndef BOOST_ASTRONOMY_ECLIPTIC_COORD_HPP\n#define BOOST_ASTRONOMY_ECLIPTIC_COORD_HPP\n\n#include <iostream>\n#include <boost/static_assert.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/units/get_dimension.hpp>\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/units/systems/si/plane_angle.hpp>\n#include <boost/units/systems/si/dimensionless.hpp>\n#include <boost/units/physical_dimensions/plane_angle.hpp>\n#include <boost/astronomy/coordinate/coord_sys/coord_sys.hpp>\n\n/**\n * The plane containing the Earth’s orbit around the Sun is called\n * the ecliptic and the other planets in our Solar System also move\n * in orbits close to this plane.\n *\n * When making calculations on objects in the Solar System it is\n * therefore often convenient to define positions with respect to\n * the ecliptic, that is, to use the ecliptic coordinate system.\n *\n * Ecliptic Latitude\n * The ecliptic plane is extended until it intersects the celestial\n * sphere to create an “ecliptic equator” as the reference point from\n * which Ecliptic Latitudes are measured. The Ecliptic Latitude, denoted\n * by β, is the angular distance that an object P lies above or below the\n * ecliptic plane and falls within the range ±90◦.\n * Latitudes above the ecliptic plane are positive angles while latitudes\n * below the ecliptic plane are negative angles. An object, such as the Sun,\n * whose orbit lies entirely within the ecliptic plane has an ecliptic latitude\n * of 0◦.\n *\n * Ecliptic Longitude\n * The Ecliptic Longitude, designated by λ, measures how far away an object is\n * from the First Point of Aries. The Ecliptic Longitude is in the range [0◦, 360◦]\n * and measured along the ecliptic toward the First Point of Aries.\n */\n\nnamespace boost { namespace astronomy { namespace coordinate {\n\nnamespace bu = boost::units;\nnamespace bg = boost::geometry;\n\ntemplate\n<\n    typename CoordinateType = double,\n    typename LatQuantity = bu::quantity<bu::si::plane_angle, CoordinateType>,\n    typename LonQuantity = bu::quantity<bu::si::plane_angle, CoordinateType>\n>\nstruct ecliptic_coord : public coord_sys\n    <2, bg::cs::spherical<bg::radian>, CoordinateType>\n{\n  ///@cond INTERNAL\n  BOOST_STATIC_ASSERT_MSG(\n      ((std::is_same<typename bu::get_dimension<LatQuantity>::type,\n          bu::plane_angle_dimension>::value) &&\n       (std::is_same<typename bu::get_dimension<LonQuantity>::type,\n           bu::plane_angle_dimension>::value)),\n      \"Latitude and Longitude must be of plane angle type\");\n  BOOST_STATIC_ASSERT_MSG((std::is_floating_point<CoordinateType>::value),\n                          \"CoordinateType must be a floating-point type\");\n  ///@endcond\npublic:\n    typedef LatQuantity quantity1;\n    typedef LonQuantity quantity2;\n\n    //Default constructor\n    ecliptic_coord() {}\n\n    ecliptic_coord\n    (\n            LatQuantity const &Lat,\n            LonQuantity const &Lon\n    )\n    {\n        this->set_lat_lon(Lat, Lon);\n    }\n\n    //Create a tuple of Ecliptic Latitude and Ecliptic Longitude\n    std::tuple<LatQuantity, LonQuantity> get_lat_lon() const\n    {\n        return std::make_tuple(this->get_lat(), this->get_lon());\n    }\n\n    //Get Ecliptic Latitude\n    LatQuantity get_lat() const\n    {\n        return static_cast<LatQuantity>\n        (\n            bu::quantity<bu::si::plane_angle, CoordinateType>::from_value\n                    (bg::get<0>(this->point))\n        );\n    }\n\n    //Get Ecliptic Longitude\n    LonQuantity get_lon() const\n    {\n        return static_cast<LonQuantity>\n        (\n                bu::quantity<bu::si::plane_angle, CoordinateType>::from_value\n                        (bg::get<1>(this->point))\n        );\n    }\n\n    //Set value of Ecliptic Latitude and Ecliptic Longitude\n    void set_lat_lon\n    (\n            LatQuantity const &Lat,\n            LonQuantity const &Lon\n    )\n    {\n        this->set_lat(Lat);\n        this->set_lon(Lon);\n    }\n\n    //Set Ecliptic Latitude\n    void set_lat(LatQuantity const &Lat)\n    {\n        bg::set<0>\n            (\n                this->point,\n                static_cast<bu::quantity<bu::si::plane_angle, CoordinateType>>(Lat).value()\n            );\n    }\n\n    //Set Ecliptic Longitude\n    void set_lon(LonQuantity const &Lon)\n    {\n        bg::set<1>\n            (\n                this->point,\n                static_cast<bu::quantity<bu::si::plane_angle, CoordinateType>>(Lon).value()\n            );\n    }\n\n}; //ecliptic_coord\n\n//Make Ecliptic Coordinate\ntemplate\n<\n    typename CoordinateType,\n    template<typename Unit2, typename CoordinateType_> class LatQuantity,\n    template<typename Unit1, typename CoordinateType_> class LonQuantity,\n    typename Unit1,\n    typename Unit2\n>\necliptic_coord\n<\n    CoordinateType,\n    LatQuantity<Unit2, CoordinateType>,\n    LonQuantity<Unit1, CoordinateType>\n> make_ecliptic_coord\n(\n    LatQuantity<Unit2, CoordinateType> const &Lat,\n    LonQuantity<Unit1, CoordinateType> const &Lon\n)\n{\n    return ecliptic_coord\n        <\n            CoordinateType,\n            LatQuantity<Unit2, CoordinateType>,\n            LonQuantity<Unit1, CoordinateType>\n        > (Lat, Lon);\n}\n\n//Print Ecliptic Coordinates\ntemplate\n<\n    typename CoordinateType,\n    class LatQuantity,\n    class LonQuantity\n>\nstd::ostream &operator << (std::ostream &out, ecliptic_coord\n        <CoordinateType, LatQuantity, LonQuantity> const &point) {\n    out << \"Ecliptic Coordinate (Ecliptic Latitude: \"\n        << point.get_lat() << \", Ecliptic Longitude: \"\n        << point.get_lon() << \")\";\n\n    return out;\n}\n\n}}}\n\n#endif //BOOST_ASTRONOMY_ECLIPTIC_COORD_HPP\n", "meta": {"hexsha": "807ecd198a311fe95199da5f6fa2aee4ef67d80f", "size": 5924, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/coordinate/coord_sys/ecliptic_coord.hpp", "max_stars_repo_name": "nitink25/astronomy", "max_stars_repo_head_hexsha": "0a1d137171b08d1014d4ff138b2a40a146f4f39b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T13:53:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T20:37:18.000Z", "max_issues_repo_path": "include/boost/astronomy/coordinate/coord_sys/ecliptic_coord.hpp", "max_issues_repo_name": "Zyro9922/astronomy", "max_issues_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 96.0, "max_issues_repo_issues_event_min_datetime": "2019-05-28T17:46:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-09T07:59:17.000Z", "max_forks_repo_path": "include/boost/astronomy/coordinate/coord_sys/ecliptic_coord.hpp", "max_forks_repo_name": "Zyro9922/astronomy", "max_forks_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2019-05-13T21:09:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T06:24:39.000Z", "avg_line_length": 30.6943005181, "max_line_length": 91, "alphanum_fraction": 0.6583389602, "num_tokens": 1434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.6334102498375401, "lm_q1q2_score": 0.4012085533658429}}
{"text": "//    Copyright 2017 Rainer Gemulla\n// \n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n// \n//        http://www.apache.org/licenses/LICENSE-2.0\n// \n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n/** \\file\n *\n * Illustrates matrix factorization with DSGD. We first creates factors and then a data matrix\n * from these factors. This process ensures that we know the best factorization of the input.\n * These matrices are distributed across a cluster. We then try to reconstruct the factors\n * using DSGD.\n *\n * Run with: mpirun --hosts localhost,localhost dsgd\n * (make sure to use a production build, otherwise it will be slow)\n */\n#include <iostream>\n\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/math/distributions/normal.hpp>\n#include <boost/random/uniform_real.hpp>\n\n#include <util/evaluation.h>\n\n#include <mpi2/mpi2.h>\n#include <mf/mf.h>\n\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"main\"));\n\nusing namespace std;\nusing namespace mf;\nusing namespace mpi2;\nusing namespace rg;\nusing namespace boost::numeric::ublas;\n\n// type of SGD\ntypedef UpdateTruncate<UpdateSl> Update;\ntypedef RegularizeTruncate<RegularizeSl> Regularize;\ntypedef SlLoss Loss;\n\nint main(int argc, char* argv[]) {\n\t// initialize mf library and mpi2\n\tboost::mpi::communicator& world = mfInit(argc, argv);\n\n\t// parameters for the factorization\n\tmf_size_type size1 = 10000;\n\tmf_size_type size2 = 10000;\n\tmf_size_type nnz = 5000000;\n\tmf_size_type r = 10;\n\n\t// parameters for distribution\n\tint tasksPerRank = 2;\n\tmf_size_type blocks1 = world.size() * tasksPerRank;\n\tmf_size_type blocks2 = world.size() * tasksPerRank;\n\n\t// parameters for SGD\n\tdouble epsMax = 0.001;\n\tmf_size_type epochs = 20;\n\tSgdOrder order = SGD_ORDER_WOR;\n\tStratumOrder stratumOrder = STRATUM_ORDER_WOR;\n\tUpdate update = Update((UpdateSl()), 0, 100);\n\tRegularize regularize((RegularizeSl()), 0, 100);\n\tLoss loss;\n\n\t// start mf library\n\t// TODO: need automatic registration\n\tmfStart();\n\n\tif (world.rank() == 0)\n\t{\n#ifndef NDEBUG\n\t\tLOG4CXX_WARN(logger, \"Warning: Debug mode activated (runtimes may be slow).\");\n#endif\n\n\t\t// TODO: distribute matrix generation\n\t\t// generate original factors by sampling from a uniform(0,1) distribution\n\t\tRandom32 random; // note: this takes a default seed (not randomized!)\n\t\tDenseMatrix wIn(size1, r);\n\t\tDenseMatrixCM hIn(r, size2);\n\t\tgenerateRandom(wIn, random, boost::uniform_real<>(0,1));\n\t\tgenerateRandom(hIn, random, boost::uniform_real<>(0,1));\n\n\t\t// generate a sparse matrix by selecting random entries from the generated factors\n\t\t// and sample from a Poisson with mean equal to the entry\n\t\t// TODO: this generation process does not match the factorization model since we sample\n\t\t//       from the Poisson only at some entries of wh\n\t\tSparseMatrix v;\n\t\tgenerateRandom(v, nnz, wIn, hIn, random);\n\t\tLOG4CXX_INFO(logger, \"Data matrix: \"\n\t\t\t<< v.size1() << \" x \" << v.size2() << \", \" << v.nnz() << \" nonzeros\");\n\t\tLOG4CXX_INFO(logger, \"Loss with original factors: \" << loss((FactorizationData<>(v, wIn, hIn))));\n\n\t\t// take a small sample and remove empty rows/columns\n\t\tProjectedSparseMatrix Vsample;\n\t\tprojectRandomSubmatrix(random, v, Vsample, v.size1()/5, v.size2()/5);\n\t\tprojectFrequent(Vsample, 0);\n\t\tLOG4CXX_INFO(logger, \"Sample matrix: \"\n\t\t\t<< Vsample.data.size1() << \" x \" << Vsample.data.size2()\n\t\t\t<< \", \" << Vsample.data.nnz() << \" nonzeros\");\n\n\t\t// generate initial factors by sampling from a uniform[0,1] distribution\n\t\tDenseMatrix w(size1, r);\n\t\tDenseMatrixCM h(r, size2);\n\t\tgenerateRandom(w, random, boost::uniform_real<>(0, 1));\n\t\tgenerateRandom(h, random, boost::uniform_real<>(0, 1));\n\n\t\t// distribute the input matrices\n\t\tDistributedSparseMatrix dv = distributeMatrix(\"V\", blocks1, blocks2, true, v);\n\t\tLOG4CXX_INFO(logger, \"Distributed data matrix: \"\n\t\t\t\t\t<< dv.blocks1() << \" x \" << dv.blocks2() << \" blocks\");\n\t\tDistributedDenseMatrix dw = distributeMatrix(\"W\", blocks1, 1, true, w);\n\t\tDistributedDenseMatrixCM dh = distributeMatrix(\"H\", 1, blocks2, false, h);\n\t\tLOG4CXX_INFO(logger, \"Distributed factor matrices\");\n\n\t\t// initialize the DSGD\n\t\tTimer t;\n\t\tDsgdRunner dsgdRunner(random);\n\t\tDsgdJob<Update,Regularize> dsgdJob(dv, dw, dh, update, regularize, order,\n\t\t\t\tstratumOrder, false, tasksPerRank);\n\t\tDistributedDecayAuto<Update,Regularize,Loss> decay(dsgdJob, loss, Vsample, \"decay\", epsMax,\n\t\t\t\tworld.size()*tasksPerRank);\n\t\tTrace trace;\n\n\t\t// run DSGD to try to reconstruct the original factors\n\t\tt.start();\n\t\tdsgdRunner.run(dsgdJob, loss, epochs, decay, trace);\n\t\tt.stop();\n\t\tLOG4CXX_INFO(logger, \"Total time: \" << t);\n\n\t\t// write trace to an R file\n\t\tLOG4CXX_INFO(logger, \"Writing trace to \" << \"/tmp/dsgd-gkl-trace.R\");\n\t\ttrace.toRfile(\"/tmp/dsgd-gkl-trace.R\", \"dsgd.gkl\");\n\t}\n\n\tmfStop();\n\tmfFinalize();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "74f77bea0529b9c674d5d2f167407774c447f532", "size": 5219, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/mf/dsgd-gnmf.cc", "max_stars_repo_name": "Hui-Li/DSGDPP", "max_stars_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-01-10T11:39:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-02T23:03:55.000Z", "max_issues_repo_path": "examples/mf/dsgd-gnmf.cc", "max_issues_repo_name": "Hui-Li/DSGDPP", "max_issues_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/mf/dsgd-gnmf.cc", "max_forks_repo_name": "Hui-Li/DSGDPP", "max_forks_repo_head_hexsha": "0ce5b115bfbed81cee1c39fbfa4a8f67a5e1b72e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-10-27T18:40:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T15:10:56.000Z", "avg_line_length": 35.2635135135, "max_line_length": 99, "alphanum_fraction": 0.7135466564, "num_tokens": 1467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4011471626771152}}
{"text": "/*\n Copyright (c) 2010, The Barbarian Group\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n    * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include \"cinder/PolyLine.h\"\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/geometry/geometries/polygon.hpp>\n#include <boost/geometry/multi/multi.hpp>\n\nnamespace cinder {\n\n\ntemplate<typename T>\nbool PolyLineT<T>::isClockwise( bool *isColinear ) const\n{\n\tif( mPoints.size() < 3 ) {\n\t\tif( isColinear != nullptr ) *isColinear = true;\n\t\treturn false;\n\t}\n\n\tsize_t last = mPoints.size() - 1;\n\t// If the first and last point are the same (on a closed polygon), ignore one.\n\tif( mPoints.front() == mPoints.back() ) --last;\n\n\t// Find an extreme point since we know it will be on the hull...\n\tsize_t smallest = 0;\n\tfor( size_t i = 1; i <= last; ++i ) {\n\t\tif( mPoints[i].x < mPoints[smallest].x ) {\n\t\t\tsmallest = i;\n\t\t}\n\t\telse if( mPoints[i].x == mPoints[smallest].x && mPoints[i].y < mPoints[smallest].y ) {\n\t\t\tsmallest = i;\n\t\t}\n\t};\n\t// ...then get the next and previous point\n\tsize_t prev = ( smallest == 0 )    ? last : ( smallest - 1 );\n\tsize_t next = ( smallest == last ) ? 0    : ( smallest + 1 );\n\tT a = mPoints[next], b = mPoints[smallest], c = mPoints[prev];\n\n\t// The sign of the determinate indicates the orientation:\n\t//   positive is clockwise\n\t//   zero is colinear\n\t//   negative is counterclockwise\n\tdouble determinate = ( b.x - a.x ) * ( c.y - a.y ) - ( c.x - a.x ) * ( b.y - a.y );\n\tif( isColinear != nullptr ) *isColinear = determinate == 0.0;\n\treturn determinate > 0.0;\n}\n\ntemplate<typename T>\nbool PolyLineT<T>::isCounterclockwise( bool *isColinear ) const\n{\n\tbool colinear;\n\tbool clockwise = this->isClockwise( &colinear );\n\tif( isColinear != nullptr ) *isColinear = colinear;\n\treturn colinear ? false : ! clockwise;\n}\n\ntemplate<typename T>\nT PolyLineT<T>::getPosition( float t ) const\n{\n\ttypedef typename T::value_type R;\n\tif( mPoints.size() <= 1 ) return T();\n\tif( t >= 1 ) return mPoints.back();\n\tif( t <= 0 ) return mPoints[0];\n\t\n\tsize_t numSpans = mPoints.size() - 1;\n\tsize_t span = (size_t)math<R>::floor( t * numSpans );\n\tR lerpT = ( t - span / (R)numSpans ) * numSpans;\n\treturn mPoints[span] * ( 1 - lerpT ) + mPoints[span+1] * lerpT;\n}\n\ntemplate<typename T>\nT PolyLineT<T>::getDerivative( float t ) const\n{\n\ttypedef typename T::value_type R;\n\tif( mPoints.size() <= 1 ) return T();\n\tif( t >= 1 ) return mPoints.back() - mPoints[mPoints.size()-2];\n\tif( t <= 0 ) return mPoints[1] - mPoints[0];\n\t\n\tsize_t numSpans = mPoints.size() - 1;\n\tsize_t span = (size_t)math<R>::floor( t * numSpans );\n\treturn mPoints[span+1] - mPoints[span];\n}\n\ntemplate<typename T>\nvoid PolyLineT<T>::scale( const T &scaleFactor, T scaleCenter )\n{\n\tfor( typename std::vector<T>::iterator ptIt = mPoints.begin(); ptIt != mPoints.end(); ++ptIt )\n\t\t*ptIt = scaleCenter + ( *ptIt - scaleCenter ) * scaleFactor;\n}\n\ntemplate<typename T>\nPolyLineT<T> PolyLineT<T>::scaled( const T &scaleFactor, T scaleCenter ) const\n{\n\tPolyLineT<T> result( *this );\n\tresult.scale( scaleFactor, scaleCenter );\n\treturn result;\n}\n\ntemplate<typename T>\nvoid PolyLineT<T>::offset( const T &offsetBy )\n{\n\tfor( typename std::vector<T>::iterator ptIt = mPoints.begin(); ptIt != mPoints.end(); ++ptIt )\n\t\t*ptIt += offsetBy;\n}\n\ntemplate<typename T>\nPolyLineT<T> PolyLineT<T>::getOffset( const T &offsetBy ) const\n{\n\tPolyLineT<T> result( *this );\n\tresult.offset( offsetBy );\n\treturn result;\n}\n\ntemplate<typename T>\nvoid PolyLineT<T>::reverse()\n{\n\tstd::reverse( mPoints.begin(), mPoints.end() );\n}\n\ntemplate<typename T>\nPolyLineT<T> PolyLineT<T>::reversed() const\n{\n\tPolyLineT result( *this );\n\tstd::reverse( result.mPoints.begin(), result.mPoints.end() );\n\treturn result;\n}\n\ntemplate<typename T>\nT linearYatX( const glm::tvec2<T, glm::defaultp> p[2], T x )\n{\n\tif( p[0].x == p[1].x ) \treturn p[0].y;\n\treturn p[0].y + (p[1].y - p[0].y) * (x - p[0].x) / (p[1].x - p[0].x);\n}\n\ntemplate<typename T>\nsize_t linearCrossings( const glm::tvec2<T, glm::defaultp> p[2], const vec2 &pt )\n{\n\tif( (p[0].x < pt.x && pt.x <= p[1].x ) ||\n\t\t(p[1].x < pt.x && pt.x <= p[0].x )) {\n\t\tif( pt.y > linearYatX<T>( p, pt.x ) )\n\t\t\treturn 1;\n\t}\n\treturn 0;\n}\n\ntemplate<typename T>\nbool PolyLineT<T>::contains( const vec2 &pt ) const\n{\n\tif( mPoints.size() <= 2 )\n\t\treturn false;\n\n\tsize_t crossings = 0;\n\tfor( size_t s = 0; s < mPoints.size() - 1; ++s ) {\n\t\tcrossings += linearCrossings( &(mPoints[s]), pt );\n\t}\n\n\tT temp[2];\n\ttemp[0] = mPoints[mPoints.size()-1];\n\ttemp[1] = mPoints[0];\n\tcrossings += linearCrossings( &(temp[0]), pt );\n\t\n\treturn (crossings & 1) == 1;\n}\n\ntemplate<typename T>\ndouble PolyLineT<T>::calcArea() const\n{\n\tdouble sum = 0;\n\tconst size_t numPoints = mPoints.size();\n\tif( numPoints > 2 ) {\n\t\tfor( size_t i = 0; i < numPoints - 1; ++i )\n\t\t\tsum += mPoints[i].x * mPoints[i+1].y - mPoints[i+1].x * mPoints[i].y;\n\t\tsum += mPoints[numPoints-1].x * mPoints[0].y - mPoints[0].x * mPoints[numPoints-1].y;\n\t}\n\n\treturn glm::abs(sum * 0.5);\n}\n\ntemplate<typename T>\nT PolyLineT<T>::calcCentroid() const\n{\n\tT result( 0 );\n\n\tconst size_t numPoints = mPoints.size();\n\tdouble area = 0;\n\tif( numPoints > 2 ) {\n\t\tfor( size_t i = 0; i < numPoints - 1; ++i ) {\n\t\t\tdouble subExpr = mPoints[i].x * mPoints[i+1].y - mPoints[i+1].x * mPoints[i].y;\n\t\t\tresult.x += ( mPoints[i].x + mPoints[i+1].x ) * subExpr;\n\t\t\tresult.y += ( mPoints[i].y + mPoints[i+1].y ) * subExpr;\n\t\t\tarea += subExpr;\n\t\t}\n\t\tdouble subExpr = mPoints[numPoints-1].x * mPoints[0].y - mPoints[0].x * mPoints[numPoints-1].y;\n\t\tresult.x += ( mPoints[numPoints-1].x + mPoints[0].x ) * subExpr;\n\t\tresult.y += ( mPoints[numPoints-1].y + mPoints[0].y ) * subExpr;\n\t\tarea += subExpr;\n\n\t\tresult *= 1 / ( area * 3 );\n\t}\n\n\treturn result;\n}\n\nnamespace {\ntypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;\n\ntemplate<typename T>\nstd::vector<PolyLineT<T> > convertBoostGeometryPolygons( std::vector<polygon> &polygons )\n{\n\tstd::vector<PolyLineT<T> > result;\n\tfor( std::vector<polygon>::const_iterator outIt = polygons.begin(); outIt != polygons.end(); ++outIt ) {\n\t\ttypedef polygon::inner_container_type::const_iterator RingIterator;\n\t\ttypedef polygon::ring_type::const_iterator PointIterator;\n\n\t\tresult.push_back( PolyLineT<T>() );\n\t\tfor( PointIterator pt = outIt->outer().begin(); pt != outIt->outer().end(); ++pt )\n\t\t\tresult.back().push_back( T( boost::geometry::get<0>(*pt), boost::geometry::get<1>(*pt) ) );\n\n\t\tfor( RingIterator crunk = outIt->inners().begin(); crunk != outIt->inners().end(); ++crunk ) {\n\t\t\tPolyLineT<T> contour;\n\t\t\tfor( PointIterator pt = crunk->begin(); pt != crunk->end(); ++pt )\n\t\t\t\tcontour.push_back( T( boost::geometry::get<0>(*pt), boost::geometry::get<1>(*pt) ) );\n\t\t\tresult.push_back( contour );\n\t\t}\n\t}\n\t\n\treturn result;\n}\n\ntemplate<typename T>\npolygon convertPolyLinesToBoostGeometry( const std::vector<PolyLineT<T> > &a )\n{\n\tpolygon result;\n\t\n\tfor( typename std::vector<T>::const_iterator ptIt = a[0].getPoints().begin(); ptIt != a[0].getPoints().end(); ++ptIt )\n\t\tresult.outer().push_back( boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( ptIt->x, ptIt->y ) );\n\tfor( typename std::vector<PolyLineT<T> >::const_iterator plIt = a.begin() + 1; plIt != a.end(); ++plIt ) {\n\t\tpolygon::ring_type ring;\n\t\tfor( typename std::vector<T>::const_iterator ptIt = plIt->getPoints().begin(); ptIt != plIt->getPoints().end(); ++ptIt )\n\t\t\tring.push_back( boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( ptIt->x, ptIt->y ) );\n\t\tresult.inners().push_back( ring );\n\t}\n\t\n\tboost::geometry::correct( result );\n\t\n\treturn result;\n}\n} // anonymous namespace\n\ntemplate<typename T>\nstd::vector<PolyLineT<T> > PolyLineT<T>::calcUnion( const std::vector<PolyLineT<T> > &a, std::vector<PolyLineT<T> > &b )\n{\n\ttypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;\n\n\tif( a.empty() )\n\t\treturn b;\n\telse if( b.empty() )\n\t\treturn a;\n\n\tpolygon polyA = convertPolyLinesToBoostGeometry( a );\n\tpolygon polyB = convertPolyLinesToBoostGeometry( b );\n\t\n\tstd::vector<polygon> output;\n\tboost::geometry::union_( polyA, polyB, output );\n\n\treturn convertBoostGeometryPolygons<T>( output );\n}\n\ntemplate<typename T>\nstd::vector<PolyLineT<T> > PolyLineT<T>::calcIntersection( const std::vector<PolyLineT<T> > &a, std::vector<PolyLineT<T> > &b )\n{\n\ttypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;\n\n\tif( a.empty() )\n\t\treturn b;\n\telse if( b.empty() )\n\t\treturn a;\n\n\tpolygon polyA = convertPolyLinesToBoostGeometry( a );\n\tpolygon polyB = convertPolyLinesToBoostGeometry( b );\n\t\n\tstd::vector<polygon> output;\n\tboost::geometry::intersection( polyA, polyB, output );\n\n\treturn convertBoostGeometryPolygons<T>( output );\n}\n\ntemplate<typename T>\nstd::vector<PolyLineT<T> > PolyLineT<T>::calcXor( const std::vector<PolyLineT<T> > &a, std::vector<PolyLineT<T> > &b )\n{\n\ttypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;\n\n\tif( a.empty() )\n\t\treturn b;\n\telse if( b.empty() )\n\t\treturn a;\n\n\tpolygon polyA = convertPolyLinesToBoostGeometry( a );\n\tpolygon polyB = convertPolyLinesToBoostGeometry( b );\n\t\n\tstd::vector<polygon> output;\n\tboost::geometry::sym_difference( polyA, polyB, output );\n\n\treturn convertBoostGeometryPolygons<T>( output );\n}\n\ntemplate<typename T>\nstd::vector<PolyLineT<T> > PolyLineT<T>::calcDifference( const std::vector<PolyLineT<T> > &a, std::vector<PolyLineT<T> > &b )\n{\n\ttypedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;\n\n\tif( a.empty() )\n\t\treturn b;\n\telse if( b.empty() )\n\t\treturn a;\n\n\tpolygon polyA = convertPolyLinesToBoostGeometry( a );\n\tpolygon polyB = convertPolyLinesToBoostGeometry( b );\n\t\n\tstd::vector<polygon> output;\n\tboost::geometry::difference( polyA, polyB, output );\n\n\treturn convertBoostGeometryPolygons<T>( output );\n}\n\ntemplate class PolyLineT<vec2>;\ntemplate class PolyLineT<dvec2>;\n\n} // namespace cinder\n", "meta": {"hexsha": "81c91b49e787a10f7695d0e35f6e96e33fef6ce3", "size": 11134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cinder/PolyLine.cpp", "max_stars_repo_name": "rsh/Cinder-Emscripten", "max_stars_repo_head_hexsha": "4a08250c56656865c7c3a52fb9380980908b1439", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-12-07T23:03:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-03T14:55:54.000Z", "max_issues_repo_path": "src/cinder/PolyLine.cpp", "max_issues_repo_name": "rsh/Cinder-Emscripten", "max_issues_repo_head_hexsha": "4a08250c56656865c7c3a52fb9380980908b1439", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2015-12-11T21:53:05.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-04T11:54:54.000Z", "max_forks_repo_path": "src/cinder/PolyLine.cpp", "max_forks_repo_name": "rsh/Cinder-Emscripten", "max_forks_repo_head_hexsha": "4a08250c56656865c7c3a52fb9380980908b1439", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T18:26:57.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-22T00:11:55.000Z", "avg_line_length": 31.7207977208, "max_line_length": 127, "alphanum_fraction": 0.6773845877, "num_tokens": 3307, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5736784074525096, "lm_q1q2_score": 0.4011471626771152}}
{"text": "//=======================================================================\n// Copyright 2007 Aaron Windsor\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n#include <iostream>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <vector>\n\n#include <boost/graph/planar_canonical_ordering.hpp>\n#include <boost/graph/is_straight_line_drawing.hpp>\n#include <boost/graph/chrobak_payne_drawing.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n\nusing namespace boost;\n\n// a class to hold the coordinates of the straight line embedding\nstruct coord_t\n{\n    std::size_t x;\n    std::size_t y;\n};\n\nint main(int argc, char** argv)\n{\n    typedef adjacency_list< vecS, vecS, undirectedS,\n        property< vertex_index_t, int > >\n        graph;\n\n    // Define the storage type for the planar embedding\n    typedef std::vector< std::vector< graph_traits< graph >::edge_descriptor > >\n        embedding_storage_t;\n    typedef boost::iterator_property_map< embedding_storage_t::iterator,\n        property_map< graph, vertex_index_t >::type >\n        embedding_t;\n\n    // Create the graph - a maximal planar graph on 7 vertices. The functions\n    // planar_canonical_ordering and chrobak_payne_straight_line_drawing both\n    // require a maximal planar graph. If you start with a graph that isn't\n    // maximal planar (or you're not sure), you can use the functions\n    // make_connected, make_biconnected_planar, and make_maximal planar in\n    // sequence to add a set of edges to any undirected planar graph to make\n    // it maximal planar.\n\n    graph g(7);\n    add_edge(0, 1, g);\n    add_edge(1, 2, g);\n    add_edge(2, 3, g);\n    add_edge(3, 0, g);\n    add_edge(3, 4, g);\n    add_edge(4, 5, g);\n    add_edge(5, 6, g);\n    add_edge(6, 3, g);\n    add_edge(0, 4, g);\n    add_edge(1, 3, g);\n    add_edge(3, 5, g);\n    add_edge(2, 6, g);\n    add_edge(1, 4, g);\n    add_edge(1, 5, g);\n    add_edge(1, 6, g);\n\n    // Create the planar embedding\n    embedding_storage_t embedding_storage(num_vertices(g));\n    embedding_t embedding(embedding_storage.begin(), get(vertex_index, g));\n\n    boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,\n        boyer_myrvold_params::embedding = embedding);\n\n    // Find a canonical ordering\n    std::vector< graph_traits< graph >::vertex_descriptor > ordering;\n    planar_canonical_ordering(g, embedding, std::back_inserter(ordering));\n\n    // Set up a property map to hold the mapping from vertices to coord_t's\n    typedef std::vector< coord_t > straight_line_drawing_storage_t;\n    typedef boost::iterator_property_map<\n        straight_line_drawing_storage_t::iterator,\n        property_map< graph, vertex_index_t >::type >\n        straight_line_drawing_t;\n\n    straight_line_drawing_storage_t straight_line_drawing_storage(\n        num_vertices(g));\n    straight_line_drawing_t straight_line_drawing(\n        straight_line_drawing_storage.begin(), get(vertex_index, g));\n\n    // Compute the straight line drawing\n    chrobak_payne_straight_line_drawing(\n        g, embedding, ordering.begin(), ordering.end(), straight_line_drawing);\n\n    std::cout << \"The straight line drawing is: \" << std::endl;\n    graph_traits< graph >::vertex_iterator vi, vi_end;\n    for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n    {\n        coord_t coord(get(straight_line_drawing, *vi));\n        std::cout << *vi << \" -> (\" << coord.x << \", \" << coord.y << \")\"\n                  << std::endl;\n    }\n\n    // Verify that the drawing is actually a plane drawing\n    if (is_straight_line_drawing(g, straight_line_drawing))\n        std::cout << \"Is a plane drawing.\" << std::endl;\n    else\n        std::cout << \"Is not a plane drawing.\" << std::endl;\n\n    return 0;\n}\n", "meta": {"hexsha": "b76bb4ab39f60f690385f1634188cfcd1060215f", "size": 4003, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "venv/boost_1_73_0/libs/graph/example/straight_line_drawing.cpp", "max_stars_repo_name": "uosorio/heroku_face", "max_stars_repo_head_hexsha": "7d6465e71dba17a15d8edaef520adb2fcd09d91e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "3rdparty/boost_1_73_0/libs/graph/example/straight_line_drawing.cpp", "max_issues_repo_name": "qingkouwei/mediaones", "max_issues_repo_head_hexsha": "cec475e1bfd5807b5351cc7e38d244ac5298ca16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/graph/example/straight_line_drawing.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 36.0630630631, "max_line_length": 80, "alphanum_fraction": 0.6627529353, "num_tokens": 1018, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.6261241702517975, "lm_q1q2_score": 0.4011175930451822}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_HYPOT_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_HYPOT_HPP_INCLUDED\n#include <boost/simd/include/functor.hpp>\n#include <boost/dispatch/include/functor.hpp>\n\nnamespace boost { namespace simd { namespace tag\n  {\n    /*!\n      @brief  hypot generic tag\n\n      Represents the hypot function in generic contexts.\n\n      @par Models:\n      Hierarchy\n    **/\n    struct hypot_ : ext::elementwise_<hypot_>\n    {\n      /// @brief Parent hierarchy\n      typedef ext::elementwise_<hypot_> parent;\n      template<class... Args>\n      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)\n      BOOST_AUTO_DECLTYPE_BODY( dispatching_hypot_( ext::adl_helper(), static_cast<Args&&>(args)... ) )\n    };\n  }\n  namespace ext\n  {\n    template<class Site, class... Ts>\n    BOOST_FORCEINLINE generic_dispatcher<tag::hypot_, Site> dispatching_hypot_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n    {\n      return generic_dispatcher<tag::hypot_, Site>();\n    }\n    template<class... Args>\n    struct impl_hypot_;\n  }\n  /*!\n    Computes \\f$(x^2 + y^2)^{1/2}\\f$\n\n    @par semantic:\n    For any given value @c x,  @c y of floating type @c T:\n\n    @code\n    T r = hypot(x, y);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    T r = sqrt(sqr(x)+sqr(y));\n    @endcode\n\n    Provision are made to avoid overflow as possible and to compute\n    @c hypot accurately.\n    If these considerations can be put aside use\n    @c fast_hypot.\n\n    @param  a0\n    @param  a1\n\n    @return      a value of the same type as the input.\n\n  **/\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::hypot_, hypot, 2)\n} }\n\n#endif\n\n\n", "meta": {"hexsha": "0f76c8cd451c19081f091f0050afbc42c98face0", "size": 2203, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/hypot.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/hypot.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/hypot.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9868421053, "max_line_length": 169, "alphanum_fraction": 0.6055379029, "num_tokens": 558, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.4011036576761863}}
{"text": "#ifndef MATHPARSER_HPP\n#define MATHPARSER_HPP\n\n/*=============================================================================\n    Copyright (c) 2004 Angus Leeming\n\n    Distributed under the Boost Software License, Version 1.0.\n    (See accompanying file LICENSE_1_0.txt or copy at\n    http://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n#if defined PHOENIX_LIMIT && PHOENIX_LIMIT < 6\n#undef PHOENIX_LIMIT\n#endif\n\n#ifndef PHOENIX_LIMIT\n#define PHOENIX_LIMIT 6\n#endif\n\n#define YAC_SINGLE_COMPILATION_UNIT\n\n#include \"external/yac/yac_gnuplot_grammar.hpp\"\n#include \"external/yac/yac_skip_grammar.hpp\"\n#include \"external/yac/yac_virtual_machine.hpp\"\n\n#include <boost/spirit/iterator/file_iterator.hpp>\n#include <boost/math/special_functions/acosh.hpp>\n#include <boost/math/special_functions/asinh.hpp>\n#include <boost/math/special_functions/atanh.hpp>\n\n#include <iostream>\n#include <sstream>\n#include <string>\n\nusing std::cerr;\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::string;\n\nnamespace spirit = boost::spirit;\n\nnamespace {\n\nint    bitwise_and(int a, int b) { return a & b; }\nint    bitwise_or(int a, int b) { return a | b; }\nint    bitwise_xor(int a, int b) { return a ^ b; }\nbool   logical_and(bool a, bool b) { return a && b; }\ndouble logical_not(double a) { return !a; }\ndouble equal(double a, double b) { return a == b; }\ndouble not_equal(double a, double b) { return a != b; }\ndouble less(double a, double b) { return a < b; }\ndouble greater(double a, double b) { return a > b; }\ndouble less_equal(double a, double b) { return a <= b; }\ndouble greater_equal(double a, double b) { return a >= b; }\nint    shift_left(int a, int b) { return a << b; }\nint    shift_right(int a, int b) { return a >> b; }\ndouble add(double a, double b) { return a + b; }\ndouble subtract(double a, double b) { return a - b; }\ndouble multiply(double a, double b) { return a * b; }\ndouble divide(double a, double b) { return a / b; }\nint    mod(int a, int b) { return a % b; }\ndouble negate(double a) { return -a; }\ndouble sgn(double a) { return a >= 0.0 ? 1.0 : -1.0; }\n\ntypedef int(* ifunc2_ptr_t)(int, int);\ntypedef bool(* bfunc2_ptr_t)(bool, bool);\ntypedef double(* dfunc2_ptr_t)(double, double);\ntypedef double(* dfunc1_ptr_t)(double);\n\n} // namespace anon\n\nnamespace yac {\n\nboost::shared_ptr<function> make_func(string const & name, dfunc1_ptr_t ptr)\n{\n    return boost::shared_ptr<function>(new function1<double>(name, ptr));\n}\n\n\nboost::shared_ptr<function> make_func(string const & name, dfunc2_ptr_t ptr)\n{\n    return boost::shared_ptr<function>(new function2<double>(name, ptr));\n}\n\nboost::shared_ptr<function> make_func(string const & name, bfunc2_ptr_t ptr)\n{\n    return boost::shared_ptr<function>(new function2<bool>(name, ptr));\n}\n\nboost::shared_ptr<function> make_func(string const & name, ifunc2_ptr_t ptr)\n{\n    return boost::shared_ptr<function>(new function2<int>(name, ptr));\n}\n\nclass controller {\nprivate:\n\t  virtual_machine vm;\n\t  std::vector<RealType> x_vector, y_vector;\npublic:\n  RealType time;\n  controller():\n    time(0.)\n    {\n      std::vector<RealType> X;\n      std::vector<RealType> Y;\n      X.push_back(0.);\n      Y.push_back(0.);\n      x_vector = X;\n      y_vector = Y;\n\n      char const * const keywords[] = {\n\t\"x\", \"y\",\n\t\"return\",\n\t\"pi\",\n\t\"abs\", \"acos\", \"acosh\", \"asin\", \"asinh\", \"atan\",\n\t\"atanh\", \"besj0\", \"besj1\", \"besy0\", \"besy1\", \"ceil\",\n\t\"cos\", \"cosh\",\n#if defined(__GNUC__)\n\t\"erf\", \"erfc\",\n#endif\n\t\"exp\", \"floor\", \"log\", \"log10\", \"sgn\", \"sin\", \"sinh\",\n\t\"sqrt\", \"tan\", \"tanh\", \"atan2\",\n      };\n      std::size_t const keywords_size =\n\tsizeof(keywords) / sizeof(keywords[0]);\n\n      for (std::size_t i = 0; i != keywords_size; ++i)\n\tname_grammar::reserved_keywords.add(keywords[i]);\n\n      vm.global_vars.add\n\t(\"pi\", 3.1415926536);\n\n      vm.funcs.add\n\t(\"bitwise_and##2\",   make_func(\"bitwise_and#\",   &::bitwise_and))\n\t(\"bitwise_or##2\",    make_func(\"bitwise_or#\",    &::bitwise_or))\n\t(\"bitwise_xor##2\",   make_func(\"bitwise_xor#\",   &::bitwise_xor))\n\t(\"logical_and##2\",   make_func(\"logical_and#\",   &::logical_and))\n\t(\"logical_not##1\",   make_func(\"logical_not#\",   &::logical_not))\n\t(\"equal##2\",         make_func(\"equal#\",         &::equal))\n\t(\"not_equal##2\",     make_func(\"not_equal#\",     &::not_equal))\n\t(\"less##2\",          make_func(\"less#\",          &::less))\n\t(\"greater##2\",       make_func(\"greater#\",       &::greater))\n\t(\"less_equal##2\",    make_func(\"less_equal#\",    &::less_equal))\n\t(\"greater_equal##2\", make_func(\"greater_equal#\", &::greater_equal))\n\t(\"shift_left##2\",    make_func(\"shift_left#\",    &::shift_left))\n\t(\"shift_right##2\",   make_func(\"shift_right#\",   &::shift_right))\n\t(\"add##2\",           make_func(\"add#\",           &::add))\n\t(\"subtract##2\",      make_func(\"subtract#\",      &::subtract))\n\t(\"multiply##2\",      make_func(\"multiply#\",      &::multiply))\n\t(\"divide##2\",        make_func(\"divide#\",        &::divide))\n\t(\"mod##2\",           make_func(\"mod#\",           &::mod))\n\t(\"negate##1\",        make_func(\"negate#\",        &::negate))\n\t(\"abs#1\",   make_func(\"abs\",   &std::abs))\n\t(\"acos#1\",  make_func(\"acos\",  &std::acos))\n\t(\"asin#1\",  make_func(\"asin\",  &std::asin))\n\t(\"atan#1\",  make_func(\"atan\",  &std::atan))\n\t(\"acosh#1\", make_func(\"acosh\", &boost::math::acosh))\n\t(\"asinh#1\", make_func(\"asinh\", &boost::math::asinh))\n\t(\"atanh#1\", make_func(\"atanh\", &boost::math::atanh))\n\t(\"besj0#1\", make_func(\"besj0\", &j0))\n\t(\"besj1#1\", make_func(\"besj1\", &j1))\n\t(\"besy0#1\", make_func(\"besy0\", &y0))\n\t(\"besy1#1\", make_func(\"besy1\", &y1))\n\t(\"ceil#1\",  make_func(\"ceil\",  &std::ceil))\n\t(\"cos#1\",   make_func(\"cos\",   &std::cos))\n\t(\"cosh#1\",  make_func(\"cosh\",  &std::cosh))\n#if defined(__GNUC__)\n\t(\"erf#1\",   make_func(\"erf\",   &erf))\n\t(\"erfc#1\",  make_func(\"erfc\",  &erfc))\n#endif\n\t(\"exp#1\",   make_func(\"exp\",   &std::exp))\n\t(\"floor#1\", make_func(\"floor\", &std::floor))\n\t(\"log#1\",   make_func(\"log\",   &std::log))\n\t(\"log10#1\", make_func(\"log10\", &std::log10))\n\t(\"sgn#1\",   make_func(\"sgn\",   &sgn))\n\t(\"sin#1\",   make_func(\"sin\",   &std::sin))\n\t(\"sinh#1\",  make_func(\"sinh\",  &std::sinh))\n\t(\"sqrt#1\",  make_func(\"sqrt\",  &std::sqrt))\n\t(\"tan#1\",   make_func(\"tan\",   &std::tan))\n\t(\"tanh#1\",  make_func(\"tanh\",  &std::tanh))\n\t(\"atan2#2\", make_func(\"atan2\", &std::atan2));\n    }\n  \n  controller(std::vector<RealType> &X, std::vector<RealType> &Y, RealType &time_)\n    : x_vector(X), y_vector(Y), time(time_)\n  {\n        char const * const keywords[] = {\n\t  \"x\", \"y\", \"t\",\n\t  \"return\",\n\t  \"pi\",\n            \"abs\", \"acos\", \"acosh\", \"asin\", \"asinh\", \"atan\",\n            \"atanh\", \"besj0\", \"besj1\", \"besy0\", \"besy1\", \"ceil\",\n            \"cos\", \"cosh\",\n#if defined(__GNUC__)\n            \"erf\", \"erfc\",\n#endif\n            \"exp\", \"floor\", \"log\", \"log10\", \"sgn\", \"sin\", \"sinh\",\n            \"sqrt\", \"tan\", \"tanh\", \"atan2\",\n        };\n        std::size_t const keywords_size =\n            sizeof(keywords) / sizeof(keywords[0]);\n\n        for (std::size_t i = 0; i != keywords_size; ++i)\n                name_grammar::reserved_keywords.add(keywords[i]);\n\n        vm.global_vars.add\n\t  (\"pi\", 3.1415926536);\n\n        vm.funcs.add\n            (\"bitwise_and##2\",   make_func(\"bitwise_and#\",   &::bitwise_and))\n            (\"bitwise_or##2\",    make_func(\"bitwise_or#\",    &::bitwise_or))\n            (\"bitwise_xor##2\",   make_func(\"bitwise_xor#\",   &::bitwise_xor))\n            (\"logical_and##2\",   make_func(\"logical_and#\",   &::logical_and))\n            (\"logical_not##1\",   make_func(\"logical_not#\",   &::logical_not))\n            (\"equal##2\",         make_func(\"equal#\",         &::equal))\n            (\"not_equal##2\",     make_func(\"not_equal#\",     &::not_equal))\n            (\"less##2\",          make_func(\"less#\",          &::less))\n            (\"greater##2\",       make_func(\"greater#\",       &::greater))\n            (\"less_equal##2\",    make_func(\"less_equal#\",    &::less_equal))\n            (\"greater_equal##2\", make_func(\"greater_equal#\", &::greater_equal))\n            (\"shift_left##2\",    make_func(\"shift_left#\",    &::shift_left))\n            (\"shift_right##2\",   make_func(\"shift_right#\",   &::shift_right))\n            (\"add##2\",           make_func(\"add#\",           &::add))\n            (\"subtract##2\",      make_func(\"subtract#\",      &::subtract))\n            (\"multiply##2\",      make_func(\"multiply#\",      &::multiply))\n            (\"divide##2\",        make_func(\"divide#\",        &::divide))\n            (\"mod##2\",           make_func(\"mod#\",           &::mod))\n            (\"negate##1\",        make_func(\"negate#\",        &::negate))\n            (\"abs#1\",   make_func(\"abs\",   &std::abs))\n            (\"acos#1\",  make_func(\"acos\",  &std::acos))\n            (\"asin#1\",  make_func(\"asin\",  &std::asin))\n            (\"atan#1\",  make_func(\"atan\",  &std::atan))\n            (\"acosh#1\", make_func(\"acosh\", &boost::math::acosh))\n            (\"asinh#1\", make_func(\"asinh\", &boost::math::asinh))\n            (\"atanh#1\", make_func(\"atanh\", &boost::math::atanh))\n            (\"besj0#1\", make_func(\"besj0\", &j0))\n            (\"besj1#1\", make_func(\"besj1\", &j1))\n            (\"besy0#1\", make_func(\"besy0\", &y0))\n            (\"besy1#1\", make_func(\"besy1\", &y1))\n            (\"ceil#1\",  make_func(\"ceil\",  &std::ceil))\n            (\"cos#1\",   make_func(\"cos\",   &std::cos))\n            (\"cosh#1\",  make_func(\"cosh\",  &std::cosh))\n#if defined(__GNUC__)\n            (\"erf#1\",   make_func(\"erf\",   &erf))\n            (\"erfc#1\",  make_func(\"erfc\",  &erfc))\n#endif\n            (\"exp#1\",   make_func(\"exp\",   &std::exp))\n            (\"floor#1\", make_func(\"floor\", &std::floor))\n            (\"log#1\",   make_func(\"log\",   &std::log))\n            (\"log10#1\", make_func(\"log10\", &std::log10))\n            (\"sgn#1\",   make_func(\"sgn\",   &sgn))\n            (\"sin#1\",   make_func(\"sin\",   &std::sin))\n            (\"sinh#1\",  make_func(\"sinh\",  &std::sinh))\n            (\"sqrt#1\",  make_func(\"sqrt\",  &std::sqrt))\n            (\"tan#1\",   make_func(\"tan\",   &std::tan))\n            (\"tanh#1\",  make_func(\"tanh\",  &std::tanh))\n            (\"atan2#2\", make_func(\"atan2\", &std::atan2));\n    }\n\n  void updateReservedVariables( std::vector<RealType> &X, \n\t\t\t\tstd::vector<RealType> &Y )\n  {\n    x_vector = X;\n    y_vector = Y;\n  }\n\n  void updateTime( RealType& t ) {\n    time = t;\n  }\n\n    template <typename ItT>\n    std::vector<RealType> parse( ItT first, ItT last )\n  {\n        using phoenix::arg1;\n        using phoenix::var;\n\n        typedef spirit::parse_info<ItT> parse_info_t;\n\n        gnuplot_grammar calculator(vm.funcs, vm.global_vars);\n\n        parse_info_t info = spirit::parse(first, last,\n                                          calculator[var(vm.stk) = arg1],\n                                          skip_grammar());\n\n        if (info.full) {\n\t  std::vector<RealType> result = vectorizedEval(vm.stk,\n\t\t\t\t\t\t      x_vector,\n\t\t\t\t\t\t      y_vector, time );\n\t  return result;\n        } else {\n            cerr << \"-------------------------\\n\"\n                 << \"Math parsing failed\\n\"\n                 << \"-------------------------\\n\";\n\t    return std::vector<RealType> ( x_vector.size(), 0.0 );\n        }\n    }\n};\n\n} // namespace yac\n\n#endif // MATHPARSER_HPP\n", "meta": {"hexsha": "0e7e0ef4c53d440c1e2b4c7a8d757fdf43d677a7", "size": 11184, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "volna_init/mathParser.hpp", "max_stars_repo_name": "Devaraj-G/volna", "max_stars_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-07-08T23:53:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T11:55:28.000Z", "max_issues_repo_path": "volna_init/mathParser.hpp", "max_issues_repo_name": "Devaraj-G/volna", "max_issues_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-02T17:31:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-02T17:31:28.000Z", "max_forks_repo_path": "volna_init/mathParser.hpp", "max_forks_repo_name": "Devaraj-G/volna", "max_forks_repo_head_hexsha": "f4a25c19ae041c81442fc0461ea3ff2d7d8f95ba", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-02-05T19:34:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-01T08:46:34.000Z", "avg_line_length": 37.0331125828, "max_line_length": 81, "alphanum_fraction": 0.5495350501, "num_tokens": 3382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.4010936916389687}}
{"text": "#include \"Scheme.h\"\n\n#include <NTL/RR.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZX.h>\n#include <cmath>\n\n#include \"EvaluatorUtils.h\"\n#include \"NumUtils.h\"\n#include \"Params.h\"\n#include \"PubKey.h\"\n#include \"Ring2Utils.h\"\n\nusing namespace std;\nusing namespace NTL;\n\nCZZ* Scheme::groupidx(CZZ*& vals, long slots) {\n\tCZZ* res = new CZZ[slots * 2];\n\tlong logslots = log2(slots);\n\tfor (long i = 0; i < slots; ++i) {\n\t\tlong idx = (params.rotGroup[i] % (4 * slots) - 1) / 2;\n\t\tres[idx] = vals[i];\n\t\tres[2 * slots - idx - 1] = vals[i].conjugate();\n\t}\n\treturn res;\n}\n\nCZZ* Scheme::groupidx(CZZ& val) {\n\tCZZ* res = new CZZ[2];\n\tres[0] = val;\n\tres[1] = val.conjugate();\n\treturn res;\n}\n\nCZZ* Scheme::degroupidx(CZZ*& vals, long slots) {\n\tlong logslots = log2(slots);\n\tCZZ* res = new CZZ[slots];\n\tfor (long i = 0; i < slots; ++i) {\n\t\tlong idx = (params.rotGroup[i] % (4 * slots) - 1) / 2;\n\t\tres[i] = vals[idx];\n\t}\n\treturn res;\n}\n\n//-----------------------------------------\n\nMessage Scheme::encodeWithBits(CZZ*& gvals, long cbits, long slots) {\n\tZZX mx;\n\tmx.SetLength(params.N);\n\tZZ mod = power2_ZZ(cbits);\n\tlong idx = 0;\n\tlong doubleslots = slots << 1;\n\tlong logDoubleslots = log2(slots) + 1;\n\tlong gap = (params.N >> logDoubleslots);\n\tNumUtils::fftSpecialInv(gvals, doubleslots, aux);\n\tfor (long i = 0; i < doubleslots; ++i) {\n\t\tmx.rep[idx] = gvals[i].r;\n\t\tidx += gap;\n\t}\n\treturn Message(mx, mod, cbits, slots);\n}\n\nMessage Scheme::encode(CZZ*& gvals, long slots) {\n\tZZX mx;\n\tmx.SetLength(params.N);\n\tlong idx = 0;\n\tlong doubleslots = slots << 1;\n\tlong logDoubleslots = log2(slots) + 1;\n\tlong gap = (params.N >> logDoubleslots);\n\n\tNumUtils::fftSpecialInv(gvals, doubleslots, aux);\n\n\tfor (long i = 0; i < doubleslots; ++i) {\n\t\tmx.rep[idx] = gvals[i].r;\n\t\tidx += gap;\n\t}\n\treturn Message(mx, params.q, params.logq, slots);\n}\n\nCipher Scheme::encryptMsg(Message& msg) {\n\tZZX ax, bx, vx, eax, ebx;\n\tNumUtils::sampleZO(vx, params.N);\n\tRing2Utils::mult(ax, vx, publicKey.ax, msg.mod, params.N);\n\tNumUtils::sampleGauss(eax, params.N, params.sigma);\n\tRing2Utils::addAndEqual(ax, eax, msg.mod, params.N);\n\n\tRing2Utils::mult(bx, vx, publicKey.bx, msg.mod, params.N);\n\tNumUtils::sampleGauss(ebx, params.N, params.sigma);\n\tRing2Utils::addAndEqual(bx, ebx, msg.mod, params.N);\n\n\tRing2Utils::addAndEqual(bx, msg.mx, msg.mod, params.N);\n\n\treturn Cipher(ax, bx, msg.mod, msg.cbits, msg.slots);\n}\n\nCipher Scheme::encryptWithBits(CZZ*& vals, long cbits, long slots) {\n\tCZZ* gvals = groupidx(vals, slots);\n\tMessage msg = encodeWithBits(gvals, cbits, slots);\n\tdelete[] gvals;\n\treturn encryptMsg(msg);\n}\n\nCipher Scheme::encrypt(CZZ*& vals, long slots) {\n\tCZZ* gvals = groupidx(vals, slots);\n\tMessage msg = encode(gvals, slots);\n\tdelete[] gvals;\n\treturn encryptMsg(msg);\n}\n\nCipher Scheme::encryptSingleWithBits(CZZ& val, long cbits) {\n\tCZZ* gvals = groupidx(val);\n\tMessage msg = encodeWithBits(gvals, cbits, 1);\n\tdelete[] gvals;\n\treturn encryptMsg(msg);\n}\n\nCipher Scheme::encryptSingle(CZZ& val) {\n\tCZZ* gvals = groupidx(val);\n\tMessage msg = encode(gvals, 1);\n\tdelete[] gvals;\n\treturn encryptMsg(msg);\n}\n\n//-----------------------------------------\n\nMessage Scheme::decryptMsg(SecKey& secretKey, Cipher& cipher) {\n\tZZX mx;\n\tRing2Utils::mult(mx, cipher.ax, secretKey.sx, cipher.mod, params.N);\n\tRing2Utils::addAndEqual(mx, cipher.bx, cipher.mod, params.N);\n\treturn Message(mx, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nCZZ* Scheme::decode(Message& msg) {\n\tlong doubleslots = msg.slots * 2;\n\tCZZ* fftinv = new CZZ[doubleslots];\n\n\tlong idx = 0;\n\tlong gap = params.N / doubleslots;\n\tfor (long i = 0; i < doubleslots; ++i) {\n\t\tZZ tmp = msg.mx.rep[idx] % msg.mod;\n\t\tif(NumBits(tmp) == msg.cbits) tmp -= msg.mod;\n\t\tfftinv[i] = CZZ(tmp, ZZ(0));\n\t\tidx += gap;\n\t}\n\tNumUtils::fftSpecial(fftinv, doubleslots, aux);\n\treturn fftinv;\n}\n\nCZZ* Scheme::decrypt(SecKey& secretKey, Cipher& cipher) {\n\tMessage msg = decryptMsg(secretKey, cipher);\n\tCZZ* gvals = decode(msg);\n\tCZZ* res = degroupidx(gvals, msg.slots);\n\tdelete[] gvals;\n\treturn res;\n}\n\nCZZ Scheme::decryptSingle(SecKey& secretKey, Cipher& cipher) {\n\tMessage msg = decryptMsg(secretKey, cipher);\n\tCZZ* gvals = decode(msg);\n\tCZZ res = gvals[0];\n\tdelete[] gvals;\n\treturn res;\n}\n\n\n\n//-----------------------------------------\n\n\nCipher Scheme::negate(Cipher& cipher){\n    ZZX ax, bx;\n    \n    Ring2Utils::multByConst(ax, cipher.ax, to_ZZ(\"-1\"), cipher.mod, params.N);\n    Ring2Utils::multByConst(bx, cipher.bx, to_ZZ(\"-1\"), cipher.mod, params.N);\n    \n    return Cipher(ax, bx, cipher.mod, cipher.cbits, cipher.slots);\n}\n\n\nvoid Scheme::negateAndEqual(Cipher& cipher){\n    Ring2Utils::multByConstAndEqual(cipher.ax, to_ZZ(\"-1\"), cipher.mod, params.N);\n    Ring2Utils::multByConstAndEqual(cipher.bx, to_ZZ(\"-1\"), cipher.mod, params.N);\n}\n\n\n\n//-----------------------------------------\n\nCipher Scheme::add(Cipher& cipher1, Cipher& cipher2) {\n\tZZX ax, bx;\n\n\tRing2Utils::add(ax, cipher1.ax, cipher2.ax, cipher1.mod, params.N);\n\tRing2Utils::add(bx, cipher1.bx, cipher2.bx, cipher1.mod, params.N);\n\n\treturn Cipher(ax, bx, cipher1.mod, cipher1.cbits, cipher1.slots);\n}\n\nvoid Scheme::addAndEqual(Cipher& cipher1, Cipher& cipher2) {\n\tRing2Utils::addAndEqual(cipher1.ax, cipher2.ax, cipher1.mod, params.N);\n\tRing2Utils::addAndEqual(cipher1.bx, cipher2.bx, cipher1.mod, params.N);\n}\n\n//-----------------------------------------\n\nCipher Scheme::addConst(Cipher& cipher, ZZ& cnst) {\n\tZZX ax = cipher.ax;\n\tZZX bx = cipher.bx;\n\n\tAddMod(bx.rep[0], cipher.bx.rep[0], cnst, cipher.mod);\n\treturn Cipher(ax, bx, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::addConstAndEqual(Cipher& cipher, ZZ& cnst) {\n\tZZ mod = power2_ZZ(cipher.cbits);\n\tAddMod(cipher.bx.rep[0], cipher.bx.rep[0], cnst, mod);\n}\n\n\n//-----------------------------------------\n\nCipher Scheme::addByPoly(Cipher& cipher, Message& msg) {\n    ZZX axres, bxres;\n    \n    //Ring2Utils::add(axres, cipher.ax, msg.mx, cipher.mod, params.N);\n    Ring2Utils::add(bxres, cipher.bx, msg.mx, cipher.mod, params.N);\n    return Cipher(cipher.ax, bxres, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::addByPolyAndEqual(Cipher& cipher, Message& msg) {\n    //Ring2Utils::addAndEqual(cipher.ax, msg.mx, cipher.mod, params.N);\n    Ring2Utils::addAndEqual(cipher.bx, msg.mx, cipher.mod, params.N);\n}\n\n\n\n\n//-----------------------------------------\n\nCipher Scheme::sub(Cipher& cipher1, Cipher& cipher2) {\n\tZZX ax, bx;\n\n\tRing2Utils::sub(ax, cipher1.ax, cipher2.ax, cipher1.mod, params.N);\n\tRing2Utils::sub(bx, cipher1.bx, cipher2.bx, cipher1.mod, params.N);\n\n\treturn Cipher(ax, bx, cipher1.mod, cipher1.cbits, cipher1.slots);\n}\n\nvoid Scheme::subAndEqual(Cipher& cipher1, Cipher& cipher2) {\n\tRing2Utils::subAndEqual(cipher1.ax, cipher2.ax, cipher1.mod, params.N);\n\tRing2Utils::subAndEqual(cipher1.bx, cipher2.bx, cipher1.mod, params.N);\n}\n\nvoid Scheme::subAndEqual2(Cipher& cipher1, Cipher& cipher2) {\n\tRing2Utils::subAndEqual2(cipher1.ax, cipher2.ax, cipher1.mod, params.N);\n\tRing2Utils::subAndEqual2(cipher1.bx, cipher2.bx, cipher1.mod, params.N);\n}\n\n\n//-----------------------------------------\n\n// cipher - msg  = (b, a) - (mx, 0)\nCipher Scheme::subByPoly(Cipher& cipher, Message& msg) {\n    ZZX bxres;\n    //Ring2Utils::sub(axres, cipher.ax, msg.mx, cipher.mod, params.N);\n    Ring2Utils::sub(bxres, cipher.bx, msg.mx, cipher.mod, params.N);\n    return Cipher(cipher.ax, bxres, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::subByPolyAndEqual(Cipher& cipher, Message& msg) {\n  \n    Ring2Utils::subAndEqual(cipher.bx, msg.mx, cipher.mod, params.N);\n}\n\n// msg - cipher  = (mx, 0 ) - (b, a)\nCipher Scheme::subByPoly2(Cipher& cipher, Message& msg) {\n    ZZX axres, bxres;\n    \n    Ring2Utils::multByConst(axres, cipher.ax, to_ZZ(\"-1\"), cipher.mod, params.N);\n    Ring2Utils::sub(bxres, msg.mx, cipher.bx, cipher.mod, params.N);\n    return Cipher(axres, bxres, cipher.mod, cipher.cbits, cipher.slots);\n}\n\n//-----------------------------------------\n\nCipher Scheme::subConst(Cipher& cipher, ZZ& cnst){\n    ZZX ax = cipher.ax;\n    ZZX bx = cipher.bx;\n    \n    SubMod(bx.rep[0], cipher.bx.rep[0], cnst, cipher.mod);\n    return Cipher(ax, bx, cipher.mod, cipher.cbits, cipher.slots);\n}\n\n\nCipher Scheme::subConst2(Cipher& cipher, ZZ& cnst){\n    Cipher res = negate(cipher);\n    addConstAndEqual(res, cnst);\n    \n    return res;\n}\n\n\nvoid Scheme::subConstAndEqual(Cipher& cipher, ZZ& cnst){\n    //ZZX ax = cipher.ax;\n    //ZZX bx = cipher.bx;\n    \n    SubMod(cipher.bx.rep[0], cipher.bx.rep[0], cnst, cipher.mod);\n    //return Cipher(ax, bx, cipher.mod, cipher.cbits, cipher.slots);\n}\n//-----------------------------------------\n\n\n\nCipher Scheme::conjugate(Cipher& cipher) {\n\tZZ Pmod = cipher.mod << params.logq;\n\n\tZZX bxconj, bxres, axres;\n\n\tRing2Utils::conjugate(bxconj, cipher.bx, params.N);\n\tRing2Utils::conjugate(bxres, cipher.ax, params.N);\n\n\tRing2Utils::mult(axres, bxres, publicKey.axConj, Pmod, params.N);\n\tRing2Utils::multAndEqual(bxres, publicKey.bxConj, Pmod, params.N);\n\n\tRing2Utils::rightShiftAndEqual(axres, params.logq, params.N);\n\tRing2Utils::rightShiftAndEqual(bxres, params.logq, params.N);\n\n\tRing2Utils::addAndEqual(bxres, bxconj, cipher.mod, params.N);\n\treturn Cipher(axres, bxres, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::conjugateAndEqual(Cipher& cipher) {\n\tZZ Pmod = cipher.mod << params.logq;\n\n\tZZX bxconj, bxres, axres;\n\n\tRing2Utils::conjugate(bxconj, cipher.bx, params.N);\n\tRing2Utils::conjugate(bxres, cipher.ax, params.N);\n\n\tRing2Utils::mult(axres, bxres, publicKey.axConj, Pmod, params.N);\n\tRing2Utils::multAndEqual(bxres, publicKey.bxConj, Pmod, params.N);\n\n\tRing2Utils::rightShiftAndEqual(axres, params.logq, params.N);\n\tRing2Utils::rightShiftAndEqual(bxres, params.logq, params.N);\n\n\tRing2Utils::addAndEqual(bxres, bxconj, cipher.mod, params.N);\n\n\tcipher.ax = axres;\n\tcipher.bx = bxres;\n}\n\nCipher Scheme::imult(Cipher& cipher, const long precisionBits) {\n\tZZ tmp = EvaluatorUtils::evaluateVal(sqrt(to_RR(2.0)), precisionBits - 1);\n\n\tZZX bxres, axres, axtmp, bxtmp;\n\n\tRing2Utils::multByMonomial(axtmp, cipher.ax, params.N / 4, params.N);\n\tRing2Utils::multByConstAndEqual(axtmp, tmp, cipher.mod, params.N);\n\n\tRing2Utils::multByMonomial(bxtmp, cipher.bx, params.N / 4, params.N);\n\tRing2Utils::multByConstAndEqual(bxtmp, tmp, cipher.mod, params.N);\n\n\tRing2Utils::multByMonomial(axres, cipher.ax, 3 * params.N / 4, params.N);\n\tRing2Utils::multByConstAndEqual(axres, tmp, cipher.mod, params.N);\n\n\tRing2Utils::multByMonomial(bxres, cipher.bx, 3 * params.N / 4, params.N);\n\tRing2Utils::multByConstAndEqual(bxres, tmp, cipher.mod, params.N);\n\n\tRing2Utils::addAndEqual(axres, axtmp, cipher.mod, params.N);\n\tRing2Utils::addAndEqual(bxres, bxtmp, cipher.mod, params.N);\n\n\tCipher res(axres, bxres, cipher.mod, cipher.cbits, cipher.slots);\n\tmodSwitchAndEqual(res, precisionBits);\n\treturn res;\n}\n\nvoid Scheme::imultAndEqual(Cipher& cipher, const long precisionBits) {\n\n\tZZ tmp = EvaluatorUtils::evaluateVal(sqrt(to_RR(2.0)), precisionBits - 1);\n\n\tZZX axtmp, bxtmp;\n\n\tRing2Utils::multByMonomial(axtmp, cipher.ax, params.N / 4, params.N);\n\tRing2Utils::multByConstAndEqual(axtmp, tmp, cipher.mod, params.N);\n\n\tRing2Utils::multByMonomial(bxtmp, cipher.bx, params.N / 4, params.N);\n\tRing2Utils::multByConstAndEqual(bxtmp, tmp, cipher.mod, params.N);\n\n\tRing2Utils::multByMonomialAndEqual(cipher.ax, 3 * params.N / 4, params.N);\n\tRing2Utils::multByConstAndEqual(cipher.ax, tmp, cipher.mod, params.N);\n\n\tRing2Utils::multByMonomialAndEqual(cipher.bx, 3 * params.N / 4, params.N);\n\tRing2Utils::multByConstAndEqual(cipher.bx, tmp, cipher.mod, params.N);\n\n\tRing2Utils::addAndEqual(cipher.ax, axtmp, cipher.mod, params.N);\n\tRing2Utils::addAndEqual(cipher.bx, bxtmp, cipher.mod, params.N);\n\n\tmodSwitchAndEqual(cipher, precisionBits);\n}\n\nCipher Scheme::mult(Cipher& cipher1, Cipher& cipher2) {\n\tZZ Pmod = cipher1.mod << params.logq;\n\n\tZZX axbx1 = Ring2Utils::add(cipher1.ax, cipher1.bx, cipher1.mod, params.N);\n\tZZX axbx2 = Ring2Utils::add(cipher2.ax, cipher2.bx, cipher1.mod, params.N);\n\tRing2Utils::multAndEqual(axbx1, axbx2, cipher1.mod, params.N);\n\n\tZZX bxbx = Ring2Utils::mult(cipher1.bx, cipher2.bx, cipher1.mod, params.N);\n\tZZX axax = Ring2Utils::mult(cipher1.ax, cipher2.ax, cipher1.mod, params.N);\n\n\tZZX axmult = Ring2Utils::mult(axax, publicKey.axStar, Pmod, params.N);\n\tZZX bxmult = Ring2Utils::mult(axax, publicKey.bxStar, Pmod, params.N);\n\n\tRing2Utils::rightShiftAndEqual(axmult, params.logq, params.N);\n\tRing2Utils::rightShiftAndEqual(bxmult, params.logq, params.N);\n\n\tRing2Utils::addAndEqual(axmult, axbx1, cipher1.mod, params.N);\n\tRing2Utils::subAndEqual(axmult, bxbx, cipher1.mod, params.N);\n\tRing2Utils::subAndEqual(axmult, axax, cipher1.mod, params.N);\n\tRing2Utils::addAndEqual(bxmult, bxbx, cipher1.mod, params.N);\n\n\treturn Cipher(axmult, bxmult, cipher1.mod, cipher1.cbits, cipher1.slots);\n}\n\nvoid Scheme::multAndEqual(Cipher& cipher1, Cipher& cipher2) {\n\tZZ Pmod = cipher1.mod << params.logq;\n\n\tZZX axbx1 = Ring2Utils::add(cipher1.ax, cipher1.bx, cipher1.mod, params.N);\n\tZZX axbx2 = Ring2Utils::add(cipher2.ax, cipher2.bx, cipher1.mod, params.N);\n\tRing2Utils::multAndEqual(axbx1, axbx2, cipher1.mod, params.N);\n\n\tZZX bxbx = Ring2Utils::mult(cipher1.bx, cipher2.bx, cipher1.mod, params.N);\n\tZZX axax = Ring2Utils::mult(cipher1.ax, cipher2.ax, cipher1.mod, params.N);\n\n\tcipher1.ax = Ring2Utils::mult(axax, publicKey.axStar, Pmod, params.N);\n\tcipher1.bx = Ring2Utils::mult(axax, publicKey.bxStar, Pmod, params.N);\n\n\tRing2Utils::rightShiftAndEqual(cipher1.ax, params.logq, params.N);\n\tRing2Utils::rightShiftAndEqual(cipher1.bx, params.logq, params.N);\n\n\tRing2Utils::addAndEqual(cipher1.ax, axbx1, cipher1.mod, params.N);\n\tRing2Utils::subAndEqual(cipher1.ax, bxbx, cipher1.mod, params.N);\n\tRing2Utils::subAndEqual(cipher1.ax, axax, cipher1.mod, params.N);\n\tRing2Utils::addAndEqual(cipher1.bx, bxbx, cipher1.mod, params.N);\n}\n\n//-----------------------------------------\n\nCipher Scheme::square(Cipher& cipher) {\n\tZZ Pmod = cipher.mod << params.logq;\n\n\tZZX axax, axbx, bxbx, bxmult, axmult;\n\n\tRing2Utils::square(bxbx, cipher.bx, cipher.mod, params.N);\n\tRing2Utils::mult(axbx, cipher.ax, cipher.bx, cipher.mod, params.N);\n\tRing2Utils::addAndEqual(axbx, axbx, cipher.mod, params.N);\n\tRing2Utils::square(axax, cipher.ax, cipher.mod, params.N);\n\n\tRing2Utils::mult(axmult, axax, publicKey.axStar, Pmod, params.N);\n\tRing2Utils::mult(bxmult, axax, publicKey.bxStar, Pmod, params.N);\n\n\tRing2Utils::rightShiftAndEqual(axmult, params.logq, params.N);\n\tRing2Utils::rightShiftAndEqual(bxmult, params.logq, params.N);\n\n\tRing2Utils::addAndEqual(axmult, axbx, cipher.mod, params.N);\n\tRing2Utils::addAndEqual(bxmult, bxbx, cipher.mod, params.N);\n\n\treturn Cipher(axmult, bxmult, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::squareAndEqual(Cipher& cipher) {\n\tZZ Pmod = cipher.mod << params.logq;\n\n\tZZX bxbx, axbx, axax, bxmult, axmult;\n\n\tRing2Utils::square(bxbx, cipher.bx, cipher.mod, params.N);\n\tRing2Utils::mult(axbx, cipher.bx, cipher.ax, cipher.mod, params.N);\n\tRing2Utils::addAndEqual(axbx, axbx, cipher.mod, params.N);\n\tRing2Utils::square(axax, cipher.ax, cipher.mod, params.N);\n\n\tRing2Utils::mult(axmult, axax, publicKey.axStar, Pmod, params.N);\n\tRing2Utils::mult(bxmult, axax, publicKey.bxStar, Pmod, params.N);\n\n\tRing2Utils::rightShiftAndEqual(axmult, params.logq, params.N);\n\tRing2Utils::rightShiftAndEqual(bxmult, params.logq, params.N);\n\n\tRing2Utils::addAndEqual(axmult, axbx, cipher.mod, params.N);\n\tRing2Utils::addAndEqual(bxmult, bxbx, cipher.mod, params.N);\n\n\tcipher.bx = bxmult;\n\tcipher.ax = axmult;\n}\n\n//-----------------------------------------\n\nCipher Scheme::multByConst(Cipher& cipher, ZZ& cnst) {\n\tZZX ax, bx;\n\tRing2Utils::multByConst(ax, cipher.ax, cnst, cipher.mod, params.N);\n\tRing2Utils::multByConst(bx, cipher.bx, cnst, cipher.mod, params.N);\n\n\treturn Cipher(ax, bx, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::multByConstAndEqual(Cipher& cipher, ZZ& cnst) {\n\tRing2Utils::multByConstAndEqual(cipher.ax, cnst, cipher.mod, params.N);\n\tRing2Utils::multByConstAndEqual(cipher.bx, cnst, cipher.mod, params.N);\n}\n\nCipher Scheme::multByPoly(Cipher& cipher, ZZX& poly) {\n\tZZX axres, bxres;\n\tRing2Utils::mult(axres, cipher.ax, poly, cipher.mod, params.N);\n\tRing2Utils::mult(bxres, cipher.bx, poly, cipher.mod, params.N);\n\treturn Cipher(axres, bxres, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::multByPolyAndEqual(Cipher& cipher, ZZX& poly) {\n\tRing2Utils::multAndEqual(cipher.ax, poly, cipher.mod, params.N);\n\tRing2Utils::multAndEqual(cipher.bx, poly, cipher.mod, params.N);\n}\n\nCipher Scheme::multByConstBySlots(Cipher& cipher, CZZ*& cnstvec) {\n\tCZZ* gcnstvec = groupidx(cnstvec, cipher.slots);\n\tMessage msg = encode(gcnstvec, cipher.slots);\n\tdelete[] gcnstvec;\n\n\tZZX axres, bxres;\n\tRing2Utils::mult(axres, cipher.ax, msg.mx, cipher.mod, params.N);\n\tRing2Utils::mult(bxres, cipher.bx, msg.mx, cipher.mod, params.N);\n\treturn Cipher(axres, bxres, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::multByConstBySlotsAndEqual(Cipher& cipher, CZZ*& cnstvec) {\n\tCZZ* gcnstvec = groupidx(cnstvec, cipher.slots);\n\tMessage msg = encode(gcnstvec, cipher.slots);\n\tdelete[] gcnstvec;\n\n\tRing2Utils::multAndEqual(cipher.ax, msg.mx, cipher.mod, params.N);\n\tRing2Utils::multAndEqual(cipher.bx, msg.mx, cipher.mod, params.N);\n}\n\n\nCipher Scheme::multByPoly(Cipher& cipher, Message& msg) {\n    ZZX axres, bxres;\n    Ring2Utils::mult(axres, cipher.ax, msg.mx, cipher.mod, params.N);\n    Ring2Utils::mult(bxres, cipher.bx, msg.mx, cipher.mod, params.N);\n    return Cipher(axres, bxres, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::multByPolyAndEqual(Cipher& cipher, Message& msg) {\n    Ring2Utils::multAndEqual(cipher.ax, msg.mx, cipher.mod, params.N);\n    Ring2Utils::multAndEqual(cipher.bx, msg.mx, cipher.mod, params.N);\n}\n\n\n\n//-----------------------------------------\n\nCipher Scheme::multByMonomial(Cipher& cipher, const long degree) {\n\tZZX ax, bx;\n\n\tRing2Utils::multByMonomial(ax, cipher.ax, degree, params.N);\n\tRing2Utils::multByMonomial(bx, cipher.bx, degree, params.N);\n\n\treturn Cipher(ax, bx, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::multByMonomialAndEqual(Cipher& cipher, const long degree) {\n\tRing2Utils::multByMonomialAndEqual(cipher.ax, degree, params.N);\n\tRing2Utils::multByMonomialAndEqual(cipher.bx, degree, params.N);\n}\n\n//-----------------------------------------\n\nCipher Scheme::leftShift(Cipher& cipher, long bits) {\n\tZZX ax, bx;\n\n\tRing2Utils::leftShift(ax, cipher.ax, bits, cipher.mod, params.N);\n\tRing2Utils::leftShift(bx, cipher.bx, bits, cipher.mod, params.N);\n\n\treturn Cipher(ax, bx, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::leftShiftAndEqual(Cipher& cipher, long bits) {\n\tRing2Utils::leftShiftAndEqual(cipher.ax, bits, cipher.mod, params.N);\n\tRing2Utils::leftShiftAndEqual(cipher.bx, bits, cipher.mod, params.N);\n}\n\nvoid Scheme::doubleAndEqual(Cipher& cipher) {\n\tRing2Utils::doubleAndEqual(cipher.ax, cipher.mod, params.N);\n\tRing2Utils::doubleAndEqual(cipher.bx, cipher.mod, params.N);\n}\n\n//-----------------------------------------\n\nCipher Scheme::modSwitch(Cipher& cipher, long bitsDown) {\n\tZZX ax, bx;\n\n\tRing2Utils::rightShift(ax, cipher.ax, bitsDown, params.N);\n\tRing2Utils::rightShift(bx, cipher.bx, bitsDown, params.N);\n\n\tlong newcbits = cipher.cbits - bitsDown;\n\tZZ newmod = cipher.mod >> bitsDown;\n\treturn Cipher(ax, bx, newmod, newcbits, cipher.slots);\n}\n\nvoid Scheme::modSwitchAndEqual(Cipher& cipher, long bitsDown) {\n\tRing2Utils::rightShiftAndEqual(cipher.ax, bitsDown, params.N);\n\tRing2Utils::rightShiftAndEqual(cipher.bx, bitsDown, params.N);\n\tcipher.cbits -= bitsDown;\n\tcipher.mod >>= bitsDown;\n}\n\nCipher Scheme::modEmbed(Cipher& cipher, long bitsDown) {\n\tZZ newmod = cipher.mod >> bitsDown;\n\tlong newcbits = cipher.cbits - bitsDown;\n\tZZX bx, ax;\n\tRing2Utils::mod(ax, cipher.ax, newmod, params.N);\n\tRing2Utils::mod(bx, cipher.bx, newmod, params.N);\n\treturn Cipher(ax, bx, newmod, newcbits, cipher.slots);\n}\n\nvoid Scheme::modEmbedAndEqual(Cipher& cipher, long bitsDown) {\n\tcipher.mod >>= bitsDown;\n\tcipher.cbits -= bitsDown;\n\tRing2Utils::modAndEqual(cipher.ax, cipher.mod, params.N);\n\tRing2Utils::modAndEqual(cipher.bx, cipher.mod, params.N);\n}\n\n//-----------------------------------------\n\nCipher Scheme::leftRotateByPo2(Cipher& cipher, long logrotSlots) {\n\tZZ Pmod = cipher.mod << params.logq;\n\n\tZZX bxrot, bxres, axres;\n\n\tlong rotSlots = (1 << logrotSlots);\n\n\tRing2Utils::inpower(bxrot, cipher.bx, params.rotGroup[rotSlots], params.q, params.N);\n\tRing2Utils::inpower(bxres, cipher.ax, params.rotGroup[rotSlots], params.q, params.N);\n\n\tRing2Utils::mult(axres, bxres, publicKey.axLeftRot[logrotSlots], Pmod, params.N);\n\tRing2Utils::multAndEqual(bxres, publicKey.bxLeftRot[logrotSlots], Pmod, params.N);\n\n\tRing2Utils::rightShiftAndEqual(axres, params.logq, params.N);\n\tRing2Utils::rightShiftAndEqual(bxres, params.logq, params.N);\n\n\tRing2Utils::addAndEqual(bxres, bxrot, cipher.mod, params.N);\n\treturn Cipher(axres, bxres, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::leftRotateByPo2AndEqual(Cipher& cipher, long logrotSlots) {\n\tZZ Pmod = cipher.mod << params.logq;\n\n\tZZX bxrot, bxres, axres;\n\n\tlong rotSlots = (1 << logrotSlots);\n\n\tRing2Utils::inpower(bxrot, cipher.bx, params.rotGroup[rotSlots], params.q, params.N);\n\tRing2Utils::inpower(bxres, cipher.ax, params.rotGroup[rotSlots], params.q, params.N);\n\n\tRing2Utils::mult(axres, bxres, publicKey.axLeftRot[logrotSlots], Pmod, params.N);\n\tRing2Utils::multAndEqual(bxres, publicKey.bxLeftRot[logrotSlots], Pmod, params.N);\n\n\tRing2Utils::rightShiftAndEqual(axres, params.logq, params.N);\n\tRing2Utils::rightShiftAndEqual(bxres, params.logq, params.N);\n\n\tRing2Utils::addAndEqual(bxres, bxrot, cipher.mod, params.N);\n\n\tcipher.ax = axres;\n\tcipher.bx = bxres;\n}\n\nCipher Scheme::rightRotateByPo2(Cipher& cipher, long logrotSlots) {\n\tZZ Pmod = cipher.mod << params.logq;\n\n\tZZX bxrot, bxres, axres;\n\n\tlong rotSlots = params.N/2 - (1 << logrotSlots);\n\n\tRing2Utils::inpower(bxrot, cipher.bx, params.rotGroup[rotSlots], params.q, params.N);\n\tRing2Utils::inpower(bxres, cipher.ax, params.rotGroup[rotSlots], params.q, params.N);\n\n\tRing2Utils::mult(axres, bxres, publicKey.axRightRot[logrotSlots], Pmod, params.N);\n\tRing2Utils::multAndEqual(bxres, publicKey.bxRightRot[logrotSlots], Pmod, params.N);\n\n\tRing2Utils::rightShiftAndEqual(axres, params.logq, params.N);\n\tRing2Utils::rightShiftAndEqual(bxres, params.logq, params.N);\n\n\tRing2Utils::addAndEqual(bxres, bxrot, cipher.mod, params.N);\n\treturn Cipher(axres, bxres, cipher.mod, cipher.cbits, cipher.slots);\n}\n\nvoid Scheme::rightRotateByPo2AndEqual(Cipher& cipher, long logrotSlots) {\n\tZZ Pmod = cipher.mod << params.logq;\n\n\tZZX bxrot, bxres, axres;\n\n\tlong rotSlots = params.N/2 - (1 << logrotSlots);\n\n\tRing2Utils::inpower(bxrot, cipher.bx, params.rotGroup[rotSlots], params.q, params.N);\n\tRing2Utils::inpower(bxres, cipher.ax, params.rotGroup[rotSlots], params.q, params.N);\n\n\tRing2Utils::mult(axres, bxres, publicKey.axRightRot[logrotSlots], Pmod, params.N);\n\tRing2Utils::multAndEqual(bxres, publicKey.bxRightRot[logrotSlots], Pmod, params.N);\n\n\tRing2Utils::rightShiftAndEqual(axres, params.logq, params.N);\n\tRing2Utils::rightShiftAndEqual(bxres, params.logq, params.N);\n\n\tRing2Utils::addAndEqual(bxres, bxrot, cipher.mod, params.N);\n\n\tcipher.ax = axres;\n\tcipher.bx = bxres;\n}\n\nCipher Scheme::leftRotate(Cipher& cipher, long rotSlots) {\n\tCipher res = cipher;\n\tleftRotateAndEqual(res, rotSlots);\n\treturn res;\n}\n\nvoid Scheme::leftRotateAndEqual(Cipher& cipher, long rotSlots) {\n\tlong remrotSlots = rotSlots % cipher.slots;\n\tlong logrotSlots = log2(remrotSlots) + 1;\n\tfor (long i = 0; i < logrotSlots; ++i) {\n\t\tif(bit(remrotSlots, i)) {\n\t\t\tleftRotateByPo2AndEqual(cipher, i);\n\t\t}\n\t}\n}\n\nCipher Scheme::rightRotate(Cipher& cipher, long rotSlots) {\n\tCipher res = cipher;\n\trightRotateAndEqual(res, rotSlots);\n\treturn res;\n}\n\nvoid Scheme::rightRotateAndEqual(Cipher& cipher, long rotSlots) {\n\tlong remrotSlots = rotSlots % cipher.slots;\n\tlong logrotSlots = log2(remrotSlots) + 1;\n\tfor (long i = 0; i < logrotSlots; ++i) {\n\t\tif(bit(remrotSlots, i)) {\n\t\t\trightRotateByPo2AndEqual(cipher, i);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "37d9dc09e08042821a62b69e758d2ccc40a1ee6e", "size": 24079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Scheme.cpp", "max_stars_repo_name": "K-miran/HELR", "max_stars_repo_head_hexsha": "c94951f2691d55defc82f95d3144c831eb6c8796", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2018-01-20T13:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:56:15.000Z", "max_issues_repo_path": "src/Scheme.cpp", "max_issues_repo_name": "yuejiayang/HELR", "max_issues_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-01-25T02:54:53.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-09T10:48:39.000Z", "max_forks_repo_path": "src/Scheme.cpp", "max_forks_repo_name": "yuejiayang/HELR", "max_forks_repo_head_hexsha": "5bc8ee66430e1e9a4f933a700260008ce35cb118", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-01-20T13:31:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-28T02:20:39.000Z", "avg_line_length": 32.3208053691, "max_line_length": 86, "alphanum_fraction": 0.6968312638, "num_tokens": 7535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.40109368605174}}
{"text": "#include <iostream>\n#include <thread>\n#include <fstream>\n#include <string>\n#include <filesystem>\n#include <tuple>\n#include <algorithm>\n#include <chrono>\n#include <regex>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nusing namespace std;\n\nnamespace mp = boost::multiprecision;\nnamespace fs = std::filesystem;\n\nconst auto iter = 1 + 28;\nconst string resultsDirectory = \"results\";\n\n\nvoid saveResult(const mp::cpp_int &power, int num) {\n    vector<unsigned char> buffer;\n    export_bits(power, back_inserter(buffer), 8);\n\n    fstream file(resultsDirectory + \"/\" + to_string(num) + \".txt\", fstream::out | fstream::trunc);\n    for (unsigned char val: buffer) {\n        file.put(val);\n    }\n    file.close();\n}\n\nvoid saveResult(const mp::cpp_int &power, const string &filename) {\n    vector<unsigned char> buffer;\n    export_bits(power, back_inserter(buffer), 8);\n\n    fstream file(resultsDirectory + \"/\" + filename + \".txt\", fstream::out | fstream::trunc);\n    for (unsigned char val: buffer) {\n        file.put(val);\n    }\n    file.close();\n}\n\ntuple <mp::cpp_int*, int> loadResults() {\n    auto *powers = new mp::cpp_int[iter];\n    mp::cpp_int partial;\n    vector<int> loadedPowers;\n    auto numberToLarge = false;\n\n    for (const auto &entry : fs::directory_iterator(resultsDirectory)) {\n        auto filename = fs::path(entry).stem(); // Get filename without path and extension\n        int power = atoi(filename.c_str()); // Convert string into integer\n\n        if (power == 0) {\n            continue;\n        }\n\n        if (power < iter) {\n            cout << \"Loading \" + entry.path().filename().string() << endl;\n\n            vector<unsigned char> buffer;\n            fstream file(entry.path(), fstream::in);\n\n            while (!file.eof()) {\n                char val;\n                file.get(val);\n                if (file.eof()) break;\n                buffer.push_back(val);\n            }\n            file.close();\n\n            import_bits(powers[power], buffer.begin(), buffer.end());\n\n            if (powers[power] == 0) {\n                continue;\n            }\n            loadedPowers.push_back(power); // Add read power to loadedPowers\n        } else {\n            numberToLarge = true;\n        }\n    }\n\n    cout << \"Finished Loading\" << endl;\n    if (numberToLarge) {\n        cout << \"Found file with power larger than set possible!\" << endl << endl;\n    }\n\n    int largestPower = 0;\n    sort(loadedPowers.begin(), loadedPowers.end());\n\n    // Find largest power without \"gaps\" in files, so\n    // 0, 1, 2, 3, 5, 6 will return 3\n    // We will need all powers in stage two\n    for (auto power: loadedPowers) {\n        if (power == largestPower + 1){\n            largestPower++;\n        }\n    }\n\n    powers[0] = 9;\n    largestPower = max(++largestPower, 1); // Set largestPower to bigger value: 1 or largestPower + 1\n\n    return {powers, largestPower};\n}\n\nstring prepareTime(chrono::steady_clock::time_point start, chrono::steady_clock::time_point end) {\n    auto microseconds = chrono::duration_cast<chrono::microseconds>(end - start).count();\n    auto milliseconds = chrono::duration_cast<chrono::milliseconds>(end - start).count();\n    auto seconds = chrono::duration_cast<chrono::seconds>(end - start).count();\n    auto hours = chrono::duration_cast<chrono::hours>(end - start).count();\n\n    string time;\n\n    if (hours > 0) {\n        time += to_string(hours) + \"h \";\n    }\n    if (seconds > 0) {\n        time += to_string(seconds % 60) + \"s \";\n    }\n    if (milliseconds > 0) {\n        time += to_string(milliseconds % 1000) + \"ms \";\n    }\n    if (microseconds > 0) {\n        time += to_string(microseconds % 1000) + \"μm\";\n    }\n\n    if (time.empty()) {\n        return \"no time\";\n    } else {\n        return time;\n    }\n}\n\nint main() {\n    auto [powers, currentPower] = loadResults();\n    thread threads[iter];\n\n    for (; currentPower < iter; ++currentPower) {\n        auto startTime = chrono::steady_clock::now();\n\n        powers[currentPower] = pow(powers[currentPower - 1], 2);\n\n        auto endTime = chrono::steady_clock::now();\n        cout << \"Calculated 9^\" << mp::pow(mp::cpp_int(2), currentPower) << \", in \" << prepareTime(startTime, endTime) << \", step \" << currentPower << endl; // For logging progress\n\n        // thread() can't find rsquare prismight function by its own (there are two),\n        // so I point it to right address manually\n        auto functionAddress = static_cast<void(*)(const mp::cpp_int&, int)>(saveResult);\n        threads[currentPower] = thread(functionAddress, powers[currentPower], currentPower);\n    }\n\n    // Stage two: multiply following elements from array:\n    // int toMultiply[] =  {28, 26, 25, 24, 20, 18, 17, 16, 15, 12, 8, 6, 3, 0};\n    int toMultiply[] = {3, 6, 8, 12, 15, 16, 17, 18, 20, 24, 25, 26, 28};\n    // Based on:\n    // https://www.wolframalpha.com/input/?i=9%5E9+%3D+2%5E28+%2B+2%5E26+%2B+2%5E25+%2B+2%5E24+%2B+2%5E20+%2B+2%5E18+%2B+2%5E17+%2B+2%5E16+%2B+2%5E15+%2B+2%5E12+%2B+2%5E8+%2B+2%5E6+%2B+2%5E3+%2B+2%5E0\n\n    mp::cpp_int final = powers[0];\n    int previous = 0;\n    for (int i = 0; i < 13; i++) {\n        cout << \"Calculating: \" << toMultiply[i] << endl;\n        final *= powers[toMultiply[i]];\n\n        cout << \"Saving...\" << endl;\n        saveResult(final, \"partial.\" + to_string(toMultiply[i]));\n        remove((\"partial.\" + to_string(previous)).c_str());\n    }\n\n    for (auto &th: threads) {\n        if (th.joinable()) {\n            th.join();\n        }\n    }\n\n    fstream result(\"result.txt\", fstream::out);\n    result << final;\n    result.close();\n    return 0;\n}", "meta": {"hexsha": "be2b01667016db300ae7ff645ae7078b410223e3", "size": 5555, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "WaxyMocha/NineToNineToNine", "max_stars_repo_head_hexsha": "051269951a53755290a94531f63994d8a81164d2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-16T20:31:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-16T20:31:16.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "WaxyMocha/NineToNineToNine", "max_issues_repo_head_hexsha": "051269951a53755290a94531f63994d8a81164d2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "WaxyMocha/NineToNineToNine", "max_forks_repo_head_hexsha": "051269951a53755290a94531f63994d8a81164d2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0335195531, "max_line_length": 200, "alphanum_fraction": 0.5873987399, "num_tokens": 1531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.40101791712441026}}
{"text": "#ifndef DIIS_HH\n#define DIIS_HH\n\n/*!\n * \\file DIIS.hh\n * \\brief Definition of the DIIS class\n */\n\n#include <Eigen/Core>\n\n/*!\n * \\brief The DIIS convergence optimizer\n *\n * Class DIIS implements the Direct Inversion in the Iterative Subspace\n * extrapolation technique to speed up the convergence in an SCF calculation.\n * It tries to make a better guess for the Fock matrix in the next iteration\n * by creating a linear combination of Fock matrices from previous iterations,\n * where the error term \\f$FDS-SDF\\f$ (with \\f$F\\f$ the Fock matrix, \\f$D\\f$\n * the density matrix, and \\f$S\\f$ the overlap matrix) is minimized.\n */\nclass DIIS\n{\npublic:\n\t/*!\n\t * \\brief Constructor\n\t *\n\t * Create a new DIIS object, for a basis of size \\a size.\n\t * \\param size The size of the matrices (basis set size).\n\t */\n\tDIIS(): _size(0), _err_vecs_used(0), _err_vecs(), _values(),\n\t\t_started(false), _max_err(0) {}\n\n\t/*!\n\t * \\brief Create a new Fock matrix\n\t *\n\t * Create the new Fock matrix from the current guess for the matrix and\n\t * the current density matrix. If the DIIS algorithm has not been\n\t * started yet (because the error term is still too large with respect\n\t * to the computed energy), it simply returns \\a F. Otherwise a linear\n\t * combination of previous Fock matrices \\f$\\tilde{F}\\f$ that minimizes\n\t * the error term \\f$\\tilde{F}DS-SD\\tilde{F}\\f$ is computed, and stored\n\t * in \\a F.\n\t * \\param F    The current Fock matrix\n\t * \\param P    The density matrix from which \\a F was computed\n\t * \\param S    The overlap matrix for the basis\n\t * \\param X    The orthogonalization matrix \\f$X = S^{-1/2}\\f$ for the basis\n\t * \\param Etot The total energy\n\t */\n\tvoid step(Eigen::MatrixXd& F, const Eigen::MatrixXd& D,\n\t\tconst Eigen::MatrixXd& S, const Eigen::MatrixXd& X, double Etot);\n\tvoid step(Eigen::MatrixXd& Fa, const Eigen::MatrixXd& Da,\n\t\tEigen::MatrixXd& Fb, const Eigen::MatrixXd& Db,\n\t\tconst Eigen::MatrixXd& S, const Eigen::MatrixXd& X, double Etot);\n\n\t//! Return the maximum error on the last iteration\n\tdouble error() const { return _max_err; }\n\nprivate:\n\t//! The basis set size\n\tint _size;\n\t//! The number of error vectors currently stored\n\tint _err_vecs_used;\n\t//! The error vectors themselves, one per column\n\tEigen::MatrixXd _err_vecs;\n\t//! The previous Fock matrices\n\tstd::vector<Eigen::MatrixXd> _values;\n\t//! Whether DIIS was started\n\tbool _started;\n\t//! Maximum error in the last DIIS step\n\tdouble _max_err;\n};\n\n#endif // DIIS_HH", "meta": {"hexsha": "1d28114e9828306a35d8063c3439db749bd2fbd2", "size": 2445, "ext": "hh", "lang": "C++", "max_stars_repo_path": "DIIS.hh", "max_stars_repo_name": "gvissers/quill2", "max_stars_repo_head_hexsha": "589d7bc3ce20da888547f8f4f6b8da908b3d63a5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DIIS.hh", "max_issues_repo_name": "gvissers/quill2", "max_issues_repo_head_hexsha": "589d7bc3ce20da888547f8f4f6b8da908b3d63a5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DIIS.hh", "max_forks_repo_name": "gvissers/quill2", "max_forks_repo_head_hexsha": "589d7bc3ce20da888547f8f4f6b8da908b3d63a5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4931506849, "max_line_length": 78, "alphanum_fraction": 0.7030674847, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7549149758396752, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.40101791126625813}}
{"text": "//=========================================================================\n//\n// Copyright 2019 Kitware, Inc.\n// Author: Guilbert Pierre (spguilbert@gmail.com)\n// Data: 03-27-2019\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//=========================================================================\n\n// LOCAL\n#include \"CameraCalibration.h\"\n#include \"CameraProjection.h\"\n#include \"vtkEigenTools.h\"\n#include \"CeresCameraCalibrationCostFunctions.h\"\n\n// STD\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n// BOOST\n#include <boost/algorithm/string.hpp>\n\n// CERES\n#include <ceres/ceres.h>\n\n//----------------------------------------------------------------------------\nvoid LoadMatchesFromCSV(std::string filename, std::vector<Eigen::Vector3d>& X, std::vector<Eigen::Vector2d>& x)\n{\n  // Load file and check that the file is opened\n  std::ifstream file(filename.c_str());\n  if (!file.is_open())\n  {\n    std::cout << \"Error: could not load file: \" << filename << std::endl;\n    return;\n  }\n\n  // check the file header\n  std::string tokenFileHeader(\"X,Y,Z,u,v\");\n  std::string line;\n  std::getline(file, line);\n  if (line != tokenFileHeader)\n  {\n    std::cout << \"Error file header is: \" << line << \" expected: \" << tokenFileHeader << std::endl;\n    return;\n  }\n\n  // parse the file\n  while (std::getline(file, line))\n  {\n    std::vector<std::string> values;\n    boost::algorithm::split(values, line, boost::is_any_of(\",\"));\n\n    // check that each lines has the right number of value\n    if (values.size() < 5)\n    {\n      std::cout << \"Error, number of values is: \" << values.size() << \" expected 5\" << std::endl;\n      continue;\n    }\n\n    Eigen::Vector3d Xc(std::atof(values[0].c_str()), std::atof(values[1].c_str()), std::atof(values[2].c_str()));\n    Eigen::Vector2d xc(std::atof(values[3].c_str()), std::atof(values[4].c_str()));\n    X.push_back(Xc);\n    x.push_back(xc);\n  }\n  return;\n}\n\n//----------------------------------------------------------------------------\ndouble LinearPinholeCalibration(const std::vector<Eigen::Vector3d>& X, const std::vector<Eigen::Vector2d>& x, Eigen::Matrix<double, 3, 4>& P)\n{\n  P = Eigen::Matrix<double, 3, 4>::Zero();\n  if (X.size() != x.size())\n  {\n    std::cout << \"Error: matches have different sizes\" << std::endl;\n    return -1.0;\n  }\n\n  // We will estimate the coefficients of the projection matrix\n  // by minimizing the reprojection euclidean distance between\n  // the image keypoints and the 3D associated keypoints reprojected\n\n  // Compute the normal equations\n  Eigen::MatrixXd A(2 * X.size(), 12);\n  for (int k = 0; k < X.size(); ++k)\n  {\n    A.row(2 * k) << X[k](0), X[k](1), X[k](2), 1,\n                    0, 0, 0, 0,\n                    -x[k](0) * X[k](0), -x[k](0) * X[k](1), -x[k](0) * X[k](2), -x[k](0);\n\n    A.row(2 * k + 1) << 0, 0, 0, 0,\n                        X[k](0), X[k](1), X[k](2), 1,\n                       -x[k](1) * X[k](0), -x[k](1) * X[k](1), -x[k](1) * X[k](2), -x[k](1);\n  }\n\n  // Solve the normal equations\n  Eigen::JacobiSVD<Eigen::MatrixXd> svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  Eigen::MatrixXd flattenP = svd.matrixV().col(11);\n  P << flattenP(0), flattenP(1), flattenP(2), flattenP(3),\n       flattenP(4), flattenP(5), flattenP(6), flattenP(7),\n       flattenP(8), flattenP(9), flattenP(10), flattenP(11);\n  P = P / P(2, 3);\n\n  // Compute the RMSE\n  double meanErr = 0;\n  for (int k = 0; k < X.size(); ++k)\n  {\n    Eigen::Vector4d homoX(X[k](0), X[k](1), X[k](2), 1);\n    Eigen::Vector3d projX = P * homoX;\n    Eigen::Vector2d projXn(projX(0) / projX(2), projX(1) / projX(2));\n    //std::cout << \"X: \" << X[k].transpose() << \" x: \" << x[k].transpose() << \" prjX: \" << projXn.transpose() << \" dist: \" << (x[k] - projXn).norm() << std::endl;\n    meanErr += ((x[k] - projXn).transpose() * (x[k] - projXn))(0);\n  }\n  return std::sqrt(meanErr / (1.0 * X.size()));\n}\n\n//----------------------------------------------------------------------------\nvoid CalibrationMatrixDecomposition(const Eigen::Matrix<double, 3, 4>& P, Eigen::Matrix3d& K, Eigen::Matrix3d& R, Eigen::Vector3d& T)\n{\n  // M = K*R\n  Eigen::Matrix3d M = P.block(0, 0, 3, 3);\n\n  // M is the product of an upper triangulate matrix\n  // and an orthogonal matrix. We will use a RQ decomposition\n  // to recover K and R. Since eigen only provides QR\n  // decomposition we will inverse the column order of M to\n  // get its RQ decomposition from the QR decomposition\n  Eigen::Matrix3d D = Eigen::Matrix3d::Zero();\n  D(2, 0) = 1; D(1, 1) = 1; D(0, 2) = 1;\n  Eigen::Matrix3d Mtilde = D * M;\n  Eigen::HouseholderQR<Eigen::Matrix3d> QRdec(Mtilde.transpose());\n  Eigen::Matrix3d Qtilde = QRdec.householderQ();\n  Eigen::Matrix3d Rtilde = Qtilde.transpose() * (Mtilde.transpose());\n  K = D * Rtilde.transpose() * D;\n  R = D * Qtilde.transpose();\n  T = P.col(3);\n  T = - R.transpose() * K.inverse() * T;\n\n  // rescale the matrix\n  K = K / K(2, 2);\n  R = R * std::cbrt(1.0 / R.determinant());\n  R = R.transpose().eval();\n\n  Eigen::Matrix<double, 3, 4> H;\n  H.block(0, 0, 3, 3) = K * R.transpose();\n  H.col(3) = -K * R.transpose() * T;\n  H = H / H(2, 3);\n  if (((H - P).transpose() * (H - P)).trace() > 1e-6)\n  {\n    std::cout << \"Error: decomposition failed\" << std::endl;\n  }\n  return;\n}\n\n//----------------------------------------------------------------------------\nvoid GetParametersFromMatrix(const Eigen::Matrix3d& K, const Eigen::Matrix3d& R, const Eigen::Vector3d& T, Eigen::Matrix<double, 11, 1>& W)\n{\n  Eigen::Vector3d eulerAngles = MatrixToRollPitchYaw(R);\n  W(0) = eulerAngles(0); W(1) = eulerAngles(1); W(2) = eulerAngles(2);\n  W(3) = T(0), W(4) = T(1), W(5) = T(2);\n  W(6) = K(0, 0);\n  W(7) = K(1, 1);\n  W(8) = K(0, 2);\n  W(9) = K(1, 2);\n  W(10) = K(0, 1);\n  return;\n}\n\n//----------------------------------------------------------------------------\ndouble NonLinearPinholeCalibration(const std::vector<Eigen::Vector3d>& X, const std::vector<Eigen::Vector2d>& x, Eigen::Matrix<double, 11, 1>& W)\n{\n  Eigen::Matrix<double, 3, 4> P0, P1;\n  GetMatrixFromParameters(W, P0);\n\n  // We want to estimate our 11-DOF parameters using a non\n  // linear least square minimization. The non linear part\n  // comes from the Euler Angle parametrization of the rotation\n  // endomorphism of SO(3) and the homographie rescaling\n  // To minimize it, we use CERES to perform\n  // the Levenberg-Marquardt algorithm.\n  ceres::Problem problem;\n  for (unsigned int k = 0; k < X.size(); ++k)\n  {\n    ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<CostFunctions::PinholeModelAlgebraicDistance, 1, 11>(\n                                         new CostFunctions::PinholeModelAlgebraicDistance(X[k], x[k]));\n    problem.AddResidualBlock(cost_function, nullptr, W.data());\n  }\n\n  // Solve the problem\n  ceres::Solver::Options options;\n  options.max_num_iterations = 1000;\n  options.linear_solver_type = ceres::DENSE_QR;\n  options.minimizer_progress_to_stdout = false;\n\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n  std::cout << summary.BriefReport() << std::endl;\n\n  // Compute mean error\n  GetMatrixFromParameters(W, P1);\n  double meanErr = 0;\n  for (int k = 0; k < X.size(); ++k)\n  {\n    Eigen::Vector4d homoX(X[k](0), X[k](1), X[k](2), 1);\n    Eigen::Vector3d projX = P1 * homoX;\n    Eigen::Vector2d projXn(projX(0) / projX(2), projX(1) / projX(2));\n    meanErr += ((x[k] - projXn).transpose() * (x[k] - projXn))(0);\n  }\n return std::sqrt(meanErr / (1.0 * X.size()));\n}\n\n//----------------------------------------------------------------------------\ndouble NonLinearFisheyeCalibration(const std::vector<Eigen::Vector3d>& X, const std::vector<Eigen::Vector2d>& x,\n                                   Eigen::Matrix<double, 15, 1>& W, unsigned int it)\n{\n  // We want to estimate our 15-DOF parameters using a non\n  // linear least square minimization. The non linear part\n  // comes from the Euler Angle parametrization of the rotation\n  // endomorphism of SO(3) and the homographie rescaling\n  // To minimize it, we use CERES to perform\n  // the Levenberg-Marquardt algorithm.\n  ceres::Problem problem;\n  for (unsigned int k = 0; k < X.size(); ++k)\n  {\n    ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<CostFunctions::FisheyeModelAlgebraicDistance, 1, 15>(\n                                         new CostFunctions::FisheyeModelAlgebraicDistance(X[k], x[k]));\n    problem.AddResidualBlock(cost_function, nullptr, W.data());\n  }\n\n  ceres::Solver::Options options;\n  options.max_num_iterations = it;\n  options.linear_solver_type = ceres::DENSE_QR;\n  options.minimizer_progress_to_stdout = false;\n\n  ceres::Solver::Summary summary;\n  ceres::Solve(options, &problem, &summary);\n\n  double meanErr = 0;\n  for (int k = 0; k < X.size(); ++k)\n  {\n    meanErr += ((x[k] - FisheyeProjection(W, X[k])).transpose() * (x[k] - FisheyeProjection(W, X[k])))(0);\n  }\n  return std::sqrt(meanErr / (1.0 * X.size()));\n}\n\n//----------------------------------------------------------------------------\ndouble BrownConradyPinholeCalibration(const std::vector<Eigen::Vector3d>& X, const std::vector<Eigen::Vector2d>& x,\n                                      Eigen::Matrix<double, 17, 1>& W, unsigned int it,\n                                      double initLossScale, double finalLossScale,\n                                      const std::vector<bool>& shouldOptimizeParam)\n{\n  unsigned int N = 100;\n\n  // The minimization algorithm will be ran multiple time\n  // with an outlier rejection loss function more restrictive\n  // at each iteration. We don't want to have a higly restrictive\n  // outlier rejection at the beginning since the initial point can\n  // be far from the global minimum and it could create convergence\n  // issues.\n  for (unsigned int minId = 0; minId < N; ++minId)\n  {\n    double lossScale = initLossScale + static_cast<double>(minId) * (finalLossScale - initLossScale) / (1.0 * N);\n\n    // We want to estimate our 17-DOF parameters using a non\n    // linear least square minimization. The non linear part\n    // comes from the Euler Angle parametrization of the rotation\n    // endomorphism of SO(3), the homographie rescaling and\n    // the lens distortions\n    // To minimize it, we use CERES to perform\n    // the Levenberg-Marquardt algorithm.\n    ceres::Problem problem;\n    for (unsigned int k = 0; k < X.size(); ++k)\n    {\n      CostFunctions::BrownConradyAlgebraicDistance* resFct = new CostFunctions::BrownConradyAlgebraicDistance(X[k], x[k]);\n      resFct->SetW0(W);\n      resFct->SetActivatedParams(shouldOptimizeParam);\n      ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<CostFunctions::BrownConradyAlgebraicDistance, 1, 17>(resFct);\n      problem.AddResidualBlock(cost_function, new ceres::ArctanLoss(lossScale), W.data());\n    }\n\n    ceres::Solver::Options options;\n    options.max_num_iterations = it;\n    options.linear_solver_type = ceres::DENSE_QR;\n    options.minimizer_progress_to_stdout = false;\n\n    ceres::Solver::Summary summary;\n    ceres::Solve(options, &problem, &summary);\n    std::cout << summary.BriefReport() << std::endl;\n  }\n\n  double meanErr = 0;\n  for (int k = 0; k < X.size(); ++k)\n  {\n    meanErr += ((x[k] - BrownConradyPinholeProjection(W, X[k])).transpose() * (x[k] - BrownConradyPinholeProjection(W, X[k])))(0);\n  }\n  return std::sqrt(meanErr / (1.0 * X.size()));\n}\n\n//----------------------------------------------------------------------------\nvoid GetMatrixFromParameters(const Eigen::Matrix<double, 11, 1>& W, Eigen::Matrix<double, 3, 4>& P)\n{\n  // Create current rotation\n  Eigen::Matrix3d R = RollPitchYawToMatrix(W(0), W(1), W(2));\n  // Create current position\n  Eigen::Vector3d T(W(3), W(4), W(5));\n\n  // Create current intrinsic parameters\n  Eigen::Matrix3d K = Eigen::Matrix3d::Zero();\n  K(0, 0) = W(6);\n  K(1, 1) = W(7);\n  K(0, 2) = W(8);\n  K(1, 2) = W(9);\n  K(0, 1) = W(10);\n  K(2, 2) = 1;\n\n  // Create current calibration matrix\n  P.block(0, 0, 3, 3) = K * R.transpose();\n  P.col(3) = -K * R.transpose() * T;\n  P = P / P(2, 3);\n}\n\n//----------------------------------------------------------------------------\nEigen::Matrix<double, 3, 4> GetMatrixFromParameters(const Eigen::Matrix<double, 11, 1>& W)\n{\n  Eigen::Matrix<double, 3, 4> P;\n  GetMatrixFromParameters(W, P);\n  return P;\n}\n\n//----------------------------------------------------------------------------\nEigen::VectorXd FullCalibrationPipelineFromMatches(std::string filename, const std::vector<bool>& activatedParams)\n{\n  Eigen::VectorXd Wf = Eigen::VectorXd::Zero(17, 1);\n\n  // Load the 3D - 2D matches\n  std::vector<Eigen::Vector3d> X;\n  std::vector<Eigen::Vector2d> x;\n  LoadMatchesFromCSV(filename, X, x);\n  if (X.size() == 0)\n  {\n    return Wf;\n  }\n\n  // First, launch a linear pinhole camera model\n  // projection matrix estimation\n  Eigen::Matrix<double, 3, 4> P;\n  double rmse1 = LinearPinholeCalibration(X, x, P);\n\n  // From this first linear pinhole projection matrix\n  // estimation, extract the pinhole model parameters\n  Eigen::Matrix3d K, R;\n  Eigen::Vector3d T;\n  CalibrationMatrixDecomposition(P, K, R, T);\n\n  // Check that the optical axis of the camera is\n  // correctly oriented according to the 3D points\n  Eigen::Vector3d Xmean = Eigen::Vector3d::Zero();\n  for (int i = 0; i < X.size(); ++i)\n  {\n    Xmean += X[i] / static_cast<double>(X.size());\n  }\n  Eigen::Vector3d ez = R.col(2);\n  double angle = std::acos((Xmean.transpose() * ez)(0) / (Xmean.norm() * ez.norm())) / vtkMath::Pi() * 180.0;\n\n  // In this case, the linear algorithm has provided\n  // a solution where the camera is looking backward and\n  // the resulting symmetry is handled by the intrinsic matrix.\n  // To avoid that, we return the camera if it is not looking\n  // forward\n  if (angle > 90.0)\n  {\n    Eigen::Matrix3d S;\n    S << -1.0, 0.0,  0.0,\n          0.0, 1.0,  0.0,\n          0.0, 0.0, -1.0;\n\n    Eigen::Matrix3d Rtilde = R * S * R.transpose();\n\n    // So that K' * R' = K * R, meaning that\n    // the global projection is unchanged but\n    // the camera orientation has made a 180\n    // rotation around its y-axis\n    K = K * Rtilde.transpose();\n    K = K / K(2, 2);\n    R = Rtilde * R;\n  }\n\n  Eigen::Matrix<double, 11, 1> Wpinhole;\n  GetParametersFromMatrix(K, R, T, Wpinhole);\n  Eigen::Matrix<double, 11, 1> Wpi = Wpinhole;\n\n  // Then, refine the model obtained using linear\n  // estimation by using a non-linear pinhole parameters\n  // estimation\n  double rmse2 = NonLinearPinholeCalibration(X, x, Wpinhole);\n\n  // Finally, create a first parameter vector estimation\n  // by using the pinhole parameters and setting the distortion\n  // coefficients to 0\n  Eigen::Matrix<double, 17, 1> West = Eigen::Matrix<double, 17, 1>::Zero();\n  West.block(0, 0, 11, 1) = Wpinhole;\n\n  double rmse3 = BrownConradyPinholeCalibration(X, x, West, 2500, 5.0, 0.6, activatedParams);\n\n  // copy params\n  for (int i = 0; i < 17; ++i)\n  {\n    Wf(i) = West(i);\n  }\n\n  Eigen::Vector3d angles(Wf(0), Wf(1), Wf(2));\n  R = RollPitchYawToMatrix(angles);\n\n  std::cout << \"RMSE1: \" << rmse1 << std::endl;\n  std::cout << \"RMSE2: \" << rmse2 << std::endl;\n  std::cout << \"RMSE3: \" << rmse3 << std::endl;\n  std::cout << \"W: \";\n  for (int i = 0; i < 17; ++i)\n  {\n    std::cout << Wf(i) << \",\";\n  }\n  std::cout << std::endl;\n  return Wf;\n}\n", "meta": {"hexsha": "5a082e2dbeb92b10094613c76634c7b5217b16ab", "size": 15771, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "LidarPlugin/Common/Calib/Camera/CameraCalibration.cxx", "max_stars_repo_name": "Pandinosaurus/LidarView", "max_stars_repo_head_hexsha": "9b9b2976e9ac5dcd891a604dabbb79bd6fc6a57a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T11:14:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-13T11:14:18.000Z", "max_issues_repo_path": "LidarPlugin/Common/Calib/Camera/CameraCalibration.cxx", "max_issues_repo_name": "yxw027/LidarView", "max_issues_repo_head_hexsha": "9267729e62886a324ba7f2e3fed50db38b24f001", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LidarPlugin/Common/Calib/Camera/CameraCalibration.cxx", "max_forks_repo_name": "yxw027/LidarView", "max_forks_repo_head_hexsha": "9267729e62886a324ba7f2e3fed50db38b24f001", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-30T10:07:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-30T10:07:35.000Z", "avg_line_length": 36.2551724138, "max_line_length": 162, "alphanum_fraction": 0.593684611, "num_tokens": 4754, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.40100090284317386}}
{"text": "#ifndef JHMI_LIVER_CONSTANTS_HPP_NRC_20150903\n#define JHMI_LIVER_CONSTANTS_HPP_NRC_20150903\n\n#include \"utility/units.hpp\"\n#include <boost/math/constants/constants.hpp>\n\nnamespace jhmi {\n//  using gamma = boost::units::static_rational<27, 10>::type;\n//  using inv_gamma = boost::units::static_rational<gamma::Denominator, gamma::Numerator>::type;\n\n  static double const pi = boost::math::double_constants::pi;\n  static Pa const input_pressure = 98_mmHg;//1999 Bezy-Wendling\n#if 0\n#if 0\n  inline Pa_s blood_viscosity(m radius) {\n    return std::min(4. * pascals * seconds, Pa_s::from_value(1.8 * .6913 * (220 * std::exp(-1.3 * 1e6 * 2. * radius.value())\n      + 3.2 - 2.44 * std::exp(-.06 * std::pow(1e6 * 2. * radius.value(), .645)))));\n  }\n#else\n  inline Pa_s blood_viscosity(m) {\n    return 3.5e-3 * pascals * seconds;\n  }\n#endif\n#endif\n  static Pa_s const blood_viscosity = 3.5e-3 * pascals * seconds;//Fung\n  //static Pa const cell_pressure = 25_mmHg;//volmar\n  //static auto const proper_ha_flow = 400. * mL / minutes;//1999 Bezy-Wendling\n}\n#endif\n", "meta": {"hexsha": "11b9dc1fdc40fae1860558e9f33f8bd5ba500844", "size": 1052, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "liver/constants.hpp", "max_stars_repo_name": "ncrookston/liver_source", "max_stars_repo_head_hexsha": "9876ac4e9ea57d8e23767af9be061a9b10c6f1e5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "liver/constants.hpp", "max_issues_repo_name": "ncrookston/liver_source", "max_issues_repo_head_hexsha": "9876ac4e9ea57d8e23767af9be061a9b10c6f1e5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "liver/constants.hpp", "max_forks_repo_name": "ncrookston/liver_source", "max_forks_repo_head_hexsha": "9876ac4e9ea57d8e23767af9be061a9b10c6f1e5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0666666667, "max_line_length": 124, "alphanum_fraction": 0.6986692015, "num_tokens": 353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434978390747, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.4009891543374835}}
{"text": "/*\nCopyright 2018 Dennis Rohde\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n#pragma once\n\n#include <cmath>\n#include <limits>\n\n#include <boost/chrono/include.hpp>\n\n#include \"knn_graph.hpp\"\n#include \"random.hpp\"\n#include \"oracle.hpp\"\n\nclass Tester_Result{\npublic:\n    bool decision;\n    double total_time;\n    double query_time;\n};\n\ntemplate <typename V = double>\nclass KNN_Tester {\n    typedef typename KNN_Graph<V>::vertices_type vertices_type;\n    \nprotected:\n    bool auto_c1;\n    \npublic:\n    /**\n     * \n     * tuning parameter c1 for psi\n     * \n     */\n    double c1 = 1;\n    \n    /**\n     * \n     * tuning parameter c2 for |T|\n     * \n     */\n    double c2 = 1;\n\n    KNN_Tester(const bool auto_c1 = true) : auto_c1{auto_c1} {}\n    \n    /**\n     * \n     * Calculates approximate for c1\n     * @param Number of dimensions delta\n     * @return approximate for c1\n     * \n     */\n    static double c1_approximate(const KNN_Graph<V> &graph) {\n        auto delta = graph.dimension();\n        return std::pow(2, 0.401 * delta * (1 + 2.85 * delta / std::pow(delta, 1.4))); \n    }\n    \n    /**\n     * \n     * Property Testing Algorithm for k-nearest Neighborhood Graphs\n     * @param KNN_Graph G, average degree of G, epsilon\n     * @return true or false\n     * \n     */\n    virtual Tester_Result test(const KNN_Graph<V> &graph, const double d, const double epsilon = 0.001) {\n        if (auto_c1) this->c1 = c1_approximate(graph);\n        const auto delta = graph.dimension();\n        const auto k = graph.get_k();\n        const auto n = graph.number_vertices();\n        const auto s = std::ceil(100 * k * sqrt(n) / epsilon * c2);\n        const auto t = std::ceil(log(10) * c1 * k * sqrt(n));\n        \n        Uniform_Random_Generator<double> urandom_gen;\n        \n        const auto S = urandom_gen.get(s);\n        const auto T = urandom_gen.get(t);\n        \n        std::cout << \"|S| = \" << s << std::endl;\n        std::cout << \"|T| = \" << t << std::endl;\n        \n        bool wrongly_connected_found = false;\n        double distn, distw;\n\n        #pragma omp parallel for shared(wrongly_connected_found, distn, distw)\n        for (unsigned long long i = 0; i < S.size(); ++i) {\n            if (wrongly_connected_found) continue;\n            const unsigned long long v = floor(S[i] * n);\n            const auto v_value = graph.get_vertex(v);\n            if (graph.number_neighbors(v) > 100 * k * d / epsilon) continue;\n            const auto &neighbors = graph.get_edges()[v];\n            V distN = 0;\n            for (const auto &neighbor: neighbors) {\n                auto dist = KNN_Graph<V>::euclidean_distance(v_value, graph.get_vertex(neighbor));\n                if (dist > distN) {\n                    distN = dist;\n                }\n            }\n            for (unsigned long long j = 0; j < T.size(); ++j) {\n                if (wrongly_connected_found) {\n                    continue;\n                }\n                unsigned long long w = floor(T[j] * n);\n                auto dist = KNN_Graph<V>::euclidean_distance(v_value, graph.get_vertex(w));\n                if (v != w and distN - dist > std::numeric_limits<V>::epsilon()) {\n                    auto is_neighbor = false;\n                    for (const auto &neighbor: neighbors) {\n                        if (w == neighbor) {\n                            is_neighbor = true;\n                            break;\n                        }\n                    }\n                    if (not is_neighbor) {\n                        #pragma omp critical\n                        {\n                            if (not wrongly_connected_found) {\n                                wrongly_connected_found = true;\n                                distn = distN;\n                                distw = dist;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        Tester_Result result;\n        if (wrongly_connected_found) {\n            std::cout << \"Reject!\" << std::endl;\n            std::cout << distw << \" < \" << distn << std::endl;\n            result.decision = false;\n        } else {\n            std::cout << \"Accept!\" << std::endl;\n            result.decision = true;\n        }\n        return result;\n    }\n    \n    inline auto get_auto_c1() const {\n        return auto_c1;\n    }\n    \n    inline void set_auto_c1(const bool auto_c1) {\n        this->auto_c1 = auto_c1;\n    }\n};\n\ntemplate <typename V = double>\nclass KNN_Tester_Oracle : public KNN_Tester<V> {\n    Query_Oracle<V> Oracle;\n    \npublic:\n    KNN_Tester_Oracle(const Query_Oracle<V> &oracle) : Oracle{std::move(oracle)} {}\n\n    /**\n     * \n     * Property Testing Algorithm for k-Nearest Neighborhood Graphs - Oracle Version\n     * @param KNN_Graph G, average degree of G, epsilon\n     * @return\n     * \n     */\n    Tester_Result test(const KNN_Graph<V> &graph, const double d, const double epsilon = 0.001) {\n        auto start = boost::chrono::process_real_cpu_clock::now();\n        Oracle.reset_timer();\n        if (this->auto_c1) this->c1 = this->c1_approximate(graph);\n        const auto delta = graph.dimension();\n        const auto k = graph.get_k();\n        const auto n = graph.number_vertices();\n        const auto s = std::ceil(100 * k * sqrt(n) / epsilon * this->c2);\n        const auto t = std::ceil(log(10) * this->c1 * k * sqrt(n));\n        \n        Uniform_Random_Generator<double> urandom_gen;\n        \n        const auto S = urandom_gen.get(s);\n        const auto T = urandom_gen.get(t);\n        \n        std::cout << \"|S| = \" << s << std::endl;\n        std::cout << \"|T| = \" << t << std::endl;\n        \n        bool wrongly_connected_found = false;\n        double distn, distw;\n        \n        #pragma omp parallel for shared(wrongly_connected_found, distn, distw)\n        for (unsigned long long i = 0; i < S.size(); ++i) {\n            if (wrongly_connected_found) continue;\n            const unsigned long long v = floor(S[i] * n);\n            const auto v_value = graph.get_vertex(v);\n            Relation<V> neighbors;\n            #pragma omp critical\n            {\n                neighbors = Oracle.query(v);\n            }\n            if (neighbors.size() > 100 * k * d / epsilon) continue;\n            V distN = 0;\n            for (const auto &neighbor: neighbors) {\n                auto dist = KNN_Graph<V>::euclidean_distance(v_value, neighbor);\n                if (dist > distN) {\n                    distN = dist;\n                }\n            }\n            for (unsigned long long j = 0; j < T.size(); ++j) {\n                if (wrongly_connected_found) {\n                    continue;\n                }\n                unsigned long long w = floor(T[j] * n);\n                auto dist = KNN_Graph<V>::euclidean_distance(v_value, graph.get_vertex(w));\n                if (v != w and distN - dist > std::numeric_limits<V>::epsilon()) {\n                    auto is_neighbor = false;\n                    for (const auto &neighbor: neighbors) {\n                        if (graph.get_vertex(w) == neighbor) {\n                            is_neighbor = true;\n                            break;\n                        }\n                    }\n                    if (not is_neighbor) {\n                        #pragma omp critical\n                        {\n                            if (not wrongly_connected_found) {\n                                wrongly_connected_found = true;\n                                distn = distN;\n                                distw = dist;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        auto stop = boost::chrono::process_real_cpu_clock::now();\n        auto total_time = (stop-start).count();\n        auto query_time = Oracle.time();\n\n        Tester_Result result;\n        result.total_time = total_time / 1000000000.0;\n        result.query_time = query_time / 1000000000.0;\n        if (wrongly_connected_found) {\n            std::cout << \"Reject!\" << std::endl;\n            std::cout << distw << \" < \" << distn << std::endl;\n            result.decision = false;\n        } else {\n            std::cout << \"Accept!\" << std::endl;\n            result.decision = true;\n        }\n        return result;\n    }\n};\n\ntemplate <typename V = double>\nclass KNN_Improver : public KNN_Tester<V> {\npublic:\n    /**\n     * \n     * Property Testing Algorithm for k-Nearest Neighborhood Graphs - Graph Restauration\n     * @param KNN_Graph G, average degree of G, epsilon\n     * @return\n     * \n     */\n    auto improve(KNN_Graph<V> &graph, const double d, const double epsilon = 0.001) {\n        auto result = 0ul; \n        if (this->auto_c1) this->c1 = this->c1_approximate(graph);\n        const auto delta = graph.dimension();\n        const auto k = graph.get_k();\n        const auto n = graph.number_vertices();\n        const auto s = ceil(100 * k * sqrt(n) / epsilon * this->c2);\n        const auto t = ceil(log(10) * this->c1 * k * sqrt(n));\n        \n        Uniform_Random_Generator<double> urandom_gen;\n        \n        const auto S = urandom_gen.get(s);\n        const auto T = urandom_gen.get(t);\n        \n        std::cout << \"|S| = \" << s << std::endl;\n        std::cout << \"|T| = \" << t << std::endl;\n\n        #pragma omp parallel for shared(result)\n        for (unsigned long long i = 0; i < S.size(); ++i) {\n            const unsigned long long v = floor(S[i] * n);\n            const auto v_value = graph.get_vertex(v);\n            if (graph.number_neighbors(v) > 100 * k * d / epsilon) continue;\n            auto &neighbors = graph.get_edges()[v];\n            V distN = 0;\n            unsigned long long furthest = 0;\n            for (const auto &neighbor: neighbors) {\n                auto dist = KNN_Graph<V>::euclidean_distance(v_value, graph.get_vertex(neighbor));\n                if (dist > distN) {\n                    distN = dist;\n                    furthest = neighbor;\n                }\n            }\n            for (unsigned long long j = 0; j < T.size(); ++j) {\n                unsigned long long w = floor(T[j] * n);\n                auto dist = KNN_Graph<V>::euclidean_distance(v_value, graph.get_vertex(w));\n                if (v != w and distN - dist > std::numeric_limits<V>::epsilon()) {\n                    auto is_neighbor = false;\n                    for (const auto &neighbor: neighbors) {\n                        if (w == neighbor) {\n                            is_neighbor = true;\n                            break;\n                        }\n                    }\n                    if (not is_neighbor) {\n                        #pragma omp critical\n                        {\n                            graph.get_edges()[v][furthest] = w;\n                            ++result;\n                            distN = 0;\n                            for (const auto &neighbor: neighbors) {\n                                auto distF = KNN_Graph<V>::euclidean_distance(v_value, graph.get_vertex(neighbor));\n                                if (distF > distN) {\n                                    distN = distF;\n                                    furthest = neighbor;\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        return result;\n    }\n};\n", "meta": {"hexsha": "2199a3d86ab5f647ad4d9e32d27f541fd27dfa3f", "size": 12290, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/knn_tester.hpp", "max_stars_repo_name": "hfichtenberger/knn_tester", "max_stars_repo_head_hexsha": "a661baf5cf43e57de7ca4e01246c61feca6160f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T16:37:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-19T16:37:53.000Z", "max_issues_repo_path": "include/knn_tester.hpp", "max_issues_repo_name": "hfichtenberger/knn_tester", "max_issues_repo_head_hexsha": "a661baf5cf43e57de7ca4e01246c61feca6160f3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/knn_tester.hpp", "max_forks_repo_name": "hfichtenberger/knn_tester", "max_forks_repo_head_hexsha": "a661baf5cf43e57de7ca4e01246c61feca6160f3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-16T09:00:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-16T09:00:36.000Z", "avg_line_length": 37.6993865031, "max_line_length": 460, "alphanum_fraction": 0.504719284, "num_tokens": 2732, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.40084487069778085}}
{"text": "#include <cassert>\r\n#include <cmath>\r\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n\r\n#include \"mincostflowsolver.h\"\r\n\r\nvoid MinCostFlowSolver::solve()\r\n{\r\n\tconstructGraph();\r\n\tboost::successive_shortest_path_nonnegative_weights(\r\n\t\tgraph, main_source, main_sink,\r\n\t\tboost::capacity_map(boost::get(&EdgeProp::capacity, graph))\r\n\t\t\t.residual_capacity_map(boost::get(&EdgeProp::residual_capacity, graph))\r\n\t\t\t.weight_map(boost::get(&EdgeProp::weight, graph))\r\n\t\t\t.reverse_edge_map(boost::make_assoc_property_map(reverseEdgeMap)));\r\n\tdecodeSolution();\r\n}\r\n\r\nvoid MinCostFlowSolver::constructGraph()\r\n{\r\n\tfor (int r = 0; r < (int)R; ++r)\r\n\t{\r\n\t\tfor (int c = 0; c < (int)C; ++c)\r\n\t\t{\r\n\t\t\tint const v = M[r][c];\r\n\t\t\tif (v == 0)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tVertex vx = boost::add_vertex(VertexProp{r, c}, graph);\r\n\t\t\t(v > 0 ? sources : sinks).insert(vx);\r\n\t\t}\r\n\t}\r\n\r\n\tfor (auto u : sources)\r\n\t{\r\n\t\tauto const &up = graph[u];\r\n\t\tfor (auto v : sinks)\r\n\t\t{\r\n\t\t\tauto const &vp = graph[v];\r\n\t\t\tint const capacity = std::min(M[up.row][up.col], -M[vp.row][vp.col]);\r\n\t\t\tint const weight = std::abs(up.row - vp.row) + std::abs(up.col - vp.col);\r\n\t\t\taddEdge(u, v, capacity, weight);\r\n\t\t}\r\n\t}\r\n\r\n\tmain_source = boost::add_vertex(graph);\r\n\tfor (auto u : sources)\r\n\t{\r\n\t\tauto const &up = graph[u];\r\n\t\taddEdge(main_source, u, M[up.row][up.col]);\r\n\t}\r\n\r\n\tmain_sink = boost::add_vertex(graph);\r\n\tfor (auto v : sinks)\r\n\t{\r\n\t\tauto const &vp = graph[v];\r\n\t\taddEdge(v, main_sink, -M[vp.row][vp.col]);\r\n\t}\r\n}\r\n\r\nvoid MinCostFlowSolver::decodeSolution()\r\n{\r\n\tfor (auto u : sources)\r\n\t{\r\n\t\tauto edges = boost::out_edges(u, graph);\r\n\t\tfor (auto it = edges.first; it != edges.second; ++it)\r\n\t\t{\r\n\t\t\tauto v = boost::target(*it, graph);\r\n\t\t\tif (v == main_source)\r\n\t\t\t\tcontinue;\r\n\t\t\tauto const &ep = graph[*it];\r\n\t\t\tauto const &up = graph[u];\r\n\t\t\tauto const &vp = graph[v];\r\n\t\t\tmove(up.row, up.col, vp.row, vp.col, ep.capacity - ep.residual_capacity);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid MinCostFlowSolver::addEdge(Vertex u, Vertex v, int capacity, int weight /* = 0 */)\r\n{\r\n\tassert(capacity > 0 && weight >= 0);\r\n\tEdge e1 = boost::add_edge(u, v, EdgeProp{capacity, weight}, graph).first;\r\n\tEdge e2 = boost::add_edge(v, u, EdgeProp{0, -weight}, graph).first;\r\n\treverseEdgeMap[e1] = e2;\r\n\treverseEdgeMap[e2] = e1;\r\n}\r\n", "meta": {"hexsha": "a2c2aa7af2529ab979ef6607cb86a582391ed3c5", "size": 2335, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++GP18/1_kozbringak/mincostflowsolver.cpp", "max_stars_repo_name": "dhanak/competitive-coding", "max_stars_repo_head_hexsha": "9e28298f8c646f169b7389d0ef20f99c5ef68f00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "C++GP18/1_kozbringak/mincostflowsolver.cpp", "max_issues_repo_name": "dhanak/competitive-coding", "max_issues_repo_head_hexsha": "9e28298f8c646f169b7389d0ef20f99c5ef68f00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "C++GP18/1_kozbringak/mincostflowsolver.cpp", "max_forks_repo_name": "dhanak/competitive-coding", "max_forks_repo_head_hexsha": "9e28298f8c646f169b7389d0ef20f99c5ef68f00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5340909091, "max_line_length": 88, "alphanum_fraction": 0.6291220557, "num_tokens": 691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.647798211152541, "lm_q1q2_score": 0.40084485807545955}}
{"text": "/* Copyright 2020 CNRS-AIST JRL */\n\n#include <Eigen/Cholesky>\n#include <Eigen/Jacobi>\n#include <Eigen/QR>\n#include <jrl-qp/GoldfarbIdnaniSolver.h>\n\nusing Givens = Eigen::JacobiRotation<double>;\n\nnamespace jrl::qp\n{\nGoldfarbIdnaniSolver::GoldfarbIdnaniSolver() : DualSolver(), work_d_(0), work_J_(0), work_R_(0) {}\n\nGoldfarbIdnaniSolver::GoldfarbIdnaniSolver(int nbVar, int nbCstr, bool useBounds) : GoldfarbIdnaniSolver()\n{\n  resize(nbVar, nbCstr, useBounds);\n}\n\nTerminationStatus GoldfarbIdnaniSolver::solve(MatrixRef G,\n                                              const VectorConstRef & a,\n                                              const MatrixConstRef & C,\n                                              const VectorConstRef & bl,\n                                              const VectorConstRef & bu,\n                                              const VectorConstRef & xl,\n                                              const VectorConstRef & xu)\n{\n  int nbVar = G.rows();\n  int nbCstr = C.cols();\n  bool useBnd = xl.size() > 0;\n\n  LOG_RESET(log_);\n  LOG(log_, LogFlags::INPUT | LogFlags::NO_ITER, G, a, C, bl, bu, xl, xu);\n\n  assert(G.cols() == nbVar);\n  assert(a.size() == nbVar);\n  assert(C.rows() == nbVar);\n  assert(bl.size() == nbCstr);\n  assert(bu.size() == nbCstr);\n  assert(xl.size() == nbVar || xl.size() == 0);\n  assert(xu.size() == xl.size());\n\n  // TODO check input: bl<=bu, xl<=xu, ...\n\n  new(&pb_.G) MatrixRef(G);\n  new(&pb_.a) VectorConstRef(a);\n  new(&pb_.C) MatrixConstRef(C);\n  new(&pb_.bl) VectorConstRef(bl);\n  new(&pb_.bu) VectorConstRef(bu);\n  new(&pb_.xl) VectorConstRef(xl);\n  new(&pb_.xu) VectorConstRef(xu);\n\n  resize(nbVar, nbCstr, useBnd);\n\n  return DualSolver::solve();\n}\n\ninternal::InitTermination GoldfarbIdnaniSolver::init_()\n{\n  int ret = Eigen::internal::llt_inplace<double, Eigen::Lower>::blocked(pb_.G);\n  auto L = pb_.G.template triangularView<Eigen::Lower>();\n\n  if(ret >= 0) return TerminationStatus::NON_POS_HESSIAN;\n\n  // J = L^-t\n  auto J = work_J_.asMatrix(nbVar_, nbVar_, nbVar_);\n  J.setIdentity();\n  L.transpose().solveInPlace(J);\n\n  // x = -G^-1 * a\n  auto x = work_x_.asVector(nbVar_);\n  x = L.solve(pb_.a);\n  L.transpose().solveInPlace(x); // possible [OPTIM]: J already contains L^-T\n  x = -x;\n  f_ = 0.5 * pb_.a.dot(x);\n\n  A_.reset();\n  DEBUG_ONLY(work_R_.setZero());\n\n  // Adding equality constraints\n  initActiveSet();\n\n  return TerminationStatus::SUCCESS;\n}\n\ninternal::ConstraintNormal GoldfarbIdnaniSolver::selectViolatedConstraint_(const VectorConstRef & x) const\n{\n  // We look for the constraint with the maximum violation\n  //[NUMERIC] scale with constraint magnitude\n  double smin = 0;\n  int p = -1;\n  ActivationStatus status = ActivationStatus::INACTIVE;\n\n  // Check general constraints\n  for(int i = 0; i < A_.nbCstr(); ++i)\n  {\n    if(!A_.isActive(i))\n    {\n      double cx = pb_.C.col(i).dot(x); // possible [OPTIM]: should we compute C^T x at once ?\n      if(double sl = cx - pb_.bl[i]; sl < smin)\n      {\n        smin = sl;\n        p = i;\n        status = ActivationStatus::LOWER;\n      }\n      else if(double su = pb_.bu[i] - cx; su < smin)\n      {\n        smin = su;\n        p = i;\n        status = ActivationStatus::UPPER;\n      }\n    }\n  }\n\n  // Check bound constraints\n  for(int i = 0; i < A_.nbBnd(); ++i)\n  {\n    if(!A_.isActiveBnd(i))\n    {\n      if(double sl = x[i] - pb_.xl[i]; sl < smin)\n      {\n        smin = sl;\n        p = A_.nbCstr() + i;\n        status = ActivationStatus::LOWER_BOUND;\n      }\n      else if(double su = pb_.xu[i] - x[i]; su < smin)\n      {\n        smin = su;\n        p = A_.nbCstr() + i;\n        status = ActivationStatus::UPPER_BOUND;\n      }\n    }\n  }\n\n  return {pb_.C, p, status};\n}\n\nvoid GoldfarbIdnaniSolver::computeStep_(VectorRef z, VectorRef r, const internal::ConstraintNormal & np) const\n{\n  int q = A_.nbActiveCstr();\n  auto d = work_d_.asVector(nbVar_, {});\n  auto J = work_J_.asMatrix(nbVar_, nbVar_, nbVar_);\n  auto R = work_R_.asMatrix(q, q, nbVar_).template triangularView<Eigen::Upper>();\n\n  np.preMultiplyByMt(d, J);\n  z.noalias() = J.rightCols(nbVar_ - q) * d.tail(nbVar_ - q);\n  r = R.solve(d.head(q));\n  DBG(log_, LogFlags::ITERATION_ADVANCE_DETAILS, J, R, d);\n}\n\nDualSolver::StepLength GoldfarbIdnaniSolver::computeStepLength_(const internal::ConstraintNormal & np,\n                                                                const VectorConstRef & x,\n                                                                const VectorConstRef & u,\n                                                                const VectorConstRef & z,\n                                                                const VectorConstRef & r) const\n{\n  double t1 = options_.bigBnd_;\n  double t2 = options_.bigBnd_;\n  int l = 0;\n\n  for(int k = 0; k < A_.nbActiveCstr(); ++k)\n  {\n    if(A_.activationStatus(k) != ActivationStatus::EQUALITY && A_.activationStatus(k) != ActivationStatus::FIXED\n       && r[k] > 0)\n    {\n      if(double tk = u[k] / r[k]; tk < t1)\n      {\n        t1 = tk;\n        l = k;\n      }\n    }\n  }\n\n  if(z.norm() > 1e-14) //[NUMERIC] better criterion\n  {\n    double b, cx, cz;\n    int p, pb;\n    switch(np.status())\n    {\n      case ActivationStatus::LOWER:\n        p = np.index();\n        b = pb_.bl[p];\n        cx = pb_.C.col(p).dot(x);\n        cz = pb_.C.col(p).dot(z);\n        break;\n      case ActivationStatus::UPPER:\n        p = np.index();\n        b = pb_.bu[p];\n        cx = pb_.C.col(p).dot(x);\n        cz = pb_.C.col(p).dot(z);\n        break;\n      case ActivationStatus::EQUALITY:\n        assert(false);\n        break;\n      case ActivationStatus::LOWER_BOUND:\n        pb = np.bndIndex();\n        b = pb_.xl[pb];\n        cx = x[pb];\n        cz = z[pb];\n        break;\n      case ActivationStatus::UPPER_BOUND:\n        pb = np.bndIndex();\n        b = pb_.xu[pb];\n        cx = x[pb];\n        cz = z[pb];\n        break;\n      case ActivationStatus::FIXED:\n        assert(false);\n        break;\n      default:\n        assert(false);\n    }\n    t2 = (b - cx) / cz;\n  }\n\n  return {t1, t2, l};\n}\n\nbool GoldfarbIdnaniSolver::addConstraint_(const internal::ConstraintNormal & np)\n{\n  int q = A_.nbActiveCstr(); // This already counts the new constraint\n  auto d = work_d_.asVector(nbVar_);\n  auto J = work_J_.asMatrix(nbVar_, nbVar_, nbVar_);\n  for(int i = nbVar_ - 2; i >= q - 1; --i) //[OPTIM] use Householder transformation instead\n  {\n    Givens Qi;\n    Qi.makeGivens(d[i], d[i + 1], &d[i]);\n    DEBUG_ONLY(d[i + 1] = 0);\n    J.applyOnTheRight(i, i + 1, Qi);\n  }\n  auto R = work_R_.asMatrix(q, q, nbVar_);\n  R.rightCols<1>() = d.head(q);\n\n  return true; //[NUMERIC]: add test on dependency\n}\n\nbool GoldfarbIdnaniSolver::removeConstraint_(int l)\n{\n  int q = A_.nbActiveCstr(); // This already counts that the constraint was removed\n  auto d = work_d_.asVector(nbVar_);\n  auto J = work_J_.asMatrix(nbVar_, nbVar_, nbVar_);\n  auto R = work_R_.asMatrix(q + 1, q + 1, nbVar_);\n\n  for(int i = l; i < q; ++i)\n  {\n    Givens Qi;\n    R.col(i).head(i) = R.col(i + 1).head(i);\n    Qi.makeGivens(R(i, i + 1), R(i + 1, i + 1), &R(i, i));\n    DEBUG_ONLY(R(i + 1, i + 1) = 0);\n    R.rightCols(q - i - 1).applyOnTheLeft(i, i + 1, Qi.transpose());\n    J.applyOnTheRight(i, i + 1, Qi);\n  }\n\n  return true;\n}\n\nvoid GoldfarbIdnaniSolver::resize_(int nbVar, int nbCstr, bool useBounds)\n{\n  if(nbVar != nbVar_)\n  {\n    work_d_.resize(nbVar);\n    work_J_.resize(nbVar, nbVar);\n    work_R_.resize(nbVar, nbVar);\n  }\n}\n\nvoid GoldfarbIdnaniSolver::initActiveSet()\n{\n  for(int i = 0; i < A_.nbCstr(); ++i)\n  {\n    if(pb_.bl[i] == pb_.bu[i])\n    {\n      internal::ConstraintNormal np(pb_.C, i, ActivationStatus::EQUALITY);\n      addInitialConstraint(np);\n    }\n  }\n\n  for(int i = 0; i < A_.nbBnd(); ++i)\n  {\n    if(pb_.xl[i] == pb_.xu[i])\n    {\n      internal::ConstraintNormal np(pb_.C, A_.nbCstr() + i, ActivationStatus::FIXED);\n      addInitialConstraint(np);\n    }\n  }\n}\n\nvoid GoldfarbIdnaniSolver::addInitialConstraint(const internal::ConstraintNormal & np)\n{\n  int q = A_.nbActiveCstr();\n  WVector x = work_x_.asVector(nbVar_);\n  WVector z = work_z_.asVector(nbVar_);\n  WVector u = work_u_.asVector(q + 1);\n  WVector r = work_r_.asVector(q);\n  u[q] = 0;\n\n  computeStep(z, r, np);\n\n  assert(np.status() == ActivationStatus::EQUALITY || np.status() == ActivationStatus::FIXED);\n  double t = 0;\n  if(z.norm() > 1e-14) //[NUMERIC] better criterion\n  {\n    if(np.status() == ActivationStatus::EQUALITY) //[OPTIM] we can avoid this if by specializing the function to general\n                                                  // constraint or bound\n    {\n      int p = np.index();\n      t = (pb_.bl[p] - pb_.C.col(p).dot(x)) / pb_.C.col(p).dot(z);\n    }\n    else\n    {\n      int pb = np.bndIndex();\n      t = (pb_.xl[pb] - x[pb]) / z[pb];\n    }\n  }\n  else\n  {\n    // numerical problem\n  }\n\n  x += t * z;\n  f_ += t * np.dot(z) * (.5 * t + u[q]);\n  // u = u + t*[-r;1]\n  u.head(q) -= t * r;\n  u[q] += t;\n  if(!addConstraint(np))\n  {\n    LOG_COMMENT(log_, LogFlags::TERMINATION, \"Attempting to add a linearly dependent constraint.\");\n    // return TerminationStatus::LINEAR_DEPENDENCY_DETECTED;\n  }\n}\n} // namespace jrl::qp", "meta": {"hexsha": "65a994251de9e813a96200d76061330b53f22320", "size": 9134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GoldfarbIdnaniSolver.cpp", "max_stars_repo_name": "mehdi-benallegue/jrl-qp", "max_stars_repo_head_hexsha": "b6d2268dcd1e91708585474b3f0f93c9104887c0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-08-20T09:06:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T03:42:58.000Z", "max_issues_repo_path": "src/GoldfarbIdnaniSolver.cpp", "max_issues_repo_name": "mehdi-benallegue/jrl-qp", "max_issues_repo_head_hexsha": "b6d2268dcd1e91708585474b3f0f93c9104887c0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-11-21T10:29:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-21T11:13:41.000Z", "max_forks_repo_path": "src/GoldfarbIdnaniSolver.cpp", "max_forks_repo_name": "mehdi-benallegue/jrl-qp", "max_forks_repo_head_hexsha": "b6d2268dcd1e91708585474b3f0f93c9104887c0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-04T12:11:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-04T12:11:44.000Z", "avg_line_length": 27.6787878788, "max_line_length": 120, "alphanum_fraction": 0.5651412306, "num_tokens": 2760, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.40083539663669904}}
{"text": "#include \"naivebayesfeature.h\"\n#include \"utilities.h\"\n#include <boost/foreach.hpp>\n\nusing namespace std;\n\nNaiveBayesFeature::NaiveBayesFeature(const HyperParameters &hp) : NaiveBayes( hp ) {\n    m_featureType = (hp.naiveBayesFeatureType == \"Gaussian\") ? FEATURE_GAUSSIAN : FEATURE_HISTOGRAM;\n}\n\nvoid NaiveBayesFeature::calcMeanAndVariance(const matrix<float>& data, const std::vector<int>& labels, Feature& f) {\n    std::vector<double> mean(m_hp.numClasses,0.0);\n    std::vector<double> variance(m_hp.numClasses,0.0);\n    std::vector<int> numCounts(m_hp.numClasses,0);\n\n    BOOST_FOREACH(int sample, m_inBagSamples) {\n        mean[labels[sample]] += data(sample,f.index);\n        numCounts[labels[sample]]++;\n        variance[labels[sample]] += pow((double)data(sample,f.index),2.0);\n    }\n\n    for (int c = 0; c < m_hp.numClasses; c++) {\n        mean[c] /= numCounts[c];  // mu\n        variance[c] /= numCounts[c]; // E(X^2)\n        variance[c] -= pow(mean[c], 2.0);\n    }\n\n    f.mean = mean;\n    f.variance = variance;\n}\n\n// Weighted Statistics\nvoid NaiveBayesFeature::calcMeanAndVariance(const matrix<float>& data, const std::vector<int>& labels, Feature& f,\n        const std::vector<double>& weights) {\n    std::vector<double> mean(m_hp.numClasses,0.0);\n    std::vector<double> variance(m_hp.numClasses,0.0);\n    std::vector<double> numCounts(m_hp.numClasses,0.0);\n\n    BOOST_FOREACH(int sample, m_inBagSamples) {\n        mean[labels[sample]] += data(sample,f.index)*weights[sample];\n        numCounts[labels[sample]] += weights[sample];\n        variance[labels[sample]] += pow((double)data(sample,f.index)*weights[sample],2.0);\n    }\n\n    for (int c = 0; c < m_hp.numClasses; c++) {\n        mean[c] /= numCounts[c];  // mu\n        variance[c] /= numCounts[c]; // E(X^2)\n        variance[c] -= pow(mean[c], 2.0);\n    }\n\n    f.mean = mean;\n    f.variance = variance;\n}\n\nvoid NaiveBayesFeature::calcHistogram(const matrix<float>& data, const std::vector<int>& labels, Feature& f) {\n    // find min and max values\n    f.min = data(m_inBagSamples[0],f.index);\n    f.max = data(m_inBagSamples[0],f.index);\n\n    BOOST_FOREACH(int sample, m_inBagSamples) {\n        f.min = (data(sample,f.index) < f.min) ? data(sample,f.index) : f.min;\n        f.max = (data(sample,f.index) > f.max) ? data(sample,f.index) : f.max;\n    }\n    f.numBins = (float)m_hp.numHistogramBins;\n\n    std::vector<float> classHistogram((int) f.numBins, 0.0);\n    std::vector<std::vector<float> > histogram(m_hp.numClasses,classHistogram);\n    std::vector<int> classCounter(m_hp.numClasses,0);\n\n    if ( f.numBins > 2.0) {\n        f.w = abs(f.min - f.max)/f.numBins;\n\n        BOOST_FOREACH(int sample, m_inBagSamples) {\n            int binIndex = (int) ((data(sample, f.index) - f.min)/f.w);\n            binIndex -= (binIndex == f.numBins) ? 1 : 0;\n            histogram[labels[sample]][binIndex]++;\n            classCounter[labels[sample]]++;\n        }\n    } else {\n        const float numSteps = 20;\n        const float stepSize = abs(f.min - f.max)/numSteps;\n        float bestEntropy = 1e10;\n        float bestThreshold = 0.0;\n        std::vector<int> decision(data.size1());\n        // Find the best threshold\n        for (double threshold = f.min ; threshold < f.max ; threshold += stepSize) {\n            int oneCount = 0, zeroCount = 0;\n            std::vector<double> zeroClassCount(m_hp.numClasses, 0.0), oneClassCount(m_hp.numClasses, 0.0);\n\n            BOOST_FOREACH(int sample, m_inBagSamples) {\n                if (data(sample, f.index) > threshold) {\n                    decision[sample] = 1;\n                    oneClassCount[labels[sample]]++;\n                    oneCount++;\n                } else {\n                    decision[sample] = 0;\n                    zeroClassCount[labels[sample]]++;\n                    zeroCount++;\n                }\n            }\n\n            // Calc entropy\n            double oneEntropy = 0, zeroEntropy = 0;\n            for (int nClass = 0; nClass < m_hp.numClasses; nClass++) {\n                oneClassCount[nClass] /= oneCount;\n                zeroClassCount[nClass] /= zeroCount;\n\n                if (oneClassCount[nClass]) {\n                    oneEntropy -= oneClassCount[nClass]*log(oneClassCount[nClass]);\n                }\n                if (zeroClassCount[nClass]) {\n                    zeroEntropy -= zeroClassCount[nClass]*log(zeroClassCount[nClass]);\n                }\n            }\n\n            // Total Entropy\n            double entropy = (zeroEntropy*zeroCount + oneEntropy*oneCount)/(zeroCount + oneCount);\n            if (entropy < bestEntropy) {\n                bestEntropy = entropy;\n                bestThreshold = threshold;\n            }\n        }\n        f.threshold = bestThreshold;\n\n        BOOST_FOREACH(int sample, m_inBagSamples) {\n            int binIndex = (data(sample, f.index) > f.threshold) ? 1 : 0;\n            histogram[labels[sample]][binIndex]++;\n            classCounter[labels[sample]]++;\n        }\n    }\n\n    std::vector<std::vector<float> >::iterator it(histogram.begin());\n    std::vector<std::vector<float> >::iterator end(histogram.end());\n    for (int c = 0;it != end; it++, c++) {\n        for (int bin = 0; bin < f.numBins; bin++) {\n            (*it)[bin] /= (classCounter[c] + 1e-10);\n        }\n    }\n    f.histogram = histogram;\n}\n\n// Weighted Discrete Statistics\nvoid NaiveBayesFeature::calcHistogram(const matrix<float>& data, const std::vector<int>& labels, Feature& f,\n                                      const std::vector<double>& weights) {\n    // find min and max values\n    f.min = data(m_inBagSamples[0],f.index);\n    f.max = data(m_inBagSamples[0],f.index);\n\n    BOOST_FOREACH(int sample, m_inBagSamples) {\n        f.min = (data(sample,f.index) < f.min) ? data(sample,f.index) : f.min;\n        f.max = (data(sample,f.index) > f.max) ? data(sample,f.index) : f.max;\n    }\n    f.numBins = (float)m_hp.numHistogramBins;\n\n    std::vector<float> classHistogram((int) f.numBins, 0.0);\n    std::vector<std::vector<float> > histogram(m_hp.numClasses,classHistogram);\n    std::vector<double> classCounter(m_hp.numClasses,0.0);\n\n    if ( f.numBins > 2.0) {\n        f.w = abs(f.min - f.max)/f.numBins;\n\n        BOOST_FOREACH(int sample, m_inBagSamples) {\n            int binIndex = (int) ((data(sample,f.index) - f.min)/f.w);\n            binIndex -= (binIndex == f.numBins) ? 1 : 0;\n            histogram[labels[sample]][binIndex] += weights[sample];\n            classCounter[labels[sample]] += weights[sample];\n        }\n    } else {\n        const float numSteps = 20;\n        const float stepSize = abs(f.min - f.max)/numSteps;\n        float bestEntropy = 1e10;\n        float bestThreshold = 0.0;\n        std::vector<int> decision(data.size1());\n        // Find the best threshold\n        for (double threshold = f.min ; threshold < f.max ; threshold += stepSize) {\n            double oneCount = 0, zeroCount = 0;\n            std::vector<double> zeroClassCount(m_hp.numClasses, 0.0), oneClassCount(m_hp.numClasses, 0.0);\n\n            BOOST_FOREACH(int sample, m_inBagSamples) {\n                if (data(sample, f.index) > threshold) {\n                    decision[sample] = 1;\n                    oneClassCount[labels[sample]] += weights[sample];\n                    oneCount += weights[sample];\n                } else {\n                    decision[sample] = 0;\n                    zeroClassCount[labels[sample]] += weights[sample];\n                    zeroCount += weights[sample];\n                }\n            }\n\n            // Calc entropy\n            double oneEntropy = 0, zeroEntropy = 0;\n            for (int nClass = 0; nClass < m_hp.numClasses; nClass++) {\n                oneClassCount[nClass] /= oneCount;\n                zeroClassCount[nClass] /= zeroCount;\n\n                if (oneClassCount[nClass]) {\n                    oneEntropy -= oneClassCount[nClass]*log(oneClassCount[nClass]);\n                }\n                if (zeroClassCount[nClass]) {\n                    zeroEntropy -= zeroClassCount[nClass]*log(zeroClassCount[nClass]);\n                }\n            }\n\n            // Total Entropy\n            double entropy = (zeroEntropy*zeroCount + oneEntropy*oneCount)/(zeroCount + oneCount);\n            if (entropy < bestEntropy) {\n                bestEntropy = entropy;\n                bestThreshold = threshold;\n            }\n        }\n        f.threshold = bestThreshold;\n\n        BOOST_FOREACH(int sample, m_inBagSamples) {\n            int binIndex = (data(sample, f.index) > f.threshold) ? 1 : 0;\n            histogram[labels[sample]][binIndex] += weights[sample];\n            classCounter[labels[sample]] += weights[sample];\n        }\n    }\n\n    // Normalise Bins\n    std::vector<std::vector<float> >::iterator it(histogram.begin());\n    std::vector<std::vector<float> >::iterator end(histogram.end());\n    for (int c = 0;it != end; it++, c++) {\n        for (int bin = 0; bin < f.numBins; bin++) {\n            (*it)[bin] /= (classCounter[c] + 1e-10);\n        }\n    }\n    f.histogram = histogram;\n}\n\n\nvoid NaiveBayesFeature::train(const matrix<float>& data, const std::vector<int>& labels,\n                              matrix<float>& forestConfidences, matrix<float>& forestOutOfBagConfidences,\n                              std::vector<int>& forestOutOfBagVoteNum) {\n    // Initialize\n    initialize(m_hp.numLabeled);\n\n    // Random Subsamples data according to bagratio\n    subSample(m_hp.numLabeled);\n\n    // Train the Naive Bayes Classifiers\n    std::vector<int> randomFeatures = randPerm(data.size2(),m_hp.numRandomFeatures);\n\n    Feature f;\n    f.type = m_featureType;\n    if (m_featureType == FEATURE_GAUSSIAN) {\n        BOOST_FOREACH(int n, randomFeatures) {\n            f.index = n;\n            calcMeanAndVariance(data,labels,f);\n            m_features.push_back(f);\n        }\n    } else { // FEATURE_HISTOGRAM\n        BOOST_FOREACH(int n, randomFeatures) {\n            f.index = n;\n            calcHistogram(data,labels,f);\n            m_features.push_back(f);\n        }\n    }\n\n    eval(data,labels);\n\n    finalize(data, forestConfidences, forestOutOfBagConfidences, forestOutOfBagVoteNum);\n}\n\n// Weighted Training\nvoid NaiveBayesFeature::train(const matrix<float>& data, const std::vector<int>& labels, const std::vector<double>& weights,\n                              matrix<float>& forestConfidences, matrix<float>& forestOutOfBagConfidences,\n                              std::vector<int>& forestOutOfBagVoteNum, bool init)\n{\n    if (init)\n    {\n        // Initialize\n        initialize(m_hp.numLabeled);\n        // Random Subsamples data according to bagratio\n        subSample(m_hp.numLabeled);\n    }\n    // Train the Naive Bayes Classifiers\n    std::vector<int> randomFeatures = randPerm(data.size2(),m_hp.numRandomFeatures);\n\n    Feature f;\n    f.type = m_featureType;\n    if (m_featureType == FEATURE_GAUSSIAN)\n    {\n        BOOST_FOREACH(int n, randomFeatures)\n        {\n            f.index = n;\n            calcMeanAndVariance(data,labels,f);\n            m_features.push_back(f);\n        }\n    }\n    else   // FEATURE_HISTOGRAM\n    {\n        BOOST_FOREACH(int n, randomFeatures)\n        {\n            f.index = n;\n            calcHistogram(data,labels,f,weights);\n            m_features.push_back(f);\n        }\n    }\n\n    eval(data,labels);\n\n    finalize(data, forestConfidences, forestOutOfBagConfidences, forestOutOfBagVoteNum);\n}\n\n// Weighted Training\nvoid NaiveBayesFeature::retrain(const matrix<float>& data, const std::vector<int>& labels, const std::vector<double>& weights,\n                              matrix<float>& forestConfidences, matrix<float>& forestOutOfBagConfidences,\n                              std::vector<int>& forestOutOfBagVoteNum, bool init)\n{\n    if (init)\n    {\n        // Initialize\n        initialize(data.size1());\n        // Random Subsamples data according to bagratio\n        subSample(data.size1());\n    }\n    // Train the Naive Bayes Classifiers\n    std::vector<int> randomFeatures = randPerm(data.size2(),m_hp.numRandomFeatures);\n\n    Feature f;\n    f.type = m_featureType;\n    if (m_featureType == FEATURE_GAUSSIAN) {\n        BOOST_FOREACH(int n, randomFeatures) {\n            f.index = n;\n            calcMeanAndVariance(data,labels,f,weights);\n            m_features.push_back(f);\n        }\n    } else { // FEATURE_HISTOGRAM\n        BOOST_FOREACH(int n, randomFeatures) {\n            f.index = n;\n            calcHistogram(data,labels,f,weights);\n            m_features.push_back(f);\n        }\n    }\n\n    eval(data,labels);\n\n    finalize(data, forestConfidences, forestOutOfBagConfidences, forestOutOfBagVoteNum);\n}\n\n\nvoid NaiveBayesFeature::evalOutOfBagSamples(const matrix<float>& data) {\n\n}\n\nvoid NaiveBayesFeature::eval(const matrix<float>& data, const std::vector<int> labels) {\n    m_confidences.resize(data.size1(), m_hp.numClasses);\n    // init to one (due to multiplication)\n    for (int sample = 0; sample < (int)data.size1(); sample++) {\n        for ( int c = 0; c < m_hp.numClasses; c++) {\n            m_confidences(sample,c) = 1.0;\n        }\n    }\n\n    // Fill confidence matrix\n    std::vector<Feature>::iterator it(m_features.begin());\n    std::vector<Feature>::iterator end(m_features.end());\n    for (int sample = 0; sample < (int)data.size1(); sample++) {\n        it = m_features.begin();\n        while (it != end) {\n            it->eval(data,sample,m_confidences);\n            ++it;\n        }\n        double max = 0.0;\n        for ( int c = 0; c < m_hp.numClasses; c++) {\n            if (m_confidences(sample,c) > max) {\n                m_predictions[sample] = c;\n                max = m_confidences(sample,c);\n            }\n        }\n    }\n\n    double error = computeError(labels);\n    if (m_hp.verbose) {\n        cout << \"Error: \" << error << endl;\n    }\n\n}\n\nvoid NaiveBayesFeature::eval(const matrix<float>& data, matrix<float>& confidences) {\n    m_confidences.resize(data.size1(), m_hp.numClasses);\n    // init to one (due to multiplication)\n    for (int sample = 0; sample < (int)data.size1(); sample++) {\n        for ( int c = 0; c < m_hp.numClasses; c++) {\n            m_confidences(sample,c) = 1.0;\n        }\n    }\n\n    // Fill confidence matrix\n    std::vector<Feature>::iterator it(m_features.begin());\n    std::vector<Feature>::iterator end(m_features.end());\n    for (int sample = 0; sample < (int)data.size1(); sample++) {\n        it = m_features.begin();\n        while (it != end) {\n            it->eval(data,sample,m_confidences);\n            ++it;\n        }\n        for ( int c = 0; c < m_hp.numClasses; c++) {\n            confidences(sample,c) += m_confidences(sample,c);\n        }\n    }\n\n}\n\nvoid Feature::eval(const matrix<float>& data, const int sampleIndex, matrix<float>& confidences) {\n    if ( type == FEATURE_GAUSSIAN ) {\n        evalGaussian(data,sampleIndex,confidences);\n    } else {\n        evalHistogram(data,sampleIndex,confidences);\n    }\n}\n\nvoid Feature::evalGaussian(const matrix<float>& data, const int sampleIndex, matrix<float>& confidences) {\n    for (int c = 0; c < (int)mean.size(); c++) {\n        confidences(sampleIndex,c) *= 1.0/variance[c] * exp(-pow(data(sampleIndex,index) - mean[c],2.0)/(2.0*pow(variance[c],2.0)));\n    }\n}\n\nvoid Feature::evalHistogram(const matrix<float>& data, const int sampleIndex, matrix<float>& confidences) {\n  int binIndex;\n  if (numBins > 2) {\n    binIndex = (int) ((data(sampleIndex,index) - min)/w);\n    binIndex -= (binIndex == numBins) ? 1 : 0;\n    binIndex = (binIndex < 0.0) ? 0 : binIndex;\n  }\n  else {\n    binIndex = (data(sampleIndex, index) > threshold) ? 1 : 0;\n  }\n  for (int c = 0; c < (int)histogram.size(); c++) {\n    confidences(sampleIndex,c) *= histogram[c][binIndex];\n  }\n}\n", "meta": {"hexsha": "64b2d31267fc59b219595b820a53e99b83247b5b", "size": 15651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/External/RF/naivebayesfeature.cpp", "max_stars_repo_name": "tschuls/ETH-SegReg-DLL", "max_stars_repo_head_hexsha": "34bd10464dc5e8b3c7bf3371ca1e190d692385b7", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-04-15T06:49:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T09:09:50.000Z", "max_issues_repo_path": "source/External/RF/naivebayesfeature.cpp", "max_issues_repo_name": "tschuls/ETH-SegReg-DLL", "max_issues_repo_head_hexsha": "34bd10464dc5e8b3c7bf3371ca1e190d692385b7", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2015-03-09T19:09:47.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-04T15:31:12.000Z", "max_forks_repo_path": "source/External/RF/naivebayesfeature.cpp", "max_forks_repo_name": "tschuls/ETH-SegReg-DLL", "max_forks_repo_head_hexsha": "34bd10464dc5e8b3c7bf3371ca1e190d692385b7", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-04-08T09:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-12T17:30:15.000Z", "avg_line_length": 35.9793103448, "max_line_length": 132, "alphanum_fraction": 0.5801546227, "num_tokens": 3942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177518, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.40083539663669904}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Piotr Smulewicz\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file multiway_cut.hpp\n * @brief\n * @author Piotr Smulewicz, Piotr Godlewski\n * @version 1.0\n * @date 2013-12-19\n */\n\n#ifndef PAAL_MULTIWAY_CUT_HPP\n#define PAAL_MULTIWAY_CUT_HPP\n\n#include \"paal/lp/glp.hpp\"\n#include \"paal/utils/type_functions.hpp\"\n#include \"paal/utils/irange.hpp\"\n#include \"paal/utils/assign_updates.hpp\"\n\n#include <boost/bimap.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/range/as_array.hpp>\n\n#include <fstream>\n#include <tuple>\n#include <utility>\n#include <vector>\n#include <random>\n\n\nnamespace paal {\nnamespace detail {\n\ninline int vertices_column_index(int vertex, int dimentions, int column) {\n    return vertex * dimentions + column;\n}\n\ntemplate <class Graph>\nusing CostType = typename boost::property_traits<\n    puretype(get(boost::edge_weight, std::declval<Graph>()))>::value_type;\n\ntemplate <typename LP> class multiway_cut_lp {\n  public:\n    /// Initialize the cut LP.\n    template <typename Graph, typename IndexMap, typename WeightMap,\n              typename ColorMap>\n    void init(const Graph &graph, int k, const IndexMap &index_map,\n              const WeightMap &weight_map, const ColorMap &color_map) {\n\n        m_lp.set_lp_name(\"Multiway Cut\");\n        m_lp.set_optimization_type(lp::MINIMIZE);\n\n        add_variables(graph, k, weight_map);\n        add_constraints(graph, k, index_map, color_map);\n    }\n\n  private:\n    // adding variables\n    // returns the number of variables\n    template <typename Graph, typename WeightMap>\n    void add_variables(const Graph &graph, int k, const WeightMap &weight_map) {\n        for (auto e : boost::as_array(edges(graph))) {\n            for (int i = 0; i < k; ++i) {\n                auto col_idx = m_lp.add_column(get(weight_map, e));\n                edges_column.push_back(col_idx);\n            }\n        }\n        for (unsigned vertex = 0; vertex <= num_vertices(graph); ++vertex) {\n            for (int i = 0; i < k; ++i) {\n                auto col_idx = m_lp.add_column(0);\n                vertices_column.push_back(col_idx);\n            }\n        }\n    }\n\n    template <typename Graph, typename IndexMap, typename ColorMap>\n    void add_constraints(const Graph &graph, int k, const IndexMap &index_map,\n                         const ColorMap &color_map) {\n        int db_index = 0;\n        for (auto edge : boost::as_array(edges(graph))) {\n            auto sour = get(index_map, source(edge, graph));\n            auto targ = get(index_map, target(edge, graph));\n            for (auto i : irange(k)) {\n                for (auto j : irange(2)) {\n                    auto x_e =\n                        edges_column[vertices_column_index(db_index, k, i)];\n                    auto x_src =\n                        vertices_column[vertices_column_index(sour, k, i)];\n                    auto x_trg =\n                        vertices_column[vertices_column_index(targ, k, i)];\n                    m_lp.add_row(\n                        x_e + (j * 2 - 1) * x_src + (1 - 2 * j) * x_trg >= 0);\n                }\n            }\n            ++db_index;\n        }\n        db_index = 0;\n        for (auto vertex : boost::as_array(vertices(graph))) {\n            auto col = get(color_map, vertex);\n            if (col != 0) {\n                auto x_col = vertices_column[\n                    vertices_column_index(db_index, k, col - 1)];\n                m_lp.add_row(x_col == 1);\n            }\n            lp::linear_expression expr;\n            for (auto i : irange(k)) {\n                expr += vertices_column[vertices_column_index(db_index, k, i)];\n            }\n            m_lp.add_row(std::move(expr) == 1);\n            ++db_index;\n        }\n    }\n\n  public:\n    LP m_lp;\n    std::vector<lp::col_id> edges_column;\n    std::vector<lp::col_id> vertices_column;\n};\n\n\ntemplate <typename Graph, typename VertexIndexMap, typename EdgeWeightMap,\n          typename Dist, typename Rand, typename LP>\nauto make_cut(const Graph &graph, int k, const VertexIndexMap &index_map,\n              const EdgeWeightMap &weight_map, Dist &dist, Rand &&random_engine,\n              multiway_cut_lp<LP> &mc_lp, std::vector<int> &vertex_to_part)\n    ->detail::CostType<Graph> {\n    double cut_cost = 0;\n    std::vector<double> random_radiuses;\n    dist.reset();\n    for (int i = 0; i < k; ++i) {\n        random_radiuses.push_back(dist(random_engine));\n    }\n    vertex_to_part.resize(num_vertices(graph));\n    auto get_column = [&](int vertex, int dimension) {\n        return mc_lp.m_lp.get_col_value(\n            mc_lp.vertices_column[vertices_column_index(vertex, k, dimension)]);\n    };\n\n    for (auto vertex : boost::as_array(vertices(graph))) {\n        for (int dimension = 0; dimension < k; ++dimension)\n            if (1.0 - get_column(get(index_map, vertex), dimension) <\n                    random_radiuses[dimension] ||\n                dimension == k - 1) {\n                // because each vertex have sum of coordinates equal 1,\n                // 1.0-get_column(vertex,dimension) is proportional to distance\n                // to vertex correspond to dimension\n                vertex_to_part[get(index_map, vertex)] = dimension;\n                break;\n            }\n    }\n    for (auto edge : boost::as_array(edges(graph))) {\n        if (vertex_to_part[get(index_map, source(edge, graph))] !=\n            vertex_to_part[get(index_map, target(edge, graph))])\n            cut_cost += get(weight_map, edge);\n    }\n    return cut_cost;\n}\n\n\ntemplate <typename Rand = std::default_random_engine,\n          typename Distribution = std::uniform_real_distribution<double>,\n          typename LP = lp::glp, typename Graph, typename OutputIterator,\n          typename VertexIndexMap, typename EdgeWeightMap,\n          typename VertexColorMap>\nauto multiway_cut_dispatch(const Graph &graph, OutputIterator result,\n                           Rand &&random_engine, int iterations,\n                           VertexIndexMap index_map, EdgeWeightMap weight_map,\n                           VertexColorMap color_map)\n    ->typename boost::property_traits<EdgeWeightMap>::value_type {\n    using CostType = detail::CostType<Graph>;\n    Distribution dis(0, 1);\n    int terminals = 0;\n    for (auto vertex : boost::as_array(vertices(graph))) {\n        assign_max(terminals, get(color_map, vertex));\n    }\n    detail::multiway_cut_lp<LP> multiway_cut_lp;\n    multiway_cut_lp.init(graph, terminals, index_map, weight_map, color_map);\n    multiway_cut_lp.m_lp.solve_simplex(lp::DUAL);\n    CostType cut_cost = std::numeric_limits<CostType>::max();\n    std::vector<int> best_solution;\n    std::vector<int> solution;\n    for (int i = 0; i < iterations; ++i) {\n        solution.clear();\n        int res = detail::make_cut(graph, terminals, index_map, weight_map, dis,\n                                   random_engine, multiway_cut_lp, solution);\n        if (res < cut_cost) {\n            swap(solution, best_solution);\n            cut_cost = res;\n        }\n    }\n    for (auto v : boost::as_array(vertices(graph))) {\n        *result = std::make_pair(v, best_solution[get(index_map, v)]);\n        ++result;\n    }\n    return cut_cost;\n}\n\ntemplate <typename Rand = std::default_random_engine,\n          typename Distribution = std::uniform_real_distribution<double>,\n          typename LP = lp::glp, typename Graph, typename OutputIterator,\n          typename VertexIndexMap, typename EdgeWeightMap,\n          typename VertexColorMap>\nauto multiway_cut_dispatch(const Graph &graph, OutputIterator result,\n                           Rand &&random_engine, boost::param_not_found,\n                           VertexIndexMap index_map, EdgeWeightMap weight_map,\n                           VertexColorMap color_map)\n    ->typename boost::property_traits<EdgeWeightMap>::value_type {\n    int vertices = num_vertices(graph);\n    const static int MIN_NUMBER_OF_REPEATS = 100;\n    auto number_of_repeats =\n        vertices * vertices +\n        MIN_NUMBER_OF_REPEATS; // This variable is not supported by any proof\n    return multiway_cut_dispatch(graph, result, random_engine,\n                                 number_of_repeats, index_map, weight_map,\n                                 color_map);\n}\n\n} //!detail\n\n/**\n * @brief this is solve multiway_cut problem\n * and return cut_cost\n * example:\n *  \\snippet multiway_cut_example.cpp  Multiway Cut Example\n * @param Graph graph\n * @param OutputIterator result pairs of vertex descriptor and number form (1,2,\n * ... ,k) id of part\n * @param random_engine\n * @param params\n * @tparam Graph\n * @tparam OutputIterator\n * @tparam Rand random engine\n * @tparam Distribution used to chose random radius\n * @tparam LP\n * @tparam P\n * @tparam T\n * @tparam R\n */\ntemplate <typename Rand = std::default_random_engine,\n          typename Distribution = std::uniform_real_distribution<double>,\n          typename LP = lp::glp, typename Graph, typename OutputIterator,\n          typename P, typename T, typename R>\nauto multiway_cut(const Graph &g, OutputIterator out,\n                  const boost::bgl_named_params<P, T, R> &params,\n                  Rand &&random_engine = std::default_random_engine(5426u))\n    ->typename boost::property_traits<puretype(\n          boost::choose_const_pmap(get_param(params, boost::edge_weight), g,\n                                   boost::edge_weight))>::value_type {\n    return detail::multiway_cut_dispatch(\n        g, out, random_engine, get_param(params, boost::iterations_t()),\n        boost::choose_const_pmap(get_param(params, boost::vertex_index), g,\n                                 boost::vertex_index),\n        boost::choose_const_pmap(get_param(params, boost::edge_weight), g,\n                                 boost::edge_weight),\n        boost::choose_const_pmap(get_param(params, boost::vertex_color), g,\n                                 boost::vertex_color));\n}\n\n/**\n * @brief this is solve multiway_cut problem\n * and return cut_cost\n * example:\n *  \\snippet multiway_cut_example.cpp  Multiway Cut Example\n *\n * example file is  multiway_cut_example.cpp\n * @param Graph graph\n * @param int repeats number of sets of radius\n * @param OutputIterator result pairs of vertex descriptor and number form (1,2,\n* ... ,k) id of part\n * @tparam Rand random engine\n * @tparam Distribution used to chose random radius\n * @tparam LP\n * @tparam Graph\n * @tparam OutputIterator\n */\ntemplate <typename Rand = std::default_random_engine,\n          typename Distribution = std::uniform_real_distribution<double>,\n          typename LP = lp::glp, typename Graph, class OutputIterator>\nauto multiway_cut(const Graph &graph, OutputIterator result,\n                  Rand random_engine = std::default_random_engine(5426u))\n    ->detail::CostType<Graph> {\n    return multiway_cut(graph, result, boost::no_named_parameters(),\n                        random_engine);\n}\n\n}      //!paal\n#endif // PAAL_MULTIWAY_CUT_HPP\n", "meta": {"hexsha": "005647f98672662cc675fb5fd5402176b8b3d234", "size": 11496, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/multiway_cut/multiway_cut.hpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/paal/multiway_cut/multiway_cut.hpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/paal/multiway_cut/multiway_cut.hpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 38.4481605351, "max_line_length": 80, "alphanum_fraction": 0.6197807933, "num_tokens": 2590, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.749087201911703, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.4008353846472576}}
{"text": "/**\n * \\file dcs/math/stats/distribution/map.hpp\n *\n * \\brief Markov Arrival Process (MAP).\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr/>\n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_MATH_STATS_DISTRIBUTION_MAP_HPP\n#define DCS_MATH_STATS_DISTRIBUTION_MAP_HPP\n\n\n#include <boost/numeric/ublas/expression_types.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/matrix_expression.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/traits.hpp>\n#include <boost/numeric/ublasx/operation/abs.hpp>\n#include <boost/numeric/ublasx/operation/cumsum.hpp>\n#include <boost/numeric/ublasx/operation/diag.hpp>\n#include <boost/numeric/ublasx/operation/inv.hpp>\n#include <boost/numeric/ublasx/operation/lu.hpp>\n#include <boost/numeric/ublasx/operation/max.hpp>\n#include <boost/numeric/ublasx/operation/num_columns.hpp>\n#include <boost/numeric/ublasx/operation/num_rows.hpp>\n#include <boost/numeric/ublasx/operation/sum.hpp>\n#include <boost/numeric/ublasx/operation/which.hpp>\n#include <cmath>\n#include <cstddef>\n#include <dcs/assert.hpp>\n#include <dcs/debug.hpp>\n#include <dcs/math/policies/policy.hpp>\n#include <dcs/math/stats/distribution/base_distribution.hpp>\n#include <dcs/math/stats/distribution/exponential.hpp>\n#include <dcs/math/stats/function/rand.hpp>\n#include <dcs/math/random/any_generator.hpp>\n#include <dcs/math/random/base_generator.hpp>\n#include <dcs/math/random/uniform_01_adaptor.hpp>\n//#include <dcs/math/random/uniform_int_adaptor.hpp>\n#include <functional>\n#include <iostream>\n#include <vector>\n#include <stdexcept>\n\n\nnamespace dcs { namespace math { namespace stats {\n\nnamespace detail { namespace /*<unnamed>*/ {\n\n/**\n * \\brief Equilibrium distribution of a continuous-time Markov chain (CTMC).\n * \\param Q Infinitesimal generator of the CTMC.\n * \\return The equilibrium distribution of the CTMC.\n *\n * Solve the following system:\n * \\f{align}\n * \\mathbf{\\pi}\\mathbf{Q}=\\mathbf{0} \\\\\n * \\mathbf{\\pi}\\mathbf{1}^T=1\n * \\f}\n * where:\n * - the first equation is the <em>global balance equation</em>,\n * - the * second one is the <em>normalization condition</em>,\n * - and \\f$\\mathbf{\\pi}\\f$ is the <em>steady state probabilities</em> vector\n *   (expressed as a row vector).\n * .\n *\n * \\note\n *  Actually, we solve the CTMC by means of the <em>direct method</em> (see\n *  [1,2,3] for possible issues and other existing methods).\n *  From the point of view of implementation, there are two main problems:\n *  -# Maths routing usually assumes that vectors are expressed as column\n *     vector.\n *     So, the global balance equation comes in the &quot;wrong&quot; form: the\n *     unknowns are given as a row vector not a column vector.\n *     This problem is resolved by transposing the equation, i.e.\n *     \\f[\n *      \\mathbf{Q}^T\\mathbf{\\pi}^T = \\mathbf{0}^T\n *     \\f]\n *     where the right hand side is now a column vector of zeros, rather than a\n *     row vector.\n *  -# The redundancy amongst the global balance equations.\n *     To solve this problem we need the additional information of the\n *     normalization condition.\n *     This problem is resolved by replacing one of the global balance equations\n *     by the normalization condition.\n *     In the transposed matrix this corresponds to replacing one row by a row\n *     of 1's.\n *     We usually choose the last row and denote the modified matrix Q_n^T .\n *     Similarly we change the constant terms vector, which was all zeros to be\n *     a column vector with 1 in the last row, and zeros everywhere else.\n *     We denote such a vector, \\f$e_n^T\\f$.\n *  .\n *\n * References:\n * -# W.J. Stewart.\n *    \"Introduction to the Numerical Solution of Markov Chains\",\n *    Princeton University Press, 1994.\n * -# W.J. Stewart.\n *    \"Performance Modeling and Markov Chains\",\n *    Formal Methods of Performance Evaluation, Springer, 2007.\n * -# W.J. Stewart.\n *    \"Probability, Markov Chains, Queues, and Simulation\",\n *    Princeton University Press, 2009.\n * .\n */\ntemplate <typename MatrixExprT>\n::boost::numeric::ublas::vector<\n\ttypename ::boost::numeric::ublas::matrix_traits<MatrixExprT>::value_type\n> ctmc_solve(::boost::numeric::ublas::matrix_expression<MatrixExprT> const& Q)\n{\n\tnamespace ublas = ::boost::numeric::ublas;\n\tnamespace ublasx = ::boost::numeric::ublasx;\n\n\ttypedef typename ublas::matrix_traits<MatrixExprT>::value_type value_type;\n\ttypedef typename ublas::matrix_traits<MatrixExprT>::size_type size_type;\n\ttypedef ublas::vector<size_type> size_vector_type;\n\ttypedef ublas::vector<value_type> vector_type;\n\n\tsize_type nr = ublasx::num_rows(Q);\n\t//size_type nc = ublasx::num_columns(Q);\n\n\tsize_vector_type z;\n\n\t// Is the CTMC irreducible?\n\n\tz = ublasx::which(\n\t\tublasx::sum<1>(\n\t\t\tublasx::abs(Q)\n\t\t),\n\t\t::std::bind2nd(\n\t\t\t::std::equal_to<value_type>(),\n\t\t\tvalue_type(0)\n\t\t)\n\t);\n\n\tsize_type nz;\n\tnz = ublasx::size(z);\n\n\tif (nz > 1)\n\t{\n\t\tDCS_DEBUG_TRACE(\"Warning: Q is a reducible infinitesimal generator.\");\n//\t\tb = ublas::zero_vector<value_type>(nr);\n\t}\n\telse if (nz == 0)\n\t{\n\t\tz.resize(1, false);\n\t\tz(0) = nr-1;\n\t\tnz = 1;\n\t}\n\n\t// Create the constant terms vecotr b=e_n^T such that Q_n^T\\pi^T=e_n^T\n\tvector_type b;\n\tb = ublas::zero_vector<value_type>(nr);\n\n\tublas::matrix<value_type> tmp_Q(Q);\n\n\t// normalization condition\n\tfor (size_type j = 0; j < nz; ++j)\n\t{\n\t\tsize_type k(z(j));\n\n\t\tb(k) = 1;\n\n\t\tfor (size_type i = 0; i < nr; ++i)\n\t\t{\n\t\t\ttmp_Q(i,k) = value_type(1);\n\t\t}\n\t}\n\n\tublasx::lu_solve_inplace(ublas::trans(tmp_Q), b);\n\n\treturn ublas::trans(b);\n}\n\n\n/**\n * \\brief Equilibrium distribution of a discrete-time Markov chain (DTMC).\n * \\param P Stochastic transition matrix of the DTMC.\n * \\return The equilibrium distribution of the DTMC.\n */\ntemplate <typename MatrixExprT>\n::boost::numeric::ublas::vector<\n\ttypename ::boost::numeric::ublas::matrix_traits<MatrixExprT>::value_type\n> dtmc_solve(::boost::numeric::ublas::matrix_expression<MatrixExprT> const& P)\n{\n\tnamespace ublas = ::boost::numeric::ublas;\n\tnamespace ublasx = ::boost::numeric::ublasx;\n\n\ttypedef MatrixExprT matrix_type;\n\ttypedef typename ublas::matrix_traits<matrix_type>::size_type size_type;\n\ttypedef typename ublas::matrix_traits<matrix_type>::value_type value_type;\n\n\tsize_type nr = ublasx::num_rows(P);\n\tsize_type nc = ublasx::num_columns(P);\n\n\tublas::identity_matrix<value_type> I(nr,nc);\n\n\treturn ctmc_solve(P-I);\n}\n\n\n/**\n * \\brief Embedded discrete-time process of the given MAP.\n *\n * \\param D0 The \\f$D_0\\f$ matrix of the MAP.\n * \\param D1 The \\f$D_1\\f$ matrix of the MAP.\n * \\return The probability transition matrix of the embedded process.\n *\n * Compute the stochastic transition matrix \\f$P\\f$ of the embedded phase\n * process at arrival instants.\n * Specifically, \\f$P_{ij} is the probability that the MAP restarts in phase\n * \\f$j\\f$ if the last absorption occurred in phase \\f$i\\f$.\n *\n * \\note If the MAP is feasible, then the probability transition matrix must be\n *  an irreducible stochastic matrix.\n *  In this case, the stationary distribution at arrival instants denoted by\n *  \\f$\\pi\\f$ is given by \\f$\\piP=\\pi$ and \\f$\\pie^T=1\\f$.\n *  After an event has been generated, the distribution of the MAP is given by\n *  \\f$\\pi\\f$.\n */\ntemplate <typename D0MatrixExprT, typename D1MatrixExprT>\n::boost::numeric::ublas::matrix<\n\ttypename ::boost::numeric::ublas::promote_traits<\n\t\ttypename ::boost::numeric::ublas::matrix_traits<D0MatrixExprT>::value_type,\n\t\ttypename ::boost::numeric::ublas::matrix_traits<D1MatrixExprT>::value_type\n\t>::promote_type\n> embedded_dtmc(::boost::numeric::ublas::matrix_expression<D0MatrixExprT> const& D0,\n\t\t\t\t::boost::numeric::ublas::matrix_expression<D1MatrixExprT> const& D1)\n{\n\n//\ttypedef typename ::boost::numeric::ublas::promote_traits<\n//\t\t\t\ttypename ::boost::numeric::ublas::matrix_traits<D0MatrixExprT>::value_type,\n//\t\t\t\ttypename ::boost::numeric::ublas::matrix_traits<D1MatrixExprT>::value_type\n//\t\t\t>::promote_type value_type;\n//\ttypedef ::boost::numeric::ublas::matrix<value_type> matrix_type;\n\n\t// Compute P=(-D0)^{-1})*D1\n\treturn ::boost::numeric::ublas::prod(\n\t\t\t\t::boost::numeric::ublasx::inv(-D0),\n\t\t\t\tD1\n\t\t\t);\n}\n\n\n/// Compute the equilibrium distribution of the embedded discrete-time process.\ntemplate <typename D0MatrixExprT, typename D1MatrixExprT>\n::boost::numeric::ublas::vector<\n\ttypename ::boost::numeric::ublas::promote_traits<\n\t\ttypename ::boost::numeric::ublas::matrix_traits<D0MatrixExprT>::value_type,\n\t\ttypename ::boost::numeric::ublas::matrix_traits<D1MatrixExprT>::value_type\n\t>::promote_type\n> equilibrium_distribution(::boost::numeric::ublas::matrix_expression<D0MatrixExprT> const& D0,\n\t\t\t\t\t\t   ::boost::numeric::ublas::matrix_expression<D1MatrixExprT> const& D1)\n{\n\treturn dtmc_solve(embedded_dtmc(D0, D1));\n}\n\n\ntemplate <typename ValueT, typename URNG>\ninline\nValueT generate_probability(URNG& rng)\n{\n\t::dcs::math::random::uniform_01_adaptor<URNG&,ValueT> u01_rng(rng);\n\n\treturn u01_rng();\n}\n\n\ntemplate <typename VectorExprT, typename URNG>\ntypename ::boost::numeric::ublas::vector_traits<VectorExprT>::size_type generate_initial_state(::boost::numeric::ublas::vector_expression<VectorExprT> const& pi, URNG& rng)\n{\n\tnamespace ublas = ::boost::numeric::ublas;\n\tnamespace ublasx = ::boost::numeric::ublasx;\n\n\ttypedef typename ublas::vector_traits<VectorExprT>::size_type size_type;\n\ttypedef typename ublas::vector_traits<VectorExprT>::value_type value_type;\n\n\tsize_type n = ublasx::size(pi);\n\n\tvalue_type p = generate_probability<value_type>(rng);\n\n\tsize_type ret(n); //default to last state\n\n\t//NOTE: states start from 1!\n\n\tublas::vector<value_type> cdf = ublasx::cumsum(pi);\n\tfor (size_type i = 0; i < n; ++i)\n\t{\n\t\tif (p <= cdf(i))\n\t\t{\n\t\t\tret = i+1;\n\t\t\tbreak;\n\t\t}\n\t}\n// Alternative (but possibly more time-consuming)\n//\tret = ublasx::min(\n//\t\t\tublasx::which(\n//\t\t\t\tublasx::cumsum(pi),\n//\t\t\t\t::std::bind1st(\n//\t\t\t\t\t::std::less_equal<value_type>(),\n//\t\t\t\t\tp\n//\t\t\t\t)\n//\t\t\t)\n//\t\t);\n\n\treturn ret;\n}\n\n\ntemplate <typename VectorExprT, typename URNG>\ntypename ::boost::numeric::ublas::vector_traits<VectorExprT>::size_type generate_next_state(::boost::numeric::ublas::vector_expression<VectorExprT> const& cdf, URNG& rng)\n{\n\tnamespace ublas = ::boost::numeric::ublas;\n\tnamespace ublasx = ::boost::numeric::ublasx;\n\n\ttypedef typename ublas::vector_traits<VectorExprT>::size_type size_type;\n\ttypedef typename ublas::vector_traits<VectorExprT>::value_type value_type;\n\n\tvalue_type p = generate_probability<value_type>(rng);\n\n\tublas::vector<size_type> ix;\n\n\tix = ublasx::which(\n\t\t\tcdf,\n\t\t\t::std::bind2nd(::std::greater_equal<value_type>(), p)\n\t\t);\n\n\tif (ix.size() == 0)\n\t{\n\t\t//TODO\n\t\tthrow ::std::runtime_error(\"Unexpected failure\");\n\t}\n\n\treturn ix(0);\n}\n\n\ntemplate <typename ValueT, typename URNG>\nValueT generate_sojourn_time(ValueT rate, URNG& rng)\n{\n\t::dcs::math::stats::exponential_distribution<ValueT> exp(rate);\n\n\treturn ::dcs::math::stats::rand(exp, rng);\n}\n\n}} // Namespace detail::<unnamed>\n\n\ntemplate <\n\ttypename RealT = double,\n\ttypename PolicyT = ::dcs::math::policies::policy<>\n>\nclass map_distribution//: public base_distribution<RealT>\n{\n//\tprivate: typedef base_distribution<RealT> base_type;\n//\tpublic: typedef typename base_type::value_type value_type;\n//\tpublic: typedef typename base_type::support_type support_type;\n\tpublic: typedef RealT value_type;\n\tpublic: typedef value_type support_type;\n\tpublic: typedef ::boost::numeric::ublas::matrix<support_type> matrix_type;\n\tpublic: typedef ::std::size_t size_type;\n\tprivate: typedef ::boost::numeric::ublas::vector<support_type> value_vector_type;\n\tprivate: typedef ::boost::numeric::ublas::vector<size_type> index_vector_type;\n\n\n\tpublic: template <typename D0MatrixExprT, typename D1MatrixExprT>\n\t\tmap_distribution(::boost::numeric::ublas::matrix_expression<D0MatrixExprT> const& D0,\n\t\t\t\t\t\t ::boost::numeric::ublas::matrix_expression<D1MatrixExprT> const& D1)\n\t: //base_type(),\n\t  D0_(D0),\n\t  D1_(D1)\n\t{\n\t\t// pre: num_rows(D0) == num_rows(D1)\n\t\tDCS_ASSERT(\n\t\t\t::boost::numeric::ublasx::num_rows(D0) == ::boost::numeric::ublasx::num_rows(D1),\n\t\t\tthrow ::std::invalid_argument(\"[dcs::math::stats::map_distribution::ctor] Matrices D0 and D1 have different number of rows.\")\n\t\t);\n\t\t// pre: num_cols(D0) == num_cols(D1)\n\t\tDCS_ASSERT(\n\t\t\t::boost::numeric::ublasx::num_columns(D0) == ::boost::numeric::ublasx::num_columns(D1),\n\t\t\tthrow ::std::invalid_argument(\"[dcs::math::stats::map_distribution::ctor] Matrices D0 and D1 have different number of columns.\")\n\t\t);\n\t}\n\n\n\t// Compiler-generated copy-constructor, copy-assignment, and destructor\n\t// are fine.\n\n\n\tpublic: matrix_type const& D0() const\n\t{\n\t\treturn D0_;\n\t}\n\n\n\tpublic: matrix_type const& D1() const\n\t{\n\t\treturn D1_;\n\t}\n\n\n/*\n\tprivate: value_type do_rand(::dcs::math::random::any_generator<value_type>& rng) const\n\t{\n\t\treturn rand_sample(rng);\n\t}\n\n\tprivate: value_type do_rand(::dcs::math::random::base_generator<value_type>& rng) const\n\t{\n\t\treturn rand_sample(rng);\n\t}\n*/\n\n\tpublic: template <typename URNG>\n\t\tvalue_type rand(URNG& rng) const\n\t{\n\t\t::std::vector<value_type> samples;\n\t\tsamples = rand(rng, 1);\n\n\t\tif (samples.size() == 0)\n\t\t{\n\t\t\tthrow ::std::runtime_error(\"[dcs::math::stats::map_distribution::rand] Unexpected failure.\");\n\t\t}\n\n\t\treturn samples[0];\n\t}\n\n\n\t/**\n\t * The following algorithm is an adaptation of the one found in the MAP-QN\n\t * toolbox (by G. Casale et al, http://www.cs.wm.edu/MAPQN/).\n\t */\n\tpublic: template <typename URNG>\n\t\t::std::vector<value_type> rand(URNG& rng, size_type n) const\n\t{\n\t\tnamespace ublas = ::boost::numeric::ublas;\n\t\tnamespace ublasx = ::boost::numeric::ublasx;\n\n\t\tconst size_type max_path_len0(20); // initial max path length\n\t\tconst size_type path_len_incr(5); // increment in the max path length\n\n\t\tsize_type ns(ublasx::num_rows(D0_)); // # stages\n\t\tsize_type ns2(ns << 1); // 2*ns\n\n\t\tvalue_vector_type pi;\n\n\t\tpi = detail::equilibrium_distribution(D0_,  D1_);\n\n\t\tsize_type s0; // initial stage\n\n\t\t// Randomly generate the initial stage.\n\t\ts0 = detail::generate_initial_state(pi, rng);\n\n\t\tmatrix_type P(ns,ns2,0);\n\n\t\tfor (size_type b=0; b < 2; ++b)\n\t\t{\n\t\t\tfor (size_type i = 0; i < ns; ++i)\n\t\t\t{\n\t\t\t\tfor (size_type j = 0; j < ns; ++j)\n\t\t\t\t{\n\t\t\t\t\tP(i,b*ns+j) = (b==0 ? D0_(i,j) : D1_(i,j)) / ::std::abs(D0_(i,i));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (size_type i=0; i < ns; ++i)\n\t\t{\n\t\t\tP(i,i) = 0;\n\t\t}\n\n\t\t// Create CDF\n\t\tmatrix_type C(ns,ns2);\n\t\tfor (size_type i = 0; i < ns; ++i)\n\t\t{\n\t\t\tublas::row(C, i) = ublasx::cumsum(ublas::row(P, i));\n\t\t}\n\t\tC = ublasx::abs(C);\n\n\t\tsize_type src_s(s0);\n\t\tmatrix_type V(ublas::zero_matrix<value_type>(n, max_path_len0));\n\t\tsize_type max_path_len(max_path_len0);\n\t\tfor (size_type i = 0; i < n; ++i)\n\t\t{\n\t\t\tbool arrival(false);\n\t\t\tsize_type last(1);\n\t\t\tV(i,0) = src_s;\n\n\t\t\twhile (!arrival)\n\t\t\t{\n\t\t\t\tsize_type dst_s;\n\t\t\t\tdst_s = detail::generate_next_state(\n\t\t\t\t\t\t\tublas::row(C, src_s-1),\n\t\t\t\t\t\t\trng\n\t\t\t\t\t);\n\t\t\t\t++dst_s; // make sure that stage id starts from 1\n\t\t\t\tif (dst_s > ns)\n\t\t\t\t{\n\t\t\t\t\tarrival = true;\n\t\t\t\t\tdst_s -= ns;\n\t\t\t\t\tsrc_s = dst_s;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tV(i,last) = dst_s;\n\t\t\t\t\tsrc_s = dst_s;\n\t\t\t\t\t++last;\n\t\t\t\t}\n\t\t\t\tif (last >= max_path_len)\n\t\t\t\t{\n\t\t\t\t\tmax_path_len += path_len_incr;\n\t\t\t\t\tV.resize(n, max_path_len, true);\n\t\t\t\t\tfor (size_type c = last; c < max_path_len; ++c)\n\t\t\t\t\t{\n\t\t\t\t\t\tublas::column(V, c) = ublas::zero_vector<size_type>(n);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n//XXX: not used\n//\t\t// Create the vector of absorbing stages (for each sample)\n//\t\tvalue_vector_type L(n);\n//\n//\t\tfor (size_type i = 0; i < n; ++i)\n//\t\t{\n//\t\t\tsize_type ix;\n//\n//\t\t\tix = ublasx::max(\n//\t\t\t\t\tublasx::which(\n//\t\t\t\t\t\tublas::row(V, i)\n//\t\t\t\t\t)\n//\t\t\t\t);\n//\t\t\tL(i) = V(i,ix);\n//\t\t}\n\n//XXX: not used\n//\t\t// Create the vector of initial stages (for each sample)\n//\t\tvalue_vector_type F;\n//\n//\t\tF = ublas::column(V, 1);\n\n\t\tvalue_vector_type hold_rates(-ublasx::diag(D0_));\n\n\t\tsize_type nv = ublasx::num_columns(V);\n\t\tmatrix_type H(V); // matrix of times to absorptions\n\t\tfor (size_type i = 0; i < ns; ++i)\n\t\t{\n\t\t\tsize_type s = i+1;\n\t\t\tfor (size_type j = 0; j < n; ++j)\n\t\t\t{\n\t\t\t\tfor (size_type k = 0; k < nv; ++k)\n\t\t\t\t{\n\t\t\t\t\tif (V(j,k) == s)\n\t\t\t\t\t{\n\t\t\t\t\t\tH(j,k) = hold_rates(i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t::std::vector<value_type> samples(n, 0);\n\n\t\tfor (size_type i = 0; i < nv; ++i)\n\t\t{\n\t\t\tfor (size_type k = 0; k < n; ++k)\n\t\t\t{\n\t\t\t\tif (H(k,i) > 0)\n\t\t\t\t{\n\t\t\t\t\tsamples[k] += detail::generate_sojourn_time<value_type>(H(k,i), rng);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn samples;\n\t}\n\n\n\tprivate: matrix_type D0_;\n\tprivate: matrix_type D1_;\n};\n\n\ntemplate <\n\ttypename CharT,\n\ttypename CharTraitsT,\n\ttypename RealT,\n\ttypename PolicyT\n>\n::std::basic_ostream<CharT,CharTraitsT>& operator<<(::std::basic_ostream<CharT,CharTraitsT>& os, map_distribution<RealT,PolicyT> const& dist)\n{\n\treturn os << \"MAP(\"\n\t\t\t  << \"D0=\" <<  dist.D0()\n\t\t\t  << \",D1=\" <<  dist.D1()\n\t\t\t  << \")\";\n}\n\n}}} // Namespace dcs:math::stats\n\n\n#endif // DCS_MATH_STATS_DISTRIBUTION_MAP_HPP\n", "meta": {"hexsha": "446da4ea10a19caf1435250ce95cb6d64537808a", "size": 17507, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/stats/distribution/map.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/math/stats/distribution/map.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/math/stats/distribution/map.hpp", "max_forks_repo_name": "sguazt/dcsxx-commons", "max_forks_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2827140549, "max_line_length": 172, "alphanum_fraction": 0.6865825099, "num_tokens": 5189, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7279754371026367, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.40082863759744786}}
{"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n/*\n * @file eqtesting.cpp\n * @brief Useful fucntions for equality testing...\n */\n#include <NTL/lzz_pXFactoring.h>\nNTL_CLIENT\n#include \"FHE.h\"\n#include \"timing.h\"\n#include \"EncryptedArray.h\"\n\n#include <cassert>\n#include <cstdio>\n\n// Map all non-zero slots to 1, leaving zero slots as zero.\n// Assumes that r=1, and that all the slot contain elements from GF(p^d).\n//\n// We compute x^{p^d-1} = x^{(1+p+...+p^{d-1})*(p-1)} by setting y=x^{p-1}\n// and then outputting y * y^p * ... * y^{p^{d-1}}, with exponentiation to\n// powers of p done via Frobenius.\nvoid mapTo01(const EncryptedArray& ea, Ctxt& ctxt)\n{\n  long p = ctxt.getPtxtSpace();\n  if (p != ctxt.getContext().zMStar.getP()) // ptxt space is p^r for r>1\n    std::logic_error(\"mapTo01 not implemented for r>1\");\n\n  if (p>2)\n    ctxt.power(p-1); // set y = x^{p-1}\n\n  long d = ea.getDegree();\n  if (d>1) { // compute the product of the d automorphisms\n    std::vector<Ctxt> v(d, ctxt);\n    for (long i=1; i<d; i++)\n      v[i].frobeniusAutomorph(i);\n    totalProduct(ctxt, v);\n  }\n}\n\n\n// computes ctxt^{2^d-1} using a method that takes\n// O(log d) automorphisms and multiplications\nvoid fastPower(Ctxt& ctxt, long d) \n{\n  assert(ctxt.getPtxtSpace()==2);\n  if (d <= 1) return;\n\n  Ctxt orig = ctxt;\n\n  long k = NumBits(d);\n  long e = 1;\n\n  for (long i = k-2; i >= 0; i--) {\n    Ctxt tmp1 = ctxt;\n    tmp1.smartAutomorph(1L << e);\n    ctxt.multiplyBy(tmp1);\n    e = 2*e;\n\n    if (bit(d, i)) {\n      ctxt.smartAutomorph(2);\n      ctxt.multiplyBy(orig);\n      e += 1;\n    }\n  }\n}\n\n// ===> This function only works for p=2, r=1 <===\n// Test if prefixes of bits in slots are all zero: Set slot j of res[i] to 0\n// if bits 0..i of j'th slot in ctxt are all zero, else it is set to 1\n// It is assumed that res and the res[i]'s are initialized by the caller.\n// Complexity: O(d + n log d) smart automorphisms\n//             O(n d) \nvoid incrementalZeroTest(Ctxt* res[], const EncryptedArray& ea,\n\t\t\t const Ctxt& ctxt, long n)\n{\n  FHE_TIMER_START;\n  long nslots = ea.size();\n  long d = ea.getDegree();\n\n  // compute linearized polynomial coefficients\n\n  vector< vector<ZZX> > Coeff;\n  Coeff.resize(n);\n\n  for (long i = 0; i < n; i++) {\n    // coeffients for mask on bits 0..i\n    // L[j] = X^j for j = 0..i, L[j] = 0 for j = i+1..d-1\n\n    vector<ZZX> L;\n    L.resize(d);\n\n    for (long j = 0; j <= i; j++) \n      SetCoeff(L[j], j);\n\n    vector<ZZX> C;\n\n    ea.buildLinPolyCoeffs(C, L);\n\n    Coeff[i].resize(d);\n    for (long j = 0; j < d; j++) {\n      // Coeff[i][j] = to the encoding that has C[j] in all slots\n      // FIXME: maybe encrtpted array should have this functionality\n      //        built in\n      vector<ZZX> T;\n      T.resize(nslots);\n      for (long s = 0; s < nslots; s++) T[s] = C[j];\n      ea.encode(Coeff[i][j], T);\n    }\n  }\n\n  vector<Ctxt> Conj(d, ctxt);\n  // initialize Cong[j] to ctxt^{2^j}\n  for (long j = 0; j < d; j++) {\n    Conj[j].smartAutomorph(1L << j);\n  }\n\n  for (long i = 0; i < n; i++) {\n    res[i]->clear();\n    for (long j = 0; j < d; j++) {\n      Ctxt tmp = Conj[j];\n      tmp.multByConstant(Coeff[i][j]);\n      *res[i] += tmp;\n    }\n\n    // *res[i] now has 0..i in each slot\n    // next, we raise to the power 2^d-1\n\n    fastPower(*res[i], d);\n  }\n  FHE_TIMER_STOP;\n}\n\n\n#ifdef DEBUG_TEST\n/************************** debugging code below *********************/\nvoid printBits(const vector<ZZX>& v, long n) \n{\n  long len = v.size();\n  if (n>50 || len>32) return;\n  for (long i = 0; i < len; i++) {\n    for (long j = n-1; j >= 0; j--)\n      cout << coeff(v[i], j);\n    cout << \" \";\n  }\n  cout << \"\\n\";\n}\n\n\nvoid  TestIt(long c, long k, long w, long L, long m, long n)\n{\n  FHEcontext context(m, 2, 1); // p = 2, r = 1\n  long d = context.zMStar.getOrdP(); \n\n  buildModChain(context, L, c);\n\n  context.zMStar.printout();\n  cerr << endl;\n#ifdef DEBUG\n  cerr << context << endl;\n#endif\n\n  FHESecKey secretKey(context);\n  const FHEPubKey& publicKey = secretKey;\n  secretKey.GenSecKey(w); // A Hamming-weight-w secret key\n\n\n  ZZX G;\n\n  G = makeIrredPoly(2, d); \n  // G = context.alMod.getFactorsOverZZ()[0];\n\n  cerr << \"generating key-switching matrices... \";\n  addFrbMatrices(secretKey);\n  addSome1DMatrices(secretKey);\n  cerr << \"done\\n\";\n\n  cerr << \"computing masks and tables for rotation...\";\n  EncryptedArray ea(context, G);\n  cerr << \"done\\n\";\n\n  long nslots = ea.size();\n\n  if (n <= 0 || n > d) n = d;\n\n  vector<ZZX> v;\n  v.resize(nslots);\n  for (long i = 0; i < nslots; i++) {\n    GF2X f;\n    random(f, n);\n    conv(v[i], f);\n  }\n\n  printBits(v, n);\n\n  Ctxt ctxt(publicKey);\n  ea.encrypt(ctxt, publicKey, v);\n  // ctxt encrypts a vector where each slots is a random\n  // polynomial of degree < n\n\n  Ctxt* res[n];\n  for (long j = 0; j < n; j++) res[j] = new Ctxt(publicKey); // allocate\n\n  resetAllTimers();\n\n  incrementalZeroTest(res, ea, ctxt, n);\n\n  for (long j = 0; j < n; j++) {\n    vector<ZZX> v1;\n    ea.decrypt(*res[j], secretKey, v1); \n    printBits(v1, n);\n  }\n\n  for (long j = 0; j < n; j++) delete res[j]; // cleanup\n}\n\nvoid usage(char *prog) \n{\n  cerr << \"Usage: \"<<prog<<\" [ optional parameters ]...\\n\";\n  cerr << \"  optional parameters have the form 'attr1=val1 attr2=val2 ...'\\n\";\n  cerr << \"  e.g, 'R=4 L=9 k=80'\\n\\n\";\n  cerr << \"  c is number of columns in the key-switching matrices [default=2]\\n\";\n  cerr << \"  k is the security parameter [default=80]\\n\";\n  cerr << \"  L is the # of primes in the modulus chain [default=20]\\n\";\n  cerr << \"  m is a specific modulus\\n\";\n  cerr << \"  n is the number of masks (defaults to all)\\n\";\n  exit(0);\n}\n\nint main(int argc, char *argv[]) \n{\n  argmap_t argmap;\n  argmap[\"c\"] = \"2\";\n  argmap[\"k\"] = \"80\";\n  argmap[\"L\"] = \"20\";\n  argmap[\"m\"] = \"0\";\n  argmap[\"n\"] = \"0\";\n\n  // get parameters from the command line\n  if (!parseArgs(argc, argv, argmap)) usage(argv[0]);\n\n  long c = atoi(argmap[\"c\"]);\n  long k = atoi(argmap[\"k\"]);\n  long L = atoi(argmap[\"L\"]);\n  long chosen_m = atoi(argmap[\"m\"]);\n  long n = atoi(argmap[\"n\"]);\n\n  long w = 64; // Hamming weight of secret key\n  //  long L = z*R; // number of levels\n\n  long m = FindM(k, L, c, 2, 1, 0, chosen_m, true);\n\n  setTimersOn();\n  TestIt(c, k, w, L, m, n);\n\n  cerr << endl;\n  printAllTimers();\n  cerr << endl;\n\n}\n// call to get our running test case:\n// eqtesting_x m=20485 \n// eqtesting_x m=105 for quick testing\n\n#endif // #ifdef DEBUG_TEST\n", "meta": {"hexsha": "1e05330cb0d24036a6fd290ff76d21b7ea3359dd", "size": 6966, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eqtesting.cpp", "max_stars_repo_name": "bryongloden/HElib", "max_stars_repo_head_hexsha": "c13dff5ce752fb9fcec9ef81a8db1c0f146fff39", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-03-29T17:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-28T06:46:20.000Z", "max_issues_repo_path": "src/eqtesting.cpp", "max_issues_repo_name": "bryongloden/HElib", "max_issues_repo_head_hexsha": "c13dff5ce752fb9fcec9ef81a8db1c0f146fff39", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-10-17T08:04:01.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-28T06:36:40.000Z", "max_forks_repo_path": "src/eqtesting.cpp", "max_forks_repo_name": "bryongloden/HElib", "max_forks_repo_head_hexsha": "c13dff5ce752fb9fcec9ef81a8db1c0f146fff39", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-10-16T09:14:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-10T07:24:51.000Z", "avg_line_length": 25.4233576642, "max_line_length": 81, "alphanum_fraction": 0.5937410278, "num_tokens": 2264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.4006404752130582}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n//  Copyright 2014 Anton Bikineev\r\n//  Copyright 2014 Christopher Kormanyos\r\n//  Copyright 2014 John Maddock\r\n//  Copyright 2014 Paul Bristow\r\n//  Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_HYPERGEOMETRIC_0F1_HPP\r\n#define BOOST_MATH_HYPERGEOMETRIC_0F1_HPP\r\n\r\n#include <boost/math/policies/policy.hpp>\r\n#include <boost/math/policies/error_handling.hpp>\r\n#include <boost/math/special_functions/detail/hypergeometric_series.hpp>\r\n#include <boost/math/special_functions/detail/hypergeometric_0F1_bessel.hpp>\r\n\r\nnamespace boost { namespace math { namespace detail {\r\n\r\n\r\n   template <class T>\r\n   struct hypergeometric_0F1_cf\r\n   {\r\n      //\r\n      // We start this continued fraction at b on index -1\r\n      // and treat the -1 and 0 cases as special cases.\r\n      // We do this to avoid adding the continued fraction result\r\n      // to 1 so that we can accurately evaluate for small results\r\n      // as well as large ones.  See http://functions.wolfram.com/07.17.10.0002.01\r\n      //\r\n      T b, z;\r\n      int k;\r\n      hypergeometric_0F1_cf(T b_, T z_) : b(b_), z(z_), k(-2) {}\r\n      typedef std::pair<T, T> result_type;\r\n\r\n      result_type operator()()\r\n      {\r\n         ++k;\r\n         if (k <= 0)\r\n            return std::make_pair(z / b, 1);\r\n         return std::make_pair(-z / ((k + 1) * (b + k)), 1 + z / ((k + 1) * (b + k)));\r\n      }\r\n   };\r\n\r\n   template <class T, class Policy>\r\n   T hypergeometric_0F1_cf_imp(T b, T z, const Policy& pol, const char* function)\r\n   {\r\n      hypergeometric_0F1_cf<T> evaluator(b, z);\r\n      boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();\r\n      T cf = tools::continued_fraction_b(evaluator, policies::get_epsilon<T, Policy>(), max_iter);\r\n      policies::check_series_iterations<T>(function, max_iter, pol);\r\n      return cf;\r\n   }\r\n\r\n\r\n   template <class T, class Policy>\r\n   inline T hypergeometric_0F1_imp(const T& b, const T& z, const Policy& pol)\r\n   {\r\n      const char* function = \"boost::math::hypergeometric_0f1<%1%,%1%>(%1%, %1%)\";\r\n      BOOST_MATH_STD_USING\r\n\r\n         // some special cases\r\n         if (z == 0)\r\n            return T(1);\r\n\r\n      if ((b <= 0) && (b == floor(b)))\r\n         return policies::raise_pole_error<T>(\r\n            function,\r\n            \"Evaluation of 0f1 with nonpositive integer b = %1%.\", b, pol);\r\n\r\n      if (z < -5 && b > -5)\r\n      {\r\n         // Series is alternating and divergent, need to do something else here,\r\n         // Bessel function relation is much more accurate, unless |b| is similarly\r\n         // large to |z|, otherwise the CF formula suffers from cancellation when\r\n         // the result would be very small.\r\n         if (fabs(z / b) > 4)\r\n            return hypergeometric_0F1_bessel(b, z, pol);\r\n         return hypergeometric_0F1_cf_imp(b, z, pol, function);\r\n      }\r\n      // evaluation through Taylor series looks\r\n      // more precisious than Bessel relation:\r\n      // detail::hypergeometric_0f1_bessel(b, z, pol);\r\n      return detail::hypergeometric_0F1_generic_series(b, z, pol);\r\n   }\r\n\r\n} // namespace detail\r\n\r\ntemplate <class T1, class T2, class Policy>\r\ninline typename tools::promote_args<T1, T2>::type hypergeometric_0F1(T1 b, T2 z, const Policy& /* pol */)\r\n{\r\n   BOOST_FPU_EXCEPTION_GUARD\r\n      typedef typename tools::promote_args<T1, T2>::type result_type;\r\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\r\n   typedef typename policies::normalise<\r\n      Policy,\r\n      policies::promote_float<false>,\r\n      policies::promote_double<false>,\r\n      policies::discrete_quantile<>,\r\n      policies::assert_undefined<> >::type forwarding_policy;\r\n   return policies::checked_narrowing_cast<result_type, Policy>(\r\n      detail::hypergeometric_0F1_imp<value_type>(\r\n         static_cast<value_type>(b),\r\n         static_cast<value_type>(z),\r\n         forwarding_policy()),\r\n      \"boost::math::hypergeometric_0F1<%1%>(%1%,%1%)\");\r\n}\r\n\r\ntemplate <class T1, class T2>\r\ninline typename tools::promote_args<T1, T2>::type hypergeometric_0F1(T1 b, T2 z)\r\n{\r\n   return hypergeometric_0F1(b, z, policies::policy<>());\r\n}\r\n\r\n\r\n} } // namespace boost::math\r\n\r\n#endif // BOOST_MATH_HYPERGEOMETRIC_HPP\r\n", "meta": {"hexsha": "14a9b5563627279bc45be09366de115337f29132", "size": 4401, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/special_functions/hypergeometric_0F1.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/math/special_functions/hypergeometric_0F1.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/math/special_functions/hypergeometric_0F1.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T06:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:55:07.000Z", "avg_line_length": 36.9831932773, "max_line_length": 106, "alphanum_fraction": 0.628039082, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.40055508679400764}}
{"text": "/*  \n * Copyright (c) 2009 Carnegie Mellon University. \n *     All rights reserved.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n *\n */\n\n\n/**\n * This implements the classical \"k-means\" clustering algorithm.\n *\n * It takes as input file a series of lines where each line is a comma separated\n * or space separated list of values representing a vector. For instance:\n *\n * \\verbatim\n * 1.1, 1.5, 0.9\n * 0.3, 0.4, -1.1\n * ...\n * \\endverbatim\n *\n * It constructs a graph with a single vertex for each data point and simply\n * uses the \"Map-Reduce\" scheme to perform a k-means clustering of all\n * the datapoints.\n */\n\n\n#include <boost/config/warning_disable.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/phoenix_stl.hpp>\n#include <boost/tokenizer.hpp>\n\n#include <limits>\n#include <vector>\n#include <map>\n#include <iostream>\n#include <stdlib.h>\n\n#include <graphlab.hpp>\n\n\nsize_t NUM_CLUSTERS = 0;\nbool IS_SPARSE = false;\n\nstruct cluster {\n  cluster(): count(0), changed(false) { }\n  std::vector<double> center;\n  std::map<size_t, double> center_sparse;\n  size_t count;\n  bool changed;\n\n  void save(graphlab::oarchive& oarc) const {\n    oarc << center << count << changed << center_sparse;\n  }\n\n  void load(graphlab::iarchive& iarc) {\n    iarc >> center >> count >> changed >> center_sparse;\n  }\n};\n\nstd::vector<cluster> CLUSTERS;\n\n// the current cluster to initialize\nsize_t KMEANS_INITIALIZATION;\n\nstruct vertex_data{\n  std::vector<double> point;\n  std::map<size_t, double> point_sparse;\n  size_t best_cluster;\n  double best_distance;\n  bool changed;\n\n  void save(graphlab::oarchive& oarc) const {\n    oarc << point << best_cluster << best_distance << changed << point_sparse;\n  }\n  void load(graphlab::iarchive& iarc) {\n    iarc >> point >> best_cluster >> best_distance >> changed >> point_sparse;\n  }\n};\n\n//use edges when edge weight file is given\nstruct edge_data {\n  double weight;\n\n  edge_data() :\n      weight(0.0) {\n  }\n  explicit edge_data(double w) :\n      weight(w) {\n  }\n\n  void save(graphlab::oarchive& oarc) const {\n    oarc << weight;\n  }\n  void load(graphlab::iarchive& iarc) {\n    iarc >> weight;\n  }\n};\n\n// helper function to compute distance between points\ndouble sqr_distance(const std::vector<double>& a,\n                    const std::vector<double>& b) {\n  ASSERT_EQ(a.size(), b.size());\n  double total = 0;\n  for (size_t i = 0;i < a.size(); ++i) {\n    double d = a[i] - b[i];\n    total += d * d;\n  }\n  return total;\n}\n\ndouble sqr_distance(const std::map<size_t, double>& a,\n                    const std::map<size_t, double>& b) {\n  double total = 0.0;\n  for(std::map<size_t, double>::const_iterator iter = a.begin();\n      iter != a.end(); ++iter){\n    size_t id = (*iter).first;\n    double val = (*iter).second;\n    if(b.find(id) != b.end()){\n      double d = val - b.at(id);\n      total += d*d;\n    }else{\n      total += val * val;\n    }\n  }\n  for(std::map<size_t, double>::const_iterator iter = b.begin();\n      iter != b.end(); ++iter){\n    double val = (*iter).second;\n    if(a.find((*iter).first) == a.end()){\n      total += val * val;\n    }\n  }\n\n  return total;\n\n////   cosine distance is better for sparse datapoints?\n//    double ip = 0.0;\n//    double lenA = 0.0;\n//    double lenB = 0.0;\n//    for(std::map<size_t, double>::const_iterator iter = a.begin();\n//        iter != a.end(); ++iter){\n//      size_t id = (*iter).first;\n//      double val = (*iter).second;\n//      if(b.find(id) != b.end()){\n//        ip += val * b.at(id);\n//      }\n//      lenA += val*val;\n//    }\n//\n//    if(ip == 0.0 || lenA == 0.0)\n//      return 1.0;\n//\n//    for(std::map<size_t, double>::const_iterator iter = b.begin();\n//        iter != b.end(); ++iter){\n//      double val = (*iter).second;\n//      lenB += val * val;\n//    }\n//\n//    if(lenB == 1.0)\n//      return 1.0;\n//\n//    return 1.0 - ip/(sqrt(lenA)*sqrt(lenB));\n\n}\n\n\n// helper function to add two vectors\nstd::vector<double>& plus_equal_vector(std::vector<double>& a,\n                                       const std::vector<double>& b) {\n  ASSERT_EQ(a.size(), b.size());\n  for (size_t i = 0;i < a.size(); ++i) {\n    a[i] += b[i];\n  }\n  return a;\n}\n\n// helper function to add two vectors\nstd::map<size_t, double>& plus_equal_vector(std::map<size_t, double>& a,\n                                       const std::map<size_t, double>& b) {\n  for(std::map<size_t, double>::const_iterator iter = b.begin();\n    iter != b.end(); ++iter){\n    size_t id = (*iter).first;\n    double val = (*iter).second;\n    if(a.find(id) != a.end()){\n      a[id] += b.at(id);\n    }else{\n      a.insert(std::make_pair(id, val));\n    }\n  }\n  return a;\n}\n\n// helper function to scale a vector vectors\nstd::vector<double>& scale_vector(std::vector<double>& a, double d) {\n  for (size_t i = 0;i < a.size(); ++i) {\n    a[i] *= d;\n  }\n  return a;\n}\n\n// helper function to scale a vector vectors\nstd::map<size_t, double>& scale_vector(std::map<size_t, double>& a, double d) {\n  for(std::map<size_t, double>::iterator iter = a.begin();\n    iter != a.end(); ++iter){\n  size_t id = (*iter).first;\n  double val = (*iter).second;\n  a[id] = val*d;\n//    (*iter).second *= d;\n  }\n  return a;\n}\n\n\ntypedef graphlab::distributed_graph<vertex_data, edge_data> graph_type;\n\ngraphlab::atomic<graphlab::vertex_id_type> NEXT_VID;\n\n// Read a line from a file and creates a vertex\nbool vertex_loader(graph_type& graph, const std::string& fname,\n                   const std::string& line) {\n  if (line.empty()) return true;\n  namespace qi = boost::spirit::qi;\n  namespace ascii = boost::spirit::ascii;\n  namespace phoenix = boost::phoenix;\n  vertex_data vtx;\n  const bool success = qi::phrase_parse\n    (line.begin(), line.end(),\n     //  Begin grammar\n     (\n      (qi::double_[phoenix::push_back(phoenix::ref(vtx.point), qi::_1)] % -qi::char_(\",\") )\n      )\n     ,\n     //  End grammar\n     ascii::space);\n\n  if (!success) return false;\n  vtx.best_cluster = (size_t)(-1);\n  vtx.best_distance = std::numeric_limits<double>::infinity();\n  vtx.changed = false;\n  graph.add_vertex(NEXT_VID.inc_ret_last(1), vtx);\n  return true;\n}\n\n// Read a line from a file and creates a vertex\nbool vertex_loader_sparse(graph_type& graph, const std::string& fname,\n                   const std::string& line) {\n  if (line.empty()) return true;\n\n  vertex_data vtx;\n  boost::char_separator<char> sep(\" \");\n  boost::tokenizer< boost::char_separator<char> > tokens(line, sep);\n  BOOST_FOREACH (const std::string& t, tokens) {\n    std::string::size_type pos = t.find(\":\");\n    if(pos > 0){\n      size_t id = (size_t)std::atoi(t.substr(0, pos).c_str());\n      double val = std::atof(t.substr(pos+1, t.length() - pos -1).c_str());\n      vtx.point_sparse.insert(std::make_pair(id, val));\n    }\n  }\n  vtx.best_cluster = (size_t)(-1);\n  vtx.best_distance = std::numeric_limits<double>::infinity();\n  vtx.changed = false;\n  graph.add_vertex(NEXT_VID.inc_ret_last(1), vtx);\n  return true;\n}\n\n// Read a line from a file and creates a vertex\nbool vertex_loader_with_id(graph_type& graph, const std::string& fname,\n                   const std::string& line) {\n  if (line.empty()) return true;\n  size_t id = 0;\n  namespace qi = boost::spirit::qi;\n  namespace ascii = boost::spirit::ascii;\n  namespace phoenix = boost::phoenix;\n  vertex_data vtx;\n  const bool success = qi::phrase_parse\n    (line.begin(), line.end(),\n     //  Begin grammar\n     (\n      qi::ulong_[phoenix::ref(id) = qi::_1] >> -qi::char_(\",\") >>\n      (qi::double_[phoenix::push_back(phoenix::ref(vtx.point), qi::_1)] % -qi::char_(\",\") )\n      )\n     ,\n     //  End grammar\n     ascii::space);\n\n  if (!success) return false;\n  vtx.best_cluster = (size_t)(-1);\n  vtx.best_distance = std::numeric_limits<double>::infinity();\n  vtx.changed = false;\n  graph.add_vertex(id, vtx);\n  return true;\n}\n\n// Read a line from a file and creates a vertex\nbool vertex_loader_with_id_sparse(graph_type& graph, const std::string& fname,\n                   const std::string& line) {\n  if (line.empty()) return true;\n\n  vertex_data vtx;\n  size_t id = 0;\n  boost::char_separator<char> sep(\" \");\n  boost::tokenizer<boost::char_separator<char> > tokens(line, sep);\n  bool first = true;\n  BOOST_FOREACH (const std::string& t, tokens) {\n    if(first){\n      id = (size_t)std::atoi(t.c_str());\n      first = false;\n    }else{\n      std::string::size_type pos = t.find(\":\");\n      if(pos > 0){\n        size_t id = (size_t)std::atoi(t.substr(0, pos).c_str());\n        double val = std::atof(t.substr(pos+1, t.length() - pos -1).c_str());\n        vtx.point_sparse.insert(std::make_pair(id, val));\n      }\n    }\n  }\n  vtx.best_cluster = (size_t)(-1);\n  vtx.best_distance = std::numeric_limits<double>::infinity();\n  vtx.changed = false;\n  graph.add_vertex(id, vtx);\n  return true;\n}\n\n\n\n//call this when edge weight file is given.\n//each line should be [source id] [target id] [weight].\n//directions of edges are ignored.\nbool edge_loader(graph_type& graph, const std::string& filename,\n    const std::string& textline) {\n  if (textline.empty())\n    return true;\n  std::stringstream strm(textline);\n  size_t source_vid = 0;\n  size_t target_vid = 0;\n  double weight = 0.0;\n  strm >> source_vid;\n  strm.ignore(1);\n  strm >> target_vid;\n  strm.ignore(1);\n  strm >> weight;\n  if(source_vid != target_vid)\n    graph.add_edge(source_vid, target_vid, edge_data(weight));\n  return true;\n}\n\n\n// A set of Map Reduces to compute the maximum and minimum vector sizes\n// to ensure that all vectors have the same length\nstruct max_point_size_reducer: public graphlab::IS_POD_TYPE {\n  size_t max_point_size;\n\n  static max_point_size_reducer get_max_point_size(const graph_type::vertex_type& v) {\n    max_point_size_reducer r;\n    r.max_point_size = v.data().point.size();\n    return r;\n  }\n\n  max_point_size_reducer& operator+=(const max_point_size_reducer& other) {\n    max_point_size = std::max(max_point_size, other.max_point_size);\n    return *this;\n  }\n};\n\nstruct min_point_size_reducer: public graphlab::IS_POD_TYPE {\n  size_t min_point_size;\n\n  static min_point_size_reducer get_min_point_size(const graph_type::vertex_type& v) {\n    min_point_size_reducer r;\n    r.min_point_size = v.data().point.size();\n    return r;\n  }\n\n  min_point_size_reducer& operator+=(const min_point_size_reducer& other) {\n    min_point_size = std::min(min_point_size, other.min_point_size);\n    return *this;\n  }\n};\n\n\n/*\n * This transform vertices call is only used during\n * the initialization phase. It computes distance to\n * cluster[KMEANS_INITIALIZATION] and assigns itself\n * to the new cluster KMEANS_INITIALIZATION if the new distance\n * is smaller that its previous cluster assignment\n */\nvoid kmeans_pp_initialization(graph_type::vertex_type& v) {\n  double d = sqr_distance(v.data().point,\n                          CLUSTERS[KMEANS_INITIALIZATION].center);\n  if (v.data().best_distance > d) {\n    v.data().best_distance = d;\n    v.data().best_cluster = KMEANS_INITIALIZATION;\n  }\n}\n\nvoid kmeans_pp_initialization_sparse(graph_type::vertex_type& v) {\n  double d = sqr_distance(v.data().point_sparse,\n                          CLUSTERS[KMEANS_INITIALIZATION].center_sparse);\n  if (v.data().best_distance > d) {\n    v.data().best_distance = d;\n    v.data().best_cluster = KMEANS_INITIALIZATION;\n  }\n}\n\n\n/*\n * Draws a random sample from the data points that is \n * proportionate to the \"best distance\" stored in the vertex.\n */\nstruct random_sample_reducer {\n  std::vector<double> vtx;\n  double weight;\n\n  random_sample_reducer():weight(0) { }\n  random_sample_reducer(const std::vector<double>& vtx,\n                        double weight):vtx(vtx),weight(weight) { }\n\n  static random_sample_reducer get_weight(const graph_type::vertex_type& v) {\n    if (v.data().best_cluster == (size_t)(-1)) {\n      return random_sample_reducer(v.data().point, 1);\n    }\n    else {\n      return random_sample_reducer(v.data().point,\n                                   v.data().best_distance);\n    }\n  }\n\n  random_sample_reducer& operator+=(const random_sample_reducer& other) {\n    double totalweight = weight + other.weight;\n    // if any weight is too small, just quit\n    if (totalweight <= 0) return *this;\n\n    double myp = weight / (weight + other.weight);\n    if (graphlab::random::bernoulli(myp)) {\n      weight += other.weight;\n      return *this;\n    }\n    else {\n      vtx = other.vtx;\n      weight += other.weight;\n      return *this;\n    }\n  }\n\n  void save(graphlab::oarchive &oarc) const {\n    oarc << vtx << weight;\n  }\n\n  void load(graphlab::iarchive& iarc) {\n    iarc >> vtx >> weight;\n  }\n};\n\nstruct random_sample_reducer_sparse{\n  std::map<size_t, double> vtx;\n  double weight;\n\n  random_sample_reducer_sparse():weight(0) { }\n  random_sample_reducer_sparse(const std::map<size_t, double>& vtx,\n                        double weight):vtx(vtx),weight(weight) { }\n\n  static random_sample_reducer_sparse get_weight(const graph_type::vertex_type& v) {\n    if (v.data().best_cluster == (size_t)(-1)) {\n      return random_sample_reducer_sparse(v.data().point_sparse, 1);\n    }\n    else {\n      return random_sample_reducer_sparse(v.data().point_sparse,\n                                   v.data().best_distance);\n    }\n  }\n\n  random_sample_reducer_sparse& operator+=(const random_sample_reducer_sparse& other) {\n    double totalweight = weight + other.weight;\n    // if any weight is too small, just quit\n    if (totalweight <= 0) return *this;\n\n    double myp = weight / (weight + other.weight);\n    if (graphlab::random::bernoulli(myp)) {\n      weight += other.weight;\n      return *this;\n    }\n    else {\n      vtx = other.vtx;\n      weight += other.weight;\n      return *this;\n    }\n  }\n\n  void save(graphlab::oarchive &oarc) const {\n    oarc << vtx << weight;\n  }\n\n  void load(graphlab::iarchive& iarc) {\n    iarc >> vtx >> weight;\n  }\n};\n\n\n/*\n * This transform vertices call is used during the \n * actual k-means iteration. It computes distance to \n * all \"changed\" clusters and reassigns itself if necessary\n */\nvoid kmeans_iteration(graph_type::vertex_type& v) {\n  // if current vertex's cluster was modified, we invalidate the distance.\n  // and we need to recompute to all existing clusters\n  // otherwise, we just need to recompute to changed cluster centers.\n  size_t prev_asg = v.data().best_cluster;\n  if (CLUSTERS[v.data().best_cluster].changed) {\n    // invalidate. recompute to all\n    v.data().best_cluster = (size_t)(-1);\n    v.data().best_distance = std::numeric_limits<double>::infinity();\n    for (size_t i = 0;i < NUM_CLUSTERS; ++i) {\n      if (CLUSTERS[i].center.size() > 0 || CLUSTERS[i].center_sparse.size() > 0) {\n        double d = 0.0;\n        if(IS_SPARSE == true)\n          d = sqr_distance(v.data().point_sparse, CLUSTERS[i].center_sparse);\n        else\n          d = sqr_distance(v.data().point, CLUSTERS[i].center);\n        if (d < v.data().best_distance) {\n          v.data().best_distance = d;\n          v.data().best_cluster = i;\n        }\n      }\n    }\n  }\n  else {\n    // just compute distance to what has changed\n    for (size_t i = 0;i < NUM_CLUSTERS; ++i) {\n      if (CLUSTERS[i].changed &&\n          (CLUSTERS[i].center.size() > 0 || CLUSTERS[i].center_sparse.size() > 0)) {\n        double d = 0.0;\n        if(IS_SPARSE == true)\n          d = sqr_distance(v.data().point_sparse, CLUSTERS[i].center_sparse);\n        else\n          d= sqr_distance(v.data().point, CLUSTERS[i].center);\n        if (d < v.data().best_distance) {\n          v.data().best_distance = d;\n          v.data().best_cluster = i;\n        }\n      }\n    }\n  }\n  v.data().changed = (prev_asg != v.data().best_cluster);\n}\n\n//gathered information\n//used when edge weight file is given\nstruct neighbor_info {\n  std::map<size_t, double> cw_map;\n\n  neighbor_info() :\n      cw_map() {\n  }\n  neighbor_info(size_t clst, double weight) :\n      cw_map() {\n    cw_map.insert(std::make_pair(clst, weight));\n  }\n\n  neighbor_info& operator+=(const neighbor_info& other) {\n    for (std::map<size_t, double>::const_iterator iter = other.cw_map.begin();\n        iter != other.cw_map.end(); iter++) {\n      size_t clst = iter->first;\n      if (cw_map.find(clst) == cw_map.end()) {\n        cw_map.insert(std::make_pair(clst, iter->second));\n      } else {\n        cw_map[clst] += iter->second;\n      }\n    }\n    return *this;\n  }\n\n  void save(graphlab::oarchive& oarc) const {\n    oarc << cw_map;\n  }\n  void load(graphlab::iarchive& iarc) {\n    iarc >> cw_map;\n  }\n};\n\n//used when edge weight file is given\nclass cluster_assignment: public graphlab::ivertex_program<graph_type,\n    neighbor_info>, public graphlab::IS_POD_TYPE {\npublic:\n  //gather on all the edges\n  edge_dir_type gather_edges(icontext_type& context,\n      const vertex_type& vertex) const {\n    return graphlab::ALL_EDGES;\n  }\n\n  //for each edge gather the weights and the assigned clusters of the neighbors\n  neighbor_info gather(icontext_type& context, const vertex_type& vertex,\n      edge_type& edge) const {\n    if (edge.source().id() == vertex.id()) { //out edge\n      return neighbor_info(edge.target().data().best_cluster,\n          edge.data().weight);\n    } else { //in edge\n      return neighbor_info(edge.source().data().best_cluster,\n          edge.data().weight);\n    }\n  }\n\n  //assign a cluster, considering the clusters of neighbors\n  void apply(icontext_type& context, vertex_type& vertex,\n      const gather_type& total) {\n    size_t past_clst = vertex.data().best_cluster;\n    vertex.data().best_cluster = (size_t) (-1);\n    vertex.data().best_distance = std::numeric_limits<double>::infinity();\n    for (size_t i = 0; i < NUM_CLUSTERS; ++i) {\n      if (CLUSTERS[i].center.size() > 0 || CLUSTERS[i].center_sparse.size() > 0) {\n        double d = 0.0;\n        if(IS_SPARSE == true)\n          d = sqr_distance(vertex.data().point_sparse, CLUSTERS[i].center_sparse);\n        else\n          d = sqr_distance(vertex.data().point, CLUSTERS[i].center);\n        //consider neighbors\n        const std::map<size_t, double>& cw_map = total.cw_map;\n        for (std::map<size_t, double>::const_iterator iter = cw_map.begin();\n            iter != cw_map.end(); iter++) {\n          size_t neighbor_cluster = iter->first;\n          double total_wieght = iter->second;\n          if (i == neighbor_cluster)\n            d -= total_wieght;\n        }\n        if (d < vertex.data().best_distance) {\n          vertex.data().best_distance = d;\n          vertex.data().best_cluster = i;\n        }\n      }\n    }\n    vertex.data().changed = (past_clst != vertex.data().best_cluster);\n  }\n\n  //send signals to the neighbors when the cluster assignment has changed\n  edge_dir_type scatter_edges(icontext_type& context,\n      const vertex_type& vertex) const {\n    if (vertex.data().changed)\n      return graphlab::ALL_EDGES;\n    else\n      return graphlab::NO_EDGES;\n  }\n\n  void scatter(icontext_type& context, const vertex_type& vertex,\n      edge_type& edge) const {\n  }\n};\n\n\n\n/*\n * computes new cluster centers\n * Also accumulates a counter counting the number of vertices which\n * assignments changed.\n */\nstruct cluster_center_reducer {\n  std::vector<cluster> new_clusters;\n  size_t num_changed;\n  double cost;\n\n  cluster_center_reducer():new_clusters(NUM_CLUSTERS), num_changed(0), cost(0) { }\n\n  static cluster_center_reducer get_center(const graph_type::vertex_type& v) {\n    cluster_center_reducer cc;\n    ASSERT_NE(v.data().best_cluster, (size_t)(-1));\n\n    if(IS_SPARSE == true)\n      cc.new_clusters[v.data().best_cluster].center_sparse = v.data().point_sparse;\n    else\n      cc.new_clusters[v.data().best_cluster].center = v.data().point;\n    cc.new_clusters[v.data().best_cluster].count = 1;\n    cc.num_changed = v.data().changed;\n    cc.cost = v.data().best_distance;\n    return cc;\n  }\n\n  cluster_center_reducer& operator+=(const cluster_center_reducer& other) {\n    for (size_t i = 0;i < NUM_CLUSTERS; ++i) {\n      if (new_clusters[i].count == 0) new_clusters[i] = other.new_clusters[i];\n      else if (other.new_clusters[i].count > 0) {\n        if(IS_SPARSE == true)\n          plus_equal_vector(new_clusters[i].center_sparse, other.new_clusters[i].center_sparse);\n        else\n          plus_equal_vector(new_clusters[i].center, other.new_clusters[i].center);\n        new_clusters[i].count += other.new_clusters[i].count;\n      }\n    }\n    num_changed += other.num_changed;\n    cost += other.cost;\n    return *this;\n  }\n\n  void save(graphlab::oarchive& oarc) const {\n    oarc << new_clusters << num_changed <<cost;\n  }\n\n  void load(graphlab::iarchive& iarc) {\n    iarc >> new_clusters >> num_changed >> cost;\n  }\n};\n\nstruct vertex_writer {\n  std::string save_vertex(graph_type::vertex_type v) {\n    std::stringstream strm;\n    for (size_t i = 0;i < v.data().point.size(); ++i) {\n      strm << v.data().point[i] << \"\\t\";\n    }\n    strm << v.data().best_distance << \"\\t\";\n    strm << v.data().best_cluster << \"\\n\";\n    strm.flush();\n    return strm.str();\n  }\n\n  std::string save_edge(graph_type::edge_type e) { return \"\"; }\n};\n\nstruct vertex_writer_sparse {\n  std::string save_vertex(graph_type::vertex_type v) {\n    std::stringstream strm;\n    for(std::map<size_t, double>::iterator iter = v.data().point_sparse.begin();\n        iter != v.data().point_sparse.end();++iter){\n      strm << (*iter).first << \":\" << (*iter).second << \" \";\n    }\n    strm << v.data().best_cluster << \"\\n\";\n    strm.flush();\n    return strm.str();\n  }\n\n  std::string save_edge(graph_type::edge_type e) { return \"\"; }\n};\n\nstruct vertex_writer_with_id {\n  std::string save_vertex(graph_type::vertex_type v) {\n    std::stringstream strm;\n    strm << v.id() << \"\\t\";\n    strm << v.data().best_cluster+1 << \"\\n\";\n    strm.flush();\n    return strm.str();\n  }\n\n  std::string save_edge(graph_type::edge_type e) { return \"\"; }\n};\n\n\nint main(int argc, char** argv) {\n  std::cout << \"Computes a K-means clustering of data.\\n\\n\";\n\n  graphlab::command_line_options clopts\n    (\"K-means clustering. The input data file is provided by the \"\n     \"--data argument which is non-optional. The format of the data file is a \"\n     \"collection of lines, where each line contains a comma or white-space \"\n     \"separated lost of numeric values representing a vector. Every line \"\n     \"must have the same number of values. The required --clusters=N \"\n     \"argument denotes the number of clusters to generate. To store the output \"\n     \"see the --output-cluster and --output-data arguments\");\n\n  std::string datafile;\n  std::string outcluster_file;\n  std::string outdata_file;\n  std::string edgedata_file;\n  size_t MAX_ITERATION = 0;\n  bool use_id = false;\n  clopts.attach_option(\"data\", datafile,\n                       \"Input file. Each line holds a white-space or comma separated numeric vector\");\n  clopts.attach_option(\"clusters\", NUM_CLUSTERS,\n                       \"The number of clusters to create.\");\n  clopts.attach_option(\"output-clusters\", outcluster_file,\n                       \"If set, will write a file containing cluster centers \"\n                       \"to this filename. This must be on the local filesystem \"\n                       \"and must be accessible to the root node.\");\n  clopts.attach_option(\"output-data\", outdata_file,\n                       \"If set, will output a copy of the input data with an additional \"\n                       \"two columns. The first added column is the distance to assigned \"\n\t\t       \"center and the last is the assigned cluster centers. The output \"\n                       \"will be written to a sequence of filenames where each file is \"\n                       \"prefixed by this value. This may be on HDFS.\");\n  clopts.attach_option(\"sparse\", IS_SPARSE,\n                       \"If set to true, will use a sparse vector representation.\"\n                       \"The file format is [feature id]:[value] [feature id]:[value] ...\"\n                       \", where [feature id] must be positive integer or zero.\");\n  clopts.attach_option(\"id\", use_id,\n                       \"If set to true, will use ids for data points. The id of a data point \"\n                       \"must be written at the head of each line of the input data. \"\n                       \"The output data will consist of two columns: the first one \"\n                       \"denotes the ids; the second one denotes the assigned clusters.\");\n  clopts.attach_option(\"pairwise-reward\", edgedata_file,\n                       \"If set, will consider pairwise rewards when clustering. \"\n                       \"Each line of the file beginning with the argument holds [id1] [id2] \"\n                       \"[reward]. This mode must be used with --id option.\");\n  clopts.attach_option(\"max-iteration\", MAX_ITERATION,\n                       \"The max number of iterations\");\n\n  if(!clopts.parse(argc, argv)) return EXIT_FAILURE;\n  if (datafile == \"\") {\n    std::cout << \"--data is not optional\\n\";\n    return EXIT_FAILURE;\n  }\n  if (NUM_CLUSTERS == 0) {\n    std::cout << \"--clusters is not optional\\n\";\n    return EXIT_FAILURE;\n  }\n  if(edgedata_file.size() > 0){\n    if(use_id == false){\n      std::cout << \"--id is not optional when you use edge data\\n\";\n      return EXIT_FAILURE;\n    }\n  }\n\n  graphlab::mpi_tools::init(argc, argv);\n  graphlab::distributed_control dc;\n  // load graph\n  graph_type graph(dc, clopts);\n  NEXT_VID = (((graphlab::vertex_id_type)1 << 31) / dc.numprocs()) * dc.procid();\n  if(IS_SPARSE == true){\n    if(use_id){\n      graph.load(datafile, vertex_loader_with_id_sparse);\n    }else{\n      graph.load(datafile, vertex_loader_sparse);\n    }\n  }else{\n    if(use_id){\n      graph.load(datafile, vertex_loader_with_id);\n    }else{\n      graph.load(datafile, vertex_loader);\n    }\n  }\n  if(edgedata_file.size() > 0){\n    graph.load(edgedata_file, edge_loader);\n  }\n  graph.finalize();\n  dc.cout() << \"Number of datapoints: \" << graph.num_vertices() << std::endl;\n\n  if (graph.num_vertices() < NUM_CLUSTERS) {\n    dc.cout() << \"More clusters than datapoints! Cannot proceed\" << std::endl;\n    return EXIT_FAILURE;\n  }\n\n  dc.cout() << \"Validating data...\";\n\n\n  CLUSTERS.resize(NUM_CLUSTERS);\n  // make sure all have the same array length\n  if(IS_SPARSE == false){\n    size_t max_p_size = graph.map_reduce_vertices<max_point_size_reducer>\n                                  (max_point_size_reducer::get_max_point_size).max_point_size;\n    size_t min_p_size = graph.map_reduce_vertices<min_point_size_reducer>\n                                  (min_point_size_reducer::get_min_point_size).min_point_size;\n    if (max_p_size != min_p_size) {\n      dc.cout() << \"Data has dimensionality ranging from \" << min_p_size << \" to \" << max_p_size\n                << \"! K-means cannot proceed!\" << std::endl;\n      return EXIT_FAILURE;\n    }\n    // allocate clusters\n    for (size_t i = 0;i < NUM_CLUSTERS; ++i) {\n      CLUSTERS[i].center.resize(max_p_size);\n    }\n  }\n\n  dc.cout() << \"Initializing using Kmeans++\\n\";\n  // ok. perform kmeans++ initialization\n  for (KMEANS_INITIALIZATION = 0;\n       KMEANS_INITIALIZATION < NUM_CLUSTERS;\n       ++KMEANS_INITIALIZATION) {\n\n    if(IS_SPARSE == true){\n      random_sample_reducer_sparse rs = graph.map_reduce_vertices<random_sample_reducer_sparse>\n                                        (random_sample_reducer_sparse::get_weight);\n      CLUSTERS[KMEANS_INITIALIZATION].center_sparse = rs.vtx;\n      graph.transform_vertices(kmeans_pp_initialization_sparse);\n    }else{\n      random_sample_reducer rs = graph.map_reduce_vertices<random_sample_reducer>\n                                        (random_sample_reducer::get_weight);\n      CLUSTERS[KMEANS_INITIALIZATION].center = rs.vtx;\n      graph.transform_vertices(kmeans_pp_initialization);\n    }\n  }\n\n  // \"reset\" all clusters\n  for (size_t i = 0; i < NUM_CLUSTERS; ++i) CLUSTERS[i].changed = true;\n  // perform Kmeans iteration\n\n  dc.cout() << \"Running Kmeans...\\n\";\n  bool clusters_changed = true;\n  size_t iteration_count = 0;\n  while(clusters_changed) {\n\t\tif(MAX_ITERATION > 0 && iteration_count >= MAX_ITERATION)\n\t\t\tbreak;\n\n    cluster_center_reducer cc = graph.map_reduce_vertices<cluster_center_reducer>\n                                    (cluster_center_reducer::get_center);\n    // the first round (iteration_count == 0) is not so meaningful\n    // since I am just recomputing the centers from the output of the KMeans++\n    // initialization\n    if (iteration_count > 0) {\n      dc.cout() << \"Kmeans iteration \" << iteration_count << \": \" <<\n                 \"# points with changed assignments = \" << cc.num_changed << \n\t\t \" total cost: \" << cc.cost << std::endl;\n    }\n    for (size_t i = 0;i < NUM_CLUSTERS; ++i) {\n      double d = cc.new_clusters[i].count;\n      if(IS_SPARSE){\n        if (d > 0) scale_vector(cc.new_clusters[i].center_sparse, 1.0 / d);\n        if (cc.new_clusters[i].count == 0 && CLUSTERS[i].count > 0) {\n          dc.cout() << \"Cluster \" << i << \" lost\" << std::endl;\n          CLUSTERS[i].center_sparse.clear();\n          CLUSTERS[i].count = 0;\n          CLUSTERS[i].changed = false;\n        }\n        else {\n          CLUSTERS[i] = cc.new_clusters[i];\n          CLUSTERS[i].changed = true;\n        }\n      }else{\n        if (d > 0) scale_vector(cc.new_clusters[i].center, 1.0 / d);\n        if (cc.new_clusters[i].count == 0 && CLUSTERS[i].count > 0) {\n          dc.cout() << \"Cluster \" << i << \" lost\" << std::endl;\n          CLUSTERS[i].center.clear();\n          CLUSTERS[i].count = 0;\n          CLUSTERS[i].changed = false;\n        }\n        else {\n          CLUSTERS[i] = cc.new_clusters[i];\n          CLUSTERS[i].changed = true;\n        }\n      }\n    }\n    clusters_changed = iteration_count == 0 || cc.num_changed > 0;\n\n    if(edgedata_file.size() > 0){\n      clopts.engine_args.set_option(\"factorized\", true);\n      graphlab::omni_engine<cluster_assignment> engine(dc, graph, \"async\", clopts);\n      engine.signal_all();\n      engine.start();\n    }else{\n      graph.transform_vertices(kmeans_iteration);\n    }\n\n    ++iteration_count;\n  }\n\n\n  if (!outcluster_file.empty() && dc.procid() == 0) {\n    dc.cout() << \"Writing Cluster Centers...\" << std::endl;\n    std::ofstream fout(outcluster_file.c_str());\n    if(IS_SPARSE){\n      for (size_t i = 0;i < NUM_CLUSTERS; ++i) {\n        if(use_id)\n          fout << i+1 << \"\\t\";\n        for (std::map<size_t, double>::iterator iter = CLUSTERS[i].center_sparse.begin();\n             iter != CLUSTERS[i].center_sparse.end();++iter) {\n          fout << (*iter).first << \":\" << (*iter).second << \" \";\n        }\n        fout << \"\\n\";\n      }\n    }else{\n      for (size_t i = 0;i < NUM_CLUSTERS; ++i) {\n        if(use_id)\n          fout << i+1 << \"\\t\";\n        for (size_t j = 0; j < CLUSTERS[i].center.size(); ++j) {\n          fout << CLUSTERS[i].center[j] << \" \";\n        }\n        fout << \"\\n\";\n      }\n    }\n  }\n\n  if (!outdata_file.empty()) {\n    dc.cout() << \"Writing Data with cluster assignments...\\n\" << std::endl;\n    if(use_id){\n      graph.save(outdata_file, vertex_writer_with_id(), false, true, false, 1);\n    }else{\n      if(IS_SPARSE == true)\n        graph.save(outdata_file, vertex_writer_sparse(), false, true, false, 1);\n      else\n        graph.save(outdata_file, vertex_writer(), false, true, false, 1);\n    }\n  }\n\n  graphlab::mpi_tools::finalize();\n}\n\n\n", "meta": {"hexsha": "6d652d42e1821de0d5623d70d61d526d0963e072", "size": 31758, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "toolkits/clustering/kmeans.cpp", "max_stars_repo_name": "RealM10/package", "max_stars_repo_head_hexsha": "3bcec9b677226ee0395e82e908f542aba0ecaad7", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 333.0, "max_stars_repo_stars_event_min_datetime": "2016-07-29T19:22:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T02:40:34.000Z", "max_issues_repo_path": "toolkits/clustering/kmeans.cpp", "max_issues_repo_name": "HybridGraph/GraphLab-PowerGraph", "max_issues_repo_head_hexsha": "ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2016-09-15T00:31:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-08T07:51:07.000Z", "max_forks_repo_path": "toolkits/clustering/kmeans.cpp", "max_forks_repo_name": "HybridGraph/GraphLab-PowerGraph", "max_forks_repo_head_hexsha": "ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 163.0, "max_forks_repo_forks_event_min_datetime": "2016-07-29T19:22:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:15:24.000Z", "avg_line_length": 31.853560682, "max_line_length": 102, "alphanum_fraction": 0.6240947163, "num_tokens": 8251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.4005031084552774}}
{"text": "#include <cfloat>\n#include <cmath>\n\n#include <boost/math/distributions/normal.hpp>\n\n#include <DataTypes/DataTypeTuple.h>\n#include <DataTypes/DataTypesDecimal.h>\n#include <DataTypes/DataTypesNumber.h>\n#include <Columns/ColumnTuple.h>\n#include <Columns/ColumnsNumber.h>\n#include <Functions/FunctionFactory.h>\n#include <Functions/FunctionHelpers.h>\n#include <Functions/IFunction.h>\n#include <Functions/castTypeToEither.h>\n#include <Interpreters/castColumn.h>\n\n\nnamespace DB\n{\n\nnamespace ErrorCodes\n{\n    extern const int ILLEGAL_TYPE_OF_ARGUMENT;\n}\n\ntemplate <typename Impl>\nclass FunctionMinSampleSize : public IFunction\n{\npublic:\n    static constexpr auto name = Impl::name;\n\n    static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionMinSampleSize<Impl>>(); }\n\n    String getName() const override { return name; }\n\n    size_t getNumberOfArguments() const override { return Impl::num_args; }\n    ColumnNumbers getArgumentsThatAreAlwaysConstant() const override\n    {\n        return ColumnNumbers(std::begin(Impl::const_args), std::end(Impl::const_args));\n    }\n\n    bool useDefaultImplementationForNulls() const override { return false; }\n    bool useDefaultImplementationForConstants() const override { return true; }\n    bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return false; }\n\n    static DataTypePtr getReturnType()\n    {\n        auto float_64_type = std::make_shared<DataTypeNumber<Float64>>();\n\n        DataTypes types{\n            float_64_type,\n            float_64_type,\n            float_64_type,\n        };\n\n        Strings names{\n            \"minimum_sample_size\",\n            \"detect_range_lower\",\n            \"detect_range_upper\",\n        };\n\n        return std::make_shared<DataTypeTuple>(std::move(types), std::move(names));\n    }\n\n    DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override\n    {\n        Impl::validateArguments(arguments);\n        return getReturnType();\n    }\n\n    ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override\n    {\n        return Impl::execute(arguments, input_rows_count);\n    }\n};\n\nstatic bool isBetweenZeroAndOne(Float64 v)\n{\n    return v >= 0.0 && v <= 1.0 && fabs(v - 0.0) >= DBL_EPSILON && fabs(v - 1.0) >= DBL_EPSILON;\n}\n\nstruct ContinousImpl\n{\n    static constexpr auto name = \"minSampleSizeContinous\";\n    static constexpr size_t num_args = 5;\n    static constexpr size_t const_args[] = {2, 3, 4};\n\n    static void validateArguments(const DataTypes & arguments)\n    {\n        for (size_t i = 0; i < arguments.size(); ++i)\n        {\n            if (!isNativeNumber(arguments[i]))\n            {\n                throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, \"The {}th Argument of function {} must be a number.\", i + 1, name);\n            }\n        }\n    }\n\n    static ColumnPtr execute(const ColumnsWithTypeAndName & arguments, size_t input_rows_count)\n    {\n        auto float_64_type = std::make_shared<DataTypeFloat64>();\n        auto baseline_argument = arguments[0];\n        baseline_argument.column = baseline_argument.column->convertToFullColumnIfConst();\n        auto baseline_column_untyped = castColumnAccurate(baseline_argument, float_64_type);\n        const auto * baseline_column = checkAndGetColumn<ColumnVector<Float64>>(*baseline_column_untyped);\n        const auto & baseline_column_data = baseline_column->getData();\n\n        auto sigma_argument = arguments[1];\n        sigma_argument.column = sigma_argument.column->convertToFullColumnIfConst();\n        auto sigma_column_untyped = castColumnAccurate(sigma_argument, float_64_type);\n        const auto * sigma_column = checkAndGetColumn<ColumnVector<Float64>>(*sigma_column_untyped);\n        const auto & sigma_column_data = sigma_column->getData();\n\n        const IColumn & col_mde = *arguments[2].column;\n        const IColumn & col_power = *arguments[3].column;\n        const IColumn & col_alpha = *arguments[4].column;\n\n        auto res_min_sample_size = ColumnFloat64::create();\n        auto & data_min_sample_size = res_min_sample_size->getData();\n        data_min_sample_size.reserve(input_rows_count);\n\n        auto res_detect_lower = ColumnFloat64::create();\n        auto & data_detect_lower = res_detect_lower->getData();\n        data_detect_lower.reserve(input_rows_count);\n\n        auto res_detect_upper = ColumnFloat64::create();\n        auto & data_detect_upper = res_detect_upper->getData();\n        data_detect_upper.reserve(input_rows_count);\n\n        /// Minimal Detectable Effect\n        const Float64 mde = col_mde.getFloat64(0);\n        /// Sufficient statistical power to detect a treatment effect\n        const Float64 power = col_power.getFloat64(0);\n        /// Significance level\n        const Float64 alpha = col_alpha.getFloat64(0);\n\n        boost::math::normal_distribution<> nd(0.0, 1.0);\n\n        for (size_t row_num = 0; row_num < input_rows_count; ++row_num)\n        {\n            /// Mean of control-metric\n            Float64 baseline = baseline_column_data[row_num];\n            /// Standard deviation of conrol-metric\n            Float64 sigma = sigma_column_data[row_num];\n\n            if (!std::isfinite(baseline) || !std::isfinite(sigma) || !isBetweenZeroAndOne(mde) || !isBetweenZeroAndOne(power)\n                || !isBetweenZeroAndOne(alpha))\n            {\n                data_min_sample_size.emplace_back(std::numeric_limits<Float64>::quiet_NaN());\n                data_detect_lower.emplace_back(std::numeric_limits<Float64>::quiet_NaN());\n                data_detect_upper.emplace_back(std::numeric_limits<Float64>::quiet_NaN());\n                continue;\n            }\n\n            Float64 delta = baseline * mde;\n\n            using namespace boost::math;\n            /// https://towardsdatascience.com/required-sample-size-for-a-b-testing-6f6608dd330a\n            /// \\frac{2\\sigma^{2} * (Z_{1 - alpha /2} + Z_{power})^{2}}{\\Delta^{2}}\n            Float64 min_sample_size\n                = 2 * std::pow(sigma, 2) * std::pow(quantile(nd, 1.0 - alpha / 2) + quantile(nd, power), 2) / std::pow(delta, 2);\n\n            data_min_sample_size.emplace_back(min_sample_size);\n            data_detect_lower.emplace_back(baseline - delta);\n            data_detect_upper.emplace_back(baseline + delta);\n        }\n\n        return ColumnTuple::create(Columns{std::move(res_min_sample_size), std::move(res_detect_lower), std::move(res_detect_upper)});\n    }\n};\n\n\nstruct ConversionImpl\n{\n    static constexpr auto name = \"minSampleSizeConversion\";\n    static constexpr size_t num_args = 4;\n    static constexpr size_t const_args[] = {1, 2, 3};\n\n    static void validateArguments(const DataTypes & arguments)\n    {\n        size_t arguments_size = arguments.size();\n        for (size_t i = 0; i < arguments_size; ++i)\n        {\n            if (!isFloat(arguments[i]))\n            {\n                throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, \"The {}th argument of function {} must be a float.\", i + 1, name);\n            }\n        }\n    }\n\n    static ColumnPtr execute(const ColumnsWithTypeAndName & arguments, size_t input_rows_count)\n    {\n        auto first_argument_column = castColumnAccurate(arguments[0], std::make_shared<DataTypeFloat64>());\n\n        if (const ColumnConst * const col_p1_const = checkAndGetColumnConst<ColumnVector<Float64>>(first_argument_column.get()))\n        {\n            const Float64 left_value = col_p1_const->template getValue<Float64>();\n            return process<true>(arguments, &left_value, input_rows_count);\n        }\n        else if (const ColumnVector<Float64> * const col_p1 = checkAndGetColumn<ColumnVector<Float64>>(first_argument_column.get()))\n        {\n            return process<false>(arguments, col_p1->getData().data(), input_rows_count);\n        }\n        else\n        {\n            throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, \"The first argument of function {} must be a float.\", name);\n        }\n    }\n\n    template <bool const_p1>\n    static ColumnPtr process(const ColumnsWithTypeAndName & arguments, const Float64 * col_p1, const size_t input_rows_count)\n    {\n        const IColumn & col_mde = *arguments[1].column;\n        const IColumn & col_power = *arguments[2].column;\n        const IColumn & col_alpha = *arguments[3].column;\n\n        auto res_min_sample_size = ColumnFloat64::create();\n        auto & data_min_sample_size = res_min_sample_size->getData();\n        data_min_sample_size.reserve(input_rows_count);\n\n        auto res_detect_lower = ColumnFloat64::create();\n        auto & data_detect_lower = res_detect_lower->getData();\n        data_detect_lower.reserve(input_rows_count);\n\n        auto res_detect_upper = ColumnFloat64::create();\n        auto & data_detect_upper = res_detect_upper->getData();\n        data_detect_upper.reserve(input_rows_count);\n\n        /// Minimal Detectable Effect\n        const Float64 mde = col_mde.getFloat64(0);\n        /// Sufficient statistical power to detect a treatment effect\n        const Float64 power = col_power.getFloat64(0);\n        /// Significance level\n        const Float64 alpha = col_alpha.getFloat64(0);\n\n        boost::math::normal_distribution<> nd(0.0, 1.0);\n\n        for (size_t row_num = 0; row_num < input_rows_count; ++row_num)\n        {\n            /// Proportion of control-metric\n            Float64 p1;\n\n            if constexpr (const_p1)\n            {\n                p1 = col_p1[0];\n            }\n            else if constexpr (!const_p1)\n            {\n                p1 = col_p1[row_num];\n            }\n\n            if (!std::isfinite(p1) || !isBetweenZeroAndOne(mde) || !isBetweenZeroAndOne(power) || !isBetweenZeroAndOne(alpha))\n            {\n                data_min_sample_size.emplace_back(std::numeric_limits<Float64>::quiet_NaN());\n                data_detect_lower.emplace_back(std::numeric_limits<Float64>::quiet_NaN());\n                data_detect_upper.emplace_back(std::numeric_limits<Float64>::quiet_NaN());\n                continue;\n            }\n\n            Float64 q1 = 1.0 - p1;\n            Float64 p2 = p1 + mde;\n            Float64 q2 = 1.0 - p2;\n            Float64 p_bar = (p1 + p2) / 2.0;\n            Float64 q_bar = 1.0 - p_bar;\n\n            using namespace boost::math;\n            /// https://towardsdatascience.com/required-sample-size-for-a-b-testing-6f6608dd330a\n            /// \\frac{(Z_{1-alpha/2} * \\sqrt{2*\\bar{p}*\\bar{q}} + Z_{power} * \\sqrt{p1*q1+p2*q2})^{2}}{\\Delta^{2}}\n            Float64 min_sample_size\n                = std::pow(\n                      quantile(nd, 1.0 - alpha / 2.0) * std::sqrt(2.0 * p_bar * q_bar) + quantile(nd, power) * std::sqrt(p1 * q1 + p2 * q2),\n                      2)\n                / std::pow(mde, 2);\n\n            data_min_sample_size.emplace_back(min_sample_size);\n            data_detect_lower.emplace_back(p1 - mde);\n            data_detect_upper.emplace_back(p1 + mde);\n        }\n\n        return ColumnTuple::create(Columns{std::move(res_min_sample_size), std::move(res_detect_lower), std::move(res_detect_upper)});\n    }\n};\n\n\nvoid registerFunctionMinSampleSize(FunctionFactory & factory)\n{\n    factory.registerFunction<FunctionMinSampleSize<ContinousImpl>>();\n    factory.registerFunction<FunctionMinSampleSize<ConversionImpl>>();\n}\n\n}\n", "meta": {"hexsha": "02a94c743e8af9c65cda4e7de39ca496ae15fe70", "size": 11310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Functions/minSampleSize.cpp", "max_stars_repo_name": "chalice19/ClickHouse", "max_stars_repo_head_hexsha": "2f38e7bc5c2113935ab86260439bb543a1737291", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8629.0, "max_stars_repo_stars_event_min_datetime": "2016-06-14T21:03:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-23T07:46:38.000Z", "max_issues_repo_path": "src/Functions/minSampleSize.cpp", "max_issues_repo_name": "chalice19/ClickHouse", "max_issues_repo_head_hexsha": "2f38e7bc5c2113935ab86260439bb543a1737291", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4335.0, "max_issues_repo_issues_event_min_datetime": "2016-06-15T12:58:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-23T11:18:43.000Z", "max_forks_repo_path": "src/Functions/minSampleSize.cpp", "max_forks_repo_name": "chalice19/ClickHouse", "max_forks_repo_head_hexsha": "2f38e7bc5c2113935ab86260439bb543a1737291", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1700.0, "max_forks_repo_forks_event_min_datetime": "2016-06-15T09:25:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-23T11:16:38.000Z", "avg_line_length": 38.7328767123, "max_line_length": 140, "alphanum_fraction": 0.6480990274, "num_tokens": 2612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7826624789529376, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.4005013863591425}}
{"text": "#include <chrono>\n#include <string>\n#include <iostream>\n#include <algorithm>\n#include <pngwriter.h>\n#include <boost/program_options.hpp>\n#include \"mandelbrot.hpp\"\n\nnamespace po = boost::program_options;\n\nint main(int argc, char* argv[]) {\n    std::string out_file;\n    double scale, cx, cy;\n    size_t max_n, width, height, n_colors, n_threads, nx, ny;\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n            (\"help,h\", \"Print this message\")\n            (\"out,o\", po::value(&out_file)->default_value(\"result.png\"), \"Output file\")\n            (\"scale,s\", po::value(&scale)->default_value(1), \"Scale\")\n            (\"cx\", po::value(&cx)->default_value(-0.28676842048), \"X center coordinate\")\n            (\"cy\", po::value(&cy)->default_value(0), \"Y center coordinate\")\n            (\"iter,i\", po::value(&max_n)->default_value(5000), \"Maximum number of iterations\")\n            (\"width\", po::value(&width)->default_value(1920), \"Image width\")\n            (\"height\", po::value(&height)->default_value(1080), \"Image height\")\n            (\"colors\", po::value(&n_colors)->default_value(10), \"Number of colors\")\n            (\"threads,t\", po::value(&n_threads)->default_value(1), \"Number of threads\")\n            (\"nx\", po::value(&nx)->default_value(16), \"Split into nx columns\")\n            (\"ny\", po::value(&ny)->default_value(16), \"Split into ny rows\");\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);\n    if (vm.count(\"help\")) {\n        std::cout << desc << std::endl;\n        return 0;\n    }\n    auto m = mtms::mandelbrot_set<double>(width, height, n_colors);\n    const auto start = std::chrono::high_resolution_clock::now();\n    m.run(n_threads, nx, ny, scale * std::max(3. / width, 2. / height), {cx, cy}, max_n);\n    const auto run_end = std::chrono::high_resolution_clock::now();\n    pngwriter png(static_cast<int>(width), static_cast<int>(height), 0, out_file.c_str());\n    for (size_t i = 0; i < height; ++i)\n        for (size_t j = 0; j < width; ++j) {\n            const auto color = m.color(i, j);\n            png.plot(static_cast<int>(j), static_cast<int>(i), color.r, color.g, color.b);\n        }\n    png.close();\n    const auto write_end = std::chrono::high_resolution_clock::now();\n    std::cout << \"Run time: \"\n              << std::chrono::duration_cast<std::chrono::nanoseconds>(run_end - start).count() << \" ns\\n\"\n              << \"Write time : \"\n              << std::chrono::duration_cast<std::chrono::nanoseconds>(write_end - run_end).count() << \" ns\\n\"\n              << \"All time: \"\n              << std::chrono::duration_cast<std::chrono::nanoseconds>(write_end - start).count() << \" ns\" << std::endl;\n    return 0;\n}", "meta": {"hexsha": "208ad30c575b6fbd64997643eccff1fbb2a17afa", "size": 2722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "BecauseWeCanStudios/MPMS", "max_stars_repo_head_hexsha": "329675af17ef644a479e0a04b1d6fb13545e8daa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "BecauseWeCanStudios/MPMS", "max_issues_repo_head_hexsha": "329675af17ef644a479e0a04b1d6fb13545e8daa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "BecauseWeCanStudios/MPMS", "max_forks_repo_head_hexsha": "329675af17ef644a479e0a04b1d6fb13545e8daa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4909090909, "max_line_length": 119, "alphanum_fraction": 0.5955180015, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4004002040214838}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// weighted_extended_p_square.hpp\n//\n//  Copyright 2005 Daniel Egloff. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_EXTENDED_P_SQUARE_HPP_DE_01_01_2006\n#define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_EXTENDED_P_SQUARE_HPP_DE_01_01_2006\n\n#include <vector>\n#include <functional>\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/permutation_iterator.hpp>\n#include <boost/parameter/keyword.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics/sum.hpp>\n#include <boost/accumulators/statistics/times2_iterator.hpp>\n#include <boost/accumulators/statistics/extended_p_square.hpp>\n\nnamespace boost { namespace accumulators\n{\n\nnamespace impl\n{\n    ///////////////////////////////////////////////////////////////////////////////\n    // weighted_extended_p_square_impl\n    //  multiple quantile estimation with weighted samples\n    /**\n        @brief Multiple quantile estimation with the extended \\f$P^2\\f$ algorithm for weighted samples\n\n        This version of the extended \\f$P^2\\f$ algorithm extends the extended \\f$P^2\\f$ algorithm to\n        support weighted samples. The extended \\f$P^2\\f$ algorithm dynamically estimates several\n        quantiles without storing samples. Assume that \\f$m\\f$ quantiles\n        \\f$\\xi_{p_1}, \\ldots, \\xi_{p_m}\\f$ are to be estimated. Instead of storing the whole sample\n        cumulative distribution, the algorithm maintains only \\f$m+2\\f$ principal markers and\n        \\f$m+1\\f$ middle markers, whose positions are updated with each sample and whose heights\n        are adjusted (if necessary) using a piecewise-parablic formula. The heights of the principal\n        markers are the current estimates of the quantiles and are returned as an iterator range.\n\n        For further details, see\n\n        K. E. E. Raatikainen, Simultaneous estimation of several quantiles, Simulation, Volume 49,\n        Number 4 (October), 1986, p. 159-164.\n\n        The extended \\f$ P^2 \\f$ algorithm generalizes the \\f$ P^2 \\f$ algorithm of\n\n        R. Jain and I. Chlamtac, The P^2 algorithm for dynamic calculation of quantiles and\n        histograms without storing observations, Communications of the ACM,\n        Volume 28 (October), Number 10, 1985, p. 1076-1085.\n\n        @param extended_p_square_probabilities A vector of quantile probabilities.\n    */\n    template<typename Sample, typename Weight>\n    struct weighted_extended_p_square_impl\n      : accumulator_base\n    {\n        typedef typename numeric::functional::multiplies<Sample, Weight>::result_type weighted_sample;\n        typedef typename numeric::functional::average<weighted_sample, std::size_t>::result_type float_type;\n        typedef std::vector<float_type> array_type;\n        // for boost::result_of\n        typedef iterator_range<\n            detail::lvalue_index_iterator<\n                permutation_iterator<\n                    typename array_type::const_iterator\n                  , detail::times2_iterator\n                >\n            >\n        > result_type;\n\n        template<typename Args>\n        weighted_extended_p_square_impl(Args const &args)\n          : probabilities(\n                boost::begin(args[extended_p_square_probabilities])\n              , boost::end(args[extended_p_square_probabilities])\n            )\n          , heights(2 * probabilities.size() + 3)\n          , actual_positions(heights.size())\n          , desired_positions(heights.size())\n        {\n        }\n\n        template<typename Args>\n        void operator ()(Args const &args)\n        {\n            std::size_t cnt = count(args);\n            std::size_t sample_cell = 1; // k\n            std::size_t num_quantiles = this->probabilities.size();\n\n            // m+2 principal markers and m+1 middle markers\n            std::size_t num_markers = 2 * num_quantiles + 3;\n\n            // first accumulate num_markers samples\n            if(cnt <= num_markers)\n            {\n                this->heights[cnt - 1] = args[sample];\n                this->actual_positions[cnt - 1] = args[weight];\n\n                // complete the initialization of heights (and actual_positions) by sorting\n                if(cnt == num_markers)\n                {\n                    // TODO: we need to sort the initial samples (in heights) in ascending order and\n                    // sort their weights (in actual_positions) the same way. The following lines do\n                    // it, but there must be a better and more efficient way of doing this.\n                    typename array_type::iterator it_begin, it_end, it_min;\n\n                    it_begin = this->heights.begin();\n                    it_end   = this->heights.end();\n\n                    std::size_t pos = 0;\n\n                    while (it_begin != it_end)\n                    {\n                        it_min = std::min_element(it_begin, it_end);\n                        std::size_t d = std::distance(it_begin, it_min);\n                        std::swap(*it_begin, *it_min);\n                        std::swap(this->actual_positions[pos], this->actual_positions[pos + d]);\n                        ++it_begin;\n                        ++pos;\n                    }\n\n                    // calculate correct initial actual positions\n                    for (std::size_t i = 1; i < num_markers; ++i)\n                    {\n                        actual_positions[i] += actual_positions[i - 1];\n                    }\n                }\n            }\n            else\n            {\n                if(args[sample] < this->heights[0])\n                {\n                    this->heights[0] = args[sample];\n                    this->actual_positions[0] = args[weight];\n                    sample_cell = 1;\n                }\n                else if(args[sample] >= this->heights[num_markers - 1])\n                {\n                    this->heights[num_markers - 1] = args[sample];\n                    sample_cell = num_markers - 1;\n                }\n                else\n                {\n                    // find cell k = sample_cell such that heights[k-1] <= sample < heights[k]\n\n                    typedef typename array_type::iterator iterator;\n                    iterator it = std::upper_bound(\n                        this->heights.begin()\n                      , this->heights.end()\n                      , args[sample]\n                    );\n\n                    sample_cell = std::distance(this->heights.begin(), it);\n                }\n\n                // update actual position of all markers above sample_cell\n                for(std::size_t i = sample_cell; i < num_markers; ++i)\n                {\n                    this->actual_positions[i] += args[weight];\n                }\n\n                // compute desired positions\n                {\n                    this->desired_positions[0] = this->actual_positions[0];\n                    this->desired_positions[num_markers - 1] = sum_of_weights(args);\n                    this->desired_positions[1] = (sum_of_weights(args) - this->actual_positions[0]) * probabilities[0]\n                                              / 2. + this->actual_positions[0];\n                    this->desired_positions[num_markers - 2] = (sum_of_weights(args) - this->actual_positions[0])\n                                                            * (probabilities[num_quantiles - 1] + 1.)\n                                                            / 2. + this->actual_positions[0];\n\n                    for (std::size_t i = 0; i < num_quantiles; ++i)\n                    {\n                        this->desired_positions[2 * i + 2] = (sum_of_weights(args) - this->actual_positions[0])\n                                                          * probabilities[i] + this->actual_positions[0];\n                    }\n\n                    for (std::size_t i = 1; i < num_quantiles; ++i)\n                    {\n                        this->desired_positions[2 * i + 1] = (sum_of_weights(args) - this->actual_positions[0])\n                                                      * (probabilities[i - 1] + probabilities[i])\n                                                      / 2. + this->actual_positions[0];\n                    }\n                }\n\n                // adjust heights and actual_positions of markers 1 to num_markers - 2 if necessary\n                for (std::size_t i = 1; i <= num_markers - 2; ++i)\n                {\n                    // offset to desired position\n                    float_type d = this->desired_positions[i] - this->actual_positions[i];\n\n                    // offset to next position\n                    float_type dp = this->actual_positions[i + 1] - this->actual_positions[i];\n\n                    // offset to previous position\n                    float_type dm = this->actual_positions[i - 1] - this->actual_positions[i];\n\n                    // height ds\n                    float_type hp = (this->heights[i + 1] - this->heights[i]) / dp;\n                    float_type hm = (this->heights[i - 1] - this->heights[i]) / dm;\n\n                    if((d >= 1 && dp > 1) || (d <= -1 && dm < -1))\n                    {\n                        short sign_d = static_cast<short>(d / std::abs(d));\n\n                        float_type h = this->heights[i] + sign_d / (dp - dm) * ((sign_d - dm)*hp + (dp - sign_d) * hm);\n\n                        // try adjusting heights[i] using p-squared formula\n                        if(this->heights[i - 1] < h && h < this->heights[i + 1])\n                        {\n                            this->heights[i] = h;\n                        }\n                        else\n                        {\n                            // use linear formula\n                            if(d > 0)\n                            {\n                                this->heights[i] += hp;\n                            }\n                            if(d < 0)\n                            {\n                                this->heights[i] -= hm;\n                            }\n                        }\n                        this->actual_positions[i] += sign_d;\n                    }\n                }\n            }\n        }\n\n        result_type result(dont_care) const\n        {\n            // for i in [1,probabilities.size()], return heights[i * 2]\n            detail::times2_iterator idx_begin = detail::make_times2_iterator(1);\n            detail::times2_iterator idx_end = detail::make_times2_iterator(this->probabilities.size() + 1);\n\n            return result_type(\n                make_permutation_iterator(this->heights.begin(), idx_begin)\n              , make_permutation_iterator(this->heights.begin(), idx_end)\n            );\n        }\n\n    private:\n        array_type probabilities;         // the quantile probabilities\n        array_type heights;               // q_i\n        array_type actual_positions;      // n_i\n        array_type desired_positions;     // d_i\n    };\n\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::weighted_extended_p_square\n//\nnamespace tag\n{\n    struct weighted_extended_p_square\n      : depends_on<count, sum_of_weights>\n      , extended_p_square_probabilities\n    {\n        typedef accumulators::impl::weighted_extended_p_square_impl<mpl::_1, mpl::_2> impl;\n    };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::weighted_extended_p_square\n//\nnamespace extract\n{\n    extractor<tag::weighted_extended_p_square> const weighted_extended_p_square = {};\n\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_extended_p_square)\n}\n\nusing extract::weighted_extended_p_square;\n\n}} // namespace boost::accumulators\n\n#endif\n", "meta": {"hexsha": "61160298256063a557c4558811947031eeec4ecf", "size": 12406, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/accumulators/statistics/weighted_extended_p_square.hpp", "max_stars_repo_name": "HelloSunyi/boost_1_54_0", "max_stars_repo_head_hexsha": "429fea793612f973d4b7a0e69c5af8156ae2b56e", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-12-05T19:34:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T09:07:09.000Z", "max_issues_repo_path": "boost/accumulators/statistics/weighted_extended_p_square.hpp", "max_issues_repo_name": "graehl/boost", "max_issues_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2015-07-22T07:35:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-14T16:03:06.000Z", "max_forks_repo_path": "boost/accumulators/statistics/weighted_extended_p_square.hpp", "max_forks_repo_name": "graehl/boost", "max_forks_repo_head_hexsha": "37cc4ca77896a86ad10e90dc03e1e825dc0d5492", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T00:09:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T10:47:11.000Z", "avg_line_length": 42.6323024055, "max_line_length": 119, "alphanum_fraction": 0.5294212478, "num_tokens": 2518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4004001971537003}}
{"text": "//\n// Created by beck on 24/9/18.\n//\n#include <stdio.h>\n#include <limits>\n#include <string.h>\n#include <Eigen/Dense>\n#include <ros/ros.h>\n#include \"kalman.h\"\n#include \"geometry_msgs/Point32.h\"\n#include \"sensor_msgs/PointCloud.h\"\n\nros::Subscriber radar_cloud_sub;\nros::Publisher filtered_cloud_pub;\n\nbool filter_initialized = false;\n\nKalmanFilter kf;\n\nvoid\ninitialize_radar_filter(double distance)\n{\n    int n = 2;\n    int m = 1;\n\n    double dt = 1.0 / 14; // 14Hz from the radar\n\n    Eigen::MatrixXd A(n, n);\n    Eigen::MatrixXd H(m, n);\n    Eigen::MatrixXd Q(n, n);\n    Eigen::MatrixXd R(m, m);\n    Eigen::MatrixXd P(n, n);\n\n    // constant velocity model\n    A << 1, dt,\n         0, 1;\n    H << 1, 0;\n    Q << 1, 0,\n         0, 1;\n    R << 0.01;\n    P << 1, 0,\n         0, 1;\n\n    // initialize the filter\n    KalmanFilter kf_init(dt, A, H, Q, R, P);\n    Eigen::VectorXd x0(n);\n    x0 << distance, 0;\n\n    // create a prediction with Kalman filter\n    kf_init.init(ros::Time::now().toSec(), x0);\n    kf = kf_init;\n\tfilter_initialized = true;\n\tROS_INFO(\"initialized the radar kalman filter at %f\", distance);\n}\n\n// change the ID to the sorted order\nvoid\npublish_message(const int id, const std_msgs::Header& header)\n{\n    geometry_msgs::Point32 point;\n\n\tpoint.x = kf.state()[0]; // estimated state\n\tpoint.y = kf.state()[1]; // estimated velocity\n\tpoint.z = id; \n\n\tsensor_msgs::PointCloud ptCloud;\n\tptCloud.header = header;\n\tptCloud.points.push_back(point);\n\tfiltered_cloud_pub.publish(ptCloud);\n}\n\nvoid\nradar_callback(const sensor_msgs::PointCloud::ConstPtr pc_ptr)\n{\n    int n = 2;\n    int m = 1;\n    int s = pc_ptr->points.size();\n    int i;\n\n    if (s > 0) {\n        if (!filter_initialized) {\n            double distance = 9.0;\n\n            for ( i = 0; i < s; ++i) {\n                double x_ = pc_ptr->points[i].x;\n                if (x_ > 9 && x_ < 10)\n                    distance = x_;\n            }\n            initialize_radar_filter(distance);\n        }\n        else\n        {\n            double minChiSquare = std::numeric_limits<double>::max();\n            int chi_index = s;\n            bool found_nearest_point = false;\n\t\t\tint id = 0;\n\n            // compare the chi-square to select into one\n            for ( i = 0; i < s; ++i) {\n                Eigen::VectorXd z(m);\n                z << pc_ptr->points[i].x;\n\n                double chiSquare = kf.chiSquare(z);\n                if (chiSquare < minChiSquare) {\n                    minChiSquare = chiSquare;\n                    chi_index = i;\n                }\n            }\n            double residual = pc_ptr->points[chi_index].x - kf.state()[0];\n            if (residual < 1 && residual > -1)\n                found_nearest_point = true;\n\n            if (found_nearest_point) {\n                ROS_INFO(\"found the number at %d with X2 %f\", chi_index, minChiSquare);\n\n                kf.propagate();\n\n                Eigen::VectorXd z_sel(m);\n                z_sel << pc_ptr->points[chi_index].x;\n                kf.update(z_sel);\n\n                publish_message(id, pc_ptr->header);\n            } \n\t\t\telse {\n\t\t\t\tROS_INFO(\"radar does not track the obstacle\");\n\t\t\t\t// kf.propagate();\n\n                publish_message(id, pc_ptr->header);\n\t\t\t}\n        }\n    }\n\telse {\n\t\tROS_INFO(\"no point available\");\n\t}\n}\n\nint main(int argc, char **argv)\n{\n    ros::init(argc, argv, \"radar_preprocess\");\n    ros::NodeHandle n = ros::NodeHandle(\"~\");\n\n    radar_cloud_sub\n    = n.subscribe<sensor_msgs::PointCloud>(\"/inf24g/inf24radar\",\n                                            10,\n                                            radar_callback);\n    filtered_cloud_pub\n    = n.advertise<sensor_msgs::PointCloud>(\"/filtered_radar\", 10);\n\n\n    ros::spin();\n\n    return 0;\n}\n", "meta": {"hexsha": "dfe8f49814732886e9391b786748292d680f0534", "size": 3725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2_localization/radar_preprocess/src/radar_preprocess_node.cpp", "max_stars_repo_name": "huying163/ros_environment", "max_stars_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-01-30T11:40:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-03T05:52:47.000Z", "max_issues_repo_path": "2_localization/radar_preprocess/src/radar_preprocess_node.cpp", "max_issues_repo_name": "huying163/ros_environment", "max_issues_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2_localization/radar_preprocess/src/radar_preprocess_node.cpp", "max_forks_repo_name": "huying163/ros_environment", "max_forks_repo_head_hexsha": "bac3343bf92e6fa2bd852baf261e80712564f990", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-23T08:14:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-23T08:14:57.000Z", "avg_line_length": 24.1883116883, "max_line_length": 87, "alphanum_fraction": 0.5428187919, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.712232184238947, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.4004001971537003}}
{"text": "\n\n#include <math.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <iostream>\n\n#include <boost/log/trivial.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"navigation.hpp\"\n#include \"common.hpp\"\n#include \"antenna.hpp\"\n#include \"enums.h\"\n\n#include \"eigenIncluder.hpp\"\n\n/** Compare two time tags (t2-t1)\n* Returns julian day difference\n*/\ndouble timecomp(\n\tconst double t1[6],\t\t///< time tag in [YMDHMS]\n\tconst double t2[6])\t\t///< time tag in [YMDHMS]\n{\n\t/* convert two time tags to julian day */\n\tdouble jd1 = ymdhms2jd(t1);\n\tdouble jd2 = ymdhms2jd(t2);\n\n// \tBOOST_LOG_TRIVIAL(debug) << \"time difference in julian day is \"<< jd2-jd1;\n\n\treturn jd2-jd1;\n}\n\n/* decode antenna field */\nint decodef(char *p, int n, double *v)\n{\n\tint i;\n\tfor (i = 0; i < n; i++)\n\t\tv[i] = 0;\n\n\tfor (i = 0, p = strtok(p,\" \"); p && i < n; p = strtok(NULL, \" \"))\n\t{\n\t\tv[i] = atof(p) * 1E-3;\n\t\ti++;\n\t}\n\treturn i;\n}\n\npcvacs_t* findAntenna(\n\tstring code,\n\tdouble tc[6],\n\tnav_t& nav)\n{\n// \tBOOST_LOG_TRIVIAL(debug)\n// \t<< \"Searching for \" << type << \", \" << code;\n\n\tauto it1 = nav.pcvMap.find(code);\n\tif (it1 == nav.pcvMap.end())\n\t{\n\t\treturn nullptr;\n\t}\n\t\n\tauto& pcvTimeMap = it1->second;\n\t\n\tif (pcvTimeMap.size() == 0)\n\t{\n\t\treturn nullptr;\n\t}\n\t\n\tGTime time = epoch2time(tc);\n\t\n\tauto it2 = pcvTimeMap.lower_bound(time);\n\tif (it2 == pcvTimeMap.end())\n\t{\n\t\t//just use the first chronologically, (last when sorted as they are) instead\n\t\tauto it3 = pcvTimeMap.rbegin();\n\t\tpcvacs_t& pcv = it3->second;\n\t\t\n\t\treturn &pcv;\n\t}\n\t\n\tpcvacs_t& pcv = it2->second;\n\t\n\treturn &pcv;\n}\n\t\n/* linear interpolate pcv ------------------------------------------------------\n*\n* args     :       double x1              I       x1 lower bound (degree)\n*                  double x2              I       x2 upper bound (degree)\n*                  double y1              I       y1 lower bound (m)\n*                  double y2              I       y2 upper bound (m)\n*                  double x               O       x current point (degree)\n*\n* return   :       interpolated pcv (m)\n*----------------------------------------------------------------------------*/\ndouble interp(double x1, double x2, double y1, double y2, double x)\n{\n#if (0)\n\treturn (y2-y1)*(x-x1)/(x2-x1)+y1;\n#endif\n\treturn y2-(y2-y1)*(x2-x)/(x2-x1);\n}\n\n/* fetch rec pco ---------------------------------------------------------------\n*\n* args     :       const pcvacs_t *pc     I       antenna info\n*                  const chat sys         I       satellite system\n*                  const int freq         I       frequency 1 or 2\n*                  double pco[3]          O       rec pco (m)\n*\n* return   :       none\n*\n* note     :       frequencies are sorted as GPS, GLONASS, Galileo and BeiDou\n*----------------------------------------------------------------------------*/\nvoid recpco(pcvacs_t *pc, int freq, Vector3d& pco)\n{\n\tpcvacs_t& pcv = *pc;\n\t/* assign rec/sat pco */\n\tif (pcv.pcoMap.find((E_FType)freq) == pcv.pcoMap.end())\t\tpco = Vector3d::Zero();\n\telse\t\t\t\t\t\t\t\t\t\t\t\t\t\tpco = pcv.pcoMap[(E_FType) freq];\n}\n\n/* fetch rec pcv ---------------------------------------------------------------\n*\n* args     :       const pcvacs_t pc      I       antenna info\n*                  const chat sys         I       satellite system\n*                  const int freq         I       frequency 1, 2\n*                  const double el        I       satellite elevation (degree)\n*                  const double azi       I       azimuth (degree)\n*                  double *pcv            O       rec pcv (m)\n*\n* return   :       none\n*\n* note     :       frequencies are sorted as GPS, GLONASS, Galileo and BeiDou\n*----------------------------------------------------------------------------*/\nvoid recpcv(\n\tpcvacs_t*\tpc,\n\tint\t\t\tfreq,\n\tdouble\t\tel,\n\tdouble\t\tazi,\n\tdouble&\t\tpcv)\n{\n\tint\t\tnz\t\t= pc->nz;\n\tint\t\tnaz\t\t= pc->naz;\n\tdouble\tzen1\t= pc->zenStart;\n\tdouble\tdzen\t= pc->zenDelta;\n\tdouble\tdazi\t= pc->aziDelta;\n\tdouble\tzen\t\t= 90 - el;\n\n\tif (pc->PCVMap1D.find(freq) == pc->PCVMap1D.end())\n\t{\n\t\t//frequency not found\n\t\treturn;\n\t}\n\tauto& pcvMap1D = pc->PCVMap1D[freq];\n\n\t/* select zenith angle range */\n\tint zen_n;\n\tfor (zen_n = 1; zen_n < nz; zen_n++)\n\t{\n\t\tif ((zen1 + dzen * zen_n) >= zen)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tdouble xz1 = zen1 + dzen * (zen_n - 1);\n\tdouble xz2 = zen1 + dzen * (zen_n);\n\n\tif (naz == 0)\n\t{\n\t\t/* linear interpolate receiver pcv - non azimuth-dependent */\n\t\t/* interpolate */\n\n\t\tdouble\tyz1 = pcvMap1D[zen_n - 1];\t\t// lower bound\n\t\tdouble\tyz2 = pcvMap1D[zen_n];\t\t\t// upper bound\n\t\tpcv = interp(xz1, xz2, yz1, yz2, zen);\n\t}\n\telse\n\t{\n\t\tif (pc->PCVMap2D.find(freq) == pc->PCVMap2D.end())\n\t\t{\n\t\t\t//frequency not found\n\t\t\treturn;\n\t\t}\n\t\tauto& pcvMap2D = pc->PCVMap2D[freq];\n\n\t\t/* bilinear interpolate receiver pcv - azimuth-dependent */\n\t\t/* select azimuth angle range */\n\t\tint az_n;\n\t\tfor (az_n = 1; az_n < naz; az_n++)\n\t\t{\n\t\t\tif ((dazi * az_n) >= azi)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tdouble xa1 = dazi * (az_n -1);\n\t\tdouble xa2 = dazi * (az_n);\n\n\t\tdouble yz3 = pcvMap2D[az_n-1]\t[zen_n-1];\t\tdouble yz1 = pcvMap2D[az_n-1]\t[zen_n];\n\t\tdouble yz4 = pcvMap2D[az_n]\t\t[zen_n-1];\t\tdouble yz2 = pcvMap2D[az_n]\t\t[zen_n];\n\n\t\t/* linear interpolation along zenith angle */\n\t\tdouble ya1\t= interp(xz1, xz2, yz3, yz1, zen);\n\t\tdouble ya2 \t= interp(xz1, xz2, yz4, yz2, zen);\n\n\t\t/* linear interpolation along azimuth angle */\n\t\tpcv\t= interp(xa1, xa2, ya1, ya2, azi);\n\t}\n\n\treturn;\n}\n//=============================================================================\n// radomeNoneAntennaType = radome2none(antennaType)\n//\n//       e,g, \"AOAD/M_T        JPLA\" => \"AOAD/M_T        NONE\"\n//\n// Change the last four characters of antenna type to NONE\n// This function is useful for when searching for an antenna model in ANTEX\n//\n// The IGS convention is to default to NONE for the radome if the calibration\n// value is not available\n//=============================================================================\n//void radome2none(char *restrict antenna_type)\nvoid radome2none(string& antenna_type)\n{\n\tsize_t length = antenna_type.size();\n\tif (length != 20)\n\t{\n\t\tprintf(\"\\n*** ERROR radome2none(): string length is less then 20 characters received %ld characters\\n\",length);\n\t\treturn;\n\t}\n\tantenna_type.replace(length - 4, 4, \"NONE\");\n}\n\nmap<string, E_FType> antexCodes =\n{\n\t{\"G01\", L1    },\n\t{\"G02\", L2    },\n\t{\"G05\", L5    },\n\t{\"R01\", G1    },\n\t{\"R02\", G2    },\n\t{\"E01\", E1    },\n\t{\"E05\", E5A   },\n\t{\"E07\", E5B   },\n\t{\"E08\", E5AB  },\n\t{\"E06\", E6    },\n\t{\"C01\", E1    },\n\t{\"C02\", E2    },\n\t{\"C07\", E5B   },\n\t{\"C06\", E6    },\n\t{\"J01\", L1    },\n\t{\"J02\", L2    },\n\t{\"J05\", L5    },\n\t{\"J06\", LEX   },\n\t{\"S01\", L1    },\n\t{\"S05\", L5    }\n};\n\n/** Read antex file */\nint readantexf(\n\tstring\tfile,\n\tnav_t&\tnav)\n{\n\tint offset;\n\tint noazi_flag\t\t= 0;\n\tint num_azi_rd\t\t= 0;\n\tint new_antenna\t\t= 0;\n\tint num_antennas\t= 0;\n\tint irms\t\t\t= 0;\n\n\tchar tmp[10];\n\tchar *p;\n\n\tFILE* fp = fopen(file.c_str(),\"r\");\n\tif (fp == nullptr)\n\t{\n\t\tBOOST_LOG_TRIVIAL(warning)\n\t\t<< \"Warning: ANTEX file opening error\";\n\n\t\treturn 0;\n\t}\n\n\tconst pcvacs_t pcv0 = {};\n\tpcvacs_t ds_pcv;\n\n\tE_FType\tft = FTYPE_NONE;\n\n\tchar buff[512];\n\twhile (fgets(buff, sizeof(buff), fp))\n\t{\n\t\tchar* comment = buff + 60;\n\n\t\tif (irms) \n\t\t\tcontinue;\n\t\t/* Read in the ANTEX header information */\n\t\tif (strlen(buff) < 60 )\t\t\t\t\t\t\t\t{\tcontinue;\t}\n\t\tif (strstr(comment, \"ANTEX VERSION / SYST\"))\t\t{\tcontinue;\t}\n\t\tif (strstr(comment, \"PCV TYPE / REFANT\")) \t\t\t{\tcontinue;\t}\n\t\tif (strstr(comment, \"COMMENT\")) \t\t\t\t\t{\tcontinue;\t}\n\t\tif (strstr(comment, \"END OF HEADER\"))\t\t\t\t{\tcontinue;\t}\n\t\t/* Read in specific Antenna information now */\n\t\t\n\t\tif (strstr(comment, \"START OF ANTENNA\"))\n\t\t{\n\t\t\tnum_antennas++;\n\t\t\tds_pcv\t\t= pcv0;\n\t\t\tnew_antenna\t= 1;        /* flag for new antenna */\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (!new_antenna)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"METH / BY / # / DATE\"))\n\t\t{\n// \t\t\tint num_calibrated;\n// \t\t\tchar cal_method[20];\n// \t\t\tchar cal_agency[20];\n// \t\t\tchar cal_date[10];\n// \t\t\tstrncpy(cal_method,\tbuff,\t\t20);/* Should be CHAMBER or FIELD or ROBOT or COPIED ot CONVERTED */\n// \t\t\tcal_method[19] = '\\0';\n// \t\t\tstrncpy(cal_agency, buff + 20,\t20);\n// \t\t\tcal_agency[19] = '\\0';\n// \t\t\tstrncpy(tmp,\t\tbuff + 40,\t10);\n// \t\t\tnum_calibrated = atoi(tmp);\n// \t\t\tstrncpy(cal_date,\tbuff + 50,\t10);\n// \t\t\tcal_date[9] = '\\0';\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"DAZI\"))\n\t\t{\n\t\t\tstrncpy(tmp,buff   ,8);tmp[8] = '\\0';\n\t\t\tds_pcv.aziDelta = atof(tmp);\n\n\t\t\tif (ds_pcv.aziDelta < 0.0001)\tds_pcv.naz = 0;\n\t\t\telse                     \t\tds_pcv.naz = (360 / ds_pcv.aziDelta) + 1;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"END OF ANTENNA\"))\n\t\t{\n\t\t\t/* reset the flags for the next antenna */\n\t\t\tnew_antenna\t= 0;\n\n\t\t\t/* stack antenna pco and pcv */\n\t\t\tstring id;\n\t\t\tstring& satId = ds_pcv.code;\n\t\t\tif (satId.find_first_not_of(' ') == satId.npos)\t\t{ id = ds_pcv.type;\t}\n\t\t\telse\t\t\t\t\t\t\t\t\t\t\t\t{ id = ds_pcv.code;\t}\n\t\t\n\t\t\tboost::trim_right(id);\n\t\t\t\n\t\t\tGTime time = epoch2time(ds_pcv.tf);\n\t\t\tnav.pcvMap[id][time] = ds_pcv;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"TYPE / SERIAL NO\"))\n\t\t{\n\t\t\tds_pcv.type\t\t.assign(buff,\t\t20);\n\t\t\tds_pcv.code\t\t.assign(buff+20,\t20);\n\t\t\tds_pcv.svn\t\t.assign(buff+40,\t4);\n\t\t\tds_pcv.cospar\t.assign(buff+50,\t10);\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"ZEN1 / ZEN2 / DZEN\"))\n\t\t{\n\t\t\tstrncpy(tmp, buff,\t\t8);\ttmp[8] = '\\0'; \tds_pcv.zenStart\t= atof(tmp);\n\t\t\tstrncpy(tmp, buff+8,\t7);\ttmp[8] = '\\0'; \tds_pcv.zenStop\t= atof(tmp);\n\t\t\tstrncpy(tmp, buff+16,\t7);\ttmp[8] = '\\0'; \tds_pcv.zenDelta\t= atof(tmp);\n\n\t\t\tds_pcv.nz = (ds_pcv.zenStop - ds_pcv.zenStart) / ds_pcv.zenDelta + 1 ;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"# OF FREQUENCIES\"))\n\t\t{\n//\t\t\tstrncpy(tmp, buff,\t\t8);\n// \t\t\ttmp[8] = '\\0'; \t\n// \t\t\tds_pcv.nf\t\t= atoi(tmp);\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"VALID FROM\"))\n\t\t{\n\t\t\tchar valid_from[44];\n\t\t\t/* if (!str2time(buff,0,43,pcv.ts)) continue;*/\n\t\t\tstrncpy(valid_from, buff, 43);\n\t\t\tvalid_from[43] = '\\0';\n\t\t\tp = strtok(valid_from, \" \");\n\t\t\tint j = 0;\n\t\t\twhile (p != NULL)\n\t\t\t{\n\t\t\t\tds_pcv.tf[j] = (double) atoi(p);\n\t\t\t\tp = strtok(NULL, \" \");\n\t\t\t\tj++;\n\t\t\t}\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"VALID UNTIL\"))\n\t\t{\n\t\t\tchar valid_until[44];\n\t\t\t/* if (!str2time(buff,0,43,pcv.te)) continue;*/\n\t\t\tstrncpy(valid_until, buff   ,43);\n\t\t\tvalid_until[43] = '\\0';\n\t\t\tp = strtok(valid_until, \" \");\n\t\t\tint j = 0;\n\t\t\twhile (p != nullptr)\n\t\t\t{\n\t\t\t\tds_pcv.tu[j] = (double) atoi(p);\n\t\t\t\tp = strtok(NULL, \" \");\n\t\t\t\tj++;\n\t\t\t}\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"NORTH / EAST / UP\"))\n\t\t{\n\t\t\tdouble neu[3];\n\t\t\tif (decodef(buff, 3, neu) < 3)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* assign pco value in ENU */\n\t\t\tVector3d& enu = ds_pcv.pcoMap[ft];\n\t\t\tenu[0] = neu[1];\n\t\t\tenu[1] = neu[0];\n\t\t\tenu[2] = neu[2];\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"START OF FREQUENCY\"))\n\t\t{\n\t\t\tnum_azi_rd = 0;\n\t\t\tnoazi_flag = 0;\n\n\t\t\tstring antexFCode;\n\t\t\tantexFCode.assign(&buff[3], 3);\n\n\t\t\tft = antexCodes[antexFCode];\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"END OF FREQUENCY\"))\t{\tnoazi_flag\t= 0;\tcontinue;\t}\n\t\tif (strstr(comment, \"START OF FREQ RMS\"))\t{\tirms\t\t= 1;\tcontinue;\t}\n\t\tif (strstr(comment, \"END OF FREQ RMS\"))\t\t{\tirms\t\t= 0;\tcontinue;\t}\n\t\t\n\t\tif (!irms && strstr(buff,\"NOAZI\"))\n\t\t{\n\t\t\tfor (int i = 0; i < ds_pcv.nz; i++)\n\t\t\t{\n\t\t\t\toffset = i * 8 + 8;\n\t\t\t\tstrncpy(tmp, buff + offset, 8);\n\t\t\t\ttmp[8]='\\0';\n\t\t\t\tdouble pcv_val = atof(tmp);\n\t\t\t\tds_pcv.PCVMap1D[ft]\t\t\t.push_back(pcv_val * 1e-3);\n\t\t\t}\n\t\t\tnoazi_flag = 1;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (!irms && noazi_flag == 1)\n\t\t{\n\t\t\tstrncpy(tmp, buff, 8);\n\t\t\ttmp[8]='\\0';\n\n\t\t\tfor (int i = 0; i < ds_pcv.nz; i++)\n\t\t\t{\n\t\t\t\toffset = i * 8 + 8;\n\t\t\t\tstrncpy(tmp, buff + offset, 8);\n\t\t\t\ttmp[8]='\\0';\n\t\t\t\tdouble pcv_val = atof(tmp);\n\t\t\t\tds_pcv.PCVMap2D[ft][num_azi_rd].push_back(pcv_val * 1e-3);\n\t\t\t}\n\t\t\tnum_azi_rd++;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\tfclose(fp);\n\n\treturn 1;\n}\n\n/** Satellite antenna model.\n* Compute satellite antenna phase center parameters\n*/\n// inplace of antmodel_\n// this will not work\n// for galileo models\nvoid interp_satantmodel(\n\tpcvacs_t&\t\t\tpcv,\t///< antenna phase center parameters\n\tdouble\t\t\t\tnadir,\t///< nadir angle for satellite (rad)\n\tmap<int, double>&\tdant)\t///< range offsets for each frequency (m)\n{\n\tfor (auto& [ft, pcvVector] : pcv.PCVMap1D)\n\t{\n\t\tdouble\tnadirDeg\t\t= nadir * R2D;\t\t\t\t// ang=0-90\n\t\tint\t\tnumSections\t\t= pcvVector.size();\n\t\tdouble\tstartAngle\t\t= pcv.zenStart;\n\t\tdouble\tsectionWidth\t= pcv.zenDelta;\n\t\tdouble\trealSection\t\t= ((nadirDeg - startAngle) / sectionWidth);\n\t\tdouble\tintSection\t\t= (int) realSection;\n\t\tdouble\tfraction\t\t= realSection - intSection;\n\n\t\tif\t\t(intSection < 0)\t\t\t\t{\tdant[ft] = pcvVector[0];\t\t\t\t\t}\n\t\telse if\t(intSection >= numSections)\t\t{\tdant[ft] = pcvVector[numSections-1];\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble a = pcvVector[intSection];\n\t\t\tdouble b = pcvVector[intSection + 1];\n\n\t\t\tdant[ft] = a + fraction * (b - a);\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "bf4ea743ccf87e6b0ca7bf758ea8ef82e4f88da3", "size": 12800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/common/antenna.cpp", "max_stars_repo_name": "RodrigoNaves/ginan-bitbucket-update-tests", "max_stars_repo_head_hexsha": "4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 73.0, "max_stars_repo_stars_event_min_datetime": "2021-07-08T23:35:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:17:58.000Z", "max_issues_repo_path": "src/cpp/common/antenna.cpp", "max_issues_repo_name": "RodrigoNaves/ginan-bitbucket-update-tests", "max_issues_repo_head_hexsha": "4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-09-27T14:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T23:50:02.000Z", "max_forks_repo_path": "src/cpp/common/antenna.cpp", "max_forks_repo_name": "RodrigoNaves/ginan-bitbucket-update-tests", "max_forks_repo_head_hexsha": "4bd5cc0a9dd0e94b1c2d8b35385e128404009b0c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T05:42:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:15:34.000Z", "avg_line_length": 23.6598890943, "max_line_length": 113, "alphanum_fraction": 0.542421875, "num_tokens": 4290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.5, "lm_q1q2_score": 0.4003460010479772}}
{"text": "/* Hector -- A Simple Climate Model\n   Copyright (C) 2014-2015  Battelle Memorial Institute\n\n   Please see the accompanying file LICENSE.md for additional licensing\n   information.\n*/\n /*\n * carbon-cycle-solver.cpp\n *\n * ODE solver for integrating the carbon cycle in hector.\n *\n * See notes in carbon-cycle-solver.cpp\n *\n */\n\n#include <math.h>\n#include <string>\n#include <boost/numeric/odeint.hpp>\n\n#include \"carbon-cycle-solver.hpp\"\n#include \"avisitor.hpp\"\n\nnamespace Hector {\n  \n//------------------------------------------------------------------------------\n/*! \\brief Constructor\n */\nCarbonCycleSolver::CarbonCycleSolver() : nc( 0 ),\neps_abs( 1.0e-6 ),eps_rel( 1.0e-6 ),\ndt( 0.3 )\n{\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief Deconstructor\n */\nCarbonCycleSolver::~CarbonCycleSolver()\n{\n}\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nvoid CarbonCycleSolver::init( Core* coreptr ) {\n    // This component is very verbose at the debug and notice levels, so limit\n    // output to the warning level, even if the rest of the model is configured\n    // for something lower.\n    logger.open(getComponentName(), false, coreptr->getGlobalLogger().getEchoToFile(), Logger::WARNING);\n    H_LOG( logger, Logger::DEBUG ) << getComponentName() << \" initialized.\" << std::endl;\n    \n    core = coreptr;\n    \n    in_spinup = false;\n    \n    // We want to run after the carbon box models, to give them a chance to initialize\n    core->registerDependency( D_ATMOSPHERIC_C, getComponentName() );\n}\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nunitval CarbonCycleSolver::sendMessage( const std::string& message,\n                                       const std::string& datum,\n                                       const message_data info ) throw ( h_exception )\n{\n    unitval returnval;\n    \n    if( message==M_GETDATA ) {          //! Caller is requesting data\n        return getData( datum, info.date );\n        \n    } else if( message==M_SETDATA ) {   //! Caller is requesting to set data\n        //TODO: call setData below\n        //TODO: change core so that parsing is routed through sendMessage\n        //TODO: make setData private\n        \n    } else {                        //! We don't handle any other messages\n        H_THROW( \"Caller sent unknown message: \"+message );\n    }\n    \n    return returnval;\n}\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nvoid CarbonCycleSolver::setData( const std::string &varName,\n                                 const message_data& data ) throw ( h_exception )\n{\n    H_LOG( logger, Logger::DEBUG ) << \"Setting \" << varName << \"[\" << data.date << \"]=\" << data.value_str << std::endl;\n    \n    try {\n        if( varName == D_CCS_EPS_ABS ) {\n            H_ASSERT( data.date == Core::undefinedIndex() , \"date not allowed\" );\n            eps_abs = data.getUnitval(U_UNDEFINED);;\n        }\n        else if( varName == D_CCS_EPS_REL ) {\n            H_ASSERT( data.date == Core::undefinedIndex() , \"date not allowed\" );\n            eps_rel = data.getUnitval(U_UNDEFINED);;\n        }\n        else if( varName == D_CCS_DT ) {\n            H_ASSERT( data.date == Core::undefinedIndex() , \"date not allowed\" );\n            dt = data.getUnitval(U_UNDEFINED);\n        }\n        else if( varName == D_EPS_SPINUP ) {\n            H_ASSERT( data.date == Core::undefinedIndex() , \"date not allowed\" );\n            eps_spinup = data.getUnitval(U_PGC);\n        }\n        else {\n            H_LOG( logger, Logger::SEVERE ) << \"Unknown variable \" << varName << std::endl;\n            H_THROW( \"Unknown variable name while parsing \"+ getComponentName() + \": \"\n                    + varName );\n        }\n    } catch( h_exception& parseException ) {\n        H_RETHROW( parseException, \"Could not parse var: \"+varName );\n    }\n    \n    return;\n}\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nvoid CarbonCycleSolver::prepareToRun() throw( h_exception )\n{\n    H_LOG( logger, Logger::DEBUG ) << \"prepareToRun \" << std::endl;\n    \n    cmodel = dynamic_cast<CarbonCycleModel*>( core->getComponentByCapability( D_ATMOSPHERIC_C ) );\n    \n    // initialize the solver's internal data\n    t = core->getStartDate();\n    nc = cmodel->ncpool();\n    H_LOG( logger, Logger::DEBUG ) << \"Carbon model in use is \" << cmodel->getComponentName() << std::endl;\n    H_LOG( logger, Logger::DEBUG ) << \"Carbon model pools: \" << nc << std::endl;\n    H_ASSERT( nc > 0, \"nc must be > 0\" );\n    // resize the array of carbon pool values\n    c.resize(nc);\n    \n}\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nunitval CarbonCycleSolver::getData( const std::string& varName,\n                                   const double date ) throw ( h_exception ) {\n    \n    unitval returnval;\n    \n    H_ASSERT( date == Core::undefinedIndex(), \"Date not allowed for CarbonCycleSolver\" );\n    \n    H_THROW( \"Caller is requesting unknown variable: \" + varName );\n    \n    return returnval;\n}\n\nvoid CarbonCycleSolver::reset(double time) throw(h_exception)\n{\n    // Only state maintained by this component is the time counter\n    t = time;\n    in_spinup = false;          // reset this in case we will be expected to rerun the spinup.\n    H_LOG(logger, Logger::NOTICE)\n        << getComponentName() << \" reset to time= \" << time << \"\\n\";\n}\n\n\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nvoid CarbonCycleSolver::shutDown()\n{\n\tH_LOG( logger, Logger::DEBUG ) << \"goodbye \" << getComponentName() << std::endl;\n    logger.close();\n}\n\n\n//------------------------------------------------------------------------------\n/*! \\brief              Dispatch function called by ODE solver\n *  \\param[in] y        pools\n *  \\param[in] dydt     pool changes\n *  \\param[in] t        time\n *  \\exception          If the carbon model returned failure flag we must throw\n *                      an exception to stop the ODE solver.\n */\nvoid CarbonCycleSolver::ODEEvalFunctor::operator()( const std::vector<double>& y,\n                                                    std::vector<double>& dydt,\n                                                    double t ) throw ( bad_derivative_exception )\n{\n    // Note the std garuntees vetors are contigous so we can convert to array by\n    // taking the address of the first value.\n    int status = modelptr->calcderivs( t, &y[0], &dydt[0] );\n\n    if( status != ODE_SUCCESS ) {\n        bad_derivative_exception e(status);\n        throw e;\n    }\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief              Observer callback called by ODE solver when a successful\n *                      step has been taken.\n *  \\details            We use this callback to update our state variable time (t)\n *                      and in principle carbon pools (c) however the later is\n *                      already updated by the solver (pass by reference) so we will\n *                      skip copying here.\n *  \\param[in] y        pools\n *  \\param[in] t        time\n */\nvoid CarbonCycleSolver::ODEEvalFunctor::operator()( const std::vector<double>& y, double t ) {\n    // copy the current time to the original in CarbonCycleSolver\n    (*this->t) = t;\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief Support function for gsl_ode failure\n *  \\param[in] stat     failure code\n *  \\param[in] t0       start of time step\n *  \\param[in] tmid     middle of time step\n *  \\exception          will always happen; gsl solver has failed\n */\nvoid CarbonCycleSolver::failure( int stat, double t0, double tmid ) throw( h_exception ) {\n    H_LOG( logger, Logger::SEVERE ) << \"gsl_ode_evolve_apply failed at t= \" <<\n    t0 << \"  tinit= \" << t << \"  tmid = \" << tmid << \"  last dt= \" <<\n    dt << \"\\nError code: \" << stat << \"\\ncvals:\\n\";\n    for( int i=0; i<nc; ++i )\n        H_LOG( logger,Logger::SEVERE ) << c[ i ] << \"  \";\n    H_LOG( logger,Logger::SEVERE ) << std::endl;\n    H_THROW( \"gsl_ode_evolve_apply failed.\" );\n}\n\n//------------------------------------------------------------------------------\n// documentation is inherited\nvoid CarbonCycleSolver::run( const double tnew ) throw ( h_exception )\n{\n    if(tnew <= t) {\n        H_LOG(logger, Logger::SEVERE) << \"run(): tnew= \" << tnew << \"   t= \" << t << std::endl;\n    }\n    H_ASSERT( tnew > t, \"solver tnew is not greater than t\" );\n    \n    // Get the initial state data from the box model. c will be filled in\n    // Note that we rely on the box model to handle the units.  Inside the\n    // solver we strip the unit values and work with raw numbers.\n    cmodel->getCValues( t, &c[0] );\n\n    double t0   = t;  // stash this in case we need to report & diagnose an error\n    // Now integrate from the beginning of the time step using the updated\n    // slow params.  Note we can discard t0 and the values in cc\n    cmodel->slowparameval( t, &c[0] );\n    int retry = 0;\n    \n    H_LOG( logger, Logger::DEBUG ) << \"Entering ODE solver \" << t << \"->\" << tnew << std::endl;\n    while( t < tnew && retry < MAX_CARBON_MODEL_RETRIES ) {\n\n        H_LOG( logger, Logger::DEBUG ) << \"Resetting evolver and stepper\" << std::endl;\n        double t_start = t;\n        double t_target = tnew;\n        \n        while( t < t_target && retry < MAX_CARBON_MODEL_RETRIES ) {\n            H_LOG( logger, Logger::NOTICE ) << \"Attempting ODE solver \" << t << \"->\" << t_target << \" (\" << t0 << \"->\" << tnew << \")\" << std::endl;\n            \n            int stat = ODE_SUCCESS;\n            ODEEvalFunctor odeFunctor( cmodel, &t );\n            try {\n                using namespace boost::numeric::odeint;\n                typedef runge_kutta_dopri5<std::vector<double> > error_stepper_type;\n                integrate_adaptive( make_controlled<error_stepper_type>( eps_abs, eps_rel ),\n                         odeFunctor, c, t_start, t_target, dt, odeFunctor );\n            } catch( bad_derivative_exception& e ) {\n                stat = e.errorFlag;\n            }\n            \n            if( stat == CARBON_CYCLE_RETRY ) {\n                H_LOG( logger, Logger::NOTICE ) << \"Carbon model requests retry #\" << ++retry << \" at t= \" << t << std::endl;\n                t_target = t_start + ( t_target - t_start ) / 2.0;\n                t = t_start;\n                \n                dt = t_target - t;\n                cmodel->getCValues( t, &c[0] );     // reset pools and inform model of new starting point\n                H_LOG( logger, Logger::NOTICE ) << \"New target is \" << t_target << std::endl;\n            } else if( stat != ODE_SUCCESS )\n                failure( stat, t_start, t_target );\n        }\n        \n        // We have exited GSL solver loop, but did we make it?\n        if( retry < MAX_CARBON_MODEL_RETRIES ) {\n            H_LOG( logger, Logger::NOTICE ) << \"Success: we have reached \" << t_target << std::endl;\n\n            retry = 0;\n            cmodel->stashCValues( t, &c[0] );   // update state\n        } else {\n            H_LOG( logger, Logger::SEVERE ) << \"Failure after failure: t is \" << t << \"; we have not reached \" << t_target << std::endl;\n            \n        }\n    }\n    H_ASSERT( t == tnew, \"solver failure: t != tnew\" );\n    \n    H_LOG( logger, Logger::NOTICE ) << \"ODE solver success at t= \" << t <<\n    \"  last dt= \" << dt << std::endl;\n    H_LOG( logger, Logger::DEBUG ) << \"cvals\\terrors\\n\";\n\n    cmodel->record_state(tnew);\n    \n    H_LOG( logger, Logger::NOTICE ) << std::endl;\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief      Run the carbon cycle to steady state, if possible\n *  \\exception  epsilon must be >0\n *\n *  We normally want the carbon model to be in steady state, i.e. with unchanging\n *  carbon pools, at the end of the preindustrial period before the main run.\n *  To reach this point, run the carbon model until all dc/dt are ~0.\n */\nbool CarbonCycleSolver::run_spinup( const int step ) throw( h_exception )\n{\n    \n    if( !in_spinup ) {  // first time\n        in_spinup = true;\n        t = step-1;\n        c_original.resize(nc);\n        c_old.resize(nc);\n        c_new.resize(nc);\n        dcdt.resize(nc);\n        // initialize to zero\n        for(int i=0; i<nc; ++i)\n          c_original[i] = c_old[i] = c_new[i] = dcdt[i] = 0.0;\n        \n        cmodel->getCValues( t, &c_original[0] );\n        cmodel->record_state(t);\n    }\n    \n    cmodel->getCValues( t, &c_old[0] );\n    run( step );\n    cmodel->getCValues( step, &c_new[0] );\n    \n    int max_dcdt_pool = 0;\n    double max_dcdt = 0.0;\n    \n    for( int i=0; i<nc; i++ ) {     // find the biggest difference\n        dcdt[ i ] = fabs( c_new[ i ] - c_old[ i ] );\n        c_old[ i ] = c_new[ i ];\n        if (dcdt[ i ] > max_dcdt) {\n            max_dcdt = dcdt[i];\n        }\n    }\n\n    bool spunup = ( max_dcdt < eps_spinup.value( U_PGC ) );\n    \n    if( spunup ) {\n        Logger& glog = core->getGlobalLogger();\n        H_LOG( glog, Logger::NOTICE ) << \"Carbon model is spun up after \" << step << \" steps\" << std::endl;\n        H_LOG( logger, Logger::NOTICE ) << \"Carbon model spun up after \" << step << \" steps. Max residual dc/dt=\"\n        << max_dcdt << \" (pool \" << max_dcdt_pool << \")\" << std::endl;\n        for( int i=0; i<nc; i++ ) {\n            H_LOG( logger, Logger::NOTICE ) << \"New pool \" << i << \":\" << c_new[ i ]\n            << \" (delta=\" << c_new[ i ]-c_original[ i ] << \")\" << std::endl;\n        }\n        t = core->getStartDate();\n        H_LOG( logger, Logger::NOTICE ) << \"Resetting solver time counter to t= \" << t << std::endl;\n    }\n\n    // Record the state as the state at the model start time.  This\n    // will be repeatedly overwritten until the spinup is complete.\n    cmodel->record_state(core->getStartDate());\n    \n    return spunup;\n}\n\n//------------------------------------------------------------------------------\n/*! \\brief visitor accept code\n */\nvoid CarbonCycleSolver::accept( AVisitor* visitor )\n{\n    visitor->visit( this );\n}\n\n}\n", "meta": {"hexsha": "740e0bcefa1ccbd34ef299a87a8a457d76bf8601", "size": 14267, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/carbon-cycle-solver.cpp", "max_stars_repo_name": "bvegawe/hector", "max_stars_repo_head_hexsha": "fddfed55c262edf1eb068a4ef63e48bc35d05ff8", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/carbon-cycle-solver.cpp", "max_issues_repo_name": "bvegawe/hector", "max_issues_repo_head_hexsha": "fddfed55c262edf1eb068a4ef63e48bc35d05ff8", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/carbon-cycle-solver.cpp", "max_forks_repo_name": "bvegawe/hector", "max_forks_repo_head_hexsha": "fddfed55c262edf1eb068a4ef63e48bc35d05ff8", "max_forks_repo_licenses": ["ECL-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4555256065, "max_line_length": 147, "alphanum_fraction": 0.5309455387, "num_tokens": 3435, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.40033862300303763}}
{"text": "//=================================================================================================\n// Copyright (c) 2011, Johannes Meyer, TU Darmstadt\n// All rights reserved.\n\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//     * Redistributions of source code must retain the above copyright\n//       notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above copyright\n//       notice, this list of conditions and the following disclaimer in the\n//       documentation and/or other materials provided with the distribution.\n//     * Neither the name of the Flight Systems and Automatic Control group,\n//       TU Darmstadt, nor the names of its contributors may be used to\n//       endorse or promote products derived from this software without\n//       specific prior written permission.\n\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//=================================================================================================\n\n#include <hector_pose_estimation/measurements/baro.h>\n#include <hector_pose_estimation/filter/set_filter.h>\n\n#include <boost/bind.hpp>\n\nnamespace hector_pose_estimation {\n\ntemplate class Measurement_<BaroModel>;\n\nBaroModel::BaroModel()\n{\n  stddev_ = 1.0;\n  qnh_ = 1013.25;\n  parameters().add(\"qnh\", qnh_);\n}\n\nBaroModel::~BaroModel() {}\n\nvoid BaroModel::getExpectedValue(MeasurementVector& y_pred, const State& state)\n{\n  y_pred(0) = qnh_ * pow(1.0 - (0.0065 * (state.getPosition().z() + getElevation())) / 288.15, 5.255);\n}\n\nvoid BaroModel::getStateJacobian(MeasurementMatrix& C, const State& state, bool)\n{\n  if (state.position()) {\n    state.position()->cols(C)(0,Z) = qnh_ * 5.255 * pow(1.0 - (0.0065 * (state.getPosition().z() + getElevation())) / 288.15, 4.255) * (-0.0065 / 288.15);\n  }\n}\n\ndouble BaroModel::getAltitude(const BaroUpdate& update)\n{\n  return 288.15 / 0.0065 * (1.0 - pow(update.getVector()(0) / qnh_, 1.0/5.255));\n}\n\nBaroUpdate::BaroUpdate() : qnh_(0) {}\nBaroUpdate::BaroUpdate(double pressure) : qnh_(0) { *this = pressure; }\nBaroUpdate::BaroUpdate(double pressure, double qnh) : qnh_(qnh) { *this = pressure; }\n\nBaro::Baro(const std::string &name)\n  : Measurement_<BaroModel>(name)\n  , HeightBaroCommon(this)\n{\n  parameters().add(\"auto_elevation\", auto_elevation_);\n}\n\nvoid Baro::onReset()\n{\n  HeightBaroCommon::onReset();\n}\n\nbool Baro::prepareUpdate(State &state, const Update &update) {\n  if (update.qnh() != 0) setQnh(update.qnh());\n  // Note: boost::bind is not real-time safe!\n  setElevation(resetElevation(state, boost::bind(&BaroModel::getAltitude, getModel(), update)));\n  return true;\n}\n\n} // namespace hector_pose_estimation\n", "meta": {"hexsha": "6a78dc6572c5e25961d41c853f7064885f14dd57", "size": 3494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hector_quadrotor/hector_pose_estimation_core/src/measurements/baro.cpp", "max_stars_repo_name": "Eashwar-S/Swarm_Drones", "max_stars_repo_head_hexsha": "1611c9a66ff0feb6d2ceed4518402e32064bf0f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-06-04T07:27:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T09:45:06.000Z", "max_issues_repo_path": "hector_quadrotor/hector_pose_estimation_core/src/measurements/baro.cpp", "max_issues_repo_name": "Eashwar-S/Swarm_Drones", "max_issues_repo_head_hexsha": "1611c9a66ff0feb6d2ceed4518402e32064bf0f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2020-11-24T13:19:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-29T12:48:35.000Z", "max_forks_repo_path": "hector_quadrotor/hector_pose_estimation_core/src/measurements/baro.cpp", "max_forks_repo_name": "Eashwar-S/Swarm_Drones", "max_forks_repo_head_hexsha": "1611c9a66ff0feb6d2ceed4518402e32064bf0f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-25T23:36:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-28T20:07:25.000Z", "avg_line_length": 39.7045454545, "max_line_length": 154, "alphanum_fraction": 0.6834573555, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4003386159047977}}
{"text": "/*\n//@HEADER\n// ************************************************************************\n//\n// solvers_linear_traits.hpp\n//                     \t\t  Pressio\n//                             Copyright 2019\n//    National Technology & Engineering Solutions of Sandia, LLC (NTESS)\n//\n// Under the terms of Contract DE-NA0003525 with NTESS, the\n// U.S. Government retains certain rights in this software.\n//\n// Pressio is licensed under BSD-3-Clause terms of use:\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions\n// are met:\n//\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its\n// contributors may be used to endorse or promote products derived\n// from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n// Questions? Contact Francesco Rizzi (fnrizzi@sandia.gov)\n//\n// ************************************************************************\n//@HEADER\n*/\n\n#ifndef SOLVERS_LINEAR_IMPL_SOLVERS_LINEAR_TRAITS_HPP_\n#define SOLVERS_LINEAR_IMPL_SOLVERS_LINEAR_TRAITS_HPP_\n\n#ifdef PRESSIO_ENABLE_TPL_EIGEN\n#include <Eigen/Core>\n#include <Eigen/IterativeLinearSolvers>\n#include <Eigen/Householder>\n#include <Eigen/QR>\n#include <Eigen/Sparse>\n#include <Eigen/SparseQR>\n#include <Eigen/OrderingMethods>\n#endif\n\nnamespace pressio{ namespace linearsolvers{\n\ntemplate <typename T>\nstruct Traits {\n  static constexpr bool direct        = false;\n  static constexpr bool iterative     = false;\n#ifdef PRESSIO_ENABLE_TPL_EIGEN\n  static constexpr bool eigen_enabled = false;\n#endif\n#ifdef PRESSIO_ENABLE_TPL_KOKKOS\n  static constexpr bool kokkos_enabled = false;\n#endif\n};\n\ntemplate <>\nstruct Traits<::pressio::linearsolvers::iterative::CG>\n{\n  static constexpr bool direct        = false;\n  static constexpr bool iterative     = true;\n\n#ifdef PRESSIO_ENABLE_TPL_EIGEN\n  template <\n    typename MatrixT,\n    typename PrecT = Eigen::DiagonalPreconditioner<typename MatrixT::Scalar>\n    >\n  using eigen_solver_type = Eigen::ConjugateGradient<MatrixT, Eigen::Lower, PrecT>;\n\n  static constexpr bool eigen_enabled = true;\n#endif\n};\n\ntemplate <>\nstruct Traits<::pressio::linearsolvers::iterative::Bicgstab>\n{\n  static constexpr bool direct        = false;\n  static constexpr bool iterative     = true;\n\n#ifdef PRESSIO_ENABLE_TPL_EIGEN\n  template <\n    typename MatrixT,\n    typename PrecT = Eigen::DiagonalPreconditioner<typename MatrixT::Scalar>\n    >\n  using eigen_solver_type = Eigen::BiCGSTAB<MatrixT, PrecT>;\n\n  static constexpr bool eigen_enabled = true;\n#endif\n};\n\ntemplate <>\nstruct Traits<::pressio::linearsolvers::iterative::LSCG>\n{\n  static constexpr bool direct        = false;\n  static constexpr bool iterative     = true;\n\n#ifdef PRESSIO_ENABLE_TPL_EIGEN\n  template <\n    typename MatrixT,\n    typename PrecT = Eigen::DiagonalPreconditioner<typename MatrixT::Scalar>\n  >\n  using eigen_solver_type = Eigen::LeastSquaresConjugateGradient<MatrixT, PrecT>;\n\n  static constexpr bool eigen_enabled = true;\n#endif\n};\n\ntemplate <>\nstruct Traits<::pressio::linearsolvers::direct::ColPivHouseholderQR>\n{\n\n  static constexpr bool iterative = false;\n  static constexpr bool direct = true;\n\n#ifdef PRESSIO_ENABLE_TPL_EIGEN\n  /* if matrix is dense, use Eigen::ColPivHouseholderQR.\n   * if the native matrix is sparse, then use Eigen::SparseQR.\n   * to use SparseQR, the matrix has to be:\n   * (a) sparse\n   * (b) column-major\n   * (c) compressed mode to use COLAMDOrdering\n  */\n  template <typename MatrixT>\n  using eigen_solver_type =\n    typename std::conditional<\n      pressio::is_sparse_matrix_eigen<MatrixT>::value &&\n      MatrixT::IsRowMajor==0,\n      Eigen::SparseQR<MatrixT, Eigen::COLAMDOrdering<typename MatrixT::StorageIndex>>,\n      Eigen::ColPivHouseholderQR<MatrixT>\n      >::type;\n\n  static constexpr bool eigen_enabled = true;\n#endif\n};\n\ntemplate <>\nstruct Traits<::pressio::linearsolvers::direct::HouseholderQR>\n{\n  static constexpr bool iterative = false;\n  static constexpr bool direct = true;\n\n#ifdef PRESSIO_ENABLE_TPL_EIGEN\n  template <typename MatrixT>\n  using eigen_solver_type = Eigen::HouseholderQR<MatrixT>;\n\n  static constexpr bool eigen_enabled = true;\n#endif\n};\n\ntemplate <>\nstruct Traits<::pressio::linearsolvers::direct::PartialPivLU>\n{\n  static constexpr bool iterative = false;\n  static constexpr bool direct = true;\n\n#ifdef PRESSIO_ENABLE_TPL_EIGEN\n  template <typename MatrixT>\n  using eigen_solver_type = Eigen::PartialPivLU<MatrixT>;\n\n  static constexpr bool eigen_enabled = true;\n#endif\n};\n\ntemplate <>\nstruct Traits<::pressio::linearsolvers::direct::potrsL>\n{\n  static constexpr bool iterative = false;\n  static constexpr bool direct = true;\n\n#ifdef PRESSIO_ENABLE_TPL_EIGEN\n  template <typename MatrixT>\n  using eigen_solver_type = Eigen::LLT<MatrixT, Eigen::Lower>;\n  static constexpr bool eigen_enabled = true;\n#endif\n\n#if defined PRESSIO_ENABLE_TPL_TRILINOS or defined PRESSIO_ENABLE_TPL_KOKKOS\n  static constexpr bool kokkos_enabled = true;\n#endif\n};\n\ntemplate <>\nstruct Traits<::pressio::linearsolvers::direct::potrsU>\n{\n  static constexpr bool direct = true;\n  static constexpr bool eigen_enabled = true;\n\n#ifdef PRESSIO_ENABLE_TPL_EIGEN\n  template <typename MatrixT>\n  using eigen_solver_type = Eigen::LLT<MatrixT, Eigen::Upper>;\n#endif\n\n#if defined PRESSIO_ENABLE_TPL_TRILINOS or defined PRESSIO_ENABLE_TPL_KOKKOS\n  static constexpr bool kokkos_enabled = true;\n#endif\n};\n\ntemplate <>\nstruct Traits<::pressio::linearsolvers::direct::getrs>\n{\n  static constexpr bool direct = true;\n#ifdef PRESSIO_ENABLE_TPL_EIGEN\n  static constexpr bool eigen_enabled = false;\n#endif\n\n#if defined PRESSIO_ENABLE_TPL_TRILINOS or defined PRESSIO_ENABLE_TPL_KOKKOS\n  static constexpr bool kokkos_enabled = true;\n#endif\n};\n\ntemplate <>\nstruct Traits<::pressio::linearsolvers::direct::geqrf>\n{\n  static constexpr bool direct = true;\n#ifdef PRESSIO_ENABLE_TPL_EIGEN\n  static constexpr bool eigen_enabled = false;\n#endif\n#if defined PRESSIO_ENABLE_TPL_TRILINOS or defined PRESSIO_ENABLE_TPL_KOKKOS\n  static constexpr bool kokkos_enabled = true;\n#endif\n};\n\n}}\n#endif  // SOLVERS_LINEAR_IMPL_SOLVERS_LINEAR_TRAITS_HPP_\n", "meta": {"hexsha": "fc4d8e46e9b863e86ed0138bb18439aef5bb4d33", "size": 7284, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tpls/pressio/include/pressio/solvers_linear/impl/solvers_linear_traits.hpp", "max_stars_repo_name": "fnrizzi/pressio-demoapps", "max_stars_repo_head_hexsha": "6ff10bbcf4d526610580940753c9620725bff1ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2019-11-11T13:17:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:31:31.000Z", "max_issues_repo_path": "tpls/pressio/include/pressio/solvers_linear/impl/solvers_linear_traits.hpp", "max_issues_repo_name": "fnrizzi/pressio-demoapps", "max_issues_repo_head_hexsha": "6ff10bbcf4d526610580940753c9620725bff1ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 303.0, "max_issues_repo_issues_event_min_datetime": "2019-09-30T10:15:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T08:24:04.000Z", "max_forks_repo_path": "tpls/pressio/include/pressio/solvers_linear/impl/solvers_linear_traits.hpp", "max_forks_repo_name": "fnrizzi/pressio-demoapps", "max_forks_repo_head_hexsha": "6ff10bbcf4d526610580940753c9620725bff1ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-07-07T03:32:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T05:21:42.000Z", "avg_line_length": 29.975308642, "max_line_length": 86, "alphanum_fraction": 0.7417627677, "num_tokens": 1698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4003386159047977}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n  @copyright 2016 NumScale SAS\n  @copyright 2016 J.T. Lapreste\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_MOD_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_MOD_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n    @ingroup group-arithmetic\n    Function object implementing mod capabilities\n\n    Computes the remainder of division.\n    The return value is x-n*y, where n is the value x/y,\n    truncated to \\f$-\\infty\\f$.\n\n    @par semantic:\n    For any given value @c x, @c y of type @c T:\n\n    @code\n    T r = mod(x, y);\n    @endcode\n\n    The code is similar to:\n\n    @code\n    T r = x-div(x, y, floor)*y;\n    @endcode\n\n    @see remainder, rem,  modulo\n\n  **/\n  const boost::dispatch::functor<tag::mod_> mod = {};\n} }\n#endif\n\n#include <boost/simd/function/scalar/mod.hpp>\n#include <boost/simd/function/simd/mod.hpp>\n\n#endif\n", "meta": {"hexsha": "b427184dffc2d7714edd5941647f39bb6663a022", "size": 1197, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/mod.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/function/mod.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/mod.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.0192307692, "max_line_length": 100, "alphanum_fraction": 0.5655806182, "num_tokens": 278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.4003386159047977}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_TWO_PROD_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_TWO_PROD_HPP_INCLUDED\n#include <boost/simd/include/functor.hpp>\n#include <boost/dispatch/include/functor.hpp>\n\n/*!\n  @file\n  @brief Definition of the two_prod function\n**/\n\nnamespace boost { namespace simd\n{\n  namespace tag\n  {\n    /// @brief Hierarchy tag for two_prod function\n    struct two_prod_ : ext::elementwise_<two_prod_>\n    {\n      typedef ext::elementwise_<two_prod_> parent;\n      template<class... Args>\n      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)\n      BOOST_AUTO_DECLTYPE_BODY( dispatching_two_prod_( ext::adl_helper(), static_cast<Args&&>(args)... ) )\n    };\n  }\n  namespace ext\n  {\n    template<class Site>\n    BOOST_FORCEINLINE generic_dispatcher<tag::two_prod_, Site> dispatching_two_prod_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)\n    {\n      return generic_dispatcher<tag::two_prod_, Site>();\n    }\n    template<class... Args>\n    struct impl_two_prod_;\n  }\n\n  /*!\n    @brief\n\n    For any two reals @c a0 and @c a1 two_prod computes two reals\n    @c r0 and @c r1 so that:\n\n    @code\n    r0 = a0* a1\n    r1 = r0 -(a0 * a1)\n    @endcode\n\n    using perfect arithmetic. Its main usage is to be able to compute\n    sum of reals and the residual error using IEEE 754 arithmetic.\n\n    @param a0 First parameter of the sum\n    @param a1 Second parameter of the sum\n\n    @return A Fusion Sequence containing @c a0+a1 and the residual.\n  **/\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::two_prod_, two_prod, 2)\n\n  /*!\n    @brief\n\n    For any two reals @c a0 and @c a1 two_prod computes two reals\n    @c r0 and @c r1 so that:\n\n    @code\n    r0 = a0 * a1\n    r1 = r0 -(a0 * a1)\n    @endcode\n\n    using perfect arithmetic. Its main usage is to be able to compute\n    sum of reals and the residual error using IEEE 754 arithmetic.\n\n    @param a0 First parameter of the sum\n    @param a1 Second parameter of the sum\n    @param a2 L-Value that will receive @c a0+a1\n\n    @return The sum residual.\n  **/\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION_TPL( tag::two_prod_, two_prod\n                                            , (A0 const&)(A1 const&)(A2&)\n                                            , 3\n                                            )\n\n  /*!\n    @brief\n\n    For any two reals @c a0 and @c a1 two_prod computes two reals\n    @c r0 and @c r1 so that:\n\n    @code\n    r0 = a0 * a1\n    r1 = r0 -(a0 * a1)\n    @endcode\n\n    using perfect arithmetic. Its main usage is to be able to compute\n    sum of reals and the residual error using IEEE 754 arithmetic.\n\n    @param a0 First parameter of the sum\n    @param a1 Second parameter of the sum\n    @param a2 L-Value that will receive @c a0+a1.\n    @param a3 L-Value that will receive @c a0+a1 residual.\n  **/\n  BOOST_DISPATCH_FUNCTION_IMPLEMENTATION_TPL( tag::two_prod_, two_prod\n                                            , (A0 const&)(A1 const&)(A2&)(A3&)\n                                            , 4\n                                            )\n} }\n\n#endif\n", "meta": {"hexsha": "73b003e64141185593a016cdb8deeb2cad68a7de", "size": 3576, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/two_prod.hpp", "max_stars_repo_name": "feelpp/nt2", "max_stars_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/two_prod.hpp", "max_issues_repo_name": "feelpp/nt2", "max_issues_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/two_prod.hpp", "max_forks_repo_name": "feelpp/nt2", "max_forks_repo_head_hexsha": "4d121e2c7450f24b735d6cff03720f07b4b2146c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 31.0956521739, "max_line_length": 140, "alphanum_fraction": 0.5931208054, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.4001852911778587}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// extended_p_square_quantile.hpp\n//\n//  Copyright 2005 Daniel Egloff. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_ACCUMULATORS_STATISTICS_EXTENDED_SINGLE_QUANTILE_HPP_DE_01_01_2006\n#define BOOST_ACCUMULATORS_STATISTICS_EXTENDED_SINGLE_QUANTILE_HPP_DE_01_01_2006\n\n#include <vector>\n#include <functional>\n#include <boost/throw_exception.hpp>\n#include <boost/range/begin.hpp>\n#include <boost/range/end.hpp>\n#include <boost/range/iterator_range.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/permutation_iterator.hpp>\n#include <boost/parameter/keyword.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/accumulators/framework/accumulator_base.hpp>\n#include <boost/accumulators/framework/extractor.hpp>\n#include <boost/accumulators/numeric/functional.hpp>\n#include <boost/accumulators/framework/parameters/sample.hpp>\n#include <boost/accumulators/framework/depends_on.hpp>\n#include <boost/accumulators/statistics_fwd.hpp>\n#include <boost/accumulators/statistics/count.hpp>\n#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>\n#include <boost/accumulators/statistics/extended_p_square.hpp>\n#include <boost/accumulators/statistics/weighted_extended_p_square.hpp>\n#include <boost/accumulators/statistics/times2_iterator.hpp>\n\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable: 4127) // conditional expression is constant\n#endif\n\nnamespace boost { namespace accumulators\n{\n\nnamespace impl\n{\n    ///////////////////////////////////////////////////////////////////////////////\n    // extended_p_square_quantile_impl\n    //  single quantile estimation\n    /**\n        @brief Quantile estimation using the extended \\f$P^2\\f$ algorithm for weighted and unweighted samples\n\n        Uses the quantile estimates calculated by the extended \\f$P^2\\f$ algorithm to compute\n        intermediate quantile estimates by means of quadratic interpolation.\n\n        @param quantile_probability The probability of the quantile to be estimated.\n    */\n    template<typename Sample, typename Impl1, typename Impl2> // Impl1: weighted/unweighted // Impl2: linear/quadratic\n    struct extended_p_square_quantile_impl\n      : accumulator_base\n    {\n        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;\n        typedef std::vector<float_type> array_type;\n        typedef iterator_range<\n            detail::lvalue_index_iterator<\n                permutation_iterator<\n                    typename array_type::const_iterator\n                  , detail::times2_iterator\n                >\n            >\n        > range_type;\n        // for boost::result_of\n        typedef float_type result_type;\n\n        template<typename Args>\n        extended_p_square_quantile_impl(Args const &args)\n          : probabilities(\n                boost::begin(args[extended_p_square_probabilities])\n              , boost::end(args[extended_p_square_probabilities])\n            )\n        {\n        }\n\n        template<typename Args>\n        result_type result(Args const &args) const\n        {\n            typedef\n                typename mpl::if_<\n                    is_same<Impl1, weighted>\n                  , tag::weighted_extended_p_square\n                  , tag::extended_p_square\n                >::type\n            extended_p_square_tag;\n\n            extractor<extended_p_square_tag> const some_extended_p_square = {};\n\n            array_type heights(some_extended_p_square(args).size());\n            std::copy(some_extended_p_square(args).begin(), some_extended_p_square(args).end(), heights.begin());\n\n            this->probability = args[quantile_probability];\n\n            typename array_type::const_iterator iter_probs = std::lower_bound(this->probabilities.begin(), this->probabilities.end(), this->probability);\n            std::size_t dist = std::distance(this->probabilities.begin(), iter_probs);\n            typename array_type::const_iterator iter_heights = heights.begin() + dist;\n\n            // If this->probability is not in a valid range return NaN or throw exception\n            if (this->probability < *this->probabilities.begin() || this->probability > *(this->probabilities.end() - 1))\n            {\n                if (std::numeric_limits<result_type>::has_quiet_NaN)\n                {\n                    return std::numeric_limits<result_type>::quiet_NaN();\n                }\n                else\n                {\n                    std::ostringstream msg;\n                    msg << \"probability = \" << this->probability << \" is not in valid range (\";\n                    msg << *this->probabilities.begin() << \", \" << *(this->probabilities.end() - 1) << \")\";\n                    boost::throw_exception(std::runtime_error(msg.str()));\n                    return Sample(0);\n                }\n\n            }\n\n            if (*iter_probs == this->probability)\n            {\n                return heights[dist];\n            }\n            else\n            {\n                result_type res;\n\n                if (is_same<Impl2, linear>::value)\n                {\n                    /////////////////////////////////////////////////////////////////////////////////\n                    // LINEAR INTERPOLATION\n                    //\n                    float_type p1 = *iter_probs;\n                    float_type p0 = *(iter_probs - 1);\n                    float_type h1 = *iter_heights;\n                    float_type h0 = *(iter_heights - 1);\n\n                    float_type a = numeric::fdiv(h1 - h0, p1 - p0);\n                    float_type b = h1 - p1 * a;\n\n                    res = a * this->probability + b;\n                }\n                else\n                {\n                    /////////////////////////////////////////////////////////////////////////////////\n                    // QUADRATIC INTERPOLATION\n                    //\n                    float_type p0, p1, p2;\n                    float_type h0, h1, h2;\n\n                    if ( (dist == 1 || *iter_probs - this->probability <= this->probability - *(iter_probs - 1) ) && dist != this->probabilities.size() - 1 )\n                    {\n                        p0 = *(iter_probs - 1);\n                        p1 = *iter_probs;\n                        p2 = *(iter_probs + 1);\n                        h0 = *(iter_heights - 1);\n                        h1 = *iter_heights;\n                        h2 = *(iter_heights + 1);\n                    }\n                    else\n                    {\n                        p0 = *(iter_probs - 2);\n                        p1 = *(iter_probs - 1);\n                        p2 = *iter_probs;\n                        h0 = *(iter_heights - 2);\n                        h1 = *(iter_heights - 1);\n                        h2 = *iter_heights;\n                    }\n\n                    float_type hp21 = numeric::fdiv(h2 - h1, p2 - p1);\n                    float_type hp10 = numeric::fdiv(h1 - h0, p1 - p0);\n                    float_type p21  = numeric::fdiv(p2 * p2 - p1 * p1, p2 - p1);\n                    float_type p10  = numeric::fdiv(p1 * p1 - p0 * p0, p1 - p0);\n\n                    float_type a = numeric::fdiv(hp21 - hp10, p21 - p10);\n                    float_type b = hp21 - a * p21;\n                    float_type c = h2 - a * p2 * p2 - b * p2;\n\n                    res = a * this->probability * this-> probability + b * this->probability + c;\n                }\n\n                return res;\n            }\n\n        }\n\n    public:\n        // make this accumulator serializeable\n        // TODO: do we need to split to load/save and verify that the parameters did not change?\n        template<class Archive>\n        void serialize(Archive & ar, const unsigned int file_version)\n        { \n            ar & probabilities;\n            ar & probability;\n        }\n\n    private:\n\n        array_type probabilities;\n        mutable float_type probability;\n\n    };\n\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::extended_p_square_quantile\n//\nnamespace tag\n{\n    struct extended_p_square_quantile\n      : depends_on<extended_p_square>\n    {\n        typedef accumulators::impl::extended_p_square_quantile_impl<mpl::_1, unweighted, linear> impl;\n    };\n    struct extended_p_square_quantile_quadratic\n      : depends_on<extended_p_square>\n    {\n        typedef accumulators::impl::extended_p_square_quantile_impl<mpl::_1, unweighted, quadratic> impl;\n    };\n    struct weighted_extended_p_square_quantile\n      : depends_on<weighted_extended_p_square>\n    {\n        typedef accumulators::impl::extended_p_square_quantile_impl<mpl::_1, weighted, linear> impl;\n    };\n    struct weighted_extended_p_square_quantile_quadratic\n      : depends_on<weighted_extended_p_square>\n    {\n        typedef accumulators::impl::extended_p_square_quantile_impl<mpl::_1, weighted, quadratic> impl;\n    };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::extended_p_square_quantile\n// extract::weighted_extended_p_square_quantile\n//\nnamespace extract\n{\n    extractor<tag::extended_p_square_quantile> const extended_p_square_quantile = {};\n    extractor<tag::extended_p_square_quantile_quadratic> const extended_p_square_quantile_quadratic = {};\n    extractor<tag::weighted_extended_p_square_quantile> const weighted_extended_p_square_quantile = {};\n    extractor<tag::weighted_extended_p_square_quantile_quadratic> const weighted_extended_p_square_quantile_quadratic = {};\n\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(extended_p_square_quantile)\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(extended_p_square_quantile_quadratic)\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_extended_p_square_quantile)\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_extended_p_square_quantile_quadratic)\n}\n\nusing extract::extended_p_square_quantile;\nusing extract::extended_p_square_quantile_quadratic;\nusing extract::weighted_extended_p_square_quantile;\nusing extract::weighted_extended_p_square_quantile_quadratic;\n\n// extended_p_square_quantile(linear) -> extended_p_square_quantile\ntemplate<>\nstruct as_feature<tag::extended_p_square_quantile(linear)>\n{\n    typedef tag::extended_p_square_quantile type;\n};\n\n// extended_p_square_quantile(quadratic) -> extended_p_square_quantile_quadratic\ntemplate<>\nstruct as_feature<tag::extended_p_square_quantile(quadratic)>\n{\n    typedef tag::extended_p_square_quantile_quadratic type;\n};\n\n// weighted_extended_p_square_quantile(linear) -> weighted_extended_p_square_quantile\ntemplate<>\nstruct as_feature<tag::weighted_extended_p_square_quantile(linear)>\n{\n    typedef tag::weighted_extended_p_square_quantile type;\n};\n\n// weighted_extended_p_square_quantile(quadratic) -> weighted_extended_p_square_quantile_quadratic\ntemplate<>\nstruct as_feature<tag::weighted_extended_p_square_quantile(quadratic)>\n{\n    typedef tag::weighted_extended_p_square_quantile_quadratic type;\n};\n\n// for the purposes of feature-based dependency resolution,\n// extended_p_square_quantile and weighted_extended_p_square_quantile\n// provide the same feature as quantile\ntemplate<>\nstruct feature_of<tag::extended_p_square_quantile>\n  : feature_of<tag::quantile>\n{\n};\ntemplate<>\nstruct feature_of<tag::extended_p_square_quantile_quadratic>\n  : feature_of<tag::quantile>\n{\n};\n// So that extended_p_square_quantile can be automatically substituted with\n// weighted_extended_p_square_quantile when the weight parameter is non-void\ntemplate<>\nstruct as_weighted_feature<tag::extended_p_square_quantile>\n{\n    typedef tag::weighted_extended_p_square_quantile type;\n};\n\ntemplate<>\nstruct feature_of<tag::weighted_extended_p_square_quantile>\n  : feature_of<tag::extended_p_square_quantile>\n{\n};\n\n// So that extended_p_square_quantile_quadratic can be automatically substituted with\n// weighted_extended_p_square_quantile_quadratic when the weight parameter is non-void\ntemplate<>\nstruct as_weighted_feature<tag::extended_p_square_quantile_quadratic>\n{\n    typedef tag::weighted_extended_p_square_quantile_quadratic type;\n};\ntemplate<>\nstruct feature_of<tag::weighted_extended_p_square_quantile_quadratic>\n  : feature_of<tag::extended_p_square_quantile_quadratic>\n{\n};\n\n}} // namespace boost::accumulators\n\n#ifdef _MSC_VER\n# pragma warning(pop)\n#endif\n\n#endif\n", "meta": {"hexsha": "f57304cd04e5a4c13f0ecd2640a0723d2b1f8721", "size": 12522, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/accumulators/statistics/extended_p_square_quantile.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/accumulators/statistics/extended_p_square_quantile.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/accumulators/statistics/extended_p_square_quantile.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 37.7168674699, "max_line_length": 157, "alphanum_fraction": 0.6279348347, "num_tokens": 2593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4001761066514151}}
{"text": "\n#include <deal.II/base/function.h>\n#include <deal.II/base/function_parser.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/base/table_handler.h>\n\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/lac/dynamic_sparsity_pattern.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/petsc_parallel_sparse_matrix.h>\n#include <deal.II/lac/petsc_parallel_vector.h>\n#include <deal.II/lac/petsc_solver.h>\n#include <deal.II/lac/petsc_precondition.h>\n#include <deal.II/lac/sparsity_tools.h>\n#include <deal.II/lac/vector.h>\n\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n\n#include <deal.II/distributed/grid_refinement.h>\n#include <deal.II/distributed/tria.h>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/fe/fe_system.h>\n#include <deal.II/fe/fe_q.h>\n\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/vector_tools.h>\n\n#include <mandy/elastic_tensor.h>\n#include <mandy/lattice_tensor.h>\n\n#include <mandy/crystal_symmetry_group.h>\n\n#include <fstream>\n#include <iostream>\n\n#include <algorithm>    // std::transform\n#include <functional>   // std::plus\n\nnamespace mandy\n{\n  /**\n   * Solve the system Ax=b, where A is the vector-valued operator of\n   * the Laplace-type and b is a linear function.\n   */\n  template <int dim>\n  class ElasticProblem\n  {\n  public:\n\n    /**\n     * Class constructor.\n     */\n    ElasticProblem (const std::string &prm);\n\n    /**\n     * Class destructor.\n     */\n    ~ElasticProblem ();\n\n    /**\n     * Wrapper function, that controls the order of excecution.\n     */\n    void run ();\n\n    /**\n     * Get coefficients from the parameter file specified at run time.\n     */\n    void get_coefficients ();\n    \n  private:\n    \n    /**\n     * Make intial coarse grid.\n     */\n    void make_coarse_grid ();\n\n    /**\n     * Setup system matrices and vectors.\n     */\n    void setup_system ();\n\n    /**\n     * Assemble system matrices and vectors.\n     */\n    void assemble_system();\n\n    /**\n     * Solve the linear algebra system.\n     */\n    unsigned int solve ();\n    \n    /**\n     * Output results, ie., finite element functions and derived\n     * quantitites for this cycle.\n     */\n    void output_results (const unsigned int cycle);\n\n    /**\n     * Refine grid based on Kelly's error estimator working on the\n     * material id (solution vector).\n     */\n    void refine_grid ();\n    \n    /**\n     * MPI communicator.\n     */\n    MPI_Comm mpi_communicator;\n\n    /**\n     * A distributed grid on which all computations are done.\n     */\n    dealii::parallel::distributed::Triangulation<dim> triangulation;\n\n    /**\n     * Scalar DoF handler primarily used for interpolating material\n     * identification.\n     */\n    dealii::DoFHandler<dim> dof_handler;\n\n    /**\n     * Scalar valued finite element primarily used for interpolating\n     * material iudentification.\n     */\n    dealii::FESystem<dim> finite_element;\n\n    /**\n     * Index set of locally owned DoFs.\n     */\n    dealii::IndexSet locally_owned_dofs;\n\n    /**\n     * Index set of locally relevant DoFs.\n     */\n    dealii::IndexSet locally_relevant_dofs;\n\n    /**\n     * A list of (hanging node) constraints.\n     */\n    dealii::ConstraintMatrix constraints;\n    \n    /**\n     * System matrix - a mass matrix.\n     */\n    dealii::PETScWrappers::MPI::SparseMatrix system_matrix;\n\n    /**\n     * Locally relevant solution vector.\n     */\n    dealii::PETScWrappers::MPI::Vector locally_relevant_solution;\n\n    /**\n     * System right hand side function - interpolated function.\n     */\n    dealii::PETScWrappers::MPI::Vector system_rhs;\n    \n    /**\n     * Parallel iostream.\n     */\n    dealii::ConditionalOStream pcout;\n\n    /**\n     * Stop clock.\n     */\n    dealii::TimerOutput timer;\n    \n    /**\n     * Input parameter file.\n     */\n    dealii::ParameterHandler parameters;\n    \n    /**\n     * Tensor of elastic coefficients.\n     */\n    mandy::Physics::ElasticTensor<mandy::CrystalSymmetryGroup::wurtzite> elastic_tensor;\n\n    /**\n     * Vector of elastic coefficients.\n     */\n    std::vector<double> elastic_coefficients;\n\n    /**\n     * Tensor of lattice coefficients.\n     */\n    mandy::Physics::LatticeTensor<mandy::CrystalSymmetryGroup::wurtzite> lattice_tensor;\n\n    /**\n     * Vector of lattice coefficients.\n     */\n    std::vector<double> lattice_coefficients;\n\n  }; // LinearElasticity\n\n\n  /**\n   * Class constructor.\n   */\n  template <int dim>\n  ElasticProblem<dim>::ElasticProblem (const std::string &prm)\n    :\n    mpi_communicator (MPI_COMM_WORLD),\n    triangulation (mpi_communicator,\n                   typename dealii::Triangulation<dim>::MeshSmoothing\n                   (dealii::Triangulation<dim>::smoothing_on_refinement |\n                    dealii::Triangulation<dim>::smoothing_on_coarsening)),\n    dof_handler (triangulation),\n    finite_element (dealii::FE_Q<dim> (2), dim),\n    // ---\n    pcout (std::cout, (dealii::Utilities::MPI::this_mpi_process (mpi_communicator) == 0)),\n    timer (mpi_communicator, pcout,\n\t   dealii::TimerOutput::summary,\n\t   dealii::TimerOutput::wall_times)\n  {\n    parameters.enter_subsection (\"Material\");\n    {\n      parameters.declare_entry (\"Material function\", \"0\",\n\t\t\t\tdealii::Patterns::Anything (),\n\t\t\t\t\"A functional description of the material.\");\n\n      parameters.declare_entry (\"Lattice background\",\n\t\t\t\t\"0, 0, 0\",\n\t\t\t\tdealii::Patterns::List (dealii::Patterns::Anything (), 1, 3, \",\"),\n\t\t\t\t\"Size of the lattice of the background\");\n\n      parameters.declare_entry (\"Lattice inclusion\",\n\t\t\t\t\"0, 0, 0\",\n\t\t\t\tdealii::Patterns::List (dealii::Patterns::Anything (), 1, 3, \",\"),\n\t\t\t\t\"Size of the lattice of an inclusion\");\n      \n      parameters.declare_entry (\"Elastic background\",\n\t\t\t\t\"0, 0, 0, 0, 0\",\n\t\t\t\tdealii::Patterns::List (dealii::Patterns::Anything (), 1, 5, \",\"),\n\t\t\t\t\"Elastic coefficients of the background\");\n      \n      parameters.declare_entry (\"Elastic inclusion\",\n\t\t\t\t\"0, 0, 0, 0, 0\",\n\t\t\t\tdealii::Patterns::List (dealii::Patterns::Anything (), 1, 5, \",\"),\n\t\t\t\t\"Elastic coefficients of an inclusion\");\n    }\n    parameters.leave_subsection ();\n    \n    parameters.parse_input (prm);\n  }\n\n  \n  /**\n   * Class destructor.\n   */\n  template <int dim>\n  ElasticProblem<dim>::~ElasticProblem ()\n  {\n    // Wipe DoF handlers.\n    dof_handler.clear ();\n  }\n  \n\n  /**\n   * Setup system matrices and vectors.\n   */\n  template <int dim>\n  void ElasticProblem<dim>::setup_system ()\n  {\n    dealii::TimerOutput::Scope time (timer, \"setup system\");\n\n    // Determine locally relevant DoFs.\n    dof_handler.distribute_dofs (finite_element);\n    locally_owned_dofs = dof_handler.locally_owned_dofs ();\n    dealii::DoFTools::extract_locally_relevant_dofs (dof_handler, locally_relevant_dofs);\n\n    // Initialise distributed vectors.\n    locally_relevant_solution.reinit (locally_owned_dofs, locally_relevant_dofs,\n\t\t\t\t      mpi_communicator);\n    system_rhs.reinit (locally_owned_dofs,\n\t\t       mpi_communicator);\n\n    // Setup hanging node constraints.\n    constraints.clear ();\n    constraints.reinit (locally_relevant_dofs);\n\n    dealii::DoFTools::make_hanging_node_constraints (dof_handler, constraints);\n    dealii::DoFTools::make_zero_boundary_constraints (dof_handler, constraints);\n    constraints.close ();\n\n    // Finally, create a distributed sparsity pattern and initialise\n    // the system matrix from that.\n    dealii::DynamicSparsityPattern dsp (locally_relevant_dofs);\n    dealii::DoFTools::make_sparsity_pattern (dof_handler, dsp, constraints, false);\n    dealii::SparsityTools::distribute_sparsity_pattern (dsp,\n\t\t\t\t\t\t\tdof_handler.n_locally_owned_dofs_per_processor (),\n\t\t\t\t\t\t\tmpi_communicator,\n\t\t\t\t\t\t\tlocally_relevant_dofs);\n\n    system_matrix.reinit (locally_owned_dofs, locally_owned_dofs,\n                          dsp, mpi_communicator);\n\n  }\n\n  \n  /**\n   * Assemble the linear algebra system.\n   */\n  template <int dim>\n  void\n  ElasticProblem<dim>::assemble_system ()\n  {\n    dealii::TimerOutput::Scope time (timer, \"assemble system\");\n   \n    // Define quadrature rule to be used.\n    const dealii::QGauss<dim> quadrature_formula (3);\n    \n    dealii::FEValues<dim> fe_values (finite_element, quadrature_formula,\n\t\t\t\t     dealii::update_values            |\n\t\t\t\t     dealii::update_gradients         |\n\t\t\t\t     dealii::update_quadrature_points |\n\t\t\t\t     dealii::update_JxW_values);\n    \n    const unsigned int dofs_per_cell = finite_element.dofs_per_cell;\n    const unsigned int n_q_points    = quadrature_formula.size ();\n\n    dealii::FullMatrix<double> cell_matrix (dofs_per_cell, dofs_per_cell); \n    dealii::Vector<double> cell_vector (dofs_per_cell); \n    std::vector<dealii::types::global_dof_index> local_dof_indices (dofs_per_cell);\n    \n    // A vector of material values at each quadrature point and the\n    // function to be parsed from the input file.\n    dealii::FunctionParser<dim> material_function;\n\n    parameters.enter_subsection (\"Material\");\n    {\n      material_function.initialize (dealii::FunctionParser<dim>::default_variable_names (),\n\t\t\t\t    parameters.get (\"Material function\"),\n\t\t\t\t    typename dealii::FunctionParser<dim>::ConstMap ());\n    }\n    parameters.leave_subsection ();\n\n    std::vector<double> material_function_values (n_q_points);\n\n    // Get lattice parameters from file.\n    std::vector<double> lattice_coefficients_background;\n    std::vector<double> lattice_coefficients_inclusion;\n\n    // Get elastic coefficients from input file.\n    std::vector<double> elastic_coefficients_background;\n    std::vector<double> elastic_coefficients_inclusion;\n    \n    parameters.enter_subsection (\"Material\");\n    {\n      lattice_coefficients_background = dealii::Utilities::string_to_double\n\t(dealii::Utilities::split_string_list (parameters.get (\"Lattice background\"), ','));\n\n      lattice_coefficients_inclusion = dealii::Utilities::string_to_double\n\t(dealii::Utilities::split_string_list (parameters.get (\"Lattice inclusion\"), ','));\n\n      elastic_coefficients_background = dealii::Utilities::string_to_double\n\t(dealii::Utilities::split_string_list (parameters.get (\"Elastic background\"), ','));\n\n      elastic_coefficients_inclusion = dealii::Utilities::string_to_double\n\t(dealii::Utilities::split_string_list (parameters.get (\"Elastic inclusion\"), ','));\n    }\n    parameters.leave_subsection ();\n    \n    AssertThrow (elastic_coefficients_background.size ()==elastic_coefficients_inclusion.size (),\n\t\t dealii::ExcDimensionMismatch (elastic_coefficients_background.size (),\n\t\t\t\t\t       elastic_coefficients_inclusion.size ()));\n   \n    typename dealii::DoFHandler<dim>::active_cell_iterator\n      cell = dof_handler.begin_active (),\n      endc = dof_handler.end ();\n    \n    for (; cell!=endc; ++cell)\n      if (cell->subdomain_id () == dealii::Utilities::MPI::this_mpi_process (mpi_communicator))\n\t{\n\t  cell_matrix = 0;\n\t  cell_vector = 0;\n\t  fe_values.reinit (cell);\n\n\t  // Extract vector-values from FEValues.\n\t  const dealii::FEValuesExtractors::Vector u (0);\n\n\t  // Obtain the material identification on this cell and\n\t  // transfer it to a strain description.\n\t  material_function.value_list (fe_values.get_quadrature_points (),\n\t\t\t\t\tmaterial_function_values);\n  \n\t  for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n\t    {\n\t          \n\t      elastic_coefficients.clear ();\n\n\t      for (unsigned int i=0; i<elastic_coefficients_inclusion.size (); ++i)\n\t\telastic_coefficients.push_back (material_function_values[q_point]*elastic_coefficients_inclusion[i] +\n\t\t\t\t\t\t(1.-material_function_values[q_point])*elastic_coefficients_background[i]);\n\n\t      elastic_tensor.set_coefficients (elastic_coefficients);\n\t      elastic_tensor.distribute_coefficients ();\n\t      \n\t      Assert (elastic_tensor.is_symmetric (), dealii::ExcMessage (\"Tensor not symmetric\"));\n\n\t      lattice_coefficients.clear ();\n\t      \n\t      for (unsigned int i=0; i<lattice_coefficients_inclusion.size (); ++i)\n\t\tlattice_coefficients.push_back (material_function_values[q_point] *\n\t\t\t\t\t\t(lattice_coefficients_inclusion[i]/lattice_coefficients_background[i]) - 1.);\n\t      lattice_tensor.set_coefficients (lattice_coefficients);\n\t      lattice_tensor.distribute_coefficients ();\n\t      \n\t      for (unsigned int i=0; i<dofs_per_cell; ++i)\n\t\t{\n\t\t  const dealii::Tensor<2, dim> u_i_grad = fe_values[u].symmetric_gradient (i, q_point);\n\t\t  \n\t\t  for (unsigned int j=0; j<dofs_per_cell; ++j)\n\t\t    {\n\t\t      const dealii::Tensor<2, dim> u_j_grad = fe_values[u].symmetric_gradient (j, q_point);\n\t\t      \n\t\t      // Local stiffness matrix.\n\t\t      cell_matrix (i,j) +=\n\t\t\tcontract (u_i_grad, elastic_tensor, u_j_grad) *\n\t\t\tfe_values.JxW (q_point);\n\t\t      \n\t\t    } \n\t\t  \n\t\t  // Local right hand side vector.\n\t\t  cell_vector (i) +=\n\t\t    contract (u_i_grad, elastic_tensor, lattice_tensor) *\n\t\t    fe_values.JxW (q_point);\n\t\t  \n\t\t}\n\n\t    } // q_point\n\t  \n\t  cell->get_dof_indices (local_dof_indices);\n\t  \n\t  constraints.distribute_local_to_global (cell_matrix, cell_vector,\n\t\t\t\t\t\t  local_dof_indices,\n\t\t\t\t\t\t  system_matrix, system_rhs);\n\t} // cell!=endc\n\n    system_matrix.compress (dealii::VectorOperation::add);\n    system_rhs.compress (dealii::VectorOperation::add);\n  }\n  \n\n  /**\n   * Solve the linear algebra system.\n   */\n  template <int dim>\n  unsigned int\n  ElasticProblem<dim>::solve ()\n  {\n    dealii::TimerOutput::Scope time (timer, \"solve\");\n    \n    dealii::PETScWrappers::MPI::Vector completely_distributed_solution (locally_owned_dofs, mpi_communicator);\n    dealii::SolverControl solver_control (dof_handler.n_dofs (), 1e-06);\n    dealii::PETScWrappers::SolverBicgstab solver (solver_control, mpi_communicator);\n    dealii::PETScWrappers::PreconditionBlockJacobi preconditioner (system_matrix);\n    \n    solver.solve (system_matrix, completely_distributed_solution, system_rhs,\n\t\t  preconditioner);\n    \n    // Ensure that all ghost elements are also copied as necessary.\n    constraints.distribute (completely_distributed_solution);\n    locally_relevant_solution = completely_distributed_solution;\n\n    // Return the number of iterations (last step) of the solve.\n    return solver_control.last_step ();\n  }\n\n\n  /**\n   * Output results.\n   */\n  template <int dim>\n  void\n  ElasticProblem<dim>::output_results (const unsigned int cycle)\n  {\n    dealii::TimerOutput::Scope time (timer, \"output_results\");\n\n    dealii::DataOut<dim> data_out;\n    data_out.attach_dof_handler (dof_handler);\n    data_out.add_data_vector (locally_relevant_solution, \"displacement\");\n\n    dealii::Vector<float> subdomain (triangulation.n_active_cells ());\n    for (unsigned int i=0; i<subdomain.size(); ++i)\n      subdomain (i) = triangulation.locally_owned_subdomain ();\n    data_out.add_data_vector (subdomain, \"subdomain\");\n\n    data_out.build_patches ();\n    \n    const std::string filename = (\"displacement-\" +\n                                  dealii::Utilities::int_to_string (cycle, 2) +\n                                  \".\" +\n                                  dealii::Utilities::int_to_string\n                                  (triangulation.locally_owned_subdomain (), 4));\n\n    std::ofstream output ((filename + \".vtu\").c_str ());\n    data_out.write_vtu (output);\n\n    if (dealii::Utilities::MPI::this_mpi_process(mpi_communicator) == 1)\n      {\n\tstd::vector<std::string> filenames;\n\t\n\tfor (unsigned int i=0;\n\t     i<dealii::Utilities::MPI::n_mpi_processes (mpi_communicator);\n\t     ++i)\n\t  filenames.push_back (\"displacement-\" +\n\t\t\t       dealii::Utilities::int_to_string (cycle, 2) +\n\t\t\t       \".\" +\n\t\t\t       dealii::Utilities::int_to_string (i, 4) +\n\t\t\t       \".vtu\");\n\tstd::ofstream master_output ((\"displacement-\" +\n\t\t\t\t      dealii::Utilities::int_to_string (cycle, 2) +\n\t\t\t\t      \".pvtu\").c_str ());\n\n\tdata_out.write_pvtu_record (master_output, filenames);\n      }\n  }\n  \n\n  /**\n   * Run the application in the order specified.\n   */\n  template <int dim>\n  void\n  ElasticProblem<dim>::run ()\n  {\n    // To solve the Elastic problem, first we need to solve the\n    // problem of a mterial identification. This is done by solving a\n    // function against the mass matrix.\n\n\n    // Create a coarse grid according to the parameters given in the\n    // input file.\n    dealii::GridGenerator::hyper_cube (triangulation, -2.5, 2.5);\n    triangulation.refine_global (3);\n    \n    pcout << \"   Number of active cells:       \"\n\t  << triangulation.n_global_active_cells ()\n\t  << std::endl;\n    \n    setup_system ();\n    \n    pcout << \"   Number of degrees of freedom: \"\n\t  << dof_handler.n_dofs ()\n\t  << std::endl;\n    \n    assemble_system ();\n\n    const unsigned int n_iterations = solve ();\n    \n    pcout << \"   Solved in \" << n_iterations\n\t  << \" iterations.\"\n\t  << std::endl;\n    \n    pcout << \"   Linfty-norm:                  \"\n\t  << locally_relevant_solution.linfty_norm ()\n\t  << std::endl;\n\n    output_results (0);\n  }\n  \n} // namespace mandy\n\n\n/**\n * Main function: Initialise problem and run it.\n */\nint main (int argc, char *argv[])\n{\n  // Initialise MPI\n  dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);\n  \n  try\n    {\n      // mandy::MaterialID<3> material_id (\"step-4.prm\");\n      // material_id.run ();\n      \n      mandy::ElasticProblem<3> elastic_problem (\"elastic.prm\");\n      elastic_problem.run ();\n    }\n\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "7a67b44af0538a1d5f6be164d232f88b5a4a8168", "size": 18551, "ext": "cc", "lang": "C++", "max_stars_repo_path": "archive/step-1-elastic.cc", "max_stars_repo_name": "oneliefleft/mandy", "max_stars_repo_head_hexsha": "e791f7defbf3f13a63769ad7231ddd32dcfd1a32", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "archive/step-1-elastic.cc", "max_issues_repo_name": "oneliefleft/mandy", "max_issues_repo_head_hexsha": "e791f7defbf3f13a63769ad7231ddd32dcfd1a32", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-02-24T13:55:50.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-24T14:00:20.000Z", "max_forks_repo_path": "archive/step-1-elastic.cc", "max_forks_repo_name": "oneliefleft/mandy", "max_forks_repo_head_hexsha": "e791f7defbf3f13a63769ad7231ddd32dcfd1a32", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7768860353, "max_line_length": 110, "alphanum_fraction": 0.6482669398, "num_tokens": 4497, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.4001761003820186}}
{"text": "#include \"libsnark/gadgetlib1/gadgets/basic_gadgets.hpp\"\n#include \"libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp\"\n#include \"libsnark/common/default_types/r1cs_ppzksnark_pp.hpp\"\n#include \"libsnark/common/utils.hpp\"\n#include <boost/optional.hpp>\n\nusing namespace libsnark;\nusing namespace std;\n\n#include \"gadget.hpp\"\n#include \"gadget_neg.hpp\"\n\n\ntemplate<typename ppzksnark_ppT>\nr1cs_ppzksnark_keypair<ppzksnark_ppT> generate_keypair(const int jw[32])\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n\n    //根据预先定义的计算门和约束生成公共参数秘钥对\n    //证明生成端若需要采用对应的公共秘钥生成证明数据成功，则必须使两端的数据符合预先定于的计算约束(R1=R2+R3+X)\n    //如此，当验证端根据对应的验证秘钥验证证明数据为真时，验证者就能够相信对应的交易中是符合预定义的计算约束的，而不是生成假证明以通过检查\n    protoboard<FieldT> pb;\n    l_gadget<FieldT> g(pb);\n    g.generate_r1cs_constraints();\n    const r1cs_constraint_system<FieldT> constraint_system = pb.get_constraint_system();\n\n    cout << \"Number of R1CS constraints: \" << constraint_system.num_constraints() << endl;\n\n    return r1cs_ppzksnark_generator<ppzksnark_ppT>(constraint_system);\n}\n\ntemplate<typename ppzksnark_ppT>\nr1cs_ppzksnark_keypair<ppzksnark_ppT> generate_keypair_neg(const int jw[2][32])\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n\n    //根据预先定义的计算门和约束生成公共参数秘钥对\n    //证明生成端若需要采用对应的公共秘钥生成证明数据成功，则必须使两端的数据符合预先定于的计算约束(R1+X=R2+R3)\n    //如此，当验证端根据对应的验证秘钥验证证明数据为真时，验证者就能够相信对应的交易中是符合预定义的计算约束的，而不是生成假证明以通过检查\n    protoboard<FieldT> pb;\n    l_gadget_neg<FieldT> g(pb);\n    g.generate_r1cs_constraints();\n    const r1cs_constraint_system<FieldT> constraint_system = pb.get_constraint_system();\n\n    cout << \"Number of R1CS constraints: \" << constraint_system.num_constraints() << endl;\n\n    return r1cs_ppzksnark_generator<ppzksnark_ppT>(constraint_system);\n}\n\ntemplate<typename ppzksnark_ppT>\nboost::optional<r1cs_ppzksnark_proof<ppzksnark_ppT>> generate_proof(r1cs_ppzksnark_proving_key<ppzksnark_ppT> proving_key,\n                                                                   const bit_vector &h1,\n                                                                   const bit_vector &h2,\n                                                                   const bit_vector &h3,\n                                                                   const bit_vector &r1,\n                                                                   const bit_vector &r2,\n                                                                   const bit_vector &r3,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   const bit_vector &x,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   const int jw[32]\n                                                                   )\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n\n    protoboard<FieldT> pb;\n    l_gadget<FieldT> g(pb);\n    g.generate_r1cs_constraints();\n    g.generate_r1cs_witness(h1, h2, h3, r1, r2, r3,x);\n\n    if (!pb.is_satisfied()) {\n      std::cout << \"System not satisfied!\" << std::endl;\n        return boost::none;\n    }\n\n    return r1cs_ppzksnark_prover<ppzksnark_ppT>(proving_key, pb.primary_input(), pb.auxiliary_input());\n}\n\ntemplate<typename ppzksnark_ppT>\nboost::optional<r1cs_ppzksnark_proof<ppzksnark_ppT>> generate_proof_neg(r1cs_ppzksnark_proving_key<ppzksnark_ppT> proving_key,\n                                                                   const bit_vector &h1,\n                                                                   const bit_vector &h2,\n                                                                   const bit_vector &h3,\n                                                                   const bit_vector &r1,\n                                                                   const bit_vector &r2,\n                                                                   const bit_vector &r3,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   const bit_vector &x,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t   const int jw[2][32]\n                                                                   )\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n\n    protoboard<FieldT> pb;\n    l_gadget_neg<FieldT> g(pb);\n    g.generate_r1cs_constraints();\n    g.generate_r1cs_witness(h1, h2, h3, r1, r2, r3,x);\n\n    if (!pb.is_satisfied()) {\n      std::cout << \"System not satisfied!\" << std::endl;\n        return boost::none;\n    }\n\n    return r1cs_ppzksnark_prover<ppzksnark_ppT>(proving_key, pb.primary_input(), pb.auxiliary_input());\n}\n\ntemplate<typename ppzksnark_ppT>\nbool verify_proof(r1cs_ppzksnark_verification_key<ppzksnark_ppT> verification_key,\n                  r1cs_ppzksnark_proof<ppzksnark_ppT> proof,\n                  const bit_vector &h1,\n                  const bit_vector &h2,\n                  const bit_vector &h3,\n\t\t\t\t  const bit_vector &x\n                 )\n{\n    typedef Fr<ppzksnark_ppT> FieldT;\n\n    const r1cs_primary_input<FieldT> input = l_input_map<FieldT>(h1, h2, h3,x);\n\n    std::cout << \"**** After l_input_map *****\" << std::endl;\n\n    return r1cs_ppzksnark_verifier_strong_IC<ppzksnark_ppT>(verification_key, input, proof);\n\n}\n\n\n", "meta": {"hexsha": "b9626d7fef80c28df6dd3377b92f69ffb8df5cde", "size": 4836, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/zkTrias/snark.hpp", "max_stars_repo_name": "dasenlinCode/lightning_circuit", "max_stars_repo_head_hexsha": "e6eb12623e13bfe62489726c732bf563c17c5169", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-19T02:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-01T05:11:27.000Z", "max_issues_repo_path": "src/zkTrias/snark.hpp", "max_issues_repo_name": "dasenlinCode/lightning_circuit", "max_issues_repo_head_hexsha": "e6eb12623e13bfe62489726c732bf563c17c5169", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/zkTrias/snark.hpp", "max_forks_repo_name": "dasenlinCode/lightning_circuit", "max_forks_repo_head_hexsha": "e6eb12623e13bfe62489726c732bf563c17c5169", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-06-28T12:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-15T08:48:53.000Z", "avg_line_length": 39.0, "max_line_length": 126, "alphanum_fraction": 0.5847808106, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311956428947, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.4001208093831609}}
{"text": "#include <cassert>\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <stdexcept>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include <boost/geometry.hpp>\n#include <csv.h>\n\n#include \"DataStructures/Geometry/SummedAreaTables/OctagonalSummedAreaTable.h\"\n#include \"DataStructures/Geometry/Area.h\"\n#include \"DataStructures/Geometry/CoordinateTransformation.h\"\n#include \"DataStructures/Geometry/Point.h\"\n#include \"DataStructures/Graph/Attributes/LatLngAttribute.h\"\n#include \"DataStructures/Graph/Attributes/SequentialVertexIdAttribute.h\"\n#include \"DataStructures/Graph/Graph.h\"\n#include \"DataStructures/Utilities/Matrix.h\"\n#include \"DataStructures/Utilities/OriginDestination.h\"\n#include \"Tools/CommandLine/CommandLineParser.h\"\n#include \"Tools/CommandLine/ProgressBar.h\"\n#include \"Tools/Constants.h\"\n#include \"Tools/Math.h\"\n#include \"Tools/Timer.h\"\n\nnamespace bg = boost::geometry;\nnamespace bgi = boost::geometry::index;\n\nvoid printUsage() {\n  std::cout <<\n      \"Usage: RadiationModel [-s <factor>] -g <file> -r <file> -grid <file> -o <file>\\n\"\n      \"Generates travel demand data for the specified road network according to the\\n\"\n      \"radiation model, using the German Census 2011 population grid.\\n\"\n      \"  -s <factor>       scale the population by <factor> (defaults to 1.0)\\n\"\n      \"  -d <meters>       the max. distance between a cell's center and mapped segment\\n\"\n      \"  -seed <seed>      start the random number generator with <seed>\\n\"\n      \"  -g <file>         the network under study in binary format\\n\"\n      \"  -r <file>         restrict origins/destinations to area from OSM POLY file\\n\"\n      \"  -grid <file>      the German Census 2011 population grid\\n\"\n      \"  -o <file>         place output in <file>\\n\"\n      \"  -help             display this help and exit\\n\";\n}\n\nint main(int argc, char* argv[]) {\n  try {\n    CommandLineParser clp(argc, argv);\n    if (clp.isSet(\"help\")) {\n      printUsage();\n      return EXIT_SUCCESS;\n    }\n\n    const auto areaFilename = clp.getValue<std::string>(\"r\");\n    const auto gridFilename = clp.getValue<std::string>(\"grid\");\n    const auto graphFilename = clp.getValue<std::string>(\"g\");\n    const auto outputFilename = clp.getValue<std::string>(\"o\");\n    const double scale = clp.getValue<double>(\"s\", 1.0);\n    const int maxDist = clp.getValue<int>(\"d\", 5000);\n\n    // Read the graph from file.\n    std::ifstream graphFile(graphFilename, std::ios::binary);\n    if (!graphFile.good())\n      throw std::invalid_argument(\"file not found -- '\" + graphFilename + \"'\");\n    StaticGraph<VertexAttrs<LatLngAttribute, SequentialVertexIdAttribute>> graph(graphFile);\n    graphFile.close();\n\n    if (graph.numVertices() > 0 && graph.sequentialVertexId(0) == INVALID_VERTEX)\n      FORALL_VERTICES(graph, v)\n        graph.sequentialVertexId(v) = v;\n\n    // Read the population grid from file.\n    std::vector<std::pair<::Point, int>> gridCells;\n    ::Point minCell(INFTY, INFTY);\n    ::Point maxCell(-INFTY, -INFTY);\n    ::Point cell;\n    int numInhabitants;\n    io::CSVReader<3, io::trim_chars<>, io::no_quote_escape<';'>> gridFile(gridFilename);\n    gridFile.read_header(io::ignore_extra_column, \"x_mp_100m\", \"y_mp_100m\", \"Einwohner\");\n    while (gridFile.read_row(cell.x(), cell.y(), numInhabitants))\n      if (numInhabitants > 0) {\n        gridCells.emplace_back(cell, numInhabitants);\n        minCell.min(cell);\n        maxCell.max(cell);\n      }\n\n    // Allocate and fill the population matrix.\n    const auto gridBounds = maxCell - minCell;\n    const int numRows = gridBounds.y() / 100 + 1;\n    const int numCols = gridBounds.x() / 100 + 1;\n    Matrix<int> populationGrid(numRows, numCols, 0);\n    for (const auto& cell : gridCells) {\n      const auto pos = cell.first - minCell;\n      populationGrid(numRows - pos.y() / 100 - 1, pos.x() / 100) = cell.second;\n    }\n\n    // Build an R-tree storing the road segments.\n    using Point = bg::model::point<double, 2, bg::cs::spherical_equatorial<bg::degree>>;\n    using Segment = bg::model::segment<Point>;\n    using RoadSegment = std::tuple<Segment, int, int>;\n    std::vector<RoadSegment> roadSegments;\n    FORALL_VALID_EDGES(graph, u, e) {\n      const int v = graph.edgeHead(e);\n      const Point tail(graph.latLng(u).lngInDeg(), graph.latLng(u).latInDeg());\n      const Point head(graph.latLng(v).lngInDeg(), graph.latLng(v).latInDeg());\n      roadSegments.emplace_back(Segment(tail, head), u, v);\n    }\n    bgi::rtree<RoadSegment, bgi::quadratic<16>> rTree(roadSegments);\n\n    // Map each cell C inside the area under study to the road segment nearest to the center of C.\n    const auto sourceCrs = CoordinateTransformation::WGS_84;\n    const auto targetCrs = CoordinateTransformation::ETRS89_LAEA_EUROPE;\n    CoordinateTransformation trans(sourceCrs, targetCrs);\n    Area area;\n    area.importFromOsmPolyFile(areaFilename);\n    const auto box = area.boundingBox();\n    LatLng nw(box.northEast().y(), box.southWest().x());\n    LatLng se(box.southWest().y(), box.northEast().x());\n    double easting, northing;\n    trans.forward(nw.lngInDeg(), nw.latInDeg(), easting, northing);\n    const auto min = ::Point(std::round(easting), std::round(northing)) - minCell;\n    trans.forward(se.lngInDeg(), se.latInDeg(), easting, northing);\n    const auto max = ::Point(std::round(easting), std::round(northing)) - minCell;\n    const ::Point minCoveredCell((min.x() + 50) / 100, numRows - (min.y() + 50) / 100 - 1);\n    const ::Point maxCoveredCell((max.x() + 50) / 100, numRows - (max.y() + 50) / 100 - 1);\n    Matrix<int> representative(numRows, numCols, INVALID_VERTEX);\n    int population = 0;\n    int numUnmappedCells = 0;\n    for (int x = minCoveredCell.x(); x <= maxCoveredCell.x(); ++x)\n      for (int y = minCoveredCell.y(); y <= maxCoveredCell.y(); ++y) {\n        const auto c = ::Point(x * 100, (numRows - y - 1) * 100) + minCell;\n        double lng, lat;\n        trans.reverse(c.x(), c.y(), lng, lat);\n        const LatLng center(lat, lng);\n        if (area.contains({center.longitude(), center.latitude()})) {\n          population += populationGrid(y, x);\n          const Point queryPoint(center.lngInDeg(), center.latInDeg());\n          RoadSegment nearestRoadSegment;\n          rTree.query(bgi::nearest(queryPoint, 1), &nearestRoadSegment);\n          Segment segment;\n          int u, v;\n          std::tie(segment, u, v) = nearestRoadSegment;\n          if (bg::distance(queryPoint, segment) * EARTH_RADIUS <= maxDist) {\n            const auto distToU = bg::comparable_distance(queryPoint, segment.first);\n            const auto distToV = bg::comparable_distance(queryPoint, segment.second);\n            representative(y, x) = distToU < distToV && graph.containsEdge(v, u) ? u : v;\n          } else {\n            ++numUnmappedCells;\n          }\n        }\n      }\n\n    // Open the output file.\n    std::ofstream out(outputFilename + \".csv\");\n    if (!out.good())\n      throw std::invalid_argument(\"file cannot be opened -- '\" + outputFilename + \".csv'\");\n    out << \"# Input graph: \" << graphFilename << '\\n';\n    out << \"# Methodology: radiation model (\" << scale << \")\\n\";\n    out << \"origin,destination\\n\";\n\n    // Generate trips between the grid cells.\n    Timer timer;\n    std::cout << \"Generating trips: \";\n    const auto coveredGridBounds = maxCoveredCell - minCoveredCell;\n    ProgressBar bar((coveredGridBounds.x() + 1) * (coveredGridBounds.y() + 1));\n    OctagonalSummedAreaTable sat(populationGrid);\n    std::vector<OriginDestination> result;\n    std::default_random_engine rand(clp.getValue<int>(\"seed\", 19900325));\n    for (int srcX = minCoveredCell.x(); srcX <= maxCoveredCell.x(); ++srcX)\n      for (int srcY = minCoveredCell.y(); srcY <= maxCoveredCell.y(); ++srcY) {\n        if (representative(srcY, srcX) != INVALID_VERTEX && populationGrid(srcY, srcX) > 0)\n          for (int dstX = minCoveredCell.x(); dstX <= maxCoveredCell.x(); ++dstX)\n            for (int dstY = minCoveredCell.y(); dstY <= maxCoveredCell.y(); ++dstY)\n              if (representative(dstY, dstX) != INVALID_VERTEX && populationGrid(dstY, dstX) > 0) {\n                if (srcX == dstX && srcY == dstY)\n                  continue;\n                const ::Point src(srcX, srcY);\n                const ::Point dst(dstX, dstY);\n                const double radius = src.getEuclideanDistanceTo(dst);\n                int64_t srcPop = populationGrid(srcY, srcX);\n                int64_t dstPop = populationGrid(dstY, dstX);\n                int64_t surroundingPop = sat.sumOverOctagon(src, radius);\n\n                // Does the surrounding population include the destination population?\n                const int height = std::round(0.92387953251128675613 * radius); // r * cos(pi / 8)\n                const int side = std::round(0.38268343236508977173 * radius);   // r * sin(pi / 8)\n                if (src.getManhattanDistanceTo(dst) <= height + side &&\n                    src.getChebyshevDistanceTo(dst) <= height)\n                  surroundingPop -= dstPop;\n                assert(surroundingPop > 0);\n\n                // Pick the number of trips between the source and destination cell.\n                double p = 1.0 * srcPop * dstPop / (surroundingPop * (dstPop + surroundingPop));\n                assert(p > 0); assert(p <= 1);\n                int numTrips = std::binomial_distribution<>(std::round(scale * srcPop), p)(rand);\n\n                // Generate the chosen number of trips.\n                for (int i = 0; i < numTrips; ++i)\n                  result.emplace_back(representative(srcY, srcX), representative(dstY, dstX));\n              }\n        ++bar;\n      }\n    const int elapsed = timer.elapsed();\n    std::cout << \"done (\" << elapsed << \"ms).\" << std::endl;\n\n    std::cout << \"Writing OD-pairs to file...\" << std::flush;\n    for (const auto& record : result) {\n      out << graph.sequentialVertexId(record.origin) << ',';\n      out << graph.sequentialVertexId(record.destination) << '\\n';\n    }\n    std::cout << \" done.\" << std::endl;\n  } catch (std::exception& e) {\n    std::cerr << argv[0] << \": \" << e.what() << std::endl;\n    std::cerr << \"Try '\" << argv[0] <<\" -help' for more information.\" << std::endl;\n    return EXIT_FAILURE;\n  }\n  return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "709fb190803354691f0e9e42c8988aa43ba866b9", "size": 10256, "ext": "cc", "lang": "C++", "max_stars_repo_path": "RawData/RadiationModel.cc", "max_stars_repo_name": "LBNL-UCB-STI/routing-framework", "max_stars_repo_head_hexsha": "8dc1f5c008384051132bf5819056584700623417", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2017-11-11T15:19:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T04:41:54.000Z", "max_issues_repo_path": "RawData/RadiationModel.cc", "max_issues_repo_name": "kirilsol/routing-framework", "max_issues_repo_head_hexsha": "80026caeddf84ef939742f33fcc69e865c51dbeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-17T07:21:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-17T07:21:56.000Z", "max_forks_repo_path": "RawData/RadiationModel.cc", "max_forks_repo_name": "kirilsol/routing-framework", "max_forks_repo_head_hexsha": "80026caeddf84ef939742f33fcc69e865c51dbeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-10-17T01:34:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-10T06:19:30.000Z", "avg_line_length": 46.1981981982, "max_line_length": 99, "alphanum_fraction": 0.630850234, "num_tokens": 2699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7879311856832191, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.4001208043255195}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_TRIGONOMETRIC_CONSTANTS_20_PI_HPP_INCLUDED\n#define NT2_TRIGONOMETRIC_CONSTANTS_20_PI_HPP_INCLUDED\n\n#include <nt2/include/functor.hpp>\n#include <boost/simd/constant/hierarchy.hpp>\n#include <boost/simd/constant/register.hpp>\nnamespace nt2\n{\n  namespace tag\n  {\n   /*!\n     @brief _20_pi generic tag\n\n     Represents the _20_pi constant in generic contexts.\n\n     @par Models:\n        Hierarchy\n   **/\n    BOOST_SIMD_CONSTANT_REGISTER( _20_pi, double\n                                , 63, 0x427b53d1       //20\\pi\n                                , 0x404f6a7a2955385ell  //20\\pi\n                                )\n  }\n  namespace ext\n  {\n   template<class Site, class... Ts>\n   BOOST_FORCEINLINE generic_dispatcher<tag::_20_pi, Site> dispatching__20_pi(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)\n   {\n     return generic_dispatcher<tag::_20_pi, Site>();\n   }\n   template<class... Args>\n   struct impl__20_pi;\n  }\n  /*!\n    Constant \\f$20\\pi\\f$.\n\n    @par Semantic:\n\n    For type T0:\n\n    @code\n    T0 r = _20_pi<T0>();\n    @endcode\n\n    is similar to:\n\n    @code\n    T0 r = Twenty<T0>()*Pi<T0>();\n    @endcode\n\n    @return a value of type T0\n  **/\n  BOOST_SIMD_CONSTANT_IMPLEMENTATION(tag::_20_pi, _20_pi);\n}\n\n#endif\n\n", "meta": {"hexsha": "3c56f4aec05d518a9017f243c56a6b38d10019a1", "size": 1781, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/_20_pi.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/_20_pi.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/trigonometric/include/nt2/trigonometric/constants/_20_pi.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9848484848, "max_line_length": 168, "alphanum_fraction": 0.5626052779, "num_tokens": 454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.6076631698328916, "lm_q1q2_score": 0.40009607361067917}}
{"text": "#pragma once\n\n#include <fftw3.h>\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <boost/assert.hpp>\n#include <complex>\n#include <type_traits>\n\n#include \"base/array_buffer.hpp\"\n#include \"planner.hpp\"\n#include \"shift.hpp\"\n\n\nnamespace local_ {\ntemplate <typename D1, typename D2>\nstruct enable_if_cc\n    : public std::enable_if<std::is_same<typename D1::Scalar, std::complex<double>>::value &&\n                            std::is_same<typename D2::Scalar, std::complex<double>>::value>\n{\n};\n\ntemplate <typename D1, typename D2>\nstruct enable_if_cr\n    : public std::enable_if<std::is_same<typename D1::Scalar, std::complex<double>>::value &&\n                            std::is_same<typename D2::Scalar, double>::value>\n{\n};\n\ntemplate <typename D1, typename D2>\nstruct enable_if_rc\n    : public std::enable_if<std::is_same<typename D1::Scalar, double>::value &&\n                            std::is_same<typename D2::Scalar, std::complex<double>>::value>\n{\n};\n}  // local_\n\ntemplate <typename PLAN_HANDLER>\nclass FFTr2c\n{\n public:\n  typedef Eigen::Array<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> array_t;\n  typedef Eigen::Array<std::complex<double>, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n      complex_array_t;\n\n  typedef std::complex<double> cdouble;\n\n public:\n  //@{\n  /// real valued transforms\n\n  /**\n   * @brief forward transform (real-valued)\n   *\n   * @param[out] dst\n   * @param[in]  src\n   * @param[in]  scale if true: scales output by 1/numel(src)\n   *\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename local_::enable_if_cr<DERIVED1, DERIVED2>::type fft2(\n      Eigen::DenseBase<DERIVED1> &dst,\n      const Eigen::DenseBase<DERIVED2> &src,\n      bool scale = true) const;\n\n  /**\n   * @brief inverse transform (does not preserve input, real-valued)\n   *\n   * @param[out] dst\n   * @param[in]  src   full spectrum\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename local_::enable_if_rc<DERIVED1, DERIVED2>::type ifft2(\n      Eigen::DenseBase<DERIVED1> &dst, Eigen::DenseBase<DERIVED2> &src) const;\n\n  /**\n   * @brief 2-dim fft (including fftshift, real-valued)\n   *\n   * @param[out] dst  complex array (centered zero-frequency convention)\n   * @param[in] src   real array\n   * @param[in] scale if true: scales output by 1/numel(src)\n   *\n   * This is the inverse of ift for \\var scale set to false!\n   *\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename local_::enable_if_cr<DERIVED1, DERIVED2>::type ft(Eigen::DenseBase<DERIVED1> &dst,\n                                                             const Eigen::DenseBase<DERIVED2> &src,\n                                                             bool scale = true) const;\n\n  /**\n   * @brief ifft2 (including ifftshift, real-valued)\n   *\n   * @param[out] dst   real array\n   * @param[in]  src   complex array\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename local_::enable_if_rc<DERIVED1, DERIVED2>::type ift(\n      Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src) const;\n  //@}\n\n  //@{\n  /// complex transforms\n  /**\n   * complex, complex\n   * @brief fft2 (including fftshift)\n   *\n   * @param[out] dst (in centered zero-frequency convention)\n   * @param[int] src\n   * @param bool  if true: scales output by 1/numel(src)\n   *\n   * This is the inverse of ift for \\var scale set to false.\n   *\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename local_::enable_if_cc<DERIVED1, DERIVED2>::type ft(Eigen::DenseBase<DERIVED1> &dst,\n                                                             const Eigen::DenseBase<DERIVED2> &src,\n                                                             bool scale = true) const;\n\n  /**\n   * complex, complex\n   * @brief complex ifft2 (including ifftshift)\n   *\n   * @param[out] dst\n   * @param[in] src\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename local_::enable_if_cc<DERIVED1, DERIVED2>::type ift(\n      Eigen::DenseBase<DERIVED1> &dst, const Eigen::DenseBase<DERIVED2> &src) const;\n\n  /**\n   *\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename local_::enable_if_cc<DERIVED1, DERIVED2>::type fft2(\n      Eigen::DenseBase<DERIVED1> &dst,\n      const Eigen::DenseBase<DERIVED2> &src,\n      bool scale = true) const;\n\n  /**\n   * @brief ifft2 (c -> c)\n   *\n   * @param[out] dst  destination\n   * @param[in] src  will be overwritten by FFTW!\n   */\n  template <typename DERIVED1, typename DERIVED2>\n  typename local_::enable_if_cc<DERIVED1, DERIVED2>::type ifft2(\n      Eigen::DenseBase<DERIVED1> &dst, Eigen::DenseBase<DERIVED2> &src) const;\n  //@}\n\n  PLAN_HANDLER &get_plan() { return plan_h_; }\n\n private:\n  static PLAN_HANDLER plan_h_;\n  thread_local static ArrayBuffer<> buf_;\n};\n\ntemplate <typename PLAN_HANDLER>\nthread_local ArrayBuffer<> FFTr2c<PLAN_HANDLER>::buf_;\n\ntemplate <typename PLAN_HANDLER>\nPLAN_HANDLER FFTr2c<PLAN_HANDLER>::plan_h_;\n\n// --------------------------------------------------------------------------------\n// --------------------------------------------------------------------------------\n// -------------------------- REAL-COMPLEX TRANSFORMS\n// -----------------------------\n// --------------------------------------------------------------------------------\n// --------------------------------------------------------------------------------\ntemplate <typename PLAN_HANDLER>\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename local_::enable_if_cr<DERIVED1, DERIVED2>::type\nFFTr2c<PLAN_HANDLER>::fft2(Eigen::DenseBase<DERIVED1> &dst,\n                           const Eigen::DenseBase<DERIVED2> &src,\n                           bool scale) const\n{\n  static_assert(DERIVED1::IsRowMajor, \"requires row-major storage\");\n  static_assert(DERIVED2::IsRowMajor, \"requires row-major storage\");\n  static_assert(sizeof(fftw_complex) == sizeof(cdouble), \"type mismatch\");\n  // assert(dst.rows() == src.rows());\n  // assert(dst.cols() == src.cols());\n\n  dst.derived().resize(src.rows(), src.cols());\n\n  // typedef double fftw_cdouble[2];\n  typedef fftw_complex fftw_cdouble;\n  const int n0 = src.rows();\n  const int n1 = src.cols();\n  int n[2] = {n0, n1};\n\n  fftw_cdouble *out = reinterpret_cast<fftw_cdouble *>(dst.derived().data());\n  double *in = const_cast<double *>(src.derived().data());\n\n  fftw_plan fwd_plan = plan_h_.get_plan(n, PLAN_HANDLER::FWD, ft_type::R2C);\n  BOOST_ASSERT_MSG(fwd_plan != NULL, \"fftw plan not found!\");\n  fftw_execute_dft_r2c(fwd_plan, in, out);\n\n  // mirror coefficients\n  for (int i = 0; i < n0; ++i) {\n    int idest = (n0 - i) % n0;\n    for (int j = 1; j < n1 / 2 + n1 % 2; ++j) {\n      dst(idest, n1 - j) = std::conj(dst(i, j));\n    }\n  }\n  if (scale) {\n    double f = 1. / (n0 * n1);\n    dst *= f;\n  }\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename PLAN_HANDLER>\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename local_::enable_if_rc<DERIVED1, DERIVED2>::type\nFFTr2c<PLAN_HANDLER>::ifft2(Eigen::DenseBase<DERIVED1> &dst, Eigen::DenseBase<DERIVED2> &src) const\n{\n  static_assert(std::is_same<typename DERIVED2::Scalar, std::complex<double>>::value,\n                \"type mismatch\");\n  static_assert(std::is_same<typename DERIVED1::Scalar, double>::value, \"type mismatch\");\n  static_assert(sizeof(fftw_complex) == sizeof(cdouble), \"type mismatch\");\n  static_assert(DERIVED1::IsRowMajor, \"requires row-major storage\");\n  static_assert(DERIVED2::IsRowMajor, \"requires row-major storage\");\n\n  dst.derived().resize(src.rows(), src.cols());\n  // typedef double fftw_cdouble[2];\n  typedef fftw_complex fftw_cdouble;\n  const int n0 = src.rows();\n  const int n1 = src.cols();\n  int n[2] = {n0, n1};\n\n  fftw_cdouble *in = reinterpret_cast<fftw_cdouble *>(src.derived().data());\n  double *out = dst.derived().data();\n\n  fftw_plan inv_plan = plan_h_.get_plan(n, PLAN_HANDLER::INV, ft_type::R2C);\n  BOOST_ASSERT_MSG(inv_plan != NULL, \"fftw plan not found!\");\n  // fftw_execute(inv_plan);\n  fftw_execute_dft_c2r(inv_plan, in, out);\n\n  double f = 1. / (n0 * n1);\n  dst *= f;\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename PLAN_HANDLER>\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename local_::enable_if_cr<DERIVED1, DERIVED2>::type\nFFTr2c<PLAN_HANDLER>::ft(Eigen::DenseBase<DERIVED1> &dst,\n                         const Eigen::DenseBase<DERIVED2> &src,\n                         bool scale) const\n{\n  static_assert(std::is_same<typename DERIVED1::Scalar, std::complex<double>>::value,\n                \"type mismatch\");\n  static_assert(std::is_same<typename DERIVED2::Scalar, double>::value, \"type mismatch\");\n\n  auto tmp = buf_.get<complex_array_t>(src.rows(), src.cols());\n  this->fft2(tmp, src, scale);\n  dst.resize(tmp.rows(), tmp.cols());\n  fftshift(dst, tmp);\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename PLAN_HANDLER>\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename local_::enable_if_rc<DERIVED1, DERIVED2>::type\nFFTr2c<PLAN_HANDLER>::ift(Eigen::DenseBase<DERIVED1> &dst,\n                          const Eigen::DenseBase<DERIVED2> &src) const\n{\n  static_assert(std::is_same<typename DERIVED1::Scalar, double>::value, \"type mismatch\");\n  static_assert(std::is_same<typename DERIVED2::Scalar, std::complex<double>>::value,\n                \"type mismatch\");\n\n  auto tmp = buf_.get<complex_array_t>(src.rows(), src.cols());\n  ifftshift(tmp, src);\n  this->ifft2(dst, tmp);\n}\n\n// --------------------------------------------------------------------------------\n// --------------------------------------------------------------------------------\n// ------------------------ COMPLEX-COMPLEX TRANSFORMS ----------------------------\n// --------------------------------------------------------------------------------\n// --------------------------------------------------------------------------------\ntemplate <typename PLAN_HANDLER>\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename local_::enable_if_cc<DERIVED1, DERIVED2>::type\nFFTr2c<PLAN_HANDLER>::fft2(Eigen::DenseBase<DERIVED1> &dst,\n                           const Eigen::DenseBase<DERIVED2> &src,\n                           bool scale) const\n{\n  static_assert(DERIVED1::IsRowMajor, \"requires row-major storage\");\n  static_assert(DERIVED2::IsRowMajor, \"requires row-major storage\");\n  static_assert(sizeof(fftw_complex) == sizeof(cdouble), \"type mismatch\");\n\n  dst.derived().resize(src.rows(), src.cols());\n\n  typedef fftw_complex fftw_cdouble;\n  const int n0 = src.rows();\n  const int n1 = src.cols();\n  int n[2] = {n0, n1};\n\n  fftw_cdouble *in =\n      const_cast<fftw_cdouble *>(reinterpret_cast<const fftw_cdouble *>(src.derived().data()));\n  fftw_cdouble *out = reinterpret_cast<fftw_cdouble *>(dst.derived().data());\n\n  fftw_plan fwd_plan = plan_h_.get_plan(n, PLAN_HANDLER::FWD, ft_type::C2C);\n  BOOST_ASSERT_MSG(fwd_plan != NULL, \"fftw plan not found!\");\n  fftw_execute_dft(fwd_plan, in, out);\n\n  if (scale) {\n    double f = 1. / (n0 * n1);\n    dst *= f;\n  }\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename PLAN_HANDLER>\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename local_::enable_if_cc<DERIVED1, DERIVED2>::type\nFFTr2c<PLAN_HANDLER>::ifft2(Eigen::DenseBase<DERIVED1> &dst, Eigen::DenseBase<DERIVED2> &src) const\n{\n  static_assert(sizeof(fftw_complex) == sizeof(cdouble), \"type mismatch\");\n  static_assert(DERIVED1::IsRowMajor, \"requires row-major storage\");\n  static_assert(DERIVED2::IsRowMajor, \"requires row-major storage\");\n\n  dst.derived().resize(src.rows(), src.cols());\n  // typedef double fftw_cdouble[2];\n  typedef fftw_complex fftw_cdouble;\n  const int n0 = src.rows();\n  const int n1 = src.cols();\n  int n[2] = {n0, n1};\n\n  fftw_cdouble *in =\n      const_cast<fftw_cdouble *>(reinterpret_cast<const fftw_cdouble *>(src.derived().data()));\n  fftw_cdouble *out = reinterpret_cast<fftw_cdouble *>(dst.derived().data());\n\n  fftw_plan inv_plan = plan_h_.get_plan(n, PLAN_HANDLER::INV, ft_type::C2C);\n  BOOST_ASSERT_MSG(inv_plan != NULL, \"fftw plan not found!\");\n  // fftw_execute(inv_plan);\n  fftw_execute_dft(inv_plan, in, out);\n\n  double f = 1. / (n0 * n1);\n  dst *= f;\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename PLAN_HANDLER>\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename local_::enable_if_cc<DERIVED1, DERIVED2>::type\nFFTr2c<PLAN_HANDLER>::ft(Eigen::DenseBase<DERIVED1> &dst,\n                         const Eigen::DenseBase<DERIVED2> &src,\n                         bool scale) const\n{\n  auto tmp = buf_.get<complex_array_t>(src.rows(), src.cols());\n  this->fft2(tmp, src, scale);\n  dst.resize(tmp.rows(), tmp.cols());\n  fftshift(dst, tmp);\n}\n\n// --------------------------------------------------------------------------------\ntemplate <typename PLAN_HANDLER>\ntemplate <typename DERIVED1, typename DERIVED2>\ntypename local_::enable_if_cc<DERIVED1, DERIVED2>::type\nFFTr2c<PLAN_HANDLER>::ift(Eigen::DenseBase<DERIVED1> &dst,\n                          const Eigen::DenseBase<DERIVED2> &src) const\n{\n  auto tmp = buf_.get<complex_array_t>(src.rows(), src.cols());\n  ifftshift(tmp, src);\n  this->ifft2(dst, tmp);\n}\n", "meta": {"hexsha": "5519aa7c1bce0b4505f32ee26b762508633992b8", "size": 13244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "fft/fft2_r2c.hpp", "max_stars_repo_name": "simonpp/2dRidgeletBTE", "max_stars_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T03:15:56.000Z", "max_issues_repo_path": "fft/fft2_r2c.hpp", "max_issues_repo_name": "simonpp/2dRidgeletBTE", "max_issues_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fft/fft2_r2c.hpp", "max_forks_repo_name": "simonpp/2dRidgeletBTE", "max_forks_repo_head_hexsha": "5d08cbb5c57fc276c7a528f128615d23c37ef6a0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-08T03:15:56.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-08T03:15:56.000Z", "avg_line_length": 35.891598916, "max_line_length": 99, "alphanum_fraction": 0.59974328, "num_tokens": 3461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.40009606546476206}}
